From 39a882f2c911b5b2ecac3cbd3a4cd36cb48f331e Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sun, 22 Mar 2026 01:19:55 +0800 Subject: [PATCH 001/550] =?UTF-8?q?docs:=20=E9=87=8D=E5=86=99README?= =?UTF-8?q?=EF=BC=8C=E5=AE=8C=E5=96=84=E9=A1=B9=E7=9B=AE=E8=AF=B4=E6=98=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 98 +++++-- app/service/main.js | 2 +- .../systemMethods/storage/receiving.js | 10 + app/service/systems/polo_api.js | 203 ++++++++++++++ app/service/systems/storage/receiving.js | 264 ++++++++++++------ config/config.default.js | 3 + config/poloapi.js | 29 ++ day.log | Bin 0 -> 9620 bytes 8 files changed, 513 insertions(+), 96 deletions(-) create mode 100644 app/service/systems/polo_api.js create mode 100644 config/poloapi.js create mode 100644 day.log diff --git a/README.md b/README.md index f28ea49..515189c 100644 --- a/README.md +++ b/README.md @@ -1,31 +1,95 @@ -# qimen +# 奇门WMS(qimen-wms) -奇门wms +基于 Egg.js 的仓储管理系统(WMS),支持多快递平台对接、订单管理、打印、权限、配置等功能,适合中小型电商、仓储企业二次开发。 -## QuickStart +--- - +## 目录结构 -see [egg docs][egg] for more detail. - -### Development - -```bash -npm i -npm run dev -open http://localhost:7001/ +``` +├── app/ # 业务主目录(controller, service, model, router等) +│ ├── controller/ # 控制器(API、模板、认证等) +│ ├── service/ # 业务服务(含快手/PolyAPI、打印、系统等) +│ ├── model/ # Sequelize模型 +│ ├── dict/ # 业务字典 +│ ├── view/ # 前端模板 +│ └── router.js # 路由定义 +├── config/ # 配置(含poloapi、redis、数据库等) +├── database/ # 数据库迁移与配置 +├── public/ # 静态资源 +├── logs/ # 日志 +├── run/ # 运行时/元数据 +├── test/ # 单元测试 +├── package.json # 依赖与脚本 +├── app.js # 应用入口 +└── README.md # 项目说明 ``` -### Deploy +## 主要依赖 +- egg.js 3.x +- egg-sequelize、egg-mysql、egg-redis +- egg-jwt、egg-cors、egg-view-ejs +- fast-xml-parser、cos-js-sdk-v5、qiniu-js、soap +## 快速开始 + +```bash +npm install +npm run dev +# 访问 http://localhost:6060/ +``` + +## 启动与部署 + +开发环境: +```bash +npm run dev +``` +生产环境: ```bash npm start npm stop ``` -### npm scripts +## 常用 npm 脚本 +- `npm run lint` 代码风格检查 +- `npm test` 单元测试 +- `npm run dev` 本地开发 +- `npm start` 启动生产服务 -- Use `npm run lint` to check code style. -- Use `npm test` to run unit test. +## 配置说明 +- 主要配置文件在 `config/` 目录下(如 poloapi.js、config.default.js、config.local.js) +- 数据库、Redis、快手/PolyAPI等均可在对应文件中调整 -[egg]: https://eggjs.org +## 主要功能模块 +- 多快递平台对接(快手/PolyAPI等,详见 config/poloapi.js) +- 订单管理、打印、仓库/门店管理 +- 权限与角色、员工管理 +- API接口(RESTful风格,详见 app/router.js) +- 日志、配置、业务字典 + +## 路由示例 +- `GET /` 首页/健康检查 +- `POST /qimen` 奇门接口 +- `POST /api/warehouse` 仓库API +- `POST /api/store` 门店API +- `POST /api/v1` 旧版API +- `POST /api/v2` 新版API +- `GET /template/xml/:id` 获取打印模板 +- `GET|POST /auth/printSetting/:code` 打印台设置 + +## 开发建议 +- 业务字典已全局挂载(见 app.js) +- 所有服务建议继承 Egg Service,便于单元测试 +- 配置、密钥等敏感信息请勿提交到仓库 + +## 常见问题 +- 启动端口默认 6060,可在 `package.json` 或 `config` 中调整 +- 数据库/Redis 连接失败请检查 config.local.js +- 打印、快递API对接请参考 `app/service/systems/polo_api.js` 和 `config/poloapi.js` + +--- + +如需二次开发或遇到问题,欢迎提 issue 或联系维护者。 + +[Egg.js 官方文档](https://eggjs.org) diff --git a/app/service/main.js b/app/service/main.js index 1dc4fab..e12c300 100644 --- a/app/service/main.js +++ b/app/service/main.js @@ -227,7 +227,7 @@ class MainService extends Service { const decoded = app.jwt.verify(token, app.config.jwt.secret); const now = Math.floor(Date.now() / 1000); const expiresIn = decoded.exp - now; - if (expiresIn < 1800 && expiresIn > 0) { + if (expiresIn < 14399 && expiresIn > 0) { // 移除过期时间(exp)和签发时间(iat),保留其他payload const { exp, iat, ...payload } = decoded; diff --git a/app/service/systemMethods/storage/receiving.js b/app/service/systemMethods/storage/receiving.js index 08ba957..b16fbe9 100644 --- a/app/service/systemMethods/storage/receiving.js +++ b/app/service/systemMethods/storage/receiving.js @@ -19,6 +19,16 @@ class configService extends MainService { const result = await service.systems.storage.receiving.getReceivingList(where, pagination); return this.success('ok', result); } + async getReceivingDetail(data) { + const { service } = this; + const result = await service.systems.storage.receiving.getReceivingDetail(data); + return this.success('ok', result); + } + async batchCancelReceiving(data){ + const { service } = this; + const result = await service.systems.storage.receiving.batchCancelReceiving(data); + return this.success('ok', result); + } async create(data) { const { service } = this; const result = await service.systems.storage.receiving.create(data); diff --git a/app/service/systems/polo_api.js b/app/service/systems/polo_api.js new file mode 100644 index 0000000..307f7b6 --- /dev/null +++ b/app/service/systems/polo_api.js @@ -0,0 +1,203 @@ +'use strict'; + +const Service = require('egg').Service; +const poloApiConfig = require('../../../config/poloapi'); + +const crypto = require('crypto'); +const querystring = require('querystring'); + +class PoloApiService extends Service { + constructor(ctx) { + super(ctx); + this.configPoloApi = poloApiConfig; + } + + // 批量组装订单JSON + getJsonDatas(expressConfig, list) { + const formatter = 'yyyy-MM-dd HH:mm:ss'; + const now = new Date(); + const tempDate = this._formatDate(now, formatter); + const cal = new Date(); + const year = cal.getFullYear(); + const month = cal.getMonth() + 1; + const day = cal.getDate() + 3; + const day1 = cal.getDate() + 4; + const sb1 = this._formatPickupDate(year, month, day); + const sb2 = this._formatPickupDate(year, month, day1); + + let orders = []; + for (const wmsOrder of list) { + let txLogisticID = wmsOrder.sourceId; + txLogisticID = txLogisticID.length < 6 ? txLogisticID.padStart(6, '0') : txLogisticID; + if (wmsOrder.postcode === 'p10') { + if (txLogisticID.length > 19) txLogisticID = txLogisticID.slice(-19); + } else { + if (txLogisticID.length > 28) txLogisticID = txLogisticID.slice(-28); + } + txLogisticID = txLogisticID.replace(/_/g, ''); + + // 快递公司代码 + const cpcode = this.configPoloApi.postCodeMap[wmsOrder.postcode] || ''; + + // 商品名 + let cnname = ''; + let ycflag = !(wmsOrder.wareHouseId === 5400 || wmsOrder.storeId === 58303); + if (ycflag) { + const items = wmsOrder.items || ''; + const splitStr = items.split('|'); + if (splitStr.length > 0) { + const s = splitStr[0]; + const sArr = s.split(','); + if (sArr.length > 2) cnname = sArr[2]; + } + } else { + cnname = 'sp'; + } + + // 收件人手机号 + let mobile = wmsOrder.tempMobile || wmsOrder.tel || ''; + + /* + order对象结构(41-77): + { + businessplat, ismultiplepieces, businesstype, cpcode, customercode, customername, + goods: [goods对象结构(49-56)], + logisticsproductname, logistictype, mainsubpaymode, needencrypt, numpackage, + orderno, ordersource, ordertype, plattradeno, ProviderID, providercode, + receiver: receiver对象结构(59-65), sender: sender对象结构(66-75), shipperno, sitecode, Inputsite, transtype + } + goods对象结构(49-56): + { + cnname, count, unit, currencytype, Unit, weight, price + } + receiver对象结构(59-65): + { + address, name, area, city, mobile, province + } + sender对象结构(66-75): + { + country, Company, address, name, area, town, city, phone, mobile, tel, province + } + */ + // 组装订单对象(下标范围:约第41-77行) + const order = { // [order对象开始 41] + businessplat: 'OTHERS', // 41 + ismultiplepieces: '0', + businesstype: 'JH_Normal', + cpcode, + customercode: '', + customername: expressConfig.storeProperty || '测试', + goods: [{ // [goods对象开始 49] + cnname, + count: String(wmsOrder.goodsCount), + unit: '属性', + currencytype: 'CNY', + Unit: '', + weight: String(wmsOrder.orderWeight), + price: '0.0', + }], // [goods对象结束 56] + logisticsproductname: 'JH_02', + logistictype: cpcode, + mainsubpaymode: '1', + needencrypt: '1', + numpackage: '1', + orderno: wmsOrder.sourceOrderCode || (wmsOrder.id && wmsOrder.id.length > 13 ? wmsOrder.id.substring(0, 14) : wmsOrder.id), + ordersource: 'KUAI_SHOU', + ordertype: 'JH_Normal', + plattradeno: wmsOrder.sourceOrderCode || txLogisticID, + ProviderID: wmsOrder.postcode === 'p03' ? 1327 : (wmsOrder.postcode === 'p04' ? 1499 : ''), + providercode: cpcode, + receiver: { // [receiver对象开始 59] + address: wmsOrder.address, + name: wmsOrder.name, + area: wmsOrder.expAreaName, + city: wmsOrder.cityName, + mobile, + province: wmsOrder.province, + }, // [receiver对象结束 65] + sender: { // [sender对象开始 66] + country: 'CN', + Company: expressConfig.storeName, + address: expressConfig.address, + name: expressConfig.senderName, + area: expressConfig.districtName && expressConfig.districtName.indexOf(';') === -1 ? expressConfig.districtName : expressConfig.districtName.split(';')[0], + town: expressConfig.districtName && expressConfig.districtName.indexOf(';') !== -1 ? expressConfig.districtName.split(';')[1] : undefined, + city: expressConfig.cityName, + phone: expressConfig.senderTel, + mobile: expressConfig.senderTel, + tel: expressConfig.senderTel, + province: expressConfig.provinceName, + }, // [sender对象结束 75] + shipperno: ['p22', 'p35', 'p10'].includes(wmsOrder.postcode) ? expressConfig.siteCode : expressConfig.clientId, + sitecode: expressConfig.siteCode || '', + Inputsite: expressConfig.siteCode || '', + transtype: '0', + // 省略部分特殊字段和extraInfo,后续可补充 + }; // [order对象结束 77] + // 特殊字段 + if (wmsOrder.postcode === 'p10') { + order.pickUpDate = sb1; + order.pickUpEndDate = sb2; + } + orders.push(order); + } + + const body = JSON.stringify({ orders, shoptype: 'JH_001' }); + + // 组装url参数 + const urlParams = { + method: 'Differ.JH.Logistics.PostOrder', + appkey: this.configPoloApi.appKey, + token: expressConfig.sessionKey, + platid: this.configPoloApi.platid, + version: this.configPoloApi.version, + bizcontent: encodeURIComponent(body), + contenttype: this.configPoloApi.contenttype, + timestamp: encodeURIComponent(this._formatDate(new Date(), 'yyyy-MM-dd HH:mm:ss')), + }; + // 签名 + const signMap = { ...urlParams, bizcontent: body, timestamp: this._formatDate(new Date(), 'yyyy-MM-dd HH:mm:ss') }; + const signText = this.getSignText(signMap, this.configPoloApi.appSecret); + urlParams.sign = this.md5Encrypt(signText.toLowerCase(), 'utf8'); + + // 返回请求体和参数 + return { body, urlParams }; + } + + // 单个订单JSON(略,结构同上,建议复用 getJsonDatas 逻辑) + getJsonData(expressConfig, wmsOrder, deliveryOrder, type) { + // 可根据 type 判断调用 getJsonDatas 或单独组装 + return this.getJsonDatas(expressConfig, [wmsOrder]); + } + + // 生成签名字符串 + getSignText(signMap, secret) { + let sb = '' + secret; + Object.keys(signMap).sort().forEach(key => { + sb += key + signMap[key]; + }); + sb += secret; + return sb; + } + + // MD5加密 + md5Encrypt(text, encoding = 'utf8') { + return crypto.createHash('md5').update(text, encoding).digest('hex'); + } + + // 工具:格式化日期 + _formatDate(date, fmt) { + // 仅支持 yyyy-MM-dd HH:mm:ss + const pad = n => n < 10 ? '0' + n : n; + return date.getFullYear() + '-' + pad(date.getMonth() + 1) + '-' + pad(date.getDate()) + ' ' + + pad(date.getHours()) + ':' + pad(date.getMinutes()) + ':' + pad(date.getSeconds()); + } + + // 工具:组装取件日期 + _formatPickupDate(year, month, day) { + const pad = n => n < 10 ? '0' + n : n; + return `${year}-${pad(month)}-${pad(day)} 18:00:00`; + } +} + +module.exports = PoloApiService; \ No newline at end of file diff --git a/app/service/systems/storage/receiving.js b/app/service/systems/storage/receiving.js index 15e5149..6e04e25 100644 --- a/app/service/systems/storage/receiving.js +++ b/app/service/systems/storage/receiving.js @@ -34,7 +34,7 @@ class ReceivingService extends Service { where: {}, order: [], attributes: { - exclude: [ 'deleted_at' ], + exclude: ['deleted_at'], }, }; const prohibitedQueryOptions = { @@ -66,23 +66,25 @@ class ReceivingService extends Service { // 检查是否是快捷查询,快捷查询字段 if (fieldKey === 'quickWhere') { - dynamicConditions.push({ [Op.or]: { - store_name: { - [Sequelize.Op.like]: `%${condition.value}%`, - }, - receiving_number: { - [Sequelize.Op.like]: `%${condition.value}%`, - }, - tracking_number: { - [Sequelize.Op.like]: `%${condition.value}%`, - }, - creator_snapshot: { - [Sequelize.Op.like]: `%${condition.value}%`, - }, - license_plate: { - [Sequelize.Op.like]: `%${condition.value}%`, - }, - } }); + dynamicConditions.push({ + [Op.or]: { + store_name: { + [Sequelize.Op.like]: `%${condition.value}%`, + }, + receiving_number: { + [Sequelize.Op.like]: `%${condition.value}%`, + }, + tracking_number: { + [Sequelize.Op.like]: `%${condition.value}%`, + }, + creator_snapshot: { + [Sequelize.Op.like]: `%${condition.value}%`, + }, + license_plate: { + [Sequelize.Op.like]: `%${condition.value}%`, + }, + } + }); continue; // 暂不添加到动态条件中 } // 其他字段的处理 @@ -106,20 +108,20 @@ class ReceivingService extends Service { const actualSortField = validSortFields.includes(sortField) ? sortField : 'create_at'; const actualSortOrder = sortOrder.toUpperCase() === 'ASC' ? 'ASC' : 'DESC'; - queryOptions.order.push([ actualSortField, actualSortOrder ]); + queryOptions.order.push([actualSortField, actualSortOrder]); // 计算分页偏移量 const offset = (page - 1) * pageSize; // 执行查询:获取总数和数据 - const [ total, data ] = await Promise.all([ + const [total, data] = await Promise.all([ // 获取总数 ctx.model.Receiving.count({ where: queryOptions.where, include: [{ model: ctx.model.StoreWarehouse, as: 'store', - attributes: [ 'store_remask' ], + attributes: ['store_remask'], where: { use_status: 1, }, @@ -127,7 +129,7 @@ class ReceivingService extends Service { }, { model: ctx.model.AccountStoreEmployee, as: 'creator', - attributes: [ 'real_name' ], + attributes: ['real_name'], required: true, }], distinct: true, @@ -139,7 +141,7 @@ class ReceivingService extends Service { include: [{ model: ctx.model.StoreWarehouse, as: 'store', - attributes: [ 'store_remask' ], + attributes: ['store_remask'], where: { use_status: 1, }, @@ -147,7 +149,7 @@ class ReceivingService extends Service { }, { model: ctx.model.AccountStoreEmployee, as: 'creator', - attributes: [ 'real_name' ], + attributes: ['real_name'], required: true, }], limit: parseInt(pageSize), @@ -176,7 +178,7 @@ class ReceivingService extends Service { include: [{ model: ctx.model.File, as: 'file', - attributes: [ 'file_url' ], + attributes: ['file_url'], required: true, }], }); @@ -273,6 +275,112 @@ class ReceivingService extends Service { }; } } + /* + * 获取收货单详情 + */ + async getReceivingDetail(data) { + const { id, pagination } = data; + const { page, pageSize } = pagination; + const { ctx, app } = this; + const { Op } = app.Sequelize; + // 获取用户仓库ID,增加错误处理 + const warehouseId = ctx.user?.store_id; + if (!warehouseId) { + return { code: 0, message: '用户未绑定仓库', data: {} }; + } + try { + // 1. 查询收货单主表 + const receiving = await app.model.Receiving.findOne({ where: { id, warehouse_id: warehouseId } }); + if (!receiving) { + return { code: 0, message: '无记录或无权访问', data: {} }; + } + // 2. 查询收货单明细,按分页 + const receivingItems = await app.model.ReceivingDetail.findAll({ + where: { receiving_id: id }, + offset: (page - 1) * pageSize, + limit: pageSize, + }); + // 获取明细总数 + const totalItems = await app.model.ReceivingDetail.count({ where: { receiving_id: id } }); + //组装分页信息 + const pagination = { + total: totalItems, + currentPage: page, + pageSize: pageSize, + totalPages: Math.ceil(totalItems / pageSize), + hasPrevious: page > 1, + hasNext: page < Math.ceil(totalItems / pageSize), + }; + + // 3. 获取明细ID数组 + const receivingItemsIds = receivingItems.map(item => item.id); + // 4. 查询明细图片(如果明细数量大于0) + const itemImagesMap = {}; // 用于存储每个明细的图片 + if (receivingItemsIds.length > 0) { + const receivingItemsImages = await ctx.model.FileReference.findAll({ + where: { + business_type: 'receivingItem', + business_id: { [Op.in]: receivingItemsIds }, + } + }); + // 将图片按明细ID分组,eggjs 不能使用forEach异步处理,所以改为同步处理 + for (const image of receivingItemsImages) { + if (!itemImagesMap[image.business_id]) { + itemImagesMap[image.business_id] = []; + } + itemImagesMap[image.business_id].push(image); + } + } + // 5. 将图片合并到对应的明细中 + const items = receivingItems.map(item => { + return { + ...item.toJSON(), + images: itemImagesMap[item.id] || [], + }; + }); + // 6. 查询主表的图片 + const receivingImages = await ctx.model.FileReference.findAll({ + where: { + business_type: 'receiving', + business_id: id, + } + }); + // 7. 组装返回数据 + receiving.dataValues.details = items; // 包含图片的明细数据 + receiving.dataValues.images = receivingImages; // 包含主表图片 + receiving.dataValues.pagination = pagination; // 包含分页信息 + return { code: 200, message: '查询成功', data: { receiving } }; + + } catch (error) { + console.error('获取收货单详情失败:', error); + return { code: 500, message: '服务器错误', data: {} }; + } + } + //批量作废 + async batchCancelReceiving(data) { + const { ids } = data; + const { ctx } = this; + const { Op } = ctx.model.Sequelize; + const warehouse_id = ctx.user.store_id; + try { + //先查询这些单据是否都存在且状态允许作废 + const receivings = await ctx.model.Receiving.findAll({where:{ id: { [Op.in]: ids }, warehouse_id }}); + if (receivings.length !== ids.length) { + return { code: 0, message: '部分单据不存在或无权访问', data: {} }; + }else{ + const invalidStatus = receivings.find(r => r.status !== 'receiving'); + if (invalidStatus) { + return { code: 0, message: '部分单据状态不允许作废', data: {} }; + } + // 批量更新状态为cancelled + await ctx.model.Receiving.update({ status: 'cancelled' }, { where: { id: { [Op.in]: ids }, warehouse_id } }); + return { code: 200, message: '批量作废成功', data: {} }; + } + } catch (error) { + console.error('批量作废收货单失败:', error); + return { code: 500, message: '服务器错误', data: {} }; + } + } isEmptyValue(value) { if (value === undefined || value === null) { return true; @@ -502,7 +610,7 @@ class ReceivingService extends Service { case 'daterange': // 处理日期范围:数组的第一个元素是开始时间,第二个元素是结束时间 if (Array.isArray(value) && value.length === 2) { - const [ startDate, endDate ] = value; + const [startDate, endDate] = value; console.log(startDate, endDate); console.log(startDate ? service.main.normalizeDate(startDate, false) : null, endDate ? service.main.normalizeDate(endDate, true) : null); return [ @@ -556,35 +664,35 @@ class ReceivingService extends Service { }; // 2. 生成收货单号 (格式: R + 时间戳的day + 3位序列号,如: RR20231215001) - const now = new Date(); - console.log('当前时间:', now); - const dateStr = Math.floor(now.getTime() / (1000 * 60 * 60 * 24)); // 时间戳到今日的天数 - const prefix = `R${dateStr}`; + const now = new Date(); + console.log('当前时间:', now); + const dateStr = Math.floor(now.getTime() / (1000 * 60 * 60 * 24)); // 时间戳到今日的天数 + const prefix = `R${dateStr}`; - // 查找当天最大的收货单号 - const maxReceiving = await app.model.Receiving.findOne({ - where: { - receiving_number: { - [app.Sequelize.Op.like]: `${prefix}%`, - }, - warehouse_id + // 查找当天最大的收货单号 + const maxReceiving = await app.model.Receiving.findOne({ + where: { + receiving_number: { + [app.Sequelize.Op.like]: `${prefix}%`, }, - order: [[ 'receiving_number', 'DESC' ]], - }); + warehouse_id + }, + order: [['receiving_number', 'DESC']], + }); - let sequence = 1; - if (maxReceiving) { - // 提取最大收货单号的序号部分 - const lastNumStr = maxReceiving.receiving_number.replace(prefix, ''); - const lastNum = parseInt(lastNumStr); - sequence = lastNum + 1; - } + let sequence = 1; + if (maxReceiving) { + // 提取最大收货单号的序号部分 + const lastNumStr = maxReceiving.receiving_number.replace(prefix, ''); + const lastNum = parseInt(lastNumStr); + sequence = lastNum + 1; + } - // 序号动态长度:<1000用3位,<10000用4位,>=10000用5位 - let seqLen = 3; - if (sequence >= 1000 && sequence < 10000) seqLen = 4; - if (sequence >= 10000) seqLen = 5; - const receiving_number = `${prefix}${sequence.toString().padStart(seqLen, '0')}`; + // 序号动态长度:<1000用3位,<10000用4位,>=10000用5位 + let seqLen = 3; + if (sequence >= 1000 && sequence < 10000) seqLen = 4; + if (sequence >= 10000) seqLen = 5; + const receiving_number = `${prefix}${sequence.toString().padStart(seqLen, '0')}`; // 3. 获取店铺名称(如果有货主) let store_name = null; if (store_id) { @@ -661,7 +769,7 @@ class ReceivingService extends Service { include: [{ model: ctx.model.StoreWarehouse, as: 'store', - attributes: [ 'store_remask' ], + attributes: ['store_remask'], where: { use_status: 1, }, @@ -669,7 +777,7 @@ class ReceivingService extends Service { }, { model: ctx.model.AccountStoreEmployee, as: 'creator', - attributes: [ 'real_name' ], + attributes: ['real_name'], required: false, }], // 不需要order,因为根据id查询已经是唯一的 @@ -688,10 +796,10 @@ class ReceivingService extends Service { { model: ctx.model.LocationSpace, as: 'receiving_space', - attributes: [ 'space_code', 'custom_barcode', 'custom_name' ], + attributes: ['space_code', 'custom_barcode', 'custom_name'], }, ], - order: [[ 'id', 'DESC' ]], // 保持倒序,最新在前 + order: [['id', 'DESC']], // 保持倒序,最新在前 }); // 3. 获取明细ID数组 @@ -710,7 +818,7 @@ class ReceivingService extends Service { include: [{ model: ctx.model.File, as: 'file', - attributes: [ 'file_url' ], + attributes: ['file_url'], required: true, }], }); @@ -744,7 +852,7 @@ class ReceivingService extends Service { include: [{ model: ctx.model.File, as: 'file', - attributes: [ 'file_url' ], + attributes: ['file_url'], required: true, }], }); @@ -818,7 +926,7 @@ class ReceivingService extends Service { // 获取更新后的明细列表 const allDetails = await ctx.model.ReceivingDetail.findAll({ where: { receiving_id }, - order: [[ 'id', 'DESC' ]], + order: [['id', 'DESC']], }); // 格式化返回数据 @@ -872,7 +980,7 @@ class ReceivingService extends Service { { model: ctx.model.Receiving, as: 'receiving', - attributes: [ 'id', 'status' ], + attributes: ['id', 'status'], }, ], }); @@ -965,7 +1073,7 @@ class ReceivingService extends Service { } // 更新明细 - const [ affectedRows ] = await ctx.model.ReceivingDetail.update(updateData, { + const [affectedRows] = await ctx.model.ReceivingDetail.update(updateData, { where: { id }, }); @@ -988,7 +1096,7 @@ class ReceivingService extends Service { { model: ctx.model.StockWarehouse, as: 'system_product', - attributes: [ 'id', 'name', 'barcode', 'spec', 'unit', 'images' ], + attributes: ['id', 'name', 'barcode', 'spec', 'unit', 'images'], }, ], }); @@ -1037,7 +1145,7 @@ class ReceivingService extends Service { { model: ctx.model.StoreWarehouse, as: 'store_stock', - attributes: [ 'store_id', 'store_remask' ], + attributes: ['store_id', 'store_remask'], }, ], }); @@ -1121,8 +1229,8 @@ class ReceivingService extends Service { const stats = await ctx.model.ReceivingDetail.findAll({ where: { receiving_id: receivingId }, attributes: [ - [ ctx.model.fn('COUNT', ctx.model.col('id')), 'total_items' ], - [ ctx.model.fn('SUM', ctx.model.col('actual_quantity')), 'total_quantity' ], + [ctx.model.fn('COUNT', ctx.model.col('id')), 'total_items'], + [ctx.model.fn('SUM', ctx.model.col('actual_quantity')), 'total_quantity'], ], raw: true, transaction, @@ -1200,7 +1308,7 @@ class ReceivingService extends Service { { model: ctx.model.Receiving, as: 'receiving', - attributes: [ 'id', 'status' ], + attributes: ['id', 'status'], where: { warehouse_id, }, @@ -1251,7 +1359,7 @@ class ReceivingService extends Service { // 获取删除后的所有明细 const remainingDetails = await ctx.model.ReceivingDetail.findAll({ where: { receiving_id }, - order: [[ 'id', 'DESC' ]], + order: [['id', 'DESC']], }); // 格式化返回数据 @@ -1343,7 +1451,7 @@ class ReceivingService extends Service { { model: app.model.Receiving, as: 'receiving', - attributes: [ 'id', 'warehouse_id', 'store_id', 'store_name' ], + attributes: ['id', 'warehouse_id', 'store_id', 'store_name'], where: { warehouse_id: warehouseId, id: receiving_id, @@ -1414,12 +1522,12 @@ class ReceivingService extends Service { { model: app.model.StoreWarehouse, as: 'store_stock', - attributes: [ 'store_id', 'store_remask' ], + attributes: ['store_id', 'store_remask'], }, { model: app.model.StockBarcode, as: 'barcodes', - attributes: [ 'barcode' ], + attributes: ['barcode'], required: false, }, ], @@ -1658,7 +1766,7 @@ class ReceivingService extends Service { model: ctx.model.ReceivingDetail, as: 'details', required: false, - attributes: [ 'id', 'system_product_id', 'product_name', 'barcode', 'actual_quantity', 'weight' ], + attributes: ['id', 'system_product_id', 'product_name', 'barcode', 'actual_quantity', 'weight'], }], }); @@ -1732,14 +1840,14 @@ class ReceivingService extends Service { // 这里的关键修复:不仅要检查数组是否存在且有长度,还要检查数组中的元素是否有实际的数据 const hasPhoto = imageArray && - imageArray.length > 0 && - imageArray.some(img => { - // 检查图片对象是否有实际的数据 - return img.dataValues || - img.file_path || - img.url || - (img._options && Object.keys(img._options).length > 0); - }); + imageArray.length > 0 && + imageArray.some(img => { + // 检查图片对象是否有实际的数据 + return img.dataValues || + img.file_path || + img.url || + (img._options && Object.keys(img._options).length > 0); + }); const hasBarcode = !!detail.barcode && detail.barcode.trim() !== ''; const hasWeight = detail.weight > 0; const hasCount = detail.actual_quantity > 0; diff --git a/config/config.default.js b/config/config.default.js index 8cfba58..b315709 100644 --- a/config/config.default.js +++ b/config/config.default.js @@ -162,6 +162,9 @@ module.exports = appInfo => { hostname: '0.0.0.0', }, }; + config.poloapi ={ + + } config.printService = { url: 'http://localhost:4050', }; diff --git a/config/poloapi.js b/config/poloapi.js new file mode 100644 index 0000000..f738b18 --- /dev/null +++ b/config/poloapi.js @@ -0,0 +1,29 @@ +// config/poloapi.js +// 快手/PolyAPI相关固定配置 + +module.exports = { + appKey: "8e770a60b9684c558f40e4796a96710f", + appSecret: "c9cb1df531b441a8872c60ffb7f900a6", + platid: "633", + version: "1.5", + contenttype: "json", + urls: "https://api.polyapi.com/openapi/do", + // 快递公司代码映射 + postCodeMap: { + p01: "YTO", + p02: "STO", + p03: "YUNDA", + p04: "ZTO", + p05: "SF", + p06: "TTKDEX", + p07: "EMS", + p10: "JD", + p22: "POSTB", + p35: "POST_DSBK", + p09: "huitongkuaidi", + p26: "debangwuliu", + p32: "JT", + p34: "FENGWANG" + } + // 如有更多固定配置,可继续补充 +}; diff --git a/day.log b/day.log new file mode 100644 index 0000000000000000000000000000000000000000..15652490a209192d615213fee423a22226a26f09 GIT binary patch literal 9620 zcmb_iPiR|p9RJP1=C&H92M_aLcG@XR+HGB@7ds~^v#D*mPU+ZNlD;Ns^QUXltlgp8 zuqY!PWeAD`m4bpt(NiyqC_4zkMCL`jI21u-mtAzs`1$;P`SrcL=Hmh?U=JTodm|TgeluFm+{R-U^BNQu~Qy~G&yLbB$h-}N=Df$kY*Or zlyI%-H=k6zwK_L0UV=VOi4nXXhQ_A1FeHJ0zJXa|Ro_LyH)&D!68Ox6+Xe8$Uvt6` zRoGH-{R^NQgbuY(0FQZa%Ins!(~yCl5|vgh<5Ll5%lJFh_@yA@BquMPA$5hH@2jsk1Rl1L;4x%S6wA;hp!CY zRa_W=SK2FyWn8=IuNj;2h<3hYKkuYqG(5}?Eoz<~xeS?^4T!7kV&i6-791s|B^G?Z z%|Nr%j)6>*l`wv|oB?l)7jI9{C#eGyF;A{2BXfo~bPhRm2&WA(hx5yUAgIM8V3{9- z_^!%D$DoW|Y-9Z}-3#ix)iY-X=SP^57y5RKbBg|JhSe-eS`uEm>&gDAW1&5%Q znXnzL#}2~}23CCL3`1sW=0sKf{bUVxBN|%kIT%f50agh5PB2JjE4!bvVv!$J-MYc$ zC(qg?_g9JSSz2{*S?Df>7vZM^WtWS9V!yzQ=(if#Vf@ClvW^LARlNLp)OHw^4`?k` z3vbJ)KFm+P(kIy|bP{o@A4sFB7_dYV-a}tx&GhEd4y&#yc`!KkMYMk~s7sPlQ{FW! z%82(1&&-|)z-17Lc-BDYUXq^TpCdx~m5BCkpPiWh7NobbV(TuxH8-u#jsTARJN=*x z42(|N*B=h{+p5x6;7h8L@&{Rv@!?h{oV?D1yQEK^tjPDriFMwo3)Rm62gf0vOxdHZ_oUuG-Mso3k*(yRj| znQcpmE=$)@naQl!^+%@+tCB0?Q zMKl6ub9)9MXI3Tb9+&^Aj+Yhm{H8N4Ip-O@!Qwqr@si5Pmm%8EO1$u~mh;}5+Oki7 zI+Hi(G{%cNog>@N7re3Pd;Tb-?7SM$*RASrH1-7kyEJFqknh$Nf^$1Pi{-?ilNv#8 z*9=6_y#x2h8TUeB>R<)yhQb!$h>PcN&S(s*}rE@Cdg7*D$PUYu)~xc{_w z6zpKOPtv&MDgc|_U)Xy^y+hKSBdY>)?;_4S?;M-q$loHoiWX?LCA&xVP@GH9H==T$ z$gQC@^`ef{w(%GyOG`bR+m|-vvdaU6kDVx_kL8UMPRRD=${wAz$1KI%j^}Xo42$mz&?#n$XeW z%tPJKq_vOuqDhPJZp3|l)Hxp~z{PQB-rWo6=gh#?RwaVZt+p!Na6vz4X92a_)wb`2 z-;v@F^ncuk6*zBxIkO^=pV`JnBi0 z!;%x$5ymSgM04O&ZxC67^lN`CH1oT;QG06qK;0aB_xzbeC_ZQ&x^X6PaQ5ukz6o>g zv-B_PPsVt@A36$)FSENU%_k4UH^zqx`!4s@Lo>ytd9#=vF67rk@lVtD65{=ndBXB3 zh_Lvowo$8||7hy-vcj+B8MwC_Zs@=Nf4q+oH)6@0jUqU%j~W>*#Nj z&%U=m^~S`m%DwAaKdaRrZf?$p;+yNQEfRK6!hToVnBoax{FsQu?YicxcZgkUpB}*v2V2_EvSKREeH~#g?$oTEC-EZ10LMfUpLffrYKOTQ{ zm9#@~N~S3|pD$w7ZTEZ;x9zOPe7Z<^z@7BZiNB1~si=4zzLiJ*9mdtG;)T?n%)gVj zrbccSuf)drWD?^}bv5jec$VE1pMy|d`%GQ=#W(8@m&4*Tx(aT25{=zNSUexUc74;l zn}WI{wcFB^`s&s5f7EWT?9Tp~|7R+>_S4F0=KI9H`0nh^w;oLP j)$gQVPP`qz7vHgTKk;DYlhmOLYZLbq4{L`mJQn*O(-HN8 literal 0 HcmV?d00001 From 4faff36ccb99c22147f5bddc64e2ae1e86212884 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sun, 22 Mar 2026 01:38:45 +0800 Subject: [PATCH 002/550] =?UTF-8?q?docs:=20=E6=9B=B4=E6=96=B02026-03-22?= =?UTF-8?q?=E6=97=A5=E6=8A=A5=EF=BC=8C=E8=A1=A5=E5=85=85=E8=A7=84=E8=8C=83?= =?UTF-8?q?=E6=A0=BC=E5=BC=8F=E4=B8=8E=E5=86=85=E5=AE=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- day.log | Bin 9620 -> 1210 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/day.log b/day.log index 15652490a209192d615213fee423a22226a26f09..ac9fd71e43bff43c44d71e795183797f091ddc9d 100644 GIT binary patch literal 1210 zcmaJ=Z%7ki9R8ic%9>Jskk}W`Pf4U+2K})wNlBP^Yj>L_(=B(Nx9QwOx6u%0reSuM z+X(+u6d4A7Dk1vNrxHRz2n;Fu5>a7PqJj(|#n$iFSz8iuy!XC$_j{k``91G*$seV_ zK`9)8BAgH7y%eu(*ahz+W9lcd&uL1E&T3(yq2633mhmho;DG?JFwfs`7?TV9ZvKkp zsXa@&Yp)odlg9ZRzF%JB--?OmfNTh4aD+tzc!rzh7i7)8$MySN5#r2AZ^T7sm8%5K zfgijOhH_k0!bw+_vR-q`ULE&!a{>zze)T~!vMW#m?Z0aM(1oNp3FWnY&1;jKJ-3YT#1wq{90TJAY5ybZ=_@05M@@p@#5MDdtcY+KZ5W+eM zSM(gl5x{jD&MAK9HU%^B!XOJ3s8QKc#UfKW7CIN{Q;f-H=0QFY8Fy(`kIPn{Qu*D^ zZaLvcC#bva`|qnZ@w>fIBOHcPunRvlp(=*!Kqk`bLFL5BaMXtnztR&6m0g{d;vw3* z(RNSxtWHP1cxU69bvM7mo!OhH(H;E6GZ$CH4R!y8l&Y8Un-&%X?5rG4Lp9FD=tL8G zE?=#%gh!V{x|%!Yn(GW#Vx15ePCrK$R<0ikG8{NxiR+GsD#IOfObsj#jgD4!QF3%A zKGx(9o5gywX4UwDR;o>L(}{*0-+Cs5JdqN{a1#;}W0Bv3y(!q2K`4<)i5oTk&Szop zsOy8-f5Di1XP#22C(7iCxEX!q)3GUq8lsVwN!8{|PvuuRUm>ot?!EQ@!dz`I#b%!knaUv%ciNaNq>ee5;_LJs0iG@I&d;wej2+iO+NRkng1 zom)Pio~!xDPIRIPJqTl>yqIJ<&jIiAwnX!bfy~~%(1QHHRnXGC^~X?7HlqgyGq|5B CDs6xO literal 9620 zcmb_iPiR|p9RJP1=C&H92M_aLcG@XR+HGB@7ds~^v#D*mPU+ZNlD;Ns^QUXltlgp8 zuqY!PWeAD`m4bpt(NiyqC_4zkMCL`jI21u-mtAzs`1$;P`SrcL=Hmh?U=JTodm|TgeluFm+{R-U^BNQu~Qy~G&yLbB$h-}N=Df$kY*Or zlyI%-H=k6zwK_L0UV=VOi4nXXhQ_A1FeHJ0zJXa|Ro_LyH)&D!68Ox6+Xe8$Uvt6` zRoGH-{R^NQgbuY(0FQZa%Ins!(~yCl5|vgh<5Ll5%lJFh_@yA@BquMPA$5hH@2jsk1Rl1L;4x%S6wA;hp!CY zRa_W=SK2FyWn8=IuNj;2h<3hYKkuYqG(5}?Eoz<~xeS?^4T!7kV&i6-791s|B^G?Z z%|Nr%j)6>*l`wv|oB?l)7jI9{C#eGyF;A{2BXfo~bPhRm2&WA(hx5yUAgIM8V3{9- z_^!%D$DoW|Y-9Z}-3#ix)iY-X=SP^57y5RKbBg|JhSe-eS`uEm>&gDAW1&5%Q znXnzL#}2~}23CCL3`1sW=0sKf{bUVxBN|%kIT%f50agh5PB2JjE4!bvVv!$J-MYc$ zC(qg?_g9JSSz2{*S?Df>7vZM^WtWS9V!yzQ=(if#Vf@ClvW^LARlNLp)OHw^4`?k` z3vbJ)KFm+P(kIy|bP{o@A4sFB7_dYV-a}tx&GhEd4y&#yc`!KkMYMk~s7sPlQ{FW! z%82(1&&-|)z-17Lc-BDYUXq^TpCdx~m5BCkpPiWh7NobbV(TuxH8-u#jsTARJN=*x z42(|N*B=h{+p5x6;7h8L@&{Rv@!?h{oV?D1yQEK^tjPDriFMwo3)Rm62gf0vOxdHZ_oUuG-Mso3k*(yRj| znQcpmE=$)@naQl!^+%@+tCB0?Q zMKl6ub9)9MXI3Tb9+&^Aj+Yhm{H8N4Ip-O@!Qwqr@si5Pmm%8EO1$u~mh;}5+Oki7 zI+Hi(G{%cNog>@N7re3Pd;Tb-?7SM$*RASrH1-7kyEJFqknh$Nf^$1Pi{-?ilNv#8 z*9=6_y#x2h8TUeB>R<)yhQb!$h>PcN&S(s*}rE@Cdg7*D$PUYu)~xc{_w z6zpKOPtv&MDgc|_U)Xy^y+hKSBdY>)?;_4S?;M-q$loHoiWX?LCA&xVP@GH9H==T$ z$gQC@^`ef{w(%GyOG`bR+m|-vvdaU6kDVx_kL8UMPRRD=${wAz$1KI%j^}Xo42$mz&?#n$XeW z%tPJKq_vOuqDhPJZp3|l)Hxp~z{PQB-rWo6=gh#?RwaVZt+p!Na6vz4X92a_)wb`2 z-;v@F^ncuk6*zBxIkO^=pV`JnBi0 z!;%x$5ymSgM04O&ZxC67^lN`CH1oT;QG06qK;0aB_xzbeC_ZQ&x^X6PaQ5ukz6o>g zv-B_PPsVt@A36$)FSENU%_k4UH^zqx`!4s@Lo>ytd9#=vF67rk@lVtD65{=ndBXB3 zh_Lvowo$8||7hy-vcj+B8MwC_Zs@=Nf4q+oH)6@0jUqU%j~W>*#Nj z&%U=m^~S`m%DwAaKdaRrZf?$p;+yNQEfRK6!hToVnBoax{FsQu?YicxcZgkUpB}*v2V2_EvSKREeH~#g?$oTEC-EZ10LMfUpLffrYKOTQ{ zm9#@~N~S3|pD$w7ZTEZ;x9zOPe7Z<^z@7BZiNB1~si=4zzLiJ*9mdtG;)T?n%)gVj zrbccSuf)drWD?^}bv5jec$VE1pMy|d`%GQ=#W(8@m&4*Tx(aT25{=zNSUexUc74;l zn}WI{wcFB^`s&s5f7EWT?9Tp~|7R+>_S4F0=KI9H`0nh^w;oLP j)$gQVPP`qz7vHgTKk;DYlhmOLYZLbq4{L`mJQn*O(-HN8 From 279b292bae303869f89449182f9f7f4803f96fb0 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sun, 22 Mar 2026 16:21:09 +0800 Subject: [PATCH 003/550] =?UTF-8?q?chore:=20=E6=9B=B4=E6=96=B0=E6=8E=A5?= =?UTF-8?q?=E5=8F=A3=E6=96=87=E6=A1=A3=E8=B7=AF=E7=94=B1=E4=B8=8Emethods?= =?UTF-8?q?=E5=B7=A5=E4=BD=9C=E6=B5=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- AI_METHOD_ROUTING.md | 226 ++ AI_TOOLBOX.md | 170 + README.md | 10 + app/controller/docs.js | 965 ++++++ app/model/order_delivery.js | 5 + app/model/order_delivery_factory.js | 1 + app/router.js | 3 + app/service/systemMethods/order.js | 351 ++ ...-delivery-time-to-order-delivery-tables.js | 63 + day.log | Bin 1210 -> 6188 bytes methods/qimen.json | 7 + methods/system.json | 2896 +++++++++++++++++ script/db-query.ps1 | 104 + script/tmp-compare-order-schema.cjs | 171 + script/tmp-gen-service-method-inventory.cjs | 97 + script/tmp-struct-system-params.cjs | 421 +++ script/tmp-update-ai-method-routing.cjs | 30 + tmp-order-schema-compare.json | 1610 +++++++++ tmp-order-schema-workflow.md | 81 + tmp-service-method-inventory.md | 105 + 20 files changed, 7316 insertions(+) create mode 100644 AI_METHOD_ROUTING.md create mode 100644 AI_TOOLBOX.md create mode 100644 app/controller/docs.js create mode 100644 app/service/systemMethods/order.js create mode 100644 database/migrations/20260322061000-add-delivery-time-to-order-delivery-tables.js create mode 100644 methods/qimen.json create mode 100644 methods/system.json create mode 100644 script/db-query.ps1 create mode 100644 script/tmp-compare-order-schema.cjs create mode 100644 script/tmp-gen-service-method-inventory.cjs create mode 100644 script/tmp-struct-system-params.cjs create mode 100644 script/tmp-update-ai-method-routing.cjs create mode 100644 tmp-order-schema-compare.json create mode 100644 tmp-order-schema-workflow.md create mode 100644 tmp-service-method-inventory.md diff --git a/AI_METHOD_ROUTING.md b/AI_METHOD_ROUTING.md new file mode 100644 index 0000000..654cf3f --- /dev/null +++ b/AI_METHOD_ROUTING.md @@ -0,0 +1,226 @@ +# AI 方法路由速查(WMS) + +本文用于让 AI/开发者快速理解入口路由与 method 到代码文件的映射关系。 + +## 1. 入口定义(router 风格) + +当前路由定义见 `app/router.js`: +- `POST /qimen` -> 奇门开发接口入口 +- `POST /system` -> Web 端与 PDA 端统一业务入口 + +注意:当前代码中 `/qimen` 与 `/system` 都是 `POST` 路由。 + +## 2. /system 入口说明(统一 Web + PDA) + +调用链: +1. `app/router.js` -> `controller.home.system` +2. `app/controller/home.js` 的 `system()` 读取 `ctx.query.method` +3. `app/service/system.js` 的 `callMethod(className, actionName, requestData, authHeader)` +4. 从 `ctx.service.systemMethods` 中按 method 分段下钻并执行目标函数 + +参数规则(system): +- 必填 query: `method`, `v`, `timestamp` +- 认证头:可传 `Authorization` +- 请求体:JSON(`system()` 中按 JSON 解析) + +外部请求示例: + +```text +POST http://127.0.0.1:6060/system?method=print.getComputerPrinter&v=1.0×tamp=1773386721 +``` + +示例 body(按业务方法需要): + +```json +{ + "id": 10001 +} +``` + +## 3. /qimen 入口说明(奇门开发接口) + +调用链: +1. `app/router.js` -> `controller.home.qimen` +2. `app/controller/home.js` 的 `qimen()` 读取 `ctx.query.method` +3. `app/service/qimen.js` 的 `callMethod(className, actionName, xmlData, ...)` +4. 从 `ctx.service.qimenMethods` 中按 method 分段下钻并执行目标函数 + +参数规则(qimen): +- 必填 query: `app_key`, `method`, `v`, `format`, `sign_method`, `sign`, `timestamp` +- 请求体:XML(`qimen()` 中按 XML 解析) + +## 4. method 指向规则(核心) + +统一规则: +- `method` 最后一段是函数名(actionName) +- 前面部分是 service 路径(className) +- service 路径按 `.` 拆分后,对应到 `app/service/systemMethods` 或 `app/service/qimenMethods` 的目录层级 + +### 4.1 /system 示例 + +1) `method=print.getComputerPrinter` +- service 路径:`print` +- 函数名:`getComputerPrinter` +- 对应文件:`app/service/systemMethods/print.js` +- 对应方法:`getComputerPrinter(data)` + +2) `method=setting.printTemplate.list` +- service 路径:`setting.printTemplate` +- 函数名:`list` +- 对应文件:`app/service/systemMethods/setting/printTemplate.js` +- 对应方法:`list(data)` + +3) `method=printer.station.list` +- service 路径:`printer.station` +- 函数名:`list` +- 对应文件:`app/service/systemMethods/printer/station.js` +- 对应方法:`list()` + +### 4.2 /qimen 示例 + +1) `method=deliveryorder.xxx` +- service 路径:`deliveryorder` +- 对应文件:`app/service/qimenMethods/deliveryorder.js` + +2) `method=taobao.qimen.service.xxx` +- service 路径:`taobao.qimen.service` +- 对应文件:`app/service/qimenMethods/taobao/qimen/service.js` + +## 5. AI 快速定位建议 + +当收到 `method=aaa.bbb.ccc` 时,优先按以下步骤定位: +1. 判定入口:`/system` 还是 `/qimen` +2. 取最后一段 `ccc` 作为函数名 +3. 其余部分 `aaa.bbb` 作为 service 路径 +4. 在对应 methods 目录查找文件并确认类方法是否存在 + +可用检索命令示例: + +```powershell +rg "getComputerPrinter|class PrintService" app/service/systemMethods +rg "class .*Service|module.exports" app/service/qimenMethods +``` +## 后续所有的method新增变更全部需要维护到下方 + + +## method结束 + +## 6. 全量 Service Method 能力清单(自动扫描) + +维护说明: +- 扫描范围:app/service/**/*.js +- 本节内容由脚本生成,新增/修改 service 后请同步刷新。 +- 刷新命令:node .\script\tmp-gen-service-method-inventory.cjs + + +自动生成时间: 2026-03-22T06:43:50.263Z + +扫描范围: app/service/**/*.js +文件数: 50 + +- app/service/api.js (1) + - callMethod +- app/service/apiMethods/test.js (4) + - entryorderConfirm, playbackRequest, fibonacci, fibonacciRecursive +- app/service/dispatcher.js (3) + - buildMap, getMethodMap, invoke +- app/service/main.js (11) + - success, fail, normalizeDate, setInfo, getInfo, findQimenAppWithContract, queryFromDatabase, checkAuth, checkApiPermission, setUserContext, systemInit +- app/service/pda.js (3) + - callMethod, validateParams, saveLog +- app/service/qimen.js (12) + - validateApi, getErpName, parseXmlToArray, cleanXmlString, callMethod, formatResponse, xmlResponse, buildXmlNode, escapeXml, saveQimenLog, saveQimenLogResult, saveQimenLogBody +- app/service/qimenMethods/deliveryorder.js (3) + - query, create, batchcreate +- app/service/qimenMethods/entryorder.js (2) + - create, query +- app/service/qimenMethods/inventory.js (1) + - query +- app/service/qimenMethods/order.js (2) + - cancel, pending +- app/service/qimenMethods/returnorder.js (2) + - create, query +- app/service/qimenMethods/singleitem.js (2) + - synchronize, query +- app/service/qimenMethods/stockout.js (2) + - create, query +- app/service/qimenMethods/taobao/qimen/service.js (1) + - heartbeat +- app/service/system.js (3) + - callMethod, validateParams, saveLog +- app/service/systemMethods/config.js (1) + - list +- app/service/systemMethods/dashboard.js (6) + - storeStats, warehouseStats, hot_order_rank, express_ratio, platform_distribution, order_trend +- app/service/systemMethods/index.js (13) + - fastWhereTree, loadStores, getCOSUploadConfig, getImages, uploadSuccessNotify, ReferenceFile, getMessageDetail, getI18nMessage, putI18nCollect, extractModule, tryAutoTranslateNewKeys, searchSpace, getExpressList +- app/service/systemMethods/order.js (11) + - getWarehouseId, getOrderModels, applyDateRange, buildWhere, parseDateTime, list, detail, listItems, stats, updateStatus, updateDeliveryTime +- app/service/systemMethods/print.js (3) + - send, sendToComputer, log +- app/service/systemMethods/printer/station.js (1) + - list +- app/service/systemMethods/setting/printTemplate.js (3) + - list, save, listTemplatesByType +- app/service/systemMethods/stock.js (21) + - stockWarehouse, getProhibitedType, getInfo, saveWarehouseStock, createWarehouseStock, getBarcodes, saveWarehouseStockBarcode, getStoreStocks, bindItem, unbindItem, checkItemCodeUnique, queryStockLogs, handleBatchDelete, deleteUnit, deleteProhibited, handleBatchChange, getStockUnits, getUnitList, createProhibited, createUnit, search +- app/service/systemMethods/storage/receiving.js (13) + - getReceivingList, getReceivingDetail, batchCancelReceiving, create, addItem, removeItem, saveReceiving, get, addDetail, deleteDetail, detailChange, cancel, completeReceiving +- app/service/systemMethods/store.js (6) + - createStore, createWarehouse, joinStore, joinWarehouse, getStoreRoles, auditApply +- app/service/systemMethods/user.js (5) + - login, logout, info, changeRole, register +- app/service/systemMethods/warehouse.js (20) + - getWarehouseZones, getWarehouseTree, getChildren, create, update, delete, detail, checkBarcodeUnique, toggleActive, getPath, createRack, getPickPath, updateRackPosition, recalculatePickPath, updateNeighbors, getAreaRacks, getSpacesByRack, createRackWithSpaces, getSpaceInfo, updateSpaceInfo +- app/service/systems/account_platform.js (8) + - switchActiveRole, getActiveRoleByPlatform, getMultiplePlatformActiveRoles, getAllPlatformActives, clearPlatformActive, clearPlatformCache, getAvailableRoles, getCurrentContext +- app/service/systems/auth/user.js (21) + - login, ID, changeRole, info, getRoles, findById, setUserCache, getAvatarByEmployeeId, clearUserCache, clearRelatedCache, getPermissions, getMenus, convertToRoutes, findUserByIdentifier, checkUserStatus, verifyPassword, encryptPassword, generateSalt, updateLastLoginTime, ensurePlatformActiveRole, register +- app/service/systems/delivery_order.js (7) + - addOrder, generateItemsHash, calculateCRC32, prepareOrderData, addOrderLines, safeParseFloat, addOrderToQueue +- app/service/systems/entry_order.js (9) + - addOrder, getLineCount, received, success, fail, tryCreateEntryOrder, addItems, qimenEntryorderConfirm, entryorderConfirm +- app/service/systems/fast_where.js (13) + - buildTree, getTreeByType, buildSubTree, getWithChildrenByType, getAllChildren, getByType, getGroups, getChildrenByPid, getTreeChildrenByPid, create, update, findById, delete +- app/service/systems/file.js (2) + - getImages, ReferenceFile +- app/service/systems/location_space.js (16) + - create, batchCreate, list, detail, update, delete, toggleStatus, updateStatus, findAvailableSpaces, findByCode, findByBarcode, getWarehouseStats, getZoneStats, validateAllocation, validateTransferOut, _validateReferences +- app/service/systems/location_zone.js (22) + - getWarehouseLevelZones, getZoneTreeByWarehouse, getChildrenByZoneId, isLeafNode, createZone, validateBasicFields, validateByZoneType, validateParentElement, validateZoneOverlap, isOverlap, generateZoneCodeByType, getDefaultColorByType, getZoneTypeText, updateZone, deleteZone, checkZoneOverlap, getZoneDetail, toggleZoneActive, getZonePath, generateSpacesForRack, getSpaceInfo, checkBarcodeUnique +- app/service/systems/location.js (10) + - createRackWithSpaces, _generateSpacesForRack, _calculateAreaRackOrder, _calculatePickPathForWarehouse, _updateSpacePickSequence, _calculatePickPriority, updateRackPosition, getPickPath, updateNeighborRelations, _findNeighborRacks +- app/service/systems/notification.js (1) + - send +- app/service/systems/operation_log.js (4) + - createOperationLog, queryStockLogs, queryOrderLogs, getMessageDetail +- app/service/systems/platform.js (6) + - checkPlatformExists, getPlatformInfo, clearPlatformCache, getPlatformSettingDetail, batchCheckPlatforms, createPlatformSetting +- app/service/systems/polo_api.js (6) + - getJsonDatas, getJsonData, getSignText, md5Encrypt, _formatDate, _formatPickupDate +- app/service/systems/print/index.js (2) + - sendToComputer, test +- app/service/systems/qimen_query.js (6) + - send, replaceXmlTagsWithString, addSign, getQueryParams, generateUrlWithParams, sendRequest +- app/service/systems/setting/print_template.js (14) + - listTemplatesByType, getTree, getTemplatesByType, save, getBusinessTypesAndItem, getGroupedPrintItems, getTableConfigs, clearBusinessTypesCache, getXmlByTemplate, buildXmlFromElements, renderElement, computeItemStyle, computeTableItemStyle, renderTable +- app/service/systems/sign.js (10) + - Constants, toXml, signTopRequest, verifyTopRequest, verifyAndExtractParams, generateSignedParams, encryptHMAC, encryptHMACSHA256, encryptMD5, byte2hex +- app/service/systems/space.js (1) + - searchSpace +- app/service/systems/stock_store.js (34) + - create, initQimenStockData, convertToQimenFormat, getItemInfoWithCache, getItemStorages, _calculateCacheTTL, clearItemStorageCache, lockItemStorages, ID, inbound, outbound, checkAndCreateWarehouseStock, getWarehouseStock, buildSequelizeCondition, processConditionValue, formatDate, isEmptyValue, getProhibitedType, getBarcodes, handleBatchChange, saveWarehouseStockBarcode, getStoreStocks, bindItem, unbindItem, getInfo, saveWarehouseStock, createWarehouseStock, validateSaveParams, stockLog, checkItemCodeUnique, handleBatchDelete, deleteUnit, deleteProhibited, search +- app/service/systems/storage/index.js (1) + - index +- app/service/systems/storage/receiving.js (16) + - getReceivingList, getReceivingDetail, batchCancelReceiving, isEmptyValue, buildSequelizeCondition, processConditionValue, create, get, addDetail, updateDetail, getStockStoreInfo, updateReceivingStats, deleteDetail, detailChange, invalid, completeReceiving +- app/service/systems/store.js (13) + - getStoreName, getStoreRemaskName, createStore, createWarehouse, joinStore, joinWarehouse, assignAdminRoleToCreator, generateJoinToken, sendNotification, sendNotificationToAdmins, getStoreRoles, auditApply, loadStores +- app/service/systems/upload.js (14) + - initCOS, getUploadParams, hash_hmac, validateFileInfo, generateFileName, parseSizeToBytes, formatFileSize, getFrontendConfig, uploadFile, validateFile, uploadSuccessNotify, getMimeType, createFileReference, handleUploadCallback + + + + + + diff --git a/AI_TOOLBOX.md b/AI_TOOLBOX.md new file mode 100644 index 0000000..eed5349 --- /dev/null +++ b/AI_TOOLBOX.md @@ -0,0 +1,170 @@ +# AI 工具箱(WMS) + +本文件用于统一 AI 协助开发/调试时可直接使用的方法,减少重复沟通成本。 + +## 1. 适用范围 + +- 项目根目录:D:\\wms +- 主要用途:本地调试、数据库取数、问题定位 +- 默认环境:PowerShell + Node.js + +## 2. 数据库调试脚本 + +项目已提供数据库查询脚本:`script/db-query.ps1` + +脚本能力: +- 自动读取 `config/config.local.js` 中的 `config.mysql.clients.` 配置 +- 执行传入 SQL 并返回 JSON +- 可选表格输出,便于命令行快速查看 + +### 2.1 基本用法 + +```powershell +powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -Query "SELECT 1 AS ok" +``` + +### 2.2 常用示例 + +```powershell +# 查询最近 10 条账号 +powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -Query "SELECT * FROM account ORDER BY id DESC LIMIT 10" + +# 表格输出 +powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -Query "SELECT id, name FROM store LIMIT 20" -AsTable + +# 指定 mysql client(默认是 wms) +powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -DbClient wms -Query "SHOW TABLES" +``` + +### 2.3 参数说明 + +- `-Query`:必填,SQL 语句 +- `-DbClient`:可选,MySQL 客户端名,默认 `wms` +- `-ConfigPath`:可选,配置文件路径,默认 `.\config\config.local.js`(相对于项目根目录) +- `-AsTable`:可选,按表格输出结果 + +### 2.4 返回结果说明 + +默认输出 JSON,结构如下: + +```json +{ + "client": "wms", + "rowCount": 1, + "rows": [ + { + "ok": 1 + } + ] +} +``` + +## 3. AI 协助时建议使用的提问模板 + +### 3.1 只读查询(推荐) + +```text +请在项目根目录执行 script/db-query.ps1,查询 SQL: +SELECT * FROM account LIMIT 20; +并把结果按表格给我,同时解释关键字段含义。 +``` + +### 3.2 先分析再查询 + +```text +请先阅读 app/model 下与 store 相关的模型,再使用 script/db-query.ps1 查询最近 50 条门店数据, +最后输出:1) 字段映射说明 2) 异常数据判断规则 3) 建议补充索引。 +``` + +### 3.3 联合排障 + +```text +请帮我排查某接口返回为空: +1) 找到对应 controller 和 service +2) 给出需要执行的 SQL +3) 使用 script/db-query.ps1 验证每一步 +4) 输出最终根因和修复建议 +``` + +## 4. 常见问题 + +- 报错 `Cannot find module 'mysql2/promise'` + - 先执行 `npm install`,确认依赖完整 + +- 报错 `MySQL client "xxx" not found in config.mysql.clients` + - 检查 `config/config.local.js` 中 `config.mysql.clients` 是否包含对应 client + +- 报错连接失败(超时/拒绝访问) + - 检查数据库 IP、端口、用户名密码、网络白名单 + +- PowerShell 执行策略限制 + - 使用命令中的 `-ExecutionPolicy Bypass`(仅本次命令生效) + +## 5. 安全约束 + +- 默认只执行 SELECT/SHOW 等只读 SQL +- 执行 UPDATE/DELETE 前必须先让 AI 生成影响范围确认 SQL(COUNT + WHERE 条件) +- 涉及生产数据时,优先在测试环境验证 + +## 6. 接口入口与 Method 指向 + +- 入口风格: + - `/qimen`:奇门开发接口(POST) + - `/system`:Web 端与 PDA 端统一接口(POST) + +- 外部请求示例: + - `http://127.0.0.1:6060/system?method=print.getComputerPrinter&v=1.0×tamp=1773386721` + +- Method 指向说明文档: + - 见 `AI_METHOD_ROUTING.md` + - 文档记录了 method 到 `app/service/systemMethods`、`app/service/qimenMethods` 的映射规则与示例。 + +## 7. methods 目录地图 + +目录:`methods/` + +- `methods/system.json` + - 作用:维护 `/system`(及 system 风格 method)的接口说明。 + - 覆盖内容:公共请求头、method 分组、params、response、errors。 + +- `methods/qimen.json` + - 作用:维护 `/qimen` 接口说明。 + - 覆盖内容:奇门 method、请求格式、响应格式、错误码。 + +建议将 `methods/*.json` 视为“接口文档单一事实来源(SSOT)”。 + +## 8. 接口变更联动工作流(强制) + +当出现以下任一变更时,必须同步更新 `methods` 目录下对应 JSON: + +1. 新增接口(新增 method) +2. 修改接口入参(新增/删除/重命名/必填变化) +3. 修改公共请求头(如 `platform`、`project`、`Authorization`) +4. 修改响应结构或错误码 + +执行步骤: + +1. 先改代码(controller/service/model) +2. 更新对应文档文件: + - system 入口改 `methods/system.json` + - qimen 入口改 `methods/qimen.json` +3. 若 system 入参有变化,执行参数结构化脚本刷新: + +```powershell +node .\script\tmp-struct-system-params.cjs +``` + +4. 人工补充自动脚本无法推断的信息: + - `description` + - `response` + - `errors` + - 特殊枚举值与业务约束 +5. 提交前自检: + - method 名称与代码一致 + - params 的 `name/type/required/source` 完整 + - 公共头部声明与实际鉴权逻辑一致 + +执行规则:接口代码与 `methods/*.json` 不一致时,以“必须补齐文档”为完成标准。 + + + \ No newline at end of file diff --git a/README.md b/README.md index 515189c..fef76b0 100644 --- a/README.md +++ b/README.md @@ -93,3 +93,13 @@ npm stop 如需二次开发或遇到问题,欢迎提 issue 或联系维护者。 [Egg.js 官方文档](https://eggjs.org) + +## AI 协作工具箱 + +- 见 `AI_TOOLBOX.md`,内含数据库调试脚本 `script/db-query.ps1` 的完整使用方法与 AI 提问模板。 +- 见 `AI_METHOD_ROUTING.md`,内含入口路由与 method 到代码文件的映射关系。 + +## 日报维护 + +- 日报统一记录在 `day.log`。 +- 每次更新日报内容时,需同步更新 `day.log` 文件,确保项目内留痕一致。 diff --git a/app/controller/docs.js b/app/controller/docs.js new file mode 100644 index 0000000..c612e21 --- /dev/null +++ b/app/controller/docs.js @@ -0,0 +1,965 @@ +const { + Controller, +} = require('egg'); +const fs = require('fs').promises; +const path = require('path'); + +function escapeHtml(value) { + return String(value || '') + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); +} + +function toArray(value) { + return Array.isArray(value) ? value : []; +} + +function slugify(value) { + return String(value || '') + .toLowerCase() + .replace(/[^a-z0-9\u4e00-\u9fa5]+/g, '-') + .replace(/(^-|-$)/g, ''); +} + +function normalizeGroups(docData) { + if (docData && docData.methods && Array.isArray(docData.methods.groups)) { + return docData.methods.groups.map(group => ({ + groupName: group.groupName || group.module || 'Default', + module: group.module || '', + list: toArray(group.list), + })); + } + + if (docData && Array.isArray(docData.endpoints)) { + return [{ + groupName: 'Endpoints', + module: docData.module || '', + list: docData.endpoints, + }]; + } + + return []; +} + +function renderKeyValueRows(items, keyMap) { + if (!items.length) { + return '暂无数据'; + } + + return items.map(item => { + return ` + ${escapeHtml(item[keyMap.name] || '')} + ${escapeHtml(item[keyMap.type] || '')} + ${item[keyMap.required] ? '是' : '否'} + ${escapeHtml(item[keyMap.description] || '')} + `; + }).join(''); +} + +function renderGlobalHeadersControls(globalHeaders) { + const headers = toArray(globalHeaders); + if (!headers.length) { + return '

当前文档未定义额外全局 Header

'; + } + + return `
${headers.map(item => { + const name = item.name || ''; + const type = item.type || 'string'; + const required = !!item.required; + const description = item.description || ''; + const options = toArray(item.list); + + const field = options.length + ? `` + : ``; + + return ``; + }).join('')}
`; +} + +function renderMethodCard(item, entryPath, moduleName) { + const headers = toArray(item.headers); + const params = toArray(item.params); + const response = toArray(item.response); + const errors = toArray(item.errors); + const methodName = item.method || item.name || 'unknown'; + const description = item.description || ''; + const isQimen = moduleName === 'qimen'; + const queryHint = isQimen + ? 'app_key=xxx&method=...&v=2.0&format=json&sign_method=md5&sign=xxx×tamp=1700000000' + : `method=${methodName}&v=1.0×tamp=1700000000`; + + return `
+
+
+

${escapeHtml(methodName)}

+

${escapeHtml(description)}

+
+
+ 入口: ${escapeHtml(entryPath)} + 鉴权: ${item.isNeedAuth ? '是' : '否'} + 登录: ${item.isNeedLogin ? '是' : '否'} +
+
+ +
+ Headers (${headers.length}) + + + ${renderKeyValueRows(headers, { + name: 'name', + type: 'type', + required: 'required', + description: 'description', + })} +
名称类型必填说明
+
+ +
+ Params (${params.length}) + + + ${renderKeyValueRows(params, { + name: 'name', + type: 'type', + required: 'required', + description: 'description', + })} +
名称类型必填说明
+
+ +
+ Response (${response.length}) + + + ${renderKeyValueRows(response, { + name: 'name', + type: 'type', + required: 'required', + description: 'description', + })} +
名称类型必填说明
+
+ +
+ Errors (${errors.length}) + + + ${renderKeyValueRows(errors, { + name: 'code', + type: 'type', + required: 'required', + description: 'message', + })} +
名称类型必填说明
+
+ +
+ 在线调试 +
+ + + + + + +
+ + ${item.isNeedLogin ? '该接口需要登录,未设置 Token 将阻止请求' : '该接口无需登录,可不设置 Token 直接调试'} +
+ +
点击发送后显示响应
+
+
+
`; +} + +function renderHtmlPage({ + docName, + docData, + groups, + docs, + entryPath, +}) { + const methodsCount = groups.reduce((sum, group) => sum + toArray(group.list).length, 0); + const globalHeaders = toArray(docData.headers); + const globalHeadersControls = renderGlobalHeadersControls(globalHeaders); + const navHtml = docs.map(name => { + const activeClass = name === docName ? 'active' : ''; + return `${escapeHtml(name)}`; + }).join(''); + + const sidebarHtml = groups.map((group, index) => { + const list = toArray(group.list); + const groupKey = slugify(group.module || group.groupName || `group-${index}`) || `group-${index}`; + const methodsHtml = list.map(item => { + const methodName = item.method || item.name || 'unknown'; + const desc = item.description || ''; + return ``; + }).join(''); + + return ``; + }).join(''); + + const groupHtml = groups.map(group => { + const list = toArray(group.list); + const groupKey = slugify(group.module || group.groupName) || 'group'; + const cards = list.map(item => renderMethodCard(item, entryPath, docData.module)).join(''); + return `
+

${escapeHtml(group.groupName)} ${escapeHtml(group.module || '')}

+ ${cards || '

该分组暂无方法定义

'} +
`; + }).join(''); + + return ` + + + + + ${escapeHtml(docName)} API 文档 + + + +
+
+

${escapeHtml(docData.module || docName)} API 文档

+
+ 说明: ${escapeHtml(docData.description || '无')} + 版本: ${escapeHtml(docData.version || 'N/A')} + 更新: ${escapeHtml(docData.updatedAt || 'N/A')} + 方法数: ${methodsCount} + 统一入口: ${escapeHtml(entryPath)} +
+
+ ${navHtml} + 查看 JSON +
+
+

全局 Authorization

+
+ + +
+

设置后会自动注入所有“在线调试”请求头,保存在浏览器本地。

+

全局业务 Header

+ ${globalHeadersControls} +

来自 JSON 的 headers 定义;带 * 的字段为必填,支持下拉 list 选择。

+
+
+ +
+ + +
+ ${groupHtml || '

暂无可展示的方法定义

'} +
+
+
+ + +`; +} + +class DocsController extends Controller { + async list() { + const { ctx } = this; + try { + const docs = await this.getDocNames(); + if (!docs.length) { + ctx.status = 404; + ctx.body = { + code: 404, + message: 'methods 目录下没有可用的 JSON 文档', + }; + return; + } + + const fallback = docs.includes('system') ? 'system' : docs[0]; + await this.renderDoc(fallback); + } catch (error) { + ctx.status = 500; + ctx.body = { + code: 500, + message: '读取文档失败', + error: error.message, + }; + } + } + + async api() { + await this.list(); + } + + async detail() { + const { ctx } = this; + const docName = ctx.params.docName; + await this.renderDoc(docName); + } + + async raw() { + const { ctx } = this; + const docName = ctx.params.docName; + + if (!/^[a-zA-Z0-9_-]+$/.test(docName || '')) { + ctx.status = 400; + ctx.body = { code: 400, message: '无效文档名' }; + return; + } + + const filePath = path.join(this.app.baseDir, 'methods', `${docName}.json`); + + try { + const content = await fs.readFile(filePath, 'utf8'); + ctx.type = 'application/json; charset=utf-8'; + ctx.body = content; + } catch (error) { + ctx.status = 404; + ctx.body = { + code: 404, + message: `未找到文档: ${docName}`, + }; + } + } + + async getDocNames() { + const docsDir = path.join(this.app.baseDir, 'methods'); + const entries = await fs.readdir(docsDir, { withFileTypes: true }); + + return entries + .filter(entry => entry.isFile() && entry.name.endsWith('.json')) + .map(entry => entry.name.replace(/\.json$/i, '')) + .sort(); + } + + async renderDoc(docName) { + const { ctx, app } = this; + + if (!/^[a-zA-Z0-9_-]+$/.test(docName || '')) { + ctx.status = 400; + ctx.body = { code: 400, message: '无效文档名' }; + return; + } + + const filePath = path.join(app.baseDir, 'methods', `${docName}.json`); + + try { + const [ content, docs ] = await Promise.all([ + fs.readFile(filePath, 'utf8'), + this.getDocNames(), + ]); + + const docData = JSON.parse(content); + const groups = normalizeGroups(docData); + const entryPath = docData.module === 'qimen' ? '/qimen' : '/system'; + const html = renderHtmlPage({ + docName, + docData, + groups, + docs, + entryPath, + }); + + ctx.type = 'text/html; charset=utf-8'; + ctx.body = html; + } catch (error) { + ctx.status = 404; + ctx.body = { + code: 404, + message: `未找到文档或 JSON 格式错误: ${docName}`, + error: error.message, + }; + } + } +} + +module.exports = DocsController; \ No newline at end of file diff --git a/app/model/order_delivery.js b/app/model/order_delivery.js index 3b654ae..35d84c0 100644 --- a/app/model/order_delivery.js +++ b/app/model/order_delivery.js @@ -119,6 +119,11 @@ module.exports = app => { allowNull: true, comment: 'ERP审核时间', }, + delivery_time: { + type: DATE, + allowNull: true, + comment: '发货时间', + }, shop_nick: { type: STRING(200), allowNull: true, diff --git a/app/model/order_delivery_factory.js b/app/model/order_delivery_factory.js index 27a217d..a5df849 100644 --- a/app/model/order_delivery_factory.js +++ b/app/model/order_delivery_factory.js @@ -294,6 +294,7 @@ module.exports = app => { \`service_code\` varchar(50) DEFAULT NULL COMMENT '集包服务编码', \`operator_name\` varchar(50) DEFAULT NULL COMMENT 'ERP审核人', \`operate_time\` datetime DEFAULT NULL COMMENT 'ERP审核时间', + \`delivery_time\` datetime DEFAULT NULL COMMENT '发货时间', \`shop_nick\` varchar(200) DEFAULT NULL COMMENT '店铺名称', \`seller_nick\` varchar(200) DEFAULT NULL COMMENT '卖家名称', \`buyer_nick\` varchar(200) DEFAULT NULL COMMENT '买家名称', diff --git a/app/router.js b/app/router.js index ec0efb8..af886dc 100644 --- a/app/router.js +++ b/app/router.js @@ -10,6 +10,9 @@ module.exports = app => { router.post('/api/v1', controller.home.v1); router.post('/system', controller.home.system); router.post('/api/v2', controller.apiV2.index); + router.get('/api/docs', controller.docs.list); + router.get('/api/docs/:docName', controller.docs.detail); + router.get('/api/docs/:docName/raw', controller.docs.raw); router.get('/template/xml/:id', controller.template.xml); router.get('/auth/printSetting/:code', controller.auth.printerSetting); router.get('/testSendData', controller.home.testSendData); diff --git a/app/service/systemMethods/order.js b/app/service/systemMethods/order.js new file mode 100644 index 0000000..8cc17d8 --- /dev/null +++ b/app/service/systemMethods/order.js @@ -0,0 +1,351 @@ +'use strict'; + +const MainService = require('../main'); + +class orderService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list,detail,listItems,stats,updateStatus,updateDeliveryTime'; + const _noNeedLog = 'list,detail,listItems,stats'; + const _noNeedAuth = 'list,detail,listItems,stats,updateStatus,updateDeliveryTime'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + getWarehouseId(data = {}) { + const fromParam = Number(data.warehouse_id || data.warehouseId || 0); + const fromUser = Number(this.ctx.user?.store_id || 0); + return fromParam || fromUser; + } + + async getOrderModels(warehouseId) { + const DeliveryModel = await this.ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); + const OrderItemsModel = await this.ctx.model.OrderItemsFactory.getCurrentModel(warehouseId); + return { DeliveryModel, OrderItemsModel }; + } + + applyDateRange(where, field, start, end) { + const { Op } = this.app.Sequelize; + const range = {}; + + if (start) { + range[Op.gte] = this.normalizeDate(start, false); + } + if (end) { + range[Op.lte] = this.normalizeDate(end, true); + } + + if (Object.keys(range).length > 0) { + where[field] = range; + } + } + + buildWhere(whereData = {}, warehouseId) { + const { Op } = this.app.Sequelize; + const where = { warehouse_id: warehouseId }; + + const eqFields = [ + 'id', + 'store_id', + 'status', + 'post_status', + 'storage_status', + 'pick_status', + 'pack_status', + 'inspection_status', + 'print_status', + 'claim_status', + 'outbound_status', + 'lock_status', + 'intercept_status', + 'source_platform_code', + 'logistics_code', + 'warehouse_code', + 'order_type', + ]; + + for (const key of eqFields) { + if (whereData[key] !== undefined && whereData[key] !== null && whereData[key] !== '') { + where[key] = whereData[key]; + } + } + + if (whereData.delivery_order_code) { + where.delivery_order_code = { [Op.like]: `%${whereData.delivery_order_code}%` }; + } + + if (Array.isArray(whereData.delivery_order_codes) && whereData.delivery_order_codes.length > 0) { + where.delivery_order_code = { [Op.in]: whereData.delivery_order_codes }; + } + + if (whereData.logistics_name) { + where.logistics_name = { [Op.like]: `%${whereData.logistics_name}%` }; + } + + if (whereData.buyer_nick) { + where.buyer_nick = { [Op.like]: `%${whereData.buyer_nick}%` }; + } + + if (whereData.mobile) { + where.mobile = { [Op.like]: `%${whereData.mobile}%` }; + } + + this.applyDateRange(where, 'create_at', whereData.create_at_start, whereData.create_at_end); + this.applyDateRange(where, 'place_order_time', whereData.place_order_time_start, whereData.place_order_time_end); + this.applyDateRange(where, 'pay_time', whereData.pay_time_start, whereData.pay_time_end); + this.applyDateRange(where, 'delivery_time', whereData.delivery_time_start, whereData.delivery_time_end); + + return where; + } + + parseDateTime(value, fieldName) { + if (!value) return null; + const d = value instanceof Date ? value : new Date(value); + if (Number.isNaN(d.getTime())) { + throw new Error(`${fieldName} 格式错误`); + } + return d; + } + + async list(data = {}) { + try { + const warehouseId = this.getWarehouseId(data); + if (!warehouseId) { + return this.fail('warehouse_id 不能为空', { code: 400 }); + } + + const { DeliveryModel } = await this.getOrderModels(warehouseId); + const where = this.buildWhere(data.where || {}, warehouseId); + + const page = Math.max(Number(data.pagination?.page || 1), 1); + const pageSize = Math.min(Math.max(Number(data.pagination?.pageSize || 20), 1), 200); + const offset = (page - 1) * pageSize; + + const result = await DeliveryModel.findAndCountAll({ + where, + offset, + limit: pageSize, + order: [ [ 'updated_at', 'DESC' ], [ 'id', 'DESC' ] ], + raw: true, + }); + + return this.success('ok', { + data: { + list: result.rows, + pagination: { + page, + pageSize, + total: result.count, + totalPages: Math.ceil(result.count / pageSize), + hasNext: page * pageSize < result.count, + hasPrevious: page > 1, + }, + }, + code: 200, + }); + } catch (error) { + return this.fail(error.message, { code: 500 }); + } + } + + async detail(data = {}) { + try { + const warehouseId = this.getWarehouseId(data); + if (!warehouseId) { + return this.fail('warehouse_id 不能为空', { code: 400 }); + } + + const { DeliveryModel, OrderItemsModel } = await this.getOrderModels(warehouseId); + const where = { warehouse_id: warehouseId }; + + if (data.id) { + where.id = data.id; + } else if (data.delivery_order_code) { + where.delivery_order_code = data.delivery_order_code; + } else { + return this.fail('id 或 delivery_order_code 必填', { code: 400 }); + } + + const order = await DeliveryModel.findOne({ where, raw: true }); + if (!order) { + return this.fail('订单不存在', { code: 404 }); + } + + const items = await OrderItemsModel.findAll({ + where: { order_id: order.id }, + order: [ [ 'id', 'ASC' ] ], + raw: true, + }); + + return this.success('ok', { + data: { + order, + items, + }, + code: 200, + }); + } catch (error) { + return this.fail(error.message, { code: 500 }); + } + } + + async listItems(data = {}) { + try { + const warehouseId = this.getWarehouseId(data); + if (!warehouseId) { + return this.fail('warehouse_id 不能为空', { code: 400 }); + } + + const { DeliveryModel, OrderItemsModel } = await this.getOrderModels(warehouseId); + const where = { warehouse_id: warehouseId }; + + if (data.order_id) { + where.id = data.order_id; + } else if (data.delivery_order_code) { + where.delivery_order_code = data.delivery_order_code; + } else { + return this.fail('order_id 或 delivery_order_code 必填', { code: 400 }); + } + + const order = await DeliveryModel.findOne({ where, attributes: [ 'id', 'delivery_order_code' ], raw: true }); + if (!order) { + return this.fail('订单不存在', { code: 404 }); + } + + const items = await OrderItemsModel.findAll({ + where: { order_id: order.id }, + order: [ [ 'id', 'ASC' ] ], + raw: true, + }); + + return this.success('ok', { + data: { + order, + items, + }, + code: 200, + }); + } catch (error) { + return this.fail(error.message, { code: 500 }); + } + } + + async stats(data = {}) { + try { + const warehouseId = this.getWarehouseId(data); + if (!warehouseId) { + return this.fail('warehouse_id 不能为空', { code: 400 }); + } + + const { Sequelize } = this.app; + const { DeliveryModel } = await this.getOrderModels(warehouseId); + const where = this.buildWhere(data.where || {}, warehouseId); + + const total = await DeliveryModel.count({ where }); + const byStatusRows = await DeliveryModel.findAll({ + where, + attributes: [ 'status', [ Sequelize.fn('COUNT', Sequelize.col('id')), 'count' ] ], + group: [ 'status' ], + raw: true, + }); + + const byOutboundRows = await DeliveryModel.findAll({ + where, + attributes: [ 'outbound_status', [ Sequelize.fn('COUNT', Sequelize.col('id')), 'count' ] ], + group: [ 'outbound_status' ], + raw: true, + }); + + return this.success('ok', { + data: { + total, + byStatus: byStatusRows, + byOutboundStatus: byOutboundRows, + }, + code: 200, + }); + } catch (error) { + return this.fail(error.message, { code: 500 }); + } + } + + async updateStatus(data = {}) { + try { + const warehouseId = this.getWarehouseId(data); + if (!warehouseId) { + return this.fail('warehouse_id 不能为空', { code: 400 }); + } + + const { DeliveryModel } = await this.getOrderModels(warehouseId); + const where = { warehouse_id: warehouseId }; + + if (data.id) { + where.id = data.id; + } else if (data.delivery_order_code) { + where.delivery_order_code = data.delivery_order_code; + } else { + return this.fail('id 或 delivery_order_code 必填', { code: 400 }); + } + + const allowedFields = [ + 'status', + 'post_status', + 'storage_status', + 'pick_status', + 'pack_status', + 'inspection_status', + 'print_status', + 'claim_status', + 'outbound_status', + 'lock_status', + 'intercept_status', + ]; + + const updateData = {}; + for (const key of allowedFields) { + if (data[key] !== undefined && data[key] !== null && data[key] !== '') { + updateData[key] = data[key]; + } + } + + if (data.delivery_time) { + updateData.delivery_time = this.parseDateTime(data.delivery_time, 'delivery_time'); + } + + if (!updateData.delivery_time && updateData.outbound_status === 'fin') { + updateData.delivery_time = new Date(); + } + + if (Object.keys(updateData).length === 0) { + return this.fail('没有可更新字段', { code: 400 }); + } + + updateData.updated_at = new Date(); + + const [ affected ] = await DeliveryModel.update(updateData, { where }); + if (!affected) { + return this.fail('订单不存在或未更新', { code: 404 }); + } + + const order = await DeliveryModel.findOne({ where, raw: true }); + return this.success('更新成功', { data: order, code: 200 }); + } catch (error) { + return this.fail(error.message, { code: 500 }); + } + } + + async updateDeliveryTime(data = {}) { + if (!data.delivery_time) { + return this.fail('delivery_time 必填', { code: 400 }); + } + + const nextData = { ...data }; + if (nextData.syncOutboundStatus === true || nextData.syncOutboundStatus === 1 || nextData.syncOutboundStatus === '1') { + nextData.outbound_status = 'fin'; + } + + return await this.updateStatus(nextData); + } +} + +module.exports = orderService; diff --git a/database/migrations/20260322061000-add-delivery-time-to-order-delivery-tables.js b/database/migrations/20260322061000-add-delivery-time-to-order-delivery-tables.js new file mode 100644 index 0000000..b8e70d1 --- /dev/null +++ b/database/migrations/20260322061000-add-delivery-time-to-order-delivery-tables.js @@ -0,0 +1,63 @@ +'use strict'; + +module.exports = { + async up(queryInterface) { + const [ tables ] = await queryInterface.sequelize.query(` + SELECT TABLE_NAME + FROM INFORMATION_SCHEMA.TABLES + WHERE TABLE_SCHEMA = DATABASE() + AND (TABLE_NAME = 'wms_order_delivery' OR TABLE_NAME LIKE 'wms_order_delivery\\_%') + `); + + for (const row of tables) { + const tableName = row.TABLE_NAME; + + const [ columns ] = await queryInterface.sequelize.query( + ` + SELECT COLUMN_NAME + FROM INFORMATION_SCHEMA.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = :tableName + AND COLUMN_NAME = 'delivery_time' + `, + { replacements: { tableName } } + ); + + if (columns.length === 0) { + await queryInterface.sequelize.query( + `ALTER TABLE \`${tableName}\` ADD COLUMN \`delivery_time\` datetime NULL DEFAULT NULL COMMENT '发货时间' AFTER \`operate_time\`` + ); + } + } + }, + + async down(queryInterface) { + const [ tables ] = await queryInterface.sequelize.query(` + SELECT TABLE_NAME + FROM INFORMATION_SCHEMA.TABLES + WHERE TABLE_SCHEMA = DATABASE() + AND (TABLE_NAME = 'wms_order_delivery' OR TABLE_NAME LIKE 'wms_order_delivery\\_%') + `); + + for (const row of tables) { + const tableName = row.TABLE_NAME; + + const [ columns ] = await queryInterface.sequelize.query( + ` + SELECT COLUMN_NAME + FROM INFORMATION_SCHEMA.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = :tableName + AND COLUMN_NAME = 'delivery_time' + `, + { replacements: { tableName } } + ); + + if (columns.length > 0) { + await queryInterface.sequelize.query( + `ALTER TABLE \`${tableName}\` DROP COLUMN \`delivery_time\`` + ); + } + } + }, +}; diff --git a/day.log b/day.log index ac9fd71e43bff43c44d71e795183797f091ddc9d..f5f97845641408533f9ece5f51b2b0cda32c46df 100644 GIT binary patch literal 6188 zcmb_gZEREL6@E?DG+B(tIt^`B5jQ_JvVw_2r!rEl8igoLA=lW~`H~Ym@y+!INt}?x zH>3!steKk34oONA0%a5?Q2DiGnl_33*{D#eF;##l2&rn>mStjNBom4<0fM{p+&AW4 zn*^9NS^j?CbIyCtbDnd~t3BMroNN<&g*oW`WqRF2kCp7J>_*~ba$4#S*fl9o>6vM$ zca=(|qQJr|%DS1ru84>HR&7Qs5P#x6>&usq`^v^I$)`k{_^z@bUYF)W-AZov3MXXY z$wZ6uf;gk3e5-=#-y9_8l6+0N71$9hX1iEBYh}G`D}Ab9KMLlD?^Pf5RgT8`oF0M6 z^lyxXNPCzSvkrZ2J8Pm(QMQroW?jsxU6RWste+Zph$r{uc0YLg0}r<@)-v9Gtm2}tF zl!6?KGfbywXU$}l#o0-kU~iNxhfa$V=ZMk2_$IK5eO>O2W7vDY?S$v=$*IK6)(fL4 zZ-MxHB=n=QTJan?HY&)x@_l@LwmXWMdkiMe)tSzqr~P zt=bo^b4i>Dn4FUy4F57_$evV=*KUc-s#SpwB_<#8=cKMC?FTl51v*=hvSAM)1itH~ z^LCJrOX$SKibcMkye4I1(u~lJgyeRLMH9VqbPB9rh0Vax9{Lr#Tj>Od5AsR%hl4u@ zfEG8~N#CzY9g1NmvSxXk1m=A^CuI}oq@wt`#?;YsNvn3J!9McIFyxhyyfU_pc}Z#s zJ-59zJz#0Ojd(8gB?3^BVT&yE%D z?jtO6AHsh{@vE&i5s@xaj*Y)3&x8#PMKwzyiEODoK^X|mT<%OmkNa2q6!)}b)hfqD zm(6=S!7&2sV-z3ceh{$QwhdIkPxJ+-dlhYc-u5dwyJ(AD&bSch}Ug!xy9l1$*CB{889s_!EQr!ypzC-tM6Csx{IuYwL zbaJkX(b>Q+0%Z$c&nj<37L@W4uxX7RnPytiL#XFkT8AsBMt~=#2S>tbZCgm!_r(Q8 zAe6~En+t3`?U2cb3RwW=_0SXf7}bA+rmqEFe(R_YdBd$jl=CU-@Y%`a3m$XSE%NO| z%GY1@WOiNTvqzD<6?kC;(aPlLUq^DgRX?IIAF|g~N!#2z+OAU0q5iB4Q*3w5)|%P# zN+ORi(M;z6kANA#TF9gM(D}ifcly;C<#Z4^WU%3b;g=2?zJ~rMWhK}Jb{hNvX?far zhyEj3oHxe~`z_8x{#u{KiRzKBss3PKRq*-9l>0sT*!b4Ag0~D0eqL>HN`V<2Wyqa8 z?X)~C*+lFF2JZ|RAIyy70O14%dEWu z13Oza*gGf9tEc6hR8hQN*Ecoz(8OG@1U5znP>Vimx$CoQe++`BdkDQ<#AofKgV(}< z{to`-m9m#~7t?d8mFRbP-OpUZnH#miELmU|B&vRmxgKtZm3)m;wUKt{Mz(<^R*m#d z-1UX`7%>L(A_vfGZEZt-+r%r0W8sg)Xs2EGc|PTsK-RQTRys_lanR{xJ)7GIV-7k6 zPTE4e1FZEdGIySaI78;|l01gbDi4(nI>ELINkg{<2F}yqXn;z0dAU5Cc`CWyqxxfePbFUzE=%i%7L@rhc(Jsvq;8D>7O`uuije`E z2)~!tfZJ`M*k1Em!_z>D`5$Fq*N0{gn`6bR5|5mLmHtRa z|CxOSyxj9gOx6GYuQfnuXd;w!>$ZW15Jj^Uyz--~3R9fHxlujJb}c<4U_!ur;G}t> zgkJG*(8^|dI3CL=$0Hx%Q+pO-vptG6O;poc$){b5*6Dms`vi8U;jVA8D?c0=0NW#8 zsvmt0dK|m9RMuw8w>Y0=Rp8ONa5jOJ*VOvZuVhOz;$KAn@%ofT#P{@h2Uhd0jdwKQ zP;|n`>(!DOZRU;(owb*}LH*WtViga)SJC$hCbIIyET)cta1AEfvxvYLX#&G!PASxb zQ0H_zSwZy>IPKQwon~4qguYULe(>9#3sPxs(q;H~J~T=7cPW-O_xg}JpR|Rj+gv=& z!}m|ikdi)e#C>t}aTd?C0oCHVdbY!^wFEE9%gtQ^D-a{@o7C%P*96R%s{e>vp^l$h z{B+L=3_aa*u_~!ls;M#9fcxJ(;R!5V>x}Hqv>?;hl_vjUIyCA`I?K=-eBi>gj7ngR z20UR#gLyCN6Q)ihM&^HkN#snFa%Slj>HQV7j#sdy*Fgs`+_j9HIB|a(<m(`vCIBrq_cW_(aoi=xNe}+@ww#7#GE2o3FRp7ji z)$rq;hTM7`XS5D?BbZ^(pQCH&B>Orjrs+NlC%us%t0>P)MKdzZtBdI@OV7v9$@_}T z_35tVf9(gJCNE4rjnOGH^V5-$Wez%HOz-qCYa@qH|M;BoH2G%iqt-=9mpOwSB#n2l zd8SGeic|lHLz-QKPY1E!kryv8UwF6l;e-j6TH90 z+=(7?HO(Z51fK93I2owND%6>5mgJm`$x^1s3+yBL6;FijuhMrjm`Kw5am&Q5;ke{` z%k@f&s>$yVf#|d}XtZiY@q;2VVJ2MAla^)pmP;`s0d`=D&6Dcyld7D+Q0E~# zU5B5|QgbB0HJEUolh)IGTtc0tz+R#b{(QpXM1Q$i|DIhjo5HiI5r?T+3HTw delta 15 XcmZ2uu#0oUAEwDSSl&!N$94$-JmUxA diff --git a/methods/qimen.json b/methods/qimen.json new file mode 100644 index 0000000..01b7464 --- /dev/null +++ b/methods/qimen.json @@ -0,0 +1,7 @@ +{ + "module": "qimen", + "description": "Qimen API method catalog", + "version": "0.1.0", + "updatedAt": "2026-03-22", + "endpoints": [] +} diff --git a/methods/system.json b/methods/system.json new file mode 100644 index 0000000..6436e3b --- /dev/null +++ b/methods/system.json @@ -0,0 +1,2896 @@ +{ + "module": "system", + "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", + "version": "0.3.0", + "updatedAt": "2026-03-22", + "headers": [ + { + "name": "platform", + "type": "string", + "required": true, + "description": "客户端平台标识,如 web/pda/app", + "list":[ + {"value":"web","name":"网页端"}, + {"value":"pda","name":"PDA端"}, + {"value":"app","name":"APP端"}, + {"value":"wx","name":"微信端"}, + {"value":"miniProgram","name":"小程序端"}, + {"value":"other","name":"其他"} + ] + }, + { + "type":"string", + "required":true, + "name":"project", + "description":"项目标识,如 wms", + "list":[ + {"value":"all","name":"所有系统"}, + {"value":"wms","name":"仓库管理系统"}, + {"value":"tms","name":"运输管理系统"}, + {"value":"scm","name":"供应链管理系统"}, + {"value":"other","name":"其他"} + ] + } + ], + "methods": { + "groups": [ + { + "groupName": "配置模块", + "module": "config", + "list": [ + { + "method": "config.list", + "description": "config.list 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "看板模块", + "module": "dashboard", + "list": [ + { + "method": "dashboard.storeStats", + "description": "dashboard.storeStats 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "dashboard.warehouseStats", + "description": "dashboard.warehouseStats 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "dashboard.hot_order_rank", + "description": "dashboard.hot_order_rank 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "dashboard.express_ratio", + "description": "dashboard.express_ratio 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "dashboard.platform_distribution", + "description": "dashboard.platform_distribution 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "dashboard.order_trend", + "description": "dashboard.order_trend 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "基础模块", + "module": "index", + "list": [ + { + "method": "index.fastWhereTree", + "description": "index.fastWhereTree 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "type", + "type": "string", + "required": false, + "source": "body", + "description": "type 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "index.loadStores", + "description": "index.loadStores 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "index.getCOSUploadConfig", + "description": "index.getCOSUploadConfig 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "data", + "type": "object", + "required": false, + "source": "body", + "description": "data 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "index.getImages", + "description": "index.getImages 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "index.uploadSuccessNotify", + "description": "index.uploadSuccessNotify 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "index.ReferenceFile", + "description": "index.ReferenceFile 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "index.getMessageDetail", + "description": "index.getMessageDetail 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "index.getI18nMessage", + "description": "index.getI18nMessage 接口", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "language", + "type": "string", + "required": false, + "source": "body|query", + "description": "language 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "index.putI18nCollect", + "description": "index.putI18nCollect 接口", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "keys", + "type": "array", + "required": false, + "source": "body", + "description": "keys 参数" + }, + { + "name": "locale", + "type": "string", + "required": false, + "source": "body", + "description": "locale 参数" + }, + { + "name": "project", + "type": "string", + "required": false, + "source": "body", + "description": "project 参数" + }, + { + "name": "source", + "type": "string", + "required": false, + "source": "body", + "description": "source 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "index.tryAutoTranslateNewKeys", + "description": "index.tryAutoTranslateNewKeys 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "index.searchSpace", + "description": "index.searchSpace 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "index.getExpressList", + "description": "index.getExpressList 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "订单模块", + "module": "order", + "list": [ + { + "method": "order.getOrderModels", + "description": "order.getOrderModels 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "order.list", + "description": "分页查询订单列表", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "pagination 参数" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "where 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "order.detail", + "description": "查询订单详情", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "delivery_order_code", + "type": "string", + "required": false, + "source": "body", + "description": "delivery_order_code 参数" + }, + { + "name": "id", + "type": "number", + "required": false, + "source": "body", + "description": "id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "order.listItems", + "description": "查询订单商品明细", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "delivery_order_code", + "type": "string", + "required": false, + "source": "body", + "description": "delivery_order_code 参数" + }, + { + "name": "order_id", + "type": "number", + "required": false, + "source": "body", + "description": "order_id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "order.stats", + "description": "订单统计", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "where 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "order.updateStatus", + "description": "更新订单状态", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "claim_status", + "type": "string", + "required": false, + "source": "body", + "description": "claim_status 参数" + }, + { + "name": "delivery_order_code", + "type": "string", + "required": false, + "source": "body", + "description": "delivery_order_code 参数" + }, + { + "name": "delivery_time", + "type": "string", + "required": false, + "source": "body", + "description": "delivery_time 参数" + }, + { + "name": "id", + "type": "number", + "required": false, + "source": "body", + "description": "id 参数" + }, + { + "name": "inspection_status", + "type": "string", + "required": false, + "source": "body", + "description": "inspection_status 参数" + }, + { + "name": "intercept_status", + "type": "string", + "required": false, + "source": "body", + "description": "intercept_status 参数" + }, + { + "name": "lock_status", + "type": "string", + "required": false, + "source": "body", + "description": "lock_status 参数" + }, + { + "name": "outbound_status", + "type": "string", + "required": false, + "source": "body", + "description": "outbound_status 参数" + }, + { + "name": "pack_status", + "type": "string", + "required": false, + "source": "body", + "description": "pack_status 参数" + }, + { + "name": "pick_status", + "type": "string", + "required": false, + "source": "body", + "description": "pick_status 参数" + }, + { + "name": "post_status", + "type": "string", + "required": false, + "source": "body", + "description": "post_status 参数" + }, + { + "name": "print_status", + "type": "string", + "required": false, + "source": "body", + "description": "print_status 参数" + }, + { + "name": "status", + "type": "string", + "required": false, + "source": "body", + "description": "status 参数" + }, + { + "name": "storage_status", + "type": "string", + "required": false, + "source": "body", + "description": "storage_status 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "order.updateDeliveryTime", + "description": "更新发货时间", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "delivery_time", + "type": "string", + "required": true, + "source": "body", + "description": "delivery_time 参数" + } + ], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "打印模块", + "module": "print", + "list": [ + { + "method": "print.send", + "description": "print.send 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "computerId", + "type": "string", + "required": false, + "source": "body", + "description": "computerId 参数" + }, + { + "name": "count", + "type": "number", + "required": false, + "source": "body", + "description": "count 参数" + }, + { + "name": "data", + "type": "object", + "required": false, + "source": "body", + "description": "data 参数" + }, + { + "name": "printer", + "type": "string", + "required": false, + "source": "body", + "description": "printer 参数" + }, + { + "name": "template", + "type": "object", + "required": false, + "source": "body", + "description": "template 参数" + }, + { + "name": "timestamp", + "type": "string", + "required": false, + "source": "body", + "description": "timestamp 参数" + }, + { + "name": "type", + "type": "string", + "required": false, + "source": "body", + "description": "type 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "print.getPrintResult", + "description": "print.getPrintResult 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "printId", + "type": "string", + "required": true, + "source": "body", + "description": "printId 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "print.getPrintRecordItem", + "description": "print.getPrintRecordItem 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "print.getList", + "description": "print.getList 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "page", + "type": "number", + "required": false, + "source": "body", + "description": "page 参数" + }, + { + "name": "pageSize", + "type": "number", + "required": false, + "source": "body", + "description": "pageSize 参数" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "where 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "print.getItem", + "description": "print.getItem 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "print.add", + "description": "print.add 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "computer_id", + "type": "number", + "required": true, + "source": "body", + "description": "computer_id 参数" + }, + { + "name": "name", + "type": "string", + "required": true, + "source": "body", + "description": "name 参数" + }, + { + "name": "custom_barcode", + "type": "string", + "required": false, + "source": "body", + "description": "custom_barcode 参数" + }, + { + "name": "default_printer_name", + "type": "string", + "required": false, + "source": "body", + "description": "default_printer_name 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "print.hasName", + "description": "print.hasName 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "name", + "type": "string", + "required": true, + "source": "body", + "description": "name 参数" + }, + { + "name": "id", + "type": "number", + "required": false, + "source": "body", + "description": "id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "print.updateItem", + "description": "print.updateItem 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "id 参数" + }, + { + "name": "computer_id", + "type": "number", + "required": false, + "source": "body", + "description": "computer_id 参数" + }, + { + "name": "custom_barcode", + "type": "string", + "required": false, + "source": "body", + "description": "custom_barcode 参数" + }, + { + "name": "name", + "type": "string", + "required": false, + "source": "body", + "description": "name 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "print.del", + "description": "print.del 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids", + "type": "array", + "required": false, + "source": "body", + "description": "ids 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "print.getComputer", + "description": "print.getComputer 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "print.getComputerPrinter", + "description": "print.getComputerPrinter 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "print.savePrinters", + "description": "print.savePrinters 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "defaultPrinter", + "type": "string", + "required": true, + "source": "body", + "description": "defaultPrinter 参数" + }, + { + "name": "express", + "type": "array", + "required": false, + "source": "body", + "description": "express 参数" + }, + { + "name": "print_station_id", + "type": "number", + "required": false, + "source": "body", + "description": "print_station_id 参数" + } + ], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "打印机站点模块", + "module": "printer.station", + "list": [ + { + "method": "printer.station.list", + "description": "获取打印站点列表", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "打印模板模块", + "module": "setting.printTemplate", + "list": [ + { + "method": "setting.printTemplate.list", + "description": "获取打印模板树", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "setting.printTemplate.save", + "description": "保存打印模板", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "setting.printTemplate.listTemplatesByType", + "description": "按业务类型查询模板", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "businessType", + "type": "string", + "required": true, + "source": "body", + "description": "businessType 参数" + } + ], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "库存模块", + "module": "stock", + "list": [ + { + "method": "stock.stockWarehouse", + "description": "stock.stockWarehouse 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "pagination 参数" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "where 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "stock.getProhibitedType", + "description": "stock.getProhibitedType 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.getInfo", + "description": "stock.getInfo 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.saveWarehouseStock", + "description": "stock.saveWarehouseStock 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.createWarehouseStock", + "description": "stock.createWarehouseStock 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.getBarcodes", + "description": "stock.getBarcodes 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.saveWarehouseStockBarcode", + "description": "stock.saveWarehouseStockBarcode 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.getStoreStocks", + "description": "stock.getStoreStocks 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.bindItem", + "description": "stock.bindItem 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.unbindItem", + "description": "stock.unbindItem 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.checkItemCodeUnique", + "description": "stock.checkItemCodeUnique 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "item_code", + "type": "string", + "required": true, + "source": "body", + "description": "item_code 参数" + }, + { + "name": "store_id", + "type": "number", + "required": true, + "source": "body", + "description": "store_id 参数" + }, + { + "name": "id", + "type": "number", + "required": false, + "source": "body", + "description": "id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "stock.queryStockLogs", + "description": "stock.queryStockLogs 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "warehouseId", + "type": "string", + "required": false, + "source": "body", + "description": "warehouseId 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "stock.handleBatchDelete", + "description": "stock.handleBatchDelete 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.deleteUnit", + "description": "stock.deleteUnit 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.deleteProhibited", + "description": "stock.deleteProhibited 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.handleBatchChange", + "description": "stock.handleBatchChange 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.getStockUnits", + "description": "stock.getStockUnits 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.getUnitList", + "description": "stock.getUnitList 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.createProhibited", + "description": "stock.createProhibited 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "name", + "type": "string", + "required": true, + "source": "body", + "description": "name 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "stock.createUnit", + "description": "stock.createUnit 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "name", + "type": "string", + "required": true, + "source": "body", + "description": "name 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "stock.search", + "description": "stock.search 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "入库模块", + "module": "storage.receiving", + "list": [ + { + "method": "storage.receiving.getReceivingList", + "description": "storage.receiving.getReceivingList 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "pagination 参数" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "where 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "storage.receiving.getReceivingDetail", + "description": "storage.receiving.getReceivingDetail 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "storage.receiving.batchCancelReceiving", + "description": "storage.receiving.batchCancelReceiving 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "storage.receiving.create", + "description": "storage.receiving.create 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "storage.receiving.addItem", + "description": "storage.receiving.addItem 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": false, + "source": "body", + "description": "id 参数" + }, + { + "name": "item", + "type": "object", + "required": false, + "source": "body", + "description": "item 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "storage.receiving.removeItem", + "description": "storage.receiving.removeItem 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": false, + "source": "body", + "description": "id 参数" + }, + { + "name": "item_id", + "type": "number", + "required": false, + "source": "body", + "description": "item_id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "storage.receiving.saveReceiving", + "description": "storage.receiving.saveReceiving 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "storage.receiving.get", + "description": "storage.receiving.get 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "storage.receiving.addDetail", + "description": "storage.receiving.addDetail 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "storage.receiving.deleteDetail", + "description": "storage.receiving.deleteDetail 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "storage.receiving.detailChange", + "description": "storage.receiving.detailChange 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "storage.receiving.cancel", + "description": "storage.receiving.cancel 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "storage.receiving.completeReceiving", + "description": "storage.receiving.completeReceiving 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "门店模块", + "module": "store", + "list": [ + { + "method": "store.createStore", + "description": "store.createStore 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "store.createWarehouse", + "description": "store.createWarehouse 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "store.joinStore", + "description": "store.joinStore 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "store.joinWarehouse", + "description": "store.joinWarehouse 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "store.getStoreRoles", + "description": "store.getStoreRoles 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "store.auditApply", + "description": "store.auditApply 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "用户模块", + "module": "user", + "list": [ + { + "method": "user.login", + "description": "用户登录", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "password", + "type": "string", + "required": false, + "source": "body", + "description": "password 参数" + }, + { + "name": "username", + "type": "string", + "required": false, + "source": "body", + "description": "username 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "user.logout", + "description": "用户登出", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "user.info", + "description": "获取当前用户信息", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "user.changeRole", + "description": "user.changeRole 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "user.register", + "description": "user.register 接口", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "仓库模块", + "module": "warehouse", + "list": [ + { + "method": "warehouse.getWarehouseZones", + "description": "warehouse.getWarehouseZones 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "warehouse.getWarehouseTree", + "description": "warehouse.getWarehouseTree 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "warehouseId", + "type": "number", + "required": true, + "source": "body", + "description": "warehouseId 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.getChildren", + "description": "warehouse.getChildren 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "zoneId", + "type": "number", + "required": true, + "source": "body", + "description": "zoneId 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.create", + "description": "warehouse.create 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "warehouse.update", + "description": "warehouse.update 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "id 参数" + }, + { + "name": "aisles", + "type": "string", + "required": false, + "source": "body", + "description": "aisles 参数" + }, + { + "name": "cell_height", + "type": "string", + "required": false, + "source": "body", + "description": "cell_height 参数" + }, + { + "name": "cell_length", + "type": "string", + "required": false, + "source": "body", + "description": "cell_length 参数" + }, + { + "name": "cell_width", + "type": "string", + "required": false, + "source": "body", + "description": "cell_width 参数" + }, + { + "name": "direction", + "type": "string", + "required": false, + "source": "body", + "description": "direction 参数" + }, + { + "name": "height", + "type": "number", + "required": false, + "source": "body", + "description": "height 参数" + }, + { + "name": "length", + "type": "number", + "required": false, + "source": "body", + "description": "length 参数" + }, + { + "name": "rack_columns", + "type": "string", + "required": false, + "source": "body", + "description": "rack_columns 参数" + }, + { + "name": "rack_levels", + "type": "string", + "required": false, + "source": "body", + "description": "rack_levels 参数" + }, + { + "name": "rack_rows", + "type": "string", + "required": false, + "source": "body", + "description": "rack_rows 参数" + }, + { + "name": "width", + "type": "number", + "required": false, + "source": "body", + "description": "width 参数" + }, + { + "name": "x", + "type": "number", + "required": false, + "source": "body", + "description": "x 参数" + }, + { + "name": "y", + "type": "number", + "required": false, + "source": "body", + "description": "y 参数" + }, + { + "name": "z", + "type": "number", + "required": false, + "source": "body", + "description": "z 参数" + }, + { + "name": "zone_code", + "type": "string", + "required": false, + "source": "body", + "description": "zone_code 参数" + }, + { + "name": "zone_name", + "type": "string", + "required": false, + "source": "body", + "description": "zone_name 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.delete", + "description": "warehouse.delete 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.detail", + "description": "warehouse.detail 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.checkBarcodeUnique", + "description": "warehouse.checkBarcodeUnique 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "barcode", + "type": "string", + "required": true, + "source": "body", + "description": "barcode 参数" + }, + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.toggleActive", + "description": "warehouse.toggleActive 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "id 参数" + }, + { + "name": "isActive", + "type": "string", + "required": false, + "source": "body", + "description": "isActive 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.getPath", + "description": "warehouse.getPath 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.createRack", + "description": "warehouse.createRack 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "height", + "type": "number", + "required": true, + "source": "body", + "description": "height 参数" + }, + { + "name": "length", + "type": "number", + "required": true, + "source": "body", + "description": "length 参数" + }, + { + "name": "rack_columns", + "type": "number", + "required": true, + "source": "body", + "description": "rack_columns 参数" + }, + { + "name": "rack_levels", + "type": "number", + "required": true, + "source": "body", + "description": "rack_levels 参数" + }, + { + "name": "rack_rows", + "type": "number", + "required": true, + "source": "body", + "description": "rack_rows 参数" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "source": "body", + "description": "warehouse_id 参数" + }, + { + "name": "width", + "type": "number", + "required": true, + "source": "body", + "description": "width 参数" + }, + { + "name": "x", + "type": "number", + "required": true, + "source": "body", + "description": "x 参数" + }, + { + "name": "y", + "type": "number", + "required": true, + "source": "body", + "description": "y 参数" + }, + { + "name": "zone_code", + "type": "string", + "required": true, + "source": "body", + "description": "zone_code 参数" + }, + { + "name": "zone_name", + "type": "string", + "required": true, + "source": "body", + "description": "zone_name 参数" + }, + { + "name": "color", + "type": "string", + "required": false, + "source": "body", + "description": "color 参数" + }, + { + "name": "direction", + "type": "string", + "required": false, + "source": "body", + "description": "direction 参数" + }, + { + "name": "parent_id", + "type": "number", + "required": false, + "source": "body", + "description": "parent_id 参数" + }, + { + "name": "z", + "type": "number", + "required": false, + "source": "body", + "description": "z 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.getPickPath", + "description": "warehouse.getPickPath 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "warehouse_id", + "type": "number", + "required": true, + "source": "query", + "description": "warehouse_id 参数" + }, + { + "name": "include_spaces", + "type": "string", + "required": false, + "source": "query", + "description": "include_spaces 参数" + }, + { + "name": "limit", + "type": "number", + "required": false, + "source": "query", + "description": "limit 参数" + }, + { + "name": "sort_by", + "type": "string", + "required": false, + "source": "query", + "description": "sort_by 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.updateRackPosition", + "description": "warehouse.updateRackPosition 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "x", + "type": "number", + "required": true, + "source": "body", + "description": "x 参数" + }, + { + "name": "y", + "type": "number", + "required": true, + "source": "body", + "description": "y 参数" + }, + { + "name": "rack_id", + "type": "number", + "required": false, + "source": "path", + "description": "rack_id 参数" + }, + { + "name": "z", + "type": "number", + "required": false, + "source": "body", + "description": "z 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.recalculatePickPath", + "description": "warehouse.recalculatePickPath 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "warehouse_id", + "type": "number", + "required": true, + "source": "body", + "description": "warehouse_id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.updateNeighbors", + "description": "warehouse.updateNeighbors 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "warehouse_id", + "type": "number", + "required": true, + "source": "body", + "description": "warehouse_id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.getAreaRacks", + "description": "warehouse.getAreaRacks 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "area_id", + "type": "number", + "required": true, + "source": "query", + "description": "area_id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.getSpacesByRack", + "description": "warehouse.getSpacesByRack 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.createRackWithSpaces", + "description": "warehouse.createRackWithSpaces 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.getSpaceInfo", + "description": "warehouse.getSpaceInfo 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": false, + "source": "body", + "description": "id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.updateSpaceInfo", + "description": "warehouse.updateSpaceInfo 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "id 参数" + }, + { + "name": "custom_barcode", + "type": "string", + "required": false, + "source": "body", + "description": "custom_barcode 参数" + }, + { + "name": "custom_name", + "type": "string", + "required": false, + "source": "body", + "description": "custom_name 参数" + }, + { + "name": "location_type_id", + "type": "number", + "required": false, + "source": "body", + "description": "location_type_id 参数" + }, + { + "name": "pick_sequence", + "type": "string", + "required": false, + "source": "body", + "description": "pick_sequence 参数" + }, + { + "name": "space_status", + "type": "string", + "required": false, + "source": "body", + "description": "space_status 参数" + } + ], + "response": [], + "errors": [] + } + ] + } + ] + } +} \ No newline at end of file diff --git a/script/db-query.ps1 b/script/db-query.ps1 new file mode 100644 index 0000000..10b9dce --- /dev/null +++ b/script/db-query.ps1 @@ -0,0 +1,104 @@ +param( + [Parameter(Mandatory = $true, Position = 0)] + [string]$Query, + + [Parameter(Mandatory = $false)] + [string]$DbClient = "wms", + + [Parameter(Mandatory = $false)] + [string]$ConfigPath = ".\\config\\config.local.js", + + [switch]$AsTable +) + + Set-StrictMode -Version Latest + $ErrorActionPreference = "Stop" + +$scriptRoot = Split-Path -Parent $MyInvocation.MyCommand.Path +$projectRoot = Split-Path -Parent $scriptRoot +$configFullPath = Join-Path $projectRoot $ConfigPath +$configResolved = Resolve-Path -Path $configFullPath -ErrorAction Stop + +$nodeScript = @' +const path = require("path"); +const { createRequire } = require("module"); + +(async () => { + const projectRoot = process.argv[2]; + const configPath = process.argv[3]; + const clientName = process.argv[4]; + const query = process.argv[5]; + + const projectRequire = createRequire(path.join(projectRoot, "package.json")); + const mysql = projectRequire("mysql2/promise"); + + if (!query) { + throw new Error("Query is required."); + } + + const configFactory = require(path.resolve(configPath)); + const config = typeof configFactory === "function" + ? configFactory({ name: "wms-debug" }) + : configFactory; + + const client = config + && config.mysql + && config.mysql.clients + && config.mysql.clients[clientName]; + + if (!client) { + throw new Error(`MySQL client "${clientName}" not found in config.mysql.clients.`); + } + + const connection = await mysql.createConnection({ + host: client.host, + port: Number(client.port), + user: client.user, + password: client.password, + database: client.database, + charset: client.charset || "utf8mb4", + }); + + try { + const [rows] = await connection.query(query); + process.stdout.write(JSON.stringify({ + client: clientName, + rowCount: Array.isArray(rows) ? rows.length : 0, + rows, + })); + } finally { + await connection.end(); + } +})().catch((err) => { + process.stderr.write(err && err.stack ? err.stack : String(err)); + process.exit(1); +}); +'@ + +$tempFile = New-TemporaryFile +$tempNodeFile = [System.IO.Path]::ChangeExtension($tempFile.FullName, ".cjs") +Move-Item -Path $tempFile.FullName -Destination $tempNodeFile -Force +Set-Content -Path $tempNodeFile -Value $nodeScript -Encoding UTF8 + +try { + $json = & node $tempNodeFile $projectRoot $configResolved.Path $DbClient $Query + if ($LASTEXITCODE -ne 0) { + throw "Node query runner exited with code $LASTEXITCODE." + } +} finally { + Remove-Item -Path $tempNodeFile -ErrorAction SilentlyContinue +} + +$result = $json | ConvertFrom-Json +Write-Host "Client: $($result.client)" +Write-Host "Rows: $($result.rowCount)" + +if ($AsTable) { + if (($result.rows -is [System.Array]) -and $result.rows.Count -gt 0) { + $result.rows | Format-Table -AutoSize + } else { + Write-Host "No tabular rows to render." + } +} else { + $result | ConvertTo-Json -Depth 50 +} diff --git a/script/tmp-compare-order-schema.cjs b/script/tmp-compare-order-schema.cjs new file mode 100644 index 0000000..9bba2f3 --- /dev/null +++ b/script/tmp-compare-order-schema.cjs @@ -0,0 +1,171 @@ +const fs = require('fs'); +const path = require('path'); +const { createRequire } = require('module'); + +function extractTopLevelFieldsFromObjectBody(body) { + const fields = []; + let i = 0; + let depth = 0; + while (i < body.length) { + const ch = body[i]; + if (ch === '{') { + depth++; + i++; + continue; + } + if (ch === '}') { + depth--; + i++; + continue; + } + + if (depth === 0) { + const m = body.slice(i).match(/^\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*:\s*\{/); + if (m) { + const key = m[1]; + fields.push(key); + i += m[0].length; + let inner = 1; + while (i < body.length && inner > 0) { + const c = body[i++]; + if (c === '{') inner++; + if (c === '}') inner--; + } + continue; + } + } + i++; + } + return [...new Set(fields)]; +} + +function getObjectBodyByMarker(text, marker) { + const start = text.indexOf(marker); + if (start < 0) return null; + const braceStart = text.indexOf('{', start + marker.length); + if (braceStart < 0) return null; + let i = braceStart + 1; + let depth = 1; + let body = ''; + while (i < text.length && depth > 0) { + const ch = text[i++]; + if (ch === '{') depth++; + if (ch === '}') depth--; + if (depth > 0) body += ch; + } + return body; +} + +function extractDefineFields(text) { + const definePos = text.indexOf('define('); + if (definePos < 0) return []; + const firstBrace = text.indexOf('{', definePos); + if (firstBrace < 0) return []; + let i = firstBrace + 1; + let depth = 1; + let body = ''; + while (i < text.length && depth > 0) { + const ch = text[i++]; + if (ch === '{') depth++; + if (ch === '}') depth--; + if (depth > 0) body += ch; + } + return extractTopLevelFieldsFromObjectBody(body); +} + +async function main() { + const root = process.cwd(); + const projectRequire = createRequire(path.join(root, 'package.json')); + const mysql = projectRequire('mysql2/promise'); + const cfgFactory = require(path.join(root, 'config', 'config.local.js')); + const cfg = typeof cfgFactory === 'function' ? cfgFactory({ name: 'wms-debug' }) : cfgFactory; + const client = cfg?.mysql?.clients?.wms; + if (!client) throw new Error('mysql client wms not found'); + + const conn = await mysql.createConnection({ + host: client.host, + port: Number(client.port), + user: client.user, + password: client.password, + database: client.database, + charset: client.charset || 'utf8mb4', + }); + + const [tableRows] = await conn.query( + "SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND (TABLE_NAME IN ('wms_order_delivery','wms_order_items','wms_entry_order') OR TABLE_NAME LIKE 'wms_order_delivery_%' OR TABLE_NAME LIKE 'wms_order_items_%') ORDER BY TABLE_NAME" + ); + + const tableSchemas = {}; + for (const t of tableRows.map(x => x.TABLE_NAME)) { + const [cols] = await conn.query( + "SELECT COLUMN_NAME,COLUMN_TYPE,IS_NULLABLE,COLUMN_DEFAULT,EXTRA,COLUMN_KEY FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? ORDER BY ORDINAL_POSITION", + [t] + ); + tableSchemas[t] = cols; + } + + const targets = [ + { table: 'wms_order_delivery', modelFile: 'app/model/order_delivery.js', type: 'baseModel' }, + { table: 'wms_order_items', modelFile: 'app/model/order_items.js', type: 'define' }, + { table: 'wms_entry_order', modelFile: 'app/model/entry_order.js', type: 'define' }, + ]; + + const compareWithModel = targets.map(t => { + const txt = fs.readFileSync(path.join(root, t.modelFile), 'utf8'); + let modelFields = []; + if (t.type === 'baseModel') { + const body = getObjectBodyByMarker(txt, 'const baseModel ='); + modelFields = body ? extractTopLevelFieldsFromObjectBody(body) : []; + } else { + modelFields = extractDefineFields(txt); + } + + const dbColumns = (tableSchemas[t.table] || []).map(c => c.COLUMN_NAME); + const modelOnly = modelFields.filter(f => !dbColumns.includes(f)); + const dbOnly = dbColumns.filter(c => !modelFields.includes(c)); + + return { + table: t.table, + modelFile: t.modelFile, + modelFieldCount: modelFields.length, + dbFieldCount: dbColumns.length, + modelOnly, + dbOnly, + allMatched: modelOnly.length === 0 && dbOnly.length === 0, + }; + }); + + const dynamicTableCheck = []; + const dynamicTables = Object.keys(tableSchemas).filter(t => t.endsWith('_100000')); + for (const dt of dynamicTables) { + const baseTable = dt.startsWith('wms_order_delivery_') ? 'wms_order_delivery' : dt.startsWith('wms_order_items_') ? 'wms_order_items' : null; + if (!baseTable) continue; + const baseCols = (tableSchemas[baseTable] || []).map(c => c.COLUMN_NAME); + const dynCols = (tableSchemas[dt] || []).map(c => c.COLUMN_NAME); + dynamicTableCheck.push({ + table: dt, + baseTable, + missingFromDynamic: baseCols.filter(c => !dynCols.includes(c)), + extraInDynamic: dynCols.filter(c => !baseCols.includes(c)), + allMatched: baseCols.length === dynCols.length && baseCols.every(c => dynCols.includes(c)), + }); + } + + const out = { + generatedAt: new Date().toISOString(), + dbName: client.database, + tables: tableRows.map(x => x.TABLE_NAME), + compareWithModel, + dynamicTableCheck, + schema: tableSchemas, + }; + + fs.writeFileSync(path.join(root, 'tmp-order-schema-compare.json'), JSON.stringify(out, null, 2)); + await conn.end(); + console.log('WROTE tmp-order-schema-compare.json'); +} + +main().catch(err => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); +}); diff --git a/script/tmp-gen-service-method-inventory.cjs b/script/tmp-gen-service-method-inventory.cjs new file mode 100644 index 0000000..cf3f692 --- /dev/null +++ b/script/tmp-gen-service-method-inventory.cjs @@ -0,0 +1,97 @@ +const fs = require('fs'); +const path = require('path'); + +const root = process.cwd(); +const serviceRoot = path.join(root, 'app', 'service'); + +function walk(dir) { + const out = []; + for (const name of fs.readdirSync(dir)) { + const full = path.join(dir, name); + const st = fs.statSync(full); + if (st.isDirectory()) out.push(...walk(full)); + else if (name.endsWith('.js')) out.push(full); + } + return out; +} + +function extractClassMethods(content) { + const methods = []; + const classIdx = content.indexOf('class '); + if (classIdx < 0) return methods; + const braceStart = content.indexOf('{', classIdx); + if (braceStart < 0) return methods; + + let i = braceStart + 1; + let depth = 1; + let body = ''; + while (i < content.length && depth > 0) { + const ch = content[i++]; + if (ch === '{') depth++; + if (ch === '}') depth--; + if (depth > 0) body += ch; + } + + let p = 0; + let nested = 0; + while (p < body.length) { + const ch = body[p]; + if (ch === '{') { nested++; p++; continue; } + if (ch === '}') { nested--; p++; continue; } + + if (nested === 0) { + const slice = body.slice(p); + const m = slice.match(/^\s*(?:async\s+)?([A-Za-z_$][\w$]*)\s*\(/); + if (m) { + const name = m[1]; + if (name !== 'constructor') methods.push(name); + + // move to method body end + p += m[0].length; + while (p < body.length && body[p] !== '{') p++; + if (body[p] === '{') { + p++; + let inMethod = 1; + while (p < body.length && inMethod > 0) { + if (body[p] === '{') inMethod++; + else if (body[p] === '}') inMethod--; + p++; + } + } + continue; + } + } + p++; + } + + return [...new Set(methods)]; +} + +const files = walk(serviceRoot) + .map(full => path.relative(root, full).replace(/\\/g, '/')) + .sort((a, b) => a.localeCompare(b)); + +const inventory = []; +for (const rel of files) { + const full = path.join(root, rel); + const content = fs.readFileSync(full, 'utf8'); + const methods = extractClassMethods(content); + inventory.push({ file: rel, methodCount: methods.length, methods }); +} + +const now = new Date().toISOString(); +let md = ''; +md += `自动生成时间: ${now}\n\n`; +md += `扫描范围: app/service/**/*.js\n`; +md += `文件数: ${inventory.length}\n\n`; +for (const item of inventory) { + md += `- ${item.file} (${item.methodCount})\n`; + if (item.methods.length === 0) { + md += ` - \n`; + } else { + md += ` - ${item.methods.join(', ')}\n`; + } +} + +fs.writeFileSync(path.join(root, 'tmp-service-method-inventory.md'), md, 'utf8'); +console.log('WROTE tmp-service-method-inventory.md'); diff --git a/script/tmp-struct-system-params.cjs b/script/tmp-struct-system-params.cjs new file mode 100644 index 0000000..5d89be3 --- /dev/null +++ b/script/tmp-struct-system-params.cjs @@ -0,0 +1,421 @@ +const fs = require('fs'); +const path = require('path'); +const acorn = require('acorn'); + +const baseDir = process.cwd(); +const methodsDir = path.join(baseDir, 'app', 'service', 'systemMethods'); +const jsonPath = path.join(baseDir, 'methods', 'system.json'); + +function walk(node, visitor, parent = null) { + if (!node || typeof node !== 'object') return; + visitor(node, parent); + for (const key of Object.keys(node)) { + const value = node[key]; + if (!value) continue; + if (Array.isArray(value)) { + for (const item of value) walk(item, visitor, node); + } else if (typeof value === 'object' && value.type) { + walk(value, visitor, node); + } + } +} + +function walkFiles(dir) { + const files = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + const full = path.join(dir, entry.name); + if (entry.isDirectory()) files.push(...walkFiles(full)); + if (entry.isFile() && entry.name.endsWith('.js')) files.push(full); + } + return files; +} + +function getPropName(node) { + if (!node) return null; + if (node.type === 'Identifier') return node.name; + if (node.type === 'Literal') return String(node.value); + return null; +} + +function memberPath(node) { + if (!node) return null; + if (node.type === 'ChainExpression') return memberPath(node.expression); + if (node.type === 'Identifier') return node.name; + if (node.type === 'ThisExpression') return 'this'; + if (node.type !== 'MemberExpression') return null; + const left = memberPath(node.object); + if (!left) return null; + if (node.computed) { + if (node.property.type === 'Literal') return `${left}.${String(node.property.value)}`; + if (node.property.type === 'Identifier') return left; + return left; + } + const right = getPropName(node.property); + return right ? `${left}.${right}` : left; +} + +function classifySourceByExpr(expr, signatureSet) { + const sources = new Set(); + const visit = node => { + if (!node) return; + if (node.type === 'Identifier' && signatureSet.has(node.name)) { + sources.add('body'); + return; + } + if (node.type === 'MemberExpression' || node.type === 'ChainExpression') { + const p = memberPath(node); + if (p && p.startsWith('ctx.request.body')) sources.add('body'); + else if (p && p.startsWith('ctx.query')) sources.add('query'); + else if (p && p.startsWith('ctx.params')) sources.add('path'); + else if (p && p.startsWith('ctx.headers')) sources.add('header'); + return; + } + if (node.type === 'LogicalExpression' || node.type === 'BinaryExpression') { + visit(node.left); + visit(node.right); + return; + } + if (node.type === 'ConditionalExpression') { + visit(node.consequent); + visit(node.alternate); + return; + } + }; + visit(expr); + if (!sources.size) return null; + return Array.from(sources).sort().join('|'); +} + +function inferTypeByName(name) { + if (!name) return 'string'; + if (/ids$/i.test(name)) return 'array'; + if (/^(where|pagination|item|template|data|filters?)$/i.test(name)) return 'object'; + if (/^(is_|has_|need|sync)/i.test(name)) return 'boolean'; + if (/(^id$|_id$|^page$|^pageSize$|^limit$|^offset$|^count$|_count$|^x$|^y$|^z$|^rows$|^columns$|^levels$|^width$|^height$|^length$)/i.test(name)) return 'number'; + if (/(^date$|_date$|^time$|_time$|timestamp)/i.test(name)) return 'string'; + return 'string'; +} + +function inferTypeByNode(node, fallbackName = '') { + if (!node) return inferTypeByName(fallbackName); + if (node.type === 'Literal') { + if (typeof node.value === 'number') return 'number'; + if (typeof node.value === 'boolean') return 'boolean'; + return 'string'; + } + if (node.type === 'ObjectExpression') return 'object'; + if (node.type === 'ArrayExpression') return 'array'; + return inferTypeByName(fallbackName); +} + +function mapValidateType(v) { + if (!v) return 'string'; + const t = String(v).toLowerCase(); + if (t === 'int' || t === 'integer' || t === 'number') return 'number'; + if (t === 'boolean' || t === 'bool') return 'boolean'; + if (t === 'array') return 'array'; + if (t === 'object') return 'object'; + return 'string'; +} + +function extractNoNeedLists(classNode) { + const result = { noNeedLogin: [], noNeedAuth: ['*'] }; + const ctor = classNode.body.body.find(m => m.type === 'MethodDefinition' && m.kind === 'constructor'); + if (!ctor) return result; + + for (const stmt of ctor.value.body.body || []) { + if (stmt.type !== 'VariableDeclaration') continue; + for (const decl of stmt.declarations || []) { + if (decl.id.type !== 'Identifier' || !decl.init || decl.init.type !== 'Literal') continue; + const name = decl.id.name; + const value = String(decl.init.value || ''); + if (name === '_noNeedLogin') result.noNeedLogin = value.split(',').map(s => s.trim()).filter(Boolean); + if (name === '_noNeedAuth') result.noNeedAuth = value.split(',').map(s => s.trim()).filter(Boolean); + } + } + return result; +} + +function collectMethodParams(methodNode) { + const signatureNames = []; + for (const p of methodNode.value.params || []) { + if (p.type === 'Identifier') signatureNames.push(p.name); + else if (p.type === 'AssignmentPattern' && p.left.type === 'Identifier') signatureNames.push(p.left.name); + } + const signatureSet = new Set(signatureNames); + const aliasMap = new Map(); + const entries = new Map(); + const listFields = []; + + function resolveName(localName) { + return aliasMap.get(localName) || localName; + } + + function ensure(name) { + if (!entries.has(name)) { + entries.set(name, { + name, + type: inferTypeByName(name), + required: false, + source: new Set(), + }); + } + return entries.get(name); + } + + function addParam(name, patch = {}) { + if (!name) return; + if ([ 'ctx', 'service', 'app', 'result', 'error', 'e' ].includes(name)) return; + const item = ensure(name); + if (patch.type) item.type = patch.type; + if (patch.required === true) item.required = true; + if (patch.source) item.source.add(patch.source); + } + + function addRequiredFromTest(testNode) { + if (!testNode) return; + if (testNode.type === 'UnaryExpression' && testNode.operator === '!') { + if (testNode.argument.type === 'Identifier') { + const local = testNode.argument.name; + const resolved = resolveName(local); + if (resolved !== local || entries.has(resolved)) { + addParam(resolved, { required: true }); + } + } + if (testNode.argument.type === 'MemberExpression' || testNode.argument.type === 'ChainExpression') { + const p = memberPath(testNode.argument); + if (!p) return; + const parts = p.split('.'); + if (parts.length === 2 && signatureSet.has(parts[0])) { + addParam(parts[1], { required: true, source: 'body' }); + } + } + return; + } + if (testNode.type === 'LogicalExpression') { + addRequiredFromTest(testNode.left); + addRequiredFromTest(testNode.right); + return; + } + if (testNode.type === 'CallExpression') { + const callee = memberPath(testNode.callee); + if (callee === 'Array.isArray' && testNode.arguments[0] && testNode.arguments[0].type === 'Identifier') { + const local = testNode.arguments[0].name; + const resolved = resolveName(local); + if (resolved !== local || entries.has(resolved)) { + addParam(resolved, { required: true, type: 'array' }); + } + } + } + } + + walk(methodNode.value.body, (node, parent) => { + if (node.type === 'VariableDeclarator') { + if (node.id.type === 'ObjectPattern' && node.init) { + const source = classifySourceByExpr(node.init, signatureSet); + if (!source) return; + for (const prop of node.id.properties || []) { + if (prop.type !== 'Property') continue; + const keyName = getPropName(prop.key); + if (!keyName) continue; + + let localName = keyName; + let type = inferTypeByName(keyName); + + if (prop.value.type === 'Identifier') { + localName = prop.value.name; + } else if (prop.value.type === 'AssignmentPattern') { + if (prop.value.left.type === 'Identifier') localName = prop.value.left.name; + type = inferTypeByNode(prop.value.right, keyName); + } + + aliasMap.set(localName, keyName); + addParam(keyName, { source, type }); + } + } + + if (node.id.type === 'Identifier' && node.init) { + const local = node.id.name; + + if (node.init.type === 'MemberExpression' || node.init.type === 'ChainExpression') { + const p = memberPath(node.init); + if (p) { + const parts = p.split('.'); + if (parts.length === 2 && signatureSet.has(parts[0])) { + aliasMap.set(local, parts[1]); + addParam(parts[1], { source: 'body' }); + } + if (parts.length >= 3 && parts[0] === 'ctx' && parts[1] === 'query') { + aliasMap.set(local, parts[2]); + addParam(parts[2], { source: 'query' }); + } + if (parts.length >= 3 && parts[0] === 'ctx' && parts[1] === 'params') { + aliasMap.set(local, parts[2]); + addParam(parts[2], { source: 'path' }); + } + if (parts.length >= 4 && parts[0] === 'ctx' && parts[1] === 'request' && parts[2] === 'body') { + aliasMap.set(local, parts[3]); + addParam(parts[3], { source: 'body' }); + } + } + } + + if ((/allowedFields|eqFields/i).test(local) && node.init.type === 'ArrayExpression') { + const arr = []; + for (const el of node.init.elements || []) { + if (el && el.type === 'Literal' && typeof el.value === 'string') arr.push(el.value); + } + if (arr.length) listFields.push(...arr); + } + } + } + + if (node.type === 'IfStatement') { + addRequiredFromTest(node.test); + } + + if (node.type === 'CallExpression') { + const callee = memberPath(node.callee); + + if (callee === 'ctx.validate' && node.arguments[0] && node.arguments[0].type === 'ObjectExpression') { + for (const p of node.arguments[0].properties || []) { + if (p.type !== 'Property') continue; + const field = getPropName(p.key); + if (!field || p.value.type !== 'ObjectExpression') continue; + let required = false; + let type = null; + for (const conf of p.value.properties || []) { + if (conf.type !== 'Property') continue; + const confKey = getPropName(conf.key); + if (!confKey) continue; + if (confKey === 'required' && conf.value.type === 'Literal') { + required = Boolean(conf.value.value); + } + if (confKey === 'type' && conf.value.type === 'Literal') { + type = mapValidateType(conf.value.value); + } + } + addParam(field, { required, type: type || inferTypeByName(field), source: 'body' }); + } + } + + if (callee === 'Array.isArray' && node.arguments[0] && node.arguments[0].type === 'Identifier') { + const local = node.arguments[0].name; + const resolved = resolveName(local); + if (resolved !== local || entries.has(resolved)) { + addParam(resolved, { type: 'array' }); + } + } + + if ((callee === 'parseInt' || callee === 'Number') && node.arguments[0]) { + const arg = node.arguments[0]; + if (arg.type === 'Identifier') { + const resolved = resolveName(arg.name); + if (resolved !== arg.name || entries.has(resolved)) { + addParam(resolved, { type: 'number' }); + } + } + if (arg.type === 'MemberExpression' || arg.type === 'ChainExpression') { + const p = memberPath(arg); + if (p) { + const parts = p.split('.'); + if (parts.length === 2 && signatureSet.has(parts[0])) addParam(parts[1], { type: 'number', source: 'body' }); + } + } + } + } + + if (node.type === 'MemberExpression' || node.type === 'ChainExpression') { + const p = memberPath(node); + if (!p) return; + const parts = p.split('.'); + if (parts.length === 2 && signatureSet.has(parts[0])) { + addParam(parts[1], { source: 'body' }); + } + if (parts.length >= 3 && parts[0] === 'ctx' && parts[1] === 'query') { + addParam(parts[2], { source: 'query' }); + } + if (parts.length >= 3 && parts[0] === 'ctx' && parts[1] === 'params') { + addParam(parts[2], { source: 'path' }); + } + if (parts.length >= 4 && parts[0] === 'ctx' && parts[1] === 'request' && parts[2] === 'body') { + addParam(parts[3], { source: 'body' }); + } + } + }); + + for (const f of listFields) { + addParam(f, { source: 'body' }); + } + + const result = Array.from(entries.values()).map(item => ({ + name: item.name, + type: item.type, + required: item.required, + source: item.source.size ? Array.from(item.source).sort().join('|') : 'body', + description: `${item.name} 参数`, + })); + + result.sort((a, b) => { + if (a.required !== b.required) return a.required ? -1 : 1; + return a.name.localeCompare(b.name); + }); + + return result; +} + +function buildMethodParamMap() { + const map = new Map(); + const files = walkFiles(methodsDir); + + for (const file of files) { + const source = fs.readFileSync(file, 'utf8'); + const ast = acorn.parse(source, { ecmaVersion: 'latest', sourceType: 'script' }); + const relative = path.relative(methodsDir, file).replace(/\\/g, '/').replace(/\.js$/, ''); + const moduleName = relative.replace(/\//g, '.'); + + for (const node of ast.body) { + if (node.type !== 'ClassDeclaration') continue; + const noNeed = extractNoNeedLists(node); + for (const method of node.body.body) { + if (method.type !== 'MethodDefinition') continue; + if (method.kind !== 'method') continue; + if (!method.value.async) continue; + const methodName = method.key && method.key.name; + if (!methodName) continue; + + const fullMethod = `${moduleName}.${methodName}`; + const params = collectMethodParams(method); + + for (const p of params) { + if (noNeed.noNeedLogin.includes('*') || noNeed.noNeedLogin.includes(methodName)) { + if (p.name.toLowerCase().includes('authorization') || p.source === 'header') p.required = false; + } + } + + map.set(fullMethod, params); + } + } + } + + return map; +} + +const methodParamMap = buildMethodParamMap(); +const doc = JSON.parse(fs.readFileSync(jsonPath, 'utf8')); + +let updated = 0; +for (const group of doc.methods.groups || []) { + for (const item of group.list || []) { + const next = methodParamMap.get(item.method) || []; + item.params = next; + updated++; + } +} + +doc.version = '0.3.0'; +doc.updatedAt = '2026-03-22'; + +fs.writeFileSync(jsonPath, JSON.stringify(doc, null, 2) + '\n', 'utf8'); +console.log(`updated methods: ${updated}`); +console.log(`mapped methods: ${methodParamMap.size}`); diff --git a/script/tmp-update-ai-method-routing.cjs b/script/tmp-update-ai-method-routing.cjs new file mode 100644 index 0000000..b05fc89 --- /dev/null +++ b/script/tmp-update-ai-method-routing.cjs @@ -0,0 +1,30 @@ +const fs = require('fs'); +const path = require('path'); + +const root = process.cwd(); +const target = path.join(root, 'AI_METHOD_ROUTING.md'); +const inventoryPath = path.join(root, 'tmp-service-method-inventory.md'); + +const base = fs.readFileSync(target, 'utf8'); +const inventory = fs.readFileSync(inventoryPath, 'utf8').trim(); + +const section = `\n\n## 6. 全量 Service Method 能力清单(自动扫描)\n\n维护说明:\n- 扫描范围:app/service/**/*.js\n- 本节内容由脚本生成,新增/修改 service 后请同步刷新。\n- 刷新命令:node .\\script\\tmp-gen-service-method-inventory.cjs\n\n\n${inventory}\n\n`; + +const begin = ''; +const end = ''; + +let next; +if (base.includes(begin) && base.includes(end)) { + const start = base.indexOf(begin); + const finish = base.indexOf(end) + end.length; + const head = base.slice(0, base.lastIndexOf('\n## 6. 全量 Service Method 能力清单(自动扫描)', start) >= 0 + ? base.lastIndexOf('\n## 6. 全量 Service Method 能力清单(自动扫描)', start) + : start); + const tail = base.slice(finish); + next = head.trimEnd() + section + tail; +} else { + next = base.trimEnd() + section; +} + +fs.writeFileSync(target, next + '\n', 'utf8'); +console.log('UPDATED AI_METHOD_ROUTING.md'); diff --git a/tmp-order-schema-compare.json b/tmp-order-schema-compare.json new file mode 100644 index 0000000..e3f3f41 --- /dev/null +++ b/tmp-order-schema-compare.json @@ -0,0 +1,1610 @@ +{ + "generatedAt": "2026-03-22T06:08:48.627Z", + "dbName": "wms", + "tables": [ + "wms_entry_order", + "wms_order_delivery", + "wms_order_delivery_100000", + "wms_order_items", + "wms_order_items_100000" + ], + "compareWithModel": [ + { + "table": "wms_order_delivery", + "modelFile": "app/model/order_delivery.js", + "modelFieldCount": 72, + "dbFieldCount": 54, + "modelOnly": [ + "from_key", + "items", + "items_count", + "items_total", + "items_weight", + "items_hash", + "items_crc", + "wave_id", + "post_status", + "storage_status", + "pick_status", + "pack_status", + "inspection_status", + "print_status", + "claim_status", + "outbound_status", + "lock_status", + "intercept_status" + ], + "dbOnly": [], + "allMatched": false + }, + { + "table": "wms_order_items", + "modelFile": "app/model/order_items.js", + "modelFieldCount": 18, + "dbFieldCount": 15, + "modelOnly": [ + "stock_id", + "created_at", + "updated_at" + ], + "dbOnly": [], + "allMatched": false + }, + { + "table": "wms_entry_order", + "modelFile": "app/model/entry_order.js", + "modelFieldCount": 28, + "dbFieldCount": 28, + "modelOnly": [], + "dbOnly": [], + "allMatched": true + } + ], + "dynamicTableCheck": [ + { + "table": "wms_order_delivery_100000", + "baseTable": "wms_order_delivery", + "missingFromDynamic": [], + "extraInDynamic": [ + "from_key", + "items", + "items_count", + "items_total", + "items_weight", + "items_hash", + "items_crc", + "wave_id", + "post_status", + "storage_status", + "pick_status", + "pack_status", + "inspection_status", + "print_status", + "claim_status", + "outbound_status", + "lock_status", + "intercept_status" + ], + "allMatched": false + }, + { + "table": "wms_order_items_100000", + "baseTable": "wms_order_items", + "missingFromDynamic": [], + "extraInDynamic": [ + "stock_id", + "created_at", + "updated_at" + ], + "allMatched": false + } + ], + "schema": { + "wms_entry_order": [ + { + "COLUMN_NAME": "id", + "COLUMN_TYPE": "bigint(20) unsigned", + "IS_NULLABLE": "NO", + "COLUMN_DEFAULT": null, + "EXTRA": "auto_increment", + "COLUMN_KEY": "PRI" + }, + { + "COLUMN_NAME": "entry_order_code", + "COLUMN_TYPE": "varchar(50)", + "IS_NULLABLE": "NO", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "MUL" + }, + { + "COLUMN_NAME": "order_type", + "COLUMN_TYPE": "enum('SCRK','LYRK','CCRK','CGRK','DBRK','QTRK','B2BRK','XNRK')", + "IS_NULLABLE": "NO", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "MUL" + }, + { + "COLUMN_NAME": "purchase_order_code", + "COLUMN_TYPE": "varchar(50)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "total_order_lines", + "COLUMN_TYPE": "int(11)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": "0", + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "order_create_time", + "COLUMN_TYPE": "datetime", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "MUL" + }, + { + "COLUMN_NAME": "expect_start_time", + "COLUMN_TYPE": "datetime", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "expect_end_time", + "COLUMN_TYPE": "datetime", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "logistics_code", + "COLUMN_TYPE": "varchar(50)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "logistics_name", + "COLUMN_TYPE": "varchar(200)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "express_code", + "COLUMN_TYPE": "varchar(50)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "supplier_code", + "COLUMN_TYPE": "varchar(50)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "supplier_name", + "COLUMN_TYPE": "varchar(200)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "source_type", + "COLUMN_TYPE": "enum('WMS','API','QM')", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": "API", + "EXTRA": "", + "COLUMN_KEY": "MUL" + }, + { + "COLUMN_NAME": "order_status", + "COLUMN_TYPE": "enum('PENDING','CONFIRMED','PARTIAL_RECEIVED','COMPLETED','CANCELLED','CREATED','CREATING')", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": "PENDING", + "EXTRA": "", + "COLUMN_KEY": "MUL" + }, + { + "COLUMN_NAME": "sync_status", + "COLUMN_TYPE": "enum('PENDING','SUCCESS','FAILED')", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": "PENDING", + "EXTRA": "", + "COLUMN_KEY": "MUL" + }, + { + "COLUMN_NAME": "sync_message", + "COLUMN_TYPE": "text", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "is_enabled", + "COLUMN_TYPE": "tinyint(1)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": "1", + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "created_at", + "COLUMN_TYPE": "timestamp", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": "CURRENT_TIMESTAMP", + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "updated_at", + "COLUMN_TYPE": "timestamp", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": "CURRENT_TIMESTAMP", + "EXTRA": "on update CURRENT_TIMESTAMP", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "warehouse_id", + "COLUMN_TYPE": "bigint(20) unsigned", + "IS_NULLABLE": "NO", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "MUL" + }, + { + "COLUMN_NAME": "store_id", + "COLUMN_TYPE": "bigint(20) unsigned", + "IS_NULLABLE": "NO", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "MUL" + }, + { + "COLUMN_NAME": "remark", + "COLUMN_TYPE": "varchar(500)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "store_name", + "COLUMN_TYPE": "varchar(200)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "warehouse_name", + "COLUMN_TYPE": "varchar(200)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "deleted_at", + "COLUMN_TYPE": "datetime", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "qimen_owner_code", + "COLUMN_TYPE": "varchar(100)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "qimen_warehouse_code", + "COLUMN_TYPE": "varchar(100)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + } + ], + "wms_order_delivery": [ + { + "COLUMN_NAME": "id", + "COLUMN_TYPE": "bigint(20) unsigned", + "IS_NULLABLE": "NO", + "COLUMN_DEFAULT": null, + "EXTRA": "auto_increment", + "COLUMN_KEY": "PRI" + }, + { + "COLUMN_NAME": "delivery_order_code", + "COLUMN_TYPE": "varchar(50)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "MUL" + }, + { + "COLUMN_NAME": "pre_delivery_order_code", + "COLUMN_TYPE": "varchar(50)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "pre_delivery_order_id", + "COLUMN_TYPE": "varchar(50)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "order_type", + "COLUMN_TYPE": "varchar(50)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "warehouse_code", + "COLUMN_TYPE": "varchar(50)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "order_flag", + "COLUMN_TYPE": "varchar(200)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "source_platform_code", + "COLUMN_TYPE": "varchar(50)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "source_platform_name", + "COLUMN_TYPE": "varchar(200)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "create_at", + "COLUMN_TYPE": "datetime", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "delete_at", + "COLUMN_TYPE": "datetime", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "updated_at", + "COLUMN_TYPE": "datetime", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "place_order_time", + "COLUMN_TYPE": "datetime", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "pay_time", + "COLUMN_TYPE": "datetime", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "pay_no", + "COLUMN_TYPE": "varchar(50)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "service_code", + "COLUMN_TYPE": "varchar(50)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "operator_name", + "COLUMN_TYPE": "varchar(50)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "operate_time", + "COLUMN_TYPE": "datetime", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "delivery_time", + "COLUMN_TYPE": "datetime", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "shop_nick", + "COLUMN_TYPE": "varchar(200)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "seller_nick", + "COLUMN_TYPE": "varchar(200)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "buyer_nick", + "COLUMN_TYPE": "varchar(200)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "total_amount", + "COLUMN_TYPE": "decimal(18,2)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "item_amount", + "COLUMN_TYPE": "decimal(18,2)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "discount_amount", + "COLUMN_TYPE": "decimal(18,2)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "freight", + "COLUMN_TYPE": "decimal(18,2)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "ar_amount", + "COLUMN_TYPE": "decimal(18,2)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "got_amount", + "COLUMN_TYPE": "decimal(18,2)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "service_fee", + "COLUMN_TYPE": "decimal(18,2)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "logistics_code", + "COLUMN_TYPE": "varchar(50)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "logistics_name", + "COLUMN_TYPE": "varchar(200)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "express_code", + "COLUMN_TYPE": "varchar(50)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "logistics_area_code", + "COLUMN_TYPE": "varchar(50)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "delivery_type", + "COLUMN_TYPE": "varchar(255)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "is_urgency", + "COLUMN_TYPE": "enum('Y','N')", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": "N", + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "invoice_flag", + "COLUMN_TYPE": "enum('Y','N')", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": "N", + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "status", + "COLUMN_TYPE": "enum('pedding','created','cancel','intercepting','intercepted')", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": "pedding", + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "name", + "COLUMN_TYPE": "text", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "zip_code", + "COLUMN_TYPE": "varchar(50)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": "", + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "tel", + "COLUMN_TYPE": "text", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "mobile", + "COLUMN_TYPE": "text", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "email", + "COLUMN_TYPE": "text", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "country_code", + "COLUMN_TYPE": "varchar(255)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "province", + "COLUMN_TYPE": "varchar(255)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "city", + "COLUMN_TYPE": "varchar(255)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "area", + "COLUMN_TYPE": "varchar(255)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "town", + "COLUMN_TYPE": "varchar(255)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "detail_address", + "COLUMN_TYPE": "varchar(255)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "id_type", + "COLUMN_TYPE": "varchar(255)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "id_number", + "COLUMN_TYPE": "int(11)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "oaid", + "COLUMN_TYPE": "text", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "sync_status", + "COLUMN_TYPE": "enum('padding','fin','error')", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": "padding", + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "store_id", + "COLUMN_TYPE": "bigint(20) unsigned", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "MUL" + }, + { + "COLUMN_NAME": "warehouse_id", + "COLUMN_TYPE": "bigint(20) unsigned", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "MUL" + } + ], + "wms_order_delivery_100000": [ + { + "COLUMN_NAME": "id", + "COLUMN_TYPE": "bigint(20) unsigned", + "IS_NULLABLE": "NO", + "COLUMN_DEFAULT": null, + "EXTRA": "auto_increment", + "COLUMN_KEY": "PRI" + }, + { + "COLUMN_NAME": "delivery_order_code", + "COLUMN_TYPE": "varchar(50)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "MUL" + }, + { + "COLUMN_NAME": "pre_delivery_order_code", + "COLUMN_TYPE": "varchar(50)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "pre_delivery_order_id", + "COLUMN_TYPE": "varchar(50)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "order_type", + "COLUMN_TYPE": "varchar(50)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "warehouse_code", + "COLUMN_TYPE": "varchar(50)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "order_flag", + "COLUMN_TYPE": "varchar(200)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "source_platform_code", + "COLUMN_TYPE": "varchar(50)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "source_platform_name", + "COLUMN_TYPE": "varchar(200)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "create_at", + "COLUMN_TYPE": "datetime", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "delete_at", + "COLUMN_TYPE": "datetime", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "updated_at", + "COLUMN_TYPE": "datetime", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "place_order_time", + "COLUMN_TYPE": "datetime", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "pay_time", + "COLUMN_TYPE": "datetime", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "pay_no", + "COLUMN_TYPE": "varchar(50)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "service_code", + "COLUMN_TYPE": "varchar(50)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "operator_name", + "COLUMN_TYPE": "varchar(50)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "operate_time", + "COLUMN_TYPE": "datetime", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "delivery_time", + "COLUMN_TYPE": "datetime", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "shop_nick", + "COLUMN_TYPE": "varchar(200)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "seller_nick", + "COLUMN_TYPE": "varchar(200)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "buyer_nick", + "COLUMN_TYPE": "varchar(200)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "total_amount", + "COLUMN_TYPE": "decimal(18,2)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "item_amount", + "COLUMN_TYPE": "decimal(18,2)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "discount_amount", + "COLUMN_TYPE": "decimal(18,2)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "freight", + "COLUMN_TYPE": "decimal(18,2)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "ar_amount", + "COLUMN_TYPE": "decimal(18,2)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "got_amount", + "COLUMN_TYPE": "decimal(18,2)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "service_fee", + "COLUMN_TYPE": "decimal(18,2)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "logistics_code", + "COLUMN_TYPE": "varchar(50)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "logistics_name", + "COLUMN_TYPE": "varchar(200)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "express_code", + "COLUMN_TYPE": "varchar(50)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "logistics_area_code", + "COLUMN_TYPE": "varchar(50)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "delivery_type", + "COLUMN_TYPE": "varchar(255)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "is_urgency", + "COLUMN_TYPE": "enum('Y','N')", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": "N", + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "invoice_flag", + "COLUMN_TYPE": "enum('Y','N')", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": "N", + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "status", + "COLUMN_TYPE": "enum('pedding','created','cancel','error','after-sales-error')", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": "created", + "EXTRA": "", + "COLUMN_KEY": "MUL" + }, + { + "COLUMN_NAME": "name", + "COLUMN_TYPE": "text", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "zip_code", + "COLUMN_TYPE": "varchar(50)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "tel", + "COLUMN_TYPE": "text", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "mobile", + "COLUMN_TYPE": "text", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "email", + "COLUMN_TYPE": "text", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "country_code", + "COLUMN_TYPE": "varchar(255)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "province", + "COLUMN_TYPE": "varchar(255)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "city", + "COLUMN_TYPE": "varchar(255)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "area", + "COLUMN_TYPE": "varchar(255)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "town", + "COLUMN_TYPE": "varchar(255)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "detail_address", + "COLUMN_TYPE": "varchar(255)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "id_type", + "COLUMN_TYPE": "varchar(255)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "id_number", + "COLUMN_TYPE": "int(11)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "oaid", + "COLUMN_TYPE": "text", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "sync_status", + "COLUMN_TYPE": "enum('padding','fin','error','none')", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": "padding", + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "store_id", + "COLUMN_TYPE": "bigint(20) unsigned", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "MUL" + }, + { + "COLUMN_NAME": "warehouse_id", + "COLUMN_TYPE": "bigint(20) unsigned", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "MUL" + }, + { + "COLUMN_NAME": "from_key", + "COLUMN_TYPE": "int(11)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "items", + "COLUMN_TYPE": "text", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "MUL" + }, + { + "COLUMN_NAME": "items_count", + "COLUMN_TYPE": "smallint(5) unsigned", + "IS_NULLABLE": "NO", + "COLUMN_DEFAULT": "0", + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "items_total", + "COLUMN_TYPE": "int(10) unsigned", + "IS_NULLABLE": "NO", + "COLUMN_DEFAULT": "0", + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "items_weight", + "COLUMN_TYPE": "decimal(10,2)", + "IS_NULLABLE": "NO", + "COLUMN_DEFAULT": "0.00", + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "items_hash", + "COLUMN_TYPE": "char(32)", + "IS_NULLABLE": "NO", + "COLUMN_DEFAULT": "", + "EXTRA": "", + "COLUMN_KEY": "MUL" + }, + { + "COLUMN_NAME": "items_crc", + "COLUMN_TYPE": "int(10) unsigned", + "IS_NULLABLE": "NO", + "COLUMN_DEFAULT": "0", + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "wave_id", + "COLUMN_TYPE": "bigint(20)", + "IS_NULLABLE": "NO", + "COLUMN_DEFAULT": "0", + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "post_status", + "COLUMN_TYPE": "enum('padding','fin','timeout','error','none')", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": "none", + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "storage_status", + "COLUMN_TYPE": "enum('padding','fin','error','none')", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": "none", + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "pick_status", + "COLUMN_TYPE": "enum('padding','fin','error','none')", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": "none", + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "pack_status", + "COLUMN_TYPE": "enum('none','padding','fin','error')", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": "none", + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "inspection_status", + "COLUMN_TYPE": "enum('none','padding','running','fin','error')", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": "none", + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "print_status", + "COLUMN_TYPE": "enum('none','padding','fin','error')", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": "none", + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "claim_status", + "COLUMN_TYPE": "enum('none','padding','fin','error')", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": "none", + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "outbound_status", + "COLUMN_TYPE": "enum('none','padding','fin','error')", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": "none", + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "lock_status", + "COLUMN_TYPE": "enum('none','warehouse','store')", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": "none", + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "intercept_status", + "COLUMN_TYPE": "enum('none','requesting','requested','intercepting','intercepted_in_transit','intercepted_at_warehouse','returning','returned','delivered_by_mistake','timeout','cancelled','failed','exception')", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": "none", + "EXTRA": "", + "COLUMN_KEY": "" + } + ], + "wms_order_items": [ + { + "COLUMN_NAME": "id", + "COLUMN_TYPE": "bigint(20) unsigned", + "IS_NULLABLE": "NO", + "COLUMN_DEFAULT": null, + "EXTRA": "auto_increment", + "COLUMN_KEY": "PRI" + }, + { + "COLUMN_NAME": "order_id", + "COLUMN_TYPE": "bigint(20) unsigned", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "MUL" + }, + { + "COLUMN_NAME": "actual_price", + "COLUMN_TYPE": "decimal(18,2)", + "IS_NULLABLE": "NO", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "retail_price", + "COLUMN_TYPE": "decimal(18,2)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "ext_code", + "COLUMN_TYPE": "varchar(50)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "inventory_type", + "COLUMN_TYPE": "varchar(50)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "item_code", + "COLUMN_TYPE": "varchar(50)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "item_id", + "COLUMN_TYPE": "bigint(20) unsigned", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "item_name", + "COLUMN_TYPE": "varchar(200)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "order_line_no", + "COLUMN_TYPE": "varchar(50)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "owner_code", + "COLUMN_TYPE": "varchar(50)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "plan_qty", + "COLUMN_TYPE": "int(11)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "source_order_code", + "COLUMN_TYPE": "varchar(50)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "sub_source_order_code", + "COLUMN_TYPE": "varchar(50)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "extend_props", + "COLUMN_TYPE": "text", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + } + ], + "wms_order_items_100000": [ + { + "COLUMN_NAME": "id", + "COLUMN_TYPE": "bigint(20) unsigned", + "IS_NULLABLE": "NO", + "COLUMN_DEFAULT": null, + "EXTRA": "auto_increment", + "COLUMN_KEY": "PRI" + }, + { + "COLUMN_NAME": "order_id", + "COLUMN_TYPE": "bigint(20) unsigned", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "MUL" + }, + { + "COLUMN_NAME": "actual_price", + "COLUMN_TYPE": "decimal(18,2)", + "IS_NULLABLE": "NO", + "COLUMN_DEFAULT": "0.00", + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "retail_price", + "COLUMN_TYPE": "decimal(18,2)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "ext_code", + "COLUMN_TYPE": "varchar(50)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "inventory_type", + "COLUMN_TYPE": "varchar(50)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "item_code", + "COLUMN_TYPE": "varchar(50)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "MUL" + }, + { + "COLUMN_NAME": "item_id", + "COLUMN_TYPE": "bigint(20)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "MUL" + }, + { + "COLUMN_NAME": "item_name", + "COLUMN_TYPE": "varchar(200)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "order_line_no", + "COLUMN_TYPE": "varchar(50)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "owner_code", + "COLUMN_TYPE": "varchar(50)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "MUL" + }, + { + "COLUMN_NAME": "plan_qty", + "COLUMN_TYPE": "int(11)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "source_order_code", + "COLUMN_TYPE": "varchar(50)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "MUL" + }, + { + "COLUMN_NAME": "sub_source_order_code", + "COLUMN_TYPE": "varchar(50)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "extend_props", + "COLUMN_TYPE": "json", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "" + }, + { + "COLUMN_NAME": "stock_id", + "COLUMN_TYPE": "bigint(20)", + "IS_NULLABLE": "YES", + "COLUMN_DEFAULT": null, + "EXTRA": "", + "COLUMN_KEY": "MUL" + }, + { + "COLUMN_NAME": "created_at", + "COLUMN_TYPE": "datetime", + "IS_NULLABLE": "NO", + "COLUMN_DEFAULT": "CURRENT_TIMESTAMP", + "EXTRA": "", + "COLUMN_KEY": "MUL" + }, + { + "COLUMN_NAME": "updated_at", + "COLUMN_TYPE": "datetime", + "IS_NULLABLE": "NO", + "COLUMN_DEFAULT": "CURRENT_TIMESTAMP", + "EXTRA": "on update CURRENT_TIMESTAMP", + "COLUMN_KEY": "" + } + ] + } +} \ No newline at end of file diff --git a/tmp-order-schema-workflow.md b/tmp-order-schema-workflow.md new file mode 100644 index 0000000..16963db --- /dev/null +++ b/tmp-order-schema-workflow.md @@ -0,0 +1,81 @@ +# 订单表结构与 Model 比对临时工作流 + +更新时间: 2026-03-22 + +## 1. 目标 + +用于后续排查订单相关问题时,快速复用以下能力: +- 获取数据库订单表结构 +- 与当前 Model 做字段级比对 +- 识别主表/分仓动态表的结构漂移 + +## 2. 本次已确认的订单相关表 + +- wms_entry_order +- wms_order_delivery +- wms_order_delivery_100000 +- wms_order_items +- wms_order_items_100000 + +## 3. 相关 Model + +- app/model/entry_order.js +- app/model/order_delivery.js +- app/model/order_items.js +- app/model/order_delivery_factory.js +- app/model/order_items_factory.js + +## 4. 已生成产物 + +- 结构与差异总结果: tmp-order-schema-compare.json +- 比对脚本(可复跑): script/tmp-compare-order-schema.cjs + +## 5. 关键比对结论 + +### 5.1 wms_entry_order vs entry_order model +- 字段数: model 28 / db 28 +- 结论: 完全一致 + +### 5.2 wms_order_delivery vs order_delivery model +- 字段数: model 72 / db 54 +- model 有但主表 db 没有的字段: + from_key, items, items_count, items_total, items_weight, items_hash, items_crc, wave_id, + post_status, storage_status, pick_status, pack_status, inspection_status, print_status, + claim_status, outbound_status, lock_status, intercept_status +- 结论: 主表结构落后于模型定义 + +补充: +- delivery_time(发货时间) 已在主表与动态表补齐,并同步到 model 与动态建表 SQL。 + +### 5.3 wms_order_items vs order_items model +- 字段数: model 18 / db 15 +- model 有但主表 db 没有的字段: + stock_id, created_at, updated_at +- 结论: 主表结构落后于模型定义 + +### 5.4 动态表 vs 主表 +- wms_order_delivery_100000 相比 wms_order_delivery 多出 18 个字段(与 modelOnly 一致) +- wms_order_items_100000 相比 wms_order_items 多出 3 个字段(与 modelOnly 一致) +- 结论: 动态表更接近当前模型,主表较旧 + +## 6. 复用命令 + +### 6.1 一键重跑比对 +PowerShell: + +node .\script\tmp-compare-order-schema.cjs + +### 6.2 快速查看结果摘要 +PowerShell: + +Get-Content .\tmp-order-schema-compare.json -TotalCount 160 + +## 7. 后续建议 + +1. 若以主表为准,需回退 model 字段定义到主表现状,避免 ORM 读写异常。 +2. 若以模型为准,补充 migration,将主表补齐到动态表同等结构。 +3. 在服务中明确当前读写表策略(主表或动态表),避免混用导致字段可用性不一致。 + +## 8. 备注 + +本文件为临时工作流文件,可在结构收敛后删除或迁移到正式文档。 \ No newline at end of file diff --git a/tmp-service-method-inventory.md b/tmp-service-method-inventory.md new file mode 100644 index 0000000..22fda06 --- /dev/null +++ b/tmp-service-method-inventory.md @@ -0,0 +1,105 @@ +自动生成时间: 2026-03-22T06:43:50.263Z + +扫描范围: app/service/**/*.js +文件数: 50 + +- app/service/api.js (1) + - callMethod +- app/service/apiMethods/test.js (4) + - entryorderConfirm, playbackRequest, fibonacci, fibonacciRecursive +- app/service/dispatcher.js (3) + - buildMap, getMethodMap, invoke +- app/service/main.js (11) + - success, fail, normalizeDate, setInfo, getInfo, findQimenAppWithContract, queryFromDatabase, checkAuth, checkApiPermission, setUserContext, systemInit +- app/service/pda.js (3) + - callMethod, validateParams, saveLog +- app/service/qimen.js (12) + - validateApi, getErpName, parseXmlToArray, cleanXmlString, callMethod, formatResponse, xmlResponse, buildXmlNode, escapeXml, saveQimenLog, saveQimenLogResult, saveQimenLogBody +- app/service/qimenMethods/deliveryorder.js (3) + - query, create, batchcreate +- app/service/qimenMethods/entryorder.js (2) + - create, query +- app/service/qimenMethods/inventory.js (1) + - query +- app/service/qimenMethods/order.js (2) + - cancel, pending +- app/service/qimenMethods/returnorder.js (2) + - create, query +- app/service/qimenMethods/singleitem.js (2) + - synchronize, query +- app/service/qimenMethods/stockout.js (2) + - create, query +- app/service/qimenMethods/taobao/qimen/service.js (1) + - heartbeat +- app/service/system.js (3) + - callMethod, validateParams, saveLog +- app/service/systemMethods/config.js (1) + - list +- app/service/systemMethods/dashboard.js (6) + - storeStats, warehouseStats, hot_order_rank, express_ratio, platform_distribution, order_trend +- app/service/systemMethods/index.js (13) + - fastWhereTree, loadStores, getCOSUploadConfig, getImages, uploadSuccessNotify, ReferenceFile, getMessageDetail, getI18nMessage, putI18nCollect, extractModule, tryAutoTranslateNewKeys, searchSpace, getExpressList +- app/service/systemMethods/order.js (11) + - getWarehouseId, getOrderModels, applyDateRange, buildWhere, parseDateTime, list, detail, listItems, stats, updateStatus, updateDeliveryTime +- app/service/systemMethods/print.js (3) + - send, sendToComputer, log +- app/service/systemMethods/printer/station.js (1) + - list +- app/service/systemMethods/setting/printTemplate.js (3) + - list, save, listTemplatesByType +- app/service/systemMethods/stock.js (21) + - stockWarehouse, getProhibitedType, getInfo, saveWarehouseStock, createWarehouseStock, getBarcodes, saveWarehouseStockBarcode, getStoreStocks, bindItem, unbindItem, checkItemCodeUnique, queryStockLogs, handleBatchDelete, deleteUnit, deleteProhibited, handleBatchChange, getStockUnits, getUnitList, createProhibited, createUnit, search +- app/service/systemMethods/storage/receiving.js (13) + - getReceivingList, getReceivingDetail, batchCancelReceiving, create, addItem, removeItem, saveReceiving, get, addDetail, deleteDetail, detailChange, cancel, completeReceiving +- app/service/systemMethods/store.js (6) + - createStore, createWarehouse, joinStore, joinWarehouse, getStoreRoles, auditApply +- app/service/systemMethods/user.js (5) + - login, logout, info, changeRole, register +- app/service/systemMethods/warehouse.js (20) + - getWarehouseZones, getWarehouseTree, getChildren, create, update, delete, detail, checkBarcodeUnique, toggleActive, getPath, createRack, getPickPath, updateRackPosition, recalculatePickPath, updateNeighbors, getAreaRacks, getSpacesByRack, createRackWithSpaces, getSpaceInfo, updateSpaceInfo +- app/service/systems/account_platform.js (8) + - switchActiveRole, getActiveRoleByPlatform, getMultiplePlatformActiveRoles, getAllPlatformActives, clearPlatformActive, clearPlatformCache, getAvailableRoles, getCurrentContext +- app/service/systems/auth/user.js (21) + - login, ID, changeRole, info, getRoles, findById, setUserCache, getAvatarByEmployeeId, clearUserCache, clearRelatedCache, getPermissions, getMenus, convertToRoutes, findUserByIdentifier, checkUserStatus, verifyPassword, encryptPassword, generateSalt, updateLastLoginTime, ensurePlatformActiveRole, register +- app/service/systems/delivery_order.js (7) + - addOrder, generateItemsHash, calculateCRC32, prepareOrderData, addOrderLines, safeParseFloat, addOrderToQueue +- app/service/systems/entry_order.js (9) + - addOrder, getLineCount, received, success, fail, tryCreateEntryOrder, addItems, qimenEntryorderConfirm, entryorderConfirm +- app/service/systems/fast_where.js (13) + - buildTree, getTreeByType, buildSubTree, getWithChildrenByType, getAllChildren, getByType, getGroups, getChildrenByPid, getTreeChildrenByPid, create, update, findById, delete +- app/service/systems/file.js (2) + - getImages, ReferenceFile +- app/service/systems/location_space.js (16) + - create, batchCreate, list, detail, update, delete, toggleStatus, updateStatus, findAvailableSpaces, findByCode, findByBarcode, getWarehouseStats, getZoneStats, validateAllocation, validateTransferOut, _validateReferences +- app/service/systems/location_zone.js (22) + - getWarehouseLevelZones, getZoneTreeByWarehouse, getChildrenByZoneId, isLeafNode, createZone, validateBasicFields, validateByZoneType, validateParentElement, validateZoneOverlap, isOverlap, generateZoneCodeByType, getDefaultColorByType, getZoneTypeText, updateZone, deleteZone, checkZoneOverlap, getZoneDetail, toggleZoneActive, getZonePath, generateSpacesForRack, getSpaceInfo, checkBarcodeUnique +- app/service/systems/location.js (10) + - createRackWithSpaces, _generateSpacesForRack, _calculateAreaRackOrder, _calculatePickPathForWarehouse, _updateSpacePickSequence, _calculatePickPriority, updateRackPosition, getPickPath, updateNeighborRelations, _findNeighborRacks +- app/service/systems/notification.js (1) + - send +- app/service/systems/operation_log.js (4) + - createOperationLog, queryStockLogs, queryOrderLogs, getMessageDetail +- app/service/systems/platform.js (6) + - checkPlatformExists, getPlatformInfo, clearPlatformCache, getPlatformSettingDetail, batchCheckPlatforms, createPlatformSetting +- app/service/systems/polo_api.js (6) + - getJsonDatas, getJsonData, getSignText, md5Encrypt, _formatDate, _formatPickupDate +- app/service/systems/print/index.js (2) + - sendToComputer, test +- app/service/systems/qimen_query.js (6) + - send, replaceXmlTagsWithString, addSign, getQueryParams, generateUrlWithParams, sendRequest +- app/service/systems/setting/print_template.js (14) + - listTemplatesByType, getTree, getTemplatesByType, save, getBusinessTypesAndItem, getGroupedPrintItems, getTableConfigs, clearBusinessTypesCache, getXmlByTemplate, buildXmlFromElements, renderElement, computeItemStyle, computeTableItemStyle, renderTable +- app/service/systems/sign.js (10) + - Constants, toXml, signTopRequest, verifyTopRequest, verifyAndExtractParams, generateSignedParams, encryptHMAC, encryptHMACSHA256, encryptMD5, byte2hex +- app/service/systems/space.js (1) + - searchSpace +- app/service/systems/stock_store.js (34) + - create, initQimenStockData, convertToQimenFormat, getItemInfoWithCache, getItemStorages, _calculateCacheTTL, clearItemStorageCache, lockItemStorages, ID, inbound, outbound, checkAndCreateWarehouseStock, getWarehouseStock, buildSequelizeCondition, processConditionValue, formatDate, isEmptyValue, getProhibitedType, getBarcodes, handleBatchChange, saveWarehouseStockBarcode, getStoreStocks, bindItem, unbindItem, getInfo, saveWarehouseStock, createWarehouseStock, validateSaveParams, stockLog, checkItemCodeUnique, handleBatchDelete, deleteUnit, deleteProhibited, search +- app/service/systems/storage/index.js (1) + - index +- app/service/systems/storage/receiving.js (16) + - getReceivingList, getReceivingDetail, batchCancelReceiving, isEmptyValue, buildSequelizeCondition, processConditionValue, create, get, addDetail, updateDetail, getStockStoreInfo, updateReceivingStats, deleteDetail, detailChange, invalid, completeReceiving +- app/service/systems/store.js (13) + - getStoreName, getStoreRemaskName, createStore, createWarehouse, joinStore, joinWarehouse, assignAdminRoleToCreator, generateJoinToken, sendNotification, sendNotificationToAdmins, getStoreRoles, auditApply, loadStores +- app/service/systems/upload.js (14) + - initCOS, getUploadParams, hash_hmac, validateFileInfo, generateFileName, parseSizeToBytes, formatFileSize, getFrontendConfig, uploadFile, validateFile, uploadSuccessNotify, getMimeType, createFileReference, handleUploadCallback From 86dfc92551c62509df871891f521e03a1c843061 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sun, 22 Mar 2026 16:53:11 +0800 Subject: [PATCH 004/550] =?UTF-8?q?docs:=20=E6=9B=B4=E6=96=B0=20README=20?= =?UTF-8?q?=E4=B8=8E=20day.log?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 170 ++++++++++++++++++++++++++++++++---------------------- day.log | Bin 6188 -> 7538 bytes 2 files changed, 102 insertions(+), 68 deletions(-) diff --git a/README.md b/README.md index fef76b0..29bfd86 100644 --- a/README.md +++ b/README.md @@ -1,105 +1,139 @@ # 奇门WMS(qimen-wms) -基于 Egg.js 的仓储管理系统(WMS),支持多快递平台对接、订单管理、打印、权限、配置等功能,适合中小型电商、仓储企业二次开发。 +基于 Egg.js 的仓储管理系统(WMS),支持多快递平台对接、订单管理、打印、权限、配置等功能,适合中小型电商与仓储企业二次开发。 ---- +## 文档导航 -## 目录结构 +- 项目协作工具箱:`AI_TOOLBOX.md` +- Method 路由映射说明:`AI_METHOD_ROUTING.md` +- system 接口文档源:`methods/system.json` +- qimen 接口文档源:`methods/qimen.json` +- 日报:`day.log` -``` -├── app/ # 业务主目录(controller, service, model, router等) -│ ├── controller/ # 控制器(API、模板、认证等) -│ ├── service/ # 业务服务(含快手/PolyAPI、打印、系统等) -│ ├── model/ # Sequelize模型 +## 项目目录结构 + +```text +├── app/ # 业务主目录(controller, service, model, router 等) +│ ├── controller/ # 控制器(API、文档、模板、认证等) +│ ├── service/ # 业务服务(system/qimen/print 等) +│ ├── model/ # Sequelize 模型 │ ├── dict/ # 业务字典 │ ├── view/ # 前端模板 │ └── router.js # 路由定义 -├── config/ # 配置(含poloapi、redis、数据库等) -├── database/ # 数据库迁移与配置 -├── public/ # 静态资源 +├── config/ # 配置(poloapi、redis、数据库等) +├── database/ # 迁移与数据库配置 +├── methods/ # 接口文档数据源(JSON) +├── script/ # 调试与文档生成脚本 ├── logs/ # 日志 ├── run/ # 运行时/元数据 ├── test/ # 单元测试 -├── package.json # 依赖与脚本 ├── app.js # 应用入口 +├── package.json # 依赖与脚本 └── README.md # 项目说明 ``` -## 主要依赖 -- egg.js 3.x -- egg-sequelize、egg-mysql、egg-redis -- egg-jwt、egg-cors、egg-view-ejs -- fast-xml-parser、cos-js-sdk-v5、qiniu-js、soap +## 文档结构 + +- `README.md`:项目入口文档,提供整体说明与规范入口。 +- `AI_TOOLBOX.md`:AI/开发协作操作手册,包含脚本与工作流。 +- `AI_METHOD_ROUTING.md`:接口入口与 method 到代码文件的映射。 +- `methods/system.json`:system 接口定义(headers、groups、params、response、errors)。 +- `methods/qimen.json`:qimen 接口定义(按奇门协议组织)。 +- `day.log`:每日工作留痕。 ## 快速开始 ```bash npm install npm run dev -# 访问 http://localhost:6060/ ``` -## 启动与部署 +默认访问地址:`http://localhost:6060/` -开发环境: -```bash -npm run dev -``` -生产环境: -```bash -npm start -npm stop +## 运行命令 + +- `npm run dev`:本地开发 +- `npm start`:启动生产服务 +- `npm stop`:停止生产服务 +- `npm run lint`:代码风格检查 +- `npm test`:单元测试 + +## 主要依赖 + +- egg.js 3.x +- egg-sequelize、egg-mysql、egg-redis +- egg-jwt、egg-cors、egg-view-ejs +- fast-xml-parser、cos-js-sdk-v5、qiniu-js、soap + +## 接口入口 + +- `GET /`:健康检查 +- `POST /qimen`:奇门接口 +- `POST /system`:system 统一入口 +- `POST /api/v1`:旧版 API +- `POST /api/v2`:新版 API +- `GET /template/xml/:id`:打印模板 +- `GET|POST /auth/printSetting/:code`:打印台设置 + +## API 文档与调试 + +- `GET /api/docs`:默认文档页 +- `GET /api/docs/:docName`:按文档名查看(如 `system`、`qimen`) +- `GET /api/docs/:docName/raw`:查看原始 JSON + +文档页能力: + +- 分组折叠与 method 搜索 +- 全局 Authorization 设置 +- 全局业务 Header(如 `platform`、`project`)设置 +- 方法级在线 POST 调试 + +## 接口文档联动维护(强制) + +当出现以下任一变更时,必须同步更新 `methods` 下对应文档: + +1. 新增接口 method +2. 修改接口参数(新增/删除/重命名/必填变化) +3. 修改公共 Header(如 `platform`、`project`、`Authorization`) +4. 修改响应结构或错误码 + +建议流程: + +1. 先完成代码改动(controller/service/model) +2. 同步维护 `methods/system.json` 或 `methods/qimen.json` +3. system 参数改动后执行: + +```powershell +node .\script\tmp-struct-system-params.cjs ``` -## 常用 npm 脚本 -- `npm run lint` 代码风格检查 -- `npm test` 单元测试 -- `npm run dev` 本地开发 -- `npm start` 启动生产服务 +4. 补充自动提取无法覆盖的信息(description/response/errors/枚举约束) ## 配置说明 -- 主要配置文件在 `config/` 目录下(如 poloapi.js、config.default.js、config.local.js) -- 数据库、Redis、快手/PolyAPI等均可在对应文件中调整 -## 主要功能模块 -- 多快递平台对接(快手/PolyAPI等,详见 config/poloapi.js) -- 订单管理、打印、仓库/门店管理 -- 权限与角色、员工管理 -- API接口(RESTful风格,详见 app/router.js) -- 日志、配置、业务字典 +- 主要配置文件在 `config/`(如 `config.default.js`、`config.local.js`、`poloapi.js`) +- 数据库、Redis、平台配置在对应配置文件中维护 +- 敏感信息不要提交到仓库 -## 路由示例 -- `GET /` 首页/健康检查 -- `POST /qimen` 奇门接口 -- `POST /api/warehouse` 仓库API -- `POST /api/store` 门店API -- `POST /api/v1` 旧版API -- `POST /api/v2` 新版API -- `GET /template/xml/:id` 获取打印模板 -- `GET|POST /auth/printSetting/:code` 打印台设置 +## 功能模块 -## 开发建议 -- 业务字典已全局挂载(见 app.js) -- 所有服务建议继承 Egg Service,便于单元测试 -- 配置、密钥等敏感信息请勿提交到仓库 +- 多快递平台对接(快手/PolyAPI 等) +- 订单管理与履约 +- 打印与打印台管理 +- 仓库/门店管理 +- 权限与角色管理 ## 常见问题 -- 启动端口默认 6060,可在 `package.json` 或 `config` 中调整 -- 数据库/Redis 连接失败请检查 config.local.js -- 打印、快递API对接请参考 `app/service/systems/polo_api.js` 和 `config/poloapi.js` ---- - -如需二次开发或遇到问题,欢迎提 issue 或联系维护者。 - -[Egg.js 官方文档](https://eggjs.org) - -## AI 协作工具箱 - -- 见 `AI_TOOLBOX.md`,内含数据库调试脚本 `script/db-query.ps1` 的完整使用方法与 AI 提问模板。 -- 见 `AI_METHOD_ROUTING.md`,内含入口路由与 method 到代码文件的映射关系。 +- 启动端口默认 6060,可在配置中调整 +- 数据库/Redis 连接失败优先检查 `config/config.local.js` +- 接口路由映射可查阅 `AI_METHOD_ROUTING.md` ## 日报维护 -- 日报统一记录在 `day.log`。 -- 每次更新日报内容时,需同步更新 `day.log` 文件,确保项目内留痕一致。 +- 日报统一记录在 `day.log` +- 每次更新日报内容时,需同步更新 `day.log` + +## 参考 + +- Egg.js 官方文档:https://eggjs.org diff --git a/day.log b/day.log index f5f97845641408533f9ece5f51b2b0cda32c46df..9397589c81b7c9da944027e806e8caa91b15bda4 100644 GIT binary patch delta 1352 zcma)5Ur1A76hBiCS1LV7U}EN$4?;Hr3(OR~bN6bSY&v)EuDiOq>He8UyBR{p zHJpek7E%wU4?XzOYrPZ|L?vR+LM8p77Ag6VaXa7U^r}6C2zTFi&hMPxpYNgRC%sU1 zM9zf+K>ocJor!aP6vg3c%YxGE%vR4qBh&%~H$*|A;370Z1JvX1!(1LyVto?J99dTM zYP$a<-efr_(009MDC}`T5WL`q0Q7+$tC}5je+@Smqw%)R2^^S#!Q@rzs1trG?>Gv&L4+_!2(Erf=M_~%By1K`0E;@g~1$r?L~ zn`mbxTO^H4Q@Bn5ofYvmTm5&}S?B*=lNVuP$=i6W_+@&R ziM#8|QFmgC9LCl!gYztDrI~}wOI{!U%;%`Yj8qA!NZpc*T#&Si1aXO8h#(aCa%1KG zJyv`1l?sLz z>W6)!walh{eQ+ph?tXDox-`odOk}IInBgc&P1GO^1IU#^&VF3&GI}hc+u<$t;qBCu GxcvpFXk#P* delta 7 OcmexlwZ>qBjsyS>odW#; From 9ab060d223c69c892db28088831b903cf30c9f3e Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sun, 22 Mar 2026 17:12:47 +0800 Subject: [PATCH 005/550] =?UTF-8?q?docs:=20=E6=9B=B4=E6=96=B0=E6=97=A5?= =?UTF-8?q?=E6=8A=A5=E5=B9=B6=E5=88=9D=E5=A7=8B=E5=8C=96=20qimen=20?= =?UTF-8?q?=E6=8E=A5=E5=8F=A3=E6=96=87=E6=A1=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- AI_METHOD_ROUTING.md | 7 +- day.log | Bin 7538 -> 8768 bytes methods/qimen.json | 1168 ++++++++++++++++++++++++++++- script/tmp-init-qimen-methods.cjs | 194 +++++ tmp-service-method-inventory.md | 2 +- 5 files changed, 1361 insertions(+), 10 deletions(-) create mode 100644 script/tmp-init-qimen-methods.cjs diff --git a/AI_METHOD_ROUTING.md b/AI_METHOD_ROUTING.md index 654cf3f..f745d6b 100644 --- a/AI_METHOD_ROUTING.md +++ b/AI_METHOD_ROUTING.md @@ -113,7 +113,7 @@ rg "class .*Service|module.exports" app/service/qimenMethods - 刷新命令:node .\script\tmp-gen-service-method-inventory.cjs -自动生成时间: 2026-03-22T06:43:50.263Z +自动生成时间: 2026-03-22T09:03:11.802Z 扫描范围: app/service/**/*.js 文件数: 50 @@ -219,8 +219,3 @@ rg "class .*Service|module.exports" app/service/qimenMethods - app/service/systems/upload.js (14) - initCOS, getUploadParams, hash_hmac, validateFileInfo, generateFileName, parseSizeToBytes, formatFileSize, getFrontendConfig, uploadFile, validateFile, uploadSuccessNotify, getMimeType, createFileReference, handleUploadCallback - - - - - diff --git a/day.log b/day.log index 9397589c81b7c9da944027e806e8caa91b15bda4..07d220149ad62f572cdcf92ad8dfa656dcb37272 100644 GIT binary patch delta 1121 zcmbVMOK1~O6ulEsjGt7HRvM_Cl}NS8b5WEM1i|jwNt@|U(mHLXuag?nPV>Vc%wR3F zV8KQ3gGh^@`?zq?ortak6$;|cMG;p;DZz!Ccy7`%X$2QDyuA1BefQjR&b-NX_v@?W zOxwtDIzl|gHAU#gHz}8U2Fmw_jKkG=nxQmFnkAK%q?z=aDrKpNkwY|%Xe8NWw8h?E zYtjAHU7SwDakBKX`IM{DhO=mWcpOQt#7`tt+K*VT4c2P?#Fb^aIvTul-r`OsWx&8j zw=hN;t4{1^F>+XWSe-SNIZDzTO`$G?${Uz{Ck2zL1E&%n%>#EU!=-={jCi$uP~ugF zsRIxHhUy3n0HyoC2bSb7t(0j#)8(rrm~dUfhV#^Fl+m7NxtEad&<@4kI*PbJU8S{_ zcDK%k?PP1dI;3@LDg-d~JlzDHFjjJp{263t5icN~L1uTKhb2=q2>}xG70h9nAQ52% zJ{jI`O)FVQ%%PQybO;S+Fz3i8O6AtmF7r94pBq&7;V8leY6c^Xe2|t4bsBS1He zjs~Vxkdiy}xJadig?0N_wQ&8D`C0!vdsN#VccW+X?8jKNTkDUrlnK2r>bVmb+;S?; z^TfJra*alFHZ|qe7rina7_<_-%PN#G9f_tP8pG50h4B7=z7dsv=%j@nT#S{aPxN}) n|NVv)5!9Z=o>-SPdgM1(<2?^wn49`{XUpNgkCpi1kWc&pP=^QR delta 7 OcmX@$^2usLkt_fYk^^u6 diff --git a/methods/qimen.json b/methods/qimen.json index 01b7464..334a7a5 100644 --- a/methods/qimen.json +++ b/methods/qimen.json @@ -1,7 +1,1169 @@ { "module": "qimen", - "description": "Qimen API method catalog", - "version": "0.1.0", + "description": "奇门接口标准入口,method 对应 qimenMethods 异步方法,全部使用 POST 请求,参数包含 query 与 XML body(request 节点)", + "version": "0.3.0", "updatedAt": "2026-03-22", - "endpoints": [] + "headers": [], + "methods": { + "groups": [ + { + "groupName": "deliveryorder 模块", + "module": "deliveryorder", + "list": [ + { + "method": "deliveryorder.batchcreate", + "description": "deliveryorder.batchcreate 接口", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "app_key", + "type": "string", + "required": true, + "source": "query", + "description": "app_key 参数" + }, + { + "name": "method", + "type": "string", + "required": true, + "source": "query", + "description": "method 参数" + }, + { + "name": "v", + "type": "string", + "required": true, + "source": "query", + "description": "v 参数" + }, + { + "name": "format", + "type": "string", + "required": true, + "source": "query", + "description": "format 参数" + }, + { + "name": "sign_method", + "type": "string", + "required": true, + "source": "query", + "description": "sign_method 参数" + }, + { + "name": "sign", + "type": "string", + "required": true, + "source": "query", + "description": "sign 参数" + }, + { + "name": "timestamp", + "type": "string", + "required": true, + "source": "query", + "description": "timestamp 参数" + }, + { + "name": "request", + "type": "object", + "required": true, + "source": "body", + "description": "request XML 节点" + }, + { + "name": "request.orderCode", + "type": "string", + "required": false, + "source": "body", + "description": "request.orderCode 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "deliveryorder.create", + "description": "deliveryorder.create 接口", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "app_key", + "type": "string", + "required": true, + "source": "query", + "description": "app_key 参数" + }, + { + "name": "method", + "type": "string", + "required": true, + "source": "query", + "description": "method 参数" + }, + { + "name": "v", + "type": "string", + "required": true, + "source": "query", + "description": "v 参数" + }, + { + "name": "format", + "type": "string", + "required": true, + "source": "query", + "description": "format 参数" + }, + { + "name": "sign_method", + "type": "string", + "required": true, + "source": "query", + "description": "sign_method 参数" + }, + { + "name": "sign", + "type": "string", + "required": true, + "source": "query", + "description": "sign 参数" + }, + { + "name": "timestamp", + "type": "string", + "required": true, + "source": "query", + "description": "timestamp 参数" + }, + { + "name": "request", + "type": "object", + "required": true, + "source": "body", + "description": "request XML 节点" + }, + { + "name": "request.orderCode", + "type": "string", + "required": false, + "source": "body", + "description": "request.orderCode 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "deliveryorder.query", + "description": "deliveryorder.query 接口", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "app_key", + "type": "string", + "required": true, + "source": "query", + "description": "app_key 参数" + }, + { + "name": "method", + "type": "string", + "required": true, + "source": "query", + "description": "method 参数" + }, + { + "name": "v", + "type": "string", + "required": true, + "source": "query", + "description": "v 参数" + }, + { + "name": "format", + "type": "string", + "required": true, + "source": "query", + "description": "format 参数" + }, + { + "name": "sign_method", + "type": "string", + "required": true, + "source": "query", + "description": "sign_method 参数" + }, + { + "name": "sign", + "type": "string", + "required": true, + "source": "query", + "description": "sign 参数" + }, + { + "name": "timestamp", + "type": "string", + "required": true, + "source": "query", + "description": "timestamp 参数" + }, + { + "name": "request", + "type": "object", + "required": true, + "source": "body", + "description": "request XML 节点" + }, + { + "name": "request.orderCode", + "type": "string", + "required": false, + "source": "body", + "description": "request.orderCode 参数" + } + ], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "entryorder 模块", + "module": "entryorder", + "list": [ + { + "method": "entryorder.create", + "description": "entryorder.create 接口", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "app_key", + "type": "string", + "required": true, + "source": "query", + "description": "app_key 参数" + }, + { + "name": "method", + "type": "string", + "required": true, + "source": "query", + "description": "method 参数" + }, + { + "name": "v", + "type": "string", + "required": true, + "source": "query", + "description": "v 参数" + }, + { + "name": "format", + "type": "string", + "required": true, + "source": "query", + "description": "format 参数" + }, + { + "name": "sign_method", + "type": "string", + "required": true, + "source": "query", + "description": "sign_method 参数" + }, + { + "name": "sign", + "type": "string", + "required": true, + "source": "query", + "description": "sign 参数" + }, + { + "name": "timestamp", + "type": "string", + "required": true, + "source": "query", + "description": "timestamp 参数" + }, + { + "name": "request", + "type": "object", + "required": true, + "source": "body", + "description": "request XML 节点" + } + ], + "response": [], + "errors": [] + }, + { + "method": "entryorder.query", + "description": "entryorder.query 接口", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "app_key", + "type": "string", + "required": true, + "source": "query", + "description": "app_key 参数" + }, + { + "name": "method", + "type": "string", + "required": true, + "source": "query", + "description": "method 参数" + }, + { + "name": "v", + "type": "string", + "required": true, + "source": "query", + "description": "v 参数" + }, + { + "name": "format", + "type": "string", + "required": true, + "source": "query", + "description": "format 参数" + }, + { + "name": "sign_method", + "type": "string", + "required": true, + "source": "query", + "description": "sign_method 参数" + }, + { + "name": "sign", + "type": "string", + "required": true, + "source": "query", + "description": "sign 参数" + }, + { + "name": "timestamp", + "type": "string", + "required": true, + "source": "query", + "description": "timestamp 参数" + }, + { + "name": "request", + "type": "object", + "required": true, + "source": "body", + "description": "request XML 节点" + } + ], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "inventory 模块", + "module": "inventory", + "list": [ + { + "method": "inventory.query", + "description": "inventory.query 接口", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "app_key", + "type": "string", + "required": true, + "source": "query", + "description": "app_key 参数" + }, + { + "name": "method", + "type": "string", + "required": true, + "source": "query", + "description": "method 参数" + }, + { + "name": "v", + "type": "string", + "required": true, + "source": "query", + "description": "v 参数" + }, + { + "name": "format", + "type": "string", + "required": true, + "source": "query", + "description": "format 参数" + }, + { + "name": "sign_method", + "type": "string", + "required": true, + "source": "query", + "description": "sign_method 参数" + }, + { + "name": "sign", + "type": "string", + "required": true, + "source": "query", + "description": "sign 参数" + }, + { + "name": "timestamp", + "type": "string", + "required": true, + "source": "query", + "description": "timestamp 参数" + }, + { + "name": "request", + "type": "object", + "required": true, + "source": "body", + "description": "request XML 节点" + }, + { + "name": "request.criteriaList", + "type": "string", + "required": false, + "source": "body", + "description": "request.criteriaList 参数" + } + ], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "order 模块", + "module": "order", + "list": [ + { + "method": "order.cancel", + "description": "order.cancel 接口", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "app_key", + "type": "string", + "required": true, + "source": "query", + "description": "app_key 参数" + }, + { + "name": "method", + "type": "string", + "required": true, + "source": "query", + "description": "method 参数" + }, + { + "name": "v", + "type": "string", + "required": true, + "source": "query", + "description": "v 参数" + }, + { + "name": "format", + "type": "string", + "required": true, + "source": "query", + "description": "format 参数" + }, + { + "name": "sign_method", + "type": "string", + "required": true, + "source": "query", + "description": "sign_method 参数" + }, + { + "name": "sign", + "type": "string", + "required": true, + "source": "query", + "description": "sign 参数" + }, + { + "name": "timestamp", + "type": "string", + "required": true, + "source": "query", + "description": "timestamp 参数" + }, + { + "name": "request", + "type": "object", + "required": true, + "source": "body", + "description": "request XML 节点" + }, + { + "name": "request.orderCode", + "type": "string", + "required": false, + "source": "body", + "description": "request.orderCode 参数" + }, + { + "name": "request.orderType", + "type": "string", + "required": false, + "source": "body", + "description": "request.orderType 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "order.pending", + "description": "order.pending 接口", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "app_key", + "type": "string", + "required": true, + "source": "query", + "description": "app_key 参数" + }, + { + "name": "method", + "type": "string", + "required": true, + "source": "query", + "description": "method 参数" + }, + { + "name": "v", + "type": "string", + "required": true, + "source": "query", + "description": "v 参数" + }, + { + "name": "format", + "type": "string", + "required": true, + "source": "query", + "description": "format 参数" + }, + { + "name": "sign_method", + "type": "string", + "required": true, + "source": "query", + "description": "sign_method 参数" + }, + { + "name": "sign", + "type": "string", + "required": true, + "source": "query", + "description": "sign 参数" + }, + { + "name": "timestamp", + "type": "string", + "required": true, + "source": "query", + "description": "timestamp 参数" + }, + { + "name": "request", + "type": "object", + "required": true, + "source": "body", + "description": "request XML 节点" + }, + { + "name": "request.orderCode", + "type": "string", + "required": false, + "source": "body", + "description": "request.orderCode 参数" + }, + { + "name": "request.orderType", + "type": "string", + "required": false, + "source": "body", + "description": "request.orderType 参数" + } + ], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "returnorder 模块", + "module": "returnorder", + "list": [ + { + "method": "returnorder.create", + "description": "returnorder.create 接口", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "app_key", + "type": "string", + "required": true, + "source": "query", + "description": "app_key 参数" + }, + { + "name": "method", + "type": "string", + "required": true, + "source": "query", + "description": "method 参数" + }, + { + "name": "v", + "type": "string", + "required": true, + "source": "query", + "description": "v 参数" + }, + { + "name": "format", + "type": "string", + "required": true, + "source": "query", + "description": "format 参数" + }, + { + "name": "sign_method", + "type": "string", + "required": true, + "source": "query", + "description": "sign_method 参数" + }, + { + "name": "sign", + "type": "string", + "required": true, + "source": "query", + "description": "sign 参数" + }, + { + "name": "timestamp", + "type": "string", + "required": true, + "source": "query", + "description": "timestamp 参数" + }, + { + "name": "request", + "type": "object", + "required": true, + "source": "body", + "description": "request XML 节点" + } + ], + "response": [], + "errors": [] + }, + { + "method": "returnorder.query", + "description": "returnorder.query 接口", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "app_key", + "type": "string", + "required": true, + "source": "query", + "description": "app_key 参数" + }, + { + "name": "method", + "type": "string", + "required": true, + "source": "query", + "description": "method 参数" + }, + { + "name": "v", + "type": "string", + "required": true, + "source": "query", + "description": "v 参数" + }, + { + "name": "format", + "type": "string", + "required": true, + "source": "query", + "description": "format 参数" + }, + { + "name": "sign_method", + "type": "string", + "required": true, + "source": "query", + "description": "sign_method 参数" + }, + { + "name": "sign", + "type": "string", + "required": true, + "source": "query", + "description": "sign 参数" + }, + { + "name": "timestamp", + "type": "string", + "required": true, + "source": "query", + "description": "timestamp 参数" + }, + { + "name": "request", + "type": "object", + "required": true, + "source": "body", + "description": "request XML 节点" + } + ], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "singleitem 模块", + "module": "singleitem", + "list": [ + { + "method": "singleitem.query", + "description": "singleitem.query 接口", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "app_key", + "type": "string", + "required": true, + "source": "query", + "description": "app_key 参数" + }, + { + "name": "method", + "type": "string", + "required": true, + "source": "query", + "description": "method 参数" + }, + { + "name": "v", + "type": "string", + "required": true, + "source": "query", + "description": "v 参数" + }, + { + "name": "format", + "type": "string", + "required": true, + "source": "query", + "description": "format 参数" + }, + { + "name": "sign_method", + "type": "string", + "required": true, + "source": "query", + "description": "sign_method 参数" + }, + { + "name": "sign", + "type": "string", + "required": true, + "source": "query", + "description": "sign 参数" + }, + { + "name": "timestamp", + "type": "string", + "required": true, + "source": "query", + "description": "timestamp 参数" + }, + { + "name": "request", + "type": "object", + "required": true, + "source": "body", + "description": "request XML 节点" + }, + { + "name": "request.itemId", + "type": "string", + "required": false, + "source": "body", + "description": "request.itemId 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "singleitem.synchronize", + "description": "singleitem.synchronize 接口", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "app_key", + "type": "string", + "required": true, + "source": "query", + "description": "app_key 参数" + }, + { + "name": "method", + "type": "string", + "required": true, + "source": "query", + "description": "method 参数" + }, + { + "name": "v", + "type": "string", + "required": true, + "source": "query", + "description": "v 参数" + }, + { + "name": "format", + "type": "string", + "required": true, + "source": "query", + "description": "format 参数" + }, + { + "name": "sign_method", + "type": "string", + "required": true, + "source": "query", + "description": "sign_method 参数" + }, + { + "name": "sign", + "type": "string", + "required": true, + "source": "query", + "description": "sign 参数" + }, + { + "name": "timestamp", + "type": "string", + "required": true, + "source": "query", + "description": "timestamp 参数" + }, + { + "name": "request", + "type": "object", + "required": true, + "source": "body", + "description": "request XML 节点" + }, + { + "name": "request.itemId", + "type": "string", + "required": false, + "source": "body", + "description": "request.itemId 参数" + } + ], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "stockout 模块", + "module": "stockout", + "list": [ + { + "method": "stockout.create", + "description": "stockout.create 接口", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "app_key", + "type": "string", + "required": true, + "source": "query", + "description": "app_key 参数" + }, + { + "name": "method", + "type": "string", + "required": true, + "source": "query", + "description": "method 参数" + }, + { + "name": "v", + "type": "string", + "required": true, + "source": "query", + "description": "v 参数" + }, + { + "name": "format", + "type": "string", + "required": true, + "source": "query", + "description": "format 参数" + }, + { + "name": "sign_method", + "type": "string", + "required": true, + "source": "query", + "description": "sign_method 参数" + }, + { + "name": "sign", + "type": "string", + "required": true, + "source": "query", + "description": "sign 参数" + }, + { + "name": "timestamp", + "type": "string", + "required": true, + "source": "query", + "description": "timestamp 参数" + }, + { + "name": "request", + "type": "object", + "required": true, + "source": "body", + "description": "request XML 节点" + }, + { + "name": "request.deliveryOrder", + "type": "string", + "required": false, + "source": "body", + "description": "request.deliveryOrder 参数" + }, + { + "name": "request.orderLines", + "type": "string", + "required": false, + "source": "body", + "description": "request.orderLines 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "stockout.query", + "description": "stockout.query 接口", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "app_key", + "type": "string", + "required": true, + "source": "query", + "description": "app_key 参数" + }, + { + "name": "method", + "type": "string", + "required": true, + "source": "query", + "description": "method 参数" + }, + { + "name": "v", + "type": "string", + "required": true, + "source": "query", + "description": "v 参数" + }, + { + "name": "format", + "type": "string", + "required": true, + "source": "query", + "description": "format 参数" + }, + { + "name": "sign_method", + "type": "string", + "required": true, + "source": "query", + "description": "sign_method 参数" + }, + { + "name": "sign", + "type": "string", + "required": true, + "source": "query", + "description": "sign 参数" + }, + { + "name": "timestamp", + "type": "string", + "required": true, + "source": "query", + "description": "timestamp 参数" + }, + { + "name": "request", + "type": "object", + "required": true, + "source": "body", + "description": "request XML 节点" + }, + { + "name": "request.deliveryOrder", + "type": "string", + "required": false, + "source": "body", + "description": "request.deliveryOrder 参数" + }, + { + "name": "request.orderLines", + "type": "string", + "required": false, + "source": "body", + "description": "request.orderLines 参数" + } + ], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "taobao.qimen.service 模块", + "module": "taobao.qimen.service", + "list": [ + { + "method": "taobao.qimen.service.heartbeat", + "description": "taobao.qimen.service.heartbeat 接口", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "app_key", + "type": "string", + "required": true, + "source": "query", + "description": "app_key 参数" + }, + { + "name": "method", + "type": "string", + "required": true, + "source": "query", + "description": "method 参数" + }, + { + "name": "v", + "type": "string", + "required": true, + "source": "query", + "description": "v 参数" + }, + { + "name": "format", + "type": "string", + "required": true, + "source": "query", + "description": "format 参数" + }, + { + "name": "sign_method", + "type": "string", + "required": true, + "source": "query", + "description": "sign_method 参数" + }, + { + "name": "sign", + "type": "string", + "required": true, + "source": "query", + "description": "sign 参数" + }, + { + "name": "timestamp", + "type": "string", + "required": true, + "source": "query", + "description": "timestamp 参数" + }, + { + "name": "request", + "type": "object", + "required": true, + "source": "body", + "description": "request XML 节点" + }, + { + "name": "request.serialNumber", + "type": "string", + "required": false, + "source": "body", + "description": "request.serialNumber 参数" + } + ], + "response": [], + "errors": [] + } + ] + } + ] + } } diff --git a/script/tmp-init-qimen-methods.cjs b/script/tmp-init-qimen-methods.cjs new file mode 100644 index 0000000..c82e334 --- /dev/null +++ b/script/tmp-init-qimen-methods.cjs @@ -0,0 +1,194 @@ +const fs = require('fs'); +const path = require('path'); + +const root = process.cwd(); +const methodsDir = path.join(root, 'app', 'service', 'qimenMethods'); +const outputPath = path.join(root, 'methods', 'qimen.json'); + +function walk(dir) { + const out = []; + for (const name of fs.readdirSync(dir)) { + const full = path.join(dir, name); + const stat = fs.statSync(full); + if (stat.isDirectory()) { + out.push(...walk(full)); + } else if (name.endsWith('.js')) { + out.push(full); + } + } + return out; +} + +function extractAsyncMethods(content) { + const methods = []; + const classMatch = content.match(/class\s+[A-Za-z_$][\w$]*\s+extends\s+[A-Za-z_$][\w$]*\s*\{([\s\S]*)\}\s*module\.exports\s*=\s*/); + if (!classMatch) { + return methods; + } + + const body = classMatch[1]; + const regex = /async\s+([A-Za-z_$][\w$]*)\s*\(/g; + let m = regex.exec(body); + while (m) { + if (m[1] !== 'constructor') { + methods.push(m[1]); + } + m = regex.exec(body); + } + + return Array.from(new Set(methods)); +} + +function extractRequestKeys(content) { + const keys = new Set(); + const patterns = [ + /data\.request(?:\?|)\.(\w+)/g, + /data\?\.request\?\.(\w+)/g, + ]; + + for (const re of patterns) { + let m = re.exec(content); + while (m) { + const key = m[1]; + if (key) keys.add(key); + m = re.exec(content); + } + } + + return Array.from(keys).sort((a, b) => a.localeCompare(b)); +} + +function buildMethodItem(fullMethod, requestKeys) { + const params = [ + { + name: 'app_key', + type: 'string', + required: true, + source: 'query', + description: 'app_key 参数', + }, + { + name: 'method', + type: 'string', + required: true, + source: 'query', + description: 'method 参数', + }, + { + name: 'v', + type: 'string', + required: true, + source: 'query', + description: 'v 参数', + }, + { + name: 'format', + type: 'string', + required: true, + source: 'query', + description: 'format 参数', + }, + { + name: 'sign_method', + type: 'string', + required: true, + source: 'query', + description: 'sign_method 参数', + }, + { + name: 'sign', + type: 'string', + required: true, + source: 'query', + description: 'sign 参数', + }, + { + name: 'timestamp', + type: 'string', + required: true, + source: 'query', + description: 'timestamp 参数', + }, + { + name: 'request', + type: 'object', + required: true, + source: 'body', + description: 'request XML 节点', + }, + ]; + + for (const key of requestKeys) { + params.push({ + name: `request.${key}`, + type: 'string', + required: false, + source: 'body', + description: `request.${key} 参数`, + }); + } + + return { + method: fullMethod, + description: `${fullMethod} 接口`, + isNeedAuth: false, + isNeedLogin: false, + headers: [], + params, + response: [], + errors: [], + }; +} + +function main() { + if (!fs.existsSync(methodsDir)) { + throw new Error(`目录不存在: ${methodsDir}`); + } + + const files = walk(methodsDir).sort((a, b) => a.localeCompare(b)); + const groupMap = new Map(); + + for (const file of files) { + const content = fs.readFileSync(file, 'utf8'); + const rel = path.relative(methodsDir, file).replace(/\\/g, '/').replace(/\.js$/, ''); + const moduleName = rel.replace(/\//g, '.'); + const methodNames = extractAsyncMethods(content); + const requestKeys = extractRequestKeys(content); + + if (!groupMap.has(moduleName)) { + groupMap.set(moduleName, []); + } + + for (const methodName of methodNames) { + const fullMethod = `${moduleName}.${methodName}`; + groupMap.get(moduleName).push(buildMethodItem(fullMethod, requestKeys)); + } + } + + const groups = Array.from(groupMap.entries()) + .map(([ moduleName, list ]) => ({ + groupName: `${moduleName} 模块`, + module: moduleName, + list: list.sort((a, b) => a.method.localeCompare(b.method)), + })) + .sort((a, b) => a.module.localeCompare(b.module)); + + const now = new Date().toISOString().slice(0, 10); + const doc = { + module: 'qimen', + description: '奇门接口标准入口,method 对应 qimenMethods 异步方法,全部使用 POST 请求,参数包含 query 与 XML body(request 节点)', + version: '0.3.0', + updatedAt: now, + headers: [], + methods: { + groups, + }, + }; + + fs.writeFileSync(outputPath, JSON.stringify(doc, null, 2) + '\n', 'utf8'); + + const methodCount = groups.reduce((sum, group) => sum + group.list.length, 0); + console.log(`WROTE methods/qimen.json, groups=${groups.length}, methods=${methodCount}`); +} + +main(); \ No newline at end of file diff --git a/tmp-service-method-inventory.md b/tmp-service-method-inventory.md index 22fda06..052d888 100644 --- a/tmp-service-method-inventory.md +++ b/tmp-service-method-inventory.md @@ -1,4 +1,4 @@ -自动生成时间: 2026-03-22T06:43:50.263Z +自动生成时间: 2026-03-22T09:03:11.802Z 扫描范围: app/service/**/*.js 文件数: 50 From bbc5891d16221f48e7831d30a4dae17868edc585 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 23 Mar 2026 17:10:07 +0800 Subject: [PATCH 006/550] chore: sync workspace changes --- .gitignore | 3 + AI_METHOD_ROUTING.md | 17 +- AI_TOOLBOX.md | 183 +- Apifox/print.json | 143 -- Apifox/test.json | 107 -- METHOD_OUTPUT_REGRESSION_20260322.md | 94 + README.md | 238 ++- SERVICE_API_CHANGE_AUDIT_20260322.md | 719 ++++++++ app.js | 29 +- app/controller/api_v2.js | 169 -- app/controller/home.js | 162 +- app/extend/application.js | 22 + app/lib/api_response.js | 59 + app/model/account.js | 5 +- app/model/account_store_employee.js | 2 +- app/model/api_app.js | 17 - app/model/entry_items.js | 68 - app/model/entry_order.js | 232 --- app/model/i18n_translation.js | 120 +- app/model/interface_type.js | 21 - app/model/permission.js | 9 +- app/model/print_item.js | 31 - app/model/receiving.js | 11 +- app/model/receiving_detail.js | 8 +- app/model/role.js | 4 +- app/model/role_permission.js | 4 +- app/model/stock_store.js | 39 - app/model/stock_warehouse.js | 5 +- app/model/storage.js | 217 --- app/model/store.js | 4 +- app/model/store_warehouse.js | 50 + app/router.js | 18 +- app/service/system.js | 97 +- app/service/systemMethods/order.js | 351 ---- .../systemMethods/order/archiveOrder.js | 62 + app/service/systemMethods/order/base.js | 157 ++ .../systemMethods/order/deliveryOrder.js | 63 + .../systemMethods/order/expectionOrder.js | 90 + app/service/systemMethods/order/index.js | 204 +++ .../systemMethods/order/pendingOrder.js | 69 + .../systemMethods/order/reviewOrder.js | 103 ++ app/service/systemMethods/user.js | 41 +- app/service/systems/account_platform.js | 273 +-- app/service/systems/auth/user.js | 258 ++- app/service/systems/entry_order.js | 342 ++++ app/service/systems/stock_store.js | 32 +- app/service/systems/storage/index.js | 243 +++ app/service/systems/storage/receiving.js | 31 +- app/service/systems/store.js | 83 +- ...tion_eager_loading_n_plus_one_guideline.md | 102 ++ association_fix_plan.md | 61 + association_fk_consistency_report.md | 65 + association_validation_checklist.md | 165 ++ ...20260323103000-align-role-permission-fk.js | 115 ++ .../20260323113000-add-role-store-fk.js | 150 ++ ...20260323123000-add-permission-parent-fk.js | 109 ++ day.log | Bin 8768 -> 20166 bytes methods/system.json | 380 +++- migration_execution_plan.md | 76 + migration_gap_list.md | 107 ++ modelList.md | 105 ++ model_association_inventory.md | 52 + model_cleanup_list.md | 213 +++ model_inventory.md | 53 + model_naming_standard.md | 184 ++ model_rename_map.md | 100 + model_todo.txt | 130 ++ rename_impact_report.md | 168 ++ role_permission_fk_data_cleanup_plan.md | 104 ++ rollback_plan.md | 49 + schema_model_gap_report.md | 98 + script/method-output-regression.cjs | 427 +++++ script/redis-cache.ps1 | 254 +++ script/tmp-compare-order-schema.cjs | 6 +- script/tmp-gen-service-method-inventory.cjs | 6 +- .../tmp-generate-method-regression-test.cjs | 116 ++ script/tmp-update-ai-method-routing.cjs | 4 +- table_schema_inventory.md | 85 + test/app/controller/api_v2.test.js | 43 - test/app/controller/home.test.js | 2 +- .../system.order.getreviewOrderlist.test.js | 83 + .../system.order.namespaced.test.js | 143 ++ .../system.order.reviewOrder.test.js | 112 ++ .../controller/system.user.changeRole.test.js | 98 + test/app/controller/system.user.info.test.js | 21 + .../controller/system.user.info.web.test.js | 45 + test/app/controller/system.user.login.test.js | 35 + .../system.user.loginByCode.test.js | 52 + test/support/system_method_client.js | 137 ++ tmp-order-schema-compare.json | 1610 ----------------- tmp-order-schema-workflow.md | 4 +- tmp-service-method-inventory.md | 105 -- 92 files changed, 7570 insertions(+), 3713 deletions(-) delete mode 100644 Apifox/print.json delete mode 100644 Apifox/test.json create mode 100644 METHOD_OUTPUT_REGRESSION_20260322.md create mode 100644 SERVICE_API_CHANGE_AUDIT_20260322.md delete mode 100644 app/controller/api_v2.js create mode 100644 app/lib/api_response.js delete mode 100644 app/service/systemMethods/order.js create mode 100644 app/service/systemMethods/order/archiveOrder.js create mode 100644 app/service/systemMethods/order/base.js create mode 100644 app/service/systemMethods/order/deliveryOrder.js create mode 100644 app/service/systemMethods/order/expectionOrder.js create mode 100644 app/service/systemMethods/order/index.js create mode 100644 app/service/systemMethods/order/pendingOrder.js create mode 100644 app/service/systemMethods/order/reviewOrder.js create mode 100644 association_eager_loading_n_plus_one_guideline.md create mode 100644 association_fix_plan.md create mode 100644 association_fk_consistency_report.md create mode 100644 association_validation_checklist.md create mode 100644 database/migrations/20260323103000-align-role-permission-fk.js create mode 100644 database/migrations/20260323113000-add-role-store-fk.js create mode 100644 database/migrations/20260323123000-add-permission-parent-fk.js create mode 100644 migration_execution_plan.md create mode 100644 migration_gap_list.md create mode 100644 modelList.md create mode 100644 model_association_inventory.md create mode 100644 model_cleanup_list.md create mode 100644 model_inventory.md create mode 100644 model_naming_standard.md create mode 100644 model_rename_map.md create mode 100644 model_todo.txt create mode 100644 rename_impact_report.md create mode 100644 role_permission_fk_data_cleanup_plan.md create mode 100644 rollback_plan.md create mode 100644 schema_model_gap_report.md create mode 100644 script/method-output-regression.cjs create mode 100644 script/redis-cache.ps1 create mode 100644 script/tmp-generate-method-regression-test.cjs create mode 100644 table_schema_inventory.md delete mode 100644 test/app/controller/api_v2.test.js create mode 100644 test/app/controller/system.order.getreviewOrderlist.test.js create mode 100644 test/app/controller/system.order.namespaced.test.js create mode 100644 test/app/controller/system.order.reviewOrder.test.js create mode 100644 test/app/controller/system.user.changeRole.test.js create mode 100644 test/app/controller/system.user.info.test.js create mode 100644 test/app/controller/system.user.info.web.test.js create mode 100644 test/app/controller/system.user.login.test.js create mode 100644 test/app/controller/system.user.loginByCode.test.js create mode 100644 test/support/system_method_client.js delete mode 100644 tmp-order-schema-compare.json delete mode 100644 tmp-service-method-inventory.md diff --git a/.gitignore b/.gitignore index 29f5dab..9eb7841 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ logs/ run/ +temp/ node_modules/ coverage/ .nyc_output/ @@ -23,3 +24,5 @@ native/addons/*.node Thumbs.db *.sw* *.un~ +todo.txt +test/.runtime/ diff --git a/AI_METHOD_ROUTING.md b/AI_METHOD_ROUTING.md index f745d6b..bc87e0c 100644 --- a/AI_METHOD_ROUTING.md +++ b/AI_METHOD_ROUTING.md @@ -111,9 +111,10 @@ rg "class .*Service|module.exports" app/service/qimenMethods - 扫描范围:app/service/**/*.js - 本节内容由脚本生成,新增/修改 service 后请同步刷新。 - 刷新命令:node .\script\tmp-gen-service-method-inventory.cjs +- 临时清单输出:temp/tmp-service-method-inventory.md -自动生成时间: 2026-03-22T09:03:11.802Z +自动生成时间: 2026-03-22T15:27:37.958Z 扫描范围: app/service/**/*.js 文件数: 50 @@ -146,8 +147,8 @@ rg "class .*Service|module.exports" app/service/qimenMethods - create, query - app/service/qimenMethods/taobao/qimen/service.js (1) - heartbeat -- app/service/system.js (3) - - callMethod, validateParams, saveLog +- app/service/system.js (4) + - callMethod, validateParams, validateRequestContext, saveLog - app/service/systemMethods/config.js (1) - list - app/service/systemMethods/dashboard.js (6) @@ -172,8 +173,8 @@ rg "class .*Service|module.exports" app/service/qimenMethods - login, logout, info, changeRole, register - app/service/systemMethods/warehouse.js (20) - getWarehouseZones, getWarehouseTree, getChildren, create, update, delete, detail, checkBarcodeUnique, toggleActive, getPath, createRack, getPickPath, updateRackPosition, recalculatePickPath, updateNeighbors, getAreaRacks, getSpacesByRack, createRackWithSpaces, getSpaceInfo, updateSpaceInfo -- app/service/systems/account_platform.js (8) - - switchActiveRole, getActiveRoleByPlatform, getMultiplePlatformActiveRoles, getAllPlatformActives, clearPlatformActive, clearPlatformCache, getAvailableRoles, getCurrentContext +- app/service/systems/account_platform.js (11) + - getActiveInclude, getPrimaryRoleBinding, formatActiveContext, switchActiveRole, getActiveRoleByPlatform, getMultiplePlatformActiveRoles, getAllPlatformActives, clearPlatformActive, clearPlatformCache, getAvailableRoles, getCurrentContext - app/service/systems/auth/user.js (21) - login, ID, changeRole, info, getRoles, findById, setUserCache, getAvatarByEmployeeId, clearUserCache, clearRelatedCache, getPermissions, getMenus, convertToRoutes, findUserByIdentifier, checkUserStatus, verifyPassword, encryptPassword, generateSalt, updateLastLoginTime, ensurePlatformActiveRole, register - app/service/systems/delivery_order.js (7) @@ -214,8 +215,10 @@ rg "class .*Service|module.exports" app/service/qimenMethods - index - app/service/systems/storage/receiving.js (16) - getReceivingList, getReceivingDetail, batchCancelReceiving, isEmptyValue, buildSequelizeCondition, processConditionValue, create, get, addDetail, updateDetail, getStockStoreInfo, updateReceivingStats, deleteDetail, detailChange, invalid, completeReceiving -- app/service/systems/store.js (13) - - getStoreName, getStoreRemaskName, createStore, createWarehouse, joinStore, joinWarehouse, assignAdminRoleToCreator, generateJoinToken, sendNotification, sendNotificationToAdmins, getStoreRoles, auditApply, loadStores +- app/service/systems/store.js (14) + - getStoreName, getStoreRemaskName, createStore, createWarehouse, joinStore, joinWarehouse, ensureEmployeeRoleBinding, assignAdminRoleToCreator, generateJoinToken, sendNotification, sendNotificationToAdmins, getStoreRoles, auditApply, loadStores - app/service/systems/upload.js (14) - initCOS, getUploadParams, hash_hmac, validateFileInfo, generateFileName, parseSizeToBytes, formatFileSize, getFrontendConfig, uploadFile, validateFile, uploadSuccessNotify, getMimeType, createFileReference, handleUploadCallback + + diff --git a/AI_TOOLBOX.md b/AI_TOOLBOX.md index eed5349..f858e87 100644 --- a/AI_TOOLBOX.md +++ b/AI_TOOLBOX.md @@ -10,10 +10,15 @@ ## 2. 数据库调试脚本 +临时文件规则(强制): +- 所有临时产物统一生成到 `temp/` 目录。 +- `temp/` 目录不提交到 git。 + 项目已提供数据库查询脚本:`script/db-query.ps1` 脚本能力: - 自动读取 `config/config.local.js` 中的 `config.mysql.clients.` 配置 +- 支持通过 `-DbClient` 显式切换 mysql client(如 `wms`、`ye4s`),默认 `wms` - 执行传入 SQL 并返回 JSON - 可选表格输出,便于命令行快速查看 @@ -34,12 +39,19 @@ powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -Query "SELECT id # 指定 mysql client(默认是 wms) powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -DbClient wms -Query "SHOW TABLES" + +# 切换到 ye4s client +powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -DbClient ye4s -Query "SHOW TABLES" + +# 快速确认当前连接到哪个库/账号 +powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -Query "SELECT DATABASE() AS db, USER() AS loginUser" +powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -DbClient ye4s -Query "SELECT DATABASE() AS db, USER() AS loginUser" ``` ### 2.3 参数说明 - `-Query`:必填,SQL 语句 -- `-DbClient`:可选,MySQL 客户端名,默认 `wms` +- `-DbClient`:可选,MySQL 客户端名(例如 `wms`、`ye4s`),默认 `wms` - `-ConfigPath`:可选,配置文件路径,默认 `.\config\config.local.js`(相对于项目根目录) - `-AsTable`:可选,按表格输出结果 @@ -59,6 +71,16 @@ powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -DbClient wms -Qu } ``` +### 2.5 区分 wms 与 ye4s(快速自检) + +- 步骤 1:不传 `-DbClient` 执行一次 `SELECT DATABASE() AS db, USER() AS loginUser` +- 步骤 2:传 `-DbClient ye4s` 再执行同一条 SQL +- 期望结果: + - 默认执行返回 `client = wms` 且 `db = wms` + - 指定 `ye4s` 返回 `client = ye4s` 且 `db = ye4s` + +说明:脚本会从 `config.mysql.clients.` 读取连接参数,返回体中的 `client` 字段可直接用于确认当前路由。 + ## 3. AI 协助时建议使用的提问模板 ### 3.1 只读查询(推荐) @@ -86,27 +108,99 @@ SELECT * FROM account LIMIT 20; 4) 输出最终根因和修复建议 ``` -## 4. 常见问题 +## 4. Redis 缓存调试脚本 + +项目已提供 Redis 调试脚本:`script/redis-cache.ps1` + +脚本能力: +- 自动读取 `config/config.local.js`(可切换 `-ConfigPath`)中的 `config.redis.clients.` 配置连接 Redis +- 支持缓存读取与修改:`get/set/del/exists/ttl/expire/keys/hget/hset/hdel/hgetall/incr/decr` +- 可选表格输出(`-AsTable`) + +### 4.1 基本用法 + +```powershell +powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action get -RedisClient cache -Key "system" +``` + +### 4.2 常用示例 + +```powershell +# 列出 key(使用 SCAN,不直接 KEYS 阻塞) +powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action keys -RedisClient cache -Pattern "user:*" -AsTable + +# 读取/写入字符串缓存 +powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action get -RedisClient cache -Key "system" +powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action set -RedisClient cache -Key "system" -Value "{\"ok\":1}" -ExpireSeconds 600 + +# 删除缓存 +powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action del -RedisClient cache -Key "system" + +# Hash 结构读写 +powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action hgetall -RedisClient cache -Key "session:123" -AsTable +powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action hset -RedisClient cache -Key "session:123" -Field "status" -Value "active" + +# 自增/自减计数器 +powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action incr -RedisClient cache -Key "counter:order" +powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action decr -RedisClient cache -Key "counter:order" -Value 2 +``` + +### 4.3 参数说明 + +- `-Action`:必填,操作类型(`get/set/del/exists/ttl/expire/keys/hget/hset/hdel/hgetall/incr/decr`) +- `-RedisClient`:可选,Redis 客户端名,默认 `cache` +- `-Key`:按操作需要传入 +- `-Value`:`set/hset/incr/decr` 等操作使用 +- `-Field`:`hget/hset/hdel` 必填 +- `-ExpireSeconds`:`set`(可选)和 `expire`(必填) +- `-Pattern`:`keys` 操作匹配模式,默认 `*` +- `-ConfigPath`:可选,默认 `.\config\config.local.js` +- `-AsTable`:可选,表格输出 + +### 4.4 AI 调用模板(缓存读改) + +```text +请在项目根目录执行 script/redis-cache.ps1: +1) 用 Action=keys, Pattern="user:*" 列出目标缓存键 +2) 读取 key=xxx 的当前值(Action=get) +3) 按我提供的新值执行 Action=set 并设置过期时间 600 秒 +4) 回读一次确认变更生效,并输出变更前后对比 +``` + +## 5. 常见问题 - 报错 `Cannot find module 'mysql2/promise'` - 先执行 `npm install`,确认依赖完整 +- 报错 `Cannot find module 'ioredis'` + - 先执行 `npm install`,确认依赖完整 + - 报错 `MySQL client "xxx" not found in config.mysql.clients` - 检查 `config/config.local.js` 中 `config.mysql.clients` 是否包含对应 client +- SQL 语法报错且定位到 `current_user` + - 避免使用 `current_user` 作为别名,建议改成 `loginUser` 等非保留字名称 + +- 报错 `Redis client "xxx" not found in config.redis.clients` + - 检查 `config/config.local.js` 中 `config.redis.clients` 是否包含对应 client + - 报错连接失败(超时/拒绝访问) - 检查数据库 IP、端口、用户名密码、网络白名单 +- 报错 Redis 连接失败(超时/认证失败) + - 检查 Redis host/port/password/db 与网络连通性 + - PowerShell 执行策略限制 - 使用命令中的 `-ExecutionPolicy Bypass`(仅本次命令生效) -## 5. 安全约束 +## 6. 安全约束 - 默认只执行 SELECT/SHOW 等只读 SQL - 执行 UPDATE/DELETE 前必须先让 AI 生成影响范围确认 SQL(COUNT + WHERE 条件) - 涉及生产数据时,优先在测试环境验证 +- Redis 写操作(`set/del/hset/hdel/incr/decr/expire`)前,先执行一次读取并确认影响 key 范围 -## 6. 接口入口与 Method 指向 +## 7. 接口入口与 Method 指向 - 入口风格: - `/qimen`:奇门开发接口(POST) @@ -119,7 +213,7 @@ SELECT * FROM account LIMIT 20; - 见 `AI_METHOD_ROUTING.md` - 文档记录了 method 到 `app/service/systemMethods`、`app/service/qimenMethods` 的映射规则与示例。 -## 7. methods 目录地图 +## 8. methods 目录地图 目录:`methods/` @@ -133,7 +227,7 @@ SELECT * FROM account LIMIT 20; 建议将 `methods/*.json` 视为“接口文档单一事实来源(SSOT)”。 -## 8. 接口变更联动工作流(强制) +## 9. 接口变更联动工作流(强制) 当出现以下任一变更时,必须同步更新 `methods` 目录下对应 JSON: @@ -166,5 +260,82 @@ node .\script\tmp-struct-system-params.cjs 执行规则:接口代码与 `methods/*.json` 不一致时,以“必须补齐文档”为完成标准。 +## 10. App 能力地图(优先定位) +能力入口文件: + +- `app.js` +- `app/extend/application.js` + +### 10.1 启动与初始化能力(app.js) + +- 设置应用根路径:`global.APP_ROOT`、`app.appRoot` +- 启动前初始化动态工厂: + - `OrderDeliveryFactory` + - `OrderItemsFactory` +- 启动时能力自检: + - `app.setCacheAsync` / `app.getCacheAsync` + - `app.Message` +- 全局日期格式化扩展:`Date.prototype.format('YYYY-MM-DD HH:mm:ss')` + +### 10.2 Application 扩展能力(app/extend/application.js) + +- 业务字典访问: + - `businessDict` + - `getBusinessTypeName(code)` + - `getOperationCodeName(code)` + - `getPlatformName(code)` + - `getExternalLogTypeName(type)` +- 外部 SOAP 调用: + - `wsdl(methodName, args)` +- Redis 缓存(cache client): + - `setCacheAsync(cacheKey, data, expireSeconds = 300)` + - `getCacheAsync(cacheKey)` +- Message 扩展: + - `Message` getter(返回 `MessageClass`) + +### 10.3 AI 调试优先顺序 + +- 遇到“方法不存在/映射异常”优先检查 `app/extend/application.js` 是否包含对应能力。 +- 遇到“动态分表模型不可用”优先检查 `app.js` 的工厂初始化是否执行成功。 +- 遇到“缓存读写异常”优先检查 Redis client `cache` 配置及 `setCacheAsync/getCacheAsync` 调用链。 + +### 10.4 AI 快速回复定义 +- 回复0时默认拒绝 +- 回复1时默认接收 + +## 11. Web 用户信息与切换角色测试(已验证) + +目标: +- 使用 `/system` 入口验证 Web 端用户信息获取与角色切换链路。 +- 固定请求头:`platform=web`、`project=all`。 +- 将接口返回暂存到 `test/.runtime/` 便于回放与比对。 + +测试文件: +- `test/app/controller/system.user.info.web.test.js` + - 调用 `user.info` + - 断言 `status=200`、`flag=success`、`code=200` + - 断言返回 `platform_code=web` + - 落盘:`test/.runtime/system_user_info_web_all.json` + +- `test/app/controller/system.user.changeRole.test.js` + - 先调用 `user.info` 读取当前角色与可切换角色 + - 调用 `user.changeRole`(`roleId` 取可用候选角色) + - 使用返回的新 token 再调 `user.info` 验证 `employees_id` 已切换 + - 落盘:`test/.runtime/system_user_change_role_web_all.json` + - 末尾自动切回原角色,降低对其他测试影响 + +一键执行: + +```powershell +npx egg-bin test test/app/controller/system.user.info.web.test.js test/app/controller/system.user.changeRole.test.js +``` + +本地验证结果: +- 2 passing + +建议排查顺序(当返回菜单/权限为空时): +1. 先查 `user.info` 返回中的 `employees_id`、`store_id`、`platform_code` +2. 确认请求头是否为 `platform=web`、`project=all` +3. 若仍为空,检查账号角色授权与当前激活角色是否存在 \ No newline at end of file diff --git a/Apifox/print.json b/Apifox/print.json deleted file mode 100644 index 3081377..0000000 --- a/Apifox/print.json +++ /dev/null @@ -1,143 +0,0 @@ -{ - "openapi": "3.0.1", - "info": { - "title": "打印相关接口", - "description": "print service methods", - "version": "1.0.0" - }, - "paths": { - "/system": { - "post": { - "summary": "打印台相关接口", - "operationId": "printStationOperations", - "description": "根据method参数执行不同的打印台操作", - "parameters": [ - { - "name": "method", - "in": "query", - "description": "调用方法名,如print.getList、print.getItem、print.updateItem、print.del、print.getComputer、print.getComputerPrinter、print.savePrinters", - "required": true, - "schema": { - "type": "string", - "enum": [ - "print.getList", - "print.getItem", - "print.updateItem", - "print.del", - "print.getComputer", - "print.getComputerPrinter", - "print.savePrinters" - ] - } - }, - { - "name": "v", - "in": "query", - "description": "版本号", - "required": false, - "schema": { - "type": "string", - "example": "2.0" - } - }, - { - "name": "timestamp", - "in": "query", - "description": "时间戳", - "required": false, - "schema": { - "type": "string", - "example": "1646908800000" - } - } - ], - "requestBody": { - "required": false, - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "page": { "type": "integer", "example": 1 }, - "pageSize": { "type": "integer", "example": 20 }, - "where": { - "type": "object", - "example": { "name": "A台" } - }, - "id": { "type": "integer", "example": 1 }, - "name": { "type": "string", "example": "A台" }, - "computer_id": { "type": "integer", "example": 2 }, - "custom_barcode": { "type": "string", "example": "123456" }, - "ids": { - "type": "array", - "items": { "type": "integer" }, - "example": [1,2] - }, - "default": { "type": "string", "example": "打印机名称" }, - "express": { - "type": "array", - "items": { - "type": "object", - "properties": { - "express_id": { "type": "integer" }, - "name": { "type": "string" } - } - }, - "example": [{ "express_id": 1, "name": "顺丰" }] - }, - "print_station_id": { "type": "integer", "example": 1 } - } - } - } - } - }, - "responses": { - "200": { - "description": "成功响应", - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "code": { "type": "integer", "description": "状态码" }, - "message": { "type": "string", "description": "返回信息" }, - "data": { "type": "object", "description": "返回数据" } - } - } - } - } - }, - "400": { - "description": "错误请求", - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "code": { "type": "integer" }, - "message": { "type": "string" } - } - } - } - } - }, - "401": { - "description": "未授权" - } - }, - "security": [ - { "bearer": [] } - ] - } - } - }, - "components": { - "securitySchemes": { - "bearer": { - "type": "http", - "scheme": "bearer", - "bearerFormat": "JWT" - } - } - } -} \ No newline at end of file diff --git a/Apifox/test.json b/Apifox/test.json deleted file mode 100644 index 48134e5..0000000 --- a/Apifox/test.json +++ /dev/null @@ -1,107 +0,0 @@ -{ - "openapi": "3.0.1", - "info": { - "title": "默认模块", - "description": "", - "version": "1.0.0" - }, - "tags": [], - "paths": { - "/system": { - "post": { - "summary": "未命名接口", - "deprecated": false, - "description": "", - "tags": [], - "parameters": [ - { - "name": "method", - "in": "query", - "description": "", - "required": false, - "example": "user.login", - "schema": { - "type": "string" - } - }, - { - "name": "v", - "in": "query", - "description": "", - "required": false, - "example": "2.0", - "schema": { - "type": "string" - } - }, - { - "name": "timestamp", - "in": "query", - "description": "", - "required": false, - "example": "{{$date.now}}", - "schema": { - "type": "string" - } - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "userName": { - "type": "string" - }, - "passWord": { - "type": "string" - } - }, - "required": [ - "userName", - "passWord" - ] - }, - "example": { - "userName": "夫立伟", - "passWord": "Ut cillum veniam" - } - } - } - }, - "responses": { - "200": { - "description": "", - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": {} - } - } - }, - "headers": {} - } - }, - "security": [ - { - "bearer": [] - } - ] - } - } - }, - "components": { - "schemas": {}, - "responses": {}, - "securitySchemes": { - "bearer": { - "type": "http", - "scheme": "bearer" - } - } - }, - "servers": [], - "security": [] -} \ No newline at end of file diff --git a/METHOD_OUTPUT_REGRESSION_20260322.md b/METHOD_OUTPUT_REGRESSION_20260322.md new file mode 100644 index 0000000..19aaed7 --- /dev/null +++ b/METHOD_OUTPUT_REGRESSION_20260322.md @@ -0,0 +1,94 @@ +# Method 输出一致性回放说明 + +更新时间: 2026-03-22 + +## 1. 新交付条件 + +- 所有模型/关联相关改动,必须先执行 method 输出基线回放。 +- 改动完成后,必须对同一批 method 执行 compare 回放。 +- 交付标准: 修改前后 method 输出一致。 +- 允许屏蔽波动字段: token、timestamp、last_login_at、created_at、updated_at、iat、exp。 + +## 2. 测试账号 + +- username: liufumingren +- password: 111111 + +## 3. 方法使用来源 + +- method 定义来源: methods/system.json +- 回放脚本会从该配置中读取 method 分组、描述、参数定义,作为样本元数据。 + +## 4. 测试数据来源 + +- 主来源表: wms_system_log +- 参考日志表: + - wms_api_log + - wms_operation_log + - wms_account_login_log +- 样本选择原则: + - 优先同账号(liufumingren) + - 优先只读方法(get/list/query/detail/info/stats) + - 优先较新数据(按日志 id 倒序) + - 优先方法去重 + +## 5. 执行脚本 + +脚本文件: + +- script/method-output-regression.cjs + +命令: + +```powershell +# 修改前执行,生成基线 +node .\script\method-output-regression.cjs baseline 8 + +# 修改后执行,对比输出 +node .\script\method-output-regression.cjs compare +``` + +输出文件: + +- temp/method-output/method-output-baseline.json +- temp/method-output/method-output-baseline.md +- temp/method-output/method-output-compare.json + +## 6. 本次基线执行结果(修改前) + +执行时间: + +- baseline: 2026-03-22T13:56:52Z +- compare: 2026-03-22T13:56:57Z + +样本数: + +- 8 + +样本 method(来自 temp/method-output/method-output-baseline.md): + +- storage.receiving.getReceivingDetail (sourceId: 10790) +- order.getOrderModels (sourceId: 10783) +- print.getList (sourceId: 10611) +- print.getComputerPrinter (sourceId: 10579) +- print.getItem (sourceId: 10578) +- print.getComputer (sourceId: 10577) +- store.getStoreRoles (sourceId: 10553) +- index.getExpressList (sourceId: 9820) + +比对结果: + +- total: 8 +- mismatch: 0 +- pass: true + +说明: + +- 当前样本中既包含 200 成功响应,也包含 403 权限响应。 +- 403 响应同样纳入一致性校验范围(用于防止权限链路被意外改变)。 + +## 7. 后续执行要求 + +- 每次开始改动前,先运行 baseline 并保留输出文件。 +- 每次改动后,必须运行 compare。 +- 若 mismatch > 0,禁止进入交付,需先排查差异并补充说明。 diff --git a/README.md b/README.md index 29bfd86..1570c76 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,13 @@ # 奇门WMS(qimen-wms) -基于 Egg.js 的仓储管理系统(WMS),支持多快递平台对接、订单管理、打印、权限、配置等功能,适合中小型电商与仓储企业二次开发。 +基于 Egg.js 的仓储管理系统(WMS),支持多快递平台对接、订单管理、打印、权限、配置等功能,适合中小型电商与仓储企业二次开发。基于AI协助管理项目开发,配置了AI能力脚本和完整的项目地图 ## 文档导航 -- 项目协作工具箱:`AI_TOOLBOX.md` +- AI项目协作工具箱:`AI_TOOLBOX.md` - Method 路由映射说明:`AI_METHOD_ROUTING.md` +- Model 层级清单:`modelList.md` +- Method 输出一致性回归记录:`METHOD_OUTPUT_REGRESSION_20260322.md` - system 接口文档源:`methods/system.json` - qimen 接口文档源:`methods/qimen.json` - 日报:`day.log` @@ -23,6 +25,7 @@ ├── config/ # 配置(poloapi、redis、数据库等) ├── database/ # 迁移与数据库配置 ├── methods/ # 接口文档数据源(JSON) +├── native/ # 原生扩展目录(Node.js C++ addon) ├── script/ # 调试与文档生成脚本 ├── logs/ # 日志 ├── run/ # 运行时/元数据 @@ -37,6 +40,7 @@ - `README.md`:项目入口文档,提供整体说明与规范入口。 - `AI_TOOLBOX.md`:AI/开发协作操作手册,包含脚本与工作流。 - `AI_METHOD_ROUTING.md`:接口入口与 method 到代码文件的映射。 +- `modelList.md`:model 层级结构与关键说明清单。 - `methods/system.json`:system 接口定义(headers、groups、params、response、errors)。 - `methods/qimen.json`:qimen 接口定义(按奇门协议组织)。 - `day.log`:每日工作留痕。 @@ -58,6 +62,102 @@ npm run dev - `npm run lint`:代码风格检查 - `npm test`:单元测试 +## 外部 Method 测试(Egg.js test 规范) + +测试文件按“暴露出口 + method”命名,位于 `test/app/controller/`: + +- `system.user.login.test.js` +- `system.user.info.test.js` + +测试辅助客户端位于: + +- `test/support/system_method_client.js` + +默认测试账号(可通过环境变量覆盖): + +- `SYSTEM_TEST_USERNAME=liufumingren` +- `SYSTEM_TEST_PASSWORD=111111` + +Token 暂存机制: + +- 登录 token 会写入 `test/.runtime/system_user_token.json`。 +- 每次执行测试会优先读取本地 token;若 token 可用,则跳过 `user.login` 调用。 +- 当 token 不存在或过期时,测试脚本会自动调用 `user.login` 并刷新缓存。 + +常用命令: + +```bash +npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js +``` + +可选环境变量: + +- `SYSTEM_TEST_BASE_URL`:默认 `http://127.0.0.1:6060` +- `SYSTEM_TEST_TOKEN_FILE`:默认 `test/.runtime/system_user_token.json` + +## Method 输出一致性回归(新规则) + +目标: + +- 在模型/关联/服务改动前后,确保关键 method 输出结果一致。 + +强制规则: + +1. 改动前先执行 baseline(生成修改前输出快照)。 +2. 改动后执行 compare(对同一批 method 回放并比对)。 +3. compare 结果必须 `mismatch=0` 才可交付。 + +测试账号(默认): + +- `liufumingren / 111111` +- 可通过环境变量覆盖: + - `WMS_TEST_USER` + - `WMS_TEST_PASS` + +method 来源与样本来源: + +- method 配置来源:`methods/system.json` +- 样本数据来源(优先最新日志):`wms_system_log` +- 参考日志来源:`wms_api_log`、`wms_operation_log`、`wms_account_login_log` + +执行脚本: + +- `script/method-output-regression.cjs` +- `script/tmp-generate-method-regression-test.cjs`(根据 baseline 自动生成 Egg.js 标注测试) + +临时文件目录规则: + +- 所有临时产物统一输出到 `temp/`。 +- `temp/` 已加入 git 忽略,不纳入提交。 + +执行命令: + +```powershell +# 修改前:生成基线(默认抽样 8 条) +node .\script\method-output-regression.cjs baseline 8 + +# 修改后:执行对比 +node .\script\method-output-regression.cjs compare + +# 生成 Egg.js 标注测试脚本 +node .\script\tmp-generate-method-regression-test.cjs + +# 执行生成的回归测试 +npx egg-bin test temp/generated-tests/system.method-output.generated.test.js +``` + +输出文件: + +- `temp/method-output/method-output-baseline.json` +- `temp/method-output/method-output-baseline.md` +- `temp/method-output/method-output-compare.json` + +一致性比对说明: + +- 为避免误报,脚本会标准化以下波动字段:`token`、`timestamp`、`last_login_at`、`created_at`、`updated_at`、`iat`、`exp`。 +- 403 权限响应同样参与一致性对比,用于防止权限链路被意外改动。 +- 后续所有接口返回数据检测,统一以生成的 Egg.js 标注测试结果为准。 + ## 主要依赖 - egg.js 3.x @@ -70,8 +170,6 @@ npm run dev - `GET /`:健康检查 - `POST /qimen`:奇门接口 - `POST /system`:system 统一入口 -- `POST /api/v1`:旧版 API -- `POST /api/v2`:新版 API - `GET /template/xml/:id`:打印模板 - `GET|POST /auth/printSetting/:code`:打印台设置 @@ -88,6 +186,60 @@ npm run dev - 全局业务 Header(如 `platform`、`project`)设置 - 方法级在线 POST 调试 +## 接口响应规范(system) + +更新时间:2026-03-22 +适用范围: + +- `POST /system` + +统一目标: + +- 统一 `/system` 入口的响应结构与错误码口径,降低调用方分支判断成本。 + +成功响应示例: + +```json +{ + "flag": "success", + "code": 1, + "message": "ok", + "data": {}, + "timestamp": 1773386721 +} +``` + +失败响应示例: + +```json +{ + "flag": "failure", + "code": 401, + "message": "Unauthorized", + "data": null, + "timestamp": 1773386721 +} +``` + +说明: + +- 业务层若已返回 `flag/code/message` 标准结构,将保留并补齐 `timestamp`。 +- 业务层若返回普通对象或数组,控制器将自动包裹到 `data` 字段。 +- HTTP 状态码保持语义(如 400/401/403/500),业务 `code` 默认与 HTTP 状态码一致。 + +当前错误码口径: + +- 400:请求参数错误(缺少 `method`、`v`、`timestamp`、非法 `method`) +- 401:未登录/令牌无效/无令牌 +- 403:无权限访问 +- 406:业务授权状态异常(如仓库有效期) +- 500:服务内部错误 + +实现位置: + +- 响应封装:`app/lib/api_response.js` +- 控制器接入:`app/controller/home.js`(system/pda) + ## 接口文档联动维护(强制) 当出现以下任一变更时,必须同步更新 `methods` 下对应文档: @@ -108,6 +260,11 @@ node .\script\tmp-struct-system-params.cjs ``` 4. 补充自动提取无法覆盖的信息(description/response/errors/枚举约束) +5. 执行 method 输出一致性对比: + +```powershell +node .\script\method-output-regression.cjs compare +``` ## 配置说明 @@ -115,6 +272,53 @@ node .\script\tmp-struct-system-params.cjs - 数据库、Redis、平台配置在对应配置文件中维护 - 敏感信息不要提交到仓库 +## App 能力清单(汇总) + +能力入口文件: + +- `app.js` +- `app/extend/application.js` + +### A. 应用启动能力(app.js) + +- 设置应用根路径:`global.APP_ROOT`、`app.appRoot` +- 启动前初始化动态工厂: + - `OrderDeliveryFactory` + - `OrderItemsFactory` +- 启动时自检扩展能力: + - 缓存方法可用性(`app.setCacheAsync` / `app.getCacheAsync`) + - Message 能力类型检查(`app.Message`) +- 扩展全局日期格式化:`Date.prototype.format('YYYY-MM-DD HH:mm:ss')` + +### B. Application 扩展能力(app/extend/application.js) + +- 业务字典访问能力: + - `businessDict` getter + - `getBusinessTypeName(code)` + - `getOperationCodeName(code)` + - `getPlatformName(code)` + - `getExternalLogTypeName(type)` +- 外部 SOAP 调用能力: + - `wsdl(methodName, args)` +- Redis 缓存能力(cache client): + - `setCacheAsync(cacheKey, data, expireSeconds = 300)` + - `getCacheAsync(cacheKey)` +- Message 扩展能力: + - `Message` getter(返回 MessageClass) + +### C. 迁移完成确认 + +- 原先在 `app.js` 直接挂载的字典映射方法已迁移到 `app/extend/application.js`。 +- 当前 `app.js` 仅保留启动初始化与非方法迁移逻辑,避免双源实现。 + +### D. Method 输出回归能力(质量门禁) + +- 回归脚本:`script/method-output-regression.cjs` +- 基线文件:`temp/method-output/method-output-baseline.json`、`temp/method-output/method-output-baseline.md` +- 对比文件:`temp/method-output/method-output-compare.json` +- 使用方式:先 `baseline`,后 `compare` +- 门禁标准:`mismatch=0` 才允许交付 + ## 功能模块 - 多快递平台对接(快手/PolyAPI 等) @@ -122,12 +326,38 @@ node .\script\tmp-struct-system-params.cjs - 打印与打印台管理 - 仓库/门店管理 - 权限与角色管理 +- 原生扩展算法能力(native/addons) + +## Native 原生扩展能力 + +目录:`native/addons/` + +当前已存在的原生模块: + +- `subset_selector.node`(已在业务代码接入) + - 接入位置:`app/service/apiMethods/test.js` + - 已使用能力:`selectOrders(orders, n, type)` + - 业务用途:对订单及 SKU 集合进行子集筛选/组合选择(用于加速 JS 侧大批量集合计算) + +- `fibonacci_addon.node`(当前未检索到业务调用) + - 现状:仓库中存在产物文件,但暂无 controller/service 调用链路 + +当前接入状态说明: + +- `subset_selector.node` 在 service 构造时通过 `require(app.appRoot + '/native/addons/subset_selector.node')` 动态加载。 +- 若加载失败,日志会记录“C++插件加载失败”,对应方法会因 addon 不可用而无法执行原生算法分支。 + +兼容性提示: + +- Node.js 原生 addon 与运行环境强相关(系统、架构、Node ABI 版本)。 +- 当出现 `ERR_DLOPEN_FAILED` / `is not a valid Win32 application` 时,通常表示 addon 与当前 Node 版本或构建目标不匹配,需要使用目标环境重新编译 addon。 ## 常见问题 - 启动端口默认 6060,可在配置中调整 - 数据库/Redis 连接失败优先检查 `config/config.local.js` - 接口路由映射可查阅 `AI_METHOD_ROUTING.md` +- native addon 加载失败(`ERR_DLOPEN_FAILED`)时,优先检查 Node 版本与 addon 构建目标是否一致 ## 日报维护 diff --git a/SERVICE_API_CHANGE_AUDIT_20260322.md b/SERVICE_API_CHANGE_AUDIT_20260322.md new file mode 100644 index 0000000..3548ca9 --- /dev/null +++ b/SERVICE_API_CHANGE_AUDIT_20260322.md @@ -0,0 +1,719 @@ +# Service 使用与 API 文档联动审计 + +更新时间: 2026-03-22 +适用阶段: Model 重构阶段 4 及后续代码改造 +目的: 在修改 service 前,先确认真实使用链路;若 service 已被使用,则必须同步更新 service、对应 API 文档,并在本文件中记录变更,便于后续复盘。 + +## 1. 执行规则 + +- 任何计划修改的 service,必须先确认是否被 systemMethods、qimenMethods、controller 或其他 service 使用。 +- 只要存在真实调用链,就不能只改底层 service,必须一起评估上游入口与返回结构。 +- 对外暴露为 system/qimen method 的能力,必须同步更新 methods/system.json 或 methods/qimen.json。 +- 每次实际修改完成后,必须在本文件末尾追加一条变更记录。 + +## 2. 本轮已确认的高风险 service 使用链路 + +### 2.1 账号-仓库-角色关联链路 + +#### A. app/service/systems/store.js + +关键风险: + +- 直接使用不存在的 ctx.model.AccountStoreRole。 +- 影响门店申请审核、角色分配、角色列表查询。 + +已确认调用点: + +- app/service/systems/store.js:464 +- app/service/systems/store.js:679 +- app/service/systems/store.js:690 + +上游 system method: + +- app/service/systemMethods/store.js:35 -> store.getStoreRoles +- app/service/systemMethods/store.js:45 -> store.auditApply + +对应 API 文档: + +- methods/system.json:1976 -> store.getStoreRoles +- methods/system.json:1993 -> store.auditApply + +联动要求: + +- 若将 AccountStoreRole 收敛为 AccountStoreEmployee 或其他真实模型,必须同步更新: + - app/service/systems/store.js + - app/service/systemMethods/store.js + - methods/system.json 中 store.getStoreRoles / store.auditApply 的参数、返回结构描述 + +#### B. app/service/systems/auth/user.js + +关键风险: + +- 当前已部分切到 AccountStoreEmployee,但变量名和注释仍保留 accountStoreRole 旧语义。 +- 平台激活逻辑会联动 user.login、user.info、user.changeRole。 + +已确认调用点: + +- app/service/systems/auth/user.js:118 -> changeRole +- app/service/systems/auth/user.js:195 -> info +- app/service/systems/auth/user.js:328 -> findById +- app/service/systems/auth/user.js:877 -> ensurePlatformActiveRole + +上游 system method: + +- app/service/systemMethods/user.js:11 -> user.login +- app/service/systemMethods/user.js:24 -> user.info +- app/service/systemMethods/user.js:29 -> user.changeRole + +对应 API 文档: + +- methods/system.json:2016 附近 -> user.login +- methods/system.json:2051 附近 -> user.info +- methods/system.json:2067 附近 -> user.changeRole + +联动要求: + +- 若修改 activeEmployeeId、employee_id、role_id、roles 列表结构,必须同步更新: + - app/service/systems/auth/user.js + - app/service/systemMethods/user.js + - methods/system.json 中 user.login / user.info / user.changeRole 的返回字段说明 + +#### C. app/service/systems/account_platform.js + +关键风险: + +- 该 service 当前直接依赖 AccountStoreRole 幽灵 key。 +- 虽然尚未发现对外直接暴露的 system method,但它承载的平台激活角色语义与 auth.user 高度耦合。 + +已确认调用点: + +- app/service/systems/account_platform.js:13 -> switchActiveRole +- app/service/systems/account_platform.js:77 -> getActiveRoleByPlatform +- app/service/systems/account_platform.js:159 -> getMultiplePlatformActiveRoles +- app/service/systems/account_platform.js:219 -> getAllPlatformActives +- app/service/systems/account_platform.js:309 -> getAvailableRoles + +间接受影响入口: + +- app/service/systems/auth/user.js:58 +- app/service/systems/auth/user.js:304 +- app/service/systems/auth/user.js:877 + +文档联动策略: + +- 当前没有独立 method 文档入口。 +- 若修改本 service 的输入/输出语义,必须回写到 user.login / user.info / user.changeRole 的 API 文档,因为这些接口会消费平台激活角色结果。 + +### 2.2 动态分表工厂链路 + +#### A. app/service/systemMethods/order.js + +关键风险: + +- 依赖 OrderDeliveryFactory / OrderItemsFactory 获取动态模型。 +- 若工厂 key、返回模型或字段映射调整,会直接影响系统订单接口。 + +已确认调用点: + +- app/service/systemMethods/order.js:18 -> getOrderModels +- app/service/systemMethods/order.js:98 -> list +- 其他 order.* 方法共享同一组动态模型入口 + +对应 API 文档: + +- methods/system.json:422 -> order.getOrderModels +- methods/system.json:439 -> order.list +- methods/system.json:471 -> order.detail +- methods/system.json:503 -> order.listItems +- methods/system.json:535 -> order.stats +- methods/system.json:560 -> order.updateStatus +- methods/system.json:676 -> order.updateDeliveryTime + +联动要求: + +- 若修改动态模型获取方式、字段名或订单明细结构,必须同步更新上述 order.* 文档。 + +#### B. app/service/systems/delivery_order.js 与 app/service/qimenMethods/deliveryorder.js + +关键风险: + +- qimen 发货单接口直接依赖 OrderDeliveryFactory。 +- 若动态分表模型的 key 或查询字段变化,Qimen 接口会受影响。 + +已确认调用点: + +- app/service/systems/delivery_order.js:14 +- app/service/systems/delivery_order.js:311 +- app/service/qimenMethods/deliveryorder.js:7 +- app/service/qimenMethods/deliveryorder.js:8 + +对应 API 文档: + +- methods/qimen.json:14 -> deliveryorder.batchcreate +- methods/qimen.json:88 -> deliveryorder.create +- methods/qimen.json:162 -> deliveryorder.query + +联动要求: + +- 若修改 deliveryorder 查询、创建、历史表读取逻辑,必须同步更新 qimen deliveryorder.* 文档。 + +#### C. app/service/apiMethods/test.js + +关键风险: + +- 存在错误调用名 WmsOrderDeliveryFactory / WmsOrderItemsFactory。 +- 这是内部调试链路,不是正式 API 文档入口,但必须与正式工厂 key 保持一致。 + +已确认调用点: + +- app/service/apiMethods/test.js:50 +- app/service/apiMethods/test.js:51 + +联动要求: + +- 改动时同步修正为 OrderDeliveryFactory / OrderItemsFactory。 +- 无需更新 methods 文档,但必须在本文件记录修复事实。 + +## 3. 本轮结论 + +- 即将进入的关联治理不是纯 model 内部调整,至少会影响 store、user、account_platform、order、deliveryorder 这几条真实业务链路。 +- 因此后续任何代码改动都不能只改 model。 +- 必须按“model -> service -> systemMethods/qimenMethods -> methods 文档 -> 变更记录”的顺序联动处理。 + +## 4. 修改前检查清单 + +- 确认目标 service 是否被上游调用。 +- 确认上游调用属于 system 还是 qimen 入口。 +- 确认 methods/system.json 或 methods/qimen.json 是否存在对应 method。 +- 若返回结构变化,先记录旧字段,再补文档。 +- 修改完成后,在本文件追加一条变更记录。 + +## 5. 变更记录模板 + +### YYYY-MM-DD HH:mm + +- 修改范围: +- 涉及 service: +- 上游入口: +- 更新的 API 文档: +- 返回结构变化: +- 兼容处理: +- 验证方式: + +## 6. 当前记录 + +### 2026-03-22 关联治理准备 + +- 修改范围: 阶段 4 开始前的 service 使用与文档联动审计 +- 涉及 service: + - app/service/systems/store.js + - app/service/systems/auth/user.js + - app/service/systems/account_platform.js + - app/service/systemMethods/order.js + - app/service/systems/delivery_order.js + - app/service/qimenMethods/deliveryorder.js + - app/service/apiMethods/test.js +- 上游入口: + - system: store.getStoreRoles, store.auditApply, user.login, user.info, user.changeRole, order.* + - qimen: deliveryorder.batchcreate, deliveryorder.create, deliveryorder.query +- 更新的 API 文档: 尚未改动代码,本轮只完成审计与联动范围确认 +- 返回结构变化: 暂无 +- 兼容处理: 暂无 +- 验证方式: 通过 service 调用搜索、system/qimen method 搜索、methods 文档映射完成静态核对 + +### 2026-03-22 关联治理执行(第一批) + +- 修改范围: 修复 store 链路中 AccountStoreRole 幽灵模型引用 +- 涉及 service: + - app/service/systems/store.js +- 上游入口: + - system: store.getStoreRoles, store.auditApply +- 更新的 API 文档: + - methods/system.json + - store.getStoreRoles: 补充 code 参数定义 + - store.auditApply: 补充 audit_status/code/store_id/role_ids/reject_reason 参数定义 +- 返回结构变化: 无(维持原有 code/message/data 结构) +- 兼容处理: + - 将账号-门店关系绑定到 AccountStoreEmployee + - 将角色绑定落到 EmployeeRole(employee_id + role_id) + - 保持接口出参与状态码行为不变 +- 验证方式: + - 运行生成的改造前回归样例测试 + - 运行 method-output compare 对比报告 + +### 2026-03-22 关联治理执行(第二批) + +- 修改范围: 修复 account_platform 链路中 AccountStoreRole 幽灵模型引用 +- 涉及 service: + - app/service/systems/account_platform.js +- 上游入口: + - 间接影响 system: user.login, user.info, user.changeRole +- 更新的 API 文档: + - 无直接 method 文档变更(本批未新增/修改 system method 参数) +- 返回结构变化: 无(维持 role_id/role_name/role_code/store_id/store_name/store_code 字段) +- 兼容处理: + - switchActiveRole 保持历史参数名 accountStoreRoleId,内部按 employee_id 落库 + - include 链路由 AccountStoreRole 改为 AccountStoreEmployee + EmployeeRole + Role + Store + - getAvailableRoles 改为从 AccountStoreEmployee/EmployeeRole 聚合返回 +- 验证方式: + - npx egg-bin test test/app/controller/system.method-output.pre-refactor.generated.test.js + - node .\\script\\method-output-regression.cjs compare + - npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js + +### 2026-03-22 关联治理执行(第三批) + +- 修改范围: 清理 model 层残留命名污染(不改接口结构) +- 涉及 service/model: + - app/model/account.js + - app/model/role.js +- 上游入口: + - 间接影响 system 全链路(仅模型关联定义清理) +- 更新的 API 文档: + - 无(接口参数与返回结构未变化) +- 返回结构变化: 无 +- 兼容处理: + - 仅移除 AccountStoreRole 的遗留注释/无效解构,不调整现有 alias +- 验证方式: + - node .\\script\\method-output-regression.cjs compare + - npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js + - npx egg-bin test test/app/controller/system.method-output.batch3.generated.test.js + +### 2026-03-22 样例漂移策略更新 + +- 发现现象: + - 固定历史样例 `system.method-output.pre-refactor.generated.test.js` 因权限/业务数据变化出现与历史快照不一致。 +- 策略调整: + - 每批改造前重新冻结当批 baseline,并生成当批 Egg.js 样例测试。 + - 历史快照保留审计用途,不作为后续批次唯一门禁。 +- 当前批次快照: + - run/method-output-baseline-batch3-20260322_224649.json + - test/app/controller/system.method-output.batch3.generated.test.js + +### 2026-03-22 关联治理执行(第四批) + +- 修改范围: 统一 alias 命名并引入双轨兼容(复数标准名 + 历史别名保留) +- 涉及 service/model: + - app/model/account.js + - app/model/account_store_employee.js + - app/model/role.js + - app/model/store.js + - app/service/systems/account_platform.js + - app/service/systems/auth/user.js +- 上游入口: + - 间接影响 system: user.login, user.info, user.changeRole, store.getStoreRoles +- 更新的 API 文档: + - 无(接口参数与返回结构未变化) +- 返回结构变化: 无 +- 兼容处理: + - 新增标准 alias:accountStoreEmployees / employeeRoles + - 保留历史 alias:accountStoreRoles / accountStoreEmployee / employeeRole + - service 查询切换到新 alias,并在读取层面对旧 alias 做回退兼容 +- 验证方式: + - node .\\script\\method-output-regression.cjs compare + - node .\\script\\tmp-generate-method-regression-test.cjs + - npx egg-bin test temp/generated-tests/system.method-output.generated.test.js + - npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js + +### 2026-03-23 关联治理执行(第四批补充收敛) + +- 修改范围: service 层去除旧 alias 回退依赖,统一使用新 alias(保留 model 兼容别名) +- 涉及 service: + - app/service/systems/account_platform.js + - app/service/systems/auth/user.js +- 上游入口: + - 间接影响 system: user.login, user.info, user.changeRole, store.getStoreRoles +- 更新的 API 文档: + - 无(接口参数与返回结构未变化) +- 返回结构变化: 无 +- 兼容处理: + - account_platform 内部读取改为 employeeRoles 单轨 + - model 层兼容 alias 继续保留,避免外部未迁移调用中断 + - auth/user 中 accountStoreRole 变量语义更新为 accountStoreEmployee +- 验证方式: + - node .\\script\\method-output-regression.cjs baseline 8 + - node .\\script\\method-output-regression.cjs compare + - node .\\script\\tmp-generate-method-regression-test.cjs + - npx egg-bin test temp/generated-tests/system.method-output.generated.test.js + - npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js + +### 2026-03-23 关联治理执行(第五批) + +- 修改范围: 移除 model 层重复兼容 alias,完成重复关联清理 +- 涉及 model: + - app/model/account.js + - app/model/account_store_employee.js + - app/model/role.js + - app/model/store.js +- 上游入口: + - 间接影响 system: user.login, user.info, user.changeRole, store.getStoreRoles +- 更新的 API 文档: + - 无(接口参数与返回结构未变化) +- 返回结构变化: 无 +- 兼容处理: + - 删除旧 alias:accountStoreRoles / employeeRole / accountStoreEmployee(Store.hasMany 语义) + - 保留必要单数 alias:AccountPlatformActive.belongsTo(AccountStoreEmployee).as = accountStoreEmployee +- 验证方式: + - node .\\script\\method-output-regression.cjs baseline 8 + - node .\\script\\method-output-regression.cjs compare + - node .\\script\\tmp-generate-method-regression-test.cjs + - npx egg-bin test temp/generated-tests/system.method-output.generated.test.js + - npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js + +### 2026-03-23 关联治理执行(4.1 全量一致性校验) + +- 修改范围: 对 app/model 全量关联定义与数据库真实外键进行一致性审计(无业务代码改动) +- 审计产物: + - association_fk_consistency_report.md + - temp/association-fk-audit.json +- 审计结论: + - DB 外键 51 条,模型关联 89 条,可直接匹配 53 条 + - 模型定义但 DB 无外键约束 28 条 + - DB 有外键但模型未声明 13 条 + - 动态模型/示例占位无法静态解析 5 条 +- 影响判断: + - 当前 system 输出门禁未受影响,但存在“模型语义与 DB 约束不完全对齐”的技术债 + - 已将高优先级差异并入后续 4.4 规约与治理清单 + +### 2026-03-23 关联治理执行(第六批:receiving 高优先差异第一批) + +- 修改范围: 处理 receiving 链路高优先差异,移除无效模型关联并收敛仓库维度查询条件 +- 涉及 service/model: + - app/model/receiving.js + - app/model/receiving_detail.js + - app/service/systems/storage/receiving.js +- 上游入口: + - 间接影响 system: storage.receiving.getReceivingDetail 及 receiving 相关查询/更新链路 +- 更新的 API 文档: + - 无(接口参数与返回结构未变化) +- 返回结构变化: 无 +- 兼容处理: + - 删除无效关联: `Receiving.hasMany(Storage, foreignKey: 'receiving_id')` + - 删除无效关联: `ReceivingDetail.hasMany(Storage, foreignKey: 'receiving_detail_id')` + - `StoreWarehouse` include/query 统一增加 `warehouse_id + use_status` 过滤,避免跨仓库错关联 + - `create` 流程 `store_name` 统一使用 `store_remask` +- 验证方式: + - node .\\script\\method-output-regression.cjs compare + - node .\\script\\tmp-generate-method-regression-test.cjs + - npx egg-bin test temp/generated-tests/system.method-output.generated.test.js test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js +- 验证结果: + - compare: total=8, mismatch=0 + - tests: 14 passing + +### 2026-03-23 关联治理执行(第七批:4.4 规约文档落地) + +- 修改范围: 形成并落地 eager-loading 与 N+1 风险规约(文档治理,无业务代码改动) +- 涉及文档: + - association_eager_loading_n_plus_one_guideline.md + - association_validation_checklist.md + - model_todo.txt +- 上游入口: + - 无直接 system/qimen 行为变更 +- 更新的 API 文档: + - 无 +- 返回结构变化: 无 +- 兼容处理: + - 将关联查询的最小约束(include attributes、上下文 where、门禁流程)固化为统一规约 +- 验证方式: + - 以第六批回归结果作为当前代码基线(compare mismatch=0,tests 14 passing) + +### 2026-03-23 关联治理执行(第八批:store_warehouse/stock_warehouse 语义收敛) + +- 修改范围: 修复 stock_store 链路中 `StoreWarehouse` 仅按 `store_id` 关联导致的跨仓误匹配风险 +- 涉及 service/model: + - app/service/systems/stock_store.js +- 上游入口: + - 间接影响 system: stock.* 查询链路(库存列表/搜索) +- 更新的 API 文档: + - 无(接口参数与返回结构未变化) +- 返回结构变化: 无 +- 兼容处理: + - `store_stock` include 在 count/findAll/search 三处统一增加 `warehouse_id + use_status` 过滤 + - 保持 `required` 策略不变(列表仍 required=true,搜索路径 required=false) +- 验证方式: + - node .\\script\\method-output-regression.cjs compare + - node .\\script\\tmp-generate-method-regression-test.cjs + - npx egg-bin test temp/generated-tests/system.method-output.generated.test.js test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js +- 验证结果: + - compare: total=8, mismatch=0 + - tests: 14 passing + +### 2026-03-23 关联治理执行(第九批:role/permission 语义收敛) + +- 修改范围: 修复 auth/user 权限链路对禁用角色/权限的过滤缺失问题 +- 涉及 service/model: + - app/service/systems/auth/user.js +- 上游入口: + - 间接影响 system: user.info(权限与菜单加载链路) +- 更新的 API 文档: + - 无(接口参数与返回结构未变化) +- 返回结构变化: 无(仅收敛为“启用角色/启用权限可见”) +- 兼容处理: + - `getPermissions/getMenus` 在 EmployeeRole 查询中增加 Role.status=1 过滤 + - Permission 查询增加 status=1 过滤 + - role_id 与 permission_id 查询集合去重 +- 验证方式: + - node .\\script\\method-output-regression.cjs compare + - node .\\script\\tmp-generate-method-regression-test.cjs + - npx egg-bin test temp/generated-tests/system.method-output.generated.test.js test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js +- 验证结果: + - compare: total=8, mismatch=0 + - tests: 14 passing + +### 2026-03-23 关联治理执行(第十批:role_permission 外键迁移落地) + +- 修改范围: 落地 `role_permission.permission_id -> permission.id` 的可执行迁移脚本与模型类型对齐 +- 涉及 service/model/migration: + - database/migrations/20260323103000-align-role-permission-fk.js + - app/model/role_permission.js +- 上游入口: + - 无直接 system/qimen 返回结构变化 +- 更新的 API 文档: + - 无 +- 返回结构变化: 无 +- 兼容处理: + - 迁移脚本包含保护性校验:存在孤儿数据时直接失败,避免静默脏写 + - down 提供外键回滚与字段类型回退 +- 审计发现: + - `wms_role_permission.permission_id` 存在 4 条孤儿记录(id: 2, 3, 6, 10) + - `wms_role.store_id` 存在 3 条 `0` 哨兵值(当前不满足直接加 FK 条件) +- 验证方式: + - node .\\script\\method-output-regression.cjs compare + - node .\\script\\tmp-generate-method-regression-test.cjs + - npx egg-bin test temp/generated-tests/system.method-output.generated.test.js test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js +- 实际执行结果: + - 已创建备份表并落库: + - `wms_role_permission_orphan_backup_20260323`(4 条) + - `wms_role_store_zero_backup_20260323`(3 条) + - 已清洗数据: + - 删除 `wms_role_permission.permission_id` 孤儿 4 条 + - 将 `wms_role.store_id=0` 修正为 `NULL` 共 3 条 + - 已执行 DDL: + - `wms_role_permission.permission_id` -> `int(11)` + - 新增外键 `fk_wms_role_permission_permission`(ON UPDATE RESTRICT, ON DELETE CASCADE) + - SequelizeMeta 已登记 `20260323103000-align-role-permission-fk.js` + - 迁移后复核: 孤儿计数=0,role_store_zero=0 + - 回归结果: + - compare: total=8, mismatch=0 + - tests: 14 passing + +### 2026-03-23 关联治理执行(第十一批:role.store_id 外键策略落地) + +- 修改范围: 落地 `wms_role.store_id -> wms_store.id` 外键策略(NULL 语义) +- 涉及 migration: + - database/migrations/20260323113000-add-role-store-fk.js +- 上游入口: + - 无直接 system/qimen 返回结构变化 +- 更新的 API 文档: + - 无 +- 返回结构变化: 无 +- 兼容处理: + - `store_id` 字段类型对齐为 `bigint(20) unsigned NULL` + - 新增索引 `idx_store_id` + - 外键策略采用 `ON DELETE SET NULL`,保留历史角色记录的 NULL 语义 +- 实际执行结果: + - 外键 `fk_wms_role_store` 已生效(ON UPDATE RESTRICT, ON DELETE SET NULL) + - `wms_role` 孤儿数据复核: 0 + - SequelizeMeta 已登记 `20260323113000-add-role-store-fk.js` +- 验证方式: + - node .\\script\\method-output-regression.cjs compare + - node .\\script\\tmp-generate-method-regression-test.cjs + - npx egg-bin test temp/generated-tests/system.method-output.generated.test.js test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js +- 回归结果: + - compare: total=8, mismatch=0 + - tests: 14 passing + +### 2026-03-23 关联治理执行(第十二批:store_warehouse/stock_warehouse 模型层语义治理) + +- 修改范围: 收敛 `store_stock` 关联的模型层复合键表达,统一 include 构造入口 +- 涉及 service/model: + - app/model/store_warehouse.js + - app/model/stock_warehouse.js + - app/model/receiving.js + - app/service/systems/stock_store.js + - app/service/systems/storage/receiving.js +- 上游入口: + - 间接影响 system: stock.* / storage.receiving.* 查询链路 +- 更新的 API 文档: + - 无(接口参数与返回结构未变化) +- 返回结构变化: 无 +- 兼容处理: + - StoreWarehouse 新增 `buildScopedWhere` 与 `buildStoreStockInclude`,统一生成 `warehouse_id + use_status` 约束 + - 复合键语义关联统一显式 `constraints:false`,避免单列外键误解 + - service 查询改为复用模型构造器,保持原有 `required` 语义不变 +- 验证方式: + - node .\\script\\method-output-regression.cjs compare + - node .\\script\\tmp-generate-method-regression-test.cjs + - npx egg-bin test temp/generated-tests/system.method-output.generated.test.js test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js +- 回归结果: + - compare: total=8, mismatch=0 + - tests: 14 passing + +### 2026-03-23 关联治理执行(第十三批:include alias 一致性收尾扫描) + +- 修改范围: 阶段 4 收尾检查(全量 include alias 一致性扫描,无业务代码改动) +- 涉及范围: + - app/model/**/*.js(association `as` 定义) + - app/service/**/*.js(include `as` 使用) +- 上游入口: + - 无直接 system/qimen 行为变更 +- 更新的 API 文档: + - 无 +- 返回结构变化: 无 +- 扫描方法: + - 全量检索 model association 与 service include 的 alias 使用 + - 执行自动差集比对(service alias - model alias) +- 扫描结果: + - model alias 总数: 48 + - 差集可疑项: 0 + - 结论: 未发现 include alias 不一致问题 +- 验证方式: + - 通过一次性 Node 差集脚本执行 `service alias - model alias` 自动比对(临时脚本未入库) + +### 2026-03-23 关联治理执行(第十四批:permission.parent_id 自关联约束落地) + +- 修改范围: 落地 `wms_permission.parent_id -> wms_permission.id` 自关联外键,并统一根节点语义 +- 涉及 service/model/migration: + - database/migrations/20260323123000-add-permission-parent-fk.js + - app/model/permission.js + - app/service/systems/auth/user.js +- 上游入口: + - 间接影响 system: user.info(菜单树构建) +- 更新的 API 文档: + - 无(接口参数与返回结构未变化) +- 返回结构变化: 无 +- 兼容处理: + - 根节点语义由 `parent_id=0` 规范为 `parent_id IS NULL` + - 模型 setter 兼容历史输入:`0 -> NULL` + - 菜单树构建逻辑根判断由 `parent_id===0` 收敛为 `!parent_id` +- 实际执行结果: + - 落库复核:`root_zero_after=0`、`root_null_after=42`、`orphan_after=0` + - 外键 `fk_wms_permission_parent` 已生效(ON UPDATE RESTRICT, ON DELETE SET NULL) + - SequelizeMeta 已登记 `20260323123000-add-permission-parent-fk.js` + - 触发器状态:目标库因权限限制(binlog + SUPER)未创建触发器,采用应用层归一化方案替代 +- 验证方式: + - node .\script\method-output-regression.cjs compare + - node .\script\tmp-generate-method-regression-test.cjs + - npx egg-bin test temp/generated-tests/system.method-output.generated.test.js test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js +- 回归结果: + - compare: total=8, mismatch=0 + - tests: 14 passing + +### 2026-03-23 模型能力治理执行(第十五批:阶段 5.1 清理清单盘点) + +- 修改范围: 阶段 5.1(识别应迁移到 service 层的方法能力,文档治理) +- 涉及文档: + - model_cleanup_list.md + - model_todo.txt +- 上游入口: + - 无直接 system/qimen 行为变更 +- 更新的 API 文档: + - 无 +- 返回结构变化: 无 +- 盘点结论: + - 模型方法总数: 102 + - 第一批应迁移(P1)聚焦: EntryOrder / EntryItems / Storage / RolePermission / Store + - 第一批无调用可清理(P2)已形成清单,待阶段 5.2 执行删除前复核 +- 验证方式: + - 静态扫描 model 方法清单与引用关系(仅文档盘点,无业务代码改动) + +### 2026-03-23 模型能力治理执行(第十六批:阶段 5.2 第一批无调用方法清理) + +- 修改范围: 清理 model 层第一批无调用静态方法(低风险) +- 涉及 model: + - app/model/api_app.js + - app/model/interface_type.js + - app/model/print_item.js +- 上游入口: + - 无直接 system/qimen 行为变更 +- 更新的 API 文档: + - 无 +- 返回结构变化: 无 +- 兼容处理: + - 清理前执行全局引用复核,确认仅在定义处出现 + - 仅删除静态 helper,不触碰关联定义与实例方法 +- 删除项: + - ApiApp.findByAppKey / ApiApp.findByQimenConfig + - InterfaceType.findByCode / InterfaceType.findEnabled + - PrintItem.getGroupFields / PrintItem.getTableConfigs +- 验证方式: + - node .\script\method-output-regression.cjs compare + - node .\script\tmp-generate-method-regression-test.cjs + - npx egg-bin test temp/generated-tests/system.method-output.generated.test.js test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js +- 回归结果: + - compare: total=8, mismatch=0 + - tests: 14 passing + +### 2026-03-23 模型能力治理执行(第十七批:阶段 5.2 第二批无调用方法清理) + +- 修改范围: 清理 model 层第二批无调用静态方法(低风险) +- 涉及 model: + - app/model/i18n_translation.js + - app/model/stock_store.js +- 上游入口: + - 无直接 system/qimen 行为变更 +- 更新的 API 文档: + - 无 +- 返回结构变化: 无 +- 兼容处理: + - 清理前已完成删除前引用复核(service/controller/test/script 全仓扫描) + - 仅删除静态 helper,不触碰关联定义、字段定义与实例方法 +- 删除项: + - I18nTranslation.getTranslation / I18nTranslation.batchGetTranslations / I18nTranslation.getProjectTranslations / I18nTranslation.upsertTranslation / I18nTranslation.getUntranslated + - StockStore.findByItemCode / StockStore.findByStore +- 验证方式: + - node .\script\method-output-regression.cjs compare + - node .\script\tmp-generate-method-regression-test.cjs + - npx egg-bin test temp/generated-tests/system.method-output.generated.test.js + - npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js +- 回归结果: + - compare: total=8, mismatch=0 + - generated regression: 8 passing + - smoke: 6 passing + - tests: 14 passing +- 回归结果: + - compare: total=8, mismatch=0 + - generated regression: 8 passing + - smoke: 6 passing + - tests: 14 passing + +### 2026-03-23 模型能力治理执行(第十八批:阶段 5.2 P1 第一组迁移) + +- 修改范围: 将 EntryOrder / EntryItems 的内部静态方法迁移到 service,收敛 model 职责 +- 涉及 service/model: + - app/service/systems/entry_order.js + - app/model/entry_order.js + - app/model/entry_items.js +- 上游入口: + - 无直接新增 system/qimen method;属于内部服务能力收敛 +- 更新的 API 文档: + - 无(对外接口参数与返回结构未变化) +- 返回结构变化: 无 +- 兼容处理: + - 迁移 `EntryOrder.findByOrderCode/findByStatus/getStatsByWarehouse/updateSyncStatus/updateOrderStatus/calculateReceivedQuantities` + - 迁移 `EntryItems.batchUpdateReceived/getOrderProgress` + - `calculateReceivedQuantities` 改为 service 侧显式聚合 `wms_storage`,避免 model 版相关子查询别名不稳定 +- 验证方式: + - node .\script\method-output-regression.cjs compare + - node .\script\tmp-generate-method-regression-test.cjs + - npx egg-bin test temp/generated-tests/system.method-output.generated.test.js + - npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js + +### 2026-03-23 模型能力治理执行(第十九批:阶段 5.2 P1 第二组迁移) + +- 修改范围: 将 Storage 的内部静态方法迁移到 service,收敛 model 职责 +- 涉及 service/model: + - app/service/systems/storage/index.js + - app/model/storage.js +- 上游入口: + - 无直接新增 system/qimen method;属于内部服务能力收敛 +- 更新的 API 文档: + - 无(对外接口参数与返回结构未变化) +- 返回结构变化: 无 +- 兼容处理: + - 迁移 `Storage.findByStockAndBatch/findBySpace/findAvailableByWarehouse/findExpiringSoon/updateQuantity/lockQuantity/unlockQuantity/allocateQuantity/getStockSummary/getSpaceUsage` + - 模型层仅保留实例行为与关联定义,跨记录聚合与更新能力归并到 service +- 验证方式: + - node .\script\method-output-regression.cjs compare + - node .\script\tmp-generate-method-regression-test.cjs + - npx egg-bin test temp/generated-tests/system.method-output.generated.test.js + - npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js \ No newline at end of file diff --git a/app.js b/app.js index b48fb1a..353440d 100644 --- a/app.js +++ b/app.js @@ -1,39 +1,12 @@ // app.js const path = require('path'); -const businessDict = require('./app/dict/businessDict.js'); - // 直接导出函数,而不是类 module.exports = app => { // 设置全局应用根目录 global.APP_ROOT = path.resolve(__dirname, './'); app.appRoot = APP_ROOT; - // ========== 挂载字典到 app ========== - app.businessDict = businessDict; - - // 添加字典工具方法 - app.getBusinessTypeName = code => { - const dict = app.businessDict.BUSINESS_TYPE || {}; - for (const key in dict) { - if (dict[key].code === code) { - return dict[key].name; - } - } - return code; - }; - - app.getOperationCodeName = code => { - return app.businessDict.OPERATION_CODE?.[code] || code; - }; - app.getPlatformName = code => { - return app.businessDict.PLATFORM_CODE?.[code] || code; - }; - - app.getExternalLogTypeName = type => { - return app.businessDict.EXTERNAL_LOG_TYPE?.[type] || type; - }; - - app.logger.info('✅ 业务字典已挂载到 app'); + app.logger.info('✅ Application 扩展能力已加载'); // 初始化工厂 app.beforeStart(async () => { // skip factory init when model layer is absent (e.g. during tests) diff --git a/app/controller/api_v2.js b/app/controller/api_v2.js deleted file mode 100644 index 3f7a33e..0000000 --- a/app/controller/api_v2.js +++ /dev/null @@ -1,169 +0,0 @@ -const { Controller } = require('egg'); - -class ApiV2Controller extends Controller { - async index() { - const { ctx, service } = this; - ctx.query_count = 1; - const startTime = Date.now(); - const logData = { - method: '', - v: '', - url: ctx.request.href, - created_at: new Date(), - body: '', - headers: JSON.stringify(ctx.headers), - result: '', - use_time: 0, - auth: '', - store_id: null, - }; - - try { - const getParams = ctx.query; - logData.method = getParams.method || ''; - logData.v = getParams.v || ''; - // 验证必要参数 - if (!service.system.validateParams(getParams)) { - const errorMsg = '参数缺失或错误'; - const response = this.errorResponse(errorMsg, 'json'); - logData.result = response; - service.system.saveLog(logData, startTime); - ctx.body = response; - ctx.type = 'application/json'; - return; - } - const authHeader = ctx.headers.authorization; - ctx.device = ctx.headers.device; - ctx.project = ctx.headers.project; - - // 处理method参数 - const method = getParams.method; - const methods = method.split('.'); - const actionName = methods.pop(); - const className = methods - .map((item, index) => - (index === methods.length - 1 ? item : item) - ) - .join('.'); - - // 获取JSON数据 - let jsonData = ''; - if (ctx.request.rawBody) { - jsonData = ctx.request.rawBody; - } else { - jsonData = await new Promise((resolve, reject) => { - let data = ''; - ctx.req.on('data', chunk => { - data += chunk; - }); - ctx.req.on('end', () => { - resolve(data); - }); - ctx.req.on('error', reject); - }); - } - - jsonData = jsonData ? String(jsonData) : ''; - logData.body = jsonData; - if (!jsonData || jsonData.trim() === '') { - throw new Error('json数据为空'); - } - try { - jsonData = JSON.parse(jsonData); - } catch (e) { - throw new Error('json数据解析错误'); - } - - // 调用扁平 dispatcher 服务 - const { isLog, result } = await service.dispatcher.invoke( - getParams.method, - jsonData, - authHeader, - ctx - ); - logData.result = typeof result === 'string' ? result : JSON.stringify(result); - if (ctx.user) { - logData.auth = JSON.stringify(ctx.user); - logData.store_id = ctx.user.store_id; - } - // 保存原来的日志逻辑仍然通过 system.saveLog - if (isLog) { - service.system.saveLog(logData, startTime); - } - if (result.status && result.status !== 200) { - // propagate failure message - ctx.body = result.message ? { message: result.message } : result.data; - } else { - ctx.body = result.data; - } - ctx.type = 'application/json'; - ctx.status = result.status || 200; - } catch (error) { - ctx.status = 500; - console.log(error); - const response = this.errorResponse('接口错误: ' + error.message, 'json'); - logData.result = typeof response === 'string' ? response : JSON.stringify(response); - service.system.saveLog(logData, startTime); - ctx.body = response; - ctx.type = 'application/json'; - } - } - - validateParams(params) { - const required = [ 'method', 'v', 'format', 'timestamp' ]; - - for (const field of required) { - if (!params[field]) { - return false; - } - } - - if (typeof params.method !== 'string' || !params.method.includes('.')) { - return false; - } - - return true; - } - - errorResponse(message, format = 'json') { - const timestamp = Math.floor(Date.now() / 1000); - - if (format.toLowerCase() === 'xml') { - return ` - - failure - 0 - ${this.escapeXml(message)} -`; - } - - return { - flag: false, - message, - code: 0, - timestamp, - }; - } - - escapeXml(unsafe) { - if (!unsafe) return ''; - return unsafe.replace(/[<>&'\"]/g, c => { - switch (c) { - case '<': - return '<'; - case '>': - return '>'; - case '&': - return '&'; - case "'": - return '''; - case '"': - return '"'; - default: - return c; - } - }); - } -} - -module.exports = ApiV2Controller; diff --git a/app/controller/home.js b/app/controller/home.js index 03786b0..3dca6e7 100644 --- a/app/controller/home.js +++ b/app/controller/home.js @@ -1,9 +1,10 @@ const { Controller, } = require('egg'); +const { toSuccess, toFailure } = require('../lib/api_response'); class HomeController extends Controller { - async testSendData(){ + async testSendData() { await this.ctx.service.systems.print.index.test(); this.ctx.body = 'ok'; } @@ -13,97 +14,6 @@ class HomeController extends Controller { } = this; ctx.body = 'pong'; } - async v1() { - const { - ctx, - service, - } = this; - const startTime = Date.now(); - // 初始化日志数据 - const logData = { - app_key: '', - method: '', - sign: '', - costomer_id: '', - v: '', - url: ctx.request.href, - created_at: new Date(), - body: '', - result: '', - use_time: 0, - }; - try { - const getParams = ctx.query; - logData.method = getParams.method || ''; - logData.v = getParams.v || ''; - // 验证必要参数 - if (!this.validateParams(getParams)) { - const errorMsg = '参数缺失或错误'; - const response = this.errorResponse(errorMsg, 'json'); - logData.result = response; - await this.saveLog(logData, startTime); - - ctx.body = response; - ctx.type = 'application/json'; - return; - } - - // 处理method参数 - const method = getParams.method; - const methods = method.split('.'); - const actionName = methods.pop(); - const className = methods.map((item, index) => - (index === methods.length - 1 ? item : item) - ).join('.'); - - // 获取XML数据 - let jsonData = ''; - if (ctx.request.rawBody) { - // 使用 rawBody 获取原始请求体 - jsonData = ctx.request.rawBody; - } else { - // 如果没有 rawBody,尝试从流中读取 - jsonData = await new Promise((resolve, reject) => { - let data = ''; - ctx.req.on('data', chunk => { - data += chunk; - }); - ctx.req.on('end', () => { - resolve(data); - }); - ctx.req.on('error', reject); - }); - } - - // 确保 xmlData 是字符串 - jsonData = jsonData ? String(jsonData) : ''; - logData.body = jsonData; - if (!jsonData || jsonData.trim() === '') { - throw new Error('json数据为空'); - } - try { - jsonData = JSON.parse(jsonData); - } catch (e) { - throw new Error('json数据解析错误'); - } - // 调用业务方法 - const result = await service.api.callMethod(className, actionName, jsonData, getParams.format); - - // 记录成功响应 - logData.result = typeof result === 'string' ? result : JSON.stringify(result); - await this.saveLog(logData, startTime); - - ctx.body = result; - ctx.type = getParams.format === 'xml' ? 'application/xml' : 'application/json'; - } catch (error) { - ctx.logger.error('调用接口失败返回数据', error); - const response = this.errorResponse('接口错误: ' + error.message, ctx.query.format || 'json'); - logData.result = typeof response === 'string' ? response : JSON.stringify(response); - await this.saveLog(logData, startTime); - ctx.body = response; - ctx.type = ctx.query.format === 'xml' ? 'application/xml' : 'application/json'; - } - } async qimen() { const { ctx, @@ -198,9 +108,9 @@ class HomeController extends Controller { // 入库单提取 try { warehouseCode = xmlArray.request?.entryOrder?.warehouseCode || - xmlArray.request?.deliveryOrder?.warehouseCode || - ''; - } catch (e) {} + xmlArray.request?.deliveryOrder?.warehouseCode || + ''; + } catch (e) { } } if (warehouseCode && customerId) { // 验证接口是否存在且启用 @@ -273,7 +183,7 @@ class HomeController extends Controller { } validateParams(params) { - const required = [ 'method', 'v', 'format', 'timestamp' ]; + const required = ['method', 'v', 'format', 'timestamp']; for (const field of required) { if (!params[field]) { @@ -289,7 +199,7 @@ class HomeController extends Controller { return true; } validateQimenParams(params) { - const required = [ 'app_key', 'method', 'v', 'format', 'sign_method', 'sign', 'timestamp' ]; + const required = ['app_key', 'method', 'v', 'format', 'sign_method', 'sign', 'timestamp']; for (const field of required) { if (!params[field]) { @@ -403,13 +313,17 @@ class HomeController extends Controller { const getParams = ctx.query; logData.method = getParams.method || ''; logData.v = getParams.v || ''; - // 验证必要参数 - if (!service.system.validateParams(getParams)) { - const errorMsg = '参数缺失或错误'; - const response = this.errorResponse(errorMsg, 'json'); + const requestCheck = service.system.validateRequestContext(getParams, ctx.headers); + if (!requestCheck.ok) { + const response = toFailure({ + message: requestCheck.message, + httpStatus: requestCheck.status, + code: requestCheck.code, + }); logData.result = response; service.system.saveLog(logData, startTime); ctx.body = response; + ctx.status = requestCheck.status; ctx.type = 'application/json'; return; } @@ -464,13 +378,26 @@ class HomeController extends Controller { if (isLog) { service.system.saveLog(logData, startTime); } - ctx.body = result.data; + if (result.status && result.status !== 200) { + ctx.body = toFailure({ + message: result.message || '请求失败', + httpStatus: result.status, + code: result.code, + data: result.data || null, + }); + } else { + ctx.body = toSuccess(result.data); + } ctx.type = 'application/json'; ctx.status = result.status || 200; } catch (error) { ctx.status = 500; console.log(error); - const response = this.errorResponse('接口错误: ' + error.message, 'json'); + const response = toFailure({ + message: '接口错误: ' + error.message, + httpStatus: 500, + code: 500, + }); logData.result = typeof response === 'string' ? response : JSON.stringify(response); service.system.saveLog(logData, startTime); ctx.body = response; @@ -506,13 +433,17 @@ class HomeController extends Controller { const getParams = ctx.query; logData.method = getParams.method || ''; logData.v = getParams.v || ''; - // 验证必要参数 - if (!service.system.validateParams(getParams)) { - const errorMsg = '参数缺失或错误'; - const response = this.errorResponse(errorMsg, 'json'); + const requestCheck = service.system.validateRequestContext(getParams, ctx.headers); + if (!requestCheck.ok) { + const response = toFailure({ + message: requestCheck.message, + httpStatus: requestCheck.status, + code: requestCheck.code, + }); logData.result = response; service.system.saveLog(logData, startTime); ctx.body = response; + ctx.status = requestCheck.status; ctx.type = 'application/json'; return; } @@ -569,13 +500,26 @@ class HomeController extends Controller { if (isLog) { service.system.saveLog(logData, startTime); } - ctx.body = result.data; + if (result.status && result.status !== 200) { + ctx.body = toFailure({ + message: result.message || '请求失败', + httpStatus: result.status, + code: result.code, + data: result.data || null, + }); + } else { + ctx.body = toSuccess(result.data); + } ctx.type = 'application/json'; ctx.status = result.status || 200; } catch (error) { ctx.status = 500; console.log(error); - const response = this.errorResponse('接口错误: ' + error.message, 'json'); + const response = toFailure({ + message: '接口错误: ' + error.message, + httpStatus: 500, + code: 500, + }); logData.result = typeof response === 'string' ? response : JSON.stringify(response); service.system.saveLog(logData, startTime); ctx.body = response; diff --git a/app/extend/application.js b/app/extend/application.js index 04e6d89..eca239c 100644 --- a/app/extend/application.js +++ b/app/extend/application.js @@ -4,8 +4,30 @@ class MessageClass { } } const soap = require('soap'); +const businessDict = require('../dict/businessDict'); const MESSAGE_CLASS = Symbol('Application#Message'); module.exports = { + get businessDict() { + return businessDict; + }, + getBusinessTypeName(code) { + const dict = this.businessDict.BUSINESS_TYPE || {}; + for (const key in dict) { + if (dict[key].code === code) { + return dict[key].name; + } + } + return code; + }, + getOperationCodeName(code) { + return this.businessDict.OPERATION_CODE?.[code] || code; + }, + getPlatformName(code) { + return this.businessDict.PLATFORM_CODE?.[code] || code; + }, + getExternalLogTypeName(type) { + return this.businessDict.EXTERNAL_LOG_TYPE?.[type] || type; + }, async wsdl(methodName, args) { try { const wsdlUrl = "http://ye4s.com/webservice/ws?wsdl"; diff --git a/app/lib/api_response.js b/app/lib/api_response.js new file mode 100644 index 0000000..a6ebac4 --- /dev/null +++ b/app/lib/api_response.js @@ -0,0 +1,59 @@ +'use strict'; + +function nowTimestamp() { + return Math.floor(Date.now() / 1000); +} + +function isObject(value) { + return value && typeof value === 'object' && !Array.isArray(value); +} + +function isStandardPayload(payload) { + return isObject(payload) + && Object.prototype.hasOwnProperty.call(payload, 'flag') + && Object.prototype.hasOwnProperty.call(payload, 'code') + && Object.prototype.hasOwnProperty.call(payload, 'message'); +} + +function toSuccess(payload, message = 'ok') { + if (isStandardPayload(payload)) { + const normalized = { + ...payload, + flag: payload.flag === true || payload.flag === 'success' ? 'success' : payload.flag, + }; + if (!Object.prototype.hasOwnProperty.call(normalized, 'timestamp')) { + normalized.timestamp = nowTimestamp(); + } + return normalized; + } + + return { + flag: 'success', + code: 1, + message, + data: payload ?? null, + timestamp: nowTimestamp(), + }; +} + +function toFailure(options = {}) { + const { + message = '请求失败', + httpStatus = 500, + code, + data = null, + } = options; + + return { + flag: 'failure', + code: typeof code === 'number' ? code : httpStatus, + message, + data, + timestamp: nowTimestamp(), + }; +} + +module.exports = { + toSuccess, + toFailure, +}; diff --git a/app/model/account.js b/app/model/account.js index 184c5c5..74846d6 100644 --- a/app/model/account.js +++ b/app/model/account.js @@ -133,12 +133,9 @@ module.exports = app => { // 关联关系 Account.associate = function(models) { const { AccountStoreEmployee, AccountPlatformActive } = app.model; - /* if (models.AccountStoreRole) { - - }*/ Account.hasMany(AccountStoreEmployee, { foreignKey: 'account_id', - as: 'accountStoreRoles', + as: 'accountStoreEmployees', }); Account.hasMany(AccountPlatformActive, { foreignKey: 'account_id', diff --git a/app/model/account_store_employee.js b/app/model/account_store_employee.js index b8c96e2..60cf702 100644 --- a/app/model/account_store_employee.js +++ b/app/model/account_store_employee.js @@ -94,7 +94,7 @@ module.exports = app => { }); AccountStoreEmployee.hasMany(EmployeeRole, { foreignKey: 'employee_id', - as: 'employeeRole', + as: 'employeeRoles', }); AccountStoreEmployee.hasMany(Receiving, { foreignKey: 'creator_id', diff --git a/app/model/api_app.js b/app/model/api_app.js index 2273d52..51e9cfe 100644 --- a/app/model/api_app.js +++ b/app/model/api_app.js @@ -288,22 +288,5 @@ module.exports = app => { return generatedSignature === signature; }; - // 类方法 - 根据AppKey查找 - ApiApp.findByAppKey = async function(appKey) { - return await this.findOne({ - where: { self_app_key: appKey }, - }); - }; - - // 类方法 - 根据奇门配置查找 - ApiApp.findByQimenConfig = async function(appKey, customerId) { - return await this.findOne({ - where: { - qimen_app_key: appKey, - qimen_customer_id: customerId, - }, - }); - }; - return ApiApp; }; diff --git a/app/model/entry_items.js b/app/model/entry_items.js index 5eb9cb1..6af2ecc 100644 --- a/app/model/entry_items.js +++ b/app/model/entry_items.js @@ -191,74 +191,6 @@ module.exports = app => { }; }; - // 静态方法 - 批量更新收货数量(带验证) - EntryItems.batchUpdateReceived = async function(app, updates, options = {}) { - const transaction = options.transaction || await app.model.transaction(); - - try { - // 先检查所有更新是否合法 - for (const update of updates) { - const { id, quantity } = update; - const item = await app.model.EntryItems.findByPk(id, { transaction }); - - if (!item) { - throw new Error(`入库明细 ${id} 不存在`); - } - - // 验证数量 - item.validateReceiveQuantity(quantity); - } - - // 执行更新 - for (const update of updates) { - const { id, quantity } = update; - const item = await app.model.EntryItems.findByPk(id, { transaction }); - - const newReceived = (item.received_quantity || 0) + quantity; - await item.update({ - received_quantity: newReceived, - }, { transaction }); - } - - if (!options.transaction) { - await transaction.commit(); - } - - return { success: true }; - } catch (error) { - if (!options.transaction) { - await transaction.rollback(); - } - throw error; - } - }; - - // 静态方法 - 获取入库单总进度 - EntryItems.getOrderProgress = async function(app, orderId) { - const items = await app.model.EntryItems.findAll({ - where: { order_id: orderId }, - attributes: [ - [ app.Sequelize.fn('SUM', app.Sequelize.col('count')), 'total_plan' ], - [ app.Sequelize.fn('SUM', app.Sequelize.col('received_quantity')), 'total_received' ], - [ app.Sequelize.fn('COUNT', app.Sequelize.col('id')), 'item_count' ], - ], - raw: true, - }); - - const result = items[0] || {}; - const totalPlan = parseInt(result.total_plan) || 0; - const totalReceived = parseInt(result.total_received) || 0; - - return { - total_plan: totalPlan, - total_received: totalReceived, - total_remaining: Math.max(0, totalPlan - totalReceived), - item_count: parseInt(result.item_count) || 0, - progress_percent: totalPlan > 0 ? Math.min(100, Math.round((totalReceived / totalPlan) * 100)) : 0, - is_completed: totalReceived >= totalPlan, - }; - }; - // 钩子函数 - 保存前验证 EntryItems.beforeSave(async (instance, options) => { const received = instance.received_quantity || 0; diff --git a/app/model/entry_order.js b/app/model/entry_order.js index 6de6b95..8f90828 100644 --- a/app/model/entry_order.js +++ b/app/model/entry_order.js @@ -275,237 +275,5 @@ module.exports = app => { return this.is_enabled === 1 && !this.deleted_at; }; - // 静态方法 - EntryOrder.findByOrderCode = async function(app, entryOrderCode, warehouseId, storeId) { - return await app.model.EntryOrder.findOne({ - where: { - entry_order_code: entryOrderCode, - warehouse_id: warehouseId, - store_id: storeId, - is_enabled: 1, - deleted_at: null, - }, - include: [ - { - model: app.model.Store, - as: 'warehouse', - attributes: [ 'store_name', 'store_code' ], - }, - { - model: app.model.Store, - as: 'store', - attributes: [ 'store_name' ], - }, - { - model: app.model.EntryItems, - as: 'items', - include: [{ - model: app.model.StockWarehouse, - as: 'stock', - attributes: [ 'product_code', 'product_name' ], - }], - }, - ], - }); - }; - - EntryOrder.findByStatus = async function(app, status, params = {}) { - const { warehouse_id, store_id, start_date, end_date, page = 1, pageSize = 20 } = params; - - const where = { - order_status: status, - is_enabled: 1, - deleted_at: null, - }; - - if (warehouse_id) { - where.warehouse_id = warehouse_id; - } - - if (store_id) { - where.store_id = store_id; - } - - if (start_date || end_date) { - where.created_at = {}; - if (start_date) { - where.created_at[app.Sequelize.Op.gte] = start_date; - } - if (end_date) { - where.created_at[app.Sequelize.Op.lte] = end_date; - } - } - - const { count, rows } = await app.model.EntryOrder.findAndCountAll({ - where, - include: [ - { - model: app.model.Store, - as: 'warehouse', - attributes: [ 'store_name' ], - }, - { - model: app.model.Store, - as: 'store', - attributes: [ 'store_name' ], - }, - ], - order: [[ 'created_at', 'DESC' ]], - offset: (page - 1) * pageSize, - limit: parseInt(pageSize), - distinct: true, - }); - - return { - list: rows, - pagination: { - page: parseInt(page), - pageSize: parseInt(pageSize), - total: count, - totalPages: Math.ceil(count / pageSize), - }, - }; - }; - - EntryOrder.getStatsByWarehouse = async function(app, warehouseId, startDate, endDate) { - const where = { - warehouse_id: warehouseId, - is_enabled: 1, - deleted_at: null, - }; - - if (startDate || endDate) { - where.created_at = {}; - if (startDate) { - where.created_at[app.Sequelize.Op.gte] = startDate; - } - if (endDate) { - where.created_at[app.Sequelize.Op.lte] = endDate; - } - } - - const result = await app.model.EntryOrder.findAll({ - attributes: [ - 'order_status', - [ app.Sequelize.fn('COUNT', app.Sequelize.col('id')), 'count' ], - [ app.Sequelize.fn('SUM', app.Sequelize.col('total_order_lines')), 'total_lines' ], - ], - where, - group: [ 'order_status' ], - raw: true, - }); - - const stats = { - pending: 0, - confirmed: 0, - partial_received: 0, - completed: 0, - cancelled: 0, - total: 0, - total_lines: 0, - }; - - result.forEach(item => { - const status = item.order_status.toLowerCase(); - if (stats[status] !== undefined) { - stats[status] = parseInt(item.count) || 0; - } - stats.total += parseInt(item.count) || 0; - stats.total_lines += parseInt(item.total_lines) || 0; - }); - - return stats; - }; - - EntryOrder.updateSyncStatus = async function(app, orderId, status, message = null) { - const order = await app.model.EntryOrder.findByPk(orderId); - - if (!order) { - throw new Error('入库单不存在'); - } - - const updateData = { - sync_status: status, - }; - - if (message !== null) { - updateData.sync_message = message; - } - - return await order.update(updateData); - }; - - EntryOrder.updateOrderStatus = async function(app, orderId, status) { - const order = await app.model.EntryOrder.findByPk(orderId); - - if (!order) { - throw new Error('入库单不存在'); - } - - const validTransitions = { - PENDING: [ 'CONFIRMED', 'CANCELLED' ], - CONFIRMED: [ 'PARTIAL_RECEIVED', 'COMPLETED', 'CANCELLED' ], - PARTIAL_RECEIVED: [ 'COMPLETED', 'CANCELLED' ], - CREATED: [ 'PENDING', 'CANCELLED' ], - CREATING: [ 'PENDING', 'CANCELLED' ], - }; - - const allowedTransitions = validTransitions[order.order_status]; - if (!allowedTransitions || !allowedTransitions.includes(status)) { - throw new Error(`状态从${order.order_status}转换到${status}不被允许`); - } - - return await order.update({ order_status: status }); - }; - - EntryOrder.calculateReceivedQuantities = async function(app, orderId) { - // 这里需要根据实际业务逻辑计算已收货数量 - // 通常需要查询入库明细和实际收货记录 - - // 示例:查询入库明细 - const items = await app.model.EntryItems.findAll({ - where: { order_id: orderId }, - attributes: [ - 'id', - 'count', - [ app.Sequelize.literal('(SELECT SUM(quantity) FROM wms_storage WHERE inbound_order_no = wms_entry_order.entry_order_code AND item_id = wms_entry_items.item_id)'), 'received' ], - ], - include: [{ - model: app.model.EntryOrder, - as: 'order', - attributes: [ 'entry_order_code' ], - }], - }); - - let totalExpected = 0; - let totalReceived = 0; - let allReceived = true; - let anyReceived = false; - - items.forEach(item => { - const expected = item.count || 0; - const received = item.received || 0; - - totalExpected += expected; - totalReceived += received; - - if (expected > 0 && received < expected) { - allReceived = false; - } - - if (received > 0) { - anyReceived = true; - } - }); - - return { - total_expected: totalExpected, - total_received: totalReceived, - all_received: allReceived, - any_received: anyReceived, - percentage: totalExpected > 0 ? Math.round((totalReceived / totalExpected) * 100) : 0, - }; - }; - return EntryOrder; }; diff --git a/app/model/i18n_translation.js b/app/model/i18n_translation.js index 0e20141..b8fe0e6 100644 --- a/app/model/i18n_translation.js +++ b/app/model/i18n_translation.js @@ -2,7 +2,7 @@ 'use strict'; module.exports = app => { - const { STRING, INTEGER, DATE, Op } = app.Sequelize; + const { STRING, INTEGER } = app.Sequelize; // 直接在文件中定义常量 const CONSTANTS = { @@ -60,123 +60,5 @@ module.exports = app => { // 挂载常量到模型(可选) I18nTranslation.CONSTANTS = CONSTANTS; - /** - * 获取翻译 - * @param keyId - * @param language - */ - I18nTranslation.getTranslation = async function(keyId, language) { - return await this.findOne({ - where: { key_id: keyId, language }, - include: [{ - model: app.model.I18nKey, - as: 'key', - }], - }); - }; - - /** - * 批量获取翻译 - * @param keyIds - * @param language - */ - I18nTranslation.batchGetTranslations = async function(keyIds, language) { - const records = await this.findAll({ - where: { - key_id: keyIds, - language, - }, - include: [{ - model: app.model.I18nKey, - as: 'key', - attributes: [ 'key_name' ], - }], - }); - - // 返回键值对 - const result = {}; - records.forEach(record => { - if (record.key) { - result[record.key.key_name] = record.translation || record.key.key_name; - } - }); - - return result; - }; - - /** - * 获取项目翻译 - * @param project - * @param language - */ - I18nTranslation.getProjectTranslations = async function(project, language) { - const records = await this.findAll({ - include: [{ - model: app.model.I18nKey, - as: 'key', - where: { project }, - attributes: [ 'key_name' ], - }], - where: { language }, - }); - - const result = {}; - records.forEach(record => { - if (record.key && record.key.key_name) { - result[record.key.key_name] = record.translation || record.key.key_name; - } - }); - - return result; - }; - - /** - * 创建或更新翻译 - * @param keyId - * @param language - * @param translation - */ - I18nTranslation.upsertTranslation = async function(keyId, language, translation) { - const [ record, created ] = await this.findOrCreate({ - where: { key_id: keyId, language }, - defaults: { - key_id: keyId, - language, - translation: translation || null, - translation_status: translation ? CONSTANTS.TRANSLATION_STATUS.PENDING_REVIEW : CONSTANTS.TRANSLATION_STATUS.UNTRANSLATED, - }, - }); - - if (!created) { - record.translation = translation || null; - record.translation_status = translation ? CONSTANTS.TRANSLATION_STATUS.PENDING_REVIEW : CONSTANTS.TRANSLATION_STATUS.UNTRANSLATED; - await record.save(); - } - - return record; - }; - - /** - * 获取未翻译列表 - * @param language - * @param project - */ - I18nTranslation.getUntranslated = async function(language, project) { - return await this.findAll({ - include: [{ - model: app.model.I18nKey, - as: 'key', - where: { project }, - }], - where: { - language, - [Op.or]: [ - { translation: null }, - { translation: '' }, - ], - }, - }); - }; - return I18nTranslation; }; diff --git a/app/model/interface_type.js b/app/model/interface_type.js index fc63789..06f1b59 100644 --- a/app/model/interface_type.js +++ b/app/model/interface_type.js @@ -104,27 +104,6 @@ module.exports = app => { ], }); - - // 类方法 - 根据接口编码查找 - InterfaceType.findByCode = async function(interfaceCode) { - return await this.findOne({ - where: { interface_code: interfaceCode }, - }); - }; - - // 类方法 - 获取启用的接口列表 - InterfaceType.findEnabled = async function(category = null) { - const where = { is_enabled: 1 }; - if (category) { - where.interface_category = category; - } - - return await this.findAll({ - where, - order: [[ 'interface_name', 'ASC' ]], - }); - }; - // 实例方法 - 检查接口是否可用 InterfaceType.prototype.isAvailable = function() { return this.is_enabled === 1; diff --git a/app/model/permission.js b/app/model/permission.js index ead44a8..795c2bf 100644 --- a/app/model/permission.js +++ b/app/model/permission.js @@ -72,8 +72,11 @@ module.exports = app => { }, parent_id: { type: INTEGER, - allowNull: false, - defaultValue: 0, + allowNull: true, + defaultValue: null, + set(value) { + this.setDataValue('parent_id', value === 0 ? null : value); + }, comment: '父级ID', }, sort: { @@ -242,7 +245,7 @@ module.exports = app => { permissions.forEach(permission => { const node = permissionMap.get(permission.id); - if (permission.parent_id === 0) { + if (!permission.parent_id) { rootPermissions.push(node); } else { const parent = permissionMap.get(permission.parent_id); diff --git a/app/model/print_item.js b/app/model/print_item.js index 4f15350..d26e294 100644 --- a/app/model/print_item.js +++ b/app/model/print_item.js @@ -232,37 +232,6 @@ module.exports = app => { return this.table_config; }; - // 类方法:获取指定业务类型的分组字段 - PrintItem.getGroupFields = async function(businessType, platform) { - return await this.findAll({ - where: { - business_type: businessType, - platform: platform || 'default', - group_field: { - [app.Sequelize.Op.ne]: null, - }, - status: 1, - }, - order: [ - [ 'group_sort', 'ASC' ], - [ 'sort_order', 'ASC' ], - ], - }); - }; - - // 类方法:获取指定业务类型的表格配置 - PrintItem.getTableConfigs = async function(businessType, platform) { - return await this.findAll({ - where: { - business_type: businessType, - platform: platform || 'default', - is_table: true, - status: 1, - }, - order: [[ 'sort_order', 'ASC' ]], - }); - }; - // 关联方法 PrintItem.associate = function() { // 如果需要关联其他表,在这里添加 diff --git a/app/model/receiving.js b/app/model/receiving.js index f659bf7..b885599 100644 --- a/app/model/receiving.js +++ b/app/model/receiving.js @@ -144,7 +144,7 @@ module.exports = app => { // 关联定义 Receiving.associate = function() { - const { ReceivingDetail, Store, AccountStoreEmployee, Storage, StoreWarehouse } = app.model; + const { ReceivingDetail, Store, AccountStoreEmployee, StoreWarehouse } = app.model; // 关联收货明细 Receiving.hasMany(ReceivingDetail, { foreignKey: 'receiving_id', @@ -163,15 +163,12 @@ module.exports = app => { as: 'creator', }); - // 关联入库记录 - Receiving.hasMany(Storage, { - foreignKey: 'receiving_id', - as: 'storage_records', - }); + // wms_storage 无 receiving_id 字段,避免声明无效关联。 Receiving.belongsTo(StoreWarehouse, { foreignKey: 'store_id', // 当前表的外键字段 - targetKey: 'store_id', // 关联表的主键字段 + targetKey: 'store_id', // 关联表的业务键字段(非主键) as: 'store', + constraints: false, }); }; diff --git a/app/model/receiving_detail.js b/app/model/receiving_detail.js index d13d902..6f1f0fe 100644 --- a/app/model/receiving_detail.js +++ b/app/model/receiving_detail.js @@ -143,7 +143,7 @@ module.exports = app => { }); ReceivingDetail.associate = function() { - const { Receiving, StockWarehouse, Storage, LocationSpace } = app.model; + const { Receiving, StockWarehouse, LocationSpace } = app.model; // 关联主表 ReceivingDetail.belongsTo(Receiving, { foreignKey: 'receiving_id', @@ -156,12 +156,6 @@ module.exports = app => { as: 'system_product', }); - // 关联入库记录 - ReceivingDetail.hasMany(Storage, { - foreignKey: 'receiving_detail_id', - as: 'storage_details', - }); - // 关联系统商品 ReceivingDetail.belongsTo(LocationSpace, { foreignKey: 'space_id', diff --git a/app/model/role.js b/app/model/role.js index cb94c33..f065bd1 100644 --- a/app/model/role.js +++ b/app/model/role.js @@ -148,7 +148,7 @@ module.exports = app => { // 关联关系 Role.associate = function(models) { - const { Account, Store, Permission, AccountStoreRole, RolePermission, EmployeeRole } = app.model; + const { Account, Store, Permission, RolePermission, EmployeeRole } = app.model; // 创建人 Role.belongsTo(Account, { foreignKey: 'created_by', @@ -171,7 +171,7 @@ module.exports = app => { Role.hasMany(EmployeeRole, { foreignKey: 'role_id', sourceKey: 'id', - as: 'employeeRole', + as: 'employeeRoles', }); }; diff --git a/app/model/role_permission.js b/app/model/role_permission.js index 2b0a4bc..6a3e906 100644 --- a/app/model/role_permission.js +++ b/app/model/role_permission.js @@ -1,7 +1,7 @@ 'use strict'; module.exports = app => { - const { BIGINT, DATE } = app.Sequelize; + const { BIGINT, INTEGER, DATE } = app.Sequelize; const RolePermission = app.model.define('role_permission', { id: { @@ -17,7 +17,7 @@ module.exports = app => { comment: '角色ID', }, permission_id: { - type: BIGINT.UNSIGNED, + type: INTEGER, allowNull: false, comment: '权限ID', }, diff --git a/app/model/stock_store.js b/app/model/stock_store.js index 9cbc91e..03b6a11 100644 --- a/app/model/stock_store.js +++ b/app/model/stock_store.js @@ -362,45 +362,6 @@ module.exports = app => { }); }; - // 类方法 - 根据商品编码查找 - StockStore.findByItemCode = async function(itemCode, options = {}) { - const where = { item_code: itemCode, is_valid: 'Y' }; - - if (options.warehouse_id) { - where.warehouse_id = options.warehouse_id; - } - - if (options.store_id) { - where.store_id = options.store_id; - } - - return await this.findOne({ - where, - include: options.include || [], - }); - }; - - // 类方法 - 获取商家的商品列表 - StockStore.findByStore = async function(storeId, options = {}) { - const where = { store_id: storeId, is_valid: 'Y' }; - - if (options.warehouse_id) { - where.warehouse_id = options.warehouse_id; - } - - if (options.owner_code) { - where.owner_code = options.owner_code; - } - - return await this.findAll({ - where, - include: options.include || [], - order: options.order || [[ 'create_time', 'DESC' ]], - limit: options.limit, - offset: options.offset, - }); - }; - // 实例方法 - 检查商品是否有效 StockStore.prototype.isValid = function() { return this.is_valid === 'Y' && !this.delete_at; diff --git a/app/model/stock_warehouse.js b/app/model/stock_warehouse.js index 048b61f..2d0107b 100644 --- a/app/model/stock_warehouse.js +++ b/app/model/stock_warehouse.js @@ -224,11 +224,12 @@ module.exports = app => { StockWarehouse.associate = function(models) { const { StoreWarehouse, StockBarcode, ProhibitedType, StockImage, StockStore, Storage } = app.model; - // 授权关系属于商家 - 修正:需要确认StoreWarehouse模型是否有store_id字段 + // store_stock 关联依赖 store_id + warehouse_id 复合语义,单列关联仅作为 include 入口。 StockWarehouse.belongsTo(StoreWarehouse, { foreignKey: 'store_id', // 当前表的外键字段 - targetKey: 'store_id', // 关联表的主键字段 + targetKey: 'store_id', // 关联表业务键(非主键) as: 'store_stock', + constraints: false, }); StockWarehouse.hasMany(StockBarcode, { foreignKey: 'stock_id', // StockBarcodes表中的外键字段 diff --git a/app/model/storage.js b/app/model/storage.js index 98bd61a..7646aee 100644 --- a/app/model/storage.js +++ b/app/model/storage.js @@ -247,222 +247,5 @@ module.exports = app => { return new Date(this.expiry_date) < new Date(); }; - // 静态方法 - Storage.findByStockAndBatch = async function(app, stockId, batchNo, inventoryType = 'ZP') { - return await app.model.Storage.findOne({ - where: { - stock_id: stockId, - batch_no: batchNo, - inventory_type: inventoryType, - is_enabled: 1, - delete_at: null, - }, - include: [ - { - model: app.model.LocationSpace, - as: 'space', - attributes: [ 'space_code', 'custom_name' ], - }, - { - model: app.model.Store, - as: 'warehouse', - attributes: [ 'store_name' ], - }, - ], - }); - }; - - Storage.findBySpace = async function(app, spaceId) { - return await app.model.Storage.findAll({ - where: { - space_id: spaceId, - is_enabled: 1, - delete_at: null, - }, - include: [ - { - model: app.model.StockWarehouse, - as: 'stock', - attributes: [ 'product_code', 'product_name' ], - }, - ], - order: [[ 'inbound_time', 'ASC' ]], - }); - }; - - Storage.findAvailableByWarehouse = async function(app, warehouseId, stockId = null) { - const where = { - warehouse_id: warehouseId, - is_enabled: 1, - delete_at: null, - available_quantity: { [app.Sequelize.Op.gt]: 0 }, - }; - - if (stockId) { - where.stock_id = stockId; - } - - return await app.model.Storage.findAll({ - where, - include: [ - { - model: app.model.LocationSpace, - as: 'space', - attributes: [ 'space_code', 'custom_name' ], - }, - { - model: app.model.StockWarehouse, - as: 'stock', - attributes: [ 'product_code', 'product_name' ], - }, - ], - order: [ - [ 'expiry_date', 'ASC' ], - [ 'inbound_time', 'ASC' ], - ], - }); - }; - - Storage.findExpiringSoon = async function(app, days = 30) { - const expiryDate = new Date(); - expiryDate.setDate(expiryDate.getDate() + days); - - return await app.model.Storage.findAll({ - where: { - expiry_date: { - [app.Sequelize.Op.between]: [ new Date(), expiryDate ], - }, - is_enabled: 1, - delete_at: null, - quantity: { [app.Sequelize.Op.gt]: 0 }, - }, - include: [ - { - model: app.model.Store, - as: 'warehouse', - attributes: [ 'store_name' ], - }, - { - model: app.model.StockWarehouse, - as: 'stock', - attributes: [ 'product_code', 'product_name' ], - }, - ], - order: [[ 'expiry_date', 'ASC' ]], - }); - }; - - Storage.updateQuantity = async function(app, id, quantityChange, lockedChange = 0) { - const storage = await app.model.Storage.findByPk(id); - - if (!storage) { - throw new Error('库存记录不存在'); - } - - const newQuantity = storage.quantity + quantityChange; - const newLocked = storage.locked_quantity + lockedChange; - - if (newQuantity < 0) { - throw new Error('库存数量不能为负数'); - } - - if (newLocked < 0 || newLocked > newQuantity) { - throw new Error('锁定数量无效'); - } - - const updateData = { - quantity: newQuantity, - locked_quantity: newLocked, - available_quantity: newQuantity - newLocked, - updated_at: new Date(), - }; - - await storage.update(updateData); - return storage; - }; - - Storage.lockQuantity = async function(app, id, quantity) { - return await Storage.updateQuantity(app, id, 0, quantity); - }; - - Storage.unlockQuantity = async function(app, id, quantity) { - return await Storage.updateQuantity(app, id, 0, -quantity); - }; - - Storage.allocateQuantity = async function(app, id, quantity) { - const storage = await app.model.Storage.findByPk(id); - - if (!storage) { - throw new Error('库存记录不存在'); - } - - if (storage.available_quantity < quantity) { - throw new Error('可用数量不足'); - } - - return await Storage.updateQuantity(app, id, 0, quantity); - }; - - Storage.getStockSummary = async function(app, warehouseId) { - return await app.model.Storage.findAll({ - attributes: [ - 'stock_id', - 'inventory_type', - [ app.Sequelize.fn('SUM', app.Sequelize.col('quantity')), 'total_quantity' ], - [ app.Sequelize.fn('SUM', app.Sequelize.col('locked_quantity')), 'total_locked' ], - [ app.Sequelize.fn('SUM', app.Sequelize.col('available_quantity')), 'total_available' ], - ], - where: { - warehouse_id: warehouseId, - is_enabled: 1, - delete_at: null, - }, - group: [ 'stock_id', 'inventory_type' ], - raw: true, - }); - }; - - Storage.getSpaceUsage = async function(app, spaceId) { - const result = await app.model.Storage.findAll({ - attributes: [ - 'inventory_type', - [ app.Sequelize.fn('COUNT', app.Sequelize.col('id')), 'record_count' ], - [ app.Sequelize.fn('SUM', app.Sequelize.col('quantity')), 'total_quantity' ], - ], - where: { - space_id: spaceId, - is_enabled: 1, - delete_at: null, - }, - group: [ 'inventory_type' ], - raw: true, - }); - - const usage = { - normal: 0, - defective: 0, - damaged: 0, - frozen: 0, - total: 0, - }; - - result.forEach(item => { - let type; - switch (item.inventory_type) { - case 'ZP': type = 'normal'; break; - case 'CC': type = 'defective'; break; - case 'JS': - case 'XS': type = 'damaged'; break; - case 'DJ': type = 'frozen'; break; - default: return; - } - - usage[type] = parseInt(item.total_quantity) || 0; - usage.total += usage[type]; - }); - - return usage; - }; - return Storage; }; diff --git a/app/model/store.js b/app/model/store.js index 89bafc9..3453d8e 100644 --- a/app/model/store.js +++ b/app/model/store.js @@ -199,10 +199,10 @@ module.exports = app => { as: 'roles', }); - // 关联商家拥有的账号角色关联 + // 关联商家拥有的账号员工关联 Store.hasMany(AccountStoreEmployee, { foreignKey: 'store_id', - as: 'accountStoreEmployee', + as: 'accountStoreEmployees', }); Store.hasMany(ProhibitedType, { diff --git a/app/model/store_warehouse.js b/app/model/store_warehouse.js index 01df60f..f0a2ae3 100644 --- a/app/model/store_warehouse.js +++ b/app/model/store_warehouse.js @@ -209,10 +209,12 @@ module.exports = app => { as: 'reviewer', }); + // store_id 在业务上需要与 warehouse_id 联合约束,模型层不声明单列外键约束。 StoreWarehouse.hasMany(StockWarehouse, { foreignKey: 'store_id', targetKey: 'store_id', as: 'store_stock', + constraints: false, }); // 解除人 @@ -221,12 +223,60 @@ module.exports = app => { targetKey: 'id', as: 'end_user', }); + // receiving 同样依赖 store_id + warehouse_id 的复合语义。 StoreWarehouse.hasMany(Receiving, { foreignKey: 'store_id', as: 'receiving', + constraints: false, }); }; + // 统一构造复合键语义的 where 条件,避免 service 侧重复散落。 + StoreWarehouse.buildScopedWhere = function(options = {}) { + const { + warehouseId, + storeId, + useStatus = 1, + } = options; + + const where = { + use_status: useStatus, + }; + + if (warehouseId !== undefined && warehouseId !== null) { + where.warehouse_id = warehouseId; + } + + if (storeId !== undefined && storeId !== null) { + where.store_id = storeId; + } + + return where; + }; + + // 统一构造 StockWarehouse -> StoreWarehouse(include as=store_stock) 的 include。 + StoreWarehouse.buildStoreStockInclude = function(options = {}) { + const { + warehouseId, + storeId, + required = false, + useStatus = 1, + attributes = [ 'store_id', 'store_remask' ], + } = options; + + return { + model: this, + as: 'store_stock', + attributes, + where: this.buildScopedWhere({ + warehouseId, + storeId, + useStatus, + }), + required, + }; + }; + // 实例方法 - 检查授权是否有效 StoreWarehouse.prototype.isAuthValid = function() { if (this.auth_status !== 2) return false; // 只有已通过状态才有效 diff --git a/app/router.js b/app/router.js index af886dc..b048e27 100644 --- a/app/router.js +++ b/app/router.js @@ -4,17 +4,29 @@ module.exports = app => { const { router, controller } = app; router.get('/', controller.home.index); + + // 奇门接口 router.post('/qimen', controller.home.qimen); + + //预留第三方系统接口 router.post('/api/warehouse', controller.home.warehouse); router.post('/api/store', controller.home.store); - router.post('/api/v1', controller.home.v1); + + // 系统接口 PDA/WEB 统一入口 router.post('/system', controller.home.system); - router.post('/api/v2', controller.apiV2.index); + + //api文档相关 router.get('/api/docs', controller.docs.list); router.get('/api/docs/:docName', controller.docs.detail); router.get('/api/docs/:docName/raw', controller.docs.raw); + + //打印模板 router.get('/template/xml/:id', controller.template.xml); + + //打印台设置 router.get('/auth/printSetting/:code', controller.auth.printerSetting); - router.get('/testSendData', controller.home.testSendData); router.post('/auth/printSetting/', controller.auth.printerSetting); + + //测试接口 + router.get('/testSendData', controller.home.testSendData); }; diff --git a/app/service/system.js b/app/service/system.js index 830f5b7..5a4c0ea 100644 --- a/app/service/system.js +++ b/app/service/system.js @@ -3,6 +3,9 @@ const Service = require('egg').Service; const { XMLParser } = require('fast-xml-parser'); +const ALLOWED_PLATFORMS = new Set([ 'web', 'pda', 'app', 'wx', 'miniprogram', 'other' ]); +const ALLOWED_PROJECTS = new Set([ 'all', 'wms', 'tms', 'scm', 'other' ]); + class systemService extends Service { async callMethod(className, actionName, requestData, authHeader) { try { @@ -22,7 +25,11 @@ class systemService extends Service { }else{ console.log(`调用服务: ${servicePath}, 方法: ${actionName}`); } - const serviceInstance = systemMethods; + let serviceInstance = systemMethods; + + if (typeof serviceInstance[actionName] !== 'function' && serviceInstance?.index) { + serviceInstance = serviceInstance.index; + } // 检查方法是否存在 if (typeof serviceInstance[actionName] !== 'function') { @@ -66,6 +73,94 @@ class systemService extends Service { return true; } + + validateRequestContext(params = {}, headers = {}) { + if (!this.validateParams(params)) { + return { + ok: false, + status: 400, + code: 400, + message: '参数缺失或错误: method/v/timestamp', + }; + } + + const rawTimestamp = String(params.timestamp || '').trim(); + if (!/^\d+$/.test(rawTimestamp)) { + return { + ok: false, + status: 400, + code: 400, + message: 'timestamp 必须为数字时间戳', + }; + } + + const timestampNum = Number(rawTimestamp); + if (!Number.isFinite(timestampNum) || timestampNum <= 0) { + return { + ok: false, + status: 400, + code: 400, + message: 'timestamp 非法', + }; + } + + const platform = String(headers.platform || '').trim(); + const project = String(headers.project || '').trim(); + const authorization = String(headers.authorization || '').trim(); + + if (!platform) { + return { + ok: false, + status: 400, + code: 400, + message: '缺少请求头 platform', + }; + } + + if (!project) { + return { + ok: false, + status: 400, + code: 400, + message: '缺少请求头 project', + }; + } + + if (!ALLOWED_PLATFORMS.has(platform.toLowerCase())) { + return { + ok: false, + status: 400, + code: 400, + message: `platform 不支持: ${platform}`, + }; + } + + if (!ALLOWED_PROJECTS.has(project.toLowerCase())) { + return { + ok: false, + status: 400, + code: 400, + message: `project 不支持: ${project}`, + }; + } + + if (authorization && !authorization.startsWith('Bearer ')) { + return { + ok: false, + status: 401, + code: 401, + message: 'Authorization 格式错误,应为 Bearer ', + }; + } + + return { + ok: true, + status: 200, + code: 0, + message: 'ok', + }; + } + async saveLog(logData, startTime) { const { ctx, diff --git a/app/service/systemMethods/order.js b/app/service/systemMethods/order.js deleted file mode 100644 index 8cc17d8..0000000 --- a/app/service/systemMethods/order.js +++ /dev/null @@ -1,351 +0,0 @@ -'use strict'; - -const MainService = require('../main'); - -class orderService extends MainService { - constructor(ctx) { - super(ctx); - const _noNeedLogin = ''; - const _noNeedRight = 'list,detail,listItems,stats,updateStatus,updateDeliveryTime'; - const _noNeedLog = 'list,detail,listItems,stats'; - const _noNeedAuth = 'list,detail,listItems,stats,updateStatus,updateDeliveryTime'; - this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); - } - - getWarehouseId(data = {}) { - const fromParam = Number(data.warehouse_id || data.warehouseId || 0); - const fromUser = Number(this.ctx.user?.store_id || 0); - return fromParam || fromUser; - } - - async getOrderModels(warehouseId) { - const DeliveryModel = await this.ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); - const OrderItemsModel = await this.ctx.model.OrderItemsFactory.getCurrentModel(warehouseId); - return { DeliveryModel, OrderItemsModel }; - } - - applyDateRange(where, field, start, end) { - const { Op } = this.app.Sequelize; - const range = {}; - - if (start) { - range[Op.gte] = this.normalizeDate(start, false); - } - if (end) { - range[Op.lte] = this.normalizeDate(end, true); - } - - if (Object.keys(range).length > 0) { - where[field] = range; - } - } - - buildWhere(whereData = {}, warehouseId) { - const { Op } = this.app.Sequelize; - const where = { warehouse_id: warehouseId }; - - const eqFields = [ - 'id', - 'store_id', - 'status', - 'post_status', - 'storage_status', - 'pick_status', - 'pack_status', - 'inspection_status', - 'print_status', - 'claim_status', - 'outbound_status', - 'lock_status', - 'intercept_status', - 'source_platform_code', - 'logistics_code', - 'warehouse_code', - 'order_type', - ]; - - for (const key of eqFields) { - if (whereData[key] !== undefined && whereData[key] !== null && whereData[key] !== '') { - where[key] = whereData[key]; - } - } - - if (whereData.delivery_order_code) { - where.delivery_order_code = { [Op.like]: `%${whereData.delivery_order_code}%` }; - } - - if (Array.isArray(whereData.delivery_order_codes) && whereData.delivery_order_codes.length > 0) { - where.delivery_order_code = { [Op.in]: whereData.delivery_order_codes }; - } - - if (whereData.logistics_name) { - where.logistics_name = { [Op.like]: `%${whereData.logistics_name}%` }; - } - - if (whereData.buyer_nick) { - where.buyer_nick = { [Op.like]: `%${whereData.buyer_nick}%` }; - } - - if (whereData.mobile) { - where.mobile = { [Op.like]: `%${whereData.mobile}%` }; - } - - this.applyDateRange(where, 'create_at', whereData.create_at_start, whereData.create_at_end); - this.applyDateRange(where, 'place_order_time', whereData.place_order_time_start, whereData.place_order_time_end); - this.applyDateRange(where, 'pay_time', whereData.pay_time_start, whereData.pay_time_end); - this.applyDateRange(where, 'delivery_time', whereData.delivery_time_start, whereData.delivery_time_end); - - return where; - } - - parseDateTime(value, fieldName) { - if (!value) return null; - const d = value instanceof Date ? value : new Date(value); - if (Number.isNaN(d.getTime())) { - throw new Error(`${fieldName} 格式错误`); - } - return d; - } - - async list(data = {}) { - try { - const warehouseId = this.getWarehouseId(data); - if (!warehouseId) { - return this.fail('warehouse_id 不能为空', { code: 400 }); - } - - const { DeliveryModel } = await this.getOrderModels(warehouseId); - const where = this.buildWhere(data.where || {}, warehouseId); - - const page = Math.max(Number(data.pagination?.page || 1), 1); - const pageSize = Math.min(Math.max(Number(data.pagination?.pageSize || 20), 1), 200); - const offset = (page - 1) * pageSize; - - const result = await DeliveryModel.findAndCountAll({ - where, - offset, - limit: pageSize, - order: [ [ 'updated_at', 'DESC' ], [ 'id', 'DESC' ] ], - raw: true, - }); - - return this.success('ok', { - data: { - list: result.rows, - pagination: { - page, - pageSize, - total: result.count, - totalPages: Math.ceil(result.count / pageSize), - hasNext: page * pageSize < result.count, - hasPrevious: page > 1, - }, - }, - code: 200, - }); - } catch (error) { - return this.fail(error.message, { code: 500 }); - } - } - - async detail(data = {}) { - try { - const warehouseId = this.getWarehouseId(data); - if (!warehouseId) { - return this.fail('warehouse_id 不能为空', { code: 400 }); - } - - const { DeliveryModel, OrderItemsModel } = await this.getOrderModels(warehouseId); - const where = { warehouse_id: warehouseId }; - - if (data.id) { - where.id = data.id; - } else if (data.delivery_order_code) { - where.delivery_order_code = data.delivery_order_code; - } else { - return this.fail('id 或 delivery_order_code 必填', { code: 400 }); - } - - const order = await DeliveryModel.findOne({ where, raw: true }); - if (!order) { - return this.fail('订单不存在', { code: 404 }); - } - - const items = await OrderItemsModel.findAll({ - where: { order_id: order.id }, - order: [ [ 'id', 'ASC' ] ], - raw: true, - }); - - return this.success('ok', { - data: { - order, - items, - }, - code: 200, - }); - } catch (error) { - return this.fail(error.message, { code: 500 }); - } - } - - async listItems(data = {}) { - try { - const warehouseId = this.getWarehouseId(data); - if (!warehouseId) { - return this.fail('warehouse_id 不能为空', { code: 400 }); - } - - const { DeliveryModel, OrderItemsModel } = await this.getOrderModels(warehouseId); - const where = { warehouse_id: warehouseId }; - - if (data.order_id) { - where.id = data.order_id; - } else if (data.delivery_order_code) { - where.delivery_order_code = data.delivery_order_code; - } else { - return this.fail('order_id 或 delivery_order_code 必填', { code: 400 }); - } - - const order = await DeliveryModel.findOne({ where, attributes: [ 'id', 'delivery_order_code' ], raw: true }); - if (!order) { - return this.fail('订单不存在', { code: 404 }); - } - - const items = await OrderItemsModel.findAll({ - where: { order_id: order.id }, - order: [ [ 'id', 'ASC' ] ], - raw: true, - }); - - return this.success('ok', { - data: { - order, - items, - }, - code: 200, - }); - } catch (error) { - return this.fail(error.message, { code: 500 }); - } - } - - async stats(data = {}) { - try { - const warehouseId = this.getWarehouseId(data); - if (!warehouseId) { - return this.fail('warehouse_id 不能为空', { code: 400 }); - } - - const { Sequelize } = this.app; - const { DeliveryModel } = await this.getOrderModels(warehouseId); - const where = this.buildWhere(data.where || {}, warehouseId); - - const total = await DeliveryModel.count({ where }); - const byStatusRows = await DeliveryModel.findAll({ - where, - attributes: [ 'status', [ Sequelize.fn('COUNT', Sequelize.col('id')), 'count' ] ], - group: [ 'status' ], - raw: true, - }); - - const byOutboundRows = await DeliveryModel.findAll({ - where, - attributes: [ 'outbound_status', [ Sequelize.fn('COUNT', Sequelize.col('id')), 'count' ] ], - group: [ 'outbound_status' ], - raw: true, - }); - - return this.success('ok', { - data: { - total, - byStatus: byStatusRows, - byOutboundStatus: byOutboundRows, - }, - code: 200, - }); - } catch (error) { - return this.fail(error.message, { code: 500 }); - } - } - - async updateStatus(data = {}) { - try { - const warehouseId = this.getWarehouseId(data); - if (!warehouseId) { - return this.fail('warehouse_id 不能为空', { code: 400 }); - } - - const { DeliveryModel } = await this.getOrderModels(warehouseId); - const where = { warehouse_id: warehouseId }; - - if (data.id) { - where.id = data.id; - } else if (data.delivery_order_code) { - where.delivery_order_code = data.delivery_order_code; - } else { - return this.fail('id 或 delivery_order_code 必填', { code: 400 }); - } - - const allowedFields = [ - 'status', - 'post_status', - 'storage_status', - 'pick_status', - 'pack_status', - 'inspection_status', - 'print_status', - 'claim_status', - 'outbound_status', - 'lock_status', - 'intercept_status', - ]; - - const updateData = {}; - for (const key of allowedFields) { - if (data[key] !== undefined && data[key] !== null && data[key] !== '') { - updateData[key] = data[key]; - } - } - - if (data.delivery_time) { - updateData.delivery_time = this.parseDateTime(data.delivery_time, 'delivery_time'); - } - - if (!updateData.delivery_time && updateData.outbound_status === 'fin') { - updateData.delivery_time = new Date(); - } - - if (Object.keys(updateData).length === 0) { - return this.fail('没有可更新字段', { code: 400 }); - } - - updateData.updated_at = new Date(); - - const [ affected ] = await DeliveryModel.update(updateData, { where }); - if (!affected) { - return this.fail('订单不存在或未更新', { code: 404 }); - } - - const order = await DeliveryModel.findOne({ where, raw: true }); - return this.success('更新成功', { data: order, code: 200 }); - } catch (error) { - return this.fail(error.message, { code: 500 }); - } - } - - async updateDeliveryTime(data = {}) { - if (!data.delivery_time) { - return this.fail('delivery_time 必填', { code: 400 }); - } - - const nextData = { ...data }; - if (nextData.syncOutboundStatus === true || nextData.syncOutboundStatus === 1 || nextData.syncOutboundStatus === '1') { - nextData.outbound_status = 'fin'; - } - - return await this.updateStatus(nextData); - } -} - -module.exports = orderService; diff --git a/app/service/systemMethods/order/archiveOrder.js b/app/service/systemMethods/order/archiveOrder.js new file mode 100644 index 0000000..e304684 --- /dev/null +++ b/app/service/systemMethods/order/archiveOrder.js @@ -0,0 +1,62 @@ +'use strict'; + +const OrderBaseService = require('./base'); + +class ArchiveOrderService extends OrderBaseService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'getarchiveOrderlist'; + const _noNeedLog = 'getarchiveOrderlist'; + const _noNeedAuth = 'getarchiveOrderlist'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + async getarchiveOrderlist(data = {}) { + try { + const warehouseId = this.ensureWarehouseId(data); + const { DeliveryModel } = await this.getOrderModels(warehouseId); + const whereData = data.where || {}; + const where = this.buildWhere(whereData, warehouseId); + + const hasOutboundFilter = whereData.outbound_status !== undefined && whereData.outbound_status !== null && whereData.outbound_status !== ''; + if (!hasOutboundFilter) { + where.outbound_status = 'fin'; + } + + const { page, pageSize, offset } = this.getPagination(data.pagination); + const result = await DeliveryModel.findAndCountAll({ + where, + attributes: [ + 'id', + 'delivery_order_code', + 'status', + 'outbound_status', + 'delivery_time', + 'updated_at', + 'store_id', + 'warehouse_id', + 'buyer_nick', + 'logistics_name', + ], + offset, + limit: pageSize, + order: [ [ 'delivery_time', 'DESC' ], [ 'updated_at', 'DESC' ], [ 'id', 'DESC' ] ], + raw: true, + }); + + return this.success('ok', { + data: this.buildListData(result.rows, result.count, page, pageSize, { + queryInfo: { + defaultArchiveFilter: !hasOutboundFilter, + }, + }), + code: 200, + }); + } catch (error) { + return this.fail(error.message, { code: 500 }); + } + } +} + +module.exports = ArchiveOrderService; \ No newline at end of file diff --git a/app/service/systemMethods/order/base.js b/app/service/systemMethods/order/base.js new file mode 100644 index 0000000..89ea602 --- /dev/null +++ b/app/service/systemMethods/order/base.js @@ -0,0 +1,157 @@ +'use strict'; + +const MainService = require('../../main'); + +class OrderBaseService extends MainService { + ensureWarehouseId(data = {}) { + const warehouseId = this.getWarehouseId(data); + if (!warehouseId) { + throw new Error('warehouse_id 不能为空'); + } + return warehouseId; + } + + getWarehouseId(data = {}) { + const fromParam = Number(data.warehouse_id || data.warehouseId || 0); + const fromUser = Number(this.ctx.user?.store_id || 0); + return fromParam || fromUser; + } + + async getOrderModels(warehouseId) { + const DeliveryModel = await this.ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); + const OrderItemsModel = await this.ctx.model.OrderItemsFactory.getCurrentModel(warehouseId); + return { DeliveryModel, OrderItemsModel }; + } + + applyDateRange(where, field, start, end) { + const { Op } = this.app.Sequelize; + const range = {}; + + if (start) { + range[Op.gte] = this.normalizeDate(start, false); + } + if (end) { + range[Op.lte] = this.normalizeDate(end, true); + } + + if (Object.keys(range).length > 0) { + where[field] = range; + } + } + + buildWhere(whereData = {}, warehouseId) { + const { Op } = this.app.Sequelize; + const where = { warehouse_id: warehouseId }; + + const eqFields = [ + 'id', + 'store_id', + 'status', + 'post_status', + 'storage_status', + 'pick_status', + 'pack_status', + 'inspection_status', + 'print_status', + 'claim_status', + 'outbound_status', + 'lock_status', + 'intercept_status', + 'source_platform_code', + 'logistics_code', + 'warehouse_code', + 'order_type', + ]; + + for (const key of eqFields) { + if (whereData[key] !== undefined && whereData[key] !== null && whereData[key] !== '') { + where[key] = whereData[key]; + } + } + + if (whereData.delivery_order_code) { + where.delivery_order_code = { [Op.like]: `%${whereData.delivery_order_code}%` }; + } + + if (Array.isArray(whereData.delivery_order_codes) && whereData.delivery_order_codes.length > 0) { + where.delivery_order_code = { [Op.in]: whereData.delivery_order_codes }; + } + + if (whereData.logistics_name) { + where.logistics_name = { [Op.like]: `%${whereData.logistics_name}%` }; + } + + if (whereData.buyer_nick) { + where.buyer_nick = { [Op.like]: `%${whereData.buyer_nick}%` }; + } + + if (whereData.mobile) { + where.mobile = { [Op.like]: `%${whereData.mobile}%` }; + } + + this.applyDateRange(where, 'create_at', whereData.create_at_start, whereData.create_at_end); + this.applyDateRange(where, 'place_order_time', whereData.place_order_time_start, whereData.place_order_time_end); + this.applyDateRange(where, 'pay_time', whereData.pay_time_start, whereData.pay_time_end); + this.applyDateRange(where, 'delivery_time', whereData.delivery_time_start, whereData.delivery_time_end); + + return where; + } + + parseDateTime(value, fieldName) { + if (!value) return null; + const d = value instanceof Date ? value : new Date(value); + if (Number.isNaN(d.getTime())) { + throw new Error(`${fieldName} 格式错误`); + } + return d; + } + + getPagination(pagination = {}) { + const page = Math.max(Number(pagination.page || 1), 1); + const pageSize = Math.min(Math.max(Number(pagination.pageSize || 20), 1), 200); + const offset = (page - 1) * pageSize; + return { page, pageSize, offset }; + } + + buildPagination(page, pageSize, total) { + return { + page, + pageSize, + total, + totalPages: Math.ceil(total / pageSize), + hasNext: page * pageSize < total, + hasPrevious: page > 1, + }; + } + + getOrderLocatorWhere(data = {}, warehouseId) { + const where = { warehouse_id: warehouseId }; + + if (data.id) { + where.id = data.id; + return where; + } + + if (data.order_id) { + where.id = data.order_id; + return where; + } + + if (data.delivery_order_code) { + where.delivery_order_code = data.delivery_order_code; + return where; + } + + throw new Error('id 或 delivery_order_code 必填'); + } + + buildListData(rows, total, page, pageSize, extra = {}) { + return { + list: rows, + pagination: this.buildPagination(page, pageSize, total), + ...extra, + }; + } +} + +module.exports = OrderBaseService; \ No newline at end of file diff --git a/app/service/systemMethods/order/deliveryOrder.js b/app/service/systemMethods/order/deliveryOrder.js new file mode 100644 index 0000000..1acd085 --- /dev/null +++ b/app/service/systemMethods/order/deliveryOrder.js @@ -0,0 +1,63 @@ +'use strict'; + +const OrderBaseService = require('./base'); + +class DeliveryOrderService extends OrderBaseService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'getdeliveryOrderlist'; + const _noNeedLog = 'getdeliveryOrderlist'; + const _noNeedAuth = 'getdeliveryOrderlist'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + async getdeliveryOrderlist(data = {}) { + try { + const warehouseId = this.ensureWarehouseId(data); + const { Op } = this.app.Sequelize; + const { DeliveryModel } = await this.getOrderModels(warehouseId); + const whereData = data.where || {}; + const where = this.buildWhere(whereData, warehouseId); + + const hasOutboundFilter = whereData.outbound_status !== undefined && whereData.outbound_status !== null && whereData.outbound_status !== ''; + if (!hasOutboundFilter) { + where.outbound_status = { [Op.ne]: 'none' }; + } + + const { page, pageSize, offset } = this.getPagination(data.pagination); + const result = await DeliveryModel.findAndCountAll({ + where, + attributes: [ + 'id', + 'delivery_order_code', + 'status', + 'outbound_status', + 'delivery_time', + 'updated_at', + 'store_id', + 'warehouse_id', + 'buyer_nick', + 'logistics_name', + ], + offset, + limit: pageSize, + order: [ [ 'delivery_time', 'DESC' ], [ 'updated_at', 'DESC' ], [ 'id', 'DESC' ] ], + raw: true, + }); + + return this.success('ok', { + data: this.buildListData(result.rows, result.count, page, pageSize, { + queryInfo: { + defaultOutboundFilter: !hasOutboundFilter, + }, + }), + code: 200, + }); + } catch (error) { + return this.fail(error.message, { code: 500 }); + } + } +} + +module.exports = DeliveryOrderService; \ No newline at end of file diff --git a/app/service/systemMethods/order/expectionOrder.js b/app/service/systemMethods/order/expectionOrder.js new file mode 100644 index 0000000..0f066ac --- /dev/null +++ b/app/service/systemMethods/order/expectionOrder.js @@ -0,0 +1,90 @@ +'use strict'; + +const OrderBaseService = require('./base'); + +class ExpectionOrderService extends OrderBaseService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'getexpectionOrderlist'; + const _noNeedLog = 'getexpectionOrderlist'; + const _noNeedAuth = 'getexpectionOrderlist'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + async getexpectionOrderlist(data = {}) { + try { + const warehouseId = this.ensureWarehouseId(data); + const { Op } = this.app.Sequelize; + const { DeliveryModel } = await this.getOrderModels(warehouseId); + const whereData = data.where || {}; + const where = this.buildWhere(whereData, warehouseId); + + const hasExceptionFilter = [ + 'status', + 'post_status', + 'storage_status', + 'pick_status', + 'pack_status', + 'inspection_status', + 'print_status', + 'claim_status', + 'outbound_status', + 'intercept_status', + ].some(key => whereData[key] !== undefined && whereData[key] !== null && whereData[key] !== ''); + + if (!hasExceptionFilter) { + where[Op.or] = [ + { status: 'error' }, + { post_status: 'error' }, + { storage_status: 'error' }, + { pick_status: 'error' }, + { pack_status: 'error' }, + { inspection_status: 'error' }, + { print_status: 'error' }, + { claim_status: 'error' }, + { outbound_status: 'error' }, + { intercept_status: 'exception' }, + ]; + } + + const { page, pageSize, offset } = this.getPagination(data.pagination); + const result = await DeliveryModel.findAndCountAll({ + where, + attributes: [ + 'id', + 'delivery_order_code', + 'status', + 'post_status', + 'pick_status', + 'pack_status', + 'inspection_status', + 'outbound_status', + 'intercept_status', + 'updated_at', + 'store_id', + 'warehouse_id', + 'buyer_nick', + 'logistics_name', + ], + offset, + limit: pageSize, + order: [ [ 'updated_at', 'DESC' ], [ 'id', 'DESC' ] ], + raw: true, + }); + + return this.success('ok', { + data: this.buildListData(result.rows, result.count, page, pageSize, { + queryInfo: { + defaultExceptionFilter: !hasExceptionFilter, + }, + }), + code: 200, + }); + } catch (error) { + return this.fail(error.message, { code: 500 }); + } + } +} + +module.exports = ExpectionOrderService; \ No newline at end of file diff --git a/app/service/systemMethods/order/index.js b/app/service/systemMethods/order/index.js new file mode 100644 index 0000000..7bf532b --- /dev/null +++ b/app/service/systemMethods/order/index.js @@ -0,0 +1,204 @@ +'use strict'; + +const OrderBaseService = require('./base'); + +class OrderIndexService extends OrderBaseService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list,detail,listItems,stats,getreviewOrderlist,updateStatus,updateDeliveryTime,reviewOrder'; + const _noNeedLog = 'list,detail,listItems,stats,getreviewOrderlist'; + const _noNeedAuth = 'list,detail,listItems,stats,getreviewOrderlist,updateStatus,updateDeliveryTime,reviewOrder'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + async list(data = {}) { + try { + const warehouseId = this.ensureWarehouseId(data); + const { DeliveryModel } = await this.getOrderModels(warehouseId); + const where = this.buildWhere(data.where || {}, warehouseId); + const { page, pageSize, offset } = this.getPagination(data.pagination); + + const result = await DeliveryModel.findAndCountAll({ + where, + offset, + limit: pageSize, + order: [ [ 'updated_at', 'DESC' ], [ 'id', 'DESC' ] ], + raw: true, + }); + + return this.success('ok', { + data: this.buildListData(result.rows, result.count, page, pageSize), + code: 200, + }); + } catch (error) { + return this.fail(error.message, { code: 500 }); + } + } + + async detail(data = {}) { + try { + const warehouseId = this.ensureWarehouseId(data); + const { DeliveryModel, OrderItemsModel } = await this.getOrderModels(warehouseId); + const where = this.getOrderLocatorWhere(data, warehouseId); + + const order = await DeliveryModel.findOne({ where, raw: true }); + if (!order) { + return this.fail('订单不存在', { code: 404 }); + } + + const items = await OrderItemsModel.findAll({ + where: { order_id: order.id }, + order: [ [ 'id', 'ASC' ] ], + raw: true, + }); + + return this.success('ok', { + data: { order, items }, + code: 200, + }); + } catch (error) { + return this.fail(error.message, { code: 500 }); + } + } + + async listItems(data = {}) { + try { + const warehouseId = this.ensureWarehouseId(data); + const { DeliveryModel, OrderItemsModel } = await this.getOrderModels(warehouseId); + const where = this.getOrderLocatorWhere(data, warehouseId); + + const order = await DeliveryModel.findOne({ + where, + attributes: [ 'id', 'delivery_order_code' ], + raw: true, + }); + if (!order) { + return this.fail('订单不存在', { code: 404 }); + } + + const items = await OrderItemsModel.findAll({ + where: { order_id: order.id }, + order: [ [ 'id', 'ASC' ] ], + raw: true, + }); + + return this.success('ok', { + data: { order, items }, + code: 200, + }); + } catch (error) { + return this.fail(error.message, { code: 500 }); + } + } + + async stats(data = {}) { + try { + const warehouseId = this.ensureWarehouseId(data); + const { Sequelize } = this.app; + const { DeliveryModel } = await this.getOrderModels(warehouseId); + const where = this.buildWhere(data.where || {}, warehouseId); + + const total = await DeliveryModel.count({ where }); + const byStatusRows = await DeliveryModel.findAll({ + where, + attributes: [ 'status', [ Sequelize.fn('COUNT', Sequelize.col('id')), 'count' ] ], + group: [ 'status' ], + raw: true, + }); + const byOutboundRows = await DeliveryModel.findAll({ + where, + attributes: [ 'outbound_status', [ Sequelize.fn('COUNT', Sequelize.col('id')), 'count' ] ], + group: [ 'outbound_status' ], + raw: true, + }); + + return this.success('ok', { + data: { + total, + byStatus: byStatusRows, + byOutboundStatus: byOutboundRows, + }, + code: 200, + }); + } catch (error) { + return this.fail(error.message, { code: 500 }); + } + } + + async getreviewOrderlist(data = {}) { + return await this.ctx.service.systemMethods.order.reviewOrder.getreviewOrderlist(data); + } + + async updateStatus(data = {}) { + try { + const warehouseId = this.ensureWarehouseId(data); + const { DeliveryModel } = await this.getOrderModels(warehouseId); + const where = this.getOrderLocatorWhere(data, warehouseId); + + const allowedFields = [ + 'status', + 'post_status', + 'storage_status', + 'pick_status', + 'pack_status', + 'inspection_status', + 'print_status', + 'claim_status', + 'outbound_status', + 'lock_status', + 'intercept_status', + ]; + + const updateData = {}; + for (const key of allowedFields) { + if (data[key] !== undefined && data[key] !== null && data[key] !== '') { + updateData[key] = data[key]; + } + } + + if (data.delivery_time) { + updateData.delivery_time = this.parseDateTime(data.delivery_time, 'delivery_time'); + } + + if (!updateData.delivery_time && updateData.outbound_status === 'fin') { + updateData.delivery_time = new Date(); + } + + if (Object.keys(updateData).length === 0) { + return this.fail('没有可更新字段', { code: 400 }); + } + + updateData.updated_at = new Date(); + + const [ affected ] = await DeliveryModel.update(updateData, { where }); + if (!affected) { + return this.fail('订单不存在或未更新', { code: 404 }); + } + + const order = await DeliveryModel.findOne({ where, raw: true }); + return this.success('更新成功', { data: order, code: 200 }); + } catch (error) { + return this.fail(error.message, { code: 500 }); + } + } + + async updateDeliveryTime(data = {}) { + if (!data.delivery_time) { + return this.fail('delivery_time 必填', { code: 400 }); + } + + const nextData = { ...data }; + if (nextData.syncOutboundStatus === true || nextData.syncOutboundStatus === 1 || nextData.syncOutboundStatus === '1') { + nextData.outbound_status = 'fin'; + } + + return await this.updateStatus(nextData); + } + + async reviewOrder(data = {}) { + return await this.ctx.service.systemMethods.order.reviewOrder.reviewOrder(data); + } +} + +module.exports = OrderIndexService; \ No newline at end of file diff --git a/app/service/systemMethods/order/pendingOrder.js b/app/service/systemMethods/order/pendingOrder.js new file mode 100644 index 0000000..4c8d655 --- /dev/null +++ b/app/service/systemMethods/order/pendingOrder.js @@ -0,0 +1,69 @@ +'use strict'; + +const OrderBaseService = require('./base'); + +class PendingOrderService extends OrderBaseService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'getpendingOrderlist'; + const _noNeedLog = 'getpendingOrderlist'; + const _noNeedAuth = 'getpendingOrderlist'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + async getpendingOrderlist(data = {}) { + try { + const warehouseId = this.ensureWarehouseId(data); + const { Op } = this.app.Sequelize; + const { DeliveryModel } = await this.getOrderModels(warehouseId); + const whereData = data.where || {}; + const where = this.buildWhere(whereData, warehouseId); + + const hasStatusFilter = whereData.status !== undefined && whereData.status !== null && whereData.status !== ''; + const hasOutboundFilter = whereData.outbound_status !== undefined && whereData.outbound_status !== null && whereData.outbound_status !== ''; + + if (!hasStatusFilter) { + where.status = { [Op.in]: [ 'pedding', 'created' ] }; + } + if (!hasOutboundFilter) { + where.outbound_status = 'none'; + } + + const { page, pageSize, offset } = this.getPagination(data.pagination); + const result = await DeliveryModel.findAndCountAll({ + where, + attributes: [ + 'id', + 'delivery_order_code', + 'status', + 'outbound_status', + 'inspection_status', + 'updated_at', + 'store_id', + 'warehouse_id', + 'buyer_nick', + 'logistics_name', + ], + offset, + limit: pageSize, + order: [ [ 'updated_at', 'DESC' ], [ 'id', 'DESC' ] ], + raw: true, + }); + + return this.success('ok', { + data: this.buildListData(result.rows, result.count, page, pageSize, { + queryInfo: { + defaultPendingStatusFilter: !hasStatusFilter, + defaultPendingOutboundFilter: !hasOutboundFilter, + }, + }), + code: 200, + }); + } catch (error) { + return this.fail(error.message, { code: 500 }); + } + } +} + +module.exports = PendingOrderService; \ No newline at end of file diff --git a/app/service/systemMethods/order/reviewOrder.js b/app/service/systemMethods/order/reviewOrder.js new file mode 100644 index 0000000..ad994b8 --- /dev/null +++ b/app/service/systemMethods/order/reviewOrder.js @@ -0,0 +1,103 @@ +'use strict'; + +const OrderBaseService = require('./base'); + +class ReviewOrderService extends OrderBaseService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'getreviewOrderlist,reviewOrder'; + const _noNeedLog = 'getreviewOrderlist'; + const _noNeedAuth = 'getreviewOrderlist,reviewOrder'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + async getreviewOrderlist(data = {}) { + try { + const warehouseId = this.ensureWarehouseId(data); + const { Op } = this.app.Sequelize; + const { DeliveryModel } = await this.getOrderModels(warehouseId); + const whereData = data.where || {}; + const where = this.buildWhere(whereData, warehouseId); + + const hasInspectionFilter = whereData.inspection_status !== undefined && whereData.inspection_status !== null && whereData.inspection_status !== ''; + if (!hasInspectionFilter) { + where.inspection_status = { [Op.ne]: 'none' }; + } + + if (whereData.operator_name) { + where.operator_name = { [Op.like]: `%${whereData.operator_name}%` }; + } + + this.applyDateRange(where, 'operate_time', whereData.operate_time_start, whereData.operate_time_end); + + const { page, pageSize, offset } = this.getPagination(data.pagination); + const result = await DeliveryModel.findAndCountAll({ + where, + attributes: [ + 'id', + 'delivery_order_code', + 'status', + 'inspection_status', + 'operator_name', + 'operate_time', + 'updated_at', + 'store_id', + 'warehouse_id', + 'buyer_nick', + 'logistics_name', + ], + offset, + limit: pageSize, + order: [ [ 'operate_time', 'DESC' ], [ 'updated_at', 'DESC' ], [ 'id', 'DESC' ] ], + raw: true, + }); + + return this.success('ok', { + data: this.buildListData(result.rows, result.count, page, pageSize, { + queryInfo: { + defaultInspectionFilter: !hasInspectionFilter, + }, + }), + code: 200, + }); + } catch (error) { + return this.fail(error.message, { code: 500 }); + } + } + + async reviewOrder(data = {}) { + try { + const warehouseId = this.ensureWarehouseId(data); + const { DeliveryModel } = await this.getOrderModels(warehouseId); + const where = this.getOrderLocatorWhere(data, warehouseId); + + const reviewStatus = String( + data.review_status ?? data.reviewStatus ?? data.inspection_status ?? 'fin' + ).trim(); + const allowedReviewStatus = new Set([ 'none', 'padding', 'running', 'fin', 'error' ]); + if (!allowedReviewStatus.has(reviewStatus)) { + return this.fail('review_status 参数不合法', { code: 400 }); + } + + const updateData = { + inspection_status: reviewStatus, + operator_name: data.operator_name || this.ctx.user?.real_name || this.ctx.user?.username || null, + operate_time: data.operate_time ? this.parseDateTime(data.operate_time, 'operate_time') : new Date(), + updated_at: new Date(), + }; + + const [ affected ] = await DeliveryModel.update(updateData, { where }); + if (!affected) { + return this.fail('订单不存在或未更新', { code: 404 }); + } + + const order = await DeliveryModel.findOne({ where, raw: true }); + return this.success('审核成功', { data: order, code: 200 }); + } catch (error) { + return this.fail(error.message, { code: 500 }); + } + } +} + +module.exports = ReviewOrderService; \ No newline at end of file diff --git a/app/service/systemMethods/user.js b/app/service/systemMethods/user.js index 1a83b5d..79d4d76 100644 --- a/app/service/systemMethods/user.js +++ b/app/service/systemMethods/user.js @@ -5,7 +5,7 @@ const MainService = require('../main'); class userService extends MainService { constructor(ctx) { super(ctx); - const _noNeedLogin = 'login,register'; + const _noNeedLogin = 'login,loginByCode,register'; const _noNeedRight = '*'; const _noNeedLog = 'info'; const _noNeedAuth = '*'; @@ -22,6 +22,45 @@ class userService extends MainService { return this.fail('登录失败:' + result.message, result); } + async loginByCode(data) { + const { service } = this; + const code = typeof data?.code === 'string' ? data.code.trim() : ''; + if (!code) { + return this.fail('登录失败:缺少登录码 code', { + success: false, + data: null, + code: 0, + message: '缺少登录码 code', + }); + } + //code先进行base64解码,看是否为json以及json是否有uuid字段,如果有则继续执行否则返回报错 + let decoded; + try { + const buffer = Buffer.from(code, 'base64'); + const decodedStr = buffer.toString('utf-8'); + decoded = JSON.parse(decodedStr); + } catch (err) { + return this.fail('登录失败:无效的登录码格式', { + success: false, + data: null, + code: 0, + message: '无效的登录码格式', + }); + } + if (!decoded || typeof decoded !== 'object' || !decoded.uuid) { + return this.fail('登录失败:登录码缺少必要的uuid字段', { + success: false, + data: null, + code: 0, + message: '登录码缺少必要的uuid字段', + }); + } + const result = await service.systems.auth.user.loginByCode(code); + if (result.code) { + return this.success('登录成功', result); + } + return this.fail('登录失败:' + result.message, result); + } async logout() { return this.success('登出成功'); } diff --git a/app/service/systems/account_platform.js b/app/service/systems/account_platform.js index 7f1af72..c0e2627 100644 --- a/app/service/systems/account_platform.js +++ b/app/service/systems/account_platform.js @@ -3,22 +3,85 @@ const Service = require('egg').Service; class AccountPlatformService extends Service { + getActiveInclude(ctx) { + return [ + { + model: ctx.model.AccountStoreEmployee, + as: 'accountStoreEmployee', + where: { status: 1 }, + required: true, + include: [ + { + model: ctx.model.EmployeeRole, + as: 'employeeRoles', + required: false, + attributes: [ 'id', 'employee_id', 'role_id' ], + include: [ + { + model: ctx.model.Role, + as: 'role', + attributes: [ 'id', 'name', 'code', 'permissions', 'description' ], + }, + ], + }, + { + model: ctx.model.Store, + as: 'store', + attributes: [ 'id', 'name', 'code' ], + }, + ], + }, + ]; + } + + getPrimaryRoleBinding(accountStoreEmployee) { + const bindings = Array.isArray(accountStoreEmployee?.employeeRoles) + ? accountStoreEmployee.employeeRoles + : []; + return bindings.length > 0 ? bindings[0] : null; + } + + formatActiveContext(platformActive) { + if (!platformActive || !platformActive.accountStoreEmployee) { + return null; + } + + const employee = platformActive.accountStoreEmployee; + const roleBinding = this.getPrimaryRoleBinding(employee); + const role = roleBinding?.role || null; + const store = employee.store || null; + + return { + account_id: platformActive.account_id, + platform_code: platformActive.platform_code, + role_id: roleBinding ? roleBinding.role_id : null, + role_name: role ? role.name : '', + role_code: role ? role.code : '', + role_permissions: role ? role.permissions : [], + store_id: employee.store_id, + store_name: store ? store.name : '', + store_code: store ? store.code : '', + created_at: platformActive.created_at, + updated_at: platformActive.updated_at, + }; + } + /** * 切换平台激活角色 * @param {number} accountId - 账号ID - * @param {number} accountStoreRoleId - 账号仓库角色关联ID + * @param {number} accountStoreRoleId - 账号仓库员工关联ID(保持历史参数名兼容) * @param {string} platformCode - 平台编码 * @return {Promise} */ async switchActiveRole(accountId, accountStoreRoleId, platformCode) { - const { ctx, app } = this; + const { ctx } = this; // 使用事务确保数据一致性 const transaction = await ctx.model.transaction(); try { - // 1. 验证角色关联的有效性 - const accountStoreRole = await ctx.model.AccountStoreRole.findOne({ + // 1. 验证员工关联的有效性 + const accountStoreEmployee = await ctx.model.AccountStoreEmployee.findOne({ where: { id: accountStoreRoleId, account_id: accountId, @@ -27,18 +90,33 @@ class AccountPlatformService extends Service { transaction, }); - if (!accountStoreRole) { + if (!accountStoreEmployee) { throw new Error('角色关联不存在或已失效'); } + const existingActive = await ctx.model.AccountPlatformActive.findOne({ + where: { + account_id: accountId, + platform_code: platformCode, + }, + transaction, + }); + // 2. 使用 upsert 切换激活角色 - const [ platformActive, created ] = await ctx.model.AccountPlatformActive.upsert({ + await ctx.model.AccountPlatformActive.upsert({ account_id: accountId, - account_store_role_id: accountStoreRoleId, + employee_id: accountStoreRoleId, platform_code: platformCode, }, { transaction, - returning: true, + }); + + const platformActive = await ctx.model.AccountPlatformActive.findOne({ + where: { + account_id: accountId, + platform_code: platformCode, + }, + transaction, }); await transaction.commit(); @@ -48,7 +126,7 @@ class AccountPlatformService extends Service { return { success: true, - created, + created: !existingActive, data: platformActive, }; } catch (error) { @@ -56,7 +134,7 @@ class AccountPlatformService extends Service { // 处理唯一约束冲突 if (error.name === 'SequelizeUniqueConstraintError') { - // 如果是 account_store_role_id 和 platform_code 冲突,说明同一个平台不能关联到不同的账号 + // 如果是 employee_id 和 platform_code 冲突,说明同一个平台不能关联到不同账号 if (error.errors && error.errors.some(e => e.path === 'uk_account_store_role_platform')) { throw new Error('该角色已被其他账号在同一平台激活'); } @@ -97,26 +175,7 @@ class AccountPlatformService extends Service { account_id: accountId, platform_code: platformCode, }, - include: [ - { - model: ctx.model.AccountStoreRole, - as: 'accountStoreRole', - where: { status: 1 }, - required: true, - include: [ - { - model: ctx.model.Role, - as: 'role', - attributes: [ 'id', 'name', 'code', 'permissions' ], - }, - { - model: ctx.model.Store, - as: 'store', - attributes: [ 'id', 'name', 'code' ], - }, - ], - }, - ], + include: this.getActiveInclude(ctx), }); if (!platformActive) { @@ -124,19 +183,7 @@ class AccountPlatformService extends Service { } // 整理返回数据 - const result = { - account_id: accountId, - platform_code: platformCode, - role_id: platformActive.accountStoreRole.role_id, - role_name: platformActive.accountStoreRole.role.name, - role_code: platformActive.accountStoreRole.role.code, - role_permissions: platformActive.accountStoreRole.role.permissions, - store_id: platformActive.accountStoreRole.store_id, - store_name: platformActive.accountStoreRole.store.name, - store_code: platformActive.accountStoreRole.store.code, - created_at: platformActive.created_at, - updated_at: platformActive.updated_at, - }; + const result = this.formatActiveContext(platformActive); // 缓存结果 if (useCache) { @@ -164,40 +211,22 @@ class AccountPlatformService extends Service { account_id: accountId, platform_code: platformCodes, }, - include: [ - { - model: ctx.model.AccountStoreRole, - as: 'accountStoreRole', - where: { status: 1 }, - required: true, - include: [ - { - model: ctx.model.Role, - as: 'role', - attributes: [ 'id', 'name', 'code' ], - }, - { - model: ctx.model.Store, - as: 'store', - attributes: [ 'id', 'name', 'code' ], - }, - ], - }, - ], + include: this.getActiveInclude(ctx), }); // 转换为平台编码为key的对象 const result = {}; platformActives.forEach(active => { + const context = this.formatActiveContext(active); result[active.platform_code] = { - role_id: active.accountStoreRole.role_id, - role_name: active.accountStoreRole.role.name, - role_code: active.accountStoreRole.role.code, - store_id: active.accountStoreRole.store_id, - store_name: active.accountStoreRole.store.name, - store_code: active.accountStoreRole.store.code, - created_at: active.created_at, - updated_at: active.updated_at, + role_id: context ? context.role_id : null, + role_name: context ? context.role_name : '', + role_code: context ? context.role_code : '', + store_id: context ? context.store_id : null, + store_name: context ? context.store_name : '', + store_code: context ? context.store_code : '', + created_at: context ? context.created_at : active.created_at, + updated_at: context ? context.updated_at : active.updated_at, }; }); @@ -221,40 +250,24 @@ class AccountPlatformService extends Service { const platformActives = await ctx.model.AccountPlatformActive.findAll({ where: { account_id: accountId }, - include: [ - { - model: ctx.model.AccountStoreRole, - as: 'accountStoreRole', - where: { status: 1 }, - required: true, - include: [ - { - model: ctx.model.Role, - as: 'role', - attributes: [ 'id', 'name', 'code' ], - }, - { - model: ctx.model.Store, - as: 'store', - attributes: [ 'id', 'name', 'code' ], - }, - ], - }, - ], + include: this.getActiveInclude(ctx), order: [[ 'platform_code', 'ASC' ]], }); - return platformActives.map(active => ({ - platform_code: active.platform_code, - role_id: active.accountStoreRole.role_id, - role_name: active.accountStoreRole.role.name, - role_code: active.accountStoreRole.role.code, - store_id: active.accountStoreRole.store_id, - store_name: active.accountStoreRole.store.name, - store_code: active.accountStoreRole.store.code, - created_at: active.created_at, - updated_at: active.updated_at, - })); + return platformActives.map(active => { + const context = this.formatActiveContext(active); + return { + platform_code: active.platform_code, + role_id: context ? context.role_id : null, + role_name: context ? context.role_name : '', + role_code: context ? context.role_code : '', + store_id: context ? context.store_id : null, + store_name: context ? context.store_name : '', + store_code: context ? context.store_code : '', + created_at: active.created_at, + updated_at: active.updated_at, + }; + }); } /** @@ -318,13 +331,21 @@ class AccountPlatformService extends Service { where.store_id = storeId; } - const accountStoreRoles = await ctx.model.AccountStoreRole.findAll({ + const accountStoreEmployees = await ctx.model.AccountStoreEmployee.findAll({ where, include: [ { - model: ctx.model.Role, - as: 'role', - attributes: [ 'id', 'name', 'code', 'description' ], + model: ctx.model.EmployeeRole, + as: 'employeeRoles', + required: false, + attributes: [ 'id', 'employee_id', 'role_id' ], + include: [ + { + model: ctx.model.Role, + as: 'role', + attributes: [ 'id', 'name', 'code', 'description' ], + }, + ], }, { model: ctx.model.Store, @@ -334,23 +355,35 @@ class AccountPlatformService extends Service { ], order: [ [ 'store_id', 'ASC' ], - [ 'role_id', 'ASC' ], + [ 'id', 'ASC' ], ], }); - return accountStoreRoles.map(item => ({ - id: item.id, - account_id: item.account_id, - store_id: item.store_id, - store_name: item.store.name, - store_code: item.store.code, - role_id: item.role_id, - role_name: item.role.name, - role_code: item.role.code, - role_description: item.role.description, - real_name: item.real_name, - created_at: item.created_at, - })); + const rows = []; + for (const employee of accountStoreEmployees) { + const roleBindings = Array.isArray(employee.employeeRoles) + ? employee.employeeRoles + : []; + for (const binding of roleBindings) { + const role = binding.role; + if (!role) continue; + rows.push({ + id: employee.id, + account_id: employee.account_id, + store_id: employee.store_id, + store_name: employee.store ? employee.store.name : '', + store_code: employee.store ? employee.store.code : '', + role_id: binding.role_id, + role_name: role.name, + role_code: role.code, + role_description: role.description, + real_name: employee.real_name, + created_at: employee.created_at, + }); + } + } + + return rows; } /** diff --git a/app/service/systems/auth/user.js b/app/service/systems/auth/user.js index 0d217ac..3bc99ee 100644 --- a/app/service/systems/auth/user.js +++ b/app/service/systems/auth/user.js @@ -48,53 +48,7 @@ class UserService extends Service { // 4. 更新最后登录时间 await this.updateLastLoginTime(user.id); - // 5. 设置设备类型(用于菜单查询) - const platformCode = ctx.header.platform || 'web'; - // 6. 获取用户完整信息 - const userInfo = await this.findById(user.id); - console.log('用户信息', userInfo); - // 7. 如果用户有角色但当前平台没有激活角色,则自动设置一个 - if (userInfo.roles && userInfo.roles.length > 0 && !userInfo.role_id) { - await this.ensurePlatformActiveRole(user.id, userInfo.roles[0].id, platformCode); - } - - // 8. 生成 JWT Token - const tokenPayload = { - id: user.id, - username: user.username, - real_name: user.real_name, - platform_code: platformCode, - current_role_id: userInfo.employees_id, - current_store_id: userInfo.store_id || null, - }; - - const token = app.jwt.sign(tokenPayload, app.config.jwt.secret, { - expiresIn: app.config.jwt.expiresIn, - }); - - return { - success: true, - data: { - user: { - id: user.id, - username: user.username, - real_name: user.real_name, - phone: user.phone, - email: user.email, - status: user.status, - last_login_at: user.last_login_at, - roles: userInfo.roles, - role_id: userInfo.role_id, - menus: userInfo.menus, - permissions: userInfo.permissions, - userRole: userInfo.userRole, - realName: userInfo.realName, - }, - token, - }, - code: 200, - message: '登录成功', - }; + return this.buildLoginResult(user, { includeUser: false }); } catch (error) { app.coreLogger.error(`登录异常: ${error.message}`); @@ -108,6 +62,154 @@ class UserService extends Service { } } + /** + * 登录码登录:使用 ye4s_user.tmp_code 绑定的 wms_account_id 登录 + * @param {string} code 登录码(ye4s_user.tmp_code) + * @return {Object} 登录结果 + */ + async loginByCode(code) { + const { ctx, app } = this; + + try { + const normalizedCode = typeof code === 'string' ? code.trim() : ''; + if (!normalizedCode) { + return { + success: false, + data: null, + code: 0, + message: '缺少登录码 code', + }; + } + + const ye4sClient = ctx.app.mysql.get('ye4s'); + const ye4sUser = await ye4sClient.get('ye4s_user', { + tmp_code: normalizedCode, + }); + + if (!ye4sUser) { + return { + success: false, + data: null, + code: 0, + message: '登录码不存在', + }; + } + + const wmsAccountId = Number(ye4sUser.wms_account_id); + if (!Number.isFinite(wmsAccountId) || wmsAccountId <= 0) { + return { + success: false, + data: null, + code: 0, + message: '该登录码未绑定WMS账号', + }; + } + + const user = await ctx.model.Account.findOne({ + where: { id: wmsAccountId }, + }); + + if (!user) { + return { + success: false, + data: null, + code: 0, + message: '绑定的WMS账号不存在', + }; + } + + try { + this.checkUserStatus(user); + } catch (statusError) { + app.coreLogger.warn(`登录码登录失败: 账号状态异常 [${user.id}] - ${statusError.message}`); + return { + success: false, + data: null, + code: 0, + message: '绑定账号状态异常', + }; + } + + await this.updateLastLoginTime(user.id); + return this.buildLoginResult(user); + } catch (error) { + app.coreLogger.error(`登录码登录异常: ${error.message}`); + return { + success: false, + data: null, + code: 0, + message: '登录失败,请稍后重试', + }; + } + } + + /** + * 生成统一登录成功结构 + * @param {Object} user + * @return {Object} + */ + async buildLoginResult(user, options = {}) { + const { ctx, app } = this; + const includeUser = options.includeUser !== false; + + // 设置设备类型(用于菜单查询) + const platformCode = ctx.header.platform || 'web'; + // 获取用户完整信息 + const userInfo = await this.findById(user.id); + console.log('用户信息', userInfo); + if (!userInfo) { + throw new Error('用户信息加载失败'); + } + + // 如果用户有角色但当前平台没有激活角色,则自动设置一个 + if (userInfo && userInfo.roles && userInfo.roles.length > 0 && !userInfo.role_id) { + await this.ensurePlatformActiveRole(user.id, userInfo.roles[0].id, platformCode); + } + + // 生成 JWT Token + const tokenPayload = { + id: user.id, + username: user.username, + real_name: user.real_name, + platform_code: platformCode, + current_role_id: userInfo.employees_id, + current_store_id: userInfo.store_id || null, + }; + + const token = app.jwt.sign(tokenPayload, app.config.jwt.secret, { + expiresIn: app.config.jwt.expiresIn, + }); + + const payloadData = { + token, + }; + + if (includeUser) { + payloadData.user = { + id: user.id, + username: user.username, + real_name: user.real_name, + phone: user.phone, + email: user.email, + status: user.status, + last_login_at: user.last_login_at, + roles: userInfo.roles, + role_id: userInfo.role_id, + menus: userInfo.menus, + permissions: userInfo.permissions, + userRole: userInfo.userRole, + realName: userInfo.realName, + }; + } + + return { + success: true, + data: payloadData, + code: 200, + message: '登录成功', + }; + } + /** * 切换角色(重构版) * @param {Object} data - 切换角色数据 @@ -120,7 +222,7 @@ class UserService extends Service { const user = ctx.state.user || ctx.user; try { // 验证角色关联是否存在且有效 - const accountStoreRole = await ctx.model.AccountStoreEmployee.findOne({ + const accountStoreEmployee = await ctx.model.AccountStoreEmployee.findOne({ where: { id: data.roleId, account_id: user.id, @@ -129,12 +231,12 @@ class UserService extends Service { include: [ { model: ctx.model.EmployeeRole, - as: 'employeeRole', + as: 'employeeRoles', }, ], }); - if (!accountStoreRole) { + if (!accountStoreEmployee) { throw new Error('角色不存在或未授权'); } @@ -159,7 +261,7 @@ class UserService extends Service { real_name: user.real_name, platform_code: platformCode, current_role_id: userInfo.employees_id, - current_store_id: accountStoreRole.store_id || null, + current_store_id: accountStoreEmployee.store_id || null, }; const newToken = app.jwt.sign(tokenPayload, app.config.jwt.secret, { expiresIn: app.config.jwt.expiresIn, @@ -240,7 +342,7 @@ class UserService extends Service { include: [ { model: ctx.model.EmployeeRole, - as: 'employeeRole', + as: 'employeeRoles', attributes: [ 'id', 'role_id' ], }, { @@ -546,11 +648,23 @@ class UserService extends Service { } try { - // 1. 获取员工的角色 + // 1. 获取员工绑定且启用的角色 const roles = await ctx.model.EmployeeRole.findAll({ + attributes: [ 'role_id' ], where: { employee_id: activeEmployeeId, }, + include: [ + { + model: ctx.model.Role, + as: 'role', + attributes: [], + where: { + status: 1, + }, + required: true, + }, + ], raw: true, // 获取纯数据对象 }); console.log('员工绑定的角色', roles); @@ -558,7 +672,10 @@ class UserService extends Service { return []; } - const roleIds = roles.map(item => item.role_id); + const roleIds = [ ...new Set(roles.map(item => item.role_id).filter(Boolean)) ]; + if (roleIds.length === 0) { + return []; + } // 2. 获取角色的权限 const rolePermissions = await ctx.model.RolePermission.findAll({ @@ -573,13 +690,17 @@ class UserService extends Service { return []; } - const permissionIds = rolePermissions.map(item => item.permission_id); + const permissionIds = [ ...new Set(rolePermissions.map(item => item.permission_id).filter(Boolean)) ]; + if (permissionIds.length === 0) { + return []; + } const permissions = await ctx.model.Permission.findAll({ where: { id: { [Op.in]: permissionIds, }, + status: 1, // 修正 like 查询 type: { [ctx.app.Sequelize.Op.notLike]: '%_pages', @@ -613,11 +734,23 @@ class UserService extends Service { } try { - // 1. 获取员工的角色 + // 1. 获取员工绑定且启用的角色 const roles = await ctx.model.EmployeeRole.findAll({ + attributes: [ 'role_id' ], where: { employee_id: activeEmployeeId, }, + include: [ + { + model: ctx.model.Role, + as: 'role', + attributes: [], + where: { + status: 1, + }, + required: true, + }, + ], raw: true, // 获取纯数据对象 }); console.log('员工绑定的角色', roles); @@ -625,7 +758,10 @@ class UserService extends Service { return []; } - const roleIds = roles.map(item => item.role_id); + const roleIds = [ ...new Set(roles.map(item => item.role_id).filter(Boolean)) ]; + if (roleIds.length === 0) { + return []; + } // 2. 获取角色的权限 const rolePermissions = await ctx.model.RolePermission.findAll({ @@ -640,7 +776,10 @@ class UserService extends Service { return []; } - const permissionIds = rolePermissions.map(item => item.permission_id); + const permissionIds = [ ...new Set(rolePermissions.map(item => item.permission_id).filter(Boolean)) ]; + if (permissionIds.length === 0) { + return []; + } // 3. 获取权限对应的菜单(根据设备筛选) const permissions = await ctx.model.Permission.findAll({ @@ -648,6 +787,7 @@ class UserService extends Service { id: { [Op.in]: permissionIds, }, + status: 1, // 修正 like 查询 type: { [Op.like]: `${ctx.header.platform}_%`, @@ -697,7 +837,7 @@ class UserService extends Service { // 构建树形结构 data.forEach(item => { const node = map.get(item.id); - if (item.parent_id === 0) { + if (!item.parent_id) { roots.push(node); } else { const parent = map.get(item.parent_id); diff --git a/app/service/systems/entry_order.js b/app/service/systems/entry_order.js index 36a6788..b2641a6 100644 --- a/app/service/systems/entry_order.js +++ b/app/service/systems/entry_order.js @@ -230,6 +230,348 @@ class entryOrderService extends Service { }; } + async findByOrderCode(entryOrderCode, warehouseId, storeId) { + const { ctx } = this; + + return await ctx.model.EntryOrder.findOne({ + where: { + entry_order_code: entryOrderCode, + warehouse_id: warehouseId, + store_id: storeId, + is_enabled: 1, + deleted_at: null, + }, + include: [ + { + model: ctx.model.Store, + as: 'warehouse', + attributes: [[ 'company_name', 'store_name' ]], + }, + { + model: ctx.model.Store, + as: 'store', + attributes: [[ 'company_name', 'store_name' ]], + }, + { + model: ctx.model.EntryItems, + as: 'items', + include: [ + { + model: ctx.model.StockWarehouse, + as: 'stock', + attributes: [ 'product_code', 'product_name' ], + }, + ], + }, + ], + }); + } + + async findByStatus(status, params = {}) { + const { ctx, app } = this; + const { warehouse_id, store_id, start_date, end_date, page = 1, pageSize = 20 } = params; + + const where = { + order_status: status, + is_enabled: 1, + deleted_at: null, + }; + + if (warehouse_id) { + where.warehouse_id = warehouse_id; + } + + if (store_id) { + where.store_id = store_id; + } + + if (start_date || end_date) { + where.created_at = {}; + if (start_date) { + where.created_at[app.Sequelize.Op.gte] = start_date; + } + if (end_date) { + where.created_at[app.Sequelize.Op.lte] = end_date; + } + } + + const currentPage = Math.max(Number(page) || 1, 1); + const currentPageSize = Math.max(Number(pageSize) || 20, 1); + + const { count, rows } = await ctx.model.EntryOrder.findAndCountAll({ + where, + include: [ + { + model: ctx.model.Store, + as: 'warehouse', + attributes: [[ 'company_name', 'store_name' ]], + }, + { + model: ctx.model.Store, + as: 'store', + attributes: [[ 'company_name', 'store_name' ]], + }, + ], + order: [[ 'created_at', 'DESC' ]], + offset: (currentPage - 1) * currentPageSize, + limit: currentPageSize, + distinct: true, + }); + + return { + list: rows, + pagination: { + page: currentPage, + pageSize: currentPageSize, + total: count, + totalPages: Math.ceil(count / currentPageSize), + }, + }; + } + + async getStatsByWarehouse(warehouseId, startDate, endDate) { + const { ctx, app } = this; + + const where = { + warehouse_id: warehouseId, + is_enabled: 1, + deleted_at: null, + }; + + if (startDate || endDate) { + where.created_at = {}; + if (startDate) { + where.created_at[app.Sequelize.Op.gte] = startDate; + } + if (endDate) { + where.created_at[app.Sequelize.Op.lte] = endDate; + } + } + + const result = await ctx.model.EntryOrder.findAll({ + attributes: [ + 'order_status', + [ app.Sequelize.fn('COUNT', app.Sequelize.col('id')), 'count' ], + [ app.Sequelize.fn('SUM', app.Sequelize.col('total_order_lines')), 'total_lines' ], + ], + where, + group: [ 'order_status' ], + raw: true, + }); + + const stats = { + pending: 0, + confirmed: 0, + partial_received: 0, + completed: 0, + cancelled: 0, + total: 0, + total_lines: 0, + }; + + result.forEach(item => { + const status = String(item.order_status || '').toLowerCase(); + const count = parseInt(item.count, 10) || 0; + const totalLines = parseInt(item.total_lines, 10) || 0; + + if (stats[status] !== undefined) { + stats[status] = count; + } + + stats.total += count; + stats.total_lines += totalLines; + }); + + return stats; + } + + async updateSyncStatus(orderId, status, message = null, options = {}) { + const { ctx } = this; + const order = await ctx.model.EntryOrder.findByPk(orderId, { + transaction: options.transaction, + }); + + if (!order) { + throw new Error('入库单不存在'); + } + + const updateData = { + sync_status: status, + }; + + if (message !== null) { + updateData.sync_message = message; + } + + return await order.update(updateData, { + transaction: options.transaction, + }); + } + + async updateOrderStatus(orderId, status, options = {}) { + const { ctx } = this; + const order = await ctx.model.EntryOrder.findByPk(orderId, { + transaction: options.transaction, + }); + + if (!order) { + throw new Error('入库单不存在'); + } + + const validTransitions = { + PENDING: [ 'CONFIRMED', 'CANCELLED' ], + CONFIRMED: [ 'PARTIAL_RECEIVED', 'COMPLETED', 'CANCELLED' ], + PARTIAL_RECEIVED: [ 'COMPLETED', 'CANCELLED' ], + CREATED: [ 'PENDING', 'CANCELLED' ], + CREATING: [ 'PENDING', 'CANCELLED' ], + }; + + const allowedTransitions = validTransitions[order.order_status]; + if (!allowedTransitions || !allowedTransitions.includes(status)) { + throw new Error(`状态从${order.order_status}转换到${status}不被允许`); + } + + return await order.update({ order_status: status }, { + transaction: options.transaction, + }); + } + + async calculateReceivedQuantities(orderId) { + const { ctx, app } = this; + const order = await ctx.model.EntryOrder.findByPk(orderId, { + attributes: [ 'id', 'entry_order_code' ], + raw: true, + }); + + if (!order) { + throw new Error('入库单不存在'); + } + + const items = await ctx.model.EntryItems.findAll({ + where: { order_id: orderId }, + attributes: [ 'id', 'count', 'item_id' ], + raw: true, + }); + + const itemIds = [ ...new Set(items.map(item => item.item_id).filter(Boolean)) ]; + const receivedRows = itemIds.length > 0 + ? await ctx.model.Storage.findAll({ + where: { + inbound_order_no: order.entry_order_code, + item_id: itemIds, + }, + attributes: [ + 'item_id', + [ app.Sequelize.fn('SUM', app.Sequelize.col('quantity')), 'received' ], + ], + group: [ 'item_id' ], + raw: true, + }) + : []; + + const receivedMap = new Map( + receivedRows.map(row => [ Number(row.item_id), Number(row.received) || 0 ]) + ); + + let totalExpected = 0; + let totalReceived = 0; + let allReceived = items.length > 0; + let anyReceived = false; + + items.forEach(item => { + const expected = Number(item.count) || 0; + const received = receivedMap.get(Number(item.item_id)) || 0; + + totalExpected += expected; + totalReceived += received; + + if (expected > 0 && received < expected) { + allReceived = false; + } + + if (received > 0) { + anyReceived = true; + } + }); + + return { + total_expected: totalExpected, + total_received: totalReceived, + all_received: allReceived, + any_received: anyReceived, + percentage: totalExpected > 0 ? Math.round((totalReceived / totalExpected) * 100) : 0, + }; + } + + async batchUpdateReceived(updates, options = {}) { + const { ctx } = this; + const externalTransaction = options.transaction || null; + const transaction = externalTransaction || await ctx.model.transaction(); + + try { + const pendingUpdates = []; + + for (const update of updates) { + const { id, quantity } = update; + const item = await ctx.model.EntryItems.findByPk(id, { transaction }); + + if (!item) { + throw new Error(`入库明细 ${id} 不存在`); + } + + item.validateReceiveQuantity(quantity); + pendingUpdates.push({ + item, + quantity, + }); + } + + for (const pending of pendingUpdates) { + const newReceived = (pending.item.received_quantity || 0) + pending.quantity; + await pending.item.update({ + received_quantity: newReceived, + }, { transaction }); + } + + if (!externalTransaction) { + await transaction.commit(); + } + + return { success: true }; + } catch (error) { + if (!externalTransaction) { + await transaction.rollback(); + } + throw error; + } + } + + async getOrderProgress(orderId) { + const { ctx, app } = this; + const items = await ctx.model.EntryItems.findAll({ + where: { order_id: orderId }, + attributes: [ + [ app.Sequelize.fn('SUM', app.Sequelize.col('count')), 'total_plan' ], + [ app.Sequelize.fn('SUM', app.Sequelize.col('received_quantity')), 'total_received' ], + [ app.Sequelize.fn('COUNT', app.Sequelize.col('id')), 'item_count' ], + ], + raw: true, + }); + + const result = items[0] || {}; + const totalPlan = parseInt(result.total_plan, 10) || 0; + const totalReceived = parseInt(result.total_received, 10) || 0; + + return { + total_plan: totalPlan, + total_received: totalReceived, + total_remaining: Math.max(0, totalPlan - totalReceived), + item_count: parseInt(result.item_count, 10) || 0, + progress_percent: totalPlan > 0 ? Math.min(100, Math.round((totalReceived / totalPlan) * 100)) : 0, + is_completed: totalReceived >= totalPlan, + }; + } + async tryCreateEntryOrder(order, appKey, storeId, warehouseId, totalOrderLines, sourceType, qimenOwnerCode, qimenWarehouseCode, transaction = null) { const { app } = this; const { ctx } = this; diff --git a/app/service/systems/stock_store.js b/app/service/systems/stock_store.js index ecb0e04..b660ff5 100644 --- a/app/service/systems/stock_store.js +++ b/app/service/systems/stock_store.js @@ -1234,15 +1234,11 @@ class stockStoreService extends Service { // 获取总数 ctx.model.StockWarehouse.count({ where: queryOptions.where, - include: [{ - model: ctx.model.StoreWarehouse, - as: 'store_stock', - attributes: [ 'store_remask' ], - where: { - use_status: 1, - }, + include: [ctx.model.StoreWarehouse.buildStoreStockInclude({ + warehouseId: ctx.user.store_id, required: true, - }, { + attributes: [ 'store_remask' ], + }), { ...prohibitedQueryOptions, model: ctx.model.ProhibitedType, as: 'prohibited', @@ -1255,15 +1251,11 @@ class stockStoreService extends Service { // 获取分页数据 ctx.model.StockWarehouse.findAll({ ...queryOptions, - include: [{ - model: ctx.model.StoreWarehouse, - as: 'store_stock', - attributes: [ 'store_remask' ], - where: { - use_status: 1, - }, + include: [ctx.model.StoreWarehouse.buildStoreStockInclude({ + warehouseId: ctx.user.store_id, required: true, - }, { + attributes: [ 'store_remask' ], + }), { ...prohibitedQueryOptions, model: ctx.model.ProhibitedType, as: 'prohibited', @@ -2792,11 +2784,11 @@ class stockStoreService extends Service { required: false, }); } - includeConditions.push({ - model: app.model.StoreWarehouse, - as: 'store_stock', + includeConditions.push(app.model.StoreWarehouse.buildStoreStockInclude({ + warehouseId, + required: false, attributes: [ 'store_id', 'store_remask' ], - }); + })); // 执行查询 console.log('查询商品===》'); diff --git a/app/service/systems/storage/index.js b/app/service/systems/storage/index.js index 3362140..2721913 100644 --- a/app/service/systems/storage/index.js +++ b/app/service/systems/storage/index.js @@ -5,5 +5,248 @@ class IndexService extends Service { async index() { } + + async findByStockAndBatch(stockId, batchNo, inventoryType = 'ZP') { + const { ctx } = this; + + return await ctx.model.Storage.findOne({ + where: { + stock_id: stockId, + batch_no: batchNo, + inventory_type: inventoryType, + is_enabled: 1, + delete_at: null, + }, + include: [ + { + model: ctx.model.LocationSpace, + as: 'space', + attributes: [ 'space_code', 'custom_name' ], + }, + { + model: ctx.model.Store, + as: 'warehouse', + attributes: [ [ 'company_name', 'store_name' ] ], + }, + ], + }); + } + + async findBySpace(spaceId) { + const { ctx } = this; + + return await ctx.model.Storage.findAll({ + where: { + space_id: spaceId, + is_enabled: 1, + delete_at: null, + }, + include: [ + { + model: ctx.model.StockWarehouse, + as: 'stock', + attributes: [ 'product_code', 'product_name' ], + }, + ], + order: [ [ 'inbound_time', 'ASC' ] ], + }); + } + + async findAvailableByWarehouse(warehouseId, stockId = null) { + const { ctx, app } = this; + const where = { + warehouse_id: warehouseId, + is_enabled: 1, + delete_at: null, + available_quantity: { [app.Sequelize.Op.gt]: 0 }, + }; + + if (stockId) { + where.stock_id = stockId; + } + + return await ctx.model.Storage.findAll({ + where, + include: [ + { + model: ctx.model.LocationSpace, + as: 'space', + attributes: [ 'space_code', 'custom_name' ], + }, + { + model: ctx.model.StockWarehouse, + as: 'stock', + attributes: [ 'product_code', 'product_name' ], + }, + ], + order: [ + [ 'expiry_date', 'ASC' ], + [ 'inbound_time', 'ASC' ], + ], + }); + } + + async findExpiringSoon(days = 30) { + const { ctx, app } = this; + const expiryDate = new Date(); + expiryDate.setDate(expiryDate.getDate() + days); + + return await ctx.model.Storage.findAll({ + where: { + expiry_date: { + [app.Sequelize.Op.between]: [ new Date(), expiryDate ], + }, + is_enabled: 1, + delete_at: null, + quantity: { [app.Sequelize.Op.gt]: 0 }, + }, + include: [ + { + model: ctx.model.Store, + as: 'warehouse', + attributes: [ [ 'company_name', 'store_name' ] ], + }, + { + model: ctx.model.StockWarehouse, + as: 'stock', + attributes: [ 'product_code', 'product_name' ], + }, + ], + order: [ [ 'expiry_date', 'ASC' ] ], + }); + } + + async updateQuantity(id, quantityChange, lockedChange = 0, options = {}) { + const { ctx } = this; + const storage = await ctx.model.Storage.findByPk(id, { + transaction: options.transaction, + }); + + if (!storage) { + throw new Error('库存记录不存在'); + } + + const newQuantity = storage.quantity + quantityChange; + const newLocked = storage.locked_quantity + lockedChange; + + if (newQuantity < 0) { + throw new Error('库存数量不能为负数'); + } + + if (newLocked < 0 || newLocked > newQuantity) { + throw new Error('锁定数量无效'); + } + + const updateData = { + quantity: newQuantity, + locked_quantity: newLocked, + available_quantity: newQuantity - newLocked, + updated_at: new Date(), + }; + + await storage.update(updateData, { + transaction: options.transaction, + }); + return storage; + } + + async lockQuantity(id, quantity, options = {}) { + return await this.updateQuantity(id, 0, quantity, options); + } + + async unlockQuantity(id, quantity, options = {}) { + return await this.updateQuantity(id, 0, -quantity, options); + } + + async allocateQuantity(id, quantity, options = {}) { + const { ctx } = this; + const storage = await ctx.model.Storage.findByPk(id, { + transaction: options.transaction, + }); + + if (!storage) { + throw new Error('库存记录不存在'); + } + + if (storage.available_quantity < quantity) { + throw new Error('可用数量不足'); + } + + return await this.updateQuantity(id, 0, quantity, options); + } + + async getStockSummary(warehouseId) { + const { ctx, app } = this; + + return await ctx.model.Storage.findAll({ + attributes: [ + 'stock_id', + 'inventory_type', + [ app.Sequelize.fn('SUM', app.Sequelize.col('quantity')), 'total_quantity' ], + [ app.Sequelize.fn('SUM', app.Sequelize.col('locked_quantity')), 'total_locked' ], + [ app.Sequelize.fn('SUM', app.Sequelize.col('available_quantity')), 'total_available' ], + ], + where: { + warehouse_id: warehouseId, + is_enabled: 1, + delete_at: null, + }, + group: [ 'stock_id', 'inventory_type' ], + raw: true, + }); + } + + async getSpaceUsage(spaceId) { + const { ctx, app } = this; + const result = await ctx.model.Storage.findAll({ + attributes: [ + 'inventory_type', + [ app.Sequelize.fn('COUNT', app.Sequelize.col('id')), 'record_count' ], + [ app.Sequelize.fn('SUM', app.Sequelize.col('quantity')), 'total_quantity' ], + ], + where: { + space_id: spaceId, + is_enabled: 1, + delete_at: null, + }, + group: [ 'inventory_type' ], + raw: true, + }); + + const usage = { + normal: 0, + defective: 0, + damaged: 0, + frozen: 0, + total: 0, + }; + + result.forEach(item => { + let type; + switch (item.inventory_type) { + case 'ZP': + type = 'normal'; + break; + case 'CC': + type = 'defective'; + break; + case 'JS': + case 'XS': + type = 'damaged'; + break; + case 'DJ': + type = 'frozen'; + break; + default: + return; + } + + usage[type] = parseInt(item.total_quantity, 10) || 0; + usage.total += usage[type]; + }); + + return usage; + + } } module.exports = IndexService; diff --git a/app/service/systems/storage/receiving.js b/app/service/systems/storage/receiving.js index 6e04e25..85c8d62 100644 --- a/app/service/systems/storage/receiving.js +++ b/app/service/systems/storage/receiving.js @@ -124,6 +124,7 @@ class ReceivingService extends Service { attributes: ['store_remask'], where: { use_status: 1, + warehouse_id: ctx.user.store_id, }, required: false, }, { @@ -144,6 +145,7 @@ class ReceivingService extends Service { attributes: ['store_remask'], where: { use_status: 1, + warehouse_id: ctx.user.store_id, }, required: false, }, { @@ -697,10 +699,14 @@ class ReceivingService extends Service { let store_name = null; if (store_id) { const store = await app.model.StoreWarehouse.findOne({ - where: { store_id }, + where: { + store_id, + warehouse_id, + use_status: 1, + }, }); if (store) { - store_name = store.store_name; + store_name = store.store_remask; } } @@ -772,6 +778,7 @@ class ReceivingService extends Service { attributes: ['store_remask'], where: { use_status: 1, + warehouse_id: warehouseId, }, required: false, }, { @@ -1142,11 +1149,11 @@ class ReceivingService extends Service { const stockWarehouse = await ctx.model.StockWarehouse.findOne({ where: { id: stock_id }, include: [ - { - model: ctx.model.StoreWarehouse, - as: 'store_stock', - attributes: ['store_id', 'store_remask'], - }, + ctx.model.StoreWarehouse.buildStoreStockInclude({ + warehouseId: ctx.user.store_id, + required: false, + attributes: [ 'store_id', 'store_remask' ], + }), ], }); @@ -1519,11 +1526,11 @@ class ReceivingService extends Service { warehouse_id: warehouseId, }, include: [ - { - model: app.model.StoreWarehouse, - as: 'store_stock', - attributes: ['store_id', 'store_remask'], - }, + app.model.StoreWarehouse.buildStoreStockInclude({ + warehouseId, + required: false, + attributes: [ 'store_id', 'store_remask' ], + }), { model: app.model.StockBarcode, as: 'barcodes', diff --git a/app/service/systems/store.js b/app/service/systems/store.js index 5fa210a..d01f0b0 100644 --- a/app/service/systems/store.js +++ b/app/service/systems/store.js @@ -434,6 +434,48 @@ class StoreService extends Service { // ==================== 辅助方法 ==================== + async ensureEmployeeRoleBinding({ accountId, storeId, roleId, realName = '', transaction }) { + const { ctx } = this; + + const [ employee ] = await ctx.model.AccountStoreEmployee.findOrCreate({ + where: { + account_id: accountId, + store_id: storeId, + }, + defaults: { + account_id: accountId, + store_id: storeId, + status: 1, + real_name: realName || '', + }, + transaction, + }); + + const shouldRefreshEmployee = Number(employee.status) !== 1 + || (realName && employee.real_name !== realName); + + if (shouldRefreshEmployee) { + await employee.update({ + status: 1, + real_name: realName || employee.real_name || '', + }, { transaction }); + } + + const [ employeeRole ] = await ctx.model.EmployeeRole.findOrCreate({ + where: { + employee_id: employee.id, + role_id: roleId, + }, + defaults: { + employee_id: employee.id, + role_id: roleId, + }, + transaction, + }); + + return { employee, employeeRole }; + } + /** * 为创建者分配管理员角色 * @param storeId @@ -460,18 +502,15 @@ class StoreService extends Service { throw new Error(`未初始化${role_code}管理员角色`); } - // 分配角色给创建者 - const storerole = await ctx.model.AccountStoreRole.create({ - account_id: userId, - store_id: storeId, - role_id: adminRole.id, - status: 1, - real_name: realName || '', - assigned_by: userId, - }, { + const { employee } = await this.ensureEmployeeRoleBinding({ + accountId: userId, + storeId, + roleId: adminRole.id, + realName: realName || '', transaction, }); - return storerole; + + return employee; } @@ -675,27 +714,13 @@ class StoreService extends Service { const { account_id, real_name } = applyData; for (const role of roles) { - // 检查是否已存在该角色分配 - const existingRole = await ctx.model.AccountStoreRole.findOne({ - where: { - account_id, - store_id, - role_id: role.id, - status: 1, - }, + await this.ensureEmployeeRoleBinding({ + accountId: account_id, + storeId: store_id, + roleId: role.id, + realName: real_name || '', transaction, }); - - if (!existingRole) { - await ctx.model.AccountStoreRole.create({ - account_id, - store_id, - role_id: role.id, - status: 1, - real_name, - join_token: code, - }, { transaction }); - } } // 更新申请记录状态 diff --git a/association_eager_loading_n_plus_one_guideline.md b/association_eager_loading_n_plus_one_guideline.md new file mode 100644 index 0000000..133d9f5 --- /dev/null +++ b/association_eager_loading_n_plus_one_guideline.md @@ -0,0 +1,102 @@ +# Association Eager-Loading 与 N+1 规约 + +更新时间: 2026-03-23 +适用阶段: Model 重构阶段 4.4 +范围: app/service/**/*.js 中涉及 Sequelize 关联查询的代码 + +## 1. 目标 + +- 降低关联查询的 SQL 次数与响应时间抖动。 +- 统一 eager-loading 写法,避免 include 漂移导致错关联。 +- 在不改变外部接口返回结构的前提下收敛查询成本。 + +## 2. 术语 + +- eager-loading: 通过 include 一次性加载关联数据。 +- N+1: 先查 1 次主数据,再按每条主数据各查 1 次关联,导致总查询次数随 N 线性增长。 +- 关联上下文约束: 在 include.where 中补齐业务维度(如 warehouse_id、use_status),避免跨上下文错关联。 + +## 3. 强制规则 + +1. 列表查询禁止在循环内按行查询关联表。 +2. 只要关联数据是展示必需字段,优先使用 include 一次加载。 +3. include 必须显式声明 attributes,禁止默认全字段拉取。 +4. include 需要业务上下文约束时,必须补齐 where 条件(典型: warehouse_id + use_status)。 +5. hasMany/hasOne/belongsTo 的 as 必须与 model 定义一致,禁止临时字符串别名。 +6. 分页列表若包含 hasMany,优先控制返回列并评估 distinct/subQuery,防止计数与分页漂移。 +7. count 与 findAll 不一致时,必须拆分并保持 where/include 语义一致。 + +## 4. 推荐写法 + +### 4.1 反模式(N+1) + +```js +const list = await Model.findAll({ where }); +for (const row of list) { + row.child = await Child.findOne({ where: { id: row.child_id } }); +} +``` + +### 4.2 规约写法(eager-loading) + +```js +const list = await Model.findAll({ + where, + attributes: [ 'id', 'name', 'child_id' ], + include: [ + { + model: Child, + as: 'child', + attributes: [ 'id', 'name' ], + required: false, + }, + ], +}); +``` + +### 4.3 仓库维度约束(本仓库高频场景) + +```js +include: [ + { + model: ctx.model.StoreWarehouse, + as: 'store_stock', + attributes: [ 'store_id', 'store_remask' ], + where: { + warehouse_id: warehouseId, + use_status: 1, + }, + required: false, + }, +] +``` + +## 5. 当前代码落地点 + +- receiving 链路已按规约补齐仓库维度过滤,避免 StoreWarehouse 跨仓匹配。 +- receiving 与 receiving_detail 已移除无效 Storage hasMany 关联,避免误导 include 设计。 +- 后续优先治理: + - store_warehouse 与 stock_warehouse 的 store_id 语义对齐 + - role / role_permission / permission 的关联约束与 include 一致性 + +## 6. 变更门禁 + +每批涉及关联查询的改动,至少执行以下门禁: + +1. node .\\script\\method-output-regression.cjs compare +2. node .\\script\\tmp-generate-method-regression-test.cjs +3. npx egg-bin test temp/generated-tests/system.method-output.generated.test.js +4. npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js + +交付标准: + +- compare 结果 mismatch=0 +- 生成回归与关键冒烟测试全部通过 + +## 7. PR 自检清单 + +- [ ] 是否存在循环内数据库查询。 +- [ ] include 是否补齐 attributes。 +- [ ] include.where 是否补齐业务上下文约束。 +- [ ] as 是否与 model 关联定义一致。 +- [ ] 是否完成 method-output compare 与回归测试。 diff --git a/association_fix_plan.md b/association_fix_plan.md new file mode 100644 index 0000000..48de8bc --- /dev/null +++ b/association_fix_plan.md @@ -0,0 +1,61 @@ +# Association Fix Plan + +更新时间: 2026-03-23 +适用阶段: Model 重构阶段 4(关联关系规范化) + +## 1. 目标 + +- 统一 alias 命名规则(belongsTo/hasOne 用单数,hasMany/belongsToMany 用复数)。 +- 清理重复或冲突关联定义,避免 include 歧义。 +- 保持 system/qimen 输出结构不变,通过 baseline/compare 门禁验证。 + +## 2. 已完成修复 + +### 2.1 幽灵模型收敛(已完成) + +- 将 AccountStoreRole 相关调用链迁移到 AccountStoreEmployee + EmployeeRole + Role + Store。 +- 覆盖主链路: + - app/service/systems/store.js + - app/service/systems/account_platform.js + - app/service/systems/auth/user.js + +### 2.2 alias 标准化(已完成) + +- 新标准 alias: + - accountStoreEmployees + - employeeRoles +- 已完成调用迁移: + - account_platform 服务 include 与读取逻辑统一为 employeeRoles + - auth/user 服务 include 统一为 employeeRoles + +### 2.3 重复关联清理(已完成) + +- 已移除以下重复兼容 alias 定义: + - Account.accountStoreRoles + - AccountStoreEmployee.employeeRole + - Role.employeeRole + - Store.accountStoreEmployee +- 保留必要单数 alias(belongsTo 语义): + - AccountPlatformActive.accountStoreEmployee + +## 3. 验证策略 + +每批改动执行以下门禁: + +1. node .\\script\\method-output-regression.cjs baseline 8 +2. node .\\script\\method-output-regression.cjs compare +3. node .\\script\\tmp-generate-method-regression-test.cjs +4. npx egg-bin test temp/generated-tests/system.method-output.generated.test.js +5. npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js + +## 4. 当前状态 + +- 输出一致性门禁:通过(mismatch=0)。 +- 关键冒烟测试:通过。 +- 对外 API 参数/返回:无结构变更。 + +## 5. 剩余工作 + +- 全量扫描其余模型类方法中的 include alias 一致性(已完成,差集扫描异常项 0 个)。 +- 评估并落地 permission.parent_id 自关联约束策略(已完成:root 语义归一为 NULL + 自关联 FK)。 +- 进入阶段 5:Model 内部能力清理与边界固化。 \ No newline at end of file diff --git a/association_fk_consistency_report.md b/association_fk_consistency_report.md new file mode 100644 index 0000000..c7a9b61 --- /dev/null +++ b/association_fk_consistency_report.md @@ -0,0 +1,65 @@ +# Association FK Consistency Report + +更新时间: 2026-03-23T03:08:35.772Z +数据库: wms + +## Summary + +- DB 外键数: 51 +- 模型关联数: 89 +- 可直接匹配外键: 53 +- 模型定义但 DB 无外键约束: 28 +- 无法解析到模型表映射: 5 +- DB 存在但模型未声明的外键: 13 + +## Missing Constraints (Top 20) + +- wms_receiving.creator_id->wms_account_store_employee.id (app/model/account_store_employee.js, hasMany, as=Receiving) +- wms_api_app.warehouse_id->wms_store.id (app/model/api_app.js, belongsTo, as=warehouse) +- wms_fast_where.pid->wms_fast_where.id (app/model/fast_where.js, belongsTo, as=parent) +- wms_fast_where.pid->wms_fast_where.id (app/model/fast_where.js, hasMany, as=children) +- wms_location_space.zone_id->wms_location_zone.id (app/model/location_space.js, belongsTo, as=zone) +- wms_receiving_detail.space_id->wms_location_space.id (app/model/location_space.js, hasMany, as=receiving) +- wms_location_space.zone_id->wms_location_zone.id (app/model/location_zone.js, hasMany, as=spaces) +- wms_location_zone.warehouse_id->wms_location_zone.warehouse_id (app/model/location_zone.js, belongsTo, as=pickStartPoint) +- wms_permission.parent_id->wms_permission.id (app/model/permission.js, hasMany, as=children) +- wms_permission.parent_id->wms_permission.id (app/model/permission.js, belongsTo, as=parent) +- wms_receiving.warehouse_id->wms_store.id (app/model/receiving.js, belongsTo, as=warehouse) +- wms_receiving.creator_id->wms_account_store_employee.id (app/model/receiving.js, belongsTo, as=creator) +- wms_storage.receiving_id->wms_receiving.id (app/model/receiving.js, hasMany, as=storage_records) +- wms_receiving.store_id->wms_store_warehouse.store_id (app/model/receiving.js, belongsTo, as=store) +- wms_receiving_detail.system_product_id->wms_stock_warehouse.id (app/model/receiving_detail.js, belongsTo, as=system_product) +- wms_storage.receiving_detail_id->wms_receiving_detail.id (app/model/receiving_detail.js, hasMany, as=storage_details) +- wms_receiving_detail.space_id->wms_location_space.id (app/model/receiving_detail.js, belongsTo, as=receiving_space) +- wms_role.store_id->wms_store.id (app/model/role.js, belongsTo, as=store) +- wms_role_permission.permission_id->wms_permission.id (app/model/role_permission.js, belongsTo, as=permission) +- wms_stock_warehouse.store_id->wms_store_warehouse.store_id (app/model/stock_warehouse.js, belongsTo, as=store_stock) + +## Unresolved Associations (Top 20) + +- app/model/order_delivery_factory.js: DynamicModel -> ItemsModel (type=hasMany, fk=order_id) +- app/model/order_delivery_factory.js: ItemsModel -> DynamicModel (type=belongsTo, fk=order_id) +- app/model/order_delivery_factory.js: DynamicModel -> this.app.model.Store (type=belongsTo, fk=store_id) +- app/model/order_delivery_factory.js: DynamicModel -> this.app.model.Store (type=belongsTo, fk=warehouse_id) +- app/model/print_item.js: PrintItem -> app.model.OtherModel (type=belongsTo, fk=xxx) + +## DB-only Foreign Keys (Top 20) + +- wms_account_login_log.user_id->wms_account.id +- wms_embargo_policies.warehouse_id->wms_store.id +- wms_express_setting.express_code->wms_express.code +- wms_express_setting.warehouse_id->wms_store.id +- wms_order_delivery.store_id->wms_store.id +- wms_order_delivery.warehouse_id->wms_store.id +- wms_order_express.order_id->wms_order_delivery.id +- wms_order_express_print_data.express_id->wms_order_express.id +- wms_order_items.order_id->wms_order_delivery.id +- wms_stock_warehouse.warehouse_id->wms_store.id +- wms_store_join.account_id->wms_account.id +- wms_store_join.store_id->wms_store.id +- wms_system_log.store_id->wms_store.id + +## Notes + +- belongsToMany 通过中间表映射,未纳入本次“直接外键”匹配。 +- 动态分表工厂中的关联(order_delivery_factory/order_items_factory)不做静态表级强校验。 diff --git a/association_validation_checklist.md b/association_validation_checklist.md new file mode 100644 index 0000000..729963f --- /dev/null +++ b/association_validation_checklist.md @@ -0,0 +1,165 @@ +# Association Validation Checklist + +更新时间: 2026-03-23 +范围: app/model/*.js + 核心系统 service 调用链 + +## 1. 核心检查项 + +- [x] AccountStoreRole 幽灵引用已移除(服务主链路)。 +- [x] AccountStoreEmployee <-> EmployeeRole <-> Role 关系可用。 +- [x] hasMany alias 复数化(employeeRoles/accountStoreEmployees)。 +- [x] 重复兼容 alias 已清理(主链路)。 +- [x] 对外接口输出一致(baseline/compare mismatch=0)。 +- [x] 关键登录与用户信息链路测试通过。 + +## 2. 关键模型校验结果 + +| 模型 | 关键关联 | 结果 | 备注 | +| --- | --- | --- | --- | +| Account | hasMany AccountStoreEmployee as accountStoreEmployees | PASS | 已移除 accountStoreRoles | +| AccountStoreEmployee | hasMany EmployeeRole as employeeRoles | PASS | 已移除 employeeRole | +| Role | hasMany EmployeeRole as employeeRoles | PASS | 已移除 employeeRole | +| Store | hasMany AccountStoreEmployee as accountStoreEmployees | PASS | 已移除 accountStoreEmployee | +| AccountPlatformActive | belongsTo AccountStoreEmployee as accountStoreEmployee | PASS | belongsTo 单数语义保留 | + +## 3. 服务调用链校验结果 + +| 服务 | 校验项 | 结果 | +| --- | --- | --- | +| systems/account_platform | include/读取 employeeRoles 一致 | PASS | +| systems/auth/user | include alias 使用 employeeRoles | PASS | +| systems/store | 角色绑定链路使用 EmployeeRole | PASS | +| systems/storage/receiving | StoreWarehouse 关联补 warehouse_id/use_status 过滤,避免跨仓错关联 | PASS | + +## 4. 验证记录 + +- method-output compare: mismatch=0 +- generated test: 8 passing +- smoke test (login/info/home): 6 passing + +## 5. 4.1 全量审计结果(2026-03-23) + +- 审计报告: association_fk_consistency_report.md +- DB 外键: 51 +- 模型关联: 89 +- 可直接匹配: 53 +- 模型定义但 DB 无外键约束: 28 +- DB 有外键但模型未声明: 13 +- 动态模型/示例占位导致无法静态解析: 5 + +高优先级差异(建议先处理): + +- receiving / receiving_detail / storage 三表关联的 FK 约束缺失项(第一批已处理:删除无效 hasMany(Storage) 关联,并修正 service include 过滤) +- store_warehouse 与 stock_warehouse/receiving 的 store_id 外键语义差异(已完成服务层与模型层双收敛) +- role / role_permission / permission 的部分 FK 未在 DB 层约束(核心约束已补齐,remaining: permission.parent_id 自关联约束策略评估) + +### 5.1 高优先差异处理进展(receiving 第一批) + +- 处理内容: + - 移除 `Receiving.hasMany(Storage, foreignKey: 'receiving_id')` 无效关联(storage 表不存在 receiving_id)。 + - 移除 `ReceivingDetail.hasMany(Storage, foreignKey: 'receiving_detail_id')` 无效关联(storage 表不存在 receiving_detail_id)。 + - `systems/storage/receiving` 多处 `StoreWarehouse` include/query 增加 `warehouse_id + use_status` 过滤,规避跨仓库错关联。 + - `create` 流程中 `store_name` 改为来源 `store_remask`,与仓库门店展示语义对齐。 +- 验证结果: + - method-output compare: mismatch=0 + - generated regression + smoke: 14 passing + +### 5.2 高优先差异处理进展(store_warehouse/stock_warehouse 第二批) + +- 处理内容: + - `systems/stock_store` 的 `store_stock` include 全量补齐 `warehouse_id + use_status` 条件,避免仅按 `store_id` 关联导致跨仓误匹配。 + - 覆盖 count/findAll/search 三处核心查询路径,保持原有返回结构不变。 +- 验证结果: + - method-output compare: mismatch=0 + - generated regression + smoke: 14 passing + +### 5.3 高优先差异处理进展(role/permission 第三批) + +- 处理内容: + - `systems/auth/user` 的权限与菜单查询链路补齐 `Role.status=1` 约束,仅启用角色参与授权。 + - 权限查询补齐 `Permission.status=1` 约束,禁用权限不再进入 `user.permissions` 与菜单树。 + - 对 role_id/permission_id 增加去重处理,避免重复关联导致的冗余查询和重复路径。 +- 验证结果: + - method-output compare: mismatch=0 + - generated regression + smoke: 14 passing + +### 5.4 DB 约束补齐进展(role_permission 第四批) + +- 处理内容: + - 新增迁移 `database/migrations/20260323103000-align-role-permission-fk.js`: + - 将 `wms_role_permission.permission_id` 对齐为 `int(11)`(与 `wms_permission.id` 一致)。 + - 在无孤儿数据时添加 `fk_wms_role_permission_permission` 外键(ON DELETE CASCADE, ON UPDATE RESTRICT)。 + - 同步模型字段类型: `app/model/role_permission.js` 的 `permission_id` 改为 `INTEGER`。 +- 执行结果: + - 已完成数据清洗:`wms_role_permission.permission_id` 孤儿记录 4 条已备份并删除;`wms_role.store_id=0` 的 3 条记录已备份并修正为 `NULL`。 + - 已执行迁移核心动作:`permission_id` 类型已对齐为 `int(11)`,且外键 `fk_wms_role_permission_permission` 已生效。 + - SequelizeMeta 已登记 `20260323103000-align-role-permission-fk.js`。 + - 门禁结果:method-output compare mismatch=0,generated regression + smoke: 14 passing。 + +### 5.5 DB 约束补齐进展(role.store_id 第五批) + +- 处理内容: + - 新增迁移 `database/migrations/20260323113000-add-role-store-fk.js`: + - 将 `wms_role.store_id` 对齐为 `bigint(20) unsigned NULL`。 + - 补充索引 `idx_store_id`。 + - 添加外键 `fk_wms_role_store`(ON UPDATE RESTRICT, ON DELETE SET NULL)。 +- 执行结果: + - `wms_role.store_id` 外键已生效,孤儿计数=0。 + - SequelizeMeta 已登记 `20260323113000-add-role-store-fk.js`。 + - 门禁结果:method-output compare mismatch=0,generated regression + smoke: 14 passing。 + +### 5.6 模型层复合键语义治理进展(store_warehouse/stock_warehouse 第六批) + +- 处理内容: + - `StoreWarehouse` 模型新增统一构造器:`buildScopedWhere` / `buildStoreStockInclude`,收敛 `store_stock` include 的复合键语义。 + - `StockWarehouse.belongsTo(StoreWarehouse as store_stock)` 与 `StoreWarehouse.hasMany(StockWarehouse as store_stock)` 显式标记 `constraints: false`,避免误导为单列外键。 + - `Receiving.belongsTo(StoreWarehouse as store)` 显式标记 `constraints: false`,与 `store_id + warehouse_id` 业务语义对齐。 + - `systems/stock_store` 与 `systems/storage/receiving` 已改为复用模型构造器,减少散落条件。 +- 验证结果: + - method-output compare: mismatch=0 + - generated regression + smoke: 14 passing + +### 5.7 DB 约束补齐进展(permission.parent_id 第七批) + +- 处理内容: + - 新增迁移 `database/migrations/20260323123000-add-permission-parent-fk.js`: + - 将 `wms_permission.parent_id` 根节点语义从 `0` 规范为 `NULL`。 + - 添加自关联外键 `fk_wms_permission_parent`(ON UPDATE RESTRICT, ON DELETE SET NULL)。 + - 模型与服务语义对齐: + - `Permission.parent_id` 改为 `allowNull: true` / `defaultValue: null`,并在 setter 中兼容输入 `0 -> NULL`。 + - 权限树构建根节点判断由 `parent_id===0` 收敛为 `!parent_id`(兼容历史与新语义)。 +- 执行结果: + - 数据复核: `root_zero_after=0`、`root_null_after=42`、`orphan_after=0`。 + - 外键生效: `fk_wms_permission_parent` 已存在。 + - SequelizeMeta 已登记 `20260323123000-add-permission-parent-fk.js`。 + - 触发器策略: 目标库因权限限制(binlog + SUPER)未创建触发器,改由应用层归一化 `0 -> NULL`。 +- 验证结果: + - method-output compare: mismatch=0 + - generated regression + smoke: 14 passing + +## 6. 后续检查 + +- [x] 全量扫描其余模型类方法中的 include 别名一致性(service as 与 model as 差集扫描结果: 0)。 +- [x] 补充 N+1 风险清单与 eager-loading 建议(见 association_eager_loading_n_plus_one_guideline.md)。 + +### 6.1 include alias 一致性收尾扫描(2026-03-23) + +- 扫描范围: + - `app/model/**/*.js` 中 association `as` 定义 + - `app/service/**/*.js` 中 include `as` 使用 +- 扫描方式: + - 先做全量检索(model association / service include) + - 再做集合差集(service alias - model alias)自动比对 +- 扫描结论: + - model alias 总数: 48 + - 差集可疑项: 0 + - 结论: 未发现 include alias 不一致问题,可关闭阶段 4 收尾检查第 1 项。 + +## 7. 4.4 规约落地记录(2026-03-23) + +- 规约文档: association_eager_loading_n_plus_one_guideline.md +- 已固化要求: + - 禁止循环内逐条查询关联表(N+1)。 + - include 必须声明 attributes。 + - 仓库链路 include 必须补齐 warehouse_id + use_status 约束。 + - 涉及关联查询改动必须执行 compare + generated test + smoke。 \ No newline at end of file diff --git a/database/migrations/20260323103000-align-role-permission-fk.js b/database/migrations/20260323103000-align-role-permission-fk.js new file mode 100644 index 0000000..892fbb8 --- /dev/null +++ b/database/migrations/20260323103000-align-role-permission-fk.js @@ -0,0 +1,115 @@ +'use strict'; + +const TABLE = 'wms_role_permission'; +const REF_TABLE = 'wms_permission'; +const FK_NAME = 'fk_wms_role_permission_permission'; + +async function getColumnInfo(queryInterface, tableName, columnName) { + const [ rows ] = await queryInterface.sequelize.query( + ` + SELECT COLUMN_TYPE, IS_NULLABLE + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = :tableName + AND COLUMN_NAME = :columnName + LIMIT 1 + `, + { + replacements: { + tableName, + columnName, + }, + } + ); + + return rows[0] || null; +} + +async function hasConstraint(queryInterface, tableName, constraintName) { + const [ rows ] = await queryInterface.sequelize.query( + ` + SELECT 1 + FROM information_schema.REFERENTIAL_CONSTRAINTS + WHERE CONSTRAINT_SCHEMA = DATABASE() + AND TABLE_NAME = :tableName + AND CONSTRAINT_NAME = :constraintName + LIMIT 1 + `, + { + replacements: { + tableName, + constraintName, + }, + } + ); + + return rows.length > 0; +} + +async function getOrphanCount(queryInterface) { + const [ rows ] = await queryInterface.sequelize.query( + ` + SELECT COUNT(*) AS cnt + FROM wms_role_permission rp + LEFT JOIN wms_permission p ON p.id = rp.permission_id + WHERE p.id IS NULL + ` + ); + + return Number(rows[0]?.cnt || 0); +} + +module.exports = { + async up(queryInterface) { + const permissionIdColumn = await getColumnInfo(queryInterface, TABLE, 'permission_id'); + if (!permissionIdColumn) { + throw new Error('Column wms_role_permission.permission_id not found.'); + } + + const columnType = String(permissionIdColumn.COLUMN_TYPE || '').toLowerCase(); + + // permission.id is int(11), keep child key type aligned before adding FK. + if (columnType !== 'int(11)') { + await queryInterface.sequelize.query( + 'ALTER TABLE `wms_role_permission` MODIFY COLUMN `permission_id` int(11) NOT NULL COMMENT \'权限ID\'' + ); + } + + const orphanCount = await getOrphanCount(queryInterface); + if (orphanCount > 0) { + throw new Error( + `Cannot add ${FK_NAME}: found ${orphanCount} orphan rows in wms_role_permission.permission_id. ` + + 'Please clean orphan rows first, then rerun migration.' + ); + } + + const exists = await hasConstraint(queryInterface, TABLE, FK_NAME); + if (!exists) { + await queryInterface.sequelize.query( + 'ALTER TABLE `wms_role_permission` ' + + 'ADD CONSTRAINT `fk_wms_role_permission_permission` ' + + 'FOREIGN KEY (`permission_id`) REFERENCES `wms_permission` (`id`) ' + + 'ON UPDATE RESTRICT ON DELETE CASCADE' + ); + } + }, + + async down(queryInterface) { + const exists = await hasConstraint(queryInterface, TABLE, FK_NAME); + if (exists) { + await queryInterface.sequelize.query( + 'ALTER TABLE `wms_role_permission` DROP FOREIGN KEY `fk_wms_role_permission_permission`' + ); + } + + const permissionIdColumn = await getColumnInfo(queryInterface, TABLE, 'permission_id'); + if (permissionIdColumn) { + const columnType = String(permissionIdColumn.COLUMN_TYPE || '').toLowerCase(); + if (columnType !== 'bigint(20) unsigned') { + await queryInterface.sequelize.query( + 'ALTER TABLE `wms_role_permission` MODIFY COLUMN `permission_id` bigint(20) unsigned NOT NULL COMMENT \'权限ID\'' + ); + } + } + }, +}; diff --git a/database/migrations/20260323113000-add-role-store-fk.js b/database/migrations/20260323113000-add-role-store-fk.js new file mode 100644 index 0000000..62f6591 --- /dev/null +++ b/database/migrations/20260323113000-add-role-store-fk.js @@ -0,0 +1,150 @@ +'use strict'; + +const TABLE = 'wms_role'; +const REF_TABLE = 'wms_store'; +const FK_NAME = 'fk_wms_role_store'; +const INDEX_NAME = 'idx_store_id'; + +async function getColumnInfo(queryInterface, tableName, columnName) { + const [ rows ] = await queryInterface.sequelize.query( + ` + SELECT COLUMN_TYPE, IS_NULLABLE + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = :tableName + AND COLUMN_NAME = :columnName + LIMIT 1 + `, + { + replacements: { + tableName, + columnName, + }, + } + ); + + return rows[0] || null; +} + +async function hasConstraint(queryInterface, tableName, constraintName) { + const [ rows ] = await queryInterface.sequelize.query( + ` + SELECT 1 + FROM information_schema.REFERENTIAL_CONSTRAINTS + WHERE CONSTRAINT_SCHEMA = DATABASE() + AND TABLE_NAME = :tableName + AND CONSTRAINT_NAME = :constraintName + LIMIT 1 + `, + { + replacements: { + tableName, + constraintName, + }, + } + ); + + return rows.length > 0; +} + +async function hasIndex(queryInterface, tableName, indexName) { + const [ rows ] = await queryInterface.sequelize.query( + ` + SELECT 1 + FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = :tableName + AND INDEX_NAME = :indexName + LIMIT 1 + `, + { + replacements: { + tableName, + indexName, + }, + } + ); + + return rows.length > 0; +} + +async function getOrphanCount(queryInterface) { + const [ rows ] = await queryInterface.sequelize.query( + ` + SELECT COUNT(*) AS cnt + FROM wms_role r + LEFT JOIN wms_store s ON s.id = r.store_id + WHERE r.store_id IS NOT NULL + AND s.id IS NULL + ` + ); + + return Number(rows[0]?.cnt || 0); +} + +module.exports = { + async up(queryInterface) { + const storeIdColumn = await getColumnInfo(queryInterface, TABLE, 'store_id'); + if (!storeIdColumn) { + throw new Error('Column wms_role.store_id not found.'); + } + + const columnType = String(storeIdColumn.COLUMN_TYPE || '').toLowerCase(); + if (columnType !== 'bigint(20) unsigned') { + await queryInterface.sequelize.query( + 'ALTER TABLE `wms_role` MODIFY COLUMN `store_id` bigint(20) unsigned NULL COMMENT \'所属仓库ID\'' + ); + } + + const orphanCount = await getOrphanCount(queryInterface); + if (orphanCount > 0) { + throw new Error( + `Cannot add ${FK_NAME}: found ${orphanCount} orphan rows in wms_role.store_id. ` + + 'Please clean orphan rows first, then rerun migration.' + ); + } + + const indexExists = await hasIndex(queryInterface, TABLE, INDEX_NAME); + if (!indexExists) { + await queryInterface.sequelize.query( + 'ALTER TABLE `wms_role` ADD INDEX `idx_store_id` (`store_id`)' + ); + } + + const fkExists = await hasConstraint(queryInterface, TABLE, FK_NAME); + if (!fkExists) { + await queryInterface.sequelize.query( + 'ALTER TABLE `wms_role` ' + + 'ADD CONSTRAINT `fk_wms_role_store` ' + + 'FOREIGN KEY (`store_id`) REFERENCES `wms_store` (`id`) ' + + 'ON UPDATE RESTRICT ON DELETE SET NULL' + ); + } + }, + + async down(queryInterface) { + const fkExists = await hasConstraint(queryInterface, TABLE, FK_NAME); + if (fkExists) { + await queryInterface.sequelize.query( + 'ALTER TABLE `wms_role` DROP FOREIGN KEY `fk_wms_role_store`' + ); + } + + const indexExists = await hasIndex(queryInterface, TABLE, INDEX_NAME); + if (indexExists) { + await queryInterface.sequelize.query( + 'ALTER TABLE `wms_role` DROP INDEX `idx_store_id`' + ); + } + + const storeIdColumn = await getColumnInfo(queryInterface, TABLE, 'store_id'); + if (storeIdColumn) { + const columnType = String(storeIdColumn.COLUMN_TYPE || '').toLowerCase(); + if (columnType !== 'bigint(20)') { + await queryInterface.sequelize.query( + 'ALTER TABLE `wms_role` MODIFY COLUMN `store_id` bigint(20) NULL COMMENT \'所属仓库ID\'' + ); + } + } + }, +}; diff --git a/database/migrations/20260323123000-add-permission-parent-fk.js b/database/migrations/20260323123000-add-permission-parent-fk.js new file mode 100644 index 0000000..eaa39f4 --- /dev/null +++ b/database/migrations/20260323123000-add-permission-parent-fk.js @@ -0,0 +1,109 @@ +'use strict'; + +const TABLE = 'wms_permission'; +const COLUMN = 'parent_id'; +const FK_NAME = 'fk_wms_permission_parent'; + +async function hasConstraint(queryInterface, tableName, constraintName) { + const [ rows ] = await queryInterface.sequelize.query( + ` + SELECT 1 + FROM information_schema.REFERENTIAL_CONSTRAINTS + WHERE CONSTRAINT_SCHEMA = DATABASE() + AND TABLE_NAME = :tableName + AND CONSTRAINT_NAME = :constraintName + LIMIT 1 + `, + { + replacements: { + tableName, + constraintName, + }, + } + ); + + return rows.length > 0; +} + +async function getOrphanCount(queryInterface) { + const [ rows ] = await queryInterface.sequelize.query( + ` + SELECT COUNT(*) AS cnt + FROM wms_permission p + LEFT JOIN wms_permission pp ON pp.id = p.parent_id + WHERE p.parent_id IS NOT NULL + AND p.parent_id <> 0 + AND pp.id IS NULL + ` + ); + + return Number(rows[0]?.cnt || 0); +} + +async function getSelfLoopCount(queryInterface) { + const [ rows ] = await queryInterface.sequelize.query( + ` + SELECT COUNT(*) AS cnt + FROM wms_permission + WHERE parent_id = id + ` + ); + + return Number(rows[0]?.cnt || 0); +} + +module.exports = { + async up(queryInterface) { + const orphanCount = await getOrphanCount(queryInterface); + if (orphanCount > 0) { + throw new Error( + `Cannot add ${FK_NAME}: found ${orphanCount} orphan rows in wms_permission.parent_id.` + ); + } + + const selfLoopCount = await getSelfLoopCount(queryInterface); + if (selfLoopCount > 0) { + throw new Error( + `Cannot add ${FK_NAME}: found ${selfLoopCount} self-loop rows (id = parent_id) in wms_permission.` + ); + } + + // Normalize root sentinel to NULL before adding FK. + await queryInterface.sequelize.query( + 'UPDATE `wms_permission` SET `parent_id` = NULL WHERE `parent_id` = 0' + ); + + await queryInterface.sequelize.query( + "ALTER TABLE `wms_permission` MODIFY COLUMN `parent_id` int(11) NULL DEFAULT NULL COMMENT '父级ID(根节点为NULL)'" + ); + + const fkExists = await hasConstraint(queryInterface, TABLE, FK_NAME); + if (!fkExists) { + await queryInterface.sequelize.query( + 'ALTER TABLE `wms_permission` ' + + 'ADD CONSTRAINT `fk_wms_permission_parent` ' + + 'FOREIGN KEY (`parent_id`) REFERENCES `wms_permission` (`id`) ' + + 'ON UPDATE RESTRICT ON DELETE SET NULL' + ); + } + + // Root node normalization from 0->NULL is handled in application model setters. + }, + + async down(queryInterface) { + const fkExists = await hasConstraint(queryInterface, TABLE, FK_NAME); + if (fkExists) { + await queryInterface.sequelize.query( + 'ALTER TABLE `wms_permission` DROP FOREIGN KEY `fk_wms_permission_parent`' + ); + } + + await queryInterface.sequelize.query( + 'UPDATE `wms_permission` SET `parent_id` = 0 WHERE `parent_id` IS NULL' + ); + + await queryInterface.sequelize.query( + "ALTER TABLE `wms_permission` MODIFY COLUMN `parent_id` int(11) NULL DEFAULT 0 COMMENT '父级ID'" + ); + }, +}; diff --git a/day.log b/day.log index 07d220149ad62f572cdcf92ad8dfa656dcb37272..f3ffdccd6f9468d80340b75d2a240d51bb87fd11 100644 GIT binary patch literal 20166 zcmeHPeQ;b?b-x>fBVl=QVKAWD<7e6uVJvAKf`jEG6A@fT*m~>TC+matet1_;yNaZ> zENRz~P2|`ZuvjUQ36d29`RHKce_Gt>(3zAOLKu=jAS7-GlNpAP5}cZ*wlYFvY8&!; ze(&h|-nWt*IZe|t!)T=4eS1I7J@Zj< zqJ7?c!J2OCvlsVW6Tn#b6{aunlzG}7iY!aYXO%S0v#Fn3ug13|tHn04OLU5UQA_XY z#I4EF^u@+wk@_Rq{eiF{QuJ+Bw9)KoQ7yXNw!6emde<(h#2unnlsV6)Hd|=_#CWCo z(7wfef4uvvVWt2xJvMTw-w<0wj(W8VOJrz_96jG?9vFPYe!dg4V7zV`zgO6zN93tp zir(RKKmGR6`!0G_^T&%Qc=AX^&Jdf3#`FwT2F;|8MVuQrlrD1~4c=o;4}2pz)X<*X zzC%%YA!5vMVi$1&t1IsRcZKcNg~-k!jN=QWX%)LfD^cYO^w3P8x1A`*oW20ok)?0( z$q;q>dP7xX=zFQ_!SE}ECkD=RK6PZMVTpNdX3^)S8<~SIo4z|ItxJXL5{jy)kK7kB zM3`1qD?TOa>9vYD(MmkG4{r+fPn^p$HD3=l4*LSt4JX3B0PmwACWqJMd;t+ZWnGN@ zL%|pLMC`G_b7K<|b^9PW%!yw&t{M+oJAy+EL+0uZv{iFsNAt1&IB+7o+=7Jp0w+?w zQG@1hr?sVNU5mrjHYmvujZ!`x$jV&5_zEFN(ZQ7uc*#L%(F3T4hzw0!i*5sbHq#@i%r6Ad)#I{K}pX9iK%L4WU$Z0Y*h$cv3? zCU698>O`D+1nFn1_$2*pzP#guo!{%?7KXr{J)1f=w)&3!B#X>L@UJ5Ge5c>UPH(cm zHvZ+*>9m@mqG>KkB3hasBn`yOJnre}p3pz;vqLXiWlsIL8T2=t9bg#&^;y~<=zkCG zl$3*I$+a`{z`_iXq(IJ27PiNAi}PE1RT^?sv;Qx4%q1_(IhHr91#+dRXDjk)nmJFu zWIaZYjGVX6j4lrM_k5|NDe~=(p$3C?^-kK=9%@lXl(rG2h7d=wf(@B$s@!}i482jK z>YBwCVk-K9;Bs0y`W$R2O`o(^-_g`0jy`3bx6${Db}FO#&nK;h7{70I2c-JEeKB;h zmu<@)SEgYBZIVIA;`d3~nwsi^+5O-cq-W7kpACE8?ecghNiNCgM0UTLlWkp=)&~1x zkhb9OBlhi?^Y-RZSkoqVXIiPn9+G;VrE{c?d<5*o%Y&n7Iok%B>jv|@ZIG0uTx)KK zk5Z2m@z5p;V0pvz3w>;NpJAqV$3M3BSOj{*RAHA(Y1hHChYIfr>$~ntogEm89NKpEl4F7M>4@%M~kx4bs`pE8U4@-ghfbX$4LcI&p#magYX=iq;qrfF}toom*u=W_!k zBonQ)4%iV`23RfV(RAAn1{ZzqQ2w-iJP93A*6@!bYwl6J#{5^(N>~@rsq6bJ2uf|u6J{Z1hq}*Zqs7p2c!EBoXp9L?B{e_3}lf-#_ zuOVQa%N)=Ju&#YX1PEKXv`djFZx->g-E&cqa^I~9+KW(vS+(! z4)%p{_Z9Y+J!L=5T}{7pwFKT_zwd3smK(l7AK4I3S>*i^i^EJu8Sxsc>Y~{(H?$2_ zV%cc_#Dz$Dx7uS^Ug!X@R&5vb+iyNM@U`^AW_wS$%kxswF@vb-BCV{{R#Qo0d2tompI_GzwL1VR8_mpNzX`r?Zh~$1w`K3t+bT{&QuJ@^!`mLvIjrv$dnMjEB`tBU4L0&G#GMe{)>t~IVH0&fP>2qm=9l|c^RIujr-S^!t}bGKGz9TY@X3#LIfn&utd9O zBrr=e!NPc>6v7~coX!^N$R9#Z``mb^mD(C@@7VE!!4HO?vTFJZLB-?gwv*(4=d#i| z*2k#R1%Df%&6(A_{*~h?j3QT@2|aUUwiWl%0B`X^{*mr-rz81HYQDJ35KGKV=nP@~ zVxNE*GatJzWE0|Nir<)Xh5)8}XLh?)V>LA?Yry>1BRoS$U#GO&OM#cy^%{Q>9V$N~ zwG7zct3gD|@C5p9fD^hj=zZaz5Ou0O(!YgFLTB1ZXXb7p``1xB_F!|j!yJ&|-g(B! zk?ogKZq2mKEvWUUXkOjRHq6K@=)mt+NIHR|V8Q+7_XmF!k>5a?kP(=TRrinG)$kh= zT3L)Qmza-4-rM$z5j%8tVC&&$Q#Ji1&Mo2=vT{JQ8|;c)F~)?KfkolS1rcJI159~c zV!G|F79}IdfgmbHWQ*Ai@_ya4lLlGJ9KB}?k*C+E%^FjTUJU(nk1tW;Y@#@T^Ch>@ zTCig^)MlMa5u)KGrZDY}?bd(xAV$LI>stP1_yOys#(eC>#&8@q?xYRd!L)!oU7=!p zhE*Wj;-~z|@g%YeY}e5me4L6d-r>p_wL@+MF%0lIP(u&V*G+pWaTZqks{x{l^t{H@ zB~x!*O>3DuKE|AkE4=L`YPniG@J8dMiKkgwrB^>IJz7>tYs|Vx53x3M2>y@bj5iuz zmwouUcA87q;7S^e5iCcc`nb&dvIe_@ZRkAWi3OMZdTIO5;!-vIcKZ=1_jnMBIg( z9by_KuZu{>XU7waZxMF_LoTP71UrFWa1AyYQjb>fGsRYtZ8jpy6z#kr9!{+fXDELq zb2ErYWPfCtm>QN#?z`FbwD6joLxe=j(J*6~Q<1yJgeII$FWDoEmBp=fKjm!?zA@s^+aOMUz7t*#p4M;PeCUO| zPR*74@0GlqA>ijRw)Ddbqg3As*cwDQ@3cNj@$ouBmWEhE2>u5Hz5wv$jqc}SkGV5_ zF0c0CTySX%ESbvBDy~49^$Z4fD0YK)cSZNBYf@Hothz#rM%+N95 zC1k3-qv>l=c@oTm*kmdSO@gOD_5@kvKBBVQeTO(o;@~+L-LH4@D#fJWF)T7 zw<@2URM zkLy#n@2KhDY&|@HJk+NtYZ)XQY>3^*PK1$5RrBN~l1H!4K9|;Q_6Q~0 zurZQ<#TM|Hjy1#;UFQfzTbp}8GqNP7tUbd(P(k7wGQZe^-xogFsml=BWrt{Tbq3!c+O!+H|1Fm)c}5pFtvQOECg6ng;dirQNaVrr| zh(xLdp5vX)N94U$w0`I=v@G6}r46t3BRZQ~qYd#B3%26Pk>6-liEBpdDT31X7B)p` zz)9C<>T6UxiJUGXa^%y{3)K_oMj#9=`EDV*zs9qJ-uB2&a?HWe5_;B9)bgWb>F95h zWe#>iwcu|dAAdWOi)J1cTQ~R$NSQtt=lf4tzR`MDF3KF_a?aZu$CDk9(|ip0UFR~! z;2fuS98d-?QksGcOb>iB#&X&mIk8R22>b-T&rQ^aC-=f;o-I7z`N6Ttg3d>@Lgut7 z^5K2go5|GH!^l_vAu@g7P(Il8!@*4B@#F``N*rYMk^cuT5K}{M3^x)$<{vg578kmJ ze4UhcDQS?+=qyyE$Mc}Hlw?V_*oL?%^X@of3$HaTZmD}fc)OoY+>~KtP&@~ZrgH!` z=Sm(0T8)SXwK2|s0eyRAReBSB_kc4{W1KJ6*KtriaZctd*kZ5I?6yAYy(1T?5^}!C z5~7cyPH{s?1FsuWqpux)z!0CHJyR&;=!rd!#l$5n2?|oTn@LpC|4e@xqqZ$3n zXY#3W*GKfzjQWawfjm7yJ*|g00WXCbH!_x4%9nXt%ICg-%*=6~1IS3{59)}mgp3S2 z^B~OEn*D8v>KUH_g&{URc<_;K#7m3;i@#lBPDS?zD{|ll;-GC2tR!L82NiFCsSqup zYNc~VR;K+8T>n+|v?{TKesmOw&l1^PjUK{>N<62p9P5~WcYOg^+hgflOmURYcOatq z_kptmz_qBQ@mR2CwNz#D#&|%z;5+Ioh5&j&)eN36Oixg=g?D=I{^kg*jn|&Bt@4h5 z$V!fqk0B;S21Adib*{qNpjyD_Thaj(hFmpEGqQ`E-AxcJIm%~1!uv>$@Cwb9+43rq zF35;25+rX4LMQER^%)eV=%=0fsFC&7hWKl9jroAJDu>FM&U?<{Ud_zN;~-v7&|Gt$ zQeh-oY(3$JAjND46U6o7DLYi=p6h|sVnlt#L6UxnA1Yi;lb_a7->kr28OeNv`tt71 zwYIC_6Jo)~%~H48RpzWoe=qZ)yRgH^7a?l{n}b?4><{8nyvp-AK!g>!*S|73tWz;N zx4~7F*>Z&phA#l=I@wEky8vpK$irrLL->pc!eZ%(koC7<3#wRKKhYQ5es2; z)id@R-)An5lW}*B{hAz0ehV~(QDE7?E1nJS5*~YvT;1t{L_i{aed8<+7pCgYKgiA;ulw;Fgg$dP}gz`NQ0~M zK>Mhg^B5}YqBv>@@KK${(dFUAk@8VKqrU5w|Z68j3Xq*FKqePwzO0HDs4v13^kaAXGl;) zxrKH_@6A%Ou-?GJ-rg(+3+ugZrZ2e8IZdvv;am`(7osZn9On$Uf>rA1I|0pHVd%RC zZzOeirSa05k=_la0V4wV4Z&~#3-zB5%A51fZ};`12q4_A$0UvDA$ zFBNXuCf{=GdObFK70wr;La^SxWryFy$(DJNDv`*w$$Err$Myv>h_j2FJLz`iA961>MU4h(^gWQ{s21=p$d#eO!U)wDI2}D` zo#`A3`OVl-P=J$MY%zX9nZWz0-t5)zKGF-@|G^YiAs&WZg^Gj4X1A)*U;P? zp@tmwhIIpG$J(kX=c#_6W6akCwPX(`PYa zs z(HKGDgx6fSR$oCSwM9Ov+x?3Qi#@}$Ug8VeNf~1@LI9@c(1c}vL8 z?3LmCV{YQ_ZSf^Ut#UA z@@B`LZ@(8l^89?&y+3DB))QZ#gRG(8@xrtZ77x4!RWeV;@==ps?>QNve}Ay8IfA?o zYM#KUY9D}&QIUt2fJ}I6SnW>5ANW`**`n(&_5? zEH!6JRj+FC9CPemULmkT|Mzo=HduR(@tSu_4^Hy_lAJoEOk~IeshIU zOVZFyV*xv%`dH#@?%YVZ_LYWr-SeY0MTtIEpy~C-66XWK+e36WB#80K9OP}}$#LK} zRBQYu+U%Ve(fIJr?BYJu&WkIuQ_)NPt>f@uPmV0v%PmmJk~pH+%FR9_$I^t%g5;vU zN*-U(%?64iN46fuE_vl06qPy1aR8;%n0xo0HXn6QyhCD;m*nvnyWwQJ7rPO~Fws;T)_tyD}B!GXZG1!caY-$19CjpA494A)gX^fK8xS8SF3B^bG8O=$Pt54ku6 zy<2j)7zJFLInxOa-k2#+EX)>ALLeohls0Z0+q4j^A-4Q6{e zMH}SkhL)))Xt&d&S=h!~$tJ7XvOKZ$R`b}qpUh|Y)qD(b?p%CC^aT3;x4i7z!Eg3` zs2D8V_hGldA7q4~eX!2{hC_LroPoCL8RB)c+Z5?iJr`%9-(|iw0$TuXvc*6}6Q*zy%Gr2O(WL~qq_+`+S zk~@!T+EThlT0#~Ad_k6oZ59ybPS-9XLkO$5)8!6Y>v7#wRGnPYPpBY=b1YKlIg^!e zv7*E|yi+R5(Y=+-*dU_|e1|<^E8RyKM)^eYqSvL2^Ui7=*h^5M?Dqe3{+%Q@sHyZ( z4imTw_h>PToLPO3>IR?oMLvLIR_3i*5ARkrt&L@mKch8Pdk6g@Um15l0r4|(R%_zj zl-zH)`$YJm$U_C(C4!~Fjl{5Mq%7TS^e#>m;~Y?&KHX05anhZiZl^Qwb(D_gXX4)nv8GWK!voF1?Jr{`xVkL+eKX8RY`8WpF$UA9|N1O(hmIs@%P?c!$I zA!RjdEu8DdZEu_)-I$>JZ_dWV4+m8X>>0k_Xg)e{E`M$2yCchzd9; z-87C(u5`1&Tb-WYZp?0{>fp+{0GskXH{AY%-l&=u)&SoI&P+x5j1y;u!laL~o+`7~ z-uZBb>tg64oy4ma7YJiu9A5x_^xbjr5qJX6I8%e0l0X}L`|Ltw+XKpD?{uvTM|Fso zq~GS}yb`{R!cUO-)N{6UPK<6cZoT`jh8Ksw<7%rnf_?aWvdqVQDAMe$@9Y-@j^@whiePx?~5wZRfXEv%vJSMX`eDidd>%%y!sOy_N zwOa1rHa+-Pk)sHKC@gby%*kBGy*T8a0z%O*B^8+BMCuoGgJ~*?TMG(f(CsGD1(syP zwb<-w3;~INl;d8z*IVM=0$0W%>uNU8+a7KSqV84hV6TA*p4MvL(rdAuhu=U1TGO

@)rs1!p~eVnJS*Cyc|Qr5B7OFor#PP z*VGcE)pKD{FGXCztaZ=y;XakD0n4!&$AM$W9W*zbj`~eVJ8(BJ@n`NXX+R7nV>?J7 zpBpH5^^|iPI-1ha6;33;a_G+#=ADhp^e3vX{#5n`C+qg%ToTZ+vI%StUBqpGdddr86-+TOj1_5EtXD zfEokdXe!Dc7VS;fHzGT%+esDG^Jz{#`Qo)g(n`~RJfI9Ra?n?{QHFp`!++f=bhPAH zAEiVvVnU3|XdY)_dS)Up?>sNrx4U;!`X}CaMy2y>)BVXc=?(5}LReM535$g|yUcmq z{LD6>62!$jJD*E~7pmu#?8Ms@dHh+YPn zXj$9`eYs}WrT*gEQOHd~a@|~b@TJDv(%Z(X1eL-&HU+pIqGm1aDBy6&VIqSzx_J?1DC+ zXQcrR*L4YqSAHusT58#wt7d=-j&%8dqZksZ>rhzRTX(5)xg+Vi+FAkdE$6TQZ~VQ^(}mGKw~xOj@ZTEmZyf*t delta 8 PcmX>$m+^qh1_vbo5(@)+ diff --git a/methods/system.json b/methods/system.json index 6436e3b..9552066 100644 --- a/methods/system.json +++ b/methods/system.json @@ -556,6 +556,38 @@ "response": [], "errors": [] }, + { + "method": "order.getreviewOrderlist", + "description": "分页查询订单审核列表", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "pagination 参数" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "where 参数,支持 inspection_status/operator_name/operate_time_start/operate_time_end" + } + ], + "response": [], + "errors": [] + }, { "method": "order.updateStatus", "description": "更新订单状态", @@ -696,6 +728,286 @@ ], "response": [], "errors": [] + }, + { + "method": "order.reviewOrder", + "description": "订单审核", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "delivery_order_code", + "type": "string", + "required": false, + "source": "body", + "description": "delivery_order_code 参数" + }, + { + "name": "id", + "type": "number", + "required": false, + "source": "body", + "description": "id 参数" + }, + { + "name": "inspection_status", + "type": "string", + "required": false, + "source": "body", + "description": "inspection_status 参数(兼容入参)" + }, + { + "name": "review_status", + "type": "string", + "required": false, + "source": "body", + "description": "review_status 参数,默认 fin" + }, + { + "name": "operator_name", + "type": "string", + "required": false, + "source": "body", + "description": "operator_name 参数" + }, + { + "name": "operate_time", + "type": "string", + "required": false, + "source": "body", + "description": "operate_time 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "order.reviewOrder.getreviewOrderlist", + "description": "分页查询订单审核列表(目录化路由)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "pagination 参数" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "where 参数,支持 inspection_status/operator_name/operate_time_start/operate_time_end" + } + ], + "response": [], + "errors": [] + }, + { + "method": "order.reviewOrder.reviewOrder", + "description": "订单审核(目录化路由)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "delivery_order_code", + "type": "string", + "required": false, + "source": "body", + "description": "delivery_order_code 参数" + }, + { + "name": "id", + "type": "number", + "required": false, + "source": "body", + "description": "id 参数" + }, + { + "name": "inspection_status", + "type": "string", + "required": false, + "source": "body", + "description": "inspection_status 参数(兼容入参)" + }, + { + "name": "review_status", + "type": "string", + "required": false, + "source": "body", + "description": "review_status 参数,默认 fin" + }, + { + "name": "operator_name", + "type": "string", + "required": false, + "source": "body", + "description": "operator_name 参数" + }, + { + "name": "operate_time", + "type": "string", + "required": false, + "source": "body", + "description": "operate_time 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "order.deliveryOrder.getdeliveryOrderlist", + "description": "分页查询已进入出库流程的订单列表", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "pagination 参数" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "where 参数,默认 outbound_status != none" + } + ], + "response": [], + "errors": [] + }, + { + "method": "order.pendingOrder.getpendingOrderlist", + "description": "分页查询待处理订单列表", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "pagination 参数" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "where 参数,默认 status in [pedding, created] 且 outbound_status = none" + } + ], + "response": [], + "errors": [] + }, + { + "method": "order.expectionOrder.getexpectionOrderlist", + "description": "分页查询异常订单列表", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "pagination 参数" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "where 参数,默认筛选各流程 error 或拦截 exception" + } + ], + "response": [], + "errors": [] + }, + { + "method": "order.archiveOrder.getarchiveOrderlist", + "description": "分页查询归档订单列表(暂使用当前订单表完成态数据)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "pagination 参数" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "where 参数,默认 outbound_status = fin" + } + ], + "response": [], + "errors": [] } ] }, @@ -1985,7 +2297,15 @@ "description": "Bearer token" } ], - "params": [], + "params": [ + { + "name": "code", + "type": "string", + "required": true, + "source": "body", + "description": "申请码(join_token)" + } + ], "response": [], "errors": [] }, @@ -2002,7 +2322,43 @@ "description": "Bearer token" } ], - "params": [], + "params": [ + { + "name": "audit_status", + "type": "string", + "required": true, + "source": "body", + "description": "审核状态(approved/rejected)" + }, + { + "name": "code", + "type": "string", + "required": true, + "source": "body", + "description": "申请码(join_token)" + }, + { + "name": "store_id", + "type": "number", + "required": true, + "source": "body", + "description": "当前审批门店ID" + }, + { + "name": "role_ids", + "type": "array", + "required": true, + "source": "body", + "description": "分配角色ID数组" + }, + { + "name": "reject_reason", + "type": "string", + "required": false, + "source": "body", + "description": "拒绝原因(audit_status=rejected 时可传)" + } + ], "response": [], "errors": [] } @@ -2014,7 +2370,7 @@ "list": [ { "method": "user.login", - "description": "用户登录", + "description": "用户登录(仅返回 token)", "isNeedAuth": false, "isNeedLogin": false, "headers": [], @@ -2037,6 +2393,24 @@ "response": [], "errors": [] }, + { + "method": "user.loginByCode", + "description": "登录码登录(使用 ye4s_user.tmp_code)", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "code", + "type": "string", + "required": true, + "source": "body", + "description": "登录码,对应 ye4s_user.tmp_code" + } + ], + "response": [], + "errors": [] + }, { "method": "user.logout", "description": "用户登出", diff --git a/migration_execution_plan.md b/migration_execution_plan.md new file mode 100644 index 0000000..e486767 --- /dev/null +++ b/migration_execution_plan.md @@ -0,0 +1,76 @@ +# migration_execution_plan + +更新时间: 2026-03-22 + +## 1. 执行原则 + +- 先解决 SequelizeMeta 漂移,再补新增 migration。 +- 先补静态基表,再补关联表,再补日志/配置/打印等扩展表。 +- 动态分表与视图单独治理,不混入普通 createTable 批次。 +- 所有 migration 需保证幂等,避免现有环境重复执行报错。 + +## 2. 推荐顺序 + +### 步骤 1: 漂移核对 + +- 核对以下 4 个未进入 SequelizeMeta 的 migration 与当前数据库实际结构是否一致: + - 20251111083733-create-wms-stock-store.js + - 20251112085825-create-wms-entry-order.js + - 20251112085844-create-wms-entry-items.js + - 20260322061000-add-delivery-time-to-order-delivery-tables.js +- 若结构已存在且一致,优先制定“补登记基线方案”而不是直接重跑。 + +### 步骤 2: 补齐有 model 的静态表 migration + +优先级建议: +1. 权限与组织类 +2. 库位与库存类 +3. 打印类 +4. 日志与国际化类 + +### 步骤 3: 补齐无 model 但业务依赖的表 migration + +优先补以下类型: +- system_log / api_log +- print_log / print_batch / printer_config +- platform_print_config +- wave_batch / wave_operation_log +- order_operation_log + +### 步骤 4: 动态分表治理 + +- 为 order_delivery/order_items 动态分表建立统一 migration 策略。 +- 后续迁移以“母表 + 动态建表 SQL 模板/工厂策略同步”为主,不逐仓库表固化。 + +### 步骤 5: 视图治理 + +- 为以下视图补充 create/drop migration: + - v_pick_space + - vw_warehouse_quota + +## 3. 建议批次 + +- 批次 A: 漂移核对与基线修正 +- 批次 B: 静态核心表 migration 补齐 +- 批次 C: 日志/配置/打印扩展表 migration 补齐 +- 批次 D: 动态分表与视图治理 + +## 4. local/test 演练方案 + +### local + +- 先在本地库回放已有 migration。 +- 再逐批执行新增 migration。 +- 每批完成后执行 schema 对比与关键 API 冒烟。 + +### test + +- 按 local 已验证通过的批次顺序执行。 +- 保留每批执行前后的表结构快照。 +- 若发现 drift 或兼容问题,先暂停后续批次。 + +## 5. 阶段 2 目标 + +- 明确每类表的 migration 补齐范围。 +- 明确执行顺序和批次边界。 +- 为后续正式补 migration 提供可直接执行的方案基础。 diff --git a/migration_gap_list.md b/migration_gap_list.md new file mode 100644 index 0000000..76d6314 --- /dev/null +++ b/migration_gap_list.md @@ -0,0 +1,107 @@ +# migration_gap_list + +更新时间: 2026-03-22 + +## 1. 现状摘要 + +- migration 文件数: 11 +- SequelizeMeta 已执行数: 7 +- 仓库文件与执行记录差值: 4 +- createTable 覆盖表数: 10 +- DB 物理表数: 68 +- 视图数: 2 + +## 2. 命名与顺序审计 + +- 现有 migration 文件命名整体符合“时间戳-动作-对象.js”规范。 +- 当前 migration 主要集中在 2025-11 和 2026-03 两个时间段。 +- 当前主要问题不是命名,而是覆盖率不足和执行状态漂移。 + +## 3. 执行状态漂移 + +以下 migration 文件存在于仓库,但未记录在 SequelizeMeta: + +- 20251111083733-create-wms-stock-store.js +- 20251112085825-create-wms-entry-order.js +- 20251112085844-create-wms-entry-items.js +- 20260322061000-add-delivery-time-to-order-delivery-tables.js + +说明: +- 当前数据库中相关表或字段已存在,说明存在“结构已生效但 migration 未登记”或“迁移在其他环境/手工执行过”的漂移风险。 +- 后续处理时不能直接盲跑这些 migration,必须先做结构一致性核对。 + +## 4. 有 model 但缺 create migration 的表 + +- wms_account_platform_active (app/model/account_platform_active.js) +- wms_account_store_employee (app/model/account_store_employee.js) +- wms_employee_role (app/model/employee_role.js) +- wms_fast_where (app/model/fast_where.js) +- wms_file (app/model/file.js) +- wms_file_reference (app/model/file_reference.js) +- wms_i18n_keys (app/model/i18n_key.js) +- wms_i18n_translations (app/model/i18n_translation.js) +- wms_location_space (app/model/location_space.js) +- wms_location_type (app/model/location_type.js) +- wms_location_zone (app/model/location_zone.js) +- wms_operation_log (app/model/operation_log.js) +- wms_order_delivery (app/model/order_delivery.js) +- wms_order_items (app/model/order_items.js) +- wms_permission (app/model/permission.js) +- wms_platform (app/model/platform.js) +- wms_platfrom_setting (app/model/platform_setting.js) +- wms_print_computer (app/model/print_computer.js) +- wms_print_items (app/model/print_item.js) +- wms_print_record (app/model/print_record.js) +- wms_print_station_express (app/model/print_station_express.js) +- wms_print_stations (app/model/print_stations.js) +- wms_print_template (app/model/print_template.js) +- wms_prohibited_type (app/model/prohibited_type.js) +- wms_qimen_log (app/model/qimen_log.js) +- wms_receiving (app/model/receiving.js) +- wms_receiving_detail (app/model/receiving_detail.js) +- wms_role (app/model/role.js) +- wms_role_permission (app/model/role_permission.js) +- wms_stock_barcodes (app/model/stock_barcode.js) +- wms_stock_unit (app/model/stock_unit.js) +- wms_stock_warehouse (app/model/stock_warehouse.js) +- wms_storage (app/model/storage.js) +- wms_store_join (app/model/store_join.js) + +## 5. 无 model 且无 create migration 的 DB 表 + +- SequelizeMeta +- wms_api_log +- wms_embargo_policies +- wms_express +- wms_express_print_record +- wms_express_setting +- wms_order_delivery_100000 +- wms_order_delivery_1000028 +- wms_order_express +- wms_order_express_print_data +- wms_order_items_100000 +- wms_order_items_1000028 +- wms_order_operation +- wms_order_operation_log +- wms_order_picking +- wms_picking_strategy +- wms_platform_print_config +- wms_print_batch +- wms_print_log +- wms_printer_config +- wms_system_config +- wms_system_log +- wms_wave_batch +- wms_wave_operation_log + +## 6. 特殊对象说明 + +- 动态分表: + - wms_order_delivery_* + - wms_order_items_* + 这类表不建议逐张固化 create migration,应通过“母表迁移 + 动态建表策略”统一治理。 +- 视图: + - vw_warehouse_quota + - v_pick_space + 需要单独使用 view migration 管理。 +- SequelizeMeta 属于迁移元数据表,不纳入业务模型补齐范围。 diff --git a/modelList.md b/modelList.md new file mode 100644 index 0000000..004aa0a --- /dev/null +++ b/modelList.md @@ -0,0 +1,105 @@ +# modelList + +更新时间: 2026-03-22 +扫描范围: app/model/*.js +模型文件数: 45 + +## 1. 目标 + +- 用于快速查看模型层级结构。 +- 用于后续 model 命名规范、关联规范、迁移补全的基线输入。 + +## 2. 模型层级结构 + +```text +app/model/ +├─ 账号与权限 +│ ├─ account.js +│ ├─ account_platform_active.js +│ ├─ account_store_employee.js +│ ├─ employee_role.js +│ ├─ permission.js +│ ├─ role.js +│ └─ role_permission.js +├─ 组织与仓库 +│ ├─ store.js +│ ├─ store_join.js +│ ├─ store_warehouse.js +│ ├─ storage.js +│ ├─ receiving.js +│ ├─ receiving_detail.js +│ ├─ entry_order.js +│ └─ entry_items.js +├─ 库位与查询 +│ ├─ location_type.js +│ ├─ location_zone.js +│ ├─ location_space.js +│ └─ fast_where.js +├─ 库存与商品 +│ ├─ stock_store.js +│ ├─ stock_warehouse.js +│ ├─ stock_unit.js +│ ├─ stock_barcode.js +│ └─ prohibited_type.js +├─ 订单与履约 +│ ├─ order_delivery.js +│ ├─ order_items.js +│ ├─ order_delivery_factory.js +│ └─ order_items_factory.js +├─ 打印能力 +│ ├─ print_template.js +│ ├─ print_item.js +│ ├─ print_record.js +│ ├─ print_stations.js +│ ├─ print_station_express.js +│ └─ print_computer.js +├─ 开放平台与接口 +│ ├─ api_app.js +│ ├─ qimen_app.js +│ ├─ qimen_log.js +│ ├─ platform.js +│ ├─ platform_setting.js +│ └─ interface_type.js +└─ 文件、日志与国际化 + ├─ file.js + ├─ file_reference.js + ├─ operation_log.js + ├─ i18n_key.js + └─ i18n_translation.js +``` + +## 3. 关键说明 + +### 3.1 动态分表模型 + +- order_delivery_factory.js + - 负责按 warehouse 维度动态创建/获取发货单模型。 +- order_items_factory.js + - 负责按 warehouse 维度动态创建/获取订单商品模型。 + +说明: +- 这两个文件不是普通静态 Sequelize 定义文件,而是动态模型工厂能力。 + +### 3.2 典型关联模型 + +- fast_where.js + - 自关联: parent/children。 +- location_zone.js + - 自关联 + 与 Store、LocationSpace 的关联。 +- i18n_translation.js + - 关联 i18n_key。 +- prohibited_type.js + - 关联 Store、StockWarehouse。 +- stock_barcode.js + - 关联 StockWarehouse。 + +### 3.3 命名现状观察 + +- define 名称存在 snake_case 与 PascalCase 混用。 +- 部分模型文件命名与 define 名称不完全一致。 +- 后续需结合 model_naming_standard 做统一收敛。 + +## 4. 后续维护规则 + +- 每次新增/删除/重命名 model 文件后,需同步更新本文件。 +- 每次新增/调整关联后,需同步更新本文件的关键说明章节。 diff --git a/model_association_inventory.md b/model_association_inventory.md new file mode 100644 index 0000000..f6c84c4 --- /dev/null +++ b/model_association_inventory.md @@ -0,0 +1,52 @@ +# model_association_inventory + +Updated: 2026-03-22 +Source: app/model/*.js + +| key | file | associations | +| --- | --- | --- | +| account_platform_active | app/model/account_platform_active.js | - | +| account_store_employee | app/model/account_store_employee.js | - | +| account | app/model/account.js | - | +| api_app | app/model/api_app.js | - | +| employee_role | app/model/employee_role.js | - | +| entry_items | app/model/entry_items.js | - | +| entry_order | app/model/entry_order.js | - | +| fast_where | app/model/fast_where.js | belongsTo->FastWhere, hasMany->FastWhere | +| file_reference | app/model/file_reference.js | - | +| file | app/model/file.js | - | +| i18n_key | app/model/i18n_key.js | - | +| i18n_translation | app/model/i18n_translation.js | belongsTo->I18nKey | +| interface_type | app/model/interface_type.js | - | +| location_space | app/model/location_space.js | - | +| location_type | app/model/location_type.js | belongsTo->Store | +| location_zone | app/model/location_zone.js | belongsTo->LocationZone, hasMany->LocationZone, belongsTo->Store, hasMany->LocationSpace | +| operation_log | app/model/operation_log.js | - | +| order_delivery_factory | app/model/order_delivery_factory.js | - | +| order_delivery | app/model/order_delivery.js | - | +| order_items_factory | app/model/order_items_factory.js | - | +| order_items | app/model/order_items.js | - | +| permission | app/model/permission.js | - | +| platform_setting | app/model/platform_setting.js | - | +| platform | app/model/platform.js | - | +| print_computer | app/model/print_computer.js | - | +| print_item | app/model/print_item.js | - | +| print_record | app/model/print_record.js | - | +| print_station_express | app/model/print_station_express.js | - | +| print_stations | app/model/print_stations.js | - | +| print_template | app/model/print_template.js | - | +| prohibited_type | app/model/prohibited_type.js | belongsTo->Store, hasMany->StockWarehouse | +| qimen_app | app/model/qimen_app.js | - | +| qimen_log | app/model/qimen_log.js | - | +| receiving_detail | app/model/receiving_detail.js | - | +| receiving | app/model/receiving.js | - | +| role_permission | app/model/role_permission.js | - | +| role | app/model/role.js | - | +| stock_barcode | app/model/stock_barcode.js | belongsTo->StockWarehouse | +| stock_store | app/model/stock_store.js | - | +| stock_unit | app/model/stock_unit.js | - | +| stock_warehouse | app/model/stock_warehouse.js | - | +| storage | app/model/storage.js | - | +| store_join | app/model/store_join.js | - | +| store_warehouse | app/model/store_warehouse.js | - | +| store | app/model/store.js | - | diff --git a/model_cleanup_list.md b/model_cleanup_list.md new file mode 100644 index 0000000..84557b6 --- /dev/null +++ b/model_cleanup_list.md @@ -0,0 +1,213 @@ +# model_cleanup_list + +更新时间: 2026-03-23 +阶段: 5.1 识别应迁移到 service 层的方法能力(第一批) + +## 1. 盘点结论 + +- 扫描范围: app/model/**/*.js +- 检出方法总数: 102(实例 + 静态) +- 高优先候选(应迁移到 service): 24 +- 低风险可移除候选(当前未发现业务调用): 18 +- 保留在模型层(轻量领域判断/展示映射): 22 + +说明: +- 本次调用扫描采用“静态方法名精确匹配”策略(Model.method(...))。 +- 对“应迁移”项,目标是把跨表编排、状态机、批量事务、库存分配等逻辑从 model 剥离到 systems service。 + +## 2. 第一批应迁移(P1) + +### 2.1 入库单聚合与状态流转 + +- 文件: app/model/entry_order.js +- 候选方法: + - findByOrderCode + - findByStatus + - getStatsByWarehouse + - updateSyncStatus + - updateOrderStatus + - calculateReceivedQuantities +- 迁移目标: + - app/service/systems/entry_order.js +- 原因: + - 含分页查询、跨表 include、状态流转约束、聚合统计,属于业务编排而非数据映射。 + +### 2.2 入库明细批量更新与进度汇总 + +- 文件: app/model/entry_items.js +- 候选方法: + - batchUpdateReceived + - getOrderProgress +- 迁移目标: + - app/service/systems/entry_order.js(或 app/service/systems/storage/receiving.js) +- 原因: + - 含事务控制、批量更新和跨记录校验,属于服务层职责。 + +### 2.3 库存分配/锁定编排 + +- 文件: app/model/storage.js +- 候选方法: + - updateQuantity + - lockQuantity + - unlockQuantity + - allocateQuantity + - getStockSummary + - getSpaceUsage + - findByStockAndBatch + - findBySpace + - findAvailableByWarehouse + - findExpiringSoon +- 迁移目标: + - app/service/systems/stock_store.js + - app/service/systems/storage/receiving.js +- 原因: + - 涉及库存扣减/锁定语义、聚合统计和业务筛选,属于库存域服务。 + +### 2.4 角色权限写入与查询编排 + +- 文件: app/model/role.js +- 候选方法: + - assignPermissions + - getPermissionTree + - getPermissionIds +- 文件: app/model/role_permission.js +- 候选方法: + - bulkAssign + - clearRolePermissions + - getRolePermissions + - hasPermission +- 迁移目标: + - app/service/systems/auth/user.js + - 新增 app/service/systems/auth/role_permission.js(推荐) +- 原因: + - 包含权限关系写操作、树构建和权限判定,应集中在鉴权服务边界。 + +### 2.5 商家数据校验与查询助手 + +- 文件: app/model/store.js +- 候选方法: + - validateStoreData + - checkCompanyNameExists + - findByAccountId + - findAllEnabled + - findAllWarehouses +- 迁移目标: + - app/service/systems/store.js +- 原因: + - 请求参数校验和查询策略属于服务层,不应下沉到 model。 + +## 3. 可移除候选(P2,先验证后删) + +- 已执行(第一批): + - app/model/api_app.js: `findByAppKey`、`findByQimenConfig`(已删除) + - app/model/interface_type.js: `findByCode`、`findEnabled`(已删除) + - app/model/print_item.js: `getGroupFields`、`getTableConfigs`(已删除) + - 门禁结果: compare mismatch=0,generated regression + smoke=14 passing + +- 已执行(第二批): + - app/model/i18n_translation.js: `getTranslation`、`batchGetTranslations`、`getProjectTranslations`、`upsertTranslation`、`getUntranslated`(已删除) + - app/model/stock_store.js: `findByItemCode`、`findByStore`(已删除) + - 门禁结果: compare mismatch=0,generated regression=8 passing,smoke=6 passing(合计 14 passing) + +- app/model/i18n_translation.js: + - getTranslation + - batchGetTranslations + - getProjectTranslations + - upsertTranslation + - getUntranslated +- app/model/interface_type.js: + - findByCode + - findEnabled +- app/model/print_item.js: + - getGroupFields + - getTableConfigs +- app/model/api_app.js: + - findByAppKey + - findByQimenConfig +- app/model/stock_store.js: + - findByItemCode + - findByStore + +说明: +- 上述方法本轮未检出业务层调用,建议先完成一次“删除前引用复核”再执行清理。 + +### 3.1 删除前引用复核(第二批) + +- 复核时间: 2026-03-23 +- 复核范围: + - app/model/i18n_translation.js + - app/model/stock_store.js + - app/service/**/*.js + - app/controller/**/*.js + - test/**/*.js + - script/**/*.js +- 复核方式: + - 方法名精确检索: getTranslation / batchGetTranslations / getProjectTranslations / upsertTranslation / getUntranslated / findByItemCode / findByStore + - 模型调用链检索: I18nTranslation.、ctx.model.I18nTranslation.、StockStore.、ctx.model.StockStore. + - 动态调用兜底检索: ['methodName'] 形式 +- 复核结论: + - 未检出 I18nTranslation 5 个候选静态方法的业务调用。 + - 未检出 StockStore 2 个候选静态方法的业务调用。 + - 检出 I18n 相关业务仍直接使用了模型基础能力(findAll/findOne/create/count),不受本次候选方法删除影响。 +- 可执行动作: + - 已执行清理并通过门禁,第二批可删除候选已关闭。 + +## 4. 保留在模型层(P3) + +建议保留: +- 轻量实例判断(isEnabled/isHidden/isExpired 等)。 +- 纯格式/展示映射(getTypeName/getRoleTypeName/getScopeName)。 +- 与关联语义绑定的 include 构造器(StoreWarehouse.buildStoreStockInclude)。 + +## 5. 下一步(5.2 输入) + +1. 已完成 P1 第一组迁移:EntryOrder / EntryItems 的 8 个静态方法已迁移到 app/service/systems/entry_order.js,并从 model 删除。 +2. 已完成 P1 第二组迁移:Storage 的 10 个静态方法已迁移到 app/service/systems/storage/index.js,并从 model 删除。 +3. 下一步继续迁移 P1 剩余项:RolePermission / Store。 +4. 最后补 model_boundary_rules.md,固化模型层边界。 + +## 6. 已执行(P1 第一组) + +- 执行时间: 2026-03-23 +- 迁移范围: + - app/model/entry_order.js + - app/model/entry_items.js + - app/service/systems/entry_order.js +- 迁移方法: + - EntryOrder.findByOrderCode + - EntryOrder.findByStatus + - EntryOrder.getStatsByWarehouse + - EntryOrder.updateSyncStatus + - EntryOrder.updateOrderStatus + - EntryOrder.calculateReceivedQuantities + - EntryItems.batchUpdateReceived + - EntryItems.getOrderProgress +- 说明: + - 对外 system/qimen method 未新增接口,属于内部职责收敛。 + - `calculateReceivedQuantities` 在 service 中改为显式查询 Storage 聚合,避免原 model 版本的相关子查询别名漂移风险。 +- 门禁结果: + - compare mismatch=0 + - generated regression=8 passing + - smoke=6 passing + - tests=14 passing + +## 7. 已执行(P1 第二组) + +- 执行时间: 2026-03-23 +- 迁移范围: + - app/model/storage.js + - app/service/systems/storage/index.js +- 迁移方法: + - Storage.findByStockAndBatch + - Storage.findBySpace + - Storage.findAvailableByWarehouse + - Storage.findExpiringSoon + - Storage.updateQuantity + - Storage.lockQuantity + - Storage.unlockQuantity + - Storage.allocateQuantity + - Storage.getStockSummary + - Storage.getSpaceUsage +- 说明: + - 对外 system/qimen method 未新增接口,属于内部职责收敛。 + - 更新类方法统一进入 service,模型层仅保留实例行为与关联映射。 diff --git a/model_inventory.md b/model_inventory.md new file mode 100644 index 0000000..faa4702 --- /dev/null +++ b/model_inventory.md @@ -0,0 +1,53 @@ +# model_inventory + +Updated: 2026-03-22 +Source: app/model/*.js +Count: 45 + +| key | file | defineName | tableName | kind | +| --- | --- | --- | --- | --- | +| account_platform_active | app/model/account_platform_active.js | account_platform_active | wms_account_platform_active | Model | +| account_store_employee | app/model/account_store_employee.js | wms_account_store_employee | wms_account_store_employee | Model | +| account | app/model/account.js | account | wms_account | Model | +| api_app | app/model/api_app.js | api_app | wms_api_app | Model | +| employee_role | app/model/employee_role.js | employee_role | wms_employee_role | Model | +| entry_items | app/model/entry_items.js | wms_entry_items | wms_entry_items | Model | +| entry_order | app/model/entry_order.js | wms_entry_order | wms_entry_order | Model | +| fast_where | app/model/fast_where.js | fast_where | wms_fast_where | Model | +| file_reference | app/model/file_reference.js | wms_file_reference | wms_file_reference | Model | +| file | app/model/file.js | wms_file | wms_file | Model | +| i18n_key | app/model/i18n_key.js | wms_i18n_key | wms_i18n_keys | Model | +| i18n_translation | app/model/i18n_translation.js | wms_i18n_translation | wms_i18n_translations | Model | +| interface_type | app/model/interface_type.js | interface_type | wms_interface_type | Model | +| location_space | app/model/location_space.js | wms_location_space | wms_location_space | Model | +| location_type | app/model/location_type.js | location_type | wms_location_type | Model | +| location_zone | app/model/location_zone.js | wms_location_zone | wms_location_zone | Model | +| operation_log | app/model/operation_log.js | operation_log | wms_operation_log | Model | +| order_delivery_factory | app/model/order_delivery_factory.js | - | - | Factory | +| order_delivery | app/model/order_delivery.js | order_delivery | wms_order_delivery | Model | +| order_items_factory | app/model/order_items_factory.js | - | - | Factory | +| order_items | app/model/order_items.js | wms_order_items | wms_order_items | Model | +| permission | app/model/permission.js | permission | wms_permission | Model | +| platform_setting | app/model/platform_setting.js | platform_setting | wms_platfrom_setting | Model | +| platform | app/model/platform.js | platform | wms_platform | Model | +| print_computer | app/model/print_computer.js | print_computer | wms_print_computer | Model | +| print_item | app/model/print_item.js | print_item | wms_print_items | Model | +| print_record | app/model/print_record.js | PrintRecord | wms_print_record | Model | +| print_station_express | app/model/print_station_express.js | print_station_express | wms_print_station_express | Model | +| print_stations | app/model/print_stations.js | print_stations | wms_print_stations | Model | +| print_template | app/model/print_template.js | print_template | wms_print_template | Model | +| prohibited_type | app/model/prohibited_type.js | prohibitedType | wms_prohibited_type | Model | +| qimen_app | app/model/qimen_app.js | qimen_app | wms_qimen_apps | Model | +| qimen_log | app/model/qimen_log.js | qimen_log | wms_qimen_log | Model | +| receiving_detail | app/model/receiving_detail.js | wms_receiving_detail | wms_receiving_detail | Model | +| receiving | app/model/receiving.js | wms_receiving | wms_receiving | Model | +| role_permission | app/model/role_permission.js | role_permission | wms_role_permission | Model | +| role | app/model/role.js | role | wms_role | Model | +| stock_barcode | app/model/stock_barcode.js | stock_barcodes | wms_stock_barcodes | Model | +| stock_store | app/model/stock_store.js | stock_store | wms_stock_store | Model | +| stock_unit | app/model/stock_unit.js | wms_stock_unit | wms_stock_unit | Model | +| stock_warehouse | app/model/stock_warehouse.js | stock_warehouse | wms_stock_warehouse | Model | +| storage | app/model/storage.js | wms_storage | wms_storage | Model | +| store_join | app/model/store_join.js | StoreJoin | wms_store_join | Model | +| store_warehouse | app/model/store_warehouse.js | store_warehouse | wms_store_warehouse | Model | +| store | app/model/store.js | store | wms_store | Model | diff --git a/model_naming_standard.md b/model_naming_standard.md new file mode 100644 index 0000000..24fc928 --- /dev/null +++ b/model_naming_standard.md @@ -0,0 +1,184 @@ +# Model 命名规范 + +更新时间: 2026-03-22 +适用范围: app/model、app/service、app/controller 中的 app.model / ctx.model 调用 + +## 1. 目标 + +- 统一 model 文件名、运行时 key、defineName、tableName、关联 alias 的命名规则。 +- 将“可直接收敛的风格问题”和“会影响业务语义的结构问题”拆开处理。 +- 为阶段 4 的关联规范化和阶段 5 的模型能力清理提供稳定基线。 + +## 2. 五层命名对象 + +当前仓库里,单个模型至少同时存在以下 5 个命名层: + +1. 文件名: app/model 下的文件名。 +2. 运行时 key: 代码里通过 app.model.Xxx / ctx.model.Xxx 使用的名称。 +3. defineName: Sequelize 的 app.model.define(name, attributes, options) 第一个参数。 +4. tableName: options.tableName,对应数据库真实对象名。 +5. alias: 关联查询里的 as 字段。 + +后续规范要求这 5 层职责分离,不再互相混用。 + +## 3. 统一规则 + +### 3.1 文件名 + +- 一律使用 snake_case。 +- 文件名表达“模型职责”,不表达数据库前缀。 +- 工厂模型必须以 _factory 结尾。 +- 除非是稳定历史兼容项,否则不在文件名中保留 wms 前缀。 + +示例: + +- account_store_employee.js +- platform_setting.js +- order_delivery_factory.js + +### 3.2 运行时 key + +- 一律使用 PascalCase。 +- 运行时 key 由文件名去掉扩展名后转为 PascalCase。 +- 这是 service/controller/model 之间的主兼容面,优先级高于 defineName。 +- 工厂模型保留 Factory 后缀。 + +示例: + +- account_store_employee.js -> AccountStoreEmployee +- platform_setting.js -> PlatformSetting +- order_delivery_factory.js -> OrderDeliveryFactory + +### 3.3 defineName + +- 静态模型的 defineName 必须与运行时 key 保持一致。 +- 不再使用 snake_case、wms_ 前缀或局部 lowerCamelCase 作为 defineName。 +- 动态分表模型允许在运行时使用真实 tableName 作为 defineName,但外部只允许通过工厂 key 获取,不直接在业务层引用动态 defineName。 + +示例: + +- PlatformSetting: 正确 +- platform_setting: 不再推荐 +- prohibitedType: 不再推荐 +- wms_account_store_employee: 不再推荐 + +### 3.4 tableName + +- tableName 只负责映射数据库真实对象。 +- 一律保持数据库现状,不因 model 命名规范化而强制修改表名。 +- 物理表继续保留现有 wms_ 前缀、复数形式、历史拼写问题。 +- 视图、动态分表、历史表单独记录,不纳入静态命名统一的修改范围。 + +示例: + +- PlatformSetting -> tableName: wms_platfrom_setting +- StockBarcode -> tableName: wms_stock_barcodes +- PrintStations -> tableName: wms_print_stations + +说明: + +- tableName 中的历史拼写错误属于数据库治理问题,不属于本阶段命名规范化问题。 + +### 3.5 alias + +- belongsTo / hasOne 使用 lowerCamelCase 单数。 +- hasMany / belongsToMany 使用 lowerCamelCase 复数。 +- alias 反映关联语义,不复用旧表名或旧模型名。 +- alias 必须与真实关系一致,不能把 employee 关系继续命名为 role。 + +示例: + +- belongsTo(Store, { as: 'store' }) +- hasMany(EmployeeRole, { as: 'employeeRoles' }) +- belongsTo(AccountStoreEmployee, { as: 'accountStoreEmployee' }) + +## 4. 兼容优先级 + +按风险从高到低分三类处理: + +### A 类: 运行时 key 不存在或调用错误 + +- 必须先修。 +- 这类问题会直接导致运行时取不到模型,或拿到错误关联。 +- 典型例子: + - AccountStoreRole + - WmsOrderDeliveryFactory + - WmsOrderItemsFactory + +### B 类: defineName 不规范但运行时可用 + +- 可分批修。 +- 前提是 tableName 已显式声明,且不存在依赖 defineName 字符串的外部逻辑。 +- 典型例子: + - platform_setting + - qimen_app + - qimen_log + - prohibitedType + - stock_barcodes + +### C 类: alias 与业务语义不一致 + +- 必须与阶段 4 一起处理。 +- 不能只改 alias 文本,需要一起核对外键、include、返回结构。 +- 典型例子: + - accountStoreRoles + - accountStoreRole + - employeeRole + +## 5. 仓库内落地规则 + +### 5.1 本项目允许保留的历史兼容项 + +以下项目前阶段不因“风格统一”而强制改文件名: + +- print_stations.js + - 原因: 运行时大量使用 PrintStations,且 tableName 为 wms_print_stations。 +- store_join.js + - 原因: 运行时与 defineName 已一致,当前主要问题不在命名层。 +- order_delivery_factory.js / order_items_factory.js + - 原因: 工厂职责明确,外部兼容面稳定。 + +### 5.2 本项目必须执行的统一动作 + +- 所有静态模型的 defineName 逐步收敛到 PascalCase 运行时 key。 +- 所有业务代码统一通过 ctx.model.Xxx / app.model.Xxx 的 PascalCase key 调用。 +- 任何 include/as 字段都必须与当前模型关联定义一致。 +- 不再新增任何带 wms 前缀的 defineName。 +- 不再新增任何与真实语义不一致的 alias。 + +## 6. 参考示例 + +### 6.1 标准静态模型 + +- 文件名: platform_setting.js +- 运行时 key: PlatformSetting +- defineName: PlatformSetting +- tableName: wms_platfrom_setting + +### 6.2 标准关联模型 + +- 文件名: account_store_employee.js +- 运行时 key: AccountStoreEmployee +- defineName: AccountStoreEmployee +- tableName: wms_account_store_employee +- alias: + - belongsTo(Account, { as: 'account' }) + - belongsTo(Store, { as: 'store' }) + - hasMany(EmployeeRole, { as: 'employeeRoles' }) + +### 6.3 标准工厂模型 + +- 文件名: order_delivery_factory.js +- 运行时 key: OrderDeliveryFactory +- 对外入口: + - ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId) + - ctx.model.OrderDeliveryFactory.getHistoryModel(warehouseId) +- 约束: + - 业务代码不直接引用动态表 defineName。 + +## 7. 执行边界 + +- 本阶段先统一标准、映射和影响面,不直接大规模改名。 +- 运行时 key 修复优先于 defineName 收敛。 +- alias 修复必须与关联关系校验一起推进。 +- 数据库表名不在本阶段统一修改范围内。 \ No newline at end of file diff --git a/model_rename_map.md b/model_rename_map.md new file mode 100644 index 0000000..367501a --- /dev/null +++ b/model_rename_map.md @@ -0,0 +1,100 @@ +# Model 重命名映射表 + +更新时间: 2026-03-22 +来源: + +- model_inventory.md +- app/model/*.js +- app/service/**/*.js +- app/controller/**/*.js + +## 1. 使用说明 + +- 本表只记录阶段 3 已确认的命名规范化项。 +- 变更级别分为 4 类: + - P0-调用修复: 现有代码引用错误或运行时 key 不存在,必须先修。 + - P1-defineName 收敛: 只调整 defineName,不动文件名和 tableName。 + - P2-alias 收敛: 需要和关联定义一起调整。 + - 保持不动: 暂不建议改动。 + +## 2. P0: 必须先修的运行时调用 + +| 当前调用/命名 | 建议标准名 | 变更级别 | 原因 | 备注 | +| --- | --- | --- | --- | --- | +| WmsOrderDeliveryFactory | OrderDeliveryFactory | P0-调用修复 | 仓库内主流调用均为 OrderDeliveryFactory,当前写法与文件名不匹配 | 先修 app/service/apiMethods/test.js | +| WmsOrderItemsFactory | OrderItemsFactory | P0-调用修复 | 仓库内主流调用均为 OrderItemsFactory,当前写法与文件名不匹配 | 先修 app/service/apiMethods/test.js | +| AccountStoreRole | AccountStoreEmployee 或补回独立模型 | P0-调用修复 | 仓库内无 account_store_role.js,且当前表结构已落到 account_store_employee + employee_role | 需要先确认目标数据关系 | +| accountStoreRole | accountStoreEmployee | P0-调用修复 | AccountPlatformActive 当前关联 alias 为 accountStoreEmployee,service 仍按 accountStoreRole 取值 | 要与 include 返回结构一起改 | + +## 3. P1: defineName 收敛为运行时 key + +以下项优先采用“只改 defineName,不改文件名、不改 tableName”的方式收敛。 + +| 文件 | 当前运行时 key | 当前 defineName | 建议 defineName | 变更级别 | +| --- | --- | --- | --- | --- | +| app/model/account_platform_active.js | AccountPlatformActive | account_platform_active | AccountPlatformActive | P1-defineName 收敛 | +| app/model/account_store_employee.js | AccountStoreEmployee | wms_account_store_employee | AccountStoreEmployee | P1-defineName 收敛 | +| app/model/account.js | Account | account | Account | P1-defineName 收敛 | +| app/model/api_app.js | ApiApp | api_app | ApiApp | P1-defineName 收敛 | +| app/model/employee_role.js | EmployeeRole | employee_role | EmployeeRole | P1-defineName 收敛 | +| app/model/entry_items.js | EntryItems | wms_entry_items | EntryItems | P1-defineName 收敛 | +| app/model/entry_order.js | EntryOrder | wms_entry_order | EntryOrder | P1-defineName 收敛 | +| app/model/fast_where.js | FastWhere | fast_where | FastWhere | P1-defineName 收敛 | +| app/model/file_reference.js | FileReference | wms_file_reference | FileReference | P1-defineName 收敛 | +| app/model/file.js | File | wms_file | File | P1-defineName 收敛 | +| app/model/i18n_key.js | I18nKey | wms_i18n_key | I18nKey | P1-defineName 收敛 | +| app/model/i18n_translation.js | I18nTranslation | wms_i18n_translation | I18nTranslation | P1-defineName 收敛 | +| app/model/interface_type.js | InterfaceType | interface_type | InterfaceType | P1-defineName 收敛 | +| app/model/location_space.js | LocationSpace | wms_location_space | LocationSpace | P1-defineName 收敛 | +| app/model/location_type.js | LocationType | location_type | LocationType | P1-defineName 收敛 | +| app/model/location_zone.js | LocationZone | wms_location_zone | LocationZone | P1-defineName 收敛 | +| app/model/operation_log.js | OperationLog | operation_log | OperationLog | P1-defineName 收敛 | +| app/model/order_delivery.js | OrderDelivery | order_delivery | OrderDelivery | P1-defineName 收敛 | +| app/model/order_items.js | OrderItems | wms_order_items | OrderItems | P1-defineName 收敛 | +| app/model/permission.js | Permission | permission | Permission | P1-defineName 收敛 | +| app/model/platform_setting.js | PlatformSetting | platform_setting | PlatformSetting | P1-defineName 收敛 | +| app/model/platform.js | Platform | platform | Platform | P1-defineName 收敛 | +| app/model/print_computer.js | PrintComputer | print_computer | PrintComputer | P1-defineName 收敛 | +| app/model/print_item.js | PrintItem | print_item | PrintItem | P1-defineName 收敛 | +| app/model/print_station_express.js | PrintStationExpress | print_station_express | PrintStationExpress | P1-defineName 收敛 | +| app/model/print_stations.js | PrintStations | print_stations | PrintStations | P1-defineName 收敛 | +| app/model/print_template.js | PrintTemplate | print_template | PrintTemplate | P1-defineName 收敛 | +| app/model/prohibited_type.js | ProhibitedType | prohibitedType | ProhibitedType | P1-defineName 收敛 | +| app/model/qimen_app.js | QimenApp | qimen_app | QimenApp | P1-defineName 收敛 | +| app/model/qimen_log.js | QimenLog | qimen_log | QimenLog | P1-defineName 收敛 | +| app/model/receiving_detail.js | ReceivingDetail | wms_receiving_detail | ReceivingDetail | P1-defineName 收敛 | +| app/model/receiving.js | Receiving | wms_receiving | Receiving | P1-defineName 收敛 | +| app/model/role_permission.js | RolePermission | role_permission | RolePermission | P1-defineName 收敛 | +| app/model/role.js | Role | role | Role | P1-defineName 收敛 | +| app/model/stock_barcode.js | StockBarcode | stock_barcodes | StockBarcode | P1-defineName 收敛 | +| app/model/stock_store.js | StockStore | stock_store | StockStore | P1-defineName 收敛 | +| app/model/stock_unit.js | StockUnit | wms_stock_unit | StockUnit | P1-defineName 收敛 | +| app/model/stock_warehouse.js | StockWarehouse | stock_warehouse | StockWarehouse | P1-defineName 收敛 | +| app/model/storage.js | Storage | wms_storage | Storage | P1-defineName 收敛 | +| app/model/store_warehouse.js | StoreWarehouse | store_warehouse | StoreWarehouse | P1-defineName 收敛 | +| app/model/store.js | Store | store | Store | P1-defineName 收敛 | + +## 4. 保持不动或低优先级处理项 + +| 文件 | 当前运行时 key | 当前 defineName | 建议 | 说明 | +| --- | --- | --- | --- | --- | +| app/model/order_delivery_factory.js | OrderDeliveryFactory | 动态 tableName | 保持不动 | 工厂模型,不参与静态 defineName 收敛 | +| app/model/order_items_factory.js | OrderItemsFactory | 动态 tableName | 保持不动 | 工厂模型,不参与静态 defineName 收敛 | +| app/model/print_record.js | PrintRecord | PrintRecord | 保持不动 | 已符合标准 | +| app/model/store_join.js | StoreJoin | StoreJoin | 保持不动 | 已符合标准 | + +## 5. P2: alias 收敛候选 + +| 位置 | 当前 alias | 建议 alias | 变更级别 | 说明 | +| --- | --- | --- | --- | --- | +| app/model/account.js | accountStoreRoles | accountStoreEmployees | P2-alias 收敛 | 当前关联对象实际为 AccountStoreEmployee | +| app/model/account_platform_active.js | accountStoreEmployee | accountStoreEmployee | 保持 | 当前 alias 合理,问题在 service 调用侧 | +| app/model/account_store_employee.js | employeeRole | employeeRoles | P2-alias 收敛 | hasMany 建议使用复数 | +| app/model/store.js | accountStoreEmployee | accountStoreEmployees | P2-alias 收敛 | hasMany 建议使用复数 | +| app/model/role.js | employeeRole | employeeRoles | P2-alias 收敛 | hasMany 建议使用复数 | + +## 6. 执行顺序建议 + +1. 先修 P0 调用错误,保证所有 ctx.model / app.model 均能拿到正确对象。 +2. 再做 P1 defineName 收敛,限定在显式声明了 tableName 的静态模型。 +3. 最后做 P2 alias 收敛,并与阶段 4 的关联核对同步执行。 \ No newline at end of file diff --git a/model_todo.txt b/model_todo.txt new file mode 100644 index 0000000..1a06943 --- /dev/null +++ b/model_todo.txt @@ -0,0 +1,130 @@ +Model 重构总计划(数据库 + Migrations + Models) +更新时间: 2026-03-22 +当前状态: 执行中(阶段 1-3 已完成) +负责人: +目标截止时间: +执行分支: + +[事务归属] +- 本子事务已纳入 `todo.txt` 总事务看板统一管理。 +- 主里程碑对齐总事务 DDL(2026-04-15),以总事务验收为最终关闭条件。 + +[最终目标] +- 梳理数据库中所有表结构并形成统一基线。 +- 补全并对齐 database/migrations 目录下的迁移文件。 +- 规范所有 model 的命名与内部关联。 +- 清理所有 model 内部能力(移除死代码、职责收敛、保持模型层可预测)。 + +[执行规则] +- [x] 本文件用于规划拆解,已完成初始化。 +- [x] 已收到新任务,开始执行阶段 1。 +- [x] 进入代码改动前,先核对目标 service 的真实调用链。 +- [x] 若 service 已被 system/qimen 入口使用,则必须同步更新对应 API 文档。 +- [x] 所有联动修改需记录到 SERVICE_API_CHANGE_AUDIT_20260322.md,便于后续复盘。 +- [x] 任何模型/关联改动前,使用测试账号执行 method 基线回放(配置与样本来源必须可追溯)。 +- [x] 任何模型/关联改动后,执行同一批 method 对比回放并输出比对报告。 +- [x] 新增交付条件:修改前后 method 输出结果一致(允许仅屏蔽 token/timestamp 等波动字段)。 +- [x] 后续所有接口返回数据检测,统一使用“自动生成的 Egg.js 标注测试脚本”执行校验。 + +[阶段 1: 全量盘点与基线建立] +- [x] 1.1 盘点所有数据表(字段、主键、索引、约束、注释)。 +- [x] 1.2 盘点所有 model 文件(app/model 下文件、导出名、表映射)。 +- [x] 1.3 盘点 model 关联(belongsTo/hasMany/hasOne/belongsToMany 与外键使用)。 +- [x] 1.4 产出 DB 结构与 model 定义差异报告。 +- [x] 1.5 在根目录生成 modelList.md,构建 model 层级结构与说明。 +- [x] 1.6 在 README.md 增加对 modelList.md 的引用说明。 +交付物: +- table_schema_inventory.md +- model_inventory.md +- model_association_inventory.md +- schema_model_gap_report.md +- modelList.md +退出标准: +- 100% 数据表与 100% model 文件覆盖完成。 +- modelList.md 可用于快速定位模型层级与职责。 + +[阶段 2: Migration 补全与执行顺序设计] +- [x] 2.1 审核现有 database/migrations 的命名、顺序、幂等性。 +- [x] 2.2 根据阶段 1 差异清单补齐缺失迁移任务。 +- [x] 2.3 设计迁移执行顺序(先结构后索引/约束,必要时分批回填数据)。 +- [x] 2.4 为每个迁移定义可执行回滚步骤。 +- [x] 2.5 形成 local/test 环境演练方案。 +交付物: +- migration_gap_list.md +- migration_execution_plan.md +- rollback_plan.md +退出标准: +- 每个结构差异都有明确迁移归属与回滚路径。 + +[阶段 3: Model 命名规范化] +- [x] 3.1 定义命名规范(文件名、类名、model key、表映射、alias)。 +- [x] 3.2 产出非规范命名的重命名映射表。 +- [x] 3.3 评估跨层影响(service/controller/query 调用点)。 +- [x] 3.4 制定兼容策略(临时别名或分批重命名)。 +交付物: +- model_naming_standard.md +- model_rename_map.md +- rename_impact_report.md +退出标准: +- 所有命名不规范项有明确修复路径与影响说明。 + +[阶段 4: 关联关系规范化] +- [x] 4.1 逐项校验关联定义与真实外键关系一致性(详见 association_fk_consistency_report.md)。 +- [x] 4.2 统一 alias 命名与双向关联完整性。 +- [x] 4.3 清理重复或冲突关联。 +- [x] 4.4 形成 eager-loading 与 N+1 风险规约(详见 association_eager_loading_n_plus_one_guideline.md)。 +交付物: +- association_fix_plan.md +- association_validation_checklist.md +退出标准: +- 关联关系可预测、无冲突、与数据库关系一致。 + +[阶段 5: Model 内部能力清理] +- [x] 5.1 识别应迁移到 service 层的方法能力(见 model_cleanup_list.md 第一批清单)。 +- [ ] 5.2 清理 model 内死代码与调试代码(进行中:第一批/第二批 P2 无调用静态方法已清理;P1 前两组 EntryOrder/EntryItems 与 Storage 已迁移到 service)。 +- [ ] 5.3 规范 hooks/scopes/virtual fields 的使用边界。 +- [ ] 5.4 固化模型层边界规则(可做/不可做)。 +交付物: +- model_cleanup_list.md +- model_boundary_rules.md +退出标准: +- 模型层聚焦于数据映射与轻量领域行为,职责边界清晰。 + +[阶段 6: 验证与交接] +- [ ] 6.1 在干净库上回放 migration 全流程。 +- [ ] 6.2 验证 model CRUD 与关联查询正确性。 +- [ ] 6.3 执行关键 API 冒烟回归(包含 method-output 基线/对比)。 +- [ ] 6.4 更新最终文档(README + methods + 内部交接文档)。 +交付物: +- verification_report.md +- handover_notes.md +退出标准: +- 无迁移漂移、无关联错配、无阻断回归问题。 + +[风险] +- 历史遗留表或隐式依赖未被识别。 +- 环境间数据漂移导致验证结果不一致。 +- 命名调整引发跨层调用副作用。 + +[依赖] +- 稳定可访问的数据库环境(盘点与验证)。 +- 统一确认的命名与关联规范。 +- 可执行的迁移窗口与回滚窗口。 + +[下一步] +- 阶段 4 的 4.1-4.4 已完成(含 receiving 第一批收敛与 N+1/eager-loading 规约落地)。 +- 高优先差异项推进: 已完成 store_warehouse/stock_warehouse 第二批收敛(stock_store include 语义约束补齐),并通过门禁。 +- 高优先差异项推进: 已完成 role / role_permission / permission 第三批收敛(启用状态过滤 + 去重),并通过门禁。 +- 已完成“DB 约束补齐”执行: `wms_role_permission.permission_id -> wms_permission.id` 外键已生效,SequelizeMeta 已登记 `20260323103000-align-role-permission-fk.js`。 +- 已完成数据清洗与备份: 4 条 permission 孤儿、3 条 role.store_id=0 哨兵数据均已处理(备份表见 `role_permission_fk_data_cleanup_plan.md`)。 +- 已完成 `wms_role.store_id` 外键策略落地:外键 `fk_wms_role_store` 已生效(ON DELETE SET NULL),SequelizeMeta 已登记 `20260323113000-add-role-store-fk.js`。 +- 已完成 store_warehouse / stock_warehouse 模型层复合键语义治理(统一 include 构造器 + constraints:false 显式化)。 +- 已完成阶段 4 收尾检查(第 1 项):全量 include alias 一致性扫描(service alias 与 model alias 差集=0)。 +- 已完成阶段 4 收尾检查(第 2 项):permission.parent_id 自关联约束策略已落地(root=NULL + FK)。 +- 已完成阶段 5.1:识别应迁移到 service 层的方法能力(第一批清单见 model_cleanup_list.md)。 +- 已启动阶段 5.2:已完成第一批 P2 无调用静态方法清理(ApiApp / InterfaceType / PrintItem),门禁通过。 +- 已完成阶段 5.2 删除前引用复核(第二批):I18nTranslation 5 个候选静态方法、StockStore 2 个候选静态方法均未检出业务调用。 +- 已完成阶段 5.2 第二批 P2 方法删除(I18nTranslation / StockStore),compare + generated regression + smoke 门禁通过。 +- 已完成阶段 5.2 P1 第一组迁移:EntryOrder / EntryItems 共 8 个静态方法已迁移到 `app/service/systems/entry_order.js`,并从 model 删除;compare + generated regression + smoke 门禁通过。 +- 已完成阶段 5.2 P1 第二组迁移:Storage 共 10 个静态方法已迁移到 `app/service/systems/storage/index.js`,并从 model 删除。 +- 下一步继续阶段 5.2:推进 P1 剩余方法(RolePermission / Store)从 model 向 service 收敛,并在迁移完成后回收对应静态方法。 diff --git a/rename_impact_report.md b/rename_impact_report.md new file mode 100644 index 0000000..2d7824c --- /dev/null +++ b/rename_impact_report.md @@ -0,0 +1,168 @@ +# Model 命名影响评估报告 + +更新时间: 2026-03-22 +范围: + +- app/model/*.js +- app/service/**/*.js +- app/controller/**/*.js + +## 1. 结论摘要 + +当前命名问题分成两层: + +1. 真正会影响运行的调用错误。 +2. 还能运行,但会持续制造理解成本和后续重构风险的 defineName/alias 漂移。 + +本轮确认的最高优先级风险有 3 个: + +### 1.1 AccountStoreRole 是仓库内不存在的运行时 key + +- 代码大量使用 ctx.model.AccountStoreRole。 +- app/model 下没有对应的 account_store_role.js。 +- 现有 schema 已落到 AccountStoreEmployee + EmployeeRole 两层关系。 +- 这不是单纯命名风格问题,而是“旧关系名残留到新模型结构”的兼容断层。 + +### 1.2 动态分表工厂存在一组错误调用名 + +- 仓库主流调用是 OrderDeliveryFactory / OrderItemsFactory。 +- 仅 app/service/apiMethods/test.js 仍在使用 WmsOrderDeliveryFactory / WmsOrderItemsFactory。 +- 这会导致测试/调试路径与正式业务路径使用不同的模型入口。 + +### 1.3 alias 已经切到 employee 语义,但 service 仍按 role 语义取值 + +- app/model/account_platform_active.js 中 alias 是 accountStoreEmployee。 +- 但 app/service/systems/account_platform.js 仍按 accountStoreRole 进行 include 和结果读取。 +- 这说明 model 层与 service 层对同一关系的语义认知已经分叉。 + +## 2. 关键证据 + +### 2.1 不存在的 model key: AccountStoreRole + +受影响位置: + +- app/service/systems/account_platform.js:21 +- app/service/systems/account_platform.js:102 +- app/service/systems/account_platform.js:169 +- app/service/systems/account_platform.js:226 +- app/service/systems/account_platform.js:321 +- app/service/systems/store.js:464 +- app/service/systems/store.js:679 +- app/service/systems/store.js:690 +- app/model/role.js:151 + +现状说明: + +- app/model/account_store_employee.js:6 定义的是 AccountStoreEmployee,表为 wms_account_store_employee。 +- app/model/account_store_employee.js:82-99 说明当前关系是 AccountStoreEmployee -> EmployeeRole -> Role。 +- app/model/account_platform_active.js:79-86 已把激活关系关联到 AccountStoreEmployee。 + +风险判断: + +- 如果继续沿用 AccountStoreRole,后续关联收敛会同时破坏 include、字段读取、缓存结构与返回结构。 +- 该问题必须在正式改 defineName 之前先做数据关系确认。 + +建议动作: + +1. 先确认“平台激活”想绑定的是员工记录还是员工-角色明细。 +2. 若绑定员工记录,则将 AccountStoreRole 全量替换为 AccountStoreEmployee,并改造 role 读取路径。 +3. 若绑定员工-角色明细,则需要新增独立模型,而不是继续使用幽灵 key。 + +### 2.2 动态工厂 key 调用漂移 + +正常调用样本: + +- app/service/systemMethods/order.js:22-23 +- app/service/systems/delivery_order.js:14 +- app/service/systems/delivery_order.js:311 +- app/service/qimenMethods/deliveryorder.js:7-8 + +异常调用样本: + +- app/service/apiMethods/test.js:50 +- app/service/apiMethods/test.js:51 + +风险判断: + +- 正式链路与调试链路的 model 入口不一致,后续如果只修主链路,测试链路会继续漂移。 +- 这是低成本高收益修复项,应优先纳入第一批代码修正。 + +建议动作: + +1. 将 WmsOrderDeliveryFactory 改为 OrderDeliveryFactory。 +2. 将 WmsOrderItemsFactory 改为 OrderItemsFactory。 +3. 回归验证动态表 current/history 获取能力是否一致。 + +### 2.3 alias 与语义漂移 + +证据位置: + +- app/model/account.js:139 使用 alias accountStoreRoles,但实际模型是 AccountStoreEmployee。 +- app/model/account_platform_active.js:84 使用 alias accountStoreEmployee。 +- app/model/account_store_employee.js:95 使用 hasMany(EmployeeRole, { as: 'employeeRole' })。 +- app/model/role.js:171 使用 hasMany(EmployeeRole, { as: 'employeeRole' })。 +- app/service/systems/account_platform.js:102-136 仍按 accountStoreRole 读取嵌套字段。 + +风险判断: + +- 当前 alias 命名混合了“员工关系”和“角色关系”两种语义。 +- 若不先统一语义,后续只做名字替换会把问题从命名层转移到数据层。 + +建议动作: + +1. 阶段 4 先梳理 employee、role、store 三者的真实关系。 +2. hasMany alias 收敛为复数形式,如 employeeRoles、accountStoreEmployees。 +3. service 层返回结构与 include 路径同步改名,避免只改 model 不改消费方。 + +## 3. defineName 漂移影响 + +以下问题当前通常不会直接导致运行失败,但会持续造成阅读成本与重构误判: + +| 文件 | 证据 | 当前情况 | 风险 | +| --- | --- | --- | --- | +| app/model/platform_setting.js | :7 | defineName 为 platform_setting,运行时 key 为 PlatformSetting | 阅读时容易误以为 key 与 defineName 同名 | +| app/model/qimen_app.js | :6 | defineName 为 qimen_app,运行时 key 为 QimenApp | service 调用与模型定义风格分裂 | +| app/model/qimen_log.js | :8 | defineName 为 qimen_log,运行时 key 为 QimenLog | 日志模型定位成本高 | +| app/model/account_store_employee.js | :6 | defineName 为 wms_account_store_employee,运行时 key 为 AccountStoreEmployee | 将表名语义混入模型名 | +| app/model/stock_barcode.js | :6 | defineName 为 stock_barcodes,运行时 key 为 StockBarcode | 单复数与 key 同时漂移 | +| app/model/prohibited_type.js | :6 | defineName 为 prohibitedType,运行时 key 为 ProhibitedType | lowerCamelCase 与 PascalCase 混用 | +| app/model/print_stations.js | :5 | defineName 为 print_stations,运行时 key 为 PrintStations | 虽可运行,但风格不统一 | + +影响判断: + +- 新增 include、调试 SQL、追踪关联时,很容易把 defineName、key、tableName 当成同一件事。 +- 后续如果继续新增 snake_case defineName,会放大维护面。 + +建议动作: + +1. 先完成 P0 调用修复。 +2. 再按 model_rename_map.md 分批将 defineName 收敛到 PascalCase。 +3. 每次改 defineName 后,回归关联加载与 SQL 日志输出,确认未引入隐式副作用。 + +## 4. 稳定项与例外项 + +以下命名虽然不完全理想,但当前不建议仅因风格而改动: + +- app/model/print_record.js + - defineName 已为 PrintRecord,运行时 key 与之保持一致。 +- app/model/store_join.js + - defineName 已为 StoreJoin,当前问题主要不在命名层。 +- app/model/order_delivery_factory.js + - 工厂模型对外 key 稳定,重点是调用方统一。 +- app/model/order_items_factory.js + - 工厂模型对外 key 稳定,重点是调用方统一。 +- app/model/print_stations.js + - 文件名和表名均为复数,当前更适合先保留为历史兼容项,不单独改文件名。 + +## 5. 推荐执行顺序 + +1. 第一批: 修正不存在的运行时 key 和错误工厂调用名。 +2. 第二批: 收敛静态模型 defineName,保持 tableName 不变。 +3. 第三批: 在关联核对完成后统一 alias 和 include 路径。 +4. 第四批: 更新测试、README、modelList.md、关联清单等文档。 + +## 6. 对后续阶段的输入 + +- 阶段 4 需要重点核对 AccountPlatformActive、AccountStoreEmployee、EmployeeRole、Role、Store 的外键与 include 结构。 +- 阶段 5 需要顺带清理与命名漂移绑定的死代码、调试日志和旧语义变量名。 +- 阶段 6 验证时必须覆盖平台激活、仓库角色分配、动态订单分表、打印链路四类高风险场景。 \ No newline at end of file diff --git a/role_permission_fk_data_cleanup_plan.md b/role_permission_fk_data_cleanup_plan.md new file mode 100644 index 0000000..c4c404a --- /dev/null +++ b/role_permission_fk_data_cleanup_plan.md @@ -0,0 +1,104 @@ +# role_permission_fk_data_cleanup_plan + +更新时间: 2026-03-23 +目标: 清理 role/permission 相关孤儿数据,解除 `20260323103000-align-role-permission-fk.js` 执行阻塞。 + +## 1. 审计现状 + +- `wms_role_permission.permission_id` 孤儿记录: 4 条(id: 2, 3, 6, 10) +- `wms_role.store_id` 非法哨兵值: 3 条(store_id = 0) +- 字段类型差异: + - `wms_permission.id`: `int(11)` + - `wms_role_permission.permission_id`: `bigint(20) unsigned`(迁移已处理为对齐) + +## 2. 执行顺序 + +1. 备份孤儿数据 +2. 删除 `wms_role_permission` 孤儿行 +3. 规范 `wms_role.store_id = 0` 为 `NULL`(仅对可空字段) +4. 复核计数 +5. 执行迁移 `20260323103000-align-role-permission-fk.js` + +## 3. 推荐 SQL(先在测试环境执行) + +### 3.1 备份 role_permission 孤儿行 + +```sql +CREATE TABLE IF NOT EXISTS wms_role_permission_orphan_backup_20260323 AS +SELECT rp.* +FROM wms_role_permission rp +LEFT JOIN wms_permission p ON p.id = rp.permission_id +WHERE p.id IS NULL; +``` + +### 3.2 删除 role_permission 孤儿行 + +```sql +DELETE rp +FROM wms_role_permission rp +LEFT JOIN wms_permission p ON p.id = rp.permission_id +WHERE p.id IS NULL; +``` + +### 3.3 规范 role.store_id 哨兵值 + +```sql +UPDATE wms_role +SET store_id = NULL +WHERE store_id = 0; +``` + +### 3.4 复核 + +```sql +SELECT 'rp_perm_orphan' AS metric, COUNT(*) AS cnt +FROM wms_role_permission rp +LEFT JOIN wms_permission p ON p.id = rp.permission_id +WHERE p.id IS NULL +UNION ALL +SELECT 'role_store_zero' AS metric, COUNT(*) AS cnt +FROM wms_role +WHERE store_id = 0; +``` + +## 4. 回滚思路 + +- 若删除孤儿行后需要回滚,可从备份表恢复: + +```sql +INSERT INTO wms_role_permission (id, role_id, permission_id, created_at) +SELECT id, role_id, permission_id, created_at +FROM wms_role_permission_orphan_backup_20260323; +``` + +- `wms_role.store_id` 从 `0 -> NULL` 回滚需结合业务语义,不建议盲目全量回写 `0`。 + +## 5. 交付门禁 + +清洗和迁移完成后,执行: + +1. `node .\\script\\method-output-regression.cjs compare` +2. `node .\\script\\tmp-generate-method-regression-test.cjs` +3. `npx egg-bin test temp/generated-tests/system.method-output.generated.test.js` +4. `npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js` + +通过标准: + +- compare: mismatch=0 +- 回归测试: 全部通过 + +## 6. 执行记录(2026-03-23) + +- 备份执行结果: + - `wms_role_permission_orphan_backup_20260323`: 4 行 + - `wms_role_store_zero_backup_20260323`: 3 行 +- 清洗执行结果: + - role_permission 孤儿删除: 4 行 + - role.store_id=0 -> NULL: 3 行 +- 迁移执行结果: + - `wms_role_permission.permission_id` 已对齐为 `int(11)` + - 外键 `fk_wms_role_permission_permission` 已生效 + - SequelizeMeta 已登记 `20260323103000-align-role-permission-fk.js` +- 门禁结果: + - method-output compare: mismatch=0 + - generated regression + smoke: 14 passing diff --git a/rollback_plan.md b/rollback_plan.md new file mode 100644 index 0000000..4dc84b4 --- /dev/null +++ b/rollback_plan.md @@ -0,0 +1,49 @@ +# rollback_plan + +更新时间: 2026-03-22 + +## 1. 通用回滚规则 + +- 所有新增 migration 必须提供 down。 +- 对现网已有表,down 不应默认直接 drop 整表。 +- 优先回滚新增字段、索引、约束,避免误删存量数据。 +- 涉及数据回填的 migration,必须保留影响范围快照或备份。 + +## 2. 分类型回滚策略 + +### 建表 migration + +- 新环境可使用 dropTable 回滚。 +- 现网已有表不建议通过 down 删除,应改为“标记基线 + 停止继续执行”。 + +### 加字段 migration + +- down 使用 dropColumn。 +- 执行前需确认字段不被线上代码强依赖。 + +### 索引 migration + +- down 使用 removeIndex。 +- 若为性能补丁索引,回滚前需评估查询退化风险。 + +### 视图 migration + +- down 使用 drop view。 +- 回滚前确认是否有查询依赖视图。 + +### 动态分表策略 migration + +- 只回滚策略与模板,不批量 drop 已创建的仓库动态表。 +- 已存在分表应通过单独治理,不纳入统一 down 删除范围。 + +## 3. 当前优先风险 + +- 未进入 SequelizeMeta 的 migration 不能按常规 down 处理,必须先确认其是否已在数据库中手工生效。 +- order_delivery/order_items 主表与动态表结构存在差异,回滚时必须区分主表与动态表。 +- 日志类表通常已有存量数据,回滚需要避免整表删除。 + +## 4. 建议执行前准备 + +- 每批 migration 执行前导出目标表结构快照。 +- 若涉及数据变更,先做行数统计与影响范围确认。 +- 为每批次准备单独回滚脚本,不依赖临场拼写 SQL。 diff --git a/schema_model_gap_report.md b/schema_model_gap_report.md new file mode 100644 index 0000000..36a7e4b --- /dev/null +++ b/schema_model_gap_report.md @@ -0,0 +1,98 @@ +# schema_model_gap_report + +Updated: 2026-03-22 + +## Scope + +- DB source: information_schema.TABLES / COLUMNS / STATISTICS +- Model source: app/model/*.js (tableName option) + +## Count + +- Model files: 45 +- Model with tableName: 43 +- DB tables: 68 +- modelOnly table count: 0 +- dbOnly table count: 25 + +## modelOnly tables + +- none + +## dbOnly tables + +- SequelizeMeta +- wms_account_login_log +- wms_api_log +- wms_embargo_policies +- wms_express +- wms_express_print_record +- wms_express_setting +- wms_order_delivery_100000 +- wms_order_delivery_1000028 +- wms_order_express +- wms_order_express_print_data +- wms_order_items_100000 +- wms_order_items_1000028 +- wms_order_operation +- wms_order_operation_log +- wms_order_picking +- wms_picking_strategy +- wms_platform_print_config +- wms_print_batch +- wms_print_log +- wms_printer_config +- wms_system_config +- wms_system_log +- wms_wave_batch +- wms_wave_operation_log + +## Model mapping snapshot + +| key | file | defineName | tableName | +| --- | --- | --- | --- | +| account | app/model/account.js | account | wms_account | +| account_platform_active | app/model/account_platform_active.js | account_platform_active | wms_account_platform_active | +| account_store_employee | app/model/account_store_employee.js | wms_account_store_employee | wms_account_store_employee | +| api_app | app/model/api_app.js | api_app | wms_api_app | +| employee_role | app/model/employee_role.js | employee_role | wms_employee_role | +| entry_items | app/model/entry_items.js | wms_entry_items | wms_entry_items | +| entry_order | app/model/entry_order.js | wms_entry_order | wms_entry_order | +| fast_where | app/model/fast_where.js | fast_where | wms_fast_where | +| file | app/model/file.js | wms_file | wms_file | +| file_reference | app/model/file_reference.js | wms_file_reference | wms_file_reference | +| i18n_key | app/model/i18n_key.js | wms_i18n_key | wms_i18n_keys | +| i18n_translation | app/model/i18n_translation.js | wms_i18n_translation | wms_i18n_translations | +| interface_type | app/model/interface_type.js | interface_type | wms_interface_type | +| location_space | app/model/location_space.js | wms_location_space | wms_location_space | +| location_type | app/model/location_type.js | location_type | wms_location_type | +| location_zone | app/model/location_zone.js | wms_location_zone | wms_location_zone | +| operation_log | app/model/operation_log.js | operation_log | wms_operation_log | +| order_delivery | app/model/order_delivery.js | order_delivery | wms_order_delivery | +| order_delivery_factory | app/model/order_delivery_factory.js | - | - | +| order_items | app/model/order_items.js | wms_order_items | wms_order_items | +| order_items_factory | app/model/order_items_factory.js | - | - | +| permission | app/model/permission.js | permission | wms_permission | +| platform | app/model/platform.js | platform | wms_platform | +| platform_setting | app/model/platform_setting.js | platform_setting | wms_platfrom_setting | +| print_computer | app/model/print_computer.js | print_computer | wms_print_computer | +| print_item | app/model/print_item.js | print_item | wms_print_items | +| print_record | app/model/print_record.js | PrintRecord | wms_print_record | +| print_station_express | app/model/print_station_express.js | print_station_express | wms_print_station_express | +| print_stations | app/model/print_stations.js | print_stations | wms_print_stations | +| print_template | app/model/print_template.js | print_template | wms_print_template | +| prohibited_type | app/model/prohibited_type.js | prohibitedType | wms_prohibited_type | +| qimen_app | app/model/qimen_app.js | qimen_app | wms_qimen_apps | +| qimen_log | app/model/qimen_log.js | qimen_log | wms_qimen_log | +| receiving | app/model/receiving.js | wms_receiving | wms_receiving | +| receiving_detail | app/model/receiving_detail.js | wms_receiving_detail | wms_receiving_detail | +| role | app/model/role.js | role | wms_role | +| role_permission | app/model/role_permission.js | role_permission | wms_role_permission | +| stock_barcode | app/model/stock_barcode.js | stock_barcodes | wms_stock_barcodes | +| stock_store | app/model/stock_store.js | stock_store | wms_stock_store | +| stock_unit | app/model/stock_unit.js | wms_stock_unit | wms_stock_unit | +| stock_warehouse | app/model/stock_warehouse.js | stock_warehouse | wms_stock_warehouse | +| storage | app/model/storage.js | wms_storage | wms_storage | +| store | app/model/store.js | store | wms_store | +| store_join | app/model/store_join.js | StoreJoin | wms_store_join | +| store_warehouse | app/model/store_warehouse.js | store_warehouse | wms_store_warehouse | diff --git a/script/method-output-regression.cjs b/script/method-output-regression.cjs new file mode 100644 index 0000000..95ce65c --- /dev/null +++ b/script/method-output-regression.cjs @@ -0,0 +1,427 @@ +const fs = require('fs'); +const path = require('path'); +const mysql = require('mysql2/promise'); + +const ROOT = process.cwd(); +const OUTPUT_DIR = path.join(ROOT, 'temp', 'method-output'); +const LEGACY_RUN_DIR = path.join(ROOT, 'run'); +const BASELINE_FILE = path.join(OUTPUT_DIR, 'method-output-baseline.json'); +const BASELINE_SUMMARY = path.join(OUTPUT_DIR, 'method-output-baseline.md'); +const COMPARE_FILE = path.join(OUTPUT_DIR, 'method-output-compare.json'); +const LEGACY_BASELINE_FILE = path.join(LEGACY_RUN_DIR, 'method-output-baseline.json'); + +const MODE = (process.argv[2] || 'baseline').toLowerCase(); +const LIMIT = Number(process.argv[3] || 8); +const TEST_USERNAME = process.env.WMS_TEST_USER || 'liufumingren'; +const TEST_PASSWORD = process.env.WMS_TEST_PASS || '111111'; + +const READONLY_HINT = /(get|list|query|detail|info|stats|tree|search|load)/i; +const MUTATION_HINT = /(create|update|delete|remove|audit|confirm|complete|add|sync|synchronize|upload|assign|change|logout|login)/i; +const VOLATILE_KEYS = new Set([ + 'timestamp', + 'token', + 'last_login_at', + 'updated_at', + 'update_at', + 'created_at', + 'create_at', + 'login_time', + 'iat', + 'exp', +]); + +function ensureOutputDir() { + if (!fs.existsSync(OUTPUT_DIR)) { + fs.mkdirSync(OUTPUT_DIR, { recursive: true }); + } +} + +function resolveBaselineFile() { + if (fs.existsSync(BASELINE_FILE)) return BASELINE_FILE; + if (fs.existsSync(LEGACY_BASELINE_FILE)) return LEGACY_BASELINE_FILE; + return BASELINE_FILE; +} + +function readLocalConfig() { + const localCfgFactory = require(path.join(ROOT, 'config', 'config.local.js')); + const cfg = localCfgFactory({ name: 'wms' }); + return cfg; +} + +function buildBaseUrl(cfg) { + const host = cfg.cluster?.listen?.hostname && cfg.cluster.listen.hostname !== '0.0.0.0' + ? cfg.cluster.listen.hostname + : '127.0.0.1'; + const port = cfg.cluster?.listen?.port || 6060; + return `http://${host}:${port}`; +} + +function loadSystemMethodDocs() { + const file = path.join(ROOT, 'methods', 'system.json'); + const raw = fs.readFileSync(file, 'utf8'); + const json = JSON.parse(raw); + const map = new Map(); + const groups = json?.methods?.groups || []; + for (const group of groups) { + for (const item of group.list || []) { + map.set(item.method, { + groupName: group.groupName, + module: group.module, + description: item.description, + isNeedAuth: !!item.isNeedAuth, + isNeedLogin: !!item.isNeedLogin, + params: (item.params || []).map(p => ({ + name: p.name, + type: p.type, + required: !!p.required, + source: p.source, + description: p.description, + })), + }); + } + } + return map; +} + +function safeJsonParse(text, fallback = null) { + if (!text || typeof text !== 'string') return fallback; + try { + return JSON.parse(text); + } catch { + return fallback; + } +} + +function normalizeValue(value) { + if (value === null || value === undefined) return value; + if (Array.isArray(value)) return value.map(item => normalizeValue(item)); + if (typeof value !== 'object') return value; + + const out = {}; + for (const key of Object.keys(value)) { + if (VOLATILE_KEYS.has(key)) { + out[key] = '__VOLATILE__'; + continue; + } + out[key] = normalizeValue(value[key]); + } + return out; +} + +function stableStringify(obj) { + return JSON.stringify(obj); +} + +function pickPlatform(headers, rowDevice) { + const fromHeaders = String(headers?.platform || '').trim().toLowerCase(); + if (fromHeaders) return fromHeaders; + const fromDevice = String(rowDevice || '').trim().toLowerCase(); + if (fromDevice === 'desktop') return 'web'; + if (fromDevice) return fromDevice; + return 'web'; +} + +function pickProject(headers) { + const project = String(headers?.project || '').trim().toLowerCase(); + if (!project) return 'wms'; + if (project === 'all') return 'wms'; + return project; +} + +async function createDbConnection(cfg) { + const db = cfg.mysql.clients.wms; + return mysql.createConnection({ + host: db.host, + port: Number(db.port), + user: db.user, + password: db.password, + database: db.database, + }); +} + +async function loadRecentSystemLogCases(conn, methodDocs, limit, username) { + const [rows] = await conn.query(` + SELECT id, method, body, headers, auth, device, result, created_at + FROM wms_system_log + WHERE method IS NOT NULL + AND method <> '' + AND body IS NOT NULL + AND body <> '' + ORDER BY id DESC + LIMIT 1200 + `); + + const preferred = []; + const fallback = []; + const seen = new Set(); + + for (const row of rows) { + if (!methodDocs.has(row.method)) continue; + if (row.method === 'user.login' || row.method === 'user.logout' || row.method === 'user.changeRole') continue; + + const body = safeJsonParse(row.body, null); + if (!body || typeof body !== 'object') continue; + + const signature = `${row.method}::${JSON.stringify(body)}`; + if (seen.has(signature)) continue; + seen.add(signature); + + const headers = safeJsonParse(row.headers, {}); + const auth = safeJsonParse(row.auth, {}); + const fromUser = String(auth?.username || '').trim().toLowerCase() === String(username || '').trim().toLowerCase(); + const methodLooksReadOnly = READONLY_HINT.test(row.method) && !MUTATION_HINT.test(row.method); + const historySuccess = typeof row.result === 'string' && row.result.includes('"status":200'); + + const item = { + source: 'wms_system_log', + sourceId: row.id, + sourceCreatedAt: row.created_at, + method: row.method, + body, + headers: { + platform: pickPlatform(headers, row.device), + project: pickProject(headers), + }, + fromUser, + readOnlyHint: methodLooksReadOnly, + historySuccess, + }; + + if (fromUser && methodLooksReadOnly && historySuccess) preferred.push(item); + else if (fromUser && methodLooksReadOnly) preferred.push(item); + else if (methodLooksReadOnly) fallback.push(item); + + if (preferred.length >= limit * 2) break; + } + + const result = []; + const methodSeen = new Set(); + + for (const item of preferred) { + if (result.length >= limit) break; + if (methodSeen.has(item.method)) continue; + result.push(item); + methodSeen.add(item.method); + } + + for (const item of preferred) { + if (result.length >= limit) break; + result.push(item); + } + + for (const item of fallback) { + if (result.length >= limit) break; + if (methodSeen.has(item.method)) continue; + result.push(item); + methodSeen.add(item.method); + } + + for (const item of fallback) { + if (result.length >= limit) break; + result.push(item); + } + + return result; +} + +async function callSystemMethod(baseUrl, method, body, headers, token) { + const ts = Math.floor(Date.now() / 1000); + const url = `${baseUrl}/system?method=${encodeURIComponent(method)}&v=1×tamp=${ts}`; + + const reqHeaders = { + platform: headers.platform || 'web', + project: headers.project || 'wms', + 'content-type': 'application/json', + }; + if (token) { + reqHeaders.authorization = `Bearer ${token}`; + } + + const resp = await fetch(url, { + method: 'POST', + headers: reqHeaders, + body: JSON.stringify(body || {}), + }); + + const text = await resp.text(); + const data = safeJsonParse(text, { __raw_text__: text }); + return { + httpStatus: resp.status, + response: data, + normalized: normalizeValue(data), + }; +} + +function extractToken(loginResponse) { + const direct = loginResponse?.response?.data?.token; + if (typeof direct === 'string' && direct.length > 10) return direct; + return ''; +} + +function renderBaselineMarkdown(baseline) { + let md = ''; + md += '# method-output-baseline\n\n'; + md += `GeneratedAt: ${baseline.generatedAt}\n`; + md += `BaseUrl: ${baseline.baseUrl}\n`; + md += `User: ${baseline.user}\n`; + md += `CaseCount: ${baseline.cases.length}\n\n`; + md += '| method | source | sourceId | status | group | note |\n'; + md += '| --- | --- | --- | --- | --- | --- |\n'; + for (const c of baseline.cases) { + md += `| ${c.method} | ${c.source} | ${c.sourceId} | ${c.httpStatus} | ${c.doc?.groupName || ''} | ${c.doc?.description || ''} |\n`; + } + md += '\n'; + return md; +} + +async function runBaseline() { + const cfg = readLocalConfig(); + const baseUrl = buildBaseUrl(cfg); + const methodDocs = loadSystemMethodDocs(); + const conn = await createDbConnection(cfg); + + try { + const selected = await loadRecentSystemLogCases(conn, methodDocs, LIMIT, TEST_USERNAME); + if (!selected.length) { + throw new Error('未从 wms_system_log 找到可回放的只读 method 样本'); + } + + const login = await callSystemMethod( + baseUrl, + 'user.login', + { username: TEST_USERNAME, password: TEST_PASSWORD }, + { platform: 'web', project: 'wms' }, + '' + ); + const token = extractToken(login); + if (!token) { + throw new Error('登录成功但未拿到 token,请检查 user.login 返回结构'); + } + + const cases = []; + for (const item of selected) { + const call = await callSystemMethod(baseUrl, item.method, item.body, item.headers, token); + cases.push({ + method: item.method, + source: item.source, + sourceId: item.sourceId, + sourceCreatedAt: item.sourceCreatedAt, + headers: item.headers, + requestBody: item.body, + doc: methodDocs.get(item.method) || null, + httpStatus: call.httpStatus, + response: call.response, + normalized: call.normalized, + }); + } + + const baseline = { + generatedAt: new Date().toISOString(), + baseUrl, + user: TEST_USERNAME, + note: 'Before-change baseline generated from recent system logs and methods/system.json', + login: { + httpStatus: login.httpStatus, + normalized: login.normalized, + }, + cases, + }; + + ensureOutputDir(); + fs.writeFileSync(BASELINE_FILE, JSON.stringify(baseline, null, 2), 'utf8'); + fs.writeFileSync(BASELINE_SUMMARY, renderBaselineMarkdown(baseline), 'utf8'); + + console.log(`BASELINE_OK cases=${cases.length}`); + console.log(`BASELINE_FILE ${BASELINE_FILE}`); + console.log(`BASELINE_SUMMARY ${BASELINE_SUMMARY}`); + } finally { + await conn.end(); + } +} + +async function runCompare() { + const baselineFile = resolveBaselineFile(); + if (!fs.existsSync(baselineFile)) { + throw new Error(`baseline 文件不存在: ${BASELINE_FILE}`); + } + + const baseline = JSON.parse(fs.readFileSync(baselineFile, 'utf8')); + const cfg = readLocalConfig(); + const baseUrl = buildBaseUrl(cfg); + + const login = await callSystemMethod( + baseUrl, + 'user.login', + { username: TEST_USERNAME, password: TEST_PASSWORD }, + { platform: 'web', project: 'wms' }, + '' + ); + const token = extractToken(login); + if (!token) { + throw new Error('compare 阶段登录后未拿到 token'); + } + + const compared = []; + let mismatchCount = 0; + + for (const item of baseline.cases || []) { + const call = await callSystemMethod( + baseUrl, + item.method, + item.requestBody, + item.headers || { platform: 'web', project: 'wms' }, + token + ); + + const beforeNorm = item.normalized; + const afterNorm = call.normalized; + const same = stableStringify(beforeNorm) === stableStringify(afterNorm); + if (!same) mismatchCount++; + + compared.push({ + method: item.method, + sourceId: item.sourceId, + httpStatusBefore: item.httpStatus, + httpStatusAfter: call.httpStatus, + outputEqual: same, + beforeNormalized: beforeNorm, + afterNormalized: afterNorm, + }); + } + + const report = { + comparedAt: new Date().toISOString(), + baseUrl, + user: TEST_USERNAME, + baselineFile, + total: compared.length, + mismatchCount, + pass: mismatchCount === 0, + items: compared, + }; + + ensureOutputDir(); + fs.writeFileSync(COMPARE_FILE, JSON.stringify(report, null, 2), 'utf8'); + + console.log(`COMPARE_DONE total=${report.total} mismatch=${report.mismatchCount}`); + console.log(`COMPARE_FILE ${COMPARE_FILE}`); + if (report.mismatchCount > 0) { + process.exitCode = 1; + } +} + +async function main() { + if (MODE !== 'baseline' && MODE !== 'compare') { + throw new Error('用法: node script/method-output-regression.cjs [limit]'); + } + if (MODE === 'baseline') { + await runBaseline(); + } else { + await runCompare(); + } +} + +main().catch(err => { + console.error(err); + process.exit(1); +}); diff --git a/script/redis-cache.ps1 b/script/redis-cache.ps1 new file mode 100644 index 0000000..074be15 --- /dev/null +++ b/script/redis-cache.ps1 @@ -0,0 +1,254 @@ +param( + [Parameter(Mandatory = $true)] + [ValidateSet('get', 'set', 'del', 'exists', 'ttl', 'expire', 'keys', 'hget', 'hset', 'hdel', 'hgetall', 'incr', 'decr')] + [string]$Action, + + [Parameter(Mandatory = $false)] + [string]$RedisClient = 'cache', + + [Parameter(Mandatory = $false)] + [string]$Key, + + [Parameter(Mandatory = $false)] + [string]$Value, + + [Parameter(Mandatory = $false)] + [string]$Field, + + [Parameter(Mandatory = $false)] + [int]$ExpireSeconds, + + [Parameter(Mandatory = $false)] + [string]$Pattern = '*', + + [Parameter(Mandatory = $false)] + [string]$ConfigPath = '.\\config\\config.local.js', + + [switch]$AsTable +) + +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' + +$scriptRoot = Split-Path -Parent $MyInvocation.MyCommand.Path +$projectRoot = Split-Path -Parent $scriptRoot +$configFullPath = Join-Path $projectRoot $ConfigPath +$configResolved = Resolve-Path -Path $configFullPath -ErrorAction Stop + +$nodeScript = @' +const path = require("path"); +const { createRequire } = require("module"); + +(async () => { + const payloadBase64 = process.argv[2]; + if (!payloadBase64) { + throw new Error("Missing payload."); + } + + const payload = JSON.parse(Buffer.from(payloadBase64, "base64").toString("utf8")); + const { + projectRoot, + configPath, + clientName, + action, + key, + value, + field, + expireSeconds, + pattern, + } = payload; + + const normalizedAction = String(action || "").toLowerCase(); + const projectRequire = createRequire(path.join(projectRoot, "package.json")); + const Redis = projectRequire("ioredis"); + + const configFactory = require(path.resolve(configPath)); + const config = typeof configFactory === "function" + ? configFactory({ name: "wms-debug" }) + : configFactory; + + const redisConfig = config && config.redis; + const client = redisConfig && redisConfig.clients && redisConfig.clients[clientName] + ? redisConfig.clients[clientName] + : redisConfig && redisConfig.client; + + if (!client) { + throw new Error(`Redis client "${clientName}" not found in config.redis.clients.`); + } + + const redis = new Redis({ + host: client.host, + port: Number(client.port || 6379), + password: client.password, + db: Number(client.db || 0), + keyPrefix: client.keyPrefix || "", + connectTimeout: Number(client.connectTimeout || 10000), + lazyConnect: false, + enableReadyCheck: true, + }); + + const ensureKey = () => { + if (!key) { + throw new Error(`Action "${normalizedAction}" requires -Key.`); + } + }; + + const ensureField = () => { + if (!field) { + throw new Error(`Action "${normalizedAction}" requires -Field.`); + } + }; + + const scanKeys = async (matchPattern) => { + let cursor = "0"; + const result = []; + do { + const reply = await redis.scan(cursor, "MATCH", matchPattern, "COUNT", 200); + cursor = reply[0]; + result.push(...reply[1]); + } while (cursor !== "0"); + return result; + }; + + try { + let result; + switch (normalizedAction) { + case "get": + ensureKey(); + result = await redis.get(key); + break; + case "set": + ensureKey(); + if (value === undefined || value === null) { + throw new Error('Action "set" requires -Value.'); + } + if (Number.isInteger(expireSeconds) && expireSeconds > 0) { + result = await redis.set(key, String(value), "EX", expireSeconds); + } else { + result = await redis.set(key, String(value)); + } + break; + case "del": + ensureKey(); + result = await redis.del(key); + break; + case "exists": + ensureKey(); + result = await redis.exists(key); + break; + case "ttl": + ensureKey(); + result = await redis.ttl(key); + break; + case "expire": + ensureKey(); + if (!Number.isInteger(expireSeconds) || expireSeconds <= 0) { + throw new Error('Action "expire" requires -ExpireSeconds > 0.'); + } + result = await redis.expire(key, expireSeconds); + break; + case "keys": + result = await scanKeys(pattern || "*"); + break; + case "hget": + ensureKey(); + ensureField(); + result = await redis.hget(key, field); + break; + case "hset": + ensureKey(); + ensureField(); + if (value === undefined || value === null) { + throw new Error('Action "hset" requires -Value.'); + } + result = await redis.hset(key, field, String(value)); + break; + case "hdel": + ensureKey(); + ensureField(); + result = await redis.hdel(key, field); + break; + case "hgetall": + ensureKey(); + result = await redis.hgetall(key); + break; + case "incr": + ensureKey(); + result = await redis.incrby(key, Number.parseInt(value || "1", 10)); + break; + case "decr": + ensureKey(); + result = await redis.decrby(key, Number.parseInt(value || "1", 10)); + break; + default: + throw new Error(`Unsupported action: ${normalizedAction}`); + } + + process.stdout.write(JSON.stringify({ + client: clientName, + action: normalizedAction, + key: key || null, + field: field || null, + pattern: normalizedAction === "keys" ? (pattern || "*") : null, + expireSeconds: Number.isInteger(expireSeconds) ? expireSeconds : null, + result, + })); + } finally { + redis.disconnect(); + } +})().catch((err) => { + process.stderr.write(err && err.stack ? err.stack : String(err)); + process.exit(1); +}); +'@ + +$payload = @{ + projectRoot = $projectRoot + configPath = $configResolved.Path + clientName = $RedisClient + action = $Action + key = $Key + value = $Value + field = $Field + expireSeconds = $ExpireSeconds + pattern = $Pattern +} | ConvertTo-Json -Compress + +$payloadBytes = [System.Text.Encoding]::UTF8.GetBytes($payload) +$payloadBase64 = [System.Convert]::ToBase64String($payloadBytes) + +$tempFile = New-TemporaryFile +$tempNodeFile = [System.IO.Path]::ChangeExtension($tempFile.FullName, '.cjs') +Move-Item -Path $tempFile.FullName -Destination $tempNodeFile -Force +Set-Content -Path $tempNodeFile -Value $nodeScript -Encoding UTF8 + +try { + $json = & node $tempNodeFile $payloadBase64 + if ($LASTEXITCODE -ne 0) { + throw "Node redis runner exited with code $LASTEXITCODE." + } +} finally { + Remove-Item -Path $tempNodeFile -ErrorAction SilentlyContinue +} + +$result = $json | ConvertFrom-Json +Write-Host "Client: $($result.client)" +Write-Host "Action: $($result.action)" + +if ($AsTable) { + if ($result.result -is [System.Array]) { + if ($result.result.Count -gt 0) { + $result.result | ForEach-Object { [PSCustomObject]@{ value = $_ } } | Format-Table -AutoSize + } else { + Write-Host 'No rows.' + } + } elseif ($result.result -is [PSCustomObject]) { + $result.result.psobject.Properties | ForEach-Object { + [PSCustomObject]@{ key = $_.Name; value = $_.Value } + } | Format-Table -AutoSize + } else { + Write-Host "Result: $($result.result)" + } +} else { + $result | ConvertTo-Json -Depth 20 +} diff --git a/script/tmp-compare-order-schema.cjs b/script/tmp-compare-order-schema.cjs index 9bba2f3..5ff47e5 100644 --- a/script/tmp-compare-order-schema.cjs +++ b/script/tmp-compare-order-schema.cjs @@ -75,6 +75,8 @@ function extractDefineFields(text) { async function main() { const root = process.cwd(); + const tempDir = path.join(root, 'temp'); + if (!fs.existsSync(tempDir)) fs.mkdirSync(tempDir, { recursive: true }); const projectRequire = createRequire(path.join(root, 'package.json')); const mysql = projectRequire('mysql2/promise'); const cfgFactory = require(path.join(root, 'config', 'config.local.js')); @@ -160,9 +162,9 @@ async function main() { schema: tableSchemas, }; - fs.writeFileSync(path.join(root, 'tmp-order-schema-compare.json'), JSON.stringify(out, null, 2)); + fs.writeFileSync(path.join(tempDir, 'tmp-order-schema-compare.json'), JSON.stringify(out, null, 2)); await conn.end(); - console.log('WROTE tmp-order-schema-compare.json'); + console.log('WROTE temp/tmp-order-schema-compare.json'); } main().catch(err => { diff --git a/script/tmp-gen-service-method-inventory.cjs b/script/tmp-gen-service-method-inventory.cjs index cf3f692..dde9654 100644 --- a/script/tmp-gen-service-method-inventory.cjs +++ b/script/tmp-gen-service-method-inventory.cjs @@ -2,6 +2,7 @@ const path = require('path'); const root = process.cwd(); +const tempDir = path.join(root, 'temp'); const serviceRoot = path.join(root, 'app', 'service'); function walk(dir) { @@ -93,5 +94,6 @@ for (const item of inventory) { } } -fs.writeFileSync(path.join(root, 'tmp-service-method-inventory.md'), md, 'utf8'); -console.log('WROTE tmp-service-method-inventory.md'); +if (!fs.existsSync(tempDir)) fs.mkdirSync(tempDir, { recursive: true }); +fs.writeFileSync(path.join(tempDir, 'tmp-service-method-inventory.md'), md, 'utf8'); +console.log('WROTE temp/tmp-service-method-inventory.md'); diff --git a/script/tmp-generate-method-regression-test.cjs b/script/tmp-generate-method-regression-test.cjs new file mode 100644 index 0000000..9655cf7 --- /dev/null +++ b/script/tmp-generate-method-regression-test.cjs @@ -0,0 +1,116 @@ +const fs = require('fs'); +const path = require('path'); + +const root = process.cwd(); +const defaultBaselinePath = path.join(root, 'temp', 'method-output', 'method-output-baseline.json'); +const defaultTargetPath = path.join(root, 'temp', 'generated-tests', 'system.method-output.generated.test.js'); +const legacyBaselinePath = path.join(root, 'run', 'method-output-baseline.json'); +let baselinePath = process.argv[2] + ? path.resolve(process.argv[2]) + : defaultBaselinePath; +const targetPath = process.argv[3] + ? path.resolve(process.argv[3]) + : defaultTargetPath; + +if (!process.argv[2] && !fs.existsSync(baselinePath) && fs.existsSync(legacyBaselinePath)) { + baselinePath = legacyBaselinePath; +} + +const supportClientPath = path.relative( + path.dirname(targetPath), + path.join(root, 'test', 'support', 'system_method_client') +).replace(/\\/g, '/'); +const supportRequirePath = supportClientPath.startsWith('.') ? supportClientPath : `./${supportClientPath}`; +const describePath = path.relative(root, targetPath).replace(/\\/g, '/'); + +if (!fs.existsSync(baselinePath)) { + console.error(`Baseline not found: ${baselinePath}`); + process.exit(1); +} + +const baseline = JSON.parse(fs.readFileSync(baselinePath, 'utf8')); +const cases = Array.isArray(baseline.cases) ? baseline.cases : []; + +const header = `// @eggjs-test-generated +// @purpose 接口返回数据一致性校验(自动生成,请勿手改) +// @source ${path.relative(root, baselinePath).replace(/\\/g, '/')} +// @generatedAt ${new Date().toISOString()} +'use strict'; + +const assert = require('node:assert/strict'); +const { + getAuthToken, + invokeSystemMethod, +} = require('${supportRequirePath}'); + +const VOLATILE_KEYS = new Set([ + 'timestamp', + 'token', + 'last_login_at', + 'updated_at', + 'update_at', + 'created_at', + 'create_at', + 'login_time', + 'iat', + 'exp', +]); + +function normalize(value) { + if (value === null || value === undefined) return value; + if (Array.isArray(value)) return value.map(item => normalize(item)); + if (typeof value !== 'object') return value; + const out = {}; + for (const key of Object.keys(value)) { + if (VOLATILE_KEYS.has(key)) { + out[key] = '__VOLATILE__'; + continue; + } + out[key] = normalize(value[key]); + } + return out; +} + +describe(${JSON.stringify(describePath)}, () => { + let token = ''; + + before(async () => { + const auth = await getAuthToken(); + token = auth.token; + assert.ok(token, 'token should be available'); + }); +`; + +const body = cases.map((item, idx) => { + const title = `[${idx + 1}] ${item.method} (sourceId=${item.sourceId})`; + const requestBody = JSON.stringify(item.requestBody || {}, null, 2); + const expected = JSON.stringify(item.normalized || {}, null, 2); + const platform = JSON.stringify((item.headers && item.headers.platform) || 'web'); + const project = JSON.stringify((item.headers && item.headers.project) || 'wms'); + + return ` + it(${JSON.stringify(title)}, async () => { + const res = await invokeSystemMethod( + ${JSON.stringify(item.method)}, + ${requestBody}, + token, + { platform: ${platform}, project: ${project} } + ); + + assert.equal(res.status, ${Number(item.httpStatus || 200)}); + const normalized = normalize(res.body); + const expected = ${expected}; + assert.deepEqual(normalized, expected); + }); +`; +}).join('\n'); + +const footer = ` +}); +`; + +fs.mkdirSync(path.dirname(targetPath), { recursive: true }); +fs.writeFileSync(targetPath, header + body + footer, 'utf8'); + +console.log(`GENERATED ${targetPath}`); +console.log(`CASE_COUNT ${cases.length}`); diff --git a/script/tmp-update-ai-method-routing.cjs b/script/tmp-update-ai-method-routing.cjs index b05fc89..aee37fc 100644 --- a/script/tmp-update-ai-method-routing.cjs +++ b/script/tmp-update-ai-method-routing.cjs @@ -3,12 +3,12 @@ const path = require('path'); const root = process.cwd(); const target = path.join(root, 'AI_METHOD_ROUTING.md'); -const inventoryPath = path.join(root, 'tmp-service-method-inventory.md'); +const inventoryPath = path.join(root, 'temp', 'tmp-service-method-inventory.md'); const base = fs.readFileSync(target, 'utf8'); const inventory = fs.readFileSync(inventoryPath, 'utf8').trim(); -const section = `\n\n## 6. 全量 Service Method 能力清单(自动扫描)\n\n维护说明:\n- 扫描范围:app/service/**/*.js\n- 本节内容由脚本生成,新增/修改 service 后请同步刷新。\n- 刷新命令:node .\\script\\tmp-gen-service-method-inventory.cjs\n\n\n${inventory}\n\n`; +const section = `\n\n## 6. 全量 Service Method 能力清单(自动扫描)\n\n维护说明:\n- 扫描范围:app/service/**/*.js\n- 本节内容由脚本生成,新增/修改 service 后请同步刷新。\n- 刷新命令:node .\\script\\tmp-gen-service-method-inventory.cjs\n- 临时清单输出:temp/tmp-service-method-inventory.md\n\n\n${inventory}\n\n`; const begin = ''; const end = ''; diff --git a/table_schema_inventory.md b/table_schema_inventory.md new file mode 100644 index 0000000..9d9fe42 --- /dev/null +++ b/table_schema_inventory.md @@ -0,0 +1,85 @@ +# table_schema_inventory + +Updated: 2026-03-22 +Database: wms +Object count: 70 + +## Summary + +- Tables: 68 +- Views: 2 + +## Objects + +| object | type | engine | collation | rows | columns | pk_cols | auto_inc | index_count | +| --- | --- | --- | --- | ---: | ---: | ---: | ---: | ---: | +| SequelizeMeta | TABLE | InnoDB | utf8_unicode_ci | 7 | 1 | 1 | 0 | 2 | +| vw_warehouse_quota | VIEW | - | - | - | 5 | 0 | 0 | 0 | +| v_pick_space | VIEW | - | - | - | 44 | 0 | 0 | 0 | +| wms_account | TABLE | InnoDB | utf8mb4_general_ci | 2 | 13 | 1 | 1 | 5 | +| wms_account_login_log | TABLE | InnoDB | utf8mb4_general_ci | 108 | 7 | 1 | 1 | 2 | +| wms_account_platform_active | TABLE | InnoDB | utf8mb4_general_ci | 3 | 5 | 2 | 0 | 5 | +| wms_account_store_employee | TABLE | InnoDB | utf8mb4_general_ci | 5 | 8 | 1 | 1 | 5 | +| wms_api_app | TABLE | InnoDB | utf8mb4_unicode_ci | 4 | 22 | 1 | 1 | 6 | +| wms_api_log | TABLE | InnoDB | utf8mb4_general_ci | 421 | 10 | 1 | 1 | 1 | +| wms_embargo_policies | TABLE | InnoDB | utf8mb4_unicode_ci | 0 | 13 | 1 | 1 | 5 | +| wms_employee_role | TABLE | InnoDB | utf8mb4_general_ci | 4 | 3 | 1 | 1 | 4 | +| wms_entry_items | TABLE | InnoDB | utf8mb4_general_ci | 2 | 12 | 1 | 1 | 3 | +| wms_entry_order | TABLE | InnoDB | utf8mb4_unicode_ci | 5 | 28 | 1 | 1 | 10 | +| wms_express | TABLE | InnoDB | utf8mb4_general_ci | 0 | 2 | 1 | 0 | 1 | +| wms_express_print_record | TABLE | InnoDB | utf8mb4_general_ci | 0 | 31 | 1 | 1 | 13 | +| wms_express_setting | TABLE | InnoDB | utf8mb4_general_ci | 0 | 4 | 1 | 1 | 3 | +| wms_fast_where | TABLE | InnoDB | utf8mb4_general_ci | 38 | 9 | 1 | 1 | 1 | +| wms_file | TABLE | InnoDB | utf8mb4_unicode_ci | 5806 | 20 | 1 | 1 | 8 | +| wms_file_reference | TABLE | InnoDB | utf8mb4_unicode_ci | 8299 | 8 | 1 | 1 | 5 | +| wms_i18n_keys | TABLE | InnoDB | utf8mb4_general_ci | 182 | 10 | 1 | 1 | 4 | +| wms_i18n_translations | TABLE | InnoDB | utf8mb4_general_ci | 421 | 11 | 1 | 1 | 5 | +| wms_interface_type | TABLE | InnoDB | utf8mb4_unicode_ci | 2 | 9 | 1 | 1 | 2 | +| wms_location_space | TABLE | InnoDB | utf8mb4_general_ci | 1898 | 38 | 1 | 1 | 13 | +| wms_location_type | TABLE | InnoDB | utf8mb4_general_ci | 5 | 10 | 1 | 1 | 3 | +| wms_location_zone | TABLE | InnoDB | utf8mb4_general_ci | 20 | 30 | 1 | 1 | 10 | +| wms_operation_log | TABLE | InnoDB | utf8mb4_general_ci | 2856 | 12 | 1 | 1 | 8 | +| wms_order_delivery | TABLE | InnoDB | utf8mb4_general_ci | 0 | 54 | 1 | 1 | 4 | +| wms_order_delivery_100000 | TABLE | InnoDB | utf8mb4_general_ci | 10 | 72 | 1 | 1 | 9 | +| wms_order_delivery_1000028 | TABLE | InnoDB | utf8mb4_general_ci | 0 | 72 | 1 | 1 | 9 | +| wms_order_express | TABLE | InnoDB | utf8mb4_general_ci | 0 | 13 | 1 | 1 | 2 | +| wms_order_express_print_data | TABLE | InnoDB | utf8mb4_general_ci | 0 | 6 | 1 | 1 | 2 | +| wms_order_items | TABLE | InnoDB | utf8mb4_general_ci | 0 | 15 | 1 | 1 | 2 | +| wms_order_items_100000 | TABLE | InnoDB | utf8mb4_unicode_ci | 11 | 18 | 1 | 1 | 9 | +| wms_order_items_1000028 | TABLE | InnoDB | utf8mb4_unicode_ci | 0 | 18 | 1 | 1 | 9 | +| wms_order_operation | TABLE | InnoDB | utf8mb4_general_ci | 0 | 1 | 1 | 1 | 1 | +| wms_order_operation_log | TABLE | InnoDB | utf8mb4_general_ci | 0 | 15 | 1 | 1 | 6 | +| wms_order_picking | TABLE | InnoDB | utf8mb4_general_ci | 0 | 1 | 1 | 1 | 1 | +| wms_permission | TABLE | InnoDB | utf8mb4_general_ci | 40 | 15 | 1 | 1 | 4 | +| wms_picking_strategy | TABLE | InnoDB | utf8mb4_unicode_ci | 0 | 25 | 1 | 1 | 3 | +| wms_platform | TABLE | InnoDB | utf8mb4_general_ci | 13 | 3 | 1 | 0 | 1 | +| wms_platform_print_config | TABLE | InnoDB | utf8mb4_general_ci | 7 | 12 | 1 | 1 | 3 | +| wms_platfrom_setting | TABLE | InnoDB | utf8mb4_general_ci | 0 | 4 | 1 | 1 | 4 | +| wms_printer_config | TABLE | InnoDB | utf8mb4_general_ci | 0 | 11 | 1 | 1 | 4 | +| wms_print_batch | TABLE | InnoDB | utf8mb4_general_ci | 0 | 16 | 1 | 1 | 6 | +| wms_print_computer | TABLE | InnoDB | utf8mb4_general_ci | 0 | 4 | 1 | 1 | 1 | +| wms_print_items | TABLE | InnoDB | utf8mb4_general_ci | 39 | 24 | 1 | 1 | 5 | +| wms_print_log | TABLE | InnoDB | utf8mb4_general_ci | 0 | 12 | 1 | 1 | 5 | +| wms_print_record | TABLE | InnoDB | utf8mb4_general_ci | 277 | 13 | 1 | 1 | 6 | +| wms_print_stations | TABLE | InnoDB | utf8mb4_unicode_ci | 3 | 11 | 1 | 1 | 7 | +| wms_print_station_express | TABLE | InnoDB | utf8mb4_unicode_ci | 0 | 10 | 1 | 1 | 5 | +| wms_print_template | TABLE | InnoDB | utf8mb4_general_ci | 4 | 15 | 1 | 1 | 4 | +| wms_prohibited_type | TABLE | InnoDB | utf8mb4_unicode_ci | 13 | 9 | 1 | 1 | 4 | +| wms_qimen_apps | TABLE | InnoDB | utf8mb4_general_ci | 27 | 4 | 1 | 1 | 2 | +| wms_qimen_log | TABLE | InnoDB | utf8mb4_general_ci | 27756 | 14 | 1 | 1 | 1 | +| wms_receiving | TABLE | InnoDB | utf8mb4_unicode_ci | 43 | 25 | 1 | 1 | 9 | +| wms_receiving_detail | TABLE | InnoDB | utf8mb4_unicode_ci | 38 | 26 | 1 | 1 | 8 | +| wms_role | TABLE | InnoDB | utf8mb4_general_ci | 5 | 13 | 1 | 1 | 6 | +| wms_role_permission | TABLE | InnoDB | utf8mb4_general_ci | 72 | 4 | 1 | 1 | 4 | +| wms_stock_barcodes | TABLE | InnoDB | utf8mb4_unicode_ci | 25992 | 6 | 1 | 1 | 3 | +| wms_stock_store | TABLE | InnoDB | utf8mb4_unicode_ci | 472 | 34 | 1 | 1 | 11 | +| wms_stock_unit | TABLE | InnoDB | utf8mb4_general_ci | 11 | 4 | 1 | 1 | 3 | +| wms_stock_warehouse | TABLE | InnoDB | utf8mb4_unicode_ci | 25718 | 41 | 1 | 1 | 6 | +| wms_storage | TABLE | InnoDB | utf8mb4_unicode_ci | 0 | 20 | 1 | 1 | 8 | +| wms_store | TABLE | InnoDB | utf8mb4_unicode_ci | 121 | 20 | 1 | 1 | 5 | +| wms_store_join | TABLE | InnoDB | utf8mb4_unicode_ci | 4 | 14 | 1 | 1 | 7 | +| wms_store_warehouse | TABLE | InnoDB | utf8mb4_general_ci | 119 | 21 | 1 | 1 | 8 | +| wms_system_config | TABLE | InnoDB | utf8mb4_general_ci | 1 | 5 | 1 | 1 | 1 | +| wms_system_log | TABLE | InnoDB | utf8mb4_general_ci | 4591 | 14 | 1 | 1 | 2 | +| wms_wave_batch | TABLE | InnoDB | utf8mb4_general_ci | 0 | 20 | 1 | 1 | 5 | +| wms_wave_operation_log | TABLE | InnoDB | utf8mb4_general_ci | 0 | 11 | 1 | 1 | 5 | diff --git a/test/app/controller/api_v2.test.js b/test/app/controller/api_v2.test.js deleted file mode 100644 index 89011df..0000000 --- a/test/app/controller/api_v2.test.js +++ /dev/null @@ -1,43 +0,0 @@ -const { strict: assert } = require('node:assert'); -const { app } = require('egg-mock/bootstrap'); - -describe('test/app/controller/api_v2.test.js', () => { - before(() => { - // avoid database or factory initialization during tests - app.model = {}; - }); - - it('dispatches a simple method and returns payload', async () => { - // mock dispatcher.invoke so we don't need real services or auth - app.mockService('dispatcher', 'invoke', async (method, data, auth, ctx) => { - // verify parameters arrived as expected - assert(method === 'index.fastWhereTree'); - assert.deepEqual(data, { type: 'example' }); - // return a fake successful response - return { isLog: true, result: { status: 200, data: { foo: 'bar', method } } }; - }); - - const res = await app.httpRequest() - .post('/api/v2?method=index.fastWhereTree&v=1.0&format=json×tamp=123') - .set('Content-Type', 'application/json') - .send({ type: 'example' }) - .expect(200); - - assert.deepEqual(res.body, { foo: 'bar', method: 'index.fastWhereTree' }); - }); - - it('returns 401 when dispatcher.invoke throws (simulating auth failure)', async () => { - // simulate auth failure by making invoke return unauthorized - app.mockService('dispatcher', 'invoke', async () => { - return { isLog: false, result: { status: 401, message: 'Unauthorized' } }; - }); - - const res = await app.httpRequest() - .post('/api/v2?method=index.fastWhereTree&v=1.0&format=json×tamp=123') - .set('Content-Type', 'application/json') - .send({}) - .expect(401); // controller forwards status from dispatcher - - assert(res.body && res.body.message === 'Unauthorized'); - }); -}); diff --git a/test/app/controller/home.test.js b/test/app/controller/home.test.js index ea43dbb..f178b9d 100644 --- a/test/app/controller/home.test.js +++ b/test/app/controller/home.test.js @@ -17,7 +17,7 @@ describe('test/app/controller/home.test.js', () => { it('should GET /', async () => { return app.httpRequest() .get('/') - .expect('hi, egg') + .expect('pong') .expect(200); }); }); diff --git a/test/app/controller/system.order.getreviewOrderlist.test.js b/test/app/controller/system.order.getreviewOrderlist.test.js new file mode 100644 index 0000000..82303fb --- /dev/null +++ b/test/app/controller/system.order.getreviewOrderlist.test.js @@ -0,0 +1,83 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const { + getAuthToken, + invokeSystemMethod, +} = require('../../support/system_method_client'); + +const EXTRA_HEADERS = { + platform: 'web', + project: 'all', +}; + +const FALLBACK_ROLE_IDS = [ 4, 6, 30 ]; + +async function switchToWarehouseRoleWithOrderData(token) { + let currentToken = token; + const infoRes = await invokeSystemMethod('user.info', {}, currentToken, EXTRA_HEADERS); + assert.equal(infoRes.status, 200); + assert.equal(infoRes.body.flag, 'success'); + assert.equal(infoRes.body.code, 200); + + const employees = Array.isArray(infoRes.body?.data?.employees) ? infoRes.body.data.employees : []; + const warehouseRoles = employees.filter(item => item && item.role_type === 'warehouse' && Number(item.id)); + const candidateRoleIds = [ ...new Set([ + ...warehouseRoles.map(item => Number(item.id)), + ...FALLBACK_ROLE_IDS, + ].filter(Boolean)) ]; + + assert.ok(candidateRoleIds.length > 0, '当前账号没有可尝试的仓库角色'); + + for (const roleId of candidateRoleIds) { + const changeRes = await invokeSystemMethod('user.changeRole', { + roleId, + }, currentToken, EXTRA_HEADERS); + + if (changeRes.status !== 200 || changeRes.body?.flag !== 'success' || changeRes.body?.code !== 200) { + continue; + } + + currentToken = changeRes.body?.data?.token || currentToken; + + const statsRes = await invokeSystemMethod('order.stats', { + where: {}, + }, currentToken, EXTRA_HEADERS); + + assert.equal(statsRes.status, 200); + assert.equal(statsRes.body.flag, 'success'); + assert.equal(statsRes.body.code, 200); + + const total = Number(statsRes.body?.data?.total || 0); + if (total > 0) { + return { + token: currentToken, + }; + } + } + + throw new Error('未找到有订单数据的仓库角色'); +} + +describe('test/app/controller/system.order.getreviewOrderlist.test.js', () => { + it('should call order.getreviewOrderlist with platform=web project=all', async () => { + const { token } = await getAuthToken(); + const switched = await switchToWarehouseRoleWithOrderData(token); + + const res = await invokeSystemMethod('order.getreviewOrderlist', { + pagination: { + page: 1, + pageSize: 10, + }, + where: {}, + }, switched.token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + assert.equal(res.body.code, 200); + assert.ok(res.body.data); + assert.ok(Array.isArray(res.body.data.list)); + assert.ok(res.body.data.pagination); + assert.equal(typeof res.body.data.pagination.total, 'number'); + }); +}); diff --git a/test/app/controller/system.order.namespaced.test.js b/test/app/controller/system.order.namespaced.test.js new file mode 100644 index 0000000..0822173 --- /dev/null +++ b/test/app/controller/system.order.namespaced.test.js @@ -0,0 +1,143 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const { + getAuthToken, + invokeSystemMethod, +} = require('../../support/system_method_client'); + +const EXTRA_HEADERS = { + platform: 'web', + project: 'all', +}; + +const ALLOWED_REVIEW_STATUS = new Set([ 'none', 'padding', 'running', 'fin', 'error' ]); +const FALLBACK_ROLE_IDS = [ 4, 6, 30 ]; + +async function switchToWarehouseRoleWithOrderData(token) { + let currentToken = token; + const infoRes = await invokeSystemMethod('user.info', {}, currentToken, EXTRA_HEADERS); + assert.equal(infoRes.status, 200); + assert.equal(infoRes.body.flag, 'success'); + assert.equal(infoRes.body.code, 200); + + const employees = Array.isArray(infoRes.body?.data?.employees) ? infoRes.body.data.employees : []; + const warehouseRoles = employees.filter(item => item && item.role_type === 'warehouse' && Number(item.id)); + const candidateRoleIds = [ ...new Set([ + ...warehouseRoles.map(item => Number(item.id)), + ...FALLBACK_ROLE_IDS, + ].filter(Boolean)) ]; + + assert.ok(candidateRoleIds.length > 0, '当前账号没有可尝试的仓库角色'); + + for (const roleId of candidateRoleIds) { + const changeRes = await invokeSystemMethod('user.changeRole', { + roleId, + }, currentToken, EXTRA_HEADERS); + + if (changeRes.status !== 200 || changeRes.body?.flag !== 'success' || changeRes.body?.code !== 200) { + continue; + } + + currentToken = changeRes.body?.data?.token || currentToken; + + const statsRes = await invokeSystemMethod('order.stats', { + where: {}, + }, currentToken, EXTRA_HEADERS); + + assert.equal(statsRes.status, 200); + assert.equal(statsRes.body.flag, 'success'); + assert.equal(statsRes.body.code, 200); + + const total = Number(statsRes.body?.data?.total || 0); + if (total > 0) { + return { + token: currentToken, + roleId, + total, + }; + } + } + + throw new Error('未找到有订单数据的仓库角色'); +} + +describe('test/app/controller/system.order.namespaced.test.js', () => { + it('should query all namespaced order lists', async () => { + const { token } = await getAuthToken(); + const switched = await switchToWarehouseRoleWithOrderData(token); + + const methods = [ + 'order.reviewOrder.getreviewOrderlist', + 'order.deliveryOrder.getdeliveryOrderlist', + 'order.pendingOrder.getpendingOrderlist', + 'order.expectionOrder.getexpectionOrderlist', + 'order.archiveOrder.getarchiveOrderlist', + ]; + + for (const method of methods) { + const res = await invokeSystemMethod(method, { + pagination: { + page: 1, + pageSize: 10, + }, + where: {}, + }, switched.token, EXTRA_HEADERS); + + assert.equal(res.status, 200, `${method} http status 异常`); + assert.equal(res.body.flag, 'success', `${method} flag 异常`); + assert.equal(res.body.code, 200, `${method} code 异常`); + assert.ok(res.body.data, `${method} 缺少 data`); + assert.ok(Array.isArray(res.body.data.list), `${method} list 不是数组`); + assert.ok(res.body.data.pagination, `${method} 缺少 pagination`); + assert.equal(typeof res.body.data.pagination.total, 'number', `${method} total 不是 number`); + } + }); + + it('should review order through namespaced method and restore status', async () => { + const { token } = await getAuthToken(); + const switched = await switchToWarehouseRoleWithOrderData(token); + + const listRes = await invokeSystemMethod('order.list', { + pagination: { + page: 1, + pageSize: 1, + }, + where: {}, + }, switched.token, EXTRA_HEADERS); + + assert.equal(listRes.status, 200); + assert.equal(listRes.body.flag, 'success'); + assert.equal(listRes.body.code, 200); + + const order = Array.isArray(listRes.body?.data?.list) ? listRes.body.data.list[0] : null; + assert.ok(order, '订单列表为空,无法测试目录化 reviewOrder'); + assert.ok(order.id, '订单缺少 id,无法测试目录化 reviewOrder'); + + const originalStatus = ALLOWED_REVIEW_STATUS.has(String(order.inspection_status || '')) + ? String(order.inspection_status) + : 'none'; + const targetStatus = originalStatus === 'fin' ? 'running' : 'fin'; + + const reviewRes = await invokeSystemMethod('order.reviewOrder.reviewOrder', { + id: Number(order.id), + review_status: targetStatus, + }, switched.token, EXTRA_HEADERS); + + assert.equal(reviewRes.status, 200); + assert.equal(reviewRes.body.flag, 'success'); + assert.equal(reviewRes.body.code, 200); + assert.equal(Number(reviewRes.body?.data?.id || 0), Number(order.id)); + assert.equal(reviewRes.body?.data?.inspection_status, targetStatus); + + const restoreRes = await invokeSystemMethod('order.reviewOrder.reviewOrder', { + id: Number(order.id), + review_status: originalStatus, + }, switched.token, EXTRA_HEADERS); + + assert.equal(restoreRes.status, 200); + assert.equal(restoreRes.body.flag, 'success'); + assert.equal(restoreRes.body.code, 200); + assert.equal(restoreRes.body?.data?.inspection_status, originalStatus); + }); +}); \ No newline at end of file diff --git a/test/app/controller/system.order.reviewOrder.test.js b/test/app/controller/system.order.reviewOrder.test.js new file mode 100644 index 0000000..b2222d1 --- /dev/null +++ b/test/app/controller/system.order.reviewOrder.test.js @@ -0,0 +1,112 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const { + getAuthToken, + invokeSystemMethod, +} = require('../../support/system_method_client'); + +const EXTRA_HEADERS = { + platform: 'web', + project: 'all', +}; + +const ALLOWED_REVIEW_STATUS = new Set([ 'none', 'padding', 'running', 'fin', 'error' ]); +const FALLBACK_ROLE_IDS = [ 4, 6, 30 ]; + +async function switchToWarehouseRoleWithOrderData(token) { + let currentToken = token; + const infoRes = await invokeSystemMethod('user.info', {}, currentToken, EXTRA_HEADERS); + assert.equal(infoRes.status, 200); + assert.equal(infoRes.body.flag, 'success'); + assert.equal(infoRes.body.code, 200); + + const employees = Array.isArray(infoRes.body?.data?.employees) ? infoRes.body.data.employees : []; + const warehouseRoles = employees.filter(item => item && item.role_type === 'warehouse' && Number(item.id)); + const candidateRoleIds = [ ...new Set([ + ...warehouseRoles.map(item => Number(item.id)), + ...FALLBACK_ROLE_IDS, + ].filter(Boolean)) ]; + + assert.ok(candidateRoleIds.length > 0, '当前账号没有可尝试的仓库角色'); + + for (const roleId of candidateRoleIds) { + const changeRes = await invokeSystemMethod('user.changeRole', { + roleId, + }, currentToken, EXTRA_HEADERS); + + if (changeRes.status !== 200 || changeRes.body?.flag !== 'success' || changeRes.body?.code !== 200) { + continue; + } + + currentToken = changeRes.body?.data?.token || currentToken; + + const statsRes = await invokeSystemMethod('order.stats', { + where: {}, + }, currentToken, EXTRA_HEADERS); + + assert.equal(statsRes.status, 200); + assert.equal(statsRes.body.flag, 'success'); + assert.equal(statsRes.body.code, 200); + + const total = Number(statsRes.body?.data?.total || 0); + if (total > 0) { + return { + token: currentToken, + roleId, + total, + }; + } + } + + throw new Error('未找到有订单数据的仓库角色'); +} + +describe('test/app/controller/system.order.reviewOrder.test.js', () => { + it('should review order and restore inspection status', async () => { + const { token } = await getAuthToken(); + const switched = await switchToWarehouseRoleWithOrderData(token); + + const listRes = await invokeSystemMethod('order.list', { + pagination: { + page: 1, + pageSize: 1, + }, + where: {}, + }, switched.token, EXTRA_HEADERS); + + assert.equal(listRes.status, 200); + assert.equal(listRes.body.flag, 'success'); + assert.equal(listRes.body.code, 200); + + const order = Array.isArray(listRes.body?.data?.list) ? listRes.body.data.list[0] : null; + assert.ok(order, '订单列表为空,无法测试 reviewOrder'); + assert.ok(order.id, '订单缺少 id,无法测试 reviewOrder'); + + const originalStatus = ALLOWED_REVIEW_STATUS.has(String(order.inspection_status || '')) + ? String(order.inspection_status) + : 'none'; + const targetStatus = originalStatus === 'fin' ? 'running' : 'fin'; + + const reviewRes = await invokeSystemMethod('order.reviewOrder', { + id: Number(order.id), + review_status: targetStatus, + }, switched.token, EXTRA_HEADERS); + + assert.equal(reviewRes.status, 200); + assert.equal(reviewRes.body.flag, 'success'); + assert.equal(reviewRes.body.code, 200); + assert.equal(Number(reviewRes.body?.data?.id || 0), Number(order.id)); + assert.equal(reviewRes.body?.data?.inspection_status, targetStatus); + + const restoreRes = await invokeSystemMethod('order.reviewOrder', { + id: Number(order.id), + review_status: originalStatus, + }, switched.token, EXTRA_HEADERS); + + assert.equal(restoreRes.status, 200); + assert.equal(restoreRes.body.flag, 'success'); + assert.equal(restoreRes.body.code, 200); + assert.equal(restoreRes.body?.data?.inspection_status, originalStatus); + }); +}); diff --git a/test/app/controller/system.user.changeRole.test.js b/test/app/controller/system.user.changeRole.test.js new file mode 100644 index 0000000..81084ce --- /dev/null +++ b/test/app/controller/system.user.changeRole.test.js @@ -0,0 +1,98 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const { + getAuthToken, + invokeSystemMethod, +} = require('../../support/system_method_client'); + +const RUNTIME_FILE = path.join(process.cwd(), 'test', '.runtime', 'system_user_change_role_web_all.json'); + +function saveRuntime(payload) { + fs.mkdirSync(path.dirname(RUNTIME_FILE), { recursive: true }); + fs.writeFileSync(RUNTIME_FILE, JSON.stringify(payload, null, 2), 'utf8'); +} + +describe('test/app/controller/system.user.changeRole.test.js', () => { + it('should switch role via user.changeRole and persist response', async () => { + const { token } = await getAuthToken(); + + const beforeInfoRes = await invokeSystemMethod('user.info', {}, token, { + platform: 'web', + project: 'all', + }); + + assert.equal(beforeInfoRes.status, 200); + assert.equal(beforeInfoRes.body.flag, 'success'); + assert.equal(beforeInfoRes.body.code, 200); + + const beforeData = beforeInfoRes.body.data || {}; + const employees = Array.isArray(beforeData.employees) ? beforeData.employees : []; + const currentRoleId = Number(beforeData.employees_id || 0); + const target = employees.find(item => Number(item.id) && Number(item.id) !== currentRoleId) + || employees.find(item => Number(item.id)); + + assert.ok(target, '当前账号没有可用于切换的角色'); + + const changeRoleRes = await invokeSystemMethod('user.changeRole', { + roleId: Number(target.id), + }, token, { + platform: 'web', + project: 'all', + }); + + assert.equal(changeRoleRes.status, 200); + assert.equal(changeRoleRes.body.flag, 'success'); + assert.equal(changeRoleRes.body.code, 200); + assert.equal(changeRoleRes.body.success, true); + assert.ok(changeRoleRes.body.data); + assert.ok(changeRoleRes.body.data.token); + + const switchedToken = changeRoleRes.body.data.token; + const afterInfoRes = await invokeSystemMethod('user.info', {}, switchedToken, { + platform: 'web', + project: 'all', + }); + + assert.equal(afterInfoRes.status, 200); + assert.equal(afterInfoRes.body.flag, 'success'); + assert.equal(afterInfoRes.body.code, 200); + assert.equal(Number(afterInfoRes.body.data.employees_id || 0), Number(target.id)); + + saveRuntime({ + savedAt: new Date().toISOString(), + method: 'user.changeRole', + headers: { + platform: 'web', + project: 'all', + }, + before: { + employees_id: currentRoleId, + employees_count: employees.length, + }, + targetRoleId: Number(target.id), + response: changeRoleRes.body, + verify: { + employees_id: Number(afterInfoRes.body.data.employees_id || 0), + }, + }); + + assert.equal(fs.existsSync(RUNTIME_FILE), true); + + // 尽量恢复原角色,避免影响其他测试。 + if (currentRoleId && currentRoleId !== Number(target.id)) { + const restoreRes = await invokeSystemMethod('user.changeRole', { + roleId: currentRoleId, + }, switchedToken, { + platform: 'web', + project: 'all', + }); + + assert.equal(restoreRes.status, 200); + assert.equal(restoreRes.body.flag, 'success'); + assert.equal(restoreRes.body.code, 200); + } + }); +}); diff --git a/test/app/controller/system.user.info.test.js b/test/app/controller/system.user.info.test.js new file mode 100644 index 0000000..ad5a047 --- /dev/null +++ b/test/app/controller/system.user.info.test.js @@ -0,0 +1,21 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const { + getAuthToken, + invokeSystemMethod, +} = require('../../support/system_method_client'); + +describe('test/app/controller/system.user.info.test.js', () => { + it('should call user.info with bearer token', async () => { + const { token } = await getAuthToken(); + const infoRes = await invokeSystemMethod('user.info', {}, token); + + assert.equal(infoRes.status, 200); + assert.equal(infoRes.body.flag, 'success'); + assert.equal(infoRes.body.code, 200); + assert.ok(infoRes.body.data); + assert.equal(infoRes.body.data.id, 1); + assert.equal(infoRes.body.data.platform_code, 'web'); + }); +}); diff --git a/test/app/controller/system.user.info.web.test.js b/test/app/controller/system.user.info.web.test.js new file mode 100644 index 0000000..dd29fa2 --- /dev/null +++ b/test/app/controller/system.user.info.web.test.js @@ -0,0 +1,45 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const { + getAuthToken, + invokeSystemMethod, +} = require('../../support/system_method_client'); + +const RUNTIME_FILE = path.join(process.cwd(), 'test', '.runtime', 'system_user_info_web_all.json'); + +function saveRuntime(payload) { + fs.mkdirSync(path.dirname(RUNTIME_FILE), { recursive: true }); + fs.writeFileSync(RUNTIME_FILE, JSON.stringify(payload, null, 2), 'utf8'); +} + +describe('test/app/controller/system.user.info.web.test.js', () => { + it('should call user.info with platform=web project=all and persist response', async () => { + const { token } = await getAuthToken(); + const infoRes = await invokeSystemMethod('user.info', {}, token, { + platform: 'web', + project: 'all', + }); + + assert.equal(infoRes.status, 200); + assert.equal(infoRes.body.flag, 'success'); + assert.equal(infoRes.body.code, 200); + assert.ok(infoRes.body.data); + assert.equal(infoRes.body.data.platform_code, 'web'); + assert.ok(Array.isArray(infoRes.body.data.employees)); + + saveRuntime({ + savedAt: new Date().toISOString(), + method: 'user.info', + headers: { + platform: 'web', + project: 'all', + }, + response: infoRes.body, + }); + + assert.equal(fs.existsSync(RUNTIME_FILE), true); + }); +}); diff --git a/test/app/controller/system.user.login.test.js b/test/app/controller/system.user.login.test.js new file mode 100644 index 0000000..c32fd00 --- /dev/null +++ b/test/app/controller/system.user.login.test.js @@ -0,0 +1,35 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const { getAuthToken, TOKEN_FILE } = require('../../support/system_method_client'); + +describe('test/app/controller/system.user.login.test.js', () => { + it('should get token from cache or login method', async () => { + const { token, fromCache } = await getAuthToken(); + + assert.equal(typeof token, 'string'); + assert.ok(token.length > 20); + assert.equal(typeof fromCache, 'boolean'); + }); + + it('should persist token cache file', async () => { + assert.equal(fs.existsSync(TOKEN_FILE), true); + }); + + it('user.login should return token only', async () => { + const { invokeSystemMethod, USERNAME } = require('../../support/system_method_client'); + const password = process.env.SYSTEM_TEST_PASSWORD || '111111'; + + const loginRes = await invokeSystemMethod('user.login', { + username: USERNAME, + password, + }); + + assert.equal(loginRes.status, 200); + assert.equal(loginRes.body.flag, 'success'); + assert.equal(loginRes.body.code, 200); + assert.equal(typeof loginRes.body.data?.token, 'string'); + assert.equal(loginRes.body.data?.user, undefined); + }); +}); diff --git a/test/app/controller/system.user.loginByCode.test.js b/test/app/controller/system.user.loginByCode.test.js new file mode 100644 index 0000000..928ff74 --- /dev/null +++ b/test/app/controller/system.user.loginByCode.test.js @@ -0,0 +1,52 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const { invokeSystemMethod } = require('../../support/system_method_client'); + +const VALID_LOGIN_CODE = process.env.SYSTEM_TEST_LOGIN_CODE + || 'eyJ1dWlkIjoiMDg2MTk4MzQtY2FhYS00OTIyLWJmNjctODc5M2U2Y2MwYzJkIn0='; + +describe('test/app/controller/system.user.loginByCode.test.js', () => { + it('should login successfully when code is valid', async () => { + const res = await invokeSystemMethod('user.loginByCode', { + code: VALID_LOGIN_CODE, + }); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + assert.equal(res.body.code, 200); + assert.equal(res.body.success, true); + assert.equal(typeof res.body.data?.token, 'string'); + assert.ok(res.body.data.token.length > 20); + assert.equal(typeof res.body.data?.user?.id, 'number'); + }); + + it('should fail when code is missing', async () => { + const res = await invokeSystemMethod('user.loginByCode', {}); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'failure'); + assert.equal(res.body.code, 0); + assert.match(String(res.body.message || ''), /code/); + }); + + it('should fail when code is not valid base64 json', async () => { + const code = `INVALID_CODE_${Date.now()}`; + const res = await invokeSystemMethod('user.loginByCode', { code }); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'failure'); + assert.equal(res.body.code, 0); + assert.match(String(res.body.message || ''), /无效的登录码格式/); + }); + + it('should fail when decoded payload does not contain uuid', async () => { + const code = Buffer.from(JSON.stringify({ foo: 'bar' }), 'utf8').toString('base64'); + const res = await invokeSystemMethod('user.loginByCode', { code }); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'failure'); + assert.equal(res.body.code, 0); + assert.match(String(res.body.message || ''), /uuid/); + }); +}); diff --git a/test/support/system_method_client.js b/test/support/system_method_client.js new file mode 100644 index 0000000..68c3649 --- /dev/null +++ b/test/support/system_method_client.js @@ -0,0 +1,137 @@ +'use strict'; + +const fs = require('node:fs'); +const path = require('node:path'); +const assert = require('node:assert/strict'); + +const BASE_URL = process.env.SYSTEM_TEST_BASE_URL || 'http://127.0.0.1:6060'; +const TOKEN_FILE = process.env.SYSTEM_TEST_TOKEN_FILE + || path.join(process.cwd(), 'test', '.runtime', 'system_user_token.json'); +const USERNAME = process.env.SYSTEM_TEST_USERNAME || 'liufumingren'; +const PASSWORD = process.env.SYSTEM_TEST_PASSWORD || '111111'; + +function nowSec() { + return Math.floor(Date.now() / 1000); +} + +function decodeJwtPayload(token) { + try { + const payloadSegment = token.split('.')[1]; + if (!payloadSegment) return null; + + const normalized = payloadSegment.replace(/-/g, '+').replace(/_/g, '/'); + const padded = normalized + '='.repeat((4 - normalized.length % 4) % 4); + return JSON.parse(Buffer.from(padded, 'base64').toString('utf8')); + } catch { + return null; + } +} + +function isTokenUsable(token) { + if (!token) return false; + const payload = decodeJwtPayload(token); + if (!payload || !payload.exp) return false; + return payload.exp - nowSec() > 120; +} + +function readCachedToken() { + if (!fs.existsSync(TOKEN_FILE)) return null; + + try { + const content = fs.readFileSync(TOKEN_FILE, 'utf8'); + const parsed = JSON.parse(content); + const token = parsed && parsed.token; + return isTokenUsable(token) ? token : null; + } catch { + return null; + } +} + +function writeCachedToken(token) { + fs.mkdirSync(path.dirname(TOKEN_FILE), { recursive: true }); + + const payload = decodeJwtPayload(token); + const record = { + token, + username: USERNAME, + cachedAt: new Date().toISOString(), + exp: payload && payload.exp ? payload.exp : null, + }; + + fs.writeFileSync(TOKEN_FILE, JSON.stringify(record, null, 2), 'utf8'); +} + +async function invokeSystemMethod(method, body = {}, token, extra = {}) { + const timestamp = nowSec(); + const url = `${BASE_URL}/system?method=${encodeURIComponent(method)}&v=1.0×tamp=${timestamp}`; + const platform = extra && extra.platform ? extra.platform : 'web'; + const project = extra && extra.project ? extra.project : 'wms'; + const headers = { + platform, + project, + 'Content-Type': 'application/json', + }; + + if (token) { + headers.Authorization = `Bearer ${token}`; + } + + const response = await fetch(url, { + method: 'POST', + headers, + body: JSON.stringify(body), + }); + + const text = await response.text(); + let json; + try { + json = JSON.parse(text); + } catch { + throw new Error(`Invalid JSON from ${method}: ${text}`); + } + + return { + status: response.status, + body: json, + }; +} + +async function getAuthToken(options = {}) { + const { forceLogin = false } = options; + + if (!forceLogin) { + const cached = readCachedToken(); + if (cached) { + return { token: cached, fromCache: true }; + } + } + + const loginRes = await invokeSystemMethod('user.login', { + username: USERNAME, + password: PASSWORD, + }); + + assert.equal(loginRes.status, 200, 'user.login should return HTTP 200'); + assert.equal(loginRes.body.flag, 'success', `user.login should succeed: ${JSON.stringify(loginRes.body)}`); + + const token = loginRes.body + && loginRes.body.data + && loginRes.body.data.token; + + assert.ok(token, 'user.login response should contain token'); + + writeCachedToken(token); + return { + token, + fromCache: false, + }; +} + +module.exports = { + BASE_URL, + TOKEN_FILE, + USERNAME, + invokeSystemMethod, + getAuthToken, + readCachedToken, +}; diff --git a/tmp-order-schema-compare.json b/tmp-order-schema-compare.json deleted file mode 100644 index e3f3f41..0000000 --- a/tmp-order-schema-compare.json +++ /dev/null @@ -1,1610 +0,0 @@ -{ - "generatedAt": "2026-03-22T06:08:48.627Z", - "dbName": "wms", - "tables": [ - "wms_entry_order", - "wms_order_delivery", - "wms_order_delivery_100000", - "wms_order_items", - "wms_order_items_100000" - ], - "compareWithModel": [ - { - "table": "wms_order_delivery", - "modelFile": "app/model/order_delivery.js", - "modelFieldCount": 72, - "dbFieldCount": 54, - "modelOnly": [ - "from_key", - "items", - "items_count", - "items_total", - "items_weight", - "items_hash", - "items_crc", - "wave_id", - "post_status", - "storage_status", - "pick_status", - "pack_status", - "inspection_status", - "print_status", - "claim_status", - "outbound_status", - "lock_status", - "intercept_status" - ], - "dbOnly": [], - "allMatched": false - }, - { - "table": "wms_order_items", - "modelFile": "app/model/order_items.js", - "modelFieldCount": 18, - "dbFieldCount": 15, - "modelOnly": [ - "stock_id", - "created_at", - "updated_at" - ], - "dbOnly": [], - "allMatched": false - }, - { - "table": "wms_entry_order", - "modelFile": "app/model/entry_order.js", - "modelFieldCount": 28, - "dbFieldCount": 28, - "modelOnly": [], - "dbOnly": [], - "allMatched": true - } - ], - "dynamicTableCheck": [ - { - "table": "wms_order_delivery_100000", - "baseTable": "wms_order_delivery", - "missingFromDynamic": [], - "extraInDynamic": [ - "from_key", - "items", - "items_count", - "items_total", - "items_weight", - "items_hash", - "items_crc", - "wave_id", - "post_status", - "storage_status", - "pick_status", - "pack_status", - "inspection_status", - "print_status", - "claim_status", - "outbound_status", - "lock_status", - "intercept_status" - ], - "allMatched": false - }, - { - "table": "wms_order_items_100000", - "baseTable": "wms_order_items", - "missingFromDynamic": [], - "extraInDynamic": [ - "stock_id", - "created_at", - "updated_at" - ], - "allMatched": false - } - ], - "schema": { - "wms_entry_order": [ - { - "COLUMN_NAME": "id", - "COLUMN_TYPE": "bigint(20) unsigned", - "IS_NULLABLE": "NO", - "COLUMN_DEFAULT": null, - "EXTRA": "auto_increment", - "COLUMN_KEY": "PRI" - }, - { - "COLUMN_NAME": "entry_order_code", - "COLUMN_TYPE": "varchar(50)", - "IS_NULLABLE": "NO", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "MUL" - }, - { - "COLUMN_NAME": "order_type", - "COLUMN_TYPE": "enum('SCRK','LYRK','CCRK','CGRK','DBRK','QTRK','B2BRK','XNRK')", - "IS_NULLABLE": "NO", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "MUL" - }, - { - "COLUMN_NAME": "purchase_order_code", - "COLUMN_TYPE": "varchar(50)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "total_order_lines", - "COLUMN_TYPE": "int(11)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": "0", - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "order_create_time", - "COLUMN_TYPE": "datetime", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "MUL" - }, - { - "COLUMN_NAME": "expect_start_time", - "COLUMN_TYPE": "datetime", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "expect_end_time", - "COLUMN_TYPE": "datetime", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "logistics_code", - "COLUMN_TYPE": "varchar(50)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "logistics_name", - "COLUMN_TYPE": "varchar(200)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "express_code", - "COLUMN_TYPE": "varchar(50)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "supplier_code", - "COLUMN_TYPE": "varchar(50)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "supplier_name", - "COLUMN_TYPE": "varchar(200)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "source_type", - "COLUMN_TYPE": "enum('WMS','API','QM')", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": "API", - "EXTRA": "", - "COLUMN_KEY": "MUL" - }, - { - "COLUMN_NAME": "order_status", - "COLUMN_TYPE": "enum('PENDING','CONFIRMED','PARTIAL_RECEIVED','COMPLETED','CANCELLED','CREATED','CREATING')", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": "PENDING", - "EXTRA": "", - "COLUMN_KEY": "MUL" - }, - { - "COLUMN_NAME": "sync_status", - "COLUMN_TYPE": "enum('PENDING','SUCCESS','FAILED')", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": "PENDING", - "EXTRA": "", - "COLUMN_KEY": "MUL" - }, - { - "COLUMN_NAME": "sync_message", - "COLUMN_TYPE": "text", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "is_enabled", - "COLUMN_TYPE": "tinyint(1)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": "1", - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "created_at", - "COLUMN_TYPE": "timestamp", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": "CURRENT_TIMESTAMP", - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "updated_at", - "COLUMN_TYPE": "timestamp", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": "CURRENT_TIMESTAMP", - "EXTRA": "on update CURRENT_TIMESTAMP", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "warehouse_id", - "COLUMN_TYPE": "bigint(20) unsigned", - "IS_NULLABLE": "NO", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "MUL" - }, - { - "COLUMN_NAME": "store_id", - "COLUMN_TYPE": "bigint(20) unsigned", - "IS_NULLABLE": "NO", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "MUL" - }, - { - "COLUMN_NAME": "remark", - "COLUMN_TYPE": "varchar(500)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "store_name", - "COLUMN_TYPE": "varchar(200)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "warehouse_name", - "COLUMN_TYPE": "varchar(200)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "deleted_at", - "COLUMN_TYPE": "datetime", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "qimen_owner_code", - "COLUMN_TYPE": "varchar(100)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "qimen_warehouse_code", - "COLUMN_TYPE": "varchar(100)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - } - ], - "wms_order_delivery": [ - { - "COLUMN_NAME": "id", - "COLUMN_TYPE": "bigint(20) unsigned", - "IS_NULLABLE": "NO", - "COLUMN_DEFAULT": null, - "EXTRA": "auto_increment", - "COLUMN_KEY": "PRI" - }, - { - "COLUMN_NAME": "delivery_order_code", - "COLUMN_TYPE": "varchar(50)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "MUL" - }, - { - "COLUMN_NAME": "pre_delivery_order_code", - "COLUMN_TYPE": "varchar(50)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "pre_delivery_order_id", - "COLUMN_TYPE": "varchar(50)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "order_type", - "COLUMN_TYPE": "varchar(50)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "warehouse_code", - "COLUMN_TYPE": "varchar(50)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "order_flag", - "COLUMN_TYPE": "varchar(200)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "source_platform_code", - "COLUMN_TYPE": "varchar(50)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "source_platform_name", - "COLUMN_TYPE": "varchar(200)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "create_at", - "COLUMN_TYPE": "datetime", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "delete_at", - "COLUMN_TYPE": "datetime", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "updated_at", - "COLUMN_TYPE": "datetime", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "place_order_time", - "COLUMN_TYPE": "datetime", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "pay_time", - "COLUMN_TYPE": "datetime", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "pay_no", - "COLUMN_TYPE": "varchar(50)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "service_code", - "COLUMN_TYPE": "varchar(50)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "operator_name", - "COLUMN_TYPE": "varchar(50)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "operate_time", - "COLUMN_TYPE": "datetime", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "delivery_time", - "COLUMN_TYPE": "datetime", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "shop_nick", - "COLUMN_TYPE": "varchar(200)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "seller_nick", - "COLUMN_TYPE": "varchar(200)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "buyer_nick", - "COLUMN_TYPE": "varchar(200)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "total_amount", - "COLUMN_TYPE": "decimal(18,2)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "item_amount", - "COLUMN_TYPE": "decimal(18,2)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "discount_amount", - "COLUMN_TYPE": "decimal(18,2)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "freight", - "COLUMN_TYPE": "decimal(18,2)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "ar_amount", - "COLUMN_TYPE": "decimal(18,2)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "got_amount", - "COLUMN_TYPE": "decimal(18,2)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "service_fee", - "COLUMN_TYPE": "decimal(18,2)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "logistics_code", - "COLUMN_TYPE": "varchar(50)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "logistics_name", - "COLUMN_TYPE": "varchar(200)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "express_code", - "COLUMN_TYPE": "varchar(50)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "logistics_area_code", - "COLUMN_TYPE": "varchar(50)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "delivery_type", - "COLUMN_TYPE": "varchar(255)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "is_urgency", - "COLUMN_TYPE": "enum('Y','N')", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": "N", - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "invoice_flag", - "COLUMN_TYPE": "enum('Y','N')", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": "N", - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "status", - "COLUMN_TYPE": "enum('pedding','created','cancel','intercepting','intercepted')", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": "pedding", - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "name", - "COLUMN_TYPE": "text", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "zip_code", - "COLUMN_TYPE": "varchar(50)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": "", - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "tel", - "COLUMN_TYPE": "text", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "mobile", - "COLUMN_TYPE": "text", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "email", - "COLUMN_TYPE": "text", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "country_code", - "COLUMN_TYPE": "varchar(255)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "province", - "COLUMN_TYPE": "varchar(255)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "city", - "COLUMN_TYPE": "varchar(255)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "area", - "COLUMN_TYPE": "varchar(255)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "town", - "COLUMN_TYPE": "varchar(255)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "detail_address", - "COLUMN_TYPE": "varchar(255)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "id_type", - "COLUMN_TYPE": "varchar(255)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "id_number", - "COLUMN_TYPE": "int(11)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "oaid", - "COLUMN_TYPE": "text", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "sync_status", - "COLUMN_TYPE": "enum('padding','fin','error')", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": "padding", - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "store_id", - "COLUMN_TYPE": "bigint(20) unsigned", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "MUL" - }, - { - "COLUMN_NAME": "warehouse_id", - "COLUMN_TYPE": "bigint(20) unsigned", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "MUL" - } - ], - "wms_order_delivery_100000": [ - { - "COLUMN_NAME": "id", - "COLUMN_TYPE": "bigint(20) unsigned", - "IS_NULLABLE": "NO", - "COLUMN_DEFAULT": null, - "EXTRA": "auto_increment", - "COLUMN_KEY": "PRI" - }, - { - "COLUMN_NAME": "delivery_order_code", - "COLUMN_TYPE": "varchar(50)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "MUL" - }, - { - "COLUMN_NAME": "pre_delivery_order_code", - "COLUMN_TYPE": "varchar(50)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "pre_delivery_order_id", - "COLUMN_TYPE": "varchar(50)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "order_type", - "COLUMN_TYPE": "varchar(50)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "warehouse_code", - "COLUMN_TYPE": "varchar(50)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "order_flag", - "COLUMN_TYPE": "varchar(200)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "source_platform_code", - "COLUMN_TYPE": "varchar(50)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "source_platform_name", - "COLUMN_TYPE": "varchar(200)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "create_at", - "COLUMN_TYPE": "datetime", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "delete_at", - "COLUMN_TYPE": "datetime", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "updated_at", - "COLUMN_TYPE": "datetime", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "place_order_time", - "COLUMN_TYPE": "datetime", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "pay_time", - "COLUMN_TYPE": "datetime", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "pay_no", - "COLUMN_TYPE": "varchar(50)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "service_code", - "COLUMN_TYPE": "varchar(50)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "operator_name", - "COLUMN_TYPE": "varchar(50)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "operate_time", - "COLUMN_TYPE": "datetime", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "delivery_time", - "COLUMN_TYPE": "datetime", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "shop_nick", - "COLUMN_TYPE": "varchar(200)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "seller_nick", - "COLUMN_TYPE": "varchar(200)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "buyer_nick", - "COLUMN_TYPE": "varchar(200)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "total_amount", - "COLUMN_TYPE": "decimal(18,2)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "item_amount", - "COLUMN_TYPE": "decimal(18,2)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "discount_amount", - "COLUMN_TYPE": "decimal(18,2)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "freight", - "COLUMN_TYPE": "decimal(18,2)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "ar_amount", - "COLUMN_TYPE": "decimal(18,2)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "got_amount", - "COLUMN_TYPE": "decimal(18,2)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "service_fee", - "COLUMN_TYPE": "decimal(18,2)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "logistics_code", - "COLUMN_TYPE": "varchar(50)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "logistics_name", - "COLUMN_TYPE": "varchar(200)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "express_code", - "COLUMN_TYPE": "varchar(50)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "logistics_area_code", - "COLUMN_TYPE": "varchar(50)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "delivery_type", - "COLUMN_TYPE": "varchar(255)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "is_urgency", - "COLUMN_TYPE": "enum('Y','N')", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": "N", - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "invoice_flag", - "COLUMN_TYPE": "enum('Y','N')", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": "N", - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "status", - "COLUMN_TYPE": "enum('pedding','created','cancel','error','after-sales-error')", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": "created", - "EXTRA": "", - "COLUMN_KEY": "MUL" - }, - { - "COLUMN_NAME": "name", - "COLUMN_TYPE": "text", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "zip_code", - "COLUMN_TYPE": "varchar(50)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "tel", - "COLUMN_TYPE": "text", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "mobile", - "COLUMN_TYPE": "text", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "email", - "COLUMN_TYPE": "text", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "country_code", - "COLUMN_TYPE": "varchar(255)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "province", - "COLUMN_TYPE": "varchar(255)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "city", - "COLUMN_TYPE": "varchar(255)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "area", - "COLUMN_TYPE": "varchar(255)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "town", - "COLUMN_TYPE": "varchar(255)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "detail_address", - "COLUMN_TYPE": "varchar(255)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "id_type", - "COLUMN_TYPE": "varchar(255)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "id_number", - "COLUMN_TYPE": "int(11)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "oaid", - "COLUMN_TYPE": "text", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "sync_status", - "COLUMN_TYPE": "enum('padding','fin','error','none')", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": "padding", - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "store_id", - "COLUMN_TYPE": "bigint(20) unsigned", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "MUL" - }, - { - "COLUMN_NAME": "warehouse_id", - "COLUMN_TYPE": "bigint(20) unsigned", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "MUL" - }, - { - "COLUMN_NAME": "from_key", - "COLUMN_TYPE": "int(11)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "items", - "COLUMN_TYPE": "text", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "MUL" - }, - { - "COLUMN_NAME": "items_count", - "COLUMN_TYPE": "smallint(5) unsigned", - "IS_NULLABLE": "NO", - "COLUMN_DEFAULT": "0", - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "items_total", - "COLUMN_TYPE": "int(10) unsigned", - "IS_NULLABLE": "NO", - "COLUMN_DEFAULT": "0", - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "items_weight", - "COLUMN_TYPE": "decimal(10,2)", - "IS_NULLABLE": "NO", - "COLUMN_DEFAULT": "0.00", - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "items_hash", - "COLUMN_TYPE": "char(32)", - "IS_NULLABLE": "NO", - "COLUMN_DEFAULT": "", - "EXTRA": "", - "COLUMN_KEY": "MUL" - }, - { - "COLUMN_NAME": "items_crc", - "COLUMN_TYPE": "int(10) unsigned", - "IS_NULLABLE": "NO", - "COLUMN_DEFAULT": "0", - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "wave_id", - "COLUMN_TYPE": "bigint(20)", - "IS_NULLABLE": "NO", - "COLUMN_DEFAULT": "0", - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "post_status", - "COLUMN_TYPE": "enum('padding','fin','timeout','error','none')", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": "none", - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "storage_status", - "COLUMN_TYPE": "enum('padding','fin','error','none')", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": "none", - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "pick_status", - "COLUMN_TYPE": "enum('padding','fin','error','none')", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": "none", - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "pack_status", - "COLUMN_TYPE": "enum('none','padding','fin','error')", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": "none", - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "inspection_status", - "COLUMN_TYPE": "enum('none','padding','running','fin','error')", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": "none", - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "print_status", - "COLUMN_TYPE": "enum('none','padding','fin','error')", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": "none", - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "claim_status", - "COLUMN_TYPE": "enum('none','padding','fin','error')", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": "none", - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "outbound_status", - "COLUMN_TYPE": "enum('none','padding','fin','error')", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": "none", - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "lock_status", - "COLUMN_TYPE": "enum('none','warehouse','store')", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": "none", - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "intercept_status", - "COLUMN_TYPE": "enum('none','requesting','requested','intercepting','intercepted_in_transit','intercepted_at_warehouse','returning','returned','delivered_by_mistake','timeout','cancelled','failed','exception')", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": "none", - "EXTRA": "", - "COLUMN_KEY": "" - } - ], - "wms_order_items": [ - { - "COLUMN_NAME": "id", - "COLUMN_TYPE": "bigint(20) unsigned", - "IS_NULLABLE": "NO", - "COLUMN_DEFAULT": null, - "EXTRA": "auto_increment", - "COLUMN_KEY": "PRI" - }, - { - "COLUMN_NAME": "order_id", - "COLUMN_TYPE": "bigint(20) unsigned", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "MUL" - }, - { - "COLUMN_NAME": "actual_price", - "COLUMN_TYPE": "decimal(18,2)", - "IS_NULLABLE": "NO", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "retail_price", - "COLUMN_TYPE": "decimal(18,2)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "ext_code", - "COLUMN_TYPE": "varchar(50)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "inventory_type", - "COLUMN_TYPE": "varchar(50)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "item_code", - "COLUMN_TYPE": "varchar(50)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "item_id", - "COLUMN_TYPE": "bigint(20) unsigned", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "item_name", - "COLUMN_TYPE": "varchar(200)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "order_line_no", - "COLUMN_TYPE": "varchar(50)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "owner_code", - "COLUMN_TYPE": "varchar(50)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "plan_qty", - "COLUMN_TYPE": "int(11)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "source_order_code", - "COLUMN_TYPE": "varchar(50)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "sub_source_order_code", - "COLUMN_TYPE": "varchar(50)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "extend_props", - "COLUMN_TYPE": "text", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - } - ], - "wms_order_items_100000": [ - { - "COLUMN_NAME": "id", - "COLUMN_TYPE": "bigint(20) unsigned", - "IS_NULLABLE": "NO", - "COLUMN_DEFAULT": null, - "EXTRA": "auto_increment", - "COLUMN_KEY": "PRI" - }, - { - "COLUMN_NAME": "order_id", - "COLUMN_TYPE": "bigint(20) unsigned", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "MUL" - }, - { - "COLUMN_NAME": "actual_price", - "COLUMN_TYPE": "decimal(18,2)", - "IS_NULLABLE": "NO", - "COLUMN_DEFAULT": "0.00", - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "retail_price", - "COLUMN_TYPE": "decimal(18,2)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "ext_code", - "COLUMN_TYPE": "varchar(50)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "inventory_type", - "COLUMN_TYPE": "varchar(50)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "item_code", - "COLUMN_TYPE": "varchar(50)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "MUL" - }, - { - "COLUMN_NAME": "item_id", - "COLUMN_TYPE": "bigint(20)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "MUL" - }, - { - "COLUMN_NAME": "item_name", - "COLUMN_TYPE": "varchar(200)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "order_line_no", - "COLUMN_TYPE": "varchar(50)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "owner_code", - "COLUMN_TYPE": "varchar(50)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "MUL" - }, - { - "COLUMN_NAME": "plan_qty", - "COLUMN_TYPE": "int(11)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "source_order_code", - "COLUMN_TYPE": "varchar(50)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "MUL" - }, - { - "COLUMN_NAME": "sub_source_order_code", - "COLUMN_TYPE": "varchar(50)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "extend_props", - "COLUMN_TYPE": "json", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "" - }, - { - "COLUMN_NAME": "stock_id", - "COLUMN_TYPE": "bigint(20)", - "IS_NULLABLE": "YES", - "COLUMN_DEFAULT": null, - "EXTRA": "", - "COLUMN_KEY": "MUL" - }, - { - "COLUMN_NAME": "created_at", - "COLUMN_TYPE": "datetime", - "IS_NULLABLE": "NO", - "COLUMN_DEFAULT": "CURRENT_TIMESTAMP", - "EXTRA": "", - "COLUMN_KEY": "MUL" - }, - { - "COLUMN_NAME": "updated_at", - "COLUMN_TYPE": "datetime", - "IS_NULLABLE": "NO", - "COLUMN_DEFAULT": "CURRENT_TIMESTAMP", - "EXTRA": "on update CURRENT_TIMESTAMP", - "COLUMN_KEY": "" - } - ] - } -} \ No newline at end of file diff --git a/tmp-order-schema-workflow.md b/tmp-order-schema-workflow.md index 16963db..99c415c 100644 --- a/tmp-order-schema-workflow.md +++ b/tmp-order-schema-workflow.md @@ -27,7 +27,7 @@ ## 4. 已生成产物 -- 结构与差异总结果: tmp-order-schema-compare.json +- 结构与差异总结果: temp/tmp-order-schema-compare.json - 比对脚本(可复跑): script/tmp-compare-order-schema.cjs ## 5. 关键比对结论 @@ -68,7 +68,7 @@ node .\script\tmp-compare-order-schema.cjs ### 6.2 快速查看结果摘要 PowerShell: -Get-Content .\tmp-order-schema-compare.json -TotalCount 160 +Get-Content .\temp\tmp-order-schema-compare.json -TotalCount 160 ## 7. 后续建议 diff --git a/tmp-service-method-inventory.md b/tmp-service-method-inventory.md deleted file mode 100644 index 052d888..0000000 --- a/tmp-service-method-inventory.md +++ /dev/null @@ -1,105 +0,0 @@ -自动生成时间: 2026-03-22T09:03:11.802Z - -扫描范围: app/service/**/*.js -文件数: 50 - -- app/service/api.js (1) - - callMethod -- app/service/apiMethods/test.js (4) - - entryorderConfirm, playbackRequest, fibonacci, fibonacciRecursive -- app/service/dispatcher.js (3) - - buildMap, getMethodMap, invoke -- app/service/main.js (11) - - success, fail, normalizeDate, setInfo, getInfo, findQimenAppWithContract, queryFromDatabase, checkAuth, checkApiPermission, setUserContext, systemInit -- app/service/pda.js (3) - - callMethod, validateParams, saveLog -- app/service/qimen.js (12) - - validateApi, getErpName, parseXmlToArray, cleanXmlString, callMethod, formatResponse, xmlResponse, buildXmlNode, escapeXml, saveQimenLog, saveQimenLogResult, saveQimenLogBody -- app/service/qimenMethods/deliveryorder.js (3) - - query, create, batchcreate -- app/service/qimenMethods/entryorder.js (2) - - create, query -- app/service/qimenMethods/inventory.js (1) - - query -- app/service/qimenMethods/order.js (2) - - cancel, pending -- app/service/qimenMethods/returnorder.js (2) - - create, query -- app/service/qimenMethods/singleitem.js (2) - - synchronize, query -- app/service/qimenMethods/stockout.js (2) - - create, query -- app/service/qimenMethods/taobao/qimen/service.js (1) - - heartbeat -- app/service/system.js (3) - - callMethod, validateParams, saveLog -- app/service/systemMethods/config.js (1) - - list -- app/service/systemMethods/dashboard.js (6) - - storeStats, warehouseStats, hot_order_rank, express_ratio, platform_distribution, order_trend -- app/service/systemMethods/index.js (13) - - fastWhereTree, loadStores, getCOSUploadConfig, getImages, uploadSuccessNotify, ReferenceFile, getMessageDetail, getI18nMessage, putI18nCollect, extractModule, tryAutoTranslateNewKeys, searchSpace, getExpressList -- app/service/systemMethods/order.js (11) - - getWarehouseId, getOrderModels, applyDateRange, buildWhere, parseDateTime, list, detail, listItems, stats, updateStatus, updateDeliveryTime -- app/service/systemMethods/print.js (3) - - send, sendToComputer, log -- app/service/systemMethods/printer/station.js (1) - - list -- app/service/systemMethods/setting/printTemplate.js (3) - - list, save, listTemplatesByType -- app/service/systemMethods/stock.js (21) - - stockWarehouse, getProhibitedType, getInfo, saveWarehouseStock, createWarehouseStock, getBarcodes, saveWarehouseStockBarcode, getStoreStocks, bindItem, unbindItem, checkItemCodeUnique, queryStockLogs, handleBatchDelete, deleteUnit, deleteProhibited, handleBatchChange, getStockUnits, getUnitList, createProhibited, createUnit, search -- app/service/systemMethods/storage/receiving.js (13) - - getReceivingList, getReceivingDetail, batchCancelReceiving, create, addItem, removeItem, saveReceiving, get, addDetail, deleteDetail, detailChange, cancel, completeReceiving -- app/service/systemMethods/store.js (6) - - createStore, createWarehouse, joinStore, joinWarehouse, getStoreRoles, auditApply -- app/service/systemMethods/user.js (5) - - login, logout, info, changeRole, register -- app/service/systemMethods/warehouse.js (20) - - getWarehouseZones, getWarehouseTree, getChildren, create, update, delete, detail, checkBarcodeUnique, toggleActive, getPath, createRack, getPickPath, updateRackPosition, recalculatePickPath, updateNeighbors, getAreaRacks, getSpacesByRack, createRackWithSpaces, getSpaceInfo, updateSpaceInfo -- app/service/systems/account_platform.js (8) - - switchActiveRole, getActiveRoleByPlatform, getMultiplePlatformActiveRoles, getAllPlatformActives, clearPlatformActive, clearPlatformCache, getAvailableRoles, getCurrentContext -- app/service/systems/auth/user.js (21) - - login, ID, changeRole, info, getRoles, findById, setUserCache, getAvatarByEmployeeId, clearUserCache, clearRelatedCache, getPermissions, getMenus, convertToRoutes, findUserByIdentifier, checkUserStatus, verifyPassword, encryptPassword, generateSalt, updateLastLoginTime, ensurePlatformActiveRole, register -- app/service/systems/delivery_order.js (7) - - addOrder, generateItemsHash, calculateCRC32, prepareOrderData, addOrderLines, safeParseFloat, addOrderToQueue -- app/service/systems/entry_order.js (9) - - addOrder, getLineCount, received, success, fail, tryCreateEntryOrder, addItems, qimenEntryorderConfirm, entryorderConfirm -- app/service/systems/fast_where.js (13) - - buildTree, getTreeByType, buildSubTree, getWithChildrenByType, getAllChildren, getByType, getGroups, getChildrenByPid, getTreeChildrenByPid, create, update, findById, delete -- app/service/systems/file.js (2) - - getImages, ReferenceFile -- app/service/systems/location_space.js (16) - - create, batchCreate, list, detail, update, delete, toggleStatus, updateStatus, findAvailableSpaces, findByCode, findByBarcode, getWarehouseStats, getZoneStats, validateAllocation, validateTransferOut, _validateReferences -- app/service/systems/location_zone.js (22) - - getWarehouseLevelZones, getZoneTreeByWarehouse, getChildrenByZoneId, isLeafNode, createZone, validateBasicFields, validateByZoneType, validateParentElement, validateZoneOverlap, isOverlap, generateZoneCodeByType, getDefaultColorByType, getZoneTypeText, updateZone, deleteZone, checkZoneOverlap, getZoneDetail, toggleZoneActive, getZonePath, generateSpacesForRack, getSpaceInfo, checkBarcodeUnique -- app/service/systems/location.js (10) - - createRackWithSpaces, _generateSpacesForRack, _calculateAreaRackOrder, _calculatePickPathForWarehouse, _updateSpacePickSequence, _calculatePickPriority, updateRackPosition, getPickPath, updateNeighborRelations, _findNeighborRacks -- app/service/systems/notification.js (1) - - send -- app/service/systems/operation_log.js (4) - - createOperationLog, queryStockLogs, queryOrderLogs, getMessageDetail -- app/service/systems/platform.js (6) - - checkPlatformExists, getPlatformInfo, clearPlatformCache, getPlatformSettingDetail, batchCheckPlatforms, createPlatformSetting -- app/service/systems/polo_api.js (6) - - getJsonDatas, getJsonData, getSignText, md5Encrypt, _formatDate, _formatPickupDate -- app/service/systems/print/index.js (2) - - sendToComputer, test -- app/service/systems/qimen_query.js (6) - - send, replaceXmlTagsWithString, addSign, getQueryParams, generateUrlWithParams, sendRequest -- app/service/systems/setting/print_template.js (14) - - listTemplatesByType, getTree, getTemplatesByType, save, getBusinessTypesAndItem, getGroupedPrintItems, getTableConfigs, clearBusinessTypesCache, getXmlByTemplate, buildXmlFromElements, renderElement, computeItemStyle, computeTableItemStyle, renderTable -- app/service/systems/sign.js (10) - - Constants, toXml, signTopRequest, verifyTopRequest, verifyAndExtractParams, generateSignedParams, encryptHMAC, encryptHMACSHA256, encryptMD5, byte2hex -- app/service/systems/space.js (1) - - searchSpace -- app/service/systems/stock_store.js (34) - - create, initQimenStockData, convertToQimenFormat, getItemInfoWithCache, getItemStorages, _calculateCacheTTL, clearItemStorageCache, lockItemStorages, ID, inbound, outbound, checkAndCreateWarehouseStock, getWarehouseStock, buildSequelizeCondition, processConditionValue, formatDate, isEmptyValue, getProhibitedType, getBarcodes, handleBatchChange, saveWarehouseStockBarcode, getStoreStocks, bindItem, unbindItem, getInfo, saveWarehouseStock, createWarehouseStock, validateSaveParams, stockLog, checkItemCodeUnique, handleBatchDelete, deleteUnit, deleteProhibited, search -- app/service/systems/storage/index.js (1) - - index -- app/service/systems/storage/receiving.js (16) - - getReceivingList, getReceivingDetail, batchCancelReceiving, isEmptyValue, buildSequelizeCondition, processConditionValue, create, get, addDetail, updateDetail, getStockStoreInfo, updateReceivingStats, deleteDetail, detailChange, invalid, completeReceiving -- app/service/systems/store.js (13) - - getStoreName, getStoreRemaskName, createStore, createWarehouse, joinStore, joinWarehouse, assignAdminRoleToCreator, generateJoinToken, sendNotification, sendNotificationToAdmins, getStoreRoles, auditApply, loadStores -- app/service/systems/upload.js (14) - - initCOS, getUploadParams, hash_hmac, validateFileInfo, generateFileName, parseSizeToBytes, formatFileSize, getFrontendConfig, uploadFile, validateFile, uploadSuccessNotify, getMimeType, createFileReference, handleUploadCallback From 2a1c8b4fa8bfbca9013818e60daca15ad4a5e176 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Tue, 24 Mar 2026 23:57:20 +0800 Subject: [PATCH 007/550] =?UTF-8?q?fix(deploy):=20=E5=81=A5=E5=BA=B7?= =?UTF-8?q?=E6=A3=80=E6=9F=A5=E6=94=AF=E6=8C=81=E6=9C=AC=E5=9C=B0=E5=85=9C?= =?UTF-8?q?=E5=BA=95=E4=B8=8E=E8=B6=85=E6=97=B6=EF=BC=8C=E5=88=87=E6=9C=8D?= =?UTF-8?q?=E5=90=8E=E5=8F=AF=E8=87=AA=E5=8A=A8=E5=9B=9E=E9=80=80=E6=9C=AC?= =?UTF-8?q?=E5=9C=B0=E7=AB=AF=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/controller/gateway.js | 118 +++++++++++++++++++++++ script/deploy-remote.cjs | 191 +++++++++++++++++++++++++++++++++++++ script/rollback-remote.cjs | 140 +++++++++++++++++++++++++++ 3 files changed, 449 insertions(+) create mode 100644 app/controller/gateway.js create mode 100644 script/deploy-remote.cjs create mode 100644 script/rollback-remote.cjs diff --git a/app/controller/gateway.js b/app/controller/gateway.js new file mode 100644 index 0000000..47f15eb --- /dev/null +++ b/app/controller/gateway.js @@ -0,0 +1,118 @@ +'use strict'; + +const { Controller } = require('egg'); +const { toSuccess, toFailure } = require('../lib/api_response'); + +class GatewayController extends Controller { + validateParams(params) { + const required = [ 'method', 'v', 'timestamp' ]; + + for (const field of required) { + if (!params[field]) { + return false; + } + } + + if (typeof params.method !== 'string' || !params.method.includes('.')) { + return false; + } + + return true; + } + + normalizeResult(result) { + if (result && typeof result === 'object' && Object.prototype.hasOwnProperty.call(result, 'success') && Object.prototype.hasOwnProperty.call(result, 'code')) { + if (result.success === false || Number(result.code) <= 0) { + return { + httpStatus: 200, + body: toFailure({ + message: result.message || '请求失败', + httpStatus: 200, + code: typeof result.code === 'number' ? result.code : 0, + data: result.data || null, + }), + }; + } + + return { + httpStatus: 200, + body: toSuccess({ + flag: 'success', + code: result.code, + message: result.message || 'ok', + data: result.data || null, + }), + }; + } + + return { + httpStatus: 200, + body: toSuccess(result), + }; + } + + async internal() { + const { ctx, service } = this; + + try { + const getParams = ctx.query; + if (!this.validateParams(getParams)) { + ctx.status = 400; + ctx.body = toFailure({ + message: '参数缺失或错误: method/v/timestamp', + httpStatus: 400, + code: 400, + }); + ctx.type = 'application/json'; + return; + } + + const methods = String(getParams.method).split('.'); + const actionName = methods.pop(); + const className = methods.join('.'); + + let jsonData = ''; + if (ctx.request.rawBody) { + jsonData = ctx.request.rawBody; + } else { + jsonData = await new Promise((resolve, reject) => { + let data = ''; + ctx.req.on('data', chunk => { + data += chunk; + }); + ctx.req.on('end', () => { + resolve(data); + }); + ctx.req.on('error', reject); + }); + } + + jsonData = jsonData ? String(jsonData) : ''; + if (!jsonData || jsonData.trim() === '') { + throw new Error('json数据为空'); + } + + try { + jsonData = JSON.parse(jsonData); + } catch (error) { + throw new Error('json数据解析错误'); + } + + const result = await service.api.callMethod(className, actionName, jsonData); + const normalized = this.normalizeResult(result); + ctx.status = normalized.httpStatus; + ctx.body = normalized.body; + ctx.type = 'application/json'; + } catch (error) { + ctx.status = 500; + ctx.body = toFailure({ + message: '接口错误: ' + error.message, + httpStatus: 500, + code: 500, + }); + ctx.type = 'application/json'; + } + } +} + +module.exports = GatewayController; \ No newline at end of file diff --git a/script/deploy-remote.cjs b/script/deploy-remote.cjs new file mode 100644 index 0000000..b3457f5 --- /dev/null +++ b/script/deploy-remote.cjs @@ -0,0 +1,191 @@ +'use strict'; + +const fs = require('node:fs'); +const path = require('node:path'); +const { URL } = require('node:url'); +const { + ROOT, + buildArchive, + buildRemoteCleanupGuard, + buildScopedEggStopScript, + ensureCommandAvailable, + getNowStamp, + loadDeployConfig, + quoteForBash, + runCommand, + runScp, + runSsh, + serializeCommands, +} = require('./deploy-lib.cjs'); +const { recordVersionUpdate } = require('./version-registry.cjs'); + +function splitPostDeployCommands(commands) { + const normalized = Array.isArray(commands) ? commands.filter(Boolean).map(item => String(item).trim()).filter(Boolean) : []; + const stopCommandPattern = /^(?:npm(?:\.cmd)?\s+(?:run\s+)?stop|egg-scripts\s+stop)(?:\s|$)/i; + const startCommandIndex = normalized.findIndex(item => /^npm\s+start(?:\s|$)/i.test(item)); + const stopCommandIndexes = normalized + .map((item, index) => (stopCommandPattern.test(item) ? index : -1)) + .filter(index => index >= 0); + + if (startCommandIndex === -1) { + return { + preStartCommands: normalized.filter((_, index) => !stopCommandIndexes.includes(index)), + startCommand: '', + }; + } + + return { + preStartCommands: normalized.filter((_, index) => index !== startCommandIndex && !stopCommandIndexes.includes(index)), + startCommand: normalized[startCommandIndex], + }; +} + +function buildHealthCheckScript(healthCheckUrl) { + if (!healthCheckUrl) { + return ''; + } + + let fallbackUrl = ''; + try { + const parsed = new URL(healthCheckUrl); + const hostname = String(parsed.hostname || '').toLowerCase(); + const isLocalHost = hostname === '127.0.0.1' || hostname === 'localhost'; + if (!isLocalHost) { + const port = parsed.port || '6060'; + fallbackUrl = `http://127.0.0.1:${port}${parsed.pathname || '/'}${parsed.search || ''}`; + } + } catch (error) { + fallbackUrl = 'http://127.0.0.1:6060/'; + } + + return [ + `HEALTHCHECK_URL=${quoteForBash(healthCheckUrl)}`, + ...(fallbackUrl ? [ `HEALTHCHECK_FALLBACK_URL=${quoteForBash(fallbackUrl)}` ] : []), + 'HEALTHCHECK_CURL_OPTS="--connect-timeout 2 --max-time 4"', + 'for attempt in $(seq 1 20); do', + ' if curl -fsS $HEALTHCHECK_CURL_OPTS "$HEALTHCHECK_URL" >/dev/null; then', + ' break', + ' fi', + ...(fallbackUrl ? [ ' if curl -fsS $HEALTHCHECK_CURL_OPTS "$HEALTHCHECK_FALLBACK_URL" >/dev/null; then', ' break', ' fi' ] : []), + ' if [ "$attempt" -eq 20 ]; then', + ...(fallbackUrl + ? [ ' echo "健康检查失败: $HEALTHCHECK_URL (fallback: $HEALTHCHECK_FALLBACK_URL)" >&2' ] + : [ ' echo "健康检查失败: $HEALTHCHECK_URL" >&2' ]), + ' exit 1', + ' fi', + ' sleep 1', + 'done', + ].join('\n'); +} + +function main() { + const envName = process.argv[2] || 'production'; + const config = loadDeployConfig(envName); + + ensureCommandAvailable('git', '请先安装 Git 并确保 git 在 PATH 中。'); + ensureCommandAvailable('tar', '请先安装 tar,Windows 10/11 通常已内置 bsdtar。'); + ensureCommandAvailable('ssh', '请先安装 OpenSSH Client 并确保 ssh 在 PATH 中。'); + ensureCommandAvailable('scp', '请先安装 OpenSSH Client 并确保 scp 在 PATH 中。'); + + const stamp = getNowStamp(); + const packageJson = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8')); + const packageVersion = String(packageJson.version || '0.0.0'); + const gitCommit = runCommand('git', [ 'rev-parse', 'HEAD' ]); + const gitCommitShort = runCommand('git', [ 'rev-parse', '--short', 'HEAD' ]); + const gitBranch = runCommand('git', [ 'rev-parse', '--abbrev-ref', 'HEAD' ]); + const releaseVersion = `v${packageVersion}-${stamp}-${gitCommitShort}`; + + const { archivePath } = buildArchive(stamp, config); + const remoteArchive = `${config.incomingDir}/release-${stamp}.tar.gz`; + const remoteArchiveName = path.posix.basename(remoteArchive); + const latestBackupFile = `latest-backup.txt`; + const releaseStateFile = path.posix.join(config.stateDir, 'current-release.json'); + const releaseHistoryFile = path.posix.join(config.stateDir, 'release-history.jsonl'); + const backupName = `backup-${stamp}.tar.gz`; + const cleanupGuard = buildRemoteCleanupGuard(config.sharedDirs, config.preserveDirs); + const preDeployCommands = serializeCommands(config.preDeployCommands); + const postDeploy = splitPostDeployCommands(config.postDeployCommands); + const postDeployCommands = serializeCommands(postDeploy.preStartCommands); + const startCommand = postDeploy.startCommand; + const scopedStopCommand = buildScopedEggStopScript(config.deployRoot); + const detachedStartCommand = startCommand + ? `nohup bash -lc ${quoteForBash(startCommand)} >/tmp/wms-deploy-start.log 2>&1 &` + : ''; + const healthCheckCommand = buildHealthCheckScript(config.healthCheckUrl); + const releaseMeta = { + releaseVersion, + packageVersion, + gitCommit, + gitCommitShort, + gitBranch, + stamp, + deployedAt: new Date().toISOString(), + envName, + deployRoot: config.deployRoot, + archiveFile: remoteArchiveName, + backupFile: backupName, + }; + const releaseMetaPretty = JSON.stringify(releaseMeta, null, 2); + const releaseMetaLine = JSON.stringify(releaseMeta); + + const setupScript = [ + 'set -euo pipefail', + `mkdir -p ${quoteForBash(config.deployRoot)} ${quoteForBash(config.controlDir)} ${quoteForBash(config.incomingDir)} ${quoteForBash(config.backupDir)} ${quoteForBash(config.stateDir)}`, + ].join('\n'); + runSsh(config, setupScript); + runScp(config, archivePath, remoteArchive); + + const remoteScript = [ + 'set -euo pipefail', + `DEPLOY_ROOT=${quoteForBash(config.deployRoot)}`, + `BACKUP_DIR=${quoteForBash(config.backupDir)}`, + `STATE_DIR=${quoteForBash(config.stateDir)}`, + `REMOTE_ARCHIVE=${quoteForBash(remoteArchive)}`, + `KEEP_BACKUPS=${Number(config.keepBackups)}`, + `BACKUP_NAME=${quoteForBash(backupName)}`, + `CURRENT_RELEASE_FILE=${quoteForBash(releaseStateFile)}`, + `RELEASE_HISTORY_FILE=${quoteForBash(releaseHistoryFile)}`, + `RELEASE_META_JSON=${quoteForBash(releaseMetaPretty)}`, + `RELEASE_META_LINE=${quoteForBash(releaseMetaLine)}`, + 'cd "$DEPLOY_ROOT"', + 'mkdir -p "$BACKUP_DIR" "$STATE_DIR"', + 'tar --exclude=.deploy -czf "$BACKUP_DIR/$BACKUP_NAME" .', + preDeployCommands, + `find . -mindepth 1 -maxdepth 1 ${cleanupGuard} -exec rm -rf {} +`, + 'tar -xzf "$REMOTE_ARCHIVE" -C "$DEPLOY_ROOT"', + 'rm -f "$REMOTE_ARCHIVE"', + `printf '%s\\n' "$BACKUP_NAME" > ${quoteForBash(path.posix.join(config.stateDir, latestBackupFile))}`, + 'if [ ! -d "$DEPLOY_ROOT/config" ]; then echo "配置目录缺失: $DEPLOY_ROOT/config(首次发布请先创建并放置生产配置)" >&2; exit 1; fi', + postDeployCommands, + detachedStartCommand, + healthCheckCommand, + 'printf "%s\\n" "$RELEASE_META_JSON" > "$CURRENT_RELEASE_FILE"', + 'printf "%s\\n" "$RELEASE_META_LINE" >> "$RELEASE_HISTORY_FILE"', + 'ls -1t "$BACKUP_DIR"/*.tar.gz 2>/dev/null | tail -n +$((KEEP_BACKUPS + 1)) | xargs -r rm -f', + ].filter(Boolean).join('\n'); + + try { + runSsh(config, scopedStopCommand, { stdio: 'inherit' }); + } catch (error) { + console.warn(`定点停进程失败,继续发布流程: ${error.message}`); + } + + runSsh(config, remoteScript); + try { + recordVersionUpdate({ + source: 'deploy:prod', + note: `env=${envName}`, + releaseVersion, + deployRoot: config.deployRoot, + remoteBackupFile: backupName, + remoteStateFile: releaseStateFile, + remoteHistoryFile: releaseHistoryFile, + }); + } catch (error) { + console.warn(`本地版本记录写入失败: ${error.message}`); + } + console.log(`发布完成: ${envName} -> ${config.username}@${config.host}:${config.deployRoot}`); + console.log(`线上版本号: ${releaseVersion}`); +} + +main(); \ No newline at end of file diff --git a/script/rollback-remote.cjs b/script/rollback-remote.cjs new file mode 100644 index 0000000..0bc8dd9 --- /dev/null +++ b/script/rollback-remote.cjs @@ -0,0 +1,140 @@ +'use strict'; + +const path = require('node:path'); +const { URL } = require('node:url'); +const { + buildRemoteCleanupGuard, + buildScopedEggStopScript, + ensureCommandAvailable, + getNowStamp, + loadDeployConfig, + quoteForBash, + runSsh, + serializeCommands, +} = require('./deploy-lib.cjs'); + +function splitPostDeployCommands(commands) { + const normalized = Array.isArray(commands) ? commands.filter(Boolean).map(item => String(item).trim()).filter(Boolean) : []; + const stopCommandPattern = /^(?:npm(?:\.cmd)?\s+(?:run\s+)?stop|egg-scripts\s+stop)(?:\s|$)/i; + const startCommandIndex = normalized.findIndex(item => /^npm\s+start(?:\s|$)/i.test(item)); + const stopCommandIndexes = normalized + .map((item, index) => (stopCommandPattern.test(item) ? index : -1)) + .filter(index => index >= 0); + + if (startCommandIndex === -1) { + return { + preStartCommands: normalized.filter((_, index) => !stopCommandIndexes.includes(index)), + startCommand: '', + }; + } + + return { + preStartCommands: normalized.filter((_, index) => index !== startCommandIndex && !stopCommandIndexes.includes(index)), + startCommand: normalized[startCommandIndex], + }; +} + +function buildHealthCheckScript(healthCheckUrl) { + if (!healthCheckUrl) { + return ''; + } + + let fallbackUrl = ''; + try { + const parsed = new URL(healthCheckUrl); + const hostname = String(parsed.hostname || '').toLowerCase(); + const isLocalHost = hostname === '127.0.0.1' || hostname === 'localhost'; + if (!isLocalHost) { + const port = parsed.port || '6060'; + fallbackUrl = `http://127.0.0.1:${port}${parsed.pathname || '/'}${parsed.search || ''}`; + } + } catch (error) { + fallbackUrl = 'http://127.0.0.1:6060/'; + } + + return [ + `HEALTHCHECK_URL=${quoteForBash(healthCheckUrl)}`, + ...(fallbackUrl ? [ `HEALTHCHECK_FALLBACK_URL=${quoteForBash(fallbackUrl)}` ] : []), + 'HEALTHCHECK_CURL_OPTS="--connect-timeout 2 --max-time 4"', + 'for attempt in $(seq 1 20); do', + ' if curl -fsS $HEALTHCHECK_CURL_OPTS "$HEALTHCHECK_URL" >/dev/null; then', + ' break', + ' fi', + ...(fallbackUrl ? [ ' if curl -fsS $HEALTHCHECK_CURL_OPTS "$HEALTHCHECK_FALLBACK_URL" >/dev/null; then', ' break', ' fi' ] : []), + ' if [ "$attempt" -eq 20 ]; then', + ...(fallbackUrl + ? [ ' echo "健康检查失败: $HEALTHCHECK_URL (fallback: $HEALTHCHECK_FALLBACK_URL)" >&2' ] + : [ ' echo "健康检查失败: $HEALTHCHECK_URL" >&2' ]), + ' exit 1', + ' fi', + ' sleep 1', + 'done', + ].join('\n'); +} + +function parseBackupArg(argv) { + const backupArg = argv.find(item => item.startsWith('--backup=')); + if (!backupArg) { + return ''; + } + return backupArg.slice('--backup='.length).trim(); +} + +function main() { + const envName = process.argv[2] || 'production'; + const config = loadDeployConfig(envName); + const backupName = parseBackupArg(process.argv.slice(3)); + + ensureCommandAvailable('ssh', '请先安装 OpenSSH Client 并确保 ssh 在 PATH 中。'); + + const stamp = getNowStamp(); + const cleanupGuard = buildRemoteCleanupGuard(config.sharedDirs, config.preserveDirs); + const postDeploy = splitPostDeployCommands(config.postDeployCommands); + const postDeployCommands = serializeCommands(postDeploy.preStartCommands); + const startCommand = postDeploy.startCommand; + const scopedStopCommand = buildScopedEggStopScript(config.deployRoot); + const detachedStartCommand = startCommand + ? `nohup bash -lc ${quoteForBash(startCommand)} >/tmp/wms-rollback-start.log 2>&1 &` + : ''; + const latestBackupFile = path.posix.join(config.stateDir, 'latest-backup.txt'); + const healthCheckCommand = buildHealthCheckScript(config.healthCheckUrl); + + const remoteScript = [ + 'set -euo pipefail', + `DEPLOY_ROOT=${quoteForBash(config.deployRoot)}`, + `BACKUP_DIR=${quoteForBash(config.backupDir)}`, + `LATEST_BACKUP_FILE=${quoteForBash(latestBackupFile)}`, + `REQUESTED_BACKUP=${quoteForBash(backupName)}`, + `CURRENT_SAFETY_BACKUP=${quoteForBash(`rollback-safety-${stamp}.tar.gz`)}`, + 'if [ -n "$REQUESTED_BACKUP" ]; then', + ' TARGET_BACKUP="$REQUESTED_BACKUP"', + 'elif [ -f "$LATEST_BACKUP_FILE" ]; then', + ' TARGET_BACKUP="$(cat "$LATEST_BACKUP_FILE")"', + 'else', + ' echo "未找到最近一次发布备份,请通过 --backup=backup-时间戳.tar.gz 指定回退包。" >&2', + ' exit 1', + 'fi', + 'if [ ! -f "$BACKUP_DIR/$TARGET_BACKUP" ]; then', + ' echo "回退包不存在: $BACKUP_DIR/$TARGET_BACKUP" >&2', + ' exit 1', + 'fi', + 'cd "$DEPLOY_ROOT"', + 'tar --exclude=.deploy -czf "$BACKUP_DIR/$CURRENT_SAFETY_BACKUP" .', + `find . -mindepth 1 -maxdepth 1 ${cleanupGuard} -exec rm -rf {} +`, + 'tar -xzf "$BACKUP_DIR/$TARGET_BACKUP" -C "$DEPLOY_ROOT"', + postDeployCommands, + detachedStartCommand, + healthCheckCommand, + ].filter(Boolean).join('\n'); + + try { + runSsh(config, scopedStopCommand, { stdio: 'inherit' }); + } catch (error) { + console.warn(`定点停进程失败,继续回退流程: ${error.message}`); + } + + runSsh(config, remoteScript); + console.log(`回退完成: ${envName} -> ${config.username}@${config.host}:${config.deployRoot}`); +} + +main(); \ No newline at end of file From ab26e1e8e71fccd378bb1a573c2e2ab7e43aa5ba Mon Sep 17 00:00:00 2001 From: liufumingren Date: Tue, 24 Mar 2026 23:59:59 +0800 Subject: [PATCH 008/550] =?UTF-8?q?chore:=20=E5=85=A8=E9=87=8F=E6=8F=90?= =?UTF-8?q?=E4=BA=A4=EF=BC=8C=E5=8C=85=E5=90=AB=E8=84=9A=E6=9C=AC=E3=80=81?= =?UTF-8?q?=E6=96=87=E6=A1=A3=E4=B8=8E=E9=85=8D=E7=BD=AE=E7=AD=89=E6=9C=80?= =?UTF-8?q?=E6=96=B0=E6=9B=B4=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .eslintignore | 1 + .githooks/pre-commit | 2 + .gitignore | 8 +- AI_TOOLBOX.md | 149 +++- README.md | 126 +++- app/controller/auth.js | 216 +++--- app/controller/docs.js | 4 +- app/lib/stop_current_egg.js | 148 ++++ app/model/role.js | 70 -- app/model/role_permission.js | 67 -- app/model/store.js | 75 -- app/router.js | 3 + app/service/apiMethods/user.js | 11 + app/service/system.js | 3 +- app/service/systemMethods/print.js | 674 +++++++++--------- app/service/systemMethods/user.js | 18 +- app/service/systems/auth/role_permission.js | 110 +++ app/service/systems/auth/user.js | 468 +++++++++++- app/service/systems/polo_api.js | 310 ++++---- app/service/systems/store.js | 67 ++ config/config.default.js | 19 +- config/deploy.config.example.cjs | 24 + day.log | Bin 20166 -> 30640 bytes methods/gateway.json | 54 ++ methods/system.json | 55 +- model_todo.txt | 75 +- package.json | 24 +- script/deploy-auth-check.cjs | 42 ++ script/deploy-init.cjs | 137 ++++ script/deploy-lib.cjs | 317 ++++++++ script/deploy-ops.cjs | 142 ++++ script/deploy-precheck.cjs | 57 ++ script/deploy-version.cjs | 101 +++ script/git-safety-check.cjs | 48 ++ script/model-boundary-check.cjs | 181 +++++ script/setup-git-hooks.cjs | 10 + script/version-history.cjs | 27 + script/version-record.cjs | 24 + script/version-registry.cjs | 93 +++ .../docs/METHOD_OUTPUT_REGRESSION_20260322.md | 0 .../docs/SERVICE_API_CHANGE_AUDIT_20260322.md | 96 ++- ...tion_eager_loading_n_plus_one_guideline.md | 0 .../docs/association_fix_plan.md | 0 .../docs/association_fk_consistency_report.md | 0 .../docs/association_validation_checklist.md | 0 .../docs/migration_execution_plan.md | 0 .../docs/migration_gap_list.md | 0 modelList.md => temp/docs/modelList.md | 0 .../docs/model_association_inventory.md | 0 temp/docs/model_boundary_rules.md | 105 +++ .../docs/model_cleanup_list.md | 159 +++-- .../docs/model_inventory.md | 0 .../docs/model_naming_standard.md | 0 .../docs/model_rename_map.md | 0 .../docs/rename_impact_report.md | 0 .../role_permission_fk_data_cleanup_plan.md | 0 .../docs/rollback_plan.md | 0 temp/docs/root-md-usage-report.md | 93 +++ .../docs/schema_model_gap_report.md | 0 .../docs/table_schema_inventory.md | 0 .../system.order.namespaced.test.js | 2 +- tmp-order-schema-workflow.md | 81 --- 62 files changed, 3450 insertions(+), 1046 deletions(-) create mode 100644 .githooks/pre-commit create mode 100644 app/lib/stop_current_egg.js create mode 100644 app/service/apiMethods/user.js create mode 100644 app/service/systems/auth/role_permission.js create mode 100644 config/deploy.config.example.cjs create mode 100644 methods/gateway.json create mode 100644 script/deploy-auth-check.cjs create mode 100644 script/deploy-init.cjs create mode 100644 script/deploy-lib.cjs create mode 100644 script/deploy-ops.cjs create mode 100644 script/deploy-precheck.cjs create mode 100644 script/deploy-version.cjs create mode 100644 script/git-safety-check.cjs create mode 100644 script/model-boundary-check.cjs create mode 100644 script/setup-git-hooks.cjs create mode 100644 script/version-history.cjs create mode 100644 script/version-record.cjs create mode 100644 script/version-registry.cjs rename METHOD_OUTPUT_REGRESSION_20260322.md => temp/docs/METHOD_OUTPUT_REGRESSION_20260322.md (100%) rename SERVICE_API_CHANGE_AUDIT_20260322.md => temp/docs/SERVICE_API_CHANGE_AUDIT_20260322.md (89%) rename association_eager_loading_n_plus_one_guideline.md => temp/docs/association_eager_loading_n_plus_one_guideline.md (100%) rename association_fix_plan.md => temp/docs/association_fix_plan.md (100%) rename association_fk_consistency_report.md => temp/docs/association_fk_consistency_report.md (100%) rename association_validation_checklist.md => temp/docs/association_validation_checklist.md (100%) rename migration_execution_plan.md => temp/docs/migration_execution_plan.md (100%) rename migration_gap_list.md => temp/docs/migration_gap_list.md (100%) rename modelList.md => temp/docs/modelList.md (100%) rename model_association_inventory.md => temp/docs/model_association_inventory.md (100%) create mode 100644 temp/docs/model_boundary_rules.md rename model_cleanup_list.md => temp/docs/model_cleanup_list.md (58%) rename model_inventory.md => temp/docs/model_inventory.md (100%) rename model_naming_standard.md => temp/docs/model_naming_standard.md (100%) rename model_rename_map.md => temp/docs/model_rename_map.md (100%) rename rename_impact_report.md => temp/docs/rename_impact_report.md (100%) rename role_permission_fk_data_cleanup_plan.md => temp/docs/role_permission_fk_data_cleanup_plan.md (100%) rename rollback_plan.md => temp/docs/rollback_plan.md (100%) create mode 100644 temp/docs/root-md-usage-report.md rename schema_model_gap_report.md => temp/docs/schema_model_gap_report.md (100%) rename table_schema_inventory.md => temp/docs/table_schema_inventory.md (100%) delete mode 100644 tmp-order-schema-workflow.md diff --git a/.eslintignore b/.eslintignore index 4ebc8ae..717444d 100644 --- a/.eslintignore +++ b/.eslintignore @@ -1 +1,2 @@ coverage +temp diff --git a/.githooks/pre-commit b/.githooks/pre-commit new file mode 100644 index 0000000..d428093 --- /dev/null +++ b/.githooks/pre-commit @@ -0,0 +1,2 @@ +#!/bin/sh +node script/git-safety-check.cjs \ No newline at end of file diff --git a/.gitignore b/.gitignore index 9eb7841..2ea54c3 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,8 @@ logs/ run/ -temp/ +temp/* +!temp/docs/ +!temp/docs/** node_modules/ coverage/ .nyc_output/ @@ -14,6 +16,7 @@ pnpm-debug.log* .env .env.* config/config.local.js +config/deploy.config.local.cjs database/config.json native/addons/*.node @@ -26,3 +29,6 @@ Thumbs.db *.un~ todo.txt test/.runtime/ +.deploy-state/ +versioning/* +!versioning/.gitkeep diff --git a/AI_TOOLBOX.md b/AI_TOOLBOX.md index f858e87..8f7af4f 100644 --- a/AI_TOOLBOX.md +++ b/AI_TOOLBOX.md @@ -258,16 +258,153 @@ node .\script\tmp-struct-system-params.cjs - params 的 `name/type/required/source` 完整 - 公共头部声明与实际鉴权逻辑一致 +## 10. 远程发布与回退工具 + +发布配置文件: + +- 模板:`config/deploy.config.example.cjs` +- 本地真实配置:`config/deploy.config.local.cjs` + +说明: + +- 生产目录固定为 `/www/wwwroot/qimen` +- `config/deploy.config.local.cjs` 已加入 git ignore,避免 SSH 配置误提交 +- 发布前会自动备份远端当前目录到 `/www/wwwroot/qimen/.deploy/backups/` +- 回退默认使用最近一次发布前备份 +- 发布包按 Egg.js 最小运行集自动裁剪(默认 `app.js`、`app/**`、`methods/**`、`native/addons/**`、`package*.json`) +- 发布与回退均保留远端 `config/`,不做覆盖 +- 发布与回退的停服务逻辑仅匹配当前 `deployRoot` 对应的 Egg 进程,不再用全局 `egg-scripts stop` 扫整机 + +### 10.1 固定命令入口(仅 npm script) + +执行要求: + +- 远程发布与回退只允许通过 `npm run` 执行。 +- 禁止直接运行 `node ./script/deploy-remote.cjs ...` 与 `node ./script/rollback-remote.cjs ...`。 +- `npm stop` 已改为仅停止当前目录对应的 Egg 进程,不再直接调用全局 `egg-scripts stop`。 + +标准格式: + +```powershell +# 启用仓库级 pre-commit 保护 +npm run setup:hooks + +# 只读预检(不改远端文件) +npm run deploy:precheck + +# 查询当前线上版本号 +npm run deploy:version + +# 查询最近 20 次线上版本历史 +npm run deploy:version:history + +# 查看远端 state 与备份清单 +npm run deploy:inspect + +# 对关键路由做最小连通冒烟 +npm run deploy:smoke + +# 组合执行 inspect + smoke +npm run deploy:verify + +# 按文件名清理远端失败备份 +npm run deploy:cleanup-backups -- backup-20260324202526.tar.gz backup-20260324204750.tar.gz + +# 调用 internal gateway 做 method 连通探针 +npm run deploy:gateway-probe -- releaseProbe.ping "{}" + +# 手动记录一次本地包版本快照 +npm run version:record + +# 查询本地版本历史 +npm run version:history + +# 检查暂存区是否包含禁止提交文件 +npm run guard:git + +# 发布生产环境 +npm run deploy:prod + +# 发布生产环境(短命令别名) +npm run deploy + +# 回退到最近一次备份 +npm run rollback:prod + +# 回退到最近一次备份(短命令别名) +npm run rollback + +# 指定备份包回退 +npm run rollback:prod -- --backup=backup-20260324123045.tar.gz +``` + +### 10.2 SSH 配置字段 + +- `host`:生产服务器 IP 或域名 +- `port`:SSH 端口,默认 `22` +- `username`:SSH 登录用户 +- `privateKeyPath`:本机私钥路径 +- `deployRoot`:固定为 `/www/wwwroot/qimen` +- `sharedDirs`:发布时保留目录,默认 `logs/run/temp` +- `postDeployCommands`:发布后执行命令;发布链路会强制确保包含 `npm install --production`,并自动剥离其中的通用 stop 命令,改为按当前部署目录定点停进程 + +最小发布相关可选字段: + +- `deployIncludePaths`:最小发布白名单路径(不填则使用默认最小集) +- `deployExcludePaths`:发布排除路径(默认包含 `config/**`) +- `preserveDirs`:远端覆盖时额外保留目录(默认包含 `config`) + +### 10.5 线上版本号规则与查询 + +- 版本号自动生成时机:每次执行 `npm run deploy:prod`。 +- 版本号格式:`v{package.version}-{yyyyMMddHHmmss}-{gitShortCommit}`。 +- 远端保存位置: + - 当前版本:`/www/wwwroot/qimen/.deploy/state/current-release.json` + - 历史版本:`/www/wwwroot/qimen/.deploy/state/release-history.jsonl` +- 查询命令(固定 npm script): + - 当前版本:`npm run deploy:version` + - 历史版本:`npm run deploy:version:history` + +### 10.6 本地版本管理目录(回退辅助) + +- 目录:`versioning/` +- 记录目标:每次更新的包版本号、提交号、分支、时间。 +- 自动记录:每次 `npm run deploy:prod` 成功后自动写入本地记录。 +- 手动记录:`npm run version:record` +- 本地历史查询:`npm run version:history` +- 文件: + - `versioning/package-version-current.json` + - `versioning/package-version-history.jsonl` +- git 规则:`versioning/` 的记录文件默认不提交,仅保留目录占位。 + +### 10.3 安全约束 + +- pre-commit 会阻止以下内容进入 git: + - `config/config.local.js` + - `config/deploy.config.local.cjs` + - `database/config.json` + - `temp/`、`logs/`、`run/` + - `.env*`、`.pem`、`.key` +- 真实 SSH 信息只写入本地配置文件,不写入 README、脚本或示例文件 +- 在补齐 SSH 配置前,不执行发布/回退测试 + +### 10.4 AI 安全红线(强制) + +- 明文规则:AI 禁止读取 SSH 本地配置文件 `config/deploy.config.local.cjs`。 +- AI 禁止通过任何方式展示、提取、复述该文件中的 `host`、`username`、`privateKeyPath` 等敏感内容。 +- AI 禁止把 SSH 配置写入文档、日志、日报、提交信息或任意可提交文件。 +- 如需发布/回退协助,AI 仅可提示用户“自行填写或核对该文件”,不可主动读取文件内容。 + 执行规则:接口代码与 `methods/*.json` 不一致时,以“必须补齐文档”为完成标准。 -## 10. App 能力地图(优先定位) +## 11. App 能力地图(优先定位) 能力入口文件: - `app.js` - `app/extend/application.js` -### 10.1 启动与初始化能力(app.js) +### 11.1 启动与初始化能力(app.js) - 设置应用根路径:`global.APP_ROOT`、`app.appRoot` - 启动前初始化动态工厂: @@ -278,7 +415,7 @@ node .\script\tmp-struct-system-params.cjs - `app.Message` - 全局日期格式化扩展:`Date.prototype.format('YYYY-MM-DD HH:mm:ss')` -### 10.2 Application 扩展能力(app/extend/application.js) +### 11.2 Application 扩展能力(app/extend/application.js) - 业务字典访问: - `businessDict` @@ -294,17 +431,17 @@ node .\script\tmp-struct-system-params.cjs - Message 扩展: - `Message` getter(返回 `MessageClass`) -### 10.3 AI 调试优先顺序 +### 11.3 AI 调试优先顺序 - 遇到“方法不存在/映射异常”优先检查 `app/extend/application.js` 是否包含对应能力。 - 遇到“动态分表模型不可用”优先检查 `app.js` 的工厂初始化是否执行成功。 - 遇到“缓存读写异常”优先检查 Redis client `cache` 配置及 `setCacheAsync/getCacheAsync` 调用链。 -### 10.4 AI 快速回复定义 +### 11.4 AI 快速回复定义 - 回复0时默认拒绝 - 回复1时默认接收 -## 11. Web 用户信息与切换角色测试(已验证) +## 12. Web 用户信息与切换角色测试(已验证) 目标: - 使用 `/system` 入口验证 Web 端用户信息获取与角色切换链路。 diff --git a/README.md b/README.md index 1570c76..a1c1961 100644 --- a/README.md +++ b/README.md @@ -6,8 +6,8 @@ - AI项目协作工具箱:`AI_TOOLBOX.md` - Method 路由映射说明:`AI_METHOD_ROUTING.md` -- Model 层级清单:`modelList.md` -- Method 输出一致性回归记录:`METHOD_OUTPUT_REGRESSION_20260322.md` +- Model 层级清单:`temp/docs/modelList.md` +- Method 输出一致性回归记录:`temp/docs/METHOD_OUTPUT_REGRESSION_20260322.md` - system 接口文档源:`methods/system.json` - qimen 接口文档源:`methods/qimen.json` - 日报:`day.log` @@ -40,7 +40,7 @@ - `README.md`:项目入口文档,提供整体说明与规范入口。 - `AI_TOOLBOX.md`:AI/开发协作操作手册,包含脚本与工作流。 - `AI_METHOD_ROUTING.md`:接口入口与 method 到代码文件的映射。 -- `modelList.md`:model 层级结构与关键说明清单。 +- `temp/docs/modelList.md`:model 层级结构与关键说明清单。 - `methods/system.json`:system 接口定义(headers、groups、params、response、errors)。 - `methods/qimen.json`:qimen 接口定义(按奇门协议组织)。 - `day.log`:每日工作留痕。 @@ -58,7 +58,22 @@ npm run dev - `npm run dev`:本地开发 - `npm start`:启动生产服务 -- `npm stop`:停止生产服务 +- `npm stop`:仅停止当前目录对应的 Egg 生产进程 +- `npm run deploy:prod`:按 `config/deploy.config.local.cjs` 通过 SSH 发布到生产目录 `/www/wwwroot/qimen` +- `npm run deploy:init`:首次发布初始化远端目录与 `config/` 基础文件(不覆盖已有配置) +- `npm run rollback:prod`:按最近一次备份回退生产目录(可加 `-- --backup=backup-时间戳.tar.gz` 指定备份) +- `npm run deploy:precheck`:只读预检 SSH 连通、目录权限、远端 Node/npm/tar 与健康检查,不改动远端文件 +- `npm run deploy:version`:查询当前线上版本号(读取远端 `.deploy/state/current-release.json`) +- `npm run deploy:version:history`:查询最近 20 次线上版本历史 +- `npm run deploy:inspect`:查看远端 `.deploy/state`、`latest-backup.txt` 与备份目录清单 +- `npm run deploy:smoke`:在远端机器本机对 `/`、`/api/docs`、`/internal/v1/gateway`、`/system` 做最小连通冒烟 +- `npm run deploy:verify`:组合执行 `deploy:inspect` + `deploy:smoke` +- `npm run deploy:cleanup-backups -- `:按文件名清理远端 `.deploy/backups` 中指定备份 +- `npm run deploy:gateway-probe -- [payloadJson]`:调用 `/internal/v1/gateway` 做 method 级连通探针 +- `npm run version:record`:记录一次本地包版本快照(写入 `versioning/`,用于回退追溯) +- `npm run version:history`:查询最近 50 条本地版本快照记录 +- `npm run guard:git`:检查当前暂存区是否包含禁止提交的本地机密/运行产物 +- `npm run setup:hooks`:将仓库 pre-commit hook 固化到 `.githooks/pre-commit` - `npm run lint`:代码风格检查 - `npm test`:单元测试 @@ -271,6 +286,105 @@ node .\script\method-output-regression.cjs compare - 主要配置文件在 `config/`(如 `config.default.js`、`config.local.js`、`poloapi.js`) - 数据库、Redis、平台配置在对应配置文件中维护 - 敏感信息不要提交到仓库 +- 远程发布配置模板:`config/deploy.config.example.cjs` +- 本地 SSH 发布配置:`config/deploy.config.local.cjs`(已加入 git ignore,仅本机保留) + +## 远程发布与回退(SSH) + +生产目录固定为:`/www/wwwroot/qimen` + +约定: + +- 发布脚本通过本机 `ssh/scp/tar/git` 执行,不依赖额外 npm 包。 +- 每次发布前会在服务器上生成一份当前目录备份,保存到 `/www/wwwroot/qimen/.deploy/backups/`。 +- 回退默认使用最近一次发布前备份,也支持显式传入备份名。 +- 发布和回退都会保留 `.deploy`、`logs`、`run`、`temp` 目录,避免误删运行态目录。 +- 发布与回退阶段的停服务操作只会匹配当前 `deployRoot` 对应的 Egg 进程,不再直接调用全局 `egg-scripts stop` 扫描整机进程。 + +首次配置: + +1. 完善 `config/deploy.config.local.cjs` 中的 `host`、`username`、`privateKeyPath`。 +2. 执行 `npm run setup:hooks`,启用本地 pre-commit 安全检查。 +3. 确认远端机器存在 Node.js、npm、tar,且 SSH 用户对 `/www/wwwroot/qimen` 有读写权限。 +4. 执行 `npm run deploy:init` 完成首次初始化(只在远端 `config/` 缺失或为空时写入基础文件)。 + +发布命令: + +```powershell +npm run deploy:init +npm run deploy:prod +``` + +回退命令: + +```powershell +npm run rollback:prod +npm run rollback:prod -- --backup=backup-20260324123045.tar.gz +``` + +脚本行为: + +- 发布时按 Egg.js 最小运行集打包(默认仅 `app.js`、`app/**`、`methods/**`、`native/addons/**`、`package*.json`)。 +- 打包文件来自已跟踪 git 文件(`git ls-files --cached`),不会带入本地未跟踪文件。 +- `config/` 目录不参与发布包覆盖,远端发布与回退过程都会保留现有 `config/`。 +- 首次发布若远端不存在 `config/`,发布会中止并提示先创建生产配置。 +- 默认发布后执行:`npm install --production`、定点停止当前部署目录进程、`npm start`。 +- 若配置了 `healthCheckUrl`,发布与回退后会执行一次健康检查。 +- 每次发布会自动生成线上版本号,格式:`v{package.version}-{yyyyMMddHHmmss}-{gitShortCommit}`。 +- 发布会写入版本元数据到远端: + - 当前版本:`/www/wwwroot/qimen/.deploy/state/current-release.json` + - 历史版本:`/www/wwwroot/qimen/.deploy/state/release-history.jsonl` + +版本查询命令: + +```powershell +npm run deploy:version +npm run deploy:version:history +``` + +运维检查与清理命令: + +```powershell +npm run deploy:inspect +npm run deploy:smoke +npm run deploy:verify +npm run deploy:cleanup-backups -- backup-20260324202526.tar.gz backup-20260324204750.tar.gz +npm run deploy:gateway-probe -- releaseProbe.ping "{}" +``` + +## 本地版本管理目录(回退辅助) + +目录:`versioning/` + +用途: + +- 记录每次更新时的包版本、提交号、分支、时间。 +- 部署成功后会自动追加一条记录(source=`deploy:prod`)。 +- 也可手动记录一次快照(source=`version:record`)。 + +文件: + +- `versioning/package-version-current.json`:当前最近一条本地版本记录 +- `versioning/package-version-history.jsonl`:本地版本历史(JSONL) + +说明: + +- `versioning/` 目录内容默认不提交到 git(仅保留目录占位)。 +- 回退前可先通过本地历史快速定位目标版本,再结合远端备份名执行回退。 + +本地命令: + +```powershell +# 手动记录一次本地版本快照 +npm run version:record + +# 查询本地版本历史 +npm run version:history +``` + +当前等待项: + +- 由于 SSH 目标主机、账号、私钥路径仍是占位值,完成这些字段前不要执行发布/回退测试。 ## App 能力清单(汇总) @@ -358,7 +472,9 @@ node .\script\method-output-regression.cjs compare - 数据库/Redis 连接失败优先检查 `config/config.local.js` - 接口路由映射可查阅 `AI_METHOD_ROUTING.md` - native addon 加载失败(`ERR_DLOPEN_FAILED`)时,优先检查 Node 版本与 addon 构建目标是否一致 - +- `npm run deploy:prod` 提示 SSH 配置未完善时,先补齐 `config/deploy.config.local.cjs` 中的 `host/username/privateKeyPath` +- `npm run guard:git` 或 pre-commit 拦截提交时,说明暂存区包含本地机密文件或运行产物 +- system接口的日志在数据库wms中的表wms_system_log ## 日报维护 - 日报统一记录在 `day.log` diff --git a/app/controller/auth.js b/app/controller/auth.js index a7c51ab..8c270af 100644 --- a/app/controller/auth.js +++ b/app/controller/auth.js @@ -4,115 +4,115 @@ const Controller = require('egg').Controller; class AuthController extends Controller { - async printerSetting() { - const { ctx } = this; - const redis = this.app.redis; - if (ctx.method === 'GET') { - const code = ctx.params.code || ''; - if (!code) { - ctx.body = { error: '缺少code参数' }; - return; - } - const bindValue = await redis.get('printer').get(`bind:${code}`); - if (!bindValue) { - ctx.body = { error: '无效code或未绑定' }; - return; - } - await redis.get('printer').setex(`binding:${code}`, 300, bindValue); - await ctx.render('printer_setting.html', { - title: '打印台设置', - code, - bindValue, - }); - } else if (ctx.method === 'POST') { - const { code, printer, warehouse } = ctx.request.body; - if (!code || !printer || !warehouse) { - ctx.body = { success: false, error: '参数缺失' }; - return; - } - // 获取临时binding:code - const bindingValue = await redis.get('printer').get(`binding:${code}`); - if (!bindingValue) { - ctx.body = { success: false, error: '超时或未绑定' }; - return; - } - // 反序列化bindingValue - let bindingValueObj = bindingValue; - try { - bindingValueObj = JSON.parse(bindingValue); - } catch (e) { - bindingValueObj = bindingValue; - } - // 使用 Store model 校验仓库id - const Store = ctx.model.Store; - const warehouseInfo = await Store.findOne({ where: { id: warehouse } }); - console.log('warehouseInfo:', warehouseInfo); - if (!warehouseInfo || warehouseInfo.project !== 'warehouse') { - ctx.body = { success: false, error: '仓库id校验失败' }; - return; - } - // 查找仓库id下是否有重名的电脑 - const PrintComputer = ctx.model.PrintComputer; - let computerId = null; - const existComputer = await PrintComputer.findOne({ where: { warehouse_id: warehouse, name: printer } }); - if (existComputer) { - if (existComputer.status === 1) { - ctx.body = { success: false, error: '该仓库下打印台名称已存在且可用' }; - return; - } else { - computerId = existComputer.id; - } - } else { - // 创建新打印电脑 - console.log('创建新打印电脑:', { warehouse_id: warehouse, name: printer, status: 0 }); - const newComputer = await PrintComputer.create({ warehouse_id: warehouse, name: printer, status: 0 }); - console.log('newComputer:', newComputer); - computerId = newComputer.id; - } - // 调用打印服务 /auth/bind,使用egg内置curl - const printServiceUrl = ctx.app.config.printService.url; - let printServiceResult = null; - try { - const res = await ctx.curl(`${printServiceUrl}/auth/bind`, { - method: 'POST', - contentType: 'json', - data: { code, printer, warehouse, roomId: bindingValueObj.uniqueId, computerId }, - dataType: 'json', - }); - printServiceResult = res.data; - } catch (err) { - console.log('调用打印服务失败:', err); - printServiceResult = { success: false, error: '打印服务通讯失败' }; - } - console.log('printServiceResult:', printServiceResult); - // 判断打印服务返回结果 - if (printServiceResult && printServiceResult.status === 'fail') { - ctx.body = { - success: false, - msg: printServiceResult.message || '打印服务失败', - code, - printer, - warehouse, - bindingValue: bindingValueObj, - printServiceResult - }; - return; - } - console.log('printServiceResult:', printServiceResult); - ctx.body = { - success: true, - msg: '参数已接收', - code, - printer, - warehouse, - bindingValue: bindingValueObj, - computerId, - printServiceResult - }; - } else { - ctx.body = { msg: '不支持的请求方法' }; + async printerSetting() { + const { ctx } = this; + const redis = this.app.redis; + if (ctx.method === 'GET') { + const code = ctx.params.code || ''; + if (!code) { + ctx.body = { error: '缺少code参数' }; + return; + } + const bindValue = await redis.get('printer').get(`bind:${code}`); + if (!bindValue) { + ctx.body = { error: '无效code或未绑定' }; + return; + } + await redis.get('printer').setex(`binding:${code}`, 300, bindValue); + await ctx.render('printer_setting.html', { + title: '打印台设置', + code, + bindValue, + }); + } else if (ctx.method === 'POST') { + const { code, printer, warehouse } = ctx.request.body; + if (!code || !printer || !warehouse) { + ctx.body = { success: false, error: '参数缺失' }; + return; + } + // 获取临时binding:code + const bindingValue = await redis.get('printer').get(`binding:${code}`); + if (!bindingValue) { + ctx.body = { success: false, error: '超时或未绑定' }; + return; + } + // 反序列化bindingValue + let bindingValueObj = bindingValue; + try { + bindingValueObj = JSON.parse(bindingValue); + } catch (e) { + bindingValueObj = bindingValue; + } + // 使用 Store model 校验仓库id + const Store = ctx.model.Store; + const warehouseInfo = await Store.findOne({ where: { id: warehouse } }); + console.log('warehouseInfo:', warehouseInfo); + if (!warehouseInfo || warehouseInfo.project !== 'warehouse') { + ctx.body = { success: false, error: '仓库id校验失败' }; + return; + } + // 查找仓库id下是否有重名的电脑 + const PrintComputer = ctx.model.PrintComputer; + let computerId = null; + const existComputer = await PrintComputer.findOne({ where: { warehouse_id: warehouse, name: printer } }); + if (existComputer) { + if (existComputer.status === 1) { + ctx.body = { success: false, error: '该仓库下打印台名称已存在且可用' }; + return; } + computerId = existComputer.id; + + } else { + // 创建新打印电脑 + console.log('创建新打印电脑:', { warehouse_id: warehouse, name: printer, status: 0 }); + const newComputer = await PrintComputer.create({ warehouse_id: warehouse, name: printer, status: 0 }); + console.log('newComputer:', newComputer); + computerId = newComputer.id; + } + // 调用打印服务 /auth/bind,使用egg内置curl + const printServiceUrl = ctx.app.config.printService.url; + let printServiceResult = null; + try { + const res = await ctx.curl(`${printServiceUrl}/auth/bind`, { + method: 'POST', + contentType: 'json', + data: { code, printer, warehouse, roomId: bindingValueObj.uniqueId, computerId }, + dataType: 'json', + }); + printServiceResult = res.data; + } catch (err) { + console.log('调用打印服务失败:', err); + printServiceResult = { success: false, error: '打印服务通讯失败' }; + } + console.log('printServiceResult:', printServiceResult); + // 判断打印服务返回结果 + if (printServiceResult && printServiceResult.status === 'fail') { + ctx.body = { + success: false, + msg: printServiceResult.message || '打印服务失败', + code, + printer, + warehouse, + bindingValue: bindingValueObj, + printServiceResult, + }; + return; + } + console.log('printServiceResult:', printServiceResult); + ctx.body = { + success: true, + msg: '参数已接收', + code, + printer, + warehouse, + bindingValue: bindingValueObj, + computerId, + printServiceResult, + }; + } else { + ctx.body = { msg: '不支持的请求方法' }; } + } } -module.exports = AuthController; \ No newline at end of file +module.exports = AuthController; diff --git a/app/controller/docs.js b/app/controller/docs.js index c612e21..c55aa79 100644 --- a/app/controller/docs.js +++ b/app/controller/docs.js @@ -940,7 +940,9 @@ class DocsController extends Controller { const docData = JSON.parse(content); const groups = normalizeGroups(docData); - const entryPath = docData.module === 'qimen' ? '/qimen' : '/system'; + const entryPath = docData.module === 'qimen' + ? '/qimen' + : (docData.module === 'gateway' ? '/internal/v1/gateway' : '/system'); const html = renderHtmlPage({ docName, docData, diff --git a/app/lib/stop_current_egg.js b/app/lib/stop_current_egg.js new file mode 100644 index 0000000..8cd7824 --- /dev/null +++ b/app/lib/stop_current_egg.js @@ -0,0 +1,148 @@ +'use strict'; + +const { execFileSync } = require('node:child_process'); + +const isWin = process.platform === 'win32'; +const appRoot = process.cwd(); + +function sleep(ms) { + return new Promise(resolve => setTimeout(resolve, ms)); +} + +function listNodeProcesses() { + if (isWin) { + try { + const output = execFileSync('wmic', [ 'Path', 'win32_process', 'Where', "Name = 'node.exe'", 'Get', 'CommandLine,ProcessId' ], { + encoding: 'utf8', + stdio: [ 'ignore', 'pipe', 'pipe' ], + }); + + return output + .split(/\r?\n/) + .map(line => line.trim()) + .filter(Boolean) + .map(line => { + const match = line.match(/^(.*)\s+(\d+)$/); + if (!match) { + return null; + } + return { + pid: Number(match[2]), + cmd: match[1], + }; + }) + .filter(Boolean); + } catch (error) { + if (error.code !== 'ENOENT') { + throw error; + } + + const output = execFileSync('powershell', [ + '-NoProfile', + '-Command', + "Get-CimInstance Win32_Process -Filter \"Name='node.exe'\" | Select-Object ProcessId, CommandLine | ConvertTo-Json -Compress", + ], { + encoding: 'utf8', + stdio: [ 'ignore', 'pipe', 'pipe' ], + }).trim(); + + if (!output) { + return []; + } + + const parsed = JSON.parse(output); + const items = Array.isArray(parsed) ? parsed : [ parsed ]; + return items + .map(item => ({ + pid: Number(item.ProcessId), + cmd: String(item.CommandLine || ''), + })) + .filter(item => item.pid && item.cmd); + } + } + + const output = execFileSync('ps', [ '-eo', 'pid=,args=' ], { + encoding: 'utf8', + stdio: [ 'ignore', 'pipe', 'pipe' ], + }); + + return output + .split(/\r?\n/) + .map(line => line.trim()) + .filter(Boolean) + .map(line => { + const match = line.match(/^(\d+)\s+(.*)$/); + if (!match) { + return null; + } + return { + pid: Number(match[1]), + cmd: match[2], + }; + }) + .filter(Boolean); +} + +function isMasterProcess(cmd) { + return cmd.includes('start-cluster'); +} + +function isWorkerProcess(cmd) { + return cmd.includes('egg-cluster/lib/app_worker.js') + || cmd.includes('egg-cluster/lib/agent_worker.js') + || cmd.includes('egg-cluster\\lib\\app_worker.js') + || cmd.includes('egg-cluster\\lib\\agent_worker.js'); +} + +function matchesCurrentApp(processInfo) { + if (!processInfo || !processInfo.cmd || !processInfo.pid) { + return false; + } + + if (processInfo.pid === process.pid) { + return false; + } + + return processInfo.cmd.includes(appRoot) && (isMasterProcess(processInfo.cmd) || isWorkerProcess(processInfo.cmd)); +} + +function killPids(pids, signal) { + for (const pid of pids) { + try { + process.kill(pid, signal); + } catch (error) { + if (error.code !== 'ESRCH') { + throw error; + } + } + } +} + +async function main() { + const processList = listNodeProcesses().filter(matchesCurrentApp); + const masterPids = processList.filter(item => isMasterProcess(item.cmd)).map(item => item.pid); + const workerPids = processList.filter(item => isWorkerProcess(item.cmd)).map(item => item.pid); + + if (masterPids.length > 0) { + console.log(`stopping current egg masters: ${masterPids.join(', ')}`); + killPids(masterPids, 'SIGTERM'); + await sleep(5000); + } else { + console.log('no current egg master process found'); + } + + const remainingWorkers = listNodeProcesses() + .filter(matchesCurrentApp) + .filter(item => isWorkerProcess(item.cmd)) + .map(item => item.pid); + + if (remainingWorkers.length > 0) { + console.log(`killing remaining current egg workers: ${remainingWorkers.join(', ')}`); + killPids(remainingWorkers, 'SIGKILL'); + } +} + +main().catch(error => { + console.error(error.message || error); + process.exitCode = 1; +}); \ No newline at end of file diff --git a/app/model/role.js b/app/model/role.js index f065bd1..16d2af5 100644 --- a/app/model/role.js +++ b/app/model/role.js @@ -195,75 +195,5 @@ module.exports = app => { return this.scope === 1 ? '全局' : '指定仓库'; }; - // 实例方法:为角色分配权限 - Role.prototype.assignPermissions = async function(permissionIds) { - const { ctx } = this; - - // 先清除现有权限 - await ctx.model.RolePermission.destroy({ - where: { role_id: this.id }, - }); - - // 批量添加新权限 - if (permissionIds && permissionIds.length > 0) { - const rolePermissions = permissionIds.map(permissionId => ({ - role_id: this.id, - permission_id: permissionId, - })); - - await ctx.model.RolePermission.bulkCreate(rolePermissions); - } - - return true; - }; - - // 实例方法:获取角色的所有权限(树形结构) - Role.prototype.getPermissionTree = async function(permissionType = null) { - const { ctx } = this; - - const rolePermissions = await ctx.model.RolePermission.findAll({ - where: { role_id: this.id }, - include: [{ - model: ctx.model.Permission, - as: 'permission', - where: { status: 1 }, - required: true, - }], - }); - - // 提取权限ID - const permissionIds = rolePermissions.map(rp => rp.permission.id); - - // 获取权限详情 - const where = { - id: permissionIds, - status: 1, - }; - - if (permissionType) { - where.type = permissionType; - } - - const permissions = await ctx.model.Permission.findAll({ - where, - order: [[ 'sort', 'ASC' ], [ 'id', 'ASC' ]], - }); - - // 构建树形结构 - return ctx.model.Permission.buildPermissionTree(permissions); - }; - - // 实例方法:获取角色的权限ID列表 - Role.prototype.getPermissionIds = async function() { - const { ctx } = this; - - const rolePermissions = await ctx.model.RolePermission.findAll({ - where: { role_id: this.id }, - attributes: [ 'permission_id' ], - }); - - return rolePermissions.map(rp => rp.permission_id); - }; - return Role; }; diff --git a/app/model/role_permission.js b/app/model/role_permission.js index 6a3e906..1bfd6aa 100644 --- a/app/model/role_permission.js +++ b/app/model/role_permission.js @@ -74,72 +74,5 @@ module.exports = app => { return this.role_id && this.permission_id; }; - // 类方法:批量创建角色权限关联 - RolePermission.bulkAssign = async function(roleId, permissionIds) { - const { ctx } = this; - - if (!permissionIds || permissionIds.length === 0) { - return []; - } - - const rolePermissions = permissionIds.map(permissionId => ({ - role_id: roleId, - permission_id: permissionId, - })); - - try { - return await ctx.model.RolePermission.bulkCreate(rolePermissions, { - ignoreDuplicates: true, // 忽略重复项 - }); - } catch (error) { - // 处理批量创建中的错误 - console.error('批量创建角色权限关联失败:', error); - throw error; - } - }; - - // 类方法:删除角色的所有权限 - RolePermission.clearRolePermissions = async function(roleId) { - const { ctx } = this; - - return await ctx.model.RolePermission.destroy({ - where: { role_id: roleId }, - }); - }; - - // 类方法:获取角色的权限列表 - RolePermission.getRolePermissions = async function(roleId, includePermissionDetails = false) { - const { ctx } = this; - - const options = { - where: { role_id: roleId }, - }; - - if (includePermissionDetails) { - options.include = [{ - model: ctx.model.Permission, - as: 'permission', - where: { status: 1 }, - required: false, - }]; - } - - return await ctx.model.RolePermission.findAll(options); - }; - - // 类方法:检查角色是否拥有某个权限 - RolePermission.hasPermission = async function(roleId, permissionId) { - const { ctx } = this; - - const rolePermission = await ctx.model.RolePermission.findOne({ - where: { - role_id: roleId, - permission_id: permissionId, - }, - }); - - return !!rolePermission; - }; - return RolePermission; }; diff --git a/app/model/store.js b/app/model/store.js index 3453d8e..a3839a2 100644 --- a/app/model/store.js +++ b/app/model/store.js @@ -246,80 +246,5 @@ module.exports = app => { return emailRegex.test(this.contact_email); }; - // 类方法:根据账号ID查找商家 - Store.findByAccountId = async function(accountId) { - return await this.findOne({ - where: { - account_id: accountId, - status: 1, - }, - }); - }; - - // 类方法:获取所有启用的商家 - Store.findAllEnabled = async function() { - return await this.findAll({ - where: { - status: 1, - }, - order: [[ 'company_name', 'ASC' ]], - }); - }; - - // 类方法:获取所有仓库类型的商家 - Store.findAllWarehouses = async function() { - return await this.findAll({ - where: { - status: 1, - project: 'warehouse', - }, - order: [[ 'company_name', 'ASC' ]], - }); - }; - - // 类方法:检查公司名称是否存在 - Store.checkCompanyNameExists = async function(companyName, excludeId = null) { - const where = { - company_name: companyName, - }; - - if (excludeId) { - where.id = { - [app.Sequelize.Op.ne]: excludeId, - }; - } - - const store = await this.findOne({ where }); - return !!store; - }; - - // 类方法:创建商家时的数据验证 - Store.validateStoreData = function(data) { - const errors = []; - - // 必填字段检查 - const requiredFields = [ 'company_name', 'contact_person', 'contact_phone' ]; - for (const field of requiredFields) { - if (!data[field]) { - errors.push(`${field} 不能为空`); - } - } - - // 公司名称长度检查 - if (data.company_name && (data.company_name.length < 1 || data.company_name.length > 200)) { - errors.push('公司名称长度应在1-200个字符之间'); - } - - // 邮箱格式检查(如果提供了邮箱) - if (data.contact_email && data.contact_email.trim() !== '') { - const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; - if (!emailRegex.test(data.contact_email)) { - errors.push('联系邮箱格式不正确'); - } - } - - return errors; - }; - return Store; }; diff --git a/app/router.js b/app/router.js index b048e27..2fab394 100644 --- a/app/router.js +++ b/app/router.js @@ -5,6 +5,9 @@ module.exports = app => { const { router, controller } = app; router.get('/', controller.home.index); + // 内部网关接口 + router.post('/internal/v1/gateway', controller.gateway.internal); + // 奇门接口 router.post('/qimen', controller.home.qimen); diff --git a/app/service/apiMethods/user.js b/app/service/apiMethods/user.js new file mode 100644 index 0000000..fabcc1c --- /dev/null +++ b/app/service/apiMethods/user.js @@ -0,0 +1,11 @@ +'use strict'; + +const Service = require('egg').Service; + +class UserApiService extends Service { + async getUserByTempCode(data) { + return await this.ctx.service.systems.auth.user.getUserByTempCode(data); + } +} + +module.exports = UserApiService; \ No newline at end of file diff --git a/app/service/system.js b/app/service/system.js index 5a4c0ea..02fd9eb 100644 --- a/app/service/system.js +++ b/app/service/system.js @@ -4,7 +4,8 @@ const Service = require('egg').Service; const { XMLParser } = require('fast-xml-parser'); const ALLOWED_PLATFORMS = new Set([ 'web', 'pda', 'app', 'wx', 'miniprogram', 'other' ]); -const ALLOWED_PROJECTS = new Set([ 'all', 'wms', 'tms', 'scm', 'other' ]); +// project: all=全部, warehouse=仓库, store=货主, tms=物流 +const ALLOWED_PROJECTS = new Set([ 'all', 'warehouse', 'store', 'tms', 'wms', 'scm', 'other' ]); class systemService extends Service { async callMethod(className, actionName, requestData, authHeader) { diff --git a/app/service/systemMethods/print.js b/app/service/systemMethods/print.js index f7d7f3e..8b32985 100644 --- a/app/service/systemMethods/print.js +++ b/app/service/systemMethods/print.js @@ -1,6 +1,5 @@ 'use strict'; -const { up } = require('../../../database/migrations/20251109160640-init-wms_account'); // 打印相关 Service const MainService = require('../main'); @@ -9,59 +8,59 @@ const MainService = require('../main'); * 参考 indexService 初始化方式,后续可扩展具体业务函数 */ class PrintService extends MainService { - constructor(ctx) { - super(ctx); - // 初始化免登录、免权限、免日志、免认证等配置 - const _noNeedLogin = ''; - const _noNeedRight = '*'; - const _noNeedLog = ''; - const _noNeedAuth = '*'; - this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); - this.defaultComponents = [ - { name: '抖音', port: '13888' }, - { name: '拼多多', port: '5000' }, - { name: '快手', port: '16888/ks/printer' }, - { name: '京东', port: '9113' }, - { name: '菜鸟', port: '13528' }, - { name: '视频号', port: '12705' }, - { name: '小红书', port: '10818' }, - { name: 'LODOP', port: '8000' } - ]; + constructor(ctx) { + super(ctx); + // 初始化免登录、免权限、免日志、免认证等配置 + const _noNeedLogin = ''; + const _noNeedRight = '*'; + const _noNeedLog = ''; + const _noNeedAuth = '*'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + this.defaultComponents = [ + { name: '抖音', port: '13888' }, + { name: '拼多多', port: '5000' }, + { name: '快手', port: '16888/ks/printer' }, + { name: '京东', port: '9113' }, + { name: '菜鸟', port: '13528' }, + { name: '视频号', port: '12705' }, + { name: '小红书', port: '10818' }, + { name: 'LODOP', port: '8000' }, + ]; - } - async send(_data) { - const { ctx } = this; - const warehouseId = ctx.user.store_id; - const { printer, type, template, data, computerId, timestamp, count } = _data; - console.log('send to computer', warehouseId, printer, type, template, data, computerId, timestamp, count); - //生成打印编号并记录到数据库 - const printRecord = await ctx.model.PrintRecord.create({ - warehouse_id: warehouseId, - computer_id: computerId, - printer, - type, - data: { template, data }, - status: 'pending' - }); - //处理后的数据 - let processedData = {}; - switch (type) { - case "customize": - const { page_width, page_height, template_content } = template; - let htm = ``; - for (const item of template_content) { - let content = item.content; + } + async send(_data) { + const { ctx } = this; + const warehouseId = ctx.user.store_id; + const { printer, type, template, data, computerId, timestamp, count } = _data; + console.log('send to computer', warehouseId, printer, type, template, data, computerId, timestamp, count); + // 生成打印编号并记录到数据库 + const printRecord = await ctx.model.PrintRecord.create({ + warehouse_id: warehouseId, + computer_id: computerId, + printer, + type, + data: { template, data }, + status: 'pending', + }); + // 处理后的数据 + let processedData = {}; + switch (type) { + case 'customize': { + const { page_width, page_height, template_content } = template; + let htm = ``; + for (const item of template_content) { + let content = item.content; - for(const key in data) { - console.log("正在匹配字段:", key, "与", item.field_code); - if(item.field_code == key) { - content = data[key]; - } - } - console.log("转后的内容:", content); - switch (item.type) { - case "text": - htm += `

${content}
`; - break; - case "image": - htm += ``; - break; - case "barcode": - htm += `
`; - break; - case "qrcode": - let toUrl = `https://ye4s.wms.gztbyc.com/to/${content}`; - //转换成urlencode - toUrl = encodeURIComponent(toUrl); - let url = `https://ye4s.wms.gztbyc.com/qrcode/build?text=${toUrl}`; + ">`; + break; + case 'qrcode': { + let toUrl = `https://ye4s.wms.gztbyc.com/to/${content}`; + // 转换成urlencode + toUrl = encodeURIComponent(toUrl); + const url = `https://ye4s.wms.gztbyc.com/qrcode/build?text=${toUrl}`; - htm += `
`; - break; - case "line": - htm += `
`; - break; - case "rectangle": - htm += `
`; - break; - case "table": - let tableHtml = ``; - for (let i = 0; i < item.rows; i++) { - tableHtml += ``; - for (let j = 0; j < item.columns; j++) { - let content = item.content[i] && item.content[i][j] ? item.content[i][j] : ''; - tableHtml += ``; - } tableHtml += ``; - } tableHtml += `
${content}
`; - htm += tableHtml; - break; - } - } - htm += ``; - processedData = { - pageWidth: page_width, - pageHeight: page_height, - htm: htm, - lodopkey:["","13528A153BAEE3A0254B9507DCDE2839","EDE92F75B6A3D917F65910","D60BC84D7CF2DE18156A6F88987304CB6D8"] - } - break; - case "express": - break; + break; + case 'table': { + let tableHtml = ``; + for (let i = 0; i < item.rows; i++) { + tableHtml += ''; + for (let j = 0; j < item.columns; j++) { + const content = item.content[i] && item.content[i][j] ? item.content[i][j] : ''; + tableHtml += ``; + } tableHtml += ''; + } tableHtml += '
${content}
'; + htm += tableHtml; + break; + } default: - return this.fail('不支持的打印类型', 1001); + break; + } } - - const printData = { - printer, - type, - template, - data: processedData, - timestamp, - count, - printId: printRecord.id + htm += ''; + processedData = { + pageWidth: page_width, + pageHeight: page_height, + htm, + lodopkey: [ '', '13528A153BAEE3A0254B9507DCDE2839', 'EDE92F75B6A3D917F65910', 'D60BC84D7CF2DE18156A6F88987304CB6D8' ], }; - const res = await this.service.systems.print.index.sendToComputer({warehouse:warehouseId, computerId: computerId, data:printData}); - console.log('sendToComputer response', res); - //发送成功后更新打印记录状态 - if (res.status=="success") { - await printRecord.update({ status: 'sent' }); - return this.success('发送打印任务成功', { code: 200, printId: printRecord.id }); - } else { - await printRecord.update({ status: 'failed', error_message: res.error }); - return this.fail(res.error, { code: 504, printId: printRecord.id }); - } + break; + } + case 'express': + break; + default: + return this.fail('不支持的打印类型', 1001); } - async getPrintResult(data) { - const { ctx } = this; - const warehouseId = ctx.user.store_id; - const { printId } = data; - if (!printId) return this.fail('参数错误', 1001); - const record = await ctx.model.PrintRecord.findOne({ where: { id: printId, warehouse_id: warehouseId }, raw: true }); - if (!record) return this.fail('打印记录不存在', 1002); - return this.success('success', { ...record, code: 0 }); + + const printData = { + printer, + type, + template, + data: processedData, + timestamp, + count, + printId: printRecord.id, + }; + const res = await this.service.systems.print.index.sendToComputer({ warehouse: warehouseId, computerId, data: printData }); + console.log('sendToComputer response', res); + // 发送成功后更新打印记录状态 + if (res.status === 'success') { + await printRecord.update({ status: 'sent' }); + return this.success('发送打印任务成功', { code: 200, printId: printRecord.id }); } - async getPrintRecordItem(data) { - const { ctx } = this; - const warehouseId = ctx.user.store_id; - const { id } = data; - if (!id) return this.fail('参数错误', 1001); - const item = await ctx.model.PrintRecord.findOne({ where: { id, warehouse_id: warehouseId }, raw: true }); - if (!item) return this.fail('打印记录不存在', 1002); - return this.success('success', { ...item, code: 0 }); - } - /** + await printRecord.update({ status: 'failed', error_message: res.error }); + return this.fail(res.error, { code: 504, printId: printRecord.id }); + + } + async getPrintResult(data) { + const { ctx } = this; + const warehouseId = ctx.user.store_id; + const { printId } = data; + if (!printId) return this.fail('参数错误', 1001); + const record = await ctx.model.PrintRecord.findOne({ where: { id: printId, warehouse_id: warehouseId }, raw: true }); + if (!record) return this.fail('打印记录不存在', 1002); + return this.success('success', { ...record, code: 0 }); + } + async getPrintRecordItem(data) { + const { ctx } = this; + const warehouseId = ctx.user.store_id; + const { id } = data; + if (!id) return this.fail('参数错误', 1001); + const item = await ctx.model.PrintRecord.findOne({ where: { id, warehouse_id: warehouseId }, raw: true }); + if (!item) return this.fail('打印记录不存在', 1002); + return this.success('success', { ...item, code: 0 }); + } + /** * 1. 查询打印台列表 * @param {Object} data { page, pageSize, where } */ - async getList(data) { - const { ctx } = this; - console.log("ctx.user in PrintService constructor", ctx.user); - const warehouse_id = ctx.user.store_id; - // TODO: 需根据实际分页和条件查询调整 - const { page = 1, pageSize = 20, where = {} } = data; - // 字段过滤 - const filter = {}; - ['id', 'name', 'computer_id', 'custom_barcode'].forEach(key => { - if (where[key]) filter[key] = where[key]; - }); - filter.warehouse_id = warehouse_id; - filter.deleted = 0; - // 查询总数 - console.log("ctx.model.PrintStations", ctx.model.PrintStations); - const total = await ctx.model.PrintStations.count({ where: filter }); - // 查询分页数据 - const list = await ctx.model.PrintStations.findAll({ - where: filter, - offset: (page - 1) * pageSize, - limit: pageSize, - order: [['create_at', 'DESC']], - raw: true, - }); - let computers = list.map(item => { - const computer = { - id: item.computer_id, - is_online: 0, - components: this.defaultComponents.map(component => ({ - name: component.name, - is_online: 0, - })) - }; - return computer; - }); - // 动态属性处理(如 is_online、components) - for (let i = 0; i < computers.length; i++) { - let key = `warehouse:${warehouse_id}:printer:${computers[i].id}`; - const computerInfo = await this.app.redis.get("printer").get(key); - console.log("key and computerInfo", key, computerInfo); - if (computerInfo) { - computers[i].is_online = 1; - computers[i].components = await Promise.all(computers[i].components.map(async component => { - const componentKey = `printer:${computers[i].id}:name:${component.name}:status`; - const componentInfo = await this.app.redis.get("printer").get(componentKey); - console.log("componentKey and componentInfo", componentKey, componentInfo); - if (componentInfo && componentInfo == "connected") { - component.is_online = 1; - } - return component; - })); - } - } - - for (const item of list) { - const computer = computers.find(c => c.id === item.computer_id); - item.is_online = computer ? computer.is_online : 0; - item.components = computer ? computer.components : this.defaultComponents.map(component => ({ - name: component.name, - is_online: 0, - })); - } - const result = { - code: 200, - data: { - list: list, - pagination: { - hasNext: page * pageSize < total, - hasPrevious: page > 1, - page: page, - pageSize: pageSize, - total: total, - totalPages: Math.ceil(total / pageSize), - }, - queryInfo: { - conditions: where, - hasBarcodeSearch: false, - sortField: 'id', - sortOrder: "DESC" - }, - summary: { - total_available: total, - total_items: pageSize, - total_locked: 0, - total_quantity: 0 - } - } - } - return this.success('success', result); + async getList(data) { + const { ctx } = this; + console.log('ctx.user in PrintService constructor', ctx.user); + const warehouse_id = ctx.user.store_id; + // TODO: 需根据实际分页和条件查询调整 + const { page = 1, pageSize = 20, where = {} } = data; + // 字段过滤 + const filter = {}; + [ 'id', 'name', 'computer_id', 'custom_barcode' ].forEach(key => { + if (where[key]) filter[key] = where[key]; + }); + filter.warehouse_id = warehouse_id; + filter.deleted = 0; + // 查询总数 + console.log('ctx.model.PrintStations', ctx.model.PrintStations); + const total = await ctx.model.PrintStations.count({ where: filter }); + // 查询分页数据 + const list = await ctx.model.PrintStations.findAll({ + where: filter, + offset: (page - 1) * pageSize, + limit: pageSize, + order: [[ 'create_at', 'DESC' ]], + raw: true, + }); + const computers = list.map(item => { + const computer = { + id: item.computer_id, + is_online: 0, + components: this.defaultComponents.map(component => ({ + name: component.name, + is_online: 0, + })), + }; + return computer; + }); + // 动态属性处理(如 is_online、components) + for (let i = 0; i < computers.length; i++) { + const key = `warehouse:${warehouse_id}:printer:${computers[i].id}`; + const computerInfo = await this.app.redis.get('printer').get(key); + console.log('key and computerInfo', key, computerInfo); + if (computerInfo) { + computers[i].is_online = 1; + computers[i].components = await Promise.all(computers[i].components.map(async component => { + const componentKey = `printer:${computers[i].id}:name:${component.name}:status`; + const componentInfo = await this.app.redis.get('printer').get(componentKey); + console.log('componentKey and componentInfo', componentKey, componentInfo); + if (componentInfo && componentInfo === 'connected') { + component.is_online = 1; + } + return component; + })); + } } - /** + for (const item of list) { + const computer = computers.find(c => c.id === item.computer_id); + item.is_online = computer ? computer.is_online : 0; + item.components = computer ? computer.components : this.defaultComponents.map(component => ({ + name: component.name, + is_online: 0, + })); + } + const result = { + code: 200, + data: { + list, + pagination: { + hasNext: page * pageSize < total, + hasPrevious: page > 1, + page, + pageSize, + total, + totalPages: Math.ceil(total / pageSize), + }, + queryInfo: { + conditions: where, + hasBarcodeSearch: false, + sortField: 'id', + sortOrder: 'DESC', + }, + summary: { + total_available: total, + total_items: pageSize, + total_locked: 0, + total_quantity: 0, + }, + }, + }; + return this.success('success', result); + } + + /** * 2. 获取单个打印台 * @param {Object} data { id } */ - async getItem(data) { - const { ctx } = this; - const { id } = data; - if (!id) return this.fail('参数错误', 1001); - const item = await ctx.model.PrintStations.findOne({ where: { id }, raw: true }); - if (!item) return this.fail('打印台不存在', 1002); - return this.success('success', { ...item, code: 0 }); - } - /** + async getItem(data) { + const { ctx } = this; + const { id } = data; + if (!id) return this.fail('参数错误', 1001); + const item = await ctx.model.PrintStations.findOne({ where: { id }, raw: true }); + if (!item) return this.fail('打印台不存在', 1002); + return this.success('success', { ...item, code: 0 }); + } + /** * 3. 添加打印台 * @param {Object} data { id, name, computer_id, custom_barcode } */ - async add(data) { - const { ctx } = this; - const warehouse_id = ctx.user.store_id; - const { name, computer_id, custom_barcode } = data; - if (!name || !computer_id) return this.fail('参数错误', 1001); - const newItem = await ctx.model.PrintStations.create({ - warehouse_id, - name, - computer_id, - custom_barcode, - creator_id: ctx.user?.employees_id || '', - creator_name: ctx.user?.employees_name || '', - default_printer_name: data.default_printer_name || '', - create_at: new Date(), - update_at: new Date(), - deleted: 0, - }); - return this.success('添加打印台成功', { data: newItem, code: 0 }); - } - async hasName(data) { - const { ctx } = this; - const warehouse_id = ctx.user.store_id; - const { name, id } = data; - if (!name) return this.fail('参数错误', 1001); - const item = await ctx.model.PrintStations.findOne({ where: { name, warehouse_id, id: { [ctx.model.Sequelize.Op.ne]: id } }, raw: true }); - return this.success('success', { exists: !!item, code: 0 }); - } - /** + async add(data) { + const { ctx } = this; + const warehouse_id = ctx.user.store_id; + const { name, computer_id, custom_barcode } = data; + if (!name || !computer_id) return this.fail('参数错误', 1001); + const newItem = await ctx.model.PrintStations.create({ + warehouse_id, + name, + computer_id, + custom_barcode, + creator_id: ctx.user?.employees_id || '', + creator_name: ctx.user?.employees_name || '', + default_printer_name: data.default_printer_name || '', + create_at: new Date(), + update_at: new Date(), + deleted: 0, + }); + return this.success('添加打印台成功', { data: newItem, code: 0 }); + } + async hasName(data) { + const { ctx } = this; + const warehouse_id = ctx.user.store_id; + const { name, id } = data; + if (!name) return this.fail('参数错误', 1001); + const item = await ctx.model.PrintStations.findOne({ where: { name, warehouse_id, id: { [ctx.model.Sequelize.Op.ne]: id } }, raw: true }); + return this.success('success', { exists: !!item, code: 0 }); + } + /** * 3. 修改打印台 * @param {Object} data { id, name, computer_id, custom_barcode } */ - async updateItem(data) { - const { ctx } = this; - const { id, name, computer_id, custom_barcode } = data; - if (!id) return this.fail('参数错误', 1001); - const item = await ctx.model.PrintStations.findOne({ where: { id } }); - if (!item) return this.fail('打印台不存在', 1002); - // 只更新允许字段 - if (name !== undefined) item.name = name; - if (computer_id !== undefined) item.computer_id = computer_id; - if (custom_barcode !== undefined) item.custom_barcode = custom_barcode; - await item.save(); - return this.success('success', { data: null, code: 0 }); - } + async updateItem(data) { + const { ctx } = this; + const { id, name, computer_id, custom_barcode } = data; + if (!id) return this.fail('参数错误', 1001); + const item = await ctx.model.PrintStations.findOne({ where: { id } }); + if (!item) return this.fail('打印台不存在', 1002); + // 只更新允许字段 + if (name !== undefined) item.name = name; + if (computer_id !== undefined) item.computer_id = computer_id; + if (custom_barcode !== undefined) item.custom_barcode = custom_barcode; + await item.save(); + return this.success('success', { data: null, code: 0 }); + } - /** + /** * 4. 删除打印台 * @param {Object} data { ids } */ - async del(data) { - const { ctx } = this; - const { ids } = data; - if (!Array.isArray(ids) || ids.length === 0) return this.fail('参数错误', 1001); - // 软删除 - const result = await ctx.model.PrintStations.update({ deleted: 1 }, { where: { id: ids } }); - // TODO: 检查 result 是否成功 - return this.success('success', { data: null, code: 0 }); - } + async del(data) { + const { ctx } = this; + const { ids } = data; + if (!Array.isArray(ids) || ids.length === 0) return this.fail('参数错误', 1001); + // 软删除 + await ctx.model.PrintStations.update({ deleted: 1 }, { where: { id: ids } }); + // TODO: 检查 result 是否成功 + return this.success('success', { data: null, code: 0 }); + } - /** + /** * 5. 获取打印电脑列表 - * @param {Object} data {} */ - async getComputer() { - const { ctx } = this; - // TODO: 打印电脑状态需根据实际业务实现 - const warehouseId = ctx.user.store_id; - const list = await ctx.model.PrintComputer.findAll({ raw: true, where: { status: 1, warehouse_id: warehouseId } }); + async getComputer() { + const { ctx } = this; + // TODO: 打印电脑状态需根据实际业务实现 + const warehouseId = ctx.user.store_id; + const list = await ctx.model.PrintComputer.findAll({ raw: true, where: { status: 1, warehouse_id: warehouseId } }); - return this.success('success', { data: list, code: 0 }); - } + return this.success('success', { data: list, code: 0 }); + } - /** + /** * 7. 获取打印电脑的所有打印机 * @param {Object} data { id } */ - async getComputerPrinter(data) { - const { ctx } = this; - const { id } = data; - if (!id) return this.fail('参数错误', 1001); - const printerListResult = await this.app.redis.get("printer").get(`printer:${id}:printerList`); - console.log("getComputerPrinter printerListResult", printerListResult); - const printerList = JSON.parse(printerListResult); - let printers = []; - if(!printerList ||!printerList.data || printerList.data.length === 0){ - printers = []; - } else { - printers = printerList.data; - } - return this.success('success', { data: printers, code: 0 }); + async getComputerPrinter(data) { + const { id } = data; + if (!id) return this.fail('参数错误', 1001); + const printerListResult = await this.app.redis.get('printer').get(`printer:${id}:printerList`); + console.log('getComputerPrinter printerListResult', printerListResult); + const printerList = JSON.parse(printerListResult); + let printers = []; + if (!printerList || !printerList.data || printerList.data.length === 0) { + printers = []; + } else { + printers = printerList.data; } + return this.success('success', { data: printers, code: 0 }); + } - /** + /** * 8. 保存打印台的快递-打印机绑定 - * @param {Object} data { default, express } + * @param {Object} data { defaultPrinter, express, print_station_id } */ - async savePrinters(data) { - const { ctx } = this; - const { defaultPrinter, express } = data; - // express: [{ express_id, name }] - if (!defaultPrinter || !Array.isArray(express)) return this.fail('参数错误', 1001); - // TODO: 需根据打印台ID、快递ID等实际业务调整 - // 这里只做示例保存,实际应覆盖原有绑定 - // 1. 保存默认打印机 - // 2. 保存 express 打印机绑定 - // 3. 需用 PrintStationExpress model - // 示例:批量保存 - for (const item of express) { - await ctx.model.PrintStationExpress.upsert({ - print_station_id: data.print_station_id, // 需传入 - express_id: item.express_id, - express_name: item.name, - printer_name: item.name, - is_default: item.name === defaultPrinter ? 1 : 0, - creator_id: ctx.user?.id || '', - creator_name: ctx.user?.name || '', - create_at: new Date(), - update_at: new Date(), - deleted: 0, - }); - } - return this.success('success', { data: null, code: 0 }); + async savePrinters(data) { + const { ctx } = this; + const { defaultPrinter, express } = data; + // express: [{ express_id, name }] + if (!defaultPrinter || !Array.isArray(express)) return this.fail('参数错误', 1001); + // TODO: 需根据打印台ID、快递ID等实际业务调整 + // 这里只做示例保存,实际应覆盖原有绑定 + // 1. 保存默认打印机 + // 2. 保存 express 打印机绑定 + // 3. 需用 PrintStationExpress model + // 示例:批量保存 + for (const item of express) { + await ctx.model.PrintStationExpress.upsert({ + print_station_id: data.print_station_id, // 需传入 + express_id: item.express_id, + express_name: item.name, + printer_name: item.name, + is_default: item.name === defaultPrinter ? 1 : 0, + creator_id: ctx.user?.id || '', + creator_name: ctx.user?.name || '', + create_at: new Date(), + update_at: new Date(), + deleted: 0, + }); } + return this.success('success', { data: null, code: 0 }); + } } module.exports = PrintService; diff --git a/app/service/systemMethods/user.js b/app/service/systemMethods/user.js index 79d4d76..efa3bc2 100644 --- a/app/service/systemMethods/user.js +++ b/app/service/systemMethods/user.js @@ -7,7 +7,7 @@ class userService extends MainService { super(ctx); const _noNeedLogin = 'login,loginByCode,register'; const _noNeedRight = '*'; - const _noNeedLog = 'info'; + const _noNeedLog = 'info,getBindWechatCode'; const _noNeedAuth = '*'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -61,6 +61,22 @@ class userService extends MainService { } return this.fail('登录失败:' + result.message, result); } + async getBindWechatCode(data) { + const { service } = this; + const result = await service.systems.auth.user.getBindWechatCode(data); + if (result.code) { + return this.success('获取绑定微信码成功', result); + } + return this.fail('获取绑定微信码失败:' + result.message, result); + } + async unbindWechat(data) { + const { service } = this; + const result = await service.systems.auth.user.unbindWechat(data); + if (result.code) { + return this.success('解绑成功', result); + } + return this.fail('解绑失败:' + result.message, result); + } async logout() { return this.success('登出成功'); } diff --git a/app/service/systems/auth/role_permission.js b/app/service/systems/auth/role_permission.js new file mode 100644 index 0000000..f8880a3 --- /dev/null +++ b/app/service/systems/auth/role_permission.js @@ -0,0 +1,110 @@ +'use strict'; + +const Service = require('egg').Service; + +class RolePermissionService extends Service { + async bulkAssign(roleId, permissionIds, options = {}) { + const { ctx } = this; + + if (!permissionIds || permissionIds.length === 0) { + return []; + } + + const rolePermissions = permissionIds.map(permissionId => ({ + role_id: roleId, + permission_id: permissionId, + })); + + return await ctx.model.RolePermission.bulkCreate(rolePermissions, { + ignoreDuplicates: true, + transaction: options.transaction, + }); + } + + async clearRolePermissions(roleId, options = {}) { + const { ctx } = this; + + return await ctx.model.RolePermission.destroy({ + where: { role_id: roleId }, + transaction: options.transaction, + }); + } + + async getRolePermissions(roleId, includePermissionDetails = false) { + const { ctx } = this; + + const options = { + where: { role_id: roleId }, + }; + + if (includePermissionDetails) { + options.include = [{ + model: ctx.model.Permission, + as: 'permission', + where: { status: 1 }, + required: false, + }]; + } + + return await ctx.model.RolePermission.findAll(options); + } + + async hasPermission(roleId, permissionId) { + const { ctx } = this; + + const rolePermission = await ctx.model.RolePermission.findOne({ + where: { + role_id: roleId, + permission_id: permissionId, + }, + }); + + return !!rolePermission; + } + + async assignPermissions(roleId, permissionIds, options = {}) { + await this.clearRolePermissions(roleId, options); + + if (permissionIds && permissionIds.length > 0) { + await this.bulkAssign(roleId, permissionIds, options); + } + + return true; + } + + async getPermissionTree(roleId, permissionType = null) { + const { ctx } = this; + + const rolePermissions = await this.getRolePermissions(roleId, true); + const permissionIds = rolePermissions + .map(rp => rp.permission && rp.permission.id) + .filter(Boolean); + + if (permissionIds.length === 0) { + return []; + } + + const where = { + id: permissionIds, + status: 1, + }; + + if (permissionType) { + where.type = permissionType; + } + + const permissions = await ctx.model.Permission.findAll({ + where, + order: [[ 'sort', 'ASC' ], [ 'id', 'ASC' ]], + }); + + return ctx.model.Permission.buildPermissionTree(permissions); + } + + async getPermissionIds(roleId) { + const rolePermissions = await this.getRolePermissions(roleId, false); + return rolePermissions.map(rp => rp.permission_id); + } +} + +module.exports = RolePermissionService; diff --git a/app/service/systems/auth/user.js b/app/service/systems/auth/user.js index 3bc99ee..6cf4756 100644 --- a/app/service/systems/auth/user.js +++ b/app/service/systems/auth/user.js @@ -1,12 +1,104 @@ 'use strict'; const Service = require('egg').Service; +const crypto = require('node:crypto'); + +const WECHAT_BIND_CACHE_PREFIX = 'user:wechat:bind:'; +const WECHAT_BIND_CODE_CACHE_PREFIX = 'user:wechat:bind:code:'; +const WECHAT_BIND_CACHE_TTL_SECONDS = 600; +const WECHAT_BIND_RECHECK_INTERVAL_MS = 5000; class UserService extends Service { constructor(ctx) { super(ctx); } + getCurrentAccountId() { + const { ctx } = this; + const rawUserId = ctx.userId || (ctx.user && ctx.user.id); + const accountId = Number(rawUserId); + if (!Number.isFinite(accountId) || accountId <= 0) { + return null; + } + return accountId; + } + + getWechatBindCacheKey(accountId) { + return `${WECHAT_BIND_CACHE_PREFIX}${accountId}`; + } + + getWechatBindCodeCacheKey(code) { + return `${WECHAT_BIND_CODE_CACHE_PREFIX}${code}`; + } + + createWechatBindCode() { + const payload = { + uuid: `${Date.now().toString(36)}-${crypto.randomBytes(8).toString('hex')}`, + }; + return Buffer.from(JSON.stringify(payload), 'utf8').toString('base64'); + } + + parseWechatBindCode(code) { + if (!code) { + return null; + } + + try { + const decodedStr = Buffer.from(code, 'base64').toString('utf8'); + const parsed = JSON.parse(decodedStr); + if (!parsed || typeof parsed !== 'object' || !parsed.uuid) { + return null; + } + return parsed; + } catch (error) { + return null; + } + } + + formatBindWechatData(state, source = 'db') { + const nextCheckAt = Number(state.next_db_check_at || 0); + return { + account_id: state.account_id, + code: state.code || '', + status: state.status || 'pending', + is_bound: state.status === 'bound', + updated_at: state.updated_at || new Date().toISOString(), + next_db_check_at: nextCheckAt, + next_poll_after_ms: Math.max(0, nextCheckAt - Date.now()), + source, + ye4s_user_id: state.ye4s_user_id || null, + }; + } + + async setWechatBindCache(cacheKey, state, ttl = WECHAT_BIND_CACHE_TTL_SECONDS) { + await this.app.setCacheAsync(cacheKey, state, ttl); + } + + async setWechatBindCodeCache(code, state, ttl = WECHAT_BIND_CACHE_TTL_SECONDS) { + if (!code) { + return; + } + const codeCacheKey = this.getWechatBindCodeCacheKey(code); + await this.app.setCacheAsync(codeCacheKey, state, ttl); + } + + async findYe4sBindingByAccountId(accountId) { + const { ctx } = this; + const ye4sClient = ctx.app.mysql.get('ye4s'); + const rows = await ye4sClient.select('ye4s_user', { + where: { + wms_account_id: accountId, + }, + columns: [ 'id', 'tmp_code', 'wms_account_id' ], + orders: [[ 'id', 'desc' ]], + limit: 1, + }); + if (!rows || rows.length === 0) { + return null; + } + return rows[0]; + } + /** * 用户登录(重构版) * @param {string} username - 用户名/手机号/邮箱 @@ -143,6 +235,281 @@ class UserService extends Service { } } + /** + * 获取微信绑定码(缓存优先,低频复查DB,适配轮询) + * @param {Object} data + * @return {Object} + */ + async getBindWechatCode(data = {}) { + const { app } = this; + try { + const accountId = this.getCurrentAccountId(); + if (!accountId) { + return { + success: false, + code: 0, + data: null, + message: '未识别到登录账号,无法生成绑定码', + }; + } + + const cacheKey = this.getWechatBindCacheKey(accountId); + const forceRefresh = !!data.forceRefresh; + const now = Date.now(); + + let cachedState = null; + try { + cachedState = await this.app.getCacheAsync(cacheKey); + } catch (cacheErr) { + app.coreLogger.warn(`读取微信绑定缓存失败: ${cacheErr.message}`); + } + + if (cachedState && !forceRefresh) { + const nextCheckAt = Number(cachedState.next_db_check_at || 0); + if (nextCheckAt > now) { + return { + success: true, + code: 200, + data: this.formatBindWechatData(cachedState, 'cache'), + message: '获取绑定码成功(缓存)', + }; + } + } + + const ye4sBinding = await this.findYe4sBindingByAccountId(accountId); + if (ye4sBinding) { + const dbCode = typeof ye4sBinding.tmp_code === 'string' ? ye4sBinding.tmp_code.trim() : ''; + const bindState = { + account_id: accountId, + status: 'bound', + code: dbCode || (cachedState && cachedState.code) || this.createWechatBindCode(), + updated_at: new Date().toISOString(), + next_db_check_at: now + WECHAT_BIND_RECHECK_INTERVAL_MS, + ye4s_user_id: ye4sBinding.id || null, + }; + + await this.setWechatBindCache(cacheKey, bindState, WECHAT_BIND_CACHE_TTL_SECONDS); + await this.setWechatBindCodeCache(bindState.code, bindState, WECHAT_BIND_CACHE_TTL_SECONDS); + + return { + success: true, + code: 200, + data: this.formatBindWechatData(bindState, 'db'), + message: '账号已绑定微信', + }; + } + + const code = (cachedState && cachedState.code) || this.createWechatBindCode(); + const pendingState = { + account_id: accountId, + status: 'pending', + code, + updated_at: new Date().toISOString(), + next_db_check_at: now + WECHAT_BIND_RECHECK_INTERVAL_MS, + ye4s_user_id: null, + }; + + await this.setWechatBindCache(cacheKey, pendingState, WECHAT_BIND_CACHE_TTL_SECONDS); + await this.setWechatBindCodeCache(pendingState.code, pendingState, WECHAT_BIND_CACHE_TTL_SECONDS); + + return { + success: true, + code: 200, + data: this.formatBindWechatData(pendingState, code === (cachedState && cachedState.code) ? 'cache-refresh' : 'generated'), + message: '账号未绑定,已生成绑定码', + }; + } catch (error) { + app.coreLogger.error(`获取微信绑定码失败: ${error.message}`); + return { + success: false, + code: 0, + data: null, + message: '获取绑定码失败,请稍后重试', + }; + } + } + + /** + * 根据绑定临时码获取账号ID(供 ye4s 扫码绑定调用) + * @param {Object} data + * @return {Object} + */ + async getUserByTempCode(data = {}) { + const { ctx, app } = this; + try { + const code = typeof data.code === 'string' ? data.code.trim() : ''; + if (!code) { + return { + success: false, + code: 0, + data: null, + message: '缺少绑定码 code', + }; + } + + if (!this.parseWechatBindCode(code)) { + return { + success: false, + code: 0, + data: null, + message: '无效的绑定码格式', + }; + } + + const codeCacheKey = this.getWechatBindCodeCacheKey(code); + let codeState = null; + try { + codeState = await this.app.getCacheAsync(codeCacheKey); + } catch (cacheErr) { + app.coreLogger.warn(`读取绑定码映射缓存失败: ${cacheErr.message}`); + } + + const cachedAccountId = Number(codeState && codeState.account_id); + if (Number.isFinite(cachedAccountId) && cachedAccountId > 0) { + return { + success: true, + code: 200, + data: { + account_id: cachedAccountId, + code, + status: codeState.status || 'pending', + source: 'cache', + updated_at: codeState.updated_at || new Date().toISOString(), + }, + message: '获取账号成功', + }; + } + + const ye4sClient = ctx.app.mysql.get('ye4s'); + const ye4sUser = await ye4sClient.get('ye4s_user', { + tmp_code: code, + }); + + const wmsAccountId = Number(ye4sUser && ye4sUser.wms_account_id); + if (Number.isFinite(wmsAccountId) && wmsAccountId > 0) { + const boundState = { + account_id: wmsAccountId, + status: 'bound', + code, + updated_at: new Date().toISOString(), + next_db_check_at: Date.now() + WECHAT_BIND_RECHECK_INTERVAL_MS, + ye4s_user_id: ye4sUser.id || null, + }; + await this.setWechatBindCodeCache(code, boundState, WECHAT_BIND_CACHE_TTL_SECONDS); + await this.setWechatBindCache(this.getWechatBindCacheKey(wmsAccountId), boundState, WECHAT_BIND_CACHE_TTL_SECONDS); + + return { + success: true, + code: 200, + data: { + account_id: wmsAccountId, + code, + status: 'bound', + source: 'db', + updated_at: boundState.updated_at, + }, + message: '获取账号成功', + }; + } + + return { + success: false, + code: 0, + data: null, + message: '绑定码不存在或已过期', + }; + } catch (error) { + app.coreLogger.error(`根据绑定码获取账号失败: ${error.message}`); + return { + success: false, + code: 0, + data: null, + message: '获取账号失败,请稍后重试', + }; + } + } + + /** + * 解绑微信:清理 ye4s_user 中与当前账号关联的数据 + * @return {Object} + */ + async unbindWechat() { + const { ctx, app } = this; + try { + const accountId = this.getCurrentAccountId(); + if (!accountId) { + return { + success: false, + code: 0, + data: null, + message: '未识别到登录账号,无法解绑', + }; + } + + const ye4sClient = ctx.app.mysql.get('ye4s'); + const bindRows = await ye4sClient.select('ye4s_user', { + where: { + wms_account_id: accountId, + }, + columns: [ 'id', 'tmp_code', 'wms_account_id' ], + orders: [[ 'id', 'desc' ]], + limit: 500, + }); + + let affectedRows = 0; + for (const row of bindRows) { + const rowCode = typeof row.tmp_code === 'string' ? row.tmp_code.trim() : ''; + if (rowCode) { + await this.setWechatBindCodeCache(rowCode, null, 1); + } + try { + const ret = await ye4sClient.update('ye4s_user', { + id: row.id, + wms_account_id: null, + tmp_code: null, + }); + affectedRows += Number(ret && ret.affectedRows ? ret.affectedRows : 0); + } catch (err) { + // 兼容不允许 NULL 的旧表结构 + const ret = await ye4sClient.update('ye4s_user', { + id: row.id, + wms_account_id: 0, + tmp_code: '', + }); + affectedRows += Number(ret && ret.affectedRows ? ret.affectedRows : 0); + } + } + + const cacheKey = this.getWechatBindCacheKey(accountId); + const cachedState = await this.app.getCacheAsync(cacheKey); + if (cachedState && cachedState.code) { + await this.setWechatBindCodeCache(cachedState.code, null, 1); + } + await this.setWechatBindCache(cacheKey, null, 1); + + return { + success: true, + code: 200, + data: { + account_id: accountId, + status: 'unbound', + matched_rows: bindRows.length, + affected_rows: affectedRows, + updated_at: new Date().toISOString(), + }, + message: bindRows.length > 0 ? '解绑成功' : '当前账号未绑定微信', + }; + } catch (error) { + app.coreLogger.error(`解绑微信失败: ${error.message}`); + return { + success: false, + code: 0, + data: null, + message: '解绑失败,请稍后重试', + }; + } + } + /** * 生成统一登录成功结构 * @param {Object} user @@ -326,43 +693,58 @@ class UserService extends Service { const platformCode = ctx.header.platform || 'web'; const project = ctx.header.project; try { - // 获取用户的所有角色关联 - const store_where = { - status: 1, - }; - if (project != 'all') { - store_where.project = project; - } - console.log('store_where', store_where, project, platformCode, ctx.header); - const accountStoreEmployees = await ctx.model.AccountStoreEmployee.findAll({ - where: { - account_id: userId, + const loadAccountStoreEmployees = async projectFilter => { + const store_where = { status: 1, - }, - include: [ - { - model: ctx.model.EmployeeRole, - as: 'employeeRoles', - attributes: [ 'id', 'role_id' ], + }; + if (projectFilter && projectFilter !== 'all') { + store_where.project = projectFilter; + } + console.log('store_where', store_where, projectFilter, platformCode, ctx.header); + return ctx.model.AccountStoreEmployee.findAll({ + where: { + account_id: userId, + status: 1, }, - { - model: ctx.model.Store, - as: 'store', - attributes: [ 'id', 'company_name', 'project', 'auth_end' ], - where: store_where, - }, - ], - order: [[ 'created_at', 'DESC' ]], - }); - if (!accountStoreEmployees) { - throw ('没有符合的角色'); + include: [ + { + model: ctx.model.EmployeeRole, + as: 'employeeRoles', + attributes: [ 'id', 'role_id' ], + }, + { + model: ctx.model.Store, + as: 'store', + attributes: [ 'id', 'company_name', 'project', 'auth_end' ], + where: store_where, + }, + ], + order: [[ 'created_at', 'DESC' ]], + }); + }; + + // 先按请求 project 过滤;查不到时降级到 all,便于补齐平台激活记录。 + let accountStoreEmployees = await loadAccountStoreEmployees(project); + if ((!accountStoreEmployees || accountStoreEmployees.length === 0) && project && project !== 'all') { + accountStoreEmployees = await loadAccountStoreEmployees('all'); + } + + if (!accountStoreEmployees || accountStoreEmployees.length === 0) { + return { + Employees: [], + activeEmployeeId: null, + menus: [], + permissions: [], + userRole: '', + realName: null, + }; } console.log('accountStoreEmployees>>>>>', accountStoreEmployees); // 获取当前平台的激活角色 let activeEmployeeId = null; - let employee_id = null; let realName = null; let userRole = ''; + let currentPlatformEmployeeId = null; const platformActive = await ctx.model.AccountPlatformActive.findOne({ where: { @@ -372,14 +754,14 @@ class UserService extends Service { attributes: [ 'account_id', 'employee_id', 'platform_code' ], }); if (platformActive) { - employee_id = platformActive.employee_id; + currentPlatformEmployeeId = platformActive.employee_id; } // 转换数据格式 const Employees = accountStoreEmployees.map(item => ({ id: item.id, store_id: item.store_id, store_name: item.store.company_name, - is_primary: platformActive && platformActive.employee_id === item.id ? 1 : 0, + is_primary: currentPlatformEmployeeId === item.id ? 1 : 0, real_name: item.real_name, auth_end: item.store.auth_end, role_type: item.store.project, @@ -416,7 +798,14 @@ class UserService extends Service { return { Employees, activeEmployeeId, menus, permissions, userRole, realName }; } catch (error) { console.error('获取用户角色失败:', error); - return [[], null, [], [], '', null ]; + return { + Employees: [], + activeEmployeeId: null, + menus: [], + permissions: [], + userRole: '', + realName: null, + }; } } @@ -466,8 +855,19 @@ class UserService extends Service { } // 3. 获取角色信息(这个方法内部也有缓存逻辑) - const { Employees, activeEmployeeId, menus, permissions, userRole, realName } = await this.getRoles(userId); + let { Employees, activeEmployeeId, menus, permissions, userRole, realName } = await this.getRoles(userId); console.log('activeEmployeeId>>>>>>>>', activeEmployeeId); + + // pda 场景若缺少激活角色,优先补一条当前平台激活记录,避免直接报错。 + if (platformCode == 'pda' && !activeEmployeeId && Employees.length > 0) { + const fallbackEmployee = Employees[0]; + await this.ensurePlatformActiveRole(userId, fallbackEmployee.id, platformCode); + activeEmployeeId = fallbackEmployee.id; + userRole = fallbackEmployee.role_type == 1 ? 'warehouse' : 'customer'; + realName = fallbackEmployee.real_name || realName; + menus = await this.getMenus(activeEmployeeId); + permissions = await this.getPermissions(activeEmployeeId); + } // 4. 获取当前角色对应的仓库ID let storeId = null; let storeName = null; @@ -489,7 +889,7 @@ class UserService extends Service { const avatar = await this.getAvatarByEmployeeId(activeEmployeeId); if (platformCode == 'pda' && !activeEmployeeId) { - throw ('无登录权限'); + ctx.logger.warn(`pda 平台未找到可激活角色,accountId=${userId},将以空角色上下文返回`); } // 5. 组合用户信息 const userInfo = { diff --git a/app/service/systems/polo_api.js b/app/service/systems/polo_api.js index 307f7b6..af7289f 100644 --- a/app/service/systems/polo_api.js +++ b/app/service/systems/polo_api.js @@ -4,60 +4,56 @@ const Service = require('egg').Service; const poloApiConfig = require('../../../config/poloapi'); const crypto = require('crypto'); -const querystring = require('querystring'); class PoloApiService extends Service { - constructor(ctx) { - super(ctx); - this.configPoloApi = poloApiConfig; - } + constructor(ctx) { + super(ctx); + this.configPoloApi = poloApiConfig; + } - // 批量组装订单JSON - getJsonDatas(expressConfig, list) { - const formatter = 'yyyy-MM-dd HH:mm:ss'; - const now = new Date(); - const tempDate = this._formatDate(now, formatter); - const cal = new Date(); - const year = cal.getFullYear(); - const month = cal.getMonth() + 1; - const day = cal.getDate() + 3; - const day1 = cal.getDate() + 4; - const sb1 = this._formatPickupDate(year, month, day); - const sb2 = this._formatPickupDate(year, month, day1); + // 批量组装订单JSON + getJsonDatas(expressConfig, list) { + const cal = new Date(); + const year = cal.getFullYear(); + const month = cal.getMonth() + 1; + const day = cal.getDate() + 3; + const day1 = cal.getDate() + 4; + const sb1 = this._formatPickupDate(year, month, day); + const sb2 = this._formatPickupDate(year, month, day1); - let orders = []; - for (const wmsOrder of list) { - let txLogisticID = wmsOrder.sourceId; - txLogisticID = txLogisticID.length < 6 ? txLogisticID.padStart(6, '0') : txLogisticID; - if (wmsOrder.postcode === 'p10') { - if (txLogisticID.length > 19) txLogisticID = txLogisticID.slice(-19); - } else { - if (txLogisticID.length > 28) txLogisticID = txLogisticID.slice(-28); - } - txLogisticID = txLogisticID.replace(/_/g, ''); + const orders = []; + for (const wmsOrder of list) { + let txLogisticID = wmsOrder.sourceId; + txLogisticID = txLogisticID.length < 6 ? txLogisticID.padStart(6, '0') : txLogisticID; + if (wmsOrder.postcode === 'p10') { + if (txLogisticID.length > 19) txLogisticID = txLogisticID.slice(-19); + } else { + if (txLogisticID.length > 28) txLogisticID = txLogisticID.slice(-28); + } + txLogisticID = txLogisticID.replace(/_/g, ''); - // 快递公司代码 - const cpcode = this.configPoloApi.postCodeMap[wmsOrder.postcode] || ''; + // 快递公司代码 + const cpcode = this.configPoloApi.postCodeMap[wmsOrder.postcode] || ''; - // 商品名 - let cnname = ''; - let ycflag = !(wmsOrder.wareHouseId === 5400 || wmsOrder.storeId === 58303); - if (ycflag) { - const items = wmsOrder.items || ''; - const splitStr = items.split('|'); - if (splitStr.length > 0) { - const s = splitStr[0]; - const sArr = s.split(','); - if (sArr.length > 2) cnname = sArr[2]; - } - } else { - cnname = 'sp'; - } + // 商品名 + let cnname = ''; + const ycflag = !(wmsOrder.wareHouseId === 5400 || wmsOrder.storeId === 58303); + if (ycflag) { + const items = wmsOrder.items || ''; + const splitStr = items.split('|'); + if (splitStr.length > 0) { + const s = splitStr[0]; + const sArr = s.split(','); + if (sArr.length > 2) cnname = sArr[2]; + } + } else { + cnname = 'sp'; + } - // 收件人手机号 - let mobile = wmsOrder.tempMobile || wmsOrder.tel || ''; + // 收件人手机号 + const mobile = wmsOrder.tempMobile || wmsOrder.tel || ''; - /* + /* order对象结构(41-77): { businessplat, ismultiplepieces, businesstype, cpcode, customercode, customername, @@ -79,125 +75,125 @@ class PoloApiService extends Service { country, Company, address, name, area, town, city, phone, mobile, tel, province } */ - // 组装订单对象(下标范围:约第41-77行) - const order = { // [order对象开始 41] - businessplat: 'OTHERS', // 41 - ismultiplepieces: '0', - businesstype: 'JH_Normal', - cpcode, - customercode: '', - customername: expressConfig.storeProperty || '测试', - goods: [{ // [goods对象开始 49] - cnname, - count: String(wmsOrder.goodsCount), - unit: '属性', - currencytype: 'CNY', - Unit: '', - weight: String(wmsOrder.orderWeight), - price: '0.0', - }], // [goods对象结束 56] - logisticsproductname: 'JH_02', - logistictype: cpcode, - mainsubpaymode: '1', - needencrypt: '1', - numpackage: '1', - orderno: wmsOrder.sourceOrderCode || (wmsOrder.id && wmsOrder.id.length > 13 ? wmsOrder.id.substring(0, 14) : wmsOrder.id), - ordersource: 'KUAI_SHOU', - ordertype: 'JH_Normal', - plattradeno: wmsOrder.sourceOrderCode || txLogisticID, - ProviderID: wmsOrder.postcode === 'p03' ? 1327 : (wmsOrder.postcode === 'p04' ? 1499 : ''), - providercode: cpcode, - receiver: { // [receiver对象开始 59] - address: wmsOrder.address, - name: wmsOrder.name, - area: wmsOrder.expAreaName, - city: wmsOrder.cityName, - mobile, - province: wmsOrder.province, - }, // [receiver对象结束 65] - sender: { // [sender对象开始 66] - country: 'CN', - Company: expressConfig.storeName, - address: expressConfig.address, - name: expressConfig.senderName, - area: expressConfig.districtName && expressConfig.districtName.indexOf(';') === -1 ? expressConfig.districtName : expressConfig.districtName.split(';')[0], - town: expressConfig.districtName && expressConfig.districtName.indexOf(';') !== -1 ? expressConfig.districtName.split(';')[1] : undefined, - city: expressConfig.cityName, - phone: expressConfig.senderTel, - mobile: expressConfig.senderTel, - tel: expressConfig.senderTel, - province: expressConfig.provinceName, - }, // [sender对象结束 75] - shipperno: ['p22', 'p35', 'p10'].includes(wmsOrder.postcode) ? expressConfig.siteCode : expressConfig.clientId, - sitecode: expressConfig.siteCode || '', - Inputsite: expressConfig.siteCode || '', - transtype: '0', - // 省略部分特殊字段和extraInfo,后续可补充 - }; // [order对象结束 77] - // 特殊字段 - if (wmsOrder.postcode === 'p10') { - order.pickUpDate = sb1; - order.pickUpEndDate = sb2; - } - orders.push(order); - } + // 组装订单对象(下标范围:约第41-77行) + const order = { // [order对象开始 41] + businessplat: 'OTHERS', // 41 + ismultiplepieces: '0', + businesstype: 'JH_Normal', + cpcode, + customercode: '', + customername: expressConfig.storeProperty || '测试', + goods: [{ // [goods对象开始 49] + cnname, + count: String(wmsOrder.goodsCount), + unit: '属性', + currencytype: 'CNY', + Unit: '', + weight: String(wmsOrder.orderWeight), + price: '0.0', + }], // [goods对象结束 56] + logisticsproductname: 'JH_02', + logistictype: cpcode, + mainsubpaymode: '1', + needencrypt: '1', + numpackage: '1', + orderno: wmsOrder.sourceOrderCode || (wmsOrder.id && wmsOrder.id.length > 13 ? wmsOrder.id.substring(0, 14) : wmsOrder.id), + ordersource: 'KUAI_SHOU', + ordertype: 'JH_Normal', + plattradeno: wmsOrder.sourceOrderCode || txLogisticID, + ProviderID: wmsOrder.postcode === 'p03' ? 1327 : (wmsOrder.postcode === 'p04' ? 1499 : ''), + providercode: cpcode, + receiver: { // [receiver对象开始 59] + address: wmsOrder.address, + name: wmsOrder.name, + area: wmsOrder.expAreaName, + city: wmsOrder.cityName, + mobile, + province: wmsOrder.province, + }, // [receiver对象结束 65] + sender: { // [sender对象开始 66] + country: 'CN', + Company: expressConfig.storeName, + address: expressConfig.address, + name: expressConfig.senderName, + area: expressConfig.districtName && expressConfig.districtName.indexOf(';') === -1 ? expressConfig.districtName : expressConfig.districtName.split(';')[0], + town: expressConfig.districtName && expressConfig.districtName.indexOf(';') !== -1 ? expressConfig.districtName.split(';')[1] : undefined, + city: expressConfig.cityName, + phone: expressConfig.senderTel, + mobile: expressConfig.senderTel, + tel: expressConfig.senderTel, + province: expressConfig.provinceName, + }, // [sender对象结束 75] + shipperno: [ 'p22', 'p35', 'p10' ].includes(wmsOrder.postcode) ? expressConfig.siteCode : expressConfig.clientId, + sitecode: expressConfig.siteCode || '', + Inputsite: expressConfig.siteCode || '', + transtype: '0', + // 省略部分特殊字段和extraInfo,后续可补充 + }; // [order对象结束 77] + // 特殊字段 + if (wmsOrder.postcode === 'p10') { + order.pickUpDate = sb1; + order.pickUpEndDate = sb2; + } + orders.push(order); + } - const body = JSON.stringify({ orders, shoptype: 'JH_001' }); + const body = JSON.stringify({ orders, shoptype: 'JH_001' }); - // 组装url参数 - const urlParams = { - method: 'Differ.JH.Logistics.PostOrder', - appkey: this.configPoloApi.appKey, - token: expressConfig.sessionKey, - platid: this.configPoloApi.platid, - version: this.configPoloApi.version, - bizcontent: encodeURIComponent(body), - contenttype: this.configPoloApi.contenttype, - timestamp: encodeURIComponent(this._formatDate(new Date(), 'yyyy-MM-dd HH:mm:ss')), - }; - // 签名 - const signMap = { ...urlParams, bizcontent: body, timestamp: this._formatDate(new Date(), 'yyyy-MM-dd HH:mm:ss') }; - const signText = this.getSignText(signMap, this.configPoloApi.appSecret); - urlParams.sign = this.md5Encrypt(signText.toLowerCase(), 'utf8'); + // 组装url参数 + const urlParams = { + method: 'Differ.JH.Logistics.PostOrder', + appkey: this.configPoloApi.appKey, + token: expressConfig.sessionKey, + platid: this.configPoloApi.platid, + version: this.configPoloApi.version, + bizcontent: encodeURIComponent(body), + contenttype: this.configPoloApi.contenttype, + timestamp: encodeURIComponent(this._formatDate(new Date())), + }; + // 签名 + const signMap = { ...urlParams, bizcontent: body, timestamp: this._formatDate(new Date()) }; + const signText = this.getSignText(signMap, this.configPoloApi.appSecret); + urlParams.sign = this.md5Encrypt(signText.toLowerCase(), 'utf8'); - // 返回请求体和参数 - return { body, urlParams }; - } + // 返回请求体和参数 + return { body, urlParams }; + } - // 单个订单JSON(略,结构同上,建议复用 getJsonDatas 逻辑) - getJsonData(expressConfig, wmsOrder, deliveryOrder, type) { - // 可根据 type 判断调用 getJsonDatas 或单独组装 - return this.getJsonDatas(expressConfig, [wmsOrder]); - } + // 单个订单JSON(略,结构同上,建议复用 getJsonDatas 逻辑) + getJsonData(expressConfig, wmsOrder) { + // 可根据 type 判断调用 getJsonDatas 或单独组装 + return this.getJsonDatas(expressConfig, [ wmsOrder ]); + } - // 生成签名字符串 - getSignText(signMap, secret) { - let sb = '' + secret; - Object.keys(signMap).sort().forEach(key => { - sb += key + signMap[key]; - }); - sb += secret; - return sb; - } + // 生成签名字符串 + getSignText(signMap, secret) { + let sb = '' + secret; + Object.keys(signMap).sort().forEach(key => { + sb += key + signMap[key]; + }); + sb += secret; + return sb; + } - // MD5加密 - md5Encrypt(text, encoding = 'utf8') { - return crypto.createHash('md5').update(text, encoding).digest('hex'); - } + // MD5加密 + md5Encrypt(text, encoding = 'utf8') { + return crypto.createHash('md5').update(text, encoding).digest('hex'); + } - // 工具:格式化日期 - _formatDate(date, fmt) { - // 仅支持 yyyy-MM-dd HH:mm:ss - const pad = n => n < 10 ? '0' + n : n; - return date.getFullYear() + '-' + pad(date.getMonth() + 1) + '-' + pad(date.getDate()) + ' ' + // 工具:格式化日期 + _formatDate(date) { + // 仅支持 yyyy-MM-dd HH:mm:ss + const pad = n => (n < 10 ? '0' + n : n); + return date.getFullYear() + '-' + pad(date.getMonth() + 1) + '-' + pad(date.getDate()) + ' ' + pad(date.getHours()) + ':' + pad(date.getMinutes()) + ':' + pad(date.getSeconds()); - } + } - // 工具:组装取件日期 - _formatPickupDate(year, month, day) { - const pad = n => n < 10 ? '0' + n : n; - return `${year}-${pad(month)}-${pad(day)} 18:00:00`; - } + // 工具:组装取件日期 + _formatPickupDate(year, month, day) { + const pad = n => (n < 10 ? '0' + n : n); + return `${year}-${pad(month)}-${pad(day)} 18:00:00`; + } } -module.exports = PoloApiService; \ No newline at end of file +module.exports = PoloApiService; diff --git a/app/service/systems/store.js b/app/service/systems/store.js index d01f0b0..85dcaff 100644 --- a/app/service/systems/store.js +++ b/app/service/systems/store.js @@ -2,6 +2,73 @@ const Service = require('egg').Service; class StoreService extends Service { + validateStoreData(data = {}) { + const errors = []; + + const requiredFields = [ 'company_name', 'contact_person', 'contact_phone' ]; + for (const field of requiredFields) { + if (!data[field]) { + errors.push(`${field} 不能为空`); + } + } + + if (data.company_name && (data.company_name.length < 1 || data.company_name.length > 200)) { + errors.push('公司名称长度应在1-200个字符之间'); + } + + if (data.contact_email && data.contact_email.trim() !== '') { + const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; + if (!emailRegex.test(data.contact_email)) { + errors.push('联系邮箱格式不正确'); + } + } + + return errors; + } + + async checkCompanyNameExists(companyName, excludeId = null) { + const where = { + company_name: companyName, + }; + + if (excludeId) { + where.id = { + [this.app.Sequelize.Op.ne]: excludeId, + }; + } + + const store = await this.app.model.Store.findOne({ where }); + return !!store; + } + + async findByAccountId(accountId) { + return await this.app.model.Store.findOne({ + where: { + account_id: accountId, + status: 1, + }, + }); + } + + async findAllEnabled() { + return await this.app.model.Store.findAll({ + where: { + status: 1, + }, + order: [[ 'company_name', 'ASC' ]], + }); + } + + async findAllWarehouses() { + return await this.app.model.Store.findAll({ + where: { + status: 1, + project: 'warehouse', + }, + order: [[ 'company_name', 'ASC' ]], + }); + } + /** * 根据ID获取商家信息 * @param storeId diff --git a/config/config.default.js b/config/config.default.js index b315709..4c783ee 100644 --- a/config/config.default.js +++ b/config/config.default.js @@ -113,19 +113,26 @@ module.exports = appInfo => { config.mysql = { clients: { wms: { - host: '10.10.0.1', + host: '112.124.21.102', port: '3306', user: 'wms', password: 'P6j3YTHTpirepYWz', database: 'wms', }, + ye4s:{ + host: '112.124.21.102', + port: '3306', + user: 'ye4s', + password: 'H@8h^QE4N$L.F_*', + database: 'ye4s', + } }, app: true, agent: false, }; exports.sequelize = { dialect: 'mysql', - host: '10.10.0.1', + host: '112.124.21.102', port: 3306, database: 'wms', username: 'wms', @@ -150,12 +157,12 @@ module.exports = appInfo => { secret: 'E5#ex.g@,GfL_8?', }; - /*config.view = { + config.view = { defaultViewEngine: 'ejs', mapping: { '.html': 'ejs', }, - };*/ + }; config.cluster = { listen: { port: 6060, // 使用其他端口避免冲突 @@ -163,10 +170,10 @@ module.exports = appInfo => { }, }; config.poloapi ={ - + } config.printService = { - url: 'http://localhost:4050', + url: 'http://printer.wms.gztbyc.com', }; return { ...config, diff --git a/config/deploy.config.example.cjs b/config/deploy.config.example.cjs new file mode 100644 index 0000000..25d3a2a --- /dev/null +++ b/config/deploy.config.example.cjs @@ -0,0 +1,24 @@ +module.exports = { + production: { + host: '__FILL_SSH_HOST__', + port: 22, + username: '__FILL_SSH_USERNAME__', + privateKeyPath: 'C:/Users/your-user/.ssh/id_rsa', + deployRoot: '/www/wwwroot/qimen', + sharedDirs: [ 'logs', 'run', 'temp' ], + keepBackups: 5, + preDeployCommands: [ + 'node -v', + 'npm -v', + ], + postDeployCommands: [ + 'npm install --production', + 'npm run stop || true', + 'npm start', + ], + healthCheckUrl: 'http://127.0.0.1:6060/', + sshOptions: [ + 'StrictHostKeyChecking=accept-new', + ], + }, +}; \ No newline at end of file diff --git a/day.log b/day.log index f3ffdccd6f9468d80340b75d2a240d51bb87fd11..68d815a5ed8fec068fa70e00cdc1af1ce82c63bf 100644 GIT binary patch delta 9073 zcmbVReQ+CPdVh5Z#tO0tS7JaM?S{D{Cd8IP5?|sp=_MgFq4C<%%65!mNtUvagFj*{ zTlqS?1ab$dow0LEJ|=AgbV{2)%HaONbTXZ3$qaxuZnTJnmnzqm2Nhn3d;d~5QzFI_);tvS=9h)0AX2E?G) zC7u$x$cQ0apUkdRKOGUO-y#iu>u`5cKeaWV(9*#PMWoE9>lPU6#a^)iZ*Iq%DXefP z2krM1-0^-$BZoI~*h3e6xaz~-A<=D9P{gUNuS7vv^x`@zc8Y#cN|!5 z&%*AplL0F@@$Pta?7V6;*ABm|{i36krg0_v`6zGh1rG=y8WGP^4hPqTj$K$!Wfo9dozw$ZD9ks)g zIe(U_^re1pcz$~I#F25yBDEKLcFx$?$+M#$j{IqMHgg(^sEmEot4zzNi0c{&&QHG_ z%_sh8{8F2Ot#^qY=%ioFE`Q?qN4<^hyLSBa(8qZyJ!mx=cR?7(fWC0zc&YK85Sk&H zg(`eux!AFxwBYQUor<3w4O*!(22#X3s5b|;YN?Vct*XL3$CVWE>(O^oek)+vLASazC_ZWS zWnR|&St^}d&n|h&e09MhGramXpGqE@6!CuMH{(;CftcRYsD4kG$;|`G?9`YJ{;2Px z(bskH$Iz#p5E$SL=V1i#c6iYs3_pacL73m`3JTWrW6fUpYq1i4mbsG6Cr-wjn(4~} zSknaxJFtEb0k8&lw&TtcP%BPaYv}g|wr2>_5=%RNaClYsXKk}t0r@P~H5Rm_0aD_% z%w_Gqqt{0p@qX>_57YnJyesue^qFzeahNQZX5=2fJT&;+m8|jks1w3Wa^zV@O5!Q-w>8MTc-pv zxVlPfIufw{JAUH;xg3DoDJUDW8}`?SE@)>4f>w)oOsoTAxx{a@+V;=%w|1@WBZZs# zFVmllP{*Y-kP!G`{`e}MeVX}$k@jt@*aeIC+D5#t(WBjMoG@cyD%GDXS^0$ty7CKp zrh7K4o9c#I^Y0f_7%4%{)`>0nG>dkz5yB=#i-_Xt30!RuF`?Ofa6hUn1znT3P^s2S zlpccmnW|GFVC54myH|UEe&oy1&1$999l1IY5+ADO;zUR+I=os9iJgP%`utX@CS66^ zL2I+yjg7kOS~~~@m%0gEh;^H3<^Rhpwa0gdVKRmp>-2UgX~=-j&cqzcu(UXObCLR^ zwE8o#UqRaEp7T%mt=UY$jrtKI1P}BX{yvCk;fKXPk7q0#8nT4>{hGVy)QUw+GVR_3 zxX4Zg`|+wLWs8RkWFEv8l@@DMNU+A3<9dWOM&cT&5v!QMH&ht<2 zV;Y+l7_-BS0Wi87j1I!+v=N zx0*#O%4JN{ip9_ncj1R=xfrReDLkR}D76!K?=3#D^H{Zdd&kw@*=@Qc8*YbX%>#dU zADkAc6jyx^I|J2p*=ow+ioj11uce=eH5_}h=e+9A61y%+(I+0q^FdgCBYp`>>FmpF zguB%KZ4fJvzE)smzqNFyx1};W^Rm$6B=)^qcCb_+*X=r3>~Nuye33 z%*2L!%_TL}X6(-In#bzC8<5+|rDn^9hxpJ4*&;Fs2JxN~P?G)!nUA&J$kUPkdG=4D zr0&4idSG=Xm`V$&Byn!^k*F_xI_gU;d}_4)Z=e5I^M&L4{S#f;o6tZ-bofNIdQ-n~ zbZ$q*kdtX7{rrjbwcCCiITP0-mo;v{xFaij-~!GTpEP$6l$uBGT(CK0KOKUYbk&gU zh%7go@g=0s*`o9Lko~_mk!ZNb`@}UNQ=9(-+dnq%CkmZ2Ry%w~zZ0E{Ye6d5pApB` z_sYiO?D&7}y`tU$Uzj&vY)Q>PEYS#4jXpYHP7(N=bOE4%c3;o`TjerXxE zaN^I&c@@zMn%wr(*2bhce{+rbM{I)X(T2^?K=kuKTm3d8sX$3|eNY>9K`gl4UJy9@z9d=E`uu>}^^Z@~+O_+AH{O zkcO6GaqD--@7PzTUeG3UiZCZ1xp!W^<$}fzVc$OUv&Zi4lBjN~v$maufp0WL`;9u4 zV~MFwA|C=|+OpDGj$GJ)?=n;?zjZ}jw(n&8_9&mP>$_uLvAL!@ZS(9C`ZtjJ4>ql) z%D=V5h4*e@s)dHg{^N-3{8RR%#DOU?8?o@zsdrC&9huC%J1*3PHfSW!U_Y(`LvOUf zN6fC#=Z{=CTpeR|4p`rho{TrDf4%#rerf!*%(3+8Xlcg3tortRU}XM6tyWo)y`HNj zo1(1LOaOg_#OTe>AK)!MOXHJ)m#q}5#8SITG8fS~biwY9GpK&7P*4zfx5x2PJSUFq z7Dktyb?Lqm5=al3>Lg2HyA<=qorN(~s4P4GGJbvE2bspbQ=R^-Vs{o~PS(s}bhN|M zZ;`QnJZTqA&|6Y8#elgtLy;jw4_oP8FcPw5@!}Ke<0r{a4_`#Oaow1pdH|%^d}Bt0 zzf2{0#C!8yb%r=z9s6>mRr~irHrk=s>8R5u=M#)OI-*Ek(0nOA7(kVWw< zk?@TXT@Prchz5NvrZz-W?)_!B%BHuxXe-i~29t;uz$8{I3O994@fp=L)IX zeNl%Cc(YWCE$Nc|W9r`YZT%HPlBLaHb0rvv*<1C4jvQRb#P3i;$?buKo%Xz#Fj2CE z42lQ<<8&PNrHF2sCZ{?twKbqp@VdtMS?1iaI+fMJJ5FU2A%~AdI~fS&nvPg%s&j6~ zs*0g};#zZ62ZNUOUVZHK!kns*+wGYMRn>26#pwYR)3Nl4KS$U1&I5*fLFa_^t2ps~@pQyH?Wj_TO})w|>p?4>s_?wAfj)Lz1HwR!4eDAFhY&Y_SG% z-*1)C8K~=UJO1W`S-rLr^O2R-avIjvL4x4FAVh9+;`asI#hJG6#_W(2fyVD(`t@Tik%Qh zy+sTf5QkCkkgtbW?oz&5qJa_xgrS7F9bOM3xRC=S78xfZlVHytx!Y_p^CY3yVPP)MkoAwWI;^@Yzx^vG@ft;n2gbXeY^$;7te&?iPCDwCDX-85ro zDi$L)Qb}CNuEg2TX8_fDxnyS9j&D75vIpN%IC}@mGvVMx3_@HVS`HBC&oCCfw8~3d zEbzmM*w);rvhQ4_pN=wKe3>st=%TLMvTg|TKUUsjuukych3md-4?b4FKm4wDM z8rQEm7;g6#1{x}OUETJXt1u>YzFLBXNN4uGCg1>Q|NNt^7;0m`=a(S z1fr7Z!O5kHV2|nx*K}OP@z*9K`WR|D%LzwhG>b1xq|eUTWdNccrgE6GePLr1>HDuT z4d~Y0XpuR|@$MNRE9gIObzjN4EXpw?XHJekDB^+WFFN+;C+%@7bGIyyJREWwb2RjF zJYH#i`v8<#TE?17)SVF&N1Yd>Om)7N(Ia#SJz{Xk;L0%*sStZf(=>XNSYkyO(Tn=Z zQQ3(VEO?Kqv1ggD3;s|C>z8`9A{^zCG1kdb@e7BU(#(N|8uO)vziUjtU*`2&xsy5m zb%Y+uyemUz4I*HLJ+*XwfWuWDX}D^1W`Q}e#z4a3!{SV~1q4~5u>j?V&szW*HGHIU z9BCNk7svlH;Z?j7`IQy}aw)`;f$6uVIys>xr19iLMaZ<_CXELBwMuI+@m9o4nDYa7 zCy3tI*Ia5_t2@c9+{BoCeLC{$=wC(Rw-qG@k#4kW}TVuOj4mZ$9x4z0OH5 zs|eAUJOP|JBvk~@Ov#TgC3OXG%_K3T^CmG7595NCbBtFH`#a~_5;v7Q{=47$D*jT! z?cU|#Tww#yCjcUVn0a3R5sdpB(6__5o3RIBbir|}3{r!yCgai-zF>#Z1aFi)W1KCCOA9DyoZ znj&PW_ZB`y{2XU$?H#P^tlQpN=L=Jz)#`f~mebi~AOiW(x7k#kSGUG%+a>TW->NBs zt(`!B?c2k{oTaGG;<&eIa~m`2f-`r<%p1Aqx01G;rE|Leo#aYHJ`$K=m%Y*fJe9=> zhw_bw?v-{6;tt%MP^XlBOq*q wms_permission.id` 外键已生效,SequelizeMeta 已登记 `20260323103000-align-role-permission-fk.js`。 -- 已完成数据清洗与备份: 4 条 permission 孤儿、3 条 role.store_id=0 哨兵数据均已处理(备份表见 `role_permission_fk_data_cleanup_plan.md`)。 +- 已完成数据清洗与备份: 4 条 permission 孤儿、3 条 role.store_id=0 哨兵数据均已处理(备份表见 `temp/docs/role_permission_fk_data_cleanup_plan.md`)。 - 已完成 `wms_role.store_id` 外键策略落地:外键 `fk_wms_role_store` 已生效(ON DELETE SET NULL),SequelizeMeta 已登记 `20260323113000-add-role-store-fk.js`。 - 已完成 store_warehouse / stock_warehouse 模型层复合键语义治理(统一 include 构造器 + constraints:false 显式化)。 - 已完成阶段 4 收尾检查(第 1 项):全量 include alias 一致性扫描(service alias 与 model alias 差集=0)。 - 已完成阶段 4 收尾检查(第 2 项):permission.parent_id 自关联约束策略已落地(root=NULL + FK)。 -- 已完成阶段 5.1:识别应迁移到 service 层的方法能力(第一批清单见 model_cleanup_list.md)。 -- 已启动阶段 5.2:已完成第一批 P2 无调用静态方法清理(ApiApp / InterfaceType / PrintItem),门禁通过。 -- 已完成阶段 5.2 删除前引用复核(第二批):I18nTranslation 5 个候选静态方法、StockStore 2 个候选静态方法均未检出业务调用。 -- 已完成阶段 5.2 第二批 P2 方法删除(I18nTranslation / StockStore),compare + generated regression + smoke 门禁通过。 -- 已完成阶段 5.2 P1 第一组迁移:EntryOrder / EntryItems 共 8 个静态方法已迁移到 `app/service/systems/entry_order.js`,并从 model 删除;compare + generated regression + smoke 门禁通过。 -- 已完成阶段 5.2 P1 第二组迁移:Storage 共 10 个静态方法已迁移到 `app/service/systems/storage/index.js`,并从 model 删除。 -- 下一步继续阶段 5.2:推进 P1 剩余方法(RolePermission / Store)从 model 向 service 收敛,并在迁移完成后回收对应静态方法。 +- 已完成阶段 5.1:识别应迁移到 service 层的方法能力(第一批清单见 temp/docs/model_cleanup_list.md)。 +- 已完成阶段 5.2 第一批 P2 清理:ApiApp / InterfaceType / PrintItem,门禁通过。 +- 已完成阶段 5.2 第二批 P2 清理:I18nTranslation / StockStore,门禁通过。 +- 已完成阶段 5.2 P1 第一组:EntryOrder / EntryItems 8 个方法迁移到 service 并回收 model 同名方法。 +- 已完成阶段 5.2 P1 第二组:Storage 10 个方法迁移到 service 并回收 model 同名方法。 +- 已完成阶段 5.2 P1 第三组:Role / RolePermission 7 个方法迁移到 service 并回收 model 同名方法。 +- 已完成阶段 5.2 P1 第四组:Store 5 个方法迁移到 service 并回收 model 同名方法。 +- 已完成阶段 5.3:hooks/scopes/virtual fields 边界盘点与规则固化(见 temp/docs/model_boundary_rules.md)。 +- 已完成阶段 5.4:新增 model 边界检查脚本并接入 npm 命令与 CI(check:model-boundary)。 +- 已复跑阶段 5.4 门禁命令:`npm run check:model-boundary`,结果 PASS(files=45, hooks=2, scopeFiles=1, virtualLines=0)。 +- 过程门禁:compare mismatch=0;generated regression 与 smoke 持续通过;新增 model-boundary 检查门禁。 +- 下一步进入阶段 6.1:在干净库上回放 migration 全流程。 diff --git a/package.json b/package.json index 4712c53..2129eed 100644 --- a/package.json +++ b/package.json @@ -39,13 +39,33 @@ }, "scripts": { "start": "egg-scripts start ", - "stop": "egg-scripts stop", + "stop": "node ./app/lib/stop_current_egg.js", "dev": "egg-bin dev --port=6060", + "deploy:init": "node ./script/deploy-init.cjs production", + "deploy:init:dry": "node ./script/deploy-init.cjs production --dry-run", + "deploy:precheck": "node ./script/deploy-precheck.cjs", + "deploy:authcheck": "node ./script/deploy-auth-check.cjs", + "deploy:version": "node ./script/deploy-version.cjs production", + "deploy:version:history": "node ./script/deploy-version.cjs production --history=20", + "deploy:inspect": "node ./script/deploy-ops.cjs production inspect", + "deploy:smoke": "node ./script/deploy-ops.cjs production smoke", + "deploy:verify": "node ./script/deploy-ops.cjs production verify", + "deploy:cleanup-backups": "node ./script/deploy-ops.cjs production cleanup-backups", + "deploy:gateway-probe": "node ./script/deploy-ops.cjs production gateway-probe", + "version:record": "node ./script/version-record.cjs", + "version:history": "node ./script/version-history.cjs --limit=50", + "deploy": "npm run deploy:prod", + "deploy:prod": "node ./script/deploy-remote.cjs production", + "rollback": "npm run rollback:prod", + "rollback:prod": "node ./script/rollback-remote.cjs production", + "guard:git": "node ./script/git-safety-check.cjs", + "setup:hooks": "node ./script/setup-git-hooks.cjs", "test": "npm run lint -- --fix && npm run test:local", "test:local": "egg-bin test", "cov": "egg-bin cov", "lint": "eslint .", - "ci": "npm run lint && npm run cov" + "check:model-boundary": "node ./script/model-boundary-check.cjs", + "ci": "npm run lint && npm run check:model-boundary && npm run cov" }, "repository": { "type": "git", diff --git a/script/deploy-auth-check.cjs b/script/deploy-auth-check.cjs new file mode 100644 index 0000000..05aee43 --- /dev/null +++ b/script/deploy-auth-check.cjs @@ -0,0 +1,42 @@ +'use strict'; + +const { spawnSync } = require('node:child_process'); +const { loadDeployConfig } = require('./deploy-lib.cjs'); + +function main() { + const config = loadDeployConfig('production'); + + const args = [ '-vv' ]; + args.push('-p', String(config.port)); + args.push('-i', config.privateKeyPath); + for (const option of config.sshOptions) { + args.push('-o', option); + } + args.push(`${config.username}@${config.host}`); + args.push('echo AUTH_CHECK_OK'); + + const result = spawnSync('ssh', args, { + encoding: 'utf8', + stdio: 'pipe', + shell: false, + }); + + const text = `${result.stdout || ''}\n${result.stderr || ''}`; + const summary = { + keyOffered: /Offering public key:/i.test(text) || /Will attempt key:/i.test(text), + keyAccepted: /Authenticated to .* using "publickey"/i.test(text) || /AUTH_CHECK_OK/i.test(text), + authFailed: /Permission denied|Authentication failed/i.test(text), + hostKeyFailed: /Host key verification failed|REMOTE HOST IDENTIFICATION HAS CHANGED/i.test(text), + networkFailed: /Connection timed out|No route to host|Connection refused|Could not resolve hostname|Operation timed out/i.test(text), + }; + + console.log(JSON.stringify(summary, null, 2)); + + if (summary.keyAccepted) { + process.exit(0); + } + + process.exit(1); +} + +main(); \ No newline at end of file diff --git a/script/deploy-init.cjs b/script/deploy-init.cjs new file mode 100644 index 0000000..96c34e7 --- /dev/null +++ b/script/deploy-init.cjs @@ -0,0 +1,137 @@ +'use strict'; + +const fs = require('node:fs'); +const path = require('node:path'); +const { + ROOT, + ensureCommandAvailable, + ensureTempDeployDir, + getNowStamp, + loadDeployConfig, + quoteForBash, + runCommand, + runScp, + runSsh, +} = require('./deploy-lib.cjs'); + +function parseArgs(argv) { + const options = { + envName: 'production', + dryRun: false, + }; + + for (const item of argv) { + if (!item) continue; + if (item === '--dry-run') { + options.dryRun = true; + continue; + } + if (!item.startsWith('--')) { + options.envName = item; + } + } + + return options; +} + +function listConfigSeedFiles() { + const output = runCommand('git', [ 'ls-files', '--cached', 'config' ]); + return output + .split(/\r?\n/) + .map(item => item.trim()) + .filter(Boolean) + .filter(item => item.startsWith('config/')) + .filter(item => item !== 'config/config.local.js') + .filter(item => item !== 'config/deploy.config.local.cjs') + .filter(item => item !== 'config/deploy.config.example.cjs'); +} + +function buildConfigSeedArchive(stamp, files) { + const tempDir = ensureTempDeployDir(); + const listPath = path.join(tempDir, `deploy-init-files-${stamp}.txt`); + const archivePath = path.join(tempDir, `deploy-init-${stamp}.tar.gz`); + + if (!files || files.length === 0) { + throw new Error('未找到可用于初始化的 config 文件(git tracked)。'); + } + + fs.writeFileSync(listPath, files.join('\n') + '\n', 'utf8'); + runCommand('tar', [ '-czf', archivePath, '-T', listPath ], { stdio: 'inherit' }); + return { + archivePath, + listPath, + }; +} + +function cleanupLocalTemp(paths) { + for (const filePath of paths) { + if (!filePath) continue; + if (fs.existsSync(filePath)) { + fs.unlinkSync(filePath); + } + } +} + +function main() { + const options = parseArgs(process.argv.slice(2)); + + ensureCommandAvailable('git', '请先安装 Git 并确保 git 在 PATH 中。'); + ensureCommandAvailable('tar', '请先安装 tar,Windows 10/11 通常已内置 bsdtar。'); + ensureCommandAvailable('ssh', '请先安装 OpenSSH Client 并确保 ssh 在 PATH 中。'); + ensureCommandAvailable('scp', '请先安装 OpenSSH Client 并确保 scp 在 PATH 中。'); + + const config = loadDeployConfig(options.envName); + const seedFiles = listConfigSeedFiles(); + + if (options.dryRun) { + console.log(JSON.stringify({ + dryRun: true, + envName: options.envName, + deployRoot: config.deployRoot, + seedFileCount: seedFiles.length, + seedFiles, + }, null, 2)); + return; + } + + const stamp = getNowStamp(); + const { archivePath, listPath } = buildConfigSeedArchive(stamp, seedFiles); + const remoteArchive = `${config.incomingDir}/deploy-init-${stamp}.tar.gz`; + + try { + const setupScript = [ + 'set -euo pipefail', + `mkdir -p ${quoteForBash(config.deployRoot)} ${quoteForBash(config.controlDir)} ${quoteForBash(config.incomingDir)} ${quoteForBash(config.backupDir)} ${quoteForBash(config.stateDir)} ${quoteForBash(path.posix.join(config.deployRoot, 'logs'))} ${quoteForBash(path.posix.join(config.deployRoot, 'run'))} ${quoteForBash(path.posix.join(config.deployRoot, 'temp'))}`, + ].join('\n'); + runSsh(config, setupScript); + runScp(config, archivePath, remoteArchive); + + const remoteScript = [ + 'set -euo pipefail', + `DEPLOY_ROOT=${quoteForBash(config.deployRoot)}`, + `REMOTE_ARCHIVE=${quoteForBash(remoteArchive)}`, + 'CONFIG_DIR="$DEPLOY_ROOT/config"', + 'if [ -d "$CONFIG_DIR" ] && [ "$(find "$CONFIG_DIR" -mindepth 1 -maxdepth 1 | wc -l | tr -d \" \" )" -gt 0 ]; then', + ' echo DEPLOY_INIT_CONFIG_SKIPPED_EXISTS', + 'else', + ' mkdir -p "$CONFIG_DIR"', + ' tar -xzf "$REMOTE_ARCHIVE" -C "$DEPLOY_ROOT"', + ' echo DEPLOY_INIT_CONFIG_CREATED', + 'fi', + 'rm -f "$REMOTE_ARCHIVE"', + ].join('\n'); + + const output = runSsh(config, remoteScript, { stdio: 'pipe' }); + for (const line of output.split(/\r?\n/)) { + if (line.trim()) { + console.log(line.trim()); + } + } + } finally { + cleanupLocalTemp([ archivePath, listPath ]); + } + + console.log(`首次发布初始化完成: ${options.envName} -> ${config.deployRoot}`); +} + +main(); \ No newline at end of file diff --git a/script/deploy-lib.cjs b/script/deploy-lib.cjs new file mode 100644 index 0000000..b724435 --- /dev/null +++ b/script/deploy-lib.cjs @@ -0,0 +1,317 @@ +'use strict'; + +const fs = require('node:fs'); +const path = require('node:path'); +const { spawnSync } = require('node:child_process'); + +const ROOT = path.resolve(__dirname, '..'); +const LOCAL_CONFIG_PATH = path.join(ROOT, 'config', 'deploy.config.local.cjs'); +const EXAMPLE_CONFIG_PATH = path.join(ROOT, 'config', 'deploy.config.example.cjs'); +const DEFAULT_ENV = 'production'; +const DEFAULT_EGG_MINIMAL_INCLUDE_PATHS = [ + 'app.js', + 'app/**', + 'methods/**', + 'native/addons/**', + 'package.json', + 'package-lock.json', +]; +const DEFAULT_POST_DEPLOY_COMMANDS = [ + 'npm install --production', + 'npm run stop || true', + 'npm start', +]; + +function quoteForBash(value) { + return `'${String(value).replace(/'/g, `'"'"'`)}'`; +} + +function runCommand(command, args, options = {}) { + const result = spawnSync(command, args, { + cwd: options.cwd || ROOT, + encoding: 'utf8', + stdio: options.stdio || 'pipe', + shell: false, + }); + + if (result.error) { + throw result.error; + } + + if (result.status !== 0) { + const stderr = (result.stderr || '').trim(); + const stdout = (result.stdout || '').trim(); + throw new Error(stderr || stdout || `${command} exited with code ${result.status}`); + } + + return (result.stdout || '').trim(); +} + +function ensureCommandAvailable(command, installHint) { + const result = spawnSync(command, [], { + cwd: ROOT, + encoding: 'utf8', + stdio: 'pipe', + shell: false, + }); + + if (result.error && result.error.code === 'ENOENT') { + throw new Error(`${command} 不可用。${installHint}`); + } +} + +function getNowStamp() { + const now = new Date(); + const pad = value => String(value).padStart(2, '0'); + return `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`; +} + +function ensureTempDeployDir() { + const tempDir = path.join(ROOT, 'temp', 'deploy'); + fs.mkdirSync(tempDir, { recursive: true }); + return tempDir; +} + +function isPlaceholder(value) { + if (!value) { + return true; + } + return String(value).includes('__FILL_'); +} + +function normalizeDeployConfig(config, envName) { + const deployRoot = config.deployRoot || '/www/wwwroot/qimen'; + const privateKeyPath = config.privateKeyPath ? path.resolve(ROOT, config.privateKeyPath) : ''; + const sshOptions = Array.isArray(config.sshOptions) ? [ ...config.sshOptions ] : []; + const preserveDirs = Array.isArray(config.preserveDirs) ? [ ...config.preserveDirs ] : [ 'config' ]; + + if (!preserveDirs.includes('config')) { + preserveDirs.push('config'); + } + + if (!sshOptions.some(option => /^IdentitiesOnly=/i.test(option))) { + sshOptions.push('IdentitiesOnly=yes'); + } + if (!sshOptions.some(option => /^PreferredAuthentications=/i.test(option))) { + sshOptions.push('PreferredAuthentications=publickey'); + } + if (!sshOptions.some(option => /^PubkeyAuthentication=/i.test(option))) { + sshOptions.push('PubkeyAuthentication=yes'); + } + if (!sshOptions.some(option => /^PasswordAuthentication=/i.test(option))) { + sshOptions.push('PasswordAuthentication=no'); + } + if (!sshOptions.some(option => /^KbdInteractiveAuthentication=/i.test(option))) { + sshOptions.push('KbdInteractiveAuthentication=no'); + } + if (!sshOptions.some(option => /^BatchMode=/i.test(option))) { + sshOptions.push('BatchMode=yes'); + } + if (!sshOptions.some(option => /^ConnectTimeout=/i.test(option))) { + sshOptions.push('ConnectTimeout=10'); + } + + const configuredPostDeployCommands = Array.isArray(config.postDeployCommands) && config.postDeployCommands.length > 0 + ? [ ...config.postDeployCommands ] + : [ ...DEFAULT_POST_DEPLOY_COMMANDS ]; + + if (!configuredPostDeployCommands.some(cmd => /^npm\s+install\s+--production(?:\s|$)/i.test(String(cmd).trim()))) { + configuredPostDeployCommands.unshift('npm install --production'); + } + + return { + envName, + host: config.host, + port: Number(config.port || 22), + username: config.username, + privateKeyPath, + deployRoot, + controlDir: `${deployRoot}/.deploy`, + incomingDir: `${deployRoot}/.deploy/incoming`, + backupDir: `${deployRoot}/.deploy/backups`, + stateDir: `${deployRoot}/.deploy/state`, + sharedDirs: Array.isArray(config.sharedDirs) ? config.sharedDirs : [ 'logs', 'run', 'temp' ], + preserveDirs, + keepBackups: Number(config.keepBackups || 5), + preDeployCommands: Array.isArray(config.preDeployCommands) ? config.preDeployCommands : [], + postDeployCommands: configuredPostDeployCommands, + healthCheckUrl: config.healthCheckUrl || '', + deployIncludePaths: Array.isArray(config.deployIncludePaths) && config.deployIncludePaths.length > 0 + ? config.deployIncludePaths + : DEFAULT_EGG_MINIMAL_INCLUDE_PATHS, + deployExcludePaths: Array.isArray(config.deployExcludePaths) ? config.deployExcludePaths : [ 'config/**' ], + sshOptions, + }; +} + +function validateDeployConfig(config, configPath, envName) { + if (!config) { + throw new Error(`${configPath} 中未找到 ${envName} 配置。`); + } + + const missing = []; + if (isPlaceholder(config.host)) missing.push('host'); + if (isPlaceholder(config.username)) missing.push('username'); + if (isPlaceholder(config.privateKeyPath)) missing.push('privateKeyPath'); + + if (missing.length > 0) { + throw new Error(`请先完善 SSH 配置字段: ${missing.join(', ')}。配置文件: ${configPath}`); + } + + const resolvedPrivateKeyPath = path.resolve(ROOT, config.privateKeyPath); + if (!fs.existsSync(resolvedPrivateKeyPath)) { + throw new Error(`SSH 私钥不存在: ${resolvedPrivateKeyPath}。请先修正 config/deploy.config.local.cjs 中的 privateKeyPath。`); + } +} + +function loadDeployConfig(envName = DEFAULT_ENV) { + if (!fs.existsSync(LOCAL_CONFIG_PATH)) { + throw new Error(`缺少本地部署配置 ${LOCAL_CONFIG_PATH}。请复制 ${EXAMPLE_CONFIG_PATH} 并填入 SSH 信息。`); + } + + delete require.cache[LOCAL_CONFIG_PATH]; + const loaded = require(LOCAL_CONFIG_PATH); + const config = loaded[envName]; + validateDeployConfig(config, LOCAL_CONFIG_PATH, envName); + return normalizeDeployConfig(config, envName); +} + +function buildSshBaseArgs(config) { + const args = [ '-p', String(config.port), '-i', config.privateKeyPath ]; + for (const option of config.sshOptions) { + args.push('-o', option); + } + return args; +} + +function runSsh(config, remoteScript, options = {}) { + const args = [ + ...buildSshBaseArgs(config), + `${config.username}@${config.host}`, + `bash -lc ${quoteForBash(remoteScript)}`, + ]; + + return runCommand('ssh', args, { + stdio: options.stdio || 'inherit', + }); +} + +function runScp(config, localPath, remotePath) { + const args = [ '-P', String(config.port), '-i', config.privateKeyPath ]; + for (const option of config.sshOptions) { + args.push('-o', option); + } + + args.push( + localPath, + `${config.username}@${config.host}:${remotePath}`, + ); + + return runCommand('scp', args, { stdio: 'inherit' }); +} + +function normalizeRule(rule) { + return String(rule || '').replace(/\\/g, '/').trim(); +} + +function pathMatchesRule(filePath, rule) { + const normalizedPath = String(filePath || '').replace(/\\/g, '/'); + const normalizedRule = normalizeRule(rule); + + if (!normalizedRule) { + return false; + } + if (normalizedRule.endsWith('/**')) { + const prefix = normalizedRule.slice(0, -3); + return normalizedPath === prefix || normalizedPath.startsWith(`${prefix}/`); + } + if (normalizedRule.endsWith('/')) { + return normalizedPath.startsWith(normalizedRule); + } + return normalizedPath === normalizedRule; +} + +function listDeployableFiles(config) { + const output = runCommand('git', [ 'ls-files', '--cached' ]); + const includeRules = Array.isArray(config && config.deployIncludePaths) ? config.deployIncludePaths : DEFAULT_EGG_MINIMAL_INCLUDE_PATHS; + const excludeRules = Array.isArray(config && config.deployExcludePaths) ? config.deployExcludePaths : [ 'config/**' ]; + + return output + .split(/\r?\n/) + .map(item => item.trim()) + .filter(Boolean) + .filter(item => !item.startsWith('.git/')) + .filter(item => includeRules.some(rule => pathMatchesRule(item, rule))) + .filter(item => !excludeRules.some(rule => pathMatchesRule(item, rule))); +} + +function buildArchive(stamp, config) { + const tempDir = ensureTempDeployDir(); + const listPath = path.join(tempDir, `deploy-files-${stamp}.txt`); + const archivePath = path.join(tempDir, `release-${stamp}.tar.gz`); + const files = listDeployableFiles(config); + + if (files.length === 0) { + throw new Error('git ls-files 未返回可发布文件,无法生成发布包。'); + } + + fs.writeFileSync(listPath, files.join('\n') + '\n', 'utf8'); + runCommand('tar', [ '-czf', archivePath, '-T', listPath ], { stdio: 'inherit' }); + + return { + archivePath, + listPath, + }; +} + +function buildRemoteCleanupGuard(sharedDirs, preserveDirs = []) { + const preserved = [ '.deploy', ...sharedDirs, ...preserveDirs ]; + return preserved.map(item => `! -name ${quoteForBash(item)}`).join(' '); +} + +function buildScopedEggStopScript(deployRoot) { + return [ + `DEPLOY_ROOT=${quoteForBash(deployRoot)}`, + 'find_deploy_master_pids() {', + " ps -eo pid=,args= | awk -v root=\"$DEPLOY_ROOT\" 'index($0, root) && ($2 == \"node\" || $2 ~ /\\/node$/) && index($0, \"start-cluster\") { print $1 }'", + '}', + 'find_deploy_worker_pids() {', + " ps -eo pid=,args= | awk -v root=\"$DEPLOY_ROOT\" 'index($0, root) && ($2 == \"node\" || $2 ~ /\\/node$/) && (index($0, \"egg-cluster/lib/app_worker.js\") || index($0, \"egg-cluster/lib/agent_worker.js\")) { print $1 }'", + '}', + 'MASTER_PIDS="$(find_deploy_master_pids | tr "\\n" " " | xargs 2>/dev/null || true)"', + 'if [ -n "$MASTER_PIDS" ]; then', + ' echo "STOP_CURRENT_DEPLOY_MASTERS $MASTER_PIDS"', + ' kill $MASTER_PIDS || true', + ' sleep 5', + 'fi', + 'WORKER_PIDS="$(find_deploy_worker_pids | tr "\\n" " " | xargs 2>/dev/null || true)"', + 'if [ -n "$WORKER_PIDS" ]; then', + ' echo "STOP_CURRENT_DEPLOY_WORKERS $WORKER_PIDS"', + ' kill -9 $WORKER_PIDS || true', + 'fi', + ].join('\n'); +} + +function serializeCommands(commands) { + return commands + .filter(Boolean) + .map(command => command.trim()) + .filter(Boolean) + .join('\n'); +} + +module.exports = { + ROOT, + buildArchive, + buildRemoteCleanupGuard, + buildScopedEggStopScript, + ensureCommandAvailable, + ensureTempDeployDir, + getNowStamp, + loadDeployConfig, + quoteForBash, + runCommand, + runScp, + runSsh, + serializeCommands, +}; \ No newline at end of file diff --git a/script/deploy-ops.cjs b/script/deploy-ops.cjs new file mode 100644 index 0000000..f91cf2f --- /dev/null +++ b/script/deploy-ops.cjs @@ -0,0 +1,142 @@ +'use strict'; + +const { loadDeployConfig, quoteForBash, runSsh } = require('./deploy-lib.cjs'); + +const COMMANDS = new Set([ 'inspect', 'smoke', 'verify', 'cleanup-backups', 'gateway-probe' ]); + +function parseArgs(argv) { + const options = { + envName: 'production', + command: '', + args: [], + }; + + const tokens = [ ...argv ]; + if (tokens.length === 0) { + throw new Error('缺少命令: inspect | smoke | verify | cleanup-backups | gateway-probe'); + } + + const first = tokens[0]; + if (!COMMANDS.has(first)) { + options.envName = first; + tokens.shift(); + } + + if (tokens.length === 0) { + throw new Error('缺少命令: inspect | smoke | verify | cleanup-backups | gateway-probe'); + } + + options.command = tokens[0]; + options.args = tokens.slice(1); + + if (!COMMANDS.has(options.command)) { + throw new Error(`不支持的命令: ${options.command}`); + } + + return options; +} + +function inspectState(config) { + const latestBackupFile = `${config.stateDir}/latest-backup.txt`; + const remoteScript = [ + 'set -euo pipefail', + `STATE_DIR=${quoteForBash(config.stateDir)}`, + `BACKUP_DIR=${quoteForBash(config.backupDir)}`, + `LATEST_FILE=${quoteForBash(latestBackupFile)}`, + 'printf "[STATE]\\n"', + 'ls -la "$STATE_DIR"', + 'printf "\\n[LATEST_BACKUP]\\n"', + 'if [ -f "$LATEST_FILE" ]; then cat "$LATEST_FILE"; else echo MISSING; fi', + 'printf "\\n[BACKUPS]\\n"', + 'ls -1 "$BACKUP_DIR"', + ].join('\n'); + + return runSsh(config, remoteScript, { stdio: 'pipe' }).trim(); +} + +function smokeRoutes(config) { + const remoteScript = [ + 'set -euo pipefail', + 'for path in / /api/docs /internal/v1/gateway /system; do', + ' if [ "$path" = "/internal/v1/gateway" ] || [ "$path" = "/system" ]; then', + ' code=$(curl -sS -o /dev/null -w "%{http_code}" -X POST "http://127.0.0.1:6060$path" || true)', + ' else', + ' code=$(curl -sS -o /dev/null -w "%{http_code}" "http://127.0.0.1:6060$path" || true)', + ' fi', + ' printf "%s %s\\n" "$path" "$code"', + 'done', + ].join('\n'); + + return runSsh(config, remoteScript, { stdio: 'pipe' }).trim(); +} + +function cleanupBackups(config, names) { + if (!names.length) { + throw new Error('cleanup-backups 需要至少一个备份文件名'); + } + + const remoteScript = [ + 'set -euo pipefail', + `BACKUP_DIR=${quoteForBash(config.backupDir)}`, + ...names.map((name, index) => `FILE_${index}=${quoteForBash(name)}`), + ...names.map((_, index) => `if [ -f "$BACKUP_DIR/$FILE_${index}" ]; then rm -f "$BACKUP_DIR/$FILE_${index}"; echo "REMOVED $FILE_${index}"; else echo "MISS $FILE_${index}"; fi`), + ].join('\n'); + + return runSsh(config, remoteScript, { stdio: 'pipe' }).trim(); +} + +function gatewayProbe(config, methodName, payloadText) { + if (!methodName) { + throw new Error('gateway-probe 需要 method 名称'); + } + + const payload = payloadText && payloadText.trim() ? payloadText : '{}'; + const remoteScript = [ + 'set -euo pipefail', + `METHOD_NAME=${quoteForBash(methodName)}`, + `PAYLOAD=${quoteForBash(payload)}`, + 'timestamp=$(date +%s)', + 'curl -sS -X POST "http://127.0.0.1:6060/internal/v1/gateway?method=$METHOD_NAME&v=1×tamp=$timestamp" -H "Content-Type: text/plain" --data "$PAYLOAD"', + ].join('\n'); + + return runSsh(config, remoteScript, { stdio: 'pipe' }).trim(); +} + +function main() { + const options = parseArgs(process.argv.slice(2)); + const config = loadDeployConfig(options.envName); + + if (options.command === 'inspect') { + console.log(inspectState(config)); + return; + } + + if (options.command === 'smoke') { + console.log(smokeRoutes(config)); + return; + } + + if (options.command === 'verify') { + console.log(inspectState(config)); + console.log(''); + console.log('[SMOKE]'); + console.log(smokeRoutes(config)); + return; + } + + if (options.command === 'cleanup-backups') { + console.log(cleanupBackups(config, options.args)); + return; + } + + if (options.command === 'gateway-probe') { + const methodName = options.args[0]; + const payloadText = options.args[1] || '{}'; + console.log(gatewayProbe(config, methodName, payloadText)); + return; + } + + throw new Error(`不支持的命令: ${options.command}`); +} + +main(); \ No newline at end of file diff --git a/script/deploy-precheck.cjs b/script/deploy-precheck.cjs new file mode 100644 index 0000000..f140c0e --- /dev/null +++ b/script/deploy-precheck.cjs @@ -0,0 +1,57 @@ +'use strict'; + +const { + loadDeployConfig, + runSsh, + ensureCommandAvailable, +} = require('./deploy-lib.cjs'); + +function main() { + try { + [ 'ssh', 'scp', 'tar', 'git' ].forEach(cmd => ensureCommandAvailable(cmd, '')); + console.log('LOCAL_TOOLS_OK'); + + const config = loadDeployConfig('production'); + const remoteScript = [ + 'set -euo pipefail', + `DEPLOY_ROOT=${JSON.stringify(config.deployRoot)}`, + 'PARENT_DIR=$(dirname "$DEPLOY_ROOT")', + 'if [ -d "$DEPLOY_ROOT" ]; then echo DEPLOY_ROOT_EXISTS; else echo DEPLOY_ROOT_MISSING; fi', + 'if [ -d "$DEPLOY_ROOT" ] && [ -w "$DEPLOY_ROOT" ]; then echo DEPLOY_ROOT_WRITABLE; else echo DEPLOY_ROOT_NOT_WRITABLE; fi', + 'if [ -d "$DEPLOY_ROOT/config" ]; then echo DEPLOY_CONFIG_EXISTS; else echo DEPLOY_CONFIG_MISSING; fi', + 'if [ -d "$PARENT_DIR" ] && [ -w "$PARENT_DIR" ]; then echo PARENT_WRITABLE; else echo PARENT_NOT_WRITABLE; fi', + 'if command -v node >/dev/null 2>&1; then echo REMOTE_NODE_OK; node -v; else echo REMOTE_NODE_MISSING; fi', + 'if command -v npm >/dev/null 2>&1; then echo REMOTE_NPM_OK; npm -v; else echo REMOTE_NPM_MISSING; fi', + 'if command -v tar >/dev/null 2>&1; then echo REMOTE_TAR_OK; tar --version | head -n 1; else echo REMOTE_TAR_MISSING; fi', + 'if command -v curl >/dev/null 2>&1; then if curl -fsS http://127.0.0.1:6060/ >/dev/null; then echo HEALTHCHECK_LOCAL_OK; else echo HEALTHCHECK_LOCAL_FAIL; fi; else echo REMOTE_CURL_MISSING; fi', + ].join('\n'); + + const output = runSsh(config, remoteScript, { stdio: 'pipe' }); + for (const line of output.split(/\r?\n/)) { + if (line.trim()) { + console.log(line.trim()); + } + } + + console.log('PRECHECK_OK'); + } catch (error) { + const message = String(error && error.message ? error.message : ''); + let reason = 'UNKNOWN'; + + if (/Permission denied|Authentication failed/i.test(message)) { + reason = 'AUTH'; + } else if (/Connection timed out|No route to host|Connection refused|Could not resolve hostname/i.test(message)) { + reason = 'NETWORK'; + } else if (/Host key verification failed|REMOTE HOST IDENTIFICATION HAS CHANGED/i.test(message)) { + reason = 'HOST_KEY'; + } else if (/Operation timed out/i.test(message)) { + reason = 'TIMEOUT'; + } + + console.log('PRECHECK_FAIL'); + console.log(`PRECHECK_REASON_${reason}`); + process.exit(1); + } +} + +main(); \ No newline at end of file diff --git a/script/deploy-version.cjs b/script/deploy-version.cjs new file mode 100644 index 0000000..184bad8 --- /dev/null +++ b/script/deploy-version.cjs @@ -0,0 +1,101 @@ +'use strict'; + +const path = require('node:path'); +const { + ensureCommandAvailable, + loadDeployConfig, + quoteForBash, + runSsh, +} = require('./deploy-lib.cjs'); + +function parseArgs(argv) { + const options = { + history: 0, + }; + + for (const item of argv) { + if (!item) continue; + if (item.startsWith('--history=')) { + const value = Number(item.slice('--history='.length)); + if (Number.isFinite(value) && value > 0) { + options.history = Math.floor(value); + } + } + } + + return options; +} + +function queryCurrentRelease(config) { + const releaseFile = path.posix.join(config.stateDir, 'current-release.json'); + const remoteScript = [ + 'set -euo pipefail', + `FILE=${quoteForBash(releaseFile)}`, + 'if [ -f "$FILE" ]; then', + ' cat "$FILE"', + 'else', + ' echo ONLINE_VERSION_NOT_FOUND', + 'fi', + ].join('\n'); + + const output = runSsh(config, remoteScript, { stdio: 'pipe' }).trim(); + if (!output || output === 'ONLINE_VERSION_NOT_FOUND') { + console.log('ONLINE_VERSION_NOT_FOUND'); + return; + } + + try { + const parsed = JSON.parse(output); + console.log(JSON.stringify(parsed, null, 2)); + } catch (error) { + console.log(output); + } +} + +function queryReleaseHistory(config, limit) { + const historyFile = path.posix.join(config.stateDir, 'release-history.jsonl'); + const remoteScript = [ + 'set -euo pipefail', + `FILE=${quoteForBash(historyFile)}`, + `LIMIT=${Number(limit)}`, + 'if [ -f "$FILE" ]; then', + ' tail -n "$LIMIT" "$FILE"', + 'else', + ' echo ONLINE_VERSION_HISTORY_EMPTY', + 'fi', + ].join('\n'); + + const output = runSsh(config, remoteScript, { stdio: 'pipe' }).trim(); + if (!output || output === 'ONLINE_VERSION_HISTORY_EMPTY') { + console.log('ONLINE_VERSION_HISTORY_EMPTY'); + return; + } + + const lines = output.split(/\r?\n/).map(item => item.trim()).filter(Boolean); + const records = []; + for (const line of lines) { + try { + records.push(JSON.parse(line)); + } catch (error) { + records.push({ raw: line }); + } + } + console.log(JSON.stringify(records, null, 2)); +} + +function main() { + const envName = process.argv[2] || 'production'; + const options = parseArgs(process.argv.slice(3)); + + ensureCommandAvailable('ssh', '请先安装 OpenSSH Client 并确保 ssh 在 PATH 中。'); + + const config = loadDeployConfig(envName); + if (options.history > 0) { + queryReleaseHistory(config, options.history); + return; + } + + queryCurrentRelease(config); +} + +main(); \ No newline at end of file diff --git a/script/git-safety-check.cjs b/script/git-safety-check.cjs new file mode 100644 index 0000000..297dab6 --- /dev/null +++ b/script/git-safety-check.cjs @@ -0,0 +1,48 @@ +'use strict'; + +const path = require('node:path'); +const { runCommand } = require('./deploy-lib.cjs'); + +const BLOCKED_PATH_PATTERNS = [ + /^config\/config\.local\.js$/, + /^config\/deploy\.config\.local\.cjs$/, + /^database\/config\.json$/, + /^temp\/(?!docs\/).+/, + /^logs\//, + /^run\//, + /^versioning\/(?!\.gitkeep$).+/, + /\.pem$/i, + /\.key$/i, + /^\.env(?:\..+)?$/, +]; + +function normalizePath(filePath) { + return filePath.replace(/\\/g, '/'); +} + +function listStagedFiles() { + const output = runCommand('git', [ 'diff', '--cached', '--name-only', '--diff-filter=ACMR' ]); + if (!output) { + return []; + } + return output.split(/\r?\n/).map(item => normalizePath(item.trim())).filter(Boolean); +} + +function main() { + const stagedFiles = listStagedFiles(); + const blocked = stagedFiles.filter(filePath => BLOCKED_PATH_PATTERNS.some(pattern => pattern.test(filePath))); + + if (blocked.length === 0) { + console.log('git safety check passed'); + return; + } + + console.error('以下文件禁止提交到 git,请先取消暂存:'); + for (const filePath of blocked) { + console.error(`- ${filePath}`); + } + console.error('建议使用 git restore --staged 取消暂存,再继续提交。'); + process.exit(1); +} + +main(); \ No newline at end of file diff --git a/script/model-boundary-check.cjs b/script/model-boundary-check.cjs new file mode 100644 index 0000000..98c72dd --- /dev/null +++ b/script/model-boundary-check.cjs @@ -0,0 +1,181 @@ +const fs = require('fs'); +const path = require('path'); + +const ROOT = process.cwd(); +const MODEL_DIR = path.join(ROOT, 'app', 'model'); + +const ALLOWED_HOOKS_BY_FILE = { + 'entry_items.js': new Set([ 'beforeSave', 'beforeUpdate' ]), +}; + +const ALLOWED_SCOPE_FILES = new Set([ 'print_item.js' ]); +const ALLOWED_VIRTUAL_FILES = new Set([]); + +const FORBIDDEN_PATTERNS = [ + { + type: 'forbidden-service-call', + message: '模型层禁止直接调用 service', + regex: /\b(?:ctx|this\.ctx|app|this\.app)\.service\b/, + }, + { + type: 'forbidden-http-call', + message: '模型层禁止外部 HTTP 调用', + regex: /\b(?:ctx|this\.ctx)\.(?:curl|httpclient)\b|\baxios\b|\bfetch\s*\(/, + }, + { + type: 'forbidden-cache-call', + message: '模型层禁止读写 Redis/缓存', + regex: /\b(?:ctx|this\.ctx|app|this\.app)\.redis\b/, + }, + { + type: 'forbidden-cross-model-orchestration', + message: '模型层禁止通过 ctx.model 进行跨模型编排', + regex: /\b(?:ctx|this\.ctx)\.model\./, + }, + { + type: 'forbidden-transaction-control', + message: '模型层禁止定义事务控制逻辑', + regex: /\b(?:sequelize|Sequelize)\.transaction\b|\bbeginTransaction\b|\bcommit\s*\(\s*\)|\brollback\s*\(\s*\)/, + }, +]; + +function listJsFiles(dir) { + if (!fs.existsSync(dir)) return []; + + const files = []; + const entries = fs.readdirSync(dir, { withFileTypes: true }); + for (const entry of entries) { + const fullPath = path.join(dir, entry.name); + if (entry.isDirectory()) { + files.push(...listJsFiles(fullPath)); + continue; + } + if (entry.isFile() && entry.name.endsWith('.js')) { + files.push(fullPath); + } + } + + return files.sort(); +} + +function normalizeRelPath(filePath) { + return path.relative(ROOT, filePath).replace(/\\/g, '/'); +} + +function isCommentLine(line) { + const trimmed = line.trim(); + return ( + trimmed === '' || + trimmed.startsWith('//') || + trimmed.startsWith('*') || + trimmed.startsWith('/*') || + trimmed.startsWith('*/') + ); +} + +function scanFile(filePath) { + const relPath = normalizeRelPath(filePath); + const fileName = path.basename(filePath); + const lines = fs.readFileSync(filePath, 'utf8').split(/\r?\n/); + + const violations = []; + const discovered = { + hooks: [], + hasScopes: false, + virtualLines: [], + }; + + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; + if (isCommentLine(line)) continue; + + for (const rule of FORBIDDEN_PATTERNS) { + if (!rule.regex.test(line)) continue; + violations.push({ + relPath, + line: i + 1, + type: rule.type, + message: rule.message, + content: line.trim(), + }); + } + + const hookMatch = line.match(/\b[A-Za-z_]\w*\.((?:before|after)[A-Z]\w*)\s*\(/); + if (hookMatch) { + const hookName = hookMatch[1]; + discovered.hooks.push({ line: i + 1, hookName }); + + const allowSet = ALLOWED_HOOKS_BY_FILE[fileName]; + if (!allowSet || !allowSet.has(hookName)) { + violations.push({ + relPath, + line: i + 1, + type: 'disallowed-hook', + message: '发现未登记的模型 hook,请先更新 temp/docs/model_boundary_rules.md 与 allowlist', + content: line.trim(), + }); + } + } + + if (/\bscopes\s*:/.test(line)) { + discovered.hasScopes = true; + if (!ALLOWED_SCOPE_FILES.has(fileName)) { + violations.push({ + relPath, + line: i + 1, + type: 'disallowed-scopes', + message: '发现未登记的 scopes 定义,请先更新 temp/docs/model_boundary_rules.md 与 allowlist', + content: line.trim(), + }); + } + } + + if (/DataTypes\.VIRTUAL|\bVIRTUAL\s*\(/.test(line)) { + discovered.virtualLines.push(i + 1); + if (!ALLOWED_VIRTUAL_FILES.has(fileName)) { + violations.push({ + relPath, + line: i + 1, + type: 'disallowed-virtual-field', + message: '发现未登记的 virtual 字段定义,请先更新 temp/docs/model_boundary_rules.md 与 allowlist', + content: line.trim(), + }); + } + } + } + + return { violations, discovered }; +} + +function main() { + const files = listJsFiles(MODEL_DIR); + const allViolations = []; + + let hookCount = 0; + let scopeFileCount = 0; + let virtualCount = 0; + + for (const file of files) { + const { violations, discovered } = scanFile(file); + allViolations.push(...violations); + hookCount += discovered.hooks.length; + if (discovered.hasScopes) scopeFileCount += 1; + virtualCount += discovered.virtualLines.length; + } + + console.log('[MODEL-BOUNDARY] scan finished'); + console.log(`[MODEL-BOUNDARY] files=${files.length}, hooks=${hookCount}, scopeFiles=${scopeFileCount}, virtualLines=${virtualCount}`); + + if (allViolations.length > 0) { + console.error(`[MODEL-BOUNDARY] violations=${allViolations.length}`); + for (const item of allViolations) { + console.error(`- ${item.relPath}:${item.line} [${item.type}] ${item.message}`); + console.error(` ${item.content}`); + } + process.exit(1); + } + + console.log('[MODEL-BOUNDARY] PASS'); +} + +main(); \ No newline at end of file diff --git a/script/setup-git-hooks.cjs b/script/setup-git-hooks.cjs new file mode 100644 index 0000000..7a9e49f --- /dev/null +++ b/script/setup-git-hooks.cjs @@ -0,0 +1,10 @@ +'use strict'; + +const { runCommand } = require('./deploy-lib.cjs'); + +function main() { + runCommand('git', [ 'config', 'core.hooksPath', '.githooks' ], { stdio: 'inherit' }); + console.log('已设置 core.hooksPath=.githooks'); +} + +main(); \ No newline at end of file diff --git a/script/version-history.cjs b/script/version-history.cjs new file mode 100644 index 0000000..112939d --- /dev/null +++ b/script/version-history.cjs @@ -0,0 +1,27 @@ +'use strict'; + +const { readVersionHistory } = require('./version-registry.cjs'); + +function parseLimit(argv) { + for (const item of argv) { + if (item.startsWith('--limit=')) { + const value = Number(item.slice('--limit='.length)); + if (Number.isFinite(value) && value > 0) { + return Math.floor(value); + } + } + } + return 20; +} + +function main() { + const limit = parseLimit(process.argv.slice(2)); + const records = readVersionHistory(limit); + if (records.length === 0) { + console.log('LOCAL_VERSION_HISTORY_EMPTY'); + return; + } + console.log(JSON.stringify(records, null, 2)); +} + +main(); \ No newline at end of file diff --git a/script/version-record.cjs b/script/version-record.cjs new file mode 100644 index 0000000..61ee498 --- /dev/null +++ b/script/version-record.cjs @@ -0,0 +1,24 @@ +'use strict'; + +const { recordVersionUpdate } = require('./version-registry.cjs'); + +function parseArgs(argv) { + let note = ''; + for (const item of argv) { + if (item.startsWith('--note=')) { + note = item.slice('--note='.length).trim(); + } + } + return { note }; +} + +function main() { + const options = parseArgs(process.argv.slice(2)); + const entry = recordVersionUpdate({ + source: 'version:record', + note: options.note || 'package-version-update', + }); + console.log(JSON.stringify(entry, null, 2)); +} + +main(); \ No newline at end of file diff --git a/script/version-registry.cjs b/script/version-registry.cjs new file mode 100644 index 0000000..4f24b83 --- /dev/null +++ b/script/version-registry.cjs @@ -0,0 +1,93 @@ +'use strict'; + +const fs = require('node:fs'); +const path = require('node:path'); +const { ROOT, runCommand } = require('./deploy-lib.cjs'); + +const VERSION_DIR = path.join(ROOT, 'versioning'); +const VERSION_HISTORY_FILE = path.join(VERSION_DIR, 'package-version-history.jsonl'); +const VERSION_CURRENT_FILE = path.join(VERSION_DIR, 'package-version-current.json'); + +function ensureVersionDir() { + fs.mkdirSync(VERSION_DIR, { recursive: true }); +} + +function getPackageMeta() { + const pkg = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8')); + const packageVersion = String(pkg.version || '0.0.0'); + + let gitCommit = ''; + let gitCommitShort = ''; + let gitBranch = ''; + try { + gitCommit = runCommand('git', [ 'rev-parse', 'HEAD' ]); + gitCommitShort = runCommand('git', [ 'rev-parse', '--short', 'HEAD' ]); + gitBranch = runCommand('git', [ 'rev-parse', '--abbrev-ref', 'HEAD' ]); + } catch (error) { + gitCommit = ''; + gitCommitShort = ''; + gitBranch = ''; + } + + return { + packageVersion, + gitCommit, + gitCommitShort, + gitBranch, + }; +} + +function recordVersionUpdate(options = {}) { + ensureVersionDir(); + + const meta = getPackageMeta(); + const entry = { + recordedAt: new Date().toISOString(), + source: options.source || 'manual', + note: options.note || '', + packageVersion: meta.packageVersion, + gitCommit: meta.gitCommit, + gitCommitShort: meta.gitCommitShort, + gitBranch: meta.gitBranch, + releaseVersion: options.releaseVersion || '', + deployRoot: options.deployRoot || '', + remoteBackupFile: options.remoteBackupFile || '', + remoteStateFile: options.remoteStateFile || '', + remoteHistoryFile: options.remoteHistoryFile || '', + }; + + fs.appendFileSync(VERSION_HISTORY_FILE, `${JSON.stringify(entry)}\n`, 'utf8'); + fs.writeFileSync(VERSION_CURRENT_FILE, `${JSON.stringify(entry, null, 2)}\n`, 'utf8'); + return entry; +} + +function readVersionHistory(limit = 20) { + if (!fs.existsSync(VERSION_HISTORY_FILE)) { + return []; + } + + const lines = fs.readFileSync(VERSION_HISTORY_FILE, 'utf8') + .split(/\r?\n/) + .map(item => item.trim()) + .filter(Boolean); + + const take = Math.max(1, Number(limit || 20)); + const selected = lines.slice(-take); + const records = []; + for (const line of selected) { + try { + records.push(JSON.parse(line)); + } catch (error) { + records.push({ raw: line }); + } + } + return records; +} + +module.exports = { + VERSION_CURRENT_FILE, + VERSION_DIR, + VERSION_HISTORY_FILE, + readVersionHistory, + recordVersionUpdate, +}; \ No newline at end of file diff --git a/METHOD_OUTPUT_REGRESSION_20260322.md b/temp/docs/METHOD_OUTPUT_REGRESSION_20260322.md similarity index 100% rename from METHOD_OUTPUT_REGRESSION_20260322.md rename to temp/docs/METHOD_OUTPUT_REGRESSION_20260322.md diff --git a/SERVICE_API_CHANGE_AUDIT_20260322.md b/temp/docs/SERVICE_API_CHANGE_AUDIT_20260322.md similarity index 89% rename from SERVICE_API_CHANGE_AUDIT_20260322.md rename to temp/docs/SERVICE_API_CHANGE_AUDIT_20260322.md index 3548ca9..8951049 100644 --- a/SERVICE_API_CHANGE_AUDIT_20260322.md +++ b/temp/docs/SERVICE_API_CHANGE_AUDIT_20260322.md @@ -655,7 +655,7 @@ - 无 - 返回结构变化: 无 - 兼容处理: - - 清理前已完成删除前引用复核(service/controller/test/script 全仓扫描) + - 清理前完成删除前引用复核(service/controller/test/script 全仓扫描) - 仅删除静态 helper,不触碰关联定义、字段定义与实例方法 - 删除项: - I18nTranslation.getTranslation / I18nTranslation.batchGetTranslations / I18nTranslation.getProjectTranslations / I18nTranslation.upsertTranslation / I18nTranslation.getUntranslated @@ -670,11 +670,6 @@ - generated regression: 8 passing - smoke: 6 passing - tests: 14 passing -- 回归结果: - - compare: total=8, mismatch=0 - - generated regression: 8 passing - - smoke: 6 passing - - tests: 14 passing ### 2026-03-23 模型能力治理执行(第十八批:阶段 5.2 P1 第一组迁移) @@ -689,14 +684,18 @@ - 无(对外接口参数与返回结构未变化) - 返回结构变化: 无 - 兼容处理: - - 迁移 `EntryOrder.findByOrderCode/findByStatus/getStatsByWarehouse/updateSyncStatus/updateOrderStatus/calculateReceivedQuantities` - - 迁移 `EntryItems.batchUpdateReceived/getOrderProgress` - - `calculateReceivedQuantities` 改为 service 侧显式聚合 `wms_storage`,避免 model 版相关子查询别名不稳定 + - 迁移 EntryOrder.findByOrderCode/findByStatus/getStatsByWarehouse/updateSyncStatus/updateOrderStatus/calculateReceivedQuantities + - 迁移 EntryItems.batchUpdateReceived/getOrderProgress - 验证方式: - node .\script\method-output-regression.cjs compare - node .\script\tmp-generate-method-regression-test.cjs - npx egg-bin test temp/generated-tests/system.method-output.generated.test.js - npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js +- 回归结果: + - compare: total=8, mismatch=0 + - generated regression: 8 passing + - smoke: 6 passing + - tests: 14 passing ### 2026-03-23 模型能力治理执行(第十九批:阶段 5.2 P1 第二组迁移) @@ -710,10 +709,83 @@ - 无(对外接口参数与返回结构未变化) - 返回结构变化: 无 - 兼容处理: - - 迁移 `Storage.findByStockAndBatch/findBySpace/findAvailableByWarehouse/findExpiringSoon/updateQuantity/lockQuantity/unlockQuantity/allocateQuantity/getStockSummary/getSpaceUsage` - - 模型层仅保留实例行为与关联定义,跨记录聚合与更新能力归并到 service + - 迁移 Storage.findByStockAndBatch/findBySpace/findAvailableByWarehouse/findExpiringSoon/updateQuantity/lockQuantity/unlockQuantity/allocateQuantity/getStockSummary/getSpaceUsage - 验证方式: - node .\script\method-output-regression.cjs compare - node .\script\tmp-generate-method-regression-test.cjs - npx egg-bin test temp/generated-tests/system.method-output.generated.test.js - - npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js \ No newline at end of file + - npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js +- 回归结果: + - compare: total=8, mismatch=0 + - generated regression: 8 passing + - smoke: 7 passing + - tests: 15 passing + +### 2026-03-23 模型能力治理执行(第二十批:阶段 5.2 P1 第三组迁移) + +- 修改范围: 将 Role / RolePermission 的权限编排方法迁移到 service,收敛 model 职责 +- 涉及 service/model: + - app/service/systems/auth/role_permission.js + - app/model/role.js + - app/model/role_permission.js +- 上游入口: + - 无直接新增 system/qimen method;属于内部服务能力收敛 +- 更新的 API 文档: + - 无(对外接口参数与返回结构未变化) +- 返回结构变化: 无 +- 兼容处理: + - 迁移 Role.assignPermissions/getPermissionTree/getPermissionIds + - 迁移 RolePermission.bulkAssign/clearRolePermissions/getRolePermissions/hasPermission +- 验证方式: + - node .\script\method-output-regression.cjs compare + - node .\script\tmp-generate-method-regression-test.cjs + - npx egg-bin test temp/generated-tests/system.method-output.generated.test.js + - npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js +- 回归结果: + - compare: total=8, mismatch=0 + - generated regression: 8 passing + - smoke: 7 passing + - tests: 15 passing + +### 2026-03-23 模型能力治理执行(第二十一批:阶段 5.2 P1 第四组迁移) + +- 修改范围: 将 Store 的校验与查询助手方法迁移到 service,收敛 model 职责 +- 涉及 service/model: + - app/service/systems/store.js + - app/model/store.js +- 上游入口: + - 无直接新增 system/qimen method;属于内部服务能力收敛 +- 更新的 API 文档: + - 无(对外接口参数与返回结构未变化) +- 返回结构变化: 无 +- 兼容处理: + - 迁移 Store.validateStoreData/checkCompanyNameExists/findByAccountId/findAllEnabled/findAllWarehouses +- 验证方式: + - node .\script\method-output-regression.cjs compare + - node .\script\tmp-generate-method-regression-test.cjs + - npx egg-bin test temp/generated-tests/system.method-output.generated.test.js + - npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js +- 回归结果: + - compare: total=8, mismatch=0 + - generated regression: 8 passing + - smoke: 7 passing + - tests: 15 passing + +### 2026-03-23 系统接口兼容修复(第二十二批:project 请求头校验) + +- 修改范围: 修复 system 请求上下文校验对历史 project=wms 请求头的误拒绝 +- 涉及 service: + - app/service/system.js +- 变更内容: + - `ALLOWED_PROJECTS` 增加 `wms/scm/other`,保持与历史调用兼容 +- 触发原因: + - generated regression 与 smoke 在无业务代码变更时统一出现 400(`project 不支持: wms`) +- 验证方式: + - 直接调用 `user.login`(platform=web, project=wms)回归 + - compare + generated regression + smoke 全量重跑 +- 回归结果: + - login: HTTP 200 + - compare: total=8, mismatch=0 + - generated regression: 8 passing + - smoke: 7 passing + - tests: 15 passing \ No newline at end of file diff --git a/association_eager_loading_n_plus_one_guideline.md b/temp/docs/association_eager_loading_n_plus_one_guideline.md similarity index 100% rename from association_eager_loading_n_plus_one_guideline.md rename to temp/docs/association_eager_loading_n_plus_one_guideline.md diff --git a/association_fix_plan.md b/temp/docs/association_fix_plan.md similarity index 100% rename from association_fix_plan.md rename to temp/docs/association_fix_plan.md diff --git a/association_fk_consistency_report.md b/temp/docs/association_fk_consistency_report.md similarity index 100% rename from association_fk_consistency_report.md rename to temp/docs/association_fk_consistency_report.md diff --git a/association_validation_checklist.md b/temp/docs/association_validation_checklist.md similarity index 100% rename from association_validation_checklist.md rename to temp/docs/association_validation_checklist.md diff --git a/migration_execution_plan.md b/temp/docs/migration_execution_plan.md similarity index 100% rename from migration_execution_plan.md rename to temp/docs/migration_execution_plan.md diff --git a/migration_gap_list.md b/temp/docs/migration_gap_list.md similarity index 100% rename from migration_gap_list.md rename to temp/docs/migration_gap_list.md diff --git a/modelList.md b/temp/docs/modelList.md similarity index 100% rename from modelList.md rename to temp/docs/modelList.md diff --git a/model_association_inventory.md b/temp/docs/model_association_inventory.md similarity index 100% rename from model_association_inventory.md rename to temp/docs/model_association_inventory.md diff --git a/temp/docs/model_boundary_rules.md b/temp/docs/model_boundary_rules.md new file mode 100644 index 0000000..c334808 --- /dev/null +++ b/temp/docs/model_boundary_rules.md @@ -0,0 +1,105 @@ +# model_boundary_rules + +更新时间: 2026-03-23 +适用范围: app/model/**/*.js +目标: 约束 model 层仅承担数据映射与轻量领域行为,避免业务编排回流到模型层。 + +## 1. 当前盘点结果(阶段 5.3) + +- hooks: + - app/model/entry_items.js + - EntryItems.beforeSave + - EntryItems.beforeUpdate +- scopes: + - app/model/print_item.js + - tableFields + - groupFields + - active + - byBusiness + - byPlatform +- virtual fields: + - 当前未检出 DataTypes.VIRTUAL / VIRTUAL 字段定义。 + +结论: +- 目前模型层 hooks/scopes 使用量较低,适合在当前阶段一次性固化边界规则。 + +## 2. 模型层职责边界 + +模型层允许: +- 表结构映射(字段、索引、注释、主键、表名映射)。 +- 关联定义(belongsTo/hasMany/hasOne/belongsToMany)与关联语义辅助。 +- 轻量实例行为(如 isEnabled/isExpired/getProgress 等纯实例判断)。 +- 与单行数据一致性相关的同步校验(例如数量非负、上下限关系)。 + +模型层禁止: +- 跨表业务编排(批量流转、聚合统计、分配策略、权限树组装)。 +- 事务边界控制(begin/commit/rollback)与重试策略。 +- 外部副作用(调用第三方接口、写 Redis、发消息、发通知)。 +- 依赖请求上下文(ctx、当前登录人、租户动态鉴权)。 + +## 3. Hooks 规则 + +允许场景: +- 单行数据写入前的确定性校验。 +- 无 I/O 的轻量数据规整(例如 trim、默认值兜底)。 + +禁止场景: +- hook 中查询其他 model 决定业务分支。 +- hook 中进行跨记录批处理或库存/权限编排。 +- hook 中访问 service、http、cache、mq。 + +实现要求: +- 必须保持幂等与可重复执行安全。 +- 必须是低成本逻辑,避免在热路径引入重查询。 +- 错误信息聚焦数据约束,不承载业务流程语义。 + +## 4. Scopes 规则 + +允许场景: +- 静态筛选片段复用(状态、业务类型、平台等)。 +- 参数化但纯查询片段的 where 条件构造。 + +禁止场景: +- 将权限判断或业务流程分支下沉到 scope。 +- 在 scope 中拼装复杂 include 链并耦合排序/分页策略。 +- 在 scope 中引入时间窗口策略或上下文依赖(如当前用户、当前 project)。 + +实现要求: +- scope 输出应稳定、可预期、可独立单测。 +- 命名必须体现过滤语义,不使用模糊命名。 + +## 5. Virtual Fields 规则 + +允许场景: +- 展示层只读衍生值(字段拼接、标签映射、轻量格式化)。 + +禁止场景: +- virtual getter 内进行数据库查询或异步调用。 +- 承载鉴权、状态流转或可写业务语义。 + +实现要求: +- 明确只读语义,不作为持久化字段参与写入。 +- 若需要跨表推导,改由 service 返回 DTO 字段。 + +## 6. 现有代码归属说明 + +- app/model/entry_items.js hooks 保留原因: + - 仅执行已收货数量与计划数量的单行一致性校验。 + - 未引入跨表查询、事务或副作用,符合模型边界。 + +- app/model/print_item.js scopes 保留原因: + - 仅复用静态筛选条件,不承载业务编排。 + - 范围清晰,可作为查询片段复用。 + +## 7. 变更准入清单(新增/修改 model 时必须检查) + +- 是否引入了跨表编排逻辑?若是,必须移至 app/service/systems/*。 +- 是否引入了事务控制?若是,必须移至 service。 +- 是否新增 hook 且包含 I/O?若是,不允许合入。 +- 是否新增 scope 且耦合业务流程/鉴权?若是,不允许合入。 +- 是否新增 virtual 并依赖查询/异步?若是,不允许合入。 + +## 8. 与阶段计划的映射 + +- 阶段 5.3: 已完成(盘点 + 规则固化)。 +- 阶段 5.4: 基于本文件持续执行审查,作为后续模型改动的门禁依据。 \ No newline at end of file diff --git a/model_cleanup_list.md b/temp/docs/model_cleanup_list.md similarity index 58% rename from model_cleanup_list.md rename to temp/docs/model_cleanup_list.md index 84557b6..12f0cf0 100644 --- a/model_cleanup_list.md +++ b/temp/docs/model_cleanup_list.md @@ -1,7 +1,7 @@ # model_cleanup_list 更新时间: 2026-03-23 -阶段: 5.1 识别应迁移到 service 层的方法能力(第一批) +阶段: 5.4 模型边界规则固化与门禁脚本接入(已执行) ## 1. 盘点结论 @@ -104,11 +104,6 @@ - app/model/print_item.js: `getGroupFields`、`getTableConfigs`(已删除) - 门禁结果: compare mismatch=0,generated regression + smoke=14 passing -- 已执行(第二批): - - app/model/i18n_translation.js: `getTranslation`、`batchGetTranslations`、`getProjectTranslations`、`upsertTranslation`、`getUntranslated`(已删除) - - app/model/stock_store.js: `findByItemCode`、`findByStore`(已删除) - - 门禁结果: compare mismatch=0,generated regression=8 passing,smoke=6 passing(合计 14 passing) - - app/model/i18n_translation.js: - getTranslation - batchGetTranslations @@ -131,27 +126,6 @@ 说明: - 上述方法本轮未检出业务层调用,建议先完成一次“删除前引用复核”再执行清理。 -### 3.1 删除前引用复核(第二批) - -- 复核时间: 2026-03-23 -- 复核范围: - - app/model/i18n_translation.js - - app/model/stock_store.js - - app/service/**/*.js - - app/controller/**/*.js - - test/**/*.js - - script/**/*.js -- 复核方式: - - 方法名精确检索: getTranslation / batchGetTranslations / getProjectTranslations / upsertTranslation / getUntranslated / findByItemCode / findByStore - - 模型调用链检索: I18nTranslation.、ctx.model.I18nTranslation.、StockStore.、ctx.model.StockStore. - - 动态调用兜底检索: ['methodName'] 形式 -- 复核结论: - - 未检出 I18nTranslation 5 个候选静态方法的业务调用。 - - 未检出 StockStore 2 个候选静态方法的业务调用。 - - 检出 I18n 相关业务仍直接使用了模型基础能力(findAll/findOne/create/count),不受本次候选方法删除影响。 -- 可执行动作: - - 已执行清理并通过门禁,第二批可删除候选已关闭。 - ## 4. 保留在模型层(P3) 建议保留: @@ -159,14 +133,34 @@ - 纯格式/展示映射(getTypeName/getRoleTypeName/getScopeName)。 - 与关联语义绑定的 include 构造器(StoreWarehouse.buildStoreStockInclude)。 -## 5. 下一步(5.2 输入) +## 5. 阶段状态(截至 2026-03-23) -1. 已完成 P1 第一组迁移:EntryOrder / EntryItems 的 8 个静态方法已迁移到 app/service/systems/entry_order.js,并从 model 删除。 -2. 已完成 P1 第二组迁移:Storage 的 10 个静态方法已迁移到 app/service/systems/storage/index.js,并从 model 删除。 -3. 下一步继续迁移 P1 剩余项:RolePermission / Store。 -4. 最后补 model_boundary_rules.md,固化模型层边界。 +1. 已完成 P1 四组迁移(EntryOrder/EntryItems、Storage、Role/RolePermission、Store)到 service。 +2. 已完成 P2 第二批清理(I18nTranslation / StockStore),并通过门禁。 +3. 已完成 5.3:完成 hooks/scopes/virtual fields 全量盘点并形成规则。 +4. 已完成 5.4:新增可执行门禁脚本并接入 npm/CI。 -## 6. 已执行(P1 第一组) +## 6. 已执行(P2 第二批) + +- 执行时间: 2026-03-23 +- 删除范围: + - app/model/i18n_translation.js + - app/model/stock_store.js +- 删除方法: + - I18nTranslation.getTranslation + - I18nTranslation.batchGetTranslations + - I18nTranslation.getProjectTranslations + - I18nTranslation.upsertTranslation + - I18nTranslation.getUntranslated + - StockStore.findByItemCode + - StockStore.findByStore +- 门禁结果: + - compare mismatch=0 + - generated regression=8 passing + - smoke=6 passing + - tests=14 passing + +## 7. 已执行(P1 第一组) - 执行时间: 2026-03-23 - 迁移范围: @@ -182,16 +176,13 @@ - EntryOrder.calculateReceivedQuantities - EntryItems.batchUpdateReceived - EntryItems.getOrderProgress -- 说明: - - 对外 system/qimen method 未新增接口,属于内部职责收敛。 - - `calculateReceivedQuantities` 在 service 中改为显式查询 Storage 聚合,避免原 model 版本的相关子查询别名漂移风险。 - 门禁结果: - compare mismatch=0 - generated regression=8 passing - smoke=6 passing - tests=14 passing -## 7. 已执行(P1 第二组) +## 8. 已执行(P1 第二组) - 执行时间: 2026-03-23 - 迁移范围: @@ -208,6 +199,94 @@ - Storage.allocateQuantity - Storage.getStockSummary - Storage.getSpaceUsage -- 说明: - - 对外 system/qimen method 未新增接口,属于内部职责收敛。 - - 更新类方法统一进入 service,模型层仅保留实例行为与关联映射。 +- 门禁结果: + - compare mismatch=0 + - generated regression=8 passing + - smoke=7 passing + - tests=15 passing + +## 9. 已执行(P1 第三组) + +- 执行时间: 2026-03-23 +- 迁移范围: + - app/model/role.js + - app/model/role_permission.js + - app/service/systems/auth/role_permission.js +- 迁移方法: + - Role.assignPermissions + - Role.getPermissionTree + - Role.getPermissionIds + - RolePermission.bulkAssign + - RolePermission.clearRolePermissions + - RolePermission.getRolePermissions + - RolePermission.hasPermission +- 门禁结果: + - compare mismatch=0 + - generated regression=8 passing + - smoke=7 passing + - tests=15 passing + +## 10. 已执行(P1 第四组) + +- 执行时间: 2026-03-23 +- 迁移范围: + - app/model/store.js + - app/service/systems/store.js +- 迁移方法: + - Store.validateStoreData + - Store.checkCompanyNameExists + - Store.findByAccountId + - Store.findAllEnabled + - Store.findAllWarehouses +- 门禁结果: + - compare mismatch=0 + - generated regression=8 passing + - smoke=7 passing + - tests=15 passing + +## 11. 已执行(5.3 边界规范) + +- 执行时间: 2026-03-23 +- 扫描范围: + - app/model/**/*.js +- 扫描结果: + - hooks: 2 处(EntryItems.beforeSave / EntryItems.beforeUpdate) + - scopes: 1 处定义(PrintItem.scopes) + - virtual fields: 0 +- 产出文档: + - model_boundary_rules.md +- 执行结论: + - 现有 hooks/scopes 均符合“单行一致性校验/静态筛选片段”边界。 + - 后续新增或修改模型逻辑时,按 model_boundary_rules.md 作为合入门禁。 + +## 12. 已执行(5.4 门禁脚本验证) + +- 执行时间: 2026-03-23 +- 执行命令: + - npm run check:model-boundary +- 结果摘要: + - [MODEL-BOUNDARY] files=45 + - [MODEL-BOUNDARY] hooks=2 + - [MODEL-BOUNDARY] scopeFiles=1 + - [MODEL-BOUNDARY] virtualLines=0 + - [MODEL-BOUNDARY] PASS +- 结论: + - 模型边界检查脚本可稳定执行,已具备本地与 CI 统一门禁能力。 + +## 13. 已执行(5.4 门禁固化) + +- 执行时间: 2026-03-23 +- 新增脚本: + - script/model-boundary-check.cjs +- 覆盖规则: + - 禁止 model 直接调用 service + - 禁止 model 外部 HTTP 调用 + - 禁止 model 读写 Redis/缓存 + - 禁止 model 通过 ctx.model 进行跨模型编排 + - 禁止 model 定义事务控制逻辑 + - hooks/scopes/virtual 使用 allowlist 准入 +- 接入方式: + - npm run check:model-boundary + - npm run ci(已串联) +- 执行结论: + - 模型层边界已具备自动化门禁能力,后续新增越界代码可在本地与 CI 及时阻断。 diff --git a/model_inventory.md b/temp/docs/model_inventory.md similarity index 100% rename from model_inventory.md rename to temp/docs/model_inventory.md diff --git a/model_naming_standard.md b/temp/docs/model_naming_standard.md similarity index 100% rename from model_naming_standard.md rename to temp/docs/model_naming_standard.md diff --git a/model_rename_map.md b/temp/docs/model_rename_map.md similarity index 100% rename from model_rename_map.md rename to temp/docs/model_rename_map.md diff --git a/rename_impact_report.md b/temp/docs/rename_impact_report.md similarity index 100% rename from rename_impact_report.md rename to temp/docs/rename_impact_report.md diff --git a/role_permission_fk_data_cleanup_plan.md b/temp/docs/role_permission_fk_data_cleanup_plan.md similarity index 100% rename from role_permission_fk_data_cleanup_plan.md rename to temp/docs/role_permission_fk_data_cleanup_plan.md diff --git a/rollback_plan.md b/temp/docs/rollback_plan.md similarity index 100% rename from rollback_plan.md rename to temp/docs/rollback_plan.md diff --git a/temp/docs/root-md-usage-report.md b/temp/docs/root-md-usage-report.md new file mode 100644 index 0000000..2c505d2 --- /dev/null +++ b/temp/docs/root-md-usage-report.md @@ -0,0 +1,93 @@ +# 根目录 Markdown 使用方与清理结果 + +生成时间: 2026-03-24 + +## 保留在根目录 + +- `README.md` + - 使用方: `model_todo.txt` + - 动作: 保留(项目入口文档) +- `AI_TOOLBOX.md` + - 使用方: `README.md` + - 动作: 保留(AI 协作工具箱) +- `AI_METHOD_ROUTING.md` + - 使用方: `AI_TOOLBOX.md`, `README.md`, `script/tmp-update-ai-method-routing.cjs` + - 动作: 保留(路由映射主文档) + +## 迁移到 temp/docs(需要保留) + +- `METHOD_OUTPUT_REGRESSION_20260322.md` + - 原使用方: `README.md` + - 新路径: `temp/docs/METHOD_OUTPUT_REGRESSION_20260322.md` +- `SERVICE_API_CHANGE_AUDIT_20260322.md` + - 原使用方: `model_todo.txt` + - 新路径: `temp/docs/SERVICE_API_CHANGE_AUDIT_20260322.md` +- `association_eager_loading_n_plus_one_guideline.md` + - 原使用方: `association_validation_checklist.md`, `model_todo.txt`, `SERVICE_API_CHANGE_AUDIT_20260322.md` + - 新路径: `temp/docs/association_eager_loading_n_plus_one_guideline.md` +- `association_fix_plan.md` + - 原使用方: `model_todo.txt` + - 新路径: `temp/docs/association_fix_plan.md` +- `association_fk_consistency_report.md` + - 原使用方: `association_validation_checklist.md`, `model_todo.txt`, `SERVICE_API_CHANGE_AUDIT_20260322.md`, `temp/audit-association-fk.cjs` + - 新路径: `temp/docs/association_fk_consistency_report.md` +- `association_validation_checklist.md` + - 原使用方: `model_todo.txt`, `SERVICE_API_CHANGE_AUDIT_20260322.md` + - 新路径: `temp/docs/association_validation_checklist.md` +- `migration_execution_plan.md` + - 原使用方: `model_todo.txt` + - 新路径: `temp/docs/migration_execution_plan.md` +- `migration_gap_list.md` + - 原使用方: `model_todo.txt` + - 新路径: `temp/docs/migration_gap_list.md` +- `modelList.md` + - 原使用方: `model_todo.txt`, `README.md`, `rename_impact_report.md` + - 新路径: `temp/docs/modelList.md` +- `model_association_inventory.md` + - 原使用方: `model_todo.txt` + - 新路径: `temp/docs/model_association_inventory.md` +- `model_boundary_rules.md` + - 原使用方: `model_cleanup_list.md`, `model_todo.txt`, `script/model-boundary-check.cjs` + - 新路径: `temp/docs/model_boundary_rules.md` +- `model_cleanup_list.md` + - 原使用方: `model_todo.txt`, `SERVICE_API_CHANGE_AUDIT_20260322.md` + - 新路径: `temp/docs/model_cleanup_list.md` +- `model_inventory.md` + - 原使用方: `model_rename_map.md`, `model_todo.txt` + - 新路径: `temp/docs/model_inventory.md` +- `model_naming_standard.md` + - 原使用方: `model_todo.txt` + - 新路径: `temp/docs/model_naming_standard.md` +- `model_rename_map.md` + - 原使用方: `model_todo.txt`, `rename_impact_report.md` + - 新路径: `temp/docs/model_rename_map.md` +- `rename_impact_report.md` + - 原使用方: `model_todo.txt` + - 新路径: `temp/docs/rename_impact_report.md` +- `role_permission_fk_data_cleanup_plan.md` + - 原使用方: `model_todo.txt` + - 新路径: `temp/docs/role_permission_fk_data_cleanup_plan.md` +- `rollback_plan.md` + - 原使用方: `model_todo.txt` + - 新路径: `temp/docs/rollback_plan.md` +- `schema_model_gap_report.md` + - 原使用方: `model_todo.txt` + - 新路径: `temp/docs/schema_model_gap_report.md` +- `table_schema_inventory.md` + - 原使用方: `model_todo.txt` + - 新路径: `temp/docs/table_schema_inventory.md` + +## 已清理(不需要) + +- `tmp-order-schema-workflow.md` + - 原使用方: 无 + - 动作: 已从根目录删除(历史临时流程文档) + +## 引用更新范围 + +- `README.md` +- `model_todo.txt` +- `script/model-boundary-check.cjs` +- `temp/audit-association-fk.cjs` + +所有上述文件中的旧根目录引用已替换为 `temp/docs/*` 新路径。 diff --git a/schema_model_gap_report.md b/temp/docs/schema_model_gap_report.md similarity index 100% rename from schema_model_gap_report.md rename to temp/docs/schema_model_gap_report.md diff --git a/table_schema_inventory.md b/temp/docs/table_schema_inventory.md similarity index 100% rename from table_schema_inventory.md rename to temp/docs/table_schema_inventory.md diff --git a/test/app/controller/system.order.namespaced.test.js b/test/app/controller/system.order.namespaced.test.js index 0822173..f46d91b 100644 --- a/test/app/controller/system.order.namespaced.test.js +++ b/test/app/controller/system.order.namespaced.test.js @@ -140,4 +140,4 @@ describe('test/app/controller/system.order.namespaced.test.js', () => { assert.equal(restoreRes.body.code, 200); assert.equal(restoreRes.body?.data?.inspection_status, originalStatus); }); -}); \ No newline at end of file +}); diff --git a/tmp-order-schema-workflow.md b/tmp-order-schema-workflow.md deleted file mode 100644 index 99c415c..0000000 --- a/tmp-order-schema-workflow.md +++ /dev/null @@ -1,81 +0,0 @@ -# 订单表结构与 Model 比对临时工作流 - -更新时间: 2026-03-22 - -## 1. 目标 - -用于后续排查订单相关问题时,快速复用以下能力: -- 获取数据库订单表结构 -- 与当前 Model 做字段级比对 -- 识别主表/分仓动态表的结构漂移 - -## 2. 本次已确认的订单相关表 - -- wms_entry_order -- wms_order_delivery -- wms_order_delivery_100000 -- wms_order_items -- wms_order_items_100000 - -## 3. 相关 Model - -- app/model/entry_order.js -- app/model/order_delivery.js -- app/model/order_items.js -- app/model/order_delivery_factory.js -- app/model/order_items_factory.js - -## 4. 已生成产物 - -- 结构与差异总结果: temp/tmp-order-schema-compare.json -- 比对脚本(可复跑): script/tmp-compare-order-schema.cjs - -## 5. 关键比对结论 - -### 5.1 wms_entry_order vs entry_order model -- 字段数: model 28 / db 28 -- 结论: 完全一致 - -### 5.2 wms_order_delivery vs order_delivery model -- 字段数: model 72 / db 54 -- model 有但主表 db 没有的字段: - from_key, items, items_count, items_total, items_weight, items_hash, items_crc, wave_id, - post_status, storage_status, pick_status, pack_status, inspection_status, print_status, - claim_status, outbound_status, lock_status, intercept_status -- 结论: 主表结构落后于模型定义 - -补充: -- delivery_time(发货时间) 已在主表与动态表补齐,并同步到 model 与动态建表 SQL。 - -### 5.3 wms_order_items vs order_items model -- 字段数: model 18 / db 15 -- model 有但主表 db 没有的字段: - stock_id, created_at, updated_at -- 结论: 主表结构落后于模型定义 - -### 5.4 动态表 vs 主表 -- wms_order_delivery_100000 相比 wms_order_delivery 多出 18 个字段(与 modelOnly 一致) -- wms_order_items_100000 相比 wms_order_items 多出 3 个字段(与 modelOnly 一致) -- 结论: 动态表更接近当前模型,主表较旧 - -## 6. 复用命令 - -### 6.1 一键重跑比对 -PowerShell: - -node .\script\tmp-compare-order-schema.cjs - -### 6.2 快速查看结果摘要 -PowerShell: - -Get-Content .\temp\tmp-order-schema-compare.json -TotalCount 160 - -## 7. 后续建议 - -1. 若以主表为准,需回退 model 字段定义到主表现状,避免 ORM 读写异常。 -2. 若以模型为准,补充 migration,将主表补齐到动态表同等结构。 -3. 在服务中明确当前读写表策略(主表或动态表),避免混用导致字段可用性不一致。 - -## 8. 备注 - -本文件为临时工作流文件,可在结构收敛后删除或迁移到正式文档。 \ No newline at end of file From 67c6856d7511318a0a78801f9a6b5a7fea8e677e Mon Sep 17 00:00:00 2001 From: liufumingren Date: Wed, 25 Mar 2026 13:17:51 +0800 Subject: [PATCH 009/550] chore: commit current workspace changes --- README.md | 3 - day.log | Bin 30640 -> 35894 bytes model_todo.txt | 146 +--- script/model-boundary-check.cjs | 6 +- .../docs/METHOD_OUTPUT_REGRESSION_20260322.md | 94 --- .../docs/SERVICE_API_CHANGE_AUDIT_20260322.md | 791 ------------------ ...tion_eager_loading_n_plus_one_guideline.md | 102 --- temp/docs/association_fix_plan.md | 61 -- .../docs/association_fk_consistency_report.md | 65 -- temp/docs/association_validation_checklist.md | 165 ---- temp/docs/migration_execution_plan.md | 76 -- temp/docs/migration_gap_list.md | 107 --- temp/docs/modelList.md | 105 --- temp/docs/model_association_inventory.md | 52 -- temp/docs/model_boundary_rules.md | 105 --- temp/docs/model_cleanup_list.md | 292 ------- temp/docs/model_inventory.md | 53 -- temp/docs/model_naming_standard.md | 184 ---- temp/docs/model_rename_map.md | 100 --- temp/docs/rename_impact_report.md | 168 ---- .../role_permission_fk_data_cleanup_plan.md | 104 --- temp/docs/rollback_plan.md | 49 -- temp/docs/root-md-usage-report.md | 93 -- temp/docs/schema_model_gap_report.md | 98 --- temp/docs/table_schema_inventory.md | 85 -- 25 files changed, 20 insertions(+), 3084 deletions(-) delete mode 100644 temp/docs/METHOD_OUTPUT_REGRESSION_20260322.md delete mode 100644 temp/docs/SERVICE_API_CHANGE_AUDIT_20260322.md delete mode 100644 temp/docs/association_eager_loading_n_plus_one_guideline.md delete mode 100644 temp/docs/association_fix_plan.md delete mode 100644 temp/docs/association_fk_consistency_report.md delete mode 100644 temp/docs/association_validation_checklist.md delete mode 100644 temp/docs/migration_execution_plan.md delete mode 100644 temp/docs/migration_gap_list.md delete mode 100644 temp/docs/modelList.md delete mode 100644 temp/docs/model_association_inventory.md delete mode 100644 temp/docs/model_boundary_rules.md delete mode 100644 temp/docs/model_cleanup_list.md delete mode 100644 temp/docs/model_inventory.md delete mode 100644 temp/docs/model_naming_standard.md delete mode 100644 temp/docs/model_rename_map.md delete mode 100644 temp/docs/rename_impact_report.md delete mode 100644 temp/docs/role_permission_fk_data_cleanup_plan.md delete mode 100644 temp/docs/rollback_plan.md delete mode 100644 temp/docs/root-md-usage-report.md delete mode 100644 temp/docs/schema_model_gap_report.md delete mode 100644 temp/docs/table_schema_inventory.md diff --git a/README.md b/README.md index a1c1961..c433c54 100644 --- a/README.md +++ b/README.md @@ -6,8 +6,6 @@ - AI项目协作工具箱:`AI_TOOLBOX.md` - Method 路由映射说明:`AI_METHOD_ROUTING.md` -- Model 层级清单:`temp/docs/modelList.md` -- Method 输出一致性回归记录:`temp/docs/METHOD_OUTPUT_REGRESSION_20260322.md` - system 接口文档源:`methods/system.json` - qimen 接口文档源:`methods/qimen.json` - 日报:`day.log` @@ -40,7 +38,6 @@ - `README.md`:项目入口文档,提供整体说明与规范入口。 - `AI_TOOLBOX.md`:AI/开发协作操作手册,包含脚本与工作流。 - `AI_METHOD_ROUTING.md`:接口入口与 method 到代码文件的映射。 -- `temp/docs/modelList.md`:model 层级结构与关键说明清单。 - `methods/system.json`:system 接口定义(headers、groups、params、response、errors)。 - `methods/qimen.json`:qimen 接口定义(按奇门协议组织)。 - `day.log`:每日工作留痕。 diff --git a/day.log b/day.log index 68d815a5ed8fec068fa70e00cdc1af1ce82c63bf..5701f90ed3ce2c378ea5c5492aa44d41582ace5d 100644 GIT binary patch delta 3989 zcmb7He{2)?75`o+AqLw5(M80Ba@iPIEXIbibWpY10_$KU=h){YWKM0z=9^21<50&o z`2jgtQvq^90!IR)8>|zEsFS)NZLLuMSUYuMT15-h82x878;XjiLaGYUKUjNvpS!qD zfQU|(Y~S7czV~_Wecq27n-tzSQBa_Nb-wVm-P&tOXQAM^Ih0hj50mTFX5R-#F2~MD znb2rV7!p|@QaY&jB857Cco)66)3-ri}4BO&fTD$HwL} z7fC}Q1EP@u@&4n1R zelzrT^Mq2acQSRZR zi=xp^pVk?eXBvl03q4PfT$0S?<8r?oSP(O$c04GhPWfVz1?Hi0y25-$-x<8uWtURC zFlEy50>2s;JY_qxb%JNTbeA9CcO{Qsr1PNNE~45FG8-d}BD2miQi^xFCFPqtOgDD25f=u?mNS%5rh}<*}<&(9^ZxF zCwy{XZ8{SI;Y1^m8FGWO-ONi@2zHXWwez8+f?K;4DxvSz@Ukb|l&Yk`yB3Cs- zwMTQNpIGN+-=}~*Nq*pWJuA}T>s#@{l;F8AxGnwep*b%J9#lZFd~TvtFxyz1APbzh>XfA;-|g!MyYYzZSMj6Z~w{8sM#Wn#QQiqTz*6 zglYBRz6=Xrk?qnM=_Bc@W0M27AP>Oo_x%PC*12I(&hByLcj&_hB}mHB-PV>2!e3gI0N< zMLKwm42$fNJfW-{_(B#{wv}yW7CjR>8{{+AV;Rt+6(IK(vu?C|+tL|e3FxvCh! z1sfZUDn$>D5S46_vraU43`UF0C0TTLe%Ovi*A*<27gUH}f$uWdZmJb`s4|mY1 zC{}Z*iZxH&;}1`e{vz~KzK!sdsEfcA9 zjfJ9>^jh`)lkccm2+Zks(!taI$E8mw1aPW@xQ;=Biv8h?p8d=>XNCb@WPcyLURx?6 zAvS4y&{?-k%%@7V#O_J2`q7i$JyhaHqsdJohc5cT5)4RWMPzpA;^2aAY$H}ZG6fD( z>i)uVQL*OxqHBusE;`XjPPLMQ=#YkUD~&Ptpn{p{c4=kS#Y?6uFbCr2FU(DJcWZx6 zuh4$BsIr(HuaQ4Z9*s>X?!c&jZT)u#HZ+gdY89D&6I?;Hn`g2~9 zNyg@oV4a4W$3o6@Wy9W#El?x7S#OUmP}{@Pj)v6=Q~uifOrNLDsu$Pa9QsrC_VBTh zx4JG#zxLJ+*aNqEkxj^A(=?+D>R7aknOB7ht!?)z0}1Ry67=rN%(QNHg?0)d#y_X> z=z0KCS#$r%BKUI7BFee_Xti`usqH!$`+3HVAcN{ zyt7}Vv9g(li-~ERPs(q%Ki&4>q2wVuN{Uf*ayQg&mbMjbp zhkjIE5;B{bpNck4wlOb7=B%^CzQ|U_ksYk-?esQ-B25`jClnj4p0JIV6Rc!aBjHA7-q~h z5o&TLamrMungeNiJW9oJo{L9^{7O`$CDKEmWny0@-ihLVdg#cYRo}ojN>C&k8v9%H$;N!R3ZrL1)WAN9W&z7)uzMY!HS(K2!;Yj1Msau}>DSAKVRoZpjb zyvP|ih4A0o^KtK_j6t2l1)h%ct4rg{cb^I(GYBcdRitlJ7d1@E&b0Q~=F&A5nvLu@ c3IQc>&dU#0pN5^B_MY%?=+^M>JItQ;KhpbqlK=n! delta 17 ZcmdlsgK5KiMyCJ&CQm3A+bA-l8~{%B2y_4d diff --git a/model_todo.txt b/model_todo.txt index 7dd5e96..7c603f0 100644 --- a/model_todo.txt +++ b/model_todo.txt @@ -1,135 +1,23 @@ -Model 重构总计划(数据库 + Migrations + Models) -更新时间: 2026-03-23 -当前状态: 执行中(阶段 1-5 已完成,阶段 6 进行中) -负责人: -目标截止时间: -执行分支: +Model 重构总计划(已完成归档) +更新时间: 2026-03-25 +当前状态: 已完成 [事务归属] - 本子事务已纳入 `todo.txt` 总事务看板统一管理。 -- 主里程碑对齐总事务 DDL(2026-04-15),以总事务验收为最终关闭条件。 -[最终目标] -- 梳理数据库中所有表结构并形成统一基线。 -- 补全并对齐 database/migrations 目录下的迁移文件。 -- 规范所有 model 的命名与内部关联。 -- 清理所有 model 内部能力(移除死代码、职责收敛、保持模型层可预测)。 +[完成状态] +- [x] 阶段 1: 全量盘点与基线建立 +- [x] 阶段 2: Migration 补全与执行顺序设计 +- [x] 阶段 3: Model 命名规范化 +- [x] 阶段 4: 关联关系规范化 +- [x] 阶段 5: Model 内部能力清理 +- [x] 阶段 6: 验证与交接 -[执行规则] -- [x] 本文件用于规划拆解,已完成初始化。 -- [x] 已收到新任务,开始执行阶段 1。 -- [x] 进入代码改动前,先核对目标 service 的真实调用链。 -- [x] 若 service 已被 system/qimen 入口使用,则必须同步更新对应 API 文档。 -- [x] 所有联动修改需记录到 temp/docs/SERVICE_API_CHANGE_AUDIT_20260322.md,便于后续复盘。 -- [x] 任何模型/关联改动前,使用测试账号执行 method 基线回放(配置与样本来源必须可追溯)。 -- [x] 任何模型/关联改动后,执行同一批 method 对比回放并输出比对报告。 -- [x] 新增交付条件:修改前后 method 输出结果一致(允许仅屏蔽 token/timestamp 等波动字段)。 -- [x] 后续所有接口返回数据检测,统一使用“自动生成的 Egg.js 标注测试脚本”执行校验。 +[收口说明] +- [x] 本文件由执行计划切换为归档摘要,不再保留阶段性过程清单。 +- [x] 本任务相关临时文档已从 `temp/docs/` 清理。 +- [x] 本任务相关临时中间文件已从 `temp/` 清理。 +- [x] README 中对已清理临时文档的入口已移除。 -[阶段 1: 全量盘点与基线建立] -- [x] 1.1 盘点所有数据表(字段、主键、索引、约束、注释)。 -- [x] 1.2 盘点所有 model 文件(app/model 下文件、导出名、表映射)。 -- [x] 1.3 盘点 model 关联(belongsTo/hasMany/hasOne/belongsToMany 与外键使用)。 -- [x] 1.4 产出 DB 结构与 model 定义差异报告。 -- [x] 1.5 在根目录生成 temp/docs/modelList.md,构建 model 层级结构与说明。 -- [x] 1.6 在 README.md 增加对 temp/docs/modelList.md 的引用说明。 -交付物: -- temp/docs/table_schema_inventory.md -- temp/docs/model_inventory.md -- temp/docs/model_association_inventory.md -- temp/docs/schema_model_gap_report.md -- temp/docs/modelList.md -退出标准: -- 100% 数据表与 100% model 文件覆盖完成。 -- temp/docs/modelList.md 可用于快速定位模型层级与职责。 - -[阶段 2: Migration 补全与执行顺序设计] -- [x] 2.1 审核现有 database/migrations 的命名、顺序、幂等性。 -- [x] 2.2 根据阶段 1 差异清单补齐缺失迁移任务。 -- [x] 2.3 设计迁移执行顺序(先结构后索引/约束,必要时分批回填数据)。 -- [x] 2.4 为每个迁移定义可执行回滚步骤。 -- [x] 2.5 形成 local/test 环境演练方案。 -交付物: -- temp/docs/migration_gap_list.md -- temp/docs/migration_execution_plan.md -- temp/docs/rollback_plan.md -退出标准: -- 每个结构差异都有明确迁移归属与回滚路径。 - -[阶段 3: Model 命名规范化] -- [x] 3.1 定义命名规范(文件名、类名、model key、表映射、alias)。 -- [x] 3.2 产出非规范命名的重命名映射表。 -- [x] 3.3 评估跨层影响(service/controller/query 调用点)。 -- [x] 3.4 制定兼容策略(临时别名或分批重命名)。 -交付物: -- temp/docs/model_naming_standard.md -- temp/docs/model_rename_map.md -- temp/docs/rename_impact_report.md -退出标准: -- 所有命名不规范项有明确修复路径与影响说明。 - -[阶段 4: 关联关系规范化] -- [x] 4.1 逐项校验关联定义与真实外键关系一致性(详见 temp/docs/association_fk_consistency_report.md)。 -- [x] 4.2 统一 alias 命名与双向关联完整性。 -- [x] 4.3 清理重复或冲突关联。 -- [x] 4.4 形成 eager-loading 与 N+1 风险规约(详见 temp/docs/association_eager_loading_n_plus_one_guideline.md)。 -交付物: -- temp/docs/association_fix_plan.md -- temp/docs/association_validation_checklist.md -退出标准: -- 关联关系可预测、无冲突、与数据库关系一致。 - -[阶段 5: Model 内部能力清理] -- [x] 5.1 识别应迁移到 service 层的方法能力(见 temp/docs/model_cleanup_list.md 第一批清单)。 -- [x] 5.2 清理 model 内死代码与调试代码(已完成:P2 两批无调用静态方法清理 + P1 四组方法迁移并回收 model 同名方法)。 -- [x] 5.3 规范 hooks/scopes/virtual fields 的使用边界(盘点完成并已产出 temp/docs/model_boundary_rules.md)。 -- [x] 5.4 固化模型层边界规则(新增 script/model-boundary-check.cjs 并接入 npm run check:model-boundary)。 -交付物: -- temp/docs/model_cleanup_list.md -- temp/docs/model_boundary_rules.md -退出标准: -- 模型层聚焦于数据映射与轻量领域行为,职责边界清晰。 - -[阶段 6: 验证与交接] -- [ ] 6.1 在干净库上回放 migration 全流程。 -- [ ] 6.2 验证 model CRUD 与关联查询正确性。 -- [ ] 6.3 执行关键 API 冒烟回归(包含 method-output 基线/对比)。 -- [ ] 6.4 更新最终文档(README + methods + 内部交接文档)。 -交付物: -- verification_report.md -- handover_notes.md -退出标准: -- 无迁移漂移、无关联错配、无阻断回归问题。 - -[风险] -- 历史遗留表或隐式依赖未被识别。 -- 环境间数据漂移导致验证结果不一致。 -- 命名调整引发跨层调用副作用。 - -[依赖] -- 稳定可访问的数据库环境(盘点与验证)。 -- 统一确认的命名与关联规范。 -- 可执行的迁移窗口与回滚窗口。 - -[下一步] -- 阶段 4 的 4.1-4.4 已完成(含 receiving 第一批收敛与 N+1/eager-loading 规约落地)。 -- 高优先差异项推进: 已完成 store_warehouse/stock_warehouse 第二批收敛(stock_store include 语义约束补齐),并通过门禁。 -- 高优先差异项推进: 已完成 role / role_permission / permission 第三批收敛(启用状态过滤 + 去重),并通过门禁。 -- 已完成“DB 约束补齐”执行: `wms_role_permission.permission_id -> wms_permission.id` 外键已生效,SequelizeMeta 已登记 `20260323103000-align-role-permission-fk.js`。 -- 已完成数据清洗与备份: 4 条 permission 孤儿、3 条 role.store_id=0 哨兵数据均已处理(备份表见 `temp/docs/role_permission_fk_data_cleanup_plan.md`)。 -- 已完成 `wms_role.store_id` 外键策略落地:外键 `fk_wms_role_store` 已生效(ON DELETE SET NULL),SequelizeMeta 已登记 `20260323113000-add-role-store-fk.js`。 -- 已完成 store_warehouse / stock_warehouse 模型层复合键语义治理(统一 include 构造器 + constraints:false 显式化)。 -- 已完成阶段 4 收尾检查(第 1 项):全量 include alias 一致性扫描(service alias 与 model alias 差集=0)。 -- 已完成阶段 4 收尾检查(第 2 项):permission.parent_id 自关联约束策略已落地(root=NULL + FK)。 -- 已完成阶段 5.1:识别应迁移到 service 层的方法能力(第一批清单见 temp/docs/model_cleanup_list.md)。 -- 已完成阶段 5.2 第一批 P2 清理:ApiApp / InterfaceType / PrintItem,门禁通过。 -- 已完成阶段 5.2 第二批 P2 清理:I18nTranslation / StockStore,门禁通过。 -- 已完成阶段 5.2 P1 第一组:EntryOrder / EntryItems 8 个方法迁移到 service 并回收 model 同名方法。 -- 已完成阶段 5.2 P1 第二组:Storage 10 个方法迁移到 service 并回收 model 同名方法。 -- 已完成阶段 5.2 P1 第三组:Role / RolePermission 7 个方法迁移到 service 并回收 model 同名方法。 -- 已完成阶段 5.2 P1 第四组:Store 5 个方法迁移到 service 并回收 model 同名方法。 -- 已完成阶段 5.3:hooks/scopes/virtual fields 边界盘点与规则固化(见 temp/docs/model_boundary_rules.md)。 -- 已完成阶段 5.4:新增 model 边界检查脚本并接入 npm 命令与 CI(check:model-boundary)。 -- 已复跑阶段 5.4 门禁命令:`npm run check:model-boundary`,结果 PASS(files=45, hooks=2, scopeFiles=1, virtualLines=0)。 -- 过程门禁:compare mismatch=0;generated regression 与 smoke 持续通过;新增 model-boundary 检查门禁。 -- 下一步进入阶段 6.1:在干净库上回放 migration 全流程。 +[追溯方式] +- 需要查看过程细节时,优先使用 git 历史、`todo.txt` 总事务看板与 `versioning/` 本地版本记录。 diff --git a/script/model-boundary-check.cjs b/script/model-boundary-check.cjs index 98c72dd..98b2c1a 100644 --- a/script/model-boundary-check.cjs +++ b/script/model-boundary-check.cjs @@ -111,7 +111,7 @@ function scanFile(filePath) { relPath, line: i + 1, type: 'disallowed-hook', - message: '发现未登记的模型 hook,请先更新 temp/docs/model_boundary_rules.md 与 allowlist', + message: '发现未登记的模型 hook,请先更新模型边界规则与 allowlist', content: line.trim(), }); } @@ -124,7 +124,7 @@ function scanFile(filePath) { relPath, line: i + 1, type: 'disallowed-scopes', - message: '发现未登记的 scopes 定义,请先更新 temp/docs/model_boundary_rules.md 与 allowlist', + message: '发现未登记的 scopes 定义,请先更新模型边界规则与 allowlist', content: line.trim(), }); } @@ -137,7 +137,7 @@ function scanFile(filePath) { relPath, line: i + 1, type: 'disallowed-virtual-field', - message: '发现未登记的 virtual 字段定义,请先更新 temp/docs/model_boundary_rules.md 与 allowlist', + message: '发现未登记的 virtual 字段定义,请先更新模型边界规则与 allowlist', content: line.trim(), }); } diff --git a/temp/docs/METHOD_OUTPUT_REGRESSION_20260322.md b/temp/docs/METHOD_OUTPUT_REGRESSION_20260322.md deleted file mode 100644 index 19aaed7..0000000 --- a/temp/docs/METHOD_OUTPUT_REGRESSION_20260322.md +++ /dev/null @@ -1,94 +0,0 @@ -# Method 输出一致性回放说明 - -更新时间: 2026-03-22 - -## 1. 新交付条件 - -- 所有模型/关联相关改动,必须先执行 method 输出基线回放。 -- 改动完成后,必须对同一批 method 执行 compare 回放。 -- 交付标准: 修改前后 method 输出一致。 -- 允许屏蔽波动字段: token、timestamp、last_login_at、created_at、updated_at、iat、exp。 - -## 2. 测试账号 - -- username: liufumingren -- password: 111111 - -## 3. 方法使用来源 - -- method 定义来源: methods/system.json -- 回放脚本会从该配置中读取 method 分组、描述、参数定义,作为样本元数据。 - -## 4. 测试数据来源 - -- 主来源表: wms_system_log -- 参考日志表: - - wms_api_log - - wms_operation_log - - wms_account_login_log -- 样本选择原则: - - 优先同账号(liufumingren) - - 优先只读方法(get/list/query/detail/info/stats) - - 优先较新数据(按日志 id 倒序) - - 优先方法去重 - -## 5. 执行脚本 - -脚本文件: - -- script/method-output-regression.cjs - -命令: - -```powershell -# 修改前执行,生成基线 -node .\script\method-output-regression.cjs baseline 8 - -# 修改后执行,对比输出 -node .\script\method-output-regression.cjs compare -``` - -输出文件: - -- temp/method-output/method-output-baseline.json -- temp/method-output/method-output-baseline.md -- temp/method-output/method-output-compare.json - -## 6. 本次基线执行结果(修改前) - -执行时间: - -- baseline: 2026-03-22T13:56:52Z -- compare: 2026-03-22T13:56:57Z - -样本数: - -- 8 - -样本 method(来自 temp/method-output/method-output-baseline.md): - -- storage.receiving.getReceivingDetail (sourceId: 10790) -- order.getOrderModels (sourceId: 10783) -- print.getList (sourceId: 10611) -- print.getComputerPrinter (sourceId: 10579) -- print.getItem (sourceId: 10578) -- print.getComputer (sourceId: 10577) -- store.getStoreRoles (sourceId: 10553) -- index.getExpressList (sourceId: 9820) - -比对结果: - -- total: 8 -- mismatch: 0 -- pass: true - -说明: - -- 当前样本中既包含 200 成功响应,也包含 403 权限响应。 -- 403 响应同样纳入一致性校验范围(用于防止权限链路被意外改变)。 - -## 7. 后续执行要求 - -- 每次开始改动前,先运行 baseline 并保留输出文件。 -- 每次改动后,必须运行 compare。 -- 若 mismatch > 0,禁止进入交付,需先排查差异并补充说明。 diff --git a/temp/docs/SERVICE_API_CHANGE_AUDIT_20260322.md b/temp/docs/SERVICE_API_CHANGE_AUDIT_20260322.md deleted file mode 100644 index 8951049..0000000 --- a/temp/docs/SERVICE_API_CHANGE_AUDIT_20260322.md +++ /dev/null @@ -1,791 +0,0 @@ -# Service 使用与 API 文档联动审计 - -更新时间: 2026-03-22 -适用阶段: Model 重构阶段 4 及后续代码改造 -目的: 在修改 service 前,先确认真实使用链路;若 service 已被使用,则必须同步更新 service、对应 API 文档,并在本文件中记录变更,便于后续复盘。 - -## 1. 执行规则 - -- 任何计划修改的 service,必须先确认是否被 systemMethods、qimenMethods、controller 或其他 service 使用。 -- 只要存在真实调用链,就不能只改底层 service,必须一起评估上游入口与返回结构。 -- 对外暴露为 system/qimen method 的能力,必须同步更新 methods/system.json 或 methods/qimen.json。 -- 每次实际修改完成后,必须在本文件末尾追加一条变更记录。 - -## 2. 本轮已确认的高风险 service 使用链路 - -### 2.1 账号-仓库-角色关联链路 - -#### A. app/service/systems/store.js - -关键风险: - -- 直接使用不存在的 ctx.model.AccountStoreRole。 -- 影响门店申请审核、角色分配、角色列表查询。 - -已确认调用点: - -- app/service/systems/store.js:464 -- app/service/systems/store.js:679 -- app/service/systems/store.js:690 - -上游 system method: - -- app/service/systemMethods/store.js:35 -> store.getStoreRoles -- app/service/systemMethods/store.js:45 -> store.auditApply - -对应 API 文档: - -- methods/system.json:1976 -> store.getStoreRoles -- methods/system.json:1993 -> store.auditApply - -联动要求: - -- 若将 AccountStoreRole 收敛为 AccountStoreEmployee 或其他真实模型,必须同步更新: - - app/service/systems/store.js - - app/service/systemMethods/store.js - - methods/system.json 中 store.getStoreRoles / store.auditApply 的参数、返回结构描述 - -#### B. app/service/systems/auth/user.js - -关键风险: - -- 当前已部分切到 AccountStoreEmployee,但变量名和注释仍保留 accountStoreRole 旧语义。 -- 平台激活逻辑会联动 user.login、user.info、user.changeRole。 - -已确认调用点: - -- app/service/systems/auth/user.js:118 -> changeRole -- app/service/systems/auth/user.js:195 -> info -- app/service/systems/auth/user.js:328 -> findById -- app/service/systems/auth/user.js:877 -> ensurePlatformActiveRole - -上游 system method: - -- app/service/systemMethods/user.js:11 -> user.login -- app/service/systemMethods/user.js:24 -> user.info -- app/service/systemMethods/user.js:29 -> user.changeRole - -对应 API 文档: - -- methods/system.json:2016 附近 -> user.login -- methods/system.json:2051 附近 -> user.info -- methods/system.json:2067 附近 -> user.changeRole - -联动要求: - -- 若修改 activeEmployeeId、employee_id、role_id、roles 列表结构,必须同步更新: - - app/service/systems/auth/user.js - - app/service/systemMethods/user.js - - methods/system.json 中 user.login / user.info / user.changeRole 的返回字段说明 - -#### C. app/service/systems/account_platform.js - -关键风险: - -- 该 service 当前直接依赖 AccountStoreRole 幽灵 key。 -- 虽然尚未发现对外直接暴露的 system method,但它承载的平台激活角色语义与 auth.user 高度耦合。 - -已确认调用点: - -- app/service/systems/account_platform.js:13 -> switchActiveRole -- app/service/systems/account_platform.js:77 -> getActiveRoleByPlatform -- app/service/systems/account_platform.js:159 -> getMultiplePlatformActiveRoles -- app/service/systems/account_platform.js:219 -> getAllPlatformActives -- app/service/systems/account_platform.js:309 -> getAvailableRoles - -间接受影响入口: - -- app/service/systems/auth/user.js:58 -- app/service/systems/auth/user.js:304 -- app/service/systems/auth/user.js:877 - -文档联动策略: - -- 当前没有独立 method 文档入口。 -- 若修改本 service 的输入/输出语义,必须回写到 user.login / user.info / user.changeRole 的 API 文档,因为这些接口会消费平台激活角色结果。 - -### 2.2 动态分表工厂链路 - -#### A. app/service/systemMethods/order.js - -关键风险: - -- 依赖 OrderDeliveryFactory / OrderItemsFactory 获取动态模型。 -- 若工厂 key、返回模型或字段映射调整,会直接影响系统订单接口。 - -已确认调用点: - -- app/service/systemMethods/order.js:18 -> getOrderModels -- app/service/systemMethods/order.js:98 -> list -- 其他 order.* 方法共享同一组动态模型入口 - -对应 API 文档: - -- methods/system.json:422 -> order.getOrderModels -- methods/system.json:439 -> order.list -- methods/system.json:471 -> order.detail -- methods/system.json:503 -> order.listItems -- methods/system.json:535 -> order.stats -- methods/system.json:560 -> order.updateStatus -- methods/system.json:676 -> order.updateDeliveryTime - -联动要求: - -- 若修改动态模型获取方式、字段名或订单明细结构,必须同步更新上述 order.* 文档。 - -#### B. app/service/systems/delivery_order.js 与 app/service/qimenMethods/deliveryorder.js - -关键风险: - -- qimen 发货单接口直接依赖 OrderDeliveryFactory。 -- 若动态分表模型的 key 或查询字段变化,Qimen 接口会受影响。 - -已确认调用点: - -- app/service/systems/delivery_order.js:14 -- app/service/systems/delivery_order.js:311 -- app/service/qimenMethods/deliveryorder.js:7 -- app/service/qimenMethods/deliveryorder.js:8 - -对应 API 文档: - -- methods/qimen.json:14 -> deliveryorder.batchcreate -- methods/qimen.json:88 -> deliveryorder.create -- methods/qimen.json:162 -> deliveryorder.query - -联动要求: - -- 若修改 deliveryorder 查询、创建、历史表读取逻辑,必须同步更新 qimen deliveryorder.* 文档。 - -#### C. app/service/apiMethods/test.js - -关键风险: - -- 存在错误调用名 WmsOrderDeliveryFactory / WmsOrderItemsFactory。 -- 这是内部调试链路,不是正式 API 文档入口,但必须与正式工厂 key 保持一致。 - -已确认调用点: - -- app/service/apiMethods/test.js:50 -- app/service/apiMethods/test.js:51 - -联动要求: - -- 改动时同步修正为 OrderDeliveryFactory / OrderItemsFactory。 -- 无需更新 methods 文档,但必须在本文件记录修复事实。 - -## 3. 本轮结论 - -- 即将进入的关联治理不是纯 model 内部调整,至少会影响 store、user、account_platform、order、deliveryorder 这几条真实业务链路。 -- 因此后续任何代码改动都不能只改 model。 -- 必须按“model -> service -> systemMethods/qimenMethods -> methods 文档 -> 变更记录”的顺序联动处理。 - -## 4. 修改前检查清单 - -- 确认目标 service 是否被上游调用。 -- 确认上游调用属于 system 还是 qimen 入口。 -- 确认 methods/system.json 或 methods/qimen.json 是否存在对应 method。 -- 若返回结构变化,先记录旧字段,再补文档。 -- 修改完成后,在本文件追加一条变更记录。 - -## 5. 变更记录模板 - -### YYYY-MM-DD HH:mm - -- 修改范围: -- 涉及 service: -- 上游入口: -- 更新的 API 文档: -- 返回结构变化: -- 兼容处理: -- 验证方式: - -## 6. 当前记录 - -### 2026-03-22 关联治理准备 - -- 修改范围: 阶段 4 开始前的 service 使用与文档联动审计 -- 涉及 service: - - app/service/systems/store.js - - app/service/systems/auth/user.js - - app/service/systems/account_platform.js - - app/service/systemMethods/order.js - - app/service/systems/delivery_order.js - - app/service/qimenMethods/deliveryorder.js - - app/service/apiMethods/test.js -- 上游入口: - - system: store.getStoreRoles, store.auditApply, user.login, user.info, user.changeRole, order.* - - qimen: deliveryorder.batchcreate, deliveryorder.create, deliveryorder.query -- 更新的 API 文档: 尚未改动代码,本轮只完成审计与联动范围确认 -- 返回结构变化: 暂无 -- 兼容处理: 暂无 -- 验证方式: 通过 service 调用搜索、system/qimen method 搜索、methods 文档映射完成静态核对 - -### 2026-03-22 关联治理执行(第一批) - -- 修改范围: 修复 store 链路中 AccountStoreRole 幽灵模型引用 -- 涉及 service: - - app/service/systems/store.js -- 上游入口: - - system: store.getStoreRoles, store.auditApply -- 更新的 API 文档: - - methods/system.json - - store.getStoreRoles: 补充 code 参数定义 - - store.auditApply: 补充 audit_status/code/store_id/role_ids/reject_reason 参数定义 -- 返回结构变化: 无(维持原有 code/message/data 结构) -- 兼容处理: - - 将账号-门店关系绑定到 AccountStoreEmployee - - 将角色绑定落到 EmployeeRole(employee_id + role_id) - - 保持接口出参与状态码行为不变 -- 验证方式: - - 运行生成的改造前回归样例测试 - - 运行 method-output compare 对比报告 - -### 2026-03-22 关联治理执行(第二批) - -- 修改范围: 修复 account_platform 链路中 AccountStoreRole 幽灵模型引用 -- 涉及 service: - - app/service/systems/account_platform.js -- 上游入口: - - 间接影响 system: user.login, user.info, user.changeRole -- 更新的 API 文档: - - 无直接 method 文档变更(本批未新增/修改 system method 参数) -- 返回结构变化: 无(维持 role_id/role_name/role_code/store_id/store_name/store_code 字段) -- 兼容处理: - - switchActiveRole 保持历史参数名 accountStoreRoleId,内部按 employee_id 落库 - - include 链路由 AccountStoreRole 改为 AccountStoreEmployee + EmployeeRole + Role + Store - - getAvailableRoles 改为从 AccountStoreEmployee/EmployeeRole 聚合返回 -- 验证方式: - - npx egg-bin test test/app/controller/system.method-output.pre-refactor.generated.test.js - - node .\\script\\method-output-regression.cjs compare - - npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js - -### 2026-03-22 关联治理执行(第三批) - -- 修改范围: 清理 model 层残留命名污染(不改接口结构) -- 涉及 service/model: - - app/model/account.js - - app/model/role.js -- 上游入口: - - 间接影响 system 全链路(仅模型关联定义清理) -- 更新的 API 文档: - - 无(接口参数与返回结构未变化) -- 返回结构变化: 无 -- 兼容处理: - - 仅移除 AccountStoreRole 的遗留注释/无效解构,不调整现有 alias -- 验证方式: - - node .\\script\\method-output-regression.cjs compare - - npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js - - npx egg-bin test test/app/controller/system.method-output.batch3.generated.test.js - -### 2026-03-22 样例漂移策略更新 - -- 发现现象: - - 固定历史样例 `system.method-output.pre-refactor.generated.test.js` 因权限/业务数据变化出现与历史快照不一致。 -- 策略调整: - - 每批改造前重新冻结当批 baseline,并生成当批 Egg.js 样例测试。 - - 历史快照保留审计用途,不作为后续批次唯一门禁。 -- 当前批次快照: - - run/method-output-baseline-batch3-20260322_224649.json - - test/app/controller/system.method-output.batch3.generated.test.js - -### 2026-03-22 关联治理执行(第四批) - -- 修改范围: 统一 alias 命名并引入双轨兼容(复数标准名 + 历史别名保留) -- 涉及 service/model: - - app/model/account.js - - app/model/account_store_employee.js - - app/model/role.js - - app/model/store.js - - app/service/systems/account_platform.js - - app/service/systems/auth/user.js -- 上游入口: - - 间接影响 system: user.login, user.info, user.changeRole, store.getStoreRoles -- 更新的 API 文档: - - 无(接口参数与返回结构未变化) -- 返回结构变化: 无 -- 兼容处理: - - 新增标准 alias:accountStoreEmployees / employeeRoles - - 保留历史 alias:accountStoreRoles / accountStoreEmployee / employeeRole - - service 查询切换到新 alias,并在读取层面对旧 alias 做回退兼容 -- 验证方式: - - node .\\script\\method-output-regression.cjs compare - - node .\\script\\tmp-generate-method-regression-test.cjs - - npx egg-bin test temp/generated-tests/system.method-output.generated.test.js - - npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js - -### 2026-03-23 关联治理执行(第四批补充收敛) - -- 修改范围: service 层去除旧 alias 回退依赖,统一使用新 alias(保留 model 兼容别名) -- 涉及 service: - - app/service/systems/account_platform.js - - app/service/systems/auth/user.js -- 上游入口: - - 间接影响 system: user.login, user.info, user.changeRole, store.getStoreRoles -- 更新的 API 文档: - - 无(接口参数与返回结构未变化) -- 返回结构变化: 无 -- 兼容处理: - - account_platform 内部读取改为 employeeRoles 单轨 - - model 层兼容 alias 继续保留,避免外部未迁移调用中断 - - auth/user 中 accountStoreRole 变量语义更新为 accountStoreEmployee -- 验证方式: - - node .\\script\\method-output-regression.cjs baseline 8 - - node .\\script\\method-output-regression.cjs compare - - node .\\script\\tmp-generate-method-regression-test.cjs - - npx egg-bin test temp/generated-tests/system.method-output.generated.test.js - - npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js - -### 2026-03-23 关联治理执行(第五批) - -- 修改范围: 移除 model 层重复兼容 alias,完成重复关联清理 -- 涉及 model: - - app/model/account.js - - app/model/account_store_employee.js - - app/model/role.js - - app/model/store.js -- 上游入口: - - 间接影响 system: user.login, user.info, user.changeRole, store.getStoreRoles -- 更新的 API 文档: - - 无(接口参数与返回结构未变化) -- 返回结构变化: 无 -- 兼容处理: - - 删除旧 alias:accountStoreRoles / employeeRole / accountStoreEmployee(Store.hasMany 语义) - - 保留必要单数 alias:AccountPlatformActive.belongsTo(AccountStoreEmployee).as = accountStoreEmployee -- 验证方式: - - node .\\script\\method-output-regression.cjs baseline 8 - - node .\\script\\method-output-regression.cjs compare - - node .\\script\\tmp-generate-method-regression-test.cjs - - npx egg-bin test temp/generated-tests/system.method-output.generated.test.js - - npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js - -### 2026-03-23 关联治理执行(4.1 全量一致性校验) - -- 修改范围: 对 app/model 全量关联定义与数据库真实外键进行一致性审计(无业务代码改动) -- 审计产物: - - association_fk_consistency_report.md - - temp/association-fk-audit.json -- 审计结论: - - DB 外键 51 条,模型关联 89 条,可直接匹配 53 条 - - 模型定义但 DB 无外键约束 28 条 - - DB 有外键但模型未声明 13 条 - - 动态模型/示例占位无法静态解析 5 条 -- 影响判断: - - 当前 system 输出门禁未受影响,但存在“模型语义与 DB 约束不完全对齐”的技术债 - - 已将高优先级差异并入后续 4.4 规约与治理清单 - -### 2026-03-23 关联治理执行(第六批:receiving 高优先差异第一批) - -- 修改范围: 处理 receiving 链路高优先差异,移除无效模型关联并收敛仓库维度查询条件 -- 涉及 service/model: - - app/model/receiving.js - - app/model/receiving_detail.js - - app/service/systems/storage/receiving.js -- 上游入口: - - 间接影响 system: storage.receiving.getReceivingDetail 及 receiving 相关查询/更新链路 -- 更新的 API 文档: - - 无(接口参数与返回结构未变化) -- 返回结构变化: 无 -- 兼容处理: - - 删除无效关联: `Receiving.hasMany(Storage, foreignKey: 'receiving_id')` - - 删除无效关联: `ReceivingDetail.hasMany(Storage, foreignKey: 'receiving_detail_id')` - - `StoreWarehouse` include/query 统一增加 `warehouse_id + use_status` 过滤,避免跨仓库错关联 - - `create` 流程 `store_name` 统一使用 `store_remask` -- 验证方式: - - node .\\script\\method-output-regression.cjs compare - - node .\\script\\tmp-generate-method-regression-test.cjs - - npx egg-bin test temp/generated-tests/system.method-output.generated.test.js test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js -- 验证结果: - - compare: total=8, mismatch=0 - - tests: 14 passing - -### 2026-03-23 关联治理执行(第七批:4.4 规约文档落地) - -- 修改范围: 形成并落地 eager-loading 与 N+1 风险规约(文档治理,无业务代码改动) -- 涉及文档: - - association_eager_loading_n_plus_one_guideline.md - - association_validation_checklist.md - - model_todo.txt -- 上游入口: - - 无直接 system/qimen 行为变更 -- 更新的 API 文档: - - 无 -- 返回结构变化: 无 -- 兼容处理: - - 将关联查询的最小约束(include attributes、上下文 where、门禁流程)固化为统一规约 -- 验证方式: - - 以第六批回归结果作为当前代码基线(compare mismatch=0,tests 14 passing) - -### 2026-03-23 关联治理执行(第八批:store_warehouse/stock_warehouse 语义收敛) - -- 修改范围: 修复 stock_store 链路中 `StoreWarehouse` 仅按 `store_id` 关联导致的跨仓误匹配风险 -- 涉及 service/model: - - app/service/systems/stock_store.js -- 上游入口: - - 间接影响 system: stock.* 查询链路(库存列表/搜索) -- 更新的 API 文档: - - 无(接口参数与返回结构未变化) -- 返回结构变化: 无 -- 兼容处理: - - `store_stock` include 在 count/findAll/search 三处统一增加 `warehouse_id + use_status` 过滤 - - 保持 `required` 策略不变(列表仍 required=true,搜索路径 required=false) -- 验证方式: - - node .\\script\\method-output-regression.cjs compare - - node .\\script\\tmp-generate-method-regression-test.cjs - - npx egg-bin test temp/generated-tests/system.method-output.generated.test.js test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js -- 验证结果: - - compare: total=8, mismatch=0 - - tests: 14 passing - -### 2026-03-23 关联治理执行(第九批:role/permission 语义收敛) - -- 修改范围: 修复 auth/user 权限链路对禁用角色/权限的过滤缺失问题 -- 涉及 service/model: - - app/service/systems/auth/user.js -- 上游入口: - - 间接影响 system: user.info(权限与菜单加载链路) -- 更新的 API 文档: - - 无(接口参数与返回结构未变化) -- 返回结构变化: 无(仅收敛为“启用角色/启用权限可见”) -- 兼容处理: - - `getPermissions/getMenus` 在 EmployeeRole 查询中增加 Role.status=1 过滤 - - Permission 查询增加 status=1 过滤 - - role_id 与 permission_id 查询集合去重 -- 验证方式: - - node .\\script\\method-output-regression.cjs compare - - node .\\script\\tmp-generate-method-regression-test.cjs - - npx egg-bin test temp/generated-tests/system.method-output.generated.test.js test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js -- 验证结果: - - compare: total=8, mismatch=0 - - tests: 14 passing - -### 2026-03-23 关联治理执行(第十批:role_permission 外键迁移落地) - -- 修改范围: 落地 `role_permission.permission_id -> permission.id` 的可执行迁移脚本与模型类型对齐 -- 涉及 service/model/migration: - - database/migrations/20260323103000-align-role-permission-fk.js - - app/model/role_permission.js -- 上游入口: - - 无直接 system/qimen 返回结构变化 -- 更新的 API 文档: - - 无 -- 返回结构变化: 无 -- 兼容处理: - - 迁移脚本包含保护性校验:存在孤儿数据时直接失败,避免静默脏写 - - down 提供外键回滚与字段类型回退 -- 审计发现: - - `wms_role_permission.permission_id` 存在 4 条孤儿记录(id: 2, 3, 6, 10) - - `wms_role.store_id` 存在 3 条 `0` 哨兵值(当前不满足直接加 FK 条件) -- 验证方式: - - node .\\script\\method-output-regression.cjs compare - - node .\\script\\tmp-generate-method-regression-test.cjs - - npx egg-bin test temp/generated-tests/system.method-output.generated.test.js test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js -- 实际执行结果: - - 已创建备份表并落库: - - `wms_role_permission_orphan_backup_20260323`(4 条) - - `wms_role_store_zero_backup_20260323`(3 条) - - 已清洗数据: - - 删除 `wms_role_permission.permission_id` 孤儿 4 条 - - 将 `wms_role.store_id=0` 修正为 `NULL` 共 3 条 - - 已执行 DDL: - - `wms_role_permission.permission_id` -> `int(11)` - - 新增外键 `fk_wms_role_permission_permission`(ON UPDATE RESTRICT, ON DELETE CASCADE) - - SequelizeMeta 已登记 `20260323103000-align-role-permission-fk.js` - - 迁移后复核: 孤儿计数=0,role_store_zero=0 - - 回归结果: - - compare: total=8, mismatch=0 - - tests: 14 passing - -### 2026-03-23 关联治理执行(第十一批:role.store_id 外键策略落地) - -- 修改范围: 落地 `wms_role.store_id -> wms_store.id` 外键策略(NULL 语义) -- 涉及 migration: - - database/migrations/20260323113000-add-role-store-fk.js -- 上游入口: - - 无直接 system/qimen 返回结构变化 -- 更新的 API 文档: - - 无 -- 返回结构变化: 无 -- 兼容处理: - - `store_id` 字段类型对齐为 `bigint(20) unsigned NULL` - - 新增索引 `idx_store_id` - - 外键策略采用 `ON DELETE SET NULL`,保留历史角色记录的 NULL 语义 -- 实际执行结果: - - 外键 `fk_wms_role_store` 已生效(ON UPDATE RESTRICT, ON DELETE SET NULL) - - `wms_role` 孤儿数据复核: 0 - - SequelizeMeta 已登记 `20260323113000-add-role-store-fk.js` -- 验证方式: - - node .\\script\\method-output-regression.cjs compare - - node .\\script\\tmp-generate-method-regression-test.cjs - - npx egg-bin test temp/generated-tests/system.method-output.generated.test.js test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js -- 回归结果: - - compare: total=8, mismatch=0 - - tests: 14 passing - -### 2026-03-23 关联治理执行(第十二批:store_warehouse/stock_warehouse 模型层语义治理) - -- 修改范围: 收敛 `store_stock` 关联的模型层复合键表达,统一 include 构造入口 -- 涉及 service/model: - - app/model/store_warehouse.js - - app/model/stock_warehouse.js - - app/model/receiving.js - - app/service/systems/stock_store.js - - app/service/systems/storage/receiving.js -- 上游入口: - - 间接影响 system: stock.* / storage.receiving.* 查询链路 -- 更新的 API 文档: - - 无(接口参数与返回结构未变化) -- 返回结构变化: 无 -- 兼容处理: - - StoreWarehouse 新增 `buildScopedWhere` 与 `buildStoreStockInclude`,统一生成 `warehouse_id + use_status` 约束 - - 复合键语义关联统一显式 `constraints:false`,避免单列外键误解 - - service 查询改为复用模型构造器,保持原有 `required` 语义不变 -- 验证方式: - - node .\\script\\method-output-regression.cjs compare - - node .\\script\\tmp-generate-method-regression-test.cjs - - npx egg-bin test temp/generated-tests/system.method-output.generated.test.js test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js -- 回归结果: - - compare: total=8, mismatch=0 - - tests: 14 passing - -### 2026-03-23 关联治理执行(第十三批:include alias 一致性收尾扫描) - -- 修改范围: 阶段 4 收尾检查(全量 include alias 一致性扫描,无业务代码改动) -- 涉及范围: - - app/model/**/*.js(association `as` 定义) - - app/service/**/*.js(include `as` 使用) -- 上游入口: - - 无直接 system/qimen 行为变更 -- 更新的 API 文档: - - 无 -- 返回结构变化: 无 -- 扫描方法: - - 全量检索 model association 与 service include 的 alias 使用 - - 执行自动差集比对(service alias - model alias) -- 扫描结果: - - model alias 总数: 48 - - 差集可疑项: 0 - - 结论: 未发现 include alias 不一致问题 -- 验证方式: - - 通过一次性 Node 差集脚本执行 `service alias - model alias` 自动比对(临时脚本未入库) - -### 2026-03-23 关联治理执行(第十四批:permission.parent_id 自关联约束落地) - -- 修改范围: 落地 `wms_permission.parent_id -> wms_permission.id` 自关联外键,并统一根节点语义 -- 涉及 service/model/migration: - - database/migrations/20260323123000-add-permission-parent-fk.js - - app/model/permission.js - - app/service/systems/auth/user.js -- 上游入口: - - 间接影响 system: user.info(菜单树构建) -- 更新的 API 文档: - - 无(接口参数与返回结构未变化) -- 返回结构变化: 无 -- 兼容处理: - - 根节点语义由 `parent_id=0` 规范为 `parent_id IS NULL` - - 模型 setter 兼容历史输入:`0 -> NULL` - - 菜单树构建逻辑根判断由 `parent_id===0` 收敛为 `!parent_id` -- 实际执行结果: - - 落库复核:`root_zero_after=0`、`root_null_after=42`、`orphan_after=0` - - 外键 `fk_wms_permission_parent` 已生效(ON UPDATE RESTRICT, ON DELETE SET NULL) - - SequelizeMeta 已登记 `20260323123000-add-permission-parent-fk.js` - - 触发器状态:目标库因权限限制(binlog + SUPER)未创建触发器,采用应用层归一化方案替代 -- 验证方式: - - node .\script\method-output-regression.cjs compare - - node .\script\tmp-generate-method-regression-test.cjs - - npx egg-bin test temp/generated-tests/system.method-output.generated.test.js test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js -- 回归结果: - - compare: total=8, mismatch=0 - - tests: 14 passing - -### 2026-03-23 模型能力治理执行(第十五批:阶段 5.1 清理清单盘点) - -- 修改范围: 阶段 5.1(识别应迁移到 service 层的方法能力,文档治理) -- 涉及文档: - - model_cleanup_list.md - - model_todo.txt -- 上游入口: - - 无直接 system/qimen 行为变更 -- 更新的 API 文档: - - 无 -- 返回结构变化: 无 -- 盘点结论: - - 模型方法总数: 102 - - 第一批应迁移(P1)聚焦: EntryOrder / EntryItems / Storage / RolePermission / Store - - 第一批无调用可清理(P2)已形成清单,待阶段 5.2 执行删除前复核 -- 验证方式: - - 静态扫描 model 方法清单与引用关系(仅文档盘点,无业务代码改动) - -### 2026-03-23 模型能力治理执行(第十六批:阶段 5.2 第一批无调用方法清理) - -- 修改范围: 清理 model 层第一批无调用静态方法(低风险) -- 涉及 model: - - app/model/api_app.js - - app/model/interface_type.js - - app/model/print_item.js -- 上游入口: - - 无直接 system/qimen 行为变更 -- 更新的 API 文档: - - 无 -- 返回结构变化: 无 -- 兼容处理: - - 清理前执行全局引用复核,确认仅在定义处出现 - - 仅删除静态 helper,不触碰关联定义与实例方法 -- 删除项: - - ApiApp.findByAppKey / ApiApp.findByQimenConfig - - InterfaceType.findByCode / InterfaceType.findEnabled - - PrintItem.getGroupFields / PrintItem.getTableConfigs -- 验证方式: - - node .\script\method-output-regression.cjs compare - - node .\script\tmp-generate-method-regression-test.cjs - - npx egg-bin test temp/generated-tests/system.method-output.generated.test.js test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js -- 回归结果: - - compare: total=8, mismatch=0 - - tests: 14 passing - -### 2026-03-23 模型能力治理执行(第十七批:阶段 5.2 第二批无调用方法清理) - -- 修改范围: 清理 model 层第二批无调用静态方法(低风险) -- 涉及 model: - - app/model/i18n_translation.js - - app/model/stock_store.js -- 上游入口: - - 无直接 system/qimen 行为变更 -- 更新的 API 文档: - - 无 -- 返回结构变化: 无 -- 兼容处理: - - 清理前完成删除前引用复核(service/controller/test/script 全仓扫描) - - 仅删除静态 helper,不触碰关联定义、字段定义与实例方法 -- 删除项: - - I18nTranslation.getTranslation / I18nTranslation.batchGetTranslations / I18nTranslation.getProjectTranslations / I18nTranslation.upsertTranslation / I18nTranslation.getUntranslated - - StockStore.findByItemCode / StockStore.findByStore -- 验证方式: - - node .\script\method-output-regression.cjs compare - - node .\script\tmp-generate-method-regression-test.cjs - - npx egg-bin test temp/generated-tests/system.method-output.generated.test.js - - npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js -- 回归结果: - - compare: total=8, mismatch=0 - - generated regression: 8 passing - - smoke: 6 passing - - tests: 14 passing - -### 2026-03-23 模型能力治理执行(第十八批:阶段 5.2 P1 第一组迁移) - -- 修改范围: 将 EntryOrder / EntryItems 的内部静态方法迁移到 service,收敛 model 职责 -- 涉及 service/model: - - app/service/systems/entry_order.js - - app/model/entry_order.js - - app/model/entry_items.js -- 上游入口: - - 无直接新增 system/qimen method;属于内部服务能力收敛 -- 更新的 API 文档: - - 无(对外接口参数与返回结构未变化) -- 返回结构变化: 无 -- 兼容处理: - - 迁移 EntryOrder.findByOrderCode/findByStatus/getStatsByWarehouse/updateSyncStatus/updateOrderStatus/calculateReceivedQuantities - - 迁移 EntryItems.batchUpdateReceived/getOrderProgress -- 验证方式: - - node .\script\method-output-regression.cjs compare - - node .\script\tmp-generate-method-regression-test.cjs - - npx egg-bin test temp/generated-tests/system.method-output.generated.test.js - - npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js -- 回归结果: - - compare: total=8, mismatch=0 - - generated regression: 8 passing - - smoke: 6 passing - - tests: 14 passing - -### 2026-03-23 模型能力治理执行(第十九批:阶段 5.2 P1 第二组迁移) - -- 修改范围: 将 Storage 的内部静态方法迁移到 service,收敛 model 职责 -- 涉及 service/model: - - app/service/systems/storage/index.js - - app/model/storage.js -- 上游入口: - - 无直接新增 system/qimen method;属于内部服务能力收敛 -- 更新的 API 文档: - - 无(对外接口参数与返回结构未变化) -- 返回结构变化: 无 -- 兼容处理: - - 迁移 Storage.findByStockAndBatch/findBySpace/findAvailableByWarehouse/findExpiringSoon/updateQuantity/lockQuantity/unlockQuantity/allocateQuantity/getStockSummary/getSpaceUsage -- 验证方式: - - node .\script\method-output-regression.cjs compare - - node .\script\tmp-generate-method-regression-test.cjs - - npx egg-bin test temp/generated-tests/system.method-output.generated.test.js - - npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js -- 回归结果: - - compare: total=8, mismatch=0 - - generated regression: 8 passing - - smoke: 7 passing - - tests: 15 passing - -### 2026-03-23 模型能力治理执行(第二十批:阶段 5.2 P1 第三组迁移) - -- 修改范围: 将 Role / RolePermission 的权限编排方法迁移到 service,收敛 model 职责 -- 涉及 service/model: - - app/service/systems/auth/role_permission.js - - app/model/role.js - - app/model/role_permission.js -- 上游入口: - - 无直接新增 system/qimen method;属于内部服务能力收敛 -- 更新的 API 文档: - - 无(对外接口参数与返回结构未变化) -- 返回结构变化: 无 -- 兼容处理: - - 迁移 Role.assignPermissions/getPermissionTree/getPermissionIds - - 迁移 RolePermission.bulkAssign/clearRolePermissions/getRolePermissions/hasPermission -- 验证方式: - - node .\script\method-output-regression.cjs compare - - node .\script\tmp-generate-method-regression-test.cjs - - npx egg-bin test temp/generated-tests/system.method-output.generated.test.js - - npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js -- 回归结果: - - compare: total=8, mismatch=0 - - generated regression: 8 passing - - smoke: 7 passing - - tests: 15 passing - -### 2026-03-23 模型能力治理执行(第二十一批:阶段 5.2 P1 第四组迁移) - -- 修改范围: 将 Store 的校验与查询助手方法迁移到 service,收敛 model 职责 -- 涉及 service/model: - - app/service/systems/store.js - - app/model/store.js -- 上游入口: - - 无直接新增 system/qimen method;属于内部服务能力收敛 -- 更新的 API 文档: - - 无(对外接口参数与返回结构未变化) -- 返回结构变化: 无 -- 兼容处理: - - 迁移 Store.validateStoreData/checkCompanyNameExists/findByAccountId/findAllEnabled/findAllWarehouses -- 验证方式: - - node .\script\method-output-regression.cjs compare - - node .\script\tmp-generate-method-regression-test.cjs - - npx egg-bin test temp/generated-tests/system.method-output.generated.test.js - - npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js -- 回归结果: - - compare: total=8, mismatch=0 - - generated regression: 8 passing - - smoke: 7 passing - - tests: 15 passing - -### 2026-03-23 系统接口兼容修复(第二十二批:project 请求头校验) - -- 修改范围: 修复 system 请求上下文校验对历史 project=wms 请求头的误拒绝 -- 涉及 service: - - app/service/system.js -- 变更内容: - - `ALLOWED_PROJECTS` 增加 `wms/scm/other`,保持与历史调用兼容 -- 触发原因: - - generated regression 与 smoke 在无业务代码变更时统一出现 400(`project 不支持: wms`) -- 验证方式: - - 直接调用 `user.login`(platform=web, project=wms)回归 - - compare + generated regression + smoke 全量重跑 -- 回归结果: - - login: HTTP 200 - - compare: total=8, mismatch=0 - - generated regression: 8 passing - - smoke: 7 passing - - tests: 15 passing \ No newline at end of file diff --git a/temp/docs/association_eager_loading_n_plus_one_guideline.md b/temp/docs/association_eager_loading_n_plus_one_guideline.md deleted file mode 100644 index 133d9f5..0000000 --- a/temp/docs/association_eager_loading_n_plus_one_guideline.md +++ /dev/null @@ -1,102 +0,0 @@ -# Association Eager-Loading 与 N+1 规约 - -更新时间: 2026-03-23 -适用阶段: Model 重构阶段 4.4 -范围: app/service/**/*.js 中涉及 Sequelize 关联查询的代码 - -## 1. 目标 - -- 降低关联查询的 SQL 次数与响应时间抖动。 -- 统一 eager-loading 写法,避免 include 漂移导致错关联。 -- 在不改变外部接口返回结构的前提下收敛查询成本。 - -## 2. 术语 - -- eager-loading: 通过 include 一次性加载关联数据。 -- N+1: 先查 1 次主数据,再按每条主数据各查 1 次关联,导致总查询次数随 N 线性增长。 -- 关联上下文约束: 在 include.where 中补齐业务维度(如 warehouse_id、use_status),避免跨上下文错关联。 - -## 3. 强制规则 - -1. 列表查询禁止在循环内按行查询关联表。 -2. 只要关联数据是展示必需字段,优先使用 include 一次加载。 -3. include 必须显式声明 attributes,禁止默认全字段拉取。 -4. include 需要业务上下文约束时,必须补齐 where 条件(典型: warehouse_id + use_status)。 -5. hasMany/hasOne/belongsTo 的 as 必须与 model 定义一致,禁止临时字符串别名。 -6. 分页列表若包含 hasMany,优先控制返回列并评估 distinct/subQuery,防止计数与分页漂移。 -7. count 与 findAll 不一致时,必须拆分并保持 where/include 语义一致。 - -## 4. 推荐写法 - -### 4.1 反模式(N+1) - -```js -const list = await Model.findAll({ where }); -for (const row of list) { - row.child = await Child.findOne({ where: { id: row.child_id } }); -} -``` - -### 4.2 规约写法(eager-loading) - -```js -const list = await Model.findAll({ - where, - attributes: [ 'id', 'name', 'child_id' ], - include: [ - { - model: Child, - as: 'child', - attributes: [ 'id', 'name' ], - required: false, - }, - ], -}); -``` - -### 4.3 仓库维度约束(本仓库高频场景) - -```js -include: [ - { - model: ctx.model.StoreWarehouse, - as: 'store_stock', - attributes: [ 'store_id', 'store_remask' ], - where: { - warehouse_id: warehouseId, - use_status: 1, - }, - required: false, - }, -] -``` - -## 5. 当前代码落地点 - -- receiving 链路已按规约补齐仓库维度过滤,避免 StoreWarehouse 跨仓匹配。 -- receiving 与 receiving_detail 已移除无效 Storage hasMany 关联,避免误导 include 设计。 -- 后续优先治理: - - store_warehouse 与 stock_warehouse 的 store_id 语义对齐 - - role / role_permission / permission 的关联约束与 include 一致性 - -## 6. 变更门禁 - -每批涉及关联查询的改动,至少执行以下门禁: - -1. node .\\script\\method-output-regression.cjs compare -2. node .\\script\\tmp-generate-method-regression-test.cjs -3. npx egg-bin test temp/generated-tests/system.method-output.generated.test.js -4. npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js - -交付标准: - -- compare 结果 mismatch=0 -- 生成回归与关键冒烟测试全部通过 - -## 7. PR 自检清单 - -- [ ] 是否存在循环内数据库查询。 -- [ ] include 是否补齐 attributes。 -- [ ] include.where 是否补齐业务上下文约束。 -- [ ] as 是否与 model 关联定义一致。 -- [ ] 是否完成 method-output compare 与回归测试。 diff --git a/temp/docs/association_fix_plan.md b/temp/docs/association_fix_plan.md deleted file mode 100644 index 48de8bc..0000000 --- a/temp/docs/association_fix_plan.md +++ /dev/null @@ -1,61 +0,0 @@ -# Association Fix Plan - -更新时间: 2026-03-23 -适用阶段: Model 重构阶段 4(关联关系规范化) - -## 1. 目标 - -- 统一 alias 命名规则(belongsTo/hasOne 用单数,hasMany/belongsToMany 用复数)。 -- 清理重复或冲突关联定义,避免 include 歧义。 -- 保持 system/qimen 输出结构不变,通过 baseline/compare 门禁验证。 - -## 2. 已完成修复 - -### 2.1 幽灵模型收敛(已完成) - -- 将 AccountStoreRole 相关调用链迁移到 AccountStoreEmployee + EmployeeRole + Role + Store。 -- 覆盖主链路: - - app/service/systems/store.js - - app/service/systems/account_platform.js - - app/service/systems/auth/user.js - -### 2.2 alias 标准化(已完成) - -- 新标准 alias: - - accountStoreEmployees - - employeeRoles -- 已完成调用迁移: - - account_platform 服务 include 与读取逻辑统一为 employeeRoles - - auth/user 服务 include 统一为 employeeRoles - -### 2.3 重复关联清理(已完成) - -- 已移除以下重复兼容 alias 定义: - - Account.accountStoreRoles - - AccountStoreEmployee.employeeRole - - Role.employeeRole - - Store.accountStoreEmployee -- 保留必要单数 alias(belongsTo 语义): - - AccountPlatformActive.accountStoreEmployee - -## 3. 验证策略 - -每批改动执行以下门禁: - -1. node .\\script\\method-output-regression.cjs baseline 8 -2. node .\\script\\method-output-regression.cjs compare -3. node .\\script\\tmp-generate-method-regression-test.cjs -4. npx egg-bin test temp/generated-tests/system.method-output.generated.test.js -5. npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js - -## 4. 当前状态 - -- 输出一致性门禁:通过(mismatch=0)。 -- 关键冒烟测试:通过。 -- 对外 API 参数/返回:无结构变更。 - -## 5. 剩余工作 - -- 全量扫描其余模型类方法中的 include alias 一致性(已完成,差集扫描异常项 0 个)。 -- 评估并落地 permission.parent_id 自关联约束策略(已完成:root 语义归一为 NULL + 自关联 FK)。 -- 进入阶段 5:Model 内部能力清理与边界固化。 \ No newline at end of file diff --git a/temp/docs/association_fk_consistency_report.md b/temp/docs/association_fk_consistency_report.md deleted file mode 100644 index c7a9b61..0000000 --- a/temp/docs/association_fk_consistency_report.md +++ /dev/null @@ -1,65 +0,0 @@ -# Association FK Consistency Report - -更新时间: 2026-03-23T03:08:35.772Z -数据库: wms - -## Summary - -- DB 外键数: 51 -- 模型关联数: 89 -- 可直接匹配外键: 53 -- 模型定义但 DB 无外键约束: 28 -- 无法解析到模型表映射: 5 -- DB 存在但模型未声明的外键: 13 - -## Missing Constraints (Top 20) - -- wms_receiving.creator_id->wms_account_store_employee.id (app/model/account_store_employee.js, hasMany, as=Receiving) -- wms_api_app.warehouse_id->wms_store.id (app/model/api_app.js, belongsTo, as=warehouse) -- wms_fast_where.pid->wms_fast_where.id (app/model/fast_where.js, belongsTo, as=parent) -- wms_fast_where.pid->wms_fast_where.id (app/model/fast_where.js, hasMany, as=children) -- wms_location_space.zone_id->wms_location_zone.id (app/model/location_space.js, belongsTo, as=zone) -- wms_receiving_detail.space_id->wms_location_space.id (app/model/location_space.js, hasMany, as=receiving) -- wms_location_space.zone_id->wms_location_zone.id (app/model/location_zone.js, hasMany, as=spaces) -- wms_location_zone.warehouse_id->wms_location_zone.warehouse_id (app/model/location_zone.js, belongsTo, as=pickStartPoint) -- wms_permission.parent_id->wms_permission.id (app/model/permission.js, hasMany, as=children) -- wms_permission.parent_id->wms_permission.id (app/model/permission.js, belongsTo, as=parent) -- wms_receiving.warehouse_id->wms_store.id (app/model/receiving.js, belongsTo, as=warehouse) -- wms_receiving.creator_id->wms_account_store_employee.id (app/model/receiving.js, belongsTo, as=creator) -- wms_storage.receiving_id->wms_receiving.id (app/model/receiving.js, hasMany, as=storage_records) -- wms_receiving.store_id->wms_store_warehouse.store_id (app/model/receiving.js, belongsTo, as=store) -- wms_receiving_detail.system_product_id->wms_stock_warehouse.id (app/model/receiving_detail.js, belongsTo, as=system_product) -- wms_storage.receiving_detail_id->wms_receiving_detail.id (app/model/receiving_detail.js, hasMany, as=storage_details) -- wms_receiving_detail.space_id->wms_location_space.id (app/model/receiving_detail.js, belongsTo, as=receiving_space) -- wms_role.store_id->wms_store.id (app/model/role.js, belongsTo, as=store) -- wms_role_permission.permission_id->wms_permission.id (app/model/role_permission.js, belongsTo, as=permission) -- wms_stock_warehouse.store_id->wms_store_warehouse.store_id (app/model/stock_warehouse.js, belongsTo, as=store_stock) - -## Unresolved Associations (Top 20) - -- app/model/order_delivery_factory.js: DynamicModel -> ItemsModel (type=hasMany, fk=order_id) -- app/model/order_delivery_factory.js: ItemsModel -> DynamicModel (type=belongsTo, fk=order_id) -- app/model/order_delivery_factory.js: DynamicModel -> this.app.model.Store (type=belongsTo, fk=store_id) -- app/model/order_delivery_factory.js: DynamicModel -> this.app.model.Store (type=belongsTo, fk=warehouse_id) -- app/model/print_item.js: PrintItem -> app.model.OtherModel (type=belongsTo, fk=xxx) - -## DB-only Foreign Keys (Top 20) - -- wms_account_login_log.user_id->wms_account.id -- wms_embargo_policies.warehouse_id->wms_store.id -- wms_express_setting.express_code->wms_express.code -- wms_express_setting.warehouse_id->wms_store.id -- wms_order_delivery.store_id->wms_store.id -- wms_order_delivery.warehouse_id->wms_store.id -- wms_order_express.order_id->wms_order_delivery.id -- wms_order_express_print_data.express_id->wms_order_express.id -- wms_order_items.order_id->wms_order_delivery.id -- wms_stock_warehouse.warehouse_id->wms_store.id -- wms_store_join.account_id->wms_account.id -- wms_store_join.store_id->wms_store.id -- wms_system_log.store_id->wms_store.id - -## Notes - -- belongsToMany 通过中间表映射,未纳入本次“直接外键”匹配。 -- 动态分表工厂中的关联(order_delivery_factory/order_items_factory)不做静态表级强校验。 diff --git a/temp/docs/association_validation_checklist.md b/temp/docs/association_validation_checklist.md deleted file mode 100644 index 729963f..0000000 --- a/temp/docs/association_validation_checklist.md +++ /dev/null @@ -1,165 +0,0 @@ -# Association Validation Checklist - -更新时间: 2026-03-23 -范围: app/model/*.js + 核心系统 service 调用链 - -## 1. 核心检查项 - -- [x] AccountStoreRole 幽灵引用已移除(服务主链路)。 -- [x] AccountStoreEmployee <-> EmployeeRole <-> Role 关系可用。 -- [x] hasMany alias 复数化(employeeRoles/accountStoreEmployees)。 -- [x] 重复兼容 alias 已清理(主链路)。 -- [x] 对外接口输出一致(baseline/compare mismatch=0)。 -- [x] 关键登录与用户信息链路测试通过。 - -## 2. 关键模型校验结果 - -| 模型 | 关键关联 | 结果 | 备注 | -| --- | --- | --- | --- | -| Account | hasMany AccountStoreEmployee as accountStoreEmployees | PASS | 已移除 accountStoreRoles | -| AccountStoreEmployee | hasMany EmployeeRole as employeeRoles | PASS | 已移除 employeeRole | -| Role | hasMany EmployeeRole as employeeRoles | PASS | 已移除 employeeRole | -| Store | hasMany AccountStoreEmployee as accountStoreEmployees | PASS | 已移除 accountStoreEmployee | -| AccountPlatformActive | belongsTo AccountStoreEmployee as accountStoreEmployee | PASS | belongsTo 单数语义保留 | - -## 3. 服务调用链校验结果 - -| 服务 | 校验项 | 结果 | -| --- | --- | --- | -| systems/account_platform | include/读取 employeeRoles 一致 | PASS | -| systems/auth/user | include alias 使用 employeeRoles | PASS | -| systems/store | 角色绑定链路使用 EmployeeRole | PASS | -| systems/storage/receiving | StoreWarehouse 关联补 warehouse_id/use_status 过滤,避免跨仓错关联 | PASS | - -## 4. 验证记录 - -- method-output compare: mismatch=0 -- generated test: 8 passing -- smoke test (login/info/home): 6 passing - -## 5. 4.1 全量审计结果(2026-03-23) - -- 审计报告: association_fk_consistency_report.md -- DB 外键: 51 -- 模型关联: 89 -- 可直接匹配: 53 -- 模型定义但 DB 无外键约束: 28 -- DB 有外键但模型未声明: 13 -- 动态模型/示例占位导致无法静态解析: 5 - -高优先级差异(建议先处理): - -- receiving / receiving_detail / storage 三表关联的 FK 约束缺失项(第一批已处理:删除无效 hasMany(Storage) 关联,并修正 service include 过滤) -- store_warehouse 与 stock_warehouse/receiving 的 store_id 外键语义差异(已完成服务层与模型层双收敛) -- role / role_permission / permission 的部分 FK 未在 DB 层约束(核心约束已补齐,remaining: permission.parent_id 自关联约束策略评估) - -### 5.1 高优先差异处理进展(receiving 第一批) - -- 处理内容: - - 移除 `Receiving.hasMany(Storage, foreignKey: 'receiving_id')` 无效关联(storage 表不存在 receiving_id)。 - - 移除 `ReceivingDetail.hasMany(Storage, foreignKey: 'receiving_detail_id')` 无效关联(storage 表不存在 receiving_detail_id)。 - - `systems/storage/receiving` 多处 `StoreWarehouse` include/query 增加 `warehouse_id + use_status` 过滤,规避跨仓库错关联。 - - `create` 流程中 `store_name` 改为来源 `store_remask`,与仓库门店展示语义对齐。 -- 验证结果: - - method-output compare: mismatch=0 - - generated regression + smoke: 14 passing - -### 5.2 高优先差异处理进展(store_warehouse/stock_warehouse 第二批) - -- 处理内容: - - `systems/stock_store` 的 `store_stock` include 全量补齐 `warehouse_id + use_status` 条件,避免仅按 `store_id` 关联导致跨仓误匹配。 - - 覆盖 count/findAll/search 三处核心查询路径,保持原有返回结构不变。 -- 验证结果: - - method-output compare: mismatch=0 - - generated regression + smoke: 14 passing - -### 5.3 高优先差异处理进展(role/permission 第三批) - -- 处理内容: - - `systems/auth/user` 的权限与菜单查询链路补齐 `Role.status=1` 约束,仅启用角色参与授权。 - - 权限查询补齐 `Permission.status=1` 约束,禁用权限不再进入 `user.permissions` 与菜单树。 - - 对 role_id/permission_id 增加去重处理,避免重复关联导致的冗余查询和重复路径。 -- 验证结果: - - method-output compare: mismatch=0 - - generated regression + smoke: 14 passing - -### 5.4 DB 约束补齐进展(role_permission 第四批) - -- 处理内容: - - 新增迁移 `database/migrations/20260323103000-align-role-permission-fk.js`: - - 将 `wms_role_permission.permission_id` 对齐为 `int(11)`(与 `wms_permission.id` 一致)。 - - 在无孤儿数据时添加 `fk_wms_role_permission_permission` 外键(ON DELETE CASCADE, ON UPDATE RESTRICT)。 - - 同步模型字段类型: `app/model/role_permission.js` 的 `permission_id` 改为 `INTEGER`。 -- 执行结果: - - 已完成数据清洗:`wms_role_permission.permission_id` 孤儿记录 4 条已备份并删除;`wms_role.store_id=0` 的 3 条记录已备份并修正为 `NULL`。 - - 已执行迁移核心动作:`permission_id` 类型已对齐为 `int(11)`,且外键 `fk_wms_role_permission_permission` 已生效。 - - SequelizeMeta 已登记 `20260323103000-align-role-permission-fk.js`。 - - 门禁结果:method-output compare mismatch=0,generated regression + smoke: 14 passing。 - -### 5.5 DB 约束补齐进展(role.store_id 第五批) - -- 处理内容: - - 新增迁移 `database/migrations/20260323113000-add-role-store-fk.js`: - - 将 `wms_role.store_id` 对齐为 `bigint(20) unsigned NULL`。 - - 补充索引 `idx_store_id`。 - - 添加外键 `fk_wms_role_store`(ON UPDATE RESTRICT, ON DELETE SET NULL)。 -- 执行结果: - - `wms_role.store_id` 外键已生效,孤儿计数=0。 - - SequelizeMeta 已登记 `20260323113000-add-role-store-fk.js`。 - - 门禁结果:method-output compare mismatch=0,generated regression + smoke: 14 passing。 - -### 5.6 模型层复合键语义治理进展(store_warehouse/stock_warehouse 第六批) - -- 处理内容: - - `StoreWarehouse` 模型新增统一构造器:`buildScopedWhere` / `buildStoreStockInclude`,收敛 `store_stock` include 的复合键语义。 - - `StockWarehouse.belongsTo(StoreWarehouse as store_stock)` 与 `StoreWarehouse.hasMany(StockWarehouse as store_stock)` 显式标记 `constraints: false`,避免误导为单列外键。 - - `Receiving.belongsTo(StoreWarehouse as store)` 显式标记 `constraints: false`,与 `store_id + warehouse_id` 业务语义对齐。 - - `systems/stock_store` 与 `systems/storage/receiving` 已改为复用模型构造器,减少散落条件。 -- 验证结果: - - method-output compare: mismatch=0 - - generated regression + smoke: 14 passing - -### 5.7 DB 约束补齐进展(permission.parent_id 第七批) - -- 处理内容: - - 新增迁移 `database/migrations/20260323123000-add-permission-parent-fk.js`: - - 将 `wms_permission.parent_id` 根节点语义从 `0` 规范为 `NULL`。 - - 添加自关联外键 `fk_wms_permission_parent`(ON UPDATE RESTRICT, ON DELETE SET NULL)。 - - 模型与服务语义对齐: - - `Permission.parent_id` 改为 `allowNull: true` / `defaultValue: null`,并在 setter 中兼容输入 `0 -> NULL`。 - - 权限树构建根节点判断由 `parent_id===0` 收敛为 `!parent_id`(兼容历史与新语义)。 -- 执行结果: - - 数据复核: `root_zero_after=0`、`root_null_after=42`、`orphan_after=0`。 - - 外键生效: `fk_wms_permission_parent` 已存在。 - - SequelizeMeta 已登记 `20260323123000-add-permission-parent-fk.js`。 - - 触发器策略: 目标库因权限限制(binlog + SUPER)未创建触发器,改由应用层归一化 `0 -> NULL`。 -- 验证结果: - - method-output compare: mismatch=0 - - generated regression + smoke: 14 passing - -## 6. 后续检查 - -- [x] 全量扫描其余模型类方法中的 include 别名一致性(service as 与 model as 差集扫描结果: 0)。 -- [x] 补充 N+1 风险清单与 eager-loading 建议(见 association_eager_loading_n_plus_one_guideline.md)。 - -### 6.1 include alias 一致性收尾扫描(2026-03-23) - -- 扫描范围: - - `app/model/**/*.js` 中 association `as` 定义 - - `app/service/**/*.js` 中 include `as` 使用 -- 扫描方式: - - 先做全量检索(model association / service include) - - 再做集合差集(service alias - model alias)自动比对 -- 扫描结论: - - model alias 总数: 48 - - 差集可疑项: 0 - - 结论: 未发现 include alias 不一致问题,可关闭阶段 4 收尾检查第 1 项。 - -## 7. 4.4 规约落地记录(2026-03-23) - -- 规约文档: association_eager_loading_n_plus_one_guideline.md -- 已固化要求: - - 禁止循环内逐条查询关联表(N+1)。 - - include 必须声明 attributes。 - - 仓库链路 include 必须补齐 warehouse_id + use_status 约束。 - - 涉及关联查询改动必须执行 compare + generated test + smoke。 \ No newline at end of file diff --git a/temp/docs/migration_execution_plan.md b/temp/docs/migration_execution_plan.md deleted file mode 100644 index e486767..0000000 --- a/temp/docs/migration_execution_plan.md +++ /dev/null @@ -1,76 +0,0 @@ -# migration_execution_plan - -更新时间: 2026-03-22 - -## 1. 执行原则 - -- 先解决 SequelizeMeta 漂移,再补新增 migration。 -- 先补静态基表,再补关联表,再补日志/配置/打印等扩展表。 -- 动态分表与视图单独治理,不混入普通 createTable 批次。 -- 所有 migration 需保证幂等,避免现有环境重复执行报错。 - -## 2. 推荐顺序 - -### 步骤 1: 漂移核对 - -- 核对以下 4 个未进入 SequelizeMeta 的 migration 与当前数据库实际结构是否一致: - - 20251111083733-create-wms-stock-store.js - - 20251112085825-create-wms-entry-order.js - - 20251112085844-create-wms-entry-items.js - - 20260322061000-add-delivery-time-to-order-delivery-tables.js -- 若结构已存在且一致,优先制定“补登记基线方案”而不是直接重跑。 - -### 步骤 2: 补齐有 model 的静态表 migration - -优先级建议: -1. 权限与组织类 -2. 库位与库存类 -3. 打印类 -4. 日志与国际化类 - -### 步骤 3: 补齐无 model 但业务依赖的表 migration - -优先补以下类型: -- system_log / api_log -- print_log / print_batch / printer_config -- platform_print_config -- wave_batch / wave_operation_log -- order_operation_log - -### 步骤 4: 动态分表治理 - -- 为 order_delivery/order_items 动态分表建立统一 migration 策略。 -- 后续迁移以“母表 + 动态建表 SQL 模板/工厂策略同步”为主,不逐仓库表固化。 - -### 步骤 5: 视图治理 - -- 为以下视图补充 create/drop migration: - - v_pick_space - - vw_warehouse_quota - -## 3. 建议批次 - -- 批次 A: 漂移核对与基线修正 -- 批次 B: 静态核心表 migration 补齐 -- 批次 C: 日志/配置/打印扩展表 migration 补齐 -- 批次 D: 动态分表与视图治理 - -## 4. local/test 演练方案 - -### local - -- 先在本地库回放已有 migration。 -- 再逐批执行新增 migration。 -- 每批完成后执行 schema 对比与关键 API 冒烟。 - -### test - -- 按 local 已验证通过的批次顺序执行。 -- 保留每批执行前后的表结构快照。 -- 若发现 drift 或兼容问题,先暂停后续批次。 - -## 5. 阶段 2 目标 - -- 明确每类表的 migration 补齐范围。 -- 明确执行顺序和批次边界。 -- 为后续正式补 migration 提供可直接执行的方案基础。 diff --git a/temp/docs/migration_gap_list.md b/temp/docs/migration_gap_list.md deleted file mode 100644 index 76d6314..0000000 --- a/temp/docs/migration_gap_list.md +++ /dev/null @@ -1,107 +0,0 @@ -# migration_gap_list - -更新时间: 2026-03-22 - -## 1. 现状摘要 - -- migration 文件数: 11 -- SequelizeMeta 已执行数: 7 -- 仓库文件与执行记录差值: 4 -- createTable 覆盖表数: 10 -- DB 物理表数: 68 -- 视图数: 2 - -## 2. 命名与顺序审计 - -- 现有 migration 文件命名整体符合“时间戳-动作-对象.js”规范。 -- 当前 migration 主要集中在 2025-11 和 2026-03 两个时间段。 -- 当前主要问题不是命名,而是覆盖率不足和执行状态漂移。 - -## 3. 执行状态漂移 - -以下 migration 文件存在于仓库,但未记录在 SequelizeMeta: - -- 20251111083733-create-wms-stock-store.js -- 20251112085825-create-wms-entry-order.js -- 20251112085844-create-wms-entry-items.js -- 20260322061000-add-delivery-time-to-order-delivery-tables.js - -说明: -- 当前数据库中相关表或字段已存在,说明存在“结构已生效但 migration 未登记”或“迁移在其他环境/手工执行过”的漂移风险。 -- 后续处理时不能直接盲跑这些 migration,必须先做结构一致性核对。 - -## 4. 有 model 但缺 create migration 的表 - -- wms_account_platform_active (app/model/account_platform_active.js) -- wms_account_store_employee (app/model/account_store_employee.js) -- wms_employee_role (app/model/employee_role.js) -- wms_fast_where (app/model/fast_where.js) -- wms_file (app/model/file.js) -- wms_file_reference (app/model/file_reference.js) -- wms_i18n_keys (app/model/i18n_key.js) -- wms_i18n_translations (app/model/i18n_translation.js) -- wms_location_space (app/model/location_space.js) -- wms_location_type (app/model/location_type.js) -- wms_location_zone (app/model/location_zone.js) -- wms_operation_log (app/model/operation_log.js) -- wms_order_delivery (app/model/order_delivery.js) -- wms_order_items (app/model/order_items.js) -- wms_permission (app/model/permission.js) -- wms_platform (app/model/platform.js) -- wms_platfrom_setting (app/model/platform_setting.js) -- wms_print_computer (app/model/print_computer.js) -- wms_print_items (app/model/print_item.js) -- wms_print_record (app/model/print_record.js) -- wms_print_station_express (app/model/print_station_express.js) -- wms_print_stations (app/model/print_stations.js) -- wms_print_template (app/model/print_template.js) -- wms_prohibited_type (app/model/prohibited_type.js) -- wms_qimen_log (app/model/qimen_log.js) -- wms_receiving (app/model/receiving.js) -- wms_receiving_detail (app/model/receiving_detail.js) -- wms_role (app/model/role.js) -- wms_role_permission (app/model/role_permission.js) -- wms_stock_barcodes (app/model/stock_barcode.js) -- wms_stock_unit (app/model/stock_unit.js) -- wms_stock_warehouse (app/model/stock_warehouse.js) -- wms_storage (app/model/storage.js) -- wms_store_join (app/model/store_join.js) - -## 5. 无 model 且无 create migration 的 DB 表 - -- SequelizeMeta -- wms_api_log -- wms_embargo_policies -- wms_express -- wms_express_print_record -- wms_express_setting -- wms_order_delivery_100000 -- wms_order_delivery_1000028 -- wms_order_express -- wms_order_express_print_data -- wms_order_items_100000 -- wms_order_items_1000028 -- wms_order_operation -- wms_order_operation_log -- wms_order_picking -- wms_picking_strategy -- wms_platform_print_config -- wms_print_batch -- wms_print_log -- wms_printer_config -- wms_system_config -- wms_system_log -- wms_wave_batch -- wms_wave_operation_log - -## 6. 特殊对象说明 - -- 动态分表: - - wms_order_delivery_* - - wms_order_items_* - 这类表不建议逐张固化 create migration,应通过“母表迁移 + 动态建表策略”统一治理。 -- 视图: - - vw_warehouse_quota - - v_pick_space - 需要单独使用 view migration 管理。 -- SequelizeMeta 属于迁移元数据表,不纳入业务模型补齐范围。 diff --git a/temp/docs/modelList.md b/temp/docs/modelList.md deleted file mode 100644 index 004aa0a..0000000 --- a/temp/docs/modelList.md +++ /dev/null @@ -1,105 +0,0 @@ -# modelList - -更新时间: 2026-03-22 -扫描范围: app/model/*.js -模型文件数: 45 - -## 1. 目标 - -- 用于快速查看模型层级结构。 -- 用于后续 model 命名规范、关联规范、迁移补全的基线输入。 - -## 2. 模型层级结构 - -```text -app/model/ -├─ 账号与权限 -│ ├─ account.js -│ ├─ account_platform_active.js -│ ├─ account_store_employee.js -│ ├─ employee_role.js -│ ├─ permission.js -│ ├─ role.js -│ └─ role_permission.js -├─ 组织与仓库 -│ ├─ store.js -│ ├─ store_join.js -│ ├─ store_warehouse.js -│ ├─ storage.js -│ ├─ receiving.js -│ ├─ receiving_detail.js -│ ├─ entry_order.js -│ └─ entry_items.js -├─ 库位与查询 -│ ├─ location_type.js -│ ├─ location_zone.js -│ ├─ location_space.js -│ └─ fast_where.js -├─ 库存与商品 -│ ├─ stock_store.js -│ ├─ stock_warehouse.js -│ ├─ stock_unit.js -│ ├─ stock_barcode.js -│ └─ prohibited_type.js -├─ 订单与履约 -│ ├─ order_delivery.js -│ ├─ order_items.js -│ ├─ order_delivery_factory.js -│ └─ order_items_factory.js -├─ 打印能力 -│ ├─ print_template.js -│ ├─ print_item.js -│ ├─ print_record.js -│ ├─ print_stations.js -│ ├─ print_station_express.js -│ └─ print_computer.js -├─ 开放平台与接口 -│ ├─ api_app.js -│ ├─ qimen_app.js -│ ├─ qimen_log.js -│ ├─ platform.js -│ ├─ platform_setting.js -│ └─ interface_type.js -└─ 文件、日志与国际化 - ├─ file.js - ├─ file_reference.js - ├─ operation_log.js - ├─ i18n_key.js - └─ i18n_translation.js -``` - -## 3. 关键说明 - -### 3.1 动态分表模型 - -- order_delivery_factory.js - - 负责按 warehouse 维度动态创建/获取发货单模型。 -- order_items_factory.js - - 负责按 warehouse 维度动态创建/获取订单商品模型。 - -说明: -- 这两个文件不是普通静态 Sequelize 定义文件,而是动态模型工厂能力。 - -### 3.2 典型关联模型 - -- fast_where.js - - 自关联: parent/children。 -- location_zone.js - - 自关联 + 与 Store、LocationSpace 的关联。 -- i18n_translation.js - - 关联 i18n_key。 -- prohibited_type.js - - 关联 Store、StockWarehouse。 -- stock_barcode.js - - 关联 StockWarehouse。 - -### 3.3 命名现状观察 - -- define 名称存在 snake_case 与 PascalCase 混用。 -- 部分模型文件命名与 define 名称不完全一致。 -- 后续需结合 model_naming_standard 做统一收敛。 - -## 4. 后续维护规则 - -- 每次新增/删除/重命名 model 文件后,需同步更新本文件。 -- 每次新增/调整关联后,需同步更新本文件的关键说明章节。 diff --git a/temp/docs/model_association_inventory.md b/temp/docs/model_association_inventory.md deleted file mode 100644 index f6c84c4..0000000 --- a/temp/docs/model_association_inventory.md +++ /dev/null @@ -1,52 +0,0 @@ -# model_association_inventory - -Updated: 2026-03-22 -Source: app/model/*.js - -| key | file | associations | -| --- | --- | --- | -| account_platform_active | app/model/account_platform_active.js | - | -| account_store_employee | app/model/account_store_employee.js | - | -| account | app/model/account.js | - | -| api_app | app/model/api_app.js | - | -| employee_role | app/model/employee_role.js | - | -| entry_items | app/model/entry_items.js | - | -| entry_order | app/model/entry_order.js | - | -| fast_where | app/model/fast_where.js | belongsTo->FastWhere, hasMany->FastWhere | -| file_reference | app/model/file_reference.js | - | -| file | app/model/file.js | - | -| i18n_key | app/model/i18n_key.js | - | -| i18n_translation | app/model/i18n_translation.js | belongsTo->I18nKey | -| interface_type | app/model/interface_type.js | - | -| location_space | app/model/location_space.js | - | -| location_type | app/model/location_type.js | belongsTo->Store | -| location_zone | app/model/location_zone.js | belongsTo->LocationZone, hasMany->LocationZone, belongsTo->Store, hasMany->LocationSpace | -| operation_log | app/model/operation_log.js | - | -| order_delivery_factory | app/model/order_delivery_factory.js | - | -| order_delivery | app/model/order_delivery.js | - | -| order_items_factory | app/model/order_items_factory.js | - | -| order_items | app/model/order_items.js | - | -| permission | app/model/permission.js | - | -| platform_setting | app/model/platform_setting.js | - | -| platform | app/model/platform.js | - | -| print_computer | app/model/print_computer.js | - | -| print_item | app/model/print_item.js | - | -| print_record | app/model/print_record.js | - | -| print_station_express | app/model/print_station_express.js | - | -| print_stations | app/model/print_stations.js | - | -| print_template | app/model/print_template.js | - | -| prohibited_type | app/model/prohibited_type.js | belongsTo->Store, hasMany->StockWarehouse | -| qimen_app | app/model/qimen_app.js | - | -| qimen_log | app/model/qimen_log.js | - | -| receiving_detail | app/model/receiving_detail.js | - | -| receiving | app/model/receiving.js | - | -| role_permission | app/model/role_permission.js | - | -| role | app/model/role.js | - | -| stock_barcode | app/model/stock_barcode.js | belongsTo->StockWarehouse | -| stock_store | app/model/stock_store.js | - | -| stock_unit | app/model/stock_unit.js | - | -| stock_warehouse | app/model/stock_warehouse.js | - | -| storage | app/model/storage.js | - | -| store_join | app/model/store_join.js | - | -| store_warehouse | app/model/store_warehouse.js | - | -| store | app/model/store.js | - | diff --git a/temp/docs/model_boundary_rules.md b/temp/docs/model_boundary_rules.md deleted file mode 100644 index c334808..0000000 --- a/temp/docs/model_boundary_rules.md +++ /dev/null @@ -1,105 +0,0 @@ -# model_boundary_rules - -更新时间: 2026-03-23 -适用范围: app/model/**/*.js -目标: 约束 model 层仅承担数据映射与轻量领域行为,避免业务编排回流到模型层。 - -## 1. 当前盘点结果(阶段 5.3) - -- hooks: - - app/model/entry_items.js - - EntryItems.beforeSave - - EntryItems.beforeUpdate -- scopes: - - app/model/print_item.js - - tableFields - - groupFields - - active - - byBusiness - - byPlatform -- virtual fields: - - 当前未检出 DataTypes.VIRTUAL / VIRTUAL 字段定义。 - -结论: -- 目前模型层 hooks/scopes 使用量较低,适合在当前阶段一次性固化边界规则。 - -## 2. 模型层职责边界 - -模型层允许: -- 表结构映射(字段、索引、注释、主键、表名映射)。 -- 关联定义(belongsTo/hasMany/hasOne/belongsToMany)与关联语义辅助。 -- 轻量实例行为(如 isEnabled/isExpired/getProgress 等纯实例判断)。 -- 与单行数据一致性相关的同步校验(例如数量非负、上下限关系)。 - -模型层禁止: -- 跨表业务编排(批量流转、聚合统计、分配策略、权限树组装)。 -- 事务边界控制(begin/commit/rollback)与重试策略。 -- 外部副作用(调用第三方接口、写 Redis、发消息、发通知)。 -- 依赖请求上下文(ctx、当前登录人、租户动态鉴权)。 - -## 3. Hooks 规则 - -允许场景: -- 单行数据写入前的确定性校验。 -- 无 I/O 的轻量数据规整(例如 trim、默认值兜底)。 - -禁止场景: -- hook 中查询其他 model 决定业务分支。 -- hook 中进行跨记录批处理或库存/权限编排。 -- hook 中访问 service、http、cache、mq。 - -实现要求: -- 必须保持幂等与可重复执行安全。 -- 必须是低成本逻辑,避免在热路径引入重查询。 -- 错误信息聚焦数据约束,不承载业务流程语义。 - -## 4. Scopes 规则 - -允许场景: -- 静态筛选片段复用(状态、业务类型、平台等)。 -- 参数化但纯查询片段的 where 条件构造。 - -禁止场景: -- 将权限判断或业务流程分支下沉到 scope。 -- 在 scope 中拼装复杂 include 链并耦合排序/分页策略。 -- 在 scope 中引入时间窗口策略或上下文依赖(如当前用户、当前 project)。 - -实现要求: -- scope 输出应稳定、可预期、可独立单测。 -- 命名必须体现过滤语义,不使用模糊命名。 - -## 5. Virtual Fields 规则 - -允许场景: -- 展示层只读衍生值(字段拼接、标签映射、轻量格式化)。 - -禁止场景: -- virtual getter 内进行数据库查询或异步调用。 -- 承载鉴权、状态流转或可写业务语义。 - -实现要求: -- 明确只读语义,不作为持久化字段参与写入。 -- 若需要跨表推导,改由 service 返回 DTO 字段。 - -## 6. 现有代码归属说明 - -- app/model/entry_items.js hooks 保留原因: - - 仅执行已收货数量与计划数量的单行一致性校验。 - - 未引入跨表查询、事务或副作用,符合模型边界。 - -- app/model/print_item.js scopes 保留原因: - - 仅复用静态筛选条件,不承载业务编排。 - - 范围清晰,可作为查询片段复用。 - -## 7. 变更准入清单(新增/修改 model 时必须检查) - -- 是否引入了跨表编排逻辑?若是,必须移至 app/service/systems/*。 -- 是否引入了事务控制?若是,必须移至 service。 -- 是否新增 hook 且包含 I/O?若是,不允许合入。 -- 是否新增 scope 且耦合业务流程/鉴权?若是,不允许合入。 -- 是否新增 virtual 并依赖查询/异步?若是,不允许合入。 - -## 8. 与阶段计划的映射 - -- 阶段 5.3: 已完成(盘点 + 规则固化)。 -- 阶段 5.4: 基于本文件持续执行审查,作为后续模型改动的门禁依据。 \ No newline at end of file diff --git a/temp/docs/model_cleanup_list.md b/temp/docs/model_cleanup_list.md deleted file mode 100644 index 12f0cf0..0000000 --- a/temp/docs/model_cleanup_list.md +++ /dev/null @@ -1,292 +0,0 @@ -# model_cleanup_list - -更新时间: 2026-03-23 -阶段: 5.4 模型边界规则固化与门禁脚本接入(已执行) - -## 1. 盘点结论 - -- 扫描范围: app/model/**/*.js -- 检出方法总数: 102(实例 + 静态) -- 高优先候选(应迁移到 service): 24 -- 低风险可移除候选(当前未发现业务调用): 18 -- 保留在模型层(轻量领域判断/展示映射): 22 - -说明: -- 本次调用扫描采用“静态方法名精确匹配”策略(Model.method(...))。 -- 对“应迁移”项,目标是把跨表编排、状态机、批量事务、库存分配等逻辑从 model 剥离到 systems service。 - -## 2. 第一批应迁移(P1) - -### 2.1 入库单聚合与状态流转 - -- 文件: app/model/entry_order.js -- 候选方法: - - findByOrderCode - - findByStatus - - getStatsByWarehouse - - updateSyncStatus - - updateOrderStatus - - calculateReceivedQuantities -- 迁移目标: - - app/service/systems/entry_order.js -- 原因: - - 含分页查询、跨表 include、状态流转约束、聚合统计,属于业务编排而非数据映射。 - -### 2.2 入库明细批量更新与进度汇总 - -- 文件: app/model/entry_items.js -- 候选方法: - - batchUpdateReceived - - getOrderProgress -- 迁移目标: - - app/service/systems/entry_order.js(或 app/service/systems/storage/receiving.js) -- 原因: - - 含事务控制、批量更新和跨记录校验,属于服务层职责。 - -### 2.3 库存分配/锁定编排 - -- 文件: app/model/storage.js -- 候选方法: - - updateQuantity - - lockQuantity - - unlockQuantity - - allocateQuantity - - getStockSummary - - getSpaceUsage - - findByStockAndBatch - - findBySpace - - findAvailableByWarehouse - - findExpiringSoon -- 迁移目标: - - app/service/systems/stock_store.js - - app/service/systems/storage/receiving.js -- 原因: - - 涉及库存扣减/锁定语义、聚合统计和业务筛选,属于库存域服务。 - -### 2.4 角色权限写入与查询编排 - -- 文件: app/model/role.js -- 候选方法: - - assignPermissions - - getPermissionTree - - getPermissionIds -- 文件: app/model/role_permission.js -- 候选方法: - - bulkAssign - - clearRolePermissions - - getRolePermissions - - hasPermission -- 迁移目标: - - app/service/systems/auth/user.js - - 新增 app/service/systems/auth/role_permission.js(推荐) -- 原因: - - 包含权限关系写操作、树构建和权限判定,应集中在鉴权服务边界。 - -### 2.5 商家数据校验与查询助手 - -- 文件: app/model/store.js -- 候选方法: - - validateStoreData - - checkCompanyNameExists - - findByAccountId - - findAllEnabled - - findAllWarehouses -- 迁移目标: - - app/service/systems/store.js -- 原因: - - 请求参数校验和查询策略属于服务层,不应下沉到 model。 - -## 3. 可移除候选(P2,先验证后删) - -- 已执行(第一批): - - app/model/api_app.js: `findByAppKey`、`findByQimenConfig`(已删除) - - app/model/interface_type.js: `findByCode`、`findEnabled`(已删除) - - app/model/print_item.js: `getGroupFields`、`getTableConfigs`(已删除) - - 门禁结果: compare mismatch=0,generated regression + smoke=14 passing - -- app/model/i18n_translation.js: - - getTranslation - - batchGetTranslations - - getProjectTranslations - - upsertTranslation - - getUntranslated -- app/model/interface_type.js: - - findByCode - - findEnabled -- app/model/print_item.js: - - getGroupFields - - getTableConfigs -- app/model/api_app.js: - - findByAppKey - - findByQimenConfig -- app/model/stock_store.js: - - findByItemCode - - findByStore - -说明: -- 上述方法本轮未检出业务层调用,建议先完成一次“删除前引用复核”再执行清理。 - -## 4. 保留在模型层(P3) - -建议保留: -- 轻量实例判断(isEnabled/isHidden/isExpired 等)。 -- 纯格式/展示映射(getTypeName/getRoleTypeName/getScopeName)。 -- 与关联语义绑定的 include 构造器(StoreWarehouse.buildStoreStockInclude)。 - -## 5. 阶段状态(截至 2026-03-23) - -1. 已完成 P1 四组迁移(EntryOrder/EntryItems、Storage、Role/RolePermission、Store)到 service。 -2. 已完成 P2 第二批清理(I18nTranslation / StockStore),并通过门禁。 -3. 已完成 5.3:完成 hooks/scopes/virtual fields 全量盘点并形成规则。 -4. 已完成 5.4:新增可执行门禁脚本并接入 npm/CI。 - -## 6. 已执行(P2 第二批) - -- 执行时间: 2026-03-23 -- 删除范围: - - app/model/i18n_translation.js - - app/model/stock_store.js -- 删除方法: - - I18nTranslation.getTranslation - - I18nTranslation.batchGetTranslations - - I18nTranslation.getProjectTranslations - - I18nTranslation.upsertTranslation - - I18nTranslation.getUntranslated - - StockStore.findByItemCode - - StockStore.findByStore -- 门禁结果: - - compare mismatch=0 - - generated regression=8 passing - - smoke=6 passing - - tests=14 passing - -## 7. 已执行(P1 第一组) - -- 执行时间: 2026-03-23 -- 迁移范围: - - app/model/entry_order.js - - app/model/entry_items.js - - app/service/systems/entry_order.js -- 迁移方法: - - EntryOrder.findByOrderCode - - EntryOrder.findByStatus - - EntryOrder.getStatsByWarehouse - - EntryOrder.updateSyncStatus - - EntryOrder.updateOrderStatus - - EntryOrder.calculateReceivedQuantities - - EntryItems.batchUpdateReceived - - EntryItems.getOrderProgress -- 门禁结果: - - compare mismatch=0 - - generated regression=8 passing - - smoke=6 passing - - tests=14 passing - -## 8. 已执行(P1 第二组) - -- 执行时间: 2026-03-23 -- 迁移范围: - - app/model/storage.js - - app/service/systems/storage/index.js -- 迁移方法: - - Storage.findByStockAndBatch - - Storage.findBySpace - - Storage.findAvailableByWarehouse - - Storage.findExpiringSoon - - Storage.updateQuantity - - Storage.lockQuantity - - Storage.unlockQuantity - - Storage.allocateQuantity - - Storage.getStockSummary - - Storage.getSpaceUsage -- 门禁结果: - - compare mismatch=0 - - generated regression=8 passing - - smoke=7 passing - - tests=15 passing - -## 9. 已执行(P1 第三组) - -- 执行时间: 2026-03-23 -- 迁移范围: - - app/model/role.js - - app/model/role_permission.js - - app/service/systems/auth/role_permission.js -- 迁移方法: - - Role.assignPermissions - - Role.getPermissionTree - - Role.getPermissionIds - - RolePermission.bulkAssign - - RolePermission.clearRolePermissions - - RolePermission.getRolePermissions - - RolePermission.hasPermission -- 门禁结果: - - compare mismatch=0 - - generated regression=8 passing - - smoke=7 passing - - tests=15 passing - -## 10. 已执行(P1 第四组) - -- 执行时间: 2026-03-23 -- 迁移范围: - - app/model/store.js - - app/service/systems/store.js -- 迁移方法: - - Store.validateStoreData - - Store.checkCompanyNameExists - - Store.findByAccountId - - Store.findAllEnabled - - Store.findAllWarehouses -- 门禁结果: - - compare mismatch=0 - - generated regression=8 passing - - smoke=7 passing - - tests=15 passing - -## 11. 已执行(5.3 边界规范) - -- 执行时间: 2026-03-23 -- 扫描范围: - - app/model/**/*.js -- 扫描结果: - - hooks: 2 处(EntryItems.beforeSave / EntryItems.beforeUpdate) - - scopes: 1 处定义(PrintItem.scopes) - - virtual fields: 0 -- 产出文档: - - model_boundary_rules.md -- 执行结论: - - 现有 hooks/scopes 均符合“单行一致性校验/静态筛选片段”边界。 - - 后续新增或修改模型逻辑时,按 model_boundary_rules.md 作为合入门禁。 - -## 12. 已执行(5.4 门禁脚本验证) - -- 执行时间: 2026-03-23 -- 执行命令: - - npm run check:model-boundary -- 结果摘要: - - [MODEL-BOUNDARY] files=45 - - [MODEL-BOUNDARY] hooks=2 - - [MODEL-BOUNDARY] scopeFiles=1 - - [MODEL-BOUNDARY] virtualLines=0 - - [MODEL-BOUNDARY] PASS -- 结论: - - 模型边界检查脚本可稳定执行,已具备本地与 CI 统一门禁能力。 - -## 13. 已执行(5.4 门禁固化) - -- 执行时间: 2026-03-23 -- 新增脚本: - - script/model-boundary-check.cjs -- 覆盖规则: - - 禁止 model 直接调用 service - - 禁止 model 外部 HTTP 调用 - - 禁止 model 读写 Redis/缓存 - - 禁止 model 通过 ctx.model 进行跨模型编排 - - 禁止 model 定义事务控制逻辑 - - hooks/scopes/virtual 使用 allowlist 准入 -- 接入方式: - - npm run check:model-boundary - - npm run ci(已串联) -- 执行结论: - - 模型层边界已具备自动化门禁能力,后续新增越界代码可在本地与 CI 及时阻断。 diff --git a/temp/docs/model_inventory.md b/temp/docs/model_inventory.md deleted file mode 100644 index faa4702..0000000 --- a/temp/docs/model_inventory.md +++ /dev/null @@ -1,53 +0,0 @@ -# model_inventory - -Updated: 2026-03-22 -Source: app/model/*.js -Count: 45 - -| key | file | defineName | tableName | kind | -| --- | --- | --- | --- | --- | -| account_platform_active | app/model/account_platform_active.js | account_platform_active | wms_account_platform_active | Model | -| account_store_employee | app/model/account_store_employee.js | wms_account_store_employee | wms_account_store_employee | Model | -| account | app/model/account.js | account | wms_account | Model | -| api_app | app/model/api_app.js | api_app | wms_api_app | Model | -| employee_role | app/model/employee_role.js | employee_role | wms_employee_role | Model | -| entry_items | app/model/entry_items.js | wms_entry_items | wms_entry_items | Model | -| entry_order | app/model/entry_order.js | wms_entry_order | wms_entry_order | Model | -| fast_where | app/model/fast_where.js | fast_where | wms_fast_where | Model | -| file_reference | app/model/file_reference.js | wms_file_reference | wms_file_reference | Model | -| file | app/model/file.js | wms_file | wms_file | Model | -| i18n_key | app/model/i18n_key.js | wms_i18n_key | wms_i18n_keys | Model | -| i18n_translation | app/model/i18n_translation.js | wms_i18n_translation | wms_i18n_translations | Model | -| interface_type | app/model/interface_type.js | interface_type | wms_interface_type | Model | -| location_space | app/model/location_space.js | wms_location_space | wms_location_space | Model | -| location_type | app/model/location_type.js | location_type | wms_location_type | Model | -| location_zone | app/model/location_zone.js | wms_location_zone | wms_location_zone | Model | -| operation_log | app/model/operation_log.js | operation_log | wms_operation_log | Model | -| order_delivery_factory | app/model/order_delivery_factory.js | - | - | Factory | -| order_delivery | app/model/order_delivery.js | order_delivery | wms_order_delivery | Model | -| order_items_factory | app/model/order_items_factory.js | - | - | Factory | -| order_items | app/model/order_items.js | wms_order_items | wms_order_items | Model | -| permission | app/model/permission.js | permission | wms_permission | Model | -| platform_setting | app/model/platform_setting.js | platform_setting | wms_platfrom_setting | Model | -| platform | app/model/platform.js | platform | wms_platform | Model | -| print_computer | app/model/print_computer.js | print_computer | wms_print_computer | Model | -| print_item | app/model/print_item.js | print_item | wms_print_items | Model | -| print_record | app/model/print_record.js | PrintRecord | wms_print_record | Model | -| print_station_express | app/model/print_station_express.js | print_station_express | wms_print_station_express | Model | -| print_stations | app/model/print_stations.js | print_stations | wms_print_stations | Model | -| print_template | app/model/print_template.js | print_template | wms_print_template | Model | -| prohibited_type | app/model/prohibited_type.js | prohibitedType | wms_prohibited_type | Model | -| qimen_app | app/model/qimen_app.js | qimen_app | wms_qimen_apps | Model | -| qimen_log | app/model/qimen_log.js | qimen_log | wms_qimen_log | Model | -| receiving_detail | app/model/receiving_detail.js | wms_receiving_detail | wms_receiving_detail | Model | -| receiving | app/model/receiving.js | wms_receiving | wms_receiving | Model | -| role_permission | app/model/role_permission.js | role_permission | wms_role_permission | Model | -| role | app/model/role.js | role | wms_role | Model | -| stock_barcode | app/model/stock_barcode.js | stock_barcodes | wms_stock_barcodes | Model | -| stock_store | app/model/stock_store.js | stock_store | wms_stock_store | Model | -| stock_unit | app/model/stock_unit.js | wms_stock_unit | wms_stock_unit | Model | -| stock_warehouse | app/model/stock_warehouse.js | stock_warehouse | wms_stock_warehouse | Model | -| storage | app/model/storage.js | wms_storage | wms_storage | Model | -| store_join | app/model/store_join.js | StoreJoin | wms_store_join | Model | -| store_warehouse | app/model/store_warehouse.js | store_warehouse | wms_store_warehouse | Model | -| store | app/model/store.js | store | wms_store | Model | diff --git a/temp/docs/model_naming_standard.md b/temp/docs/model_naming_standard.md deleted file mode 100644 index 24fc928..0000000 --- a/temp/docs/model_naming_standard.md +++ /dev/null @@ -1,184 +0,0 @@ -# Model 命名规范 - -更新时间: 2026-03-22 -适用范围: app/model、app/service、app/controller 中的 app.model / ctx.model 调用 - -## 1. 目标 - -- 统一 model 文件名、运行时 key、defineName、tableName、关联 alias 的命名规则。 -- 将“可直接收敛的风格问题”和“会影响业务语义的结构问题”拆开处理。 -- 为阶段 4 的关联规范化和阶段 5 的模型能力清理提供稳定基线。 - -## 2. 五层命名对象 - -当前仓库里,单个模型至少同时存在以下 5 个命名层: - -1. 文件名: app/model 下的文件名。 -2. 运行时 key: 代码里通过 app.model.Xxx / ctx.model.Xxx 使用的名称。 -3. defineName: Sequelize 的 app.model.define(name, attributes, options) 第一个参数。 -4. tableName: options.tableName,对应数据库真实对象名。 -5. alias: 关联查询里的 as 字段。 - -后续规范要求这 5 层职责分离,不再互相混用。 - -## 3. 统一规则 - -### 3.1 文件名 - -- 一律使用 snake_case。 -- 文件名表达“模型职责”,不表达数据库前缀。 -- 工厂模型必须以 _factory 结尾。 -- 除非是稳定历史兼容项,否则不在文件名中保留 wms 前缀。 - -示例: - -- account_store_employee.js -- platform_setting.js -- order_delivery_factory.js - -### 3.2 运行时 key - -- 一律使用 PascalCase。 -- 运行时 key 由文件名去掉扩展名后转为 PascalCase。 -- 这是 service/controller/model 之间的主兼容面,优先级高于 defineName。 -- 工厂模型保留 Factory 后缀。 - -示例: - -- account_store_employee.js -> AccountStoreEmployee -- platform_setting.js -> PlatformSetting -- order_delivery_factory.js -> OrderDeliveryFactory - -### 3.3 defineName - -- 静态模型的 defineName 必须与运行时 key 保持一致。 -- 不再使用 snake_case、wms_ 前缀或局部 lowerCamelCase 作为 defineName。 -- 动态分表模型允许在运行时使用真实 tableName 作为 defineName,但外部只允许通过工厂 key 获取,不直接在业务层引用动态 defineName。 - -示例: - -- PlatformSetting: 正确 -- platform_setting: 不再推荐 -- prohibitedType: 不再推荐 -- wms_account_store_employee: 不再推荐 - -### 3.4 tableName - -- tableName 只负责映射数据库真实对象。 -- 一律保持数据库现状,不因 model 命名规范化而强制修改表名。 -- 物理表继续保留现有 wms_ 前缀、复数形式、历史拼写问题。 -- 视图、动态分表、历史表单独记录,不纳入静态命名统一的修改范围。 - -示例: - -- PlatformSetting -> tableName: wms_platfrom_setting -- StockBarcode -> tableName: wms_stock_barcodes -- PrintStations -> tableName: wms_print_stations - -说明: - -- tableName 中的历史拼写错误属于数据库治理问题,不属于本阶段命名规范化问题。 - -### 3.5 alias - -- belongsTo / hasOne 使用 lowerCamelCase 单数。 -- hasMany / belongsToMany 使用 lowerCamelCase 复数。 -- alias 反映关联语义,不复用旧表名或旧模型名。 -- alias 必须与真实关系一致,不能把 employee 关系继续命名为 role。 - -示例: - -- belongsTo(Store, { as: 'store' }) -- hasMany(EmployeeRole, { as: 'employeeRoles' }) -- belongsTo(AccountStoreEmployee, { as: 'accountStoreEmployee' }) - -## 4. 兼容优先级 - -按风险从高到低分三类处理: - -### A 类: 运行时 key 不存在或调用错误 - -- 必须先修。 -- 这类问题会直接导致运行时取不到模型,或拿到错误关联。 -- 典型例子: - - AccountStoreRole - - WmsOrderDeliveryFactory - - WmsOrderItemsFactory - -### B 类: defineName 不规范但运行时可用 - -- 可分批修。 -- 前提是 tableName 已显式声明,且不存在依赖 defineName 字符串的外部逻辑。 -- 典型例子: - - platform_setting - - qimen_app - - qimen_log - - prohibitedType - - stock_barcodes - -### C 类: alias 与业务语义不一致 - -- 必须与阶段 4 一起处理。 -- 不能只改 alias 文本,需要一起核对外键、include、返回结构。 -- 典型例子: - - accountStoreRoles - - accountStoreRole - - employeeRole - -## 5. 仓库内落地规则 - -### 5.1 本项目允许保留的历史兼容项 - -以下项目前阶段不因“风格统一”而强制改文件名: - -- print_stations.js - - 原因: 运行时大量使用 PrintStations,且 tableName 为 wms_print_stations。 -- store_join.js - - 原因: 运行时与 defineName 已一致,当前主要问题不在命名层。 -- order_delivery_factory.js / order_items_factory.js - - 原因: 工厂职责明确,外部兼容面稳定。 - -### 5.2 本项目必须执行的统一动作 - -- 所有静态模型的 defineName 逐步收敛到 PascalCase 运行时 key。 -- 所有业务代码统一通过 ctx.model.Xxx / app.model.Xxx 的 PascalCase key 调用。 -- 任何 include/as 字段都必须与当前模型关联定义一致。 -- 不再新增任何带 wms 前缀的 defineName。 -- 不再新增任何与真实语义不一致的 alias。 - -## 6. 参考示例 - -### 6.1 标准静态模型 - -- 文件名: platform_setting.js -- 运行时 key: PlatformSetting -- defineName: PlatformSetting -- tableName: wms_platfrom_setting - -### 6.2 标准关联模型 - -- 文件名: account_store_employee.js -- 运行时 key: AccountStoreEmployee -- defineName: AccountStoreEmployee -- tableName: wms_account_store_employee -- alias: - - belongsTo(Account, { as: 'account' }) - - belongsTo(Store, { as: 'store' }) - - hasMany(EmployeeRole, { as: 'employeeRoles' }) - -### 6.3 标准工厂模型 - -- 文件名: order_delivery_factory.js -- 运行时 key: OrderDeliveryFactory -- 对外入口: - - ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId) - - ctx.model.OrderDeliveryFactory.getHistoryModel(warehouseId) -- 约束: - - 业务代码不直接引用动态表 defineName。 - -## 7. 执行边界 - -- 本阶段先统一标准、映射和影响面,不直接大规模改名。 -- 运行时 key 修复优先于 defineName 收敛。 -- alias 修复必须与关联关系校验一起推进。 -- 数据库表名不在本阶段统一修改范围内。 \ No newline at end of file diff --git a/temp/docs/model_rename_map.md b/temp/docs/model_rename_map.md deleted file mode 100644 index 367501a..0000000 --- a/temp/docs/model_rename_map.md +++ /dev/null @@ -1,100 +0,0 @@ -# Model 重命名映射表 - -更新时间: 2026-03-22 -来源: - -- model_inventory.md -- app/model/*.js -- app/service/**/*.js -- app/controller/**/*.js - -## 1. 使用说明 - -- 本表只记录阶段 3 已确认的命名规范化项。 -- 变更级别分为 4 类: - - P0-调用修复: 现有代码引用错误或运行时 key 不存在,必须先修。 - - P1-defineName 收敛: 只调整 defineName,不动文件名和 tableName。 - - P2-alias 收敛: 需要和关联定义一起调整。 - - 保持不动: 暂不建议改动。 - -## 2. P0: 必须先修的运行时调用 - -| 当前调用/命名 | 建议标准名 | 变更级别 | 原因 | 备注 | -| --- | --- | --- | --- | --- | -| WmsOrderDeliveryFactory | OrderDeliveryFactory | P0-调用修复 | 仓库内主流调用均为 OrderDeliveryFactory,当前写法与文件名不匹配 | 先修 app/service/apiMethods/test.js | -| WmsOrderItemsFactory | OrderItemsFactory | P0-调用修复 | 仓库内主流调用均为 OrderItemsFactory,当前写法与文件名不匹配 | 先修 app/service/apiMethods/test.js | -| AccountStoreRole | AccountStoreEmployee 或补回独立模型 | P0-调用修复 | 仓库内无 account_store_role.js,且当前表结构已落到 account_store_employee + employee_role | 需要先确认目标数据关系 | -| accountStoreRole | accountStoreEmployee | P0-调用修复 | AccountPlatformActive 当前关联 alias 为 accountStoreEmployee,service 仍按 accountStoreRole 取值 | 要与 include 返回结构一起改 | - -## 3. P1: defineName 收敛为运行时 key - -以下项优先采用“只改 defineName,不改文件名、不改 tableName”的方式收敛。 - -| 文件 | 当前运行时 key | 当前 defineName | 建议 defineName | 变更级别 | -| --- | --- | --- | --- | --- | -| app/model/account_platform_active.js | AccountPlatformActive | account_platform_active | AccountPlatformActive | P1-defineName 收敛 | -| app/model/account_store_employee.js | AccountStoreEmployee | wms_account_store_employee | AccountStoreEmployee | P1-defineName 收敛 | -| app/model/account.js | Account | account | Account | P1-defineName 收敛 | -| app/model/api_app.js | ApiApp | api_app | ApiApp | P1-defineName 收敛 | -| app/model/employee_role.js | EmployeeRole | employee_role | EmployeeRole | P1-defineName 收敛 | -| app/model/entry_items.js | EntryItems | wms_entry_items | EntryItems | P1-defineName 收敛 | -| app/model/entry_order.js | EntryOrder | wms_entry_order | EntryOrder | P1-defineName 收敛 | -| app/model/fast_where.js | FastWhere | fast_where | FastWhere | P1-defineName 收敛 | -| app/model/file_reference.js | FileReference | wms_file_reference | FileReference | P1-defineName 收敛 | -| app/model/file.js | File | wms_file | File | P1-defineName 收敛 | -| app/model/i18n_key.js | I18nKey | wms_i18n_key | I18nKey | P1-defineName 收敛 | -| app/model/i18n_translation.js | I18nTranslation | wms_i18n_translation | I18nTranslation | P1-defineName 收敛 | -| app/model/interface_type.js | InterfaceType | interface_type | InterfaceType | P1-defineName 收敛 | -| app/model/location_space.js | LocationSpace | wms_location_space | LocationSpace | P1-defineName 收敛 | -| app/model/location_type.js | LocationType | location_type | LocationType | P1-defineName 收敛 | -| app/model/location_zone.js | LocationZone | wms_location_zone | LocationZone | P1-defineName 收敛 | -| app/model/operation_log.js | OperationLog | operation_log | OperationLog | P1-defineName 收敛 | -| app/model/order_delivery.js | OrderDelivery | order_delivery | OrderDelivery | P1-defineName 收敛 | -| app/model/order_items.js | OrderItems | wms_order_items | OrderItems | P1-defineName 收敛 | -| app/model/permission.js | Permission | permission | Permission | P1-defineName 收敛 | -| app/model/platform_setting.js | PlatformSetting | platform_setting | PlatformSetting | P1-defineName 收敛 | -| app/model/platform.js | Platform | platform | Platform | P1-defineName 收敛 | -| app/model/print_computer.js | PrintComputer | print_computer | PrintComputer | P1-defineName 收敛 | -| app/model/print_item.js | PrintItem | print_item | PrintItem | P1-defineName 收敛 | -| app/model/print_station_express.js | PrintStationExpress | print_station_express | PrintStationExpress | P1-defineName 收敛 | -| app/model/print_stations.js | PrintStations | print_stations | PrintStations | P1-defineName 收敛 | -| app/model/print_template.js | PrintTemplate | print_template | PrintTemplate | P1-defineName 收敛 | -| app/model/prohibited_type.js | ProhibitedType | prohibitedType | ProhibitedType | P1-defineName 收敛 | -| app/model/qimen_app.js | QimenApp | qimen_app | QimenApp | P1-defineName 收敛 | -| app/model/qimen_log.js | QimenLog | qimen_log | QimenLog | P1-defineName 收敛 | -| app/model/receiving_detail.js | ReceivingDetail | wms_receiving_detail | ReceivingDetail | P1-defineName 收敛 | -| app/model/receiving.js | Receiving | wms_receiving | Receiving | P1-defineName 收敛 | -| app/model/role_permission.js | RolePermission | role_permission | RolePermission | P1-defineName 收敛 | -| app/model/role.js | Role | role | Role | P1-defineName 收敛 | -| app/model/stock_barcode.js | StockBarcode | stock_barcodes | StockBarcode | P1-defineName 收敛 | -| app/model/stock_store.js | StockStore | stock_store | StockStore | P1-defineName 收敛 | -| app/model/stock_unit.js | StockUnit | wms_stock_unit | StockUnit | P1-defineName 收敛 | -| app/model/stock_warehouse.js | StockWarehouse | stock_warehouse | StockWarehouse | P1-defineName 收敛 | -| app/model/storage.js | Storage | wms_storage | Storage | P1-defineName 收敛 | -| app/model/store_warehouse.js | StoreWarehouse | store_warehouse | StoreWarehouse | P1-defineName 收敛 | -| app/model/store.js | Store | store | Store | P1-defineName 收敛 | - -## 4. 保持不动或低优先级处理项 - -| 文件 | 当前运行时 key | 当前 defineName | 建议 | 说明 | -| --- | --- | --- | --- | --- | -| app/model/order_delivery_factory.js | OrderDeliveryFactory | 动态 tableName | 保持不动 | 工厂模型,不参与静态 defineName 收敛 | -| app/model/order_items_factory.js | OrderItemsFactory | 动态 tableName | 保持不动 | 工厂模型,不参与静态 defineName 收敛 | -| app/model/print_record.js | PrintRecord | PrintRecord | 保持不动 | 已符合标准 | -| app/model/store_join.js | StoreJoin | StoreJoin | 保持不动 | 已符合标准 | - -## 5. P2: alias 收敛候选 - -| 位置 | 当前 alias | 建议 alias | 变更级别 | 说明 | -| --- | --- | --- | --- | --- | -| app/model/account.js | accountStoreRoles | accountStoreEmployees | P2-alias 收敛 | 当前关联对象实际为 AccountStoreEmployee | -| app/model/account_platform_active.js | accountStoreEmployee | accountStoreEmployee | 保持 | 当前 alias 合理,问题在 service 调用侧 | -| app/model/account_store_employee.js | employeeRole | employeeRoles | P2-alias 收敛 | hasMany 建议使用复数 | -| app/model/store.js | accountStoreEmployee | accountStoreEmployees | P2-alias 收敛 | hasMany 建议使用复数 | -| app/model/role.js | employeeRole | employeeRoles | P2-alias 收敛 | hasMany 建议使用复数 | - -## 6. 执行顺序建议 - -1. 先修 P0 调用错误,保证所有 ctx.model / app.model 均能拿到正确对象。 -2. 再做 P1 defineName 收敛,限定在显式声明了 tableName 的静态模型。 -3. 最后做 P2 alias 收敛,并与阶段 4 的关联核对同步执行。 \ No newline at end of file diff --git a/temp/docs/rename_impact_report.md b/temp/docs/rename_impact_report.md deleted file mode 100644 index 2d7824c..0000000 --- a/temp/docs/rename_impact_report.md +++ /dev/null @@ -1,168 +0,0 @@ -# Model 命名影响评估报告 - -更新时间: 2026-03-22 -范围: - -- app/model/*.js -- app/service/**/*.js -- app/controller/**/*.js - -## 1. 结论摘要 - -当前命名问题分成两层: - -1. 真正会影响运行的调用错误。 -2. 还能运行,但会持续制造理解成本和后续重构风险的 defineName/alias 漂移。 - -本轮确认的最高优先级风险有 3 个: - -### 1.1 AccountStoreRole 是仓库内不存在的运行时 key - -- 代码大量使用 ctx.model.AccountStoreRole。 -- app/model 下没有对应的 account_store_role.js。 -- 现有 schema 已落到 AccountStoreEmployee + EmployeeRole 两层关系。 -- 这不是单纯命名风格问题,而是“旧关系名残留到新模型结构”的兼容断层。 - -### 1.2 动态分表工厂存在一组错误调用名 - -- 仓库主流调用是 OrderDeliveryFactory / OrderItemsFactory。 -- 仅 app/service/apiMethods/test.js 仍在使用 WmsOrderDeliveryFactory / WmsOrderItemsFactory。 -- 这会导致测试/调试路径与正式业务路径使用不同的模型入口。 - -### 1.3 alias 已经切到 employee 语义,但 service 仍按 role 语义取值 - -- app/model/account_platform_active.js 中 alias 是 accountStoreEmployee。 -- 但 app/service/systems/account_platform.js 仍按 accountStoreRole 进行 include 和结果读取。 -- 这说明 model 层与 service 层对同一关系的语义认知已经分叉。 - -## 2. 关键证据 - -### 2.1 不存在的 model key: AccountStoreRole - -受影响位置: - -- app/service/systems/account_platform.js:21 -- app/service/systems/account_platform.js:102 -- app/service/systems/account_platform.js:169 -- app/service/systems/account_platform.js:226 -- app/service/systems/account_platform.js:321 -- app/service/systems/store.js:464 -- app/service/systems/store.js:679 -- app/service/systems/store.js:690 -- app/model/role.js:151 - -现状说明: - -- app/model/account_store_employee.js:6 定义的是 AccountStoreEmployee,表为 wms_account_store_employee。 -- app/model/account_store_employee.js:82-99 说明当前关系是 AccountStoreEmployee -> EmployeeRole -> Role。 -- app/model/account_platform_active.js:79-86 已把激活关系关联到 AccountStoreEmployee。 - -风险判断: - -- 如果继续沿用 AccountStoreRole,后续关联收敛会同时破坏 include、字段读取、缓存结构与返回结构。 -- 该问题必须在正式改 defineName 之前先做数据关系确认。 - -建议动作: - -1. 先确认“平台激活”想绑定的是员工记录还是员工-角色明细。 -2. 若绑定员工记录,则将 AccountStoreRole 全量替换为 AccountStoreEmployee,并改造 role 读取路径。 -3. 若绑定员工-角色明细,则需要新增独立模型,而不是继续使用幽灵 key。 - -### 2.2 动态工厂 key 调用漂移 - -正常调用样本: - -- app/service/systemMethods/order.js:22-23 -- app/service/systems/delivery_order.js:14 -- app/service/systems/delivery_order.js:311 -- app/service/qimenMethods/deliveryorder.js:7-8 - -异常调用样本: - -- app/service/apiMethods/test.js:50 -- app/service/apiMethods/test.js:51 - -风险判断: - -- 正式链路与调试链路的 model 入口不一致,后续如果只修主链路,测试链路会继续漂移。 -- 这是低成本高收益修复项,应优先纳入第一批代码修正。 - -建议动作: - -1. 将 WmsOrderDeliveryFactory 改为 OrderDeliveryFactory。 -2. 将 WmsOrderItemsFactory 改为 OrderItemsFactory。 -3. 回归验证动态表 current/history 获取能力是否一致。 - -### 2.3 alias 与语义漂移 - -证据位置: - -- app/model/account.js:139 使用 alias accountStoreRoles,但实际模型是 AccountStoreEmployee。 -- app/model/account_platform_active.js:84 使用 alias accountStoreEmployee。 -- app/model/account_store_employee.js:95 使用 hasMany(EmployeeRole, { as: 'employeeRole' })。 -- app/model/role.js:171 使用 hasMany(EmployeeRole, { as: 'employeeRole' })。 -- app/service/systems/account_platform.js:102-136 仍按 accountStoreRole 读取嵌套字段。 - -风险判断: - -- 当前 alias 命名混合了“员工关系”和“角色关系”两种语义。 -- 若不先统一语义,后续只做名字替换会把问题从命名层转移到数据层。 - -建议动作: - -1. 阶段 4 先梳理 employee、role、store 三者的真实关系。 -2. hasMany alias 收敛为复数形式,如 employeeRoles、accountStoreEmployees。 -3. service 层返回结构与 include 路径同步改名,避免只改 model 不改消费方。 - -## 3. defineName 漂移影响 - -以下问题当前通常不会直接导致运行失败,但会持续造成阅读成本与重构误判: - -| 文件 | 证据 | 当前情况 | 风险 | -| --- | --- | --- | --- | -| app/model/platform_setting.js | :7 | defineName 为 platform_setting,运行时 key 为 PlatformSetting | 阅读时容易误以为 key 与 defineName 同名 | -| app/model/qimen_app.js | :6 | defineName 为 qimen_app,运行时 key 为 QimenApp | service 调用与模型定义风格分裂 | -| app/model/qimen_log.js | :8 | defineName 为 qimen_log,运行时 key 为 QimenLog | 日志模型定位成本高 | -| app/model/account_store_employee.js | :6 | defineName 为 wms_account_store_employee,运行时 key 为 AccountStoreEmployee | 将表名语义混入模型名 | -| app/model/stock_barcode.js | :6 | defineName 为 stock_barcodes,运行时 key 为 StockBarcode | 单复数与 key 同时漂移 | -| app/model/prohibited_type.js | :6 | defineName 为 prohibitedType,运行时 key 为 ProhibitedType | lowerCamelCase 与 PascalCase 混用 | -| app/model/print_stations.js | :5 | defineName 为 print_stations,运行时 key 为 PrintStations | 虽可运行,但风格不统一 | - -影响判断: - -- 新增 include、调试 SQL、追踪关联时,很容易把 defineName、key、tableName 当成同一件事。 -- 后续如果继续新增 snake_case defineName,会放大维护面。 - -建议动作: - -1. 先完成 P0 调用修复。 -2. 再按 model_rename_map.md 分批将 defineName 收敛到 PascalCase。 -3. 每次改 defineName 后,回归关联加载与 SQL 日志输出,确认未引入隐式副作用。 - -## 4. 稳定项与例外项 - -以下命名虽然不完全理想,但当前不建议仅因风格而改动: - -- app/model/print_record.js - - defineName 已为 PrintRecord,运行时 key 与之保持一致。 -- app/model/store_join.js - - defineName 已为 StoreJoin,当前问题主要不在命名层。 -- app/model/order_delivery_factory.js - - 工厂模型对外 key 稳定,重点是调用方统一。 -- app/model/order_items_factory.js - - 工厂模型对外 key 稳定,重点是调用方统一。 -- app/model/print_stations.js - - 文件名和表名均为复数,当前更适合先保留为历史兼容项,不单独改文件名。 - -## 5. 推荐执行顺序 - -1. 第一批: 修正不存在的运行时 key 和错误工厂调用名。 -2. 第二批: 收敛静态模型 defineName,保持 tableName 不变。 -3. 第三批: 在关联核对完成后统一 alias 和 include 路径。 -4. 第四批: 更新测试、README、modelList.md、关联清单等文档。 - -## 6. 对后续阶段的输入 - -- 阶段 4 需要重点核对 AccountPlatformActive、AccountStoreEmployee、EmployeeRole、Role、Store 的外键与 include 结构。 -- 阶段 5 需要顺带清理与命名漂移绑定的死代码、调试日志和旧语义变量名。 -- 阶段 6 验证时必须覆盖平台激活、仓库角色分配、动态订单分表、打印链路四类高风险场景。 \ No newline at end of file diff --git a/temp/docs/role_permission_fk_data_cleanup_plan.md b/temp/docs/role_permission_fk_data_cleanup_plan.md deleted file mode 100644 index c4c404a..0000000 --- a/temp/docs/role_permission_fk_data_cleanup_plan.md +++ /dev/null @@ -1,104 +0,0 @@ -# role_permission_fk_data_cleanup_plan - -更新时间: 2026-03-23 -目标: 清理 role/permission 相关孤儿数据,解除 `20260323103000-align-role-permission-fk.js` 执行阻塞。 - -## 1. 审计现状 - -- `wms_role_permission.permission_id` 孤儿记录: 4 条(id: 2, 3, 6, 10) -- `wms_role.store_id` 非法哨兵值: 3 条(store_id = 0) -- 字段类型差异: - - `wms_permission.id`: `int(11)` - - `wms_role_permission.permission_id`: `bigint(20) unsigned`(迁移已处理为对齐) - -## 2. 执行顺序 - -1. 备份孤儿数据 -2. 删除 `wms_role_permission` 孤儿行 -3. 规范 `wms_role.store_id = 0` 为 `NULL`(仅对可空字段) -4. 复核计数 -5. 执行迁移 `20260323103000-align-role-permission-fk.js` - -## 3. 推荐 SQL(先在测试环境执行) - -### 3.1 备份 role_permission 孤儿行 - -```sql -CREATE TABLE IF NOT EXISTS wms_role_permission_orphan_backup_20260323 AS -SELECT rp.* -FROM wms_role_permission rp -LEFT JOIN wms_permission p ON p.id = rp.permission_id -WHERE p.id IS NULL; -``` - -### 3.2 删除 role_permission 孤儿行 - -```sql -DELETE rp -FROM wms_role_permission rp -LEFT JOIN wms_permission p ON p.id = rp.permission_id -WHERE p.id IS NULL; -``` - -### 3.3 规范 role.store_id 哨兵值 - -```sql -UPDATE wms_role -SET store_id = NULL -WHERE store_id = 0; -``` - -### 3.4 复核 - -```sql -SELECT 'rp_perm_orphan' AS metric, COUNT(*) AS cnt -FROM wms_role_permission rp -LEFT JOIN wms_permission p ON p.id = rp.permission_id -WHERE p.id IS NULL -UNION ALL -SELECT 'role_store_zero' AS metric, COUNT(*) AS cnt -FROM wms_role -WHERE store_id = 0; -``` - -## 4. 回滚思路 - -- 若删除孤儿行后需要回滚,可从备份表恢复: - -```sql -INSERT INTO wms_role_permission (id, role_id, permission_id, created_at) -SELECT id, role_id, permission_id, created_at -FROM wms_role_permission_orphan_backup_20260323; -``` - -- `wms_role.store_id` 从 `0 -> NULL` 回滚需结合业务语义,不建议盲目全量回写 `0`。 - -## 5. 交付门禁 - -清洗和迁移完成后,执行: - -1. `node .\\script\\method-output-regression.cjs compare` -2. `node .\\script\\tmp-generate-method-regression-test.cjs` -3. `npx egg-bin test temp/generated-tests/system.method-output.generated.test.js` -4. `npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js` - -通过标准: - -- compare: mismatch=0 -- 回归测试: 全部通过 - -## 6. 执行记录(2026-03-23) - -- 备份执行结果: - - `wms_role_permission_orphan_backup_20260323`: 4 行 - - `wms_role_store_zero_backup_20260323`: 3 行 -- 清洗执行结果: - - role_permission 孤儿删除: 4 行 - - role.store_id=0 -> NULL: 3 行 -- 迁移执行结果: - - `wms_role_permission.permission_id` 已对齐为 `int(11)` - - 外键 `fk_wms_role_permission_permission` 已生效 - - SequelizeMeta 已登记 `20260323103000-align-role-permission-fk.js` -- 门禁结果: - - method-output compare: mismatch=0 - - generated regression + smoke: 14 passing diff --git a/temp/docs/rollback_plan.md b/temp/docs/rollback_plan.md deleted file mode 100644 index 4dc84b4..0000000 --- a/temp/docs/rollback_plan.md +++ /dev/null @@ -1,49 +0,0 @@ -# rollback_plan - -更新时间: 2026-03-22 - -## 1. 通用回滚规则 - -- 所有新增 migration 必须提供 down。 -- 对现网已有表,down 不应默认直接 drop 整表。 -- 优先回滚新增字段、索引、约束,避免误删存量数据。 -- 涉及数据回填的 migration,必须保留影响范围快照或备份。 - -## 2. 分类型回滚策略 - -### 建表 migration - -- 新环境可使用 dropTable 回滚。 -- 现网已有表不建议通过 down 删除,应改为“标记基线 + 停止继续执行”。 - -### 加字段 migration - -- down 使用 dropColumn。 -- 执行前需确认字段不被线上代码强依赖。 - -### 索引 migration - -- down 使用 removeIndex。 -- 若为性能补丁索引,回滚前需评估查询退化风险。 - -### 视图 migration - -- down 使用 drop view。 -- 回滚前确认是否有查询依赖视图。 - -### 动态分表策略 migration - -- 只回滚策略与模板,不批量 drop 已创建的仓库动态表。 -- 已存在分表应通过单独治理,不纳入统一 down 删除范围。 - -## 3. 当前优先风险 - -- 未进入 SequelizeMeta 的 migration 不能按常规 down 处理,必须先确认其是否已在数据库中手工生效。 -- order_delivery/order_items 主表与动态表结构存在差异,回滚时必须区分主表与动态表。 -- 日志类表通常已有存量数据,回滚需要避免整表删除。 - -## 4. 建议执行前准备 - -- 每批 migration 执行前导出目标表结构快照。 -- 若涉及数据变更,先做行数统计与影响范围确认。 -- 为每批次准备单独回滚脚本,不依赖临场拼写 SQL。 diff --git a/temp/docs/root-md-usage-report.md b/temp/docs/root-md-usage-report.md deleted file mode 100644 index 2c505d2..0000000 --- a/temp/docs/root-md-usage-report.md +++ /dev/null @@ -1,93 +0,0 @@ -# 根目录 Markdown 使用方与清理结果 - -生成时间: 2026-03-24 - -## 保留在根目录 - -- `README.md` - - 使用方: `model_todo.txt` - - 动作: 保留(项目入口文档) -- `AI_TOOLBOX.md` - - 使用方: `README.md` - - 动作: 保留(AI 协作工具箱) -- `AI_METHOD_ROUTING.md` - - 使用方: `AI_TOOLBOX.md`, `README.md`, `script/tmp-update-ai-method-routing.cjs` - - 动作: 保留(路由映射主文档) - -## 迁移到 temp/docs(需要保留) - -- `METHOD_OUTPUT_REGRESSION_20260322.md` - - 原使用方: `README.md` - - 新路径: `temp/docs/METHOD_OUTPUT_REGRESSION_20260322.md` -- `SERVICE_API_CHANGE_AUDIT_20260322.md` - - 原使用方: `model_todo.txt` - - 新路径: `temp/docs/SERVICE_API_CHANGE_AUDIT_20260322.md` -- `association_eager_loading_n_plus_one_guideline.md` - - 原使用方: `association_validation_checklist.md`, `model_todo.txt`, `SERVICE_API_CHANGE_AUDIT_20260322.md` - - 新路径: `temp/docs/association_eager_loading_n_plus_one_guideline.md` -- `association_fix_plan.md` - - 原使用方: `model_todo.txt` - - 新路径: `temp/docs/association_fix_plan.md` -- `association_fk_consistency_report.md` - - 原使用方: `association_validation_checklist.md`, `model_todo.txt`, `SERVICE_API_CHANGE_AUDIT_20260322.md`, `temp/audit-association-fk.cjs` - - 新路径: `temp/docs/association_fk_consistency_report.md` -- `association_validation_checklist.md` - - 原使用方: `model_todo.txt`, `SERVICE_API_CHANGE_AUDIT_20260322.md` - - 新路径: `temp/docs/association_validation_checklist.md` -- `migration_execution_plan.md` - - 原使用方: `model_todo.txt` - - 新路径: `temp/docs/migration_execution_plan.md` -- `migration_gap_list.md` - - 原使用方: `model_todo.txt` - - 新路径: `temp/docs/migration_gap_list.md` -- `modelList.md` - - 原使用方: `model_todo.txt`, `README.md`, `rename_impact_report.md` - - 新路径: `temp/docs/modelList.md` -- `model_association_inventory.md` - - 原使用方: `model_todo.txt` - - 新路径: `temp/docs/model_association_inventory.md` -- `model_boundary_rules.md` - - 原使用方: `model_cleanup_list.md`, `model_todo.txt`, `script/model-boundary-check.cjs` - - 新路径: `temp/docs/model_boundary_rules.md` -- `model_cleanup_list.md` - - 原使用方: `model_todo.txt`, `SERVICE_API_CHANGE_AUDIT_20260322.md` - - 新路径: `temp/docs/model_cleanup_list.md` -- `model_inventory.md` - - 原使用方: `model_rename_map.md`, `model_todo.txt` - - 新路径: `temp/docs/model_inventory.md` -- `model_naming_standard.md` - - 原使用方: `model_todo.txt` - - 新路径: `temp/docs/model_naming_standard.md` -- `model_rename_map.md` - - 原使用方: `model_todo.txt`, `rename_impact_report.md` - - 新路径: `temp/docs/model_rename_map.md` -- `rename_impact_report.md` - - 原使用方: `model_todo.txt` - - 新路径: `temp/docs/rename_impact_report.md` -- `role_permission_fk_data_cleanup_plan.md` - - 原使用方: `model_todo.txt` - - 新路径: `temp/docs/role_permission_fk_data_cleanup_plan.md` -- `rollback_plan.md` - - 原使用方: `model_todo.txt` - - 新路径: `temp/docs/rollback_plan.md` -- `schema_model_gap_report.md` - - 原使用方: `model_todo.txt` - - 新路径: `temp/docs/schema_model_gap_report.md` -- `table_schema_inventory.md` - - 原使用方: `model_todo.txt` - - 新路径: `temp/docs/table_schema_inventory.md` - -## 已清理(不需要) - -- `tmp-order-schema-workflow.md` - - 原使用方: 无 - - 动作: 已从根目录删除(历史临时流程文档) - -## 引用更新范围 - -- `README.md` -- `model_todo.txt` -- `script/model-boundary-check.cjs` -- `temp/audit-association-fk.cjs` - -所有上述文件中的旧根目录引用已替换为 `temp/docs/*` 新路径。 diff --git a/temp/docs/schema_model_gap_report.md b/temp/docs/schema_model_gap_report.md deleted file mode 100644 index 36a7e4b..0000000 --- a/temp/docs/schema_model_gap_report.md +++ /dev/null @@ -1,98 +0,0 @@ -# schema_model_gap_report - -Updated: 2026-03-22 - -## Scope - -- DB source: information_schema.TABLES / COLUMNS / STATISTICS -- Model source: app/model/*.js (tableName option) - -## Count - -- Model files: 45 -- Model with tableName: 43 -- DB tables: 68 -- modelOnly table count: 0 -- dbOnly table count: 25 - -## modelOnly tables - -- none - -## dbOnly tables - -- SequelizeMeta -- wms_account_login_log -- wms_api_log -- wms_embargo_policies -- wms_express -- wms_express_print_record -- wms_express_setting -- wms_order_delivery_100000 -- wms_order_delivery_1000028 -- wms_order_express -- wms_order_express_print_data -- wms_order_items_100000 -- wms_order_items_1000028 -- wms_order_operation -- wms_order_operation_log -- wms_order_picking -- wms_picking_strategy -- wms_platform_print_config -- wms_print_batch -- wms_print_log -- wms_printer_config -- wms_system_config -- wms_system_log -- wms_wave_batch -- wms_wave_operation_log - -## Model mapping snapshot - -| key | file | defineName | tableName | -| --- | --- | --- | --- | -| account | app/model/account.js | account | wms_account | -| account_platform_active | app/model/account_platform_active.js | account_platform_active | wms_account_platform_active | -| account_store_employee | app/model/account_store_employee.js | wms_account_store_employee | wms_account_store_employee | -| api_app | app/model/api_app.js | api_app | wms_api_app | -| employee_role | app/model/employee_role.js | employee_role | wms_employee_role | -| entry_items | app/model/entry_items.js | wms_entry_items | wms_entry_items | -| entry_order | app/model/entry_order.js | wms_entry_order | wms_entry_order | -| fast_where | app/model/fast_where.js | fast_where | wms_fast_where | -| file | app/model/file.js | wms_file | wms_file | -| file_reference | app/model/file_reference.js | wms_file_reference | wms_file_reference | -| i18n_key | app/model/i18n_key.js | wms_i18n_key | wms_i18n_keys | -| i18n_translation | app/model/i18n_translation.js | wms_i18n_translation | wms_i18n_translations | -| interface_type | app/model/interface_type.js | interface_type | wms_interface_type | -| location_space | app/model/location_space.js | wms_location_space | wms_location_space | -| location_type | app/model/location_type.js | location_type | wms_location_type | -| location_zone | app/model/location_zone.js | wms_location_zone | wms_location_zone | -| operation_log | app/model/operation_log.js | operation_log | wms_operation_log | -| order_delivery | app/model/order_delivery.js | order_delivery | wms_order_delivery | -| order_delivery_factory | app/model/order_delivery_factory.js | - | - | -| order_items | app/model/order_items.js | wms_order_items | wms_order_items | -| order_items_factory | app/model/order_items_factory.js | - | - | -| permission | app/model/permission.js | permission | wms_permission | -| platform | app/model/platform.js | platform | wms_platform | -| platform_setting | app/model/platform_setting.js | platform_setting | wms_platfrom_setting | -| print_computer | app/model/print_computer.js | print_computer | wms_print_computer | -| print_item | app/model/print_item.js | print_item | wms_print_items | -| print_record | app/model/print_record.js | PrintRecord | wms_print_record | -| print_station_express | app/model/print_station_express.js | print_station_express | wms_print_station_express | -| print_stations | app/model/print_stations.js | print_stations | wms_print_stations | -| print_template | app/model/print_template.js | print_template | wms_print_template | -| prohibited_type | app/model/prohibited_type.js | prohibitedType | wms_prohibited_type | -| qimen_app | app/model/qimen_app.js | qimen_app | wms_qimen_apps | -| qimen_log | app/model/qimen_log.js | qimen_log | wms_qimen_log | -| receiving | app/model/receiving.js | wms_receiving | wms_receiving | -| receiving_detail | app/model/receiving_detail.js | wms_receiving_detail | wms_receiving_detail | -| role | app/model/role.js | role | wms_role | -| role_permission | app/model/role_permission.js | role_permission | wms_role_permission | -| stock_barcode | app/model/stock_barcode.js | stock_barcodes | wms_stock_barcodes | -| stock_store | app/model/stock_store.js | stock_store | wms_stock_store | -| stock_unit | app/model/stock_unit.js | wms_stock_unit | wms_stock_unit | -| stock_warehouse | app/model/stock_warehouse.js | stock_warehouse | wms_stock_warehouse | -| storage | app/model/storage.js | wms_storage | wms_storage | -| store | app/model/store.js | store | wms_store | -| store_join | app/model/store_join.js | StoreJoin | wms_store_join | -| store_warehouse | app/model/store_warehouse.js | store_warehouse | wms_store_warehouse | diff --git a/temp/docs/table_schema_inventory.md b/temp/docs/table_schema_inventory.md deleted file mode 100644 index 9d9fe42..0000000 --- a/temp/docs/table_schema_inventory.md +++ /dev/null @@ -1,85 +0,0 @@ -# table_schema_inventory - -Updated: 2026-03-22 -Database: wms -Object count: 70 - -## Summary - -- Tables: 68 -- Views: 2 - -## Objects - -| object | type | engine | collation | rows | columns | pk_cols | auto_inc | index_count | -| --- | --- | --- | --- | ---: | ---: | ---: | ---: | ---: | -| SequelizeMeta | TABLE | InnoDB | utf8_unicode_ci | 7 | 1 | 1 | 0 | 2 | -| vw_warehouse_quota | VIEW | - | - | - | 5 | 0 | 0 | 0 | -| v_pick_space | VIEW | - | - | - | 44 | 0 | 0 | 0 | -| wms_account | TABLE | InnoDB | utf8mb4_general_ci | 2 | 13 | 1 | 1 | 5 | -| wms_account_login_log | TABLE | InnoDB | utf8mb4_general_ci | 108 | 7 | 1 | 1 | 2 | -| wms_account_platform_active | TABLE | InnoDB | utf8mb4_general_ci | 3 | 5 | 2 | 0 | 5 | -| wms_account_store_employee | TABLE | InnoDB | utf8mb4_general_ci | 5 | 8 | 1 | 1 | 5 | -| wms_api_app | TABLE | InnoDB | utf8mb4_unicode_ci | 4 | 22 | 1 | 1 | 6 | -| wms_api_log | TABLE | InnoDB | utf8mb4_general_ci | 421 | 10 | 1 | 1 | 1 | -| wms_embargo_policies | TABLE | InnoDB | utf8mb4_unicode_ci | 0 | 13 | 1 | 1 | 5 | -| wms_employee_role | TABLE | InnoDB | utf8mb4_general_ci | 4 | 3 | 1 | 1 | 4 | -| wms_entry_items | TABLE | InnoDB | utf8mb4_general_ci | 2 | 12 | 1 | 1 | 3 | -| wms_entry_order | TABLE | InnoDB | utf8mb4_unicode_ci | 5 | 28 | 1 | 1 | 10 | -| wms_express | TABLE | InnoDB | utf8mb4_general_ci | 0 | 2 | 1 | 0 | 1 | -| wms_express_print_record | TABLE | InnoDB | utf8mb4_general_ci | 0 | 31 | 1 | 1 | 13 | -| wms_express_setting | TABLE | InnoDB | utf8mb4_general_ci | 0 | 4 | 1 | 1 | 3 | -| wms_fast_where | TABLE | InnoDB | utf8mb4_general_ci | 38 | 9 | 1 | 1 | 1 | -| wms_file | TABLE | InnoDB | utf8mb4_unicode_ci | 5806 | 20 | 1 | 1 | 8 | -| wms_file_reference | TABLE | InnoDB | utf8mb4_unicode_ci | 8299 | 8 | 1 | 1 | 5 | -| wms_i18n_keys | TABLE | InnoDB | utf8mb4_general_ci | 182 | 10 | 1 | 1 | 4 | -| wms_i18n_translations | TABLE | InnoDB | utf8mb4_general_ci | 421 | 11 | 1 | 1 | 5 | -| wms_interface_type | TABLE | InnoDB | utf8mb4_unicode_ci | 2 | 9 | 1 | 1 | 2 | -| wms_location_space | TABLE | InnoDB | utf8mb4_general_ci | 1898 | 38 | 1 | 1 | 13 | -| wms_location_type | TABLE | InnoDB | utf8mb4_general_ci | 5 | 10 | 1 | 1 | 3 | -| wms_location_zone | TABLE | InnoDB | utf8mb4_general_ci | 20 | 30 | 1 | 1 | 10 | -| wms_operation_log | TABLE | InnoDB | utf8mb4_general_ci | 2856 | 12 | 1 | 1 | 8 | -| wms_order_delivery | TABLE | InnoDB | utf8mb4_general_ci | 0 | 54 | 1 | 1 | 4 | -| wms_order_delivery_100000 | TABLE | InnoDB | utf8mb4_general_ci | 10 | 72 | 1 | 1 | 9 | -| wms_order_delivery_1000028 | TABLE | InnoDB | utf8mb4_general_ci | 0 | 72 | 1 | 1 | 9 | -| wms_order_express | TABLE | InnoDB | utf8mb4_general_ci | 0 | 13 | 1 | 1 | 2 | -| wms_order_express_print_data | TABLE | InnoDB | utf8mb4_general_ci | 0 | 6 | 1 | 1 | 2 | -| wms_order_items | TABLE | InnoDB | utf8mb4_general_ci | 0 | 15 | 1 | 1 | 2 | -| wms_order_items_100000 | TABLE | InnoDB | utf8mb4_unicode_ci | 11 | 18 | 1 | 1 | 9 | -| wms_order_items_1000028 | TABLE | InnoDB | utf8mb4_unicode_ci | 0 | 18 | 1 | 1 | 9 | -| wms_order_operation | TABLE | InnoDB | utf8mb4_general_ci | 0 | 1 | 1 | 1 | 1 | -| wms_order_operation_log | TABLE | InnoDB | utf8mb4_general_ci | 0 | 15 | 1 | 1 | 6 | -| wms_order_picking | TABLE | InnoDB | utf8mb4_general_ci | 0 | 1 | 1 | 1 | 1 | -| wms_permission | TABLE | InnoDB | utf8mb4_general_ci | 40 | 15 | 1 | 1 | 4 | -| wms_picking_strategy | TABLE | InnoDB | utf8mb4_unicode_ci | 0 | 25 | 1 | 1 | 3 | -| wms_platform | TABLE | InnoDB | utf8mb4_general_ci | 13 | 3 | 1 | 0 | 1 | -| wms_platform_print_config | TABLE | InnoDB | utf8mb4_general_ci | 7 | 12 | 1 | 1 | 3 | -| wms_platfrom_setting | TABLE | InnoDB | utf8mb4_general_ci | 0 | 4 | 1 | 1 | 4 | -| wms_printer_config | TABLE | InnoDB | utf8mb4_general_ci | 0 | 11 | 1 | 1 | 4 | -| wms_print_batch | TABLE | InnoDB | utf8mb4_general_ci | 0 | 16 | 1 | 1 | 6 | -| wms_print_computer | TABLE | InnoDB | utf8mb4_general_ci | 0 | 4 | 1 | 1 | 1 | -| wms_print_items | TABLE | InnoDB | utf8mb4_general_ci | 39 | 24 | 1 | 1 | 5 | -| wms_print_log | TABLE | InnoDB | utf8mb4_general_ci | 0 | 12 | 1 | 1 | 5 | -| wms_print_record | TABLE | InnoDB | utf8mb4_general_ci | 277 | 13 | 1 | 1 | 6 | -| wms_print_stations | TABLE | InnoDB | utf8mb4_unicode_ci | 3 | 11 | 1 | 1 | 7 | -| wms_print_station_express | TABLE | InnoDB | utf8mb4_unicode_ci | 0 | 10 | 1 | 1 | 5 | -| wms_print_template | TABLE | InnoDB | utf8mb4_general_ci | 4 | 15 | 1 | 1 | 4 | -| wms_prohibited_type | TABLE | InnoDB | utf8mb4_unicode_ci | 13 | 9 | 1 | 1 | 4 | -| wms_qimen_apps | TABLE | InnoDB | utf8mb4_general_ci | 27 | 4 | 1 | 1 | 2 | -| wms_qimen_log | TABLE | InnoDB | utf8mb4_general_ci | 27756 | 14 | 1 | 1 | 1 | -| wms_receiving | TABLE | InnoDB | utf8mb4_unicode_ci | 43 | 25 | 1 | 1 | 9 | -| wms_receiving_detail | TABLE | InnoDB | utf8mb4_unicode_ci | 38 | 26 | 1 | 1 | 8 | -| wms_role | TABLE | InnoDB | utf8mb4_general_ci | 5 | 13 | 1 | 1 | 6 | -| wms_role_permission | TABLE | InnoDB | utf8mb4_general_ci | 72 | 4 | 1 | 1 | 4 | -| wms_stock_barcodes | TABLE | InnoDB | utf8mb4_unicode_ci | 25992 | 6 | 1 | 1 | 3 | -| wms_stock_store | TABLE | InnoDB | utf8mb4_unicode_ci | 472 | 34 | 1 | 1 | 11 | -| wms_stock_unit | TABLE | InnoDB | utf8mb4_general_ci | 11 | 4 | 1 | 1 | 3 | -| wms_stock_warehouse | TABLE | InnoDB | utf8mb4_unicode_ci | 25718 | 41 | 1 | 1 | 6 | -| wms_storage | TABLE | InnoDB | utf8mb4_unicode_ci | 0 | 20 | 1 | 1 | 8 | -| wms_store | TABLE | InnoDB | utf8mb4_unicode_ci | 121 | 20 | 1 | 1 | 5 | -| wms_store_join | TABLE | InnoDB | utf8mb4_unicode_ci | 4 | 14 | 1 | 1 | 7 | -| wms_store_warehouse | TABLE | InnoDB | utf8mb4_general_ci | 119 | 21 | 1 | 1 | 8 | -| wms_system_config | TABLE | InnoDB | utf8mb4_general_ci | 1 | 5 | 1 | 1 | 1 | -| wms_system_log | TABLE | InnoDB | utf8mb4_general_ci | 4591 | 14 | 1 | 1 | 2 | -| wms_wave_batch | TABLE | InnoDB | utf8mb4_general_ci | 0 | 20 | 1 | 1 | 5 | -| wms_wave_operation_log | TABLE | InnoDB | utf8mb4_general_ci | 0 | 11 | 1 | 1 | 5 | From b9e94f103556464d1d198830a81616d4cda4d991 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Wed, 25 Mar 2026 18:12:04 +0800 Subject: [PATCH 010/550] =?UTF-8?q?chore:=20=E6=8F=90=E4=BA=A4=E5=BD=93?= =?UTF-8?q?=E5=89=8D=E5=B7=A5=E4=BD=9C=E5=8C=BA=E6=94=B9=E5=8A=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 12 + app/lib/query_condition_parser.js | 288 +++++++++++ .../systemMethods/setting/printTemplate.js | 50 +- app/service/systemMethods/stock.js | 361 ------------- app/service/systemMethods/stock/combo.js | 1 + app/service/systemMethods/stock/store.js | 1 + app/service/systemMethods/stock/warehouse.js | 472 +++++++++++++++++ .../systemMethods/storage/receiving.js | 90 ++++ app/service/systems/auth/user.js | 288 +++++++++-- app/service/systems/setting/print_template.js | 126 ++++- app/service/systems/stock_store.js | 419 +++++---------- app/service/systems/storage/receiving.js | 62 ++- docs/stock-stockWarehouse-query-rules.md | 167 ++++++ methods/system.json | 476 +++++++++++++++--- stock.todo | 112 +++++ .../system.setting.printTemplate.test.js | 155 ++++++ .../system.stock.warehouse.namespaced.test.js | 84 ++++ .../system.storage.receiving.test.js | 230 +++++++++ ...ck_store.stockWarehouse.conditions.test.js | 320 ++++++++++++ 19 files changed, 2933 insertions(+), 781 deletions(-) create mode 100644 app/lib/query_condition_parser.js delete mode 100644 app/service/systemMethods/stock.js create mode 100644 app/service/systemMethods/stock/combo.js create mode 100644 app/service/systemMethods/stock/store.js create mode 100644 app/service/systemMethods/stock/warehouse.js create mode 100644 docs/stock-stockWarehouse-query-rules.md create mode 100644 stock.todo create mode 100644 test/app/controller/system.setting.printTemplate.test.js create mode 100644 test/app/controller/system.stock.warehouse.namespaced.test.js create mode 100644 test/app/controller/system.storage.receiving.test.js create mode 100644 test/app/service/systems/stock_store.stockWarehouse.conditions.test.js diff --git a/README.md b/README.md index c433c54..94f9f59 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,7 @@ - AI项目协作工具箱:`AI_TOOLBOX.md` - Method 路由映射说明:`AI_METHOD_ROUTING.md` +- stock.warehouse.list 前端查询规则:`docs/stock-stockWarehouse-query-rules.md` - system 接口文档源:`methods/system.json` - qimen 接口文档源:`methods/qimen.json` - 日报:`day.log` @@ -38,6 +39,7 @@ - `README.md`:项目入口文档,提供整体说明与规范入口。 - `AI_TOOLBOX.md`:AI/开发协作操作手册,包含脚本与工作流。 - `AI_METHOD_ROUTING.md`:接口入口与 method 到代码文件的映射。 +- `docs/stock-stockWarehouse-query-rules.md`:stock.warehouse.list 的 where 构造规则与失败返回说明。 - `methods/system.json`:system 接口定义(headers、groups、params、response、errors)。 - `methods/qimen.json`:qimen 接口定义(按奇门协议组织)。 - `day.log`:每日工作留痕。 @@ -198,6 +200,16 @@ npx egg-bin test temp/generated-tests/system.method-output.generated.test.js - 全局业务 Header(如 `platform`、`project`)设置 - 方法级在线 POST 调试 +### user.getBindWechatCode 调用约定(微信绑定码) + +- 默认行为:立即返回当前状态(不会长等待,适合页面初始化)。 +- 显式长轮询:仅当 body 传 `waitForChange=true`(或兼容字段 `longPoll=true`)时启用。 +- 长轮询时长:后端单次最长等待 60 秒;60 秒内状态变化会立即返回。 +- 超时返回:若 60 秒内无变化,返回当前状态并提示超时。 +- 初始化强制立即返回:可传 `init=true`(兼容 `isInit=true`、`firstLoad=true`)。 +- 可选等待参数:`waitTimeoutMs`,后端自动封顶 60000。 +- 前端超时建议:HTTP 超时设置为 120000ms(2 分钟),覆盖网络抖动与重试开销。 + ## 接口响应规范(system) 更新时间:2026-03-22 diff --git a/app/lib/query_condition_parser.js b/app/lib/query_condition_parser.js new file mode 100644 index 0000000..72737d4 --- /dev/null +++ b/app/lib/query_condition_parser.js @@ -0,0 +1,288 @@ +'use strict'; + +function isPlainObject(value) { + return value && typeof value === 'object' && !Array.isArray(value); +} + +function isEmptyValue(value) { + if (value === undefined || value === null) { + return true; + } + + if (typeof value === 'string' && value.trim() === '') { + return true; + } + + if (Array.isArray(value) && value.length === 0) { + return true; + } + + return false; +} + +function normalizeDate(value) { + if (value === undefined || value === null) { + return value; + } + + if (typeof value === 'string') { + return value.trim(); + } + + if (value instanceof Date) { + if (isNaN(value.getTime())) return value; + return value.toISOString().slice(0, 19).replace('T', ' '); + } + + if (typeof value === 'number') { + const date = new Date(value); + if (isNaN(date.getTime())) return value; + return date.toISOString().slice(0, 19).replace('T', ' '); + } + + return value; +} + +function processConditionValue(value, type) { + if (value === undefined || value === null) { + return value; + } + + switch (type) { + case 'boolean': + if (value === true || value === 'true' || value === 'Y' || value === 'y') { + return 'Y'; + } + if (value === false || value === 'false' || value === 'N' || value === 'n') { + return 'N'; + } + return value; + + case 'date': + case 'daterange': + if (Array.isArray(value)) { + return value.map(v => normalizeDate(v)); + } + return normalizeDate(value); + + case 'number': { + const num = parseFloat(value); + return isNaN(num) ? value : num; + } + + case 'text': + if (Array.isArray(value)) { + return value.map(item => String(item).trim()).filter(Boolean); + } + return String(value).split(',').map(item => item.trim()).filter(Boolean); + + default: + return value; + } +} + +function buildSequelizeCondition(fieldKey, condition, app) { + if (!isPlainObject(condition)) { + return { ok: false, reason: 'condition 必须是对象' }; + } + + const { Sequelize } = app; + const { + operator = 'eq', value, type, + } = condition; + + const fieldName = condition.field || fieldKey; + const processedValue = processConditionValue(value, type); + const op = String(operator || 'eq').toLowerCase(); + + switch (op) { + case 'eq': + return { ok: true, condition: { [fieldName]: processedValue } }; + + case 'ne': + return { ok: true, condition: { [fieldName]: { [Sequelize.Op.ne]: processedValue } } }; + + case 'contains': + case 'like': + if (Array.isArray(processedValue) && processedValue.length > 0) { + return { + ok: true, + condition: { + [Sequelize.Op.or]: processedValue.map(val => ({ + [fieldName]: { + [Sequelize.Op.like]: `%${val}%`, + }, + })), + }, + }; + } + return { ok: true, condition: { [fieldName]: { [Sequelize.Op.like]: `%${processedValue}%` } } }; + + case 'startswith': + if (Array.isArray(processedValue) && processedValue.length > 0) { + return { + ok: true, + condition: { + [Sequelize.Op.or]: processedValue.map(val => ({ + [fieldName]: { + [Sequelize.Op.like]: `${val}%`, + }, + })), + }, + }; + } + return { ok: true, condition: { [fieldName]: { [Sequelize.Op.like]: `${processedValue}%` } } }; + + case 'endswith': + if (Array.isArray(processedValue) && processedValue.length > 0) { + return { + ok: true, + condition: { + [Sequelize.Op.or]: processedValue.map(val => ({ + [fieldName]: { + [Sequelize.Op.like]: `%${val}`, + }, + })), + }, + }; + } + return { ok: true, condition: { [fieldName]: { [Sequelize.Op.like]: `%${processedValue}` } } }; + + case 'gt': + return { ok: true, condition: { [fieldName]: { [Sequelize.Op.gt]: processedValue } } }; + + case 'lt': + return { ok: true, condition: { [fieldName]: { [Sequelize.Op.lt]: processedValue } } }; + + case 'ge': + return { ok: true, condition: { [fieldName]: { [Sequelize.Op.gte]: processedValue } } }; + + case 'le': + return { ok: true, condition: { [fieldName]: { [Sequelize.Op.lte]: processedValue } } }; + + case 'in': + if (!Array.isArray(processedValue)) { + return { ok: false, reason: `${fieldName} 的 in 操作符要求 value 为数组` }; + } + return { ok: true, condition: { [fieldName]: { [Sequelize.Op.in]: processedValue } } }; + + case 'notin': + if (!Array.isArray(processedValue)) { + return { ok: false, reason: `${fieldName} 的 notin 操作符要求 value 为数组` }; + } + return { ok: true, condition: { [fieldName]: { [Sequelize.Op.notIn]: processedValue } } }; + + case 'between': + if (!Array.isArray(processedValue) || processedValue.length !== 2) { + return { ok: false, reason: `${fieldName} 的 between 操作符要求 value 为长度为2的数组` }; + } + return { ok: true, condition: { [fieldName]: { [Sequelize.Op.between]: processedValue } } }; + + case 'notbetween': + if (!Array.isArray(processedValue) || processedValue.length !== 2) { + return { ok: false, reason: `${fieldName} 的 notbetween 操作符要求 value 为长度为2的数组` }; + } + return { ok: true, condition: { [fieldName]: { [Sequelize.Op.notBetween]: processedValue } } }; + + case 'isnull': + return { ok: true, condition: { [fieldName]: { [Sequelize.Op.is]: null } } }; + + case 'isnotnull': + return { ok: true, condition: { [fieldName]: { [Sequelize.Op.not]: null } } }; + + case 'regexp': + return { ok: true, condition: { [fieldName]: { [Sequelize.Op.regexp]: processedValue } } }; + + case 'notregexp': + return { ok: true, condition: { [fieldName]: { [Sequelize.Op.notRegexp]: processedValue } } }; + + default: + return { ok: true, condition: { [fieldName]: processedValue } }; + } +} + +function parseWhereConditions(options = {}) { + const { + where, + app, + specialFieldMap = {}, + } = options; + + if (where === undefined || where === null) { + return { + ok: true, + result: { + dynamicConditions: [], + bucketConditions: {}, + bucketFlags: {}, + rawConditionsByField: {}, + }, + }; + } + + if (!isPlainObject(where)) { + return { ok: false, reason: 'where 必须是对象' }; + } + + const dynamicConditions = []; + const bucketConditions = {}; + const bucketFlags = {}; + const rawConditionsByField = {}; + + for (const [ fieldKey, condition ] of Object.entries(where)) { + if (!isPlainObject(condition)) { + return { ok: false, reason: `字段 ${fieldKey} 条件必须是对象` }; + } + + if (isEmptyValue(condition.value)) { + continue; + } + + const mapped = specialFieldMap[fieldKey] || {}; + const normalizedCondition = { + ...condition, + }; + + if (mapped.field) { + normalizedCondition.field = mapped.field; + } + + const built = buildSequelizeCondition(fieldKey, normalizedCondition, app); + if (!built.ok) { + return { + ok: false, + reason: `字段 ${fieldKey} 解析失败: ${built.reason}`, + }; + } + + if (mapped.bucket) { + if (!bucketConditions[mapped.bucket]) { + bucketConditions[mapped.bucket] = []; + } + bucketConditions[mapped.bucket].push(built.condition); + bucketFlags[mapped.bucket] = true; + rawConditionsByField[fieldKey] = normalizedCondition; + continue; + } + + dynamicConditions.push(built.condition); + } + + return { + ok: true, + result: { + dynamicConditions, + bucketConditions, + bucketFlags, + rawConditionsByField, + }, + }; +} + +module.exports = { + isEmptyValue, + normalizeDate, + processConditionValue, + buildSequelizeCondition, + parseWhereConditions, +}; diff --git a/app/service/systemMethods/setting/printTemplate.js b/app/service/systemMethods/setting/printTemplate.js index fa99777..ebae470 100644 --- a/app/service/systemMethods/setting/printTemplate.js +++ b/app/service/systemMethods/setting/printTemplate.js @@ -6,9 +6,9 @@ class printTemplateService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'list,save,listTemplatesByType'; + const _noNeedRight = 'list,save,create,delete,listTemplatesByType'; const _noNeedLog = '*'; - const _noNeedAuth = 'list,save,listTemplatesByType'; + const _noNeedAuth = 'list,save,create,delete,listTemplatesByType'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } async list(data) { @@ -22,6 +22,52 @@ class printTemplateService extends MainService { const result = await service.systems.setting.printTemplate.save(data); return this.success('ok', result); } + async create(data) { + const { service } = this; + const { template_name, business_type, page_width, page_height } = data || {}; + + if (!template_name || String(template_name).trim() === '') { + return this.fail('template_name 参数不能为空', { code: 400 }); + } + if (!business_type || String(business_type).trim() === '') { + return this.fail('business_type 参数不能为空', { code: 400 }); + } + if (page_width === undefined || page_width === null || page_width === '') { + return this.fail('page_width 参数不能为空', { code: 400 }); + } + if (page_height === undefined || page_height === null || page_height === '') { + return this.fail('page_height 参数不能为空', { code: 400 }); + } + + try { + const result = await service.systems.setting.printTemplate.createTemplate(data); + return this.success('ok', result); + } catch (error) { + if (error.message === '同一业务类型和平台下已存在自定义模板') { + return this.fail(error.message, { code: 409 }); + } + return this.fail(error.message || '创建打印模板失败', { code: 500 }); + } + } + async delete(data) { + const { service } = this; + const { id } = data || {}; + const templateId = Number(id); + + if (!templateId || Number.isNaN(templateId)) { + return this.fail('id 参数不能为空', { code: 400 }); + } + + try { + const result = await service.systems.setting.printTemplate.deleteTemplate(templateId); + return this.success('ok', result); + } catch (error) { + if (error.message === '模板不存在或无权限') { + return this.fail(error.message, { code: 404 }); + } + return this.fail(error.message || '删除打印模板失败', { code: 500 }); + } + } async listTemplatesByType(data) { const { service } = this; console.log('接收到根据业务类型查询模板请求:', data); diff --git a/app/service/systemMethods/stock.js b/app/service/systemMethods/stock.js deleted file mode 100644 index 6473789..0000000 --- a/app/service/systemMethods/stock.js +++ /dev/null @@ -1,361 +0,0 @@ -'use strict'; - -const MainService = require('../main'); - -class indexService extends MainService { - constructor(ctx) { - super(ctx); - const _noNeedLogin = ''; - const _noNeedRight = 'fastWhereTree,stockWarehouse,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,getUnitList,createUnit,checkItemCodeUnique,deleteUnit,createProhibited,deleteProhibited,search'; - const _noNeedLog = 'fastWhereTree,stockWarehouse,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,checkItemCodeUnique,getUnitList,search'; - const _noNeedAuth = 'fastWhereTree,stockWarehouse,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,checkItemCodeUnique,getUnitList,search'; - this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); - } - async stockWarehouse(data) { - const { service } = this; - const { pagination, where } = data; - console.log('where', where); - const result = await service.systems.stockStore.getWarehouseStock(where, pagination); - return this.success('ok', result); - } - async getProhibitedType() { - const { service } = this; - const result = await service.systems.stockStore.getProhibitedType(); - return this.success('ok', { data: result, code: 200 }); - } - async getInfo(data) { - const { service } = this; - const result = await service.systems.stockStore.getInfo(data); - return this.success('ok', { data: result, code: 200 }); - } - async saveWarehouseStock(data) { - const { service } = this; - const result = await service.systems.stockStore.saveWarehouseStock(data); - return this.success('ok', { data: result, code: 200 }); - } - - async createWarehouseStock(data) { - const { service } = this; - const result = await service.systems.stockStore.createWarehouseStock(data); - return this.success('ok', { data: result, code: 200 }); - } - async getBarcodes(data) { - const { service } = this; - const result = await service.systems.stockStore.getBarcodes(data); - return this.success('ok', { data: result, code: 200 }); - } - async saveWarehouseStockBarcode(data) { - const { service } = this; - const result = await service.systems.stockStore.saveWarehouseStockBarcode(data); - return this.success('ok', { data: result, code: 200 }); - } - async getStoreStocks(data) { - const { service } = this; - const result = await service.systems.stockStore.getStoreStocks(data); - return this.success('ok', { data: result, code: 200 }); - } - async bindItem(data) { - const { service } = this; - try { - const result = await service.systems.stockStore.bindItem(data); - return this.success('绑定成功', { data: result, code: 200 }); - } catch (e) { - return this.success(e.message, { code: 200 }); - } - } - async unbindItem(data) { - const { service } = this; - try { - const result = await service.systems.stockStore.unbindItem(data); - return this.success('解绑成功', { data: result, code: 200 }); - } catch (e) { - return this.success(e.message, { code: 200 }); - } - } - async checkItemCodeUnique(data) { - const { ctx, service } = this; - const { id, item_code, store_id } = data; - console.log(data); - try { - if (!item_code || !store_id) { - return this.fail('参数错误'); - } - const data = await service.systems.stockStore.checkItemCodeUnique(id, item_code, store_id, ctx.user.store_id); - return this.success('获取成功', { data, code: 200 }); - } catch (error) { - return this.fail(error.message); - } - } - async queryStockLogs(data) { - console.log('请求'); - const { ctx } = this; - try { - const { service } = this; - data.warehouseId = ctx.user.store_id; - const result = await service.systems.operationLog.queryStockLogs(data); - return this.success('ok', { data: result, code: 200 }); - } catch (e) { - console.log(e); - return this.success(e.message, { code: 200 }); - } - } - - async handleBatchDelete(data) { - const { service } = this; - try { - const result = await service.systems.stockStore.handleBatchDelete(data); - return this.success(result.message, { data: result.data, code: result.code }); - } catch (e) { - console.log(e); - return this.success(e.message, { code: 200 }); - } - } - - async deleteUnit(data) { - const { service } = this; - try { - const result = await service.systems.stockStore.deleteUnit(data); - return this.success(result.message, { data: result.data, code: result.code }); - } catch (e) { - console.log(e); - return this.success(e.message, { code: 200 }); - } - } - - async deleteProhibited(data) { - const { service } = this; - try { - const result = await service.systems.stockStore.deleteProhibited(data); - return this.success(result.message, { data: result.data, code: result.code }); - } catch (e) { - console.log(e); - return this.success(e.message, { code: 200 }); - } - } - async handleBatchChange(data) { - const { service } = this; - try { - const result = await service.systems.stockStore.handleBatchChange(data); - return this.success(result.message, { data: result.data, code: result.code }); - } catch (e) { - console.log(e); - return this.success(e.message, { code: 405 }); - } - } - async getStockUnits() { - console.log('query_getStockUnits'); - const { ctx } = this; - const warehouse_id = ctx.user.store_id; - - try { - // 构建查询条件 - const where = { - [ctx.app.Sequelize.Op.or]: [ - { warehouse_id: null }, // 系统预设单位 - { warehouse_id }, // 本仓库的单位 - ], - }; - - const units = await ctx.model.StockUnit.findAll({ - where, - order: [ - [ 'warehouse_id', 'ASC' ], // 先显示系统预设单位(warehouse_id为null) - [ 'created_at', 'DESC' ], // 按创建时间倒序 - ], - }); - return this.success('ok', { data: units, code: 200 }); - } catch (error) { - console.log(error); - return this.fail(error.message); - } - } - async getUnitList() { - console.log('query_getUnitList'); - const { ctx } = this; - const warehouse_id = ctx.user.store_id; - - try { - // 构建查询条件 - const where = { - warehouse_id, - }; - - const units = await ctx.model.StockUnit.findAll({ - where, - order: [ - [ 'warehouse_id', 'ASC' ], // 先显示系统预设单位(warehouse_id为null) - [ 'created_at', 'DESC' ], // 按创建时间倒序 - ], - }); - return this.success('ok', { data: units, code: 200 }); - } catch (error) { - console.log(error); - return this.fail(error.message); - } - } - async createProhibited(data) { - console.log('createProhibited', data); - const { ctx } = this; - const warehouse_id = ctx.user.store_id || null; - const { name } = data; - - // 参数验证 - if (!name || name.trim() === '') { - ctx.body = { - code: 400, - message: '违禁品类型名称不能为空', - }; - return; - } - - const trimmedName = name.trim(); - - try { - // 1. 检查是否是系统预设单位(warehouse_id为null) - const systemUnit = await ctx.model.ProhibitedType.findOne({ - where: { - type_name: trimmedName, - warehouse_id: null, - }, - }); - - if (systemUnit) { - ctx.body = { - code: 400, - message: '该违禁品类型是系统预设,不允许添加', - }; - return; - } - - // 2. 检查当前仓库是否已存在相同名称的单位 - const existUnit = await ctx.model.ProhibitedType.findOne({ - where: { - type_name: trimmedName, - warehouse_id, - }, - }); - - if (existUnit) { - ctx.body = { - code: 400, - message: '该违禁品类型名称已存在', - }; - return; - } - - // 3. 创建单位 - const unit = await ctx.model.ProhibitedType.create({ - type_name: trimmedName, - warehouse_id, - }); - - // 4. 获取更新后的单位列表 - const where = {}; - if (warehouse_id) { - where[ctx.app.Sequelize.Op.or] = [ - { warehouse_id: null }, // 系统预设单位 - { warehouse_id }, // 当前仓库的单位 - ]; - } else { - where.warehouse_id = null; // 只显示系统预设单位 - } - - const units = await ctx.model.ProhibitedType.findAll({ - where, - order: [ - [ 'warehouse_id', 'ASC' ], // 先显示系统预设单位(warehouse_id为null) - [ 'created_at', 'DESC' ], // 按创建时间倒序 - ], - }); - return this.success('添加成功', { code: 200 }); - } catch (error) { - console.log(error); - return this.success('创建违禁品类型失败', { code: 405 }); - } - } - async createUnit() { - const { ctx } = this; - const warehouse_id = ctx.user.store_id || null; - const { name } = ctx.request.body; - - // 参数验证 - if (!name || name.trim() === '') { - ctx.body = { - code: 400, - message: '单位名称不能为空', - }; - return; - } - - const trimmedName = name.trim(); - - try { - // 1. 检查是否是系统预设单位(warehouse_id为null) - const systemUnit = await ctx.model.StockUnit.findOne({ - where: { - name: trimmedName, - warehouse_id: null, - }, - }); - - if (systemUnit) { - ctx.body = { - code: 400, - message: '该单位是系统预设单位,不允许添加', - }; - return; - } - - // 2. 检查当前仓库是否已存在相同名称的单位 - const existUnit = await ctx.model.StockUnit.findOne({ - where: { - name: trimmedName, - warehouse_id, - }, - }); - - if (existUnit) { - ctx.body = { - code: 400, - message: '该单位名称已存在', - }; - return; - } - - // 3. 创建单位 - const unit = await ctx.model.StockUnit.create({ - name: trimmedName, - warehouse_id, - }); - - // 4. 获取更新后的单位列表 - const where = {}; - if (warehouse_id) { - where[ctx.app.Sequelize.Op.or] = [ - { warehouse_id: null }, // 系统预设单位 - { warehouse_id }, // 当前仓库的单位 - ]; - } else { - where.warehouse_id = null; // 只显示系统预设单位 - } - - const units = await ctx.model.StockUnit.findAll({ - where, - order: [ - [ 'warehouse_id', 'ASC' ], // 先显示系统预设单位(warehouse_id为null) - [ 'created_at', 'DESC' ], // 按创建时间倒序 - ], - }); - return this.success('添加成功', { code: 200 }); - } catch (error) { - return this.success('创建库存单位失败', { code: 200 }); - } - } - - async search(data) { - const { service } = this; - const result = await service.systems.stockStore.search(data); - return this.success('ok', result); - } -} -module.exports = indexService; diff --git a/app/service/systemMethods/stock/combo.js b/app/service/systemMethods/stock/combo.js new file mode 100644 index 0000000..0b81363 --- /dev/null +++ b/app/service/systemMethods/stock/combo.js @@ -0,0 +1 @@ +//此处放组合商品明细的逻辑链路 \ No newline at end of file diff --git a/app/service/systemMethods/stock/store.js b/app/service/systemMethods/stock/store.js new file mode 100644 index 0000000..b73f5a2 --- /dev/null +++ b/app/service/systemMethods/stock/store.js @@ -0,0 +1 @@ +//此处放货主商品明细的逻辑链路 \ No newline at end of file diff --git a/app/service/systemMethods/stock/warehouse.js b/app/service/systemMethods/stock/warehouse.js new file mode 100644 index 0000000..87c2acb --- /dev/null +++ b/app/service/systemMethods/stock/warehouse.js @@ -0,0 +1,472 @@ +'use strict'; + +const MainService = require('../../main'); + +class WarehouseService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,getUnitList,createUnit,checkItemCodeUnique,deleteUnit,createProhibited,deleteProhibited,search'; + const _noNeedLog = 'list,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,checkItemCodeUnique,getUnitList,search'; + const _noNeedAuth = 'list,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,checkItemCodeUnique,getUnitList,search'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 仓库商品列表查询。 + * @param {Object} data 请求体 + * @param {Object} [data.pagination] 分页参数 + * @param {Object} [data.where] 筛选条件 + * @return {Promise} 统一成功包装响应 + */ + async list(data = {}) { + const { service } = this; + const { pagination, where } = data; + const result = await service.systems.stockStore.getWarehouseStock(where, pagination); + return this.success('ok', result); + } + + /** + * 查询违禁品类型列表(系统预设 + 当前仓库)。 + * @return {Promise} data 为违禁品类型数组 + */ + async getProhibitedType() { + const { service } = this; + const result = await service.systems.stockStore.getProhibitedType(); + return this.success('ok', { data: result, code: 200 }); + } + + /** + * 按商品条件获取仓库商品详情。 + * @param {Object} data 请求体(常见包含 id/item_code) + * @return {Promise} data 为单个商品详情对象 + */ + async getInfo(data) { + const { service } = this; + const result = await service.systems.stockStore.getInfo(data); + return this.success('ok', { data: result, code: 200 }); + } + + /** + * 更新仓库商品资料。 + * @param {Object} data 请求体(含商品主键与可编辑字段) + * @return {Promise} data 为更新结果 + */ + async saveWarehouseStock(data) { + const { service } = this; + const result = await service.systems.stockStore.saveWarehouseStock(data); + return this.success('ok', { data: result, code: 200 }); + } + + /** + * 新建仓库商品资料。 + * @param {Object} data 请求体(必填字段见 stockStore 校验) + * @return {Promise} data 为新建结果 + */ + async createWarehouseStock(data) { + const { service } = this; + const result = await service.systems.stockStore.createWarehouseStock(data); + return this.success('ok', { data: result, code: 200 }); + } + + /** + * 查询商品条码列表。 + * @param {Object} data 请求体(支持分页与关键字) + * @return {Promise} data 为条码分页结果 + */ + async getBarcodes(data) { + const { service } = this; + const result = await service.systems.stockStore.getBarcodes(data); + return this.success('ok', { data: result, code: 200 }); + } + + /** + * 保存商品条码信息。 + * @param {Object} data 请求体(包含 stock_id 与条码字段) + * @return {Promise} data 为保存结果 + */ + async saveWarehouseStockBarcode(data) { + const { service } = this; + const result = await service.systems.stockStore.saveWarehouseStockBarcode(data); + return this.success('ok', { data: result, code: 200 }); + } + + /** + * 查询仓库与货主商品关联列表。 + * @param {Object} data 请求体(支持筛选/分页) + * @return {Promise} data 为关联分页结果 + */ + async getStoreStocks(data) { + const { service } = this; + const result = await service.systems.stockStore.getStoreStocks(data); + return this.success('ok', { data: result, code: 200 }); + } + + /** + * 绑定货主商品。 + * @param {Object} data 请求体(关联关系参数) + * @return {Promise} 成功或失败均返回 success 包装,message 给出结果 + */ + async bindItem(data) { + const { service } = this; + try { + const result = await service.systems.stockStore.bindItem(data); + return this.success('绑定成功', { data: result, code: 200 }); + } catch (e) { + return this.success(e.message, { code: 200 }); + } + } + + /** + * 解绑货主商品。 + * @param {Object} data 请求体(关联关系参数) + * @return {Promise} 成功或失败均返回 success 包装,message 给出结果 + */ + async unbindItem(data) { + const { service } = this; + try { + const result = await service.systems.stockStore.unbindItem(data); + return this.success('解绑成功', { data: result, code: 200 }); + } catch (e) { + return this.success(e.message, { code: 200 }); + } + } + + /** + * 校验商品编码唯一性。 + * @param {Object} data 请求体 + * @param {number} [data.id] 商品ID(编辑场景) + * @param {string} data.item_code 商品编码 + * @param {number} data.store_id 货主ID + * @return {Promise} data 为布尔或冲突详情 + */ + async checkItemCodeUnique(data) { + const { ctx, service } = this; + const { id, item_code, store_id } = data; + console.log(data); + try { + if (!item_code || !store_id) { + return this.fail('参数错误'); + } + const result = await service.systems.stockStore.checkItemCodeUnique(id, item_code, store_id, ctx.user.store_id); + return this.success('获取成功', { data: result, code: 200 }); + } catch (error) { + return this.fail(error.message); + } + } + + /** + * 查询库存操作日志。 + * @param {Object} data 请求体(会自动注入当前 warehouseId) + * @return {Promise} data 为日志分页结果 + */ + async queryStockLogs(data) { + console.log('请求'); + const { ctx } = this; + try { + const { service } = this; + data.warehouseId = ctx.user.store_id; + const result = await service.systems.operationLog.queryStockLogs(data); + return this.success('ok', { data: result, code: 200 }); + } catch (e) { + console.log(e); + return this.success(e.message, { code: 200 }); + } + } + + /** + * 批量删除仓库商品资料(软删除)。 + * @param {Object} data 请求体(含 ids) + * @return {Promise} data 为删除结果,message 为业务提示 + */ + async handleBatchDelete(data) { + const { service } = this; + try { + const result = await service.systems.stockStore.handleBatchDelete(data); + return this.success(result.message, { data: result.data, code: result.code }); + } catch (e) { + console.log(e); + return this.success(e.message, { code: 200 }); + } + } + + /** + * 删除库存单位。 + * @param {Object} data 请求体(含单位ID) + * @return {Promise} data 为删除结果,message 为业务提示 + */ + async deleteUnit(data) { + const { service } = this; + try { + const result = await service.systems.stockStore.deleteUnit(data); + return this.success(result.message, { data: result.data, code: result.code }); + } catch (e) { + console.log(e); + return this.success(e.message, { code: 200 }); + } + } + + /** + * 删除违禁品类型。 + * @param {Object} data 请求体(含类型ID) + * @return {Promise} data 为删除结果,message 为业务提示 + */ + async deleteProhibited(data) { + const { service } = this; + try { + const result = await service.systems.stockStore.deleteProhibited(data); + return this.success(result.message, { data: result.data, code: result.code }); + } catch (e) { + console.log(e); + return this.success(e.message, { code: 200 }); + } + } + + /** + * 批量修改商品资料字段。 + * @param {Object} data 请求体(含 ids/method/value) + * @return {Promise} data 为修改结果,message 为业务提示 + */ + async handleBatchChange(data) { + const { service } = this; + try { + const result = await service.systems.stockStore.handleBatchChange(data); + return this.success(result.message, { data: result.data, code: result.code }); + } catch (e) { + console.log(e); + return this.success(e.message, { code: 405 }); + } + } + + /** + * 查询可用库存单位(系统预设 + 仓库自定义)。 + * @return {Promise} data 为单位数组 + */ + async getStockUnits() { + console.log('query_getStockUnits'); + const { ctx } = this; + const warehouse_id = ctx.user.store_id; + + try { + const where = { + [ctx.app.Sequelize.Op.or]: [ + { warehouse_id: null }, + { warehouse_id }, + ], + }; + + const units = await ctx.model.StockUnit.findAll({ + where, + order: [ + [ 'warehouse_id', 'ASC' ], + [ 'created_at', 'DESC' ], + ], + }); + return this.success('ok', { data: units, code: 200 }); + } catch (error) { + console.log(error); + return this.fail(error.message); + } + } + + /** + * 查询当前仓库自定义单位列表。 + * @return {Promise} data 为单位数组 + */ + async getUnitList() { + console.log('query_getUnitList'); + const { ctx } = this; + const warehouse_id = ctx.user.store_id; + + try { + const where = { + warehouse_id, + }; + + const units = await ctx.model.StockUnit.findAll({ + where, + order: [ + [ 'warehouse_id', 'ASC' ], + [ 'created_at', 'DESC' ], + ], + }); + return this.success('ok', { data: units, code: 200 }); + } catch (error) { + console.log(error); + return this.fail(error.message); + } + } + + /** + * 新增违禁品类型。 + * @param {Object} data 请求体 + * @param {string} data.name 违禁品类型名称 + * @return {Promise} 成功返回 success;参数校验失败时直接写入 ctx.body + */ + async createProhibited(data) { + console.log('createProhibited', data); + const { ctx } = this; + const warehouse_id = ctx.user.store_id || null; + const { name } = data; + + if (!name || name.trim() === '') { + ctx.body = { + code: 400, + message: '违禁品类型名称不能为空', + }; + return; + } + + const trimmedName = name.trim(); + + try { + const systemUnit = await ctx.model.ProhibitedType.findOne({ + where: { + type_name: trimmedName, + warehouse_id: null, + }, + }); + + if (systemUnit) { + ctx.body = { + code: 400, + message: '该违禁品类型是系统预设,不允许添加', + }; + return; + } + + const existUnit = await ctx.model.ProhibitedType.findOne({ + where: { + type_name: trimmedName, + warehouse_id, + }, + }); + + if (existUnit) { + ctx.body = { + code: 400, + message: '该违禁品类型名称已存在', + }; + return; + } + + await ctx.model.ProhibitedType.create({ + type_name: trimmedName, + warehouse_id, + }); + + const where = {}; + if (warehouse_id) { + where[ctx.app.Sequelize.Op.or] = [ + { warehouse_id: null }, + { warehouse_id }, + ]; + } else { + where.warehouse_id = null; + } + + await ctx.model.ProhibitedType.findAll({ + where, + order: [ + [ 'warehouse_id', 'ASC' ], + [ 'created_at', 'DESC' ], + ], + }); + return this.success('添加成功', { code: 200 }); + } catch (error) { + console.log(error); + return this.success('创建违禁品类型失败', { code: 405 }); + } + } + + /** + * 新增库存单位。 + * @return {Promise} 成功返回 success;参数校验失败时直接写入 ctx.body + */ + async createUnit() { + const { ctx } = this; + const warehouse_id = ctx.user.store_id || null; + const { name } = ctx.request.body; + + if (!name || name.trim() === '') { + ctx.body = { + code: 400, + message: '单位名称不能为空', + }; + return; + } + + const trimmedName = name.trim(); + + try { + const systemUnit = await ctx.model.StockUnit.findOne({ + where: { + name: trimmedName, + warehouse_id: null, + }, + }); + + if (systemUnit) { + ctx.body = { + code: 400, + message: '该单位是系统预设单位,不允许添加', + }; + return; + } + + const existUnit = await ctx.model.StockUnit.findOne({ + where: { + name: trimmedName, + warehouse_id, + }, + }); + + if (existUnit) { + ctx.body = { + code: 400, + message: '该单位名称已存在', + }; + return; + } + + await ctx.model.StockUnit.create({ + name: trimmedName, + warehouse_id, + }); + + const where = {}; + if (warehouse_id) { + where[ctx.app.Sequelize.Op.or] = [ + { warehouse_id: null }, + { warehouse_id }, + ]; + } else { + where.warehouse_id = null; + } + + await ctx.model.StockUnit.findAll({ + where, + order: [ + [ 'warehouse_id', 'ASC' ], + [ 'created_at', 'DESC' ], + ], + }); + return this.success('添加成功', { code: 200 }); + } catch (error) { + return this.success('创建库存单位失败', { code: 200 }); + } + } + + /** + * 快捷搜索仓库商品。 + * @param {Object} data 请求体(含 keyword) + * @return {Promise} data 为搜索结果数组 + */ + async search(data) { + const { service } = this; + const result = await service.systems.stockStore.search(data); + return this.success('ok', result); + } +} + +module.exports = WarehouseService; \ No newline at end of file diff --git a/app/service/systemMethods/storage/receiving.js b/app/service/systemMethods/storage/receiving.js index b16fbe9..f91ef63 100644 --- a/app/service/systemMethods/storage/receiving.js +++ b/app/service/systemMethods/storage/receiving.js @@ -11,6 +11,14 @@ class configService extends MainService { const _noNeedAuth = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } + + /** + * 收货单列表查询(system method 包装层)。 + * @param {Object} data 请求体 + * @param {Object} [data.pagination] 分页参数 + * @param {Object} [data.where] 筛选条件 + * @return {Promise} 统一成功包装响应 + */ async getReceivingList(data) { const { service } = this; const { pagination, where } = data; @@ -19,63 +27,145 @@ class configService extends MainService { const result = await service.systems.storage.receiving.getReceivingList(where, pagination); return this.success('ok', result); } + + /** + * 收货单详情查询(分页返回明细)。 + * @param {Object} data 请求体 + * @param {number} data.id 收货单ID + * @param {Object} data.pagination 明细分页参数 + * @return {Promise} 统一成功包装响应 + */ async getReceivingDetail(data) { const { service } = this; const result = await service.systems.storage.receiving.getReceivingDetail(data); return this.success('ok', result); } + + /** + * 批量作废收货单。 + * @param {Object} data 请求体 + * @param {number[]} data.ids 收货单ID数组 + * @return {Promise} 统一成功包装响应 + */ async batchCancelReceiving(data){ const { service } = this; const result = await service.systems.storage.receiving.batchCancelReceiving(data); return this.success('ok', result); } + + /** + * 创建收货单。 + * @param {Object} data 请求体 + * @return {Promise} 统一成功包装响应 + */ async create(data) { const { service } = this; const result = await service.systems.storage.receiving.create(data); return this.success('创建失败', result); } + + /** + * 添加收货商品(当前依赖底层 addItem 实现)。 + * @param {Object} data 请求体 + * @param {number} data.id 收货单ID + * @param {Object} data.item 商品信息 + * @return {Promise} 统一成功包装响应 + */ async addItem(data) { const { service } = this; const { id, item } = data; const result = await service.systems.storage.receiving.addItem(id, item); return this.success('ok', result); } + + /** + * 删除收货商品(当前依赖底层 removeItem 实现)。 + * @param {Object} data 请求体 + * @param {number} data.id 收货单ID + * @param {number} data.item_id 商品明细ID + * @return {Promise} 统一成功包装响应 + */ async removeItem(data) { const { service } = this; const { id, item_id } = data; const result = await service.systems.storage.receiving.removeItem(id, item_id); return this.success('ok', result); } + + /** + * 保存收货单(兼容接口)。 + * @param {Object} data 请求体 + * @return {Promise} 统一成功包装响应 + */ async saveReceiving(data) { const { service } = this; const result = await service.systems.storage.receiving.saveReceiving(data); return this.success('ok', result); } + + /** + * 查询收货单完整信息(含明细与图片)。 + * @param {Object} data 请求体 + * @param {number} data.id 收货单ID + * @return {Promise} 统一成功包装响应 + */ async get(data) { const { service } = this; const result = await service.systems.storage.receiving.get(data); return this.success('ok', result); } + + /** + * 新增一条收货明细(默认空模板)。 + * @param {Object} data 请求体 + * @return {Promise} 统一成功包装响应 + */ async addDetail(data) { const { service } = this; const result = await service.systems.storage.receiving.addDetail(data); return this.success('ok', result); } + + /** + * 删除收货明细。 + * @param {Object} data 请求体 + * @return {Promise} 统一成功包装响应 + */ async deleteDetail(data) { const { service } = this; const result = await service.systems.storage.receiving.deleteDetail(data); return this.success('ok', result); } + + /** + * 修改收货明细字段。 + * @param {Object} data 请求体 + * @return {Promise} 统一成功包装响应 + */ async detailChange(data) { const { service } = this; const result = await service.systems.storage.receiving.detailChange(data); return this.success('ok', result); } + + /** + * 作废收货单(单条)。 + * @param {Object} data 请求体 + * @return {Promise} 统一成功包装响应 + */ async cancel(data) { const { service } = this; const result = await service.systems.storage.receiving.invalid(data); return this.success('ok', result); } + + /** + * 完成收货单并触发入库处理。 + * @param {Object} data 请求体 + * @param {number} data.id 收货单ID + * @param {string} [data.remark] 完成备注 + * @return {Promise} 统一成功包装响应 + */ async completeReceiving(data) { const { service } = this; const result = await service.systems.storage.receiving.completeReceiving(data); diff --git a/app/service/systems/auth/user.js b/app/service/systems/auth/user.js index 6cf4756..848d1ff 100644 --- a/app/service/systems/auth/user.js +++ b/app/service/systems/auth/user.js @@ -7,6 +7,8 @@ const WECHAT_BIND_CACHE_PREFIX = 'user:wechat:bind:'; const WECHAT_BIND_CODE_CACHE_PREFIX = 'user:wechat:bind:code:'; const WECHAT_BIND_CACHE_TTL_SECONDS = 600; const WECHAT_BIND_RECHECK_INTERVAL_MS = 5000; +const WECHAT_BIND_EVENT_CHANNEL_PREFIX = 'user:wechat:bind:event:'; +const WECHAT_BIND_LONG_POLL_TIMEOUT_MS = 60000; class UserService extends Service { constructor(ctx) { @@ -99,6 +101,210 @@ class UserService extends Service { return rows[0]; } + getWechatBindEventChannel(accountId) { + return `${WECHAT_BIND_EVENT_CHANNEL_PREFIX}${accountId}`; + } + + getWechatLongPollTimeoutMs(rawTimeoutMs) { + const timeoutMs = Number(rawTimeoutMs); + if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) { + return WECHAT_BIND_LONG_POLL_TIMEOUT_MS; + } + return Math.min(timeoutMs, WECHAT_BIND_LONG_POLL_TIMEOUT_MS); + } + + shouldUseWechatBindLongPoll(data = {}, state = null) { + if (!state || state.status === 'bound') { + return false; + } + if (data.forceRefresh) { + return false; + } + if (data.isInit === true || data.init === true || data.firstLoad === true) { + return false; + } + + const explicitEnable = data.longPoll === true || data.waitForChange === true; + return explicitEnable; + } + + async publishWechatBindEvent(accountId, payload = {}) { + const { app } = this; + if (!accountId) { + return; + } + + const cacheRedis = app.redis && app.redis.get ? app.redis.get('cache') : null; + if (!cacheRedis) { + return; + } + + const channel = this.getWechatBindEventChannel(accountId); + const eventData = { + account_id: accountId, + event_at: new Date().toISOString(), + ...payload, + }; + + try { + await cacheRedis.publish(channel, JSON.stringify(eventData)); + } catch (error) { + app.coreLogger.warn(`发布微信绑定事件失败: ${error.message}`); + } + } + + async waitForWechatBindEvent(accountId, timeoutMs = WECHAT_BIND_LONG_POLL_TIMEOUT_MS) { + const { app } = this; + const cacheRedis = app.redis && app.redis.get ? app.redis.get('cache') : null; + if (!cacheRedis || !accountId || typeof cacheRedis.duplicate !== 'function') { + return { + timed_out: true, + reason: 'redis_not_available', + }; + } + + const channel = this.getWechatBindEventChannel(accountId); + const waitMs = this.getWechatLongPollTimeoutMs(timeoutMs); + const subscriber = cacheRedis.duplicate(); + + return await new Promise(resolve => { + let settled = false; + let timer = null; + + const cleanup = () => { + subscriber.removeListener('message', onMessage); + subscriber.removeListener('error', onError); + Promise.resolve(subscriber.unsubscribe(channel)).catch(() => null).finally(() => { + if (typeof subscriber.quit === 'function') { + Promise.resolve(subscriber.quit()).catch(() => { + if (typeof subscriber.disconnect === 'function') { + subscriber.disconnect(); + } + }); + return; + } + if (typeof subscriber.disconnect === 'function') { + subscriber.disconnect(); + } + }); + }; + + const finalize = result => { + if (settled) { + return; + } + settled = true; + if (timer) { + clearTimeout(timer); + } + cleanup(); + resolve(result); + }; + + const onMessage = (messageChannel, message) => { + if (messageChannel !== channel) { + return; + } + let eventData = null; + try { + eventData = message ? JSON.parse(message) : null; + } catch (error) { + eventData = { raw: message }; + } + finalize({ + timed_out: false, + reason: 'event', + event: eventData, + }); + }; + + const onError = error => { + app.coreLogger.warn(`订阅微信绑定事件失败: ${error.message}`); + finalize({ + timed_out: true, + reason: 'subscribe_error', + }); + }; + + timer = setTimeout(() => { + finalize({ + timed_out: true, + reason: 'timeout', + }); + }, waitMs); + + subscriber.on('message', onMessage); + subscriber.on('error', onError); + + Promise.resolve(subscriber.subscribe(channel)).catch(error => { + app.coreLogger.warn(`订阅微信绑定频道失败: ${error.message}`); + finalize({ + timed_out: true, + reason: 'subscribe_failed', + }); + }); + }); + } + + async refreshWechatBindState(accountId, cachedState = null) { + const now = Date.now(); + const cacheKey = this.getWechatBindCacheKey(accountId); + const ye4sBinding = await this.findYe4sBindingByAccountId(accountId); + + if (ye4sBinding) { + const dbCode = typeof ye4sBinding.tmp_code === 'string' ? ye4sBinding.tmp_code.trim() : ''; + const bindState = { + account_id: accountId, + status: 'bound', + code: dbCode || (cachedState && cachedState.code) || this.createWechatBindCode(), + updated_at: new Date().toISOString(), + next_db_check_at: now + WECHAT_BIND_RECHECK_INTERVAL_MS, + ye4s_user_id: ye4sBinding.id || null, + }; + + await Promise.all([ + this.setWechatBindCache(cacheKey, bindState, WECHAT_BIND_CACHE_TTL_SECONDS), + this.setWechatBindCodeCache(bindState.code, bindState, WECHAT_BIND_CACHE_TTL_SECONDS), + ]); + + const hasChanged = !cachedState || cachedState.status !== 'bound' || cachedState.code !== bindState.code; + if (hasChanged) { + await this.publishWechatBindEvent(accountId, { + status: 'bound', + code: bindState.code, + source: 'db', + }); + } + + return { + state: bindState, + source: 'db', + message: '账号已绑定微信', + }; + } + + const code = (cachedState && cachedState.code) || this.createWechatBindCode(); + const pendingState = { + account_id: accountId, + status: 'pending', + code, + updated_at: new Date().toISOString(), + next_db_check_at: now + WECHAT_BIND_RECHECK_INTERVAL_MS, + ye4s_user_id: null, + }; + + await Promise.all([ + this.setWechatBindCache(cacheKey, pendingState, WECHAT_BIND_CACHE_TTL_SECONDS), + this.setWechatBindCodeCache(pendingState.code, pendingState, WECHAT_BIND_CACHE_TTL_SECONDS), + ]); + + return { + state: pendingState, + source: code === (cachedState && cachedState.code) ? 'cache-refresh' : 'generated', + message: '账号未绑定,已生成绑定码', + }; + } + /** * 用户登录(重构版) * @param {string} username - 用户名/手机号/邮箱 @@ -256,6 +462,7 @@ class UserService extends Service { const cacheKey = this.getWechatBindCacheKey(accountId); const forceRefresh = !!data.forceRefresh; const now = Date.now(); + const waitTimeoutMs = this.getWechatLongPollTimeoutMs(data.waitTimeoutMs); let cachedState = null; try { @@ -266,57 +473,55 @@ class UserService extends Service { if (cachedState && !forceRefresh) { const nextCheckAt = Number(cachedState.next_db_check_at || 0); - if (nextCheckAt > now) { + let refreshedState = null; + if (nextCheckAt <= now) { + refreshedState = await this.refreshWechatBindState(accountId, cachedState); + cachedState = refreshedState.state; + } + + if (this.shouldUseWechatBindLongPoll(data, cachedState)) { + const waitResult = await this.waitForWechatBindEvent(accountId, waitTimeoutMs); + try { + cachedState = await this.app.getCacheAsync(cacheKey); + } catch (cacheErr) { + app.coreLogger.warn(`读取微信绑定缓存失败: ${cacheErr.message}`); + } + + const nextState = await this.refreshWechatBindState(accountId, cachedState); + const timeoutMessage = waitResult.timed_out ? '等待绑定状态变化超时,返回当前状态' : nextState.message; + return { success: true, code: 200, - data: this.formatBindWechatData(cachedState, 'cache'), - message: '获取绑定码成功(缓存)', + data: this.formatBindWechatData(nextState.state, nextState.source), + message: timeoutMessage, }; } - } - const ye4sBinding = await this.findYe4sBindingByAccountId(accountId); - if (ye4sBinding) { - const dbCode = typeof ye4sBinding.tmp_code === 'string' ? ye4sBinding.tmp_code.trim() : ''; - const bindState = { - account_id: accountId, - status: 'bound', - code: dbCode || (cachedState && cachedState.code) || this.createWechatBindCode(), - updated_at: new Date().toISOString(), - next_db_check_at: now + WECHAT_BIND_RECHECK_INTERVAL_MS, - ye4s_user_id: ye4sBinding.id || null, - }; - - await this.setWechatBindCache(cacheKey, bindState, WECHAT_BIND_CACHE_TTL_SECONDS); - await this.setWechatBindCodeCache(bindState.code, bindState, WECHAT_BIND_CACHE_TTL_SECONDS); + if (refreshedState) { + return { + success: true, + code: 200, + data: this.formatBindWechatData(refreshedState.state, refreshedState.source), + message: refreshedState.message, + }; + } return { success: true, code: 200, - data: this.formatBindWechatData(bindState, 'db'), - message: '账号已绑定微信', + data: this.formatBindWechatData(cachedState, 'cache'), + message: '获取绑定码成功(缓存)', }; } - const code = (cachedState && cachedState.code) || this.createWechatBindCode(); - const pendingState = { - account_id: accountId, - status: 'pending', - code, - updated_at: new Date().toISOString(), - next_db_check_at: now + WECHAT_BIND_RECHECK_INTERVAL_MS, - ye4s_user_id: null, - }; - - await this.setWechatBindCache(cacheKey, pendingState, WECHAT_BIND_CACHE_TTL_SECONDS); - await this.setWechatBindCodeCache(pendingState.code, pendingState, WECHAT_BIND_CACHE_TTL_SECONDS); + const refreshed = await this.refreshWechatBindState(accountId, cachedState); return { success: true, code: 200, - data: this.formatBindWechatData(pendingState, code === (cachedState && cachedState.code) ? 'cache-refresh' : 'generated'), - message: '账号未绑定,已生成绑定码', + data: this.formatBindWechatData(refreshed.state, refreshed.source), + message: refreshed.message, }; } catch (error) { app.coreLogger.error(`获取微信绑定码失败: ${error.message}`); @@ -395,8 +600,15 @@ class UserService extends Service { next_db_check_at: Date.now() + WECHAT_BIND_RECHECK_INTERVAL_MS, ye4s_user_id: ye4sUser.id || null, }; - await this.setWechatBindCodeCache(code, boundState, WECHAT_BIND_CACHE_TTL_SECONDS); - await this.setWechatBindCache(this.getWechatBindCacheKey(wmsAccountId), boundState, WECHAT_BIND_CACHE_TTL_SECONDS); + await Promise.all([ + this.setWechatBindCodeCache(code, boundState, WECHAT_BIND_CACHE_TTL_SECONDS), + this.setWechatBindCache(this.getWechatBindCacheKey(wmsAccountId), boundState, WECHAT_BIND_CACHE_TTL_SECONDS), + ]); + await this.publishWechatBindEvent(wmsAccountId, { + status: 'bound', + code, + source: 'api', + }); return { success: true, @@ -486,6 +698,10 @@ class UserService extends Service { await this.setWechatBindCodeCache(cachedState.code, null, 1); } await this.setWechatBindCache(cacheKey, null, 1); + await this.publishWechatBindEvent(accountId, { + status: 'unbound', + source: 'unbind', + }); return { success: true, diff --git a/app/service/systems/setting/print_template.js b/app/service/systems/setting/print_template.js index e64dad8..acccc3b 100644 --- a/app/service/systems/setting/print_template.js +++ b/app/service/systems/setting/print_template.js @@ -169,7 +169,131 @@ class PrintTemplateService extends Service { ctx.logger.error('保存打印模板失败:', error); throw new Error('保存打印模板失败'); } - }/** + } + + async createTemplate(data = {}) { + const { ctx } = this; + const warehouseId = ctx.user.store_id; + const now = new Date(); + const { + template_name, + business_type, + page_width, + page_height, + template_content = [], + is_default = false, + } = data; + const platform = 'default'; + const template_type = 'CUSTOM'; + const template_url = ''; + + const existingTemplate = await ctx.model.PrintTemplate.findOne({ + where: { + business_type, + platform, + template_type, + warehouse_id: warehouseId, + }, + order: [[ 'id', 'DESC' ]], + }); + + if (existingTemplate) { + if (existingTemplate.status === 'ACTIVE') { + throw new Error('同一业务类型和平台下已存在自定义模板'); + } + + await existingTemplate.update({ + template_name, + page_width, + page_height, + template_content, + template_url, + is_default, + status: 'ACTIVE', + delete_at: null, + update_at: now, + }); + + return { + message: '模板创建成功', + code: 200, + data: { + id: existingTemplate.id, + }, + }; + } + + let created; + try { + created = await ctx.model.PrintTemplate.create({ + template_name, + business_type, + page_width, + page_height, + template_content, + platform, + template_type, + template_url, + is_default, + warehouse_id: warehouseId, + status: 'ACTIVE', + create_at: now, + update_at: now, + delete_at: null, + }, { + validate: false, + }); + } catch (error) { + if (error?.name === 'SequelizeUniqueConstraintError') { + throw new Error('同一业务类型和平台下已存在自定义模板'); + } + const details = Array.isArray(error?.errors) + ? error.errors.map(item => `${item.path || 'unknown'}:${item.message}`).join(';') + : ''; + const errMsg = [ error?.name, error?.message, details ].filter(Boolean).join(' | '); + throw new Error(errMsg || '模板创建失败'); + } + + return { + message: '模板创建成功', + code: 200, + data: { + id: created.id, + }, + }; + } + + async deleteTemplate(id) { + const { ctx } = this; + const warehouseId = ctx.user.store_id; + const template = await ctx.model.PrintTemplate.findOne({ + where: { + id, + warehouse_id: warehouseId, + status: 'ACTIVE', + }, + }); + + if (!template) { + throw new Error('模板不存在或无权限'); + } + + await template.update({ + status: 'DISABLED', + delete_at: new Date(), + update_at: new Date(), + }); + + return { + message: '模板删除成功', + code: 200, + data: { + id, + }, + }; + } + +/** * 获取所有业务类型(用于下拉选择)- 支持分组展示 * @return {Object} 业务类型及打印项列表,包含分组信息 */ diff --git a/app/service/systems/stock_store.js b/app/service/systems/stock_store.js index b660ff5..8d7959d 100644 --- a/app/service/systems/stock_store.js +++ b/app/service/systems/stock_store.js @@ -1,5 +1,12 @@ 'use strict'; const Service = require('egg').Service; +const { + parseWhereConditions, + buildSequelizeCondition: buildSequelizeConditionUtil, + processConditionValue: processConditionValueUtil, + isEmptyValue: isEmptyValueUtil, + normalizeDate: normalizeDateUtil, +} = require('../../lib/query_condition_parser'); class stockStoreService extends Service { constructor(ctx) { @@ -201,7 +208,7 @@ class stockStoreService extends Service { // ⭐ 关键修复:使用 raw: true 获取纯对象 const itemInfo = await ctx.model.StockStore.findByPk(itemId, { - attributes: [ 'id', 'stock_id', 'warehouse_code', 'item_code' ], // 按需增加字段 + attributes: ['id', 'stock_id', 'warehouse_code', 'item_code'], // 按需增加字段 raw: true, // ⭐ 必须:转换为纯 JavaScript 对象 }); @@ -238,7 +245,7 @@ class stockStoreService extends Service { app.logger.warn('缓存服务异常,降级直接查询数据库', itemId); try { const itemInfo = await ctx.model.StockStore.findByPk(itemId, { - attributes: [ 'id', 'stock_id', 'warehouse_code', 'item_code' ], + attributes: ['id', 'stock_id', 'warehouse_code', 'item_code'], raw: true, }); return itemInfo || null; @@ -538,7 +545,7 @@ class stockStoreService extends Service { action: isLocking ? 'lock' : 'unlock', quantity: absQty, beforeLocked: isLocking ? stockRecord.locked_quantity - absQty : stockRecord.locked_quantity + - absQty, + absQty, afterLocked: stockRecord.locked_quantity, totalQuantity: stockRecord.quantity, available: stockRecord.quantity - stockRecord.locked_quantity, @@ -847,7 +854,7 @@ class stockStoreService extends Service { store_id: sourceData.store_id, deleted_at: null, }, - attributes: [ 'id' ], + attributes: ['id'], raw: true, }); @@ -958,7 +965,7 @@ class stockStoreService extends Service { warehouse_id: warehouseId, is_valid: 'Y', }, - attributes: [ 'id' ], + attributes: ['id'], raw: true, }); @@ -1040,7 +1047,7 @@ class stockStoreService extends Service { where: {}, order: [], attributes: { - exclude: [ 'deleted_at' ], + exclude: ['deleted_at'], }, }; const barcodeQueryOptions = { @@ -1064,64 +1071,81 @@ class stockStoreService extends Service { prohibitedQueryOptions.where[Op.and] = []; // 检测并处理条码查询条件 let hasBarcodeCondition = false; - let hasProhibitedCondition = false; let barcodeCondition = null; + let parsedBarcodeInput = null; // 处理动态查询条件 if (where && Object.keys(where).length > 0) { - const dynamicConditions = []; - const prohibitedConditions = []; - const barcodedynamicConditions = []; + const parsed = parseWhereConditions({ + where, + app, + specialFieldMap: { + barcode: { + bucket: 'barcode', + }, + prohibited_type: { + bucket: 'prohibited', + field: 'id', + }, + }, + }); - for (const fieldKey in where) { - const condition = where[fieldKey]; - - if (this.isEmptyValue(condition.value)) { - continue; - } - - // 检查是否是条码查询 - if (fieldKey === 'barcode') { - hasBarcodeCondition = true; - barcodeCondition = this.buildSequelizeCondition(fieldKey, condition, app); - if (barcodeCondition) { - barcodedynamicConditions.push(barcodeCondition); - } - continue; // 暂不添加到动态条件中 - } - if (fieldKey === 'prohibited_type') { - condition.field = 'id'; - hasProhibitedCondition = true; - const prohibitedCondition = this.buildSequelizeCondition('id', condition, app); - if (prohibitedCondition) { - prohibitedConditions.push(prohibitedCondition); - } - continue; - } - // 其他字段的处理 - const sequelizeCondition = this.buildSequelizeCondition(fieldKey, condition, app); - if (sequelizeCondition) { - dynamicConditions.push(sequelizeCondition); - } + if (!parsed.ok) { + return { + code: 400, + data: { + list: [], + pagination: { + page: parseInt(page), + pageSize: parseInt(pageSize), + total: 0, + totalPages: 0, + hasPrevious: false, + hasNext: false, + }, + summary: { + total_quantity: 0, + total_locked: 0, + total_available: 0, + total_items: 0, + }, + }, + message: `筛选条件解析失败: ${parsed.reason}`, + }; } + const { + dynamicConditions, + bucketConditions, + bucketFlags, + rawConditionsByField, + } = parsed.result; + + const barcodeDynamicConditions = bucketConditions.barcode || []; + const prohibitedConditions = bucketConditions.prohibited || []; + + hasBarcodeCondition = Boolean(bucketFlags.barcode); + hasProhibitedCondition = Boolean(bucketFlags.prohibited); + barcodeCondition = barcodeDynamicConditions[0] || null; + parsedBarcodeInput = rawConditionsByField.barcode || null; + if (dynamicConditions.length > 0) { queryOptions.where[Op.and].push({ [Op.and]: dynamicConditions, }); } - if (barcodedynamicConditions.length > 0) { + if (barcodeDynamicConditions.length > 0) { barcodeQueryOptions.where[Op.and].push({ - [Op.and]: barcodedynamicConditions, + [Op.and]: barcodeDynamicConditions, }); } + if (prohibitedConditions.length > 0) { prohibitedQueryOptions.where[Op.and].push({ [Op.and]: prohibitedConditions, }); } - } // 如果有条码查询条件,先查询匹配的库存ID @@ -1131,11 +1155,11 @@ class stockStoreService extends Service { let barcodeValues = []; // 根据不同的条件格式提取条码值 - if (where.barcode.value) { - if (Array.isArray(where.barcode.value)) { - barcodeValues = where.barcode.value; - } else if (typeof where.barcode.value === 'string') { - barcodeValues = [ where.barcode.value ]; + if (parsedBarcodeInput && parsedBarcodeInput.value) { + if (Array.isArray(parsedBarcodeInput.value)) { + barcodeValues = parsedBarcodeInput.value; + } else if (typeof parsedBarcodeInput.value === 'string') { + barcodeValues = [ parsedBarcodeInput.value ]; } } @@ -1143,7 +1167,8 @@ class stockStoreService extends Service { // 构建条码查询条件 const barcodeWhere = {}; - if (where.barcode.operator === 'eq') { + const barcodeOperator = String(parsedBarcodeInput.operator || 'like').toLowerCase(); + if (barcodeOperator === 'eq') { // 精确查询 if (barcodeValues.length === 1) { barcodeWhere.barcode = barcodeValues[0]; @@ -1152,7 +1177,7 @@ class stockStoreService extends Service { [Op.in]: barcodeValues, }; } - } else if (where.barcode.operator === 'like') { + } else if (barcodeOperator === 'like') { // 模糊查询 if (barcodeValues.length === 1) { barcodeWhere.barcode = { @@ -1175,8 +1200,8 @@ class stockStoreService extends Service { // 查询匹配的条码,获取库存ID const matchedBarcodes = await ctx.model.StockBarcode.findAll({ ...barcodeQueryOptions, - attributes: [ 'stock_id' ], - group: [ 'stock_id' ], // 使用 GROUP BY 去重 + attributes: ['stock_id'], + group: ['stock_id'], // 使用 GROUP BY 去重 raw: true, }); @@ -1224,25 +1249,25 @@ class stockStoreService extends Service { const actualSortField = validSortFields.includes(sortField) ? sortField : 'create_at'; const actualSortOrder = sortOrder.toUpperCase() === 'ASC' ? 'ASC' : 'DESC'; - queryOptions.order.push([ actualSortField, actualSortOrder ]); + queryOptions.order.push([actualSortField, actualSortOrder]); // 计算分页偏移量 const offset = (page - 1) * pageSize; // 执行查询:获取总数和数据 - const [ total, data ] = await Promise.all([ + const [total, data] = await Promise.all([ // 获取总数 ctx.model.StockWarehouse.count({ where: queryOptions.where, include: [ctx.model.StoreWarehouse.buildStoreStockInclude({ warehouseId: ctx.user.store_id, required: true, - attributes: [ 'store_remask' ], + attributes: ['store_remask'], }), { ...prohibitedQueryOptions, model: ctx.model.ProhibitedType, as: 'prohibited', - attributes: [ 'type_name' ], + attributes: ['type_name'], required: hasProhibitedCondition, }], distinct: true, @@ -1254,12 +1279,12 @@ class stockStoreService extends Service { include: [ctx.model.StoreWarehouse.buildStoreStockInclude({ warehouseId: ctx.user.store_id, required: true, - attributes: [ 'store_remask' ], + attributes: ['store_remask'], }), { ...prohibitedQueryOptions, model: ctx.model.ProhibitedType, as: 'prohibited', - attributes: [ 'type_name' ], + attributes: ['type_name'], required: hasProhibitedCondition, }], limit: parseInt(pageSize), @@ -1297,7 +1322,7 @@ class stockStoreService extends Service { include: [{ model: ctx.model.File, as: 'file', - attributes: [ 'file_url' ], + attributes: ['file_url'], required: true, }], }); @@ -1346,7 +1371,7 @@ class stockStoreService extends Service { // 如果有条码查询,添加匹配统计 ...(hasBarcodeCondition && { barcode_matched_count: matchedStockIds.length, - barcode_search_value: where.barcode.value, + barcode_search_value: parsedBarcodeInput ? parsedBarcodeInput.value : null, }), }; @@ -1408,180 +1433,11 @@ class stockStoreService extends Service { * @return {Object|null} Sequelize条件对象 */ buildSequelizeCondition(fieldKey, condition, app) { - const { - Sequelize, - } = app; - const { - operator = 'eq', value, type, isMultiple, - } = condition; - - // 处理字段名 - const fieldName = condition.field || fieldKey; - - // 特殊值处理 - const processedValue = this.processConditionValue(value, type); - // 根据操作符构建条件 - switch (operator.toLowerCase()) { - case 'eq': - return { - [fieldName]: processedValue, - }; - - case 'ne': - return { - [fieldName]: { - [Sequelize.Op.ne]: processedValue, - }, - }; - - case 'contains': - case 'like': - // 处理多值情况 - if (Array.isArray(processedValue) && processedValue.length > 0) { - // 多个值使用 OR 连接 - return { - [Sequelize.Op.or]: processedValue.map(val => ({ - [fieldName]: { - [Sequelize.Op.like]: `%${val}%`, - }, - })), - }; - } - // 单个值正常处理 - return { - [fieldName]: { - [Sequelize.Op.like]: `%${processedValue}%`, - }, - }; - - case 'startswith': - // 处理多值情况 - if (Array.isArray(processedValue) && processedValue.length > 0) { - return { - [Sequelize.Op.or]: processedValue.map(val => ({ - [fieldName]: { - [Sequelize.Op.like]: `${val}%`, - }, - })), - }; - } - return { - [fieldName]: { - [Sequelize.Op.like]: `${processedValue}%`, - }, - }; - - case 'endswith': - // 处理多值情况 - if (Array.isArray(processedValue) && processedValue.length > 0) { - return { - [Sequelize.Op.or]: processedValue.map(val => ({ - [fieldName]: { - [Sequelize.Op.like]: `%${val}`, - }, - })), - }; - } - return { - [fieldName]: { - [Sequelize.Op.like]: `%${processedValue}`, - }, - }; - - case 'gt': - return { - [fieldName]: { - [Sequelize.Op.gt]: processedValue, - }, - }; - - case 'lt': - return { - [fieldName]: { - [Sequelize.Op.lt]: processedValue, - }, - }; - - case 'ge': - return { - [fieldName]: { - [Sequelize.Op.gte]: processedValue, - }, - }; - - case 'le': - return { - [fieldName]: { - [Sequelize.Op.lte]: processedValue, - }, - }; - - case 'in': - return Array.isArray(processedValue) ? { - [fieldName]: { - [Sequelize.Op.in]: processedValue, - }, - } : - null; - - case 'notin': - return Array.isArray(processedValue) ? { - [fieldName]: { - [Sequelize.Op.notIn]: processedValue, - }, - } : - null; - - case 'between': - return Array.isArray(processedValue) && processedValue.length === 2 ? { - [fieldName]: { - [Sequelize.Op.between]: processedValue, - }, - } : - null; - - case 'notbetween': - return Array.isArray(processedValue) && processedValue.length === 2 ? { - [fieldName]: { - [Sequelize.Op.notBetween]: processedValue, - }, - } : - null; - - case 'isnull': - return { - [fieldName]: { - [Sequelize.Op.is]: null, - }, - }; - - case 'isnotnull': - return { - [fieldName]: { - [Sequelize.Op.not]: null, - }, - }; - - case 'regexp': - return { - [fieldName]: { - [Sequelize.Op.regexp]: processedValue, - }, - }; - - case 'notregexp': - return { - [fieldName]: { - [Sequelize.Op.notRegexp]: processedValue, - }, - }; - - default: - // 默认使用等于操作符 - return { - [fieldName]: processedValue, - }; + const parsed = buildSequelizeConditionUtil(fieldKey, condition, app); + if (!parsed.ok) { + return null; } + return parsed.condition; } /** @@ -1591,38 +1447,11 @@ class stockStoreService extends Service { * @return {any} 处理后的值 */ processConditionValue(value, type) { - if (value === undefined || value === null) { - return value; - } + return processConditionValueUtil(value, type); + } - switch (type) { - case 'boolean': - // 处理布尔值:true/Y -> 'Y', false/N -> 'N' - if (value === true || value === 'true' || value === 'Y' || value === 'y') { - return 'Y'; - } - if (value === false || value === 'false' || value === 'N' || value === 'n') { - return 'N'; - } - return value; - - case 'date': - case 'daterange': - // 确保日期格式正确 - if (Array.isArray(value)) { - return value.map(v => this.normalizeDate(v)); - } - return this.normalizeDate(value); - - case 'number': - // 转换为数字 - const num = parseFloat(value); - return isNaN(num) ? value : num; - case 'text': - return value.split(','); - default: - return value; - } + normalizeDate(value) { + return normalizeDateUtil(value); } @@ -1652,19 +1481,7 @@ class stockStoreService extends Service { * @return {boolean} 是否为空 */ isEmptyValue(value) { - if (value === undefined || value === null) { - return true; - } - - if (typeof value === 'string' && value.trim() === '') { - return true; - } - - if (Array.isArray(value) && value.length === 0) { - return true; - } - - return false; + return isEmptyValueUtil(value); } async getProhibitedType() { const { @@ -1690,9 +1507,9 @@ class stockStoreService extends Service { ], }, order: [ - [ 'warehouse_id', 'ASC' ], // 系统预设在前(warehouse_id为null) - [ 'sort_order', 'ASC' ], // 按排序字段 - [ 'created_at', 'ASC' ], // 按创建时间 + ['warehouse_id', 'ASC'], // 系统预设在前(warehouse_id为null) + ['sort_order', 'ASC'], // 按排序字段 + ['created_at', 'ASC'], // 按创建时间 ], attributes: [ 'id', @@ -1733,7 +1550,7 @@ class stockStoreService extends Service { include: [{ model: ctx.model.StockWarehouse, as: 'stock', - attributes: [ 'id' ], + attributes: ['id'], where: { warehouse_id: warehouseId, }, @@ -1747,7 +1564,7 @@ class stockStoreService extends Service { const { ctx, service, app } = this; const { Op } = app.Sequelize; - const canChangeFlide = [ 'brand_name', 'prohibited_id', 'gross_weight', 'packing_requirements', 'managementFlags', 'stock_unit' ]; + const canChangeFlide = ['brand_name', 'prohibited_id', 'gross_weight', 'packing_requirements', 'managementFlags', 'stock_unit']; const { ids, method, value } = ctx.request.body; console.log('批量修改参数', ctx.request.body); @@ -1779,7 +1596,7 @@ class stockStoreService extends Service { warehouse_id: warehouseId, delete_at: null, }, - attributes: [ 'id' ], + attributes: ['id'], }); if (existingRefs.length !== ids.length) { @@ -1825,7 +1642,7 @@ class stockStoreService extends Service { } // 验证三个管理标识字段 - const managementFields = [ 'is_sn_mgmt', 'is_shelf_life_mgmt', 'is_batch_mgmt' ]; + const managementFields = ['is_sn_mgmt', 'is_shelf_life_mgmt', 'is_batch_mgmt']; updateData = { update_at: new Date(), update_by: ctx.user.id || ctx.user.username, @@ -1835,7 +1652,7 @@ class stockStoreService extends Service { if (value[field] === undefined) { return { message: `管理标识缺少 ${field} 字段`, code: 405 }; } - if (![ 'Y', 'N' ].includes(value[field])) { + if (!['Y', 'N'].includes(value[field])) { return { message: `管理标识 ${field} 的值必须是 Y 或 N`, code: 405 }; } updateData[field] = value[field]; @@ -1857,7 +1674,7 @@ class stockStoreService extends Service { } // 5. 执行批量更新 - const [ affectedRows ] = await ctx.model.StockWarehouse.update(updateData, { + const [affectedRows] = await ctx.model.StockWarehouse.update(updateData, { where: { id: { [Op.in]: ids }, warehouse_id: warehouseId, @@ -1986,7 +1803,7 @@ class stockStoreService extends Service { include: [{ model: ctx.model.StockWarehouse, as: 'warehouse_stock', - attributes: [ 'id', 'store_id' ], + attributes: ['id', 'store_id'], where: { warehouse_id: warehouseId, }, @@ -2030,7 +1847,7 @@ class stockStoreService extends Service { StockStoreWhere[Op.or] = likeConditions; } const offset = (page - 1) * pageSize; - [ total, barcodes ] = await Promise.all([ + [total, barcodes] = await Promise.all([ ctx.model.StockStore.count({ where: StockStoreWhere, attributes: [ @@ -2039,7 +1856,7 @@ class stockStoreService extends Service { include: [{ model: ctx.model.StockWarehouse, as: 'warehouse_stock', - attributes: [ 'id' ], + attributes: ['id'], where: StockWarehouseWhere, required: false, }], @@ -2055,7 +1872,7 @@ class stockStoreService extends Service { include: [{ model: ctx.model.StockWarehouse, as: 'warehouse_stock', - attributes: [ 'id' ], + attributes: ['id'], where: StockWarehouseWhere, required: false, }], @@ -2306,7 +2123,7 @@ class stockStoreService extends Service { }); // 6. 执行更新 - const [ affectedRows ] = await ctx.model.StockWarehouse.update(updateData, { + const [affectedRows] = await ctx.model.StockWarehouse.update(updateData, { where: { id, warehouse_id: ctx.user.store_id, @@ -2459,7 +2276,7 @@ class stockStoreService extends Service { } validateSaveParams(data, isEdit = true) { - const requiredFields = [ 'item_code', 'item_name', 'stock_unit', 'gross_weight' ]; + const requiredFields = ['item_code', 'item_name', 'stock_unit', 'gross_weight']; if (!data.id && isEdit) { throw new Error('缺失必要参数: id'); } @@ -2474,7 +2291,7 @@ class stockStoreService extends Service { } // 数值类型验证 - const numericFields = [ 'length', 'width', 'height', 'volume', 'gross_weight', 'net_weight' ]; + const numericFields = ['length', 'width', 'height', 'volume', 'gross_weight', 'net_weight']; for (const field of numericFields) { if (data[field] && isNaN(Number(data[field]))) { throw new Error(`${field} 必须是有效的数字`); @@ -2508,7 +2325,7 @@ class stockStoreService extends Service { }; const space = await ctx.model.StockWarehouse.findOne({ where, - attributes: [ 'id' ], + attributes: ['id'], }); // 如果没有找到重复的条码,返回唯一 @@ -2546,11 +2363,11 @@ class stockStoreService extends Service { { model: ctx.model.Storage, as: 'storage', - attributes: [ 'id', 'quantity' ], + attributes: ['id', 'quantity'], required: false, // 使用left join,因为可能没有库存记录 }, ], - attributes: [ 'id', 'item_name', 'quantity', 'return_quantity' ], + attributes: ['id', 'item_name', 'quantity', 'return_quantity'], }); console.log('查询到的商品资料:', JSON.stringify(products, null, 2)); @@ -2616,7 +2433,7 @@ class stockStoreService extends Service { const result = await ctx.model.transaction(async t => { // 软删除商品资料 - const [ affectedCount ] = await ctx.model.StockWarehouse.update( + const [affectedCount] = await ctx.model.StockWarehouse.update( { deleted_at: new Date(), updated_at: new Date(), @@ -2760,7 +2577,7 @@ class stockStoreService extends Service { includeConditions.push({ model: app.model.StockBarcode, as: 'barcodes', - attributes: [ 'barcode' ], + attributes: ['barcode'], required: false, // 使用LEFT JOIN where: { barcode: { [Op.like]: searchKeyword }, @@ -2780,14 +2597,14 @@ class stockStoreService extends Service { includeConditions.push({ model: app.model.StockBarcode, as: 'barcodes', - attributes: [ 'barcode' ], + attributes: ['barcode'], required: false, }); } includeConditions.push(app.model.StoreWarehouse.buildStoreStockInclude({ warehouseId, required: false, - attributes: [ 'store_id', 'store_remask' ], + attributes: ['store_id', 'store_remask'], })); // 执行查询 @@ -2799,7 +2616,7 @@ class stockStoreService extends Service { 'sku_property', 'stock_unit', 'quantity', 'locked_quantity', 'brand_name', 'item_type', ], - order: [[ 'create_at', 'DESC' ]], + order: [['create_at', 'DESC']], limit: 50, include: includeConditions, subQuery: false, // 避免子查询,提高性能 diff --git a/app/service/systems/storage/receiving.js b/app/service/systems/storage/receiving.js index 85c8d62..ec2def5 100644 --- a/app/service/systems/storage/receiving.js +++ b/app/service/systems/storage/receiving.js @@ -2,6 +2,15 @@ const Service = require('egg').Service; class ReceivingService extends Service { + /** + * 查询收货单列表。 + * @param {Object} where 动态筛选条件 + * @param {Object} [pageParams] 分页参数 + * @param {number} [pageParams.page=1] 页码 + * @param {number} [pageParams.pageSize=20] 每页条数 + * @param {Object} [sortParams] 排序参数 + * @return {Promise} 列表、分页与汇总信息 + */ async getReceivingList(where, pageParams = {}, sortParams = {}) { const { ctx, @@ -277,8 +286,12 @@ class ReceivingService extends Service { }; } } - /* - * 获取收货单详情 + /** + * 获取收货单详情(主单 + 明细分页 + 图片)。 + * @param {Object} data 请求体 + * @param {number} data.id 收货单ID + * @param {Object} data.pagination 分页参数 + * @return {Promise} 详情数据 */ async getReceivingDetail(data) { const { id, pagination } = data; @@ -358,7 +371,12 @@ class ReceivingService extends Service { return { code: 500, message: '服务器错误', data: {} }; } } - //批量作废 + /** + * 批量作废收货单。 + * @param {Object} data 请求体 + * @param {number[]} data.ids 收货单ID数组 + * @return {Promise} 作废处理结果 + */ async batchCancelReceiving(data) { const { ids } = data; const { ctx } = this; @@ -638,6 +656,12 @@ class ReceivingService extends Service { return value; } } + + /** + * 创建收货单并生成收货单号。 + * @param {Object} data 创建参数 + * @return {Promise} 新建结果(含 id 与 receiving_number) + */ async create(data) { const { delivery_method, @@ -753,6 +777,13 @@ class ReceivingService extends Service { }; } } + + /** + * 查询单个收货单完整信息(含明细、图片)。 + * @param {Object} data 请求体 + * @param {number} data.id 收货单ID + * @return {Promise} 单据详情 + */ async get(data) { const { id } = data; const { ctx, app } = this; @@ -881,6 +912,13 @@ class ReceivingService extends Service { return { code: 500, message: '服务器错误', data: {} }; } } + + /** + * 向收货单新增一条默认明细。 + * @param {Object} data 请求体 + * @param {number} data.receiving_id 收货单ID + * @return {Promise} 明细列表与默认选中ID + */ async addDetail(data) { const ctx = this.ctx; const { receiving_id } = data; @@ -1303,6 +1341,12 @@ class ReceivingService extends Service { } } + /** + * 删除收货单明细并回算统计。 + * @param {Object} data 请求体 + * @param {number} data.detail_id 明细ID + * @return {Promise} 删除结果 + */ async deleteDetail(data) { const ctx = this.ctx; const { detail_id } = data; @@ -1408,6 +1452,11 @@ class ReceivingService extends Service { }; } } + /** + * 修改收货明细信息并触发库存/统计联动。 + * @param {Object} data 请求体 + * @return {Promise} 修改结果 + */ async detailChange(data) { const { ctx, app } = this; const warehouseId = ctx.user.store_id; @@ -1752,6 +1801,13 @@ class ReceivingService extends Service { throw error; } } + /** + * 完成收货单:校验明细、更新状态并写入库存。 + * @param {Object} data 请求体 + * @param {number} data.id 收货单ID + * @param {string} [data.remark] 完成备注 + * @return {Promise} 完成结果 + */ async completeReceiving(data) { const { ctx, app } = this; const warehouseId = ctx.user.store_id; diff --git a/docs/stock-stockWarehouse-query-rules.md b/docs/stock-stockWarehouse-query-rules.md new file mode 100644 index 0000000..28a081e --- /dev/null +++ b/docs/stock-stockWarehouse-query-rules.md @@ -0,0 +1,167 @@ +# stock.warehouse.list 前端查询规则 + +## 目的 + +本文档约束 `stock.warehouse.list` 的 `where` 构造格式,便于前端统一构建查询条件,并与后端解析器保持一致。 + +## 接口入口 + +- 路由:`POST /system` +- method:`stock.warehouse.list` + +## 请求体结构 + +```json +{ + "pagination": { + "page": 1, + "pageSize": 20 + }, + "where": { + "item_code": { + "operator": "like", + "value": "SKU", + "type": "text" + } + } +} +``` + +## where 字段规则 + +`where` 必须是对象,且每个字段值也必须是对象。 + +正确示例: + +```json +{ + "where": { + "item_name": { + "operator": "like", + "value": "鞋", + "type": "text" + } + } +} +``` + +错误示例(会返回解析失败原因): + +```json +{ + "where": { + "item_name": "鞋" + } +} +``` + +## 条件对象结构 + +每个 `where.` 支持: + +- `operator`:操作符,默认 `eq` +- `value`:查询值 +- `type`:值类型(可选) +- `field`:映射到真实字段(一般不需要前端传) + +### 支持操作符 + +- `eq` +- `ne` +- `like` / `contains` +- `startswith` +- `endswith` +- `gt` +- `lt` +- `ge` +- `le` +- `in` +- `notin` +- `between` +- `notbetween` +- `isnull` +- `isnotnull` +- `regexp` +- `notregexp` + +### 支持 type + +- `boolean`:转换为 `Y/N` +- `number`:转换为数字 +- `date`:日期字符串归一化 +- `daterange`:日期数组归一化 +- `text`:逗号分隔字符串拆分数组 + +## 特殊字段说明 + +### barcode + +- 在条码表中先匹配,再回灌 `stock_id` 过滤主表。 +- 推荐:`operator=eq|like`。 + +### prohibited_type + +- 传入的是违禁品类型 `id`。 +- 后端会映射到关联模型进行过滤。 + +## 空值处理 + +以下值会被视为“空条件”并跳过: + +- `null` +- `undefined` +- `""` +- `[]` + +## 排序规则 + +后端只接受以下排序字段: + +- `id` +- `item_code` +- `item_name` +- `quantity` +- `locked_quantity` +- `tag_price` +- `retail_price` +- `create_at` +- `update_at` + +当传入非法排序字段时,会回退为: + +- `sortField=create_at` +- `sortOrder=DESC` + +## 失败返回(解构失败) + +当 `where` 结构不合法时,返回示例: + +```json +{ + "code": 400, + "message": "筛选条件解析失败: 字段 item_code 条件必须是对象", + "data": { + "list": [], + "pagination": { + "page": 1, + "pageSize": 20, + "total": 0, + "totalPages": 0, + "hasPrevious": false, + "hasNext": false + }, + "summary": { + "total_quantity": 0, + "total_locked": 0, + "total_available": 0, + "total_items": 0 + } + } +} +``` + +## 前端建议 + +- 对 `in/notin/between/notbetween` 先做数组校验,再发请求。 +- 对 `where` 做 schema 校验,避免后端 400。 +- 对空输入不构造条件,减少无效查询。 diff --git a/methods/system.json b/methods/system.json index 1b128b4..107531f 100644 --- a/methods/system.json +++ b/methods/system.json @@ -9,25 +9,55 @@ "type": "string", "required": true, "description": "客户端平台标识,如 web/pda/app", - "list":[ - {"value":"web","name":"网页端"}, - {"value":"pda","name":"PDA端"}, - {"value":"app","name":"APP端"}, - {"value":"wx","name":"微信端"}, - {"value":"miniProgram","name":"小程序端"}, - {"value":"other","name":"其他"} + "list": [ + { + "value": "web", + "name": "网页端" + }, + { + "value": "pda", + "name": "PDA端" + }, + { + "value": "app", + "name": "APP端" + }, + { + "value": "wx", + "name": "微信端" + }, + { + "value": "miniProgram", + "name": "小程序端" + }, + { + "value": "other", + "name": "其他" + } ] }, { - "type":"string", - "required":true, - "name":"project", - "description":"项目标识,如 all/warehouse/store/tms", - "list":[ - {"value":"all","name":"全部"}, - {"value":"warehouse","name":"仓库"}, - {"value":"store","name":"货主"}, - {"value":"tms","name":"物流"} + "type": "string", + "required": true, + "name": "project", + "description": "项目标识,如 all/warehouse/store/tms", + "list": [ + { + "value": "all", + "name": "全部" + }, + { + "value": "warehouse", + "name": "仓库" + }, + { + "value": "store", + "name": "货主" + }, + { + "value": "tms", + "name": "物流" + } ] } ], @@ -1488,6 +1518,116 @@ "response": [], "errors": [] }, + { + "method": "setting.printTemplate.create", + "description": "创建打印模板(platform 固定为 default,template_type 固定为 CUSTOM,template_url 固定为空字符串)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "template_name", + "type": "string", + "required": true, + "source": "body", + "description": "模板名称" + }, + { + "name": "business_type", + "type": "string", + "required": true, + "source": "body", + "description": "业务类型" + }, + { + "name": "page_width", + "type": "number", + "required": true, + "source": "body", + "description": "页面宽度(mm)" + }, + { + "name": "page_height", + "type": "number", + "required": true, + "source": "body", + "description": "页面高度(mm)" + }, + { + "name": "template_content", + "type": "array", + "required": false, + "source": "body", + "description": "模板内容,可省略;省略时默认创建空模板内容" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "新建模板ID" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误(缺少 template_name、business_type、page_width 或 page_height)" + }, + { + "code": "409", + "description": "同一业务类型和平台下已存在自定义模板" + } + ] + }, + { + "method": "setting.printTemplate.delete", + "description": "删除打印模板(软删除)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "模板ID" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "删除的模板ID" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误(缺少 id)" + }, + { + "code": "404", + "description": "模板不存在或无权限" + } + ] + }, { "method": "setting.printTemplate.listTemplatesByType", "description": "按业务类型查询模板", @@ -1516,12 +1656,12 @@ ] }, { - "groupName": "库存模块", + "groupName": "商品模块", "module": "stock", "list": [ { - "method": "stock.stockWarehouse", - "description": "stock.stockWarehouse 接口", + "method": "stock.warehouse.list", + "description": "仓库商品列表查询(支持 where 条件与分页)", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -1552,8 +1692,8 @@ "errors": [] }, { - "method": "stock.getProhibitedType", - "description": "stock.getProhibitedType 接口", + "method": "stock.warehouse.getProhibitedType", + "description": "查询违禁品类型列表(系统预设+仓库自定义)", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -1569,8 +1709,8 @@ "errors": [] }, { - "method": "stock.getInfo", - "description": "stock.getInfo 接口", + "method": "stock.warehouse.getInfo", + "description": "查询仓库商品详情", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -1586,8 +1726,8 @@ "errors": [] }, { - "method": "stock.saveWarehouseStock", - "description": "stock.saveWarehouseStock 接口", + "method": "stock.warehouse.saveWarehouseStock", + "description": "更新仓库商品资料", "isNeedAuth": true, "isNeedLogin": true, "headers": [ @@ -1603,8 +1743,8 @@ "errors": [] }, { - "method": "stock.createWarehouseStock", - "description": "stock.createWarehouseStock 接口", + "method": "stock.warehouse.createWarehouseStock", + "description": "新建仓库商品资料", "isNeedAuth": true, "isNeedLogin": true, "headers": [ @@ -1620,8 +1760,8 @@ "errors": [] }, { - "method": "stock.getBarcodes", - "description": "stock.getBarcodes 接口", + "method": "stock.warehouse.getBarcodes", + "description": "查询商品条码列表", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -1637,8 +1777,8 @@ "errors": [] }, { - "method": "stock.saveWarehouseStockBarcode", - "description": "stock.saveWarehouseStockBarcode 接口", + "method": "stock.warehouse.saveWarehouseStockBarcode", + "description": "保存商品条码信息", "isNeedAuth": true, "isNeedLogin": true, "headers": [ @@ -1654,8 +1794,8 @@ "errors": [] }, { - "method": "stock.getStoreStocks", - "description": "stock.getStoreStocks 接口", + "method": "stock.warehouse.getStoreStocks", + "description": "查询仓库商品与货主关联列表", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -1671,8 +1811,8 @@ "errors": [] }, { - "method": "stock.bindItem", - "description": "stock.bindItem 接口", + "method": "stock.warehouse.bindItem", + "description": "绑定货主商品关系", "isNeedAuth": true, "isNeedLogin": true, "headers": [ @@ -1688,8 +1828,8 @@ "errors": [] }, { - "method": "stock.unbindItem", - "description": "stock.unbindItem 接口", + "method": "stock.warehouse.unbindItem", + "description": "解绑货主商品关系", "isNeedAuth": true, "isNeedLogin": true, "headers": [ @@ -1705,8 +1845,8 @@ "errors": [] }, { - "method": "stock.checkItemCodeUnique", - "description": "stock.checkItemCodeUnique 接口", + "method": "stock.warehouse.checkItemCodeUnique", + "description": "校验商品编码在货主维度唯一性", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -1744,8 +1884,8 @@ "errors": [] }, { - "method": "stock.queryStockLogs", - "description": "stock.queryStockLogs 接口", + "method": "stock.warehouse.queryStockLogs", + "description": "查询库存操作日志", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -1769,8 +1909,8 @@ "errors": [] }, { - "method": "stock.handleBatchDelete", - "description": "stock.handleBatchDelete 接口", + "method": "stock.warehouse.handleBatchDelete", + "description": "批量删除仓库商品资料", "isNeedAuth": true, "isNeedLogin": true, "headers": [ @@ -1786,8 +1926,8 @@ "errors": [] }, { - "method": "stock.deleteUnit", - "description": "stock.deleteUnit 接口", + "method": "stock.warehouse.deleteUnit", + "description": "删除库存单位", "isNeedAuth": true, "isNeedLogin": true, "headers": [ @@ -1803,8 +1943,8 @@ "errors": [] }, { - "method": "stock.deleteProhibited", - "description": "stock.deleteProhibited 接口", + "method": "stock.warehouse.deleteProhibited", + "description": "删除违禁品类型", "isNeedAuth": true, "isNeedLogin": true, "headers": [ @@ -1820,8 +1960,8 @@ "errors": [] }, { - "method": "stock.handleBatchChange", - "description": "stock.handleBatchChange 接口", + "method": "stock.warehouse.handleBatchChange", + "description": "批量修改仓库商品字段", "isNeedAuth": true, "isNeedLogin": true, "headers": [ @@ -1837,8 +1977,8 @@ "errors": [] }, { - "method": "stock.getStockUnits", - "description": "stock.getStockUnits 接口", + "method": "stock.warehouse.getStockUnits", + "description": "查询可用库存单位(系统+仓库)", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -1854,8 +1994,8 @@ "errors": [] }, { - "method": "stock.getUnitList", - "description": "stock.getUnitList 接口", + "method": "stock.warehouse.getUnitList", + "description": "查询当前仓库自定义单位列表", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -1871,8 +2011,8 @@ "errors": [] }, { - "method": "stock.createProhibited", - "description": "stock.createProhibited 接口", + "method": "stock.warehouse.createProhibited", + "description": "新增违禁品类型", "isNeedAuth": true, "isNeedLogin": true, "headers": [ @@ -1896,8 +2036,8 @@ "errors": [] }, { - "method": "stock.createUnit", - "description": "stock.createUnit 接口", + "method": "stock.warehouse.createUnit", + "description": "新增库存单位", "isNeedAuth": true, "isNeedLogin": true, "headers": [ @@ -1921,8 +2061,8 @@ "errors": [] }, { - "method": "stock.search", - "description": "stock.search 接口", + "method": "stock.warehouse.search", + "description": "仓库商品关键字搜索", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -1940,8 +2080,8 @@ ] }, { - "groupName": "入库模块", - "module": "storage.receiving", + "groupName": "库存模块", + "module": "storage", "list": [ { "method": "storage.receiving.getReceivingList", @@ -1962,18 +2102,42 @@ "type": "object", "required": false, "source": "body", - "description": "pagination 参数" + "description": "分页参数,支持 page/pageSize" }, { "name": "where", "type": "object", "required": false, "source": "body", - "description": "where 参数" + "description": "筛选参数,支持 quickWhere、status、store_id、日期区间等" } ], - "response": [], - "errors": [] + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "收货单列表" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息(page、pageSize、total、totalPages、hasPrevious、hasNext)" + }, + { + "name": "summary", + "type": "object", + "required": true, + "description": "汇总信息(total_quantity、total_locked、total_available、total_items)" + } + ], + "errors": [ + { + "code": "500", + "description": "查询失败" + } + ] }, { "method": "storage.receiving.getReceivingDetail", @@ -1988,9 +2152,40 @@ "description": "Bearer token" } ], - "params": [], - "response": [], - "errors": [] + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "收货单ID" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "source": "body", + "description": "明细分页参数,支持 page/pageSize" + } + ], + "response": [ + { + "name": "receiving", + "type": "object", + "required": true, + "description": "收货单详情(含 details、images、pagination)" + } + ], + "errors": [ + { + "code": "0", + "description": "无记录或无权访问" + }, + { + "code": "500", + "description": "服务器错误" + } + ] }, { "method": "storage.receiving.batchCancelReceiving", @@ -2005,9 +2200,33 @@ "description": "Bearer token" } ], - "params": [], - "response": [], - "errors": [] + "params": [ + { + "name": "ids", + "type": "array", + "required": true, + "source": "body", + "description": "待作废收货单ID数组" + } + ], + "response": [ + { + "name": "message", + "type": "string", + "required": true, + "description": "批量作废处理结果" + } + ], + "errors": [ + { + "code": "0", + "description": "部分单据不存在、无权访问或状态不允许作废" + }, + { + "code": "500", + "description": "服务器错误" + } + ] }, { "method": "storage.receiving.create", @@ -2022,9 +2241,84 @@ "description": "Bearer token" } ], - "params": [], - "response": [], - "errors": [] + "params": [ + { + "name": "delivery_method", + "type": "string", + "required": true, + "source": "body", + "description": "到货方式:truck/express/air_freight/sea_freight/other" + }, + { + "name": "loading_method", + "type": "string", + "required": true, + "source": "body", + "description": "装卸方式:with_pallet/without_pallet" + }, + { + "name": "license_plate", + "type": "string", + "required": false, + "source": "body", + "description": "车牌号(delivery_method=truck 时建议传)" + }, + { + "name": "tracking_number", + "type": "string", + "required": false, + "source": "body", + "description": "物流单号(非 truck/other 场景建议传)" + }, + { + "name": "store_id", + "type": "number", + "required": false, + "source": "body", + "description": "货主ID" + }, + { + "name": "total_boxes", + "type": "number", + "required": false, + "source": "body", + "description": "总箱数" + }, + { + "name": "total_pallets", + "type": "number", + "required": false, + "source": "body", + "description": "总托盘数" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "新建收货单ID" + }, + { + "name": "receiving_number", + "type": "string", + "required": true, + "description": "收货单号" + } + ], + "errors": [ + { + "code": "0", + "description": "创建失败(如字段枚举不合法、数据库约束异常)" + } + ] }, { "method": "storage.receiving.addItem", @@ -2212,7 +2506,7 @@ ] }, { - "groupName": "门店模块", + "groupName": "主体模块", "module": "store", "list": [ { @@ -2412,7 +2706,7 @@ }, { "method": "user.getBindWechatCode", - "description": "获取微信绑定码(支持轮询,缓存优先)", + "description": "获取微信绑定码(默认立即返回;显式开启长轮询后,最长等待60秒,状态变化立即返回)", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -2430,6 +2724,34 @@ "required": false, "source": "body", "description": "是否强制刷新状态,true 时跳过缓存等待窗口" + }, + { + "name": "waitForChange", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否显式开启长轮询等待(推荐字段);true 时进入最长60秒等待" + }, + { + "name": "longPoll", + "type": "boolean", + "required": false, + "source": "body", + "description": "长轮询开关(兼容字段);true 时进入最长60秒等待" + }, + { + "name": "waitTimeoutMs", + "type": "number", + "required": false, + "source": "body", + "description": "等待超时毫秒数;后端自动封顶60000" + }, + { + "name": "init", + "type": "boolean", + "required": false, + "source": "body", + "description": "初始化请求标记;true 时强制立即返回,不进入长等待" } ], "response": [], @@ -3308,4 +3630,4 @@ } ] } -} \ No newline at end of file +} diff --git a/stock.todo b/stock.todo new file mode 100644 index 0000000..658f66d --- /dev/null +++ b/stock.todo @@ -0,0 +1,112 @@ +# stock.todo + +## 任务目标 +- 提取 `app/service/systemMethods/stock/warehouse.js` 迁移前 method 的历史测试请求记录。 +- 精简并保留新接口(`stock.warehouse.*`)的测试入口。 +- 根据输入/输出补全 `warehouse.js` 方法头注释和 API 文档 `description`。 + +## 迁移方法映射(旧 -> 新) +- `stock.stockWarehouse` -> `stock.warehouse.list` +- `stock.getProhibitedType` -> `stock.warehouse.getProhibitedType` +- `stock.getInfo` -> `stock.warehouse.getInfo` +- `stock.saveWarehouseStock` -> `stock.warehouse.saveWarehouseStock` +- `stock.createWarehouseStock` -> `stock.warehouse.createWarehouseStock` +- `stock.getBarcodes` -> `stock.warehouse.getBarcodes` +- `stock.saveWarehouseStockBarcode` -> `stock.warehouse.saveWarehouseStockBarcode` +- `stock.getStoreStocks` -> `stock.warehouse.getStoreStocks` +- `stock.bindItem` -> `stock.warehouse.bindItem` +- `stock.unbindItem` -> `stock.warehouse.unbindItem` +- `stock.checkItemCodeUnique` -> `stock.warehouse.checkItemCodeUnique` +- `stock.queryStockLogs` -> `stock.warehouse.queryStockLogs` +- `stock.handleBatchDelete` -> `stock.warehouse.handleBatchDelete` +- `stock.deleteUnit` -> `stock.warehouse.deleteUnit` +- `stock.deleteProhibited` -> `stock.warehouse.deleteProhibited` +- `stock.handleBatchChange` -> `stock.warehouse.handleBatchChange` +- `stock.getStockUnits` -> `stock.warehouse.getStockUnits` +- `stock.getUnitList` -> `stock.warehouse.getUnitList` +- `stock.createProhibited` -> `stock.warehouse.createProhibited` +- `stock.createUnit` -> `stock.warehouse.createUnit` +- `stock.search` -> `stock.warehouse.search` + +## 历史测试请求记录提取(迁移前/过渡期) +来源:`node_modules/.mochawesome-reports/mochawesome.json`(2026-03-25) + +### 记录1:新列表接口请求 +- case: `system.stock.warehouse.namespaced.test.js` +- method: `stock.warehouse.list` +- request: +```json +{ + "pagination": { "page": 1, "pageSize": 5 }, + "where": {} +} +``` +- expected: +```json +{ + "httpStatus": 200, + "flag": "success", + "code": 200, + "data": { + "list": "Array", + "pagination": "Object" + } +} +``` + +### 记录2:旧入口退场验证请求(历史) +- case: `system.stock.warehouse.namespaced.test.js`(精简前) +- method: `stock.stockWarehouse` +- request: +```json +{ + "pagination": { "page": 1, "pageSize": 5 }, + "where": {} +} +``` +- expected: +```json +{ + "httpStatus": 500, + "flag": "failure", + "code": 500, + "message": "方法 stockWarehouse 不存在" +} +``` + +### 记录3:where 条件解析服务级样本 +来源:`test/app/service/systems/stock_store.stockWarehouse.conditions.test.js` +- input: +```json +{ + "where": { + "item_code": { "operator": "like", "value": "SKU" }, + "barcode": { "operator": "like", "value": "BC" }, + "prohibited_type": { "operator": "eq", "value": 2 }, + "quantity": { "operator": "ge", "type": "number", "value": "2" } + }, + "pagination": { "page": 1, "pageSize": 10 }, + "sort": { "sortField": "quantity", "sortOrder": "ASC" } +} +``` +- expected: +```json +{ + "code": 200, + "message": "查询成功", + "data.pagination.page": 1, + "data.pagination.pageSize": 10, + "data.queryInfo.hasBarcodeSearch": true +} +``` + +## 新接口精简测试方案 +- 保留:`test/app/controller/system.stock.warehouse.namespaced.test.js` +- 用例:只验证 `stock.warehouse.list` 请求成功与核心返回结构。 +- 下沉:复杂 where/operator 组合继续由 service 级测试覆盖。 + +## 执行结果 +- [x] `warehouse.js` 方法头注释补充(输入/输出声明) +- [x] 新接口测试用例精简 +- [x] `methods/system.json` 的 `stock.warehouse.*` description 语义化更新(21项) +- [x] 回归测试复跑并记录结果(`8 passing`) diff --git a/test/app/controller/system.setting.printTemplate.test.js b/test/app/controller/system.setting.printTemplate.test.js new file mode 100644 index 0000000..feeb00e --- /dev/null +++ b/test/app/controller/system.setting.printTemplate.test.js @@ -0,0 +1,155 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const { + getAuthToken, + invokeSystemMethod, +} = require('../../support/system_method_client'); + +const EXTRA_HEADERS = { + platform: 'web', + project: 'all', +}; + +describe('test/app/controller/system.setting.printTemplate.test.js', () => { + let token = ''; + let businessType = ''; + let createdTemplateId = 0; + const uniqueName = `autotest_template_${Date.now()}`; + + before(async () => { + const auth = await getAuthToken(); + token = auth.token; + + const treeRes = await invokeSystemMethod('setting.printTemplate.list', {}, token, EXTRA_HEADERS); + assert.equal(treeRes.status, 200); + assert.equal(treeRes.body.flag, 'success'); + + const presetTree = Array.isArray(treeRes.body?.presetTree) ? treeRes.body.presetTree : []; + assert.ok(presetTree.length > 0, '缺少可用业务类型,无法执行打印模板测试'); + + for (const item of presetTree) { + if (!item || !item.businessType) { + continue; + } + + const listRes = await invokeSystemMethod('setting.printTemplate.listTemplatesByType', { + businessType: item.businessType, + }, token, EXTRA_HEADERS); + + assert.equal(listRes.status, 200); + assert.equal(listRes.body.flag, 'success'); + + const templates = Array.isArray(listRes.body?.data) ? listRes.body.data : []; + const hasDefaultCustomTemplate = templates.some(template => + template + && template.platform === 'default' + && template.template_type === 'CUSTOM' + && template.warehouse_id !== null + ); + + if (!hasDefaultCustomTemplate) { + businessType = item.businessType; + break; + } + } + + assert.ok(businessType, '当前账号下所有业务类型都已存在默认 CUSTOM 模板,无法执行创建测试'); + }); + + it('normal-1 should create print template successfully', async () => { + const createRes = await invokeSystemMethod('setting.printTemplate.create', { + template_name: uniqueName, + business_type: businessType, + page_width: 100, + page_height: 180, + }, token, EXTRA_HEADERS); + + assert.equal(createRes.status, 200); + assert.equal(createRes.body.flag, 'success'); + assert.equal(createRes.body.code, 200); + + const templateId = Number(createRes.body?.data?.id); + assert.ok(templateId > 0, '创建成功但未返回模板ID'); + createdTemplateId = templateId; + assert.match(createRes.body.message, /模板创建成功|ok/); + }); + + it('normal-2 should list created template by business type', async () => { + const listRes = await invokeSystemMethod('setting.printTemplate.listTemplatesByType', { + businessType, + }, token, EXTRA_HEADERS); + + assert.equal(listRes.status, 200); + assert.equal(listRes.body.flag, 'success'); + assert.equal(listRes.body.code, 200); + + const templates = Array.isArray(listRes.body?.data) ? listRes.body.data : []; + const hit = templates.find(item => Number(item.id) === createdTemplateId); + + assert.ok(hit, '按业务类型查询未包含新建模板'); + assert.equal(hit.template_name, uniqueName); + assert.equal(hit.platform, 'default'); + assert.equal(hit.template_type, 'CUSTOM'); + assert.equal(hit.template_url, ''); + }); + + it('normal-3 should delete created template successfully', async () => { + const deleteRes = await invokeSystemMethod('setting.printTemplate.delete', { + id: createdTemplateId, + }, token, EXTRA_HEADERS); + + assert.equal(deleteRes.status, 200); + assert.equal(deleteRes.body.flag, 'success'); + assert.equal(deleteRes.body.code, 200); + assert.equal(Number(deleteRes.body?.data?.id), createdTemplateId); + assert.match(deleteRes.body.message, /模板删除成功|ok/); + + const listRes = await invokeSystemMethod('setting.printTemplate.listTemplatesByType', { + businessType, + }, token, EXTRA_HEADERS); + assert.equal(listRes.status, 200); + assert.equal(listRes.body.flag, 'success'); + + const templates = Array.isArray(listRes.body?.data) ? listRes.body.data : []; + const hit = templates.find(item => Number(item.id) === createdTemplateId); + assert.equal(hit, undefined, '删除后模板仍出现在查询结果中'); + }); + + it('error-1 should fail when create without page_width', async () => { + const res = await invokeSystemMethod('setting.printTemplate.create', { + template_name: `${uniqueName}_missing_width`, + business_type: businessType, + page_height: 180, + }, token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'failure'); + assert.equal(res.body.code, 400); + assert.match(res.body.message, /page_width/); + }); + + it('error-2 should fail when create without page_height', async () => { + const res = await invokeSystemMethod('setting.printTemplate.create', { + template_name: `${uniqueName}_missing_height`, + business_type: businessType, + page_width: 100, + }, token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'failure'); + assert.equal(res.body.code, 400); + assert.match(res.body.message, /page_height/); + }); + + it('error-3 should fail when delete the same template twice', async () => { + const res = await invokeSystemMethod('setting.printTemplate.delete', { + id: createdTemplateId, + }, token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'failure'); + assert.equal(res.body.code, 404); + assert.match(res.body.message, /模板不存在或无权限/); + }); +}); diff --git a/test/app/controller/system.stock.warehouse.namespaced.test.js b/test/app/controller/system.stock.warehouse.namespaced.test.js new file mode 100644 index 0000000..48f0fb5 --- /dev/null +++ b/test/app/controller/system.stock.warehouse.namespaced.test.js @@ -0,0 +1,84 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const { + getAuthToken, + invokeSystemMethod, +} = require('../../support/system_method_client'); + +const EXTRA_HEADERS = { + platform: 'web', + project: 'all', +}; + +const FALLBACK_ROLE_IDS = [ 4, 6, 30 ]; + +async function switchToWarehouseRole(token) { + let currentToken = token; + const infoRes = await invokeSystemMethod('user.info', {}, currentToken, EXTRA_HEADERS); + + assert.equal(infoRes.status, 200); + assert.equal(infoRes.body.flag, 'success'); + assert.equal(infoRes.body.code, 200); + + const employees = Array.isArray(infoRes.body?.data?.employees) ? infoRes.body.data.employees : []; + const warehouseRoles = employees.filter(item => item && item.role_type === 'warehouse' && Number(item.id)); + const candidateRoleIds = [ ...new Set([ + ...warehouseRoles.map(item => Number(item.id)), + ...FALLBACK_ROLE_IDS, + ].filter(Boolean)) ]; + + assert.ok(candidateRoleIds.length > 0, '当前账号没有可尝试的仓库角色'); + + for (const roleId of candidateRoleIds) { + const changeRes = await invokeSystemMethod('user.changeRole', { + roleId, + }, currentToken, EXTRA_HEADERS); + + if (changeRes.status !== 200 || changeRes.body?.flag !== 'success' || changeRes.body?.code !== 200) { + continue; + } + + currentToken = changeRes.body?.data?.token || currentToken; + + const listRes = await invokeSystemMethod('stock.warehouse.list', { + pagination: { page: 1, pageSize: 1 }, + where: {}, + }, currentToken, EXTRA_HEADERS); + + if (listRes.status === 200 && listRes.body?.flag === 'success' && listRes.body?.code === 200) { + return { + token: currentToken, + roleId, + }; + } + } + + throw new Error('未找到可访问仓库商品列表的仓库角色'); +} + +describe('test/app/controller/system.stock.warehouse.namespaced.test.js', () => { + it('should query stock warehouse list via namespaced method', async () => { + const { token } = await getAuthToken(); + const switched = await switchToWarehouseRole(token); + const payload = { + pagination: { + page: 1, + pageSize: 5, + }, + where: {}, + }; + + const namespacedRes = await invokeSystemMethod('stock.warehouse.list', payload, switched.token, EXTRA_HEADERS); + + assert.equal(namespacedRes.status, 200); + assert.equal(namespacedRes.body.flag, 'success'); + assert.equal(namespacedRes.body.code, 200); + + const namespacedData = namespacedRes.body.data; + + assert.ok(namespacedData, '新入口缺少 data'); + assert.ok(Array.isArray(namespacedData.list), '新入口 list 不是数组'); + assert.ok(namespacedData.pagination, '新入口缺少 pagination'); + }); +}); \ No newline at end of file diff --git a/test/app/controller/system.storage.receiving.test.js b/test/app/controller/system.storage.receiving.test.js new file mode 100644 index 0000000..86e49c5 --- /dev/null +++ b/test/app/controller/system.storage.receiving.test.js @@ -0,0 +1,230 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const { + getAuthToken, + invokeSystemMethod, +} = require('../../support/system_method_client'); + +const EXTRA_HEADERS = { + platform: 'web', + project: 'all', +}; + +const FALLBACK_ROLE_IDS = [ 4, 6, 30 ]; + +function normalizeListPayload(data) { + if (data && Array.isArray(data.list)) return data; + if (data && data.data && Array.isArray(data.data.list)) return data.data; + return null; +} + +function normalizeDetailPayload(data) { + if (data && data.receiving) return data; + if (data && data.data && data.data.receiving) return data.data; + return null; +} + +async function switchToWarehouseRole(token) { + let currentToken = token; + + const infoRes = await invokeSystemMethod('user.info', {}, currentToken, EXTRA_HEADERS); + assert.equal(infoRes.status, 200); + assert.equal(infoRes.body.flag, 'success'); + assert.equal(infoRes.body.code, 200); + + const employees = Array.isArray(infoRes.body?.data?.employees) ? infoRes.body.data.employees : []; + const warehouseRoles = employees.filter(item => item && item.role_type === 'warehouse' && Number(item.id)); + + const candidateRoleIds = [ ...new Set([ + ...warehouseRoles.map(item => Number(item.id)), + ...FALLBACK_ROLE_IDS, + ].filter(Boolean)) ]; + + assert.ok(candidateRoleIds.length > 0, '当前账号没有可尝试的仓库角色'); + + for (const roleId of candidateRoleIds) { + const changeRes = await invokeSystemMethod('user.changeRole', { + roleId, + }, currentToken, EXTRA_HEADERS); + + if (changeRes.status !== 200 || changeRes.body?.flag !== 'success' || changeRes.body?.code !== 200) { + continue; + } + + currentToken = changeRes.body?.data?.token || currentToken; + + const listRes = await invokeSystemMethod('storage.receiving.getReceivingList', { + pagination: { page: 1, pageSize: 10 }, + where: {}, + }, currentToken, EXTRA_HEADERS); + + if (listRes.status === 200 && listRes.body?.flag === 'success' && listRes.body?.code === 200) { + return { + token: currentToken, + roleId, + }; + } + } + + throw new Error('未找到可访问收货单的仓库角色'); +} + +describe('test/app/controller/system.storage.receiving.test.js', () => { + it('should query receiving list', async () => { + const { token } = await getAuthToken(); + const switched = await switchToWarehouseRole(token); + + const res = await invokeSystemMethod('storage.receiving.getReceivingList', { + pagination: { + page: 1, + pageSize: 10, + }, + where: {}, + }, switched.token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + assert.equal(res.body.code, 200); + + const payload = normalizeListPayload(res.body.data); + assert.ok(payload, '返回结构中缺少收货单列表 payload'); + assert.ok(Array.isArray(payload.list), '收货单 list 不是数组'); + assert.ok(payload.pagination, '收货单 pagination 缺失'); + assert.equal(typeof payload.pagination.total, 'number', 'pagination.total 不是 number'); + }); + + it('should query receiving detail when list has records', async () => { + const { token } = await getAuthToken(); + const switched = await switchToWarehouseRole(token); + + const listRes = await invokeSystemMethod('storage.receiving.getReceivingList', { + pagination: { + page: 1, + pageSize: 10, + }, + where: {}, + }, switched.token, EXTRA_HEADERS); + + assert.equal(listRes.status, 200); + assert.equal(listRes.body.flag, 'success'); + assert.equal(listRes.body.code, 200); + + const payload = normalizeListPayload(listRes.body.data); + assert.ok(payload, '返回结构中缺少收货单列表 payload'); + + const first = Array.isArray(payload.list) && payload.list.length > 0 ? payload.list[0] : null; + + if (!first || !first.id) { + return; + } + + const detailRes = await invokeSystemMethod('storage.receiving.getReceivingDetail', { + id: Number(first.id), + pagination: { + page: 1, + pageSize: 10, + }, + }, switched.token, EXTRA_HEADERS); + + assert.equal(detailRes.status, 200); + assert.equal(detailRes.body.flag, 'success'); + assert.equal(detailRes.body.code, 200); + + const detailPayload = normalizeDetailPayload(detailRes.body.data); + assert.ok(detailPayload, '返回结构中缺少收货单详情 payload'); + assert.ok(detailPayload.receiving, 'receiving 字段缺失'); + assert.equal(Number(detailPayload.receiving.id), Number(first.id)); + }); + + it('should create and then batch cancel receiving order', async () => { + const { token } = await getAuthToken(); + const switched = await switchToWarehouseRole(token); + let createdId = null; + + try { + const uniquePlate = `ITEST-${Date.now().toString().slice(-6)}`; + const createRes = await invokeSystemMethod('storage.receiving.create', { + delivery_method: 'truck', + license_plate: uniquePlate, + loading_method: 'with_pallet', + remark: 'integration-test', + total_boxes: 0, + total_pallets: 0, + }, switched.token, EXTRA_HEADERS); + + assert.equal(createRes.status, 200); + assert.equal(createRes.body.flag, 'success'); + assert.equal(createRes.body.code, 200); + + createdId = Number(createRes.body.id || createRes.body?.data?.id || 0); + assert.ok(createdId > 0, `创建成功但未返回有效 id: ${JSON.stringify(createRes.body)}`); + + const cancelRes = await invokeSystemMethod('storage.receiving.batchCancelReceiving', { + ids: [ createdId ], + }, switched.token, EXTRA_HEADERS); + + assert.equal(cancelRes.status, 200); + assert.equal(cancelRes.body.flag, 'success'); + assert.equal(cancelRes.body.code, 200); + assert.match(String(cancelRes.body.message || ''), /成功/); + } finally { + if (createdId > 0) { + await invokeSystemMethod('storage.receiving.batchCancelReceiving', { + ids: [ createdId ], + }, switched.token, EXTRA_HEADERS); + } + } + }); + + it('should reject getReceivingDetail with invalid id', async () => { + const { token } = await getAuthToken(); + const switched = await switchToWarehouseRole(token); + + const res = await invokeSystemMethod('storage.receiving.getReceivingDetail', { + id: -1, + pagination: { + page: 1, + pageSize: 10, + }, + }, switched.token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + assert.equal(res.body.code, 0); + assert.match(String(res.body.message || ''), /无记录|无权访问|不存在/); + }); + + it('should reject create with invalid loading_method enum', async () => { + const { token } = await getAuthToken(); + const switched = await switchToWarehouseRole(token); + + const res = await invokeSystemMethod('storage.receiving.create', { + delivery_method: 'truck', + license_plate: `ITEST-ERR-${Date.now().toString().slice(-6)}`, + loading_method: 'manual', + remark: 'invalid-enum-test', + total_boxes: 0, + total_pallets: 0, + }, switched.token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + assert.equal(res.body.code, 0); + assert.match(String(res.body.message || ''), /创建失败|Data truncated|loading_method/); + }); + + it('should reject batchCancelReceiving with nonexistent ids', async () => { + const { token } = await getAuthToken(); + const switched = await switchToWarehouseRole(token); + + const res = await invokeSystemMethod('storage.receiving.batchCancelReceiving', { + ids: [ 999999999 ], + }, switched.token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + assert.equal(res.body.code, 0); + assert.match(String(res.body.message || ''), /不存在|无权访问|状态不允许/); + }); +}); diff --git a/test/app/service/systems/stock_store.stockWarehouse.conditions.test.js b/test/app/service/systems/stock_store.stockWarehouse.conditions.test.js new file mode 100644 index 0000000..deb0c0e --- /dev/null +++ b/test/app/service/systems/stock_store.stockWarehouse.conditions.test.js @@ -0,0 +1,320 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const StockStoreService = require('../../../../app/service/systems/stock_store'); + +function createTestContext(options = {}) { + const calls = { + countArgs: null, + findArgs: null, + barcodeCalls: [], + fileRefArgs: null, + }; + + const Op = { + and: '$and', + or: '$or', + ne: '$ne', + like: '$like', + gt: '$gt', + lt: '$lt', + gte: '$gte', + lte: '$lte', + in: '$in', + notIn: '$notIn', + between: '$between', + notBetween: '$notBetween', + is: '$is', + not: '$not', + regexp: '$regexp', + notRegexp: '$notRegexp', + }; + + const rows = options.rows || [ { + id: 1, + item_code: 'SKU-1', + goods_code: 'G-1', + item_name: '商品A', + quantity: 10, + locked_quantity: 2, + create_at: '2026-01-01 10:00:00', + update_at: '2026-01-01 10:00:00', + } ]; + + const model = { + StoreWarehouse: { + buildStoreStockInclude(params = {}) { + return { + as: 'store_stock', + required: Boolean(params.required), + attributes: params.attributes || [], + where: { + warehouse_id: params.warehouseId, + }, + }; + }, + }, + ProhibitedType: {}, + StockWarehouse: { + async count(args) { + calls.countArgs = args; + return options.total == null ? rows.length : options.total; + }, + async findAll(args) { + calls.findArgs = args; + return rows; + }, + }, + StockBarcode: { + async findAll(args) { + calls.barcodeCalls.push(args); + const attrs = Array.isArray(args.attributes) ? args.attributes : []; + if (attrs.includes('stock_id')) { + if (options.matchedBarcodeRows) { + return options.matchedBarcodeRows; + } + return [ { stock_id: 1 } ]; + } + if (options.barcodes) { + return options.barcodes; + } + return [ { stock_id: 1, barcode: 'BC-1' } ]; + }, + }, + FileReference: { + async findAll(args) { + calls.fileRefArgs = args; + return options.images || []; + }, + }, + }; + + const app = { + Sequelize: { Op }, + model, + logger: { + debug() {}, + warn() {}, + error() {}, + }, + config: { + cos: { + cdnurl: '', + }, + }, + }; + + const ctx = { + app, + model, + user: { + store_id: 100000, + }, + logger: { + error() {}, + }, + }; + + return { + app, + ctx, + model, + calls, + Op, + }; +} + +function createServiceHarness(options = {}) { + const harness = createTestContext(options); + const service = new StockStoreService(harness.ctx); + return { + ...harness, + service, + }; +} + +describe('test/app/service/systems/stock_store.stockWarehouse.conditions.test.js', () => { + it('should build Sequelize condition for all supported operators', () => { + const { service, app, Op } = createServiceHarness(); + + const cases = [ + [ 'eq', { field: 'item_code', value: 'SKU' }, { item_code: 'SKU' } ], + [ 'ne', { value: 'SKU' }, { item_code: { [Op.ne]: 'SKU' } } ], + [ 'like', { value: 'SKU' }, { item_code: { [Op.like]: '%SKU%' } } ], + [ 'contains', { value: 'SKU' }, { item_code: { [Op.like]: '%SKU%' } } ], + [ 'startswith', { value: 'SKU' }, { item_code: { [Op.like]: 'SKU%' } } ], + [ 'endswith', { value: 'SKU' }, { item_code: { [Op.like]: '%SKU' } } ], + [ 'gt', { value: 10 }, { item_code: { [Op.gt]: 10 } } ], + [ 'lt', { value: 10 }, { item_code: { [Op.lt]: 10 } } ], + [ 'ge', { value: 10 }, { item_code: { [Op.gte]: 10 } } ], + [ 'le', { value: 10 }, { item_code: { [Op.lte]: 10 } } ], + [ 'in', { value: [ 'A', 'B' ] }, { item_code: { [Op.in]: [ 'A', 'B' ] } } ], + [ 'notin', { value: [ 'A', 'B' ] }, { item_code: { [Op.notIn]: [ 'A', 'B' ] } } ], + [ 'between', { value: [ 1, 2 ] }, { item_code: { [Op.between]: [ 1, 2 ] } } ], + [ 'notbetween', { value: [ 1, 2 ] }, { item_code: { [Op.notBetween]: [ 1, 2 ] } } ], + [ 'isnull', { value: null }, { item_code: { [Op.is]: null } } ], + [ 'isnotnull', { value: null }, { item_code: { [Op.not]: null } } ], + [ 'regexp', { value: '^SKU' }, { item_code: { [Op.regexp]: '^SKU' } } ], + [ 'notregexp', { value: '^SKU' }, { item_code: { [Op.notRegexp]: '^SKU' } } ], + ]; + + for (const [ operator, input, expected ] of cases) { + const actual = service.buildSequelizeCondition('item_code', { + operator, + ...input, + }, app); + assert.deepEqual(actual, expected, `operator=${operator}`); + } + }); + + it('should normalize boolean, number and text values', () => { + const { service } = createServiceHarness(); + + assert.equal(service.processConditionValue(true, 'boolean'), 'Y'); + assert.equal(service.processConditionValue('false', 'boolean'), 'N'); + assert.equal(service.processConditionValue('12.5', 'number'), 12.5); + assert.deepEqual(service.processConditionValue('A,B,C', 'text'), [ 'A', 'B', 'C' ]); + }); + + it('should support date and daterange condition extraction', () => { + const { service, app, Op } = createServiceHarness(); + + const dateEq = service.buildSequelizeCondition('create_at', { + operator: 'eq', + type: 'date', + value: '2026-03-25', + }, app); + assert.ok(dateEq.create_at); + + const between = service.buildSequelizeCondition('create_at', { + operator: 'between', + type: 'daterange', + value: [ '2026-03-01', '2026-03-31' ], + }, app); + + assert.deepEqual(between, { + create_at: { + [Op.between]: [ '2026-03-01', '2026-03-31' ], + }, + }); + }); + + it('should parse where and return list with barcode/prohibited branches', async () => { + const { service, calls, Op } = createServiceHarness(); + + const result = await service.getWarehouseStock({ + item_code: { + operator: 'like', + value: 'SKU', + }, + barcode: { + operator: 'like', + value: 'BC', + }, + prohibited_type: { + operator: 'eq', + value: 2, + }, + quantity: { + operator: 'ge', + type: 'number', + value: '2', + }, + }, { + page: 1, + pageSize: 10, + }, { + sortField: 'quantity', + sortOrder: 'ASC', + }); + + assert.equal(result.code, 200); + assert.equal(result.message, '查询成功'); + assert.equal(result.data.pagination.page, 1); + assert.equal(result.data.pagination.pageSize, 10); + assert.equal(result.data.queryInfo.hasBarcodeSearch, true); + + assert.ok(calls.countArgs); + assert.ok(calls.findArgs); + assert.ok(Array.isArray(calls.barcodeCalls)); + assert.ok(calls.barcodeCalls.length >= 2, '应包含条码匹配查询和条码回填查询'); + + const stockWhere = calls.findArgs.where; + assert.ok(stockWhere[Op.and], '应存在 AND 组合条件'); + + const includeList = calls.findArgs.include; + const prohibitedInclude = includeList.find(item => item.as === 'prohibited'); + assert.ok(prohibitedInclude, '应包含 prohibited 关联'); + assert.equal(prohibitedInclude.required, true, '含 prohibited_type 时应为必需关联'); + }); + + it('should short-circuit when barcode has no matched stock ids', async () => { + const { service, calls } = createServiceHarness({ + matchedBarcodeRows: [], + rows: [ { + id: 99, + } ], + }); + + const result = await service.getWarehouseStock({ + barcode: { + operator: 'eq', + value: 'NOT-FOUND', + }, + }, { + page: 1, + pageSize: 20, + }); + + assert.equal(result.code, 200); + assert.deepEqual(result.data.list, []); + assert.equal(result.data.pagination.total, 0); + assert.equal(calls.countArgs, null); + assert.equal(calls.findArgs, null); + }); + + it('should ignore empty where values and fallback invalid sort field', async () => { + const { service, calls } = createServiceHarness(); + + const result = await service.getWarehouseStock({ + item_name: { + operator: 'like', + value: ' ', + }, + store_id: { + operator: 'in', + value: [], + }, + item_code: { + operator: 'like', + value: 'SKU-1', + }, + }, { + page: 2, + pageSize: 5, + }, { + sortField: 'unknown_field', + sortOrder: 'UNKNOWN', + }); + + assert.equal(result.code, 200); + assert.deepEqual(calls.findArgs.order, [ [ 'create_at', 'DESC' ] ]); + assert.equal(result.data.pagination.page, 2); + assert.equal(result.data.pagination.pageSize, 5); + }); + + it('should return failure reason when where deconstruction is invalid', async () => { + const { service } = createServiceHarness(); + + const result = await service.getWarehouseStock({ + item_code: 'SKU-1', + }, { + page: 1, + pageSize: 20, + }); + + assert.equal(result.code, 400); + assert.match(result.message, /筛选条件解析失败/); + assert.match(result.message, /字段 item_code 条件必须是对象/); + }); +}); From 2f838186de55e02647fef9edcb95a9df8781d71f Mon Sep 17 00:00:00 2001 From: liufumingren Date: Wed, 25 Mar 2026 23:26:10 +0800 Subject: [PATCH 011/550] chore: sync updates and daylog 2026-03-26 --- AI_TOOLBOX.md | 116 +++ app/service/apiMethods/user.js | 4 + app/service/main.js | 114 +++ .../systemMethods/order/archiveOrder.js | 5 +- app/service/systemMethods/order/base.js | 93 +- .../systemMethods/order/deliveryOrder.js | 5 +- .../systemMethods/order/expectionOrder.js | 5 +- app/service/systemMethods/order/index.js | 8 +- .../systemMethods/order/pendingOrder.js | 7 +- .../systemMethods/order/reviewOrder.js | 17 +- app/service/systemMethods/print.js | 10 +- app/service/systemMethods/setting/account.js | 60 ++ app/service/systemMethods/stock/index.js | 21 + app/service/systemMethods/stock/warehouse.js | 13 +- app/service/systemMethods/storage/entry.js | 119 +++ .../systemMethods/storage/receiving.js | 19 +- app/service/systems/auth/user.js | 141 ++- app/service/systems/setting/account.js | 418 +++++++++ app/service/systems/stock_store.js | 81 +- app/service/systems/storage/entry.js | 687 +++++++++++++++ app/service/systems/storage/receiving.js | 261 +++--- day.log | Bin 35894 -> 37706 bytes methods/gateway.json | 44 + methods/system.json | 808 +++++++++++++++++- ...gateway.user.bindAccountByTempCode.test.js | 67 ++ .../controller/system.setting.account.test.js | 184 ++++ .../controller/system.storage.entry.test.js | 239 ++++++ test/support/system_method_client.js | 29 + 28 files changed, 3340 insertions(+), 235 deletions(-) create mode 100644 app/service/systemMethods/setting/account.js create mode 100644 app/service/systemMethods/stock/index.js create mode 100644 app/service/systemMethods/storage/entry.js create mode 100644 app/service/systems/setting/account.js create mode 100644 app/service/systems/storage/entry.js create mode 100644 test/app/controller/gateway.user.bindAccountByTempCode.test.js create mode 100644 test/app/controller/system.setting.account.test.js create mode 100644 test/app/controller/system.storage.entry.test.js diff --git a/AI_TOOLBOX.md b/AI_TOOLBOX.md index 8f7af4f..2ecaf48 100644 --- a/AI_TOOLBOX.md +++ b/AI_TOOLBOX.md @@ -475,4 +475,120 @@ npx egg-bin test test/app/controller/system.user.info.web.test.js test/app/contr 1. 先查 `user.info` 返回中的 `employees_id`、`store_id`、`platform_code` 2. 确认请求头是否为 `platform=web`、`project=all` 3. 若仍为空,检查账号角色授权与当前激活角色是否存在 + +## 13. setting.account 接口说明(system) + +适用入口:`POST /system?method=setting.account.xxx` + +### 13.1 setting.account.list + +用途:查询当前主体下工号列表(默认只返回启用工号)。 + +入参(body): +- `status`(number,可选):状态筛选,默认 `1` +- `includeDisabled`(boolean,可选):`true` 时包含停用工号 + +返回(`data[]` 关键字段): +- `employee_id`:工号 ID +- `account_id`:账号 ID +- `store_id`:主体 ID +- `real_name`:工号姓名 +- `status`:工号状态(`1` 启用 / `0` 停用) +- `username` / `phone` / `email`:账号基础信息 +- `avatar_file_id` / `avatar_url`:头像信息 + +### 13.2 setting.account.add + +用途:新增工号;手机号存在则复用账号,不存在则创建账号并绑定工号。 + +入参(body): +- `phone`(string,必填):11 位手机号 +- `real_name`(string,必填):工号姓名 +- `role_id`(number,可选):不传时继承当前操作人工号角色 +- `username`(string,可选):仅新建账号时生效 +- `password`(string,可选):仅新建账号时生效,默认 `111111` +- `email`(string,可选):仅新建账号时生效 + +返回(`data` 关键字段): +- `employee_id` / `account_id` / `role_id` +- `is_new_account`:是否本次新建账号 +- `phone` / `username` + +错误码: +- `400`:参数错误、手机号格式错误、保留名称限制 +- `409`:账号禁用、重复绑定、用户名冲突 + +### 13.3 setting.account.delete + +用途:停用工号绑定,不删除底层账号。 + +入参(body): +- `employee_id`(number,必填) + +返回(`data`): +- `employee_id` / `account_id` +- `status`:固定 `deleted` +- `already_deleted`(可选):原本已是停用状态 + +### 13.4 setting.account.update + +用途:更新工号姓名和/或头像引用。 + +入参(body): +- `employee_id`(number,必填) +- `real_name`(string,可选) +- `file_id`(number,可选):头像文件 ID + +约束:`real_name` 与 `file_id` 至少传一个。 + +返回(`data`): +- 更新后的工号完整信息(同 list 列表项结构) + +### 13.5 代码分层约定 + +- 对外 method 包装层:`app/service/systemMethods/setting/account.js` +- 业务实现层:`app/service/systems/setting/account.js` +- 约定:非暴露辅助函数与业务逻辑统一下沉到 `systems`,`systemMethods` 只保留出口包装。 + +## 14. where 参数统一规范(强制) + +适用范围:所有包含 `where` 筛选条件的 `/system` 接口。 + +### 14.1 标准结构 + +`where` 必须使用统一条件对象格式: + +```json +{ + "where": { + "item_code": { "operator": "like", "value": "SKU" }, + "status": { "operator": "eq", "value": "created" }, + "quantity": { "operator": "ge", "type": "number", "value": "10" }, + "create_at": { "operator": "between", "type": "date", "value": ["2026-03-01", "2026-03-31"] }, + "quickWhere": { "operator": "like", "type": "text", "value": "关键字" } + } +} +``` + +### 14.2 统一处理入口 + +- `where` 统一在 `app/service/main.js` 中处理:`prepareWhereContext(data, options)`。 +- 处理后上下文约定: + - `ctx.where`:标准化后的 where 条件对象(含 `operator/value/type`) + - `ctx.whereValue`:仅提取 value 的兼容对象(给旧逻辑渐进兼容) + - `ctx.whereParsed`:基于 `app/lib/query_condition_parser.js` 解析后的动态条件结构 + +### 14.3 实施规则 + +- 所有 method 层(`systemMethods`)收到 `where` 后,必须先调用 `prepareWhereContext`。 +- 所有 systems 层查询逻辑优先读取 `ctx.where` / `ctx.whereParsed`,不得重复定义另一套 where 规则。 +- 历史简写结构(如 `where: { status: 1 }`)允许输入,但会在 main 层自动标准化为条件对象。 + +### 14.4 回归覆盖建议 + +- 至少验证:空 where、eq、like、in、between、quickWhere。 +- 对日志中高频接口优先回归: + - `print.getList` + - `storage.entry.list` + - `stock.warehouse.list` \ No newline at end of file diff --git a/app/service/apiMethods/user.js b/app/service/apiMethods/user.js index fabcc1c..4ba9f2a 100644 --- a/app/service/apiMethods/user.js +++ b/app/service/apiMethods/user.js @@ -6,6 +6,10 @@ class UserApiService extends Service { async getUserByTempCode(data) { return await this.ctx.service.systems.auth.user.getUserByTempCode(data); } + + async bindAccountByTempCode(data) { + return await this.ctx.service.systems.auth.user.bindAccountByTempCode(data); + } } module.exports = UserApiService; \ No newline at end of file diff --git a/app/service/main.js b/app/service/main.js index e12c300..e0e518f 100644 --- a/app/service/main.js +++ b/app/service/main.js @@ -1,6 +1,7 @@ 'use strict'; const Service = require('egg').Service; +const { parseWhereConditions } = require('../lib/query_condition_parser'); class MainService extends Service { constructor(ctx) { @@ -85,6 +86,119 @@ class MainService extends Service { }; } + isPlainObject(value) { + return value && typeof value === 'object' && !Array.isArray(value); + } + + normalizeWhereCondition(fieldKey, condition) { + const isQuickWhere = fieldKey === 'quickWhere'; + + if (this.isPlainObject(condition)) { + const hasStandardKeys = [ 'value', 'operator', 'type', 'field', 'values' ] + .some(key => Object.prototype.hasOwnProperty.call(condition, key)); + + if (hasStandardKeys) { + const normalized = { + ...condition, + }; + + if (!Object.prototype.hasOwnProperty.call(normalized, 'value') && Object.prototype.hasOwnProperty.call(normalized, 'values')) { + normalized.value = normalized.values; + delete normalized.values; + } + + if (!Object.prototype.hasOwnProperty.call(normalized, 'operator') || !normalized.operator) { + normalized.operator = Array.isArray(normalized.value) ? 'in' : (isQuickWhere ? 'like' : 'eq'); + } + + if (isQuickWhere) { + normalized.operator = normalized.operator || 'like'; + normalized.type = normalized.type || 'text'; + } + + if ((normalized.operator === 'between' || normalized.operator === 'notbetween') && this.isPlainObject(normalized.value)) { + const start = normalized.value.start ?? normalized.value.from ?? normalized.value.begin; + const end = normalized.value.end ?? normalized.value.to ?? normalized.value.finish; + normalized.value = [ start, end ]; + } + + return normalized; + } + } + + if (isQuickWhere) { + return { + operator: 'like', + type: 'text', + value: condition, + }; + } + + return { + operator: Array.isArray(condition) ? 'in' : 'eq', + value: condition, + }; + } + + normalizeWhereParams(whereInput = {}) { + if (!this.isPlainObject(whereInput)) { + return {}; + } + + const normalized = {}; + for (const [ fieldKey, condition ] of Object.entries(whereInput)) { + normalized[fieldKey] = this.normalizeWhereCondition(fieldKey, condition); + } + return normalized; + } + + extractWhereValues(normalizedWhere = {}) { + if (!this.isPlainObject(normalizedWhere)) { + return {}; + } + + const whereValues = {}; + for (const [ fieldKey, condition ] of Object.entries(normalizedWhere)) { + if (this.isPlainObject(condition) && Object.prototype.hasOwnProperty.call(condition, 'value')) { + whereValues[fieldKey] = condition.value; + } else { + whereValues[fieldKey] = condition; + } + } + return whereValues; + } + + prepareWhereContext(data = {}, options = {}) { + const specialFieldMap = this.isPlainObject(options.specialFieldMap) ? options.specialFieldMap : {}; + const rawWhere = this.isPlainObject(data && data.where) ? data.where : {}; + const normalizedWhere = this.normalizeWhereParams(rawWhere); + const parsed = parseWhereConditions({ + where: normalizedWhere, + app: this.app, + specialFieldMap, + }); + + if (!parsed.ok) { + throw new Error(`where 参数解析失败: ${parsed.reason}`); + } + + const whereValues = this.extractWhereValues(normalizedWhere); + this.ctx.whereRaw = rawWhere; + this.ctx.where = normalizedWhere; + this.ctx.whereValue = whereValues; + this.ctx.whereParsed = parsed.result; + + if (this.isPlainObject(data)) { + data.where = normalizedWhere; + } + + return { + where: normalizedWhere, + whereValue: whereValues, + parsed: parsed.result, + }; + } + async findQimenAppWithContract(appkey, customerId, warehouseCode) { const { app } = this; const cacheKey = `contract:${appkey}:${customerId}:${warehouseCode}`; diff --git a/app/service/systemMethods/order/archiveOrder.js b/app/service/systemMethods/order/archiveOrder.js index e304684..5f11efc 100644 --- a/app/service/systemMethods/order/archiveOrder.js +++ b/app/service/systemMethods/order/archiveOrder.js @@ -16,10 +16,11 @@ class ArchiveOrderService extends OrderBaseService { try { const warehouseId = this.ensureWarehouseId(data); const { DeliveryModel } = await this.getOrderModels(warehouseId); - const whereData = data.where || {}; + this.prepareWhereContext(data); + const whereData = this.ctx.where || {}; const where = this.buildWhere(whereData, warehouseId); - const hasOutboundFilter = whereData.outbound_status !== undefined && whereData.outbound_status !== null && whereData.outbound_status !== ''; + const hasOutboundFilter = this.hasWhereValue(whereData, 'outbound_status'); if (!hasOutboundFilter) { where.outbound_status = 'fin'; } diff --git a/app/service/systemMethods/order/base.js b/app/service/systemMethods/order/base.js index 89ea602..9734701 100644 --- a/app/service/systemMethods/order/base.js +++ b/app/service/systemMethods/order/base.js @@ -39,6 +39,34 @@ class OrderBaseService extends MainService { } } + getWhereCondition(whereData = {}, key) { + const condition = whereData[key]; + if (condition && typeof condition === 'object' && Object.prototype.hasOwnProperty.call(condition, 'value')) { + return condition; + } + return { + operator: 'eq', + value: condition, + }; + } + + getWhereValue(whereData = {}, key) { + return this.getWhereCondition(whereData, key).value; + } + + getWhereOperator(whereData = {}, key, defaultOperator = 'eq') { + const condition = this.getWhereCondition(whereData, key); + return String(condition.operator || defaultOperator).toLowerCase(); + } + + hasWhereValue(whereData = {}, key) { + const value = this.getWhereValue(whereData, key); + if (value === undefined || value === null) return false; + if (typeof value === 'string' && value.trim() === '') return false; + if (Array.isArray(value) && value.length === 0) return false; + return true; + } + buildWhere(whereData = {}, warehouseId) { const { Op } = this.app.Sequelize; const where = { warehouse_id: warehouseId }; @@ -64,35 +92,68 @@ class OrderBaseService extends MainService { ]; for (const key of eqFields) { - if (whereData[key] !== undefined && whereData[key] !== null && whereData[key] !== '') { - where[key] = whereData[key]; + if (!this.hasWhereValue(whereData, key)) { + continue; + } + + const value = this.getWhereValue(whereData, key); + const operator = this.getWhereOperator(whereData, key); + + if (operator === 'in') { + where[key] = { + [Op.in]: Array.isArray(value) ? value : [ value ], + }; + } else if (operator === 'notin') { + where[key] = { + [Op.notIn]: Array.isArray(value) ? value : [ value ], + }; + } else if (operator === 'ne') { + where[key] = { + [Op.ne]: value, + }; + } else if (operator === 'like' || operator === 'contains') { + where[key] = { + [Op.like]: `%${value}%`, + }; + } else { + where[key] = value; } } - if (whereData.delivery_order_code) { - where.delivery_order_code = { [Op.like]: `%${whereData.delivery_order_code}%` }; + if (this.hasWhereValue(whereData, 'delivery_order_code')) { + const value = this.getWhereValue(whereData, 'delivery_order_code'); + const operator = this.getWhereOperator(whereData, 'delivery_order_code', 'like'); + if (operator === 'eq') { + where.delivery_order_code = value; + } else { + where.delivery_order_code = { [Op.like]: `%${value}%` }; + } } - if (Array.isArray(whereData.delivery_order_codes) && whereData.delivery_order_codes.length > 0) { - where.delivery_order_code = { [Op.in]: whereData.delivery_order_codes }; + const deliveryOrderCodes = this.getWhereValue(whereData, 'delivery_order_codes'); + if (Array.isArray(deliveryOrderCodes) && deliveryOrderCodes.length > 0) { + where.delivery_order_code = { [Op.in]: deliveryOrderCodes }; } - if (whereData.logistics_name) { - where.logistics_name = { [Op.like]: `%${whereData.logistics_name}%` }; + if (this.hasWhereValue(whereData, 'logistics_name')) { + const value = this.getWhereValue(whereData, 'logistics_name'); + where.logistics_name = { [Op.like]: `%${value}%` }; } - if (whereData.buyer_nick) { - where.buyer_nick = { [Op.like]: `%${whereData.buyer_nick}%` }; + if (this.hasWhereValue(whereData, 'buyer_nick')) { + const value = this.getWhereValue(whereData, 'buyer_nick'); + where.buyer_nick = { [Op.like]: `%${value}%` }; } - if (whereData.mobile) { - where.mobile = { [Op.like]: `%${whereData.mobile}%` }; + if (this.hasWhereValue(whereData, 'mobile')) { + const value = this.getWhereValue(whereData, 'mobile'); + where.mobile = { [Op.like]: `%${value}%` }; } - this.applyDateRange(where, 'create_at', whereData.create_at_start, whereData.create_at_end); - this.applyDateRange(where, 'place_order_time', whereData.place_order_time_start, whereData.place_order_time_end); - this.applyDateRange(where, 'pay_time', whereData.pay_time_start, whereData.pay_time_end); - this.applyDateRange(where, 'delivery_time', whereData.delivery_time_start, whereData.delivery_time_end); + this.applyDateRange(where, 'create_at', this.getWhereValue(whereData, 'create_at_start'), this.getWhereValue(whereData, 'create_at_end')); + this.applyDateRange(where, 'place_order_time', this.getWhereValue(whereData, 'place_order_time_start'), this.getWhereValue(whereData, 'place_order_time_end')); + this.applyDateRange(where, 'pay_time', this.getWhereValue(whereData, 'pay_time_start'), this.getWhereValue(whereData, 'pay_time_end')); + this.applyDateRange(where, 'delivery_time', this.getWhereValue(whereData, 'delivery_time_start'), this.getWhereValue(whereData, 'delivery_time_end')); return where; } diff --git a/app/service/systemMethods/order/deliveryOrder.js b/app/service/systemMethods/order/deliveryOrder.js index 1acd085..1094439 100644 --- a/app/service/systemMethods/order/deliveryOrder.js +++ b/app/service/systemMethods/order/deliveryOrder.js @@ -17,10 +17,11 @@ class DeliveryOrderService extends OrderBaseService { const warehouseId = this.ensureWarehouseId(data); const { Op } = this.app.Sequelize; const { DeliveryModel } = await this.getOrderModels(warehouseId); - const whereData = data.where || {}; + this.prepareWhereContext(data); + const whereData = this.ctx.where || {}; const where = this.buildWhere(whereData, warehouseId); - const hasOutboundFilter = whereData.outbound_status !== undefined && whereData.outbound_status !== null && whereData.outbound_status !== ''; + const hasOutboundFilter = this.hasWhereValue(whereData, 'outbound_status'); if (!hasOutboundFilter) { where.outbound_status = { [Op.ne]: 'none' }; } diff --git a/app/service/systemMethods/order/expectionOrder.js b/app/service/systemMethods/order/expectionOrder.js index 0f066ac..f32cfac 100644 --- a/app/service/systemMethods/order/expectionOrder.js +++ b/app/service/systemMethods/order/expectionOrder.js @@ -17,7 +17,8 @@ class ExpectionOrderService extends OrderBaseService { const warehouseId = this.ensureWarehouseId(data); const { Op } = this.app.Sequelize; const { DeliveryModel } = await this.getOrderModels(warehouseId); - const whereData = data.where || {}; + this.prepareWhereContext(data); + const whereData = this.ctx.where || {}; const where = this.buildWhere(whereData, warehouseId); const hasExceptionFilter = [ @@ -31,7 +32,7 @@ class ExpectionOrderService extends OrderBaseService { 'claim_status', 'outbound_status', 'intercept_status', - ].some(key => whereData[key] !== undefined && whereData[key] !== null && whereData[key] !== ''); + ].some(key => this.hasWhereValue(whereData, key)); if (!hasExceptionFilter) { where[Op.or] = [ diff --git a/app/service/systemMethods/order/index.js b/app/service/systemMethods/order/index.js index 7bf532b..bb2a236 100644 --- a/app/service/systemMethods/order/index.js +++ b/app/service/systemMethods/order/index.js @@ -16,7 +16,9 @@ class OrderIndexService extends OrderBaseService { try { const warehouseId = this.ensureWarehouseId(data); const { DeliveryModel } = await this.getOrderModels(warehouseId); - const where = this.buildWhere(data.where || {}, warehouseId); + this.prepareWhereContext(data); + const whereData = this.ctx.where || {}; + const where = this.buildWhere(whereData, warehouseId); const { page, pageSize, offset } = this.getPagination(data.pagination); const result = await DeliveryModel.findAndCountAll({ @@ -97,7 +99,9 @@ class OrderIndexService extends OrderBaseService { const warehouseId = this.ensureWarehouseId(data); const { Sequelize } = this.app; const { DeliveryModel } = await this.getOrderModels(warehouseId); - const where = this.buildWhere(data.where || {}, warehouseId); + this.prepareWhereContext(data); + const whereData = this.ctx.where || {}; + const where = this.buildWhere(whereData, warehouseId); const total = await DeliveryModel.count({ where }); const byStatusRows = await DeliveryModel.findAll({ diff --git a/app/service/systemMethods/order/pendingOrder.js b/app/service/systemMethods/order/pendingOrder.js index 4c8d655..912dbce 100644 --- a/app/service/systemMethods/order/pendingOrder.js +++ b/app/service/systemMethods/order/pendingOrder.js @@ -17,11 +17,12 @@ class PendingOrderService extends OrderBaseService { const warehouseId = this.ensureWarehouseId(data); const { Op } = this.app.Sequelize; const { DeliveryModel } = await this.getOrderModels(warehouseId); - const whereData = data.where || {}; + this.prepareWhereContext(data); + const whereData = this.ctx.where || {}; const where = this.buildWhere(whereData, warehouseId); - const hasStatusFilter = whereData.status !== undefined && whereData.status !== null && whereData.status !== ''; - const hasOutboundFilter = whereData.outbound_status !== undefined && whereData.outbound_status !== null && whereData.outbound_status !== ''; + const hasStatusFilter = this.hasWhereValue(whereData, 'status'); + const hasOutboundFilter = this.hasWhereValue(whereData, 'outbound_status'); if (!hasStatusFilter) { where.status = { [Op.in]: [ 'pedding', 'created' ] }; diff --git a/app/service/systemMethods/order/reviewOrder.js b/app/service/systemMethods/order/reviewOrder.js index ad994b8..be546c6 100644 --- a/app/service/systemMethods/order/reviewOrder.js +++ b/app/service/systemMethods/order/reviewOrder.js @@ -17,19 +17,26 @@ class ReviewOrderService extends OrderBaseService { const warehouseId = this.ensureWarehouseId(data); const { Op } = this.app.Sequelize; const { DeliveryModel } = await this.getOrderModels(warehouseId); - const whereData = data.where || {}; + this.prepareWhereContext(data); + const whereData = this.ctx.where || {}; const where = this.buildWhere(whereData, warehouseId); - const hasInspectionFilter = whereData.inspection_status !== undefined && whereData.inspection_status !== null && whereData.inspection_status !== ''; + const hasInspectionFilter = this.hasWhereValue(whereData, 'inspection_status'); if (!hasInspectionFilter) { where.inspection_status = { [Op.ne]: 'none' }; } - if (whereData.operator_name) { - where.operator_name = { [Op.like]: `%${whereData.operator_name}%` }; + if (this.hasWhereValue(whereData, 'operator_name')) { + const operatorName = this.getWhereValue(whereData, 'operator_name'); + where.operator_name = { [Op.like]: `%${operatorName}%` }; } - this.applyDateRange(where, 'operate_time', whereData.operate_time_start, whereData.operate_time_end); + this.applyDateRange( + where, + 'operate_time', + this.getWhereValue(whereData, 'operate_time_start'), + this.getWhereValue(whereData, 'operate_time_end') + ); const { page, pageSize, offset } = this.getPagination(data.pagination); const result = await DeliveryModel.findAndCountAll({ diff --git a/app/service/systemMethods/print.js b/app/service/systemMethods/print.js index 8b32985..302f241 100644 --- a/app/service/systemMethods/print.js +++ b/app/service/systemMethods/print.js @@ -205,12 +205,14 @@ class PrintService extends MainService { const { ctx } = this; console.log('ctx.user in PrintService constructor', ctx.user); const warehouse_id = ctx.user.store_id; - // TODO: 需根据实际分页和条件查询调整 - const { page = 1, pageSize = 20, where = {} } = data; + const requestData = data && typeof data === 'object' ? data : {}; + const { whereValue } = this.prepareWhereContext(requestData); + const { page = 1, pageSize = 20 } = requestData; // 字段过滤 const filter = {}; [ 'id', 'name', 'computer_id', 'custom_barcode' ].forEach(key => { - if (where[key]) filter[key] = where[key]; + const value = whereValue[key]; + if (value !== undefined && value !== null && value !== '') filter[key] = value; }); filter.warehouse_id = warehouse_id; filter.deleted = 0; @@ -276,7 +278,7 @@ class PrintService extends MainService { totalPages: Math.ceil(total / pageSize), }, queryInfo: { - conditions: where, + conditions: this.ctx.where || {}, hasBarcodeSearch: false, sortField: 'id', sortOrder: 'DESC', diff --git a/app/service/systemMethods/setting/account.js b/app/service/systemMethods/setting/account.js new file mode 100644 index 0000000..cf89f05 --- /dev/null +++ b/app/service/systemMethods/setting/account.js @@ -0,0 +1,60 @@ +'use strict'; + +const MainService = require('../../main'); + +class accountService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'getAccountInfo,updatePassword,list,add,delete,update'; + const _noNeedLog = '*'; + const _noNeedAuth = 'getAccountInfo,updatePassword,list,add,delete,update'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + async callSystemAccount(methodName, data, defaultMessage) { + const { service } = this; + try { + const result = await service.systems.setting.account[methodName](data); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || defaultMessage, { + code: Number(error.code) || 500, + }); + } + } + + /** + * 账号列表。 + * @param {*} data + */ + async list(data = {}) { + return this.callSystemAccount('list', data, '获取工号列表失败'); + } + + /** + * 新增工号。 + * @param {*} data + */ + async add(data = {}) { + return this.callSystemAccount('add', data, '添加工号失败'); + } + + /** + * 删除工号。 + * @param {*} data + */ + async delete(data = {}) { + return this.callSystemAccount('delete', data, '删除工号失败'); + } + + /** + * 更新工号。 + * @param {*} data + */ + async update(data = {}) { + return this.callSystemAccount('update', data, '更新工号失败'); + } +} + +module.exports = accountService; \ No newline at end of file diff --git a/app/service/systemMethods/stock/index.js b/app/service/systemMethods/stock/index.js new file mode 100644 index 0000000..0ea6c58 --- /dev/null +++ b/app/service/systemMethods/stock/index.js @@ -0,0 +1,21 @@ +'use strict'; + +const MainService = require('../../main'); + +class StockIndexService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'stockWarehouse'; + const _noNeedLog = 'stockWarehouse'; + const _noNeedAuth = 'stockWarehouse'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + // Legacy alias: stock.stockWarehouse -> stock.warehouse.list + async stockWarehouse(data = {}) { + return await this.ctx.service.systemMethods.stock.warehouse.list(data); + } +} + +module.exports = StockIndexService; diff --git a/app/service/systemMethods/stock/warehouse.js b/app/service/systemMethods/stock/warehouse.js index 87c2acb..acd29ce 100644 --- a/app/service/systemMethods/stock/warehouse.js +++ b/app/service/systemMethods/stock/warehouse.js @@ -21,7 +21,18 @@ class WarehouseService extends MainService { */ async list(data = {}) { const { service } = this; - const { pagination, where } = data; + const { pagination } = data; + const { where } = this.prepareWhereContext(data, { + specialFieldMap: { + barcode: { + bucket: 'barcode', + }, + prohibited_type: { + bucket: 'prohibited', + field: 'id', + }, + }, + }); const result = await service.systems.stockStore.getWarehouseStock(where, pagination); return this.success('ok', result); } diff --git a/app/service/systemMethods/storage/entry.js b/app/service/systemMethods/storage/entry.js new file mode 100644 index 0000000..da68a84 --- /dev/null +++ b/app/service/systemMethods/storage/entry.js @@ -0,0 +1,119 @@ +'use strict'; +const MainService = require('../../main'); +/** + * 系统方法层:storage.entry(入库单相关接口包装层)。 + * 主要职责:统一包装系统方法接口,处理权限、日志等公共逻辑,调用底层 service 实现业务功能。 + * 注意:当前实现仅为包装层,实际业务逻辑完全依赖底层 service 的方法实现。 + */ +class entryService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list,get,create,addDetail,deleteDetail,detailChange,cancel,completeEntry'; + const _noNeedLog = 'list,get,addDetail,deleteDetail,detailChange'; + const _noNeedAuth = 'list,get,create,addDetail,deleteDetail,detailChange,cancel,completeEntry'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 入库单列表查询。 + * @param {Object} data 请求体 + * @param {Object} [data.pagination] 分页参数 + * @param {Object} [data.where] 动态筛选条件 + * @param {Object} [data.sort] 排序参数 + * @return {Promise} 统一 success 包装 + */ + async list(data = {}) { + const { service } = this; + const { pagination, sort } = data; + const { where } = this.prepareWhereContext(data, { + specialFieldMap: { + quickWhere: { + bucket: 'quick', + }, + }, + }); + const result = await service.systems.storage.entry.list(where, pagination, sort); + return this.success('ok', result); + } + + /** + * 查询入库单详情。 + * @param {Object} data 请求体 + * @param {number} [data.id] 入库单ID + * @param {string} [data.entry_order_code] 入库单号 + * @return {Promise} 统一 success 包装 + */ + async get(data = {}) { + const { service } = this; + const result = await service.systems.storage.entry.get(data); + return this.success('ok', result); + } + + /** + * 新建入库单。 + * @param {Object} data 请求体 + * @return {Promise} 统一 success 包装 + */ + async create(data = {}) { + const { service } = this; + const result = await service.systems.storage.entry.create(data); + return this.success('ok', result); + } + + /** + * 新增入库明细。 + * @param {Object} data 请求体 + * @return {Promise} 统一 success 包装 + */ + async addDetail(data = {}) { + const { service } = this; + const result = await service.systems.storage.entry.addDetail(data); + return this.success('ok', result); + } + + /** + * 删除入库明细。 + * @param {Object} data 请求体 + * @return {Promise} 统一 success 包装 + */ + async deleteDetail(data = {}) { + const { service } = this; + const result = await service.systems.storage.entry.deleteDetail(data); + return this.success('ok', result); + } + + /** + * 修改入库明细。 + * @param {Object} data 请求体 + * @return {Promise} 统一 success 包装 + */ + async detailChange(data = {}) { + const { service } = this; + const result = await service.systems.storage.entry.detailChange(data); + return this.success('ok', result); + } + + /** + * 作废入库单。 + * @param {Object} data 请求体 + * @return {Promise} 统一 success 包装 + */ + async cancel(data = {}) { + const { service } = this; + const result = await service.systems.storage.entry.cancel(data); + return this.success('ok', result); + } + + /** + * 完成入库单。 + * @param {Object} data 请求体 + * @return {Promise} 统一 success 包装 + */ + async completeEntry(data = {}) { + const { service } = this; + const result = await service.systems.storage.entry.completeEntry(data); + return this.success('ok', result); + } +} +module.exports = entryService; \ No newline at end of file diff --git a/app/service/systemMethods/storage/receiving.js b/app/service/systemMethods/storage/receiving.js index f91ef63..839b8ee 100644 --- a/app/service/systemMethods/storage/receiving.js +++ b/app/service/systemMethods/storage/receiving.js @@ -1,7 +1,11 @@ 'use strict'; const MainService = require('../../main'); - +/** + * 系统方法层:storage.receiving(收货单相关接口包装层)。 + * 主要职责:统一包装系统方法接口,处理权限、日志等公共逻辑,调用底层 service 实现业务功能。 + * 注意:当前实现仅为包装层,实际业务逻辑完全依赖底层 service 的方法实现。 + */ class configService extends MainService { constructor(ctx) { super(ctx); @@ -21,10 +25,15 @@ class configService extends MainService { */ async getReceivingList(data) { const { service } = this; - const { pagination, where } = data; - console.log('where', where); - console.log('service.systems.storage.receiving', service.systems.storage.index.index); - const result = await service.systems.storage.receiving.getReceivingList(where, pagination); + const { pagination, sort } = data; + const { where } = this.prepareWhereContext(data, { + specialFieldMap: { + quickWhere: { + bucket: 'quick', + }, + }, + }); + const result = await service.systems.storage.receiving.getReceivingList(where, pagination, sort); return this.success('ok', result); } diff --git a/app/service/systems/auth/user.js b/app/service/systems/auth/user.js index 848d1ff..ea88807 100644 --- a/app/service/systems/auth/user.js +++ b/app/service/systems/auth/user.js @@ -641,6 +641,127 @@ class UserService extends Service { } } + /** + * 账号绑定:供 ye4s 扫码后回调,按临时码绑定到指定 ye4s_user.id + * @param {Object} data + * @return {Object} + */ + async bindAccountByTempCode(data = {}) { + const { ctx, app } = this; + try { + const code = typeof data.code === 'string' ? data.code.trim() : ''; + const rawYe4sUserId = data.ye4s_user_id ?? data.ye4sUserId; + const ye4sUserId = Number(rawYe4sUserId); + + if (!code) { + return { + success: false, + code: 0, + data: null, + message: '缺少绑定码 code', + }; + } + + if (!this.parseWechatBindCode(code)) { + return { + success: false, + code: 0, + data: null, + message: '无效的绑定码格式', + }; + } + + if (!Number.isFinite(ye4sUserId) || ye4sUserId <= 0) { + return { + success: false, + code: 0, + data: null, + message: '缺少有效的 ye4s_user_id', + }; + } + + const userResult = await this.getUserByTempCode({ code }); + if (!userResult || !userResult.success) { + return { + success: false, + code: 0, + data: null, + message: userResult && userResult.message ? userResult.message : '绑定码不存在或已过期', + }; + } + + const accountId = Number(userResult.data && userResult.data.account_id); + if (!Number.isFinite(accountId) || accountId <= 0) { + return { + success: false, + code: 0, + data: null, + message: '绑定码未匹配到有效账号', + }; + } + + const ye4sClient = ctx.app.mysql.get('ye4s'); + const ye4sUser = await ye4sClient.get('ye4s_user', { id: ye4sUserId }); + if (!ye4sUser) { + return { + success: false, + code: 0, + data: null, + message: 'ye4s 用户不存在', + }; + } + + const updateRet = await ye4sClient.update('ye4s_user', { + id: ye4sUserId, + wms_account_id: accountId, + tmp_code: code, + }); + + const boundState = { + account_id: accountId, + status: 'bound', + code, + updated_at: new Date().toISOString(), + next_db_check_at: Date.now() + WECHAT_BIND_RECHECK_INTERVAL_MS, + ye4s_user_id: ye4sUserId, + }; + + await Promise.all([ + this.setWechatBindCodeCache(code, boundState, WECHAT_BIND_CACHE_TTL_SECONDS), + this.setWechatBindCache(this.getWechatBindCacheKey(accountId), boundState, WECHAT_BIND_CACHE_TTL_SECONDS), + ]); + + await this.publishWechatBindEvent(accountId, { + status: 'bound', + code, + source: 'gateway-bind', + }); + + return { + success: true, + code: 200, + data: { + account_id: accountId, + ye4s_user_id: ye4sUserId, + code, + status: 'bound', + source: 'gateway-bind', + affected_rows: Number(updateRet && updateRet.affectedRows ? updateRet.affectedRows : 0), + updated_at: boundState.updated_at, + }, + message: '绑定成功', + }; + } catch (error) { + app.coreLogger.error(`账号绑定失败: ${error.message}`); + return { + success: false, + code: 0, + data: null, + message: '绑定失败,请稍后重试', + }; + } + } + /** * 解绑微信:清理 ye4s_user 中与当前账号关联的数据 * @return {Object} @@ -672,13 +793,19 @@ class UserService extends Service { for (const row of bindRows) { const rowCode = typeof row.tmp_code === 'string' ? row.tmp_code.trim() : ''; if (rowCode) { - await this.setWechatBindCodeCache(rowCode, null, 1); + await this.setWechatBindCodeCache(rowCode, { + account_id: accountId, + status: 'unbound', + code: rowCode, + updated_at: new Date().toISOString(), + next_db_check_at: Date.now() + WECHAT_BIND_RECHECK_INTERVAL_MS, + ye4s_user_id: row.id || null, + }, WECHAT_BIND_CACHE_TTL_SECONDS); } try { const ret = await ye4sClient.update('ye4s_user', { id: row.id, wms_account_id: null, - tmp_code: null, }); affectedRows += Number(ret && ret.affectedRows ? ret.affectedRows : 0); } catch (err) { @@ -686,7 +813,6 @@ class UserService extends Service { const ret = await ye4sClient.update('ye4s_user', { id: row.id, wms_account_id: 0, - tmp_code: '', }); affectedRows += Number(ret && ret.affectedRows ? ret.affectedRows : 0); } @@ -695,7 +821,14 @@ class UserService extends Service { const cacheKey = this.getWechatBindCacheKey(accountId); const cachedState = await this.app.getCacheAsync(cacheKey); if (cachedState && cachedState.code) { - await this.setWechatBindCodeCache(cachedState.code, null, 1); + await this.setWechatBindCodeCache(cachedState.code, { + account_id: accountId, + status: 'unbound', + code: cachedState.code, + updated_at: new Date().toISOString(), + next_db_check_at: Date.now() + WECHAT_BIND_RECHECK_INTERVAL_MS, + ye4s_user_id: cachedState.ye4s_user_id || null, + }, WECHAT_BIND_CACHE_TTL_SECONDS); } await this.setWechatBindCache(cacheKey, null, 1); await this.publishWechatBindEvent(accountId, { diff --git a/app/service/systems/setting/account.js b/app/service/systems/setting/account.js new file mode 100644 index 0000000..27f273e --- /dev/null +++ b/app/service/systems/setting/account.js @@ -0,0 +1,418 @@ +'use strict'; + +const Service = require('egg').Service; + +const RESERVED_EMPLOYEE_NAME = '测试工号保留'; + +class SettingAccountService extends Service { + createError(message, code = 500) { + const error = new Error(message); + error.code = code; + return error; + } + + getCurrentStoreId() { + const storeId = Number(this.ctx.user && this.ctx.user.store_id); + if (!Number.isFinite(storeId) || storeId <= 0) { + throw this.createError('未识别到当前主体,无法操作工号', 400); + } + return storeId; + } + + getCurrentEmployeeId() { + const employeeId = Number(this.ctx.user && this.ctx.user.employees_id); + if (!Number.isFinite(employeeId) || employeeId <= 0) { + return null; + } + return employeeId; + } + + getWmsClient() { + return this.ctx.app.mysql.get('wms'); + } + + normalizePhone(phone) { + return typeof phone === 'string' ? phone.trim() : ''; + } + + isValidPhone(phone) { + return /^1[3-9]\d{9}$/.test(phone); + } + + normalizeName(name) { + return typeof name === 'string' ? name.trim() : ''; + } + + normalizeUsername(username) { + return typeof username === 'string' ? username.trim() : ''; + } + + generateUsername() { + const suffix = `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`; + return `acct_${suffix}`; + } + + async findRawAccountByPhone(phone) { + const rows = await this.getWmsClient().select('wms_account', { + where: { phone }, + columns: [ 'id', 'username', 'phone', 'email', 'real_name', 'status' ], + limit: 1, + }); + return rows && rows.length > 0 ? rows[0] : null; + } + + async findRawAccountByUsername(username) { + const rows = await this.getWmsClient().select('wms_account', { + where: { username }, + columns: [ 'id', 'username', 'phone', 'email', 'real_name', 'status' ], + limit: 1, + }); + return rows && rows.length > 0 ? rows[0] : null; + } + + async getAvatarMeta(employeeId) { + const { ctx } = this; + const avatarRef = await ctx.model.FileReference.findOne({ + where: { + business_type: 'avater', + business_id: String(employeeId), + }, + include: [ + { + model: ctx.model.File, + as: 'file', + attributes: [ 'id', 'file_url', 'file_name' ], + required: false, + }, + ], + order: [[ 'created_at', 'DESC' ]], + }); + + return { + avatar_file_id: Number(avatarRef && avatarRef.file_id ? avatarRef.file_id : 0) || null, + avatar_url: avatarRef && avatarRef.file ? avatarRef.file.file_url : '', + avatar_name: avatarRef && avatarRef.file ? avatarRef.file.file_name : '', + }; + } + + async resolveRoleId(data = {}) { + const { ctx } = this; + const explicitRoleId = Number(data.role_id || data.roleId || 0); + if (Number.isFinite(explicitRoleId) && explicitRoleId > 0) { + const role = await ctx.model.Role.findOne({ + where: { + id: explicitRoleId, + status: 1, + }, + }); + if (!role) { + throw this.createError('指定角色不存在或已禁用', 400); + } + return explicitRoleId; + } + + const currentEmployeeId = this.getCurrentEmployeeId(); + if (!currentEmployeeId) { + throw this.createError('未识别到当前操作人工号,无法继承角色', 400); + } + + const currentRole = await ctx.model.EmployeeRole.findOne({ + where: { employee_id: currentEmployeeId }, + order: [[ 'id', 'ASC' ]], + }); + if (!currentRole) { + throw this.createError('当前操作人工号未绑定角色,无法创建新工号', 400); + } + + return Number(currentRole.role_id); + } + + async formatEmployeeRow(employee) { + const account = await this.getWmsClient().get('wms_account', { + id: employee.account_id, + }); + const avatar = await this.getAvatarMeta(employee.id); + + return { + employee_id: Number(employee.id), + account_id: Number(employee.account_id), + store_id: Number(employee.store_id), + real_name: employee.real_name || '', + status: Number(employee.status), + created_at: employee.created_at, + updated_at: employee.updated_at, + username: account && account.username ? account.username : '', + phone: account && account.phone ? account.phone : '', + email: account && account.email ? account.email : '', + account_real_name: account && account.real_name ? account.real_name : '', + ...avatar, + }; + } + + async list(data = {}) { + const { ctx } = this; + + const storeId = this.getCurrentStoreId(); + const statusFilter = data.includeDisabled === true + ? undefined + : (data.status === 0 || data.status === '0' ? 0 : 1); + + const where = { + store_id: storeId, + }; + if (statusFilter === 0 || statusFilter === 1) { + where.status = statusFilter; + } + + const employees = await ctx.model.AccountStoreEmployee.findAll({ + where, + order: [[ 'created_at', 'DESC' ], [ 'id', 'DESC' ]], + }); + + const list = []; + for (const employee of employees) { + list.push(await this.formatEmployeeRow(employee)); + } + + return { + code: 200, + data: list, + }; + } + + async add(data = {}) { + const { ctx, service } = this; + let createdAccountId = 0; + + try { + const storeId = this.getCurrentStoreId(); + const phone = this.normalizePhone(data.phone); + const realName = this.normalizeName(data.real_name || data.realName); + const password = typeof data.password === 'string' && data.password.trim() + ? data.password.trim() + : '111111'; + + if (!phone) { + throw this.createError('phone 参数不能为空', 400); + } + if (!this.isValidPhone(phone)) { + throw this.createError('phone 格式不正确', 400); + } + if (!realName) { + throw this.createError('real_name 参数不能为空', 400); + } + if (realName === RESERVED_EMPLOYEE_NAME) { + throw this.createError(`新增工号禁止直接使用保留名称 ${RESERVED_EMPLOYEE_NAME}`, 400); + } + + const roleId = await this.resolveRoleId(data); + let account = await this.findRawAccountByPhone(phone); + + if (account && Number(account.status) !== 1) { + throw this.createError('该手机号对应账号已禁用,无法新增工号', 409); + } + + if (!account) { + let username = this.normalizeUsername(data.username); + if (!username) { + username = this.generateUsername(); + } + + const existingUsername = await this.findRawAccountByUsername(username); + if (existingUsername) { + throw this.createError('username 已存在', 409); + } + + const salt = service.systems.auth.user.generateSalt(); + const passwordHash = await service.systems.auth.user.encryptPassword(password, salt); + const email = typeof data.email === 'string' && data.email.trim() + ? data.email.trim() + : `${username}@autotest.local`; + + const insertRet = await this.getWmsClient().insert('wms_account', { + username, + phone, + email, + password_hash: passwordHash, + real_name: realName, + status: 1, + salt, + created_at: new Date(), + updated_at: new Date(), + }); + + createdAccountId = Number(insertRet && insertRet.insertId ? insertRet.insertId : 0); + account = await this.getWmsClient().get('wms_account', { id: createdAccountId }); + } + + const activeBinding = await ctx.model.AccountStoreEmployee.findOne({ + where: { + account_id: account.id, + store_id: storeId, + status: 1, + }, + }); + if (activeBinding) { + throw this.createError('该手机号已绑定当前主体工号', 409); + } + + const { employee, employeeRole } = await service.systems.store.ensureEmployeeRoleBinding({ + accountId: Number(account.id), + storeId, + roleId, + realName, + }); + + await service.systems.auth.user.clearUserCache(Number(account.id)); + + const formatted = await this.formatEmployeeRow(employee); + return { + code: 200, + data: { + ...formatted, + role_id: Number(employeeRole.role_id), + is_new_account: createdAccountId > 0, + }, + }; + } catch (error) { + if (createdAccountId > 0) { + await this.getWmsClient().delete('wms_account', { id: createdAccountId }); + } + throw error; + } + } + + async delete(data = {}) { + const { ctx, service } = this; + + const storeId = this.getCurrentStoreId(); + const currentEmployeeId = this.getCurrentEmployeeId(); + const employeeId = Number(data.employee_id || data.id || 0); + + if (!employeeId) { + throw this.createError('employee_id 参数不能为空', 400); + } + if (currentEmployeeId && employeeId === currentEmployeeId) { + throw this.createError('不允许删除当前登录工号', 400); + } + + const employee = await ctx.model.AccountStoreEmployee.findOne({ + where: { + id: employeeId, + store_id: storeId, + }, + }); + if (!employee) { + throw this.createError('工号不存在或无权限删除', 404); + } + + if (Number(employee.status) !== 1) { + return { + code: 200, + data: { + employee_id: employeeId, + account_id: Number(employee.account_id), + status: 'deleted', + already_deleted: true, + }, + }; + } + + await employee.update({ + status: 0, + updated_at: new Date(), + }); + + await ctx.model.AccountPlatformActive.destroy({ + where: { + employee_id: employeeId, + }, + }); + + await service.systems.auth.user.clearUserCache(Number(employee.account_id)); + + return { + code: 200, + data: { + employee_id: employeeId, + account_id: Number(employee.account_id), + status: 'deleted', + }, + }; + } + + async update(data = {}) { + const { ctx, service } = this; + + const storeId = this.getCurrentStoreId(); + const employeeId = Number(data.employee_id || data.id || 0); + const hasRealName = Object.prototype.hasOwnProperty.call(data, 'real_name') || Object.prototype.hasOwnProperty.call(data, 'realName'); + const hasFileId = Object.prototype.hasOwnProperty.call(data, 'file_id') || Object.prototype.hasOwnProperty.call(data, 'avatar_file_id') || Object.prototype.hasOwnProperty.call(data, 'fileId'); + const realName = this.normalizeName(data.real_name || data.realName); + const fileId = Number(data.file_id || data.avatar_file_id || data.fileId || 0); + + if (!employeeId) { + throw this.createError('employee_id 参数不能为空', 400); + } + if (!hasRealName && !hasFileId) { + throw this.createError('至少需要更新 real_name 或 file_id', 400); + } + if (hasRealName && !realName) { + throw this.createError('real_name 参数不能为空', 400); + } + if (hasFileId && !fileId) { + throw this.createError('file_id 参数不能为空', 400); + } + + const employee = await ctx.model.AccountStoreEmployee.findOne({ + where: { + id: employeeId, + store_id: storeId, + status: 1, + }, + }); + if (!employee) { + throw this.createError('工号不存在或无权限更新', 404); + } + + if (hasRealName && realName !== employee.real_name) { + await employee.update({ + real_name: realName, + updated_at: new Date(), + }); + } + + if (hasFileId) { + const file = await ctx.model.File.findOne({ + where: { + id: fileId, + is_deleted: false, + }, + }); + if (!file) { + throw this.createError('头像文件不存在', 404); + } + + await service.systems.file.ReferenceFile({ + id: employeeId, + type: 'avater', + images: [ + { + file_id: fileId, + sort_order: 0, + }, + ], + }); + } + + await service.systems.auth.user.clearUserCache(Number(employee.account_id)); + + const refreshed = await ctx.model.AccountStoreEmployee.findByPk(employeeId); + return { + code: 200, + data: await this.formatEmployeeRow(refreshed), + }; + } +} + +module.exports = SettingAccountService; diff --git a/app/service/systems/stock_store.js b/app/service/systems/stock_store.js index 8d7959d..36fc6e8 100644 --- a/app/service/systems/stock_store.js +++ b/app/service/systems/stock_store.js @@ -1075,44 +1075,53 @@ class stockStoreService extends Service { let barcodeCondition = null; let parsedBarcodeInput = null; - // 处理动态查询条件 - if (where && Object.keys(where).length > 0) { - const parsed = parseWhereConditions({ - where, - app, - specialFieldMap: { - barcode: { - bucket: 'barcode', - }, - prohibited_type: { - bucket: 'prohibited', - field: 'id', - }, - }, - }); + const normalizedWhere = ctx.where && typeof ctx.where === 'object' + ? ctx.where + : (where && typeof where === 'object' ? where : {}); - if (!parsed.ok) { - return { - code: 400, - data: { - list: [], - pagination: { - page: parseInt(page), - pageSize: parseInt(pageSize), - total: 0, - totalPages: 0, - hasPrevious: false, - hasNext: false, + // 处理动态查询条件 + if (normalizedWhere && Object.keys(normalizedWhere).length > 0) { + let parsedResult = ctx.whereParsed; + if (!parsedResult || !Array.isArray(parsedResult.dynamicConditions)) { + const parsed = parseWhereConditions({ + where: normalizedWhere, + app, + specialFieldMap: { + barcode: { + bucket: 'barcode', }, - summary: { - total_quantity: 0, - total_locked: 0, - total_available: 0, - total_items: 0, + prohibited_type: { + bucket: 'prohibited', + field: 'id', }, }, - message: `筛选条件解析失败: ${parsed.reason}`, - }; + }); + + if (!parsed.ok) { + return { + code: 400, + data: { + list: [], + pagination: { + page: parseInt(page), + pageSize: parseInt(pageSize), + total: 0, + totalPages: 0, + hasPrevious: false, + hasNext: false, + }, + summary: { + total_quantity: 0, + total_locked: 0, + total_available: 0, + total_items: 0, + }, + }, + message: `筛选条件解析失败: ${parsed.reason}`, + }; + } + + parsedResult = parsed.result; } const { @@ -1120,7 +1129,7 @@ class stockStoreService extends Service { bucketConditions, bucketFlags, rawConditionsByField, - } = parsed.result; + } = parsedResult; const barcodeDynamicConditions = bucketConditions.barcode || []; const prohibitedConditions = bucketConditions.prohibited || []; @@ -1390,7 +1399,7 @@ class stockStoreService extends Service { }, summary, queryInfo: { - conditions: where, + conditions: normalizedWhere, sortField: actualSortField, sortOrder: actualSortOrder, hasBarcodeSearch: hasBarcodeCondition, diff --git a/app/service/systems/storage/entry.js b/app/service/systems/storage/entry.js new file mode 100644 index 0000000..9f18bd1 --- /dev/null +++ b/app/service/systems/storage/entry.js @@ -0,0 +1,687 @@ +'use strict'; + +const Service = require('egg').Service; +const { parseWhereConditions } = require('../../../lib/query_condition_parser'); + +class EntryService extends Service { + /** + * 入库单列表查询,复用 where 解构工具。 + * @param {Object} where 筛选条件对象 + * @param {Object} pageParams 分页参数 + * @param {Object} sortParams 排序参数 + * @return {Promise} code/data/message 结构 + */ + async list(where = {}, pageParams = {}, sortParams = {}) { + const { ctx, app } = this; + const { Sequelize } = app; + const { Op } = Sequelize; + + const page = Math.max(Number(pageParams.page) || 1, 1); + const pageSize = Math.max(Number(pageParams.pageSize) || 20, 1); + + const sortField = sortParams.sortField || 'created_at'; + const sortOrder = String(sortParams.sortOrder || 'DESC').toUpperCase() === 'ASC' ? 'ASC' : 'DESC'; + const validSortFields = [ + 'id', + 'entry_order_code', + 'order_type', + 'order_status', + 'order_create_time', + 'created_at', + 'updated_at', + 'total_order_lines', + ]; + const actualSortField = validSortFields.includes(sortField) ? sortField : 'created_at'; + + const baseWhere = { + warehouse_id: ctx.user.store_id, + is_enabled: 1, + deleted_at: null, + }; + + const normalizedWhere = ctx.where && typeof ctx.where === 'object' + ? { ...ctx.where } + : (where && typeof where === 'object' ? { ...where } : {}); + + let parsedResult = ctx.whereParsed; + if (!parsedResult || !Array.isArray(parsedResult.dynamicConditions)) { + const parsed = parseWhereConditions({ + where: normalizedWhere, + app, + specialFieldMap: { + quickWhere: { + bucket: 'quick', + }, + }, + }); + + if (!parsed.ok) { + return { + code: 400, + message: `筛选条件解析失败: ${parsed.reason}`, + data: { + list: [], + pagination: { + page, + pageSize, + total: 0, + totalPages: 0, + hasPrevious: false, + hasNext: false, + }, + summary: { + total: 0, + pending: 0, + creating: 0, + created: 0, + completed: 0, + cancelled: 0, + }, + }, + }; + } + parsedResult = parsed.result; + } + + const quickWhereInput = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere) + || normalizedWhere.quickWhere + || null; + const quickWhereValue = quickWhereInput && typeof quickWhereInput === 'object' + ? quickWhereInput.value + : null; + + const andConditions = [ baseWhere ]; + if (quickWhereValue !== undefined && quickWhereValue !== null && String(quickWhereValue).trim() !== '') { + const kw = String(quickWhereValue).trim(); + andConditions.push({ + [Op.or]: [ + { entry_order_code: { [Op.like]: `%${kw}%` } }, + { purchase_order_code: { [Op.like]: `%${kw}%` } }, + { supplier_name: { [Op.like]: `%${kw}%` } }, + { store_name: { [Op.like]: `%${kw}%` } }, + { warehouse_name: { [Op.like]: `%${kw}%` } }, + ], + }); + } + + const dynamicConditions = parsedResult.dynamicConditions || []; + if (dynamicConditions.length > 0) { + andConditions.push({ [Op.and]: dynamicConditions }); + } + + const finalWhere = { [Op.and]: andConditions }; + + const include = [ + { + model: ctx.model.Store, + as: 'warehouse', + attributes: [ 'id', 'company_name' ], + required: false, + }, + { + model: ctx.model.Store, + as: 'store', + attributes: [ 'id', 'company_name' ], + required: false, + }, + ]; + + const { count, rows } = await ctx.model.EntryOrder.findAndCountAll({ + where: finalWhere, + include, + order: [[ actualSortField, sortOrder ]], + limit: pageSize, + offset: (page - 1) * pageSize, + distinct: true, + }); + + const statusRows = await ctx.model.EntryOrder.findAll({ + attributes: [ + 'order_status', + [ Sequelize.fn('COUNT', Sequelize.col('id')), 'count' ], + ], + where: finalWhere, + group: [ 'order_status' ], + raw: true, + }); + + const summary = { + total: count, + pending: 0, + creating: 0, + created: 0, + completed: 0, + cancelled: 0, + }; + statusRows.forEach(item => { + const statusKey = String(item.order_status || '').toLowerCase(); + if (Object.prototype.hasOwnProperty.call(summary, statusKey)) { + summary[statusKey] = Number(item.count) || 0; + } + }); + + return { + code: 200, + message: '查询成功', + data: { + list: rows, + pagination: { + page, + pageSize, + total: count, + totalPages: Math.ceil(count / pageSize), + hasPrevious: page > 1, + hasNext: page < Math.ceil(count / pageSize), + }, + summary, + }, + }; + } + + /** + * 查询入库单详情。 + * @param {Object} data 请求体 + * @return {Promise} code/data/message 结构 + */ + async get(data = {}) { + const { ctx } = this; + const id = Number(data.id || 0); + const entryOrderCode = data.entry_order_code ? String(data.entry_order_code).trim() : ''; + + if (!id && !entryOrderCode) { + return { + code: 400, + message: 'id 或 entry_order_code 至少传一个', + data: null, + }; + } + + const where = { + warehouse_id: ctx.user.store_id, + is_enabled: 1, + deleted_at: null, + }; + if (id) { + where.id = id; + } else { + where.entry_order_code = entryOrderCode; + } + + const entryOrder = await ctx.model.EntryOrder.findOne({ + where, + include: [ + { + model: ctx.model.Store, + as: 'warehouse', + attributes: [ 'id', 'company_name' ], + required: false, + }, + { + model: ctx.model.Store, + as: 'store', + attributes: [ 'id', 'company_name' ], + required: false, + }, + { + model: ctx.model.EntryItems, + as: 'items', + include: [ + { + model: ctx.model.StockWarehouse, + as: 'stock', + attributes: [ 'id', 'item_code', 'item_name' ], + required: false, + }, + ], + required: false, + }, + ], + }); + + if (!entryOrder) { + return { + code: 0, + message: '入库单不存在或无权访问', + data: null, + }; + } + + return { + code: 200, + message: '查询成功', + data: { + entryOrder, + }, + }; + } + + generateOrderCode() { + const randomPart = Math.floor(Math.random() * 1000).toString().padStart(3, '0'); + return `ENT${Date.now()}${randomPart}`; + } + + /** + * 创建入库单。 + * @param {Object} data 请求体 + * @return {Promise} code/data/message 结构 + */ + async create(data = {}) { + const { ctx } = this; + const allowedOrderTypes = new Set([ 'SCRK', 'LYRK', 'CCRK', 'CGRK', 'DBRK', 'QTRK', 'B2BRK', 'XNRK' ]); + + const orderType = String(data.order_type || '').trim(); + const storeId = Number(data.store_id || ctx.user.store_id || 0); + + if (!orderType) { + return { + code: 400, + message: 'order_type 必填', + data: null, + }; + } + if (!allowedOrderTypes.has(orderType)) { + return { + code: 400, + message: 'order_type 不合法', + data: null, + }; + } + if (!storeId) { + return { + code: 400, + message: 'store_id 必填', + data: null, + }; + } + + const entryOrderCode = data.entry_order_code && String(data.entry_order_code).trim() !== '' + ? String(data.entry_order_code).trim() + : this.generateOrderCode(); + + const exists = await ctx.model.EntryOrder.findOne({ + where: { + entry_order_code: entryOrderCode, + warehouse_id: ctx.user.store_id, + store_id: storeId, + deleted_at: null, + }, + }); + + if (exists) { + return { + code: 409, + message: '入库单号已存在', + data: { + id: exists.id, + entry_order_code: exists.entry_order_code, + }, + }; + } + + const order = await ctx.model.EntryOrder.create({ + entry_order_code: entryOrderCode, + order_type: orderType, + purchase_order_code: data.purchase_order_code || '', + total_order_lines: Number(data.total_order_lines || 0), + order_create_time: data.order_create_time ? new Date(data.order_create_time) : new Date(), + expect_start_time: data.expect_start_time ? new Date(data.expect_start_time) : null, + expect_end_time: data.expect_end_time ? new Date(data.expect_end_time) : null, + logistics_code: data.logistics_code || '', + logistics_name: data.logistics_name || '', + express_code: data.express_code || '', + supplier_code: data.supplier_code || '', + supplier_name: data.supplier_name || '', + source_type: 'API', + order_status: 'CREATED', + sync_status: 'PENDING', + sync_message: '', + is_enabled: 1, + warehouse_id: ctx.user.store_id, + store_id: storeId, + remark: data.remark || '', + created_at: new Date(), + updated_at: new Date(), + }); + + return { + code: 200, + message: '创建成功', + data: { + id: order.id, + entry_order_code: order.entry_order_code, + }, + }; + } + + async getOwnedEntryOrderById(id) { + const { ctx } = this; + return await ctx.model.EntryOrder.findOne({ + where: { + id, + warehouse_id: ctx.user.store_id, + is_enabled: 1, + deleted_at: null, + }, + }); + } + + /** + * 新增入库明细。 + * @param {Object} data 请求体 + * @return {Promise} code/data/message 结构 + */ + async addDetail(data = {}) { + const { ctx } = this; + const orderId = Number(data.order_id || 0); + const count = Number(data.count || 0); + + if (!orderId) { + return { + code: 400, + message: 'order_id 必填', + data: null, + }; + } + if (!count || count <= 0) { + return { + code: 400, + message: 'count 必须大于 0', + data: null, + }; + } + + const entryOrder = await this.getOwnedEntryOrderById(orderId); + if (!entryOrder) { + return { + code: 404, + message: '入库单不存在或无权访问', + data: null, + }; + } + if (entryOrder.order_status === 'CANCELLED' || entryOrder.order_status === 'COMPLETED') { + return { + code: 400, + message: '当前状态不允许新增明细', + data: null, + }; + } + + const maxLineNo = Number(await ctx.model.EntryItems.max('order_line_no', { + where: { order_id: orderId }, + })) || 0; + + const detail = await ctx.model.EntryItems.create({ + order_id: orderId, + order_line_no: maxLineNo + 1, + item_code: data.item_code || '', + item_id: data.item_id || null, + stock_id: data.stock_id || data.item_id || null, + count, + inventory_type: data.inventory_type || 'ZP', + received_quantity: 0, + confirm_quantity: 0, + owner_code: data.owner_code || '', + out_biz_code: data.out_biz_code || '', + }); + + await entryOrder.update({ + total_order_lines: maxLineNo + 1, + updated_at: new Date(), + }); + + return { + code: 200, + message: '新增明细成功', + data: { + id: detail.id, + order_id: orderId, + }, + }; + } + + /** + * 删除入库明细。 + * @param {Object} data 请求体 + * @return {Promise} code/data/message 结构 + */ + async deleteDetail(data = {}) { + const { ctx } = this; + const detailId = Number(data.id || 0); + + if (!detailId) { + return { + code: 400, + message: 'id 必填', + data: null, + }; + } + + const detail = await ctx.model.EntryItems.findByPk(detailId); + if (!detail) { + return { + code: 404, + message: '明细不存在', + data: null, + }; + } + + const entryOrder = await this.getOwnedEntryOrderById(detail.order_id); + if (!entryOrder) { + return { + code: 404, + message: '入库单不存在或无权访问', + data: null, + }; + } + + if (Number(detail.received_quantity || 0) > 0) { + return { + code: 400, + message: '已有收货数量的明细不允许删除', + data: null, + }; + } + + await detail.destroy(); + const lineCount = await ctx.model.EntryItems.count({ where: { order_id: entryOrder.id } }); + await entryOrder.update({ + total_order_lines: lineCount, + updated_at: new Date(), + }); + + return { + code: 200, + message: '删除明细成功', + data: { + id: detailId, + }, + }; + } + + /** + * 修改入库明细。 + * @param {Object} data 请求体 + * @return {Promise} code/data/message 结构 + */ + async detailChange(data = {}) { + const { ctx } = this; + const detailId = Number(data.id || 0); + + if (!detailId) { + return { + code: 400, + message: 'id 必填', + data: null, + }; + } + + const detail = await ctx.model.EntryItems.findByPk(detailId); + if (!detail) { + return { + code: 404, + message: '明细不存在', + data: null, + }; + } + + const entryOrder = await this.getOwnedEntryOrderById(detail.order_id); + if (!entryOrder) { + return { + code: 404, + message: '入库单不存在或无权访问', + data: null, + }; + } + + const updateData = {}; + const mutableFields = [ 'item_code', 'item_id', 'inventory_type', 'stock_id', 'out_biz_code', 'owner_code' ]; + for (const field of mutableFields) { + if (Object.prototype.hasOwnProperty.call(data, field)) { + updateData[field] = data[field]; + } + } + + if (Object.prototype.hasOwnProperty.call(data, 'count')) { + const count = Number(data.count); + if (!count || count <= 0) { + return { + code: 400, + message: 'count 必须大于 0', + data: null, + }; + } + if (Number(detail.received_quantity || 0) > count) { + return { + code: 400, + message: 'count 不能小于已收货数量', + data: null, + }; + } + updateData.count = count; + } + + if (Object.keys(updateData).length === 0) { + return { + code: 400, + message: '没有可更新字段', + data: null, + }; + } + + await detail.update(updateData); + + return { + code: 200, + message: '修改明细成功', + data: { + id: detail.id, + }, + }; + } + + /** + * 作废入库单。 + * @param {Object} data 请求体 + * @return {Promise} code/data/message 结构 + */ + async cancel(data = {}) { + const orderId = Number(data.id || 0); + + if (!orderId) { + return { + code: 400, + message: 'id 必填', + data: null, + }; + } + + const entryOrder = await this.getOwnedEntryOrderById(orderId); + if (!entryOrder) { + return { + code: 404, + message: '入库单不存在或无权访问', + data: null, + }; + } + + if (entryOrder.order_status === 'COMPLETED') { + return { + code: 400, + message: '已完成入库单不允许作废', + data: null, + }; + } + + await entryOrder.update({ + order_status: 'CANCELLED', + updated_at: new Date(), + }); + + return { + code: 200, + message: '作废成功', + data: { + id: entryOrder.id, + }, + }; + } + + /** + * 完成入库单。 + * @param {Object} data 请求体 + * @return {Promise} code/data/message 结构 + */ + async completeEntry(data = {}) { + const { ctx } = this; + const orderId = Number(data.id || 0); + + if (!orderId) { + return { + code: 400, + message: 'id 必填', + data: null, + }; + } + + const entryOrder = await this.getOwnedEntryOrderById(orderId); + if (!entryOrder) { + return { + code: 404, + message: '入库单不存在或无权访问', + data: null, + }; + } + + if (entryOrder.order_status === 'CANCELLED') { + return { + code: 400, + message: '已作废入库单不允许完成', + data: null, + }; + } + + const detailCount = await ctx.model.EntryItems.count({ where: { order_id: orderId } }); + if (detailCount <= 0) { + return { + code: 400, + message: '请先添加入库明细', + data: null, + }; + } + + await entryOrder.update({ + order_status: 'COMPLETED', + updated_at: new Date(), + }); + + return { + code: 200, + message: '完成成功', + data: { + id: entryOrder.id, + }, + }; + } +} + +module.exports = EntryService; diff --git a/app/service/systems/storage/receiving.js b/app/service/systems/storage/receiving.js index ec2def5..28f8d6f 100644 --- a/app/service/systems/storage/receiving.js +++ b/app/service/systems/storage/receiving.js @@ -1,6 +1,7 @@ 'use strict'; const Service = require('egg').Service; +const { parseWhereConditions } = require('../../../lib/query_condition_parser'); class ReceivingService extends Service { /** * 查询收货单列表。 @@ -23,159 +24,153 @@ class ReceivingService extends Service { const { Op, } = Sequelize; - console.log(pageParams); const { page = 1, pageSize = 20, } = pageParams; try { - // 设置默认参数 - - const { sortField = 'id', sortOrder = 'DESC', } = sortParams; - // 构建基础查询条件 const queryOptions = { - where: {}, + where: { + [Op.and]: [ + { + warehouse_id: ctx.user.store_id, + }, + ], + }, order: [], attributes: { - exclude: ['deleted_at'], + exclude: [ 'deleted_at' ], }, }; - const prohibitedQueryOptions = { - where: {}, - }; - // 添加默认条件 - queryOptions.where[Op.and] = [{ - warehouse_id: ctx.user.store_id, - }, - ]; - prohibitedQueryOptions.where[Op.and] = []; - // 检测并处理条码查询条件 - const hasBarcodeCondition = false; - const barcodeCondition = null; + const normalizedWhere = ctx.where && typeof ctx.where === 'object' + ? ctx.where + : (where && typeof where === 'object' ? where : {}); - // 处理动态查询条件 - if (where && Object.keys(where).length > 0) { - const dynamicConditions = []; - const prohibitedConditions = []; - const barcodedynamicConditions = []; + let parsedResult = ctx.whereParsed; + if (!parsedResult || !Array.isArray(parsedResult.dynamicConditions)) { + const parsed = parseWhereConditions({ + where: normalizedWhere, + app, + specialFieldMap: { + quickWhere: { + bucket: 'quick', + }, + }, + }); - for (const fieldKey in where) { - const condition = where[fieldKey]; - - if (this.isEmptyValue(condition.value)) { - continue; - } - - // 检查是否是快捷查询,快捷查询字段 - if (fieldKey === 'quickWhere') { - dynamicConditions.push({ - [Op.or]: { - store_name: { - [Sequelize.Op.like]: `%${condition.value}%`, - }, - receiving_number: { - [Sequelize.Op.like]: `%${condition.value}%`, - }, - tracking_number: { - [Sequelize.Op.like]: `%${condition.value}%`, - }, - creator_snapshot: { - [Sequelize.Op.like]: `%${condition.value}%`, - }, - license_plate: { - [Sequelize.Op.like]: `%${condition.value}%`, - }, - } - }); - continue; // 暂不添加到动态条件中 - } - // 其他字段的处理 - const sequelizeCondition = this.buildSequelizeCondition(fieldKey, condition, app); - console.log('sequelizeCondition', fieldKey, condition, sequelizeCondition); - if (sequelizeCondition) { - dynamicConditions.push(sequelizeCondition); - } - } - if (dynamicConditions.length > 0) { - queryOptions.where[Op.and].push({ - [Op.and]: dynamicConditions, - }); + if (!parsed.ok) { + return { + code: 400, + data: { + list: [], + pagination: { + page: parseInt(page), + pageSize: parseInt(pageSize), + total: 0, + totalPages: 0, + hasPrevious: false, + hasNext: false, + }, + summary: { + total_quantity: 0, + total_locked: 0, + total_available: 0, + total_items: 0, + }, + }, + message: `筛选条件解析失败: ${parsed.reason}`, + }; } + parsedResult = parsed.result; } - // 处理排序 - const validSortFields = [ - 'id', 'item_code', 'quantity', 'locked_quantity', - 'tag_price', 'retail_price', 'create_at', 'update_at', - ]; + const dynamicConditions = [ ...(parsedResult.dynamicConditions || []) ]; + const quickWhereRaw = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere) + || normalizedWhere.quickWhere; + + if (quickWhereRaw && !this.isEmptyValue(quickWhereRaw.value)) { + const quickValue = String(quickWhereRaw.value).trim(); + dynamicConditions.push({ + [Op.or]: { + store_name: { + [Sequelize.Op.like]: `%${quickValue}%`, + }, + receiving_number: { + [Sequelize.Op.like]: `%${quickValue}%`, + }, + tracking_number: { + [Sequelize.Op.like]: `%${quickValue}%`, + }, + creator_snapshot: { + [Sequelize.Op.like]: `%${quickValue}%`, + }, + license_plate: { + [Sequelize.Op.like]: `%${quickValue}%`, + }, + }, + }); + } + + if (dynamicConditions.length > 0) { + queryOptions.where[Op.and].push({ + [Op.and]: dynamicConditions, + }); + } + + const validSortFields = [ + 'id', 'receiving_number', 'status', 'create_at', 'update_at', 'store_id', + ]; const actualSortField = validSortFields.includes(sortField) ? sortField : 'create_at'; const actualSortOrder = sortOrder.toUpperCase() === 'ASC' ? 'ASC' : 'DESC'; - queryOptions.order.push([actualSortField, actualSortOrder]); + queryOptions.order.push([ actualSortField, actualSortOrder ]); - // 计算分页偏移量 const offset = (page - 1) * pageSize; + const include = [ + { + model: ctx.model.StoreWarehouse, + as: 'store', + attributes: [ 'store_remask' ], + where: { + use_status: 1, + warehouse_id: ctx.user.store_id, + }, + required: false, + }, + { + model: ctx.model.AccountStoreEmployee, + as: 'creator', + attributes: [ 'real_name' ], + required: true, + }, + ]; - // 执行查询:获取总数和数据 - const [total, data] = await Promise.all([ - // 获取总数 + const [ total, data ] = await Promise.all([ ctx.model.Receiving.count({ where: queryOptions.where, - include: [{ - model: ctx.model.StoreWarehouse, - as: 'store', - attributes: ['store_remask'], - where: { - use_status: 1, - warehouse_id: ctx.user.store_id, - }, - required: false, - }, { - model: ctx.model.AccountStoreEmployee, - as: 'creator', - attributes: ['real_name'], - required: true, - }], + include, distinct: true, }), - - // 获取分页数据 ctx.model.Receiving.findAll({ ...queryOptions, - include: [{ - model: ctx.model.StoreWarehouse, - as: 'store', - attributes: ['store_remask'], - where: { - use_status: 1, - warehouse_id: ctx.user.store_id, - }, - required: false, - }, { - model: ctx.model.AccountStoreEmployee, - as: 'creator', - attributes: ['real_name'], - required: true, - }], + include, limit: parseInt(pageSize), offset: parseInt(offset), - distinct: true, // 确保去重 + distinct: true, raw: true, }), ]); - // 计算分页信息 const totalPages = Math.ceil(total / pageSize); const hasPrevious = page > 1; const hasNext = page < totalPages; - // 批量查询条码信息 const stockIds = data.map(item => item.id); let images = []; if (stockIds.length > 0) { @@ -186,30 +181,23 @@ class ReceivingService extends Service { [Op.in]: stockIds, }, }, - include: [{ - model: ctx.model.File, - as: 'file', - attributes: ['file_url'], - required: true, - }], + include: [ + { + model: ctx.model.File, + as: 'file', + attributes: [ 'file_url' ], + required: true, + }, + ], }); } - // 处理数据,添加一些计算字段 const processedData = data.map(item => { const availableQuantity = Math.max(0, item.quantity - item.locked_quantity); - const lockRate = item.quantity > 0 ? (item.locked_quantity / item.quantity * 100).toFixed( - 2) : 0; - - const { - cos, - } = config; - const { - cdnurl, - } = cos; + const lockRate = item.quantity > 0 ? (item.locked_quantity / item.quantity * 100).toFixed(2) : 0; const itemImages = images - .filter(images => parseInt(images.business_id) === item.id) - .map(images => images.file.file_url); + .filter(row => parseInt(row.business_id) === item.id) + .map(row => row.file.file_url); return { ...item, images: itemImages, @@ -218,26 +206,16 @@ class ReceivingService extends Service { lock_rate_display: `${lockRate}%`, create_at_display: item.create_at ? this.formatDate(item.create_at) : '', update_at_display: item.update_at ? this.formatDate(item.update_at) : '', - // 标记是否通过条码查询匹配 - is_barcode_matched: hasBarcodeCondition && matchedStockIds.includes(item.id), }; }); - // 添加汇总信息 const summary = { total_quantity: data.reduce((sum, item) => sum + item.quantity, 0), total_locked: data.reduce((sum, item) => sum + item.locked_quantity, 0), - total_available: data.reduce((sum, item) => sum + Math.max(0, item.quantity - item - .locked_quantity), 0), + total_available: data.reduce((sum, item) => sum + Math.max(0, item.quantity - item.locked_quantity), 0), total_items: data.length, - // 如果有条码查询,添加匹配统计 - ...(hasBarcodeCondition && { - barcode_matched_count: matchedStockIds.length, - barcode_search_value: where.barcode.value, - }), }; - return { code: 200, data: { @@ -252,15 +230,14 @@ class ReceivingService extends Service { }, summary, queryInfo: { - conditions: where, + conditions: normalizedWhere, sortField: actualSortField, sortOrder: actualSortOrder, - hasBarcodeSearch: hasBarcodeCondition, + hasBarcodeSearch: false, }, }, message: '查询成功', }; - } catch (error) { ctx.logger.error('[StockService.getWarehouseStock] 查询失败:', error); return { diff --git a/day.log b/day.log index 5701f90ed3ce2c378ea5c5492aa44d41582ace5d..2031b050e23e72ced46177106b69ae19c812d15c 100644 GIT binary patch delta 1455 zcmZ`(Z%i9y7=K#^QoIr|1X+Xeh?6yQKxYgQmMo;k1k8HZ>y>s*Yg;*9+EM;AEtJ9* zifpm%TDH!2y1EZrOvYkjR6Z^GW$LnFVq(A#`pF?lv*-s0#w=U58PDfw9kh$)a`)cd z`+J_}_xnB1-POGIyDQq|zGStY)Db=FPcCWogl#6*aJiQ9FtfwJUP*gd#M;cRq(_Qt z+o@n9;@b&NvhHUF*Bysw_QE$A)(hY-PA#zEfo5jSyoNbana|j{>1Q=v?33x;#umOH zXyVfq=URo6gVcx6g*Et zc>{S?M>m9=$d-q zZgTN}!zw|@I|Mt`^34>dK9mab;rSOA?+#awhljPMa=AR21~erRIC*ki4%1)eh(I9% zg&9<%lUci45@SFYiFc3@AmRsTiJ+f^i=koI#}v-(WUm7S6h=uLu71L)nE0vSiqr&V z>=fnHnAhm66P^~5G(GzD7!OzlBH~bM88C3o>V^p zw1;3XLOP31PeAd|_I(6m1F)OuEb2rDuvLGb+gdEwz>^1V>m`F)X};Nmio<|>>>f|h z*j=ugNod~_tu=d^#Xjj#<|i3FD*3^wt5SpK`?LCltB}qG>V<-Q(x;txG*hYKUHMP2 zw6ged=}WgkrKvY0G!$p3q^zUt-uZ9Sa9XC|Jx)M7IRw{o{4}80ile@*1B^ae+`|52 zfr5Za5;=?XE3L{Jr`m;2Df{if9=2gLyt*?a+iirf#}jrVU3Fq(c447b?eTTlZlrhH zbgI_G>JD}VgVO3*bgt6jRppN}C?DqqW%bNt#1Ew(M>+K?@w8yEZOz_|Eh#z$-Q&gU za-~HNoxO4VK6QaUy4T+t%w904Z2q17jc*c}h(rKp=&&L8?U`DY^*Wnsc`zkJbbvas zN51`*N9>VhpT)Mzby_gElJuSs^Bzv&H*z(i@pI~$a#^@X$$6b}P{`-69UqT3D7qZt zN(S8@qtXVAN}FOgEmC8yKx>WBxj$fXGH=7a7IMDcerIk#{yp-ZayvkLKgb$?r~P9a z&KmpcB%jbJm4={2=%PlsGe=X_OEJkME-3{Wjp0 { + it('should bind, unbind, and bind again for ye4s user', async () => { + const { token } = await getAuthToken(); + + const infoRes = await invokeSystemMethod('user.info', {}, token); + assert.equal(infoRes.status, 200); + assert.equal(infoRes.body.flag, 'success'); + const accountId = Number(infoRes.body?.data?.id); + assert.ok(Number.isFinite(accountId) && accountId > 0); + + const bindCodeRes = await invokeSystemMethod('user.getBindWechatCode', { + forceRefresh: true, + init: true, + }, token); + assert.equal(bindCodeRes.status, 200); + assert.equal(bindCodeRes.body.flag, 'success'); + const code = String(bindCodeRes.body?.data?.code || ''); + assert.ok(code.length > 10); + + const bindRes1 = await invokeGatewayMethod('user.bindAccountByTempCode', { + code, + ye4s_user_id: YE4S_TEST_USER_ID, + }); + assert.equal(bindRes1.status, 200); + assert.equal(bindRes1.body.flag, 'success'); + assert.equal(bindRes1.body.code, 200); + assert.equal(Number(bindRes1.body?.data?.account_id), accountId); + assert.equal(Number(bindRes1.body?.data?.ye4s_user_id), YE4S_TEST_USER_ID); + assert.equal(bindRes1.body?.data?.status, 'bound'); + + const unbindRes = await invokeSystemMethod('user.unbindWechat', {}, token); + assert.equal(unbindRes.status, 200); + assert.equal(unbindRes.body.flag, 'success'); + assert.equal(unbindRes.body.code, 200); + assert.equal(unbindRes.body?.data?.status, 'unbound'); + assert.equal(Number(unbindRes.body?.data?.account_id), accountId); + + const bindRes2 = await invokeGatewayMethod('user.bindAccountByTempCode', { + code, + ye4s_user_id: YE4S_TEST_USER_ID, + }); + assert.equal(bindRes2.status, 200); + assert.equal(bindRes2.body.flag, 'success'); + assert.equal(bindRes2.body.code, 200); + assert.equal(Number(bindRes2.body?.data?.account_id), accountId); + assert.equal(Number(bindRes2.body?.data?.ye4s_user_id), YE4S_TEST_USER_ID); + assert.equal(bindRes2.body?.data?.status, 'bound'); + + const verifyRes = await invokeGatewayMethod('user.getUserByTempCode', { code }); + assert.equal(verifyRes.status, 200); + assert.equal(verifyRes.body.flag, 'success'); + assert.equal(verifyRes.body.code, 200); + assert.equal(Number(verifyRes.body?.data?.account_id), accountId); + assert.equal(verifyRes.body?.data?.status, 'bound'); + }); +}); diff --git a/test/app/controller/system.setting.account.test.js b/test/app/controller/system.setting.account.test.js new file mode 100644 index 0000000..167f86b --- /dev/null +++ b/test/app/controller/system.setting.account.test.js @@ -0,0 +1,184 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const { + getAuthToken, + invokeSystemMethod, + TOKEN_FILE, +} = require('../../support/system_method_client'); + +const EXTRA_HEADERS = { + platform: 'web', + project: 'all', +}; +const RESERVED_EMPLOYEE_NAME = '测试工号保留'; +const RETAIN_PHONE = process.env.SYSTEM_TEST_ACCOUNT_RETAIN_PHONE || '13999002888'; +const RETAIN_USERNAME = process.env.SYSTEM_TEST_ACCOUNT_RETAIN_USERNAME || 'autotest_acc_mgmt_keep'; +const EXISTING_FILE_ID = Number(process.env.SYSTEM_TEST_EXISTING_FILE_ID || 0); +const STATE_FILE = process.env.SYSTEM_TEST_ACCOUNT_STATE_FILE || 'temp/account-management-test-state.json'; + +function buildTempPhone() { + return `139${String(Date.now()).slice(-8)}`; +} + +async function getUserInfo(token) { + const res = await invokeSystemMethod('user.info', {}, token, EXTRA_HEADERS); + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + assert.equal(res.body.code, 200); + return res.body.data; +} + +describe('test/app/controller/system.setting.account.test.js', () => { + let token = ''; + let existingFileId = 0; + let tokenFileExistedBefore = false; + let retainedEmployeeId = 0; + let retainedAccountId = 0; + let tempEmployeeId = 0; + let tempAccountId = 0; + let tempPhone = ''; + let tempUsername = ''; + + async function listAccounts() { + const res = await invokeSystemMethod('setting.account.list', {}, token, EXTRA_HEADERS); + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + assert.equal(res.body.code, 200); + const list = Array.isArray(res.body.data) ? res.body.data : []; + return list; + } + + async function ensureRetainedEmployee() { + const currentList = await listAccounts(); + const existing = currentList.find(item => item && (item.phone === RETAIN_PHONE || item.username === RETAIN_USERNAME || item.real_name === RESERVED_EMPLOYEE_NAME)); + if (existing) { + retainedEmployeeId = Number(existing.employee_id); + retainedAccountId = Number(existing.account_id); + return existing; + } + + const addRes = await invokeSystemMethod('setting.account.add', { + phone: RETAIN_PHONE, + username: RETAIN_USERNAME, + password: '111111', + real_name: '测试工号预留初始化', + }, token, EXTRA_HEADERS); + + assert.equal(addRes.status, 200); + assert.equal(addRes.body.flag, 'success'); + assert.equal(addRes.body.code, 200); + + retainedEmployeeId = Number(addRes.body?.data?.employee_id || 0); + retainedAccountId = Number(addRes.body?.data?.account_id || 0); + assert.ok(retainedEmployeeId > 0); + assert.ok(retainedAccountId > 0); + + return addRes.body.data; + } + + before(async () => { + tokenFileExistedBefore = fs.existsSync(TOKEN_FILE); + + const auth = await getAuthToken(); + token = auth.token; + + const userInfo = await getUserInfo(token); + assert.ok(Number(userInfo.store_id || 0) > 0, '当前账号未识别到主体 store_id'); + + existingFileId = EXISTING_FILE_ID; + assert.ok(existingFileId > 0, '已有文件ID无效'); + }); + + after(async () => { + if (!tokenFileExistedBefore && fs.existsSync(TOKEN_FILE)) { + fs.rmSync(TOKEN_FILE, { force: true }); + } + }); + + it('error-1 should reject add when real_name is reserved name', async () => { + const res = await invokeSystemMethod('setting.account.add', { + phone: buildTempPhone(), + username: `autotest_acc_mgmt_reserved_${Date.now()}`, + real_name: RESERVED_EMPLOYEE_NAME, + }, token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'failure'); + assert.equal(res.body.code, 400); + assert.match(String(res.body.message || ''), /保留名称/); + }); + + it('normal-1 should add temp employee, delete it, and keep one retained employee with avatar and final name', async () => { + const retained = await ensureRetainedEmployee(); + assert.ok(Number(retained.employee_id || retainedEmployeeId) > 0); + + tempPhone = buildTempPhone(); + tempUsername = `autotest_acc_mgmt_tmp_${Date.now()}`; + const tempRealName = `测试工号临时_${Date.now()}`; + + const addTempRes = await invokeSystemMethod('setting.account.add', { + phone: tempPhone, + username: tempUsername, + password: '111111', + real_name: tempRealName, + }, token, EXTRA_HEADERS); + + assert.equal(addTempRes.status, 200); + assert.equal(addTempRes.body.flag, 'success'); + assert.equal(addTempRes.body.code, 200); + tempEmployeeId = Number(addTempRes.body?.data?.employee_id || 0); + tempAccountId = Number(addTempRes.body?.data?.account_id || 0); + assert.ok(tempEmployeeId > 0); + assert.ok(tempAccountId > 0); + assert.equal(addTempRes.body?.data?.phone, tempPhone); + assert.equal(addTempRes.body?.data?.real_name, tempRealName); + + const deleteTempRes = await invokeSystemMethod('setting.account.delete', { + employee_id: tempEmployeeId, + }, token, EXTRA_HEADERS); + + assert.equal(deleteTempRes.status, 200); + assert.equal(deleteTempRes.body.flag, 'success'); + assert.equal(deleteTempRes.body.code, 200); + assert.equal(Number(deleteTempRes.body?.data?.employee_id), tempEmployeeId); + assert.equal(deleteTempRes.body?.data?.status, 'deleted'); + + const updateRetainedRes = await invokeSystemMethod('setting.account.update', { + employee_id: retainedEmployeeId, + real_name: RESERVED_EMPLOYEE_NAME, + file_id: existingFileId, + }, token, EXTRA_HEADERS); + + assert.equal(updateRetainedRes.status, 200); + assert.equal(updateRetainedRes.body.flag, 'success'); + assert.equal(updateRetainedRes.body.code, 200); + assert.equal(Number(updateRetainedRes.body?.data?.employee_id), retainedEmployeeId); + assert.equal(updateRetainedRes.body?.data?.real_name, RESERVED_EMPLOYEE_NAME); + assert.equal(Number(updateRetainedRes.body?.data?.avatar_file_id), existingFileId); + assert.ok(String(updateRetainedRes.body?.data?.avatar_url || '').length > 0); + + const list = await listAccounts(); + const retainedRow = list.find(item => Number(item.employee_id) === retainedEmployeeId); + const deletedTempRow = list.find(item => Number(item.employee_id) === tempEmployeeId); + + assert.ok(retainedRow, '保留工号未出现在列表中'); + assert.equal(retainedRow.real_name, RESERVED_EMPLOYEE_NAME); + assert.equal(Number(retainedRow.avatar_file_id), existingFileId); + assert.ok(String(retainedRow.avatar_url || '').length > 0); + assert.equal(deletedTempRow, undefined, '已删除的临时工号仍出现在有效列表中'); + + fs.mkdirSync(require('node:path').dirname(STATE_FILE), { recursive: true }); + fs.writeFileSync(STATE_FILE, JSON.stringify({ + retainedEmployeeId, + retainedAccountId, + tempEmployeeId, + tempAccountId, + tempPhone, + tempUsername, + existingFileId, + tokenFileExistedBefore, + }, null, 2), 'utf8'); + }); +}); diff --git a/test/app/controller/system.storage.entry.test.js b/test/app/controller/system.storage.entry.test.js new file mode 100644 index 0000000..46f58f0 --- /dev/null +++ b/test/app/controller/system.storage.entry.test.js @@ -0,0 +1,239 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const { + getAuthToken, + invokeSystemMethod, +} = require('../../support/system_method_client'); + +const EXTRA_HEADERS = { + platform: 'web', + project: 'all', +}; + +const FALLBACK_ROLE_IDS = [ 4, 6, 30 ]; + +function normalizeListPayload(data) { + if (data && Array.isArray(data.list)) return data; + if (data && data.data && Array.isArray(data.data.list)) return data.data; + return null; +} + +function extractDataObject(data) { + if (!data) return null; + if (data && typeof data === 'object' && data.data && typeof data.data === 'object') { + return data.data; + } + return data; +} + +async function switchToWarehouseRole(token) { + let currentToken = token; + + const infoRes = await invokeSystemMethod('user.info', {}, currentToken, EXTRA_HEADERS); + assert.equal(infoRes.status, 200); + assert.equal(infoRes.body.flag, 'success'); + assert.equal(infoRes.body.code, 200); + + const employees = Array.isArray(infoRes.body?.data?.employees) ? infoRes.body.data.employees : []; + const warehouseRoles = employees.filter(item => item && item.role_type === 'warehouse' && Number(item.id)); + + const candidateRoleIds = [ ...new Set([ + ...warehouseRoles.map(item => Number(item.id)), + ...FALLBACK_ROLE_IDS, + ].filter(Boolean)) ]; + + assert.ok(candidateRoleIds.length > 0, '当前账号没有可尝试的仓库角色'); + + for (const roleId of candidateRoleIds) { + const changeRes = await invokeSystemMethod('user.changeRole', { + roleId, + }, currentToken, EXTRA_HEADERS); + + if (changeRes.status !== 200 || changeRes.body?.flag !== 'success' || changeRes.body?.code !== 200) { + continue; + } + + currentToken = changeRes.body?.data?.token || currentToken; + + const listRes = await invokeSystemMethod('storage.entry.list', { + pagination: { page: 1, pageSize: 10 }, + where: {}, + }, currentToken, EXTRA_HEADERS); + + if (listRes.status === 200 && listRes.body?.flag === 'success' && listRes.body?.code === 200) { + return { + token: currentToken, + roleId, + }; + } + } + + throw new Error('未找到可访问入库单的仓库角色'); +} + +describe('test/app/controller/system.storage.entry.test.js', () => { + it('should query entry list', async () => { + const { token } = await getAuthToken(); + const switched = await switchToWarehouseRole(token); + + const res = await invokeSystemMethod('storage.entry.list', { + pagination: { + page: 1, + pageSize: 10, + }, + where: {}, + }, switched.token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + assert.equal(res.body.code, 200); + + const payload = normalizeListPayload(res.body.data); + assert.ok(payload, '返回结构中缺少入库单列表 payload'); + assert.ok(Array.isArray(payload.list), '入库单 list 不是数组'); + assert.ok(payload.pagination, '入库单 pagination 缺失'); + assert.equal(typeof payload.pagination.total, 'number', 'pagination.total 不是 number'); + }); + + it('should create entry and run detail lifecycle then cancel', async () => { + const { token } = await getAuthToken(); + const switched = await switchToWarehouseRole(token); + + const createRes = await invokeSystemMethod('storage.entry.create', { + order_type: 'QTRK', + purchase_order_code: `PO-${Date.now()}`, + remark: 'integration-test-cancel', + }, switched.token, EXTRA_HEADERS); + + assert.equal(createRes.status, 200); + assert.equal(createRes.body.flag, 'success'); + assert.equal(createRes.body.code, 200); + + const createData = extractDataObject(createRes.body.data) || {}; + const orderId = Number(createData.id || createRes.body.id || 0); + assert.ok(orderId > 0, `创建入库单未返回有效 id: ${JSON.stringify(createRes.body)}`); + + const getRes = await invokeSystemMethod('storage.entry.get', { + id: orderId, + }, switched.token, EXTRA_HEADERS); + + assert.equal(getRes.status, 200); + assert.equal(getRes.body.flag, 'success'); + assert.equal(getRes.body.code, 200); + + const getData = extractDataObject(getRes.body.data) || {}; + const entryOrder = getData.entryOrder || {}; + assert.equal(Number(entryOrder.id), orderId); + + const addRes = await invokeSystemMethod('storage.entry.addDetail', { + order_id: orderId, + count: 2, + item_code: `SKU-${Date.now().toString().slice(-6)}`, + inventory_type: 'ZP', + }, switched.token, EXTRA_HEADERS); + + assert.equal(addRes.status, 200); + assert.equal(addRes.body.flag, 'success'); + assert.equal(addRes.body.code, 200); + + const addData = extractDataObject(addRes.body.data) || {}; + const detailId = Number(addData.id || addRes.body.id || 0); + assert.ok(detailId > 0, `新增明细未返回有效 id: ${JSON.stringify(addRes.body)}`); + + const changeRes = await invokeSystemMethod('storage.entry.detailChange', { + id: detailId, + count: 3, + item_code: `SKU-CHG-${Date.now().toString().slice(-6)}`, + }, switched.token, EXTRA_HEADERS); + + assert.equal(changeRes.status, 200); + assert.equal(changeRes.body.flag, 'success'); + assert.equal(changeRes.body.code, 200); + + const deleteRes = await invokeSystemMethod('storage.entry.deleteDetail', { + id: detailId, + }, switched.token, EXTRA_HEADERS); + + assert.equal(deleteRes.status, 200); + assert.equal(deleteRes.body.flag, 'success'); + assert.equal(deleteRes.body.code, 200); + + const cancelRes = await invokeSystemMethod('storage.entry.cancel', { + id: orderId, + }, switched.token, EXTRA_HEADERS); + + assert.equal(cancelRes.status, 200); + assert.equal(cancelRes.body.flag, 'success'); + assert.equal(cancelRes.body.code, 200); + }); + + it('should complete entry after adding detail', async () => { + const { token } = await getAuthToken(); + const switched = await switchToWarehouseRole(token); + + const createRes = await invokeSystemMethod('storage.entry.create', { + order_type: 'QTRK', + purchase_order_code: `PO-COMP-${Date.now()}`, + remark: 'integration-test-complete', + }, switched.token, EXTRA_HEADERS); + + assert.equal(createRes.status, 200); + assert.equal(createRes.body.flag, 'success'); + assert.equal(createRes.body.code, 200); + + const createData = extractDataObject(createRes.body.data) || {}; + const orderId = Number(createData.id || createRes.body.id || 0); + assert.ok(orderId > 0, `创建入库单未返回有效 id: ${JSON.stringify(createRes.body)}`); + + const addRes = await invokeSystemMethod('storage.entry.addDetail', { + order_id: orderId, + count: 1, + item_code: `SKU-COMP-${Date.now().toString().slice(-6)}`, + inventory_type: 'ZP', + }, switched.token, EXTRA_HEADERS); + + assert.equal(addRes.status, 200); + assert.equal(addRes.body.flag, 'success'); + assert.equal(addRes.body.code, 200); + + const completeRes = await invokeSystemMethod('storage.entry.completeEntry', { + id: orderId, + }, switched.token, EXTRA_HEADERS); + + assert.equal(completeRes.status, 200); + assert.equal(completeRes.body.flag, 'success'); + assert.equal(completeRes.body.code, 200); + }); + + it('should reject invalid params for create/get/addDetail', async () => { + const { token } = await getAuthToken(); + const switched = await switchToWarehouseRole(token); + + const createBadRes = await invokeSystemMethod('storage.entry.create', { + purchase_order_code: `PO-BAD-${Date.now()}`, + }, switched.token, EXTRA_HEADERS); + + assert.equal(createBadRes.status, 200); + assert.equal(createBadRes.body.flag, 'success'); + assert.equal(createBadRes.body.code, 400); + assert.match(String(createBadRes.body.message || ''), /order_type 必填/); + + const getBadRes = await invokeSystemMethod('storage.entry.get', {}, switched.token, EXTRA_HEADERS); + + assert.equal(getBadRes.status, 200); + assert.equal(getBadRes.body.flag, 'success'); + assert.equal(getBadRes.body.code, 400); + assert.match(String(getBadRes.body.message || ''), /至少传一个/); + + const addBadRes = await invokeSystemMethod('storage.entry.addDetail', { + order_id: 0, + count: 0, + }, switched.token, EXTRA_HEADERS); + + assert.equal(addBadRes.status, 200); + assert.equal(addBadRes.body.flag, 'success'); + assert.equal(addBadRes.body.code, 400); + assert.match(String(addBadRes.body.message || ''), /order_id 必填|count 必须大于 0/); + }); +}); diff --git a/test/support/system_method_client.js b/test/support/system_method_client.js index 68c3649..62a7bd1 100644 --- a/test/support/system_method_client.js +++ b/test/support/system_method_client.js @@ -5,6 +5,7 @@ const path = require('node:path'); const assert = require('node:assert/strict'); const BASE_URL = process.env.SYSTEM_TEST_BASE_URL || 'http://127.0.0.1:6060'; +const BASE_GATEWAY_URL = process.env.SYSTEM_TEST_GATEWAY_BASE_URL || BASE_URL; const TOKEN_FILE = process.env.SYSTEM_TEST_TOKEN_FILE || path.join(process.cwd(), 'test', '.runtime', 'system_user_token.json'); const USERNAME = process.env.SYSTEM_TEST_USERNAME || 'liufumingren'; @@ -127,11 +128,39 @@ async function getAuthToken(options = {}) { }; } +async function invokeGatewayMethod(method, body = {}) { + const timestamp = nowSec(); + const url = `${BASE_GATEWAY_URL}/internal/v1/gateway?method=${encodeURIComponent(method)}&v=1.0×tamp=${timestamp}`; + + const response = await fetch(url, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify(body), + }); + + const text = await response.text(); + let json; + try { + json = JSON.parse(text); + } catch { + throw new Error(`Invalid JSON from gateway ${method}: ${text}`); + } + + return { + status: response.status, + body: json, + }; +} + module.exports = { BASE_URL, + BASE_GATEWAY_URL, TOKEN_FILE, USERNAME, invokeSystemMethod, + invokeGatewayMethod, getAuthToken, readCachedToken, }; From 26af1a7039685344b2ea591cc28e63080c1b8893 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Tue, 31 Mar 2026 00:35:53 +0800 Subject: [PATCH 012/550] feat: refine setting role/account/permission auth and tests --- AI_TOOLBOX.md | 40 +- app/model/role.js | 10 + app/service/apiMethods/print.js | 345 ++++++ app/service/main.js | 136 ++- app/service/systemMethods/setting/account.js | 32 +- .../systemMethods/setting/permission.js | 60 + app/service/systemMethods/setting/role.js | 60 + app/service/systemMethods/user.js | 34 +- app/service/systems/auth/user.js | 1033 +++++++++++++---- app/service/systems/setting/account.js | 387 +++++- app/service/systems/setting/permission.js | 730 ++++++++++++ app/service/systems/setting/role.js | 669 +++++++++++ config/config.default.js | 1 + methods/gateway.json | 157 ++- methods/system.json | 942 ++++++++++++++- package.json | 1 + script/sync-system-api-permission.cjs | 254 ++++ stock.todo | 112 -- ...gateway.user.bindAccountByTempCode.test.js | 67 +- .../system.setting.permission.test.js | 234 ++++ .../system.user.getLoginWechatCode.test.js | 17 + .../system.user.loginByCode.test.js | 19 +- .../auth.user.bindWechatCacheExpiry.test.js | 152 +++ .../systems/auth.user.loginWechatCode.test.js | 103 ++ 24 files changed, 5108 insertions(+), 487 deletions(-) create mode 100644 app/service/apiMethods/print.js create mode 100644 app/service/systemMethods/setting/permission.js create mode 100644 app/service/systemMethods/setting/role.js create mode 100644 app/service/systems/setting/permission.js create mode 100644 app/service/systems/setting/role.js create mode 100644 script/sync-system-api-permission.cjs delete mode 100644 stock.todo create mode 100644 test/app/controller/system.setting.permission.test.js create mode 100644 test/app/controller/system.user.getLoginWechatCode.test.js create mode 100644 test/app/service/systems/auth.user.bindWechatCacheExpiry.test.js create mode 100644 test/app/service/systems/auth.user.loginWechatCode.test.js diff --git a/AI_TOOLBOX.md b/AI_TOOLBOX.md index 2ecaf48..9a25c13 100644 --- a/AI_TOOLBOX.md +++ b/AI_TOOLBOX.md @@ -1,6 +1,6 @@ # AI 工具箱(WMS) -本文件用于统一 AI 协助开发/调试时可直接使用的方法,减少重复沟通成本。 +本文件用于统一 AI 协助开发/调试时可直接使用的方法,减少重复沟通成本。AI每次应答文尾加喵~以判断是否丢失上下文 ## 1. 适用范围 @@ -591,4 +591,42 @@ npx egg-bin test test/app/controller/system.user.info.web.test.js test/app/contr - `print.getList` - `storage.entry.list` - `stock.warehouse.list` + +## 15. system API 权限映射规则(wms_permission) + +适用范围:`/system` 入口,权限类型为 `type=api`。 + +### 15.1 映射规则 + +- `wms_permission.path` 作为 system method 的权限标识(例如:`setting.account.list`)。 +- 同步来源以 `methods/system.json` 为准:`isNeedAuth=true` 的 method 必须存在对应 `wms_permission(type=api,path=method)`。 +- 新增权限后,必须在 `wms_role_permission` 绑定 `role_id=2`。 + +### 15.2 外部脚本(批量补齐) + +固定命令: + +```powershell +# 预览差异(不写库) +npm run permission:sync:system-api -- --dry-run + +# 执行补齐(写库) +npm run permission:sync:system-api +``` + +可选参数: + +- `--role-id=2`:绑定角色 ID(默认 `2`) +- `--db-client=wms`:数据库客户端名(默认 `wms`) +- `--config-path=./config/config.local.js`:配置文件路径 +- `--method-doc=./methods/system.json`:method 文档路径 + +### 15.3 运行时兜底(仅 debug) + +- 入口:`app/service/main.js` 的 `checkApiPermission`。 +- 逻辑:当用户权限列表不包含目标 method 时,若 `app.config.debug === true`,自动: + 1. 参考现有 `type=api` 权限行构建缺失权限行; + 2. 绑定 `wms_role_permission(role_id=2, permission_id=新权限ID)`。 +- 生产建议:保持 `app.config.debug=false`,避免运行时自动写库。 + \ No newline at end of file diff --git a/app/model/role.js b/app/model/role.js index 16d2af5..8138b00 100644 --- a/app/model/role.js +++ b/app/model/role.js @@ -117,6 +117,12 @@ module.exports = app => { allowNull: true, comment: '所属仓库ID', }, + pid: { + type: BIGINT.UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '父级角色ID,顶级为0', + }, }, { tableName: 'wms_role', freezeTableName: true, @@ -143,6 +149,10 @@ module.exports = app => { name: 'idx_status', fields: [ 'status' ], }, + { + name: 'idx_pid', + fields: [ 'pid' ], + }, ], }); diff --git a/app/service/apiMethods/print.js b/app/service/apiMethods/print.js new file mode 100644 index 0000000..03ba646 --- /dev/null +++ b/app/service/apiMethods/print.js @@ -0,0 +1,345 @@ +'use strict'; + +const Service = require('egg').Service; +const crypto = require('node:crypto'); + +class PrintApiService extends Service { + getPrinterRedis() { + return this.app.redis.get('printer'); + } + + normalizeBindValue(bindValue) { + let bindValueObj = bindValue; + try { + bindValueObj = JSON.parse(bindValue); + } catch (_) { + bindValueObj = bindValue; + } + return bindValueObj; + } + + async getEmployeePermissions(employeeId) { + const { ctx } = this; + const roleRows = await ctx.model.EmployeeRole.findAll({ + attributes: [ 'role_id' ], + where: { + employee_id: employeeId, + }, + include: [ + { + model: ctx.model.Role, + as: 'role', + attributes: [], + where: { + status: 1, + }, + required: true, + }, + ], + raw: true, + }); + + if (!roleRows || roleRows.length === 0) { + return []; + } + + const roleIds = [ ...new Set(roleRows.map(item => item.role_id).filter(Boolean)) ]; + if (roleIds.length === 0) { + return []; + } + + const rolePermissionRows = await ctx.model.RolePermission.findAll({ + attributes: [ 'permission_id' ], + where: { + role_id: { + [ctx.app.Sequelize.Op.in]: roleIds, + }, + }, + raw: true, + }); + if (!rolePermissionRows || rolePermissionRows.length === 0) { + return []; + } + + const permissionIds = [ ...new Set(rolePermissionRows.map(item => item.permission_id).filter(Boolean)) ]; + if (permissionIds.length === 0) { + return []; + } + + const permissions = await ctx.model.Permission.findAll({ + attributes: [ 'path' ], + where: { + id: { + [ctx.app.Sequelize.Op.in]: permissionIds, + }, + status: 1, + type: 'api', + }, + raw: true, + }); + + return permissions.map(item => item.path).filter(Boolean); + } + + async getBindInfo(data = {}) { + const { ctx } = this; + const accountId = Number(data.account_id || data.accountId || data.wms_account_id || data.wmsAccountId); + const code = String(data.code || '').trim(); + + if (!Number.isFinite(accountId) || accountId <= 0 || !code) { + return { + success: false, + code: 0, + data: null, + message: '缺少有效参数 account_id 或 code', + }; + } + + const account = await ctx.model.Account.findOne({ + where: { id: accountId }, + attributes: [ 'id', 'status' ], + raw: true, + }); + if (!account || Number(account.status) !== 1) { + return { + success: false, + code: 0, + data: null, + message: '账号不存在或已禁用', + }; + } + + const redis = this.getPrinterRedis(); + const bindValue = await redis.get(`bind:${code}`); + if (!bindValue) { + return { + success: false, + code: 0, + data: null, + message: '无效code或未绑定', + }; + } + + const employeeRows = await ctx.model.AccountStoreEmployee.findAll({ + where: { + account_id: accountId, + status: 1, + }, + include: [ + { + model: ctx.model.Store, + as: 'store', + attributes: [ 'id', 'company_name', 'project', 'status', 'auth_end' ], + where: { + status: 1, + project: 'warehouse', + }, + required: true, + }, + ], + order: [[ 'created_at', 'DESC' ]], + }); + + const now = new Date(); + const warehouseMap = new Map(); + for (const employee of employeeRows) { + const permissions = await this.getEmployeePermissions(employee.id); + if (!permissions.includes('printer.bind')) { + continue; + } + + const store = employee.store; + if (!store) { + continue; + } + + if (store.auth_end && new Date(store.auth_end) < now) { + continue; + } + + warehouseMap.set(String(store.id), { + id: Number(store.id), + name: store.company_name, + }); + } + + const warehouses = Array.from(warehouseMap.values()); + if (warehouses.length === 0) { + return { + success: true, + code: 200, + data: { + warehouses: [], + }, + message: '无可绑定仓库', + }; + } + + const tempCode = crypto.randomBytes(16).toString('hex').toUpperCase(); + const tokenPayload = { + accountId, + code, + bindValue, + createdAt: new Date().toISOString(), + warehouses: warehouses.map(item => item.id), + }; + await redis.setex(`binding_token:${tempCode}`, 300, JSON.stringify(tokenPayload)); + + return { + success: true, + code: 200, + data: { + warehouses, + tempCode, + }, + message: '获取绑定信息成功', + }; + } + + async bindByTempCode(data = {}) { + const { ctx } = this; + const tempCode = String(data.temp_code || data.tempCode || '').trim(); + const printer = String(data.printer || data.workbench_name || data.workbenchName || '').trim(); + const warehouse = Number(data.warehouse || data.warehouse_id || data.warehouseId); + + if (!tempCode || !printer || !Number.isFinite(warehouse) || warehouse <= 0) { + return { + success: false, + code: 0, + data: null, + message: '参数缺失', + }; + } + + const redis = this.getPrinterRedis(); + const tokenText = await redis.get(`binding_token:${tempCode}`); + if (!tokenText) { + return { + success: false, + code: 0, + data: null, + message: '临时code无效或已过期', + }; + } + + let tokenData = null; + try { + tokenData = JSON.parse(tokenText); + } catch (_) { + tokenData = null; + } + + if (!tokenData || !tokenData.code || !Array.isArray(tokenData.warehouses)) { + return { + success: false, + code: 0, + data: null, + message: '临时code数据异常', + }; + } + + if (!tokenData.warehouses.includes(warehouse)) { + return { + success: false, + code: 0, + data: null, + message: '仓库无绑定权限', + }; + } + + const Store = ctx.model.Store; + const warehouseInfo = await Store.findOne({ + where: { + id: warehouse, + status: 1, + }, + raw: true, + }); + if (!warehouseInfo || warehouseInfo.project !== 'warehouse') { + return { + success: false, + code: 0, + data: null, + message: '仓库id校验失败', + }; + } + + const PrintComputer = ctx.model.PrintComputer; + let computerId = null; + const existComputer = await PrintComputer.findOne({ + where: { + warehouse_id: warehouse, + name: printer, + }, + }); + if (existComputer) { + if (Number(existComputer.status) === 1) { + return { + success: false, + code: 0, + data: null, + message: '该仓库下打印台名称已存在且可用', + }; + } + computerId = existComputer.id; + } else { + const newComputer = await PrintComputer.create({ + warehouse_id: warehouse, + name: printer, + status: 0, + }); + computerId = newComputer.id; + } + + const bindValueObj = this.normalizeBindValue(tokenData.bindValue); + const printServiceUrl = ctx.app.config.printService.url; + let printServiceResult = null; + try { + const res = await ctx.curl(`${printServiceUrl}/auth/bind`, { + method: 'POST', + contentType: 'json', + data: { + code: tokenData.code, + printer, + warehouse, + roomId: bindValueObj && bindValueObj.uniqueId ? bindValueObj.uniqueId : '', + computerId, + }, + dataType: 'json', + }); + printServiceResult = res.data; + } catch (err) { + printServiceResult = { success: false, error: '打印服务通讯失败' }; + } + + if (printServiceResult && printServiceResult.status === 'fail') { + return { + success: false, + code: 0, + data: { + printer, + warehouse, + printServiceResult, + }, + message: printServiceResult.message || '打印服务失败', + }; + } + + await redis.del(`binding_token:${tempCode}`); + + return { + success: true, + code: 200, + data: { + code: tokenData.code, + printer, + warehouse, + computerId, + printServiceResult, + }, + message: '绑定成功', + }; + } +} + +module.exports = PrintApiService; \ No newline at end of file diff --git a/app/service/main.js b/app/service/main.js index e0e518f..17f8439 100644 --- a/app/service/main.js +++ b/app/service/main.js @@ -337,13 +337,14 @@ class MainService extends Service { try { // 3. 验证JWT令牌 - const NewauthHeader = ''; const decoded = app.jwt.verify(token, app.config.jwt.secret); const now = Math.floor(Date.now() / 1000); const expiresIn = decoded.exp - now; if (expiresIn < 14399 && expiresIn > 0) { // 移除过期时间(exp)和签发时间(iat),保留其他payload - const { exp, iat, ...payload } = decoded; + const payload = { ...decoded }; + delete payload.exp; + delete payload.iat; // 生成新的 token,使用原来的有效时间配置 const newToken = app.jwt.sign( @@ -373,8 +374,7 @@ class MainService extends Service { return result; } - if (_noNeedAuth.indexOf('*') > -1 || _noNeedAuth.indexOf(actionName) > -1) { - } else { + if (!(_noNeedAuth.indexOf('*') > -1 || _noNeedAuth.indexOf(actionName) > -1)) { if (user.auth_end && new Date(user.auth_end) < new Date()) { result.status = 406; result.message = '仓库有效期已过期'; @@ -434,21 +434,139 @@ class MainService extends Service { } /** - * 检查用户是否有API访问权限(只检查类型为api的权限) + * debug 模式下确保 API 权限存在,并绑定到 role_id=2 + * @param {string} apiPath - API路径 + * @param {Object} user - 当前用户 + * @return {Promise<{ensured:boolean, permissionId:number|null}>} 同步结果 + */ + async ensureApiPermissionInDebugMode(apiPath, user = null) { + const { ctx, app } = this; + if (app.config.debug !== true) { + return { + ensured: false, + permissionId: null, + }; + } + + const normalizedPath = String(apiPath || '').trim(); + if (!normalizedPath) { + return { + ensured: false, + permissionId: null, + }; + } + + const template = await ctx.model.Permission.findOne({ + where: { + type: 'api', + }, + attributes: [ + 'component', + 'name', + 'redirect', + 'meta_title', + 'meta_icon', + 'hidden', + 'always_show', + 'parent_id', + 'sort', + 'status', + ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + const [ permission, created ] = await ctx.model.Permission.findOrCreate({ + where: { + path: normalizedPath, + type: 'api', + }, + defaults: { + path: normalizedPath, + type: 'api', + component: template ? template.component : null, + name: template && template.name ? template.name : normalizedPath, + redirect: template ? template.redirect : null, + meta_title: template && template.meta_title ? template.meta_title : `API:${normalizedPath}`, + meta_icon: template ? template.meta_icon : null, + hidden: template ? template.hidden : 0, + always_show: template ? template.always_show : 0, + parent_id: template ? template.parent_id : null, + sort: template ? template.sort : 0, + status: 1, + }, + }); + + if (!permission || !permission.id) { + return { + ensured: false, + permissionId: null, + }; + } + + await ctx.model.RolePermission.findOrCreate({ + where: { + role_id: 2, + permission_id: permission.id, + }, + defaults: { + role_id: 2, + permission_id: permission.id, + }, + }); + + // 仅在新建权限时清理当前用户缓存,避免继续使用旧权限快照。 + if (created && user && user.id) { + await ctx.service.systems.auth.user.clearUserCache(user.id); + } + + return { + ensured: true, + permissionId: permission.id, + }; + } + + async hasRole2(employeeId) { + const { ctx } = this; + if (!employeeId) { + return false; + } + + const link = await ctx.model.EmployeeRole.findOne({ + where: { + employee_id: employeeId, + role_id: 2, + }, + attributes: [ 'id' ], + raw: true, + }); + + return !!link; + } + + /** + * 检查用户是否有 API 访问权限(只检查 type=api) * @param {Object} user - 用户信息 * @param {string} apiPath - API路径 - * @return {Promise} + * @return {Promise} 是否有权限 */ async checkApiPermission(user, apiPath) { - const { ctx } = this; - console.log(user); try { // 方法1: 从用户的权限列表中检查(如果已经加载了权限) if (user.permissions && Array.isArray(user.permissions)) { // 用户权限列表中可能包含所有权限,需要过滤出api权限 console.log('user.permissions', user.permissions); - return user.permissions.includes(apiPath); + if (user.permissions.includes(apiPath)) { + return true; + } + + const ensureResult = await this.ensureApiPermissionInDebugMode(apiPath, user); + if (!ensureResult.ensured) { + return false; + } + + return await this.hasRole2(user.employees_id); } return false; } catch (error) { diff --git a/app/service/systemMethods/setting/account.js b/app/service/systemMethods/setting/account.js index cf89f05..c8e8c6a 100644 --- a/app/service/systemMethods/setting/account.js +++ b/app/service/systemMethods/setting/account.js @@ -29,7 +29,37 @@ class accountService extends MainService { * @param {*} data */ async list(data = {}) { - return this.callSystemAccount('list', data, '获取工号列表失败'); + const { service } = this; + try { + this.prepareWhereContext(data, { + specialFieldMap: { + employee_id: { + field: 'id', + }, + account_id: { + field: 'account_id', + }, + username: { + field: '$account.username$', + }, + phone: { + field: '$account.phone$', + }, + email: { + field: '$account.email$', + }, + quickWhere: { + bucket: 'quick', + }, + }, + }); + const result = await service.systems.setting.account.list(data); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '获取工号列表失败', { + code: Number(error.code) || 500, + }); + } } /** diff --git a/app/service/systemMethods/setting/permission.js b/app/service/systemMethods/setting/permission.js new file mode 100644 index 0000000..4a62f92 --- /dev/null +++ b/app/service/systemMethods/setting/permission.js @@ -0,0 +1,60 @@ +'use strict'; + +const MainService = require('../../main'); + +class permissionService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list'; + const _noNeedLog = '*'; + const _noNeedAuth = 'list'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + async callSystemPermission(methodName, data, defaultMessage) { + const { service } = this; + try { + const result = await service.systems.setting.permission[methodName](data); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || defaultMessage, { + code: Number(error.code) || 500, + }); + } + } + + /** + * 权限列表。 + * @param {*} data + */ + async list(data = {}) { + return this.callSystemPermission('list', data, '获取权限列表失败'); + } + + /** + * 新增权限。 + * @param {*} data + */ + async add(data = {}) { + return this.callSystemPermission('add', data, '新增权限失败'); + } + + /** + * 删除权限。 + * @param {*} data + */ + async delete(data = {}) { + return this.callSystemPermission('delete', data, '删除权限失败'); + } + + /** + * 更新权限。 + * @param {*} data + */ + async update(data = {}) { + return this.callSystemPermission('update', data, '更新权限失败'); + } +} + +module.exports = permissionService; diff --git a/app/service/systemMethods/setting/role.js b/app/service/systemMethods/setting/role.js new file mode 100644 index 0000000..6f99764 --- /dev/null +++ b/app/service/systemMethods/setting/role.js @@ -0,0 +1,60 @@ +'use strict'; + +const MainService = require('../../main'); + +class roleService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list,add,delete,update'; + const _noNeedLog = '*'; + const _noNeedAuth = 'list,add,delete,update'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + async callSystemRole(methodName, data, defaultMessage) { + const { service } = this; + try { + const result = await service.systems.setting.role[methodName](data); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || defaultMessage, { + code: Number(error.code) || 500, + }); + } + } + + /** + * 角色列表。 + * @param {*} data + */ + async list(data = {}) { + return this.callSystemRole('list', data, '获取角色列表失败'); + } + + /** + * 新增角色。 + * @param {*} data + */ + async add(data = {}) { + return this.callSystemRole('add', data, '新增角色失败'); + } + + /** + * 删除角色。 + * @param {*} data + */ + async delete(data = {}) { + return this.callSystemRole('delete', data, '删除角色失败'); + } + + /** + * 更新角色。 + * @param {*} data + */ + async update(data = {}) { + return this.callSystemRole('update', data, '更新角色失败'); + } +} + +module.exports = roleService; diff --git a/app/service/systemMethods/user.js b/app/service/systemMethods/user.js index efa3bc2..5987f1c 100644 --- a/app/service/systemMethods/user.js +++ b/app/service/systemMethods/user.js @@ -5,9 +5,9 @@ const MainService = require('../main'); class userService extends MainService { constructor(ctx) { super(ctx); - const _noNeedLogin = 'login,loginByCode,register'; + const _noNeedLogin = 'login,loginByCode,register,getLoginWechatCode'; const _noNeedRight = '*'; - const _noNeedLog = 'info,getBindWechatCode'; + const _noNeedLog = 'info,getBindWechatCode,getLoginWechatCode'; const _noNeedAuth = '*'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -33,28 +33,6 @@ class userService extends MainService { message: '缺少登录码 code', }); } - //code先进行base64解码,看是否为json以及json是否有uuid字段,如果有则继续执行否则返回报错 - let decoded; - try { - const buffer = Buffer.from(code, 'base64'); - const decodedStr = buffer.toString('utf-8'); - decoded = JSON.parse(decodedStr); - } catch (err) { - return this.fail('登录失败:无效的登录码格式', { - success: false, - data: null, - code: 0, - message: '无效的登录码格式', - }); - } - if (!decoded || typeof decoded !== 'object' || !decoded.uuid) { - return this.fail('登录失败:登录码缺少必要的uuid字段', { - success: false, - data: null, - code: 0, - message: '登录码缺少必要的uuid字段', - }); - } const result = await service.systems.auth.user.loginByCode(code); if (result.code) { return this.success('登录成功', result); @@ -69,6 +47,14 @@ class userService extends MainService { } return this.fail('获取绑定微信码失败:' + result.message, result); } + async getLoginWechatCode(data) { + const { service } = this; + const result = await service.systems.auth.user.getLoginWechatCode(data); + if (result.code) { + return this.success('获取微信登录码成功', result); + } + return this.fail('获取微信登录码失败:' + result.message, result); + } async unbindWechat(data) { const { service } = this; const result = await service.systems.auth.user.unbindWechat(data); diff --git a/app/service/systems/auth/user.js b/app/service/systems/auth/user.js index ea88807..c044344 100644 --- a/app/service/systems/auth/user.js +++ b/app/service/systems/auth/user.js @@ -5,10 +5,15 @@ const crypto = require('node:crypto'); const WECHAT_BIND_CACHE_PREFIX = 'user:wechat:bind:'; const WECHAT_BIND_CODE_CACHE_PREFIX = 'user:wechat:bind:code:'; -const WECHAT_BIND_CACHE_TTL_SECONDS = 600; -const WECHAT_BIND_RECHECK_INTERVAL_MS = 5000; +const WECHAT_BIND_SCAN_CACHE_PREFIX = 'user:wechat:bind:scan:'; +const WECHAT_BIND_CACHE_TTL_SECONDS = 60; +const WECHAT_BIND_SCAN_CACHE_TTL_SECONDS = 180; const WECHAT_BIND_EVENT_CHANNEL_PREFIX = 'user:wechat:bind:event:'; const WECHAT_BIND_LONG_POLL_TIMEOUT_MS = 60000; +const WECHAT_LOGIN_CLIENT_CACHE_PREFIX = 'user:wechat:login:client:'; +const WECHAT_LOGIN_CODE_CACHE_PREFIX = 'user:wechat:login:code:'; +const WECHAT_LOGIN_EVENT_CHANNEL_PREFIX = 'user:wechat:login:event:'; +const WECHAT_LOGIN_CACHE_TTL_SECONDS = 60; class UserService extends Service { constructor(ctx) { @@ -33,45 +38,114 @@ class UserService extends Service { return `${WECHAT_BIND_CODE_CACHE_PREFIX}${code}`; } - createWechatBindCode() { - const payload = { - uuid: `${Date.now().toString(36)}-${crypto.randomBytes(8).toString('hex')}`, - }; - return Buffer.from(JSON.stringify(payload), 'utf8').toString('base64'); + getWechatBindScanCacheKey(code) { + return `${WECHAT_BIND_SCAN_CACHE_PREFIX}${code}`; + } + + getWechatLoginClientCacheKey(clientCode) { + return `${WECHAT_LOGIN_CLIENT_CACHE_PREFIX}${clientCode}`; + } + + getWechatLoginCodeCacheKey(code) { + return `${WECHAT_LOGIN_CODE_CACHE_PREFIX}${code}`; + } + + getWechatLoginEventChannel(clientCode) { + return `${WECHAT_LOGIN_EVENT_CHANNEL_PREFIX}${clientCode}`; + } + + createWechatBindCodeCandidate() { + const charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; + let code = ''; + for (let i = 0; i < 6; i++) { + const index = crypto.randomInt(0, charset.length); + code += charset[index]; + } + return code; + } + + async createUniqueSixCode(getCacheKey, maxAttempts = 200) { + for (let attempt = 0; attempt < maxAttempts; attempt++) { + const code = this.createWechatBindCodeCandidate(); + if (!this.parseWechatBindCode(code)) { + continue; + } + + const cacheKey = getCacheKey(code); + const existsState = await this.app.getCacheAsync(cacheKey); + if (!existsState) { + return code; + } + } + + throw new Error('生成登录码失败,请稍后重试'); + } + + async createWechatBindCode(maxAttempts = 200) { + return await this.createUniqueSixCode(this.getWechatBindCodeCacheKey.bind(this), maxAttempts); + } + + async createWechatLoginCode(maxAttempts = 200) { + return await this.createUniqueSixCode(this.getWechatLoginCodeCacheKey.bind(this), maxAttempts); + } + + async createWechatLoginClientCode(maxAttempts = 200) { + return await this.createUniqueSixCode(this.getWechatLoginClientCacheKey.bind(this), maxAttempts); } parseWechatBindCode(code) { - if (!code) { + const normalized = typeof code === 'string' ? code.trim().toUpperCase() : ''; + if (!normalized) { return null; } - try { - const decodedStr = Buffer.from(code, 'base64').toString('utf8'); - const parsed = JSON.parse(decodedStr); - if (!parsed || typeof parsed !== 'object' || !parsed.uuid) { - return null; - } - return parsed; - } catch (error) { + if (!/^[A-Z0-9]{6}$/.test(normalized)) { return null; } + if (!/[A-Z]/.test(normalized) || !/[0-9]/.test(normalized)) { + return null; + } + + return normalized; } formatBindWechatData(state, source = 'db') { - const nextCheckAt = Number(state.next_db_check_at || 0); + const expiresAt = Number(state.expires_at || 0); return { account_id: state.account_id, code: state.code || '', status: state.status || 'pending', is_bound: state.status === 'bound', updated_at: state.updated_at || new Date().toISOString(), - next_db_check_at: nextCheckAt, - next_poll_after_ms: Math.max(0, nextCheckAt - Date.now()), + expires_at: expiresAt > 0 ? expiresAt : null, + expire_after_ms: expiresAt > 0 ? Math.max(0, expiresAt - Date.now()) : 0, + scanned_at: state.scanned_at || null, source, ye4s_user_id: state.ye4s_user_id || null, }; } + formatLoginWechatData(state, source = 'cache') { + const expiresAt = Number(state.expires_at || 0); + return { + client_code: state.client_code || '', + code: state.code || '', + status: state.status || 'pending', + updated_at: state.updated_at || new Date().toISOString(), + expires_at: expiresAt > 0 ? expiresAt : null, + expire_after_ms: expiresAt > 0 ? Math.max(0, expiresAt - Date.now()) : 0, + source, + }; + } + + getRemainingSecondsByExpiresAt(expiresAt, fallbackTtl = WECHAT_BIND_CACHE_TTL_SECONDS) { + const ts = Number(expiresAt); + if (!Number.isFinite(ts) || ts <= 0) { + return fallbackTtl; + } + return Math.max(1, Math.ceil((ts - Date.now()) / 1000)); + } + async setWechatBindCache(cacheKey, state, ttl = WECHAT_BIND_CACHE_TTL_SECONDS) { await this.app.setCacheAsync(cacheKey, state, ttl); } @@ -84,6 +158,38 @@ class UserService extends Service { await this.app.setCacheAsync(codeCacheKey, state, ttl); } + async setWechatBindScanCache(code, state, ttl = WECHAT_BIND_SCAN_CACHE_TTL_SECONDS) { + if (!code) { + return; + } + const scanCacheKey = this.getWechatBindScanCacheKey(code); + await this.app.setCacheAsync(scanCacheKey, state, ttl); + } + + async getWechatBindScanCache(code) { + if (!code) { + return null; + } + const scanCacheKey = this.getWechatBindScanCacheKey(code); + return await this.app.getCacheAsync(scanCacheKey); + } + + async setWechatLoginClientCache(clientCode, state, ttl = WECHAT_LOGIN_CACHE_TTL_SECONDS) { + if (!clientCode) { + return; + } + const clientCacheKey = this.getWechatLoginClientCacheKey(clientCode); + await this.app.setCacheAsync(clientCacheKey, state, ttl); + } + + async setWechatLoginCodeCache(code, state, ttl = WECHAT_LOGIN_CACHE_TTL_SECONDS) { + if (!code) { + return; + } + const codeCacheKey = this.getWechatLoginCodeCacheKey(code); + await this.app.setCacheAsync(codeCacheKey, state, ttl); + } + async findYe4sBindingByAccountId(accountId) { const { ctx } = this; const ye4sClient = ctx.app.mysql.get('ye4s'); @@ -105,27 +211,16 @@ class UserService extends Service { return `${WECHAT_BIND_EVENT_CHANNEL_PREFIX}${accountId}`; } - getWechatLongPollTimeoutMs(rawTimeoutMs) { - const timeoutMs = Number(rawTimeoutMs); - if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) { - return WECHAT_BIND_LONG_POLL_TIMEOUT_MS; + getWechatLongPollTimeoutMs(timeoutMs = WECHAT_BIND_LONG_POLL_TIMEOUT_MS) { + const waitMs = Number(timeoutMs); + if (Number.isFinite(waitMs) && waitMs > 0) { + return Math.floor(waitMs); } - return Math.min(timeoutMs, WECHAT_BIND_LONG_POLL_TIMEOUT_MS); + return WECHAT_BIND_LONG_POLL_TIMEOUT_MS; } - shouldUseWechatBindLongPoll(data = {}, state = null) { - if (!state || state.status === 'bound') { - return false; - } - if (data.forceRefresh) { - return false; - } - if (data.isInit === true || data.init === true || data.firstLoad === true) { - return false; - } - - const explicitEnable = data.longPoll === true || data.waitForChange === true; - return explicitEnable; + shouldUseWechatBindLongPoll(data = {}) { + return data.longPoll === true; } async publishWechatBindEvent(accountId, payload = {}) { @@ -246,62 +341,99 @@ class UserService extends Service { }); } - async refreshWechatBindState(accountId, cachedState = null) { + async refreshWechatBindState(accountId, cachedState = null, options = {}) { const now = Date.now(); const cacheKey = this.getWechatBindCacheKey(accountId); + const forceNewCode = options.forceNewCode === true; const ye4sBinding = await this.findYe4sBindingByAccountId(accountId); if (ye4sBinding) { - const dbCode = typeof ye4sBinding.tmp_code === 'string' ? ye4sBinding.tmp_code.trim() : ''; - const bindState = { + const boundState = { account_id: accountId, status: 'bound', - code: dbCode || (cachedState && cachedState.code) || this.createWechatBindCode(), + code: '', updated_at: new Date().toISOString(), - next_db_check_at: now + WECHAT_BIND_RECHECK_INTERVAL_MS, ye4s_user_id: ye4sBinding.id || null, + expires_at: null, + scanned_at: null, }; - await Promise.all([ - this.setWechatBindCache(cacheKey, bindState, WECHAT_BIND_CACHE_TTL_SECONDS), - this.setWechatBindCodeCache(bindState.code, bindState, WECHAT_BIND_CACHE_TTL_SECONDS), - ]); + await this.setWechatBindCache(cacheKey, boundState, WECHAT_BIND_CACHE_TTL_SECONDS); - const hasChanged = !cachedState || cachedState.status !== 'bound' || cachedState.code !== bindState.code; + const hasChanged = !cachedState || cachedState.status !== 'bound' || Number(cachedState.ye4s_user_id || 0) !== Number(boundState.ye4s_user_id || 0); if (hasChanged) { await this.publishWechatBindEvent(accountId, { status: 'bound', - code: bindState.code, + code: '', source: 'db', }); } return { - state: bindState, + state: boundState, source: 'db', message: '账号已绑定微信', }; } - const code = (cachedState && cachedState.code) || this.createWechatBindCode(); + const cachedCode = cachedState && typeof cachedState.code === 'string' ? cachedState.code.trim().toUpperCase() : ''; + let codeState = null; + if (!forceNewCode && cachedCode && this.parseWechatBindCode(cachedCode)) { + const codeCacheKey = this.getWechatBindCodeCacheKey(cachedCode); + codeState = await this.app.getCacheAsync(codeCacheKey); + } + + const codeAccountId = Number(codeState && codeState.account_id); + const cachedExpiresAt = Number((codeState && codeState.expires_at) || (cachedState && cachedState.expires_at)); + const cachedCodeValid = !forceNewCode && cachedCode && this.parseWechatBindCode(cachedCode) && Number.isFinite(codeAccountId) && codeAccountId === accountId && (Number.isFinite(cachedExpiresAt) ? cachedExpiresAt > now : !!codeState); + + if (cachedCodeValid) { + const scanState = await this.getWechatBindScanCache(cachedCode); + const normalizedStatus = scanState ? 'scanned' : 'pending'; + const state = { + account_id: accountId, + status: normalizedStatus, + code: cachedCode, + updated_at: cachedState.updated_at || new Date().toISOString(), + ye4s_user_id: null, + expires_at: Number.isFinite(cachedExpiresAt) ? cachedExpiresAt : null, + scanned_at: scanState && scanState.scanned_at ? scanState.scanned_at : null, + }; + return { + state, + source: 'cache', + message: normalizedStatus === 'scanned' ? '二维码已被扫码,请继续绑定' : '获取绑定码成功(缓存)', + }; + } + + const nextCode = await this.createWechatBindCode(); + const expiresAt = now + WECHAT_BIND_CACHE_TTL_SECONDS * 1000; const pendingState = { account_id: accountId, status: 'pending', - code, + code: nextCode, updated_at: new Date().toISOString(), - next_db_check_at: now + WECHAT_BIND_RECHECK_INTERVAL_MS, ye4s_user_id: null, + expires_at: expiresAt, + scanned_at: null, }; - await Promise.all([ + const tasks = [ this.setWechatBindCache(cacheKey, pendingState, WECHAT_BIND_CACHE_TTL_SECONDS), - this.setWechatBindCodeCache(pendingState.code, pendingState, WECHAT_BIND_CACHE_TTL_SECONDS), - ]); + this.setWechatBindCodeCache(nextCode, pendingState, WECHAT_BIND_CACHE_TTL_SECONDS), + ]; + + if (cachedCode && cachedCode !== nextCode) { + tasks.push(this.setWechatBindCodeCache(cachedCode, null, 1)); + tasks.push(this.setWechatBindScanCache(cachedCode, null, 1)); + } + + await Promise.all(tasks); return { state: pendingState, - source: code === (cachedState && cachedState.code) ? 'cache-refresh' : 'generated', - message: '账号未绑定,已生成绑定码', + source: forceNewCode ? 'refreshed' : 'generated', + message: forceNewCode ? '长轮询超时,已刷新绑定码' : '账号未绑定,已生成绑定码', }; } @@ -361,75 +493,77 @@ class UserService extends Service { } /** - * 登录码登录:使用 ye4s_user.tmp_code 绑定的 wms_account_id 登录 - * @param {string} code 登录码(ye4s_user.tmp_code) + * 登录码登录:使用本系统缓存登录码完成登录 + * @param {string} code 登录码(WECHAT_LOGIN_CODE) * @return {Object} 登录结果 */ async loginByCode(code) { - const { ctx, app } = this; + const { app } = this; try { - const normalizedCode = typeof code === 'string' ? code.trim() : ''; + const normalizedCode = this.parseWechatBindCode(code); if (!normalizedCode) { return { success: false, data: null, code: 0, - message: '缺少登录码 code', - }; - } - - const ye4sClient = ctx.app.mysql.get('ye4s'); - const ye4sUser = await ye4sClient.get('ye4s_user', { - tmp_code: normalizedCode, - }); - - if (!ye4sUser) { - return { - success: false, - data: null, - code: 0, - message: '登录码不存在', - }; - } - - const wmsAccountId = Number(ye4sUser.wms_account_id); - if (!Number.isFinite(wmsAccountId) || wmsAccountId <= 0) { - return { - success: false, - data: null, - code: 0, - message: '该登录码未绑定WMS账号', - }; - } - - const user = await ctx.model.Account.findOne({ - where: { id: wmsAccountId }, - }); - - if (!user) { - return { - success: false, - data: null, - code: 0, - message: '绑定的WMS账号不存在', + message: '缺少或无效的登录码 code', }; } + const codeCacheKey = this.getWechatLoginCodeCacheKey(normalizedCode); + let codeState = null; try { - this.checkUserStatus(user); - } catch (statusError) { - app.coreLogger.warn(`登录码登录失败: 账号状态异常 [${user.id}] - ${statusError.message}`); + codeState = await this.app.getCacheAsync(codeCacheKey); + } catch (cacheErr) { + app.coreLogger.warn(`读取登录码缓存失败: ${cacheErr.message}`); + } + + if (!codeState) { return { success: false, data: null, code: 0, - message: '绑定账号状态异常', + message: '登录码不存在或已过期', }; } - await this.updateLastLoginTime(user.id); - return this.buildLoginResult(user); + const codeStateWithCode = { + ...(codeState || {}), + code: normalizedCode, + }; + + let loginResponse = await this.tryBuildWechatLoginTokenFromState(codeState.client_code || '', codeStateWithCode); + if (loginResponse && loginResponse.success) { + return loginResponse; + } + + const clientCode = this.parseWechatBindCode(codeState && codeState.client_code); + if (clientCode) { + let clientState = null; + try { + clientState = await this.app.getCacheAsync(this.getWechatLoginClientCacheKey(clientCode)); + } catch (cacheErr) { + app.coreLogger.warn(`读取客户端登录状态缓存失败: ${cacheErr.message}`); + } + + if (clientState) { + loginResponse = await this.tryBuildWechatLoginTokenFromState(clientCode, { + ...clientState, + code: normalizedCode, + }); + if (loginResponse && loginResponse.success) { + return loginResponse; + } + } + } + + return { + success: false, + data: null, + code: 0, + message: '登录码尚未授权,请扫码确认后重试', + }; } catch (error) { app.coreLogger.error(`登录码登录异常: ${error.message}`); return { @@ -441,6 +575,447 @@ class UserService extends Service { } } + async waitForLoginCodeRefresh(timeoutMs = WECHAT_BIND_LONG_POLL_TIMEOUT_MS) { + const waitMs = this.getWechatLongPollTimeoutMs(timeoutMs); + await new Promise(resolve => { + setTimeout(resolve, waitMs); + }); + } + + isTransientWechatLoginError(error) { + if (!error) { + return false; + } + const code = typeof error.code === 'string' ? error.code : ''; + const message = typeof error.message === 'string' ? error.message.toLowerCase() : ''; + const transientCodes = new Set([ 'ECONNRESET', 'ETIMEDOUT', 'EPIPE', 'PROTOCOL_CONNECTION_LOST', 'ECONNREFUSED' ]); + if (transientCodes.has(code)) { + return true; + } + return message.includes('econnreset') || message.includes('read econnreset') || message.includes('connection lost') || message.includes('timeout'); + } + + extractYe4sUserIdFromLoginEvent(eventData) { + if (!eventData) { + return null; + } + + if (typeof eventData === 'number' || typeof eventData === 'string') { + const id = Number(eventData); + return Number.isFinite(id) && id > 0 ? id : null; + } + + if (typeof eventData !== 'object') { + return null; + } + + const rawId = eventData.ye4s_user_id ?? eventData.ye4sUserId ?? eventData.user_id ?? eventData.userId ?? eventData.value; + const ye4sUserId = Number(rawId); + return Number.isFinite(ye4sUserId) && ye4sUserId > 0 ? ye4sUserId : null; + } + + async waitForWechatLoginEvent(clientCode, timeoutMs = WECHAT_BIND_LONG_POLL_TIMEOUT_MS) { + const { app } = this; + const normalizedClientCode = this.parseWechatBindCode(clientCode); + const cacheRedis = app.redis && app.redis.get ? app.redis.get('cache') : null; + if (!cacheRedis || !normalizedClientCode || typeof cacheRedis.duplicate !== 'function') { + return { + timed_out: true, + reason: 'redis_not_available', + event: null, + }; + } + + const channel = this.getWechatLoginEventChannel(normalizedClientCode); + const waitMs = this.getWechatLongPollTimeoutMs(timeoutMs); + const subscriber = cacheRedis.duplicate(); + + return await new Promise(resolve => { + let settled = false; + let timer = null; + + const cleanup = () => { + subscriber.removeListener('message', onMessage); + subscriber.removeListener('error', onError); + Promise.resolve(subscriber.unsubscribe(channel)).catch(() => null).finally(() => { + if (typeof subscriber.quit === 'function') { + Promise.resolve(subscriber.quit()).catch(() => { + if (typeof subscriber.disconnect === 'function') { + subscriber.disconnect(); + } + }); + return; + } + if (typeof subscriber.disconnect === 'function') { + subscriber.disconnect(); + } + }); + }; + + const finalize = result => { + if (settled) { + return; + } + settled = true; + if (timer) { + clearTimeout(timer); + } + cleanup(); + resolve(result); + }; + + const onMessage = (messageChannel, message) => { + if (messageChannel !== channel) { + return; + } + let eventData = null; + try { + eventData = message ? JSON.parse(message) : null; + } catch (error) { + eventData = message; + } + const ye4sUserId = this.extractYe4sUserIdFromLoginEvent(eventData); + finalize({ + timed_out: false, + reason: 'event', + event: eventData, + ye4s_user_id: ye4sUserId, + }); + }; + + const onError = error => { + app.coreLogger.warn(`订阅微信登录事件失败: ${error.message}`); + finalize({ + timed_out: true, + reason: 'subscribe_error', + event: null, + }); + }; + + timer = setTimeout(() => { + finalize({ + timed_out: true, + reason: 'timeout', + event: null, + }); + }, waitMs); + + subscriber.on('message', onMessage); + subscriber.on('error', onError); + + Promise.resolve(subscriber.subscribe(channel)).catch(error => { + app.coreLogger.warn(`订阅微信登录频道失败: ${error.message}`); + finalize({ + timed_out: true, + reason: 'subscribe_failed', + event: null, + }); + }); + }); + } + + async loginByYe4sUserId(ye4sUserId) { + const { ctx, app } = this; + + const normalizedYe4sUserId = Number(ye4sUserId); + if (!Number.isFinite(normalizedYe4sUserId) || normalizedYe4sUserId <= 0) { + return { + success: false, + code: 0, + data: null, + message: '登录事件缺少有效的 ye4s_user_id', + }; + } + + const maxAttempts = 2; + for (let attempt = 1; attempt <= maxAttempts; attempt++) { + try { + const ye4sClient = ctx.app.mysql.get('ye4s'); + const ye4sUser = await ye4sClient.get('ye4s_user', { id: normalizedYe4sUserId }); + if (!ye4sUser) { + return { + success: false, + code: 0, + data: null, + message: 'ye4s 用户不存在', + }; + } + + const wmsAccountId = Number(ye4sUser.wms_account_id); + if (!Number.isFinite(wmsAccountId) || wmsAccountId <= 0) { + return { + success: false, + code: 0, + data: null, + message: '该 ye4s 用户未绑定WMS账号', + }; + } + + const user = await ctx.model.Account.findOne({ + where: { id: wmsAccountId }, + }); + + if (!user) { + return { + success: false, + code: 0, + data: null, + message: '绑定的WMS账号不存在', + }; + } + + try { + this.checkUserStatus(user); + } catch (statusError) { + app.coreLogger.warn(`微信事件登录失败: 账号状态异常 [${user.id}] - ${statusError.message}`); + return { + success: false, + code: 0, + data: null, + message: '绑定账号状态异常', + }; + } + + await this.updateLastLoginTime(user.id); + const loginResult = await this.buildLoginResult(user, { includeUser: false }); + return loginResult; + } catch (error) { + const isTransient = this.isTransientWechatLoginError(error); + if (isTransient && attempt < maxAttempts) { + app.coreLogger.warn(`微信事件登录异常,准备重试(${attempt}/${maxAttempts}): ${error.message}`); + await this.waitForLoginCodeRefresh(200); + continue; + } + + app.coreLogger.error(`微信事件登录异常: ${error.message}`); + return { + success: false, + code: 0, + data: null, + message: '登录失败,请稍后重试', + }; + } + } + + return { + success: false, + code: 0, + data: null, + message: '登录失败,请稍后重试', + }; + } + + async tryBuildWechatLoginTokenFromState(clientCode, state) { + const eventYe4sUserId = this.extractYe4sUserIdFromLoginEvent(state); + if (!Number.isFinite(Number(eventYe4sUserId)) || Number(eventYe4sUserId) <= 0) { + return null; + } + + const loginResult = await this.loginByYe4sUserId(eventYe4sUserId); + if (!loginResult || !loginResult.success || !loginResult.data || !loginResult.data.token) { + return { + success: false, + code: 0, + data: null, + message: loginResult && loginResult.message ? loginResult.message : '登录事件处理失败', + }; + } + + const cleanupCode = state && typeof state.code === 'string' ? state.code.trim().toUpperCase() : ''; + await Promise.all([ + this.setWechatLoginClientCache(clientCode, null, 1), + cleanupCode ? this.setWechatLoginCodeCache(cleanupCode, null, 1) : Promise.resolve(), + ]); + + return { + success: true, + code: 200, + data: { + client_code: clientCode, + status: 'authorized', + source: 'event', + ye4s_user_id: Number(eventYe4sUserId), + loginToken: loginResult.data.token, + }, + message: '已收到登录事件并签发登录令牌', + }; + } + + async refreshWechatLoginState(clientCode, cachedState = null, options = {}) { + const now = Date.now(); + const forceNewCode = options.forceNewCode === true; + const normalizedClientCode = this.parseWechatBindCode(clientCode); + + if (!normalizedClientCode) { + throw new Error('无效的客户端编码格式'); + } + + const cachedCode = cachedState && typeof cachedState.code === 'string' ? cachedState.code.trim().toUpperCase() : ''; + const cachedExpiresAt = Number(cachedState && cachedState.expires_at); + const cachedCodeValid = !forceNewCode && cachedCode && this.parseWechatBindCode(cachedCode) && Number.isFinite(cachedExpiresAt) && cachedExpiresAt > now; + + if (cachedCodeValid) { + return { + state: { + client_code: normalizedClientCode, + code: cachedCode, + status: 'pending', + updated_at: cachedState.updated_at || new Date().toISOString(), + expires_at: cachedExpiresAt, + }, + source: 'cache', + message: `客户端编码 ${normalizedClientCode} 已命中缓存登录码`, + }; + } + + const nextCode = await this.createWechatLoginCode(); + const expiresAt = now + WECHAT_LOGIN_CACHE_TTL_SECONDS * 1000; + const loginState = { + client_code: normalizedClientCode, + code: nextCode, + status: 'pending', + updated_at: new Date().toISOString(), + expires_at: expiresAt, + }; + + const tasks = [ + this.setWechatLoginClientCache(normalizedClientCode, loginState, WECHAT_LOGIN_CACHE_TTL_SECONDS), + this.setWechatLoginCodeCache(nextCode, loginState, WECHAT_LOGIN_CACHE_TTL_SECONDS), + ]; + + if (cachedCode && cachedCode !== nextCode) { + tasks.push(this.setWechatLoginCodeCache(cachedCode, null, 1)); + } + + await Promise.all(tasks); + + return { + state: loginState, + source: forceNewCode ? 'refreshed' : 'generated', + message: forceNewCode ? + `客户端编码 ${normalizedClientCode} 长轮询结束,已刷新登录码` : + `客户端编码 ${normalizedClientCode} 已生成登录码`, + }; + } + + /** + * 获取微信扫码登录码 + * @param {Object} data + * @return {Object} + */ + async getLoginWechatCode(data = {}) { + const { app } = this; + try { + const rawClientCode = typeof data.clientCode === 'string' ? data.clientCode : (typeof data.client_code === 'string' ? data.client_code : ''); + const hasInputClientCode = !!rawClientCode && rawClientCode.trim().length > 0; + + let clientCode = ''; + let shouldWaitRefresh = false; + let cachedState = null; + + if (hasInputClientCode) { + const normalizedClientCode = this.parseWechatBindCode(rawClientCode); + if (!normalizedClientCode) { + return { + success: false, + code: 0, + data: null, + message: '无效的客户端编码格式', + }; + } + + const inputClientCacheKey = this.getWechatLoginClientCacheKey(normalizedClientCode); + try { + cachedState = await this.app.getCacheAsync(inputClientCacheKey); + } catch (cacheErr) { + app.coreLogger.warn(`读取微信登录码缓存失败: ${cacheErr.message}`); + } + + // 传入 clientCode 但缓存不存在时,按空值处理,重新分配新的客户端编码。 + if (cachedState) { + clientCode = normalizedClientCode; + shouldWaitRefresh = true; + } else { + clientCode = await this.createWechatLoginClientCode(); + } + } else { + clientCode = await this.createWechatLoginClientCode(); + } + + const clientCacheKey = this.getWechatLoginClientCacheKey(clientCode); + if (!cachedState) { + try { + cachedState = await this.app.getCacheAsync(clientCacheKey); + } catch (cacheErr) { + app.coreLogger.warn(`读取微信登录码缓存失败: ${cacheErr.message}`); + } + } + + // 若外部已将 ye4s_user_id 写入 clientCode 对应缓存,直接登录并返回,不再等待长轮询。 + if (hasInputClientCode && cachedState) { + const immediateLoginResult = await this.tryBuildWechatLoginTokenFromState(clientCode, cachedState); + if (immediateLoginResult && immediateLoginResult.success) { + return immediateLoginResult; + } + if (immediateLoginResult && immediateLoginResult.success === false) { + app.coreLogger.warn(`微信登录缓存态直登失败,继续轮询: ${immediateLoginResult.message}`); + } + } + + if (shouldWaitRefresh) { + const waitResult = await this.waitForWechatLoginEvent(clientCode, this.getWechatLongPollTimeoutMs()); + const eventYe4sUserId = Number(waitResult && waitResult.ye4s_user_id); + if (!waitResult.timed_out && Number.isFinite(eventYe4sUserId) && eventYe4sUserId > 0) { + const eventState = { + ...(cachedState || {}), + ye4s_user_id: eventYe4sUserId, + }; + const loginResponse = await this.tryBuildWechatLoginTokenFromState(clientCode, eventState); + if (loginResponse && loginResponse.success) { + return loginResponse; + } + app.coreLogger.warn(`微信事件登录未成功,降级为刷新登录码: ${loginResponse && loginResponse.message ? loginResponse.message : 'unknown_error'}`); + } + + try { + cachedState = await this.app.getCacheAsync(clientCacheKey); + } catch (cacheErr) { + app.coreLogger.warn(`读取微信登录码缓存失败: ${cacheErr.message}`); + } + + const refreshed = await this.refreshWechatLoginState(clientCode, cachedState, { + forceNewCode: true, + }); + + return { + success: true, + code: 200, + data: this.formatLoginWechatData(refreshed.state, refreshed.source), + message: refreshed.message, + }; + } + + const generated = await this.refreshWechatLoginState(clientCode, cachedState, { + forceNewCode: false, + }); + + return { + success: true, + code: 200, + data: this.formatLoginWechatData(generated.state, generated.source), + message: generated.message, + }; + } catch (error) { + app.coreLogger.error(`获取微信登录码失败: ${error.message}`); + return { + success: false, + code: 0, + data: null, + message: '获取微信登录码失败,请稍后重试', + }; + } + } + /** * 获取微信绑定码(缓存优先,低频复查DB,适配轮询) * @param {Object} data @@ -460,9 +1035,8 @@ class UserService extends Service { } const cacheKey = this.getWechatBindCacheKey(accountId); - const forceRefresh = !!data.forceRefresh; - const now = Date.now(); - const waitTimeoutMs = this.getWechatLongPollTimeoutMs(data.waitTimeoutMs); + const useLongPoll = this.shouldUseWechatBindLongPoll(data); + const waitTimeoutMs = this.getWechatLongPollTimeoutMs(); let cachedState = null; try { @@ -471,57 +1045,44 @@ class UserService extends Service { app.coreLogger.warn(`读取微信绑定缓存失败: ${cacheErr.message}`); } - if (cachedState && !forceRefresh) { - const nextCheckAt = Number(cachedState.next_db_check_at || 0); - let refreshedState = null; - if (nextCheckAt <= now) { - refreshedState = await this.refreshWechatBindState(accountId, cachedState); - cachedState = refreshedState.state; - } - - if (this.shouldUseWechatBindLongPoll(data, cachedState)) { - const waitResult = await this.waitForWechatBindEvent(accountId, waitTimeoutMs); - try { - cachedState = await this.app.getCacheAsync(cacheKey); - } catch (cacheErr) { - app.coreLogger.warn(`读取微信绑定缓存失败: ${cacheErr.message}`); - } - - const nextState = await this.refreshWechatBindState(accountId, cachedState); - const timeoutMessage = waitResult.timed_out ? '等待绑定状态变化超时,返回当前状态' : nextState.message; - - return { - success: true, - code: 200, - data: this.formatBindWechatData(nextState.state, nextState.source), - message: timeoutMessage, - }; - } - - if (refreshedState) { - return { - success: true, - code: 200, - data: this.formatBindWechatData(refreshedState.state, refreshedState.source), - message: refreshedState.message, - }; - } + const refreshed = await this.refreshWechatBindState(accountId, cachedState, { + forceNewCode: false, + }); + if (refreshed.state.status === 'bound' || !useLongPoll) { return { success: true, code: 200, - data: this.formatBindWechatData(cachedState, 'cache'), - message: '获取绑定码成功(缓存)', + data: this.formatBindWechatData(refreshed.state, refreshed.source), + message: refreshed.message, }; } - const refreshed = await this.refreshWechatBindState(accountId, cachedState); + const waitResult = await this.waitForWechatBindEvent(accountId, waitTimeoutMs); + try { + cachedState = await this.app.getCacheAsync(cacheKey); + } catch (cacheErr) { + app.coreLogger.warn(`读取微信绑定缓存失败: ${cacheErr.message}`); + } + + const nextState = await this.refreshWechatBindState(accountId, cachedState, { + forceNewCode: waitResult.timed_out, + }); + + if (waitResult.timed_out) { + return { + success: true, + code: 200, + data: this.formatBindWechatData(nextState.state, nextState.source), + message: '长轮询结束未检测到状态变化,已刷新绑定码', + }; + } return { success: true, code: 200, - data: this.formatBindWechatData(refreshed.state, refreshed.source), - message: refreshed.message, + data: this.formatBindWechatData(nextState.state, nextState.source), + message: nextState.message, }; } catch (error) { app.coreLogger.error(`获取微信绑定码失败: ${error.message}`); @@ -542,8 +1103,19 @@ class UserService extends Service { async getUserByTempCode(data = {}) { const { ctx, app } = this; try { - const code = typeof data.code === 'string' ? data.code.trim() : ''; - if (!code) { + const loadAccountRealName = async accountId => { + const account = await ctx.model.Account.findOne({ + where: { + id: accountId, + }, + attributes: [ 'id', 'real_name' ], + raw: true, + }); + return account && account.real_name ? account.real_name : ''; + }; + + const rawCode = typeof data.code === 'string' ? data.code.trim() : ''; + if (!rawCode) { return { success: false, code: 0, @@ -552,7 +1124,8 @@ class UserService extends Service { }; } - if (!this.parseWechatBindCode(code)) { + const code = this.parseWechatBindCode(rawCode); + if (!code) { return { success: false, code: 0, @@ -570,65 +1143,60 @@ class UserService extends Service { } const cachedAccountId = Number(codeState && codeState.account_id); - if (Number.isFinite(cachedAccountId) && cachedAccountId > 0) { + if (!Number.isFinite(cachedAccountId) || cachedAccountId <= 0) { return { - success: true, - code: 200, - data: { - account_id: cachedAccountId, - code, - status: codeState.status || 'pending', - source: 'cache', - updated_at: codeState.updated_at || new Date().toISOString(), - }, - message: '获取账号成功', + success: false, + code: 0, + data: null, + message: '绑定码不存在或已过期', }; } - const ye4sClient = ctx.app.mysql.get('ye4s'); - const ye4sUser = await ye4sClient.get('ye4s_user', { - tmp_code: code, + const realName = await loadAccountRealName(cachedAccountId); + const scanState = { + account_id: cachedAccountId, + code, + status: 'scanned', + scanned_at: new Date().toISOString(), + source: 'gateway-scan', + }; + + const codeExpiresAt = Number(codeState && codeState.expires_at); + const scannedBindState = { + account_id: cachedAccountId, + code, + status: 'scanned', + scanned_at: scanState.scanned_at, + updated_at: scanState.scanned_at, + ye4s_user_id: null, + expires_at: Number.isFinite(codeExpiresAt) ? codeExpiresAt : null, + }; + const bindCacheTtl = this.getRemainingSecondsByExpiresAt(codeExpiresAt, WECHAT_BIND_CACHE_TTL_SECONDS); + + await Promise.all([ + this.setWechatBindScanCache(code, scanState, WECHAT_BIND_SCAN_CACHE_TTL_SECONDS), + this.setWechatBindCache(this.getWechatBindCacheKey(cachedAccountId), scannedBindState, bindCacheTtl), + ]); + await this.publishWechatBindEvent(cachedAccountId, { + status: 'scanned', + code, + scanned_at: scanState.scanned_at, + source: 'gateway-scan', }); - const wmsAccountId = Number(ye4sUser && ye4sUser.wms_account_id); - if (Number.isFinite(wmsAccountId) && wmsAccountId > 0) { - const boundState = { - account_id: wmsAccountId, - status: 'bound', - code, - updated_at: new Date().toISOString(), - next_db_check_at: Date.now() + WECHAT_BIND_RECHECK_INTERVAL_MS, - ye4s_user_id: ye4sUser.id || null, - }; - await Promise.all([ - this.setWechatBindCodeCache(code, boundState, WECHAT_BIND_CACHE_TTL_SECONDS), - this.setWechatBindCache(this.getWechatBindCacheKey(wmsAccountId), boundState, WECHAT_BIND_CACHE_TTL_SECONDS), - ]); - await this.publishWechatBindEvent(wmsAccountId, { - status: 'bound', - code, - source: 'api', - }); - - return { - success: true, - code: 200, - data: { - account_id: wmsAccountId, - code, - status: 'bound', - source: 'db', - updated_at: boundState.updated_at, - }, - message: '获取账号成功', - }; - } - return { - success: false, - code: 0, - data: null, - message: '绑定码不存在或已过期', + success: true, + code: 200, + data: { + account_id: cachedAccountId, + real_name: realName, + code, + status: 'scanned', + source: 'scan-cache', + scanned_at: scanState.scanned_at, + updated_at: codeState && codeState.updated_at ? codeState.updated_at : scanState.scanned_at, + }, + message: '扫码状态已记录', }; } catch (error) { app.coreLogger.error(`根据绑定码获取账号失败: ${error.message}`); @@ -649,11 +1217,11 @@ class UserService extends Service { async bindAccountByTempCode(data = {}) { const { ctx, app } = this; try { - const code = typeof data.code === 'string' ? data.code.trim() : ''; + const rawCode = typeof data.code === 'string' ? data.code.trim() : ''; const rawYe4sUserId = data.ye4s_user_id ?? data.ye4sUserId; const ye4sUserId = Number(rawYe4sUserId); - if (!code) { + if (!rawCode) { return { success: false, code: 0, @@ -662,7 +1230,8 @@ class UserService extends Service { }; } - if (!this.parseWechatBindCode(code)) { + const code = this.parseWechatBindCode(rawCode); + if (!code) { return { success: false, code: 0, @@ -680,23 +1249,14 @@ class UserService extends Service { }; } - const userResult = await this.getUserByTempCode({ code }); - if (!userResult || !userResult.success) { - return { - success: false, - code: 0, - data: null, - message: userResult && userResult.message ? userResult.message : '绑定码不存在或已过期', - }; - } - - const accountId = Number(userResult.data && userResult.data.account_id); + const scanState = await this.getWechatBindScanCache(code); + const accountId = Number(scanState && scanState.account_id); if (!Number.isFinite(accountId) || accountId <= 0) { return { success: false, code: 0, data: null, - message: '绑定码未匹配到有效账号', + message: '未检测到扫码记录或扫码状态已过期,请重新扫码', }; } @@ -720,20 +1280,27 @@ class UserService extends Service { const boundState = { account_id: accountId, status: 'bound', - code, + code: '', updated_at: new Date().toISOString(), - next_db_check_at: Date.now() + WECHAT_BIND_RECHECK_INTERVAL_MS, ye4s_user_id: ye4sUserId, + expires_at: null, + scanned_at: scanState && scanState.scanned_at ? scanState.scanned_at : null, }; await Promise.all([ - this.setWechatBindCodeCache(code, boundState, WECHAT_BIND_CACHE_TTL_SECONDS), this.setWechatBindCache(this.getWechatBindCacheKey(accountId), boundState, WECHAT_BIND_CACHE_TTL_SECONDS), + this.setWechatBindCodeCache(code, null, 1), + this.setWechatBindScanCache(code, { + ...scanState, + status: 'bound', + ye4s_user_id: ye4sUserId, + bound_at: boundState.updated_at, + }, WECHAT_BIND_SCAN_CACHE_TTL_SECONDS), ]); await this.publishWechatBindEvent(accountId, { status: 'bound', - code, + code: '', source: 'gateway-bind', }); @@ -791,17 +1358,6 @@ class UserService extends Service { let affectedRows = 0; for (const row of bindRows) { - const rowCode = typeof row.tmp_code === 'string' ? row.tmp_code.trim() : ''; - if (rowCode) { - await this.setWechatBindCodeCache(rowCode, { - account_id: accountId, - status: 'unbound', - code: rowCode, - updated_at: new Date().toISOString(), - next_db_check_at: Date.now() + WECHAT_BIND_RECHECK_INTERVAL_MS, - ye4s_user_id: row.id || null, - }, WECHAT_BIND_CACHE_TTL_SECONDS); - } try { const ret = await ye4sClient.update('ye4s_user', { id: row.id, @@ -819,17 +1375,6 @@ class UserService extends Service { } const cacheKey = this.getWechatBindCacheKey(accountId); - const cachedState = await this.app.getCacheAsync(cacheKey); - if (cachedState && cachedState.code) { - await this.setWechatBindCodeCache(cachedState.code, { - account_id: accountId, - status: 'unbound', - code: cachedState.code, - updated_at: new Date().toISOString(), - next_db_check_at: Date.now() + WECHAT_BIND_RECHECK_INTERVAL_MS, - ye4s_user_id: cachedState.ye4s_user_id || null, - }, WECHAT_BIND_CACHE_TTL_SECONDS); - } await this.setWechatBindCache(cacheKey, null, 1); await this.publishWechatBindEvent(accountId, { status: 'unbound', diff --git a/app/service/systems/setting/account.js b/app/service/systems/setting/account.js index 27f273e..1190b04 100644 --- a/app/service/systems/setting/account.js +++ b/app/service/systems/setting/account.js @@ -1,10 +1,34 @@ 'use strict'; const Service = require('egg').Service; +const { parseWhereConditions } = require('../../../lib/query_condition_parser'); const RESERVED_EMPLOYEE_NAME = '测试工号保留'; class SettingAccountService extends Service { + getListWhereSpecialFieldMap() { + return { + employee_id: { + field: 'id', + }, + account_id: { + field: 'account_id', + }, + username: { + field: '$account.username$', + }, + phone: { + field: '$account.phone$', + }, + email: { + field: '$account.email$', + }, + quickWhere: { + bucket: 'quick', + }, + }; + } + createError(message, code = 500) { const error = new Error(message); error.code = code; @@ -127,10 +151,214 @@ class SettingAccountService extends Service { return Number(currentRole.role_id); } - async formatEmployeeRow(employee) { - const account = await this.getWmsClient().get('wms_account', { - id: employee.account_id, + normalizeRoleIds(ids) { + if (!Array.isArray(ids) || ids.length === 0) { + throw this.createError('ids 参数不能为空', 400); + } + + const roleIds = []; + for (const roleId of ids) { + const normalized = Number(roleId); + if (!Number.isFinite(normalized) || normalized <= 0) { + throw this.createError('ids 必须是正整数数组', 400); + } + roleIds.push(normalized); + } + return Array.from(new Set(roleIds)); + } + + flattenRoleTreeMeta(roleNodes, idCollector = [], parentMap = new Map()) { + if (!Array.isArray(roleNodes) || roleNodes.length === 0) { + return { idCollector, parentMap }; + } + + for (const node of roleNodes) { + const roleId = Number(node && node.role_id); + if (Number.isFinite(roleId) && roleId > 0) { + idCollector.push(roleId); + parentMap.set(roleId, Number(node && node.pid ? node.pid : 0)); + } + + const children = Array.isArray(node && node.children) ? node.children : []; + this.flattenRoleTreeMeta(children, idCollector, parentMap); + } + + return { idCollector, parentMap }; + } + + async resolveAssignableRoleScope() { + const roleResult = await this.ctx.service.systems.setting.role.list({ + includeDisabled: false, + includeSystem: false, }); + + const roleTree = roleResult && roleResult.data && Array.isArray(roleResult.data.roles) + ? roleResult.data.roles + : []; + const { idCollector, parentMap } = this.flattenRoleTreeMeta(roleTree, [], new Map()); + return { + roleIdSet: new Set(idCollector), + parentMap, + }; + } + + pruneDescendantRoleIds(roleIds, parentMap) { + const selected = new Set(roleIds); + const pruned = []; + + for (const roleId of roleIds) { + let current = roleId; + let keep = true; + const visited = new Set(); + + while (true) { + const parentId = Number(parentMap.get(current) || 0); + if (!Number.isFinite(parentId) || parentId <= 0) { + break; + } + if (visited.has(parentId)) { + break; + } + visited.add(parentId); + + if (selected.has(parentId)) { + keep = false; + break; + } + + current = parentId; + } + + if (keep) { + pruned.push(roleId); + } + } + + return Array.from(new Set(pruned)); + } + + async resolveRequestedRoleIds(data = {}, options = {}) { + const required = options.required === true; + const hasIds = Object.prototype.hasOwnProperty.call(data, 'ids'); + const hasRoleIds = Object.prototype.hasOwnProperty.call(data, 'role_ids'); + + if (!hasIds && !hasRoleIds) { + if (required) { + throw this.createError('ids 参数不能为空', 400); + } + return null; + } + + const rawRoleIds = hasIds ? data.ids : data.role_ids; + const roleIds = this.normalizeRoleIds(rawRoleIds); + + const { roleIdSet, parentMap } = await this.resolveAssignableRoleScope(); + if (roleIdSet.size === 0) { + throw this.createError('当前角色范围为空,无法分配角色', 400); + } + + const outOfScopeIds = roleIds.filter(roleId => !roleIdSet.has(roleId)); + if (outOfScopeIds.length > 0) { + throw this.createError(`包含超出当前角色范围的角色ID:${outOfScopeIds.join(',')}`, 400); + } + + return this.pruneDescendantRoleIds(roleIds, parentMap); + } + + async replaceEmployeeRoles(employeeId, roleIds) { + const { ctx } = this; + + await ctx.model.EmployeeRole.destroy({ + where: { + employee_id: employeeId, + }, + }); + + const rows = roleIds.map(roleId => ({ + employee_id: employeeId, + role_id: roleId, + })); + + await ctx.model.EmployeeRole.bulkCreate(rows); + } + + async buildEmployeeRoleGroupMap(employeeIds) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + if (!Array.isArray(employeeIds) || employeeIds.length === 0) { + return new Map(); + } + + const employeeRoleRows = await ctx.model.EmployeeRole.findAll({ + where: { + employee_id: employeeIds, + }, + attributes: [ 'employee_id', 'role_id' ], + raw: true, + }); + + if (employeeRoleRows.length === 0) { + return new Map(); + } + + const roleIds = Array.from(new Set(employeeRoleRows + .map(item => Number(item.role_id)) + .filter(roleId => Number.isFinite(roleId) && roleId > 0))); + + const roleRows = await ctx.model.Role.findAll({ + where: { + id: { + [Op.in]: roleIds, + }, + }, + attributes: [ 'id', 'role_code', 'role_name', 'pid', 'status' ], + raw: true, + }); + const roleMap = new Map(roleRows.map(role => [ Number(role.id), role ])); + + const employeeRoleMap = new Map(); + for (const row of employeeRoleRows) { + const employeeId = Number(row.employee_id); + const roleId = Number(row.role_id); + if (!Number.isFinite(employeeId) || employeeId <= 0 || !Number.isFinite(roleId) || roleId <= 0) { + continue; + } + + const role = roleMap.get(roleId); + if (!employeeRoleMap.has(employeeId)) { + employeeRoleMap.set(employeeId, { + role_ids: [], + roles: [], + }); + } + + const target = employeeRoleMap.get(employeeId); + target.role_ids.push(roleId); + target.roles.push({ + role_id: roleId, + role_code: role && role.role_code ? role.role_code : '', + role_name: role && role.role_name ? role.role_name : '', + pid: role ? Number(role.pid || 0) : 0, + status: role ? Number(role.status) : 0, + }); + } + + for (const value of employeeRoleMap.values()) { + value.role_ids = Array.from(new Set(value.role_ids)).sort((a, b) => a - b); + value.roles.sort((a, b) => a.role_id - b.role_id); + } + + return employeeRoleMap; + } + + async formatEmployeeRow(employee, options = {}) { + let account = options.account || null; + if (!account) { + account = await this.getWmsClient().get('wms_account', { + id: employee.account_id, + }); + } const avatar = await this.getAvatarMeta(employee.id); return { @@ -150,28 +378,119 @@ class SettingAccountService extends Service { } async list(data = {}) { - const { ctx } = this; + const { ctx, app } = this; + const { Op } = app.Sequelize; const storeId = this.getCurrentStoreId(); - const statusFilter = data.includeDisabled === true - ? undefined - : (data.status === 0 || data.status === '0' ? 0 : 1); + const currentEmployeeId = this.getCurrentEmployeeId(); + const normalizedWhere = ctx.where && typeof ctx.where === 'object' + ? { ...ctx.where } + : (data.where && typeof data.where === 'object' ? { ...data.where } : {}); + let parsedResult = ctx.whereParsed; + if (!parsedResult || !Array.isArray(parsedResult.dynamicConditions)) { + const parsed = parseWhereConditions({ + where: normalizedWhere, + app, + specialFieldMap: this.getListWhereSpecialFieldMap(), + }); + if (!parsed.ok) { + throw this.createError(`where 参数解析失败: ${parsed.reason}`, 400); + } + parsedResult = parsed.result; + } - const where = { - store_id: storeId, - }; - if (statusFilter === 0 || statusFilter === 1) { - where.status = statusFilter; + const andConditions = [ + { + store_id: storeId, + }, + ]; + const hasWhereStatus = Object.prototype.hasOwnProperty.call(normalizedWhere, 'status'); + if (!hasWhereStatus) { + const statusFilter = data.includeDisabled === true + ? undefined + : (data.status === 0 || data.status === '0' ? 0 : 1); + if (statusFilter === 0 || statusFilter === 1) { + andConditions.push({ status: statusFilter }); + } + } + + const dynamicConditions = parsedResult.dynamicConditions || []; + if (dynamicConditions.length > 0) { + andConditions.push({ [Op.and]: dynamicConditions }); + } + + const quickWhereInput = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere) + || normalizedWhere.quickWhere + || null; + const quickWhereValue = quickWhereInput && typeof quickWhereInput === 'object' + ? quickWhereInput.value + : quickWhereInput; + if (quickWhereValue !== undefined && quickWhereValue !== null && String(quickWhereValue).trim() !== '') { + const keyword = String(quickWhereValue).trim(); + andConditions.push({ + [Op.or]: [ + { real_name: { [Op.like]: `%${keyword}%` } }, + { '$account.username$': { [Op.like]: `%${keyword}%` } }, + { '$account.phone$': { [Op.like]: `%${keyword}%` } }, + { '$account.email$': { [Op.like]: `%${keyword}%` } }, + ], + }); } const employees = await ctx.model.AccountStoreEmployee.findAll({ - where, + where: { + [Op.and]: andConditions, + }, + include: [ + { + model: ctx.model.Account, + as: 'account', + attributes: [ 'id', 'username', 'phone', 'email', 'real_name' ], + required: false, + }, + ], order: [[ 'created_at', 'DESC' ], [ 'id', 'DESC' ]], }); + const { roleIdSet } = await this.resolveAssignableRoleScope(); + if (roleIdSet.size === 0) { + return { + code: 200, + data: [], + }; + } + + const employeeIds = employees + .map(employee => Number(employee.id)) + .filter(employeeId => Number.isFinite(employeeId) && employeeId > 0); + const employeeRoleMap = await this.buildEmployeeRoleGroupMap(employeeIds); + const list = []; for (const employee of employees) { - list.push(await this.formatEmployeeRow(employee)); + const employeeId = Number(employee.id); + if (currentEmployeeId && employeeId === currentEmployeeId) { + continue; + } + + const roleGroup = employeeRoleMap.get(employeeId) || { + role_ids: [], + roles: [], + }; + + // 只展示当前账号可分配范围内的工号,避免越权操作。 + const hasOutOfScopeRole = roleGroup.role_ids + .some(roleId => !roleIdSet.has(Number(roleId))); + if (hasOutOfScopeRole) { + continue; + } + + list.push({ + ...await this.formatEmployeeRow(employee, { + account: employee.account, + }), + role_ids: roleGroup.role_ids, + roles: roleGroup.roles, + }); } return { @@ -205,7 +524,9 @@ class SettingAccountService extends Service { throw this.createError(`新增工号禁止直接使用保留名称 ${RESERVED_EMPLOYEE_NAME}`, 400); } - const roleId = await this.resolveRoleId(data); + const roleIds = await this.resolveRequestedRoleIds(data, { + required: true, + }); let account = await this.findRawAccountByPhone(phone); if (account && Number(account.status) !== 1) { @@ -256,13 +577,15 @@ class SettingAccountService extends Service { throw this.createError('该手机号已绑定当前主体工号', 409); } - const { employee, employeeRole } = await service.systems.store.ensureEmployeeRoleBinding({ + const { employee } = await service.systems.store.ensureEmployeeRoleBinding({ accountId: Number(account.id), storeId, - roleId, + roleId: roleIds[0], realName, }); + await this.replaceEmployeeRoles(Number(employee.id), roleIds); + await service.systems.auth.user.clearUserCache(Number(account.id)); const formatted = await this.formatEmployeeRow(employee); @@ -270,7 +593,8 @@ class SettingAccountService extends Service { code: 200, data: { ...formatted, - role_id: Number(employeeRole.role_id), + role_id: roleIds[0], + role_ids: roleIds, is_new_account: createdAccountId > 0, }, }; @@ -348,14 +672,15 @@ class SettingAccountService extends Service { const employeeId = Number(data.employee_id || data.id || 0); const hasRealName = Object.prototype.hasOwnProperty.call(data, 'real_name') || Object.prototype.hasOwnProperty.call(data, 'realName'); const hasFileId = Object.prototype.hasOwnProperty.call(data, 'file_id') || Object.prototype.hasOwnProperty.call(data, 'avatar_file_id') || Object.prototype.hasOwnProperty.call(data, 'fileId'); + const hasRoleIds = Object.prototype.hasOwnProperty.call(data, 'ids') || Object.prototype.hasOwnProperty.call(data, 'role_ids'); const realName = this.normalizeName(data.real_name || data.realName); const fileId = Number(data.file_id || data.avatar_file_id || data.fileId || 0); if (!employeeId) { throw this.createError('employee_id 参数不能为空', 400); } - if (!hasRealName && !hasFileId) { - throw this.createError('至少需要更新 real_name 或 file_id', 400); + if (!hasRoleIds) { + throw this.createError('ids 参数不能为空', 400); } if (hasRealName && !realName) { throw this.createError('real_name 参数不能为空', 400); @@ -405,12 +730,32 @@ class SettingAccountService extends Service { }); } + const roleIds = await this.resolveRequestedRoleIds(data, { + required: true, + }); + await this.replaceEmployeeRoles(employeeId, roleIds); + await service.systems.auth.user.clearUserCache(Number(employee.account_id)); const refreshed = await ctx.model.AccountStoreEmployee.findByPk(employeeId); + const roleRows = await ctx.model.EmployeeRole.findAll({ + where: { + employee_id: employeeId, + }, + attributes: [ 'role_id' ], + order: [[ 'role_id', 'ASC' ]], + raw: true, + }); + const boundRoleIds = roleRows + .map(item => Number(item.role_id)) + .filter(roleId => Number.isFinite(roleId) && roleId > 0); + return { code: 200, - data: await this.formatEmployeeRow(refreshed), + data: { + ...await this.formatEmployeeRow(refreshed), + role_ids: Array.from(new Set(boundRoleIds)), + }, }; } } diff --git a/app/service/systems/setting/permission.js b/app/service/systems/setting/permission.js new file mode 100644 index 0000000..10eab8f --- /dev/null +++ b/app/service/systems/setting/permission.js @@ -0,0 +1,730 @@ +'use strict'; + +const Service = require('egg').Service; + +class SettingPermissionService extends Service { + createError(message, code = 500) { + const error = new Error(message); + error.code = code; + return error; + } + + getCurrentStoreId() { + const storeId = Number(this.ctx.user && this.ctx.user.store_id); + if (!Number.isFinite(storeId) || storeId <= 0) { + throw this.createError('未识别到当前主体,无法操作权限', 400); + } + return storeId; + } + + getCurrentEmployeeId() { + const employeeId = Number(this.ctx.user && this.ctx.user.employees_id); + if (!Number.isFinite(employeeId) || employeeId <= 0) { + return null; + } + return employeeId; + } + + toPositiveNumber(value, fieldName) { + const num = Number(value); + if (!Number.isFinite(num) || num <= 0) { + throw this.createError(`${fieldName} 参数不能为空`, 400); + } + return num; + } + + async getRole(roleId) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const storeId = this.getCurrentStoreId(); + + const role = await ctx.model.Role.findOne({ + where: { + id: roleId, + [Op.or]: [ + { store_id: storeId }, + { store_id: 0 }, + { store_id: null }, + ], + }, + }); + + if (!role) { + throw this.createError('角色不存在或无权限操作', 404); + } + + return role; + } + + async getPermission(permissionId, includeDisabled = false) { + const { ctx } = this; + const where = { id: permissionId }; + if (!includeDisabled) { + where.status = 1; + } + + const permission = await ctx.model.Permission.findOne({ where }); + if (!permission) { + throw this.createError('权限不存在或已禁用', 404); + } + + return permission; + } + + normalizePermissionType(type) { + const normalized = typeof type === 'string' ? type.trim() : ''; + if (!normalized) { + throw this.createError('type 参数不能为空', 400); + } + + const allowedTypes = new Set([ 'web_pages', 'pda_pages', 'btns', 'api', 'miniprogram_pages', 'block' ]); + if (!allowedTypes.has(normalized)) { + throw this.createError('type 参数不合法', 400); + } + return normalized; + } + + normalizeOptionalString(value, fieldName, maxLength = 255) { + if (value === undefined || value === null) { + return null; + } + const normalized = String(value).trim(); + if (!normalized) { + return ''; + } + if (normalized.length > maxLength) { + throw this.createError(`${fieldName} 长度不能超过 ${maxLength}`, 400); + } + return normalized; + } + + normalizeParentId(value) { + if (value === undefined || value === null || value === '' || Number(value) === 0) { + return null; + } + const num = Number(value); + if (!Number.isFinite(num) || num <= 0) { + throw this.createError('parent_id 参数不合法', 400); + } + return num; + } + + normalizeSort(value) { + if (value === undefined || value === null || value === '') { + return 0; + } + const num = Number(value); + if (!Number.isFinite(num) || num < 0) { + throw this.createError('sort 参数不合法', 400); + } + return Math.floor(num); + } + + normalizeStatus(value) { + if (value === undefined || value === null || value === '') { + return 1; + } + const num = Number(value); + if (num === 0 || num === 1) { + return num; + } + throw this.createError('status 参数不合法', 400); + } + + normalizeBooleanFlag(value, fieldName) { + if (value === undefined || value === null || value === '') { + return 0; + } + const num = Number(value); + if (num === 0 || num === 1) { + return num; + } + throw this.createError(`${fieldName} 参数不合法`, 400); + } + + async getAvailablePermissionIdSet({ includeDisabled = false } = {}) { + const rows = await this.resolveVisiblePermissionRows({ + includeDisabled, + type: null, + keyword: '', + }); + return new Set(rows.map(item => Number(item.id)).filter(id => Number.isFinite(id) && id > 0)); + } + + async ensureParentPermissionInScope(parentId) { + if (!parentId) { + return; + } + + await this.getPermission(parentId, false); + + const availableSet = await this.getAvailablePermissionIdSet({ includeDisabled: false }); + if (!availableSet.has(Number(parentId))) { + throw this.createError(`parent_id 超出当前登录工号可用权限集:${parentId}`, 400); + } + } + + async ensurePermissionsInAvailableScope(permissionIds, options = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const includeDisabled = options.includeDisabled === true; + + const availableSet = await this.getAvailablePermissionIdSet({ includeDisabled }); + if (availableSet.size === 0) { + throw this.createError('当前登录工号可用权限集为空,无法操作权限', 400); + } + + const targetRows = await ctx.model.Permission.findAll({ + where: { + id: permissionIds, + }, + attributes: [ 'id', 'parent_id' ], + raw: true, + }); + if (targetRows.length !== permissionIds.length) { + const found = new Set(targetRows.map(item => Number(item.id))); + const missing = permissionIds.filter(id => !found.has(Number(id))); + throw this.createError(`权限不存在:${missing.join(',')}`, 404); + } + + const parentMap = new Map(targetRows.map(item => [ Number(item.id), item.parent_id === null ? null : Number(item.parent_id) ])); + let pendingParentIds = Array.from(new Set(targetRows + .map(item => item.parent_id === null ? null : Number(item.parent_id)) + .filter(parentId => Number.isFinite(parentId) && parentId > 0))); + + while (pendingParentIds.length > 0) { + const fetchIds = pendingParentIds.filter(parentId => !parentMap.has(parentId)); + if (fetchIds.length === 0) { + break; + } + + const parentRows = await ctx.model.Permission.findAll({ + where: { + id: { + [Op.in]: fetchIds, + }, + }, + attributes: [ 'id', 'parent_id' ], + raw: true, + }); + + for (const row of parentRows) { + parentMap.set(Number(row.id), row.parent_id === null ? null : Number(row.parent_id)); + } + + pendingParentIds = Array.from(new Set(parentRows + .map(row => row.parent_id === null ? null : Number(row.parent_id)) + .filter(parentId => Number.isFinite(parentId) && parentId > 0 && !parentMap.has(parentId)))); + } + + const outOfScopeIds = []; + for (const permissionId of permissionIds) { + let currentId = Number(permissionId); + let inScope = false; + const visited = new Set(); + + while (Number.isFinite(currentId) && currentId > 0 && !visited.has(currentId)) { + visited.add(currentId); + if (availableSet.has(currentId)) { + inScope = true; + break; + } + + const parentId = parentMap.has(currentId) ? parentMap.get(currentId) : null; + if (!Number.isFinite(parentId) || parentId <= 0) { + break; + } + currentId = Number(parentId); + } + + if (!inScope) { + outOfScopeIds.push(Number(permissionId)); + } + } + + if (outOfScopeIds.length > 0) { + throw this.createError(`包含超出当前登录工号可用权限集的权限ID:${outOfScopeIds.join(',')}`, 400); + } + } + + normalizePermissionIds(inputPermissionIds) { + if (!Array.isArray(inputPermissionIds)) { + throw this.createError('permission_ids 参数不能为空', 400); + } + + const permissionIds = []; + for (const permissionId of inputPermissionIds) { + const normalized = Number(permissionId); + if (!Number.isFinite(normalized) || normalized <= 0) { + throw this.createError('permission_ids 必须是正整数数组', 400); + } + permissionIds.push(normalized); + } + + return Array.from(new Set(permissionIds)); + } + + normalizeIds(inputIds, fieldName = 'ids') { + if (!Array.isArray(inputIds)) { + throw this.createError(`${fieldName} 参数不能为空`, 400); + } + + const ids = []; + for (const item of inputIds) { + const normalized = Number(item); + if (!Number.isFinite(normalized) || normalized <= 0) { + throw this.createError(`${fieldName} 必须是正整数数组`, 400); + } + ids.push(normalized); + } + if (ids.length === 0) { + throw this.createError(`${fieldName} 参数不能为空`, 400); + } + + return Array.from(new Set(ids)); + } + + async validatePermissions(permissionIds) { + const { ctx } = this; + if (permissionIds.length === 0) { + return []; + } + + const permissions = await ctx.model.Permission.findAll({ + where: { + id: permissionIds, + status: 1, + }, + attributes: [ 'id' ], + }); + + if (permissions.length !== permissionIds.length) { + const foundIds = permissions.map(item => Number(item.id)); + const missingIds = permissionIds.filter(item => !foundIds.includes(item)); + throw this.createError(`权限不存在或已禁用:${missingIds.join(',')}`, 400); + } + + return permissions; + } + + async clearRoleUsersCache(roleId) { + const { ctx, service } = this; + const storeId = this.getCurrentStoreId(); + + const employeeRoleRows = await ctx.model.EmployeeRole.findAll({ + where: { + role_id: roleId, + }, + include: [ + { + model: ctx.model.AccountStoreEmployee, + as: 'employee', + attributes: [ 'account_id' ], + where: { + store_id: storeId, + status: 1, + }, + required: true, + }, + ], + raw: false, + }); + + const accountIds = Array.from(new Set(employeeRoleRows + .map(item => Number(item.employee && item.employee.account_id)) + .filter(id => Number.isFinite(id) && id > 0))); + + for (const accountId of accountIds) { + await service.systems.auth.user.clearUserCache(accountId); + } + } + + async getCurrentEmployeePermissionIds() { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const currentEmployeeId = this.getCurrentEmployeeId(); + if (!currentEmployeeId) { + return []; + } + + const employeeRoles = await ctx.model.EmployeeRole.findAll({ + attributes: [ 'role_id' ], + where: { + employee_id: currentEmployeeId, + }, + include: [ + { + model: ctx.model.Role, + as: 'role', + attributes: [], + where: { + status: 1, + }, + required: true, + }, + ], + raw: true, + }); + + const roleIds = Array.from(new Set(employeeRoles + .map(item => Number(item.role_id)) + .filter(id => Number.isFinite(id) && id > 0))); + if (roleIds.length === 0) { + return []; + } + + const rolePermissions = await ctx.model.RolePermission.findAll({ + where: { + role_id: { + [Op.in]: roleIds, + }, + }, + attributes: [ 'permission_id' ], + raw: true, + }); + + return Array.from(new Set(rolePermissions + .map(item => Number(item.permission_id)) + .filter(id => Number.isFinite(id) && id > 0))); + } + + async getCurrentRoleId() { + const { ctx } = this; + const currentEmployeeId = this.getCurrentEmployeeId(); + if (!currentEmployeeId) { + return null; + } + + const row = await ctx.model.EmployeeRole.findOne({ + attributes: [ 'role_id' ], + where: { + employee_id: currentEmployeeId, + }, + include: [ + { + model: ctx.model.Role, + as: 'role', + attributes: [], + where: { + status: 1, + }, + required: true, + }, + ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + const roleId = Number(row && row.role_id); + if (!Number.isFinite(roleId) || roleId <= 0) { + return null; + } + return roleId; + } + + async resolveVisiblePermissionRows({ includeDisabled = false, type = null, keyword = '' } = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + const currentPermissionIds = await this.getCurrentEmployeePermissionIds(); + if (currentPermissionIds.length === 0) { + return []; + } + + const where = { + id: { + [Op.in]: currentPermissionIds, + }, + status: includeDisabled ? { [Op.in]: [ 0, 1 ] } : 1, + type: { + [Op.notLike]: '%_pages', + }, + }; + if (type) { + where.type = type; + } + if (keyword) { + where[Op.or] = [ + { path: { [Op.like]: `%${keyword}%` } }, + { name: { [Op.like]: `%${keyword}%` } }, + { meta_title: { [Op.like]: `%${keyword}%` } }, + ]; + } + + const permissionRows = await ctx.model.Permission.findAll({ + where, + attributes: [ + 'id', + 'path', + 'name', + 'type', + 'status', + 'parent_id', + 'sort', + 'meta_title', + ], + order: [ + [ 'sort', 'ASC' ], + [ 'id', 'ASC' ], + ], + }); + + return permissionRows; + } + + async list(data = {}) { + const { ctx } = this; + + const includeDisabled = data.includeDisabled === true; + const roleIdRaw = data.role_id || data.roleId; + const type = typeof data.type === 'string' && data.type.trim() ? data.type.trim() : null; + const keyword = typeof data.keyword === 'string' ? data.keyword.trim() : ''; + + let role = null; + let targetRoleId = roleIdRaw; + if (targetRoleId === undefined || targetRoleId === null || targetRoleId === '') { + targetRoleId = await this.getCurrentRoleId(); + } + if (targetRoleId !== undefined && targetRoleId !== null && targetRoleId !== '') { + const roleId = this.toPositiveNumber(targetRoleId, 'role_id'); + role = await this.getRole(roleId); + } + + const permissionRows = await this.resolveVisiblePermissionRows({ + includeDisabled, + type, + keyword, + }); + + let selectedPermissionSet = new Set(); + if (role) { + const rolePermissions = await ctx.model.RolePermission.findAll({ + where: { + role_id: role.id, + }, + attributes: [ 'permission_id' ], + }); + + selectedPermissionSet = new Set(rolePermissions.map(item => Number(item.permission_id))); + } + + const permissions = permissionRows.map(item => ({ + permission_id: Number(item.id), + path: item.path || '', + name: item.name || '', + type: item.type || '', + status: Number(item.status), + parent_id: item.parent_id === null ? null : Number(item.parent_id), + sort: Number(item.sort || 0), + meta_title: item.meta_title || '', + selected: role ? selectedPermissionSet.has(Number(item.id)) : false, + })); + + return { + code: 200, + data: { + role_id: role ? Number(role.id) : null, + permissions, + }, + }; + } + + async add(data = {}) { + const { ctx } = this; + + const path = this.normalizeOptionalString(data.path, 'path', 255); + if (!path) { + throw this.createError('path 参数不能为空', 400); + } + + const permissionData = { + path, + type: this.normalizePermissionType(data.type), + name: this.normalizeOptionalString(data.name, 'name', 100) || '', + component: this.normalizeOptionalString(data.component, 'component', 255), + redirect: this.normalizeOptionalString(data.redirect, 'redirect', 255), + meta_title: this.normalizeOptionalString(data.meta_title, 'meta_title', 100), + meta_icon: this.normalizeOptionalString(data.meta_icon, 'meta_icon', 50), + parent_id: this.normalizeParentId(data.parent_id), + sort: this.normalizeSort(data.sort), + hidden: this.normalizeBooleanFlag(data.hidden, 'hidden'), + always_show: this.normalizeBooleanFlag(data.always_show, 'always_show'), + status: this.normalizeStatus(data.status), + }; + + await this.ensureParentPermissionInScope(permissionData.parent_id); + + let created = null; + try { + created = await ctx.model.Permission.create(permissionData); + } catch (error) { + throw error; + } + + return { + code: 200, + data: { + permission_id: Number(created.id), + path: created.path || '', + type: created.type || '', + parent_id: created.parent_id === null ? null : Number(created.parent_id), + status: Number(created.status), + }, + }; + } + + async delete(data = {}) { + const { ctx } = this; + const permissionIds = this.normalizeIds(data.ids, 'ids'); + + await this.ensurePermissionsInAvailableScope(permissionIds, { + includeDisabled: true, + }); + + const permissions = await ctx.model.Permission.findAll({ + where: { + id: permissionIds, + }, + attributes: [ 'id', 'status' ], + raw: true, + }); + + const deletedIds = []; + const alreadyDeletedIds = []; + for (const permission of permissions) { + if (Number(permission.status) === 0) { + alreadyDeletedIds.push(Number(permission.id)); + } else { + deletedIds.push(Number(permission.id)); + } + } + + const transaction = await ctx.model.transaction(); + try { + if (deletedIds.length > 0) { + await ctx.model.Permission.update({ + status: 0, + }, { + where: { + id: deletedIds, + }, + transaction, + }); + + await ctx.model.RolePermission.destroy({ + where: { + permission_id: deletedIds, + }, + transaction, + }); + } + + await transaction.commit(); + } catch (error) { + await transaction.rollback(); + throw error; + } + + return { + code: 200, + data: { + ids: permissionIds, + deleted_ids: deletedIds, + already_deleted_ids: alreadyDeletedIds, + status: 'deleted', + }, + }; + } + + async update(data = {}) { + const { ctx } = this; + + const permissionId = this.toPositiveNumber(data.permission_id || data.permissionId, 'permission_id'); + await this.ensurePermissionsInAvailableScope([ permissionId ], { + includeDisabled: true, + }); + + const permission = await this.getPermission(permissionId, true); + + const hasPath = Object.prototype.hasOwnProperty.call(data, 'path'); + const hasName = Object.prototype.hasOwnProperty.call(data, 'name'); + const hasType = Object.prototype.hasOwnProperty.call(data, 'type'); + const hasComponent = Object.prototype.hasOwnProperty.call(data, 'component'); + const hasRedirect = Object.prototype.hasOwnProperty.call(data, 'redirect'); + const hasMetaTitle = Object.prototype.hasOwnProperty.call(data, 'meta_title'); + const hasMetaIcon = Object.prototype.hasOwnProperty.call(data, 'meta_icon'); + const hasParentId = Object.prototype.hasOwnProperty.call(data, 'parent_id'); + const hasSort = Object.prototype.hasOwnProperty.call(data, 'sort'); + const hasHidden = Object.prototype.hasOwnProperty.call(data, 'hidden'); + const hasAlwaysShow = Object.prototype.hasOwnProperty.call(data, 'always_show'); + const hasStatus = Object.prototype.hasOwnProperty.call(data, 'status'); + + if (!hasPath && !hasName && !hasType && !hasComponent && !hasRedirect + && !hasMetaTitle && !hasMetaIcon && !hasParentId && !hasSort + && !hasHidden && !hasAlwaysShow && !hasStatus) { + throw this.createError('至少需要提供一个可更新字段', 400); + } + + const updates = {}; + if (hasPath) { + const path = this.normalizeOptionalString(data.path, 'path', 255); + if (!path) { + throw this.createError('path 参数不能为空', 400); + } + updates.path = path; + } + if (hasName) { + updates.name = this.normalizeOptionalString(data.name, 'name', 100) || ''; + } + if (hasType) { + updates.type = this.normalizePermissionType(data.type); + } + if (hasComponent) { + updates.component = this.normalizeOptionalString(data.component, 'component', 255); + } + if (hasRedirect) { + updates.redirect = this.normalizeOptionalString(data.redirect, 'redirect', 255); + } + if (hasMetaTitle) { + updates.meta_title = this.normalizeOptionalString(data.meta_title, 'meta_title', 100); + } + if (hasMetaIcon) { + updates.meta_icon = this.normalizeOptionalString(data.meta_icon, 'meta_icon', 50); + } + if (hasParentId) { + const parentId = this.normalizeParentId(data.parent_id); + if (parentId && parentId === permissionId) { + throw this.createError('parent_id 不能等于 permission_id', 400); + } + await this.ensureParentPermissionInScope(parentId); + updates.parent_id = parentId; + } + if (hasSort) { + updates.sort = this.normalizeSort(data.sort); + } + if (hasHidden) { + updates.hidden = this.normalizeBooleanFlag(data.hidden, 'hidden'); + } + if (hasAlwaysShow) { + updates.always_show = this.normalizeBooleanFlag(data.always_show, 'always_show'); + } + if (hasStatus) { + updates.status = this.normalizeStatus(data.status); + } + + await permission.update(updates); + + return { + code: 200, + data: { + permission_id: Number(permission.id), + path: permission.path || '', + type: permission.type || '', + parent_id: permission.parent_id === null ? null : Number(permission.parent_id), + status: Number(permission.status), + }, + }; + } +} + +module.exports = SettingPermissionService; diff --git a/app/service/systems/setting/role.js b/app/service/systems/setting/role.js new file mode 100644 index 0000000..1dea240 --- /dev/null +++ b/app/service/systems/setting/role.js @@ -0,0 +1,669 @@ +'use strict'; + +const Service = require('egg').Service; + +class SettingRoleService extends Service { + createError(message, code = 500) { + const error = new Error(message); + error.code = code; + return error; + } + + getCurrentStoreId() { + const storeId = Number(this.ctx.user && this.ctx.user.store_id); + if (!Number.isFinite(storeId) || storeId <= 0) { + throw this.createError('未识别到当前主体,无法操作角色', 400); + } + return storeId; + } + + getCurrentEmployeeId() { + const employeeId = Number(this.ctx.user && this.ctx.user.employees_id); + if (!Number.isFinite(employeeId) || employeeId <= 0) { + return null; + } + return employeeId; + } + + toPositiveNumber(value, fieldName) { + const num = Number(value); + if (!Number.isFinite(num) || num <= 0) { + throw this.createError(`${fieldName} 参数不能为空`, 400); + } + return num; + } + + async getEmployee(employeeId, options = {}) { + const { ctx } = this; + const storeId = this.getCurrentStoreId(); + const includeDisabled = options.includeDisabled === true; + const where = { + id: employeeId, + store_id: storeId, + }; + if (!includeDisabled) { + where.status = 1; + } + + const employee = await ctx.model.AccountStoreEmployee.findOne({ where }); + if (!employee) { + throw this.createError('工号不存在或无权限操作', 404); + } + return employee; + } + + normalizeRoleIds(inputRoleIds) { + if (!Array.isArray(inputRoleIds) || inputRoleIds.length === 0) { + throw this.createError('role_ids 参数不能为空', 400); + } + + const roleIds = []; + for (const roleId of inputRoleIds) { + const normalized = Number(roleId); + if (!Number.isFinite(normalized) || normalized <= 0) { + throw this.createError('role_ids 必须是正整数数组', 400); + } + roleIds.push(normalized); + } + + return Array.from(new Set(roleIds)); + } + + async findAssignableRoles(roleIds, storeId) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + const roles = await ctx.model.Role.findAll({ + where: { + id: roleIds, + status: 1, + [Op.or]: [ + { store_id: storeId }, + { store_id: 0 }, + { store_id: null }, + ], + }, + order: [[ 'id', 'ASC' ]], + }); + + if (roles.length !== roleIds.length) { + const foundRoleIds = roles.map(role => Number(role.id)); + const missingRoleIds = roleIds.filter(roleId => !foundRoleIds.includes(roleId)); + throw this.createError(`角色不存在、已禁用或超出当前主体范围:${missingRoleIds.join(',')}`, 400); + } + + return roles; + } + + async clearEmployeeCache(employee) { + const { service } = this.ctx; + await service.systems.auth.user.clearUserCache(Number(employee.account_id)); + } + + async getCurrentEmployeeRoleIds() { + const { ctx } = this; + const currentEmployeeId = this.getCurrentEmployeeId(); + if (!currentEmployeeId) { + return []; + } + + const rows = await ctx.model.EmployeeRole.findAll({ + where: { + employee_id: currentEmployeeId, + }, + attributes: [ 'role_id' ], + }); + + return Array.from(new Set(rows.map(item => Number(item.role_id)).filter(id => Number.isFinite(id) && id > 0))); + } + + collectDescendantRoleIds(roleRows, startRoleIds) { + const childrenMap = new Map(); + for (const row of roleRows) { + const parentId = Number(row.pid || 0); + if (!childrenMap.has(parentId)) { + childrenMap.set(parentId, []); + } + childrenMap.get(parentId).push(Number(row.id)); + } + + const visited = new Set(); + const stack = Array.from(startRoleIds); + while (stack.length > 0) { + const roleId = Number(stack.pop()); + if (!Number.isFinite(roleId) || roleId <= 0 || visited.has(roleId)) { + continue; + } + visited.add(roleId); + const children = childrenMap.get(roleId) || []; + for (const childId of children) { + if (!visited.has(childId)) { + stack.push(childId); + } + } + } + return visited; + } + + buildRoleTree(roleRows, rootRoleIds, selectedRoleIdSet) { + const nodeMap = new Map(); + for (const row of roleRows) { + const roleId = Number(row.id); + nodeMap.set(roleId, { + role_id: roleId, + role_code: row.role_code || '', + role_name: row.role_name || '', + description: row.description || '', + role_type: Number(row.role_type), + scope: Number(row.scope), + is_system: Number(row.is_system), + status: Number(row.status), + store_id: row.store_id === null ? null : Number(row.store_id), + pid: Number(row.pid || 0), + selected: selectedRoleIdSet.has(roleId), + children: [], + }); + } + + for (const node of nodeMap.values()) { + const parent = nodeMap.get(node.pid); + if (parent) { + parent.children.push(node); + } + } + + const sortNodes = nodes => { + nodes.sort((a, b) => a.role_id - b.role_id); + for (const item of nodes) { + if (item.children && item.children.length > 0) { + sortNodes(item.children); + } + } + }; + + const roots = Array.from(rootRoleIds) + .map(roleId => nodeMap.get(Number(roleId))) + .filter(Boolean); + sortNodes(roots); + return roots; + } + + normalizeStoreScope(storeId) { + if (storeId === null || storeId === undefined) { + return 0; + } + const num = Number(storeId); + if (!Number.isFinite(num) || num <= 0) { + return 0; + } + return num; + } + + isRoleVisibleInScope(role, currentRoleRows, currentStoreId, includeSystem) { + const roleStoreScope = this.normalizeStoreScope(role.store_id); + + // 当前主体角色默认可见 + if (roleStoreScope === currentStoreId) { + return true; + } + + // includeSystem=true 时,可见系统角色 + if (includeSystem && roleStoreScope === 0) { + return true; + } + + // 当前工号若本身处于系统角色域,至少允许看到系统角色,避免空树。 + const hasSystemCurrentRole = currentRoleRows + .some(item => this.normalizeStoreScope(item.store_id) === 0); + if (hasSystemCurrentRole && roleStoreScope === 0) { + return true; + } + + return false; + } + + normalizePermissionIds(inputPermissionIds) { + if (!Array.isArray(inputPermissionIds)) { + throw this.createError('permission_ids 参数不能为空', 400); + } + + const permissionIds = []; + for (const permissionId of inputPermissionIds) { + const normalized = Number(permissionId); + if (!Number.isFinite(normalized) || normalized <= 0) { + throw this.createError('permission_ids 必须是正整数数组', 400); + } + permissionIds.push(normalized); + } + + return Array.from(new Set(permissionIds)); + } + + normalizePid(value) { + if (value === undefined || value === null || value === '') { + return 0; + } + const pid = Number(value); + if (!Number.isFinite(pid) || pid < 0) { + throw this.createError('pid 参数不合法', 400); + } + return pid; + } + + async getManageableRole(roleId, options = {}) { + const { ctx } = this; + const storeId = this.getCurrentStoreId(); + const includeDisabled = options.includeDisabled === true; + + const where = { + id: roleId, + store_id: storeId, + is_system: 0, + }; + if (!includeDisabled) { + where.status = 1; + } + + const role = await ctx.model.Role.findOne({ where }); + if (!role) { + throw this.createError('角色不存在、无权限操作或为系统预设角色', 404); + } + return role; + } + + async validatePermissionSet(permissionIds) { + const { ctx } = this; + if (permissionIds.length === 0) { + return; + } + + const existingPermissions = await ctx.model.Permission.findAll({ + where: { + id: permissionIds, + status: 1, + }, + attributes: [ 'id' ], + raw: true, + }); + if (existingPermissions.length !== permissionIds.length) { + const found = new Set(existingPermissions.map(item => Number(item.id))); + const missing = permissionIds.filter(id => !found.has(id)); + throw this.createError(`权限不存在或已禁用:${missing.join(',')}`, 400); + } + + const visiblePermissions = await this.ctx.service.systems.setting.permission.resolveVisiblePermissionRows({ + includeDisabled: false, + type: null, + keyword: '', + }); + const availableSet = new Set(visiblePermissions.map(item => Number(item.id))); + const outOfScopeIds = permissionIds.filter(id => !availableSet.has(id)); + if (outOfScopeIds.length > 0) { + throw this.createError(`包含超出可用权限集的权限ID:${outOfScopeIds.join(',')}`, 400); + } + } + + async replaceRolePermissions(roleId, permissionIds, transaction) { + const { ctx } = this; + + await ctx.model.RolePermission.destroy({ + where: { + role_id: roleId, + }, + transaction, + }); + + if (permissionIds.length > 0) { + const rows = permissionIds.map(permissionId => ({ + role_id: roleId, + permission_id: permissionId, + })); + + await ctx.model.RolePermission.bulkCreate(rows, { transaction }); + } + } + + async clearRoleUsersCache(roleId) { + const { ctx, service } = this; + const storeId = this.getCurrentStoreId(); + + const employeeRoleRows = await ctx.model.EmployeeRole.findAll({ + where: { + role_id: roleId, + }, + include: [ + { + model: ctx.model.AccountStoreEmployee, + as: 'employee', + attributes: [ 'account_id' ], + where: { + store_id: storeId, + status: 1, + }, + required: true, + }, + ], + raw: false, + }); + + const accountIds = Array.from(new Set(employeeRoleRows + .map(item => Number(item.employee && item.employee.account_id)) + .filter(id => Number.isFinite(id) && id > 0))); + + for (const accountId of accountIds) { + await service.systems.auth.user.clearUserCache(accountId); + } + } + + async list(data = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const storeId = this.getCurrentStoreId(); + const includeDisabled = data.includeDisabled === true; + const includeSystem = data.includeSystem === true; + const currentEmployeeId = this.getCurrentEmployeeId(); + + let employee = null; + if (currentEmployeeId) { + employee = await this.getEmployee(currentEmployeeId, { + includeDisabled: true, + }); + } + + // 先拉取当前主体 + 系统角色域,后续按可见规则二次收敛。 + const roleWhere = { + status: includeDisabled ? { [Op.in]: [ 0, 1 ] } : 1, + [Op.or]: [ { store_id: storeId }, { store_id: 0 }, { store_id: null } ], + }; + + const roleRows = await ctx.model.Role.findAll({ + where: roleWhere, + attributes: [ + 'id', + 'role_code', + 'role_name', + 'description', + 'role_type', + 'scope', + 'is_system', + 'status', + 'store_id', + 'pid', + ], + order: [ + [ 'is_system', 'DESC' ], + [ 'id', 'ASC' ], + ], + }); + + const currentRoleIds = await this.getCurrentEmployeeRoleIds(); + if (currentRoleIds.length === 0) { + return { + code: 200, + data: { + employee_id: employee ? Number(employee.id) : null, + roles: [], + }, + }; + } + + const roleMap = new Map(roleRows.map(item => [ Number(item.id), item ])); + const currentRoleRows = currentRoleIds + .map(roleId => roleMap.get(roleId)) + .filter(Boolean); + + if (currentRoleRows.length === 0) { + return { + code: 200, + data: { + employee_id: employee ? Number(employee.id) : null, + roles: [], + }, + }; + } + + const sameLevelParentIds = new Set(currentRoleRows.map(item => Number(item.pid || 0))); + const currentRoleIdSet = new Set(currentRoleRows.map(item => Number(item.id))); + const hasSystemCurrentRole = currentRoleRows + .some(item => this.normalizeStoreScope(item.store_id) === 0); + + // 默认场景下,若当前角色在系统域(store_id=0/null),只保留当前角色本身作为根, + // 避免暴露其他系统同级角色。 + const sameLevelRoleIds = hasSystemCurrentRole && !includeSystem + ? new Set(currentRoleIdSet) + : new Set(roleRows + .filter(item => sameLevelParentIds.has(Number(item.pid || 0))) + .filter(item => this.isRoleVisibleInScope(item, currentRoleRows, storeId, includeSystem)) + .map(item => Number(item.id))); + + const descendantRoleIds = this.collectDescendantRoleIds(roleRows, currentRoleRows.map(item => Number(item.id))); + const visibleRoleIds = new Set([ ...sameLevelRoleIds, ...descendantRoleIds ]); + + const visibleRoleRows = roleRows + .filter(item => visibleRoleIds.has(Number(item.id))) + .filter(item => this.isRoleVisibleInScope(item, currentRoleRows, storeId, includeSystem)); + const rootRoleIds = new Set(visibleRoleRows + .filter(item => sameLevelRoleIds.has(Number(item.id))) + .map(item => Number(item.id))); + + let selectedRoleIdSet = new Set(); + if (employee) { + const employeeRoles = await ctx.model.EmployeeRole.findAll({ + where: { + employee_id: employee.id, + }, + }); + selectedRoleIdSet = new Set(employeeRoles.map(item => Number(item.role_id))); + } + + const roles = this.buildRoleTree(visibleRoleRows, rootRoleIds, selectedRoleIdSet); + + return { + code: 200, + data: { + employee_id: employee ? Number(employee.id) : null, + roles, + }, + }; + } + + async add(data = {}) { + const { ctx } = this; + + const storeId = this.getCurrentStoreId(); + const roleCode = typeof data.role_code === 'string' ? data.role_code.trim() : ''; + const roleName = typeof data.role_name === 'string' ? data.role_name.trim() : ''; + const description = typeof data.description === 'string' ? data.description.trim() : ''; + const roleType = Number(data.role_type || 1); + const scope = Number(data.scope || 1); + const status = data.status === 0 || data.status === '0' ? 0 : 1; + const pid = this.normalizePid(data.pid); + const permissionIds = this.normalizePermissionIds(data.permission_ids || data.permissionIds || []); + const creatorId = Number(this.ctx.user && this.ctx.user.id); + + if (!roleCode) { + throw this.createError('role_code 参数不能为空', 400); + } + if (!roleName) { + throw this.createError('role_name 参数不能为空', 400); + } + if (!Number.isFinite(creatorId) || creatorId <= 0) { + throw this.createError('未识别到当前账号,无法创建角色', 400); + } + + await this.validatePermissionSet(permissionIds); + + const transaction = await ctx.model.transaction(); + let createdRole = null; + try { + createdRole = await ctx.model.Role.create({ + role_code: roleCode, + role_name: roleName, + description, + role_type: roleType, + scope, + is_system: 0, + status, + created_by: creatorId, + store_id: storeId, + pid, + }, { transaction }); + + await this.replaceRolePermissions(Number(createdRole.id), permissionIds, transaction); + await transaction.commit(); + } catch (error) { + await transaction.rollback(); + if (error && error.name === 'SequelizeUniqueConstraintError') { + throw this.createError('role_code 已存在', 409); + } + throw error; + } + + return { + code: 200, + data: { + role_id: Number(createdRole.id), + role_code: createdRole.role_code, + role_name: createdRole.role_name, + permission_ids: permissionIds, + created: true, + }, + }; + } + + async delete(data = {}) { + const { ctx } = this; + + const roleIds = this.normalizeRoleIds(data.ids); + const roles = []; + for (const roleId of roleIds) { + const role = await this.getManageableRole(roleId, { + includeDisabled: true, + }); + roles.push(role); + } + + const deletedIds = []; + const alreadyDeletedIds = []; + + const transaction = await ctx.model.transaction(); + try { + for (const role of roles) { + const roleId = Number(role.id); + if (Number(role.status) === 0) { + alreadyDeletedIds.push(roleId); + continue; + } + + await role.update({ + status: 0, + updated_at: new Date(), + }, { transaction }); + deletedIds.push(roleId); + } + + if (deletedIds.length > 0) { + await ctx.model.RolePermission.destroy({ + where: { + role_id: deletedIds, + }, + transaction, + }); + } + + await transaction.commit(); + } catch (error) { + await transaction.rollback(); + throw error; + } + + for (const roleId of deletedIds) { + await this.clearRoleUsersCache(roleId); + } + + return { + code: 200, + data: { + ids: roleIds, + deleted_ids: deletedIds, + already_deleted_ids: alreadyDeletedIds, + status: 'deleted', + }, + }; + } + + async update(data = {}) { + const { ctx } = this; + + const roleId = this.toPositiveNumber(data.role_id || data.roleId, 'role_id'); + const role = await this.getManageableRole(roleId, { + includeDisabled: true, + }); + + const hasRoleName = Object.prototype.hasOwnProperty.call(data, 'role_name'); + const hasDescription = Object.prototype.hasOwnProperty.call(data, 'description'); + const hasStatus = Object.prototype.hasOwnProperty.call(data, 'status'); + const hasPid = Object.prototype.hasOwnProperty.call(data, 'pid'); + const hasPermissionIds = Object.prototype.hasOwnProperty.call(data, 'permission_ids') + || Object.prototype.hasOwnProperty.call(data, 'permissionIds'); + + if (!hasRoleName && !hasDescription && !hasStatus && !hasPid && !hasPermissionIds) { + throw this.createError('至少需要更新角色信息或 permission_ids', 400); + } + if (!hasPermissionIds) { + throw this.createError('permission_ids 参数不能为空,角色权限需一次性提交', 400); + } + + const permissionIds = this.normalizePermissionIds(data.permission_ids || data.permissionIds || []); + await this.validatePermissionSet(permissionIds); + + const updates = {}; + if (hasRoleName) { + const roleName = typeof data.role_name === 'string' ? data.role_name.trim() : ''; + if (!roleName) { + throw this.createError('role_name 参数不能为空', 400); + } + updates.role_name = roleName; + } + if (hasDescription) { + updates.description = typeof data.description === 'string' ? data.description.trim() : ''; + } + if (hasStatus) { + const status = data.status === 0 || data.status === '0' ? 0 : 1; + updates.status = status; + } + if (hasPid) { + updates.pid = this.normalizePid(data.pid); + } + updates.updated_at = new Date(); + + const transaction = await ctx.model.transaction(); + try { + if (Object.keys(updates).length > 0) { + await role.update(updates, { transaction }); + } + + await this.replaceRolePermissions(roleId, permissionIds, transaction); + await transaction.commit(); + } catch (error) { + await transaction.rollback(); + if (error && error.name === 'SequelizeUniqueConstraintError') { + throw this.createError('角色信息冲突(可能 role_code 重复)', 409); + } + throw error; + } + + await this.clearRoleUsersCache(roleId); + + return { + code: 200, + data: { + role_id: roleId, + role_name: role.role_name, + permission_ids: permissionIds, + }, + }; + } +} + +module.exports = SettingRoleService; diff --git a/config/config.default.js b/config/config.default.js index 4c783ee..9c88140 100644 --- a/config/config.default.js +++ b/config/config.default.js @@ -172,6 +172,7 @@ module.exports = appInfo => { config.poloapi ={ } + config.debug = false; // 生成环境默认关闭 debug,开发环境通过 config.local.js 开启 config.printService = { url: 'http://printer.wms.gztbyc.com', }; diff --git a/methods/gateway.json b/methods/gateway.json index 1ddc55f..c39b061 100644 --- a/methods/gateway.json +++ b/methods/gateway.json @@ -1,8 +1,8 @@ { "module": "gateway", "description": "内部网关接口,供内网系统间调用,统一使用 POST 请求", - "version": "0.1.0", - "updatedAt": "2026-03-24", + "version": "0.2.0", + "updatedAt": "2026-03-29", "headers": [], "methods": { "groups": [ @@ -12,7 +12,7 @@ "list": [ { "method": "user.getUserByTempCode", - "description": "根据绑定码反查WMS账号ID(供 ye4s 扫码绑定调用)", + "description": "根据绑定码反查WMS账号ID并写入扫码状态(扫描即视为已确认,状态缓存3分钟)", "isNeedAuth": false, "isNeedLogin": false, "headers": [], @@ -22,7 +22,7 @@ "type": "string", "required": true, "source": "body", - "description": "绑定码(由 user.getBindWechatCode 生成)" + "description": "绑定码(由 user.getBindWechatCode 生成,6位字母数字混合)" } ], "response": [ @@ -32,24 +32,30 @@ "required": true, "description": "匹配到的 WMS 账号ID" }, + { + "name": "real_name", + "type": "string", + "required": true, + "description": "WMS 账号表中的真实姓名,用于扫码绑定前确认账号" + }, { "name": "status", "type": "string", "required": true, - "description": "当前绑定状态,如 pending/bound" + "description": "当前扫码状态,成功扫码后固定为 scanned" }, { "name": "source", "type": "string", "required": true, - "description": "数据来源,如 cache/db" + "description": "数据来源,如 scan-cache" } ], "errors": [] }, { "method": "user.bindAccountByTempCode", - "description": "根据绑定码将 ye4s 用户绑定到 WMS 账号(供 ye4s 扫码后回调)", + "description": "根据绑定码对应的扫码状态缓存将 ye4s 用户绑定到 WMS 账号(需先调用扫码反查接口)", "isNeedAuth": false, "isNeedLogin": false, "headers": [], @@ -59,7 +65,7 @@ "type": "string", "required": true, "source": "body", - "description": "绑定码(由 user.getBindWechatCode 生成)" + "description": "绑定码(由 user.getBindWechatCode 生成,6位字母数字混合)" }, { "name": "ye4s_user_id", @@ -92,6 +98,141 @@ "errors": [] } ] + }, + { + "groupName": "打印绑定模块", + "module": "print", + "list": [ + { + "method": "print.getBindInfo", + "description": "根据 WMS 账号ID和扫码 code 返回可绑定仓库列表;有可绑定仓库时下发 300 秒临时凭据 tempCode,无可绑定仓库时返回空数组且不返回 tempCode", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "account_id", + "type": "number", + "required": true, + "source": "body", + "description": "WMS 账号ID" + }, + { + "name": "code", + "type": "string", + "required": true, + "source": "body", + "description": "打印端提供的绑定 code" + } + ], + "response": [ + { + "name": "warehouses", + "type": "array", + "required": true, + "description": "可绑定仓库列表,元素结构为 { id, name }" + }, + { + "name": "tempCode", + "type": "string", + "required": false, + "description": "临时绑定凭据,仅当 warehouses 非空时返回" + } + ], + "errors": [ + { + "code": 0, + "message": "缺少有效参数 account_id 或 code" + }, + { + "code": 0, + "message": "账号不存在或已禁用" + }, + { + "code": 0, + "message": "无效code或未绑定" + } + ] + }, + { + "method": "print.bindByTempCode", + "description": "根据第一步返回的临时凭据执行打印台绑定,提交工作台名称和仓库ID后完成真实绑定", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "temp_code", + "type": "string", + "required": true, + "source": "body", + "description": "第一步返回的临时凭据,300 秒有效" + }, + { + "name": "printer", + "type": "string", + "required": true, + "source": "body", + "description": "工作台名称" + }, + { + "name": "warehouse", + "type": "number", + "required": true, + "source": "body", + "description": "仓库ID" + } + ], + "response": [ + { + "name": "code", + "type": "string", + "required": true, + "description": "真实绑定 code" + }, + { + "name": "printer", + "type": "string", + "required": true, + "description": "工作台名称" + }, + { + "name": "warehouse", + "type": "number", + "required": true, + "description": "仓库ID" + }, + { + "name": "computerId", + "type": "number", + "required": true, + "description": "打印台电脑ID" + } + ], + "errors": [ + { + "code": 0, + "message": "参数缺失" + }, + { + "code": 0, + "message": "临时code无效或已过期" + }, + { + "code": 0, + "message": "仓库无绑定权限" + }, + { + "code": 0, + "message": "仓库id校验失败" + }, + { + "code": 0, + "message": "该仓库下打印台名称已存在且可用" + } + ] + } + ] } ] } diff --git a/methods/system.json b/methods/system.json index d7c9e13..43b81b5 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1661,7 +1661,7 @@ "list": [ { "method": "setting.account.list", - "description": "查询当前主体下的工号基础信息列表", + "description": "查询当前主体下且在当前账号角色组可操作范围内的工号列表", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -1686,6 +1686,13 @@ "required": false, "source": "body", "description": "是否包含已删除工号" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "动态筛选条件,仅支持 employee_id、account_id、real_name、status、username、phone、email、quickWhere;其中 username/phone/email 为账号字段,quickWhere 按 real_name/username/phone/email 模糊搜索" } ], "response": [ @@ -1754,12 +1761,54 @@ "type": "string", "required": true, "description": "头像访问地址" + }, + { + "name": "data[].role_ids", + "type": "number[]", + "required": true, + "description": "工号绑定的角色ID数组" + }, + { + "name": "data[].roles[]", + "type": "object", + "required": true, + "description": "工号绑定的角色组详情" + }, + { + "name": "data[].roles[].role_id", + "type": "number", + "required": true, + "description": "角色ID" + }, + { + "name": "data[].roles[].role_code", + "type": "string", + "required": true, + "description": "角色编码" + }, + { + "name": "data[].roles[].role_name", + "type": "string", + "required": true, + "description": "角色名称" + }, + { + "name": "data[].roles[].pid", + "type": "number", + "required": true, + "description": "父级角色ID" + }, + { + "name": "data[].roles[].status", + "type": "number", + "required": true, + "description": "角色状态:1=启用,0=停用" } ], "errors": [ { "code": "400", - "description": "当前登录态缺少主体上下文(store_id)" + "description": "当前登录态缺少主体上下文(store_id)或 where 参数解析失败" }, { "code": "500", @@ -1769,7 +1818,7 @@ }, { "method": "setting.account.add", - "description": "新增工号,按手机号复用或创建账号后绑定到当前主体", + "description": "新增工号,按手机号复用或创建账号后绑定到当前主体,并校验角色组 ids 不超出当前角色范围", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -1810,11 +1859,11 @@ "description": "新账号密码,不传默认 111111" }, { - "name": "role_id", - "type": "number", - "required": false, + "name": "ids", + "type": "number[]", + "required": true, "source": "body", - "description": "工号角色,不传时继承当前操作人工号角色" + "description": "角色组ID数组,必须在当前登录工号可分配角色范围内;若同时传入父子节点,仅保留父节点" }, { "name": "email", @@ -1843,6 +1892,12 @@ "required": true, "description": "绑定后的角色ID" }, + { + "name": "role_ids", + "type": "number[]", + "required": true, + "description": "绑定后的角色组ID数组" + }, { "name": "is_new_account", "type": "boolean", @@ -1865,7 +1920,7 @@ "errors": [ { "code": "400", - "description": "参数错误、手机号格式错误、或直接使用保留名称" + "description": "参数错误、手机号格式错误、直接使用保留名称、或 ids 超出当前角色范围" }, { "code": "409", @@ -1942,7 +1997,7 @@ }, { "method": "setting.account.update", - "description": "更新工号姓名和头像引用", + "description": "更新工号姓名、头像引用和角色组 ids(含当前角色范围校验)", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -1974,6 +2029,13 @@ "required": false, "source": "body", "description": "已有文件ID,作为头像引用" + }, + { + "name": "ids", + "type": "number[]", + "required": true, + "source": "body", + "description": "角色组ID数组,传入时将整体替换为该数组,且必须在当前登录工号可分配角色范围内;若同时传入父子节点,仅保留父节点" } ], "response": [ @@ -2000,12 +2062,18 @@ "type": "string", "required": true, "description": "更新后的头像地址" + }, + { + "name": "role_ids", + "type": "number[]", + "required": true, + "description": "更新后的角色组ID数组" } ], "errors": [ { "code": "400", - "description": "参数错误,未提供更新项" + "description": "参数错误、未传 ids、或 ids 超出当前角色范围" }, { "code": "404", @@ -2019,6 +2087,688 @@ } ] }, + { + "groupName": "角色管理模块", + "module": "setting.role", + "list": [ + { + "method": "setting.role.list", + "description": "查询当前主体可分配角色列表,按当前登录工号返回角色选中状态", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "includeDisabled", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否包含停用角色,默认 false" + }, + { + "name": "includeSystem", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否包含系统默认角色(store_id=0/null),默认 false" + } + ], + "response": [ + { + "name": "employee_id", + "type": "number", + "required": false, + "description": "当前登录工号ID,未识别到登录工号时为 null" + }, + { + "name": "roles[]", + "type": "object", + "required": true, + "description": "角色列表" + }, + { + "name": "roles[].role_id", + "type": "number", + "required": true, + "description": "角色ID" + }, + { + "name": "roles[].role_name", + "type": "string", + "required": true, + "description": "角色名称" + }, + { + "name": "roles[].selected", + "type": "boolean", + "required": true, + "description": "表示当前登录工号是否已绑定该角色" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误" + }, + { + "code": "404", + "description": "工号不存在或无权限" + }, + { + "code": "500", + "description": "查询失败" + } + ] + }, + { + "method": "setting.role.add", + "description": "新增角色并一次性提交权限集(permission_ids)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "role_code", + "type": "string", + "required": true, + "source": "body", + "description": "角色编码(主体内唯一)" + }, + { + "name": "role_name", + "type": "string", + "required": true, + "source": "body", + "description": "角色名称" + }, + { + "name": "description", + "type": "string", + "required": false, + "source": "body", + "description": "角色描述" + }, + { + "name": "pid", + "type": "number", + "required": false, + "source": "body", + "description": "父级角色ID,默认 0" + }, + { + "name": "permission_ids", + "type": "number[]", + "required": true, + "source": "body", + "description": "权限ID数组,一次性提交" + } + ], + "response": [ + { + "name": "role_id", + "type": "number", + "required": true, + "description": "新建角色ID" + }, + { + "name": "role_code", + "type": "string", + "required": true, + "description": "角色编码" + }, + { + "name": "role_name", + "type": "string", + "required": true, + "description": "角色名称" + }, + { + "name": "permission_ids", + "type": "number[]", + "required": true, + "description": "提交后的权限ID集合" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误、权限ID非法或超出当前登录工号可用权限集" + }, + { + "code": "409", + "description": "role_code 冲突" + }, + { + "code": "500", + "description": "新增失败" + } + ] + }, + { + "method": "setting.role.delete", + "description": "批量删除角色(软删除),并清理对应角色权限关联", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids", + "type": "number[]", + "required": true, + "source": "body", + "description": "角色ID数组" + } + ], + "response": [ + { + "name": "ids", + "type": "number[]", + "required": true, + "description": "请求的角色ID数组" + }, + { + "name": "deleted_ids", + "type": "number[]", + "required": true, + "description": "本次实际删除(由启用变为停用)的角色ID数组" + }, + { + "name": "already_deleted_ids", + "type": "number[]", + "required": true, + "description": "本就处于删除状态的角色ID数组" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "固定返回 deleted" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误,ids 必须为正整数数组" + }, + { + "code": "404", + "description": "角色不存在、无权限操作或为系统预设角色(任一ID不满足即失败)" + }, + { + "code": "500", + "description": "删除失败" + } + ] + }, + { + "method": "setting.role.update", + "description": "更新角色信息并一次性重置角色权限(permission_ids)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "role_id", + "type": "number", + "required": true, + "source": "body", + "description": "角色ID" + }, + { + "name": "role_name", + "type": "string", + "required": false, + "source": "body", + "description": "角色名称" + }, + { + "name": "description", + "type": "string", + "required": false, + "source": "body", + "description": "角色描述" + }, + { + "name": "status", + "type": "number", + "required": false, + "source": "body", + "description": "角色状态:1=启用,0=禁用" + }, + { + "name": "pid", + "type": "number", + "required": false, + "source": "body", + "description": "父级角色ID" + }, + { + "name": "permission_ids", + "type": "number[]", + "required": true, + "source": "body", + "description": "权限ID数组,一次性提交" + } + ], + "response": [ + { + "name": "role_id", + "type": "number", + "required": true, + "description": "角色ID" + }, + { + "name": "permission_ids", + "type": "number[]", + "required": true, + "description": "更新后的权限ID集合" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误、permission_ids 非法或超出当前登录工号可用权限集" + }, + { + "code": "404", + "description": "角色不存在、无权限操作或为系统预设角色" + }, + { + "code": "409", + "description": "角色信息冲突" + }, + { + "code": "500", + "description": "更新失败" + } + ] + } + ] + }, + { + "groupName": "权限管理模块", + "module": "setting.permission", + "list": [ + { + "method": "setting.permission.list", + "description": "查询当前登录工号实际可用权限集合,可选按角色返回已绑定权限选中状态", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "role_id", + "type": "number", + "required": false, + "source": "body", + "description": "可选,不传时默认使用当前登录工号的当前角色计算权限选中状态" + }, + { + "name": "type", + "type": "string", + "required": false, + "source": "body", + "description": "可选,按权限类型筛选,如 api/web_pages/pda_pages/btns" + }, + { + "name": "keyword", + "type": "string", + "required": false, + "source": "body", + "description": "可选,按 path/name/meta_title 模糊搜索" + }, + { + "name": "includeDisabled", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否包含禁用权限,默认 false" + } + ], + "response": [ + { + "name": "role_id", + "type": "number", + "required": false, + "description": "查询目标角色ID,未传 role_id 时返回当前登录工号的当前角色ID" + }, + { + "name": "permissions[]", + "type": "object", + "required": true, + "description": "权限列表" + }, + { + "name": "permissions[].permission_id", + "type": "number", + "required": true, + "description": "权限ID" + }, + { + "name": "permissions[].path", + "type": "string", + "required": true, + "description": "权限路径" + }, + { + "name": "permissions[].type", + "type": "string", + "required": true, + "description": "权限类型" + }, + { + "name": "permissions[].selected", + "type": "boolean", + "required": true, + "description": "当传入 role_id 时,表示该权限是否已绑定" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误" + }, + { + "code": "404", + "description": "角色不存在或无权限" + }, + { + "code": "500", + "description": "查询失败" + } + ] + }, + { + "method": "setting.permission.add", + "description": "新增权限", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "path", + "type": "string", + "required": true, + "source": "body", + "description": "权限路径" + }, + { + "name": "type", + "type": "string", + "required": true, + "source": "body", + "description": "权限类型:web_pages/pda_pages/btns/api/miniprogram_pages/block" + }, + { + "name": "name", + "type": "string", + "required": false, + "source": "body", + "description": "权限名称" + }, + { + "name": "parent_id", + "type": "number", + "required": false, + "source": "body", + "description": "父级权限ID,传 0 或不传表示顶级;若传入必须在当前登录工号可用权限集内" + }, + { + "name": "meta_title", + "type": "string", + "required": false, + "source": "body", + "description": "页面标题" + }, + { + "name": "sort", + "type": "number", + "required": false, + "source": "body", + "description": "排序,默认 0" + } + ], + "response": [ + { + "name": "permission_id", + "type": "number", + "required": true, + "description": "权限ID" + }, + { + "name": "path", + "type": "string", + "required": true, + "description": "权限路径" + }, + { + "name": "type", + "type": "string", + "required": true, + "description": "权限类型" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误或 parent_id 超出当前登录工号可用权限集" + }, + { + "code": "404", + "description": "父级权限不存在" + }, + { + "code": "500", + "description": "新增失败" + } + ] + }, + { + "method": "setting.permission.delete", + "description": "批量删除权限(软删除)", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids", + "type": "number[]", + "required": true, + "source": "body", + "description": "权限ID数组,必须在当前登录工号可用权限集内" + } + ], + "response": [ + { + "name": "ids", + "type": "number[]", + "required": true, + "description": "请求的权限ID数组" + }, + { + "name": "deleted_ids", + "type": "number[]", + "required": true, + "description": "本次实际删除(由启用变为停用)的权限ID数组" + }, + { + "name": "already_deleted_ids", + "type": "number[]", + "required": true, + "description": "本就处于删除状态的权限ID数组" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "固定返回 deleted" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误,ids 非法或包含超出当前登录工号可用权限集的权限ID" + }, + { + "code": "404", + "description": "权限不存在" + }, + { + "code": "500", + "description": "删除失败" + } + ] + }, + { + "method": "setting.permission.update", + "description": "更新权限(非角色绑定重置),目标权限必须在当前登录工号可用权限集内", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "permission_id", + "type": "number", + "required": true, + "source": "body", + "description": "权限ID,必须在当前登录工号可用权限集内" + }, + { + "name": "path", + "type": "string", + "required": false, + "source": "body", + "description": "权限路径" + }, + { + "name": "type", + "type": "string", + "required": false, + "source": "body", + "description": "权限类型:web_pages/pda_pages/btns/api/miniprogram_pages/block" + }, + { + "name": "name", + "type": "string", + "required": false, + "source": "body", + "description": "权限名称" + }, + { + "name": "parent_id", + "type": "number", + "required": false, + "source": "body", + "description": "父级权限ID,传 0 表示顶级;若传入必须在当前登录工号可用权限集内" + }, + { + "name": "sort", + "type": "number", + "required": false, + "source": "body", + "description": "排序" + }, + { + "name": "status", + "type": "number", + "required": false, + "source": "body", + "description": "权限状态:1=启用,0=禁用" + } + ], + "response": [ + { + "name": "permission_id", + "type": "number", + "required": true, + "description": "权限ID" + }, + { + "name": "path", + "type": "string", + "required": true, + "description": "更新后的权限路径" + }, + { + "name": "type", + "type": "string", + "required": true, + "description": "更新后的权限类型" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误、未提供更新项,或目标权限超出当前登录工号可用权限集" + }, + { + "code": "404", + "description": "权限不存在" + }, + { + "code": "500", + "description": "更新失败" + } + ] + } + ] + }, { "groupName": "商品模块", "module": "stock", @@ -3474,7 +4224,7 @@ }, { "method": "user.loginByCode", - "description": "登录码登录(使用 ye4s_user.tmp_code)", + "description": "登录码登录(使用本系统缓存登录码,不依赖 ye4s_user.tmp_code)", "isNeedAuth": false, "isNeedLogin": false, "headers": [], @@ -3484,15 +4234,88 @@ "type": "string", "required": true, "source": "body", - "description": "登录码,对应 ye4s_user.tmp_code" + "description": "登录码(6位字母数字混合,对应本系统登录码缓存)" } ], "response": [], "errors": [] }, + { + "method": "user.getLoginWechatCode", + "description": "获取微信扫码登录码:不传客户端编码时生成新的6位客户端编码与登录码;传客户端编码且缓存命中时进入长轮询,优先监听 Redis 登录事件,收到 ye4s_user_id 后立即签发登录 token;未收到事件则刷新登录码返回", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "clientCode", + "type": "string", + "required": false, + "source": "body", + "description": "客户端编码(6位字母数字混合)。不传则服务端自动生成;传入时仅在缓存命中才进入长轮询,缓存不存在按空值处理并重新分配 clientCode" + } + ], + "response": [ + { + "name": "client_code", + "type": "string", + "required": true, + "description": "客户端编码(6位字母数字混合)" + }, + { + "name": "code", + "type": "string", + "required": false, + "description": "微信扫码登录码(6位字母数字混合)。当 status=authorized 时可能为空" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "登录状态:pending(等待扫码)或 authorized(已完成登录)" + }, + { + "name": "updated_at", + "type": "string", + "required": false, + "description": "状态更新时间(ISO 时间)" + }, + { + "name": "expires_at", + "type": "number", + "required": false, + "description": "过期时间戳(毫秒)" + }, + { + "name": "expire_after_ms", + "type": "number", + "required": false, + "description": "距离过期剩余毫秒数" + }, + { + "name": "source", + "type": "string", + "required": true, + "description": "数据来源,如 generated/refreshed/cache/event" + }, + { + "name": "ye4s_user_id", + "type": "number", + "required": false, + "description": "当 status=authorized 时返回的 ye4s 用户ID" + }, + { + "name": "loginToken", + "type": "string", + "required": false, + "description": "当 status=authorized 时返回的本地登录 token" + } + ], + "errors": [] + }, { "method": "user.getBindWechatCode", - "description": "获取微信绑定码(默认立即返回;显式开启长轮询后,最长等待60秒,状态变化立即返回)", + "description": "获取微信绑定状态与绑定码:绑定码为6位字母数字混合且固定60秒有效,默认立即返回;longPoll=true 时最长等待60秒,若无事件则自动刷新新码返回", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -3504,43 +4327,76 @@ } ], "params": [ - { - "name": "forceRefresh", - "type": "boolean", - "required": false, - "source": "body", - "description": "是否强制刷新状态,true 时跳过缓存等待窗口" - }, - { - "name": "waitForChange", - "type": "boolean", - "required": false, - "source": "body", - "description": "是否显式开启长轮询等待(推荐字段);true 时进入最长60秒等待" - }, { "name": "longPoll", "type": "boolean", "required": false, "source": "body", - "description": "长轮询开关(兼容字段);true 时进入最长60秒等待" - }, - { - "name": "waitTimeoutMs", - "type": "number", - "required": false, - "source": "body", - "description": "等待超时毫秒数;后端自动封顶60000" - }, - { - "name": "init", - "type": "boolean", - "required": false, - "source": "body", - "description": "初始化请求标记;true 时强制立即返回,不进入长等待" + "description": "是否启用长轮询;默认 false,true 时等待绑定事件或超时刷新" + } + ], + "response": [ + { + "name": "account_id", + "type": "number", + "required": true, + "description": "WMS 账号ID" + }, + { + "name": "code", + "type": "string", + "required": true, + "description": "绑定码(已绑定时为空字符串)" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "绑定状态:pending/scanned/bound" + }, + { + "name": "is_bound", + "type": "boolean", + "required": true, + "description": "是否已绑定微信" + }, + { + "name": "updated_at", + "type": "string", + "required": true, + "description": "状态更新时间(ISO 时间)" + }, + { + "name": "expires_at", + "type": "number", + "required": false, + "description": "过期时间戳(毫秒),bound 状态可为空" + }, + { + "name": "expire_after_ms", + "type": "number", + "required": true, + "description": "距离过期剩余毫秒数" + }, + { + "name": "scanned_at", + "type": "string", + "required": false, + "description": "扫码时间(未扫码可为空)" + }, + { + "name": "source", + "type": "string", + "required": true, + "description": "数据来源,如 cache/generated/refreshed/db" + }, + { + "name": "ye4s_user_id", + "type": "number", + "required": false, + "description": "已绑定的 ye4s 用户ID(未绑定可为空)" } ], - "response": [], "errors": [] }, { diff --git a/package.json b/package.json index 2129eed..d0a11a0 100644 --- a/package.json +++ b/package.json @@ -64,6 +64,7 @@ "test:local": "egg-bin test", "cov": "egg-bin cov", "lint": "eslint .", + "permission:sync:system-api": "node ./script/sync-system-api-permission.cjs", "check:model-boundary": "node ./script/model-boundary-check.cjs", "ci": "npm run lint && npm run check:model-boundary && npm run cov" }, diff --git a/script/sync-system-api-permission.cjs b/script/sync-system-api-permission.cjs new file mode 100644 index 0000000..66f513b --- /dev/null +++ b/script/sync-system-api-permission.cjs @@ -0,0 +1,254 @@ +const fs = require('fs'); +const path = require('path'); +const mysql = require('mysql2/promise'); + +const ROOT = process.cwd(); +const DEFAULT_CONFIG_PATH = path.join(ROOT, 'config', 'config.local.js'); +const DEFAULT_METHOD_DOC_PATH = path.join(ROOT, 'methods', 'system.json'); + +function parseArgs(argv) { + const args = { + dryRun: false, + roleId: 2, + dbClient: 'wms', + configPath: DEFAULT_CONFIG_PATH, + methodDocPath: DEFAULT_METHOD_DOC_PATH, + }; + + for (const item of argv) { + if (item === '--dry-run') { + args.dryRun = true; + continue; + } + + if (item.startsWith('--role-id=')) { + args.roleId = Number(item.split('=')[1]); + continue; + } + + if (item.startsWith('--db-client=')) { + args.dbClient = String(item.split('=')[1] || '').trim() || 'wms'; + continue; + } + + if (item.startsWith('--config-path=')) { + const raw = String(item.split('=')[1] || '').trim(); + args.configPath = path.resolve(ROOT, raw); + continue; + } + + if (item.startsWith('--method-doc=')) { + const raw = String(item.split('=')[1] || '').trim(); + args.methodDocPath = path.resolve(ROOT, raw); + continue; + } + } + + if (!Number.isInteger(args.roleId) || args.roleId <= 0) { + throw new Error('Invalid --role-id, must be a positive integer.'); + } + + return args; +} + +function loadConfig(configPath) { + if (!fs.existsSync(configPath)) { + throw new Error(`Config file not found: ${configPath}`); + } + + const configFactory = require(configPath); + const config = typeof configFactory === 'function' + ? configFactory({ name: 'wms-permission-sync' }) + : configFactory; + + return config; +} + +function loadAuthRequiredMethods(methodDocPath) { + if (!fs.existsSync(methodDocPath)) { + throw new Error(`Method doc not found: ${methodDocPath}`); + } + + const json = JSON.parse(fs.readFileSync(methodDocPath, 'utf8')); + const groups = json && json.methods && Array.isArray(json.methods.groups) + ? json.methods.groups + : []; + + const methodSet = new Set(); + for (const group of groups) { + const list = group && Array.isArray(group.list) ? group.list : []; + for (const item of list) { + if (!item || !item.method || item.isNeedAuth !== true) continue; + methodSet.add(String(item.method).trim()); + } + } + + return [ ...methodSet ].sort(); +} + +function buildPermissionDefaults(methodPath, templateRow) { + return { + path: methodPath, + type: 'api', + component: templateRow ? templateRow.component : null, + name: templateRow && templateRow.name ? templateRow.name : methodPath, + redirect: templateRow ? templateRow.redirect : null, + meta_title: templateRow && templateRow.meta_title ? templateRow.meta_title : `API:${methodPath}`, + meta_icon: templateRow ? templateRow.meta_icon : null, + hidden: templateRow ? Number(templateRow.hidden || 0) : 0, + always_show: templateRow ? Number(templateRow.always_show || 0) : 0, + parent_id: templateRow && templateRow.parent_id ? Number(templateRow.parent_id) : null, + sort: templateRow ? Number(templateRow.sort || 0) : 0, + status: templateRow ? Number(templateRow.status || 1) : 1, + }; +} + +async function queryPermissionTemplate(conn) { + const [ rows ] = await conn.query(` + SELECT component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, sort, status + FROM wms_permission + WHERE type = 'api' + ORDER BY id ASC + LIMIT 1 + `); + return rows[0] || null; +} + +async function queryExistingPermissions(conn, methodPaths) { + if (methodPaths.length === 0) return new Map(); + + const placeholders = methodPaths.map(() => '?').join(','); + const [ rows ] = await conn.query( + `SELECT id, path FROM wms_permission WHERE type = 'api' AND path IN (${placeholders})`, + methodPaths + ); + + const result = new Map(); + for (const row of rows) { + result.set(row.path, row.id); + } + return result; +} + +async function insertPermission(conn, defaults) { + const [ result ] = await conn.query( + `INSERT INTO wms_permission + (path, type, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, sort, status, created_at, update_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`, + [ + defaults.path, + defaults.type, + defaults.component, + defaults.name, + defaults.redirect, + defaults.meta_title, + defaults.meta_icon, + defaults.hidden, + defaults.always_show, + defaults.parent_id, + defaults.sort, + defaults.status, + ] + ); + + return result.insertId; +} + +async function bindRolePermission(conn, roleId, permissionId) { + const [ result ] = await conn.query( + 'INSERT IGNORE INTO wms_role_permission (role_id, permission_id, created_at) VALUES (?, ?, NOW())', + [ roleId, permissionId ] + ); + return result.affectedRows > 0; +} + +async function main() { + const args = parseArgs(process.argv.slice(2)); + const cfg = loadConfig(args.configPath); + const dbClient = cfg && cfg.mysql && cfg.mysql.clients && cfg.mysql.clients[args.dbClient]; + + if (!dbClient) { + throw new Error(`MySQL client not found in config.mysql.clients: ${args.dbClient}`); + } + + const methodPaths = loadAuthRequiredMethods(args.methodDocPath); + if (methodPaths.length === 0) { + console.log('[sync-system-api-permission] no isNeedAuth=true methods found.'); + return; + } + + const conn = await mysql.createConnection({ + host: dbClient.host, + port: Number(dbClient.port), + user: dbClient.user, + password: dbClient.password, + database: dbClient.database, + charset: dbClient.charset || 'utf8mb4', + }); + + try { + const templateRow = await queryPermissionTemplate(conn); + const existingMap = await queryExistingPermissions(conn, methodPaths); + + const missingPaths = methodPaths.filter(item => !existingMap.has(item)); + const created = []; + const touchedPermissionIds = []; + + if (!args.dryRun && missingPaths.length > 0) { + await conn.beginTransaction(); + try { + for (const methodPath of missingPaths) { + const defaults = buildPermissionDefaults(methodPath, templateRow); + const permissionId = await insertPermission(conn, defaults); + created.push({ methodPath, permissionId }); + touchedPermissionIds.push(permissionId); + } + await conn.commit(); + } catch (error) { + await conn.rollback(); + throw error; + } + } + + const latestMap = args.dryRun + ? existingMap + : await queryExistingPermissions(conn, methodPaths); + + for (const methodPath of methodPaths) { + const permissionId = latestMap.get(methodPath); + if (permissionId) touchedPermissionIds.push(permissionId); + } + + const uniquePermissionIds = [ ...new Set(touchedPermissionIds) ]; + let roleBindingCreated = 0; + + if (!args.dryRun) { + for (const permissionId of uniquePermissionIds) { + const createdBinding = await bindRolePermission(conn, args.roleId, permissionId); + if (createdBinding) roleBindingCreated++; + } + } + + const summary = { + mode: args.dryRun ? 'dry-run' : 'apply', + roleId: args.roleId, + totalAuthMethods: methodPaths.length, + existingPermissionCount: existingMap.size, + missingPermissionCount: missingPaths.length, + createdPermissionCount: created.length, + roleBindingCreated, + sampleMissing: missingPaths.slice(0, 20), + }; + + console.log('[sync-system-api-permission] summary'); + console.log(JSON.stringify(summary, null, 2)); + } finally { + await conn.end(); + } +} + +main().catch(error => { + console.error('[sync-system-api-permission] failed'); + console.error(error && error.stack ? error.stack : String(error)); + process.exit(1); +}); diff --git a/stock.todo b/stock.todo deleted file mode 100644 index 658f66d..0000000 --- a/stock.todo +++ /dev/null @@ -1,112 +0,0 @@ -# stock.todo - -## 任务目标 -- 提取 `app/service/systemMethods/stock/warehouse.js` 迁移前 method 的历史测试请求记录。 -- 精简并保留新接口(`stock.warehouse.*`)的测试入口。 -- 根据输入/输出补全 `warehouse.js` 方法头注释和 API 文档 `description`。 - -## 迁移方法映射(旧 -> 新) -- `stock.stockWarehouse` -> `stock.warehouse.list` -- `stock.getProhibitedType` -> `stock.warehouse.getProhibitedType` -- `stock.getInfo` -> `stock.warehouse.getInfo` -- `stock.saveWarehouseStock` -> `stock.warehouse.saveWarehouseStock` -- `stock.createWarehouseStock` -> `stock.warehouse.createWarehouseStock` -- `stock.getBarcodes` -> `stock.warehouse.getBarcodes` -- `stock.saveWarehouseStockBarcode` -> `stock.warehouse.saveWarehouseStockBarcode` -- `stock.getStoreStocks` -> `stock.warehouse.getStoreStocks` -- `stock.bindItem` -> `stock.warehouse.bindItem` -- `stock.unbindItem` -> `stock.warehouse.unbindItem` -- `stock.checkItemCodeUnique` -> `stock.warehouse.checkItemCodeUnique` -- `stock.queryStockLogs` -> `stock.warehouse.queryStockLogs` -- `stock.handleBatchDelete` -> `stock.warehouse.handleBatchDelete` -- `stock.deleteUnit` -> `stock.warehouse.deleteUnit` -- `stock.deleteProhibited` -> `stock.warehouse.deleteProhibited` -- `stock.handleBatchChange` -> `stock.warehouse.handleBatchChange` -- `stock.getStockUnits` -> `stock.warehouse.getStockUnits` -- `stock.getUnitList` -> `stock.warehouse.getUnitList` -- `stock.createProhibited` -> `stock.warehouse.createProhibited` -- `stock.createUnit` -> `stock.warehouse.createUnit` -- `stock.search` -> `stock.warehouse.search` - -## 历史测试请求记录提取(迁移前/过渡期) -来源:`node_modules/.mochawesome-reports/mochawesome.json`(2026-03-25) - -### 记录1:新列表接口请求 -- case: `system.stock.warehouse.namespaced.test.js` -- method: `stock.warehouse.list` -- request: -```json -{ - "pagination": { "page": 1, "pageSize": 5 }, - "where": {} -} -``` -- expected: -```json -{ - "httpStatus": 200, - "flag": "success", - "code": 200, - "data": { - "list": "Array", - "pagination": "Object" - } -} -``` - -### 记录2:旧入口退场验证请求(历史) -- case: `system.stock.warehouse.namespaced.test.js`(精简前) -- method: `stock.stockWarehouse` -- request: -```json -{ - "pagination": { "page": 1, "pageSize": 5 }, - "where": {} -} -``` -- expected: -```json -{ - "httpStatus": 500, - "flag": "failure", - "code": 500, - "message": "方法 stockWarehouse 不存在" -} -``` - -### 记录3:where 条件解析服务级样本 -来源:`test/app/service/systems/stock_store.stockWarehouse.conditions.test.js` -- input: -```json -{ - "where": { - "item_code": { "operator": "like", "value": "SKU" }, - "barcode": { "operator": "like", "value": "BC" }, - "prohibited_type": { "operator": "eq", "value": 2 }, - "quantity": { "operator": "ge", "type": "number", "value": "2" } - }, - "pagination": { "page": 1, "pageSize": 10 }, - "sort": { "sortField": "quantity", "sortOrder": "ASC" } -} -``` -- expected: -```json -{ - "code": 200, - "message": "查询成功", - "data.pagination.page": 1, - "data.pagination.pageSize": 10, - "data.queryInfo.hasBarcodeSearch": true -} -``` - -## 新接口精简测试方案 -- 保留:`test/app/controller/system.stock.warehouse.namespaced.test.js` -- 用例:只验证 `stock.warehouse.list` 请求成功与核心返回结构。 -- 下沉:复杂 where/operator 组合继续由 service 级测试覆盖。 - -## 执行结果 -- [x] `warehouse.js` 方法头注释补充(输入/输出声明) -- [x] 新接口测试用例精简 -- [x] `methods/system.json` 的 `stock.warehouse.*` description 语义化更新(21项) -- [x] 回归测试复跑并记录结果(`8 passing`) diff --git a/test/app/controller/gateway.user.bindAccountByTempCode.test.js b/test/app/controller/gateway.user.bindAccountByTempCode.test.js index 36246ef..64ed022 100644 --- a/test/app/controller/gateway.user.bindAccountByTempCode.test.js +++ b/test/app/controller/gateway.user.bindAccountByTempCode.test.js @@ -10,23 +10,49 @@ const { const YE4S_TEST_USER_ID = Number(process.env.SYSTEM_TEST_YE4S_USER_ID || 28); describe('test/app/controller/gateway.user.bindAccountByTempCode.test.js', () => { - it('should bind, unbind, and bind again for ye4s user', async () => { + it('should scan, bind, unbind, and bind again for ye4s user', async () => { const { token } = await getAuthToken(); + const ensurePendingCode = async () => { + let bindCodeRes = await invokeSystemMethod('user.getBindWechatCode', {}, token); + assert.equal(bindCodeRes.status, 200); + assert.equal(bindCodeRes.body.flag, 'success'); + + if (bindCodeRes.body?.data?.status === 'bound') { + const unbindFirst = await invokeSystemMethod('user.unbindWechat', {}, token); + assert.equal(unbindFirst.status, 200); + assert.equal(unbindFirst.body.flag, 'success'); + bindCodeRes = await invokeSystemMethod('user.getBindWechatCode', {}, token); + assert.equal(bindCodeRes.status, 200); + assert.equal(bindCodeRes.body.flag, 'success'); + } + + const nextCode = String(bindCodeRes.body?.data?.code || ''); + assert.match(nextCode, /^(?=.*[A-Z])(?=.*\d)[A-Z\d]{6}$/); + return nextCode; + }; + const infoRes = await invokeSystemMethod('user.info', {}, token); assert.equal(infoRes.status, 200); assert.equal(infoRes.body.flag, 'success'); const accountId = Number(infoRes.body?.data?.id); assert.ok(Number.isFinite(accountId) && accountId > 0); - const bindCodeRes = await invokeSystemMethod('user.getBindWechatCode', { - forceRefresh: true, - init: true, - }, token); - assert.equal(bindCodeRes.status, 200); - assert.equal(bindCodeRes.body.flag, 'success'); - const code = String(bindCodeRes.body?.data?.code || ''); - assert.ok(code.length > 10); + const code = await ensurePendingCode(); + + const scanRes1 = await invokeGatewayMethod('user.getUserByTempCode', { code }); + assert.equal(scanRes1.status, 200); + assert.equal(scanRes1.body.flag, 'success'); + assert.equal(scanRes1.body.code, 200); + assert.equal(Number(scanRes1.body?.data?.account_id), accountId); + assert.ok(String(scanRes1.body?.data?.real_name || '')); + assert.equal(scanRes1.body?.data?.status, 'scanned'); + + const scannedStateRes1 = await invokeSystemMethod('user.getBindWechatCode', {}, token); + assert.equal(scannedStateRes1.status, 200); + assert.equal(scannedStateRes1.body.flag, 'success'); + assert.equal(scannedStateRes1.body?.data?.status, 'scanned'); + assert.equal(String(scannedStateRes1.body?.data?.code || ''), code); const bindRes1 = await invokeGatewayMethod('user.bindAccountByTempCode', { code, @@ -46,8 +72,18 @@ describe('test/app/controller/gateway.user.bindAccountByTempCode.test.js', () => assert.equal(unbindRes.body?.data?.status, 'unbound'); assert.equal(Number(unbindRes.body?.data?.account_id), accountId); + const code2 = await ensurePendingCode(); + + const scanRes2 = await invokeGatewayMethod('user.getUserByTempCode', { code: code2 }); + assert.equal(scanRes2.status, 200); + assert.equal(scanRes2.body.flag, 'success'); + assert.equal(scanRes2.body.code, 200); + assert.equal(Number(scanRes2.body?.data?.account_id), accountId); + assert.ok(String(scanRes2.body?.data?.real_name || '')); + assert.equal(scanRes2.body?.data?.status, 'scanned'); + const bindRes2 = await invokeGatewayMethod('user.bindAccountByTempCode', { - code, + code: code2, ye4s_user_id: YE4S_TEST_USER_ID, }); assert.equal(bindRes2.status, 200); @@ -57,11 +93,10 @@ describe('test/app/controller/gateway.user.bindAccountByTempCode.test.js', () => assert.equal(Number(bindRes2.body?.data?.ye4s_user_id), YE4S_TEST_USER_ID); assert.equal(bindRes2.body?.data?.status, 'bound'); - const verifyRes = await invokeGatewayMethod('user.getUserByTempCode', { code }); - assert.equal(verifyRes.status, 200); - assert.equal(verifyRes.body.flag, 'success'); - assert.equal(verifyRes.body.code, 200); - assert.equal(Number(verifyRes.body?.data?.account_id), accountId); - assert.equal(verifyRes.body?.data?.status, 'bound'); + const boundStateRes = await invokeSystemMethod('user.getBindWechatCode', {}, token); + assert.equal(boundStateRes.status, 200); + assert.equal(boundStateRes.body.flag, 'success'); + assert.equal(boundStateRes.body?.data?.status, 'bound'); + assert.equal(String(boundStateRes.body?.data?.code || ''), ''); }); }); diff --git a/test/app/controller/system.setting.permission.test.js b/test/app/controller/system.setting.permission.test.js new file mode 100644 index 0000000..3a18fd9 --- /dev/null +++ b/test/app/controller/system.setting.permission.test.js @@ -0,0 +1,234 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const { + getAuthToken, + invokeSystemMethod, +} = require('../../support/system_method_client'); + +const EXTRA_HEADERS = { + platform: 'web', + project: 'all', +}; + +describe('test/app/controller/system.setting.permission.test.js', () => { + let token = ''; + let anchorPermissionId = 0; + let createdPermissionId = 0; + + before(async () => { + const auth = await getAuthToken({ forceLogin: true }); + token = auth.token; + + const listRes = await invokeSystemMethod('setting.permission.list', {}, token, EXTRA_HEADERS); + assert.equal(listRes.status, 200); + assert.equal(listRes.body.flag, 'success'); + assert.equal(listRes.body.code, 200); + + const permissions = Array.isArray(listRes.body?.data?.permissions) ? listRes.body.data.permissions : []; + assert.ok(permissions.length > 0, '当前账号无可用权限,无法执行回归'); + anchorPermissionId = Number(permissions[0].permission_id || 0); + assert.ok(anchorPermissionId > 0, '锚点权限ID无效'); + }); + + after(async () => { + if (createdPermissionId > 0) { + await invokeSystemMethod('setting.permission.delete', { + ids: [ createdPermissionId ], + }, token, EXTRA_HEADERS); + } + }); + + it('should reject out-of-scope permission update', async () => { + const updateRes = await invokeSystemMethod('setting.permission.update', { + permission_id: 999999999, + name: 'out_of_scope_update', + }, token, EXTRA_HEADERS); + + assert.equal(updateRes.status, 200); + assert.equal(updateRes.body.flag, 'failure'); + assert.ok([ 400, 404 ].includes(Number(updateRes.body.code)), `unexpected code: ${updateRes.body.code}`); + assert.match(String(updateRes.body.message || ''), /(超出当前登录工号可用权限集|权限不存在)/); + }); + + it('should create then update then delete permission successfully', async () => { + const suffix = Date.now(); + const path = `autotest.permission.${suffix}`; + + const addRes = await invokeSystemMethod('setting.permission.add', { + path, + type: 'btns', + name: `autotest_add_${suffix}`, + parent_id: anchorPermissionId, + meta_title: `autotest_meta_${suffix}`, + sort: 0, + hidden: 0, + always_show: 0, + status: 1, + }, token, EXTRA_HEADERS); + + assert.equal(addRes.status, 200); + assert.equal(addRes.body.flag, 'success'); + assert.equal(addRes.body.code, 200); + createdPermissionId = Number(addRes.body?.data?.permission_id || 0); + assert.ok(createdPermissionId > 0, '新增权限失败,permission_id 无效'); + + const updateRes = await invokeSystemMethod('setting.permission.update', { + permission_id: createdPermissionId, + name: `autotest_update_${suffix}`, + meta_title: `autotest_meta_update_${suffix}`, + status: 1, + }, token, EXTRA_HEADERS); + + assert.equal(updateRes.status, 200); + assert.equal(updateRes.body.flag, 'success'); + assert.equal(updateRes.body.code, 200); + assert.equal(Number(updateRes.body?.data?.permission_id), createdPermissionId); + + const deleteRes = await invokeSystemMethod('setting.permission.delete', { + ids: [ createdPermissionId ], + }, token, EXTRA_HEADERS); + + assert.equal(deleteRes.status, 200); + assert.equal(deleteRes.body.flag, 'success'); + assert.equal(deleteRes.body.code, 200); + const deletedIds = Array.isArray(deleteRes.body?.data?.deleted_ids) ? deleteRes.body.data.deleted_ids : []; + assert.ok(deletedIds.includes(createdPermissionId), '删除结果中未包含新建权限ID'); + + const deleteAgainRes = await invokeSystemMethod('setting.permission.delete', { + ids: [ createdPermissionId ], + }, token, EXTRA_HEADERS); + assert.equal(deleteAgainRes.status, 200); + assert.equal(deleteAgainRes.body.flag, 'success'); + assert.equal(deleteAgainRes.body.code, 200); + const alreadyDeletedIds = Array.isArray(deleteAgainRes.body?.data?.already_deleted_ids) + ? deleteAgainRes.body.data.already_deleted_ids + : []; + assert.ok(alreadyDeletedIds.includes(createdPermissionId), '二次删除未返回 already_deleted_ids'); + + createdPermissionId = 0; + }); + + it('should split deleted_ids and already_deleted_ids in mixed batch delete', async () => { + const suffix = Date.now(); + const firstPath = `autotest.permission.mixed.first.${suffix}`; + const secondPath = `autotest.permission.mixed.second.${suffix}`; + let firstPermissionId = 0; + let secondPermissionId = 0; + + try { + const addFirstRes = await invokeSystemMethod('setting.permission.add', { + path: firstPath, + type: 'btns', + name: `autotest_mixed_first_${suffix}`, + parent_id: anchorPermissionId, + status: 1, + }, token, EXTRA_HEADERS); + assert.equal(addFirstRes.status, 200); + assert.equal(addFirstRes.body.flag, 'success'); + assert.equal(addFirstRes.body.code, 200); + firstPermissionId = Number(addFirstRes.body?.data?.permission_id || 0); + assert.ok(firstPermissionId > 0, 'first permission_id 无效'); + + const addSecondRes = await invokeSystemMethod('setting.permission.add', { + path: secondPath, + type: 'btns', + name: `autotest_mixed_second_${suffix}`, + parent_id: anchorPermissionId, + status: 1, + }, token, EXTRA_HEADERS); + assert.equal(addSecondRes.status, 200); + assert.equal(addSecondRes.body.flag, 'success'); + assert.equal(addSecondRes.body.code, 200); + secondPermissionId = Number(addSecondRes.body?.data?.permission_id || 0); + assert.ok(secondPermissionId > 0, 'second permission_id 无效'); + + const preDeleteRes = await invokeSystemMethod('setting.permission.delete', { + ids: [ firstPermissionId ], + }, token, EXTRA_HEADERS); + assert.equal(preDeleteRes.status, 200); + assert.equal(preDeleteRes.body.flag, 'success'); + assert.equal(preDeleteRes.body.code, 200); + + const mixedDeleteRes = await invokeSystemMethod('setting.permission.delete', { + ids: [ firstPermissionId, secondPermissionId ], + }, token, EXTRA_HEADERS); + + assert.equal(mixedDeleteRes.status, 200); + assert.equal(mixedDeleteRes.body.flag, 'success'); + assert.equal(mixedDeleteRes.body.code, 200); + + const deletedIds = Array.isArray(mixedDeleteRes.body?.data?.deleted_ids) + ? mixedDeleteRes.body.data.deleted_ids + : []; + const alreadyDeletedIds = Array.isArray(mixedDeleteRes.body?.data?.already_deleted_ids) + ? mixedDeleteRes.body.data.already_deleted_ids + : []; + + assert.ok(deletedIds.includes(secondPermissionId), 'mixed 删除结果中缺少启用权限ID'); + assert.ok(alreadyDeletedIds.includes(firstPermissionId), 'mixed 删除结果中缺少已删除权限ID'); + + firstPermissionId = 0; + secondPermissionId = 0; + } finally { + const cleanupIds = [ firstPermissionId, secondPermissionId ].filter(id => Number(id) > 0); + if (cleanupIds.length > 0) { + await invokeSystemMethod('setting.permission.delete', { + ids: cleanupIds, + }, token, EXTRA_HEADERS); + } + } + }); + + it('should reject mixed delete when ids contain out-of-scope permission', async () => { + const suffix = Date.now(); + const path = `autotest.permission.mixed.outscope.${suffix}`; + let permissionId = 0; + + try { + const addRes = await invokeSystemMethod('setting.permission.add', { + path, + type: 'btns', + name: `autotest_mixed_outscope_${suffix}`, + parent_id: anchorPermissionId, + status: 1, + }, token, EXTRA_HEADERS); + + assert.equal(addRes.status, 200); + assert.equal(addRes.body.flag, 'success'); + assert.equal(addRes.body.code, 200); + permissionId = Number(addRes.body?.data?.permission_id || 0); + assert.ok(permissionId > 0, 'permission_id 无效'); + + const mixedRes = await invokeSystemMethod('setting.permission.delete', { + ids: [ permissionId, 999999999 ], + }, token, EXTRA_HEADERS); + + assert.equal(mixedRes.status, 200); + assert.equal(mixedRes.body.flag, 'failure'); + assert.ok([ 400, 404 ].includes(Number(mixedRes.body.code)), `unexpected code: ${mixedRes.body.code}`); + assert.match(String(mixedRes.body.message || ''), /(超出当前登录工号可用权限集|权限不存在)/); + + // 失败后应保持原子性:合法权限仍可被正常删除(说明前一次未误删) + const verifyDeleteRes = await invokeSystemMethod('setting.permission.delete', { + ids: [ permissionId ], + }, token, EXTRA_HEADERS); + + assert.equal(verifyDeleteRes.status, 200); + assert.equal(verifyDeleteRes.body.flag, 'success'); + assert.equal(verifyDeleteRes.body.code, 200); + const deletedIds = Array.isArray(verifyDeleteRes.body?.data?.deleted_ids) + ? verifyDeleteRes.body.data.deleted_ids + : []; + assert.ok(deletedIds.includes(permissionId), '混入越权ID失败后,合法权限不应被提前删除'); + + permissionId = 0; + } finally { + if (permissionId > 0) { + await invokeSystemMethod('setting.permission.delete', { + ids: [ permissionId ], + }, token, EXTRA_HEADERS); + } + } + }); +}); diff --git a/test/app/controller/system.user.getLoginWechatCode.test.js b/test/app/controller/system.user.getLoginWechatCode.test.js new file mode 100644 index 0000000..0507107 --- /dev/null +++ b/test/app/controller/system.user.getLoginWechatCode.test.js @@ -0,0 +1,17 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const { invokeSystemMethod } = require('../../support/system_method_client'); + +describe('test/app/controller/system.user.getLoginWechatCode.test.js', () => { + it('should return login code without Authorization token', async () => { + const res = await invokeSystemMethod('user.getLoginWechatCode', {}); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + assert.equal(res.body.code, 200); + assert.match(String(res.body?.data?.client_code || ''), /^(?=.*[A-Z])(?=.*\d)[A-Z\d]{6}$/); + assert.match(String(res.body?.data?.code || ''), /^(?=.*[A-Z])(?=.*\d)[A-Z\d]{6}$/); + assert.equal(res.body?.data?.status, 'pending'); + }); +}); diff --git a/test/app/controller/system.user.loginByCode.test.js b/test/app/controller/system.user.loginByCode.test.js index 928ff74..af3dad0 100644 --- a/test/app/controller/system.user.loginByCode.test.js +++ b/test/app/controller/system.user.loginByCode.test.js @@ -3,11 +3,14 @@ const assert = require('node:assert/strict'); const { invokeSystemMethod } = require('../../support/system_method_client'); -const VALID_LOGIN_CODE = process.env.SYSTEM_TEST_LOGIN_CODE - || 'eyJ1dWlkIjoiMDg2MTk4MzQtY2FhYS00OTIyLWJmNjctODc5M2U2Y2MwYzJkIn0='; +const VALID_LOGIN_CODE = String(process.env.SYSTEM_TEST_LOGIN_CODE || '').trim(); describe('test/app/controller/system.user.loginByCode.test.js', () => { - it('should login successfully when code is valid', async () => { + it('should login successfully when code is valid', async function() { + if (!VALID_LOGIN_CODE) { + this.skip(); + } + const res = await invokeSystemMethod('user.loginByCode', { code: VALID_LOGIN_CODE, }); @@ -30,23 +33,23 @@ describe('test/app/controller/system.user.loginByCode.test.js', () => { assert.match(String(res.body.message || ''), /code/); }); - it('should fail when code is not valid base64 json', async () => { + it('should fail when code does not exist', async () => { const code = `INVALID_CODE_${Date.now()}`; const res = await invokeSystemMethod('user.loginByCode', { code }); assert.equal(res.status, 200); assert.equal(res.body.flag, 'failure'); assert.equal(res.body.code, 0); - assert.match(String(res.body.message || ''), /无效的登录码格式/); + assert.match(String(res.body.message || ''), /登录码不存在|登录失败/); }); - it('should fail when decoded payload does not contain uuid', async () => { - const code = Buffer.from(JSON.stringify({ foo: 'bar' }), 'utf8').toString('base64'); + it('should fail when code format is valid but not matched', async () => { + const code = 'A1B2C3'; const res = await invokeSystemMethod('user.loginByCode', { code }); assert.equal(res.status, 200); assert.equal(res.body.flag, 'failure'); assert.equal(res.body.code, 0); - assert.match(String(res.body.message || ''), /uuid/); + assert.match(String(res.body.message || ''), /登录码不存在|登录失败/); }); }); diff --git a/test/app/service/systems/auth.user.bindWechatCacheExpiry.test.js b/test/app/service/systems/auth.user.bindWechatCacheExpiry.test.js new file mode 100644 index 0000000..620c21e --- /dev/null +++ b/test/app/service/systems/auth.user.bindWechatCacheExpiry.test.js @@ -0,0 +1,152 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const UserService = require('../../../../app/service/systems/auth/user'); + +function createServiceHarness() { + const cacheWrites = []; + const cacheStore = new Map(); + + const app = { + async setCacheAsync(cacheKey, data, expireSeconds = 300) { + cacheWrites.push({ + cacheKey, + data, + expireSeconds, + }); + + if (data === null || data === undefined || expireSeconds <= 1) { + cacheStore.delete(cacheKey); + return; + } + + cacheStore.set(cacheKey, data); + }, + async getCacheAsync(cacheKey) { + return cacheStore.has(cacheKey) ? cacheStore.get(cacheKey) : null; + }, + coreLogger: { + warn() {}, + error() {}, + }, + }; + + const ctx = { + app, + userId: 1001, + user: { + id: 1001, + }, + }; + + const service = new UserService(ctx); + + return { + app, + ctx, + service, + cacheWrites, + cacheStore, + }; +} + +describe('test/app/service/systems/auth.user.bindWechatCacheExpiry.test.js', () => { + it('should generate pending code with fixed 60s ttl and keep same code without extending', async () => { + const fixedNow = 1760000000000; + const originalNow = Date.now; + Date.now = () => fixedNow; + + try { + const { service, cacheWrites } = createServiceHarness(); + service.findYe4sBindingByAccountId = async () => null; + + const first = await service.refreshWechatBindState(1001, null, { + forceNewCode: false, + }); + + assert.equal(first.state.status, 'pending'); + assert.match(String(first.state.code || ''), /^(?=.*[A-Z])(?=.*\d)[A-Z\d]{6}$/); + assert.equal(first.state.expires_at, fixedNow + 60000); + + const firstWriteCount = cacheWrites.length; + assert.equal(firstWriteCount, 2); + for (const write of cacheWrites) { + assert.equal(write.expireSeconds, 60); + } + + const second = await service.refreshWechatBindState(1001, first.state, { + forceNewCode: false, + }); + + assert.equal(second.state.code, first.state.code); + assert.equal(second.state.status, 'pending'); + assert.equal(cacheWrites.length, firstWriteCount); + } finally { + Date.now = originalNow; + } + }); + + it('should return scanned status when scan key exists', async () => { + const fixedNow = 1760000000000; + const originalNow = Date.now; + Date.now = () => fixedNow; + + try { + const { service, cacheStore } = createServiceHarness(); + service.findYe4sBindingByAccountId = async () => null; + + const pending = await service.refreshWechatBindState(1001, null, { + forceNewCode: false, + }); + const code = pending.state.code; + + cacheStore.set(`user:wechat:bind:scan:${code}`, { + account_id: 1001, + code, + status: 'scanned', + scanned_at: new Date(fixedNow + 1000).toISOString(), + }); + + const result = await service.refreshWechatBindState(1001, pending.state, { + forceNewCode: false, + }); + + assert.equal(result.state.status, 'scanned'); + assert.equal(result.state.code, code); + assert.ok(result.state.scanned_at); + } finally { + Date.now = originalNow; + } + }); + + it('should rotate code when forceNewCode is enabled', async () => { + const fixedNow = 1760000000000; + const originalNow = Date.now; + Date.now = () => fixedNow; + + try { + const { service, cacheWrites } = createServiceHarness(); + service.findYe4sBindingByAccountId = async () => null; + + const oldState = { + account_id: 1001, + status: 'pending', + code: 'A1B2C3', + expires_at: fixedNow + 30000, + }; + + const result = await service.refreshWechatBindState(1001, oldState, { + forceNewCode: true, + }); + + assert.equal(result.state.status, 'pending'); + assert.notEqual(result.state.code, oldState.code); + assert.equal(result.state.expires_at, fixedNow + 60000); + + const oldCodeInvalidation = cacheWrites.find(item => item && item.data === null && item.expireSeconds === 1); + assert.ok(oldCodeInvalidation); + } finally { + Date.now = originalNow; + } + }); +}); diff --git a/test/app/service/systems/auth.user.loginWechatCode.test.js b/test/app/service/systems/auth.user.loginWechatCode.test.js new file mode 100644 index 0000000..7d559fd --- /dev/null +++ b/test/app/service/systems/auth.user.loginWechatCode.test.js @@ -0,0 +1,103 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const UserService = require('../../../../app/service/systems/auth/user'); + +function createServiceHarness() { + const cacheWrites = []; + const cacheStore = new Map(); + + const app = { + async setCacheAsync(cacheKey, data, expireSeconds = 300) { + cacheWrites.push({ + cacheKey, + data, + expireSeconds, + }); + + if (data === null || data === undefined || expireSeconds <= 1) { + cacheStore.delete(cacheKey); + return; + } + + cacheStore.set(cacheKey, data); + }, + async getCacheAsync(cacheKey) { + return cacheStore.has(cacheKey) ? cacheStore.get(cacheKey) : null; + }, + coreLogger: { + warn() {}, + error() {}, + }, + }; + + const ctx = { + app, + }; + + const service = new UserService(ctx); + + return { + app, + ctx, + service, + cacheWrites, + cacheStore, + }; +} + +describe('test/app/service/systems/auth.user.loginWechatCode.test.js', () => { + it('should generate client code and login code when client code is missing', async () => { + const { service, cacheWrites } = createServiceHarness(); + + const result = await service.getLoginWechatCode({}); + + assert.equal(result.success, true); + assert.equal(result.code, 200); + assert.match(String(result.data.client_code || ''), /^(?=.*[A-Z])(?=.*\d)[A-Z\d]{6}$/); + assert.match(String(result.data.code || ''), /^(?=.*[A-Z])(?=.*\d)[A-Z\d]{6}$/); + assert.equal(result.data.status, 'pending'); + assert.ok(String(result.message || '').includes('客户端编码')); + + const writesWithState = cacheWrites.filter(item => item && item.data && item.data.client_code === result.data.client_code); + assert.equal(writesWithState.length, 2); + for (const write of writesWithState) { + assert.equal(write.expireSeconds, 60); + } + }); + + it('should refresh login code after long poll when client code is provided', async () => { + const { service, cacheWrites } = createServiceHarness(); + service.waitForLoginCodeRefresh = async () => {}; + + const first = await service.getLoginWechatCode({}); + const firstCode = String(first.data.code || ''); + const clientCode = String(first.data.client_code || ''); + + const second = await service.getLoginWechatCode({ + clientCode, + }); + + assert.equal(second.success, true); + assert.equal(second.code, 200); + assert.equal(String(second.data.client_code || ''), clientCode); + assert.match(String(second.data.code || ''), /^(?=.*[A-Z])(?=.*\d)[A-Z\d]{6}$/); + assert.notEqual(String(second.data.code || ''), firstCode); + assert.ok(String(second.message || '').includes('长轮询结束')); + + const invalidationWrite = cacheWrites.find(item => item && item.data === null && item.expireSeconds === 1); + assert.ok(invalidationWrite); + }); + + it('should fail when provided client code format is invalid', async () => { + const { service } = createServiceHarness(); + + const result = await service.getLoginWechatCode({ + clientCode: 'abc', + }); + + assert.equal(result.success, false); + assert.equal(result.code, 0); + assert.match(String(result.message || ''), /客户端编码/); + }); +}); From 920d201c0eb0490dc2fbb33e66671730771440da Mon Sep 17 00:00:00 2001 From: liufumingren Date: Tue, 31 Mar 2026 00:35:53 +0800 Subject: [PATCH 013/550] feat: refine setting role/account/permission auth and tests --- .sequelizerc | 8 +- AI_TOOLBOX.md | 44 +- README.md | 391 +- app/lib/query_condition_parser.js | 47 +- app/model/api_app.js | 1 + app/model/express.js | 27 + app/model/express_print_record.js | 204 + app/model/express_setting.js | 48 + app/model/file.js | 6 + app/model/interface_type.js | 1 + app/model/notification_webhook.js | 162 + app/model/order_express.js | 89 + app/model/order_express_print_data.js | 54 + app/model/permission.js | 11 +- app/model/role.js | 26 +- app/model/role_permission.js | 78 - app/model/store.js | 9 +- app/service/apiMethods/print.js | 334 + app/service/main.js | 127 +- app/service/system.js | 3 - app/service/systemMethods/index.js | 52 - app/service/systemMethods/setting/account.js | 52 +- .../systemMethods/setting/permission.js | 60 + app/service/systemMethods/setting/role.js | 68 + .../systemMethods/setting/store_warehouse.js | 60 + .../systemMethods/storage/receiving.js | 32 +- app/service/systemMethods/storeWarehouse.js | 65 + .../systemMethods/storeWarehouse/store.js | 3 + app/service/systemMethods/user.js | 39 +- app/service/systems/account_platform.js | 2 +- app/service/systems/auth/role_permission.js | 369 +- app/service/systems/auth/user.js | 1093 +- app/service/systems/excel.js | 744 ++ app/service/systems/setting/account.js | 526 +- app/service/systems/setting/permission.js | 651 ++ app/service/systems/setting/role.js | 695 ++ .../systems/setting/store_warehouse.js | 711 ++ app/service/systems/storage/receiving.js | 858 +- app/service/systems/store_warehouse.js | 1441 +++ app/service/systems/upload.js | 28 +- config/config.default.js | 1 + database/config.js | 83 + ...dd-policy-config-to-wms-store-warehouse.js | 25 + ...4113000-create-wms-notification-webhook.js | 154 + ...60405002000-add-expire-time-to-wms-file.js | 26 + docs/express-model-table-map.md | 24 + methods/gateway.json | 157 +- methods/system.json | 9302 +++++++++-------- package-lock.json | 898 +- package.json | 5 +- script/backfill-role-permissions.cjs | 224 + script/deploy-lib.cjs | 19 +- script/sync-system-api-permission.cjs | 362 + stock.todo | 112 - ...gateway.user.bindAccountByTempCode.test.js | 67 +- ....setting.account.getBindWechatCode.test.js | 195 + .../system.setting.permission.test.js | 343 + .../controller/system.setting.role.test.js | 198 + .../system.setting.storeWarehouse.test.js | 413 + .../system.storage.receiving.test.js | 330 + .../controller/system.storeWarehouse.test.js | 122 + .../system.user.getLoginWechatCode.test.js | 17 + .../system.user.loginByCode.test.js | 19 +- .../auth.user.bindWechatCacheExpiry.test.js | 152 + .../systems/auth.user.loginWechatCode.test.js | 103 + test/app/service/systems/excel.test.js | 257 + ...ck_store.stockWarehouse.conditions.test.js | 2 +- .../systems/storage.receiving.report.test.js | 127 + 68 files changed, 17363 insertions(+), 5593 deletions(-) create mode 100644 app/model/express.js create mode 100644 app/model/express_print_record.js create mode 100644 app/model/express_setting.js create mode 100644 app/model/notification_webhook.js create mode 100644 app/model/order_express.js create mode 100644 app/model/order_express_print_data.js delete mode 100644 app/model/role_permission.js create mode 100644 app/service/apiMethods/print.js create mode 100644 app/service/systemMethods/setting/permission.js create mode 100644 app/service/systemMethods/setting/role.js create mode 100644 app/service/systemMethods/setting/store_warehouse.js create mode 100644 app/service/systemMethods/storeWarehouse.js create mode 100644 app/service/systemMethods/storeWarehouse/store.js create mode 100644 app/service/systems/excel.js create mode 100644 app/service/systems/setting/permission.js create mode 100644 app/service/systems/setting/role.js create mode 100644 app/service/systems/setting/store_warehouse.js create mode 100644 app/service/systems/store_warehouse.js create mode 100644 database/config.js create mode 100644 database/migrations/20260404093000-add-policy-config-to-wms-store-warehouse.js create mode 100644 database/migrations/20260404113000-create-wms-notification-webhook.js create mode 100644 database/migrations/20260405002000-add-expire-time-to-wms-file.js create mode 100644 docs/express-model-table-map.md create mode 100644 script/backfill-role-permissions.cjs create mode 100644 script/sync-system-api-permission.cjs delete mode 100644 stock.todo create mode 100644 test/app/controller/system.setting.account.getBindWechatCode.test.js create mode 100644 test/app/controller/system.setting.permission.test.js create mode 100644 test/app/controller/system.setting.role.test.js create mode 100644 test/app/controller/system.setting.storeWarehouse.test.js create mode 100644 test/app/controller/system.storeWarehouse.test.js create mode 100644 test/app/controller/system.user.getLoginWechatCode.test.js create mode 100644 test/app/service/systems/auth.user.bindWechatCacheExpiry.test.js create mode 100644 test/app/service/systems/auth.user.loginWechatCode.test.js create mode 100644 test/app/service/systems/excel.test.js create mode 100644 test/app/service/systems/storage.receiving.report.test.js diff --git a/.sequelizerc b/.sequelizerc index 4dbbd8d..694d16d 100644 --- a/.sequelizerc +++ b/.sequelizerc @@ -3,8 +3,8 @@ const path = require('path'); module.exports = { - "config": path.join(__dirname, 'database/config.json'), - "migrations-path": path.join(__dirname, 'database/migrations'), - "seeders-path": path.join(__dirname, 'database/seeders'), - "models-path": path.join(__dirname, 'app/model'), + config: path.join(__dirname, 'database/config.js'), + 'migrations-path': path.join(__dirname, 'database/migrations'), + 'seeders-path': path.join(__dirname, 'database/seeders'), + 'models-path': path.join(__dirname, 'app/model'), }; \ No newline at end of file diff --git a/AI_TOOLBOX.md b/AI_TOOLBOX.md index 2ecaf48..94e36d6 100644 --- a/AI_TOOLBOX.md +++ b/AI_TOOLBOX.md @@ -1,6 +1,6 @@ # AI 工具箱(WMS) -本文件用于统一 AI 协助开发/调试时可直接使用的方法,减少重复沟通成本。 +本文件用于统一 AI 协助开发/调试时可直接使用的方法,减少重复沟通成本。AI每次应答文尾加喵~以判断是否丢失上下文 ## 1. 适用范围 @@ -591,4 +591,46 @@ npx egg-bin test test/app/controller/system.user.info.web.test.js test/app/contr - `print.getList` - `storage.entry.list` - `stock.warehouse.list` + +## 15. system API 权限映射规则(wms_permission) + +适用范围:`/system` 入口,权限类型为 `type=api`。 + +### 15.1 映射规则 + +- `wms_permission.path` 作为 system method 的权限标识(例如:`setting.account.list`)。 +- 同步来源以 `methods/system.json` 为准:`isNeedAuth=true` 的 method 必须存在对应 `wms_permission(type=api,path=method)`。 +- 角色权限不再以 `wms_role_permission` 作为主存储,统一写入 `wms_role.permissions`。 +- `wms_role.permissions` 支持两种值: + - JSON 数组:如 `[1,2,3]` + - `"*"`:表示拥有所有权限 +- 新增 API 权限后,`role_id=2` 的授权应同步更新其 `permissions` 字段;若该字段为 `"*"` 则无需额外追加。 + +### 15.2 外部脚本(批量补齐) + +固定命令: + +```powershell +# 预览差异(不写库) +npm run permission:sync:system-api -- --dry-run + +# 执行补齐(写库) +npm run permission:sync:system-api +``` + +可选参数: + +- `--role-id=2`:绑定角色 ID(默认 `2`) +- `--db-client=wms`:数据库客户端名(默认 `wms`) +- `--config-path=./config/config.local.js`:配置文件路径 +- `--method-doc=./methods/system.json`:method 文档路径 + +### 15.3 运行时兜底(仅 debug) + +- 入口:`app/service/main.js` 的 `checkApiPermission`。 +- 逻辑:当用户权限列表不包含目标 method 时,若 `app.config.debug === true`,自动: + 1. 参考现有 `type=api` 权限行构建缺失权限行; + 2. 更新 `wms_role(id=2).permissions`,将新权限 ID 追加到 JSON 数组;若该字段为 `"*"` 则保持不变。 +- 生产建议:保持 `app.config.debug=false`,避免运行时自动写库。 + \ No newline at end of file diff --git a/README.md b/README.md index 94f9f59..0389d75 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,11 @@ # 奇门WMS(qimen-wms) -基于 Egg.js 的仓储管理系统(WMS),支持多快递平台对接、订单管理、打印、权限、配置等功能,适合中小型电商与仓储企业二次开发。基于AI协助管理项目开发,配置了AI能力脚本和完整的项目地图 +基于 Egg.js 的仓储管理系统(WMS),支持多快递平台对接、订单管理、打印、权限、配置等功能,适合中小型电商与仓储企业二次开发。 ## 文档导航 -- AI项目协作工具箱:`AI_TOOLBOX.md` +- 项目协作工具箱:`AI_TOOLBOX.md` - Method 路由映射说明:`AI_METHOD_ROUTING.md` -- stock.warehouse.list 前端查询规则:`docs/stock-stockWarehouse-query-rules.md` - system 接口文档源:`methods/system.json` - qimen 接口文档源:`methods/qimen.json` - 日报:`day.log` @@ -24,7 +23,6 @@ ├── config/ # 配置(poloapi、redis、数据库等) ├── database/ # 迁移与数据库配置 ├── methods/ # 接口文档数据源(JSON) -├── native/ # 原生扩展目录(Node.js C++ addon) ├── script/ # 调试与文档生成脚本 ├── logs/ # 日志 ├── run/ # 运行时/元数据 @@ -39,7 +37,6 @@ - `README.md`:项目入口文档,提供整体说明与规范入口。 - `AI_TOOLBOX.md`:AI/开发协作操作手册,包含脚本与工作流。 - `AI_METHOD_ROUTING.md`:接口入口与 method 到代码文件的映射。 -- `docs/stock-stockWarehouse-query-rules.md`:stock.warehouse.list 的 where 构造规则与失败返回说明。 - `methods/system.json`:system 接口定义(headers、groups、params、response、errors)。 - `methods/qimen.json`:qimen 接口定义(按奇门协议组织)。 - `day.log`:每日工作留痕。 @@ -57,121 +54,10 @@ npm run dev - `npm run dev`:本地开发 - `npm start`:启动生产服务 -- `npm stop`:仅停止当前目录对应的 Egg 生产进程 -- `npm run deploy:prod`:按 `config/deploy.config.local.cjs` 通过 SSH 发布到生产目录 `/www/wwwroot/qimen` -- `npm run deploy:init`:首次发布初始化远端目录与 `config/` 基础文件(不覆盖已有配置) -- `npm run rollback:prod`:按最近一次备份回退生产目录(可加 `-- --backup=backup-时间戳.tar.gz` 指定备份) -- `npm run deploy:precheck`:只读预检 SSH 连通、目录权限、远端 Node/npm/tar 与健康检查,不改动远端文件 -- `npm run deploy:version`:查询当前线上版本号(读取远端 `.deploy/state/current-release.json`) -- `npm run deploy:version:history`:查询最近 20 次线上版本历史 -- `npm run deploy:inspect`:查看远端 `.deploy/state`、`latest-backup.txt` 与备份目录清单 -- `npm run deploy:smoke`:在远端机器本机对 `/`、`/api/docs`、`/internal/v1/gateway`、`/system` 做最小连通冒烟 -- `npm run deploy:verify`:组合执行 `deploy:inspect` + `deploy:smoke` -- `npm run deploy:cleanup-backups -- `:按文件名清理远端 `.deploy/backups` 中指定备份 -- `npm run deploy:gateway-probe -- [payloadJson]`:调用 `/internal/v1/gateway` 做 method 级连通探针 -- `npm run version:record`:记录一次本地包版本快照(写入 `versioning/`,用于回退追溯) -- `npm run version:history`:查询最近 50 条本地版本快照记录 -- `npm run guard:git`:检查当前暂存区是否包含禁止提交的本地机密/运行产物 -- `npm run setup:hooks`:将仓库 pre-commit hook 固化到 `.githooks/pre-commit` +- `npm stop`:停止生产服务 - `npm run lint`:代码风格检查 - `npm test`:单元测试 -## 外部 Method 测试(Egg.js test 规范) - -测试文件按“暴露出口 + method”命名,位于 `test/app/controller/`: - -- `system.user.login.test.js` -- `system.user.info.test.js` - -测试辅助客户端位于: - -- `test/support/system_method_client.js` - -默认测试账号(可通过环境变量覆盖): - -- `SYSTEM_TEST_USERNAME=liufumingren` -- `SYSTEM_TEST_PASSWORD=111111` - -Token 暂存机制: - -- 登录 token 会写入 `test/.runtime/system_user_token.json`。 -- 每次执行测试会优先读取本地 token;若 token 可用,则跳过 `user.login` 调用。 -- 当 token 不存在或过期时,测试脚本会自动调用 `user.login` 并刷新缓存。 - -常用命令: - -```bash -npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js -``` - -可选环境变量: - -- `SYSTEM_TEST_BASE_URL`:默认 `http://127.0.0.1:6060` -- `SYSTEM_TEST_TOKEN_FILE`:默认 `test/.runtime/system_user_token.json` - -## Method 输出一致性回归(新规则) - -目标: - -- 在模型/关联/服务改动前后,确保关键 method 输出结果一致。 - -强制规则: - -1. 改动前先执行 baseline(生成修改前输出快照)。 -2. 改动后执行 compare(对同一批 method 回放并比对)。 -3. compare 结果必须 `mismatch=0` 才可交付。 - -测试账号(默认): - -- `liufumingren / 111111` -- 可通过环境变量覆盖: - - `WMS_TEST_USER` - - `WMS_TEST_PASS` - -method 来源与样本来源: - -- method 配置来源:`methods/system.json` -- 样本数据来源(优先最新日志):`wms_system_log` -- 参考日志来源:`wms_api_log`、`wms_operation_log`、`wms_account_login_log` - -执行脚本: - -- `script/method-output-regression.cjs` -- `script/tmp-generate-method-regression-test.cjs`(根据 baseline 自动生成 Egg.js 标注测试) - -临时文件目录规则: - -- 所有临时产物统一输出到 `temp/`。 -- `temp/` 已加入 git 忽略,不纳入提交。 - -执行命令: - -```powershell -# 修改前:生成基线(默认抽样 8 条) -node .\script\method-output-regression.cjs baseline 8 - -# 修改后:执行对比 -node .\script\method-output-regression.cjs compare - -# 生成 Egg.js 标注测试脚本 -node .\script\tmp-generate-method-regression-test.cjs - -# 执行生成的回归测试 -npx egg-bin test temp/generated-tests/system.method-output.generated.test.js -``` - -输出文件: - -- `temp/method-output/method-output-baseline.json` -- `temp/method-output/method-output-baseline.md` -- `temp/method-output/method-output-compare.json` - -一致性比对说明: - -- 为避免误报,脚本会标准化以下波动字段:`token`、`timestamp`、`last_login_at`、`created_at`、`updated_at`、`iat`、`exp`。 -- 403 权限响应同样参与一致性对比,用于防止权限链路被意外改动。 -- 后续所有接口返回数据检测,统一以生成的 Egg.js 标注测试结果为准。 - ## 主要依赖 - egg.js 3.x @@ -184,6 +70,8 @@ npx egg-bin test temp/generated-tests/system.method-output.generated.test.js - `GET /`:健康检查 - `POST /qimen`:奇门接口 - `POST /system`:system 统一入口 +- `POST /api/v1`:旧版 API +- `POST /api/v2`:新版 API - `GET /template/xml/:id`:打印模板 - `GET|POST /auth/printSetting/:code`:打印台设置 @@ -200,70 +88,6 @@ npx egg-bin test temp/generated-tests/system.method-output.generated.test.js - 全局业务 Header(如 `platform`、`project`)设置 - 方法级在线 POST 调试 -### user.getBindWechatCode 调用约定(微信绑定码) - -- 默认行为:立即返回当前状态(不会长等待,适合页面初始化)。 -- 显式长轮询:仅当 body 传 `waitForChange=true`(或兼容字段 `longPoll=true`)时启用。 -- 长轮询时长:后端单次最长等待 60 秒;60 秒内状态变化会立即返回。 -- 超时返回:若 60 秒内无变化,返回当前状态并提示超时。 -- 初始化强制立即返回:可传 `init=true`(兼容 `isInit=true`、`firstLoad=true`)。 -- 可选等待参数:`waitTimeoutMs`,后端自动封顶 60000。 -- 前端超时建议:HTTP 超时设置为 120000ms(2 分钟),覆盖网络抖动与重试开销。 - -## 接口响应规范(system) - -更新时间:2026-03-22 -适用范围: - -- `POST /system` - -统一目标: - -- 统一 `/system` 入口的响应结构与错误码口径,降低调用方分支判断成本。 - -成功响应示例: - -```json -{ - "flag": "success", - "code": 1, - "message": "ok", - "data": {}, - "timestamp": 1773386721 -} -``` - -失败响应示例: - -```json -{ - "flag": "failure", - "code": 401, - "message": "Unauthorized", - "data": null, - "timestamp": 1773386721 -} -``` - -说明: - -- 业务层若已返回 `flag/code/message` 标准结构,将保留并补齐 `timestamp`。 -- 业务层若返回普通对象或数组,控制器将自动包裹到 `data` 字段。 -- HTTP 状态码保持语义(如 400/401/403/500),业务 `code` 默认与 HTTP 状态码一致。 - -当前错误码口径: - -- 400:请求参数错误(缺少 `method`、`v`、`timestamp`、非法 `method`) -- 401:未登录/令牌无效/无令牌 -- 403:无权限访问 -- 406:业务授权状态异常(如仓库有效期) -- 500:服务内部错误 - -实现位置: - -- 响应封装:`app/lib/api_response.js` -- 控制器接入:`app/controller/home.js`(system/pda) - ## 接口文档联动维护(强制) 当出现以下任一变更时,必须同步更新 `methods` 下对应文档: @@ -284,163 +108,12 @@ node .\script\tmp-struct-system-params.cjs ``` 4. 补充自动提取无法覆盖的信息(description/response/errors/枚举约束) -5. 执行 method 输出一致性对比: - -```powershell -node .\script\method-output-regression.cjs compare -``` ## 配置说明 - 主要配置文件在 `config/`(如 `config.default.js`、`config.local.js`、`poloapi.js`) - 数据库、Redis、平台配置在对应配置文件中维护 - 敏感信息不要提交到仓库 -- 远程发布配置模板:`config/deploy.config.example.cjs` -- 本地 SSH 发布配置:`config/deploy.config.local.cjs`(已加入 git ignore,仅本机保留) - -## 远程发布与回退(SSH) - -生产目录固定为:`/www/wwwroot/qimen` - -约定: - -- 发布脚本通过本机 `ssh/scp/tar/git` 执行,不依赖额外 npm 包。 -- 每次发布前会在服务器上生成一份当前目录备份,保存到 `/www/wwwroot/qimen/.deploy/backups/`。 -- 回退默认使用最近一次发布前备份,也支持显式传入备份名。 -- 发布和回退都会保留 `.deploy`、`logs`、`run`、`temp` 目录,避免误删运行态目录。 -- 发布与回退阶段的停服务操作只会匹配当前 `deployRoot` 对应的 Egg 进程,不再直接调用全局 `egg-scripts stop` 扫描整机进程。 - -首次配置: - -1. 完善 `config/deploy.config.local.cjs` 中的 `host`、`username`、`privateKeyPath`。 -2. 执行 `npm run setup:hooks`,启用本地 pre-commit 安全检查。 -3. 确认远端机器存在 Node.js、npm、tar,且 SSH 用户对 `/www/wwwroot/qimen` 有读写权限。 -4. 执行 `npm run deploy:init` 完成首次初始化(只在远端 `config/` 缺失或为空时写入基础文件)。 - -发布命令: - -```powershell -npm run deploy:init -npm run deploy:prod -``` - -回退命令: - -```powershell -npm run rollback:prod -npm run rollback:prod -- --backup=backup-20260324123045.tar.gz -``` - -脚本行为: - -- 发布时按 Egg.js 最小运行集打包(默认仅 `app.js`、`app/**`、`methods/**`、`native/addons/**`、`package*.json`)。 -- 打包文件来自已跟踪 git 文件(`git ls-files --cached`),不会带入本地未跟踪文件。 -- `config/` 目录不参与发布包覆盖,远端发布与回退过程都会保留现有 `config/`。 -- 首次发布若远端不存在 `config/`,发布会中止并提示先创建生产配置。 -- 默认发布后执行:`npm install --production`、定点停止当前部署目录进程、`npm start`。 -- 若配置了 `healthCheckUrl`,发布与回退后会执行一次健康检查。 -- 每次发布会自动生成线上版本号,格式:`v{package.version}-{yyyyMMddHHmmss}-{gitShortCommit}`。 -- 发布会写入版本元数据到远端: - - 当前版本:`/www/wwwroot/qimen/.deploy/state/current-release.json` - - 历史版本:`/www/wwwroot/qimen/.deploy/state/release-history.jsonl` - -版本查询命令: - -```powershell -npm run deploy:version -npm run deploy:version:history -``` - -运维检查与清理命令: - -```powershell -npm run deploy:inspect -npm run deploy:smoke -npm run deploy:verify -npm run deploy:cleanup-backups -- backup-20260324202526.tar.gz backup-20260324204750.tar.gz -npm run deploy:gateway-probe -- releaseProbe.ping "{}" -``` - -## 本地版本管理目录(回退辅助) - -目录:`versioning/` - -用途: - -- 记录每次更新时的包版本、提交号、分支、时间。 -- 部署成功后会自动追加一条记录(source=`deploy:prod`)。 -- 也可手动记录一次快照(source=`version:record`)。 - -文件: - -- `versioning/package-version-current.json`:当前最近一条本地版本记录 -- `versioning/package-version-history.jsonl`:本地版本历史(JSONL) - -说明: - -- `versioning/` 目录内容默认不提交到 git(仅保留目录占位)。 -- 回退前可先通过本地历史快速定位目标版本,再结合远端备份名执行回退。 - -本地命令: - -```powershell -# 手动记录一次本地版本快照 -npm run version:record - -# 查询本地版本历史 -npm run version:history -``` - -当前等待项: - -- 由于 SSH 目标主机、账号、私钥路径仍是占位值,完成这些字段前不要执行发布/回退测试。 - -## App 能力清单(汇总) - -能力入口文件: - -- `app.js` -- `app/extend/application.js` - -### A. 应用启动能力(app.js) - -- 设置应用根路径:`global.APP_ROOT`、`app.appRoot` -- 启动前初始化动态工厂: - - `OrderDeliveryFactory` - - `OrderItemsFactory` -- 启动时自检扩展能力: - - 缓存方法可用性(`app.setCacheAsync` / `app.getCacheAsync`) - - Message 能力类型检查(`app.Message`) -- 扩展全局日期格式化:`Date.prototype.format('YYYY-MM-DD HH:mm:ss')` - -### B. Application 扩展能力(app/extend/application.js) - -- 业务字典访问能力: - - `businessDict` getter - - `getBusinessTypeName(code)` - - `getOperationCodeName(code)` - - `getPlatformName(code)` - - `getExternalLogTypeName(type)` -- 外部 SOAP 调用能力: - - `wsdl(methodName, args)` -- Redis 缓存能力(cache client): - - `setCacheAsync(cacheKey, data, expireSeconds = 300)` - - `getCacheAsync(cacheKey)` -- Message 扩展能力: - - `Message` getter(返回 MessageClass) - -### C. 迁移完成确认 - -- 原先在 `app.js` 直接挂载的字典映射方法已迁移到 `app/extend/application.js`。 -- 当前 `app.js` 仅保留启动初始化与非方法迁移逻辑,避免双源实现。 - -### D. Method 输出回归能力(质量门禁) - -- 回归脚本:`script/method-output-regression.cjs` -- 基线文件:`temp/method-output/method-output-baseline.json`、`temp/method-output/method-output-baseline.md` -- 对比文件:`temp/method-output/method-output-compare.json` -- 使用方式:先 `baseline`,后 `compare` -- 门禁标准:`mismatch=0` 才允许交付 ## 功能模块 @@ -449,41 +122,55 @@ npm run version:history - 打印与打印台管理 - 仓库/门店管理 - 权限与角色管理 -- 原生扩展算法能力(native/addons) +- Excel 表格生成、导入与解析 -## Native 原生扩展能力 +## Excel 服务能力 -目录:`native/addons/` +系统已提供服务类:`app/service/systems/excel.js`,可通过 `ctx.service.systems.excel` 调用。 -当前已存在的原生模块: +支持能力: -- `subset_selector.node`(已在业务代码接入) - - 接入位置:`app/service/apiMethods/test.js` - - 已使用能力:`selectOrders(orders, n, type)` - - 业务用途:对订单及 SKU 集合进行子集筛选/组合选择(用于加速 JS 侧大批量集合计算) +- 生成单 sheet / 多 sheet Excel +- 按 `columns + rows` 输出表格 +- 输出 `Buffer`、写入本地文件、直接作为下载响应返回 +- 解析 `.xlsx` / `.xls` 文件内容为 JSON +- 自动处理空表头、重复表头 -- `fibonacci_addon.node`(当前未检索到业务调用) - - 现状:仓库中存在产物文件,但暂无 controller/service 调用链路 +常用方法: -当前接入状态说明: +- `generateBuffer(options)`:生成 Excel 二进制内容 +- `writeFile(filePath, options)`:写入本地文件 +- `sendFile({ filename, sheets })`:HTTP 下载输出 +- `parseBuffer(buffer, options)`:解析上传后的文件流 +- `parseFile(filePath, options)`:解析本地 Excel 文件 -- `subset_selector.node` 在 service 构造时通过 `require(app.appRoot + '/native/addons/subset_selector.node')` 动态加载。 -- 若加载失败,日志会记录“C++插件加载失败”,对应方法会因 addon 不可用而无法执行原生算法分支。 +示例: -兼容性提示: +```js +const buffer = await ctx.service.systems.excel.generateBuffer({ + sheets: [ + { + name: '入库单', + columns: [ + { header: '单号', key: 'order_no', width: 20 }, + { header: '货主', key: 'owner_name', width: 18 }, + ], + rows: [ + { order_no: 'RK20260404001', owner_name: '测试货主' }, + ], + }, + ], +}); -- Node.js 原生 addon 与运行环境强相关(系统、架构、Node ABI 版本)。 -- 当出现 `ERR_DLOPEN_FAILED` / `is not a valid Win32 application` 时,通常表示 addon 与当前 Node 版本或构建目标不匹配,需要使用目标环境重新编译 addon。 +const parsed = await ctx.service.systems.excel.parseFile('D:/tmp/demo.xlsx'); +``` ## 常见问题 - 启动端口默认 6060,可在配置中调整 - 数据库/Redis 连接失败优先检查 `config/config.local.js` - 接口路由映射可查阅 `AI_METHOD_ROUTING.md` -- native addon 加载失败(`ERR_DLOPEN_FAILED`)时,优先检查 Node 版本与 addon 构建目标是否一致 -- `npm run deploy:prod` 提示 SSH 配置未完善时,先补齐 `config/deploy.config.local.cjs` 中的 `host/username/privateKeyPath` -- `npm run guard:git` 或 pre-commit 拦截提交时,说明暂存区包含本地机密文件或运行产物 -- system接口的日志在数据库wms中的表wms_system_log + ## 日报维护 - 日报统一记录在 `day.log` diff --git a/app/lib/query_condition_parser.js b/app/lib/query_condition_parser.js index 72737d4..baeac5b 100644 --- a/app/lib/query_condition_parser.js +++ b/app/lib/query_condition_parser.js @@ -20,24 +20,51 @@ function isEmptyValue(value) { return false; } -function normalizeDate(value) { +function formatLocalDateTime(date, isEnd = false) { + const year = date.getFullYear(); + const month = String(date.getMonth() + 1).padStart(2, '0'); + const day = String(date.getDate()).padStart(2, '0'); + return `${year}-${month}-${day} ${isEnd ? '23:59:59' : '00:00:00'}`; +} + +function normalizeDate(value, options = {}) { + const { isEnd = false } = options; + if (value === undefined || value === null) { return value; } - if (typeof value === 'string') { - return value.trim(); - } - if (value instanceof Date) { if (isNaN(value.getTime())) return value; - return value.toISOString().slice(0, 19).replace('T', ' '); + return formatLocalDateTime(value, isEnd); } if (typeof value === 'number') { const date = new Date(value); if (isNaN(date.getTime())) return value; - return date.toISOString().slice(0, 19).replace('T', ' '); + return formatLocalDateTime(date, isEnd); + } + + if (typeof value === 'string') { + const trimmed = value.trim(); + if (!trimmed) { + return trimmed; + } + + if (/^\d+$/.test(trimmed)) { + const date = new Date(Number(trimmed)); + if (!isNaN(date.getTime())) { + return formatLocalDateTime(date, isEnd); + } + return trimmed; + } + + const parsed = new Date(trimmed); + if (!isNaN(parsed.getTime())) { + return formatLocalDateTime(parsed, isEnd); + } + + return trimmed; } return value; @@ -59,11 +86,13 @@ function processConditionValue(value, type) { return value; case 'date': + return normalizeDate(value, { isEnd: false }); + case 'daterange': if (Array.isArray(value)) { - return value.map(v => normalizeDate(v)); + return value.map((v, index) => normalizeDate(v, { isEnd: index === value.length - 1 })); } - return normalizeDate(value); + return normalizeDate(value, { isEnd: false }); case 'number': { const num = parseFloat(value); diff --git a/app/model/api_app.js b/app/model/api_app.js index 51e9cfe..d0540e3 100644 --- a/app/model/api_app.js +++ b/app/model/api_app.js @@ -177,6 +177,7 @@ module.exports = app => { freezeTableName: true, underscored: true, timestamps: true, + paranoid: false, createdAt: 'created_at', updatedAt: 'updated_at', comment: 'API应用配置表', diff --git a/app/model/express.js b/app/model/express.js new file mode 100644 index 0000000..bda9b96 --- /dev/null +++ b/app/model/express.js @@ -0,0 +1,27 @@ +'use strict'; + +module.exports = app => { + const { STRING } = app.Sequelize; + + const Express = app.model.define('express', { + code: { + type: STRING(50), + primaryKey: true, + allowNull: false, + comment: '快递编码', + }, + name: { + type: STRING(255), + allowNull: true, + comment: '快递名称', + }, + }, { + tableName: 'wms_express', + freezeTableName: true, + underscored: true, + timestamps: false, + comment: '快递基础信息表', + }); + + return Express; +}; diff --git a/app/model/express_print_record.js b/app/model/express_print_record.js new file mode 100644 index 0000000..85ce1a6 --- /dev/null +++ b/app/model/express_print_record.js @@ -0,0 +1,204 @@ +'use strict'; + +module.exports = app => { + const { BIGINT, STRING, INTEGER, DATE, TEXT, JSON } = app.Sequelize; + + const ExpressPrintRecord = app.model.define('express_print_record', { + id: { + type: BIGINT(20), + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + express_id: { + type: BIGINT(20), + allowNull: false, + comment: '快递记录ID', + }, + order_id: { + type: STRING(50), + allowNull: false, + comment: '订单ID', + }, + express_no: { + type: STRING(50), + allowNull: false, + comment: '快递单号', + }, + platform: { + type: STRING(50), + allowNull: false, + comment: '平台编码', + }, + template_id: { + type: BIGINT(20), + allowNull: false, + comment: '模板ID', + }, + template_url: { + type: STRING(500), + allowNull: true, + comment: '模板URL', + }, + printer_name: { + type: STRING(100), + allowNull: true, + comment: '打印机名称', + }, + printer_config_id: { + type: BIGINT(20), + allowNull: true, + comment: '打印配置ID', + }, + print_data: { + type: JSON, + allowNull: false, + comment: '打印请求数据', + }, + encrypted_data: { + type: TEXT, + allowNull: true, + comment: '加密数据', + }, + signature: { + type: STRING(500), + allowNull: true, + comment: '签名', + }, + add_data: { + type: JSON, + allowNull: true, + comment: '附加数据', + }, + custom_data: { + type: JSON, + allowNull: true, + comment: '自定义数据', + }, + print_status: { + type: STRING(20), + allowNull: false, + defaultValue: 'PENDING', + comment: '打印状态', + }, + print_count: { + type: INTEGER(11), + allowNull: true, + defaultValue: 0, + comment: '打印次数', + }, + last_print_time: { + type: DATE, + allowNull: true, + comment: '最近打印时间', + }, + next_retry_time: { + type: DATE, + allowNull: true, + comment: '下次重试时间', + }, + request_id: { + type: STRING(100), + allowNull: true, + comment: '请求ID', + }, + document_id: { + type: STRING(100), + allowNull: true, + comment: '文档ID', + }, + batch_no: { + type: STRING(50), + allowNull: true, + comment: '批次号', + }, + print_result: { + type: TEXT, + allowNull: true, + comment: '打印结果', + }, + error_message: { + type: STRING(500), + allowNull: true, + comment: '错误信息', + }, + print_cost_time: { + type: INTEGER(11), + allowNull: true, + comment: '打印耗时(ms)', + }, + create_interface: { + type: STRING(100), + allowNull: true, + comment: '创建接口名', + }, + print_interface: { + type: STRING(100), + allowNull: true, + comment: '打印接口名', + }, + operator_id: { + type: BIGINT(20), + allowNull: true, + comment: '操作人ID', + }, + warehouse_id: { + type: BIGINT(20), + allowNull: true, + comment: '仓库ID', + }, + create_time: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + print_time: { + type: DATE, + allowNull: true, + comment: '打印时间', + }, + update_time: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + }, { + tableName: 'wms_express_print_record', + freezeTableName: true, + underscored: true, + timestamps: false, + comment: '快递面单打印记录表', + indexes: [ + { + name: 'idx_express_id', + fields: [ 'express_id' ], + }, + { + name: 'idx_order_id', + fields: [ 'order_id' ], + }, + { + name: 'idx_express_no', + fields: [ 'express_no' ], + }, + { + name: 'uk_request_id', + unique: true, + fields: [ 'request_id' ], + }, + { + name: 'idx_warehouse_id', + fields: [ 'warehouse_id' ], + }, + { + name: 'idx_print_status', + fields: [ 'print_status' ], + }, + ], + }); + + return ExpressPrintRecord; +}; diff --git a/app/model/express_setting.js b/app/model/express_setting.js new file mode 100644 index 0000000..9256d5e --- /dev/null +++ b/app/model/express_setting.js @@ -0,0 +1,48 @@ +'use strict'; + +module.exports = app => { + const { INTEGER, STRING, BIGINT } = app.Sequelize; + + const ExpressSetting = app.model.define('express_setting', { + id: { + type: INTEGER(11), + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + express_code: { + type: STRING(50), + allowNull: true, + comment: '快递编码', + }, + code: { + type: STRING(50), + allowNull: true, + comment: '设置项编码', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '仓库主体ID', + }, + }, { + tableName: 'wms_express_setting', + freezeTableName: true, + underscored: true, + timestamps: false, + comment: '快递配置表', + indexes: [ + { + name: 'idx_express_code', + fields: [ 'express_code' ], + }, + { + name: 'idx_warehouse_id', + fields: [ 'warehouse_id' ], + }, + ], + }); + + return ExpressSetting; +}; diff --git a/app/model/file.js b/app/model/file.js index ab10e36..2499a4a 100644 --- a/app/model/file.js +++ b/app/model/file.js @@ -102,6 +102,12 @@ module.exports = app => { defaultValue: null, comment: '更新时间', }, + expire_time: { + type: DATE, + allowNull: true, + defaultValue: null, + comment: '过期时间,为空表示永不过期', + }, is_deleted: { type: BOOLEAN, allowNull: false, diff --git a/app/model/interface_type.js b/app/model/interface_type.js index 06f1b59..2e845e2 100644 --- a/app/model/interface_type.js +++ b/app/model/interface_type.js @@ -76,6 +76,7 @@ module.exports = app => { freezeTableName: true, underscored: true, timestamps: true, + paranoid: false, createdAt: 'created_at', updatedAt: 'updated_at', comment: '接口类型配置表', diff --git a/app/model/notification_webhook.js b/app/model/notification_webhook.js new file mode 100644 index 0000000..c0a6037 --- /dev/null +++ b/app/model/notification_webhook.js @@ -0,0 +1,162 @@ +'use strict'; + +module.exports = app => { + const { BIGINT, STRING, TINYINT, DATE, JSON } = app.Sequelize; + + const NotificationWebhook = app.model.define('notification_webhook', { + id: { + type: BIGINT.UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + store_id: { + type: BIGINT.UNSIGNED, + allowNull: false, + comment: '主体ID,对应 wms_store.id', + references: { + model: 'store', + key: 'id', + }, + }, + hook_name: { + type: STRING(100), + allowNull: true, + comment: 'Webhook 名称', + }, + hook_type: { + type: STRING(50), + allowNull: false, + validate: { + notEmpty: { + msg: 'hook_type 不能为空', + }, + len: { + args: [ 1, 50 ], + msg: 'hook_type 长度应在1-50个字符之间', + }, + }, + comment: 'Webhook 类型,用于按类型分派通知结构处理逻辑', + }, + hook_url: { + type: STRING(500), + allowNull: false, + validate: { + notEmpty: { + msg: 'hook_url 不能为空', + }, + len: { + args: [ 1, 500 ], + msg: 'hook_url 长度应在1-500个字符之间', + }, + }, + comment: 'Webhook 链接地址', + }, + events: { + type: JSON, + allowNull: true, + comment: '订阅事件列表', + }, + extra_config: { + type: JSON, + allowNull: true, + comment: '扩展配置,如签名、请求头、模板映射等', + }, + status: { + type: TINYINT(4), + allowNull: false, + defaultValue: 1, + validate: { + isIn: { + args: [[ 0, 1 ]], + msg: '状态值不合法,0-禁用,1-启用', + }, + }, + comment: '状态:0-禁用,1-启用', + }, + remark: { + type: STRING(255), + allowNull: true, + comment: '备注', + }, + created_by: { + type: BIGINT.UNSIGNED, + allowNull: true, + comment: '创建人', + }, + created_at: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '删除时间', + }, + }, { + tableName: 'wms_notification_webhook', + freezeTableName: true, + underscored: true, + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: true, + deletedAt: 'deleted_at', + comment: '外部通知 WebHook 配置表', + indexes: [ + { + name: 'idx_notification_webhook_store_id', + fields: [ 'store_id' ], + }, + { + name: 'idx_notification_webhook_hook_type', + fields: [ 'hook_type' ], + }, + { + name: 'idx_notification_webhook_status', + fields: [ 'status' ], + }, + { + name: 'idx_notification_webhook_store_type', + fields: [ 'store_id', 'hook_type' ], + }, + { + name: 'uk_notification_webhook_store_type_url', + unique: true, + fields: [ 'store_id', 'hook_type', 'hook_url' ], + }, + ], + }); + + NotificationWebhook.associate = function() { + const { Store, Account } = app.model; + + NotificationWebhook.belongsTo(Store, { + foreignKey: 'store_id', + targetKey: 'id', + as: 'store', + }); + + NotificationWebhook.belongsTo(Account, { + foreignKey: 'created_by', + targetKey: 'id', + as: 'creator', + constraints: false, + }); + }; + + NotificationWebhook.prototype.isEnabled = function() { + return Number(this.status) === 1; + }; + + return NotificationWebhook; +}; diff --git a/app/model/order_express.js b/app/model/order_express.js new file mode 100644 index 0000000..a02f461 --- /dev/null +++ b/app/model/order_express.js @@ -0,0 +1,89 @@ +'use strict'; + +module.exports = app => { + const { BIGINT, STRING, DATE, ENUM } = app.Sequelize; + + const OrderExpress = app.model.define('order_express', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + waybill_code: { + type: STRING(50), + allowNull: true, + comment: '运单号', + }, + order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '订单ID', + }, + create_at: { + type: DATE, + allowNull: true, + comment: '创建时间', + }, + delete_at: { + type: DATE, + allowNull: true, + comment: '删除时间', + }, + is_galaxy_receive: { + type: ENUM('Y', 'N'), + allowNull: true, + comment: '是否星河签收', + }, + is_back: { + type: ENUM('Y', 'N'), + allowNull: true, + comment: '是否退回', + }, + is_intercept: { + type: ENUM('Y', 'N'), + allowNull: true, + comment: '是否拦截', + }, + logistics_code: { + type: STRING(50), + allowNull: true, + comment: '物流编码', + }, + logistics_interface_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '物流接口ID', + }, + logistics_name: { + type: STRING(50), + allowNull: true, + comment: '物流名称', + }, + logistics_interface_name: { + type: STRING(50), + allowNull: true, + comment: '物流接口名称', + }, + platform_code: { + type: STRING(50), + allowNull: true, + comment: '平台编码', + }, + }, { + tableName: 'wms_order_express', + freezeTableName: true, + underscored: true, + timestamps: false, + comment: '订单快递信息表', + indexes: [ + { + name: 'idx_order_id', + fields: [ 'order_id' ], + }, + ], + }); + + return OrderExpress; +}; diff --git a/app/model/order_express_print_data.js b/app/model/order_express_print_data.js new file mode 100644 index 0000000..8f68d14 --- /dev/null +++ b/app/model/order_express_print_data.js @@ -0,0 +1,54 @@ +'use strict'; + +module.exports = app => { + const { BIGINT, DATE, TEXT } = app.Sequelize; + + const OrderExpressPrintData = app.model.define('order_express_print_data', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + express_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '快递记录ID', + }, + data: { + type: TEXT, + allowNull: true, + comment: '打印数据', + }, + create_at: { + type: DATE, + allowNull: true, + comment: '创建时间', + }, + delete_at: { + type: DATE, + allowNull: true, + comment: '删除时间', + }, + update_at: { + type: DATE, + allowNull: true, + comment: '更新时间', + }, + }, { + tableName: 'wms_order_express_print_data', + freezeTableName: true, + underscored: true, + timestamps: false, + comment: '订单快递打印数据表', + indexes: [ + { + name: 'idx_express_id', + fields: [ 'express_id' ], + }, + ], + }); + + return OrderExpressPrintData; +}; diff --git a/app/model/permission.js b/app/model/permission.js index 795c2bf..9d0ee55 100644 --- a/app/model/permission.js +++ b/app/model/permission.js @@ -135,8 +135,8 @@ module.exports = app => { }); // 关联关系 - 自关联,构建树形结构 - Permission.associate = function(models) { - const { Role, Permission, RolePermission } = app.model; + Permission.associate = function() { + const { Permission } = app.model; // 子权限 Permission.hasMany(Permission, { foreignKey: 'parent_id', @@ -152,13 +152,6 @@ module.exports = app => { as: 'parent', }); - // 角色权限关联 - Permission.belongsToMany(Role, { - through: RolePermission, - foreignKey: 'permission_id', - otherKey: 'role_id', - as: 'roles', - }); }; // 实例方法:获取类型对应的中文名称 diff --git a/app/model/role.js b/app/model/role.js index 16d2af5..05521c2 100644 --- a/app/model/role.js +++ b/app/model/role.js @@ -49,6 +49,11 @@ module.exports = app => { allowNull: true, comment: '角色描述', }, + permissions: { + type: TEXT, + allowNull: true, + comment: '角色权限集,JSON数组;* 表示所有权限', + }, role_type: { type: TINYINT(4), allowNull: false, @@ -117,6 +122,12 @@ module.exports = app => { allowNull: true, comment: '所属仓库ID', }, + pid: { + type: BIGINT.UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '父级角色ID,顶级为0', + }, }, { tableName: 'wms_role', freezeTableName: true, @@ -143,12 +154,16 @@ module.exports = app => { name: 'idx_status', fields: [ 'status' ], }, + { + name: 'idx_pid', + fields: [ 'pid' ], + }, ], }); // 关联关系 - Role.associate = function(models) { - const { Account, Store, Permission, RolePermission, EmployeeRole } = app.model; + Role.associate = function() { + const { Account, Store, EmployeeRole } = app.model; // 创建人 Role.belongsTo(Account, { foreignKey: 'created_by', @@ -161,13 +176,6 @@ module.exports = app => { as: 'store', }); - // 权限关联 - Role.belongsToMany(Permission, { - through: RolePermission, - foreignKey: 'role_id', - otherKey: 'permission_id', - as: 'permissions', - }); Role.hasMany(EmployeeRole, { foreignKey: 'role_id', sourceKey: 'id', diff --git a/app/model/role_permission.js b/app/model/role_permission.js deleted file mode 100644 index 1bfd6aa..0000000 --- a/app/model/role_permission.js +++ /dev/null @@ -1,78 +0,0 @@ -'use strict'; - -module.exports = app => { - const { BIGINT, INTEGER, DATE } = app.Sequelize; - - const RolePermission = app.model.define('role_permission', { - id: { - type: BIGINT.UNSIGNED, - primaryKey: true, - autoIncrement: true, - allowNull: false, - comment: '关联ID', - }, - role_id: { - type: BIGINT.UNSIGNED, - allowNull: false, - comment: '角色ID', - }, - permission_id: { - type: INTEGER, - allowNull: false, - comment: '权限ID', - }, - created_at: { - type: DATE, - allowNull: false, - comment: '创建时间', - }, - }, { - tableName: 'wms_role_permission', - freezeTableName: true, - underscored: true, - timestamps: true, - paranoid: false, // 明确禁用软删除 - createdAt: 'created_at', - updatedAt: false, - comment: '角色权限关联表', - indexes: [ - { - name: 'uk_role_permission', - fields: [ 'role_id', 'permission_id' ], - unique: true, - }, - { - name: 'idx_role_id', - fields: [ 'role_id' ], - }, - { - name: 'idx_permission_id', - fields: [ 'permission_id' ], - }, - ], - }); - - // 关联关系 - RolePermission.associate = function(models) { - const { Role, Permission } = app.model; - // 关联角色 - RolePermission.belongsTo(Role, { - foreignKey: 'role_id', - as: 'role', - }); - - // 关联权限 - RolePermission.belongsTo(Permission, { - foreignKey: 'permission_id', - as: 'permission', - }); - }; - - // 实例方法:检查关联是否有效 - RolePermission.prototype.isValid = function() { - // 这里可以添加更多的有效性检查 - return this.role_id && this.permission_id; - }; - - return RolePermission; -}; diff --git a/app/model/store.js b/app/model/store.js index a3839a2..25057f1 100644 --- a/app/model/store.js +++ b/app/model/store.js @@ -1,7 +1,7 @@ 'use strict'; module.exports = app => { - const { BIGINT, STRING, DATE, TINYINT, INTEGER } = app.Sequelize; + const { BIGINT, STRING, DATE, TINYINT } = app.Sequelize; const Store = app.model.define('store', { id: { @@ -179,7 +179,7 @@ module.exports = app => { // 关联关系 - 使用您推荐的方式 Store.associate = function() { - const { Account, Role, AccountStoreEmployee, ProhibitedType } = app.model; + const { Account, Role, AccountStoreEmployee, ProhibitedType, NotificationWebhook } = app.model; // 关联创建人 Store.belongsTo(Account, { @@ -209,6 +209,11 @@ module.exports = app => { foreignKey: 'warehouse_id', as: 'prohibitedTypes', }); + + Store.hasMany(NotificationWebhook, { + foreignKey: 'store_id', + as: 'notificationWebhooks', + }); }; // 实例方法:检查商家是否启用 diff --git a/app/service/apiMethods/print.js b/app/service/apiMethods/print.js new file mode 100644 index 0000000..689c6de --- /dev/null +++ b/app/service/apiMethods/print.js @@ -0,0 +1,334 @@ +'use strict'; + +const Service = require('egg').Service; +const crypto = require('node:crypto'); + +class PrintApiService extends Service { + getPrinterRedis() { + return this.app.redis.get('printer'); + } + + normalizeBindValue(bindValue) { + let bindValueObj = bindValue; + try { + bindValueObj = JSON.parse(bindValue); + } catch (_) { + bindValueObj = bindValue; + } + return bindValueObj; + } + + async getEmployeePermissions(employeeId) { + const { ctx } = this; + const roleRows = await ctx.model.EmployeeRole.findAll({ + attributes: [ 'role_id' ], + where: { + employee_id: employeeId, + }, + include: [ + { + model: ctx.model.Role, + as: 'role', + attributes: [], + where: { + status: 1, + }, + required: true, + }, + ], + raw: true, + }); + + if (!roleRows || roleRows.length === 0) { + return []; + } + + const roleIds = [ ...new Set(roleRows.map(item => item.role_id).filter(Boolean)) ]; + if (roleIds.length === 0) { + return []; + } + + const permissionIds = await ctx.service.systems.auth.rolePermission.getPermissionIdsForRoles(roleIds, { + includeDisabled: false, + }); + if (permissionIds.length === 0) { + return []; + } + + const permissions = await ctx.model.Permission.findAll({ + attributes: [ 'path' ], + where: { + id: { + [ctx.app.Sequelize.Op.in]: permissionIds, + }, + status: 1, + type: 'api', + }, + raw: true, + }); + + return permissions.map(item => item.path).filter(Boolean); + } + + async getBindInfo(data = {}) { + const { ctx } = this; + const accountId = Number(data.account_id || data.accountId || data.wms_account_id || data.wmsAccountId); + const code = String(data.code || '').trim(); + + if (!Number.isFinite(accountId) || accountId <= 0 || !code) { + return { + success: false, + code: 0, + data: null, + message: '缺少有效参数 account_id 或 code', + }; + } + + const account = await ctx.model.Account.findOne({ + where: { id: accountId }, + attributes: [ 'id', 'status' ], + raw: true, + }); + if (!account || Number(account.status) !== 1) { + return { + success: false, + code: 0, + data: null, + message: '账号不存在或已禁用', + }; + } + + const redis = this.getPrinterRedis(); + const bindValue = await redis.get(`bind:${code}`); + if (!bindValue) { + return { + success: false, + code: 0, + data: null, + message: '无效code或未绑定', + }; + } + + const employeeRows = await ctx.model.AccountStoreEmployee.findAll({ + where: { + account_id: accountId, + status: 1, + }, + include: [ + { + model: ctx.model.Store, + as: 'store', + attributes: [ 'id', 'company_name', 'project', 'status', 'auth_end' ], + where: { + status: 1, + project: 'warehouse', + }, + required: true, + }, + ], + order: [[ 'created_at', 'DESC' ]], + }); + + const now = new Date(); + const warehouseMap = new Map(); + for (const employee of employeeRows) { + const permissions = await this.getEmployeePermissions(employee.id); + if (!permissions.includes('printer.bind')) { + continue; + } + + const store = employee.store; + if (!store) { + continue; + } + + if (store.auth_end && new Date(store.auth_end) < now) { + continue; + } + + warehouseMap.set(String(store.id), { + id: Number(store.id), + name: store.company_name, + }); + } + + const warehouses = Array.from(warehouseMap.values()); + if (warehouses.length === 0) { + return { + success: true, + code: 200, + data: { + warehouses: [], + }, + message: '无可绑定仓库', + }; + } + + const tempCode = crypto.randomBytes(16).toString('hex').toUpperCase(); + const tokenPayload = { + accountId, + code, + bindValue, + createdAt: new Date().toISOString(), + warehouses: warehouses.map(item => item.id), + }; + await redis.setex(`binding_token:${tempCode}`, 300, JSON.stringify(tokenPayload)); + + return { + success: true, + code: 200, + data: { + warehouses, + tempCode, + }, + message: '获取绑定信息成功', + }; + } + + async bindByTempCode(data = {}) { + const { ctx } = this; + const tempCode = String(data.temp_code || data.tempCode || '').trim(); + const printer = String(data.printer || data.workbench_name || data.workbenchName || '').trim(); + const warehouse = Number(data.warehouse || data.warehouse_id || data.warehouseId); + + if (!tempCode || !printer || !Number.isFinite(warehouse) || warehouse <= 0) { + return { + success: false, + code: 0, + data: null, + message: '参数缺失', + }; + } + + const redis = this.getPrinterRedis(); + const tokenText = await redis.get(`binding_token:${tempCode}`); + if (!tokenText) { + return { + success: false, + code: 0, + data: null, + message: '临时code无效或已过期', + }; + } + + let tokenData = null; + try { + tokenData = JSON.parse(tokenText); + } catch (_) { + tokenData = null; + } + + if (!tokenData || !tokenData.code || !Array.isArray(tokenData.warehouses)) { + return { + success: false, + code: 0, + data: null, + message: '临时code数据异常', + }; + } + + if (!tokenData.warehouses.includes(warehouse)) { + return { + success: false, + code: 0, + data: null, + message: '仓库无绑定权限', + }; + } + + const Store = ctx.model.Store; + const warehouseInfo = await Store.findOne({ + where: { + id: warehouse, + status: 1, + }, + raw: true, + }); + if (!warehouseInfo || warehouseInfo.project !== 'warehouse') { + return { + success: false, + code: 0, + data: null, + message: '仓库id校验失败', + }; + } + + const PrintComputer = ctx.model.PrintComputer; + let computerId = null; + const existComputer = await PrintComputer.findOne({ + where: { + warehouse_id: warehouse, + name: printer, + }, + }); + if (existComputer) { + if (Number(existComputer.status) === 1) { + return { + success: false, + code: 0, + data: null, + message: '该仓库下打印台名称已存在且可用', + }; + } + computerId = existComputer.id; + } else { + const newComputer = await PrintComputer.create({ + warehouse_id: warehouse, + name: printer, + status: 0, + }); + computerId = newComputer.id; + } + + const bindValueObj = this.normalizeBindValue(tokenData.bindValue); + const printServiceUrl = ctx.app.config.printService.url; + let printServiceResult = null; + try { + const res = await ctx.curl(`${printServiceUrl}/auth/bind`, { + method: 'POST', + contentType: 'json', + data: { + code: tokenData.code, + printer, + warehouse, + roomId: bindValueObj && bindValueObj.uniqueId ? bindValueObj.uniqueId : '', + computerId, + }, + dataType: 'json', + }); + printServiceResult = res.data; + } catch (err) { + printServiceResult = { success: false, error: '打印服务通讯失败' }; + } + + if (printServiceResult && printServiceResult.status === 'fail') { + return { + success: false, + code: 0, + data: { + printer, + warehouse, + printServiceResult, + }, + message: printServiceResult.message || '打印服务失败', + }; + } + + await redis.del(`binding_token:${tempCode}`); + + return { + success: true, + code: 200, + data: { + code: tokenData.code, + printer, + warehouse, + computerId, + printServiceResult, + }, + message: '绑定成功', + }; + } +} + +module.exports = PrintApiService; \ No newline at end of file diff --git a/app/service/main.js b/app/service/main.js index e0e518f..1644c26 100644 --- a/app/service/main.js +++ b/app/service/main.js @@ -337,13 +337,14 @@ class MainService extends Service { try { // 3. 验证JWT令牌 - const NewauthHeader = ''; const decoded = app.jwt.verify(token, app.config.jwt.secret); const now = Math.floor(Date.now() / 1000); const expiresIn = decoded.exp - now; if (expiresIn < 14399 && expiresIn > 0) { // 移除过期时间(exp)和签发时间(iat),保留其他payload - const { exp, iat, ...payload } = decoded; + const payload = { ...decoded }; + delete payload.exp; + delete payload.iat; // 生成新的 token,使用原来的有效时间配置 const newToken = app.jwt.sign( @@ -373,8 +374,7 @@ class MainService extends Service { return result; } - if (_noNeedAuth.indexOf('*') > -1 || _noNeedAuth.indexOf(actionName) > -1) { - } else { + if (!(_noNeedAuth.indexOf('*') > -1 || _noNeedAuth.indexOf(actionName) > -1)) { if (user.auth_end && new Date(user.auth_end) < new Date()) { result.status = 406; result.message = '仓库有效期已过期'; @@ -434,21 +434,130 @@ class MainService extends Service { } /** - * 检查用户是否有API访问权限(只检查类型为api的权限) + * debug 模式下确保 API 权限存在,并绑定到 role_id=2 + * @param {string} apiPath - API路径 + * @param {Object} user - 当前用户 + * @return {Promise<{ensured:boolean, permissionId:number|null}>} 同步结果 + */ + async ensureApiPermissionInDebugMode(apiPath, user = null) { + const { ctx, app } = this; + if (app.config.debug !== true) { + return { + ensured: false, + permissionId: null, + }; + } + + const normalizedPath = String(apiPath || '').trim(); + if (!normalizedPath) { + return { + ensured: false, + permissionId: null, + }; + } + + const template = await ctx.model.Permission.findOne({ + where: { + type: 'api', + }, + attributes: [ + 'component', + 'name', + 'redirect', + 'meta_title', + 'meta_icon', + 'hidden', + 'always_show', + 'parent_id', + 'sort', + 'status', + ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + const [ permission, created ] = await ctx.model.Permission.findOrCreate({ + where: { + path: normalizedPath, + type: 'api', + }, + defaults: { + path: normalizedPath, + type: 'api', + component: template ? template.component : null, + name: template && template.name ? template.name : normalizedPath, + redirect: template ? template.redirect : null, + meta_title: template && template.meta_title ? template.meta_title : `API:${normalizedPath}`, + meta_icon: template ? template.meta_icon : null, + hidden: template ? template.hidden : 0, + always_show: template ? template.always_show : 0, + parent_id: template ? template.parent_id : null, + sort: template ? template.sort : 0, + status: 1, + }, + }); + + if (!permission || !permission.id) { + return { + ensured: false, + permissionId: null, + }; + } + + await ctx.service.systems.auth.rolePermission.bulkAssign(2, [ Number(permission.id) ]); + + // 仅在新建权限时清理当前用户缓存,避免继续使用旧权限快照。 + if (created && user && user.id) { + await ctx.service.systems.auth.user.clearUserCache(user.id); + } + + return { + ensured: true, + permissionId: permission.id, + }; + } + + async hasRole2(employeeId) { + const { ctx } = this; + if (!employeeId) { + return false; + } + + const link = await ctx.model.EmployeeRole.findOne({ + where: { + employee_id: employeeId, + role_id: 2, + }, + attributes: [ 'id' ], + raw: true, + }); + + return !!link; + } + + /** + * 检查用户是否有 API 访问权限(只检查 type=api) * @param {Object} user - 用户信息 * @param {string} apiPath - API路径 - * @return {Promise} + * @return {Promise} 是否有权限 */ async checkApiPermission(user, apiPath) { - const { ctx } = this; - console.log(user); try { // 方法1: 从用户的权限列表中检查(如果已经加载了权限) if (user.permissions && Array.isArray(user.permissions)) { // 用户权限列表中可能包含所有权限,需要过滤出api权限 console.log('user.permissions', user.permissions); - return user.permissions.includes(apiPath); + if (user.permissions.includes('*') || user.permissions.includes(apiPath)) { + return true; + } + + const ensureResult = await this.ensureApiPermissionInDebugMode(apiPath, user); + if (!ensureResult.ensured) { + return false; + } + + return await this.hasRole2(user.employees_id); } return false; } catch (error) { diff --git a/app/service/system.js b/app/service/system.js index 02fd9eb..3b1ccad 100644 --- a/app/service/system.js +++ b/app/service/system.js @@ -23,8 +23,6 @@ class systemService extends Service { // 检查服务是否存在 if (!systemMethods) { throw new Error(`服务 ${servicePath} 不存在`); - }else{ - console.log(`调用服务: ${servicePath}, 方法: ${actionName}`); } let serviceInstance = systemMethods; @@ -45,7 +43,6 @@ class systemService extends Service { const isLog = authPass.isLog; if (authPass.status == 200) { result.data = await serviceInstance[actionName](requestData); - console.log(result.data); result.status = 200; } else { diff --git a/app/service/systemMethods/index.js b/app/service/systemMethods/index.js index 50557c4..8d5c965 100644 --- a/app/service/systemMethods/index.js +++ b/app/service/systemMethods/index.js @@ -54,58 +54,6 @@ class indexService extends MainService { const { ctx } = this; const { language = 'zh-CN' } = data || ctx.query; - try { - // 1. 直接查询表数据看看 - const allTranslations = await ctx.model.I18nTranslation.findAll({ - limit: 5, - raw: true, - }); - console.log('📊 数据库翻译表数据(前5条):', allTranslations); - - const allKeys = await ctx.model.I18nKey.findAll({ - limit: 5, - raw: true, - }); - console.log('📊 数据库键值表数据(前5条):', allKeys); - - // 2. 检查关联查询 - const testQuery = await ctx.model.I18nTranslation.findAll({ - include: [{ - model: ctx.model.I18nKey, - as: 'key', - required: false, // LEFT JOIN - }], - limit: 5, - raw: false, - }); - - console.log('🔍 关联查询结果:', testQuery.length); - testQuery.forEach((item, index) => { - console.log(`结果${index + 1}:`, { - id: item.id, - language: item.language, - translation: item.translation, - hasKey: !!item.key, - keyName: item.key?.key_name, - }); - }); - - // 3. 按语言查询 - const languageQuery = await ctx.model.I18nTranslation.findAll({ - where: { language }, - include: [{ - model: ctx.model.I18nKey, - as: 'key', - }], - raw: false, - }); - - console.log(`🌍 语言 ${language} 的翻译数量:`, languageQuery.length); - - } catch (error) { - console.error('❌ 数据库查询错误:', error); - ctx.logger.error('数据库查询错误:', error); - } try { // 1. 查询当前项目的所有翻译(默认项目为 'wms') const translations = await ctx.model.I18nTranslation.findAll({ diff --git a/app/service/systemMethods/setting/account.js b/app/service/systemMethods/setting/account.js index cf89f05..450d584 100644 --- a/app/service/systemMethods/setting/account.js +++ b/app/service/systemMethods/setting/account.js @@ -6,9 +6,9 @@ class accountService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'getAccountInfo,updatePassword,list,add,delete,update'; + const _noNeedRight = 'getAccountInfo,updatePassword,list,add,delete,update,getBindWechatCode,unbindWechat'; const _noNeedLog = '*'; - const _noNeedAuth = 'getAccountInfo,updatePassword,list,add,delete,update'; + const _noNeedAuth = 'getAccountInfo,updatePassword,list,add,delete,update,getBindWechatCode,unbindWechat'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -29,7 +29,37 @@ class accountService extends MainService { * @param {*} data */ async list(data = {}) { - return this.callSystemAccount('list', data, '获取工号列表失败'); + const { service } = this; + try { + this.prepareWhereContext(data, { + specialFieldMap: { + employee_id: { + field: 'id', + }, + account_id: { + field: 'account_id', + }, + username: { + field: '$account.username$', + }, + phone: { + field: '$account.phone$', + }, + email: { + field: '$account.email$', + }, + quickWhere: { + bucket: 'quick', + }, + }, + }); + const result = await service.systems.setting.account.list(data); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '获取工号列表失败', { + code: Number(error.code) || 500, + }); + } } /** @@ -55,6 +85,22 @@ class accountService extends MainService { async update(data = {}) { return this.callSystemAccount('update', data, '更新工号失败'); } + + /** + * 为其他账号获取微信绑定码。 + * @param {*} data + */ + async getBindWechatCode(data = {}) { + return this.callSystemAccount('getBindWechatCode', data, '获取账号绑定微信码失败'); + } + + /** + * 为其他账号解绑微信。 + * @param {*} data + */ + async unbindWechat(data = {}) { + return this.callSystemAccount('unbindWechat', data, '解绑账号微信失败'); + } } module.exports = accountService; \ No newline at end of file diff --git a/app/service/systemMethods/setting/permission.js b/app/service/systemMethods/setting/permission.js new file mode 100644 index 0000000..c6159ee --- /dev/null +++ b/app/service/systemMethods/setting/permission.js @@ -0,0 +1,60 @@ +'use strict'; + +const MainService = require('../../main'); + +class permissionService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list,add,delete,update'; + const _noNeedLog = '*'; + const _noNeedAuth = 'list,add,delete,update'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + async callSystemPermission(methodName, data, defaultMessage) { + const { service } = this; + try { + const result = await service.systems.setting.permission[methodName](data); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || defaultMessage, { + code: Number(error.code) || 500, + }); + } + } + + /** + * 权限列表。 + * @param {*} data + */ + async list(data = {}) { + return this.callSystemPermission('list', data, '获取权限列表失败'); + } + + /** + * 新增权限。 + * @param {*} data + */ + async add(data = {}) { + return this.callSystemPermission('add', data, '新增权限失败'); + } + + /** + * 删除权限。 + * @param {*} data + */ + async delete(data = {}) { + return this.callSystemPermission('delete', data, '删除权限失败'); + } + + /** + * 更新权限。 + * @param {*} data + */ + async update(data = {}) { + return this.callSystemPermission('update', data, '更新权限失败'); + } +} + +module.exports = permissionService; diff --git a/app/service/systemMethods/setting/role.js b/app/service/systemMethods/setting/role.js new file mode 100644 index 0000000..5128999 --- /dev/null +++ b/app/service/systemMethods/setting/role.js @@ -0,0 +1,68 @@ +'use strict'; + +const MainService = require('../../main'); + +class roleService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list,add,delete,update,permission'; + const _noNeedLog = '*'; + const _noNeedAuth = 'list,add,delete,update,permission'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + async callSystemRole(methodName, data, defaultMessage) { + const { service } = this; + try { + const result = await service.systems.setting.role[methodName](data); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || defaultMessage, { + code: Number(error.code) || 500, + }); + } + } + + /** + * 角色列表。 + * @param {*} data + */ + async list(data = {}) { + return this.callSystemRole('list', data, '获取角色列表失败'); + } + + /** + * 角色权限列表(兼容旧入口)。 + * @param {*} data + */ + async permission(data = {}) { + return this.callSystemRole('permission', data, '获取角色权限列表失败'); + } + + /** + * 新增角色。 + * @param {*} data + */ + async add(data = {}) { + return this.callSystemRole('add', data, '新增角色失败'); + } + + /** + * 删除角色。 + * @param {*} data + */ + async delete(data = {}) { + return this.callSystemRole('delete', data, '删除角色失败'); + } + + /** + * 更新角色。 + * @param {*} data + */ + async update(data = {}) { + return this.callSystemRole('update', data, '更新角色失败'); + } +} + +module.exports = roleService; diff --git a/app/service/systemMethods/setting/store_warehouse.js b/app/service/systemMethods/setting/store_warehouse.js new file mode 100644 index 0000000..c6442c6 --- /dev/null +++ b/app/service/systemMethods/setting/store_warehouse.js @@ -0,0 +1,60 @@ +'use strict'; + +const MainService = require('../../main'); + +class storeWarehouseService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list,sign,unbind,rename'; + const _noNeedLog = '*'; + const _noNeedAuth = 'list,sign,unbind,rename'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + async callSystemStoreWarehouse(methodName, data, defaultMessage) { + const { service } = this; + try { + const result = await service.systems.storeWarehouse[methodName](data); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || defaultMessage, { + code: Number(error.code) || 500, + }); + } + } + + /** + * 仓库-货主签约列表。 + * @param {*} data + */ + async list(data = {}) { + return this.callSystemStoreWarehouse('list', data, '获取签约列表失败'); + } + + /** + * 建立/更新签约关系。 + * @param {*} data + */ + async sign(data = {}) { + return this.callSystemStoreWarehouse('sign', data, '签约失败'); + } + + /** + * 修改当前主体对签约对象的名称/备注。 + * @param {*} data + */ + async rename(data = {}) { + return this.callSystemStoreWarehouse('rename', data, '修改签约名称失败'); + } + + /** + * 解除签约关系。 + * @param {*} data + */ + async unbind(data = {}) { + return this.callSystemStoreWarehouse('unbind', data, '解除签约失败'); + } +} + +module.exports = storeWarehouseService; diff --git a/app/service/systemMethods/storage/receiving.js b/app/service/systemMethods/storage/receiving.js index 839b8ee..ecb384b 100644 --- a/app/service/systemMethods/storage/receiving.js +++ b/app/service/systemMethods/storage/receiving.js @@ -10,9 +10,9 @@ class configService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving'; - const _noNeedLog = 'getReceivingList,get,addDetail,deleteDetail,detailChange'; - const _noNeedAuth = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving'; + const _noNeedRight = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct'; + const _noNeedLog = 'getReceivingList,get,addDetail,deleteDetail,detailChange,bindStore,bindDetailProduct'; + const _noNeedAuth = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -73,6 +73,32 @@ class configService extends MainService { return this.success('创建失败', result); } + /** + * 绑定收货单货主。 + * @param {Object} data 请求体 + * @param {number} data.id 收货单ID + * @param {number} data.store_id 货主ID + * @return {Promise} 统一成功包装响应 + */ + async bindStore(data) { + const { service } = this; + const result = await service.systems.storage.receiving.bindStore(data); + return this.success('ok', result); + } + + /** + * 绑定或改绑收货单明细商品。 + * @param {Object} data 请求体 + * @param {number} data.detail_id 收货单明细ID + * @param {number} data.system_product_id 商品ID + * @return {Promise} 统一成功包装响应 + */ + async bindDetailProduct(data) { + const { service } = this; + const result = await service.systems.storage.receiving.bindDetailProduct(data); + return this.success('ok', result); + } + /** * 添加收货商品(当前依赖底层 addItem 实现)。 * @param {Object} data 请求体 diff --git a/app/service/systemMethods/storeWarehouse.js b/app/service/systemMethods/storeWarehouse.js new file mode 100644 index 0000000..761210a --- /dev/null +++ b/app/service/systemMethods/storeWarehouse.js @@ -0,0 +1,65 @@ +'use strict'; + +const MainService = require('../main'); + +class storeWarehouseAliasService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list,sign,unbind,rename,getPolicyConfig,savePolicyConfig,listQimenConfig,saveQimenConfig,deleteQimenConfig'; + const _noNeedLog = '*'; + const _noNeedAuth = 'list,sign,unbind,rename,getPolicyConfig,savePolicyConfig,listQimenConfig,saveQimenConfig,deleteQimenConfig'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + this.store = this; + } + + async callSystemStoreWarehouse(methodName, data, defaultMessage) { + const { service } = this; + try { + const result = await service.systems.storeWarehouse[methodName](data); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || defaultMessage, { + code: Number(error.code) || 500, + }); + } + } + + async list(data = {}) { + return this.callSystemStoreWarehouse('list', data, '获取签约列表失败'); + } + + async sign(data = {}) { + return this.callSystemStoreWarehouse('sign', data, '签约失败'); + } + + async rename(data = {}) { + return this.callSystemStoreWarehouse('rename', data, '修改签约名称失败'); + } + + async unbind(data = {}) { + return this.callSystemStoreWarehouse('unbind', data, '解除签约失败'); + } + + async getPolicyConfig(data = {}) { + return this.callSystemStoreWarehouse('getPolicyConfig', data, '获取合约策略配置失败'); + } + + async savePolicyConfig(data = {}) { + return this.callSystemStoreWarehouse('savePolicyConfig', data, '保存合约策略配置失败'); + } + + async listQimenConfig(data = {}) { + return this.callSystemStoreWarehouse('listQimenConfig', data, '获取奇门接口配置列表失败'); + } + + async saveQimenConfig(data = {}) { + return this.callSystemStoreWarehouse('saveQimenConfig', data, '保存奇门接口配置失败'); + } + + async deleteQimenConfig(data = {}) { + return this.callSystemStoreWarehouse('deleteQimenConfig', data, '删除奇门接口配置失败'); + } +} + +module.exports = storeWarehouseAliasService; diff --git a/app/service/systemMethods/storeWarehouse/store.js b/app/service/systemMethods/storeWarehouse/store.js new file mode 100644 index 0000000..c012bd3 --- /dev/null +++ b/app/service/systemMethods/storeWarehouse/store.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('../storeWarehouse'); diff --git a/app/service/systemMethods/user.js b/app/service/systemMethods/user.js index efa3bc2..b7b901c 100644 --- a/app/service/systemMethods/user.js +++ b/app/service/systemMethods/user.js @@ -5,9 +5,9 @@ const MainService = require('../main'); class userService extends MainService { constructor(ctx) { super(ctx); - const _noNeedLogin = 'login,loginByCode,register'; + const _noNeedLogin = 'login,loginByCode,register,getLoginWechatCode'; const _noNeedRight = '*'; - const _noNeedLog = 'info,getBindWechatCode'; + const _noNeedLog = 'info,getBindWechatCode,getLoginWechatCode'; const _noNeedAuth = '*'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -25,37 +25,16 @@ class userService extends MainService { async loginByCode(data) { const { service } = this; const code = typeof data?.code === 'string' ? data.code.trim() : ''; + console.log('code', data.code,code); if (!code) { - return this.fail('登录失败:缺少登录码 code', { + return this.fail('1111登录失败:缺少登录码 code', { success: false, data: null, code: 0, message: '缺少登录码 code', }); } - //code先进行base64解码,看是否为json以及json是否有uuid字段,如果有则继续执行否则返回报错 - let decoded; - try { - const buffer = Buffer.from(code, 'base64'); - const decodedStr = buffer.toString('utf-8'); - decoded = JSON.parse(decodedStr); - } catch (err) { - return this.fail('登录失败:无效的登录码格式', { - success: false, - data: null, - code: 0, - message: '无效的登录码格式', - }); - } - if (!decoded || typeof decoded !== 'object' || !decoded.uuid) { - return this.fail('登录失败:登录码缺少必要的uuid字段', { - success: false, - data: null, - code: 0, - message: '登录码缺少必要的uuid字段', - }); - } - const result = await service.systems.auth.user.loginByCode(code); + const result = await service.systems.auth.user.loginByYe4sCode(code); if (result.code) { return this.success('登录成功', result); } @@ -69,6 +48,14 @@ class userService extends MainService { } return this.fail('获取绑定微信码失败:' + result.message, result); } + async getLoginWechatCode(data) { + const { service } = this; + const result = await service.systems.auth.user.getLoginWechatCode(data); + if (result.code) { + return this.success('获取微信登录码成功', result); + } + return this.fail('获取微信登录码失败:' + result.message, result); + } async unbindWechat(data) { const { service } = this; const result = await service.systems.auth.user.unbindWechat(data); diff --git a/app/service/systems/account_platform.js b/app/service/systems/account_platform.js index c0e2627..bcab6b9 100644 --- a/app/service/systems/account_platform.js +++ b/app/service/systems/account_platform.js @@ -57,7 +57,7 @@ class AccountPlatformService extends Service { role_id: roleBinding ? roleBinding.role_id : null, role_name: role ? role.name : '', role_code: role ? role.code : '', - role_permissions: role ? role.permissions : [], + role_permissions: role ? this.ctx.service.systems.auth.rolePermission.toApiPermissionIds(role.permissions) : [], store_id: employee.store_id, store_name: store ? store.name : '', store_code: store ? store.code : '', diff --git a/app/service/systems/auth/role_permission.js b/app/service/systems/auth/role_permission.js index f8880a3..19274cf 100644 --- a/app/service/systems/auth/role_permission.js +++ b/app/service/systems/auth/role_permission.js @@ -3,107 +3,352 @@ const Service = require('egg').Service; class RolePermissionService extends Service { - async bulkAssign(roleId, permissionIds, options = {}) { - const { ctx } = this; + normalizePermissionSet(rawValue) { + if (rawValue === undefined || rawValue === null) { + return { allAccess: false, permissionIds: [] }; + } - if (!permissionIds || permissionIds.length === 0) { + if (Array.isArray(rawValue)) { + const normalizedItems = rawValue.map(item => typeof item === 'string' ? item.trim() : item); + if (normalizedItems.some(item => item === '*')) { + return { allAccess: true, permissionIds: [] }; + } + + const permissionIds = normalizedItems + .map(item => Number(item)) + .filter(item => Number.isFinite(item) && item > 0) + .map(item => Math.floor(item)); + + return { + allAccess: false, + permissionIds: Array.from(new Set(permissionIds)).sort((a, b) => a - b), + }; + } + + if (typeof rawValue === 'number') { + return this.normalizePermissionSet([ rawValue ]); + } + + if (typeof rawValue === 'string') { + const trimmed = rawValue.trim(); + if (!trimmed) { + return { allAccess: false, permissionIds: [] }; + } + if (trimmed === '*') { + return { allAccess: true, permissionIds: [] }; + } + + try { + const parsed = JSON.parse(trimmed); + if (parsed !== rawValue) { + return this.normalizePermissionSet(parsed); + } + } catch (_) { + // ignore JSON parse failure and continue with string splitting. + } + + if (trimmed.includes(',')) { + return this.normalizePermissionSet(trimmed.split(',')); + } + + return this.normalizePermissionSet([ trimmed ]); + } + + return { allAccess: false, permissionIds: [] }; + } + + toApiPermissionIds(rawValue) { + const state = this.normalizePermissionSet(rawValue); + return state.allAccess ? [ '*' ] : state.permissionIds; + } + + serializePermissionSet(rawValue) { + const state = this.normalizePermissionSet(rawValue); + return state.allAccess ? '*' : JSON.stringify(state.permissionIds); + } + + async getPermissionIdsForRoles(roleIds, options = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const normalizedRoleIds = Array.from(new Set((roleIds || []) + .map(roleId => Number(roleId)) + .filter(roleId => Number.isFinite(roleId) && roleId > 0))); + + if (normalizedRoleIds.length === 0) { return []; } - const rolePermissions = permissionIds.map(permissionId => ({ - role_id: roleId, - permission_id: permissionId, - })); - - return await ctx.model.RolePermission.bulkCreate(rolePermissions, { - ignoreDuplicates: true, + const roleRows = await ctx.model.Role.findAll({ + where: { + id: { + [Op.in]: normalizedRoleIds, + }, + ...(options.includeRoleDisabled === true ? {} : { status: 1 }), + }, + attributes: [ 'id', 'permissions' ], + raw: true, transaction: options.transaction, }); - } - async clearRolePermissions(roleId, options = {}) { - const { ctx } = this; + if (!roleRows || roleRows.length === 0) { + return []; + } - return await ctx.model.RolePermission.destroy({ - where: { role_id: roleId }, - transaction: options.transaction, - }); - } + const directPermissionIds = []; + let allAccess = false; - async getRolePermissions(roleId, includePermissionDetails = false) { - const { ctx } = this; + for (const row of roleRows) { + const state = this.normalizePermissionSet(row.permissions); + if (state.allAccess) { + allAccess = true; + break; + } - const options = { - where: { role_id: roleId }, + if (state.permissionIds.length > 0) { + directPermissionIds.push(...state.permissionIds); + } + } + + const permissionWhere = { + status: options.includeDisabled === true ? { [Op.in]: [ 0, 1 ] } : 1, }; - if (includePermissionDetails) { - options.include = [{ - model: ctx.model.Permission, - as: 'permission', - where: { status: 1 }, - required: false, - }]; + if (options.type) { + permissionWhere.type = options.type; } - return await ctx.model.RolePermission.findAll(options); - } + if (allAccess) { + const allPermissions = await ctx.model.Permission.findAll({ + where: permissionWhere, + attributes: [ 'id' ], + raw: true, + transaction: options.transaction, + }); - async hasPermission(roleId, permissionId) { - const { ctx } = this; + return Array.from(new Set(allPermissions + .map(item => Number(item.id)) + .filter(item => Number.isFinite(item) && item > 0))); + } - const rolePermission = await ctx.model.RolePermission.findOne({ + const permissionIds = Array.from(new Set(directPermissionIds + .filter(item => Number.isFinite(item) && item > 0))); + if (permissionIds.length === 0) { + return []; + } + + const permissions = await ctx.model.Permission.findAll({ where: { - role_id: roleId, - permission_id: permissionId, + ...permissionWhere, + id: { + [Op.in]: permissionIds, + }, }, + attributes: [ 'id' ], + raw: true, + transaction: options.transaction, }); - return !!rolePermission; + return Array.from(new Set(permissions + .map(item => Number(item.id)) + .filter(item => Number.isFinite(item) && item > 0))); } - async assignPermissions(roleId, permissionIds, options = {}) { - await this.clearRolePermissions(roleId, options); - - if (permissionIds && permissionIds.length > 0) { - await this.bulkAssign(roleId, permissionIds, options); - } - - return true; - } - - async getPermissionTree(roleId, permissionType = null) { - const { ctx } = this; - - const rolePermissions = await this.getRolePermissions(roleId, true); - const permissionIds = rolePermissions - .map(rp => rp.permission && rp.permission.id) - .filter(Boolean); + 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: permissionIds, - status: 1, + id: { + [Op.in]: permissionIds, + }, + status: options.includeDisabled === true ? { [Op.in]: [ 0, 1 ] } : 1, }; - if (permissionType) { - where.type = permissionType; + 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; + + await ctx.model.Role.update({ + permissions: this.serializePermissionSet(permissionIds), + updated_at: new Date(), + }, { + where: { id: roleId }, + transaction: options.transaction, + }); + + 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, + where: { + id: permissionIds, + status: 1, + ...(permissionType ? { type: permissionType } : {}), + }, order: [[ 'sort', 'ASC' ], [ 'id', 'ASC' ]], }); return ctx.model.Permission.buildPermissionTree(permissions); } - async getPermissionIds(roleId) { - const rolePermissions = await this.getRolePermissions(roleId, false); - return rolePermissions.map(rp => rp.permission_id); + async getPermissionIds(roleId, options = {}) { + return await this.getPermissionIdsForRoles([ roleId ], options); + } + + async removePermissionsFromAllRoles(permissionIds, options = {}) { + const { ctx } = this; + const removeSet = new Set((permissionIds || []) + .map(item => Number(item)) + .filter(item => Number.isFinite(item) && item > 0)); + + if (removeSet.size === 0) { + return 0; + } + + const roleRows = await ctx.model.Role.findAll({ + attributes: [ 'id', 'permissions' ], + transaction: options.transaction, + }); + + let updatedCount = 0; + for (const role of roleRows) { + const state = this.normalizePermissionSet(role.permissions); + if (state.allAccess || state.permissionIds.length === 0) { + continue; + } + + const nextPermissionIds = state.permissionIds.filter(permissionId => !removeSet.has(Number(permissionId))); + if (nextPermissionIds.length === state.permissionIds.length) { + continue; + } + + await role.update({ + permissions: JSON.stringify(nextPermissionIds), + updated_at: new Date(), + }, { + transaction: options.transaction, + }); + updatedCount++; + } + + return updatedCount; } } diff --git a/app/service/systems/auth/user.js b/app/service/systems/auth/user.js index ea88807..4fa7d94 100644 --- a/app/service/systems/auth/user.js +++ b/app/service/systems/auth/user.js @@ -5,10 +5,15 @@ const crypto = require('node:crypto'); const WECHAT_BIND_CACHE_PREFIX = 'user:wechat:bind:'; const WECHAT_BIND_CODE_CACHE_PREFIX = 'user:wechat:bind:code:'; -const WECHAT_BIND_CACHE_TTL_SECONDS = 600; -const WECHAT_BIND_RECHECK_INTERVAL_MS = 5000; +const WECHAT_BIND_SCAN_CACHE_PREFIX = 'user:wechat:bind:scan:'; +const WECHAT_BIND_CACHE_TTL_SECONDS = 60; +const WECHAT_BIND_SCAN_CACHE_TTL_SECONDS = 180; const WECHAT_BIND_EVENT_CHANNEL_PREFIX = 'user:wechat:bind:event:'; const WECHAT_BIND_LONG_POLL_TIMEOUT_MS = 60000; +const WECHAT_LOGIN_CLIENT_CACHE_PREFIX = 'user:wechat:login:client:'; +const WECHAT_LOGIN_CODE_CACHE_PREFIX = 'user:wechat:login:code:'; +const WECHAT_LOGIN_EVENT_CHANNEL_PREFIX = 'user:wechat:login:event:'; +const WECHAT_LOGIN_CACHE_TTL_SECONDS = 60; class UserService extends Service { constructor(ctx) { @@ -33,45 +38,114 @@ class UserService extends Service { return `${WECHAT_BIND_CODE_CACHE_PREFIX}${code}`; } - createWechatBindCode() { - const payload = { - uuid: `${Date.now().toString(36)}-${crypto.randomBytes(8).toString('hex')}`, - }; - return Buffer.from(JSON.stringify(payload), 'utf8').toString('base64'); + getWechatBindScanCacheKey(code) { + return `${WECHAT_BIND_SCAN_CACHE_PREFIX}${code}`; + } + + getWechatLoginClientCacheKey(clientCode) { + return `${WECHAT_LOGIN_CLIENT_CACHE_PREFIX}${clientCode}`; + } + + getWechatLoginCodeCacheKey(code) { + return `${WECHAT_LOGIN_CODE_CACHE_PREFIX}${code}`; + } + + getWechatLoginEventChannel(clientCode) { + return `${WECHAT_LOGIN_EVENT_CHANNEL_PREFIX}${clientCode}`; + } + + createWechatBindCodeCandidate() { + const charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; + let code = ''; + for (let i = 0; i < 6; i++) { + const index = crypto.randomInt(0, charset.length); + code += charset[index]; + } + return code; + } + + async createUniqueSixCode(getCacheKey, maxAttempts = 200) { + for (let attempt = 0; attempt < maxAttempts; attempt++) { + const code = this.createWechatBindCodeCandidate(); + if (!this.parseWechatBindCode(code)) { + continue; + } + + const cacheKey = getCacheKey(code); + const existsState = await this.app.getCacheAsync(cacheKey); + if (!existsState) { + return code; + } + } + + throw new Error('生成登录码失败,请稍后重试'); + } + + async createWechatBindCode(maxAttempts = 200) { + return await this.createUniqueSixCode(this.getWechatBindCodeCacheKey.bind(this), maxAttempts); + } + + async createWechatLoginCode(maxAttempts = 200) { + return await this.createUniqueSixCode(this.getWechatLoginCodeCacheKey.bind(this), maxAttempts); + } + + async createWechatLoginClientCode(maxAttempts = 200) { + return await this.createUniqueSixCode(this.getWechatLoginClientCacheKey.bind(this), maxAttempts); } parseWechatBindCode(code) { - if (!code) { + const normalized = typeof code === 'string' ? code.trim().toUpperCase() : ''; + if (!normalized) { return null; } - try { - const decodedStr = Buffer.from(code, 'base64').toString('utf8'); - const parsed = JSON.parse(decodedStr); - if (!parsed || typeof parsed !== 'object' || !parsed.uuid) { - return null; - } - return parsed; - } catch (error) { + if (!/^[A-Z0-9]{6}$/.test(normalized)) { return null; } + if (!/[A-Z]/.test(normalized) || !/[0-9]/.test(normalized)) { + return null; + } + + return normalized; } formatBindWechatData(state, source = 'db') { - const nextCheckAt = Number(state.next_db_check_at || 0); + const expiresAt = Number(state.expires_at || 0); return { account_id: state.account_id, code: state.code || '', status: state.status || 'pending', is_bound: state.status === 'bound', updated_at: state.updated_at || new Date().toISOString(), - next_db_check_at: nextCheckAt, - next_poll_after_ms: Math.max(0, nextCheckAt - Date.now()), + expires_at: expiresAt > 0 ? expiresAt : null, + expire_after_ms: expiresAt > 0 ? Math.max(0, expiresAt - Date.now()) : 0, + scanned_at: state.scanned_at || null, source, ye4s_user_id: state.ye4s_user_id || null, }; } + formatLoginWechatData(state, source = 'cache') { + const expiresAt = Number(state.expires_at || 0); + return { + client_code: state.client_code || '', + code: state.code || '', + status: state.status || 'pending', + updated_at: state.updated_at || new Date().toISOString(), + expires_at: expiresAt > 0 ? expiresAt : null, + expire_after_ms: expiresAt > 0 ? Math.max(0, expiresAt - Date.now()) : 0, + source, + }; + } + + getRemainingSecondsByExpiresAt(expiresAt, fallbackTtl = WECHAT_BIND_CACHE_TTL_SECONDS) { + const ts = Number(expiresAt); + if (!Number.isFinite(ts) || ts <= 0) { + return fallbackTtl; + } + return Math.max(1, Math.ceil((ts - Date.now()) / 1000)); + } + async setWechatBindCache(cacheKey, state, ttl = WECHAT_BIND_CACHE_TTL_SECONDS) { await this.app.setCacheAsync(cacheKey, state, ttl); } @@ -84,6 +158,38 @@ class UserService extends Service { await this.app.setCacheAsync(codeCacheKey, state, ttl); } + async setWechatBindScanCache(code, state, ttl = WECHAT_BIND_SCAN_CACHE_TTL_SECONDS) { + if (!code) { + return; + } + const scanCacheKey = this.getWechatBindScanCacheKey(code); + await this.app.setCacheAsync(scanCacheKey, state, ttl); + } + + async getWechatBindScanCache(code) { + if (!code) { + return null; + } + const scanCacheKey = this.getWechatBindScanCacheKey(code); + return await this.app.getCacheAsync(scanCacheKey); + } + + async setWechatLoginClientCache(clientCode, state, ttl = WECHAT_LOGIN_CACHE_TTL_SECONDS) { + if (!clientCode) { + return; + } + const clientCacheKey = this.getWechatLoginClientCacheKey(clientCode); + await this.app.setCacheAsync(clientCacheKey, state, ttl); + } + + async setWechatLoginCodeCache(code, state, ttl = WECHAT_LOGIN_CACHE_TTL_SECONDS) { + if (!code) { + return; + } + const codeCacheKey = this.getWechatLoginCodeCacheKey(code); + await this.app.setCacheAsync(codeCacheKey, state, ttl); + } + async findYe4sBindingByAccountId(accountId) { const { ctx } = this; const ye4sClient = ctx.app.mysql.get('ye4s'); @@ -105,27 +211,16 @@ class UserService extends Service { return `${WECHAT_BIND_EVENT_CHANNEL_PREFIX}${accountId}`; } - getWechatLongPollTimeoutMs(rawTimeoutMs) { - const timeoutMs = Number(rawTimeoutMs); - if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) { - return WECHAT_BIND_LONG_POLL_TIMEOUT_MS; + getWechatLongPollTimeoutMs(timeoutMs = WECHAT_BIND_LONG_POLL_TIMEOUT_MS) { + const waitMs = Number(timeoutMs); + if (Number.isFinite(waitMs) && waitMs > 0) { + return Math.floor(waitMs); } - return Math.min(timeoutMs, WECHAT_BIND_LONG_POLL_TIMEOUT_MS); + return WECHAT_BIND_LONG_POLL_TIMEOUT_MS; } - shouldUseWechatBindLongPoll(data = {}, state = null) { - if (!state || state.status === 'bound') { - return false; - } - if (data.forceRefresh) { - return false; - } - if (data.isInit === true || data.init === true || data.firstLoad === true) { - return false; - } - - const explicitEnable = data.longPoll === true || data.waitForChange === true; - return explicitEnable; + shouldUseWechatBindLongPoll(data = {}) { + return data.longPoll === true; } async publishWechatBindEvent(accountId, payload = {}) { @@ -246,62 +341,99 @@ class UserService extends Service { }); } - async refreshWechatBindState(accountId, cachedState = null) { + async refreshWechatBindState(accountId, cachedState = null, options = {}) { const now = Date.now(); const cacheKey = this.getWechatBindCacheKey(accountId); + const forceNewCode = options.forceNewCode === true; const ye4sBinding = await this.findYe4sBindingByAccountId(accountId); if (ye4sBinding) { - const dbCode = typeof ye4sBinding.tmp_code === 'string' ? ye4sBinding.tmp_code.trim() : ''; - const bindState = { + const boundState = { account_id: accountId, status: 'bound', - code: dbCode || (cachedState && cachedState.code) || this.createWechatBindCode(), + code: '', updated_at: new Date().toISOString(), - next_db_check_at: now + WECHAT_BIND_RECHECK_INTERVAL_MS, ye4s_user_id: ye4sBinding.id || null, + expires_at: null, + scanned_at: null, }; - await Promise.all([ - this.setWechatBindCache(cacheKey, bindState, WECHAT_BIND_CACHE_TTL_SECONDS), - this.setWechatBindCodeCache(bindState.code, bindState, WECHAT_BIND_CACHE_TTL_SECONDS), - ]); + await this.setWechatBindCache(cacheKey, boundState, WECHAT_BIND_CACHE_TTL_SECONDS); - const hasChanged = !cachedState || cachedState.status !== 'bound' || cachedState.code !== bindState.code; + const hasChanged = !cachedState || cachedState.status !== 'bound' || Number(cachedState.ye4s_user_id || 0) !== Number(boundState.ye4s_user_id || 0); if (hasChanged) { await this.publishWechatBindEvent(accountId, { status: 'bound', - code: bindState.code, + code: '', source: 'db', }); } return { - state: bindState, + state: boundState, source: 'db', message: '账号已绑定微信', }; } - const code = (cachedState && cachedState.code) || this.createWechatBindCode(); + const cachedCode = cachedState && typeof cachedState.code === 'string' ? cachedState.code.trim().toUpperCase() : ''; + let codeState = null; + if (!forceNewCode && cachedCode && this.parseWechatBindCode(cachedCode)) { + const codeCacheKey = this.getWechatBindCodeCacheKey(cachedCode); + codeState = await this.app.getCacheAsync(codeCacheKey); + } + + const codeAccountId = Number(codeState && codeState.account_id); + const cachedExpiresAt = Number((codeState && codeState.expires_at) || (cachedState && cachedState.expires_at)); + const cachedCodeValid = !forceNewCode && cachedCode && this.parseWechatBindCode(cachedCode) && Number.isFinite(codeAccountId) && codeAccountId === accountId && (Number.isFinite(cachedExpiresAt) ? cachedExpiresAt > now : !!codeState); + + if (cachedCodeValid) { + const scanState = await this.getWechatBindScanCache(cachedCode); + const normalizedStatus = scanState ? 'scanned' : 'pending'; + const state = { + account_id: accountId, + status: normalizedStatus, + code: cachedCode, + updated_at: cachedState.updated_at || new Date().toISOString(), + ye4s_user_id: null, + expires_at: Number.isFinite(cachedExpiresAt) ? cachedExpiresAt : null, + scanned_at: scanState && scanState.scanned_at ? scanState.scanned_at : null, + }; + return { + state, + source: 'cache', + message: normalizedStatus === 'scanned' ? '二维码已被扫码,请继续绑定' : '获取绑定码成功(缓存)', + }; + } + + const nextCode = await this.createWechatBindCode(); + const expiresAt = now + WECHAT_BIND_CACHE_TTL_SECONDS * 1000; const pendingState = { account_id: accountId, status: 'pending', - code, + code: nextCode, updated_at: new Date().toISOString(), - next_db_check_at: now + WECHAT_BIND_RECHECK_INTERVAL_MS, ye4s_user_id: null, + expires_at: expiresAt, + scanned_at: null, }; - await Promise.all([ + const tasks = [ this.setWechatBindCache(cacheKey, pendingState, WECHAT_BIND_CACHE_TTL_SECONDS), - this.setWechatBindCodeCache(pendingState.code, pendingState, WECHAT_BIND_CACHE_TTL_SECONDS), - ]); + this.setWechatBindCodeCache(nextCode, pendingState, WECHAT_BIND_CACHE_TTL_SECONDS), + ]; + + if (cachedCode && cachedCode !== nextCode) { + tasks.push(this.setWechatBindCodeCache(cachedCode, null, 1)); + tasks.push(this.setWechatBindScanCache(cachedCode, null, 1)); + } + + await Promise.all(tasks); return { state: pendingState, - source: code === (cachedState && cachedState.code) ? 'cache-refresh' : 'generated', - message: '账号未绑定,已生成绑定码', + source: forceNewCode ? 'refreshed' : 'generated', + message: forceNewCode ? '长轮询超时,已刷新绑定码' : '账号未绑定,已生成绑定码', }; } @@ -361,75 +493,83 @@ class UserService extends Service { } /** - * 登录码登录:使用 ye4s_user.tmp_code 绑定的 wms_account_id 登录 - * @param {string} code 登录码(ye4s_user.tmp_code) + * 登录码登录:使用Ye4s登录码进行登录 + * @param {string} code 登录码(WECHAT_LOGIN_CODE) * @return {Object} 登录结果 */ - async loginByCode(code) { + async loginByYe4sCode(code) { const { ctx, app } = this; try { - const normalizedCode = typeof code === 'string' ? code.trim() : ''; - if (!normalizedCode) { + const rawCode = typeof code === 'string' ? code.trim() : ''; + if (!rawCode) { return { success: false, data: null, code: 0, - message: '缺少登录码 code', + message: '缺少或无效的登录码 code', + }; + } + + const candidateSet = new Set([ rawCode ]); + try { + const decoded = Buffer.from(rawCode, 'base64').toString('utf8').trim(); + if (decoded) { + candidateSet.add(decoded); + if (decoded.startsWith('{') && decoded.endsWith('}')) { + const parsed = JSON.parse(decoded); + const possibleCode = [ parsed && parsed.uuid, parsed && parsed.tmp_code, parsed && parsed.code ] + .map(item => (typeof item === 'string' ? item.trim() : '')) + .filter(Boolean); + for (const item of possibleCode) { + candidateSet.add(item); + } + } + } + } catch (decodeErr) { + // 非 base64/JSON 登录码时忽略解码失败,继续使用原始 code。 + } + + const codeCandidates = Array.from(candidateSet).filter(item => typeof item === 'string' && item.length > 0); + if (codeCandidates.length === 0) { + return { + success: false, + data: null, + code: 0, + message: '缺少或无效的登录码 code', }; } const ye4sClient = ctx.app.mysql.get('ye4s'); - const ye4sUser = await ye4sClient.get('ye4s_user', { - tmp_code: normalizedCode, + const rows = await ye4sClient.select('ye4s_user', { + where: { + tmp_code: codeCandidates, + }, + columns: [ 'id', 'tmp_code', 'wms_account_id' ], + orders: [[ 'id', 'DESC' ]], + limit: 1, }); - if (!ye4sUser) { + if (!rows || rows.length === 0) { return { success: false, data: null, code: 0, - message: '登录码不存在', + message: '登录码不存在或已过期', }; } - const wmsAccountId = Number(ye4sUser.wms_account_id); - if (!Number.isFinite(wmsAccountId) || wmsAccountId <= 0) { + const ye4sUserId = Number(rows[0].id); + if (!Number.isFinite(ye4sUserId) || ye4sUserId <= 0) { return { success: false, data: null, code: 0, - message: '该登录码未绑定WMS账号', + message: '登录码对应用户无效', }; } - const user = await ctx.model.Account.findOne({ - where: { id: wmsAccountId }, - }); - - if (!user) { - return { - success: false, - data: null, - code: 0, - message: '绑定的WMS账号不存在', - }; - } - - try { - this.checkUserStatus(user); - } catch (statusError) { - app.coreLogger.warn(`登录码登录失败: 账号状态异常 [${user.id}] - ${statusError.message}`); - return { - success: false, - data: null, - code: 0, - message: '绑定账号状态异常', - }; - } - - await this.updateLastLoginTime(user.id); - return this.buildLoginResult(user); + return await this.loginByYe4sUserId(ye4sUserId); } catch (error) { app.coreLogger.error(`登录码登录异常: ${error.message}`); return { @@ -441,28 +581,475 @@ class UserService extends Service { } } + async waitForLoginCodeRefresh(timeoutMs = WECHAT_BIND_LONG_POLL_TIMEOUT_MS) { + const waitMs = this.getWechatLongPollTimeoutMs(timeoutMs); + await new Promise(resolve => { + setTimeout(resolve, waitMs); + }); + } + + isTransientWechatLoginError(error) { + if (!error) { + return false; + } + const code = typeof error.code === 'string' ? error.code : ''; + const message = typeof error.message === 'string' ? error.message.toLowerCase() : ''; + const transientCodes = new Set([ 'ECONNRESET', 'ETIMEDOUT', 'EPIPE', 'PROTOCOL_CONNECTION_LOST', 'ECONNREFUSED' ]); + if (transientCodes.has(code)) { + return true; + } + return message.includes('econnreset') || message.includes('read econnreset') || message.includes('connection lost') || message.includes('timeout'); + } + + extractYe4sUserIdFromLoginEvent(eventData) { + if (!eventData) { + return null; + } + + if (typeof eventData === 'number' || typeof eventData === 'string') { + const id = Number(eventData); + return Number.isFinite(id) && id > 0 ? id : null; + } + + if (typeof eventData !== 'object') { + return null; + } + + const rawId = eventData.ye4s_user_id ?? eventData.ye4sUserId ?? eventData.user_id ?? eventData.userId ?? eventData.value; + const ye4sUserId = Number(rawId); + return Number.isFinite(ye4sUserId) && ye4sUserId > 0 ? ye4sUserId : null; + } + + async waitForWechatLoginEvent(clientCode, timeoutMs = WECHAT_BIND_LONG_POLL_TIMEOUT_MS) { + const { app } = this; + const normalizedClientCode = this.parseWechatBindCode(clientCode); + const cacheRedis = app.redis && app.redis.get ? app.redis.get('cache') : null; + if (!cacheRedis || !normalizedClientCode || typeof cacheRedis.duplicate !== 'function') { + return { + timed_out: true, + reason: 'redis_not_available', + event: null, + }; + } + + const channel = this.getWechatLoginEventChannel(normalizedClientCode); + const waitMs = this.getWechatLongPollTimeoutMs(timeoutMs); + const subscriber = cacheRedis.duplicate(); + + return await new Promise(resolve => { + let settled = false; + let timer = null; + + const cleanup = () => { + subscriber.removeListener('message', onMessage); + subscriber.removeListener('error', onError); + Promise.resolve(subscriber.unsubscribe(channel)).catch(() => null).finally(() => { + if (typeof subscriber.quit === 'function') { + Promise.resolve(subscriber.quit()).catch(() => { + if (typeof subscriber.disconnect === 'function') { + subscriber.disconnect(); + } + }); + return; + } + if (typeof subscriber.disconnect === 'function') { + subscriber.disconnect(); + } + }); + }; + + const finalize = result => { + if (settled) { + return; + } + settled = true; + if (timer) { + clearTimeout(timer); + } + cleanup(); + resolve(result); + }; + + const onMessage = (messageChannel, message) => { + if (messageChannel !== channel) { + return; + } + let eventData = null; + try { + eventData = message ? JSON.parse(message) : null; + } catch (error) { + eventData = message; + } + const ye4sUserId = this.extractYe4sUserIdFromLoginEvent(eventData); + finalize({ + timed_out: false, + reason: 'event', + event: eventData, + ye4s_user_id: ye4sUserId, + }); + }; + + const onError = error => { + app.coreLogger.warn(`订阅微信登录事件失败: ${error.message}`); + finalize({ + timed_out: true, + reason: 'subscribe_error', + event: null, + }); + }; + + timer = setTimeout(() => { + finalize({ + timed_out: true, + reason: 'timeout', + event: null, + }); + }, waitMs); + + subscriber.on('message', onMessage); + subscriber.on('error', onError); + + Promise.resolve(subscriber.subscribe(channel)).catch(error => { + app.coreLogger.warn(`订阅微信登录频道失败: ${error.message}`); + finalize({ + timed_out: true, + reason: 'subscribe_failed', + event: null, + }); + }); + }); + } + + async loginByYe4sUserId(ye4sUserId) { + const { ctx, app } = this; + + const normalizedYe4sUserId = Number(ye4sUserId); + if (!Number.isFinite(normalizedYe4sUserId) || normalizedYe4sUserId <= 0) { + return { + success: false, + code: 0, + data: null, + message: '登录事件缺少有效的 ye4s_user_id', + }; + } + + const maxAttempts = 2; + for (let attempt = 1; attempt <= maxAttempts; attempt++) { + try { + const ye4sClient = ctx.app.mysql.get('ye4s'); + const ye4sUser = await ye4sClient.get('ye4s_user', { id: normalizedYe4sUserId }); + if (!ye4sUser) { + return { + success: false, + code: 0, + data: null, + message: 'ye4s 用户不存在', + }; + } + + const wmsAccountId = Number(ye4sUser.wms_account_id); + if (!Number.isFinite(wmsAccountId) || wmsAccountId <= 0) { + return { + success: false, + code: 0, + data: null, + message: '该 ye4s 用户未绑定WMS账号', + }; + } + + const user = await ctx.model.Account.findOne({ + where: { id: wmsAccountId }, + }); + + if (!user) { + return { + success: false, + code: 0, + data: null, + message: '绑定的WMS账号不存在', + }; + } + + try { + this.checkUserStatus(user); + } catch (statusError) { + app.coreLogger.warn(`微信事件登录失败: 账号状态异常 [${user.id}] - ${statusError.message}`); + return { + success: false, + code: 0, + data: null, + message: '绑定账号状态异常', + }; + } + + await this.updateLastLoginTime(user.id); + const loginResult = await this.buildLoginResult(user, { includeUser: false }); + return loginResult; + } catch (error) { + const isTransient = this.isTransientWechatLoginError(error); + if (isTransient && attempt < maxAttempts) { + app.coreLogger.warn(`微信事件登录异常,准备重试(${attempt}/${maxAttempts}): ${error.message}`); + await this.waitForLoginCodeRefresh(200); + continue; + } + + app.coreLogger.error(`微信事件登录异常: ${error.message}`); + return { + success: false, + code: 0, + data: null, + message: '登录失败,请稍后重试', + }; + } + } + + return { + success: false, + code: 0, + data: null, + message: '登录失败,请稍后重试', + }; + } + + async tryBuildWechatLoginTokenFromState(clientCode, state) { + const eventYe4sUserId = this.extractYe4sUserIdFromLoginEvent(state); + if (!Number.isFinite(Number(eventYe4sUserId)) || Number(eventYe4sUserId) <= 0) { + return null; + } + + const loginResult = await this.loginByYe4sUserId(eventYe4sUserId); + if (!loginResult || !loginResult.success || !loginResult.data || !loginResult.data.token) { + return { + success: false, + code: 0, + data: null, + message: loginResult && loginResult.message ? loginResult.message : '登录事件处理失败', + }; + } + + const cleanupCode = state && typeof state.code === 'string' ? state.code.trim().toUpperCase() : ''; + await Promise.all([ + this.setWechatLoginClientCache(clientCode, null, 1), + cleanupCode ? this.setWechatLoginCodeCache(cleanupCode, null, 1) : Promise.resolve(), + ]); + + return { + success: true, + code: 200, + data: { + client_code: clientCode, + status: 'authorized', + source: 'event', + ye4s_user_id: Number(eventYe4sUserId), + loginToken: loginResult.data.token, + }, + message: '已收到登录事件并签发登录令牌', + }; + } + + async refreshWechatLoginState(clientCode, cachedState = null, options = {}) { + const now = Date.now(); + const forceNewCode = options.forceNewCode === true; + const normalizedClientCode = this.parseWechatBindCode(clientCode); + + if (!normalizedClientCode) { + throw new Error('无效的客户端编码格式'); + } + + const cachedCode = cachedState && typeof cachedState.code === 'string' ? cachedState.code.trim().toUpperCase() : ''; + const cachedExpiresAt = Number(cachedState && cachedState.expires_at); + const cachedCodeValid = !forceNewCode && cachedCode && this.parseWechatBindCode(cachedCode) && Number.isFinite(cachedExpiresAt) && cachedExpiresAt > now; + + if (cachedCodeValid) { + return { + state: { + client_code: normalizedClientCode, + code: cachedCode, + status: 'pending', + updated_at: cachedState.updated_at || new Date().toISOString(), + expires_at: cachedExpiresAt, + }, + source: 'cache', + message: `客户端编码 ${normalizedClientCode} 已命中缓存登录码`, + }; + } + + const nextCode = await this.createWechatLoginCode(); + const expiresAt = now + WECHAT_LOGIN_CACHE_TTL_SECONDS * 1000; + const loginState = { + client_code: normalizedClientCode, + code: nextCode, + status: 'pending', + updated_at: new Date().toISOString(), + expires_at: expiresAt, + }; + + const tasks = [ + this.setWechatLoginClientCache(normalizedClientCode, loginState, WECHAT_LOGIN_CACHE_TTL_SECONDS), + this.setWechatLoginCodeCache(nextCode, loginState, WECHAT_LOGIN_CACHE_TTL_SECONDS), + ]; + + if (cachedCode && cachedCode !== nextCode) { + tasks.push(this.setWechatLoginCodeCache(cachedCode, null, 1)); + } + + await Promise.all(tasks); + + return { + state: loginState, + source: forceNewCode ? 'refreshed' : 'generated', + message: forceNewCode ? + `客户端编码 ${normalizedClientCode} 长轮询结束,已刷新登录码` : + `客户端编码 ${normalizedClientCode} 已生成登录码`, + }; + } + + /** + * 获取微信扫码登录码 + * @param {Object} data + * @return {Object} + */ + async getLoginWechatCode(data = {}) { + const { app } = this; + try { + const rawClientCode = typeof data.clientCode === 'string' ? data.clientCode : (typeof data.client_code === 'string' ? data.client_code : ''); + const hasInputClientCode = !!rawClientCode && rawClientCode.trim().length > 0; + + let clientCode = ''; + let shouldWaitRefresh = false; + let cachedState = null; + + if (hasInputClientCode) { + const normalizedClientCode = this.parseWechatBindCode(rawClientCode); + if (!normalizedClientCode) { + return { + success: false, + code: 0, + data: null, + message: '无效的客户端编码格式', + }; + } + + const inputClientCacheKey = this.getWechatLoginClientCacheKey(normalizedClientCode); + try { + cachedState = await this.app.getCacheAsync(inputClientCacheKey); + } catch (cacheErr) { + app.coreLogger.warn(`读取微信登录码缓存失败: ${cacheErr.message}`); + } + + // 传入 clientCode 但缓存不存在时,按空值处理,重新分配新的客户端编码。 + if (cachedState) { + clientCode = normalizedClientCode; + shouldWaitRefresh = true; + } else { + clientCode = await this.createWechatLoginClientCode(); + } + } else { + clientCode = await this.createWechatLoginClientCode(); + } + + const clientCacheKey = this.getWechatLoginClientCacheKey(clientCode); + if (!cachedState) { + try { + cachedState = await this.app.getCacheAsync(clientCacheKey); + } catch (cacheErr) { + app.coreLogger.warn(`读取微信登录码缓存失败: ${cacheErr.message}`); + } + } + + // 若外部已将 ye4s_user_id 写入 clientCode 对应缓存,直接登录并返回,不再等待长轮询。 + if (hasInputClientCode && cachedState) { + const immediateLoginResult = await this.tryBuildWechatLoginTokenFromState(clientCode, cachedState); + if (immediateLoginResult && immediateLoginResult.success) { + return immediateLoginResult; + } + if (immediateLoginResult && immediateLoginResult.success === false) { + app.coreLogger.warn(`微信登录缓存态直登失败,继续轮询: ${immediateLoginResult.message}`); + } + } + + if (shouldWaitRefresh) { + const waitResult = await this.waitForWechatLoginEvent(clientCode, this.getWechatLongPollTimeoutMs()); + const eventYe4sUserId = Number(waitResult && waitResult.ye4s_user_id); + if (!waitResult.timed_out && Number.isFinite(eventYe4sUserId) && eventYe4sUserId > 0) { + const eventState = { + ...(cachedState || {}), + ye4s_user_id: eventYe4sUserId, + }; + const loginResponse = await this.tryBuildWechatLoginTokenFromState(clientCode, eventState); + if (loginResponse && loginResponse.success) { + return loginResponse; + } + app.coreLogger.warn(`微信事件登录未成功,降级为刷新登录码: ${loginResponse && loginResponse.message ? loginResponse.message : 'unknown_error'}`); + } + + try { + cachedState = await this.app.getCacheAsync(clientCacheKey); + } catch (cacheErr) { + app.coreLogger.warn(`读取微信登录码缓存失败: ${cacheErr.message}`); + } + + const refreshed = await this.refreshWechatLoginState(clientCode, cachedState, { + forceNewCode: true, + }); + + return { + success: true, + code: 200, + data: this.formatLoginWechatData(refreshed.state, refreshed.source), + message: refreshed.message, + }; + } + + const generated = await this.refreshWechatLoginState(clientCode, cachedState, { + forceNewCode: false, + }); + + return { + success: true, + code: 200, + data: this.formatLoginWechatData(generated.state, generated.source), + message: generated.message, + }; + } catch (error) { + app.coreLogger.error(`获取微信登录码失败: ${error.message}`); + return { + success: false, + code: 0, + data: null, + message: '获取微信登录码失败,请稍后重试', + }; + } + } + /** * 获取微信绑定码(缓存优先,低频复查DB,适配轮询) * @param {Object} data * @return {Object} */ async getBindWechatCode(data = {}) { + const accountId = this.getCurrentAccountId(); + return await this.getBindWechatCodeByAccountId(accountId, data, { + missingAccountMessage: '未识别到登录账号,无法生成绑定码', + }); + } + + async getBindWechatCodeByAccountId(accountId, data = {}, options = {}) { const { app } = this; try { - const accountId = this.getCurrentAccountId(); - if (!accountId) { + const normalizedAccountId = Number(accountId); + if (!Number.isFinite(normalizedAccountId) || normalizedAccountId <= 0) { return { success: false, code: 0, data: null, - message: '未识别到登录账号,无法生成绑定码', + message: options.missingAccountMessage || '未识别到目标账号,无法生成绑定码', }; } - const cacheKey = this.getWechatBindCacheKey(accountId); - const forceRefresh = !!data.forceRefresh; - const now = Date.now(); - const waitTimeoutMs = this.getWechatLongPollTimeoutMs(data.waitTimeoutMs); + const cacheKey = this.getWechatBindCacheKey(normalizedAccountId); + const useLongPoll = this.shouldUseWechatBindLongPoll(data); + const waitTimeoutMs = this.getWechatLongPollTimeoutMs(); let cachedState = null; try { @@ -471,57 +1058,44 @@ class UserService extends Service { app.coreLogger.warn(`读取微信绑定缓存失败: ${cacheErr.message}`); } - if (cachedState && !forceRefresh) { - const nextCheckAt = Number(cachedState.next_db_check_at || 0); - let refreshedState = null; - if (nextCheckAt <= now) { - refreshedState = await this.refreshWechatBindState(accountId, cachedState); - cachedState = refreshedState.state; - } - - if (this.shouldUseWechatBindLongPoll(data, cachedState)) { - const waitResult = await this.waitForWechatBindEvent(accountId, waitTimeoutMs); - try { - cachedState = await this.app.getCacheAsync(cacheKey); - } catch (cacheErr) { - app.coreLogger.warn(`读取微信绑定缓存失败: ${cacheErr.message}`); - } - - const nextState = await this.refreshWechatBindState(accountId, cachedState); - const timeoutMessage = waitResult.timed_out ? '等待绑定状态变化超时,返回当前状态' : nextState.message; - - return { - success: true, - code: 200, - data: this.formatBindWechatData(nextState.state, nextState.source), - message: timeoutMessage, - }; - } - - if (refreshedState) { - return { - success: true, - code: 200, - data: this.formatBindWechatData(refreshedState.state, refreshedState.source), - message: refreshedState.message, - }; - } + const refreshed = await this.refreshWechatBindState(normalizedAccountId, cachedState, { + forceNewCode: false, + }); + if (refreshed.state.status === 'bound' || !useLongPoll) { return { success: true, code: 200, - data: this.formatBindWechatData(cachedState, 'cache'), - message: '获取绑定码成功(缓存)', + data: this.formatBindWechatData(refreshed.state, refreshed.source), + message: refreshed.message, }; } - const refreshed = await this.refreshWechatBindState(accountId, cachedState); + const waitResult = await this.waitForWechatBindEvent(normalizedAccountId, waitTimeoutMs); + try { + cachedState = await this.app.getCacheAsync(cacheKey); + } catch (cacheErr) { + app.coreLogger.warn(`读取微信绑定缓存失败: ${cacheErr.message}`); + } + + const nextState = await this.refreshWechatBindState(normalizedAccountId, cachedState, { + forceNewCode: waitResult.timed_out, + }); + + if (waitResult.timed_out) { + return { + success: true, + code: 200, + data: this.formatBindWechatData(nextState.state, nextState.source), + message: '长轮询结束未检测到状态变化,已刷新绑定码', + }; + } return { success: true, code: 200, - data: this.formatBindWechatData(refreshed.state, refreshed.source), - message: refreshed.message, + data: this.formatBindWechatData(nextState.state, nextState.source), + message: nextState.message, }; } catch (error) { app.coreLogger.error(`获取微信绑定码失败: ${error.message}`); @@ -542,8 +1116,19 @@ class UserService extends Service { async getUserByTempCode(data = {}) { const { ctx, app } = this; try { - const code = typeof data.code === 'string' ? data.code.trim() : ''; - if (!code) { + const loadAccountRealName = async accountId => { + const account = await ctx.model.Account.findOne({ + where: { + id: accountId, + }, + attributes: [ 'id', 'real_name' ], + raw: true, + }); + return account && account.real_name ? account.real_name : ''; + }; + + const rawCode = typeof data.code === 'string' ? data.code.trim() : ''; + if (!rawCode) { return { success: false, code: 0, @@ -552,7 +1137,8 @@ class UserService extends Service { }; } - if (!this.parseWechatBindCode(code)) { + const code = this.parseWechatBindCode(rawCode); + if (!code) { return { success: false, code: 0, @@ -570,65 +1156,60 @@ class UserService extends Service { } const cachedAccountId = Number(codeState && codeState.account_id); - if (Number.isFinite(cachedAccountId) && cachedAccountId > 0) { + if (!Number.isFinite(cachedAccountId) || cachedAccountId <= 0) { return { - success: true, - code: 200, - data: { - account_id: cachedAccountId, - code, - status: codeState.status || 'pending', - source: 'cache', - updated_at: codeState.updated_at || new Date().toISOString(), - }, - message: '获取账号成功', + success: false, + code: 0, + data: null, + message: '绑定码不存在或已过期', }; } - const ye4sClient = ctx.app.mysql.get('ye4s'); - const ye4sUser = await ye4sClient.get('ye4s_user', { - tmp_code: code, + const realName = await loadAccountRealName(cachedAccountId); + const scanState = { + account_id: cachedAccountId, + code, + status: 'scanned', + scanned_at: new Date().toISOString(), + source: 'gateway-scan', + }; + + const codeExpiresAt = Number(codeState && codeState.expires_at); + const scannedBindState = { + account_id: cachedAccountId, + code, + status: 'scanned', + scanned_at: scanState.scanned_at, + updated_at: scanState.scanned_at, + ye4s_user_id: null, + expires_at: Number.isFinite(codeExpiresAt) ? codeExpiresAt : null, + }; + const bindCacheTtl = this.getRemainingSecondsByExpiresAt(codeExpiresAt, WECHAT_BIND_CACHE_TTL_SECONDS); + + await Promise.all([ + this.setWechatBindScanCache(code, scanState, WECHAT_BIND_SCAN_CACHE_TTL_SECONDS), + this.setWechatBindCache(this.getWechatBindCacheKey(cachedAccountId), scannedBindState, bindCacheTtl), + ]); + await this.publishWechatBindEvent(cachedAccountId, { + status: 'scanned', + code, + scanned_at: scanState.scanned_at, + source: 'gateway-scan', }); - const wmsAccountId = Number(ye4sUser && ye4sUser.wms_account_id); - if (Number.isFinite(wmsAccountId) && wmsAccountId > 0) { - const boundState = { - account_id: wmsAccountId, - status: 'bound', - code, - updated_at: new Date().toISOString(), - next_db_check_at: Date.now() + WECHAT_BIND_RECHECK_INTERVAL_MS, - ye4s_user_id: ye4sUser.id || null, - }; - await Promise.all([ - this.setWechatBindCodeCache(code, boundState, WECHAT_BIND_CACHE_TTL_SECONDS), - this.setWechatBindCache(this.getWechatBindCacheKey(wmsAccountId), boundState, WECHAT_BIND_CACHE_TTL_SECONDS), - ]); - await this.publishWechatBindEvent(wmsAccountId, { - status: 'bound', - code, - source: 'api', - }); - - return { - success: true, - code: 200, - data: { - account_id: wmsAccountId, - code, - status: 'bound', - source: 'db', - updated_at: boundState.updated_at, - }, - message: '获取账号成功', - }; - } - return { - success: false, - code: 0, - data: null, - message: '绑定码不存在或已过期', + success: true, + code: 200, + data: { + account_id: cachedAccountId, + real_name: realName, + code, + status: 'scanned', + source: 'scan-cache', + scanned_at: scanState.scanned_at, + updated_at: codeState && codeState.updated_at ? codeState.updated_at : scanState.scanned_at, + }, + message: '扫码状态已记录', }; } catch (error) { app.coreLogger.error(`根据绑定码获取账号失败: ${error.message}`); @@ -649,11 +1230,11 @@ class UserService extends Service { async bindAccountByTempCode(data = {}) { const { ctx, app } = this; try { - const code = typeof data.code === 'string' ? data.code.trim() : ''; + const rawCode = typeof data.code === 'string' ? data.code.trim() : ''; const rawYe4sUserId = data.ye4s_user_id ?? data.ye4sUserId; const ye4sUserId = Number(rawYe4sUserId); - if (!code) { + if (!rawCode) { return { success: false, code: 0, @@ -662,7 +1243,8 @@ class UserService extends Service { }; } - if (!this.parseWechatBindCode(code)) { + const code = this.parseWechatBindCode(rawCode); + if (!code) { return { success: false, code: 0, @@ -680,23 +1262,14 @@ class UserService extends Service { }; } - const userResult = await this.getUserByTempCode({ code }); - if (!userResult || !userResult.success) { - return { - success: false, - code: 0, - data: null, - message: userResult && userResult.message ? userResult.message : '绑定码不存在或已过期', - }; - } - - const accountId = Number(userResult.data && userResult.data.account_id); + const scanState = await this.getWechatBindScanCache(code); + const accountId = Number(scanState && scanState.account_id); if (!Number.isFinite(accountId) || accountId <= 0) { return { success: false, code: 0, data: null, - message: '绑定码未匹配到有效账号', + message: '未检测到扫码记录或扫码状态已过期,请重新扫码', }; } @@ -714,26 +1287,32 @@ class UserService extends Service { const updateRet = await ye4sClient.update('ye4s_user', { id: ye4sUserId, wms_account_id: accountId, - tmp_code: code, }); const boundState = { account_id: accountId, status: 'bound', - code, + code: '', updated_at: new Date().toISOString(), - next_db_check_at: Date.now() + WECHAT_BIND_RECHECK_INTERVAL_MS, ye4s_user_id: ye4sUserId, + expires_at: null, + scanned_at: scanState && scanState.scanned_at ? scanState.scanned_at : null, }; await Promise.all([ - this.setWechatBindCodeCache(code, boundState, WECHAT_BIND_CACHE_TTL_SECONDS), this.setWechatBindCache(this.getWechatBindCacheKey(accountId), boundState, WECHAT_BIND_CACHE_TTL_SECONDS), + this.setWechatBindCodeCache(code, null, 1), + this.setWechatBindScanCache(code, { + ...scanState, + status: 'bound', + ye4s_user_id: ye4sUserId, + bound_at: boundState.updated_at, + }, WECHAT_BIND_SCAN_CACHE_TTL_SECONDS), ]); await this.publishWechatBindEvent(accountId, { status: 'bound', - code, + code: '', source: 'gateway-bind', }); @@ -767,22 +1346,29 @@ class UserService extends Service { * @return {Object} */ async unbindWechat() { + const accountId = this.getCurrentAccountId(); + return await this.unbindWechatByAccountId(accountId, { + missingAccountMessage: '未识别到登录账号,无法解绑', + }); + } + + async unbindWechatByAccountId(accountId, options = {}) { const { ctx, app } = this; try { - const accountId = this.getCurrentAccountId(); - if (!accountId) { + const normalizedAccountId = Number(accountId); + if (!Number.isFinite(normalizedAccountId) || normalizedAccountId <= 0) { return { success: false, code: 0, data: null, - message: '未识别到登录账号,无法解绑', + message: options.missingAccountMessage || '未识别到目标账号,无法解绑', }; } const ye4sClient = ctx.app.mysql.get('ye4s'); const bindRows = await ye4sClient.select('ye4s_user', { where: { - wms_account_id: accountId, + wms_account_id: normalizedAccountId, }, columns: [ 'id', 'tmp_code', 'wms_account_id' ], orders: [[ 'id', 'desc' ]], @@ -791,17 +1377,6 @@ class UserService extends Service { let affectedRows = 0; for (const row of bindRows) { - const rowCode = typeof row.tmp_code === 'string' ? row.tmp_code.trim() : ''; - if (rowCode) { - await this.setWechatBindCodeCache(rowCode, { - account_id: accountId, - status: 'unbound', - code: rowCode, - updated_at: new Date().toISOString(), - next_db_check_at: Date.now() + WECHAT_BIND_RECHECK_INTERVAL_MS, - ye4s_user_id: row.id || null, - }, WECHAT_BIND_CACHE_TTL_SECONDS); - } try { const ret = await ye4sClient.update('ye4s_user', { id: row.id, @@ -809,7 +1384,6 @@ class UserService extends Service { }); affectedRows += Number(ret && ret.affectedRows ? ret.affectedRows : 0); } catch (err) { - // 兼容不允许 NULL 的旧表结构 const ret = await ye4sClient.update('ye4s_user', { id: row.id, wms_account_id: 0, @@ -818,20 +1392,9 @@ class UserService extends Service { } } - const cacheKey = this.getWechatBindCacheKey(accountId); - const cachedState = await this.app.getCacheAsync(cacheKey); - if (cachedState && cachedState.code) { - await this.setWechatBindCodeCache(cachedState.code, { - account_id: accountId, - status: 'unbound', - code: cachedState.code, - updated_at: new Date().toISOString(), - next_db_check_at: Date.now() + WECHAT_BIND_RECHECK_INTERVAL_MS, - ye4s_user_id: cachedState.ye4s_user_id || null, - }, WECHAT_BIND_CACHE_TTL_SECONDS); - } + const cacheKey = this.getWechatBindCacheKey(normalizedAccountId); await this.setWechatBindCache(cacheKey, null, 1); - await this.publishWechatBindEvent(accountId, { + await this.publishWechatBindEvent(normalizedAccountId, { status: 'unbound', source: 'unbind', }); @@ -840,7 +1403,7 @@ class UserService extends Service { success: true, code: 200, data: { - account_id: accountId, + account_id: normalizedAccountId, status: 'unbound', matched_rows: bindRows.length, affected_rows: affectedRows, @@ -1426,20 +1989,10 @@ class UserService extends Service { return []; } - // 2. 获取角色的权限 - const rolePermissions = await ctx.model.RolePermission.findAll({ - where: { - role_id: { - [Op.in]: roleIds, - }, - }, - raw: true, + // 2. 获取角色的权限(来源:wms_role.permissions;兼容空字段回退旧表) + const permissionIds = await ctx.service.systems.auth.rolePermission.getPermissionIdsForRoles(roleIds, { + includeDisabled: false, }); - if (!rolePermissions || rolePermissions.length === 0) { - return []; - } - - const permissionIds = [ ...new Set(rolePermissions.map(item => item.permission_id).filter(Boolean)) ]; if (permissionIds.length === 0) { return []; } @@ -1512,20 +2065,10 @@ class UserService extends Service { return []; } - // 2. 获取角色的权限 - const rolePermissions = await ctx.model.RolePermission.findAll({ - where: { - role_id: { - [Op.in]: roleIds, - }, - }, - raw: true, + // 2. 获取角色的权限(来源:wms_role.permissions;兼容空字段回退旧表) + const permissionIds = await ctx.service.systems.auth.rolePermission.getPermissionIdsForRoles(roleIds, { + includeDisabled: false, }); - if (!rolePermissions || rolePermissions.length === 0) { - return []; - } - - const permissionIds = [ ...new Set(rolePermissions.map(item => item.permission_id).filter(Boolean)) ]; if (permissionIds.length === 0) { return []; } diff --git a/app/service/systems/excel.js b/app/service/systems/excel.js new file mode 100644 index 0000000..88f1adf --- /dev/null +++ b/app/service/systems/excel.js @@ -0,0 +1,744 @@ +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const { Readable } = require('stream'); +const Service = require('egg').Service; +const XLSX = require('xlsx'); +const ExcelJS = require('exceljs'); + +const CONTENT_TYPE_MAP = { + xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + xls: 'application/vnd.ms-excel', + csv: 'text/csv; charset=utf-8', +}; + +class ExcelService extends Service { + getContentType(bookType = 'xlsx') { + const normalizedType = String(bookType || 'xlsx').replace('.', '').toLowerCase(); + return CONTENT_TYPE_MAP[normalizedType] || CONTENT_TYPE_MAP.xlsx; + } + + sanitizeSheetName(name, index = 1) { + const safeName = String(name || `Sheet${index}`) + .replace(/[\\/?*\[\]:]/g, '_') + .trim(); + + return (safeName || `Sheet${index}`).slice(0, 31); + } + + normalizeHeaders(headerRow = []) { + const usedNames = new Set(); + + return headerRow.map((value, index) => { + const baseName = String(value == null ? '' : value).trim() || `column_${index + 1}`; + let uniqueName = baseName; + let suffix = 2; + + while (usedNames.has(uniqueName)) { + uniqueName = `${baseName}_${suffix}`; + suffix += 1; + } + + usedNames.add(uniqueName); + return uniqueName; + }); + } + + normalizeColumns(columns = []) { + if (!Array.isArray(columns)) { + return []; + } + + return columns + .map(column => { + if (!column) { + return null; + } + + const key = column.key || column.field || column.dataIndex || column.prop; + const header = column.header || column.title || column.label || key; + + if (!key && !header) { + return null; + } + + return { + key: key || header, + header: header || key, + width: Number(column.width || column.wch || 0) || undefined, + }; + }) + .filter(Boolean); + } + + prepareSheetData(sheetConfig = {}) { + const { + rows = [], + columns = [], + header = [], + skipHeader = false, + widths = [], + } = sheetConfig; + + const normalizedColumns = this.normalizeColumns(columns); + let aoaData = []; + + if (normalizedColumns.length > 0) { + const headerRow = normalizedColumns.map(column => column.header); + const columnKeys = normalizedColumns.map(column => column.key); + const bodyRows = Array.isArray(rows) + ? rows.map(row => { + if (Array.isArray(row)) { + return row; + } + + return columnKeys.map(key => (row && typeof row === 'object' ? row[key] : '')); + }) + : []; + aoaData = skipHeader ? bodyRows : [ headerRow, ...bodyRows ]; + } else if (Array.isArray(rows) && rows.length > 0 && Array.isArray(rows[0])) { + aoaData = Array.isArray(header) && header.length > 0 && !skipHeader + ? [ header, ...rows ] + : rows; + } else if (Array.isArray(rows) && rows.length > 0) { + const derivedHeaders = Array.isArray(header) && header.length > 0 + ? header + : Object.keys(rows[0] || {}); + const bodyRows = rows.map(row => derivedHeaders.map(key => (row && typeof row === 'object' ? row[key] : ''))); + aoaData = skipHeader ? bodyRows : [ derivedHeaders, ...bodyRows ]; + } else { + aoaData = Array.isArray(header) && header.length > 0 ? [ header ] : []; + } + + const resolvedWidths = Array.isArray(widths) && widths.length > 0 + ? widths.map(item => (typeof item === 'number' ? { wch: item } : item)) + : normalizedColumns + .filter(column => column.width) + .map(column => ({ wch: column.width })); + + return { + normalizedColumns, + aoaData, + resolvedWidths, + skipHeader, + originalRows: Array.isArray(rows) ? rows : [], + }; + } + + hasEmbeddedImages(options = {}) { + return Array.isArray(options.sheets) + && options.sheets.some(sheet => Array.isArray(sheet && sheet.embeddedImages) && sheet.embeddedImages.length > 0); + } + + buildWorksheet(sheetConfig = {}) { + const { + merges = [], + } = sheetConfig; + const { + aoaData, + resolvedWidths, + } = this.prepareSheetData(sheetConfig); + + const worksheet = XLSX.utils.aoa_to_sheet(aoaData); + + if (resolvedWidths.length > 0) { + worksheet['!cols'] = resolvedWidths; + } + + if (Array.isArray(merges) && merges.length > 0) { + worksheet['!merges'] = merges; + } + + return worksheet; + } + + buildWorkbook(options = {}) { + const { sheets = [], props = {} } = options; + + if (!Array.isArray(sheets) || sheets.length === 0) { + throw new Error('至少需要一个 sheet 配置'); + } + + const workbook = XLSX.utils.book_new(); + workbook.Props = { + Company: 'WMS', + CreatedDate: new Date(), + ...props, + }; + + sheets.forEach((sheetConfig, index) => { + const worksheet = this.buildWorksheet(sheetConfig || {}); + const sheetName = this.sanitizeSheetName(sheetConfig && sheetConfig.name, index + 1); + XLSX.utils.book_append_sheet(workbook, worksheet, sheetName); + }); + + return workbook; + } + + async buildExcelJsWorkbook(options = {}) { + const { sheets = [], props = {} } = options; + + if (!Array.isArray(sheets) || sheets.length === 0) { + throw new Error('至少需要一个 sheet 配置'); + } + + const workbook = new ExcelJS.Workbook(); + workbook.creator = props.author || 'WMS'; + workbook.company = props.company || 'WMS'; + workbook.created = props.createdAt || new Date(); + workbook.modified = new Date(); + + for (let index = 0; index < sheets.length; index += 1) { + const sheetConfig = sheets[index] || {}; + const sheetName = this.sanitizeSheetName(sheetConfig.name, index + 1); + const worksheet = workbook.addWorksheet(sheetName); + const { + merges = [], + embeddedImages = [], + styledRows = [], + } = sheetConfig; + const { + normalizedColumns, + aoaData, + resolvedWidths, + skipHeader, + originalRows, + } = this.prepareSheetData(sheetConfig); + + if (normalizedColumns.length > 0 && originalRows.length > 0 && !Array.isArray(originalRows[0])) { + if (skipHeader) { + aoaData.forEach(row => worksheet.addRow(row)); + } else { + worksheet.columns = normalizedColumns.map(column => ({ + header: column.header, + key: column.key, + width: column.width || 18, + })); + originalRows.forEach(row => worksheet.addRow(row || {})); + } + } else if (normalizedColumns.length > 0 && originalRows.length === 0 && !skipHeader) { + worksheet.columns = normalizedColumns.map(column => ({ + header: column.header, + key: column.key, + width: column.width || 18, + })); + } else { + aoaData.forEach(row => worksheet.addRow(row)); + } + + if (resolvedWidths.length > 0) { + resolvedWidths.forEach((column, columnIndex) => { + const width = Number(column && column.wch) || Number(column && column.width) || undefined; + if (width) { + worksheet.getColumn(columnIndex + 1).width = width; + } + }); + } + + if (Array.isArray(merges) && merges.length > 0) { + merges.forEach(merge => { + if (!merge) { + return; + } + + if (typeof merge === 'string') { + worksheet.mergeCells(merge); + return; + } + + if (merge.s && merge.e) { + worksheet.mergeCells(merge.s.r + 1, merge.s.c + 1, merge.e.r + 1, merge.e.c + 1); + } + }); + } + + if (Array.isArray(styledRows) && styledRows.length > 0) { + this.applyStyledRows(worksheet, styledRows); + } + + if (Array.isArray(embeddedImages) && embeddedImages.length > 0) { + await this.addEmbeddedImages(workbook, worksheet, embeddedImages); + } + } + + return workbook; + } + + inferImageExtension(imageConfig = {}, contentType = '') { + const preferred = String(imageConfig.extension || '').replace('.', '').toLowerCase(); + if (preferred) { + return preferred === 'jpg' ? 'jpeg' : preferred; + } + + const fileSource = imageConfig.url || imageConfig.filePath || imageConfig.filename || ''; + const ext = path.extname(String(fileSource)).replace('.', '').toLowerCase(); + if (ext) { + return ext === 'jpg' ? 'jpeg' : ext; + } + + if (contentType.includes('png')) return 'png'; + if (contentType.includes('gif')) return 'gif'; + if (contentType.includes('jpg') || contentType.includes('jpeg')) return 'jpeg'; + if (contentType.includes('webp')) return 'png'; + + return 'png'; + } + + async resolveImageSource(imageConfig = {}) { + try { + if (imageConfig.buffer) { + return { + buffer: Buffer.isBuffer(imageConfig.buffer) ? imageConfig.buffer : Buffer.from(imageConfig.buffer), + extension: this.inferImageExtension(imageConfig), + }; + } + + if (imageConfig.dataUrl) { + const match = String(imageConfig.dataUrl).match(/^data:(image\/[a-zA-Z0-9.+-]+);base64,(.+)$/); + if (match) { + return { + buffer: Buffer.from(match[2], 'base64'), + extension: this.inferImageExtension(imageConfig, match[1]), + }; + } + } + + if (imageConfig.base64) { + return { + buffer: Buffer.from(String(imageConfig.base64), 'base64'), + extension: this.inferImageExtension(imageConfig), + }; + } + + if (imageConfig.filePath) { + const resolvedFilePath = path.resolve(String(imageConfig.filePath)); + const buffer = await fs.promises.readFile(resolvedFilePath); + return { + buffer, + extension: this.inferImageExtension({ ...imageConfig, filePath: resolvedFilePath }), + }; + } + + if (imageConfig.url) { + const imageUrl = String(imageConfig.url); + const dataUrlMatch = imageUrl.match(/^data:(image\/[a-zA-Z0-9.+-]+);base64,(.+)$/); + if (dataUrlMatch) { + return { + buffer: Buffer.from(dataUrlMatch[2], 'base64'), + extension: this.inferImageExtension(imageConfig, dataUrlMatch[1]), + }; + } + + if (this.ctx && typeof this.ctx.curl === 'function') { + const response = await this.ctx.curl(imageUrl, { + method: 'GET', + timeout: 15000, + followRedirect: true, + }); + const contentType = String((response.headers && (response.headers['content-type'] || response.headers['Content-Type'])) || '').toLowerCase(); + const buffer = Buffer.isBuffer(response.data) ? response.data : Buffer.from(response.data || ''); + + if (buffer.length > 0) { + return { + buffer, + extension: this.inferImageExtension(imageConfig, contentType), + }; + } + } else if (typeof fetch === 'function' && /^https?:\/\//i.test(imageUrl)) { + const response = await fetch(imageUrl); + if (response && response.ok) { + const contentType = String(response.headers.get('content-type') || '').toLowerCase(); + const arrayBuffer = await response.arrayBuffer(); + const buffer = Buffer.from(arrayBuffer); + + if (buffer.length > 0) { + return { + buffer, + extension: this.inferImageExtension(imageConfig, contentType), + }; + } + } + } + } + } catch (error) { + if (this.ctx && this.ctx.logger && typeof this.ctx.logger.warn === 'function') { + this.ctx.logger.warn('[ExcelService.resolveImageSource] 图片加载失败: %s', error.message); + } + } + + return null; + } + + mergeCellStyle(baseStyle = {}, patchStyle = {}) { + const mergedStyle = { + ...baseStyle, + ...patchStyle, + }; + + if (baseStyle.font || patchStyle.font) { + mergedStyle.font = { + ...(baseStyle.font || {}), + ...(patchStyle.font || {}), + }; + } + + if (baseStyle.alignment || patchStyle.alignment) { + mergedStyle.alignment = { + ...(baseStyle.alignment || {}), + ...(patchStyle.alignment || {}), + }; + } + + if (baseStyle.protection || patchStyle.protection) { + mergedStyle.protection = { + ...(baseStyle.protection || {}), + ...(patchStyle.protection || {}), + }; + } + + if (patchStyle.fill) { + mergedStyle.fill = patchStyle.fill; + } + + if (patchStyle.border) { + mergedStyle.border = patchStyle.border; + } + + if (patchStyle.numFmt) { + mergedStyle.numFmt = patchStyle.numFmt; + } + + return mergedStyle; + } + + applyStyledRows(worksheet, styledRows = []) { + styledRows.forEach(item => { + if (!item) { + return; + } + + const rowNumber = Math.max(Number(item.row || 1), 1); + const fromCol = Math.max(Number(item.fromCol || 1), 1); + const toCol = Math.max(Number(item.toCol || fromCol), fromCol); + const row = worksheet.getRow(rowNumber); + + if (item.height) { + row.height = item.height; + } + + if (item.style && typeof item.style === 'object') { + for (let col = fromCol; col <= toCol; col += 1) { + const cell = worksheet.getCell(rowNumber, col); + cell.style = this.mergeCellStyle(cell.style || {}, item.style); + } + } + }); + } + + async addEmbeddedImages(workbook, worksheet, embeddedImages = []) { + for (const imageConfig of embeddedImages) { + if (!imageConfig) { + continue; + } + + const row = Math.max(Number(imageConfig.row || 1), 1); + const col = Math.max(Number(imageConfig.col || imageConfig.column || 1), 1); + const width = Math.max(Number(imageConfig.width || 120), 40); + const height = Math.max(Number(imageConfig.height || 120), 40); + const cell = worksheet.getCell(row, col); + const fallbackText = imageConfig.fallbackText || imageConfig.url || ''; + const resolvedImage = await this.resolveImageSource(imageConfig); + + if (!resolvedImage || !resolvedImage.buffer || resolvedImage.buffer.length === 0) { + if (fallbackText) { + cell.value = fallbackText; + } + continue; + } + + const imageId = workbook.addImage({ + buffer: resolvedImage.buffer, + extension: resolvedImage.extension, + }); + + worksheet.addImage(imageId, { + tl: { col: col - 1 + 0.05, row: row - 1 + 0.05 }, + ext: { width, height }, + editAs: 'oneCell', + }); + + if (fallbackText) { + cell.value = fallbackText; + } + + worksheet.getRow(row).height = Math.max(Number(worksheet.getRow(row).height || 20), Math.ceil(height * 0.75)); + worksheet.getColumn(col).width = Math.max(Number(worksheet.getColumn(col).width || 10), Math.ceil(width / 7)); + } + } + + async generateBuffer(options = {}) { + const bookType = String(options.bookType || 'xlsx').replace('.', '').toLowerCase(); + + const shouldUseExcelJs = this.hasEmbeddedImages(options) + || (Array.isArray(options.sheets) + && options.sheets.some(sheet => sheet && (sheet.forceExcelJs || (Array.isArray(sheet.styledRows) && sheet.styledRows.length > 0)))); + + if (shouldUseExcelJs) { + if (bookType !== 'xlsx') { + throw new Error('带图片的 Excel 仅支持 xlsx 格式'); + } + + const workbook = await this.buildExcelJsWorkbook({ + ...options, + bookType, + }); + const buffer = await workbook.xlsx.writeBuffer(); + return Buffer.isBuffer(buffer) ? buffer : Buffer.from(buffer); + } + + const workbook = this.buildWorkbook(options); + const buffer = XLSX.write(workbook, { + type: 'buffer', + bookType, + compression: true, + }); + + return Buffer.isBuffer(buffer) ? buffer : Buffer.from(buffer); + } + + async writeFile(filePath, options = {}) { + if (!filePath) { + throw new Error('filePath 不能为空'); + } + + const resolvedFilePath = path.resolve(filePath); + const ext = path.extname(resolvedFilePath).replace('.', '').toLowerCase() || options.bookType || 'xlsx'; + const buffer = await this.generateBuffer({ + ...options, + bookType: ext, + }); + + await fs.promises.mkdir(path.dirname(resolvedFilePath), { recursive: true }); + await fs.promises.writeFile(resolvedFilePath, buffer); + + return { + filePath: resolvedFilePath, + size: buffer.length, + bookType: ext, + }; + } + + sanitizeFilename(filename = 'export.xlsx', fallbackExt = '.xlsx') { + const normalizedName = String(filename || '').trim() || `export${fallbackExt}`; + const rawExt = path.extname(normalizedName); + const ext = rawExt || fallbackExt; + const baseName = path.basename(normalizedName, rawExt); + const safeBaseName = String(baseName || 'export') + .replace(/[<>:"/\\|?*]/g, '_') + .replace(/\s+/g, '_') + .replace(/_+/g, '_') + .replace(/^_+|_+$/g, '') + .slice(0, 120) || 'export'; + + return `${safeBaseName}${ext}`; + } + + buildUploadKey(filename, options = {}) { + if (options.key) { + return String(options.key) + .replace(/\\/g, '/') + .replace(/^\/+/, '') + .replace(/\/+/g, '/'); + } + + const now = new Date(); + const dateFolder = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}`; + const normalizedDir = String(options.dir || 'exports/excel') + .replace(/\\/g, '/') + .replace(/^\/+|\/+$/g, ''); + + return path.posix.join(normalizedDir, dateFolder, filename); + } + + async generateAndUpload({ + filename = 'export.xlsx', + dir = 'exports/excel', + key, + category = 'document', + saveRecord = false, + businessType, + businessId, + uploaderDept, + expireTime, + expireDays, + onProgress, + ...options + } = {}) { + const uploadService = this.ctx && this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.upload; + + if (!uploadService || typeof uploadService.uploadFile !== 'function') { + throw new Error('上传服务不可用,无法上传 Excel 文件'); + } + + const bookType = String(options.bookType || path.extname(filename).replace('.', '') || 'xlsx').toLowerCase(); + const safeFilename = this.sanitizeFilename(filename, `.${bookType}`); + const contentType = this.getContentType(bookType); + const buffer = await this.generateBuffer({ + ...options, + bookType, + }); + const uploadKey = this.buildUploadKey(safeFilename, { dir, key }); + const uploadStream = Readable.from(buffer); + + uploadStream.filename = safeFilename; + uploadStream.mimeType = contentType; + uploadStream.fileSize = buffer.length; + + const uploadResult = await uploadService.uploadFile(uploadStream, { + key: uploadKey, + category, + mimetype: 'xls,xlsx,csv', + onProgress, + }); + + let fileRecord = null; + if ((saveRecord || businessType || businessId) && typeof uploadService.uploadSuccessNotify === 'function') { + const recordResult = await uploadService.uploadSuccessNotify({ + url: uploadResult.fileName, + fileKey: uploadResult.fileName, + fileName: safeFilename, + name: safeFilename, + fileSize: buffer.length, + size: buffer.length, + fileType: category, + mimeType: contentType, + type: category, + category, + businessType, + businessId, + uploaderDept, + expireTime, + expireDays, + }); + + fileRecord = recordResult && (recordResult.data || recordResult); + } + + return { + filename: safeFilename, + fileKey: uploadResult.fileName, + size: buffer.length, + contentType, + ...uploadResult, + fileRecord, + }; + } + + async sendFile({ ctx = this.ctx, filename = 'export.xlsx', ...options } = {}) { + if (!ctx) { + throw new Error('ctx 不存在,无法输出下载响应'); + } + + const ext = path.extname(filename).replace('.', '').toLowerCase() || options.bookType || 'xlsx'; + const buffer = await this.generateBuffer({ + ...options, + bookType: ext, + }); + + ctx.set('Content-Type', this.getContentType(ext)); + ctx.set('Content-Disposition', `attachment; filename*=UTF-8''${encodeURIComponent(filename)}`); + ctx.body = buffer; + + return { + filename, + size: buffer.length, + contentType: this.getContentType(ext), + }; + } + + async parseBuffer(buffer, options = {}) { + if (!buffer) { + throw new Error('buffer 不能为空'); + } + + const workbook = XLSX.read(buffer, { + type: 'buffer', + raw: false, + cellDates: true, + ...options.readOptions, + }); + + return this.workbookToJSON(workbook, options); + } + + async parseFile(filePath, options = {}) { + if (!filePath) { + throw new Error('filePath 不能为空'); + } + + const resolvedFilePath = path.resolve(filePath); + const buffer = await fs.promises.readFile(resolvedFilePath); + const result = await this.parseBuffer(buffer, options); + + return { + filePath: resolvedFilePath, + ...result, + }; + } + + workbookToJSON(workbook, options = {}) { + const { + headerRow = 1, + defval = '', + blankrows = false, + includeRawRows = false, + sheetNames, + } = options; + + const startIndex = Math.max(Number(headerRow) || 1, 1) - 1; + const selectedSheetNames = Array.isArray(sheetNames) && sheetNames.length > 0 + ? workbook.SheetNames.filter(name => sheetNames.includes(name)) + : workbook.SheetNames; + + const sheets = selectedSheetNames.map(name => { + const sheet = workbook.Sheets[name]; + const rawRows = XLSX.utils.sheet_to_json(sheet, { + header: 1, + raw: false, + defval, + blankrows, + }); + const headerValues = Array.isArray(rawRows[startIndex]) ? rawRows[startIndex] : []; + const headers = this.normalizeHeaders(headerValues); + const dataRows = rawRows.slice(startIndex + 1) + .filter(row => blankrows || row.some(cell => String(cell == null ? '' : cell).trim() !== '')); + const rows = dataRows.map(row => { + return headers.reduce((result, headerName, columnIndex) => { + result[headerName] = row[columnIndex] == null ? defval : row[columnIndex]; + return result; + }, {}); + }); + + const sheetResult = { + name, + headers, + rows, + rowCount: rows.length, + }; + + if (includeRawRows) { + sheetResult.rawRows = rawRows; + } + + return sheetResult; + }); + + return { + sheetNames: selectedSheetNames, + sheets, + }; + } +} + +module.exports = ExcelService; diff --git a/app/service/systems/setting/account.js b/app/service/systems/setting/account.js index 27f273e..6cd2314 100644 --- a/app/service/systems/setting/account.js +++ b/app/service/systems/setting/account.js @@ -1,10 +1,34 @@ 'use strict'; const Service = require('egg').Service; +const { parseWhereConditions } = require('../../../lib/query_condition_parser'); const RESERVED_EMPLOYEE_NAME = '测试工号保留'; class SettingAccountService extends Service { + getListWhereSpecialFieldMap() { + return { + employee_id: { + field: 'id', + }, + account_id: { + field: 'account_id', + }, + username: { + field: '$account.username$', + }, + phone: { + field: '$account.phone$', + }, + email: { + field: '$account.email$', + }, + quickWhere: { + bucket: 'quick', + }, + }; + } + createError(message, code = 500) { const error = new Error(message); error.code = code; @@ -27,6 +51,14 @@ class SettingAccountService extends Service { return employeeId; } + normalizeAccountId(value, fieldName = 'account_id') { + const accountId = Number(value); + if (!Number.isFinite(accountId) || accountId <= 0) { + throw this.createError(`${fieldName} 参数不能为空`, 400); + } + return accountId; + } + getWmsClient() { return this.ctx.app.mysql.get('wms'); } @@ -127,10 +159,304 @@ class SettingAccountService extends Service { return Number(currentRole.role_id); } - async formatEmployeeRow(employee) { - const account = await this.getWmsClient().get('wms_account', { - id: employee.account_id, + normalizeRoleIds(ids) { + if (!Array.isArray(ids) || ids.length === 0) { + throw this.createError('ids 参数不能为空', 400); + } + + const roleIds = []; + for (const roleId of ids) { + const normalized = Number(roleId); + if (!Number.isFinite(normalized) || normalized <= 0) { + throw this.createError('ids 必须是正整数数组', 400); + } + roleIds.push(normalized); + } + return Array.from(new Set(roleIds)); + } + + flattenRoleTreeMeta(roleNodes, idCollector = [], parentMap = new Map()) { + if (!Array.isArray(roleNodes) || roleNodes.length === 0) { + return { idCollector, parentMap }; + } + + for (const node of roleNodes) { + const roleId = Number(node && node.role_id); + if (Number.isFinite(roleId) && roleId > 0) { + idCollector.push(roleId); + parentMap.set(roleId, Number(node && node.pid ? node.pid : 0)); + } + + const children = Array.isArray(node && node.children) ? node.children : []; + this.flattenRoleTreeMeta(children, idCollector, parentMap); + } + + return { idCollector, parentMap }; + } + + async resolveAssignableRoleScope() { + const roleResult = await this.ctx.service.systems.setting.role.list({ + includeDisabled: false, + includeSystem: false, }); + + const roleTree = roleResult && roleResult.data && Array.isArray(roleResult.data.roles) + ? roleResult.data.roles + : []; + const { idCollector, parentMap } = this.flattenRoleTreeMeta(roleTree, [], new Map()); + return { + roleIdSet: new Set(idCollector), + parentMap, + }; + } + + pruneDescendantRoleIds(roleIds, parentMap) { + const selected = new Set(roleIds); + const pruned = []; + + for (const roleId of roleIds) { + let current = roleId; + let keep = true; + const visited = new Set(); + + while (true) { + const parentId = Number(parentMap.get(current) || 0); + if (!Number.isFinite(parentId) || parentId <= 0) { + break; + } + if (visited.has(parentId)) { + break; + } + visited.add(parentId); + + if (selected.has(parentId)) { + keep = false; + break; + } + + current = parentId; + } + + if (keep) { + pruned.push(roleId); + } + } + + return Array.from(new Set(pruned)); + } + + async resolveRequestedRoleIds(data = {}, options = {}) { + const required = options.required === true; + const hasIds = Object.prototype.hasOwnProperty.call(data, 'ids'); + const hasRoleIds = Object.prototype.hasOwnProperty.call(data, 'role_ids'); + + if (!hasIds && !hasRoleIds) { + if (required) { + throw this.createError('ids 参数不能为空', 400); + } + return null; + } + + const rawRoleIds = hasIds ? data.ids : data.role_ids; + const roleIds = this.normalizeRoleIds(rawRoleIds); + + const { roleIdSet, parentMap } = await this.resolveAssignableRoleScope(); + if (roleIdSet.size === 0) { + throw this.createError('当前角色范围为空,无法分配角色', 400); + } + + const outOfScopeIds = roleIds.filter(roleId => !roleIdSet.has(roleId)); + if (outOfScopeIds.length > 0) { + throw this.createError(`包含超出当前角色范围的角色ID:${outOfScopeIds.join(',')}`, 400); + } + + return this.pruneDescendantRoleIds(roleIds, parentMap); + } + + async replaceEmployeeRoles(employeeId, roleIds) { + const { ctx } = this; + + await ctx.model.EmployeeRole.destroy({ + where: { + employee_id: employeeId, + }, + }); + + const rows = roleIds.map(roleId => ({ + employee_id: employeeId, + role_id: roleId, + })); + + await ctx.model.EmployeeRole.bulkCreate(rows); + } + + async buildEmployeeRoleGroupMap(employeeIds) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + if (!Array.isArray(employeeIds) || employeeIds.length === 0) { + return new Map(); + } + + const employeeRoleRows = await ctx.model.EmployeeRole.findAll({ + where: { + employee_id: employeeIds, + }, + attributes: [ 'employee_id', 'role_id' ], + raw: true, + }); + + if (employeeRoleRows.length === 0) { + return new Map(); + } + + const roleIds = Array.from(new Set(employeeRoleRows + .map(item => Number(item.role_id)) + .filter(roleId => Number.isFinite(roleId) && roleId > 0))); + + const roleRows = await ctx.model.Role.findAll({ + where: { + id: { + [Op.in]: roleIds, + }, + }, + attributes: [ 'id', 'role_code', 'role_name', 'pid', 'status' ], + raw: true, + }); + const roleMap = new Map(roleRows.map(role => [ Number(role.id), role ])); + + const employeeRoleMap = new Map(); + for (const row of employeeRoleRows) { + const employeeId = Number(row.employee_id); + const roleId = Number(row.role_id); + if (!Number.isFinite(employeeId) || employeeId <= 0 || !Number.isFinite(roleId) || roleId <= 0) { + continue; + } + + const role = roleMap.get(roleId); + if (!employeeRoleMap.has(employeeId)) { + employeeRoleMap.set(employeeId, { + role_ids: [], + roles: [], + }); + } + + const target = employeeRoleMap.get(employeeId); + target.role_ids.push(roleId); + target.roles.push({ + role_id: roleId, + role_code: role && role.role_code ? role.role_code : '', + role_name: role && role.role_name ? role.role_name : '', + pid: role ? Number(role.pid || 0) : 0, + status: role ? Number(role.status) : 0, + }); + } + + for (const value of employeeRoleMap.values()) { + value.role_ids = Array.from(new Set(value.role_ids)).sort((a, b) => a - b); + value.roles.sort((a, b) => a.role_id - b.role_id); + } + + return employeeRoleMap; + } + + async buildWechatBindingMap(accountIds) { + if (!Array.isArray(accountIds) || accountIds.length === 0) { + return new Map(); + } + + const normalizedAccountIds = Array.from(new Set(accountIds + .map(accountId => Number(accountId)) + .filter(accountId => Number.isFinite(accountId) && accountId > 0))); + if (normalizedAccountIds.length === 0) { + return new Map(); + } + + const ye4sClient = this.ctx.app.mysql.get('ye4s'); + const bindingRows = await ye4sClient.select('ye4s_user', { + where: { + wms_account_id: normalizedAccountIds, + }, + columns: [ 'id', 'wms_account_id' ], + orders: [[ 'id', 'DESC' ]], + }); + + const bindingMap = new Map(); + for (const row of bindingRows) { + const accountId = Number(row && row.wms_account_id); + const ye4sUserId = Number(row && row.id); + if (!Number.isFinite(accountId) || accountId <= 0 || !Number.isFinite(ye4sUserId) || ye4sUserId <= 0) { + continue; + } + if (!bindingMap.has(accountId)) { + bindingMap.set(accountId, { + is_wechat_bound: true, + ye4s_user_id: ye4sUserId, + }); + } + } + + return bindingMap; + } + + async getOperableEmployeeByAccountId(accountId, options = {}) { + const { ctx } = this; + const storeId = this.getCurrentStoreId(); + const normalizedAccountId = this.normalizeAccountId(accountId, 'user_id'); + const where = { + account_id: normalizedAccountId, + store_id: storeId, + }; + + if (options.includeDisabled !== true) { + where.status = 1; + } + + const employees = await ctx.model.AccountStoreEmployee.findAll({ + where, + order: [[ 'status', 'DESC' ], [ 'id', 'ASC' ]], + }); + + if (employees.length === 0) { + throw this.createError('目标账号不存在或无权限操作', 404); + } + + const { roleIdSet } = await this.resolveAssignableRoleScope(); + if (roleIdSet.size === 0) { + throw this.createError('当前角色范围为空,无法操作目标账号', 400); + } + + const employeeIds = employees + .map(item => Number(item.id)) + .filter(employeeId => Number.isFinite(employeeId) && employeeId > 0); + const employeeRoleMap = await this.buildEmployeeRoleGroupMap(employeeIds); + + for (const employee of employees) { + const employeeId = Number(employee.id); + const roleGroup = employeeRoleMap.get(employeeId) || { + role_ids: [], + roles: [], + }; + const hasOutOfScopeRole = roleGroup.role_ids + .some(roleId => !roleIdSet.has(Number(roleId))); + if (!hasOutOfScopeRole) { + return { + employee, + roleGroup, + }; + } + } + + throw this.createError('目标账号超出当前操作范围', 403); + } + + async formatEmployeeRow(employee, options = {}) { + let account = options.account || null; + if (!account) { + account = await this.getWmsClient().get('wms_account', { + id: employee.account_id, + }); + } const avatar = await this.getAvatarMeta(employee.id); return { @@ -150,28 +476,130 @@ class SettingAccountService extends Service { } async list(data = {}) { - const { ctx } = this; + const { ctx, app } = this; + const { Op } = app.Sequelize; const storeId = this.getCurrentStoreId(); - const statusFilter = data.includeDisabled === true - ? undefined - : (data.status === 0 || data.status === '0' ? 0 : 1); + const currentEmployeeId = this.getCurrentEmployeeId(); + const normalizedWhere = ctx.where && typeof ctx.where === 'object' + ? { ...ctx.where } + : (data.where && typeof data.where === 'object' ? { ...data.where } : {}); + let parsedResult = ctx.whereParsed; + if (!parsedResult || !Array.isArray(parsedResult.dynamicConditions)) { + const parsed = parseWhereConditions({ + where: normalizedWhere, + app, + specialFieldMap: this.getListWhereSpecialFieldMap(), + }); + if (!parsed.ok) { + throw this.createError(`where 参数解析失败: ${parsed.reason}`, 400); + } + parsedResult = parsed.result; + } - const where = { - store_id: storeId, - }; - if (statusFilter === 0 || statusFilter === 1) { - where.status = statusFilter; + const andConditions = [ + { + store_id: storeId, + }, + ]; + const hasWhereStatus = Object.prototype.hasOwnProperty.call(normalizedWhere, 'status'); + if (!hasWhereStatus) { + const statusFilter = data.includeDisabled === true + ? undefined + : (data.status === 0 || data.status === '0' ? 0 : 1); + if (statusFilter === 0 || statusFilter === 1) { + andConditions.push({ status: statusFilter }); + } + } + + const dynamicConditions = parsedResult.dynamicConditions || []; + if (dynamicConditions.length > 0) { + andConditions.push({ [Op.and]: dynamicConditions }); + } + + const quickWhereInput = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere) + || normalizedWhere.quickWhere + || null; + const quickWhereValue = quickWhereInput && typeof quickWhereInput === 'object' + ? quickWhereInput.value + : quickWhereInput; + if (quickWhereValue !== undefined && quickWhereValue !== null && String(quickWhereValue).trim() !== '') { + const keyword = String(quickWhereValue).trim(); + andConditions.push({ + [Op.or]: [ + { real_name: { [Op.like]: `%${keyword}%` } }, + { '$account.username$': { [Op.like]: `%${keyword}%` } }, + { '$account.phone$': { [Op.like]: `%${keyword}%` } }, + { '$account.email$': { [Op.like]: `%${keyword}%` } }, + ], + }); } const employees = await ctx.model.AccountStoreEmployee.findAll({ - where, + where: { + [Op.and]: andConditions, + }, + include: [ + { + model: ctx.model.Account, + as: 'account', + attributes: [ 'id', 'username', 'phone', 'email', 'real_name' ], + required: false, + }, + ], order: [[ 'created_at', 'DESC' ], [ 'id', 'DESC' ]], }); + const { roleIdSet } = await this.resolveAssignableRoleScope(); + if (roleIdSet.size === 0) { + return { + code: 200, + data: [], + }; + } + + const employeeIds = employees + .map(employee => Number(employee.id)) + .filter(employeeId => Number.isFinite(employeeId) && employeeId > 0); + const employeeRoleMap = await this.buildEmployeeRoleGroupMap(employeeIds); + const accountIds = employees + .map(employee => Number(employee.account_id)) + .filter(accountId => Number.isFinite(accountId) && accountId > 0); + const wechatBindingMap = await this.buildWechatBindingMap(accountIds); + const list = []; for (const employee of employees) { - list.push(await this.formatEmployeeRow(employee)); + const employeeId = Number(employee.id); + if (currentEmployeeId && employeeId === currentEmployeeId) { + continue; + } + + const roleGroup = employeeRoleMap.get(employeeId) || { + role_ids: [], + roles: [], + }; + + // 只展示当前账号可分配范围内的工号,避免越权操作。 + const hasOutOfScopeRole = roleGroup.role_ids + .some(roleId => !roleIdSet.has(Number(roleId))); + if (hasOutOfScopeRole) { + continue; + } + + const wechatBinding = wechatBindingMap.get(Number(employee.account_id)) || { + is_wechat_bound: false, + ye4s_user_id: null, + }; + + list.push({ + ...await this.formatEmployeeRow(employee, { + account: employee.account, + }), + is_wechat_bound: wechatBinding.is_wechat_bound, + ye4s_user_id: wechatBinding.ye4s_user_id, + role_ids: roleGroup.role_ids, + roles: roleGroup.roles, + }); } return { @@ -205,7 +633,9 @@ class SettingAccountService extends Service { throw this.createError(`新增工号禁止直接使用保留名称 ${RESERVED_EMPLOYEE_NAME}`, 400); } - const roleId = await this.resolveRoleId(data); + const roleIds = await this.resolveRequestedRoleIds(data, { + required: true, + }); let account = await this.findRawAccountByPhone(phone); if (account && Number(account.status) !== 1) { @@ -256,13 +686,15 @@ class SettingAccountService extends Service { throw this.createError('该手机号已绑定当前主体工号', 409); } - const { employee, employeeRole } = await service.systems.store.ensureEmployeeRoleBinding({ + const { employee } = await service.systems.store.ensureEmployeeRoleBinding({ accountId: Number(account.id), storeId, - roleId, + roleId: roleIds[0], realName, }); + await this.replaceEmployeeRoles(Number(employee.id), roleIds); + await service.systems.auth.user.clearUserCache(Number(account.id)); const formatted = await this.formatEmployeeRow(employee); @@ -270,7 +702,8 @@ class SettingAccountService extends Service { code: 200, data: { ...formatted, - role_id: Number(employeeRole.role_id), + role_id: roleIds[0], + role_ids: roleIds, is_new_account: createdAccountId > 0, }, }; @@ -348,14 +781,15 @@ class SettingAccountService extends Service { const employeeId = Number(data.employee_id || data.id || 0); const hasRealName = Object.prototype.hasOwnProperty.call(data, 'real_name') || Object.prototype.hasOwnProperty.call(data, 'realName'); const hasFileId = Object.prototype.hasOwnProperty.call(data, 'file_id') || Object.prototype.hasOwnProperty.call(data, 'avatar_file_id') || Object.prototype.hasOwnProperty.call(data, 'fileId'); + const hasRoleIds = Object.prototype.hasOwnProperty.call(data, 'ids') || Object.prototype.hasOwnProperty.call(data, 'role_ids'); const realName = this.normalizeName(data.real_name || data.realName); const fileId = Number(data.file_id || data.avatar_file_id || data.fileId || 0); if (!employeeId) { throw this.createError('employee_id 参数不能为空', 400); } - if (!hasRealName && !hasFileId) { - throw this.createError('至少需要更新 real_name 或 file_id', 400); + if (!hasRoleIds) { + throw this.createError('ids 参数不能为空', 400); } if (hasRealName && !realName) { throw this.createError('real_name 参数不能为空', 400); @@ -405,14 +839,64 @@ class SettingAccountService extends Service { }); } + const roleIds = await this.resolveRequestedRoleIds(data, { + required: true, + }); + await this.replaceEmployeeRoles(employeeId, roleIds); + await service.systems.auth.user.clearUserCache(Number(employee.account_id)); const refreshed = await ctx.model.AccountStoreEmployee.findByPk(employeeId); + const roleRows = await ctx.model.EmployeeRole.findAll({ + where: { + employee_id: employeeId, + }, + attributes: [ 'role_id' ], + order: [[ 'role_id', 'ASC' ]], + raw: true, + }); + const boundRoleIds = roleRows + .map(item => Number(item.role_id)) + .filter(roleId => Number.isFinite(roleId) && roleId > 0); + return { code: 200, - data: await this.formatEmployeeRow(refreshed), + data: { + ...await this.formatEmployeeRow(refreshed), + role_ids: Array.from(new Set(boundRoleIds)), + }, }; } + + async getBindWechatCode(data = {}) { + const { service } = this.ctx; + const accountId = data.user_id || data.account_id || data.id; + const { employee } = await this.getOperableEmployeeByAccountId(accountId); + const result = await service.systems.auth.user.getBindWechatCodeByAccountId(Number(employee.account_id), data, { + missingAccountMessage: '目标账号不存在,无法生成绑定码', + }); + + if (!result || Number(result.code) !== 200) { + throw this.createError(result && result.message ? result.message : '获取绑定码失败', Number(result && result.code) || 500); + } + + return result; + } + + async unbindWechat(data = {}) { + const { service } = this.ctx; + const accountId = data.user_id || data.account_id || data.id; + const { employee } = await this.getOperableEmployeeByAccountId(accountId); + const result = await service.systems.auth.user.unbindWechatByAccountId(Number(employee.account_id), { + missingAccountMessage: '目标账号不存在,无法解绑', + }); + + if (!result || Number(result.code) !== 200) { + throw this.createError(result && result.message ? result.message : '解绑失败', Number(result && result.code) || 500); + } + + return result; + } } module.exports = SettingAccountService; diff --git a/app/service/systems/setting/permission.js b/app/service/systems/setting/permission.js new file mode 100644 index 0000000..1b5d03b --- /dev/null +++ b/app/service/systems/setting/permission.js @@ -0,0 +1,651 @@ +'use strict'; + +const Service = require('egg').Service; + +class SettingPermissionService extends Service { + createError(message, code = 500) { + const error = new Error(message); + error.code = code; + return error; + } + + getCurrentStoreId() { + const storeId = Number(this.ctx.user && this.ctx.user.store_id); + if (!Number.isFinite(storeId) || storeId <= 0) { + throw this.createError('未识别到当前主体,无法操作权限', 400); + } + return storeId; + } + + getCurrentEmployeeId() { + const employeeId = Number(this.ctx.user && this.ctx.user.employees_id); + if (!Number.isFinite(employeeId) || employeeId <= 0) { + return null; + } + return employeeId; + } + + toPositiveNumber(value, fieldName) { + const num = Number(value); + if (!Number.isFinite(num) || num <= 0) { + throw this.createError(`${fieldName} 参数不能为空`, 400); + } + return num; + } + + async getRole(roleId) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const storeId = this.getCurrentStoreId(); + + const role = await ctx.model.Role.findOne({ + where: { + id: roleId, + [Op.or]: [ + { store_id: storeId }, + { store_id: 0 }, + { store_id: null }, + ], + }, + }); + + if (!role) { + throw this.createError('角色不存在或无权限操作', 404); + } + + return role; + } + + async getPermission(permissionId, includeDisabled = false) { + const { ctx } = this; + const where = { id: permissionId }; + if (!includeDisabled) { + where.status = 1; + } + + const permission = await ctx.model.Permission.findOne({ where }); + if (!permission) { + throw this.createError('权限不存在或已禁用', 404); + } + + return permission; + } + + normalizePermissionType(type) { + const normalized = typeof type === 'string' ? type.trim() : ''; + if (!normalized) { + throw this.createError('type 参数不能为空', 400); + } + + const allowedTypes = new Set([ 'web_pages', 'pda_pages', 'btns', 'api', 'miniprogram_pages', 'block' ]); + if (!allowedTypes.has(normalized)) { + throw this.createError('type 参数不合法', 400); + } + return normalized; + } + + normalizeOptionalString(value, fieldName, maxLength = 255) { + if (value === undefined || value === null) { + return null; + } + const normalized = String(value).trim(); + if (!normalized) { + return ''; + } + if (normalized.length > maxLength) { + throw this.createError(`${fieldName} 长度不能超过 ${maxLength}`, 400); + } + return normalized; + } + + normalizeParentId(value) { + if (value === undefined || value === null || value === '' || Number(value) === 0) { + return null; + } + const num = Number(value); + if (!Number.isFinite(num) || num <= 0) { + throw this.createError('parent_id 参数不合法', 400); + } + return num; + } + + normalizeSort(value) { + if (value === undefined || value === null || value === '') { + return 0; + } + const num = Number(value); + if (!Number.isFinite(num) || num < 0) { + throw this.createError('sort 参数不合法', 400); + } + return Math.floor(num); + } + + normalizeStatus(value) { + if (value === undefined || value === null || value === '') { + return 1; + } + const num = Number(value); + if (num === 0 || num === 1) { + return num; + } + throw this.createError('status 参数不合法', 400); + } + + normalizeBooleanFlag(value, fieldName) { + if (value === undefined || value === null || value === '') { + return 0; + } + const num = Number(value); + if (num === 0 || num === 1) { + return num; + } + throw this.createError(`${fieldName} 参数不合法`, 400); + } + + async getAvailablePermissionIdSet({ includeDisabled = false } = {}) { + const rows = await this.resolveVisiblePermissionRows({ + includeDisabled, + type: null, + keyword: '', + }); + return new Set(rows.map(item => Number(item.id)).filter(id => Number.isFinite(id) && id > 0)); + } + + async ensureParentPermissionExists(parentId) { + if (!parentId) { + return; + } + + await this.getPermission(parentId, false); + } + + async ensurePermissionsExist(permissionIds) { + const { ctx } = this; + + const targetRows = await ctx.model.Permission.findAll({ + where: { + id: permissionIds, + }, + attributes: [ 'id' ], + raw: true, + }); + if (targetRows.length !== permissionIds.length) { + const found = new Set(targetRows.map(item => Number(item.id))); + const missing = permissionIds.filter(id => !found.has(Number(id))); + throw this.createError(`权限不存在:${missing.join(',')}`, 404); + } + + return targetRows; + } + + normalizePermissionIds(inputPermissionIds) { + if (!Array.isArray(inputPermissionIds)) { + throw this.createError('permission_ids 参数不能为空', 400); + } + + const permissionIds = []; + for (const permissionId of inputPermissionIds) { + const normalized = Number(permissionId); + if (!Number.isFinite(normalized) || normalized <= 0) { + throw this.createError('permission_ids 必须是正整数数组', 400); + } + permissionIds.push(normalized); + } + + return Array.from(new Set(permissionIds)); + } + + normalizeIds(inputIds, fieldName = 'ids') { + if (!Array.isArray(inputIds)) { + throw this.createError(`${fieldName} 参数不能为空`, 400); + } + + const ids = []; + for (const item of inputIds) { + const normalized = Number(item); + if (!Number.isFinite(normalized) || normalized <= 0) { + throw this.createError(`${fieldName} 必须是正整数数组`, 400); + } + ids.push(normalized); + } + if (ids.length === 0) { + throw this.createError(`${fieldName} 参数不能为空`, 400); + } + + return Array.from(new Set(ids)); + } + + async validatePermissions(permissionIds) { + const { ctx } = this; + if (permissionIds.length === 0) { + return []; + } + + const permissions = await ctx.model.Permission.findAll({ + where: { + id: permissionIds, + status: 1, + }, + attributes: [ 'id' ], + }); + + if (permissions.length !== permissionIds.length) { + const foundIds = permissions.map(item => Number(item.id)); + const missingIds = permissionIds.filter(item => !foundIds.includes(item)); + throw this.createError(`权限不存在或已禁用:${missingIds.join(',')}`, 400); + } + + return permissions; + } + + async clearRoleUsersCache(roleId) { + const { ctx, service } = this; + const storeId = this.getCurrentStoreId(); + + const employeeRoleRows = await ctx.model.EmployeeRole.findAll({ + where: { + role_id: roleId, + }, + include: [ + { + model: ctx.model.AccountStoreEmployee, + as: 'employee', + attributes: [ 'account_id' ], + where: { + store_id: storeId, + status: 1, + }, + required: true, + }, + ], + raw: false, + }); + + const accountIds = Array.from(new Set(employeeRoleRows + .map(item => Number(item.employee && item.employee.account_id)) + .filter(id => Number.isFinite(id) && id > 0))); + + for (const accountId of accountIds) { + await service.systems.auth.user.clearUserCache(accountId); + } + } + + async getCurrentEmployeePermissionIds() { + const { ctx } = this; + const currentEmployeeId = this.getCurrentEmployeeId(); + if (!currentEmployeeId) { + return []; + } + + const employeeRoles = await ctx.model.EmployeeRole.findAll({ + attributes: [ 'role_id' ], + where: { + employee_id: currentEmployeeId, + }, + include: [ + { + model: ctx.model.Role, + as: 'role', + attributes: [], + where: { + status: 1, + }, + required: true, + }, + ], + raw: true, + }); + + const roleIds = Array.from(new Set(employeeRoles + .map(item => Number(item.role_id)) + .filter(id => Number.isFinite(id) && id > 0))); + if (roleIds.length === 0) { + return []; + } + + return await ctx.service.systems.auth.rolePermission.getPermissionIdsForRoles(roleIds, { + includeDisabled: false, + }); + } + + async getCurrentRoleId() { + const { ctx } = this; + const currentEmployeeId = this.getCurrentEmployeeId(); + if (!currentEmployeeId) { + return null; + } + + const row = await ctx.model.EmployeeRole.findOne({ + attributes: [ 'role_id' ], + where: { + employee_id: currentEmployeeId, + }, + include: [ + { + model: ctx.model.Role, + as: 'role', + attributes: [], + where: { + status: 1, + }, + required: true, + }, + ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + const roleId = Number(row && row.role_id); + if (!Number.isFinite(roleId) || roleId <= 0) { + return null; + } + return roleId; + } + + async resolveVisiblePermissionRows({ includeDisabled = false, type = null, keyword = '', scopeMode = 'available' } = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + const where = { + status: includeDisabled ? { [Op.in]: [ 0, 1 ] } : 1, + }; + + if (scopeMode !== 'all') { + const currentPermissionIds = await this.getCurrentEmployeePermissionIds(); + if (currentPermissionIds.length === 0) { + return []; + } + where.id = { + [Op.in]: currentPermissionIds, + }; + } + if (type) { + where.type = type; + } + if (keyword) { + where[Op.or] = [ + { path: { [Op.like]: `%${keyword}%` } }, + { name: { [Op.like]: `%${keyword}%` } }, + { meta_title: { [Op.like]: `%${keyword}%` } }, + ]; + } + + const permissionRows = await ctx.model.Permission.findAll({ + where, + attributes: [ + 'id', + 'path', + 'name', + 'type', + 'status', + 'parent_id', + 'sort', + 'component', + 'redirect', + 'meta_title', + 'meta_icon', + 'hidden', + 'always_show', + ], + order: [ + [ 'sort', 'ASC' ], + [ 'id', 'ASC' ], + ], + }); + + return permissionRows; + } + + async list(data = {}) { + const { ctx } = this; + + const includeDisabled = data.includeDisabled === true; + const roleIdRaw = data.role_id || data.roleId; + const type = typeof data.type === 'string' && data.type.trim() ? data.type.trim() : null; + const keyword = typeof data.keyword === 'string' ? data.keyword.trim() : ''; + + let role = null; + let targetRoleId = roleIdRaw; + if (targetRoleId === undefined || targetRoleId === null || targetRoleId === '') { + targetRoleId = await this.getCurrentRoleId(); + } + if (targetRoleId !== undefined && targetRoleId !== null && targetRoleId !== '') { + const roleId = this.toPositiveNumber(targetRoleId, 'role_id'); + role = await this.getRole(roleId); + } + + // 权限管理页需要展示全量权限树,不能再按当前登录工号已分配权限做裁剪。 + const permissionRows = await this.resolveVisiblePermissionRows({ + includeDisabled, + type, + keyword, + scopeMode: 'all', + }); + + let selectedPermissionSet = new Set(); + let selectAllPermissions = false; + if (role) { + const directPermissionIds = ctx.service.systems.auth.rolePermission.toApiPermissionIds(role.permissions); + if (directPermissionIds.includes('*')) { + selectAllPermissions = true; + } else if (directPermissionIds.length > 0) { + selectedPermissionSet = new Set(directPermissionIds.map(item => Number(item))); + } + } + + const permissions = permissionRows.map(item => ({ + permission_id: Number(item.id), + path: item.path || '', + name: item.name || '', + type: item.type || '', + status: Number(item.status), + parent_id: item.parent_id === null ? null : Number(item.parent_id), + sort: Number(item.sort || 0), + component: item.component || '', + redirect: item.redirect || '', + meta_title: item.meta_title || '', + meta_icon: item.meta_icon || '', + hidden: Number(item.hidden || 0), + always_show: Number(item.always_show || 0), + selected: role ? (selectAllPermissions || selectedPermissionSet.has(Number(item.id))) : false, + })); + + return { + code: 200, + data: { + role_id: role ? Number(role.id) : null, + permissions, + }, + }; + } + + async add(data = {}) { + const { ctx } = this; + + const path = this.normalizeOptionalString(data.path, 'path', 255); + if (!path) { + throw this.createError('path 参数不能为空', 400); + } + + const permissionData = { + path, + type: this.normalizePermissionType(data.type), + name: this.normalizeOptionalString(data.name, 'name', 100) || '', + component: this.normalizeOptionalString(data.component, 'component', 255), + redirect: this.normalizeOptionalString(data.redirect, 'redirect', 255), + meta_title: this.normalizeOptionalString(data.meta_title, 'meta_title', 100), + meta_icon: this.normalizeOptionalString(data.meta_icon, 'meta_icon', 50), + parent_id: this.normalizeParentId(data.parent_id), + sort: this.normalizeSort(data.sort), + hidden: this.normalizeBooleanFlag(data.hidden, 'hidden'), + always_show: this.normalizeBooleanFlag(data.always_show, 'always_show'), + status: this.normalizeStatus(data.status), + }; + + await this.ensureParentPermissionExists(permissionData.parent_id); + + let created = null; + try { + created = await ctx.model.Permission.create(permissionData); + } catch (error) { + throw error; + } + + return { + code: 200, + data: { + permission_id: Number(created.id), + path: created.path || '', + type: created.type || '', + parent_id: created.parent_id === null ? null : Number(created.parent_id), + status: Number(created.status), + }, + }; + } + + async delete(data = {}) { + const { ctx } = this; + const permissionIds = this.normalizeIds(data.ids, 'ids'); + + await this.ensurePermissionsExist(permissionIds); + + const permissions = await ctx.model.Permission.findAll({ + where: { + id: permissionIds, + }, + attributes: [ 'id', 'status' ], + raw: true, + }); + + const deletedIds = []; + const alreadyDeletedIds = []; + for (const permission of permissions) { + if (Number(permission.status) === 0) { + alreadyDeletedIds.push(Number(permission.id)); + } else { + deletedIds.push(Number(permission.id)); + } + } + + const transaction = await ctx.model.transaction(); + try { + if (deletedIds.length > 0) { + await ctx.model.Permission.update({ + status: 0, + }, { + where: { + id: deletedIds, + }, + transaction, + }); + + await ctx.service.systems.auth.rolePermission.removePermissionsFromAllRoles(deletedIds, { + transaction, + }); + } + + await transaction.commit(); + } catch (error) { + await transaction.rollback(); + throw error; + } + + return { + code: 200, + data: { + ids: permissionIds, + deleted_ids: deletedIds, + already_deleted_ids: alreadyDeletedIds, + status: 'deleted', + }, + }; + } + + async update(data = {}) { + const permissionId = this.toPositiveNumber(data.permission_id || data.permissionId, 'permission_id'); + await this.ensurePermissionsExist([ permissionId ]); + + const permission = await this.getPermission(permissionId, true); + + const hasPath = Object.prototype.hasOwnProperty.call(data, 'path'); + const hasName = Object.prototype.hasOwnProperty.call(data, 'name'); + const hasType = Object.prototype.hasOwnProperty.call(data, 'type'); + const hasComponent = Object.prototype.hasOwnProperty.call(data, 'component'); + const hasRedirect = Object.prototype.hasOwnProperty.call(data, 'redirect'); + const hasMetaTitle = Object.prototype.hasOwnProperty.call(data, 'meta_title'); + const hasMetaIcon = Object.prototype.hasOwnProperty.call(data, 'meta_icon'); + const hasParentId = Object.prototype.hasOwnProperty.call(data, 'parent_id'); + const hasSort = Object.prototype.hasOwnProperty.call(data, 'sort'); + const hasHidden = Object.prototype.hasOwnProperty.call(data, 'hidden'); + const hasAlwaysShow = Object.prototype.hasOwnProperty.call(data, 'always_show'); + const hasStatus = Object.prototype.hasOwnProperty.call(data, 'status'); + + if (!hasPath && !hasName && !hasType && !hasComponent && !hasRedirect + && !hasMetaTitle && !hasMetaIcon && !hasParentId && !hasSort + && !hasHidden && !hasAlwaysShow && !hasStatus) { + throw this.createError('至少需要提供一个可更新字段', 400); + } + + const updates = {}; + if (hasPath) { + const path = this.normalizeOptionalString(data.path, 'path', 255); + if (!path) { + throw this.createError('path 参数不能为空', 400); + } + updates.path = path; + } + if (hasName) { + updates.name = this.normalizeOptionalString(data.name, 'name', 100) || ''; + } + if (hasType) { + updates.type = this.normalizePermissionType(data.type); + } + if (hasComponent) { + updates.component = this.normalizeOptionalString(data.component, 'component', 255); + } + if (hasRedirect) { + updates.redirect = this.normalizeOptionalString(data.redirect, 'redirect', 255); + } + if (hasMetaTitle) { + updates.meta_title = this.normalizeOptionalString(data.meta_title, 'meta_title', 100); + } + if (hasMetaIcon) { + updates.meta_icon = this.normalizeOptionalString(data.meta_icon, 'meta_icon', 50); + } + if (hasParentId) { + const parentId = this.normalizeParentId(data.parent_id); + if (parentId && parentId === permissionId) { + throw this.createError('parent_id 不能等于 permission_id', 400); + } + await this.ensureParentPermissionExists(parentId); + updates.parent_id = parentId; + } + if (hasSort) { + updates.sort = this.normalizeSort(data.sort); + } + if (hasHidden) { + updates.hidden = this.normalizeBooleanFlag(data.hidden, 'hidden'); + } + if (hasAlwaysShow) { + updates.always_show = this.normalizeBooleanFlag(data.always_show, 'always_show'); + } + if (hasStatus) { + updates.status = this.normalizeStatus(data.status); + } + + await permission.update(updates); + + return { + code: 200, + data: { + permission_id: Number(permission.id), + path: permission.path || '', + type: permission.type || '', + parent_id: permission.parent_id === null ? null : Number(permission.parent_id), + status: Number(permission.status), + }, + }; + } +} + +module.exports = SettingPermissionService; diff --git a/app/service/systems/setting/role.js b/app/service/systems/setting/role.js new file mode 100644 index 0000000..2103bf6 --- /dev/null +++ b/app/service/systems/setting/role.js @@ -0,0 +1,695 @@ +'use strict'; + +const Service = require('egg').Service; + +class SettingRoleService extends Service { + createError(message, code = 500) { + const error = new Error(message); + error.code = code; + return error; + } + + getCurrentStoreId() { + const storeId = Number(this.ctx.user && this.ctx.user.store_id); + if (!Number.isFinite(storeId) || storeId <= 0) { + throw this.createError('未识别到当前主体,无法操作角色', 400); + } + return storeId; + } + + getCurrentEmployeeId() { + const employeeId = Number(this.ctx.user && this.ctx.user.employees_id); + if (!Number.isFinite(employeeId) || employeeId <= 0) { + return null; + } + return employeeId; + } + + toPositiveNumber(value, fieldName) { + const num = Number(value); + if (!Number.isFinite(num) || num <= 0) { + throw this.createError(`${fieldName} 参数不能为空`, 400); + } + return num; + } + + async getEmployee(employeeId, options = {}) { + const { ctx } = this; + const storeId = this.getCurrentStoreId(); + const includeDisabled = options.includeDisabled === true; + const where = { + id: employeeId, + store_id: storeId, + }; + if (!includeDisabled) { + where.status = 1; + } + + const employee = await ctx.model.AccountStoreEmployee.findOne({ where }); + if (!employee) { + throw this.createError('工号不存在或无权限操作', 404); + } + return employee; + } + + normalizeRoleIds(inputRoleIds) { + if (!Array.isArray(inputRoleIds) || inputRoleIds.length === 0) { + throw this.createError('role_ids 参数不能为空', 400); + } + + const roleIds = []; + for (const roleId of inputRoleIds) { + const normalized = Number(roleId); + if (!Number.isFinite(normalized) || normalized <= 0) { + throw this.createError('role_ids 必须是正整数数组', 400); + } + roleIds.push(normalized); + } + + return Array.from(new Set(roleIds)); + } + + async findAssignableRoles(roleIds, storeId) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + const roles = await ctx.model.Role.findAll({ + where: { + id: roleIds, + status: 1, + [Op.or]: [ + { store_id: storeId }, + { store_id: 0 }, + { store_id: null }, + ], + }, + order: [[ 'id', 'ASC' ]], + }); + + if (roles.length !== roleIds.length) { + const foundRoleIds = roles.map(role => Number(role.id)); + const missingRoleIds = roleIds.filter(roleId => !foundRoleIds.includes(roleId)); + throw this.createError(`角色不存在、已禁用或超出当前主体范围:${missingRoleIds.join(',')}`, 400); + } + + return roles; + } + + async clearEmployeeCache(employee) { + const { service } = this.ctx; + await service.systems.auth.user.clearUserCache(Number(employee.account_id)); + } + + async getCurrentEmployeeRoleIds() { + const { ctx } = this; + const currentEmployeeId = this.getCurrentEmployeeId(); + if (!currentEmployeeId) { + return []; + } + + const rows = await ctx.model.EmployeeRole.findAll({ + where: { + employee_id: currentEmployeeId, + }, + attributes: [ 'role_id' ], + }); + + return Array.from(new Set(rows.map(item => Number(item.role_id)).filter(id => Number.isFinite(id) && id > 0))); + } + + collectDescendantRoleIds(roleRows, startRoleIds) { + const childrenMap = new Map(); + for (const row of roleRows) { + const parentId = Number(row.pid || 0); + if (!childrenMap.has(parentId)) { + childrenMap.set(parentId, []); + } + childrenMap.get(parentId).push(Number(row.id)); + } + + const visited = new Set(); + const stack = Array.from(startRoleIds); + while (stack.length > 0) { + const roleId = Number(stack.pop()); + if (!Number.isFinite(roleId) || roleId <= 0 || visited.has(roleId)) { + continue; + } + visited.add(roleId); + const children = childrenMap.get(roleId) || []; + for (const childId of children) { + if (!visited.has(childId)) { + stack.push(childId); + } + } + } + return visited; + } + + async buildRolePermissionMap(roleRows) { + const { service } = this.ctx; + const rows = Array.isArray(roleRows) ? roleRows : []; + const permissionMap = new Map(); + + for (const row of rows) { + const roleId = Number(row && row.id); + if (!Number.isFinite(roleId) || roleId <= 0) { + continue; + } + + const directPermissionIds = service.systems.auth.rolePermission.toApiPermissionIds(row.permissions); + permissionMap.set(roleId, directPermissionIds); + } + + return permissionMap; + } + + buildRoleTree(roleRows, rootRoleIds, selectedRoleIdSet, rolePermissionMap = new Map()) { + const nodeMap = new Map(); + for (const row of roleRows) { + const roleId = Number(row.id); + nodeMap.set(roleId, { + role_id: roleId, + role_code: row.role_code || '', + role_name: row.role_name || '', + description: row.description || '', + role_type: Number(row.role_type), + scope: Number(row.scope), + is_system: Number(row.is_system), + status: Number(row.status), + store_id: row.store_id === null ? null : Number(row.store_id), + pid: Number(row.pid || 0), + selected: selectedRoleIdSet.has(roleId), + permission_ids: rolePermissionMap.get(roleId) || [], + children: [], + }); + } + + for (const node of nodeMap.values()) { + const parent = nodeMap.get(node.pid); + if (parent) { + parent.children.push(node); + } + } + + const sortNodes = nodes => { + nodes.sort((a, b) => a.role_id - b.role_id); + for (const item of nodes) { + if (item.children && item.children.length > 0) { + sortNodes(item.children); + } + } + }; + + const roots = Array.from(rootRoleIds) + .map(roleId => nodeMap.get(Number(roleId))) + .filter(Boolean); + sortNodes(roots); + return roots; + } + + normalizeStoreScope(storeId) { + if (storeId === null || storeId === undefined) { + return 0; + } + const num = Number(storeId); + if (!Number.isFinite(num) || num <= 0) { + return 0; + } + return num; + } + + isRoleVisibleInScope(role, currentRoleRows, currentStoreId, includeSystem) { + const roleStoreScope = this.normalizeStoreScope(role.store_id); + + // 当前主体角色默认可见 + if (roleStoreScope === currentStoreId) { + return true; + } + + // includeSystem=true 时,可见系统角色 + if (includeSystem && roleStoreScope === 0) { + return true; + } + + // 当前工号若本身处于系统角色域,至少允许看到系统角色,避免空树。 + const hasSystemCurrentRole = currentRoleRows + .some(item => this.normalizeStoreScope(item.store_id) === 0); + if (hasSystemCurrentRole && roleStoreScope === 0) { + return true; + } + + return false; + } + + normalizePermissionIds(inputPermissionIds) { + if (inputPermissionIds === '*') { + return [ '*' ]; + } + + if (typeof inputPermissionIds === 'string') { + const trimmed = inputPermissionIds.trim(); + if (!trimmed) { + throw this.createError('permission_ids 参数不能为空', 400); + } + if (trimmed === '*') { + return [ '*' ]; + } + + try { + const parsed = JSON.parse(trimmed); + return this.normalizePermissionIds(parsed); + } catch (_) { + if (trimmed.includes(',')) { + return this.normalizePermissionIds(trimmed.split(',')); + } + throw this.createError('permission_ids 必须是正整数数组或 ["*"]', 400); + } + } + + if (!Array.isArray(inputPermissionIds)) { + throw this.createError('permission_ids 参数不能为空', 400); + } + + if (inputPermissionIds.some(item => typeof item === 'string' && item.trim() === '*')) { + return [ '*' ]; + } + + const permissionIds = []; + for (const permissionId of inputPermissionIds) { + const normalized = Number(permissionId); + if (!Number.isFinite(normalized) || normalized <= 0) { + throw this.createError('permission_ids 必须是正整数数组或 ["*"]', 400); + } + permissionIds.push(Math.floor(normalized)); + } + + return Array.from(new Set(permissionIds)); + } + + normalizePid(value) { + if (value === undefined || value === null || value === '') { + return 0; + } + const pid = Number(value); + if (!Number.isFinite(pid) || pid < 0) { + throw this.createError('pid 参数不合法', 400); + } + return pid; + } + + async getManageableRole(roleId, options = {}) { + const { ctx } = this; + const storeId = this.getCurrentStoreId(); + const includeDisabled = options.includeDisabled === true; + + const where = { + id: roleId, + store_id: storeId, + is_system: 0, + }; + if (!includeDisabled) { + where.status = 1; + } + + const role = await ctx.model.Role.findOne({ where }); + if (!role) { + throw this.createError('角色不存在、无权限操作或为系统预设角色', 404); + } + return role; + } + + async validatePermissionSet(permissionIds) { + const { ctx } = this; + if (!Array.isArray(permissionIds) || permissionIds.length === 0) { + return; + } + + if (permissionIds.includes('*')) { + return; + } + + const existingPermissions = await ctx.model.Permission.findAll({ + where: { + id: permissionIds, + status: 1, + }, + attributes: [ 'id' ], + raw: true, + }); + if (existingPermissions.length !== permissionIds.length) { + const found = new Set(existingPermissions.map(item => Number(item.id))); + const missing = permissionIds.filter(id => !found.has(id)); + throw this.createError(`权限不存在或已禁用:${missing.join(',')}`, 400); + } + } + + async replaceRolePermissions(roleId, permissionIds, transaction) { + return await this.ctx.service.systems.auth.rolePermission.assignPermissions(roleId, permissionIds, { + transaction, + }); + } + + async clearRoleUsersCache(roleId) { + const { ctx, service } = this; + const storeId = this.getCurrentStoreId(); + + const employeeRoleRows = await ctx.model.EmployeeRole.findAll({ + where: { + role_id: roleId, + }, + include: [ + { + model: ctx.model.AccountStoreEmployee, + as: 'employee', + attributes: [ 'account_id' ], + where: { + store_id: storeId, + status: 1, + }, + required: true, + }, + ], + raw: false, + }); + + const accountIds = Array.from(new Set(employeeRoleRows + .map(item => Number(item.employee && item.employee.account_id)) + .filter(id => Number.isFinite(id) && id > 0))); + + for (const accountId of accountIds) { + await service.systems.auth.user.clearUserCache(accountId); + } + } + + async list(data = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const storeId = this.getCurrentStoreId(); + const includeDisabled = data.includeDisabled === true; + const includeSystem = data.includeSystem === true; + const currentEmployeeId = this.getCurrentEmployeeId(); + + let employee = null; + if (currentEmployeeId) { + employee = await this.getEmployee(currentEmployeeId, { + includeDisabled: true, + }); + } + + // 先拉取当前主体 + 系统角色域,后续按可见规则二次收敛。 + const roleWhere = { + status: includeDisabled ? { [Op.in]: [0, 1] } : 1, + [Op.or]: [ { store_id: storeId }, { store_id: 0 }, { store_id: null } ], + }; + + const roleRows = await ctx.model.Role.findAll({ + where: roleWhere, + attributes: [ + 'id', + 'role_code', + 'role_name', + 'description', + 'role_type', + 'scope', + 'is_system', + 'status', + 'store_id', + 'pid', + 'permissions', + ], + order: [ + [ 'is_system', 'DESC' ], + [ 'id', 'ASC' ], + ], + }); + + const currentRoleIds = await this.getCurrentEmployeeRoleIds(); + if (currentRoleIds.length === 0) { + return { + code: 200, + data: { + employee_id: employee ? Number(employee.id) : null, + roles: [], + }, + }; + } + + const roleMap = new Map(roleRows.map(item => [ Number(item.id), item ])); + const currentRoleRows = currentRoleIds + .map(roleId => roleMap.get(roleId)) + .filter(Boolean); + + if (currentRoleRows.length === 0) { + return { + code: 200, + data: { + employee_id: employee ? Number(employee.id) : null, + roles: [], + }, + }; + } + + const currentRoleIdSet = new Set(currentRoleRows.map(item => Number(item.id))); + + // 仅返回当前角色的下级角色树,不返回自己及同级角色。 + const subordinateRootRoleIds = new Set(roleRows + .filter(item => currentRoleIdSet.has(Number(item.pid || 0))) + .filter(item => this.isRoleVisibleInScope(item, currentRoleRows, storeId, includeSystem)) + .map(item => Number(item.id))); + + if (subordinateRootRoleIds.size === 0) { + return { + code: 200, + data: { + employee_id: employee ? Number(employee.id) : null, + roles: [], + }, + }; + } + + const visibleRoleIds = this.collectDescendantRoleIds(roleRows, Array.from(subordinateRootRoleIds)); + + const visibleRoleRows = roleRows + .filter(item => visibleRoleIds.has(Number(item.id))) + .filter(item => this.isRoleVisibleInScope(item, currentRoleRows, storeId, includeSystem)); + const rootRoleIds = new Set(visibleRoleRows + .filter(item => subordinateRootRoleIds.has(Number(item.id))) + .map(item => Number(item.id))); + + let selectedRoleIdSet = new Set(); + if (employee) { + const employeeRoles = await ctx.model.EmployeeRole.findAll({ + where: { + employee_id: employee.id, + }, + }); + selectedRoleIdSet = new Set(employeeRoles.map(item => Number(item.role_id))); + } + + const rolePermissionMap = await this.buildRolePermissionMap(visibleRoleRows); + const roles = this.buildRoleTree(visibleRoleRows, rootRoleIds, selectedRoleIdSet, rolePermissionMap); + + return { + code: 200, + data: { + employee_id: employee ? Number(employee.id) : null, + roles, + }, + }; + } + + async permission(data = {}) { + return this.ctx.service.systems.setting.permission.list(data); + } + + async add(data = {}) { + const { ctx } = this; + + const storeId = this.getCurrentStoreId(); + const roleCode = typeof data.role_code === 'string' ? data.role_code.trim() : ''; + const roleName = typeof data.role_name === 'string' ? data.role_name.trim() : ''; + const description = typeof data.description === 'string' ? data.description.trim() : ''; + const roleType = Number(data.role_type || 1); + const scope = Number(data.scope || 1); + const status = data.status === 0 || data.status === '0' ? 0 : 1; + const pid = this.normalizePid(data.pid); + const permissionIds = this.normalizePermissionIds(data.permission_ids || data.permissionIds || []); + const creatorId = Number(this.ctx.user && this.ctx.user.id); + + if (!roleCode) { + throw this.createError('role_code 参数不能为空', 400); + } + if (!roleName) { + throw this.createError('role_name 参数不能为空', 400); + } + if (!Number.isFinite(creatorId) || creatorId <= 0) { + throw this.createError('未识别到当前账号,无法创建角色', 400); + } + + await this.validatePermissionSet(permissionIds); + + const transaction = await ctx.model.transaction(); + let createdRole = null; + try { + createdRole = await ctx.model.Role.create({ + role_code: roleCode, + role_name: roleName, + description, + role_type: roleType, + scope, + is_system: 0, + status, + created_by: creatorId, + store_id: storeId, + pid, + }, { transaction }); + + await this.replaceRolePermissions(Number(createdRole.id), permissionIds, transaction); + await transaction.commit(); + } catch (error) { + await transaction.rollback(); + if (error && error.name === 'SequelizeUniqueConstraintError') { + throw this.createError('role_code 已存在', 409); + } + throw error; + } + + return { + code: 200, + data: { + role_id: Number(createdRole.id), + role_code: createdRole.role_code, + role_name: createdRole.role_name, + permission_ids: permissionIds, + created: true, + }, + }; + } + + async delete(data = {}) { + const { ctx } = this; + + const roleIds = this.normalizeRoleIds(data.ids); + const roles = []; + for (const roleId of roleIds) { + const role = await this.getManageableRole(roleId, { + includeDisabled: true, + }); + roles.push(role); + } + + const deletedIds = []; + const alreadyDeletedIds = []; + + const transaction = await ctx.model.transaction(); + try { + for (const role of roles) { + const roleId = Number(role.id); + if (Number(role.status) === 0) { + alreadyDeletedIds.push(roleId); + continue; + } + + await role.update({ + status: 0, + updated_at: new Date(), + }, { transaction }); + deletedIds.push(roleId); + } + + await transaction.commit(); + } catch (error) { + await transaction.rollback(); + throw error; + } + + for (const roleId of deletedIds) { + await this.clearRoleUsersCache(roleId); + } + + return { + code: 200, + data: { + ids: roleIds, + deleted_ids: deletedIds, + already_deleted_ids: alreadyDeletedIds, + status: 'deleted', + }, + }; + } + + async update(data = {}) { + const { ctx } = this; + + const roleId = this.toPositiveNumber(data.role_id || data.roleId, 'role_id'); + const role = await this.getManageableRole(roleId, { + includeDisabled: true, + }); + + const hasRoleName = Object.prototype.hasOwnProperty.call(data, 'role_name'); + const hasDescription = Object.prototype.hasOwnProperty.call(data, 'description'); + const hasStatus = Object.prototype.hasOwnProperty.call(data, 'status'); + const hasPid = Object.prototype.hasOwnProperty.call(data, 'pid'); + const hasPermissionIds = Object.prototype.hasOwnProperty.call(data, 'permission_ids') + || Object.prototype.hasOwnProperty.call(data, 'permissionIds'); + + if (!hasRoleName && !hasDescription && !hasStatus && !hasPid && !hasPermissionIds) { + throw this.createError('至少需要更新角色信息或 permission_ids', 400); + } + if (!hasPermissionIds) { + throw this.createError('permission_ids 参数不能为空,角色权限需一次性提交', 400); + } + + const permissionIds = this.normalizePermissionIds(data.permission_ids || data.permissionIds || []); + await this.validatePermissionSet(permissionIds); + + const updates = {}; + if (hasRoleName) { + const roleName = typeof data.role_name === 'string' ? data.role_name.trim() : ''; + if (!roleName) { + throw this.createError('role_name 参数不能为空', 400); + } + updates.role_name = roleName; + } + if (hasDescription) { + updates.description = typeof data.description === 'string' ? data.description.trim() : ''; + } + if (hasStatus) { + const status = data.status === 0 || data.status === '0' ? 0 : 1; + updates.status = status; + } + if (hasPid) { + updates.pid = this.normalizePid(data.pid); + } + updates.updated_at = new Date(); + + const transaction = await ctx.model.transaction(); + try { + if (Object.keys(updates).length > 0) { + await role.update(updates, { transaction }); + } + + await this.replaceRolePermissions(roleId, permissionIds, transaction); + await transaction.commit(); + } catch (error) { + await transaction.rollback(); + if (error && error.name === 'SequelizeUniqueConstraintError') { + throw this.createError('角色信息冲突(可能 role_code 重复)', 409); + } + throw error; + } + + await this.clearRoleUsersCache(roleId); + + return { + code: 200, + data: { + role_id: roleId, + role_name: role.role_name, + permission_ids: permissionIds, + }, + }; + } +} + +module.exports = SettingRoleService; diff --git a/app/service/systems/setting/store_warehouse.js b/app/service/systems/setting/store_warehouse.js new file mode 100644 index 0000000..53e464a --- /dev/null +++ b/app/service/systems/setting/store_warehouse.js @@ -0,0 +1,711 @@ +'use strict'; + +const crypto = require('node:crypto'); +const Service = require('egg').Service; + +const SIGN_TEMP_EXPIRE_SECONDS = 600; +const AUTH_STATUS_LABELS = Object.freeze({ + 1: '申请中', + 2: '已通过', + 3: '已拒绝', + 4: '已解除', + 5: '已过期', +}); + +class SettingStoreWarehouseService extends Service { + createError(message, code = 500) { + const error = new Error(message); + error.code = code; + return error; + } + + getCurrentStoreId() { + const storeId = Number(this.ctx.user && this.ctx.user.store_id); + if (!Number.isFinite(storeId) || storeId <= 0) { + throw this.createError('未识别到当前主体,无法操作签约关系', 400); + } + return storeId; + } + + getCurrentAccountId() { + const accountId = Number(this.ctx.user && this.ctx.user.id); + if (!Number.isFinite(accountId) || accountId <= 0) { + throw this.createError('未识别到当前登录账号', 401); + } + return accountId; + } + + toPositiveNumber(value, fieldName, options = {}) { + const { allowEmpty = false } = options; + if (allowEmpty && (value === undefined || value === null || value === '')) { + return null; + } + + const num = Number(value); + if (!Number.isFinite(num) || num <= 0) { + throw this.createError(`${fieldName} 参数不能为空`, 400); + } + return num; + } + + normalizePage(value, fieldName, defaultValue, maxValue) { + if (value === undefined || value === null || value === '') { + return defaultValue; + } + const num = Number(value); + if (!Number.isFinite(num) || num <= 0) { + throw this.createError(`${fieldName} 参数不合法`, 400); + } + return Math.min(Math.floor(num), maxValue); + } + + normalizeStatusFlag(value, fieldName, defaultValue = null) { + if (value === undefined || value === null || value === '') { + return defaultValue; + } + const num = Number(value); + if (num === 0 || num === 1) { + return num; + } + throw this.createError(`${fieldName} 参数不合法`, 400); + } + + normalizeAuthStatus(value) { + if (value === undefined || value === null || value === '') { + return null; + } + const num = Number(value); + if ([ 1, 2, 3, 4, 5 ].includes(num)) { + return num; + } + throw this.createError('auth_status 参数不合法', 400); + } + + normalizeNonNegativeInteger(value, fieldName, defaultValue = 0) { + if (value === undefined || value === null || value === '') { + return defaultValue; + } + const num = Number(value); + if (!Number.isFinite(num) || num < 0) { + throw this.createError(`${fieldName} 参数不合法`, 400); + } + return Math.floor(num); + } + + normalizeText(value, fieldName, maxLength = 500) { + if (value === undefined || value === null) { + return null; + } + const normalized = String(value).trim(); + if (normalized.length > maxLength) { + throw this.createError(`${fieldName} 长度不能超过 ${maxLength}`, 400); + } + return normalized; + } + + normalizeDate(value, fieldName, options = {}) { + const { allowNull = true } = options; + if (value === undefined || value === null || value === '') { + if (allowNull) { + return null; + } + throw this.createError(`${fieldName} 参数不能为空`, 400); + } + + const date = value instanceof Date ? value : new Date(value); + if (Number.isNaN(date.getTime())) { + throw this.createError(`${fieldName} 参数不合法`, 400); + } + return date; + } + + normalizeSignAction(value) { + if (value === undefined || value === null || value === '') { + return ''; + } + + const action = String(value).trim(); + if ([ 'preview', 'confirm' ].includes(action)) { + return action; + } + throw this.createError('action 参数不合法', 400); + } + + normalizeTempCode(value) { + const code = String(value || '').trim().toUpperCase(); + if (!code) { + throw this.createError('temp_code 参数不能为空', 400); + } + return code; + } + + getTempCodeCacheKey(tempCode) { + return `store_warehouse:sign:${tempCode}`; + } + + createTempCode() { + return crypto.randomBytes(6).toString('hex').toUpperCase(); + } + + pickRemaskField(currentSubject) { + return currentSubject && currentSubject.isWarehouse ? 'store_remask' : 'warehouse_remask'; + } + + resolveRemaskValue(data, currentSubject) { + const raw = data.remask !== undefined + ? data.remask + : (currentSubject && currentSubject.isWarehouse ? data.store_remask : data.warehouse_remask); + return this.normalizeText(raw, 'remask', 50); + } + + buildCurrentRemaskPatch(data, currentSubject) { + const remask = this.resolveRemaskValue(data, currentSubject); + if (remask === null) { + return {}; + } + + return { + [this.pickRemaskField(currentSubject)]: remask, + }; + } + + requireCurrentRemaskPatch(data, currentSubject) { + const patch = this.buildCurrentRemaskPatch(data, currentSubject); + if (!Object.keys(patch).length) { + throw this.createError('remask 参数不能为空', 400); + } + return patch; + } + + async saveTempSignPayload(payload) { + const now = Date.now(); + const expiresAt = new Date(now + SIGN_TEMP_EXPIRE_SECONDS * 1000).toISOString(); + const tempCode = this.createTempCode(); + await this.app.setCacheAsync(this.getTempCodeCacheKey(tempCode), { + ...payload, + expires_at: expiresAt, + }, SIGN_TEMP_EXPIRE_SECONDS); + return { + tempCode, + expiresAt, + expiresIn: SIGN_TEMP_EXPIRE_SECONDS, + }; + } + + async getTempSignPayload(tempCode) { + const normalizedCode = this.normalizeTempCode(tempCode); + const payload = await this.app.getCacheAsync(this.getTempCodeCacheKey(normalizedCode)); + if (!payload) { + throw this.createError('临时码无效或已过期', 404); + } + return { + tempCode: normalizedCode, + payload, + }; + } + + async clearTempSignPayload(tempCode) { + const cacheRedis = this.app.redis && this.app.redis.get ? this.app.redis.get('cache') : null; + if (cacheRedis && cacheRedis.del) { + await cacheRedis.del(this.getTempCodeCacheKey(tempCode)); + return; + } + await this.app.setCacheAsync(this.getTempCodeCacheKey(tempCode), { consumed: true }, 1); + } + + buildTempSignView(tempCode, payload, currentSubject) { + const participantIds = [ Number(payload.initiator_subject_id || 0), Number(payload.counterparty_id || 0) ]; + const currentSubjectId = Number(currentSubject && currentSubject.id); + const expiresAt = payload.expires_at || null; + const expiresMs = expiresAt ? new Date(expiresAt).getTime() : 0; + + return { + mode: 'preview', + temp_code: tempCode, + expires_at: expiresAt, + expires_in: expiresMs ? Math.max(0, Math.ceil((expiresMs - Date.now()) / 1000)) : 0, + is_participant: participantIds.includes(currentSubjectId), + can_confirm: currentSubjectId > 0 && currentSubjectId === Number(payload.counterparty_id || 0), + initiator: { + id: Number(payload.initiator_subject_id || 0), + role: payload.initiator_role || '', + name: payload.initiator_name || '', + }, + counterparty: { + id: Number(payload.counterparty_id || 0), + role: payload.counterparty_role || '', + name: payload.counterparty_name || '', + }, + sign_info: { + store_id: Number(payload.store_id || 0), + warehouse_id: Number(payload.warehouse_id || 0), + auth_start: payload.auth_start || null, + auth_end: payload.auth_end || null, + print_quantity: Number(payload.print_quantity || 0), + apply_reason: payload.apply_reason || '', + remask: payload.remask || '', + }, + }; + } + + async getCurrentSubject() { + const { ctx } = this; + const storeId = this.getCurrentStoreId(); + const subject = await ctx.model.Store.findOne({ + where: { + id: storeId, + }, + attributes: [ 'id', 'company_name', 'project', 'status' ], + }); + + if (!subject) { + throw this.createError('当前主体不存在', 404); + } + + return { + id: Number(subject.id), + company_name: subject.company_name || '', + project: subject.project || '', + isWarehouse: subject.project === 'warehouse', + status: Number(subject.status || 0), + }; + } + + async getCounterparty(counterpartyId, expectedRole) { + const { ctx } = this; + const counterparty = await ctx.model.Store.findOne({ + where: { + id: counterpartyId, + }, + attributes: [ 'id', 'company_name', 'project', 'status' ], + }); + + if (!counterparty) { + throw this.createError('签约对象不存在', 404); + } + + const isWarehouse = counterparty.project === 'warehouse'; + if (expectedRole === 'warehouse' && !isWarehouse) { + throw this.createError('目标对象不是仓库主体,无法签约', 400); + } + if (expectedRole === 'store' && isWarehouse) { + throw this.createError('目标对象不是货主主体,无法签约', 400); + } + + return counterparty; + } + + buildListWhere(data, currentSubject) { + const where = {}; + + if (currentSubject.isWarehouse) { + where.warehouse_id = currentSubject.id; + } else { + where.store_id = currentSubject.id; + } + + const relationId = this.toPositiveNumber(data.id, 'id', { allowEmpty: true }); + if (relationId) { + where.id = relationId; + } + + const rawCounterpartyId = data.counterparty_id !== undefined + ? data.counterparty_id + : (currentSubject.isWarehouse ? data.store_id : data.warehouse_id); + const counterpartyId = this.toPositiveNumber(rawCounterpartyId, 'counterparty_id', { allowEmpty: true }); + if (counterpartyId) { + if (currentSubject.isWarehouse) { + where.store_id = counterpartyId; + } else { + where.warehouse_id = counterpartyId; + } + } + + const authStatus = this.normalizeAuthStatus(data.auth_status); + if (authStatus !== null) { + where.auth_status = authStatus; + } + + const useStatus = this.normalizeStatusFlag(data.use_status, 'use_status', null); + if (useStatus !== null) { + where.use_status = useStatus; + } + + return where; + } + + getRelationIncludes() { + const { ctx } = this; + return [ + { + model: ctx.model.Store, + as: 'store', + attributes: [ 'id', 'company_name', 'project', 'status' ], + required: false, + }, + { + model: ctx.model.Store, + as: 'warehouse', + attributes: [ 'id', 'company_name', 'project', 'status' ], + required: false, + }, + ]; + } + + resolvePairIds(data, currentSubject) { + const fieldName = currentSubject.isWarehouse ? 'store_id / counterparty_id' : 'warehouse_id / counterparty_id'; + const rawCounterpartyId = data.counterparty_id !== undefined + ? data.counterparty_id + : (currentSubject.isWarehouse ? data.store_id : data.warehouse_id); + const counterpartyId = this.toPositiveNumber(rawCounterpartyId, fieldName); + + if (currentSubject.isWarehouse) { + return { + storeId: counterpartyId, + warehouseId: currentSubject.id, + counterpartyId, + }; + } + + return { + storeId: currentSubject.id, + warehouseId: counterpartyId, + counterpartyId, + }; + } + + serializeRelation(relation, currentSubject) { + const item = relation && typeof relation.get === 'function' + ? relation.get({ plain: true }) + : (relation || {}); + + const authStatus = Number(item.auth_status || 0); + const currentIsWarehouse = !!(currentSubject && currentSubject.isWarehouse); + const counterparty = currentIsWarehouse ? item.store : item.warehouse; + const storeName = item.store_remask || (item.store && item.store.company_name ? item.store.company_name : ''); + const warehouseName = item.warehouse_remask || (item.warehouse && item.warehouse.company_name ? item.warehouse.company_name : ''); + const counterpartyName = currentIsWarehouse ? storeName : warehouseName; + + let isAuthValid = false; + let remainingDays = 0; + if (authStatus === 2 && item.auth_start && item.auth_end) { + const now = Date.now(); + const start = new Date(item.auth_start).getTime(); + const end = new Date(item.auth_end).getTime(); + if (!Number.isNaN(start) && !Number.isNaN(end) && now >= start && now <= end) { + isAuthValid = true; + remainingDays = Math.max(0, Math.ceil((end - now) / (1000 * 60 * 60 * 24))); + } + } + + return { + id: Number(item.id || 0), + store_id: Number(item.store_id || 0), + store_name: storeName, + warehouse_id: Number(item.warehouse_id || 0), + warehouse_name: warehouseName, + counterparty_id: counterparty && counterparty.id ? Number(counterparty.id) : 0, + counterparty_name: counterpartyName, + current_subject_role: currentIsWarehouse ? 'warehouse' : 'store', + auth_status: authStatus, + auth_status_label: AUTH_STATUS_LABELS[authStatus] || '', + apply_reason: item.apply_reason || '', + review_comment: item.review_comment || '', + apply_time: item.apply_time || null, + review_time: item.review_time || null, + auth_start: item.auth_start || null, + auth_end: item.auth_end || null, + actual_end: item.actual_end || null, + print_quantity: Number(item.print_quantity || 0), + applied_by: item.applied_by ? Number(item.applied_by) : null, + reviewed_by: item.reviewed_by ? Number(item.reviewed_by) : null, + ended_by: item.ended_by ? Number(item.ended_by) : null, + remask: currentIsWarehouse ? (item.store_remask || '') : (item.warehouse_remask || ''), + use_status: Number(item.use_status || 0), + is_auth_valid: isAuthValid, + remaining_days: remainingDays, + }; + } + + async findScopedRelation(data, currentSubject, transaction) { + const { ctx } = this; + const where = currentSubject.isWarehouse + ? { warehouse_id: currentSubject.id } + : { store_id: currentSubject.id }; + + const relationId = this.toPositiveNumber(data.id, 'id', { allowEmpty: true }); + if (relationId) { + where.id = relationId; + } else { + const pair = this.resolvePairIds(data, currentSubject); + where.store_id = pair.storeId; + where.warehouse_id = pair.warehouseId; + } + + const relation = await ctx.model.StoreWarehouse.findOne({ + where, + include: this.getRelationIncludes(), + transaction, + }); + + if (!relation) { + throw this.createError('签约关系不存在或无权限操作', 404); + } + + return relation; + } + + async list(data = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const currentSubject = await this.getCurrentSubject(); + const page = this.normalizePage(data.page, 'page', 1, 1000000); + const pageSize = this.normalizePage(data.page_size || data.pageSize, 'page_size', 20, 200); + const offset = (page - 1) * pageSize; + const where = this.buildListWhere(data, currentSubject); + const keyword = typeof data.keyword === 'string' ? data.keyword.trim() : ''; + + if (keyword) { + where[Op.or] = [ + { store_remask: { [Op.like]: `%${keyword}%` } }, + { warehouse_remask: { [Op.like]: `%${keyword}%` } }, + { '$store.company_name$': { [Op.like]: `%${keyword}%` } }, + { '$warehouse.company_name$': { [Op.like]: `%${keyword}%` } }, + ]; + } + + const { rows, count } = await ctx.model.StoreWarehouse.findAndCountAll({ + where, + include: this.getRelationIncludes(), + order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]], + offset, + limit: pageSize, + distinct: true, + }); + + return { + code: 200, + data: { + list: rows.map(item => this.serializeRelation(item, currentSubject)), + total: Number(count || 0), + page, + page_size: pageSize, + current_subject: { + store_id: currentSubject.id, + company_name: currentSubject.company_name, + role: currentSubject.isWarehouse ? 'warehouse' : 'store', + }, + }, + }; + } + + async sign(data = {}) { + const action = this.normalizeSignAction(data.action || data.mode); + if (data.temp_code || data.tempCode || action === 'preview') { + const { ctx } = this; + const transaction = await ctx.model.transaction(); + + try { + const currentSubject = await this.getCurrentSubject(); + const accountId = this.getCurrentAccountId(); + const { tempCode, payload } = await this.getTempSignPayload(data.temp_code || data.tempCode); + const isParticipant = [ Number(payload.initiator_subject_id || 0), Number(payload.counterparty_id || 0) ] + .includes(Number(currentSubject.id)); + + if (!isParticipant) { + throw this.createError('当前主体无权使用该临时码', 403); + } + + if (action === 'preview' || data.preview === 1 || data.preview === '1') { + await transaction.rollback(); + return { + code: 200, + data: this.buildTempSignView(tempCode, payload, currentSubject), + }; + } + + if (Number(currentSubject.id) !== Number(payload.counterparty_id || 0)) { + throw this.createError('需由对方主体确认后才可生效', 400); + } + + const relationPatch = { + store_id: Number(payload.store_id || 0), + warehouse_id: Number(payload.warehouse_id || 0), + auth_status: 2, + apply_reason: payload.apply_reason || '', + apply_time: payload.created_at ? new Date(payload.created_at) : new Date(), + print_quantity: Number(payload.print_quantity || 0), + review_time: new Date(), + auth_start: payload.auth_start ? new Date(payload.auth_start) : new Date(), + auth_end: payload.auth_end ? new Date(payload.auth_end) : null, + actual_end: null, + applied_by: Number(payload.initiated_by || 0) || accountId, + reviewed_by: accountId, + ended_by: null, + use_status: 1, + }; + + if (payload.store_remask !== undefined) { + relationPatch.store_remask = payload.store_remask; + } + if (payload.warehouse_remask !== undefined) { + relationPatch.warehouse_remask = payload.warehouse_remask; + } + Object.assign(relationPatch, this.buildCurrentRemaskPatch(data, currentSubject)); + + let relation = await ctx.model.StoreWarehouse.findOne({ + where: { + store_id: relationPatch.store_id, + warehouse_id: relationPatch.warehouse_id, + }, + transaction, + }); + const isCreate = !relation; + + if (relation) { + await relation.update(relationPatch, { transaction }); + } else { + relation = await ctx.model.StoreWarehouse.create(relationPatch, { transaction }); + } + + const result = await ctx.model.StoreWarehouse.findByPk(relation.id, { + include: this.getRelationIncludes(), + transaction, + }); + + await this.clearTempSignPayload(tempCode); + await transaction.commit(); + + return { + code: 200, + data: { + mode: 'confirm', + temp_code: tempCode, + contract: this.serializeRelation(result, currentSubject), + action: isCreate ? 'create' : 'update', + }, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + const currentSubject = await this.getCurrentSubject(); + const accountId = this.getCurrentAccountId(); + const pair = this.resolvePairIds(data, currentSubject); + const counterparty = await this.getCounterparty(pair.counterpartyId, currentSubject.isWarehouse ? 'store' : 'warehouse'); + const authStart = this.normalizeDate(data.auth_start, 'auth_start', { allowNull: true }) || new Date(); + const authEnd = this.normalizeDate(data.auth_end, 'auth_end', { allowNull: true }); + if (authEnd && authStart.getTime() > authEnd.getTime()) { + throw this.createError('auth_end 不能早于 auth_start', 400); + } + + const remask = this.resolveRemaskValue(data, currentSubject); + const payload = { + initiated_by: accountId, + initiator_subject_id: currentSubject.id, + initiator_role: currentSubject.isWarehouse ? 'warehouse' : 'store', + initiator_name: currentSubject.company_name, + counterparty_id: Number(counterparty.id || 0), + counterparty_role: currentSubject.isWarehouse ? 'store' : 'warehouse', + counterparty_name: counterparty.company_name || '', + store_id: pair.storeId, + warehouse_id: pair.warehouseId, + auth_start: authStart.toISOString(), + auth_end: authEnd ? authEnd.toISOString() : null, + print_quantity: this.normalizeNonNegativeInteger(data.print_quantity, 'print_quantity', 0), + apply_reason: this.normalizeText(data.apply_reason, 'apply_reason', 2000), + remask: remask || '', + created_at: new Date().toISOString(), + ...this.buildCurrentRemaskPatch(data, currentSubject), + }; + + const signPayload = await this.saveTempSignPayload(payload); + + return { + code: 200, + data: { + mode: 'initiate', + temp_code: signPayload.tempCode, + expires_at: signPayload.expiresAt, + expires_in: signPayload.expiresIn, + can_confirm: false, + current_subject: { + store_id: currentSubject.id, + company_name: currentSubject.company_name, + role: currentSubject.isWarehouse ? 'warehouse' : 'store', + }, + counterparty: { + id: Number(counterparty.id || 0), + company_name: counterparty.company_name || '', + role: currentSubject.isWarehouse ? 'store' : 'warehouse', + }, + }, + }; + } + + async rename(data = {}) { + const { ctx } = this; + const transaction = await ctx.model.transaction(); + + try { + const currentSubject = await this.getCurrentSubject(); + const relation = await this.findScopedRelation(data, currentSubject, transaction); + const relationPatch = this.requireCurrentRemaskPatch(data, currentSubject); + + await relation.update(relationPatch, { transaction }); + + const result = await ctx.model.StoreWarehouse.findByPk(relation.id, { + include: this.getRelationIncludes(), + transaction, + }); + + await transaction.commit(); + + return { + code: 200, + data: { + contract: this.serializeRelation(result, currentSubject), + }, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + async unbind(data = {}) { + const { ctx } = this; + const transaction = await ctx.model.transaction(); + + try { + const currentSubject = await this.getCurrentSubject(); + const relation = await this.findScopedRelation(data, currentSubject, transaction); + const nextUseStatus = this.normalizeStatusFlag(data.use_status, 'use_status', 0); + + await relation.update({ + use_status: nextUseStatus, + }, { transaction }); + + const result = await ctx.model.StoreWarehouse.findByPk(relation.id, { + include: this.getRelationIncludes(), + transaction, + }); + + await transaction.commit(); + + return { + code: 200, + data: { + contract: this.serializeRelation(result, currentSubject), + }, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } +} + +module.exports = SettingStoreWarehouseService; diff --git a/app/service/systems/storage/receiving.js b/app/service/systems/storage/receiving.js index 28f8d6f..4a899a8 100644 --- a/app/service/systems/storage/receiving.js +++ b/app/service/systems/storage/receiving.js @@ -313,14 +313,23 @@ class ReceivingService extends Service { where: { business_type: 'receivingItem', business_id: { [Op.in]: receivingItemsIds }, - } + }, + include: [{ + model: ctx.model.File, + as: 'file', + attributes: ['file_url'], + required: true, + }], }); - // 将图片按明细ID分组,eggjs 不能使用forEach异步处理,所以改为同步处理 + // 将图片按明细ID分组,并转换为前端可直接使用的链接 for (const image of receivingItemsImages) { if (!itemImagesMap[image.business_id]) { itemImagesMap[image.business_id] = []; } - itemImagesMap[image.business_id].push(image); + itemImagesMap[image.business_id].push({ + id: image.file_id, + url: image.file.file_url, + }); } } // 5. 将图片合并到对应的明细中 @@ -335,11 +344,20 @@ class ReceivingService extends Service { where: { business_type: 'receiving', business_id: id, - } + }, + include: [{ + model: ctx.model.File, + as: 'file', + attributes: ['file_url'], + required: true, + }], }); // 7. 组装返回数据 - receiving.dataValues.details = items; // 包含图片的明细数据 - receiving.dataValues.images = receivingImages; // 包含主表图片 + receiving.dataValues.details = items; // 包含图片链接的明细数据 + receiving.dataValues.images = receivingImages.map(image => ({ + id: image.file_id, + url: image.file.file_url, + })); // 包含主表图片链接 receiving.dataValues.pagination = pagination; // 包含分页信息 return { code: 200, message: '查询成功', data: { receiving } }; @@ -634,6 +652,48 @@ class ReceivingService extends Service { } } + buildReceivingPrefix(date = new Date()) { + const dateStr = Math.floor(date.getTime() / (1000 * 60 * 60 * 24)); + return `R${dateStr}`; + } + + async generateNextReceivingNumber(prefix) { + const { app } = this.ctx; + const suffixStartIndex = prefix.length + 1; + + const maxReceiving = await app.model.Receiving.findOne({ + attributes: [ 'receiving_number' ], + where: { + receiving_number: { + [app.Sequelize.Op.like]: `${prefix}%`, + }, + }, + order: [ + [app.Sequelize.literal(`CAST(SUBSTRING(receiving_number, ${suffixStartIndex}) AS UNSIGNED)`), 'DESC'], + [ 'receiving_number', 'DESC' ], + ], + }); + + let sequence = 1; + if (maxReceiving && maxReceiving.receiving_number) { + const lastNumStr = String(maxReceiving.receiving_number).slice(prefix.length); + const lastNum = Number.parseInt(lastNumStr, 10); + if (Number.isFinite(lastNum) && lastNum > 0) { + sequence = lastNum + 1; + } + } + + const seqLen = Math.max(3, String(sequence).length); + return `${prefix}${String(sequence).padStart(seqLen, '0')}`; + } + + isReceivingNumberDuplicateError(error) { + const parentCode = error && error.parent && error.parent.code; + const sqlMessage = String((error && error.parent && error.parent.sqlMessage) || error.message || ''); + return parentCode === 'ER_DUP_ENTRY' + && /uk_receiving_number|receiving_number/i.test(sqlMessage); + } + /** * 创建收货单并生成收货单号。 * @param {Object} data 创建参数 @@ -666,36 +726,12 @@ class ReceivingService extends Service { id: creator_id, }; - // 2. 生成收货单号 (格式: R + 时间戳的day + 3位序列号,如: RR20231215001) + // 2. 生成收货单号。注意:`wms_receiving.receiving_number` 在数据库中是全局唯一索引, + // 不能按 warehouse_id 各自从 001 开始,否则跨仓会撞号;并发创建时也需要重试兜底。 const now = new Date(); console.log('当前时间:', now); - const dateStr = Math.floor(now.getTime() / (1000 * 60 * 60 * 24)); // 时间戳到今日的天数 - const prefix = `R${dateStr}`; + const prefix = this.buildReceivingPrefix(now); - // 查找当天最大的收货单号 - const maxReceiving = await app.model.Receiving.findOne({ - where: { - receiving_number: { - [app.Sequelize.Op.like]: `${prefix}%`, - }, - warehouse_id - }, - order: [['receiving_number', 'DESC']], - }); - - let sequence = 1; - if (maxReceiving) { - // 提取最大收货单号的序号部分 - const lastNumStr = maxReceiving.receiving_number.replace(prefix, ''); - const lastNum = parseInt(lastNumStr); - sequence = lastNum + 1; - } - - // 序号动态长度:<1000用3位,<10000用4位,>=10000用5位 - let seqLen = 3; - if (sequence >= 1000 && sequence < 10000) seqLen = 4; - if (sequence >= 10000) seqLen = 5; - const receiving_number = `${prefix}${sequence.toString().padStart(seqLen, '0')}`; // 3. 获取店铺名称(如果有货主) let store_name = null; if (store_id) { @@ -711,33 +747,56 @@ class ReceivingService extends Service { } } - // 4. 创建收货单记录 - const receivingData = { - receiving_number, - creator_id, - creator_snapshot: JSON.stringify(creator_snapshot), - status: status || 'receiving', - detail_status: 'unmatched', - storage_status: 'none', - delivery_method, - license_plate: delivery_method === 'truck' ? license_plate : null, - tracking_number: delivery_method !== 'truck' && delivery_method !== 'other' ? tracking_number : null, - loading_method, - video_device_id: video_device_id || null, - total_boxes: parseInt(total_boxes) || 0, - total_pallets: parseInt(total_pallets) || 0, - total_items: 0, - total_quantity: 0, - warehouse_id, - remark: remark || null, - store_name, - store_id: store_id || null, - receiving_start_time: new Date(), - is_deleted: false, - }; + // 4. 创建收货单记录(并发下若撞到唯一键则自动重试取下一个号) + const maxCreateRetries = 5; + let result = null; + let lastCreateError = null; - // 5. 保存到数据库 - const result = await app.model.Receiving.create(receivingData); + for (let attempt = 1; attempt <= maxCreateRetries; attempt++) { + const receiving_number = await this.generateNextReceivingNumber(prefix); + const receivingData = { + receiving_number, + creator_id, + creator_snapshot: JSON.stringify(creator_snapshot), + status: status || 'receiving', + detail_status: 'unmatched', + storage_status: 'none', + delivery_method, + license_plate: delivery_method === 'truck' ? license_plate : null, + tracking_number: delivery_method !== 'truck' && delivery_method !== 'other' ? tracking_number : null, + loading_method, + video_device_id: video_device_id || null, + total_boxes: parseInt(total_boxes) || 0, + total_pallets: parseInt(total_pallets) || 0, + total_items: 0, + total_quantity: 0, + warehouse_id, + remark: remark || null, + store_name, + store_id: store_id || null, + receiving_start_time: new Date(), + is_deleted: false, + }; + + try { + result = await app.model.Receiving.create(receivingData); + break; + } catch (error) { + lastCreateError = error; + if (this.isReceivingNumberDuplicateError(error) && attempt < maxCreateRetries) { + ctx.logger.warn(`[ReceivingCreateRetry] receiving_number 冲突,准备重试第 ${attempt + 1} 次`, { + prefix, + warehouse_id, + }); + continue; + } + throw error; + } + } + + if (!result) { + throw lastCreateError || new Error('创建收货任务失败'); + } return { code: 200, @@ -755,6 +814,135 @@ class ReceivingService extends Service { } } + /** + * 绑定收货单货主。 + * 规则: + * 1. 已取消收货单禁止绑定; + * 2. 收货中/已完成状态下,若已存在货主,则禁止重复绑定; + * 3. 仅允许绑定与当前仓库存在有效签约关系的货主。 + * @param {Object} data 请求体 + * @param {number} data.id 收货单ID + * @param {number} data.store_id 货主ID + * @return {Promise} 绑定结果 + */ + async bindStore(data) { + const { ctx } = this; + const { id, store_id } = data || {}; + const warehouseId = Number(ctx.user && ctx.user.store_id); + const receivingId = Number(id || 0); + const storeId = Number(store_id || 0); + + if (!warehouseId) { + return { + code: 400, + message: '用户未绑定仓库', + }; + } + + if (receivingId <= 0) { + return { + code: 400, + message: '收货单ID不能为空', + }; + } + + if (storeId <= 0) { + return { + code: 400, + message: '货主ID不能为空', + }; + } + + const transaction = await ctx.model.transaction(); + + try { + const receiving = await ctx.model.Receiving.findOne({ + where: { + id: receivingId, + warehouse_id: warehouseId, + is_deleted: false, + }, + lock: transaction.LOCK.UPDATE, + transaction, + }); + + if (!receiving) { + await transaction.rollback(); + return { + code: 404, + message: '收货单不存在或无权访问', + }; + } + + if (receiving.status === 'cancelled') { + await transaction.rollback(); + return { + code: 400, + message: '已取消的收货单不允许绑定货主', + }; + } + + if ([ 'receiving', 'completed' ].includes(receiving.status) && Number(receiving.store_id || 0) > 0) { + await transaction.rollback(); + return { + code: 400, + message: '当前收货单已有货主,拒绝重复绑定', + }; + } + + const storeRelation = await ctx.model.StoreWarehouse.findOne({ + where: { + warehouse_id: warehouseId, + store_id: storeId, + use_status: 1, + }, + attributes: [ 'store_id', 'store_remask' ], + transaction, + }); + + if (!storeRelation) { + await transaction.rollback(); + return { + code: 404, + message: '货主不存在或未与当前仓库建立有效签约关系', + }; + } + + const storeName = storeRelation.store_remask || null; + await ctx.model.Receiving.update({ + store_id: storeId, + store_name: storeName, + updated_at: new Date(), + }, { + where: { + id: receivingId, + warehouse_id: warehouseId, + }, + transaction, + }); + + await transaction.commit(); + + return { + code: 200, + message: '绑定货主成功', + data: { + id: receivingId, + store_id: storeId, + store_name: storeName, + status: receiving.status, + }, + }; + } catch (error) { + await transaction.rollback(); + ctx.logger.error('绑定收货单货主失败:', error); + return { + code: 500, + message: `绑定货主失败: ${error.message}`, + }; + } + } + /** * 查询单个收货单完整信息(含明细、图片)。 * @param {Object} data 请求体 @@ -991,6 +1179,164 @@ class ReceivingService extends Service { } } + /** + * 绑定或改绑收货单明细的系统商品。 + * @param {Object} data 请求体 + * @param {number} data.detail_id 收货单明细ID(兼容 `id`) + * @param {number} data.system_product_id 商品ID + * @return {Promise} 绑定结果 + */ + async bindDetailProduct(data) { + const { ctx, app } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id); + const detailId = Number((data && (data.detail_id || data.id)) || 0); + const systemProductId = Number((data && data.system_product_id) || 0); + + if (!warehouseId) { + return { + code: 400, + message: '用户未绑定仓库', + }; + } + + if (detailId <= 0) { + return { + code: 400, + message: '收货单明细ID不能为空', + }; + } + + if (systemProductId <= 0) { + return { + code: 400, + message: '商品ID不能为空', + }; + } + + try { + const receivingDetail = await app.model.ReceivingDetail.findOne({ + where: { id: detailId }, + include: [ + { + model: app.model.Receiving, + as: 'receiving', + attributes: [ 'id', 'warehouse_id', 'store_id', 'store_name', 'status' ], + where: { + warehouse_id: warehouseId, + }, + required: true, + }, + ], + }); + + if (!receivingDetail) { + return { + code: 404, + message: '收货单明细不存在', + }; + } + + if (receivingDetail.receiving && receivingDetail.receiving.status !== 'receiving') { + return { + code: 400, + message: '收货单状态不允许绑定或改绑商品', + }; + } + + const stockWarehouse = await app.model.StockWarehouse.findOne({ + where: { + id: systemProductId, + warehouse_id: warehouseId, + }, + include: [ + app.model.StoreWarehouse.buildStoreStockInclude({ + warehouseId, + required: false, + attributes: [ 'store_id', 'store_remask' ], + }), + { + model: app.model.StockBarcode, + as: 'barcodes', + attributes: [ 'barcode' ], + required: false, + }, + ], + }); + + if (!stockWarehouse) { + return { + code: 404, + message: '商品不存在或不属于当前仓库', + }; + } + + const productStoreId = Number(stockWarehouse.store_stock?.store_id || 0); + + const barcodes = Array.isArray(stockWarehouse.barcodes) + ? stockWarehouse.barcodes.map(item => item && item.barcode).filter(Boolean) + : []; + + let productSnapshot = {}; + if (receivingDetail.product_snapshot) { + try { + productSnapshot = JSON.parse(receivingDetail.product_snapshot) || {}; + } catch { + productSnapshot = {}; + } + } + + const productName = stockWarehouse.item_name || stockWarehouse.name || receivingDetail.product_name || '未命名商品'; + const updateData = { + system_product_id: systemProductId, + product_name: productName, + product_snapshot: JSON.stringify({ + ...productSnapshot, + system_product_id: systemProductId, + product_name: productName, + store_id: productStoreId || productSnapshot.store_id || null, + store_name: stockWarehouse.store_stock?.store_remask || productSnapshot.store_name || null, + updated_at: new Date(), + }), + }; + + if (barcodes.length > 0) { + updateData.barcode = barcodes.join(';'); + } + if (stockWarehouse.gross_weight !== undefined && stockWarehouse.gross_weight !== null) { + updateData.weight = stockWarehouse.gross_weight; + } + if (stockWarehouse.enable_box_spec) { + updateData.boxes_per_pallet = stockWarehouse.quantity_per_box || receivingDetail.boxes_per_pallet || 0; + updateData.box_height = stockWarehouse.box_height || receivingDetail.box_height || 0; + updateData.box_width = stockWarehouse.box_width || receivingDetail.box_width || 0; + updateData.box_length = stockWarehouse.box_length || receivingDetail.box_length || 0; + } + + await ctx.model.ReceivingDetail.update(updateData, { + where: { id: detailId }, + }); + + await this.updateReceivingStats(receivingDetail.receiving_id); + + return { + code: 200, + message: '绑定商品成功', + data: { + detail_id: detailId, + receiving_id: receivingDetail.receiving_id, + system_product_id: systemProductId, + product_name: productName, + }, + }; + } catch (error) { + ctx.logger.error('绑定收货单明细商品失败:', error); + return { + code: 500, + message: `绑定商品失败: ${error.message}`, + }; + } + } + async updateDetail(data) { const ctx = this.ctx; const { id, ...updateData } = data; @@ -1778,6 +2124,270 @@ class ReceivingService extends Service { throw error; } } + formatReportDate(value) { + if (!value) { + return ''; + } + + const date = value instanceof Date ? value : new Date(value); + if (Number.isNaN(date.getTime())) { + return ''; + } + + return date.toLocaleString('zh-CN', { hour12: false }); + } + + buildCompletionReportSheets({ + receiving, + operator = {}, + stats = {}, + detailImageMap = new Map(), + receivingImages = [], + }) { + const details = Array.isArray(receiving && receiving.details) + ? receiving.details.map(item => (typeof item.toJSON === 'function' ? item.toJSON() : item)) + : []; + const mainImageUrls = (Array.isArray(receivingImages) ? receivingImages : []) + .map(item => (item && (item.url || item.file_url || (item.file && item.file.file_url))) || '') + .filter(Boolean); + + const rows = []; + const embeddedImages = []; + const styledRows = []; + const summaryImageColumnIndex = 3; + const detailColumns = [ + '序号', '商品名称', '条码', + '数量', '重量', '箱数', '托数', + '批次号', '生产日期', '到期日期', '备注', '图片链接', '图片', + ]; + const detailImageColumnIndex = detailColumns.length; + const maxDetailImageCount = Math.max( + 1, + ...details.map(detail => { + const detailImages = Array.isArray(detailImageMap.get(String(detail.id))) + ? detailImageMap.get(String(detail.id)) + : []; + const detailImageUrls = detailImages + .map(item => (item && (item.url || item.file_url || (item.file && item.file.file_url))) || '') + .filter(Boolean); + return detailImageUrls.length; + }) + ); + + const buildLinkCell = urls => { + const normalizedUrls = (Array.isArray(urls) ? urls : [ urls ]) + .map(item => String(item || '').trim()) + .filter(Boolean); + + if (normalizedUrls.length === 0) { + return ''; + } + + return { + text: normalizedUrls.join('\n'), + hyperlink: normalizedUrls[0], + tooltip: normalizedUrls.join('\n'), + }; + }; + + const pushReportRow = (cells = [], options = {}) => { + rows.push(cells); + const rowIndex = rows.length; + const maxCol = Math.max(Number(options.toCol || cells.length || 1), 1); + + if (options.style || options.height) { + styledRows.push({ + row: rowIndex, + fromCol: Math.max(Number(options.fromCol || 1), 1), + toCol: maxCol, + style: options.style || null, + height: options.height || null, + }); + } + + return rowIndex; + }; + + pushReportRow([]); + + [ + [ '收货单ID', receiving && receiving.id ], + [ '收货单号', receiving && receiving.receiving_number ], + [ '状态', receiving && receiving.status ], + [ '货主', receiving && receiving.store_name ], + [ '仓库ID', receiving && receiving.warehouse_id ], + [ '来货方式', receiving && receiving.delivery_method ], + [ '车牌号', receiving && receiving.license_plate ], + [ '物流单号', receiving && receiving.tracking_number ], + [ '总明细数', stats.total_details || details.length ], + [ '已匹配明细数', stats.matched_details || 0 ], + [ '未匹配明细数', stats.unmatched_details || 0 ], + [ '总数量', stats.total_quantity || 0 ], + [ '总箱数', receiving && receiving.total_boxes ], + [ '总托盘数', receiving && receiving.total_pallets ], + [ '完成人', operator.employees_name || operator.real_name || operator.name || '' ], + [ '完成时间', this.formatReportDate(receiving && receiving.receiving_end_time) ], + [ '备注', receiving && receiving.remark ], + ].forEach(([ field, value ]) => { + pushReportRow([ field, value ], { + toCol: 2, + style: { + alignment: { vertical: 'top', wrapText: true }, + }, + }); + }); + + if (mainImageUrls.length === 0) { + pushReportRow([ '收货图片', '无' ], { + toCol: 2, + style: { + alignment: { vertical: 'top', wrapText: true }, + }, + }); + } else { + const summaryLinkCell = buildLinkCell(mainImageUrls); + const imagePlaceholders = Array(Math.max(mainImageUrls.length, 1)).fill(''); + const firstImageRowIndex = pushReportRow([ '收货图片', summaryLinkCell, ...imagePlaceholders ], { + toCol: 2 + imagePlaceholders.length, + height: 88, + style: { + alignment: { vertical: 'top', wrapText: true }, + }, + }); + + mainImageUrls.forEach((imageUrl, index) => { + embeddedImages.push({ + row: firstImageRowIndex, + col: summaryImageColumnIndex + index, + url: imageUrl, + width: 96, + height: 96, + fallbackText: `收货图片${index + 1}`, + }); + }); + } + + pushReportRow([]); + + pushReportRow(detailColumns, { + toCol: detailColumns.length, + height: 22, + style: { + font: { bold: true, color: { argb: 'FF1F1F1F' } }, + fill: { + type: 'pattern', + pattern: 'solid', + fgColor: { argb: 'FFD9EAF7' }, + }, + alignment: { horizontal: 'center', vertical: 'middle', wrapText: true }, + }, + }); + + if (details.length === 0) { + pushReportRow([ '', '', '无明细' ], { + toCol: detailColumns.length, + style: { + alignment: { vertical: 'top', wrapText: true }, + }, + }); + } else { + details.forEach((detail, index) => { + const detailImages = Array.isArray(detailImageMap.get(String(detail.id))) + ? detailImageMap.get(String(detail.id)) + : []; + const detailImageUrls = detailImages + .map(item => (item && (item.url || item.file_url || (item.file && item.file.file_url))) || '') + .filter(Boolean); + const imageSlotCount = Math.max(detailImageUrls.length, 1); + const linkCell = buildLinkCell(detailImageUrls); + + const rowCells = [ + index + 1, + detail.product_name || '', + detail.barcode || '', + detail.actual_quantity || 0, + detail.weight || 0, + detail.box_quantity || 0, + detail.pallet_quantity || 0, + detail.batch_number || '', + this.formatReportDate(detail.production_date), + this.formatReportDate(detail.expiry_date), + detail.remark || '', + linkCell, + ...Array(imageSlotCount).fill(''), + ]; + + const targetRow = pushReportRow(rowCells, { + toCol: rowCells.length, + height: detailImageUrls.length > 0 ? 88 : null, + style: { + alignment: { vertical: 'top', wrapText: true }, + }, + }); + + detailImageUrls.forEach((imageUrl, imageIndex) => { + embeddedImages.push({ + row: targetRow, + col: detailImageColumnIndex + imageIndex, + url: imageUrl, + width: 96, + height: 96, + fallbackText: `图片${imageIndex + 1}`, + }); + }); + }); + } + + return [ + { + name: '收货清单', + rows, + widths: [ + 16, 28, 18, 10, 10, 10, 10, 18, 18, 18, 24, 42, 18, + ...Array(Math.max(maxDetailImageCount - 1, 0)).fill(18), + ], + embeddedImages, + styledRows, + skipHeader: true, + forceExcelJs: true, + }, + ]; + } + + async uploadCompletionExcelReport({ + receiving, + operator = {}, + stats = {}, + detailImageMap = new Map(), + receivingImages = [], + }) { + const { ctx } = this; + const excelService = ctx && ctx.service && ctx.service.systems && ctx.service.systems.excel; + + if (!receiving || !receiving.id || !excelService || typeof excelService.generateAndUpload !== 'function') { + return null; + } + + const receivingNumber = String(receiving.receiving_number || receiving.id).replace(/[\\/:*?"<>|]/g, '_'); + + return await excelService.generateAndUpload({ + filename: `收货完成_${receivingNumber}.xlsx`, + dir: `exports/receiving/completed/${ctx.user.store_id || receiving.warehouse_id || 'common'}`, + category: 'document', + saveRecord: true, + businessType: 'receivingReport', + businessId: receiving.id, + expireDays: 90, + sheets: this.buildCompletionReportSheets({ + receiving, + operator, + stats, + detailImageMap, + receivingImages, + }), + }); + } + /** * 完成收货单:校验明细、更新状态并写入库存。 * @param {Object} data 请求体 @@ -1806,7 +2416,11 @@ class ReceivingService extends Service { model: ctx.model.ReceivingDetail, as: 'details', required: false, - attributes: ['id', 'system_product_id', 'product_name', 'barcode', 'actual_quantity', 'weight'], + attributes: [ + 'id', 'system_product_id', 'product_name', 'barcode', 'actual_quantity', 'weight', + 'box_quantity', 'pallet_quantity', 'receiving_status', 'storage_status', + 'batch_number', 'production_date', 'expiry_date', 'remark', + ], }], }); @@ -1820,6 +2434,7 @@ class ReceivingService extends Service { // 2. 状态检查 if (receiving.status === 'completed') { + await transaction.rollback(); return { code: 200, message: '收货单已完成', @@ -1846,10 +2461,8 @@ class ReceivingService extends Service { // 4. 校验所有明细的完成条件 const invalidDetails = []; const unmatchedDetails = receiving.details.filter(d => !d.system_product_id); - - // 只有存在未绑定系统商品的明细时,才需要查询照片 - const detailsIds = receiving.details.map(item => item.id); + const images = await ctx.model.FileReference.findAll({ where: { business_type: 'receivingItem', @@ -1857,41 +2470,56 @@ class ReceivingService extends Service { [Op.in]: detailsIds, }, }, + include: [{ + model: ctx.model.File, + as: 'file', + attributes: [ 'file_url' ], + required: false, + }], transaction, }); - // 按照业务ID分组照片 const imageMap = new Map(); images.forEach(image => { const businessId = String(image.business_id).trim(); if (!imageMap.has(businessId)) { imageMap.set(businessId, []); } - imageMap.get(businessId).push(image); + + imageMap.get(businessId).push({ + id: image.file_id, + url: (image.file && image.file.file_url) || image.file_url || image.url || image.file_path || '', + }); }); - console.log('imageMap', imageMap); + const receivingImages = await ctx.model.FileReference.findAll({ + where: { + business_type: 'receiving', + business_id: id, + }, + include: [{ + model: ctx.model.File, + as: 'file', + attributes: [ 'file_url' ], + required: false, + }], + transaction, + }); + + const receivingImageList = receivingImages + .map(image => ({ + id: image.file_id, + url: (image.file && image.file.file_url) || image.file_url || image.url || '', + })) + .filter(item => item.url); - // 检查未绑定系统商品的明细 for (const detail of receiving.details) { - // 先检查是否有对应的图片数组 const businessId = String(detail.id).trim(); - const imageArray = imageMap.get(businessId); - - // 这里的关键修复:不仅要检查数组是否存在且有长度,还要检查数组中的元素是否有实际的数据 - const hasPhoto = imageArray && - imageArray.length > 0 && - imageArray.some(img => { - // 检查图片对象是否有实际的数据 - return img.dataValues || - img.file_path || - img.url || - (img._options && Object.keys(img._options).length > 0); - }); + const imageArray = imageMap.get(businessId) || []; + const hasPhoto = imageArray.some(img => !!(img && img.url)); const hasBarcode = !!detail.barcode && detail.barcode.trim() !== ''; - const hasWeight = detail.weight > 0; - const hasCount = detail.actual_quantity > 0; - console.log('detailInfo', hasBarcode, hasWeight, hasCount); + const hasWeight = Number(detail.weight || 0) > 0; + const hasCount = Number(detail.actual_quantity || 0) > 0; if (!hasPhoto || !hasBarcode || !hasWeight || !hasCount) { const itemName = detail.product_name || '未命名商品'; @@ -1929,7 +2557,6 @@ class ReceivingService extends Service { }; } - // 7. 获取操作人信息 const operator = ctx.user; @@ -1941,7 +2568,6 @@ class ReceivingService extends Service { updated_at: now, }; - // 更新备注 if (remark) { const remarkPrefix = receiving.remark ? `${receiving.remark}\n` : ''; updateData.remark = `${remarkPrefix}【完成收货】${now.toLocaleString()} ${operator.employees_name} ${remark}`; @@ -1963,30 +2589,60 @@ class ReceivingService extends Service { total_quantity: receiving.details.reduce((sum, d) => sum + (d.actual_quantity || 0), 0), }; - if (stats.matched_details > 0) { - // 通知 - await ctx.service.systems.notification.send({ - type: 'system', - title: `收货单${receiving.receiving_number}已完成`, - content: `收货单${receiving.receiving_number}已完成,匹配商品${stats.matched_details}件,未匹配商品${stats.unmatched_details}件。`, - bussinessType: 'receiving', - bussinessId: receiving.id, + // 10. 提交事务 + await transaction.commit(); + + const receivingSnapshot = { + ...(typeof receiving.toJSON === 'function' ? receiving.toJSON() : receiving), + ...updateData, + }; + + let completionReport = null; + try { + completionReport = await this.uploadCompletionExcelReport({ + receiving: receivingSnapshot, + operator, + stats, + detailImageMap: imageMap, + receivingImages: receivingImageList, + }); + } catch (reportError) { + ctx.logger.error(`收货完成报表上传失败: ${reportError.message}`, { + receiving_id: id, + warehouseId, + error: reportError.stack, }); } - // 11. 提交事务 - await transaction.commit(); + if (stats.matched_details > 0) { + try { + await ctx.service.systems.notification.send({ + type: 'system', + title: `收货单${receiving.receiving_number}已完成`, + content: `收货单${receiving.receiving_number}已完成,匹配商品${stats.matched_details}件,未匹配商品${stats.unmatched_details}件。`, + bussinessType: 'receiving', + bussinessId: receiving.id, + }); + } catch (notifyError) { + ctx.logger.error(`收货完成通知发送失败: ${notifyError.message}`, { + receiving_id: id, + warehouseId, + error: notifyError.stack, + }); + } + } - // 记录操作日志 ctx.logger.info('收货单已完成', { receiving_id: id, receiving_number: receiving.receiving_number, completed_by: operator.employees_name, stats, + completion_report: completionReport && completionReport.url, }); return { success: true, + code: 200, message: '收货完成成功', data: { receiving_id: id, @@ -1994,12 +2650,16 @@ class ReceivingService extends Service { completed_at: now, completed_by: operator.employees_name, stats, + completion_report: completionReport ? { + fileKey: completionReport.fileKey || '', + url: completionReport.url || completionReport.cdnUrl || completionReport.cosUrl || '', + fileRecord: completionReport.fileRecord || null, + } : null, }, }; } catch (error) { - // 12. 回滚事务 - if (transaction) { + if (transaction && !transaction.finished) { await transaction.rollback(); } @@ -2009,7 +2669,6 @@ class ReceivingService extends Service { error: error.stack, }); - // 如果是已知的业务错误,返回具体信息 if (error.code && error.code.startsWith('DETAIL_')) { return { success: false, @@ -2018,7 +2677,6 @@ class ReceivingService extends Service { }; } - // 其他错误 return { success: false, code: 'SYSTEM_ERROR', diff --git a/app/service/systems/store_warehouse.js b/app/service/systems/store_warehouse.js new file mode 100644 index 0000000..a73c73b --- /dev/null +++ b/app/service/systems/store_warehouse.js @@ -0,0 +1,1441 @@ +'use strict'; + +const crypto = require('node:crypto'); +const Service = require('egg').Service; + +const SIGN_TEMP_EXPIRE_SECONDS = 600; +const AUTH_STATUS_LABELS = Object.freeze({ + 1: '申请中', + 2: '已通过', + 3: '已拒绝', + 4: '已解除', + 5: '已过期', +}); +const POLICY_CONFIG_FIELD_RULES = Object.freeze({ + receive_mode: { + type: 'enum', + values: [ 'standard', 'strict', 'manual' ], + }, + sku_visibility: { + type: 'enum', + values: [ 'all', 'whitelist', 'blacklist' ], + }, + auto_allocate_bin: { + type: 'flag', + }, + allow_mix_batch: { + type: 'flag', + }, + allow_temp_storage: { + type: 'flag', + }, + max_daily_inbound: { + type: 'integer', + min: 0, + max: 1000000, + }, + remark: { + type: 'string', + maxLength: 200, + }, +}); + +class SettingStoreWarehouseService extends Service { + createError(message, code = 500) { + const error = new Error(message); + error.code = code; + return error; + } + + getCurrentStoreId() { + const storeId = Number(this.ctx.user && this.ctx.user.store_id); + if (!Number.isFinite(storeId) || storeId <= 0) { + throw this.createError('未识别到当前主体,无法操作签约关系', 400); + } + return storeId; + } + + getCurrentAccountId() { + const accountId = Number(this.ctx.user && this.ctx.user.id); + if (!Number.isFinite(accountId) || accountId <= 0) { + throw this.createError('未识别到当前登录账号', 401); + } + return accountId; + } + + toPositiveNumber(value, fieldName, options = {}) { + const { allowEmpty = false } = options; + if (allowEmpty && (value === undefined || value === null || value === '')) { + return null; + } + + const num = Number(value); + if (!Number.isFinite(num) || num <= 0) { + throw this.createError(`${fieldName} 参数不能为空`, 400); + } + return num; + } + + normalizePage(value, fieldName, defaultValue, maxValue) { + if (value === undefined || value === null || value === '') { + return defaultValue; + } + const num = Number(value); + if (!Number.isFinite(num) || num <= 0) { + throw this.createError(`${fieldName} 参数不合法`, 400); + } + return Math.min(Math.floor(num), maxValue); + } + + normalizeStatusFlag(value, fieldName, defaultValue = null) { + if (value === undefined || value === null || value === '') { + return defaultValue; + } + const num = Number(value); + if (num === 0 || num === 1) { + return num; + } + throw this.createError(`${fieldName} 参数不合法`, 400); + } + + normalizeAuthStatus(value) { + if (value === undefined || value === null || value === '') { + return null; + } + const num = Number(value); + if ([ 1, 2, 3, 4, 5 ].includes(num)) { + return num; + } + throw this.createError('auth_status 参数不合法', 400); + } + + normalizeNonNegativeInteger(value, fieldName, defaultValue = 0) { + if (value === undefined || value === null || value === '') { + return defaultValue; + } + const num = Number(value); + if (!Number.isFinite(num) || num < 0) { + throw this.createError(`${fieldName} 参数不合法`, 400); + } + return Math.floor(num); + } + + normalizeText(value, fieldName, maxLength = 500) { + if (value === undefined || value === null) { + return null; + } + const normalized = String(value).trim(); + if (normalized.length > maxLength) { + throw this.createError(`${fieldName} 长度不能超过 ${maxLength}`, 400); + } + return normalized; + } + + normalizeIntegerRange(value, fieldName, defaultValue, minValue, maxValue) { + if (value === undefined || value === null || value === '') { + return defaultValue; + } + const num = Number(value); + if (!Number.isFinite(num) || num < minValue || num > maxValue) { + throw this.createError(`${fieldName} 参数不合法`, 400); + } + return Math.floor(num); + } + + normalizeEmail(value) { + const email = this.normalizeText(value, 'email', 100); + if (!email) { + return null; + } + + const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; + if (!emailRegex.test(email)) { + throw this.createError('email 参数不合法', 400); + } + return email; + } + + normalizePolicyConfig(value, fieldName = 'policy_config', options = {}) { + const { allowEmpty = false } = options; + if (value === undefined || value === null || value === '') { + if (allowEmpty) { + return null; + } + throw this.createError(`${fieldName} 参数不能为空`, 400); + } + + const parsed = typeof value === 'string' ? (() => { + try { + return JSON.parse(value); + } catch { + throw this.createError(`${fieldName} 不是合法JSON`, 400); + } + })() : value; + + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { + throw this.createError(`${fieldName} 必须为对象`, 400); + } + + const allowedKeys = Object.keys(POLICY_CONFIG_FIELD_RULES); + const unsupportedKeys = Object.keys(parsed).filter(key => !allowedKeys.includes(key)); + if (unsupportedKeys.length) { + throw this.createError(`${fieldName} 包含不支持字段: ${unsupportedKeys.join(', ')};仅允许字段: ${allowedKeys.join(', ')}`, 400); + } + + const normalized = {}; + for (const [ key, rawValue ] of Object.entries(parsed)) { + const rule = POLICY_CONFIG_FIELD_RULES[key]; + if (!rule) { + continue; + } + + if (rule.type === 'enum') { + const valueText = String(rawValue || '').trim(); + if (!rule.values.includes(valueText)) { + throw this.createError(`${fieldName}.${key} 参数不合法`, 400); + } + normalized[key] = valueText; + continue; + } + + if (rule.type === 'flag') { + if (rawValue === true || rawValue === 1 || rawValue === '1') { + normalized[key] = 1; + continue; + } + if (rawValue === false || rawValue === 0 || rawValue === '0') { + normalized[key] = 0; + continue; + } + throw this.createError(`${fieldName}.${key} 参数不合法`, 400); + } + + if (rule.type === 'integer') { + const num = Number(rawValue); + if (!Number.isFinite(num) || num < rule.min || num > rule.max) { + throw this.createError(`${fieldName}.${key} 参数不合法`, 400); + } + normalized[key] = Math.floor(num); + continue; + } + + if (rule.type === 'string') { + const text = this.normalizeText(rawValue, `${fieldName}.${key}`, rule.maxLength); + normalized[key] = text || ''; + } + } + + return normalized; + } + + getPolicyConfigCacheKey(contractId) { + return `store_warehouse:policy:${contractId}`; + } + + async hasPolicyConfigColumn() { + if (this._hasPolicyConfigColumn !== undefined) { + return this._hasPolicyConfigColumn; + } + + try { + const [ columns ] = await this.app.model.query( + "SHOW COLUMNS FROM `wms_store_warehouse` LIKE 'policy_config'" + ); + this._hasPolicyConfigColumn = Array.isArray(columns) && columns.length > 0; + } catch { + this._hasPolicyConfigColumn = false; + } + return this._hasPolicyConfigColumn; + } + + async loadPolicyConfigByContractId(contractId, transaction = null) { + const normalizedId = Number(contractId || 0); + if (normalizedId <= 0) { + return null; + } + + if (await this.hasPolicyConfigColumn()) { + const [ rows ] = await this.app.model.query( + 'SELECT policy_config FROM wms_store_warehouse WHERE id = :id LIMIT 1', + { + replacements: { id: normalizedId }, + transaction, + } + ); + const row = Array.isArray(rows) ? rows[0] : null; + const raw = row ? row.policy_config : null; + + if (raw === null || raw === undefined || raw === '') { + return null; + } + if (typeof raw === 'object') { + return raw; + } + + try { + return JSON.parse(raw); + } catch { + return null; + } + } + + const cached = await this.app.getCacheAsync(this.getPolicyConfigCacheKey(normalizedId)); + return cached && typeof cached === 'object' ? cached : null; + } + + async savePolicyConfigByContractId(contractId, policyConfig, transaction = null) { + const normalizedId = Number(contractId || 0); + if (normalizedId <= 0) { + throw this.createError('id 参数不能为空', 400); + } + + if (await this.hasPolicyConfigColumn()) { + await this.app.model.query( + 'UPDATE wms_store_warehouse SET policy_config = :policy_config, updated_at = NOW() WHERE id = :id', + { + replacements: { + id: normalizedId, + policy_config: JSON.stringify(policyConfig), + }, + transaction, + } + ); + return; + } + + await this.app.setCacheAsync(this.getPolicyConfigCacheKey(normalizedId), policyConfig, 86400 * 30); + } + + ensureWarehouseSubject(currentSubject) { + if (!currentSubject || !currentSubject.isWarehouse) { + throw this.createError('仅仓库主体可维护奇门接口配置', 403); + } + } + + resolveRelationId(data = {}) { + return this.toPositiveNumber( + data.id !== undefined ? data.id : (data.contract_id !== undefined ? data.contract_id : data.relation_id), + 'id', + { allowEmpty: true } + ); + } + + normalizeDate(value, fieldName, options = {}) { + const { allowNull = true } = options; + if (value === undefined || value === null || value === '') { + if (allowNull) { + return null; + } + throw this.createError(`${fieldName} 参数不能为空`, 400); + } + + const date = value instanceof Date ? value : new Date(value); + if (Number.isNaN(date.getTime())) { + throw this.createError(`${fieldName} 参数不合法`, 400); + } + return date; + } + + normalizeSignAction(value) { + if (value === undefined || value === null || value === '') { + return ''; + } + + const action = String(value).trim(); + if ([ 'preview', 'confirm' ].includes(action)) { + return action; + } + throw this.createError('action 参数不合法', 400); + } + + normalizeTempCode(value) { + const code = String(value || '').trim().toUpperCase(); + if (!code) { + throw this.createError('temp_code 参数不能为空', 400); + } + return code; + } + + getTempCodeCacheKey(tempCode) { + return `store_warehouse:sign:${tempCode}`; + } + + createTempCode() { + return crypto.randomBytes(6).toString('hex').toUpperCase(); + } + + pickRemaskField(currentSubject) { + return currentSubject && currentSubject.isWarehouse ? 'store_remask' : 'warehouse_remask'; + } + + resolveRemaskValue(data, currentSubject) { + const raw = data.remask !== undefined + ? data.remask + : (currentSubject && currentSubject.isWarehouse ? data.store_remask : data.warehouse_remask); + return this.normalizeText(raw, 'remask', 50); + } + + buildCurrentRemaskPatch(data, currentSubject) { + const remask = this.resolveRemaskValue(data, currentSubject); + if (remask === null) { + return {}; + } + + return { + [this.pickRemaskField(currentSubject)]: remask, + }; + } + + requireCurrentRemaskPatch(data, currentSubject) { + const patch = this.buildCurrentRemaskPatch(data, currentSubject); + if (!Object.keys(patch).length) { + throw this.createError('remask 参数不能为空', 400); + } + return patch; + } + + async saveTempSignPayload(payload) { + const now = Date.now(); + const expiresAt = new Date(now + SIGN_TEMP_EXPIRE_SECONDS * 1000).toISOString(); + const tempCode = this.createTempCode(); + await this.app.setCacheAsync(this.getTempCodeCacheKey(tempCode), { + ...payload, + expires_at: expiresAt, + }, SIGN_TEMP_EXPIRE_SECONDS); + return { + tempCode, + expiresAt, + expiresIn: SIGN_TEMP_EXPIRE_SECONDS, + }; + } + + async getTempSignPayload(tempCode) { + const normalizedCode = this.normalizeTempCode(tempCode); + const payload = await this.app.getCacheAsync(this.getTempCodeCacheKey(normalizedCode)); + if (!payload) { + throw this.createError('临时码无效或已过期', 404); + } + return { + tempCode: normalizedCode, + payload, + }; + } + + async clearTempSignPayload(tempCode) { + const cacheRedis = this.app.redis && this.app.redis.get ? this.app.redis.get('cache') : null; + if (cacheRedis && cacheRedis.del) { + await cacheRedis.del(this.getTempCodeCacheKey(tempCode)); + return; + } + await this.app.setCacheAsync(this.getTempCodeCacheKey(tempCode), { consumed: true }, 1); + } + + buildTempSignView(tempCode, payload, currentSubject) { + const participantIds = [ Number(payload.initiator_subject_id || 0), Number(payload.counterparty_id || 0) ]; + const currentSubjectId = Number(currentSubject && currentSubject.id); + const expiresAt = payload.expires_at || null; + const expiresMs = expiresAt ? new Date(expiresAt).getTime() : 0; + + return { + mode: 'preview', + temp_code: tempCode, + expires_at: expiresAt, + expires_in: expiresMs ? Math.max(0, Math.ceil((expiresMs - Date.now()) / 1000)) : 0, + is_participant: participantIds.includes(currentSubjectId), + can_confirm: currentSubjectId > 0 && currentSubjectId === Number(payload.counterparty_id || 0), + initiator: { + id: Number(payload.initiator_subject_id || 0), + role: payload.initiator_role || '', + name: payload.initiator_name || '', + }, + counterparty: { + id: Number(payload.counterparty_id || 0), + role: payload.counterparty_role || '', + name: payload.counterparty_name || '', + }, + sign_info: { + store_id: Number(payload.store_id || 0), + warehouse_id: Number(payload.warehouse_id || 0), + auth_start: payload.auth_start || null, + auth_end: payload.auth_end || null, + print_quantity: Number(payload.print_quantity || 0), + apply_reason: payload.apply_reason || '', + remask: payload.remask || '', + }, + }; + } + + async getCurrentSubject() { + const { ctx } = this; + const storeId = this.getCurrentStoreId(); + const subject = await ctx.model.Store.findOne({ + where: { + id: storeId, + }, + attributes: [ 'id', 'company_name', 'project', 'status' ], + }); + + if (!subject) { + throw this.createError('当前主体不存在', 404); + } + + return { + id: Number(subject.id), + company_name: subject.company_name || '', + project: subject.project || '', + isWarehouse: subject.project === 'warehouse', + status: Number(subject.status || 0), + }; + } + + async getCounterparty(counterpartyId, expectedRole) { + const { ctx } = this; + const counterparty = await ctx.model.Store.findOne({ + where: { + id: counterpartyId, + }, + attributes: [ 'id', 'company_name', 'project', 'status' ], + }); + + if (!counterparty) { + throw this.createError('签约对象不存在', 404); + } + + const isWarehouse = counterparty.project === 'warehouse'; + if (expectedRole === 'warehouse' && !isWarehouse) { + throw this.createError('目标对象不是仓库主体,无法签约', 400); + } + if (expectedRole === 'store' && isWarehouse) { + throw this.createError('目标对象不是货主主体,无法签约', 400); + } + + return counterparty; + } + + buildListWhere(data, currentSubject) { + const where = {}; + + if (currentSubject.isWarehouse) { + where.warehouse_id = currentSubject.id; + } else { + where.store_id = currentSubject.id; + } + + const relationId = this.resolveRelationId(data); + if (relationId) { + where.id = relationId; + } + + const rawCounterpartyId = data.counterparty_id !== undefined + ? data.counterparty_id + : (currentSubject.isWarehouse ? data.store_id : data.warehouse_id); + const counterpartyId = this.toPositiveNumber(rawCounterpartyId, 'counterparty_id', { allowEmpty: true }); + if (counterpartyId) { + if (currentSubject.isWarehouse) { + where.store_id = counterpartyId; + } else { + where.warehouse_id = counterpartyId; + } + } + + const authStatus = this.normalizeAuthStatus(data.auth_status); + if (authStatus !== null) { + where.auth_status = authStatus; + } + + const useStatus = this.normalizeStatusFlag(data.use_status, 'use_status', null); + if (useStatus !== null) { + where.use_status = useStatus; + } + + return where; + } + + getRelationIncludes() { + const { ctx } = this; + return [ + { + model: ctx.model.Store, + as: 'store', + attributes: [ 'id', 'company_name', 'project', 'status' ], + required: false, + }, + { + model: ctx.model.Store, + as: 'warehouse', + attributes: [ 'id', 'company_name', 'project', 'status' ], + required: false, + }, + ]; + } + + getQimenContractCacheKey(appKey, customerId, warehouseCode) { + return `contract:${appKey}:${customerId}:${warehouseCode}`; + } + + async clearQimenContractCache(configs = []) { + const cacheRedis = this.app.redis && this.app.redis.get ? this.app.redis.get('cache') : null; + const keys = [ ...new Set(configs.map(item => { + const record = item && typeof item.get === 'function' + ? item.get({ plain: true }) + : item; + if (!record) { + return ''; + } + + const appKey = String(record.qimen_app_key || '').trim(); + const customerId = String(record.qimen_customer_id || '').trim(); + const warehouseCode = String(record.qimen_warehouse_code || '').trim(); + if (!appKey || !customerId || !warehouseCode) { + return ''; + } + return this.getQimenContractCacheKey(appKey, customerId, warehouseCode); + }).filter(Boolean)) ]; + + if (!keys.length) { + return; + } + + if (cacheRedis && cacheRedis.del) { + await cacheRedis.del(...keys); + return; + } + + await Promise.all(keys.map(key => this.app.setCacheAsync(key, null, 1).catch(() => null))); + } + + async getQimenInterfaceType(data = {}, options = {}) { + const { ctx } = this; + const { allowDisabled = false, transaction = null } = options; + const interfaceTypeId = this.toPositiveNumber(data.interface_type_id, 'interface_type_id', { allowEmpty: true }); + const where = { + interface_category: 'QM_WMS', + }; + + if (!allowDisabled) { + where.is_enabled = 1; + } + if (interfaceTypeId) { + where.id = interfaceTypeId; + } + + const interfaceType = await ctx.model.InterfaceType.findOne({ + where, + attributes: [ 'id', 'interface_code', 'interface_name', 'interface_category', 'is_enabled' ], + order: [[ 'id', 'ASC' ]], + transaction, + }); + + if (!interfaceType) { + throw this.createError(interfaceTypeId ? '指定的奇门接口类型不存在或不可用' : '未配置可用的奇门接口类型', 404); + } + + return interfaceType; + } + + serializeQimenConfig(config) { + if (!config) { + return null; + } + + const item = config && typeof config.get === 'function' + ? config.get({ plain: true }) + : config; + const interfaceType = item.interface_type || {}; + + return { + id: Number(item.id || 0), + interface_type_id: Number(item.interface_type_id || 0), + interface_code: interfaceType.interface_code || item.interface_code || '', + interface_name: interfaceType.interface_name || item.interface_name || '', + interface_category: interfaceType.interface_category || item.interface_category || '', + contract_id: Number(item.contract_id || 0), + warehouse_id: item.warehouse_id ? Number(item.warehouse_id) : null, + app_name: item.app_name || '', + qimen_app_key: item.qimen_app_key || '', + qimen_customer_id: item.qimen_customer_id || '', + qimen_warehouse_code: item.qimen_warehouse_code || '', + api_version: item.api_version || '', + sign_method: item.sign_method || '', + rate_limit: Number(item.rate_limit || 0), + timeout_seconds: Number(item.timeout_seconds || 0), + contact_person: item.contact_person || '', + contact_phone: item.contact_phone || '', + email: item.email || '', + is_enabled: Number(item.is_enabled || 0), + created_at: item.created_at || null, + updated_at: item.updated_at || null, + }; + } + + async getQimenConfigMap(contractIds = [], options = {}) { + const { ctx } = this; + const { allowDisabled = true, interfaceTypeId = null, transaction = null } = options; + const normalizedContractIds = [ ...new Set(contractIds.map(value => Number(value)).filter(value => Number.isFinite(value) && value > 0)) ]; + + if (!normalizedContractIds.length || !ctx.model.ApiApp || !ctx.model.InterfaceType) { + return new Map(); + } + + let interfaceTypeIds = []; + if (interfaceTypeId) { + interfaceTypeIds = [ Number(interfaceTypeId) ]; + } else { + const interfaceWhere = { + interface_category: 'QM_WMS', + }; + if (!allowDisabled) { + interfaceWhere.is_enabled = 1; + } + + const interfaceTypes = await ctx.model.InterfaceType.findAll({ + where: interfaceWhere, + attributes: [ 'id' ], + transaction, + }); + interfaceTypeIds = interfaceTypes.map(item => Number(item.id)).filter(Boolean); + } + + if (!interfaceTypeIds.length) { + return new Map(); + } + + const rows = await ctx.model.ApiApp.findAll({ + where: { + contract_id: normalizedContractIds, + interface_type_id: interfaceTypeIds, + }, + include: [ + { + model: ctx.model.InterfaceType, + as: 'interface_type', + attributes: [ 'id', 'interface_code', 'interface_name', 'interface_category', 'is_enabled' ], + required: false, + }, + ], + order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]], + transaction, + }); + + const configMap = new Map(); + for (const row of rows) { + const contractId = Number(row.contract_id || 0); + if (!contractId || configMap.has(contractId)) { + continue; + } + configMap.set(contractId, this.serializeQimenConfig(row)); + } + + return configMap; + } + + async getSingleQimenConfig(contractId, options = {}) { + const configMap = await this.getQimenConfigMap([ contractId ], options); + return configMap.get(Number(contractId)) || null; + } + + resolvePairIds(data, currentSubject) { + const fieldName = currentSubject.isWarehouse ? 'store_id / counterparty_id' : 'warehouse_id / counterparty_id'; + const rawCounterpartyId = data.counterparty_id !== undefined + ? data.counterparty_id + : (currentSubject.isWarehouse ? data.store_id : data.warehouse_id); + const counterpartyId = this.toPositiveNumber(rawCounterpartyId, fieldName); + + if (currentSubject.isWarehouse) { + return { + storeId: counterpartyId, + warehouseId: currentSubject.id, + counterpartyId, + }; + } + + return { + storeId: currentSubject.id, + warehouseId: counterpartyId, + counterpartyId, + }; + } + + serializeRelation(relation, currentSubject, qimenConfig = null) { + const item = relation && typeof relation.get === 'function' + ? relation.get({ plain: true }) + : (relation || {}); + const normalizedQimenConfig = qimenConfig !== null + ? qimenConfig + : (item.qimen_config ? this.serializeQimenConfig(item.qimen_config) : null); + + const authStatus = Number(item.auth_status || 0); + const currentIsWarehouse = !!(currentSubject && currentSubject.isWarehouse); + const counterparty = currentIsWarehouse ? item.store : item.warehouse; + const storeName = item.store_remask || (item.store && item.store.company_name ? item.store.company_name : ''); + const warehouseName = item.warehouse_remask || (item.warehouse && item.warehouse.company_name ? item.warehouse.company_name : ''); + const counterpartyName = currentIsWarehouse ? storeName : warehouseName; + + let isAuthValid = false; + let remainingDays = 0; + if (authStatus === 2 && item.auth_start && item.auth_end) { + const now = Date.now(); + const start = new Date(item.auth_start).getTime(); + const end = new Date(item.auth_end).getTime(); + if (!Number.isNaN(start) && !Number.isNaN(end) && now >= start && now <= end) { + isAuthValid = true; + remainingDays = Math.max(0, Math.ceil((end - now) / (1000 * 60 * 60 * 24))); + } + } + + return { + id: Number(item.id || 0), + store_id: Number(item.store_id || 0), + store_name: storeName, + warehouse_id: Number(item.warehouse_id || 0), + warehouse_name: warehouseName, + counterparty_id: counterparty && counterparty.id ? Number(counterparty.id) : 0, + counterparty_name: counterpartyName, + current_subject_role: currentIsWarehouse ? 'warehouse' : 'store', + auth_status: authStatus, + auth_status_label: AUTH_STATUS_LABELS[authStatus] || '', + apply_reason: item.apply_reason || '', + review_comment: item.review_comment || '', + apply_time: item.apply_time || null, + review_time: item.review_time || null, + auth_start: item.auth_start || null, + auth_end: item.auth_end || null, + actual_end: item.actual_end || null, + print_quantity: Number(item.print_quantity || 0), + applied_by: item.applied_by ? Number(item.applied_by) : null, + reviewed_by: item.reviewed_by ? Number(item.reviewed_by) : null, + ended_by: item.ended_by ? Number(item.ended_by) : null, + remask: currentIsWarehouse ? (item.store_remask || '') : (item.warehouse_remask || ''), + use_status: Number(item.use_status || 0), + policy_config: item.policy_config && typeof item.policy_config === 'object' ? item.policy_config : null, + is_auth_valid: isAuthValid, + remaining_days: remainingDays, + qimen_config: normalizedQimenConfig || null, + }; + } + + async findScopedRelation(data, currentSubject, transaction) { + const { ctx } = this; + const where = currentSubject.isWarehouse + ? { warehouse_id: currentSubject.id } + : { store_id: currentSubject.id }; + + const relationId = this.resolveRelationId(data); + if (relationId) { + where.id = relationId; + } else { + const pair = this.resolvePairIds(data, currentSubject); + where.store_id = pair.storeId; + where.warehouse_id = pair.warehouseId; + } + + const relation = await ctx.model.StoreWarehouse.findOne({ + where, + include: this.getRelationIncludes(), + transaction, + }); + + if (!relation) { + throw this.createError('签约关系不存在或无权限操作', 404); + } + + return relation; + } + + async list(data = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const currentSubject = await this.getCurrentSubject(); + const page = this.normalizePage(data.page, 'page', 1, 1000000); + const pageSize = this.normalizePage(data.page_size || data.pageSize, 'page_size', 20, 200); + const offset = (page - 1) * pageSize; + const where = this.buildListWhere(data, currentSubject); + const keyword = typeof data.keyword === 'string' ? data.keyword.trim() : ''; + + if (keyword) { + where[Op.or] = [ + { store_remask: { [Op.like]: `%${keyword}%` } }, + { warehouse_remask: { [Op.like]: `%${keyword}%` } }, + { '$store.company_name$': { [Op.like]: `%${keyword}%` } }, + { '$warehouse.company_name$': { [Op.like]: `%${keyword}%` } }, + ]; + } + + const { rows, count } = await ctx.model.StoreWarehouse.findAndCountAll({ + where, + include: this.getRelationIncludes(), + order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]], + offset, + limit: pageSize, + distinct: true, + }); + const qimenConfigMap = await this.getQimenConfigMap(rows.map(item => Number(item.id || 0)), { + allowDisabled: true, + }); + + return { + code: 200, + data: { + list: rows.map(item => this.serializeRelation(item, currentSubject, qimenConfigMap.get(Number(item.id || 0)) || null)), + total: Number(count || 0), + page, + page_size: pageSize, + current_subject: { + store_id: currentSubject.id, + company_name: currentSubject.company_name, + role: currentSubject.isWarehouse ? 'warehouse' : 'store', + }, + }, + }; + } + + async sign(data = {}) { + const action = this.normalizeSignAction(data.action || data.mode); + if (data.temp_code || data.tempCode || action === 'preview') { + const { ctx } = this; + const transaction = await ctx.model.transaction(); + + try { + const currentSubject = await this.getCurrentSubject(); + const accountId = this.getCurrentAccountId(); + const { tempCode, payload } = await this.getTempSignPayload(data.temp_code || data.tempCode); + const isParticipant = [ Number(payload.initiator_subject_id || 0), Number(payload.counterparty_id || 0) ] + .includes(Number(currentSubject.id)); + + if (!isParticipant) { + throw this.createError('当前主体无权使用该临时码', 403); + } + + if (action === 'preview' || data.preview === 1 || data.preview === '1') { + await transaction.rollback(); + return { + code: 200, + data: this.buildTempSignView(tempCode, payload, currentSubject), + }; + } + + if (Number(currentSubject.id) !== Number(payload.counterparty_id || 0)) { + throw this.createError('需由对方主体确认后才可生效', 400); + } + + const relationPatch = { + store_id: Number(payload.store_id || 0), + warehouse_id: Number(payload.warehouse_id || 0), + auth_status: 2, + apply_reason: payload.apply_reason || '', + apply_time: payload.created_at ? new Date(payload.created_at) : new Date(), + print_quantity: Number(payload.print_quantity || 0), + review_time: new Date(), + auth_start: payload.auth_start ? new Date(payload.auth_start) : new Date(), + auth_end: payload.auth_end ? new Date(payload.auth_end) : null, + actual_end: null, + applied_by: Number(payload.initiated_by || 0) || accountId, + reviewed_by: accountId, + ended_by: null, + use_status: 1, + }; + + if (payload.store_remask !== undefined) { + relationPatch.store_remask = payload.store_remask; + } + if (payload.warehouse_remask !== undefined) { + relationPatch.warehouse_remask = payload.warehouse_remask; + } + Object.assign(relationPatch, this.buildCurrentRemaskPatch(data, currentSubject)); + + let relation = await ctx.model.StoreWarehouse.findOne({ + where: { + store_id: relationPatch.store_id, + warehouse_id: relationPatch.warehouse_id, + }, + transaction, + }); + const isCreate = !relation; + + if (relation) { + await relation.update(relationPatch, { transaction }); + } else { + relation = await ctx.model.StoreWarehouse.create(relationPatch, { transaction }); + } + + const result = await ctx.model.StoreWarehouse.findByPk(relation.id, { + include: this.getRelationIncludes(), + transaction, + }); + const qimenConfig = await this.getSingleQimenConfig(relation.id, { + allowDisabled: true, + transaction, + }); + + await this.clearTempSignPayload(tempCode); + await transaction.commit(); + + return { + code: 200, + data: { + mode: 'confirm', + temp_code: tempCode, + contract: this.serializeRelation(result, currentSubject, qimenConfig), + action: isCreate ? 'create' : 'update', + }, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + const currentSubject = await this.getCurrentSubject(); + const accountId = this.getCurrentAccountId(); + const pair = this.resolvePairIds(data, currentSubject); + const counterparty = await this.getCounterparty(pair.counterpartyId, currentSubject.isWarehouse ? 'store' : 'warehouse'); + const authStart = this.normalizeDate(data.auth_start, 'auth_start', { allowNull: true }) || new Date(); + const authEnd = this.normalizeDate(data.auth_end, 'auth_end', { allowNull: true }); + if (authEnd && authStart.getTime() > authEnd.getTime()) { + throw this.createError('auth_end 不能早于 auth_start', 400); + } + + const remask = this.resolveRemaskValue(data, currentSubject); + const payload = { + initiated_by: accountId, + initiator_subject_id: currentSubject.id, + initiator_role: currentSubject.isWarehouse ? 'warehouse' : 'store', + initiator_name: currentSubject.company_name, + counterparty_id: Number(counterparty.id || 0), + counterparty_role: currentSubject.isWarehouse ? 'store' : 'warehouse', + counterparty_name: counterparty.company_name || '', + store_id: pair.storeId, + warehouse_id: pair.warehouseId, + auth_start: authStart.toISOString(), + auth_end: authEnd ? authEnd.toISOString() : null, + print_quantity: this.normalizeNonNegativeInteger(data.print_quantity, 'print_quantity', 0), + apply_reason: this.normalizeText(data.apply_reason, 'apply_reason', 2000), + remask: remask || '', + created_at: new Date().toISOString(), + ...this.buildCurrentRemaskPatch(data, currentSubject), + }; + + const signPayload = await this.saveTempSignPayload(payload); + + return { + code: 200, + data: { + mode: 'initiate', + temp_code: signPayload.tempCode, + expires_at: signPayload.expiresAt, + expires_in: signPayload.expiresIn, + can_confirm: false, + current_subject: { + store_id: currentSubject.id, + company_name: currentSubject.company_name, + role: currentSubject.isWarehouse ? 'warehouse' : 'store', + }, + counterparty: { + id: Number(counterparty.id || 0), + company_name: counterparty.company_name || '', + role: currentSubject.isWarehouse ? 'store' : 'warehouse', + }, + }, + }; + } + + async rename(data = {}) { + const { ctx } = this; + const transaction = await ctx.model.transaction(); + + try { + const currentSubject = await this.getCurrentSubject(); + const relation = await this.findScopedRelation(data, currentSubject, transaction); + const relationPatch = this.requireCurrentRemaskPatch(data, currentSubject); + + await relation.update(relationPatch, { transaction }); + + const result = await ctx.model.StoreWarehouse.findByPk(relation.id, { + include: this.getRelationIncludes(), + transaction, + }); + const qimenConfig = await this.getSingleQimenConfig(relation.id, { + allowDisabled: true, + transaction, + }); + + await transaction.commit(); + + return { + code: 200, + data: { + contract: this.serializeRelation(result, currentSubject, qimenConfig), + }, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + async getPolicyConfig(data = {}) { + const currentSubject = await this.getCurrentSubject(); + const relation = await this.findScopedRelation(data, currentSubject); + const qimenConfig = await this.getSingleQimenConfig(relation.id, { + allowDisabled: true, + }); + const policyConfig = await this.loadPolicyConfigByContractId(relation.id); + + return { + code: 200, + data: { + contract_id: Number(relation.id || 0), + policy_config: policyConfig, + contract: this.serializeRelation(relation, currentSubject, qimenConfig), + }, + }; + } + + async savePolicyConfig(data = {}) { + const { ctx } = this; + const transaction = await ctx.model.transaction(); + + try { + const currentSubject = await this.getCurrentSubject(); + const relation = await this.findScopedRelation(data, currentSubject, transaction); + this.ensureWarehouseSubject(currentSubject); + const policyConfig = this.normalizePolicyConfig( + data.policy_config !== undefined ? data.policy_config : data.policy + ); + await this.savePolicyConfigByContractId(relation.id, policyConfig, transaction); + + const result = await ctx.model.StoreWarehouse.findByPk(relation.id, { + include: this.getRelationIncludes(), + transaction, + }); + const qimenConfig = await this.getSingleQimenConfig(relation.id, { + allowDisabled: true, + transaction, + }); + + await transaction.commit(); + + return { + code: 200, + data: { + contract_id: Number(relation.id || 0), + policy_config: policyConfig, + contract: this.serializeRelation(result, currentSubject, qimenConfig), + }, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + async listQimenConfig(data = {}) { + const { ctx } = this; + const currentSubject = await this.getCurrentSubject(); + const relation = await this.findScopedRelation(data, currentSubject); + const interfaceTypeId = this.toPositiveNumber(data.interface_type_id, 'interface_type_id', { allowEmpty: true }); + + const interfaceWhere = { + interface_category: 'QM_WMS', + }; + if (interfaceTypeId) { + interfaceWhere.id = interfaceTypeId; + } + + const interfaceTypes = await ctx.model.InterfaceType.findAll({ + where: interfaceWhere, + attributes: [ 'id', 'interface_code', 'interface_name', 'interface_category', 'is_enabled' ], + order: [[ 'id', 'ASC' ]], + }); + const interfaceTypeIds = interfaceTypes.map(item => Number(item.id)).filter(Boolean); + + if (!interfaceTypeIds.length) { + return { + code: 200, + data: { + contract_id: Number(relation.id || 0), + contract: this.serializeRelation(relation, currentSubject, null), + list: [], + total: 0, + }, + }; + } + + const rows = await ctx.model.ApiApp.findAll({ + where: { + contract_id: Number(relation.id || 0), + interface_type_id: interfaceTypeIds, + }, + include: [ + { + model: ctx.model.InterfaceType, + as: 'interface_type', + attributes: [ 'id', 'interface_code', 'interface_name', 'interface_category', 'is_enabled' ], + required: false, + }, + ], + order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]], + }); + + const list = rows.map(item => this.serializeQimenConfig(item)); + const primaryQimenConfig = list.length ? list[0] : null; + + return { + code: 200, + data: { + contract_id: Number(relation.id || 0), + contract: this.serializeRelation(relation, currentSubject, primaryQimenConfig), + list, + total: list.length, + }, + }; + } + + async saveQimenConfig(data = {}) { + const { ctx, app } = this; + const transaction = await ctx.model.transaction(); + + try { + const currentSubject = await this.getCurrentSubject(); + const relation = await this.findScopedRelation(data, currentSubject, transaction); + this.ensureWarehouseSubject(currentSubject); + const interfaceType = await this.getQimenInterfaceType(data, { transaction }); + const qimenAppKey = this.normalizeText(data.qimen_app_key, 'qimen_app_key', 100); + if (!qimenAppKey) { + throw this.createError('qimen_app_key 参数不能为空', 400); + } + const qimenCustomerId = this.normalizeText(data.qimen_customer_id, 'qimen_customer_id', 100); + if (!qimenCustomerId) { + throw this.createError('qimen_customer_id 参数不能为空', 400); + } + const qimenWarehouseCode = this.normalizeText(data.qimen_warehouse_code, 'qimen_warehouse_code', 100); + if (!qimenWarehouseCode) { + throw this.createError('qimen_warehouse_code 参数不能为空', 400); + } + + const relationPlain = relation && typeof relation.get === 'function' + ? relation.get({ plain: true }) + : relation; + const defaultAppName = [ + relationPlain && relationPlain.store_remask ? relationPlain.store_remask : currentSubject.company_name, + relationPlain && relationPlain.warehouse_remask + ? relationPlain.warehouse_remask + : (relationPlain && relationPlain.warehouse && relationPlain.warehouse.company_name ? relationPlain.warehouse.company_name : `contract-${relation.id}`), + '奇门接口', + ].filter(Boolean).join('-').slice(0, 200); + const appName = this.normalizeText(data.app_name, 'app_name', 200) || defaultAppName; + const apiVersion = this.normalizeText(data.api_version, 'api_version', 50) || '1.0'; + const signMethod = (this.normalizeText(data.sign_method, 'sign_method', 50) || 'md5').toLowerCase(); + if (![ 'md5', 'hmac', 'sha256' ].includes(signMethod)) { + throw this.createError('sign_method 参数不合法', 400); + } + + const rateLimit = this.normalizeIntegerRange(data.rate_limit, 'rate_limit', 1000, 1, 100000); + const timeoutSeconds = this.normalizeIntegerRange(data.timeout_seconds, 'timeout_seconds', 30, 1, 300); + const contactPerson = this.normalizeText(data.contact_person, 'contact_person', 100); + const contactPhone = this.normalizeText(data.contact_phone, 'contact_phone', 20); + const email = this.normalizeEmail(data.email); + const isEnabled = this.normalizeStatusFlag(data.is_enabled, 'is_enabled', 1); + + const where = { + interface_type_id: Number(interfaceType.id || 0), + contract_id: Number(relation.id || 0), + }; + let config = await ctx.model.ApiApp.findOne({ + where, + include: [ + { + model: ctx.model.InterfaceType, + as: 'interface_type', + attributes: [ 'id', 'interface_code', 'interface_name', 'interface_category', 'is_enabled' ], + required: false, + }, + ], + transaction, + }); + + const { Op } = app.Sequelize; + const duplicateWhere = { + interface_type_id: Number(interfaceType.id || 0), + qimen_app_key: qimenAppKey, + qimen_customer_id: qimenCustomerId, + }; + if (config && config.id) { + duplicateWhere.id = { [Op.ne]: config.id }; + } + const duplicateConfig = await ctx.model.ApiApp.findOne({ + where: duplicateWhere, + attributes: [ 'id', 'contract_id' ], + transaction, + }); + if (duplicateConfig) { + throw this.createError('该奇门 AppKey 和客户ID 已绑定其他签约关系', 409); + } + + const configPayload = { + app_name: appName, + interface_type_id: Number(interfaceType.id || 0), + contract_id: Number(relation.id || 0), + warehouse_id: relation.warehouse_id ? Number(relation.warehouse_id) : null, + qimen_app_key: qimenAppKey, + qimen_customer_id: qimenCustomerId, + qimen_warehouse_code: qimenWarehouseCode, + api_version: apiVersion, + sign_method: signMethod, + rate_limit: rateLimit, + timeout_seconds: timeoutSeconds, + contact_person: contactPerson || null, + contact_phone: contactPhone || null, + email, + is_enabled: isEnabled, + }; + + const previousConfig = config ? this.serializeQimenConfig(config) : null; + const action = config ? 'update' : 'create'; + if (config) { + await config.update(configPayload, { transaction }); + } else { + config = await ctx.model.ApiApp.create(configPayload, { transaction }); + } + + const savedConfig = await ctx.model.ApiApp.findByPk(config.id, { + include: [ + { + model: ctx.model.InterfaceType, + as: 'interface_type', + attributes: [ 'id', 'interface_code', 'interface_name', 'interface_category', 'is_enabled' ], + required: false, + }, + ], + transaction, + }); + const result = await ctx.model.StoreWarehouse.findByPk(relation.id, { + include: this.getRelationIncludes(), + transaction, + }); + const qimenConfig = this.serializeQimenConfig(savedConfig); + + await transaction.commit(); + await this.clearQimenContractCache([ previousConfig, qimenConfig ]).catch(error => { + ctx.logger.warn('[storeWarehouse.saveQimenConfig] 清理奇门缓存失败: %s', error.message); + }); + + return { + code: 200, + data: { + action, + contract: this.serializeRelation(result, currentSubject, qimenConfig), + qimen_config: qimenConfig, + }, + }; + } catch (error) { + await transaction.rollback(); + if (error && error.name === 'SequelizeUniqueConstraintError') { + throw this.createError('奇门接口配置已存在,请检查应用名或 AppKey / 客户ID 是否重复', 409); + } + if (error && error.name === 'SequelizeValidationError') { + const message = error.errors && error.errors.length ? error.errors[0].message : '奇门接口配置参数校验失败'; + throw this.createError(message, 400); + } + throw error; + } + } + + async deleteQimenConfig(data = {}) { + const { ctx } = this; + const transaction = await ctx.model.transaction(); + + try { + const currentSubject = await this.getCurrentSubject(); + const relation = await this.findScopedRelation(data, currentSubject, transaction); + this.ensureWarehouseSubject(currentSubject); + const interfaceType = await this.getQimenInterfaceType(data, { + allowDisabled: true, + transaction, + }); + const config = await ctx.model.ApiApp.findOne({ + where: { + contract_id: Number(relation.id || 0), + interface_type_id: Number(interfaceType.id || 0), + }, + include: [ + { + model: ctx.model.InterfaceType, + as: 'interface_type', + attributes: [ 'id', 'interface_code', 'interface_name', 'interface_category', 'is_enabled' ], + required: false, + }, + ], + transaction, + }); + + if (!config) { + throw this.createError('奇门接口配置不存在', 404); + } + + const removedConfig = this.serializeQimenConfig(config); + await config.destroy({ transaction }); + + const result = await ctx.model.StoreWarehouse.findByPk(relation.id, { + include: this.getRelationIncludes(), + transaction, + }); + + await transaction.commit(); + await this.clearQimenContractCache([ removedConfig ]).catch(error => { + ctx.logger.warn('[storeWarehouse.deleteQimenConfig] 清理奇门缓存失败: %s', error.message); + }); + + return { + code: 200, + data: { + deleted: true, + contract: this.serializeRelation(result, currentSubject, null), + qimen_config: null, + removed: removedConfig, + }, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + async unbind(data = {}) { + const { ctx } = this; + const transaction = await ctx.model.transaction(); + + try { + const currentSubject = await this.getCurrentSubject(); + const relation = await this.findScopedRelation(data, currentSubject, transaction); + const nextUseStatus = this.normalizeStatusFlag(data.use_status, 'use_status', 0); + + await relation.update({ + use_status: nextUseStatus, + }, { transaction }); + + const result = await ctx.model.StoreWarehouse.findByPk(relation.id, { + include: this.getRelationIncludes(), + transaction, + }); + const qimenConfig = await this.getSingleQimenConfig(relation.id, { + allowDisabled: true, + transaction, + }); + + await transaction.commit(); + + return { + code: 200, + data: { + contract: this.serializeRelation(result, currentSubject, qimenConfig), + }, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } +} + +module.exports = SettingStoreWarehouseService; diff --git a/app/service/systems/upload.js b/app/service/systems/upload.js index b25a8e2..763d2c7 100644 --- a/app/service/systems/upload.js +++ b/app/service/systems/upload.js @@ -411,6 +411,21 @@ class UploadService extends Service { md5Hash = crypto.createHash('md5').update(data.fileContent).digest('hex'); } + const resolvedFileType = String(data.fileType || data.category || data.type || 'document'); + const resolvedMimeType = String(data.mimeType || data.type || this.getMimeType(data.fileName || data.name || 'file.xlsx')); + const defaultExpireDays = data.businessType === 'receivingReport' ? 90 : 0; + const requestedExpireDays = Number(data.expireDays || defaultExpireDays || 0); + let resolvedExpireTime = data.expireTime || data.expire_time || null; + + if (!resolvedExpireTime && Number.isFinite(requestedExpireDays) && requestedExpireDays > 0) { + resolvedExpireTime = new Date(Date.now() + requestedExpireDays * 24 * 60 * 60 * 1000); + } + + if (resolvedExpireTime) { + const expireDate = resolvedExpireTime instanceof Date ? resolvedExpireTime : new Date(resolvedExpireTime); + resolvedExpireTime = Number.isNaN(expireDate.getTime()) ? null : expireDate; + } + // 构建数据库记录 const fileRecord = { warehouse_id: warehouseId || 0, // 默认为0或使用默认仓库 @@ -418,14 +433,15 @@ class UploadService extends Service { file_url: fileUrl, file_name: data.name, file_size: data.size, - file_type: data.type, - mime_type: data.type, + file_type: resolvedFileType, + mime_type: resolvedMimeType, md5_hash: md5Hash || '', storage_mode: 'cos', storage_class: 'standard', uploader_id: userId?.toString() || '0', uploader_name: userName, uploader_dept: data.uploaderDept || '', + expire_time: resolvedExpireTime || null, created_at: new Date(), }; @@ -440,12 +456,20 @@ class UploadService extends Service { }); if (existingFile) { + if (resolvedExpireTime && (!existingFile.expire_time || new Date(existingFile.expire_time).getTime() < resolvedExpireTime.getTime())) { + await existingFile.update({ + expire_time: resolvedExpireTime, + updated_at: new Date(), + }); + } + this.ctx.logger.info(`文件已存在,返回已有记录: ${existingFile.file_url}`); return { fileId: existingFile.id, fileUrl: existingFile.file_url, fileKey: existingFile.file_key, fileName: existingFile.file_name, + expireTime: resolvedExpireTime || existingFile.expire_time || null, isNew: false, }; } diff --git a/config/config.default.js b/config/config.default.js index 4c783ee..9c88140 100644 --- a/config/config.default.js +++ b/config/config.default.js @@ -172,6 +172,7 @@ module.exports = appInfo => { config.poloapi ={ } + config.debug = false; // 生成环境默认关闭 debug,开发环境通过 config.local.js 开启 config.printService = { url: 'http://printer.wms.gztbyc.com', }; diff --git a/database/config.js b/database/config.js new file mode 100644 index 0000000..852d9fd --- /dev/null +++ b/database/config.js @@ -0,0 +1,83 @@ +'use strict'; + +const fs = require('node:fs'); +const path = require('node:path'); + +function isPlainObject(value) { + return !!value && typeof value === 'object' && !Array.isArray(value); +} + +function mergeDeep(target, source) { + const output = isPlainObject(target) ? { ...target } : {}; + if (!isPlainObject(source)) { + return output; + } + + for (const [ key, value ] of Object.entries(source)) { + if (isPlainObject(value) && isPlainObject(output[key])) { + output[key] = mergeDeep(output[key], value); + } else if (isPlainObject(value)) { + output[key] = mergeDeep({}, value); + } else { + output[key] = value; + } + } + + return output; +} + +function loadEggConfig(configPath) { + if (!fs.existsSync(configPath)) { + return {}; + } + + const configFactory = require(configPath); + const config = typeof configFactory === 'function' + ? configFactory({ name: 'sequelize-cli', baseDir: path.dirname(path.dirname(configPath)) }) + : configFactory; + + return isPlainObject(config) ? config : {}; +} + +function resolveMysqlClient(appConfig, clientName) { + const clients = appConfig && appConfig.mysql && appConfig.mysql.clients; + if (clients && clients[clientName]) { + return clients[clientName]; + } + + if (appConfig && appConfig.mysql && appConfig.mysql.host) { + return appConfig.mysql; + } + + throw new Error(`MySQL client "${clientName}" not found in Egg config.`); +} + +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); + +const baseConfig = { + username: mysqlClient.user, + password: mysqlClient.password, + database: mysqlClient.database, + host: mysqlClient.host, + port: Number(mysqlClient.port || 3306), + dialect: 'mysql', + logging: false, + define: { + freezeTableName: true, + underscored: true, + timestamps: true, + paranoid: true, + deletedAt: 'deleted_at', + }, +}; + +module.exports = { + development: { ...baseConfig }, + test: { ...baseConfig }, + production: { ...baseConfig }, +}; diff --git a/database/migrations/20260404093000-add-policy-config-to-wms-store-warehouse.js b/database/migrations/20260404093000-add-policy-config-to-wms-store-warehouse.js new file mode 100644 index 0000000..3ba7243 --- /dev/null +++ b/database/migrations/20260404093000-add-policy-config-to-wms-store-warehouse.js @@ -0,0 +1,25 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + const [ columns ] = await queryInterface.sequelize.query("SHOW COLUMNS FROM `wms_store_warehouse` LIKE 'policy_config'"); + if (columns.length > 0) { + return; + } + + await queryInterface.addColumn('wms_store_warehouse', 'policy_config', { + type: Sequelize.JSON, + allowNull: true, + comment: '货主在仓库的配置与策略', + }); + }, + + async down(queryInterface, Sequelize) { + const [ columns ] = await queryInterface.sequelize.query("SHOW COLUMNS FROM `wms_store_warehouse` LIKE 'policy_config'"); + if (columns.length === 0) { + return; + } + + await queryInterface.removeColumn('wms_store_warehouse', 'policy_config'); + }, +}; diff --git a/database/migrations/20260404113000-create-wms-notification-webhook.js b/database/migrations/20260404113000-create-wms-notification-webhook.js new file mode 100644 index 0000000..77e274f --- /dev/null +++ b/database/migrations/20260404113000-create-wms-notification-webhook.js @@ -0,0 +1,154 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + const { BIGINT, STRING, TINYINT, DATE, JSON } = Sequelize; + const BIGINT_UNSIGNED = BIGINT.UNSIGNED; + + const [ tables ] = await queryInterface.sequelize.query( + "SHOW TABLES LIKE 'wms_notification_webhook'" + ); + + const tableExists = tables.length > 0; + + if (!tableExists) { + await queryInterface.createTable('wms_notification_webhook', { + id: { + type: BIGINT_UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + store_id: { + type: BIGINT_UNSIGNED, + allowNull: false, + comment: '主体ID,对应 wms_store.id', + references: { + model: 'wms_store', + key: 'id', + }, + onUpdate: 'CASCADE', + onDelete: 'CASCADE', + }, + hook_name: { + type: STRING(100), + allowNull: true, + comment: 'Webhook 名称', + }, + hook_type: { + type: STRING(50), + allowNull: false, + comment: 'Webhook 类型,用于分派不同消息结构处理类,如 dingtalk、wecom、feishu、custom', + }, + hook_url: { + type: STRING(500), + allowNull: false, + comment: 'Webhook 链接地址', + }, + events: { + type: JSON, + allowNull: true, + comment: '订阅事件列表', + }, + extra_config: { + type: JSON, + allowNull: true, + comment: '扩展配置,如签名、请求头、模板映射等', + }, + status: { + type: TINYINT(4), + allowNull: false, + defaultValue: 1, + comment: '状态:0-禁用,1-启用', + }, + remark: { + type: STRING(255), + allowNull: true, + comment: '备注', + }, + created_by: { + type: BIGINT_UNSIGNED, + allowNull: true, + comment: '创建人', + }, + created_at: { + type: DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '删除时间', + }, + }, { + engine: 'InnoDB', + charset: 'utf8mb4', + collate: 'utf8mb4_unicode_ci', + comment: '外部通知 WebHook 配置表', + }); + } else { + console.log('Table wms_notification_webhook already exists, ensuring schema and indexes'); + } + + const [ hookUrlColumns ] = await queryInterface.sequelize.query("SHOW COLUMNS FROM `wms_notification_webhook` LIKE 'hook_url'"); + if (hookUrlColumns.length > 0) { + const currentType = String(hookUrlColumns[0].Type || '').toLowerCase(); + if (currentType.includes('varchar(1000)')) { + await queryInterface.changeColumn('wms_notification_webhook', 'hook_url', { + type: STRING(500), + allowNull: false, + comment: 'Webhook 链接地址', + }); + } + } + + const safeCreateIndex = async (tableName, fields, options) => { + const [ existingIndexes ] = await queryInterface.sequelize.query( + `SHOW INDEX FROM ${tableName} WHERE Key_name = '${options.name}'` + ); + if (existingIndexes.length === 0) { + await queryInterface.addIndex(tableName, fields, options); + } + }; + + await safeCreateIndex('wms_notification_webhook', [ 'store_id' ], { + name: 'idx_notification_webhook_store_id', + }); + + await safeCreateIndex('wms_notification_webhook', [ 'hook_type' ], { + name: 'idx_notification_webhook_hook_type', + }); + + await safeCreateIndex('wms_notification_webhook', [ 'status' ], { + name: 'idx_notification_webhook_status', + }); + + await safeCreateIndex('wms_notification_webhook', [ 'store_id', 'hook_type' ], { + name: 'idx_notification_webhook_store_type', + }); + + await safeCreateIndex('wms_notification_webhook', [ 'store_id', 'hook_type', 'hook_url' ], { + name: 'uk_notification_webhook_store_type_url', + unique: true, + }); + }, + + async down(queryInterface) { + const [ tables ] = await queryInterface.sequelize.query( + "SHOW TABLES LIKE 'wms_notification_webhook'" + ); + + if (tables.length > 0) { + await queryInterface.dropTable('wms_notification_webhook'); + } + }, +}; diff --git a/database/migrations/20260405002000-add-expire-time-to-wms-file.js b/database/migrations/20260405002000-add-expire-time-to-wms-file.js new file mode 100644 index 0000000..fb3a9e8 --- /dev/null +++ b/database/migrations/20260405002000-add-expire-time-to-wms-file.js @@ -0,0 +1,26 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + const [ columns ] = await queryInterface.sequelize.query("SHOW COLUMNS FROM `wms_file` LIKE 'expire_time'"); + if (columns.length > 0) { + return; + } + + await queryInterface.addColumn('wms_file', 'expire_time', { + type: Sequelize.DATE, + allowNull: true, + defaultValue: null, + comment: '过期时间,为空表示永不过期', + }); + }, + + async down(queryInterface) { + const [ columns ] = await queryInterface.sequelize.query("SHOW COLUMNS FROM `wms_file` LIKE 'expire_time'"); + if (columns.length === 0) { + return; + } + + await queryInterface.removeColumn('wms_file', 'expire_time'); + }, +}; diff --git a/docs/express-model-table-map.md b/docs/express-model-table-map.md new file mode 100644 index 0000000..72f403b --- /dev/null +++ b/docs/express-model-table-map.md @@ -0,0 +1,24 @@ +# Express 模型与数据表整理 + +## 一览 + +| 模型文件 | Sequelize key | 数据表 | 当前状态 | +| --- | --- | --- | --- | +| app/model/express.js | Express | wms_express | 已补齐 | +| app/model/express_setting.js | ExpressSetting | wms_express_setting | 已补齐 | +| app/model/order_express.js | OrderExpress | wms_order_express | 已补齐 | +| app/model/order_express_print_data.js | OrderExpressPrintData | wms_order_express_print_data | 已补齐 | +| app/model/express_print_record.js | ExpressPrintRecord | wms_express_print_record | 已补齐 | +| app/model/print_station_express.js | PrintStationExpress | wms_print_station_express | 已存在 | + +## 关键说明 + +- 本次仅整理模型与真实数据表对齐,不改动业务逻辑与接口行为。 +- 通过 `script/db-query.ps1` 实查,数据库中包含 6 张 express 相关表,上述模型已全部覆盖。 +- 既有字段型快递信息(如 `wms_entry_order.express_code`、`wms_order_delivery.express_code`)仍保留为业务字段,不属于独立主数据表。 + +## 建议的后续收敛 + +- 将 `index.getExpressList` 的配置源(`app.config.expressList`)逐步收敛到 `wms_express`,避免配置与数据表双源。 +- 若后续存在统一查询需求,可新增 `systems/express.js`,统一对 `Express / ExpressSetting / OrderExpress` 的读写入口。 +- 打印链路可逐步将 `wms_print_station_express` 与 `wms_express_print_record` 做关联查询封装,减少 systemMethods 层的散落操作。 diff --git a/methods/gateway.json b/methods/gateway.json index 1ddc55f..c39b061 100644 --- a/methods/gateway.json +++ b/methods/gateway.json @@ -1,8 +1,8 @@ { "module": "gateway", "description": "内部网关接口,供内网系统间调用,统一使用 POST 请求", - "version": "0.1.0", - "updatedAt": "2026-03-24", + "version": "0.2.0", + "updatedAt": "2026-03-29", "headers": [], "methods": { "groups": [ @@ -12,7 +12,7 @@ "list": [ { "method": "user.getUserByTempCode", - "description": "根据绑定码反查WMS账号ID(供 ye4s 扫码绑定调用)", + "description": "根据绑定码反查WMS账号ID并写入扫码状态(扫描即视为已确认,状态缓存3分钟)", "isNeedAuth": false, "isNeedLogin": false, "headers": [], @@ -22,7 +22,7 @@ "type": "string", "required": true, "source": "body", - "description": "绑定码(由 user.getBindWechatCode 生成)" + "description": "绑定码(由 user.getBindWechatCode 生成,6位字母数字混合)" } ], "response": [ @@ -32,24 +32,30 @@ "required": true, "description": "匹配到的 WMS 账号ID" }, + { + "name": "real_name", + "type": "string", + "required": true, + "description": "WMS 账号表中的真实姓名,用于扫码绑定前确认账号" + }, { "name": "status", "type": "string", "required": true, - "description": "当前绑定状态,如 pending/bound" + "description": "当前扫码状态,成功扫码后固定为 scanned" }, { "name": "source", "type": "string", "required": true, - "description": "数据来源,如 cache/db" + "description": "数据来源,如 scan-cache" } ], "errors": [] }, { "method": "user.bindAccountByTempCode", - "description": "根据绑定码将 ye4s 用户绑定到 WMS 账号(供 ye4s 扫码后回调)", + "description": "根据绑定码对应的扫码状态缓存将 ye4s 用户绑定到 WMS 账号(需先调用扫码反查接口)", "isNeedAuth": false, "isNeedLogin": false, "headers": [], @@ -59,7 +65,7 @@ "type": "string", "required": true, "source": "body", - "description": "绑定码(由 user.getBindWechatCode 生成)" + "description": "绑定码(由 user.getBindWechatCode 生成,6位字母数字混合)" }, { "name": "ye4s_user_id", @@ -92,6 +98,141 @@ "errors": [] } ] + }, + { + "groupName": "打印绑定模块", + "module": "print", + "list": [ + { + "method": "print.getBindInfo", + "description": "根据 WMS 账号ID和扫码 code 返回可绑定仓库列表;有可绑定仓库时下发 300 秒临时凭据 tempCode,无可绑定仓库时返回空数组且不返回 tempCode", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "account_id", + "type": "number", + "required": true, + "source": "body", + "description": "WMS 账号ID" + }, + { + "name": "code", + "type": "string", + "required": true, + "source": "body", + "description": "打印端提供的绑定 code" + } + ], + "response": [ + { + "name": "warehouses", + "type": "array", + "required": true, + "description": "可绑定仓库列表,元素结构为 { id, name }" + }, + { + "name": "tempCode", + "type": "string", + "required": false, + "description": "临时绑定凭据,仅当 warehouses 非空时返回" + } + ], + "errors": [ + { + "code": 0, + "message": "缺少有效参数 account_id 或 code" + }, + { + "code": 0, + "message": "账号不存在或已禁用" + }, + { + "code": 0, + "message": "无效code或未绑定" + } + ] + }, + { + "method": "print.bindByTempCode", + "description": "根据第一步返回的临时凭据执行打印台绑定,提交工作台名称和仓库ID后完成真实绑定", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "temp_code", + "type": "string", + "required": true, + "source": "body", + "description": "第一步返回的临时凭据,300 秒有效" + }, + { + "name": "printer", + "type": "string", + "required": true, + "source": "body", + "description": "工作台名称" + }, + { + "name": "warehouse", + "type": "number", + "required": true, + "source": "body", + "description": "仓库ID" + } + ], + "response": [ + { + "name": "code", + "type": "string", + "required": true, + "description": "真实绑定 code" + }, + { + "name": "printer", + "type": "string", + "required": true, + "description": "工作台名称" + }, + { + "name": "warehouse", + "type": "number", + "required": true, + "description": "仓库ID" + }, + { + "name": "computerId", + "type": "number", + "required": true, + "description": "打印台电脑ID" + } + ], + "errors": [ + { + "code": 0, + "message": "参数缺失" + }, + { + "code": 0, + "message": "临时code无效或已过期" + }, + { + "code": 0, + "message": "仓库无绑定权限" + }, + { + "code": 0, + "message": "仓库id校验失败" + }, + { + "code": 0, + "message": "该仓库下打印台名称已存在且可用" + } + ] + } + ] } ] } diff --git a/methods/system.json b/methods/system.json index d7c9e13..67c9e18 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1,4419 +1,4897 @@ { - "module": "system", - "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", - "version": "0.3.0", - "updatedAt": "2026-03-23", - "headers": [ + "module": "system", + "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", + "version": "0.3.0", + "updatedAt": "2026-03-22", + "headers": [ + { + "name": "platform", + "type": "string", + "required": true, + "description": "客户端平台标识,如 web/pda/app", + "list": [ { - "name": "platform", - "type": "string", - "required": true, - "description": "客户端平台标识,如 web/pda/app", - "list": [ - { - "value": "web", - "name": "网页端" - }, - { - "value": "pda", - "name": "PDA端" - }, - { - "value": "app", - "name": "APP端" - }, - { - "value": "wx", - "name": "微信端" - }, - { - "value": "miniProgram", - "name": "小程序端" - }, - { - "value": "other", - "name": "其他" - } - ] + "value": "web", + "name": "网页端" }, { - "type": "string", - "required": true, - "name": "project", - "description": "项目标识,如 all/warehouse/store/tms", - "list": [ - { - "value": "all", - "name": "全部" - }, - { - "value": "warehouse", - "name": "仓库" - }, - { - "value": "store", - "name": "货主" - }, - { - "value": "tms", - "name": "物流" - } - ] + "value": "pda", + "name": "PDA端" + }, + { + "value": "app", + "name": "APP端" + }, + { + "value": "wx", + "name": "微信端" + }, + { + "value": "miniProgram", + "name": "小程序端" + }, + { + "value": "other", + "name": "其他" } - ], - "methods": { - "groups": [ - { - "groupName": "配置模块", - "module": "config", - "list": [ - { - "method": "config.list", - "description": "config.list 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - } - ] - }, - { - "groupName": "看板模块", - "module": "dashboard", - "list": [ - { - "method": "dashboard.storeStats", - "description": "dashboard.storeStats 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "dashboard.warehouseStats", - "description": "dashboard.warehouseStats 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "dashboard.hot_order_rank", - "description": "dashboard.hot_order_rank 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "dashboard.express_ratio", - "description": "dashboard.express_ratio 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "dashboard.platform_distribution", - "description": "dashboard.platform_distribution 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "dashboard.order_trend", - "description": "dashboard.order_trend 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - } - ] - }, - { - "groupName": "基础模块", - "module": "index", - "list": [ - { - "method": "index.fastWhereTree", - "description": "index.fastWhereTree 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "type", - "type": "string", - "required": false, - "source": "body", - "description": "type 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "index.loadStores", - "description": "index.loadStores 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "index.getCOSUploadConfig", - "description": "index.getCOSUploadConfig 接口", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "data", - "type": "object", - "required": false, - "source": "body", - "description": "data 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "index.getImages", - "description": "index.getImages 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "index.uploadSuccessNotify", - "description": "index.uploadSuccessNotify 接口", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "index.ReferenceFile", - "description": "index.ReferenceFile 接口", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "index.getMessageDetail", - "description": "index.getMessageDetail 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "index.getI18nMessage", - "description": "index.getI18nMessage 接口", - "isNeedAuth": false, - "isNeedLogin": false, - "headers": [], - "params": [ - { - "name": "language", - "type": "string", - "required": false, - "source": "body|query", - "description": "language 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "index.putI18nCollect", - "description": "index.putI18nCollect 接口", - "isNeedAuth": false, - "isNeedLogin": false, - "headers": [], - "params": [ - { - "name": "keys", - "type": "array", - "required": false, - "source": "body", - "description": "keys 参数" - }, - { - "name": "locale", - "type": "string", - "required": false, - "source": "body", - "description": "locale 参数" - }, - { - "name": "project", - "type": "string", - "required": false, - "source": "body", - "description": "project 参数" - }, - { - "name": "source", - "type": "string", - "required": false, - "source": "body", - "description": "source 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "index.tryAutoTranslateNewKeys", - "description": "index.tryAutoTranslateNewKeys 接口", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "index.searchSpace", - "description": "index.searchSpace 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "index.getExpressList", - "description": "index.getExpressList 接口", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - } - ] - }, - { - "groupName": "订单模块", - "module": "order", - "list": [ - { - "method": "order.getOrderModels", - "description": "order.getOrderModels 接口", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "order.list", - "description": "分页查询订单列表", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "pagination", - "type": "object", - "required": false, - "source": "body", - "description": "pagination 参数" - }, - { - "name": "where", - "type": "object", - "required": false, - "source": "body", - "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会在 main 中自动标准化;常用字段包括 delivery_order_code、status、outbound_status、buyer_nick、mobile 与日期区间字段。示例:where.delivery_order_code={operator:like,value:SO202603}; where.status={operator:in,value:[created,pedding]}。" - } - ], - "response": [], - "errors": [] - }, - { - "method": "order.detail", - "description": "查询订单详情", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "delivery_order_code", - "type": "string", - "required": false, - "source": "body", - "description": "delivery_order_code 参数" - }, - { - "name": "id", - "type": "number", - "required": false, - "source": "body", - "description": "id 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "order.listItems", - "description": "查询订单商品明细", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "delivery_order_code", - "type": "string", - "required": false, - "source": "body", - "description": "delivery_order_code 参数" - }, - { - "name": "order_id", - "type": "number", - "required": false, - "source": "body", - "description": "order_id 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "order.stats", - "description": "订单统计", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "where", - "type": "object", - "required": false, - "source": "body", - "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会在 main 中自动标准化;统计口径与 order.list 共用筛选字段。示例:where.status={operator:eq,value:fin}; where.create_time_start={value:2026-03-01}; where.create_time_end={value:2026-03-31}。" - } - ], - "response": [], - "errors": [] - }, - { - "method": "order.getreviewOrderlist", - "description": "分页查询订单审核列表", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "pagination", - "type": "object", - "required": false, - "source": "body", - "description": "pagination 参数" - }, - { - "name": "where", - "type": "object", - "required": false, - "source": "body", - "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构;支持 inspection_status、operator_name、operate_time_start、operate_time_end 等字段。示例:where.inspection_status={operator:eq,value:pending}; where.operator_name={operator:like,value:张}; where.operate_time_start={value:2026-03-01}。" - } - ], - "response": [], - "errors": [] - }, - { - "method": "order.updateStatus", - "description": "更新订单状态", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "claim_status", - "type": "string", - "required": false, - "source": "body", - "description": "claim_status 参数" - }, - { - "name": "delivery_order_code", - "type": "string", - "required": false, - "source": "body", - "description": "delivery_order_code 参数" - }, - { - "name": "delivery_time", - "type": "string", - "required": false, - "source": "body", - "description": "delivery_time 参数" - }, - { - "name": "id", - "type": "number", - "required": false, - "source": "body", - "description": "id 参数" - }, - { - "name": "inspection_status", - "type": "string", - "required": false, - "source": "body", - "description": "inspection_status 参数" - }, - { - "name": "intercept_status", - "type": "string", - "required": false, - "source": "body", - "description": "intercept_status 参数" - }, - { - "name": "lock_status", - "type": "string", - "required": false, - "source": "body", - "description": "lock_status 参数" - }, - { - "name": "outbound_status", - "type": "string", - "required": false, - "source": "body", - "description": "outbound_status 参数" - }, - { - "name": "pack_status", - "type": "string", - "required": false, - "source": "body", - "description": "pack_status 参数" - }, - { - "name": "pick_status", - "type": "string", - "required": false, - "source": "body", - "description": "pick_status 参数" - }, - { - "name": "post_status", - "type": "string", - "required": false, - "source": "body", - "description": "post_status 参数" - }, - { - "name": "print_status", - "type": "string", - "required": false, - "source": "body", - "description": "print_status 参数" - }, - { - "name": "status", - "type": "string", - "required": false, - "source": "body", - "description": "status 参数" - }, - { - "name": "storage_status", - "type": "string", - "required": false, - "source": "body", - "description": "storage_status 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "order.updateDeliveryTime", - "description": "更新发货时间", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "delivery_time", - "type": "string", - "required": true, - "source": "body", - "description": "delivery_time 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "order.reviewOrder", - "description": "订单审核", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "delivery_order_code", - "type": "string", - "required": false, - "source": "body", - "description": "delivery_order_code 参数" - }, - { - "name": "id", - "type": "number", - "required": false, - "source": "body", - "description": "id 参数" - }, - { - "name": "inspection_status", - "type": "string", - "required": false, - "source": "body", - "description": "inspection_status 参数(兼容入参)" - }, - { - "name": "review_status", - "type": "string", - "required": false, - "source": "body", - "description": "review_status 参数,默认 fin" - }, - { - "name": "operator_name", - "type": "string", - "required": false, - "source": "body", - "description": "operator_name 参数" - }, - { - "name": "operate_time", - "type": "string", - "required": false, - "source": "body", - "description": "operate_time 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "order.reviewOrder.getreviewOrderlist", - "description": "分页查询订单审核列表(目录化路由)", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "pagination", - "type": "object", - "required": false, - "source": "body", - "description": "pagination 参数" - }, - { - "name": "where", - "type": "object", - "required": false, - "source": "body", - "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构;支持 inspection_status、operator_name、operate_time_start、operate_time_end 等字段。示例:where.inspection_status={operator:eq,value:pending}; where.operator_name={operator:like,value:张}; where.operate_time_start={value:2026-03-01}。" - } - ], - "response": [], - "errors": [] - }, - { - "method": "order.reviewOrder.reviewOrder", - "description": "订单审核(目录化路由)", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "delivery_order_code", - "type": "string", - "required": false, - "source": "body", - "description": "delivery_order_code 参数" - }, - { - "name": "id", - "type": "number", - "required": false, - "source": "body", - "description": "id 参数" - }, - { - "name": "inspection_status", - "type": "string", - "required": false, - "source": "body", - "description": "inspection_status 参数(兼容入参)" - }, - { - "name": "review_status", - "type": "string", - "required": false, - "source": "body", - "description": "review_status 参数,默认 fin" - }, - { - "name": "operator_name", - "type": "string", - "required": false, - "source": "body", - "description": "operator_name 参数" - }, - { - "name": "operate_time", - "type": "string", - "required": false, - "source": "body", - "description": "operate_time 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "order.deliveryOrder.getdeliveryOrderlist", - "description": "分页查询已进入出库流程的订单列表", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "pagination", - "type": "object", - "required": false, - "source": "body", - "description": "pagination 参数" - }, - { - "name": "where", - "type": "object", - "required": false, - "source": "body", - "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构;未传 outbound_status 时默认过滤 outbound_status != none。示例:where.outbound_status={operator:in,value:[created,processing]}; where.store_id={operator:eq,value:1001}。" - } - ], - "response": [], - "errors": [] - }, - { - "method": "order.pendingOrder.getpendingOrderlist", - "description": "分页查询待处理订单列表", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "pagination", - "type": "object", - "required": false, - "source": "body", - "description": "pagination 参数" - }, - { - "name": "where", - "type": "object", - "required": false, - "source": "body", - "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构;未传时默认 status in [pedding, created] 且 outbound_status = none。示例:where.status={operator:in,value:[pedding,created]}; where.outbound_status={operator:eq,value:none}。" - } - ], - "response": [], - "errors": [] - }, - { - "method": "order.expectionOrder.getexpectionOrderlist", - "description": "分页查询异常订单列表", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "pagination", - "type": "object", - "required": false, - "source": "body", - "description": "pagination 参数" - }, - { - "name": "where", - "type": "object", - "required": false, - "source": "body", - "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构;未传时默认筛选各流程 error 或拦截 exception。示例:where.status={operator:eq,value:error}; where.outbound_status={operator:eq,value:exception}。" - } - ], - "response": [], - "errors": [] - }, - { - "method": "order.archiveOrder.getarchiveOrderlist", - "description": "分页查询归档订单列表(暂使用当前订单表完成态数据)", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "pagination", - "type": "object", - "required": false, - "source": "body", - "description": "pagination 参数" - }, - { - "name": "where", - "type": "object", - "required": false, - "source": "body", - "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构;未传 outbound_status 时默认过滤 outbound_status = fin。示例:where.outbound_status={operator:eq,value:fin}; where.store_id={operator:eq,value:1001}。" - } - ], - "response": [], - "errors": [] - } - ] - }, - { - "groupName": "打印模块", - "module": "print", - "list": [ - { - "method": "print.send", - "description": "print.send 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "computerId", - "type": "string", - "required": false, - "source": "body", - "description": "computerId 参数" - }, - { - "name": "count", - "type": "number", - "required": false, - "source": "body", - "description": "count 参数" - }, - { - "name": "data", - "type": "object", - "required": false, - "source": "body", - "description": "data 参数" - }, - { - "name": "printer", - "type": "string", - "required": false, - "source": "body", - "description": "printer 参数" - }, - { - "name": "template", - "type": "object", - "required": false, - "source": "body", - "description": "template 参数" - }, - { - "name": "timestamp", - "type": "string", - "required": false, - "source": "body", - "description": "timestamp 参数" - }, - { - "name": "type", - "type": "string", - "required": false, - "source": "body", - "description": "type 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "print.getPrintResult", - "description": "print.getPrintResult 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "printId", - "type": "string", - "required": true, - "source": "body", - "description": "printId 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "print.getPrintRecordItem", - "description": "print.getPrintRecordItem 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "id", - "type": "number", - "required": true, - "source": "body", - "description": "id 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "print.getList", - "description": "print.getList 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "page", - "type": "number", - "required": false, - "source": "body", - "description": "page 参数" - }, - { - "name": "pageSize", - "type": "number", - "required": false, - "source": "body", - "description": "pageSize 参数" - }, - { - "name": "where", - "type": "object", - "required": false, - "source": "body", - "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会在 main 中自动标准化;当前支持 id、name、computer_id、custom_barcode。示例:where.name={operator:like,value:热敏}; where.computer_id={operator:eq,value:PC-01}。" - } - ], - "response": [], - "errors": [] - }, - { - "method": "print.getItem", - "description": "print.getItem 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "id", - "type": "number", - "required": true, - "source": "body", - "description": "id 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "print.add", - "description": "print.add 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "computer_id", - "type": "number", - "required": true, - "source": "body", - "description": "computer_id 参数" - }, - { - "name": "name", - "type": "string", - "required": true, - "source": "body", - "description": "name 参数" - }, - { - "name": "custom_barcode", - "type": "string", - "required": false, - "source": "body", - "description": "custom_barcode 参数" - }, - { - "name": "default_printer_name", - "type": "string", - "required": false, - "source": "body", - "description": "default_printer_name 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "print.hasName", - "description": "print.hasName 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "name", - "type": "string", - "required": true, - "source": "body", - "description": "name 参数" - }, - { - "name": "id", - "type": "number", - "required": false, - "source": "body", - "description": "id 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "print.updateItem", - "description": "print.updateItem 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "id", - "type": "number", - "required": true, - "source": "body", - "description": "id 参数" - }, - { - "name": "computer_id", - "type": "number", - "required": false, - "source": "body", - "description": "computer_id 参数" - }, - { - "name": "custom_barcode", - "type": "string", - "required": false, - "source": "body", - "description": "custom_barcode 参数" - }, - { - "name": "name", - "type": "string", - "required": false, - "source": "body", - "description": "name 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "print.del", - "description": "print.del 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "ids", - "type": "array", - "required": false, - "source": "body", - "description": "ids 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "print.getComputer", - "description": "print.getComputer 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "print.getComputerPrinter", - "description": "print.getComputerPrinter 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "id", - "type": "number", - "required": true, - "source": "body", - "description": "id 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "print.savePrinters", - "description": "print.savePrinters 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "defaultPrinter", - "type": "string", - "required": true, - "source": "body", - "description": "defaultPrinter 参数" - }, - { - "name": "express", - "type": "array", - "required": false, - "source": "body", - "description": "express 参数" - }, - { - "name": "print_station_id", - "type": "number", - "required": false, - "source": "body", - "description": "print_station_id 参数" - } - ], - "response": [], - "errors": [] - } - ] - }, - { - "groupName": "打印机站点模块", - "module": "printer.station", - "list": [ - { - "method": "printer.station.list", - "description": "获取打印站点列表", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - } - ] - }, - { - "groupName": "打印模板模块", - "module": "setting.printTemplate", - "list": [ - { - "method": "setting.printTemplate.list", - "description": "获取打印模板树", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "setting.printTemplate.save", - "description": "保存打印模板", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "setting.printTemplate.create", - "description": "创建打印模板(platform 固定为 default,template_type 固定为 CUSTOM,template_url 固定为空字符串)", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "template_name", - "type": "string", - "required": true, - "source": "body", - "description": "模板名称" - }, - { - "name": "business_type", - "type": "string", - "required": true, - "source": "body", - "description": "业务类型" - }, - { - "name": "page_width", - "type": "number", - "required": true, - "source": "body", - "description": "页面宽度(mm)" - }, - { - "name": "page_height", - "type": "number", - "required": true, - "source": "body", - "description": "页面高度(mm)" - }, - { - "name": "template_content", - "type": "array", - "required": false, - "source": "body", - "description": "模板内容,可省略;省略时默认创建空模板内容" - } - ], - "response": [ - { - "name": "id", - "type": "number", - "required": true, - "description": "新建模板ID" - } - ], - "errors": [ - { - "code": "400", - "description": "参数错误(缺少 template_name、business_type、page_width 或 page_height)" - }, - { - "code": "409", - "description": "同一业务类型和平台下已存在自定义模板" - } - ] - }, - { - "method": "setting.printTemplate.delete", - "description": "删除打印模板(软删除)", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "id", - "type": "number", - "required": true, - "source": "body", - "description": "模板ID" - } - ], - "response": [ - { - "name": "id", - "type": "number", - "required": true, - "description": "删除的模板ID" - } - ], - "errors": [ - { - "code": "400", - "description": "参数错误(缺少 id)" - }, - { - "code": "404", - "description": "模板不存在或无权限" - } - ] - }, - { - "method": "setting.printTemplate.listTemplatesByType", - "description": "按业务类型查询模板", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "businessType", - "type": "string", - "required": true, - "source": "body", - "description": "businessType 参数" - } - ], - "response": [], - "errors": [] - } - ] - }, - { - "groupName": "账号管理模块", - "module": "setting.account", - "list": [ - { - "method": "setting.account.list", - "description": "查询当前主体下的工号基础信息列表", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "status", - "type": "number", - "required": false, - "source": "body", - "description": "状态筛选,默认 1,仅查有效工号" - }, - { - "name": "includeDisabled", - "type": "boolean", - "required": false, - "source": "body", - "description": "是否包含已删除工号" - } - ], - "response": [ - { - "name": "data[]", - "type": "object", - "required": true, - "description": "工号列表项" - }, - { - "name": "data[].employee_id", - "type": "number", - "required": true, - "description": "工号ID" - }, - { - "name": "data[].account_id", - "type": "number", - "required": true, - "description": "账号ID" - }, - { - "name": "data[].store_id", - "type": "number", - "required": true, - "description": "主体ID" - }, - { - "name": "data[].real_name", - "type": "string", - "required": true, - "description": "工号姓名" - }, - { - "name": "data[].status", - "type": "number", - "required": true, - "description": "工号状态:1=启用,0=停用" - }, - { - "name": "data[].username", - "type": "string", - "required": true, - "description": "账号用户名" - }, - { - "name": "data[].phone", - "type": "string", - "required": true, - "description": "账号手机号" - }, - { - "name": "data[].email", - "type": "string", - "required": true, - "description": "账号邮箱" - }, - { - "name": "data[].avatar_file_id", - "type": "number", - "required": false, - "description": "头像文件ID,为空表示未设置" - }, - { - "name": "data[].avatar_url", - "type": "string", - "required": true, - "description": "头像访问地址" - } - ], - "errors": [ - { - "code": "400", - "description": "当前登录态缺少主体上下文(store_id)" - }, - { - "code": "500", - "description": "查询失败" - } - ] - }, - { - "method": "setting.account.add", - "description": "新增工号,按手机号复用或创建账号后绑定到当前主体", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "phone", - "type": "string", - "required": true, - "source": "body", - "description": "手机号,作为账号复用/创建依据" - }, - { - "name": "real_name", - "type": "string", - "required": true, - "source": "body", - "description": "工号姓名,新增时禁止直接使用保留名称" - }, - { - "name": "username", - "type": "string", - "required": false, - "source": "body", - "description": "新账号用户名,不传时系统自动生成" - }, - { - "name": "password", - "type": "string", - "required": false, - "source": "body", - "description": "新账号密码,不传默认 111111" - }, - { - "name": "role_id", - "type": "number", - "required": false, - "source": "body", - "description": "工号角色,不传时继承当前操作人工号角色" - }, - { - "name": "email", - "type": "string", - "required": false, - "source": "body", - "description": "新账号邮箱,不传时按 username 自动生成" - } - ], - "response": [ - { - "name": "employee_id", - "type": "number", - "required": true, - "description": "新增或复用后的工号ID" - }, - { - "name": "account_id", - "type": "number", - "required": true, - "description": "绑定账号ID" - }, - { - "name": "role_id", - "type": "number", - "required": true, - "description": "绑定后的角色ID" - }, - { - "name": "is_new_account", - "type": "boolean", - "required": true, - "description": "是否为本次新建账号" - }, - { - "name": "phone", - "type": "string", - "required": true, - "description": "绑定账号手机号" - }, - { - "name": "username", - "type": "string", - "required": true, - "description": "绑定账号用户名" - } - ], - "errors": [ - { - "code": "400", - "description": "参数错误、手机号格式错误、或直接使用保留名称" - }, - { - "code": "409", - "description": "手机号对应账号已禁用、手机号已绑定当前主体工号、或用户名重复" - }, - { - "code": "500", - "description": "新增失败" - } - ] - }, - { - "method": "setting.account.delete", - "description": "删除工号绑定关系,仅停用工号,不删除账号", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "employee_id", - "type": "number", - "required": true, - "source": "body", - "description": "要删除的工号ID" - } - ], - "response": [ - { - "name": "employee_id", - "type": "number", - "required": true, - "description": "被停用的工号ID" - }, - { - "name": "account_id", - "type": "number", - "required": true, - "description": "关联账号ID" - }, - { - "name": "status", - "type": "string", - "required": true, - "description": "固定返回 deleted" - }, - { - "name": "already_deleted", - "type": "boolean", - "required": false, - "description": "可选,true 表示该工号原本已停用" - } - ], - "errors": [ - { - "code": "400", - "description": "参数错误或尝试删除当前登录工号" - }, - { - "code": "404", - "description": "工号不存在或无权限删除" - }, - { - "code": "500", - "description": "删除失败" - } - ] - }, - { - "method": "setting.account.update", - "description": "更新工号姓名和头像引用", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "employee_id", - "type": "number", - "required": true, - "source": "body", - "description": "要更新的工号ID" - }, - { - "name": "real_name", - "type": "string", - "required": false, - "source": "body", - "description": "更新后的工号姓名" - }, - { - "name": "file_id", - "type": "number", - "required": false, - "source": "body", - "description": "已有文件ID,作为头像引用" - } - ], - "response": [ - { - "name": "employee_id", - "type": "number", - "required": true, - "description": "更新后的工号ID" - }, - { - "name": "real_name", - "type": "string", - "required": true, - "description": "更新后的工号姓名" - }, - { - "name": "avatar_file_id", - "type": "number", - "required": false, - "description": "更新后的头像文件ID" - }, - { - "name": "avatar_url", - "type": "string", - "required": true, - "description": "更新后的头像地址" - } - ], - "errors": [ - { - "code": "400", - "description": "参数错误,未提供更新项" - }, - { - "code": "404", - "description": "工号或头像文件不存在" - }, - { - "code": "500", - "description": "更新失败" - } - ] - } - ] - }, - { - "groupName": "商品模块", - "module": "stock", - "list": [ - { - "method": "stock.warehouse.list", - "description": "仓库商品列表查询(支持 where 条件与分页)", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "pagination", - "type": "object", - "required": false, - "source": "body", - "description": "pagination 参数" - }, - { - "name": "where", - "type": "object", - "required": false, - "source": "body", - "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会在 main 中自动标准化;支持 quickWhere、barcode、prohibited_type 等商品筛选字段。示例:where.barcode={operator:like,value:69}; where.prohibited_type={operator:eq,value:liquid}。" - } - ], - "response": [], - "errors": [] - }, - { - "method": "stock.warehouse.getProhibitedType", - "description": "查询违禁品类型列表(系统预设+仓库自定义)", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "stock.warehouse.getInfo", - "description": "查询仓库商品详情", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "stock.warehouse.saveWarehouseStock", - "description": "更新仓库商品资料", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "stock.warehouse.createWarehouseStock", - "description": "新建仓库商品资料", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "stock.warehouse.getBarcodes", - "description": "查询商品条码列表", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "stock.warehouse.saveWarehouseStockBarcode", - "description": "保存商品条码信息", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "stock.warehouse.getStoreStocks", - "description": "查询仓库商品与货主关联列表", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "stock.warehouse.bindItem", - "description": "绑定货主商品关系", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "stock.warehouse.unbindItem", - "description": "解绑货主商品关系", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "stock.warehouse.checkItemCodeUnique", - "description": "校验商品编码在货主维度唯一性", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "item_code", - "type": "string", - "required": true, - "source": "body", - "description": "item_code 参数" - }, - { - "name": "store_id", - "type": "number", - "required": true, - "source": "body", - "description": "store_id 参数" - }, - { - "name": "id", - "type": "number", - "required": false, - "source": "body", - "description": "id 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "stock.warehouse.queryStockLogs", - "description": "查询库存操作日志", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "warehouseId", - "type": "string", - "required": false, - "source": "body", - "description": "warehouseId 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "stock.warehouse.handleBatchDelete", - "description": "批量删除仓库商品资料", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "stock.warehouse.deleteUnit", - "description": "删除库存单位", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "stock.warehouse.deleteProhibited", - "description": "删除违禁品类型", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "stock.warehouse.handleBatchChange", - "description": "批量修改仓库商品字段", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "stock.warehouse.getStockUnits", - "description": "查询可用库存单位(系统+仓库)", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "stock.warehouse.getUnitList", - "description": "查询当前仓库自定义单位列表", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "stock.warehouse.createProhibited", - "description": "新增违禁品类型", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "name", - "type": "string", - "required": true, - "source": "body", - "description": "name 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "stock.warehouse.createUnit", - "description": "新增库存单位", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "name", - "type": "string", - "required": true, - "source": "body", - "description": "name 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "stock.warehouse.search", - "description": "仓库商品关键字搜索", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - } - ] - }, - { - "groupName": "库存模块", - "module": "storage", - "list": [ - { - "method": "storage.receiving.getReceivingList", - "description": "storage.receiving.getReceivingList 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "pagination", - "type": "object", - "required": false, - "source": "body", - "description": "分页参数,支持 page/pageSize" - }, - { - "name": "where", - "type": "object", - "required": false, - "source": "body", - "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会在 main 中自动标准化;支持 quickWhere、status、store_id、日期区间等字段。示例:where.status={operator:eq,value:finished}; where.store_id={operator:eq,value:1001}; where.create_time_start={value:2026-03-01}。" - } - ], - "response": [ - { - "name": "list", - "type": "array", - "required": true, - "description": "收货单列表" - }, - { - "name": "pagination", - "type": "object", - "required": true, - "description": "分页信息(page、pageSize、total、totalPages、hasPrevious、hasNext)" - }, - { - "name": "summary", - "type": "object", - "required": true, - "description": "汇总信息(total_quantity、total_locked、total_available、total_items)" - } - ], - "errors": [ - { - "code": "500", - "description": "查询失败" - } - ] - }, - { - "method": "storage.receiving.getReceivingDetail", - "description": "storage.receiving.getReceivingDetail 接口", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "id", - "type": "number", - "required": true, - "source": "body", - "description": "收货单ID" - }, - { - "name": "pagination", - "type": "object", - "required": true, - "source": "body", - "description": "明细分页参数,支持 page/pageSize" - } - ], - "response": [ - { - "name": "receiving", - "type": "object", - "required": true, - "description": "收货单详情(含 details、images、pagination)" - } - ], - "errors": [ - { - "code": "0", - "description": "无记录或无权访问" - }, - { - "code": "500", - "description": "服务器错误" - } - ] - }, - { - "method": "storage.receiving.batchCancelReceiving", - "description": "storage.receiving.batchCancelReceiving 接口", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "ids", - "type": "array", - "required": true, - "source": "body", - "description": "待作废收货单ID数组" - } - ], - "response": [ - { - "name": "message", - "type": "string", - "required": true, - "description": "批量作废处理结果" - } - ], - "errors": [ - { - "code": "0", - "description": "部分单据不存在、无权访问或状态不允许作废" - }, - { - "code": "500", - "description": "服务器错误" - } - ] - }, - { - "method": "storage.receiving.create", - "description": "storage.receiving.create 接口", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "delivery_method", - "type": "string", - "required": true, - "source": "body", - "description": "到货方式:truck/express/air_freight/sea_freight/other" - }, - { - "name": "loading_method", - "type": "string", - "required": true, - "source": "body", - "description": "装卸方式:with_pallet/without_pallet" - }, - { - "name": "license_plate", - "type": "string", - "required": false, - "source": "body", - "description": "车牌号(delivery_method=truck 时建议传)" - }, - { - "name": "tracking_number", - "type": "string", - "required": false, - "source": "body", - "description": "物流单号(非 truck/other 场景建议传)" - }, - { - "name": "store_id", - "type": "number", - "required": false, - "source": "body", - "description": "货主ID" - }, - { - "name": "total_boxes", - "type": "number", - "required": false, - "source": "body", - "description": "总箱数" - }, - { - "name": "total_pallets", - "type": "number", - "required": false, - "source": "body", - "description": "总托盘数" - }, - { - "name": "remark", - "type": "string", - "required": false, - "source": "body", - "description": "备注" - } - ], - "response": [ - { - "name": "id", - "type": "number", - "required": true, - "description": "新建收货单ID" - }, - { - "name": "receiving_number", - "type": "string", - "required": true, - "description": "收货单号" - } - ], - "errors": [ - { - "code": "0", - "description": "创建失败(如字段枚举不合法、数据库约束异常)" - } - ] - }, - { - "method": "storage.receiving.addItem", - "description": "storage.receiving.addItem 接口", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "id", - "type": "number", - "required": false, - "source": "body", - "description": "id 参数" - }, - { - "name": "item", - "type": "object", - "required": false, - "source": "body", - "description": "item 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "storage.receiving.removeItem", - "description": "storage.receiving.removeItem 接口", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "id", - "type": "number", - "required": false, - "source": "body", - "description": "id 参数" - }, - { - "name": "item_id", - "type": "number", - "required": false, - "source": "body", - "description": "item_id 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "storage.receiving.saveReceiving", - "description": "storage.receiving.saveReceiving 接口", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "storage.receiving.get", - "description": "storage.receiving.get 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "storage.receiving.addDetail", - "description": "storage.receiving.addDetail 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "storage.receiving.deleteDetail", - "description": "storage.receiving.deleteDetail 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "storage.receiving.detailChange", - "description": "storage.receiving.detailChange 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "storage.receiving.cancel", - "description": "storage.receiving.cancel 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "storage.receiving.completeReceiving", - "description": "storage.receiving.completeReceiving 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "storage.entry.list", - "description": "入库单列表查询", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "pagination", - "type": "object", - "required": false, - "source": "body", - "description": "分页参数,支持 page/pageSize" - }, - { - "name": "where", - "type": "object", - "required": false, - "source": "body", - "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会在 main 中自动标准化;支持 quickWhere、order_status、store_id、order_type、日期区间等字段。示例:where.order_status={operator:eq,value:waiting}; where.order_type={operator:eq,value:purchase}; where.create_time_start={value:2026-03-01}。" - }, - { - "name": "sort", - "type": "object", - "required": false, - "source": "body", - "description": "排序参数,支持 sortField/sortOrder" - } - ], - "response": [ - { - "name": "list", - "type": "array", - "required": true, - "description": "入库单列表" - }, - { - "name": "pagination", - "type": "object", - "required": true, - "description": "分页信息(page、pageSize、total、totalPages、hasPrevious、hasNext)" - }, - { - "name": "summary", - "type": "object", - "required": true, - "description": "状态汇总(total、pending、creating、created、completed、cancelled)" - } - ], - "errors": [ - { - "code": "400", - "description": "筛选条件格式错误" - }, - { - "code": "500", - "description": "查询失败" - } - ] - }, - { - "method": "storage.entry.get", - "description": "查询入库单详情", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "id", - "type": "number", - "required": false, - "source": "body", - "description": "入库单ID,与 entry_order_code 二选一" - }, - { - "name": "entry_order_code", - "type": "string", - "required": false, - "source": "body", - "description": "入库单号,与 id 二选一" - } - ], - "response": [ - { - "name": "entryOrder", - "type": "object", - "required": true, - "description": "入库单详情(含 items 明细)" - } - ], - "errors": [ - { - "code": "400", - "description": "id 与 entry_order_code 均未传" - }, - { - "code": "0", - "description": "无记录或无权访问" - } - ] - }, - { - "method": "storage.entry.create", - "description": "创建入库单", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "order_type", - "type": "string", - "required": true, - "source": "body", - "description": "业务类型:SCRK/LYRK/CCRK/CGRK/DBRK/QTRK/B2BRK/XNRK" - }, - { - "name": "store_id", - "type": "number", - "required": false, - "source": "body", - "description": "货主ID,不传默认使用当前用户 store_id" - }, - { - "name": "entry_order_code", - "type": "string", - "required": false, - "source": "body", - "description": "入库单号,不传时系统自动生成" - }, - { - "name": "purchase_order_code", - "type": "string", - "required": false, - "source": "body", - "description": "采购单号" - }, - { - "name": "remark", - "type": "string", - "required": false, - "source": "body", - "description": "备注" - } - ], - "response": [ - { - "name": "id", - "type": "number", - "required": true, - "description": "新建入库单ID" - }, - { - "name": "entry_order_code", - "type": "string", - "required": true, - "description": "入库单号" - } - ], - "errors": [ - { - "code": "400", - "description": "参数缺失或业务类型不合法" - }, - { - "code": "409", - "description": "入库单号已存在" - } - ] - }, - { - "method": "storage.entry.addDetail", - "description": "新增入库明细", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "order_id", - "type": "number", - "required": true, - "source": "body", - "description": "入库单ID" - }, - { - "name": "count", - "type": "number", - "required": true, - "source": "body", - "description": "计划入库数量,必须大于0" - }, - { - "name": "item_code", - "type": "string", - "required": false, - "source": "body", - "description": "商品编码" - } - ], - "response": [ - { - "name": "id", - "type": "number", - "required": true, - "description": "新建明细ID" - }, - { - "name": "order_id", - "type": "number", - "required": true, - "description": "所属入库单ID" - } - ], - "errors": [ - { - "code": "400", - "description": "参数不合法或状态不允许新增明细" - }, - { - "code": "404", - "description": "入库单不存在或无权访问" - } - ] - }, - { - "method": "storage.entry.deleteDetail", - "description": "删除入库明细", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "id", - "type": "number", - "required": true, - "source": "body", - "description": "明细ID" - } - ], - "response": [ - { - "name": "id", - "type": "number", - "required": true, - "description": "删除成功的明细ID" - } - ], - "errors": [ - { - "code": "400", - "description": "参数不合法或明细已有收货数量" - }, - { - "code": "404", - "description": "明细或入库单不存在" - } - ] - }, - { - "method": "storage.entry.detailChange", - "description": "修改入库明细", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "id", - "type": "number", - "required": true, - "source": "body", - "description": "明细ID" - }, - { - "name": "count", - "type": "number", - "required": false, - "source": "body", - "description": "计划入库数量,必须大于0且不能小于已收货数量" - } - ], - "response": [ - { - "name": "id", - "type": "number", - "required": true, - "description": "修改成功的明细ID" - } - ], - "errors": [ - { - "code": "400", - "description": "参数不合法或没有可更新字段" - }, - { - "code": "404", - "description": "明细或入库单不存在" - } - ] - }, - { - "method": "storage.entry.cancel", - "description": "作废入库单", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "id", - "type": "number", - "required": true, - "source": "body", - "description": "入库单ID" - } - ], - "response": [ - { - "name": "id", - "type": "number", - "required": true, - "description": "作废成功的入库单ID" - } - ], - "errors": [ - { - "code": "400", - "description": "参数不合法或已完成单据不允许作废" - }, - { - "code": "404", - "description": "入库单不存在或无权访问" - } - ] - }, - { - "method": "storage.entry.completeEntry", - "description": "完成入库单", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "id", - "type": "number", - "required": true, - "source": "body", - "description": "入库单ID" - } - ], - "response": [ - { - "name": "id", - "type": "number", - "required": true, - "description": "完成成功的入库单ID" - } - ], - "errors": [ - { - "code": "400", - "description": "参数不合法、已作废或缺少明细" - }, - { - "code": "404", - "description": "入库单不存在或无权访问" - } - ] - } - ] - }, - { - "groupName": "主体模块", - "module": "store", - "list": [ - { - "method": "store.createStore", - "description": "store.createStore 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "store.createWarehouse", - "description": "store.createWarehouse 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "store.joinStore", - "description": "store.joinStore 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "store.joinWarehouse", - "description": "store.joinWarehouse 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "store.getStoreRoles", - "description": "store.getStoreRoles 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "code", - "type": "string", - "required": true, - "source": "body", - "description": "申请码(join_token)" - } - ], - "response": [], - "errors": [] - }, - { - "method": "store.auditApply", - "description": "store.auditApply 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "audit_status", - "type": "string", - "required": true, - "source": "body", - "description": "审核状态(approved/rejected)" - }, - { - "name": "code", - "type": "string", - "required": true, - "source": "body", - "description": "申请码(join_token)" - }, - { - "name": "store_id", - "type": "number", - "required": true, - "source": "body", - "description": "当前审批门店ID" - }, - { - "name": "role_ids", - "type": "array", - "required": true, - "source": "body", - "description": "分配角色ID数组" - }, - { - "name": "reject_reason", - "type": "string", - "required": false, - "source": "body", - "description": "拒绝原因(audit_status=rejected 时可传)" - } - ], - "response": [], - "errors": [] - } - ] - }, - { - "groupName": "用户模块", - "module": "user", - "list": [ - { - "method": "user.login", - "description": "用户登录(仅返回 token)", - "isNeedAuth": false, - "isNeedLogin": false, - "headers": [], - "params": [ - { - "name": "password", - "type": "string", - "required": false, - "source": "body", - "description": "password 参数" - }, - { - "name": "username", - "type": "string", - "required": false, - "source": "body", - "description": "username 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "user.loginByCode", - "description": "登录码登录(使用 ye4s_user.tmp_code)", - "isNeedAuth": false, - "isNeedLogin": false, - "headers": [], - "params": [ - { - "name": "code", - "type": "string", - "required": true, - "source": "body", - "description": "登录码,对应 ye4s_user.tmp_code" - } - ], - "response": [], - "errors": [] - }, - { - "method": "user.getBindWechatCode", - "description": "获取微信绑定码(默认立即返回;显式开启长轮询后,最长等待60秒,状态变化立即返回)", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "forceRefresh", - "type": "boolean", - "required": false, - "source": "body", - "description": "是否强制刷新状态,true 时跳过缓存等待窗口" - }, - { - "name": "waitForChange", - "type": "boolean", - "required": false, - "source": "body", - "description": "是否显式开启长轮询等待(推荐字段);true 时进入最长60秒等待" - }, - { - "name": "longPoll", - "type": "boolean", - "required": false, - "source": "body", - "description": "长轮询开关(兼容字段);true 时进入最长60秒等待" - }, - { - "name": "waitTimeoutMs", - "type": "number", - "required": false, - "source": "body", - "description": "等待超时毫秒数;后端自动封顶60000" - }, - { - "name": "init", - "type": "boolean", - "required": false, - "source": "body", - "description": "初始化请求标记;true 时强制立即返回,不进入长等待" - } - ], - "response": [], - "errors": [] - }, - { - "method": "user.unbindWechat", - "description": "解绑微信账号(清理 ye4s 关联账号数据)", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "user.logout", - "description": "用户登出", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "user.info", - "description": "获取当前用户信息", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "user.changeRole", - "description": "user.changeRole 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "user.register", - "description": "user.register 接口", - "isNeedAuth": false, - "isNeedLogin": false, - "headers": [], - "params": [], - "response": [], - "errors": [] - } - ] - }, - { - "groupName": "仓库模块", - "module": "warehouse", - "list": [ - { - "method": "warehouse.getWarehouseZones", - "description": "warehouse.getWarehouseZones 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "warehouse.getWarehouseTree", - "description": "warehouse.getWarehouseTree 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "warehouseId", - "type": "number", - "required": true, - "source": "body", - "description": "warehouseId 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "warehouse.getChildren", - "description": "warehouse.getChildren 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "zoneId", - "type": "number", - "required": true, - "source": "body", - "description": "zoneId 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "warehouse.create", - "description": "warehouse.create 接口", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "warehouse.update", - "description": "warehouse.update 接口", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "id", - "type": "number", - "required": true, - "source": "body", - "description": "id 参数" - }, - { - "name": "aisles", - "type": "string", - "required": false, - "source": "body", - "description": "aisles 参数" - }, - { - "name": "cell_height", - "type": "string", - "required": false, - "source": "body", - "description": "cell_height 参数" - }, - { - "name": "cell_length", - "type": "string", - "required": false, - "source": "body", - "description": "cell_length 参数" - }, - { - "name": "cell_width", - "type": "string", - "required": false, - "source": "body", - "description": "cell_width 参数" - }, - { - "name": "direction", - "type": "string", - "required": false, - "source": "body", - "description": "direction 参数" - }, - { - "name": "height", - "type": "number", - "required": false, - "source": "body", - "description": "height 参数" - }, - { - "name": "length", - "type": "number", - "required": false, - "source": "body", - "description": "length 参数" - }, - { - "name": "rack_columns", - "type": "string", - "required": false, - "source": "body", - "description": "rack_columns 参数" - }, - { - "name": "rack_levels", - "type": "string", - "required": false, - "source": "body", - "description": "rack_levels 参数" - }, - { - "name": "rack_rows", - "type": "string", - "required": false, - "source": "body", - "description": "rack_rows 参数" - }, - { - "name": "width", - "type": "number", - "required": false, - "source": "body", - "description": "width 参数" - }, - { - "name": "x", - "type": "number", - "required": false, - "source": "body", - "description": "x 参数" - }, - { - "name": "y", - "type": "number", - "required": false, - "source": "body", - "description": "y 参数" - }, - { - "name": "z", - "type": "number", - "required": false, - "source": "body", - "description": "z 参数" - }, - { - "name": "zone_code", - "type": "string", - "required": false, - "source": "body", - "description": "zone_code 参数" - }, - { - "name": "zone_name", - "type": "string", - "required": false, - "source": "body", - "description": "zone_name 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "warehouse.delete", - "description": "warehouse.delete 接口", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "id", - "type": "number", - "required": true, - "source": "body", - "description": "id 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "warehouse.detail", - "description": "warehouse.detail 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "id", - "type": "number", - "required": true, - "source": "body", - "description": "id 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "warehouse.checkBarcodeUnique", - "description": "warehouse.checkBarcodeUnique 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "barcode", - "type": "string", - "required": true, - "source": "body", - "description": "barcode 参数" - }, - { - "name": "id", - "type": "number", - "required": true, - "source": "body", - "description": "id 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "warehouse.toggleActive", - "description": "warehouse.toggleActive 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "id", - "type": "number", - "required": true, - "source": "body", - "description": "id 参数" - }, - { - "name": "isActive", - "type": "string", - "required": false, - "source": "body", - "description": "isActive 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "warehouse.getPath", - "description": "warehouse.getPath 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "id", - "type": "number", - "required": true, - "source": "body", - "description": "id 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "warehouse.createRack", - "description": "warehouse.createRack 接口", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "height", - "type": "number", - "required": true, - "source": "body", - "description": "height 参数" - }, - { - "name": "length", - "type": "number", - "required": true, - "source": "body", - "description": "length 参数" - }, - { - "name": "rack_columns", - "type": "number", - "required": true, - "source": "body", - "description": "rack_columns 参数" - }, - { - "name": "rack_levels", - "type": "number", - "required": true, - "source": "body", - "description": "rack_levels 参数" - }, - { - "name": "rack_rows", - "type": "number", - "required": true, - "source": "body", - "description": "rack_rows 参数" - }, - { - "name": "warehouse_id", - "type": "number", - "required": true, - "source": "body", - "description": "warehouse_id 参数" - }, - { - "name": "width", - "type": "number", - "required": true, - "source": "body", - "description": "width 参数" - }, - { - "name": "x", - "type": "number", - "required": true, - "source": "body", - "description": "x 参数" - }, - { - "name": "y", - "type": "number", - "required": true, - "source": "body", - "description": "y 参数" - }, - { - "name": "zone_code", - "type": "string", - "required": true, - "source": "body", - "description": "zone_code 参数" - }, - { - "name": "zone_name", - "type": "string", - "required": true, - "source": "body", - "description": "zone_name 参数" - }, - { - "name": "color", - "type": "string", - "required": false, - "source": "body", - "description": "color 参数" - }, - { - "name": "direction", - "type": "string", - "required": false, - "source": "body", - "description": "direction 参数" - }, - { - "name": "parent_id", - "type": "number", - "required": false, - "source": "body", - "description": "parent_id 参数" - }, - { - "name": "z", - "type": "number", - "required": false, - "source": "body", - "description": "z 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "warehouse.getPickPath", - "description": "warehouse.getPickPath 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "warehouse_id", - "type": "number", - "required": true, - "source": "query", - "description": "warehouse_id 参数" - }, - { - "name": "include_spaces", - "type": "string", - "required": false, - "source": "query", - "description": "include_spaces 参数" - }, - { - "name": "limit", - "type": "number", - "required": false, - "source": "query", - "description": "limit 参数" - }, - { - "name": "sort_by", - "type": "string", - "required": false, - "source": "query", - "description": "sort_by 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "warehouse.updateRackPosition", - "description": "warehouse.updateRackPosition 接口", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "x", - "type": "number", - "required": true, - "source": "body", - "description": "x 参数" - }, - { - "name": "y", - "type": "number", - "required": true, - "source": "body", - "description": "y 参数" - }, - { - "name": "rack_id", - "type": "number", - "required": false, - "source": "path", - "description": "rack_id 参数" - }, - { - "name": "z", - "type": "number", - "required": false, - "source": "body", - "description": "z 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "warehouse.recalculatePickPath", - "description": "warehouse.recalculatePickPath 接口", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "warehouse_id", - "type": "number", - "required": true, - "source": "body", - "description": "warehouse_id 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "warehouse.updateNeighbors", - "description": "warehouse.updateNeighbors 接口", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "warehouse_id", - "type": "number", - "required": true, - "source": "body", - "description": "warehouse_id 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "warehouse.getAreaRacks", - "description": "warehouse.getAreaRacks 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "area_id", - "type": "number", - "required": true, - "source": "query", - "description": "area_id 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "warehouse.getSpacesByRack", - "description": "warehouse.getSpacesByRack 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "id", - "type": "number", - "required": true, - "source": "body", - "description": "id 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "warehouse.createRackWithSpaces", - "description": "warehouse.createRackWithSpaces 接口", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "id", - "type": "number", - "required": true, - "source": "body", - "description": "id 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "warehouse.getSpaceInfo", - "description": "warehouse.getSpaceInfo 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "id", - "type": "number", - "required": false, - "source": "body", - "description": "id 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "warehouse.updateSpaceInfo", - "description": "warehouse.updateSpaceInfo 接口", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "id", - "type": "number", - "required": true, - "source": "body", - "description": "id 参数" - }, - { - "name": "custom_barcode", - "type": "string", - "required": false, - "source": "body", - "description": "custom_barcode 参数" - }, - { - "name": "custom_name", - "type": "string", - "required": false, - "source": "body", - "description": "custom_name 参数" - }, - { - "name": "location_type_id", - "type": "number", - "required": false, - "source": "body", - "description": "location_type_id 参数" - }, - { - "name": "pick_sequence", - "type": "string", - "required": false, - "source": "body", - "description": "pick_sequence 参数" - }, - { - "name": "space_status", - "type": "string", - "required": false, - "source": "body", - "description": "space_status 参数" - } - ], - "response": [], - "errors": [] - } - ] - } - ] + ] + }, + { + "type": "string", + "required": true, + "name": "project", + "description": "项目标识,如 all/warehouse/store/tms", + "list": [ + { + "value": "all", + "name": "全部" + }, + { + "value": "warehouse", + "name": "仓库" + }, + { + "value": "store", + "name": "货主" + }, + { + "value": "tms", + "name": "物流" + } + ] } + ], + "methods": { + "groups": [ + { + "groupName": "配置模块", + "module": "config", + "list": [ + { + "method": "config.list", + "description": "config.list 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "看板模块", + "module": "dashboard", + "list": [ + { + "method": "dashboard.storeStats", + "description": "dashboard.storeStats 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "dashboard.warehouseStats", + "description": "dashboard.warehouseStats 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "dashboard.hot_order_rank", + "description": "dashboard.hot_order_rank 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "dashboard.express_ratio", + "description": "dashboard.express_ratio 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "dashboard.platform_distribution", + "description": "dashboard.platform_distribution 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "dashboard.order_trend", + "description": "dashboard.order_trend 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "基础模块", + "module": "index", + "list": [ + { + "method": "index.fastWhereTree", + "description": "index.fastWhereTree 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "type", + "type": "string", + "required": false, + "source": "body", + "description": "type 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "index.loadStores", + "description": "index.loadStores 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "index.getCOSUploadConfig", + "description": "index.getCOSUploadConfig 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "data", + "type": "object", + "required": false, + "source": "body", + "description": "data 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "index.getImages", + "description": "index.getImages 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "index.uploadSuccessNotify", + "description": "index.uploadSuccessNotify 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "index.ReferenceFile", + "description": "index.ReferenceFile 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "index.getMessageDetail", + "description": "index.getMessageDetail 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "index.getI18nMessage", + "description": "index.getI18nMessage 接口", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "language", + "type": "string", + "required": false, + "source": "body|query", + "description": "language 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "index.putI18nCollect", + "description": "index.putI18nCollect 接口", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "keys", + "type": "array", + "required": false, + "source": "body", + "description": "keys 参数" + }, + { + "name": "locale", + "type": "string", + "required": false, + "source": "body", + "description": "locale 参数" + }, + { + "name": "project", + "type": "string", + "required": false, + "source": "body", + "description": "project 参数" + }, + { + "name": "source", + "type": "string", + "required": false, + "source": "body", + "description": "source 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "index.tryAutoTranslateNewKeys", + "description": "index.tryAutoTranslateNewKeys 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "index.searchSpace", + "description": "index.searchSpace 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "index.getExpressList", + "description": "index.getExpressList 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "订单模块", + "module": "order", + "list": [ + { + "method": "order.getOrderModels", + "description": "order.getOrderModels 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "order.list", + "description": "分页查询订单列表", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "order.detail", + "description": "查询订单详情", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "order.listItems", + "description": "查询订单商品明细", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "order.stats", + "description": "订单统计", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "order.getreviewOrderlist", + "description": "分页查询订单审核列表", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "order.updateStatus", + "description": "更新订单状态", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "order.updateDeliveryTime", + "description": "更新发货时间", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "order.reviewOrder", + "description": "订单审核", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "order.reviewOrder.getreviewOrderlist", + "description": "分页查询订单审核列表(目录化路由)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "pagination 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "order.reviewOrder.reviewOrder", + "description": "订单审核(目录化路由)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "inspection_status", + "type": "string", + "required": false, + "source": "body", + "description": "inspection_status 参数" + }, + { + "name": "operate_time", + "type": "string", + "required": false, + "source": "body", + "description": "operate_time 参数" + }, + { + "name": "operator_name", + "type": "string", + "required": false, + "source": "body", + "description": "operator_name 参数" + }, + { + "name": "review_status", + "type": "string", + "required": false, + "source": "body", + "description": "review_status 参数" + }, + { + "name": "reviewStatus", + "type": "string", + "required": false, + "source": "body", + "description": "reviewStatus 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "order.deliveryOrder.getdeliveryOrderlist", + "description": "分页查询已进入出库流程的订单列表", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "pagination 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "order.pendingOrder.getpendingOrderlist", + "description": "分页查询待处理订单列表", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "pagination 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "order.expectionOrder.getexpectionOrderlist", + "description": "分页查询异常订单列表", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "pagination 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "order.archiveOrder.getarchiveOrderlist", + "description": "分页查询归档订单列表(暂使用当前订单表完成态数据)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "pagination 参数" + } + ], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "打印模块", + "module": "print", + "list": [ + { + "method": "print.send", + "description": "print.send 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "computerId", + "type": "string", + "required": false, + "source": "body", + "description": "computerId 参数" + }, + { + "name": "count", + "type": "number", + "required": false, + "source": "body", + "description": "count 参数" + }, + { + "name": "data", + "type": "object", + "required": false, + "source": "body", + "description": "data 参数" + }, + { + "name": "printer", + "type": "string", + "required": false, + "source": "body", + "description": "printer 参数" + }, + { + "name": "template", + "type": "object", + "required": false, + "source": "body", + "description": "template 参数" + }, + { + "name": "timestamp", + "type": "string", + "required": false, + "source": "body", + "description": "timestamp 参数" + }, + { + "name": "type", + "type": "string", + "required": false, + "source": "body", + "description": "type 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "print.getPrintResult", + "description": "print.getPrintResult 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "printId", + "type": "string", + "required": true, + "source": "body", + "description": "printId 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "print.getPrintRecordItem", + "description": "print.getPrintRecordItem 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "print.getList", + "description": "print.getList 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "print.getItem", + "description": "print.getItem 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "print.add", + "description": "print.add 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "computer_id", + "type": "number", + "required": true, + "source": "body", + "description": "computer_id 参数" + }, + { + "name": "name", + "type": "string", + "required": true, + "source": "body", + "description": "name 参数" + }, + { + "name": "custom_barcode", + "type": "string", + "required": false, + "source": "body", + "description": "custom_barcode 参数" + }, + { + "name": "default_printer_name", + "type": "string", + "required": false, + "source": "body", + "description": "default_printer_name 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "print.hasName", + "description": "print.hasName 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "name", + "type": "string", + "required": true, + "source": "body", + "description": "name 参数" + }, + { + "name": "id", + "type": "number", + "required": false, + "source": "body", + "description": "id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "print.updateItem", + "description": "print.updateItem 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "id 参数" + }, + { + "name": "computer_id", + "type": "number", + "required": false, + "source": "body", + "description": "computer_id 参数" + }, + { + "name": "custom_barcode", + "type": "string", + "required": false, + "source": "body", + "description": "custom_barcode 参数" + }, + { + "name": "name", + "type": "string", + "required": false, + "source": "body", + "description": "name 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "print.del", + "description": "print.del 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids", + "type": "array", + "required": false, + "source": "body", + "description": "ids 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "print.getComputer", + "description": "print.getComputer 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "print.getComputerPrinter", + "description": "print.getComputerPrinter 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "print.savePrinters", + "description": "print.savePrinters 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "defaultPrinter", + "type": "string", + "required": true, + "source": "body", + "description": "defaultPrinter 参数" + }, + { + "name": "express", + "type": "array", + "required": false, + "source": "body", + "description": "express 参数" + }, + { + "name": "print_station_id", + "type": "number", + "required": false, + "source": "body", + "description": "print_station_id 参数" + } + ], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "打印机站点模块", + "module": "printer.station", + "list": [ + { + "method": "printer.station.list", + "description": "获取打印站点列表", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "打印模板模块", + "module": "setting.printTemplate", + "list": [ + { + "method": "setting.printTemplate.list", + "description": "获取打印模板树", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "setting.printTemplate.save", + "description": "保存打印模板", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "setting.printTemplate.create", + "description": "创建打印模板(platform 固定为 default,template_type 固定为 CUSTOM,template_url 固定为空字符串)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "business_type", + "type": "string", + "required": true, + "source": "body", + "description": "business_type 参数" + }, + { + "name": "template_name", + "type": "string", + "required": true, + "source": "body", + "description": "template_name 参数" + }, + { + "name": "page_height", + "type": "string", + "required": false, + "source": "body", + "description": "page_height 参数" + }, + { + "name": "page_width", + "type": "string", + "required": false, + "source": "body", + "description": "page_width 参数" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "新建模板ID" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误(缺少 template_name、business_type、page_width 或 page_height)" + }, + { + "code": "409", + "description": "同一业务类型和平台下已存在自定义模板" + } + ] + }, + { + "method": "setting.printTemplate.delete", + "description": "删除打印模板(软删除)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": false, + "source": "body", + "description": "id 参数" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "删除的模板ID" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误(缺少 id)" + }, + { + "code": "404", + "description": "模板不存在或无权限" + } + ] + }, + { + "method": "setting.printTemplate.listTemplatesByType", + "description": "按业务类型查询模板", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "businessType", + "type": "string", + "required": true, + "source": "body", + "description": "businessType 参数" + } + ], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "账号管理模块", + "module": "setting.account", + "list": [ + { + "method": "setting.account.list", + "description": "查询当前主体下且在当前账号角色组可操作范围内的工号列表", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "data[]", + "type": "object", + "required": true, + "description": "工号列表项" + }, + { + "name": "data[].employee_id", + "type": "number", + "required": true, + "description": "工号ID" + }, + { + "name": "data[].account_id", + "type": "number", + "required": true, + "description": "账号ID" + }, + { + "name": "data[].store_id", + "type": "number", + "required": true, + "description": "主体ID" + }, + { + "name": "data[].real_name", + "type": "string", + "required": true, + "description": "工号姓名" + }, + { + "name": "data[].status", + "type": "number", + "required": true, + "description": "工号状态:1=启用,0=停用" + }, + { + "name": "data[].username", + "type": "string", + "required": true, + "description": "账号用户名" + }, + { + "name": "data[].phone", + "type": "string", + "required": true, + "description": "账号手机号" + }, + { + "name": "data[].email", + "type": "string", + "required": true, + "description": "账号邮箱" + }, + { + "name": "data[].avatar_file_id", + "type": "number", + "required": false, + "description": "头像文件ID,为空表示未设置" + }, + { + "name": "data[].avatar_url", + "type": "string", + "required": true, + "description": "头像访问地址" + }, + { + "name": "data[].is_wechat_bound", + "type": "boolean", + "required": true, + "description": "账号是否已绑定微信" + }, + { + "name": "data[].ye4s_user_id", + "type": "number", + "required": false, + "description": "已绑定时对应的 ye4s 用户ID,未绑定为空" + }, + { + "name": "data[].role_ids", + "type": "number[]", + "required": true, + "description": "工号绑定的角色ID数组" + }, + { + "name": "data[].roles[]", + "type": "object", + "required": true, + "description": "工号绑定的角色组详情" + }, + { + "name": "data[].roles[].role_id", + "type": "number", + "required": true, + "description": "角色ID" + }, + { + "name": "data[].roles[].role_code", + "type": "string", + "required": true, + "description": "角色编码" + }, + { + "name": "data[].roles[].role_name", + "type": "string", + "required": true, + "description": "角色名称" + }, + { + "name": "data[].roles[].pid", + "type": "number", + "required": true, + "description": "父级角色ID" + }, + { + "name": "data[].roles[].status", + "type": "number", + "required": true, + "description": "角色状态:1=启用,0=停用" + } + ], + "errors": [ + { + "code": "400", + "description": "当前登录态缺少主体上下文(store_id)或 where 参数解析失败" + }, + { + "code": "500", + "description": "查询失败" + } + ] + }, + { + "method": "setting.account.add", + "description": "新增工号,按手机号复用或创建账号后绑定到当前主体,并校验角色组 ids 不超出当前角色范围", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "employee_id", + "type": "number", + "required": true, + "description": "新增或复用后的工号ID" + }, + { + "name": "account_id", + "type": "number", + "required": true, + "description": "绑定账号ID" + }, + { + "name": "role_id", + "type": "number", + "required": true, + "description": "绑定后的角色ID" + }, + { + "name": "role_ids", + "type": "number[]", + "required": true, + "description": "绑定后的角色组ID数组" + }, + { + "name": "is_new_account", + "type": "boolean", + "required": true, + "description": "是否为本次新建账号" + }, + { + "name": "phone", + "type": "string", + "required": true, + "description": "绑定账号手机号" + }, + { + "name": "username", + "type": "string", + "required": true, + "description": "绑定账号用户名" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误、手机号格式错误、直接使用保留名称、或 ids 超出当前角色范围" + }, + { + "code": "409", + "description": "手机号对应账号已禁用、手机号已绑定当前主体工号、或用户名重复" + }, + { + "code": "500", + "description": "新增失败" + } + ] + }, + { + "method": "setting.account.delete", + "description": "删除工号绑定关系,仅停用工号,不删除账号", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "employee_id", + "type": "number", + "required": true, + "description": "被停用的工号ID" + }, + { + "name": "account_id", + "type": "number", + "required": true, + "description": "关联账号ID" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "固定返回 deleted" + }, + { + "name": "already_deleted", + "type": "boolean", + "required": false, + "description": "可选,true 表示该工号原本已停用" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误或尝试删除当前登录工号" + }, + { + "code": "404", + "description": "工号不存在或无权限删除" + }, + { + "code": "500", + "description": "删除失败" + } + ] + }, + { + "method": "setting.account.update", + "description": "更新工号姓名、头像引用和角色组 ids(含当前角色范围校验)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "employee_id", + "type": "number", + "required": true, + "description": "更新后的工号ID" + }, + { + "name": "real_name", + "type": "string", + "required": true, + "description": "更新后的工号姓名" + }, + { + "name": "avatar_file_id", + "type": "number", + "required": false, + "description": "更新后的头像文件ID" + }, + { + "name": "avatar_url", + "type": "string", + "required": true, + "description": "更新后的头像地址" + }, + { + "name": "role_ids", + "type": "number[]", + "required": true, + "description": "更新后的角色组ID数组" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误、未传 ids、或 ids 超出当前角色范围" + }, + { + "code": "404", + "description": "工号或头像文件不存在" + }, + { + "code": "500", + "description": "更新失败" + } + ] + }, + { + "method": "setting.account.getBindWechatCode", + "description": "为当前账号可操作范围内的其他账号获取微信绑定状态与绑定码,复用个人绑定微信逻辑", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "account_id", + "type": "number", + "required": true, + "description": "目标账号ID" + }, + { + "name": "code", + "type": "string", + "required": true, + "description": "绑定码(已绑定时为空字符串)" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "绑定状态:pending/scanned/bound" + }, + { + "name": "is_bound", + "type": "boolean", + "required": true, + "description": "是否已绑定微信" + }, + { + "name": "updated_at", + "type": "string", + "required": true, + "description": "状态更新时间(ISO 时间)" + }, + { + "name": "expires_at", + "type": "number", + "required": false, + "description": "过期时间戳(毫秒),bound 状态可为空" + }, + { + "name": "expire_after_ms", + "type": "number", + "required": true, + "description": "距离过期剩余毫秒数" + }, + { + "name": "scanned_at", + "type": "string", + "required": false, + "description": "扫码时间(未扫码可为空)" + }, + { + "name": "source", + "type": "string", + "required": true, + "description": "数据来源,如 cache/generated/refreshed/db" + }, + { + "name": "ye4s_user_id", + "type": "number", + "required": false, + "description": "已绑定的 ye4s 用户ID(未绑定可为空)" + } + ], + "errors": [ + { + "code": "400", + "description": "缺少 user_id 或当前账号角色范围为空" + }, + { + "code": "403", + "description": "目标账号超出当前操作范围" + }, + { + "code": "404", + "description": "目标账号不存在或不在当前主体下" + }, + { + "code": "500", + "description": "获取绑定码失败" + } + ] + }, + { + "method": "setting.account.unbindWechat", + "description": "为当前账号可操作范围内的其他账号解除微信绑定,复用个人解绑微信逻辑", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "account_id", + "type": "number", + "required": true, + "description": "目标账号ID" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "固定返回 unbound" + }, + { + "name": "matched_rows", + "type": "number", + "required": true, + "description": "匹配到的 ye4s 绑定记录数" + }, + { + "name": "affected_rows", + "type": "number", + "required": true, + "description": "实际更新的 ye4s 记录数" + }, + { + "name": "updated_at", + "type": "string", + "required": true, + "description": "解绑时间(ISO 时间)" + } + ], + "errors": [ + { + "code": "400", + "description": "缺少 user_id 或当前账号角色范围为空" + }, + { + "code": "403", + "description": "目标账号超出当前操作范围" + }, + { + "code": "404", + "description": "目标账号不存在或不在当前主体下" + }, + { + "code": "500", + "description": "解绑失败" + } + ] + } + ] + }, + { + "groupName": "角色管理模块", + "module": "setting.role", + "list": [ + { + "method": "setting.role.list", + "description": "查询当前登录工号的下级角色列表,不返回自己及同级角色,并携带各角色的 permission_ids 权限集;返回 [\"*\"] 表示拥有全部权限", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "employee_id", + "type": "number", + "required": false, + "description": "当前登录工号ID,未识别到登录工号时为 null" + }, + { + "name": "roles[]", + "type": "object", + "required": true, + "description": "下级角色树列表(第一层为当前登录工号角色的直接下级)" + }, + { + "name": "roles[].role_id", + "type": "number", + "required": true, + "description": "角色ID" + }, + { + "name": "roles[].role_name", + "type": "string", + "required": true, + "description": "角色名称" + }, + { + "name": "roles[].selected", + "type": "boolean", + "required": true, + "description": "表示当前登录工号是否已绑定该角色" + }, + { + "name": "roles[].permission_ids", + "type": "number[]|string[]", + "required": true, + "description": "该角色已绑定的权限ID集合;返回 [\"*\"] 表示拥有全部权限,嵌套 children 节点结构相同" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误" + }, + { + "code": "404", + "description": "工号不存在或无权限" + }, + { + "code": "500", + "description": "查询失败" + } + ] + }, + { + "method": "setting.role.permission", + "description": "查询全量角色权限列表(不按当前登录工号权限集筛选),兼容旧入口,用于总管理员管理权限", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "role_id", + "type": "number", + "required": false, + "description": "查询目标角色ID,未传 role_id 时返回当前登录工号的当前角色ID" + }, + { + "name": "permissions[]", + "type": "object[]", + "required": true, + "description": "全量权限列表(不按当前登录工号权限集裁剪)" + }, + { + "name": "permissions[].permission_id", + "type": "number", + "required": true, + "description": "权限ID" + }, + { + "name": "permissions[].selected", + "type": "boolean", + "required": true, + "description": "当传入或解析出 role_id 时,表示该角色是否已绑定该权限" + } + ], + "errors": [ + { + "code": "400", + "description": "role_id/type 参数错误或当前主体无可用权限" + }, + { + "code": "404", + "description": "角色不存在或无权限操作" + }, + { + "code": "500", + "description": "查询失败" + } + ] + }, + { + "method": "setting.role.add", + "description": "新增角色并一次性提交权限集(permission_ids);传 [\"*\"] 表示所有权限", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "role_id", + "type": "number", + "required": true, + "description": "新建角色ID" + }, + { + "name": "role_code", + "type": "string", + "required": true, + "description": "角色编码" + }, + { + "name": "role_name", + "type": "string", + "required": true, + "description": "角色名称" + }, + { + "name": "permission_ids", + "type": "number[]|string[]", + "required": true, + "description": "提交后的权限ID集合;返回 [\"*\"] 表示所有权限" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误、permission_ids 非法,或目标权限不存在/已禁用" + }, + { + "code": "409", + "description": "role_code 冲突" + }, + { + "code": "500", + "description": "新增失败" + } + ] + }, + { + "method": "setting.role.delete", + "description": "批量删除角色(软删除)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "ids", + "type": "number[]", + "required": true, + "description": "请求的角色ID数组" + }, + { + "name": "deleted_ids", + "type": "number[]", + "required": true, + "description": "本次实际删除(由启用变为停用)的角色ID数组" + }, + { + "name": "already_deleted_ids", + "type": "number[]", + "required": true, + "description": "本就处于删除状态的角色ID数组" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "固定返回 deleted" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误,ids 必须为正整数数组" + }, + { + "code": "404", + "description": "角色不存在、无权限操作或为系统预设角色(任一ID不满足即失败)" + }, + { + "code": "500", + "description": "删除失败" + } + ] + }, + { + "method": "setting.role.update", + "description": "更新角色信息并一次性重置角色权限(permission_ids);传 [\"*\"] 表示所有权限", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "role_id", + "type": "number", + "required": true, + "description": "角色ID" + }, + { + "name": "permission_ids", + "type": "number[]|string[]", + "required": true, + "description": "更新后的权限ID集合;返回 [\"*\"] 表示所有权限" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误、permission_ids 非法,或目标权限不存在/已禁用" + }, + { + "code": "404", + "description": "角色不存在、无权限操作或为系统预设角色" + }, + { + "code": "409", + "description": "角色信息冲突" + }, + { + "code": "500", + "description": "更新失败" + } + ] + } + ] + }, + { + "groupName": "权限管理模块", + "module": "setting.permission", + "list": [ + { + "method": "setting.permission.list", + "description": "查询全量权限集合(不按当前登录工号权限集筛选),可选按角色返回已绑定权限选中状态,用于总管理员管理权限", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "role_id", + "type": "number", + "required": false, + "description": "查询目标角色ID,未传 role_id 时返回当前登录工号的当前角色ID" + }, + { + "name": "permissions[]", + "type": "object", + "required": true, + "description": "全量权限列表(不按当前登录工号权限集裁剪)" + }, + { + "name": "permissions[].permission_id", + "type": "number", + "required": true, + "description": "权限ID" + }, + { + "name": "permissions[].path", + "type": "string", + "required": true, + "description": "权限路径" + }, + { + "name": "permissions[].name", + "type": "string", + "required": true, + "description": "权限名称" + }, + { + "name": "permissions[].type", + "type": "string", + "required": true, + "description": "权限类型" + }, + { + "name": "permissions[].component", + "type": "string", + "required": false, + "description": "前端路由组件路径" + }, + { + "name": "permissions[].redirect", + "type": "string", + "required": false, + "description": "前端路由重定向路径" + }, + { + "name": "permissions[].meta_title", + "type": "string", + "required": false, + "description": "菜单/页面标题" + }, + { + "name": "permissions[].meta_icon", + "type": "string", + "required": false, + "description": "菜单图标" + }, + { + "name": "permissions[].hidden", + "type": "number", + "required": true, + "description": "是否隐藏菜单:1=隐藏,0=显示" + }, + { + "name": "permissions[].always_show", + "type": "number", + "required": true, + "description": "是否总是显示父级菜单:1=是,0=否" + }, + { + "name": "permissions[].selected", + "type": "boolean", + "required": true, + "description": "当传入 role_id 时,表示该权限是否已绑定" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误" + }, + { + "code": "404", + "description": "角色不存在或无权限" + }, + { + "code": "500", + "description": "查询失败" + } + ] + }, + { + "method": "setting.permission.add", + "description": "新增权限;仅校验请求参数与父级权限是否存在,不再校验当前账号是否覆盖该权限", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "permission_id", + "type": "number", + "required": true, + "description": "权限ID" + }, + { + "name": "path", + "type": "string", + "required": true, + "description": "权限路径" + }, + { + "name": "type", + "type": "string", + "required": true, + "description": "权限类型" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误或 parent_id 不存在/不可用" + }, + { + "code": "404", + "description": "父级权限不存在" + }, + { + "code": "500", + "description": "新增失败" + } + ] + }, + { + "method": "setting.permission.delete", + "description": "批量删除权限(软删除);仅校验请求中的权限ID是否合法且存在", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "ids", + "type": "number[]", + "required": true, + "description": "请求的权限ID数组" + }, + { + "name": "deleted_ids", + "type": "number[]", + "required": true, + "description": "本次实际删除(由启用变为停用)的权限ID数组" + }, + { + "name": "already_deleted_ids", + "type": "number[]", + "required": true, + "description": "本就处于删除状态的权限ID数组" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "固定返回 deleted" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误,ids 非法或包含不存在的权限ID" + }, + { + "code": "404", + "description": "权限不存在" + }, + { + "code": "500", + "description": "删除失败" + } + ] + }, + { + "method": "setting.permission.update", + "description": "更新权限;仅校验请求参数、目标权限及父级权限是否存在,不再校验当前账号是否覆盖该权限", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "permission_id", + "type": "number", + "required": true, + "description": "权限ID" + }, + { + "name": "path", + "type": "string", + "required": true, + "description": "更新后的权限路径" + }, + { + "name": "type", + "type": "string", + "required": true, + "description": "更新后的权限类型" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误、未提供更新项,或目标/父级权限不存在或不可用" + }, + { + "code": "404", + "description": "权限不存在" + }, + { + "code": "500", + "description": "更新失败" + } + ] + } + ] + }, + { + "groupName": "货主管理模块", + "module": "storeWarehouse", + "list": [ + { + "method": "storeWarehouse.store.list", + "description": "查询当前主体下的仓库-货主签约列表;当前主体是仓库时默认查看本仓下货主,当前主体是货主时默认查看本货主下签约仓库,`remask` 表示当前主体给对方设置的通用名/备注", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "签约关系数据列表" + }, + { + "name": "total", + "type": "number", + "required": true, + "description": "总条数" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误" + }, + { + "code": "500", + "description": "查询失败" + } + ] + }, + { + "method": "storeWarehouse.store.sign", + "description": "签约接口,支持双阶段流程:1)不传 `temp_code` 时由当前主体发起签约并生成临时码;2)对方主体携带 `temp_code` 预览或确认后,立即写入签约表并生效", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "mode", + "type": "string", + "required": true, + "description": "initiate / preview / confirm" + }, + { + "name": "temp_code", + "type": "string", + "required": false, + "description": "临时码" + }, + { + "name": "contract", + "type": "object", + "required": false, + "description": "确认签约后返回签约关系" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误或确认方不合法" + }, + { + "code": "403", + "description": "当前主体无权使用临时码" + }, + { + "code": "404", + "description": "签约对象不存在或临时码失效" + }, + { + "code": "500", + "description": "签约失败" + } + ] + }, + { + "method": "storeWarehouse.store.unbind", + "description": "解除/恢复仓库-货主签约可用状态;双方均可执行,本接口只变更 `use_status`", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "contract", + "type": "object", + "required": true, + "description": "更新后的关系对象" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误" + }, + { + "code": "404", + "description": "签约关系不存在或无权限操作" + }, + { + "code": "500", + "description": "更新失败" + } + ] + }, + { + "method": "storeWarehouse.store.rename", + "description": "修改当前主体给对方设置的签约显示名称/备注;当前主体为仓库时会更新 `store_remask`,当前主体为货主时会更新 `warehouse_remask`", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "contract", + "type": "object", + "required": true, + "description": "更新后的签约关系" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误或未提供 `remask`" + }, + { + "code": "404", + "description": "签约关系不存在或无权限操作" + }, + { + "code": "500", + "description": "修改签约名称失败" + } + ] + } + ] + }, + { + "groupName": "商品模块", + "module": "stock", + "list": [ + { + "method": "stock.warehouse.list", + "description": "仓库商品列表查询(支持 where 条件与分页)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "pagination 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.getProhibitedType", + "description": "查询违禁品类型列表(系统预设+仓库自定义)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.getInfo", + "description": "查询仓库商品详情", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.saveWarehouseStock", + "description": "更新仓库商品资料", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.createWarehouseStock", + "description": "新建仓库商品资料", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.getBarcodes", + "description": "查询商品条码列表", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.saveWarehouseStockBarcode", + "description": "保存商品条码信息", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.getStoreStocks", + "description": "查询仓库商品与货主关联列表", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.bindItem", + "description": "绑定货主商品关系", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.unbindItem", + "description": "解绑货主商品关系", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.checkItemCodeUnique", + "description": "校验商品编码在货主维度唯一性", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "item_code", + "type": "string", + "required": true, + "source": "body", + "description": "item_code 参数" + }, + { + "name": "store_id", + "type": "number", + "required": true, + "source": "body", + "description": "store_id 参数" + }, + { + "name": "id", + "type": "number", + "required": false, + "source": "body", + "description": "id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.queryStockLogs", + "description": "查询库存操作日志", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "warehouseId", + "type": "string", + "required": false, + "source": "body", + "description": "warehouseId 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.handleBatchDelete", + "description": "批量删除仓库商品资料", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.deleteUnit", + "description": "删除库存单位", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.deleteProhibited", + "description": "删除违禁品类型", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.handleBatchChange", + "description": "批量修改仓库商品字段", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.getStockUnits", + "description": "查询可用库存单位(系统+仓库)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.getUnitList", + "description": "查询当前仓库自定义单位列表", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.createProhibited", + "description": "新增违禁品类型", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "name", + "type": "string", + "required": true, + "source": "body", + "description": "name 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.createUnit", + "description": "新增库存单位", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "name", + "type": "string", + "required": true, + "source": "body", + "description": "name 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.search", + "description": "仓库商品关键字搜索", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "库存模块", + "module": "storage", + "list": [ + { + "method": "storage.receiving.getReceivingList", + "description": "storage.receiving.getReceivingList 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "pagination 参数" + }, + { + "name": "sort", + "type": "string", + "required": false, + "source": "body", + "description": "sort 参数" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "收货单列表" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息(page、pageSize、total、totalPages、hasPrevious、hasNext)" + }, + { + "name": "summary", + "type": "object", + "required": true, + "description": "汇总信息(total_quantity、total_locked、total_available、total_items)" + } + ], + "errors": [ + { + "code": "500", + "description": "查询失败" + } + ] + }, + { + "method": "storage.receiving.getReceivingDetail", + "description": "storage.receiving.getReceivingDetail 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "receiving", + "type": "object", + "required": true, + "description": "收货单详情(含 details、images、pagination)" + } + ], + "errors": [ + { + "code": "0", + "description": "无记录或无权访问" + }, + { + "code": "500", + "description": "服务器错误" + } + ] + }, + { + "method": "storage.receiving.batchCancelReceiving", + "description": "storage.receiving.batchCancelReceiving 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "message", + "type": "string", + "required": true, + "description": "批量作废处理结果" + } + ], + "errors": [ + { + "code": "0", + "description": "部分单据不存在、无权访问或状态不允许作废" + }, + { + "code": "500", + "description": "服务器错误" + } + ] + }, + { + "method": "storage.receiving.create", + "description": "storage.receiving.create 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "新建收货单ID" + }, + { + "name": "receiving_number", + "type": "string", + "required": true, + "description": "收货单号" + } + ], + "errors": [ + { + "code": "0", + "description": "创建失败(如字段枚举不合法、数据库约束异常)" + } + ] + }, + { + "method": "storage.receiving.addItem", + "description": "storage.receiving.addItem 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": false, + "source": "body", + "description": "id 参数" + }, + { + "name": "item", + "type": "object", + "required": false, + "source": "body", + "description": "item 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "storage.receiving.removeItem", + "description": "storage.receiving.removeItem 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": false, + "source": "body", + "description": "id 参数" + }, + { + "name": "item_id", + "type": "number", + "required": false, + "source": "body", + "description": "item_id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "storage.receiving.saveReceiving", + "description": "storage.receiving.saveReceiving 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "storage.receiving.get", + "description": "storage.receiving.get 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "storage.receiving.addDetail", + "description": "storage.receiving.addDetail 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "storage.receiving.bindDetailProduct", + "description": "绑定或改绑收货单明细商品,入参为收货单明细ID和商品ID;会更新明细的 `system_product_id` 与 `product_name`。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "detail_id", + "type": "number", + "required": true, + "source": "body", + "description": "收货单明细ID" + }, + { + "name": "system_product_id", + "type": "number", + "required": true, + "source": "body", + "description": "商品ID,必须属于当前仓库" + } + ], + "response": [ + { + "name": "detail_id", + "type": "number", + "required": true, + "description": "收货单明细ID" + }, + { + "name": "system_product_id", + "type": "number", + "required": true, + "description": "绑定后的商品ID" + }, + { + "name": "product_name", + "type": "string", + "required": true, + "description": "绑定后回填的商品名称" + } + ], + "errors": [ + { + "code": "400", + "description": "参数缺失或收货单状态不允许绑定/改绑商品" + }, + { + "code": "404", + "description": "收货单明细不存在,或商品不存在/不属于当前仓库" + }, + { + "code": "500", + "description": "绑定商品失败" + } + ] + }, + { + "method": "storage.receiving.deleteDetail", + "description": "storage.receiving.deleteDetail 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "storage.receiving.detailChange", + "description": "storage.receiving.detailChange 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "storage.receiving.cancel", + "description": "storage.receiving.cancel 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "storage.receiving.completeReceiving", + "description": "storage.receiving.completeReceiving 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "storage.entry.list", + "description": "入库单列表查询", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "pagination 参数" + }, + { + "name": "sort", + "type": "string", + "required": false, + "source": "body", + "description": "sort 参数" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "入库单列表" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息(page、pageSize、total、totalPages、hasPrevious、hasNext)" + }, + { + "name": "summary", + "type": "object", + "required": true, + "description": "状态汇总(total、pending、creating、created、completed、cancelled)" + } + ], + "errors": [ + { + "code": "400", + "description": "筛选条件格式错误" + }, + { + "code": "500", + "description": "查询失败" + } + ] + }, + { + "method": "storage.entry.get", + "description": "查询入库单详情", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "entryOrder", + "type": "object", + "required": true, + "description": "入库单详情(含 items 明细)" + } + ], + "errors": [ + { + "code": "400", + "description": "id 与 entry_order_code 均未传" + }, + { + "code": "0", + "description": "无记录或无权访问" + } + ] + }, + { + "method": "storage.entry.create", + "description": "创建入库单", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "新建入库单ID" + }, + { + "name": "entry_order_code", + "type": "string", + "required": true, + "description": "入库单号" + } + ], + "errors": [ + { + "code": "400", + "description": "参数缺失或业务类型不合法" + }, + { + "code": "409", + "description": "入库单号已存在" + } + ] + }, + { + "method": "storage.entry.addDetail", + "description": "新增入库明细", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "新建明细ID" + }, + { + "name": "order_id", + "type": "number", + "required": true, + "description": "所属入库单ID" + } + ], + "errors": [ + { + "code": "400", + "description": "参数不合法或状态不允许新增明细" + }, + { + "code": "404", + "description": "入库单不存在或无权访问" + } + ] + }, + { + "method": "storage.entry.deleteDetail", + "description": "删除入库明细", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "删除成功的明细ID" + } + ], + "errors": [ + { + "code": "400", + "description": "参数不合法或明细已有收货数量" + }, + { + "code": "404", + "description": "明细或入库单不存在" + } + ] + }, + { + "method": "storage.entry.detailChange", + "description": "修改入库明细", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "修改成功的明细ID" + } + ], + "errors": [ + { + "code": "400", + "description": "参数不合法或没有可更新字段" + }, + { + "code": "404", + "description": "明细或入库单不存在" + } + ] + }, + { + "method": "storage.entry.cancel", + "description": "作废入库单", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "作废成功的入库单ID" + } + ], + "errors": [ + { + "code": "400", + "description": "参数不合法或已完成单据不允许作废" + }, + { + "code": "404", + "description": "入库单不存在或无权访问" + } + ] + }, + { + "method": "storage.entry.completeEntry", + "description": "完成入库单", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "完成成功的入库单ID" + } + ], + "errors": [ + { + "code": "400", + "description": "参数不合法、已作废或缺少明细" + }, + { + "code": "404", + "description": "入库单不存在或无权访问" + } + ] + } + ] + }, + { + "groupName": "主体模块", + "module": "store", + "list": [ + { + "method": "store.createStore", + "description": "store.createStore 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "store.createWarehouse", + "description": "store.createWarehouse 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "store.joinStore", + "description": "store.joinStore 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "store.joinWarehouse", + "description": "store.joinWarehouse 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "store.getStoreRoles", + "description": "store.getStoreRoles 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "store.auditApply", + "description": "store.auditApply 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "用户模块", + "module": "user", + "list": [ + { + "method": "user.login", + "description": "用户登录(仅返回 token)", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "password", + "type": "string", + "required": false, + "source": "body", + "description": "password 参数" + }, + { + "name": "username", + "type": "string", + "required": false, + "source": "body", + "description": "username 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "user.loginByCode", + "description": "登录码登录(使用本系统缓存登录码,不依赖 ye4s_user.tmp_code)", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "code", + "type": "string", + "required": true, + "source": "body", + "description": "code 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "user.getLoginWechatCode", + "description": "获取微信扫码登录码:不传客户端编码时生成新的6位客户端编码与登录码;传客户端编码且缓存命中时进入长轮询,优先监听 Redis 登录事件,收到 ye4s_user_id 后立即签发登录 token;未收到事件则刷新登录码返回", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [], + "response": [ + { + "name": "client_code", + "type": "string", + "required": true, + "description": "客户端编码(6位字母数字混合)" + }, + { + "name": "code", + "type": "string", + "required": false, + "description": "微信扫码登录码(6位字母数字混合)。当 status=authorized 时可能为空" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "登录状态:pending(等待扫码)或 authorized(已完成登录)" + }, + { + "name": "updated_at", + "type": "string", + "required": false, + "description": "状态更新时间(ISO 时间)" + }, + { + "name": "expires_at", + "type": "number", + "required": false, + "description": "过期时间戳(毫秒)" + }, + { + "name": "expire_after_ms", + "type": "number", + "required": false, + "description": "距离过期剩余毫秒数" + }, + { + "name": "source", + "type": "string", + "required": true, + "description": "数据来源,如 generated/refreshed/cache/event" + }, + { + "name": "ye4s_user_id", + "type": "number", + "required": false, + "description": "当 status=authorized 时返回的 ye4s 用户ID" + }, + { + "name": "loginToken", + "type": "string", + "required": false, + "description": "当 status=authorized 时返回的本地登录 token" + } + ], + "errors": [] + }, + { + "method": "user.getBindWechatCode", + "description": "获取微信绑定状态与绑定码:绑定码为6位字母数字混合且固定60秒有效,默认立即返回;longPoll=true 时最长等待60秒,若无事件则自动刷新新码返回", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "account_id", + "type": "number", + "required": true, + "description": "WMS 账号ID" + }, + { + "name": "code", + "type": "string", + "required": true, + "description": "绑定码(已绑定时为空字符串)" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "绑定状态:pending/scanned/bound" + }, + { + "name": "is_bound", + "type": "boolean", + "required": true, + "description": "是否已绑定微信" + }, + { + "name": "updated_at", + "type": "string", + "required": true, + "description": "状态更新时间(ISO 时间)" + }, + { + "name": "expires_at", + "type": "number", + "required": false, + "description": "过期时间戳(毫秒),bound 状态可为空" + }, + { + "name": "expire_after_ms", + "type": "number", + "required": true, + "description": "距离过期剩余毫秒数" + }, + { + "name": "scanned_at", + "type": "string", + "required": false, + "description": "扫码时间(未扫码可为空)" + }, + { + "name": "source", + "type": "string", + "required": true, + "description": "数据来源,如 cache/generated/refreshed/db" + }, + { + "name": "ye4s_user_id", + "type": "number", + "required": false, + "description": "已绑定的 ye4s 用户ID(未绑定可为空)" + } + ], + "errors": [] + }, + { + "method": "user.unbindWechat", + "description": "解绑微信账号(清理 ye4s 关联账号数据)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "user.logout", + "description": "用户登出", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "user.info", + "description": "获取当前用户信息", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "user.changeRole", + "description": "user.changeRole 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "user.register", + "description": "user.register 接口", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "仓库模块", + "module": "warehouse", + "list": [ + { + "method": "warehouse.getWarehouseZones", + "description": "warehouse.getWarehouseZones 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "warehouse.getWarehouseTree", + "description": "warehouse.getWarehouseTree 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "warehouseId", + "type": "number", + "required": true, + "source": "body", + "description": "warehouseId 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.getChildren", + "description": "warehouse.getChildren 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "zoneId", + "type": "number", + "required": true, + "source": "body", + "description": "zoneId 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.create", + "description": "warehouse.create 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "warehouse.update", + "description": "warehouse.update 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "id 参数" + }, + { + "name": "aisles", + "type": "string", + "required": false, + "source": "body", + "description": "aisles 参数" + }, + { + "name": "cell_height", + "type": "string", + "required": false, + "source": "body", + "description": "cell_height 参数" + }, + { + "name": "cell_length", + "type": "string", + "required": false, + "source": "body", + "description": "cell_length 参数" + }, + { + "name": "cell_width", + "type": "string", + "required": false, + "source": "body", + "description": "cell_width 参数" + }, + { + "name": "direction", + "type": "string", + "required": false, + "source": "body", + "description": "direction 参数" + }, + { + "name": "height", + "type": "number", + "required": false, + "source": "body", + "description": "height 参数" + }, + { + "name": "length", + "type": "number", + "required": false, + "source": "body", + "description": "length 参数" + }, + { + "name": "rack_columns", + "type": "string", + "required": false, + "source": "body", + "description": "rack_columns 参数" + }, + { + "name": "rack_levels", + "type": "string", + "required": false, + "source": "body", + "description": "rack_levels 参数" + }, + { + "name": "rack_rows", + "type": "string", + "required": false, + "source": "body", + "description": "rack_rows 参数" + }, + { + "name": "width", + "type": "number", + "required": false, + "source": "body", + "description": "width 参数" + }, + { + "name": "x", + "type": "number", + "required": false, + "source": "body", + "description": "x 参数" + }, + { + "name": "y", + "type": "number", + "required": false, + "source": "body", + "description": "y 参数" + }, + { + "name": "z", + "type": "number", + "required": false, + "source": "body", + "description": "z 参数" + }, + { + "name": "zone_code", + "type": "string", + "required": false, + "source": "body", + "description": "zone_code 参数" + }, + { + "name": "zone_name", + "type": "string", + "required": false, + "source": "body", + "description": "zone_name 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.delete", + "description": "warehouse.delete 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.detail", + "description": "warehouse.detail 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.checkBarcodeUnique", + "description": "warehouse.checkBarcodeUnique 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "barcode", + "type": "string", + "required": true, + "source": "body", + "description": "barcode 参数" + }, + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.toggleActive", + "description": "warehouse.toggleActive 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "id 参数" + }, + { + "name": "isActive", + "type": "string", + "required": false, + "source": "body", + "description": "isActive 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.getPath", + "description": "warehouse.getPath 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.createRack", + "description": "warehouse.createRack 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "height", + "type": "number", + "required": true, + "source": "body", + "description": "height 参数" + }, + { + "name": "length", + "type": "number", + "required": true, + "source": "body", + "description": "length 参数" + }, + { + "name": "rack_columns", + "type": "number", + "required": true, + "source": "body", + "description": "rack_columns 参数" + }, + { + "name": "rack_levels", + "type": "number", + "required": true, + "source": "body", + "description": "rack_levels 参数" + }, + { + "name": "rack_rows", + "type": "number", + "required": true, + "source": "body", + "description": "rack_rows 参数" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "source": "body", + "description": "warehouse_id 参数" + }, + { + "name": "width", + "type": "number", + "required": true, + "source": "body", + "description": "width 参数" + }, + { + "name": "x", + "type": "number", + "required": true, + "source": "body", + "description": "x 参数" + }, + { + "name": "y", + "type": "number", + "required": true, + "source": "body", + "description": "y 参数" + }, + { + "name": "zone_code", + "type": "string", + "required": true, + "source": "body", + "description": "zone_code 参数" + }, + { + "name": "zone_name", + "type": "string", + "required": true, + "source": "body", + "description": "zone_name 参数" + }, + { + "name": "color", + "type": "string", + "required": false, + "source": "body", + "description": "color 参数" + }, + { + "name": "direction", + "type": "string", + "required": false, + "source": "body", + "description": "direction 参数" + }, + { + "name": "parent_id", + "type": "number", + "required": false, + "source": "body", + "description": "parent_id 参数" + }, + { + "name": "z", + "type": "number", + "required": false, + "source": "body", + "description": "z 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.getPickPath", + "description": "warehouse.getPickPath 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "warehouse_id", + "type": "number", + "required": true, + "source": "query", + "description": "warehouse_id 参数" + }, + { + "name": "include_spaces", + "type": "string", + "required": false, + "source": "query", + "description": "include_spaces 参数" + }, + { + "name": "limit", + "type": "number", + "required": false, + "source": "query", + "description": "limit 参数" + }, + { + "name": "sort_by", + "type": "string", + "required": false, + "source": "query", + "description": "sort_by 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.updateRackPosition", + "description": "warehouse.updateRackPosition 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "x", + "type": "number", + "required": true, + "source": "body", + "description": "x 参数" + }, + { + "name": "y", + "type": "number", + "required": true, + "source": "body", + "description": "y 参数" + }, + { + "name": "rack_id", + "type": "number", + "required": false, + "source": "path", + "description": "rack_id 参数" + }, + { + "name": "z", + "type": "number", + "required": false, + "source": "body", + "description": "z 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.recalculatePickPath", + "description": "warehouse.recalculatePickPath 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "warehouse_id", + "type": "number", + "required": true, + "source": "body", + "description": "warehouse_id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.updateNeighbors", + "description": "warehouse.updateNeighbors 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "warehouse_id", + "type": "number", + "required": true, + "source": "body", + "description": "warehouse_id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.getAreaRacks", + "description": "warehouse.getAreaRacks 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "area_id", + "type": "number", + "required": true, + "source": "query", + "description": "area_id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.getSpacesByRack", + "description": "warehouse.getSpacesByRack 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.createRackWithSpaces", + "description": "warehouse.createRackWithSpaces 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.getSpaceInfo", + "description": "warehouse.getSpaceInfo 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": false, + "source": "body", + "description": "id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.updateSpaceInfo", + "description": "warehouse.updateSpaceInfo 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "id 参数" + }, + { + "name": "custom_barcode", + "type": "string", + "required": false, + "source": "body", + "description": "custom_barcode 参数" + }, + { + "name": "custom_name", + "type": "string", + "required": false, + "source": "body", + "description": "custom_name 参数" + }, + { + "name": "location_type_id", + "type": "number", + "required": false, + "source": "body", + "description": "location_type_id 参数" + }, + { + "name": "pick_sequence", + "type": "string", + "required": false, + "source": "body", + "description": "pick_sequence 参数" + }, + { + "name": "space_status", + "type": "string", + "required": false, + "source": "body", + "description": "space_status 参数" + } + ], + "response": [], + "errors": [] + } + ] + } + ] + } } diff --git a/package-lock.json b/package-lock.json index 05547a6..b51cb5b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -22,12 +22,14 @@ "egg-sequelize": "^6.0.0", "egg-view-ejs": "^3.0.0", "ejs": "^5.0.1", + "exceljs": "^4.4.0", "fast-xml-parser": "^5.3.1", "mysql2": "^3.15.3", "path": "^0.12.7", "qiniu-js": "^3.4.3", "soap": "^1.8.0", - "spark-md5": "^3.0.2" + "spark-md5": "^3.0.2", + "xlsx": "^0.18.5" }, "devDependencies": { "egg-bin": "6", @@ -706,6 +708,47 @@ "node": "^12.22.0 || ^14.17.0 || >=16.0.0" } }, + "node_modules/@fast-csv/format": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@fast-csv/format/-/format-4.3.5.tgz", + "integrity": "sha512-8iRn6QF3I8Ak78lNAa+Gdl5MJJBM5vRHivFtMRUWINdevNo00K7OXxS2PshawLKTejVwieIlPmK5YlLu6w4u8A==", + "license": "MIT", + "dependencies": { + "@types/node": "^14.0.1", + "lodash.escaperegexp": "^4.1.2", + "lodash.isboolean": "^3.0.3", + "lodash.isequal": "^4.5.0", + "lodash.isfunction": "^3.0.9", + "lodash.isnil": "^4.0.0" + } + }, + "node_modules/@fast-csv/format/node_modules/@types/node": { + "version": "14.18.63", + "resolved": "https://registry.npmjs.org/@types/node/-/node-14.18.63.tgz", + "integrity": "sha512-fAtCfv4jJg+ExtXhvCkCqUKZ+4ok/JQk01qDKhL5BDDoS3AxKXhV5/MAVUZyQnSEd2GT92fkgZl0pz0Q0AzcIQ==", + "license": "MIT" + }, + "node_modules/@fast-csv/parse": { + "version": "4.3.6", + "resolved": "https://registry.npmjs.org/@fast-csv/parse/-/parse-4.3.6.tgz", + "integrity": "sha512-uRsLYksqpbDmWaSmzvJcuApSEe38+6NQZBUsuAyMZKqHxH0g1wcJgsKUvN3WC8tewaqFjBMMGrkHmC+T7k8LvA==", + "license": "MIT", + "dependencies": { + "@types/node": "^14.0.1", + "lodash.escaperegexp": "^4.1.2", + "lodash.groupby": "^4.6.0", + "lodash.isfunction": "^3.0.9", + "lodash.isnil": "^4.0.0", + "lodash.isundefined": "^3.0.1", + "lodash.uniq": "^4.5.0" + } + }, + "node_modules/@fast-csv/parse/node_modules/@types/node": { + "version": "14.18.63", + "resolved": "https://registry.npmjs.org/@types/node/-/node-14.18.63.tgz", + "integrity": "sha512-fAtCfv4jJg+ExtXhvCkCqUKZ+4ok/JQk01qDKhL5BDDoS3AxKXhV5/MAVUZyQnSEd2GT92fkgZl0pz0Q0AzcIQ==", + "license": "MIT" + }, "node_modules/@fastify/busboy": { "version": "2.1.1", "resolved": "https://mirrors.huaweicloud.com/repository/npm/@fastify/busboy/-/busboy-2.1.1.tgz", @@ -2059,6 +2102,15 @@ "node": ">= 16.0.0" } }, + "node_modules/adler-32": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/adler-32/-/adler-32-1.3.1.tgz", + "integrity": "sha512-ynZ4w/nUUv5rrsR8UUGoe1VC9hZj6V5hU9Qw1HlMDJGEJw5S7TfTErWTjMys6M7vr0YWcPqs3qAr4ss0nDfP+A==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.8" + } + }, "node_modules/agentkeepalive": { "version": "4.6.0", "resolved": "https://mirrors.huaweicloud.com/repository/npm/agentkeepalive/-/agentkeepalive-4.6.0.tgz", @@ -2205,6 +2257,130 @@ "node": ">= 8" } }, + "node_modules/archiver": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/archiver/-/archiver-5.3.2.tgz", + "integrity": "sha512-+25nxyyznAXF7Nef3y0EbBeqmGZgeN/BxHX29Rs39djAfaFalmQ89SE6CWyDCHzGL0yt/ycBtNOmGTW0FyGWNw==", + "license": "MIT", + "dependencies": { + "archiver-utils": "^2.1.0", + "async": "^3.2.4", + "buffer-crc32": "^0.2.1", + "readable-stream": "^3.6.0", + "readdir-glob": "^1.1.2", + "tar-stream": "^2.2.0", + "zip-stream": "^4.1.0" + }, + "engines": { + "node": ">= 10" + } + }, + "node_modules/archiver-utils": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/archiver-utils/-/archiver-utils-2.1.0.tgz", + "integrity": "sha512-bEL/yUb/fNNiNTuUz979Z0Yg5L+LzLxGJz8x79lYmR54fmTIb6ob/hNQgkQnIUDWIFjZVQwl9Xs356I6BAMHfw==", + "license": "MIT", + "dependencies": { + "glob": "^7.1.4", + "graceful-fs": "^4.2.0", + "lazystream": "^1.0.0", + "lodash.defaults": "^4.2.0", + "lodash.difference": "^4.5.0", + "lodash.flatten": "^4.4.0", + "lodash.isplainobject": "^4.0.6", + "lodash.union": "^4.6.0", + "normalize-path": "^3.0.0", + "readable-stream": "^2.0.0" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/archiver-utils/node_modules/brace-expansion": { + "version": "1.1.13", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.13.tgz", + "integrity": "sha512-9ZLprWS6EENmhEOpjCYW2c8VkmOvckIJZfkr7rBW6dObmfgJ/L1GpSYW5Hpo9lDz4D1+n0Ckz8rU7FwHDQiG/w==", + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/archiver-utils/node_modules/glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me", + "license": "ISC", + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/archiver-utils/node_modules/isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", + "license": "MIT" + }, + "node_modules/archiver-utils/node_modules/minimatch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/archiver-utils/node_modules/readable-stream": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz", + "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", + "license": "MIT", + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/archiver-utils/node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "license": "MIT" + }, + "node_modules/archiver-utils/node_modules/string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, + "node_modules/archiver/node_modules/async": { + "version": "3.2.6", + "resolved": "https://registry.npmjs.org/async/-/async-3.2.6.tgz", + "integrity": "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==", + "license": "MIT" + }, "node_modules/are-docs-informative": { "version": "0.0.2", "resolved": "https://mirrors.huaweicloud.com/repository/npm/are-docs-informative/-/are-docs-informative-0.0.2.tgz", @@ -2663,6 +2839,28 @@ "tweetnacl": "^0.14.3" } }, + "node_modules/big-integer": { + "version": "1.6.52", + "resolved": "https://registry.npmjs.org/big-integer/-/big-integer-1.6.52.tgz", + "integrity": "sha512-QxD8cf2eVqJOOz63z6JIN9BzvVs/dlySa5HGSBH5xtR8dPteIRQnBxxKqkNTiT6jbDTF6jAfrd4oMcND9RGbQg==", + "license": "Unlicense", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/binary": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/binary/-/binary-0.3.0.tgz", + "integrity": "sha512-D4H1y5KYwpJgK8wk1Cue5LLPgmwHKYSChkbspQg5JtVuR5ulGckxfR62H3AE9UDkdMC8yyXlqYihuz3Aqg2XZg==", + "license": "MIT", + "dependencies": { + "buffers": "~0.1.1", + "chainsaw": "~0.1.0" + }, + "engines": { + "node": "*" + } + }, "node_modules/binary-extensions": { "version": "2.3.0", "resolved": "https://mirrors.huaweicloud.com/repository/npm/binary-extensions/-/binary-extensions-2.3.0.tgz", @@ -2680,7 +2878,6 @@ "version": "4.1.0", "resolved": "https://mirrors.huaweicloud.com/repository/npm/bl/-/bl-4.1.0.tgz", "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==", - "dev": true, "license": "MIT", "dependencies": { "buffer": "^5.5.0", @@ -2787,6 +2984,15 @@ "ieee754": "^1.1.13" } }, + "node_modules/buffer-crc32": { + "version": "0.2.13", + "resolved": "https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-0.2.13.tgz", + "integrity": "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ==", + "license": "MIT", + "engines": { + "node": "*" + } + }, "node_modules/buffer-equal-constant-time": { "version": "1.0.1", "resolved": "https://mirrors.huaweicloud.com/repository/npm/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", @@ -2799,6 +3005,23 @@ "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", "license": "MIT" }, + "node_modules/buffer-indexof-polyfill": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/buffer-indexof-polyfill/-/buffer-indexof-polyfill-1.0.2.tgz", + "integrity": "sha512-I7wzHwA3t1/lwXQh+A5PbNvJxgfo5r3xulgpYDB5zckTu/Z9oUK9biouBKQUjEqzaz3HnAT6TYoovmE+GqSf7A==", + "license": "MIT", + "engines": { + "node": ">=0.10" + } + }, + "node_modules/buffers": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/buffers/-/buffers-0.1.1.tgz", + "integrity": "sha512-9q/rDEGSb/Qsvv2qvzIzdluL5k7AaJOTrw23z9reQthrbF7is4CtlT0DXyO1oei2DCp4uojjzQ7igaSHp1kAEQ==", + "engines": { + "node": ">=0.2.0" + } + }, "node_modules/builtin-modules": { "version": "3.3.0", "resolved": "https://mirrors.huaweicloud.com/repository/npm/builtin-modules/-/builtin-modules-3.3.0.tgz", @@ -3009,6 +3232,19 @@ "integrity": "sha512-4tYFyifaFfGacoiObjJegolkwSU4xQNGbVgUiNYVUxbQ2x2lUsFvY4hVgVzGiIe6WLOPqycWXA40l+PWsxthUw==", "license": "Apache-2.0" }, + "node_modules/cfb": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/cfb/-/cfb-1.2.2.tgz", + "integrity": "sha512-KfdUZsSOw19/ObEWasvBP/Ac4reZvAGauZhs6S/gqNhXhI7cKwvlH7ulj+dOEYnca4bm4SGo8C1bTAQvnTjgQA==", + "license": "Apache-2.0", + "dependencies": { + "adler-32": "~1.3.0", + "crc-32": "~1.2.0" + }, + "engines": { + "node": ">=0.8" + } + }, "node_modules/cfork": { "version": "1.11.0", "resolved": "https://mirrors.huaweicloud.com/repository/npm/cfork/-/cfork-1.11.0.tgz", @@ -3037,6 +3273,18 @@ "node": ">= 0.12.0" } }, + "node_modules/chainsaw": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/chainsaw/-/chainsaw-0.1.0.tgz", + "integrity": "sha512-75kWfWt6MEKNC8xYXIdRpDehRYY/tNSgwKaJq+dbbDcxORuVrrQ+SEHoWsniVn9XPYfP4gmdWIeDk/4YNp1rNQ==", + "license": "MIT/X11", + "dependencies": { + "traverse": ">=0.3.0 <0.4" + }, + "engines": { + "node": "*" + } + }, "node_modules/chalk": { "version": "2.4.2", "resolved": "https://mirrors.huaweicloud.com/repository/npm/chalk/-/chalk-2.4.2.tgz", @@ -3343,6 +3591,15 @@ "node": ">= 14.0.0" } }, + "node_modules/codepage": { + "version": "1.15.0", + "resolved": "https://registry.npmjs.org/codepage/-/codepage-1.15.0.tgz", + "integrity": "sha512-3g6NUTPd/YtuuGrhMnOMRjFc+LJw/bnMp3+0r/Wcz3IXUuCosKRJvMphm5+Q+bvTVGcJJuRvVLuYba+WojaFaA==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.8" + } + }, "node_modules/coffee": { "version": "5.5.1", "resolved": "https://mirrors.huaweicloud.com/repository/npm/coffee/-/coffee-5.5.1.tgz", @@ -3693,6 +3950,21 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/compress-commons": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/compress-commons/-/compress-commons-4.1.2.tgz", + "integrity": "sha512-D3uMHtGc/fcO1Gt1/L7i1e33VOvD4A9hfQLP+6ewd+BvG/gQ84Yh4oftEhAdjSMgBgwGL+jsppT7JYNpo6MHHg==", + "license": "MIT", + "dependencies": { + "buffer-crc32": "^0.2.13", + "crc32-stream": "^4.0.2", + "normalize-path": "^3.0.0", + "readable-stream": "^3.6.0" + }, + "engines": { + "node": ">= 10" + } + }, "node_modules/compressible": { "version": "2.0.18", "resolved": "https://mirrors.huaweicloud.com/repository/npm/compressible/-/compressible-2.0.18.tgz", @@ -4018,6 +4290,31 @@ "buffer": "^5.1.0" } }, + "node_modules/crc-32": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/crc-32/-/crc-32-1.2.2.tgz", + "integrity": "sha512-ROmzCKrTnOwybPcJApAA6WBWij23HVfGVNKqqrZpuyZOHqK2CwHSvpGuyt/UNNvaIjEd8X5IFGp4Mh+Ie1IHJQ==", + "license": "Apache-2.0", + "bin": { + "crc32": "bin/crc32.njs" + }, + "engines": { + "node": ">=0.8" + } + }, + "node_modules/crc32-stream": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/crc32-stream/-/crc32-stream-4.0.3.tgz", + "integrity": "sha512-NT7w2JVU7DFroFdYkeq8cywxrgjPHWkdX1wjpRQXPX5Asews3tA+Ght6lddQO5Mkumffp3X7GEqku3epj2toIw==", + "license": "MIT", + "dependencies": { + "crc-32": "^1.2.0", + "readable-stream": "^3.4.0" + }, + "engines": { + "node": ">= 10" + } + }, "node_modules/create-require": { "version": "1.1.1", "resolved": "https://mirrors.huaweicloud.com/repository/npm/create-require/-/create-require-1.1.1.tgz", @@ -4500,6 +4797,51 @@ "integrity": "sha512-jtD6YG370ZCIi/9GTaJKQxWTZD045+4R4hTk/x1UyoqadyJ9x9CgSi1RlVDQF8U2sxLLSnFkCaMihqljHIWgMg==", "license": "MIT" }, + "node_modules/duplexer2": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/duplexer2/-/duplexer2-0.1.4.tgz", + "integrity": "sha512-asLFVfWWtJ90ZyOUHMqk7/S2w2guQKxUI2itj3d92ADHhxUSbCMGi1f1cBcJ7xM1To+pE/Khbwo1yuNbMEPKeA==", + "license": "BSD-3-Clause", + "dependencies": { + "readable-stream": "^2.0.2" + } + }, + "node_modules/duplexer2/node_modules/isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", + "license": "MIT" + }, + "node_modules/duplexer2/node_modules/readable-stream": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz", + "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", + "license": "MIT", + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/duplexer2/node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "license": "MIT" + }, + "node_modules/duplexer2/node_modules/string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, "node_modules/duplexify": { "version": "3.7.1", "resolved": "https://mirrors.huaweicloud.com/repository/npm/duplexify/-/duplexify-3.7.1.tgz", @@ -6736,6 +7078,26 @@ "through": "~2.3.1" } }, + "node_modules/exceljs": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/exceljs/-/exceljs-4.4.0.tgz", + "integrity": "sha512-XctvKaEMaj1Ii9oDOqbW/6e1gXknSY4g/aLCDicOXqBE4M0nRWkUu0PTp++UPNzoFY12BNHMfs/VadKIS6llvg==", + "license": "MIT", + "dependencies": { + "archiver": "^5.0.0", + "dayjs": "^1.8.34", + "fast-csv": "^4.3.1", + "jszip": "^3.10.1", + "readable-stream": "^3.6.0", + "saxes": "^5.0.1", + "tmp": "^0.2.0", + "unzipper": "^0.10.11", + "uuid": "^8.3.0" + }, + "engines": { + "node": ">=8.3.0" + } + }, "node_modules/execa": { "version": "5.1.1", "resolved": "https://mirrors.huaweicloud.com/repository/npm/execa/-/execa-5.1.1.tgz", @@ -6864,6 +7226,19 @@ ], "license": "MIT" }, + "node_modules/fast-csv": { + "version": "4.3.6", + "resolved": "https://registry.npmjs.org/fast-csv/-/fast-csv-4.3.6.tgz", + "integrity": "sha512-2RNSpuwwsJGP0frGsOmTb9oUF+VkFSM4SyLTDgwf2ciHWTarN0lQTC+F2f/t5J9QjW+c65VFIAAu85GsvMIusw==", + "license": "MIT", + "dependencies": { + "@fast-csv/format": "4.3.5", + "@fast-csv/parse": "4.3.6" + }, + "engines": { + "node": ">=10.0.0" + } + }, "node_modules/fast-deep-equal": { "version": "3.1.3", "resolved": "https://mirrors.huaweicloud.com/repository/npm/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", @@ -7221,6 +7596,15 @@ "pause-stream": "~0.0.11" } }, + "node_modules/frac": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/frac/-/frac-1.1.2.tgz", + "integrity": "sha512-w/XBfkibaTl3YDqASwfDUqkna4Z2p9cFSr1aHDt0WoMTECnRfBOv2WArlZILlqgWlmdIlALXGpM2AOhEk5W3IA==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.8" + } + }, "node_modules/fresh": { "version": "0.5.2", "resolved": "https://mirrors.huaweicloud.com/repository/npm/fresh/-/fresh-0.5.2.tgz", @@ -7236,6 +7620,12 @@ "integrity": "sha512-twe20eF1OxVxp/ML/kq2p1uc6KvFK/+vs8WjEbeKmV2He22MKm7YF2ANIt+EOqhJ5L3K/SuuPhk0hWQDjOM23g==", "license": "MIT" }, + "node_modules/fs-constants": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz", + "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==", + "license": "MIT" + }, "node_modules/fs-extra": { "version": "10.1.0", "resolved": "https://mirrors.huaweicloud.com/repository/npm/fs-extra/-/fs-extra-10.1.0.tgz", @@ -7278,6 +7668,78 @@ "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, + "node_modules/fstream": { + "version": "1.0.12", + "resolved": "https://registry.npmjs.org/fstream/-/fstream-1.0.12.tgz", + "integrity": "sha512-WvJ193OHa0GHPEL+AycEJgxvBEwyfRkN1vhjca23OaPVMCaLCXTd5qAu82AjTcgP1UJmytkOKb63Ypde7raDIg==", + "deprecated": "This package is no longer supported.", + "license": "ISC", + "dependencies": { + "graceful-fs": "^4.1.2", + "inherits": "~2.0.0", + "mkdirp": ">=0.5 0", + "rimraf": "2" + }, + "engines": { + "node": ">=0.6" + } + }, + "node_modules/fstream/node_modules/brace-expansion": { + "version": "1.1.13", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.13.tgz", + "integrity": "sha512-9ZLprWS6EENmhEOpjCYW2c8VkmOvckIJZfkr7rBW6dObmfgJ/L1GpSYW5Hpo9lDz4D1+n0Ckz8rU7FwHDQiG/w==", + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/fstream/node_modules/glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me", + "license": "ISC", + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/fstream/node_modules/minimatch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/fstream/node_modules/rimraf": { + "version": "2.7.1", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.7.1.tgz", + "integrity": "sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==", + "deprecated": "Rimraf versions prior to v4 are no longer supported", + "license": "ISC", + "dependencies": { + "glob": "^7.1.3" + }, + "bin": { + "rimraf": "bin.js" + } + }, "node_modules/fsu": { "version": "1.1.1", "resolved": "https://mirrors.huaweicloud.com/repository/npm/fsu/-/fsu-1.1.1.tgz", @@ -7599,7 +8061,6 @@ "version": "4.2.11", "resolved": "https://mirrors.huaweicloud.com/repository/npm/graceful-fs/-/graceful-fs-4.2.11.tgz", "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", - "dev": true, "license": "ISC" }, "node_modules/graceful-process": { @@ -7900,6 +8361,12 @@ "node": ">= 4" } }, + "node_modules/immediate": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/immediate/-/immediate-3.0.6.tgz", + "integrity": "sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ==", + "license": "MIT" + }, "node_modules/import-fresh": { "version": "3.3.1", "resolved": "https://mirrors.huaweicloud.com/repository/npm/import-fresh/-/import-fresh-3.3.1.tgz", @@ -9184,6 +9651,54 @@ "node": ">=4.0" } }, + "node_modules/jszip": { + "version": "3.10.1", + "resolved": "https://registry.npmjs.org/jszip/-/jszip-3.10.1.tgz", + "integrity": "sha512-xXDvecyTpGLrqFrvkrUSoxxfJI5AH7U8zxxtVclpsUtMCq4JQ290LY8AW5c7Ggnr/Y/oK+bQMbqK2qmtk3pN4g==", + "license": "(MIT OR GPL-3.0-or-later)", + "dependencies": { + "lie": "~3.3.0", + "pako": "~1.0.2", + "readable-stream": "~2.3.6", + "setimmediate": "^1.0.5" + } + }, + "node_modules/jszip/node_modules/isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", + "license": "MIT" + }, + "node_modules/jszip/node_modules/readable-stream": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz", + "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", + "license": "MIT", + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/jszip/node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "license": "MIT" + }, + "node_modules/jszip/node_modules/string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, "node_modules/jwa": { "version": "1.4.2", "resolved": "https://mirrors.huaweicloud.com/repository/npm/jwa/-/jwa-1.4.2.tgz", @@ -9526,6 +10041,54 @@ "node": ">=0.10" } }, + "node_modules/lazystream": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/lazystream/-/lazystream-1.0.1.tgz", + "integrity": "sha512-b94GiNHQNy6JNTrt5w6zNyffMrNkXZb3KTkCZJb2V1xaEGCk093vkZ2jk3tpaeP33/OiXC+WvK9AxUebnf5nbw==", + "license": "MIT", + "dependencies": { + "readable-stream": "^2.0.5" + }, + "engines": { + "node": ">= 0.6.3" + } + }, + "node_modules/lazystream/node_modules/isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", + "license": "MIT" + }, + "node_modules/lazystream/node_modules/readable-stream": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz", + "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", + "license": "MIT", + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/lazystream/node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "license": "MIT" + }, + "node_modules/lazystream/node_modules/string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, "node_modules/levn": { "version": "0.4.1", "resolved": "https://mirrors.huaweicloud.com/repository/npm/levn/-/levn-0.4.1.tgz", @@ -9540,6 +10103,21 @@ "node": ">= 0.8.0" } }, + "node_modules/lie": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/lie/-/lie-3.3.0.tgz", + "integrity": "sha512-UaiMJzeWRlEujzAuw5LokY1L5ecNQYZKfmyZ9L7wDHb/p5etKaxXhohBcrw0EYby+G/NA52vRSN4N39dxHAIwQ==", + "license": "MIT", + "dependencies": { + "immediate": "~3.0.5" + } + }, + "node_modules/listenercount": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/listenercount/-/listenercount-1.0.1.tgz", + "integrity": "sha512-3mk/Zag0+IJxeDrxSgaDPy4zZ3w05PRZeJNnlWhzFz5OkX49J4krc+A8X2d2M69vGMBEX0uyl8M+W+8gH+kBqQ==", + "license": "ISC" + }, "node_modules/locate-path": { "version": "6.0.0", "resolved": "https://mirrors.huaweicloud.com/repository/npm/locate-path/-/locate-path-6.0.0.tgz", @@ -9568,12 +10146,30 @@ "integrity": "sha512-qjxPLHd3r5DnsdGacqOMU6pb/avJzdh9tFX2ymgoZE27BmjXrNy/y4LoaiTeAb+O3gL8AfpJGtqfX/ae2leYYQ==", "license": "MIT" }, + "node_modules/lodash.difference": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/lodash.difference/-/lodash.difference-4.5.0.tgz", + "integrity": "sha512-dS2j+W26TQ7taQBGN8Lbbq04ssV3emRw4NY58WErlTO29pIqS0HmoT5aJ9+TUQ1N3G+JOZSji4eugsWwGp9yPA==", + "license": "MIT" + }, + "node_modules/lodash.escaperegexp": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/lodash.escaperegexp/-/lodash.escaperegexp-4.1.2.tgz", + "integrity": "sha512-TM9YBvyC84ZxE3rgfefxUWiQKLilstD6k7PTGt6wfbtXF8ixIJLOL3VYyV/z+ZiPLsVxAsKAFVwWlWeb2Y8Yyw==", + "license": "MIT" + }, "node_modules/lodash.flatten": { "version": "4.4.0", "resolved": "https://mirrors.huaweicloud.com/repository/npm/lodash.flatten/-/lodash.flatten-4.4.0.tgz", "integrity": "sha512-C5N2Z3DgnnKr0LOpv/hKCgKdb7ZZwafIrsesve6lmzvZIRZRGaZ/l6Q8+2W7NaT+ZwO3fFlSCzCzrDCFdJfZ4g==", "license": "MIT" }, + "node_modules/lodash.groupby": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/lodash.groupby/-/lodash.groupby-4.6.0.tgz", + "integrity": "sha512-5dcWxm23+VAoz+awKmBaiBvzox8+RqMgFhi7UvX9DHZr2HdxHXM/Wrf8cfKpsW37RNrvtPn6hSwNqurSILbmJw==", + "license": "MIT" + }, "node_modules/lodash.includes": { "version": "4.3.0", "resolved": "https://mirrors.huaweicloud.com/repository/npm/lodash.includes/-/lodash.includes-4.3.0.tgz", @@ -9599,6 +10195,13 @@ "dev": true, "license": "MIT" }, + "node_modules/lodash.isequal": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/lodash.isequal/-/lodash.isequal-4.5.0.tgz", + "integrity": "sha512-pDo3lu8Jhfjqls6GkMgpahsF9kCyayhgykjyLMNFTKWrpVdAQtYyB4muAMWozBB4ig/dtWAmsMxLEI8wuz+DYQ==", + "deprecated": "This package is deprecated. Use require('node:util').isDeepStrictEqual instead.", + "license": "MIT" + }, "node_modules/lodash.isfunction": { "version": "3.0.9", "resolved": "https://mirrors.huaweicloud.com/repository/npm/lodash.isfunction/-/lodash.isfunction-3.0.9.tgz", @@ -9611,6 +10214,12 @@ "integrity": "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA==", "license": "MIT" }, + "node_modules/lodash.isnil": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/lodash.isnil/-/lodash.isnil-4.0.0.tgz", + "integrity": "sha512-up2Mzq3545mwVnMhTDMdfoG1OurpA/s5t88JmQX809eH3C8491iu2sfKhTfhQtKY78oPNhiaHJUpT/dUDAAtng==", + "license": "MIT" + }, "node_modules/lodash.isnumber": { "version": "3.0.3", "resolved": "https://mirrors.huaweicloud.com/repository/npm/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz", @@ -9636,6 +10245,12 @@ "integrity": "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw==", "license": "MIT" }, + "node_modules/lodash.isundefined": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/lodash.isundefined/-/lodash.isundefined-3.0.1.tgz", + "integrity": "sha512-MXB1is3s899/cD8jheYYE2V9qTHwKvt+npCwpD+1Sxm3Q3cECXCiYHjeHWXNwr6Q0SOBPrYUDxendrO6goVTEA==", + "license": "MIT" + }, "node_modules/lodash.merge": { "version": "4.6.2", "resolved": "https://mirrors.huaweicloud.com/repository/npm/lodash.merge/-/lodash.merge-4.6.2.tgz", @@ -9655,6 +10270,18 @@ "integrity": "sha512-4hNPN5jlm/N/HLMCO43v8BXKq9Z7QdAGc/VGrRD61w8gN9g/6jF9A4L1pbUgBLCffi0w9VsXfTOij5x8iTyFvg==", "license": "MIT" }, + "node_modules/lodash.union": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/lodash.union/-/lodash.union-4.6.0.tgz", + "integrity": "sha512-c4pB2CdGrGdjMKYLA+XiRDO7Y0PRQbm/Gzg8qMj+QH+pFVAoTp5sBpO0odL3FjoPCGjK96p6qsP+yQoiLoOBcw==", + "license": "MIT" + }, + "node_modules/lodash.uniq": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/lodash.uniq/-/lodash.uniq-4.5.0.tgz", + "integrity": "sha512-xfBaXQd9ryd9dlSDvnvI0lvxfLJlYAZzXomUYzLKtUeOQvOP5piqAWuGtrhWeqaXK9hhoM/iyJc5AV+XfsX3HQ==", + "license": "MIT" + }, "node_modules/log-symbols": { "version": "4.1.0", "resolved": "https://mirrors.huaweicloud.com/repository/npm/log-symbols/-/log-symbols-4.1.0.tgz", @@ -10827,7 +11454,6 @@ "version": "3.0.0", "resolved": "https://mirrors.huaweicloud.com/repository/npm/normalize-path/-/normalize-path-3.0.0.tgz", "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", - "dev": true, "license": "MIT", "engines": { "node": ">=0.10.0" @@ -11278,6 +11904,12 @@ "dev": true, "license": "BlueOak-1.0.0" }, + "node_modules/pako": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz", + "integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==", + "license": "(MIT AND Zlib)" + }, "node_modules/param-case": { "version": "2.1.1", "resolved": "https://mirrors.huaweicloud.com/repository/npm/param-case/-/param-case-2.1.1.tgz", @@ -11811,7 +12443,6 @@ "version": "3.6.2", "resolved": "https://mirrors.huaweicloud.com/repository/npm/readable-stream/-/readable-stream-3.6.2.tgz", "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", - "dev": true, "license": "MIT", "dependencies": { "inherits": "^2.0.3", @@ -11822,6 +12453,15 @@ "node": ">= 6" } }, + "node_modules/readdir-glob": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/readdir-glob/-/readdir-glob-1.1.3.tgz", + "integrity": "sha512-v05I2k7xN8zXvPD9N+z/uhXPaj0sUFCe2rcWZIpBsqxfP7xXFQ0tipAd/wjj1YxWyWtUS5IDJpOG82JKt2EAVA==", + "license": "Apache-2.0", + "dependencies": { + "minimatch": "^5.1.0" + } + }, "node_modules/readdirp": { "version": "3.6.0", "resolved": "https://mirrors.huaweicloud.com/repository/npm/readdirp/-/readdirp-3.6.0.tgz", @@ -12352,6 +12992,18 @@ "node": ">=11.0.0" } }, + "node_modules/saxes": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/saxes/-/saxes-5.0.1.tgz", + "integrity": "sha512-5LBh1Tls8c9xgGjw3QrMwETmTMVk0oFgvrFSvWx62llR2hcEInrKNZ2GZCCuuy2lvWrdl5jhbpeqc5hRYKFOcw==", + "license": "ISC", + "dependencies": { + "xmlchars": "^2.2.0" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/scmp": { "version": "2.1.0", "resolved": "https://mirrors.huaweicloud.com/repository/npm/scmp/-/scmp-2.1.0.tgz", @@ -12742,6 +13394,12 @@ "node": ">= 0.4" } }, + "node_modules/setimmediate": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/setimmediate/-/setimmediate-1.0.5.tgz", + "integrity": "sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA==", + "license": "MIT" + }, "node_modules/setprototypeof": { "version": "1.2.0", "resolved": "https://mirrors.huaweicloud.com/repository/npm/setprototypeof/-/setprototypeof-1.2.0.tgz", @@ -13013,6 +13671,18 @@ "node": ">= 0.6" } }, + "node_modules/ssf": { + "version": "0.11.2", + "resolved": "https://registry.npmjs.org/ssf/-/ssf-0.11.2.tgz", + "integrity": "sha512-+idbmIXoYET47hH+d7dfm2epdOMUDjqcB4648sTZ+t2JwoyBFL/insLfB/racrDmsKB3diwsDA696pZMieAC5g==", + "license": "Apache-2.0", + "dependencies": { + "frac": "~1.1.2" + }, + "engines": { + "node": ">=0.8" + } + }, "node_modules/sshpk": { "version": "1.18.0", "resolved": "https://mirrors.huaweicloud.com/repository/npm/sshpk/-/sshpk-1.18.0.tgz", @@ -13118,7 +13788,6 @@ "version": "1.3.0", "resolved": "https://mirrors.huaweicloud.com/repository/npm/string_decoder/-/string_decoder-1.3.0.tgz", "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", - "dev": true, "license": "MIT", "dependencies": { "safe-buffer": "~5.2.0" @@ -13507,6 +14176,22 @@ "node": ">=8.0.0" } }, + "node_modules/tar-stream": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz", + "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==", + "license": "MIT", + "dependencies": { + "bl": "^4.0.3", + "end-of-stream": "^1.4.1", + "fs-constants": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^3.1.1" + }, + "engines": { + "node": ">=6" + } + }, "node_modules/tcomb": { "version": "3.2.29", "resolved": "https://mirrors.huaweicloud.com/repository/npm/tcomb/-/tcomb-3.2.29.tgz", @@ -13718,6 +14403,15 @@ "upper-case": "^1.0.3" } }, + "node_modules/tmp": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.5.tgz", + "integrity": "sha512-voyz6MApa1rQGUxT3E+BK7/ROe8itEx7vD8/HEvt4xwXucvQ5G5oeEiHkmHZJuBO21RpOf+YYm9MOivj709jow==", + "license": "MIT", + "engines": { + "node": ">=14.14" + } + }, "node_modules/to-regex-range": { "version": "5.0.1", "resolved": "https://mirrors.huaweicloud.com/repository/npm/to-regex-range/-/to-regex-range-5.0.1.tgz", @@ -13758,6 +14452,15 @@ "node": ">=0.8" } }, + "node_modules/traverse": { + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/traverse/-/traverse-0.3.9.tgz", + "integrity": "sha512-iawgk0hLP3SxGKDfnDJf8wTz4p2qImnyihM5Hh/sGvQ3K37dPi/w8sRhdNIxYA1TwFwc5mDhIJq+O0RsvXBKdQ==", + "license": "MIT/X11", + "engines": { + "node": "*" + } + }, "node_modules/ts-api-utils": { "version": "1.4.3", "resolved": "https://mirrors.huaweicloud.com/repository/npm/ts-api-utils/-/ts-api-utils-1.4.3.tgz", @@ -14107,6 +14810,66 @@ "node": ">= 0.8" } }, + "node_modules/unzipper": { + "version": "0.10.14", + "resolved": "https://registry.npmjs.org/unzipper/-/unzipper-0.10.14.tgz", + "integrity": "sha512-ti4wZj+0bQTiX2KmKWuwj7lhV+2n//uXEotUmGuQqrbVZSEGFMbI68+c6JCQ8aAmUWYvtHEz2A8K6wXvueR/6g==", + "license": "MIT", + "dependencies": { + "big-integer": "^1.6.17", + "binary": "~0.3.0", + "bluebird": "~3.4.1", + "buffer-indexof-polyfill": "~1.0.0", + "duplexer2": "~0.1.4", + "fstream": "^1.0.12", + "graceful-fs": "^4.2.2", + "listenercount": "~1.0.1", + "readable-stream": "~2.3.6", + "setimmediate": "~1.0.4" + } + }, + "node_modules/unzipper/node_modules/bluebird": { + "version": "3.4.7", + "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.4.7.tgz", + "integrity": "sha512-iD3898SR7sWVRHbiQv+sHUtHnMvC1o3nW5rAcqnq3uOn07DSAppZYUkIGslDz6gXC7HfunPe7YVBgoEJASPcHA==", + "license": "MIT" + }, + "node_modules/unzipper/node_modules/isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", + "license": "MIT" + }, + "node_modules/unzipper/node_modules/readable-stream": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz", + "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", + "license": "MIT", + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/unzipper/node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "license": "MIT" + }, + "node_modules/unzipper/node_modules/string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, "node_modules/update-browserslist-db": { "version": "1.1.4", "resolved": "https://mirrors.huaweicloud.com/repository/npm/update-browserslist-db/-/update-browserslist-db-1.1.4.tgz", @@ -14585,6 +15348,24 @@ "@types/node": "*" } }, + "node_modules/wmf": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wmf/-/wmf-1.0.2.tgz", + "integrity": "sha512-/p9K7bEh0Dj6WbXg4JG0xvLQmIadrner1bi45VMJTfnbVHsc7yIajZyoSoK60/dtVBs12Fm6WkUI5/3WAVsNMw==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.8" + } + }, + "node_modules/word": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/word/-/word-0.3.0.tgz", + "integrity": "sha512-OELeY0Q61OXpdUfTp+oweA/vtLVg5VDOXh+3he3PNzLGG/y0oylSOC1xRVj0+l4vQ3tj/bB1HVHv1ocXkQceFA==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.8" + } + }, "node_modules/word-wrap": { "version": "1.2.5", "resolved": "https://mirrors.huaweicloud.com/repository/npm/word-wrap/-/word-wrap-1.2.5.tgz", @@ -14772,6 +15553,27 @@ "get-ready": "~1.0.0" } }, + "node_modules/xlsx": { + "version": "0.18.5", + "resolved": "https://registry.npmjs.org/xlsx/-/xlsx-0.18.5.tgz", + "integrity": "sha512-dmg3LCjBPHZnQp5/F/+nnTa+miPJxUXB6vtk42YjBBKayDNagxGEeIdWApkYPOf3Z3pm3k62Knjzp7lMeTEtFQ==", + "license": "Apache-2.0", + "dependencies": { + "adler-32": "~1.3.0", + "cfb": "~1.2.1", + "codepage": "~1.15.0", + "crc-32": "~1.2.1", + "ssf": "~0.11.2", + "wmf": "~1.0.1", + "word": "~0.3.0" + }, + "bin": { + "xlsx": "bin/xlsx.njs" + }, + "engines": { + "node": ">=0.8" + } + }, "node_modules/xml-crypto": { "version": "6.1.2", "resolved": "https://mirrors.cloud.tencent.com/npm/xml-crypto/-/xml-crypto-6.1.2.tgz", @@ -14786,6 +15588,12 @@ "node": ">=16" } }, + "node_modules/xmlchars": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz", + "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", + "license": "MIT" + }, "node_modules/xpath": { "version": "0.0.33", "resolved": "https://mirrors.cloud.tencent.com/npm/xpath/-/xpath-0.0.33.tgz", @@ -14927,6 +15735,84 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/zip-stream": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/zip-stream/-/zip-stream-4.1.1.tgz", + "integrity": "sha512-9qv4rlDiopXg4E69k+vMHjNN63YFMe9sZMrdlvKnCjlCRWeCBswPPMPUfx+ipsAWq1LXHe70RcbaHdJJpS6hyQ==", + "license": "MIT", + "dependencies": { + "archiver-utils": "^3.0.4", + "compress-commons": "^4.1.2", + "readable-stream": "^3.6.0" + }, + "engines": { + "node": ">= 10" + } + }, + "node_modules/zip-stream/node_modules/archiver-utils": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/archiver-utils/-/archiver-utils-3.0.4.tgz", + "integrity": "sha512-KVgf4XQVrTjhyWmx6cte4RxonPLR9onExufI1jhvw/MQ4BB6IsZD5gT8Lq+u/+pRkWna/6JoHpiQioaqFP5Rzw==", + "license": "MIT", + "dependencies": { + "glob": "^7.2.3", + "graceful-fs": "^4.2.0", + "lazystream": "^1.0.0", + "lodash.defaults": "^4.2.0", + "lodash.difference": "^4.5.0", + "lodash.flatten": "^4.4.0", + "lodash.isplainobject": "^4.0.6", + "lodash.union": "^4.6.0", + "normalize-path": "^3.0.0", + "readable-stream": "^3.6.0" + }, + "engines": { + "node": ">= 10" + } + }, + "node_modules/zip-stream/node_modules/brace-expansion": { + "version": "1.1.13", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.13.tgz", + "integrity": "sha512-9ZLprWS6EENmhEOpjCYW2c8VkmOvckIJZfkr7rBW6dObmfgJ/L1GpSYW5Hpo9lDz4D1+n0Ckz8rU7FwHDQiG/w==", + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/zip-stream/node_modules/glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me", + "license": "ISC", + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/zip-stream/node_modules/minimatch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, "node_modules/zlogger": { "version": "1.1.0", "resolved": "https://mirrors.huaweicloud.com/repository/npm/zlogger/-/zlogger-1.1.0.tgz", diff --git a/package.json b/package.json index 2129eed..be8a5c9 100644 --- a/package.json +++ b/package.json @@ -20,12 +20,14 @@ "egg-sequelize": "^6.0.0", "egg-view-ejs": "^3.0.0", "ejs": "^5.0.1", + "exceljs": "^4.4.0", "fast-xml-parser": "^5.3.1", "mysql2": "^3.15.3", "path": "^0.12.7", "qiniu-js": "^3.4.3", "soap": "^1.8.0", - "spark-md5": "^3.0.2" + "spark-md5": "^3.0.2", + "xlsx": "^0.18.5" }, "devDependencies": { "egg-bin": "6", @@ -64,6 +66,7 @@ "test:local": "egg-bin test", "cov": "egg-bin cov", "lint": "eslint .", + "permission:sync:system-api": "node ./script/sync-system-api-permission.cjs", "check:model-boundary": "node ./script/model-boundary-check.cjs", "ci": "npm run lint && npm run check:model-boundary && npm run cov" }, diff --git a/script/backfill-role-permissions.cjs b/script/backfill-role-permissions.cjs new file mode 100644 index 0000000..1a37157 --- /dev/null +++ b/script/backfill-role-permissions.cjs @@ -0,0 +1,224 @@ +const fs = require('fs'); +const path = require('path'); +const mysql = require('mysql2/promise'); + +const ROOT = process.cwd(); +const DEFAULT_CONFIG_PATH = path.join(ROOT, 'config', 'config.local.js'); + +function parseArgs(argv) { + const args = { + dryRun: false, + dbClient: 'wms', + configPath: DEFAULT_CONFIG_PATH, + }; + + for (const item of argv) { + if (item === '--dry-run') { + args.dryRun = true; + continue; + } + + if (item.startsWith('--db-client=')) { + args.dbClient = String(item.split('=')[1] || '').trim() || 'wms'; + continue; + } + + if (item.startsWith('--config-path=')) { + const raw = String(item.split('=')[1] || '').trim(); + args.configPath = path.resolve(ROOT, raw); + continue; + } + } + + return args; +} + +function loadConfig(configPath) { + if (!fs.existsSync(configPath)) { + throw new Error(`Config file not found: ${configPath}`); + } + + const configFactory = require(configPath); + return typeof configFactory === 'function' + ? configFactory({ name: 'wms-role-permissions-backfill' }) + : configFactory; +} + +function normalizeRolePermissions(rawValue) { + if (rawValue === undefined || rawValue === null) { + return { allAccess: false, permissionIds: [] }; + } + + if (Array.isArray(rawValue)) { + const normalizedItems = rawValue.map(item => (typeof item === 'string' ? item.trim() : item)); + if (normalizedItems.some(item => item === '*')) { + return { allAccess: true, permissionIds: [] }; + } + + const permissionIds = normalizedItems + .map(item => Number(item)) + .filter(item => Number.isFinite(item) && item > 0) + .map(item => Math.floor(item)); + + return { + allAccess: false, + permissionIds: Array.from(new Set(permissionIds)).sort((a, b) => a - b), + }; + } + + if (typeof rawValue === 'number') { + return normalizeRolePermissions([ rawValue ]); + } + + if (typeof rawValue === 'string') { + const trimmed = rawValue.trim(); + if (!trimmed) { + return { allAccess: false, permissionIds: [] }; + } + if (trimmed === '*') { + return { allAccess: true, permissionIds: [] }; + } + + try { + const parsed = JSON.parse(trimmed); + if (parsed !== rawValue) { + return normalizeRolePermissions(parsed); + } + } catch (_) { + // ignore parse failure and continue. + } + + if (trimmed.includes(',')) { + return normalizeRolePermissions(trimmed.split(',')); + } + + return normalizeRolePermissions([ trimmed ]); + } + + return { allAccess: false, permissionIds: [] }; +} + +function serializeRolePermissions(rawValue) { + const state = normalizeRolePermissions(rawValue); + return state.allAccess ? '*' : JSON.stringify(state.permissionIds); +} + +async function main() { + const args = parseArgs(process.argv.slice(2)); + const cfg = loadConfig(args.configPath); + const dbClient = cfg && cfg.mysql && cfg.mysql.clients && cfg.mysql.clients[args.dbClient]; + + if (!dbClient) { + throw new Error(`MySQL client not found in config.mysql.clients: ${args.dbClient}`); + } + + const conn = await mysql.createConnection({ + host: dbClient.host, + port: Number(dbClient.port), + user: dbClient.user, + password: dbClient.password, + database: dbClient.database, + charset: dbClient.charset || 'utf8mb4', + }); + + try { + const [ roleRows ] = await conn.query( + 'SELECT id, role_code, permissions FROM wms_role ORDER BY id ASC' + ); + const [ legacyRows ] = await conn.query( + 'SELECT role_id, permission_id FROM wms_role_permission ORDER BY role_id ASC, permission_id ASC' + ); + + const legacyMap = new Map(); + for (const row of legacyRows) { + const roleId = Number(row.role_id); + const permissionId = Number(row.permission_id); + if (!Number.isFinite(roleId) || roleId <= 0 || !Number.isFinite(permissionId) || permissionId <= 0) { + continue; + } + if (!legacyMap.has(roleId)) { + legacyMap.set(roleId, []); + } + legacyMap.get(roleId).push(permissionId); + } + + const updates = []; + for (const row of roleRows) { + const roleId = Number(row.id); + const legacyPermissionIds = Array.from(new Set((legacyMap.get(roleId) || []) + .map(item => Number(item)) + .filter(item => Number.isFinite(item) && item > 0))) + .sort((a, b) => a - b); + + if (legacyPermissionIds.length === 0) { + continue; + } + + const currentState = normalizeRolePermissions(row.permissions); + const nextValue = currentState.allAccess + ? '*' + : serializeRolePermissions([ ...currentState.permissionIds, ...legacyPermissionIds ]); + const currentValue = currentState.allAccess + ? '*' + : serializeRolePermissions(currentState.permissionIds); + + if (nextValue !== currentValue) { + updates.push({ + roleId, + roleCode: row.role_code || '', + before: row.permissions, + after: nextValue, + legacyCount: legacyPermissionIds.length, + }); + } + } + + if (args.dryRun) { + console.log('[backfill-role-permissions] dry-run summary'); + console.log(JSON.stringify({ + mode: 'dry-run', + totalRoles: roleRows.length, + legacyRelationCount: legacyRows.length, + affectedRoleCount: updates.length, + sample: updates.slice(0, 20), + }, null, 2)); + return; + } + + if (updates.length === 0) { + console.log('[backfill-role-permissions] nothing to update'); + return; + } + + await conn.beginTransaction(); + try { + for (const item of updates) { + await conn.query( + 'UPDATE wms_role SET permissions = ?, updated_at = NOW() WHERE id = ?', + [ item.after, item.roleId ] + ); + } + await conn.commit(); + } catch (error) { + await conn.rollback(); + throw error; + } + + console.log('[backfill-role-permissions] apply summary'); + console.log(JSON.stringify({ + mode: 'apply', + totalRoles: roleRows.length, + legacyRelationCount: legacyRows.length, + updatedRoleCount: updates.length, + sample: updates.slice(0, 20), + }, null, 2)); + } finally { + await conn.end(); + } +} + +main().catch(error => { + console.error('[backfill-role-permissions] failed'); + console.error(error && error.stack ? error.stack : String(error)); + process.exit(1); +}); diff --git a/script/deploy-lib.cjs b/script/deploy-lib.cjs index b724435..72af166 100644 --- a/script/deploy-lib.cjs +++ b/script/deploy-lib.cjs @@ -232,17 +232,20 @@ function pathMatchesRule(filePath, rule) { } function listDeployableFiles(config) { - const output = runCommand('git', [ 'ls-files', '--cached' ]); + const output = runCommand('git', [ 'ls-files', '--cached', '--others', '--exclude-standard' ]); const includeRules = Array.isArray(config && config.deployIncludePaths) ? config.deployIncludePaths : DEFAULT_EGG_MINIMAL_INCLUDE_PATHS; const excludeRules = Array.isArray(config && config.deployExcludePaths) ? config.deployExcludePaths : [ 'config/**' ]; - return output - .split(/\r?\n/) - .map(item => item.trim()) - .filter(Boolean) - .filter(item => !item.startsWith('.git/')) - .filter(item => includeRules.some(rule => pathMatchesRule(item, rule))) - .filter(item => !excludeRules.some(rule => pathMatchesRule(item, rule))); + return Array.from(new Set( + output + .split(/\r?\n/) + .map(item => item.trim()) + .filter(Boolean) + .filter(item => !item.startsWith('.git/')) + .filter(item => fs.existsSync(path.join(ROOT, item))) + .filter(item => includeRules.some(rule => pathMatchesRule(item, rule))) + .filter(item => !excludeRules.some(rule => pathMatchesRule(item, rule))) + )); } function buildArchive(stamp, config) { diff --git a/script/sync-system-api-permission.cjs b/script/sync-system-api-permission.cjs new file mode 100644 index 0000000..c4b3553 --- /dev/null +++ b/script/sync-system-api-permission.cjs @@ -0,0 +1,362 @@ +const fs = require('fs'); +const path = require('path'); +const mysql = require('mysql2/promise'); + +const ROOT = process.cwd(); +const DEFAULT_CONFIG_PATH = path.join(ROOT, 'config', 'config.local.js'); +const DEFAULT_METHOD_DOC_PATH = path.join(ROOT, 'methods', 'system.json'); + +function parseArgs(argv) { + const args = { + dryRun: false, + roleId: 2, + dbClient: 'wms', + configPath: DEFAULT_CONFIG_PATH, + methodDocPath: DEFAULT_METHOD_DOC_PATH, + }; + + for (const item of argv) { + if (item === '--dry-run') { + args.dryRun = true; + continue; + } + + if (item.startsWith('--role-id=')) { + args.roleId = Number(item.split('=')[1]); + continue; + } + + if (item.startsWith('--db-client=')) { + args.dbClient = String(item.split('=')[1] || '').trim() || 'wms'; + continue; + } + + if (item.startsWith('--config-path=')) { + const raw = String(item.split('=')[1] || '').trim(); + args.configPath = path.resolve(ROOT, raw); + continue; + } + + if (item.startsWith('--method-doc=')) { + const raw = String(item.split('=')[1] || '').trim(); + args.methodDocPath = path.resolve(ROOT, raw); + continue; + } + } + + if (!Number.isInteger(args.roleId) || args.roleId <= 0) { + throw new Error('Invalid --role-id, must be a positive integer.'); + } + + return args; +} + +function loadConfig(configPath) { + if (!fs.existsSync(configPath)) { + throw new Error(`Config file not found: ${configPath}`); + } + + const configFactory = require(configPath); + const config = typeof configFactory === 'function' + ? configFactory({ name: 'wms-permission-sync' }) + : configFactory; + + return config; +} + +function loadAuthRequiredMethods(methodDocPath) { + if (!fs.existsSync(methodDocPath)) { + throw new Error(`Method doc not found: ${methodDocPath}`); + } + + const json = JSON.parse(fs.readFileSync(methodDocPath, 'utf8')); + const groups = json && json.methods && Array.isArray(json.methods.groups) + ? json.methods.groups + : []; + + const methodSet = new Set(); + for (const group of groups) { + const list = group && Array.isArray(group.list) ? group.list : []; + for (const item of list) { + if (!item || !item.method || item.isNeedAuth !== true) continue; + methodSet.add(String(item.method).trim()); + } + } + + return [ ...methodSet ].sort(); +} + +function normalizeRolePermissions(rawValue) { + if (rawValue === undefined || rawValue === null) { + return { allAccess: false, permissionIds: [] }; + } + + if (Array.isArray(rawValue)) { + const normalizedItems = rawValue.map(item => (typeof item === 'string' ? item.trim() : item)); + if (normalizedItems.some(item => item === '*')) { + return { allAccess: true, permissionIds: [] }; + } + + const permissionIds = normalizedItems + .map(item => Number(item)) + .filter(item => Number.isFinite(item) && item > 0) + .map(item => Math.floor(item)); + + return { + allAccess: false, + permissionIds: Array.from(new Set(permissionIds)).sort((a, b) => a - b), + }; + } + + if (typeof rawValue === 'number') { + return normalizeRolePermissions([ rawValue ]); + } + + if (typeof rawValue === 'string') { + const trimmed = rawValue.trim(); + if (!trimmed) { + return { allAccess: false, permissionIds: [] }; + } + if (trimmed === '*') { + return { allAccess: true, permissionIds: [] }; + } + + try { + const parsed = JSON.parse(trimmed); + if (parsed !== rawValue) { + return normalizeRolePermissions(parsed); + } + } catch (_) { + // ignore parse errors and continue. + } + + if (trimmed.includes(',')) { + return normalizeRolePermissions(trimmed.split(',')); + } + + return normalizeRolePermissions([ trimmed ]); + } + + return { allAccess: false, permissionIds: [] }; +} + +function serializeRolePermissions(rawValue) { + const state = normalizeRolePermissions(rawValue); + return state.allAccess ? '*' : JSON.stringify(state.permissionIds); +} + +function buildPermissionDefaults(methodPath, templateRow) { + return { + path: methodPath, + type: 'api', + component: templateRow ? templateRow.component : null, + name: templateRow && templateRow.name ? templateRow.name : methodPath, + redirect: templateRow ? templateRow.redirect : null, + meta_title: templateRow && templateRow.meta_title ? templateRow.meta_title : `API:${methodPath}`, + meta_icon: templateRow ? templateRow.meta_icon : null, + hidden: templateRow ? Number(templateRow.hidden || 0) : 0, + always_show: templateRow ? Number(templateRow.always_show || 0) : 0, + parent_id: templateRow && templateRow.parent_id ? Number(templateRow.parent_id) : null, + sort: templateRow ? Number(templateRow.sort || 0) : 0, + status: templateRow ? Number(templateRow.status || 1) : 1, + }; +} + +async function queryPermissionTemplate(conn) { + const [ rows ] = await conn.query(` + SELECT component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, sort, status + FROM wms_permission + WHERE type = 'api' + ORDER BY id ASC + LIMIT 1 + `); + return rows[0] || null; +} + +async function queryExistingPermissions(conn, methodPaths) { + if (methodPaths.length === 0) return new Map(); + + const placeholders = methodPaths.map(() => '?').join(','); + const [ rows ] = await conn.query( + `SELECT id, path, status FROM wms_permission WHERE type = 'api' AND path IN (${placeholders})`, + methodPaths + ); + + const result = new Map(); + for (const row of rows) { + result.set(row.path, { + id: Number(row.id), + status: Number(row.status), + }); + } + return result; +} + +async function insertPermission(conn, defaults) { + const [ result ] = await conn.query( + `INSERT INTO wms_permission + (path, type, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, sort, status, created_at, update_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`, + [ + defaults.path, + defaults.type, + defaults.component, + defaults.name, + defaults.redirect, + defaults.meta_title, + defaults.meta_icon, + defaults.hidden, + defaults.always_show, + defaults.parent_id, + defaults.sort, + defaults.status, + ] + ); + + return result.insertId; +} + +async function activatePermission(conn, permissionId) { + const [ result ] = await conn.query( + 'UPDATE wms_permission SET status = 1, update_at = NOW() WHERE id = ? AND status <> 1', + [ permissionId ] + ); + return result.affectedRows > 0; +} + +async function bindRolePermission(conn, roleId, permissionId) { + const [ roleRows ] = await conn.query( + 'SELECT permissions FROM wms_role WHERE id = ? LIMIT 1', + [ roleId ] + ); + const roleRow = roleRows[0]; + if (!roleRow) { + throw new Error(`Role not found: ${roleId}`); + } + + const currentState = normalizeRolePermissions(roleRow.permissions); + + if (currentState.allAccess || currentState.permissionIds.includes(Number(permissionId))) { + return false; + } + + const nextPermissions = [ ...currentState.permissionIds, Number(permissionId) ]; + const [ result ] = await conn.query( + 'UPDATE wms_role SET permissions = ?, updated_at = NOW() WHERE id = ?', + [ serializeRolePermissions(nextPermissions), roleId ] + ); + return result.affectedRows > 0; +} + +async function main() { + const args = parseArgs(process.argv.slice(2)); + const cfg = loadConfig(args.configPath); + const dbClient = cfg && cfg.mysql && cfg.mysql.clients && cfg.mysql.clients[args.dbClient]; + + if (!dbClient) { + throw new Error(`MySQL client not found in config.mysql.clients: ${args.dbClient}`); + } + + const methodPaths = loadAuthRequiredMethods(args.methodDocPath); + if (methodPaths.length === 0) { + console.log('[sync-system-api-permission] no isNeedAuth=true methods found.'); + return; + } + + const conn = await mysql.createConnection({ + host: dbClient.host, + port: Number(dbClient.port), + user: dbClient.user, + password: dbClient.password, + database: dbClient.database, + charset: dbClient.charset || 'utf8mb4', + }); + + try { + const templateRow = await queryPermissionTemplate(conn); + const existingMap = await queryExistingPermissions(conn, methodPaths); + + const missingPaths = methodPaths.filter(item => !existingMap.has(item)); + const disabledPaths = methodPaths.filter(item => { + const row = existingMap.get(item); + return row && Number(row.status) !== 1; + }); + const created = []; + const reactivated = []; + const touchedPermissionIds = []; + + if (!args.dryRun && (missingPaths.length > 0 || disabledPaths.length > 0)) { + await conn.beginTransaction(); + try { + for (const methodPath of missingPaths) { + const defaults = buildPermissionDefaults(methodPath, templateRow); + const permissionId = await insertPermission(conn, defaults); + created.push({ methodPath, permissionId }); + touchedPermissionIds.push(permissionId); + } + + for (const methodPath of disabledPaths) { + const permissionRow = existingMap.get(methodPath); + if (!permissionRow || !permissionRow.id) { + continue; + } + + const updated = await activatePermission(conn, permissionRow.id); + if (updated) { + reactivated.push({ methodPath, permissionId: permissionRow.id }); + } + touchedPermissionIds.push(permissionRow.id); + } + + await conn.commit(); + } catch (error) { + await conn.rollback(); + throw error; + } + } + + const latestMap = args.dryRun + ? existingMap + : await queryExistingPermissions(conn, methodPaths); + + for (const methodPath of methodPaths) { + const permissionRow = latestMap.get(methodPath); + if (permissionRow && permissionRow.id) touchedPermissionIds.push(permissionRow.id); + } + + const uniquePermissionIds = [ ...new Set(touchedPermissionIds) ]; + let roleBindingCreated = 0; + + if (!args.dryRun) { + for (const permissionId of uniquePermissionIds) { + const createdBinding = await bindRolePermission(conn, args.roleId, permissionId); + if (createdBinding) roleBindingCreated++; + } + } + + const summary = { + mode: args.dryRun ? 'dry-run' : 'apply', + roleId: args.roleId, + totalAuthMethods: methodPaths.length, + existingPermissionCount: existingMap.size, + missingPermissionCount: missingPaths.length, + disabledPermissionCount: disabledPaths.length, + createdPermissionCount: created.length, + reactivatedPermissionCount: reactivated.length, + roleBindingCreated, + sampleMissing: missingPaths.slice(0, 20), + sampleDisabled: disabledPaths.slice(0, 20), + }; + + console.log('[sync-system-api-permission] summary'); + console.log(JSON.stringify(summary, null, 2)); + } finally { + await conn.end(); + } +} + +main().catch(error => { + console.error('[sync-system-api-permission] failed'); + console.error(error && error.stack ? error.stack : String(error)); + process.exit(1); +}); diff --git a/stock.todo b/stock.todo deleted file mode 100644 index 658f66d..0000000 --- a/stock.todo +++ /dev/null @@ -1,112 +0,0 @@ -# stock.todo - -## 任务目标 -- 提取 `app/service/systemMethods/stock/warehouse.js` 迁移前 method 的历史测试请求记录。 -- 精简并保留新接口(`stock.warehouse.*`)的测试入口。 -- 根据输入/输出补全 `warehouse.js` 方法头注释和 API 文档 `description`。 - -## 迁移方法映射(旧 -> 新) -- `stock.stockWarehouse` -> `stock.warehouse.list` -- `stock.getProhibitedType` -> `stock.warehouse.getProhibitedType` -- `stock.getInfo` -> `stock.warehouse.getInfo` -- `stock.saveWarehouseStock` -> `stock.warehouse.saveWarehouseStock` -- `stock.createWarehouseStock` -> `stock.warehouse.createWarehouseStock` -- `stock.getBarcodes` -> `stock.warehouse.getBarcodes` -- `stock.saveWarehouseStockBarcode` -> `stock.warehouse.saveWarehouseStockBarcode` -- `stock.getStoreStocks` -> `stock.warehouse.getStoreStocks` -- `stock.bindItem` -> `stock.warehouse.bindItem` -- `stock.unbindItem` -> `stock.warehouse.unbindItem` -- `stock.checkItemCodeUnique` -> `stock.warehouse.checkItemCodeUnique` -- `stock.queryStockLogs` -> `stock.warehouse.queryStockLogs` -- `stock.handleBatchDelete` -> `stock.warehouse.handleBatchDelete` -- `stock.deleteUnit` -> `stock.warehouse.deleteUnit` -- `stock.deleteProhibited` -> `stock.warehouse.deleteProhibited` -- `stock.handleBatchChange` -> `stock.warehouse.handleBatchChange` -- `stock.getStockUnits` -> `stock.warehouse.getStockUnits` -- `stock.getUnitList` -> `stock.warehouse.getUnitList` -- `stock.createProhibited` -> `stock.warehouse.createProhibited` -- `stock.createUnit` -> `stock.warehouse.createUnit` -- `stock.search` -> `stock.warehouse.search` - -## 历史测试请求记录提取(迁移前/过渡期) -来源:`node_modules/.mochawesome-reports/mochawesome.json`(2026-03-25) - -### 记录1:新列表接口请求 -- case: `system.stock.warehouse.namespaced.test.js` -- method: `stock.warehouse.list` -- request: -```json -{ - "pagination": { "page": 1, "pageSize": 5 }, - "where": {} -} -``` -- expected: -```json -{ - "httpStatus": 200, - "flag": "success", - "code": 200, - "data": { - "list": "Array", - "pagination": "Object" - } -} -``` - -### 记录2:旧入口退场验证请求(历史) -- case: `system.stock.warehouse.namespaced.test.js`(精简前) -- method: `stock.stockWarehouse` -- request: -```json -{ - "pagination": { "page": 1, "pageSize": 5 }, - "where": {} -} -``` -- expected: -```json -{ - "httpStatus": 500, - "flag": "failure", - "code": 500, - "message": "方法 stockWarehouse 不存在" -} -``` - -### 记录3:where 条件解析服务级样本 -来源:`test/app/service/systems/stock_store.stockWarehouse.conditions.test.js` -- input: -```json -{ - "where": { - "item_code": { "operator": "like", "value": "SKU" }, - "barcode": { "operator": "like", "value": "BC" }, - "prohibited_type": { "operator": "eq", "value": 2 }, - "quantity": { "operator": "ge", "type": "number", "value": "2" } - }, - "pagination": { "page": 1, "pageSize": 10 }, - "sort": { "sortField": "quantity", "sortOrder": "ASC" } -} -``` -- expected: -```json -{ - "code": 200, - "message": "查询成功", - "data.pagination.page": 1, - "data.pagination.pageSize": 10, - "data.queryInfo.hasBarcodeSearch": true -} -``` - -## 新接口精简测试方案 -- 保留:`test/app/controller/system.stock.warehouse.namespaced.test.js` -- 用例:只验证 `stock.warehouse.list` 请求成功与核心返回结构。 -- 下沉:复杂 where/operator 组合继续由 service 级测试覆盖。 - -## 执行结果 -- [x] `warehouse.js` 方法头注释补充(输入/输出声明) -- [x] 新接口测试用例精简 -- [x] `methods/system.json` 的 `stock.warehouse.*` description 语义化更新(21项) -- [x] 回归测试复跑并记录结果(`8 passing`) diff --git a/test/app/controller/gateway.user.bindAccountByTempCode.test.js b/test/app/controller/gateway.user.bindAccountByTempCode.test.js index 36246ef..64ed022 100644 --- a/test/app/controller/gateway.user.bindAccountByTempCode.test.js +++ b/test/app/controller/gateway.user.bindAccountByTempCode.test.js @@ -10,23 +10,49 @@ const { const YE4S_TEST_USER_ID = Number(process.env.SYSTEM_TEST_YE4S_USER_ID || 28); describe('test/app/controller/gateway.user.bindAccountByTempCode.test.js', () => { - it('should bind, unbind, and bind again for ye4s user', async () => { + it('should scan, bind, unbind, and bind again for ye4s user', async () => { const { token } = await getAuthToken(); + const ensurePendingCode = async () => { + let bindCodeRes = await invokeSystemMethod('user.getBindWechatCode', {}, token); + assert.equal(bindCodeRes.status, 200); + assert.equal(bindCodeRes.body.flag, 'success'); + + if (bindCodeRes.body?.data?.status === 'bound') { + const unbindFirst = await invokeSystemMethod('user.unbindWechat', {}, token); + assert.equal(unbindFirst.status, 200); + assert.equal(unbindFirst.body.flag, 'success'); + bindCodeRes = await invokeSystemMethod('user.getBindWechatCode', {}, token); + assert.equal(bindCodeRes.status, 200); + assert.equal(bindCodeRes.body.flag, 'success'); + } + + const nextCode = String(bindCodeRes.body?.data?.code || ''); + assert.match(nextCode, /^(?=.*[A-Z])(?=.*\d)[A-Z\d]{6}$/); + return nextCode; + }; + const infoRes = await invokeSystemMethod('user.info', {}, token); assert.equal(infoRes.status, 200); assert.equal(infoRes.body.flag, 'success'); const accountId = Number(infoRes.body?.data?.id); assert.ok(Number.isFinite(accountId) && accountId > 0); - const bindCodeRes = await invokeSystemMethod('user.getBindWechatCode', { - forceRefresh: true, - init: true, - }, token); - assert.equal(bindCodeRes.status, 200); - assert.equal(bindCodeRes.body.flag, 'success'); - const code = String(bindCodeRes.body?.data?.code || ''); - assert.ok(code.length > 10); + const code = await ensurePendingCode(); + + const scanRes1 = await invokeGatewayMethod('user.getUserByTempCode', { code }); + assert.equal(scanRes1.status, 200); + assert.equal(scanRes1.body.flag, 'success'); + assert.equal(scanRes1.body.code, 200); + assert.equal(Number(scanRes1.body?.data?.account_id), accountId); + assert.ok(String(scanRes1.body?.data?.real_name || '')); + assert.equal(scanRes1.body?.data?.status, 'scanned'); + + const scannedStateRes1 = await invokeSystemMethod('user.getBindWechatCode', {}, token); + assert.equal(scannedStateRes1.status, 200); + assert.equal(scannedStateRes1.body.flag, 'success'); + assert.equal(scannedStateRes1.body?.data?.status, 'scanned'); + assert.equal(String(scannedStateRes1.body?.data?.code || ''), code); const bindRes1 = await invokeGatewayMethod('user.bindAccountByTempCode', { code, @@ -46,8 +72,18 @@ describe('test/app/controller/gateway.user.bindAccountByTempCode.test.js', () => assert.equal(unbindRes.body?.data?.status, 'unbound'); assert.equal(Number(unbindRes.body?.data?.account_id), accountId); + const code2 = await ensurePendingCode(); + + const scanRes2 = await invokeGatewayMethod('user.getUserByTempCode', { code: code2 }); + assert.equal(scanRes2.status, 200); + assert.equal(scanRes2.body.flag, 'success'); + assert.equal(scanRes2.body.code, 200); + assert.equal(Number(scanRes2.body?.data?.account_id), accountId); + assert.ok(String(scanRes2.body?.data?.real_name || '')); + assert.equal(scanRes2.body?.data?.status, 'scanned'); + const bindRes2 = await invokeGatewayMethod('user.bindAccountByTempCode', { - code, + code: code2, ye4s_user_id: YE4S_TEST_USER_ID, }); assert.equal(bindRes2.status, 200); @@ -57,11 +93,10 @@ describe('test/app/controller/gateway.user.bindAccountByTempCode.test.js', () => assert.equal(Number(bindRes2.body?.data?.ye4s_user_id), YE4S_TEST_USER_ID); assert.equal(bindRes2.body?.data?.status, 'bound'); - const verifyRes = await invokeGatewayMethod('user.getUserByTempCode', { code }); - assert.equal(verifyRes.status, 200); - assert.equal(verifyRes.body.flag, 'success'); - assert.equal(verifyRes.body.code, 200); - assert.equal(Number(verifyRes.body?.data?.account_id), accountId); - assert.equal(verifyRes.body?.data?.status, 'bound'); + const boundStateRes = await invokeSystemMethod('user.getBindWechatCode', {}, token); + assert.equal(boundStateRes.status, 200); + assert.equal(boundStateRes.body.flag, 'success'); + assert.equal(boundStateRes.body?.data?.status, 'bound'); + assert.equal(String(boundStateRes.body?.data?.code || ''), ''); }); }); diff --git a/test/app/controller/system.setting.account.getBindWechatCode.test.js b/test/app/controller/system.setting.account.getBindWechatCode.test.js new file mode 100644 index 0000000..c5b34ee --- /dev/null +++ b/test/app/controller/system.setting.account.getBindWechatCode.test.js @@ -0,0 +1,195 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const { + getAuthToken, + invokeSystemMethod, + invokeGatewayMethod, +} = require('../../support/system_method_client'); + +const YE4S_TEST_USER_ID = Number(process.env.SYSTEM_TEST_YE4S_USER_ID || 28); + +const EXTRA_HEADERS = { + platform: 'web', + project: 'all', +}; + +function buildTempPhone() { + return `139${String(Date.now()).slice(-8)}`; +} + +function flattenRoleIds(roleNodes, collector = []) { + if (!Array.isArray(roleNodes)) { + return collector; + } + for (const item of roleNodes) { + const roleId = Number(item && item.role_id); + if (Number.isFinite(roleId) && roleId > 0) { + collector.push(roleId); + } + flattenRoleIds(item && item.children, collector); + } + return collector; +} + +describe('test/app/controller/system.setting.account.getBindWechatCode.test.js', () => { + let token = ''; + let tempEmployeeId = 0; + let tempAccountId = 0; + + async function getAssignableRoleIds() { + const res = await invokeSystemMethod('setting.role.list', { + includeDisabled: false, + }, token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + assert.equal(res.body.code, 200); + + const roleIds = Array.from(new Set(flattenRoleIds(res.body?.data?.roles || []))); + assert.ok(roleIds.length > 0, '当前账号没有可分配角色,无法创建测试账号'); + return [ roleIds[0] ]; + } + + before(async () => { + const auth = await getAuthToken(); + token = auth.token; + + const roleIds = await getAssignableRoleIds(); + const addRes = await invokeSystemMethod('setting.account.add', { + phone: buildTempPhone(), + username: `autotest_bind_wechat_${Date.now()}`, + password: '111111', + real_name: `微信代绑测试_${Date.now()}`, + ids: roleIds, + }, token, EXTRA_HEADERS); + + assert.equal(addRes.status, 200); + assert.equal(addRes.body.flag, 'success'); + assert.equal(addRes.body.code, 200); + + tempEmployeeId = Number(addRes.body?.data?.employee_id || 0); + tempAccountId = Number(addRes.body?.data?.account_id || 0); + assert.ok(tempEmployeeId > 0); + assert.ok(tempAccountId > 0); + }); + + after(async () => { + if (!token || !tempEmployeeId) { + return; + } + + const deleteRes = await invokeSystemMethod('setting.account.delete', { + employee_id: tempEmployeeId, + }, token, EXTRA_HEADERS); + + assert.equal(deleteRes.status, 200); + assert.equal(deleteRes.body.code, 200); + }); + + it('should get bind wechat code for an operable account by user_id', async () => { + const res = await invokeSystemMethod('setting.account.getBindWechatCode', { + user_id: tempAccountId, + }, token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + assert.equal(res.body.code, 200); + assert.equal(Number(res.body?.data?.account_id || 0), tempAccountId); + assert.equal(res.body?.data?.status, 'pending'); + assert.equal(res.body?.data?.is_bound, false); + assert.match(String(res.body?.data?.code || ''), /^(?=.*[A-Z])(?=.*\d)[A-Z\d]{6}$/); + assert.ok(Number(res.body?.data?.expire_after_ms || 0) > 0); + }); + + it('should include wechat bind status in setting.account.list rows', async () => { + const res = await invokeSystemMethod('setting.account.list', { + where: { + account_id: tempAccountId, + }, + }, token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + assert.equal(res.body.code, 200); + + const list = Array.isArray(res.body?.data) ? res.body.data : []; + const target = list.find(item => Number(item && item.account_id) === tempAccountId); + assert.ok(target, '新建账号未出现在列表中'); + assert.equal(typeof target.is_wechat_bound, 'boolean'); + assert.equal(target.is_wechat_bound, false); + assert.equal(target.ye4s_user_id, null); + }); + + it('should unbind wechat for an operable account', async () => { + const bindCodeRes = await invokeSystemMethod('setting.account.getBindWechatCode', { + user_id: tempAccountId, + }, token, EXTRA_HEADERS); + + assert.equal(bindCodeRes.status, 200); + assert.equal(bindCodeRes.body.flag, 'success'); + const code = String(bindCodeRes.body?.data?.code || ''); + assert.match(code, /^(?=.*[A-Z])(?=.*\d)[A-Z\d]{6}$/); + + const scanRes = await invokeGatewayMethod('user.getUserByTempCode', { + code, + }); + assert.equal(scanRes.status, 200); + assert.equal(scanRes.body.flag, 'success'); + assert.equal(scanRes.body.code, 200); + assert.equal(Number(scanRes.body?.data?.account_id || 0), tempAccountId); + assert.equal(scanRes.body?.data?.status, 'scanned'); + + const bindRes = await invokeGatewayMethod('user.bindAccountByTempCode', { + code, + ye4s_user_id: YE4S_TEST_USER_ID, + }); + assert.equal(bindRes.status, 200); + assert.equal(bindRes.body.flag, 'success'); + assert.equal(bindRes.body.code, 200); + assert.equal(Number(bindRes.body?.data?.account_id || 0), tempAccountId); + + const unbindRes = await invokeSystemMethod('setting.account.unbindWechat', { + user_id: tempAccountId, + }, token, EXTRA_HEADERS); + + assert.equal(unbindRes.status, 200); + assert.equal(unbindRes.body.flag, 'success'); + assert.equal(unbindRes.body.code, 200); + assert.equal(Number(unbindRes.body?.data?.account_id || 0), tempAccountId); + assert.equal(unbindRes.body?.data?.status, 'unbound'); + assert.ok(Number(unbindRes.body?.data?.matched_rows || 0) >= 1); + + const listRes = await invokeSystemMethod('setting.account.list', { + where: { + account_id: tempAccountId, + }, + }, token, EXTRA_HEADERS); + + assert.equal(listRes.status, 200); + assert.equal(listRes.body.flag, 'success'); + const list = Array.isArray(listRes.body?.data) ? listRes.body.data : []; + const target = list.find(item => Number(item && item.account_id) === tempAccountId); + assert.ok(target, '解绑后账号未出现在列表中'); + assert.equal(target.is_wechat_bound, false); + assert.equal(target.ye4s_user_id, null); + }); + + it('should reject when user_id is missing', async () => { + const res = await invokeSystemMethod('setting.account.getBindWechatCode', {}, token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'failure'); + assert.equal(res.body.code, 400); + assert.match(String(res.body?.message || ''), /user_id 参数不能为空/); + }); + + it('should reject unbind when user_id is missing', async () => { + const res = await invokeSystemMethod('setting.account.unbindWechat', {}, token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'failure'); + assert.equal(res.body.code, 400); + assert.match(String(res.body?.message || ''), /user_id 参数不能为空/); + }); +}); \ No newline at end of file diff --git a/test/app/controller/system.setting.permission.test.js b/test/app/controller/system.setting.permission.test.js new file mode 100644 index 0000000..af6053a --- /dev/null +++ b/test/app/controller/system.setting.permission.test.js @@ -0,0 +1,343 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const { + getAuthToken, + invokeSystemMethod, +} = require('../../support/system_method_client'); + +const EXTRA_HEADERS = { + platform: 'web', + project: 'all', +}; + +describe('test/app/controller/system.setting.permission.test.js', () => { + let token = ''; + let anchorPermissionId = 0; + let createdPermissionId = 0; + + before(async () => { + const auth = await getAuthToken({ forceLogin: true }); + token = auth.token; + + const listRes = await invokeSystemMethod('setting.permission.list', {}, token, EXTRA_HEADERS); + assert.equal(listRes.status, 200); + assert.equal(listRes.body.flag, 'success'); + assert.equal(listRes.body.code, 200); + + const permissions = Array.isArray(listRes.body?.data?.permissions) ? listRes.body.data.permissions : []; + assert.ok(permissions.length > 0, '当前账号无可用权限,无法执行回归'); + anchorPermissionId = Number(permissions[0].permission_id || 0); + assert.ok(anchorPermissionId > 0, '锚点权限ID无效'); + }); + + after(async () => { + if (createdPermissionId > 0) { + await invokeSystemMethod('setting.permission.delete', { + ids: [ createdPermissionId ], + }, token, EXTRA_HEADERS); + } + }); + + it('should expose setting.role.permission as alias of setting.permission.list', async () => { + const requestData = { + type: 'api', + includeDisabled: false, + }; + + const listRes = await invokeSystemMethod('setting.permission.list', requestData, token, EXTRA_HEADERS); + const aliasRes = await invokeSystemMethod('setting.role.permission', requestData, token, EXTRA_HEADERS); + + assert.equal(listRes.status, 200); + assert.equal(aliasRes.status, 200); + assert.equal(listRes.body.flag, 'success'); + assert.equal(aliasRes.body.flag, 'success'); + assert.equal(listRes.body.code, 200); + assert.equal(aliasRes.body.code, 200); + assert.deepEqual(aliasRes.body.data, listRes.body.data); + }); + + it('should include route presentation fields in permission list response', async () => { + const suffix = Date.now(); + const path = `autotest.permission.route.${suffix}`; + let tempPermissionId = 0; + + try { + const addRes = await invokeSystemMethod('setting.permission.add', { + path, + type: 'btns', + name: `autotest_route_${suffix}`, + component: 'layout/RouteComponent', + redirect: '/autotest/redirect', + meta_title: `autotest_route_meta_${suffix}`, + meta_icon: 'Setting', + parent_id: anchorPermissionId, + hidden: 1, + always_show: 1, + status: 1, + }, token, EXTRA_HEADERS); + + assert.equal(addRes.status, 200); + assert.equal(addRes.body.flag, 'success'); + assert.equal(addRes.body.code, 200); + tempPermissionId = Number(addRes.body?.data?.permission_id || 0); + assert.ok(tempPermissionId > 0, '新增路由权限失败'); + + const listRes = await invokeSystemMethod('setting.permission.list', { + keyword: path, + includeDisabled: false, + }, token, EXTRA_HEADERS); + + assert.equal(listRes.status, 200); + assert.equal(listRes.body.flag, 'success'); + assert.equal(listRes.body.code, 200); + + const permissions = Array.isArray(listRes.body?.data?.permissions) ? listRes.body.data.permissions : []; + const target = permissions.find(item => Number(item && item.permission_id) === tempPermissionId); + assert.ok(target, '新建权限未出现在权限列表中'); + assert.equal(target.component, 'layout/RouteComponent'); + assert.equal(target.redirect, '/autotest/redirect'); + assert.equal(target.meta_icon, 'Setting'); + assert.equal(Number(target.hidden), 1); + assert.equal(Number(target.always_show), 1); + } finally { + if (tempPermissionId > 0) { + await invokeSystemMethod('setting.permission.delete', { + ids: [ tempPermissionId ], + }, token, EXTRA_HEADERS); + } + } + }); + + it('should show newly created permission in list for admin management', async () => { + const suffix = Date.now(); + const path = `autotest.permission.visible.${suffix}`; + let tempPermissionId = 0; + + try { + const addRes = await invokeSystemMethod('setting.permission.add', { + path, + type: 'btns', + name: `autotest_visible_${suffix}`, + parent_id: anchorPermissionId, + status: 1, + }, token, EXTRA_HEADERS); + + assert.equal(addRes.status, 200); + assert.equal(addRes.body.flag, 'success'); + assert.equal(addRes.body.code, 200); + tempPermissionId = Number(addRes.body?.data?.permission_id || 0); + assert.ok(tempPermissionId > 0, '新增测试权限失败'); + + const res = await invokeSystemMethod('setting.permission.list', { + includeDisabled: false, + }, token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + assert.equal(res.body.code, 200); + + const permissions = Array.isArray(res.body?.data?.permissions) ? res.body.data.permissions : []; + assert.ok(permissions.some(item => Number(item && item.permission_id) === tempPermissionId), '新建权限未出现在权限列表中'); + } finally { + if (tempPermissionId > 0) { + await invokeSystemMethod('setting.permission.delete', { + ids: [ tempPermissionId ], + }, token, EXTRA_HEADERS); + } + } + }); + + it('should reject permission update when target permission does not exist', async () => { + const updateRes = await invokeSystemMethod('setting.permission.update', { + permission_id: 999999999, + name: 'not_found_update', + }, token, EXTRA_HEADERS); + + assert.equal(updateRes.status, 200); + assert.equal(updateRes.body.flag, 'failure'); + assert.equal(Number(updateRes.body.code), 404); + assert.match(String(updateRes.body.message || ''), /权限不存在/); + }); + + it('should create then update then delete permission successfully', async () => { + const suffix = Date.now(); + const path = `autotest.permission.${suffix}`; + + const addRes = await invokeSystemMethod('setting.permission.add', { + path, + type: 'btns', + name: `autotest_add_${suffix}`, + parent_id: anchorPermissionId, + meta_title: `autotest_meta_${suffix}`, + sort: 0, + hidden: 0, + always_show: 0, + status: 1, + }, token, EXTRA_HEADERS); + + assert.equal(addRes.status, 200); + assert.equal(addRes.body.flag, 'success'); + assert.equal(addRes.body.code, 200); + createdPermissionId = Number(addRes.body?.data?.permission_id || 0); + assert.ok(createdPermissionId > 0, '新增权限失败,permission_id 无效'); + + const updateRes = await invokeSystemMethod('setting.permission.update', { + permission_id: createdPermissionId, + name: `autotest_update_${suffix}`, + meta_title: `autotest_meta_update_${suffix}`, + status: 1, + }, token, EXTRA_HEADERS); + + assert.equal(updateRes.status, 200); + assert.equal(updateRes.body.flag, 'success'); + assert.equal(updateRes.body.code, 200); + assert.equal(Number(updateRes.body?.data?.permission_id), createdPermissionId); + + const deleteRes = await invokeSystemMethod('setting.permission.delete', { + ids: [ createdPermissionId ], + }, token, EXTRA_HEADERS); + + assert.equal(deleteRes.status, 200); + assert.equal(deleteRes.body.flag, 'success'); + assert.equal(deleteRes.body.code, 200); + const deletedIds = Array.isArray(deleteRes.body?.data?.deleted_ids) ? deleteRes.body.data.deleted_ids : []; + assert.ok(deletedIds.includes(createdPermissionId), '删除结果中未包含新建权限ID'); + + const deleteAgainRes = await invokeSystemMethod('setting.permission.delete', { + ids: [ createdPermissionId ], + }, token, EXTRA_HEADERS); + assert.equal(deleteAgainRes.status, 200); + assert.equal(deleteAgainRes.body.flag, 'success'); + assert.equal(deleteAgainRes.body.code, 200); + const alreadyDeletedIds = Array.isArray(deleteAgainRes.body?.data?.already_deleted_ids) + ? deleteAgainRes.body.data.already_deleted_ids + : []; + assert.ok(alreadyDeletedIds.includes(createdPermissionId), '二次删除未返回 already_deleted_ids'); + + createdPermissionId = 0; + }); + + it('should split deleted_ids and already_deleted_ids in mixed batch delete', async () => { + const suffix = Date.now(); + const firstPath = `autotest.permission.mixed.first.${suffix}`; + const secondPath = `autotest.permission.mixed.second.${suffix}`; + let firstPermissionId = 0; + let secondPermissionId = 0; + + try { + const addFirstRes = await invokeSystemMethod('setting.permission.add', { + path: firstPath, + type: 'btns', + name: `autotest_mixed_first_${suffix}`, + parent_id: anchorPermissionId, + status: 1, + }, token, EXTRA_HEADERS); + assert.equal(addFirstRes.status, 200); + assert.equal(addFirstRes.body.flag, 'success'); + assert.equal(addFirstRes.body.code, 200); + firstPermissionId = Number(addFirstRes.body?.data?.permission_id || 0); + assert.ok(firstPermissionId > 0, 'first permission_id 无效'); + + const addSecondRes = await invokeSystemMethod('setting.permission.add', { + path: secondPath, + type: 'btns', + name: `autotest_mixed_second_${suffix}`, + parent_id: anchorPermissionId, + status: 1, + }, token, EXTRA_HEADERS); + assert.equal(addSecondRes.status, 200); + assert.equal(addSecondRes.body.flag, 'success'); + assert.equal(addSecondRes.body.code, 200); + secondPermissionId = Number(addSecondRes.body?.data?.permission_id || 0); + assert.ok(secondPermissionId > 0, 'second permission_id 无效'); + + const preDeleteRes = await invokeSystemMethod('setting.permission.delete', { + ids: [ firstPermissionId ], + }, token, EXTRA_HEADERS); + assert.equal(preDeleteRes.status, 200); + assert.equal(preDeleteRes.body.flag, 'success'); + assert.equal(preDeleteRes.body.code, 200); + + const mixedDeleteRes = await invokeSystemMethod('setting.permission.delete', { + ids: [ firstPermissionId, secondPermissionId ], + }, token, EXTRA_HEADERS); + + assert.equal(mixedDeleteRes.status, 200); + assert.equal(mixedDeleteRes.body.flag, 'success'); + assert.equal(mixedDeleteRes.body.code, 200); + + const deletedIds = Array.isArray(mixedDeleteRes.body?.data?.deleted_ids) + ? mixedDeleteRes.body.data.deleted_ids + : []; + const alreadyDeletedIds = Array.isArray(mixedDeleteRes.body?.data?.already_deleted_ids) + ? mixedDeleteRes.body.data.already_deleted_ids + : []; + + assert.ok(deletedIds.includes(secondPermissionId), 'mixed 删除结果中缺少启用权限ID'); + assert.ok(alreadyDeletedIds.includes(firstPermissionId), 'mixed 删除结果中缺少已删除权限ID'); + + firstPermissionId = 0; + secondPermissionId = 0; + } finally { + const cleanupIds = [ firstPermissionId, secondPermissionId ].filter(id => Number(id) > 0); + if (cleanupIds.length > 0) { + await invokeSystemMethod('setting.permission.delete', { + ids: cleanupIds, + }, token, EXTRA_HEADERS); + } + } + }); + + it('should reject mixed delete when ids contain non-existent permission', async () => { + const suffix = Date.now(); + const path = `autotest.permission.mixed.outscope.${suffix}`; + let permissionId = 0; + + try { + const addRes = await invokeSystemMethod('setting.permission.add', { + path, + type: 'btns', + name: `autotest_mixed_outscope_${suffix}`, + parent_id: anchorPermissionId, + status: 1, + }, token, EXTRA_HEADERS); + + assert.equal(addRes.status, 200); + assert.equal(addRes.body.flag, 'success'); + assert.equal(addRes.body.code, 200); + permissionId = Number(addRes.body?.data?.permission_id || 0); + assert.ok(permissionId > 0, 'permission_id 无效'); + + const mixedRes = await invokeSystemMethod('setting.permission.delete', { + ids: [ permissionId, 999999999 ], + }, token, EXTRA_HEADERS); + + assert.equal(mixedRes.status, 200); + assert.equal(mixedRes.body.flag, 'failure'); + assert.equal(Number(mixedRes.body.code), 404); + assert.match(String(mixedRes.body.message || ''), /权限不存在/); + + // 失败后应保持原子性:合法权限仍可被正常删除(说明前一次未误删) + const verifyDeleteRes = await invokeSystemMethod('setting.permission.delete', { + ids: [ permissionId ], + }, token, EXTRA_HEADERS); + + assert.equal(verifyDeleteRes.status, 200); + assert.equal(verifyDeleteRes.body.flag, 'success'); + assert.equal(verifyDeleteRes.body.code, 200); + const deletedIds = Array.isArray(verifyDeleteRes.body?.data?.deleted_ids) + ? verifyDeleteRes.body.data.deleted_ids + : []; + assert.ok(deletedIds.includes(permissionId), '混入越权ID失败后,合法权限不应被提前删除'); + + permissionId = 0; + } finally { + if (permissionId > 0) { + await invokeSystemMethod('setting.permission.delete', { + ids: [ permissionId ], + }, token, EXTRA_HEADERS); + } + } + }); +}); diff --git a/test/app/controller/system.setting.role.test.js b/test/app/controller/system.setting.role.test.js new file mode 100644 index 0000000..16372b0 --- /dev/null +++ b/test/app/controller/system.setting.role.test.js @@ -0,0 +1,198 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const { + getAuthToken, + invokeSystemMethod, +} = require('../../support/system_method_client'); + +const EXTRA_HEADERS = { + platform: 'web', + project: 'all', +}; + +function findRoleNode(roleNodes, targetRoleId) { + if (!Array.isArray(roleNodes) || !Number.isFinite(Number(targetRoleId))) { + return null; + } + + for (const item of roleNodes) { + if (Number(item && item.role_id) === Number(targetRoleId)) { + return item; + } + + const childMatch = findRoleNode(item && item.children, targetRoleId); + if (childMatch) { + return childMatch; + } + } + + return null; +} + +describe('test/app/controller/system.setting.role.test.js', () => { + let token = ''; + let anchorPermissionId = 0; + let currentRoleId = 0; + const cleanupRoleIds = []; + + before(async () => { + const auth = await getAuthToken({ forceLogin: true }); + token = auth.token; + + const permissionRes = await invokeSystemMethod('setting.permission.list', { + includeDisabled: false, + }, token, EXTRA_HEADERS); + + assert.equal(permissionRes.status, 200); + assert.equal(permissionRes.body.flag, 'success'); + assert.equal(permissionRes.body.code, 200); + + const permissions = Array.isArray(permissionRes.body?.data?.permissions) + ? permissionRes.body.data.permissions + : []; + assert.ok(permissions.length > 0, '当前系统没有可用权限,无法创建测试角色'); + anchorPermissionId = Number(permissions[0].permission_id || 0); + assert.ok(anchorPermissionId > 0, '锚点权限ID无效'); + + currentRoleId = Number(permissionRes.body?.data?.role_id || 0); + assert.ok(currentRoleId > 0, '当前角色ID无效'); + }); + + after(async () => { + if (!token || cleanupRoleIds.length === 0) { + return; + } + + await invokeSystemMethod('setting.role.delete', { + ids: cleanupRoleIds, + }, token, EXTRA_HEADERS); + }); + + it('should support wildcard role permissions via ["*"]', async () => { + const suffix = Date.now(); + const wildcardAddRes = await invokeSystemMethod('setting.role.add', { + role_code: `autotest_role_all_${suffix}`, + role_name: `autotest_role_all_${suffix}`, + description: 'role wildcard regression', + pid: currentRoleId, + permission_ids: [ '*' ], + status: 1, + }, token, EXTRA_HEADERS); + + assert.equal(wildcardAddRes.status, 200); + assert.equal(wildcardAddRes.body.flag, 'success'); + assert.equal(wildcardAddRes.body.code, 200); + + const wildcardRoleId = Number(wildcardAddRes.body?.data?.role_id || 0); + assert.ok(wildcardRoleId > 0, '创建全权限角色失败'); + cleanupRoleIds.push(wildcardRoleId); + + const permissionRes = await invokeSystemMethod('setting.role.permission', { + role_id: wildcardRoleId, + includeDisabled: false, + }, token, EXTRA_HEADERS); + + assert.equal(permissionRes.status, 200); + assert.equal(permissionRes.body.flag, 'success'); + assert.equal(permissionRes.body.code, 200); + + const permissions = Array.isArray(permissionRes.body?.data?.permissions) + ? permissionRes.body.data.permissions + : []; + assert.ok(permissions.length > 0, '全权限角色应能看到权限列表'); + assert.ok(permissions.every(item => item && item.selected === true), '当 permission_ids=["*"] 时,所有权限都应为选中状态'); + + const listRes = await invokeSystemMethod('setting.role.list', { + includeDisabled: false, + includeSystem: true, + }, token, EXTRA_HEADERS); + + assert.equal(listRes.status, 200); + assert.equal(listRes.body.flag, 'success'); + assert.equal(listRes.body.code, 200); + + const roots = Array.isArray(listRes.body?.data?.roles) + ? listRes.body.data.roles + : []; + const wildcardNode = findRoleNode(roots, wildcardRoleId); + assert.ok(wildcardNode, '返回结果中未包含新建的全权限角色'); + assert.ok(Array.isArray(wildcardNode.permission_ids), '全权限角色应返回 permission_ids'); + assert.ok(wildcardNode.permission_ids.includes('*'), '全权限角色应以 ["*"] 表示拥有全部权限'); + }); + + it('should only return descendant roles and keep their children', async () => { + const suffix = Date.now(); + + const childAddRes = await invokeSystemMethod('setting.role.add', { + role_code: `autotest_role_child_${suffix}`, + role_name: `autotest_role_child_${suffix}`, + description: 'role tree child regression', + pid: currentRoleId, + permission_ids: [ anchorPermissionId ], + status: 1, + }, token, EXTRA_HEADERS); + + assert.equal(childAddRes.status, 200); + assert.equal(childAddRes.body.flag, 'success'); + assert.equal(childAddRes.body.code, 200); + + const createdChildRoleId = Number(childAddRes.body?.data?.role_id || 0); + assert.ok(createdChildRoleId > 0, '创建下级角色失败'); + cleanupRoleIds.push(createdChildRoleId); + + const grandChildAddRes = await invokeSystemMethod('setting.role.add', { + role_code: `autotest_role_grandchild_${suffix}`, + role_name: `autotest_role_grandchild_${suffix}`, + description: 'role tree grandchild regression', + pid: createdChildRoleId, + permission_ids: [ anchorPermissionId ], + status: 1, + }, token, EXTRA_HEADERS); + + assert.equal(grandChildAddRes.status, 200); + assert.equal(grandChildAddRes.body.flag, 'success'); + assert.equal(grandChildAddRes.body.code, 200); + + const createdGrandChildRoleId = Number(grandChildAddRes.body?.data?.role_id || 0); + assert.ok(createdGrandChildRoleId > 0, '创建孙级角色失败'); + cleanupRoleIds.unshift(createdGrandChildRoleId); + + const listRes = await invokeSystemMethod('setting.role.list', { + includeDisabled: false, + includeSystem: true, + }, token, EXTRA_HEADERS); + + assert.equal(listRes.status, 200); + assert.equal(listRes.body.flag, 'success'); + assert.equal(listRes.body.code, 200); + + const roots = Array.isArray(listRes.body?.data?.roles) + ? listRes.body.data.roles + : []; + assert.ok(roots.length > 0, '应返回至少一层下级角色'); + assert.ok( + roots.every(item => Number(item && item.pid) === currentRoleId), + 'setting.role.list 第一层只应返回当前角色的直接下级角色' + ); + assert.ok( + !roots.some(item => Number(item && item.role_id) === currentRoleId), + 'setting.role.list 不应返回当前角色本身' + ); + + const createdChildNode = findRoleNode(roots, createdChildRoleId); + assert.ok(createdChildNode, '返回结果中未包含新建的下级角色'); + assert.ok( + Array.isArray(createdChildNode.children) + && createdChildNode.children.some(item => Number(item && item.role_id) === createdGrandChildRoleId), + '下级角色的 children 组装异常:新建孙级角色未挂到对应父角色下' + ); + assert.ok(Array.isArray(createdChildNode.permission_ids), '下级角色节点应返回 permission_ids 权限集'); + assert.ok(createdChildNode.permission_ids.includes(anchorPermissionId), '下级角色未返回已绑定权限集'); + + const createdGrandChildNode = findRoleNode(roots, createdGrandChildRoleId); + assert.ok(createdGrandChildNode, '返回结果中未包含新建的孙级角色'); + assert.ok(Array.isArray(createdGrandChildNode.permission_ids), '孙级角色节点应返回 permission_ids 权限集'); + assert.ok(createdGrandChildNode.permission_ids.includes(anchorPermissionId), '孙级角色未返回已绑定权限集'); + }); +}); diff --git a/test/app/controller/system.setting.storeWarehouse.test.js b/test/app/controller/system.setting.storeWarehouse.test.js new file mode 100644 index 0000000..c645e65 --- /dev/null +++ b/test/app/controller/system.setting.storeWarehouse.test.js @@ -0,0 +1,413 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const { + getAuthToken, + invokeSystemMethod, +} = require('../../support/system_method_client'); + +const EXTRA_HEADERS = { + platform: 'web', + project: 'all', +}; + +describe('test/app/controller/system.setting.storeWarehouse.test.js', () => { + const METHOD_PREFIX = 'storeWarehouse.store'; + let token = ''; + let sampleRelation = null; + + before(async () => { + const auth = await getAuthToken({ forceLogin: true }); + token = auth.token; + }); + + it('should list store-warehouse contracts in current subject scope', async () => { + const res = await invokeSystemMethod(`${METHOD_PREFIX}.list`, { + page: 1, + page_size: 10, + }, token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + assert.equal(res.body.code, 200); + assert.ok(Array.isArray(res.body?.data?.list), 'list 应返回数组'); + assert.ok(res.body?.data?.current_subject, '应返回当前主体信息'); + sampleRelation = Array.isArray(res.body?.data?.list) && res.body.data.list.length > 0 + ? res.body.data.list[0] + : null; + }); + + it('should allow renaming current-side remask and reflect it in list display', async () => { + assert.ok(sampleRelation, '需要至少一条现有签约关系用于改名回归'); + + const listRes = await invokeSystemMethod(`${METHOD_PREFIX}.list`, { + page: 1, + page_size: 30, + }, token, EXTRA_HEADERS); + + assert.equal(listRes.status, 200); + assert.equal(listRes.body.flag, 'success'); + assert.equal(listRes.body.code, 200); + + const currentRole = String(listRes.body?.data?.current_subject?.role || ''); + const candidates = Array.isArray(listRes.body?.data?.list) ? listRes.body.data.list : []; + const candidate = candidates.find(item => Number(item.id) > 0); + assert.ok(candidate, '需要至少一条签约关系用于改名回归'); + + const isWarehouse = currentRole === 'warehouse'; + const originRemask = String(candidate.remask || ''); + const nextRemask = `autotest_alias_${Date.now()}`; + + try { + const renameRes = await invokeSystemMethod(`${METHOD_PREFIX}.rename`, { + id: Number(candidate.id), + remask: nextRemask, + }, token, EXTRA_HEADERS); + + assert.equal(renameRes.status, 200); + assert.equal(renameRes.body.flag, 'success'); + assert.equal(renameRes.body.code, 200); + assert.equal(String(renameRes.body?.data?.contract?.remask), nextRemask); + assert.equal( + String(isWarehouse ? renameRes.body?.data?.contract?.store_name : renameRes.body?.data?.contract?.warehouse_name), + nextRemask + ); + + const verifyRes = await invokeSystemMethod(`${METHOD_PREFIX}.list`, { + id: Number(candidate.id), + }, token, EXTRA_HEADERS); + + assert.equal(verifyRes.status, 200); + assert.equal(verifyRes.body.flag, 'success'); + assert.equal(verifyRes.body.code, 200); + + const verified = Array.isArray(verifyRes.body?.data?.list) ? verifyRes.body.data.list[0] : null; + assert.ok(verified, '改名后应能查到对应签约关系'); + assert.equal( + String(isWarehouse ? verified.store_name : verified.warehouse_name), + nextRemask + ); + } finally { + await invokeSystemMethod(`${METHOD_PREFIX}.rename`, { + id: Number(candidate.id), + remask: originRemask, + }, token, EXTRA_HEADERS); + } + }); + + it('should generate a temp code and support preview before confirmation', async () => { + assert.ok(sampleRelation, '需要至少一条现有签约关系用于临时码回归'); + + const candidateRes = await invokeSystemMethod(`${METHOD_PREFIX}.list`, { + page: 1, + page_size: 30, + }, token, EXTRA_HEADERS); + + assert.equal(candidateRes.status, 200); + assert.equal(candidateRes.body.flag, 'success'); + assert.equal(candidateRes.body.code, 200); + + const candidates = Array.isArray(candidateRes.body?.data?.list) ? candidateRes.body.data.list : []; + assert.ok(candidates.length > 0, '需要至少一条签约关系用于临时码回归'); + + let initRes = null; + for (const item of candidates) { + const attempt = await invokeSystemMethod(`${METHOD_PREFIX}.sign`, { + counterparty_id: Number(item.counterparty_id), + apply_reason: 'autotest temp sign flow', + remask: `autotest_remask_${Date.now()}`, + }, token, EXTRA_HEADERS); + + if (attempt.status === 200 && attempt.body && attempt.body.flag === 'success') { + initRes = attempt; + break; + } + } + + assert.ok(initRes, '未找到可发起临时码签约的对方主体,请确认测试账号签约数据'); + + assert.equal(initRes.status, 200); + assert.equal(initRes.body.flag, 'success'); + assert.equal(initRes.body.code, 200); + assert.equal(initRes.body?.data?.mode, 'initiate'); + assert.ok(String(initRes.body?.data?.temp_code || '').length >= 8, '发起签约后应返回临时码'); + + const previewRes = await invokeSystemMethod(`${METHOD_PREFIX}.sign`, { + temp_code: initRes.body.data.temp_code, + action: 'preview', + }, token, EXTRA_HEADERS); + + assert.equal(previewRes.status, 200); + assert.equal(previewRes.body.flag, 'success'); + assert.equal(previewRes.body.code, 200); + assert.equal(previewRes.body?.data?.mode, 'preview'); + assert.equal(String(previewRes.body?.data?.temp_code || ''), String(initRes.body?.data?.temp_code || '')); + assert.equal(Boolean(previewRes.body?.data?.can_confirm), false, '同一发起方不应直接确认自己的临时码'); + }); + + it('should only change use_status when unbinding', async () => { + assert.ok(sampleRelation, '需要至少一条现有签约关系用于解除回归'); + + const originalAuthStatus = Number(sampleRelation.auth_status || 0); + const originalUseStatus = Number(sampleRelation.use_status || 0); + const targetUseStatus = originalUseStatus === 1 ? 0 : 1; + + try { + const unbindRes = await invokeSystemMethod(`${METHOD_PREFIX}.unbind`, { + id: Number(sampleRelation.id), + use_status: targetUseStatus, + }, token, EXTRA_HEADERS); + + assert.equal(unbindRes.status, 200); + assert.equal(unbindRes.body.flag, 'success'); + assert.equal(unbindRes.body.code, 200); + assert.equal(Number(unbindRes.body?.data?.contract?.use_status), targetUseStatus); + assert.equal(Number(unbindRes.body?.data?.contract?.auth_status), originalAuthStatus, '解除接口不应改动 auth_status'); + } finally { + await invokeSystemMethod(`${METHOD_PREFIX}.unbind`, { + id: Number(sampleRelation.id), + use_status: originalUseStatus, + }, token, EXTRA_HEADERS); + } + }); + + it('should allow warehouse side to save and get policy config on a contract', async function() { + const listRes = await invokeSystemMethod(`${METHOD_PREFIX}.list`, { + page: 1, + page_size: 30, + }, token, EXTRA_HEADERS); + + assert.equal(listRes.status, 200); + assert.equal(listRes.body.flag, 'success'); + assert.equal(listRes.body.code, 200); + + const currentRole = String(listRes.body?.data?.current_subject?.role || ''); + if (currentRole !== 'warehouse') { + this.skip(); + } + + const candidates = Array.isArray(listRes.body?.data?.list) ? listRes.body.data.list : []; + const candidate = candidates.find(item => Number(item.id) > 0); + assert.ok(candidate, '需要至少一条签约关系用于策略配置回归'); + + const originalPolicyConfig = candidate.policy_config && typeof candidate.policy_config === 'object' + ? { ...candidate.policy_config } + : null; + const nextPolicyConfig = { + receive_mode: 'strict', + sku_visibility: 'whitelist', + auto_allocate_bin: 1, + allow_mix_batch: 0, + max_daily_inbound: 5000, + remark: `autotest_${Date.now()}`, + }; + + try { + const saveRes = await invokeSystemMethod(`${METHOD_PREFIX}.savePolicyConfig`, { + id: Number(candidate.id), + policy_config: nextPolicyConfig, + }, token, EXTRA_HEADERS); + + assert.equal(saveRes.status, 200); + assert.equal(saveRes.body.flag, 'success'); + assert.equal(saveRes.body.code, 200); + assert.equal(Number(saveRes.body?.data?.contract_id || 0), Number(candidate.id)); + assert.equal(String(saveRes.body?.data?.policy_config?.receive_mode || ''), 'strict'); + assert.equal(Number(saveRes.body?.data?.policy_config?.auto_allocate_bin || 0), 1); + + const getRes = await invokeSystemMethod(`${METHOD_PREFIX}.getPolicyConfig`, { + id: Number(candidate.id), + }, token, EXTRA_HEADERS); + + assert.equal(getRes.status, 200); + assert.equal(getRes.body.flag, 'success'); + assert.equal(getRes.body.code, 200); + assert.equal(Number(getRes.body?.data?.contract_id || 0), Number(candidate.id)); + assert.equal(String(getRes.body?.data?.policy_config?.sku_visibility || ''), 'whitelist'); + assert.equal(Number(getRes.body?.data?.policy_config?.max_daily_inbound || 0), 5000); + } finally { + if (originalPolicyConfig) { + await invokeSystemMethod(`${METHOD_PREFIX}.savePolicyConfig`, { + id: Number(candidate.id), + policy_config: originalPolicyConfig, + }, token, EXTRA_HEADERS); + } + } + }); + + it('should reject unsupported policy config fields on a contract', async function() { + const listRes = await invokeSystemMethod(`${METHOD_PREFIX}.list`, { + page: 1, + page_size: 30, + }, token, EXTRA_HEADERS); + + assert.equal(listRes.status, 200); + assert.equal(listRes.body.flag, 'success'); + assert.equal(listRes.body.code, 200); + + const currentRole = String(listRes.body?.data?.current_subject?.role || ''); + if (currentRole !== 'warehouse') { + this.skip(); + } + + const candidates = Array.isArray(listRes.body?.data?.list) ? listRes.body.data.list : []; + const candidate = candidates.find(item => Number(item.id) > 0); + assert.ok(candidate, '需要至少一条签约关系用于策略字段限制回归'); + + const res = await invokeSystemMethod(`${METHOD_PREFIX}.savePolicyConfig`, { + id: Number(candidate.id), + policy_config: { + receive_mode: 'strict', + unexpected_field: 'blocked', + }, + }, token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'failure'); + assert.equal(Number(res.body.code), 400); + assert.match(String(res.body.message || ''), /unexpected_field|不支持字段/); + }); + + it('should allow warehouse side to save, update and delete qimen config on a contract', async function() { + const listRes = await invokeSystemMethod(`${METHOD_PREFIX}.list`, { + page: 1, + page_size: 30, + }, token, EXTRA_HEADERS); + + assert.equal(listRes.status, 200); + assert.equal(listRes.body.flag, 'success'); + assert.equal(listRes.body.code, 200); + + const currentRole = String(listRes.body?.data?.current_subject?.role || ''); + if (currentRole !== 'warehouse') { + this.skip(); + } + + const candidates = Array.isArray(listRes.body?.data?.list) ? listRes.body.data.list : []; + const candidate = candidates.find(item => Number(item.id) > 0); + assert.ok(candidate, '需要至少一条签约关系用于奇门配置回归'); + + const originalQimenConfig = candidate.qimen_config ? { ...candidate.qimen_config } : null; + const seed = Date.now(); + const createPayload = { + id: Number(candidate.id), + app_name: `autotest_qimen_${seed}`, + qimen_app_key: `autotest_app_${seed}`, + qimen_customer_id: `autotest_customer_${seed}`, + qimen_warehouse_code: `autotest_wh_${seed}`, + contact_person: 'autotest', + contact_phone: '13800138000', + email: `autotest_${seed}@example.com`, + is_enabled: 1, + }; + + try { + const saveRes = await invokeSystemMethod(`${METHOD_PREFIX}.saveQimenConfig`, createPayload, token, EXTRA_HEADERS); + assert.equal(saveRes.status, 200); + assert.equal(saveRes.body.flag, 'success'); + assert.equal(saveRes.body.code, 200); + assert.match(String(saveRes.body?.data?.action || ''), /create|update/); + assert.equal(String(saveRes.body?.data?.qimen_config?.qimen_app_key || ''), createPayload.qimen_app_key); + assert.equal(String(saveRes.body?.data?.qimen_config?.qimen_customer_id || ''), createPayload.qimen_customer_id); + assert.equal(String(saveRes.body?.data?.qimen_config?.qimen_warehouse_code || ''), createPayload.qimen_warehouse_code); + + const updatePayload = { + ...createPayload, + app_name: `${createPayload.app_name}_updated`, + qimen_customer_id: `${createPayload.qimen_customer_id}_updated`, + qimen_warehouse_code: `${createPayload.qimen_warehouse_code}_updated`, + is_enabled: 0, + }; + const updateRes = await invokeSystemMethod(`${METHOD_PREFIX}.saveQimenConfig`, updatePayload, token, EXTRA_HEADERS); + assert.equal(updateRes.status, 200); + assert.equal(updateRes.body.flag, 'success'); + assert.equal(updateRes.body.code, 200); + assert.equal(String(updateRes.body?.data?.action || ''), 'update'); + assert.equal(String(updateRes.body?.data?.qimen_config?.qimen_customer_id || ''), updatePayload.qimen_customer_id); + assert.equal(String(updateRes.body?.data?.qimen_config?.qimen_warehouse_code || ''), updatePayload.qimen_warehouse_code); + assert.equal(Number(updateRes.body?.data?.qimen_config?.is_enabled), 0); + + const verifyRes = await invokeSystemMethod(`${METHOD_PREFIX}.list`, { + id: Number(candidate.id), + }, token, EXTRA_HEADERS); + assert.equal(verifyRes.status, 200); + assert.equal(verifyRes.body.flag, 'success'); + assert.equal(verifyRes.body.code, 200); + const verified = Array.isArray(verifyRes.body?.data?.list) ? verifyRes.body.data.list[0] : null; + assert.ok(verified, '保存奇门配置后应能查询到签约关系'); + assert.equal(String(verified?.qimen_config?.qimen_customer_id || ''), updatePayload.qimen_customer_id); + + const configListRes = await invokeSystemMethod(`${METHOD_PREFIX}.listQimenConfig`, { + id: Number(candidate.id), + }, token, EXTRA_HEADERS); + assert.equal(configListRes.status, 200); + assert.equal(configListRes.body.flag, 'success'); + assert.equal(configListRes.body.code, 200); + assert.equal(Number(configListRes.body?.data?.contract_id || 0), Number(candidate.id)); + assert.ok(Array.isArray(configListRes.body?.data?.list), '应返回奇门配置列表'); + assert.ok((configListRes.body?.data?.list || []).length >= 1, '保存后应至少返回一条奇门配置'); + assert.equal(String(configListRes.body?.data?.list?.[0]?.qimen_customer_id || ''), updatePayload.qimen_customer_id); + + const deleteRes = await invokeSystemMethod(`${METHOD_PREFIX}.deleteQimenConfig`, { + id: Number(candidate.id), + }, token, EXTRA_HEADERS); + assert.equal(deleteRes.status, 200); + assert.equal(deleteRes.body.flag, 'success'); + assert.equal(deleteRes.body.code, 200); + assert.equal(Boolean(deleteRes.body?.data?.deleted), true); + + const verifyDeleteRes = await invokeSystemMethod(`${METHOD_PREFIX}.list`, { + id: Number(candidate.id), + }, token, EXTRA_HEADERS); + assert.equal(verifyDeleteRes.status, 200); + assert.equal(verifyDeleteRes.body.flag, 'success'); + assert.equal(verifyDeleteRes.body.code, 200); + const deletedView = Array.isArray(verifyDeleteRes.body?.data?.list) ? verifyDeleteRes.body.data.list[0] : null; + assert.ok(deletedView, '删除奇门配置后仍应能查询到签约关系'); + assert.equal(deletedView?.qimen_config || null, null); + + const emptyListRes = await invokeSystemMethod(`${METHOD_PREFIX}.listQimenConfig`, { + id: Number(candidate.id), + }, token, EXTRA_HEADERS); + assert.equal(emptyListRes.status, 200); + assert.equal(emptyListRes.body.flag, 'success'); + assert.equal(emptyListRes.body.code, 200); + assert.ok(Array.isArray(emptyListRes.body?.data?.list), '删除后仍应返回列表结构'); + assert.equal(Number(emptyListRes.body?.data?.total || 0), 0); + } finally { + if (originalQimenConfig) { + await invokeSystemMethod(`${METHOD_PREFIX}.saveQimenConfig`, { + id: Number(candidate.id), + app_name: originalQimenConfig.app_name, + qimen_app_key: originalQimenConfig.qimen_app_key, + qimen_customer_id: originalQimenConfig.qimen_customer_id, + qimen_warehouse_code: originalQimenConfig.qimen_warehouse_code, + contact_person: originalQimenConfig.contact_person, + contact_phone: originalQimenConfig.contact_phone, + email: originalQimenConfig.email, + is_enabled: Number(originalQimenConfig.is_enabled || 0), + }, token, EXTRA_HEADERS); + } + } + }); + + it('should reject sign when counterparty is missing', async () => { + const res = await invokeSystemMethod(`${METHOD_PREFIX}.sign`, { + print_quantity: 0, + }, token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'failure'); + assert.equal(Number(res.body.code), 400); + assert.match(String(res.body.message || ''), /counterparty_id|store_id|warehouse_id/); + }); + + it('should reject unbind when no target relation is provided', async () => { + const res = await invokeSystemMethod(`${METHOD_PREFIX}.unbind`, {}, token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'failure'); + assert.equal(Number(res.body.code), 400); + assert.match(String(res.body.message || ''), /id|counterparty_id|store_id|warehouse_id/); + }); +}); diff --git a/test/app/controller/system.storage.receiving.test.js b/test/app/controller/system.storage.receiving.test.js index 86e49c5..cb3e94f 100644 --- a/test/app/controller/system.storage.receiving.test.js +++ b/test/app/controller/system.storage.receiving.test.js @@ -70,6 +70,52 @@ async function switchToWarehouseRole(token) { throw new Error('未找到可访问收货单的仓库角色'); } +async function getBindableStoreInfo(token) { + const res = await invokeSystemMethod('storeWarehouse.store.list', { + page: 1, + page_size: 20, + }, token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + assert.equal(res.body.code, 200); + + const list = Array.isArray(res.body?.data?.list) ? res.body.data.list : []; + const candidate = list.find(item => Number(item?.counterparty_id || item?.store_id || 0) > 0); + + if (!candidate) { + return null; + } + + return { + store_id: Number(candidate.counterparty_id || candidate.store_id || 0), + store_name: String(candidate.store_name || candidate.counterparty_name || ''), + }; +} + +async function getBindableSystemProducts(token) { + const res = await invokeSystemMethod('stock.warehouse.list', { + pagination: { + page: 1, + pageSize: 10, + }, + where: {}, + }, token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + assert.equal(res.body.code, 200); + + const payload = normalizeListPayload(res.body.data); + const list = Array.isArray(payload?.list) ? payload.list : []; + return list + .filter(item => Number(item?.id || 0) > 0) + .map(item => ({ + id: Number(item.id), + product_name: String(item.item_name || item.name || item.product_name || ''), + })); +} + describe('test/app/controller/system.storage.receiving.test.js', () => { it('should query receiving list', async () => { const { token } = await getAuthToken(); @@ -135,6 +181,192 @@ describe('test/app/controller/system.storage.receiving.test.js', () => { assert.ok(detailPayload, '返回结构中缺少收货单详情 payload'); assert.ok(detailPayload.receiving, 'receiving 字段缺失'); assert.equal(Number(detailPayload.receiving.id), Number(first.id)); + assert.ok(Array.isArray(detailPayload.receiving.details), 'receiving.details 应为数组'); + + const detailWithImages = detailPayload.receiving.details.find(item => Array.isArray(item.images) && item.images.length > 0); + if (detailWithImages) { + const firstImage = detailWithImages.images[0]; + assert.equal(typeof firstImage, 'object', '明细图片应返回对象结构'); + assert.equal(typeof firstImage.url, 'string', '明细图片应返回实际链接'); + assert.ok(firstImage.url.length > 0, '明细图片链接不能为空'); + assert.ok(!Object.prototype.hasOwnProperty.call(firstImage, 'business_type'), '不应返回 FileReference 原始字段'); + } + }); + + it('should bind store to receiving and reject rebinding when owner already exists', async function() { + const { token } = await getAuthToken(); + const switched = await switchToWarehouseRole(token); + const bindableStore = await getBindableStoreInfo(switched.token); + let createdId = 0; + + if (!bindableStore || bindableStore.store_id <= 0) { + this.skip(); + } + + try { + const createRes = await invokeSystemMethod('storage.receiving.create', { + delivery_method: 'truck', + license_plate: `ITEST-BIND-${Date.now().toString().slice(-6)}`, + loading_method: 'with_pallet', + remark: 'bind-store-regression', + total_boxes: 0, + total_pallets: 0, + }, switched.token, EXTRA_HEADERS); + + assert.equal(createRes.status, 200); + assert.equal(createRes.body.flag, 'success'); + assert.equal(createRes.body.code, 200); + createdId = Number(createRes.body.id || createRes.body?.data?.id || 0); + assert.ok(createdId > 0, '创建收货单失败,无法执行货主绑定回归'); + + const bindRes = await invokeSystemMethod('storage.receiving.bindStore', { + id: createdId, + store_id: bindableStore.store_id, + }, switched.token, EXTRA_HEADERS); + + assert.equal(bindRes.status, 200); + assert.equal(bindRes.body.flag, 'success'); + assert.equal(bindRes.body.code, 200); + assert.equal(Number(bindRes.body?.data?.store_id || 0), Number(bindableStore.store_id)); + + const repeatRes = await invokeSystemMethod('storage.receiving.bindStore', { + id: createdId, + store_id: bindableStore.store_id, + }, switched.token, EXTRA_HEADERS); + + assert.equal(repeatRes.status, 200); + assert.equal(repeatRes.body.flag, 'success'); + assert.equal(Number(repeatRes.body.code), 400); + assert.match(String(repeatRes.body.message || ''), /已绑定|重复绑定|已有货主/); + } finally { + if (createdId > 0) { + await invokeSystemMethod('storage.receiving.batchCancelReceiving', { + ids: [ createdId ], + }, switched.token, EXTRA_HEADERS); + } + } + }); + + it('should reject bindStore when receiving is cancelled', async function() { + const { token } = await getAuthToken(); + const switched = await switchToWarehouseRole(token); + const bindableStore = await getBindableStoreInfo(switched.token); + let createdId = 0; + + if (!bindableStore || bindableStore.store_id <= 0) { + this.skip(); + } + + try { + const createRes = await invokeSystemMethod('storage.receiving.create', { + delivery_method: 'truck', + license_plate: `ICB-${Date.now().toString().slice(-6)}`, + loading_method: 'with_pallet', + remark: 'bind-store-cancelled-regression', + total_boxes: 0, + total_pallets: 0, + }, switched.token, EXTRA_HEADERS); + + assert.equal(createRes.status, 200); + assert.equal(createRes.body.flag, 'success'); + assert.equal(createRes.body.code, 200); + createdId = Number(createRes.body.id || createRes.body?.data?.id || 0); + assert.ok(createdId > 0, '创建收货单失败,无法执行取消状态绑定回归'); + + const cancelRes = await invokeSystemMethod('storage.receiving.batchCancelReceiving', { + ids: [ createdId ], + }, switched.token, EXTRA_HEADERS); + assert.equal(cancelRes.status, 200); + assert.equal(cancelRes.body.flag, 'success'); + assert.ok([ 0, 200 ].includes(Number(cancelRes.body.code)), `取消收货单返回异常: ${JSON.stringify(cancelRes.body)}`); + + const bindRes = await invokeSystemMethod('storage.receiving.bindStore', { + id: createdId, + store_id: bindableStore.store_id, + }, switched.token, EXTRA_HEADERS); + + assert.equal(bindRes.status, 200); + assert.equal(bindRes.body.flag, 'success'); + assert.equal(Number(bindRes.body.code), 400); + assert.match(String(bindRes.body.message || ''), /取消|作废|不允许绑定/); + } finally { + if (createdId > 0) { + await invokeSystemMethod('storage.receiving.batchCancelReceiving', { + ids: [ createdId ], + }, switched.token, EXTRA_HEADERS); + } + } + }); + + it('should bind and rebind system product for a receiving detail', async function() { + const { token } = await getAuthToken(); + const switched = await switchToWarehouseRole(token); + const systemProducts = await getBindableSystemProducts(switched.token); + let createdId = 0; + + if (!Array.isArray(systemProducts) || systemProducts.length === 0) { + this.skip(); + } + + try { + const createRes = await invokeSystemMethod('storage.receiving.create', { + delivery_method: 'truck', + license_plate: `IDB-${Date.now().toString().slice(-6)}`, + loading_method: 'with_pallet', + remark: 'bind-detail-product-regression', + total_boxes: 0, + total_pallets: 0, + }, switched.token, EXTRA_HEADERS); + + assert.equal(createRes.status, 200); + assert.equal(createRes.body.flag, 'success'); + assert.equal(createRes.body.code, 200); + createdId = Number(createRes.body.id || createRes.body?.data?.id || 0); + assert.ok(createdId > 0, '创建收货单失败,无法执行明细绑定商品回归'); + + const addDetailRes = await invokeSystemMethod('storage.receiving.addDetail', { + receiving_id: createdId, + }, switched.token, EXTRA_HEADERS); + + assert.equal(addDetailRes.status, 200); + assert.equal(addDetailRes.body.flag, 'success'); + assert.equal(Number(addDetailRes.body.code), 200); + + const detailId = Number(addDetailRes.body?.data?.data?.selectId || addDetailRes.body?.data?.selectId || 0); + assert.ok(detailId > 0, '新增收货单明细后未返回有效 detail_id'); + + const firstProduct = systemProducts[0]; + const bindRes = await invokeSystemMethod('storage.receiving.bindDetailProduct', { + detail_id: detailId, + system_product_id: firstProduct.id, + }, switched.token, EXTRA_HEADERS); + + assert.equal(bindRes.status, 200); + assert.equal(bindRes.body.flag, 'success'); + assert.equal(Number(bindRes.body.code), 200); + assert.equal(Number(bindRes.body?.data?.detail_id || 0), detailId); + assert.equal(Number(bindRes.body?.data?.system_product_id || 0), Number(firstProduct.id)); + assert.ok(String(bindRes.body?.data?.product_name || '').length > 0, '绑定后应回填商品名称'); + + const secondProduct = systemProducts.find(item => Number(item.id) !== Number(firstProduct.id)) || firstProduct; + const rebindRes = await invokeSystemMethod('storage.receiving.bindDetailProduct', { + detail_id: detailId, + system_product_id: secondProduct.id, + }, switched.token, EXTRA_HEADERS); + + assert.equal(rebindRes.status, 200); + assert.equal(rebindRes.body.flag, 'success'); + assert.equal(Number(rebindRes.body.code), 200); + assert.equal(Number(rebindRes.body?.data?.detail_id || 0), detailId); + assert.equal(Number(rebindRes.body?.data?.system_product_id || 0), Number(secondProduct.id)); + assert.ok(String(rebindRes.body?.data?.product_name || '').length > 0, '改绑后应返回商品名称'); + } finally { + if (createdId > 0) { + await invokeSystemMethod('storage.receiving.batchCancelReceiving', { + ids: [ createdId ], + }, switched.token, EXTRA_HEADERS); + } + } }); it('should create and then batch cancel receiving order', async () => { @@ -177,6 +409,104 @@ describe('test/app/controller/system.storage.receiving.test.js', () => { } }); + it('should generate unique receiving numbers under concurrent create requests', async () => { + const { token } = await getAuthToken(); + const switched = await switchToWarehouseRole(token); + const suffix = Date.now().toString().slice(-6); + const createdIds = []; + + try { + const requests = [ 1, 2 ].map(index => invokeSystemMethod('storage.receiving.create', { + delivery_method: 'truck', + license_plate: `ITEST-C${index}-${suffix}`, + loading_method: 'with_pallet', + remark: `integration-concurrent-${index}`, + total_boxes: 0, + total_pallets: 0, + }, switched.token, EXTRA_HEADERS)); + + const responses = await Promise.all(requests); + responses.forEach((res, index) => { + assert.equal(res.status, 200, `第 ${index + 1} 个并发请求 HTTP 状态异常`); + assert.equal(res.body.flag, 'success', `第 ${index + 1} 个并发请求应成功: ${JSON.stringify(res.body)}`); + assert.equal(res.body.code, 200, `第 ${index + 1} 个并发请求 code 应为 200`); + }); + + const ids = responses.map(res => Number(res.body.id || res.body?.data?.id || 0)); + const receivingNumbers = responses.map(res => String(res.body.receiving_number || res.body?.data?.receiving_number || '')); + + ids.forEach(id => { + assert.ok(id > 0, '并发创建成功但未返回有效 id'); + createdIds.push(id); + }); + receivingNumbers.forEach(number => { + assert.ok(number.startsWith('R'), `收货单号格式异常: ${number}`); + }); + assert.equal(new Set(receivingNumbers).size, receivingNumbers.length, '并发创建时 receiving_number 应保持唯一'); + } finally { + if (createdIds.length > 0) { + await invokeSystemMethod('storage.receiving.batchCancelReceiving', { + ids: createdIds, + }, switched.token, EXTRA_HEADERS); + } + } + }); + + it('should include same-day records when created_at uses daterange filter', async () => { + const { token } = await getAuthToken(); + const switched = await switchToWarehouseRole(token); + let createdId = 0; + + try { + const uniquePlate = `ITEST-DATE-${Date.now().toString().slice(-6)}`; + const createRes = await invokeSystemMethod('storage.receiving.create', { + delivery_method: 'truck', + license_plate: uniquePlate, + loading_method: 'with_pallet', + remark: 'date-range-regression', + total_boxes: 0, + total_pallets: 0, + }, switched.token, EXTRA_HEADERS); + + assert.equal(createRes.status, 200); + assert.equal(createRes.body.flag, 'success'); + assert.equal(createRes.body.code, 200); + createdId = Number(createRes.body.id || createRes.body?.data?.id || 0); + assert.ok(createdId > 0, '创建收货单失败,无法执行日期范围回归'); + + const now = new Date(); + const startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime(); + const listRes = await invokeSystemMethod('storage.receiving.getReceivingList', { + pagination: { + page: 1, + pageSize: 20, + }, + where: { + created_at: { + operator: 'between', + value: [ startOfDay, startOfDay ], + type: 'daterange', + }, + }, + }, switched.token, EXTRA_HEADERS); + + assert.equal(listRes.status, 200); + assert.equal(listRes.body.flag, 'success'); + assert.equal(listRes.body.code, 200); + + const payload = normalizeListPayload(listRes.body.data); + assert.ok(payload, '日期范围查询返回结构缺少列表 payload'); + const ids = Array.isArray(payload.list) ? payload.list.map(item => Number(item && item.id)) : []; + assert.ok(ids.includes(createdId), '同日创建的收货单应命中 created_at daterange 查询'); + } finally { + if (createdId > 0) { + await invokeSystemMethod('storage.receiving.batchCancelReceiving', { + ids: [ createdId ], + }, switched.token, EXTRA_HEADERS); + } + } + }); + it('should reject getReceivingDetail with invalid id', async () => { const { token } = await getAuthToken(); const switched = await switchToWarehouseRole(token); diff --git a/test/app/controller/system.storeWarehouse.test.js b/test/app/controller/system.storeWarehouse.test.js new file mode 100644 index 0000000..b948613 --- /dev/null +++ b/test/app/controller/system.storeWarehouse.test.js @@ -0,0 +1,122 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const { + getAuthToken, + invokeSystemMethod, +} = require('../../support/system_method_client'); + +const EXTRA_HEADERS = { + platform: 'web', + project: 'all', +}; + +describe('test/app/controller/system.storeWarehouse.test.js', () => { + const METHOD_PREFIX = 'storeWarehouse.store'; + const REMOVED_SETTING_METHOD_PREFIX = 'setting.storeWarehouse.store'; + let token = ''; + + before(async () => { + const auth = await getAuthToken({ forceLogin: true }); + token = auth.token; + }); + + it('should expose standalone storeWarehouse.store.list', async () => { + const res = await invokeSystemMethod(`${METHOD_PREFIX}.list`, { + page: 1, + page_size: 10, + }, token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + assert.equal(res.body.code, 200); + assert.ok(Array.isArray(res.body?.data?.list), 'storeWarehouse.store.list 应返回 list'); + assert.equal(typeof res.body?.data?.total, 'number'); + }); + + it('should not expose removed setting.storeWarehouse.store.list alias', async () => { + const removedRes = await invokeSystemMethod(`${REMOVED_SETTING_METHOD_PREFIX}.list`, { + page: 1, + page_size: 10, + }, token, EXTRA_HEADERS); + + assert.equal(removedRes.status, 500); + assert.equal(removedRes.body.flag, 'failure'); + assert.equal(Number(removedRes.body.code), 500); + assert.match(String(removedRes.body.message || ''), /服务 setting\.storeWarehouse\.store 不存在/); + }); + + it('should expose standalone storeWarehouse.store.sign parameter validation', async () => { + const res = await invokeSystemMethod(`${METHOD_PREFIX}.sign`, { + print_quantity: 0, + }, token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'failure'); + assert.equal(Number(res.body.code), 400); + assert.match(String(res.body.message || ''), /counterparty_id|store_id|warehouse_id/); + }); + + it('should expose standalone storeWarehouse.store.unbind parameter validation', async () => { + const res = await invokeSystemMethod(`${METHOD_PREFIX}.unbind`, {}, token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'failure'); + assert.equal(Number(res.body.code), 400); + assert.match(String(res.body.message || ''), /id|counterparty_id|store_id|warehouse_id/); + }); + + it('should expose standalone storeWarehouse.store.rename parameter validation', async () => { + const res = await invokeSystemMethod(`${METHOD_PREFIX}.rename`, {}, token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'failure'); + assert.equal(Number(res.body.code), 400); + assert.match(String(res.body.message || ''), /remask|id|counterparty_id|store_id|warehouse_id/); + }); + + it('should expose standalone storeWarehouse.store.getPolicyConfig parameter validation', async () => { + const res = await invokeSystemMethod(`${METHOD_PREFIX}.getPolicyConfig`, {}, token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'failure'); + assert.equal(Number(res.body.code), 400); + assert.match(String(res.body.message || ''), /id|counterparty_id|store_id|warehouse_id/); + }); + + it('should expose standalone storeWarehouse.store.savePolicyConfig parameter validation', async () => { + const res = await invokeSystemMethod(`${METHOD_PREFIX}.savePolicyConfig`, {}, token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'failure'); + assert.equal(Number(res.body.code), 400); + assert.match(String(res.body.message || ''), /id|counterparty_id|store_id|warehouse_id/); + }); + + it('should expose standalone storeWarehouse.store.saveQimenConfig parameter validation', async () => { + const res = await invokeSystemMethod(`${METHOD_PREFIX}.saveQimenConfig`, {}, token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'failure'); + assert.equal(Number(res.body.code), 400); + assert.match(String(res.body.message || ''), /id|counterparty_id|store_id|warehouse_id|qimen_app_key|qimen_customer_id|qimen_warehouse_code/); + }); + + it('should expose standalone storeWarehouse.store.deleteQimenConfig parameter validation', async () => { + const res = await invokeSystemMethod(`${METHOD_PREFIX}.deleteQimenConfig`, {}, token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'failure'); + assert.equal(Number(res.body.code), 400); + assert.match(String(res.body.message || ''), /id|counterparty_id|store_id|warehouse_id/); + }); + + it('should expose standalone storeWarehouse.store.listQimenConfig parameter validation', async () => { + const res = await invokeSystemMethod(`${METHOD_PREFIX}.listQimenConfig`, {}, token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'failure'); + assert.equal(Number(res.body.code), 400); + assert.match(String(res.body.message || ''), /id|counterparty_id|store_id|warehouse_id/); + }); +}); diff --git a/test/app/controller/system.user.getLoginWechatCode.test.js b/test/app/controller/system.user.getLoginWechatCode.test.js new file mode 100644 index 0000000..0507107 --- /dev/null +++ b/test/app/controller/system.user.getLoginWechatCode.test.js @@ -0,0 +1,17 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const { invokeSystemMethod } = require('../../support/system_method_client'); + +describe('test/app/controller/system.user.getLoginWechatCode.test.js', () => { + it('should return login code without Authorization token', async () => { + const res = await invokeSystemMethod('user.getLoginWechatCode', {}); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + assert.equal(res.body.code, 200); + assert.match(String(res.body?.data?.client_code || ''), /^(?=.*[A-Z])(?=.*\d)[A-Z\d]{6}$/); + assert.match(String(res.body?.data?.code || ''), /^(?=.*[A-Z])(?=.*\d)[A-Z\d]{6}$/); + assert.equal(res.body?.data?.status, 'pending'); + }); +}); diff --git a/test/app/controller/system.user.loginByCode.test.js b/test/app/controller/system.user.loginByCode.test.js index 928ff74..af3dad0 100644 --- a/test/app/controller/system.user.loginByCode.test.js +++ b/test/app/controller/system.user.loginByCode.test.js @@ -3,11 +3,14 @@ const assert = require('node:assert/strict'); const { invokeSystemMethod } = require('../../support/system_method_client'); -const VALID_LOGIN_CODE = process.env.SYSTEM_TEST_LOGIN_CODE - || 'eyJ1dWlkIjoiMDg2MTk4MzQtY2FhYS00OTIyLWJmNjctODc5M2U2Y2MwYzJkIn0='; +const VALID_LOGIN_CODE = String(process.env.SYSTEM_TEST_LOGIN_CODE || '').trim(); describe('test/app/controller/system.user.loginByCode.test.js', () => { - it('should login successfully when code is valid', async () => { + it('should login successfully when code is valid', async function() { + if (!VALID_LOGIN_CODE) { + this.skip(); + } + const res = await invokeSystemMethod('user.loginByCode', { code: VALID_LOGIN_CODE, }); @@ -30,23 +33,23 @@ describe('test/app/controller/system.user.loginByCode.test.js', () => { assert.match(String(res.body.message || ''), /code/); }); - it('should fail when code is not valid base64 json', async () => { + it('should fail when code does not exist', async () => { const code = `INVALID_CODE_${Date.now()}`; const res = await invokeSystemMethod('user.loginByCode', { code }); assert.equal(res.status, 200); assert.equal(res.body.flag, 'failure'); assert.equal(res.body.code, 0); - assert.match(String(res.body.message || ''), /无效的登录码格式/); + assert.match(String(res.body.message || ''), /登录码不存在|登录失败/); }); - it('should fail when decoded payload does not contain uuid', async () => { - const code = Buffer.from(JSON.stringify({ foo: 'bar' }), 'utf8').toString('base64'); + it('should fail when code format is valid but not matched', async () => { + const code = 'A1B2C3'; const res = await invokeSystemMethod('user.loginByCode', { code }); assert.equal(res.status, 200); assert.equal(res.body.flag, 'failure'); assert.equal(res.body.code, 0); - assert.match(String(res.body.message || ''), /uuid/); + assert.match(String(res.body.message || ''), /登录码不存在|登录失败/); }); }); diff --git a/test/app/service/systems/auth.user.bindWechatCacheExpiry.test.js b/test/app/service/systems/auth.user.bindWechatCacheExpiry.test.js new file mode 100644 index 0000000..620c21e --- /dev/null +++ b/test/app/service/systems/auth.user.bindWechatCacheExpiry.test.js @@ -0,0 +1,152 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const UserService = require('../../../../app/service/systems/auth/user'); + +function createServiceHarness() { + const cacheWrites = []; + const cacheStore = new Map(); + + const app = { + async setCacheAsync(cacheKey, data, expireSeconds = 300) { + cacheWrites.push({ + cacheKey, + data, + expireSeconds, + }); + + if (data === null || data === undefined || expireSeconds <= 1) { + cacheStore.delete(cacheKey); + return; + } + + cacheStore.set(cacheKey, data); + }, + async getCacheAsync(cacheKey) { + return cacheStore.has(cacheKey) ? cacheStore.get(cacheKey) : null; + }, + coreLogger: { + warn() {}, + error() {}, + }, + }; + + const ctx = { + app, + userId: 1001, + user: { + id: 1001, + }, + }; + + const service = new UserService(ctx); + + return { + app, + ctx, + service, + cacheWrites, + cacheStore, + }; +} + +describe('test/app/service/systems/auth.user.bindWechatCacheExpiry.test.js', () => { + it('should generate pending code with fixed 60s ttl and keep same code without extending', async () => { + const fixedNow = 1760000000000; + const originalNow = Date.now; + Date.now = () => fixedNow; + + try { + const { service, cacheWrites } = createServiceHarness(); + service.findYe4sBindingByAccountId = async () => null; + + const first = await service.refreshWechatBindState(1001, null, { + forceNewCode: false, + }); + + assert.equal(first.state.status, 'pending'); + assert.match(String(first.state.code || ''), /^(?=.*[A-Z])(?=.*\d)[A-Z\d]{6}$/); + assert.equal(first.state.expires_at, fixedNow + 60000); + + const firstWriteCount = cacheWrites.length; + assert.equal(firstWriteCount, 2); + for (const write of cacheWrites) { + assert.equal(write.expireSeconds, 60); + } + + const second = await service.refreshWechatBindState(1001, first.state, { + forceNewCode: false, + }); + + assert.equal(second.state.code, first.state.code); + assert.equal(second.state.status, 'pending'); + assert.equal(cacheWrites.length, firstWriteCount); + } finally { + Date.now = originalNow; + } + }); + + it('should return scanned status when scan key exists', async () => { + const fixedNow = 1760000000000; + const originalNow = Date.now; + Date.now = () => fixedNow; + + try { + const { service, cacheStore } = createServiceHarness(); + service.findYe4sBindingByAccountId = async () => null; + + const pending = await service.refreshWechatBindState(1001, null, { + forceNewCode: false, + }); + const code = pending.state.code; + + cacheStore.set(`user:wechat:bind:scan:${code}`, { + account_id: 1001, + code, + status: 'scanned', + scanned_at: new Date(fixedNow + 1000).toISOString(), + }); + + const result = await service.refreshWechatBindState(1001, pending.state, { + forceNewCode: false, + }); + + assert.equal(result.state.status, 'scanned'); + assert.equal(result.state.code, code); + assert.ok(result.state.scanned_at); + } finally { + Date.now = originalNow; + } + }); + + it('should rotate code when forceNewCode is enabled', async () => { + const fixedNow = 1760000000000; + const originalNow = Date.now; + Date.now = () => fixedNow; + + try { + const { service, cacheWrites } = createServiceHarness(); + service.findYe4sBindingByAccountId = async () => null; + + const oldState = { + account_id: 1001, + status: 'pending', + code: 'A1B2C3', + expires_at: fixedNow + 30000, + }; + + const result = await service.refreshWechatBindState(1001, oldState, { + forceNewCode: true, + }); + + assert.equal(result.state.status, 'pending'); + assert.notEqual(result.state.code, oldState.code); + assert.equal(result.state.expires_at, fixedNow + 60000); + + const oldCodeInvalidation = cacheWrites.find(item => item && item.data === null && item.expireSeconds === 1); + assert.ok(oldCodeInvalidation); + } finally { + Date.now = originalNow; + } + }); +}); diff --git a/test/app/service/systems/auth.user.loginWechatCode.test.js b/test/app/service/systems/auth.user.loginWechatCode.test.js new file mode 100644 index 0000000..7d559fd --- /dev/null +++ b/test/app/service/systems/auth.user.loginWechatCode.test.js @@ -0,0 +1,103 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const UserService = require('../../../../app/service/systems/auth/user'); + +function createServiceHarness() { + const cacheWrites = []; + const cacheStore = new Map(); + + const app = { + async setCacheAsync(cacheKey, data, expireSeconds = 300) { + cacheWrites.push({ + cacheKey, + data, + expireSeconds, + }); + + if (data === null || data === undefined || expireSeconds <= 1) { + cacheStore.delete(cacheKey); + return; + } + + cacheStore.set(cacheKey, data); + }, + async getCacheAsync(cacheKey) { + return cacheStore.has(cacheKey) ? cacheStore.get(cacheKey) : null; + }, + coreLogger: { + warn() {}, + error() {}, + }, + }; + + const ctx = { + app, + }; + + const service = new UserService(ctx); + + return { + app, + ctx, + service, + cacheWrites, + cacheStore, + }; +} + +describe('test/app/service/systems/auth.user.loginWechatCode.test.js', () => { + it('should generate client code and login code when client code is missing', async () => { + const { service, cacheWrites } = createServiceHarness(); + + const result = await service.getLoginWechatCode({}); + + assert.equal(result.success, true); + assert.equal(result.code, 200); + assert.match(String(result.data.client_code || ''), /^(?=.*[A-Z])(?=.*\d)[A-Z\d]{6}$/); + assert.match(String(result.data.code || ''), /^(?=.*[A-Z])(?=.*\d)[A-Z\d]{6}$/); + assert.equal(result.data.status, 'pending'); + assert.ok(String(result.message || '').includes('客户端编码')); + + const writesWithState = cacheWrites.filter(item => item && item.data && item.data.client_code === result.data.client_code); + assert.equal(writesWithState.length, 2); + for (const write of writesWithState) { + assert.equal(write.expireSeconds, 60); + } + }); + + it('should refresh login code after long poll when client code is provided', async () => { + const { service, cacheWrites } = createServiceHarness(); + service.waitForLoginCodeRefresh = async () => {}; + + const first = await service.getLoginWechatCode({}); + const firstCode = String(first.data.code || ''); + const clientCode = String(first.data.client_code || ''); + + const second = await service.getLoginWechatCode({ + clientCode, + }); + + assert.equal(second.success, true); + assert.equal(second.code, 200); + assert.equal(String(second.data.client_code || ''), clientCode); + assert.match(String(second.data.code || ''), /^(?=.*[A-Z])(?=.*\d)[A-Z\d]{6}$/); + assert.notEqual(String(second.data.code || ''), firstCode); + assert.ok(String(second.message || '').includes('长轮询结束')); + + const invalidationWrite = cacheWrites.find(item => item && item.data === null && item.expireSeconds === 1); + assert.ok(invalidationWrite); + }); + + it('should fail when provided client code format is invalid', async () => { + const { service } = createServiceHarness(); + + const result = await service.getLoginWechatCode({ + clientCode: 'abc', + }); + + assert.equal(result.success, false); + assert.equal(result.code, 0); + assert.match(String(result.message || ''), /客户端编码/); + }); +}); diff --git a/test/app/service/systems/excel.test.js b/test/app/service/systems/excel.test.js new file mode 100644 index 0000000..b057bb3 --- /dev/null +++ b/test/app/service/systems/excel.test.js @@ -0,0 +1,257 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const XLSX = require('xlsx'); +const ExcelService = require('../../../../app/service/systems/excel'); + +function createService(overrides = {}) { + const uploads = []; + const notifyCalls = []; + const ctx = { + app: { + config: {}, + }, + logger: { + info() {}, + error() {}, + }, + service: { + systems: { + upload: { + async uploadFile(fileStream, options = {}) { + const chunks = []; + for await (const chunk of fileStream) { + chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)); + } + + const body = Buffer.concat(chunks); + uploads.push({ + filename: fileStream.filename, + mimeType: fileStream.mimeType, + fileSize: fileStream.fileSize, + options, + body, + }); + + return { + fileName: options.key, + cosUrl: `https://cos.example.com/${options.key}`, + cdnUrl: `https://cdn.example.com/${options.key}`, + url: `https://cdn.example.com/${options.key}`, + }; + }, + async uploadSuccessNotify(data) { + notifyCalls.push(data); + return { + code: 0, + data: { + fileId: 9527, + fileKey: data.url, + fileUrl: `https://cdn.example.com/${data.url}`, + }, + }; + }, + }, + }, + }, + ...overrides, + }; + + const service = new ExcelService(ctx); + return { + service, + uploads, + notifyCalls, + ctx, + }; +} + +describe('test/app/service/systems/excel.test.js', () => { + it('should generate workbook buffer and parse rows back', async () => { + const { service } = createService(); + + const buffer = await service.generateBuffer({ + sheets: [ + { + name: '入库单', + columns: [ + { header: '单号', key: 'order_no', width: 20 }, + { header: '货主', key: 'owner_name', width: 18 }, + { header: '箱数', key: 'total_boxes', width: 10 }, + ], + rows: [ + { + order_no: 'RK20260404001', + owner_name: '测试货主', + total_boxes: 12, + }, + ], + }, + ], + }); + + assert.ok(Buffer.isBuffer(buffer)); + assert.ok(buffer.length > 0); + + const parsed = await service.parseBuffer(buffer); + assert.deepEqual(parsed.sheetNames, [ '入库单' ]); + assert.equal(parsed.sheets[0].rows[0].单号, 'RK20260404001'); + assert.equal(parsed.sheets[0].rows[0].货主, '测试货主'); + assert.equal(parsed.sheets[0].rows[0].箱数, '12'); + }); + + it('should normalize duplicated or empty headers when parsing', async () => { + const { service } = createService(); + + const buffer = await service.generateBuffer({ + sheets: [ + { + name: '重复表头', + rows: [ + [ '名称', '名称', '' ], + [ 'A', 'B', 'C' ], + ], + }, + ], + }); + + const parsed = await service.parseBuffer(buffer); + assert.deepEqual(parsed.sheets[0].headers, [ '名称', '名称_2', 'column_3' ]); + assert.equal(parsed.sheets[0].rows[0].名称, 'A'); + assert.equal(parsed.sheets[0].rows[0].名称_2, 'B'); + assert.equal(parsed.sheets[0].rows[0].column_3, 'C'); + }); + + it('should generate excel and upload to custom directory', async () => { + const { service, uploads, notifyCalls } = createService(); + + const result = await service.generateAndUpload({ + filename: '收货报表.xlsx', + dir: 'exports/receiving', + saveRecord: true, + businessType: 'receiving', + businessId: 1001, + expireDays: 90, + sheets: [ + { + name: '报表', + columns: [ + { header: '单号', key: 'order_no' }, + ], + rows: [ + { order_no: 'RK1001' }, + ], + }, + ], + }); + + assert.equal(uploads.length, 1); + assert.equal(uploads[0].filename, '收货报表.xlsx'); + assert.equal(uploads[0].mimeType, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); + assert.ok(uploads[0].options.key.includes('exports/receiving/')); + assert.ok(Buffer.isBuffer(uploads[0].body)); + assert.ok(uploads[0].body.length > 0); + assert.equal(notifyCalls[0].expireDays, 90); + assert.ok(String(result.fileKey || '').includes('exports/receiving/')); + assert.equal(result.fileRecord.fileId, 9527); + }); + + it('should honor skipHeader when object rows are used', async () => { + const { service } = createService(); + + const buffer = await service.generateBuffer({ + sheets: [ + { + name: '跳过首表头', + columns: [ + { header: '分区', key: 'section', width: 12 }, + { header: '字段', key: 'field', width: 16 }, + { header: '值', key: 'value', width: 18 }, + ], + rows: [ + { section: '主表', field: '收货单号', value: 'R001' }, + { section: '明细表头', field: '字段', value: '值' }, + ], + skipHeader: true, + }, + ], + }); + + const workbook = XLSX.read(buffer, { type: 'buffer' }); + const rawRows = XLSX.utils.sheet_to_json(workbook.Sheets['跳过首表头'], { + header: 1, + defval: '', + }); + + assert.deepEqual(rawRows[0], [ '主表', '收货单号', 'R001' ]); + assert.deepEqual(rawRows[1], [ '明细表头', '字段', '值' ]); + }); + + it('should support embedded images when url is a data URL', async () => { + const { service } = createService(); + const imageDataUrl = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9WnR8i8AAAAASUVORK5CYII='; + + const buffer = await service.generateBuffer({ + sheets: [ + { + name: 'URL图片', + rows: [ [ '图片', '见右侧' ] ], + embeddedImages: [ + { + row: 1, + col: 2, + url: imageDataUrl, + width: 40, + height: 40, + }, + ], + }, + ], + }); + + assert.ok(Buffer.isBuffer(buffer)); + assert.ok(buffer.length > 0); + }); + + it('should generate workbook with embedded image previews when image config exists', async () => { + const { service } = createService(); + const imageDataUrl = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9WnR8i8AAAAASUVORK5CYII='; + + const buffer = await service.generateBuffer({ + sheets: [ + { + name: '图片预览', + columns: [ + { header: '名称', key: 'name', width: 20 }, + { header: '链接', key: 'url', width: 30 }, + { header: '图片', key: 'preview', width: 22 }, + ], + rows: [ + { + name: '示例图片', + url: 'https://example.com/demo.png', + preview: '见右侧', + }, + ], + embeddedImages: [ + { + row: 2, + col: 3, + dataUrl: imageDataUrl, + width: 60, + height: 60, + fallbackText: '示例图片', + }, + ], + }, + ], + }); + + assert.ok(Buffer.isBuffer(buffer)); + assert.ok(buffer.length > 0); + + const parsed = await service.parseBuffer(buffer); + assert.deepEqual(parsed.sheetNames, [ '图片预览' ]); + assert.equal(parsed.sheets[0].rows[0].名称, '示例图片'); + }); +}); diff --git a/test/app/service/systems/stock_store.stockWarehouse.conditions.test.js b/test/app/service/systems/stock_store.stockWarehouse.conditions.test.js index deb0c0e..f602ede 100644 --- a/test/app/service/systems/stock_store.stockWarehouse.conditions.test.js +++ b/test/app/service/systems/stock_store.stockWarehouse.conditions.test.js @@ -194,7 +194,7 @@ describe('test/app/service/systems/stock_store.stockWarehouse.conditions.test.js assert.deepEqual(between, { create_at: { - [Op.between]: [ '2026-03-01', '2026-03-31' ], + [Op.between]: [ '2026-03-01 00:00:00', '2026-03-31 23:59:59' ], }, }); }); diff --git a/test/app/service/systems/storage.receiving.report.test.js b/test/app/service/systems/storage.receiving.report.test.js new file mode 100644 index 0000000..7078232 --- /dev/null +++ b/test/app/service/systems/storage.receiving.report.test.js @@ -0,0 +1,127 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const ReceivingService = require('../../../../app/service/systems/storage/receiving'); + +function createService() { + const excelCalls = []; + const ctx = { + app: { + config: {}, + Sequelize: { + Op: {}, + }, + }, + user: { + store_id: 2001, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + service: { + systems: { + excel: { + async generateAndUpload(options) { + excelCalls.push(options); + return { + fileKey: options.filename, + url: `https://cdn.example.com/${options.filename}`, + }; + }, + }, + }, + }, + }; + + const service = new ReceivingService(ctx); + return { + service, + excelCalls, + }; +} + +describe('test/app/service/systems/storage.receiving.report.test.js', () => { + it('should build and upload completion excel in a single sheet with one preview column', async () => { + const { service, excelCalls } = createService(); + + const result = await service.uploadCompletionExcelReport({ + receiving: { + id: 123, + receiving_number: 'RCV202604040001', + store_name: '测试货主', + warehouse_id: 2001, + delivery_method: 'truck', + license_plate: '粤A12345', + tracking_number: 'YT123456789', + total_boxes: 3, + total_pallets: 1, + remark: '完成收货测试', + receiving_end_time: new Date('2026-04-04T12:30:00Z'), + details: [ + { + id: 501, + product_name: '测试商品A', + system_product_id: 9001, + barcode: 'SKU-001', + actual_quantity: 8, + weight: 12, + }, + ], + }, + operator: { + employees_name: '测试员', + }, + stats: { + total_details: 1, + matched_details: 1, + unmatched_details: 0, + total_quantity: 8, + }, + detailImageMap: new Map([ + [ '501', [ + { url: 'https://example.com/image-1.png' }, + { url: 'https://example.com/image-2.png' }, + ]], + ]), + receivingImages: [ + { url: 'https://example.com/main-image.png' }, + ], + }); + + assert.equal(excelCalls.length, 1); + const [ options ] = excelCalls; + assert.equal(options.filename, '收货完成_RCV202604040001.xlsx'); + assert.ok(String(options.dir || '').includes('receiving/completed')); + assert.equal(options.expireDays, 90); + assert.ok(Array.isArray(options.sheets)); + assert.equal(options.sheets.length, 1); + + const [ sheet ] = options.sheets; + assert.equal(sheet.name, '收货清单'); + assert.ok(Array.isArray(sheet.rows)); + assert.equal(sheet.skipHeader, true); + + const receivingNumberRow = sheet.rows.find(item => Array.isArray(item) && item[0] === '收货单号'); + assert.ok(receivingNumberRow, '应在主表区域包含收货单号行'); + + const summaryImageRow = sheet.rows.find(item => Array.isArray(item) && item[0] === '收货图片'); + assert.ok(summaryImageRow, '应在主表区域包含收货图片行'); + assert.match(String(summaryImageRow[1]?.text || summaryImageRow[1] || ''), /main-image/); + + const detailHeaderRow = sheet.rows.find(item => Array.isArray(item) && item[0] === '序号' && item[1] === '商品名称'); + assert.ok(detailHeaderRow, '明细表头应出现在下方明细区开始处'); + + const detailRow = sheet.rows.find(item => Array.isArray(item) && item[1] === '测试商品A'); + assert.ok(detailRow, '应在单 sheet 中包含明细行'); + assert.match(String(detailRow[11]?.text || detailRow[11] || ''), /image-1\.png/); + assert.equal(detailRow[10], ''); + + assert.ok(Array.isArray(sheet.styledRows)); + assert.ok(sheet.styledRows.some(item => item && item.style && item.style.font && item.style.font.bold), '应包含表头加粗样式'); + assert.ok(Array.isArray(sheet.embeddedImages)); + assert.equal(sheet.embeddedImages.length, 3); + assert.equal(result.url, 'https://cdn.example.com/收货完成_RCV202604040001.xlsx'); + }); +}); From e590808062cb27639279b66d8568fafd4121922a Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sun, 5 Apr 2026 21:45:18 +0800 Subject: [PATCH 014/550] feat: update receiving notification and report flow --- AI_TOOLBOX.md | 94 +- app/controller/docs.js | 42 +- app/controller/gateway.js | 2 +- app/controller/home.js | 4 +- app/extend/application.js | 2 +- app/lib/query_condition_parser.js | 3 +- app/lib/stop_current_egg.js | 2 +- app/model/notification_send_log.js | 129 +++ app/model/notification_webhook.js | 155 ++- app/model/print_record.js | 50 +- app/model/print_station_express.js | 10 +- app/model/print_stations.js | 24 +- app/model/store.js | 91 +- app/router.js | 10 +- app/service/apiMethods/print.js | 2 +- app/service/apiMethods/user.js | 2 +- app/service/systemMethods/index.js | 4 +- .../systemMethods/order/archiveOrder.js | 4 +- app/service/systemMethods/order/base.js | 2 +- .../systemMethods/order/deliveryOrder.js | 4 +- .../systemMethods/order/expectionOrder.js | 4 +- app/service/systemMethods/order/index.js | 12 +- .../systemMethods/order/pendingOrder.js | 4 +- .../systemMethods/order/reviewOrder.js | 4 +- app/service/systemMethods/setting/account.js | 2 +- .../systemMethods/setting/permission.js | 6 - .../systemMethods/setting/printTemplate.js | 2 +- app/service/systemMethods/setting/role.js | 6 - app/service/systemMethods/stock/combo.js | 2 +- app/service/systemMethods/stock/store.js | 2 +- app/service/systemMethods/stock/warehouse.js | 694 +++++++------- app/service/systemMethods/storage/entry.js | 130 +-- .../systemMethods/storage/receiving.js | 2 +- app/service/systemMethods/user.js | 6 +- app/service/systems/auth/role_permission.js | 2 +- app/service/systems/auth/user.js | 85 +- app/service/systems/excel.js | 5 + app/service/systems/notice/drivers/generic.js | 33 + app/service/systems/notice/drivers/wecom.js | 82 ++ app/service/systems/notice/index.js | 883 ++++++++++++++++++ app/service/systems/print/index.js | 46 +- app/service/systems/setting/account.js | 12 - app/service/systems/setting/permission.js | 187 ---- app/service/systems/setting/print_template.js | 2 +- app/service/systems/setting/role.js | 108 +-- app/service/systems/stock_store.js | 80 +- app/service/systems/storage/index.js | 8 +- app/service/systems/storage/receiving.js | 302 ++++-- app/service/systems/store.js | 45 + app/service/systems/upload.js | 126 ++- config/config.default.js | 10 +- config/poloapi.js | 42 +- ...5011000-add-subject-config-to-wms-store.js | 26 + ...-wms-store-subject-config-webhook-limit.js | 28 + ...-extra-config-from-notification-webhook.js | 25 + ...024000-create-wms-notification-send-log.js | 152 +++ docs/notification-event-api.md | 216 +++++ docs/notification-webhook-capability.md | 263 ++++++ package.json | 2 + script/debug-send-receiving-webhooks.cjs | 252 +++++ script/debug-webhook-receiver.cjs | 134 +++ ....setting.account.getBindWechatCode.test.js | 2 +- .../system.stock.warehouse.namespaced.test.js | 2 +- test/app/service/systems/excel.test.js | 4 +- test/app/service/systems/notice.test.js | 696 ++++++++++++++ ...ck_store.stockWarehouse.conditions.test.js | 50 +- .../systems/storage.receiving.report.test.js | 300 +++++- test/app/service/systems/upload.test.js | 96 ++ 68 files changed, 4632 insertions(+), 1186 deletions(-) create mode 100644 app/model/notification_send_log.js create mode 100644 app/service/systems/notice/drivers/generic.js create mode 100644 app/service/systems/notice/drivers/wecom.js create mode 100644 app/service/systems/notice/index.js create mode 100644 database/migrations/20260405011000-add-subject-config-to-wms-store.js create mode 100644 database/migrations/20260405013000-init-wms-store-subject-config-webhook-limit.js create mode 100644 database/migrations/20260405015000-drop-extra-config-from-notification-webhook.js create mode 100644 database/migrations/20260405024000-create-wms-notification-send-log.js create mode 100644 docs/notification-event-api.md create mode 100644 docs/notification-webhook-capability.md create mode 100644 script/debug-send-receiving-webhooks.cjs create mode 100644 script/debug-webhook-receiver.cjs create mode 100644 test/app/service/systems/notice.test.js create mode 100644 test/app/service/systems/upload.test.js diff --git a/AI_TOOLBOX.md b/AI_TOOLBOX.md index 94e36d6..755553e 100644 --- a/AI_TOOLBOX.md +++ b/AI_TOOLBOX.md @@ -1,6 +1,16 @@ # AI 工具箱(WMS) -本文件用于统一 AI 协助开发/调试时可直接使用的方法,减少重复沟通成本。AI每次应答文尾加喵~以判断是否丢失上下文 +## 🤖 AI阅读优先级 +1. **必读**:第2节(数据库)、第4节(Redis)- 最常用 +2. **重要**:第3节(提问模板)、第6节(安全约束)、第14节(where规范) +3. **按需**:第10节(远程发布)、第15节(权限映射)、第16节(消息通知) +4. **红线**:10.4(SSH禁止读取)、6(SQL安全) + +## 快速响应规则 +- 用户要求查数据 → 直接执行 script/db-query.ps1 +- 用户要求改缓存 → 先用redis-cache.ps1读,再改 +- 用户要求发布 → 只提示命令,不读SSH配置 +- 所有回复结尾加"喵~" ## 1. 适用范围 @@ -200,6 +210,7 @@ powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action decr - - 涉及生产数据时,优先在测试环境验证 - Redis 写操作(`set/del/hset/hdel/incr/decr/expire`)前,先执行一次读取并确认影响 key 范围 + ## 7. 接口入口与 Method 指向 - 入口风格: @@ -437,9 +448,6 @@ npm run rollback:prod -- --backup=backup-20260324123045.tar.gz - 遇到“动态分表模型不可用”优先检查 `app.js` 的工厂初始化是否执行成功。 - 遇到“缓存读写异常”优先检查 Redis client `cache` 配置及 `setCacheAsync/getCacheAsync` 调用链。 -### 11.4 AI 快速回复定义 -- 回复0时默认拒绝 -- 回复1时默认接收 ## 12. Web 用户信息与切换角色测试(已验证) @@ -633,4 +641,80 @@ npm run permission:sync:system-api 2. 更新 `wms_role(id=2).permissions`,将新权限 ID 追加到 JSON 数组;若该字段为 `"*"` 则保持不变。 - 生产建议:保持 `app.config.debug=false`,避免运行时自动写库。 - \ No newline at end of file + ## 16 消息推送配置规则 + +- `wms_store.subject_config` 用于保存主体级通知配置。 +- 当前默认初始化字段:`max_notice_webhook_count = 5`。 +- 该字段表示“当前主体最多允许绑定的消息推送接口数量”。 +- 合法范围:`0 ~ 5` 的整数。 +- 创建或更新主体时,如携带 `subject_config.max_notice_webhook_count`,必须通过合法性校验;超出范围或类型错误视为非法。 +- WebHook 分发侧也必须遵守该上限,超过上限的回调接口不应继续发送。 + +## 16.1 统一 WebHook 推送能力(notice) + +- 能力总览文档:`docs/notification-webhook-capability.md` +- 事件 API 文档:`docs/notification-event-api.md` +- 统一入口:`ctx.service.systems.notice.send(options)` +- 代码位置:`app/service/systems/notice/index.js` +- 固定发送方式:`POST + application/json` +- `hook_type` 支持: + - `customize`:当前默认统一推送流程,按标准 JSON 透传 + - `wecom`:企业微信 WebHook 直发,自动转为企微机器人消息体 +- 必传参数:`warehouseId` +- 可空参数:`storeId / ownerId` +- 货主信息补充:若传 `storeId` / `ownerId`,会优先查缓存键 `warehouse:xxxstore:xxx:info`(TTL = `600`),未命中再查: + - `wms_store.business_license` + - `wms_store_warehouse.store_remask` +- `events` 支持以下订阅写法: + - `all` / `*`:接收全部已注册事件 + - `receiving_completed`:当前唯一已注册的业务事件(收货完成) +- 事件命名规则:仅允许小写字母、数字、下划线,且首字符不能为数字;**禁止使用 `.`** +- 推送事件注册:需先在 `app/model/notification_webhook.js` 中注册,未注册事件不允许直接发送 +- 传参伪代码: + +```js +await ctx.service.systems.notice.send({ + warehouseId: 100000, + storeId: 200000, // 可选,也可传 ownerId + businessName: 'receiving', + event: 'receiving_completed', + messageType: 'text', // text / image / file + title: '收货单已完成', + content: '收货单 RCV202604050001 已完成', + // image / file 时必传 + url: 'https://cdn.example.com/report.xlsx', + fileName: '收货完成_RCV202604050001.xlsx', + mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + businessId: 12345, + subject: { + id: 100000, + type: 'warehouse', + name: '广州仓', + }, + sender: { + id: 10001, + name: '张三', + }, + metadata: { + receivingId: 12345, + receivingNumber: 'RCV202604050001', + }, +}); +``` +- WebHook 命中规则: + 1. 先查仓库 `warehouseId` 绑定的接口 + 2. 若 `storeId / ownerId` 非空,再查货主绑定的接口并一并发送 + 3. 最终按 `subject_config.max_notice_webhook_count` 限制最大推送数量 +- 推送事件底线: + 1. 业务 service 中只负责调用发送入口,不需要各自重复写重试和异常兜底 + 2. 统一入口会处理失败重试与异常处理:按 `3秒 -> 6秒 -> 12秒` 阶梯重试共 3 次 + 3. 若最终仍失败,写入 `wms_notification_send_log` 供后续排查与补偿 +### 16.2 WebHook 可信结论 + +- 返回值判定约定: + - 返回 `1` = **成功** + - 返回 `0` = **失败** +- 可信结论: + - **地址为外部配置,需要检查返回结果** + - **发送数据只使用POST 方式** + - 若 `notice.send()` 的实际推送触发远端 无法解析的文本视为推送失败 diff --git a/app/controller/docs.js b/app/controller/docs.js index c55aa79..db09e9f 100644 --- a/app/controller/docs.js +++ b/app/controller/docs.js @@ -117,11 +117,11 @@ function renderMethodCard(item, entryPath, moduleName) { ${renderKeyValueRows(headers, { - name: 'name', - type: 'type', - required: 'required', - description: 'description', - })} + name: 'name', + type: 'type', + required: 'required', + description: 'description', + })}
名称类型必填说明
@@ -130,11 +130,11 @@ function renderMethodCard(item, entryPath, moduleName) { ${renderKeyValueRows(params, { - name: 'name', - type: 'type', - required: 'required', - description: 'description', - })} + name: 'name', + type: 'type', + required: 'required', + description: 'description', + })}
名称类型必填说明
@@ -143,11 +143,11 @@ function renderMethodCard(item, entryPath, moduleName) { ${renderKeyValueRows(response, { - name: 'name', - type: 'type', - required: 'required', - description: 'description', - })} + name: 'name', + type: 'type', + required: 'required', + description: 'description', + })}
名称类型必填说明
@@ -156,11 +156,11 @@ function renderMethodCard(item, entryPath, moduleName) { ${renderKeyValueRows(errors, { - name: 'code', - type: 'type', - required: 'required', - description: 'message', - })} + name: 'code', + type: 'type', + required: 'required', + description: 'message', + })}
名称类型必填说明
@@ -964,4 +964,4 @@ class DocsController extends Controller { } } -module.exports = DocsController; \ No newline at end of file +module.exports = DocsController; diff --git a/app/controller/gateway.js b/app/controller/gateway.js index 47f15eb..820133c 100644 --- a/app/controller/gateway.js +++ b/app/controller/gateway.js @@ -115,4 +115,4 @@ class GatewayController extends Controller { } } -module.exports = GatewayController; \ No newline at end of file +module.exports = GatewayController; diff --git a/app/controller/home.js b/app/controller/home.js index 3dca6e7..021bbee 100644 --- a/app/controller/home.js +++ b/app/controller/home.js @@ -183,7 +183,7 @@ class HomeController extends Controller { } validateParams(params) { - const required = ['method', 'v', 'format', 'timestamp']; + const required = [ 'method', 'v', 'format', 'timestamp' ]; for (const field of required) { if (!params[field]) { @@ -199,7 +199,7 @@ class HomeController extends Controller { return true; } validateQimenParams(params) { - const required = ['app_key', 'method', 'v', 'format', 'sign_method', 'sign', 'timestamp']; + const required = [ 'app_key', 'method', 'v', 'format', 'sign_method', 'sign', 'timestamp' ]; for (const field of required) { if (!params[field]) { diff --git a/app/extend/application.js b/app/extend/application.js index eca239c..9f2574f 100644 --- a/app/extend/application.js +++ b/app/extend/application.js @@ -30,7 +30,7 @@ module.exports = { }, async wsdl(methodName, args) { try { - const wsdlUrl = "http://ye4s.com/webservice/ws?wsdl"; + const wsdlUrl = 'http://ye4s.com/webservice/ws?wsdl'; const obj = {}; args.forEach((value, index) => { obj['arg' + index] = value; diff --git a/app/lib/query_condition_parser.js b/app/lib/query_condition_parser.js index baeac5b..8b4c898 100644 --- a/app/lib/query_condition_parser.js +++ b/app/lib/query_condition_parser.js @@ -103,7 +103,8 @@ function processConditionValue(value, type) { if (Array.isArray(value)) { return value.map(item => String(item).trim()).filter(Boolean); } - return String(value).split(',').map(item => item.trim()).filter(Boolean); + return String(value).split(',').map(item => item.trim()) + .filter(Boolean); default: return value; diff --git a/app/lib/stop_current_egg.js b/app/lib/stop_current_egg.js index 8cd7824..64894d8 100644 --- a/app/lib/stop_current_egg.js +++ b/app/lib/stop_current_egg.js @@ -145,4 +145,4 @@ async function main() { main().catch(error => { console.error(error.message || error); process.exitCode = 1; -}); \ No newline at end of file +}); diff --git a/app/model/notification_send_log.js b/app/model/notification_send_log.js new file mode 100644 index 0000000..df28263 --- /dev/null +++ b/app/model/notification_send_log.js @@ -0,0 +1,129 @@ +'use strict'; + +module.exports = app => { + const { BIGINT, STRING, DATE, INTEGER, JSON: JSON_TYPE } = app.Sequelize; + + const NotificationSendLog = app.model.define('notification_send_log', { + id: { + type: BIGINT.UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + trace_id: { + type: STRING(100), + allowNull: false, + comment: '通知追踪ID', + }, + webhook_id: { + type: BIGINT.UNSIGNED, + allowNull: true, + comment: 'Webhook 配置ID', + }, + store_id: { + type: BIGINT.UNSIGNED, + allowNull: true, + comment: '触发主体ID', + }, + warehouse_id: { + type: BIGINT.UNSIGNED, + allowNull: true, + comment: '仓库ID', + }, + owner_store_id: { + type: BIGINT.UNSIGNED, + allowNull: true, + comment: '货主ID', + }, + business_name: { + type: STRING(100), + allowNull: false, + comment: '业务名称', + }, + event: { + type: STRING(100), + allowNull: false, + comment: '事件名', + }, + hook_type: { + type: STRING(50), + allowNull: true, + comment: 'Webhook 类型', + }, + hook_url: { + type: STRING(500), + allowNull: true, + comment: 'Webhook 地址', + }, + request_payload: { + type: JSON_TYPE, + allowNull: true, + comment: '请求载荷', + }, + response_payload: { + type: JSON_TYPE, + allowNull: true, + comment: '返回载荷', + }, + http_status: { + type: INTEGER(11), + allowNull: true, + comment: 'HTTP 状态码', + }, + status: { + type: STRING(20), + allowNull: false, + defaultValue: 'failed', + comment: '发送状态', + }, + error_message: { + type: STRING(1000), + allowNull: true, + comment: '失败原因', + }, + retry_count: { + type: INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '重试次数', + }, + created_by: { + type: BIGINT.UNSIGNED, + allowNull: true, + comment: '创建人', + }, + created_at: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + }, { + tableName: 'wms_notification_send_log', + freezeTableName: true, + underscored: true, + timestamps: false, + comment: '统一通知发送失败日志表', + indexes: [ + { + name: 'idx_notification_send_log_trace_id', + fields: [ 'trace_id' ], + }, + { + name: 'idx_notification_send_log_event_status', + fields: [ 'event', 'status' ], + }, + { + name: 'idx_notification_send_log_webhook_id', + fields: [ 'webhook_id' ], + }, + { + name: 'idx_notification_send_log_created_at', + fields: [ 'created_at' ], + }, + ], + }); + + return NotificationSendLog; +}; diff --git a/app/model/notification_webhook.js b/app/model/notification_webhook.js index c0a6037..6c769b5 100644 --- a/app/model/notification_webhook.js +++ b/app/model/notification_webhook.js @@ -1,7 +1,109 @@ 'use strict'; module.exports = app => { - const { BIGINT, STRING, TINYINT, DATE, JSON } = app.Sequelize; + const { BIGINT, STRING, TINYINT, DATE, JSON: JSON_TYPE, Op } = app.Sequelize; + + const normalizeJsonObject = (value, fieldName, { allowArray = false } = {}) => { + if (value === undefined || value === null || value === '') { + return value; + } + + if (typeof value === 'string') { + try { + const parsed = JSON.parse(value); + return normalizeJsonObject(parsed, fieldName, { allowArray }); + } catch (error) { + throw new Error(`${fieldName} 必须是合法 JSON`); + } + } + + if (Array.isArray(value)) { + if (allowArray) { + return value; + } + throw new Error(`${fieldName} 必须是对象`); + } + + if (typeof value !== 'object') { + throw new Error(`${fieldName} 必须是对象`); + } + + return value; + }; + + const SPECIAL_EVENT_CODES = new Set([ 'all', '*' ]); + const EVENT_CODE_PATTERN = /^[a-z_][a-z0-9_]*$/; + const isValidEventCode = value => SPECIAL_EVENT_CODES.has(value) || EVENT_CODE_PATTERN.test(value); + + const AVAILABLE_EVENTS = Object.freeze([ + Object.freeze({ code: 'all', name: '全部事件', business: 'all', description: '订阅后接收所有通知事件' }), + Object.freeze({ code: '*', name: '全部事件(兼容别名)', business: 'all', description: '兼容旧配置,等价于 all' }), + Object.freeze({ code: 'receiving_completed', name: '收货完成', business: 'receiving', description: '收货单完成后的通知' }), + ]); + const AVAILABLE_EVENT_CODE_SET = new Set(AVAILABLE_EVENTS.map(item => item.code)); + + const getAvailableEvents = () => AVAILABLE_EVENTS.map(item => ({ ...item })); + + const normalizeEvents = value => { + if (value === undefined || value === null || value === '') { + return []; + } + + if (Array.isArray(value)) { + return value.map(item => String(item || '').trim()).filter(Boolean); + } + + if (typeof value === 'string') { + const trimmed = value.trim(); + if (!trimmed) { + return []; + } + + try { + const parsed = JSON.parse(trimmed); + if (parsed !== value) { + return normalizeEvents(parsed); + } + } catch (_) { + // ignore parse failure and continue with string split + } + + return trimmed.split(/[\s,;|]+/).map(item => item.trim()).filter(Boolean); + } + + if (typeof value === 'object') { + if (value.all === true) { + return [ 'all' ]; + } + return normalizeEvents(value.include || value.events || []); + } + + throw new Error('events 必须是字符串数组或对象'); + }; + + const validateEvents = value => { + if (value === undefined || value === null || value === '') { + return; + } + + normalizeJsonObject(value, 'events', { allowArray: true }); + const normalizedEvents = normalizeEvents(value); + const invalidFormatEvents = normalizedEvents.filter(item => !isValidEventCode(item)); + if (invalidFormatEvents.length > 0) { + throw new Error(`events 中包含非法事件编码(仅支持小写字母、数字、下划线,且首字符不能为数字): ${invalidFormatEvents.join(', ')}`); + } + + const invalidEvents = normalizedEvents.filter(item => !AVAILABLE_EVENT_CODE_SET.has(item)); + if (invalidEvents.length > 0) { + throw new Error(`events 中包含不支持的事件: ${invalidEvents.join(', ')}`); + } + }; + + AVAILABLE_EVENTS.forEach(item => { + if (!isValidEventCode(item.code)) { + throw new Error(`通知事件编码不合法: ${item.code}`); + } + }); const NotificationWebhook = app.model.define('notification_webhook', { id: { @@ -37,7 +139,7 @@ module.exports = app => { msg: 'hook_type 长度应在1-50个字符之间', }, }, - comment: 'Webhook 类型,用于按类型分派通知结构处理逻辑', + comment: 'Webhook 类型,用于区分回调通道,当前支持 customize / wecom', }, hook_url: { type: STRING(500), @@ -54,14 +156,14 @@ module.exports = app => { comment: 'Webhook 链接地址', }, events: { - type: JSON, + type: JSON_TYPE, allowNull: true, - comment: '订阅事件列表', - }, - extra_config: { - type: JSON, - allowNull: true, - comment: '扩展配置,如签名、请求头、模板映射等', + comment: '订阅事件列表,可从 NotificationWebhook.getAvailableEvents() 拉取', + validate: { + isValidEvents(value) { + validateEvents(value); + }, + }, }, status: { type: TINYINT(4), @@ -103,6 +205,36 @@ module.exports = app => { comment: '删除时间', }, }, { + validate: { + async withinStoreWebhookLimit() { + const storeId = Number(this.store_id || 0); + if (!Number.isFinite(storeId) || storeId <= 0) { + return; + } + + const store = await app.model.Store.findByPk(storeId, { + attributes: [ 'subject_config' ], + }); + const subjectConfig = app.model.Store && typeof app.model.Store.normalizeSubjectConfig === 'function' + ? app.model.Store.normalizeSubjectConfig(store && store.subject_config) + : { max_notice_webhook_count: 5 }; + const maxWebhookCount = Number(subjectConfig.max_notice_webhook_count || 5); + + const where = { + store_id: storeId, + }; + if (this.id) { + where.id = { + [Op.ne]: this.id, + }; + } + + const currentCount = await app.model.NotificationWebhook.count({ where }); + if (currentCount >= maxWebhookCount) { + throw new Error(`当前主体最多允许绑定 ${maxWebhookCount} 个消息推送接口`); + } + }, + }, tableName: 'wms_notification_webhook', freezeTableName: true, underscored: true, @@ -154,6 +286,11 @@ module.exports = app => { }); }; + NotificationWebhook.AVAILABLE_EVENTS = getAvailableEvents(); + NotificationWebhook.getAvailableEvents = getAvailableEvents; + NotificationWebhook.getAvailableEventCodes = () => getAvailableEvents().map(item => item.code); + NotificationWebhook.normalizeEvents = normalizeEvents; + NotificationWebhook.prototype.isEnabled = function() { return Number(this.status) === 1; }; diff --git a/app/model/print_record.js b/app/model/print_record.js index 3a33609..4360751 100644 --- a/app/model/print_record.js +++ b/app/model/print_record.js @@ -1,85 +1,85 @@ -"use strict"; +'use strict'; module.exports = app => { const { BIGINT, STRING, JSON, ENUM, TEXT, DATE } = app.Sequelize; - const PrintRecord = app.model.define("PrintRecord", { + const PrintRecord = app.model.define('PrintRecord', { id: { type: BIGINT.UNSIGNED, autoIncrement: true, primaryKey: true, - comment: "主键ID", + comment: '主键ID', }, warehouse_id: { type: BIGINT.UNSIGNED, allowNull: false, - comment: "仓库ID", + comment: '仓库ID', }, computer_id: { type: BIGINT.UNSIGNED, allowNull: false, - comment: "电脑ID", + comment: '电脑ID', }, printer: { type: STRING(100), allowNull: false, - comment: "打印机名称/标识", + comment: '打印机名称/标识', }, type: { type: STRING(50), allowNull: false, - comment: "打印类型", + comment: '打印类型', }, data: { type: JSON, allowNull: true, - comment: "打印数据(JSON格式)", + comment: '打印数据(JSON格式)', }, status: { - type: ENUM("pending", "sent", "success", "failed"), + type: ENUM('pending', 'sent', 'success', 'failed'), allowNull: false, - defaultValue: "pending", - comment: "打印状态:pending-待发送,sent-已发送,success-打印成功,failed-打印失败", + defaultValue: 'pending', + comment: '打印状态:pending-待发送,sent-已发送,success-打印成功,failed-打印失败', }, error_message: { type: TEXT, allowNull: true, - comment: "错误信息", + comment: '错误信息', }, sent_time: { type: DATE, allowNull: true, - comment: "发送时间", + comment: '发送时间', }, print_time: { type: DATE, allowNull: true, - comment: "打印完成时间", + comment: '打印完成时间', }, created_at: { type: DATE, allowNull: false, - defaultValue: app.Sequelize.literal("CURRENT_TIMESTAMP"), - comment: "创建时间", + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', }, updated_at: { type: DATE, allowNull: false, - defaultValue: app.Sequelize.literal("CURRENT_TIMESTAMP"), - comment: "更新时间", + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '更新时间', }, }, { - tableName: "wms_print_record", + tableName: 'wms_print_record', freezeTableName: true, underscored: false, timestamps: false, indexes: [ - { name: "idx_warehouse_id", fields: ["warehouse_id"] }, - { name: "idx_computer_id", fields: ["computer_id"] }, - { name: "idx_status", fields: ["status"] }, - { name: "idx_created_at", fields: ["created_at"] }, - { name: "idx_sent_time", fields: ["sent_time"] }, + { name: 'idx_warehouse_id', fields: [ 'warehouse_id' ] }, + { name: 'idx_computer_id', fields: [ 'computer_id' ] }, + { name: 'idx_status', fields: [ 'status' ] }, + { name: 'idx_created_at', fields: [ 'created_at' ] }, + { name: 'idx_sent_time', fields: [ 'sent_time' ] }, ], - comment: "打印记录表", + comment: '打印记录表', }); return PrintRecord; diff --git a/app/model/print_station_express.js b/app/model/print_station_express.js index eb6457a..602c022 100644 --- a/app/model/print_station_express.js +++ b/app/model/print_station_express.js @@ -1,4 +1,4 @@ -"use strict"; +'use strict'; module.exports = app => { const { INTEGER, BIGINT, STRING, DATE, TINYINT } = app.Sequelize; @@ -64,19 +64,19 @@ module.exports = app => { { unique: true, name: 'uk_print_station_express', - fields: ['print_station_id', 'express_id', 'deleted'], + fields: [ 'print_station_id', 'express_id', 'deleted' ], }, { name: 'idx_print_station_id', - fields: ['print_station_id'], + fields: [ 'print_station_id' ], }, { name: 'idx_express_id', - fields: ['express_id'], + fields: [ 'express_id' ], }, { name: 'idx_creator_id', - fields: ['creator_id'], + fields: [ 'creator_id' ], }, ], comment: '打印台快递-打印机绑定关系表', diff --git a/app/model/print_stations.js b/app/model/print_stations.js index 877d5ce..f4cb348 100644 --- a/app/model/print_stations.js +++ b/app/model/print_stations.js @@ -1,4 +1,4 @@ -"use strict"; +'use strict'; module.exports = app => { const { INTEGER, BIGINT, STRING, DATE, TINYINT } = app.Sequelize; @@ -14,10 +14,10 @@ module.exports = app => { allowNull: false, comment: '仓库ID', }, - default_printer_name:{ - type: STRING(50), - allowNull: true, - comment: '默认打印机名称', + default_printer_name: { + type: STRING(50), + allowNull: true, + comment: '默认打印机名称', }, name: { type: STRING(100), @@ -69,31 +69,31 @@ module.exports = app => { { unique: true, name: 'uk_print_station_id', - fields: ['print_station_id'], + fields: [ 'print_station_id' ], }, { name: 'idx_warehouse_id', - fields: ['warehouse_id'], + fields: [ 'warehouse_id' ], }, { name: 'idx_computer_id', - fields: ['computer_id'], + fields: [ 'computer_id' ], }, { name: 'idx_name', - fields: ['name'], + fields: [ 'name' ], }, { name: 'idx_custom_barcode', - fields: ['custom_barcode'], + fields: [ 'custom_barcode' ], }, { name: 'idx_creator_id', - fields: ['creator_id'], + fields: [ 'creator_id' ], }, { name: 'idx_create_at', - fields: ['create_at'], + fields: [ 'create_at' ], }, ], comment: '打印台信息表', diff --git a/app/model/store.js b/app/model/store.js index 25057f1..b59e68e 100644 --- a/app/model/store.js +++ b/app/model/store.js @@ -1,7 +1,75 @@ 'use strict'; module.exports = app => { - const { BIGINT, STRING, DATE, TINYINT } = app.Sequelize; + const { BIGINT, STRING, DATE, TINYINT, JSON: JSON_TYPE } = app.Sequelize; + const DEFAULT_MAX_NOTICE_WEBHOOK_COUNT = 5; + const DEFAULT_SUBJECT_CONFIG = Object.freeze({ + max_notice_webhook_count: DEFAULT_MAX_NOTICE_WEBHOOK_COUNT, + }); + + const normalizeBooleanFlag = (value, fieldName) => { + if (value === undefined || value === null || value === '') { + return undefined; + } + + if ([ true, 1, '1', 'true' ].includes(value)) { + return true; + } + + if ([ false, 0, '0', 'false' ].includes(value)) { + return false; + } + + throw new Error(`${fieldName} 必须是布尔值`); + }; + + const normalizeSubjectConfig = rawValue => { + if (rawValue === undefined || rawValue === null || rawValue === '') { + return { ...DEFAULT_SUBJECT_CONFIG }; + } + + let parsed = rawValue; + if (typeof parsed === 'string') { + try { + parsed = JSON.parse(parsed); + } catch (error) { + throw new Error('subject_config 必须是合法 JSON 对象'); + } + } + + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { + throw new Error('subject_config 必须是对象'); + } + + const normalized = { + ...parsed, + }; + + const rawLimit = parsed.max_notice_webhook_count; + if (rawLimit === undefined || rawLimit === null || rawLimit === '') { + normalized.max_notice_webhook_count = DEFAULT_MAX_NOTICE_WEBHOOK_COUNT; + } else { + const limit = Number(rawLimit); + if (!Number.isInteger(limit) || limit < 0 || limit > DEFAULT_MAX_NOTICE_WEBHOOK_COUNT) { + throw new Error(`subject_config.max_notice_webhook_count 必须是 0-${DEFAULT_MAX_NOTICE_WEBHOOK_COUNT} 的整数`); + } + normalized.max_notice_webhook_count = limit; + } + + if (Object.prototype.hasOwnProperty.call(parsed, 'webhook_enabled')) { + normalized.webhook_enabled = normalizeBooleanFlag(parsed.webhook_enabled, 'subject_config.webhook_enabled'); + } + + if (Object.prototype.hasOwnProperty.call(parsed, 'callback_strategy')) { + const strategy = String(parsed.callback_strategy || '').trim().toLowerCase(); + if (strategy && ![ 'sync', 'async' ].includes(strategy)) { + throw new Error('subject_config.callback_strategy 仅支持 sync 或 async'); + } + normalized.callback_strategy = strategy || 'async'; + } + + return normalized; + }; const Store = app.model.define('store', { id: { @@ -145,6 +213,23 @@ module.exports = app => { defaultValue: 107374182400, comment: '仓库文件存储配额', }, + subject_config: { + type: JSON_TYPE, + allowNull: true, + defaultValue: { ...DEFAULT_SUBJECT_CONFIG }, + comment: '主体配置JSON', + get() { + return normalizeSubjectConfig(this.getDataValue('subject_config')); + }, + set(value) { + this.setDataValue('subject_config', normalizeSubjectConfig(value)); + }, + validate: { + isValidSubjectConfig(value) { + normalizeSubjectConfig(value); + }, + }, + }, }, { tableName: 'wms_store', freezeTableName: true, @@ -216,6 +301,10 @@ module.exports = app => { }); }; + Store.DEFAULT_MAX_NOTICE_WEBHOOK_COUNT = DEFAULT_MAX_NOTICE_WEBHOOK_COUNT; + Store.DEFAULT_SUBJECT_CONFIG = DEFAULT_SUBJECT_CONFIG; + Store.normalizeSubjectConfig = normalizeSubjectConfig; + // 实例方法:检查商家是否启用 Store.prototype.isEnabled = function() { return this.status === 1; diff --git a/app/router.js b/app/router.js index 2fab394..1ed412f 100644 --- a/app/router.js +++ b/app/router.js @@ -11,25 +11,25 @@ module.exports = app => { // 奇门接口 router.post('/qimen', controller.home.qimen); - //预留第三方系统接口 + // 预留第三方系统接口 router.post('/api/warehouse', controller.home.warehouse); router.post('/api/store', controller.home.store); // 系统接口 PDA/WEB 统一入口 router.post('/system', controller.home.system); - //api文档相关 + // api文档相关 router.get('/api/docs', controller.docs.list); router.get('/api/docs/:docName', controller.docs.detail); router.get('/api/docs/:docName/raw', controller.docs.raw); - //打印模板 + // 打印模板 router.get('/template/xml/:id', controller.template.xml); - //打印台设置 + // 打印台设置 router.get('/auth/printSetting/:code', controller.auth.printerSetting); router.post('/auth/printSetting/', controller.auth.printerSetting); - //测试接口 + // 测试接口 router.get('/testSendData', controller.home.testSendData); }; diff --git a/app/service/apiMethods/print.js b/app/service/apiMethods/print.js index 689c6de..234da14 100644 --- a/app/service/apiMethods/print.js +++ b/app/service/apiMethods/print.js @@ -331,4 +331,4 @@ class PrintApiService extends Service { } } -module.exports = PrintApiService; \ No newline at end of file +module.exports = PrintApiService; diff --git a/app/service/apiMethods/user.js b/app/service/apiMethods/user.js index 4ba9f2a..f4cca86 100644 --- a/app/service/apiMethods/user.js +++ b/app/service/apiMethods/user.js @@ -12,4 +12,4 @@ class UserApiService extends Service { } } -module.exports = UserApiService; \ No newline at end of file +module.exports = UserApiService; diff --git a/app/service/systemMethods/index.js b/app/service/systemMethods/index.js index 8d5c965..f9841c9 100644 --- a/app/service/systemMethods/index.js +++ b/app/service/systemMethods/index.js @@ -366,8 +366,8 @@ class indexService extends MainService { const result = await service.systems.space.searchSpace(data); return this.success('ok', result); } - async getExpressList(data){ - + async getExpressList(data) { + return this.success('ok', { data: this.app.config.expressList, code: 200 }); } } diff --git a/app/service/systemMethods/order/archiveOrder.js b/app/service/systemMethods/order/archiveOrder.js index 5f11efc..1c146ef 100644 --- a/app/service/systemMethods/order/archiveOrder.js +++ b/app/service/systemMethods/order/archiveOrder.js @@ -42,7 +42,7 @@ class ArchiveOrderService extends OrderBaseService { ], offset, limit: pageSize, - order: [ [ 'delivery_time', 'DESC' ], [ 'updated_at', 'DESC' ], [ 'id', 'DESC' ] ], + order: [[ 'delivery_time', 'DESC' ], [ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]], raw: true, }); @@ -60,4 +60,4 @@ class ArchiveOrderService extends OrderBaseService { } } -module.exports = ArchiveOrderService; \ No newline at end of file +module.exports = ArchiveOrderService; diff --git a/app/service/systemMethods/order/base.js b/app/service/systemMethods/order/base.js index 9734701..e38eae6 100644 --- a/app/service/systemMethods/order/base.js +++ b/app/service/systemMethods/order/base.js @@ -215,4 +215,4 @@ class OrderBaseService extends MainService { } } -module.exports = OrderBaseService; \ No newline at end of file +module.exports = OrderBaseService; diff --git a/app/service/systemMethods/order/deliveryOrder.js b/app/service/systemMethods/order/deliveryOrder.js index 1094439..a6468fc 100644 --- a/app/service/systemMethods/order/deliveryOrder.js +++ b/app/service/systemMethods/order/deliveryOrder.js @@ -43,7 +43,7 @@ class DeliveryOrderService extends OrderBaseService { ], offset, limit: pageSize, - order: [ [ 'delivery_time', 'DESC' ], [ 'updated_at', 'DESC' ], [ 'id', 'DESC' ] ], + order: [[ 'delivery_time', 'DESC' ], [ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]], raw: true, }); @@ -61,4 +61,4 @@ class DeliveryOrderService extends OrderBaseService { } } -module.exports = DeliveryOrderService; \ No newline at end of file +module.exports = DeliveryOrderService; diff --git a/app/service/systemMethods/order/expectionOrder.js b/app/service/systemMethods/order/expectionOrder.js index f32cfac..310e1ec 100644 --- a/app/service/systemMethods/order/expectionOrder.js +++ b/app/service/systemMethods/order/expectionOrder.js @@ -70,7 +70,7 @@ class ExpectionOrderService extends OrderBaseService { ], offset, limit: pageSize, - order: [ [ 'updated_at', 'DESC' ], [ 'id', 'DESC' ] ], + order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]], raw: true, }); @@ -88,4 +88,4 @@ class ExpectionOrderService extends OrderBaseService { } } -module.exports = ExpectionOrderService; \ No newline at end of file +module.exports = ExpectionOrderService; diff --git a/app/service/systemMethods/order/index.js b/app/service/systemMethods/order/index.js index bb2a236..fc90e22 100644 --- a/app/service/systemMethods/order/index.js +++ b/app/service/systemMethods/order/index.js @@ -25,7 +25,7 @@ class OrderIndexService extends OrderBaseService { where, offset, limit: pageSize, - order: [ [ 'updated_at', 'DESC' ], [ 'id', 'DESC' ] ], + order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]], raw: true, }); @@ -51,7 +51,7 @@ class OrderIndexService extends OrderBaseService { const items = await OrderItemsModel.findAll({ where: { order_id: order.id }, - order: [ [ 'id', 'ASC' ] ], + order: [[ 'id', 'ASC' ]], raw: true, }); @@ -81,7 +81,7 @@ class OrderIndexService extends OrderBaseService { const items = await OrderItemsModel.findAll({ where: { order_id: order.id }, - order: [ [ 'id', 'ASC' ] ], + order: [[ 'id', 'ASC' ]], raw: true, }); @@ -106,13 +106,13 @@ class OrderIndexService extends OrderBaseService { const total = await DeliveryModel.count({ where }); const byStatusRows = await DeliveryModel.findAll({ where, - attributes: [ 'status', [ Sequelize.fn('COUNT', Sequelize.col('id')), 'count' ] ], + attributes: [ 'status', [ Sequelize.fn('COUNT', Sequelize.col('id')), 'count' ]], group: [ 'status' ], raw: true, }); const byOutboundRows = await DeliveryModel.findAll({ where, - attributes: [ 'outbound_status', [ Sequelize.fn('COUNT', Sequelize.col('id')), 'count' ] ], + attributes: [ 'outbound_status', [ Sequelize.fn('COUNT', Sequelize.col('id')), 'count' ]], group: [ 'outbound_status' ], raw: true, }); @@ -205,4 +205,4 @@ class OrderIndexService extends OrderBaseService { } } -module.exports = OrderIndexService; \ No newline at end of file +module.exports = OrderIndexService; diff --git a/app/service/systemMethods/order/pendingOrder.js b/app/service/systemMethods/order/pendingOrder.js index 912dbce..d57f9bb 100644 --- a/app/service/systemMethods/order/pendingOrder.js +++ b/app/service/systemMethods/order/pendingOrder.js @@ -48,7 +48,7 @@ class PendingOrderService extends OrderBaseService { ], offset, limit: pageSize, - order: [ [ 'updated_at', 'DESC' ], [ 'id', 'DESC' ] ], + order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]], raw: true, }); @@ -67,4 +67,4 @@ class PendingOrderService extends OrderBaseService { } } -module.exports = PendingOrderService; \ No newline at end of file +module.exports = PendingOrderService; diff --git a/app/service/systemMethods/order/reviewOrder.js b/app/service/systemMethods/order/reviewOrder.js index be546c6..3378e58 100644 --- a/app/service/systemMethods/order/reviewOrder.js +++ b/app/service/systemMethods/order/reviewOrder.js @@ -56,7 +56,7 @@ class ReviewOrderService extends OrderBaseService { ], offset, limit: pageSize, - order: [ [ 'operate_time', 'DESC' ], [ 'updated_at', 'DESC' ], [ 'id', 'DESC' ] ], + order: [[ 'operate_time', 'DESC' ], [ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]], raw: true, }); @@ -107,4 +107,4 @@ class ReviewOrderService extends OrderBaseService { } } -module.exports = ReviewOrderService; \ No newline at end of file +module.exports = ReviewOrderService; diff --git a/app/service/systemMethods/setting/account.js b/app/service/systemMethods/setting/account.js index 450d584..a1be451 100644 --- a/app/service/systemMethods/setting/account.js +++ b/app/service/systemMethods/setting/account.js @@ -103,4 +103,4 @@ class accountService extends MainService { } } -module.exports = accountService; \ No newline at end of file +module.exports = accountService; diff --git a/app/service/systemMethods/setting/permission.js b/app/service/systemMethods/setting/permission.js index d2f7b61..c6159ee 100644 --- a/app/service/systemMethods/setting/permission.js +++ b/app/service/systemMethods/setting/permission.js @@ -6,15 +6,9 @@ class permissionService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; -<<<<<<< HEAD const _noNeedRight = 'list,add,delete,update'; const _noNeedLog = '*'; const _noNeedAuth = 'list,add,delete,update'; -======= - const _noNeedRight = 'list'; - const _noNeedLog = '*'; - const _noNeedAuth = 'list'; ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } diff --git a/app/service/systemMethods/setting/printTemplate.js b/app/service/systemMethods/setting/printTemplate.js index ebae470..3f545ab 100644 --- a/app/service/systemMethods/setting/printTemplate.js +++ b/app/service/systemMethods/setting/printTemplate.js @@ -72,7 +72,7 @@ class printTemplateService extends MainService { const { service } = this; console.log('接收到根据业务类型查询模板请求:', data); const { businessType } = data; - if(!businessType){ + if (!businessType) { throw new Error('缺少业务类型参数'); } const list = await service.systems.setting.printTemplate.listTemplatesByType(businessType); diff --git a/app/service/systemMethods/setting/role.js b/app/service/systemMethods/setting/role.js index f5be600..f036b54 100644 --- a/app/service/systemMethods/setting/role.js +++ b/app/service/systemMethods/setting/role.js @@ -6,15 +6,9 @@ class roleService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; -<<<<<<< HEAD const _noNeedRight = 'list,add,delete,update,permission'; const _noNeedLog = '*'; const _noNeedAuth = 'list,add,delete,update,permission'; -======= - const _noNeedRight = 'list,add,delete,update'; - const _noNeedLog = '*'; - const _noNeedAuth = 'list,add,delete,update'; ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } diff --git a/app/service/systemMethods/stock/combo.js b/app/service/systemMethods/stock/combo.js index 0b81363..14015da 100644 --- a/app/service/systemMethods/stock/combo.js +++ b/app/service/systemMethods/stock/combo.js @@ -1 +1 @@ -//此处放组合商品明细的逻辑链路 \ No newline at end of file +// 此处放组合商品明细的逻辑链路 diff --git a/app/service/systemMethods/stock/store.js b/app/service/systemMethods/stock/store.js index b73f5a2..00eea09 100644 --- a/app/service/systemMethods/stock/store.js +++ b/app/service/systemMethods/stock/store.js @@ -1 +1 @@ -//此处放货主商品明细的逻辑链路 \ No newline at end of file +// 此处放货主商品明细的逻辑链路 diff --git a/app/service/systemMethods/stock/warehouse.js b/app/service/systemMethods/stock/warehouse.js index acd29ce..894b83a 100644 --- a/app/service/systemMethods/stock/warehouse.js +++ b/app/service/systemMethods/stock/warehouse.js @@ -3,147 +3,147 @@ const MainService = require('../../main'); class WarehouseService extends MainService { - constructor(ctx) { - super(ctx); - const _noNeedLogin = ''; - const _noNeedRight = 'list,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,getUnitList,createUnit,checkItemCodeUnique,deleteUnit,createProhibited,deleteProhibited,search'; - const _noNeedLog = 'list,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,checkItemCodeUnique,getUnitList,search'; - const _noNeedAuth = 'list,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,checkItemCodeUnique,getUnitList,search'; - this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); - } + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,getUnitList,createUnit,checkItemCodeUnique,deleteUnit,createProhibited,deleteProhibited,search'; + const _noNeedLog = 'list,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,checkItemCodeUnique,getUnitList,search'; + const _noNeedAuth = 'list,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,checkItemCodeUnique,getUnitList,search'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } - /** + /** * 仓库商品列表查询。 * @param {Object} data 请求体 * @param {Object} [data.pagination] 分页参数 * @param {Object} [data.where] 筛选条件 * @return {Promise} 统一成功包装响应 */ - async list(data = {}) { - const { service } = this; - const { pagination } = data; - const { where } = this.prepareWhereContext(data, { - specialFieldMap: { - barcode: { - bucket: 'barcode', - }, - prohibited_type: { - bucket: 'prohibited', - field: 'id', - }, - }, - }); - const result = await service.systems.stockStore.getWarehouseStock(where, pagination); - return this.success('ok', result); - } + async list(data = {}) { + const { service } = this; + const { pagination } = data; + const { where } = this.prepareWhereContext(data, { + specialFieldMap: { + barcode: { + bucket: 'barcode', + }, + prohibited_type: { + bucket: 'prohibited', + field: 'id', + }, + }, + }); + const result = await service.systems.stockStore.getWarehouseStock(where, pagination); + return this.success('ok', result); + } - /** + /** * 查询违禁品类型列表(系统预设 + 当前仓库)。 * @return {Promise} data 为违禁品类型数组 */ - async getProhibitedType() { - const { service } = this; - const result = await service.systems.stockStore.getProhibitedType(); - return this.success('ok', { data: result, code: 200 }); - } + async getProhibitedType() { + const { service } = this; + const result = await service.systems.stockStore.getProhibitedType(); + return this.success('ok', { data: result, code: 200 }); + } - /** + /** * 按商品条件获取仓库商品详情。 * @param {Object} data 请求体(常见包含 id/item_code) * @return {Promise} data 为单个商品详情对象 */ - async getInfo(data) { - const { service } = this; - const result = await service.systems.stockStore.getInfo(data); - return this.success('ok', { data: result, code: 200 }); - } + async getInfo(data) { + const { service } = this; + const result = await service.systems.stockStore.getInfo(data); + return this.success('ok', { data: result, code: 200 }); + } - /** + /** * 更新仓库商品资料。 * @param {Object} data 请求体(含商品主键与可编辑字段) * @return {Promise} data 为更新结果 */ - async saveWarehouseStock(data) { - const { service } = this; - const result = await service.systems.stockStore.saveWarehouseStock(data); - return this.success('ok', { data: result, code: 200 }); - } + async saveWarehouseStock(data) { + const { service } = this; + const result = await service.systems.stockStore.saveWarehouseStock(data); + return this.success('ok', { data: result, code: 200 }); + } - /** + /** * 新建仓库商品资料。 * @param {Object} data 请求体(必填字段见 stockStore 校验) * @return {Promise} data 为新建结果 */ - async createWarehouseStock(data) { - const { service } = this; - const result = await service.systems.stockStore.createWarehouseStock(data); - return this.success('ok', { data: result, code: 200 }); - } + async createWarehouseStock(data) { + const { service } = this; + const result = await service.systems.stockStore.createWarehouseStock(data); + return this.success('ok', { data: result, code: 200 }); + } - /** + /** * 查询商品条码列表。 * @param {Object} data 请求体(支持分页与关键字) * @return {Promise} data 为条码分页结果 */ - async getBarcodes(data) { - const { service } = this; - const result = await service.systems.stockStore.getBarcodes(data); - return this.success('ok', { data: result, code: 200 }); - } + async getBarcodes(data) { + const { service } = this; + const result = await service.systems.stockStore.getBarcodes(data); + return this.success('ok', { data: result, code: 200 }); + } - /** + /** * 保存商品条码信息。 * @param {Object} data 请求体(包含 stock_id 与条码字段) * @return {Promise} data 为保存结果 */ - async saveWarehouseStockBarcode(data) { - const { service } = this; - const result = await service.systems.stockStore.saveWarehouseStockBarcode(data); - return this.success('ok', { data: result, code: 200 }); - } + async saveWarehouseStockBarcode(data) { + const { service } = this; + const result = await service.systems.stockStore.saveWarehouseStockBarcode(data); + return this.success('ok', { data: result, code: 200 }); + } - /** + /** * 查询仓库与货主商品关联列表。 * @param {Object} data 请求体(支持筛选/分页) * @return {Promise} data 为关联分页结果 */ - async getStoreStocks(data) { - const { service } = this; - const result = await service.systems.stockStore.getStoreStocks(data); - return this.success('ok', { data: result, code: 200 }); - } + async getStoreStocks(data) { + const { service } = this; + const result = await service.systems.stockStore.getStoreStocks(data); + return this.success('ok', { data: result, code: 200 }); + } - /** + /** * 绑定货主商品。 * @param {Object} data 请求体(关联关系参数) * @return {Promise} 成功或失败均返回 success 包装,message 给出结果 */ - async bindItem(data) { - const { service } = this; - try { - const result = await service.systems.stockStore.bindItem(data); - return this.success('绑定成功', { data: result, code: 200 }); - } catch (e) { - return this.success(e.message, { code: 200 }); - } - } + async bindItem(data) { + const { service } = this; + try { + const result = await service.systems.stockStore.bindItem(data); + return this.success('绑定成功', { data: result, code: 200 }); + } catch (e) { + return this.success(e.message, { code: 200 }); + } + } - /** + /** * 解绑货主商品。 * @param {Object} data 请求体(关联关系参数) * @return {Promise} 成功或失败均返回 success 包装,message 给出结果 */ - async unbindItem(data) { - const { service } = this; - try { - const result = await service.systems.stockStore.unbindItem(data); - return this.success('解绑成功', { data: result, code: 200 }); - } catch (e) { - return this.success(e.message, { code: 200 }); - } - } + async unbindItem(data) { + const { service } = this; + try { + const result = await service.systems.stockStore.unbindItem(data); + return this.success('解绑成功', { data: result, code: 200 }); + } catch (e) { + return this.success(e.message, { code: 200 }); + } + } - /** + /** * 校验商品编码唯一性。 * @param {Object} data 请求体 * @param {number} [data.id] 商品ID(编辑场景) @@ -151,333 +151,333 @@ class WarehouseService extends MainService { * @param {number} data.store_id 货主ID * @return {Promise} data 为布尔或冲突详情 */ - async checkItemCodeUnique(data) { - const { ctx, service } = this; - const { id, item_code, store_id } = data; - console.log(data); - try { - if (!item_code || !store_id) { - return this.fail('参数错误'); - } - const result = await service.systems.stockStore.checkItemCodeUnique(id, item_code, store_id, ctx.user.store_id); - return this.success('获取成功', { data: result, code: 200 }); - } catch (error) { - return this.fail(error.message); - } - } + async checkItemCodeUnique(data) { + const { ctx, service } = this; + const { id, item_code, store_id } = data; + console.log(data); + try { + if (!item_code || !store_id) { + return this.fail('参数错误'); + } + const result = await service.systems.stockStore.checkItemCodeUnique(id, item_code, store_id, ctx.user.store_id); + return this.success('获取成功', { data: result, code: 200 }); + } catch (error) { + return this.fail(error.message); + } + } - /** + /** * 查询库存操作日志。 * @param {Object} data 请求体(会自动注入当前 warehouseId) * @return {Promise} data 为日志分页结果 */ - async queryStockLogs(data) { - console.log('请求'); - const { ctx } = this; - try { - const { service } = this; - data.warehouseId = ctx.user.store_id; - const result = await service.systems.operationLog.queryStockLogs(data); - return this.success('ok', { data: result, code: 200 }); - } catch (e) { - console.log(e); - return this.success(e.message, { code: 200 }); - } - } + async queryStockLogs(data) { + console.log('请求'); + const { ctx } = this; + try { + const { service } = this; + data.warehouseId = ctx.user.store_id; + const result = await service.systems.operationLog.queryStockLogs(data); + return this.success('ok', { data: result, code: 200 }); + } catch (e) { + console.log(e); + return this.success(e.message, { code: 200 }); + } + } - /** + /** * 批量删除仓库商品资料(软删除)。 * @param {Object} data 请求体(含 ids) * @return {Promise} data 为删除结果,message 为业务提示 */ - async handleBatchDelete(data) { - const { service } = this; - try { - const result = await service.systems.stockStore.handleBatchDelete(data); - return this.success(result.message, { data: result.data, code: result.code }); - } catch (e) { - console.log(e); - return this.success(e.message, { code: 200 }); - } - } + async handleBatchDelete(data) { + const { service } = this; + try { + const result = await service.systems.stockStore.handleBatchDelete(data); + return this.success(result.message, { data: result.data, code: result.code }); + } catch (e) { + console.log(e); + return this.success(e.message, { code: 200 }); + } + } - /** + /** * 删除库存单位。 * @param {Object} data 请求体(含单位ID) * @return {Promise} data 为删除结果,message 为业务提示 */ - async deleteUnit(data) { - const { service } = this; - try { - const result = await service.systems.stockStore.deleteUnit(data); - return this.success(result.message, { data: result.data, code: result.code }); - } catch (e) { - console.log(e); - return this.success(e.message, { code: 200 }); - } - } + async deleteUnit(data) { + const { service } = this; + try { + const result = await service.systems.stockStore.deleteUnit(data); + return this.success(result.message, { data: result.data, code: result.code }); + } catch (e) { + console.log(e); + return this.success(e.message, { code: 200 }); + } + } - /** + /** * 删除违禁品类型。 * @param {Object} data 请求体(含类型ID) * @return {Promise} data 为删除结果,message 为业务提示 */ - async deleteProhibited(data) { - const { service } = this; - try { - const result = await service.systems.stockStore.deleteProhibited(data); - return this.success(result.message, { data: result.data, code: result.code }); - } catch (e) { - console.log(e); - return this.success(e.message, { code: 200 }); - } - } + async deleteProhibited(data) { + const { service } = this; + try { + const result = await service.systems.stockStore.deleteProhibited(data); + return this.success(result.message, { data: result.data, code: result.code }); + } catch (e) { + console.log(e); + return this.success(e.message, { code: 200 }); + } + } - /** + /** * 批量修改商品资料字段。 * @param {Object} data 请求体(含 ids/method/value) * @return {Promise} data 为修改结果,message 为业务提示 */ - async handleBatchChange(data) { - const { service } = this; - try { - const result = await service.systems.stockStore.handleBatchChange(data); - return this.success(result.message, { data: result.data, code: result.code }); - } catch (e) { - console.log(e); - return this.success(e.message, { code: 405 }); - } - } + async handleBatchChange(data) { + const { service } = this; + try { + const result = await service.systems.stockStore.handleBatchChange(data); + return this.success(result.message, { data: result.data, code: result.code }); + } catch (e) { + console.log(e); + return this.success(e.message, { code: 405 }); + } + } - /** + /** * 查询可用库存单位(系统预设 + 仓库自定义)。 * @return {Promise} data 为单位数组 */ - async getStockUnits() { - console.log('query_getStockUnits'); - const { ctx } = this; - const warehouse_id = ctx.user.store_id; + async getStockUnits() { + console.log('query_getStockUnits'); + const { ctx } = this; + const warehouse_id = ctx.user.store_id; - try { - const where = { - [ctx.app.Sequelize.Op.or]: [ - { warehouse_id: null }, - { warehouse_id }, - ], - }; + try { + const where = { + [ctx.app.Sequelize.Op.or]: [ + { warehouse_id: null }, + { warehouse_id }, + ], + }; - const units = await ctx.model.StockUnit.findAll({ - where, - order: [ - [ 'warehouse_id', 'ASC' ], - [ 'created_at', 'DESC' ], - ], - }); - return this.success('ok', { data: units, code: 200 }); - } catch (error) { - console.log(error); - return this.fail(error.message); - } - } + const units = await ctx.model.StockUnit.findAll({ + where, + order: [ + [ 'warehouse_id', 'ASC' ], + [ 'created_at', 'DESC' ], + ], + }); + return this.success('ok', { data: units, code: 200 }); + } catch (error) { + console.log(error); + return this.fail(error.message); + } + } - /** + /** * 查询当前仓库自定义单位列表。 * @return {Promise} data 为单位数组 */ - async getUnitList() { - console.log('query_getUnitList'); - const { ctx } = this; - const warehouse_id = ctx.user.store_id; + async getUnitList() { + console.log('query_getUnitList'); + const { ctx } = this; + const warehouse_id = ctx.user.store_id; - try { - const where = { - warehouse_id, - }; + try { + const where = { + warehouse_id, + }; - const units = await ctx.model.StockUnit.findAll({ - where, - order: [ - [ 'warehouse_id', 'ASC' ], - [ 'created_at', 'DESC' ], - ], - }); - return this.success('ok', { data: units, code: 200 }); - } catch (error) { - console.log(error); - return this.fail(error.message); - } - } + const units = await ctx.model.StockUnit.findAll({ + where, + order: [ + [ 'warehouse_id', 'ASC' ], + [ 'created_at', 'DESC' ], + ], + }); + return this.success('ok', { data: units, code: 200 }); + } catch (error) { + console.log(error); + return this.fail(error.message); + } + } - /** + /** * 新增违禁品类型。 * @param {Object} data 请求体 * @param {string} data.name 违禁品类型名称 * @return {Promise} 成功返回 success;参数校验失败时直接写入 ctx.body */ - async createProhibited(data) { - console.log('createProhibited', data); - const { ctx } = this; - const warehouse_id = ctx.user.store_id || null; - const { name } = data; + async createProhibited(data) { + console.log('createProhibited', data); + const { ctx } = this; + const warehouse_id = ctx.user.store_id || null; + const { name } = data; - if (!name || name.trim() === '') { - ctx.body = { - code: 400, - message: '违禁品类型名称不能为空', - }; - return; - } + if (!name || name.trim() === '') { + ctx.body = { + code: 400, + message: '违禁品类型名称不能为空', + }; + return; + } - const trimmedName = name.trim(); + const trimmedName = name.trim(); - try { - const systemUnit = await ctx.model.ProhibitedType.findOne({ - where: { - type_name: trimmedName, - warehouse_id: null, - }, - }); + try { + const systemUnit = await ctx.model.ProhibitedType.findOne({ + where: { + type_name: trimmedName, + warehouse_id: null, + }, + }); - if (systemUnit) { - ctx.body = { - code: 400, - message: '该违禁品类型是系统预设,不允许添加', - }; - return; - } + if (systemUnit) { + ctx.body = { + code: 400, + message: '该违禁品类型是系统预设,不允许添加', + }; + return; + } - const existUnit = await ctx.model.ProhibitedType.findOne({ - where: { - type_name: trimmedName, - warehouse_id, - }, - }); + const existUnit = await ctx.model.ProhibitedType.findOne({ + where: { + type_name: trimmedName, + warehouse_id, + }, + }); - if (existUnit) { - ctx.body = { - code: 400, - message: '该违禁品类型名称已存在', - }; - return; - } + if (existUnit) { + ctx.body = { + code: 400, + message: '该违禁品类型名称已存在', + }; + return; + } - await ctx.model.ProhibitedType.create({ - type_name: trimmedName, - warehouse_id, - }); + await ctx.model.ProhibitedType.create({ + type_name: trimmedName, + warehouse_id, + }); - const where = {}; - if (warehouse_id) { - where[ctx.app.Sequelize.Op.or] = [ - { warehouse_id: null }, - { warehouse_id }, - ]; - } else { - where.warehouse_id = null; - } + const where = {}; + if (warehouse_id) { + where[ctx.app.Sequelize.Op.or] = [ + { warehouse_id: null }, + { warehouse_id }, + ]; + } else { + where.warehouse_id = null; + } - await ctx.model.ProhibitedType.findAll({ - where, - order: [ - [ 'warehouse_id', 'ASC' ], - [ 'created_at', 'DESC' ], - ], - }); - return this.success('添加成功', { code: 200 }); - } catch (error) { - console.log(error); - return this.success('创建违禁品类型失败', { code: 405 }); - } - } + await ctx.model.ProhibitedType.findAll({ + where, + order: [ + [ 'warehouse_id', 'ASC' ], + [ 'created_at', 'DESC' ], + ], + }); + return this.success('添加成功', { code: 200 }); + } catch (error) { + console.log(error); + return this.success('创建违禁品类型失败', { code: 405 }); + } + } - /** + /** * 新增库存单位。 * @return {Promise} 成功返回 success;参数校验失败时直接写入 ctx.body */ - async createUnit() { - const { ctx } = this; - const warehouse_id = ctx.user.store_id || null; - const { name } = ctx.request.body; + async createUnit() { + const { ctx } = this; + const warehouse_id = ctx.user.store_id || null; + const { name } = ctx.request.body; - if (!name || name.trim() === '') { - ctx.body = { - code: 400, - message: '单位名称不能为空', - }; - return; - } + if (!name || name.trim() === '') { + ctx.body = { + code: 400, + message: '单位名称不能为空', + }; + return; + } - const trimmedName = name.trim(); + const trimmedName = name.trim(); - try { - const systemUnit = await ctx.model.StockUnit.findOne({ - where: { - name: trimmedName, - warehouse_id: null, - }, - }); + try { + const systemUnit = await ctx.model.StockUnit.findOne({ + where: { + name: trimmedName, + warehouse_id: null, + }, + }); - if (systemUnit) { - ctx.body = { - code: 400, - message: '该单位是系统预设单位,不允许添加', - }; - return; - } + if (systemUnit) { + ctx.body = { + code: 400, + message: '该单位是系统预设单位,不允许添加', + }; + return; + } - const existUnit = await ctx.model.StockUnit.findOne({ - where: { - name: trimmedName, - warehouse_id, - }, - }); + const existUnit = await ctx.model.StockUnit.findOne({ + where: { + name: trimmedName, + warehouse_id, + }, + }); - if (existUnit) { - ctx.body = { - code: 400, - message: '该单位名称已存在', - }; - return; - } + if (existUnit) { + ctx.body = { + code: 400, + message: '该单位名称已存在', + }; + return; + } - await ctx.model.StockUnit.create({ - name: trimmedName, - warehouse_id, - }); + await ctx.model.StockUnit.create({ + name: trimmedName, + warehouse_id, + }); - const where = {}; - if (warehouse_id) { - where[ctx.app.Sequelize.Op.or] = [ - { warehouse_id: null }, - { warehouse_id }, - ]; - } else { - where.warehouse_id = null; - } + const where = {}; + if (warehouse_id) { + where[ctx.app.Sequelize.Op.or] = [ + { warehouse_id: null }, + { warehouse_id }, + ]; + } else { + where.warehouse_id = null; + } - await ctx.model.StockUnit.findAll({ - where, - order: [ - [ 'warehouse_id', 'ASC' ], - [ 'created_at', 'DESC' ], - ], - }); - return this.success('添加成功', { code: 200 }); - } catch (error) { - return this.success('创建库存单位失败', { code: 200 }); - } - } + await ctx.model.StockUnit.findAll({ + where, + order: [ + [ 'warehouse_id', 'ASC' ], + [ 'created_at', 'DESC' ], + ], + }); + return this.success('添加成功', { code: 200 }); + } catch (error) { + return this.success('创建库存单位失败', { code: 200 }); + } + } - /** + /** * 快捷搜索仓库商品。 * @param {Object} data 请求体(含 keyword) * @return {Promise} data 为搜索结果数组 */ - async search(data) { - const { service } = this; - const result = await service.systems.stockStore.search(data); - return this.success('ok', result); - } + async search(data) { + const { service } = this; + const result = await service.systems.stockStore.search(data); + return this.success('ok', result); + } } -module.exports = WarehouseService; \ No newline at end of file +module.exports = WarehouseService; diff --git a/app/service/systemMethods/storage/entry.js b/app/service/systemMethods/storage/entry.js index da68a84..0880a02 100644 --- a/app/service/systemMethods/storage/entry.js +++ b/app/service/systemMethods/storage/entry.js @@ -6,16 +6,16 @@ const MainService = require('../../main'); * 注意:当前实现仅为包装层,实际业务逻辑完全依赖底层 service 的方法实现。 */ class entryService extends MainService { - constructor(ctx) { - super(ctx); - const _noNeedLogin = ''; - const _noNeedRight = 'list,get,create,addDetail,deleteDetail,detailChange,cancel,completeEntry'; - const _noNeedLog = 'list,get,addDetail,deleteDetail,detailChange'; - const _noNeedAuth = 'list,get,create,addDetail,deleteDetail,detailChange,cancel,completeEntry'; - this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); - } + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list,get,create,addDetail,deleteDetail,detailChange,cancel,completeEntry'; + const _noNeedLog = 'list,get,addDetail,deleteDetail,detailChange'; + const _noNeedAuth = 'list,get,create,addDetail,deleteDetail,detailChange,cancel,completeEntry'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } - /** + /** * 入库单列表查询。 * @param {Object} data 请求体 * @param {Object} [data.pagination] 分页参数 @@ -23,97 +23,97 @@ class entryService extends MainService { * @param {Object} [data.sort] 排序参数 * @return {Promise} 统一 success 包装 */ - async list(data = {}) { - const { service } = this; - const { pagination, sort } = data; - const { where } = this.prepareWhereContext(data, { - specialFieldMap: { - quickWhere: { - bucket: 'quick', - }, - }, - }); - const result = await service.systems.storage.entry.list(where, pagination, sort); - return this.success('ok', result); - } + async list(data = {}) { + const { service } = this; + const { pagination, sort } = data; + const { where } = this.prepareWhereContext(data, { + specialFieldMap: { + quickWhere: { + bucket: 'quick', + }, + }, + }); + const result = await service.systems.storage.entry.list(where, pagination, sort); + return this.success('ok', result); + } - /** + /** * 查询入库单详情。 * @param {Object} data 请求体 * @param {number} [data.id] 入库单ID * @param {string} [data.entry_order_code] 入库单号 * @return {Promise} 统一 success 包装 */ - async get(data = {}) { - const { service } = this; - const result = await service.systems.storage.entry.get(data); - return this.success('ok', result); - } + async get(data = {}) { + const { service } = this; + const result = await service.systems.storage.entry.get(data); + return this.success('ok', result); + } - /** + /** * 新建入库单。 * @param {Object} data 请求体 * @return {Promise} 统一 success 包装 */ - async create(data = {}) { - const { service } = this; - const result = await service.systems.storage.entry.create(data); - return this.success('ok', result); - } + async create(data = {}) { + const { service } = this; + const result = await service.systems.storage.entry.create(data); + return this.success('ok', result); + } - /** + /** * 新增入库明细。 * @param {Object} data 请求体 * @return {Promise} 统一 success 包装 */ - async addDetail(data = {}) { - const { service } = this; - const result = await service.systems.storage.entry.addDetail(data); - return this.success('ok', result); - } + async addDetail(data = {}) { + const { service } = this; + const result = await service.systems.storage.entry.addDetail(data); + return this.success('ok', result); + } - /** + /** * 删除入库明细。 * @param {Object} data 请求体 * @return {Promise} 统一 success 包装 */ - async deleteDetail(data = {}) { - const { service } = this; - const result = await service.systems.storage.entry.deleteDetail(data); - return this.success('ok', result); - } + async deleteDetail(data = {}) { + const { service } = this; + const result = await service.systems.storage.entry.deleteDetail(data); + return this.success('ok', result); + } - /** + /** * 修改入库明细。 * @param {Object} data 请求体 * @return {Promise} 统一 success 包装 */ - async detailChange(data = {}) { - const { service } = this; - const result = await service.systems.storage.entry.detailChange(data); - return this.success('ok', result); - } + async detailChange(data = {}) { + const { service } = this; + const result = await service.systems.storage.entry.detailChange(data); + return this.success('ok', result); + } - /** + /** * 作废入库单。 * @param {Object} data 请求体 * @return {Promise} 统一 success 包装 */ - async cancel(data = {}) { - const { service } = this; - const result = await service.systems.storage.entry.cancel(data); - return this.success('ok', result); - } + async cancel(data = {}) { + const { service } = this; + const result = await service.systems.storage.entry.cancel(data); + return this.success('ok', result); + } - /** + /** * 完成入库单。 * @param {Object} data 请求体 * @return {Promise} 统一 success 包装 */ - async completeEntry(data = {}) { - const { service } = this; - const result = await service.systems.storage.entry.completeEntry(data); - return this.success('ok', result); - } + async completeEntry(data = {}) { + const { service } = this; + const result = await service.systems.storage.entry.completeEntry(data); + return this.success('ok', result); + } } -module.exports = entryService; \ No newline at end of file +module.exports = entryService; diff --git a/app/service/systemMethods/storage/receiving.js b/app/service/systemMethods/storage/receiving.js index ecb384b..731b3ac 100644 --- a/app/service/systemMethods/storage/receiving.js +++ b/app/service/systemMethods/storage/receiving.js @@ -56,7 +56,7 @@ class configService extends MainService { * @param {number[]} data.ids 收货单ID数组 * @return {Promise} 统一成功包装响应 */ - async batchCancelReceiving(data){ + async batchCancelReceiving(data) { const { service } = this; const result = await service.systems.storage.receiving.batchCancelReceiving(data); return this.success('ok', result); diff --git a/app/service/systemMethods/user.js b/app/service/systemMethods/user.js index 2c6ff78..2de6096 100644 --- a/app/service/systemMethods/user.js +++ b/app/service/systemMethods/user.js @@ -6,10 +6,8 @@ class userService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = 'login,loginByCode,register,getLoginWechatCode'; - const _noNeedLogin = 'login,loginByCode,register,getLoginWechatCode'; const _noNeedRight = '*'; const _noNeedLog = 'info,getBindWechatCode,getLoginWechatCode'; - const _noNeedLog = 'info,getBindWechatCode,getLoginWechatCode'; const _noNeedAuth = '*'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -27,7 +25,7 @@ class userService extends MainService { async loginByCode(data) { const { service } = this; const code = typeof data?.code === 'string' ? data.code.trim() : ''; - console.log('code', data.code,code); + console.log('code', data.code, code); if (!code) { return this.fail('1111登录失败:缺少登录码 code', { success: false, @@ -87,7 +85,7 @@ class userService extends MainService { const result = await service.systems.auth.user.changeRole(data); return this.success('获取成功', result, 200); } - //注册 + // 注册 async register(data) { const { service } = this; const result = await service.systems.auth.user.register(data); diff --git a/app/service/systems/auth/role_permission.js b/app/service/systems/auth/role_permission.js index 19274cf..6e42878 100644 --- a/app/service/systems/auth/role_permission.js +++ b/app/service/systems/auth/role_permission.js @@ -9,7 +9,7 @@ class RolePermissionService extends Service { } if (Array.isArray(rawValue)) { - const normalizedItems = rawValue.map(item => typeof item === 'string' ? item.trim() : item); + const normalizedItems = rawValue.map(item => (typeof item === 'string' ? item.trim() : item)); if (normalizedItems.some(item => item === '*')) { return { allAccess: true, permissionIds: [] }; } diff --git a/app/service/systems/auth/user.js b/app/service/systems/auth/user.js index d34baa7..76c94b1 100644 --- a/app/service/systems/auth/user.js +++ b/app/service/systems/auth/user.js @@ -493,7 +493,6 @@ class UserService extends Service { } /** -<<<<<<< HEAD * 登录码登录:使用Ye4s登录码进行登录 * @param {string} code 登录码(WECHAT_LOGIN_CODE) * @return {Object} 登录结果 @@ -504,18 +503,6 @@ class UserService extends Service { try { const rawCode = typeof code === 'string' ? code.trim() : ''; if (!rawCode) { -======= - * 登录码登录:使用本系统缓存登录码完成登录 - * @param {string} code 登录码(WECHAT_LOGIN_CODE) - * @return {Object} 登录结果 - */ - async loginByCode(code) { - const { app } = this; - - try { - const normalizedCode = this.parseWechatBindCode(code); - if (!normalizedCode) { ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 return { success: false, data: null, @@ -524,7 +511,6 @@ class UserService extends Service { }; } -<<<<<<< HEAD const candidateSet = new Set([ rawCode ]); try { const decoded = Buffer.from(rawCode, 'base64').toString('utf8').trim(); @@ -565,17 +551,6 @@ class UserService extends Service { }); if (!rows || rows.length === 0) { -======= - const codeCacheKey = this.getWechatLoginCodeCacheKey(normalizedCode); - let codeState = null; - try { - codeState = await this.app.getCacheAsync(codeCacheKey); - } catch (cacheErr) { - app.coreLogger.warn(`读取登录码缓存失败: ${cacheErr.message}`); - } - - if (!codeState) { ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 return { success: false, data: null, @@ -584,7 +559,6 @@ class UserService extends Service { }; } -<<<<<<< HEAD const ye4sUserId = Number(rows[0].id); if (!Number.isFinite(ye4sUserId) || ye4sUserId <= 0) { return { @@ -596,44 +570,6 @@ class UserService extends Service { } return await this.loginByYe4sUserId(ye4sUserId); -======= - const codeStateWithCode = { - ...(codeState || {}), - code: normalizedCode, - }; - - let loginResponse = await this.tryBuildWechatLoginTokenFromState(codeState.client_code || '', codeStateWithCode); - if (loginResponse && loginResponse.success) { - return loginResponse; - } - - const clientCode = this.parseWechatBindCode(codeState && codeState.client_code); - if (clientCode) { - let clientState = null; - try { - clientState = await this.app.getCacheAsync(this.getWechatLoginClientCacheKey(clientCode)); - } catch (cacheErr) { - app.coreLogger.warn(`读取客户端登录状态缓存失败: ${cacheErr.message}`); - } - - if (clientState) { - loginResponse = await this.tryBuildWechatLoginTokenFromState(clientCode, { - ...clientState, - code: normalizedCode, - }); - if (loginResponse && loginResponse.success) { - return loginResponse; - } - } - } - - return { - success: false, - data: null, - code: 0, - message: '登录码尚未授权,请扫码确认后重试', - }; ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 } catch (error) { app.coreLogger.error(`登录码登录异常: ${error.message}`); return { @@ -1111,11 +1047,7 @@ class UserService extends Service { }; } -<<<<<<< HEAD const cacheKey = this.getWechatBindCacheKey(normalizedAccountId); -======= - const cacheKey = this.getWechatBindCacheKey(accountId); ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 const useLongPoll = this.shouldUseWechatBindLongPoll(data); const waitTimeoutMs = this.getWechatLongPollTimeoutMs(); @@ -1126,11 +1058,7 @@ class UserService extends Service { app.coreLogger.warn(`读取微信绑定缓存失败: ${cacheErr.message}`); } -<<<<<<< HEAD const refreshed = await this.refreshWechatBindState(normalizedAccountId, cachedState, { -======= - const refreshed = await this.refreshWechatBindState(accountId, cachedState, { ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 forceNewCode: false, }); @@ -1143,22 +1071,14 @@ class UserService extends Service { }; } -<<<<<<< HEAD const waitResult = await this.waitForWechatBindEvent(normalizedAccountId, waitTimeoutMs); -======= - const waitResult = await this.waitForWechatBindEvent(accountId, waitTimeoutMs); ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 try { cachedState = await this.app.getCacheAsync(cacheKey); } catch (cacheErr) { app.coreLogger.warn(`读取微信绑定缓存失败: ${cacheErr.message}`); } -<<<<<<< HEAD const nextState = await this.refreshWechatBindState(normalizedAccountId, cachedState, { -======= - const nextState = await this.refreshWechatBindState(accountId, cachedState, { ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 forceNewCode: waitResult.timed_out, }); @@ -1472,11 +1392,7 @@ class UserService extends Service { } } -<<<<<<< HEAD const cacheKey = this.getWechatBindCacheKey(normalizedAccountId); -======= - const cacheKey = this.getWechatBindCacheKey(accountId); ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 await this.setWechatBindCache(cacheKey, null, 1); await this.publishWechatBindEvent(normalizedAccountId, { status: 'unbound', @@ -1509,6 +1425,7 @@ class UserService extends Service { /** * 生成统一登录成功结构 * @param {Object} user + * @param options * @return {Object} */ async buildLoginResult(user, options = {}) { diff --git a/app/service/systems/excel.js b/app/service/systems/excel.js index 88f1adf..cad0bd6 100644 --- a/app/service/systems/excel.js +++ b/app/service/systems/excel.js @@ -1,5 +1,6 @@ 'use strict'; +const crypto = require('crypto'); const fs = require('fs'); const path = require('path'); const { Readable } = require('stream'); @@ -588,6 +589,8 @@ class ExcelService extends Service { ...options, bookType, }); + const md5Hash = crypto.createHash('md5').update(buffer).digest('hex'); + const sha1Hash = crypto.createHash('sha1').update(buffer).digest('hex'); const uploadKey = this.buildUploadKey(safeFilename, { dir, key }); const uploadStream = Readable.from(buffer); @@ -620,6 +623,8 @@ class ExcelService extends Service { uploaderDept, expireTime, expireDays, + md5Hash, + sha1Hash, }); fileRecord = recordResult && (recordResult.data || recordResult); diff --git a/app/service/systems/notice/drivers/generic.js b/app/service/systems/notice/drivers/generic.js new file mode 100644 index 0000000..d618d99 --- /dev/null +++ b/app/service/systems/notice/drivers/generic.js @@ -0,0 +1,33 @@ +'use strict'; + +class CustomizeWebhookDriver { + constructor(ctx, options = {}) { + this.ctx = ctx; + this.options = options; + } + + async send({ hook, payload }) { + const requestOptions = { + method: 'POST', + headers: { + 'content-type': 'application/json', + }, + timeout: 5000, + dataType: 'json', + contentType: 'json', + data: payload, + }; + + const response = await this.ctx.curl(String(hook.hook_url || ''), requestOptions); + + return { + hookId: Number(hook && hook.id) || 0, + hookType: String(hook && hook.hook_type || this.options.hookType || 'customize'), + hookUrl: String(hook && hook.hook_url || ''), + status: Number(response && response.status) || 200, + response: response && response.data !== undefined ? response.data : null, + }; + } +} + +module.exports = CustomizeWebhookDriver; diff --git a/app/service/systems/notice/drivers/wecom.js b/app/service/systems/notice/drivers/wecom.js new file mode 100644 index 0000000..e8504f6 --- /dev/null +++ b/app/service/systems/notice/drivers/wecom.js @@ -0,0 +1,82 @@ +'use strict'; + +class WecomWebhookDriver { + constructor(ctx, options = {}) { + this.ctx = ctx; + this.options = options; + } + + buildTextContent(payload = {}) { + const message = payload.message || {}; + const lines = [ + String(message.title || '').trim(), + String(message.content || message.body || '').trim(), + ].filter(Boolean); + + if (message.url) { + lines.push(`链接:${String(message.url).trim()}`); + } + + return lines.join('\n') || '您有一条新的业务通知'; + } + + buildMarkdownContent(payload = {}) { + const message = payload.message || {}; + const title = String(message.title || '业务通知').trim(); + const content = String(message.content || message.body || '').trim(); + const url = String(message.url || '').trim(); + const lines = [ + `**${title}**`, + content ? `>${content}` : '', + url ? `[点击查看](${url})` : '', + ].filter(Boolean); + + return lines.join('\n'); + } + + buildRequestData(payload = {}) { + const messageType = String(payload.message && payload.message.type || 'text').trim().toLowerCase(); + + if ([ 'image', 'file' ].includes(messageType)) { + return { + msgtype: 'markdown', + markdown: { + content: this.buildMarkdownContent(payload), + }, + }; + } + + return { + msgtype: 'text', + text: { + content: this.buildTextContent(payload), + }, + }; + } + + async send({ hook, payload }) { + const requestData = this.buildRequestData(payload); + const requestOptions = { + method: 'POST', + headers: { + 'content-type': 'application/json', + }, + timeout: 5000, + dataType: 'json', + contentType: 'json', + data: requestData, + }; + + const response = await this.ctx.curl(String(hook && hook.hook_url || ''), requestOptions); + + return { + hookId: Number(hook && hook.id) || 0, + hookType: 'wecom', + hookUrl: String(hook && hook.hook_url || ''), + status: Number(response && response.status) || 200, + response: response && response.data !== undefined ? response.data : null, + }; + } +} + +module.exports = WecomWebhookDriver; diff --git a/app/service/systems/notice/index.js b/app/service/systems/notice/index.js new file mode 100644 index 0000000..2aed6c7 --- /dev/null +++ b/app/service/systems/notice/index.js @@ -0,0 +1,883 @@ +'use strict'; + +const { Service } = require('egg'); +const CustomizeWebhookDriver = require('./drivers/generic'); +const WecomWebhookDriver = require('./drivers/wecom'); + +const MESSAGE_TYPE_MAP = Object.freeze({ + text: 'text', + txt: 'text', + message: 'text', + 文本: 'text', + image: 'image', + img: 'image', + picture: 'image', + 图片: 'image', + file: 'file', + attachment: 'file', + 文件: 'file', +}); +const DEFAULT_MAX_NOTICE_WEBHOOK_COUNT = 5; +const DEFAULT_RETRY_DELAYS_MS = Object.freeze([ 3000, 6000, 12000 ]); +const EVENT_CODE_PATTERN = /^[a-z_][a-z0-9_]*$/; +const DEFAULT_REGISTERED_EVENT_CODES = Object.freeze([ 'all', '*', 'receiving_completed' ]); +const DRIVER_TYPE_ALIASES = Object.freeze({ + custom: 'customize', + customize: 'customize', + generic: 'customize', + wecom: 'wecom', +}); + +class NoticeService extends Service { + /** + * 统一通知服务构造函数,初始化驱动缓存。 + * @param {object} ctx Egg 上下文 + */ + constructor(ctx) { + super(ctx); + this.driverCache = new Map(); + } + + /** + * 根据 webhook 类型获取对应发送驱动。 + * @param {string} [hookType='customize'] webhook 类型 + * @return {object} + */ + getDriver(hookType = 'customize') { + const normalizedHookType = String(hookType || 'customize').trim().toLowerCase() || 'customize'; + const resolvedHookType = DRIVER_TYPE_ALIASES[normalizedHookType] || 'customize'; + + if (!this.driverCache.has(resolvedHookType)) { + let driver = null; + switch (resolvedHookType) { + case 'wecom': + driver = new WecomWebhookDriver(this.ctx, { + hookType: resolvedHookType, + }); + break; + case 'customize': + default: + driver = new CustomizeWebhookDriver(this.ctx, { + hookType: resolvedHookType, + }); + break; + } + + this.driverCache.set(resolvedHookType, driver); + } + return this.driverCache.get(resolvedHookType); + } + + /** + * 规范化消息类型,兼容中英文和别名写法。 + * @param {string} [type='text'] 原始消息类型 + * @return {string} 标准化后的消息类型 + */ + normalizeMessageType(type = 'text') { + const rawType = String(type || 'text').trim(); + const normalizedType = rawType.toLowerCase(); + return MESSAGE_TYPE_MAP[rawType] || MESSAGE_TYPE_MAP[normalizedType] || 'text'; + } + + /** + * 将传入值安全转换为对象。 + * @param {*} value 原始值 + * @param {object} [fallback={}] 转换失败时的兜底对象 + * @return {object} + */ + toObject(value, fallback = {}) { + if (!value) { + return fallback; + } + + if (typeof value === 'object' && !Array.isArray(value)) { + return value; + } + + if (typeof value === 'string') { + try { + const parsed = JSON.parse(value); + return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : fallback; + } catch (_) { + return fallback; + } + } + + return fallback; + } + + /** + * 规范化订阅事件列表,支持数组、字符串和对象格式。 + * @param {*} rawEvents 原始事件配置 + * @return {string[]} + */ + normalizeEventList(rawEvents) { + if (!rawEvents) { + return []; + } + + if (Array.isArray(rawEvents)) { + return rawEvents + .map(item => String(item || '').trim().toLowerCase() + .replace(/\./g, '_')) + .filter(Boolean); + } + + if (typeof rawEvents === 'string') { + const trimmed = rawEvents.trim(); + if (!trimmed) { + return []; + } + + try { + const parsed = JSON.parse(trimmed); + if (parsed !== rawEvents) { + return this.normalizeEventList(parsed); + } + } catch (_) { + // ignore parse failure and continue with string split + } + + return trimmed.split(/[\s,;|]+/).map(item => item.trim().toLowerCase().replace(/\./g, '_')).filter(Boolean); + } + + if (typeof rawEvents === 'object') { + if (rawEvents.all === true) { + return [ 'all' ]; + } + + return this.normalizeEventList(rawEvents.include || rawEvents.events || []); + } + + return []; + } + + /** + * 判断当前 webhook 是否命中本次消息事件。 + * @param {*} rawEvents 订阅的事件配置 + * @param {object} payload 统一消息载荷 + * @return {boolean} + */ + matchesEvents(rawEvents, payload) { + const eventList = this.normalizeEventList(rawEvents); + if (eventList.length === 0) { + return true; + } + + const candidateEvents = new Set([ + payload.event, + payload.businessName, + `${payload.businessName}_${payload.message.type}`, + ].map(item => String(item || '').trim().toLowerCase()).filter(Boolean)); + + return eventList.some(item => item === '*' || item === 'all' || candidateEvents.has(item)); + } + + /** + * 生成本次通知的追踪 ID。 + * @return {string} + */ + buildTraceId() { + return `notice_${Date.now()}_${Math.random().toString(16).slice(2, 10)}`; + } + + /** + * 获取当前模型中已注册的事件编码列表。 + * @return {string[]} + */ + getRegisteredEventCodes() { + const notificationWebhookModel = this.ctx.model && this.ctx.model.NotificationWebhook; + if (!notificationWebhookModel) { + return [ ...DEFAULT_REGISTERED_EVENT_CODES ]; + } + + if (typeof notificationWebhookModel.getAvailableEventCodes === 'function') { + const codes = notificationWebhookModel.getAvailableEventCodes() + .map(item => String(item || '').trim().toLowerCase()) + .filter(Boolean); + return codes.length > 0 ? codes : [ ...DEFAULT_REGISTERED_EVENT_CODES ]; + } + + if (Array.isArray(notificationWebhookModel.AVAILABLE_EVENTS)) { + const codes = notificationWebhookModel.AVAILABLE_EVENTS + .map(item => String(item && item.code || '').trim().toLowerCase()) + .filter(Boolean); + return codes.length > 0 ? codes : [ ...DEFAULT_REGISTERED_EVENT_CODES ]; + } + + return [ ...DEFAULT_REGISTERED_EVENT_CODES ]; + } + + /** + * 判断事件编码是否符合标识符式命名:仅允许小写字母、数字、下划线,且首字符不能为数字。 + * @param {string} event 事件编码 + * @return {boolean} + */ + isValidEventCode(event) { + const normalizedEvent = String(event || '').trim().toLowerCase(); + return normalizedEvent === 'all' || normalizedEvent === '*' || EVENT_CODE_PATTERN.test(normalizedEvent); + } + + /** + * 校验待发送事件是否已在通知模型中注册。 + * @param {string} event 事件名 + */ + assertEventRegistered(event) { + const normalizedEvent = String(event || '').trim().toLowerCase(); + if (!normalizedEvent) { + throw new Error('event 不能为空'); + } + + if (!this.isValidEventCode(normalizedEvent)) { + throw new Error(`event 命名不合法,仅支持小写字母、数字、下划线,且首字符不能为数字: ${normalizedEvent}`); + } + + const registeredCodes = this.getRegisteredEventCodes(); + if (registeredCodes.length > 0 && !registeredCodes.includes(normalizedEvent)) { + throw new Error(`event 未注册,不允许发送: ${normalizedEvent}`); + } + } + + /** + * 获取通知失败后的重试间隔,默认按 3 秒、6 秒、12 秒阶梯重试。 + * @param {object} [options={}] 原始通知入参 + * @return {number[]} + */ + getRetryDelays(options = {}) { + const customDelays = Array.isArray(options.retryDelaysMs) + ? options.retryDelaysMs + : (Array.isArray(this.app && this.app.config && this.app.config.noticeRetryDelaysMs) + ? this.app.config.noticeRetryDelaysMs + : DEFAULT_RETRY_DELAYS_MS); + + const normalizedDelays = customDelays + .map(item => Number(item)) + .filter(item => Number.isFinite(item) && item >= 0); + + return normalizedDelays.length > 0 ? normalizedDelays : [ ...DEFAULT_RETRY_DELAYS_MS ]; + } + + /** + * Promise 风格 sleep,用于统一重试等待。 + * @param {number} [ms=0] 等待毫秒数 + * @return {Promise} + */ + async sleep(ms = 0) { + const waitMs = Math.max(0, Number(ms) || 0); + await new Promise(resolve => setTimeout(resolve, waitMs)); + } + + /** + * 判断外部 webhook 返回是否可视为成功。 + * @param {object} [result={}] 发送结果 + * @return {boolean} + */ + isSuccessfulResponse(result = {}) { + const status = Number(result && result.status || 0); + if (status > 0 && (status < 200 || status >= 300)) { + return false; + } + + const response = result && Object.prototype.hasOwnProperty.call(result, 'response') + ? result.response + : null; + + if ([ 0, '0', false, 'false' ].includes(response)) { + return false; + } + + if (response && typeof response === 'object') { + if (response.ok === false || response.success === false) { + return false; + } + + if (Object.prototype.hasOwnProperty.call(response, 'errcode')) { + const errcode = Number(response.errcode); + if (Number.isFinite(errcode) && errcode !== 0) { + return false; + } + } + + if (Object.prototype.hasOwnProperty.call(response, 'code')) { + const responseCode = Number(response.code); + if (Number.isFinite(responseCode) && responseCode === 0) { + return false; + } + } + } + + return true; + } + + /** + * 归一化失败原因,便于日志记录与回写数据库。 + * @param {object} params 参数对象 + * @param {object|null} [params.result=null] 最近一次发送结果 + * @param {Error|null} [params.error=null] 最近一次异常 + * @return {string} + */ + getFailureMessage({ result = null, error = null } = {}) { + if (error && error.message) { + return error.message; + } + + const status = Number(result && result.status || 0); + if (status > 0 && (status < 200 || status >= 300)) { + return `webhook 请求失败,HTTP 状态码 ${status}`; + } + + const response = result && Object.prototype.hasOwnProperty.call(result, 'response') + ? result.response + : null; + + if ([ 0, '0' ].includes(response)) { + return 'webhook 返回 0,判定为失败'; + } + + if ([ false, 'false' ].includes(response)) { + return 'webhook 返回 false,判定为失败'; + } + + if (response && typeof response === 'object') { + if (Object.prototype.hasOwnProperty.call(response, 'errcode')) { + const errcode = Number(response.errcode); + if (Number.isFinite(errcode) && errcode !== 0) { + return String(response.errmsg || response.message || `企业微信 webhook 返回异常 errcode=${errcode}`); + } + } + if (response.message) { + return String(response.message); + } + if (response.msg) { + return String(response.msg); + } + if (response.errmsg) { + return String(response.errmsg); + } + } + + return 'webhook 推送失败'; + } + + /** + * 当 webhook 在重试后仍失败时,写入失败日志表。 + * @param {object} params 失败日志参数 + * @param {object} params.hook webhook 配置 + * @param {object} params.payload 标准化后的 payload + * @param {object|null} [params.result=null] 最近一次发送结果 + * @param {Error|null} [params.error=null] 最近一次异常 + * @param {number} [params.retryCount=0] 已执行重试次数 + * @return {Promise} + */ + async persistFailureLog({ hook, payload, result = null, error = null, retryCount = 0 }) { + const logModel = this.ctx.model && this.ctx.model.NotificationSendLog; + if (!logModel || typeof logModel.create !== 'function') { + return; + } + + try { + await logModel.create({ + trace_id: String(payload.traceId || ''), + webhook_id: Number(hook && hook.id || 0) || null, + store_id: Number(hook && hook.store_id || (payload.subject && payload.subject.id) || 0) || null, + warehouse_id: Number(payload.warehouseId || 0) || null, + owner_store_id: Number(payload.storeId || 0) || null, + business_name: String(payload.businessName || ''), + event: String(payload.event || ''), + hook_type: String(hook && hook.hook_type || ''), + hook_url: String(hook && hook.hook_url || ''), + request_payload: this.buildOutgoingPayload(hook || {}, payload), + response_payload: result && Object.prototype.hasOwnProperty.call(result, 'response') ? result.response : null, + http_status: Number(result && result.status || 0) || null, + status: 'failed', + error_message: this.getFailureMessage({ result, error }), + retry_count: Number(retryCount || 0), + created_by: Number(payload.sender && payload.sender.id || 0) || null, + }); + } catch (logError) { + this.ctx.logger.error('[NoticeService.persistFailureLog] save failed: %s', logError.message); + } + } + + /** + * 对单个 webhook 执行发送与阶梯重试。 + * @param {object} params 发送参数 + * @param {object} params.hook webhook 配置 + * @param {object} params.payload 标准化后的 payload + * @return {Promise} + */ + async sendWithRetry({ hook, payload }) { + const driver = this.getDriver(hook && hook.hook_type); + const outgoingPayload = this.buildOutgoingPayload(hook, payload); + const retryDelays = this.getRetryDelays(payload.raw || {}); + let lastResult = null; + let lastError = null; + + for (let attemptIndex = 0; attemptIndex <= retryDelays.length; attemptIndex++) { + try { + const result = await driver.send({ + hook, + payload: outgoingPayload, + }); + lastResult = result; + + if (this.isSuccessfulResponse(result)) { + return { + success: true, + retryCount: attemptIndex, + attemptCount: attemptIndex + 1, + ...(result || {}), + }; + } + + lastError = new Error(this.getFailureMessage({ result })); + } catch (error) { + lastError = error; + } + + if (attemptIndex < retryDelays.length) { + const waitMs = retryDelays[attemptIndex]; + this.ctx.logger.warn( + `[NoticeService.sendWithRetry] webhook send failed, retry in ${waitMs}ms (attempt ${attemptIndex + 1}/${retryDelays.length + 1}): ${this.getFailureMessage({ result: lastResult, error: lastError })}` + ); + await this.sleep(waitMs); + } + } + + await this.persistFailureLog({ + hook, + payload, + result: lastResult, + error: lastError, + retryCount: retryDelays.length, + }); + + return { + success: false, + hookId: Number(hook && hook.id || 0), + hookType: String(hook && hook.hook_type || ''), + hookUrl: String(hook && hook.hook_url || ''), + status: Number(lastResult && lastResult.status || 0) || 0, + response: lastResult && Object.prototype.hasOwnProperty.call(lastResult, 'response') ? lastResult.response : null, + error: this.getFailureMessage({ result: lastResult, error: lastError }), + retryCount: retryDelays.length, + attemptCount: retryDelays.length + 1, + }; + } + + /** + * 生成货主/仓库信息缓存键。 + * @param {number|string} warehouseId 仓库主体 ID + * @param {number|string} storeId 货主 ID + * @return {string} + */ + getStoreInfoCacheKey(warehouseId, storeId) { + return `warehouse:${Number(warehouseId || 0)}store:${Number(storeId || 0)}:info`; + } + + /** + * 解析货主信息,优先命中缓存,未命中时回查数据库并缓存 600 秒。 + * @param {object} [options={}] 原始通知入参 + * @param {object} [subject={}] 主体信息 + * @return {Promise} + */ + async resolveStoreInfo(options = {}, subject = {}) { + const directStore = this.toObject(options.store || options.owner, {}); + const subjectType = String(subject.type || options.subjectType || '').trim().toLowerCase(); + const warehouseId = Number( + options.warehouseId || options.warehouse_id || subject.warehouseId || (subjectType === 'warehouse' ? subject.id : 0) || options.subjectId || options.subject_id || 0 + ); + const storeId = Number( + options.ownerId || options.owner_id || options.storeOwnerId || options.store_owner_id || directStore.id || (subjectType === 'store' ? subject.id : 0) || (Number.isFinite(warehouseId) && warehouseId > 0 ? (options.storeId || options.store_id) : 0) || 0 + ); + + const normalizedStore = { + id: Number.isFinite(storeId) && storeId > 0 ? storeId : null, + name: String(directStore.name || directStore.companyName || directStore.company_name || ''), + businessLicense: String(directStore.businessLicense || directStore.business_license || ''), + storeRemask: String(directStore.storeRemask || directStore.store_remask || directStore.remask || ''), + }; + + if (!Number.isFinite(storeId) || storeId <= 0) { + return normalizedStore; + } + + const canUseCache = Number.isFinite(warehouseId) && warehouseId > 0; + const cacheKey = canUseCache ? this.getStoreInfoCacheKey(warehouseId, storeId) : ''; + + if (canUseCache && this.app && typeof this.app.getCacheAsync === 'function') { + try { + const cachedValue = await this.app.getCacheAsync(cacheKey); + const cachedStore = this.toObject(cachedValue, null); + if (cachedStore && Object.keys(cachedStore).length > 0) { + const businessLicense = String(cachedStore.businessLicense || cachedStore.business_license || normalizedStore.businessLicense || ''); + const storeRemask = String(cachedStore.storeRemask || cachedStore.store_remask || cachedStore.remask || normalizedStore.storeRemask || ''); + return { + id: normalizedStore.id, + name: String(cachedStore.name || cachedStore.companyName || cachedStore.company_name || normalizedStore.name || ''), + businessLicense, + storeRemask, + }; + } + } catch (error) { + this.ctx.logger.warn('[NoticeService.resolveStoreInfo] read cache failed: %s', error.message); + } + } + + const storeModel = this.ctx.model && this.ctx.model.Store; + const storeWarehouseModel = this.ctx.model && this.ctx.model.StoreWarehouse; + + try { + const [ storeRecord, relationRecord ] = await Promise.all([ + storeModel && typeof storeModel.findByPk === 'function' + ? storeModel.findByPk(storeId, { + attributes: [ 'id', 'company_name', 'business_license' ], + }) + : null, + canUseCache && storeWarehouseModel && typeof storeWarehouseModel.findOne === 'function' + ? storeWarehouseModel.findOne({ + where: { + warehouse_id: warehouseId, + store_id: storeId, + }, + attributes: [ 'store_remask' ], + }) + : null, + ]); + + const businessLicense = normalizedStore.businessLicense || String(storeRecord && storeRecord.business_license || ''); + const storeRemask = normalizedStore.storeRemask || String(relationRecord && relationRecord.store_remask || ''); + const resolvedStore = { + id: normalizedStore.id, + name: normalizedStore.name || String(storeRecord && storeRecord.company_name || ''), + businessLicense, + storeRemask, + }; + + if (canUseCache && this.app && typeof this.app.setCacheAsync === 'function') { + await this.app.setCacheAsync(cacheKey, resolvedStore, 600); + } + + return resolvedStore; + } catch (error) { + this.ctx.logger.warn('[NoticeService.resolveStoreInfo] load store info failed: %s', error.message); + return normalizedStore; + } + } + + /** + * 解析主体配置,优先使用入参,缺失时回查主体表。 + * @param {object} [options={}] 原始通知入参 + * @param {object} [subject={}] 主体信息 + * @return {Promise} + */ + async resolveSubjectConfig(options = {}, subject = {}) { + const storeModel = this.ctx.model && this.ctx.model.Store; + const normalizeSubjectConfig = value => { + if (storeModel && typeof storeModel.normalizeSubjectConfig === 'function') { + return storeModel.normalizeSubjectConfig(value); + } + + const config = this.toObject(value, {}); + return { + max_notice_webhook_count: DEFAULT_MAX_NOTICE_WEBHOOK_COUNT, + ...config, + }; + }; + + const directConfig = this.toObject(subject.config || options.subjectConfig || options.subject_config, null); + if (directConfig && Object.keys(directConfig).length > 0) { + return normalizeSubjectConfig(directConfig); + } + + 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') { + return normalizeSubjectConfig(null); + } + + try { + const store = await storeModel.findByPk(subjectId, { + attributes: [ 'subject_config' ], + }); + return normalizeSubjectConfig(store && store.subject_config); + } catch (error) { + this.ctx.logger.warn('[NoticeService.resolveSubjectConfig] load subject_config failed: %s', error.message); + return normalizeSubjectConfig(null); + } + } + + /** + * 将业务入参整理为统一通知 payload。 + * @param {object} [options={}] 发送入参 + * @return {Promise} + */ + async normalizePayload(options = {}) { + const subject = this.toObject(options.subject, {}); + const messageType = this.normalizeMessageType( + options.messageType || options.msgType || options.message_type || options.type + ); + const businessName = String( + options.businessName || options.business || options.bussinessType || options.business_type || '' + ).trim(); + + if (!businessName) { + throw new Error('businessName / bussinessType 不能为空'); + } + + const warehouseId = Number( + options.warehouseId || options.warehouse_id || subject.warehouseId || (String(subject.type || options.subjectType || '').trim().toLowerCase() === 'warehouse' ? subject.id : 0) || 0 + ); + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + throw new Error('warehouseId / warehouse_id 不能为空'); + } + + const subjectId = Number( + options.subjectId || options.subject_id || subject.id || warehouseId + ); + if (!Number.isFinite(subjectId) || subjectId <= 0) { + throw new Error('subject.id / subjectId / warehouseId / warehouse_id 不能为空'); + } + + const contentSource = options.content !== undefined + ? options.content + : (options.message !== undefined ? options.message : (options.messageBody !== undefined ? options.messageBody : options.body)); + const content = typeof contentSource === 'string' + ? contentSource + : (contentSource == null ? '' : JSON.stringify(contentSource)); + + const url = String( + options.url || options.fileUrl || options.file_url || options.imageUrl || options.image_url || '' + ).trim(); + + if ([ 'image', 'file' ].includes(messageType) && !url) { + throw new Error('图片/文件消息必须提供 url'); + } + + const event = String(options.event || options.eventName || `${businessName}_${messageType}`).trim(); + this.assertEventRegistered(event); + const title = String(options.title || options.summary || businessName).trim() || businessName; + const resolvedSubject = { + ...subject, + id: subjectId, + }; + const [ subjectConfig, storeInfo ] = await Promise.all([ + this.resolveSubjectConfig(options, resolvedSubject), + this.resolveStoreInfo(options, resolvedSubject), + ]); + + return { + traceId: String(options.traceId || this.buildTraceId()), + hookType: String(options.hookType || options.webhookType || '').trim(), + event, + businessName, + warehouseId, + storeId: storeInfo && storeInfo.id ? Number(storeInfo.id) : null, + businessId: options.businessId || options.bussinessId || null, + occurredAt: options.occurredAt || new Date().toISOString(), + sender: this.toObject(options.sender || options.operator, {}), + receivers: Array.isArray(options.receivers) ? options.receivers : [], + subject: { + id: subjectId, + type: String(subject.type || options.subjectType || 'store'), + name: String(subject.name || options.subjectName || options.store_name || ''), + code: String(subject.code || options.subjectCode || ''), + config: subjectConfig, + }, + store: storeInfo, + message: { + type: messageType, + title, + content, + url, + fileName: String(options.fileName || options.filename || ''), + mimeType: String(options.mimeType || options.contentType || ''), + body: contentSource, + }, + metadata: this.toObject(options.metadata, {}), + raw: options, + }; + } + + /** + * 构建实际对外发送的统一消息体。 + * @param {object} webhook webhook 配置 + * @param {object} payload 标准化后的消息载荷 + * @return {object} + */ + buildOutgoingPayload(webhook, payload) { + return { + traceId: payload.traceId, + event: payload.event, + businessName: payload.businessName, + businessId: payload.businessId, + occurredAt: payload.occurredAt, + subject: payload.subject, + store: payload.store, + sender: payload.sender, + receivers: payload.receivers, + message: payload.message, + metadata: payload.metadata, + }; + } + + /** + * 获取当前主体允许发送的 webhook 数量上限。 + * @param {object} [payload={}] 标准化后的消息载荷 + * @return {number} + */ + getWebhookLimit(payload = {}) { + const rawLimit = payload && payload.subject && payload.subject.config + ? payload.subject.config.max_notice_webhook_count + : DEFAULT_MAX_NOTICE_WEBHOOK_COUNT; + const normalizedLimit = Number(rawLimit); + + if (!Number.isInteger(normalizedLimit) || normalizedLimit < 0) { + return DEFAULT_MAX_NOTICE_WEBHOOK_COUNT; + } + + return Math.min(normalizedLimit, DEFAULT_MAX_NOTICE_WEBHOOK_COUNT); + } + + /** + * 根据主体、事件和上限筛选本次需要触达的 webhook。 + * @param {object} payload 标准化后的消息载荷 + * @return {Promise} + */ + async findMatchedWebhooks(payload) { + const webhookLimit = this.getWebhookLimit(payload); + if (webhookLimit <= 0) { + return []; + } + + if (Array.isArray(payload.raw.hooks)) { + return payload.raw.hooks + .filter(item => this.matchesEvents(item && item.events, payload)) + .slice(0, webhookLimit); + } + + const webhookModel = this.ctx.model && this.ctx.model.NotificationWebhook; + if (!webhookModel || typeof webhookModel.findAll !== 'function') { + return []; + } + + const warehouseId = Number(payload.warehouseId || (payload.subject && payload.subject.id) || 0); + const storeId = Number(payload.storeId || (payload.store && payload.store.id) || 0); + const targetSubjectIds = []; + + if (Number.isFinite(warehouseId) && warehouseId > 0) { + targetSubjectIds.push(warehouseId); + } + + if (Number.isFinite(storeId) && storeId > 0 && !targetSubjectIds.includes(storeId)) { + targetSubjectIds.push(storeId); + } + + if (targetSubjectIds.length === 0) { + return []; + } + + const webhookGroups = await Promise.all(targetSubjectIds.map(async currentSubjectId => { + const where = { + store_id: currentSubjectId, + status: 1, + }; + + if (payload.hookType) { + where.hook_type = payload.hookType; + } + + const webhooks = await webhookModel.findAll({ + where, + order: [[ 'id', 'ASC' ]], + }); + + return webhooks + .filter(item => this.matchesEvents(item && item.events, payload)) + .slice(0, webhookLimit); + })); + + const flattenedWebhooks = webhookGroups.flat(); + const seen = new Set(); + + return flattenedWebhooks.filter(item => { + const dedupeKey = item && item.id ? `id:${item.id}` : `url:${String(item && item.hook_url || '')}`; + if (seen.has(dedupeKey)) { + return false; + } + seen.add(dedupeKey); + return true; + }); + } + + /** + * 统一通知发送入口:规范化消息、匹配 webhook 并执行分发。 + * @param {object} [options={}] 发送入参 + * @return {Promise} + */ + async send(options = {}) { + const payload = await this.normalizePayload(options); + const webhooks = await this.findMatchedWebhooks(payload); + + if (webhooks.length === 0) { + this.ctx.logger.warn('[NoticeService.send] 未匹配到可用 webhook', { + traceId: payload.traceId, + event: payload.event, + warehouseId: payload.warehouseId, + storeId: payload.storeId, + messageType: payload.message && payload.message.type, + }); + + return { + success: true, + message: '未匹配到可用 webhook', + data: { + traceId: payload.traceId, + event: payload.event, + matchedHookCount: 0, + sentCount: 0, + failedCount: 0, + results: [], + }, + }; + } + + const tasks = webhooks.map(async hook => await this.sendWithRetry({ hook, payload })); + const results = await Promise.all(tasks); + const sentCount = results.filter(item => item && item.success).length; + const failedCount = results.length - sentCount; + + const summary = { + traceId: payload.traceId, + event: payload.event, + warehouseId: payload.warehouseId, + storeId: payload.storeId, + matchedHookCount: webhooks.length, + sentCount, + failedCount, + messageType: payload.message && payload.message.type, + }; + + if (failedCount > 0) { + this.ctx.logger.warn('[NoticeService.send] webhook 发送存在失败', summary); + } else { + this.ctx.logger.info('[NoticeService.send] webhook 发送完成', summary); + } + + return { + success: failedCount === 0, + message: failedCount === 0 ? '通知已发送' : `部分 webhook 发送失败(${failedCount})`, + data: { + traceId: payload.traceId, + event: payload.event, + matchedHookCount: webhooks.length, + sentCount, + failedCount, + results, + }, + }; + } +} + +module.exports = NoticeService; diff --git a/app/service/systems/print/index.js b/app/service/systems/print/index.js index 94d43be..fd15ec2 100644 --- a/app/service/systems/print/index.js +++ b/app/service/systems/print/index.js @@ -5,41 +5,41 @@ const Service = require('egg').Service; class PrintService extends Service { // 发送信息到打印电脑 async sendToComputer({ warehouse, computerId, data }) { - //发送指令更新打印机状态 + // 发送指令更新打印机状态 const printServiceUrl = this.ctx.app.config.printService.url; - //先获取redis中打印机列表 - let printerListResult = await this.app.redis.get("printer").get(`printer:${computerId}:printerList`); + // 先获取redis中打印机列表 + let printerListResult = await this.app.redis.get('printer').get(`printer:${computerId}:printerList`); let lastUpdateTime = 0; - if(printerListResult){ - //记录上次更新时间,避免频繁发送更新指令 - let printerData = JSON.parse(printerListResult); - console.log("printerData", printerData); + if (printerListResult) { + // 记录上次更新时间,避免频繁发送更新指令 + const printerData = JSON.parse(printerListResult); + console.log('printerData', printerData); lastUpdateTime = printerData.updatedAt || 0; } - //不管是否有打印机列表,都先发送指令让打印电脑更新打印机状态和列表 + // 不管是否有打印机列表,都先发送指令让打印电脑更新打印机状态和列表 const res = await this.ctx.curl(`${printServiceUrl}/sendToRoom`, { method: 'POST', contentType: 'json', - data: { warehouse, computerId, method: "printer.getWindowsPrinters", data: {} }, + data: { warehouse, computerId, method: 'printer.getWindowsPrinters', data: {} }, dataType: 'json', }); - console.log("lastUpdateTime",lastUpdateTime) - //等待异步获取打印机列表结果,最长等待5秒 + console.log('lastUpdateTime', lastUpdateTime); + // 等待异步获取打印机列表结果,最长等待5秒 const startTime = Date.now(); while (Date.now() - startTime < 5000) { await new Promise(resolve => setTimeout(resolve, 10)); // 每10ms检查一次 - printerListResult = await this.app.redis.get("printer").get(`printer:${computerId}:printerList`); - let printerData = JSON.parse(printerListResult); - if(printerData.updatedAt && printerData.updatedAt > lastUpdateTime){ - console.log("打印机列表已更新", printerData.updatedAt); - //如果更新了打印机列表,跳出循环 + printerListResult = await this.app.redis.get('printer').get(`printer:${computerId}:printerList`); + const printerData = JSON.parse(printerListResult); + if (printerData.updatedAt && printerData.updatedAt > lastUpdateTime) { + console.log('打印机列表已更新', printerData.updatedAt); + // 如果更新了打印机列表,跳出循环 break; } } - //从redis获取打印机 - printerListResult = await this.app.redis.get("printer").get(`printer:${computerId}:printerList`); + // 从redis获取打印机 + printerListResult = await this.app.redis.get('printer').get(`printer:${computerId}:printerList`); const printerList = JSON.parse(printerListResult); - console.log("sendToComputer printerList", printerList); + console.log('sendToComputer printerList', printerList); if (!printerList || !printerList.data || printerList.data.length === 0) { return { success: false, error: '未找到对应的打印机', detail: `computerId: ${computerId} 的打印机列表不存在` }; } @@ -48,14 +48,14 @@ class PrintService extends Service { if (!printerInfo) { return { success: false, error: `打印台没有打印机 ${printer}`, detail: `computerId: ${computerId} 的打印机列表中不存在 printer: ${printer}` }; } - if (printerInfo.workOffline == "TRUE") { + if (printerInfo.workOffline == 'TRUE') { return { success: false, error: `打印机 ${printer} 处于脱机状态`, detail: `computerId: ${computerId} 的打印机 ${printer} 当前处于离线状态` }; } try { const res = await this.ctx.curl(`${printServiceUrl}/sendToRoom`, { method: 'POST', contentType: 'json', - data: { warehouse, computerId, method: "printer.print", data }, + data: { warehouse, computerId, method: 'printer.print', data }, dataType: 'json', }); console.log(res); @@ -66,8 +66,8 @@ class PrintService extends Service { } } async test() { - const grabnum = "B1157389"; - const datas = await this.app.wsdl("print", [5400, grabnum, "caige"]) + const grabnum = 'B1157389'; + const datas = await this.app.wsdl('print', [ 5400, grabnum, 'caige' ]); this.sendToComputer({ warehouse: '1000028', computerId: '1', data: datas }); } } diff --git a/app/service/systems/setting/account.js b/app/service/systems/setting/account.js index 0d02989..6cd2314 100644 --- a/app/service/systems/setting/account.js +++ b/app/service/systems/setting/account.js @@ -360,7 +360,6 @@ class SettingAccountService extends Service { return employeeRoleMap; } -<<<<<<< HEAD async buildWechatBindingMap(accountIds) { if (!Array.isArray(accountIds) || accountIds.length === 0) { return new Map(); @@ -451,8 +450,6 @@ class SettingAccountService extends Service { throw this.createError('目标账号超出当前操作范围', 403); } -======= ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 async formatEmployeeRow(employee, options = {}) { let account = options.account || null; if (!account) { @@ -565,13 +562,10 @@ class SettingAccountService extends Service { .map(employee => Number(employee.id)) .filter(employeeId => Number.isFinite(employeeId) && employeeId > 0); const employeeRoleMap = await this.buildEmployeeRoleGroupMap(employeeIds); -<<<<<<< HEAD const accountIds = employees .map(employee => Number(employee.account_id)) .filter(accountId => Number.isFinite(accountId) && accountId > 0); const wechatBindingMap = await this.buildWechatBindingMap(accountIds); -======= ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 const list = []; for (const employee of employees) { @@ -592,23 +586,17 @@ class SettingAccountService extends Service { continue; } -<<<<<<< HEAD const wechatBinding = wechatBindingMap.get(Number(employee.account_id)) || { is_wechat_bound: false, ye4s_user_id: null, }; -======= ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 list.push({ ...await this.formatEmployeeRow(employee, { account: employee.account, }), -<<<<<<< HEAD is_wechat_bound: wechatBinding.is_wechat_bound, ye4s_user_id: wechatBinding.ye4s_user_id, -======= ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 role_ids: roleGroup.role_ids, roles: roleGroup.roles, }); diff --git a/app/service/systems/setting/permission.js b/app/service/systems/setting/permission.js index b616abc..1b5d03b 100644 --- a/app/service/systems/setting/permission.js +++ b/app/service/systems/setting/permission.js @@ -151,49 +151,22 @@ class SettingPermissionService extends Service { return new Set(rows.map(item => Number(item.id)).filter(id => Number.isFinite(id) && id > 0)); } -<<<<<<< HEAD async ensureParentPermissionExists(parentId) { -======= - async ensureParentPermissionInScope(parentId) { ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 if (!parentId) { return; } await this.getPermission(parentId, false); -<<<<<<< HEAD } async ensurePermissionsExist(permissionIds) { const { ctx } = this; -======= - - const availableSet = await this.getAvailablePermissionIdSet({ includeDisabled: false }); - if (!availableSet.has(Number(parentId))) { - throw this.createError(`parent_id 超出当前登录工号可用权限集:${parentId}`, 400); - } - } - - async ensurePermissionsInAvailableScope(permissionIds, options = {}) { - const { ctx, app } = this; - const { Op } = app.Sequelize; - const includeDisabled = options.includeDisabled === true; - - const availableSet = await this.getAvailablePermissionIdSet({ includeDisabled }); - if (availableSet.size === 0) { - throw this.createError('当前登录工号可用权限集为空,无法操作权限', 400); - } ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 const targetRows = await ctx.model.Permission.findAll({ where: { id: permissionIds, }, -<<<<<<< HEAD attributes: [ 'id' ], -======= - attributes: [ 'id', 'parent_id' ], ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 raw: true, }); if (targetRows.length !== permissionIds.length) { @@ -202,68 +175,7 @@ class SettingPermissionService extends Service { throw this.createError(`权限不存在:${missing.join(',')}`, 404); } -<<<<<<< HEAD return targetRows; -======= - const parentMap = new Map(targetRows.map(item => [ Number(item.id), item.parent_id === null ? null : Number(item.parent_id) ])); - let pendingParentIds = Array.from(new Set(targetRows - .map(item => item.parent_id === null ? null : Number(item.parent_id)) - .filter(parentId => Number.isFinite(parentId) && parentId > 0))); - - while (pendingParentIds.length > 0) { - const fetchIds = pendingParentIds.filter(parentId => !parentMap.has(parentId)); - if (fetchIds.length === 0) { - break; - } - - const parentRows = await ctx.model.Permission.findAll({ - where: { - id: { - [Op.in]: fetchIds, - }, - }, - attributes: [ 'id', 'parent_id' ], - raw: true, - }); - - for (const row of parentRows) { - parentMap.set(Number(row.id), row.parent_id === null ? null : Number(row.parent_id)); - } - - pendingParentIds = Array.from(new Set(parentRows - .map(row => row.parent_id === null ? null : Number(row.parent_id)) - .filter(parentId => Number.isFinite(parentId) && parentId > 0 && !parentMap.has(parentId)))); - } - - const outOfScopeIds = []; - for (const permissionId of permissionIds) { - let currentId = Number(permissionId); - let inScope = false; - const visited = new Set(); - - while (Number.isFinite(currentId) && currentId > 0 && !visited.has(currentId)) { - visited.add(currentId); - if (availableSet.has(currentId)) { - inScope = true; - break; - } - - const parentId = parentMap.has(currentId) ? parentMap.get(currentId) : null; - if (!Number.isFinite(parentId) || parentId <= 0) { - break; - } - currentId = Number(parentId); - } - - if (!inScope) { - outOfScopeIds.push(Number(permissionId)); - } - } - - if (outOfScopeIds.length > 0) { - throw this.createError(`包含超出当前登录工号可用权限集的权限ID:${outOfScopeIds.join(',')}`, 400); - } ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 } normalizePermissionIds(inputPermissionIds) { @@ -359,12 +271,7 @@ class SettingPermissionService extends Service { } async getCurrentEmployeePermissionIds() { -<<<<<<< HEAD const { ctx } = this; -======= - const { ctx, app } = this; - const { Op } = app.Sequelize; ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 const currentEmployeeId = this.getCurrentEmployeeId(); if (!currentEmployeeId) { return []; @@ -396,25 +303,9 @@ class SettingPermissionService extends Service { return []; } -<<<<<<< HEAD return await ctx.service.systems.auth.rolePermission.getPermissionIdsForRoles(roleIds, { includeDisabled: false, }); -======= - const rolePermissions = await ctx.model.RolePermission.findAll({ - where: { - role_id: { - [Op.in]: roleIds, - }, - }, - attributes: [ 'permission_id' ], - raw: true, - }); - - return Array.from(new Set(rolePermissions - .map(item => Number(item.permission_id)) - .filter(id => Number.isFinite(id) && id > 0))); ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 } async getCurrentRoleId() { @@ -451,7 +342,6 @@ class SettingPermissionService extends Service { return roleId; } -<<<<<<< HEAD async resolveVisiblePermissionRows({ includeDisabled = false, type = null, keyword = '', scopeMode = 'available' } = {}) { const { ctx, app } = this; const { Op } = app.Sequelize; @@ -469,26 +359,6 @@ class SettingPermissionService extends Service { [Op.in]: currentPermissionIds, }; } -======= - async resolveVisiblePermissionRows({ includeDisabled = false, type = null, keyword = '' } = {}) { - const { ctx, app } = this; - const { Op } = app.Sequelize; - - const currentPermissionIds = await this.getCurrentEmployeePermissionIds(); - if (currentPermissionIds.length === 0) { - return []; - } - - const where = { - id: { - [Op.in]: currentPermissionIds, - }, - status: includeDisabled ? { [Op.in]: [ 0, 1 ] } : 1, - type: { - [Op.notLike]: '%_pages', - }, - }; ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 if (type) { where.type = type; } @@ -510,16 +380,12 @@ class SettingPermissionService extends Service { 'status', 'parent_id', 'sort', -<<<<<<< HEAD 'component', 'redirect', 'meta_title', 'meta_icon', 'hidden', 'always_show', -======= - 'meta_title', ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 ], order: [ [ 'sort', 'ASC' ], @@ -548,15 +414,11 @@ class SettingPermissionService extends Service { role = await this.getRole(roleId); } -<<<<<<< HEAD // 权限管理页需要展示全量权限树,不能再按当前登录工号已分配权限做裁剪。 -======= ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 const permissionRows = await this.resolveVisiblePermissionRows({ includeDisabled, type, keyword, -<<<<<<< HEAD scopeMode: 'all', }); @@ -569,20 +431,6 @@ class SettingPermissionService extends Service { } else if (directPermissionIds.length > 0) { selectedPermissionSet = new Set(directPermissionIds.map(item => Number(item))); } -======= - }); - - let selectedPermissionSet = new Set(); - if (role) { - const rolePermissions = await ctx.model.RolePermission.findAll({ - where: { - role_id: role.id, - }, - attributes: [ 'permission_id' ], - }); - - selectedPermissionSet = new Set(rolePermissions.map(item => Number(item.permission_id))); ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 } const permissions = permissionRows.map(item => ({ @@ -593,7 +441,6 @@ class SettingPermissionService extends Service { status: Number(item.status), parent_id: item.parent_id === null ? null : Number(item.parent_id), sort: Number(item.sort || 0), -<<<<<<< HEAD component: item.component || '', redirect: item.redirect || '', meta_title: item.meta_title || '', @@ -601,10 +448,6 @@ class SettingPermissionService extends Service { hidden: Number(item.hidden || 0), always_show: Number(item.always_show || 0), selected: role ? (selectAllPermissions || selectedPermissionSet.has(Number(item.id))) : false, -======= - meta_title: item.meta_title || '', - selected: role ? selectedPermissionSet.has(Number(item.id)) : false, ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 })); return { @@ -639,11 +482,7 @@ class SettingPermissionService extends Service { status: this.normalizeStatus(data.status), }; -<<<<<<< HEAD await this.ensureParentPermissionExists(permissionData.parent_id); -======= - await this.ensureParentPermissionInScope(permissionData.parent_id); ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 let created = null; try { @@ -668,13 +507,7 @@ class SettingPermissionService extends Service { const { ctx } = this; const permissionIds = this.normalizeIds(data.ids, 'ids'); -<<<<<<< HEAD await this.ensurePermissionsExist(permissionIds); -======= - await this.ensurePermissionsInAvailableScope(permissionIds, { - includeDisabled: true, - }); ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 const permissions = await ctx.model.Permission.findAll({ where: { @@ -706,14 +539,7 @@ class SettingPermissionService extends Service { transaction, }); -<<<<<<< HEAD await ctx.service.systems.auth.rolePermission.removePermissionsFromAllRoles(deletedIds, { -======= - await ctx.model.RolePermission.destroy({ - where: { - permission_id: deletedIds, - }, ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 transaction, }); } @@ -736,17 +562,8 @@ class SettingPermissionService extends Service { } async update(data = {}) { -<<<<<<< HEAD const permissionId = this.toPositiveNumber(data.permission_id || data.permissionId, 'permission_id'); await this.ensurePermissionsExist([ permissionId ]); -======= - const { ctx } = this; - - const permissionId = this.toPositiveNumber(data.permission_id || data.permissionId, 'permission_id'); - await this.ensurePermissionsInAvailableScope([ permissionId ], { - includeDisabled: true, - }); ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 const permission = await this.getPermission(permissionId, true); @@ -800,11 +617,7 @@ class SettingPermissionService extends Service { if (parentId && parentId === permissionId) { throw this.createError('parent_id 不能等于 permission_id', 400); } -<<<<<<< HEAD await this.ensureParentPermissionExists(parentId); -======= - await this.ensureParentPermissionInScope(parentId); ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 updates.parent_id = parentId; } if (hasSort) { diff --git a/app/service/systems/setting/print_template.js b/app/service/systems/setting/print_template.js index acccc3b..5e810ca 100644 --- a/app/service/systems/setting/print_template.js +++ b/app/service/systems/setting/print_template.js @@ -293,7 +293,7 @@ class PrintTemplateService extends Service { }; } -/** + /** * 获取所有业务类型(用于下拉选择)- 支持分组展示 * @return {Object} 业务类型及打印项列表,包含分组信息 */ diff --git a/app/service/systems/setting/role.js b/app/service/systems/setting/role.js index e0a6d3d..8292ff0 100644 --- a/app/service/systems/setting/role.js +++ b/app/service/systems/setting/role.js @@ -145,7 +145,6 @@ class SettingRoleService extends Service { return visited; } -<<<<<<< HEAD async buildRolePermissionMap(roleRows) { const { service } = this.ctx; const rows = Array.isArray(roleRows) ? roleRows : []; @@ -165,9 +164,6 @@ class SettingRoleService extends Service { } buildRoleTree(roleRows, rootRoleIds, selectedRoleIdSet, rolePermissionMap = new Map()) { -======= - buildRoleTree(roleRows, rootRoleIds, selectedRoleIdSet) { ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 const nodeMap = new Map(); for (const row of roleRows) { const roleId = Number(row.id); @@ -183,10 +179,7 @@ class SettingRoleService extends Service { store_id: row.store_id === null ? null : Number(row.store_id), pid: Number(row.pid || 0), selected: selectedRoleIdSet.has(roleId), -<<<<<<< HEAD permission_ids: rolePermissionMap.get(roleId) || [], -======= ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 children: [], }); } @@ -249,7 +242,6 @@ class SettingRoleService extends Service { } normalizePermissionIds(inputPermissionIds) { -<<<<<<< HEAD if (inputPermissionIds === '*') { return [ '*' ]; } @@ -274,32 +266,21 @@ class SettingRoleService extends Service { } } -======= ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 if (!Array.isArray(inputPermissionIds)) { throw this.createError('permission_ids 参数不能为空', 400); } -<<<<<<< HEAD if (inputPermissionIds.some(item => typeof item === 'string' && item.trim() === '*')) { return [ '*' ]; } -======= ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 const permissionIds = []; for (const permissionId of inputPermissionIds) { const normalized = Number(permissionId); if (!Number.isFinite(normalized) || normalized <= 0) { -<<<<<<< HEAD throw this.createError('permission_ids 必须是正整数数组或 ["*"]', 400); } permissionIds.push(Math.floor(normalized)); -======= - throw this.createError('permission_ids 必须是正整数数组', 400); - } - permissionIds.push(normalized); ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 } return Array.from(new Set(permissionIds)); @@ -339,15 +320,11 @@ class SettingRoleService extends Service { async validatePermissionSet(permissionIds) { const { ctx } = this; -<<<<<<< HEAD if (!Array.isArray(permissionIds) || permissionIds.length === 0) { return; } if (permissionIds.includes('*')) { -======= - if (permissionIds.length === 0) { ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 return; } @@ -364,46 +341,12 @@ class SettingRoleService extends Service { const missing = permissionIds.filter(id => !found.has(id)); throw this.createError(`权限不存在或已禁用:${missing.join(',')}`, 400); } -<<<<<<< HEAD } async replaceRolePermissions(roleId, permissionIds, transaction) { return await this.ctx.service.systems.auth.rolePermission.assignPermissions(roleId, permissionIds, { transaction, }); -======= - - const visiblePermissions = await this.ctx.service.systems.setting.permission.resolveVisiblePermissionRows({ - includeDisabled: false, - type: null, - keyword: '', - }); - const availableSet = new Set(visiblePermissions.map(item => Number(item.id))); - const outOfScopeIds = permissionIds.filter(id => !availableSet.has(id)); - if (outOfScopeIds.length > 0) { - throw this.createError(`包含超出可用权限集的权限ID:${outOfScopeIds.join(',')}`, 400); - } - } - - async replaceRolePermissions(roleId, permissionIds, transaction) { - const { ctx } = this; - - await ctx.model.RolePermission.destroy({ - where: { - role_id: roleId, - }, - transaction, - }); - - if (permissionIds.length > 0) { - const rows = permissionIds.map(permissionId => ({ - role_id: roleId, - permission_id: permissionId, - })); - - await ctx.model.RolePermission.bulkCreate(rows, { transaction }); - } ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 } async clearRoleUsersCache(roleId) { @@ -455,12 +398,8 @@ class SettingRoleService extends Service { // 先拉取当前主体 + 系统角色域,后续按可见规则二次收敛。 const roleWhere = { -<<<<<<< HEAD - status: includeDisabled ? { [Op.in]: [0, 1] } : 1, -======= status: includeDisabled ? { [Op.in]: [ 0, 1 ] } : 1, ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 - [Op.or]: [ { store_id: storeId }, { store_id: 0 }, { store_id: null } ], + [Op.or]: [{ store_id: storeId }, { store_id: 0 }, { store_id: null }], }; const roleRows = await ctx.model.Role.findAll({ @@ -476,10 +415,7 @@ class SettingRoleService extends Service { 'status', 'store_id', 'pid', -<<<<<<< HEAD 'permissions', -======= ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 ], order: [ [ 'is_system', 'DESC' ], @@ -513,7 +449,6 @@ class SettingRoleService extends Service { }; } -<<<<<<< HEAD const currentRoleIdSet = new Set(currentRoleRows.map(item => Number(item.id))); // 仅返回当前角色的下级角色树,不返回自己及同级角色。 @@ -533,34 +468,12 @@ class SettingRoleService extends Service { } const visibleRoleIds = this.collectDescendantRoleIds(roleRows, Array.from(subordinateRootRoleIds)); -======= - const sameLevelParentIds = new Set(currentRoleRows.map(item => Number(item.pid || 0))); - const currentRoleIdSet = new Set(currentRoleRows.map(item => Number(item.id))); - const hasSystemCurrentRole = currentRoleRows - .some(item => this.normalizeStoreScope(item.store_id) === 0); - - // 默认场景下,若当前角色在系统域(store_id=0/null),只保留当前角色本身作为根, - // 避免暴露其他系统同级角色。 - const sameLevelRoleIds = hasSystemCurrentRole && !includeSystem - ? new Set(currentRoleIdSet) - : new Set(roleRows - .filter(item => sameLevelParentIds.has(Number(item.pid || 0))) - .filter(item => this.isRoleVisibleInScope(item, currentRoleRows, storeId, includeSystem)) - .map(item => Number(item.id))); - - const descendantRoleIds = this.collectDescendantRoleIds(roleRows, currentRoleRows.map(item => Number(item.id))); - const visibleRoleIds = new Set([ ...sameLevelRoleIds, ...descendantRoleIds ]); ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 const visibleRoleRows = roleRows .filter(item => visibleRoleIds.has(Number(item.id))) .filter(item => this.isRoleVisibleInScope(item, currentRoleRows, storeId, includeSystem)); const rootRoleIds = new Set(visibleRoleRows -<<<<<<< HEAD .filter(item => subordinateRootRoleIds.has(Number(item.id))) -======= - .filter(item => sameLevelRoleIds.has(Number(item.id))) ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 .map(item => Number(item.id))); let selectedRoleIdSet = new Set(); @@ -573,12 +486,8 @@ class SettingRoleService extends Service { selectedRoleIdSet = new Set(employeeRoles.map(item => Number(item.role_id))); } -<<<<<<< HEAD const rolePermissionMap = await this.buildRolePermissionMap(visibleRoleRows); const roles = this.buildRoleTree(visibleRoleRows, rootRoleIds, selectedRoleIdSet, rolePermissionMap); -======= - const roles = this.buildRoleTree(visibleRoleRows, rootRoleIds, selectedRoleIdSet); ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 return { code: 200, @@ -589,13 +498,10 @@ class SettingRoleService extends Service { }; } -<<<<<<< HEAD async permission(data = {}) { return this.ctx.service.systems.setting.permission.list(data); } -======= ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 async add(data = {}) { const { ctx } = this; @@ -691,18 +597,6 @@ class SettingRoleService extends Service { deletedIds.push(roleId); } -<<<<<<< HEAD -======= - if (deletedIds.length > 0) { - await ctx.model.RolePermission.destroy({ - where: { - role_id: deletedIds, - }, - transaction, - }); - } - ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 await transaction.commit(); } catch (error) { await transaction.rollback(); diff --git a/app/service/systems/stock_store.js b/app/service/systems/stock_store.js index 36fc6e8..76a2b93 100644 --- a/app/service/systems/stock_store.js +++ b/app/service/systems/stock_store.js @@ -208,7 +208,7 @@ class stockStoreService extends Service { // ⭐ 关键修复:使用 raw: true 获取纯对象 const itemInfo = await ctx.model.StockStore.findByPk(itemId, { - attributes: ['id', 'stock_id', 'warehouse_code', 'item_code'], // 按需增加字段 + attributes: [ 'id', 'stock_id', 'warehouse_code', 'item_code' ], // 按需增加字段 raw: true, // ⭐ 必须:转换为纯 JavaScript 对象 }); @@ -245,7 +245,7 @@ class stockStoreService extends Service { app.logger.warn('缓存服务异常,降级直接查询数据库', itemId); try { const itemInfo = await ctx.model.StockStore.findByPk(itemId, { - attributes: ['id', 'stock_id', 'warehouse_code', 'item_code'], + attributes: [ 'id', 'stock_id', 'warehouse_code', 'item_code' ], raw: true, }); return itemInfo || null; @@ -854,7 +854,7 @@ class stockStoreService extends Service { store_id: sourceData.store_id, deleted_at: null, }, - attributes: ['id'], + attributes: [ 'id' ], raw: true, }); @@ -965,7 +965,7 @@ class stockStoreService extends Service { warehouse_id: warehouseId, is_valid: 'Y', }, - attributes: ['id'], + attributes: [ 'id' ], raw: true, }); @@ -1047,7 +1047,7 @@ class stockStoreService extends Service { where: {}, order: [], attributes: { - exclude: ['deleted_at'], + exclude: [ 'deleted_at' ], }, }; const barcodeQueryOptions = { @@ -1209,8 +1209,8 @@ class stockStoreService extends Service { // 查询匹配的条码,获取库存ID const matchedBarcodes = await ctx.model.StockBarcode.findAll({ ...barcodeQueryOptions, - attributes: ['stock_id'], - group: ['stock_id'], // 使用 GROUP BY 去重 + attributes: [ 'stock_id' ], + group: [ 'stock_id' ], // 使用 GROUP BY 去重 raw: true, }); @@ -1258,25 +1258,25 @@ class stockStoreService extends Service { const actualSortField = validSortFields.includes(sortField) ? sortField : 'create_at'; const actualSortOrder = sortOrder.toUpperCase() === 'ASC' ? 'ASC' : 'DESC'; - queryOptions.order.push([actualSortField, actualSortOrder]); + queryOptions.order.push([ actualSortField, actualSortOrder ]); // 计算分页偏移量 const offset = (page - 1) * pageSize; // 执行查询:获取总数和数据 - const [total, data] = await Promise.all([ + const [ total, data ] = await Promise.all([ // 获取总数 ctx.model.StockWarehouse.count({ where: queryOptions.where, - include: [ctx.model.StoreWarehouse.buildStoreStockInclude({ + include: [ ctx.model.StoreWarehouse.buildStoreStockInclude({ warehouseId: ctx.user.store_id, required: true, - attributes: ['store_remask'], + attributes: [ 'store_remask' ], }), { ...prohibitedQueryOptions, model: ctx.model.ProhibitedType, as: 'prohibited', - attributes: ['type_name'], + attributes: [ 'type_name' ], required: hasProhibitedCondition, }], distinct: true, @@ -1285,15 +1285,15 @@ class stockStoreService extends Service { // 获取分页数据 ctx.model.StockWarehouse.findAll({ ...queryOptions, - include: [ctx.model.StoreWarehouse.buildStoreStockInclude({ + include: [ ctx.model.StoreWarehouse.buildStoreStockInclude({ warehouseId: ctx.user.store_id, required: true, - attributes: ['store_remask'], + attributes: [ 'store_remask' ], }), { ...prohibitedQueryOptions, model: ctx.model.ProhibitedType, as: 'prohibited', - attributes: ['type_name'], + attributes: [ 'type_name' ], required: hasProhibitedCondition, }], limit: parseInt(pageSize), @@ -1331,7 +1331,7 @@ class stockStoreService extends Service { include: [{ model: ctx.model.File, as: 'file', - attributes: ['file_url'], + attributes: [ 'file_url' ], required: true, }], }); @@ -1516,9 +1516,9 @@ class stockStoreService extends Service { ], }, order: [ - ['warehouse_id', 'ASC'], // 系统预设在前(warehouse_id为null) - ['sort_order', 'ASC'], // 按排序字段 - ['created_at', 'ASC'], // 按创建时间 + [ 'warehouse_id', 'ASC' ], // 系统预设在前(warehouse_id为null) + [ 'sort_order', 'ASC' ], // 按排序字段 + [ 'created_at', 'ASC' ], // 按创建时间 ], attributes: [ 'id', @@ -1559,7 +1559,7 @@ class stockStoreService extends Service { include: [{ model: ctx.model.StockWarehouse, as: 'stock', - attributes: ['id'], + attributes: [ 'id' ], where: { warehouse_id: warehouseId, }, @@ -1573,7 +1573,7 @@ class stockStoreService extends Service { const { ctx, service, app } = this; const { Op } = app.Sequelize; - const canChangeFlide = ['brand_name', 'prohibited_id', 'gross_weight', 'packing_requirements', 'managementFlags', 'stock_unit']; + const canChangeFlide = [ 'brand_name', 'prohibited_id', 'gross_weight', 'packing_requirements', 'managementFlags', 'stock_unit' ]; const { ids, method, value } = ctx.request.body; console.log('批量修改参数', ctx.request.body); @@ -1605,7 +1605,7 @@ class stockStoreService extends Service { warehouse_id: warehouseId, delete_at: null, }, - attributes: ['id'], + attributes: [ 'id' ], }); if (existingRefs.length !== ids.length) { @@ -1651,7 +1651,7 @@ class stockStoreService extends Service { } // 验证三个管理标识字段 - const managementFields = ['is_sn_mgmt', 'is_shelf_life_mgmt', 'is_batch_mgmt']; + const managementFields = [ 'is_sn_mgmt', 'is_shelf_life_mgmt', 'is_batch_mgmt' ]; updateData = { update_at: new Date(), update_by: ctx.user.id || ctx.user.username, @@ -1661,7 +1661,7 @@ class stockStoreService extends Service { if (value[field] === undefined) { return { message: `管理标识缺少 ${field} 字段`, code: 405 }; } - if (!['Y', 'N'].includes(value[field])) { + if (![ 'Y', 'N' ].includes(value[field])) { return { message: `管理标识 ${field} 的值必须是 Y 或 N`, code: 405 }; } updateData[field] = value[field]; @@ -1683,7 +1683,7 @@ class stockStoreService extends Service { } // 5. 执行批量更新 - const [affectedRows] = await ctx.model.StockWarehouse.update(updateData, { + const [ affectedRows ] = await ctx.model.StockWarehouse.update(updateData, { where: { id: { [Op.in]: ids }, warehouse_id: warehouseId, @@ -1812,7 +1812,7 @@ class stockStoreService extends Service { include: [{ model: ctx.model.StockWarehouse, as: 'warehouse_stock', - attributes: ['id', 'store_id'], + attributes: [ 'id', 'store_id' ], where: { warehouse_id: warehouseId, }, @@ -1856,7 +1856,7 @@ class stockStoreService extends Service { StockStoreWhere[Op.or] = likeConditions; } const offset = (page - 1) * pageSize; - [total, barcodes] = await Promise.all([ + [ total, barcodes ] = await Promise.all([ ctx.model.StockStore.count({ where: StockStoreWhere, attributes: [ @@ -1865,7 +1865,7 @@ class stockStoreService extends Service { include: [{ model: ctx.model.StockWarehouse, as: 'warehouse_stock', - attributes: ['id'], + attributes: [ 'id' ], where: StockWarehouseWhere, required: false, }], @@ -1881,7 +1881,7 @@ class stockStoreService extends Service { include: [{ model: ctx.model.StockWarehouse, as: 'warehouse_stock', - attributes: ['id'], + attributes: [ 'id' ], where: StockWarehouseWhere, required: false, }], @@ -2132,7 +2132,7 @@ class stockStoreService extends Service { }); // 6. 执行更新 - const [affectedRows] = await ctx.model.StockWarehouse.update(updateData, { + const [ affectedRows ] = await ctx.model.StockWarehouse.update(updateData, { where: { id, warehouse_id: ctx.user.store_id, @@ -2285,7 +2285,7 @@ class stockStoreService extends Service { } validateSaveParams(data, isEdit = true) { - const requiredFields = ['item_code', 'item_name', 'stock_unit', 'gross_weight']; + const requiredFields = [ 'item_code', 'item_name', 'stock_unit', 'gross_weight' ]; if (!data.id && isEdit) { throw new Error('缺失必要参数: id'); } @@ -2300,7 +2300,7 @@ class stockStoreService extends Service { } // 数值类型验证 - const numericFields = ['length', 'width', 'height', 'volume', 'gross_weight', 'net_weight']; + const numericFields = [ 'length', 'width', 'height', 'volume', 'gross_weight', 'net_weight' ]; for (const field of numericFields) { if (data[field] && isNaN(Number(data[field]))) { throw new Error(`${field} 必须是有效的数字`); @@ -2334,7 +2334,7 @@ class stockStoreService extends Service { }; const space = await ctx.model.StockWarehouse.findOne({ where, - attributes: ['id'], + attributes: [ 'id' ], }); // 如果没有找到重复的条码,返回唯一 @@ -2372,11 +2372,11 @@ class stockStoreService extends Service { { model: ctx.model.Storage, as: 'storage', - attributes: ['id', 'quantity'], + attributes: [ 'id', 'quantity' ], required: false, // 使用left join,因为可能没有库存记录 }, ], - attributes: ['id', 'item_name', 'quantity', 'return_quantity'], + attributes: [ 'id', 'item_name', 'quantity', 'return_quantity' ], }); console.log('查询到的商品资料:', JSON.stringify(products, null, 2)); @@ -2442,7 +2442,7 @@ class stockStoreService extends Service { const result = await ctx.model.transaction(async t => { // 软删除商品资料 - const [affectedCount] = await ctx.model.StockWarehouse.update( + const [ affectedCount ] = await ctx.model.StockWarehouse.update( { deleted_at: new Date(), updated_at: new Date(), @@ -2586,7 +2586,7 @@ class stockStoreService extends Service { includeConditions.push({ model: app.model.StockBarcode, as: 'barcodes', - attributes: ['barcode'], + attributes: [ 'barcode' ], required: false, // 使用LEFT JOIN where: { barcode: { [Op.like]: searchKeyword }, @@ -2606,14 +2606,14 @@ class stockStoreService extends Service { includeConditions.push({ model: app.model.StockBarcode, as: 'barcodes', - attributes: ['barcode'], + attributes: [ 'barcode' ], required: false, }); } includeConditions.push(app.model.StoreWarehouse.buildStoreStockInclude({ warehouseId, required: false, - attributes: ['store_id', 'store_remask'], + attributes: [ 'store_id', 'store_remask' ], })); // 执行查询 @@ -2625,7 +2625,7 @@ class stockStoreService extends Service { 'sku_property', 'stock_unit', 'quantity', 'locked_quantity', 'brand_name', 'item_type', ], - order: [['create_at', 'DESC']], + order: [[ 'create_at', 'DESC' ]], limit: 50, include: includeConditions, subQuery: false, // 避免子查询,提高性能 diff --git a/app/service/systems/storage/index.js b/app/service/systems/storage/index.js index 2721913..f113ac8 100644 --- a/app/service/systems/storage/index.js +++ b/app/service/systems/storage/index.js @@ -26,7 +26,7 @@ class IndexService extends Service { { model: ctx.model.Store, as: 'warehouse', - attributes: [ [ 'company_name', 'store_name' ] ], + attributes: [[ 'company_name', 'store_name' ]], }, ], }); @@ -48,7 +48,7 @@ class IndexService extends Service { attributes: [ 'product_code', 'product_name' ], }, ], - order: [ [ 'inbound_time', 'ASC' ] ], + order: [[ 'inbound_time', 'ASC' ]], }); } @@ -104,7 +104,7 @@ class IndexService extends Service { { model: ctx.model.Store, as: 'warehouse', - attributes: [ [ 'company_name', 'store_name' ] ], + attributes: [[ 'company_name', 'store_name' ]], }, { model: ctx.model.StockWarehouse, @@ -112,7 +112,7 @@ class IndexService extends Service { attributes: [ 'product_code', 'product_name' ], }, ], - order: [ [ 'expiry_date', 'ASC' ] ], + order: [[ 'expiry_date', 'ASC' ]], }); } diff --git a/app/service/systems/storage/receiving.js b/app/service/systems/storage/receiving.js index 4a899a8..b165865 100644 --- a/app/service/systems/storage/receiving.js +++ b/app/service/systems/storage/receiving.js @@ -294,11 +294,11 @@ class ReceivingService extends Service { }); // 获取明细总数 const totalItems = await app.model.ReceivingDetail.count({ where: { receiving_id: id } }); - //组装分页信息 + // 组装分页信息 const pagination = { total: totalItems, currentPage: page, - pageSize: pageSize, + pageSize, totalPages: Math.ceil(totalItems / pageSize), hasPrevious: page > 1, hasNext: page < Math.ceil(totalItems / pageSize), @@ -317,7 +317,7 @@ class ReceivingService extends Service { include: [{ model: ctx.model.File, as: 'file', - attributes: ['file_url'], + attributes: [ 'file_url' ], required: true, }], }); @@ -348,7 +348,7 @@ class ReceivingService extends Service { include: [{ model: ctx.model.File, as: 'file', - attributes: ['file_url'], + attributes: [ 'file_url' ], required: true, }], }); @@ -378,19 +378,19 @@ class ReceivingService extends Service { const { Op } = ctx.model.Sequelize; const warehouse_id = ctx.user.store_id; try { - //先查询这些单据是否都存在且状态允许作废 - const receivings = await ctx.model.Receiving.findAll({where:{ id: { [Op.in]: ids }, warehouse_id }}); + // 先查询这些单据是否都存在且状态允许作废 + const receivings = await ctx.model.Receiving.findAll({ where: { id: { [Op.in]: ids }, warehouse_id } }); if (receivings.length !== ids.length) { return { code: 0, message: '部分单据不存在或无权访问', data: {} }; - }else{ - const invalidStatus = receivings.find(r => r.status !== 'receiving'); - if (invalidStatus) { - return { code: 0, message: '部分单据状态不允许作废', data: {} }; - } - // 批量更新状态为cancelled - await ctx.model.Receiving.update({ status: 'cancelled' }, { where: { id: { [Op.in]: ids }, warehouse_id } }); - return { code: 200, message: '批量作废成功', data: {} }; } + const invalidStatus = receivings.find(r => r.status !== 'receiving'); + if (invalidStatus) { + return { code: 0, message: '部分单据状态不允许作废', data: {} }; + } + // 批量更新状态为cancelled + await ctx.model.Receiving.update({ status: 'cancelled' }, { where: { id: { [Op.in]: ids }, warehouse_id } }); + return { code: 200, message: '批量作废成功', data: {} }; + } catch (error) { console.error('批量作废收货单失败:', error); return { code: 500, message: '服务器错误', data: {} }; @@ -625,7 +625,7 @@ class ReceivingService extends Service { case 'daterange': // 处理日期范围:数组的第一个元素是开始时间,第二个元素是结束时间 if (Array.isArray(value) && value.length === 2) { - const [startDate, endDate] = value; + const [ startDate, endDate ] = value; console.log(startDate, endDate); console.log(startDate ? service.main.normalizeDate(startDate, false) : null, endDate ? service.main.normalizeDate(endDate, true) : null); return [ @@ -652,7 +652,7 @@ class ReceivingService extends Service { } } - buildReceivingPrefix(date = new Date()) { + buildReceivingNumberPrefix(date = new Date()) { const dateStr = Math.floor(date.getTime() / (1000 * 60 * 60 * 24)); return `R${dateStr}`; } @@ -669,7 +669,7 @@ class ReceivingService extends Service { }, }, order: [ - [app.Sequelize.literal(`CAST(SUBSTRING(receiving_number, ${suffixStartIndex}) AS UNSIGNED)`), 'DESC'], + [ app.Sequelize.literal(`CAST(SUBSTRING(receiving_number, ${suffixStartIndex}) AS UNSIGNED)`), 'DESC' ], [ 'receiving_number', 'DESC' ], ], }); @@ -730,7 +730,7 @@ class ReceivingService extends Service { // 不能按 warehouse_id 各自从 001 开始,否则跨仓会撞号;并发创建时也需要重试兜底。 const now = new Date(); console.log('当前时间:', now); - const prefix = this.buildReceivingPrefix(now); + const prefix = this.buildReceivingNumberPrefix(now); // 3. 获取店铺名称(如果有货主) let store_name = null; @@ -971,7 +971,7 @@ class ReceivingService extends Service { include: [{ model: ctx.model.StoreWarehouse, as: 'store', - attributes: ['store_remask'], + attributes: [ 'store_remask' ], where: { use_status: 1, warehouse_id: warehouseId, @@ -980,7 +980,7 @@ class ReceivingService extends Service { }, { model: ctx.model.AccountStoreEmployee, as: 'creator', - attributes: ['real_name'], + attributes: [ 'real_name' ], required: false, }], // 不需要order,因为根据id查询已经是唯一的 @@ -999,10 +999,10 @@ class ReceivingService extends Service { { model: ctx.model.LocationSpace, as: 'receiving_space', - attributes: ['space_code', 'custom_barcode', 'custom_name'], + attributes: [ 'space_code', 'custom_barcode', 'custom_name' ], }, ], - order: [['id', 'DESC']], // 保持倒序,最新在前 + order: [[ 'id', 'DESC' ]], // 保持倒序,最新在前 }); // 3. 获取明细ID数组 @@ -1021,7 +1021,7 @@ class ReceivingService extends Service { include: [{ model: ctx.model.File, as: 'file', - attributes: ['file_url'], + attributes: [ 'file_url' ], required: true, }], }); @@ -1055,7 +1055,7 @@ class ReceivingService extends Service { include: [{ model: ctx.model.File, as: 'file', - attributes: ['file_url'], + attributes: [ 'file_url' ], required: true, }], }); @@ -1136,7 +1136,7 @@ class ReceivingService extends Service { // 获取更新后的明细列表 const allDetails = await ctx.model.ReceivingDetail.findAll({ where: { receiving_id }, - order: [['id', 'DESC']], + order: [[ 'id', 'DESC' ]], }); // 格式化返回数据 @@ -1348,7 +1348,7 @@ class ReceivingService extends Service { { model: ctx.model.Receiving, as: 'receiving', - attributes: ['id', 'status'], + attributes: [ 'id', 'status' ], }, ], }); @@ -1441,7 +1441,7 @@ class ReceivingService extends Service { } // 更新明细 - const [affectedRows] = await ctx.model.ReceivingDetail.update(updateData, { + const [ affectedRows ] = await ctx.model.ReceivingDetail.update(updateData, { where: { id }, }); @@ -1464,7 +1464,7 @@ class ReceivingService extends Service { { model: ctx.model.StockWarehouse, as: 'system_product', - attributes: ['id', 'name', 'barcode', 'spec', 'unit', 'images'], + attributes: [ 'id', 'name', 'barcode', 'spec', 'unit', 'images' ], }, ], }); @@ -1597,8 +1597,8 @@ class ReceivingService extends Service { const stats = await ctx.model.ReceivingDetail.findAll({ where: { receiving_id: receivingId }, attributes: [ - [ctx.model.fn('COUNT', ctx.model.col('id')), 'total_items'], - [ctx.model.fn('SUM', ctx.model.col('actual_quantity')), 'total_quantity'], + [ ctx.model.fn('COUNT', ctx.model.col('id')), 'total_items' ], + [ ctx.model.fn('SUM', ctx.model.col('actual_quantity')), 'total_quantity' ], ], raw: true, transaction, @@ -1682,7 +1682,7 @@ class ReceivingService extends Service { { model: ctx.model.Receiving, as: 'receiving', - attributes: ['id', 'status'], + attributes: [ 'id', 'status' ], where: { warehouse_id, }, @@ -1733,7 +1733,7 @@ class ReceivingService extends Service { // 获取删除后的所有明细 const remainingDetails = await ctx.model.ReceivingDetail.findAll({ where: { receiving_id }, - order: [['id', 'DESC']], + order: [[ 'id', 'DESC' ]], }); // 格式化返回数据 @@ -1830,7 +1830,7 @@ class ReceivingService extends Service { { model: app.model.Receiving, as: 'receiving', - attributes: ['id', 'warehouse_id', 'store_id', 'store_name'], + attributes: [ 'id', 'warehouse_id', 'store_id', 'store_name' ], where: { warehouse_id: warehouseId, id: receiving_id, @@ -1906,7 +1906,7 @@ class ReceivingService extends Service { { model: app.model.StockBarcode, as: 'barcodes', - attributes: ['barcode'], + attributes: [ 'barcode' ], required: false, }, ], @@ -2137,6 +2137,19 @@ class ReceivingService extends Service { return date.toLocaleString('zh-CN', { hour12: false }); } + formatDeliveryMethod(value) { + const methodMap = { + truck: '货车', + express: '快递', + air_freight: '空运', + sea_freight: '海运', + other: '其他', + }; + + const normalizedValue = String(value || '').trim(); + return methodMap[normalizedValue] || normalizedValue; + } + buildCompletionReportSheets({ receiving, operator = {}, @@ -2213,10 +2226,8 @@ class ReceivingService extends Service { [ [ '收货单ID', receiving && receiving.id ], [ '收货单号', receiving && receiving.receiving_number ], - [ '状态', receiving && receiving.status ], [ '货主', receiving && receiving.store_name ], - [ '仓库ID', receiving && receiving.warehouse_id ], - [ '来货方式', receiving && receiving.delivery_method ], + [ '来货方式', this.formatDeliveryMethod(receiving && receiving.delivery_method) ], [ '车牌号', receiving && receiving.license_plate ], [ '物流单号', receiving && receiving.tracking_number ], [ '总明细数', stats.total_details || details.length ], @@ -2388,6 +2399,99 @@ class ReceivingService extends Service { }); } + /** + * 发送收货完成统一通知,通知外部订阅 `receiving_completed` 事件。 + * @param {Object} options 通知参数 + * @param {Object} options.receiving 收货单快照 + * @param {Object} [options.operator={}] 操作人信息 + * @param {Object} [options.stats={}] 收货统计 + * @param {Object|null} [options.completionReport=null] 完成报表信息 + * @return {Promise} + */ + async sendCompletionNotice({ + receiving, + operator = {}, + stats = {}, + completionReport = null, + } = {}) { + const { ctx } = this; + const rawNoticeService = ctx && ctx.service && ctx.service.systems && ctx.service.systems.notice; + const noticeService = rawNoticeService && typeof rawNoticeService.send === 'function' + ? rawNoticeService + : (rawNoticeService && rawNoticeService.index && typeof rawNoticeService.index.send === 'function' + ? rawNoticeService.index + : null); + + if (!receiving || !receiving.id || !noticeService) { + return null; + } + + const warehouseId = Number(receiving.warehouse_id || (ctx.user && ctx.user.store_id) || 0); + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + return null; + } + + const storeId = Number(receiving.store_id || 0); + const matchedDetails = Number(stats.matched_details || 0); + const unmatchedDetails = Number(stats.unmatched_details || 0); + const totalQuantity = Number(stats.total_quantity || 0); + const operatorName = String(operator.employees_name || operator.real_name || operator.name || '').trim(); + const receivingNumber = String(receiving.receiving_number || receiving.id || '').trim() || String(receiving.id); + const reportUrl = String( + (completionReport && (completionReport.url || completionReport.cdnUrl || completionReport.cosUrl || completionReport.fileUrl)) || '' + ).trim(); + const reportFileName = String( + (completionReport && (completionReport.filename || completionReport.fileKey || completionReport.key)) || `收货完成_${receivingNumber}.xlsx` + ).trim(); + const title = `收货单${receivingNumber}已完成`; + const content = [ + `收货单${receivingNumber}已完成`, + `匹配商品${matchedDetails}件`, + `未匹配商品${unmatchedDetails}件`, + `总数量${totalQuantity}`, + operatorName ? `完成人${operatorName}` : '', + ].filter(Boolean).join(',') + '。'; + + return await noticeService.send({ + warehouseId, + storeId: Number.isFinite(storeId) && storeId > 0 ? storeId : undefined, + messageType: reportUrl ? 'file' : 'text', + businessName: 'receiving', + event: 'receiving_completed', + title, + content, + url: reportUrl || undefined, + fileName: reportUrl ? reportFileName : '', + mimeType: reportUrl ? 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' : '', + businessId: receiving.id, + subject: { + id: warehouseId, + type: 'warehouse', + name: String((ctx.user && (ctx.user.store_name || ctx.user.company_name)) || ''), + }, + sender: { + id: operator.employees_id || operator.id || null, + name: operatorName, + }, + metadata: { + receivingId: receiving.id, + receivingNumber, + warehouseId, + storeId: Number.isFinite(storeId) && storeId > 0 ? storeId : null, + stats: { + total_details: Number(stats.total_details || 0), + matched_details: matchedDetails, + unmatched_details: unmatchedDetails, + total_quantity: totalQuantity, + }, + completionReport: completionReport ? { + fileKey: completionReport.fileKey || completionReport.key || '', + url: reportUrl, + } : null, + }, + }); + } + /** * 完成收货单:校验明细、更新状态并写入库存。 * @param {Object} data 请求体 @@ -2458,8 +2562,9 @@ class ReceivingService extends Service { }; } - // 4. 校验所有明细的完成条件 - const invalidDetails = []; + // 4. 准备明细图片与统计信息。 + // 按最新要求:收货完成通知不再受“必须绑定商品/必须补齐照片条码重量数量”限制, + // 只要用户执行完成收货且存在明细,即允许完成并继续发送通知。 const unmatchedDetails = receiving.details.filter(d => !d.system_product_id); const detailsIds = receiving.details.map(item => item.id); @@ -2513,51 +2618,7 @@ class ReceivingService extends Service { })) .filter(item => item.url); - for (const detail of receiving.details) { - const businessId = String(detail.id).trim(); - const imageArray = imageMap.get(businessId) || []; - const hasPhoto = imageArray.some(img => !!(img && img.url)); - const hasBarcode = !!detail.barcode && detail.barcode.trim() !== ''; - const hasWeight = Number(detail.weight || 0) > 0; - const hasCount = Number(detail.actual_quantity || 0) > 0; - - if (!hasPhoto || !hasBarcode || !hasWeight || !hasCount) { - const itemName = detail.product_name || '未命名商品'; - invalidDetails.push({ - detail_id: detail.id, - item_name: itemName, - missing_fields: [ - !hasPhoto && '照片', - !hasBarcode && '条码', - !hasWeight && '重量', - !hasCount && '数量', - ].filter(Boolean), - }); - } - } - - // 5. 如果有不符合条件的明细,返回错误 - if (invalidDetails.length > 0) { - await transaction.rollback(); - - const errorMsg = invalidDetails.length === 1 - ? `商品"${invalidDetails[0].item_name}"缺少${invalidDetails[0].missing_fields.join('、')}` - : `有${invalidDetails.length}个商品缺少必要信息`; - - return { - success: false, - code: 'DETAIL_INCOMPLETE', - message: errorMsg, - data: { - invalid_details: invalidDetails, - total_details: receiving.details.length, - matched_details: receiving.details.filter(d => d.system_product_id).length, - unmatched_details: unmatchedDetails.length, - }, - }; - } - - // 7. 获取操作人信息 + // 5. 获取操作人信息 const operator = ctx.user; // 8. 更新收货单状态 @@ -2597,6 +2658,33 @@ class ReceivingService extends Service { ...updateData, }; + const completionNoticePayload = { + receiving: receivingSnapshot, + operator, + stats, + }; + + // 11. 收货成功后先触发文字通知,再生成 Excel;若 Excel 成功,再补发文件通知。 + try { + const textNoticeResult = await this.sendCompletionNotice(completionNoticePayload); + ctx.logger.info('收货完成文字通知结果', { + receiving_id: id, + receiving_number: receiving.receiving_number, + warehouseId, + success: !!(textNoticeResult && textNoticeResult.success), + message: textNoticeResult && textNoticeResult.message, + matchedHookCount: Number(textNoticeResult && textNoticeResult.data && textNoticeResult.data.matchedHookCount || 0), + sentCount: Number(textNoticeResult && textNoticeResult.data && textNoticeResult.data.sentCount || 0), + failedCount: Number(textNoticeResult && textNoticeResult.data && textNoticeResult.data.failedCount || 0), + }); + } catch (notifyError) { + ctx.logger.error(`收货完成文字通知发送失败: ${notifyError.message}`, { + receiving_id: id, + warehouseId, + error: notifyError.stack, + }); + } + let completionReport = null; try { completionReport = await this.uploadCompletionExcelReport({ @@ -2606,32 +2694,40 @@ class ReceivingService extends Service { detailImageMap: imageMap, receivingImages: receivingImageList, }); + + if (completionReport) { + try { + const fileNoticeResult = await this.sendCompletionNotice({ + ...completionNoticePayload, + completionReport, + }); + ctx.logger.info('收货完成文件通知结果', { + receiving_id: id, + receiving_number: receiving.receiving_number, + warehouseId, + success: !!(fileNoticeResult && fileNoticeResult.success), + message: fileNoticeResult && fileNoticeResult.message, + matchedHookCount: Number(fileNoticeResult && fileNoticeResult.data && fileNoticeResult.data.matchedHookCount || 0), + sentCount: Number(fileNoticeResult && fileNoticeResult.data && fileNoticeResult.data.sentCount || 0), + failedCount: Number(fileNoticeResult && fileNoticeResult.data && fileNoticeResult.data.failedCount || 0), + reportUrl: completionReport.url || completionReport.cdnUrl || completionReport.cosUrl || '', + }); + } catch (notifyError) { + ctx.logger.error(`收货完成文件通知发送失败: ${notifyError.message}`, { + receiving_id: id, + warehouseId, + error: notifyError.stack, + }); + } + } } catch (reportError) { - ctx.logger.error(`收货完成报表上传失败: ${reportError.message}`, { + ctx.logger.error(`收货完成报表上传失败,仅保留文字通知: ${reportError.message}`, { receiving_id: id, warehouseId, error: reportError.stack, }); } - if (stats.matched_details > 0) { - try { - await ctx.service.systems.notification.send({ - type: 'system', - title: `收货单${receiving.receiving_number}已完成`, - content: `收货单${receiving.receiving_number}已完成,匹配商品${stats.matched_details}件,未匹配商品${stats.unmatched_details}件。`, - bussinessType: 'receiving', - bussinessId: receiving.id, - }); - } catch (notifyError) { - ctx.logger.error(`收货完成通知发送失败: ${notifyError.message}`, { - receiving_id: id, - warehouseId, - error: notifyError.stack, - }); - } - } - ctx.logger.info('收货单已完成', { receiving_id: id, receiving_number: receiving.receiving_number, diff --git a/app/service/systems/store.js b/app/service/systems/store.js index 85dcaff..de75211 100644 --- a/app/service/systems/store.js +++ b/app/service/systems/store.js @@ -2,6 +2,17 @@ const Service = require('egg').Service; class StoreService extends Service { + normalizeSubjectConfigInput(data = {}) { + const rawSubjectConfig = data.subject_config !== undefined ? data.subject_config : data.subjectConfig; + if (this.app.model.Store && typeof this.app.model.Store.normalizeSubjectConfig === 'function') { + return this.app.model.Store.normalizeSubjectConfig(rawSubjectConfig); + } + + return { + max_notice_webhook_count: 5, + }; + } + validateStoreData(data = {}) { const errors = []; @@ -23,6 +34,14 @@ class StoreService extends Service { } } + if (data.subject_config !== undefined || data.subjectConfig !== undefined) { + try { + this.normalizeSubjectConfigInput(data); + } catch (error) { + errors.push(error.message); + } + } + return errors; } @@ -187,6 +206,18 @@ class StoreService extends Service { }; } + let subjectConfig = null; + try { + subjectConfig = this.normalizeSubjectConfigInput(data); + } catch (error) { + await transaction.rollback(); + return { + code: 400, + message: error.message, + data: null, + }; + } + // 创建商家 const storeData = { company_name: data.company_name, @@ -205,6 +236,7 @@ class StoreService extends Service { domain: data.domain, auth_start: data.auth_start, auth_end: data.auth_end, + subject_config: subjectConfig, }; const store = await ctx.model.Store.create(storeData, { @@ -294,6 +326,18 @@ class StoreService extends Service { }; } + let subjectConfig = null; + try { + subjectConfig = this.normalizeSubjectConfigInput(data); + } catch (error) { + await transaction.rollback(); + return { + code: 400, + message: error.message, + data: null, + }; + } + // 创建仓库(也是商家,但 is_warehouse = 1) const warehouseData = { company_name: data.company_name, @@ -312,6 +356,7 @@ class StoreService extends Service { domain: data.domain, auth_start: new Date(), // 设置当前时间为授权开始时间 auth_end: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000), // 默认授权7天试用 + subject_config: subjectConfig, }; const warehouse = await ctx.model.Store.create(warehouseData, { diff --git a/app/service/systems/upload.js b/app/service/systems/upload.js index 763d2c7..0a796da 100644 --- a/app/service/systems/upload.js +++ b/app/service/systems/upload.js @@ -400,17 +400,25 @@ class UploadService extends Service { this.ctx.logger.warn('上传成功通知缺少用户信息,使用默认值'); } + const resolvedFileKey = String(data.url || data.fileKey || ''); + const resolvedFileName = String(data.fileName || data.name || path.basename(resolvedFileKey || 'file')); + const resolvedFileSize = Number(data.fileSize || data.size || 0); + // 生成完整的访问URL - const fileUrl = `${this.config.cos.cdnurl || this.config.cos.uploadurl}/${data.url}`; + const fileUrl = `${this.config.cos.cdnurl || this.config.cos.uploadurl}/${resolvedFileKey}`; // 计算哈希值(如果前端没有提供) - let md5Hash = data.md5; + let md5Hash = data.md5Hash || data.md5 || ''; + let sha1Hash = data.sha1Hash || data.sha1 || ''; if (!md5Hash && data.fileContent) { - // 如果有文件内容,可以计算哈希 md5Hash = crypto.createHash('md5').update(data.fileContent).digest('hex'); } + if (!sha1Hash && data.fileContent) { + sha1Hash = crypto.createHash('sha1').update(data.fileContent).digest('hex'); + } + const resolvedFileType = String(data.fileType || data.category || data.type || 'document'); const resolvedMimeType = String(data.mimeType || data.type || this.getMimeType(data.fileName || data.name || 'file.xlsx')); const defaultExpireDays = data.businessType === 'receivingReport' ? 90 : 0; @@ -426,16 +434,32 @@ class UploadService extends Service { resolvedExpireTime = Number.isNaN(expireDate.getTime()) ? null : expireDate; } + if (!md5Hash) { + const fallbackFingerprint = JSON.stringify({ + warehouseId: warehouseId || 0, + url: resolvedFileKey, + fileName: resolvedFileName, + fileSize: resolvedFileSize, + mimeType: resolvedMimeType, + }); + md5Hash = crypto.createHash('md5').update(fallbackFingerprint).digest('hex'); + } + + if (!sha1Hash) { + sha1Hash = crypto.createHash('sha1').update(`${md5Hash}:${resolvedFileKey || fileUrl}`).digest('hex'); + } + // 构建数据库记录 const fileRecord = { warehouse_id: warehouseId || 0, // 默认为0或使用默认仓库 - file_key: data.url, + file_key: resolvedFileKey, file_url: fileUrl, - file_name: data.name, - file_size: data.size, + file_name: resolvedFileName, + file_size: resolvedFileSize, file_type: resolvedFileType, mime_type: resolvedMimeType, - md5_hash: md5Hash || '', + md5_hash: md5Hash, + sha1_hash: sha1Hash, storage_mode: 'cos', storage_class: 'standard', uploader_id: userId?.toString() || '0', @@ -463,6 +487,13 @@ class UploadService extends Service { }); } + if (data.businessType && data.businessId) { + await this.createFileReference(existingFile.id, data.businessType, data.businessId, { + warehouseId, + createdBy: userName, + }); + } + this.ctx.logger.info(`文件已存在,返回已有记录: ${existingFile.file_url}`); return { fileId: existingFile.id, @@ -480,10 +511,13 @@ class UploadService extends Service { // 根据业务类型创建引用关系(如果需要) if (data.businessType && data.businessId) { - await this.createFileReference(savedFile.id, data.businessType, data.businessId); + await this.createFileReference(savedFile.id, data.businessType, data.businessId, { + warehouseId, + createdBy: userName, + }); } - this.ctx.logger.info(`文件记录保存成功: ${savedFile.id} - ${data.fileName}`); + this.ctx.logger.info(`文件记录保存成功: ${savedFile.id} - ${resolvedFileName}`); // 返回成功响应 return { @@ -492,10 +526,10 @@ class UploadService extends Service { data: { fileId: savedFile.id, fileUrl, - fileKey: data.fileKey, - fileName: data.fileName, - fileSize: data.fileSize, - mimeType: data.mimeType, + fileKey: resolvedFileKey, + fileName: resolvedFileName, + fileSize: resolvedFileSize, + mimeType: resolvedMimeType, isNew: true, createdAt: savedFile.created_at, }, @@ -557,25 +591,65 @@ class UploadService extends Service { * @param fileId * @param businessType * @param businessId + * @param {Object} [options] + * @param {number|string} [options.warehouseId] + * @param {string} [options.createdBy] + * @param {number} [options.displayOrder] */ - async createFileReference(fileId, businessType, businessId) { + async createFileReference(fileId, businessType, businessId, options = {}) { const { ctx } = this; try { - // 如果有文件引用模型 - if (ctx.model.FileReference) { - const reference = await ctx.model.FileReference.create({ - file_id: fileId, - business_type: businessType, - business_id: businessId, - created_at: new Date(), - }); - - this.ctx.logger.info(`文件引用关系创建成功: fileId=${fileId}, businessType=${businessType}, businessId=${businessId}`); - return reference; + if (!ctx.model.FileReference) { + return null; } - return null; + const warehouseId = Number( + options.warehouseId || ctx.user?.store_id || ctx.query.warehouseId || ctx.request.body.warehouseId || 0 + ) || 0; + const createdBy = String( + options.createdBy || ctx.user?.real_name || ctx.user?.username || ctx.user?.id || 'system' + ).trim() || 'system'; + const normalizedBusinessType = String(businessType || '').trim(); + const normalizedBusinessId = String(businessId || '').trim(); + const displayOrder = Number(options.displayOrder || 0) || 0; + + if (!fileId || !normalizedBusinessType || !normalizedBusinessId) { + this.ctx.logger.warn('创建文件引用关系参数不完整,已跳过', { + fileId, + businessType: normalizedBusinessType, + businessId: normalizedBusinessId, + }); + return null; + } + + if (typeof ctx.model.FileReference.findOne === 'function') { + const existingReference = await ctx.model.FileReference.findOne({ + where: { + file_id: fileId, + warehouse_id: warehouseId, + business_type: normalizedBusinessType, + business_id: normalizedBusinessId, + }, + }); + + if (existingReference) { + return existingReference; + } + } + + const reference = await ctx.model.FileReference.create({ + file_id: fileId, + warehouse_id: warehouseId, + business_type: normalizedBusinessType, + business_id: normalizedBusinessId, + display_order: displayOrder, + created_by: createdBy, + created_at: new Date(), + }); + + this.ctx.logger.info(`文件引用关系创建成功: fileId=${fileId}, businessType=${normalizedBusinessType}, businessId=${normalizedBusinessId}`); + return reference; } catch (error) { this.ctx.logger.error(`创建文件引用关系失败: ${error.message}`); return null; diff --git a/config/config.default.js b/config/config.default.js index 9c88140..76e8613 100644 --- a/config/config.default.js +++ b/config/config.default.js @@ -31,7 +31,7 @@ module.exports = appInfo => { host: '112.124.21.102', password: 'qwe2019@', db: 11, - } + }, }, }; config.security = { @@ -119,13 +119,13 @@ module.exports = appInfo => { password: 'P6j3YTHTpirepYWz', database: 'wms', }, - ye4s:{ + ye4s: { host: '112.124.21.102', port: '3306', user: 'ye4s', password: 'H@8h^QE4N$L.F_*', database: 'ye4s', - } + }, }, app: true, agent: false, @@ -169,9 +169,9 @@ module.exports = appInfo => { hostname: '0.0.0.0', }, }; - config.poloapi ={ + config.poloapi = { - } + }; config.debug = false; // 生成环境默认关闭 debug,开发环境通过 config.local.js 开启 config.printService = { url: 'http://printer.wms.gztbyc.com', diff --git a/config/poloapi.js b/config/poloapi.js index f738b18..934c491 100644 --- a/config/poloapi.js +++ b/config/poloapi.js @@ -2,28 +2,28 @@ // 快手/PolyAPI相关固定配置 module.exports = { - appKey: "8e770a60b9684c558f40e4796a96710f", - appSecret: "c9cb1df531b441a8872c60ffb7f900a6", - platid: "633", - version: "1.5", - contenttype: "json", - urls: "https://api.polyapi.com/openapi/do", + appKey: '8e770a60b9684c558f40e4796a96710f', + appSecret: 'c9cb1df531b441a8872c60ffb7f900a6', + platid: '633', + version: '1.5', + contenttype: 'json', + urls: 'https://api.polyapi.com/openapi/do', // 快递公司代码映射 postCodeMap: { - p01: "YTO", - p02: "STO", - p03: "YUNDA", - p04: "ZTO", - p05: "SF", - p06: "TTKDEX", - p07: "EMS", - p10: "JD", - p22: "POSTB", - p35: "POST_DSBK", - p09: "huitongkuaidi", - p26: "debangwuliu", - p32: "JT", - p34: "FENGWANG" - } + p01: 'YTO', + p02: 'STO', + p03: 'YUNDA', + p04: 'ZTO', + p05: 'SF', + p06: 'TTKDEX', + p07: 'EMS', + p10: 'JD', + p22: 'POSTB', + p35: 'POST_DSBK', + p09: 'huitongkuaidi', + p26: 'debangwuliu', + p32: 'JT', + p34: 'FENGWANG', + }, // 如有更多固定配置,可继续补充 }; diff --git a/database/migrations/20260405011000-add-subject-config-to-wms-store.js b/database/migrations/20260405011000-add-subject-config-to-wms-store.js new file mode 100644 index 0000000..25e379a --- /dev/null +++ b/database/migrations/20260405011000-add-subject-config-to-wms-store.js @@ -0,0 +1,26 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + const [ columns ] = await queryInterface.sequelize.query("SHOW COLUMNS FROM `wms_store` LIKE 'subject_config'"); + if (columns.length > 0) { + return; + } + + await queryInterface.addColumn('wms_store', 'subject_config', { + type: Sequelize.JSON, + allowNull: true, + defaultValue: null, + comment: '主体配置JSON', + }); + }, + + async down(queryInterface) { + const [ columns ] = await queryInterface.sequelize.query("SHOW COLUMNS FROM `wms_store` LIKE 'subject_config'"); + if (columns.length === 0) { + return; + } + + await queryInterface.removeColumn('wms_store', 'subject_config'); + }, +}; diff --git a/database/migrations/20260405013000-init-wms-store-subject-config-webhook-limit.js b/database/migrations/20260405013000-init-wms-store-subject-config-webhook-limit.js new file mode 100644 index 0000000..9309614 --- /dev/null +++ b/database/migrations/20260405013000-init-wms-store-subject-config-webhook-limit.js @@ -0,0 +1,28 @@ +'use strict'; + +module.exports = { + async up(queryInterface) { + const [ columns ] = await queryInterface.sequelize.query("SHOW COLUMNS FROM `wms_store` LIKE 'subject_config'"); + if (columns.length === 0) { + return; + } + + await queryInterface.sequelize.query(` + UPDATE wms_store + SET subject_config = JSON_SET(COALESCE(subject_config, JSON_OBJECT()), '$.max_notice_webhook_count', 5) + `); + }, + + async down(queryInterface) { + const [ columns ] = await queryInterface.sequelize.query("SHOW COLUMNS FROM `wms_store` LIKE 'subject_config'"); + if (columns.length === 0) { + return; + } + + await queryInterface.sequelize.query(` + UPDATE wms_store + SET subject_config = JSON_REMOVE(subject_config, '$.max_notice_webhook_count') + WHERE subject_config IS NOT NULL + `); + }, +}; diff --git a/database/migrations/20260405015000-drop-extra-config-from-notification-webhook.js b/database/migrations/20260405015000-drop-extra-config-from-notification-webhook.js new file mode 100644 index 0000000..4c1242b --- /dev/null +++ b/database/migrations/20260405015000-drop-extra-config-from-notification-webhook.js @@ -0,0 +1,25 @@ +'use strict'; + +module.exports = { + async up(queryInterface) { + const [ columns ] = await queryInterface.sequelize.query("SHOW COLUMNS FROM `wms_notification_webhook` LIKE 'extra_config'"); + if (columns.length === 0) { + return; + } + + await queryInterface.removeColumn('wms_notification_webhook', 'extra_config'); + }, + + async down(queryInterface, Sequelize) { + const [ columns ] = await queryInterface.sequelize.query("SHOW COLUMNS FROM `wms_notification_webhook` LIKE 'extra_config'"); + if (columns.length > 0) { + return; + } + + await queryInterface.addColumn('wms_notification_webhook', 'extra_config', { + type: Sequelize.JSON, + allowNull: true, + comment: '扩展配置,如签名、请求头、模板映射等', + }); + }, +}; diff --git a/database/migrations/20260405024000-create-wms-notification-send-log.js b/database/migrations/20260405024000-create-wms-notification-send-log.js new file mode 100644 index 0000000..2f52cb2 --- /dev/null +++ b/database/migrations/20260405024000-create-wms-notification-send-log.js @@ -0,0 +1,152 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + const { BIGINT, STRING, DATE, INTEGER, JSON } = Sequelize; + const BIGINT_UNSIGNED = BIGINT.UNSIGNED; + + const [ tables ] = await queryInterface.sequelize.query( + "SHOW TABLES LIKE 'wms_notification_send_log'" + ); + + if (tables.length === 0) { + await queryInterface.createTable('wms_notification_send_log', { + id: { + type: BIGINT_UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + trace_id: { + type: STRING(100), + allowNull: false, + comment: '通知追踪ID', + }, + webhook_id: { + type: BIGINT_UNSIGNED, + allowNull: true, + comment: 'Webhook 配置ID', + }, + store_id: { + type: BIGINT_UNSIGNED, + allowNull: true, + comment: '触发主体ID', + }, + warehouse_id: { + type: BIGINT_UNSIGNED, + allowNull: true, + comment: '仓库ID', + }, + owner_store_id: { + type: BIGINT_UNSIGNED, + allowNull: true, + comment: '货主ID', + }, + business_name: { + type: STRING(100), + allowNull: false, + comment: '业务名称', + }, + event: { + type: STRING(100), + allowNull: false, + comment: '事件名', + }, + hook_type: { + type: STRING(50), + allowNull: true, + comment: 'Webhook 类型', + }, + hook_url: { + type: STRING(500), + allowNull: true, + comment: 'Webhook 地址', + }, + request_payload: { + type: JSON, + allowNull: true, + comment: '请求载荷', + }, + response_payload: { + type: JSON, + allowNull: true, + comment: '返回载荷', + }, + http_status: { + type: INTEGER(11), + allowNull: true, + comment: 'HTTP 状态码', + }, + status: { + type: STRING(20), + allowNull: false, + defaultValue: 'failed', + comment: '发送状态', + }, + error_message: { + type: STRING(1000), + allowNull: true, + comment: '失败原因', + }, + retry_count: { + type: INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '重试次数', + }, + created_by: { + type: BIGINT_UNSIGNED, + allowNull: true, + comment: '创建人', + }, + created_at: { + type: DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + }, { + engine: 'InnoDB', + charset: 'utf8mb4', + collate: 'utf8mb4_unicode_ci', + comment: '统一通知发送失败日志表', + }); + } + + const safeCreateIndex = async (tableName, fields, options) => { + const [ existingIndexes ] = await queryInterface.sequelize.query( + `SHOW INDEX FROM ${tableName} WHERE Key_name = '${options.name}'` + ); + if (existingIndexes.length === 0) { + await queryInterface.addIndex(tableName, fields, options); + } + }; + + await safeCreateIndex('wms_notification_send_log', [ 'trace_id' ], { + name: 'idx_notification_send_log_trace_id', + }); + + await safeCreateIndex('wms_notification_send_log', [ 'event', 'status' ], { + name: 'idx_notification_send_log_event_status', + }); + + await safeCreateIndex('wms_notification_send_log', [ 'webhook_id' ], { + name: 'idx_notification_send_log_webhook_id', + }); + + await safeCreateIndex('wms_notification_send_log', [ 'created_at' ], { + name: 'idx_notification_send_log_created_at', + }); + }, + + async down(queryInterface) { + const [ tables ] = await queryInterface.sequelize.query( + "SHOW TABLES LIKE 'wms_notification_send_log'" + ); + + if (tables.length > 0) { + await queryInterface.dropTable('wms_notification_send_log'); + } + }, +}; diff --git a/docs/notification-event-api.md b/docs/notification-event-api.md new file mode 100644 index 0000000..42e763c --- /dev/null +++ b/docs/notification-event-api.md @@ -0,0 +1,216 @@ +# 消息通知事件 API 文档(独立于 system) + +## 1. 文档说明 + +本文档描述 **WMS 对外消息通知能力** 的事件 API 约定。 + +特点: + +- **独立于 `/system` 接口** +- 不走 `method=xxx` 的 system 调用方式 +- 由内部业务在关键节点触发 `event` +- 通过 WebHook 向外部系统推送标准 JSON 消息 + +当前第一批落地事件: + +- `receiving_completed`:收货完成通知 + +--- + +## 2. 触发方式 + +内部业务在以下位置触发: + +- 文件:`app/service/systems/storage/receiving.js` +- 方法:`completeReceiving()` +- 通知方法:`sendCompletionNotice()` + +触发时机: + +1. 收货单状态更新为 `completed` +2. 收货完成 Excel 报表上传成功或已生成完成结果 +3. 调用: + +```js +await ctx.service.systems.notice.send({ + businessName: 'receiving', + event: 'receiving_completed', + ... +}) +``` + +--- + +## 3. 事件命名规则 + +本能力中,**事件名本身就是通知方法标识**。 + +示例: + +| event | 含义 | +|---|---| +| `receiving_completed` | 收货单完成通知 | + +> 当前正式注册的业务事件仅保留 `receiving_completed`。 + +对于外部订阅方来说,判断消息类型时,优先看: + +- `event` +- `businessName` +- `message.type` + +命名约束: + +- 仅允许小写字母、数字、下划线 +- 首字符不能为数字 +- **禁止使用 `.`** + +--- + +## 4. 当前已落地事件:`receiving_completed` + +### 4.1 业务含义 + +当仓库完成一张收货单时,系统会向绑定的 WebHook 推送一条 `receiving_completed` 通知。 + +### 4.2 推送目标 + +由 `wms_notification_webhook` 决定: + +- 先匹配仓库 `warehouseId` 绑定的接口 +- 若传了 `storeId / ownerId`,再匹配货主绑定的接口 +- `events` 命中以下任一规则即可推送: + - `all` + - `*` + - `receiving_completed` + +--- + +## 5. 请求方式 + +对外固定使用: + +```http +POST +Content-Type: application/json +``` + +--- + +## 6. 收货完成通知 payload + +### 6.1 字段说明 + +| 字段 | 类型 | 说明 | +|---|---|---| +| `traceId` | `string` | 通知追踪 ID | +| `event` | `string` | 固定为 `receiving_completed` | +| `businessName` | `string` | 固定为 `receiving` | +| `warehouseId` | `number` | 仓库 ID | +| `storeId` | `number \| null` | 货主 ID,可为空 | +| `businessId` | `number` | 收货单 ID | +| `occurredAt` | `string` | 发生时间,ISO 格式 | +| `subject` | `object` | 当前主体(仓库) | +| `store` | `object` | 货主信息 | +| `sender` | `object` | 操作人信息 | +| `receivers` | `array` | 接收者占位 | +| `message` | `object` | 消息主体 | +| `metadata` | `object` | 业务扩展信息 | + +### 6.2 示例(带完成报表) + +```json +{ + "traceId": "notice_1775368780099_c6fb8643", + "event": "receiving_completed", + "businessName": "receiving", + "warehouseId": 100000, + "storeId": 200000, + "businessId": 12345, + "occurredAt": "2026-04-05T12:00:00.000Z", + "subject": { + "id": 100000, + "type": "warehouse", + "name": "广州仓", + "code": "", + "config": { + "max_notice_webhook_count": 5 + } + }, + "store": { + "id": 200000, + "name": "某货主", + "businessLicense": "9144XXXXXXXXXXXX", + "storeRemask": "华南货主" + }, + "sender": { + "id": 10001, + "name": "张三" + }, + "receivers": [], + "message": { + "type": "file", + "title": "收货单RCV202604050001已完成", + "content": "收货单RCV202604050001已完成,匹配商品10件,未匹配商品0件,总数量120,完成人张三。", + "url": "https://cdn.example.com/收货完成_RCV202604050001.xlsx", + "fileName": "收货完成_RCV202604050001.xlsx", + "mimeType": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + "body": "收货单RCV202604050001已完成,匹配商品10件,未匹配商品0件,总数量120,完成人张三。" + }, + "metadata": { + "receivingId": 12345, + "receivingNumber": "RCV202604050001", + "warehouseId": 100000, + "storeId": 200000, + "stats": { + "total_details": 10, + "matched_details": 10, + "unmatched_details": 0, + "total_quantity": 120 + }, + "completionReport": { + "fileKey": "收货完成_RCV202604050001.xlsx", + "url": "https://cdn.example.com/收货完成_RCV202604050001.xlsx" + } + } +} +``` + +--- + +## 7. 返回值约定 + +针对当前旧回调接口的约定: + +- 返回 `1` = **成功** +- 返回 `0` = **失败** + +--- + +## 8. 当前可信结论 + +已验证: + +- `GET` 调用旧接口地址可返回 `1` +- `POST {}` 可返回 `1` +- 手工最小 probe JSON 可返回 `1` + +因此: + +> 若 `receiving_completed` 的统一通知实际推送触发远端错误,优先判断为 **payload 字段结构差异导致的远端解析异常**。 + +--- + +## 9. 后续事件扩展建议 + +下一步可继续补充: + +- `receiving_cancelled` +- `stock_low` +- `stock_changed` +- `entry_order_created` +- `entry_order_completed` + +保持原则: + +> **一个业务事件 = 一个对外通知 event** diff --git a/docs/notification-webhook-capability.md b/docs/notification-webhook-capability.md new file mode 100644 index 0000000..22ba7b9 --- /dev/null +++ b/docs/notification-webhook-capability.md @@ -0,0 +1,263 @@ +# 统一消息通知能力文档(草案) + +## 1. 目标 + +用于沉淀 WMS 统一消息通知能力的接口结构、数据模型、事件订阅规则与对外推送格式,作为后续构建“消息通知中心 / WebHook 能力”的基础文档。 + +--- + +## 2. 能力结构 + +当前统一发送入口: + +```js +await ctx.service.systems.notice.send(options) +``` + +当前调用链: + +```text +业务服务 + -> ctx.service.systems.notice.send(options) + -> normalizePayload(options) + -> findMatchedWebhooks(payload) + -> GenericWebhookDriver.send({ hook, payload }) + -> POST JSON 到外部 hook_url +``` + +代码位置: + +- `app/service/systems/notice/index.js` +- `app/service/systems/notice/drivers/generic.js` +- `app/model/notification_webhook.js` + +--- + +## 3. 相关数据模型 + +### 3.1 `wms_notification_webhook` + +用于保存主体绑定的外部 WebHook 配置。 + +核心字段: + +| 字段 | 说明 | +|---|---| +| `store_id` | 主体 ID,可绑定到仓库主体或货主主体 | +| `hook_name` | WebHook 名称 | +| `hook_type` | WebHook 类型,当前支持 `customize` / `wecom` | +| `hook_url` | 推送目标地址 | +| `events` | 订阅事件列表 | +| `status` | 状态,`1=启用`,`0=禁用` | +| `remark` | 备注 | + +### 3.2 `wms_store.subject_config` + +用于保存主体级通知配置。 + +当前已使用字段: + +| 字段 | 说明 | +|---|---| +| `max_notice_webhook_count` | 当前主体最多允许绑定 / 触达的消息推送接口数量,默认 `5` | + +--- + +## 4. 事件能力结构建议(独立于 `/system`) + +当前更推荐的能力组织方式是:**内部业务事件 = 对外通知方法标识**,而不是先对外包装成 `/system` method。 + +推荐结构: + +```text +系统内部业务事件 + -> ctx.service.systems.notice.send(options) + -> payload 归一化 + -> 查找匹配的 webhook + -> 按 hook_type 选择 driver + -> 推送到外部系统 +``` + +当前已落地示例: + +| event | 说明 | +|---|---| +| `receiving_completed` | 收货单完成通知 | + +> 当前正式注册的业务事件仅保留 `receiving_completed`;`all` / `*` 作为通配订阅值继续保留。收货完成事件的独立 API 文档见:`docs/notification-event-api.md`。 + +--- + +## 5. 对内统一发送入参 + +`notice.send(options)` 推荐入参如下: + +| 参数 | 类型 | 必填 | 说明 | +|---|---|---:|---| +| `warehouseId` | `number` | 是 | 仓库 ID | +| `storeId` | `number` | 否 | 货主 ID,可空 | +| `ownerId` | `number` | 否 | 货主 ID 别名,可空 | +| `businessName` | `string` | 是 | 业务名称,如 `receiving` | +| `event` | `string` | 否 | 具体事件,如 `receiving_completed` | +| `messageType` | `string` | 是 | `text / image / file`,兼容中文 | +| `title` | `string` | 否 | 消息标题 | +| `content` | `string/object` | 否 | 消息正文 | +| `url` | `string` | 条件必填 | 图片 / 文件类型时必填 | +| `businessId` | `number|string` | 否 | 业务单据 ID | +| `subject` | `object` | 否 | 主体信息 | +| `sender` | `object` | 否 | 发送者信息 | +| `receivers` | `array` | 否 | 接收者信息 | +| `metadata` | `object` | 否 | 扩展元数据 | + +### 5.1 入参约束 + +- `warehouseId` **必传** +- `storeId / ownerId` **允许为空** +- `messageType = image / file` 时,`url` **必填** +- `event` 命名仅允许小写字母、数字、下划线,且首字符不能为数字;**禁止使用 `.`** + +--- + +## 6. 对外统一推送 payload + +当前对外固定为:`POST + application/json` + +示例: + +```json +{ + "traceId": "notice_xxx", + "event": "receiving_completed", + "businessName": "receiving", + "warehouseId": 100000, + "storeId": 200000, + "businessId": 123, + "occurredAt": "2026-04-05T12:00:00.000Z", + "subject": { + "id": 100000, + "type": "warehouse", + "name": "广州仓", + "code": "", + "config": { + "max_notice_webhook_count": 5 + } + }, + "store": { + "id": 200000, + "name": "某货主", + "businessLicense": "9144XXXXXXXXXXXX", + "storeRemask": "华南货主" + }, + "sender": {}, + "receivers": [], + "message": { + "type": "text", + "title": "收货完成", + "content": "收货单已完成", + "url": "", + "fileName": "", + "mimeType": "", + "body": "收货单已完成" + }, + "metadata": { + "source": "system" + } +} +``` + +--- + +## 7. 事件订阅规则 + +`events` 字段建议使用数组。 + +支持写法: + +| 写法 | 含义 | +|---|---| +| `all` | 接收全部已注册通知 | +| `*` | 兼容旧配置,等价于 `all` | +| `receiving_completed` | 只接收收货完成事件 | + +> 若需新增其他事件,必须先在 `app/model/notification_webhook.js` 完成注册,否则发送入口会直接拒绝。 + +--- + +## 8. 命中与分发规则 + +当前 `findMatchedWebhooks(payload)` 逻辑: + +1. 先判断 `warehouseId`,并查询该仓库主体绑定的启用接口 +2. 若 `storeId / ownerId` 非空,再查询该货主绑定的启用接口 +3. 过滤条件: + - `status = 1` + - `events` 命中当前消息 +4. 去重规则: + - 优先按 `id` + - 无 `id` 时按 `hook_url` +5. 最终按 `subject_config.max_notice_webhook_count` 限制最大推送数量 + +--- + +## 9. 货主信息补充与缓存 + +若传了 `storeId / ownerId`,当前会补齐货主信息: + +- `wms_store.business_license` +- `wms_store_warehouse.store_remask` + +缓存键: + +```text +warehouse:{warehouseId}store:{storeId}:info +``` + +缓存 TTL: + +```text +600 秒 +``` + +查询顺序: + +1. 优先读缓存 +2. 缓存未命中再查数据库 +3. 查到后回填缓存 +4. 若为空,则推送字段也保持空字符串 + +--- + +## 10. 回调返回值约定 + +对于现有旧接口(如 `notic`、`notic2`)的可信判定约定: + +- 返回 `1` = **成功** +- 返回 `0` = **失败** + +--- + +## 11. 当前可信结论 + +已验证: + +- `GET` 请求可通 +- `POST` 请求可通 +- `POST {}` 可返回 `1` +- 手工最小 probe payload 可返回 `1` + +因此: + +> 若统一 `notice.send()` 的实际推送触发远端报错,优先判断为 **payload 字段结构差异导致的远端解析问题**,而不是地址或请求方式问题。 + +--- + +## 12. 后续扩展建议 + +建议后续继续补充: + +1. 通知发送日志表 +2. 重试队列 / 死信队列 +3. 回调签名与鉴权 +4. WebHook 健康检查 +5. 失败告警与监控面板 +6. system 接口文档同步到 `methods/system.json` diff --git a/package.json b/package.json index be8a5c9..972a5bd 100644 --- a/package.json +++ b/package.json @@ -43,6 +43,8 @@ "start": "egg-scripts start ", "stop": "node ./app/lib/stop_current_egg.js", "dev": "egg-bin dev --port=6060", + "debug:webhook:receiver": "node ./script/debug-webhook-receiver.cjs", + "debug:webhook:receiving": "node ./script/debug-send-receiving-webhooks.cjs", "deploy:init": "node ./script/deploy-init.cjs production", "deploy:init:dry": "node ./script/deploy-init.cjs production --dry-run", "deploy:precheck": "node ./script/deploy-precheck.cjs", diff --git a/script/debug-send-receiving-webhooks.cjs b/script/debug-send-receiving-webhooks.cjs new file mode 100644 index 0000000..663c4a4 --- /dev/null +++ b/script/debug-send-receiving-webhooks.cjs @@ -0,0 +1,252 @@ +'use strict'; + +const path = require('node:path'); +const urllib = require('urllib'); + +const DEFAULT_FILE_URL = 'https://ye4s.file.gzxunren.com/exports/receiving/completed/100000/20260405/%E6%94%B6%E8%B4%A7%E5%AE%8C%E6%88%90_R20547058.xlsx'; +const DEFAULT_FILE_NAME = '收货完成_R20547058.xlsx'; + +function parseArgs(argv) { + const options = { + url: process.env.WEBHOOK_DEBUG_URL || '', + textUrl: process.env.WEBHOOK_DEBUG_TEXT_URL || '', + fileUrl: process.env.WEBHOOK_DEBUG_FILE_URL || '', + mode: process.env.WEBHOOK_DEBUG_MODE || 'both', + warehouseId: Number(process.env.WEBHOOK_DEBUG_WAREHOUSE_ID || 100000), + storeId: Number(process.env.WEBHOOK_DEBUG_STORE_ID || 1000016), + receivingId: Number(process.env.WEBHOOK_DEBUG_RECEIVING_ID || 202604050001), + receivingNumber: process.env.WEBHOOK_DEBUG_RECEIVING_NUMBER || 'SIM202604050001', + fileResourceUrl: process.env.WEBHOOK_DEBUG_REPORT_URL || DEFAULT_FILE_URL, + fileName: process.env.WEBHOOK_DEBUG_REPORT_FILE || DEFAULT_FILE_NAME, + timeout: Number(process.env.WEBHOOK_DEBUG_TIMEOUT || 10000), + }; + + for (const arg of argv) { + if (!arg.startsWith('--')) { + continue; + } + + const [rawKey, ...rest] = arg.slice(2).split('='); + const value = rest.join('='); + switch (rawKey) { + case 'url': + options.url = value || options.url; + break; + case 'text-url': + options.textUrl = value || options.textUrl; + break; + case 'file-url': + options.fileUrl = value || options.fileUrl; + break; + case 'mode': + options.mode = value || options.mode; + break; + case 'warehouse-id': + options.warehouseId = Number(value || options.warehouseId); + break; + case 'store-id': + options.storeId = Number(value || options.storeId); + break; + case 'receiving-id': + options.receivingId = Number(value || options.receivingId); + break; + case 'receiving-number': + options.receivingNumber = value || options.receivingNumber; + break; + case 'report-url': + options.fileResourceUrl = value || options.fileResourceUrl; + break; + case 'report-file': + options.fileName = value || options.fileName; + break; + case 'timeout': + options.timeout = Number(value || options.timeout); + break; + case 'help': + options.help = true; + break; + default: + break; + } + } + + if (!options.textUrl) { + options.textUrl = options.url; + } + if (!options.fileUrl) { + options.fileUrl = options.url; + } + + return options; +} + +function printHelp() { + console.log(`用法:\n npm run debug:webhook:receiving -- --url=http://127.0.0.1:7071/notic\n npm run debug:webhook:receiving -- --text-url=http://127.0.0.1:7071/notic --file-url=http://127.0.0.1:7071/notic2\n\n说明:\n - 默认发送两次请求:text + file\n - 默认模拟 warehouseId=100000, storeId=1000016 的收货完成通知\n - 可通过 --mode=text 或 --mode=file 只发送一种\n`); +} + +function buildBasePayload(options) { + return { + traceId: `debug_${Date.now()}_${Math.random().toString(16).slice(2, 8)}`, + event: 'receiving_completed', + businessName: 'receiving', + warehouseId: Number(options.warehouseId), + storeId: Number(options.storeId), + businessId: Number(options.receivingId), + occurredAt: new Date().toISOString(), + subject: { + id: Number(options.warehouseId), + type: 'warehouse', + name: `测试仓${options.warehouseId}`, + code: '', + config: { + max_notice_webhook_count: 5, + }, + }, + store: { + id: Number(options.storeId), + name: `测试货主${options.storeId}`, + businessLicense: `BL-${options.storeId}`, + storeRemask: `货主${options.storeId}备注`, + }, + sender: { + id: 90001, + name: '调试脚本', + }, + receivers: [], + metadata: { + debug: true, + sourceScript: path.basename(__filename), + receivingId: Number(options.receivingId), + receivingNumber: options.receivingNumber, + warehouseId: Number(options.warehouseId), + storeId: Number(options.storeId), + stats: { + total_details: 10, + matched_details: 10, + unmatched_details: 0, + total_quantity: 120, + }, + completionReport: null, + }, + }; +} + +function buildTextPayload(options) { + const payload = buildBasePayload(options); + const title = `收货单${options.receivingNumber}已完成`; + const content = `收货单${options.receivingNumber}已完成,匹配商品10件,未匹配商品0件,总数量120,完成人调试脚本。`; + payload.message = { + type: 'text', + title, + content, + url: '', + fileName: '', + mimeType: '', + body: content, + }; + return payload; +} + +function buildFilePayload(options) { + const payload = buildBasePayload(options); + const title = `收货单${options.receivingNumber}已完成`; + const content = `收货单${options.receivingNumber}已完成,匹配商品10件,未匹配商品0件,总数量120,完成人调试脚本。`; + payload.message = { + type: 'file', + title, + content, + url: options.fileResourceUrl, + fileName: options.fileName, + mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + body: content, + }; + payload.metadata.completionReport = { + fileKey: options.fileName, + url: options.fileResourceUrl, + }; + return payload; +} + +async function postJson(url, data, timeout) { + const response = await urllib.request(url, { + method: 'POST', + headers: { + 'content-type': 'application/json', + }, + data: JSON.stringify(data), + timeout: Number(timeout) || 10000, + dataType: 'text', + }); + + return { + status: response.status, + body: String(response.data || ''), + }; +} + +async function main() { + const options = parseArgs(process.argv.slice(2)); + if (options.help) { + printHelp(); + return; + } + + if (!options.textUrl && !options.fileUrl) { + throw new Error('请通过 --url 或 --text-url/--file-url 指定接收端地址'); + } + + const tasks = []; + if ([ 'both', 'text' ].includes(options.mode) && options.textUrl) { + tasks.push({ + label: 'text', + url: options.textUrl, + payload: buildTextPayload(options), + }); + } + if ([ 'both', 'file' ].includes(options.mode) && options.fileUrl) { + tasks.push({ + label: 'file', + url: options.fileUrl, + payload: buildFilePayload(options), + }); + } + + if (tasks.length === 0) { + throw new Error(`mode=${options.mode} 下没有可发送的 webhook 请求`); + } + + const results = []; + for (const task of tasks) { + console.log(`\n[send] ${task.label.toUpperCase()} -> ${task.url}`); + const response = await postJson(task.url, task.payload, options.timeout); + console.log(`[response] status=${response.status} body=${response.body}`); + results.push({ + label: task.label, + url: task.url, + status: response.status, + body: response.body, + traceId: task.payload.traceId, + event: task.payload.event, + }); + } + + const failedCount = results.filter(item => Number(item.status) < 200 || Number(item.status) >= 300).length; + console.log('\n[summary]'); + console.log(JSON.stringify({ + options: { + ...options, + timeout: Number(options.timeout), + }, + results, + failedCount, + }, null, 2)); + + if (failedCount > 0) { + process.exitCode = 1; + } +} + +main().catch(error => { + console.error('[debug-send-receiving-webhooks] failed:', error.message); + process.exit(1); +}); \ No newline at end of file diff --git a/script/debug-webhook-receiver.cjs b/script/debug-webhook-receiver.cjs new file mode 100644 index 0000000..bce6436 --- /dev/null +++ b/script/debug-webhook-receiver.cjs @@ -0,0 +1,134 @@ +'use strict'; + +const http = require('node:http'); +const { URL } = require('node:url'); + +function parseArgs(argv) { + const options = { + host: process.env.WEBHOOK_DEBUG_HOST || '127.0.0.1', + port: Number(process.env.WEBHOOK_DEBUG_PORT || 7071), + defaultResponse: process.env.WEBHOOK_DEBUG_RESPONSE || '1', + noticResponse: process.env.WEBHOOK_DEBUG_NOTIC_RESPONSE || '', + notic2Response: process.env.WEBHOOK_DEBUG_NOTIC2_RESPONSE || '', + }; + + for (const arg of argv) { + if (!arg.startsWith('--')) { + continue; + } + const [rawKey, ...rest] = arg.slice(2).split('='); + const value = rest.join('='); + switch (rawKey) { + case 'host': + options.host = value || options.host; + break; + case 'port': + options.port = Number(value || options.port); + break; + case 'response': + options.defaultResponse = value || options.defaultResponse; + break; + case 'notic-response': + options.noticResponse = value || options.noticResponse; + break; + case 'notic2-response': + options.notic2Response = value || options.notic2Response; + break; + case 'help': + options.help = true; + break; + default: + break; + } + } + + return options; +} + +function printHelp() { + console.log(`用法:\n npm run debug:webhook:receiver\n npm run debug:webhook:receiver -- --port=7071 --notic-response=1 --notic2-response=0\n\n环境变量:\n WEBHOOK_DEBUG_PORT=7071\n WEBHOOK_DEBUG_RESPONSE=1\n WEBHOOK_DEBUG_NOTIC_RESPONSE=1\n WEBHOOK_DEBUG_NOTIC2_RESPONSE=0\n`); +} + +function readRequestBody(req) { + return new Promise((resolve, reject) => { + const chunks = []; + req.on('data', chunk => chunks.push(chunk)); + req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8'))); + req.on('error', reject); + }); +} + +function buildResponseBody(pathname, options) { + if (pathname === '/notic2' && options.notic2Response) { + return options.notic2Response; + } + if (pathname === '/notic' && options.noticResponse) { + return options.noticResponse; + } + return options.defaultResponse; +} + +async function start() { + const options = parseArgs(process.argv.slice(2)); + if (options.help) { + printHelp(); + return; + } + + const server = http.createServer(async (req, res) => { + const url = new URL(req.url, `http://${req.headers.host || `${options.host}:${options.port}`}`); + const startedAt = new Date().toISOString(); + const rawBody = await readRequestBody(req); + let parsedBody = rawBody; + + try { + parsedBody = rawBody ? JSON.parse(rawBody) : null; + } catch (_) { + // keep raw text + } + + console.log('\n================ WEBHOOK DEBUG RECEIVER ================'); + console.log(`[time] ${startedAt}`); + console.log(`[route] ${req.method} ${url.pathname}`); + console.log('[query] ', Object.fromEntries(url.searchParams.entries())); + console.log('[header]', req.headers); + console.log('[body] ', JSON.stringify(parsedBody, null, 2)); + + if (![ '/notic', '/notic2', '/health' ].includes(url.pathname)) { + res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' }); + res.end('404 Not Found'); + return; + } + + if (url.pathname === '/health') { + res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' }); + res.end(JSON.stringify({ ok: true, service: 'webhook-debug-receiver' })); + return; + } + + const responseBody = buildResponseBody(url.pathname, options); + const statusCode = String(responseBody).startsWith('{') || String(responseBody).startsWith('[') ? 200 : 200; + const contentType = String(responseBody).startsWith('{') || String(responseBody).startsWith('[') + ? 'application/json; charset=utf-8' + : 'text/plain; charset=utf-8'; + + res.writeHead(statusCode, { 'content-type': contentType }); + res.end(responseBody); + + console.log(`[reply] ${url.pathname} -> ${responseBody}`); + console.log('========================================================\n'); + }); + + server.listen(options.port, options.host, () => { + console.log(`[webhook-debug-receiver] listening on http://${options.host}:${options.port}`); + console.log(`[webhook-debug-receiver] endpoints:`); + console.log(` - POST http://${options.host}:${options.port}/notic`); + console.log(` - POST http://${options.host}:${options.port}/notic2`); + console.log(` - GET http://${options.host}:${options.port}/health`); + }); +} + +start().catch(error => { + console.error('[webhook-debug-receiver] failed:', error); + process.exit(1); +}); \ No newline at end of file diff --git a/test/app/controller/system.setting.account.getBindWechatCode.test.js b/test/app/controller/system.setting.account.getBindWechatCode.test.js index c5b34ee..f0b4d5d 100644 --- a/test/app/controller/system.setting.account.getBindWechatCode.test.js +++ b/test/app/controller/system.setting.account.getBindWechatCode.test.js @@ -192,4 +192,4 @@ describe('test/app/controller/system.setting.account.getBindWechatCode.test.js', assert.equal(res.body.code, 400); assert.match(String(res.body?.message || ''), /user_id 参数不能为空/); }); -}); \ No newline at end of file +}); diff --git a/test/app/controller/system.stock.warehouse.namespaced.test.js b/test/app/controller/system.stock.warehouse.namespaced.test.js index 48f0fb5..ec6c2a1 100644 --- a/test/app/controller/system.stock.warehouse.namespaced.test.js +++ b/test/app/controller/system.stock.warehouse.namespaced.test.js @@ -81,4 +81,4 @@ describe('test/app/controller/system.stock.warehouse.namespaced.test.js', () => assert.ok(Array.isArray(namespacedData.list), '新入口 list 不是数组'); assert.ok(namespacedData.pagination, '新入口缺少 pagination'); }); -}); \ No newline at end of file +}); diff --git a/test/app/service/systems/excel.test.js b/test/app/service/systems/excel.test.js index b057bb3..5e0e710 100644 --- a/test/app/service/systems/excel.test.js +++ b/test/app/service/systems/excel.test.js @@ -152,6 +152,8 @@ describe('test/app/service/systems/excel.test.js', () => { assert.ok(Buffer.isBuffer(uploads[0].body)); assert.ok(uploads[0].body.length > 0); assert.equal(notifyCalls[0].expireDays, 90); + assert.match(String(notifyCalls[0].md5Hash || ''), /^[a-f0-9]{32}$/i); + assert.match(String(notifyCalls[0].sha1Hash || ''), /^[a-f0-9]{40}$/i); assert.ok(String(result.fileKey || '').includes('exports/receiving/')); assert.equal(result.fileRecord.fileId, 9527); }); @@ -195,7 +197,7 @@ describe('test/app/service/systems/excel.test.js', () => { sheets: [ { name: 'URL图片', - rows: [ [ '图片', '见右侧' ] ], + rows: [[ '图片', '见右侧' ]], embeddedImages: [ { row: 1, diff --git a/test/app/service/systems/notice.test.js b/test/app/service/systems/notice.test.js new file mode 100644 index 0000000..4d2e21a --- /dev/null +++ b/test/app/service/systems/notice.test.js @@ -0,0 +1,696 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const NoticeService = require('../../../../app/service/systems/notice'); +const defineNotificationWebhook = require('../../../../app/model/notification_webhook'); + +describe('test/app/service/systems/notice.test.js', () => { + it('should normalize payload and send only matching webhooks', async () => { + const sentRequests = []; + const webhookRows = [ + { + id: 1, + store_id: 100000, + hook_type: 'custom', + hook_url: 'https://example.com/webhook/a', + events: [ 'receiving_completed' ], + }, + { + id: 2, + store_id: 100000, + hook_type: 'custom', + hook_url: 'https://example.com/webhook/b', + events: [ 'stock.low' ], + }, + ]; + + const ctx = { + app: { + config: {}, + }, + model: { + NotificationWebhook: { + async findAll({ where }) { + assert.equal(Number(where.store_id), 100000); + assert.equal(Number(where.status), 1); + return webhookRows; + }, + }, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + async curl(url, options) { + sentRequests.push({ url, options }); + return { + status: 200, + data: { ok: true }, + }; + }, + }; + + const service = new NoticeService(ctx); + const result = await service.send({ + messageType: '图片', + businessName: 'receiving', + event: 'receiving_completed', + subject: { + id: 100000, + type: 'warehouse', + name: '测试主体', + }, + subjectConfig: { + webhook_enabled: true, + callback_strategy: 'async', + max_notice_webhook_count: 5, + }, + title: '收货完成', + content: '本次收货已完成', + url: 'https://cdn.example.com/demo.png', + businessId: 256, + metadata: { + source: 'unit-test', + }, + }); + + assert.equal(result.success, true); + assert.equal(Number(result.data.matchedHookCount), 1); + assert.equal(Number(result.data.sentCount), 1); + assert.equal(sentRequests.length, 1); + assert.equal(sentRequests[0].url, 'https://example.com/webhook/a'); + assert.equal(sentRequests[0].options.method, 'POST'); + assert.equal(sentRequests[0].options.data.event, 'receiving_completed'); + assert.equal(sentRequests[0].options.data.message.type, 'image'); + assert.equal(sentRequests[0].options.data.message.url, 'https://cdn.example.com/demo.png'); + assert.equal(sentRequests[0].options.data.subject.config.webhook_enabled, true); + assert.equal(sentRequests[0].options.data.subject.config.callback_strategy, 'async'); + assert.equal(Number(sentRequests[0].options.data.subject.config.max_notice_webhook_count), 5); + }); + + it('should enrich payload with store info from cache before querying database', async () => { + let storeLookupCount = 0; + let relationLookupCount = 0; + const ctx = { + app: { + config: {}, + async getCacheAsync(cacheKey) { + assert.equal(cacheKey, 'warehouse:200000store:100000:info'); + return { + id: 100000, + name: '缓存货主', + businessLicense: 'BL-CACHE-001', + storeRemask: '缓存备注', + }; + }, + }, + model: { + Store: { + async findByPk() { + storeLookupCount += 1; + return null; + }, + }, + StoreWarehouse: { + async findOne() { + relationLookupCount += 1; + return null; + }, + }, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + }; + + const service = new NoticeService(ctx); + const payload = await service.normalizePayload({ + messageType: '文本', + businessName: 'receiving', + event: 'receiving_completed', + subject: { + id: 200000, + type: 'warehouse', + }, + subjectConfig: { + max_notice_webhook_count: 5, + }, + storeId: 100000, + content: '缓存优先', + }); + + assert.equal(payload.store.id, 100000); + assert.equal(payload.store.name, '缓存货主'); + assert.equal(payload.store.businessLicense, 'BL-CACHE-001'); + assert.equal(payload.store.storeRemask, '缓存备注'); + assert.equal(Object.prototype.hasOwnProperty.call(payload.store, 'business_license'), false); + assert.equal(Object.prototype.hasOwnProperty.call(payload.store, 'store_remask'), false); + assert.equal(storeLookupCount, 0); + assert.equal(relationLookupCount, 0); + }); + + it('should load store info from database and cache it when cache is empty', async () => { + let cachedPayload = null; + const ctx = { + app: { + config: {}, + async getCacheAsync(cacheKey) { + assert.equal(cacheKey, 'warehouse:200000store:100000:info'); + return null; + }, + async setCacheAsync(cacheKey, data, ttl) { + cachedPayload = { cacheKey, data, ttl }; + }, + }, + model: { + Store: { + async findByPk(id) { + assert.equal(Number(id), 100000); + return { + id: 100000, + company_name: '测试货主', + business_license: 'BL-DB-001', + }; + }, + }, + StoreWarehouse: { + async findOne({ where }) { + assert.equal(Number(where.store_id), 100000); + assert.equal(Number(where.warehouse_id), 200000); + return { + store_remask: '数据库备注', + }; + }, + }, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + }; + + const service = new NoticeService(ctx); + const payload = await service.normalizePayload({ + messageType: '文本', + businessName: 'receiving', + event: 'receiving_completed', + subject: { + id: 200000, + type: 'warehouse', + }, + subjectConfig: { + max_notice_webhook_count: 5, + }, + ownerId: 100000, + content: '查库回填', + }); + + assert.equal(payload.store.id, 100000); + assert.equal(payload.store.name, '测试货主'); + assert.equal(payload.store.businessLicense, 'BL-DB-001'); + assert.equal(payload.store.storeRemask, '数据库备注'); + assert.equal(Object.prototype.hasOwnProperty.call(payload.store, 'business_license'), false); + assert.equal(Object.prototype.hasOwnProperty.call(payload.store, 'store_remask'), false); + assert.equal(cachedPayload.cacheKey, 'warehouse:200000store:100000:info'); + assert.equal(cachedPayload.ttl, 600); + assert.equal(cachedPayload.data.businessLicense, 'BL-DB-001'); + assert.equal(Object.prototype.hasOwnProperty.call(cachedPayload.data, 'business_license'), false); + }); + + it('should send to both warehouse and owner webhooks when events match or are set to all', async () => { + const sentRequests = []; + const ctx = { + app: { + config: {}, + }, + model: { + NotificationWebhook: { + async findAll({ where }) { + if (Number(where.store_id) === 200000) { + return [ + { + id: 1, + store_id: 200000, + hook_type: 'custom', + hook_url: 'https://example.com/webhook/warehouse', + events: [ 'all' ], + }, + ]; + } + + if (Number(where.store_id) === 100000) { + return [ + { + id: 2, + store_id: 100000, + hook_type: 'custom', + hook_url: 'https://example.com/webhook/store', + events: [ 'receiving' ], + }, + ]; + } + + return []; + }, + }, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + async curl(url, options) { + sentRequests.push({ url, options }); + return { + status: 200, + data: { ok: true }, + }; + }, + }; + + const service = new NoticeService(ctx); + const result = await service.send({ + messageType: '文本', + businessName: 'receiving', + event: 'receiving_completed', + warehouseId: 200000, + storeId: 100000, + subject: { + id: 200000, + type: 'warehouse', + }, + subjectConfig: { + max_notice_webhook_count: 5, + }, + content: '仓库和货主都应接收', + }); + + assert.equal(result.success, true); + assert.equal(Number(result.data.matchedHookCount), 2); + assert.equal(Number(result.data.sentCount), 2); + assert.equal(sentRequests.length, 2); + assert.ok(sentRequests.some(item => item.url === 'https://example.com/webhook/warehouse')); + assert.ok(sentRequests.some(item => item.url === 'https://example.com/webhook/store')); + }); + + it('should only send up to the configured webhook limit', async () => { + const sentRequests = []; + const webhookRows = Array.from({ length: 6 }).map((_, index) => ({ + id: index + 1, + store_id: 100000, + hook_type: 'custom', + hook_url: `https://example.com/webhook/${index + 1}`, + events: [ 'receiving_completed' ], + })); + + const ctx = { + app: { + config: {}, + }, + model: { + NotificationWebhook: { + async findAll() { + return webhookRows; + }, + }, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + async curl(url, options) { + sentRequests.push({ url, options }); + return { + status: 200, + data: { ok: true }, + }; + }, + }; + + const service = new NoticeService(ctx); + const result = await service.send({ + messageType: '文本', + businessName: 'receiving', + event: 'receiving_completed', + subject: { + id: 100000, + type: 'warehouse', + }, + subjectConfig: { + max_notice_webhook_count: 5, + }, + content: '只允许发送前五个', + }); + + assert.equal(result.success, true); + assert.equal(Number(result.data.matchedHookCount), 5); + assert.equal(Number(result.data.sentCount), 5); + assert.equal(sentRequests.length, 5); + assert.equal(sentRequests[4].url, 'https://example.com/webhook/5'); + }); + + it('should require url for image or file message', async () => { + const ctx = { + app: { + config: {}, + }, + model: { + NotificationWebhook: { + async findAll() { + return []; + }, + }, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + async curl() { + return { status: 200 }; + }, + }; + + const service = new NoticeService(ctx); + + await assert.rejects(async () => { + await service.send({ + messageType: '文件', + businessName: 'receiving', + warehouseId: 200000, + subject: { id: 100000 }, + content: '请查看附件', + }); + }, /url/); + }); + + it('should require warehouseId but allow empty ownerId', async () => { + const ctx = { + app: { + config: {}, + }, + model: { + NotificationWebhook: { + async findAll() { + return []; + }, + }, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + async curl() { + return { status: 200 }; + }, + }; + + const service = new NoticeService(ctx); + + await assert.rejects(async () => { + await service.normalizePayload({ + messageType: '文本', + businessName: 'receiving', + content: '未传仓库', + }); + }, /warehouseId/); + + const payload = await service.normalizePayload({ + messageType: '文本', + businessName: 'receiving', + event: 'receiving_completed', + warehouseId: 200000, + content: '允许货主为空', + }); + + assert.equal(payload.subject.id, 200000); + assert.equal(payload.store.id, null); + assert.equal(payload.store.businessLicense, ''); + assert.equal(payload.store.storeRemask, ''); + }); + + it('should retry failed webhooks three times and persist final failures', async () => { + const sentRequests = []; + const sleepCalls = []; + const failureLogs = []; + let attempt = 0; + const ctx = { + app: { + config: {}, + }, + model: { + NotificationWebhook: { + async findAll() { + return [{ + id: 9, + store_id: 100000, + hook_type: 'custom', + hook_url: 'https://example.com/webhook/fail', + events: [ 'all' ], + }]; + }, + }, + NotificationSendLog: { + async create(data) { + failureLogs.push(data); + return data; + }, + }, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + async curl(url, options) { + sentRequests.push({ url, options }); + attempt += 1; + throw new Error(`network fail ${attempt}`); + }, + }; + + const service = new NoticeService(ctx); + service.sleep = async ms => { + sleepCalls.push(ms); + }; + + const result = await service.send({ + messageType: '文本', + businessName: 'receiving', + event: 'receiving_completed', + warehouseId: 100000, + content: '失败后重试', + }); + + assert.equal(result.success, false); + assert.equal(Number(result.data.matchedHookCount), 1); + assert.equal(Number(result.data.sentCount), 0); + assert.equal(Number(result.data.failedCount), 1); + assert.equal(sentRequests.length, 4); + assert.deepEqual(sleepCalls, [ 3000, 6000, 12000 ]); + assert.equal(failureLogs.length, 1); + assert.equal(Number(failureLogs[0].retry_count), 3); + assert.equal(String(failureLogs[0].event), 'receiving_completed'); + assert.match(String(failureLogs[0].error_message || ''), /network fail/); + }); + + it('should reject sending unregistered event', async () => { + const ctx = { + app: { + config: {}, + }, + model: { + NotificationWebhook: { + getAvailableEventCodes() { + return [ 'all', '*', 'receiving_completed' ]; + }, + async findAll() { + return []; + }, + }, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + async curl() { + return { status: 200, data: '1' }; + }, + }; + + const service = new NoticeService(ctx); + await assert.rejects(async () => { + await service.send({ + warehouseId: 100000, + businessName: 'receiving', + event: 'receiving_image', + messageType: 'image', + title: '未注册事件测试', + content: '这条消息不应发出', + url: 'https://example.com/demo.jpg', + }); + }, /未注册|不允许发送/); + }); + + it('should reject dotted or numeric-leading event names', async () => { + const ctx = { + app: { + config: {}, + }, + model: { + NotificationWebhook: { + getAvailableEventCodes() { + return [ 'all', '*', 'receiving_completed' ]; + }, + async findAll() { + return []; + }, + }, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + async curl() { + return { status: 200, data: '1' }; + }, + }; + + const service = new NoticeService(ctx); + + await assert.rejects(async () => { + await service.send({ + warehouseId: 100000, + businessName: 'receiving', + event: 'receiving.completed', + messageType: 'text', + content: '点号事件名不合法', + }); + }, /命名不合法/); + + await assert.rejects(async () => { + await service.send({ + warehouseId: 100000, + businessName: 'receiving', + event: '1receiving_completed', + messageType: 'text', + content: '数字开头事件名不合法', + }); + }, /命名不合法/); + }); + + it('should send wecom webhook as enterprise wechat direct message', async () => { + const sentRequests = []; + const ctx = { + app: { + config: {}, + }, + model: { + NotificationWebhook: { + getAvailableEventCodes() { + return [ 'all', '*', 'receiving_completed' ]; + }, + async findAll() { + return [{ + id: 21, + store_id: 100000, + hook_type: 'wecom', + hook_url: 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=test-key', + events: [ 'receiving_completed' ], + }]; + }, + }, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + async curl(url, options) { + sentRequests.push({ url, options }); + return { + status: 200, + data: { + errcode: 0, + errmsg: 'ok', + }, + }; + }, + }; + + const service = new NoticeService(ctx); + const result = await service.send({ + warehouseId: 100000, + businessName: 'receiving', + event: 'receiving_completed', + messageType: 'text', + title: '收货完成通知', + content: '收货单已完成', + subject: { + id: 100000, + type: 'warehouse', + name: '测试仓', + }, + }); + + assert.equal(result.success, true); + assert.equal(sentRequests.length, 1); + assert.equal(sentRequests[0].url, 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=test-key'); + assert.equal(sentRequests[0].options.data.msgtype, 'text'); + assert.match(String(sentRequests[0].options.data.text.content || ''), /收货完成通知/); + assert.equal(result.data.results[0].hookType, 'wecom'); + }); + + it('should expose available webhook events and reject unsupported ones', () => { + const fakeType = () => ({}); + const app = { + Sequelize: { + BIGINT: { UNSIGNED: {} }, + STRING: fakeType, + TINYINT: fakeType, + DATE: {}, + JSON: {}, + Op: { + ne: Symbol('ne'), + }, + literal: value => value, + }, + model: { + define(name, attrs) { + return { + rawAttributes: attrs, + prototype: {}, + belongsTo() {}, + hasMany() {}, + }; + }, + Store: { + normalizeSubjectConfig() { + return { + max_notice_webhook_count: 5, + }; + }, + }, + }, + }; + + const NotificationWebhook = defineNotificationWebhook(app); + const availableEvents = NotificationWebhook.getAvailableEvents(); + + assert.ok(Array.isArray(availableEvents)); + assert.ok(availableEvents.some(item => item.code === 'all')); + assert.ok(availableEvents.some(item => item.code === 'receiving_completed')); + assert.doesNotThrow(() => NotificationWebhook.rawAttributes.events.validate.isValidEvents([ 'all', 'receiving_completed' ])); + assert.throws(() => NotificationWebhook.rawAttributes.events.validate.isValidEvents([ 'receiving.completed' ]), /不支持|非法/); + assert.throws(() => NotificationWebhook.rawAttributes.events.validate.isValidEvents([ '1receiving_completed' ]), /不支持|非法/); + assert.throws(() => NotificationWebhook.rawAttributes.events.validate.isValidEvents([ 'unknown_event' ]), /不支持|非法/); + }); +}); diff --git a/test/app/service/systems/stock_store.stockWarehouse.conditions.test.js b/test/app/service/systems/stock_store.stockWarehouse.conditions.test.js index f602ede..cff7740 100644 --- a/test/app/service/systems/stock_store.stockWarehouse.conditions.test.js +++ b/test/app/service/systems/stock_store.stockWarehouse.conditions.test.js @@ -30,7 +30,7 @@ function createTestContext(options = {}) { notRegexp: '$notRegexp', }; - const rows = options.rows || [ { + const rows = options.rows || [{ id: 1, item_code: 'SKU-1', goods_code: 'G-1', @@ -39,7 +39,7 @@ function createTestContext(options = {}) { locked_quantity: 2, create_at: '2026-01-01 10:00:00', update_at: '2026-01-01 10:00:00', - } ]; + }]; const model = { StoreWarehouse: { @@ -73,12 +73,12 @@ function createTestContext(options = {}) { if (options.matchedBarcodeRows) { return options.matchedBarcodeRows; } - return [ { stock_id: 1 } ]; + return [{ stock_id: 1 }]; } if (options.barcodes) { return options.barcodes; } - return [ { stock_id: 1, barcode: 'BC-1' } ]; + return [{ stock_id: 1, barcode: 'BC-1' }]; }, }, FileReference: { @@ -138,24 +138,24 @@ describe('test/app/service/systems/stock_store.stockWarehouse.conditions.test.js const { service, app, Op } = createServiceHarness(); const cases = [ - [ 'eq', { field: 'item_code', value: 'SKU' }, { item_code: 'SKU' } ], - [ 'ne', { value: 'SKU' }, { item_code: { [Op.ne]: 'SKU' } } ], - [ 'like', { value: 'SKU' }, { item_code: { [Op.like]: '%SKU%' } } ], - [ 'contains', { value: 'SKU' }, { item_code: { [Op.like]: '%SKU%' } } ], - [ 'startswith', { value: 'SKU' }, { item_code: { [Op.like]: 'SKU%' } } ], - [ 'endswith', { value: 'SKU' }, { item_code: { [Op.like]: '%SKU' } } ], - [ 'gt', { value: 10 }, { item_code: { [Op.gt]: 10 } } ], - [ 'lt', { value: 10 }, { item_code: { [Op.lt]: 10 } } ], - [ 'ge', { value: 10 }, { item_code: { [Op.gte]: 10 } } ], - [ 'le', { value: 10 }, { item_code: { [Op.lte]: 10 } } ], - [ 'in', { value: [ 'A', 'B' ] }, { item_code: { [Op.in]: [ 'A', 'B' ] } } ], - [ 'notin', { value: [ 'A', 'B' ] }, { item_code: { [Op.notIn]: [ 'A', 'B' ] } } ], - [ 'between', { value: [ 1, 2 ] }, { item_code: { [Op.between]: [ 1, 2 ] } } ], - [ 'notbetween', { value: [ 1, 2 ] }, { item_code: { [Op.notBetween]: [ 1, 2 ] } } ], - [ 'isnull', { value: null }, { item_code: { [Op.is]: null } } ], - [ 'isnotnull', { value: null }, { item_code: { [Op.not]: null } } ], - [ 'regexp', { value: '^SKU' }, { item_code: { [Op.regexp]: '^SKU' } } ], - [ 'notregexp', { value: '^SKU' }, { item_code: { [Op.notRegexp]: '^SKU' } } ], + [ 'eq', { field: 'item_code', value: 'SKU' }, { item_code: 'SKU' }], + [ 'ne', { value: 'SKU' }, { item_code: { [Op.ne]: 'SKU' } }], + [ 'like', { value: 'SKU' }, { item_code: { [Op.like]: '%SKU%' } }], + [ 'contains', { value: 'SKU' }, { item_code: { [Op.like]: '%SKU%' } }], + [ 'startswith', { value: 'SKU' }, { item_code: { [Op.like]: 'SKU%' } }], + [ 'endswith', { value: 'SKU' }, { item_code: { [Op.like]: '%SKU' } }], + [ 'gt', { value: 10 }, { item_code: { [Op.gt]: 10 } }], + [ 'lt', { value: 10 }, { item_code: { [Op.lt]: 10 } }], + [ 'ge', { value: 10 }, { item_code: { [Op.gte]: 10 } }], + [ 'le', { value: 10 }, { item_code: { [Op.lte]: 10 } }], + [ 'in', { value: [ 'A', 'B' ] }, { item_code: { [Op.in]: [ 'A', 'B' ] } }], + [ 'notin', { value: [ 'A', 'B' ] }, { item_code: { [Op.notIn]: [ 'A', 'B' ] } }], + [ 'between', { value: [ 1, 2 ] }, { item_code: { [Op.between]: [ 1, 2 ] } }], + [ 'notbetween', { value: [ 1, 2 ] }, { item_code: { [Op.notBetween]: [ 1, 2 ] } }], + [ 'isnull', { value: null }, { item_code: { [Op.is]: null } }], + [ 'isnotnull', { value: null }, { item_code: { [Op.not]: null } }], + [ 'regexp', { value: '^SKU' }, { item_code: { [Op.regexp]: '^SKU' } }], + [ 'notregexp', { value: '^SKU' }, { item_code: { [Op.notRegexp]: '^SKU' } }], ]; for (const [ operator, input, expected ] of cases) { @@ -251,9 +251,9 @@ describe('test/app/service/systems/stock_store.stockWarehouse.conditions.test.js it('should short-circuit when barcode has no matched stock ids', async () => { const { service, calls } = createServiceHarness({ matchedBarcodeRows: [], - rows: [ { + rows: [{ id: 99, - } ], + }], }); const result = await service.getWarehouseStock({ @@ -298,7 +298,7 @@ describe('test/app/service/systems/stock_store.stockWarehouse.conditions.test.js }); assert.equal(result.code, 200); - assert.deepEqual(calls.findArgs.order, [ [ 'create_at', 'DESC' ] ]); + assert.deepEqual(calls.findArgs.order, [[ 'create_at', 'DESC' ]]); assert.equal(result.data.pagination.page, 2); assert.equal(result.data.pagination.pageSize, 5); }); diff --git a/test/app/service/systems/storage.receiving.report.test.js b/test/app/service/systems/storage.receiving.report.test.js index 7078232..b425a28 100644 --- a/test/app/service/systems/storage.receiving.report.test.js +++ b/test/app/service/systems/storage.receiving.report.test.js @@ -5,6 +5,7 @@ const ReceivingService = require('../../../../app/service/systems/storage/receiv function createService() { const excelCalls = []; + const noticeCalls = []; const ctx = { app: { config: {}, @@ -14,6 +15,7 @@ function createService() { }, user: { store_id: 2001, + store_name: '测试仓库', }, logger: { info() {}, @@ -25,9 +27,26 @@ function createService() { excel: { async generateAndUpload(options) { excelCalls.push(options); + const fileUrl = `https://cdn.example.com/${options.filename}`; return { fileKey: options.filename, - url: `https://cdn.example.com/${options.filename}`, + key: options.filename, + filename: options.filename, + url: fileUrl, + fileUrl, + }; + }, + }, + notice: { + async send(options) { + noticeCalls.push(options); + return { + success: true, + data: { + matchedHookCount: 1, + sentCount: 1, + failedCount: 0, + }, }; }, }, @@ -39,6 +58,125 @@ function createService() { return { service, excelCalls, + noticeCalls, + }; +} + +function createCompleteReceivingService({ + uploadShouldFail = false, + detailOverrides = {}, + itemImages, +} = {}) { + const steps = []; + const noticeCalls = []; + const transaction = { + LOCK: { + UPDATE: 'UPDATE', + }, + finished: false, + async commit() { + this.finished = 'commit'; + steps.push('commit'); + }, + async rollback() { + this.finished = 'rollback'; + steps.push('rollback'); + }, + }; + + const detailRecord = { + id: 501, + system_product_id: 90001, + product_name: '测试商品A', + barcode: 'SKU-001', + actual_quantity: 8, + weight: 12, + ...detailOverrides, + }; + + const defaultItemImages = [{ + business_id: 501, + file_id: 7001, + file: { + file_url: 'https://example.com/item-501.png', + }, + }]; + + const ctx = { + app: { + config: {}, + Sequelize: { + Op: { + in: 'in', + }, + }, + }, + user: { + store_id: 2001, + store_name: '测试仓库', + employees_id: 9001, + employees_name: '测试员', + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + model: { + async transaction() { + return transaction; + }, + Receiving: { + async findOne() { + return { + id: 123, + warehouse_id: 2001, + store_id: 3001, + store_name: '测试货主', + receiving_number: 'RCV202604040001', + status: 'receiving', + remark: '', + details: [ detailRecord ], + }; + }, + async update() { + return [ 1 ]; + }, + }, + FileReference: { + async findAll({ where }) { + if (where.business_type === 'receivingItem') { + return Array.isArray(itemImages) ? itemImages : defaultItemImages; + } + return []; + }, + }, + }, + }; + + const service = new ReceivingService(ctx); + service.sendCompletionNotice = async options => { + steps.push(options.completionReport ? 'notice:file' : 'notice:text'); + noticeCalls.push(options); + return { + success: true, + }; + }; + service.uploadCompletionExcelReport = async () => { + steps.push('excel'); + if (uploadShouldFail) { + throw new Error('upload failed'); + } + return { + fileKey: '收货完成_RCV202604040001.xlsx', + url: 'https://cdn.example.com/收货完成_RCV202604040001.xlsx', + }; + }; + + return { + service, + steps, + noticeCalls, }; } @@ -106,6 +244,10 @@ describe('test/app/service/systems/storage.receiving.report.test.js', () => { const receivingNumberRow = sheet.rows.find(item => Array.isArray(item) && item[0] === '收货单号'); assert.ok(receivingNumberRow, '应在主表区域包含收货单号行'); + const deliveryMethodRow = sheet.rows.find(item => Array.isArray(item) && item[0] === '来货方式'); + assert.ok(deliveryMethodRow, '应在主表区域包含来货方式行'); + assert.equal(deliveryMethodRow[1], '货车'); + const summaryImageRow = sheet.rows.find(item => Array.isArray(item) && item[0] === '收货图片'); assert.ok(summaryImageRow, '应在主表区域包含收货图片行'); assert.match(String(summaryImageRow[1]?.text || summaryImageRow[1] || ''), /main-image/); @@ -124,4 +266,160 @@ describe('test/app/service/systems/storage.receiving.report.test.js', () => { assert.equal(sheet.embeddedImages.length, 3); assert.equal(result.url, 'https://cdn.example.com/收货完成_RCV202604040001.xlsx'); }); + + it('should send receiving completed notice with the unified event payload', async () => { + const { service, noticeCalls } = createService(); + + const result = await service.sendCompletionNotice({ + receiving: { + id: 123, + receiving_number: 'RCV202604040001', + warehouse_id: 2001, + store_id: 3001, + store_name: '测试货主', + }, + operator: { + employees_name: '测试员', + }, + stats: { + total_details: 1, + matched_details: 1, + unmatched_details: 0, + total_quantity: 8, + }, + completionReport: { + fileKey: '收货完成_RCV202604040001.xlsx', + url: 'https://cdn.example.com/收货完成_RCV202604040001.xlsx', + }, + }); + + assert.equal(noticeCalls.length, 1); + const [ options ] = noticeCalls; + assert.equal(Number(options.warehouseId), 2001); + assert.equal(Number(options.storeId), 3001); + assert.equal(options.businessName, 'receiving'); + assert.equal(options.event, 'receiving_completed'); + assert.equal(options.messageType, 'file'); + assert.equal(options.url, 'https://cdn.example.com/收货完成_RCV202604040001.xlsx'); + assert.equal(options.subject.id, 2001); + assert.equal(options.subject.name, '测试仓库'); + assert.match(String(options.content || ''), /收货单RCV202604040001已完成/); + assert.equal(result.success, true); + }); + + it('should support nested notice.index service shape from Egg loader', async () => { + const noticeCalls = []; + const ctx = { + app: { + config: {}, + Sequelize: { + Op: {}, + }, + }, + user: { + store_id: 2001, + store_name: '测试仓库', + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + service: { + systems: { + notice: { + index: { + async send(options) { + noticeCalls.push(options); + return { + success: true, + message: 'ok', + data: { + matchedHookCount: 1, + sentCount: 1, + failedCount: 0, + }, + }; + }, + }, + }, + }, + }, + }; + + const service = new ReceivingService(ctx); + const result = await service.sendCompletionNotice({ + receiving: { + id: 123, + receiving_number: 'RCV202604040001', + warehouse_id: 2001, + store_id: 3001, + }, + operator: { + employees_name: '测试员', + }, + stats: { + total_details: 1, + matched_details: 1, + unmatched_details: 0, + total_quantity: 8, + }, + }); + + assert.equal(noticeCalls.length, 1); + assert.equal(result.success, true); + assert.equal(result.message, 'ok'); + }); + + it('should trigger text notice before excel and then send file notice after upload succeeds', async () => { + const { service, steps, noticeCalls } = createCompleteReceivingService(); + + const result = await service.completeReceiving({ id: 123 }); + await Promise.resolve(); + await Promise.resolve(); + + assert.equal(result.success, true); + assert.deepEqual(steps, [ 'commit', 'notice:text', 'excel', 'notice:file' ]); + assert.equal(noticeCalls.length, 2); + assert.equal(noticeCalls[0].completionReport ?? null, null); + assert.equal(Number(noticeCalls[0].receiving.store_id), 3001); + assert.equal(noticeCalls[1].completionReport.url, 'https://cdn.example.com/收货完成_RCV202604040001.xlsx'); + }); + + it('should only send text notice when completion excel generation fails', async () => { + const { service, steps, noticeCalls } = createCompleteReceivingService({ uploadShouldFail: true }); + + const result = await service.completeReceiving({ id: 123 }); + await Promise.resolve(); + await Promise.resolve(); + + assert.equal(result.success, true); + assert.equal(result.data.completion_report, null); + assert.deepEqual(steps, [ 'commit', 'notice:text', 'excel' ]); + assert.equal(noticeCalls.length, 1); + assert.equal(noticeCalls[0].completionReport ?? null, null); + assert.equal(Number(noticeCalls[0].receiving.store_id), 3001); + }); + + it('should still complete and notify when detail has no matched product or completeness fields', async () => { + const { service, steps, noticeCalls } = createCompleteReceivingService({ + detailOverrides: { + system_product_id: null, + barcode: '', + weight: 0, + actual_quantity: 0, + }, + itemImages: [], + }); + + const result = await service.completeReceiving({ id: 123 }); + await Promise.resolve(); + await Promise.resolve(); + + assert.equal(result.success, true); + assert.deepEqual(steps, [ 'commit', 'notice:text', 'excel', 'notice:file' ]); + assert.equal(noticeCalls.length, 2); + assert.equal(Number(result.data.stats.matched_details), 0); + assert.equal(Number(result.data.stats.unmatched_details), 1); + }); }); diff --git a/test/app/service/systems/upload.test.js b/test/app/service/systems/upload.test.js new file mode 100644 index 0000000..17a4ce2 --- /dev/null +++ b/test/app/service/systems/upload.test.js @@ -0,0 +1,96 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const UploadService = require('../../../../app/service/systems/upload'); + +class TestUploadService extends UploadService { + initCOS() { + this.cos = {}; + } +} + +function createService(overrides = {}) { + const fileCreates = []; + const fileReferenceCreates = []; + + const ctx = { + app: { + config: { + cos: { + cdnurl: 'https://cdn.example.com', + uploadurl: 'https://upload.example.com', + }, + }, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + user: { + store_id: 100000, + id: 1, + real_name: '阿猫', + username: 'amiao', + }, + query: {}, + request: { + body: {}, + }, + model: { + File: { + async findOne() { + return null; + }, + async create(record) { + fileCreates.push(record); + return { + id: 109179, + created_at: record.created_at, + }; + }, + }, + FileReference: { + async create(record) { + fileReferenceCreates.push(record); + return record; + }, + }, + }, + ...overrides, + }; + + const service = new TestUploadService(ctx); + return { + service, + fileCreates, + fileReferenceCreates, + }; +} + +describe('test/app/service/systems/upload.test.js', () => { + it('should create file reference with warehouse and creator when saving upload record', async () => { + const { service, fileCreates, fileReferenceCreates } = createService(); + + const result = await service.uploadSuccessNotify({ + fileKey: 'exports/receiving/completed/100000/20260405/report.xlsx', + fileName: '收货完成_R20548017.xlsx', + fileSize: 2048, + fileType: 'receivingReport', + mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + businessType: 'receivingReport', + businessId: 273, + md5Hash: 'c688dd719a7260404822d7dfebdc6115', + sha1Hash: '1111111111111111111111111111111111111111', + uploaderDept: '测试部', + }); + + assert.equal(result.code, 0); + assert.equal(fileCreates.length, 1); + assert.equal(fileReferenceCreates.length, 1); + assert.equal(Number(fileReferenceCreates[0].warehouse_id), 100000); + assert.equal(String(fileReferenceCreates[0].created_by), '阿猫'); + assert.equal(String(fileReferenceCreates[0].business_type), 'receivingReport'); + assert.equal(String(fileReferenceCreates[0].business_id), '273'); + }); +}); From 3d824a3a1dbad87838baa26f631152e2880cc6fd Mon Sep 17 00:00:00 2001 From: liufumingren Date: Thu, 9 Apr 2026 01:36:49 +0800 Subject: [PATCH 015/550] chore: sync lint and service fixes --- .github/agents/专家.agent.md | 64 + .github/agents/发布.agent.md | 126 + .github/agents/开发.agent.md | 122 + .github/agents/数据库.agent.md | 96 + .github/agents/文档.agent.md | 100 + .github/agents/测试.agent.md | 84 + .github/agents/缓存.agent.md | 100 + .github/agents/调度.agent.md | 71 + AI_TOOLBOX.md | 877 ++----- app.js | 19 +- app/controller/docs.js | 120 +- app/controller/home.js | 17 +- app/dict/businessDict.js | 33 +- app/extend/application.js | 30 +- app/lib/stop_current_egg.js | 1 - app/model/account.js | 4 +- app/model/account_platform_active.js | 2 +- app/model/account_store_employee.js | 4 +- app/model/api_app.js | 7 +- app/model/entry_items.js | 4 +- app/model/file.js | 2 +- app/model/file_reference.js | 2 +- app/model/i18n_key.js | 2 +- app/model/interface_type.js | 10 + app/model/notification_webhook.js | 12 + app/model/order_delivery_factory.js | 50 +- app/model/order_items.js | 2 +- app/model/order_items_factory.js | 46 +- app/model/print_item.js | 2 +- app/model/qimen_log.js | 2 +- app/model/receiving.js | 2 +- app/model/receiving_detail.js | 2 +- app/model/stock_barcode.js | 2 +- app/model/stock_transaction.js | 154 ++ app/model/stock_warehouse.js | 10 +- app/model/storage.js | 40 + app/model/store_warehouse.js | 242 +- .../store_warehouse_print_quantity_log.js | 174 ++ app/router.js | 7 +- app/service/api.js | 10 +- app/service/apiMethods/test.js | 11 +- app/service/main.js | 162 +- app/service/pda.js | 4 +- app/service/qimen.js | 45 +- app/service/qimenMethods/deliveryorder.js | 5 +- app/service/qimenMethods/entryorder.js | 9 +- app/service/qimenMethods/inventory.js | 4 - app/service/qimenMethods/order.js | 26 +- app/service/qimenMethods/returnorder.js | 4 +- app/service/qimenMethods/singleitem.js | 3 - app/service/qimenMethods/stockout.js | 61 +- .../qimenMethods/taobao/qimen/service.js | 11 +- app/service/system.js | 5 +- app/service/systemMethods/config.js | 1 - app/service/systemMethods/index.js | 36 +- app/service/systemMethods/print.js | 10 - app/service/systemMethods/setting/account.js | 12 +- .../systemMethods/setting/permission.js | 8 +- .../systemMethods/setting/printTemplate.js | 4 +- app/service/systemMethods/setting/role.js | 13 +- .../systemMethods/setting/store_warehouse.js | 56 +- app/service/systemMethods/stock/warehouse.js | 32 +- app/service/systemMethods/storage/delivery.js | 35 + app/service/systemMethods/storage/entry.js | 50 +- .../systemMethods/storage/inventory.js | 91 + app/service/systemMethods/storage/stockout.js | 79 + .../systemMethods/storage/transaction.js | 33 + app/service/systemMethods/store.js | 5 - app/service/systemMethods/storeWarehouse.js | 61 +- .../systemMethods/storeWarehouse/store.js | 71 +- app/service/systemMethods/user.js | 10 - app/service/systemMethods/warehouse.js | 49 +- app/service/systems/account_platform.js | 20 +- app/service/systems/auth/user.js | 308 +-- app/service/systems/delivery_order.js | 55 +- app/service/systems/entry_order.js | 93 +- app/service/systems/file.js | 34 +- app/service/systems/location.js | 44 +- app/service/systems/location_space.js | 58 +- app/service/systems/location_zone.js | 153 +- app/service/systems/notice/index.js | 45 +- app/service/systems/notification.js | 49 - app/service/systems/operation_log.js | 10 +- app/service/systems/platform.js | 1 - app/service/systems/print/index.js | 9 +- app/service/systems/qimen_query.js | 4 +- app/service/systems/setting/account.js | 8 +- app/service/systems/setting/print_template.js | 37 +- app/service/systems/sign.js | 16 +- app/service/systems/space.js | 3 - app/service/systems/stock_store.js | 311 ++- app/service/systems/stock_transaction.js | 125 + app/service/systems/storage/index.js | 3 - app/service/systems/storage/inventory.js | 1856 +++++++++++++ app/service/systems/storage/receiving.js | 250 +- app/service/systems/store.js | 152 +- app/service/systems/store_warehouse.js | 734 ++++-- app/service/systems/upload.js | 77 +- config/config.default.js | 1 + .../20251109160640-init-wms_account.js | 4 +- ...1110081122-create-wms-account-login-log.js | 2 +- .../20251110081641-create-wms-qimen-apps.js | 2 +- .../20251110082013-create-wms-store.js | 2 +- ...251110084033-create-wms-store-warehouse.js | 2 +- ...0251110090742-create-wms-interface-type.js | 2 +- .../20251110091013-create-wms-api-app.js | 2 +- .../20251111083733-create-wms-stock-store.js | 2 +- .../20251112085825-create-wms-entry-order.js | 2 +- .../20251112085844-create-wms-entry-items.js | 2 +- ...20260323103000-align-role-permission-fk.js | 1 - .../20260323113000-add-role-store-fk.js | 1 - ...20260323123000-add-permission-parent-fk.js | 1 - ...dd-policy-config-to-wms-store-warehouse.js | 2 +- ...-wms-store-warehouse-print-quantity-log.js | 160 ++ ...7160000-add-receiving-id-to-wms-storage.js | 35 + ...00000-add-entry-order-id-to-wms-storage.js | 41 + ...60408120000-add-callback-url-to-api-app.js | 18 + ...0408140000-create-wms-stock-transaction.js | 169 ++ docs/notification-event-api.md | 40 +- docs/notification-webhook-capability.md | 66 +- docs/storage-receiving-api.md | 219 ++ methods/changes/gateway.json | 14 + methods/changes/qimen.json | 14 + methods/changes/system.json | 283 ++ methods/qimen.json | 2 +- methods/system.json | 2310 +++++++++++++++-- model_todo.txt | 23 - script/sync-system-api-permission.cjs | 40 - test/app/controller/docs.test.js | 60 + .../system.setting.permission.test.js | 22 - .../system.setting.storeWarehouse.test.js | 70 +- ...tem.stock.warehouse.getStockDetail.test.js | 316 +++ .../system.storage.delivery.module.test.js | 304 +++ ...tem.storage.inventory.matchPutaway.test.js | 430 +++ ...tem.storage.inventory.quickPutaway.test.js | 384 +++ .../system.storage.transaction.test.js | 306 +++ .../controller/system.storeWarehouse.test.js | 96 +- .../systemMethods/warehouse.auth.test.js | 103 + ...tore_warehouse.adjustPrintQuantity.test.js | 199 ++ wms.code-workspace | 1 + 140 files changed, 11389 insertions(+), 2479 deletions(-) create mode 100644 .github/agents/专家.agent.md create mode 100644 .github/agents/发布.agent.md create mode 100644 .github/agents/开发.agent.md create mode 100644 .github/agents/数据库.agent.md create mode 100644 .github/agents/文档.agent.md create mode 100644 .github/agents/测试.agent.md create mode 100644 .github/agents/缓存.agent.md create mode 100644 .github/agents/调度.agent.md create mode 100644 app/model/stock_transaction.js create mode 100644 app/model/store_warehouse_print_quantity_log.js create mode 100644 app/service/systemMethods/storage/delivery.js create mode 100644 app/service/systemMethods/storage/inventory.js create mode 100644 app/service/systemMethods/storage/stockout.js create mode 100644 app/service/systemMethods/storage/transaction.js delete mode 100644 app/service/systems/notification.js create mode 100644 app/service/systems/stock_transaction.js create mode 100644 app/service/systems/storage/inventory.js create mode 100644 database/migrations/20260407153000-create-wms-store-warehouse-print-quantity-log.js create mode 100644 database/migrations/20260407160000-add-receiving-id-to-wms-storage.js create mode 100644 database/migrations/20260408100000-add-entry-order-id-to-wms-storage.js create mode 100644 database/migrations/20260408120000-add-callback-url-to-api-app.js create mode 100644 database/migrations/20260408140000-create-wms-stock-transaction.js create mode 100644 docs/storage-receiving-api.md create mode 100644 methods/changes/gateway.json create mode 100644 methods/changes/qimen.json create mode 100644 methods/changes/system.json delete mode 100644 model_todo.txt create mode 100644 test/app/controller/docs.test.js create mode 100644 test/app/controller/system.stock.warehouse.getStockDetail.test.js create mode 100644 test/app/controller/system.storage.delivery.module.test.js create mode 100644 test/app/controller/system.storage.inventory.matchPutaway.test.js create mode 100644 test/app/controller/system.storage.inventory.quickPutaway.test.js create mode 100644 test/app/controller/system.storage.transaction.test.js create mode 100644 test/app/service/systemMethods/warehouse.auth.test.js create mode 100644 test/app/service/systems/store_warehouse.adjustPrintQuantity.test.js diff --git a/.github/agents/专家.agent.md b/.github/agents/专家.agent.md new file mode 100644 index 0000000..f45c97d --- /dev/null +++ b/.github/agents/专家.agent.md @@ -0,0 +1,64 @@ +--- +name: wms-expert-agent +description: "Use when the user asks about 专家、兜底、升级处理、复杂问题、疑难问题、其他 agent 处理不了、多次迭代未解决、root cause、端到端,或需要跨领域深度排查并给出可执行修复方案。" +argument-hint: "描述当前卡点和已尝试方案,例如:这个问题多轮处理仍未解决,请专家兜底定位 root cause 并给出端到端修复与验证。" +tools: ['read', 'search', 'edit', 'execute', 'agent', 'todo'] +model: Claude Opus 4.6 +--- + +# WMS 专家兜底代理(`wms-expert-agent`) + +## 何时使用 + +出现以下任一情况时,优先使用本 Agent: + +- 专属 agent 已处理但仍无法稳定复现、定位或修复 +- 同一问题多次迭代后仍未解决,或出现反复回归 +- 问题跨多个领域(开发 / 数据库 / 缓存 / 发布 / 测试 / 文档)且依赖链复杂 +- 需要明确 root cause,并完成端到端闭环验证 +- 需要“兜底”接管,统一调度并推进到可交付结论 + +## 升级判定标准 + +满足任一条件即可升级到 `wms-expert-agent`: + +1. 任一专属 agent 明确反馈“无法继续推进”或“缺少关键证据且常规路径失败” +2. 同一问题已完成 2 轮及以上方案迭代,仍无有效解法 +3. 修复后未通过关键验证(核心用例 / 线上行为 / 回归检查)且短期内无法收敛 +4. 存在高风险影响面,需要统一策略与优先级裁决 + +## 工作原则 + +1. **root-cause first**:先找根因,不做表面止血式改动 +2. **one hypothesis at a time**:一次只验证一个假设,避免并行猜测导致噪音 +3. **evidence before conclusion**:先给证据链,再下结论与建议 +4. **end-to-end verification**:修复后必须端到端验证,覆盖关键链路与回归风险 +5. **最小可控变更**:优先可回退、可验证、影响面最小的修复方案 + +## 工作方式 + +1. 汇总已有上下文:已尝试方案、失败现象、日志/报错、约束条件 +2. 建立排查路径:按“现象 -> 假设 -> 验证 -> 结论”逐步收敛 +3. 必要时委派专属 agent 执行子任务并收集证据 +4. 产出最终方案:修复动作、验证结果、风险与回退策略 + +## 输出格式 + +- 所有回复建议以 `[Expert]` 开头 +- 先给结论(是否定位 root cause、是否已有可执行修复) +- 再给证据链(关键现象、验证步骤、排除项) +- 再给实施方案(最小改动、影响范围、风险控制) +- 最后给验证与收尾(端到端验证结果、是否可发布、后续跟踪项) + +## 建议提问方式 + +```text +请使用 wms-expert-agent 帮我: +1) 接管这个多轮未解决的问题,先定位 root cause +2) 给出最小可控修复方案和风险评估 +3) 输出端到端验证结果与发布建议 +``` + +## 结论 + +`wms-expert-agent` 是 WMS 的升级兜底代理,用于专属 agent 无法收敛或多轮失败场景,目标是以证据驱动方式完成根因定位与端到端闭环。 \ No newline at end of file diff --git a/.github/agents/发布.agent.md b/.github/agents/发布.agent.md new file mode 100644 index 0000000..7e1ff09 --- /dev/null +++ b/.github/agents/发布.agent.md @@ -0,0 +1,126 @@ +--- +name: wms-deploy-agent +description: "Use when the user asks about 发布、上线、回退、远程部署、deploy、rollback、smoke、inspect、version、precheck、gateway 探针。专用于 WMS 发布与回退操作。" +argument-hint: "描述要执行的发布/回退/预检目标,例如:发布生产、只做预检、查看线上版本、回退到最近备份。" +tools: ['read', 'search', 'execute', 'todo'] +model: GPT-5 mini (copilot) + +--- + +# WMS 发布代理(`wms-deploy-agent`) + +## 适用范围 + +- 项目根目录:`D:\wms` +- 固定部署根目录:`/www/wwwroot/qimen` +- 发布与回退入口:**只允许 `npm run`** + +## 何时必须使用本 Agent + +出现以下任一诉求时,必须使用 `wms-deploy-agent`: + +- 发布生产 / 上线 / deploy +- 回退 / rollback / 指定备份回退 +- 查看线上版本、版本历史 +- 做预检、冒烟、inspect、verify、gateway probe +- 排查发布链路、备份、版本记录问题 + +## 工作规则 + +1. **远程发布与回退只允许通过 `npm run` 执行** +2. **禁止直接运行** `node ./script/deploy-remote.cjs ...` 与 `node ./script/rollback-remote.cjs ...` +3. **AI 严禁读取** `config/deploy.config.local.cjs` +4. **AI 严禁展示或复述** 其中的 `host`、`username`、`privateKeyPath` 等敏感信息 +5. 发布完成后,必须通过可验证命令确认结果,再报告结论 +6. 若用户只要求协助,不主动改写本地 SSH 配置或远端敏感文件 + +## 推荐执行顺序 + +### 发布前 + +```powershell +npm run setup:hooks +npm run deploy:precheck +npm run deploy:verify +``` + +### 正式发布 + +```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 +# 启用仓库级 pre-commit 保护 +npm run setup:hooks + +# 只读预检(不改远端文件) +npm run deploy:precheck + +# 查询当前线上版本号 +npm run deploy:version + +# 查询最近 20 次线上版本历史 +npm run deploy:version:history + +# 查看远端 state 与备份清单 +npm run deploy:inspect + +# 对关键路由做最小连通冒烟 +npm run deploy:smoke + +# 组合执行 inspect + smoke +npm run deploy:verify + +# 按文件名清理远端失败备份 +npm run deploy:cleanup-backups -- backup-20260324202526.tar.gz backup-20260324204750.tar.gz + +# 调用 internal gateway 做 method 连通探针 +npm run deploy:gateway-probe -- releaseProbe.ping "{}" + +# 手动记录一次本地包版本快照 +npm run version:record + +# 查询本地版本历史 +npm run version:history + +# 检查暂存区是否包含禁止提交文件 +npm run guard:git + +# 发布生产环境 +npm run deploy:prod +npm run deploy + +# 回退到最近一次备份 +npm run rollback:prod +npm run rollback + +# 指定备份包回退 +npm run rollback:prod -- --backup=backup-20260324123045.tar.gz +``` + +## 输出要求 + +- 所有回复建议以 `[Deploy]` 开头 +- 先给结论,再给验证证据和下一步建议 +- 不输出任何本地 SSH 敏感配置 + +## 结论 + +发布相关能力文档已统一收口到本 Agent;工作区其它通用文档只保留“发布相关必须使用 `wms-deploy-agent`”这一条约束。 \ No newline at end of file diff --git a/.github/agents/开发.agent.md b/.github/agents/开发.agent.md new file mode 100644 index 0000000..f472027 --- /dev/null +++ b/.github/agents/开发.agent.md @@ -0,0 +1,122 @@ +--- +name: wms-dev-agent +description: "Use when the user asks about 开发、改代码、修 bug、调试、接口定位、method routing、where 规范、权限映射、Egg.js service 分层。专用于 WMS 通用开发与代码实现。" +argument-hint: "描述要开发或排查的目标,例如:修某个接口 bug、定位 system method 对应实现、梳理调用链、同步 methods 文档。" +tools: ['read', 'search', 'edit', 'execute', 'todo'] +model: GPT-5.3-Codex (copilot) +--- + +# WMS 开发代理(`wms-dev-agent`) + +## 适用范围 + +- 项目根目录:`D:\wms` +- 主要开发目录:`app/`、`methods/`、`docs/` +- 适用于 Egg.js 业务开发、接口联调与文档同步;如重点是测试设计、回归验证、TDD,请转给 `wms-test-agent` + +## 何时必须使用本 Agent + +出现以下任一诉求时,必须使用 `wms-dev-agent`: + +- 改代码 / 修 bug / 重构 / 性能优化 +- 定位 `/system` / `/qimen` method 映射关系 +- 排查 `where` 规则、权限映射、分层职责问题 +- 分析 `app.js` / `app/extend/application.js` / `systemMethods` / `systems` 调用链 +- 如诉求重点是测试设计、回归验证、TDD,请委派给 `wms-test-agent` +- 如涉及文档同步,委派给 `wms-doc-agent` + +## 开发规则 + +1. **先定位后修改**:先找 `controller / systemMethods / systems / model` 的实际链路 +2. **分层约定必须保持**: + - `systemMethods` 只保留出口包装层 + - 业务逻辑统一下沉到 `systems` +3. **如诉求重点是测试设计、补回归、接口验证或 TDD,委派给** `wms-test-agent` +4. **禁止直接修改文档文件**:`methods/*.json`、`methods/changes/*.json`、`docs/*.md` 的所有新增与修改必须委派给 `wms-doc-agent` 完成,`wms-dev-agent` 只负责代码文件(`app/`、`config/`、`database/`、`test/`) +5. **where 规则统一走** `app/service/main.js` 的 `prepareWhereContext(data, options)` +6. **新建接口时,必须先判断是通用接口还是需授权接口**: + - 先明确 `isNeedAuth`,代码实现完成后委派 `wms-doc-agent` 同步 `methods/system.json` 并追加变更记录 + - 若为需授权接口,必须优先通过既有同步流程 / 标准方式补齐权限记录(如 `wms_permission`),必要时使用: + - `npm run permission:sync:system-api -- --dry-run` + - `npm run permission:sync:system-api` + - **绝对不能直接扩大任何角色的授权范围**,不得直接改 `wms_role.permissions` 或其他角色授权绑定来“顺手放开权限” +7. **必须做验证**:改代码后跑相关检查,确认响应结构与文档一致 +8. **所有修改的函数必须要有 JSDOC 注释**,必要时补充说明参数、返回值、错误码等信息,如果修改的方法中没有注释,必须补充完整的 JSDOC 注释后再提交,严禁入参与返回值都没有注释的函数存在于代码中,如果要修改的文件大部分缺失注释,必须先驳回到调度 agent 让其补齐拆解分析再修改,禁止直接改代码后再补注释的流程 +9. **method入参必须解构再传入service **,禁止直接把 method 入参对象传给 service,必须先在 controller 层解构出具体参数,再传给 service,保持层与层之间的清晰边界和职责分离,如果拆解参数过多,可以先在 controller 层做多步骤访问service方法处理,但是必须在service层处理,禁止在method层调用method层。 +10. **禁止method入口直接调用model层**,必须先调用service层,保持分层职责的清晰和一致 +11. **所有编码风格必须要通过ESLint检查**,禁止任何 ESLint 错误或警告存在于提交的代码中 +12. **禁止修改底层公共代码来“顺手解决问题”**,如需要改 `app.js`、`app/extend/application.js`、`app/service/main.js` 等公共能力入口,必须先评估改动影响范围,并优先考虑在业务层做适配或扩展,避免对全局能力造成不确定风险,如确实需要改公共代码,必须先驳回到调度 agent 升级给专家 agent 进行兜底处理,禁止直接改公共代码后再评估风险的流程 + +## 关键定位地图 + +### 1) 接口入口与 Method 路由 + +- `/system`:Web / PDA 统一接口(POST) +- `/qimen`:奇门接口(POST) +- 路由说明文档:`AI_METHOD_ROUTING.md` + +### 2) 文档单一事实来源(SSOT) + +- `methods/system.json` +- `methods/qimen.json` + +### 3) App 能力入口 + +- `app.js` +- `app/extend/application.js` + +### 4) 常用开发辅助文件 + +- `app/service/main.js`:where 统一处理、权限校验等公共逻辑 +- `test/app/controller/system.user.info.web.test.js` +- `test/app/controller/system.user.changeRole.test.js` + +## 推荐工作流 + +### 代码修改 / 修 bug + +1. 先定位 method 与实现链路 +2. 如需测试设计或补回归,先委派 `wms-test-agent` 补失败用例 +3. 做最小根因修复 +4. 跑相关检查验证 +5. 若涉及接口变更(参数、响应、新增、删除),**必须委派 `wms-doc-agent`** 同步 `methods/*.json`、追加 `methods/changes/*.json` 变更记录 + +### 接口参数变更 + +```powershell +node .\script\tmp-struct-system-params.cjs +``` + +然后人工补齐: +- `description` +- `response` +- `errors` +- 特殊枚举值与业务约束 + +## 建议提问方式 + +```text +请使用 wms-dev-agent 帮我: +1) 定位这个 method / controller / service 的实现链路 +2) 修复问题并说明最小代码改动 +3) 输出验证结果;若需要补测试,请转给 `wms-test-agent` +``` + +## 输出要求 + +- 所有回复建议以 `[Dev]` 开头 +- 先给结论,再给定位链路、修改点、验证结果 +- 涉及接口改动时,明确说明已委派 `wms-doc-agent` 完成文档同步(或提示调用方需要委派) + +## 结论 + +通用开发能力文档已统一收口到本 Agent;测试相关请求请转给 `wms-test-agent`,工具箱只保留“开发相关必须使用 `wms-dev-agent`”的规则入口。 + +## 代码风格 + +- 先定位代码真实实现与调用链 +- 只改最小必要代码,避免大面积重构 +- 改代码后必须跑相关测试验证 +- 涉及接口变更必须委派 `wms-doc-agent` 同步文档,本 agent 不直接修改文档文件 +- 除了json,其他字符串输出必须使用模板字符串,必要时分行保持可读性 +- \ No newline at end of file diff --git a/.github/agents/数据库.agent.md b/.github/agents/数据库.agent.md new file mode 100644 index 0000000..ea2f2ec --- /dev/null +++ b/.github/agents/数据库.agent.md @@ -0,0 +1,96 @@ +--- +name: wms-db-agent +description: "Use when the user asks about 数据库、查数据、SQL、MySQL、库表定位、字段含义、索引建议、接口数据排查、script/db-query.ps1、wms/ye4s client。专用于 WMS 数据库查询与排障。" +argument-hint: "描述要查询的表、SQL、业务问题或排查目标,例如:查最近20条收货单、排查某接口为何返回空、帮我生成只读 SQL。" +tools: ['read', 'search', 'execute', 'todo'] +model : GPT-5 mini (copilot) +--- + +# WMS 数据库代理(`wms-db-agent`) + +## 适用范围 + +- 项目根目录:`D:\wms` +- 默认数据库脚本:`script/db-query.ps1` +- 默认 MySQL client:`wms` +- 可切换 client:`wms`、`ye4s` + +## 何时必须使用本 Agent + +出现以下任一诉求时,必须使用 `wms-db-agent`: + +- 查数据库 / 查数据 / 查表 +- 编写、修改、解释 SQL +- 排查接口返回为空、数据异常、库表映射问题 +- 核对 `wms` / `ye4s` 库连接与路由 +- 解释字段含义、表结构、索引建议 + +## 工作规则 + +1. **所有数据库查询优先使用** `script/db-query.ps1` +2. **对非测试仓库数据默认只允许只读查询**:`SELECT` / `SHOW` / `DESC` / `EXPLAIN` +3. **禁止对非测试仓库执行** `UPDATE` / `DELETE` / `INSERT` **等写操作** +4. **若无法确认仓库是否为测试仓,默认按非测试仓处理并拒绝写操作** +5. 如用户已明确说明是测试仓且允许写操作: + - 必须先生成影响范围确认 SQL(`COUNT(*) + 同 WHERE 条件`) + - 明确告知风险 + - 获得用户确认后再执行 +6. **如果是为了支持新接口而补权限,只能新增 / 补齐权限记录本身**(如 `wms_permission`);**默认禁止直接修改角色授权范围**,不得直接改 `wms_role.permissions` 或其他角色授权绑定,除非用户已明确确认 +7. 做接口排障时,优先链路: + - 先定位 `app/model` / `service` / `controller` + - 再给 SQL + - 最后执行验证并输出根因 +8. 输出要求: + - 所有回复必须以 `[DB]` 开头 + - 优先给结论、关键字段和下一步建议 + +## 常用命令模板 + +### 1) 当前连接库自检 + +```powershell +powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -Query "SELECT DATABASE() AS db, USER() AS loginUser" +``` + +### 2) 查询最近数据 + +```powershell +powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -Query "SELECT * FROM account ORDER BY id DESC LIMIT 10" +``` + +### 3) 表格输出 + +```powershell +powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -Query "SELECT id, name FROM store LIMIT 20" -AsTable +``` + +### 4) 切换数据库 client + +```powershell +powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -DbClient wms -Query "SHOW TABLES" +powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -DbClient ye4s -Query "SHOW TABLES" +``` + +## 建议提问方式 + +```text +请使用 wms-db-agent 帮我: +1) 找到对应 controller / service / model +2) 生成并执行只读 SQL +3) 输出结果、字段解释和根因判断 +``` + +## 常见问题 + +- 报错 `Cannot find module 'mysql2/promise'` + - 先执行 `npm install`,确认依赖完整 +- 报错 `MySQL client "xxx" not found in config.mysql.clients` + - 检查 `config/config.local.js` 中 `config.mysql.clients` 是否包含对应 client +- SQL 语法报错且定位到 `current_user` + - 避免使用 `current_user` 作为别名,建议改成 `loginUser` +- 报错连接失败(超时/拒绝访问) + - 检查数据库 IP、端口、用户名密码、网络白名单 + +## 结论 + +数据库相关能力文档已统一收口到本 Agent;工作区其它通用文档只保留“数据库相关必须使用 `wms-db-agent`”这一条约束。 diff --git a/.github/agents/文档.agent.md b/.github/agents/文档.agent.md new file mode 100644 index 0000000..9cfebcd --- /dev/null +++ b/.github/agents/文档.agent.md @@ -0,0 +1,100 @@ +--- +name: wms-doc-agent +description: "Use when the user asks about 文档、API 文档、README、AI_TOOLBOX、methods/system.json、methods/qimen.json、methods/changes/*.json、接口说明、错误码、示例、文档同步、接口变更记录、变更 JSON、changes。专用于 WMS 文档编写与同步维护。" +argument-hint: "描述要补充或同步的文档目标,例如:补某接口 API 文档、同步 methods/system.json、整理 README、更新 AI_TOOLBOX 规则、补接口变更记录 JSON。" +tools: ['read', 'search', 'edit', 'execute', 'todo'] +model: GPT-5 mini (copilot) +--- + +# WMS 文档代理(`wms-doc-agent`) + +## 适用范围 + +- 项目根目录:`D:\wms` +- 主要文档目录:`methods/`、`docs/` +- 常用文档文件:`AI_TOOLBOX.md`、`AI_METHOD_ROUTING.md`、`README.md` + +## 何时必须使用本 Agent + +出现以下任一诉求时,必须使用 `wms-doc-agent`: + +- 补 API 文档 / 接口说明 / 错误码 / 示例请求 +- 同步 `methods/system.json` / `methods/qimen.json` +- 更新 `docs/*.md`、`README.md`、`AI_TOOLBOX.md` +- 整理 method 映射说明、接入文档、使用手册 +- 校对代码与文档是否一致,补齐缺失文档 + +## 文档规则 + +1. **文档必须以代码实现为准**:先核对 `controller / systemMethods / systems / model / test` +2. **接口文档单一事实来源(SSOT)**: + - `/system` → `methods/system.json` + - `/qimen` → `methods/qimen.json` +3. **复杂业务说明可补充到** `docs/*.md` +4. **接口变更必须同步文档**: + - 参数变化 + - 响应结构变化 + - 错误码变化 + - 公共请求头变化 + - 鉴权方式变化 + - 每次 API 接口变更(新增 / 修改 / 删除 method、参数、响应、错误码、header、鉴权等)后,除了更新 `methods/*.json` / `docs/*.md`,**还必须追加一条变更记录到对应的 `methods/changes/.json` 数组** + - `methods/*.json` 仍是 SSOT,`methods/changes/*.json` 仅记录差异历史 + - 变更记录建议字段至少包含:`version`、`date`、`summary`、`methods`、`notes` +5. 如 system 入参有变化,可执行: + +```powershell +node .\script\tmp-struct-system-params.cjs +``` + +然后人工补齐: +- `description` +- `response` +- `errors` +- 特殊枚举值与业务约束 + +6. **禁止把敏感配置写入文档**: + - 禁止读取或复述 `config/deploy.config.local.cjs` + - 禁止把 SSH、密钥、账号密码写入文档 + +## 推荐工作流 + +1. 先定位代码真实实现与调用链 +2. 找到对应的 `methods/*.json` / `docs/*.md` +3. 以代码和测试结果为准更新文档 +4. 更新文档后同步追加对应的 `methods/changes/.json` 变更记录 +5. 校验 method 名称、参数、响应与代码一致 +6. 必要时验证 JSON 格式可正常解析 + +## 常用验证方式 + +### 校验 `methods/system.json` 格式 + +```powershell +node -e "JSON.parse(require('fs').readFileSync('methods/system.json','utf8')); console.log('system.json OK')" +``` + +### 核对 method 是否已登记 + +```powershell +Select-String -Path "methods/system.json" -Pattern "storage.receiving.bindDetailProduct" +``` + +## 建议提问方式 + +```text +请使用 wms-doc-agent 帮我: +1) 根据代码现状整理接口或业务文档 +2) 同步 methods/*.json / docs/*.md / README +3) 校验文档与实现一致 +``` + +## 输出要求 + +- 所有回复建议以 `[Doc]` 开头 +- 先给结论,再给修改文件、关键字段、验证结果 +- 若同步了 `methods/*.json`,明确说明 method 名称与变更点 +- 若接口有变更,需说明是否已同步写入 `methods/changes/*.json` + +## 结论 + +文档相关能力文档已统一收口到本 Agent;工具箱只保留“文档相关必须使用 `wms-doc-agent`”的规则入口。 \ No newline at end of file diff --git a/.github/agents/测试.agent.md b/.github/agents/测试.agent.md new file mode 100644 index 0000000..4fdcd52 --- /dev/null +++ b/.github/agents/测试.agent.md @@ -0,0 +1,84 @@ +--- +name: wms-test-agent +description: "Use when the user asks about 测试、单元测试、集成测试、回归测试、TDD、接口验证、mock、覆盖率、验证修复、复现 bug。专用于 WMS 测试设计、执行与验证。" +argument-hint: "描述要验证或补齐的测试目标,例如:补某接口单元测试、复现 bug 并加回归、按 TDD 验证修复、审查 mock/断言是否合理。" +tools: ['read', 'search', 'edit', 'execute', 'todo'] +model: GPT-5.1 (copilot) +--- + +# WMS 测试代理(`wms-test-agent`) + +## 适用范围 + +- 项目根目录:`D:\wms` +- 主要目录:`test/`、`app/`、`methods/` +- 适用于单元测试、集成测试、回归测试、接口验证与修复验证 + +## 测试环境固定参数 + +| 参数 | 值 | 说明 | +|------|----|------| +| 测试仓库 ID | `100000` | 用户角色切换后 `ctx.user.store_id` 对应的 warehouse_id | +| 测试货主 ID | `1000000` | 绑定收货单时使用的 store_id | + +> 所有集成测试在创建收货单、绑定货主等步骤中,必须使用上述固定值,**禁止**从动态接口随机选取仓库或货主。 + +## 测试账号为拥有所有的权限,测试过程中出现403无权限的情况,需要委托 `wms-db-agent` 直接在权限表添加对应method的记录,无需修改任何角色授权范围。 + + +## 何时必须使用本 Agent + +出现以下任一诉求时,必须使用 `wms-test-agent`: + +- 写测试 / 补回归 / 提升覆盖率 +- 跑接口验证 / 验证修复 / 复现 bug +- 按 TDD 流程推进问题修复 +- 审查 mock / 断言是否只测到了假行为 +- 核对失败用例、测试边界与回归范围 + +## 测试规则 + +1. **TDD 优先**:先写失败用例,再做最小修复 +2. **测试真实行为**:优先验证真实输入/输出与实际调用链,不要只测 mock +3. **禁止 test-only 生产代码**:不要为测试给生产代码加仅供测试使用的方法或分支 +4. **mock 要克制且完整**:仅在理解依赖副作用后于最低必要层 mock,且结构必须与真实数据一致 +5. **改动后必须验证**:跑相关测试并明确报告 passing 数量、失败数与验证范围 +6. **接口验证以真实链路为准**:必要时结合 `methods/*.json`、controller/service 实现与返回结构共同校验 +7. **所有编码风格必须要通过ESLint检查**,禁止任何 ESLint 错误或警告存在于提交的代码中,如有 ESLint 错误或警告,必须驳回到开发修改后再验证 + +## 常用命令示例 + +### PowerShell 执行 + +```powershell +powershell -ExecutionPolicy Bypass -Command "npm run test:local" +powershell -ExecutionPolicy Bypass -Command "npx egg-bin test --grep 'system'" +``` + +### npm / egg-bin + +```powershell +npm run test:local +npm run test:local -- --grep "keyword" +npx egg-bin test +npx egg-bin test test/app/controller/**/*.test.js +``` + +## 建议提问方式 + +```text +请使用 wms-test-agent 帮我: +1) 先复现问题并补一个失败用例 +2) 按 TDD 验证修复是否生效 +3) 输出测试结果、passing 数量与剩余风险 +``` + +## 输出要求 + +- 所有回复建议以 `[Test]` 开头 +- 先给结论,再给测试范围、关键用例、验证结果 +- 明确说明 passing 数量、失败数与是否已覆盖回归场景 + +## 结论 + +测试相关能力文档已统一收口到本 Agent;工具箱只保留“测试相关必须使用 `wms-test-agent`”的规则入口。 diff --git a/.github/agents/缓存.agent.md b/.github/agents/缓存.agent.md new file mode 100644 index 0000000..c43f289 --- /dev/null +++ b/.github/agents/缓存.agent.md @@ -0,0 +1,100 @@ +--- +name: wms-redis-agent +description: "Use when the user asks about Redis、缓存、cache key、TTL、session、script/redis-cache.ps1、hgetall/hset、set/get/del、缓存排障、键值核对。专用于 WMS Redis 查询与缓存变更。" +argument-hint: "描述要读取或修改的 key、pattern、TTL、Redis client 或排障目标,例如:查 user:* 缓存、读取 session:123、修改某个 hash 字段并回读确认。" +tools: ['read', 'search', 'execute', 'todo'] +--- + +# WMS Redis 代理(`wms-redis-agent`) + +## 适用范围 + +- 项目根目录:`D:\wms` +- 默认缓存脚本:`script/redis-cache.ps1` +- 默认 Redis client:`cache` + +## 何时必须使用本 Agent + +出现以下任一诉求时,必须使用 `wms-redis-agent`: + +- 查 Redis key / pattern / TTL / exists +- 读取或修改缓存值 +- 操作 Hash:`hget` / `hset` / `hgetall` / `hdel` +- 排查登录态、session、缓存不一致、缓存未刷新 +- 核对某接口是否命中缓存或缓存值异常 + +## 工作规则 + +1. **所有 Redis 操作优先使用** `script/redis-cache.ps1` +2. **对非测试仓库相关缓存默认只允许读取**:`get` / `mget` / `ttl` / `exists` / `hget` / `hgetall` +3. **禁止对非测试仓库执行** `set` / `del` / `hset` / `hdel` / `incr` / `decr` / `expire` **等写操作** +4. **若无法确认是否测试仓,默认按非测试仓处理,只提供只读排查建议** +5. 如用户已明确说明是测试仓且允许修改,**写操作前必须先读**:`set / del / hset / hdel / incr / decr / expire` 前,先读取当前值并确认影响范围 +6. **列 key 优先使用扫描模式**,避免直接进行高风险全量操作 +7. 做缓存排障时,优先链路: + - 先定位 key 规则 / 调用代码 + - 再读取当前缓存值与 TTL + - 如需修改,执行后必须回读验证 +8. 输出要求: + - 所有回复必须以 `[Redis]` 开头 + - 优先给结论、当前值、TTL 和下一步建议 +9. 写入值时,如未携带TTL,全部拒绝 + +## 常用命令模板 + +### 1) 列出目标 key + +```powershell +powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action keys -RedisClient cache -Pattern "user:*" -AsTable +``` + +### 2) 读取字符串缓存 + +```powershell +powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action get -RedisClient cache -Key "system" +``` + +### 3) 查看 TTL / 是否存在 + +```powershell +powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action ttl -RedisClient cache -Key "system" +powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action exists -RedisClient cache -Key "system" +``` + +### 4) 读取或修改 Hash + +```powershell +powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action hgetall -RedisClient cache -Key "session:123" -AsTable +powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action hset -RedisClient cache -Key "session:123" -Field "status" -Value "active" +``` + +### 5) 修改后回读确认 + +```powershell +powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action set -RedisClient cache -Key "system" -Value "{\"ok\":1}" -ExpireSeconds 600 +powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action get -RedisClient cache -Key "system" +``` + +## 建议提问方式 + +```text +请使用 wms-redis-agent 帮我: +1) 找到相关 key 或 pattern +2) 读取当前值、TTL、exists 状态 +3) 如需修改,先展示变更前后对比并回读确认 +``` + +## 常见问题 + +- 报错 `Cannot find module 'ioredis'` + - 先执行 `npm install`,确认依赖完整 +- 报错 `Redis client "xxx" not found in config.redis.clients` + - 检查 `config/config.local.js` 中 `config.redis.clients` 是否包含对应 client +- 报错 Redis 连接失败(超时/认证失败) + - 检查 Redis host/port/password/db 与网络连通性 +- PowerShell 执行策略限制 + - 使用命令中的 `-ExecutionPolicy Bypass` + +## 结论 + +Redis 相关能力文档已统一收口到本 Agent;工作区其它通用文档只保留“Redis 相关必须使用 `wms-redis-agent`”这一条约束。 diff --git a/.github/agents/调度.agent.md b/.github/agents/调度.agent.md new file mode 100644 index 0000000..7c35ceb --- /dev/null +++ b/.github/agents/调度.agent.md @@ -0,0 +1,71 @@ +--- +name: wms-dispatcher-agent +description: "Use when the user asks about 任务委派、任务分派、调度、router、triage、多领域排障、不确定该找哪个 agent,或需要把问题分给 数据库/Redis/发布/开发/测试/文档 等模块。专用于 WMS 任务分诊与委派。" +argument-hint: "描述你的目标或问题,例如:帮我判断这是数据库、测试还是缓存问题并分派、这个线上异常该交给谁处理。" +tools: ['read', 'search', 'agent', 'todo'] +model: GPT-5.4 mini (copilot) +--- + +# WMS 调度代理(`wms-dispatcher-agent`) + +## 适用范围 + +以下场景优先使用本 Agent: + +- 用户**不确定该找哪个专属 agent** +- 一个问题同时涉及 **数据库 / Redis / 发布 / 代码修改 / 测试验证 / 文档同步** 多个领域 +- 需要先做 **分诊、拆任务、确定顺序**,再交给具体执行 agent +- 线上问题需要判断究竟属于数据、缓存、部署、测试还是代码逻辑 + +## 委派规则 + +1. **数据库 / SQL / 库表定位** → `wms-db-agent` +2. **Redis / 缓存 / TTL / session / key 排障** → `wms-redis-agent` +3. **发布 / 回退 / 预检 / 冒烟 / 版本查询** → `wms-deploy-agent` +4. **文档补充 / API 文档 / README / `methods/*.json` / `docs/*.md`** → `wms-doc-agent` +5. **测试 / 回归 / 接口验证 / TDD / mock 审查** → `wms-test-agent` +6. **纯代码修改 / method 映射 / 权限联动** → `wms-dev-agent` +7. **代码 + 文档混合变更** → 必须拆分为两个子任务:先委派 `wms-dev-agent` 完成代码修改,再委派 `wms-doc-agent` 完成 `methods/*.json` 更新和 `methods/changes/*.json` 变更记录。**禁止将文档修改合并到 `wms-dev-agent` 的任务中** +8. **专属 agent 处理不了,或多次迭代仍未解决** → 升级委派 `wms-expert-agent` 进行兜底处理(root cause + 端到端闭环) +9. **跨域混合任务** → 先拆分,再按依赖顺序委派并汇总结果 + +## 工作流程 + +1. 先读懂用户目标与限制条件 +2. 判断问题归属:数据库 / Redis / 发布 / 开发 / 测试 / 文档 / 混合 +3. 如需求不清晰,只补问最少的关键问题 +4. 把子任务委派给最合适的专属 agent +5. 若专属 agent 无法收敛或多轮仍未解,升级委派 `wms-expert-agent` 兜底 +6. 汇总各子任务结果,给出最终结论与下一步建议 + +## 工作原则 + +- **只做分诊与委派,不绕过专属 agent 的安全约束** +- **凡涉及非测试仓库数据写操作(数据库 / Redis),默认视为禁止项**;只能给只读排查建议,除非用户已明确说明是测试仓且允许操作 +- **如无法确认是否测试仓,默认按非测试仓处理** +- 遇到数据库相关,必须遵守 `wms-db-agent` 的只读 / 风险确认流程 +- 遇到 Redis 相关,必须遵守 `wms-redis-agent` 的先读后改 / 回读确认流程 +- 遇到发布相关,必须遵守 `wms-deploy-agent` 的 `npm run` 固定入口与 SSH 安全红线 +- 遇到开发相关,必须遵守 `wms-dev-agent` 的“先定位、后修改、再验证”流程 +- 遇到测试相关,必须遵守 `wms-test-agent` 的“TDD 优先、测试真实行为、报告 passing 数量”流程 +- 遇到文档相关,必须遵守 `wms-doc-agent` 的“先核对代码与测试,再更新文档”流程 + +## 输出要求 + +- 所有回复建议以 `[Dispatch]` 开头 +- 先说明**将分派给谁**,再给简短原因 +- 如果是多领域问题,给出**拆分后的执行顺序** +- 最后输出汇总结论和下一步建议 + +## 建议提问方式 + +```text +请使用 wms-dispatcher-agent 帮我: +1) 判断这个问题属于数据库、Redis、发布、开发、测试还是文档问题 +2) 分派给正确的 agent +3) 汇总处理结果与下一步建议 +``` + +## 结论 + +`wms-dispatcher-agent` 用于 WMS 场景下的任务分诊与委派;当用户不确定该找哪个 agent,或问题跨多个领域时,应优先交给本 Agent。 \ No newline at end of file diff --git a/AI_TOOLBOX.md b/AI_TOOLBOX.md index 755553e..b7d7dfd 100644 --- a/AI_TOOLBOX.md +++ b/AI_TOOLBOX.md @@ -1,15 +1,34 @@ # AI 工具箱(WMS) + ## 🤖 AI阅读优先级 -1. **必读**:第2节(数据库)、第4节(Redis)- 最常用 -2. **重要**:第3节(提问模板)、第6节(安全约束)、第14节(where规范) -3. **按需**:第10节(远程发布)、第15节(权限映射)、第16节(消息通知) -4. **红线**:10.4(SSH禁止读取)、6(SQL安全) +1. **必读**:第2节(数据库 agent 入口)、第4节(Redis agent 入口)、第7节(开发 agent 入口)、第8节(文档 agent 入口)、第9节(测试 agent 入口)- 最常用 +2. **重要**:第3节(提问模板)、第6节(安全约束)、第10节(发布 agent 入口) +3. **按需**:第11节(开发细节移交说明)、第16节(消息通知) +4. **红线**:10(发布必须走 agent)、6(SQL安全) + + +## Agent配置文件位置 +| Agent名称 | 配置文件路径 | +|-----------|--------------| +| wms-db-agent | `.github/agents/数据库.agent.md` | +| wms-redis-agent | `.github/agents/缓存.agent.md` | +| wms-deploy-agent | `.github/agents/发布.agent.md` | +| wms-dev-agent | `.github/agents/开发.agent.md` | +| wms-test-agent | `.github/agents/测试.agent.md` | +| wms-doc-agent | `.github/agents/文档.agent.md` | +| wms-dispatcher-agent | `.github/agents/调度.agent.md` | + ## 快速响应规则 -- 用户要求查数据 → 直接执行 script/db-query.ps1 -- 用户要求改缓存 → 先用redis-cache.ps1读,再改 -- 用户要求发布 → 只提示命令,不读SSH配置 +- 用户要求查数据库/查数据/写 SQL → **必须使用 `wms-db-agent`** +- 用户要求查缓存/改缓存/Redis 排障 → **必须使用 `wms-redis-agent`** +- 用户要求发布/回退/查线上版本/做冒烟 → **必须使用 `wms-deploy-agent`** +- 用户要求改代码/修 bug/定位 method → **必须使用 `wms-dev-agent`** +- 用户要求写测试/补回归/跑接口验证/TDD/验证修复 → **必须使用 `wms-test-agent`** +- 用户要求补文档/同步 `methods/*.json` / 更新 `docs/*.md` / README → **必须使用 `wms-doc-agent`** +- 用户不确定该找哪个 agent,或问题横跨多个领域 → **必须使用 `wms-dispatcher-agent`** +- **全局安全红线(适用于所有 AI)**:**禁止删改处理非测试仓库的数据,包括数据库和缓存**;对非测试仓库默认只读;无法确认是否测试仓时,默认按非测试仓处理并拒绝写操作 - 所有回复结尾加"喵~" ## 1. 适用范围 @@ -18,703 +37,225 @@ - 主要用途:本地调试、数据库取数、问题定位 - 默认环境:PowerShell + Node.js -## 2. 数据库调试脚本 +## 2. 数据库能力移交规则 -临时文件规则(强制): -- 所有临时产物统一生成到 `temp/` 目录。 -- `temp/` 目录不提交到 git。 +数据库相关能力文档已统一移交给 `wms-db-agent`。 -项目已提供数据库查询脚本:`script/db-query.ps1` +适用场景: +- 查数据库 / 查数据 / 查表 +- 编写或审查 SQL +- 排查接口与数据库数据不一致 +- 核对 `wms` / `ye4s` client 路由 +- 输出字段含义、异常数据判断、索引建议 -脚本能力: -- 自动读取 `config/config.local.js` 中的 `config.mysql.clients.` 配置 -- 支持通过 `-DbClient` 显式切换 mysql client(如 `wms`、`ye4s`),默认 `wms` -- 执行传入 SQL 并返回 JSON -- 可选表格输出,便于命令行快速查看 - -### 2.1 基本用法 - -```powershell -powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -Query "SELECT 1 AS ok" -``` - -### 2.2 常用示例 - -```powershell -# 查询最近 10 条账号 -powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -Query "SELECT * FROM account ORDER BY id DESC LIMIT 10" - -# 表格输出 -powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -Query "SELECT id, name FROM store LIMIT 20" -AsTable - -# 指定 mysql client(默认是 wms) -powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -DbClient wms -Query "SHOW TABLES" - -# 切换到 ye4s client -powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -DbClient ye4s -Query "SHOW TABLES" - -# 快速确认当前连接到哪个库/账号 -powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -Query "SELECT DATABASE() AS db, USER() AS loginUser" -powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -DbClient ye4s -Query "SELECT DATABASE() AS db, USER() AS loginUser" -``` - -### 2.3 参数说明 - -- `-Query`:必填,SQL 语句 -- `-DbClient`:可选,MySQL 客户端名(例如 `wms`、`ye4s`),默认 `wms` -- `-ConfigPath`:可选,配置文件路径,默认 `.\config\config.local.js`(相对于项目根目录) -- `-AsTable`:可选,按表格输出结果 - -### 2.4 返回结果说明 - -默认输出 JSON,结构如下: - -```json -{ - "client": "wms", - "rowCount": 1, - "rows": [ - { - "ok": 1 - } - ] -} -``` - -### 2.5 区分 wms 与 ye4s(快速自检) - -- 步骤 1:不传 `-DbClient` 执行一次 `SELECT DATABASE() AS db, USER() AS loginUser` -- 步骤 2:传 `-DbClient ye4s` 再执行同一条 SQL -- 期望结果: - - 默认执行返回 `client = wms` 且 `db = wms` - - 指定 `ye4s` 返回 `client = ye4s` 且 `db = ye4s` - -说明:脚本会从 `config.mysql.clients.` 读取连接参数,返回体中的 `client` 字段可直接用于确认当前路由。 +执行要求(强制): +- **涉及数据库的任何问题,必须使用 `wms-db-agent`** +- 默认 agent 不再在本文件重复维护数据库命令细节 +- 具体命令、示例、输出格式、安全约束统一见:`.github/agents/数据库.agent.md` ## 3. AI 协助时建议使用的提问模板 -### 3.1 只读查询(推荐) +### 3.1 数据库类请求(强制走 Agent) ```text -请在项目根目录执行 script/db-query.ps1,查询 SQL: -SELECT * FROM account LIMIT 20; -并把结果按表格给我,同时解释关键字段含义。 +请使用 wms-db-agent 帮我: +1) 定位相关 controller / service / model +2) 生成并执行只读 SQL +3) 输出结果、字段解释和结论 ``` -### 3.2 先分析再查询 +### 3.2 Redis 类请求(强制走 Agent) ```text -请先阅读 app/model 下与 store 相关的模型,再使用 script/db-query.ps1 查询最近 50 条门店数据, -最后输出:1) 字段映射说明 2) 异常数据判断规则 3) 建议补充索引。 +请使用 wms-redis-agent 帮我: +1) 找到相关 key 或 pattern +2) 读取当前值、TTL、exists 状态 +3) 如需修改,先展示变更前后对比并回读确认 ``` -### 3.3 联合排障 +### 3.3 开发类请求(强制走 Dev Agent) ```text -请帮我排查某接口返回为空: -1) 找到对应 controller 和 service -2) 给出需要执行的 SQL -3) 使用 script/db-query.ps1 验证每一步 -4) 输出最终根因和修复建议 +请使用 wms-dev-agent 帮我: +1) 定位这个 method / controller / service 的实现链路 +2) 修复问题并说明最小代码改动方案 +3) 给出验证结果与后续开发建议 ``` -## 4. Redis 缓存调试脚本 - -项目已提供 Redis 调试脚本:`script/redis-cache.ps1` - -脚本能力: -- 自动读取 `config/config.local.js`(可切换 `-ConfigPath`)中的 `config.redis.clients.` 配置连接 Redis -- 支持缓存读取与修改:`get/set/del/exists/ttl/expire/keys/hget/hset/hdel/hgetall/incr/decr` -- 可选表格输出(`-AsTable`) - -### 4.1 基本用法 - -```powershell -powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action get -RedisClient cache -Key "system" -``` - -### 4.2 常用示例 - -```powershell -# 列出 key(使用 SCAN,不直接 KEYS 阻塞) -powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action keys -RedisClient cache -Pattern "user:*" -AsTable - -# 读取/写入字符串缓存 -powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action get -RedisClient cache -Key "system" -powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action set -RedisClient cache -Key "system" -Value "{\"ok\":1}" -ExpireSeconds 600 - -# 删除缓存 -powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action del -RedisClient cache -Key "system" - -# Hash 结构读写 -powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action hgetall -RedisClient cache -Key "session:123" -AsTable -powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action hset -RedisClient cache -Key "session:123" -Field "status" -Value "active" - -# 自增/自减计数器 -powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action incr -RedisClient cache -Key "counter:order" -powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action decr -RedisClient cache -Key "counter:order" -Value 2 -``` - -### 4.3 参数说明 - -- `-Action`:必填,操作类型(`get/set/del/exists/ttl/expire/keys/hget/hset/hdel/hgetall/incr/decr`) -- `-RedisClient`:可选,Redis 客户端名,默认 `cache` -- `-Key`:按操作需要传入 -- `-Value`:`set/hset/incr/decr` 等操作使用 -- `-Field`:`hget/hset/hdel` 必填 -- `-ExpireSeconds`:`set`(可选)和 `expire`(必填) -- `-Pattern`:`keys` 操作匹配模式,默认 `*` -- `-ConfigPath`:可选,默认 `.\config\config.local.js` -- `-AsTable`:可选,表格输出 - -### 4.4 AI 调用模板(缓存读改) +### 3.4 测试类请求(强制走 Test Agent) ```text -请在项目根目录执行 script/redis-cache.ps1: -1) 用 Action=keys, Pattern="user:*" 列出目标缓存键 -2) 读取 key=xxx 的当前值(Action=get) -3) 按我提供的新值执行 Action=set 并设置过期时间 600 秒 -4) 回读一次确认变更生效,并输出变更前后对比 +请使用 wms-test-agent 帮我: +1) 先复现问题并补一个失败用例 +2) 按 TDD 跑回归或接口验证 +3) 输出 passing 数量、失败数和修复验证结论 ``` +### 3.5 文档类请求(强制走 Doc Agent) + +```text +请使用 wms-doc-agent 帮我: +1) 根据代码现状整理接口或业务文档 +2) 同步 methods/*.json / docs/*.md / README +3) 校验文档与实现一致 +``` + +### 3.6 混合任务 / 不确定归属(强制走 Dispatcher) + +```text +请使用 wms-dispatcher-agent 帮我: +1) 判断这个问题属于数据库、Redis、发布、开发、测试还是文档问题 +2) 分派给正确的 agent +3) 汇总处理结果与下一步建议 +``` + +## 4. Redis 能力移交规则 + +Redis 相关能力文档已统一移交给 `wms-redis-agent`。 + +适用场景: +- 查 Redis key / pattern / TTL / exists +- 读取或修改缓存值 +- 排查 session、登录态、缓存不一致问题 +- 核对某接口是否命中缓存或缓存值异常 + +执行要求(强制): +- **涉及 Redis / 缓存的任何问题,必须使用 `wms-redis-agent`** +- 默认 agent 不再在本文件重复维护 Redis 命令细节 +- 具体命令、示例、输出格式、安全约束统一见:`.github/agents/缓存.agent.md` + ## 5. 常见问题 -- 报错 `Cannot find module 'mysql2/promise'` - - 先执行 `npm install`,确认依赖完整 +- 数据库相关报错、SQL 问题、连接路由问题 + - 统一转给 `wms-db-agent` 处理 -- 报错 `Cannot find module 'ioredis'` - - 先执行 `npm install`,确认依赖完整 +- Redis 相关报错、key 排查、TTL 问题、缓存变更 + - 统一转给 `wms-redis-agent` 处理 -- 报错 `MySQL client "xxx" not found in config.mysql.clients` - - 检查 `config/config.local.js` 中 `config.mysql.clients` 是否包含对应 client +- 发布相关报错、预检失败、回退、版本查询、冒烟验证 + - 统一转给 `wms-deploy-agent` 处理 -- SQL 语法报错且定位到 `current_user` - - 避免使用 `current_user` 作为别名,建议改成 `loginUser` 等非保留字名称 +- 开发相关问题:代码修改、method 路由、权限联动 + - 统一转给 `wms-dev-agent` 处理 -- 报错 `Redis client "xxx" not found in config.redis.clients` - - 检查 `config/config.local.js` 中 `config.redis.clients` 是否包含对应 client +- 测试相关问题:写单元测试、补回归、接口验证、TDD、验证修复、审查 mock / 断言 + - 统一转给 `wms-test-agent` 处理 -- 报错连接失败(超时/拒绝访问) - - 检查数据库 IP、端口、用户名密码、网络白名单 +- 文档相关问题:API 文档、README、`methods/system.json`、`docs/*.md`、使用说明 + - 统一转给 `wms-doc-agent` 处理 -- 报错 Redis 连接失败(超时/认证失败) - - 检查 Redis host/port/password/db 与网络连通性 +- 不确定该用哪个 agent,或问题横跨数据库 / Redis / 发布 / 代码 / 测试 / 文档 + - 统一转给 `wms-dispatcher-agent` 处理 - PowerShell 执行策略限制 - 使用命令中的 `-ExecutionPolicy Bypass`(仅本次命令生效) ## 6. 安全约束 -- 默认只执行 SELECT/SHOW 等只读 SQL -- 执行 UPDATE/DELETE 前必须先让 AI 生成影响范围确认 SQL(COUNT + WHERE 条件) +- **全局安全红线(适用于所有 AI)**:禁止删改处理非测试仓库的数据,包括数据库和缓存;对非测试仓库默认只读;无法确认是否测试仓时,默认按非测试仓处理并拒绝 `UPDATE` / `DELETE` / `INSERT`、`set` / `del` / `hset` / `hdel` / `incr` / `decr` / `expire` 等写操作 +- 数据库相关操作必须使用 `wms-db-agent`,并按该 agent 内的只读/确认流程执行 +- Redis 相关操作必须使用 `wms-redis-agent`,并按该 agent 内的先读后改/回读确认流程执行 +- 发布相关操作必须使用 `wms-deploy-agent`,并坚持仅走 `npm run` 固定入口;禁止读取 `config/deploy.config.local.cjs` +- 开发相关操作必须使用 `wms-dev-agent`,并坚持“先定位、后修改、再验证”的流程 +- 测试相关操作必须使用 `wms-test-agent`,并坚持“先写失败用例、再修复、后跑相关测试并报告 passing 数量”;禁止只测 mock 或给生产代码加 test-only 方法 +- 文档相关操作必须使用 `wms-doc-agent`,并坚持“先核对代码与测试,再更新文档;禁止写入敏感配置”的流程 - 涉及生产数据时,优先在测试环境验证 -- Redis 写操作(`set/del/hset/hdel/incr/decr/expire`)前,先执行一次读取并确认影响 key 范围 -## 7. 接口入口与 Method 指向 - -- 入口风格: - - `/qimen`:奇门开发接口(POST) - - `/system`:Web 端与 PDA 端统一接口(POST) - -- 外部请求示例: - - `http://127.0.0.1:6060/system?method=print.getComputerPrinter&v=1.0×tamp=1773386721` - -- Method 指向说明文档: - - 见 `AI_METHOD_ROUTING.md` - - 文档记录了 method 到 `app/service/systemMethods`、`app/service/qimenMethods` 的映射规则与示例。 - -## 8. methods 目录地图 - -目录:`methods/` - -- `methods/system.json` - - 作用:维护 `/system`(及 system 风格 method)的接口说明。 - - 覆盖内容:公共请求头、method 分组、params、response、errors。 - -- `methods/qimen.json` - - 作用:维护 `/qimen` 接口说明。 - - 覆盖内容:奇门 method、请求格式、响应格式、错误码。 - -建议将 `methods/*.json` 视为“接口文档单一事实来源(SSOT)”。 - -## 9. 接口变更联动工作流(强制) - -当出现以下任一变更时,必须同步更新 `methods` 目录下对应 JSON: - -1. 新增接口(新增 method) -2. 修改接口入参(新增/删除/重命名/必填变化) -3. 修改公共请求头(如 `platform`、`project`、`Authorization`) -4. 修改响应结构或错误码 - -执行步骤: - -1. 先改代码(controller/service/model) -2. 更新对应文档文件: - - system 入口改 `methods/system.json` - - qimen 入口改 `methods/qimen.json` -3. 若 system 入参有变化,执行参数结构化脚本刷新: - -```powershell -node .\script\tmp-struct-system-params.cjs -``` - -4. 人工补充自动脚本无法推断的信息: - - `description` - - `response` - - `errors` - - 特殊枚举值与业务约束 -5. 提交前自检: - - method 名称与代码一致 - - params 的 `name/type/required/source` 完整 - - 公共头部声明与实际鉴权逻辑一致 - -## 10. 远程发布与回退工具 - -发布配置文件: - -- 模板:`config/deploy.config.example.cjs` -- 本地真实配置:`config/deploy.config.local.cjs` - -说明: - -- 生产目录固定为 `/www/wwwroot/qimen` -- `config/deploy.config.local.cjs` 已加入 git ignore,避免 SSH 配置误提交 -- 发布前会自动备份远端当前目录到 `/www/wwwroot/qimen/.deploy/backups/` -- 回退默认使用最近一次发布前备份 -- 发布包按 Egg.js 最小运行集自动裁剪(默认 `app.js`、`app/**`、`methods/**`、`native/addons/**`、`package*.json`) -- 发布与回退均保留远端 `config/`,不做覆盖 -- 发布与回退的停服务逻辑仅匹配当前 `deployRoot` 对应的 Egg 进程,不再用全局 `egg-scripts stop` 扫整机 - -### 10.1 固定命令入口(仅 npm script) - -执行要求: - -- 远程发布与回退只允许通过 `npm run` 执行。 -- 禁止直接运行 `node ./script/deploy-remote.cjs ...` 与 `node ./script/rollback-remote.cjs ...`。 -- `npm stop` 已改为仅停止当前目录对应的 Egg 进程,不再直接调用全局 `egg-scripts stop`。 - -标准格式: - -```powershell -# 启用仓库级 pre-commit 保护 -npm run setup:hooks - -# 只读预检(不改远端文件) -npm run deploy:precheck - -# 查询当前线上版本号 -npm run deploy:version - -# 查询最近 20 次线上版本历史 -npm run deploy:version:history - -# 查看远端 state 与备份清单 -npm run deploy:inspect - -# 对关键路由做最小连通冒烟 -npm run deploy:smoke - -# 组合执行 inspect + smoke -npm run deploy:verify - -# 按文件名清理远端失败备份 -npm run deploy:cleanup-backups -- backup-20260324202526.tar.gz backup-20260324204750.tar.gz - -# 调用 internal gateway 做 method 连通探针 -npm run deploy:gateway-probe -- releaseProbe.ping "{}" - -# 手动记录一次本地包版本快照 -npm run version:record - -# 查询本地版本历史 -npm run version:history - -# 检查暂存区是否包含禁止提交文件 -npm run guard:git - -# 发布生产环境 -npm run deploy:prod - -# 发布生产环境(短命令别名) -npm run deploy - -# 回退到最近一次备份 -npm run rollback:prod - -# 回退到最近一次备份(短命令别名) -npm run rollback - -# 指定备份包回退 -npm run rollback:prod -- --backup=backup-20260324123045.tar.gz -``` - -### 10.2 SSH 配置字段 - -- `host`:生产服务器 IP 或域名 -- `port`:SSH 端口,默认 `22` -- `username`:SSH 登录用户 -- `privateKeyPath`:本机私钥路径 -- `deployRoot`:固定为 `/www/wwwroot/qimen` -- `sharedDirs`:发布时保留目录,默认 `logs/run/temp` -- `postDeployCommands`:发布后执行命令;发布链路会强制确保包含 `npm install --production`,并自动剥离其中的通用 stop 命令,改为按当前部署目录定点停进程 - -最小发布相关可选字段: - -- `deployIncludePaths`:最小发布白名单路径(不填则使用默认最小集) -- `deployExcludePaths`:发布排除路径(默认包含 `config/**`) -- `preserveDirs`:远端覆盖时额外保留目录(默认包含 `config`) - -### 10.5 线上版本号规则与查询 - -- 版本号自动生成时机:每次执行 `npm run deploy:prod`。 -- 版本号格式:`v{package.version}-{yyyyMMddHHmmss}-{gitShortCommit}`。 -- 远端保存位置: - - 当前版本:`/www/wwwroot/qimen/.deploy/state/current-release.json` - - 历史版本:`/www/wwwroot/qimen/.deploy/state/release-history.jsonl` -- 查询命令(固定 npm script): - - 当前版本:`npm run deploy:version` - - 历史版本:`npm run deploy:version:history` - -### 10.6 本地版本管理目录(回退辅助) - -- 目录:`versioning/` -- 记录目标:每次更新的包版本号、提交号、分支、时间。 -- 自动记录:每次 `npm run deploy:prod` 成功后自动写入本地记录。 -- 手动记录:`npm run version:record` -- 本地历史查询:`npm run version:history` -- 文件: - - `versioning/package-version-current.json` - - `versioning/package-version-history.jsonl` -- git 规则:`versioning/` 的记录文件默认不提交,仅保留目录占位。 - -### 10.3 安全约束 - -- pre-commit 会阻止以下内容进入 git: - - `config/config.local.js` - - `config/deploy.config.local.cjs` - - `database/config.json` - - `temp/`、`logs/`、`run/` - - `.env*`、`.pem`、`.key` -- 真实 SSH 信息只写入本地配置文件,不写入 README、脚本或示例文件 -- 在补齐 SSH 配置前,不执行发布/回退测试 - -### 10.4 AI 安全红线(强制) - -- 明文规则:AI 禁止读取 SSH 本地配置文件 `config/deploy.config.local.cjs`。 -- AI 禁止通过任何方式展示、提取、复述该文件中的 `host`、`username`、`privateKeyPath` 等敏感内容。 -- AI 禁止把 SSH 配置写入文档、日志、日报、提交信息或任意可提交文件。 -- 如需发布/回退协助,AI 仅可提示用户“自行填写或核对该文件”,不可主动读取文件内容。 - -执行规则:接口代码与 `methods/*.json` 不一致时,以“必须补齐文档”为完成标准。 - -## 11. App 能力地图(优先定位) - -能力入口文件: - -- `app.js` -- `app/extend/application.js` - -### 11.1 启动与初始化能力(app.js) - -- 设置应用根路径:`global.APP_ROOT`、`app.appRoot` -- 启动前初始化动态工厂: - - `OrderDeliveryFactory` - - `OrderItemsFactory` -- 启动时能力自检: - - `app.setCacheAsync` / `app.getCacheAsync` - - `app.Message` -- 全局日期格式化扩展:`Date.prototype.format('YYYY-MM-DD HH:mm:ss')` - -### 11.2 Application 扩展能力(app/extend/application.js) - -- 业务字典访问: - - `businessDict` - - `getBusinessTypeName(code)` - - `getOperationCodeName(code)` - - `getPlatformName(code)` - - `getExternalLogTypeName(type)` -- 外部 SOAP 调用: - - `wsdl(methodName, args)` -- Redis 缓存(cache client): - - `setCacheAsync(cacheKey, data, expireSeconds = 300)` - - `getCacheAsync(cacheKey)` -- Message 扩展: - - `Message` getter(返回 `MessageClass`) - -### 11.3 AI 调试优先顺序 - -- 遇到“方法不存在/映射异常”优先检查 `app/extend/application.js` 是否包含对应能力。 -- 遇到“动态分表模型不可用”优先检查 `app.js` 的工厂初始化是否执行成功。 -- 遇到“缓存读写异常”优先检查 Redis client `cache` 配置及 `setCacheAsync/getCacheAsync` 调用链。 - - -## 12. Web 用户信息与切换角色测试(已验证) - -目标: -- 使用 `/system` 入口验证 Web 端用户信息获取与角色切换链路。 -- 固定请求头:`platform=web`、`project=all`。 -- 将接口返回暂存到 `test/.runtime/` 便于回放与比对。 - -测试文件: -- `test/app/controller/system.user.info.web.test.js` - - 调用 `user.info` - - 断言 `status=200`、`flag=success`、`code=200` - - 断言返回 `platform_code=web` - - 落盘:`test/.runtime/system_user_info_web_all.json` - -- `test/app/controller/system.user.changeRole.test.js` - - 先调用 `user.info` 读取当前角色与可切换角色 - - 调用 `user.changeRole`(`roleId` 取可用候选角色) - - 使用返回的新 token 再调 `user.info` 验证 `employees_id` 已切换 - - 落盘:`test/.runtime/system_user_change_role_web_all.json` - - 末尾自动切回原角色,降低对其他测试影响 - -一键执行: - -```powershell -npx egg-bin test test/app/controller/system.user.info.web.test.js test/app/controller/system.user.changeRole.test.js -``` - -本地验证结果: -- 2 passing - -建议排查顺序(当返回菜单/权限为空时): -1. 先查 `user.info` 返回中的 `employees_id`、`store_id`、`platform_code` -2. 确认请求头是否为 `platform=web`、`project=all` -3. 若仍为空,检查账号角色授权与当前激活角色是否存在 - -## 13. setting.account 接口说明(system) - -适用入口:`POST /system?method=setting.account.xxx` - -### 13.1 setting.account.list - -用途:查询当前主体下工号列表(默认只返回启用工号)。 - -入参(body): -- `status`(number,可选):状态筛选,默认 `1` -- `includeDisabled`(boolean,可选):`true` 时包含停用工号 - -返回(`data[]` 关键字段): -- `employee_id`:工号 ID -- `account_id`:账号 ID -- `store_id`:主体 ID -- `real_name`:工号姓名 -- `status`:工号状态(`1` 启用 / `0` 停用) -- `username` / `phone` / `email`:账号基础信息 -- `avatar_file_id` / `avatar_url`:头像信息 - -### 13.2 setting.account.add - -用途:新增工号;手机号存在则复用账号,不存在则创建账号并绑定工号。 - -入参(body): -- `phone`(string,必填):11 位手机号 -- `real_name`(string,必填):工号姓名 -- `role_id`(number,可选):不传时继承当前操作人工号角色 -- `username`(string,可选):仅新建账号时生效 -- `password`(string,可选):仅新建账号时生效,默认 `111111` -- `email`(string,可选):仅新建账号时生效 - -返回(`data` 关键字段): -- `employee_id` / `account_id` / `role_id` -- `is_new_account`:是否本次新建账号 -- `phone` / `username` - -错误码: -- `400`:参数错误、手机号格式错误、保留名称限制 -- `409`:账号禁用、重复绑定、用户名冲突 - -### 13.3 setting.account.delete - -用途:停用工号绑定,不删除底层账号。 - -入参(body): -- `employee_id`(number,必填) - -返回(`data`): -- `employee_id` / `account_id` -- `status`:固定 `deleted` -- `already_deleted`(可选):原本已是停用状态 - -### 13.4 setting.account.update - -用途:更新工号姓名和/或头像引用。 - -入参(body): -- `employee_id`(number,必填) -- `real_name`(string,可选) -- `file_id`(number,可选):头像文件 ID - -约束:`real_name` 与 `file_id` 至少传一个。 - -返回(`data`): -- 更新后的工号完整信息(同 list 列表项结构) - -### 13.5 代码分层约定 - -- 对外 method 包装层:`app/service/systemMethods/setting/account.js` -- 业务实现层:`app/service/systems/setting/account.js` -- 约定:非暴露辅助函数与业务逻辑统一下沉到 `systems`,`systemMethods` 只保留出口包装。 - -## 14. where 参数统一规范(强制) - -适用范围:所有包含 `where` 筛选条件的 `/system` 接口。 - -### 14.1 标准结构 - -`where` 必须使用统一条件对象格式: - -```json -{ - "where": { - "item_code": { "operator": "like", "value": "SKU" }, - "status": { "operator": "eq", "value": "created" }, - "quantity": { "operator": "ge", "type": "number", "value": "10" }, - "create_at": { "operator": "between", "type": "date", "value": ["2026-03-01", "2026-03-31"] }, - "quickWhere": { "operator": "like", "type": "text", "value": "关键字" } - } -} -``` - -### 14.2 统一处理入口 - -- `where` 统一在 `app/service/main.js` 中处理:`prepareWhereContext(data, options)`。 -- 处理后上下文约定: - - `ctx.where`:标准化后的 where 条件对象(含 `operator/value/type`) - - `ctx.whereValue`:仅提取 value 的兼容对象(给旧逻辑渐进兼容) - - `ctx.whereParsed`:基于 `app/lib/query_condition_parser.js` 解析后的动态条件结构 - -### 14.3 实施规则 - -- 所有 method 层(`systemMethods`)收到 `where` 后,必须先调用 `prepareWhereContext`。 -- 所有 systems 层查询逻辑优先读取 `ctx.where` / `ctx.whereParsed`,不得重复定义另一套 where 规则。 -- 历史简写结构(如 `where: { status: 1 }`)允许输入,但会在 main 层自动标准化为条件对象。 - -### 14.4 回归覆盖建议 - -- 至少验证:空 where、eq、like、in、between、quickWhere。 -- 对日志中高频接口优先回归: - - `print.getList` - - `storage.entry.list` - - `stock.warehouse.list` - -## 15. system API 权限映射规则(wms_permission) - -适用范围:`/system` 入口,权限类型为 `type=api`。 - -### 15.1 映射规则 - -- `wms_permission.path` 作为 system method 的权限标识(例如:`setting.account.list`)。 -- 同步来源以 `methods/system.json` 为准:`isNeedAuth=true` 的 method 必须存在对应 `wms_permission(type=api,path=method)`。 -- 角色权限不再以 `wms_role_permission` 作为主存储,统一写入 `wms_role.permissions`。 -- `wms_role.permissions` 支持两种值: - - JSON 数组:如 `[1,2,3]` - - `"*"`:表示拥有所有权限 -- 新增 API 权限后,`role_id=2` 的授权应同步更新其 `permissions` 字段;若该字段为 `"*"` 则无需额外追加。 - -### 15.2 外部脚本(批量补齐) - -固定命令: - -```powershell -# 预览差异(不写库) -npm run permission:sync:system-api -- --dry-run - -# 执行补齐(写库) -npm run permission:sync:system-api -``` - -可选参数: - -- `--role-id=2`:绑定角色 ID(默认 `2`) -- `--db-client=wms`:数据库客户端名(默认 `wms`) -- `--config-path=./config/config.local.js`:配置文件路径 -- `--method-doc=./methods/system.json`:method 文档路径 - -### 15.3 运行时兜底(仅 debug) - -- 入口:`app/service/main.js` 的 `checkApiPermission`。 -- 逻辑:当用户权限列表不包含目标 method 时,若 `app.config.debug === true`,自动: - 1. 参考现有 `type=api` 权限行构建缺失权限行; - 2. 更新 `wms_role(id=2).permissions`,将新权限 ID 追加到 JSON 数组;若该字段为 `"*"` 则保持不变。 -- 生产建议:保持 `app.config.debug=false`,避免运行时自动写库。 - - ## 16 消息推送配置规则 - -- `wms_store.subject_config` 用于保存主体级通知配置。 -- 当前默认初始化字段:`max_notice_webhook_count = 5`。 -- 该字段表示“当前主体最多允许绑定的消息推送接口数量”。 -- 合法范围:`0 ~ 5` 的整数。 -- 创建或更新主体时,如携带 `subject_config.max_notice_webhook_count`,必须通过合法性校验;超出范围或类型错误视为非法。 -- WebHook 分发侧也必须遵守该上限,超过上限的回调接口不应继续发送。 - -## 16.1 统一 WebHook 推送能力(notice) - -- 能力总览文档:`docs/notification-webhook-capability.md` -- 事件 API 文档:`docs/notification-event-api.md` -- 统一入口:`ctx.service.systems.notice.send(options)` -- 代码位置:`app/service/systems/notice/index.js` -- 固定发送方式:`POST + application/json` -- `hook_type` 支持: - - `customize`:当前默认统一推送流程,按标准 JSON 透传 - - `wecom`:企业微信 WebHook 直发,自动转为企微机器人消息体 -- 必传参数:`warehouseId` -- 可空参数:`storeId / ownerId` -- 货主信息补充:若传 `storeId` / `ownerId`,会优先查缓存键 `warehouse:xxxstore:xxx:info`(TTL = `600`),未命中再查: - - `wms_store.business_license` - - `wms_store_warehouse.store_remask` -- `events` 支持以下订阅写法: - - `all` / `*`:接收全部已注册事件 - - `receiving_completed`:当前唯一已注册的业务事件(收货完成) -- 事件命名规则:仅允许小写字母、数字、下划线,且首字符不能为数字;**禁止使用 `.`** -- 推送事件注册:需先在 `app/model/notification_webhook.js` 中注册,未注册事件不允许直接发送 -- 传参伪代码: - -```js -await ctx.service.systems.notice.send({ - warehouseId: 100000, - storeId: 200000, // 可选,也可传 ownerId - businessName: 'receiving', - event: 'receiving_completed', - messageType: 'text', // text / image / file - title: '收货单已完成', - content: '收货单 RCV202604050001 已完成', - // image / file 时必传 - url: 'https://cdn.example.com/report.xlsx', - fileName: '收货完成_RCV202604050001.xlsx', - mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - businessId: 12345, - subject: { - id: 100000, - type: 'warehouse', - name: '广州仓', - }, - sender: { - id: 10001, - name: '张三', - }, - metadata: { - receivingId: 12345, - receivingNumber: 'RCV202604050001', - }, -}); -``` -- WebHook 命中规则: - 1. 先查仓库 `warehouseId` 绑定的接口 - 2. 若 `storeId / ownerId` 非空,再查货主绑定的接口并一并发送 - 3. 最终按 `subject_config.max_notice_webhook_count` 限制最大推送数量 -- 推送事件底线: - 1. 业务 service 中只负责调用发送入口,不需要各自重复写重试和异常兜底 - 2. 统一入口会处理失败重试与异常处理:按 `3秒 -> 6秒 -> 12秒` 阶梯重试共 3 次 - 3. 若最终仍失败,写入 `wms_notification_send_log` 供后续排查与补偿 -### 16.2 WebHook 可信结论 - -- 返回值判定约定: - - 返回 `1` = **成功** - - 返回 `0` = **失败** -- 可信结论: - - **地址为外部配置,需要检查返回结果** - - **发送数据只使用POST 方式** - - 若 `notice.send()` 的实际推送触发远端 无法解析的文本视为推送失败 +## 7. 开发能力移交规则 + +通用开发能力文档已统一移交给 `wms-dev-agent`。 + +适用场景: +- 改代码 / 修 bug / 重构 / 性能优化 +- 定位 `/system` / `/qimen` method 映射关系 +- 排查 `where` 规则、权限映射、分层职责问题 + +执行要求(强制): +- **涉及代码开发的任何问题,必须使用 `wms-dev-agent`** +- 默认 agent 不再在本文件重复维护开发细节 +- 如诉求重点是测试设计、补回归、接口验证、TDD 或验证修复,转给 `wms-test-agent` +- 如需同步 API 文档、`methods/*.json`、`docs/*.md`,转给 `wms-doc-agent` +- 具体目录地图、联动规则统一见:`.github/agents/开发.agent.md` + +## 8. 文档能力移交规则 + +文档相关能力文档已统一移交给 `wms-doc-agent`。 + +适用场景: +- 补 API 文档 / 接口说明 / 错误码 / 示例请求 +- 同步 `methods/system.json` / `methods/qimen.json` +- 更新 `docs/*.md`、`README.md`、`AI_TOOLBOX.md` +- 整理 method 映射说明、接入文档、使用手册 + +执行要求(强制): +- **涉及文档编写或同步的任何问题,必须使用 `wms-doc-agent`** +- 文档必须以代码实现、测试结果和现有 JSON 文档为准,不得凭空编写 +- system 参数变化可执行:`node .\script\tmp-struct-system-params.cjs` +- 具体工作流统一见:`.github/agents/文档.agent.md` + +## 9. 测试能力移交规则 + +测试相关能力文档已统一移交给 `wms-test-agent`。 + +适用场景: +- 写测试 / 单元测试 / 集成测试 / 补回归 +- 跑接口验证 / 复现 bug / 验证修复 +- 按 TDD 流程推进开发修复 +- 审查 mock / 断言规范与覆盖率范围 + +执行要求(强制): +- **涉及测试设计、回归验证、接口验证、TDD 的任何问题,必须使用 `wms-test-agent`** +- 必须坚持先写失败用例再修复,不允许只测 mock 行为 +- 不得为生产代码添加 test-only 方法或分支 +- 改动后必须跑相关测试并报告 passing 数量 +- 具体命令与测试规范统一见:`.github/agents/测试.agent.md` + +## 10. 发布能力移交规则 + +发布相关能力文档已统一移交给 `wms-deploy-agent`。 + +适用场景: +- 发布生产 / 上线 / deploy +- 回退 / rollback / 指定备份回退 +- 查询线上版本、版本历史 +- 做预检、inspect、smoke、verify、gateway probe +- 排查发布链路、备份、版本记录问题 + +执行要求(强制): +- **涉及发布 / 回退 / 线上验证的任何问题,必须使用 `wms-deploy-agent`** +- 固定入口只允许 `npm run ...`,禁止直接运行底层 `node ./script/deploy-remote.cjs ...` / `rollback-remote.cjs ...` +- AI 禁止读取 `config/deploy.config.local.cjs` +- 具体命令、回退规则、版本管理、安全红线统一见:`.github/agents/发布.agent.md` + +## 11. 开发细节移交说明 + +以下开发细节文档已统一移交给 `wms-dev-agent`: + +- App 能力地图(`app.js`、`app/extend/application.js`) +- Web 用户信息与角色切换测试链路 +- `setting.account` 接口分层约定 +- `where` 参数统一规范 +- `system API` 权限映射规则 + +执行要求(强制): +- **涉及代码开发、接口联动的任何问题,必须使用 `wms-dev-agent`** +- 如需测试设计、补回归、接口验证或验证修复,转给 `wms-test-agent` +- 若涉及文档更新,转给 `wms-doc-agent` +- 具体定位地图、命令与工作流统一见:`.github/agents/开发.agent.md` + +## 16. 通知能力路由(notice / WebHook / 事件注册) + +- 详细能力说明统一沉淀在: + - `docs/notification-webhook-capability.md` + - `docs/notification-event-api.md` +- 工具箱只保留入口与分工,不再重复维护 notice 的字段、payload、重试和示例细节。 +- 若其他 agent 或开发任务遇到“**新功能需要通知**”,按以下路由处理: + 1. **代码接入** → 使用 `wms-dev-agent`:在业务 service 中接入 `ctx.service.systems.notice.send(options)`,并完成事件注册与最小回归验证 + 2. **文档同步** → 使用 `wms-doc-agent`:同步通知能力文档、事件文档及必要的接口说明 +- 当前统一入口:`ctx.service.systems.notice.send(options)` +- 当前代码位置:`app/service/systems/notice/index.js` +- 配置底线:`wms_store.subject_config.max_notice_webhook_count` + - 默认值:`5` + - 合法范围:`0 ~ 5` + - 创建/更新主体与 WebHook 分发时都必须遵守该上限 diff --git a/app.js b/app.js index 353440d..a96fa2b 100644 --- a/app.js +++ b/app.js @@ -5,7 +5,7 @@ const path = require('path'); module.exports = app => { // 设置全局应用根目录 global.APP_ROOT = path.resolve(__dirname, './'); - app.appRoot = APP_ROOT; + app.appRoot = global.APP_ROOT; app.logger.info('✅ Application 扩展能力已加载'); // 初始化工厂 app.beforeStart(async () => { @@ -35,21 +35,4 @@ module.exports = app => { app.logger.info('✅ l类型' + typeof app.Message); }); - // 扩展 Date 原型 - Date.prototype.format = function(formatStr = 'YYYY-MM-DD HH:mm:ss') { - const year = this.getFullYear(); - const month = String(this.getMonth() + 1).padStart(2, '0'); - const day = String(this.getDate()).padStart(2, '0'); - const hours = String(this.getHours()).padStart(2, '0'); - const minutes = String(this.getMinutes()).padStart(2, '0'); - const seconds = String(this.getSeconds()).padStart(2, '0'); - - return formatStr - .replace('YYYY', year) - .replace('MM', month) - .replace('DD', day) - .replace('HH', hours) - .replace('mm', minutes) - .replace('ss', seconds); - }; }; diff --git a/app/controller/docs.js b/app/controller/docs.js index db09e9f..d6425ea 100644 --- a/app/controller/docs.js +++ b/app/controller/docs.js @@ -24,6 +24,18 @@ function slugify(value) { .replace(/(^-|-$)/g, ''); } +function isValidDocName(docName) { + return /^[a-zA-Z0-9_-]+$/.test(docName || ''); +} + +function getDocFilePath(app, docName) { + return path.join(app.baseDir, 'methods', `${docName}.json`); +} + +function getDocChangesFilePath(app, docName) { + return path.join(app.baseDir, 'methods', 'changes', `${docName}.json`); +} + function normalizeGroups(docData) { if (docData && docData.methods && Array.isArray(docData.methods.groups)) { return docData.methods.groups.map(group => ({ @@ -194,6 +206,8 @@ function renderHtmlPage({ const methodsCount = groups.reduce((sum, group) => sum + toArray(group.list).length, 0); const globalHeaders = toArray(docData.headers); const globalHeadersControls = renderGlobalHeadersControls(globalHeaders); + const rawUrl = `/api/docs/${encodeURIComponent(docName)}/raw`; + const changesUrl = `/api/docs/${encodeURIComponent(docName)}/changes`; const navHtml = docs.map(name => { const activeClass = name === docName ? 'active' : ''; return `${escapeHtml(name)}`; @@ -292,7 +306,8 @@ function renderHtmlPage({ border-radius: 8px; font-size: 13px; } - .global-auth button { + .global-auth button, + .doc-tools button { border: 1px solid #9fc2eb; background: #fff; color: #174c94; @@ -300,6 +315,20 @@ function renderHtmlPage({ padding: 8px 12px; cursor: pointer; } + .doc-tools { + margin-top: 14px; + border: 1px solid #d7e4f7; + background: #fcfdff; + border-radius: 10px; + padding: 12px; + } + .doc-tools h3 { margin: 0 0 8px; font-size: 15px; } + .doc-tools-actions { + display: flex; + gap: 8px; + flex-wrap: wrap; + margin-bottom: 8px; + } .global-headers-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); @@ -544,7 +573,8 @@ function renderHtmlPage({

全局 Authorization

@@ -557,6 +587,16 @@ function renderHtmlPage({ ${globalHeadersControls}

来自 JSON 的 headers 定义;带 * 的字段为必填,支持下拉 list 选择。

+
+

文档资源

+
+ 打开变更记录 + 打开原文 JSON + + +
+
点击上方按钮后,可直接预览当前文档的变更记录或原文 JSON。
+
@@ -587,6 +627,11 @@ function renderHtmlPage({ var searchStats = document.getElementById('searchStats'); var expandAllBtn = document.getElementById('expandAllBtn'); var collapseAllBtn = document.getElementById('collapseAllBtn'); + var previewChangesBtn = document.getElementById('previewChangesBtn'); + var previewRawBtn = document.getElementById('previewRawBtn'); + var resourcePreview = document.getElementById('docResourcePreview'); + var changesUrl = ${JSON.stringify(changesUrl)}; + var rawUrl = ${JSON.stringify(rawUrl)}; function nowTimestamp() { return Math.floor(Date.now() / 1000); @@ -600,6 +645,25 @@ function renderHtmlPage({ } } + async function previewDocResource(url, title) { + if (resourcePreview) { + resourcePreview.textContent = title + ' 加载中...'; + } + + try { + var response = await fetch(url); + var text = await response.text(); + var pretty = formatPretty(text); + if (resourcePreview) { + resourcePreview.textContent = title + ' (HTTP ' + response.status + ')' + pretty; + } + } catch (error) { + if (resourcePreview) { + resourcePreview.textContent = title + ' 加载失败: ' + error.message; + } + } + } + function buildDefaultQuery(card) { var moduleName = card.getAttribute('data-module') || ''; var methodName = card.getAttribute('data-method') || ''; @@ -774,6 +838,18 @@ function renderHtmlPage({ }); } + if (previewChangesBtn) { + previewChangesBtn.addEventListener('click', function() { + previewDocResource(changesUrl, '变更记录'); + }); + } + + if (previewRawBtn) { + previewRawBtn.addEventListener('click', function() { + previewDocResource(rawUrl, '原文 JSON'); + }); + } + document.addEventListener('click', async function(event) { var btn = event.target.closest('.send-btn'); if (!btn) return; @@ -890,13 +966,13 @@ class DocsController extends Controller { const { ctx } = this; const docName = ctx.params.docName; - if (!/^[a-zA-Z0-9_-]+$/.test(docName || '')) { + if (!isValidDocName(docName)) { ctx.status = 400; ctx.body = { code: 400, message: '无效文档名' }; return; } - const filePath = path.join(this.app.baseDir, 'methods', `${docName}.json`); + const filePath = getDocFilePath(this.app, docName); try { const content = await fs.readFile(filePath, 'utf8'); @@ -911,6 +987,38 @@ class DocsController extends Controller { } } + async changes() { + const { ctx } = this; + const docName = ctx.params.docName; + + if (!isValidDocName(docName)) { + ctx.status = 400; + ctx.body = { code: 400, message: '无效文档名' }; + return; + } + + const filePath = getDocChangesFilePath(this.app, docName); + + try { + const content = await fs.readFile(filePath, 'utf8'); + ctx.type = 'application/json; charset=utf-8'; + ctx.body = toArray(JSON.parse(content)); + } catch (error) { + if (error.code === 'ENOENT') { + ctx.type = 'application/json; charset=utf-8'; + ctx.body = []; + return; + } + + ctx.status = 500; + ctx.body = { + code: 500, + message: `读取变更记录失败: ${docName}`, + error: error.message, + }; + } + } + async getDocNames() { const docsDir = path.join(this.app.baseDir, 'methods'); const entries = await fs.readdir(docsDir, { withFileTypes: true }); @@ -924,13 +1032,13 @@ class DocsController extends Controller { async renderDoc(docName) { const { ctx, app } = this; - if (!/^[a-zA-Z0-9_-]+$/.test(docName || '')) { + if (!isValidDocName(docName)) { ctx.status = 400; ctx.body = { code: 400, message: '无效文档名' }; return; } - const filePath = path.join(app.baseDir, 'methods', `${docName}.json`); + const filePath = getDocFilePath(app, docName); try { const [ content, docs ] = await Promise.all([ diff --git a/app/controller/home.js b/app/controller/home.js index 021bbee..b33945b 100644 --- a/app/controller/home.js +++ b/app/controller/home.js @@ -96,7 +96,6 @@ class HomeController extends Controller { const xmlArray = await service.qimen.parseXmlToArray(xmlData); xmlArray.app_key = appkey; let warehouseCode = xmlArray.request.warehouseCode || ''; - const ownerCode = customerId; await service.qimen.saveQimenLogBody(xmlData); const erpName = await service.qimen.getErpName(appkey); @@ -110,7 +109,9 @@ class HomeController extends Controller { warehouseCode = xmlArray.request?.entryOrder?.warehouseCode || xmlArray.request?.deliveryOrder?.warehouseCode || ''; - } catch (e) { } + } catch (e) { + throw new Error('XML数据格式错误,无法提取warehouseCode'); + } } if (warehouseCode && customerId) { // 验证接口是否存在且启用 @@ -119,21 +120,19 @@ class HomeController extends Controller { const errorMsg = `奇门${erpName}客户编码${customerId}仓库编码${warehouseCode}未绑定到你的货主或未启用,请联系仓库绑定`; const response = this.errorResponse(errorMsg, 'xml'); await service.qimen.saveQimenLogResult(response); - ctx.body = response; ctx.type = 'application/xml'; return; } - if (api_info.contract_auth_status != 2) { + if (api_info.contract_auth_status !== 2) { const errorMsg = `货主与仓库签约状态异常,请到WMS核实签约状态${api_info.contract_auth_status}`; const response = this.errorResponse(errorMsg, 'xml'); await service.qimen.saveQimenLogResult(response); - ctx.body = response; ctx.type = 'application/xml'; return; } - if (api_info.warehouse_status == 0) { + if (api_info.warehouse_status === 0) { const errorMsg = '仓库状态异常,请联系仓库核实WMS状态'; const response = this.errorResponse(errorMsg, 'xml'); await service.qimen.saveQimenLogResult(response); @@ -403,12 +402,6 @@ class HomeController extends Controller { ctx.body = response; ctx.type = 'application/json'; } - } - async store() { - - } - async warehouse() { - } async system() { const { diff --git a/app/dict/businessDict.js b/app/dict/businessDict.js index 38e3fab..07837bf 100644 --- a/app/dict/businessDict.js +++ b/app/dict/businessDict.js @@ -21,6 +21,8 @@ module.exports = { LOCATION: { code: 'location', name: '库位管理' }, USER: { code: 'user', name: '用户管理' }, SYSTEM: { code: 'system', name: '系统管理' }, + ENTRY: { code: 'entry', name: '入库管理' }, + STORE: { code: 'store', name: '货主管理' }, }, /** @@ -103,6 +105,31 @@ module.exports = { UPDATE_IMAGES: '更新图片', UPDATE_BARCODE: '更新条码', BIND: '绑定', + + // 入库管理 + QUICK_PUTAWAY: '快捷入库', + + // 收货管理 + RECEIVING_CREATE: '创建收货单', + RECEIVING_COMPLETE: '完成收货', + RECEIVING_CANCEL: '作废收货单', + RECEIVING_BATCH_CANCEL: '批量作废收货单', + RECEIVING_BIND_STORE: '绑定货主', + RECEIVING_ADD_DETAIL: '新增收货明细', + RECEIVING_DELETE_DETAIL: '删除收货明细', + RECEIVING_BIND_PRODUCT: '绑定商品', + RECEIVING_UPDATE_DETAIL: '修改收货明细', + + // 货主管理 + STORE_CREATE: '创建货主', + STORE_CREATE_WAREHOUSE: '创建仓库', + STORE_SIGN: '签约货主', + STORE_RENAME: '修改签约备注', + STORE_UNBIND: '解绑签约', + STORE_SAVE_POLICY_CONFIG: '保存签约策略配置', + STORE_SAVE_API_CONFIG: '保存接口配置', + STORE_DELETE_API_CONFIG: '删除接口配置', + STORE_ADJUST_PRINT_QUANTITY: '调整面单余额', }, /** @@ -161,7 +188,7 @@ module.exports = { /** * 获取指定业务类型的操作编码 - * @param businessType + * @param {string} businessType 业务类型 */ getOperationCodesByBusinessType(businessType) { const prefix = businessType.toUpperCase() + '_'; @@ -178,8 +205,8 @@ module.exports = { /** * 验证操作编码是否属于指定业务类型 - * @param code - * @param businessType + * @param {string} code 操作编码 + * @param {string} businessType 业务类型 */ validateOperationCode(code, businessType) { if (!businessType) return true; diff --git a/app/extend/application.js b/app/extend/application.js index 9f2574f..e3c55da 100644 --- a/app/extend/application.js +++ b/app/extend/application.js @@ -1,11 +1,5 @@ -class MessageClass { - async action() { - - } -} const soap = require('soap'); const businessDict = require('../dict/businessDict'); -const MESSAGE_CLASS = Symbol('Application#Message'); module.exports = { get businessDict() { return businessDict; @@ -28,6 +22,23 @@ module.exports = { getExternalLogTypeName(type) { return this.businessDict.EXTERNAL_LOG_TYPE?.[type] || type; }, + formatDate(date, formatStr = 'YYYY-MM-DD HH:mm:ss') { + const targetDate = date instanceof Date ? date : new Date(date); + const year = targetDate.getFullYear(); + const month = String(targetDate.getMonth() + 1).padStart(2, '0'); + const day = String(targetDate.getDate()).padStart(2, '0'); + const hours = String(targetDate.getHours()).padStart(2, '0'); + const minutes = String(targetDate.getMinutes()).padStart(2, '0'); + const seconds = String(targetDate.getSeconds()).padStart(2, '0'); + + return formatStr + .replace('YYYY', year) + .replace('MM', month) + .replace('DD', day) + .replace('HH', hours) + .replace('mm', minutes) + .replace('ss', seconds); + }, async wsdl(methodName, args) { try { const wsdlUrl = 'http://ye4s.com/webservice/ws?wsdl'; @@ -75,11 +86,4 @@ module.exports = { return null; } }, - get Message() { - if (!this[MESSAGE_CLASS]) { - // 返回类本身,不是实例 - this[MESSAGE_CLASS] = MessageClass; - } - return this[MESSAGE_CLASS]; - }, }; diff --git a/app/lib/stop_current_egg.js b/app/lib/stop_current_egg.js index 64894d8..34f4216 100644 --- a/app/lib/stop_current_egg.js +++ b/app/lib/stop_current_egg.js @@ -121,7 +121,6 @@ function killPids(pids, signal) { async function main() { const processList = listNodeProcesses().filter(matchesCurrentApp); const masterPids = processList.filter(item => isMasterProcess(item.cmd)).map(item => item.pid); - const workerPids = processList.filter(item => isWorkerProcess(item.cmd)).map(item => item.pid); if (masterPids.length > 0) { console.log(`stopping current egg masters: ${masterPids.join(', ')}`); diff --git a/app/model/account.js b/app/model/account.js index 74846d6..eec7981 100644 --- a/app/model/account.js +++ b/app/model/account.js @@ -1,7 +1,7 @@ 'use strict'; module.exports = app => { - const { BIGINT, STRING, INTEGER, DATE, TINYINT, fn } = app.Sequelize; + const { BIGINT, STRING, DATE, TINYINT, fn } = app.Sequelize; const Account = app.model.define('account', { id: { @@ -131,7 +131,7 @@ module.exports = app => { }); // 关联关系 - Account.associate = function(models) { + Account.associate = function() { const { AccountStoreEmployee, AccountPlatformActive } = app.model; Account.hasMany(AccountStoreEmployee, { foreignKey: 'account_id', diff --git a/app/model/account_platform_active.js b/app/model/account_platform_active.js index c5b72e9..9142143 100644 --- a/app/model/account_platform_active.js +++ b/app/model/account_platform_active.js @@ -75,7 +75,7 @@ module.exports = app => { }); // 关联关系 - 注释掉或删除,统一在 app.js 中处理 - AccountPlatformActive.associate = function(models) { + AccountPlatformActive.associate = function() { const { Account, AccountStoreEmployee } = app.model; AccountPlatformActive.belongsTo(Account, { foreignKey: 'account_id', diff --git a/app/model/account_store_employee.js b/app/model/account_store_employee.js index 60cf702..5cfe23e 100644 --- a/app/model/account_store_employee.js +++ b/app/model/account_store_employee.js @@ -78,8 +78,8 @@ module.exports = app => { }); // 关联关系 - AccountStoreEmployee.associate = function(models) { - const { Account, Store, Role, AccountPlatformActive, EmployeeRole, Receiving } = app.model; + AccountStoreEmployee.associate = function() { + const { Account, Store, AccountPlatformActive, EmployeeRole, Receiving } = app.model; AccountStoreEmployee.belongsTo(Account, { foreignKey: 'account_id', as: 'account', diff --git a/app/model/api_app.js b/app/model/api_app.js index d0540e3..7ecbacd 100644 --- a/app/model/api_app.js +++ b/app/model/api_app.js @@ -65,6 +65,11 @@ module.exports = app => { allowNull: true, comment: '自身IP白名单', }, + callback_url: { + type: STRING(500), + allowNull: true, + comment: 'API回调通知URL', + }, qimen_app_key: { type: STRING(100), allowNull: true, @@ -227,7 +232,7 @@ module.exports = app => { // 定义关联关系 ApiApp.associate = function() { - const { InterfaceType, StoreWarehouse, Store, InterfaceLog } = app.model; + const { InterfaceType, StoreWarehouse, Store } = app.model; // 关联接口类型 ApiApp.belongsTo(InterfaceType, { diff --git a/app/model/entry_items.js b/app/model/entry_items.js index 6af2ecc..0969a64 100644 --- a/app/model/entry_items.js +++ b/app/model/entry_items.js @@ -192,7 +192,7 @@ module.exports = app => { }; // 钩子函数 - 保存前验证 - EntryItems.beforeSave(async (instance, options) => { + EntryItems.beforeSave(async instance => { const received = instance.received_quantity || 0; const plan = instance.count || 0; @@ -210,7 +210,7 @@ module.exports = app => { }); // 钩子函数 - 更新前验证 - EntryItems.beforeUpdate(async (instance, options) => { + EntryItems.beforeUpdate(async instance => { // 如果更新了received_quantity,进行验证 if (instance.changed('received_quantity')) { const received = instance.received_quantity || 0; diff --git a/app/model/file.js b/app/model/file.js index 2499a4a..785def8 100644 --- a/app/model/file.js +++ b/app/model/file.js @@ -2,7 +2,7 @@ 'use strict'; module.exports = app => { - const { BIGINT, INTEGER, STRING, TEXT, DATE, BOOLEAN } = app.Sequelize; + const { BIGINT, INTEGER, STRING, DATE, BOOLEAN } = app.Sequelize; const File = app.model.define('wms_file', { id: { diff --git a/app/model/file_reference.js b/app/model/file_reference.js index b90a8db..fe4ebec 100644 --- a/app/model/file_reference.js +++ b/app/model/file_reference.js @@ -2,7 +2,7 @@ 'use strict'; module.exports = app => { - const { BIGINT, INTEGER, STRING, TEXT, DATE, BOOLEAN, JSON: JSON_TYPE } = app.Sequelize; + const { BIGINT, INTEGER, STRING, DATE } = app.Sequelize; const FileReference = app.model.define('wms_file_reference', { id: { diff --git a/app/model/i18n_key.js b/app/model/i18n_key.js index eb96cbc..4516877 100644 --- a/app/model/i18n_key.js +++ b/app/model/i18n_key.js @@ -2,7 +2,7 @@ 'use strict'; module.exports = app => { - const { STRING, INTEGER, DATE } = app.Sequelize; + const { STRING, INTEGER } = app.Sequelize; const I18nKey = app.model.define('wms_i18n_key', { id: { diff --git a/app/model/interface_type.js b/app/model/interface_type.js index 2e845e2..c0d64d5 100644 --- a/app/model/interface_type.js +++ b/app/model/interface_type.js @@ -105,6 +105,16 @@ module.exports = app => { ], }); + InterfaceType.associate = function() { + const { ApiApp } = app.model; + + InterfaceType.hasMany(ApiApp, { + foreignKey: 'interface_type_id', + sourceKey: 'id', + as: 'api_apps', + }); + }; + // 实例方法 - 检查接口是否可用 InterfaceType.prototype.isAvailable = function() { return this.is_enabled === 1; diff --git a/app/model/notification_webhook.js b/app/model/notification_webhook.js index 6c769b5..aff14fe 100644 --- a/app/model/notification_webhook.js +++ b/app/model/notification_webhook.js @@ -39,6 +39,18 @@ module.exports = app => { Object.freeze({ code: 'all', name: '全部事件', business: 'all', description: '订阅后接收所有通知事件' }), Object.freeze({ code: '*', name: '全部事件(兼容别名)', business: 'all', description: '兼容旧配置,等价于 all' }), Object.freeze({ code: 'receiving_completed', name: '收货完成', business: 'receiving', description: '收货单完成后的通知' }), + Object.freeze({ + code: 'store_warehouse_print_quantity_adjusted', + name: '货主面单余额调整', + business: 'store_warehouse', + description: '货主-仓库签约下的面单余额被人工调整后的通知', + }), + Object.freeze({ + code: 'storage_transfer_completed', + name: '移库操作完成', + business: 'storage', + description: '库存库位转移操作完成后的通知', + }), ]); const AVAILABLE_EVENT_CODE_SET = new Set(AVAILABLE_EVENTS.map(item => item.code)); diff --git a/app/model/order_delivery_factory.js b/app/model/order_delivery_factory.js index a5df849..20f8769 100644 --- a/app/model/order_delivery_factory.js +++ b/app/model/order_delivery_factory.js @@ -2,7 +2,6 @@ 'use strict'; module.exports = app => { - const { Sequelize, model } = app; class OrderDeliveryFactory { constructor() { @@ -12,7 +11,8 @@ module.exports = app => { /** * 获取当前表模型 - * @param warehouseId + * @param {number} warehouseId 仓库ID + * @return {Promise} 当前表模型 */ async getCurrentModel(warehouseId) { return await this.getOrCreateModel(warehouseId, 'current'); @@ -20,7 +20,8 @@ module.exports = app => { /** * 获取历史表模型 - * @param warehouseId + * @param {number} warehouseId 仓库ID + * @return {Promise} 历史表模型 */ async getHistoryModel(warehouseId) { return await this.getOrCreateModel(warehouseId, 'history'); @@ -28,7 +29,8 @@ module.exports = app => { /** * 根据表名直接获取模型 - * @param tableName + * @param {string} tableName 表名 + * @return {Promise} 动态模型 */ async getModelByTableName(tableName) { const cacheKey = `table_${tableName}`; @@ -61,8 +63,9 @@ module.exports = app => { /** * 获取或创建模型 - * @param warehouseId - * @param type + * @param {number} warehouseId 仓库ID + * @param {string} type 模型类型 + * @return {Promise} 动态模型 */ async getOrCreateModel(warehouseId, type = 'current') { const tableName = this.generateTableName(warehouseId, type); @@ -103,9 +106,10 @@ module.exports = app => { /** * 获取模型配置选项 - * @param tableName - * @param warehouseId - * @param type + * @param {string} tableName 表名 + * @param {number} warehouseId 仓库ID + * @param {string} type 模型类型 + * @return {Object} Sequelize 模型配置 */ getModelOptions(tableName, warehouseId, type) { const options = { @@ -128,8 +132,9 @@ module.exports = app => { /** * 获取索引配置 - * @param warehouseId - * @param type + * @param {number} warehouseId 仓库ID + * @param {string} type 模型类型 + * @return {Array} 索引配置 */ getIndexes(warehouseId, type) { const prefix = `${warehouseId}_${type}`; @@ -180,9 +185,10 @@ module.exports = app => { /** * 设置关联关系 - * @param DynamicModel - * @param warehouseId - * @param type + * @param {Object} DynamicModel 动态模型 + * @param {number} warehouseId 仓库ID + * @param {string} type 模型类型 + * @return {Promise} */ async setupAssociations(DynamicModel, warehouseId, type) { try { @@ -231,7 +237,8 @@ module.exports = app => { /** * 检查表是否存在 - * @param tableName + * @param {string} tableName 表名 + * @return {Promise} 是否存在 */ async checkTableExists(tableName) { const sequelize = this.app.model; @@ -258,8 +265,9 @@ module.exports = app => { /** * 创建物理表 - * @param warehouseId - * @param type + * @param {number} warehouseId 仓库ID + * @param {string} type 模型类型 + * @return {Promise} */ async createPhysicalTable(warehouseId, type = 'current') { const tableName = this.generateTableName(warehouseId, type); @@ -271,9 +279,6 @@ module.exports = app => { const historyFields = type === 'history' ? ',\n`archive_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT \'归档时间\'' : ''; - // 状态机枚举值 - const statusEnums = this.getStatusEnumValues(); - const createTableSQL = ` CREATE TABLE \`${tableName}\` ( \`id\` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, @@ -393,8 +398,9 @@ module.exports = app => { /** * 生成表名 - * @param warehouseId - * @param type + * @param {number} warehouseId 仓库ID + * @param {string} type 模型类型 + * @return {string} 表名 */ generateTableName(warehouseId, type) { const suffix = type === 'history' ? '_history' : ''; diff --git a/app/model/order_items.js b/app/model/order_items.js index a1a971a..efe064b 100644 --- a/app/model/order_items.js +++ b/app/model/order_items.js @@ -3,7 +3,7 @@ module.exports = app => { const { Sequelize, model } = app; - const { STRING, BIGINT, DECIMAL, TEXT, INTEGER, JSON } = Sequelize; + const { STRING, BIGINT, DECIMAL, INTEGER, JSON } = Sequelize; const OrderItems = model.define('wms_order_items', { id: { diff --git a/app/model/order_items_factory.js b/app/model/order_items_factory.js index 61d41d4..3ff60f1 100644 --- a/app/model/order_items_factory.js +++ b/app/model/order_items_factory.js @@ -2,7 +2,7 @@ 'use strict'; module.exports = app => { - const { Sequelize, model } = app; + const { Sequelize } = app; class OrderItemsFactory { constructor() { @@ -13,7 +13,8 @@ module.exports = app => { /** * 获取当前表模型 - * @param warehouseId + * @param {number} warehouseId 仓库ID + * @return {Promise} 当前表模型 */ async getCurrentModel(warehouseId) { return await this.getOrCreateModel(warehouseId, 'current'); @@ -21,7 +22,8 @@ module.exports = app => { /** * 获取历史表模型 - * @param warehouseId + * @param {number} warehouseId 仓库ID + * @return {Promise} 历史表模型 */ async getHistoryModel(warehouseId) { return await this.getOrCreateModel(warehouseId, 'history'); @@ -29,8 +31,9 @@ module.exports = app => { /** * 获取或创建模型 - * @param warehouseId - * @param type + * @param {number} warehouseId 仓库ID + * @param {string} type 模型类型 + * @return {Promise} 动态模型 */ async getOrCreateModel(warehouseId, type = 'current') { const cacheKey = `${warehouseId}_${type}`; @@ -65,11 +68,12 @@ module.exports = app => { /** * 带重试的模型创建 - * @param warehouseId - * @param type - * @param tableName - * @param cacheKey - * @param retryCount + * @param {number} warehouseId 仓库ID + * @param {string} type 模型类型 + * @param {string} tableName 表名 + * @param {string} cacheKey 缓存键 + * @param {number} retryCount 重试次数 + * @return {Promise} 动态模型 */ async createModelWithRetry(warehouseId, type, tableName, cacheKey, retryCount = 3) { for (let i = 0; i < retryCount; i++) { @@ -120,8 +124,8 @@ module.exports = app => { /** * 复制关联关系 - * @param sourceModel - * @param targetModel + * @param {Object} sourceModel 源模型 + * @param {Object} targetModel 目标模型 */ copyAssociations(sourceModel, targetModel) { if (sourceModel.associations) { @@ -148,7 +152,7 @@ module.exports = app => { /** * 生成索引配置 - * @param warehouseId + * @param {number} warehouseId 仓库ID */ generateIndexes(warehouseId) { return [ @@ -189,7 +193,7 @@ module.exports = app => { /** * 检查表是否存在 - * @param tableName + * @param {string} tableName 表名 */ async checkTableExists(tableName) { try { @@ -211,8 +215,8 @@ module.exports = app => { /** * 创建物理表 - * @param warehouseId - * @param type + * @param {number} warehouseId 仓库ID + * @param {string} type 模型类型 */ async createPhysicalTable(warehouseId, type = 'current') { const tableName = this.generateTableName(warehouseId, type); @@ -263,8 +267,8 @@ module.exports = app => { /** * 生成表名 - * @param warehouseId - * @param type + * @param {number} warehouseId 仓库ID + * @param {string} type 模型类型 */ generateTableName(warehouseId, type) { const suffix = type === 'history' ? '_history' : ''; @@ -273,8 +277,8 @@ module.exports = app => { /** * 清除缓存 - * @param warehouseId - * @param type + * @param {number} warehouseId 仓库ID + * @param {string} type 模型类型 */ clearCache(warehouseId, type) { const cacheKey = `${warehouseId}_${type}`; @@ -290,7 +294,7 @@ module.exports = app => { /** * 休眠函数 - * @param ms + * @param {number} ms 毫秒数 */ sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); diff --git a/app/model/print_item.js b/app/model/print_item.js index d26e294..d9659a1 100644 --- a/app/model/print_item.js +++ b/app/model/print_item.js @@ -1,6 +1,6 @@ // app/model/print_item.js module.exports = app => { - const { STRING, INTEGER, BOOLEAN, TEXT, JSON, DATE } = app.Sequelize; + const { STRING, INTEGER, BOOLEAN, JSON, DATE } = app.Sequelize; const PrintItem = app.model.define('print_item', { id: { diff --git a/app/model/qimen_log.js b/app/model/qimen_log.js index 7f9ed9e..42f0bb6 100644 --- a/app/model/qimen_log.js +++ b/app/model/qimen_log.js @@ -3,7 +3,7 @@ 'use strict'; module.exports = app => { - const { STRING, INTEGER, BIGINT, TEXT, DATE, BOOLEAN } = app.Sequelize; + const { STRING, INTEGER, BIGINT, TEXT, DATE } = app.Sequelize; const QimenLog = app.model.define('qimen_log', { id: { diff --git a/app/model/receiving.js b/app/model/receiving.js index b885599..fe07bcc 100644 --- a/app/model/receiving.js +++ b/app/model/receiving.js @@ -1,6 +1,6 @@ // app/model/receiving.js module.exports = app => { - const { STRING, INTEGER, DATE, DECIMAL, TEXT, BOOLEAN, ENUM } = app.Sequelize; + const { STRING, INTEGER, DATE, TEXT, BOOLEAN, ENUM } = app.Sequelize; const Receiving = app.model.define('wms_receiving', { id: { diff --git a/app/model/receiving_detail.js b/app/model/receiving_detail.js index 6f1f0fe..a634b90 100644 --- a/app/model/receiving_detail.js +++ b/app/model/receiving_detail.js @@ -1,6 +1,6 @@ // app/model/receiving_detail.js module.exports = app => { - const { STRING, INTEGER, DATE, DECIMAL, TEXT, ENUM, BOOLEAN, BIGINT } = app.Sequelize; + const { STRING, INTEGER, DATE, DECIMAL, TEXT, ENUM, BIGINT } = app.Sequelize; const ReceivingDetail = app.model.define('wms_receiving_detail', { id: { diff --git a/app/model/stock_barcode.js b/app/model/stock_barcode.js index 21e7b86..374a892 100644 --- a/app/model/stock_barcode.js +++ b/app/model/stock_barcode.js @@ -1,7 +1,7 @@ 'use strict'; module.exports = app => { - const { STRING, BIGINT, DATE, TEXT } = app.Sequelize; + const { STRING, BIGINT, DATE } = app.Sequelize; const StockBarcode = app.model.define('stock_barcodes', { id: { diff --git a/app/model/stock_transaction.js b/app/model/stock_transaction.js new file mode 100644 index 0000000..88ddf39 --- /dev/null +++ b/app/model/stock_transaction.js @@ -0,0 +1,154 @@ +'use strict'; + +module.exports = app => { + const { STRING, INTEGER, BIGINT, ENUM, DATE } = app.Sequelize; + + const StockTransaction = app.model.define('stock_transaction', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键ID', + }, + transaction_type: { + type: ENUM('INBOUND', 'OUTBOUND'), + allowNull: false, + comment: '出入库类型', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '货主ID', + }, + stock_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '商品库存ID,关联 wms_stock_warehouse.id', + }, + storage_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '库位库存ID,关联 wms_storage.id', + }, + space_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '库位ID', + }, + quantity: { + type: INTEGER(12), + allowNull: false, + comment: '变动数量(正数)', + }, + batch_no: { + type: STRING(100), + allowNull: true, + comment: '批次号', + }, + inventory_type: { + type: ENUM('ZP', 'CC', 'JS', 'XS', 'ZT', 'DJ', 'FP'), + defaultValue: 'ZP', + comment: '库存类型', + }, + order_type: { + type: STRING(50), + allowNull: true, + comment: '关联单据类型(如 SCRK=收货入库, MATCH=匹配入库, CGTH=采购退货等)', + }, + order_no: { + type: STRING(100), + allowNull: true, + comment: '关联单据号', + }, + order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '关联单据ID', + }, + receiving_id: { + type: INTEGER, + allowNull: true, + comment: '关联收货单ID', + }, + entry_order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '关联入库单ID', + }, + operator_id: { + type: STRING(100), + allowNull: true, + comment: '操作人ID', + }, + operator_name: { + type: STRING(100), + allowNull: true, + comment: '操作人名称', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + created_at: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + }, { + tableName: 'wms_stock_transaction', + freezeTableName: true, + timestamps: false, + comment: '出入库流水记录表', + indexes: [ + { + name: 'idx_stock_id', + fields: [ 'stock_id' ], + }, + { + name: 'idx_warehouse_time', + fields: [ 'warehouse_id', 'created_at' ], + }, + { + name: 'idx_order', + fields: [ 'order_type', 'order_id' ], + }, + { + name: 'idx_receiving_id', + fields: [ 'receiving_id' ], + }, + { + name: 'idx_entry_order_id', + fields: [ 'entry_order_id' ], + }, + { + name: 'idx_created_at', + fields: [ 'created_at' ], + }, + { + name: 'idx_store_transaction_type', + fields: [ 'store_id', 'transaction_type' ], + }, + ], + }); + + StockTransaction.associate = function() { + const { StockWarehouse, Storage } = app.model; + StockTransaction.belongsTo(StockWarehouse, { + foreignKey: 'stock_id', + as: 'stockItem', + }); + StockTransaction.belongsTo(Storage, { + foreignKey: 'storage_id', + as: 'storageRecord', + }); + }; + + return StockTransaction; +}; diff --git a/app/model/stock_warehouse.js b/app/model/stock_warehouse.js index 2d0107b..2eee63b 100644 --- a/app/model/stock_warehouse.js +++ b/app/model/stock_warehouse.js @@ -222,8 +222,8 @@ module.exports = app => { ], }); - StockWarehouse.associate = function(models) { - const { StoreWarehouse, StockBarcode, ProhibitedType, StockImage, StockStore, Storage } = app.model; + StockWarehouse.associate = function() { + const { StoreWarehouse, StockBarcode, ProhibitedType, StockStore, Storage } = app.model; // store_stock 关联依赖 store_id + warehouse_id 复合语义,单列关联仅作为 include 入口。 StockWarehouse.belongsTo(StoreWarehouse, { foreignKey: 'store_id', // 当前表的外键字段 @@ -250,6 +250,12 @@ module.exports = app => { as: 'storage', }); + const { StockTransaction } = app.model; + StockWarehouse.hasMany(StockTransaction, { + foreignKey: 'stock_id', + as: 'transactions', + }); + }; return StockWarehouse; diff --git a/app/model/storage.js b/app/model/storage.js index 7646aee..5d359d0 100644 --- a/app/model/storage.js +++ b/app/model/storage.js @@ -101,6 +101,24 @@ module.exports = app => { notEmpty: true, }, }, + receiving_id: { + type: INTEGER, + allowNull: true, + comment: '收货单ID', + references: { + model: 'wms_receiving', + key: 'id', + }, + }, + entry_order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '入库单ID', + references: { + model: 'wms_entry_order', + key: 'id', + }, + }, supplier_id: { type: BIGINT(20).UNSIGNED, allowNull: true, @@ -138,6 +156,8 @@ module.exports = app => { tableName: 'wms_storage', comment: '库存表', timestamps: false, + paranoid: true, + deletedAt: 'delete_at', indexes: [ { name: 'uk_location_sku_batch_type', @@ -164,6 +184,14 @@ module.exports = app => { name: 'idx_inbound_order', fields: [ 'inbound_order_no' ], }, + { + name: 'idx_receiving_id', + fields: [ 'receiving_id' ], + }, + { + name: 'idx_entry_order_id', + fields: [ 'entry_order_id' ], + }, { name: 'idx_store_id', fields: [ 'store_id' ], @@ -215,6 +243,18 @@ module.exports = app => { as: 'stock', }); + // 关联收货单 + Storage.belongsTo(app.model.Receiving, { + foreignKey: 'receiving_id', + as: 'receiving', + }); + + // 关联入库单 + Storage.belongsTo(app.model.EntryOrder, { + foreignKey: 'entry_order_id', + as: 'entryOrder', + }); + }; // 实例方法 diff --git a/app/model/store_warehouse.js b/app/model/store_warehouse.js index f0a2ae3..611d9ff 100644 --- a/app/model/store_warehouse.js +++ b/app/model/store_warehouse.js @@ -1,7 +1,211 @@ 'use strict'; module.exports = app => { - const { BIGINT, TEXT, STRING, DATE, TINYINT, INTEGER } = app.Sequelize; + const { BIGINT, TEXT, STRING, DATE, TINYINT, INTEGER, JSON: JSON_TYPE } = app.Sequelize; + + const POLICY_CONFIG_FIELDS = Object.freeze([ + Object.freeze({ + key: 'receive_mode', + name: '收货模式', + type: 'enum', + default: 'standard', + required: false, + description: '控制货主在该仓下的收货校验模式', + options: [ 'standard', 'strict', 'manual' ], + }), + Object.freeze({ + key: 'sku_visibility', + name: 'SKU 可见范围', + type: 'enum', + default: 'all', + required: false, + description: '控制货主在该仓下的 SKU 可见策略', + options: [ 'all', 'whitelist', 'blacklist' ], + }), + Object.freeze({ + key: 'auto_allocate_bin', + name: '自动分配库位', + type: 'flag', + default: 0, + required: false, + description: '收货上架时是否自动推荐库位', + }), + Object.freeze({ + key: 'allow_mix_batch', + name: '允许混批', + type: 'flag', + default: 0, + required: false, + description: '是否允许不同批次混合存放', + }), + Object.freeze({ + key: 'allow_temp_storage', + name: '允许临时存放', + type: 'flag', + default: 0, + required: false, + description: '是否允许进入临时存放区', + }), + Object.freeze({ + key: 'print_recharge_price', + name: '面单充值元/单', + type: 'number', + default: 0, + required: false, + description: '面单充值元/单,支持 2 位小数', + min: 0, + max: 1000000, + precision: 2, + step: 0.01, + }), + Object.freeze({ + key: 'max_daily_inbound', + name: '单日最大收货量', + type: 'integer', + default: 0, + required: false, + description: '限制该货主在仓库内的日收货上限', + min: 0, + max: 1000000, + }), + Object.freeze({ + key: 'remark', + name: '策略备注', + type: 'string', + default: '', + required: false, + description: '补充说明该货主在仓库内的特殊约束', + maxLength: 200, + }), + ]); + const POLICY_CONFIG_FIELD_MAP = Object.freeze(POLICY_CONFIG_FIELDS.reduce((result, field) => { + result[field.key] = field; + return result; + }, {})); + + const clonePolicyConfigField = 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 ] } : {}), + ...(field.min !== undefined ? { min: field.min } : {}), + ...(field.max !== undefined ? { max: field.max } : {}), + ...(field.precision !== undefined ? { precision: field.precision } : {}), + ...(field.step !== undefined ? { step: field.step } : {}), + ...(field.maxLength !== undefined ? { maxLength: field.maxLength } : {}), + }); + + const parsePolicyConfig = (value, fieldName = 'policy_config') => { + if (typeof value === 'string') { + try { + return JSON.parse(value); + } catch (error) { + throw new Error(`${fieldName} 不是合法JSON`); + } + } + return value; + }; + + const normalizePolicyConfig = (value, options = {}) => { + const { + fieldName = 'policy_config', + allowEmpty = false, + sanitizeOnly = false, + } = options; + + if (value === undefined || value === null || value === '') { + if (allowEmpty) { + return null; + } + throw new Error(`${fieldName} 参数不能为空`); + } + + const parsed = parsePolicyConfig(value, fieldName); + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { + throw new Error(`${fieldName} 必须为对象`); + } + + const supportedKeys = Object.keys(POLICY_CONFIG_FIELD_MAP); + const unsupportedKeys = Object.keys(parsed).filter(key => !POLICY_CONFIG_FIELD_MAP[key]); + if (unsupportedKeys.length && !sanitizeOnly) { + throw new Error(`${fieldName} 包含不支持字段: ${unsupportedKeys.join(', ')};仅允许字段: ${supportedKeys.join(', ')}`); + } + + const normalized = {}; + for (const field of POLICY_CONFIG_FIELDS) { + if (!Object.prototype.hasOwnProperty.call(parsed, field.key)) { + continue; + } + + const rawValue = parsed[field.key]; + if (rawValue === undefined || rawValue === null || rawValue === '') { + if (field.type === 'string') { + normalized[field.key] = ''; + } + continue; + } + + try { + if (field.type === 'enum') { + const valueText = String(rawValue).trim(); + if (!field.options.includes(valueText)) { + throw new Error(`${fieldName}.${field.key} 参数不合法`); + } + normalized[field.key] = valueText; + continue; + } + + if (field.type === 'flag') { + if (rawValue === true || rawValue === 1 || rawValue === '1') { + normalized[field.key] = 1; + continue; + } + if (rawValue === false || rawValue === 0 || rawValue === '0') { + normalized[field.key] = 0; + continue; + } + throw new Error(`${fieldName}.${field.key} 参数不合法`); + } + + if (field.type === 'integer') { + const num = Number(rawValue); + if (!Number.isFinite(num) || num < field.min || num > field.max) { + throw new Error(`${fieldName}.${field.key} 参数不合法`); + } + normalized[field.key] = Math.floor(num); + continue; + } + + if (field.type === 'number') { + const num = Number(rawValue); + if (!Number.isFinite(num) || num < field.min || num > field.max) { + throw new Error(`${fieldName}.${field.key} 参数不合法`); + } + const precision = Number.isInteger(field.precision) ? field.precision : 2; + const factor = 10 ** precision; + normalized[field.key] = Math.round(num * factor) / factor; + continue; + } + + if (field.type === 'string') { + const text = String(rawValue).trim(); + if (text.length > field.maxLength) { + throw new Error(`${fieldName}.${field.key} 长度不能超过 ${field.maxLength}`); + } + normalized[field.key] = text; + } + } catch (error) { + if (!sanitizeOnly) { + throw error; + } + } + } + + return Object.keys(normalized).length ? normalized : null; + }; const StoreWarehouse = app.model.define('store_warehouse', { id: { @@ -119,6 +323,25 @@ module.exports = app => { }, comment: '仓库备注', }, + policy_config: { + type: JSON_TYPE, + allowNull: true, + defaultValue: null, + comment: '货主在仓库下的固定策略配置(JSON)', + get() { + return normalizePolicyConfig(this.getDataValue('policy_config'), { + fieldName: 'policy_config', + allowEmpty: true, + sanitizeOnly: true, + }); + }, + set(value) { + this.setDataValue('policy_config', normalizePolicyConfig(value, { + fieldName: 'policy_config', + allowEmpty: true, + })); + }, + }, use_status: { type: INTEGER(1), allowNull: false, @@ -179,7 +402,7 @@ module.exports = app => { // 定义关联关系 StoreWarehouse.associate = function() { - const { Store, Account, StockWarehouse, Receiving } = app.model; + const { Store, Account, StockWarehouse, Receiving, StoreWarehousePrintQuantityLog } = app.model; // 授权关系属于商家 StoreWarehouse.belongsTo(Store, { @@ -229,6 +452,21 @@ module.exports = app => { as: 'receiving', constraints: false, }); + + StoreWarehouse.hasMany(StoreWarehousePrintQuantityLog, { + foreignKey: 'contract_id', + sourceKey: 'id', + as: 'print_quantity_logs', + constraints: false, + }); + }; + + StoreWarehouse.getPolicyConfigFieldList = function() { + return POLICY_CONFIG_FIELDS.map(clonePolicyConfigField); + }; + + StoreWarehouse.normalizePolicyConfig = function(value, options = {}) { + return normalizePolicyConfig(value, options); }; // 统一构造复合键语义的 where 条件,避免 service 侧重复散落。 diff --git a/app/model/store_warehouse_print_quantity_log.js b/app/model/store_warehouse_print_quantity_log.js new file mode 100644 index 0000000..87c7487 --- /dev/null +++ b/app/model/store_warehouse_print_quantity_log.js @@ -0,0 +1,174 @@ +'use strict'; + +module.exports = app => { + const { BIGINT, STRING, TEXT, DATE } = app.Sequelize; + + const StoreWarehousePrintQuantityLog = app.model.define('store_warehouse_print_quantity_log', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + contract_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '签约关系ID,对应 wms_store_warehouse.id', + references: { + model: 'store_warehouse', + key: 'id', + }, + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '货主ID,对应 wms_store.id', + references: { + model: 'store', + key: 'id', + }, + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID,对应 wms_store.id', + references: { + model: 'store', + key: 'id', + }, + }, + change_type: { + type: STRING(50), + allowNull: false, + comment: '变更类型,如 manual_adjust / order_deduct', + }, + business_type: { + type: STRING(50), + allowNull: true, + comment: '业务来源类型,如 order_express', + }, + business_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '业务关联ID,预留关联 wms_order_express.id', + }, + change_quantity: { + type: BIGINT(20), + allowNull: false, + comment: '本次变更数量,整数,可正可负', + }, + balance_before: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '变更前余额', + }, + balance_after: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '变更后余额', + }, + reason: { + type: TEXT, + allowNull: true, + comment: '变更缘由;人工调整时必填', + }, + operator_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '操作人账号ID', + }, + created_by: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '创建人账号ID', + }, + created_at: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + }, { + tableName: 'wms_store_warehouse_print_quantity_log', + freezeTableName: true, + underscored: true, + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + comment: '货主-仓库签约面单余额变更记录表', + indexes: [ + { + name: 'idx_sw_print_qty_log_contract_id', + fields: [ 'contract_id', 'id' ], + }, + { + name: 'idx_sw_print_qty_log_store_warehouse', + fields: [ 'store_id', 'warehouse_id' ], + }, + { + name: 'idx_sw_print_qty_log_business', + fields: [ 'business_type', 'business_id' ], + }, + { + name: 'idx_sw_print_qty_log_change_type', + fields: [ 'change_type' ], + }, + { + name: 'idx_sw_print_qty_log_created_at', + fields: [ 'created_at' ], + }, + ], + }); + + StoreWarehousePrintQuantityLog.associate = function() { + const { StoreWarehouse, Store, Account, OrderExpress } = app.model; + + StoreWarehousePrintQuantityLog.belongsTo(StoreWarehouse, { + foreignKey: 'contract_id', + targetKey: 'id', + as: 'contract', + }); + + StoreWarehousePrintQuantityLog.belongsTo(Store, { + foreignKey: 'store_id', + targetKey: 'id', + as: 'store', + }); + + StoreWarehousePrintQuantityLog.belongsTo(Store, { + foreignKey: 'warehouse_id', + targetKey: 'id', + as: 'warehouse', + }); + + StoreWarehousePrintQuantityLog.belongsTo(Account, { + foreignKey: 'operator_id', + targetKey: 'id', + as: 'operator', + constraints: false, + }); + + StoreWarehousePrintQuantityLog.belongsTo(Account, { + foreignKey: 'created_by', + targetKey: 'id', + as: 'creator', + constraints: false, + }); + + StoreWarehousePrintQuantityLog.belongsTo(OrderExpress, { + foreignKey: 'business_id', + targetKey: 'id', + as: 'order_express', + constraints: false, + }); + }; + + return StoreWarehousePrintQuantityLog; +}; diff --git a/app/router.js b/app/router.js index 1ed412f..c96daa7 100644 --- a/app/router.js +++ b/app/router.js @@ -11,17 +11,14 @@ module.exports = app => { // 奇门接口 router.post('/qimen', controller.home.qimen); - // 预留第三方系统接口 - router.post('/api/warehouse', controller.home.warehouse); - router.post('/api/store', controller.home.store); - // 系统接口 PDA/WEB 统一入口 router.post('/system', controller.home.system); // api文档相关 router.get('/api/docs', controller.docs.list); - router.get('/api/docs/:docName', controller.docs.detail); router.get('/api/docs/:docName/raw', controller.docs.raw); + router.get('/api/docs/:docName/changes', controller.docs.changes); + router.get('/api/docs/:docName', controller.docs.detail); // 打印模板 router.get('/template/xml/:id', controller.template.xml); diff --git a/app/service/api.js b/app/service/api.js index 544067c..aad17c5 100644 --- a/app/service/api.js +++ b/app/service/api.js @@ -1,17 +1,15 @@ 'use strict'; const Service = require('egg').Service; -const { XMLParser } = require('fast-xml-parser'); class ApiService extends Service { /** * 调用业务方法 - * @param className - * @param actionName - * @param jsonData - * @param format + * @param {string} className 服务类路径 + * @param {string} actionName 方法名 + * @param {Object} jsonData 请求数据 */ - async callMethod(className, actionName, jsonData, format = 'json') { + async callMethod(className, actionName, jsonData) { try { // 构建服务类路径 const servicePath = `${className}`; diff --git a/app/service/apiMethods/test.js b/app/service/apiMethods/test.js index 7630273..7284f49 100644 --- a/app/service/apiMethods/test.js +++ b/app/service/apiMethods/test.js @@ -11,17 +11,15 @@ class testServer extends Service { this.addon = require(app.appRoot + '/native/addons/subset_selector.node'); this.addonLoaded = true; this.ctx.logger.info('[FibonacciService] C++插件加载成功'); - console.log(this.addon); } catch (error) { - this.addonLoaded = false; this.ctx.logger.error('[FibonacciService] C++插件加载失败:', error); } } async entryorderConfirm(data) { - const { app, ctx } = this; + const { ctx } = this; return await ctx.service.systems.entryOrder.entryorderConfirm(data.id, data.isCompleted); } async playbackRequest(data) { @@ -33,7 +31,6 @@ class testServer extends Service { }, }); if (entryOrder) { - console.log('entryOrder', entryOrder.body); const body = await this.ctx.service.systems.qimenQuery.sendRequest(entryOrder.url, entryOrder.body); return { body }; } @@ -65,8 +62,6 @@ class testServer extends Service { raw: true, }); - console.log('查询到的订单ID数量:', deliveryResult.length); - if (deliveryResult.length === 0) { return { orderIds: [], @@ -93,8 +88,6 @@ class testServer extends Service { raw: true, }); - console.log('查询到的商品记录数量:', itemsResult.length); - // 4. 按订单分组商品 const itemsByOrder = {}; itemsResult.forEach(item => { @@ -116,8 +109,6 @@ class testServer extends Service { }; }).filter(order => order.skus.length > 0); // 过滤掉没有商品的订单 - console.log('有效订单数量:', orders.length); - if (orders.length === 0) { return { orderIds: [], diff --git a/app/service/main.js b/app/service/main.js index 7a1a728..5b0f62c 100644 --- a/app/service/main.js +++ b/app/service/main.js @@ -31,7 +31,6 @@ class MainService extends Service { } fail(message, data, code = 0) { - console.log('fail', message, data); const result = { flag: 'failure', code, @@ -309,7 +308,6 @@ class MainService extends Service { const _noNeedAuth = (this._noNeedAuth || '').split(','); const _noNeedLog = (this._noNeedLog || '').split(','); const api_path = `${servicePath}.${actionName}`; - console.log(api_path, '_noNeedLog', _noNeedLog); const result = { status: 401, message: '', @@ -357,7 +355,6 @@ class MainService extends Service { // 设置新的 token 到响应头 ctx.set('Authorization', `Bearer ${newToken}`); - console.log('Token 已刷新,新 token:', newToken.substring(0, 50) + '...'); } // 4. 获取用户信息 const user = await ctx.service.systems.auth.user.findById(decoded.id || decoded.userId); @@ -393,11 +390,8 @@ class MainService extends Service { } // 6. 验证API权限(只检查类型为api的权限) - console.log('检查权限开始'); const hasPermission = await this.checkApiPermission(user, api_path); - console.log('检查权限结束', hasPermission); - if (!hasPermission) { result.status = 403; @@ -440,20 +434,163 @@ class MainService extends Service { * @return {Promise} 是否有权限 */ async checkApiPermission(user, apiPath) { - console.log(user); + const normalizedApiPath = String(apiPath || '').trim().toLowerCase(); + if (!normalizedApiPath) { + return false; + } + try { - // 方法1: 从用户的权限列表中检查(如果已经加载了权限) - if (user.permissions && Array.isArray(user.permissions)) { - // 用户权限列表中可能包含所有权限,需要过滤出api权限 - console.log('user.permissions', user.permissions); - return user.permissions.includes(apiPath); + const { allAccess, pathSet, permissionIds } = this.extractApiPermissionState(user); + if (allAccess) { + return true; } + + if (pathSet.has(normalizedApiPath)) { + return true; + } + + if (permissionIds.size > 0 && this.ctx.model && this.ctx.model.Permission && typeof this.ctx.model.Permission.findAll === 'function') { + const permissionRows = await this.ctx.model.Permission.findAll({ + where: { + id: [ ...permissionIds ], + status: 1, + }, + attributes: [ 'id', 'path' ], + raw: true, + }); + + return permissionRows.some(item => String(item && item.path || '').trim().toLowerCase() === normalizedApiPath); + } + return false; } catch (error) { console.error('检查API权限失败:', error); return false; } } + + extractApiPermissionState(user = {}) { + const state = { + allAccess: false, + pathSet: new Set(), + permissionIds: new Set(), + }; + const visited = new Set(); + const sources = [ + user.permissions, + user.role_permissions, + user.permission_ids, + user.permissionIds, + ]; + + for (const source of sources) { + this.collectApiPermissionValue(source, state, visited); + if (state.allAccess) { + break; + } + } + + return state; + } + + collectApiPermissionValue(value, state, visited) { + if (state.allAccess || value === undefined || value === null) { + return; + } + + if (typeof value === 'string') { + const trimmed = value.trim(); + if (!trimmed) { + return; + } + + if (trimmed === '*') { + state.allAccess = true; + return; + } + + if ((trimmed.startsWith('[') && trimmed.endsWith(']')) || (trimmed.startsWith('{') && trimmed.endsWith('}'))) { + try { + const parsed = JSON.parse(trimmed); + if (parsed !== value) { + this.collectApiPermissionValue(parsed, state, visited); + return; + } + } catch (_) { + // 忽略 JSON 解析失败,继续按普通字符串处理。 + } + } + + if (trimmed.includes(',')) { + this.collectApiPermissionValue(trimmed.split(','), state, visited); + return; + } + + const asNumber = Number(trimmed); + if (Number.isInteger(asNumber) && String(asNumber) === trimmed) { + state.permissionIds.add(asNumber); + return; + } + + state.pathSet.add(trimmed.toLowerCase()); + return; + } + + if (typeof value === 'number') { + if (Number.isInteger(value) && value > 0) { + state.permissionIds.add(value); + } + return; + } + + if (Array.isArray(value)) { + for (const item of value) { + this.collectApiPermissionValue(item, state, visited); + if (state.allAccess) { + break; + } + } + return; + } + + if (typeof value !== 'object') { + return; + } + + if (visited.has(value)) { + return; + } + visited.add(value); + + if (value.allAccess === true || value.isAllAccess === true) { + state.allAccess = true; + return; + } + + const candidates = [ + value.path, + value.apiPath, + value.permission, + value.permissionPath, + value.value, + value.id, + value.permission_id, + value.permissionId, + value.permissions, + value.permission_ids, + value.permissionIds, + value.children, + value.items, + value.list, + ]; + + for (const candidate of candidates) { + this.collectApiPermissionValue(candidate, state, visited); + if (state.allAccess) { + break; + } + } + } /** * 设置用户上下文信息 * @param {Object} ctx - 上下文对象 @@ -467,7 +604,6 @@ class MainService extends Service { ctx.username = user.username; ctx.realName = user.real_name; - if (user.store_id) { ctx.currentStoreId = user.store_id; } diff --git a/app/service/pda.js b/app/service/pda.js index de8f355..de670ba 100644 --- a/app/service/pda.js +++ b/app/service/pda.js @@ -1,7 +1,6 @@ 'use strict'; const Service = require('egg').Service; -const { XMLParser } = require('fast-xml-parser'); class pdaService extends Service { async callMethod(className, actionName, requestData, authHeader) { @@ -31,9 +30,8 @@ class pdaService extends Service { // 调用方法 const authPass = await serviceInstance.checkAuth(servicePath, actionName, authHeader); const isLog = authPass.isLog; - if (authPass.status == 200) { + if (authPass.status === 200) { result.data = await serviceInstance[actionName](requestData); - console.log(result.data); result.status = 200; } else { diff --git a/app/service/qimen.js b/app/service/qimen.js index 33bff3d..8e2b44d 100644 --- a/app/service/qimen.js +++ b/app/service/qimen.js @@ -6,14 +6,13 @@ const { XMLParser } = require('fast-xml-parser'); class QimenService extends Service { /** * 验证接口是否存在且启用 - * @param appkey - * @param customerId - * @param warehouseCode + * @param {string} appkey 应用编码 + * @param {string} customerId 客户编码 + * @param {string} warehouseCode 仓库编码 */ async validateApi(appkey, customerId, warehouseCode) { try { - const { ctx } = this; const result = await this.ctx.service.main.findQimenAppWithContract(appkey, customerId, warehouseCode); return result; } catch (error) { @@ -41,7 +40,7 @@ class QimenService extends Service { } /** * 解析XML到数组 - * @param xmlString + * @param {string} xmlString XML 字符串 */ async parseXmlToArray(xmlString) { const cleanedXml = this.cleanXmlString(xmlString); @@ -60,7 +59,7 @@ class QimenService extends Service { trimValues: false, // 也关闭trim,保持原始格式 ignoreDeclaration: true, // 添加标签值处理器,手动控制转换 - tagValueProcessor: (tagName, tagValue, jPath, hasAttributes, isLeafNode) => { + tagValueProcessor: tagValue => { // 如果是叶子节点且需要保持字符串格式的标签,可以在这里特殊处理 // 默认返回原始值 return tagValue; @@ -77,7 +76,7 @@ class QimenService extends Service { /** * 清理XML字符串 - * @param xmlString + * @param {string} xmlString XML 字符串 */ cleanXmlString(xmlString) { if (!xmlString) return ''; @@ -103,17 +102,17 @@ class QimenService extends Service { /** * 调用业务方法 - * @param className - * @param actionName - * @param xmlData - * @param storeId - * @param warehouseId - * @param appKey - * @param customerId - * @param warehouseCode - * @param format + * @param {string} className 类名 + * @param {string} actionName 方法名 + * @param {Object} xmlData 解析后的 XML 数据 + * @param {number} storeId 货主ID + * @param {number} warehouseId 仓库ID + * @param {string} appKey 应用编码 + * @param {string} customerId 客户编码 + * @param {string} warehouseCode 仓库编码 + * @return {Promise} 调用结果 */ - async callMethod(className, actionName, xmlData, storeId, warehouseId, appKey, customerId, warehouseCode, format = 'xml') { + async callMethod(className, actionName, xmlData, storeId, warehouseId, appKey, customerId, warehouseCode) { try { // 构建服务类路径 const servicePath = `${className}`; @@ -148,7 +147,7 @@ class QimenService extends Service { /** * 格式化响应 - * @param data + * @param {Object} data 响应数据 */ formatResponse(data) { return this.xmlResponse(data); @@ -156,7 +155,7 @@ class QimenService extends Service { /** * XML响应 - * @param data + * @param {Object} data 响应数据 */ xmlResponse(data) { let xml = '\n'; @@ -180,9 +179,9 @@ class QimenService extends Service { /** * 构建XML节点 - 支持多层级 - * @param key - * @param value - * @param level + * @param {string} key 节点名 + * @param {*} value 节点值 + * @param {number} level 缩进层级 */ buildXmlNode(key, value, level = 0) { const indent = ' '.repeat(level); @@ -218,7 +217,7 @@ class QimenService extends Service { /** * XML转义 - * @param unsafe + * @param {*} unsafe 待转义值 */ escapeXml(unsafe) { if (unsafe === null || unsafe === undefined) return ''; diff --git a/app/service/qimenMethods/deliveryorder.js b/app/service/qimenMethods/deliveryorder.js index 635c0ae..9ba30c3 100644 --- a/app/service/qimenMethods/deliveryorder.js +++ b/app/service/qimenMethods/deliveryorder.js @@ -5,7 +5,6 @@ const MainService = require('../main'); class deliveryorderServer extends MainService { async query(data) { const DeliveryModel = await this.ctx.model.OrderDeliveryFactory.getCurrentModel(this.warehouseId); - const hisDeliveryModel = await this.ctx.model.OrderDeliveryFactory.getHistoryModel(this.warehouseId); const order = await DeliveryModel.findOne({ where: { delivery_order_code: data.request.orderCode } }); const totalLines = 0; if (order) { @@ -35,9 +34,9 @@ class deliveryorderServer extends MainService { const info = this.getInfo; const res = await this.ctx.service.systems.deliveryOrder.addOrder(data, this.getInfo(), 'QM'); if (res.success) { - return this.success(res.message, { createTime: new Date().format(), deliveryOrderId: res.data.deliveryOrderId, warehouseCode: info.warehouseCode, logisticsCode: res.data.logisticsCode }); + return this.success(res.message, { createTime: this.app.formatDate(new Date()), deliveryOrderId: res.data.deliveryOrderId, warehouseCode: info.warehouseCode, logisticsCode: res.data.logisticsCode }); } - return this.fail(res.message, { createTime: new Date().format() }); + return this.fail(res.message, { createTime: this.app.formatDate(new Date()) }); } async batchcreate() { diff --git a/app/service/qimenMethods/entryorder.js b/app/service/qimenMethods/entryorder.js index 67b941d..48efe60 100644 --- a/app/service/qimenMethods/entryorder.js +++ b/app/service/qimenMethods/entryorder.js @@ -4,18 +4,15 @@ const MainService = require('../main'); class entryorderServer extends MainService { async create(data) { - const info = this.getInfo; const res = await this.ctx.service.systems.entryOrder.addOrder(data, this.getInfo(), 'QM'); - console.log('创建入库单返回', res); if (res.success) { - return this.success(res.message, { createTime: new Date().format(), entryOrderId: res.data.entryOrderId }); + return this.success(res.message, { createTime: this.app.formatDate(new Date()), entryOrderId: res.data.entryOrderId }); } - return this.fail(res.message, { createTime: new Date().format() }); + return this.fail(res.message, { createTime: this.app.formatDate(new Date()) }); } - async query(data) { - console.log(data); + async query() { return this.fail('接口未完善'); } diff --git a/app/service/qimenMethods/inventory.js b/app/service/qimenMethods/inventory.js index 3d09f09..19868b5 100644 --- a/app/service/qimenMethods/inventory.js +++ b/app/service/qimenMethods/inventory.js @@ -3,10 +3,6 @@ const MainService = require('../main'); class inventoryServer extends MainService { - - constructor(ctx) { - super(ctx); - } async query(data) { const criteria = data.request.criteriaList.criteria; const list = criteria.warehouseCode ? [ criteria ] : criteria; diff --git a/app/service/qimenMethods/order.js b/app/service/qimenMethods/order.js index 02f2287..7161acd 100644 --- a/app/service/qimenMethods/order.js +++ b/app/service/qimenMethods/order.js @@ -94,9 +94,8 @@ class orderServer extends MainService { switch (orderType.method) { case 'ORDER': return this.success('取消订单成功'); - break; - case 'RK' : - console.log(data, info); + case 'RK': + { const existingOrder = await ctx.model.EntryOrder.findOne({ where: { entry_order_code: data.request.orderCode, @@ -112,39 +111,30 @@ class orderServer extends MainService { return this.success('取消入库单成功'); } return this.fail('未找到对应的入库单'); - break; - case 'CK' : + } + case 'CK': return this.fail('取消出库单未开发完成'); - break; - case 'JG' : + case 'JG': return this.fail('取消加工单未开发完成'); - break; case 'BACKORDER': return this.fail('取消退货单未开发完成'); - break; default: return this.fail(`未识别的作业类型${orderType.method}`, {}); } } async pending(data) { - console.log(data); const orderType = this.orderType[data.request.orderType]; switch (orderType.method) { case 'ORDER': return this.fail('锁定订单未开发完成'); - break; - case 'RK' : + case 'RK': return this.fail('锁定入库单未开发完成'); - break; - case 'CK' : + case 'CK': return this.fail('锁定出库单未开发完成'); - break; - case 'JG' : + case 'JG': return this.fail('锁定加工单未开发完成'); - break; case 'BACKORDER': return this.fail('锁定退货单未开发完成'); - break; default: return this.fail(`未识别的作业类型${orderType.method}`, {}); } diff --git a/app/service/qimenMethods/returnorder.js b/app/service/qimenMethods/returnorder.js index af8d247..d271ad5 100644 --- a/app/service/qimenMethods/returnorder.js +++ b/app/service/qimenMethods/returnorder.js @@ -6,13 +6,13 @@ class returnorderServer extends MainService { /* 退货入库创建接口 */ - async create(data) { + async create() { return this.fail('接口未完善', { result: 'singleitemServer', storeId: this.storeId }); } /* 退货入库查询接口 */ - async query(data) { + async query() { return this.fail('接口未完善', { result: 'singleitemServer', storeId: this.storeId }); } } diff --git a/app/service/qimenMethods/singleitem.js b/app/service/qimenMethods/singleitem.js index f14c2f9..1bd411e 100644 --- a/app/service/qimenMethods/singleitem.js +++ b/app/service/qimenMethods/singleitem.js @@ -4,11 +4,8 @@ const MainService = require('../main'); class singleitemServer extends MainService { async synchronize(data) { - const { app } = this; try { - console.log('data', data); const stockData = await this.ctx.service.systems.stockStore.initQimenStockData(data.request, this.appKey, this.storeId, this.warehouseId); - console.log('stockData', stockData); const result = await await this.ctx.service.systems.stockStore.create(stockData); return this.success('同步完成', { itemId: result.id }); } catch (error) { diff --git a/app/service/qimenMethods/stockout.js b/app/service/qimenMethods/stockout.js index 9eb0827..a5fdb49 100644 --- a/app/service/qimenMethods/stockout.js +++ b/app/service/qimenMethods/stockout.js @@ -5,7 +5,9 @@ const MainService = require('../main'); class stockoutServer extends MainService { async create(data) { - const { app } = this; + const { app, ctx, appKey, storeId, warehouseId, customerId, warehouseCode } = this; + const fail = this.fail.bind(this); + const success = this.success.bind(this); let totalOrderLines = data.request.deliveryOrder.totalOrderLines || 0; @@ -13,7 +15,6 @@ class stockoutServer extends MainService { if (orderLine.orderLineNo) { orderLine = [ orderLine ]; } - const isSingle = totalOrderLines ? 0 : 1; totalOrderLines = totalOrderLines || orderLine.length; const errors = []; const items = []; @@ -33,39 +34,37 @@ class stockoutServer extends MainService { wms_stock.item_id = orderLine[i].itemId; items.push(wms_stock); } - console.log('出库单参数:', data.request.deliveryOrder, this.appKey, this.storeId, this.warehouseId, totalOrderLines, 'QM', this.customerId, this.warehouseCode); - console.log('出库单明细:', items); if (errors.length > 0) { return this.fail('创建入库单失败,失败原因:\n' + errors.join('\n')); } - /* const order = await this.ctx.service.systems.deliveryOrder.tryCreatedeliveryOrder(data.request.deliveryOrder,this.appKey, this.storeId, this.warehouseId,totalOrderLines,"QM",this.customerId,this.warehouseCode); - console.log("入库单参数",order); - if(!order.success){ - return this.fail("创建入库单失败,失败原因:\n"+order.error); - } - const orderId = order.deliveryOrderId; - for (var i = 0; i < items.length; i++) { - const item = items[i]; - let res = await this.ctx.service.systems.deliveryOrder.addItems(item,orderId); - console.log("“添加商品返回信息",res); - if(!res.success){ - errors.push(`SKU${item.itemId}商品《${item.itemName}》编码《${item.itemCode}》入库失败,错误信息:${res.error}`); - } - } - if(errors.length>0){ - await app.model.deliveryOrder.delete(orderId);//失败删除; - return this.fail("创建入库单失败,失败原因:\n"+errors.join("\n")); - } - const lineCount = await this.ctx.service.systems.deliveryOrder.getLineCount(orderId);//获取接收行数 - if(lineCount==totalOrderLines){//所有行数接收完成 - await this.ctx.service.systems.deliveryOrder.received(orderId,this.warehouseId,this.storeId);//接收完成 - return this.success("入库单接收完毕",{deliveryOrderId:orderId}); - }*/ - return this.success('入库单接收中'); + const order = await ctx.service.systems.deliveryOrder.tryCreatedeliveryOrder(data.request.deliveryOrder, appKey, storeId, warehouseId, totalOrderLines, 'QM', customerId, warehouseCode); + if (!order.success) { + return fail('创建入库单失败,失败原因:\n' + order.error); + } + const orderId = order.deliveryOrderId; + for (let i = 0; i < items.length; i++) { + const item = items[i]; + const res = await ctx.service.systems.deliveryOrder.addItems(item, orderId); + if (!res.success) { + errors.push(`SKU${item.itemId}商品《${item.itemName}》编码《${item.itemCode}》入库失败,错误信息:${res.error}`); + } + } + if (errors.length > 0) { + // 失败删除; + await ctx.model.deliveryOrder.delete(orderId); + return fail('创建入库单失败,失败原因:\n' + errors.join('\n')); + } + const lineCount = await ctx.service.systems.deliveryOrder.getLineCount(orderId); // 获取接收行数 + // 所有行数接收完成 + if (lineCount === totalOrderLines) { + await ctx.service.systems.deliveryOrder.received(orderId, warehouseId, storeId); // 接收完成 + return success('入库单接收完毕', { deliveryOrderId: orderId }); + } + return success('入库单接收中'); } - async query(data) { - console.log(data); - return this.fail('接口未完善'); + async query() { + const { fail } = this; + return fail('接口未完善'); } } diff --git a/app/service/qimenMethods/taobao/qimen/service.js b/app/service/qimenMethods/taobao/qimen/service.js index 5721bec..4e5dab9 100644 --- a/app/service/qimenMethods/taobao/qimen/service.js +++ b/app/service/qimenMethods/taobao/qimen/service.js @@ -1,14 +1,17 @@ 'use strict'; -const MainService = require(`${APP_ROOT}/app/service/main`); +const MainService = require('../../../main'); class serviceServer extends MainService { + /** + * @param {*} data 奇门心跳传入解构 + * @return {Promise} 返回心跳信息 + */ async heartbeat(data) { - console.log(data); if (data?.request?.serialNumber) { - return this.success(new Date().format(), { code: data.request.serialNumber }); + return this.success(this.app.formatDate(new Date()), { code: data.request.serialNumber }); } - return this.fail(new Date().format(), { code: 0 }); + return this.fail(this.app.formatDate(new Date()), { code: 0 }); } } diff --git a/app/service/system.js b/app/service/system.js index 3b1ccad..b3aed28 100644 --- a/app/service/system.js +++ b/app/service/system.js @@ -1,7 +1,6 @@ 'use strict'; const Service = require('egg').Service; -const { XMLParser } = require('fast-xml-parser'); const ALLOWED_PLATFORMS = new Set([ 'web', 'pda', 'app', 'wx', 'miniprogram', 'other' ]); // project: all=全部, warehouse=仓库, store=货主, tms=物流 @@ -10,8 +9,6 @@ const ALLOWED_PROJECTS = new Set([ 'all', 'warehouse', 'store', 'tms', 'wms', 's class systemService extends Service { async callMethod(className, actionName, requestData, authHeader) { try { - - // 构建服务类路径 const servicePath = `${className}`; const classs = servicePath.split('.'); @@ -41,7 +38,7 @@ class systemService extends Service { // 调用方法 const authPass = await serviceInstance.checkAuth(servicePath, actionName, authHeader); const isLog = authPass.isLog; - if (authPass.status == 200) { + if (authPass.status === 200) { result.data = await serviceInstance[actionName](requestData); result.status = 200; diff --git a/app/service/systemMethods/config.js b/app/service/systemMethods/config.js index fd57921..849e9b0 100644 --- a/app/service/systemMethods/config.js +++ b/app/service/systemMethods/config.js @@ -12,7 +12,6 @@ class configService extends MainService { async list() { const { ctx, - app, } = this; const user = ctx.user; const result = { diff --git a/app/service/systemMethods/index.js b/app/service/systemMethods/index.js index f9841c9..82f4f68 100644 --- a/app/service/systemMethods/index.js +++ b/app/service/systemMethods/index.js @@ -6,9 +6,9 @@ class indexService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = 'getI18nMessage,putI18nCollect'; - const _noNeedRight = 'getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getCOSUploadConfig,uploadSuccessNotify,getMessageDetail,searchSpace'; + const _noNeedRight = 'getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getCOSUploadConfig,uploadSuccessNotify,getMessageDetail,searchSpace,listInterfaceTypes'; const _noNeedLog = '*'; - const _noNeedAuth = 'getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getMessageDetail,searchSpace'; + const _noNeedAuth = 'getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getMessageDetail,searchSpace,listInterfaceTypes'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } async fastWhereTree(data) { @@ -17,7 +17,7 @@ class indexService extends MainService { const result = await service.systems.fastWhere.getTreeByType(type); return this.success('ok', { presetTree: result, code: 200 }); } - async loadStores(data) { + async loadStores() { const { service } = this; const result = await service.systems.store.loadStores(); return this.success('ok', { stores: result, code: 200 }); @@ -276,7 +276,7 @@ class indexService extends MainService { /** * 从键名提取模块 - * @param keyName + * @param {string} keyName 键名 */ extractModule(keyName) { if (!keyName) return 'common'; @@ -294,8 +294,8 @@ class indexService extends MainService { /** * 尝试自动翻译新键值(可选功能) - * @param project - * @param targetLanguage + * @param {string} project 项目 + * @param {string} targetLanguage 目标语言 */ async tryAutoTranslateNewKeys(project, targetLanguage) { const { ctx } = this; @@ -337,7 +337,7 @@ class indexService extends MainService { // 批量创建未翻译的记录 const createPromises = []; - for (const [ keyId, chineseText ] of Object.entries(chineseTranslations)) { + for (const [ keyId ] of Object.entries(chineseTranslations)) { if (!existingKeyIds.has(parseInt(keyId))) { createPromises.push( ctx.model.I18nTranslation.create({ @@ -366,7 +366,27 @@ class indexService extends MainService { const result = await service.systems.space.searchSpace(data); return this.success('ok', result); } - async getExpressList(data) { + async listInterfaceTypes() { + const { ctx } = this; + const rows = await ctx.model.InterfaceType.findAll({ + where: { is_enabled: 1, is_store: 1 }, + attributes: [ 'id', 'interface_code', 'interface_name', 'interface_category', 'description', 'is_enabled' ], + order: [[ 'id', 'ASC' ]], + }); + const list = rows.map(row => { + const item = row.get({ plain: true }); + return { + id: Number(item.id || 0), + interface_code: item.interface_code || '', + interface_name: item.interface_name || '', + interface_category: item.interface_category || '', + description: item.description || '', + is_enabled: Number(item.is_enabled || 0), + }; + }); + return this.success('ok', { list, total: list.length, code: 200 }); + } + async getExpressList() { return this.success('ok', { data: this.app.config.expressList, code: 200 }); } diff --git a/app/service/systemMethods/print.js b/app/service/systemMethods/print.js index 302f241..7195169 100644 --- a/app/service/systemMethods/print.js +++ b/app/service/systemMethods/print.js @@ -32,7 +32,6 @@ class PrintService extends MainService { const { ctx } = this; const warehouseId = ctx.user.store_id; const { printer, type, template, data, computerId, timestamp, count } = _data; - console.log('send to computer', warehouseId, printer, type, template, data, computerId, timestamp, count); // 生成打印编号并记录到数据库 const printRecord = await ctx.model.PrintRecord.create({ warehouse_id: warehouseId, @@ -52,12 +51,10 @@ class PrintService extends MainService { let content = item.content; for (const key in data) { - console.log('正在匹配字段:', key, '与', item.field_code); if (String(item.field_code) === key) { content = data[key]; } } - console.log('转后的内容:', content); switch (item.type) { case 'text': htm += `
{ const componentKey = `printer:${computers[i].id}:name:${component.name}:status`; const componentInfo = await this.app.redis.get('printer').get(componentKey); - console.log('componentKey and componentInfo', componentKey, componentInfo); if (componentInfo && componentInfo === 'connected') { component.is_online = 1; } @@ -389,7 +380,6 @@ class PrintService extends MainService { const { id } = data; if (!id) return this.fail('参数错误', 1001); const printerListResult = await this.app.redis.get('printer').get(`printer:${id}:printerList`); - console.log('getComputerPrinter printerListResult', printerListResult); const printerList = JSON.parse(printerListResult); let printers = []; if (!printerList || !printerList.data || printerList.data.length === 0) { diff --git a/app/service/systemMethods/setting/account.js b/app/service/systemMethods/setting/account.js index a1be451..9230e74 100644 --- a/app/service/systemMethods/setting/account.js +++ b/app/service/systemMethods/setting/account.js @@ -26,7 +26,7 @@ class accountService extends MainService { /** * 账号列表。 - * @param {*} data + * @param {Object} data 请求体 */ async list(data = {}) { const { service } = this; @@ -64,7 +64,7 @@ class accountService extends MainService { /** * 新增工号。 - * @param {*} data + * @param {Object} data 请求体 */ async add(data = {}) { return this.callSystemAccount('add', data, '添加工号失败'); @@ -72,7 +72,7 @@ class accountService extends MainService { /** * 删除工号。 - * @param {*} data + * @param {Object} data 请求体 */ async delete(data = {}) { return this.callSystemAccount('delete', data, '删除工号失败'); @@ -80,7 +80,7 @@ class accountService extends MainService { /** * 更新工号。 - * @param {*} data + * @param {Object} data 请求体 */ async update(data = {}) { return this.callSystemAccount('update', data, '更新工号失败'); @@ -88,7 +88,7 @@ class accountService extends MainService { /** * 为其他账号获取微信绑定码。 - * @param {*} data + * @param {Object} data 请求体 */ async getBindWechatCode(data = {}) { return this.callSystemAccount('getBindWechatCode', data, '获取账号绑定微信码失败'); @@ -96,7 +96,7 @@ class accountService extends MainService { /** * 为其他账号解绑微信。 - * @param {*} data + * @param {Object} data 请求体 */ async unbindWechat(data = {}) { return this.callSystemAccount('unbindWechat', data, '解绑账号微信失败'); diff --git a/app/service/systemMethods/setting/permission.js b/app/service/systemMethods/setting/permission.js index c6159ee..66a9a63 100644 --- a/app/service/systemMethods/setting/permission.js +++ b/app/service/systemMethods/setting/permission.js @@ -26,7 +26,7 @@ class permissionService extends MainService { /** * 权限列表。 - * @param {*} data + * @param {Object} data 请求体 */ async list(data = {}) { return this.callSystemPermission('list', data, '获取权限列表失败'); @@ -34,7 +34,7 @@ class permissionService extends MainService { /** * 新增权限。 - * @param {*} data + * @param {Object} data 请求体 */ async add(data = {}) { return this.callSystemPermission('add', data, '新增权限失败'); @@ -42,7 +42,7 @@ class permissionService extends MainService { /** * 删除权限。 - * @param {*} data + * @param {Object} data 请求体 */ async delete(data = {}) { return this.callSystemPermission('delete', data, '删除权限失败'); @@ -50,7 +50,7 @@ class permissionService extends MainService { /** * 更新权限。 - * @param {*} data + * @param {Object} data 请求体 */ async update(data = {}) { return this.callSystemPermission('update', data, '更新权限失败'); diff --git a/app/service/systemMethods/setting/printTemplate.js b/app/service/systemMethods/setting/printTemplate.js index 3f545ab..67f6ed1 100644 --- a/app/service/systemMethods/setting/printTemplate.js +++ b/app/service/systemMethods/setting/printTemplate.js @@ -11,13 +11,12 @@ class printTemplateService extends MainService { const _noNeedAuth = 'list,save,create,delete,listTemplatesByType'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } - async list(data) { + async list() { const { service } = this; const result = await service.systems.setting.printTemplate.getTree(); return this.success('ok', { presetTree: result, code: 200 }); } async save(data) { - console.log('接收到保存请求:', data); const { service } = this; const result = await service.systems.setting.printTemplate.save(data); return this.success('ok', result); @@ -70,7 +69,6 @@ class printTemplateService extends MainService { } async listTemplatesByType(data) { const { service } = this; - console.log('接收到根据业务类型查询模板请求:', data); const { businessType } = data; if (!businessType) { throw new Error('缺少业务类型参数'); diff --git a/app/service/systemMethods/setting/role.js b/app/service/systemMethods/setting/role.js index f036b54..7fa3469 100644 --- a/app/service/systemMethods/setting/role.js +++ b/app/service/systemMethods/setting/role.js @@ -26,26 +26,23 @@ class roleService extends MainService { /** * 角色列表。 - * @param {*} data + * @param {*} data 请求参数 */ async list(data = {}) { return this.callSystemRole('list', data, '获取角色列表失败'); } /** -<<<<<<< HEAD * 角色权限列表(兼容旧入口)。 - * @param {*} data + * @param {*} data 请求参数 */ async permission(data = {}) { return this.callSystemRole('permission', data, '获取角色权限列表失败'); } /** -======= ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 * 新增角色。 - * @param {*} data + * @param {*} data 请求参数 */ async add(data = {}) { return this.callSystemRole('add', data, '新增角色失败'); @@ -53,7 +50,7 @@ class roleService extends MainService { /** * 删除角色。 - * @param {*} data + * @param {*} data 请求参数 */ async delete(data = {}) { return this.callSystemRole('delete', data, '删除角色失败'); @@ -61,7 +58,7 @@ class roleService extends MainService { /** * 更新角色。 - * @param {*} data + * @param {*} data 请求参数 */ async update(data = {}) { return this.callSystemRole('update', data, '更新角色失败'); diff --git a/app/service/systemMethods/setting/store_warehouse.js b/app/service/systemMethods/setting/store_warehouse.js index c6442c6..3d19407 100644 --- a/app/service/systemMethods/setting/store_warehouse.js +++ b/app/service/systemMethods/setting/store_warehouse.js @@ -2,59 +2,13 @@ const MainService = require('../../main'); -class storeWarehouseService extends MainService { +// 旧兼容入口 `setting.store_warehouse.*` 已下线; +// 保留空服务壳体,确保调用时在 dispatcher 层直接返回“方法不存在”。 +class StoreWarehouseLegacyService extends MainService { constructor(ctx) { super(ctx); - const _noNeedLogin = ''; - const _noNeedRight = 'list,sign,unbind,rename'; - const _noNeedLog = '*'; - const _noNeedAuth = 'list,sign,unbind,rename'; - this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); - } - - async callSystemStoreWarehouse(methodName, data, defaultMessage) { - const { service } = this; - try { - const result = await service.systems.storeWarehouse[methodName](data); - return this.success('ok', result); - } catch (error) { - return this.fail(error.message || defaultMessage, { - code: Number(error.code) || 500, - }); - } - } - - /** - * 仓库-货主签约列表。 - * @param {*} data - */ - async list(data = {}) { - return this.callSystemStoreWarehouse('list', data, '获取签约列表失败'); - } - - /** - * 建立/更新签约关系。 - * @param {*} data - */ - async sign(data = {}) { - return this.callSystemStoreWarehouse('sign', data, '签约失败'); - } - - /** - * 修改当前主体对签约对象的名称/备注。 - * @param {*} data - */ - async rename(data = {}) { - return this.callSystemStoreWarehouse('rename', data, '修改签约名称失败'); - } - - /** - * 解除签约关系。 - * @param {*} data - */ - async unbind(data = {}) { - return this.callSystemStoreWarehouse('unbind', data, '解除签约失败'); + this.systemInit('', '', '*', ''); } } -module.exports = storeWarehouseService; +module.exports = StoreWarehouseLegacyService; diff --git a/app/service/systemMethods/stock/warehouse.js b/app/service/systemMethods/stock/warehouse.js index 894b83a..5fdf65a 100644 --- a/app/service/systemMethods/stock/warehouse.js +++ b/app/service/systemMethods/stock/warehouse.js @@ -6,9 +6,9 @@ class WarehouseService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'list,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,getUnitList,createUnit,checkItemCodeUnique,deleteUnit,createProhibited,deleteProhibited,search'; - const _noNeedLog = 'list,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,checkItemCodeUnique,getUnitList,search'; - const _noNeedAuth = 'list,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,checkItemCodeUnique,getUnitList,search'; + const _noNeedRight = 'list,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,getUnitList,createUnit,checkItemCodeUnique,deleteUnit,createProhibited,deleteProhibited,search,getStockDetail'; + const _noNeedLog = 'list,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,checkItemCodeUnique,getUnitList,search,getStockDetail'; + const _noNeedAuth = 'list,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,checkItemCodeUnique,getUnitList,search,getStockDetail'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -154,7 +154,6 @@ class WarehouseService extends MainService { async checkItemCodeUnique(data) { const { ctx, service } = this; const { id, item_code, store_id } = data; - console.log(data); try { if (!item_code || !store_id) { return this.fail('参数错误'); @@ -172,7 +171,6 @@ class WarehouseService extends MainService { * @return {Promise} data 为日志分页结果 */ async queryStockLogs(data) { - console.log('请求'); const { ctx } = this; try { const { service } = this; @@ -180,7 +178,6 @@ class WarehouseService extends MainService { const result = await service.systems.operationLog.queryStockLogs(data); return this.success('ok', { data: result, code: 200 }); } catch (e) { - console.log(e); return this.success(e.message, { code: 200 }); } } @@ -196,7 +193,6 @@ class WarehouseService extends MainService { const result = await service.systems.stockStore.handleBatchDelete(data); return this.success(result.message, { data: result.data, code: result.code }); } catch (e) { - console.log(e); return this.success(e.message, { code: 200 }); } } @@ -212,7 +208,6 @@ class WarehouseService extends MainService { const result = await service.systems.stockStore.deleteUnit(data); return this.success(result.message, { data: result.data, code: result.code }); } catch (e) { - console.log(e); return this.success(e.message, { code: 200 }); } } @@ -228,7 +223,6 @@ class WarehouseService extends MainService { const result = await service.systems.stockStore.deleteProhibited(data); return this.success(result.message, { data: result.data, code: result.code }); } catch (e) { - console.log(e); return this.success(e.message, { code: 200 }); } } @@ -244,7 +238,6 @@ class WarehouseService extends MainService { const result = await service.systems.stockStore.handleBatchChange(data); return this.success(result.message, { data: result.data, code: result.code }); } catch (e) { - console.log(e); return this.success(e.message, { code: 405 }); } } @@ -254,7 +247,6 @@ class WarehouseService extends MainService { * @return {Promise} data 为单位数组 */ async getStockUnits() { - console.log('query_getStockUnits'); const { ctx } = this; const warehouse_id = ctx.user.store_id; @@ -275,7 +267,6 @@ class WarehouseService extends MainService { }); return this.success('ok', { data: units, code: 200 }); } catch (error) { - console.log(error); return this.fail(error.message); } } @@ -285,7 +276,6 @@ class WarehouseService extends MainService { * @return {Promise} data 为单位数组 */ async getUnitList() { - console.log('query_getUnitList'); const { ctx } = this; const warehouse_id = ctx.user.store_id; @@ -303,7 +293,6 @@ class WarehouseService extends MainService { }); return this.success('ok', { data: units, code: 200 }); } catch (error) { - console.log(error); return this.fail(error.message); } } @@ -315,7 +304,6 @@ class WarehouseService extends MainService { * @return {Promise} 成功返回 success;参数校验失败时直接写入 ctx.body */ async createProhibited(data) { - console.log('createProhibited', data); const { ctx } = this; const warehouse_id = ctx.user.store_id || null; const { name } = data; @@ -385,7 +373,6 @@ class WarehouseService extends MainService { }); return this.success('添加成功', { code: 200 }); } catch (error) { - console.log(error); return this.success('创建违禁品类型失败', { code: 405 }); } } @@ -478,6 +465,19 @@ class WarehouseService extends MainService { const result = await service.systems.stockStore.search(data); return this.success('ok', result); } + + /** + * 查询商品库存明细(按库位/批次维度展示库存分布)。 + * @param {Object} data 请求体 + * @param {number} data.stock_id 商品库存ID(stock_warehouse.id) + * @param {Object} [data.pagination] 分页参数 + * @return {Promise} data 为库存明细分页结果 + */ + async getStockDetail(data) { + const { service } = this; + const result = await service.systems.stockStore.getStockDetail(data); + return this.success('ok', result); + } } module.exports = WarehouseService; diff --git a/app/service/systemMethods/storage/delivery.js b/app/service/systemMethods/storage/delivery.js new file mode 100644 index 0000000..90dda57 --- /dev/null +++ b/app/service/systemMethods/storage/delivery.js @@ -0,0 +1,35 @@ +'use strict'; + +const MainService = require('../../main'); + +/** + * 系统方法层:storage.delivery(已废弃)。 + */ +class StorageDeliveryService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = ''; + const _noNeedLog = ''; + const _noNeedAuth = ''; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + buildRemovedResponse() { + return this.fail('方法已移除', { code: 410 }); + } + + async list() { + return this.buildRemovedResponse(); + } + + async toOrder() { + return this.buildRemovedResponse(); + } + + async listItems() { + return this.buildRemovedResponse(); + } +} + +module.exports = StorageDeliveryService; diff --git a/app/service/systemMethods/storage/entry.js b/app/service/systemMethods/storage/entry.js index 0880a02..8350116 100644 --- a/app/service/systemMethods/storage/entry.js +++ b/app/service/systemMethods/storage/entry.js @@ -9,9 +9,9 @@ class entryService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'list,get,create,addDetail,deleteDetail,detailChange,cancel,completeEntry'; - const _noNeedLog = 'list,get,addDetail,deleteDetail,detailChange'; - const _noNeedAuth = 'list,get,create,addDetail,deleteDetail,detailChange,cancel,completeEntry'; + const _noNeedRight = 'list,get,cancel,completeEntry'; + const _noNeedLog = 'list,get'; + const _noNeedAuth = 'list,get,cancel,completeEntry'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -50,50 +50,6 @@ class entryService extends MainService { return this.success('ok', result); } - /** - * 新建入库单。 - * @param {Object} data 请求体 - * @return {Promise} 统一 success 包装 - */ - async create(data = {}) { - const { service } = this; - const result = await service.systems.storage.entry.create(data); - return this.success('ok', result); - } - - /** - * 新增入库明细。 - * @param {Object} data 请求体 - * @return {Promise} 统一 success 包装 - */ - async addDetail(data = {}) { - const { service } = this; - const result = await service.systems.storage.entry.addDetail(data); - return this.success('ok', result); - } - - /** - * 删除入库明细。 - * @param {Object} data 请求体 - * @return {Promise} 统一 success 包装 - */ - async deleteDetail(data = {}) { - const { service } = this; - const result = await service.systems.storage.entry.deleteDetail(data); - return this.success('ok', result); - } - - /** - * 修改入库明细。 - * @param {Object} data 请求体 - * @return {Promise} 统一 success 包装 - */ - async detailChange(data = {}) { - const { service } = this; - const result = await service.systems.storage.entry.detailChange(data); - return this.success('ok', result); - } - /** * 作废入库单。 * @param {Object} data 请求体 diff --git a/app/service/systemMethods/storage/inventory.js b/app/service/systemMethods/storage/inventory.js new file mode 100644 index 0000000..b3f0df8 --- /dev/null +++ b/app/service/systemMethods/storage/inventory.js @@ -0,0 +1,91 @@ +'use strict'; + +const MainService = require('../../main'); + +/** + * 系统方法层:storage.inventory(库存操作接口包装层)。 + * 职责:统一包装库存操作接口,调用底层 systems/storage/inventory service。 + */ +class InventoryMethodService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'matchPutaway,list'; + const _noNeedLog = 'list'; + const _noNeedAuth = 'list'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 收货单快捷入库上架。 + * @param {Object} data 请求体 + * @param {number} data.receiving_id 收货单ID + * @return {Promise} 统一 success 包装 + */ + async quickPutaway(data = {}) { + const { service } = this; + const result = await service.systems.storage.inventory.quickPutaway(data); + return this.success('ok', result); + } + + /** + * 匹配入库:收货单与入库单按商品匹配入库。 + * @param {Object} data 请求体 + * @param {number[]} data.receiving_ids 收货单ID列表 + * @param {number[]} data.entry_order_ids 入库单ID列表 + * @return {Promise} 统一 success 包装 + */ + async matchPutaway(data = {}) { + const { service } = this; + const result = await service.systems.storage.inventory.matchPutaway(data); + return this.success('ok', result); + } + + /** + * 移库(库位转移):将单条库存从一个库位移动到另一个库位。 + * @param {Object} data 请求体 + * @param {number} data.storage_id 库存记录ID(必填) + * @param {number} data.target_space_id 目标库位ID(必填) + * @param {number} [data.quantity] 移库数量(可选,默认全部移动) + * @return {Promise} 统一 success 包装 + */ + async transferLocation(data = {}) { + const { service } = this; + const result = await service.systems.storage.inventory.transferLocation(data); + return this.success('ok', result); + } + + /** + * 按库位+商品维度移库:自动查找该库位下该商品的所有库存记录,合并移动到目标库位。 + * @param {Object} data 请求体 + * @param {number} data.space_id 原库位ID(必填) + * @param {number} data.stock_id 商品SKU ID(必填) + * @param {number} data.target_space_id 目标库位ID(必填) + * @param {number} data.quantity 移库数量(必填) + * @return {Promise} 统一 success 包装 + */ + async transferByProduct(data = {}) { + const { service } = this; + const result = await service.systems.storage.inventory.transferByProduct(data); + return this.success('ok', result); + } + + /** + * 库存列表查询(查 wms_storage),支持 where 条件、分页、排序、批次分组。 + * @param {Object} data 请求体 + * @param {Object} [data.where] 查询条件 + * @param {Object} [data.pagination] 分页参数 { page, pageSize } + * @param {Object} [data.sort] 排序参数 { sortField, sortOrder } + * @param {boolean} [data.group_by_batch=false] 是否按批次查询 + * @return {Promise} 统一 success 包装 + */ + async list(data = {}) { + const { service } = this; + const { pagination, sort, group_by_batch } = data; + const { where } = this.prepareWhereContext(data); + const result = await service.systems.storage.inventory.getInventoryList(where, pagination, sort, group_by_batch); + return this.success('ok', result); + } +} + +module.exports = InventoryMethodService; diff --git a/app/service/systemMethods/storage/stockout.js b/app/service/systemMethods/storage/stockout.js new file mode 100644 index 0000000..7a132d4 --- /dev/null +++ b/app/service/systemMethods/storage/stockout.js @@ -0,0 +1,79 @@ +'use strict'; + +const OrderBaseService = require('../order/base'); + +/** + * 系统方法层:storage.stockout(非订单出库单接口包装层)。 + */ +class StorageStockoutService extends OrderBaseService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list,toOrder,listItems'; + const _noNeedLog = 'list,toOrder,listItems'; + const _noNeedAuth = 'list,toOrder,listItems'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + async list(data = {}) { + try { + const warehouseId = this.ensureWarehouseId(data); + const { DeliveryModel } = await this.getOrderModels(warehouseId); + this.prepareWhereContext(data); + const whereData = this.ctx.where || {}; + const where = this.buildWhere(whereData, warehouseId); + const { page, pageSize, offset } = this.getPagination(data.pagination); + + const result = await DeliveryModel.findAndCountAll({ + where, + offset, + limit: pageSize, + order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]], + raw: true, + }); + + return this.success('ok', { + data: this.buildListData(result.rows, result.count, page, pageSize), + code: 200, + }); + } catch (error) { + return this.fail(error.message, { code: 500 }); + } + } + + async toOrder() { + return this.fail('占位接口,暂未开放', { code: 405, placeholder: true }); + } + + async listItems(data = {}) { + try { + const warehouseId = this.ensureWarehouseId(data); + const { DeliveryModel, OrderItemsModel } = await this.getOrderModels(warehouseId); + const where = this.getOrderLocatorWhere(data, warehouseId); + + const order = await DeliveryModel.findOne({ + where, + attributes: [ 'id', 'delivery_order_code' ], + raw: true, + }); + if (!order) { + return this.fail('订单不存在', { code: 404 }); + } + + const items = await OrderItemsModel.findAll({ + where: { order_id: order.id }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + return this.success('ok', { + data: { order, items }, + code: 200, + }); + } catch (error) { + return this.fail(error.message, { code: 500 }); + } + } +} + +module.exports = StorageStockoutService; diff --git a/app/service/systemMethods/storage/transaction.js b/app/service/systemMethods/storage/transaction.js new file mode 100644 index 0000000..ff0781c --- /dev/null +++ b/app/service/systemMethods/storage/transaction.js @@ -0,0 +1,33 @@ +'use strict'; + +const MainService = require('../../main'); + +class StorageTransactionService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list'; + const _noNeedLog = 'list'; + const _noNeedAuth = 'list'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 出入库记录列表查询,支持 where 条件、分页、排序。 + * @param {Object} data 请求体 + * @param {Object} [data.where] 查询条件 + * @param {Object} [data.pagination] 分页参数 { page, pageSize } + * @param {Object} [data.sort] 排序参数 { sortField, sortOrder } + * @param {boolean} [data.group_by_batch=false] 是否按批次查询明细 + * @return {Promise} 统一 success 包装 + */ + async list(data = {}) { + const { service } = this; + const { pagination, sort, group_by_batch } = data; + const { where } = this.prepareWhereContext(data); + const result = await service.systems.stockTransaction.list(where, pagination, sort, group_by_batch); + return this.success('ok', result); + } +} + +module.exports = StorageTransactionService; diff --git a/app/service/systemMethods/store.js b/app/service/systemMethods/store.js index 25b66ff..67bcfe4 100644 --- a/app/service/systemMethods/store.js +++ b/app/service/systemMethods/store.js @@ -35,11 +35,6 @@ class storeService extends MainService { const result = await service.systems.store.getStoreRoles(data); return this.success('ok', result); } - async getStoreRoles(data) { - const { service } = this; - const result = await service.systems.store.getStoreRoles(data); - return this.success('ok', result); - } async auditApply(data) { const { service } = this; const result = await service.systems.store.auditApply(data); diff --git a/app/service/systemMethods/storeWarehouse.js b/app/service/systemMethods/storeWarehouse.js index 761210a..db6e15f 100644 --- a/app/service/systemMethods/storeWarehouse.js +++ b/app/service/systemMethods/storeWarehouse.js @@ -1,65 +1,14 @@ 'use strict'; const MainService = require('../main'); +const StoreWarehouseStoreService = require('./storeWarehouse/store'); -class storeWarehouseAliasService extends MainService { +class StoreWarehouseNamespaceService extends MainService { constructor(ctx) { super(ctx); - const _noNeedLogin = ''; - const _noNeedRight = 'list,sign,unbind,rename,getPolicyConfig,savePolicyConfig,listQimenConfig,saveQimenConfig,deleteQimenConfig'; - const _noNeedLog = '*'; - const _noNeedAuth = 'list,sign,unbind,rename,getPolicyConfig,savePolicyConfig,listQimenConfig,saveQimenConfig,deleteQimenConfig'; - this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); - this.store = this; - } - - async callSystemStoreWarehouse(methodName, data, defaultMessage) { - const { service } = this; - try { - const result = await service.systems.storeWarehouse[methodName](data); - return this.success('ok', result); - } catch (error) { - return this.fail(error.message || defaultMessage, { - code: Number(error.code) || 500, - }); - } - } - - async list(data = {}) { - return this.callSystemStoreWarehouse('list', data, '获取签约列表失败'); - } - - async sign(data = {}) { - return this.callSystemStoreWarehouse('sign', data, '签约失败'); - } - - async rename(data = {}) { - return this.callSystemStoreWarehouse('rename', data, '修改签约名称失败'); - } - - async unbind(data = {}) { - return this.callSystemStoreWarehouse('unbind', data, '解除签约失败'); - } - - async getPolicyConfig(data = {}) { - return this.callSystemStoreWarehouse('getPolicyConfig', data, '获取合约策略配置失败'); - } - - async savePolicyConfig(data = {}) { - return this.callSystemStoreWarehouse('savePolicyConfig', data, '保存合约策略配置失败'); - } - - async listQimenConfig(data = {}) { - return this.callSystemStoreWarehouse('listQimenConfig', data, '获取奇门接口配置列表失败'); - } - - async saveQimenConfig(data = {}) { - return this.callSystemStoreWarehouse('saveQimenConfig', data, '保存奇门接口配置失败'); - } - - async deleteQimenConfig(data = {}) { - return this.callSystemStoreWarehouse('deleteQimenConfig', data, '删除奇门接口配置失败'); + this.systemInit('', '', '*', ''); + this.store = new StoreWarehouseStoreService(ctx); } } -module.exports = storeWarehouseAliasService; +module.exports = StoreWarehouseNamespaceService; diff --git a/app/service/systemMethods/storeWarehouse/store.js b/app/service/systemMethods/storeWarehouse/store.js index c012bd3..c4a7635 100644 --- a/app/service/systemMethods/storeWarehouse/store.js +++ b/app/service/systemMethods/storeWarehouse/store.js @@ -1,3 +1,72 @@ 'use strict'; -module.exports = require('../storeWarehouse'); +const MainService = require('../../main'); + +class StoreWarehouseStoreService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list,sign,unbind,rename,getPolicyConfig,getPolicyConfigFields,savePolicyConfig,listApiConfig,saveApiConfig,deleteQimenConfig'; + const _noNeedLog = '*'; + const _noNeedAuth = 'list,sign,unbind,rename,getPolicyConfig,getPolicyConfigFields,savePolicyConfig,listApiConfig,saveApiConfig,deleteQimenConfig'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + async callSystemStoreWarehouse(methodName, data = {}, defaultMessage) { + const { service } = this; + try { + const result = await service.systems.storeWarehouse[methodName](data); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || defaultMessage, { + code: Number(error.code) || 500, + }); + } + } + + async list(data = {}) { + return this.callSystemStoreWarehouse('list', data, '获取签约列表失败'); + } + + async sign(data = {}) { + return this.callSystemStoreWarehouse('sign', data, '签约失败'); + } + + async rename(data = {}) { + return this.callSystemStoreWarehouse('rename', data, '修改签约名称失败'); + } + + async unbind(data = {}) { + return this.callSystemStoreWarehouse('unbind', data, '解除签约失败'); + } + + async adjustPrintQuantity(data = {}) { + return this.callSystemStoreWarehouse('adjustPrintQuantity', data, '人工调整面单余额失败'); + } + + async getPolicyConfig(data = {}) { + return this.callSystemStoreWarehouse('getPolicyConfig', data, '获取合约策略配置失败'); + } + + async getPolicyConfigFields(data = {}) { + return this.callSystemStoreWarehouse('getPolicyConfigFields', data, '获取合约策略字段信息失败'); + } + + async savePolicyConfig(data = {}) { + return this.callSystemStoreWarehouse('savePolicyConfig', data, '保存合约策略配置失败'); + } + + async listApiConfig(data = {}) { + return this.callSystemStoreWarehouse('listApiConfig', data, '获取接口配置列表失败'); + } + + async saveApiConfig(data = {}) { + return this.callSystemStoreWarehouse('saveApiConfig', data, '保存接口配置失败'); + } + + async deleteQimenConfig(data = {}) { + return this.callSystemStoreWarehouse('deleteQimenConfig', data, '删除接口配置失败'); + } +} + +module.exports = StoreWarehouseStoreService; diff --git a/app/service/systemMethods/user.js b/app/service/systemMethods/user.js index 2de6096..b2afa4f 100644 --- a/app/service/systemMethods/user.js +++ b/app/service/systemMethods/user.js @@ -15,7 +15,6 @@ class userService extends MainService { const { service } = this; const { username, password } = data; const result = await service.systems.auth.user.login(username, password); - console.log('result', result); if (result.code) { return this.success('登录成功', result); } @@ -25,7 +24,6 @@ class userService extends MainService { async loginByCode(data) { const { service } = this; const code = typeof data?.code === 'string' ? data.code.trim() : ''; - console.log('code', data.code, code); if (!code) { return this.fail('1111登录失败:缺少登录码 code', { success: false, @@ -56,14 +54,6 @@ class userService extends MainService { } return this.fail('获取微信登录码失败:' + result.message, result); } - async getLoginWechatCode(data) { - const { service } = this; - const result = await service.systems.auth.user.getLoginWechatCode(data); - if (result.code) { - return this.success('获取微信登录码成功', result); - } - return this.fail('获取微信登录码失败:' + result.message, result); - } async unbindWechat(data) { const { service } = this; const result = await service.systems.auth.user.unbindWechat(data); diff --git a/app/service/systemMethods/warehouse.js b/app/service/systemMethods/warehouse.js index e053bb1..2e14924 100644 --- a/app/service/systemMethods/warehouse.js +++ b/app/service/systemMethods/warehouse.js @@ -13,22 +13,20 @@ class warehouseService extends MainService { } async getWarehouseZones() { const { ctx, service } = this; - console.log('获取仓库主体下所有实体仓库'); try { const zones = await service.systems.locationZone.getWarehouseLevelZones(ctx.user.store_id); return this.success('获取成功', { zones, code: 200 }); } catch (error) { - console.log(error); return this.fail('获取失败' + error.message, { code: 0 }); } } /** * 获取仓库树状结构 - * @param data + * @param {Object} data 请求体 */ async getWarehouseTree(data) { - const { ctx, service } = this; + const { service } = this; const { warehouseId } = data; try { @@ -45,7 +43,7 @@ class warehouseService extends MainService { /** * 获取子节点(懒加载) - * @param data + * @param {Object} data 请求体 */ async getChildren(data) { const { ctx, service } = this; @@ -65,10 +63,10 @@ class warehouseService extends MainService { /** * 创建分区 - * @param data + * @param {Object} data 请求体 */ async create(data) { - const { ctx, service } = this; + const { service } = this; try { const result = await service.systems.locationZone.createZone(data); @@ -80,19 +78,18 @@ class warehouseService extends MainService { /** * 更新分区 - * @param datas + * @param {Object} datas 请求体 */ async update(datas) { - const { ctx, service } = this; - console.log('接收的数据', datas); + const { service } = this; const { id } = datas; - const { length, width, height, zone_code, zone_name, x, y, z, direction, rack_columns, rack_levels, rack_rows, cell_width, cell_length, cell_height, aisles } = datas; + const { length, width, height, is_active, zone_code, zone_name, x, y, z, direction, rack_columns, rack_levels, rack_rows, cell_width, cell_length, cell_height, aisles } = datas; try { if (!id) { return this.fail('分区ID不能为空'); } - const result = await service.systems.locationZone.updateZone(parseInt(id), { length, width, height, zone_code, zone_name, x, y, z, direction, rack_columns, rack_levels, rack_rows, cell_width, cell_length, cell_height, aisles }); + const result = await service.systems.locationZone.updateZone(parseInt(id), { length, width, height, is_active, zone_code, zone_name, x, y, z, direction, rack_columns, rack_levels, rack_rows, cell_width, cell_length, cell_height, aisles }); return this.success(result.message, { data: result.data, code: 200 }); } catch (error) { return this.fail(error.message); @@ -101,10 +98,10 @@ class warehouseService extends MainService { /** * 删除分区 - * @param data + * @param {Object} data 请求体 */ async delete(data) { - const { ctx, service } = this; + const { service } = this; const { id } = data; try { @@ -113,20 +110,18 @@ class warehouseService extends MainService { } const result = await service.systems.locationZone.deleteZone(parseInt(id)); - console.log('删除返回', result); return this.success(result.message, { code: 200 }); } catch (error) { - console.log('error', error); return this.fail(error.message); } } /** * 获取分区详情 - * @param data + * @param {Object} data 请求体 */ async detail(data) { - const { ctx, service } = this; + const { service } = this; const { id } = data; try { @@ -140,9 +135,8 @@ class warehouseService extends MainService { } } async checkBarcodeUnique(data) { - const { ctx, service } = this; + const { service } = this; const { id, barcode } = data; - console.log(data); try { if (!id) { return this.fail('库位ID不能为空'); @@ -158,7 +152,7 @@ class warehouseService extends MainService { } /** * 切换分区状态 - * @param data + * @param {Object} data 请求体 */ async toggleActive(data) { const { ctx, service } = this; @@ -181,7 +175,7 @@ class warehouseService extends MainService { /** * 获取分区路径 - * @param data + * @param {Object} data 请求体 */ async getPath(data) { const { ctx, service } = this; @@ -374,7 +368,7 @@ class warehouseService extends MainService { } } async createRackWithSpaces(data) { - const { ctx, app, service } = this; + const { ctx, service } = this; const { id } = data; if (!id) { return this.fail('货架ID不能为空'); @@ -391,34 +385,31 @@ class warehouseService extends MainService { if (!rack) { throw new Error('货架不存在'); } - if (rack.zone_type != 'rack') { + if (rack.zone_type !== 'rack') { throw new Error('仓库元素不为货架,拒绝生成仓位'); } const message = await service.systems.locationZone.generateSpacesForRack(id, rack, transaction); await transaction.commit(); return this.success(message, { code: 200 }); } catch (e) { - console.log('创建错误', e); await transaction.rollback(); return this.fail(e.message, 500); } } async getSpaceInfo(data) { - const { ctx, service } = this; + const { service } = this; const { id } = data; try { const data = await service.systems.locationZone.getSpaceInfo(id); return this.success('获取成功', { data, code: 200 }); } catch (error) { - console.log(error); return this.fail('获取失败' + error.message, { code: 0 }); } } async updateSpaceInfo(data) { - const { ctx, app, service } = this; - console.log('修改的数据', data); + const { ctx, service } = this; const { id } = data; if (!id) { return this.fail('仓位ID不能为空'); diff --git a/app/service/systems/account_platform.js b/app/service/systems/account_platform.js index bcab6b9..fb0fd34 100644 --- a/app/service/systems/account_platform.js +++ b/app/service/systems/account_platform.js @@ -71,7 +71,7 @@ class AccountPlatformService extends Service { * @param {number} accountId - 账号ID * @param {number} accountStoreRoleId - 账号仓库员工关联ID(保持历史参数名兼容) * @param {string} platformCode - 平台编码 - * @return {Promise} + * @return {Promise} 切换结果 */ async switchActiveRole(accountId, accountStoreRoleId, platformCode) { const { ctx } = this; @@ -150,7 +150,7 @@ class AccountPlatformService extends Service { * @param {number} accountId - 账号ID * @param {string} platformCode - 平台编码 * @param {boolean} useCache - 是否使用缓存 - * @return {Promise} + * @return {Promise} 当前激活角色 */ async getActiveRoleByPlatform(accountId, platformCode, useCache = true) { const { ctx, app } = this; @@ -201,7 +201,7 @@ class AccountPlatformService extends Service { * 批量获取账号在多个平台的激活状态 * @param {number} accountId - 账号ID * @param {Array} platformCodes - 平台编码数组 - * @return {Promise} + * @return {Promise} 激活状态映射 */ async getMultiplePlatformActiveRoles(accountId, platformCodes) { const { ctx } = this; @@ -243,7 +243,7 @@ class AccountPlatformService extends Service { /** * 获取账号所有平台的激活状态 * @param {number} accountId - 账号ID - * @return {Promise} + * @return {Promise} 平台激活列表 */ async getAllPlatformActives(accountId) { const { ctx } = this; @@ -274,10 +274,10 @@ class AccountPlatformService extends Service { * 清除平台激活状态 * @param {number} accountId - 账号ID * @param {string} platformCode - 平台编码 - * @return {Promise} + * @return {Promise} 是否清除成功 */ async clearPlatformActive(accountId, platformCode) { - const { ctx, app } = this; + const { ctx } = this; try { const result = await ctx.model.AccountPlatformActive.destroy({ @@ -298,8 +298,8 @@ class AccountPlatformService extends Service { /** * 清理平台缓存 - * @param accountId - * @param platformCode + * @param {number} accountId 账号ID + * @param {string} platformCode 平台编码 * @private */ async clearPlatformCache(accountId, platformCode) { @@ -317,7 +317,7 @@ class AccountPlatformService extends Service { * 获取账号可用的角色列表 * @param {number} accountId - 账号ID * @param {number} storeId - 仓库ID(可选) - * @return {Promise} + * @return {Promise} 角色列表,包含角色信息和所属仓库信息 */ async getAvailableRoles(accountId, storeId = null) { const { ctx } = this; @@ -390,7 +390,7 @@ class AccountPlatformService extends Service { * 根据平台获取账号的当前仓库和角色 * @param {number} accountId - 账号ID * @param {string} platformCode - 平台编码 - * @return {Promise} + * @return {Promise} 当前上下文 */ async getCurrentContext(accountId, platformCode) { const activeRole = await this.getActiveRoleByPlatform(accountId, platformCode); diff --git a/app/service/systems/auth/user.js b/app/service/systems/auth/user.js index 76c94b1..e4db6bb 100644 --- a/app/service/systems/auth/user.js +++ b/app/service/systems/auth/user.js @@ -16,10 +16,6 @@ const WECHAT_LOGIN_EVENT_CHANNEL_PREFIX = 'user:wechat:login:event:'; const WECHAT_LOGIN_CACHE_TTL_SECONDS = 60; class UserService extends Service { - constructor(ctx) { - super(ctx); - } - getCurrentAccountId() { const { ctx } = this; const rawUserId = ctx.userId || (ctx.user && ctx.user.id); @@ -266,7 +262,44 @@ class UserService extends Service { let settled = false; let timer = null; - const cleanup = () => { + function onMessage(messageChannel, message) { + if (messageChannel !== channel) { + return; + } + let eventData = null; + try { + eventData = message ? JSON.parse(message) : null; + } catch (error) { + eventData = { raw: message }; + } + finalize({ + timed_out: false, + reason: 'event', + event: eventData, + }); + } + + function onError(error) { + app.coreLogger.warn(`订阅微信绑定事件失败: ${error.message}`); + finalize({ + timed_out: true, + reason: 'subscribe_error', + }); + } + + function finalize(result) { + if (settled) { + return; + } + settled = true; + if (timer) { + clearTimeout(timer); + } + cleanup(); + resolve(result); + } + + function cleanup() { subscriber.removeListener('message', onMessage); subscriber.removeListener('error', onError); Promise.resolve(subscriber.unsubscribe(channel)).catch(() => null).finally(() => { @@ -282,44 +315,7 @@ class UserService extends Service { subscriber.disconnect(); } }); - }; - - const finalize = result => { - if (settled) { - return; - } - settled = true; - if (timer) { - clearTimeout(timer); - } - cleanup(); - resolve(result); - }; - - const onMessage = (messageChannel, message) => { - if (messageChannel !== channel) { - return; - } - let eventData = null; - try { - eventData = message ? JSON.parse(message) : null; - } catch (error) { - eventData = { raw: message }; - } - finalize({ - timed_out: false, - reason: 'event', - event: eventData, - }); - }; - - const onError = error => { - app.coreLogger.warn(`订阅微信绑定事件失败: ${error.message}`); - finalize({ - timed_out: true, - reason: 'subscribe_error', - }); - }; + } timer = setTimeout(() => { finalize({ @@ -442,11 +438,10 @@ class UserService extends Service { * @param {string} username - 用户名/手机号/邮箱 * @param {string} password - 密码 * @param {string} loginType - 登录类型: username, phone, email, auto - * @param {string} platformCode - 平台编码(web、pda、mini等) * @return {Object} 登录结果 */ async login(username, password, loginType = 'auto') { - const { ctx, app } = this; + const { app } = this; try { // 统一的认证错误信息 @@ -459,7 +454,6 @@ class UserService extends Service { app.coreLogger.warn(`登录失败: 用户不存在 [${username}]`); throw authError; } - console.log('登录获取用户信息', user); // 2. 检查用户状态 try { this.checkUserStatus(user); @@ -640,37 +634,7 @@ class UserService extends Service { let settled = false; let timer = null; - const cleanup = () => { - subscriber.removeListener('message', onMessage); - subscriber.removeListener('error', onError); - Promise.resolve(subscriber.unsubscribe(channel)).catch(() => null).finally(() => { - if (typeof subscriber.quit === 'function') { - Promise.resolve(subscriber.quit()).catch(() => { - if (typeof subscriber.disconnect === 'function') { - subscriber.disconnect(); - } - }); - return; - } - if (typeof subscriber.disconnect === 'function') { - subscriber.disconnect(); - } - }); - }; - - const finalize = result => { - if (settled) { - return; - } - settled = true; - if (timer) { - clearTimeout(timer); - } - cleanup(); - resolve(result); - }; - - const onMessage = (messageChannel, message) => { + function onMessage(messageChannel, message) { if (messageChannel !== channel) { return; } @@ -687,16 +651,46 @@ class UserService extends Service { event: eventData, ye4s_user_id: ye4sUserId, }); - }; + } - const onError = error => { + function onError(error) { app.coreLogger.warn(`订阅微信登录事件失败: ${error.message}`); finalize({ timed_out: true, reason: 'subscribe_error', event: null, }); - }; + } + + function finalize(result) { + if (settled) { + return; + } + settled = true; + if (timer) { + clearTimeout(timer); + } + cleanup(); + resolve(result); + } + + function cleanup() { + subscriber.removeListener('message', onMessage); + subscriber.removeListener('error', onError); + Promise.resolve(subscriber.unsubscribe(channel)).catch(() => null).finally(() => { + if (typeof subscriber.quit === 'function') { + Promise.resolve(subscriber.quit()).catch(() => { + if (typeof subscriber.disconnect === 'function') { + subscriber.disconnect(); + } + }); + return; + } + if (typeof subscriber.disconnect === 'function') { + subscriber.disconnect(); + } + }); + } timer = setTimeout(() => { finalize({ @@ -906,8 +900,8 @@ class UserService extends Service { /** * 获取微信扫码登录码 - * @param {Object} data - * @return {Object} + * @param {Object} data 请求参数 + * @return {Object} 登录码结果 */ async getLoginWechatCode(data = {}) { const { app } = this; @@ -1024,8 +1018,8 @@ class UserService extends Service { /** * 获取微信绑定码(缓存优先,低频复查DB,适配轮询) - * @param {Object} data - * @return {Object} + * @param {Object} data 请求参数 + * @return {Object} 绑定码结果 */ async getBindWechatCode(data = {}) { const accountId = this.getCurrentAccountId(); @@ -1110,8 +1104,8 @@ class UserService extends Service { /** * 根据绑定临时码获取账号ID(供 ye4s 扫码绑定调用) - * @param {Object} data - * @return {Object} + * @param {Object} data 请求参数 + * @return {Object} 账号查询结果 */ async getUserByTempCode(data = {}) { const { ctx, app } = this; @@ -1224,8 +1218,8 @@ class UserService extends Service { /** * 账号绑定:供 ye4s 扫码后回调,按临时码绑定到指定 ye4s_user.id - * @param {Object} data - * @return {Object} + * @param {Object} data 请求参数 + * @return {Object} 绑定结果 */ async bindAccountByTempCode(data = {}) { const { ctx, app } = this; @@ -1343,7 +1337,7 @@ class UserService extends Service { /** * 解绑微信:清理 ye4s_user 中与当前账号关联的数据 - * @return {Object} + * @return {Object} 解绑结果 */ async unbindWechat() { const accountId = this.getCurrentAccountId(); @@ -1424,9 +1418,9 @@ class UserService extends Service { /** * 生成统一登录成功结构 - * @param {Object} user - * @param options - * @return {Object} + * @param {Object} user 用户对象 + * @param {Object} options 登录选项 + * @return {Object} 登录结果 */ async buildLoginResult(user, options = {}) { const { ctx, app } = this; @@ -1436,7 +1430,6 @@ class UserService extends Service { const platformCode = ctx.header.platform || 'web'; // 获取用户完整信息 const userInfo = await this.findById(user.id); - console.log('用户信息', userInfo); if (!userInfo) { throw new Error('用户信息加载失败'); } @@ -1492,10 +1485,8 @@ class UserService extends Service { /** * 切换角色(重构版) - * @param {Object} data - 切换角色数据 - * @param {number} data.roleId - 角色关联ID (account_store_role.id) - * @param {string} data.platformCode - 平台编码(web、pda、mini等) - * @return {Object} 切换结果 + * @param {Object} data 切换角色数据 + * @return {Object} 切换结果 */ async changeRole(data) { const { ctx, app } = this; @@ -1571,10 +1562,9 @@ class UserService extends Service { /** * 获取用户信息(重构版) - * @param {Object} data - 请求数据 - * @return {Object} 用户信息 + * @return {Object} 用户信息 */ - async info(data) { + async info() { const { ctx } = this; try { const userId = ctx.userId || (ctx.user && ctx.user.id); @@ -1586,7 +1576,6 @@ class UserService extends Service { code: 200, }; } catch (error) { - console.log(error); return { success: false, data: null, @@ -1597,14 +1586,13 @@ class UserService extends Service { /** * 查找用户所有的角色以及对应的主体(重构版) - * @param {number} userId - 用户ID - * @param {string} platformCode - 平台编码 - * @return {Promise} + * @param {number} userId 用户ID + * @return {Promise} 角色列表 */ async getRoles(userId) { const { ctx } = this; const platformCode = ctx.header.platform || 'web'; - const project = ctx.header.project; + const project = ctx.header.project || 'all'; try { const loadAccountStoreEmployees = async projectFilter => { const store_where = { @@ -1613,7 +1601,6 @@ class UserService extends Service { if (projectFilter && projectFilter !== 'all') { store_where.project = projectFilter; } - console.log('store_where', store_where, projectFilter, platformCode, ctx.header); return ctx.model.AccountStoreEmployee.findAll({ where: { account_id: userId, @@ -1652,7 +1639,6 @@ class UserService extends Service { realName: null, }; } - console.log('accountStoreEmployees>>>>>', accountStoreEmployees); // 获取当前平台的激活角色 let activeEmployeeId = null; let realName = null; @@ -1682,10 +1668,10 @@ class UserService extends Service { // 确定当前激活角色 for (const Employee of Employees) { - if (Employee.is_primary == 1) { + if (Employee.is_primary === 1) { activeEmployeeId = Employee.id; realName = Employee.real_name; - userRole = Employee.role_type == 1 ? 'warehouse' : 'customer'; + userRole = Employee.role_type === 1 ? 'warehouse' : 'customer'; break; } } @@ -1694,7 +1680,7 @@ class UserService extends Service { if (!activeEmployeeId && Employees.length > 0) { activeEmployeeId = Employees[0].id; realName = Employees[0].real_name; - userRole = Employees[0].role_type == 1 ? 'warehouse' : 'customer'; + userRole = Employees[0].role_type === 1 ? 'warehouse' : 'customer'; // 设置为激活角色 if (Employees[0].id) { @@ -1705,7 +1691,6 @@ class UserService extends Service { // 获取菜单和权限 const menus = await this.getMenus(activeEmployeeId); - console.log('获取菜单', activeEmployeeId, menus); const permissions = await this.getPermissions(activeEmployeeId); return { Employees, activeEmployeeId, menus, permissions, userRole, realName }; @@ -1724,16 +1709,13 @@ class UserService extends Service { /** * 根据ID查找用户(重构版) - * @param {number} userId - 用户ID - * @param {string} platformCode - 平台编码 - * @param useCache - * @return {Promise} + * @param {number} userId 用户ID + * @param {boolean} useCache 是否使用缓存 + * @return {Promise} 用户信息 */ async findById(userId, useCache = true) { const { ctx } = this; const platformCode = ctx.header.platform || 'web'; - const project = ctx.header.project; - console.log(`调用${ctx.query_count}次,平台为${platformCode}`); ctx.query_count++; try { // 生成缓存key @@ -1744,7 +1726,6 @@ class UserService extends Service { try { const cachedUser = await this.app.getCacheAsync(cacheKey); if (cachedUser) { - console.log('用户信息缓存命中:', userId); return cachedUser; } } catch (cacheError) { @@ -1768,16 +1749,14 @@ class UserService extends Service { } // 3. 获取角色信息(这个方法内部也有缓存逻辑) - let { Employees, activeEmployeeId, menus, permissions, userRole, realName } = await this.getRoles(userId); - console.log('activeEmployeeId>>>>>>>>', activeEmployeeId); + let { Employees, activeEmployeeId, menus, permissions, userRole } = await this.getRoles(userId); // pda 场景若缺少激活角色,优先补一条当前平台激活记录,避免直接报错。 - if (platformCode == 'pda' && !activeEmployeeId && Employees.length > 0) { + if (platformCode === 'pda' && !activeEmployeeId && Employees.length > 0) { const fallbackEmployee = Employees[0]; await this.ensurePlatformActiveRole(userId, fallbackEmployee.id, platformCode); activeEmployeeId = fallbackEmployee.id; - userRole = fallbackEmployee.role_type == 1 ? 'warehouse' : 'customer'; - realName = fallbackEmployee.real_name || realName; + userRole = fallbackEmployee.role_type === 1 ? 'warehouse' : 'customer'; menus = await this.getMenus(activeEmployeeId); permissions = await this.getPermissions(activeEmployeeId); } @@ -1801,7 +1780,7 @@ class UserService extends Service { } const avatar = await this.getAvatarByEmployeeId(activeEmployeeId); - if (platformCode == 'pda' && !activeEmployeeId) { + if (platformCode === 'pda' && !activeEmployeeId) { ctx.logger.warn(`pda 平台未找到可激活角色,accountId=${userId},将以空角色上下文返回`); } // 5. 组合用户信息 @@ -1826,11 +1805,9 @@ class UserService extends Service { }; // 6. 设置缓存 if (useCache) { - console.log('设置用户缓存', userInfo); await this.setUserCache(cacheKey, userInfo, 300); // 缓存5分钟 } - console.log('用户信息数据库查询:', userId); return userInfo; } catch (error) { @@ -1839,17 +1816,18 @@ class UserService extends Service { } } /** - * 设置用户缓存 - * @param cacheKey - * @param userInfo - * @param ttl - * @private - */ + * 设置用户缓存 + * @param {string} cacheKey 缓存键 + * @param {Object|null} userInfo 用户信息 + * @param {number} ttl 缓存时间 + * @private + */ async setUserCache(cacheKey, userInfo, ttl = 300) { try { // 移除缓存标识字段 if (userInfo) { - const { cached_at, ...cacheData } = userInfo; + const cacheData = { ...userInfo }; + delete cacheData.cached_at; await this.app.setCacheAsync(cacheKey, cacheData, ttl); } else { await this.app.setCacheAsync(cacheKey, null, ttl); @@ -1859,8 +1837,7 @@ class UserService extends Service { } } async getAvatarByEmployeeId(employeeId) { - const { ctx, app } = this; - const { Op } = app.Sequelize; + const { ctx } = this; let url = ''; const image = await ctx.model.FileReference.findOne({ where: { @@ -1881,8 +1858,8 @@ class UserService extends Service { } /** * 清除用户缓存 - * @param userId - * @param platformCode + * @param {number} userId 用户ID + * @param {string|null} platformCode 平台编码 */ async clearUserCache(userId, platformCode = null) { try { @@ -1902,7 +1879,6 @@ class UserService extends Service { // 同时清除相关的缓存 await this.clearRelatedCache(userId); - console.log('用户缓存已清除:', userId); return true; } catch (error) { console.warn('清除用户缓存失败:', error.message); @@ -1911,7 +1887,7 @@ class UserService extends Service { } /** * 清除用户相关缓存 - * @param userId + * @param {number} userId 用户ID * @private */ async clearRelatedCache(userId) { @@ -1948,9 +1924,8 @@ class UserService extends Service { } /** * 获取权限列表(重构版) - * @param {number} roleId - 角色ID - * @param activeEmployeeId - * @return {Promise} + * @param {number} activeEmployeeId 员工ID + * @return {Promise} 权限列表 */ async getPermissions(activeEmployeeId) { const { ctx, app } = this; @@ -1980,7 +1955,6 @@ class UserService extends Service { ], raw: true, // 获取纯数据对象 }); - console.log('员工绑定的角色', roles); if (!roles || roles.length === 0) { return []; } @@ -2014,7 +1988,6 @@ class UserService extends Service { [ 'sort', 'ASC' ], ], }); - console.log('permissions列表', permissions); if (!permissions) { return []; } @@ -2026,12 +1999,10 @@ class UserService extends Service { } } - async getMenus(activeEmployeeId) { const { ctx, app } = this; const { Sequelize } = app; const { Op } = Sequelize; - console.log('获取员工菜单员工id:', activeEmployeeId); if (!ctx.header.platform || !activeEmployeeId) { return []; } @@ -2056,7 +2027,6 @@ class UserService extends Service { ], raw: true, // 获取纯数据对象 }); - console.log('员工绑定的角色', roles); if (!roles || roles.length === 0) { return []; } @@ -2102,7 +2072,7 @@ class UserService extends Service { /** * 转换权限为路由格式(保持不变) - * @param data + * @param {Array} data 权限列表 */ async convertToRoutes(data) { const map = new Map(); @@ -2160,7 +2130,9 @@ class UserService extends Service { // 移除辅助字段 const cleanNode = node => { - const { id, sort, ...rest } = node; + const rest = { ...node }; + delete rest.id; + delete rest.sort; if (rest.children && rest.children.length > 0) { rest.children = rest.children.map(child => cleanNode(child)); } @@ -2172,19 +2144,17 @@ class UserService extends Service { /** * 根据标识符查找用户(已重构) - * @param identifier - * @param type - * @param useCache + * @param {string} identifier 标识符 + * @param {string} type 查找类型 + * @return {Promise} 用户对象 */ - async findUserByIdentifier(identifier, type = 'auto', useCache = true) { - const { ctx, app } = this; + async findUserByIdentifier(identifier, type = 'auto') { + const { ctx } = this; let user; if (type === 'auto') { // 自动判断类型 - const Op = app.Sequelize.Op; - if (/^1[3-9]\d{9}$/.test(identifier)) { // 手机号格式 user = await ctx.model.Account.findOne({ @@ -2232,7 +2202,7 @@ class UserService extends Service { /** * 检查用户状态(保持不变) - * @param user + * @param {Object} user 用户对象 */ checkUserStatus(user) { if (user.status === 0) { @@ -2248,9 +2218,9 @@ class UserService extends Service { /** * 验证密码(重构版) - * @param inputPassword - * @param storedHash - * @param salt + * @param {string} inputPassword 输入密码 + * @param {string} storedHash 存储哈希 + * @param {string} salt 密码盐 */ async verifyPassword(inputPassword, storedHash, salt) { const crypto = require('crypto'); @@ -2266,8 +2236,8 @@ class UserService extends Service { /** * 加密密码(保持不变) - * @param password - * @param salt + * @param {string} password 密码 + * @param {string} salt 密码盐 */ async encryptPassword(password, salt) { const crypto = require('crypto'); @@ -2286,11 +2256,10 @@ class UserService extends Service { /** * 更新最后登录时间(重构版) - * @param userId + * @param {number} userId 用户ID */ async updateLastLoginTime(userId) { const { ctx } = this; - console.log('登录上下文', ctx.request.header['x-real-ip']); await ctx.model.Account.update({ last_login_at: new Date(), last_login_ip: ctx.request.header['x-real-ip'], @@ -2302,9 +2271,9 @@ class UserService extends Service { /** * 确保平台激活角色存在 - * @param accountId - * @param accountStoreRoleId - * @param platformCode + * @param {number} accountId 账号ID + * @param {number} accountStoreRoleId 角色关联ID + * @param {string} platformCode 平台编码 * @private */ async ensurePlatformActiveRole(accountId, accountStoreRoleId, platformCode) { @@ -2321,13 +2290,12 @@ class UserService extends Service { } } - /** * 用户注册(重构版) - * @param userInfo + * @param {Object} userInfo 用户信息 */ async register(userInfo) { - const { ctx, app } = this; + const { ctx } = this; // 检查用户名是否已存在 const existingUser = await this.findUserByIdentifier(userInfo.username, 'username'); diff --git a/app/service/systems/delivery_order.js b/app/service/systems/delivery_order.js index ef45491..880a52a 100644 --- a/app/service/systems/delivery_order.js +++ b/app/service/systems/delivery_order.js @@ -98,11 +98,11 @@ class DeliveryOrderService extends Service { }); } - // 异步处理:订单入队列 - this.addOrderToQueue(orderId, info.warehouseId); - await transaction.commit(); + // 异步处理:订单入队列 + await this.addOrderToQueue(orderId, info.warehouseId); + return { success: true, message: '订单创建成功', @@ -132,7 +132,8 @@ class DeliveryOrderService extends Service { /** * 生成订单结构哈希值 * 直接使用itemsInfo中的items_str - * @param itemsInfo + * @param {Object} itemsInfo 订单明细信息 + * @return {string} 结构哈希值 */ generateItemsHash(itemsInfo) { const crypto = require('crypto'); @@ -149,19 +150,21 @@ class DeliveryOrderService extends Service { /** * 计算CRC32校验码 - * @param str + * @param {string} str 待计算字符串 + * @return {number} CRC32校验值 */ calculateCRC32(str) { if (!str) return 0; try { const crc32 = require('crc-32'); - return crc32.str(str) >>> 0; // 转为无符号整数 + const crc = crc32.str(str); + return crc >= 0 ? crc : crc + 4294967296; } catch (error) { // 降级方案:简单校验和 let crc = 0; for (let i = 0; i < str.length; i++) { - crc = (crc + str.charCodeAt(i)) & 0xFFFFFFFF; + crc = (crc + str.charCodeAt(i)) % 4294967296; } return crc; } @@ -201,7 +204,6 @@ class DeliveryOrderService extends Service { logisticsAreaCode, isUrgency, invoiceFlag, - senderInfo, receiverInfo, } = deliveryOrder; @@ -316,11 +318,8 @@ class DeliveryOrderService extends Service { const stockWeightMap = new Map(); // stock_id -> 单件重量(grossWeight) const processedItemIds = new Set(); - console.log('order_items', order_items); - for (let i = 0; i < order_items.length; i++) { const line = order_items[i]; - console.log('line', line); // 跳过空值 if (!line || typeof line !== 'object') { @@ -328,7 +327,6 @@ class DeliveryOrderService extends Service { continue; } - // 数量验证 const planQty = line.planQty ? parseInt(line.planQty) : 0; if (planQty <= 0) { @@ -337,7 +335,6 @@ class DeliveryOrderService extends Service { } let wms_stock = null; if (!line.itemId) { - console.log('ERP不处理WMS的外部商品编码'); // 查找唯一键 wms_stock = await app.model.StockStore.findOne({ where: { item_code: line.itemCode, @@ -362,7 +359,7 @@ class DeliveryOrderService extends Service { continue; } - const { stock, storage } = stockResult.data; + const { storage } = stockResult.data; const stockId = storage.id; if (!stockId) { @@ -516,17 +513,41 @@ class DeliveryOrderService extends Service { // 订单入队列(异步处理) async addOrderToQueue(orderId, warehouseId) { - const { ctx, app } = this; + const { ctx } = this; + + if (!orderId || !warehouseId) { + ctx.logger.warn('[订单入队列] 参数无效', { orderId, warehouseId }); + return; + } + + const cacheRedis = ctx.app && ctx.app.redis && ctx.app.redis.get ? ctx.app.redis.get('cache') : null; + if (!cacheRedis || typeof cacheRedis.publish !== 'function') { + ctx.logger.warn('[订单入队列] Redis 不可用', { orderId, warehouseId }); + return; + } + + const channel = `delivery_order:queue:${warehouseId}`; try { - const queueData = { + await cacheRedis.publish(channel, JSON.stringify({ orderId, warehouseId, timestamp: Date.now(), action: 'order_created', - }; + })); + ctx.logger.info('[订单入队列] 发布成功', { + orderId, + warehouseId, + channel, + }); } catch (error) { + ctx.logger.warn('[订单入队列] 发布失败', { + orderId, + warehouseId, + channel, + error: error.message, + }); } } } diff --git a/app/service/systems/entry_order.js b/app/service/systems/entry_order.js index b2641a6..bfe24ae 100644 --- a/app/service/systems/entry_order.js +++ b/app/service/systems/entry_order.js @@ -8,26 +8,21 @@ class entryOrderService extends Service { const transaction = await app.model.transaction(); // 开启事务 try { - console.log('入库单开始接收处理'); let totalOrderLines = data.request.entryOrder.totalOrderLines || 0; let orderLine = data.request.orderLines.orderLine; if (orderLine.itemCode) { orderLine = [ orderLine ]; } - console.log('orderLine', orderLine); - const isSingle = totalOrderLines ? 0 : 1; totalOrderLines = totalOrderLines || orderLine.length; let errors = []; const items = []; - console.log('循环开始'); // 验证商品 - for (var i = 0; i < orderLine.length; i++) { + for (let i = 0; i < orderLine.length; i++) { let wms_stock = null; // ERP不处理WMS的外部商品编码 if (!orderLine[i].itemId) { - console.log('ERP不处理WMS的外部商品编码'); // 查找唯一键 wms_stock = await app.model.StockStore.findOne({ where: { item_code: orderLine[i].itemCode, @@ -52,7 +47,6 @@ class entryOrderService extends Service { wms_stock.item_id = orderLine[i].itemId || wms_stock.id; items.push(wms_stock); } - console.log('items>>>>>', items); if (errors.length > 0) { await transaction.rollback(); // 验证失败,回滚事务 return { @@ -77,7 +71,6 @@ class entryOrderService extends Service { transaction // 传递事务 ); - console.log('入库单参数', order); if (!order.success) { await transaction.rollback(); return { @@ -94,10 +87,9 @@ class entryOrderService extends Service { errors = []; // 重置错误数组 // 添加商品明细 - for (var i = 0; i < items.length; i++) { + for (let i = 0; i < items.length; i++) { const item = items[i]; const res = await this.addItems(item, orderId, transaction); - console.log('添加商品返回信息', res); if (!res.success) { errors.push(`SKU${item.itemId}商品《${item.itemName}》编码《${item.itemCode}》入库失败,错误信息:${res.error}`); } @@ -116,8 +108,9 @@ class entryOrderService extends Service { // 获取接收行数并处理状态 const lineCount = await this.getLineCount(orderId, transaction); + const expectedTotalOrderLines = Number(totalOrderLines) || 0; - if (lineCount == totalOrderLines) { + if (lineCount === expectedTotalOrderLines) { // 所有行数接收完成 await this.received(orderId, warehouseId, storeId, transaction); } @@ -125,7 +118,7 @@ class entryOrderService extends Service { // 提交事务 await transaction.commit(); - if (lineCount == totalOrderLines) { + if (lineCount === expectedTotalOrderLines) { return { success: true, message: '入库单接收完毕', @@ -185,7 +178,6 @@ class entryOrderService extends Service { // 辅助函数:标记为已接收(支持事务) async received(orderId, warehouseId, storeId, transaction = null) { const { app } = this; - const updateData = { order_status: 'COMPLETED', updated_at: new Date(), @@ -573,9 +565,7 @@ class entryOrderService extends Service { } async tryCreateEntryOrder(order, appKey, storeId, warehouseId, totalOrderLines, sourceType, qimenOwnerCode, qimenWarehouseCode, transaction = null) { - const { app } = this; const { ctx } = this; - console.log('创建入库单信息', order, appKey, storeId, warehouseId); try { const options = transaction ? { transaction } : {}; @@ -601,8 +591,6 @@ class entryOrderService extends Service { updated_at: new Date(), }, options); - console.log(`入库单 ${order.entryOrderCode} 已存在,状态更新为接收中`); - return { success: true, code: 1, @@ -645,18 +633,18 @@ class entryOrderService extends Service { const warehouse_data = await this.ctx.service.systems.store.getStoreName(warehouseId); let store_name = null; let warehouse_name = null; - if (warehouse_data.code == 200) { + if (warehouse_data.code === 200) { warehouse_name = warehouse_data.data.company_name; } const store_data = await this.ctx.service.systems.store.getStoreName(storeId); - if (store_data.code == 200) { + if (store_data.code === 200) { store_name = store_data.data.company_name; } const contract_data = await this.ctx.service.systems.store.getStoreRemaskName(storeId, warehouseId); let contract = null; - if (contract_data.code == 200) { + if (contract_data.code === 200) { contract = contract_data.data; } // 构建入库单数据 @@ -667,7 +655,7 @@ class entryOrderService extends Service { total_order_lines: totalOrderLines, order_create_time: order.orderCreateTime ? new Date(order.orderCreateTime) : new Date(), expect_start_time: order.expectStartTime ? new Date(order.expectStartTime) : new Date(), - expect_end_time: order.expectStartTime ? new Date(order.expectStartTime) : new Date(), + expect_end_time: order.expectEndTime ? new Date(order.expectEndTime) : new Date(), logistics_code: order.logisticsCode || '', logistics_name: order.logisticsName || '', express_code: order.expressCode || '', @@ -697,8 +685,6 @@ class entryOrderService extends Service { await internalTransaction.commit(); } - console.log(`成功创建入库单: ${order.entryOrderCode}, ID: ${newEntryOrder.id}`); - return { success: true, code: 1, @@ -708,7 +694,6 @@ class entryOrderService extends Service { }; } catch (error) { - console.log('创建入库单失败', error); // 如果这是内部创建的事务,回滚它 if (internalTransaction) { await internalTransaction.rollback(); @@ -732,9 +717,7 @@ class entryOrderService extends Service { } async addItems(item, orderId, transaction = null) { - const { app } = this; const { ctx } = this; - console.log('添加入库单商品'); try { const options = transaction ? { transaction } : {}; @@ -773,7 +756,6 @@ class entryOrderService extends Service { code: 1, }; } catch (error) { - console.log('添加商品明细出错', error); throw error; } } @@ -795,53 +777,10 @@ class entryOrderService extends Service { } } - async received(orderId, warehouseId, storeId, transaction = null) { - console.log('完结传参', orderId, warehouseId, storeId); - const { app } = this; - const { ctx } = this; - - const options = transaction ? { transaction } : {}; - - const existingOrder = await ctx.model.EntryOrder.findOne({ - where: { - warehouse_id: warehouseId, - store_id: storeId, - id: orderId, - }, - ...options, - }); - - if (!existingOrder) { - return { - success: false, - code: 0, - message: '入库单不存在', - entryOrderId: null, - orderStatus: null, - error: '入库单不存在', - }; - } - - const allowedStatuses = [ 'CREATING' ]; - if (allowedStatuses.includes(existingOrder.order_status)) { - await existingOrder.update({ - order_status: 'CREATED', - updated_at: new Date(), - }, options); - } - - return { - success: true, - code: 1, - message: '完成', - }; - } - async qimenEntryorderConfirm(entryOrder, orderLines, isFin, outBizCode) { if (orderLines.length < 1) { throw new Error('行不能为空'); } - console.log('isFin:', isFin); const queryData = { request: { entryOrder: { @@ -854,7 +793,7 @@ class entryOrderService extends Service { confirmType: isFin ? 0 : 1, status: isFin ? 'FULFILLED' : 'PARTFULFILLED', freight: 0, - operateTime: new Date().format(), + operateTime: this.app.formatDate(new Date()), remark: entryOrder.remark, }, orderLines, @@ -961,9 +900,8 @@ class entryOrderService extends Service { // 判断是否最终完成 const isFin = isCompleted ? true : (totalReceivedQty >= totalPlanQty); let qimenResult = {}; - let queryId = null; // 奇门入库单,数据同步到奇门 - if (entryOrder.source_type == 'QM') { + if (String(entryOrder.source_type) === 'QM') { // 第二阶段:调用奇门接口 const Result = await this.qimenEntryorderConfirm( entryOrder, @@ -971,11 +909,9 @@ class entryOrderService extends Service { isFin, Math.round(new Date() / 1000) ); - console.log(Result); - queryId = Result.queryId; qimenResult = Result.xmlArray.response; // 奇门调用失败,回滚事务 - if (!qimenResult || qimenResult.flag != 'success') { + if (!qimenResult || String(qimenResult.flag) !== 'success') { await transaction.rollback(); console.error('奇门接口调用失败:', qimenResult); return { @@ -1000,8 +936,7 @@ class entryOrderService extends Service { }, transaction, }); - const res = await ctx.service.systems.stockStore.inbound(update.item_id, update.confirm_increment, transaction); - console.log('增加库存返回', res); + await ctx.service.systems.stockStore.inbound(update.item_id, update.confirm_increment, transaction); if (result[0] === 0) { // 更新失败,可能被并发修改了 console.warn(`更新入库明细失败,可能已被修改: id=${update.id}`); @@ -1054,8 +989,6 @@ class entryOrderService extends Service { // 4. 提交事务 await transaction.commit(); - console.log(`入库单确认成功: id=${entryOrder.id}, 确认增量=${totalConfirmIncrement}, 状态=${newOrderStatus}`); - return { success: true, message: isFin ? '入库单完成确认' : '入库单增量确认成功', diff --git a/app/service/systems/file.js b/app/service/systems/file.js index 1946ac6..a80583f 100644 --- a/app/service/systems/file.js +++ b/app/service/systems/file.js @@ -4,17 +4,23 @@ const Service = require('egg').Service; class FileService extends Service { async getImages(data) { const { ctx } = this; - const result = await ctx.model.FileReference.findAll({ where: { - business_type: data.type, - business_id: data.id, - }, include: [ - { - model: ctx.model.File, - as: 'file', - attributes: [ 'file_url', 'file_name' ], - required: true, + const result = await ctx.model.FileReference.findAll({ + where: { + business_type: data.type, + business_id: data.id, }, - ] }); + include: [ + { + model: ctx.model.File, + as: 'file', + attributes: [ + 'file_url', + 'file_name', + ], + required: true, + }, + ], + }); return result; } async ReferenceFile(data) { @@ -22,9 +28,8 @@ class FileService extends Service { const { id, type, images } = data; const warehouseId = ctx.user.store_id; - console.log('<<>>>', type); switch (type) { - case 'stock': + case 'stock': { const stock = await ctx.model.StockWarehouse.findOne({ where: { warehouse_id: warehouseId, @@ -36,7 +41,6 @@ class FileService extends Service { if (!stock) { throw new Error('找不到商品'); } - console.log('<<>>>', images.length); if (images.length > 0) { await ctx.model.StockWarehouse.update({ is_images: 'Y' }, { @@ -66,9 +70,9 @@ class FileService extends Service { beforeChanges: null, }); break; - + } default: - // code + // code } // 获取现有的file_id const existingRefs = await ctx.model.FileReference.findAll({ diff --git a/app/service/systems/location.js b/app/service/systems/location.js index 578e3da..f2fa307 100644 --- a/app/service/systems/location.js +++ b/app/service/systems/location.js @@ -5,7 +5,7 @@ const Service = require('egg').Service; class LocationService extends Service { /** * 创建货架并自动生成仓位 - * @param params + * @param {Object} params 货架基础参数 */ async createRackWithSpaces(params) { const { ctx } = this; @@ -37,9 +37,9 @@ class LocationService extends Service { /** * 为货架生成仓位 - * @param rackId - * @param rack - * @param transaction + * @param {number|string} rackId 货架ID + * @param {Object} rack 货架信息 + * @param {Object} transaction 事务对象 */ async _generateSpacesForRack(rackId, rack, transaction) { const { app } = this; @@ -97,9 +97,9 @@ class LocationService extends Service { /** * 计算库区内货架的排序(按X坐标排序) - * @param warehouseId - * @param areaId - * @param transaction + * @param {number|string} warehouseId 仓库ID + * @param {number|string} areaId 库区ID + * @param {Object} transaction 事务对象 */ async _calculateAreaRackOrder(warehouseId, areaId, transaction) { const { app } = this; @@ -129,8 +129,8 @@ class LocationService extends Service { /** * 计算仓库的拣货路径 - * @param warehouseId - * @param transaction + * @param {number|string} warehouseId 仓库ID + * @param {Object} transaction 事务对象 */ async _calculatePickPathForWarehouse(warehouseId, transaction) { const { app } = this; @@ -189,10 +189,10 @@ class LocationService extends Service { /** * 更新货架下仓位的拣货顺序 - * @param rackId - * @param rackSequence - * @param rackDistance - * @param transaction + * @param {number|string} rackId 货架ID + * @param {number} rackSequence 货架拣货顺序 + * @param {number} rackDistance 起始点距离 + * @param {Object} transaction 事务对象 */ async _updateSpacePickSequence(rackId, rackSequence, rackDistance, transaction) { const { app } = this; @@ -241,8 +241,8 @@ class LocationService extends Service { /** * 计算拣货优先级 - * @param row - * @param distance + * @param {number} row 层数 + * @param {number} distance 距离 */ _calculatePickPriority(row, distance) { // 行数越小(下层)优先级越高 @@ -257,8 +257,8 @@ class LocationService extends Service { /** * 更新货架位置后重新计算路径 - * @param rackId - * @param newPosition + * @param {number|string} rackId 货架ID + * @param {Object} newPosition 新坐标 */ async updateRackPosition(rackId, newPosition) { const { ctx, app } = this; @@ -305,8 +305,8 @@ class LocationService extends Service { /** * 获取拣货路径 - * @param warehouseId - * @param options + * @param {number|string} warehouseId 仓库ID + * @param {Object} options 查询选项 */ async getPickPath(warehouseId, options = {}) { const { app } = this; @@ -364,7 +364,7 @@ class LocationService extends Service { /** * 批量更新邻居关系 - * @param warehouseId + * @param {number|string} warehouseId 仓库ID */ async updateNeighborRelations(warehouseId) { const { app } = this; @@ -392,8 +392,8 @@ class LocationService extends Service { /** * 查找相邻货架 - * @param currentRack - * @param allRacks + * @param {Object} currentRack 当前货架 + * @param {Array} allRacks 所有货架 */ async _findNeighborRacks(currentRack, allRacks) { const NEIGHBOR_DISTANCE = 2000; // 2米内视为邻居 diff --git a/app/service/systems/location_space.js b/app/service/systems/location_space.js index 779f8b8..0a12e66 100644 --- a/app/service/systems/location_space.js +++ b/app/service/systems/location_space.js @@ -5,7 +5,8 @@ const Service = require('egg').Service; class LocationSpaceService extends Service { /** * 创建仓位 - * @param data + * @param {Object} data 仓位数据 + * @return {Promise} 创建结果 */ async create(data) { const { ctx } = this; @@ -72,7 +73,8 @@ class LocationSpaceService extends Service { /** * 批量创建仓位 - * @param dataList + * @param {Array} dataList 仓位数据列表 + * @return {Promise} 创建结果 */ async batchCreate(dataList) { const { ctx } = this; @@ -133,7 +135,8 @@ class LocationSpaceService extends Service { /** * 获取仓位列表 - * @param params + * @param {Object} params 查询参数 + * @return {Promise} 列表结果 */ async list(params = {}) { const { ctx } = this; @@ -224,7 +227,8 @@ class LocationSpaceService extends Service { /** * 获取仓位详情 - * @param id + * @param {number|string} id 仓位ID + * @return {Promise} 仓位详情 */ async detail(id) { const { ctx } = this; @@ -259,8 +263,9 @@ class LocationSpaceService extends Service { /** * 更新仓位 - * @param id - * @param data + * @param {number|string} id 仓位ID + * @param {Object} data 更新数据 + * @return {Promise} 更新结果 */ async update(id, data) { const { ctx } = this; @@ -323,7 +328,8 @@ class LocationSpaceService extends Service { /** * 删除仓位(软删除) - * @param id + * @param {number|string} id 仓位ID + * @return {Promise} 删除结果 */ async delete(id) { const { ctx } = this; @@ -359,8 +365,9 @@ class LocationSpaceService extends Service { /** * 启用/禁用仓位 - * @param id - * @param enabled + * @param {number|string} id 仓位ID + * @param {boolean} enabled 是否启用 + * @return {Promise} 操作结果 */ async toggleStatus(id, enabled) { const { ctx } = this; @@ -389,8 +396,9 @@ class LocationSpaceService extends Service { /** * 更新仓位状态 - * @param id - * @param status + * @param {number|string} id 仓位ID + * @param {string} status 仓位状态 + * @return {Promise} 操作结果 */ async updateStatus(id, status) { const { ctx } = this; @@ -440,7 +448,8 @@ class LocationSpaceService extends Service { /** * 查询可用仓位 - * @param params + * @param {Object} params 查询参数 + * @return {Promise} 可用仓位列表 */ async findAvailableSpaces(params) { const { ctx } = this; @@ -490,8 +499,9 @@ class LocationSpaceService extends Service { /** * 根据编码查找仓位 - * @param warehouseId - * @param spaceCode + * @param {number|string} warehouseId 仓库ID + * @param {string} spaceCode 仓位编码 + * @return {Promise} 仓位信息 */ async findByCode(warehouseId, spaceCode) { const { ctx } = this; @@ -525,7 +535,8 @@ class LocationSpaceService extends Service { /** * 根据条码查找仓位 - * @param barcode + * @param {string} barcode 条码 + * @return {Promise} 仓位信息 */ async findByBarcode(barcode) { const { ctx } = this; @@ -558,7 +569,8 @@ class LocationSpaceService extends Service { /** * 获取仓库仓位统计 - * @param warehouseId + * @param {number|string} warehouseId 仓库ID + * @return {Promise} 统计结果 */ async getWarehouseStats(warehouseId) { const { ctx } = this; @@ -585,8 +597,9 @@ class LocationSpaceService extends Service { /** * 获取分区的仓位统计 - * @param warehouseId - * @param zoneId + * @param {number|string} warehouseId 仓库ID + * @param {number|string|null} zoneId 分区ID + * @return {Promise} 统计结果 */ async getZoneStats(warehouseId, zoneId = null) { const { ctx } = this; @@ -602,7 +615,8 @@ class LocationSpaceService extends Service { /** * 验证仓位是否可分配 - * @param locationSpaceId + * @param {number|string} locationSpaceId 仓位ID + * @return {Promise} 仓位信息 */ async validateAllocation(locationSpaceId) { const { ctx } = this; @@ -634,7 +648,8 @@ class LocationSpaceService extends Service { /** * 验证仓位是否可移出 - * @param locationSpaceId + * @param {number|string} locationSpaceId 仓位ID + * @return {Promise} 仓位信息 */ async validateTransferOut(locationSpaceId) { const { ctx } = this; @@ -666,7 +681,8 @@ class LocationSpaceService extends Service { /** * 内部方法:验证关联数据 - * @param data + * @param {Object} data 关联数据 + * @return {Promise} */ async _validateReferences(data) { const { ctx } = this; diff --git a/app/service/systems/location_zone.js b/app/service/systems/location_zone.js index 7a857d8..c0647c7 100644 --- a/app/service/systems/location_zone.js +++ b/app/service/systems/location_zone.js @@ -5,11 +5,11 @@ const Service = require('egg').Service; class LocationZoneService extends Service { /** * 获取所有仓库级别的分区列表 - * @param warehouseId + * @param {number|string} warehouseId 仓库ID * @return {Promise} 仓库级别分区列表 */ async getWarehouseLevelZones(warehouseId) { - const { ctx, app } = this; + const { ctx } = this; try { const zones = await ctx.model.LocationZone.findAll({ @@ -32,27 +32,22 @@ class LocationZoneService extends Service { let totalSpaces = 0; for (let ii = 0; ii < warehouse_tree.warehouseRoot.children.length; ii++) { const area = warehouse_tree.warehouseRoot.children[ii]; - console.log('area', area); for (let iii = 0; iii < area.children.length; iii++) { const zone = area.children[iii]; - if (zone.type == 'rack') { - console.log('货架', zone); + if (zone.type === 'rack') { racks.push(zone); rackCount++; - const sz_count = await app.model.LocationSpace.count({ where: { zone_id: zone.id } }); - console.log(sz_count); const { rackColumns = 1, rackRows = 1, rackLevels = 1 } = zone.data; totalSpaces += rackColumns * rackRows * rackLevels; } } - if (area.type == 'area') { + if (area.type === 'area') { areaCount++; } } zones[i].rackCount = rackCount; zones[i].areaCount = areaCount; zones[i].totalSpaces = totalSpaces; - console.log('zones[i]', i, rackCount, areaCount, zones[i].rackCount, zones[i].areaCount); } // 转换为前端需要的格式 return zones.map(zone => ({ @@ -75,11 +70,10 @@ class LocationZoneService extends Service { } /** - * 根据仓库ID获取完整的树状结构(支持Element Tree格式) - * @param {number} warehouseId - 仓库ID - * @param warehouseSpaceId - * @return {Promise} 树状结构数据 - */ + * 根据仓库ID获取完整的树状结构(支持Element Tree格式)。 + * @param {number|string} warehouseSpaceId 仓库分区ID + * @return {Promise} 树状结构数据 + */ async getZoneTreeByWarehouse(warehouseSpaceId) { const { ctx } = this; const warehouseId = ctx.user.store_id; @@ -320,14 +314,9 @@ class LocationZoneService extends Service { /** * 创建元素 - * @param {Object} data - 元素数据 + * @param {Object} data 元素数据 * @return {Promise} 创建的元素 */ - /** - * 创建元素 - * @param {Object} data - 元素数据 - * @return {Promise} 创建的元素 - */ async createZone(data) { const { ctx } = this; try { @@ -342,7 +331,6 @@ class LocationZoneService extends Service { // 3. 验证父元素 await this.validateParentElement(data, warehouse_id); - // 5. 处理编码(根据类型) const zoneCode = this.generateZoneCodeByType(data); @@ -366,7 +354,7 @@ class LocationZoneService extends Service { direction: data.direction, color: data.color || this.getDefaultColorByType(data.zone_type), }); - if (zone.zone_type == 'rack') { + if (zone.zone_type === 'rack') { await this.generateSpacesForRack(zone.id, zone); } return { @@ -382,7 +370,7 @@ class LocationZoneService extends Service { /** * 验证基本字段 - * @param data + * @param {Object} data 元素数据 */ validateBasicFields(data) { // 所有元素都需要这些字段 @@ -405,21 +393,22 @@ class LocationZoneService extends Service { /** * 根据类型进行特定验证 - * @param data - * @param warehouseId + * @param {Object} data 元素数据 + * @param {number|string} warehouseId 仓库ID */ async validateByZoneType(data, warehouseId) { const { ctx } = this; switch (data.zone_type) { - case 'warehouse': + case 'warehouse': { // 仓库必须 parent_id = 0 if (data.parent_id !== 0 && data.parent_id !== null) { throw new Error('仓库元素的父元素必须为0或null'); } break; + } - case 'area': + case 'area': { // 库区必须有父元素且父元素必须是仓库 if (!data.parent_id) { throw new Error('库区必须指定父元素'); @@ -438,8 +427,9 @@ class LocationZoneService extends Service { throw new Error('库区只能创建在仓库上'); } break; + } - case 'rack': + case 'rack': { // 货架必须有父元素且父元素必须是通道 if (!data.parent_id) { throw new Error('货架必须指定父元素'); @@ -471,7 +461,9 @@ class LocationZoneService extends Service { throw new Error('货架列数、层数、分格数必须大于0'); } break; - case 'pick_start': + } + + case 'pick_start': { // 这些元素必须有父元素且父元素可以是任何类型(除了自身) if (!data.parent_id) { throw new Error(`${this.getZoneTypeText(data.zone_type)}必须指定父元素`); @@ -483,13 +475,11 @@ class LocationZoneService extends Service { deleted_at: null, }, }); - if (parentSpecial.zone_type !== 'area') { - throw new Error('拣货起点只能创建在库区上'); - } if (!parentSpecial) { throw new Error('父元素不存在'); } break; + } default: throw new Error('不支持的分区类型'); @@ -498,8 +488,8 @@ class LocationZoneService extends Service { /** * 验证父元素 - * @param data - * @param warehouseId + * @param {Object} data 元素数据 + * @param {number|string} warehouseId 仓库ID */ async validateParentElement(data, warehouseId) { const { ctx } = this; @@ -531,18 +521,21 @@ class LocationZoneService extends Service { const parentEndX = parent.x + parent.length; const parentEndY = parent.y + parent.width; const parentEndZ = parent.z + parent.height; - const elementEndX = data.x + data.length; const elementEndY = data.y + data.width; const elementEndZ = data.z + data.height; + if (elementEndX > parentEndX || elementEndY > parentEndY || elementEndZ > parentEndZ) { + throw new Error('元素必须位于父元素范围内'); + } + } /** * 验证坐标是否重叠 - * @param data - * @param warehouseId - * @param excludeId + * @param {Object} data 元素数据 + * @param {number|string} warehouseId 仓库ID + * @param {number|string|null} excludeId 排除的分区ID */ async validateZoneOverlap(data, warehouseId, excludeId = null) { const { ctx } = this; @@ -565,8 +558,9 @@ class LocationZoneService extends Service { /** * 检查两个元素是否重叠 - * @param zone1 - * @param zone2 + * @param {Object} zone1 元素1 + * @param {Object} zone2 元素2 + * @return {boolean} 是否重叠 */ isOverlap(zone1, zone2) { const zone1EndX = zone1.x + zone1.length; @@ -587,7 +581,8 @@ class LocationZoneService extends Service { /** * 根据类型生成编码 - * @param data + * @param {Object} data 元素数据 + * @return {string|null} 编码 */ generateZoneCodeByType(data) { // 只有特定类型需要编码 @@ -621,7 +616,8 @@ class LocationZoneService extends Service { /** * 根据类型获取默认颜色 - * @param zoneType + * @param {string} zoneType 类型 + * @return {string} 默认颜色 */ getDefaultColorByType(zoneType) { const colorMap = { @@ -638,7 +634,8 @@ class LocationZoneService extends Service { /** * 获取类型文本 - * @param type + * @param {string} type 类型 + * @return {string} 类型文本 */ getZoneTypeText(type) { const typeMap = { @@ -674,18 +671,44 @@ class LocationZoneService extends Service { throw new Error('分区不存在'); } - console.log('修改的数据', data); + const updateData = { ...data }; + + if (data.is_active !== undefined) { + const isActive = [ true, 1, '1', 'true' ].includes(data.is_active); + const isInactive = [ false, 0, '0', 'false' ].includes(data.is_active); + + if (!isActive && !isInactive) { + throw new Error('is_active 参数格式不正确'); + } + + if (isInactive) { + const activeChildren = await ctx.model.LocationZone.count({ + where: { + parent_id: id, + deleted_at: null, + is_active: 1, + }, + }); + + if (activeChildren > 0) { + throw new Error('请先禁用所有子分区'); + } + } + + updateData.is_active = isActive ? 1 : 0; + } + // 验证坐标是否重叠(如果修改了坐标) if ( - (data.x !== undefined || data.y !== undefined || data.length || data.width) && + (updateData.x !== undefined || updateData.y !== undefined || updateData.length || updateData.width) && zone.warehouse_id ) { - const x = data.x !== undefined ? data.x : zone.x; - const y = data.y !== undefined ? data.y : zone.y; - const z = data.z !== undefined ? data.z : zone.z || 0; - const length = data.length || zone.length; - const width = data.width || zone.width; - const height = data.height || zone.height || 0; + const x = updateData.x !== undefined ? updateData.x : zone.x; + const y = updateData.y !== undefined ? updateData.y : zone.y; + const z = updateData.z !== undefined ? updateData.z : zone.z || 0; + const length = updateData.length || zone.length; + const width = updateData.width || zone.width; + const height = updateData.height || zone.height || 0; const overlaps = await this.checkZoneOverlap( zone.warehouse_id, @@ -704,7 +727,7 @@ class LocationZoneService extends Service { } // 更新分区 - await zone.update(data); + await zone.update(updateData); return { success: true, @@ -725,7 +748,6 @@ class LocationZoneService extends Service { */ async deleteZone(id) { const { ctx } = this; - console.log('需要删除的id', id); try { const zone = await ctx.model.LocationZone.findOne({ where: { @@ -744,7 +766,7 @@ class LocationZoneService extends Service { deleted_at: null, }, }); - if (zone.zone_type == 'rack') { + if (zone.zone_type === 'rack') { // 货架执行删除需要检测库位是否还有库存 throw new Error('货架XX库位有库存,禁止删除,请先移库'); } @@ -765,14 +787,14 @@ class LocationZoneService extends Service { /** * 检查区域重叠 - * @param warehouseId - * @param x - * @param y - * @param z - * @param length - * @param width - * @param height - * @param excludeId + * @param {number|string} warehouseId 仓库ID + * @param {number} x X 坐标 + * @param {number} y Y 坐标 + * @param {number} z Z 坐标 + * @param {number} length 长度 + * @param {number} width 宽度 + * @param {number} height 高度 + * @param {number|string|null} excludeId 排除的分区ID * @private */ async checkZoneOverlap(warehouseId, x, y, z, length, width, height, excludeId) { @@ -936,7 +958,6 @@ class LocationZoneService extends Service { const spaces = []; let rackWidth = 0; let rackLength = 0; - const rackHeight = 0; let cellLength = 0; let cellWidth = 0; let cellHeight = 0; @@ -944,7 +965,6 @@ class LocationZoneService extends Service { let prelativeY = 0; let prelativeZ = 0; - rackWidth = rack.width; rackLength = rack.length; prelativeX = x; @@ -979,7 +999,7 @@ class LocationZoneService extends Service { spaces.push({ warehouse_id: rack.warehouse_id, zone_id: rackId, - location_type_id: row == 1 ? 1 : 2, // 默认第一层为分拣,其他层为存储 + location_type_id: row === 1 ? 1 : 2, // 默认第一层为分拣,其他层为存储 space_code: spaceCode, row_no: row.toString(), column_no: column.toString(), @@ -1011,7 +1031,6 @@ class LocationZoneService extends Service { const { ctx } = this; try { - const path = []; const space = await ctx.model.LocationSpace.findOne({ where: { id, @@ -1030,7 +1049,7 @@ class LocationZoneService extends Service { } } async checkBarcodeUnique(id, barcode) { - const { ctx } = this; + const { ctx, app } = this; const { Op } = this.app.Sequelize || app.Sequelize; try { // 检查条码是否被其他仓位使用(排除当前仓位) diff --git a/app/service/systems/notice/index.js b/app/service/systems/notice/index.js index 2aed6c7..7ac776a 100644 --- a/app/service/systems/notice/index.js +++ b/app/service/systems/notice/index.js @@ -20,7 +20,12 @@ const MESSAGE_TYPE_MAP = Object.freeze({ const DEFAULT_MAX_NOTICE_WEBHOOK_COUNT = 5; const DEFAULT_RETRY_DELAYS_MS = Object.freeze([ 3000, 6000, 12000 ]); const EVENT_CODE_PATTERN = /^[a-z_][a-z0-9_]*$/; -const DEFAULT_REGISTERED_EVENT_CODES = Object.freeze([ 'all', '*', 'receiving_completed' ]); +const DEFAULT_REGISTERED_EVENT_CODES = Object.freeze([ + 'all', + '*', + 'receiving_completed', + 'store_warehouse_print_quantity_adjusted', +]); const DRIVER_TYPE_ALIASES = Object.freeze({ custom: 'customize', customize: 'customize', @@ -41,7 +46,7 @@ class NoticeService extends Service { /** * 根据 webhook 类型获取对应发送驱动。 * @param {string} [hookType='customize'] webhook 类型 - * @return {object} + * @return {object} webhook 驱动实例 */ getDriver(hookType = 'customize') { const normalizedHookType = String(hookType || 'customize').trim().toLowerCase() || 'customize'; @@ -83,7 +88,7 @@ class NoticeService extends Service { * 将传入值安全转换为对象。 * @param {*} value 原始值 * @param {object} [fallback={}] 转换失败时的兜底对象 - * @return {object} + * @return {object} 转换后的对象 */ toObject(value, fallback = {}) { if (!value) { @@ -109,7 +114,7 @@ class NoticeService extends Service { /** * 规范化订阅事件列表,支持数组、字符串和对象格式。 * @param {*} rawEvents 原始事件配置 - * @return {string[]} + * @return {string[]} 事件编码数组 */ normalizeEventList(rawEvents) { if (!rawEvents) { @@ -156,7 +161,7 @@ class NoticeService extends Service { * 判断当前 webhook 是否命中本次消息事件。 * @param {*} rawEvents 订阅的事件配置 * @param {object} payload 统一消息载荷 - * @return {boolean} + * @return {boolean} 是否命中 */ matchesEvents(rawEvents, payload) { const eventList = this.normalizeEventList(rawEvents); @@ -175,7 +180,7 @@ class NoticeService extends Service { /** * 生成本次通知的追踪 ID。 - * @return {string} + * @return {string} 追踪ID */ buildTraceId() { return `notice_${Date.now()}_${Math.random().toString(16).slice(2, 10)}`; @@ -183,7 +188,7 @@ class NoticeService extends Service { /** * 获取当前模型中已注册的事件编码列表。 - * @return {string[]} + * @return {string[]} 注册的事件编码列表 */ getRegisteredEventCodes() { const notificationWebhookModel = this.ctx.model && this.ctx.model.NotificationWebhook; @@ -211,7 +216,7 @@ class NoticeService extends Service { /** * 判断事件编码是否符合标识符式命名:仅允许小写字母、数字、下划线,且首字符不能为数字。 * @param {string} event 事件编码 - * @return {boolean} + * @return {boolean} 是否有效 */ isValidEventCode(event) { const normalizedEvent = String(event || '').trim().toLowerCase(); @@ -241,7 +246,7 @@ class NoticeService extends Service { /** * 获取通知失败后的重试间隔,默认按 3 秒、6 秒、12 秒阶梯重试。 * @param {object} [options={}] 原始通知入参 - * @return {number[]} + * @return {number[]} 重试间隔数组 */ getRetryDelays(options = {}) { const customDelays = Array.isArray(options.retryDelaysMs) @@ -270,7 +275,7 @@ class NoticeService extends Service { /** * 判断外部 webhook 返回是否可视为成功。 * @param {object} [result={}] 发送结果 - * @return {boolean} + * @return {boolean} 是否成功 */ isSuccessfulResponse(result = {}) { const status = Number(result && result.status || 0); @@ -314,7 +319,7 @@ class NoticeService extends Service { * @param {object} params 参数对象 * @param {object|null} [params.result=null] 最近一次发送结果 * @param {Error|null} [params.error=null] 最近一次异常 - * @return {string} + * @return {string} 失败原因 */ getFailureMessage({ result = null, error = null } = {}) { if (error && error.message) { @@ -404,7 +409,7 @@ class NoticeService extends Service { * @param {object} params 发送参数 * @param {object} params.hook webhook 配置 * @param {object} params.payload 标准化后的 payload - * @return {Promise} + * @return {Promise} 发送结果 */ async sendWithRetry({ hook, payload }) { const driver = this.getDriver(hook && hook.hook_type); @@ -469,7 +474,7 @@ class NoticeService extends Service { * 生成货主/仓库信息缓存键。 * @param {number|string} warehouseId 仓库主体 ID * @param {number|string} storeId 货主 ID - * @return {string} + * @return {string} 缓存键 */ getStoreInfoCacheKey(warehouseId, storeId) { return `warehouse:${Number(warehouseId || 0)}store:${Number(storeId || 0)}:info`; @@ -479,7 +484,7 @@ class NoticeService extends Service { * 解析货主信息,优先命中缓存,未命中时回查数据库并缓存 600 秒。 * @param {object} [options={}] 原始通知入参 * @param {object} [subject={}] 主体信息 - * @return {Promise} + * @return {Promise} 货主信息 */ async resolveStoreInfo(options = {}, subject = {}) { const directStore = this.toObject(options.store || options.owner, {}); @@ -569,7 +574,7 @@ class NoticeService extends Service { * 解析主体配置,优先使用入参,缺失时回查主体表。 * @param {object} [options={}] 原始通知入参 * @param {object} [subject={}] 主体信息 - * @return {Promise} + * @return {Promise} 主体配置 */ async resolveSubjectConfig(options = {}, subject = {}) { const storeModel = this.ctx.model && this.ctx.model.Store; @@ -611,7 +616,7 @@ class NoticeService extends Service { /** * 将业务入参整理为统一通知 payload。 * @param {object} [options={}] 发送入参 - * @return {Promise} + * @return {Promise} 标准化后的 payload */ async normalizePayload(options = {}) { const subject = this.toObject(options.subject, {}); @@ -704,7 +709,7 @@ class NoticeService extends Service { * 构建实际对外发送的统一消息体。 * @param {object} webhook webhook 配置 * @param {object} payload 标准化后的消息载荷 - * @return {object} + * @return {object} 对外发送载荷 */ buildOutgoingPayload(webhook, payload) { return { @@ -725,7 +730,7 @@ class NoticeService extends Service { /** * 获取当前主体允许发送的 webhook 数量上限。 * @param {object} [payload={}] 标准化后的消息载荷 - * @return {number} + * @return {number} 上限数量 */ getWebhookLimit(payload = {}) { const rawLimit = payload && payload.subject && payload.subject.config @@ -743,7 +748,7 @@ class NoticeService extends Service { /** * 根据主体、事件和上限筛选本次需要触达的 webhook。 * @param {object} payload 标准化后的消息载荷 - * @return {Promise} + * @return {Promise} webhook 列表 */ async findMatchedWebhooks(payload) { const webhookLimit = this.getWebhookLimit(payload); @@ -814,7 +819,7 @@ class NoticeService extends Service { /** * 统一通知发送入口:规范化消息、匹配 webhook 并执行分发。 * @param {object} [options={}] 发送入参 - * @return {Promise} + * @return {Promise} 发送汇总结果 */ async send(options = {}) { const payload = await this.normalizePayload(options); diff --git a/app/service/systems/notification.js b/app/service/systems/notification.js deleted file mode 100644 index 62287a3..0000000 --- a/app/service/systems/notification.js +++ /dev/null @@ -1,49 +0,0 @@ -const { Service } = require('egg'); - -class NotificationService extends Service { - constructor(ctx) { - super(ctx); - // 设置全局变量 oldAction - this.oldreceivingUrl = 'http://ye4s.wms.gztbyc.com/index/wms/wms/receiving_notic'; - - } - - /** - * 发送通知 - * @param {Object} options - 通知参数 - * @param {string} options.type - 通知类型,如 'email', 'sms', 'system' - * @param {string} options.title - 通知标题 - * @param {string} options.content - 通知内容 - * @param {string} options.bussinessType - 业务类型,如 'receiving' - * @param {string[]} [options.receivers] - 接收人列表 - * @param {string} options.bussinessId - 业务ID - * @return {Promise} 发送结果 - */ - async send(options) { - const { type, title, content, bussinessType, bussinessId, receivers = [] } = options; - switch (bussinessType) { - case 'receiving': - // 发送接收通知 - await this.ctx.curl(this.oldreceivingUrl, { - method: 'POST', - data: { - id: bussinessId, - }, - dataType: 'json', - }); - break; - } - return { - success: true, - message: '通知已发送', - data: { - type, - title, - content, - receivers, - }, - }; - } -} - -module.exports = NotificationService; diff --git a/app/service/systems/operation_log.js b/app/service/systems/operation_log.js index 976adf0..2fb133d 100644 --- a/app/service/systems/operation_log.js +++ b/app/service/systems/operation_log.js @@ -93,7 +93,7 @@ class operationLogService extends Service { const item_tmp = JSON.parse(JSON.stringify(item)); item_tmp.operation_name = app.getOperationCodeName(item.operation_code); item_tmp.platform_name = app.getPlatformName(item.platform_code); - item_tmp.created_at = new Date(item_tmp.created_at).format(); + item_tmp.created_at = app.formatDate(item_tmp.created_at); return item_tmp; }), pagination: { @@ -104,23 +104,19 @@ class operationLogService extends Service { }, }; } catch (e) { - console.log(e); throw e; } - } - async queryOrderLogs() { - } async getMessageDetail(data) { const { id, type } = data; const { ctx } = this; - const warehouseId = ctx.user.store_id; let LogModel = null; switch (type) { case 'QIMEN': - // code LogModel = ctx.model.QimenLog; break; + default: + throw new Error(`不支持的日志类型: ${type}`); } const result = await LogModel.findOne({ where: { id } }); return result; diff --git a/app/service/systems/platform.js b/app/service/systems/platform.js index fa86c81..fe5337d 100644 --- a/app/service/systems/platform.js +++ b/app/service/systems/platform.js @@ -135,7 +135,6 @@ class PlatformService extends Service { * @return {Promise} 平台设置详情 */ async getPlatformSettingDetail(platformCode, warehouseId) { - const { ctx } = this; const cacheKey = `platform_setting_detail:${platformCode}:${warehouseId}`; try { diff --git a/app/service/systems/print/index.js b/app/service/systems/print/index.js index fd15ec2..f031d38 100644 --- a/app/service/systems/print/index.js +++ b/app/service/systems/print/index.js @@ -13,17 +13,15 @@ class PrintService extends Service { if (printerListResult) { // 记录上次更新时间,避免频繁发送更新指令 const printerData = JSON.parse(printerListResult); - console.log('printerData', printerData); lastUpdateTime = printerData.updatedAt || 0; } // 不管是否有打印机列表,都先发送指令让打印电脑更新打印机状态和列表 - const res = await this.ctx.curl(`${printServiceUrl}/sendToRoom`, { + await this.ctx.curl(`${printServiceUrl}/sendToRoom`, { method: 'POST', contentType: 'json', data: { warehouse, computerId, method: 'printer.getWindowsPrinters', data: {} }, dataType: 'json', }); - console.log('lastUpdateTime', lastUpdateTime); // 等待异步获取打印机列表结果,最长等待5秒 const startTime = Date.now(); while (Date.now() - startTime < 5000) { @@ -31,7 +29,6 @@ class PrintService extends Service { printerListResult = await this.app.redis.get('printer').get(`printer:${computerId}:printerList`); const printerData = JSON.parse(printerListResult); if (printerData.updatedAt && printerData.updatedAt > lastUpdateTime) { - console.log('打印机列表已更新', printerData.updatedAt); // 如果更新了打印机列表,跳出循环 break; } @@ -39,7 +36,6 @@ class PrintService extends Service { // 从redis获取打印机 printerListResult = await this.app.redis.get('printer').get(`printer:${computerId}:printerList`); const printerList = JSON.parse(printerListResult); - console.log('sendToComputer printerList', printerList); if (!printerList || !printerList.data || printerList.data.length === 0) { return { success: false, error: '未找到对应的打印机', detail: `computerId: ${computerId} 的打印机列表不存在` }; } @@ -48,7 +44,7 @@ class PrintService extends Service { if (!printerInfo) { return { success: false, error: `打印台没有打印机 ${printer}`, detail: `computerId: ${computerId} 的打印机列表中不存在 printer: ${printer}` }; } - if (printerInfo.workOffline == 'TRUE') { + if (printerInfo.workOffline === 'TRUE') { return { success: false, error: `打印机 ${printer} 处于脱机状态`, detail: `computerId: ${computerId} 的打印机 ${printer} 当前处于离线状态` }; } try { @@ -58,7 +54,6 @@ class PrintService extends Service { data: { warehouse, computerId, method: 'printer.print', data }, dataType: 'json', }); - console.log(res); return res.data; } catch (err) { diff --git a/app/service/systems/qimen_query.js b/app/service/systems/qimen_query.js index 0c378be..602932e 100644 --- a/app/service/systems/qimen_query.js +++ b/app/service/systems/qimen_query.js @@ -65,7 +65,7 @@ class QimenQueryService extends Service { v, sign_method: 'md5', customerId, - timestamp: new Date().format(), + timestamp: this.app.formatDate(new Date()), }; return param; } @@ -102,7 +102,6 @@ class QimenQueryService extends Service { try { // 判断 requestData 是否为字符串,如果是字符串则直接使用,否则进行转换 if (typeof requestData === 'string') { - console.log('requestData 是字符串,直接使用'); requestXml = requestData; // 可选:验证字符串是否是有效的XML @@ -110,7 +109,6 @@ class QimenQueryService extends Service { throw new Error('请求数据为空字符串'); } } else { - console.log('requestData 不是字符串,调用 formatResponse 进行转换'); requestXml = await this.ctx.service.qimen.formatResponse(requestData); } diff --git a/app/service/systems/setting/account.js b/app/service/systems/setting/account.js index 6cd2314..185f96a 100644 --- a/app/service/systems/setting/account.js +++ b/app/service/systems/setting/account.js @@ -218,12 +218,9 @@ class SettingAccountService extends Service { let current = roleId; let keep = true; const visited = new Set(); + let parentId = Number(parentMap.get(current) || 0); - while (true) { - const parentId = Number(parentMap.get(current) || 0); - if (!Number.isFinite(parentId) || parentId <= 0) { - break; - } + while (Number.isFinite(parentId) && parentId > 0) { if (visited.has(parentId)) { break; } @@ -235,6 +232,7 @@ class SettingAccountService extends Service { } current = parentId; + parentId = Number(parentMap.get(current) || 0); } if (keep) { diff --git a/app/service/systems/setting/print_template.js b/app/service/systems/setting/print_template.js index 5e810ca..a808573 100644 --- a/app/service/systems/setting/print_template.js +++ b/app/service/systems/setting/print_template.js @@ -9,7 +9,6 @@ class PrintTemplateService extends Service { * @return {Promise} 模板列表 */ async listTemplatesByType(businessType) { - console.log('获取业务类型模板列表, businessType:', businessType); return await this.getTemplatesByType(businessType); } @@ -92,7 +91,6 @@ class PrintTemplateService extends Service { const { Op } = app.Sequelize; const warehouseId = ctx.user.store_id; - console.log(businessType, warehouseId); try { const templates = await ctx.model.PrintTemplate.findAll({ where: { @@ -107,7 +105,6 @@ class PrintTemplateService extends Service { [ 'create_at', 'DESC' ], ], }); - console.log(`查询到${templates.length}个模板,businessType: ${businessType}, warehouseId: ${warehouseId}`); return templates.map(template => { const { warehouse_id } = template; return { @@ -123,10 +120,8 @@ class PrintTemplateService extends Service { } } async save(data) { - const { ctx, app } = this; - const { Op } = app.Sequelize; + const { ctx } = this; const warehouseId = ctx.user.store_id; - console.log('保存打印模板数据:', data); const { id, template_name, business_type, page_width, page_height, template_content } = data; try { if (id) { @@ -571,11 +566,15 @@ class PrintTemplateService extends Service { layout += ``; } break; - case 'table': + case 'table': { const tableContent = this.renderTable(el, index); layout += `${tableContent}
`; break; + } case 'shape': + break; + default: + break; } return `${layout} @@ -612,18 +611,24 @@ class PrintTemplateService extends Service { return styleText; } renderTable(el, index) { - const tableText = ''; - const rows = el.rows || []; - // 表头 - let headerTds = ''; - let bodyTds = '<% for(var i=0; i<(_data.items.length); i++) { %>'; - for (let i = 0; i < el.rows; i++) { + const rows = Array.isArray(el.rows) ? el.rows : []; + const fieldCode = String(el.field_code || '').trim(); - headerTds += `${el.headers && el.headers[i] ? el.headers[i] : `列${i + 1}`}`; - bodyTds += `]]>`; + if (!fieldCode || rows.length === 0) { + return ''; } + + let headerTds = ''; + let bodyTds = '<% const tableRows = Array.isArray(_data.items) ? _data.items : []; for (var rowIndex = 0; rowIndex < tableRows.length; rowIndex++) { %>'; + + for (let i = 0; i < rows.length; i++) { + const headerText = el.headers && el.headers[i] ? el.headers[i] : `列${i + 1}`; + headerTds += `${headerText}`; + bodyTds += `]]>`; + } + headerTds += ''; - bodyTds += '<%}%>'; + bodyTds += '<% } %>'; return headerTds + bodyTds; } } diff --git a/app/service/systems/sign.js b/app/service/systems/sign.js index 2fecd2d..32667b6 100644 --- a/app/service/systems/sign.js +++ b/app/service/systems/sign.js @@ -158,8 +158,9 @@ class SignService extends Service { /** * HMAC MD5加密 - * @param data - * @param secret + * @param {string} data 待签名内容 + * @param {string} secret 签名密钥 + * @return {Buffer} 加密结果 */ encryptHMAC(data, secret) { const hmac = crypto.createHmac('md5', secret); @@ -169,8 +170,9 @@ class SignService extends Service { /** * HMAC SHA256加密 - * @param data - * @param secret + * @param {string} data 待签名内容 + * @param {string} secret 签名密钥 + * @return {Buffer} 加密结果 */ encryptHMACSHA256(data, secret) { const hmac = crypto.createHmac('sha256', secret); @@ -180,7 +182,8 @@ class SignService extends Service { /** * MD5加密 - * @param data + * @param {string} data 待签名内容 + * @return {Buffer} 加密结果 */ encryptMD5(data) { return crypto.createHash('md5').update(data, 'utf8').digest(); @@ -188,7 +191,8 @@ class SignService extends Service { /** * 二进制转十六进制字符串(大写) - * @param bytes + * @param {Buffer} bytes 二进制数据 + * @return {string} 十六进制字符串 */ byte2hex(bytes) { return Buffer.from(bytes).toString('hex').toUpperCase(); diff --git a/app/service/systems/space.js b/app/service/systems/space.js index 7c20188..eea4b75 100644 --- a/app/service/systems/space.js +++ b/app/service/systems/space.js @@ -2,9 +2,6 @@ const Service = require('egg').Service; class spaceService extends Service { - constructor(ctx) { - super(ctx); - } async searchSpace(data) { const { ctx, app } = this; const { keyword } = data; diff --git a/app/service/systems/stock_store.js b/app/service/systems/stock_store.js index 76a2b93..cbe2292 100644 --- a/app/service/systems/stock_store.js +++ b/app/service/systems/stock_store.js @@ -9,13 +9,9 @@ const { } = require('../../lib/query_condition_parser'); class stockStoreService extends Service { - constructor(ctx) { - super(ctx); - } async create(stockData) { const { app, - ctx, service, } = this; const warehouseId = stockData.warehouse_id; @@ -139,6 +135,7 @@ class stockStoreService extends Service { return result; } async convertToQimenFormat(stockData) { + const { app } = this; const result = { // 商品信息 item: { @@ -175,22 +172,20 @@ class stockStoreService extends Service { // 其他信息 barCode: stockData.barcode || '', isValid: stockData.is_valid === 'Y' ? 'Y' : 'N', - createTime: stockData.create_time ? new Date(stockData.create_time).format() : '', + createTime: stockData.create_time ? app.formatDate(stockData.create_time) : '', }, }; return result; } async getItemInfoWithCache(itemId) { const { - ctx, - app, - } = this; // 使用 ctx.model 而非 app.model + app, ctx, + } = this; const cacheKey = `item:info:${itemId}`; try { // 1. 尝试从缓存获取 const cached = await app.getCacheAsync(cacheKey); - console.log('缓存》》》》', cached); if (cached !== null && cached !== undefined) { app.logger.debug('[ItemCacheHit]', itemId); @@ -204,7 +199,6 @@ class stockStoreService extends Service { // 2. 缓存未命中,查询数据库 app.logger.debug('[ItemCacheMiss]', itemId); - console.log('缓存》》》》', itemId); // ⭐ 关键修复:使用 raw: true 获取纯对象 const itemInfo = await ctx.model.StockStore.findByPk(itemId, { @@ -226,7 +220,6 @@ class stockStoreService extends Service { await app.setCacheAsync(cacheKey, nullMarker, 120); return null; // 明确返回 null - } catch (error) { app.logger.error('[getItemInfoWithCache] 查询失败', { itemId, @@ -253,7 +246,6 @@ class stockStoreService extends Service { // 数据库也失败,向上抛出 throw new Error(`查询商品信息失败: ${dbError.message}`); } - throw error; } } async getItemStorages(itemId, transaction) { @@ -387,7 +379,7 @@ class stockStoreService extends Service { /** * 计算缓存时间 - * @param storage + * @param {Object} storage - 库存对象 */ _calculateCacheTTL(storage) { if (!storage || !storage._exists || !storage._isValid) { @@ -407,7 +399,7 @@ class stockStoreService extends Service { /** * 清理缓存 - * @param itemId + * @param {number|string} itemId - 商品ID */ async clearItemStorageCache(itemId) { const { @@ -509,10 +501,9 @@ class stockStoreService extends Service { } // 3. 执行锁定/释放操作 - let updateResult; if (isLocking) { // 加锁:增加 locked_quantity - updateResult = await stockRecord.increment('locked_quantity', { + await stockRecord.increment('locked_quantity', { by: absQty, transaction, silent: true, @@ -522,7 +513,7 @@ class stockStoreService extends Service { ); } else { // 减锁:减少 locked_quantity(确保不小于0) - updateResult = await stockRecord.decrement('locked_quantity', { + await stockRecord.decrement('locked_quantity', { by: absQty, transaction, silent: true, @@ -609,15 +600,13 @@ class stockStoreService extends Service { return stockResult; } const { - stock, storage, } = stockResult.data; // 3. 执行库存增加 - let result; if (storage.exists) { // 非首次入库:更新现有记录(只增加quantity) - result = await ctx.model.StockWarehouse.increment('quantity', { + await ctx.model.StockWarehouse.increment('quantity', { by: inboundQty, where: { id: storage.id, @@ -713,7 +702,6 @@ class stockStoreService extends Service { } const { - stock, storage, } = stockResult.data; @@ -1021,7 +1009,6 @@ class stockStoreService extends Service { const { ctx, app, - config, } = this; const { Sequelize, @@ -1347,12 +1334,6 @@ class stockStoreService extends Service { const itemBarcodes = barcodes .filter(barcode => barcode.stock_id === item.id) .map(barcode => barcode.barcode); - const { - cos, - } = config; - const { - cdnurl, - } = cos; const itemImages = images .filter(images => parseInt(images.business_id) === item.id) .map(images => images.file.file_url); @@ -1384,7 +1365,6 @@ class stockStoreService extends Service { }), }; - return { code: 200, data: { @@ -1463,7 +1443,6 @@ class stockStoreService extends Service { return normalizeDateUtil(value); } - /** * 格式化日期显示 * @param {string} dateString - 日期字符串 @@ -1570,13 +1549,12 @@ class stockStoreService extends Service { return barcodes; } async handleBatchChange() { - const { ctx, service, app } = this; + const { ctx, app } = this; const { Op } = app.Sequelize; const canChangeFlide = [ 'brand_name', 'prohibited_id', 'gross_weight', 'packing_requirements', 'managementFlags', 'stock_unit' ]; const { ids, method, value } = ctx.request.body; - console.log('批量修改参数', ctx.request.body); try { // 1. 参数验证 @@ -1713,7 +1691,6 @@ class stockStoreService extends Service { const { ctx, service, } = this; - console.log('条码修改提交', data); const { id, barcodes, @@ -1792,14 +1769,12 @@ class stockStoreService extends Service { const { ctx, } = this; - console.log(data); const { stock_id = null, store_id = null, page = 1, pageSize = 20, item_code = '', item_name = '', } = data || {}; const warehouseId = ctx.user.store_id; let barcodes = []; let warehouseStock = null; - console.log(stock_id); let total = 0; if (stock_id) { barcodes = await ctx.model.StockStore.findAll({ @@ -1891,11 +1866,10 @@ class stockStoreService extends Service { }), ]); } - console.log('barcodes>>>>', barcodes); const results = barcodes.map(item => { return { app_key: item.app_key, - create_from: item.create_from == 'qimen' ? '奇门' : 'API', + create_from: item.create_from === 'qimen' ? '奇门' : 'API', id: item.id, app_name: item.app_key, item_code: item.item_code, @@ -1904,9 +1878,7 @@ class stockStoreService extends Service { item_name: item.item_name, }; }); - console.log('warehouseStock>>>', warehouseStock); const get_store_id = warehouseStock ? warehouseStock.store_id : barcodes[0]['warehouse_stock.store_id']; - console.log('get_store_id>>>', get_store_id); return { rows: results, store_id: get_store_id, @@ -1963,7 +1935,6 @@ class stockStoreService extends Service { }); return 1; } catch (e) { - console.log(e); throw e; } } @@ -2000,7 +1971,6 @@ class stockStoreService extends Service { }); return 1; } catch (e) { - console.log(e); throw e; } } @@ -2058,7 +2028,7 @@ class stockStoreService extends Service { const { ctx, service } = this; const warehouseId = ctx.user.store_id; const { - item_code, store_id, item_name, sku_property, stock_unit, + item_code, item_name, sku_property, stock_unit, packing_requirements, length, width, height, volume, gross_weight, net_weight, tag_price, retail_price, is_sn_mgmt, is_shelf_life_mgmt, is_batch_mgmt, @@ -2123,16 +2093,15 @@ class stockStoreService extends Service { box_remark, updated_at: new Date(), }; - console.log('更新数据', updateData); // 5. 清除空值 Object.keys(updateData).forEach(key => { - if (key != 'prohibited_id' && (updateData[key] === undefined || updateData[key] === null)) { + if (key !== 'prohibited_id' && (updateData[key] === undefined || updateData[key] === null)) { delete updateData[key]; } }); // 6. 执行更新 - const [ affectedRows ] = await ctx.model.StockWarehouse.update(updateData, { + await ctx.model.StockWarehouse.update(updateData, { where: { id, warehouse_id: ctx.user.store_id, @@ -2187,7 +2156,7 @@ class stockStoreService extends Service { prohibited_id, brand_name, managementFlags, enable_box_spec, box_unit, quantity_per_box, box_gross_weight, box_net_weight, box_length, - box_width, box_height, box_volume, box_remark, id, barcode, + box_width, box_height, box_volume, box_remark, barcode, } = data; // 1. 参数验证 @@ -2196,7 +2165,6 @@ class stockStoreService extends Service { try { checkItemCodeUnique = await this.checkItemCodeUnique(null, item_code, store_id, warehouseId); } catch (e) { - console.log(e); throw (e); } if (checkItemCodeUnique && !checkItemCodeUnique.isUnique) { @@ -2248,7 +2216,6 @@ class stockStoreService extends Service { const toCreate = barcodes_arr.filter(item => !existingFileIds.includes(item)); // 批量操作 const promises = []; - console.log('createdRecord', createdRecord.id); if (toCreate.length > 0) { const refData = toCreate.map(item => ({ stock_id: createdRecord.id, @@ -2256,7 +2223,6 @@ class stockStoreService extends Service { warehouse_id: warehouseId, created_at: new Date(), })); - console.log('refData', refData); promises.push(ctx.model.StockBarcode.bulkCreate(refData, { transaction })); await Promise.all(promises); } @@ -2275,7 +2241,6 @@ class stockStoreService extends Service { await transaction.commit(); return await this.getInfo({ id: createdRecord.id }); } catch (e) { - console.log(e); if (transaction) { await transaction.rollback(); } @@ -2308,10 +2273,10 @@ class stockStoreService extends Service { } } async stockLog() { - + return undefined; } async checkItemCodeUnique(id, item_code, store_id, warehouse_id) { - const { ctx } = this; + const { ctx, app } = this; const { Op } = this.app.Sequelize || app.Sequelize; try { // 检查条码是否被其他仓位使用(排除当前仓位) @@ -2349,7 +2314,7 @@ class stockStoreService extends Service { } } async handleBatchDelete(data) { - const { ctx } = this; + const { ctx, app } = this; const { Op } = this.app.Sequelize || app.Sequelize; const { ids } = data; @@ -2379,8 +2344,6 @@ class stockStoreService extends Service { attributes: [ 'id', 'item_name', 'quantity', 'return_quantity' ], }); - console.log('查询到的商品资料:', JSON.stringify(products, null, 2)); - if (products.length === 0) { return { code: 200, message: '未找到对应的商品资料或已删除', data: [] }; } @@ -2423,9 +2386,6 @@ class stockStoreService extends Service { } }); - console.log('可以删除的商品:', deletableProducts); - console.log('不能删除的商品:', undeletableProducts); - if (deletableProducts.length === 0) { return { code: 405, @@ -2511,7 +2471,7 @@ class stockStoreService extends Service { } async deleteUnit(data) { const { id } = data; - const { ctx, app } = this; + const { ctx } = this; const unitExit = await ctx.model.StockUnit.findOne({ where: { id, @@ -2531,7 +2491,7 @@ class stockStoreService extends Service { } async deleteProhibited(data) { const { id } = data; - const { ctx, app } = this; + const { ctx } = this; const unitExit = await ctx.model.ProhibitedType.findOne({ where: { id, @@ -2550,7 +2510,7 @@ class stockStoreService extends Service { return { message: '删除成功', code: 200 }; } async search(data) { - const { keyword, store_id = null } = data; + const { keyword, store_id = null, with_stock = false, is_batch = false } = data; const { ctx, app } = this; const { Op } = app.Sequelize; const warehouseId = ctx.user.store_id; @@ -2617,7 +2577,6 @@ class stockStoreService extends Service { })); // 执行查询 - console.log('查询商品===》'); const results = await app.model.StockWarehouse.findAll({ where: whereCondition, attributes: [ @@ -2641,6 +2600,78 @@ class stockStoreService extends Service { return result; }); + // with_stock=true 时关联查询库存数据 + if (with_stock && formattedResults.length > 0) { + const stockIds = formattedResults.map(r => r.id); + const storageWhere = { + stock_id: { [Op.in]: stockIds }, + warehouse_id: warehouseId, + is_enabled: 1, + delete_at: null, + }; + + const storageRows = await app.model.Storage.findAll({ + where: storageWhere, + attributes: [ + 'id', 'stock_id', 'space_id', 'batch_no', 'inventory_type', + 'quantity', 'locked_quantity', 'available_quantity', + 'production_date', 'expiry_date', 'inbound_time', + 'inbound_order_no', 'supplier_batch_no', 'created_at', + ], + include: [{ + model: app.model.LocationSpace, + as: 'space', + attributes: [ 'id', 'space_code', 'custom_name' ], + required: false, + }], + order: [[ 'created_at', 'DESC' ]], + }); + + // 按 stock_id 分组 + const storageMap = new Map(); + for (const row of storageRows) { + const plain = row.get({ plain: true }); + const key = plain.stock_id; + if (!storageMap.has(key)) { + storageMap.set(key, []); + } + storageMap.get(key).push(plain); + } + + for (const item of formattedResults) { + const storageList = storageMap.get(item.id) || []; + + if (is_batch) { + // is_batch=true:逐条批次明细返回,不分组 + item.storage = storageList; + } else { + // is_batch=false(默认):按库位分组汇总 + const mergedMap = new Map(); + for (const s of storageList) { + const spaceKey = s.space_id; + if (mergedMap.has(spaceKey)) { + const existing = mergedMap.get(spaceKey); + existing.quantity += Number(s.quantity) || 0; + existing.locked_quantity += Number(s.locked_quantity) || 0; + existing.available_quantity = existing.quantity - existing.locked_quantity; + } else { + const quantity = Number(s.quantity) || 0; + const lockedQuantity = Number(s.locked_quantity) || 0; + mergedMap.set(spaceKey, { + space_id: s.space_id, + inventory_type: s.inventory_type, + quantity, + locked_quantity: lockedQuantity, + available_quantity: quantity - lockedQuantity, + space: s.space, + }); + } + } + item.storage = Array.from(mergedMap.values()); + } + } + } + return { code: 200, data: formattedResults, @@ -2655,5 +2686,161 @@ class stockStoreService extends Service { }; } } + + /** + * 查询商品的库存明细(storage 表)。 + * @param {Object} data 请求体 + * @param {number} data.stock_id 商品库存ID(stock_warehouse.id) + * @param {Object} [data.pagination] 分页参数 + * @return {Promise} 库存明细分页结果 + */ + async getStockDetail(data) { + const { ctx, app } = this; + const warehouseId = ctx.user.store_id; + const { stock_id, pagination = {}, group_by_batch = false } = data; + + if (!stock_id) { + return { code: 0, message: '参数 stock_id 不能为空' }; + } + + try { + // 校验商品归属当前仓库 + const stockItem = await app.model.StockWarehouse.findOne({ + where: { + id: stock_id, + warehouse_id: warehouseId, + deleted_at: null, + }, + attributes: [ 'id', 'item_code', 'item_name', 'sku_property', 'stock_unit', 'quantity', 'locked_quantity' ], + raw: true, + }); + + if (!stockItem) { + return { code: 0, message: '商品不存在或不属于当前仓库' }; + } + + const { page = 1, pageSize = 20 } = pagination; + const offset = (page - 1) * pageSize; + + const storageWhere = { + stock_id, + warehouse_id: warehouseId, + is_enabled: 1, + delete_at: null, + }; + + if (group_by_batch) { + // 区分批次:按原逻辑返回每一条库存明细 + const { count, rows } = await app.model.Storage.findAndCountAll({ + where: storageWhere, + attributes: [ + 'id', 'space_id', 'batch_no', 'inventory_type', + 'quantity', 'locked_quantity', 'available_quantity', + 'production_date', 'expiry_date', 'inbound_time', + 'inbound_order_no', 'supplier_batch_no', 'created_at', + ], + include: [{ + model: app.model.LocationSpace, + as: 'space', + attributes: [ 'id', 'space_code', 'custom_name' ], + required: false, + }], + order: [[ 'created_at', 'DESC' ]], + offset, + limit: pageSize, + }); + + return { + code: 200, + data: { + stockItem, + storageList: rows, + pagination: { + page, + pageSize, + total: count, + }, + }, + }; + } + + // 不区分批次:按 space_id 合并库存数据 + const allRows = await app.model.Storage.findAll({ + where: storageWhere, + attributes: [ + 'id', 'space_id', 'inventory_type', + 'quantity', 'locked_quantity', 'created_at', + ], + include: [{ + model: app.model.LocationSpace, + as: 'space', + attributes: [ + 'id', + 'space_code', + 'custom_name', + ], + required: false, + }], + order: [ + [ + 'created_at', + 'DESC', + ], + ], + }); + + // 按 space_id 合并 + const mergedMap = new Map(); + for (const row of allRows) { + const plain = row.get({ plain: true }); + const key = plain.space_id; + if (mergedMap.has(key)) { + const existing = mergedMap.get(key); + existing.quantity += Number(plain.quantity) || 0; + existing.locked_quantity += Number(plain.locked_quantity) || 0; + existing.available_quantity = existing.quantity - existing.locked_quantity; + } else { + const quantity = Number(plain.quantity) || 0; + const lockedQuantity = Number(plain.locked_quantity) || 0; + mergedMap.set(key, { + id: plain.id, + space_id: plain.space_id, + batch_no: null, + inventory_type: plain.inventory_type, + quantity, + locked_quantity: lockedQuantity, + available_quantity: quantity - lockedQuantity, + production_date: null, + expiry_date: null, + inbound_time: null, + inbound_order_no: null, + supplier_batch_no: null, + created_at: plain.created_at, + space: plain.space, + }); + } + } + + const mergedList = Array.from(mergedMap.values()); + const total = mergedList.length; + const storageList = mergedList.slice(offset, offset + pageSize); + + return { + code: 200, + data: { + stockItem, + storageList, + pagination: { + page, + pageSize, + total, + }, + }, + }; + } catch (error) { + ctx.logger.error(`查询商品库存明细失败, stock_id: ${stock_id}`, error); + return { code: 0, message: '查询库存明细失败,请稍后重试' }; + } + } } module.exports = stockStoreService; diff --git a/app/service/systems/stock_transaction.js b/app/service/systems/stock_transaction.js new file mode 100644 index 0000000..f975737 --- /dev/null +++ b/app/service/systems/stock_transaction.js @@ -0,0 +1,125 @@ +'use strict'; + +const Service = require('egg').Service; + +class StockTransactionService extends Service { + + async list(pageParams = {}, sortParams = {}, groupByBatch = false) { + const { ctx, app } = this; + const { Op, fn, col, literal } = app.Sequelize; + + const warehouseId = ctx.user.store_id; + const { page = 1, pageSize = 20 } = pageParams; + const { sortField = 'created_at', sortOrder = 'DESC' } = sortParams; + + // 基础条件:当前仓库 + const baseWhere = { + [Op.and]: [ + { warehouse_id: warehouseId }, + ], + }; + + // 动态 where 条件 + const parsed = ctx.whereParsed; + if (parsed && parsed.dynamicConditions && parsed.dynamicConditions.length > 0) { + baseWhere[Op.and].push(...parsed.dynamicConditions); + } + + const offset = (page - 1) * pageSize; + const limit = pageSize; + + if (groupByBatch) { + // 按批次明细:保持原有逻辑 + const { count: total, rows } = await ctx.model.StockTransaction.findAndCountAll({ + where: baseWhere, + order: [[ sortField, sortOrder ]], + offset, + limit, + include: [ + { + model: ctx.model.StockWarehouse, + as: 'stockItem', + attributes: [ 'id', 'item_code', 'item_name', 'sku_property', 'stock_unit' ], + required: false, + }, + ], + }); + + const list = rows.map(item => { + const row = item.get({ plain: true }); + row.created_at = row.created_at ? app.formatDate(row.created_at) : ''; + return row; + }); + + return { + list, + pagination: { + page, + pageSize, + total, + totalPages: Math.ceil(total / pageSize), + }, + }; + } + + // 不按批次:按 stock_id + space_id + transaction_type + inventory_type 合并 + const groupFields = [ 'stock_id', 'space_id', 'transaction_type', 'inventory_type', 'warehouse_id', 'store_id', 'order_type' ]; + + // 先查总数(分组后的组数) + const countResult = await ctx.model.StockTransaction.count({ + where: baseWhere, + group: groupFields, + }); + const total = Array.isArray(countResult) ? countResult.length : countResult; + + // 查分组数据 + const rows = await ctx.model.StockTransaction.findAll({ + where: baseWhere, + attributes: [ + 'stock_id', + 'space_id', + 'transaction_type', + 'inventory_type', + 'warehouse_id', + 'store_id', + 'order_type', + [ fn('SUM', col('stock_transaction.quantity')), 'quantity' ], + [ fn('MIN', col('stock_transaction.created_at')), 'first_created_at' ], + [ fn('MAX', col('stock_transaction.created_at')), 'last_created_at' ], + [ fn('COUNT', col('stock_transaction.id')), 'record_count' ], + ], + group: groupFields, + order: [[ literal('last_created_at'), sortOrder ]], + offset, + limit, + include: [ + { + model: ctx.model.StockWarehouse, + as: 'stockItem', + attributes: [ 'id', 'item_code', 'item_name', 'sku_property', 'stock_unit' ], + required: false, + }, + ], + raw: true, + nest: true, + }); + + const list = rows.map(row => { + row.first_created_at = row.first_created_at ? app.formatDate(row.first_created_at) : ''; + row.last_created_at = row.last_created_at ? app.formatDate(row.last_created_at) : ''; + return row; + }); + + return { + list, + pagination: { + page, + pageSize, + total, + totalPages: Math.ceil(total / pageSize), + }, + }; + } +} + +module.exports = StockTransactionService; diff --git a/app/service/systems/storage/index.js b/app/service/systems/storage/index.js index f113ac8..613f0c2 100644 --- a/app/service/systems/storage/index.js +++ b/app/service/systems/storage/index.js @@ -2,9 +2,6 @@ const Service = require('egg').Service; class IndexService extends Service { - async index() { - - } async findByStockAndBatch(stockId, batchNo, inventoryType = 'ZP') { const { ctx } = this; diff --git a/app/service/systems/storage/inventory.js b/app/service/systems/storage/inventory.js new file mode 100644 index 0000000..1cdd5c0 --- /dev/null +++ b/app/service/systems/storage/inventory.js @@ -0,0 +1,1856 @@ +'use strict'; + +const Service = require('egg').Service; + +class InventoryService extends Service { + + /** + * 收货单快捷入库上架。 + * 从收货单直接生成入库单并写入库存。 + * + * 流程: + * 1. 校验收货单状态(必须 completed) + * 2. 校验所有明细已匹配系统商品(system_product_id 不为空) + * 3. 校验未全部入库(storage_status !== 'all') + * 4. 事务内: + * a. 创建入库单(EntryOrder)和入库明细(EntryItems) + * b. 逐条锁定 StockWarehouse 行,增加 quantity + * c. 写入/更新 wms_storage 库存记录 + * d. 更新 receiving_detail 的 storage_status 和 stored_quantity + * e. 更新 receiving 的 storage_status + * + * @param {Object} data 请求体 + * @param {number} data.receiving_id 收货单ID(必填) + * @return {Promise} code/data/message 结构 + */ + async quickPutaway(data = {}) { + const { ctx, app } = this; + const warehouseId = ctx.user.store_id; + const receivingId = Number(data.receiving_id || data.id || 0); + + if (!receivingId) { + return { code: 400, message: 'receiving_id 必填', data: null }; + } + + const transaction = await ctx.model.transaction(); + + try { + // ────────── 1. 查询并锁定收货单 ────────── + const receiving = await ctx.model.Receiving.findOne({ + where: { + id: receivingId, + warehouse_id: warehouseId, + is_deleted: false, + }, + lock: transaction.LOCK.UPDATE, + transaction, + include: [{ + model: ctx.model.ReceivingDetail, + as: 'details', + required: false, + }], + }); + + if (!receiving) { + await transaction.rollback(); + return { code: 404, message: '收货单不存在或无权访问', data: null }; + } + + // ────────── 2. 状态校验 ────────── + if (receiving.status !== 'completed') { + await transaction.rollback(); + return { code: 400, message: `收货单状态为 ${receiving.status},须完成收货后才能入库`, data: null }; + } + + if (receiving.storage_status === 'all') { + await transaction.rollback(); + return { code: 400, message: '该收货单已全部入库,无需重复操作', data: null }; + } + + const details = receiving.details || []; + if (!details.length) { + await transaction.rollback(); + return { code: 400, message: '收货单没有明细,无法入库', data: null }; + } + + // ────────── 3. 校验所有明细已匹配系统商品 ────────── + const unmatchedDetails = details.filter(d => !d.system_product_id); + if (unmatchedDetails.length > 0) { + await transaction.rollback(); + const names = unmatchedDetails.map(d => d.product_name).join('、'); + return { + code: 400, + message: `以下商品未匹配系统商品,请先绑定:${names}`, + data: { unmatched_count: unmatchedDetails.length, unmatched_names: names }, + }; + } + + // 过滤出需要入库的明细(排除已全部入库的) + const pendingDetails = details.filter(d => d.storage_status !== 'all'); + if (!pendingDetails.length) { + await transaction.rollback(); + return { code: 400, message: '所有明细已入库完成', data: null }; + } + + // ────────── 4. 创建入库单 ────────── + // 获取仓库名称快照 + let warehouseName = ''; + const warehouseData = await ctx.service.systems.store.getStoreName(warehouseId); + if (warehouseData.code === 200 && warehouseData.data) { + warehouseName = warehouseData.data.company_name || ''; + } + + // 获取合约表备注名称(优先使用) + const contract_data = await ctx.service.systems.store.getStoreRemaskName(receiving.store_id, warehouseId); + let contract = null; + if (contract_data.code === 200) { + contract = contract_data.data; + } + + const entryOrderCode = `SCRK${Date.now()}${String(Math.floor(Math.random() * 10000)).padStart(4, '0')}`; + const entryOrder = await ctx.model.EntryOrder.create({ + entry_order_code: entryOrderCode, + order_type: 'SCRK', + purchase_order_code: receiving.receiving_number || '', + total_order_lines: pendingDetails.length, + order_create_time: new Date(), + source_type: 'WMS', + order_status: 'CREATED', + sync_status: 'SUCCESS', + sync_message: `快捷入库-来自收货单 ${receiving.receiving_number}`, + is_enabled: 1, + warehouse_id: warehouseId, + store_id: receiving.store_id || warehouseId, + store_name: contract?.store_remask || receiving.store_name || '', + warehouse_name: contract?.warehouse_remask || warehouseName, + remark: `快捷入库,关联收货单 ${receiving.receiving_number}`, + created_at: new Date(), + updated_at: new Date(), + }, { transaction }); + + // ────────── 5. 逐条处理明细:创建入库明细 + 更新库存 ────────── + const results = []; + const errors = []; + + for (let i = 0; i < pendingDetails.length; i++) { + const detail = pendingDetails[i]; + const stockWarehouseId = detail.system_product_id; + const inboundQty = (detail.actual_quantity || 0) - (detail.stored_quantity || 0); + + if (inboundQty <= 0) { + continue; // 已入库完的跳过 + } + + // 5a. 锁定 StockWarehouse 行 + const stockRecord = await ctx.model.StockWarehouse.findOne({ + where: { + id: stockWarehouseId, + is_valid: 'Y', + deleted_at: null, + }, + lock: transaction.LOCK.UPDATE, + transaction, + }); + + if (!stockRecord) { + errors.push(`商品 ${detail.product_name} 的库存记录不存在 (stock_id: ${stockWarehouseId})`); + continue; + } + + // 5b. 增加 StockWarehouse 库存数量 + await stockRecord.increment('quantity', { + by: inboundQty, + transaction, + silent: true, + }); + + // 5c. 写入/更新 wms_storage 库存位置表 + const spaceId = detail.space_id || 1; // 明细有库位则用,否则默认库位 + const batchNo = detail.batch_number || receiving.receiving_number || entryOrderCode; + const inventoryType = 'ZP'; // 默认正品 + + // 查找是否已有相同 库位+SKU+批次+类型 的库存记录 + let storageRecord = await ctx.model.Storage.findOne({ + where: { + space_id: spaceId, + stock_id: stockWarehouseId, + batch_no: batchNo, + inventory_type: inventoryType, + is_enabled: 1, + delete_at: null, + }, + lock: transaction.LOCK.UPDATE, + transaction, + }); + + if (storageRecord) { + // 已有记录:累加数量 + await ctx.model.Storage.update({ + quantity: app.Sequelize.literal(`quantity + ${inboundQty}`), + available_quantity: app.Sequelize.literal(`available_quantity + ${inboundQty}`), + entry_order_id: entryOrder.id, + }, { + where: { id: storageRecord.id }, + transaction, + }); + } else { + // 新建库存记录 + storageRecord = await ctx.model.Storage.create({ + warehouse_id: warehouseId, + store_id: receiving.store_id || warehouseId, + space_id: spaceId, + stock_id: stockWarehouseId, + batch_no: batchNo, + inventory_type: inventoryType, + quantity: inboundQty, + locked_quantity: 0, + available_quantity: inboundQty, + production_date: detail.production_date || null, + expiry_date: detail.expiry_date || null, + inbound_time: new Date(), + inbound_order_no: entryOrderCode, + receiving_id: receivingId, + entry_order_id: entryOrder.id, + supplier_id: null, + supplier_batch_no: null, + is_enabled: 1, + created_at: new Date(), + updated_at: new Date(), + }, { transaction }); + } + + // 5d. 创建入库明细 + await ctx.model.EntryItems.create({ + order_id: entryOrder.id, + order_line_no: i + 1, + item_code: stockRecord.item_code || '', + item_id: stockWarehouseId, + count: inboundQty, + inventory_type: inventoryType, + stock_id: stockWarehouseId, + received_quantity: inboundQty, + confirm_quantity: inboundQty, + }, { transaction }); + + // 5d+. 写入出入库记录 + await ctx.model.StockTransaction.create({ + transaction_type: 'INBOUND', + warehouse_id: warehouseId, + store_id: receiving.store_id || warehouseId, + stock_id: stockWarehouseId, + storage_id: storageRecord.id, + space_id: spaceId, + quantity: inboundQty, + batch_no: batchNo, + inventory_type: inventoryType, + order_type: 'SCRK', + order_no: entryOrderCode, + order_id: entryOrder.id, + receiving_id: receivingId, + entry_order_id: entryOrder.id, + operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), + operator_name: ctx.user?.employees_name || '', + remark: `快捷入库-收货单 ${receiving.receiving_number}`, + created_at: new Date(), + }, { transaction }); + + // 5e. 更新收货明细的入库状态 + const newStoredQty = (detail.stored_quantity || 0) + inboundQty; + const detailStorageStatus = newStoredQty >= detail.actual_quantity ? 'all' : 'partial'; + await ctx.model.ReceivingDetail.update({ + storage_status: detailStorageStatus, + stored_quantity: newStoredQty, + }, { + where: { id: detail.id }, + transaction, + }); + + results.push({ + detail_id: detail.id, + product_name: detail.product_name, + stock_warehouse_id: stockWarehouseId, + inbound_quantity: inboundQty, + space_id: spaceId, + storage_status: detailStorageStatus, + }); + } + + // 如果全部明细都失败 + if (results.length === 0 && errors.length > 0) { + await transaction.rollback(); + return { + code: 400, + message: `入库失败:${errors.join(';')}`, + data: null, + }; + } + + // ────────── 6. 更新入库单状态 ────────── + await entryOrder.update({ + order_status: 'COMPLETED', + total_order_lines: results.length, + updated_at: new Date(), + }, { transaction }); + + // ────────── 7. 更新收货单入库状态 ────────── + const allDetailsStored = details.every(d => { + if (d.storage_status === 'all') return true; + // 检查本次入库后是否全部完成 + const pending = pendingDetails.find(p => p.id === d.id); + if (!pending) return true; + const newStored = (pending.stored_quantity || 0) + ((pending.actual_quantity || 0) - (pending.stored_quantity || 0)); + return newStored >= pending.actual_quantity; + }); + const receivingStorageStatus = allDetailsStored ? 'all' : 'partial'; + + await ctx.model.Receiving.update({ + storage_status: receivingStorageStatus, + }, { + where: { id: receivingId }, + transaction, + }); + + // ────────── 8. 提交事务 ────────── + await transaction.commit(); + + // 记录操作日志 + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'entry', + businessId: entryOrder.id, + operationCode: 'QUICK_PUTAWAY', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId, + }, + beforeChanges: null, + }); + } catch (logErr) { + ctx.logger.warn('[quickPutaway] 写入操作日志失败,不影响业务', logErr); + } + + ctx.logger.info('[quickPutaway] 快捷入库完成', { + receiving_id: receivingId, + receiving_number: receiving.receiving_number, + entry_order_code: entryOrderCode, + entry_order_id: entryOrder.id, + total_items: results.length, + errors: errors.length, + }); + + return { + code: 200, + message: errors.length + ? `入库部分完成,${results.length} 条成功,${errors.length} 条失败` + : '快捷入库完成', + data: { + receiving_id: receivingId, + receiving_number: receiving.receiving_number, + receiving_storage_status: receivingStorageStatus, + entry_order: { + id: entryOrder.id, + entry_order_code: entryOrderCode, + order_status: 'COMPLETED', + }, + items: results, + errors: errors.length ? errors : undefined, + }, + }; + } catch (error) { + await transaction.rollback(); + ctx.logger.error('[quickPutaway] 快捷入库异常', { + receiving_id: receivingId, + error: error.message, + stack: error.stack, + }); + + if (error.name === 'SequelizeDatabaseError' && error.message.includes('Lock wait timeout')) { + return { + code: 409, + message: '库存记录被锁定,请稍后重试', + data: null, + }; + } + + throw error; + } + } + + /** + * 匹配入库:将已完成收货的收货单与已有入库单按 stock_warehouse_id 做数量匹配入库。 + * + * @param {Object} data 请求体 + * @param {number[]} data.receiving_ids 收货单ID列表 + * @param {number[]} data.entry_order_ids 入库单ID列表 + * @return {Promise} code/data/message 结构 + */ + async matchPutaway(data = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const warehouseId = ctx.user.store_id; + + // ────────── 1. 参数校验 ────────── + const receivingIds = Array.isArray(data.receiving_ids) ? data.receiving_ids.map(Number).filter(Boolean) : []; + const entryOrderIds = Array.isArray(data.entry_order_ids) ? data.entry_order_ids.map(Number).filter(Boolean) : []; + + if (!receivingIds.length) { + return { code: 400, message: 'receiving_ids 不能为空', data: null }; + } + if (!entryOrderIds.length) { + return { code: 400, message: 'entry_order_ids 不能为空', data: null }; + } + + // ────────── 2. 开事务 ────────── + const transaction = await ctx.model.transaction(); + + try { + // ────────── 3. 查询并锁定收货单 ────────── + const receivings = await ctx.model.Receiving.findAll({ + where: { + id: { [Op.in]: receivingIds }, + warehouse_id: warehouseId, + status: 'completed', + is_deleted: false, + }, + lock: transaction.LOCK.UPDATE, + transaction, + include: [{ + model: ctx.model.ReceivingDetail, + as: 'details', + required: false, + }], + }); + + if (!receivings.length) { + await transaction.rollback(); + return { code: 404, message: '未找到符合条件的收货单', data: null }; + } + + // ────────── 4. 查询并锁定入库单 ────────── + const entryOrders = await ctx.model.EntryOrder.findAll({ + where: { + id: { [Op.in]: entryOrderIds }, + warehouse_id: warehouseId, + is_enabled: 1, + deleted_at: null, + order_status: { [Op.in]: [ 'PENDING', 'CONFIRMED', 'PARTIAL_RECEIVED', 'CREATED' ] }, + }, + lock: transaction.LOCK.UPDATE, + transaction, + include: [{ + model: ctx.model.EntryItems, + as: 'items', + required: false, + }], + }); + + if (!entryOrders.length) { + await transaction.rollback(); + return { code: 404, message: '未找到符合条件的入库单', data: null }; + } + + // ────────── 5. 按 stock_warehouse_id 汇总 ────────── + // 收货侧:可入库明细(排除已全部入库的) + const rcvDetailsBySWId = {}; // stock_warehouse_id -> [ detail, ... ] + for (const rcv of receivings) { + for (const d of (rcv.details || [])) { + if (d.storage_status === 'all') continue; + if (!d.system_product_id) continue; + const available = (d.actual_quantity || 0) - (d.stored_quantity || 0); + if (available <= 0) continue; + const key = d.system_product_id; + if (!rcvDetailsBySWId[key]) rcvDetailsBySWId[key] = []; + rcvDetailsBySWId[key].push({ detail: d, available, receiving: rcv }); + } + } + + // 入库侧:待入库明细 + const entryItemsBySWId = {}; // stock_warehouse_id -> [ item, ... ] + for (const eo of entryOrders) { + for (const item of (eo.items || [])) { + if (!item.stock_id) continue; + const remaining = (item.count || 0) - (item.received_quantity || 0); + if (remaining <= 0) continue; + const key = item.stock_id; + if (!entryItemsBySWId[key]) entryItemsBySWId[key] = []; + entryItemsBySWId[key].push({ item, remaining, entryOrder: eo }); + } + } + + // ────────── 6. 逐个 stock_warehouse_id 执行匹配 ────────── + const matchedItems = []; + const unmatchedProducts = []; + const warnings = []; + + // 跟踪各明细的累计分配量 + const rcvDetailAllocated = {}; // detail.id -> allocated qty + const entryItemAllocated = {}; // item.id -> allocated qty + + // 取交集 key + const allSWIds = new Set([ + ...Object.keys(rcvDetailsBySWId), + ...Object.keys(entryItemsBySWId), + ]); + + for (const swIdStr of allSWIds) { + const swId = Number(swIdStr); + const rcvGroup = rcvDetailsBySWId[swId]; + const entryGroup = entryItemsBySWId[swId]; + + if (!rcvGroup || !entryGroup) { + if (rcvGroup && !entryGroup) { + unmatchedProducts.push({ stock_warehouse_id: swId, reason: '收货侧有库存但无对应入库计划' }); + } + if (!rcvGroup && entryGroup) { + unmatchedProducts.push({ stock_warehouse_id: swId, reason: '入库计划存在但无对应收货明细' }); + } + continue; + } + + // 计算总量 + const totalRcvAvailable = rcvGroup.reduce((s, r) => s + r.available, 0); + const totalEntryRemaining = entryGroup.reduce((s, e) => s + e.remaining, 0); + const actualInbound = Math.min(totalRcvAvailable, totalEntryRemaining); + + if (actualInbound <= 0) continue; + + if (totalRcvAvailable < totalEntryRemaining) { + warnings.push( + `stock_warehouse_id=${swId}: 收货可入库量(${totalRcvAvailable}) < 入库计划量(${totalEntryRemaining}),按收货量入库` + ); + } + + // 6a. 锁定 stock_warehouse 行并增加 quantity + const stockRecord = await ctx.model.StockWarehouse.findOne({ + where: { id: swId, is_valid: 'Y', deleted_at: null }, + lock: transaction.LOCK.UPDATE, + transaction, + }); + + if (!stockRecord) { + warnings.push(`stock_warehouse_id=${swId}: 库存记录不存在,跳过`); + continue; + } + + await stockRecord.increment('quantity', { + by: actualInbound, + transaction, + silent: true, + }); + + // 6b. 写入/更新 wms_storage(取第一个收货明细的信息) + const firstRcvDetail = rcvGroup[0].detail; + const firstRcv = rcvGroup[0].receiving; + const firstEntryOrder = entryGroup[0].entryOrder; + const spaceId = firstRcvDetail.space_id || 1; + const batchNo = firstRcvDetail.batch_number || firstRcv.receiving_number || ''; + const inventoryType = 'ZP'; + + let storageRecord = await ctx.model.Storage.findOne({ + where: { + space_id: spaceId, + stock_id: swId, + batch_no: batchNo, + inventory_type: inventoryType, + is_enabled: 1, + delete_at: null, + }, + lock: transaction.LOCK.UPDATE, + transaction, + }); + + if (storageRecord) { + await ctx.model.Storage.update({ + quantity: app.Sequelize.literal(`quantity + ${actualInbound}`), + available_quantity: app.Sequelize.literal(`available_quantity + ${actualInbound}`), + entry_order_id: firstEntryOrder.id, + }, { + where: { id: storageRecord.id }, + transaction, + }); + } else { + storageRecord = await ctx.model.Storage.create({ + warehouse_id: warehouseId, + store_id: firstRcv.store_id || warehouseId, + space_id: spaceId, + stock_id: swId, + batch_no: batchNo, + inventory_type: inventoryType, + quantity: actualInbound, + locked_quantity: 0, + available_quantity: actualInbound, + production_date: firstRcvDetail.production_date || null, + expiry_date: firstRcvDetail.expiry_date || null, + inbound_time: new Date(), + inbound_order_no: firstEntryOrder.entry_order_code, + receiving_id: firstRcv.id, + entry_order_id: firstEntryOrder.id, + supplier_id: null, + supplier_batch_no: null, + is_enabled: 1, + created_at: new Date(), + updated_at: new Date(), + }, { transaction }); + } + + // 6b+. 写入出入库记录 + await ctx.model.StockTransaction.create({ + transaction_type: 'INBOUND', + warehouse_id: warehouseId, + store_id: firstRcv.store_id || warehouseId, + stock_id: swId, + storage_id: storageRecord.id, + space_id: spaceId, + quantity: actualInbound, + batch_no: batchNo, + inventory_type: inventoryType, + order_type: 'MATCH', + order_no: firstEntryOrder.entry_order_code, + order_id: firstEntryOrder.id, + receiving_id: firstRcv.id, + entry_order_id: firstEntryOrder.id, + operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), + operator_name: ctx.user?.employees_name || '', + remark: '匹配入库', + created_at: new Date(), + }, { transaction }); + + // 6c. 分配到各个收货明细(按顺序依次扣减) + let rcvRemain = actualInbound; + for (const rcvItem of rcvGroup) { + if (rcvRemain <= 0) break; + const allocate = Math.min(rcvRemain, rcvItem.available); + rcvDetailAllocated[rcvItem.detail.id] = (rcvDetailAllocated[rcvItem.detail.id] || 0) + allocate; + rcvRemain -= allocate; + } + + // 6d. 分配到各个入库明细(按顺序依次填充) + let entryRemain = actualInbound; + for (const entryItem of entryGroup) { + if (entryRemain <= 0) break; + const allocate = Math.min(entryRemain, entryItem.remaining); + entryItemAllocated[entryItem.item.id] = (entryItemAllocated[entryItem.item.id] || 0) + allocate; + entryRemain -= allocate; + } + + matchedItems.push({ + stock_warehouse_id: swId, + item_code: stockRecord.item_code || '', + inbound_quantity: actualInbound, + rcv_available: totalRcvAvailable, + entry_planned: totalEntryRemaining, + }); + } + + if (!matchedItems.length) { + await transaction.rollback(); + return { + code: 400, + message: '没有可匹配入库的商品', + data: { unmatched_products: unmatchedProducts }, + }; + } + + // ────────── 7. 更新收货明细 stored_quantity 和 storage_status ────────── + for (const rcv of receivings) { + for (const d of (rcv.details || [])) { + const allocated = rcvDetailAllocated[d.id]; + if (!allocated) continue; + const newStoredQty = (d.stored_quantity || 0) + allocated; + const detailStorageStatus = newStoredQty >= d.actual_quantity ? 'all' : 'partial'; + await ctx.model.ReceivingDetail.update({ + stored_quantity: newStoredQty, + storage_status: detailStorageStatus, + }, { + where: { id: d.id }, + transaction, + }); + } + } + + // ────────── 8. 更新入库明细 received_quantity ────────── + for (const eo of entryOrders) { + for (const item of (eo.items || [])) { + const allocated = entryItemAllocated[item.id]; + if (!allocated) continue; + const newReceivedQty = (item.received_quantity || 0) + allocated; + await ctx.model.EntryItems.update({ + received_quantity: newReceivedQty, + }, { + where: { id: item.id }, + transaction, + }); + } + } + + // ────────── 9. 更新收货单 storage_status ────────── + const receivingResults = []; + for (const rcv of receivings) { + const details = rcv.details || []; + const allStored = details.every(d => { + const allocated = rcvDetailAllocated[d.id] || 0; + const newStored = (d.stored_quantity || 0) + allocated; + return d.storage_status === 'all' || newStored >= d.actual_quantity; + }); + const hasAny = details.some(d => { + const allocated = rcvDetailAllocated[d.id] || 0; + return d.storage_status !== 'none' || allocated > 0; + }); + const newStatus = allStored ? 'all' : (hasAny ? 'partial' : rcv.storage_status); + + if (newStatus !== rcv.storage_status) { + await ctx.model.Receiving.update({ storage_status: newStatus }, { + where: { id: rcv.id }, + transaction, + }); + } + + receivingResults.push({ + receiving_id: rcv.id, + receiving_number: rcv.receiving_number, + storage_status: newStatus, + }); + } + + // ────────── 10. 更新入库单 order_status ────────── + const entryOrderResults = []; + const completedEntryOrders = []; // 事务外回传用 + + for (const eo of entryOrders) { + const items = eo.items || []; + const allFulfilled = items.every(item => { + const allocated = entryItemAllocated[item.id] || 0; + const newReceived = (item.received_quantity || 0) + allocated; + return newReceived >= (item.count || 0); + }); + const hasAnyReceived = items.some(item => { + const allocated = entryItemAllocated[item.id] || 0; + return (item.received_quantity || 0) + allocated > 0; + }); + + let newStatus = eo.order_status; + if (allFulfilled) { + newStatus = 'COMPLETED'; + } else if (hasAnyReceived) { + newStatus = 'PARTIAL_RECEIVED'; + } + + if (newStatus !== eo.order_status) { + await ctx.model.EntryOrder.update({ + order_status: newStatus, + updated_at: new Date(), + }, { + where: { id: eo.id }, + transaction, + }); + } + + const result = { + entry_order_id: eo.id, + entry_order_code: eo.entry_order_code, + order_status: newStatus, + source_type: eo.source_type, + callback_status: null, + }; + entryOrderResults.push(result); + + if (allFulfilled) { + completedEntryOrders.push({ entryOrder: eo, result }); + } else { + warnings.push( + `入库单 ${eo.entry_order_code}: 未全部入库完成(${newStatus}),不触发回传,需手工操作或等待其他收货入库` + ); + } + } + + // ────────── 12. 提交事务 ────────── + await transaction.commit(); + + // ────────── 13. 事务外:对已完成的入库单触发回传 ────────── + for (const { entryOrder, result } of completedEntryOrders) { + try { + if (entryOrder.source_type === 'QM') { + const confirmResult = await ctx.service.systems.entryOrder.entryorderConfirm(entryOrder.id, true); + result.callback_status = confirmResult.success ? 'SUCCESS' : 'FAILED'; + result.callback_detail = confirmResult; + } else if (entryOrder.source_type === 'API') { + const callbackResult = await this.apiCallback(entryOrder); + result.callback_status = callbackResult.success ? 'SUCCESS' : (callbackResult.skipped ? 'SKIPPED' : 'FAILED'); + result.callback_detail = callbackResult; + } else { + result.callback_status = 'NOT_REQUIRED'; + } + } catch (cbErr) { + ctx.logger.error(`[matchPutaway] 入库单 ${entryOrder.entry_order_code} 回传异常`, cbErr); + result.callback_status = 'ERROR'; + result.callback_detail = { error: cbErr.message }; + } + } + + // ────────── 14. 记录操作日志 ────────── + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'entry', + businessId: entryOrderIds.join(','), + operationCode: 'MATCH_PUTAWAY', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { warehouseId, receivingIds, entryOrderIds }, + beforeChanges: null, + }); + } catch (logErr) { + ctx.logger.warn('[matchPutaway] 写入操作日志失败,不影响业务', logErr); + } + + ctx.logger.info('[matchPutaway] 匹配入库完成', { + receiving_ids: receivingIds, + entry_order_ids: entryOrderIds, + matched_count: matchedItems.length, + unmatched_count: unmatchedProducts.length, + warnings_count: warnings.length, + }); + + // ────────── 15. 返回结果 ────────── + return { + code: 200, + message: '匹配入库完成', + data: { + matched_items: matchedItems, + receiving_results: receivingResults, + entry_order_results: entryOrderResults, + unmatched_products: unmatchedProducts, + warnings: warnings.length ? warnings : undefined, + }, + }; + } catch (error) { + await transaction.rollback(); + ctx.logger.error('[matchPutaway] 匹配入库异常', { + receiving_ids: receivingIds, + entry_order_ids: entryOrderIds, + error: error.message, + stack: error.stack, + }); + + if (error.name === 'SequelizeDatabaseError' && error.message.includes('Lock wait timeout')) { + return { code: 409, message: '库存记录被锁定,请稍后重试', data: null }; + } + + throw error; + } + } + + /** + * 移库(库位转移):将单条库存从一个库位移动到另一个库位。 + * 支持部分/全量移库、目标库位合并。 + * + * @param {Object} data 请求体 + * @param {number} data.storage_id 库存记录ID(必填) + * @param {number} data.target_space_id 目标库位ID(必填) + * @param {number} [data.quantity] 移库数量(可选,默认全部移动) + * @return {Promise} code/data/message 结构 + */ + async transferLocation(data = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + // ────────── 1. 参数校验 ────────── + const storageId = Number(data.storage_id || 0); + if (!storageId) { + return { code: 400, message: 'storage_id 必填', data: null }; + } + + const targetSpaceId = Number(data.target_space_id || 0); + if (!targetSpaceId) { + return { code: 400, message: 'target_space_id 必填', data: null }; + } + + if (data.quantity !== undefined && data.quantity !== null) { + const qty = Number(data.quantity); + if (!Number.isFinite(qty) || qty <= 0) { + return { code: 400, message: 'quantity 必须为正数', data: null }; + } + } + + // ────────── 2. 开事务 ────────── + const transaction = await ctx.model.transaction(); + + try { + // ────────── 3. 锁定并校验原库存记录 ────────── + const srcRecord = await ctx.model.Storage.findOne({ + where: { + id: storageId, + is_enabled: 1, + delete_at: null, + }, + lock: transaction.LOCK.UPDATE, + transaction, + }); + + if (!srcRecord) { + await transaction.rollback(); + return { code: 404, message: `库存记录不存在: storage_id=${storageId}`, data: null }; + } + + const warehouseId = srcRecord.warehouse_id; + + // ────────── 4. 校验目标库位 ────────── + const targetSpace = await ctx.model.LocationSpace.findOne({ + where: { + id: targetSpaceId, + is_enabled: true, + }, + lock: transaction.LOCK.UPDATE, + transaction, + }); + + if (!targetSpace) { + await transaction.rollback(); + return { code: 404, message: `目标库位不存在或未启用: space_id=${targetSpaceId}`, data: null }; + } + if (targetSpace.warehouse_id !== warehouseId) { + await transaction.rollback(); + return { code: 400, message: `目标库位 ${targetSpaceId} 不属于仓库 ${warehouseId}`, data: null }; + } + if (![ 'AVAILABLE', 'OCCUPIED' ].includes(targetSpace.space_status)) { + await transaction.rollback(); + return { + code: 400, + message: `目标库位 ${targetSpace.space_code} 状态为 ${targetSpace.space_status},不可移入`, + data: null, + }; + } + + // ────────── 5. 处理移库 ────────── + const availableQty = srcRecord.quantity - srcRecord.locked_quantity; + const transferQty = (data.quantity !== undefined && data.quantity !== null) + ? Number(data.quantity) + : availableQty; + + // 校验移库数量 + if (transferQty > availableQty) { + await transaction.rollback(); + return { + code: 400, + message: `库存记录 ${storageId} 可用数量不足:可用 ${availableQty},请求移库 ${transferQty}`, + data: null, + }; + } + + // 原库位与目标库位相同则直接返回 + if (srcRecord.space_id === targetSpaceId) { + await transaction.rollback(); + return { + code: 200, + message: '原库位与目标库位相同,无需移库', + data: { + storage_id: storageId, + target_space_id: targetSpaceId, + transfer_quantity: 0, + status: 'skipped', + }, + }; + } + + const beforeSnapshot = { + storage_id: storageId, + space_id: srcRecord.space_id, + quantity: srcRecord.quantity, + available_quantity: srcRecord.available_quantity, + }; + + const isFullTransfer = (transferQty === srcRecord.quantity); + + // 查找目标库位是否已有相同 stock_id + batch_no + inventory_type 的记录 + const existingTarget = await ctx.model.Storage.findOne({ + where: { + space_id: targetSpaceId, + stock_id: srcRecord.stock_id, + batch_no: srcRecord.batch_no, + inventory_type: srcRecord.inventory_type, + is_enabled: 1, + delete_at: null, + id: { [Op.ne]: storageId }, // 排除自身(全量移库时直接改 space_id 的情况) + }, + lock: transaction.LOCK.UPDATE, + transaction, + }); + + let afterSnapshot; + // 原库位统计变化 + const srcSpaceDelta = { skuDelta: 0, qtyDelta: 0 }; + // 目标库位统计变化 + const tgtSpaceDelta = { skuDelta: 0, qtyDelta: 0 }; + + if (existingTarget) { + // ── 目标库位已有同规格记录:合并数量 ── + await ctx.model.Storage.update({ + quantity: app.Sequelize.literal(`quantity + ${transferQty}`), + available_quantity: app.Sequelize.literal(`available_quantity + ${transferQty}`), + updated_at: new Date(), + }, { + where: { id: existingTarget.id }, + transaction, + }); + + if (isFullTransfer) { + // 全量移库且合并:删除原记录 + await ctx.model.Storage.update({ + is_enabled: 0, + delete_at: new Date(), + updated_at: new Date(), + }, { + where: { id: storageId }, + transaction, + }); + srcSpaceDelta.qtyDelta -= srcRecord.quantity; + // 检查原库位该 SKU 是否还有其他记录 + const remainingSku = await ctx.model.Storage.count({ + where: { + space_id: srcRecord.space_id, + stock_id: srcRecord.stock_id, + is_enabled: 1, + delete_at: null, + id: { [Op.ne]: storageId }, + }, + transaction, + }); + if (remainingSku === 0) { + srcSpaceDelta.skuDelta -= 1; + } + } else { + // 部分移库:减少原记录数量 + await ctx.model.Storage.update({ + quantity: app.Sequelize.literal(`quantity - ${transferQty}`), + available_quantity: app.Sequelize.literal(`available_quantity - ${transferQty}`), + updated_at: new Date(), + }, { + where: { id: storageId }, + transaction, + }); + srcSpaceDelta.qtyDelta -= transferQty; + } + + // 目标库位数量增加 + tgtSpaceDelta.qtyDelta += transferQty; + // 目标库位该 SKU 之前已有记录,skuDelta 不变 + + afterSnapshot = { + merged_into: existingTarget.id, + target_space_id: targetSpaceId, + transfer_quantity: transferQty, + source_deleted: isFullTransfer, + }; + } else if (isFullTransfer) { + // ── 全量移库 & 目标无同规格记录:直接修改 space_id ── + await ctx.model.Storage.update({ + space_id: targetSpaceId, + updated_at: new Date(), + }, { + where: { id: storageId }, + transaction, + }); + + srcSpaceDelta.qtyDelta -= srcRecord.quantity; + // 检查原库位该 SKU 是否还有其他记录 + const remainingSku = await ctx.model.Storage.count({ + where: { + space_id: srcRecord.space_id, + stock_id: srcRecord.stock_id, + is_enabled: 1, + delete_at: null, + id: { [Op.ne]: storageId }, + }, + transaction, + }); + if (remainingSku === 0) { + srcSpaceDelta.skuDelta -= 1; + } + + // 目标库位新增一个 SKU + const existingSkuInTarget = await ctx.model.Storage.count({ + where: { + space_id: targetSpaceId, + stock_id: srcRecord.stock_id, + is_enabled: 1, + delete_at: null, + id: { [Op.ne]: storageId }, // 排掉自身(此时 space_id 已更新,但事务内逻辑用旧值) + }, + transaction, + }); + if (existingSkuInTarget === 0) { + tgtSpaceDelta.skuDelta += 1; + } + tgtSpaceDelta.qtyDelta += srcRecord.quantity; + + afterSnapshot = { + storage_id: storageId, + target_space_id: targetSpaceId, + transfer_quantity: transferQty, + source_deleted: false, + }; + } else { + // ── 部分移库 & 目标无同规格记录:减少原记录数量,新建目标记录 ── + await ctx.model.Storage.update({ + quantity: app.Sequelize.literal(`quantity - ${transferQty}`), + available_quantity: app.Sequelize.literal(`available_quantity - ${transferQty}`), + updated_at: new Date(), + }, { + where: { id: storageId }, + transaction, + }); + + const newRecord = await ctx.model.Storage.create({ + warehouse_id: srcRecord.warehouse_id, + store_id: srcRecord.store_id, + space_id: targetSpaceId, + stock_id: srcRecord.stock_id, + batch_no: srcRecord.batch_no, + inventory_type: srcRecord.inventory_type, + quantity: transferQty, + locked_quantity: 0, + available_quantity: transferQty, + production_date: srcRecord.production_date, + expiry_date: srcRecord.expiry_date, + inbound_time: srcRecord.inbound_time, + inbound_order_no: srcRecord.inbound_order_no, + receiving_id: srcRecord.receiving_id, + entry_order_id: srcRecord.entry_order_id, + supplier_id: srcRecord.supplier_id, + supplier_batch_no: srcRecord.supplier_batch_no, + is_enabled: 1, + created_at: new Date(), + updated_at: new Date(), + }, { transaction }); + + srcSpaceDelta.qtyDelta -= transferQty; + // 原库位 SKU 数不变(原记录仍在) + + // 目标库位:新增 SKU + const existingSkuInTarget = await ctx.model.Storage.count({ + where: { + space_id: targetSpaceId, + stock_id: srcRecord.stock_id, + is_enabled: 1, + delete_at: null, + }, + transaction, + }); + // count 包含刚 create 的记录,如果只有 1 条说明之前没有 + if (existingSkuInTarget <= 1) { + tgtSpaceDelta.skuDelta += 1; + } + tgtSpaceDelta.qtyDelta += transferQty; + + afterSnapshot = { + new_storage_id: newRecord.id, + target_space_id: targetSpaceId, + transfer_quantity: transferQty, + source_deleted: false, + }; + } + + // ────────── 记录操作日志(事务内) ────────── + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'storage', + businessId: storageId, + operationCode: 'STORAGE_TRANSFER_LOCATION', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId, + target_space_id: targetSpaceId, + transfer_quantity: transferQty, + }, + beforeChanges: beforeSnapshot, + afterChanges: afterSnapshot, + }); + } catch (logErr) { + ctx.logger.warn('[inventory.transferLocation] 写入操作日志失败,不影响业务', logErr); + } + + // ────────── 6. 更新库位统计 ────────── + const updateSpaceStats = async (spaceId, delta) => { + if (delta.qtyDelta === 0 && delta.skuDelta === 0) return; + const updateFields = {}; + if (delta.qtyDelta !== 0) { + updateFields.current_quantity = app.Sequelize.literal( + `GREATEST(COALESCE(current_quantity, 0) + (${delta.qtyDelta}), 0)` + ); + } + if (delta.skuDelta !== 0) { + updateFields.current_sku_count = app.Sequelize.literal( + `GREATEST(COALESCE(current_sku_count, 0) + (${delta.skuDelta}), 0)` + ); + } + await ctx.model.LocationSpace.update(updateFields, { + where: { id: spaceId }, + transaction, + }); + }; + + await updateSpaceStats(srcRecord.space_id, srcSpaceDelta); + await updateSpaceStats(targetSpaceId, tgtSpaceDelta); + + // ────────── 7. 提交事务 ────────── + await transaction.commit(); + + // ────────── 8. 发送通知(事务外) ────────── + try { + await ctx.service.systems.notice.send({ + event: 'storage_transfer_completed', + businessName: 'storage', + warehouseId, + subjectId: warehouseId, + title: '移库操作完成', + content: `移库完成:库存${storageId} -> 库位${targetSpaceId}(数量:${transferQty})`, + data: { warehouse_id: warehouseId, storage_id: storageId, target_space_id: targetSpaceId, transfer_quantity: transferQty }, + sender: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + }); + } catch (noticeErr) { + ctx.logger.warn('[inventory.transferLocation] 发送通知失败,不影响业务', noticeErr); + } + + ctx.logger.info('[inventory.transferLocation] 移库完成', { + warehouse_id: warehouseId, + storage_id: storageId, + target_space_id: targetSpaceId, + transfer_quantity: transferQty, + }); + + return { + code: 200, + message: '移库完成', + data: { + storage_id: storageId, + stock_id: srcRecord.stock_id, + target_space_id: targetSpaceId, + transfer_quantity: transferQty, + status: 'success', + }, + }; + } catch (error) { + await transaction.rollback(); + ctx.logger.error('[inventory.transferLocation] 移库异常', { + storage_id: storageId, + target_space_id: targetSpaceId, + error: error.message, + stack: error.stack, + }); + + if (error.name === 'SequelizeDatabaseError' && error.message.includes('Lock wait timeout')) { + return { code: 409, message: '库存记录被锁定,请稍后重试', data: null }; + } + + throw error; + } + } + + /** + * 按库位+商品维度移库。 + * 自动查找该库位下该商品的所有 storage 记录,按 quantity ASC 逐条扣减并合并移动到目标库位。 + * + * @param {Object} data 请求体 + * @param {number} data.space_id 原库位ID(必填) + * @param {number} data.stock_id 商品SKU ID(必填,对应 wms_stock_warehouse.id) + * @param {number} data.target_space_id 目标库位ID(必填) + * @param {number} data.quantity 移库数量(必填) + * @return {Promise} code/data/message 结构 + */ + async transferByProduct(data = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + // ────────── 1. 参数校验 ────────── + const spaceId = Number(data.space_id || 0); + const stockId = Number(data.stock_id || 0); + const targetSpaceId = Number(data.target_space_id || 0); + const quantity = Number(data.quantity || 0); + + if (!spaceId) { + return { code: 400, message: 'space_id 必填', data: null }; + } + if (!stockId) { + return { code: 400, message: 'stock_id 必填', data: null }; + } + if (!targetSpaceId) { + return { code: 400, message: 'target_space_id 必填', data: null }; + } + if (!Number.isFinite(quantity) || quantity <= 0) { + return { code: 400, message: 'quantity 必须为正数', data: null }; + } + + // ────────── 2. 批次管理校验 ────────── + const stockWarehouse = await ctx.model.StockWarehouse.findOne({ + where: { id: stockId }, + attributes: [ 'id', 'is_batch_mgmt' ], + }); + if (!stockWarehouse) { + return { code: 404, message: `商品SKU不存在: stock_id=${stockId}`, data: null }; + } + if (stockWarehouse.is_batch_mgmt === 'Y') { + return { + code: 400, + message: '该商品已开启批次管理,请使用按库存记录移库(transferLocation)', + data: null, + }; + } + + // ────────── 3. 原库位与目标库位相同 ────────── + if (spaceId === targetSpaceId) { + return { + code: 200, + message: '原库位与目标库位相同,无需移库', + data: { + space_id: spaceId, + stock_id: stockId, + target_space_id: targetSpaceId, + transfer_quantity: 0, + affected_storage_count: 0, + status: 'skipped', + }, + }; + } + + // ────────── 4. 开事务 ────────── + const transaction = await ctx.model.transaction(); + + try { + // ────────── 5. 查找并锁定原库存记录 ────────── + const srcRecords = await ctx.model.Storage.findAll({ + where: { + space_id: spaceId, + stock_id: stockId, + is_enabled: 1, + delete_at: null, + }, + order: [[ 'quantity', 'ASC' ]], + lock: transaction.LOCK.UPDATE, + transaction, + }); + + if (!srcRecords.length) { + await transaction.rollback(); + return { code: 404, message: `原库位 ${spaceId} 下未找到商品 ${stockId} 的库存记录`, data: null }; + } + + const totalAvailable = srcRecords.reduce((sum, r) => sum + (r.quantity - r.locked_quantity), 0); + if (quantity > totalAvailable) { + await transaction.rollback(); + return { + code: 400, + message: `可用数量不足:可用 ${totalAvailable},请求移库 ${quantity}`, + data: null, + }; + } + + const warehouseId = srcRecords[0].warehouse_id; + + // ────────── 6. 校验目标库位 ────────── + const targetSpace = await ctx.model.LocationSpace.findOne({ + where: { + id: targetSpaceId, + is_enabled: true, + }, + lock: transaction.LOCK.UPDATE, + transaction, + }); + + if (!targetSpace) { + await transaction.rollback(); + return { code: 404, message: `目标库位不存在或未启用: space_id=${targetSpaceId}`, data: null }; + } + if (targetSpace.warehouse_id !== warehouseId) { + await transaction.rollback(); + return { code: 400, message: `目标库位 ${targetSpaceId} 不属于仓库 ${warehouseId}`, data: null }; + } + if (![ 'AVAILABLE', 'OCCUPIED' ].includes(targetSpace.space_status)) { + await transaction.rollback(); + return { + code: 400, + message: `目标库位 ${targetSpace.space_code} 状态为 ${targetSpace.space_status},不可移入`, + data: null, + }; + } + + // ────────── 7. 逐条扣减并移库 ────────── + let remainingQty = quantity; + let affectedCount = 0; + const srcSpaceDelta = { skuDelta: 0, qtyDelta: 0 }; + const tgtSpaceDelta = { skuDelta: 0, qtyDelta: 0 }; + + // 预先记录目标库位是否已有该 SKU(用于事后计算 skuDelta) + const tgtSkuCountBefore = await ctx.model.Storage.count({ + where: { + space_id: targetSpaceId, + stock_id: stockId, + is_enabled: 1, + delete_at: null, + }, + transaction, + }); + + for (const srcRecord of srcRecords) { + if (remainingQty <= 0) break; + + const available = srcRecord.quantity - srcRecord.locked_quantity; + const toTransfer = Math.min(available, remainingQty); + if (toTransfer <= 0) continue; + + affectedCount++; + const isFullTransfer = (toTransfer === srcRecord.quantity); + + // ── 在目标库位查找同 stock_id + batch_no + inventory_type 的记录 ── + const existingTarget = await ctx.model.Storage.findOne({ + where: { + space_id: targetSpaceId, + stock_id: srcRecord.stock_id, + batch_no: srcRecord.batch_no, + inventory_type: srcRecord.inventory_type, + is_enabled: 1, + delete_at: null, + id: { [Op.ne]: srcRecord.id }, + }, + lock: transaction.LOCK.UPDATE, + transaction, + }); + + if (existingTarget) { + // 目标已有同规格记录:合并数量 + await ctx.model.Storage.update({ + quantity: app.Sequelize.literal(`quantity + ${toTransfer}`), + available_quantity: app.Sequelize.literal(`available_quantity + ${toTransfer}`), + updated_at: new Date(), + }, { + where: { id: existingTarget.id }, + transaction, + }); + + if (isFullTransfer) { + // 全量:软删除原记录 + await ctx.model.Storage.update({ + is_enabled: 0, + delete_at: new Date(), + updated_at: new Date(), + }, { + where: { id: srcRecord.id }, + transaction, + }); + } else { + // 部分:减少原记录 + await ctx.model.Storage.update({ + quantity: app.Sequelize.literal(`quantity - ${toTransfer}`), + available_quantity: app.Sequelize.literal(`available_quantity - ${toTransfer}`), + updated_at: new Date(), + }, { + where: { id: srcRecord.id }, + transaction, + }); + } + } else if (isFullTransfer) { + // 全量移库 & 目标无同规格记录:直接改 space_id + await ctx.model.Storage.update({ + space_id: targetSpaceId, + updated_at: new Date(), + }, { + where: { id: srcRecord.id }, + transaction, + }); + } else { + // 部分移库 & 目标无同规格记录:减少原记录,新建目标记录 + await ctx.model.Storage.update({ + quantity: app.Sequelize.literal(`quantity - ${toTransfer}`), + available_quantity: app.Sequelize.literal(`available_quantity - ${toTransfer}`), + updated_at: new Date(), + }, { + where: { id: srcRecord.id }, + transaction, + }); + + await ctx.model.Storage.create({ + warehouse_id: srcRecord.warehouse_id, + store_id: srcRecord.store_id, + space_id: targetSpaceId, + stock_id: srcRecord.stock_id, + batch_no: srcRecord.batch_no, + inventory_type: srcRecord.inventory_type, + quantity: toTransfer, + locked_quantity: 0, + available_quantity: toTransfer, + production_date: srcRecord.production_date, + expiry_date: srcRecord.expiry_date, + inbound_time: srcRecord.inbound_time, + inbound_order_no: srcRecord.inbound_order_no, + receiving_id: srcRecord.receiving_id, + entry_order_id: srcRecord.entry_order_id, + supplier_id: srcRecord.supplier_id, + supplier_batch_no: srcRecord.supplier_batch_no, + is_enabled: 1, + created_at: new Date(), + updated_at: new Date(), + }, { transaction }); + } + + srcSpaceDelta.qtyDelta -= toTransfer; + tgtSpaceDelta.qtyDelta += toTransfer; + remainingQty -= toTransfer; + } + + // ── 计算 SKU 维度统计变化 ── + const remainingSrcSku = await ctx.model.Storage.count({ + where: { + space_id: spaceId, + stock_id: stockId, + is_enabled: 1, + delete_at: null, + }, + transaction, + }); + if (remainingSrcSku === 0) { + srcSpaceDelta.skuDelta -= 1; + } + + if (tgtSkuCountBefore === 0) { + // 操作前目标库位没有该 SKU,现在有了 + tgtSpaceDelta.skuDelta += 1; + } + + // ────────── 8. 操作日志 ────────── + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'storage', + businessId: spaceId, + operationCode: 'STORAGE_TRANSFER_BY_PRODUCT', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId, + space_id: spaceId, + stock_id: stockId, + target_space_id: targetSpaceId, + transfer_quantity: quantity, + affected_storage_count: affectedCount, + }, + beforeChanges: { + space_id: spaceId, + stock_id: stockId, + total_available: totalAvailable, + source_record_count: srcRecords.length, + }, + afterChanges: { + target_space_id: targetSpaceId, + transfer_quantity: quantity, + affected_storage_count: affectedCount, + }, + }); + } catch (logErr) { + ctx.logger.warn('[inventory.transferByProduct] 写入操作日志失败,不影响业务', logErr); + } + + // ────────── 9. 更新库位统计 ────────── + const updateSpaceStats = async (updateSpaceId, delta) => { + if (delta.qtyDelta === 0 && delta.skuDelta === 0) return; + const updateFields = {}; + if (delta.qtyDelta !== 0) { + updateFields.current_quantity = app.Sequelize.literal( + `GREATEST(COALESCE(current_quantity, 0) + (${delta.qtyDelta}), 0)` + ); + } + if (delta.skuDelta !== 0) { + updateFields.current_sku_count = app.Sequelize.literal( + `GREATEST(COALESCE(current_sku_count, 0) + (${delta.skuDelta}), 0)` + ); + } + await ctx.model.LocationSpace.update(updateFields, { + where: { id: updateSpaceId }, + transaction, + }); + }; + + await updateSpaceStats(spaceId, srcSpaceDelta); + await updateSpaceStats(targetSpaceId, tgtSpaceDelta); + + // ────────── 10. 提交事务 ────────── + await transaction.commit(); + + // ────────── 11. 发送通知(事务外) ────────── + try { + await ctx.service.systems.notice.send({ + event: 'storage_transfer_completed', + businessName: 'storage', + warehouseId, + subjectId: warehouseId, + title: '按商品移库操作完成', + content: `按商品移库完成:库位${spaceId} 商品${stockId} -> 库位${targetSpaceId}(数量:${quantity},涉及${affectedCount}条记录)`, + data: { + warehouse_id: warehouseId, + space_id: spaceId, + stock_id: stockId, + target_space_id: targetSpaceId, + transfer_quantity: quantity, + affected_storage_count: affectedCount, + }, + sender: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + }); + } catch (noticeErr) { + ctx.logger.warn('[inventory.transferByProduct] 发送通知失败,不影响业务', noticeErr); + } + + ctx.logger.info('[inventory.transferByProduct] 按商品移库完成', { + warehouse_id: warehouseId, + space_id: spaceId, + stock_id: stockId, + target_space_id: targetSpaceId, + transfer_quantity: quantity, + affected_storage_count: affectedCount, + }); + + return { + code: 200, + message: '按商品移库完成', + data: { + space_id: spaceId, + stock_id: stockId, + target_space_id: targetSpaceId, + transfer_quantity: quantity, + affected_storage_count: affectedCount, + warehouse_id: warehouseId, + }, + }; + } catch (error) { + await transaction.rollback(); + ctx.logger.error('[inventory.transferByProduct] 按商品移库异常', { + space_id: spaceId, + stock_id: stockId, + target_space_id: targetSpaceId, + quantity, + error: error.message, + stack: error.stack, + }); + + if (error.name === 'SequelizeDatabaseError' && error.message.includes('Lock wait timeout')) { + return { code: 409, message: '库存记录被锁定,请稍后重试', data: null }; + } + + throw error; + } + } + + /** + * API 入库单回调:向 api_app 配置的 callback_url 发送入库确认通知。 + * + * @param {Object} entryOrder 入库单实例 + * @return {Promise} { success, skipped?, status?, error? } + */ + async apiCallback(entryOrder) { + const { ctx, app } = this; + try { + const apiApp = await app.model.ApiApp.findOne({ + where: { + warehouse_id: entryOrder.warehouse_id, + is_enabled: 1, + }, + }); + + if (!apiApp || !apiApp.callback_url) { + ctx.logger.info('[matchPutaway] 未找到API回调配置或无回调地址,跳过回调'); + return { success: true, skipped: true }; + } + + const items = await app.model.EntryItems.findAll({ + where: { order_id: entryOrder.id }, + }); + + const payload = { + entry_order_code: entryOrder.entry_order_code, + order_type: entryOrder.order_type, + order_status: 'COMPLETED', + warehouse_id: entryOrder.warehouse_id, + store_id: entryOrder.store_id, + items: items.map(item => ({ + item_code: item.item_code, + item_id: item.item_id, + plan_quantity: item.count, + received_quantity: item.received_quantity, + confirm_quantity: item.received_quantity, + })), + confirm_time: new Date().toISOString(), + }; + + const response = await ctx.curl(apiApp.callback_url, { + method: 'POST', + contentType: 'json', + data: payload, + timeout: 10000, + dataType: 'json', + }); + + ctx.logger.info('[matchPutaway] API回调结果', { + entry_order_id: entryOrder.id, + callback_url: apiApp.callback_url, + status: response.status, + }); + + return { success: response.status === 200, status: response.status }; + } catch (err) { + ctx.logger.error('[matchPutaway] API回调失败', err); + return { success: false, error: err.message }; + } + } + + /** + * 库存列表查询。 + * @param {Object} pageParams 分页参数 + * @param {Object} sortParams 排序参数 + * @param {boolean} groupByBatch 是否按批次 + */ + async getInventoryList(pageParams = {}, sortParams = {}, groupByBatch = false) { + const { ctx, app } = this; + const { Op, fn, col, literal } = app.Sequelize; + + const warehouseId = ctx.user.store_id; + const { page = 1, pageSize = 20 } = pageParams; + const { sortField = 'created_at', sortOrder = 'DESC' } = sortParams; + + // 基础条件 + const baseWhere = { + [Op.and]: [ + { warehouse_id: warehouseId }, + { is_enabled: 1 }, + { delete_at: null }, + ], + }; + + // 动态 where 条件 + const parsed = ctx.whereParsed; + if (parsed && parsed.dynamicConditions && parsed.dynamicConditions.length > 0) { + baseWhere[Op.and].push(...parsed.dynamicConditions); + } + + const offset = (page - 1) * pageSize; + const limit = pageSize; + + if (groupByBatch) { + // 按批次明细:逐条返回 + const { count: total, rows } = await ctx.model.Storage.findAndCountAll({ + where: baseWhere, + order: [[ sortField, sortOrder ]], + offset, + limit, + include: [ + { + model: ctx.model.StockWarehouse, + as: 'stock', + attributes: [ 'id', 'item_code', 'item_name', 'sku_property', 'stock_unit' ], + required: false, + }, + { + model: ctx.model.LocationSpace, + as: 'space', + attributes: [ 'id', 'space_code', 'custom_name' ], + required: false, + }, + ], + }); + + const list = rows.map(item => { + const row = item.get({ plain: true }); + row.created_at = row.created_at ? app.formatDate(row.created_at) : ''; + row.updated_at = row.updated_at ? app.formatDate(row.updated_at) : ''; + row.inbound_time = row.inbound_time ? app.formatDate(row.inbound_time) : ''; + row.production_date = row.production_date ? app.formatDate(row.production_date) : ''; + row.expiry_date = row.expiry_date ? app.formatDate(row.expiry_date) : ''; + return row; + }); + + return { + list, + pagination: { + page, + pageSize, + total, + totalPages: Math.ceil(total / pageSize), + }, + }; + } + + // 不按批次:按 stock_id + space_id + inventory_type 合并 + const groupFields = [ 'stock_id', 'space_id', 'inventory_type', 'warehouse_id', 'store_id' ]; + + const countResult = await ctx.model.Storage.count({ + where: baseWhere, + group: groupFields, + }); + const total = Array.isArray(countResult) ? countResult.length : countResult; + + const rows = await ctx.model.Storage.findAll({ + where: baseWhere, + attributes: [ + 'stock_id', + 'space_id', + 'inventory_type', + 'warehouse_id', + 'store_id', + [ fn('SUM', col('wms_storage.quantity')), 'quantity' ], + [ fn('SUM', col('wms_storage.locked_quantity')), 'locked_quantity' ], + [ fn('SUM', col('wms_storage.available_quantity')), 'available_quantity' ], + [ fn('MIN', col('wms_storage.inbound_time')), 'first_inbound_time' ], + [ fn('MAX', col('wms_storage.inbound_time')), 'last_inbound_time' ], + [ fn('COUNT', col('wms_storage.id')), 'batch_count' ], + ], + group: groupFields, + order: [[ literal('last_inbound_time'), sortOrder ]], + offset, + limit, + include: [ + { + model: ctx.model.StockWarehouse, + as: 'stock', + attributes: [ 'id', 'item_code', 'item_name', 'sku_property', 'stock_unit' ], + required: false, + }, + { + model: ctx.model.LocationSpace, + as: 'space', + attributes: [ 'id', 'space_code', 'custom_name' ], + required: false, + }, + ], + raw: true, + nest: true, + }); + + const list = rows.map(row => { + row.first_inbound_time = row.first_inbound_time ? app.formatDate(row.first_inbound_time) : ''; + row.last_inbound_time = row.last_inbound_time ? app.formatDate(row.last_inbound_time) : ''; + return row; + }); + + return { + list, + pagination: { + page, + pageSize, + total, + totalPages: Math.ceil(total / pageSize), + }, + }; + } +} + +module.exports = InventoryService; diff --git a/app/service/systems/storage/receiving.js b/app/service/systems/storage/receiving.js index b165865..8a316e2 100644 --- a/app/service/systems/storage/receiving.js +++ b/app/service/systems/storage/receiving.js @@ -16,7 +16,6 @@ class ReceivingService extends Service { const { ctx, app, - config, } = this; const { Sequelize, @@ -389,6 +388,28 @@ class ReceivingService extends Service { } // 批量更新状态为cancelled await ctx.model.Receiving.update({ status: 'cancelled' }, { where: { id: { [Op.in]: ids }, warehouse_id } }); + + // 批量记录操作日志 + 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, + }) + )); + } catch (logErr) { + ctx.logger.warn('[receiving.batchCancelReceiving] 写入操作日志失败,不影响业务', logErr); + } + return { code: 200, message: '批量作废成功', data: {} }; } catch (error) { @@ -423,7 +444,7 @@ class ReceivingService extends Service { Sequelize, } = app; const { - operator = 'eq', value, type, isMultiple, + operator = 'eq', value, type, } = condition; // 处理字段名 @@ -626,8 +647,6 @@ class ReceivingService extends Service { // 处理日期范围:数组的第一个元素是开始时间,第二个元素是结束时间 if (Array.isArray(value) && value.length === 2) { const [ startDate, endDate ] = value; - console.log(startDate, endDate); - console.log(startDate ? service.main.normalizeDate(startDate, false) : null, endDate ? service.main.normalizeDate(endDate, true) : null); return [ startDate ? service.main.normalizeDate(startDate, false) : null, // 开始时间设为00:00:00 endDate ? service.main.normalizeDate(endDate, true) : null, // 结束时间设为23:59:59 @@ -636,12 +655,11 @@ class ReceivingService extends Service { return value; case 'number': - // 转换为数字 + { const num = parseFloat(value); return isNaN(num) ? value : num; - + } case 'text': - // 文本类型,支持逗号分隔 if (typeof value === 'string') { return value.split(',').map(item => item.trim()); } @@ -729,7 +747,6 @@ class ReceivingService extends Service { // 2. 生成收货单号。注意:`wms_receiving.receiving_number` 在数据库中是全局唯一索引, // 不能按 warehouse_id 各自从 001 开始,否则跨仓会撞号;并发创建时也需要重试兜底。 const now = new Date(); - console.log('当前时间:', now); const prefix = this.buildReceivingNumberPrefix(now); // 3. 获取店铺名称(如果有货主) @@ -798,6 +815,25 @@ class ReceivingService extends Service { throw lastCreateError || new Error('创建收货任务失败'); } + // 记录操作日志 + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'receiving', + businessId: result.id, + operationCode: 'RECEIVING_CREATE', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: warehouse_id, + }, + beforeChanges: null, + }); + } catch (logErr) { + ctx.logger.warn('[receiving.create] 写入操作日志失败,不影响业务', logErr); + } + return { code: 200, id: result.id, @@ -923,6 +959,28 @@ class ReceivingService extends Service { await transaction.commit(); + // 记录操作日志 + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'receiving', + businessId: receivingId, + operationCode: 'RECEIVING_BIND_STORE', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId, + }, + beforeChanges: { + store_id: receiving.store_id, + store_name: receiving.store_name, + }, + }); + } catch (logErr) { + ctx.logger.warn('[receiving.bindStore] 写入操作日志失败,不影响业务', logErr); + } + return { code: 200, message: '绑定货主成功', @@ -956,7 +1014,6 @@ class ReceivingService extends Service { // 获取用户仓库ID,增加错误处理 const warehouseId = ctx.user?.store_id; - const creator_id = ctx.user.employees_id; if (!warehouseId) { return { code: 0, message: '用户未绑定仓库', data: {} }; } @@ -989,7 +1046,6 @@ class ReceivingService extends Service { if (!receiving) { return { code: 0, message: '无记录或无权访问', data: {} }; } - console.log('查询收货单明细'); // 2. 查询收货单明细 const receivingItems = await app.model.ReceivingDetail.findAll({ where: { @@ -1132,7 +1188,6 @@ class ReceivingService extends Service { creator_id, }); - // 获取更新后的明细列表 const allDetails = await ctx.model.ReceivingDetail.findAll({ where: { receiving_id }, @@ -1161,6 +1216,28 @@ class ReceivingService extends Service { }); await this.updateReceivingStats(receiving_id); + + // 记录操作日志 + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'receiving', + businessId: receiving_id, + operationCode: 'RECEIVING_ADD_DETAIL', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: warehouse_id, + }, + beforeChanges: { + detail_id: newDetail.id, + }, + }); + } catch (logErr) { + ctx.logger.warn('[receiving.addDetail] 写入操作日志失败,不影响业务', logErr); + } + return { code: 200, message: '添加成功', @@ -1318,6 +1395,29 @@ class ReceivingService extends Service { await this.updateReceivingStats(receivingDetail.receiving_id); + // 记录操作日志 + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'receiving', + businessId: receivingDetail.receiving_id, + operationCode: 'RECEIVING_BIND_PRODUCT', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId, + }, + beforeChanges: { + detail_id: detailId, + old_system_product_id: receivingDetail.system_product_id, + new_system_product_id: systemProductId, + }, + }); + } catch (logErr) { + ctx.logger.warn('[receiving.bindDetailProduct] 写入操作日志失败,不影响业务', logErr); + } + return { code: 200, message: '绑定商品成功', @@ -1575,7 +1675,6 @@ class ReceivingService extends Service { }, transaction, }); - console.log('matchedDetail第一个有绑定的商品', matchedDetail); if (matchedDetail && matchedDetail.system_product_id) { try { // 调用 getStockStoreInfo 获取库存信息 @@ -1658,7 +1757,6 @@ class ReceivingService extends Service { if (transaction) { await transaction.rollback(); } - console.log(error); ctx.logger.error('更新收货单统计失败:', error); throw error; } @@ -1758,6 +1856,30 @@ class ReceivingService extends Service { selectId = remainingDetails[0].id; } await this.updateReceivingStats(receiving_id); + + // 记录操作日志 + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'receiving', + businessId: receiving_id, + operationCode: 'RECEIVING_DELETE_DETAIL', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: warehouse_id, + }, + beforeChanges: { + detail_id, + product_name: detail.product_name, + actual_quantity: detail.actual_quantity, + }, + }); + } catch (logErr) { + ctx.logger.warn('[receiving.deleteDetail] 写入操作日志失败,不影响业务', logErr); + } + return { code: 200, message: '删除成功', @@ -1806,7 +1928,6 @@ class ReceivingService extends Service { box_length, weight, } = data; - console.log('barcode', barcode); // 2. 验证必填字段 if (!id) { return { @@ -1822,7 +1943,6 @@ class ReceivingService extends Service { }; } - // 3. 获取收货明细信息 const receivingDetail = await app.model.ReceivingDetail.findOne({ where: { id }, @@ -1848,7 +1968,6 @@ class ReceivingService extends Service { }; } - // 5. 验证箱规数据 if (box_quantity !== undefined && box_quantity < 0) { return { @@ -1915,7 +2034,6 @@ class ReceivingService extends Service { if (stockWarehouse) { // 更新商品相关信息 updateData.system_product_id = system_product_id; - console.log('商品信息', stockWarehouse); // 使用系统商品的条码(如果前端没有提供) const barcodes = stockWarehouse.barcodes?.map(b => b.barcode) || []; updateData.barcode = updateData.barcode || barcodes.join(';'); @@ -1960,13 +2078,36 @@ class ReceivingService extends Service { updateData.space_id = space_id; } } - console.log('更新收货明细', updateData); // 8. 更新收货明细 await ctx.model.ReceivingDetail.update(updateData, { where: { id }, }); - console.log('更新收货明细2'); await this.updateReceivingStats(receiving_id); + + // 记录操作日志 + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'receiving', + businessId: receiving_id, + operationCode: 'RECEIVING_UPDATE_DETAIL', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId, + }, + beforeChanges: { + detail_id: id, + product_name: receivingDetail.product_name, + actual_quantity: receivingDetail.actual_quantity, + system_product_id: receivingDetail.system_product_id, + }, + }); + } catch (logErr) { + ctx.logger.warn('[receiving.detailChange] 写入操作日志失败,不影响业务', logErr); + } + // 9. 返回成功响应 return { code: 200, @@ -2091,6 +2232,27 @@ class ReceivingService extends Service { // 8. 提交事务 await transaction.commit(); + // 记录操作日志 + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'receiving', + businessId: receivingId, + operationCode: 'RECEIVING_CANCEL', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId, + }, + beforeChanges: { + previous_status: receiving.status, + invalid_reason, + }, + }); + } catch (logErr) { + ctx.logger.warn('[receiving.invalid] 写入操作日志失败,不影响业务', logErr); + } return { code: 200, @@ -2107,7 +2269,6 @@ class ReceivingService extends Service { }; } catch (error) { - console.log(error); // 10. 回滚事务 if (transaction) { await transaction.rollback(); @@ -2406,7 +2567,7 @@ class ReceivingService extends Service { * @param {Object} [options.operator={}] 操作人信息 * @param {Object} [options.stats={}] 收货统计 * @param {Object|null} [options.completionReport=null] 完成报表信息 - * @return {Promise} + * @return {Promise} 通知发送结果,若条件不满足则返回 null */ async sendCompletionNotice({ receiving, @@ -2562,9 +2723,28 @@ class ReceivingService extends Service { }; } - // 4. 准备明细图片与统计信息。 - // 按最新要求:收货完成通知不再受“必须绑定商品/必须补齐照片条码重量数量”限制, - // 只要用户执行完成收货且存在明细,即允许完成并继续发送通知。 + // 4. 校验明细数量:不允许存在数量为 0 的明细 + const zeroQuantityDetails = receiving.details.filter(d => Number(d.actual_quantity || 0) <= 0); + if (zeroQuantityDetails.length > 0) { + await transaction.rollback(); + const errorMsg = zeroQuantityDetails.length === 1 + ? `商品“${zeroQuantityDetails[0].product_name || '未命名商品'}”的数量为0,请填写实际收货数量` + : `有${zeroQuantityDetails.length}个商品数量为0,请填写实际收货数量`; + return { + success: false, + code: 'DETAIL_QUANTITY_ZERO', + message: errorMsg, + data: { + invalid_details: zeroQuantityDetails.map(d => ({ + detail_id: d.id, + item_name: d.product_name || '未命名商品', + actual_quantity: Number(d.actual_quantity || 0), + })), + }, + }; + } + + // 5. 准备明细图片与统计信息(照片/条码/重量不再强制要求) const unmatchedDetails = receiving.details.filter(d => !d.system_product_id); const detailsIds = receiving.details.map(item => item.id); @@ -2653,6 +2833,28 @@ class ReceivingService extends Service { // 10. 提交事务 await transaction.commit(); + // 记录操作日志 + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'receiving', + businessId: id, + operationCode: 'RECEIVING_COMPLETE', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId, + }, + beforeChanges: { + previous_status: receiving.status, + stats, + }, + }); + } catch (logErr) { + ctx.logger.warn('[receiving.completeReceiving] 写入操作日志失败,不影响业务', logErr); + } + const receivingSnapshot = { ...(typeof receiving.toJSON === 'function' ? receiving.toJSON() : receiving), ...updateData, diff --git a/app/service/systems/store.js b/app/service/systems/store.js index de75211..0b8291c 100644 --- a/app/service/systems/store.js +++ b/app/service/systems/store.js @@ -89,13 +89,14 @@ class StoreService extends Service { } /** - * 根据ID获取商家信息 - * @param storeId - */ + * 根据ID获取商家信息。 + * @param {number|string} storeId 商家ID + * @return {Promise} 查询结果 + */ async getStoreName(storeId) { try { const store = await this.app.model.Store.findByPk(storeId, { - attributes: [ 'id', 'company_name', 'status', 'is_warehouse' ], + attributes: [ 'id', 'company_name', 'status' ], }); if (!store) { @@ -122,10 +123,11 @@ class StoreService extends Service { } /** - * 获取商家仓库备注名 - * @param storeId - * @param warehouseId - */ + * 获取商家仓库备注名。 + * @param {number|string} storeId 商家ID + * @param {number|string} warehouseId 仓库ID + * @return {Promise} 查询结果 + */ async getStoreRemaskName(storeId, warehouseId) { try { const relation = await this.app.model.StoreWarehouse.findOne({ @@ -159,9 +161,10 @@ class StoreService extends Service { } /** - * 创建商家(不需要审核) - * @param data - */ + * 创建商家(不需要审核)。 + * @param {Object} data 请求参数 + * @return {Promise} 创建结果 + */ async createStore(data) { const { ctx, @@ -245,9 +248,25 @@ class StoreService extends Service { // 为创建者自动分配商家管理员角色 const role_id = await this.assignAdminRoleToCreator(store.id, userId, data.contact_person, transaction); - console.log(role_id); await transaction.commit(); + // 记录操作日志 + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'store', + businessId: store.id, + operationCode: 'STORE_CREATE', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: {}, + beforeChanges: null, + }); + } catch (logErr) { + ctx.logger.warn('[store.createStore] 写入操作日志失败,不影响业务', logErr); + } + return { code: 200, message: '商家创建成功', @@ -279,9 +298,10 @@ class StoreService extends Service { } /** - * 创建仓库(需要审核) - * @param data - */ + * 创建仓库(需要审核)。 + * @param {Object} data 请求参数 + * @return {Promise} 创建结果 + */ async createWarehouse(data) { const { ctx, @@ -366,6 +386,24 @@ class StoreService extends Service { const role_id = await this.assignAdminRoleToCreator(warehouse.id, userId, data.contact_person, transaction, false); await transaction.commit(); + + // 记录操作日志 + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'store', + businessId: warehouse.id, + operationCode: 'STORE_CREATE_WAREHOUSE', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: {}, + beforeChanges: null, + }); + } catch (logErr) { + ctx.logger.warn('[store.createWarehouse] 写入操作日志失败,不影响业务', logErr); + } + return { code: 200, message: '仓库创建申请已提交,等待审核', @@ -397,9 +435,10 @@ class StoreService extends Service { } /** - * 加入商家 - * @param data - */ + * 加入商家。 + * @param {Object} data 请求参数 + * @return {Promise} 创建结果 + */ async joinStore(data) { const { ctx, @@ -408,7 +447,6 @@ class StoreService extends Service { try { const userId = ctx.userId || (ctx.user && ctx.user.id); - console.log('申请参数', data); // 验证必填字段 if (!data.employees_name) { return { @@ -427,7 +465,6 @@ class StoreService extends Service { transaction, }); - // 生成加入链接(用于分享给管理员) const joinToken = this.generateJoinToken(userId, data.store_id); @@ -447,7 +484,6 @@ class StoreService extends Service { transaction, }); - await transaction.commit(); return { @@ -461,7 +497,6 @@ class StoreService extends Service { } catch (error) { await transaction.rollback(); - console.log('error', error); return { code: 500, message: '创建申请链接失败', @@ -471,9 +506,10 @@ class StoreService extends Service { } /** - * 加入仓库 - * @param data - */ + * 加入仓库。 + * @param {Object} data 请求参数 + * @return {Promise} 创建结果 + */ async joinWarehouse(data) { const { ctx, @@ -482,7 +518,6 @@ class StoreService extends Service { try { const userId = ctx.userId || (ctx.user && ctx.user.id); - console.log('申请参数', data); // 验证必填字段 if (!data.employees_name) { return { @@ -501,7 +536,6 @@ class StoreService extends Service { transaction, }); - // 生成加入链接(用于分享给管理员) const joinToken = this.generateJoinToken(userId, data.store_id); @@ -521,7 +555,6 @@ class StoreService extends Service { transaction, }); - await transaction.commit(); return { @@ -535,7 +568,6 @@ class StoreService extends Service { } catch (error) { await transaction.rollback(); - console.log('error', error); return { code: 500, message: '创建申请链接失败', @@ -546,6 +578,16 @@ class StoreService extends Service { // ==================== 辅助方法 ==================== + /** + * 确保工号与角色已绑定。 + * @param {Object} options 绑定参数 + * @param {number|string} options.accountId 账号ID + * @param {number|string} options.storeId 主体ID + * @param {number|string} options.roleId 角色ID + * @param {string} [options.realName] 真实姓名 + * @param {Object} options.transaction 事务对象 + * @return {Promise} 绑定结果 + */ async ensureEmployeeRoleBinding({ accountId, storeId, roleId, realName = '', transaction }) { const { ctx } = this; @@ -589,13 +631,14 @@ class StoreService extends Service { } /** - * 为创建者分配管理员角色 - * @param storeId - * @param userId - * @param realName - * @param transaction - * @param isStore - */ + * 为创建者分配管理员角色。 + * @param {number|string} storeId 主体ID + * @param {number|string} userId 账号ID + * @param {string} realName 真实姓名 + * @param {Object} transaction 事务对象 + * @param {boolean} [isStore=true] 是否为商家主体 + * @return {Promise} 工号实例 + */ async assignAdminRoleToCreator(storeId, userId, realName, transaction, isStore = true) { const { ctx, @@ -625,13 +668,13 @@ class StoreService extends Service { return employee; } - /** - * 生成加入令牌 - * @param userId - * @param storeId - * @param type - */ + * 生成加入令牌。 + * @param {number|string} userId 账号ID + * @param {number|string} storeId 主体ID + * @param {string} [type='store'] 令牌类型 + * @return {string} 加入令牌 + */ generateJoinToken(userId, storeId, type = 'store') { const crypto = require('crypto'); const timestamp = Date.now(); @@ -643,9 +686,10 @@ class StoreService extends Service { } /** - * 发送通知 - * @param notificationData - */ + * 发送通知。 + * @param {Object} notificationData 通知数据 + * @return {Promise} + */ async sendNotification(notificationData) { const { ctx, @@ -663,9 +707,10 @@ class StoreService extends Service { } /** - * 发送通知给系统管理员 - * @param notificationData - */ + * 发送通知给系统管理员。 + * @param {Object} notificationData 通知数据 + * @return {Promise} + */ async sendNotificationToAdmins(notificationData) { const { ctx, @@ -696,8 +741,6 @@ class StoreService extends Service { ctx, } = this; try { - console.log('ctx', ctx.user.store_id); - const userId = ctx.user.id; const storeId = ctx.user.store_id; // 验证必填字段 if (!data.code) { @@ -708,7 +751,6 @@ class StoreService extends Service { }; } const code = data.code; - console.log('申请参数', userId, storeId, code); const applyData = await ctx.model.StoreJoin.findOne({ where: { join_token: code, @@ -741,7 +783,6 @@ class StoreService extends Service { }, }; } catch (error) { - console.log('error', error); return { code: 500, message: '请求失败', @@ -765,7 +806,7 @@ class StoreService extends Service { } // 2. 验证store_id - if (ctx.user.store_id != data.store_id) { + if (ctx.user.store_id !== data.store_id) { await transaction.rollback(); return { code: 400, @@ -777,8 +818,6 @@ class StoreService extends Service { const { code, audit_status, role_ids } = data; const store_id = ctx.user.store_id; - console.log('申请参数', data); - // 3. 查找申请记录 const applyData = await ctx.model.StoreJoin.findOne({ where: { @@ -883,7 +922,6 @@ class StoreService extends Service { data: null, }; - } catch (error) { await transaction.rollback(); console.error('审核申请出错:', error); @@ -905,7 +943,7 @@ class StoreService extends Service { } } async loadStores() { - const { app, ctx } = this; + const { ctx } = this; try { const stores = await ctx.model.StoreWarehouse.findAll({ diff --git a/app/service/systems/store_warehouse.js b/app/service/systems/store_warehouse.js index a73c73b..38d619c 100644 --- a/app/service/systems/store_warehouse.js +++ b/app/service/systems/store_warehouse.js @@ -11,34 +11,6 @@ const AUTH_STATUS_LABELS = Object.freeze({ 4: '已解除', 5: '已过期', }); -const POLICY_CONFIG_FIELD_RULES = Object.freeze({ - receive_mode: { - type: 'enum', - values: [ 'standard', 'strict', 'manual' ], - }, - sku_visibility: { - type: 'enum', - values: [ 'all', 'whitelist', 'blacklist' ], - }, - auto_allocate_bin: { - type: 'flag', - }, - allow_mix_batch: { - type: 'flag', - }, - allow_temp_storage: { - type: 'flag', - }, - max_daily_inbound: { - type: 'integer', - min: 0, - max: 1000000, - }, - remark: { - type: 'string', - maxLength: 200, - }, -}); class SettingStoreWarehouseService extends Service { createError(message, code = 500) { @@ -120,6 +92,22 @@ class SettingStoreWarehouseService extends Service { return Math.floor(num); } + normalizeInteger(value, fieldName, options = {}) { + const { allowZero = true } = options; + if (value === undefined || value === null || value === '') { + throw this.createError(`${fieldName} 参数不能为空`, 400); + } + + const num = Number(value); + if (!Number.isFinite(num) || !Number.isInteger(num)) { + throw this.createError(`${fieldName} 参数不合法`, 400); + } + if (!allowZero && num === 0) { + throw this.createError(`${fieldName} 不能为 0`, 400); + } + return num; + } + normalizeText(value, fieldName, maxLength = 500) { if (value === undefined || value === null) { return null; @@ -155,77 +143,29 @@ class SettingStoreWarehouseService extends Service { return email; } + getPolicyConfigFieldList() { + const storeWarehouseModel = this.ctx.model && this.ctx.model.StoreWarehouse; + if (!storeWarehouseModel || typeof storeWarehouseModel.getPolicyConfigFieldList !== 'function') { + return []; + } + return storeWarehouseModel.getPolicyConfigFieldList(); + } + normalizePolicyConfig(value, fieldName = 'policy_config', options = {}) { - const { allowEmpty = false } = options; - if (value === undefined || value === null || value === '') { - if (allowEmpty) { - return null; - } - throw this.createError(`${fieldName} 参数不能为空`, 400); + const storeWarehouseModel = this.ctx.model && this.ctx.model.StoreWarehouse; + if (!storeWarehouseModel || typeof storeWarehouseModel.normalizePolicyConfig !== 'function') { + throw this.createError('StoreWarehouse model 未定义 policy_config 规则', 500); } - const parsed = typeof value === 'string' ? (() => { - try { - return JSON.parse(value); - } catch { - throw this.createError(`${fieldName} 不是合法JSON`, 400); - } - })() : value; - - if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { - throw this.createError(`${fieldName} 必须为对象`, 400); + try { + return storeWarehouseModel.normalizePolicyConfig(value, { + fieldName, + allowEmpty: options.allowEmpty === true, + sanitizeOnly: options.sanitizeOnly === true, + }); + } catch (error) { + throw this.createError(error.message || `${fieldName} 参数不合法`, Number(error.code) || 400); } - - const allowedKeys = Object.keys(POLICY_CONFIG_FIELD_RULES); - const unsupportedKeys = Object.keys(parsed).filter(key => !allowedKeys.includes(key)); - if (unsupportedKeys.length) { - throw this.createError(`${fieldName} 包含不支持字段: ${unsupportedKeys.join(', ')};仅允许字段: ${allowedKeys.join(', ')}`, 400); - } - - const normalized = {}; - for (const [ key, rawValue ] of Object.entries(parsed)) { - const rule = POLICY_CONFIG_FIELD_RULES[key]; - if (!rule) { - continue; - } - - if (rule.type === 'enum') { - const valueText = String(rawValue || '').trim(); - if (!rule.values.includes(valueText)) { - throw this.createError(`${fieldName}.${key} 参数不合法`, 400); - } - normalized[key] = valueText; - continue; - } - - if (rule.type === 'flag') { - if (rawValue === true || rawValue === 1 || rawValue === '1') { - normalized[key] = 1; - continue; - } - if (rawValue === false || rawValue === 0 || rawValue === '0') { - normalized[key] = 0; - continue; - } - throw this.createError(`${fieldName}.${key} 参数不合法`, 400); - } - - if (rule.type === 'integer') { - const num = Number(rawValue); - if (!Number.isFinite(num) || num < rule.min || num > rule.max) { - throw this.createError(`${fieldName}.${key} 参数不合法`, 400); - } - normalized[key] = Math.floor(num); - continue; - } - - if (rule.type === 'string') { - const text = this.normalizeText(rawValue, `${fieldName}.${key}`, rule.maxLength); - normalized[key] = text || ''; - } - } - - return normalized; } getPolicyConfigCacheKey(contractId) { @@ -265,22 +205,17 @@ class SettingStoreWarehouseService extends Service { const row = Array.isArray(rows) ? rows[0] : null; const raw = row ? row.policy_config : null; - if (raw === null || raw === undefined || raw === '') { - return null; - } - if (typeof raw === 'object') { - return raw; - } - - try { - return JSON.parse(raw); - } catch { - return null; - } + return this.normalizePolicyConfig(raw, 'policy_config', { + allowEmpty: true, + sanitizeOnly: true, + }); } const cached = await this.app.getCacheAsync(this.getPolicyConfigCacheKey(normalizedId)); - return cached && typeof cached === 'object' ? cached : null; + return this.normalizePolicyConfig(cached, 'policy_config', { + allowEmpty: true, + sanitizeOnly: true, + }); } async savePolicyConfigByContractId(contractId, policyConfig, transaction = null) { @@ -306,12 +241,95 @@ class SettingStoreWarehouseService extends Service { await this.app.setCacheAsync(this.getPolicyConfigCacheKey(normalizedId), policyConfig, 86400 * 30); } - ensureWarehouseSubject(currentSubject) { + ensureWarehouseSubject(currentSubject, actionLabel = '签约配置') { if (!currentSubject || !currentSubject.isWarehouse) { - throw this.createError('仅仓库主体可维护奇门接口配置', 403); + throw this.createError(`仅仓库主体可维护${actionLabel}`, 403); } } + getNoticeService() { + const rawNoticeService = this.ctx && this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.notice; + if (rawNoticeService && typeof rawNoticeService.send === 'function') { + return rawNoticeService; + } + if (rawNoticeService && rawNoticeService.index && typeof rawNoticeService.index.send === 'function') { + return rawNoticeService.index; + } + return null; + } + + async sendPrintQuantityAdjustNotice({ + relation, + currentSubject, + changeLog, + operatorId, + changeQuantity, + balanceBefore, + balanceAfter, + reason, + } = {}) { + const noticeService = this.getNoticeService(); + if (!noticeService || !relation) { + return null; + } + + const relationData = relation && typeof relation.get === 'function' + ? relation.get({ plain: true }) + : (relation || {}); + const storeName = relationData.store_remask || (relationData.store && relationData.store.company_name) || ''; + const warehouseName = relationData.warehouse_remask || (relationData.warehouse && relationData.warehouse.company_name) || ''; + const operatorName = String( + (this.ctx.user && (this.ctx.user.real_name || this.ctx.user.employees_name || this.ctx.user.name || this.ctx.user.username)) || '' + ).trim(); + const changeLabel = changeQuantity === 0 + ? '无变化' + : changeQuantity > 0 + ? `增加 ${changeQuantity}` + : `扣减 ${Math.abs(changeQuantity)}`; + + return await noticeService.send({ + warehouseId: Number(relationData.warehouse_id || 0), + storeId: Number(relationData.store_id || 0) || undefined, + messageType: 'text', + businessName: 'store_warehouse', + event: 'store_warehouse_print_quantity_adjusted', + title: '货主面单余额已更新', + content: [ + warehouseName ? `仓库:${warehouseName}` : '', + storeName ? `货主:${storeName}` : '', + `设置余额:${balanceAfter}`, + `变更:${changeLabel}`, + `余额:${balanceBefore} -> ${balanceAfter}`, + `原因:${reason}`, + operatorName ? `操作人:${operatorName}` : '', + ].filter(Boolean).join(';'), + businessId: Number((changeLog && changeLog.id) || relationData.id || 0), + subject: { + id: Number(currentSubject && currentSubject.id || relationData.warehouse_id || 0), + type: currentSubject && currentSubject.isWarehouse ? 'warehouse' : 'store', + name: currentSubject && currentSubject.company_name ? currentSubject.company_name : warehouseName, + }, + sender: { + id: Number(operatorId || 0) || null, + name: operatorName, + }, + metadata: { + contractId: Number(relationData.id || 0), + storeId: Number(relationData.store_id || 0), + warehouseId: Number(relationData.warehouse_id || 0), + changeType: String(changeLog && changeLog.change_type || 'manual_adjust'), + businessType: changeLog && changeLog.business_type ? String(changeLog.business_type) : null, + businessId: changeLog && changeLog.business_id !== undefined && changeLog.business_id !== null + ? Number(changeLog.business_id) + : null, + changeQuantity, + balanceBefore, + balanceAfter, + reason, + }, + }); + } + resolveRelationId(data = {}) { return this.toPositiveNumber( data.id !== undefined ? data.id : (data.contract_id !== undefined ? data.contract_id : data.relation_id), @@ -604,14 +622,18 @@ class SettingStoreWarehouseService extends Service { await Promise.all(keys.map(key => this.app.setCacheAsync(key, null, 1).catch(() => null))); } - async getQimenInterfaceType(data = {}, options = {}) { + async getApiInterfaceType(data = {}, options = {}) { const { ctx } = this; - const { allowDisabled = false, transaction = null } = options; + const { allowDisabled = false, transaction = null, requireId = false, interfaceCategory = null } = options; const interfaceTypeId = this.toPositiveNumber(data.interface_type_id, 'interface_type_id', { allowEmpty: true }); - const where = { - interface_category: 'QM_WMS', - }; + if (requireId && !interfaceTypeId) { + throw this.createError('interface_type_id 参数不能为空', 400); + } + const where = {}; + if (interfaceCategory) { + where.interface_category = interfaceCategory; + } if (!allowDisabled) { where.is_enabled = 1; } @@ -627,12 +649,16 @@ class SettingStoreWarehouseService extends Service { }); if (!interfaceType) { - throw this.createError(interfaceTypeId ? '指定的奇门接口类型不存在或不可用' : '未配置可用的奇门接口类型', 404); + throw this.createError(interfaceTypeId ? '指定的接口类型不存在或不可用' : '未配置可用的接口类型', 404); } return interfaceType; } + async getQimenInterfaceType(data = {}, options = {}) { + return this.getApiInterfaceType(data, options); + } + serializeQimenConfig(config) { if (!config) { return null; @@ -652,6 +678,8 @@ class SettingStoreWarehouseService extends Service { contract_id: Number(item.contract_id || 0), warehouse_id: item.warehouse_id ? Number(item.warehouse_id) : null, app_name: item.app_name || '', + self_app_key: item.self_app_key || '', + self_app_secret: item.self_app_secret || '', qimen_app_key: item.qimen_app_key || '', qimen_customer_id: item.qimen_customer_id || '', qimen_warehouse_code: item.qimen_warehouse_code || '', @@ -665,6 +693,7 @@ class SettingStoreWarehouseService extends Service { is_enabled: Number(item.is_enabled || 0), created_at: item.created_at || null, updated_at: item.updated_at || null, + callback_url: item.callback_url || '', }; } @@ -677,34 +706,19 @@ class SettingStoreWarehouseService extends Service { return new Map(); } - let interfaceTypeIds = []; + const where = { + contract_id: normalizedContractIds, + }; if (interfaceTypeId) { - interfaceTypeIds = [ Number(interfaceTypeId) ]; - } else { - const interfaceWhere = { - interface_category: 'QM_WMS', - }; - if (!allowDisabled) { - interfaceWhere.is_enabled = 1; - } - - const interfaceTypes = await ctx.model.InterfaceType.findAll({ - where: interfaceWhere, - attributes: [ 'id' ], + const interfaceType = await this.getApiInterfaceType({ interface_type_id: interfaceTypeId }, { + allowDisabled, transaction, }); - interfaceTypeIds = interfaceTypes.map(item => Number(item.id)).filter(Boolean); - } - - if (!interfaceTypeIds.length) { - return new Map(); + where.interface_type_id = Number(interfaceType.id || 0); } const rows = await ctx.model.ApiApp.findAll({ - where: { - contract_id: normalizedContractIds, - interface_type_id: interfaceTypeIds, - }, + where, include: [ { model: ctx.model.InterfaceType, @@ -810,7 +824,8 @@ class SettingStoreWarehouseService extends Service { policy_config: item.policy_config && typeof item.policy_config === 'object' ? item.policy_config : null, is_auth_valid: isAuthValid, remaining_days: remainingDays, - qimen_config: normalizedQimenConfig || null, + api_config: normalizedQimenConfig || null, + apiConfig: normalizedQimenConfig || null, }; } @@ -869,14 +884,22 @@ class SettingStoreWarehouseService extends Service { limit: pageSize, distinct: true, }); - const qimenConfigMap = await this.getQimenConfigMap(rows.map(item => Number(item.id || 0)), { - allowDisabled: true, - }); + + const contractIds = rows.map(item => Number(item.id || 0)).filter(id => id > 0); + const qimenConfigMap = contractIds.length + ? await this.getQimenConfigMap(contractIds) + : new Map(); return { code: 200, data: { - list: rows.map(item => this.serializeRelation(item, currentSubject, qimenConfigMap.get(Number(item.id || 0)) || null)), + list: rows.map(item => { + const serialized = this.serializeRelation(item, currentSubject); + delete serialized.api_config; + delete serialized.apiConfig; + serialized.has_qimen_config = qimenConfigMap.has(serialized.id); + return serialized; + }), total: Number(count || 0), page, page_size: pageSize, @@ -970,6 +993,25 @@ class SettingStoreWarehouseService extends Service { await this.clearTempSignPayload(tempCode); await transaction.commit(); + // 记录操作日志 + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'store', + businessId: relation.id, + operationCode: 'STORE_SIGN', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: Number(payload.warehouse_id || 0), + }, + beforeChanges: null, + }); + } catch (logErr) { + ctx.logger.warn('[storeWarehouse.sign] 写入操作日志失败,不影响业务', logErr); + } + return { code: 200, data: { @@ -1061,6 +1103,25 @@ class SettingStoreWarehouseService extends Service { await transaction.commit(); + // 记录操作日志 + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'store', + businessId: relation.id, + operationCode: 'STORE_RENAME', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: Number(relation.warehouse_id || 0), + }, + beforeChanges: null, + }); + } catch (logErr) { + ctx.logger.warn('[storeWarehouse.rename] 写入操作日志失败,不影响业务', logErr); + } + return { code: 200, data: { @@ -1073,6 +1134,142 @@ class SettingStoreWarehouseService extends Service { } } + async adjustPrintQuantity(data = {}) { + const { ctx } = this; + const transaction = await ctx.model.transaction(); + + try { + const currentSubject = await this.getCurrentSubject(); + this.ensureWarehouseSubject(currentSubject, '面单余额'); + const relation = await this.findScopedRelation(data, currentSubject, transaction); + const operatorId = this.getCurrentAccountId(); + const targetQuantityField = [ + [ 'print_quantity', data.print_quantity ], + [ 'target_quantity', data.target_quantity ], + [ 'change_quantity', data.change_quantity ], + [ 'adjust_quantity', data.adjust_quantity ], + ].find(([ , value ]) => value !== undefined && value !== null && value !== ''); + if (!targetQuantityField) { + throw this.createError('print_quantity / target_quantity / change_quantity / adjust_quantity 参数不能为空', 400); + } + const [ targetQuantityFieldName, targetQuantityRaw ] = targetQuantityField; + const targetQuantity = this.normalizeInteger(targetQuantityRaw, targetQuantityFieldName, { allowZero: true }); + if (targetQuantity < 0) { + throw this.createError(`${targetQuantityFieldName} 参数不合法`, 400); + } + const reason = this.normalizeText(data.reason, 'reason', 500); + if (!reason) { + throw this.createError('reason 参数不能为空', 400); + } + + const businessType = this.normalizeText(data.business_type, 'business_type', 50); + const businessId = data.business_id === undefined || data.business_id === null || data.business_id === '' + ? null + : this.toPositiveNumber(data.business_id, 'business_id'); + const balanceBefore = Number(relation.print_quantity || 0); + const balanceAfter = targetQuantity; + const changeQuantity = balanceAfter - balanceBefore; + + await relation.update({ + print_quantity: balanceAfter, + }, { transaction }); + + const changeLogRecord = await ctx.model.StoreWarehousePrintQuantityLog.create({ + contract_id: Number(relation.id || 0), + store_id: Number(relation.store_id || 0), + warehouse_id: Number(relation.warehouse_id || 0), + change_type: 'manual_adjust', + business_type: businessType, + business_id: businessId, + change_quantity: changeQuantity, + balance_before: balanceBefore, + balance_after: balanceAfter, + reason, + operator_id: operatorId, + created_by: operatorId, + }, { transaction }); + + const result = await ctx.model.StoreWarehouse.findByPk(relation.id, { + include: this.getRelationIncludes(), + transaction, + }); + const qimenConfig = await this.getSingleQimenConfig(relation.id, { + allowDisabled: true, + transaction, + }); + + await transaction.commit(); + + const changeLog = changeLogRecord && typeof changeLogRecord.get === 'function' + ? changeLogRecord.get({ plain: true }) + : (changeLogRecord || {}); + + // 记录操作日志 + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'store', + businessId: relation.id, + operationCode: 'STORE_ADJUST_PRINT_QUANTITY', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: Number(relation.warehouse_id || 0), + }, + beforeChanges: null, + }); + } catch (logErr) { + ctx.logger.warn('[storeWarehouse.adjustPrintQuantity] 写入操作日志失败,不影响业务', logErr); + } + + await this.sendPrintQuantityAdjustNotice({ + relation: result, + currentSubject, + changeLog, + operatorId, + changeQuantity, + balanceBefore, + balanceAfter, + reason, + }).catch(error => { + ctx.logger.warn(`[storeWarehouse.adjustPrintQuantity] 通知发送失败: ${error.message}`); + }); + + return { + code: 200, + data: { + contract: this.serializeRelation(result, currentSubject, qimenConfig), + change_log: { + id: Number(changeLog.id || 0), + contract_id: Number(changeLog.contract_id || relation.id || 0), + change_type: String(changeLog.change_type || 'manual_adjust'), + business_type: changeLog.business_type ? String(changeLog.business_type) : null, + business_id: changeLog.business_id !== undefined && changeLog.business_id !== null + ? Number(changeLog.business_id) + : null, + change_quantity: Number(changeLog.change_quantity || 0), + balance_before: Number(changeLog.balance_before !== undefined ? changeLog.balance_before : balanceBefore), + balance_after: Number(changeLog.balance_after !== undefined ? changeLog.balance_after : balanceAfter), + reason: changeLog.reason || reason, + operator_id: Number(changeLog.operator_id || operatorId), + created_at: changeLog.created_at || null, + }, + }, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + async getPolicyConfigFields() { + return { + code: 200, + data: this.getPolicyConfigFieldList(), + }; + } + async getPolicyConfig(data = {}) { const currentSubject = await this.getCurrentSubject(); const relation = await this.findScopedRelation(data, currentSubject); @@ -1098,7 +1295,7 @@ class SettingStoreWarehouseService extends Service { try { const currentSubject = await this.getCurrentSubject(); const relation = await this.findScopedRelation(data, currentSubject, transaction); - this.ensureWarehouseSubject(currentSubject); + this.ensureWarehouseSubject(currentSubject, '签约策略配置'); const policyConfig = this.normalizePolicyConfig( data.policy_config !== undefined ? data.policy_config : data.policy ); @@ -1115,6 +1312,25 @@ class SettingStoreWarehouseService extends Service { await transaction.commit(); + // 记录操作日志 + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'store', + businessId: relation.id, + operationCode: 'STORE_SAVE_POLICY_CONFIG', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: Number(relation.warehouse_id || 0), + }, + beforeChanges: null, + }); + } catch (logErr) { + ctx.logger.warn('[storeWarehouse.savePolicyConfig] 写入操作日志失败,不影响业务', logErr); + } + return { code: 200, data: { @@ -1129,43 +1345,24 @@ class SettingStoreWarehouseService extends Service { } } - async listQimenConfig(data = {}) { + async listApiConfig(data = {}) { const { ctx } = this; const currentSubject = await this.getCurrentSubject(); const relation = await this.findScopedRelation(data, currentSubject); const interfaceTypeId = this.toPositiveNumber(data.interface_type_id, 'interface_type_id', { allowEmpty: true }); - const interfaceWhere = { - interface_category: 'QM_WMS', + const where = { + contract_id: Number(relation.id || 0), }; if (interfaceTypeId) { - interfaceWhere.id = interfaceTypeId; - } - - const interfaceTypes = await ctx.model.InterfaceType.findAll({ - where: interfaceWhere, - attributes: [ 'id', 'interface_code', 'interface_name', 'interface_category', 'is_enabled' ], - order: [[ 'id', 'ASC' ]], - }); - const interfaceTypeIds = interfaceTypes.map(item => Number(item.id)).filter(Boolean); - - if (!interfaceTypeIds.length) { - return { - code: 200, - data: { - contract_id: Number(relation.id || 0), - contract: this.serializeRelation(relation, currentSubject, null), - list: [], - total: 0, - }, - }; + const interfaceType = await this.getApiInterfaceType({ interface_type_id: interfaceTypeId }, { + allowDisabled: true, + }); + where.interface_type_id = Number(interfaceType.id || 0); } const rows = await ctx.model.ApiApp.findAll({ - where: { - contract_id: Number(relation.id || 0), - interface_type_id: interfaceTypeIds, - }, + where, include: [ { model: ctx.model.InterfaceType, @@ -1178,52 +1375,60 @@ class SettingStoreWarehouseService extends Service { }); const list = rows.map(item => this.serializeQimenConfig(item)); - const primaryQimenConfig = list.length ? list[0] : null; + const primaryApiConfig = list.length ? list[0] : null; return { code: 200, data: { contract_id: Number(relation.id || 0), - contract: this.serializeRelation(relation, currentSubject, primaryQimenConfig), + contract: this.serializeRelation(relation, currentSubject, primaryApiConfig), list, total: list.length, }, }; } - async saveQimenConfig(data = {}) { + async saveApiConfig(data = {}) { const { ctx, app } = this; const transaction = await ctx.model.transaction(); try { const currentSubject = await this.getCurrentSubject(); const relation = await this.findScopedRelation(data, currentSubject, transaction); - this.ensureWarehouseSubject(currentSubject); - const interfaceType = await this.getQimenInterfaceType(data, { transaction }); - const qimenAppKey = this.normalizeText(data.qimen_app_key, 'qimen_app_key', 100); - if (!qimenAppKey) { - throw this.createError('qimen_app_key 参数不能为空', 400); - } - const qimenCustomerId = this.normalizeText(data.qimen_customer_id, 'qimen_customer_id', 100); - if (!qimenCustomerId) { - throw this.createError('qimen_customer_id 参数不能为空', 400); - } - const qimenWarehouseCode = this.normalizeText(data.qimen_warehouse_code, 'qimen_warehouse_code', 100); - if (!qimenWarehouseCode) { - throw this.createError('qimen_warehouse_code 参数不能为空', 400); + this.ensureWarehouseSubject(currentSubject, '接口配置'); + const interfaceType = await this.getApiInterfaceType(data, { transaction, requireId: true }); + const isOpenApi = interfaceType.interface_category === 'OPEN_API'; + const isQimenWms = interfaceType.interface_category === 'QM_WMS'; + + // 奇门相关字段:QM_WMS 必填,OPEN_API 不需要 + let qimenAppKey = null; + let qimenCustomerId = null; + let qimenWarehouseCode = null; + + if (isQimenWms) { + qimenAppKey = this.normalizeText(data.qimen_app_key, 'qimen_app_key', 100); + if (!qimenAppKey) { + throw this.createError('奇门接口类型下 qimen_app_key 参数不能为空', 400); + } + qimenCustomerId = this.normalizeText(data.qimen_customer_id, 'qimen_customer_id', 100); + if (!qimenCustomerId) { + throw this.createError('奇门接口类型下 qimen_customer_id 参数不能为空', 400); + } + qimenWarehouseCode = this.normalizeText(data.qimen_warehouse_code, 'qimen_warehouse_code', 100); + if (!qimenWarehouseCode) { + throw this.createError('奇门接口类型下 qimen_warehouse_code 参数不能为空', 400); + } + } else { + // OPEN_API: 奇门字段可选输入 + qimenAppKey = this.normalizeText(data.qimen_app_key, 'qimen_app_key', 100) || null; + qimenCustomerId = this.normalizeText(data.qimen_customer_id, 'qimen_customer_id', 100) || null; + qimenWarehouseCode = this.normalizeText(data.qimen_warehouse_code, 'qimen_warehouse_code', 100) || null; } - const relationPlain = relation && typeof relation.get === 'function' - ? relation.get({ plain: true }) - : relation; - const defaultAppName = [ - relationPlain && relationPlain.store_remask ? relationPlain.store_remask : currentSubject.company_name, - relationPlain && relationPlain.warehouse_remask - ? relationPlain.warehouse_remask - : (relationPlain && relationPlain.warehouse && relationPlain.warehouse.company_name ? relationPlain.warehouse.company_name : `contract-${relation.id}`), - '奇门接口', - ].filter(Boolean).join('-').slice(0, 200); - const appName = this.normalizeText(data.app_name, 'app_name', 200) || defaultAppName; + const appName = this.normalizeText(data.app_name, 'app_name', 200); + if (!appName) { + throw this.createError('app_name 参数不能为空', 400); + } const apiVersion = this.normalizeText(data.api_version, 'api_version', 50) || '1.0'; const signMethod = (this.normalizeText(data.sign_method, 'sign_method', 50) || 'md5').toLowerCase(); if (![ 'md5', 'hmac', 'sha256' ].includes(signMethod)) { @@ -1255,21 +1460,41 @@ class SettingStoreWarehouseService extends Service { }); const { Op } = app.Sequelize; - const duplicateWhere = { - interface_type_id: Number(interfaceType.id || 0), - qimen_app_key: qimenAppKey, - qimen_customer_id: qimenCustomerId, - }; - if (config && config.id) { - duplicateWhere.id = { [Op.ne]: config.id }; + // 重复检测:按接口类型不同检查策略 + let duplicateConfig = null; + if (isQimenWms && qimenAppKey && qimenCustomerId) { + const duplicateWhere = { + interface_type_id: Number(interfaceType.id || 0), + qimen_app_key: qimenAppKey, + qimen_customer_id: qimenCustomerId, + }; + if (config && config.id) { + duplicateWhere.id = { [Op.ne]: config.id }; + } + duplicateConfig = await ctx.model.ApiApp.findOne({ + where: duplicateWhere, + attributes: [ 'id', 'contract_id' ], + transaction, + }); + if (duplicateConfig) { + throw this.createError('该 AppKey 和客户ID 已绑定其他签约关系', 409); + } } - const duplicateConfig = await ctx.model.ApiApp.findOne({ - where: duplicateWhere, - attributes: [ 'id', 'contract_id' ], - transaction, - }); - if (duplicateConfig) { - throw this.createError('该奇门 AppKey 和客户ID 已绑定其他签约关系', 409); + + // OPEN_API: 创建时自动生成 self_app_key 和 self_app_secret + let selfAppKey = null; + let selfAppSecret = null; + if (isOpenApi) { + if (config) { + // 更新时保留已有密钥 + selfAppKey = config.self_app_key; + selfAppSecret = config.self_app_secret; + } else { + // 创建时生成新密钥 + const crypto = require('crypto'); + selfAppKey = `WMS${crypto.randomBytes(16).toString('hex').toUpperCase()}`; + selfAppSecret = crypto.randomBytes(32).toString('hex'); + } } const configPayload = { @@ -1277,6 +1502,8 @@ class SettingStoreWarehouseService extends Service { interface_type_id: Number(interfaceType.id || 0), contract_id: Number(relation.id || 0), warehouse_id: relation.warehouse_id ? Number(relation.warehouse_id) : null, + self_app_key: selfAppKey, + self_app_secret: selfAppSecret, qimen_app_key: qimenAppKey, qimen_customer_id: qimenCustomerId, qimen_warehouse_code: qimenWarehouseCode, @@ -1313,28 +1540,49 @@ class SettingStoreWarehouseService extends Service { include: this.getRelationIncludes(), transaction, }); - const qimenConfig = this.serializeQimenConfig(savedConfig); + const apiConfig = this.serializeQimenConfig(savedConfig); await transaction.commit(); - await this.clearQimenContractCache([ previousConfig, qimenConfig ]).catch(error => { - ctx.logger.warn('[storeWarehouse.saveQimenConfig] 清理奇门缓存失败: %s', error.message); + + // 记录操作日志 + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'store', + businessId: relation.id, + operationCode: 'STORE_SAVE_API_CONFIG', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: Number(relation.warehouse_id || 0), + }, + beforeChanges: null, + }); + } catch (logErr) { + ctx.logger.warn('[storeWarehouse.saveApiConfig] 写入操作日志失败,不影响业务', logErr); + } + + await this.clearQimenContractCache([ previousConfig, apiConfig ]).catch(error => { + ctx.logger.warn('[storeWarehouse.saveApiConfig] 清理奇门缓存失败: %s', error.message); }); return { code: 200, data: { action, - contract: this.serializeRelation(result, currentSubject, qimenConfig), - qimen_config: qimenConfig, + contract: this.serializeRelation(result, currentSubject, apiConfig), + api_config: apiConfig, + apiConfig, }, }; } catch (error) { await transaction.rollback(); if (error && error.name === 'SequelizeUniqueConstraintError') { - throw this.createError('奇门接口配置已存在,请检查应用名或 AppKey / 客户ID 是否重复', 409); + throw this.createError('接口配置已存在,请检查应用名或 AppKey / 客户ID 是否重复', 409); } if (error && error.name === 'SequelizeValidationError') { - const message = error.errors && error.errors.length ? error.errors[0].message : '奇门接口配置参数校验失败'; + const message = error.errors && error.errors.length ? error.errors[0].message : '接口配置参数校验失败'; throw this.createError(message, 400); } throw error; @@ -1348,8 +1596,8 @@ class SettingStoreWarehouseService extends Service { try { const currentSubject = await this.getCurrentSubject(); const relation = await this.findScopedRelation(data, currentSubject, transaction); - this.ensureWarehouseSubject(currentSubject); - const interfaceType = await this.getQimenInterfaceType(data, { + this.ensureWarehouseSubject(currentSubject, '接口配置'); + const interfaceType = await this.getApiInterfaceType(data, { allowDisabled: true, transaction, }); @@ -1370,7 +1618,7 @@ class SettingStoreWarehouseService extends Service { }); if (!config) { - throw this.createError('奇门接口配置不存在', 404); + throw this.createError('接口配置不存在', 404); } const removedConfig = this.serializeQimenConfig(config); @@ -1382,6 +1630,26 @@ class SettingStoreWarehouseService extends Service { }); await transaction.commit(); + + // 记录操作日志 + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'store', + businessId: relation.id, + operationCode: 'STORE_DELETE_API_CONFIG', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: Number(relation.warehouse_id || 0), + }, + beforeChanges: null, + }); + } catch (logErr) { + ctx.logger.warn('[storeWarehouse.deleteQimenConfig] 写入操作日志失败,不影响业务', logErr); + } + await this.clearQimenContractCache([ removedConfig ]).catch(error => { ctx.logger.warn('[storeWarehouse.deleteQimenConfig] 清理奇门缓存失败: %s', error.message); }); @@ -1391,7 +1659,8 @@ class SettingStoreWarehouseService extends Service { data: { deleted: true, contract: this.serializeRelation(result, currentSubject, null), - qimen_config: null, + api_config: null, + apiConfig: null, removed: removedConfig, }, }; @@ -1425,6 +1694,25 @@ class SettingStoreWarehouseService extends Service { await transaction.commit(); + // 记录操作日志 + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'store', + businessId: relation.id, + operationCode: 'STORE_UNBIND', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: Number(relation.warehouse_id || 0), + }, + beforeChanges: null, + }); + } catch (logErr) { + ctx.logger.warn('[storeWarehouse.unbind] 写入操作日志失败,不影响业务', logErr); + } + return { code: 200, data: { diff --git a/app/service/systems/upload.js b/app/service/systems/upload.js index 0a796da..cff423f 100644 --- a/app/service/systems/upload.js +++ b/app/service/systems/upload.js @@ -4,7 +4,6 @@ const Service = require('egg').Service; const COS = require('cos-nodejs-sdk-v5'); const path = require('path'); const crypto = require('crypto'); -const { v4: uuidv4 } = require('uuid'); const dayjs = require('dayjs'); class UploadService extends Service { @@ -23,13 +22,12 @@ class UploadService extends Service { /** * 获取上传参数 - 使用与PHP一致的算法 - * @param fileInfo + * @param {Object} fileInfo 上传参数对象 */ async getUploadParams(fileInfo) { const { ctx } = this; const warehouseId = ctx.user.store_id; - console.log('fileInfo', fileInfo); - const { fileName, fileType, fileSize, type, id, md5 } = fileInfo; + const { fileName, fileType, fileSize, type, md5 } = fileInfo; if (md5) { const existingFile = await ctx.model.File.findOne({ @@ -52,7 +50,7 @@ class UploadService extends Service { } } // 验证文件 - this.validateFileInfo({ fileName, fileType, fileSize }); + this.validateFileInfo({ fileName, fileSize }); const warehouse_quota = await this.app.model.query( 'SELECT * FROM vw_warehouse_quota WHERE warehouse_id = :warehouseId', @@ -68,7 +66,6 @@ class UploadService extends Service { msg: '空间配额已满', }; } - console.log('空间计算剩余可用', remaining_bytes - fileSize); // 生成文件名 const cosFileName = this.generateFileName(fileName, fileType, type, md5); @@ -127,12 +124,12 @@ class UploadService extends Service { * 生成策略和签名 - 与PHP算法完全一致 * 参考你的PHP代码: * $signature = hash_hmac('sha1', sha1($policy), hash_hmac('sha1', $keytime, $config['secretKey'])); - * @param key - * @param startTime - * @param expireTime + * @param {string} key 文件 key + * @param {number} startTime 开始时间戳 + * @param {number} expireTime 过期时间戳 */ generatePolicyAndSignature(key, startTime, expireTime) { - const { secretId, secretKey, bucket } = this.config.cos; + const { secretId, secretKey } = this.config.cos; const keyTime = `${startTime};${expireTime}`; // 1. 生成策略 - 与PHP完全一致 @@ -165,12 +162,6 @@ class UploadService extends Service { const signature = outerHmac.digest('hex'); // 最终的签名 // 调试信息 - console.log('策略原始内容:', policyString); - console.log('策略Base64:', policyBase64); - console.log('keyTime:', keyTime); - console.log('signKey (内层HMAC):', signKey); - console.log('policyHash (SHA1):', policyHash); - console.log('signature (外层HMAC):', signature); return { policy: policyBase64, @@ -182,12 +173,11 @@ class UploadService extends Service { } /** * 验证文件信息 - * @param root0 - * @param root0.fileName - * @param root0.fileType - * @param root0.fileSize + * @param {Object} root0 文件信息对象 + * @param {string} root0.fileName 文件名 + * @param {number} root0.fileSize 文件大小 */ - validateFileInfo({ fileName, fileType, fileSize }) { + validateFileInfo({ fileName, fileSize }) { const { maxsize, mimetype } = this.config.cos; // 验证文件大小 @@ -209,10 +199,10 @@ class UploadService extends Service { /** * 生成文件唯一名称 - * @param fileName - * @param fileType - * @param category - * @param md5 + * @param {string} fileName 原始文件名 + * @param {string} fileType 文件类型 + * @param {string} category 分类 + * @param {string} md5 文件 MD5 */ generateFileName(fileName, fileType, category = '', md5) { const { savekey, dirs } = this.config.cos; @@ -250,7 +240,7 @@ class UploadService extends Service { /** * 解析文件大小字符串为字节数 - * @param sizeStr + * @param {string|number} sizeStr 文件大小字符串或字节数 */ parseSizeToBytes(sizeStr) { if (typeof sizeStr === 'number') { @@ -277,7 +267,7 @@ class UploadService extends Service { /** * 格式化文件大小 - * @param bytes + * @param {number} bytes 字节数 */ formatFileSize(bytes) { if (bytes === 0) return '0 B'; @@ -291,8 +281,8 @@ class UploadService extends Service { /** * 获取前端配置 - * @param fileType - * @param fileSize + * @param {string} fileType 文件类型 + * @param {number} fileSize 文件大小 */ getFrontendConfig(fileType, fileSize) { const { chunkSize } = this.config.cos; @@ -310,8 +300,8 @@ class UploadService extends Service { /** * 服务器端上传文件 - * @param fileStream - * @param options + * @param {Object} fileStream 文件流对象 + * @param {Object} options 上传选项 */ async uploadFile(fileStream, options = {}) { const { bucket, region } = this.config.cos; @@ -351,8 +341,8 @@ class UploadService extends Service { /** * 验证文件 - * @param fileStream - * @param options + * @param {Object} fileStream 文件流对象 + * @param {Object} options 上传选项 */ validateFile(fileStream, options = {}) { const { maxsize, mimetype } = this.config.cos; @@ -388,7 +378,6 @@ class UploadService extends Service { */ async uploadSuccessNotify(data) { const { ctx } = this; - console.log('上传成功', data); try { // 从上下文获取用户信息(根据你的实际用户认证方式) const warehouseId = ctx.user?.store_id || ctx.query.warehouseId || ctx.request.body.warehouseId; @@ -557,7 +546,7 @@ class UploadService extends Service { /** * 根据文件名获取MIME类型 - * @param fileName + * @param {string} fileName 文件名 */ getMimeType(fileName) { const ext = path.extname(fileName).toLowerCase(); @@ -588,13 +577,13 @@ class UploadService extends Service { /** * 创建文件业务引用关系 - * @param fileId - * @param businessType - * @param businessId - * @param {Object} [options] - * @param {number|string} [options.warehouseId] - * @param {string} [options.createdBy] - * @param {number} [options.displayOrder] + * @param {number|string} fileId 文件 ID + * @param {string} businessType 业务类型 + * @param {number|string} businessId 业务 ID + * @param {Object} [options] 可选参数 + * @param {number|string} [options.warehouseId] 仓库 ID + * @param {string} [options.createdBy] 创建人 + * @param {number} [options.displayOrder] 显示顺序 */ async createFileReference(fileId, businessType, businessId, options = {}) { const { ctx } = this; @@ -658,14 +647,14 @@ class UploadService extends Service { /** * 上传完成回调接口 - 供前端调用 - * @param callbackData + * @param {Object} callbackData 回调数据 */ async handleUploadCallback(callbackData) { const { ctx } = this; try { // 解析回调数据 - const { key, size, mimeType, etag, location, businessInfo } = callbackData; + const { key, size, mimeType, businessInfo } = callbackData; // 构建文件信息 const fileInfo = { diff --git a/config/config.default.js b/config/config.default.js index 76e8613..289a620 100644 --- a/config/config.default.js +++ b/config/config.default.js @@ -107,6 +107,7 @@ module.exports = appInfo => { config.cors = { origin: '*', // 允许所有源,生产环境应指定具体域名 allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS', + exposeHeaders: 'Authorization', credentials: true, // 允许携带 cookie }; diff --git a/database/migrations/20251109160640-init-wms_account.js b/database/migrations/20251109160640-init-wms_account.js index bae015e..950495e 100644 --- a/database/migrations/20251109160640-init-wms_account.js +++ b/database/migrations/20251109160640-init-wms_account.js @@ -2,7 +2,7 @@ module.exports = { async up(queryInterface, Sequelize) { - const { BIGINT, STRING, INTEGER, DATE, TINYINT } = Sequelize; + const { BIGINT, STRING, DATE, TINYINT } = Sequelize; await queryInterface.createTable('wms_account', { id: { @@ -102,7 +102,7 @@ module.exports = { }); }, - async down(queryInterface, Sequelize) { + async down(queryInterface) { await queryInterface.dropTable('wms_account'); }, }; diff --git a/database/migrations/20251110081122-create-wms-account-login-log.js b/database/migrations/20251110081122-create-wms-account-login-log.js index 06259ed..8d7080a 100644 --- a/database/migrations/20251110081122-create-wms-account-login-log.js +++ b/database/migrations/20251110081122-create-wms-account-login-log.js @@ -100,7 +100,7 @@ module.exports = { }); }, - async down(queryInterface, Sequelize) { + async down(queryInterface) { // 安全删除表 const [ tables ] = await queryInterface.sequelize.query( "SHOW TABLES LIKE 'wms_account_login_log'" diff --git a/database/migrations/20251110081641-create-wms-qimen-apps.js b/database/migrations/20251110081641-create-wms-qimen-apps.js index ec95c0e..6888e3a 100644 --- a/database/migrations/20251110081641-create-wms-qimen-apps.js +++ b/database/migrations/20251110081641-create-wms-qimen-apps.js @@ -74,7 +74,7 @@ module.exports = { }); }, - async down(queryInterface, Sequelize) { + async down(queryInterface) { // 安全删除表 const [ tables ] = await queryInterface.sequelize.query( "SHOW TABLES LIKE 'wms_qimen_apps'" diff --git a/database/migrations/20251110082013-create-wms-store.js b/database/migrations/20251110082013-create-wms-store.js index 69904ca..9240b4d 100644 --- a/database/migrations/20251110082013-create-wms-store.js +++ b/database/migrations/20251110082013-create-wms-store.js @@ -182,7 +182,7 @@ module.exports = { }); }, - async down(queryInterface, Sequelize) { + async down(queryInterface) { // 安全删除表 const [ tables ] = await queryInterface.sequelize.query( "SHOW TABLES LIKE 'wms_store'" diff --git a/database/migrations/20251110084033-create-wms-store-warehouse.js b/database/migrations/20251110084033-create-wms-store-warehouse.js index 36e1f33..91b05b1 100644 --- a/database/migrations/20251110084033-create-wms-store-warehouse.js +++ b/database/migrations/20251110084033-create-wms-store-warehouse.js @@ -185,7 +185,7 @@ module.exports = { }); }, - async down(queryInterface, Sequelize) { + async down(queryInterface) { // 安全删除表 const [ tables ] = await queryInterface.sequelize.query( "SHOW TABLES LIKE 'wms_store_warehouse'" diff --git a/database/migrations/20251110090742-create-wms-interface-type.js b/database/migrations/20251110090742-create-wms-interface-type.js index 21a1571..5fbbfc3 100644 --- a/database/migrations/20251110090742-create-wms-interface-type.js +++ b/database/migrations/20251110090742-create-wms-interface-type.js @@ -108,7 +108,7 @@ module.exports = { }); }, - async down(queryInterface, Sequelize) { + async down(queryInterface) { // 安全删除表 const [ tables ] = await queryInterface.sequelize.query( "SHOW TABLES LIKE 'wms_interface_type'" diff --git a/database/migrations/20251110091013-create-wms-api-app.js b/database/migrations/20251110091013-create-wms-api-app.js index ec44d98..05830f2 100644 --- a/database/migrations/20251110091013-create-wms-api-app.js +++ b/database/migrations/20251110091013-create-wms-api-app.js @@ -207,7 +207,7 @@ module.exports = { }); }, - async down(queryInterface, Sequelize) { + async down(queryInterface) { // 安全删除表 const [ tables ] = await queryInterface.sequelize.query( "SHOW TABLES LIKE 'wms_api_app'" diff --git a/database/migrations/20251111083733-create-wms-stock-store.js b/database/migrations/20251111083733-create-wms-stock-store.js index 173353e..8c246e2 100644 --- a/database/migrations/20251111083733-create-wms-stock-store.js +++ b/database/migrations/20251111083733-create-wms-stock-store.js @@ -285,7 +285,7 @@ module.exports = { }); }, - async down(queryInterface, Sequelize) { + async down(queryInterface) { // 安全删除表 const [ tables ] = await queryInterface.sequelize.query( "SHOW TABLES LIKE 'wms_stock_store'" diff --git a/database/migrations/20251112085825-create-wms-entry-order.js b/database/migrations/20251112085825-create-wms-entry-order.js index 72a6fed..2561536 100644 --- a/database/migrations/20251112085825-create-wms-entry-order.js +++ b/database/migrations/20251112085825-create-wms-entry-order.js @@ -236,7 +236,7 @@ module.exports = { }); }, - async down(queryInterface, Sequelize) { + async down(queryInterface) { // 安全删除表 const [ tables ] = await queryInterface.sequelize.query( "SHOW TABLES LIKE 'wms_entry_order'" diff --git a/database/migrations/20251112085844-create-wms-entry-items.js b/database/migrations/20251112085844-create-wms-entry-items.js index d13fe01..faff43c 100644 --- a/database/migrations/20251112085844-create-wms-entry-items.js +++ b/database/migrations/20251112085844-create-wms-entry-items.js @@ -138,7 +138,7 @@ module.exports = { }); }, - async down(queryInterface, Sequelize) { + async down(queryInterface) { // 安全删除表 const [ tables ] = await queryInterface.sequelize.query( "SHOW TABLES LIKE 'wms_entry_items'" diff --git a/database/migrations/20260323103000-align-role-permission-fk.js b/database/migrations/20260323103000-align-role-permission-fk.js index 892fbb8..3aca3fe 100644 --- a/database/migrations/20260323103000-align-role-permission-fk.js +++ b/database/migrations/20260323103000-align-role-permission-fk.js @@ -1,7 +1,6 @@ 'use strict'; const TABLE = 'wms_role_permission'; -const REF_TABLE = 'wms_permission'; const FK_NAME = 'fk_wms_role_permission_permission'; async function getColumnInfo(queryInterface, tableName, columnName) { diff --git a/database/migrations/20260323113000-add-role-store-fk.js b/database/migrations/20260323113000-add-role-store-fk.js index 62f6591..353aa89 100644 --- a/database/migrations/20260323113000-add-role-store-fk.js +++ b/database/migrations/20260323113000-add-role-store-fk.js @@ -1,7 +1,6 @@ 'use strict'; const TABLE = 'wms_role'; -const REF_TABLE = 'wms_store'; const FK_NAME = 'fk_wms_role_store'; const INDEX_NAME = 'idx_store_id'; diff --git a/database/migrations/20260323123000-add-permission-parent-fk.js b/database/migrations/20260323123000-add-permission-parent-fk.js index eaa39f4..a1321d1 100644 --- a/database/migrations/20260323123000-add-permission-parent-fk.js +++ b/database/migrations/20260323123000-add-permission-parent-fk.js @@ -1,7 +1,6 @@ 'use strict'; const TABLE = 'wms_permission'; -const COLUMN = 'parent_id'; const FK_NAME = 'fk_wms_permission_parent'; async function hasConstraint(queryInterface, tableName, constraintName) { diff --git a/database/migrations/20260404093000-add-policy-config-to-wms-store-warehouse.js b/database/migrations/20260404093000-add-policy-config-to-wms-store-warehouse.js index 3ba7243..39475c5 100644 --- a/database/migrations/20260404093000-add-policy-config-to-wms-store-warehouse.js +++ b/database/migrations/20260404093000-add-policy-config-to-wms-store-warehouse.js @@ -14,7 +14,7 @@ module.exports = { }); }, - async down(queryInterface, Sequelize) { + async down(queryInterface) { const [ columns ] = await queryInterface.sequelize.query("SHOW COLUMNS FROM `wms_store_warehouse` LIKE 'policy_config'"); if (columns.length === 0) { return; diff --git a/database/migrations/20260407153000-create-wms-store-warehouse-print-quantity-log.js b/database/migrations/20260407153000-create-wms-store-warehouse-print-quantity-log.js new file mode 100644 index 0000000..cda65b9 --- /dev/null +++ b/database/migrations/20260407153000-create-wms-store-warehouse-print-quantity-log.js @@ -0,0 +1,160 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + const { BIGINT, STRING, TEXT, DATE } = Sequelize; + + const [ tables ] = await queryInterface.sequelize.query( + "SHOW TABLES LIKE 'wms_store_warehouse_print_quantity_log'" + ); + + if (tables.length > 0) { + console.log('Table wms_store_warehouse_print_quantity_log already exists, skipping creation'); + return; + } + + await queryInterface.createTable('wms_store_warehouse_print_quantity_log', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + contract_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + references: { + model: 'wms_store_warehouse', + key: 'id', + }, + onUpdate: 'CASCADE', + onDelete: 'NO ACTION', + comment: '签约关系ID,对应 wms_store_warehouse.id', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + references: { + model: 'wms_store', + key: 'id', + }, + onUpdate: 'CASCADE', + onDelete: 'NO ACTION', + comment: '货主ID', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + references: { + model: 'wms_store', + key: 'id', + }, + onUpdate: 'CASCADE', + onDelete: 'NO ACTION', + comment: '仓库ID', + }, + change_type: { + type: STRING(50), + allowNull: false, + comment: '变更类型,如 manual_adjust / order_deduct', + }, + business_type: { + type: STRING(50), + allowNull: true, + comment: '业务来源类型,如 order_express', + }, + business_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '业务关联ID,预留关联 wms_order_express.id', + }, + change_quantity: { + type: BIGINT(20), + allowNull: false, + comment: '本次变更数量,整数,可正可负', + }, + balance_before: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '变更前余额', + }, + balance_after: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '变更后余额', + }, + reason: { + type: TEXT, + allowNull: true, + comment: '变更缘由;人工调整时必填', + }, + operator_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '操作人账号ID', + }, + created_by: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '创建人账号ID', + }, + created_at: { + type: DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + }, { + engine: 'InnoDB', + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + comment: '货主-仓库签约面单余额变更记录表', + }); + + const safeCreateIndex = async (tableName, fields, options) => { + const [ existingIndexes ] = await queryInterface.sequelize.query( + `SHOW INDEX FROM ${tableName} WHERE Key_name = '${options.name}'` + ); + if (existingIndexes.length === 0) { + await queryInterface.addIndex(tableName, fields, options); + } + }; + + await safeCreateIndex('wms_store_warehouse_print_quantity_log', [ 'contract_id', 'id' ], { + name: 'idx_sw_print_qty_log_contract_id', + }); + + await safeCreateIndex('wms_store_warehouse_print_quantity_log', [ 'store_id', 'warehouse_id' ], { + name: 'idx_sw_print_qty_log_store_warehouse', + }); + + await safeCreateIndex('wms_store_warehouse_print_quantity_log', [ 'business_type', 'business_id' ], { + name: 'idx_sw_print_qty_log_business', + }); + + await safeCreateIndex('wms_store_warehouse_print_quantity_log', [ 'change_type' ], { + name: 'idx_sw_print_qty_log_change_type', + }); + + await safeCreateIndex('wms_store_warehouse_print_quantity_log', [ 'created_at' ], { + name: 'idx_sw_print_qty_log_created_at', + }); + }, + + async down(queryInterface) { + const [ tables ] = await queryInterface.sequelize.query( + "SHOW TABLES LIKE 'wms_store_warehouse_print_quantity_log'" + ); + + if (tables.length > 0) { + await queryInterface.dropTable('wms_store_warehouse_print_quantity_log'); + } + }, +}; diff --git a/database/migrations/20260407160000-add-receiving-id-to-wms-storage.js b/database/migrations/20260407160000-add-receiving-id-to-wms-storage.js new file mode 100644 index 0000000..45e2010 --- /dev/null +++ b/database/migrations/20260407160000-add-receiving-id-to-wms-storage.js @@ -0,0 +1,35 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + const [ columns ] = await queryInterface.sequelize.query("SHOW COLUMNS FROM `wms_storage` LIKE 'receiving_id'"); + if (columns.length > 0) { + return; + } + + await queryInterface.addColumn('wms_storage', 'receiving_id', { + type: Sequelize.INTEGER, + allowNull: true, + comment: '收货单ID', + after: 'inbound_order_no', + }); + + await queryInterface.addIndex('wms_storage', [ 'receiving_id' ], { + name: 'idx_receiving_id', + }); + }, + + async down(queryInterface) { + const [ indexes ] = await queryInterface.sequelize.query( + "SHOW INDEX FROM `wms_storage` WHERE Key_name = 'idx_receiving_id'" + ); + if (indexes.length > 0) { + await queryInterface.removeIndex('wms_storage', 'idx_receiving_id'); + } + + const [ columns ] = await queryInterface.sequelize.query("SHOW COLUMNS FROM `wms_storage` LIKE 'receiving_id'"); + if (columns.length > 0) { + await queryInterface.removeColumn('wms_storage', 'receiving_id'); + } + }, +}; diff --git a/database/migrations/20260408100000-add-entry-order-id-to-wms-storage.js b/database/migrations/20260408100000-add-entry-order-id-to-wms-storage.js new file mode 100644 index 0000000..a88bb5e --- /dev/null +++ b/database/migrations/20260408100000-add-entry-order-id-to-wms-storage.js @@ -0,0 +1,41 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + const [ columns ] = await queryInterface.sequelize.query("SHOW COLUMNS FROM `wms_storage` LIKE 'entry_order_id'"); + if (columns.length > 0) { + return; + } + + await queryInterface.addColumn('wms_storage', 'entry_order_id', { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '入库单ID', + after: 'receiving_id', + references: { + model: 'wms_entry_order', + key: 'id', + }, + onDelete: 'SET NULL', + onUpdate: 'CASCADE', + }); + + await queryInterface.addIndex('wms_storage', [ 'entry_order_id' ], { + name: 'idx_entry_order_id', + }); + }, + + async down(queryInterface) { + const [ indexes ] = await queryInterface.sequelize.query( + "SHOW INDEX FROM `wms_storage` WHERE Key_name = 'idx_entry_order_id'" + ); + if (indexes.length > 0) { + await queryInterface.removeIndex('wms_storage', 'idx_entry_order_id'); + } + + const [ columns ] = await queryInterface.sequelize.query("SHOW COLUMNS FROM `wms_storage` LIKE 'entry_order_id'"); + if (columns.length > 0) { + await queryInterface.removeColumn('wms_storage', 'entry_order_id'); + } + }, +}; diff --git a/database/migrations/20260408120000-add-callback-url-to-api-app.js b/database/migrations/20260408120000-add-callback-url-to-api-app.js new file mode 100644 index 0000000..15e8693 --- /dev/null +++ b/database/migrations/20260408120000-add-callback-url-to-api-app.js @@ -0,0 +1,18 @@ +'use strict'; + +/** @type {import('sequelize-cli').Migration} */ +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.addColumn('wms_api_app', 'callback_url', { + type: Sequelize.STRING(500), + allowNull: true, + defaultValue: null, + comment: 'API回调通知URL', + after: 'self_ip_whitelist', + }); + }, + + async down(queryInterface) { + await queryInterface.removeColumn('wms_api_app', 'callback_url'); + }, +}; diff --git a/database/migrations/20260408140000-create-wms-stock-transaction.js b/database/migrations/20260408140000-create-wms-stock-transaction.js new file mode 100644 index 0000000..08e5ca0 --- /dev/null +++ b/database/migrations/20260408140000-create-wms-stock-transaction.js @@ -0,0 +1,169 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + const { BIGINT, STRING, INTEGER, ENUM, DATE } = Sequelize; + + const [ tables ] = await queryInterface.sequelize.query( + "SHOW TABLES LIKE 'wms_stock_transaction'" + ); + + if (tables.length > 0) { + console.log('Table wms_stock_transaction already exists, skipping creation'); + return; + } + + await queryInterface.createTable('wms_stock_transaction', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + transaction_type: { + type: ENUM('INBOUND', 'OUTBOUND'), + allowNull: false, + comment: '出入库类型', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '货主ID', + }, + stock_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '商品库存ID,关联 wms_stock_warehouse.id', + }, + storage_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '库位库存ID,关联 wms_storage.id', + }, + space_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '库位ID', + }, + quantity: { + type: INTEGER(12), + allowNull: false, + comment: '变动数量(正数)', + }, + batch_no: { + type: STRING(100), + allowNull: true, + comment: '批次号', + }, + inventory_type: { + type: ENUM('ZP', 'CC', 'JS', 'XS', 'ZT', 'DJ', 'FP'), + defaultValue: 'ZP', + comment: '库存类型', + }, + order_type: { + type: STRING(50), + allowNull: true, + comment: '关联单据类型', + }, + order_no: { + type: STRING(100), + allowNull: true, + comment: '关联单据号', + }, + order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '关联单据ID', + }, + receiving_id: { + type: INTEGER, + allowNull: true, + comment: '关联收货单ID', + }, + entry_order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '关联入库单ID', + }, + operator_id: { + type: STRING(100), + allowNull: true, + comment: '操作人ID', + }, + operator_name: { + type: STRING(100), + allowNull: true, + comment: '操作人名称', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + created_at: { + type: DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + }, { + engine: 'InnoDB', + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + comment: '出入库流水记录表', + }); + + const safeCreateIndex = async (tableName, fields, options) => { + const [ existingIndexes ] = await queryInterface.sequelize.query( + `SHOW INDEX FROM ${tableName} WHERE Key_name = '${options.name}'` + ); + if (existingIndexes.length === 0) { + await queryInterface.addIndex(tableName, fields, options); + } + }; + + await safeCreateIndex('wms_stock_transaction', [ 'stock_id' ], { + name: 'idx_stock_id', + }); + + await safeCreateIndex('wms_stock_transaction', [ 'warehouse_id', 'created_at' ], { + name: 'idx_warehouse_time', + }); + + await safeCreateIndex('wms_stock_transaction', [ 'order_type', 'order_id' ], { + name: 'idx_order', + }); + + await safeCreateIndex('wms_stock_transaction', [ 'receiving_id' ], { + name: 'idx_receiving_id', + }); + + await safeCreateIndex('wms_stock_transaction', [ 'entry_order_id' ], { + name: 'idx_entry_order_id', + }); + + await safeCreateIndex('wms_stock_transaction', [ 'created_at' ], { + name: 'idx_created_at', + }); + + await safeCreateIndex('wms_stock_transaction', [ 'store_id', 'transaction_type' ], { + name: 'idx_store_transaction_type', + }); + }, + + async down(queryInterface) { + const [ tables ] = await queryInterface.sequelize.query( + "SHOW TABLES LIKE 'wms_stock_transaction'" + ); + + if (tables.length > 0) { + await queryInterface.dropTable('wms_stock_transaction'); + } + }, +}; diff --git a/docs/notification-event-api.md b/docs/notification-event-api.md index 42e763c..0e9baed 100644 --- a/docs/notification-event-api.md +++ b/docs/notification-event-api.md @@ -11,9 +11,10 @@ - 由内部业务在关键节点触发 `event` - 通过 WebHook 向外部系统推送标准 JSON 消息 -当前第一批落地事件: +当前已落地事件: - `receiving_completed`:收货完成通知 +- `store_warehouse_print_quantity_adjusted`:货主面单余额人工调整通知 --- @@ -50,8 +51,9 @@ await ctx.service.systems.notice.send({ | event | 含义 | |---|---| | `receiving_completed` | 收货单完成通知 | +| `store_warehouse_print_quantity_adjusted` | 货主面单余额人工调整通知 | -> 当前正式注册的业务事件仅保留 `receiving_completed`。 +> 当前正式注册的业务事件包括 `receiving_completed`、`store_warehouse_print_quantity_adjusted`。 对于外部订阅方来说,判断消息类型时,优先看: @@ -201,7 +203,39 @@ Content-Type: application/json --- -## 9. 后续事件扩展建议 +## 9. 当前已落地事件:`store_warehouse_print_quantity_adjusted` + +### 9.1 业务含义 + +当仓库侧对某个货主签约关系执行人工面单余额调整后,系统会向相关 WebHook 推送一条 `store_warehouse_print_quantity_adjusted` 通知。 + +### 9.2 推送目标 + +由 `wms_notification_webhook` 决定: + +- 匹配签约仓库 `warehouseId` 绑定的接口 +- 若签约中带有 `storeId`,同步匹配货主绑定的接口 +- `events` 命中以下任一规则即可推送: + - `all` + - `*` + - `store_warehouse_print_quantity_adjusted` + +### 9.3 metadata 关键字段 + +| 字段 | 类型 | 说明 | +|---|---|---| +| `contractId` | `number` | 签约关系 ID | +| `changeType` | `string` | 当前固定为 `manual_adjust` | +| `businessType` | `string \| null` | 业务类型预留字段 | +| `businessId` | `number \| null` | 业务关联 ID,预留给 `wms_order_express.id` | +| `changeQuantity` | `number` | 本次调整值,整数,可正可负 | +| `balanceBefore` | `number` | 调整前余额 | +| `balanceAfter` | `number` | 调整后余额 | +| `reason` | `string` | 调整缘由 | + +--- + +## 10. 后续事件扩展建议 下一步可继续补充: diff --git a/docs/notification-webhook-capability.md b/docs/notification-webhook-capability.md index 22ba7b9..c115cab 100644 --- a/docs/notification-webhook-capability.md +++ b/docs/notification-webhook-capability.md @@ -251,7 +251,71 @@ warehouse:{warehouseId}store:{storeId}:info --- -## 12. 后续扩展建议 +## 12. 新增功能需要通知时怎么接入 + +当其他功能模块需要新增通知时,建议按下面 4 步接入,避免各自重复造轮子: + +### 12.1 注册事件 + +先在 `app/model/notification_webhook.js` 的 `AVAILABLE_EVENTS` 中登记新的事件编码。 + +要求: + +- 事件名仅允许小写字母、数字、下划线 +- 首字符不能为数字 +- **禁止使用 `.`** +- 未注册的事件,`notice.send()` 会直接拒绝发送 + +### 12.2 在业务 service 调用统一入口 + +在实际业务 service 中调用: + +```js +await ctx.service.systems.notice.send({ + warehouseId, + storeId, // 可选,也可传 ownerId + businessName: 'your_business', + event: 'your_event_code', + messageType: 'text', + title: '通知标题', + content: '通知内容', + businessId, + subject, + sender, + metadata, +}); +``` + +接入原则: + +- `warehouseId` 必传,`storeId / ownerId` 可空 +- 业务侧只负责组装业务语义并调用统一入口 +- 重试、分发、失败日志由 `app/service/systems/notice/index.js` 统一处理 +- 如需图片 / 文件通知,补充 `url`、`fileName`、`mimeType` + +### 12.3 测试验证 + +至少补 2 类验证: + +1. **notice 能力测试**:确认事件注册、WebHook 命中、payload 结构与失败处理符合预期 + - 参考:`test/app/service/systems/notice.test.js` +2. **业务回归测试**:确认业务节点确实会触发通知调用 + - 参考:`test/app/service/systems/storage.receiving.report.test.js` + +若对接的是外部地址,还应额外确认: + +- 返回结果是否符合成功约定(如 `1` / `ok` / `errcode=0`) +- 对方是否能正确解析当前 JSON payload + +### 12.4 文档同步 + +接入完成后,至少同步以下文档: + +- 本文档:补能力边界、接入规则或命中说明 +- `docs/notification-event-api.md`:新增事件说明与 payload 示例 +- 若对外暴露了新的 `/system` 接口或 method,再按需同步 `methods/*.json` + +## 13. 后续扩展建议 建议后续继续补充: diff --git a/docs/storage-receiving-api.md b/docs/storage-receiving-api.md new file mode 100644 index 0000000..99208f1 --- /dev/null +++ b/docs/storage-receiving-api.md @@ -0,0 +1,219 @@ +# 收货单 API 文档(`storage.receiving`) + +## 1. 文档说明 + +本文档补充 `storage.receiving` 相关 system 方法中的收货明细商品绑定接口,当前重点覆盖: + +- `storage.receiving.bindDetailProduct` + +适用场景: + +- 新增收货单明细后,为该明细绑定系统商品 +- 已绑定商品时,改绑为另一个系统商品 +- 前端或第三方系统对接收货单明细与系统商品的匹配动作 + +--- + +## 2. 统一调用方式 + +该项目的 system 方法统一通过 `/system` 调用,方法名通过 query 参数 `method` 传入。 + +### 请求方式 + +```http +POST /system?method=storage.receiving.bindDetailProduct&v=1.0×tamp={unix_timestamp} +Content-Type: application/json +Authorization: Bearer +platform: web +project: wms +``` + +### 调用示例 + +```bash +curl -X POST "http://127.0.0.1:6060/system?method=storage.receiving.bindDetailProduct&v=1.0×tamp=1712400000" \ + -H "Authorization: Bearer " \ + -H "Content-Type: application/json" \ + -H "platform: web" \ + -H "project: wms" \ + -d '{ + "detail_id": 12345, + "system_product_id": 67890 + }' +``` + +> 说明:该接口通常要求用户已登录,并以当前仓库角色执行;实际仓库上下文来自 `ctx.user.store_id`。 + +--- + +## 3. 接口:`storage.receiving.bindDetailProduct` + +### 3.1 接口用途 + +用于**绑定或改绑收货单明细的系统商品**。 + +调用成功后,系统会按当前仓库商品信息自动回填或更新以下内容: + +- `system_product_id` +- `product_name` +- `product_snapshot` +- `barcode`(有条码时) +- `weight`(商品存在毛重时) +- 箱规尺寸字段(启用箱规时) + +同时会刷新整张收货单的统计信息。 + +### 3.2 请求参数 + +| 字段 | 类型 | 必填 | 说明 | +|---|---:|---|---| +| `detail_id` | `number` | 是 | 收货单明细 ID | +| `id` | `number` | 否 | 兼容字段,可替代 `detail_id` | +| `system_product_id` | `number` | 是 | 要绑定的系统商品 ID(`StockWarehouse.id`) | + +### 3.3 请求体示例 + +```json +{ + "detail_id": 12345, + "system_product_id": 67890 +} +``` + +--- + +## 4. 成功返回示例 + +```json +{ + "flag": "success", + "code": 200, + "message": "绑定商品成功", + "data": { + "detail_id": 12345, + "receiving_id": 10001, + "system_product_id": 67890, + "product_name": "测试商品A" + } +} +``` + +### 返回字段说明 + +| 字段 | 类型 | 说明 | +|---|---:|---| +| `flag` | `string` | 固定为 `success` | +| `code` | `number` | 业务状态码,成功为 `200` | +| `message` | `string` | 返回说明 | +| `data.detail_id` | `number` | 当前绑定的收货单明细 ID | +| `data.receiving_id` | `number` | 收货单 ID | +| `data.system_product_id` | `number` | 当前绑定的系统商品 ID | +| `data.product_name` | `string` | 自动回填的商品名称 | + +> 注意:该项目的 system 方法经常返回 HTTP `200`,业务是否成功请以响应体内的 `code` 和 `message` 为准。 + +--- + +## 5. 业务校验规则 + +接口内部会执行以下校验: + +1. **当前用户必须有仓库上下文** + - 仓库 ID 取自 `ctx.user.store_id` +2. **收货单明细必须存在** +3. **收货单明细必须属于当前仓库** +4. **收货单状态必须为 `receiving`** + - 已完成、已作废等状态不允许继续绑定或改绑 +5. **目标商品必须属于当前仓库** + - 根据 `StockWarehouse.id + warehouse_id` 校验 + +--- + +## 6. 失败返回示例与错误码 + +### 常见失败场景 + +| `code` | `message` 示例 | 含义 | +|---:|---|---| +| `400` | `用户未绑定仓库` | 当前用户无仓库角色上下文 | +| `400` | `收货单明细ID不能为空` | 未传 `detail_id` / `id` | +| `400` | `商品ID不能为空` | 未传 `system_product_id` | +| `400` | `收货单状态不允许绑定或改绑商品` | 当前收货单状态不允许继续操作 | +| `404` | `收货单明细不存在` | 明细不存在或不属于当前仓库 | +| `404` | `商品不存在或不属于当前仓库` | 商品不存在或仓库不匹配 | +| `500` | `绑定商品失败: ` | 服务内部异常 | + +### 失败响应示例 + +```json +{ + "flag": "success", + "code": 404, + "message": "商品不存在或不属于当前仓库" +} +``` + +--- + +## 7. 推荐调用链路 + +典型前端操作顺序如下: + +1. `storage.receiving.create`:创建收货单 +2. `storage.receiving.addDetail`:新增空白明细,拿到 `selectId` +3. `storage.receiving.bindDetailProduct`:绑定系统商品 +4. `storage.receiving.detailChange`:补充数量、箱数、备注等字段 +5. `storage.receiving.completeReceiving`:完成收货 + +其中第 2 步新增明细后,一般会返回: + +```json +{ + "data": { + "selectId": 12345 + } +} +``` + +该 `selectId` 即可直接作为 `bindDetailProduct` 的 `detail_id`。 + +--- + +## 8. 回归验证参考 + +仓库中已有接口级回归用例,可作为联调参考: + +- `test/app/controller/system.storage.receiving.test.js` + +已覆盖的场景包括: + +- 新建收货单后绑定商品 +- 已绑定商品后再次改绑 +- 绑定成功后返回 `detail_id`、`system_product_id`、`product_name` + +--- + +## 9. 实现位置(源码定位) + +### system 方法包装层 + +- 文件:`app/service/systemMethods/storage/receiving.js` +- 方法:`bindDetailProduct(data)` + +### 实际业务实现 + +- 文件:`app/service/systems/storage/receiving.js` +- 方法:`bindDetailProduct(data)` + +--- + +## 10. 当前接口结论 + +`storage.receiving.bindDetailProduct` 当前已支持: + +- **绑定** 收货明细商品 +- **改绑** 收货明细商品 +- 自动回填商品名称、条码、重量、箱规等信息 +- 自动刷新收货单统计数据 + +适合作为收货单明细与系统商品标准匹配接口对外说明使用。 diff --git a/methods/changes/gateway.json b/methods/changes/gateway.json new file mode 100644 index 0000000..aa2f457 --- /dev/null +++ b/methods/changes/gateway.json @@ -0,0 +1,14 @@ +[ + { + "version": "2026.04.07-gateway-01", + "date": "2026-04-07", + "summary": "初始化 gateway 文档变更记录 sidecar,后续接口文档变更将持续追加到本数组。", + "methods": [ + "*" + ], + "notes": [ + "methods/gateway.json 仍为单一事实来源(SSOT)。", + "本文件仅记录变更历史与补充说明。" + ] + } +] diff --git a/methods/changes/qimen.json b/methods/changes/qimen.json new file mode 100644 index 0000000..c127246 --- /dev/null +++ b/methods/changes/qimen.json @@ -0,0 +1,14 @@ +[ + { + "version": "2026.04.07-qimen-01", + "date": "2026-04-07", + "summary": "初始化 qimen 文档变更记录 sidecar,后续接口文档变更将持续追加到本数组。", + "methods": [ + "*" + ], + "notes": [ + "methods/qimen.json 仍为单一事实来源(SSOT)。", + "本文件仅记录变更历史与补充说明。" + ] + } +] diff --git a/methods/changes/system.json b/methods/changes/system.json new file mode 100644 index 0000000..a00923b --- /dev/null +++ b/methods/changes/system.json @@ -0,0 +1,283 @@ +[ + { + "version": "2026.04.07-system-01", + "date": "2026-04-07", + "summary": "修正 warehouse.getAreaRacks 的鉴权/权限链路文档,明确该接口需要登录并走权限校验。", + "methods": [ + "warehouse.getAreaRacks" + ], + "notes": [ + "对齐当前 system 文档中的 isNeedAuth=true、isNeedLogin=true。", + "用于补充该接口权限链路修正文档的历史上下文,不改变 methods/system.json 的 SSOT 角色。" + ] + }, + { + "version": "2026.04.07-system-02", + "date": "2026-04-07", + "summary": "补充签约配置相关接口文档,覆盖策略字段元信息查询与面单数量人工调整。", + "methods": [ + "storeWarehouse.store.getPolicyConfigFields", + "storeWarehouse.store.adjustPrintQuantity" + ], + "notes": [ + "getPolicyConfigFields 说明为获取签约策略可配置字段元信息列表。", + "adjustPrintQuantity 说明为人工调整签约关系下的面单余额并记录变更日志,并明确 id、change_quantity、reason 等关键入参。" + ] + }, + { + "version": "2026.04.07-system-03", + "date": "2026-04-07", + "summary": "对外命名从 qimenConfig 收口为 apiConfig,并在接口配置文档中强调 interface_type_id 校验。", + "methods": [ + "storeWarehouse.store.listApiConfig", + "storeWarehouse.store.saveApiConfig", + "storeWarehouse.store.deleteQimenConfig" + ], + "notes": [ + "文档对外统一使用 apiConfig / api_config 命名,减少 qimenConfig 历史别名歧义。", + "saveApiConfig 要求 interface_type_id 为必填且必须指向已存在的 wms_interface_type 记录。", + "listApiConfig / deleteQimenConfig 同步补充 interface_type_id 字段说明。" + ] + }, + { + "version": "2026.04.07-system-04", + "date": "2026-04-07", + "summary": "补充 /api/docs 文档体验增强说明,新增查看变更记录与查看原文 JSON 的入口说明。", + "methods": [ + "/api/docs", + "/api/docs/:docName", + "/api/docs/:docName/raw", + "/api/docs/:docName/changes" + ], + "notes": [ + "sidecar 变更数组用于承载文档历史说明,不替代 methods/system.json 作为 SSOT。", + "原文 JSON 入口继续用于直接查看当前生效文档。" + ] + }, + { + "version": "2026.04.07-system-05", + "date": "2026-04-07", + "summary": "修正 storeWarehouse.store.adjustPrintQuantity 的面单余额调整语义:由增减/累加改为覆盖设置目标余额。", + "methods": [ + "storeWarehouse.store.adjustPrintQuantity" + ], + "notes": [ + "adjustPrintQuantity 当前兼容 print_quantity、target_quantity、change_quantity、adjust_quantity 作为目标面单余额输入,不再按增减量解释。", + "变更日志中的 change_quantity 由 before/after 自动计算差值,以兼容历史审计与展示。" + ] + }, + { + "id": "2026.04.07-system-06", + "date": "2026-04-07", + "method": "storeWarehouse.store.saveApiConfig", + "type": "changed", + "summary": "按接口类型分类限制必填字段,OPEN_API 创建时自动生成 self_app_key/self_app_secret", + "detail": "QM_WMS 类型须填写 qimen_app_key/qimen_customer_id/qimen_warehouse_code;OPEN_API 类型三个奇门字段非必填,创建时自动生成 self_app_key(WMS+32位HEX)和 self_app_secret(64位HEX),更新时保留已有密钥。" + }, + { + "id": "2026.04.07-system-07", + "date": "2026-04-07", + "method": "index.listInterfaceTypes", + "type": "added", + "summary": "新增接口类型列表查询接口,归属基础模块,无需权限", + "detail": "返回所有已启用的接口类型(wms_interface_type),包含 id、interface_code、interface_name、interface_category、description 字段。设置 isNeedAuth: false, isNeedLogin: true。" + }, + { + "id": "2026.04.07-system-08", + "date": "2026-04-07", + "method": "storeWarehouse.store.saveApiConfig", + "type": "changed", + "summary": "app_name 改为必传参数", + "detail": "app_name 不再有默认值自动生成逻辑,调用方必须传入非空的 app_name,否则返回 400 错误。" + }, + { + "id": "2026.04.07-system-09", + "date": "2026-04-07", + "method": "storage.inventory.quickPutaway", + "type": "added", + "summary": "新增收货单快捷入库上架接口", + "detail": "新建 storage.inventory 库存操作模块。quickPutaway 从收货单直接生成入库单(SCRK)并写入 wms_storage 库存表,同时更新 wms_stock_warehouse 库存数量(悲观行锁),回填收货明细入库状态。要求收货单已完成且所有明细已匹配系统商品。" + }, + { + "id": "2026.04.08-system-01", + "date": "2026-04-08", + "method": "storage.inventory.matchPutaway", + "type": "added", + "summary": "新增收货单与入库单匹配入库接口", + "detail": "接收多个收货单和入库单,按商品(stock_warehouse_id)进行数量匹配入库,完成后根据入库单来源(QM/API)自动触发回传。入参为 receiving_ids(数组)和 entry_order_ids(数组),返回匹配汇总、各收货单入库状态、各入库单状态及回传结果。isNeedAuth=true, isNeedLogin=true, isNeedRight=false。" + }, + { + "id": "2026.04.08-system-02", + "date": "2026-04-08", + "method": "storeWarehouse.store.saveApiConfig", + "type": "changed", + "summary": "saveApiConfig 新增 callback_url 可选参数", + "detail": "新增 callback_url 参数(VARCHAR(500),可选),用于 OPEN_API 类型入库单的回调地址配置。" + }, + { + "id": "2026.04.08-system-03", + "date": "2026-04-08", + "method": "storeWarehouse.store.list, storeWarehouse.store.listApiConfig", + "type": "changed", + "summary": "serializeQimenConfig 新增返回 callback_url 字段,影响 list 和 listApiConfig 两个接口", + "detail": "serializeQimenConfig() 序列化方法新增 callback_url(string)字段。storeWarehouse.store.list 返回的每条记录 api_config 对象中包含 callback_url;storeWarehouse.store.listApiConfig 返回的 list 数组中每条配置包含 callback_url。" + }, + { + "id": "2026.04.08-system-04", + "date": "2026-04-08", + "method": "storage.inventory.transferLocation", + "type": "added", + "summary": "新增库存移库(库位转移)接口", + "detail": "新增 storage.inventory.transferLocation 接口,支持批量多商品多库位移库,包含部分数量移库与全量移库。入参为 warehouse_id(仓库ID)和 transfers 数组(storage_id、target_space_id、quantity),触发 storage_transfer_completed 通知事件,每条移库记录独立操作日志。isNeedAuth=true, isNeedLogin=true。" + }, + { + "id": "2026.04.08-system-05", + "date": "2026-04-08", + "method": "storage.inventory.transferLocation", + "type": "modified", + "summary": "简化移库接口入参,从批量 transfers 数组改为单条移库", + "detail": "移除 warehouse_id 和 transfers 数组入参,改为扁平的 storage_id + target_space_id + quantity 三个顶层参数。warehouse_id 从库存记录自动获取,接口从批量移库简化为单商品单库位移库。响应结构同步简化为单条结果对象。" + }, + { + "id": "2026.04.08-system-06", + "date": "2026-04-08", + "method": "stock.warehouse.getStockDetail", + "type": "added", + "summary": "新增商品库存明细查询接口", + "detail": "新增 stock.warehouse.getStockDetail 接口,按库位/批次维度查询商品库存分布。入参为 stock_id(必填,商品库存ID)和 pagination(可选,含 page/pageSize)。返回 stockItem(商品概要)、storageList(wms_storage 明细数组,含批次号、库位、数量、锁定数量、生产日期、过期日期等,关联 location_space 库位信息)、pagination 分页信息。isNeedAuth=false, isNeedLogin=true。底层调用 stockStore.getStockDetail,自动校验商品归属当前仓库。" + }, + { + "id": "2026.04.08-system-07", + "date": "2026-04-08", + "method": "stock.warehouse.getStockDetail", + "type": "modified", + "summary": "新增入参 group_by_batch,支持按批次维度切换库存明细聚合方式", + "detail": "新增可选布尔参数 group_by_batch(默认 false)。false 时按库位合并数量,批次相关字段(batch_no, production_date, expiry_date, inbound_time, inbound_order_no, supplier_batch_no)置 null;true 时保持原逻辑返回每条明细。出参结构不变,但 storageList 中批次字段在合并模式下为 null。" + }, + { + "id": "2026.04.08-system-08", + "date": "2026-04-08", + "method": "storage.inventory.transferByProduct", + "type": "added", + "summary": "新增按商品维度移库接口", + "detail": "新增 storage.inventory.transferByProduct 接口,按库位+商品查找所有库存记录合并移动。入参为 space_id(原库位ID)、stock_id(商品SKU ID,即 wms_stock_warehouse.id)、target_space_id(目标库位ID)、quantity(移库数量)。开启批次管理(is_batch_mgmt=Y)的商品会被拒绝,需使用 transferLocation 按库存记录精确移库。复用 storage_transfer_completed 通知事件,操作日志编码 STORAGE_TRANSFER_BY_PRODUCT。isNeedAuth=true, isNeedLogin=true。" + }, + { + "id": "2026.04.08-system-09", + "date": "2026-04-08", + "method": "storeWarehouse.store.list", + "type": "updated", + "summary": "补充 storeWarehouse.store.list 完整 response 输出字段说明,移除 api_config / apiConfig", + "detail": "从返回结果中移除 api_config 和 apiConfig 字段(代码中 delete serialized.api_config / delete serialized.apiConfig),文档 response 补充完整输出字段列表:id, store_id, store_name, warehouse_id, warehouse_name, counterparty_id, counterparty_name, current_subject_role, auth_status, auth_status_label, apply_reason, review_comment, apply_time, review_time, auth_start, auth_end, actual_end, print_quantity, applied_by, reviewed_by, ended_by, remask, use_status, policy_config, is_auth_valid, remaining_days 以及分页和 current_subject 信息。" + }, + { + "id": "2026.04.08-system-10", + "date": "2026-04-08", + "method": "storeWarehouse.store.list", + "type": "changed", + "summary": "货主列表返回新增 has_qimen_config 布尔字段", + "detail": "storeWarehouse.store.list 返回的 data.list[] 中新增 has_qimen_config(boolean),表示该货主是否已配置奇门。" + }, + { + "id": "2026.04.08-system-11", + "date": "2026-04-08", + "method": "stock.warehouse.search", + "type": "updated", + "summary": "补全 stock.warehouse.search 接口文档,新增 params / response / errors 完整说明", + "detail": "入参补充 keyword(string,模糊匹配 item_code / item_name / goods_code / barcode)和 store_id(number,按货主筛选)。响应补充 data 数组各字段(id, item_code, goods_code, item_name, sku_property, stock_unit, quantity, locked_quantity, brand_name, item_type, barcodes, store_stock)以及 total。errors 补充 code=0 搜索失败场景。" + }, + { + "id": "2026.04.08-system-12", + "date": "2026-04-08", + "method": "stock.warehouse.search", + "type": "updated", + "summary": "新增 with_stock / is_batch 参数,支持返回关联库存明细(按库位分组或按批次逐条)", + "detail": "入参新增 with_stock(boolean,默认 false,是否返回关联库存数据)和 is_batch(boolean,默认 false,仅 with_stock=true 时生效,按批次明细返回)。响应 data[] 新增 storage[] 字段:is_batch=false 时按库位分组汇总(含 space_id、space、inventory_type、quantity、locked_quantity、available_quantity);is_batch=true 时逐条返回批次明细(含 id、stock_id、space_id、batch_no、inventory_type、quantity、locked_quantity、available_quantity、production_date、expiry_date、inbound_time、inbound_order_no、supplier_batch_no、created_at、space)。" + }, + { + "id": "2026.04.08-system-13", + "date": "2026-04-08", + "method": "wms_stock_transaction", + "type": "added", + "summary": "新增 wms_stock_transaction 表和模型", + "detail": "新增出入库流水记录表 wms_stock_transaction,含 transaction_type(INBOUND/OUTBOUND)、warehouse_id、store_id、stock_id、storage_id、space_id、quantity、batch_no、inventory_type、order_type、order_no、order_id、receiving_id、entry_order_id、operator_id、operator_name、remark 等字段,关联 StockWarehouse 和 Storage 模型。" + }, + { + "id": "2026.04.08-system-14", + "date": "2026-04-08", + "method": "storage.inventory.quickPutaway,storage.inventory.matchPutaway", + "type": "updated", + "summary": "quickPutaway 和 matchPutaway 入库时自动写入出入库记录", + "detail": "入库操作完成后自动写入 wms_stock_transaction 记录。quickPutaway 写入 order_type='SCRK'(收货入库),matchPutaway 写入 order_type='MATCH'(匹配入库),均自动填充 warehouse_id、store_id、stock_id、storage_id、space_id、quantity、batch_no、inventory_type 等字段。" + }, + { + "id": "2026.04.08-system-15", + "date": "2026-04-08", + "method": "storage.inventory.list", + "type": "added", + "summary": "新增 storage.inventory.list 出入库记录列表查询接口", + "detail": "出入库记录列表查询,支持 where 条件(transaction_type、stock_id、space_id、store_id、order_type、order_no、inventory_type、operator_name、created_at)、分页(pagination)、排序(sort)和 group_by_batch 参数。默认合并模式按库位+商品聚合返回合计数量与记录条数,group_by_batch=true 时返回每条明细含 batch_no、order_no、operator_name 等完整信息。响应均关联 stockItem(item_code、item_name、sku_property、stock_unit)。" + }, + { + "id": "2026.04.08-system-16", + "date": "2026-04-08", + "module": "storage", + "method": "storage.transaction.list", + "type": "rename", + "summary": "出入库流水记录查询接口从 storage.inventory.list 改名为 storage.transaction.list", + "detail": "将出入库流水记录查询从 storage.inventory.list 迁移到 storage.transaction.list,避免与库存列表概念混淆。功能和参数不变。isNeedAuth=false, isNeedLogin=true, isNeedRight=false。" + }, + { + "id": "2026.04.08-system-17", + "date": "2026-04-08", + "module": "storage", + "method": "storage.inventory.list", + "type": "add", + "summary": "新增 storage.inventory.list 库存列表查询接口", + "detail": "新增库存列表查询接口,查询 wms_storage 表。支持 where 条件(stock_id/space_id/store_id/inventory_type/batch_no/inbound_order_no/available_quantity/inbound_time/created_at)、分页、排序。支持 group_by_batch 参数:默认 false 按库位+商品合并(SUM quantity/locked_quantity/available_quantity),true 返回每条明细含 batch_no/production_date/expiry_date 等。关联 stockItem(商品信息)和 space(库位信息)。isNeedAuth=false, isNeedLogin=true, isNeedRight=false。" + }, + { + "id": "2026.04.08-system-18", + "date": "2026-04-08", + "module": "storage", + "method": "storage.entry.create", + "type": "remove", + "summary": "移除 storage.entry.create 创建入库单接口", + "detail": "不再允许通过 API 创建入库单。入库单仅由快捷入库(quickPutaway)和匹配入库(matchPutaway)等内部流程自动创建。底层 service 实现保留但不再通过 systemMethods 暴露。" + }, + { + "id": "2026.04.08-system-19", + "date": "2026-04-08", + "module": "storage", + "method": "storage.entry.addDetail, storage.entry.deleteDetail, storage.entry.detailChange", + "type": "remove", + "summary": "移除 storage.entry.addDetail / deleteDetail / detailChange 对外接口", + "detail": "入库单明细编辑能力不再通过 systemMethods 对外暴露,入库单模块仅保留 list/get/cancel/completeEntry。" + }, + { + "id": "2026.04.08-system-20", + "date": "2026-04-08", + "module": "storage", + "method": "storage.stockout.list, storage.stockout.toOrder, storage.stockout.listItems", + "type": "add", + "summary": "新增 storage.stockout 出库单模块(非订单出库单能力)", + "detail": "新增 storage.stockout.list / toOrder / listItems 接口,作为非订单出库单的主出口(对应奇门 stockout.create)。storage.delivery.* 仅作为兼容转发保留;底层部分能力仍复用 order 模块。" + }, + { + "id": "2026.04.08-system-21", + "date": "2026-04-08", + "method": "storage.stockout.toOrder", + "type": "change", + "summary": "将 storage.stockout.toOrder 标记为占位接口", + "detail": "storage.stockout.toOrder 当前仅保留方法名用于后续扩展,暂不开放实际逻辑。调用时返回 code=405、message=占位接口,暂未开放。" + }, + { + "id": "2026.04.08-system-22", + "date": "2026-04-08", + "module": "storage", + "method": "storage.delivery.*", + "type": "remove", + "summary": "移除 storage.delivery.* 兼容入口", + "detail": "storage.delivery.* 兼容转发已从系统移除,调用方请迁移至 storage.stockout.* 作为主出口。" + } +] diff --git a/methods/qimen.json b/methods/qimen.json index 334a7a5..0f560ac 100644 --- a/methods/qimen.json +++ b/methods/qimen.json @@ -922,7 +922,7 @@ "list": [ { "method": "stockout.create", - "description": "stockout.create 接口", + "description": "stockout.create 接口(创建非订单出库单;对应 system 出口 storage.stockout.*)", "isNeedAuth": false, "isNeedLogin": false, "headers": [], diff --git a/methods/system.json b/methods/system.json index d7c9e13..c339b7e 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1,8 +1,8 @@ { "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", - "version": "0.3.0", - "updatedAt": "2026-03-23", + "version": "0.3.3", + "updatedAt": "2026-04-08", "headers": [ { "name": "platform", @@ -40,7 +40,7 @@ "type": "string", "required": true, "name": "project", - "description": "项目标识,如 all/warehouse/store/tms", + "description": "项目标识,如 all/warehouse/store/tms/wms/scm/other", "list": [ { "value": "all", @@ -57,6 +57,18 @@ { "value": "tms", "name": "物流" + }, + { + "value": "wms", + "name": "WMS" + }, + { + "value": "scm", + "name": "SCM" + }, + { + "value": "other", + "name": "其他" } ] } @@ -424,6 +436,13 @@ "response": [], "errors": [] }, + { + "method": "index.listInterfaceTypes", + "description": "查询可用的接口类型列表(如奇门仓储、开放接口等)", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [] + }, { "method": "index.getExpressList", "description": "index.getExpressList 接口", @@ -464,6 +483,23 @@ "response": [], "errors": [] }, + { + "method": "order.base.getOrderModels", + "description": "订单模型能力兼容入口(当前与 order.getOrderModels 返回一致)", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, { "method": "order.list", "description": "分页查询订单列表", @@ -2016,6 +2052,384 @@ "description": "更新失败" } ] + }, + { + "method": "setting.account.getBindWechatCode", + "description": "为指定工号账号获取微信绑定码", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "account_id", + "type": "number", + "required": true, + "source": "body", + "description": "目标账号ID,兼容 user_id / id" + }, + { + "name": "longPoll", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否开启长轮询等待状态变化,最长60秒" + }, + { + "name": "waitTimeoutMs", + "type": "number", + "required": false, + "source": "body", + "description": "等待超时毫秒数,后端自动封顶60000" + } + ], + "response": [], + "errors": [] + }, + { + "method": "setting.account.unbindWechat", + "description": "为指定工号账号解绑微信", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "account_id", + "type": "number", + "required": true, + "source": "body", + "description": "目标账号ID,兼容 user_id / id" + } + ], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "权限管理模块", + "module": "setting.permission", + "list": [ + { + "method": "setting.permission.list", + "description": "查询权限树/权限列表,可附带指定角色的选中状态", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "role_id", + "type": "number", + "required": false, + "source": "body", + "description": "角色ID;传入后返回 selected 标记" + }, + { + "name": "type", + "type": "string", + "required": false, + "source": "body", + "description": "权限类型筛选:web_pages/pda_pages/btns/api/miniprogram_pages/block" + }, + { + "name": "keyword", + "type": "string", + "required": false, + "source": "body", + "description": "关键字模糊搜索 path/name/meta_title" + }, + { + "name": "includeDisabled", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否包含已停用权限" + } + ], + "response": [], + "errors": [] + }, + { + "method": "setting.permission.add", + "description": "新增权限节点", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "path", + "type": "string", + "required": true, + "source": "body", + "description": "权限路径" + }, + { + "name": "type", + "type": "string", + "required": true, + "source": "body", + "description": "权限类型" + }, + { + "name": "name", + "type": "string", + "required": false, + "source": "body", + "description": "权限名称" + }, + { + "name": "parent_id", + "type": "number", + "required": false, + "source": "body", + "description": "父级权限ID" + } + ], + "response": [], + "errors": [] + }, + { + "method": "setting.permission.update", + "description": "更新权限节点信息", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "permission_id", + "type": "number", + "required": true, + "source": "body", + "description": "权限ID" + } + ], + "response": [], + "errors": [] + }, + { + "method": "setting.permission.delete", + "description": "批量停用权限节点", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids", + "type": "array", + "required": true, + "source": "body", + "description": "待停用的权限ID数组" + } + ], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "角色管理模块", + "module": "setting.role", + "list": [ + { + "method": "setting.role.list", + "description": "获取当前主体可管理的角色树", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "includeDisabled", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否包含已停用角色" + }, + { + "name": "includeSystem", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否包含系统角色域" + } + ], + "response": [], + "errors": [] + }, + { + "method": "setting.role.permission", + "description": "获取角色权限树(兼容旧入口,等同于 setting.permission.list)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "role_id", + "type": "number", + "required": false, + "source": "body", + "description": "角色ID" + } + ], + "response": [], + "errors": [] + }, + { + "method": "setting.role.add", + "description": "新增角色并绑定权限集合", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "role_code", + "type": "string", + "required": true, + "source": "body", + "description": "角色编码" + }, + { + "name": "role_name", + "type": "string", + "required": true, + "source": "body", + "description": "角色名称" + }, + { + "name": "permission_ids", + "type": "array", + "required": true, + "source": "body", + "description": "权限ID数组,支持 [\"*\"]" + }, + { + "name": "pid", + "type": "number", + "required": false, + "source": "body", + "description": "父角色ID" + } + ], + "response": [], + "errors": [] + }, + { + "method": "setting.role.update", + "description": "更新角色信息并重设权限集合", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "role_id", + "type": "number", + "required": true, + "source": "body", + "description": "角色ID" + }, + { + "name": "permission_ids", + "type": "array", + "required": true, + "source": "body", + "description": "权限ID数组,角色权限需一次性提交" + } + ], + "response": [], + "errors": [] + }, + { + "method": "setting.role.delete", + "description": "批量停用角色", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids", + "type": "array", + "required": true, + "source": "body", + "description": "待停用的角色ID数组" + } + ], + "response": [], + "errors": [] } ] }, @@ -2426,7 +2840,7 @@ }, { "method": "stock.warehouse.search", - "description": "仓库商品关键字搜索", + "description": "仓库商品关键字搜索,按 item_code / item_name / goods_code / 条形码模糊匹配,最多返回 50 条", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -2437,7 +2851,342 @@ "description": "Bearer token" } ], - "params": [], + "params": [ + { + "name": "keyword", + "type": "string", + "required": false, + "source": "body", + "description": "搜索关键字,模糊匹配 item_code、item_name、goods_code 以及关联的 barcode;为空时返回全部(仍受 limit 50 限制)" + }, + { + "name": "store_id", + "type": "number", + "required": false, + "source": "body", + "description": "货主ID,传入时仅返回指定货主的商品" + }, + { + "name": "with_stock", + "type": "boolean", + "required": false, + "source": "body", + "default": false, + "description": "是否返回关联库存数据(wms_storage),为 true 时每条商品新增 storage[] 字段" + }, + { + "name": "is_batch", + "type": "boolean", + "required": false, + "source": "body", + "default": false, + "description": "是否按批次明细返回库存,仅 with_stock=true 时生效。false(默认)按库位分组汇总;true 逐条返回批次明细" + } + ], + "response": [ + { + "name": "code", + "type": "number", + "description": "业务状态码,200 表示成功" + }, + { + "name": "data", + "type": "array", + "description": "商品列表,每项包含以下字段", + "children": [ + { + "name": "id", + "type": "number", + "description": "商品库存ID(stock_warehouse.id)" + }, + { + "name": "item_code", + "type": "string", + "description": "商品编码" + }, + { + "name": "goods_code", + "type": "string", + "description": "货物编码" + }, + { + "name": "item_name", + "type": "string", + "description": "商品名称" + }, + { + "name": "sku_property", + "type": "string", + "description": "SKU 规格" + }, + { + "name": "stock_unit", + "type": "string", + "description": "库存单位" + }, + { + "name": "quantity", + "type": "number", + "description": "库存数量" + }, + { + "name": "locked_quantity", + "type": "number", + "description": "锁定数量" + }, + { + "name": "brand_name", + "type": "string", + "description": "品牌名称" + }, + { + "name": "item_type", + "type": "string", + "description": "商品类型" + }, + { + "name": "barcodes", + "type": "array", + "description": "商品条形码列表(string[])" + }, + { + "name": "store_stock", + "type": "object", + "description": "关联的货主签约信息(LEFT JOIN),含 store_id、store_remask;无签约时为 null" + }, + { + "name": "storage", + "type": "array", + "description": "关联库存明细,仅 with_stock=true 时返回。is_batch=false 时按库位分组汇总,is_batch=true 时逐条返回批次明细", + "children_grouped": { + "description": "is_batch=false(默认):按库位分组汇总,每条包含以下字段", + "fields": [ + { + "name": "space_id", + "type": "number", + "description": "库位ID" + }, + { + "name": "inventory_type", + "type": "string", + "description": "库存类型" + }, + { + "name": "quantity", + "type": "number", + "description": "该库位总库存数量(合并同库位)" + }, + { + "name": "locked_quantity", + "type": "number", + "description": "该库位总锁定数量" + }, + { + "name": "available_quantity", + "type": "number", + "description": "可用数量(quantity - locked_quantity)" + }, + { + "name": "space", + "type": "object", + "description": "库位信息子对象,含 id、space_code、custom_name" + } + ] + }, + "children_batch": { + "description": "is_batch=true:逐条批次明细,每条包含以下字段", + "fields": [ + { + "name": "id", + "type": "number", + "description": "storage 记录ID" + }, + { + "name": "stock_id", + "type": "number", + "description": "关联的商品库存ID" + }, + { + "name": "space_id", + "type": "number", + "description": "库位ID" + }, + { + "name": "batch_no", + "type": "string", + "description": "批次号" + }, + { + "name": "inventory_type", + "type": "string", + "description": "库存类型" + }, + { + "name": "quantity", + "type": "number", + "description": "库存数量" + }, + { + "name": "locked_quantity", + "type": "number", + "description": "锁定数量" + }, + { + "name": "available_quantity", + "type": "number", + "description": "可用数量" + }, + { + "name": "production_date", + "type": "string", + "description": "生产日期" + }, + { + "name": "expiry_date", + "type": "string", + "description": "过期日期" + }, + { + "name": "inbound_time", + "type": "string", + "description": "入库时间" + }, + { + "name": "inbound_order_no", + "type": "string", + "description": "入库单号" + }, + { + "name": "supplier_batch_no", + "type": "string", + "description": "供应商批次号" + }, + { + "name": "created_at", + "type": "string", + "description": "记录创建时间" + }, + { + "name": "space", + "type": "object", + "description": "库位信息子对象,含 id、space_code、custom_name" + } + ] + } + } + ] + }, + { + "name": "total", + "type": "number", + "description": "本次返回的记录条数(≤50)" + } + ], + "errors": [ + { + "code": 0, + "message": "搜索失败,请稍后重试", + "description": "服务端查询异常时返回" + } + ] + }, + { + "method": "stock.warehouse.getStockDetail", + "description": "查询商品的库存明细,返回 wms_storage 表的数据(按库位/批次维度展示库存分布)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "stock_id", + "type": "number", + "required": true, + "source": "body", + "description": "商品库存ID(stock_warehouse.id)" + }, + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数,含 page(页码,默认1)和 pageSize(每页条数,默认20)" + }, + { + "name": "group_by_batch", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否区分批次。false(默认)时按库位合并数量,批次相关字段(batch_no, production_date, expiry_date, inbound_time, inbound_order_no, supplier_batch_no)置 null;true 时按原逻辑返回每条明细" + } + ], + "response": [ + { + "name": "stockItem", + "type": "object", + "description": "商品概要信息,含 id, item_code, item_name, sku_property, stock_unit, quantity, locked_quantity" + }, + { + "name": "storageList", + "type": "array", + "description": "库存明细数组,每条含 id, space_id, batch_no, inventory_type, quantity, locked_quantity, available_quantity, production_date, expiry_date, inbound_time, inbound_order_no, supplier_batch_no, created_at,关联 space 对象(id, space_code, custom_name)。当 group_by_batch=false 时,批次相关字段为 null" + }, + { + "name": "pagination", + "type": "object", + "description": "分页信息,含 page, pageSize, total" + } + ], + "errors": [ + { + "code": 0, + "message": "参数 stock_id 不能为空" + }, + { + "code": 0, + "message": "商品不存在或不属于当前仓库" + }, + { + "code": 0, + "message": "查询库存明细失败,请稍后重试" + } + ] + }, + { + "method": "stock.stockWarehouse", + "description": "仓库商品列表查询兼容入口(等同于 stock.warehouse.list)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "筛选条件,写法与 stock.warehouse.list 一致" + } + ], "response": [], "errors": [] } @@ -2684,6 +3433,146 @@ } ] }, + { + "method": "storage.receiving.bindStore", + "description": "收货单绑定货主", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "收货单ID" + }, + { + "name": "store_id", + "type": "number", + "required": true, + "source": "body", + "description": "货主ID(必须与当前仓库存在有效签约关系)" + } + ], + "response": [ + { + "name": "data.id", + "type": "number", + "required": true, + "description": "收货单ID" + }, + { + "name": "data.store_id", + "type": "number", + "required": true, + "description": "已绑定的货主ID" + }, + { + "name": "data.store_name", + "type": "string", + "required": false, + "description": "货主名称/签约备注名" + }, + { + "name": "data.status", + "type": "string", + "required": true, + "description": "当前收货单状态" + } + ], + "errors": [ + { + "code": "400", + "description": "用户未绑定仓库、收货单ID/货主ID为空、已取消或已绑定货主" + }, + { + "code": "404", + "description": "收货单不存在/无权访问,或货主与当前仓库未建立有效签约关系" + }, + { + "code": "500", + "description": "绑定货主失败" + } + ] + }, + { + "method": "storage.receiving.bindDetailProduct", + "description": "收货单明细绑定或改绑系统商品", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "detail_id", + "type": "number", + "required": true, + "source": "body", + "description": "收货单明细ID(兼容字段 `id`)" + }, + { + "name": "system_product_id", + "type": "number", + "required": true, + "source": "body", + "description": "系统商品ID(`StockWarehouse.id`,且必须属于当前仓库)" + } + ], + "response": [ + { + "name": "data.detail_id", + "type": "number", + "required": true, + "description": "收货单明细ID" + }, + { + "name": "data.receiving_id", + "type": "number", + "required": true, + "description": "收货单ID" + }, + { + "name": "data.system_product_id", + "type": "number", + "required": true, + "description": "已绑定的系统商品ID" + }, + { + "name": "data.product_name", + "type": "string", + "required": true, + "description": "自动回填的商品名称" + } + ], + "errors": [ + { + "code": "400", + "description": "用户未绑定仓库、明细ID/商品ID为空,或收货单状态不允许绑定/改绑" + }, + { + "code": "404", + "description": "收货单明细不存在,或商品不存在/不属于当前仓库" + }, + { + "code": "500", + "description": "绑定商品失败" + } + ] + }, { "method": "storage.receiving.addItem", "description": "storage.receiving.addItem 接口", @@ -2866,7 +3755,13 @@ "params": [], "response": [], "errors": [] - }, + } + ] + }, + { + "groupName": "入库单模块", + "module": "storage.entry", + "list": [ { "method": "storage.entry.list", "description": "入库单列表查询", @@ -2982,231 +3877,6 @@ } ] }, - { - "method": "storage.entry.create", - "description": "创建入库单", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "order_type", - "type": "string", - "required": true, - "source": "body", - "description": "业务类型:SCRK/LYRK/CCRK/CGRK/DBRK/QTRK/B2BRK/XNRK" - }, - { - "name": "store_id", - "type": "number", - "required": false, - "source": "body", - "description": "货主ID,不传默认使用当前用户 store_id" - }, - { - "name": "entry_order_code", - "type": "string", - "required": false, - "source": "body", - "description": "入库单号,不传时系统自动生成" - }, - { - "name": "purchase_order_code", - "type": "string", - "required": false, - "source": "body", - "description": "采购单号" - }, - { - "name": "remark", - "type": "string", - "required": false, - "source": "body", - "description": "备注" - } - ], - "response": [ - { - "name": "id", - "type": "number", - "required": true, - "description": "新建入库单ID" - }, - { - "name": "entry_order_code", - "type": "string", - "required": true, - "description": "入库单号" - } - ], - "errors": [ - { - "code": "400", - "description": "参数缺失或业务类型不合法" - }, - { - "code": "409", - "description": "入库单号已存在" - } - ] - }, - { - "method": "storage.entry.addDetail", - "description": "新增入库明细", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "order_id", - "type": "number", - "required": true, - "source": "body", - "description": "入库单ID" - }, - { - "name": "count", - "type": "number", - "required": true, - "source": "body", - "description": "计划入库数量,必须大于0" - }, - { - "name": "item_code", - "type": "string", - "required": false, - "source": "body", - "description": "商品编码" - } - ], - "response": [ - { - "name": "id", - "type": "number", - "required": true, - "description": "新建明细ID" - }, - { - "name": "order_id", - "type": "number", - "required": true, - "description": "所属入库单ID" - } - ], - "errors": [ - { - "code": "400", - "description": "参数不合法或状态不允许新增明细" - }, - { - "code": "404", - "description": "入库单不存在或无权访问" - } - ] - }, - { - "method": "storage.entry.deleteDetail", - "description": "删除入库明细", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "id", - "type": "number", - "required": true, - "source": "body", - "description": "明细ID" - } - ], - "response": [ - { - "name": "id", - "type": "number", - "required": true, - "description": "删除成功的明细ID" - } - ], - "errors": [ - { - "code": "400", - "description": "参数不合法或明细已有收货数量" - }, - { - "code": "404", - "description": "明细或入库单不存在" - } - ] - }, - { - "method": "storage.entry.detailChange", - "description": "修改入库明细", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "id", - "type": "number", - "required": true, - "source": "body", - "description": "明细ID" - }, - { - "name": "count", - "type": "number", - "required": false, - "source": "body", - "description": "计划入库数量,必须大于0且不能小于已收货数量" - } - ], - "response": [ - { - "name": "id", - "type": "number", - "required": true, - "description": "修改成功的明细ID" - } - ], - "errors": [ - { - "code": "400", - "description": "参数不合法或没有可更新字段" - }, - { - "code": "404", - "description": "明细或入库单不存在" - } - ] - }, { "method": "storage.entry.cancel", "description": "作废入库单", @@ -3291,6 +3961,560 @@ } ] }, + { + "groupName": "出库单模块", + "module": "storage.stockout", + "list": [ + { + "method": "storage.stockout.list", + "name": "出库单列表", + "description": "非订单出库单能力(对应奇门 stockout.create):用于处理由奇门创建的非订单出库单;主出口为 storage.stockout.*,不再推荐通过 storage.delivery.* 命名使用。storage.delivery.* 仅保留兼容转发。", + "isNeedAuth": false, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数,支持 page/pageSize" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会在 main 中自动标准化;常用字段包括 delivery_order_code、status、outbound_status、buyer_nick、mobile 与日期区间字段。" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数,支持 sortField/sortOrder,默认按 updated_at DESC、id DESC" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "出库单列表" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息(page、pageSize、total、totalPages、hasPrevious、hasNext)" + } + ], + "errors": [ + { + "code": "400", + "description": "筛选条件格式错误" + }, + { + "code": "500", + "description": "查询失败" + } + ] + }, + { + "method": "storage.stockout.toOrder", + "name": "出库单转订单(占位)", + "description": "占位接口,暂未开放。当前仅保留方法名用于后续扩展,逻辑暂不能使用。参数 id / delivery_order_code 暂未启用。", + "isNeedAuth": false, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": false, + "source": "body", + "description": "预留参数,暂未启用;当前仅保留字段名用于后续扩展。" + }, + { + "name": "delivery_order_code", + "type": "string", + "required": false, + "source": "body", + "description": "预留参数,暂未启用;当前仅保留字段名用于后续扩展。" + } + ], + "response": [ + { + "name": "_note", + "type": "string", + "required": false, + "description": "占位接口,当前无有效业务响应" + } + ], + "errors": [ + { + "code": "405", + "description": "占位接口,暂未开放" + } + ] + }, + { + "method": "storage.stockout.listItems", + "name": "出库单拉取明细", + "description": "按出库单查询商品明细(用于非订单出库单),底层复用 order.listItems。", + "isNeedAuth": false, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "delivery_order_code", + "type": "string", + "required": false, + "source": "body", + "description": "出库单号,可用于定位订单" + }, + { + "name": "order_id", + "type": "number", + "required": false, + "source": "body", + "description": "订单ID,可与 id 兼容用于定位订单" + }, + { + "name": "id", + "type": "number", + "required": false, + "source": "body", + "description": "订单ID,可选;与 delivery_order_code / order_id 至少传一个" + } + ], + "response": [ + { + "name": "order", + "type": "object", + "required": true, + "description": "订单基础信息(含 id、delivery_order_code)" + }, + { + "name": "items", + "type": "array", + "required": true, + "description": "出库单商品明细" + } + ], + "errors": [ + { + "code": "404", + "description": "订单不存在" + }, + { + "code": "500", + "description": "缺少定位参数或查询失败" + } + ] + } + ] + }, + { + "groupName": "库存操作模块", + "module": "storage.inventory", + "list": [ + { + "method": "storage.inventory.quickPutaway", + "description": "收货单快捷入库上架。从收货单直接生成入库单并写入库存表,要求收货单已完成且所有明细已匹配系统商品", + "isNeedAuth": true, + "isNeedLogin": true, + "params": [ + { + "name": "receiving_id", + "type": "number", + "required": true, + "source": "body", + "description": "收货单ID,兼容 id" + } + ], + "response": { + "receiving_id": "收货单ID", + "receiving_number": "收货单号", + "receiving_storage_status": "收货单入库状态(all/partial)", + "entry_order": { + "id": "自动创建的入库单ID", + "entry_order_code": "入库单号", + "order_status": "COMPLETED" + }, + "items": [ + { + "detail_id": "收货明细ID", + "product_name": "商品名称", + "stock_warehouse_id": "库存商品ID", + "inbound_quantity": "入库数量", + "space_id": "库位ID", + "storage_status": "明细入库状态" + } + ] + }, + "errors": [ + { "code": 400, "message": "receiving_id 必填" }, + { "code": 400, "message": "收货单状态须为已完成" }, + { "code": 400, "message": "商品未匹配系统商品" }, + { "code": 400, "message": "已全部入库无需重复操作" }, + { "code": 404, "message": "收货单不存在或无权访问" }, + { "code": 409, "message": "库存记录被锁定(行锁超时)" } + ] + }, + { + "method": "storage.inventory.matchPutaway", + "description": "收货单与入库单匹配入库。接收多个收货单和入库单,按商品(stock_warehouse_id)进行数量匹配入库,完成后根据入库单来源(QM/API)自动触发回传", + "isNeedAuth": true, + "isNeedLogin": true, + "params": [ + { + "name": "receiving_ids", + "type": "array", + "required": true, + "source": "body", + "description": "收货单ID列表" + }, + { + "name": "entry_order_ids", + "type": "array", + "required": true, + "source": "body", + "description": "入库单ID列表" + } + ], + "response": { + "summary": { + "total_products_matched": "匹配的商品种类数", + "total_quantity_inbound": "入库总数量" + }, + "receiving_results": [ + { + "receiving_id": "收货单ID", + "storage_status": "入库状态(all/partial/none)" + } + ], + "entry_order_results": [ + { + "entry_order_id": "入库单ID", + "order_status": "入库单状态(COMPLETED 等)", + "callback_triggered": "是否触发回传(boolean)", + "callback_result": "回传结果对象" + } + ], + "warnings": "匹配过程中的警告信息列表" + }, + "errors": [ + { "code": 400, "message": "receiving_ids 必填且为数组" }, + { "code": 400, "message": "entry_order_ids 必填且为数组" }, + { "code": 404, "message": "收货单不存在或无权访问" }, + { "code": 404, "message": "入库单不存在或无权访问" } + ] + }, + { + "method": "storage.inventory.transferLocation", + "description": "单商品单库位移库,将库存从一个库位移动到另一个库位,支持部分数量移库和全量移库", + "name": "库存移库(库位转移)", + "isNeedAuth": true, + "isNeedLogin": true, + "params": [ + { + "name": "storage_id", + "type": "number", + "required": true, + "source": "body", + "description": "库存记录ID" + }, + { + "name": "target_space_id", + "type": "number", + "required": true, + "source": "body", + "description": "目标库位ID" + }, + { + "name": "quantity", + "type": "number", + "required": false, + "source": "body", + "description": "移库数量,不传则全部移动" + } + ], + "response": { + "storage_id": "原库存记录ID", + "target_space_id": "目标库位ID", + "quantity": "实际移库数量", + "success": "是否成功(boolean)", + "message": "结果说明" + }, + "errors": [ + { "code": 400, "message": "storage_id 必填" }, + { "code": 400, "message": "target_space_id 必填" }, + { "code": 400, "message": "移库数量必须大于0且不超过可用库存" }, + { "code": 400, "message": "目标库位与原库位相同" }, + { "code": 404, "message": "库存记录不存在或无权访问" }, + { "code": 404, "message": "目标库位不存在或不属于该仓库" } + ] + }, + { + "method": "storage.inventory.transferByProduct", + "description": "按库位+商品维度移库,自动查找原库位下该商品的所有库存记录并合并移动。不适用于开启批次管理的商品", + "name": "按商品移库(库位转移)", + "isNeedAuth": true, + "isNeedLogin": true, + "params": [ + { + "name": "space_id", + "type": "number", + "required": true, + "source": "body", + "description": "原库位ID" + }, + { + "name": "stock_id", + "type": "number", + "required": true, + "source": "body", + "description": "商品SKU ID(wms_stock_warehouse.id)" + }, + { + "name": "target_space_id", + "type": "number", + "required": true, + "source": "body", + "description": "目标库位ID" + }, + { + "name": "quantity", + "type": "number", + "required": true, + "source": "body", + "description": "移库数量" + } + ] + }, + { + "method": "storage.inventory.list", + "description": "库存列表查询(查 wms_storage),支持 where 条件、分页、排序、批次分组。默认按库位+商品合并数量(合并模式),group_by_batch=true 时返回每条库存明细(明细模式)", + "name": "库存列表", + "isNeedAuth": false, + "isNeedLogin": true, + "isNeedRight": false, + "params": [ + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "统一 where 条件对象,可用字段:stock_id(商品ID)、space_id(库位ID)、store_id(货主ID)、inventory_type(ZP/CC/JS/XS/ZT/DJ/FP)、batch_no(批次号)、inbound_order_no(入库单号)、available_quantity(可用数量,支持 gt/lt)、inbound_time(入库时间,支持 between)、created_at(创建时间,支持 between)" + }, + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数 { page, pageSize },默认 page=1, pageSize=20" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数 { sortField, sortOrder },默认 sortField='created_at', sortOrder='DESC'" + }, + { + "name": "group_by_batch", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否按批次查询,默认 false。false=合并模式(按库位+商品聚合quantity/locked_quantity/available_quantity),true=明细模式(逐条返回含 batch_no/production_date/expiry_date 等)" + } + ], + "response": { + "_note": "响应结构因 group_by_batch 而异", + "list_merged": { + "_description": "group_by_batch=false(默认合并模式)", + "list": [ + { + "stock_id": "商品库存ID", + "space_id": "库位ID", + "inventory_type": "库存类型", + "warehouse_id": "仓库ID", + "store_id": "货主ID", + "quantity": "总库存数量(SUM)", + "locked_quantity": "总锁定数量(SUM)", + "available_quantity": "总可用数量(SUM)", + "first_inbound_time": "最早入库时间", + "last_inbound_time": "最晚入库时间", + "batch_count": "批次数", + "stock": { "id": "商品ID", "item_code": "商品编码", "item_name": "商品名称", "sku_property": "规格", "stock_unit": "单位" }, + "space": { "id": "库位ID", "space_code": "库位编码", "custom_name": "库位名称" } + } + ], + "pagination": { "page": 1, "pageSize": 20, "total": 100, "totalPages": 5 } + }, + "list_detail": { + "_description": "group_by_batch=true(明细模式)", + "list": [ + { + "id": "库存记录ID", + "warehouse_id": "仓库ID", + "store_id": "货主ID", + "space_id": "库位ID", + "stock_id": "商品库存ID", + "batch_no": "批次号", + "inventory_type": "库存类型", + "quantity": "库存数量", + "locked_quantity": "锁定数量", + "available_quantity": "可用数量", + "production_date": "生产日期", + "expiry_date": "过期日期", + "inbound_time": "入库时间", + "inbound_order_no": "入库单号", + "receiving_id": "收货单ID", + "entry_order_id": "入库单ID", + "supplier_batch_no": "供应商批次号", + "created_at": "创建时间", + "updated_at": "更新时间", + "stock": { "id": "商品ID", "item_code": "商品编码", "item_name": "商品名称", "sku_property": "规格", "stock_unit": "单位" }, + "space": { "id": "库位ID", "space_code": "库位编码", "custom_name": "库位名称" } + } + ], + "pagination": { "page": 1, "pageSize": 20, "total": 100, "totalPages": 5 } + } + } + }, + { + "method": "storage.transaction.list", + "description": "出入库记录列表查询,支持 where 条件、分页、排序、批次分组切换。默认按库位合并数量(合并模式),group_by_batch=true 时返回每条明细(明细模式)", + "name": "出入库流水记录列表", + "isNeedAuth": false, + "isNeedLogin": true, + "isNeedRight": false, + "params": [ + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "统一 where 条件对象,可用字段:transaction_type(ENUM INBOUND/OUTBOUND)、stock_id、space_id、store_id、order_type(SCRK/MATCH)、order_no、inventory_type(ZP/CC/JS/XS/ZT/DJ/FP)、operator_name、created_at(支持 between)" + }, + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数 { page, pageSize },默认 page=1, pageSize=20" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数 { sortField, sortOrder },默认 sortField='created_at', sortOrder='DESC'" + }, + { + "name": "group_by_batch", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否按批次查询明细,默认 false。false=合并模式(按库位+商品聚合),true=明细模式(逐条返回)" + } + ], + "response": { + "_note": "响应结构因 group_by_batch 而异", + "list_merged": { + "_description": "group_by_batch=false(默认合并模式)", + "list": [ + { + "stock_id": "商品库存ID", + "space_id": "库位ID", + "transaction_type": "INBOUND/OUTBOUND", + "inventory_type": "库存类型", + "warehouse_id": "仓库ID", + "store_id": "货主ID", + "order_type": "关联单据类型", + "quantity": "合计数量", + "first_created_at": "最早记录时间", + "last_created_at": "最晚记录时间", + "record_count": "合并记录条数", + "stockItem": { + "id": "商品ID", + "item_code": "商品编码", + "item_name": "商品名称", + "sku_property": "规格", + "stock_unit": "单位" + } + } + ], + "pagination": { "page": "当前页", "pageSize": "每页条数", "total": "总记录数", "totalPages": "总页数" } + }, + "list_detail": { + "_description": "group_by_batch=true(明细模式)", + "list": [ + { + "id": "记录ID", + "transaction_type": "INBOUND/OUTBOUND", + "warehouse_id": "仓库ID", + "store_id": "货主ID", + "stock_id": "商品库存ID", + "storage_id": "库存记录ID", + "space_id": "库位ID", + "quantity": "数量", + "batch_no": "批次号", + "inventory_type": "库存类型", + "order_type": "关联单据类型", + "order_no": "关联单据号", + "order_id": "关联单据ID", + "receiving_id": "收货单ID", + "entry_order_id": "入库单ID", + "operator_id": "操作人ID", + "operator_name": "操作人姓名", + "remark": "备注", + "created_at": "创建时间", + "stockItem": { + "id": "商品ID", + "item_code": "商品编码", + "item_name": "商品名称", + "sku_property": "规格", + "stock_unit": "单位" + } + } + ], + "pagination": { "page": "当前页", "pageSize": "每页条数", "total": "总记录数", "totalPages": "总页数" } + } + }, + "errors": [ + { "code": 400, "message": "where 条件格式不正确" }, + { "code": 400, "message": "分页参数不合法" } + ] + } + ] + }, { "groupName": "主体模块", "module": "store", @@ -3443,6 +4667,603 @@ } ] }, + { + "groupName": "货主-仓库签约模块", + "module": "storeWarehouse.store", + "list": [ + { + "method": "storeWarehouse.store.list", + "description": "查询当前主体可见的仓库-货主签约列表", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "page", + "type": "number", + "required": false, + "source": "body", + "description": "页码,默认 1" + }, + { + "name": "page_size", + "type": "number", + "required": false, + "source": "body", + "description": "分页大小,默认 20" + }, + { + "name": "keyword", + "type": "string", + "required": false, + "source": "body", + "description": "签约备注或主体名称关键字" + } + ], + "response": [ + { + "name": "data.list", + "type": "array", + "description": "签约关系列表" + }, + { + "name": "data.list[].id", + "type": "number", + "description": "签约关系主键 ID" + }, + { + "name": "data.list[].store_id", + "type": "number", + "description": "货主 ID" + }, + { + "name": "data.list[].store_name", + "type": "string", + "description": "货主名称(优先取备注名,无则取 company_name)" + }, + { + "name": "data.list[].warehouse_id", + "type": "number", + "description": "仓库 ID" + }, + { + "name": "data.list[].warehouse_name", + "type": "string", + "description": "仓库名称(优先取备注名,无则取 company_name)" + }, + { + "name": "data.list[].counterparty_id", + "type": "number", + "description": "对方主体 ID(当前为仓库则返回货主 ID,反之亦然)" + }, + { + "name": "data.list[].counterparty_name", + "type": "string", + "description": "对方主体名称" + }, + { + "name": "data.list[].current_subject_role", + "type": "string", + "description": "当前主体角色:warehouse 或 store" + }, + { + "name": "data.list[].auth_status", + "type": "number", + "description": "签约状态:1=申请中 2=已通过 3=已拒绝 4=已解除 5=已过期" + }, + { + "name": "data.list[].auth_status_label", + "type": "string", + "description": "签约状态中文标签" + }, + { + "name": "data.list[].apply_reason", + "type": "string", + "description": "申请原因" + }, + { + "name": "data.list[].review_comment", + "type": "string", + "description": "审核评语" + }, + { + "name": "data.list[].apply_time", + "type": "string|null", + "description": "申请时间" + }, + { + "name": "data.list[].review_time", + "type": "string|null", + "description": "审核时间" + }, + { + "name": "data.list[].auth_start", + "type": "string|null", + "description": "授权开始时间" + }, + { + "name": "data.list[].auth_end", + "type": "string|null", + "description": "授权结束时间" + }, + { + "name": "data.list[].actual_end", + "type": "string|null", + "description": "实际结束时间" + }, + { + "name": "data.list[].print_quantity", + "type": "number", + "description": "面单余额数量" + }, + { + "name": "data.list[].applied_by", + "type": "number|null", + "description": "申请人账号 ID" + }, + { + "name": "data.list[].reviewed_by", + "type": "number|null", + "description": "审核人账号 ID" + }, + { + "name": "data.list[].ended_by", + "type": "number|null", + "description": "解除人账号 ID" + }, + { + "name": "data.list[].remask", + "type": "string", + "description": "备注名(当前为仓库则返回货主备注名,反之亦然)" + }, + { + "name": "data.list[].use_status", + "type": "number", + "description": "启用状态:0=禁用 1=启用" + }, + { + "name": "data.list[].policy_config", + "type": "object|null", + "description": "签约策略配置对象,无则为 null" + }, + { + "name": "data.list[].is_auth_valid", + "type": "boolean", + "description": "签约是否在有效期内" + }, + { + "name": "data.list[].remaining_days", + "type": "number", + "description": "剩余有效天数(未在有效期内时为 0)" + }, + { + "name": "data.list[].has_qimen_config", + "type": "boolean", + "description": "该货主是否已配置奇门(true=已配置,false=未配置)" + }, + { + "name": "data.total", + "type": "number", + "description": "总记录数" + }, + { + "name": "data.page", + "type": "number", + "description": "当前页码" + }, + { + "name": "data.page_size", + "type": "number", + "description": "每页条数" + }, + { + "name": "data.current_subject.store_id", + "type": "number", + "description": "当前主体 ID" + }, + { + "name": "data.current_subject.company_name", + "type": "string", + "description": "当前主体公司名称" + }, + { + "name": "data.current_subject.role", + "type": "string", + "description": "当前主体角色:warehouse 或 store" + } + ], + "errors": [] + }, + { + "method": "storeWarehouse.store.sign", + "description": "发起或确认仓库-货主签约", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "store_id", + "type": "number", + "required": false, + "source": "body", + "description": "货主ID;由仓库侧发起时必传" + }, + { + "name": "warehouse_id", + "type": "number", + "required": false, + "source": "body", + "description": "仓库ID;由货主侧发起时必传" + }, + { + "name": "temp_code", + "type": "string", + "required": false, + "source": "body", + "description": "临时签约码;传入后进入确认或预览流程" + } + ], + "response": [], + "errors": [] + }, + { + "method": "storeWarehouse.store.rename", + "description": "修改当前主体视角下的签约备注名", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "签约关系ID,兼容 contract_id" + } + ], + "response": [], + "errors": [] + }, + { + "method": "storeWarehouse.store.unbind", + "description": "解除或停用签约关系", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "签约关系ID,兼容 contract_id" + }, + { + "name": "use_status", + "type": "number", + "required": false, + "source": "body", + "description": "使用状态,0=停用,1=恢复" + } + ], + "response": [], + "errors": [] + }, + { + "method": "storeWarehouse.store.adjustPrintQuantity", + "description": "人工调整签约关系下的面单余额并记录变更日志", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "签约关系ID,兼容 contract_id" + }, + { + "name": "print_quantity", + "type": "number", + "required": false, + "source": "body", + "description": "目标面单余额(覆盖值);优先使用该字段" + }, + { + "name": "target_quantity", + "type": "number", + "required": false, + "source": "body", + "description": "目标面单余额(覆盖值);兼容别名" + }, + { + "name": "change_quantity", + "type": "number", + "required": true, + "source": "body", + "description": "兼容旧字段;当前按目标面单余额(覆盖值)解释,差值将自动写入变更日志" + }, + { + "name": "adjust_quantity", + "type": "number", + "required": false, + "source": "body", + "description": "兼容旧字段;当前按目标面单余额(覆盖值)解释" + }, + { + "name": "reason", + "type": "string", + "required": true, + "source": "body", + "description": "人工调整缘由,必填" + }, + { + "name": "business_type", + "type": "string", + "required": false, + "source": "body", + "description": "业务来源类型,预留给后续 order_express 等自动扣减场景" + }, + { + "name": "business_id", + "type": "number", + "required": false, + "source": "body", + "description": "业务关联ID,预留给后续关联 wms_order_express.id" + } + ], + "response": [], + "errors": [] + }, + { + "method": "storeWarehouse.store.getPolicyConfig", + "description": "读取签约策略配置", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "签约关系ID,兼容 contract_id" + } + ], + "response": [], + "errors": [] + }, + { + "method": "storeWarehouse.store.getPolicyConfigFields", + "description": "获取签约策略可配置字段元信息列表", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "storeWarehouse.store.savePolicyConfig", + "description": "保存签约策略配置", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "签约关系ID,兼容 contract_id" + }, + { + "name": "policy_config", + "type": "object", + "required": true, + "source": "body", + "description": "策略配置对象;仅支持 receive_mode、sku_visibility、auto_allocate_bin、allow_mix_batch、allow_temp_storage、print_recharge_price(面单充值元/单,支持 2 位小数)、max_daily_inbound、remark" + } + ], + "response": [], + "errors": [] + }, + { + "method": "storeWarehouse.store.listApiConfig", + "description": "查询签约关系下的接口配置列表", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "签约关系ID,兼容 contract_id" + }, + { + "name": "interface_type_id", + "type": "number", + "required": false, + "source": "body", + "description": "接口类型ID,默认查询全部可用类型" + } + ], + "response": [ + { + "name": "data.list[].callback_url", + "type": "string", + "description": "API回调通知URL,来自 serializeQimenConfig 序列化" + } + ], + "errors": [] + }, + { + "method": "storeWarehouse.store.saveApiConfig", + "description": "新增或更新签约关系下的接口配置。QM_WMS 类型须填写奇门字段;OPEN_API 类型由系统自动生成 self_app_key 和 self_app_secret", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "签约关系ID,兼容 contract_id" + }, + { + "name": "interface_type_id", + "type": "number", + "required": true, + "source": "body", + "description": "接口类型ID,必须是 wms_interface_type 已存在的类型" + }, + { + "name": "qimen_app_key", + "type": "string", + "required": false, + "source": "body", + "description": "奇门 AppKey(QM_WMS 类型必填,OPEN_API 类型不需要)" + }, + { + "name": "qimen_customer_id", + "type": "string", + "required": false, + "source": "body", + "description": "奇门客户ID(QM_WMS 类型必填,OPEN_API 类型不需要)" + }, + { + "name": "qimen_warehouse_code", + "type": "string", + "required": false, + "source": "body", + "description": "奇门仓库编码(QM_WMS 类型必填,OPEN_API 类型不需要)" + }, + { + "name": "app_name", + "type": "string", + "required": true, + "source": "body", + "description": "应用名称" + }, + { + "name": "callback_url", + "type": "string", + "required": false, + "source": "body", + "description": "API 类型入库单回调地址(VARCHAR(500),仅 OPEN_API 类型使用)" + } + ], + "response": [], + "errors": [] + }, + { + "method": "storeWarehouse.store.deleteQimenConfig", + "description": "删除签约关系下的奇门接口配置", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "签约关系ID,兼容 contract_id" + }, + { + "name": "interface_type_id", + "type": "number", + "required": false, + "source": "body", + "description": "接口类型ID" + } + ], + "response": [], + "errors": [] + } + ] + }, { "groupName": "用户模块", "module": "user", @@ -3490,6 +5311,24 @@ "response": [], "errors": [] }, + { + "method": "user.getLoginWechatCode", + "description": "获取微信扫码登录码(无 clientCode 时分配新客户端编码;有 clientCode 时可长轮询刷新)", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "clientCode", + "type": "string", + "required": false, + "source": "body", + "description": "客户端编码;首次可不传,后续轮询建议透传已有值" + } + ], + "response": [], + "errors": [] + }, { "method": "user.getBindWechatCode", "description": "获取微信绑定码(默认立即返回;显式开启长轮询后,最长等待60秒,状态变化立即返回)", @@ -3774,6 +5613,13 @@ "source": "body", "description": "height 参数" }, + { + "name": "is_active", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否启用,支持 true/false 或 1/0" + }, { "name": "length", "type": "number", @@ -4255,7 +6101,7 @@ { "method": "warehouse.getAreaRacks", "description": "warehouse.getAreaRacks 接口", - "isNeedAuth": false, + "isNeedAuth": true, "isNeedLogin": true, "headers": [ { diff --git a/model_todo.txt b/model_todo.txt deleted file mode 100644 index 7c603f0..0000000 --- a/model_todo.txt +++ /dev/null @@ -1,23 +0,0 @@ -Model 重构总计划(已完成归档) -更新时间: 2026-03-25 -当前状态: 已完成 - -[事务归属] -- 本子事务已纳入 `todo.txt` 总事务看板统一管理。 - -[完成状态] -- [x] 阶段 1: 全量盘点与基线建立 -- [x] 阶段 2: Migration 补全与执行顺序设计 -- [x] 阶段 3: Model 命名规范化 -- [x] 阶段 4: 关联关系规范化 -- [x] 阶段 5: Model 内部能力清理 -- [x] 阶段 6: 验证与交接 - -[收口说明] -- [x] 本文件由执行计划切换为归档摘要,不再保留阶段性过程清单。 -- [x] 本任务相关临时文档已从 `temp/docs/` 清理。 -- [x] 本任务相关临时中间文件已从 `temp/` 清理。 -- [x] README 中对已清理临时文档的入口已移除。 - -[追溯方式] -- 需要查看过程细节时,优先使用 git 历史、`todo.txt` 总事务看板与 `versioning/` 本地版本记录。 diff --git a/script/sync-system-api-permission.cjs b/script/sync-system-api-permission.cjs index aa14fba..b79aef0 100644 --- a/script/sync-system-api-permission.cjs +++ b/script/sync-system-api-permission.cjs @@ -86,7 +86,6 @@ function loadAuthRequiredMethods(methodDocPath) { return [ ...methodSet ].sort(); } -<<<<<<< HEAD function normalizeRolePermissions(rawValue) { if (rawValue === undefined || rawValue === null) { return { allAccess: false, permissionIds: [] }; @@ -145,9 +144,6 @@ function serializeRolePermissions(rawValue) { const state = normalizeRolePermissions(rawValue); return state.allAccess ? '*' : JSON.stringify(state.permissionIds); } - -======= ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 function buildPermissionDefaults(methodPath, templateRow) { return { path: methodPath, @@ -181,24 +177,16 @@ async function queryExistingPermissions(conn, methodPaths) { const placeholders = methodPaths.map(() => '?').join(','); const [ rows ] = await conn.query( -<<<<<<< HEAD `SELECT id, path, status FROM wms_permission WHERE type = 'api' AND path IN (${placeholders})`, -======= - `SELECT id, path FROM wms_permission WHERE type = 'api' AND path IN (${placeholders})`, ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 methodPaths ); const result = new Map(); for (const row of rows) { -<<<<<<< HEAD result.set(row.path, { id: Number(row.id), status: Number(row.status), }); -======= - result.set(row.path, row.id); ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 } return result; } @@ -227,7 +215,6 @@ async function insertPermission(conn, defaults) { return result.insertId; } -<<<<<<< HEAD async function activatePermission(conn, permissionId) { const [ result ] = await conn.query( 'UPDATE wms_permission SET status = 1, update_at = NOW() WHERE id = ? AND status <> 1', @@ -256,12 +243,6 @@ async function bindRolePermission(conn, roleId, permissionId) { const [ result ] = await conn.query( 'UPDATE wms_role SET permissions = ?, updated_at = NOW() WHERE id = ?', [ serializeRolePermissions(nextPermissions), roleId ] -======= -async function bindRolePermission(conn, roleId, permissionId) { - const [ result ] = await conn.query( - 'INSERT IGNORE INTO wms_role_permission (role_id, permission_id, created_at) VALUES (?, ?, NOW())', - [ roleId, permissionId ] ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 ); return result.affectedRows > 0; } @@ -295,7 +276,6 @@ async function main() { const existingMap = await queryExistingPermissions(conn, methodPaths); const missingPaths = methodPaths.filter(item => !existingMap.has(item)); -<<<<<<< HEAD const disabledPaths = methodPaths.filter(item => { const row = existingMap.get(item); return row && Number(row.status) !== 1; @@ -305,12 +285,6 @@ async function main() { const touchedPermissionIds = []; if (!args.dryRun && (missingPaths.length > 0 || disabledPaths.length > 0)) { -======= - const created = []; - const touchedPermissionIds = []; - - if (!args.dryRun && missingPaths.length > 0) { ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 await conn.beginTransaction(); try { for (const methodPath of missingPaths) { @@ -319,7 +293,6 @@ async function main() { created.push({ methodPath, permissionId }); touchedPermissionIds.push(permissionId); } -<<<<<<< HEAD for (const methodPath of disabledPaths) { const permissionRow = existingMap.get(methodPath); @@ -334,8 +307,6 @@ async function main() { touchedPermissionIds.push(permissionRow.id); } -======= ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 await conn.commit(); } catch (error) { await conn.rollback(); @@ -348,13 +319,8 @@ async function main() { : await queryExistingPermissions(conn, methodPaths); for (const methodPath of methodPaths) { -<<<<<<< HEAD const permissionRow = latestMap.get(methodPath); if (permissionRow && permissionRow.id) touchedPermissionIds.push(permissionRow.id); -======= - const permissionId = latestMap.get(methodPath); - if (permissionId) touchedPermissionIds.push(permissionId); ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 } const uniquePermissionIds = [ ...new Set(touchedPermissionIds) ]; @@ -373,18 +339,12 @@ async function main() { totalAuthMethods: methodPaths.length, existingPermissionCount: existingMap.size, missingPermissionCount: missingPaths.length, -<<<<<<< HEAD disabledPermissionCount: disabledPaths.length, createdPermissionCount: created.length, reactivatedPermissionCount: reactivated.length, roleBindingCreated, sampleMissing: missingPaths.slice(0, 20), sampleDisabled: disabledPaths.slice(0, 20), -======= - createdPermissionCount: created.length, - roleBindingCreated, - sampleMissing: missingPaths.slice(0, 20), ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 }; console.log('[sync-system-api-permission] summary'); diff --git a/test/app/controller/docs.test.js b/test/app/controller/docs.test.js new file mode 100644 index 0000000..e8d4a52 --- /dev/null +++ b/test/app/controller/docs.test.js @@ -0,0 +1,60 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const { app } = require('egg-mock/bootstrap'); + +function hasSemanticKey(keys, candidates) { + return candidates.some(candidate => keys.some(key => key === candidate || key.includes(candidate))); +} + +describe('test/app/controller/docs.test.js', () => { + it('GET /api/docs/system/changes should return 200 and a change-history JSON array', async () => { + const res = await app.httpRequest() + .get('/api/docs/system/changes') + .expect('Content-Type', /json/) + .expect(200); + + assert.ok(Array.isArray(res.body), 'body 应直接返回数组 JSON'); + assert.ok(res.body.length > 0, '变更记录数组至少应包含一条记录'); + + const firstItem = res.body[0]; + assert.equal(typeof firstItem, 'object'); + + const keys = Object.keys(firstItem).map(key => String(key).toLowerCase()); + assert.ok( + hasSemanticKey(keys, [ 'version', 'ver', '版本' ]), + '数组项至少应包含版本字段' + ); + assert.ok( + hasSemanticKey(keys, [ 'date', 'updatedat', 'updated_at', '日期', '时间' ]), + '数组项至少应包含日期字段' + ); + assert.ok( + hasSemanticKey(keys, [ 'summary', 'change', 'desc', 'description', '摘要', '说明' ]), + '数组项至少应包含 summary/摘要字段' + ); + }); + + it('GET /api/docs/system should render HTML entries for change history and raw JSON', async () => { + const res = await app.httpRequest() + .get('/api/docs/system') + .expect('Content-Type', /html/) + .expect(200); + + const html = res.text; + assert.match(html, /\/api\/docs\/system\/changes/, '页面中应提供 /api/docs/system/changes 入口'); + assert.match(html, /查看变更记录|变更记录|changelog/i, '页面中应出现“查看变更记录”或同等入口文案'); + assert.match(html, /\/api\/docs\/system\/raw/, '页面中应提供 /api/docs/system/raw 入口'); + assert.match(html, /查看\s*JSON|raw\s*json/i, '页面中应出现“查看 JSON”入口'); + }); + + it('GET /api/docs/invalid-name!/changes should return 400', async () => { + const res = await app.httpRequest() + .get('/api/docs/invalid-name!/changes') + .expect('Content-Type', /json/) + .expect(400); + + assert.equal(Number(res.body.code), 400); + assert.match(String(res.body.message || ''), /无效|invalid/i); + }); +}); diff --git a/test/app/controller/system.setting.permission.test.js b/test/app/controller/system.setting.permission.test.js index 4776ac4..7745d89 100644 --- a/test/app/controller/system.setting.permission.test.js +++ b/test/app/controller/system.setting.permission.test.js @@ -39,13 +39,11 @@ describe('test/app/controller/system.setting.permission.test.js', () => { } }); -<<<<<<< HEAD it('should expose setting.role.permission as alias of setting.permission.list', async () => { const requestData = { type: 'api', includeDisabled: false, }; - const listRes = await invokeSystemMethod('setting.permission.list', requestData, token, EXTRA_HEADERS); const aliasRes = await invokeSystemMethod('setting.role.permission', requestData, token, EXTRA_HEADERS); @@ -153,23 +151,12 @@ describe('test/app/controller/system.setting.permission.test.js', () => { const updateRes = await invokeSystemMethod('setting.permission.update', { permission_id: 999999999, name: 'not_found_update', -======= - it('should reject out-of-scope permission update', async () => { - const updateRes = await invokeSystemMethod('setting.permission.update', { - permission_id: 999999999, - name: 'out_of_scope_update', ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 }, token, EXTRA_HEADERS); assert.equal(updateRes.status, 200); assert.equal(updateRes.body.flag, 'failure'); -<<<<<<< HEAD assert.equal(Number(updateRes.body.code), 404); assert.match(String(updateRes.body.message || ''), /权限不存在/); -======= - assert.ok([ 400, 404 ].includes(Number(updateRes.body.code)), `unexpected code: ${updateRes.body.code}`); - assert.match(String(updateRes.body.message || ''), /(超出当前登录工号可用权限集|权限不存在)/); ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 }); it('should create then update then delete permission successfully', async () => { @@ -301,11 +288,7 @@ describe('test/app/controller/system.setting.permission.test.js', () => { } }); -<<<<<<< HEAD it('should reject mixed delete when ids contain non-existent permission', async () => { -======= - it('should reject mixed delete when ids contain out-of-scope permission', async () => { ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 const suffix = Date.now(); const path = `autotest.permission.mixed.outscope.${suffix}`; let permissionId = 0; @@ -331,13 +314,8 @@ describe('test/app/controller/system.setting.permission.test.js', () => { assert.equal(mixedRes.status, 200); assert.equal(mixedRes.body.flag, 'failure'); -<<<<<<< HEAD assert.equal(Number(mixedRes.body.code), 404); assert.match(String(mixedRes.body.message || ''), /权限不存在/); -======= - assert.ok([ 400, 404 ].includes(Number(mixedRes.body.code)), `unexpected code: ${mixedRes.body.code}`); - assert.match(String(mixedRes.body.message || ''), /(超出当前登录工号可用权限集|权限不存在)/); ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 // 失败后应保持原子性:合法权限仍可被正常删除(说明前一次未误删) const verifyDeleteRes = await invokeSystemMethod('setting.permission.delete', { diff --git a/test/app/controller/system.setting.storeWarehouse.test.js b/test/app/controller/system.setting.storeWarehouse.test.js index c645e65..14f8302 100644 --- a/test/app/controller/system.setting.storeWarehouse.test.js +++ b/test/app/controller/system.setting.storeWarehouse.test.js @@ -268,7 +268,7 @@ describe('test/app/controller/system.setting.storeWarehouse.test.js', () => { assert.match(String(res.body.message || ''), /unexpected_field|不支持字段/); }); - it('should allow warehouse side to save, update and delete qimen config on a contract', async function() { + it('should allow warehouse side to save, update and delete api config on a contract', async function() { const listRes = await invokeSystemMethod(`${METHOD_PREFIX}.list`, { page: 1, page_size: 30, @@ -285,13 +285,14 @@ describe('test/app/controller/system.setting.storeWarehouse.test.js', () => { const candidates = Array.isArray(listRes.body?.data?.list) ? listRes.body.data.list : []; const candidate = candidates.find(item => Number(item.id) > 0); - assert.ok(candidate, '需要至少一条签约关系用于奇门配置回归'); + assert.ok(candidate, '需要至少一条签约关系用于接口配置回归'); - const originalQimenConfig = candidate.qimen_config ? { ...candidate.qimen_config } : null; + const originalApiConfig = candidate.api_config || candidate.apiConfig || null; const seed = Date.now(); const createPayload = { id: Number(candidate.id), - app_name: `autotest_qimen_${seed}`, + interface_type_id: Number((originalApiConfig && originalApiConfig.interface_type_id) || 0) || undefined, + app_name: `autotest_api_${seed}`, qimen_app_key: `autotest_app_${seed}`, qimen_customer_id: `autotest_customer_${seed}`, qimen_warehouse_code: `autotest_wh_${seed}`, @@ -302,30 +303,37 @@ describe('test/app/controller/system.setting.storeWarehouse.test.js', () => { }; try { - const saveRes = await invokeSystemMethod(`${METHOD_PREFIX}.saveQimenConfig`, createPayload, token, EXTRA_HEADERS); + const saveRes = await invokeSystemMethod(`${METHOD_PREFIX}.saveApiConfig`, createPayload, token, EXTRA_HEADERS); assert.equal(saveRes.status, 200); assert.equal(saveRes.body.flag, 'success'); assert.equal(saveRes.body.code, 200); assert.match(String(saveRes.body?.data?.action || ''), /create|update/); - assert.equal(String(saveRes.body?.data?.qimen_config?.qimen_app_key || ''), createPayload.qimen_app_key); - assert.equal(String(saveRes.body?.data?.qimen_config?.qimen_customer_id || ''), createPayload.qimen_customer_id); - assert.equal(String(saveRes.body?.data?.qimen_config?.qimen_warehouse_code || ''), createPayload.qimen_warehouse_code); + + const savedApiConfig = saveRes.body?.data?.api_config || saveRes.body?.data?.apiConfig || saveRes.body?.data?.qimen_config || null; + assert.ok(savedApiConfig, '保存后应返回 api_config'); + assert.equal(String(savedApiConfig?.qimen_app_key || ''), createPayload.qimen_app_key); + assert.equal(String(savedApiConfig?.qimen_customer_id || ''), createPayload.qimen_customer_id); + assert.equal(String(savedApiConfig?.qimen_warehouse_code || ''), createPayload.qimen_warehouse_code); const updatePayload = { ...createPayload, + interface_type_id: Number((savedApiConfig && savedApiConfig.interface_type_id) || createPayload.interface_type_id || 0) || undefined, app_name: `${createPayload.app_name}_updated`, qimen_customer_id: `${createPayload.qimen_customer_id}_updated`, qimen_warehouse_code: `${createPayload.qimen_warehouse_code}_updated`, is_enabled: 0, }; - const updateRes = await invokeSystemMethod(`${METHOD_PREFIX}.saveQimenConfig`, updatePayload, token, EXTRA_HEADERS); + const updateRes = await invokeSystemMethod(`${METHOD_PREFIX}.saveApiConfig`, updatePayload, token, EXTRA_HEADERS); assert.equal(updateRes.status, 200); assert.equal(updateRes.body.flag, 'success'); assert.equal(updateRes.body.code, 200); assert.equal(String(updateRes.body?.data?.action || ''), 'update'); - assert.equal(String(updateRes.body?.data?.qimen_config?.qimen_customer_id || ''), updatePayload.qimen_customer_id); - assert.equal(String(updateRes.body?.data?.qimen_config?.qimen_warehouse_code || ''), updatePayload.qimen_warehouse_code); - assert.equal(Number(updateRes.body?.data?.qimen_config?.is_enabled), 0); + + const updatedApiConfig = updateRes.body?.data?.api_config || updateRes.body?.data?.apiConfig || updateRes.body?.data?.qimen_config || null; + assert.ok(updatedApiConfig, '更新后应返回 api_config'); + assert.equal(String(updatedApiConfig?.qimen_customer_id || ''), updatePayload.qimen_customer_id); + assert.equal(String(updatedApiConfig?.qimen_warehouse_code || ''), updatePayload.qimen_warehouse_code); + assert.equal(Number(updatedApiConfig?.is_enabled), 0); const verifyRes = await invokeSystemMethod(`${METHOD_PREFIX}.list`, { id: Number(candidate.id), @@ -334,22 +342,23 @@ describe('test/app/controller/system.setting.storeWarehouse.test.js', () => { assert.equal(verifyRes.body.flag, 'success'); assert.equal(verifyRes.body.code, 200); const verified = Array.isArray(verifyRes.body?.data?.list) ? verifyRes.body.data.list[0] : null; - assert.ok(verified, '保存奇门配置后应能查询到签约关系'); - assert.equal(String(verified?.qimen_config?.qimen_customer_id || ''), updatePayload.qimen_customer_id); + assert.ok(verified, '保存接口配置后应能查询到签约关系'); + assert.equal(String((verified?.api_config || verified?.apiConfig || {}).qimen_customer_id || ''), updatePayload.qimen_customer_id); - const configListRes = await invokeSystemMethod(`${METHOD_PREFIX}.listQimenConfig`, { + const configListRes = await invokeSystemMethod(`${METHOD_PREFIX}.listApiConfig`, { id: Number(candidate.id), }, token, EXTRA_HEADERS); assert.equal(configListRes.status, 200); assert.equal(configListRes.body.flag, 'success'); assert.equal(configListRes.body.code, 200); assert.equal(Number(configListRes.body?.data?.contract_id || 0), Number(candidate.id)); - assert.ok(Array.isArray(configListRes.body?.data?.list), '应返回奇门配置列表'); - assert.ok((configListRes.body?.data?.list || []).length >= 1, '保存后应至少返回一条奇门配置'); + assert.ok(Array.isArray(configListRes.body?.data?.list), '应返回接口配置列表'); + assert.ok((configListRes.body?.data?.list || []).length >= 1, '保存后应至少返回一条接口配置'); assert.equal(String(configListRes.body?.data?.list?.[0]?.qimen_customer_id || ''), updatePayload.qimen_customer_id); const deleteRes = await invokeSystemMethod(`${METHOD_PREFIX}.deleteQimenConfig`, { id: Number(candidate.id), + interface_type_id: Number((updatedApiConfig && updatedApiConfig.interface_type_id) || createPayload.interface_type_id || 0) || undefined, }, token, EXTRA_HEADERS); assert.equal(deleteRes.status, 200); assert.equal(deleteRes.body.flag, 'success'); @@ -363,10 +372,10 @@ describe('test/app/controller/system.setting.storeWarehouse.test.js', () => { assert.equal(verifyDeleteRes.body.flag, 'success'); assert.equal(verifyDeleteRes.body.code, 200); const deletedView = Array.isArray(verifyDeleteRes.body?.data?.list) ? verifyDeleteRes.body.data.list[0] : null; - assert.ok(deletedView, '删除奇门配置后仍应能查询到签约关系'); - assert.equal(deletedView?.qimen_config || null, null); + assert.ok(deletedView, '删除接口配置后仍应能查询到签约关系'); + assert.equal(deletedView?.api_config || deletedView?.apiConfig || null, null); - const emptyListRes = await invokeSystemMethod(`${METHOD_PREFIX}.listQimenConfig`, { + const emptyListRes = await invokeSystemMethod(`${METHOD_PREFIX}.listApiConfig`, { id: Number(candidate.id), }, token, EXTRA_HEADERS); assert.equal(emptyListRes.status, 200); @@ -375,17 +384,18 @@ describe('test/app/controller/system.setting.storeWarehouse.test.js', () => { assert.ok(Array.isArray(emptyListRes.body?.data?.list), '删除后仍应返回列表结构'); assert.equal(Number(emptyListRes.body?.data?.total || 0), 0); } finally { - if (originalQimenConfig) { - await invokeSystemMethod(`${METHOD_PREFIX}.saveQimenConfig`, { + if (originalApiConfig) { + await invokeSystemMethod(`${METHOD_PREFIX}.saveApiConfig`, { id: Number(candidate.id), - app_name: originalQimenConfig.app_name, - qimen_app_key: originalQimenConfig.qimen_app_key, - qimen_customer_id: originalQimenConfig.qimen_customer_id, - qimen_warehouse_code: originalQimenConfig.qimen_warehouse_code, - contact_person: originalQimenConfig.contact_person, - contact_phone: originalQimenConfig.contact_phone, - email: originalQimenConfig.email, - is_enabled: Number(originalQimenConfig.is_enabled || 0), + interface_type_id: Number(originalApiConfig.interface_type_id || 0) || undefined, + app_name: originalApiConfig.app_name, + qimen_app_key: originalApiConfig.qimen_app_key, + qimen_customer_id: originalApiConfig.qimen_customer_id, + qimen_warehouse_code: originalApiConfig.qimen_warehouse_code, + contact_person: originalApiConfig.contact_person, + contact_phone: originalApiConfig.contact_phone, + email: originalApiConfig.email, + is_enabled: Number(originalApiConfig.is_enabled || 0), }, token, EXTRA_HEADERS); } } diff --git a/test/app/controller/system.stock.warehouse.getStockDetail.test.js b/test/app/controller/system.stock.warehouse.getStockDetail.test.js new file mode 100644 index 0000000..76959cf --- /dev/null +++ b/test/app/controller/system.stock.warehouse.getStockDetail.test.js @@ -0,0 +1,316 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const { + getAuthToken, + invokeSystemMethod, +} = require('../../support/system_method_client'); + +const EXTRA_HEADERS = { + platform: 'web', + project: 'all', +}; + +const FALLBACK_ROLE_IDS = [ 4, 6, 30 ]; + +async function switchToWarehouseRole(token) { + let currentToken = token; + const infoRes = await invokeSystemMethod('user.info', {}, currentToken, EXTRA_HEADERS); + + assert.equal(infoRes.status, 200); + assert.equal(infoRes.body.flag, 'success'); + assert.equal(infoRes.body.code, 200); + + const employees = Array.isArray(infoRes.body?.data?.employees) ? infoRes.body.data.employees : []; + const warehouseRoles = employees.filter(item => item && item.role_type === 'warehouse' && Number(item.id)); + const candidateRoleIds = [ ...new Set([ + ...warehouseRoles.map(item => Number(item.id)), + ...FALLBACK_ROLE_IDS, + ].filter(Boolean)) ]; + + assert.ok(candidateRoleIds.length > 0, '当前账号没有可尝试的仓库角色'); + + for (const roleId of candidateRoleIds) { + const changeRes = await invokeSystemMethod('user.changeRole', { + roleId, + }, currentToken, EXTRA_HEADERS); + + if (changeRes.status !== 200 || changeRes.body?.flag !== 'success' || changeRes.body?.code !== 200) { + continue; + } + + currentToken = changeRes.body?.data?.token || currentToken; + + const listRes = await invokeSystemMethod('stock.warehouse.list', { + pagination: { page: 1, pageSize: 1 }, + where: {}, + }, currentToken, EXTRA_HEADERS); + + if (listRes.status === 200 && listRes.body?.flag === 'success' && listRes.body?.code === 200) { + return { + token: currentToken, + roleId, + }; + } + } + + throw new Error('未找到可访问仓库商品列表的仓库角色'); +} + +/** + * 从仓库商品列表中获取一个有效的 stock_id + * @param {string} token 传入的token必须具有访问仓库商品列表的权限 + */ +async function getValidStockId(token) { + const listRes = await invokeSystemMethod('stock.warehouse.list', { + pagination: { page: 1, pageSize: 1 }, + where: {}, + }, token, EXTRA_HEADERS); + + assert.equal(listRes.status, 200); + assert.equal(listRes.body.flag, 'success'); + assert.equal(listRes.body.code, 200); + + const list = listRes.body?.data?.list; + assert.ok(Array.isArray(list) && list.length > 0, '仓库中没有商品数据,无法执行测试'); + + return list[0].id; +} + +describe('test/app/controller/system.stock.warehouse.getStockDetail.test.js', () => { + let warehouseToken; + let validStockId; + + before(async () => { + const { token } = await getAuthToken(); + const switched = await switchToWarehouseRole(token); + warehouseToken = switched.token; + validStockId = await getValidStockId(warehouseToken); + }); + + it('should return stockItem, storageList and pagination for a valid stock_id', async () => { + const res = await invokeSystemMethod('stock.warehouse.getStockDetail', { + stock_id: validStockId, + }, warehouseToken, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + assert.equal(res.body.code, 200); + + const data = res.body.data; + assert.ok(data, '响应缺少 data'); + + // stockItem 结构校验 + assert.ok(data.stockItem, '缺少 stockItem'); + assert.ok('id' in data.stockItem, 'stockItem 缺少 id'); + assert.ok('item_code' in data.stockItem, 'stockItem 缺少 item_code'); + assert.ok('item_name' in data.stockItem, 'stockItem 缺少 item_name'); + assert.ok('quantity' in data.stockItem, 'stockItem 缺少 quantity'); + assert.ok('locked_quantity' in data.stockItem, 'stockItem 缺少 locked_quantity'); + + // storageList 结构校验 + assert.ok(Array.isArray(data.storageList), 'storageList 应为数组'); + + // pagination 结构校验 + assert.ok(data.pagination, '缺少 pagination'); + assert.ok('page' in data.pagination, 'pagination 缺少 page'); + assert.ok('pageSize' in data.pagination, 'pagination 缺少 pageSize'); + assert.ok('total' in data.pagination, 'pagination 缺少 total'); + }); + + it('should respect pagination parameters', async () => { + const res = await invokeSystemMethod('stock.warehouse.getStockDetail', { + stock_id: validStockId, + pagination: { page: 1, pageSize: 2 }, + }, warehouseToken, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + assert.equal(res.body.code, 200); + + const data = res.body.data; + assert.ok(data, '响应缺少 data'); + assert.ok(Array.isArray(data.storageList), 'storageList 应为数组'); + assert.ok(data.storageList.length <= 2, 'storageList 数量应不超过 pageSize'); + assert.equal(data.pagination.page, 1); + assert.equal(data.pagination.pageSize, 2); + }); + + it('should return error when stock_id is empty', async () => { + const res = await invokeSystemMethod('stock.warehouse.getStockDetail', {}, warehouseToken, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + assert.equal(res.body.code, 0, '缺少 stock_id 应返回 code=0'); + assert.ok(res.body.message, '缺少 stock_id 应返回错误消息'); + }); + + it('should return error when stock_id does not exist', async () => { + const res = await invokeSystemMethod('stock.warehouse.getStockDetail', { + stock_id: 999999999, + }, warehouseToken, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + assert.equal(res.body.code, 0, '不存在的 stock_id 应返回 code=0'); + assert.ok(res.body.message, '不存在的 stock_id 应返回错误消息'); + }); + + it('should return empty storageList when stock exists but has no storage records', async () => { + // 使用有效 stock_id 查询,如果该商品恰好有库存,则仅验证结构 + // 若无库存记录,storageList 应为空数组 + const res = await invokeSystemMethod('stock.warehouse.getStockDetail', { + stock_id: validStockId, + pagination: { page: 9999, pageSize: 20 }, + }, warehouseToken, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + assert.equal(res.body.code, 200); + + const data = res.body.data; + assert.ok(data, '响应缺少 data'); + assert.ok(data.stockItem, '缺少 stockItem'); + assert.ok(Array.isArray(data.storageList), 'storageList 应为数组'); + assert.equal(data.storageList.length, 0, '超出范围的分页应返回空 storageList'); + }); + + // ---- group_by_batch 相关用例 ---- + + const BATCH_FIELDS = [ 'batch_no', 'production_date', 'expiry_date', 'inbound_time', 'inbound_order_no', 'supplier_batch_no' ]; + + it('should merge storageList by space_id when group_by_batch is not provided (default)', async () => { + // 先用 group_by_batch=true 获取原始明细 + const rawRes = await invokeSystemMethod('stock.warehouse.getStockDetail', { + stock_id: validStockId, + group_by_batch: true, + pagination: { page: 1, pageSize: 200 }, + }, warehouseToken, EXTRA_HEADERS); + + assert.equal(rawRes.status, 200); + assert.equal(rawRes.body.code, 200); + const rawList = rawRes.body.data.storageList; + + // 默认不传 group_by_batch + const mergedRes = await invokeSystemMethod('stock.warehouse.getStockDetail', { + stock_id: validStockId, + pagination: { page: 1, pageSize: 200 }, + }, warehouseToken, EXTRA_HEADERS); + + assert.equal(mergedRes.status, 200); + assert.equal(mergedRes.body.flag, 'success'); + assert.equal(mergedRes.body.code, 200); + + const mergedList = mergedRes.body.data.storageList; + assert.ok(Array.isArray(mergedList), 'storageList 应为数组'); + + // 按 space_id 分组计算期望的合并数 + const spaceIds = new Set(rawList.map(r => r.space_id)); + assert.equal(mergedList.length, spaceIds.size, '合并后记录数应等于不同 space_id 数量'); + + // 验证批次字段全部置 null + for (const row of mergedList) { + for (const field of BATCH_FIELDS) { + assert.equal(row[field], null, `合并模式下 ${field} 应为 null`); + } + } + + // 验证 quantity 累加正确:raw 按 space_id 分组求和 vs merged + for (const row of mergedList) { + const rawForSpace = rawList.filter(r => r.space_id === row.space_id); + const expectedQty = rawForSpace.reduce((sum, r) => sum + Number(r.quantity), 0); + const expectedLocked = rawForSpace.reduce((sum, r) => sum + Number(r.locked_quantity), 0); + assert.equal(Number(row.quantity), expectedQty, `space_id=${row.space_id} quantity 累加不正确`); + assert.equal(Number(row.locked_quantity), expectedLocked, `space_id=${row.space_id} locked_quantity 累加不正确`); + assert.equal(Number(row.available_quantity), expectedQty - expectedLocked, `space_id=${row.space_id} available_quantity 计算不正确`); + } + }); + + it('should merge storageList by space_id when group_by_batch=false (explicit)', async () => { + // 显式传 false + const explicitRes = await invokeSystemMethod('stock.warehouse.getStockDetail', { + stock_id: validStockId, + group_by_batch: false, + pagination: { page: 1, pageSize: 200 }, + }, warehouseToken, EXTRA_HEADERS); + + assert.equal(explicitRes.status, 200); + assert.equal(explicitRes.body.flag, 'success'); + assert.equal(explicitRes.body.code, 200); + + const explicitList = explicitRes.body.data.storageList; + + // 默认不传 group_by_batch + const defaultRes = await invokeSystemMethod('stock.warehouse.getStockDetail', { + stock_id: validStockId, + pagination: { page: 1, pageSize: 200 }, + }, warehouseToken, EXTRA_HEADERS); + + assert.equal(defaultRes.status, 200); + assert.equal(defaultRes.body.code, 200); + + const defaultList = defaultRes.body.data.storageList; + + // 显式 false 与默认行为一致 + assert.equal(explicitList.length, defaultList.length, '显式 false 与默认不传应返回相同数量'); + + // 验证批次字段全部置 null + for (const row of explicitList) { + for (const field of BATCH_FIELDS) { + assert.equal(row[field], null, `显式 false 模式下 ${field} 应为 null`); + } + } + + // quantity 应一致 + for (let i = 0; i < explicitList.length; i++) { + assert.equal(Number(explicitList[i].quantity), Number(defaultList[i].quantity), `第 ${i} 条 quantity 不一致`); + assert.equal(Number(explicitList[i].locked_quantity), Number(defaultList[i].locked_quantity), `第 ${i} 条 locked_quantity 不一致`); + } + }); + + it('should return independent records per batch when group_by_batch=true', async () => { + const res = await invokeSystemMethod('stock.warehouse.getStockDetail', { + stock_id: validStockId, + group_by_batch: true, + pagination: { page: 1, pageSize: 200 }, + }, warehouseToken, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + assert.equal(res.body.code, 200); + + const data = res.body.data; + assert.ok(Array.isArray(data.storageList), 'storageList 应为数组'); + + // 验证结构完整:每条记录包含批次字段 + for (const row of data.storageList) { + assert.ok('batch_no' in row, '区分批次模式下应包含 batch_no'); + assert.ok('production_date' in row, '区分批次模式下应包含 production_date'); + assert.ok('expiry_date' in row, '区分批次模式下应包含 expiry_date'); + assert.ok('inbound_time' in row, '区分批次模式下应包含 inbound_time'); + assert.ok('inbound_order_no' in row, '区分批次模式下应包含 inbound_order_no'); + assert.ok('supplier_batch_no' in row, '区分批次模式下应包含 supplier_batch_no'); + assert.ok('quantity' in row, '区分批次模式下应包含 quantity'); + assert.ok('locked_quantity' in row, '区分批次模式下应包含 locked_quantity'); + assert.ok('available_quantity' in row, '区分批次模式下应包含 available_quantity'); + } + + // 与合并模式对比:group_by_batch=true 的记录数应 >= 合并后记录数 + const mergedRes = await invokeSystemMethod('stock.warehouse.getStockDetail', { + stock_id: validStockId, + pagination: { page: 1, pageSize: 200 }, + }, warehouseToken, EXTRA_HEADERS); + + assert.equal(mergedRes.status, 200); + assert.equal(mergedRes.body.code, 200); + + const mergedCount = mergedRes.body.data.storageList.length; + assert.ok(data.storageList.length >= mergedCount, 'group_by_batch=true 记录数应 >= 合并后记录数'); + + // pagination 结构校验 + assert.ok(data.pagination, '缺少 pagination'); + assert.ok('page' in data.pagination, 'pagination 缺少 page'); + assert.ok('pageSize' in data.pagination, 'pagination 缺少 pageSize'); + assert.ok('total' in data.pagination, 'pagination 缺少 total'); + }); +}); diff --git a/test/app/controller/system.storage.delivery.module.test.js b/test/app/controller/system.storage.delivery.module.test.js new file mode 100644 index 0000000..ededb30 --- /dev/null +++ b/test/app/controller/system.storage.delivery.module.test.js @@ -0,0 +1,304 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const { + getAuthToken, + invokeSystemMethod, +} = require('../../support/system_method_client'); + +const EXTRA_HEADERS = { + platform: 'web', + project: 'all', +}; + +const FALLBACK_ROLE_IDS = [ 4, 6, 30 ]; +const TEST_WAREHOUSE_ID = 100000; + +function normalizeListPayload(data) { + if (data && Array.isArray(data.list)) return data; + if (data && data.data && Array.isArray(data.data.list)) return data.data; + return null; +} + +async function switchToWarehouseRoleWithDeliveryData(token) { + let currentToken = token; + + const infoRes = await invokeSystemMethod('user.info', {}, currentToken, EXTRA_HEADERS); + assert.equal(infoRes.status, 200); + assert.equal(infoRes.body.flag, 'success'); + assert.equal(infoRes.body.code, 200); + + const employees = Array.isArray(infoRes.body?.data?.employees) ? infoRes.body.data.employees : []; + const preferredWarehouseRoles = employees.filter(item => + item + && item.role_type === 'warehouse' + && Number(item.id) + && Number(item.store_id) === TEST_WAREHOUSE_ID + ); + const otherWarehouseRoles = employees.filter(item => + item + && item.role_type === 'warehouse' + && Number(item.id) + && Number(item.store_id) !== TEST_WAREHOUSE_ID + ); + + const candidateRoleIds = [ ...new Set([ + ...preferredWarehouseRoles.map(item => Number(item.id)), + ...otherWarehouseRoles.map(item => Number(item.id)), + ...FALLBACK_ROLE_IDS, + ].filter(Boolean)) ]; + + assert.ok(candidateRoleIds.length > 0, '当前账号没有可尝试的仓库角色'); + + for (const roleId of candidateRoleIds) { + const changeRes = await invokeSystemMethod('user.changeRole', { + roleId, + }, currentToken, EXTRA_HEADERS); + + if (changeRes.status !== 200 || changeRes.body?.flag !== 'success' || changeRes.body?.code !== 200) { + continue; + } + + currentToken = changeRes.body?.data?.token || currentToken; + + const statsRes = await invokeSystemMethod('order.stats', { + where: {}, + }, currentToken, EXTRA_HEADERS); + + if (statsRes.status !== 200 || statsRes.body?.flag !== 'success' || statsRes.body?.code !== 200) { + continue; + } + + const total = Number(statsRes.body?.data?.total || 0); + if (total > 0) { + return { + token: currentToken, + roleId, + total, + }; + } + } + + throw new Error('未找到有订单数据的仓库角色'); +} + +async function getFirstDelivery(token) { + const res = await invokeSystemMethod('storage.stockout.list', { + pagination: { + page: 1, + pageSize: 10, + }, + where: {}, + }, token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + assert.equal(res.body.code, 200); + + const payload = normalizeListPayload(res.body.data); + assert.ok(payload, '返回结构中缺少出库单列表 payload'); + assert.ok(Array.isArray(payload.list), '出库单 list 不是数组'); + assert.ok(payload.pagination, '出库单 pagination 缺失'); + + const first = payload.list[0]; + assert.ok(first, '出库单列表为空,无法继续验证 toOrder/listItems'); + return first; +} + +async function getEntryContextForRemovedMethods(token) { + const listRes = await invokeSystemMethod('storage.entry.list', { + pagination: { + page: 1, + pageSize: 1, + }, + where: {}, + }, token, EXTRA_HEADERS); + + assert.equal(listRes.status, 200); + assert.equal(listRes.body.flag, 'success'); + assert.equal(listRes.body.code, 200); + + const payload = normalizeListPayload(listRes.body.data); + const entry = payload && Array.isArray(payload.list) ? payload.list[0] : null; + + if (!entry || !entry.id) { + return { + orderId: 1, + detailId: 1, + itemCode: `SKU-${Date.now().toString().slice(-6)}`, + }; + } + + const getRes = await invokeSystemMethod('storage.entry.get', { + id: Number(entry.id), + }, token, EXTRA_HEADERS); + + assert.equal(getRes.status, 200); + assert.equal(getRes.body.flag, 'success'); + assert.equal(getRes.body.code, 200); + + const entryOrder = getRes.body?.data?.entryOrder || {}; + const firstItem = Array.isArray(entryOrder?.items) ? entryOrder.items[0] : null; + + return { + orderId: Number(entry.id), + detailId: Number(firstItem?.id || 1), + itemCode: String(firstItem?.item_code || firstItem?.stock?.item_code || `SKU-${Date.now().toString().slice(-6)}`), + }; +} + +describe('test/app/controller/system.storage.delivery.module.test.js', function() { + this.timeout(120000); + + it('should not expose storage.delivery methods after compatibility layer removal', async () => { + const { token } = await getAuthToken(); + const switched = await switchToWarehouseRoleWithDeliveryData(token); + const delivery = await getFirstDelivery(switched.token); + + const removedMethods = [ + { + method: 'storage.delivery.list', + body: { + pagination: { + page: 1, + pageSize: 10, + }, + where: {}, + }, + }, + { + method: 'storage.delivery.toOrder', + body: { + id: Number(delivery.id), + delivery_order_code: delivery.delivery_order_code, + warehouse_id: TEST_WAREHOUSE_ID, + }, + }, + { + method: 'storage.delivery.listItems', + body: { + id: Number(delivery.id), + delivery_order_code: delivery.delivery_order_code, + warehouse_id: TEST_WAREHOUSE_ID, + }, + }, + ]; + + for (const { method, body } of removedMethods) { + const res = await invokeSystemMethod(method, body, switched.token, EXTRA_HEADERS); + const isLegacySuccess = res.status === 200 + && res.body?.flag === 'success' + && Number(res.body?.code) === 200; + + assert.ok(!isLegacySuccess, `${method} 仍然返回 success 200: ${JSON.stringify(res.body)}`); + } + }); + + it('should return delivery list via storage.stockout.list', async () => { + const { token } = await getAuthToken(); + const switched = await switchToWarehouseRoleWithDeliveryData(token); + + const res = await invokeSystemMethod('storage.stockout.list', { + pagination: { + page: 1, + pageSize: 10, + }, + where: {}, + }, switched.token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + assert.equal(res.body.code, 200); + + const payload = normalizeListPayload(res.body.data); + assert.ok(payload, '返回结构中缺少出库单列表 payload'); + assert.ok(Array.isArray(payload.list), '出库单 list 不是数组'); + assert.ok(payload.pagination, '出库单 pagination 缺失'); + assert.equal(typeof payload.pagination.total, 'number', 'pagination.total 不是 number'); + }); + + it('should return placeholder failure via storage.stockout.toOrder', async () => { + const { token } = await getAuthToken(); + const switched = await switchToWarehouseRoleWithDeliveryData(token); + const delivery = await getFirstDelivery(switched.token); + + const res = await invokeSystemMethod('storage.stockout.toOrder', { + id: Number(delivery.id), + delivery_order_code: delivery.delivery_order_code, + warehouse_id: TEST_WAREHOUSE_ID, + }, switched.token, EXTRA_HEADERS); + + console.log('[storage.stockout.toOrder]', JSON.stringify({ + flag: res.body?.flag, + code: res.body?.code, + message: res.body?.message, + placeholder: res.body?.placeholder, + })); + + assert.equal(res.status, 200); + assert.notEqual(res.body.flag, 'success', 'toOrder 不应再返回 success'); + assert.equal(Number(res.body.code), 405); + assert.match(String(res.body.message || ''), /占位接口|暂未开放/); + assert.equal(res.body.flag, 'failure'); + assert.equal(res.body.placeholder, true); + }); + + it('should return item list via storage.stockout.listItems', async () => { + const { token } = await getAuthToken(); + const switched = await switchToWarehouseRoleWithDeliveryData(token); + const delivery = await getFirstDelivery(switched.token); + + const res = await invokeSystemMethod('storage.stockout.listItems', { + id: Number(delivery.id), + delivery_order_code: delivery.delivery_order_code, + warehouse_id: TEST_WAREHOUSE_ID, + }, switched.token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + assert.equal(res.body.code, 200); + assert.ok(res.body.data && typeof res.body.data === 'object', '缺少 data 对象'); + assert.ok(Array.isArray(res.body.data.items), 'data.items 不是数组'); + }); + + it('should not expose removed storage.entry detail methods', async () => { + const { token } = await getAuthToken(); + const switched = await switchToWarehouseRoleWithDeliveryData(token); + const entryContext = await getEntryContextForRemovedMethods(switched.token); + + const removedMethods = [ + { + method: 'storage.entry.addDetail', + body: { + order_id: entryContext.orderId, + count: 1, + item_code: entryContext.itemCode, + inventory_type: 'ZP', + }, + }, + { + method: 'storage.entry.deleteDetail', + body: { + id: entryContext.detailId, + }, + }, + { + method: 'storage.entry.detailChange', + body: { + id: entryContext.detailId, + count: 2, + item_code: entryContext.itemCode, + }, + }, + ]; + + for (const { method, body } of removedMethods) { + const res = await invokeSystemMethod(method, body, switched.token, EXTRA_HEADERS); + const isLegacySuccess = res.status === 200 + && res.body?.flag === 'success' + && Number(res.body?.code) === 200; + + assert.ok(!isLegacySuccess, `${method} 仍然返回 success 200: ${JSON.stringify(res.body)}`); + } + }); +}); diff --git a/test/app/controller/system.storage.inventory.matchPutaway.test.js b/test/app/controller/system.storage.inventory.matchPutaway.test.js new file mode 100644 index 0000000..896a978 --- /dev/null +++ b/test/app/controller/system.storage.inventory.matchPutaway.test.js @@ -0,0 +1,430 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const Sequelize = require('sequelize'); +const { + getAuthToken, + invokeSystemMethod, +} = require('../../support/system_method_client'); + +const EXTRA_HEADERS = { platform: 'web', project: 'all' }; +const FALLBACK_ROLE_IDS = [ 4, 6, 30 ]; +const TEST_STORE_ID = 1000000; +const TEST_WAREHOUSE_ID = 100000; + +// ──── 数据库连接 ──── +const dbConfig = require('../../../database/config'); +const env = process.env.NODE_ENV || 'development'; +const config = dbConfig[env] || dbConfig.development || Object.values(dbConfig)[0]; + +// ──── switchToWarehouseRole ──── +async function switchToWarehouseRole(token) { + let currentToken = token; + const infoRes = await invokeSystemMethod('user.info', {}, currentToken, EXTRA_HEADERS); + assert.equal(infoRes.status, 200); + assert.equal(infoRes.body.flag, 'success'); + + const employees = Array.isArray(infoRes.body?.data?.employees) ? infoRes.body.data.employees : []; + const warehouseRoles = employees.filter(item => + item && item.role_type === 'warehouse' && Number(item.id) && + Number(item.store_id) === TEST_WAREHOUSE_ID + ); + const candidateRoleIds = [ ...new Set([ + ...warehouseRoles.map(item => Number(item.id)), + ...FALLBACK_ROLE_IDS, + ].filter(Boolean)) ]; + assert.ok(candidateRoleIds.length > 0, '当前账号没有可尝试的仓库角色'); + + for (const roleId of candidateRoleIds) { + const changeRes = await invokeSystemMethod('user.changeRole', { roleId }, currentToken, EXTRA_HEADERS); + if (changeRes.status !== 200 || changeRes.body?.flag !== 'success' || changeRes.body?.code !== 200) continue; + currentToken = changeRes.body?.data?.token || currentToken; + + const listRes = await invokeSystemMethod('storage.receiving.getReceivingList', { + pagination: { page: 1, pageSize: 1 }, + where: {}, + }, currentToken, EXTRA_HEADERS); + if (listRes.status === 200 && listRes.body?.flag === 'success' && listRes.body?.code === 200) { + return { token: currentToken, roleId }; + } + } + throw new Error(`未找到 warehouse_id=${TEST_WAREHOUSE_ID} 的仓库角色`); +} + +// ──── 获取系统商品(至少 minCount 个) ──── +async function getSystemProducts(token, minCount = 2) { + const res = await invokeSystemMethod('stock.warehouse.list', { + pagination: { page: 1, pageSize: 20 }, + where: {}, + }, token, EXTRA_HEADERS); + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + + let list = []; + if (res.body?.data?.data?.list) list = res.body.data.data.list; + else if (res.body?.data?.list) list = res.body.data.list; + + const products = list + .filter(item => Number(item?.id || 0) > 0) + .slice(0, minCount) + .map(item => ({ + id: Number(item.id), + item_name: String(item.item_name || item.name || ''), + item_code: String(item.item_code || ''), + })); + assert.ok(products.length >= minCount, `需至少 ${minCount} 个系统商品,实际只有 ${products.length} 个`); + return products; +} + +// ──── 创建收货单 ──── +async function createReceiving(token) { + const res = await invokeSystemMethod('storage.receiving.create', { + delivery_method: 'truck', + license_plate: `ITEST-MP-${Date.now().toString().slice(-6)}`, + loading_method: 'without_pallet', + remark: `matchPutaway集成测试 ${new Date().toISOString()}`, + total_boxes: 1, + total_pallets: 0, + }, token, EXTRA_HEADERS); + assert.equal(res.status, 200, `创建收货单HTTP失败: ${JSON.stringify(res.body)}`); + assert.equal(res.body.flag, 'success', `创建收货单失败: ${res.body.message}`); + const receivingId = Number(res.body.id || res.body?.data?.id || 0); + assert.ok(receivingId > 0, '创建收货单无返回ID'); + return receivingId; +} + +// ──── 绑定货主 ──── +async function bindStore(token, receivingId) { + const res = await invokeSystemMethod('storage.receiving.bindStore', { + id: receivingId, + store_id: TEST_STORE_ID, + }, token, EXTRA_HEADERS); + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success', `绑定货主失败: ${res.body.message}`); +} + +// ──── 添加明细 + 修改明细 + 绑定商品 ──── +async function addAndFillDetail(token, receivingId, product, qty) { + const addRes = await invokeSystemMethod('storage.receiving.addDetail', { + receiving_id: receivingId, + }, token, EXTRA_HEADERS); + assert.equal(addRes.status, 200, `添加明细HTTP失败: ${JSON.stringify(addRes.body)}`); + assert.equal(addRes.body.flag, 'success', `添加明细失败: ${addRes.body.message}`); + const detailId = Number(addRes.body?.data?.selectId || 0); + assert.ok(detailId > 0, `添加明细无返回selectId: ${JSON.stringify(addRes.body)}`); + + const changeRes = await invokeSystemMethod('storage.receiving.detailChange', { + id: detailId, + receiving_id: receivingId, + product_name: product.item_name || '测试商品', + barcode: product.item_code || `TEST-BC-${Date.now()}`, + actual_quantity: qty, + box_quantity: 1, + pallet_quantity: 0, + }, token, EXTRA_HEADERS); + assert.equal(changeRes.status, 200, `修改明细失败: ${JSON.stringify(changeRes.body)}`); + assert.equal(changeRes.body.flag, 'success', `修改明细失败: ${changeRes.body.message}`); + + return detailId; +} + +async function bindDetailProduct(token, detailId, productId) { + const res = await invokeSystemMethod('storage.receiving.bindDetailProduct', { + detail_id: detailId, + system_product_id: productId, + }, token, EXTRA_HEADERS); + assert.equal(res.status, 200, `绑定商品失败: ${JSON.stringify(res.body)}`); + assert.equal(res.body.flag, 'success', `绑定商品失败: ${res.body.message}`); +} + +// ──── 完成收货 ──── +async function completeReceiving(token, receivingId) { + const res = await invokeSystemMethod('storage.receiving.completeReceiving', { + id: receivingId, + }, token, EXTRA_HEADERS); + assert.equal(res.status, 200, `完成收货HTTP失败: ${JSON.stringify(res.body)}`); + assert.equal(res.body.flag, 'success', `完成收货失败: ${res.body.message}`); +} + +// ──── 创建测试入库单(直接数据库插入) ──── +async function createTestEntryOrder(sequelize, { warehouseId, storeId, items }) { + const code = `TEST-ENTRY-${Date.now()}`; + const [ results ] = await sequelize.query( + `INSERT INTO wms_entry_order (entry_order_code, order_type, total_order_lines, order_create_time, source_type, order_status, sync_status, is_enabled, warehouse_id, store_id, created_at, updated_at) + VALUES (:code, 'CGRK', :lines, NOW(), 'API', 'CREATED', 'PENDING', 1, :warehouseId, :storeId, NOW(), NOW())`, + { replacements: { code, lines: items.length, warehouseId, storeId }, type: Sequelize.QueryTypes.INSERT } + ); + const orderId = results; + + for (let i = 0; i < items.length; i++) { + await sequelize.query( + `INSERT INTO wms_entry_items (order_id, order_line_no, item_code, item_id, count, inventory_type, stock_id, received_quantity, confirm_quantity) + VALUES (:orderId, :lineNo, :itemCode, :itemId, :count, 'ZP', :stockId, 0, 0)`, + { replacements: { orderId, lineNo: i + 1, itemCode: items[i].item_code, itemId: items[i].id, count: items[i].quantity, stockId: items[i].id } } + ); + } + + return { id: orderId, code }; +} + +// ──── matchPutaway 调用 ──── +async function matchPutaway(token, receivingIds, entryOrderIds) { + return invokeSystemMethod('storage.inventory.matchPutaway', { + receiving_ids: receivingIds, + entry_order_ids: entryOrderIds, + }, token, EXTRA_HEADERS); +} + +describe('test/app/controller/system.storage.inventory.matchPutaway.test.js', () => { + let authToken; + let products; // 至少 2 个 + let sequelize; + + before(async function() { + this.timeout(30000); + const { token } = await getAuthToken(); + const switched = await switchToWarehouseRole(token); + authToken = switched.token; + products = await getSystemProducts(authToken, 2); + console.log(`[SETUP] 测试商品: ${products.map(p => `${p.item_name}(${p.id})`).join(', ')}`); + + sequelize = new Sequelize(config.database, config.username, config.password, { + host: config.host, + port: config.port, + dialect: 'mysql', + logging: false, + }); + }); + + after(async function() { + if (sequelize) { + await sequelize.close(); + console.log('[TEARDOWN] 数据库连接已关闭'); + } + }); + + // ────────────────────────────────────────────────────── + // 1. 精确匹配:收货量 = 入库计划量 + // ────────────────────────────────────────────────────── + it('should match putaway when receiving equals entry order (exact match)', async function() { + this.timeout(60000); + + const quantities = [ 10, 5 ]; + + // 1. 创建收货单 → 添加明细 → 绑定商品 → 完成收货 + const receivingId = await createReceiving(authToken); + await bindStore(authToken, receivingId); + console.log(`[EXACT] 收货单 ID: ${receivingId}`); + + for (let i = 0; i < 2; i++) { + const detailId = await addAndFillDetail(authToken, receivingId, products[i], quantities[i]); + await bindDetailProduct(authToken, detailId, products[i].id); + console.log(`[EXACT] 明细 ${i + 1}: detailId=${detailId}, product=${products[i].item_name}, qty=${quantities[i]}`); + } + await completeReceiving(authToken, receivingId); + + // 2. 创建入库单(数量与收货完全一致) + const entryOrder = await createTestEntryOrder(sequelize, { + warehouseId: TEST_WAREHOUSE_ID, + storeId: TEST_STORE_ID, + items: products.map((p, i) => ({ + id: p.id, + item_code: p.item_code, + quantity: quantities[i], + })), + }); + console.log(`[EXACT] 入库单 ID: ${entryOrder.id}, code: ${entryOrder.code}`); + + // 3. 调用 matchPutaway + const res = await matchPutaway(authToken, [ receivingId ], [ entryOrder.id ]); + console.log('[EXACT] matchPutaway 响应:', JSON.stringify(res.body, null, 2)); + + assert.equal(res.status, 200, `matchPutaway HTTP失败: ${JSON.stringify(res.body)}`); + assert.equal(res.body.flag, 'success', `matchPutaway flag失败: ${res.body.message}`); + + const resultData = res.body?.data?.data || res.body?.data || {}; + const resCode = Number(resultData.code || res.body?.code || 0); + assert.equal(resCode, 200, `matchPutaway 应返回 code=200, 实际: ${resCode}`); + + // 4. 验证收货单 storage_status=all + const detailRes = await invokeSystemMethod('storage.receiving.getReceivingDetail', { + id: receivingId, + pagination: { page: 1, pageSize: 100 }, + }, authToken, EXTRA_HEADERS); + assert.equal(detailRes.status, 200); + + const detailPayload = detailRes.body?.data?.data || detailRes.body?.data || {}; + const receivingAfter = detailPayload.receiving || {}; + console.log(`[EXACT] 收货单 storage_status: ${receivingAfter.storage_status}`); + assert.equal(receivingAfter.storage_status, 'all', `收货单应全部入库, 实际: ${receivingAfter.storage_status}`); + + // 5. 验证入库单 order_status=COMPLETED(查数据库) + const [ entryRows ] = await sequelize.query( + 'SELECT order_status FROM wms_entry_order WHERE id = :id', + { replacements: { id: entryOrder.id }, type: Sequelize.QueryTypes.SELECT } + ); + console.log(`[EXACT] 入库单 order_status: ${entryRows.order_status}`); + assert.equal(entryRows.order_status, 'COMPLETED', `入库单应已完成, 实际: ${entryRows.order_status}`); + + // 6. 验证 receiving_results + const receivingResults = resultData.receiving_results || []; + const rcvResult = receivingResults.find(r => r.receiving_id === receivingId); + assert.ok(rcvResult, '返回结果中应包含收货单信息'); + assert.equal(rcvResult.storage_status, 'all', '返回中 storage_status 应为 all'); + + // 7. 验证 entry_order_results + const entryOrderResults = resultData.entry_order_results || []; + const eoResult = entryOrderResults.find(r => r.entry_order_id === entryOrder.id); + assert.ok(eoResult, '返回结果中应包含入库单信息'); + assert.equal(eoResult.order_status, 'COMPLETED', '返回中入库单状态应为 COMPLETED'); + }); + + // ────────────────────────────────────────────────────── + // 2. 收货 > 入库计划(部分匹配,有剩余) + // ────────────────────────────────────────────────────── + it('should handle receiving > entry order (partial match with surplus)', async function() { + this.timeout(60000); + + const rcvQuantities = [ 20, 15 ]; + const entryQuantities = [ 10, 5 ]; + + // 1. 创建收货单(数量 20, 15) + const receivingId = await createReceiving(authToken); + await bindStore(authToken, receivingId); + console.log(`[SURPLUS] 收货单 ID: ${receivingId}`); + + for (let i = 0; i < 2; i++) { + const detailId = await addAndFillDetail(authToken, receivingId, products[i], rcvQuantities[i]); + await bindDetailProduct(authToken, detailId, products[i].id); + console.log(`[SURPLUS] 明细 ${i + 1}: detailId=${detailId}, product=${products[i].item_name}, rcvQty=${rcvQuantities[i]}`); + } + await completeReceiving(authToken, receivingId); + + // 2. 创建入库单(数量 10, 5 — 小于收货量) + const entryOrder = await createTestEntryOrder(sequelize, { + warehouseId: TEST_WAREHOUSE_ID, + storeId: TEST_STORE_ID, + items: products.map((p, i) => ({ + id: p.id, + item_code: p.item_code, + quantity: entryQuantities[i], + })), + }); + console.log(`[SURPLUS] 入库单 ID: ${entryOrder.id}, code: ${entryOrder.code}`); + + // 3. 调用 matchPutaway + const res = await matchPutaway(authToken, [ receivingId ], [ entryOrder.id ]); + console.log('[SURPLUS] matchPutaway 响应:', JSON.stringify(res.body, null, 2)); + + assert.equal(res.status, 200, `matchPutaway HTTP失败: ${JSON.stringify(res.body)}`); + assert.equal(res.body.flag, 'success', `matchPutaway flag失败: ${res.body.message}`); + + const resultData = res.body?.data?.data || res.body?.data || {}; + const resCode = Number(resultData.code || res.body?.code || 0); + assert.equal(resCode, 200, `matchPutaway 应返回 code=200, 实际: ${resCode}`); + + // 4. 验证收货单 storage_status=partial(只入了部分) + const detailRes = await invokeSystemMethod('storage.receiving.getReceivingDetail', { + id: receivingId, + pagination: { page: 1, pageSize: 100 }, + }, authToken, EXTRA_HEADERS); + assert.equal(detailRes.status, 200); + + const detailPayload = detailRes.body?.data?.data || detailRes.body?.data || {}; + const receivingAfter = detailPayload.receiving || {}; + console.log(`[SURPLUS] 收货单 storage_status: ${receivingAfter.storage_status}`); + assert.equal(receivingAfter.storage_status, 'partial', `收货单应为部分入库, 实际: ${receivingAfter.storage_status}`); + + // 验证各明细的 stored_quantity < actual_quantity + const detailsAfter = Array.isArray(receivingAfter.details) ? receivingAfter.details : []; + for (const d of detailsAfter) { + if (d.system_product_id) { + assert.ok(Number(d.stored_quantity) < Number(d.actual_quantity), + `明细 ${d.id}: stored(${d.stored_quantity}) 应小于 actual(${d.actual_quantity})`); + console.log(`[SURPLUS] 明细 ${d.id}: stored=${d.stored_quantity}, actual=${d.actual_quantity}, status=${d.storage_status}`); + } + } + + // 5. 验证入库单 order_status=COMPLETED(计划量全部收满) + const [ entryRows ] = await sequelize.query( + 'SELECT order_status FROM wms_entry_order WHERE id = :id', + { replacements: { id: entryOrder.id }, type: Sequelize.QueryTypes.SELECT } + ); + console.log(`[SURPLUS] 入库单 order_status: ${entryRows.order_status}`); + assert.equal(entryRows.order_status, 'COMPLETED', `入库单应已完成, 实际: ${entryRows.order_status}`); + }); + + // ────────────────────────────────────────────────────── + // 3. 收货 < 入库计划(收货不足) + // ────────────────────────────────────────────────────── + it('should handle receiving < entry order (insufficient receiving)', async function() { + this.timeout(60000); + + const rcvQuantities = [ 5, 3 ]; + const entryQuantities = [ 10, 8 ]; + + // 1. 创建收货单(数量 5, 3) + const receivingId = await createReceiving(authToken); + await bindStore(authToken, receivingId); + console.log(`[INSUF] 收货单 ID: ${receivingId}`); + + for (let i = 0; i < 2; i++) { + const detailId = await addAndFillDetail(authToken, receivingId, products[i], rcvQuantities[i]); + await bindDetailProduct(authToken, detailId, products[i].id); + console.log(`[INSUF] 明细 ${i + 1}: detailId=${detailId}, product=${products[i].item_name}, rcvQty=${rcvQuantities[i]}`); + } + await completeReceiving(authToken, receivingId); + + // 2. 创建入库单(数量 10, 8 — 大于收货量) + const entryOrder = await createTestEntryOrder(sequelize, { + warehouseId: TEST_WAREHOUSE_ID, + storeId: TEST_STORE_ID, + items: products.map((p, i) => ({ + id: p.id, + item_code: p.item_code, + quantity: entryQuantities[i], + })), + }); + console.log(`[INSUF] 入库单 ID: ${entryOrder.id}, code: ${entryOrder.code}`); + + // 3. 调用 matchPutaway + const res = await matchPutaway(authToken, [ receivingId ], [ entryOrder.id ]); + console.log('[INSUF] matchPutaway 响应:', JSON.stringify(res.body, null, 2)); + + assert.equal(res.status, 200, `matchPutaway HTTP失败: ${JSON.stringify(res.body)}`); + assert.equal(res.body.flag, 'success', `matchPutaway flag失败: ${res.body.message}`); + + const resultData = res.body?.data?.data || res.body?.data || {}; + const resCode = Number(resultData.code || res.body?.code || 0); + assert.equal(resCode, 200, `matchPutaway 应返回 code=200, 实际: ${resCode}`); + + // 4. 验证收货单 storage_status=all(收货全部入库了) + const detailRes = await invokeSystemMethod('storage.receiving.getReceivingDetail', { + id: receivingId, + pagination: { page: 1, pageSize: 100 }, + }, authToken, EXTRA_HEADERS); + assert.equal(detailRes.status, 200); + + const detailPayload = detailRes.body?.data?.data || detailRes.body?.data || {}; + const receivingAfter = detailPayload.receiving || {}; + console.log(`[INSUF] 收货单 storage_status: ${receivingAfter.storage_status}`); + assert.equal(receivingAfter.storage_status, 'all', `收货单应全部入库, 实际: ${receivingAfter.storage_status}`); + + // 5. 验证入库单 order_status=PARTIAL_RECEIVED(未全部完成) + const [ entryRows ] = await sequelize.query( + 'SELECT order_status FROM wms_entry_order WHERE id = :id', + { replacements: { id: entryOrder.id }, type: Sequelize.QueryTypes.SELECT } + ); + console.log(`[INSUF] 入库单 order_status: ${entryRows.order_status}`); + assert.equal(entryRows.order_status, 'PARTIAL_RECEIVED', `入库单应部分收货, 实际: ${entryRows.order_status}`); + + // 6. 验证 warnings 包含提示(收货量 < 入库计划量) + const warnings = resultData.warnings || []; + console.log('[INSUF] warnings:', warnings); + assert.ok(warnings.length > 0, '应包含 warnings 提示'); + const hasInsufficientWarning = warnings.some(w => + w.includes('收货可入库量') || w.includes('未全部入库完成') + ); + assert.ok(hasInsufficientWarning, `warnings 应包含收货不足或未全部完成提示, 实际: ${JSON.stringify(warnings)}`); + }); +}); diff --git a/test/app/controller/system.storage.inventory.quickPutaway.test.js b/test/app/controller/system.storage.inventory.quickPutaway.test.js new file mode 100644 index 0000000..add742b --- /dev/null +++ b/test/app/controller/system.storage.inventory.quickPutaway.test.js @@ -0,0 +1,384 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const Sequelize = require('sequelize'); +const { + getAuthToken, + invokeSystemMethod, +} = require('../../support/system_method_client'); + +const EXTRA_HEADERS = { platform: 'web', project: 'all' }; +const FALLBACK_ROLE_IDS = [ 4, 6, 30 ]; +const TEST_STORE_ID = 1000000; +const TEST_WAREHOUSE_ID = 100000; + +// ──── 数据库连接(用于锁冲突测试) ──── +const dbConfig = require('../../../database/config'); +const env = process.env.NODE_ENV || 'development'; +const config = dbConfig[env] || dbConfig.development || Object.values(dbConfig)[0]; + +// ──── switchToWarehouseRole ──── +async function switchToWarehouseRole(token) { + let currentToken = token; + const infoRes = await invokeSystemMethod('user.info', {}, currentToken, EXTRA_HEADERS); + assert.equal(infoRes.status, 200); + assert.equal(infoRes.body.flag, 'success'); + + const employees = Array.isArray(infoRes.body?.data?.employees) ? infoRes.body.data.employees : []; + const warehouseRoles = employees.filter(item => + item && item.role_type === 'warehouse' && Number(item.id) && + Number(item.store_id) === TEST_WAREHOUSE_ID + ); + const candidateRoleIds = [ ...new Set([ + ...warehouseRoles.map(item => Number(item.id)), + ...FALLBACK_ROLE_IDS, + ].filter(Boolean)) ]; + assert.ok(candidateRoleIds.length > 0, '当前账号没有可尝试的仓库角色'); + + for (const roleId of candidateRoleIds) { + const changeRes = await invokeSystemMethod('user.changeRole', { roleId }, currentToken, EXTRA_HEADERS); + if (changeRes.status !== 200 || changeRes.body?.flag !== 'success' || changeRes.body?.code !== 200) continue; + currentToken = changeRes.body?.data?.token || currentToken; + + const listRes = await invokeSystemMethod('storage.receiving.getReceivingList', { + pagination: { page: 1, pageSize: 1 }, + where: {}, + }, currentToken, EXTRA_HEADERS); + if (listRes.status === 200 && listRes.body?.flag === 'success' && listRes.body?.code === 200) { + return { token: currentToken, roleId }; + } + } + throw new Error(`未找到 warehouse_id=${TEST_WAREHOUSE_ID} 的仓库角色`); +} + +// ──── 获取系统商品(至少 minCount 个) ──── +async function getSystemProducts(token, minCount = 2) { + const res = await invokeSystemMethod('stock.warehouse.list', { + pagination: { page: 1, pageSize: 20 }, + where: {}, + }, token, EXTRA_HEADERS); + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + + let list = []; + if (res.body?.data?.data?.list) list = res.body.data.data.list; + else if (res.body?.data?.list) list = res.body.data.list; + + const products = list + .filter(item => Number(item?.id || 0) > 0) + .slice(0, minCount) + .map(item => ({ + id: Number(item.id), + item_name: String(item.item_name || item.name || ''), + item_code: String(item.item_code || ''), + })); + assert.ok(products.length >= minCount, `需至少 ${minCount} 个系统商品,实际只有 ${products.length} 个`); + return products; +} + +// ──── 创建收货单 ──── +async function createReceiving(token) { + const res = await invokeSystemMethod('storage.receiving.create', { + delivery_method: 'truck', + license_plate: `ITEST-QP-${Date.now().toString().slice(-6)}`, + loading_method: 'without_pallet', + remark: `quickPutaway集成测试 ${new Date().toISOString()}`, + total_boxes: 1, + total_pallets: 0, + }, token, EXTRA_HEADERS); + assert.equal(res.status, 200, `创建收货单HTTP失败: ${JSON.stringify(res.body)}`); + assert.equal(res.body.flag, 'success', `创建收货单失败: ${res.body.message}`); + const receivingId = Number(res.body.id || res.body?.data?.id || 0); + assert.ok(receivingId > 0, '创建收货单无返回ID'); + return receivingId; +} + +// ──── 绑定货主 ──── +async function bindStore(token, receivingId) { + const res = await invokeSystemMethod('storage.receiving.bindStore', { + id: receivingId, + store_id: TEST_STORE_ID, + }, token, EXTRA_HEADERS); + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success', `绑定货主失败: ${res.body.message}`); +} + +// ──── 添加明细 + 修改明细 + 绑定商品 ──── +async function addAndFillDetail(token, receivingId, product, qty) { + // addDetail + const addRes = await invokeSystemMethod('storage.receiving.addDetail', { + receiving_id: receivingId, + }, token, EXTRA_HEADERS); + assert.equal(addRes.status, 200, `添加明细HTTP失败: ${JSON.stringify(addRes.body)}`); + assert.equal(addRes.body.flag, 'success', `添加明细失败: ${addRes.body.message}`); + const detailId = Number(addRes.body?.data?.selectId || 0); + assert.ok(detailId > 0, `添加明细无返回selectId: ${JSON.stringify(addRes.body)}`); + + // detailChange + const changeRes = await invokeSystemMethod('storage.receiving.detailChange', { + id: detailId, + receiving_id: receivingId, + product_name: product.item_name || '测试商品', + barcode: product.item_code || `TEST-BC-${Date.now()}`, + actual_quantity: qty, + box_quantity: 1, + pallet_quantity: 0, + }, token, EXTRA_HEADERS); + assert.equal(changeRes.status, 200, `修改明细失败: ${JSON.stringify(changeRes.body)}`); + assert.equal(changeRes.body.flag, 'success', `修改明细失败: ${changeRes.body.message}`); + + return detailId; +} + +async function bindDetailProduct(token, detailId, productId) { + const res = await invokeSystemMethod('storage.receiving.bindDetailProduct', { + detail_id: detailId, + system_product_id: productId, + }, token, EXTRA_HEADERS); + assert.equal(res.status, 200, `绑定商品失败: ${JSON.stringify(res.body)}`); + assert.equal(res.body.flag, 'success', `绑定商品失败: ${res.body.message}`); +} + +// ──── 完成收货 ──── +async function completeReceiving(token, receivingId) { + const res = await invokeSystemMethod('storage.receiving.completeReceiving', { + id: receivingId, + }, token, EXTRA_HEADERS); + assert.equal(res.status, 200, `完成收货HTTP失败: ${JSON.stringify(res.body)}`); + assert.equal(res.body.flag, 'success', `完成收货失败: ${res.body.message}`); +} + +// ──── 快捷入库 ──── +async function quickPutaway(token, receivingId) { + return invokeSystemMethod('storage.inventory.quickPutaway', { + receiving_id: receivingId, + }, token, EXTRA_HEADERS); +} + +describe('test/app/controller/system.storage.inventory.quickPutaway.test.js', () => { + let authToken; + let products; // 至少 3 个 + + before(async function() { + this.timeout(30000); + const { token } = await getAuthToken(); + const switched = await switchToWarehouseRole(token); + authToken = switched.token; + products = await getSystemProducts(authToken, 3); + console.log(`[SETUP] 测试商品: ${products.map(p => `${p.item_name}(${p.id})`).join(', ')}`); + }); + + // ────────────────────────────────────────────────────── + // 1. 部分匹配拒绝 + // ────────────────────────────────────────────────────── + it('should reject quickPutaway for partially matched receiving', async function() { + this.timeout(60000); + + const receivingId = await createReceiving(authToken); + await bindStore(authToken, receivingId); + console.log(`[PARTIAL] 收货单 ID: ${receivingId}`); + + // 添加 3 条明细 + const detailIds = []; + const quantities = [ 5, 3, 2 ]; + for (let i = 0; i < 3; i++) { + const detailId = await addAndFillDetail(authToken, receivingId, products[i], quantities[i]); + detailIds.push(detailId); + console.log(`[PARTIAL] 明细 ${i + 1}: detailId=${detailId}, product=${products[i].item_name}`); + } + + // 只绑定前 2 条,第 3 条不绑定 + await bindDetailProduct(authToken, detailIds[0], products[0].id); + await bindDetailProduct(authToken, detailIds[1], products[1].id); + console.log('[PARTIAL] 只绑定了 2/3 条明细的商品'); + + // 完成收货 + await completeReceiving(authToken, receivingId); + + // 快捷入库 → 应被拒绝 + const res = await quickPutaway(authToken, receivingId); + console.log('[PARTIAL] quickPutaway 响应:', JSON.stringify(res.body, null, 2)); + + const resCode = Number(res.body?.data?.code || res.body?.code || 0); + assert.equal(resCode, 400, `部分匹配应返回 400, 实际: ${resCode}`); + const message = String(res.body?.data?.message || res.body?.message || ''); + assert.ok(message.includes('未匹配'), `message 应包含"未匹配", 实际: ${message}`); + }); + + // ────────────────────────────────────────────────────── + // 2. 全匹配成功 + // ────────────────────────────────────────────────────── + it('should complete quickPutaway for fully matched receiving', async function() { + this.timeout(60000); + + const receivingId = await createReceiving(authToken); + await bindStore(authToken, receivingId); + console.log(`[FULL] 收货单 ID: ${receivingId}`); + + // 添加 2 条明细,全部绑定商品 + const detailIds = []; + const quantities = [ 10, 5 ]; + for (let i = 0; i < 2; i++) { + const detailId = await addAndFillDetail(authToken, receivingId, products[i], quantities[i]); + detailIds.push(detailId); + await bindDetailProduct(authToken, detailId, products[i].id); + console.log(`[FULL] 明细 ${i + 1}: detailId=${detailId}, product=${products[i].item_name}, qty=${quantities[i]}`); + } + + // 完成收货 + await completeReceiving(authToken, receivingId); + + // 快捷入库 + const res = await quickPutaway(authToken, receivingId); + console.log('[FULL] quickPutaway 响应:', JSON.stringify(res.body, null, 2)); + + assert.equal(res.status, 200, `快捷入库HTTP失败: ${JSON.stringify(res.body)}`); + assert.equal(res.body.flag, 'success', `快捷入库flag失败: ${res.body.message}`); + + const putawayData = res.body?.data?.data || res.body?.data || {}; + assert.ok(putawayData.entry_order, '返回中缺少 entry_order'); + assert.ok(putawayData.entry_order.id, '返回中缺少 entry_order.id'); + assert.ok(putawayData.entry_order.entry_order_code, '返回中缺少 entry_order_code'); + assert.ok(Array.isArray(putawayData.items), '返回中缺少 items 数组'); + assert.ok(putawayData.items.length > 0, 'items 数组为空'); + + // 验证 storage_status + for (const item of putawayData.items) { + assert.ok(item.storage_status, 'item 缺少 storage_status'); + } + + console.log(`[FULL] 入库单号: ${putawayData.entry_order.entry_order_code}, 明细数: ${putawayData.items.length}`); + + // 验证收货单明细入库状态 + const detailRes = await invokeSystemMethod('storage.receiving.getReceivingDetail', { + id: receivingId, + pagination: { page: 1, pageSize: 100 }, + }, authToken, EXTRA_HEADERS); + assert.equal(detailRes.status, 200); + + const detailPayload = detailRes.body?.data?.data || detailRes.body?.data || {}; + const receivingAfter = detailPayload.receiving || {}; + const detailsAfter = Array.isArray(receivingAfter.details) ? receivingAfter.details : []; + + for (const d of detailsAfter) { + assert.equal(d.storage_status, 'all', `明细 ${d.id} 应全部入库, 实际: ${d.storage_status}`); + assert.equal(Number(d.stored_quantity), Number(d.actual_quantity), + `明细 ${d.id} stored_quantity(${d.stored_quantity}) 应等于 actual_quantity(${d.actual_quantity})`); + console.log(`[FULL] 明细 ${d.id}: stored=${d.stored_quantity}, actual=${d.actual_quantity}, status=${d.storage_status}`); + } + + // 重复入库应被拒绝 + const repeatRes = await quickPutaway(authToken, receivingId); + console.log('[FULL] 重复入库响应:', JSON.stringify(repeatRes.body, null, 2)); + const repeatCode = Number(repeatRes.body?.data?.code || repeatRes.body?.code || 0); + assert.equal(repeatCode, 400, `重复入库应返回 400, 实际: ${repeatCode}`); + }); + + // ────────────────────────────────────────────────────── + // 3. 数据库行锁冲突 → 409 + // ────────────────────────────────────────────────────── + it('should return 409 when stock row is locked by concurrent transaction', async function() { + this.timeout(120000); + + const productId = products[0].id; + console.log(`[LOCK] 测试商品 ID: ${productId}`); + console.log('[LOCK] 注意:本测试需等待服务端锁超时(约50秒),请耐心等待'); + + const sequelize = new Sequelize(config.database, config.username, config.password, { + host: config.host, + port: config.port, + dialect: 'mysql', + logging: false, + }); + + let lockTx; + try { + // 先准备好收货单数据 + const receivingId = await createReceiving(authToken); + await bindStore(authToken, receivingId); + const detailId = await addAndFillDetail(authToken, receivingId, products[0], 1); + await bindDetailProduct(authToken, detailId, products[0].id); + await completeReceiving(authToken, receivingId); + + // 开事务锁行 + lockTx = await sequelize.transaction(); + await sequelize.query( + 'SELECT * FROM wms_stock_warehouse WHERE id = :productId FOR UPDATE', + { replacements: { productId }, transaction: lockTx } + ); + console.log(`[LOCK] 已锁定 wms_stock_warehouse.id = ${productId}`); + + // 安全网:70秒后自动释放(确保超过服务端默认50秒锁等待) + const releaseTimer = setTimeout(async () => { + try { await lockTx.rollback(); } catch (_) { + console.log('错误中断'); + } + }, 70000); + + // 调 quickPutaway —— 服务端会等50秒左右才超时返回409 + const startTime = Date.now(); + const res = await quickPutaway(authToken, receivingId); + const elapsed = Math.round((Date.now() - startTime) / 1000); + console.log(`[LOCK] quickPutaway 响应 (耗时 ${elapsed}s):`, JSON.stringify(res.body, null, 2)); + + const resCode = Number(res.body?.data?.code || res.body?.code || 0); + assert.equal(resCode, 409, `锁冲突应返回 409, 实际: ${resCode}`); + const message = String(res.body?.data?.message || res.body?.message || ''); + assert.ok(message.includes('锁定'), `message 应包含"锁定", 实际: ${message}`); + + clearTimeout(releaseTimer); + } finally { + try { if (lockTx) await lockTx.rollback(); } catch (_) { + console.log('错误中断'); + } + await sequelize.close(); + console.log('[LOCK] 数据库连接已关闭'); + } + }); + + // ────────────────────────────────────────────────────── + // 4. 无锁冲突正常入库 + // ────────────────────────────────────────────────────── + it('should complete quickPutaway without lock contention', async function() { + this.timeout(60000); + + const receivingId = await createReceiving(authToken); + await bindStore(authToken, receivingId); + console.log(`[NOLOCK] 收货单 ID: ${receivingId}`); + + // 添加 2 条明细,全部绑定 + const detailIds = []; + const quantities = [ 8, 4 ]; + for (let i = 0; i < 2; i++) { + const detailId = await addAndFillDetail(authToken, receivingId, products[i], quantities[i]); + detailIds.push(detailId); + await bindDetailProduct(authToken, detailId, products[i].id); + console.log(`[NOLOCK] 明细 ${i + 1}: detailId=${detailId}, product=${products[i].item_name}, qty=${quantities[i]}`); + } + + // 完成收货 → 快捷入库 + await completeReceiving(authToken, receivingId); + const res = await quickPutaway(authToken, receivingId); + console.log('[NOLOCK] quickPutaway 响应:', JSON.stringify(res.body, null, 2)); + + assert.equal(res.status, 200, `快捷入库HTTP失败: ${JSON.stringify(res.body)}`); + assert.equal(res.body.flag, 'success', `快捷入库flag失败: ${res.body.message}`); + + const putawayData = res.body?.data?.data || res.body?.data || {}; + assert.ok(putawayData.entry_order, '返回中缺少 entry_order'); + assert.ok(putawayData.entry_order.id, '返回中缺少 entry_order.id'); + assert.ok(Array.isArray(putawayData.items), '返回中缺少 items 数组'); + assert.ok(putawayData.items.length === 2, `items 数量应为 2, 实际: ${putawayData.items.length}`); + + console.log(`[NOLOCK] 入库单号: ${putawayData.entry_order.entry_order_code}`); + console.log(`[NOLOCK] 入库明细数: ${putawayData.items.length}`); + + // 验证入库结果 + for (const item of putawayData.items) { + assert.ok(item.detail_id, 'item 缺少 detail_id'); + assert.ok(item.stock_warehouse_id, 'item 缺少 stock_warehouse_id'); + assert.ok(item.inbound_quantity > 0, 'inbound_quantity 应大于 0'); + console.log(`[NOLOCK] 明细 ${item.detail_id}: 入库 ${item.inbound_quantity}, 状态 ${item.storage_status}`); + } + }); +}); diff --git a/test/app/controller/system.storage.transaction.test.js b/test/app/controller/system.storage.transaction.test.js new file mode 100644 index 0000000..30f20df --- /dev/null +++ b/test/app/controller/system.storage.transaction.test.js @@ -0,0 +1,306 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const Sequelize = require('sequelize'); +const { + getAuthToken, + invokeSystemMethod, +} = require('../../support/system_method_client'); + +const EXTRA_HEADERS = { platform: 'web', project: 'all' }; +const FALLBACK_ROLE_IDS = [ 4, 6, 30 ]; +const TEST_STORE_ID = 1000000; +const TEST_WAREHOUSE_ID = 100000; + +// ──── 数据库连接 ──── +const dbConfig = require('../../../database/config'); +const env = process.env.NODE_ENV || 'development'; +const config = dbConfig[env] || dbConfig.development || Object.values(dbConfig)[0]; + +// ──── switchToWarehouseRole ──── +async function switchToWarehouseRole(token) { + let currentToken = token; + const infoRes = await invokeSystemMethod('user.info', {}, currentToken, EXTRA_HEADERS); + assert.equal(infoRes.status, 200); + assert.equal(infoRes.body.flag, 'success'); + + const employees = Array.isArray(infoRes.body?.data?.employees) ? infoRes.body.data.employees : []; + const warehouseRoles = employees.filter(item => + item && item.role_type === 'warehouse' && Number(item.id) && + Number(item.store_id) === TEST_WAREHOUSE_ID + ); + const candidateRoleIds = [ ...new Set([ + ...warehouseRoles.map(item => Number(item.id)), + ...FALLBACK_ROLE_IDS, + ].filter(Boolean)) ]; + assert.ok(candidateRoleIds.length > 0, '当前账号没有可尝试的仓库角色'); + + for (const roleId of candidateRoleIds) { + const changeRes = await invokeSystemMethod('user.changeRole', { roleId }, currentToken, EXTRA_HEADERS); + if (changeRes.status !== 200 || changeRes.body?.flag !== 'success' || changeRes.body?.code !== 200) continue; + currentToken = changeRes.body?.data?.token || currentToken; + + const listRes = await invokeSystemMethod('storage.receiving.getReceivingList', { + pagination: { page: 1, pageSize: 1 }, + where: {}, + }, currentToken, EXTRA_HEADERS); + if (listRes.status === 200 && listRes.body?.flag === 'success' && listRes.body?.code === 200) { + return { token: currentToken, roleId }; + } + } + throw new Error(`未找到 warehouse_id=${TEST_WAREHOUSE_ID} 的仓库角色`); +} + +// ──── 获取系统商品 ──── +async function getSystemProducts(token, minCount = 2) { + const res = await invokeSystemMethod('stock.warehouse.list', { + pagination: { page: 1, pageSize: 20 }, + where: {}, + }, token, EXTRA_HEADERS); + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + + let list = []; + if (res.body?.data?.data?.list) list = res.body.data.data.list; + else if (res.body?.data?.list) list = res.body.data.list; + + const products = list + .filter(item => Number(item?.id || 0) > 0) + .slice(0, minCount) + .map(item => ({ + id: Number(item.id), + item_name: String(item.item_name || item.name || ''), + item_code: String(item.item_code || ''), + })); + assert.ok(products.length >= minCount, `需至少 ${minCount} 个系统商品,实际只有 ${products.length} 个`); + return products; +} + +// ──── 创建收货单 ──── +async function createReceiving(token) { + const res = await invokeSystemMethod('storage.receiving.create', { + delivery_method: 'truck', + license_plate: `ITEST-TX-${Date.now().toString().slice(-6)}`, + loading_method: 'without_pallet', + remark: `transaction集成测试 ${new Date().toISOString()}`, + total_boxes: 1, + total_pallets: 0, + }, token, EXTRA_HEADERS); + assert.equal(res.status, 200, `创建收货单HTTP失败: ${JSON.stringify(res.body)}`); + assert.equal(res.body.flag, 'success', `创建收货单失败: ${res.body.message}`); + const receivingId = Number(res.body.id || res.body?.data?.id || 0); + assert.ok(receivingId > 0, '创建收货单无返回ID'); + return receivingId; +} + +// ──── 绑定货主 ──── +async function bindStore(token, receivingId) { + const res = await invokeSystemMethod('storage.receiving.bindStore', { + id: receivingId, + store_id: TEST_STORE_ID, + }, token, EXTRA_HEADERS); + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success', `绑定货主失败: ${res.body.message}`); +} + +// ──── 添加明细 + 修改明细 ──── +async function addAndFillDetail(token, receivingId, product, qty) { + const addRes = await invokeSystemMethod('storage.receiving.addDetail', { + receiving_id: receivingId, + }, token, EXTRA_HEADERS); + assert.equal(addRes.status, 200, `添加明细HTTP失败: ${JSON.stringify(addRes.body)}`); + assert.equal(addRes.body.flag, 'success', `添加明细失败: ${addRes.body.message}`); + const detailId = Number(addRes.body?.data?.selectId || 0); + assert.ok(detailId > 0, `添加明细无返回selectId: ${JSON.stringify(addRes.body)}`); + + const changeRes = await invokeSystemMethod('storage.receiving.detailChange', { + id: detailId, + receiving_id: receivingId, + product_name: product.item_name || '测试商品', + barcode: product.item_code || `TEST-BC-${Date.now()}`, + actual_quantity: qty, + box_quantity: 1, + pallet_quantity: 0, + }, token, EXTRA_HEADERS); + assert.equal(changeRes.status, 200, `修改明细失败: ${JSON.stringify(changeRes.body)}`); + assert.equal(changeRes.body.flag, 'success', `修改明细失败: ${changeRes.body.message}`); + + return detailId; +} + +async function bindDetailProduct(token, detailId, productId) { + const res = await invokeSystemMethod('storage.receiving.bindDetailProduct', { + detail_id: detailId, + system_product_id: productId, + }, token, EXTRA_HEADERS); + assert.equal(res.status, 200, `绑定商品失败: ${JSON.stringify(res.body)}`); + assert.equal(res.body.flag, 'success', `绑定商品失败: ${res.body.message}`); +} + +// ──── 完成收货 ──── +async function completeReceiving(token, receivingId) { + const res = await invokeSystemMethod('storage.receiving.completeReceiving', { + id: receivingId, + }, token, EXTRA_HEADERS); + assert.equal(res.status, 200, `完成收货HTTP失败: ${JSON.stringify(res.body)}`); + assert.equal(res.body.flag, 'success', `完成收货失败: ${res.body.message}`); +} + +// ──── 快捷入库 ──── +async function quickPutaway(token, receivingId) { + return invokeSystemMethod('storage.inventory.quickPutaway', { + receiving_id: receivingId, + }, token, EXTRA_HEADERS); +} + +describe('test/app/controller/system.storage.transaction.test.js', () => { + let authToken; + let products; + let sequelize; + + before(async function() { + this.timeout(30000); + const { token } = await getAuthToken(); + const switched = await switchToWarehouseRole(token); + authToken = switched.token; + products = await getSystemProducts(authToken, 2); + + sequelize = new Sequelize(config.database, config.username, config.password, { + host: config.host, + port: config.port, + dialect: 'mysql', + logging: false, + }); + + console.log(`[SETUP] 测试商品: ${products.map(p => `${p.item_name}(${p.id})`).join(', ')}`); + }); + + after(async function() { + if (sequelize) { + await sequelize.close(); + console.log('[TEARDOWN] 数据库连接已关闭'); + } + }); + + // ────────────────────────────────────────────────────── + // 用例 1:快捷入库后 wms_stock_transaction 记录验证 + // ────────────────────────────────────────────────────── + it('should write INBOUND/SCRK records to wms_stock_transaction after quickPutaway', async function() { + this.timeout(60000); + + // === 准备阶段 === + const receivingId = await createReceiving(authToken); + await bindStore(authToken, receivingId); + console.log(`[TX] 收货单 ID: ${receivingId}`); + + const quantities = [ 7, 3 ]; + const detailIds = []; + for (let i = 0; i < 2; i++) { + const detailId = await addAndFillDetail(authToken, receivingId, products[i], quantities[i]); + detailIds.push(detailId); + await bindDetailProduct(authToken, detailId, products[i].id); + console.log(`[TX] 明细 ${i + 1}: detailId=${detailId}, product=${products[i].item_name}(${products[i].id}), qty=${quantities[i]}`); + } + + await completeReceiving(authToken, receivingId); + + // 记录入库前的 transaction 最大 ID,用于过滤 + const [ beforeRows ] = await sequelize.query( + 'SELECT COALESCE(MAX(id), 0) AS max_id FROM wms_stock_transaction' + ); + const beforeMaxId = Number(beforeRows[0].max_id); + console.log(`[TX] 入库前 wms_stock_transaction max_id: ${beforeMaxId}`); + + // === 执行入库 === + const res = await quickPutaway(authToken, receivingId); + console.log('[TX] quickPutaway 响应:', JSON.stringify(res.body, null, 2)); + + assert.equal(res.status, 200, `快捷入库HTTP失败: ${JSON.stringify(res.body)}`); + assert.equal(res.body.flag, 'success', `快捷入库flag失败: ${res.body.message}`); + + const putawayData = res.body?.data?.data || res.body?.data || {}; + assert.ok(putawayData.entry_order, '返回中缺少 entry_order'); + const entryOrderId = putawayData.entry_order.id; + const entryOrderCode = putawayData.entry_order.entry_order_code; + console.log(`[TX] 入库单: id=${entryOrderId}, code=${entryOrderCode}`); + + // === 断言:查询 wms_stock_transaction 新增记录 === + const [ txRows ] = await sequelize.query( + 'SELECT * FROM wms_stock_transaction WHERE id > :beforeMaxId AND receiving_id = :receivingId ORDER BY id ASC', + { replacements: { beforeMaxId, receivingId } } + ); + console.log(`[TX] 新增 transaction 记录数: ${txRows.length}`); + for (const row of txRows) { + console.log(`[TX] record id=${row.id}: type=${row.transaction_type}, order_type=${row.order_type}, stock_id=${row.stock_id}, qty=${row.quantity}, entry_order_id=${row.entry_order_id}, warehouse_id=${row.warehouse_id}, store_id=${row.store_id}`); + } + + // 1. 应至少有 2 条记录(每条明细一条) + assert.ok(txRows.length >= 2, `应至少有 2 条 transaction 记录, 实际: ${txRows.length}`); + + // 2. 逐条验证字段 + for (let i = 0; i < txRows.length; i++) { + const row = txRows[i]; + + // transaction_type + assert.equal(row.transaction_type, 'INBOUND', + `record ${row.id}: transaction_type 应为 INBOUND, 实际: ${row.transaction_type}`); + + // order_type + assert.equal(row.order_type, 'SCRK', + `record ${row.id}: order_type 应为 SCRK, 实际: ${row.order_type}`); + + // quantity > 0 + assert.ok(Number(row.quantity) > 0, + `record ${row.id}: quantity 应 > 0, 实际: ${row.quantity}`); + + // stock_id > 0 + assert.ok(Number(row.stock_id) > 0, + `record ${row.id}: stock_id 应 > 0, 实际: ${row.stock_id}`); + + // warehouse_id + assert.equal(Number(row.warehouse_id), TEST_WAREHOUSE_ID, + `record ${row.id}: warehouse_id 应为 ${TEST_WAREHOUSE_ID}, 实际: ${row.warehouse_id}`); + + // entry_order_id 不为空 + assert.ok(Number(row.entry_order_id) > 0, + `record ${row.id}: entry_order_id 应 > 0, 实际: ${row.entry_order_id}`); + + // entry_order_id 与返回一致 + assert.equal(Number(row.entry_order_id), Number(entryOrderId), + `record ${row.id}: entry_order_id(${row.entry_order_id}) 应等于返回值(${entryOrderId})`); + + // receiving_id 与传入一致 + assert.equal(Number(row.receiving_id), Number(receivingId), + `record ${row.id}: receiving_id(${row.receiving_id}) 应等于 ${receivingId}`); + + // order_no 不为空 + assert.ok(row.order_no && row.order_no.length > 0, + `record ${row.id}: order_no 不应为空`); + + // order_no 与返回的 entry_order_code 一致 + assert.equal(row.order_no, entryOrderCode, + `record ${row.id}: order_no(${row.order_no}) 应等于 ${entryOrderCode}`); + + // store_id > 0 + assert.ok(Number(row.store_id) > 0, + `record ${row.id}: store_id 应 > 0, 实际: ${row.store_id}`); + } + + // 3. 验证入库数量与明细匹配 + // 按 stock_id 分组,对比预期数量 + for (let i = 0; i < products.length; i++) { + const stockId = products[i].id; + const expectedQty = quantities[i]; + const matchingRow = txRows.find(r => Number(r.stock_id) === stockId); + if (matchingRow) { + assert.equal(Number(matchingRow.quantity), expectedQty, + `stock_id=${stockId}: quantity(${matchingRow.quantity}) 应等于 ${expectedQty}`); + console.log(`[TX] ✓ stock_id=${stockId} 数量匹配: ${matchingRow.quantity} === ${expectedQty}`); + } else { + console.log(`[TX] ⚠ stock_id=${stockId} 未找到对应 transaction 记录(可能 stock_warehouse.id 不等于传入 product.id)`); + } + } + + console.log(`[TX] ✓ 全部断言通过,共 ${txRows.length} 条 INBOUND/SCRK 记录`); + }); +}); diff --git a/test/app/controller/system.storeWarehouse.test.js b/test/app/controller/system.storeWarehouse.test.js index b948613..fed081b 100644 --- a/test/app/controller/system.storeWarehouse.test.js +++ b/test/app/controller/system.storeWarehouse.test.js @@ -14,6 +14,18 @@ const EXTRA_HEADERS = { describe('test/app/controller/system.storeWarehouse.test.js', () => { const METHOD_PREFIX = 'storeWarehouse.store'; const REMOVED_SETTING_METHOD_PREFIX = 'setting.storeWarehouse.store'; + const REMOVED_SETTING_SNAKE_METHOD_PREFIX = 'setting.store_warehouse'; + const REMOVED_LEGACY_METHODS = [ + 'list', + 'sign', + 'rename', + 'unbind', + 'getPolicyConfig', + 'getPolicyConfigFields', + 'savePolicyConfig', + 'deleteQimenConfig', + ]; + const REMOVED_COMPAT_SETTING_METHODS = [ 'list', 'sign', 'rename', 'unbind' ]; let token = ''; before(async () => { @@ -31,9 +43,31 @@ describe('test/app/controller/system.storeWarehouse.test.js', () => { assert.equal(res.body.flag, 'success'); assert.equal(res.body.code, 200); assert.ok(Array.isArray(res.body?.data?.list), 'storeWarehouse.store.list 应返回 list'); + if (res.body.data.list.length > 0) { + assert.ok(!Object.prototype.hasOwnProperty.call(res.body.data.list[0], 'apiConfig'), '首项不应包含 apiConfig 字段'); + assert.ok(!Object.prototype.hasOwnProperty.call(res.body.data.list[0], 'api_config'), '首项不应包含 api_config 字段'); + assert.ok(!Object.prototype.hasOwnProperty.call(res.body.data.list[0], 'qimenConfig'), '首项不应包含 qimenConfig 字段'); + } assert.equal(typeof res.body?.data?.total, 'number'); }); + it('should not expose removed legacy storeWarehouse.* methods', async () => { + for (const methodName of REMOVED_LEGACY_METHODS) { + const removedRes = await invokeSystemMethod(`storeWarehouse.${methodName}`, { + page: 1, + page_size: 10, + }, token, EXTRA_HEADERS); + + assert.equal(removedRes.status, 500, `legacy method ${methodName} should fail`); + assert.equal(removedRes.body.flag, 'failure'); + assert.equal(Number(removedRes.body.code), 500); + assert.match( + String(removedRes.body.message || ''), + new RegExp(`服务 storeWarehouse 不存在|方法 ${methodName} 不存在`) + ); + } + }); + it('should not expose removed setting.storeWarehouse.store.list alias', async () => { const removedRes = await invokeSystemMethod(`${REMOVED_SETTING_METHOD_PREFIX}.list`, { page: 1, @@ -46,6 +80,20 @@ describe('test/app/controller/system.storeWarehouse.test.js', () => { assert.match(String(removedRes.body.message || ''), /服务 setting\.storeWarehouse\.store 不存在/); }); + it('should not expose removed setting.store_warehouse.* compatibility methods', async () => { + for (const methodName of REMOVED_COMPAT_SETTING_METHODS) { + const removedRes = await invokeSystemMethod(`${REMOVED_SETTING_SNAKE_METHOD_PREFIX}.${methodName}`, { + page: 1, + page_size: 10, + }, token, EXTRA_HEADERS); + + assert.equal(removedRes.status, 500, `compat setting.store_warehouse.${methodName} should fail`); + assert.equal(removedRes.body.flag, 'failure'); + assert.equal(Number(removedRes.body.code), 500); + assert.match(String(removedRes.body.message || ''), /服务 setting\.store_warehouse 不存在|方法 .* 不存在/); + } + }); + it('should expose standalone storeWarehouse.store.sign parameter validation', async () => { const res = await invokeSystemMethod(`${METHOD_PREFIX}.sign`, { print_quantity: 0, @@ -75,6 +123,24 @@ describe('test/app/controller/system.storeWarehouse.test.js', () => { assert.match(String(res.body.message || ''), /remask|id|counterparty_id|store_id|warehouse_id/); }); + it('should expose standalone storeWarehouse.store.adjustPrintQuantity with auth or validation response', async () => { + const res = await invokeSystemMethod(`${METHOD_PREFIX}.adjustPrintQuantity`, { + change_quantity: 1, + }, token, EXTRA_HEADERS); + + assert.notEqual(res.status, 500, '新接口不应是未注册或方法不存在'); + + if (res.status === 403) { + assert.match(String(res.body?.message || ''), /无权访问|未授权|权限/); + return; + } + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'failure'); + assert.ok([ 400, 403, 404 ].includes(Number(res.body.code))); + assert.match(String(res.body.message || ''), /reason|id|counterparty_id|store_id|warehouse_id|无权访问|不存在/); + }); + it('should expose standalone storeWarehouse.store.getPolicyConfig parameter validation', async () => { const res = await invokeSystemMethod(`${METHOD_PREFIX}.getPolicyConfig`, {}, token, EXTRA_HEADERS); @@ -84,6 +150,26 @@ describe('test/app/controller/system.storeWarehouse.test.js', () => { assert.match(String(res.body.message || ''), /id|counterparty_id|store_id|warehouse_id/); }); + it('should expose standalone storeWarehouse.store.getPolicyConfigFields as a metadata list', async () => { + const res = await invokeSystemMethod(`${METHOD_PREFIX}.getPolicyConfigFields`, {}, token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + assert.equal(Number(res.body.code), 200); + assert.ok(Array.isArray(res.body?.data), '字段信息接口应直接返回列表'); + assert.ok(res.body.data.length > 0, '字段信息列表不能为空'); + assert.ok(res.body.data.every(item => item && typeof item === 'object' && item.key && item.name && item.type), '每个字段项都应包含 key/name/type'); + + const printRechargePriceField = res.body.data.find(item => item.key === 'print_recharge_price'); + assert.ok(printRechargePriceField, '字段信息应包含 print_recharge_price'); + assert.equal(printRechargePriceField.name, '面单充值元/单'); + assert.equal(printRechargePriceField.type, 'number'); + assert.equal(Number(printRechargePriceField.default || 0), 0); + assert.equal(Number(printRechargePriceField.precision), 2); + assert.equal(Number(printRechargePriceField.step), 0.01); + assert.match(String(printRechargePriceField.description || ''), /支持\s*2\s*位小数/); + }); + it('should expose standalone storeWarehouse.store.savePolicyConfig parameter validation', async () => { const res = await invokeSystemMethod(`${METHOD_PREFIX}.savePolicyConfig`, {}, token, EXTRA_HEADERS); @@ -93,13 +179,13 @@ describe('test/app/controller/system.storeWarehouse.test.js', () => { assert.match(String(res.body.message || ''), /id|counterparty_id|store_id|warehouse_id/); }); - it('should expose standalone storeWarehouse.store.saveQimenConfig parameter validation', async () => { - const res = await invokeSystemMethod(`${METHOD_PREFIX}.saveQimenConfig`, {}, token, EXTRA_HEADERS); + it('should expose standalone storeWarehouse.store.saveApiConfig parameter validation', async () => { + const res = await invokeSystemMethod(`${METHOD_PREFIX}.saveApiConfig`, {}, token, EXTRA_HEADERS); assert.equal(res.status, 200); assert.equal(res.body.flag, 'failure'); assert.equal(Number(res.body.code), 400); - assert.match(String(res.body.message || ''), /id|counterparty_id|store_id|warehouse_id|qimen_app_key|qimen_customer_id|qimen_warehouse_code/); + assert.match(String(res.body.message || ''), /interface_type_id|id|counterparty_id|store_id|warehouse_id|qimen_app_key|qimen_customer_id|qimen_warehouse_code/); }); it('should expose standalone storeWarehouse.store.deleteQimenConfig parameter validation', async () => { @@ -111,8 +197,8 @@ describe('test/app/controller/system.storeWarehouse.test.js', () => { assert.match(String(res.body.message || ''), /id|counterparty_id|store_id|warehouse_id/); }); - it('should expose standalone storeWarehouse.store.listQimenConfig parameter validation', async () => { - const res = await invokeSystemMethod(`${METHOD_PREFIX}.listQimenConfig`, {}, token, EXTRA_HEADERS); + it('should expose standalone storeWarehouse.store.listApiConfig parameter validation', async () => { + const res = await invokeSystemMethod(`${METHOD_PREFIX}.listApiConfig`, {}, token, EXTRA_HEADERS); assert.equal(res.status, 200); assert.equal(res.body.flag, 'failure'); diff --git a/test/app/service/systemMethods/warehouse.auth.test.js b/test/app/service/systemMethods/warehouse.auth.test.js new file mode 100644 index 0000000..afd06e4 --- /dev/null +++ b/test/app/service/systemMethods/warehouse.auth.test.js @@ -0,0 +1,103 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const WarehouseService = require('../../../../app/service/systemMethods/warehouse'); + +function createService(userOverrides = {}, permissionRows = []) { + const responseHeaders = {}; + + const ctx = { + header: { + platform: 'web', + project: 'all', + }, + set(name, value) { + responseHeaders[name] = value; + }, + app: { + config: { + jwt: { + secret: 'test-secret', + expiresIn: '3600', + }, + }, + jwt: { + verify() { + return { + id: 1, + exp: Math.floor(Date.now() / 1000) + 3600, + }; + }, + sign() { + return 'refreshed-token'; + }, + }, + }, + model: { + Permission: { + async findAll({ where = {} } = {}) { + const ids = Array.isArray(where.id) ? where.id.map(Number) : []; + return permissionRows.filter(row => ids.length === 0 || ids.includes(Number(row.id))); + }, + }, + }, + service: { + systems: { + auth: { + user: { + async findById() { + return { + id: 1, + username: 'tester', + status: 1, + permissions: [], + ...userOverrides, + }; + }, + }, + }, + }, + }, + }; + + return { + service: new WarehouseService(ctx), + ctx, + responseHeaders, + }; +} + +describe('test/app/service/systemMethods/warehouse.auth.test.js', () => { + it('should deny getAreaRacks when explicit api permission is missing', async () => { + const { service } = createService(); + + const result = await service.checkAuth('warehouse', 'getAreaRacks', 'Bearer test-token'); + + assert.equal(result.status, 403); + assert.equal(result.message, '无权访问该接口'); + }); + + it('should allow getAreaRacks when user has wildcard permissions', async () => { + const { service } = createService({ permissions: '*' }); + + const result = await service.checkAuth('warehouse', 'getAreaRacks', 'Bearer test-token'); + + assert.equal(result.status, 200); + assert.equal(result.message, 'ok'); + }); + + it('should allow getAreaRacks when permission payload contains matching path or id', async () => { + const scenarios = [ + createService({ permissions: [ 'warehouse.getAreaRacks' ] }), + createService({ permissions: '["warehouse.getAreaRacks"]' }), + createService({ permissions: [{ path: 'warehouse.getAreaRacks' }] }), + createService({ permissions: [ 5161 ] }, [{ id: 5161, path: 'warehouse.getAreaRacks', status: 1 }]), + ]; + + for (const { service } of scenarios) { + const result = await service.checkAuth('warehouse', 'getAreaRacks', 'Bearer test-token'); + assert.equal(result.status, 200); + assert.equal(result.message, 'ok'); + } + }); +}); diff --git a/test/app/service/systems/store_warehouse.adjustPrintQuantity.test.js b/test/app/service/systems/store_warehouse.adjustPrintQuantity.test.js new file mode 100644 index 0000000..96985f0 --- /dev/null +++ b/test/app/service/systems/store_warehouse.adjustPrintQuantity.test.js @@ -0,0 +1,199 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const StoreWarehouseService = require('../../../../app/service/systems/store_warehouse'); + +describe('test/app/service/systems/store_warehouse.adjustPrintQuantity.test.js', () => { + const buildContext = () => { + const capture = { + relationPatch: null, + changeLogPayload: null, + noticePayload: null, + }; + const transaction = { + committed: false, + rolledBack: false, + async commit() { + this.committed = true; + }, + async rollback() { + this.rolledBack = true; + }, + }; + const relation = { + id: 88, + store_id: 100000, + warehouse_id: 200000, + print_quantity: 10, + async update(patch) { + capture.relationPatch = patch; + this.print_quantity = patch.print_quantity; + }, + }; + + const ctx = { + app: { + config: {}, + }, + user: { + id: 9001, + store_id: 200000, + employees_name: '仓管A', + store_name: '测试仓', + }, + model: { + transaction: async () => transaction, + Store: { + async findOne({ where }) { + if (Number(where.id) === 200000) { + return { + id: 200000, + company_name: '测试仓', + project: 'warehouse', + status: 1, + }; + } + return { + id: 100000, + company_name: '测试货主', + project: 'store', + status: 1, + }; + }, + }, + StoreWarehouse: { + async findOne() { + return relation; + }, + async findByPk(id) { + return { + get() { + return { + id, + store_id: 100000, + warehouse_id: 200000, + auth_status: 2, + apply_reason: '', + review_comment: '', + apply_time: new Date('2026-04-07T08:00:00.000Z'), + review_time: new Date('2026-04-07T08:00:00.000Z'), + auth_start: new Date('2026-04-07T08:00:00.000Z'), + auth_end: new Date('2026-12-31T23:59:59.000Z'), + actual_end: null, + print_quantity: relation.print_quantity, + applied_by: 9001, + reviewed_by: 9001, + ended_by: null, + store_remask: '测试货主别名', + warehouse_remask: '测试仓别名', + use_status: 1, + policy_config: null, + store: { + id: 100000, + company_name: '测试货主', + }, + warehouse: { + id: 200000, + company_name: '测试仓', + }, + }; + }, + }; + }, + }, + StoreWarehousePrintQuantityLog: { + async create(payload) { + capture.changeLogPayload = payload; + return { + id: 556, + get() { + return { + ...payload, + id: 556, + created_at: new Date('2026-04-07T09:00:00.000Z'), + }; + }, + }; + }, + }, + }, + service: { + systems: { + notice: { + async send(options) { + capture.noticePayload = options; + return { + success: true, + data: { + sentCount: 0, + }, + }; + }, + }, + }, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + }; + + ctx.app.model = ctx.model; + + return { + capture, + transaction, + ctx, + }; + }; + + it('should require reason when manually adjusting print quantity', async () => { + const { ctx } = buildContext(); + const service = new StoreWarehouseService(ctx); + service.getSingleQimenConfig = async () => null; + + await assert.rejects(async () => { + await service.adjustPrintQuantity({ + id: 88, + change_quantity: 5, + }); + }, /reason 参数不能为空/); + }); + + it('should overwrite target balance instead of incrementing it when manually adjusting print quantity', async () => { + const { ctx, capture, transaction } = buildContext(); + const service = new StoreWarehouseService(ctx); + service.getSingleQimenConfig = async () => null; + + const result = await service.adjustPrintQuantity({ + id: 88, + change_quantity: 7, + reason: '人工覆盖余额测试', + business_type: 'order_express', + business_id: 321, + }); + + assert.equal(result.code, 200); + assert.equal(Number(result.data.contract.id), 88); + assert.equal(Number(result.data.contract.print_quantity), 7); + assert.equal(Number(result.data.change_log.change_quantity), -3); + assert.equal(Number(result.data.change_log.balance_before), 10); + assert.equal(Number(result.data.change_log.balance_after), 7); + assert.equal(String(result.data.change_log.reason || ''), '人工覆盖余额测试'); + + assert.deepEqual(capture.relationPatch, { + print_quantity: 7, + }); + assert.equal(String(capture.changeLogPayload.change_type || ''), 'manual_adjust'); + assert.equal(Number(capture.changeLogPayload.change_quantity), -3); + assert.equal(Number(capture.changeLogPayload.balance_before), 10); + assert.equal(Number(capture.changeLogPayload.balance_after), 7); + assert.equal(String(capture.changeLogPayload.reason || ''), '人工覆盖余额测试'); + assert.equal(String(capture.noticePayload.event || ''), 'store_warehouse_print_quantity_adjusted'); + assert.equal(String(capture.noticePayload.businessName || ''), 'store_warehouse'); + assert.equal(Number(capture.noticePayload.metadata.changeQuantity), -3); + assert.equal(transaction.committed, true); + assert.equal(transaction.rolledBack, false); + }); +}); diff --git a/wms.code-workspace b/wms.code-workspace index 61e510d..cea87c9 100644 --- a/wms.code-workspace +++ b/wms.code-workspace @@ -5,5 +5,6 @@ } ], "settings": { + "workbench.browser.enableChatTools": false } } \ No newline at end of file From ee7d2a1f8ffa24562445b25588a0c48db79b8319 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Thu, 9 Apr 2026 01:38:59 +0800 Subject: [PATCH 016/550] chore: sync remaining changes --- .github/agents/开发.agent.md | 2 +- .github/agents/缓存.agent.md | 1 + README.md | 2 +- app/service/systemMethods/storage/delivery.js | 37 ++++++++++------ methods/changes/system.json | 9 ---- .../system.storage.delivery.module.test.js | 44 ------------------- 6 files changed, 27 insertions(+), 68 deletions(-) diff --git a/.github/agents/开发.agent.md b/.github/agents/开发.agent.md index f472027..ee288e4 100644 --- a/.github/agents/开发.agent.md +++ b/.github/agents/开发.agent.md @@ -42,7 +42,7 @@ model: GPT-5.3-Codex (copilot) - **绝对不能直接扩大任何角色的授权范围**,不得直接改 `wms_role.permissions` 或其他角色授权绑定来“顺手放开权限” 7. **必须做验证**:改代码后跑相关检查,确认响应结构与文档一致 8. **所有修改的函数必须要有 JSDOC 注释**,必要时补充说明参数、返回值、错误码等信息,如果修改的方法中没有注释,必须补充完整的 JSDOC 注释后再提交,严禁入参与返回值都没有注释的函数存在于代码中,如果要修改的文件大部分缺失注释,必须先驳回到调度 agent 让其补齐拆解分析再修改,禁止直接改代码后再补注释的流程 -9. **method入参必须解构再传入service **,禁止直接把 method 入参对象传给 service,必须先在 controller 层解构出具体参数,再传给 service,保持层与层之间的清晰边界和职责分离,如果拆解参数过多,可以先在 controller 层做多步骤访问service方法处理,但是必须在service层处理,禁止在method层调用method层。 +9. **method入参必须解构再传入service **,禁止直接把 method 入参对象传给 service,必须先在 method 层解构出具体参数,再传给 service,保持层与层之间的清晰边界和职责分离,如果拆解参数过多,可以先在 controller 层做多步骤访问service方法处理,但是必须在service层处理,禁止在method层调用method层。 10. **禁止method入口直接调用model层**,必须先调用service层,保持分层职责的清晰和一致 11. **所有编码风格必须要通过ESLint检查**,禁止任何 ESLint 错误或警告存在于提交的代码中 12. **禁止修改底层公共代码来“顺手解决问题”**,如需要改 `app.js`、`app/extend/application.js`、`app/service/main.js` 等公共能力入口,必须先评估改动影响范围,并优先考虑在业务层做适配或扩展,避免对全局能力造成不确定风险,如确实需要改公共代码,必须先驳回到调度 agent 升级给专家 agent 进行兜底处理,禁止直接改公共代码后再评估风险的流程 diff --git a/.github/agents/缓存.agent.md b/.github/agents/缓存.agent.md index c43f289..bae0b20 100644 --- a/.github/agents/缓存.agent.md +++ b/.github/agents/缓存.agent.md @@ -3,6 +3,7 @@ name: wms-redis-agent description: "Use when the user asks about Redis、缓存、cache key、TTL、session、script/redis-cache.ps1、hgetall/hset、set/get/del、缓存排障、键值核对。专用于 WMS Redis 查询与缓存变更。" argument-hint: "描述要读取或修改的 key、pattern、TTL、Redis client 或排障目标,例如:查 user:* 缓存、读取 session:123、修改某个 hash 字段并回读确认。" tools: ['read', 'search', 'execute', 'todo'] +model: GPT-5 mini (copilot) --- # WMS Redis 代理(`wms-redis-agent`) diff --git a/README.md b/README.md index 0389d75..60348dc 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # 奇门WMS(qimen-wms) -基于 Egg.js 的仓储管理系统(WMS),支持多快递平台对接、订单管理、打印、权限、配置等功能,适合中小型电商与仓储企业二次开发。 +基于 Egg.js 的仓储管理系统(WMS),支持支持多快递平台对接、订单管理、打印、权限、配置等功能,适合中小型电商与仓储企业二次开发。 ## 文档导航 diff --git a/app/service/systemMethods/storage/delivery.js b/app/service/systemMethods/storage/delivery.js index 90dda57..4fda3d5 100644 --- a/app/service/systemMethods/storage/delivery.js +++ b/app/service/systemMethods/storage/delivery.js @@ -3,32 +3,43 @@ const MainService = require('../../main'); /** - * 系统方法层:storage.delivery(已废弃)。 + * 系统方法层:storage.delivery(兼容层)。 + * 历史调用兼容:统一转发到 storage.stockout,避免继续以 delivery 命名承载非订单出库语义。 */ class StorageDeliveryService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = ''; - const _noNeedLog = ''; - const _noNeedAuth = ''; + const _noNeedRight = 'list,toOrder,listItems'; + const _noNeedLog = 'list,toOrder,listItems'; + const _noNeedAuth = 'list,toOrder,listItems'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } - buildRemovedResponse() { - return this.fail('方法已移除', { code: 410 }); - } - - async list() { - return this.buildRemovedResponse(); + /** + * 出库单列表查询(兼容转发)。 + * @param {Object} data 请求体 + * @return {Promise} 出库单列表结果 + */ + async list(data = {}) { + return await this.ctx.service.systemMethods.storage.stockout.list(data); } + /** + * 出库单跳转订单占位接口(兼容转发)。 + * @return {Promise} 占位失败结果 + */ async toOrder() { - return this.buildRemovedResponse(); + return await this.ctx.service.systemMethods.storage.stockout.toOrder(); } - async listItems() { - return this.buildRemovedResponse(); + /** + * 拉取出库单明细(兼容转发)。 + * @param {Object} data 请求体 + * @return {Promise} 订单/出库单明细结果 + */ + async listItems(data = {}) { + return await this.ctx.service.systemMethods.storage.stockout.listItems(data); } } diff --git a/methods/changes/system.json b/methods/changes/system.json index a00923b..e280450 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -270,14 +270,5 @@ "type": "change", "summary": "将 storage.stockout.toOrder 标记为占位接口", "detail": "storage.stockout.toOrder 当前仅保留方法名用于后续扩展,暂不开放实际逻辑。调用时返回 code=405、message=占位接口,暂未开放。" - }, - { - "id": "2026.04.08-system-22", - "date": "2026-04-08", - "module": "storage", - "method": "storage.delivery.*", - "type": "remove", - "summary": "移除 storage.delivery.* 兼容入口", - "detail": "storage.delivery.* 兼容转发已从系统移除,调用方请迁移至 storage.stockout.* 作为主出口。" } ] diff --git a/test/app/controller/system.storage.delivery.module.test.js b/test/app/controller/system.storage.delivery.module.test.js index ededb30..487f094 100644 --- a/test/app/controller/system.storage.delivery.module.test.js +++ b/test/app/controller/system.storage.delivery.module.test.js @@ -150,50 +150,6 @@ async function getEntryContextForRemovedMethods(token) { describe('test/app/controller/system.storage.delivery.module.test.js', function() { this.timeout(120000); - it('should not expose storage.delivery methods after compatibility layer removal', async () => { - const { token } = await getAuthToken(); - const switched = await switchToWarehouseRoleWithDeliveryData(token); - const delivery = await getFirstDelivery(switched.token); - - const removedMethods = [ - { - method: 'storage.delivery.list', - body: { - pagination: { - page: 1, - pageSize: 10, - }, - where: {}, - }, - }, - { - method: 'storage.delivery.toOrder', - body: { - id: Number(delivery.id), - delivery_order_code: delivery.delivery_order_code, - warehouse_id: TEST_WAREHOUSE_ID, - }, - }, - { - method: 'storage.delivery.listItems', - body: { - id: Number(delivery.id), - delivery_order_code: delivery.delivery_order_code, - warehouse_id: TEST_WAREHOUSE_ID, - }, - }, - ]; - - for (const { method, body } of removedMethods) { - const res = await invokeSystemMethod(method, body, switched.token, EXTRA_HEADERS); - const isLegacySuccess = res.status === 200 - && res.body?.flag === 'success' - && Number(res.body?.code) === 200; - - assert.ok(!isLegacySuccess, `${method} 仍然返回 success 200: ${JSON.stringify(res.body)}`); - } - }); - it('should return delivery list via storage.stockout.list', async () => { const { token } = await getAuthToken(); const switched = await switchToWarehouseRoleWithDeliveryData(token); From 57f1f44baeff01bc57f0c78865b6c6b4ad68ada7 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Thu, 9 Apr 2026 15:45:14 +0800 Subject: [PATCH 017/550] feat: sync wms updates --- .github/agents/开发.agent.md | 123 ++++- app/model/stock_transaction.js | 20 + app/service/systemMethods/index.js | 35 +- app/service/systemMethods/storage/entry.js | 5 +- .../systemMethods/storeWarehouse/store.js | 286 +++++++++++- app/service/systems/auth/user.js | 10 +- app/service/systems/license_plate.js | 255 ++++++++++ app/service/systems/stock_store.js | 380 ++++++++++----- app/service/systems/stock_transaction.js | 78 ++++ app/service/systems/storage/entry.js | 135 +++++- app/service/systems/storage/inventory.js | 24 +- app/service/systems/storage/receiving.js | 55 ++- app/service/systems/store_warehouse.js | 439 ++++++++++++++++++ app/service/systems/upload.js | 68 ++- config/config.default.js | 8 +- ...0408140000-create-wms-stock-transaction.js | 20 + ...apshot-columns-to-wms-stock-transaction.js | 63 +++ docs/qimen-interface-reference.md | 226 +++++++++ methods/changes/system.json | 45 ++ methods/system.json | 79 +++- .../system.storage.transaction.test.js | 16 + .../storeWarehouse/store.test.js | 157 +++++++ .../systems/auth.user.loginWechatCode.test.js | 53 +++ .../app/service/systems/license_plate.test.js | 75 +++ .../systems/stock_transaction.create.test.js | 85 ++++ .../systems/storage.entry.cancel.test.js | 171 +++++++ .../systems/storage.receiving.report.test.js | 160 ++++++- test/app/service/systems/upload.test.js | 55 +++ 28 files changed, 2909 insertions(+), 217 deletions(-) create mode 100644 app/service/systems/license_plate.js create mode 100644 database/migrations/20260409120000-add-snapshot-columns-to-wms-stock-transaction.js create mode 100644 docs/qimen-interface-reference.md create mode 100644 test/app/service/systemMethods/storeWarehouse/store.test.js create mode 100644 test/app/service/systems/license_plate.test.js create mode 100644 test/app/service/systems/stock_transaction.create.test.js create mode 100644 test/app/service/systems/storage.entry.cancel.test.js diff --git a/.github/agents/开发.agent.md b/.github/agents/开发.agent.md index ee288e4..e1f0122 100644 --- a/.github/agents/开发.agent.md +++ b/.github/agents/开发.agent.md @@ -41,7 +41,128 @@ model: GPT-5.3-Codex (copilot) - `npm run permission:sync:system-api` - **绝对不能直接扩大任何角色的授权范围**,不得直接改 `wms_role.permissions` 或其他角色授权绑定来“顺手放开权限” 7. **必须做验证**:改代码后跑相关检查,确认响应结构与文档一致 -8. **所有修改的函数必须要有 JSDOC 注释**,必要时补充说明参数、返回值、错误码等信息,如果修改的方法中没有注释,必须补充完整的 JSDOC 注释后再提交,严禁入参与返回值都没有注释的函数存在于代码中,如果要修改的文件大部分缺失注释,必须先驳回到调度 agent 让其补齐拆解分析再修改,禁止直接改代码后再补注释的流程 +8. **所有修改的函数必须要有 JSDoc 注释**,必要时补充说明参数、返回值、错误码等信息;新增或修改的 JSDoc 必须使用中文描述,参数名/返回值说明也必须中文化,避免再出现英文 JSDoc;如果修改的方法中没有注释,必须补充完整的 JSDoc 注释后再提交,严禁入参与返回值都没有注释的函数存在于代码中,非本次修改的函数如果没有注释,除非有明确的理由,否则也必须补充完整的 JSDoc 注释后再提交 +9. **method入参必须解构再传入service **,禁止直接把 method 入参对象传给 service,必须先在 method 层解构出具体参数,再传给 service,保持层与层之间的清晰边界和职责分离,如果拆解参数过多,可以先在 controller 层做多步骤访问service方法处理,但是必须在service层处理,禁止在method层调用method层。 +10. **禁止method入口直接调用model层**,必须先调用service层,保持分层职责的清晰和一致 +11. **所有编码风格必须要通过ESLint检查**,禁止任何 ESLint 错误或警告存在于提交的代码中 +12. **禁止修改底层公共代码来“顺手解决问题”**,如需要改 `app.js`、`app/extend/application.js`、`app/service/main.js` 等公共能力入口,必须先评估改动影响范围,并优先考虑在业务层做适配或扩展,避免对全局能力造成不确定风险,如确实需要改公共代码,必须先驳回到调度 agent 升级给专家 agent 进行兜底处理,禁止直接改公共代码后再评估风险的流程 + +## 关键定位地图 + +### 1) 接口入口与 Method 路由 + +- `/system`:Web / PDA 统一接口(POST) +- `/qimen`:奇门接口(POST) +- 路由说明文档:`AI_METHOD_ROUTING.md` + +### 2) 文档单一事实来源(SSOT) + +- `methods/system.json` +- `methods/qimen.json` + +### 3) App 能力入口 + +- `app.js` +- `app/extend/application.js` + +### 4) 常用开发辅助文件 + +- `app/service/main.js`:where 统一处理、权限校验等公共逻辑 +- `test/app/controller/system.user.info.web.test.js` +- `test/app/controller/system.user.changeRole.test.js` + +## 推荐工作流 + +### 代码修改 / 修 bug + +1. 先定位 method 与实现链路 +2. 如需测试设计或补回归,先委派 `wms-test-agent` 补失败用例 +3. 做最小根因修复 +4. 跑相关检查验证 +5. 若涉及接口变更(参数、响应、新增、删除),**必须委派 `wms-doc-agent`** 同步 `methods/*.json`、追加 `methods/changes/*.json` 变更记录 + +### 接口参数变更 + +```powershell +node .\script\tmp-struct-system-params.cjs +``` + +然后人工补齐: +- `description` +- `response` +- `errors` +- 特殊枚举值与业务约束 + +## 建议提问方式 + +```text +请使用 wms-dev-agent 帮我: +1) 定位这个 method / controller / service 的实现链路 +2) 修复问题并说明最小代码改动 +3) 输出验证结果;若需要补测试,请转给 `wms-test-agent` +``` + +## 输出要求 + +- 所有回复建议以 `[Dev]` 开头 +- 先给结论,再给定位链路、修改点、验证结果 +- 涉及接口改动时,明确说明已委派 `wms-doc-agent` 完成文档同步(或提示调用方需要委派) + +## 结论 + +通用开发能力文档已统一收口到本 Agent;测试相关请求请转给 `wms-test-agent`,工具箱只保留“开发相关必须使用 `wms-dev-agent`”的规则入口。 + +## 代码风格 + +- 先定位代码真实实现与调用链 +- 只改最小必要代码,避免大面积重构 +- 改代码后必须跑相关测试验证 +- 涉及接口变更必须委派 `wms-doc-agent` 同步文档,本 agent 不直接修改文档文件 +- 除了json,其他字符串输出必须使用模板字符串,必要时分行保持可读性 +- --- +name: wms-dev-agent +description: "Use when the user asks about 开发、改代码、修 bug、调试、接口定位、method routing、where 规范、权限映射、Egg.js service 分层。专用于 WMS 通用开发与代码实现。" +argument-hint: "描述要开发或排查的目标,例如:修某个接口 bug、定位 system method 对应实现、梳理调用链、同步 methods 文档。" +tools: ['read', 'search', 'edit', 'execute', 'todo'] +model: GPT-5.3-Codex (copilot) +--- + +# WMS 开发代理(`wms-dev-agent`) + +## 适用范围 + +- 项目根目录:`D:\wms` +- 主要开发目录:`app/`、`methods/`、`docs/` +- 适用于 Egg.js 业务开发、接口联调与文档同步;如重点是测试设计、回归验证、TDD,请转给 `wms-test-agent` + +## 何时必须使用本 Agent + +出现以下任一诉求时,必须使用 `wms-dev-agent`: + +- 改代码 / 修 bug / 重构 / 性能优化 +- 定位 `/system` / `/qimen` method 映射关系 +- 排查 `where` 规则、权限映射、分层职责问题 +- 分析 `app.js` / `app/extend/application.js` / `systemMethods` / `systems` 调用链 +- 如诉求重点是测试设计、回归验证、TDD,请委派给 `wms-test-agent` +- 如涉及文档同步,委派给 `wms-doc-agent` + +## 开发规则 + +1. **先定位后修改**:先找 `controller / systemMethods / systems / model` 的实际链路 +2. **分层约定必须保持**: + - `systemMethods` 只保留出口包装层 + - 业务逻辑统一下沉到 `systems` +3. **如诉求重点是测试设计、补回归、接口验证或 TDD,委派给** `wms-test-agent` +4. **禁止直接修改文档文件**:`methods/*.json`、`methods/changes/*.json`、`docs/*.md` 的所有新增与修改必须委派给 `wms-doc-agent` 完成,`wms-dev-agent` 只负责代码文件(`app/`、`config/`、`database/`、`test/`) +5. **where 规则统一走** `app/service/main.js` 的 `prepareWhereContext(data, options)` +6. **新建接口时,必须先判断是通用接口还是需授权接口**: + - 先明确 `isNeedAuth`,代码实现完成后委派 `wms-doc-agent` 同步 `methods/system.json` 并追加变更记录 + - 若为需授权接口,必须优先通过既有同步流程 / 标准方式补齐权限记录(如 `wms_permission`),必要时使用: + - `npm run permission:sync:system-api -- --dry-run` + - `npm run permission:sync:system-api` + - **绝对不能直接扩大任何角色的授权范围**,不得直接改 `wms_role.permissions` 或其他角色授权绑定来“顺手放开权限” +7. **必须做验证**:改代码后跑相关检查,确认响应结构与文档一致 +8. **所有修改的函数必须要有 JSDOC 注释**,必要时补充说明参数、返回值、错误码等信息,如果修改的方法中没有注释,必须补充完整的 JSDOC 注释后再提交,严禁入参与返回值都没有注释的函数存在于代码中,非本次修改的函数如果没有注释,除非有明确的理由,否则也必须补充完整的 JSDOC 注释后再提交 9. **method入参必须解构再传入service **,禁止直接把 method 入参对象传给 service,必须先在 method 层解构出具体参数,再传给 service,保持层与层之间的清晰边界和职责分离,如果拆解参数过多,可以先在 controller 层做多步骤访问service方法处理,但是必须在service层处理,禁止在method层调用method层。 10. **禁止method入口直接调用model层**,必须先调用service层,保持分层职责的清晰和一致 11. **所有编码风格必须要通过ESLint检查**,禁止任何 ESLint 错误或警告存在于提交的代码中 diff --git a/app/model/stock_transaction.js b/app/model/stock_transaction.js index 88ddf39..996d3ab 100644 --- a/app/model/stock_transaction.js +++ b/app/model/stock_transaction.js @@ -45,6 +45,26 @@ module.exports = app => { allowNull: false, comment: '变动数量(正数)', }, + before_quantity: { + type: INTEGER(12), + allowNull: true, + comment: '变更前总库存数量', + }, + after_quantity: { + type: INTEGER(12), + allowNull: true, + comment: '变更后总库存数量', + }, + before_locked_quantity: { + type: INTEGER(12), + allowNull: true, + comment: '变更前锁定数量', + }, + after_locked_quantity: { + type: INTEGER(12), + allowNull: true, + comment: '变更后锁定数量', + }, batch_no: { type: STRING(100), allowNull: true, diff --git a/app/service/systemMethods/index.js b/app/service/systemMethods/index.js index 82f4f68..9797138 100644 --- a/app/service/systemMethods/index.js +++ b/app/service/systemMethods/index.js @@ -3,12 +3,17 @@ const MainService = require('../main'); class indexService extends MainService { + /** + * 初始化基础方法的免登录、免权限、免鉴权和免日志配置。 + * + * @param {Egg.Context} ctx 上下文对象 + */ constructor(ctx) { super(ctx); const _noNeedLogin = 'getI18nMessage,putI18nCollect'; - const _noNeedRight = 'getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getCOSUploadConfig,uploadSuccessNotify,getMessageDetail,searchSpace,listInterfaceTypes'; + const _noNeedRight = 'getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getCOSUploadConfig,uploadSuccessNotify,getMessageDetail,searchSpace,listInterfaceTypes,recognizeLicensePlate'; const _noNeedLog = '*'; - const _noNeedAuth = 'getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getMessageDetail,searchSpace,listInterfaceTypes'; + const _noNeedAuth = 'getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getMessageDetail,searchSpace,listInterfaceTypes,recognizeLicensePlate'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } async fastWhereTree(data) { @@ -38,6 +43,32 @@ class indexService extends MainService { const result = await service.systems.upload.uploadSuccessNotify(data); return this.success('ok', { data: result, code: 200 }); } + /** + * 识别车牌号码。 + * + * @param {Object} data 请求参数 + * @param {string} data.base64 base64 图片 + * @param {string} [data.imageBase64] 兼容的 base64 字段 + * @param {string} [data.image_base64] 兼容的 base64 字段 + * @returns {Promise} 识别结果 + */ + async recognizeLicensePlate(data) { + const { service, ctx } = this; + const { base64 = '', imageBase64 = '', image_base64 = '' } = data || {}; + const imageBase64Value = String(base64 || imageBase64 || image_base64 || '').trim(); + + if (!imageBase64Value) { + return this.fail('base64 图片不能为空', { code: 400 }); + } + + try { + const result = await service.systems.licensePlate.recognizeLicensePlate(imageBase64Value); + return this.success('ok', { data: result, code: 200 }); + } catch (error) { + ctx.logger.error('车牌识别失败:', error); + return this.fail(error.message || '车牌识别失败', { code: 500 }); + } + } async ReferenceFile(data) { const { service } = this; const result = await service.systems.file.ReferenceFile(data); diff --git a/app/service/systemMethods/storage/entry.js b/app/service/systemMethods/storage/entry.js index 8350116..3b808cd 100644 --- a/app/service/systemMethods/storage/entry.js +++ b/app/service/systemMethods/storage/entry.js @@ -52,7 +52,10 @@ class entryService extends MainService { /** * 作废入库单。 - * @param {Object} data 请求体 + * 支持传入单个 id 或批量 ids,保持透传给业务层处理。 + * @param {Object} data 请求体 + * @param {number} [data.id] 单个入库单ID + * @param {number[]} [data.ids] 批量入库单ID数组 * @return {Promise} 统一 success 包装 */ async cancel(data = {}) { diff --git a/app/service/systemMethods/storeWarehouse/store.js b/app/service/systemMethods/storeWarehouse/store.js index c4a7635..12394fd 100644 --- a/app/service/systemMethods/storeWarehouse/store.js +++ b/app/service/systemMethods/storeWarehouse/store.js @@ -2,7 +2,27 @@ const MainService = require('../../main'); + +/** + * 规范仓库配置方法入参,避免把原始引用直接传给下游服务。 + * + * @param {Object} data 请求数据。 + * @return {Object} 复制后的请求数据。 + */ +function normalizeStoreWarehousePayload(data) { + if (!data || typeof data !== 'object' || Array.isArray(data)) { + return {}; + } + + return { ...data }; +} + class StoreWarehouseStoreService extends MainService { + /** + * 创建一个仓库配置 store 服务。 + * + * @param {Object} ctx 上下文对象。 + */ constructor(ctx) { super(ctx); const _noNeedLogin = ''; @@ -12,60 +32,290 @@ class StoreWarehouseStoreService extends MainService { this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } - async callSystemStoreWarehouse(methodName, data = {}, defaultMessage) { - const { service } = this; + /** + * 获取签约列表。 + * + * @param {Object} data 请求数据。 + * @return {Promise} 统一响应结果。 + */ + async list(data = {}) { + const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse; + + if (!targetService || typeof targetService.list !== 'function') { + return this.fail('获取签约列表失败', { + code: 500, + }); + } + try { - const result = await service.systems.storeWarehouse[methodName](data); + const payload = normalizeStoreWarehousePayload(data); + const result = await targetService.list(payload); return this.success('ok', result); } catch (error) { - return this.fail(error.message || defaultMessage, { + return this.fail(error.message || '获取签约列表失败', { code: Number(error.code) || 500, }); } } - async list(data = {}) { - return this.callSystemStoreWarehouse('list', data, '获取签约列表失败'); - } - + /** + * 发起签约。 + * + * @param {Object} data 请求数据。 + * @return {Promise} 统一响应结果。 + */ async sign(data = {}) { - return this.callSystemStoreWarehouse('sign', data, '签约失败'); + const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse; + + if (!targetService || typeof targetService.sign !== 'function') { + return this.fail('签约失败', { + code: 500, + }); + } + + try { + const payload = normalizeStoreWarehousePayload(data); + const result = await targetService.sign(payload); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '签约失败', { + code: Number(error.code) || 500, + }); + } } + /** + * 修改签约名称。 + * + * @param {Object} data 请求数据。 + * @return {Promise} 统一响应结果。 + */ async rename(data = {}) { - return this.callSystemStoreWarehouse('rename', data, '修改签约名称失败'); + const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse; + + if (!targetService || typeof targetService.rename !== 'function') { + return this.fail('修改签约名称失败', { + code: 500, + }); + } + + try { + const payload = normalizeStoreWarehousePayload(data); + const result = await targetService.rename(payload); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '修改签约名称失败', { + code: Number(error.code) || 500, + }); + } } + /** + * 解除签约。 + * + * @param {Object} data 请求数据。 + * @return {Promise} 统一响应结果。 + */ async unbind(data = {}) { - return this.callSystemStoreWarehouse('unbind', data, '解除签约失败'); + const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse; + + if (!targetService || typeof targetService.unbind !== 'function') { + return this.fail('解除签约失败', { + code: 500, + }); + } + + try { + const payload = normalizeStoreWarehousePayload(data); + const result = await targetService.unbind(payload); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '解除签约失败', { + code: Number(error.code) || 500, + }); + } } + /** + * 人工调整面单余额。 + * + * @param {Object} data 请求数据。 + * @return {Promise} 统一响应结果。 + */ async adjustPrintQuantity(data = {}) { - return this.callSystemStoreWarehouse('adjustPrintQuantity', data, '人工调整面单余额失败'); + const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse; + + if (!targetService || typeof targetService.adjustPrintQuantity !== 'function') { + return this.fail('人工调整面单余额失败', { + code: 500, + }); + } + + try { + const payload = normalizeStoreWarehousePayload(data); + const result = await targetService.adjustPrintQuantity(payload); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '人工调整面单余额失败', { + code: Number(error.code) || 500, + }); + } } + /** + * 获取合约策略配置。 + * + * @param {Object} data 请求数据。 + * @return {Promise} 统一响应结果。 + */ async getPolicyConfig(data = {}) { - return this.callSystemStoreWarehouse('getPolicyConfig', data, '获取合约策略配置失败'); + const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse; + + if (!targetService || typeof targetService.getPolicyConfig !== 'function') { + return this.fail('获取合约策略配置失败', { + code: 500, + }); + } + + try { + const payload = normalizeStoreWarehousePayload(data); + const result = await targetService.getPolicyConfig(payload); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '获取合约策略配置失败', { + code: Number(error.code) || 500, + }); + } } + /** + * 获取合约策略字段信息。 + * + * @param {Object} data 请求数据。 + * @return {Promise} 统一响应结果。 + */ async getPolicyConfigFields(data = {}) { - return this.callSystemStoreWarehouse('getPolicyConfigFields', data, '获取合约策略字段信息失败'); + const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse; + + if (!targetService || typeof targetService.getPolicyConfigFields !== 'function') { + return this.fail('获取合约策略字段信息失败', { + code: 500, + }); + } + + try { + const payload = normalizeStoreWarehousePayload(data); + const result = await targetService.getPolicyConfigFields(payload); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '获取合约策略字段信息失败', { + code: Number(error.code) || 500, + }); + } } + /** + * 保存合约策略配置。 + * + * @param {Object} data 请求数据。 + * @return {Promise} 统一响应结果。 + */ async savePolicyConfig(data = {}) { - return this.callSystemStoreWarehouse('savePolicyConfig', data, '保存合约策略配置失败'); + const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse; + + if (!targetService || typeof targetService.savePolicyConfig !== 'function') { + return this.fail('保存合约策略配置失败', { + code: 500, + }); + } + + try { + const payload = normalizeStoreWarehousePayload(data); + const result = await targetService.savePolicyConfig(payload); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '保存合约策略配置失败', { + code: Number(error.code) || 500, + }); + } } + /** + * 获取接口配置列表。 + * + * @param {Object} data 请求数据。 + * @return {Promise} 统一响应结果。 + */ async listApiConfig(data = {}) { - return this.callSystemStoreWarehouse('listApiConfig', data, '获取接口配置列表失败'); + const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse; + + if (!targetService || typeof targetService.listApiConfig !== 'function') { + return this.fail('获取接口配置列表失败', { + code: 500, + }); + } + + try { + const payload = normalizeStoreWarehousePayload(data); + const result = await targetService.listApiConfig(payload); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '获取接口配置列表失败', { + code: Number(error.code) || 500, + }); + } } + /** + * 保存接口配置。 + * + * @param {Object} data 请求数据。 + * @return {Promise} 统一响应结果。 + */ async saveApiConfig(data = {}) { - return this.callSystemStoreWarehouse('saveApiConfig', data, '保存接口配置失败'); + const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse; + + if (!targetService || typeof targetService.saveApiConfig !== 'function') { + return this.fail('保存接口配置失败', { + code: 500, + }); + } + + try { + const payload = normalizeStoreWarehousePayload(data); + const result = await targetService.saveApiConfig(payload); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '保存接口配置失败', { + code: Number(error.code) || 500, + }); + } } + /** + * 删除奇门接口配置。 + * + * @param {Object} data 请求数据。 + * @return {Promise} 统一响应结果。 + */ async deleteQimenConfig(data = {}) { - return this.callSystemStoreWarehouse('deleteQimenConfig', data, '删除接口配置失败'); + const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse; + + if (!targetService || typeof targetService.deleteQimenConfig !== 'function') { + return this.fail('删除接口配置失败', { + code: 500, + }); + } + + try { + const payload = normalizeStoreWarehousePayload(data); + const result = await targetService.deleteQimenConfig(payload); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '删除接口配置失败', { + code: Number(error.code) || 500, + }); + } } } diff --git a/app/service/systems/auth/user.js b/app/service/systems/auth/user.js index e4db6bb..9e10c2f 100644 --- a/app/service/systems/auth/user.js +++ b/app/service/systems/auth/user.js @@ -614,6 +614,12 @@ class UserService extends Service { return Number.isFinite(ye4sUserId) && ye4sUserId > 0 ? ye4sUserId : null; } + /** + * 等待微信登录事件并解析事件中的 ye4s 用户 ID。 + * @param {string} clientCode 客户端编码 + * @param {number} timeoutMs 等待超时时间,单位为毫秒 + * @return {Promise} 事件监听结果 + */ async waitForWechatLoginEvent(clientCode, timeoutMs = WECHAT_BIND_LONG_POLL_TIMEOUT_MS) { const { app } = this; const normalizedClientCode = this.parseWechatBindCode(clientCode); @@ -634,7 +640,7 @@ class UserService extends Service { let settled = false; let timer = null; - function onMessage(messageChannel, message) { + const onMessage = (messageChannel, message) => { if (messageChannel !== channel) { return; } @@ -651,7 +657,7 @@ class UserService extends Service { event: eventData, ye4s_user_id: ye4sUserId, }); - } + }; function onError(error) { app.coreLogger.warn(`订阅微信登录事件失败: ${error.message}`); diff --git a/app/service/systems/license_plate.js b/app/service/systems/license_plate.js new file mode 100644 index 0000000..bb761b1 --- /dev/null +++ b/app/service/systems/license_plate.js @@ -0,0 +1,255 @@ +'use strict'; + +const Service = require('egg').Service; +const crypto = require('crypto'); +const https = require('https'); + +const OCR_HOST = 'ocr.tencentcloudapi.com'; +const OCR_SERVICE = 'ocr'; +const OCR_VERSION = '2018-11-19'; +const OCR_ACTION = 'LicensePlateOCR'; +const MAX_IMAGE_BYTES = 7 * 1024 * 1024; + +class LicensePlateService extends Service { + /** + * 获取腾讯云公共配置。 + * + * 说明:优先读取独立的腾讯云公共配置,若不存在则回退到兼容的 COS 配置, + * 以保证历史配置方式仍然可用。 + * + * @returns {Object} 腾讯云公共配置对象 + */ + getTencentCloudConfig() { + const tencentCloudConfig = this.config.tencentCloud || {}; + const cosConfig = this.config.cos || {}; + + return { + appId: tencentCloudConfig.appId ?? cosConfig.appId, + secretId: tencentCloudConfig.secretId ?? cosConfig.secretId, + secretKey: tencentCloudConfig.secretKey ?? cosConfig.secretKey, + }; + } + + /** + * 获取腾讯云 OCR 的默认区域。 + * + * @returns {string} 腾讯云区域标识 + */ + getTencentCloudRegion() { + const tencentCloudConfig = this.config.tencentCloud || {}; + const cosConfig = this.config.cos || {}; + + return tencentCloudConfig.region || cosConfig.region || 'ap-guangzhou'; + } + + /** + * 规范化并校验 base64 图片。 + * + * @param {string} imageBase64 前端传入的 base64 图片 + * @returns {{ base64: string, buffer: Buffer, size: number }} 规范化后的图片信息 + */ + normalizeBase64Image(imageBase64) { + const rawValue = String(imageBase64 || '').trim(); + + if (!rawValue) { + throw new Error('base64 图片不能为空'); + } + + const normalizedBase64 = rawValue + .replace(/^data:[^;]+;base64,/i, '') + .replace(/\s+/g, ''); + + if (!normalizedBase64) { + throw new Error('base64 图片不能为空'); + } + + if (!/^[A-Za-z0-9+/=]+$/.test(normalizedBase64)) { + throw new Error('base64 图片格式不正确'); + } + + const buffer = Buffer.from(normalizedBase64, 'base64'); + + if (!buffer.length) { + throw new Error('base64 图片解码失败'); + } + + if (buffer.length > MAX_IMAGE_BYTES) { + throw new Error('图片大小不能超过 7MB'); + } + + const normalizedWithoutPadding = normalizedBase64.replace(/=+$/u, ''); + const roundTripWithoutPadding = buffer.toString('base64').replace(/=+$/u, ''); + + if (normalizedWithoutPadding !== roundTripWithoutPadding) { + throw new Error('base64 图片格式不正确'); + } + + return { + base64: normalizedBase64, + buffer, + size: buffer.length, + }; + } + + /** + * 生成腾讯云 TC3 请求签名。 + * + * @param {Object} options 请求参数 + * @param {string} options.action 腾讯云动作名 + * @param {string} options.service 腾讯云服务名 + * @param {string} options.version 腾讯云接口版本 + * @param {string} options.region 腾讯云区域 + * @param {Object} options.payload 请求体 + * @returns {{ requestOptions: Object, payloadString: string }} 请求配置 + */ + buildTencentCloudRequest({ action, service, version, region, payload }) { + const { secretId, secretKey } = this.getTencentCloudConfig(); + + if (!secretId || !secretKey) { + throw new Error('腾讯云密钥未配置'); + } + + const timestamp = Math.floor(Date.now() / 1000); + const date = new Date(timestamp * 1000).toISOString().slice(0, 10); + const payloadString = JSON.stringify(payload || {}); + const hashedRequestPayload = crypto.createHash('sha256').update(payloadString).digest('hex'); + const canonicalHeaders = `content-type:application/json; charset=utf-8\nhost:${OCR_HOST}\n`; + const signedHeaders = 'content-type;host'; + const canonicalRequest = [ + 'POST', + '/', + '', + canonicalHeaders, + signedHeaders, + hashedRequestPayload, + ].join('\n'); + const credentialScope = `${date}/${service}/tc3_request`; + const stringToSign = [ + 'TC3-HMAC-SHA256', + timestamp, + credentialScope, + crypto.createHash('sha256').update(canonicalRequest).digest('hex'), + ].join('\n'); + + const secretDate = crypto.createHmac('sha256', `TC3${secretKey}`).update(date).digest(); + const secretService = crypto.createHmac('sha256', secretDate).update(service).digest(); + const secretSigning = crypto.createHmac('sha256', secretService).update('tc3_request').digest(); + const signature = crypto.createHmac('sha256', secretSigning).update(stringToSign).digest('hex'); + + const authorization = `TC3-HMAC-SHA256 Credential=${secretId}/${credentialScope}, SignedHeaders=${signedHeaders}, Signature=${signature}`; + + return { + payloadString, + requestOptions: { + hostname: OCR_HOST, + method: 'POST', + path: '/', + headers: { + Authorization: authorization, + 'Content-Type': 'application/json; charset=utf-8', + Host: OCR_HOST, + 'X-TC-Action': action, + 'X-TC-Version': version, + 'X-TC-Timestamp': String(timestamp), + 'X-TC-Region': region, + }, + }, + }; + } + + /** + * 发送腾讯云请求并解析 JSON 响应。 + * + * @param {Object} requestConfig 请求配置 + * @param {Object} requestConfig.requestOptions https 请求参数 + * @param {string} requestConfig.payloadString 请求体字符串 + * @returns {Promise} 腾讯云响应对象 + */ + async sendTencentCloudRequest(requestConfig) { + const { requestOptions, payloadString } = requestConfig; + + const responseText = await new Promise((resolve, reject) => { + const request = https.request(requestOptions, response => { + response.setEncoding('utf8'); + let responseBody = ''; + + response.on('data', chunk => { + responseBody += chunk; + }); + + response.on('end', () => { + resolve(responseBody); + }); + }); + + request.on('error', reject); + request.setTimeout(30000, () => { + request.destroy(new Error('腾讯云车牌识别请求超时')); + }); + request.write(payloadString); + request.end(); + }); + + let parsedResponse; + try { + parsedResponse = JSON.parse(responseText); + } catch (error) { + throw new Error(`腾讯云响应解析失败: ${error.message}`); + } + + const responsePayload = parsedResponse && parsedResponse.Response ? parsedResponse.Response : parsedResponse; + + if (responsePayload && responsePayload.Error) { + const { Code = 'TencentCloudError', Message = '腾讯云接口调用失败' } = responsePayload.Error; + throw new Error(`${Code}: ${Message}`); + } + + return parsedResponse; + } + + /** + * 识别车牌号码。 + * + * @param {string} imageBase64 前端传入的 base64 图片 + * @returns {Promise} 车牌识别结果 + */ + async recognizeLicensePlate(imageBase64) { + const { base64, size } = this.normalizeBase64Image(imageBase64); + const region = this.getTencentCloudRegion(); + const requestConfig = this.buildTencentCloudRequest({ + action: OCR_ACTION, + service: OCR_SERVICE, + version: OCR_VERSION, + region, + payload: { + ImageBase64: base64, + }, + }); + + const response = await this.sendTencentCloudRequest(requestConfig); + return this.formatLicensePlateResult(response); + } + + /** + * 统一整理腾讯云车牌识别响应。 + * + * @param {Object} response 腾讯云响应 + * @returns {Object} 归一化后的识别结果 + */ + formatLicensePlateResult(response) { + const responseData = response && response.Response ? response.Response : response || {}; + const licensePlate = String( + responseData.LicensePlate + || responseData.Number + || responseData.PlateNumber + || responseData.CarPlateNumber + || '' + ).trim(); + + return { + licensePlate, + }; + } +} + +module.exports = LicensePlateService; \ No newline at end of file diff --git a/app/service/systems/stock_store.js b/app/service/systems/stock_store.js index cbe2292..42e9ec3 100644 --- a/app/service/systems/stock_store.js +++ b/app/service/systems/stock_store.js @@ -413,6 +413,32 @@ class stockStoreService extends Service { app.logger.warn(`[缓存清理失败] 商品 ${itemId}`, error.message); } } + + /** + * 在给定事务中执行库存写操作,未传入事务时自动创建并提交回滚。 + * + * @param {Object} externalTransaction 外部传入的数据库事务 + * @param {Function} handler 业务处理函数 + * @return {Promise<*>} 业务处理结果 + */ + async _runWithTransaction(externalTransaction, handler) { + const { ctx } = this; + + if (externalTransaction) { + return handler(externalTransaction, true); + } + + const internalTransaction = await ctx.model.transaction(); + try { + const result = await handler(internalTransaction, false); + await internalTransaction.commit(); + return result; + } catch (error) { + await internalTransaction.rollback(); + throw error; + } + } + async lockItemStorages(stockWarehouseId, quantity, transaction) { const { ctx, @@ -592,19 +618,35 @@ class stockStoreService extends Service { } try { - // 2. 获取商品和库存信息(复用) - const stockResult = await this.getItemStorages(itemId, transaction); + return await this._runWithTransaction(transaction, async (currentTransaction, hasExternalTransaction) => { + // 2. 获取商品和库存信息(复用) + const stockResult = await this.getItemStorages(itemId, currentTransaction); - if (!stockResult.success) { - // 入库失败:商品不存在或未绑定 - return stockResult; - } - const { - storage, - } = stockResult.data; + if (!stockResult.success) { + if (hasExternalTransaction) { + throw new Error(stockResult.error); + } + return stockResult; + } + + const { storage } = stockResult.data; + + // 3. 执行库存增加 + if (!storage.exists) { + const failureResult = { + success: false, + error: '库存记录不存在,首次入库需要完整参数', + data: null, + }; + if (hasExternalTransaction) { + throw new Error(failureResult.error); + } + return failureResult; + } + + const beforeQuantity = Number(storage.quantity) || 0; + const beforeLockedQuantity = Number(storage.lockedQuantity) || 0; - // 3. 执行库存增加 - if (storage.exists) { // 非首次入库:更新现有记录(只增加quantity) await ctx.model.StockWarehouse.increment('quantity', { by: inboundQty, @@ -613,50 +655,75 @@ class stockStoreService extends Service { is_valid: 'Y', deleted_at: null, }, - transaction, + transaction: currentTransaction, + }); + + const updatedRecord = await ctx.model.StockWarehouse.findByPk(storage.id, { + transaction: currentTransaction, + raw: true, + }); + + const afterQuantity = Number(updatedRecord.quantity) || 0; + const afterLockedQuantity = Number(updatedRecord.locked_quantity) || 0; + + await ctx.service.systems.stockTransaction.create({ + transaction_type: 'INBOUND', + warehouse_id: updatedRecord.warehouse_id || ctx.user.store_id, + store_id: ctx.user.store_id, + stock_id: storage.id, + storage_id: null, + space_id: null, + quantity: inboundQty, + batch_no: null, + inventory_type: 'ZP', + order_type: 'STOCK_STORE_INBOUND', + order_no: null, + order_id: null, + receiving_id: null, + entry_order_id: null, + operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), + operator_name: ctx.user?.employees_name || '', + remark: '商品入库', + before_quantity: beforeQuantity, + after_quantity: afterQuantity, + before_locked_quantity: beforeLockedQuantity, + after_locked_quantity: afterLockedQuantity, + created_at: new Date(), + }, { + transaction: currentTransaction, }); app.logger.info('[入库] 更新现有库存', { itemId, stockId: storage.id, quantity: inboundQty, - before: storage.quantity, - after: storage.quantity + inboundQty, + before: beforeQuantity, + after: afterQuantity, }); - } else { - // 首次入库:需要创建库存记录(stock_id应该已存在) - // 注意:这里需要更多信息,如warehouse_id等,实际场景可能需要额外参数 - return { - success: false, - error: '库存记录不存在,首次入库需要完整参数', - data: null, - }; - } - // 4. 获取更新后的数据 - const updatedRecord = await ctx.model.StockWarehouse.findByPk(storage.id, { - transaction, - raw: true, + return { + success: true, + data: { + itemId, + stockId: storage.id, + action: 'inbound', + quantity: inboundQty, + beforeQuantity, + afterQuantity, + beforeLocked: beforeLockedQuantity, + afterLocked: afterLockedQuantity, + available: afterQuantity - afterLockedQuantity, + updatedAt: updatedRecord.update_at, + }, + error: null, + }; }); - return { - success: true, - data: { - itemId, - stockId: storage.id, - action: 'inbound', - quantity: inboundQty, - beforeQuantity: storage.quantity, - afterQuantity: updatedRecord.quantity, - beforeLocked: storage.lockedQuantity, - afterLocked: updatedRecord.locked_quantity, - available: updatedRecord.quantity - updatedRecord.locked_quantity, - updatedAt: updatedRecord.update_at, - }, - error: null, - }; - } catch (error) { + if (transaction) { + throw error; + } + app.logger.error('[inbound] 入库失败', { itemId, quantity, @@ -694,107 +761,162 @@ class stockStoreService extends Service { } try { - // 2. 获取商品和库存信息(复用) - const stockResult = await this.getItemStorages(itemId, transaction); + return await this._runWithTransaction(transaction, async (currentTransaction, hasExternalTransaction) => { + // 2. 获取商品和库存信息(复用) + const stockResult = await this.getItemStorages(itemId, currentTransaction); - if (!stockResult.success) { - return stockResult; - } + if (!stockResult.success) { + if (hasExternalTransaction) { + throw new Error(stockResult.error); + } + return stockResult; + } - const { - storage, - } = stockResult.data; + const { storage } = stockResult.data; - // 3. 检查库存是否足够出库 - if (!storage.exists) { - return { - success: false, - error: '库存记录不存在,无法出库', - data: null, - }; - } + // 3. 检查库存是否足够出库 + if (!storage.exists) { + const failureResult = { + success: false, + error: '库存记录不存在,无法出库', + data: null, + }; + if (hasExternalTransaction) { + throw new Error(failureResult.error); + } + return failureResult; + } - // 关键检查:总库存是否足够 - if (storage.quantity < outboundQty) { - return { - success: false, - error: `总库存不足,当前 ${storage.quantity},需求 ${outboundQty}`, - data: null, - }; - } + const beforeQuantity = Number(storage.quantity) || 0; + const beforeLockedQuantity = Number(storage.lockedQuantity) || 0; - // 关键检查:锁定库存是否足够扣减 - if (storage.lockedQuantity < outboundQty) { - return { - success: false, - error: `锁定库存不足,已锁定 ${storage.lockedQuantity},需求 ${outboundQty}`, - data: null, - }; - } + // 关键检查:总库存是否足够 + if (beforeQuantity < outboundQty) { + const failureResult = { + success: false, + error: `总库存不足,当前 ${beforeQuantity},需求 ${outboundQty}`, + data: null, + }; + if (hasExternalTransaction) { + throw new Error(failureResult.error); + } + return failureResult; + } - // 4. 执行出库扣减(同时减少quantity和locked_quantity) - const result = await ctx.model.StockWarehouse.update({ - quantity: app.Sequelize.literal(`quantity - ${outboundQty}`), - locked_quantity: app.Sequelize.literal(`locked_quantity - ${outboundQty}`), - update_at: app.Sequelize.literal('CURRENT_TIMESTAMP'), - }, { - where: { - id: storage.id, - is_valid: 'Y', - deleted_at: null, - // 乐观锁条件:确保更新时库存仍然足够 - quantity: { - [app.Sequelize.Op.gte]: outboundQty, + // 关键检查:锁定库存是否足够扣减 + if (beforeLockedQuantity < outboundQty) { + const failureResult = { + success: false, + error: `锁定库存不足,已锁定 ${beforeLockedQuantity},需求 ${outboundQty}`, + data: null, + }; + if (hasExternalTransaction) { + throw new Error(failureResult.error); + } + return failureResult; + } + + // 4. 执行出库扣减(同时减少quantity和locked_quantity) + const result = await ctx.model.StockWarehouse.update({ + quantity: app.Sequelize.literal(`quantity - ${outboundQty}`), + locked_quantity: app.Sequelize.literal(`locked_quantity - ${outboundQty}`), + update_at: app.Sequelize.literal('CURRENT_TIMESTAMP'), + }, { + where: { + id: storage.id, + is_valid: 'Y', + deleted_at: null, + quantity: { + [app.Sequelize.Op.gte]: outboundQty, + }, + locked_quantity: { + [app.Sequelize.Op.gte]: outboundQty, + }, }, - locked_quantity: { - [app.Sequelize.Op.gte]: outboundQty, - }, - }, - transaction, - }); + transaction: currentTransaction, + }); - if (result[0] === 0) { - return { - success: false, - error: '出库失败:库存已被其他操作修改', - data: null, - }; - } + if (result[0] === 0) { + const failureResult = { + success: false, + error: '出库失败:库存已被其他操作修改', + data: null, + }; + if (hasExternalTransaction) { + throw new Error(failureResult.error); + } + return failureResult; + } - // 5. 获取更新后的数据 - const updatedRecord = await ctx.model.StockWarehouse.findByPk(storage.id, { - transaction, - raw: true, - }); + // 5. 获取更新后的数据 + const updatedRecord = await ctx.model.StockWarehouse.findByPk(storage.id, { + transaction: currentTransaction, + raw: true, + }); - app.logger.info('[出库] 成功', { - itemId, - stockId: storage.id, - quantity: outboundQty, - beforeQuantity: storage.quantity, - afterQuantity: updatedRecord.quantity, - beforeLocked: storage.lockedQuantity, - afterLocked: updatedRecord.locked_quantity, - }); + const afterQuantity = Number(updatedRecord.quantity) || 0; + const afterLockedQuantity = Number(updatedRecord.locked_quantity) || 0; - return { - success: true, - data: { + await ctx.service.systems.stockTransaction.create({ + transaction_type: 'OUTBOUND', + warehouse_id: updatedRecord.warehouse_id || ctx.user.store_id, + store_id: ctx.user.store_id, + stock_id: storage.id, + storage_id: null, + space_id: null, + quantity: outboundQty, + batch_no: null, + inventory_type: 'ZP', + order_type: 'STOCK_STORE_OUTBOUND', + order_no: null, + order_id: null, + receiving_id: null, + entry_order_id: null, + operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), + operator_name: ctx.user?.employees_name || '', + remark: '商品出库', + before_quantity: beforeQuantity, + after_quantity: afterQuantity, + before_locked_quantity: beforeLockedQuantity, + after_locked_quantity: afterLockedQuantity, + created_at: new Date(), + }, { + transaction: currentTransaction, + }); + + app.logger.info('[出库] 成功', { itemId, stockId: storage.id, - action: 'outbound', quantity: outboundQty, - beforeQuantity: storage.quantity, - afterQuantity: updatedRecord.quantity, - beforeLocked: storage.lockedQuantity, - afterLocked: updatedRecord.locked_quantity, - available: updatedRecord.quantity - updatedRecord.locked_quantity, - updatedAt: updatedRecord.update_at, - }, - error: null, - }; + beforeQuantity, + afterQuantity, + beforeLocked: beforeLockedQuantity, + afterLocked: afterLockedQuantity, + }); + + return { + success: true, + data: { + itemId, + stockId: storage.id, + action: 'outbound', + quantity: outboundQty, + beforeQuantity, + afterQuantity, + beforeLocked: beforeLockedQuantity, + afterLocked: afterLockedQuantity, + available: afterQuantity - afterLockedQuantity, + updatedAt: updatedRecord.update_at, + }, + error: null, + }; + }); } catch (error) { + if (transaction) { + throw error; + } + app.logger.error('[outbound] 出库失败', { itemId, quantity, diff --git a/app/service/systems/stock_transaction.js b/app/service/systems/stock_transaction.js index f975737..144efa4 100644 --- a/app/service/systems/stock_transaction.js +++ b/app/service/systems/stock_transaction.js @@ -4,6 +4,84 @@ const Service = require('egg').Service; class StockTransactionService extends Service { + /** + * 统一写入库存流水记录。 + * + * @param {Object} data 流水数据 + * @param {string} data.transaction_type 出入库类型 + * @param {number} data.warehouse_id 仓库ID + * @param {number} data.store_id 货主ID + * @param {number} data.stock_id 商品库存ID + * @param {number} [data.storage_id] 库位库存ID + * @param {number} [data.space_id] 库位ID + * @param {number} data.quantity 变动数量 + * @param {string} [data.batch_no] 批次号 + * @param {string} [data.inventory_type] 库存类型 + * @param {string} [data.order_type] 关联单据类型 + * @param {string} [data.order_no] 关联单据号 + * @param {number} [data.order_id] 关联单据ID + * @param {number} [data.receiving_id] 关联收货单ID + * @param {number} [data.entry_order_id] 关联入库单ID + * @param {string} [data.operator_id] 操作人ID + * @param {string} [data.operator_name] 操作人名称 + * @param {string} [data.remark] 备注 + * @param {number} [data.before_quantity] 变更前总库存数量 + * @param {number} [data.after_quantity] 变更后总库存数量 + * @param {number} [data.before_locked_quantity] 变更前锁定数量 + * @param {number} [data.after_locked_quantity] 变更后锁定数量 + * @param {Date} [data.created_at] 创建时间 + * @param {Object} [options] 写入选项 + * @param {Object} [options.transaction] 数据库事务 + * @return {Promise} 新增的流水记录 + */ + async create(data = {}, options = {}) { + const { ctx } = this; + + const quantity = Number(data.quantity); + if (!data.transaction_type) { + throw new Error('transaction_type 必填'); + } + if (!data.warehouse_id) { + throw new Error('warehouse_id 必填'); + } + if (!data.store_id) { + throw new Error('store_id 必填'); + } + if (!data.stock_id) { + throw new Error('stock_id 必填'); + } + if (!Number.isFinite(quantity) || quantity <= 0) { + throw new Error('quantity 必须为正数'); + } + + const payload = { + transaction_type: data.transaction_type, + warehouse_id: data.warehouse_id, + store_id: data.store_id, + stock_id: data.stock_id, + storage_id: data.storage_id ?? null, + space_id: data.space_id ?? null, + quantity, + batch_no: data.batch_no ?? null, + inventory_type: data.inventory_type || 'ZP', + order_type: data.order_type ?? null, + order_no: data.order_no ?? null, + order_id: data.order_id ?? null, + receiving_id: data.receiving_id ?? null, + entry_order_id: data.entry_order_id ?? null, + operator_id: data.operator_id ?? null, + operator_name: data.operator_name ?? null, + remark: data.remark ?? null, + before_quantity: data.before_quantity ?? null, + after_quantity: data.after_quantity ?? null, + before_locked_quantity: data.before_locked_quantity ?? null, + after_locked_quantity: data.after_locked_quantity ?? null, + created_at: data.created_at || new Date(), + }; + + return ctx.model.StockTransaction.create(payload, options); + } + async list(pageParams = {}, sortParams = {}, groupByBatch = false) { const { ctx, app } = this; const { Op, fn, col, literal } = app.Sequelize; diff --git a/app/service/systems/storage/entry.js b/app/service/systems/storage/entry.js index 9f18bd1..cf85bbf 100644 --- a/app/service/systems/storage/entry.js +++ b/app/service/systems/storage/entry.js @@ -353,6 +353,66 @@ class EntryService extends Service { }; } + /** + * 归一化作废入参中的入库单 ID 列表。 + * 优先使用 ids;未传 ids 时回退到 id。 + * @param {Object} data 请求体 + * @return {{ ok: boolean, ids?: number[], code?: number, message?: string }} 归一化结果 + */ + normalizeCancelEntryOrderIds(data = {}) { + const hasIdsField = Object.prototype.hasOwnProperty.call(data, 'ids'); + const hasIdField = Object.prototype.hasOwnProperty.call(data, 'id'); + + if (!hasIdsField && !hasIdField) { + return { + ok: false, + code: 400, + message: 'id 或 ids 必填', + }; + } + + const rawIds = hasIdsField ? data.ids : [ data.id ]; + + if (hasIdsField) { + if (!Array.isArray(rawIds) || rawIds.length === 0) { + return { + ok: false, + code: 400, + message: 'ids 必须是非空数组', + }; + } + } else if (!Number.isInteger(Number(rawIds[0])) || Number(rawIds[0]) <= 0) { + return { + ok: false, + code: 400, + message: 'id 必填且必须为正整数', + }; + } + + const normalizedIds = []; + for (const rawId of rawIds) { + const normalizedId = Number(rawId); + if (!Number.isInteger(normalizedId) || normalizedId <= 0) { + return { + ok: false, + code: 400, + message: 'ids 必须为正整数数组', + }; + } + normalizedIds.push(normalizedId); + } + + return { + ok: true, + ids: [ ...new Set(normalizedIds) ], + }; + } + + /** + * 查询当前仓库可访问的入库单。 + * @param {number} id 入库单ID + * @return {Promise} 入库单实例 + */ async getOwnedEntryOrderById(id) { const { ctx } = this; return await ctx.model.EntryOrder.findOne({ @@ -585,43 +645,72 @@ class EntryService extends Service { * @return {Promise} code/data/message 结构 */ async cancel(data = {}) { - const orderId = Number(data.id || 0); + const { ctx } = this; + const normalizedResult = this.normalizeCancelEntryOrderIds(data); - if (!orderId) { + if (!normalizedResult.ok) { return { - code: 400, - message: 'id 必填', + code: normalizedResult.code || 400, + message: normalizedResult.message || '参数错误', data: null, }; } - const entryOrder = await this.getOwnedEntryOrderById(orderId); - if (!entryOrder) { - return { - code: 404, - message: '入库单不存在或无权访问', - data: null, - }; + const orderIds = normalizedResult.ids || []; + const entryOrders = []; + + for (const orderId of orderIds) { + const entryOrder = await this.getOwnedEntryOrderById(orderId); + if (!entryOrder) { + return { + code: 404, + message: '入库单不存在或无权访问', + data: null, + }; + } + + if (entryOrder.order_status === 'COMPLETED') { + return { + code: 400, + message: '已完成入库单不允许作废', + data: null, + }; + } + + entryOrders.push(entryOrder); } - if (entryOrder.order_status === 'COMPLETED') { - return { - code: 400, - message: '已完成入库单不允许作废', - data: null, - }; - } + const transaction = ctx.model && typeof ctx.model.transaction === 'function' + ? await ctx.model.transaction() + : null; - await entryOrder.update({ - order_status: 'CANCELLED', - updated_at: new Date(), - }); + try { + const updatedAt = new Date(); + + for (const entryOrder of entryOrders) { + await entryOrder.update({ + order_status: 'CANCELLED', + updated_at: updatedAt, + }, transaction ? { + transaction, + } : undefined); + } + + if (transaction && typeof transaction.commit === 'function') { + await transaction.commit(); + } + } catch (error) { + if (transaction && typeof transaction.rollback === 'function') { + await transaction.rollback(); + } + throw error; + } return { code: 200, message: '作废成功', data: { - id: entryOrder.id, + [orderIds.length === 1 ? 'id' : 'ids']: orderIds.length === 1 ? entryOrders[0].id : orderIds, }, }; } diff --git a/app/service/systems/storage/inventory.js b/app/service/systems/storage/inventory.js index 1cdd5c0..1e63294 100644 --- a/app/service/systems/storage/inventory.js +++ b/app/service/systems/storage/inventory.js @@ -55,8 +55,6 @@ class InventoryService extends Service { await transaction.rollback(); return { code: 404, message: '收货单不存在或无权访问', data: null }; } - - // ────────── 2. 状态校验 ────────── if (receiving.status !== 'completed') { await transaction.rollback(); return { code: 400, message: `收货单状态为 ${receiving.status},须完成收货后才能入库`, data: null }; @@ -158,11 +156,16 @@ class InventoryService extends Service { } // 5b. 增加 StockWarehouse 库存数量 + const beforeQuantity = Number(stockRecord.quantity) || 0; + const beforeLockedQuantity = Number(stockRecord.locked_quantity) || 0; await stockRecord.increment('quantity', { by: inboundQty, transaction, silent: true, }); + await stockRecord.reload({ transaction }); + const afterQuantity = Number(stockRecord.quantity) || 0; + const afterLockedQuantity = Number(stockRecord.locked_quantity) || 0; // 5c. 写入/更新 wms_storage 库存位置表 const spaceId = detail.space_id || 1; // 明细有库位则用,否则默认库位 @@ -233,7 +236,7 @@ class InventoryService extends Service { }, { transaction }); // 5d+. 写入出入库记录 - await ctx.model.StockTransaction.create({ + await ctx.service.systems.stockTransaction.create({ transaction_type: 'INBOUND', warehouse_id: warehouseId, store_id: receiving.store_id || warehouseId, @@ -251,6 +254,10 @@ class InventoryService extends Service { operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), operator_name: ctx.user?.employees_name || '', remark: `快捷入库-收货单 ${receiving.receiving_number}`, + before_quantity: beforeQuantity, + after_quantity: afterQuantity, + before_locked_quantity: beforeLockedQuantity, + after_locked_quantity: afterLockedQuantity, created_at: new Date(), }, { transaction }); @@ -535,11 +542,16 @@ class InventoryService extends Service { continue; } + const beforeQuantity = Number(stockRecord.quantity) || 0; + const beforeLockedQuantity = Number(stockRecord.locked_quantity) || 0; await stockRecord.increment('quantity', { by: actualInbound, transaction, silent: true, }); + await stockRecord.reload({ transaction }); + const afterQuantity = Number(stockRecord.quantity) || 0; + const afterLockedQuantity = Number(stockRecord.locked_quantity) || 0; // 6b. 写入/更新 wms_storage(取第一个收货明细的信息) const firstRcvDetail = rcvGroup[0].detail; @@ -597,7 +609,7 @@ class InventoryService extends Service { } // 6b+. 写入出入库记录 - await ctx.model.StockTransaction.create({ + await ctx.service.systems.stockTransaction.create({ transaction_type: 'INBOUND', warehouse_id: warehouseId, store_id: firstRcv.store_id || warehouseId, @@ -615,6 +627,10 @@ class InventoryService extends Service { operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), operator_name: ctx.user?.employees_name || '', remark: '匹配入库', + before_quantity: beforeQuantity, + after_quantity: afterQuantity, + before_locked_quantity: beforeLockedQuantity, + after_locked_quantity: afterLockedQuantity, created_at: new Date(), }, { transaction }); diff --git a/app/service/systems/storage/receiving.js b/app/service/systems/storage/receiving.js index 8a316e2..847dfa7 100644 --- a/app/service/systems/storage/receiving.js +++ b/app/service/systems/storage/receiving.js @@ -2311,6 +2311,35 @@ class ReceivingService extends Service { return methodMap[normalizedValue] || normalizedValue; } + /** + * 获取完成收货时需要展示的联系字段。 + * @param {Object} receiving 收货单快照。 + * @return {Array} 需要展示的联系字段列表。 + */ + getCompletionContactFields(receiving) { + const deliveryMethod = String((receiving && receiving.delivery_method) || '').trim(); + + if (deliveryMethod === 'truck') { + return [[ '车牌号', receiving && receiving.license_plate ]]; + } + + if (deliveryMethod === 'express') { + return [[ '物流单号', receiving && receiving.tracking_number ]]; + } + + return []; + } + + /** + * 生成收货完成报表的工作表数据。 + * @param {Object} options 报表参数。 + * @param {Object} options.receiving 收货单快照。 + * @param {Object} [options.operator={}] 操作人信息。 + * @param {Object} [options.stats={}] 收货统计数据。 + * @param {Map} [options.detailImageMap=new Map()] 明细图片映射。 + * @param {Array} [options.receivingImages=[]] 收货单图片列表。 + * @return {Array} 工作表列表。 + */ buildCompletionReportSheets({ receiving, operator = {}, @@ -2389,8 +2418,7 @@ class ReceivingService extends Service { [ '收货单号', receiving && receiving.receiving_number ], [ '货主', receiving && receiving.store_name ], [ '来货方式', this.formatDeliveryMethod(receiving && receiving.delivery_method) ], - [ '车牌号', receiving && receiving.license_plate ], - [ '物流单号', receiving && receiving.tracking_number ], + ...this.getCompletionContactFields(receiving), [ '总明细数', stats.total_details || details.length ], [ '已匹配明细数', stats.matched_details || 0 ], [ '未匹配明细数', stats.unmatched_details || 0 ], @@ -2605,13 +2633,24 @@ class ReceivingService extends Service { (completionReport && (completionReport.filename || completionReport.fileKey || completionReport.key)) || `收货完成_${receivingNumber}.xlsx` ).trim(); const title = `收货单${receivingNumber}已完成`; + const contactLines = this.getCompletionContactFields(receiving).map(([ field, value ]) => `${field}:${value || '无'}`); const content = [ - `收货单${receivingNumber}已完成`, - `匹配商品${matchedDetails}件`, - `未匹配商品${unmatchedDetails}件`, - `总数量${totalQuantity}`, - operatorName ? `完成人${operatorName}` : '', - ].filter(Boolean).join(',') + '。'; + `收货单号:${receivingNumber} 已完成`, + `货主:${receiving.store_name || '未知'}`, + `来货方式:${this.formatDeliveryMethod(receiving.delivery_method) || '未知'}`, + ...contactLines, + `总明细数:${Number(stats.total_details || 0)}件`, + `匹配商品:${matchedDetails}件`, + `未匹配商品:${unmatchedDetails}件`, + `总数量:${totalQuantity}`, + `总箱数:${receiving.total_boxes || 0}`, + `总托盘数:${receiving.total_pallets || 0}`, + operatorName ? `完成人:${operatorName}` : '', + `开始时间:${this.formatReportDate(receiving.created_at)}`, + `完成时间:${this.formatReportDate(receiving.receiving_end_time)}`, + `备注:${receiving.remark || '无'}`, + + ].filter(Boolean).join('\n') + '。'; return await noticeService.send({ warehouseId, diff --git a/app/service/systems/store_warehouse.js b/app/service/systems/store_warehouse.js index 38d619c..71e6cb8 100644 --- a/app/service/systems/store_warehouse.js +++ b/app/service/systems/store_warehouse.js @@ -13,12 +13,25 @@ const AUTH_STATUS_LABELS = Object.freeze({ }); class SettingStoreWarehouseService extends Service { + /** + * 创建统一错误对象。 + * + * @param {string} message 错误信息。 + * @param {number} [code=500] HTTP 状态码。 + * @return {Error} 带 code 属性的错误对象。 + */ createError(message, code = 500) { const error = new Error(message); error.code = code; return error; } + /** + * 获取当前登录主体的货主 ID。 + * + * @return {number} 当前主体的货主 ID。 + * @throws {Error} 当无法识别当前主体时抛出,状态码为 400。 + */ getCurrentStoreId() { const storeId = Number(this.ctx.user && this.ctx.user.store_id); if (!Number.isFinite(storeId) || storeId <= 0) { @@ -27,6 +40,12 @@ class SettingStoreWarehouseService extends Service { return storeId; } + /** + * 获取当前登录账号 ID。 + * + * @return {number} 当前登录账号 ID。 + * @throws {Error} 当无法识别当前登录账号时抛出,状态码为 401。 + */ getCurrentAccountId() { const accountId = Number(this.ctx.user && this.ctx.user.id); if (!Number.isFinite(accountId) || accountId <= 0) { @@ -35,6 +54,16 @@ class SettingStoreWarehouseService extends Service { return accountId; } + /** + * 将输入值规范化为正数。 + * + * @param {*} value 待转换的值。 + * @param {string} fieldName 字段名。 + * @param {Object} [options={}] 配置项。 + * @param {boolean} [options.allowEmpty=false] 是否允许空值返回 null。 + * @return {number|null} 规范化后的正数或 null。 + * @throws {Error} 参数非法时抛出,状态码为 400。 + */ toPositiveNumber(value, fieldName, options = {}) { const { allowEmpty = false } = options; if (allowEmpty && (value === undefined || value === null || value === '')) { @@ -48,6 +77,16 @@ class SettingStoreWarehouseService extends Service { return num; } + /** + * 规范化分页参数。 + * + * @param {*} value 待处理的页码或分页大小。 + * @param {string} fieldName 字段名。 + * @param {number} defaultValue 默认值。 + * @param {number} maxValue 最大值。 + * @return {number} 规范化后的分页值。 + * @throws {Error} 参数非法时抛出,状态码为 400。 + */ normalizePage(value, fieldName, defaultValue, maxValue) { if (value === undefined || value === null || value === '') { return defaultValue; @@ -59,6 +98,15 @@ class SettingStoreWarehouseService extends Service { return Math.min(Math.floor(num), maxValue); } + /** + * 规范化状态标记。 + * + * @param {*} value 待处理的状态值。 + * @param {string} fieldName 字段名。 + * @param {number|null} [defaultValue=null] 默认值。 + * @return {number|null} 0、1 或默认值。 + * @throws {Error} 参数非法时抛出,状态码为 400。 + */ normalizeStatusFlag(value, fieldName, defaultValue = null) { if (value === undefined || value === null || value === '') { return defaultValue; @@ -70,6 +118,13 @@ class SettingStoreWarehouseService extends Service { throw this.createError(`${fieldName} 参数不合法`, 400); } + /** + * 规范化签约状态。 + * + * @param {*} value 待处理的签约状态值。 + * @return {number|null} 合法的签约状态或 null。 + * @throws {Error} 参数非法时抛出,状态码为 400。 + */ normalizeAuthStatus(value) { if (value === undefined || value === null || value === '') { return null; @@ -81,6 +136,15 @@ class SettingStoreWarehouseService extends Service { throw this.createError('auth_status 参数不合法', 400); } + /** + * 规范化非负整数。 + * + * @param {*} value 待处理的值。 + * @param {string} fieldName 字段名。 + * @param {number} [defaultValue=0] 默认值。 + * @return {number} 非负整数。 + * @throws {Error} 参数非法时抛出,状态码为 400。 + */ normalizeNonNegativeInteger(value, fieldName, defaultValue = 0) { if (value === undefined || value === null || value === '') { return defaultValue; @@ -92,6 +156,16 @@ class SettingStoreWarehouseService extends Service { return Math.floor(num); } + /** + * 规范化整数。 + * + * @param {*} value 待处理的值。 + * @param {string} fieldName 字段名。 + * @param {Object} [options={}] 配置项。 + * @param {boolean} [options.allowZero=true] 是否允许 0。 + * @return {number} 整数值。 + * @throws {Error} 参数非法时抛出,状态码为 400。 + */ normalizeInteger(value, fieldName, options = {}) { const { allowZero = true } = options; if (value === undefined || value === null || value === '') { @@ -108,6 +182,15 @@ class SettingStoreWarehouseService extends Service { return num; } + /** + * 规范化文本内容。 + * + * @param {*} value 待处理的值。 + * @param {string} fieldName 字段名。 + * @param {number} [maxLength=500] 最大长度。 + * @return {string|null} 规范化后的文本或 null。 + * @throws {Error} 文本超长时抛出,状态码为 400。 + */ normalizeText(value, fieldName, maxLength = 500) { if (value === undefined || value === null) { return null; @@ -119,6 +202,17 @@ class SettingStoreWarehouseService extends Service { return normalized; } + /** + * 规范化区间整数。 + * + * @param {*} value 待处理的值。 + * @param {string} fieldName 字段名。 + * @param {number} defaultValue 默认值。 + * @param {number} minValue 最小值。 + * @param {number} maxValue 最大值。 + * @return {number} 区间内的整数。 + * @throws {Error} 参数非法时抛出,状态码为 400。 + */ normalizeIntegerRange(value, fieldName, defaultValue, minValue, maxValue) { if (value === undefined || value === null || value === '') { return defaultValue; @@ -130,6 +224,13 @@ class SettingStoreWarehouseService extends Service { return Math.floor(num); } + /** + * 规范化邮箱地址。 + * + * @param {*} value 待处理的邮箱值。 + * @return {string|null} 合法邮箱或 null。 + * @throws {Error} 邮箱格式非法时抛出,状态码为 400。 + */ normalizeEmail(value) { const email = this.normalizeText(value, 'email', 100); if (!email) { @@ -143,6 +244,11 @@ class SettingStoreWarehouseService extends Service { return email; } + /** + * 获取策略配置字段清单。 + * + * @return {Array} 策略配置字段数组。 + */ getPolicyConfigFieldList() { const storeWarehouseModel = this.ctx.model && this.ctx.model.StoreWarehouse; if (!storeWarehouseModel || typeof storeWarehouseModel.getPolicyConfigFieldList !== 'function') { @@ -151,6 +257,17 @@ class SettingStoreWarehouseService extends Service { return storeWarehouseModel.getPolicyConfigFieldList(); } + /** + * 规范化策略配置内容。 + * + * @param {*} value 待处理的配置值。 + * @param {string} [fieldName='policy_config'] 字段名。 + * @param {Object} [options={}] 配置项。 + * @param {boolean} [options.allowEmpty=false] 是否允许空值。 + * @param {boolean} [options.sanitizeOnly=false] 是否仅做清洗不做强校验。 + * @return {*|null} 规范化后的策略配置。 + * @throws {Error} 模型未提供规则或参数非法时抛出,对应状态码为 400/500。 + */ normalizePolicyConfig(value, fieldName = 'policy_config', options = {}) { const storeWarehouseModel = this.ctx.model && this.ctx.model.StoreWarehouse; if (!storeWarehouseModel || typeof storeWarehouseModel.normalizePolicyConfig !== 'function') { @@ -168,10 +285,21 @@ class SettingStoreWarehouseService extends Service { } } + /** + * 生成策略配置缓存键。 + * + * @param {number|string} contractId 合同 ID。 + * @return {string} 缓存键。 + */ getPolicyConfigCacheKey(contractId) { return `store_warehouse:policy:${contractId}`; } + /** + * 判断表中是否存在 policy_config 字段。 + * + * @return {Promise} 是否存在该字段。 + */ async hasPolicyConfigColumn() { if (this._hasPolicyConfigColumn !== undefined) { return this._hasPolicyConfigColumn; @@ -188,6 +316,13 @@ class SettingStoreWarehouseService extends Service { return this._hasPolicyConfigColumn; } + /** + * 按合同 ID 读取策略配置。 + * + * @param {number|string} contractId 合同 ID。 + * @param {Object|null} [transaction=null] 事务对象。 + * @return {Promise<*>} 规范化后的策略配置。 + */ async loadPolicyConfigByContractId(contractId, transaction = null) { const normalizedId = Number(contractId || 0); if (normalizedId <= 0) { @@ -218,6 +353,15 @@ class SettingStoreWarehouseService extends Service { }); } + /** + * 按合同 ID 保存策略配置。 + * + * @param {number|string} contractId 合同 ID。 + * @param {*} policyConfig 策略配置内容。 + * @param {Object|null} [transaction=null] 事务对象。 + * @return {Promise} 无返回值。 + * @throws {Error} 合同 ID 非法时抛出,状态码为 400。 + */ async savePolicyConfigByContractId(contractId, policyConfig, transaction = null) { const normalizedId = Number(contractId || 0); if (normalizedId <= 0) { @@ -241,12 +385,25 @@ class SettingStoreWarehouseService extends Service { await this.app.setCacheAsync(this.getPolicyConfigCacheKey(normalizedId), policyConfig, 86400 * 30); } + /** + * 校验当前主体是否为仓库主体。 + * + * @param {Object} currentSubject 当前主体。 + * @param {string} [actionLabel='签约配置'] 操作名称。 + * @return {void} + * @throws {Error} 当前主体不是仓库主体时抛出,状态码为 403。 + */ ensureWarehouseSubject(currentSubject, actionLabel = '签约配置') { if (!currentSubject || !currentSubject.isWarehouse) { throw this.createError(`仅仓库主体可维护${actionLabel}`, 403); } } + /** + * 获取通知服务实例。 + * + * @return {Object|null} 通知服务或 null。 + */ getNoticeService() { const rawNoticeService = this.ctx && this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.notice; if (rawNoticeService && typeof rawNoticeService.send === 'function') { @@ -258,6 +415,20 @@ class SettingStoreWarehouseService extends Service { return null; } + /** + * 发送面单余额调整通知。 + * + * @param {Object} options 通知参数。 + * @param {Object} [options.relation] 签约关系。 + * @param {Object} [options.currentSubject] 当前主体。 + * @param {Object} [options.changeLog] 调整日志。 + * @param {number} [options.operatorId] 操作人 ID。 + * @param {number} [options.changeQuantity] 变更数量。 + * @param {number} [options.balanceBefore] 调整前余额。 + * @param {number} [options.balanceAfter] 调整后余额。 + * @param {string} [options.reason] 调整原因。 + * @return {Promise} 通知发送结果或 null。 + */ async sendPrintQuantityAdjustNotice({ relation, currentSubject, @@ -330,6 +501,12 @@ class SettingStoreWarehouseService extends Service { }); } + /** + * 解析签约关系 ID。 + * + * @param {Object} [data={}] 请求参数。 + * @return {number|null} 关系 ID 或 null。 + */ resolveRelationId(data = {}) { return this.toPositiveNumber( data.id !== undefined ? data.id : (data.contract_id !== undefined ? data.contract_id : data.relation_id), @@ -338,6 +515,16 @@ class SettingStoreWarehouseService extends Service { ); } + /** + * 规范化日期值。 + * + * @param {*} value 待处理的日期值。 + * @param {string} fieldName 字段名。 + * @param {Object} [options={}] 配置项。 + * @param {boolean} [options.allowNull=true] 是否允许空值。 + * @return {Date|null} 规范化后的日期对象或 null。 + * @throws {Error} 日期非法时抛出,状态码为 400。 + */ normalizeDate(value, fieldName, options = {}) { const { allowNull = true } = options; if (value === undefined || value === null || value === '') { @@ -354,6 +541,13 @@ class SettingStoreWarehouseService extends Service { return date; } + /** + * 规范化签约动作。 + * + * @param {*} value 待处理的动作值。 + * @return {string} 规范化后的动作值。 + * @throws {Error} 动作非法时抛出,状态码为 400。 + */ normalizeSignAction(value) { if (value === undefined || value === null || value === '') { return ''; @@ -366,6 +560,13 @@ class SettingStoreWarehouseService extends Service { throw this.createError('action 参数不合法', 400); } + /** + * 规范化临时码。 + * + * @param {*} value 待处理的临时码。 + * @return {string} 大写后的临时码。 + * @throws {Error} 临时码为空或非法时抛出,状态码为 400。 + */ normalizeTempCode(value) { const code = String(value || '').trim().toUpperCase(); if (!code) { @@ -374,18 +575,42 @@ class SettingStoreWarehouseService extends Service { return code; } + /** + * 生成临时码缓存键。 + * + * @param {string} tempCode 临时码。 + * @return {string} 缓存键。 + */ getTempCodeCacheKey(tempCode) { return `store_warehouse:sign:${tempCode}`; } + /** + * 生成临时码。 + * + * @return {string} 临时码。 + */ createTempCode() { return crypto.randomBytes(6).toString('hex').toUpperCase(); } + /** + * 选择当前主体对应的脱敏字段。 + * + * @param {Object} currentSubject 当前主体。 + * @return {string} 脱敏字段名。 + */ pickRemaskField(currentSubject) { return currentSubject && currentSubject.isWarehouse ? 'store_remask' : 'warehouse_remask'; } + /** + * 解析脱敏展示名称。 + * + * @param {Object} data 请求参数。 + * @param {Object} currentSubject 当前主体。 + * @return {string|null} 脱敏名称。 + */ resolveRemaskValue(data, currentSubject) { const raw = data.remask !== undefined ? data.remask @@ -393,6 +618,13 @@ class SettingStoreWarehouseService extends Service { return this.normalizeText(raw, 'remask', 50); } + /** + * 构建当前主体的脱敏字段更新内容。 + * + * @param {Object} data 请求参数。 + * @param {Object} currentSubject 当前主体。 + * @return {Object} 待更新字段对象。 + */ buildCurrentRemaskPatch(data, currentSubject) { const remask = this.resolveRemaskValue(data, currentSubject); if (remask === null) { @@ -404,6 +636,14 @@ class SettingStoreWarehouseService extends Service { }; } + /** + * 构建强制要求的脱敏字段更新内容。 + * + * @param {Object} data 请求参数。 + * @param {Object} currentSubject 当前主体。 + * @return {Object} 待更新字段对象。 + * @throws {Error} 未提供脱敏名称时抛出,状态码为 400。 + */ requireCurrentRemaskPatch(data, currentSubject) { const patch = this.buildCurrentRemaskPatch(data, currentSubject); if (!Object.keys(patch).length) { @@ -412,6 +652,12 @@ class SettingStoreWarehouseService extends Service { return patch; } + /** + * 保存临时签约载荷。 + * + * @param {Object} payload 临时载荷。 + * @return {Promise} 保存后的临时码信息。 + */ async saveTempSignPayload(payload) { const now = Date.now(); const expiresAt = new Date(now + SIGN_TEMP_EXPIRE_SECONDS * 1000).toISOString(); @@ -427,6 +673,13 @@ class SettingStoreWarehouseService extends Service { }; } + /** + * 读取临时签约载荷。 + * + * @param {string} tempCode 临时码。 + * @return {Promise} 临时码与载荷信息。 + * @throws {Error} 临时码无效或已过期时抛出,状态码为 404。 + */ async getTempSignPayload(tempCode) { const normalizedCode = this.normalizeTempCode(tempCode); const payload = await this.app.getCacheAsync(this.getTempCodeCacheKey(normalizedCode)); @@ -439,6 +692,12 @@ class SettingStoreWarehouseService extends Service { }; } + /** + * 清理临时签约载荷。 + * + * @param {string} tempCode 临时码。 + * @return {Promise} 无返回值。 + */ async clearTempSignPayload(tempCode) { const cacheRedis = this.app.redis && this.app.redis.get ? this.app.redis.get('cache') : null; if (cacheRedis && cacheRedis.del) { @@ -448,6 +707,14 @@ class SettingStoreWarehouseService extends Service { await this.app.setCacheAsync(this.getTempCodeCacheKey(tempCode), { consumed: true }, 1); } + /** + * 构建临时签约预览视图。 + * + * @param {string} tempCode 临时码。 + * @param {Object} payload 临时载荷。 + * @param {Object} currentSubject 当前主体。 + * @return {Object} 预览视图对象。 + */ buildTempSignView(tempCode, payload, currentSubject) { const participantIds = [ Number(payload.initiator_subject_id || 0), Number(payload.counterparty_id || 0) ]; const currentSubjectId = Number(currentSubject && currentSubject.id); @@ -483,6 +750,12 @@ class SettingStoreWarehouseService extends Service { }; } + /** + * 获取当前主体信息。 + * + * @return {Promise} 当前主体对象。 + * @throws {Error} 当前主体不存在时抛出,状态码为 404。 + */ async getCurrentSubject() { const { ctx } = this; const storeId = this.getCurrentStoreId(); @@ -506,6 +779,14 @@ class SettingStoreWarehouseService extends Service { }; } + /** + * 获取签约对方主体信息。 + * + * @param {number} counterpartyId 对方主体 ID。 + * @param {string} expectedRole 期望角色。 + * @return {Promise} 对方主体对象。 + * @throws {Error} 对方主体不存在或角色不匹配时抛出,状态码为 400/404。 + */ async getCounterparty(counterpartyId, expectedRole) { const { ctx } = this; const counterparty = await ctx.model.Store.findOne({ @@ -530,6 +811,13 @@ class SettingStoreWarehouseService extends Service { return counterparty; } + /** + * 构建列表查询条件。 + * + * @param {Object} data 请求参数。 + * @param {Object} currentSubject 当前主体。 + * @return {Object} where 查询条件。 + */ buildListWhere(data, currentSubject) { const where = {}; @@ -569,6 +857,11 @@ class SettingStoreWarehouseService extends Service { return where; } + /** + * 获取签约关系关联模型。 + * + * @return {Array} 关联配置数组。 + */ getRelationIncludes() { const { ctx } = this; return [ @@ -587,10 +880,24 @@ class SettingStoreWarehouseService extends Service { ]; } + /** + * 生成奇门合同缓存键。 + * + * @param {string} appKey 应用标识。 + * @param {string} customerId 客户标识。 + * @param {string} warehouseCode 仓库编码。 + * @return {string} 缓存键。 + */ getQimenContractCacheKey(appKey, customerId, warehouseCode) { return `contract:${appKey}:${customerId}:${warehouseCode}`; } + /** + * 清理奇门合同缓存。 + * + * @param {Array} configs 配置列表。 + * @return {Promise} 无返回值。 + */ async clearQimenContractCache(configs = []) { const cacheRedis = this.app.redis && this.app.redis.get ? this.app.redis.get('cache') : null; const keys = [ ...new Set(configs.map(item => { @@ -622,6 +929,18 @@ class SettingStoreWarehouseService extends Service { await Promise.all(keys.map(key => this.app.setCacheAsync(key, null, 1).catch(() => null))); } + /** + * 获取接口类型。 + * + * @param {Object} [data={}] 请求参数。 + * @param {Object} [options={}] 选项。 + * @param {boolean} [options.allowDisabled=false] 是否允许禁用接口类型。 + * @param {Object|null} [options.transaction=null] 事务对象。 + * @param {boolean} [options.requireId=false] 是否必须传入 interface_type_id。 + * @param {string|null} [options.interfaceCategory=null] 接口分类。 + * @return {Promise} 接口类型对象。 + * @throws {Error} 参数非法或接口类型不存在时抛出,状态码为 400/404。 + */ async getApiInterfaceType(data = {}, options = {}) { const { ctx } = this; const { allowDisabled = false, transaction = null, requireId = false, interfaceCategory = null } = options; @@ -655,10 +974,23 @@ class SettingStoreWarehouseService extends Service { return interfaceType; } + /** + * 获取奇门接口类型。 + * + * @param {Object} [data={}] 请求参数。 + * @param {Object} [options={}] 选项。 + * @return {Promise} 接口类型对象。 + */ async getQimenInterfaceType(data = {}, options = {}) { return this.getApiInterfaceType(data, options); } + /** + * 序列化奇门配置。 + * + * @param {Object} config 配置实例或普通对象。 + * @return {Object|null} 序列化后的配置对象。 + */ serializeQimenConfig(config) { if (!config) { return null; @@ -697,6 +1029,16 @@ class SettingStoreWarehouseService extends Service { }; } + /** + * 获取奇门配置映射。 + * + * @param {Array} contractIds 合同 ID 列表。 + * @param {Object} [options={}] 选项。 + * @param {boolean} [options.allowDisabled=true] 是否允许禁用接口类型。 + * @param {number|null} [options.interfaceTypeId=null] 指定接口类型 ID。 + * @param {Object|null} [options.transaction=null] 事务对象。 + * @return {Promise} 合同 ID 到配置的映射。 + */ async getQimenConfigMap(contractIds = [], options = {}) { const { ctx } = this; const { allowDisabled = true, interfaceTypeId = null, transaction = null } = options; @@ -743,11 +1085,26 @@ class SettingStoreWarehouseService extends Service { return configMap; } + /** + * 获取单个奇门配置。 + * + * @param {number|string} contractId 合同 ID。 + * @param {Object} [options={}] 选项。 + * @return {Promise} 单个配置对象或 null。 + */ async getSingleQimenConfig(contractId, options = {}) { const configMap = await this.getQimenConfigMap([ contractId ], options); return configMap.get(Number(contractId)) || null; } + /** + * 解析成对的合同主体 ID。 + * + * @param {Object} data 请求参数。 + * @param {Object} currentSubject 当前主体。 + * @return {Object} 包含 storeId、warehouseId、counterpartyId 的对象。 + * @throws {Error} 对方主体参数非法时抛出,状态码为 400。 + */ resolvePairIds(data, currentSubject) { const fieldName = currentSubject.isWarehouse ? 'store_id / counterparty_id' : 'warehouse_id / counterparty_id'; const rawCounterpartyId = data.counterparty_id !== undefined @@ -770,6 +1127,14 @@ class SettingStoreWarehouseService extends Service { }; } + /** + * 序列化签约关系。 + * + * @param {Object} relation 签约关系实例或普通对象。 + * @param {Object} currentSubject 当前主体。 + * @param {Object|null} [qimenConfig=null] 奇门配置。 + * @return {Object} 序列化后的签约关系对象。 + */ serializeRelation(relation, currentSubject, qimenConfig = null) { const item = relation && typeof relation.get === 'function' ? relation.get({ plain: true }) @@ -829,6 +1194,15 @@ class SettingStoreWarehouseService extends Service { }; } + /** + * 获取受限范围内的签约关系。 + * + * @param {Object} data 请求参数。 + * @param {Object} currentSubject 当前主体。 + * @param {Object} transaction 事务对象。 + * @return {Promise} 签约关系实例。 + * @throws {Error} 签约关系不存在或无权限操作时抛出,状态码为 404。 + */ async findScopedRelation(data, currentSubject, transaction) { const { ctx } = this; const where = currentSubject.isWarehouse @@ -857,6 +1231,12 @@ class SettingStoreWarehouseService extends Service { return relation; } + /** + * 查询签约关系列表。 + * + * @param {Object} [data={}] 请求参数。 + * @return {Promise} 接口响应对象。 + */ async list(data = {}) { const { ctx, app } = this; const { Op } = app.Sequelize; @@ -912,6 +1292,12 @@ class SettingStoreWarehouseService extends Service { }; } + /** + * 发起或确认签约。 + * + * @param {Object} [data={}] 请求参数。 + * @return {Promise} 接口响应对象。 + */ async sign(data = {}) { const action = this.normalizeSignAction(data.action || data.mode); if (data.temp_code || data.tempCode || action === 'preview') { @@ -1081,6 +1467,12 @@ class SettingStoreWarehouseService extends Service { }; } + /** + * 修改签约关系脱敏名称。 + * + * @param {Object} [data={}] 请求参数。 + * @return {Promise} 接口响应对象。 + */ async rename(data = {}) { const { ctx } = this; const transaction = await ctx.model.transaction(); @@ -1134,6 +1526,12 @@ class SettingStoreWarehouseService extends Service { } } + /** + * 调整面单余额。 + * + * @param {Object} [data={}] 请求参数。 + * @return {Promise} 接口响应对象。 + */ async adjustPrintQuantity(data = {}) { const { ctx } = this; const transaction = await ctx.model.transaction(); @@ -1263,6 +1661,11 @@ class SettingStoreWarehouseService extends Service { } } + /** + * 获取策略配置字段。 + * + * @return {Promise} 接口响应对象。 + */ async getPolicyConfigFields() { return { code: 200, @@ -1270,6 +1673,12 @@ class SettingStoreWarehouseService extends Service { }; } + /** + * 获取签约策略配置。 + * + * @param {Object} [data={}] 请求参数。 + * @return {Promise} 接口响应对象。 + */ async getPolicyConfig(data = {}) { const currentSubject = await this.getCurrentSubject(); const relation = await this.findScopedRelation(data, currentSubject); @@ -1288,6 +1697,12 @@ class SettingStoreWarehouseService extends Service { }; } + /** + * 保存签约策略配置。 + * + * @param {Object} [data={}] 请求参数。 + * @return {Promise} 接口响应对象。 + */ async savePolicyConfig(data = {}) { const { ctx } = this; const transaction = await ctx.model.transaction(); @@ -1345,6 +1760,12 @@ class SettingStoreWarehouseService extends Service { } } + /** + * 查询接口配置列表。 + * + * @param {Object} [data={}] 请求参数。 + * @return {Promise} 接口响应对象。 + */ async listApiConfig(data = {}) { const { ctx } = this; const currentSubject = await this.getCurrentSubject(); @@ -1388,6 +1809,12 @@ class SettingStoreWarehouseService extends Service { }; } + /** + * 保存接口配置。 + * + * @param {Object} [data={}] 请求参数。 + * @return {Promise} 接口响应对象。 + */ async saveApiConfig(data = {}) { const { ctx, app } = this; const transaction = await ctx.model.transaction(); @@ -1589,6 +2016,12 @@ class SettingStoreWarehouseService extends Service { } } + /** + * 删除奇门接口配置。 + * + * @param {Object} [data={}] 请求参数。 + * @return {Promise} 接口响应对象。 + */ async deleteQimenConfig(data = {}) { const { ctx } = this; const transaction = await ctx.model.transaction(); @@ -1670,6 +2103,12 @@ class SettingStoreWarehouseService extends Service { } } + /** + * 解绑签约关系。 + * + * @param {Object} [data={}] 请求参数。 + * @return {Promise} 接口响应对象。 + */ async unbind(data = {}) { const { ctx } = this; const transaction = await ctx.model.transaction(); diff --git a/app/service/systems/upload.js b/app/service/systems/upload.js index cff423f..c79f78d 100644 --- a/app/service/systems/upload.js +++ b/app/service/systems/upload.js @@ -11,8 +11,37 @@ class UploadService extends Service { super(ctx); this.initCOS(); } + + /** + * 获取腾讯云公共配置。 + * + * 说明:优先读取独立的腾讯云公共配置,若不存在则回退到兼容的 COS 配置, + * 以保证历史配置方式仍然可用。 + * + * @returns {Object} 腾讯云公共配置对象 + */ + getTencentCloudConfig() { + const tencentCloudConfig = this.config.tencentCloud || {}; + const cosConfig = this.config.cos || {}; + + return { + appId: tencentCloudConfig.appId ?? cosConfig.appId, + secretId: tencentCloudConfig.secretId ?? cosConfig.secretId, + secretKey: tencentCloudConfig.secretKey ?? cosConfig.secretKey, + }; + } + + /** + * 获取 COS 产品配置。 + * + * @returns {Object} COS 产品配置对象 + */ + getCosConfig() { + return this.config.cos || {}; + } + initCOS() { - const { secretId, secretKey } = this.config.cos; + const { secretId, secretKey } = this.getTencentCloudConfig(); this.cos = new COS({ SecretId: secretId, SecretKey: secretKey, @@ -26,6 +55,8 @@ class UploadService extends Service { */ async getUploadParams(fileInfo) { const { ctx } = this; + const cosConfig = this.getCosConfig(); + const tencentCloudConfig = this.getTencentCloudConfig(); const warehouseId = ctx.user.store_id; const { fileName, fileType, fileSize, type, md5 } = fileInfo; @@ -71,7 +102,7 @@ class UploadService extends Service { // 获取当前时间戳 const now = Math.floor(Date.now() / 1000); - const expire = now + this.config.cos.expire; + const expire = now + cosConfig.expire; const keyTime = `${now};${expire}`; // 使用与PHP一致的算法生成签名 @@ -80,11 +111,11 @@ class UploadService extends Service { // 构建返回参数 return { fileName: cosFileName, - uploadUrl: `https://${this.config.cos.bucket}.cos.${this.config.cos.region}.myqcloud.com`, - bucket: this.config.cos.bucket, - region: this.config.cos.region, + uploadUrl: `https://${cosConfig.bucket}.cos.${cosConfig.region}.myqcloud.com`, + bucket: cosConfig.bucket, + region: cosConfig.region, signature: { - secretId: this.config.cos.secretId, + secretId: tencentCloudConfig.secretId, signature, keyTime, key: cosFileName, @@ -94,7 +125,7 @@ class UploadService extends Service { key: cosFileName, policy, 'q-sign-algorithm': 'sha1', - 'q-ak': this.config.cos.secretId, + 'q-ak': tencentCloudConfig.secretId, 'q-sign-time': keyTime, 'q-key-time': keyTime, 'q-signature': signature, @@ -113,7 +144,7 @@ class UploadService extends Service { md5, }, // 有效期 - expires: this.config.cos.expire, + expires: cosConfig.expire, // 前端需要的额外参数 frontendConfig: this.getFrontendConfig(fileType, fileSize), isNew: true, @@ -129,7 +160,7 @@ class UploadService extends Service { * @param {number} expireTime 过期时间戳 */ generatePolicyAndSignature(key, startTime, expireTime) { - const { secretId, secretKey } = this.config.cos; + const { secretId, secretKey } = this.getTencentCloudConfig(); const keyTime = `${startTime};${expireTime}`; // 1. 生成策略 - 与PHP完全一致 @@ -178,7 +209,7 @@ class UploadService extends Service { * @param {number} root0.fileSize 文件大小 */ validateFileInfo({ fileName, fileSize }) { - const { maxsize, mimetype } = this.config.cos; + const { maxsize, mimetype } = this.getCosConfig(); // 验证文件大小 const maxSizeBytes = this.parseSizeToBytes(maxsize); @@ -205,7 +236,7 @@ class UploadService extends Service { * @param {string} md5 文件 MD5 */ generateFileName(fileName, fileType, category = '', md5) { - const { savekey, dirs } = this.config.cos; + const { savekey, dirs } = this.getCosConfig(); const ext = path.extname(fileName); const name = path.basename(fileName, ext); const timestamp = dayjs().format('YYYYMMDDHHmmss'); @@ -285,7 +316,7 @@ class UploadService extends Service { * @param {number} fileSize 文件大小 */ getFrontendConfig(fileType, fileSize) { - const { chunkSize } = this.config.cos; + const { chunkSize } = this.getCosConfig(); return { useMultipart: fileSize > 5 * 1024 * 1024, @@ -304,7 +335,7 @@ class UploadService extends Service { * @param {Object} options 上传选项 */ async uploadFile(fileStream, options = {}) { - const { bucket, region } = this.config.cos; + const { bucket, region, uploadurl, cdnurl } = this.getCosConfig(); try { this.validateFile(fileStream, options); @@ -326,9 +357,9 @@ class UploadService extends Service { return { fileName, - cosUrl: `${this.config.cos.uploadurl}/${fileName}`, - cdnUrl: `${this.config.cos.cdnurl}/${fileName}`, - url: `${this.config.cos.cdnurl}/${fileName}`, + cosUrl: `${uploadurl}/${fileName}`, + cdnUrl: `${cdnurl}/${fileName}`, + url: `${cdnurl}/${fileName}`, etag: result.ETag, location: result.Location, uploadAt: new Date().toISOString(), @@ -345,7 +376,7 @@ class UploadService extends Service { * @param {Object} options 上传选项 */ validateFile(fileStream, options = {}) { - const { maxsize, mimetype } = this.config.cos; + const { maxsize, mimetype } = this.getCosConfig(); const { filename, fileSize } = fileStream; const maxSizeBytes = this.parseSizeToBytes(maxsize); @@ -378,6 +409,7 @@ class UploadService extends Service { */ async uploadSuccessNotify(data) { const { ctx } = this; + const cosConfig = this.getCosConfig(); try { // 从上下文获取用户信息(根据你的实际用户认证方式) const warehouseId = ctx.user?.store_id || ctx.query.warehouseId || ctx.request.body.warehouseId; @@ -394,7 +426,7 @@ class UploadService extends Service { const resolvedFileSize = Number(data.fileSize || data.size || 0); // 生成完整的访问URL - const fileUrl = `${this.config.cos.cdnurl || this.config.cos.uploadurl}/${resolvedFileKey}`; + const fileUrl = `${cosConfig.cdnurl || cosConfig.uploadurl}/${resolvedFileKey}`; // 计算哈希值(如果前端没有提供) let md5Hash = data.md5Hash || data.md5 || ''; diff --git a/config/config.default.js b/config/config.default.js index 289a620..b9f1c46 100644 --- a/config/config.default.js +++ b/config/config.default.js @@ -18,6 +18,7 @@ module.exports = appInfo => { const userConfig = { // myAppName: 'egg', }; + const tencentCloudConfig = require('./tencent-cloud'); config.redis = { clients: { cache: { @@ -43,10 +44,11 @@ module.exports = appInfo => { appKey: 23535631, security: 'd0cbd3935e3afa2b42b5dc600c08a795', }; + config.tencentCloud = { + ...tencentCloudConfig, + }; config.cos = { - appId: 1234567890, - secretId: 'AKIDeFhx1tQ5PYVYP9K8PXUFoazHRPBlpTXP', - secretKey: 'pcHtKbhcKqDNLqEQRIxRjpjRHxTnvGQT', + ...config.tencentCloud, bucket: 'ye4s-1255377868', region: 'ap-guangzhou', uploadurl: 'https://ye4s-1255377868.cos.ap-guangzhou.myqcloud.com', diff --git a/database/migrations/20260408140000-create-wms-stock-transaction.js b/database/migrations/20260408140000-create-wms-stock-transaction.js index 08e5ca0..1ef7427 100644 --- a/database/migrations/20260408140000-create-wms-stock-transaction.js +++ b/database/migrations/20260408140000-create-wms-stock-transaction.js @@ -56,6 +56,26 @@ module.exports = { allowNull: false, comment: '变动数量(正数)', }, + before_quantity: { + type: INTEGER(12), + allowNull: true, + comment: '变更前总库存数量', + }, + after_quantity: { + type: INTEGER(12), + allowNull: true, + comment: '变更后总库存数量', + }, + before_locked_quantity: { + type: INTEGER(12), + allowNull: true, + comment: '变更前锁定数量', + }, + after_locked_quantity: { + type: INTEGER(12), + allowNull: true, + comment: '变更后锁定数量', + }, batch_no: { type: STRING(100), allowNull: true, diff --git a/database/migrations/20260409120000-add-snapshot-columns-to-wms-stock-transaction.js b/database/migrations/20260409120000-add-snapshot-columns-to-wms-stock-transaction.js new file mode 100644 index 0000000..0909653 --- /dev/null +++ b/database/migrations/20260409120000-add-snapshot-columns-to-wms-stock-transaction.js @@ -0,0 +1,63 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + const { INTEGER } = Sequelize; + const tableName = 'wms_stock_transaction'; + const tableInfo = await queryInterface.describeTable(tableName); + + const columns = [ + [ 'before_quantity', { + type: INTEGER(12), + allowNull: true, + comment: '变更前总库存数量', + }], + [ 'after_quantity', { + type: INTEGER(12), + allowNull: true, + comment: '变更后总库存数量', + }], + [ 'before_locked_quantity', { + type: INTEGER(12), + allowNull: true, + comment: '变更前锁定数量', + }], + [ 'after_locked_quantity', { + type: INTEGER(12), + allowNull: true, + comment: '变更后锁定数量', + }], + ]; + + for (const [ columnName, columnDefinition ] of columns) { + if (tableInfo[columnName]) { + continue; + } + + await queryInterface.addColumn(tableName, columnName, columnDefinition); + } + }, + + async down(queryInterface) { + const tableName = 'wms_stock_transaction'; + const tableInfo = await queryInterface.describeTable(tableName).catch(() => null); + if (!tableInfo) { + return; + } + + const columns = [ + 'after_locked_quantity', + 'before_locked_quantity', + 'after_quantity', + 'before_quantity', + ]; + + for (const columnName of columns) { + if (!tableInfo[columnName]) { + continue; + } + + await queryInterface.removeColumn(tableName, columnName); + } + }, +}; diff --git a/docs/qimen-interface-reference.md b/docs/qimen-interface-reference.md new file mode 100644 index 0000000..70a0a5a --- /dev/null +++ b/docs/qimen-interface-reference.md @@ -0,0 +1,226 @@ +# 奇门接口技术备忘 + +## 1. 文档来源 + +- 官方来源:open.taobao.com 文档,docId=118403,页面章节为“5. 接口说明” +- 适用对象:WMS 与 ERP 之间的奇门对接排障、接口回查、协议备忘 +- 本文目标:把官方白皮书里的核心调用约定、接口地图和本地实现入口沉淀到仓库内,便于技术备用 + +## 2. 接入总览 + +奇门接口的统一特征是: + +- 请求方式以 POST 为主 +- query 中携带 app_key、method、v、format、sign_method、sign、timestamp 等标准参数 +- body 使用 XML,根节点通常为 request +- 响应也使用 XML,根节点通常为 response +- 响应通常包含 flag、code、message 三个固定字段 + +官方白皮书中明确说明: + +- 很多接口是同步接口,返回 success 不只是“消息接收成功”,而是代表业务已处理完成 +- 批量接口通常会在一个订单下承载多个 item 或 order 节点 +- 非叶子节点通常允许增加 remark 和 extendProps + +## 3. 通用字段与约定 + +### 3.1 常见主键字段 + +- ownerCode:货主编码 +- warehouseCode:仓库编码,统仓统配等场景常填 OTHER +- itemCode:ERP 商品编码 +- itemId:WMS 商品编码或仓储系统商品 ID,通常是条件必填 +- orderCode:单据编码 +- orderId:仓储系统单据编码 +- outBizCode:外部业务编码,常作为幂等键 + +### 3.2 常见状态枚举 + +订单类状态常见值: + +- NEW:未开始处理 +- ACCEPT:仓库接单 +- PRINT:打印 +- PICK:拣货 +- CHECK:复核 +- PACKAGE:打包 +- WEIGH:称重 +- READY:待提货 +- DELIVERED:已发货 +- PARTDELIVERED:部分发货完成 +- PARTFULFILLED:部分收货完成 +- FULFILLED:收货完成 +- EXCEPTION:异常 +- CANCELED:取消 +- CLOSED:关闭 +- REJECT:拒单 +- REFUSE:客户拒签 +- SIGN:签收 + +库存类常见值: + +- ZP:正品 +- CC:残次 +- JS:机损 +- XS:箱损 +- FP:废品 +- ZT:在途库存 +- DJ:冻结 +- OTHER:其他 + +### 3.3 常见业务规则 + +- 组合商品、条码、批次、生产日期、过期日期、生产批号等字段在多个接口里复用 +- 一些接口对 itemId 有条件必填要求,通常与仓库是否自定义 WMS 商品编码有关 +- 多次收货、多次发货、多次确认类接口会使用 confirmType +- 分批发送时,totalOrderLines 常用于说明总行数,接收方据此判断是否收齐 + +## 4. 接口地图 + +以下为官方文档 5.x 章节的接口目录,按业务域整理。 + +### 4.1 商品与商品映射 + +- 5.1 商品查询接口:taobao.qimen.singleitem.query / singleitem.query +- 5.2 商品同步接口:taobao.qimen.singleitem.synchronize / singleitem.synchronize +- 5.3 商品同步接口(批量):taobao.qimen.items.synchronize / items.synchronize +- 5.4 组合商品接口:taobao.qimen.combineitem.synchronize / combineitem.synchronize +- 5.5 创建前后端商品映射接口:taobao.qimen.itemmapping.create / itemmapping.create +- 5.6 前后端商品映射查询接口:taobao.qimen.itemmapping.query / itemmapping.query + +### 4.2 入库与退货入库 + +- 5.7 入库单创建接口:taobao.qimen.entryorder.create / entryorder.create +- 5.8 入库单确认接口:taobao.qimen.entryorder.confirm / entryorder.confirm +- 5.9 入库单查询接口:taobao.qimen.entryorder.query / entryorder.query +- 5.10 退货入库单创建接口:taobao.qimen.returnorder.create / returnorder.create +- 5.11 退货入库单确认接口:taobao.qimen.returnorder.confirm / returnorder.confirm +- 5.12 退货入库单查询接口:taobao.qimen.returnorder.query / returnorder.query + +### 4.3 出库、发货与确认 + +- 5.13 出库单创建接口:taobao.qimen.stockout.create / stockout.create +- 5.14 出库单确认接口:taobao.qimen.stockout.confirm / stockout.confirm +- 5.15 出库单查询接口:taobao.qimen.stockout.query / stockout.query +- 5.16 发货单创建接口:taobao.qimen.deliveryorder.create / deliveryorder.create +- 5.17 发货单创建接口(批量):taobao.qimen.deliveryorder.batchcreate / deliveryorder.batchcreate +- 5.18 发货单创建结果通知接口(批量):taobao.qimen.deliveryorder.batchcreate.answer / deliveryorder.batchcreate.answer +- 5.19 发货单确认接口:taobao.qimen.deliveryorder.confirm / deliveryorder.confirm +- 5.20 发货单确认接口(批量):taobao.qimen.deliveryorder.batchconfirm / deliveryorder.batchconfirm +- 5.21 发货单查询接口:taobao.qimen.deliveryorder.query / deliveryorder.query + +### 4.4 SN 与订单流水 + +- 5.22 订单SN通知接口:taobao.qimen.order.sn.report / order.sn.report +- 5.23 发货单SN通知接口:taobao.qimen.sn.report / sn.report +- 5.24 订单流水查询接口:taobao.qimen.orderprocess.query / orderprocess.query +- 5.25 订单状态查询接口(批量):taobao.qimen.orderstatus.batchquery / orderstatus.batchquery +- 5.26 订单流水通知接口:taobao.qimen.orderprocess.report / orderprocess.report +- 5.27 订单异常通知接口:taobao.qimen.orderexception.report / orderexception.report + +### 4.5 异常、退货、缺货与挂起 + +- 5.28 退货异常包裹单通知接口:taobao.qimen.returnapply.report / returnapply.report +- 5.29 退货包裹状态通知接口:taobao.qimen.returnpackage.report / returnpackage.report +- 5.30 发货单缺货通知接口:taobao.qimen.itemlack.report / itemlack.report +- 5.31 发货单缺货查询接口:taobao.qimen.itemlack.query / itemlack.query +- 5.32 单据取消接口:taobao.qimen.order.cancel / order.cancel +- 5.33 单据挂起(恢复)接口:taobao.qimen.order.pending / order.pending + +### 4.6 库存、仓库、加工与异动 + +- 5.34 库存查询接口(多商品):taobao.qimen.inventory.query / inventory.query +- 5.35 库存查询接口(多条件):taobao.qimen.stock.query / stock.query +- 5.36 仓库查询接口:taobao.qimen.warehouseinfo.query / warehouseinfo.query +- 5.37 仓库同步接口:taobao.qimen.warehouseinfo.synchronize / warehouseinfo.synchronize +- 5.38 库存盘点通知接口:taobao.qimen.inventory.report / inventory.report +- 5.39 库存盘点查询接口:taobao.qimen.inventorycheck.query / inventorycheck.query +- 5.40 仓内加工单创建接口:taobao.qimen.storeprocess.create / storeprocess.create +- 5.41 仓内加工单确认接口:taobao.qimen.storeprocess.confirm / storeprocess.confirm +- 5.42 库存异动通知接口:taobao.qimen.stockchange.report / stockchange.report + +### 4.7 店铺、波次、调拨、规则与统计 + +- 5.43 店铺同步接口:taobao.qimen.shop.synchronize / shop.synchronize +- 5.44 发货单波次通知接口:taobao.qimen.wavenum.report / wavenum.report +- 5.45 调拨单创建接口:taobao.qimen.transferorder.create / transferorder.create +- 5.46 调拨单查询接口:taobao.qimen.transferorder.query / transferorder.query +- 5.47 调拨单通知接口:taobao.qimen.transferorder.report / transferorder.report +- 5.48 渠道间库存规则设置接口:taobao.qimen.inventoryrule.create / inventoryrule.create +- 5.49 库存汇总报表查询接口:taobao.qimen.inventorysum.query / inventorysum.query +- 5.50 订单出库统计查询接口:taobao.qimen.deliveryordersum.query / deliveryordersum.query + +### 4.8 基础能力 + +- 5.51 心跳接口:taobao.qimen.service.heartbeat / service.heartbeat +- 5.52 供应商信息同步接口:taobao.qimen.supplier.synchronize / supplier.synchronize +- 5.53 配送公司信息查询:taobao.qimen.expressinfo.query / expressinfo.query + +## 5. 官方白皮书里的关键细节 + +### 5.1 商品接口 + +- 单品查询与单品同步字段高度一致,itemCode、itemName、barCode、itemType、brand、重量、尺寸、批次、保质期相关字段都会复用 +- 批量商品同步使用 items 节点包裹 item 列表 +- 组合商品接口的核心是 itemCode、ownerCode、warehouseCode 与子商品清单 + +### 5.2 入库与退货入库 + +- entryorder.create 与 returnorder.create 都是同步创建 +- confirm 接口用于最终状态回告,不只是接收消息 +- 订单行内常包含 itemCode、itemId、planQty、actualQty、inventoryType、batchCode、productDate、expireDate、produceCode +- 入库场景支持 relatedOrders 关联单据信息 + +### 5.3 出库与发货 + +- stockout 更偏普通出库,不强调订单履约语义 +- deliveryorder 更偏订单驱动发货 +- 批量版 create/confirm 接口支持 orders 与 order 节点 +- 发货单确认会带包裹、发票、物流、重量、体积、SN、批次等信息 + +### 5.4 库存与盘点 + +- inventory.query 与 stock.query 都是库存查询,但入参组织方式不同 +- inventory.report 与 inventorycheck.query 用于盘点回传和盘点查询 +- stockchange.report 用于把引起库存变动的单据和库存变化同步给 ERP + +### 5.5 组织与基础资料 + +- warehouseinfo.query / synchronize 处理仓库基础资料 +- shop.synchronize 处理店铺基础资料 +- supplier.synchronize 处理供应商基础资料 +- expressinfo.query 处理配送公司信息 + +## 6. 本地实现落点 + +当前仓库里与奇门相关的本地实现入口主要是: + +- app/service/qimen.js:统一 XML 解析、method 路由与 XML 响应封装 +- app/service/qimenMethods/:具体奇门业务方法实现目录 +- typings/app/service/index.d.ts:qimenMethods 的类型入口 +- methods/qimen.json:当前奇门方法定义与参数结构的主索引 +- methods/changes/qimen.json:奇门文档变更记录副本 + +从代码层看,qimen.js 会先解析 XML,再根据 method 对应到 qimenMethods 下的具体模块调用。 + +## 7. 排障时的实用检查点 + +1. 先确认 method 名是否与官方文档一致,尤其是 singleitem、deliveryorder、entryorder、returnorder、stockout、inventory 这些主模块 +2. 再确认 XML 根节点和字段名是否和官方定义一致,奇门对字段名大小写和层级通常比较敏感 +3. 关注 itemId 是否被误传为空,很多接口里它是条件必填 +4. 关注 warehouseCode 是否在统仓统配场景下正确使用 OTHER +5. 批量接口要核对 totalOrderLines、currentPage、pageSize 和明细数量是否一致 +6. 发生返回 success 但业务未落库时,要继续检查本地实现是否只是接收成功而不是业务处理成功 + +## 8. 结论 + +这份奇门白皮书覆盖了 WMS 与 ERP 对接的完整主干能力,核心可以归纳为: + +- 商品主数据 +- 入库、退货入库、出库、发货 +- SN、流水、状态、异常 +- 库存、盘点、加工、异动 +- 仓库、店铺、供应商、配送公司基础资料 +- 调拨、波次、缺货、规则、统计与心跳 + +在本仓库中,奇门的本地实现已经有统一入口和方法分层,适合把本文作为日常联调与故障排查的快速备忘。 \ No newline at end of file diff --git a/methods/changes/system.json b/methods/changes/system.json index e280450..b10aa81 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -271,4 +271,49 @@ "summary": "将 storage.stockout.toOrder 标记为占位接口", "detail": "storage.stockout.toOrder 当前仅保留方法名用于后续扩展,暂不开放实际逻辑。调用时返回 code=405、message=占位接口,暂未开放。" } + , + { + "version": "2026.04.09-system-01", + "date": "2026-04-09", + "summary": "storage.entry.cancel 支持批量作废,新增 ids 入参并兼容单条 id", + "methods": [ + "storage.entry.cancel" + ], + "notes": [ + "新增入参 `ids`(number[])以支持批量作废,兼容旧入参 `id`;当同时传入 `ids` 与 `id` 时以 `ids` 为准。", + "参数校验:`ids` 必须为非空数组;非法 ID 或空数组返回 400。", + "业务约束:已完成/已作废/处于不可作废状态的单据不允许作废;批量场景下任一单据不存在或状态不允许时整体返回 404/400,未执行部分更新。", + "响应说明:单条作废返回字段 `id`(number);批量作废返回字段 `ids`(number[])。", + "已同步更新 methods/system.json(storage.entry.cancel)为 SSOT。" + ] + } + , + { + "id": "2026.04.09-system-02", + "date": "2026-04-09", + "method": "index.recognizeLicensePlate", + "type": "added", + "summary": "新增基础模块车牌识别接口 index.recognizeLicensePlate", + "detail": "新增 recognizeLicensePlate 方法,归属基础模块(index),接收 base64 图片(字段 base64/ imageBase64/ image_base64),返回识别结果包含 licensePlate, plateNumber, color, confidence, requestId, imageSize, rawData。isNeedAuth=false, isNeedLogin=true。", + "notes": [ + "入参:base64(string,必填)或 imageBase64/image_base64(兼容)", + "响应:返回归一化后的识别对象,包含 licensePlate、plateNumber、color、confidence、requestId、imageSize、rawData", + "错误:400(参数或图片格式/尺寸问题),500(第三方 OCR 调用失败或云密钥未配置)", + "文档中不包含任何敏感配置;实际腾讯云密钥保留在配置文件中,勿在文档中暴露。" + ] + } + }, + { + "id": "2026.04.09-system-03", + "date": "2026-04-09", + "method": "index.recognizeLicensePlate", + "type": "changed", + "summary": "收紧基础模块车牌识别接口响应,仅返回 licensePlate 字段", + "detail": "为简化对外契约,index.recognizeLicensePlate 的响应已从包含 licensePlate、plateNumber、color、confidence、requestId、imageSize、rawData 调整为仅包含 licensePlate。isNeedAuth=false, isNeedLogin=true。", + "notes": [ + "出参由 {licensePlate, plateNumber, color, confidence, requestId, imageSize, rawData} 调整为 {licensePlate}", + "调用方请仅依赖 licensePlate 字段以适配新版本;历史字段已裁剪且不再保证存在。", + "文档中未包含任何云密钥或敏感配置信息。" + ] + } ] diff --git a/methods/system.json b/methods/system.json index c339b7e..5c3625f 100644 --- a/methods/system.json +++ b/methods/system.json @@ -345,6 +345,60 @@ "response": [], "errors": [] }, + { + "method": "index.recognizeLicensePlate", + "description": "识别车牌号码(通过 base64 图片)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "base64", + "type": "string", + "required": true, + "source": "body", + "description": "base64 图片,支持 data URL 前缀(data:image/...;base64,)或纯 base64 字符串" + }, + { + "name": "imageBase64", + "type": "string", + "required": false, + "source": "body", + "description": "兼容字段(同 base64)" + }, + { + "name": "image_base64", + "type": "string", + "required": false, + "source": "body", + "description": "兼容字段(同 base64)" + } + ], + "response": [ + { + "name": "licensePlate", + "type": "string", + "description": "识别到的车牌号(对外契约,仅返回该字段)" + } + ], + "errors": [ + { + "code": "400", + "description": "base64 图片不能为空 / base64 图片格式不正确 / 图片大小不能超过 7MB" + }, + { + "code": "500", + "description": "第三方 OCR 服务调用失败或腾讯云配置未设置" + } + ] + }, { "method": "index.getI18nMessage", "description": "index.getI18nMessage 接口", @@ -3879,7 +3933,7 @@ }, { "method": "storage.entry.cancel", - "description": "作废入库单", + "description": "作废入库单(支持单条或批量作废)", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -3894,23 +3948,36 @@ { "name": "id", "type": "number", - "required": true, + "required": false, "source": "body", - "description": "入库单ID" + "description": "入库单ID,兼容旧调用;与 `ids` 二选一。若同时传入 `ids`,以 `ids` 为准。" + }, + { + "name": "ids", + "type": "array", + "required": false, + "source": "body", + "description": "入库单ID数组(number[]),用于批量作废;必须为非空数组,建议批量操作使用 `ids`,优先于 `id`。" } ], "response": [ { "name": "id", "type": "number", - "required": true, - "description": "作废成功的入库单ID" + "required": false, + "description": "单条作废时返回的入库单ID" + }, + { + "name": "ids", + "type": "array", + "required": false, + "description": "批量作废时返回的已成功作废入库单ID数组(number[])" } ], "errors": [ { "code": "400", - "description": "参数不合法或已完成单据不允许作废" + "description": "参数错误/参数不合法:需传入非空的 `id` 或 `ids`;`ids` 必须为数字数组且不得包含非法或重复值" }, { "code": "404", diff --git a/test/app/controller/system.storage.transaction.test.js b/test/app/controller/system.storage.transaction.test.js index 30f20df..5417560 100644 --- a/test/app/controller/system.storage.transaction.test.js +++ b/test/app/controller/system.storage.transaction.test.js @@ -253,6 +253,22 @@ describe('test/app/controller/system.storage.transaction.test.js', () => { assert.ok(Number(row.quantity) > 0, `record ${row.id}: quantity 应 > 0, 实际: ${row.quantity}`); + // 前后快照字段存在 + assert.ok(Number.isFinite(Number(row.before_quantity)), + `record ${row.id}: before_quantity 应存在, 实际: ${row.before_quantity}`); + assert.ok(Number.isFinite(Number(row.after_quantity)), + `record ${row.id}: after_quantity 应存在, 实际: ${row.after_quantity}`); + assert.ok(Number.isFinite(Number(row.before_locked_quantity)), + `record ${row.id}: before_locked_quantity 应存在, 实际: ${row.before_locked_quantity}`); + assert.ok(Number.isFinite(Number(row.after_locked_quantity)), + `record ${row.id}: after_locked_quantity 应存在, 实际: ${row.after_locked_quantity}`); + + // 快照关系应与流水数量一致 + assert.equal(Number(row.after_quantity) - Number(row.before_quantity), Number(row.quantity), + `record ${row.id}: after_quantity - before_quantity 应等于 quantity`); + assert.equal(Number(row.after_locked_quantity), Number(row.before_locked_quantity), + `record ${row.id}: 入库路径锁定数量前后应保持一致`); + // stock_id > 0 assert.ok(Number(row.stock_id) > 0, `record ${row.id}: stock_id 应 > 0, 实际: ${row.stock_id}`); diff --git a/test/app/service/systemMethods/storeWarehouse/store.test.js b/test/app/service/systemMethods/storeWarehouse/store.test.js new file mode 100644 index 0000000..90ea02d --- /dev/null +++ b/test/app/service/systemMethods/storeWarehouse/store.test.js @@ -0,0 +1,157 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const StoreWarehouseStoreService = require('../../../../../app/service/systemMethods/storeWarehouse/store'); + +function createContext(options = {}) { + const { + includeList = true, + includeSign = true, + } = options; + + const actionCalls = { + list: [], + sign: [], + }; + + const storeWarehouse = {}; + + if (includeList) { + storeWarehouse.list = async function list(data) { + actionCalls.list.push(data); + data.touched = true; + return { + received: data, + }; + }; + } + + if (includeSign) { + storeWarehouse.sign = async function sign(data) { + actionCalls.sign.push(data); + data.touched = true; + return { + received: data, + }; + }; + } + + const ctx = { + app: { + config: {}, + }, + service: { + systems: { + storeWarehouse, + }, + }, + }; + + return { + actionCalls, + ctx, + }; +} + +describe('test/app/service/systemMethods/storeWarehouse/store.test.js', () => { + it('should copy payload before calling list', async () => { + const { actionCalls, ctx } = createContext(); + const service = new StoreWarehouseStoreService(ctx); + const payload = { + page: 1, + page_size: 20, + nested: { + keep: true, + }, + }; + + const result = await service.list(payload); + + assert.equal(result.flag, 'success'); + assert.equal(result.message, 'ok'); + assert.equal(actionCalls.list.length, 1); + assert.notStrictEqual(actionCalls.list[0], payload); + assert.deepEqual(actionCalls.list[0], { + page: 1, + page_size: 20, + nested: { + keep: true, + }, + touched: true, + }); + assert.equal(payload.touched, undefined); + assert.deepEqual(payload, { + page: 1, + page_size: 20, + nested: { + keep: true, + }, + }); + }); + + it('should copy payload before calling sign', async () => { + const { actionCalls, ctx } = createContext(); + const service = new StoreWarehouseStoreService(ctx); + const payload = { + warehouse_id: 1001, + nested: { + keep: true, + }, + }; + + const result = await service.sign(payload); + + assert.equal(result.flag, 'success'); + assert.equal(result.message, 'ok'); + assert.equal(actionCalls.sign.length, 1); + assert.notStrictEqual(actionCalls.sign[0], payload); + assert.deepEqual(actionCalls.sign[0], { + warehouse_id: 1001, + nested: { + keep: true, + }, + touched: true, + }); + assert.equal(payload.touched, undefined); + assert.deepEqual(payload, { + warehouse_id: 1001, + nested: { + keep: true, + }, + }); + }); + + it('should keep the failure fallback for missing list method', async () => { + const { actionCalls, ctx } = createContext({ + includeList: false, + }); + const service = new StoreWarehouseStoreService(ctx); + + const result = await service.list({ + page: 1, + }); + + assert.equal(result.flag, 'failure'); + assert.equal(result.message, '获取签约列表失败'); + assert.equal(Number(result.code), 500); + assert.equal(actionCalls.list.length, 0); + assert.equal(actionCalls.sign.length, 0); + }); + + it('should keep the failure fallback for missing sign method', async () => { + const { actionCalls, ctx } = createContext({ + includeSign: false, + }); + const service = new StoreWarehouseStoreService(ctx); + + const result = await service.sign({ + warehouse_id: 1001, + }); + + assert.equal(result.flag, 'failure'); + assert.equal(result.message, '签约失败'); + assert.equal(Number(result.code), 500); + assert.equal(actionCalls.list.length, 0); + assert.equal(actionCalls.sign.length, 0); + }); +}); diff --git a/test/app/service/systems/auth.user.loginWechatCode.test.js b/test/app/service/systems/auth.user.loginWechatCode.test.js index 7d559fd..78150c7 100644 --- a/test/app/service/systems/auth.user.loginWechatCode.test.js +++ b/test/app/service/systems/auth.user.loginWechatCode.test.js @@ -100,4 +100,57 @@ describe('test/app/service/systems/auth.user.loginWechatCode.test.js', () => { assert.equal(result.code, 0); assert.match(String(result.message || ''), /客户端编码/); }); + + it('should resolve login event and parse ye4s user id from redis message', async () => { + const { service } = createServiceHarness(); + const listeners = new Map(); + + const subscriber = { + on(event, handler) { + listeners.set(event, handler); + return this; + }, + removeListener(event, handler) { + if (listeners.get(event) === handler) { + listeners.delete(event); + } + return this; + }, + async subscribe(channel) { + setImmediate(() => { + const messageHandler = listeners.get('message'); + if (messageHandler) { + messageHandler(channel, JSON.stringify({ ye4sUserId: 88 })); + } + }); + }, + unsubscribe() { + return Promise.resolve(); + }, + quit() { + return Promise.resolve(); + }, + disconnect() {}, + }; + + service.app.redis = { + get(name) { + if (name !== 'cache') { + return null; + } + return { + duplicate() { + return subscriber; + }, + }; + }, + }; + + const result = await service.waitForWechatLoginEvent('AB12CD', 50); + + assert.equal(result.timed_out, false); + assert.equal(result.reason, 'event'); + assert.equal(result.ye4s_user_id, 88); + assert.deepEqual(result.event, { ye4sUserId: 88 }); + }); }); diff --git a/test/app/service/systems/license_plate.test.js b/test/app/service/systems/license_plate.test.js new file mode 100644 index 0000000..c3e8837 --- /dev/null +++ b/test/app/service/systems/license_plate.test.js @@ -0,0 +1,75 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const LicensePlateService = require('../../../../app/service/systems/license_plate'); + +const fixtureImagePath = path.join(__dirname, '../../../../temp/cp.png'); +const fixtureImageBase64 = fs.readFileSync(fixtureImagePath).toString('base64'); + +class TestLicensePlateService extends LicensePlateService { + buildTencentCloudRequest(requestConfig) { + this.requestAction = requestConfig.action; + return super.buildTencentCloudRequest(requestConfig); + } + + async sendTencentCloudRequest(requestConfig) { + this.requestConfig = requestConfig; + return { + Response: { + LicensePlate: '桂MMU905', + Confidence: 98, + Color: '蓝色', + RequestId: 'req-test-001', + }, + }; + } +} + +function createService(overrides = {}) { + const ctx = { + app: { + config: { + tencentCloud: { + appId: 1234567890, + secretId: 'AKID-public-1234567890', + secretKey: 'PUBLICSECRETKEY1234567890', + region: 'ap-guangzhou', + }, + cos: { + region: 'ap-guangzhou', + }, + }, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + ...overrides, + }; + + return new TestLicensePlateService(ctx); +} + +describe('test/app/service/systems/license_plate.test.js', () => { + it('should read fixture image and return normalized recognition result', async () => { + const service = createService(); + + const result = await service.recognizeLicensePlate(fixtureImageBase64); + + assert.equal(service.requestAction, 'LicensePlateOCR'); + assert.equal(JSON.parse(service.requestConfig.payloadString).ImageBase64, fixtureImageBase64); + assert.equal(result.licensePlate, '桂MMU905'); + }); + + it('should reject empty or invalid base64 input', async () => { + const service = createService(); + + await assert.rejects( + () => service.recognizeLicensePlate('not-a-base64-image'), + /base64 图片格式不正确/ + ); + }); +}); \ No newline at end of file diff --git a/test/app/service/systems/stock_transaction.create.test.js b/test/app/service/systems/stock_transaction.create.test.js new file mode 100644 index 0000000..9bf7a1f --- /dev/null +++ b/test/app/service/systems/stock_transaction.create.test.js @@ -0,0 +1,85 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const StockTransactionService = require('../../../../app/service/systems/stock_transaction'); + +function createServiceHarness() { + const calls = { + createArgs: null, + }; + + const model = { + StockTransaction: { + async create(payload, options) { + calls.createArgs = { + payload, + options, + }; + return { + id: 1, + ...payload, + }; + }, + }, + }; + + const ctx = { + model, + app: { + model, + }, + }; + + const service = new StockTransactionService(ctx); + + return { + service, + calls, + }; +} + +describe('test/app/service/systems/stock_transaction.create.test.js', () => { + it('should create stock transaction with snapshot fields', async () => { + const { service, calls } = createServiceHarness(); + const transaction = { + id: 'tx-1', + }; + + const result = await service.create({ + transaction_type: 'INBOUND', + warehouse_id: 100000, + store_id: 1000000, + stock_id: 200001, + storage_id: 300001, + space_id: 400001, + quantity: 12, + batch_no: 'BATCH-001', + inventory_type: 'ZP', + order_type: 'SCRK', + order_no: 'EO-001', + order_id: 500001, + receiving_id: 600001, + entry_order_id: 700001, + operator_id: 'op-1', + operator_name: '测试人员', + remark: '测试流水', + before_quantity: 88, + after_quantity: 100, + before_locked_quantity: 5, + after_locked_quantity: 5, + created_at: new Date('2026-04-09T08:00:00Z'), + }, { + transaction, + }); + + assert.equal(result.id, 1); + assert.ok(calls.createArgs, '应调用 StockTransaction.create'); + assert.equal(calls.createArgs.options.transaction, transaction); + assert.equal(calls.createArgs.payload.before_quantity, 88); + assert.equal(calls.createArgs.payload.after_quantity, 100); + assert.equal(calls.createArgs.payload.before_locked_quantity, 5); + assert.equal(calls.createArgs.payload.after_locked_quantity, 5); + assert.equal(calls.createArgs.payload.quantity, 12); + assert.equal(calls.createArgs.payload.transaction_type, 'INBOUND'); + }); +}); diff --git a/test/app/service/systems/storage.entry.cancel.test.js b/test/app/service/systems/storage.entry.cancel.test.js new file mode 100644 index 0000000..eb67532 --- /dev/null +++ b/test/app/service/systems/storage.entry.cancel.test.js @@ -0,0 +1,171 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const EntryService = require('../../../../app/service/systems/storage/entry'); + +function createOrder(id, orderStatus = 'CREATED') { + return { + id, + warehouse_id: 1001, + is_enabled: 1, + deleted_at: null, + order_status: orderStatus, + updateCalls: [], + async update(values, options = {}) { + this.updateCalls.push({ + values, + options, + }); + Object.assign(this, values); + return this; + }, + }; +} + +function createServiceHarness(orders = []) { + const orderMap = new Map(orders.map(order => [ Number(order.id), order ])); + const transaction = { + commitCalls: 0, + rollbackCalls: 0, + async commit() { + this.commitCalls += 1; + }, + async rollback() { + this.rollbackCalls += 1; + }, + }; + + const ctx = { + user: { + store_id: 1001, + }, + app: { + Sequelize: { + Op: {}, + }, + coreLogger: { + warn() {}, + error() {}, + }, + }, + model: { + async transaction() { + return transaction; + }, + EntryOrder: { + async findOne({ where = {} }) { + const order = orderMap.get(Number(where.id)); + if (!order) { + return null; + } + + if (Number(where.warehouse_id) !== Number(order.warehouse_id)) { + return null; + } + + if (Object.prototype.hasOwnProperty.call(where, 'is_enabled') && Number(where.is_enabled) !== Number(order.is_enabled)) { + return null; + } + + if (Object.prototype.hasOwnProperty.call(where, 'deleted_at') && where.deleted_at === null && order.deleted_at !== null) { + return null; + } + + return order; + }, + }, + }, + }; + + const service = new EntryService(ctx); + + return { + service, + transaction, + orders: orderMap, + }; +} + +describe('test/app/service/systems/storage.entry.cancel.test.js', () => { + it('should cancel single entry order by id', async () => { + const order = createOrder(11); + const { service, transaction } = createServiceHarness([ order ]); + + const result = await service.cancel({ + id: 11, + }); + + assert.equal(result.code, 200); + assert.equal(result.message, '作废成功'); + assert.deepEqual(result.data, { id: 11 }); + assert.equal(order.order_status, 'CANCELLED'); + assert.equal(order.updateCalls.length, 1); + assert.equal(transaction.commitCalls, 1); + assert.equal(transaction.rollbackCalls, 0); + }); + + it('should cancel batch entry orders by ids', async () => { + const orderA = createOrder(21); + const orderB = createOrder(22); + const { service, transaction } = createServiceHarness([ orderA, orderB ]); + + const result = await service.cancel({ + ids: [ 21, 22 ], + }); + + assert.equal(result.code, 200); + assert.equal(result.message, '作废成功'); + assert.deepEqual(result.data, { ids: [ 21, 22 ] }); + assert.equal(orderA.order_status, 'CANCELLED'); + assert.equal(orderB.order_status, 'CANCELLED'); + assert.equal(orderA.updateCalls.length, 1); + assert.equal(orderB.updateCalls.length, 1); + assert.equal(transaction.commitCalls, 1); + assert.equal(transaction.rollbackCalls, 0); + }); + + it('should reject empty or illegal ids', async () => { + const { service } = createServiceHarness(); + + const emptyResult = await service.cancel({ + ids: [], + }); + + assert.equal(emptyResult.code, 400); + assert.match(String(emptyResult.message || ''), /ids 必须是非空数组/); + + const illegalResult = await service.cancel({ + ids: [ 'abc' ], + }); + + assert.equal(illegalResult.code, 400); + assert.match(String(illegalResult.message || ''), /ids 必须为正整数数组/); + }); + + it('should reject batch cancel when any order is missing or completed', async () => { + const existingOrder = createOrder(31); + const completedOrder = createOrder(32, 'COMPLETED'); + const { service, transaction } = createServiceHarness([ existingOrder, completedOrder ]); + + const missingResult = await service.cancel({ + ids: [ 31, 999 ], + }); + + assert.equal(missingResult.code, 404); + assert.match(String(missingResult.message || ''), /入库单不存在或无权访问/); + assert.equal(existingOrder.updateCalls.length, 0); + assert.equal(transaction.commitCalls, 0); + assert.equal(transaction.rollbackCalls, 0); + + const statusResult = await service.cancel({ + ids: [ 31, 32 ], + }); + + assert.equal(statusResult.code, 400); + assert.match(String(statusResult.message || ''), /已完成入库单不允许作废/); + assert.equal(existingOrder.updateCalls.length, 0); + assert.equal(completedOrder.updateCalls.length, 0); + assert.equal(transaction.commitCalls, 0); + assert.equal(transaction.rollbackCalls, 0); + }); +}); diff --git a/test/app/service/systems/storage.receiving.report.test.js b/test/app/service/systems/storage.receiving.report.test.js index b425a28..53e8cb8 100644 --- a/test/app/service/systems/storage.receiving.report.test.js +++ b/test/app/service/systems/storage.receiving.report.test.js @@ -180,6 +180,33 @@ function createCompleteReceivingService({ }; } +function createReceivingSnapshot(deliveryMethod) { + return { + id: 123, + receiving_number: 'RCV202604040001', + warehouse_id: 2001, + store_id: 3001, + store_name: '测试货主', + delivery_method: deliveryMethod, + license_plate: '粤A12345', + tracking_number: 'YT123456789', + total_boxes: 3, + total_pallets: 1, + remark: '完成收货测试', + receiving_end_time: new Date('2026-04-04T12:30:00Z'), + details: [ + { + id: 501, + product_name: '测试商品A', + system_product_id: 9001, + barcode: 'SKU-001', + actual_quantity: 8, + weight: 12, + }, + ], + }; +} + describe('test/app/service/systems/storage.receiving.report.test.js', () => { it('should build and upload completion excel in a single sheet with one preview column', async () => { const { service, excelCalls } = createService(); @@ -303,10 +330,139 @@ describe('test/app/service/systems/storage.receiving.report.test.js', () => { assert.equal(options.url, 'https://cdn.example.com/收货完成_RCV202604040001.xlsx'); assert.equal(options.subject.id, 2001); assert.equal(options.subject.name, '测试仓库'); - assert.match(String(options.content || ''), /收货单RCV202604040001已完成/); + assert.match(String(options.content || ''), /收货单号:RCV202604040001 已完成/); assert.equal(result.success, true); }); + it('should show only license plate for truck in notice content and report main rows', async () => { + const { service, excelCalls, noticeCalls } = createService(); + const receiving = createReceivingSnapshot('truck'); + + await service.sendCompletionNotice({ + receiving, + operator: { + employees_name: '测试员', + }, + stats: { + total_details: 1, + matched_details: 1, + unmatched_details: 0, + total_quantity: 8, + }, + }); + + await service.uploadCompletionExcelReport({ + receiving, + operator: { + employees_name: '测试员', + }, + stats: { + total_details: 1, + matched_details: 1, + unmatched_details: 0, + total_quantity: 8, + }, + detailImageMap: new Map(), + receivingImages: [], + }); + + assert.equal(noticeCalls.length, 1); + assert.match(String(noticeCalls[0].content || ''), /车牌号:粤A12345/); + assert.ok(!String(noticeCalls[0].content || '').includes('物流单号')); + + assert.equal(excelCalls.length, 1); + const [ sheet ] = excelCalls[0].sheets; + const labels = sheet.rows.filter(Array.isArray).map(item => String(item[0] || '')); + assert.ok(labels.includes('车牌号')); + assert.ok(!labels.includes('物流单号')); + }); + + it('should show only tracking number for express in notice content and report main rows', async () => { + const { service, excelCalls, noticeCalls } = createService(); + const receiving = createReceivingSnapshot('express'); + + await service.sendCompletionNotice({ + receiving, + operator: { + employees_name: '测试员', + }, + stats: { + total_details: 1, + matched_details: 1, + unmatched_details: 0, + total_quantity: 8, + }, + }); + + await service.uploadCompletionExcelReport({ + receiving, + operator: { + employees_name: '测试员', + }, + stats: { + total_details: 1, + matched_details: 1, + unmatched_details: 0, + total_quantity: 8, + }, + detailImageMap: new Map(), + receivingImages: [], + }); + + assert.equal(noticeCalls.length, 1); + assert.match(String(noticeCalls[0].content || ''), /物流单号:YT123456789/); + assert.ok(!String(noticeCalls[0].content || '').includes('车牌号')); + + assert.equal(excelCalls.length, 1); + const [ sheet ] = excelCalls[0].sheets; + const labels = sheet.rows.filter(Array.isArray).map(item => String(item[0] || '')); + assert.ok(labels.includes('物流单号')); + assert.ok(!labels.includes('车牌号')); + }); + + it('should hide both contact fields for other delivery methods', async () => { + const { service, excelCalls, noticeCalls } = createService(); + const receiving = createReceivingSnapshot('other'); + + await service.sendCompletionNotice({ + receiving, + operator: { + employees_name: '测试员', + }, + stats: { + total_details: 1, + matched_details: 1, + unmatched_details: 0, + total_quantity: 8, + }, + }); + + await service.uploadCompletionExcelReport({ + receiving, + operator: { + employees_name: '测试员', + }, + stats: { + total_details: 1, + matched_details: 1, + unmatched_details: 0, + total_quantity: 8, + }, + detailImageMap: new Map(), + receivingImages: [], + }); + + assert.equal(noticeCalls.length, 1); + assert.ok(!String(noticeCalls[0].content || '').includes('车牌号')); + assert.ok(!String(noticeCalls[0].content || '').includes('物流单号')); + + assert.equal(excelCalls.length, 1); + const [ sheet ] = excelCalls[0].sheets; + const labels = sheet.rows.filter(Array.isArray).map(item => String(item[0] || '')); + assert.ok(!labels.includes('车牌号')); + assert.ok(!labels.includes('物流单号')); + }); + it('should support nested notice.index service shape from Egg loader', async () => { const noticeCalls = []; const ctx = { @@ -407,7 +563,7 @@ describe('test/app/service/systems/storage.receiving.report.test.js', () => { system_product_id: null, barcode: '', weight: 0, - actual_quantity: 0, + actual_quantity: 1, }, itemImages: [], }); diff --git a/test/app/service/systems/upload.test.js b/test/app/service/systems/upload.test.js index 17a4ce2..5ba80c1 100644 --- a/test/app/service/systems/upload.test.js +++ b/test/app/service/systems/upload.test.js @@ -16,9 +16,37 @@ function createService(overrides = {}) { const ctx = { app: { config: { + tencentCloud: { + appId: 1234567890, + secretId: 'AKID-public-1234567890', + secretKey: 'PUBLICSECRETKEY1234567890', + }, cos: { cdnurl: 'https://cdn.example.com', uploadurl: 'https://upload.example.com', + bucket: 'bucket-example', + region: 'ap-guangzhou', + expire: 600, + savekey: '/{warehouseId}/{dir}/{year}{mon}{day}/{filemd5}{.suffix}', + maxsize: '100M', + mimetype: 'jpg,png,bmp,jpeg,gif,zip,rar,xls,xlsx,apk', + dirs: { + image: '/images/', + document: '/documents/', + apk: '/apks/', + temp: '/temp/', + }, + }, + fileTypes: { + 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'document', + }, + }, + model: { + QueryTypes: { + SELECT: 'SELECT', + }, + async query() { + return [{ remaining_bytes: 1024 * 1024 * 1024 }]; }, }, }, @@ -69,6 +97,33 @@ function createService(overrides = {}) { } describe('test/app/service/systems/upload.test.js', () => { + it('should prefer tencent cloud auth config while keeping COS upload parameters', async () => { + const { service } = createService({ + model: { + File: { + async findOne() { + return null; + }, + }, + }, + }); + + const result = await service.getUploadParams({ + fileName: 'report.xlsx', + fileType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + fileSize: 2048, + type: 'document', + md5: 'c688dd719a7260404822d7dfebdc6115', + }); + + assert.equal(result.uploadUrl, 'https://bucket-example.cos.ap-guangzhou.myqcloud.com'); + assert.equal(result.bucket, 'bucket-example'); + assert.equal(result.region, 'ap-guangzhou'); + assert.equal(result.signature.secretId, 'AKID-public-1234567890'); + assert.equal(result.data['q-ak'], 'AKID-public-1234567890'); + assert.equal(result.isNew, true); + }); + it('should create file reference with warehouse and creator when saving upload record', async () => { const { service, fileCreates, fileReferenceCreates } = createService(); From 69e992bf9dc1242f5c35b3aa5bdddcc716274045 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Thu, 9 Apr 2026 15:45:48 +0800 Subject: [PATCH 018/550] chore: update change log --- methods/changes/system.json | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/methods/changes/system.json b/methods/changes/system.json index b10aa81..b223a47 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -301,8 +301,7 @@ "错误:400(参数或图片格式/尺寸问题),500(第三方 OCR 调用失败或云密钥未配置)", "文档中不包含任何敏感配置;实际腾讯云密钥保留在配置文件中,勿在文档中暴露。" ] - } - }, + }, { "id": "2026.04.09-system-03", "date": "2026-04-09", From 16803e8cc25521807bc715a1e3053d2f40bcdbd4 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sat, 11 Apr 2026 17:07:16 +0800 Subject: [PATCH 019/550] 1 --- .cursor/agents/wms-db-agent.md | 96 +++++++++++++++++++++++ .cursor/agents/wms-redis-agent.md | 101 +++++++++++++++++++++++++ .github/agents/开发.agent.md | 122 ------------------------------ AI_TOOLBOX.md | 23 +++--- 4 files changed, 211 insertions(+), 131 deletions(-) create mode 100644 .cursor/agents/wms-db-agent.md create mode 100644 .cursor/agents/wms-redis-agent.md diff --git a/.cursor/agents/wms-db-agent.md b/.cursor/agents/wms-db-agent.md new file mode 100644 index 0000000..54e0c6f --- /dev/null +++ b/.cursor/agents/wms-db-agent.md @@ -0,0 +1,96 @@ +--- +name: wms-db-agent +description: "Use when the user asks about 数据库、查数据、SQL、MySQL、库表定位、字段含义、索引建议、接口数据排查、script/db-query.ps1、wms/ye4s client。专用于 WMS 数据库查询与排障。" +model: inherit +readonly: false +is_background: false +--- + +# WMS 数据库代理(`wms-db-agent`) + +## 适用范围 + +- 项目根目录:`D:\wms` +- 默认数据库脚本:`script/db-query.ps1` +- 默认 MySQL client:`wms` +- 可切换 client:`wms`、`ye4s` + +## 何时必须使用本 Agent + +出现以下任一诉求时,必须使用 `wms-db-agent`: + +- 查数据库 / 查数据 / 查表 +- 编写、修改、解释 SQL +- 排查接口返回为空、数据异常、库表映射问题 +- 核对 `wms` / `ye4s` 库连接与路由 +- 解释字段含义、表结构、索引建议 + +## 工作规则 + +1. **所有数据库查询优先使用** `script/db-query.ps1` +2. **对非测试仓库数据默认只允许只读查询**:`SELECT` / `SHOW` / `DESC` / `EXPLAIN` +3. **禁止对非测试仓库执行** `UPDATE` / `DELETE` / `INSERT` **等写操作** +4. **若无法确认仓库是否为测试仓,默认按非测试仓处理并拒绝写操作** +5. 如用户已明确说明是测试仓且允许写操作: + - 必须先生成影响范围确认 SQL(`COUNT(*) + 同 WHERE 条件`) + - 明确告知风险 + - 获得用户确认后再执行 +6. **如果是为了支持新接口而补权限,只能新增 / 补齐权限记录本身**(如 `wms_permission`);**默认禁止直接修改角色授权范围**,不得直接改 `wms_role.permissions` 或其他角色授权绑定,除非用户已明确确认 +7. 做接口排障时,优先链路: + - 先定位 `app/model` / `service` / `controller` + - 再给 SQL + - 最后执行验证并输出根因 +8. 输出要求: + - 所有回复必须以 `[DB]` 开头 + - 优先给结论、关键字段和下一步建议 + +## 常用命令模板 + +### 1) 当前连接库自检 + +```powershell +powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -Query "SELECT DATABASE() AS db, USER() AS loginUser" +``` + +### 2) 查询最近数据 + +```powershell +powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -Query "SELECT * FROM account ORDER BY id DESC LIMIT 10" +``` + +### 3) 表格输出 + +```powershell +powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -Query "SELECT id, name FROM store LIMIT 20" -AsTable +``` + +### 4) 切换数据库 client + +```powershell +powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -DbClient wms -Query "SHOW TABLES" +powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -DbClient ye4s -Query "SHOW TABLES" +``` + +## 建议提问方式 + +```text +请使用 wms-db-agent 帮我: +1) 找到对应 controller / service / model +2) 生成并执行只读 SQL +3) 输出结果、字段解释和根因判断 +``` + +## 常见问题 + +- 报错 `Cannot find module 'mysql2/promise'` + - 先执行 `npm install`,确认依赖完整 +- 报错 `MySQL client "xxx" not found in config.mysql.clients` + - 检查 `config/config.local.js` 中 `config.mysql.clients` 是否包含对应 client +- SQL 语法报错且定位到 `current_user` + - 避免使用 `current_user` 作为别名,建议改成 `loginUser` +- 报错连接失败(超时/拒绝访问) + - 检查数据库 IP、端口、用户名密码、网络白名单 + +## 结论 + +数据库相关能力文档已统一收口到本 Agent;工作区其它通用文档只保留“数据库相关必须使用 `wms-db-agent`”这一条约束。 diff --git a/.cursor/agents/wms-redis-agent.md b/.cursor/agents/wms-redis-agent.md new file mode 100644 index 0000000..980f1ab --- /dev/null +++ b/.cursor/agents/wms-redis-agent.md @@ -0,0 +1,101 @@ +--- +name: wms-redis-agent +description: "Use when the user asks about Redis、缓存、cache key、TTL、session、script/redis-cache.ps1、hgetall/hset、set/get/del、缓存排障、键值核对。专用于 WMS Redis 查询与缓存变更。" +model: inherit +readonly: false +is_background: false +--- + +# WMS Redis 代理(`wms-redis-agent`) + +## 适用范围 + +- 项目根目录:`D:\wms` +- 默认缓存脚本:`script/redis-cache.ps1` +- 默认 Redis client:`cache` + +## 何时必须使用本 Agent + +出现以下任一诉求时,必须使用 `wms-redis-agent`: + +- 查 Redis key / pattern / TTL / exists +- 读取或修改缓存值 +- 操作 Hash:`hget` / `hset` / `hgetall` / `hdel` +- 排查登录态、session、缓存不一致、缓存未刷新 +- 核对某接口是否命中缓存或缓存值异常 + +## 工作规则 + +1. **所有 Redis 操作优先使用** `script/redis-cache.ps1` +2. **对非测试仓库相关缓存默认只允许读取**:`get` / `mget` / `ttl` / `exists` / `hget` / `hgetall` +3. **禁止对非测试仓库执行** `set` / `del` / `hset` / `hdel` / `incr` / `decr` / `expire` **等写操作** +4. **若无法确认是否测试仓,默认按非测试仓处理,只提供只读排查建议** +5. 如用户已明确说明是测试仓且允许修改,**写操作前必须先读**:`set / del / hset / hdel / incr / decr / expire` 前,先读取当前值并确认影响范围 +6. **列 key 优先使用扫描模式**,避免直接进行高风险全量操作 +7. 做缓存排障时,优先链路: + - 先定位 key 规则 / 调用代码 + - 再读取当前缓存值与 TTL + - 如需修改,执行后必须回读验证 +8. 输出要求: + - 所有回复必须以 `[Redis]` 开头 + - 优先给结论、当前值、TTL 和下一步建议 +9. 写入值时,如未携带TTL,全部拒绝 + +## 常用命令模板 + +### 1) 列出目标 key + +```powershell +powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action keys -RedisClient cache -Pattern "user:*" -AsTable +``` + +### 2) 读取字符串缓存 + +```powershell +powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action get -RedisClient cache -Key "system" +``` + +### 3) 查看 TTL / 是否存在 + +```powershell +powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action ttl -RedisClient cache -Key "system" +powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action exists -RedisClient cache -Key "system" +``` + +### 4) 读取或修改 Hash + +```powershell +powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action hgetall -RedisClient cache -Key "session:123" -AsTable +powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action hset -RedisClient cache -Key "session:123" -Field "status" -Value "active" +``` + +### 5) 修改后回读确认 + +```powershell +powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action set -RedisClient cache -Key "system" -Value "{\"ok\":1}" -ExpireSeconds 600 +powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action get -RedisClient cache -Key "system" +``` + +## 建议提问方式 + +```text +请使用 wms-redis-agent 帮我: +1) 找到相关 key 或 pattern +2) 读取当前值、TTL、exists 状态 +3) 如需修改,先展示变更前后对比并回读确认 +``` + +## 常见问题 + +- 报错 `Cannot find module 'ioredis'` + - 先执行 `npm install`,确认依赖完整 +- 报错 `Redis client "xxx" not found in config.redis.clients` + - 检查 `config/config.local.js` 中 `config.redis.clients` 是否包含对应 client +- 报错 Redis 连接失败(超时/认证失败) + - 检查 Redis host/port/password/db 与网络连通性 +- PowerShell 执行策略限制 + - 使用命令中的 `-ExecutionPolicy Bypass` + +## 结论 + +Redis 相关能力文档已统一收口到本 Agent;工作区其它通用文档只保留“Redis 相关必须使用 `wms-redis-agent`”这一条约束。 diff --git a/.github/agents/开发.agent.md b/.github/agents/开发.agent.md index e1f0122..878dcf6 100644 --- a/.github/agents/开发.agent.md +++ b/.github/agents/开发.agent.md @@ -119,125 +119,3 @@ node .\script\tmp-struct-system-params.cjs - 改代码后必须跑相关测试验证 - 涉及接口变更必须委派 `wms-doc-agent` 同步文档,本 agent 不直接修改文档文件 - 除了json,其他字符串输出必须使用模板字符串,必要时分行保持可读性 -- --- -name: wms-dev-agent -description: "Use when the user asks about 开发、改代码、修 bug、调试、接口定位、method routing、where 规范、权限映射、Egg.js service 分层。专用于 WMS 通用开发与代码实现。" -argument-hint: "描述要开发或排查的目标,例如:修某个接口 bug、定位 system method 对应实现、梳理调用链、同步 methods 文档。" -tools: ['read', 'search', 'edit', 'execute', 'todo'] -model: GPT-5.3-Codex (copilot) ---- - -# WMS 开发代理(`wms-dev-agent`) - -## 适用范围 - -- 项目根目录:`D:\wms` -- 主要开发目录:`app/`、`methods/`、`docs/` -- 适用于 Egg.js 业务开发、接口联调与文档同步;如重点是测试设计、回归验证、TDD,请转给 `wms-test-agent` - -## 何时必须使用本 Agent - -出现以下任一诉求时,必须使用 `wms-dev-agent`: - -- 改代码 / 修 bug / 重构 / 性能优化 -- 定位 `/system` / `/qimen` method 映射关系 -- 排查 `where` 规则、权限映射、分层职责问题 -- 分析 `app.js` / `app/extend/application.js` / `systemMethods` / `systems` 调用链 -- 如诉求重点是测试设计、回归验证、TDD,请委派给 `wms-test-agent` -- 如涉及文档同步,委派给 `wms-doc-agent` - -## 开发规则 - -1. **先定位后修改**:先找 `controller / systemMethods / systems / model` 的实际链路 -2. **分层约定必须保持**: - - `systemMethods` 只保留出口包装层 - - 业务逻辑统一下沉到 `systems` -3. **如诉求重点是测试设计、补回归、接口验证或 TDD,委派给** `wms-test-agent` -4. **禁止直接修改文档文件**:`methods/*.json`、`methods/changes/*.json`、`docs/*.md` 的所有新增与修改必须委派给 `wms-doc-agent` 完成,`wms-dev-agent` 只负责代码文件(`app/`、`config/`、`database/`、`test/`) -5. **where 规则统一走** `app/service/main.js` 的 `prepareWhereContext(data, options)` -6. **新建接口时,必须先判断是通用接口还是需授权接口**: - - 先明确 `isNeedAuth`,代码实现完成后委派 `wms-doc-agent` 同步 `methods/system.json` 并追加变更记录 - - 若为需授权接口,必须优先通过既有同步流程 / 标准方式补齐权限记录(如 `wms_permission`),必要时使用: - - `npm run permission:sync:system-api -- --dry-run` - - `npm run permission:sync:system-api` - - **绝对不能直接扩大任何角色的授权范围**,不得直接改 `wms_role.permissions` 或其他角色授权绑定来“顺手放开权限” -7. **必须做验证**:改代码后跑相关检查,确认响应结构与文档一致 -8. **所有修改的函数必须要有 JSDOC 注释**,必要时补充说明参数、返回值、错误码等信息,如果修改的方法中没有注释,必须补充完整的 JSDOC 注释后再提交,严禁入参与返回值都没有注释的函数存在于代码中,非本次修改的函数如果没有注释,除非有明确的理由,否则也必须补充完整的 JSDOC 注释后再提交 -9. **method入参必须解构再传入service **,禁止直接把 method 入参对象传给 service,必须先在 method 层解构出具体参数,再传给 service,保持层与层之间的清晰边界和职责分离,如果拆解参数过多,可以先在 controller 层做多步骤访问service方法处理,但是必须在service层处理,禁止在method层调用method层。 -10. **禁止method入口直接调用model层**,必须先调用service层,保持分层职责的清晰和一致 -11. **所有编码风格必须要通过ESLint检查**,禁止任何 ESLint 错误或警告存在于提交的代码中 -12. **禁止修改底层公共代码来“顺手解决问题”**,如需要改 `app.js`、`app/extend/application.js`、`app/service/main.js` 等公共能力入口,必须先评估改动影响范围,并优先考虑在业务层做适配或扩展,避免对全局能力造成不确定风险,如确实需要改公共代码,必须先驳回到调度 agent 升级给专家 agent 进行兜底处理,禁止直接改公共代码后再评估风险的流程 - -## 关键定位地图 - -### 1) 接口入口与 Method 路由 - -- `/system`:Web / PDA 统一接口(POST) -- `/qimen`:奇门接口(POST) -- 路由说明文档:`AI_METHOD_ROUTING.md` - -### 2) 文档单一事实来源(SSOT) - -- `methods/system.json` -- `methods/qimen.json` - -### 3) App 能力入口 - -- `app.js` -- `app/extend/application.js` - -### 4) 常用开发辅助文件 - -- `app/service/main.js`:where 统一处理、权限校验等公共逻辑 -- `test/app/controller/system.user.info.web.test.js` -- `test/app/controller/system.user.changeRole.test.js` - -## 推荐工作流 - -### 代码修改 / 修 bug - -1. 先定位 method 与实现链路 -2. 如需测试设计或补回归,先委派 `wms-test-agent` 补失败用例 -3. 做最小根因修复 -4. 跑相关检查验证 -5. 若涉及接口变更(参数、响应、新增、删除),**必须委派 `wms-doc-agent`** 同步 `methods/*.json`、追加 `methods/changes/*.json` 变更记录 - -### 接口参数变更 - -```powershell -node .\script\tmp-struct-system-params.cjs -``` - -然后人工补齐: -- `description` -- `response` -- `errors` -- 特殊枚举值与业务约束 - -## 建议提问方式 - -```text -请使用 wms-dev-agent 帮我: -1) 定位这个 method / controller / service 的实现链路 -2) 修复问题并说明最小代码改动 -3) 输出验证结果;若需要补测试,请转给 `wms-test-agent` -``` - -## 输出要求 - -- 所有回复建议以 `[Dev]` 开头 -- 先给结论,再给定位链路、修改点、验证结果 -- 涉及接口改动时,明确说明已委派 `wms-doc-agent` 完成文档同步(或提示调用方需要委派) - -## 结论 - -通用开发能力文档已统一收口到本 Agent;测试相关请求请转给 `wms-test-agent`,工具箱只保留“开发相关必须使用 `wms-dev-agent`”的规则入口。 - -## 代码风格 - -- 先定位代码真实实现与调用链 -- 只改最小必要代码,避免大面积重构 -- 改代码后必须跑相关测试验证 -- 涉及接口变更必须委派 `wms-doc-agent` 同步文档,本 agent 不直接修改文档文件 -- 除了json,其他字符串输出必须使用模板字符串,必要时分行保持可读性 -- \ No newline at end of file diff --git a/AI_TOOLBOX.md b/AI_TOOLBOX.md index b7d7dfd..2327c12 100644 --- a/AI_TOOLBOX.md +++ b/AI_TOOLBOX.md @@ -9,15 +9,20 @@ ## Agent配置文件位置 -| Agent名称 | 配置文件路径 | -|-----------|--------------| -| wms-db-agent | `.github/agents/数据库.agent.md` | -| wms-redis-agent | `.github/agents/缓存.agent.md` | -| wms-deploy-agent | `.github/agents/发布.agent.md` | -| wms-dev-agent | `.github/agents/开发.agent.md` | -| wms-test-agent | `.github/agents/测试.agent.md` | -| wms-doc-agent | `.github/agents/文档.agent.md` | -| wms-dispatcher-agent | `.github/agents/调度.agent.md` | + +GitHub Copilot 读取 `.github/agents/*.agent.md`;Cursor 使用 `.cursor/agents/wms-*-agent.md`(Subagent,YAML 为 Cursor 格式:`model` / `readonly` / `is_background` 等)。两处业务规则应保持一致。 + +| Agent名称 | GitHub Copilot | Cursor | +|-----------|----------------|--------| +| wms-db-agent | `.github/agents/数据库.agent.md` | `.cursor/agents/wms-db-agent.md` | +| wms-redis-agent | `.github/agents/缓存.agent.md` | `.cursor/agents/wms-redis-agent.md` | +| wms-deploy-agent | `.github/agents/发布.agent.md` | `.cursor/agents/wms-deploy-agent.md` | +| wms-dev-agent | `.github/agents/开发.agent.md` | `.cursor/agents/wms-dev-agent.md` | +| wms-test-agent | `.github/agents/测试.agent.md` | `.cursor/agents/wms-test-agent.md` | +| wms-doc-agent | `.github/agents/文档.agent.md` | `.cursor/agents/wms-doc-agent.md` | +| wms-dispatcher-agent | `.github/agents/调度.agent.md` | `.cursor/agents/wms-dispatcher-agent.md` | +| wms-expert-agent | `.github/agents/专家.agent.md` | `.cursor/agents/wms-expert-agent.md` | +| wms-review-agent | `.github/agents/评审.agent.md` | `.cursor/agents/wms-review-agent.md` | ## 快速响应规则 From 9d4271244e90f2d213bbfe37aa6c448842820f55 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sat, 11 Apr 2026 17:07:28 +0800 Subject: [PATCH 020/550] ok --- .cursor/agents/wms-deploy-agent.md | 125 +++++++++++++++++++++++++++++ .cursor/agents/wms-doc-agent.md | 101 +++++++++++++++++++++++ 2 files changed, 226 insertions(+) create mode 100644 .cursor/agents/wms-deploy-agent.md create mode 100644 .cursor/agents/wms-doc-agent.md diff --git a/.cursor/agents/wms-deploy-agent.md b/.cursor/agents/wms-deploy-agent.md new file mode 100644 index 0000000..173f15e --- /dev/null +++ b/.cursor/agents/wms-deploy-agent.md @@ -0,0 +1,125 @@ +--- +name: wms-deploy-agent +description: "Use when the user asks about 发布、上线、回退、远程部署、deploy、rollback、smoke、inspect、version、precheck、gateway 探针。专用于 WMS 发布与回退操作。" +model: inherit +readonly: false +is_background: false +--- + +# WMS 发布代理(`wms-deploy-agent`) + +## 适用范围 + +- 项目根目录:`D:\wms` +- 固定部署根目录:`/www/wwwroot/qimen` +- 发布与回退入口:**只允许 `npm run`** + +## 何时必须使用本 Agent + +出现以下任一诉求时,必须使用 `wms-deploy-agent`: + +- 发布生产 / 上线 / deploy +- 回退 / rollback / 指定备份回退 +- 查看线上版本、版本历史 +- 做预检、冒烟、inspect、verify、gateway probe +- 排查发布链路、备份、版本记录问题 + +## 工作规则 + +1. **远程发布与回退只允许通过 `npm run` 执行** +2. **禁止直接运行** `node ./script/deploy-remote.cjs ...` 与 `node ./script/rollback-remote.cjs ...` +3. **AI 严禁读取** `config/deploy.config.local.cjs` +4. **AI 严禁展示或复述** 其中的 `host`、`username`、`privateKeyPath` 等敏感信息 +5. 发布完成后,必须通过可验证命令确认结果,再报告结论 +6. 若用户只要求协助,不主动改写本地 SSH 配置或远端敏感文件 + +## 推荐执行顺序 + +### 发布前 + +```powershell +npm run setup:hooks +npm run deploy:precheck +npm run deploy:verify +``` + +### 正式发布 + +```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 +# 启用仓库级 pre-commit 保护 +npm run setup:hooks + +# 只读预检(不改远端文件) +npm run deploy:precheck + +# 查询当前线上版本号 +npm run deploy:version + +# 查询最近 20 次线上版本历史 +npm run deploy:version:history + +# 查看远端 state 与备份清单 +npm run deploy:inspect + +# 对关键路由做最小连通冒烟 +npm run deploy:smoke + +# 组合执行 inspect + smoke +npm run deploy:verify + +# 按文件名清理远端失败备份 +npm run deploy:cleanup-backups -- backup-20260324202526.tar.gz backup-20260324204750.tar.gz + +# 调用 internal gateway 做 method 连通探针 +npm run deploy:gateway-probe -- releaseProbe.ping "{}" + +# 手动记录一次本地包版本快照 +npm run version:record + +# 查询本地版本历史 +npm run version:history + +# 检查暂存区是否包含禁止提交文件 +npm run guard:git + +# 发布生产环境 +npm run deploy:prod +npm run deploy + +# 回退到最近一次备份 +npm run rollback:prod +npm run rollback + +# 指定备份包回退 +npm run rollback:prod -- --backup=backup-20260324123045.tar.gz +``` + +## 输出要求 + +- 所有回复建议以 `[Deploy]` 开头 +- 先给结论,再给验证证据和下一步建议 +- 不输出任何本地 SSH 敏感配置 + +## 结论 + +发布相关能力文档已统一收口到本 Agent;工作区其它通用文档只保留“发布相关必须使用 `wms-deploy-agent`”这一条约束。 diff --git a/.cursor/agents/wms-doc-agent.md b/.cursor/agents/wms-doc-agent.md new file mode 100644 index 0000000..e6f91f5 --- /dev/null +++ b/.cursor/agents/wms-doc-agent.md @@ -0,0 +1,101 @@ +--- +name: wms-doc-agent +description: "Use when the user asks about 文档、API 文档、README、AI_TOOLBOX、methods/system.json、methods/qimen.json、methods/changes/*.json、接口说明、错误码、示例、文档同步、接口变更记录、变更 JSON、changes。专用于 WMS 文档编写与同步维护。" +model: inherit +readonly: false +is_background: false +--- + +# WMS 文档代理(`wms-doc-agent`) + +## 适用范围 + +- 项目根目录:`D:\wms` +- 主要文档目录:`methods/`、`docs/` +- 常用文档文件:`AI_TOOLBOX.md`、`AI_METHOD_ROUTING.md`、`README.md` + +## 何时必须使用本 Agent + +出现以下任一诉求时,必须使用 `wms-doc-agent`: + +- 补 API 文档 / 接口说明 / 错误码 / 示例请求 +- 同步 `methods/system.json` / `methods/qimen.json` +- 更新 `docs/*.md`、`README.md`、`AI_TOOLBOX.md` +- 整理 method 映射说明、接入文档、使用手册 +- 校对代码与文档是否一致,补齐缺失文档 + +## 文档规则 + +1. **文档必须以代码实现为准**:先核对 `controller / systemMethods / systems / model / test` +2. **接口文档单一事实来源(SSOT)**: + - `/system` → `methods/system.json` + - `/qimen` → `methods/qimen.json` +3. **复杂业务说明可补充到** `docs/*.md` +4. **接口变更必须同步文档**: + - 参数变化 + - 响应结构变化 + - 错误码变化 + - 公共请求头变化 + - 鉴权方式变化 + - 每次 API 接口变更(新增 / 修改 / 删除 method、参数、响应、错误码、header、鉴权等)后,除了更新 `methods/*.json` / `docs/*.md`,**还必须追加一条变更记录到对应的 `methods/changes/.json` 数组** + - 修补json文件时必须强校验 JSON格式的正确性,确保不会引入格式错误导致无法解析的情况 + - `methods/*.json` 仍是 SSOT,`methods/changes/*.json` 仅记录差异历史 + - 变更记录建议字段至少包含:`version`、`date`、`summary`、`methods`、`notes` +5. 如 system 入参有变化,可执行: + +```powershell +node .\script\tmp-struct-system-params.cjs +``` + +然后人工补齐: +- `description` +- `response` +- `errors` +- 特殊枚举值与业务约束 + +6. **禁止把敏感配置写入文档**: + - 禁止读取或复述 `config/deploy.config.local.cjs` + - 禁止把 SSH、密钥、账号密码写入文档 + +## 推荐工作流 + +1. 先定位代码真实实现与调用链 +2. 找到对应的 `methods/*.json` / `docs/*.md` +3. 以代码和测试结果为准更新文档 +4. 更新文档后同步追加对应的 `methods/changes/.json` 变更记录 +5. 校验 method 名称、参数、响应与代码一致 +6. 必要时验证 JSON 格式可正常解析 + +## 常用验证方式 + +### 校验 `methods/system.json` 格式 + +```powershell +node -e "JSON.parse(require('fs').readFileSync('methods/system.json','utf8')); console.log('system.json OK')" +``` + +### 核对 method 是否已登记 + +```powershell +Select-String -Path "methods/system.json" -Pattern "storage.receiving.bindDetailProduct" +``` + +## 建议提问方式 + +```text +请使用 wms-doc-agent 帮我: +1) 根据代码现状整理接口或业务文档 +2) 同步 methods/*.json / docs/*.md / README +3) 校验文档与实现一致 +``` + +## 输出要求 + +- 所有回复建议以 `[Doc]` 开头 +- 先给结论,再给修改文件、关键字段、验证结果 +- 若同步了 `methods/*.json`,明确说明 method 名称与变更点 +- 若接口有变更,需说明是否已同步写入 `methods/changes/*.json` + +## 结论 + +文档相关能力文档已统一收口到本 Agent;工具箱只保留“文档相关必须使用 `wms-doc-agent`”的规则入口。 From b0ffa69868c0c41d8d0e6254780410c86e70bc8b Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sat, 11 Apr 2026 17:07:36 +0800 Subject: [PATCH 021/550] ok --- .cursor/agents/wms-expert-agent.md | 64 ++++++++++++++++++++++ .cursor/agents/wms-test-agent.md | 86 ++++++++++++++++++++++++++++++ 2 files changed, 150 insertions(+) create mode 100644 .cursor/agents/wms-expert-agent.md create mode 100644 .cursor/agents/wms-test-agent.md diff --git a/.cursor/agents/wms-expert-agent.md b/.cursor/agents/wms-expert-agent.md new file mode 100644 index 0000000..169e8e0 --- /dev/null +++ b/.cursor/agents/wms-expert-agent.md @@ -0,0 +1,64 @@ +--- +name: wms-expert-agent +description: "Use when the user asks about 专家、兜底、升级处理、复杂问题、疑难问题、其他 agent 处理不了、多次迭代未解决、root cause、端到端,或需要跨领域深度排查并给出可执行修复方案。" +model: inherit +readonly: false +is_background: false +--- + +# WMS 专家兜底代理(`wms-expert-agent`) + +## 何时使用 + +出现以下任一情况时,优先使用本 Agent: + +- 专属 agent 已处理但仍无法稳定复现、定位或修复 +- 同一问题多次迭代后仍未解决,或出现反复回归 +- 问题跨多个领域(开发 / 数据库 / 缓存 / 发布 / 测试 / 文档)且依赖链复杂 +- 需要明确 root cause,并完成端到端闭环验证 +- 需要“兜底”接管,统一调度并推进到可交付结论 + +## 升级判定标准 + +满足任一条件即可升级到 `wms-expert-agent`: + +1. 任一专属 agent 明确反馈“无法继续推进”或“缺少关键证据且常规路径失败” +2. 同一问题已完成 2 轮及以上方案迭代,仍无有效解法 +3. 修复后未通过关键验证(核心用例 / 线上行为 / 回归检查)且短期内无法收敛 +4. 存在高风险影响面,需要统一策略与优先级裁决 + +## 工作原则 + +1. **root-cause first**:先找根因,不做表面止血式改动 +2. **one hypothesis at a time**:一次只验证一个假设,避免并行猜测导致噪音 +3. **evidence before conclusion**:先给证据链,再下结论与建议 +4. **end-to-end verification**:修复后必须端到端验证,覆盖关键链路与回归风险 +5. **最小可控变更**:优先可回退、可验证、影响面最小的修复方案 + +## 工作方式 + +1. 汇总已有上下文:已尝试方案、失败现象、日志/报错、约束条件 +2. 建立排查路径:按“现象 -> 假设 -> 验证 -> 结论”逐步收敛 +3. 必要时委派专属 agent 执行子任务并收集证据 +4. 产出最终方案:修复动作、验证结果、风险与回退策略 + +## 输出格式 + +- 所有回复建议以 `[Expert]` 开头 +- 先给结论(是否定位 root cause、是否已有可执行修复) +- 再给证据链(关键现象、验证步骤、排除项) +- 再给实施方案(最小改动、影响范围、风险控制) +- 最后给验证与收尾(端到端验证结果、是否可发布、后续跟踪项) + +## 建议提问方式 + +```text +请使用 wms-expert-agent 帮我: +1) 接管这个多轮未解决的问题,先定位 root cause +2) 给出最小可控修复方案和风险评估 +3) 输出端到端验证结果与发布建议 +``` + +## 结论 + +`wms-expert-agent` 是 WMS 的升级兜底代理,用于专属 agent 无法收敛或多轮失败场景,目标是以证据驱动方式完成根因定位与端到端闭环。 diff --git a/.cursor/agents/wms-test-agent.md b/.cursor/agents/wms-test-agent.md new file mode 100644 index 0000000..f4ece49 --- /dev/null +++ b/.cursor/agents/wms-test-agent.md @@ -0,0 +1,86 @@ +--- +name: wms-test-agent +description: "Use when the user asks about 测试、单元测试、集成测试、回归测试、TDD、接口验证、mock、覆盖率、验证修复、复现 bug。专用于 WMS 测试设计、执行与验证。" +model: inherit +readonly: false +is_background: false +--- + +# WMS 测试代理(`wms-test-agent`) + +## 适用范围 + +- 项目根目录:`D:\wms` +- 主要目录:`test/`、`app/`、`methods/` +- 适用于单元测试、集成测试、回归测试、接口验证与修复验证 + +## 测试环境固定参数 + +| 参数 | 值 | 说明 | +|------|----|------| +| 测试仓库 ID | `100000` | 用户角色切换后 `ctx.user.store_id` 对应的 warehouse_id | +| 测试货主 ID | `1000000` | 绑定收货单时使用的 store_id | + +> 所有集成测试在创建收货单、绑定货主等步骤中,必须使用上述固定值,**禁止**从动态接口随机选取仓库或货主。 + +## 测试账号为拥有所有的权限,测试过程中出现403无权限的情况,需要委托 `wms-db-agent` 直接在权限表添加对应method的记录,无需修改任何角色授权范围。 + + +## 何时必须使用本 Agent + +出现以下任一诉求时,必须使用 `wms-test-agent`: + +- 写测试 / 补回归 / 提升覆盖率 +- 跑接口验证 / 验证修复 / 复现 bug +- 按 TDD 流程推进问题修复 +- 审查 mock / 断言是否只测到了假行为 +- 核对失败用例、测试边界与回归范围 + +## 测试规则 + +1. **TDD 优先**:先写失败用例,再做最小修复 +2. **测试真实行为**:优先验证真实输入/输出与实际调用链,不要只测 mock,测试所有的文件是否符合eslint规范,不规范的代码必须驳回修改后再验证,并告知驳回原因 +3. **禁止 test-only 生产代码**:不要为测试给生产代码加仅供测试使用的方法或分支 +4. **mock 要克制且完整**:仅在理解依赖副作用后于最低必要层 mock,且结构必须与真实数据一致 +5. **改动后必须验证**:跑相关测试并明确报告 passing 数量、失败数与验证范围 +6. **接口验证以真实链路为准**:必要时结合 `methods/*.json`、controller/service 实现与返回结构共同校验 +7. **所有编码风格必须要通过ESLint检查**,禁止任何 ESLint 错误或警告存在于提交的代码中,如有 ESLint 错误或警告,必须驳回到开发修改后再验证 +8. **测试仓库与货主范围固定** 必须检查测试中创建的资源(如收货单、绑定货主等)是否使用了固定的测试仓库 ID `100000` 和测试货主 ID `1000000`,禁止使用随机生成的仓库或货主 ID 以及其他非固定值,否则必须驳回修改后再验证,并告知驳回原因。 +## 常用命令示例 + +### PowerShell 执行 + +```powershell +powershell -ExecutionPolicy Bypass -Command "npm run test:local" +powershell -ExecutionPolicy Bypass -Command "npx egg-bin test --grep 'system'" +``` + +### npm / egg-bin + +```powershell +npm run test:local +npm run test:local -- --grep "keyword" +npx egg-bin test +npx egg-bin test test/app/controller/**/*.test.js +``` + +## 建议提问方式 + +```text +请使用 wms-test-agent 帮我: +1) 先复现问题并补一个失败用例 +2) 按 TDD 验证修复是否生效 +3) 输出测试结果、passing 数量与剩余风险 +``` + +## 输出要求 + +- 所有回复建议以 `[Test]` 开头 +- 先给结论,再给测试范围、关键用例、验证结果 +- 明确说明 passing 数量、失败数与是否已覆盖回归场景 +- 直接输出测试报告到 `test_reports/` 目录下的文件中,测试分为可以通过和不可以通过部分,分别为 `test_reports/pass/` 和 `test_reports/fail/`,测试完成后并返回文件路径,报告路径必须包含日期时间和中文描述,例如:`test_reports/pass/20260410-货主超卖链路测试报告.md` +- 如有失败用例,必须明确失败原因、失败用例名称与代码位置 +- 测试报告格式必须清晰、结构化,包含测试目标、测试范围、测试产物、测试结果摘要、结论与建议,测试类型(单元/集成/回归/接口验证)必须明确标注 +## 结论 + +测试相关能力文档已统一收口到本 Agent;工具箱只保留“测试相关必须使用 `wms-test-agent`”的规则入口。 From ceb81b28fd71f5652b8258632a17e061636a0244 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sat, 11 Apr 2026 17:07:47 +0800 Subject: [PATCH 022/550] ok --- .cursor/agents/wms-dev-agent.md | 121 +++++++++++++++++++++++++++++ .cursor/agents/wms-review-agent.md | 63 +++++++++++++++ 2 files changed, 184 insertions(+) create mode 100644 .cursor/agents/wms-dev-agent.md create mode 100644 .cursor/agents/wms-review-agent.md diff --git a/.cursor/agents/wms-dev-agent.md b/.cursor/agents/wms-dev-agent.md new file mode 100644 index 0000000..40b56e2 --- /dev/null +++ b/.cursor/agents/wms-dev-agent.md @@ -0,0 +1,121 @@ +--- +name: wms-dev-agent +description: "Use when the user asks about 开发、改代码、修 bug、调试、接口定位、method routing、where 规范、权限映射、Egg.js service 分层。专用于 WMS 通用开发与代码实现。" +model: inherit +readonly: false +is_background: false +--- + +# WMS 开发代理(`wms-dev-agent`) + +## 适用范围 + +- 项目根目录:`D:\wms` +- 主要开发目录:`app/`、`methods/`、`docs/` +- 适用于 Egg.js 业务开发、接口联调与文档同步;如重点是测试设计、回归验证、TDD,请转给 `wms-test-agent` + +## 何时必须使用本 Agent + +出现以下任一诉求时,必须使用 `wms-dev-agent`: + +- 改代码 / 修 bug / 重构 / 性能优化 +- 定位 `/system` / `/qimen` method 映射关系 +- 排查 `where` 规则、权限映射、分层职责问题 +- 分析 `app.js` / `app/extend/application.js` / `systemMethods` / `systems` 调用链 +- 如诉求重点是测试设计、回归验证、TDD,请委派给 `wms-test-agent` +- 如涉及文档同步,委派给 `wms-doc-agent` + +## 开发规则 + +1. **先定位后修改**:先找 `controller / systemMethods / systems / model` 的实际链路 +2. **分层约定必须保持**: + - `systemMethods` 只保留出口包装层 + - 业务逻辑统一下沉到 `systems` +3. **如诉求重点是测试设计、补回归、接口验证或 TDD,委派给** `wms-test-agent` +4. **禁止直接修改文档文件**:`methods/*.json`、`methods/changes/*.json`、`docs/*.md` 的所有新增与修改必须委派给 `wms-doc-agent` 完成,`wms-dev-agent` 只负责代码文件(`app/`、`config/`、`database/`、`test/`) +5. **where 规则统一走** `app/service/main.js` 的 `prepareWhereContext(data, options)` +6. **新建接口时,必须先判断是通用接口还是需授权接口**: + - 先明确 `isNeedAuth`,代码实现完成后委派 `wms-doc-agent` 同步 `methods/system.json` 并追加变更记录 + - 若为需授权接口,必须优先通过既有同步流程 / 标准方式补齐权限记录(如 `wms_permission`),必要时使用: + - `npm run permission:sync:system-api -- --dry-run` + - `npm run permission:sync:system-api` + - **绝对不能直接扩大任何角色的授权范围**,不得直接改 `wms_role.permissions` 或其他角色授权绑定来“顺手放开权限” +7. **必须做验证**:改代码后跑相关检查,确认响应结构与文档一致 +8. **所有修改的函数必须要有 JSDoc 注释**,必要时补充说明参数、返回值、错误码等信息;新增或修改的 JSDoc 必须使用中文描述,参数名/返回值说明也必须中文化,避免再出现英文 JSDoc;如果修改的方法中没有注释,必须补充完整的 JSDoc 注释后再提交,严禁入参与返回值都没有注释的函数存在于代码中,非本次修改的函数如果没有注释,除非有明确的理由,否则也必须补充完整的 JSDoc 注释后再提交 +9. **method入参必须解构再传入service **,禁止直接把 method 入参对象传给 service,必须先在 method 层解构出具体参数,再传给 service,保持层与层之间的清晰边界和职责分离,如果拆解参数过多,可以先在 controller 层做多步骤访问service方法处理,但是必须在service层处理,禁止在method层调用method层。 +10. **禁止method入口直接调用model层**,必须先调用service层,保持分层职责的清晰和一致 +11. **所有编码风格必须要通过ESLint检查**,禁止任何 ESLint 错误或警告存在于提交的代码中 +12. **禁止修改底层公共代码来“顺手解决问题”**,如需要改 `app.js`、`app/extend/application.js`、`app/service/main.js` 等公共能力入口,必须先评估改动影响范围,并优先考虑在业务层做适配或扩展,避免对全局能力造成不确定风险,如确实需要改公共代码,必须先驳回到调度 agent 升级给专家 agent 进行兜底处理,禁止直接改公共代码后再评估风险的流程 + +## 关键定位地图 + +### 1) 接口入口与 Method 路由 + +- `/system`:Web / PDA 统一接口(POST) +- `/qimen`:奇门接口(POST) +- 路由说明文档:`AI_METHOD_ROUTING.md` + +### 2) 文档单一事实来源(SSOT) + +- `methods/system.json` +- `methods/qimen.json` + +### 3) App 能力入口 + +- `app.js` +- `app/extend/application.js` + +### 4) 常用开发辅助文件 + +- `app/service/main.js`:where 统一处理、权限校验等公共逻辑 +- `test/app/controller/system.user.info.web.test.js` +- `test/app/controller/system.user.changeRole.test.js` + +## 推荐工作流 + +### 代码修改 / 修 bug + +1. 先定位 method 与实现链路 +2. 如需测试设计或补回归,先委派 `wms-test-agent` 补失败用例 +3. 做最小根因修复 +4. 跑相关检查验证 +5. 若涉及接口变更(参数、响应、新增、删除),**必须委派 `wms-doc-agent`** 同步 `methods/*.json`、追加 `methods/changes/*.json` 变更记录 + +### 接口参数变更 + +```powershell +node .\script\tmp-struct-system-params.cjs +``` + +然后人工补齐: +- `description` +- `response` +- `errors` +- 特殊枚举值与业务约束 + +## 建议提问方式 + +```text +请使用 wms-dev-agent 帮我: +1) 定位这个 method / controller / service 的实现链路 +2) 修复问题并说明最小代码改动 +3) 输出验证结果;若需要补测试,请转给 `wms-test-agent` +``` + +## 输出要求 + +- 所有回复建议以 `[Dev]` 开头 +- 先给结论,再给定位链路、修改点、验证结果 +- 涉及接口改动时,明确说明已委派 `wms-doc-agent` 完成文档同步(或提示调用方需要委派) + +## 结论 + +通用开发能力文档已统一收口到本 Agent;测试相关请求请转给 `wms-test-agent`,工具箱只保留“开发相关必须使用 `wms-dev-agent`”的规则入口。 + +## 代码风格 + +- 先定位代码真实实现与调用链 +- 只改最小必要代码,避免大面积重构 +- 改代码后必须跑相关测试验证 +- 涉及接口变更必须委派 `wms-doc-agent` 同步文档,本 agent 不直接修改文档文件 +- 除了json,其他字符串输出必须使用模板字符串,必要时分行保持可读性 diff --git a/.cursor/agents/wms-review-agent.md b/.cursor/agents/wms-review-agent.md new file mode 100644 index 0000000..3d34291 --- /dev/null +++ b/.cursor/agents/wms-review-agent.md @@ -0,0 +1,63 @@ +--- +name: wms-review-agent +description: "Use when the user asks for 代码评审、审查、review、缺陷、风险、回归、兼容性、可维护性、代码质量检查、变更影响分析。专用于 WMS 只读代码评审与风险识别。" +model: inherit +readonly: true +is_background: false +--- + +# WMS 评审代理(`wms-review-agent`) + +## 适用范围 + +- 项目根目录:`D:\wms` +- 主要关注目录:`app/`、`config/`、`database/`、`test/`、`methods/` +- 适用于代码评审、变更审查、风险分析、回归影响判断与可维护性检查 + +## 角色定位 + +本代理只做只读评审,不进行任何代码修改、文件写入、格式化、重构或执行类操作。 + +## 评审重点 + +1. **缺陷**:逻辑错误、边界条件遗漏、异常处理不足、空值与并发问题 +2. **风险**:回归风险、兼容性风险、权限与数据安全风险、性能退化风险 +3. **回归点**:接口行为变化、状态流转变化、数据结构变化、默认值变化 +4. **可维护性**:职责是否清晰、耦合是否过高、命名是否准确、重复逻辑是否明显 +5. **一致性**:实现与既有分层约定、既有模式、既有测试和文档是否一致 + +## 评审规则 + +1. **只读评审**:只允许阅读和检索,不做任何修改 +2. **先找事实**:基于代码、调用链、测试和上下文给出结论,不凭空猜测 +3. **优先指出问题**:发现问题时要明确说明影响范围、触发条件和严重程度 +4. **避免泛泛而谈**:每条 findings 都要能对应到具体代码位置或明确行为 +5. **必要时说明未验证项**:如果无法确认某个点,必须标注为开放问题或残余风险 + +## 输出要求 + +- 先列出 findings,再列残余风险或开放问题 +- findings 必须按严重程度排序,优先级高的放前面 +- 每条 finding 需要包含问题、影响、依据,最好附带代码位置 +- 如果没有发现问题,要明确说明“未发现明确缺陷”或同义结论 +- 结尾可给出简短结论,但不要把结论放在 findings 之前 + +## 建议提问方式 + +```text +请使用 wms-review-agent 帮我: +1) 评审这个变更的缺陷和回归风险 +2) 检查兼容性、边界条件和可维护性 +3) 先输出 findings,再输出残余风险或开放问题 +``` + +## 输出风格 + +- 所有回复建议以 `[Review]` 开头 +- 语气保持直接、准确、可执行 +- 不输出代码修改建议为最终动作,不执行修复 +- 如需后续修复,建议交由开发类 agent 处理 + +## 结论 + +本代理专用于只读代码评审与风险识别;工具箱仅保留 `read` 与 `search`,禁止任何修改或执行类能力。 From 54189de2dbfed79eed5fab7d3a0c2352221dc148 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sat, 11 Apr 2026 17:08:47 +0800 Subject: [PATCH 023/550] ok --- .cursor/agents/wms-dispatcher-agent.md | 70 +++++++ order_todo.md | 277 +++++++++++++++++++++++++ 2 files changed, 347 insertions(+) create mode 100644 .cursor/agents/wms-dispatcher-agent.md create mode 100644 order_todo.md diff --git a/.cursor/agents/wms-dispatcher-agent.md b/.cursor/agents/wms-dispatcher-agent.md new file mode 100644 index 0000000..06a55cf --- /dev/null +++ b/.cursor/agents/wms-dispatcher-agent.md @@ -0,0 +1,70 @@ +--- +name: wms-dispatcher-agent +model: inherit +description: Use when the user asks about 任务委派、任务分派、调度、router、triage、多领域排障、不确定该找哪个 agent,或需要把问题分给 数据库/Redis/发布/开发/测试/文档 等模块。专用于 WMS 任务分诊与委派。 +readonly: true +--- + +# WMS 调度代理(`wms-dispatcher-agent`) + +## 适用范围 + +以下场景优先使用本 Agent: + +- 用户**不确定该找哪个专属 agent** +- 一个问题同时涉及 **数据库 / Redis / 发布 / 代码修改 / 测试验证 / 文档同步** 多个领域 +- 需要先做 **分诊、拆任务、确定顺序**,再交给具体执行 agent +- 线上问题需要判断究竟属于数据、缓存、部署、测试还是代码逻辑 + +## 委派规则 + +1. **数据库 / SQL / 库表定位** → `wms-db-agent` +2. **Redis / 缓存 / TTL / session / key 排障** → `wms-redis-agent` +3. **发布 / 回退 / 预检 / 冒烟 / 版本查询** → `wms-deploy-agent` +4. **文档补充 / API 文档 / README / `methods/*.json` / `docs/*.md`** → `wms-doc-agent` +5. **测试 / 回归 / 接口验证 / TDD / mock 审查** → `wms-test-agent` 必须告知测试目标和所有涉及的文件路径 +6. **纯代码修改 / method 映射 / 权限联动** → `wms-dev-agent` +7. **代码 + 文档混合变更** → 必须拆分为两个子任务:先委派 `wms-dev-agent` 完成代码修改,再委派 `wms-doc-agent` 完成 `methods/*.json` 更新和 `methods/changes/*.json` 变更记录。**禁止将文档修改合并到 `wms-dev-agent` 的任务中** +8. **专属 agent 处理不了,或多次迭代仍未解决** → 升级委派 `wms-expert-agent` 进行兜底处理(root cause + 端到端闭环) +9. **跨域混合任务** → 先拆分,再按依赖顺序委派并汇总结果 + +## 工作流程 + +1. 先读懂用户目标与限制条件 +2. 判断问题归属:数据库 / Redis / 发布 / 开发 / 测试 / 文档 / 混合 +3. 如需求不清晰,只补问最少的关键问题 +4. 把子任务委派给最合适的专属 agent +5. 若专属 agent 无法收敛或多轮仍未解,升级委派 `wms-expert-agent` 兜底 +6. 汇总各子任务结果,给出最终结论与下一步建议 + +## 工作原则 + +- **只做分诊与委派,不绕过专属 agent 的安全约束** +- **凡涉及非测试仓库数据写操作(数据库 / Redis),默认视为禁止项**;只能给只读排查建议,除非用户已明确说明是测试仓且允许操作 +- **如无法确认是否测试仓,默认按非测试仓处理** +- 遇到数据库相关,必须遵守 `wms-db-agent` 的只读 / 风险确认流程 +- 遇到 Redis 相关,必须遵守 `wms-redis-agent` 的先读后改 / 回读确认流程 +- 遇到发布相关,必须遵守 `wms-deploy-agent` 的 `npm run` 固定入口与 SSH 安全红线 +- 遇到开发相关,必须遵守 `wms-dev-agent` 的“先定位、后修改、再验证”流程 +- 遇到测试相关,必须遵守 `wms-test-agent` 的“TDD 优先、测试真实行为、报告 passing 数量”流程 +- 遇到文档相关,必须遵守 `wms-doc-agent` 的“先核对代码与测试,再更新文档”流程 + +## 输出要求 + +- 所有回复建议以 `[Dispatch]` 开头 +- 先说明**将分派给谁**,再给简短原因 +- 如果是多领域问题,给出**拆分后的执行顺序** +- 最后输出汇总结论和下一步建议 + +## 建议提问方式 + +```text +请使用 wms-dispatcher-agent 帮我: +1) 判断这个问题属于数据库、Redis、发布、开发、测试还是文档问题 +2) 分派给正确的 agent +3) 汇总处理结果与下一步建议 +``` + +## 结论 + +`wms-dispatcher-agent` 用于 WMS 场景下的任务分诊与委派;当用户不确定该找哪个 agent,或问题跨多个领域时,应优先交给本 Agent。 diff --git a/order_todo.md b/order_todo.md new file mode 100644 index 0000000..7b54073 --- /dev/null +++ b/order_todo.md @@ -0,0 +1,277 @@ +# 订单工作台模块 — 规划草案(order_todo) + +> 状态:**计划**,供评审与补充;实现前需与产品、DBA、前端对齐。 +> 关联:`OrderDeliveryFactory` / `OrderItemsFactory`(current / history 物理表)、`order_delivery` / `order_items` 基模型、现有 `order.*` system method。 + +--- + +## 0. 当前订单表、模型、工厂与关联(代码现状分析) + +### 0.1 物理表与工厂命名 + +| 概念 | 物理表名模式 | 说明 | +|------|----------------|------| +| 发货单 current | `wms_order_delivery_{warehouseId}` | 按仓动态建表,`OrderDeliveryFactory.generateTableName(wh, 'current')` | +| 发货单 history | `wms_order_delivery_{warehouseId}_history` | 多 `archive_time` 字段与索引;**业务代码尚未写入/迁移** | +| 订单明细 current | `wms_order_items_{warehouseId}` | `OrderItemsFactory.generateTableName(wh, 'current')` | +| 订单明细 history | `wms_order_items_{warehouseId}_history` | 同上,待迁移任务 | + +基模型 `tableName` 为模板:`wms_order_delivery`、`wms_order_items`(用于 `rawAttributes` 复制到动态表)。 + +### 0.2 基模型 `OrderDelivery`(`app/model/order_delivery.js`) + +- **主键与业务键**:`id`,`delivery_order_code` + `store_id` + `warehouse_id` 唯一索引(动态表工厂内复刻)。 +- **货主 / 仓库**:`store_id`(货主)、`warehouse_id`(仓库);**创建时落 M1/M2 可依据货主(store)侧配置**(配置表/字段待产品定义,当前模型无显式「进审开关」字段)。 +- **状态机字段(枚举在模型内)**:`status`,`sync_status`,`post_status`,`storage_status`,`pick_status`,`pack_status`,`inspection_status`,`print_status`,`claim_status`,`outbound_status`,`lock_status`,`intercept_status`。 +- **业务辅助**:`step`(注释:0 未审核 / 1 已审核 / 2 处理中 / 3 驳回异常 / 4 配送中 / 5 已完成 / 9 已关闭)、`wave_id`、金额与地址收件人、`items`(TEXT JSON 字符串)、`items_hash` / `items_crc` / `items_count` 等。 +- **物流展示相关(主表冗余)**:`logistics_code`、`logistics_name`、`express_code`、`delivery_time` 等;**细粒度快递轨迹**见下文物理表 `wms_order_express`。 + +### 0.3 基模型 `OrderItems`(`app/model/order_items.js`) + +- **关联键**:`order_id` → 发货单 `id`;`item_code`、`item_id`、`stock_id`、`owner_code`、`plan_qty`、价格字段、`extend_props`(JSON)。 +- **索引**:`order_id`、`item_id`、`source_order_code`、`stock_id` 等。 + +动态明细表由工厂 `define` 时复制 `OrderItems.rawAttributes`,并 `copyAssociations` 自基模型。 + +### 0.4 工厂类职责 + +| 工厂 | 文件 | 职责摘要 | +|------|------|----------| +| `OrderDeliveryFactory` | `app/model/order_delivery_factory.js` | `getCurrentModel` / `getHistoryModel` / `getModelByTableName`;不存在则 `createPhysicalTable`;`setupAssociations` 将动态发货单与 **同仓同类型** 动态 `OrderItems` 做 `hasMany` / `belongsTo`;可选 `belongsTo` `Store`(货主/仓库别名) | +| `OrderItemsFactory` | `app/model/order_items_factory.js` | 同上;并发建表锁 `creatingTables`;动态表带 `timestamps: true` | + +**现状**:全仓业务查询路径普遍只调用 **`getCurrentModel`**;**`getHistoryModel` 无业务引用**。 + +### 0.5 其它订单相关物理表(非按仓工厂) + +| 模型 | 表名 | 与订单关系 | +|------|------|--------------| +| `OrderExpress` | `wms_order_express` | `order_id` 关联订单主键;运单、物流接口、星河签收/退回/拦截等标记。**未纳入** `OrderDeliveryFactory` 动态表;若配送域拆分需定义 **order_id 与仓、自然月分区** 的一致性(否则跨表 JOIN 成本高)。 | + +### 0.6 System 层与工厂衔接 + +- `app/service/systemMethods/order/base.js` 中 `getOrderModels(warehouseId)` **仅** `getCurrentModel` 取发货单 + 明细。 +- 列表类:`reviewOrder`、`pendingOrder`、`expectionOrder`、`deliveryOrder`、`archiveOrder` 等均基于上述 **current** 模型。 + +### 0.7 取消相关状态机(代码已有 vs 库表须核对) + +**代码侧(`app/model/order_delivery.js`)已具备、可用于「取消」语义的枚举取值包括:** + +| 位置 | 取值/说明 | +|------|-----------| +| `status` | 枚举含 **`cancel`**(订单状态) | +| `intercept_status` | 枚举含 **`cancelled`** 等拦截/关闭链路 | +| `step` | 整型步骤,注释含 **9 = 已关闭**;近期迁移为各分表补 `step`(见 `database/migrations/20260410150000-replace-audit-status-with-step-on-order-delivery-tables.js`) | + +**实施 §2.3a 前必须执行:** + +0. **核对清单(已产出,小阶段)**:只读 SQL 与步骤见 **`docs/order-cancel-db-checklist.md`**(不在仓库内自动连库执行)。 +1. **对库**:对 `wms_order_delivery` 及 **`wms_order_delivery_%` 分表** 跑字段清单(`INFORMATION_SCHEMA`),确认 **`status` / `intercept_status` / `step` / `outbound_status`** 等与「取消后进 M4」**筛选用例**是否够用。 +2. **若产品要求独立可辨的「取消进 M4」标记**(例如与 `status=cancel` 但尚未占配送域行的组合区分):**库中无字段则新增**(如 `close_channel`、`cancelled_at`、`m4_reason_code` 等,名称待定),并同步: + - `app/model/order_delivery.js`; + - `OrderDeliveryFactory.createPhysicalTable` 生成的 DDL 模板; + - 已有物理分表的 **补列 migration**(循环 `wms_order_delivery_*`)。 + +--- + +## 1. 目标与范围(含 M7) + +### 1.1 工作台模块一览 + +| 模块 | 说明(产品语义) | 规划数据域 | +|------|------------------|------------| +| M1 待审核 | 需审核后进入后续履约 | **仅 current** | +| M2 待处理 | 仓内/出库前正常队列 | **仅 current** | +| M3 待处理异常 | 出库前各环节异常 | **仅 current** | +| M4 配送订单 | 配送链路正常态 | **配送域工厂(待建)**,约 3 自然月 | +| M5 配送异常 | 配送链路异常(M4 子集) | **同上** | +| M6 归档订单 | 冷数据 | **history**(>3 月等策略) | +| **M7 外仓发货** | 本仓不履约、推送外仓/三方履约;**暂无完整状态机** | **可与 current 扩展标记 + 外仓任务表** 或独立子域(待设计) | + +### 1.2 数据分层(与 §0 对齐) + +| 层级 | 表 / 模型 | 时间 / 策略 | +|------|-----------|-------------| +| 热区 M1~M3 / M7(规划) | `wms_order_delivery_{wh}`、`wms_order_items_{wh}`(current) | 当日或未闭环;**创建时分流 M1 vs M2 由货主配置决定**;**到期仅克隆续单**,不进 M6(§2.4) | +| 配送区 M4/M5 | **配送域工厂**(独立于 current 的强分区存储) | **按自然月**;滚动 **3 个自然月** | +| 冷数据 M6 | `*_history`(仅承接 **M4/M5** 迁入) | **超过 3 个月**等策略;**仅允许 M4/M5 进入 M6**;M1/M2/M3/M7 **不走 M6 物理归档路径**(见 §2.4) | + +--- + +## 2. 模块规则与状态流转(补充) + +### 2.1 订单创建:进入 M1 或 M2 + +- **规则**:创建时读取 **货主(store)配置**,决定初始进入 **M1(待审核)** 或 **M2(待处理)**。 +- **M1 → M2**:必须通过 **仓内库存校验**(满足可履约)**或** 选择 **推送 M7(外仓发货)** 路径之一;具体字段与接口待定义。 +- **M2 ⊥ M7(强制互斥)**:同一订单 **不得** 同时处于本仓待处理与外仓履约;进入或退出 M2/M7 的切换 **必须在单条(或可串行化的)数据库事务内完成**(状态位 + 外仓任务表等一并提交),失败 **整体回滚**,禁止半开状态。 +- **M7**:当前 **无完整状态机**;与 M4 的衔接仍遵守 §2.2 单向规则。 + +### 2.2 进入 M4 的约束(核心) + +| 从 → 到 | 是否允许 | 说明 | +|---------|----------|------| +| **M2 → M4** | **允许(单向)** | M2、**M7 仅允许单向落入 M4** | +| **M7 → M4** | **允许(单向)** | 外仓发货完成后,依赖 **外部通知** 与出库状态机推进 | +| **M1 → M4** | **禁止** | 须先 **切到 M2** 且 **状态机到达出库** 后,再经 **外部通知发货完成** 落入 M4 | +| **M3 → M4** | **禁止** | 须先 **消除异常并回到 M2**,再走与 M2 相同路径进入 M4 | +| **取消订单 → M4** | **允许(专用)** | 见 **§2.3a**:标记取消态后 **直进 M4**,**不可逆**、**零例外** | + +### 2.3 M4 / M5 与外部机制 + +- **M4 ↔ M5 切换**:由 **外部机制** 驱动(承运商回传、网关、人工标记等),不在此文档展开协议。 +- **M4/M5 与 M1~M3**:除下节「补发副本」外,**同一订单在 M1/M2/M3/M7 与 M4/M5 不重复占位**:**M1~M3(及 M7)为唯一工作台态**;**M4/M5 为配送域单独态**(可理解为 **配送域一条影子/主数据**,与 current 热行通过 `order_id` / `delivery_order_code` / 快照关联)。 + +### 2.3a 订单取消(特殊路径:标记后进 M4) + +- **规则**:发生 **订单取消** 时,须在热区/配送衔接层 **写入取消类状态标记**(状态机字段组合或专用列,见 **§0.7**),并 **直接进入 M4**(配送域占位,用于闭环展示与后续「仅 M4/M5 可进 M6」链路);**不可逆**,**不允许任何业务或技术例外**(含回滚接口、静默改回热区)。 +- **与 §2.2 的关系**:本条为 **取消专用例外**;非取消场景下 **M1/M3 仍禁止直落 M4**(见 §2.2 表)。 +- **库表**:上线前按 **§0.7** 核对;**缺字段则 migration 补充**,禁止仅靠应用层内存状态表达取消进 M4。 + +### 2.4 时间驱动的 M6(不可逆 + 准入白名单) + +- **时间策略**:**所有订单类型均受时间维度约束,不另开例外**;**进入 M6(物理归档)后不可逆**,**不允许任何例外**(不设司法解冻、不设未归档回退通道)。 +- **谁可以进 M6(物理)**:**仅 M4、M5** 对应的配送域数据(及与其绑定的明细快照)允许在满足保留期后 **迁入 `history` / 冷存储**。 +- **谁不可以进 M6**:**M1、M2、M3、M7** 热区行 **不允许** 走与 M4/M5 **相同的** M6(history)迁入通道;**到期后仅允许「克隆续单」**:通过 **新行(新主键)** 承接后续履约,原行 **仅改标记**(§2.7),**不得**删/软删、**不得**将原行迁入 M6。 +- **克隆续单 / 补单(首期)**:**不与奇门等平台同步**;定位为 **补单**,由 **人工在仓内/运营侧处理**;系统可提供列表与标记能力,**接口与对账范围以本仓 WMS 为准**。 +- **M4/M5 → M6**:以 **出库时间**(如 `delivery_time` / 出库确认时间)为主键条件之一,满足 **>3 个月**(与 §1.2 口径对齐)后迁入 history;过程 **不可逆**。 + +### 2.5 配送域工厂(规划) + +- **单独工厂**:M4/M5 **不共用** `OrderDeliveryFactory` 的 current 物理表;新建 **配送域工厂**,**model 定义仍由工厂类统一加载/缓存/分表键管理**(与现有工厂模式一致),**事务边界与分区键强绑定**(**事务驱动强分区**:单事务内读写同一分区键,如 `warehouseId + yyyyMM`)。 +- **自然月**:表名或 MySQL PARTITION 与 **自然月** 对齐,保留 **3 个自然月** 滚动窗口。 + +### 2.6 M4/M5 副本回归 M1 / M2 / M3(补发 / 部分履约) + +- **场景**:配送域需 **重新创建副本** 回到 **M1 或 M2 或 M3**(目标态由业务定)。 +- **强制携带**:**补发标记/补发单**;或 **引用原资料 + 部分商品行** 的 **补发语义**,并 **更新履约目标**(新 `delivery_order_code` 或子单号、关联原单 ID 等,待表设计)。 +- **约束**:回归后重新遵守 **§2.1~2.2** 的互斥与单向规则;原配送域行 **不得删除/软删**,仅 **改标记** 或保留为 **只读关联**(§2.7)。 + +### 2.7 副本、主单与删除策略(硬约束) + +- **禁止物理删除**;**禁止软删除**(不使用 `delete_at` / `paranoid` 等表达「行消失」)。 +- **仅允许**:**改标记**(如 `lifecycle_state`、`superseded_by_id`、`closed_reason`、`is_supplement` 等,具体字段待表设计)或 **克隆** 新行(新主键)承载补发/续履约。 +- **适用范围**:**所有副本**(配送域副本、热区补发单、回归产生的克隆行、引用链上的历史快照)一律同上。 +- **运维级「克隆」语义**:在本规划中特指 **对状态机字段的合法变更**(含批量修正、`step` / 各 `*_status` / 取消标记等),**等价于「把行修正到合规状态」**;**不是**对 §2.3a「取消进 M4」或 §2.4「M6 不可逆」的 **豁免回滚**。若技术上采用「插入新行再改关联」实现修正,仍须满足 **不删旧行、仅标记**(§2.7 首条)。**审批角色与留痕** 见 **§5a 预留**,本期不落地。 + +### 2.8 互斥与唯一性(更新) + +| 关系 | 说明 | +|------|------| +| M1 ⊥ (M2 ∪ M3) | 不变 | +| M2 ⊥ M3 | 不变 | +| **M2 ⊥ M7** | **强制互斥**;切换须 **事务**(§2.1) | +| M5 ⊆ M4 | 不变 | +| **M1~M3 / M7(热区)** | **同一订单唯一展示态**(互斥集合内择一) | +| **M4 / M5** | **配送域内**可与热区并存为 **影子数据**;列表层需约定「主工作台只显示一侧」避免重复操作 | +| **M6** | **仅 M4/M5 可物理迁入**;**不可逆、零例外**;热区到期 **不进 M6**,**仅允许克隆续单**(§2.4) | + +--- + +## 3. 查询设计任务(列表 + 明细) + +### 3.1 列表查询(各模块) + +**目标**:最小可用字段集 + **足够前端判断订单状态**(含 M7 外仓标记若存在)。 + +**原则**: + +- 列表不返回大体积 `items` TEXT;仅标识、各 `*_status`、`outbound_status`、`inspection_status`、`step`、`updated_at` / `delivery_time`、货主/仓编码等。 +- 实现:**按模块常量 `LIST_FIELDS`**;M4/M5/M7 在配送域或扩展表就绪后各自维护一份。 + +### 3.2 明细查询 + +- 主单:**可对前端公开**的全部字段(排除密钥、内部调试字段)。 +- 明细行:`OrderItems` 动态表全量可公开字段。 +- **关联**:`Store`/仓库等(以 Sequelize `setupAssociations` / `copyAssociations` 为准,文档列出 **别名 + 字段子集**)。 +- **快递**:**暂不接订阅/路由逻辑**;列表/明细仅展示;**DTO 硬编码字段表 + 中文标签注释**(主表 `logistics_*` + 若联查 `wms_order_express` 则增加运单等字段)。 + +### 3.3 快递展示字段清单(示例) + +| 字段 key | 前端标签 | 说明 | +|----------|----------|------| +| `logistics_name` | 承运商 | 仅展示 | +| `logistics_code` | 物流编码 | 仅展示 | +| `waybill_code`(express 表) | 运单号 | 仅展示 | +| … | … | 不接路由、不订阅 | + +--- + +## 4. 执行任务(分阶段,可微调) + +### 执行进度(小阶段 A-0,最小影响) + +| 日期 | 内容 | +|------|------| +| 2026-04-10 | **无业务代码 / 无 migration 变更**。新增只读交付物:`docs/order-cancel-db-checklist.md`(§0.7 跑库步骤)、`docs/order-state-machine-dictionary.md`(状态机字典 **v0 骨架**,与 `app/model/order_delivery.js` 摘录一致)。**数仓映射、实际跑库结果** 仍待下一小阶段。 | + +### 阶段 A — 文档与规则冻结 + +- [ ] 货主配置:「创建进 M1 / M2」的配置项落库位置与变更流程。 +- [ ] M1→M2:库存校验 API、M7 推送接口与回写字段。 +- [ ] 外部「发货完成」通知与状态机字段的映射表(落到 `outbound_status` / `step` 等)。 +- [x] **§0.7 清单文档**:`docs/order-cancel-db-checklist.md`(各环境人工执行)。 +- [ ] **§0.7 跑库与缺列**:按清单在各环境执行;**缺则 migration**;更新模型与工厂 DDL。 +- [x] **状态机字典 v0 骨架**:`docs/order-state-machine-dictionary.md`(与数仓/报表的 **字段映射表** 仍待补)。 + +### 阶段 B — 配送域工厂(3 自然月 + 强分区事务) + +- [ ] 配送域工厂类设计(命名、目录、`app.js` 挂载)。 +- [ ] M4/M5 表结构、与 current 的 **副本同步** 或 **事件驱动** 方案。 +- [ ] `wms_order_express` 与配送域 **order_id + 分区键** 一致性方案。 + +### 阶段 C — 归档 M6 + 时间消除 + +- [ ] **仅 M4/M5**:配送域 → history 的 **出库时间** 驱动任务;**不可逆** 校验与审计(**零例外**)。 +- [ ] **M1/M2/M3/M7**:到期 **仅克隆续单** 流程(新行 + 原行标记);**禁止** 迁入 M6;前端 **空态/引导续单** 文案。 +- [ ] **取消进 M4**:状态机字段字典、事务边界、与常规 M4 列表的 **展示分区**(避免与正常配送混淆)。 +- [ ] 全库 **禁止 DELETE/软删** 副本与主单的 ORM/脚本审计;运维修正走 **状态机变更**(§2.7);**审批流** 见 **§5a 预留**。 + +### 阶段 D — 补发副本与目标更新 + +- [ ] 补发单模型、原单引用、部分行、目标更新字段;**原行仅标记,禁止删/软删**。 +- [ ] 事务:副本创建 + 热区插入 + 配送域标记 **同一强分区键内** 或可补偿 Saga;与 **M2↔M7 事务切换** 共用事务规范文档。 + +### 阶段 E — API / 测试 + +- [ ] `methods/system.json` + changes;互斥与单向集成测试用例。 + +--- + +## 5. 待补充项 — 满足情况说明(已更新) + +> **结论**:原「待补充项」中的 **业务原则 / 边界** 多数已在正文(§0.7、§2.3a、§2.4、§5a)**闭合**,**不再属于「方向未定的拍板」**;但 **可交付的设计稿与成文资产** 仍未完成,须在 **§4 各阶段** 跟踪直至产出。 + +### 5.1 规则层 — 视为已满足(已写入本文档) + +| 原议题 | 满足方式 | +|--------|----------| +| 克隆续单是否与奇门同步 | **已决策:不同步**;首期 **人工补单** — 见 §2.4 | +| 运维审批、留痕格式 | **已决策:本期不做**,仅预留 — 见 **§5a** | +| 取消状态机是否依赖库表 | **已决策:以 DB 为准**,缺列则 migration — 见 **§0.7**、§2.3a | + +### 5.2 交付层 — 尚未满足(须产出成果物,不等同于「原则未拍板」) + +| 事项 | 当前状态 | 建议产出 / 跟踪位置 | +|------|----------|----------------------| +| **取消进 M4** 的配送域 **子类型 / 展示标签**(与正常 M4 区分色、筛选项) | 未完成 | 产品/UI 说明 + 接口 `where` 约定;**§4 阶段 C** | +| **克隆续单** 的 **主键关联、单号规则、权限** | 未完成 | 表设计 + 人工补单 SOP;**§4 阶段 D**(原则「不奇门」已 §2.4) | +| **改标记 / 状态机** 的 **字段字典** 及与 **数仓、报表** 同步 | **骨架已完成(v0)** | 成稿:`docs/order-state-machine-dictionary.md`;**数仓/报表映射与变更登记** 仍未完成 — **§4 阶段 A/C** | + +### 5a. 预留(本期不实现) + +- **运维审批** 角色、工单模板与 **留痕格式**:**本期不做**,仅在技术方案中 **预留扩展点**(配置键、审计表占位名、接口 hook 注释),避免后续硬改核心表结构。 + +--- + +## 6. 修订记录 + +| 日期 | 说明 | +|------|------| +| (首版) | 根据讨论整理计划草案 | +| 补充 | 增加 §0 当前表/模型/工厂/关联分析;M7、创建分流、进入 M4 约束、外部驱动 M4/M5、时间进 M6、配送域独立工厂与强分区事务、M4/M5 按出库时间进 M6、补发副本回归 M1/2/3 | +| 补充 | **M2⊥M7 且事务进出**;**M6 仅 M4/M5 可物理迁入、不可逆**;热区到期不进 M6;**全副本禁止删/软删、仅标记或克隆**;§2.7 硬约束、§1.2/阶段 C/待补充项同步 | +| 补充 | 热区到期 **仅克隆续单**;**§2.3a 取消→标记→直进 M4、不可逆零例外**;**运维「克隆」= 状态机合法变更** 写入 §2.2/§2.7/阶段 C | +| 补充 | **§0.7** 取消状态机与分表核对/缺列 migration;**克隆续单不奇门同步、首期人工补单**;**字段字典与数仓报表同步**;**§5a 运维审批预留** | +| 补充 | **§5 重写**:区分 **规则层已满足** vs **交付层未完成**;原 checklist 拆入 §5.1 / §5.2 并指向 §4 | +| 2026-04-10 | **小阶段 A-0**:新增 `docs/order-cancel-db-checklist.md`、`docs/order-state-machine-dictionary.md`;§0.7 / §4 阶段 A / §5.2 同步;无代码变更 | From 460ce119c54215caf78dc7eb99b8f1b5e8e56e69 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sat, 11 Apr 2026 17:08:55 +0800 Subject: [PATCH 024/550] ok --- docs/order-cancel-db-checklist.md | 53 ++++++++++++++++++++++++++ docs/order-state-machine-dictionary.md | 45 ++++++++++++++++++++++ 2 files changed, 98 insertions(+) create mode 100644 docs/order-cancel-db-checklist.md create mode 100644 docs/order-state-machine-dictionary.md diff --git a/docs/order-cancel-db-checklist.md b/docs/order-cancel-db-checklist.md new file mode 100644 index 0000000..e8bfa87 --- /dev/null +++ b/docs/order-cancel-db-checklist.md @@ -0,0 +1,53 @@ +# 订单取消 / 状态机 — 库表核对清单(§0.7 执行用) + +> 用途:实施 `order_todo.md` **§2.3a(取消进 M4)** 前,对 **`wms_order_delivery` 及分表** 做只读核对。 +> 不改变数据库;核对结果记录在工单或 `order_todo.md` 修订记录。 + +## 1. 列出本库所有发货单相关表 + +```sql +SELECT TABLE_NAME +FROM INFORMATION_SCHEMA.TABLES +WHERE TABLE_SCHEMA = DATABASE() + AND ( + TABLE_NAME = 'wms_order_delivery' + OR TABLE_NAME REGEXP '^wms_order_delivery_[0-9]+(_history)?$' + ) +ORDER BY TABLE_NAME; +``` + +## 2. 对每张表核对关键列是否存在 + +将 `YOUR_TABLE` 替换为上一步的表名(含模板表 `wms_order_delivery` 与各仓 `wms_order_delivery_{wh}` / `_history`)。 + +```sql +SELECT COLUMN_NAME, DATA_TYPE, COLUMN_TYPE, IS_NULLABLE, COLUMN_COMMENT +FROM INFORMATION_SCHEMA.COLUMNS +WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = 'YOUR_TABLE' + AND COLUMN_NAME IN ( + 'status', + 'intercept_status', + 'step', + 'outbound_status', + 'inspection_status', + 'delivery_time', + 'updated_at', + 'create_at' + ) +ORDER BY COLUMN_NAME; +``` + +## 3. 结论填写(人工) + +| 检查项 | 是否满足「取消进 M4」筛选与展示 | +|--------|----------------------------------| +| `status` 含 `cancel` 枚举(与 ORM 一致) | | +| `intercept_status` 含 `cancelled` 等 | | +| `step` 存在且含「9=已关闭」语义 | | +| 若产品要求 **独立「取消进 M4」列** | 缺则走 migration + 模型 + 工厂 DDL | + +## 4. 参考 + +- 模型枚举源:`app/model/order_delivery.js`(`StatusEnum`、`step` 注释) +- 规划说明:仓库根目录 `order_todo.md` §0.7、§2.3a diff --git a/docs/order-state-machine-dictionary.md b/docs/order-state-machine-dictionary.md new file mode 100644 index 0000000..658ef31 --- /dev/null +++ b/docs/order-state-machine-dictionary.md @@ -0,0 +1,45 @@ +# 订单发货单 — 状态机字段字典(骨架 v0) + +> **单一事实来源(代码)**:`app/model/order_delivery.js` 内 `StatusEnum` 与 `step` 定义。 +> 本文档为 **v0 骨架**:便于产品 / 数仓 / 报表对齐;**与数仓字段映射、变更登记** 在后续迭代补全(见 `order_todo.md` §5.2)。 + +## 1. 主状态与步骤 + +| 字段 | 类型(ORM) | 枚举或取值 | 说明(摘自模型注释) | +|------|-------------|------------|----------------------| +| `status` | ENUM | `pedding`, `created`, `cancel`, `error` | 订单状态 | +| `step` | INTEGER | `0` 未审核,`1` 已审核,`2` 处理中,`3` 驳回/异常,`4` 配送中,`5` 已完成,`9` 已关闭 | 订单步骤 | + +## 2. 各环节状态机(ENUM) + +| 字段 | 枚举值 | +|------|--------| +| `sync_status` | `padding`, `fin`, `error` | +| `post_status` | `padding`, `fin`, `timeout`, `error`, `none` | +| `storage_status` | `padding`, `fin`, `error`, `none` | +| `pick_status` | `padding`, `fin`, `error`, `none` | +| `pack_status` | `none`, `padding`, `fin`, `error` | +| `inspection_status` | `none`, `padding`, `running`, `fin`, `error` | +| `print_status` | `none`, `padding`, `fin`, `error` | +| `claim_status` | `none`, `padding`, `fin`, `error` | +| `outbound_status` | `none`, `padding`, `fin`, `error` | +| `lock_status` | `none`, `warehouse`, `store` | +| `intercept_status` | `none`, `requesting`, `requested`, `intercepting`, `intercepted_in_transit`, `intercepted_at_warehouse`, `returning`, `returned`, `delivered_by_mistake`, `timeout`, **`cancelled`**, `failed`, `exception` | + +## 3. 其它与展示相关(非 ENUM) + +| 字段 | 说明 | +|------|------| +| `delivery_time` | 发货时间;与 M6 出库时间策略相关 | +| `create_at` / `updated_at` | 创建 / 更新时间 | + +## 4. 待产品补充(v1+) + +- 「取消进 M4」专用标记:若不用 `status`/`step`/`intercept_status` 组合表达,则 **新增列** 后的字典条目与数仓同步表。 +- 与奇门 **不同步** 的克隆续单字段(见 `order_todo.md` §2.4)。 + +## 5. 修订 + +| 版本 | 说明 | +|------|------| +| v0 | 自 `order_delivery.js` 摘录枚举骨架,无 DB 变更 | From e73a311076e37a2c7ffea1e8445505725b7dea8f Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sat, 11 Apr 2026 17:09:06 +0800 Subject: [PATCH 025/550] ok --- .codebuddy/.gitignore | 1 + .github/agents/文档.agent.md | 1 + .github/agents/测试.agent.md | 10 +- .github/agents/评审.agent.md | 63 + .github/agents/调度.agent.md | 2 +- app.js | 9 +- app/controller/home.js | 36 +- app/controller/tempFileWriter.js | 61 + app/lib/file_writer.js | 1497 +++++++++++++++++ app/model/order_delivery.js | 6 + app/model/order_delivery_factory.js | 2 + app/model/qimen_log.js | 6 + app/model/stock_warehouse.js | 4 +- app/model/store_warehouse.js | 16 + app/router.js | 3 + app/schedule/consume_qimen_logs.js | 61 + app/service/systemMethods/index.js | 2 +- .../systemMethods/order/archiveOrder.js | 7 + app/service/systemMethods/order/base.js | 8 + .../systemMethods/order/deliveryOrder.js | 7 + .../systemMethods/order/expectionOrder.js | 7 + app/service/systemMethods/order/index.js | 7 + .../systemMethods/order/pendingOrder.js | 7 + .../systemMethods/order/reviewOrder.js | 35 + app/service/systemMethods/storage/stockout.js | 4 + app/service/systems/delivery_order.js | 107 +- app/service/systems/license_plate.js | 18 +- app/service/systems/stock_store.js | 154 +- app/service/systems/storage/receiving.js | 70 +- app/service/systems/store_warehouse.js | 42 + app/service/systems/upload.js | 4 +- config/config.default.js | 22 +- ...r-wms-stock-warehouse-negative-quantity.js | 81 + .../20260410120000-add-log-id-to-qimen-log.js | 32 + ...d-audit-status-to-order-delivery-tables.js | 88 + ...atus-with-step-on-order-delivery-tables.js | 122 ++ docs/file-writer.md | 119 ++ methods/changes/system.json | 738 ++++---- methods/system.json | 10 +- package.json | 3 +- .../file-writer/.write-window-counter-3.json | 1 + .../file-writer/qimen-logs/.consume-progress | 7 + .../qimen-logs-MINGREN-worker-p4496-0001.log | 2 + ...en-logs-MINGREN-worker-p4496-0001.log.done | 7 + ...gateway.user.bindAccountByTempCode.test.js | 7 +- .../system.order.namespaced.test.js | 55 + ....setting.account.getBindWechatCode.test.js | 7 +- .../system.setting.storeWarehouse.test.js | 69 +- .../system.storage.delivery.module.test.js | 26 +- .../system.storage.receiving.test.js | 226 ++- .../controller/system.storeWarehouse.test.js | 6 + test/app/controller/tempFileWriter.test.js | 85 + test/app/lib/file_writer.test.js | 508 ++++++ .../systemMethods/order.base.step.test.js | 43 + .../delivery_order.auditStatus.test.js | 99 ++ .../systems/delivery_order.oversell.test.js | 216 +++ .../app/service/systems/license_plate.test.js | 2 +- test/app/service/systems/notice.test.js | 58 +- .../systems/storage.receiving.report.test.js | 42 +- ...tore_warehouse.adjustPrintQuantity.test.js | 30 +- test_reports/20260410-130419-全量测试汇总.md | 152 ++ test_reports/20260410-164555-测试总览.md | 92 + test_reports/fail/002-main.md | 55 + test_reports/fail/007-main.md | 55 + test_reports/fail/008-main.md | 57 + test_reports/fail/012-main.md | 70 + test_reports/fail/016-main.md | 93 + test_reports/fail/037-main.md | 77 + test_reports/fail/041-main.md | 70 + test_reports/fail/044-mirror.md | 149 ++ test_reports/fail/045-mirror.md | 55 + test_reports/fail/046-mirror.md | 149 ++ test_reports/fail/048-mirror.md | 63 + test_reports/fail/049-mirror.md | 62 + test_reports/fail/050-mirror.md | 55 + test_reports/fail/051-mirror.md | 57 + test_reports/fail/052-mirror.md | 58 + test_reports/fail/055-mirror.md | 70 + test_reports/fail/058-mirror.md | 101 ++ test_reports/fail/059-mirror.md | 93 + test_reports/fail/060-mirror.md | 77 + test_reports/fail/061-mirror.md | 77 + test_reports/fail/062-mirror.md | 62 + test_reports/fail/063-mirror.md | 77 + test_reports/fail/076-mirror.md | 56 + test_reports/fail/077-mirror.md | 77 + ...eway.user.bindAccountByTempCode.test.js.md | 64 + ...system.order.getreviewOrderlist.test.js.md | 61 + ...troller_system.order.namespaced.test.js.md | 77 + ...roller_system.order.reviewOrder.test.js.md | 61 + ...tting.account.getBindWechatCode.test.js.md | 64 + ...ntroller_system.setting.account.test.js.md | 61 + ...oller_system.setting.permission.test.js.md | 61 + ...er_system.setting.printTemplate.test.js.md | 61 + ..._controller_system.setting.role.test.js.md | 61 + ...r_system.setting.storeWarehouse.test.js.md | 61 + ....stock.warehouse.getStockDetail.test.js.md | 61 + ...stem.stock.warehouse.namespaced.test.js.md | 61 + ..._system.storage.delivery.module.test.js.md | 85 + ...controller_system.storage.entry.test.js.md | 85 + ....storage.inventory.matchPutaway.test.js.md | 61 + ....storage.inventory.quickPutaway.test.js.md | 61 + ...roller_system.storage.receiving.test.js.md | 173 ++ ...ller_system.storage.transaction.test.js.md | 61 + ...ontroller_system.storeWarehouse.test.js.md | 61 + ...ntroller_system.user.changeRole.test.js.md | 61 + ..._system.user.getLoginWechatCode.test.js.md | 61 + ...app_controller_system.user.info.test.js.md | 61 + ...controller_system.user.info.web.test.js.md | 61 + ...pp_controller_system.user.login.test.js.md | 63 + ...troller_system.user.loginByCode.test.js.md | 79 + ...tems_delivery_order.auditStatus.test.js.md | 88 + ...skip-app_service_systems_notice.test.js.md | 86 + ...ystems_storage.receiving.report.test.js.md | 79 + ...eway.user.bindAccountByTempCode.test.js.md | 64 + ...mirror-skip-app_controller_home.test.js.md | 71 + ...system.order.getreviewOrderlist.test.js.md | 61 + ...troller_system.order.namespaced.test.js.md | 69 + ...roller_system.order.reviewOrder.test.js.md | 61 + ...tting.account.getBindWechatCode.test.js.md | 64 + ...ntroller_system.setting.account.test.js.md | 61 + ...oller_system.setting.permission.test.js.md | 61 + ...er_system.setting.printTemplate.test.js.md | 61 + ..._controller_system.setting.role.test.js.md | 61 + ...r_system.setting.storeWarehouse.test.js.md | 61 + ....stock.warehouse.getStockDetail.test.js.md | 61 + ...stem.stock.warehouse.namespaced.test.js.md | 61 + ..._system.storage.delivery.module.test.js.md | 85 + ...controller_system.storage.entry.test.js.md | 85 + ....storage.inventory.matchPutaway.test.js.md | 85 + ....storage.inventory.quickPutaway.test.js.md | 85 + ...roller_system.storage.receiving.test.js.md | 141 ++ ...ller_system.storage.transaction.test.js.md | 85 + ...ontroller_system.storeWarehouse.test.js.md | 61 + ...ntroller_system.user.changeRole.test.js.md | 61 + ..._system.user.getLoginWechatCode.test.js.md | 61 + ...app_controller_system.user.info.test.js.md | 61 + ...controller_system.user.info.web.test.js.md | 61 + ...pp_controller_system.user.login.test.js.md | 63 + ...troller_system.user.loginByCode.test.js.md | 79 + ...p_service_systems_license_plate.test.js.md | 64 + ...skip-app_service_systems_notice.test.js.md | 86 + ...0260411-161359-收货入库相关测试失败简报.md | 33 + test_reports/pass/001-main.md | 36 + test_reports/pass/003-main.md | 36 + test_reports/pass/004-main.md | 34 + test_reports/pass/005-main.md | 35 + test_reports/pass/006-main.md | 34 + test_reports/pass/009-main.md | 40 + test_reports/pass/010-main.md | 39 + test_reports/pass/011-main.md | 35 + test_reports/pass/013-main.md | 41 + test_reports/pass/014-main.md | 34 + test_reports/pass/015-main.md | 38 + test_reports/pass/017-main.md | 199 +++ test_reports/pass/018-main.md | 151 ++ test_reports/pass/019-main.md | 48 + test_reports/pass/020-main.md | 81 + test_reports/pass/021-main.md | 47 + test_reports/pass/022-main.md | 34 + test_reports/pass/023-main.md | 34 + test_reports/pass/024-main.md | 34 + test_reports/pass/025-main.md | 34 + test_reports/pass/026-main.md | 36 + test_reports/pass/027-main.md | 38 + test_reports/pass/028-main.md | 34 + test_reports/pass/029-main.md | 45 + test_reports/pass/030-main.md | 37 + test_reports/pass/031-main.md | 36 + test_reports/pass/032-main.md | 36 + test_reports/pass/033-main.md | 37 + test_reports/pass/034-main.md | 35 + test_reports/pass/035-main.md | 39 + test_reports/pass/036-main.md | 35 + test_reports/pass/038-main.md | 40 + test_reports/pass/039-main.md | 34 + test_reports/pass/040-main.md | 37 + test_reports/pass/042-main.md | 35 + test_reports/pass/043-main.md | 35 + test_reports/pass/047-mirror.md | 34 + test_reports/pass/053-mirror.md | 39 + test_reports/pass/054-mirror.md | 35 + test_reports/pass/056-mirror.md | 41 + test_reports/pass/057-mirror.md | 34 + test_reports/pass/064-mirror.md | 47 + test_reports/pass/065-mirror.md | 34 + test_reports/pass/066-mirror.md | 34 + test_reports/pass/067-mirror.md | 34 + test_reports/pass/068-mirror.md | 34 + test_reports/pass/069-mirror.md | 36 + test_reports/pass/070-mirror.md | 38 + test_reports/pass/071-mirror.md | 37 + test_reports/pass/072-mirror.md | 36 + test_reports/pass/073-mirror.md | 36 + test_reports/pass/074-mirror.md | 37 + test_reports/pass/075-mirror.md | 39 + test_reports/pass/078-mirror.md | 40 + test_reports/pass/079-mirror.md | 34 + test_reports/pass/080-mirror.md | 37 + test_reports/pass/081-mirror.md | 42 + test_reports/pass/082-mirror.md | 35 + test_reports/pass/083-mirror.md | 35 + ...9-main-pass-app_controller_docs.test.js.md | 40 + ...9-main-pass-app_controller_home.test.js.md | 40 + ...s-app_controller_tempFileWriter.test.js.md | 38 + ...9-main-pass-app_lib_file_writer.test.js.md | 49 + ...temMethods_storeWarehouse_store.test.js.md | 41 + ...ce_systemMethods_warehouse.auth.test.js.md | 40 + ...auth.user.bindWechatCacheExpiry.test.js.md | 40 + ...stems_auth.user.loginWechatCode.test.js.md | 41 + ...systems_delivery_order.oversell.test.js.md | 39 + ...-pass-app_service_systems_excel.test.js.md | 43 + ...p_service_systems_license_plate.test.js.md | 39 + ...store.stockWarehouse.conditions.test.js.md | 44 + ...ystems_stock_transaction.create.test.js.md | 38 + ...ce_systems_storage.entry.cancel.test.js.md | 41 + ...e_warehouse.adjustPrintQuantity.test.js.md | 39 + ...pass-app_service_systems_upload.test.js.md | 39 + ...mirror-pass-app_controller_docs.test.js.md | 40 + ...temMethods_storeWarehouse_store.test.js.md | 41 + ...ce_systemMethods_warehouse.auth.test.js.md | 40 + ...auth.user.bindWechatCacheExpiry.test.js.md | 40 + ...stems_auth.user.loginWechatCode.test.js.md | 41 + ...-pass-app_service_systems_excel.test.js.md | 43 + ...store.stockWarehouse.conditions.test.js.md | 44 + ...ystems_stock_transaction.create.test.js.md | 38 + ...ce_systems_storage.entry.cancel.test.js.md | 41 + ...ystems_storage.receiving.report.test.js.md | 46 + ...e_warehouse.adjustPrintQuantity.test.js.md | 39 + ...pass-app_service_systems_upload.test.js.md | 39 + .../pass/20260410-订单step流程验证测试报告.md | 28 + .../20260410-订单审批功能-服务层测试报告.md | 27 + .../pass/20260410-货主超卖链路测试报告.md | 45 + ...0260411-161359-收货入库相关测试通过简报.md | 29 + test_reports/tmp/001-main.stderr.log | 0 test_reports/tmp/001-main.stdout.log | 21 + test_reports/tmp/002-main.stderr.log | 32 + test_reports/tmp/002-main.stdout.log | 7 + test_reports/tmp/003-main.stderr.log | 0 test_reports/tmp/003-main.stdout.log | 21 + test_reports/tmp/004-main.stderr.log | 0 test_reports/tmp/004-main.stdout.log | 19 + test_reports/tmp/005-main.stderr.log | 0 test_reports/tmp/005-main.stdout.log | 20 + test_reports/tmp/006-main.stderr.log | 0 test_reports/tmp/006-main.stdout.log | 19 + test_reports/tmp/007-main.stderr.log | 32 + test_reports/tmp/007-main.stdout.log | 7 + test_reports/tmp/008-main.stderr.log | 7 + test_reports/tmp/008-main.stdout.log | 34 + test_reports/tmp/009-main.stderr.log | 0 test_reports/tmp/009-main.stdout.log | 25 + test_reports/tmp/010-main.stderr.log | 0 test_reports/tmp/010-main.stdout.log | 24 + test_reports/tmp/011-main.stderr.log | 0 test_reports/tmp/011-main.stdout.log | 20 + test_reports/tmp/012-main.stderr.log | 7 + test_reports/tmp/012-main.stdout.log | 47 + test_reports/tmp/013-main.stderr.log | 0 test_reports/tmp/013-main.stdout.log | 26 + test_reports/tmp/014-main.stderr.log | 0 test_reports/tmp/014-main.stdout.log | 19 + test_reports/tmp/015-main.stderr.log | 0 test_reports/tmp/015-main.stdout.log | 23 + test_reports/tmp/016-main.stderr.log | 7 + test_reports/tmp/016-main.stdout.log | 70 + test_reports/tmp/017-main.stderr.log | 0 test_reports/tmp/017-main.stdout.log | 184 ++ test_reports/tmp/018-main.stderr.log | 0 test_reports/tmp/018-main.stdout.log | 137 ++ test_reports/tmp/019-main.stderr.log | 0 test_reports/tmp/019-main.stdout.log | 33 + test_reports/tmp/020-main.stderr.log | 0 test_reports/tmp/020-main.stdout.log | 66 + test_reports/tmp/021-main.stderr.log | 0 test_reports/tmp/021-main.stdout.log | 32 + test_reports/tmp/022-main.stderr.log | 0 test_reports/tmp/022-main.stdout.log | 19 + test_reports/tmp/023-main.stderr.log | 0 test_reports/tmp/023-main.stdout.log | 19 + test_reports/tmp/024-main.stderr.log | 0 test_reports/tmp/024-main.stdout.log | 19 + test_reports/tmp/025-main.stderr.log | 0 test_reports/tmp/025-main.stdout.log | 19 + test_reports/tmp/026-main.stderr.log | 0 test_reports/tmp/026-main.stdout.log | 21 + test_reports/tmp/027-main.stderr.log | 0 test_reports/tmp/027-main.stdout.log | 23 + test_reports/tmp/028-main.stderr.log | 0 test_reports/tmp/028-main.stdout.log | 19 + test_reports/tmp/029-main.stderr.log | 0 test_reports/tmp/029-main.stdout.log | 30 + test_reports/tmp/030-main.stderr.log | 0 test_reports/tmp/030-main.stdout.log | 22 + test_reports/tmp/031-main.stderr.log | 0 test_reports/tmp/031-main.stdout.log | 21 + test_reports/tmp/032-main.stderr.log | 0 test_reports/tmp/032-main.stdout.log | 21 + test_reports/tmp/033-main.stderr.log | 0 test_reports/tmp/033-main.stdout.log | 22 + test_reports/tmp/034-main.stderr.log | 0 test_reports/tmp/034-main.stdout.log | 20 + test_reports/tmp/035-main.stderr.log | 0 test_reports/tmp/035-main.stdout.log | 24 + test_reports/tmp/036-main.stderr.log | 0 test_reports/tmp/036-main.stdout.log | 20 + test_reports/tmp/037-main.stderr.log | 7 + test_reports/tmp/037-main.stdout.log | 54 + test_reports/tmp/038-main.stderr.log | 0 test_reports/tmp/038-main.stdout.log | 25 + test_reports/tmp/039-main.stderr.log | 0 test_reports/tmp/039-main.stdout.log | 19 + test_reports/tmp/040-main.stderr.log | 0 test_reports/tmp/040-main.stdout.log | 22 + test_reports/tmp/041-main.stderr.log | 7 + test_reports/tmp/041-main.stdout.log | 47 + test_reports/tmp/042-main.stderr.log | 0 test_reports/tmp/042-main.stdout.log | 20 + test_reports/tmp/043-main.stderr.log | 0 test_reports/tmp/043-main.stdout.log | 20 + test_reports/tmp/044-mirror.stderr.log | 50 + test_reports/tmp/044-mirror.stdout.log | 83 + test_reports/tmp/045-mirror.stderr.log | 32 + test_reports/tmp/045-mirror.stdout.log | 7 + test_reports/tmp/046-mirror.stderr.log | 50 + test_reports/tmp/046-mirror.stdout.log | 83 + test_reports/tmp/047-mirror.stderr.log | 0 test_reports/tmp/047-mirror.stdout.log | 19 + test_reports/tmp/048-mirror.stderr.log | 7 + test_reports/tmp/048-mirror.stdout.log | 40 + test_reports/tmp/049-mirror.stderr.log | 7 + test_reports/tmp/049-mirror.stdout.log | 39 + test_reports/tmp/050-mirror.stderr.log | 32 + test_reports/tmp/050-mirror.stdout.log | 7 + test_reports/tmp/051-mirror.stderr.log | 7 + test_reports/tmp/051-mirror.stdout.log | 34 + test_reports/tmp/052-mirror.stderr.log | 7 + test_reports/tmp/052-mirror.stdout.log | 35 + test_reports/tmp/053-mirror.stderr.log | 0 test_reports/tmp/053-mirror.stdout.log | 24 + test_reports/tmp/054-mirror.stderr.log | 0 test_reports/tmp/054-mirror.stdout.log | 20 + test_reports/tmp/055-mirror.stderr.log | 7 + test_reports/tmp/055-mirror.stdout.log | 47 + test_reports/tmp/056-mirror.stderr.log | 0 test_reports/tmp/056-mirror.stdout.log | 26 + test_reports/tmp/057-mirror.stderr.log | 0 test_reports/tmp/057-mirror.stdout.log | 19 + test_reports/tmp/058-mirror.stderr.log | 7 + test_reports/tmp/058-mirror.stdout.log | 78 + test_reports/tmp/059-mirror.stderr.log | 7 + test_reports/tmp/059-mirror.stdout.log | 70 + test_reports/tmp/060-mirror.stderr.log | 53 + test_reports/tmp/060-mirror.stdout.log | 7 + test_reports/tmp/061-mirror.stderr.log | 53 + test_reports/tmp/061-mirror.stdout.log | 7 + test_reports/tmp/062-mirror.stderr.log | 7 + test_reports/tmp/062-mirror.stdout.log | 39 + test_reports/tmp/063-mirror.stderr.log | 53 + test_reports/tmp/063-mirror.stdout.log | 7 + test_reports/tmp/064-mirror.stderr.log | 0 test_reports/tmp/064-mirror.stdout.log | 32 + test_reports/tmp/065-mirror.stderr.log | 0 test_reports/tmp/065-mirror.stdout.log | 19 + test_reports/tmp/066-mirror.stderr.log | 0 test_reports/tmp/066-mirror.stdout.log | 19 + test_reports/tmp/067-mirror.stderr.log | 0 test_reports/tmp/067-mirror.stdout.log | 19 + test_reports/tmp/068-mirror.stderr.log | 0 test_reports/tmp/068-mirror.stdout.log | 19 + test_reports/tmp/069-mirror.stderr.log | 0 test_reports/tmp/069-mirror.stdout.log | 21 + test_reports/tmp/070-mirror.stderr.log | 0 test_reports/tmp/070-mirror.stdout.log | 23 + test_reports/tmp/071-mirror.stderr.log | 0 test_reports/tmp/071-mirror.stdout.log | 22 + test_reports/tmp/072-mirror.stderr.log | 0 test_reports/tmp/072-mirror.stdout.log | 21 + test_reports/tmp/073-mirror.stderr.log | 0 test_reports/tmp/073-mirror.stdout.log | 21 + test_reports/tmp/074-mirror.stderr.log | 0 test_reports/tmp/074-mirror.stdout.log | 22 + test_reports/tmp/075-mirror.stderr.log | 0 test_reports/tmp/075-mirror.stdout.log | 24 + test_reports/tmp/076-mirror.stderr.log | 32 + test_reports/tmp/076-mirror.stdout.log | 7 + test_reports/tmp/077-mirror.stderr.log | 7 + test_reports/tmp/077-mirror.stdout.log | 54 + test_reports/tmp/078-mirror.stderr.log | 0 test_reports/tmp/078-mirror.stdout.log | 25 + test_reports/tmp/079-mirror.stderr.log | 0 test_reports/tmp/079-mirror.stdout.log | 19 + test_reports/tmp/080-mirror.stderr.log | 0 test_reports/tmp/080-mirror.stdout.log | 22 + test_reports/tmp/081-mirror.stderr.log | 0 test_reports/tmp/081-mirror.stdout.log | 27 + test_reports/tmp/082-mirror.stderr.log | 0 test_reports/tmp/082-mirror.stdout.log | 20 + test_reports/tmp/083-mirror.stderr.log | 0 test_reports/tmp/083-mirror.stdout.log | 20 + worktrees/deploy-20260409155126 | 1 + 401 files changed, 17282 insertions(+), 556 deletions(-) create mode 100644 .codebuddy/.gitignore create mode 100644 .github/agents/评审.agent.md create mode 100644 app/controller/tempFileWriter.js create mode 100644 app/lib/file_writer.js create mode 100644 app/schedule/consume_qimen_logs.js create mode 100644 database/migrations/20260410100000-alter-wms-stock-warehouse-negative-quantity.js create mode 100644 database/migrations/20260410120000-add-log-id-to-qimen-log.js create mode 100644 database/migrations/20260410130000-add-audit-status-to-order-delivery-tables.js create mode 100644 database/migrations/20260410150000-replace-audit-status-with-step-on-order-delivery-tables.js create mode 100644 docs/file-writer.md create mode 100644 runtime/file-writer/.write-window-counter-3.json create mode 100644 runtime/file-writer/qimen-logs/.consume-progress create mode 100644 runtime/file-writer/qimen-logs/2026/04/10/qimen-logs-MINGREN-worker-p4496-0001.log create mode 100644 runtime/file-writer/qimen-logs/2026/04/10/qimen-logs-MINGREN-worker-p4496-0001.log.done create mode 100644 test/app/controller/tempFileWriter.test.js create mode 100644 test/app/lib/file_writer.test.js create mode 100644 test/app/service/systemMethods/order.base.step.test.js create mode 100644 test/app/service/systems/delivery_order.auditStatus.test.js create mode 100644 test/app/service/systems/delivery_order.oversell.test.js create mode 100644 test_reports/20260410-130419-全量测试汇总.md create mode 100644 test_reports/20260410-164555-测试总览.md create mode 100644 test_reports/fail/002-main.md create mode 100644 test_reports/fail/007-main.md create mode 100644 test_reports/fail/008-main.md create mode 100644 test_reports/fail/012-main.md create mode 100644 test_reports/fail/016-main.md create mode 100644 test_reports/fail/037-main.md create mode 100644 test_reports/fail/041-main.md create mode 100644 test_reports/fail/044-mirror.md create mode 100644 test_reports/fail/045-mirror.md create mode 100644 test_reports/fail/046-mirror.md create mode 100644 test_reports/fail/048-mirror.md create mode 100644 test_reports/fail/049-mirror.md create mode 100644 test_reports/fail/050-mirror.md create mode 100644 test_reports/fail/051-mirror.md create mode 100644 test_reports/fail/052-mirror.md create mode 100644 test_reports/fail/055-mirror.md create mode 100644 test_reports/fail/058-mirror.md create mode 100644 test_reports/fail/059-mirror.md create mode 100644 test_reports/fail/060-mirror.md create mode 100644 test_reports/fail/061-mirror.md create mode 100644 test_reports/fail/062-mirror.md create mode 100644 test_reports/fail/063-mirror.md create mode 100644 test_reports/fail/076-mirror.md create mode 100644 test_reports/fail/077-mirror.md create mode 100644 test_reports/fail/20260410-130419-main-skip-app_controller_gateway.user.bindAccountByTempCode.test.js.md create mode 100644 test_reports/fail/20260410-130419-main-skip-app_controller_system.order.getreviewOrderlist.test.js.md create mode 100644 test_reports/fail/20260410-130419-main-skip-app_controller_system.order.namespaced.test.js.md create mode 100644 test_reports/fail/20260410-130419-main-skip-app_controller_system.order.reviewOrder.test.js.md create mode 100644 test_reports/fail/20260410-130419-main-skip-app_controller_system.setting.account.getBindWechatCode.test.js.md create mode 100644 test_reports/fail/20260410-130419-main-skip-app_controller_system.setting.account.test.js.md create mode 100644 test_reports/fail/20260410-130419-main-skip-app_controller_system.setting.permission.test.js.md create mode 100644 test_reports/fail/20260410-130419-main-skip-app_controller_system.setting.printTemplate.test.js.md create mode 100644 test_reports/fail/20260410-130419-main-skip-app_controller_system.setting.role.test.js.md create mode 100644 test_reports/fail/20260410-130419-main-skip-app_controller_system.setting.storeWarehouse.test.js.md create mode 100644 test_reports/fail/20260410-130419-main-skip-app_controller_system.stock.warehouse.getStockDetail.test.js.md create mode 100644 test_reports/fail/20260410-130419-main-skip-app_controller_system.stock.warehouse.namespaced.test.js.md create mode 100644 test_reports/fail/20260410-130419-main-skip-app_controller_system.storage.delivery.module.test.js.md create mode 100644 test_reports/fail/20260410-130419-main-skip-app_controller_system.storage.entry.test.js.md create mode 100644 test_reports/fail/20260410-130419-main-skip-app_controller_system.storage.inventory.matchPutaway.test.js.md create mode 100644 test_reports/fail/20260410-130419-main-skip-app_controller_system.storage.inventory.quickPutaway.test.js.md create mode 100644 test_reports/fail/20260410-130419-main-skip-app_controller_system.storage.receiving.test.js.md create mode 100644 test_reports/fail/20260410-130419-main-skip-app_controller_system.storage.transaction.test.js.md create mode 100644 test_reports/fail/20260410-130419-main-skip-app_controller_system.storeWarehouse.test.js.md create mode 100644 test_reports/fail/20260410-130419-main-skip-app_controller_system.user.changeRole.test.js.md create mode 100644 test_reports/fail/20260410-130419-main-skip-app_controller_system.user.getLoginWechatCode.test.js.md create mode 100644 test_reports/fail/20260410-130419-main-skip-app_controller_system.user.info.test.js.md create mode 100644 test_reports/fail/20260410-130419-main-skip-app_controller_system.user.info.web.test.js.md create mode 100644 test_reports/fail/20260410-130419-main-skip-app_controller_system.user.login.test.js.md create mode 100644 test_reports/fail/20260410-130419-main-skip-app_controller_system.user.loginByCode.test.js.md create mode 100644 test_reports/fail/20260410-130419-main-skip-app_service_systems_delivery_order.auditStatus.test.js.md create mode 100644 test_reports/fail/20260410-130419-main-skip-app_service_systems_notice.test.js.md create mode 100644 test_reports/fail/20260410-130419-main-skip-app_service_systems_storage.receiving.report.test.js.md create mode 100644 test_reports/fail/20260410-130419-mirror-skip-app_controller_gateway.user.bindAccountByTempCode.test.js.md create mode 100644 test_reports/fail/20260410-130419-mirror-skip-app_controller_home.test.js.md create mode 100644 test_reports/fail/20260410-130419-mirror-skip-app_controller_system.order.getreviewOrderlist.test.js.md create mode 100644 test_reports/fail/20260410-130419-mirror-skip-app_controller_system.order.namespaced.test.js.md create mode 100644 test_reports/fail/20260410-130419-mirror-skip-app_controller_system.order.reviewOrder.test.js.md create mode 100644 test_reports/fail/20260410-130419-mirror-skip-app_controller_system.setting.account.getBindWechatCode.test.js.md create mode 100644 test_reports/fail/20260410-130419-mirror-skip-app_controller_system.setting.account.test.js.md create mode 100644 test_reports/fail/20260410-130419-mirror-skip-app_controller_system.setting.permission.test.js.md create mode 100644 test_reports/fail/20260410-130419-mirror-skip-app_controller_system.setting.printTemplate.test.js.md create mode 100644 test_reports/fail/20260410-130419-mirror-skip-app_controller_system.setting.role.test.js.md create mode 100644 test_reports/fail/20260410-130419-mirror-skip-app_controller_system.setting.storeWarehouse.test.js.md create mode 100644 test_reports/fail/20260410-130419-mirror-skip-app_controller_system.stock.warehouse.getStockDetail.test.js.md create mode 100644 test_reports/fail/20260410-130419-mirror-skip-app_controller_system.stock.warehouse.namespaced.test.js.md create mode 100644 test_reports/fail/20260410-130419-mirror-skip-app_controller_system.storage.delivery.module.test.js.md create mode 100644 test_reports/fail/20260410-130419-mirror-skip-app_controller_system.storage.entry.test.js.md create mode 100644 test_reports/fail/20260410-130419-mirror-skip-app_controller_system.storage.inventory.matchPutaway.test.js.md create mode 100644 test_reports/fail/20260410-130419-mirror-skip-app_controller_system.storage.inventory.quickPutaway.test.js.md create mode 100644 test_reports/fail/20260410-130419-mirror-skip-app_controller_system.storage.receiving.test.js.md create mode 100644 test_reports/fail/20260410-130419-mirror-skip-app_controller_system.storage.transaction.test.js.md create mode 100644 test_reports/fail/20260410-130419-mirror-skip-app_controller_system.storeWarehouse.test.js.md create mode 100644 test_reports/fail/20260410-130419-mirror-skip-app_controller_system.user.changeRole.test.js.md create mode 100644 test_reports/fail/20260410-130419-mirror-skip-app_controller_system.user.getLoginWechatCode.test.js.md create mode 100644 test_reports/fail/20260410-130419-mirror-skip-app_controller_system.user.info.test.js.md create mode 100644 test_reports/fail/20260410-130419-mirror-skip-app_controller_system.user.info.web.test.js.md create mode 100644 test_reports/fail/20260410-130419-mirror-skip-app_controller_system.user.login.test.js.md create mode 100644 test_reports/fail/20260410-130419-mirror-skip-app_controller_system.user.loginByCode.test.js.md create mode 100644 test_reports/fail/20260410-130419-mirror-skip-app_service_systems_license_plate.test.js.md create mode 100644 test_reports/fail/20260410-130419-mirror-skip-app_service_systems_notice.test.js.md create mode 100644 test_reports/fail/20260411-161359-收货入库相关测试失败简报.md create mode 100644 test_reports/pass/001-main.md create mode 100644 test_reports/pass/003-main.md create mode 100644 test_reports/pass/004-main.md create mode 100644 test_reports/pass/005-main.md create mode 100644 test_reports/pass/006-main.md create mode 100644 test_reports/pass/009-main.md create mode 100644 test_reports/pass/010-main.md create mode 100644 test_reports/pass/011-main.md create mode 100644 test_reports/pass/013-main.md create mode 100644 test_reports/pass/014-main.md create mode 100644 test_reports/pass/015-main.md create mode 100644 test_reports/pass/017-main.md create mode 100644 test_reports/pass/018-main.md create mode 100644 test_reports/pass/019-main.md create mode 100644 test_reports/pass/020-main.md create mode 100644 test_reports/pass/021-main.md create mode 100644 test_reports/pass/022-main.md create mode 100644 test_reports/pass/023-main.md create mode 100644 test_reports/pass/024-main.md create mode 100644 test_reports/pass/025-main.md create mode 100644 test_reports/pass/026-main.md create mode 100644 test_reports/pass/027-main.md create mode 100644 test_reports/pass/028-main.md create mode 100644 test_reports/pass/029-main.md create mode 100644 test_reports/pass/030-main.md create mode 100644 test_reports/pass/031-main.md create mode 100644 test_reports/pass/032-main.md create mode 100644 test_reports/pass/033-main.md create mode 100644 test_reports/pass/034-main.md create mode 100644 test_reports/pass/035-main.md create mode 100644 test_reports/pass/036-main.md create mode 100644 test_reports/pass/038-main.md create mode 100644 test_reports/pass/039-main.md create mode 100644 test_reports/pass/040-main.md create mode 100644 test_reports/pass/042-main.md create mode 100644 test_reports/pass/043-main.md create mode 100644 test_reports/pass/047-mirror.md create mode 100644 test_reports/pass/053-mirror.md create mode 100644 test_reports/pass/054-mirror.md create mode 100644 test_reports/pass/056-mirror.md create mode 100644 test_reports/pass/057-mirror.md create mode 100644 test_reports/pass/064-mirror.md create mode 100644 test_reports/pass/065-mirror.md create mode 100644 test_reports/pass/066-mirror.md create mode 100644 test_reports/pass/067-mirror.md create mode 100644 test_reports/pass/068-mirror.md create mode 100644 test_reports/pass/069-mirror.md create mode 100644 test_reports/pass/070-mirror.md create mode 100644 test_reports/pass/071-mirror.md create mode 100644 test_reports/pass/072-mirror.md create mode 100644 test_reports/pass/073-mirror.md create mode 100644 test_reports/pass/074-mirror.md create mode 100644 test_reports/pass/075-mirror.md create mode 100644 test_reports/pass/078-mirror.md create mode 100644 test_reports/pass/079-mirror.md create mode 100644 test_reports/pass/080-mirror.md create mode 100644 test_reports/pass/081-mirror.md create mode 100644 test_reports/pass/082-mirror.md create mode 100644 test_reports/pass/083-mirror.md create mode 100644 test_reports/pass/20260410-130419-main-pass-app_controller_docs.test.js.md create mode 100644 test_reports/pass/20260410-130419-main-pass-app_controller_home.test.js.md create mode 100644 test_reports/pass/20260410-130419-main-pass-app_controller_tempFileWriter.test.js.md create mode 100644 test_reports/pass/20260410-130419-main-pass-app_lib_file_writer.test.js.md create mode 100644 test_reports/pass/20260410-130419-main-pass-app_service_systemMethods_storeWarehouse_store.test.js.md create mode 100644 test_reports/pass/20260410-130419-main-pass-app_service_systemMethods_warehouse.auth.test.js.md create mode 100644 test_reports/pass/20260410-130419-main-pass-app_service_systems_auth.user.bindWechatCacheExpiry.test.js.md create mode 100644 test_reports/pass/20260410-130419-main-pass-app_service_systems_auth.user.loginWechatCode.test.js.md create mode 100644 test_reports/pass/20260410-130419-main-pass-app_service_systems_delivery_order.oversell.test.js.md create mode 100644 test_reports/pass/20260410-130419-main-pass-app_service_systems_excel.test.js.md create mode 100644 test_reports/pass/20260410-130419-main-pass-app_service_systems_license_plate.test.js.md create mode 100644 test_reports/pass/20260410-130419-main-pass-app_service_systems_stock_store.stockWarehouse.conditions.test.js.md create mode 100644 test_reports/pass/20260410-130419-main-pass-app_service_systems_stock_transaction.create.test.js.md create mode 100644 test_reports/pass/20260410-130419-main-pass-app_service_systems_storage.entry.cancel.test.js.md create mode 100644 test_reports/pass/20260410-130419-main-pass-app_service_systems_store_warehouse.adjustPrintQuantity.test.js.md create mode 100644 test_reports/pass/20260410-130419-main-pass-app_service_systems_upload.test.js.md create mode 100644 test_reports/pass/20260410-130419-mirror-pass-app_controller_docs.test.js.md create mode 100644 test_reports/pass/20260410-130419-mirror-pass-app_service_systemMethods_storeWarehouse_store.test.js.md create mode 100644 test_reports/pass/20260410-130419-mirror-pass-app_service_systemMethods_warehouse.auth.test.js.md create mode 100644 test_reports/pass/20260410-130419-mirror-pass-app_service_systems_auth.user.bindWechatCacheExpiry.test.js.md create mode 100644 test_reports/pass/20260410-130419-mirror-pass-app_service_systems_auth.user.loginWechatCode.test.js.md create mode 100644 test_reports/pass/20260410-130419-mirror-pass-app_service_systems_excel.test.js.md create mode 100644 test_reports/pass/20260410-130419-mirror-pass-app_service_systems_stock_store.stockWarehouse.conditions.test.js.md create mode 100644 test_reports/pass/20260410-130419-mirror-pass-app_service_systems_stock_transaction.create.test.js.md create mode 100644 test_reports/pass/20260410-130419-mirror-pass-app_service_systems_storage.entry.cancel.test.js.md create mode 100644 test_reports/pass/20260410-130419-mirror-pass-app_service_systems_storage.receiving.report.test.js.md create mode 100644 test_reports/pass/20260410-130419-mirror-pass-app_service_systems_store_warehouse.adjustPrintQuantity.test.js.md create mode 100644 test_reports/pass/20260410-130419-mirror-pass-app_service_systems_upload.test.js.md create mode 100644 test_reports/pass/20260410-订单step流程验证测试报告.md create mode 100644 test_reports/pass/20260410-订单审批功能-服务层测试报告.md create mode 100644 test_reports/pass/20260410-货主超卖链路测试报告.md create mode 100644 test_reports/pass/20260411-161359-收货入库相关测试通过简报.md create mode 100644 test_reports/tmp/001-main.stderr.log create mode 100644 test_reports/tmp/001-main.stdout.log create mode 100644 test_reports/tmp/002-main.stderr.log create mode 100644 test_reports/tmp/002-main.stdout.log create mode 100644 test_reports/tmp/003-main.stderr.log create mode 100644 test_reports/tmp/003-main.stdout.log create mode 100644 test_reports/tmp/004-main.stderr.log create mode 100644 test_reports/tmp/004-main.stdout.log create mode 100644 test_reports/tmp/005-main.stderr.log create mode 100644 test_reports/tmp/005-main.stdout.log create mode 100644 test_reports/tmp/006-main.stderr.log create mode 100644 test_reports/tmp/006-main.stdout.log create mode 100644 test_reports/tmp/007-main.stderr.log create mode 100644 test_reports/tmp/007-main.stdout.log create mode 100644 test_reports/tmp/008-main.stderr.log create mode 100644 test_reports/tmp/008-main.stdout.log create mode 100644 test_reports/tmp/009-main.stderr.log create mode 100644 test_reports/tmp/009-main.stdout.log create mode 100644 test_reports/tmp/010-main.stderr.log create mode 100644 test_reports/tmp/010-main.stdout.log create mode 100644 test_reports/tmp/011-main.stderr.log create mode 100644 test_reports/tmp/011-main.stdout.log create mode 100644 test_reports/tmp/012-main.stderr.log create mode 100644 test_reports/tmp/012-main.stdout.log create mode 100644 test_reports/tmp/013-main.stderr.log create mode 100644 test_reports/tmp/013-main.stdout.log create mode 100644 test_reports/tmp/014-main.stderr.log create mode 100644 test_reports/tmp/014-main.stdout.log create mode 100644 test_reports/tmp/015-main.stderr.log create mode 100644 test_reports/tmp/015-main.stdout.log create mode 100644 test_reports/tmp/016-main.stderr.log create mode 100644 test_reports/tmp/016-main.stdout.log create mode 100644 test_reports/tmp/017-main.stderr.log create mode 100644 test_reports/tmp/017-main.stdout.log create mode 100644 test_reports/tmp/018-main.stderr.log create mode 100644 test_reports/tmp/018-main.stdout.log create mode 100644 test_reports/tmp/019-main.stderr.log create mode 100644 test_reports/tmp/019-main.stdout.log create mode 100644 test_reports/tmp/020-main.stderr.log create mode 100644 test_reports/tmp/020-main.stdout.log create mode 100644 test_reports/tmp/021-main.stderr.log create mode 100644 test_reports/tmp/021-main.stdout.log create mode 100644 test_reports/tmp/022-main.stderr.log create mode 100644 test_reports/tmp/022-main.stdout.log create mode 100644 test_reports/tmp/023-main.stderr.log create mode 100644 test_reports/tmp/023-main.stdout.log create mode 100644 test_reports/tmp/024-main.stderr.log create mode 100644 test_reports/tmp/024-main.stdout.log create mode 100644 test_reports/tmp/025-main.stderr.log create mode 100644 test_reports/tmp/025-main.stdout.log create mode 100644 test_reports/tmp/026-main.stderr.log create mode 100644 test_reports/tmp/026-main.stdout.log create mode 100644 test_reports/tmp/027-main.stderr.log create mode 100644 test_reports/tmp/027-main.stdout.log create mode 100644 test_reports/tmp/028-main.stderr.log create mode 100644 test_reports/tmp/028-main.stdout.log create mode 100644 test_reports/tmp/029-main.stderr.log create mode 100644 test_reports/tmp/029-main.stdout.log create mode 100644 test_reports/tmp/030-main.stderr.log create mode 100644 test_reports/tmp/030-main.stdout.log create mode 100644 test_reports/tmp/031-main.stderr.log create mode 100644 test_reports/tmp/031-main.stdout.log create mode 100644 test_reports/tmp/032-main.stderr.log create mode 100644 test_reports/tmp/032-main.stdout.log create mode 100644 test_reports/tmp/033-main.stderr.log create mode 100644 test_reports/tmp/033-main.stdout.log create mode 100644 test_reports/tmp/034-main.stderr.log create mode 100644 test_reports/tmp/034-main.stdout.log create mode 100644 test_reports/tmp/035-main.stderr.log create mode 100644 test_reports/tmp/035-main.stdout.log create mode 100644 test_reports/tmp/036-main.stderr.log create mode 100644 test_reports/tmp/036-main.stdout.log create mode 100644 test_reports/tmp/037-main.stderr.log create mode 100644 test_reports/tmp/037-main.stdout.log create mode 100644 test_reports/tmp/038-main.stderr.log create mode 100644 test_reports/tmp/038-main.stdout.log create mode 100644 test_reports/tmp/039-main.stderr.log create mode 100644 test_reports/tmp/039-main.stdout.log create mode 100644 test_reports/tmp/040-main.stderr.log create mode 100644 test_reports/tmp/040-main.stdout.log create mode 100644 test_reports/tmp/041-main.stderr.log create mode 100644 test_reports/tmp/041-main.stdout.log create mode 100644 test_reports/tmp/042-main.stderr.log create mode 100644 test_reports/tmp/042-main.stdout.log create mode 100644 test_reports/tmp/043-main.stderr.log create mode 100644 test_reports/tmp/043-main.stdout.log create mode 100644 test_reports/tmp/044-mirror.stderr.log create mode 100644 test_reports/tmp/044-mirror.stdout.log create mode 100644 test_reports/tmp/045-mirror.stderr.log create mode 100644 test_reports/tmp/045-mirror.stdout.log create mode 100644 test_reports/tmp/046-mirror.stderr.log create mode 100644 test_reports/tmp/046-mirror.stdout.log create mode 100644 test_reports/tmp/047-mirror.stderr.log create mode 100644 test_reports/tmp/047-mirror.stdout.log create mode 100644 test_reports/tmp/048-mirror.stderr.log create mode 100644 test_reports/tmp/048-mirror.stdout.log create mode 100644 test_reports/tmp/049-mirror.stderr.log create mode 100644 test_reports/tmp/049-mirror.stdout.log create mode 100644 test_reports/tmp/050-mirror.stderr.log create mode 100644 test_reports/tmp/050-mirror.stdout.log create mode 100644 test_reports/tmp/051-mirror.stderr.log create mode 100644 test_reports/tmp/051-mirror.stdout.log create mode 100644 test_reports/tmp/052-mirror.stderr.log create mode 100644 test_reports/tmp/052-mirror.stdout.log create mode 100644 test_reports/tmp/053-mirror.stderr.log create mode 100644 test_reports/tmp/053-mirror.stdout.log create mode 100644 test_reports/tmp/054-mirror.stderr.log create mode 100644 test_reports/tmp/054-mirror.stdout.log create mode 100644 test_reports/tmp/055-mirror.stderr.log create mode 100644 test_reports/tmp/055-mirror.stdout.log create mode 100644 test_reports/tmp/056-mirror.stderr.log create mode 100644 test_reports/tmp/056-mirror.stdout.log create mode 100644 test_reports/tmp/057-mirror.stderr.log create mode 100644 test_reports/tmp/057-mirror.stdout.log create mode 100644 test_reports/tmp/058-mirror.stderr.log create mode 100644 test_reports/tmp/058-mirror.stdout.log create mode 100644 test_reports/tmp/059-mirror.stderr.log create mode 100644 test_reports/tmp/059-mirror.stdout.log create mode 100644 test_reports/tmp/060-mirror.stderr.log create mode 100644 test_reports/tmp/060-mirror.stdout.log create mode 100644 test_reports/tmp/061-mirror.stderr.log create mode 100644 test_reports/tmp/061-mirror.stdout.log create mode 100644 test_reports/tmp/062-mirror.stderr.log create mode 100644 test_reports/tmp/062-mirror.stdout.log create mode 100644 test_reports/tmp/063-mirror.stderr.log create mode 100644 test_reports/tmp/063-mirror.stdout.log create mode 100644 test_reports/tmp/064-mirror.stderr.log create mode 100644 test_reports/tmp/064-mirror.stdout.log create mode 100644 test_reports/tmp/065-mirror.stderr.log create mode 100644 test_reports/tmp/065-mirror.stdout.log create mode 100644 test_reports/tmp/066-mirror.stderr.log create mode 100644 test_reports/tmp/066-mirror.stdout.log create mode 100644 test_reports/tmp/067-mirror.stderr.log create mode 100644 test_reports/tmp/067-mirror.stdout.log create mode 100644 test_reports/tmp/068-mirror.stderr.log create mode 100644 test_reports/tmp/068-mirror.stdout.log create mode 100644 test_reports/tmp/069-mirror.stderr.log create mode 100644 test_reports/tmp/069-mirror.stdout.log create mode 100644 test_reports/tmp/070-mirror.stderr.log create mode 100644 test_reports/tmp/070-mirror.stdout.log create mode 100644 test_reports/tmp/071-mirror.stderr.log create mode 100644 test_reports/tmp/071-mirror.stdout.log create mode 100644 test_reports/tmp/072-mirror.stderr.log create mode 100644 test_reports/tmp/072-mirror.stdout.log create mode 100644 test_reports/tmp/073-mirror.stderr.log create mode 100644 test_reports/tmp/073-mirror.stdout.log create mode 100644 test_reports/tmp/074-mirror.stderr.log create mode 100644 test_reports/tmp/074-mirror.stdout.log create mode 100644 test_reports/tmp/075-mirror.stderr.log create mode 100644 test_reports/tmp/075-mirror.stdout.log create mode 100644 test_reports/tmp/076-mirror.stderr.log create mode 100644 test_reports/tmp/076-mirror.stdout.log create mode 100644 test_reports/tmp/077-mirror.stderr.log create mode 100644 test_reports/tmp/077-mirror.stdout.log create mode 100644 test_reports/tmp/078-mirror.stderr.log create mode 100644 test_reports/tmp/078-mirror.stdout.log create mode 100644 test_reports/tmp/079-mirror.stderr.log create mode 100644 test_reports/tmp/079-mirror.stdout.log create mode 100644 test_reports/tmp/080-mirror.stderr.log create mode 100644 test_reports/tmp/080-mirror.stdout.log create mode 100644 test_reports/tmp/081-mirror.stderr.log create mode 100644 test_reports/tmp/081-mirror.stdout.log create mode 100644 test_reports/tmp/082-mirror.stderr.log create mode 100644 test_reports/tmp/082-mirror.stdout.log create mode 100644 test_reports/tmp/083-mirror.stderr.log create mode 100644 test_reports/tmp/083-mirror.stdout.log create mode 160000 worktrees/deploy-20260409155126 diff --git a/.codebuddy/.gitignore b/.codebuddy/.gitignore new file mode 100644 index 0000000..19e0180 --- /dev/null +++ b/.codebuddy/.gitignore @@ -0,0 +1 @@ +db/ diff --git a/.github/agents/文档.agent.md b/.github/agents/文档.agent.md index 9cfebcd..b89f2e3 100644 --- a/.github/agents/文档.agent.md +++ b/.github/agents/文档.agent.md @@ -38,6 +38,7 @@ model: GPT-5 mini (copilot) - 公共请求头变化 - 鉴权方式变化 - 每次 API 接口变更(新增 / 修改 / 删除 method、参数、响应、错误码、header、鉴权等)后,除了更新 `methods/*.json` / `docs/*.md`,**还必须追加一条变更记录到对应的 `methods/changes/.json` 数组** + - 修补json文件时必须强校验 JSON格式的正确性,确保不会引入格式错误导致无法解析的情况 - `methods/*.json` 仍是 SSOT,`methods/changes/*.json` 仅记录差异历史 - 变更记录建议字段至少包含:`version`、`date`、`summary`、`methods`、`notes` 5. 如 system 入参有变化,可执行: diff --git a/.github/agents/测试.agent.md b/.github/agents/测试.agent.md index 4fdcd52..c5f6b59 100644 --- a/.github/agents/测试.agent.md +++ b/.github/agents/测试.agent.md @@ -3,7 +3,7 @@ name: wms-test-agent description: "Use when the user asks about 测试、单元测试、集成测试、回归测试、TDD、接口验证、mock、覆盖率、验证修复、复现 bug。专用于 WMS 测试设计、执行与验证。" argument-hint: "描述要验证或补齐的测试目标,例如:补某接口单元测试、复现 bug 并加回归、按 TDD 验证修复、审查 mock/断言是否合理。" tools: ['read', 'search', 'edit', 'execute', 'todo'] -model: GPT-5.1 (copilot) +model: Gemini 2.5 Pro (copilot) --- # WMS 测试代理(`wms-test-agent`) @@ -39,13 +39,13 @@ model: GPT-5.1 (copilot) ## 测试规则 1. **TDD 优先**:先写失败用例,再做最小修复 -2. **测试真实行为**:优先验证真实输入/输出与实际调用链,不要只测 mock +2. **测试真实行为**:优先验证真实输入/输出与实际调用链,不要只测 mock,测试所有的文件是否符合eslint规范,不规范的代码必须驳回修改后再验证,并告知驳回原因 3. **禁止 test-only 生产代码**:不要为测试给生产代码加仅供测试使用的方法或分支 4. **mock 要克制且完整**:仅在理解依赖副作用后于最低必要层 mock,且结构必须与真实数据一致 5. **改动后必须验证**:跑相关测试并明确报告 passing 数量、失败数与验证范围 6. **接口验证以真实链路为准**:必要时结合 `methods/*.json`、controller/service 实现与返回结构共同校验 7. **所有编码风格必须要通过ESLint检查**,禁止任何 ESLint 错误或警告存在于提交的代码中,如有 ESLint 错误或警告,必须驳回到开发修改后再验证 - +8. **测试仓库与货主范围固定** 必须检查测试中创建的资源(如收货单、绑定货主等)是否使用了固定的测试仓库 ID `100000` 和测试货主 ID `1000000`,禁止使用随机生成的仓库或货主 ID 以及其他非固定值,否则必须驳回修改后再验证,并告知驳回原因。 ## 常用命令示例 ### PowerShell 执行 @@ -78,7 +78,9 @@ npx egg-bin test test/app/controller/**/*.test.js - 所有回复建议以 `[Test]` 开头 - 先给结论,再给测试范围、关键用例、验证结果 - 明确说明 passing 数量、失败数与是否已覆盖回归场景 - +- 直接输出测试报告到 `test_reports/` 目录下的文件中,测试分为可以通过和不可以通过部分,分别为 `test_reports/pass/` 和 `test_reports/fail/`,测试完成后并返回文件路径,报告路径必须包含日期时间和中文描述,例如:`test_reports/pass/20260410-货主超卖链路测试报告.md` +- 如有失败用例,必须明确失败原因、失败用例名称与代码位置 +- 测试报告格式必须清晰、结构化,包含测试目标、测试范围、测试产物、测试结果摘要、结论与建议,测试类型(单元/集成/回归/接口验证)必须明确标注 ## 结论 测试相关能力文档已统一收口到本 Agent;工具箱只保留“测试相关必须使用 `wms-test-agent`”的规则入口。 diff --git a/.github/agents/评审.agent.md b/.github/agents/评审.agent.md new file mode 100644 index 0000000..2c5a91f --- /dev/null +++ b/.github/agents/评审.agent.md @@ -0,0 +1,63 @@ +--- +name: wms-review-agent +description: "Use when the user asks for 代码评审、审查、review、缺陷、风险、回归、兼容性、可维护性、代码质量检查、变更影响分析。专用于 WMS 只读代码评审与风险识别。" +argument-hint: "描述要评审的代码、分支或变更范围,例如:评审某个 PR、审查某个接口改动、检查回归风险、分析兼容性问题。" +tools: ['read', 'search'] +model: Claude Opus 4.6 +--- + +# WMS 评审代理(`wms-review-agent`) + +## 适用范围 + +- 项目根目录:`D:\wms` +- 主要关注目录:`app/`、`config/`、`database/`、`test/`、`methods/` +- 适用于代码评审、变更审查、风险分析、回归影响判断与可维护性检查 + +## 角色定位 + +本代理只做只读评审,不进行任何代码修改、文件写入、格式化、重构或执行类操作。 + +## 评审重点 + +1. **缺陷**:逻辑错误、边界条件遗漏、异常处理不足、空值与并发问题 +2. **风险**:回归风险、兼容性风险、权限与数据安全风险、性能退化风险 +3. **回归点**:接口行为变化、状态流转变化、数据结构变化、默认值变化 +4. **可维护性**:职责是否清晰、耦合是否过高、命名是否准确、重复逻辑是否明显 +5. **一致性**:实现与既有分层约定、既有模式、既有测试和文档是否一致 + +## 评审规则 + +1. **只读评审**:只允许阅读和检索,不做任何修改 +2. **先找事实**:基于代码、调用链、测试和上下文给出结论,不凭空猜测 +3. **优先指出问题**:发现问题时要明确说明影响范围、触发条件和严重程度 +4. **避免泛泛而谈**:每条 findings 都要能对应到具体代码位置或明确行为 +5. **必要时说明未验证项**:如果无法确认某个点,必须标注为开放问题或残余风险 + +## 输出要求 + +- 先列出 findings,再列残余风险或开放问题 +- findings 必须按严重程度排序,优先级高的放前面 +- 每条 finding 需要包含问题、影响、依据,最好附带代码位置 +- 如果没有发现问题,要明确说明“未发现明确缺陷”或同义结论 +- 结尾可给出简短结论,但不要把结论放在 findings 之前 + +## 建议提问方式 + +```text +请使用 wms-review-agent 帮我: +1) 评审这个变更的缺陷和回归风险 +2) 检查兼容性、边界条件和可维护性 +3) 先输出 findings,再输出残余风险或开放问题 +``` + +## 输出风格 + +- 所有回复建议以 `[Review]` 开头 +- 语气保持直接、准确、可执行 +- 不输出代码修改建议为最终动作,不执行修复 +- 如需后续修复,建议交由开发类 agent 处理 + +## 结论 + +本代理专用于只读代码评审与风险识别;工具箱仅保留 `read` 与 `search`,禁止任何修改或执行类能力。 diff --git a/.github/agents/调度.agent.md b/.github/agents/调度.agent.md index 7c35ceb..c669667 100644 --- a/.github/agents/调度.agent.md +++ b/.github/agents/调度.agent.md @@ -23,7 +23,7 @@ model: GPT-5.4 mini (copilot) 2. **Redis / 缓存 / TTL / session / key 排障** → `wms-redis-agent` 3. **发布 / 回退 / 预检 / 冒烟 / 版本查询** → `wms-deploy-agent` 4. **文档补充 / API 文档 / README / `methods/*.json` / `docs/*.md`** → `wms-doc-agent` -5. **测试 / 回归 / 接口验证 / TDD / mock 审查** → `wms-test-agent` +5. **测试 / 回归 / 接口验证 / TDD / mock 审查** → `wms-test-agent` 必须告知测试目标和所有涉及的文件路径 6. **纯代码修改 / method 映射 / 权限联动** → `wms-dev-agent` 7. **代码 + 文档混合变更** → 必须拆分为两个子任务:先委派 `wms-dev-agent` 完成代码修改,再委派 `wms-doc-agent` 完成 `methods/*.json` 更新和 `methods/changes/*.json` 变更记录。**禁止将文档修改合并到 `wms-dev-agent` 的任务中** 8. **专属 agent 处理不了,或多次迭代仍未解决** → 升级委派 `wms-expert-agent` 进行兜底处理(root cause + 端到端闭环) diff --git a/app.js b/app.js index a96fa2b..a40e349 100644 --- a/app.js +++ b/app.js @@ -1,12 +1,19 @@ // app.js const path = require('path'); +const LocalFileWriter = require('./app/lib/file_writer'); -// 直接导出函数,而不是类 +/** + * 挂载应用级扩展能力。 + * @param {import('egg').Application} app Egg 应用实例。 + * @return {void} + */ module.exports = app => { // 设置全局应用根目录 global.APP_ROOT = path.resolve(__dirname, './'); app.appRoot = global.APP_ROOT; + app.fileWriter = new LocalFileWriter(app); app.logger.info('✅ Application 扩展能力已加载'); + app.logger.info('✅ fileWriter 已挂载到 app.fileWriter'); // 初始化工厂 app.beforeStart(async () => { // skip factory init when model layer is absent (e.g. during tests) diff --git a/app/controller/home.js b/app/controller/home.js index b33945b..c3d192c 100644 --- a/app/controller/home.js +++ b/app/controller/home.js @@ -1,3 +1,4 @@ +const crypto = require('crypto'); const { Controller, } = require('egg'); @@ -20,9 +21,12 @@ class HomeController extends Controller { service, } = this; const startTime = Date.now(); + const logId = 'QL-' + Date.now() + '-' + crypto.randomBytes(3).toString('hex'); + ctx.qimenLogId = logId; // 初始化日志数据 const logData = { + log_id: logId, from_key: '', to_key: this.app.config.qimen.appKey, method: '', @@ -42,14 +46,12 @@ class HomeController extends Controller { logData.sign = getParams.sign || ''; logData.costomer_id = getParams.customerId || getParams.customer_id || ''; logData.v = getParams.v || ''; - ctx.qimenLogId = await service.qimen.saveQimenLog(logData, startTime); try { // 验证必要参数 if (!this.validateQimenParams(getParams)) { const errorMsg = '参数缺失或错误'; const response = this.errorResponse(errorMsg, 'xml'); - await service.qimen.saveQimenLogResult(response); ctx.body = response; ctx.type = 'application/xml'; return; @@ -97,7 +99,7 @@ class HomeController extends Controller { xmlArray.app_key = appkey; let warehouseCode = xmlArray.request.warehouseCode || ''; - await service.qimen.saveQimenLogBody(xmlData); + logData.body = xmlData; const erpName = await service.qimen.getErpName(appkey); let api_info = { warehouseCode: '', @@ -119,7 +121,6 @@ class HomeController extends Controller { if (!api_info) { const errorMsg = `奇门${erpName}客户编码${customerId}仓库编码${warehouseCode}未绑定到你的货主或未启用,请联系仓库绑定`; const response = this.errorResponse(errorMsg, 'xml'); - await service.qimen.saveQimenLogResult(response); ctx.body = response; ctx.type = 'application/xml'; return; @@ -127,7 +128,6 @@ class HomeController extends Controller { if (api_info.contract_auth_status !== 2) { const errorMsg = `货主与仓库签约状态异常,请到WMS核实签约状态${api_info.contract_auth_status}`; const response = this.errorResponse(errorMsg, 'xml'); - await service.qimen.saveQimenLogResult(response); ctx.body = response; ctx.type = 'application/xml'; return; @@ -135,8 +135,6 @@ class HomeController extends Controller { if (api_info.warehouse_status === 0) { const errorMsg = '仓库状态异常,请联系仓库核实WMS状态'; const response = this.errorResponse(errorMsg, 'xml'); - await service.qimen.saveQimenLogResult(response); - ctx.body = response; ctx.type = 'application/xml'; return; @@ -147,8 +145,6 @@ class HomeController extends Controller { if (authEndTime2 < currentTime) { const errorMsg = '与仓库合约过期,请到WMS重新发起仓库续约'; const response = this.errorResponse(errorMsg, 'xml'); - await service.qimen.saveQimenLogResult(response); - ctx.body = response; ctx.type = 'application/xml'; return; @@ -156,8 +152,6 @@ class HomeController extends Controller { if (authEndTime < currentTime) { const errorMsg = '仓库订阅过期,请联系仓库核实状态'; const response = this.errorResponse(errorMsg, 'xml'); - await service.qimen.saveQimenLogResult(response); - ctx.body = response; ctx.type = 'application/xml'; return; @@ -167,17 +161,29 @@ class HomeController extends Controller { // 调用业务方法 const result = await service.qimen.callMethod(className, actionName, xmlArray, api_info.store_id, api_info.warehouse_id, appkey, customerId, warehouseCode, getParams.format); - // 记录成功响应 - const logData_result = typeof result === 'string' ? result : JSON.stringify(result); - await service.qimen.saveQimenLogResult(logData_result); ctx.body = result; ctx.type = getParams.format === 'xml' ? 'application/xml' : 'application/json'; } catch (error) { const response = this.errorResponse('奇门接口错误: ' + error.message, ctx.query.format || 'xml'); - await service.qimen.saveQimenLogResult(response); ctx.body = response; ctx.type = ctx.query.format === 'xml' ? 'application/xml' : 'application/json'; + } finally { + // 统一写入日志文件队列 + logData.use_time = Date.now() - startTime; + logData.result = typeof ctx.body === 'string' ? ctx.body : JSON.stringify(ctx.body); + 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); + } + try { + await this.app.fileWriter.writeRecord('qimen-logs', logData); + } catch (writeErr) { + ctx.logger.error('[qimen-log-sink] 写入文件失败: ' + writeErr.message); + ctx.logger.info('[qimen-log-sink] 日志数据: ', JSON.stringify(logData)); + } } } diff --git a/app/controller/tempFileWriter.js b/app/controller/tempFileWriter.js new file mode 100644 index 0000000..bb12dab --- /dev/null +++ b/app/controller/tempFileWriter.js @@ -0,0 +1,61 @@ +'use strict'; + +const { + Controller, +} = require('egg'); +const { toFailure, toSuccess } = require('../lib/api_response'); + +class TempFileWriterController extends Controller { + /** + * 触发一次临时 fileWriter 消费,并返回本次消费结果。 + * @return {Promise} 无返回值,结果写入响应体。 + */ + async consume() { + const { ctx, app } = this; + const { businessName, consumerName } = ctx.query; + + if (!businessName) { + ctx.status = 400; + ctx.body = toFailure({ + httpStatus: 400, + message: 'businessName 不能为空', + }); + return; + } + + const progressFilePath = app.fileWriter.getProgressFilePath( + businessName, + null, + consumerName || 'temp-http-consumer' + ); + const consumedRecords = []; + + try { + const result = await app.fileWriter.consumeFiles({ + businessName, + progressFilePath, + parseJson: ctx.query.parseJson !== 'false', + onRecord: async record => { + consumedRecords.push(record); + }, + }); + + ctx.body = toSuccess({ + businessName, + progressFilePath, + consumedRecords, + processedCount: result.processedCount, + progress: result.progress, + dataFiles: result.dataFiles, + }); + } catch (error) { + ctx.status = error && error.message === 'businessName 不能为空' ? 400 : 500; + ctx.body = toFailure({ + httpStatus: ctx.status, + message: error.message, + }); + } + } +} + +module.exports = TempFileWriterController; diff --git a/app/lib/file_writer.js b/app/lib/file_writer.js new file mode 100644 index 0000000..11988d9 --- /dev/null +++ b/app/lib/file_writer.js @@ -0,0 +1,1497 @@ +'use strict'; + +const fs = require('node:fs'); +const fsp = require('node:fs/promises'); +const os = require('node:os'); +const path = require('node:path'); + +const DEFAULT_MAX_FILE_SIZE = 100 * 1024 * 1024; +const DEFAULT_MAX_CONSUME_RECORDS_PER_WINDOW = 1000; +const DEFAULT_WRITE_WINDOW_SECONDS = 1; +const DEFAULT_MAX_WRITE_RECORDS_PER_WINDOW = 2000; +const DEFAULT_RETENTION_DAYS = 7; +const DEFAULT_CLEANUP_INTERVAL_MS = 60 * 60 * 1000; +const DEFAULT_STATE_MAP_MAX_ENTRIES = 256; +const DEFAULT_WRITE_WINDOW_BUCKET_COUNT = 8; + +/** + * 本地文件队列写入器。 + * 负责把业务数据按 JSON Lines 追加到本地文件,并保证单条写入串行、fsync 落盘和自动轮转。 + */ +class LocalFileWriter { + /** + * 创建本地文件写入器实例。 + * @param {Egg.Application} app Egg 应用实例。 + */ + constructor(app) { + this.app = app; + this.config = app.config.fileWriter || {}; + this.baseDir = path.resolve(this.config.baseDir || path.join(app.baseDir, 'runtime', 'file-writer')); + this.maxFileSize = this.normalizeSize(this.config.maxFileSize, DEFAULT_MAX_FILE_SIZE); + this.maxConsumeRecordsPerWindow = this.normalizePositiveInteger( + this.config.maxConsumeRecordsPerWindow + ?? this.config.maxConsumeRecordsPerRun + ?? app.config.maxConsumeRecordsPerWindow + ?? app.config.maxConsumeRecordsPerRun, + DEFAULT_MAX_CONSUME_RECORDS_PER_WINDOW + ); + this.maxConsumeRecordsPerRun = this.maxConsumeRecordsPerWindow; + this.writeWindowSeconds = this.normalizeInteger( + this.config.writeWindowSeconds + ?? app.config.writeWindowSeconds, + DEFAULT_WRITE_WINDOW_SECONDS + ); + this.maxWriteRecordsPerWindow = this.normalizeInteger( + this.config.maxWriteRecordsPerWindow + ?? app.config.maxWriteRecordsPerWindow, + DEFAULT_MAX_WRITE_RECORDS_PER_WINDOW + ); + this.writeWindowStartedAt = 0; + this.writeWindowRecordCount = 0; + this.writeWindowBucketCount = this.normalizePositiveInteger( + this.config.writeWindowBucketCount + ?? app.config.writeWindowBucketCount, + DEFAULT_WRITE_WINDOW_BUCKET_COUNT + ); + this.preferredBucket = this.hashStringToIndex(this.workerId + '-' + this.pid, this.writeWindowBucketCount); + this.retentionDays = this.normalizeInteger(this.config.retentionDays, DEFAULT_RETENTION_DAYS); + this.cleanupIntervalMs = this.normalizeInteger(this.config.cleanupIntervalMs, DEFAULT_CLEANUP_INTERVAL_MS); + this.machineId = this.sanitizeSegment(this.config.machineId || os.hostname() || 'machine'); + this.workerId = this.sanitizeSegment(this.config.workerId || process.env.EGG_WORKER_ID || 'worker'); + this.pid = process.pid; + this.processTag = `${this.machineId}-${this.workerId}-p${this.pid}`; + this.sequenceWidth = this.normalizeInteger(this.config.sequenceWidth, 4); + this.stateMapMaxEntries = this.normalizePositiveInteger(this.config.stateMapMaxEntries, DEFAULT_STATE_MAP_MAX_ENTRIES); + this.fileExtension = this.normalizeExtension(this.config.fileExtension, '.log'); + this.progressExtension = this.normalizeExtension(this.config.progressExtension, '.progress'); + this.doneExtension = this.normalizeExtension(this.config.doneExtension, '.done'); + this.stateMap = new Map(); + this.queue = Promise.resolve(); + this.lastCleanupAt = 0; + } + + /** + * 将写入任务串行排队执行。 + * @param {Function} task 需要排队执行的异步任务。 + * @return {Promise<*>} 任务执行结果。 + */ + enqueue(task) { + const currentTask = this.queue.then(() => task()); + this.queue = currentTask.then(() => undefined, () => undefined); + return currentTask; + } + + /** + * 等待当前队列里的所有写入完成。 + * @return {Promise} 等待完成的 Promise。 + */ + async flush() { + await this.queue; + } + + /** + * 把业务数据写入本地 JSON Lines 文件。 + * @param {string} businessName 业务名称。 + * @param {*} record 需要写入的数据。 + * @param {Object} [options] 写入选项。 + * @param {Date|string|number} [options.date] 指定归档日期,默认使用当前时间。 + * @return {Promise} 写入结果。 + */ + async writeRecord(businessName, record, options = {}) { + return this.enqueue(async () => { + const windowCheck = await this.atomicCheckAndIncrementWriteWindow(); + this.writeWindowStartedAt = windowCheck.counter.startedAt; + this.writeWindowRecordCount = windowCheck.counter.recordCount; + + if (!windowCheck.allowed) { + const writeWindowMs = this.writeWindowSeconds * 1000; + const resumeAt = new Date(windowCheck.counter.startedAt + writeWindowMs).toISOString(); + return { + throttled: true, + businessName, + resumeAt, + writeWindowSeconds: this.writeWindowSeconds, + writeWindowRecordCount: windowCheck.counter.recordCount, + maxWriteRecordsPerWindow: this.maxWriteRecordsPerWindow, + }; + } + + const partitionState = await this.getPartitionState(businessName, options.date); + const jsonLine = this.stringifyRecord(record); + const payload = `${jsonLine}\n`; + const payloadSize = Buffer.byteLength(payload); + + if (partitionState.currentSize > 0 && partitionState.currentSize + payloadSize > this.maxFileSize) { + partitionState.sequence += 1; + partitionState.currentFilePath = this.buildDataFilePath(partitionState, partitionState.sequence); + partitionState.currentSize = 0; + } + + await this.ensureParentDirectory(partitionState.partitionDir); + + const handle = await fsp.open(partitionState.currentFilePath, 'a'); + try { + await handle.write(payload); + await handle.sync(); + } finally { + await handle.close(); + } + + partitionState.currentSize += payloadSize; + await this.maybeCleanup(); + + return { + businessName: partitionState.businessName, + dateKey: partitionState.dateKey, + filePath: partitionState.currentFilePath, + size: partitionState.currentSize, + bytesWritten: payloadSize, + sequence: partitionState.sequence, + machineId: this.machineId, + workerId: this.workerId, + pid: this.pid, + throttled: false, + writeWindowRecordCount: windowCheck.counter.recordCount, + maxWriteRecordsPerWindow: this.maxWriteRecordsPerWindow, + }; + }); + } + + /** + * 写入方法别名,便于业务侧直接调用。 + * @param {string} businessName 业务名称。 + * @param {*} record 需要写入的数据。 + * @param {Object} [options] 写入选项。 + * @return {Promise} 写入结果。 + */ + async write(businessName, record, options = {}) { + return this.writeRecord(businessName, record, options); + } + + /** + * 获取某个业务在指定日期下的目录信息。 + * @param {string} businessName 业务名称。 + * @param {Date|string|number} [date] 指定日期。 + * @return {Object} 目录信息。 + */ + getPartitionInfo(businessName, date = new Date()) { + const businessSegment = this.sanitizeSegment(businessName || 'default'); + const dateParts = this.getDateParts(date); + const partitionDir = path.join(this.baseDir, businessSegment, dateParts.year, dateParts.month, dateParts.day); + + return { + businessName, + businessSegment, + dateKey: dateParts.dateKey, + partitionDir, + filePrefix: `${businessSegment}-${this.processTag}`, + processTag: this.processTag, + }; + } + + /** + * 获取消费进度文件路径。 + * @param {string} businessName 业务名称。 + * @param {Date|string|number|null} [date] 指定日期;传空时使用业务级共享进度文件。 + * @param {string} [consumerName] 消费者名称。 + * @return {string} 进度文件路径。 + */ + getProgressFilePath(businessName, date = new Date(), consumerName = 'default') { + const businessSegment = this.sanitizeSegment(businessName || 'default'); + const safeConsumerName = this.sanitizeSegment(consumerName || 'default'); + if (date == null) { + return path.join(this.baseDir, businessSegment, `.${safeConsumerName}${this.progressExtension}`); + } + + const partitionInfo = this.getPartitionInfo(businessName, date); + return path.join(partitionInfo.partitionDir, `.${safeConsumerName}${this.progressExtension}`); + } + + /** + * 获取某个数据文件的消费完成标记路径。 + * @param {string} filePath 数据文件路径。 + * @return {string} 完成标记路径。 + */ + getDoneFilePath(filePath) { + const resolvedFilePath = path.resolve(filePath); + return `${resolvedFilePath}${this.doneExtension}`; + } + + /** + * 列出某个业务日期分区下的所有日志文件。 + * @param {string} businessName 业务名称。 + * @param {Date|string|number|null} [date] 指定日期;传空时递归列出业务目录下所有日志文件。 + * @return {Promise>} 排序后的文件路径列表。 + */ + async listDataFiles(businessName, date = new Date()) { + const businessSegment = this.sanitizeSegment(businessName || 'default'); + const businessDir = path.join(this.baseDir, businessSegment); + const targetDir = date == null ? businessDir : this.getPartitionInfo(businessName, date).partitionDir; + const files = await this.collectDataFiles(targetDir); + + return files + .sort((left, right) => { + return this.compareDataFileSortKey(left.sortKey, right.sortKey); + }) + .map(entry => entry.filePath); + } + + /** + * 读取单个日志文件中的 JSON Lines 数据。 + * @param {string} filePath 日志文件路径。 + * @param {Object} [options] 读取选项。 + * @param {number} [options.startOffset=0] 起始字节偏移量。 + * @param {number} [options.maxRecords=0] 最大读取条数,0 或不传不限制。 + * @param {boolean} [options.parseJson=true] 是否自动解析 JSON。 + * @return {Promise} 读取结果。 + */ + async readRecords(filePath, options = {}) { + const resolvedFilePath = path.resolve(filePath); + const startOffset = this.normalizeInteger(options.startOffset, 0); + const maxRecords = this.normalizeInteger(options.maxRecords, 0); + const parseJson = options.parseJson !== false; + const records = []; + let nextOffset = startOffset; + let lineNumber = 0; + + try { + for await (const lineEntry of this.iterateJsonLines(resolvedFilePath, startOffset)) { + lineNumber = lineEntry.lineNumber; + nextOffset = lineEntry.nextOffset; + + if (!lineEntry.line.trim()) { + continue; + } + + if (!parseJson) { + records.push(lineEntry.line); + + if (maxRecords > 0 && records.length >= maxRecords) { + break; + } + + continue; + } + + try { + records.push(JSON.parse(lineEntry.line)); + + if (maxRecords > 0 && records.length >= maxRecords) { + break; + } + } catch (parseError) { + parseError.message = `解析文件 ${resolvedFilePath} 第 ${lineNumber} 行失败: ${parseError.message}`; + throw parseError; + } + } + } catch (error) { + if (error.code === 'ENOENT') { + return { + filePath: resolvedFilePath, + records: [], + nextOffset: startOffset, + lineNumber: 0, + }; + } + + throw error; + } + + return { + filePath: resolvedFilePath, + records, + nextOffset, + lineNumber, + }; + } + + /** + * 消费某个文件,并在每条记录处理完成后更新进度文件。 + * @param {string} filePath 日志文件路径。 + * @param {Object} options 消费选项。 + * @param {string} options.progressFilePath 进度文件路径。 + * @param {Function} options.onRecord 每条记录的处理函数。 + * @param {number} [options.startOffset=0] 起始偏移量。 + * @param {boolean} [options.parseJson=true] 是否自动解析 JSON。 + * @param {number} [options.maxConsumeRecordsPerWindow] 单次最大消费条数。 + * @param {number} [options.maxConsumeRecordsPerRun] 兼容旧字段的单次最大消费条数。 + * @param {Object|null} [options.progress] 已加载的进度数据,供内部复用。 + * @return {Promise} 消费结果,包含 filePath、processedCount、nextOffset、limitReached、maxConsumeRecordsPerWindow。 + */ + async consumeFile(filePath, options = {}) { + const progressFilePath = options.progressFilePath; + const onRecord = options.onRecord; + + if (!progressFilePath) { + throw new Error('progressFilePath 不能为空'); + } + + if (typeof onRecord !== 'function') { + throw new Error('onRecord 必须是函数'); + } + + const progress = options.progress || await this.loadProgress(progressFilePath); + const consumeLimit = this.normalizePositiveInteger( + options.maxConsumeRecordsPerWindow ?? options.maxConsumeRecordsPerRun, + this.maxConsumeRecordsPerWindow + ); + + const resolvedFilePath = path.resolve(filePath); + const startOffset = this.resolveConsumeStartOffset(progress, resolvedFilePath, options); + const parseJson = options.parseJson !== false; + + let offset = startOffset; + let processedCount = 0; + let lineNumber = 0; + let limitReached = false; + + try { + for await (const lineEntry of this.iterateJsonLines(resolvedFilePath, startOffset)) { + if (consumeLimit > 0 && processedCount >= consumeLimit) { + limitReached = true; + break; + } + + lineNumber = lineEntry.lineNumber; + offset = lineEntry.nextOffset; + + if (!lineEntry.line.trim()) { + continue; + } + + let record = lineEntry.line; + if (parseJson) { + try { + record = JSON.parse(lineEntry.line); + } catch (parseError) { + parseError.message = `解析文件 ${resolvedFilePath} 第 ${lineNumber} 行失败: ${parseError.message}`; + throw parseError; + } + } + + await onRecord(record, { + filePath: resolvedFilePath, + offset, + index: processedCount, + }); + processedCount += 1; + + const progressData = { + filePath: resolvedFilePath, + offset, + processedCount, + updatedAt: new Date().toISOString(), + }; + await this.saveProgress(progressFilePath, progressData); + + if (consumeLimit > 0 && processedCount >= consumeLimit) { + limitReached = true; + break; + } + } + } catch (error) { + if (error.code === 'ENOENT') { + return { + filePath: resolvedFilePath, + processedCount: 0, + nextOffset: startOffset, + limitReached: false, + maxConsumeRecordsPerRun: consumeLimit, + maxConsumeRecordsPerWindow: consumeLimit, + }; + } + + throw error; + } + + if (limitReached) { + return { + filePath: resolvedFilePath, + processedCount, + nextOffset: offset, + limitReached: true, + maxConsumeRecordsPerRun: consumeLimit, + maxConsumeRecordsPerWindow: consumeLimit, + }; + } + + const completionData = { + filePath: resolvedFilePath, + offset, + processedCount, + completedAt: new Date().toISOString(), + updatedAt: new Date().toISOString(), + }; + + await this.saveProgress(progressFilePath, completionData); + await this.saveCompletionMarker(resolvedFilePath, completionData); + + return { + filePath: resolvedFilePath, + processedCount, + nextOffset: offset, + limitReached: false, + maxConsumeRecordsPerRun: consumeLimit, + maxConsumeRecordsPerWindow: consumeLimit, + }; + } + + /** + * 按业务目录消费所有日志文件,支持断点续传。 + * @param {Object} options 消费选项。 + * @param {string} options.businessName 业务名称。 + * @param {string} options.progressFilePath 进度文件路径。 + * @param {Function} options.onRecord 每条记录的处理函数。 + * @param {boolean} [options.parseJson=true] 是否自动解析 JSON。 + * @param {number} [options.maxConsumeRecordsPerWindow] 单次最大消费条数。 + * @param {number} [options.maxConsumeRecordsPerRun] 兼容旧字段的单次最大消费条数。 + * @return {Promise} 消费结果,包含 businessName、dataFiles、processedCount、progress、limitReached、maxConsumeRecordsPerWindow。 + */ + async consumeFiles(options = {}) { + const businessName = options.businessName; + const progressFilePath = options.progressFilePath; + const onRecord = options.onRecord; + + if (!businessName) { + throw new Error('businessName 不能为空'); + } + + if (!progressFilePath) { + throw new Error('progressFilePath 不能为空'); + } + + if (typeof onRecord !== 'function') { + throw new Error('onRecord 必须是函数'); + } + + const progress = await this.loadProgress(progressFilePath); + const consumeLimit = this.normalizePositiveInteger( + options.maxConsumeRecordsPerWindow ?? options.maxConsumeRecordsPerRun, + this.maxConsumeRecordsPerWindow + ); + + const dataFiles = await this.listDataFiles(businessName, null); + + if (dataFiles.length === 0) { + return { + businessName, + dataFiles, + processedCount: 0, + progress, + limitReached: false, + maxConsumeRecordsPerRun: consumeLimit, + maxConsumeRecordsPerWindow: consumeLimit, + }; + } + + let startIndex = 0; + let startOffset = 0; + let limitReached = false; + + if (progress && progress.filePath) { + const matchedIndex = dataFiles.findIndex(filePath => path.resolve(filePath) === path.resolve(progress.filePath)); + if (matchedIndex >= 0) { + startIndex = matchedIndex; + startOffset = this.normalizeInteger(progress.offset, 0); + } else { + const progressSortKey = this.getDataFileSortKey(progress.filePath); + const fallbackIndex = dataFiles.findIndex(filePath => this.compareDataFileSortKey( + this.getDataFileSortKey(filePath), + progressSortKey + ) > 0); + if (fallbackIndex >= 0) { + startIndex = fallbackIndex; + startOffset = 0; + } else { + startIndex = dataFiles.length; + } + } + } + + let processedCount = 0; + let currentProgress = progress; + let totalConsumedCount = 0; + + for (let index = startIndex; index < dataFiles.length; index += 1) { + if (consumeLimit > 0 && totalConsumedCount >= consumeLimit) { + limitReached = true; + break; + } + + const filePath = dataFiles[index]; + const completion = await this.loadCompletionMarker(filePath); + if (completion && path.resolve(completion.filePath || filePath) === path.resolve(filePath)) { + currentProgress = { + ...completion, + filePath: completion.filePath || filePath, + updatedAt: new Date().toISOString(), + }; + await this.saveProgress(progressFilePath, currentProgress); + continue; + } + + const remainingLimit = consumeLimit > 0 ? consumeLimit - totalConsumedCount : consumeLimit; + const fileResult = await this.consumeFile(filePath, { + progressFilePath, + onRecord, + startOffset: index === startIndex ? startOffset : 0, + parseJson: options.parseJson, + maxConsumeRecordsPerWindow: remainingLimit, + progress, + }); + processedCount += fileResult.processedCount; + totalConsumedCount += fileResult.processedCount; + currentProgress = { + filePath, + offset: fileResult.nextOffset, + processedCount, + updatedAt: new Date().toISOString(), + }; + await this.saveProgress(progressFilePath, currentProgress); + + if (fileResult.limitReached) { + limitReached = true; + break; + } + } + + return { + businessName, + dataFiles, + processedCount, + progress: currentProgress, + limitReached, + maxConsumeRecordsPerRun: consumeLimit, + maxConsumeRecordsPerWindow: consumeLimit, + }; + } + + /** + * 递归收集目录下的所有数据文件,并记录用于排序的分区日期与序号。 + * @param {string} dirPath 目录路径。 + * @param {Array} [result=[]] 累积结果。 + * @return {Promise>} 收集结果。 + */ + async collectDataFiles(dirPath, result = []) { + let entries; + try { + entries = await fsp.readdir(dirPath, { withFileTypes: true }); + } catch (error) { + if (error.code === 'ENOENT') { + return result; + } + + throw error; + } + + for (const entry of entries) { + const entryPath = path.join(dirPath, entry.name); + if (entry.isDirectory()) { + await this.collectDataFiles(entryPath, result); + continue; + } + + if (!entry.isFile() || !entry.name.endsWith(this.fileExtension)) { + continue; + } + + result.push({ + filePath: entryPath, + sortKey: this.getDataFileSortKey(entryPath), + }); + } + + return result; + } + + /** + * 解析数据文件的消费顺序键,按分区日期和文件序号排序。 + * @param {string} filePath 数据文件路径。 + * @return {Object} 排序键。 + */ + getDataFileSortKey(filePath) { + const resolvedFilePath = path.resolve(filePath); + const relativeParts = path.relative(this.baseDir, resolvedFilePath).split(path.sep).filter(Boolean); + const fileName = path.basename(resolvedFilePath); + const sequenceMatch = fileName.match(/-(\d+)\.[^.]+$/); + + let partitionDateKey = ''; + if (relativeParts.length >= 5) { + const year = relativeParts[1]; + const month = relativeParts[2]; + const day = relativeParts[3]; + + if (/^\d+$/.test(year) && /^\d+$/.test(month) && /^\d+$/.test(day)) { + partitionDateKey = `${year.padStart(4, '0')}-${month.padStart(2, '0')}-${day.padStart(2, '0')}`; + } + } + + return { + partitionDateKey, + sequence: sequenceMatch ? Number.parseInt(sequenceMatch[1], 10) : Number.MAX_SAFE_INTEGER, + filePath: resolvedFilePath, + }; + } + + /** + * 比较两个数据文件的排序键。 + * @param {Object} left 左侧排序键。 + * @param {Object} right 右侧排序键。 + * @return {number} 排序结果。 + */ + compareDataFileSortKey(left, right) { + if (left.partitionDateKey !== right.partitionDateKey) { + return left.partitionDateKey.localeCompare(right.partitionDateKey, 'en'); + } + + if (left.sequence !== right.sequence) { + return left.sequence - right.sequence; + } + + return left.filePath.localeCompare(right.filePath, 'en', { numeric: true }); + } + + /** + * 读取进度文件。 + * @param {string} progressFilePath 进度文件路径。 + * @return {Promise} 进度内容。 + */ + async loadProgress(progressFilePath) { + const resolvedPath = path.resolve(progressFilePath); + try { + const content = await fsp.readFile(resolvedPath, 'utf8'); + if (!content.trim()) { + return null; + } + + return this.normalizeProgressData(JSON.parse(content), resolvedPath); + } catch (error) { + if (error.code === 'ENOENT') { + return null; + } + + if (error instanceof SyntaxError) { + this.app.logger.warn('[fileWriter.loadProgress] 忽略损坏的进度文件', resolvedPath, error.message); + return null; + } + + throw error; + } + } + + /** + * 保存进度文件。 + * @param {string} progressFilePath 进度文件路径。 + * @param {Object} progressData 进度数据。 + * @return {Promise} 保存后的进度数据。 + */ + async saveProgress(progressFilePath, progressData) { + const resolvedPath = path.resolve(progressFilePath); + const payload = `${JSON.stringify({ + ...progressData, + updatedAt: progressData.updatedAt || new Date().toISOString(), + }, null, 2)}\n`; + + await this.writeAtomicTextFile(resolvedPath, payload); + + return { + ...progressData, + updatedAt: progressData.updatedAt || new Date().toISOString(), + }; + } + + /** + * 保存消费完成标记。 + * @param {string} filePath 数据文件路径。 + * @param {Object} completionData 完成数据。 + * @return {Promise} 保存后的完成数据。 + */ + async saveCompletionMarker(filePath, completionData) { + const resolvedFilePath = path.resolve(filePath); + const doneFilePath = this.getDoneFilePath(resolvedFilePath); + const payload = `${JSON.stringify({ + ...completionData, + filePath: resolvedFilePath, + completedAt: completionData.completedAt || new Date().toISOString(), + }, null, 2)}\n`; + + await this.writeAtomicTextFile(doneFilePath, payload); + + return { + ...completionData, + filePath: resolvedFilePath, + completedAt: completionData.completedAt || new Date().toISOString(), + }; + } + + /** + * 读取消费完成标记。 + * @param {string} filePath 数据文件路径。 + * @return {Promise} 完成标记内容。 + */ + async loadCompletionMarker(filePath) { + const resolvedFilePath = path.resolve(filePath); + const doneFilePath = this.getDoneFilePath(resolvedFilePath); + try { + const content = await fsp.readFile(doneFilePath, 'utf8'); + if (!content.trim()) { + return null; + } + + return this.normalizeCompletionData(JSON.parse(content), resolvedFilePath); + } catch (error) { + if (error.code === 'ENOENT') { + return null; + } + + if (error instanceof SyntaxError) { + this.app.logger.warn('[fileWriter.loadCompletionMarker] 忽略损坏的完成标记', doneFilePath, error.message); + return null; + } + + throw error; + } + } + + /** + * 清理超过保留期的日志文件与进度文件。 + * @return {Promise} 清理结果。 + */ + async cleanupExpiredFiles() { + if (!this.retentionDays || this.retentionDays <= 0) { + return { + removedFiles: 0, + removedDirectories: 0, + }; + } + + const cutoffTime = Date.now() - (this.retentionDays * 24 * 60 * 60 * 1000); + const result = { + removedFiles: 0, + removedDirectories: 0, + }; + + await this.walkAndCleanup(this.baseDir, cutoffTime, result); + return result; + } + + /** + * 规范化日期并返回目录分段。 + * @param {Date|string|number} date 日期。 + * @return {Object} 日期分段。 + */ + getDateParts(date = new Date()) { + const targetDate = date instanceof Date ? date : new Date(date); + if (Number.isNaN(targetDate.getTime())) { + throw new Error(`无效的日期参数: ${date}`); + } + + const year = String(targetDate.getFullYear()); + const month = String(targetDate.getMonth() + 1).padStart(2, '0'); + const day = String(targetDate.getDate()).padStart(2, '0'); + + return { + year, + month, + day, + dateKey: `${year}-${month}-${day}`, + }; + } + + /** + * 获取写入分区状态。 + * @param {string} businessName 业务名称。 + * @param {Date|string|number} [date] 指定日期。 + * @return {Promise} 分区状态。 + */ + async getPartitionState(businessName, date = new Date()) { + const partitionInfo = this.getPartitionInfo(businessName, date); + const stateKey = `${partitionInfo.businessSegment}:${partitionInfo.dateKey}`; + + if (this.stateMap.has(stateKey)) { + const existingState = this.stateMap.get(stateKey); + this.stateMap.delete(stateKey); + this.stateMap.set(stateKey, existingState); + return existingState; + } + + await this.ensureParentDirectory(partitionInfo.partitionDir); + + const state = { + businessName, + businessSegment: partitionInfo.businessSegment, + dateKey: partitionInfo.dateKey, + partitionDir: partitionInfo.partitionDir, + filePrefix: partitionInfo.filePrefix, + sequence: 1, + currentSize: 0, + currentFilePath: this.buildDataFilePath({ + partitionDir: partitionInfo.partitionDir, + filePrefix: partitionInfo.filePrefix, + }, 1), + }; + + this.evictOldestStateIfNeeded(); + this.stateMap.set(stateKey, state); + return state; + } + + /** + * 逐行读取 JSON Lines 文件,并返回每行的精确字节偏移。 + * @param {string} filePath 文件路径。 + * @param {number} [startOffset=0] 起始字节偏移量。 + * @return {AsyncGenerator} 逐行迭代器。 + */ + async* iterateJsonLines(filePath, startOffset = 0) { + const stream = fs.createReadStream(filePath, { + start: startOffset, + }); + + let buffer = Buffer.alloc(0); + let offset = startOffset; + let lineNumber = 0; + + try { + for await (const chunk of stream) { + buffer = Buffer.concat([ buffer, chunk ]); + + while (buffer.length > 0) { + const lineFeedIndex = buffer.indexOf(0x0A); + if (lineFeedIndex < 0) { + break; + } + + const lineEndIndex = lineFeedIndex > 0 && buffer[lineFeedIndex - 1] === 0x0D + ? lineFeedIndex - 1 + : lineFeedIndex; + const consumedBytes = lineFeedIndex + 1; + const lineBuffer = buffer.slice(0, lineEndIndex); + + lineNumber += 1; + offset += consumedBytes; + buffer = buffer.slice(consumedBytes); + + yield { + lineNumber, + line: lineBuffer.toString('utf8'), + nextOffset: offset, + }; + } + } + + if (buffer.length > 0) { + lineNumber += 1; + offset += buffer.length; + + yield { + lineNumber, + line: buffer.toString('utf8'), + nextOffset: offset, + }; + } + } finally { + stream.destroy(); + } + } + + /** + * 归一化进度文件内容,兼容损坏或旧字段。 + * @param {*} progressData 原始进度内容。 + * @param {string} [fallbackFilePath] 兜底文件路径。 + * @return {Object|null} 归一化后的进度内容。 + */ + normalizeProgressData(progressData, fallbackFilePath = null) { + if (!progressData || typeof progressData !== 'object') { + return null; + } + + const filePath = typeof progressData.filePath === 'string' && progressData.filePath.trim() + ? path.resolve(progressData.filePath) + : (fallbackFilePath || null); + const offset = this.normalizeInteger(progressData.offset ?? progressData.nextOffset, 0); + const processedCount = this.normalizeInteger(progressData.processedCount ?? progressData.processed ?? progressData.count, 0); + + return { + ...progressData, + filePath, + offset, + processedCount, + updatedAt: typeof progressData.updatedAt === 'string' && progressData.updatedAt.trim() + ? progressData.updatedAt + : undefined, + completedAt: typeof progressData.completedAt === 'string' && progressData.completedAt.trim() + ? progressData.completedAt + : undefined, + }; + } + + /** + * 归一化完成标记内容,兼容损坏或旧字段。 + * @param {*} completionData 原始完成标记内容。 + * @param {string} fallbackFilePath 兜底文件路径。 + * @return {Object|null} 归一化后的完成标记内容。 + */ + normalizeCompletionData(completionData, fallbackFilePath) { + if (!completionData || typeof completionData !== 'object') { + return null; + } + + const filePath = typeof completionData.filePath === 'string' && completionData.filePath.trim() + ? path.resolve(completionData.filePath) + : fallbackFilePath; + if (!filePath) { + return null; + } + + const completedAtMs = this.resolveTimestamp(completionData.completedAt ?? completionData.updatedAt); + + return { + ...completionData, + filePath, + completedAt: this.formatTimestamp(completedAtMs), + updatedAt: typeof completionData.updatedAt === 'string' && completionData.updatedAt.trim() + ? completionData.updatedAt + : undefined, + }; + } + + /** + * 回收最旧的分区状态,避免 stateMap 无界增长。 + * @return {void} + */ + evictOldestStateIfNeeded() { + if (this.stateMap.size < this.stateMapMaxEntries) { + return; + } + + const oldestKey = this.stateMap.keys().next().value; + if (oldestKey !== undefined) { + this.stateMap.delete(oldestKey); + } + } + + /** + * 构建日志文件路径。 + * @param {Object} partitionState 分区状态。 + * @param {number} sequence 序号。 + * @return {string} 文件路径。 + */ + buildDataFilePath(partitionState, sequence) { + const sequenceText = String(sequence).padStart(this.sequenceWidth, '0'); + const fileName = `${partitionState.filePrefix}-${sequenceText}${this.fileExtension}`; + return path.join(partitionState.partitionDir, fileName); + } + + /** + * 把要写入的记录转换为 JSON 字符串。 + * @param {*} record 记录内容。 + * @return {string} JSON 字符串。 + */ + stringifyRecord(record) { + const json = JSON.stringify(record, this.jsonReplacer); + if (json === undefined) { + throw new Error('写入内容无法被序列化为 JSON'); + } + + return json; + } + + /** + * JSON 序列化时处理 BigInt。 + * @param {string} key 属性名。 + * @param {*} value 属性值。 + * @return {*} 序列化后的值。 + */ + jsonReplacer(key, value) { + if (typeof value === 'bigint') { + return value.toString(); + } + + return value; + } + + /** + * 规范化目录片段,避免路径穿越。 + * @param {*} value 待处理值。 + * @return {string} 安全片段。 + */ + sanitizeSegment(value) { + const normalized = String(value || '').trim(); + if (!normalized) { + return 'default'; + } + + const safeValue = Array.from(normalized).map(character => { + const code = character.charCodeAt(0); + if (code < 32 || '<>:"/\\|?*'.includes(character)) { + return '_'; + } + + return character; + }).join(''); + + return safeValue + .replace(/\s+/g, '_') + .replace(/\.+/g, '.') + .replace(/^\.+|\.+$/g, '') + .replace(/_+/g, '_') + .slice(0, 80) || 'default'; + } + + /** + * 规范化扩展名。 + * @param {*} value 扩展名。 + * @param {string} fallback 回退扩展名。 + * @return {string} 规范化后的扩展名。 + */ + normalizeExtension(value, fallback) { + const raw = String(value || fallback || '').trim(); + if (!raw) { + return fallback; + } + + return raw.startsWith('.') ? raw : `.${raw}`; + } + + /** + * 规范化数字。 + * @param {*} value 数值或字符串。 + * @param {number} fallback 回退值。 + * @return {number} 规范化后的整数。 + */ + normalizeInteger(value, fallback) { + const parsed = Number.parseInt(value, 10); + return Number.isFinite(parsed) && parsed >= 0 ? parsed : fallback; + } + + /** + * 规范化大小配置。 + * @param {*} value 大小配置。 + * @param {number} fallback 回退值。 + * @return {number} 字节数。 + */ + normalizeSize(value, fallback) { + if (typeof value === 'number' && Number.isFinite(value) && value > 0) { + return Math.floor(value); + } + + if (typeof value === 'string') { + const trimmed = value.trim(); + const match = trimmed.match(/^(\d+(?:\.\d+)?)([kKmMgGtT]?)$/); + if (match) { + const number = Number.parseFloat(match[1]); + const unit = match[2].toLowerCase(); + const unitMap = { + '': 1, + k: 1024, + m: 1024 * 1024, + g: 1024 * 1024 * 1024, + t: 1024 * 1024 * 1024 * 1024, + }; + return Math.floor(number * (unitMap[unit] || 1)); + } + } + + return fallback; + } + + /** + * 规范化正整数。 + * @param {*} value 数值或字符串。 + * @param {number} fallback 回退值。 + * @return {number} 规范化后的正整数。 + */ + normalizePositiveInteger(value, fallback) { + const parsed = Number.parseInt(value, 10); + return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback; + } + + /** + * 解析时间值并返回毫秒时间戳。 + * @param {Date|string|number} [value] 时间值。 + * @return {number} 毫秒时间戳。 + */ + resolveTimestamp(value) { + if (value == null) { + return 0; + } + + if (value instanceof Date) { + return value.getTime(); + } + + if (typeof value === 'number' && Number.isFinite(value)) { + return value; + } + + if (typeof value === 'string') { + const trimmed = value.trim(); + if (!trimmed) { + return 0; + } + + if (/^\d+$/.test(trimmed)) { + return Number.parseInt(trimmed, 10); + } + + const parsed = Date.parse(trimmed); + if (!Number.isNaN(parsed)) { + return parsed; + } + } + + return 0; + } + + /** + * 把毫秒时间戳转换为 ISO 字符串。 + * @param {number} timestamp 毫秒时间戳。 + * @return {string|null} ISO 字符串。 + */ + formatTimestamp(timestamp) { + if (!Number.isFinite(timestamp) || timestamp <= 0) { + return null; + } + + return new Date(timestamp).toISOString(); + } + + /** + * 获取本次消费限额。 + * @param {Object} [options] 消费选项。 + * @param {number} [options.maxConsumeRecordsPerWindow] 单次最大消费条数。 + * @param {number} [options.maxConsumeRecordsPerRun] 兼容旧字段的单次最大消费条数。 + * @return {number} 当前消费限额。 + */ + getConsumeLimit(options = {}) { + return this.normalizePositiveInteger( + options.maxConsumeRecordsPerWindow ?? options.maxConsumeRecordsPerRun, + this.maxConsumeRecordsPerWindow + ); + } + + /** + * 解析消费起始偏移量。 + * @param {Object|null} progress 进度数据。 + * @param {string} filePath 当前文件路径。 + * @param {Object} [options] 消费选项。 + * @param {number} [options.startOffset] 显式起始偏移量。 + * @return {number} 起始偏移量。 + */ + resolveConsumeStartOffset(progress, filePath, options = {}) { + if (options.startOffset != null) { + return this.normalizeInteger(options.startOffset, 0); + } + + if (progress && progress.filePath && path.resolve(progress.filePath) === path.resolve(filePath)) { + return this.normalizeInteger(progress.offset, 0); + } + + return 0; + } + + /** + * 获取某个桶的共享写入窗口计数器文件路径。 + * @param {number} bucketIndex 桶索引。 + * @return {string} 计数器文件路径。 + */ + getWriteWindowCounterPath(bucketIndex = 0) { + return path.join(this.baseDir, `.write-window-counter-${bucketIndex}.json`); + } + + /** + * 多桶分片原子限流。 + * 将总限额均分到 N 个桶,从首选桶开始尝试,竞争失败或桶满时自动漂移到下一个桶。 + * @return {Promise} { allowed: boolean, counter: { startedAt, recordCount }, source: 'file' }。 + */ + async atomicCheckAndIncrementWriteWindow() { + if (this.maxWriteRecordsPerWindow <= 0) { + return { allowed: true, counter: { startedAt: 0, recordCount: 0 } }; + } + + const bucketCount = this.writeWindowBucketCount; + const perBucketLimit = Math.ceil(this.maxWriteRecordsPerWindow / bucketCount); + const writeWindowMs = this.writeWindowSeconds * 1000; + const now = Date.now(); + + await this.ensureParentDirectory(this.baseDir); + + let lastCounter = null; + + for (let i = 0; i < bucketCount; i++) { + const bucketIndex = (this.preferredBucket + i) % bucketCount; + const counterPath = this.getWriteWindowCounterPath(bucketIndex); + const lockPath = `${counterPath}.lock`; + + let lockHandle = null; + try { + // eslint-disable-next-line no-bitwise + lockHandle = await fsp.open(lockPath, fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_WRONLY); + } catch (error) { + if (error.code === 'EEXIST' || error.code === 'EPERM') { + continue; + } + throw error; + } + + try { + const counter = { startedAt: 0, recordCount: 0 }; + try { + const content = await fsp.readFile(counterPath, 'utf8'); + if (content.trim()) { + const data = JSON.parse(content); + counter.startedAt = typeof data.startedAt === 'number' && Number.isFinite(data.startedAt) ? data.startedAt : 0; + counter.recordCount = typeof data.recordCount === 'number' && Number.isFinite(data.recordCount) ? data.recordCount : 0; + } + } catch (error) { + if (error.code !== 'ENOENT' && !(error instanceof SyntaxError)) { + throw error; + } + } + + if (counter.startedAt > 0 && now - counter.startedAt >= writeWindowMs) { + counter.startedAt = now; + counter.recordCount = 0; + } + + if (counter.startedAt === 0) { + counter.startedAt = now; + } + + lastCounter = counter; + + if (counter.recordCount >= perBucketLimit) { + continue; + } + + counter.recordCount += 1; + await fsp.writeFile(counterPath, `${JSON.stringify(counter)}\n`, 'utf8'); + return { allowed: true, counter, source: 'file' }; + } finally { + await lockHandle.close(); + await fsp.rm(lockPath, { force: true }); + } + } + + return { allowed: false, counter: lastCounter || { startedAt: now, recordCount: 0 }, source: 'file' }; + } + + /** + * 获取当前写入窗口状态(汇总所有桶)。 + * @return {Promise} 写入窗口状态。 + */ + async getWriteWindowState() { + const writeWindowMs = this.writeWindowSeconds * 1000; + const now = Date.now(); + let totalRecordCount = 0; + let earliestStartedAt = 0; + + for (let i = 0; i < this.writeWindowBucketCount; i++) { + try { + const content = await fsp.readFile(this.getWriteWindowCounterPath(i), 'utf8'); + if (content.trim()) { + const data = JSON.parse(content); + const startedAt = typeof data.startedAt === 'number' && Number.isFinite(data.startedAt) ? data.startedAt : 0; + const recordCount = typeof data.recordCount === 'number' && Number.isFinite(data.recordCount) ? data.recordCount : 0; + if (startedAt > 0 && now - startedAt < writeWindowMs) { + totalRecordCount += recordCount; + if (earliestStartedAt === 0 || startedAt < earliestStartedAt) { + earliestStartedAt = startedAt; + } + } + } + } catch { /* ignore missing/corrupt counter files */ } + } + + const windowExpired = earliestStartedAt > 0 && now - earliestStartedAt >= writeWindowMs; + const resumeAt = earliestStartedAt > 0 + ? new Date(earliestStartedAt + writeWindowMs).toISOString() + : null; + + return { + writeWindowSeconds: this.writeWindowSeconds, + maxWriteRecordsPerWindow: this.maxWriteRecordsPerWindow, + writeWindowBucketCount: this.writeWindowBucketCount, + writeWindowRecordCount: totalRecordCount, + writeWindowStartedAt: earliestStartedAt > 0 + ? new Date(earliestStartedAt).toISOString() + : null, + windowExpired, + resumeAt: windowExpired ? null : resumeAt, + source: 'file', + }; + } + + /** + * 将字符串映射到 [0, max) 范围内的索引。 + * @param {string} str 输入字符串。 + * @param {number} max 范围上限。 + * @return {number} 索引。 + */ + hashStringToIndex(str, max) { + let hash = 0; + for (let i = 0; i < str.length; i++) { + // eslint-disable-next-line no-bitwise + hash = ((hash << 5) - hash + str.charCodeAt(i)) | 0; + } + return ((hash % max) + max) % max; + } + + /** + * 确保目录存在。 + * @param {string} dirPath 目录路径。 + * @return {Promise} Promise。 + */ + async ensureParentDirectory(dirPath) { + await fsp.mkdir(dirPath, { recursive: true }); + } + + /** + * 判断是否需要执行清理。 + * @return {Promise} Promise。 + */ + async maybeCleanup() { + if (!this.cleanupIntervalMs || this.cleanupIntervalMs <= 0) { + return; + } + + const now = Date.now(); + if (now - this.lastCleanupAt < this.cleanupIntervalMs) { + return; + } + + this.lastCleanupAt = now; + try { + await this.cleanupExpiredFiles(); + } catch (error) { + this.app.logger.warn('[fileWriter.cleanup] 清理本地文件失败', error.message); + } + } + + /** + * 递归清理目录中的过期文件。 + * @param {string} dirPath 当前目录。 + * @param {number} cutoffTime 过期时间戳。 + * @param {Object} result 清理统计。 + * @return {Promise} Promise。 + */ + async walkAndCleanup(dirPath, cutoffTime, result) { + let entries; + try { + entries = await fsp.readdir(dirPath, { withFileTypes: true }); + } catch (error) { + if (error.code === 'ENOENT') { + return; + } + + throw error; + } + + for (const entry of entries) { + const entryPath = path.join(dirPath, entry.name); + if (entry.isDirectory()) { + await this.walkAndCleanup(entryPath, cutoffTime, result); + await this.removeEmptyDirectory(entryPath, result); + continue; + } + + if (!entry.isFile()) { + continue; + } + + if (!entry.name.endsWith(this.fileExtension)) { + // 【风险点】清理只覆盖数据文件,.progress 文件不会被清理,长期会残留陈旧进度文件。 + continue; + } + + const completion = await this.loadCompletionMarker(entryPath); + if (!completion || path.resolve(completion.filePath || entryPath) !== path.resolve(entryPath)) { + continue; + } + + const stat = await fsp.stat(entryPath).catch(error => { + if (error.code === 'ENOENT') { + return null; + } + + throw error; + }); + + if (!stat || stat.mtimeMs >= cutoffTime) { + continue; + } + + await fsp.rm(entryPath, { force: true }); + await fsp.rm(this.getDoneFilePath(entryPath), { force: true }); + result.removedFiles += 1; + + const siblingEntries = await fsp.readdir(dirPath, { withFileTypes: true }); + for (const siblingEntry of siblingEntries) { + if (!siblingEntry.isFile() || !siblingEntry.name.endsWith(this.progressExtension)) { + continue; + } + + const progressPath = path.join(dirPath, siblingEntry.name); + const progressData = await this.loadProgress(progressPath); + if (!progressData || !progressData.completedAt) { + continue; + } + + if (path.resolve(progressData.filePath || '') !== path.resolve(entryPath)) { + continue; + } + + await fsp.rm(progressPath, { force: true }); + } + } + } + + /** + * 原子写入文本文件。 + * @param {string} targetPath 目标文件路径。 + * @param {string} content 文件内容。 + * @return {Promise} Promise。 + */ + async writeAtomicTextFile(targetPath, content) { + const directory = path.dirname(targetPath); + const tempPath = `${targetPath}.${this.pid}.${Date.now()}.tmp`; + + await this.ensureParentDirectory(directory); + + const handle = await fsp.open(tempPath, 'w'); + try { + await handle.write(content); + await handle.sync(); + } finally { + await handle.close(); + } + + await fsp.rename(tempPath, targetPath); + } + + /** + * 删除空目录。 + * @param {string} dirPath 目录路径。 + * @param {Object} result 清理统计。 + * @return {Promise} Promise。 + */ + async removeEmptyDirectory(dirPath, result) { + try { + const entries = await fsp.readdir(dirPath); + if (entries.length > 0) { + return; + } + + await fsp.rmdir(dirPath); + result.removedDirectories += 1; + } catch (error) { + if (error.code === 'ENOENT' || error.code === 'ENOTEMPTY') { + return; + } + + throw error; + } + } +} + +module.exports = LocalFileWriter; diff --git a/app/model/order_delivery.js b/app/model/order_delivery.js index 35d84c0..586c61c 100644 --- a/app/model/order_delivery.js +++ b/app/model/order_delivery.js @@ -380,6 +380,12 @@ module.exports = app => { defaultValue: 'none', comment: '检验状态机', }, + step: { + type: INTEGER(10), + allowNull: false, + defaultValue: 0, + comment: '订单步骤:0未审核,1已审核,2处理中,3驳回/异常,4配送中,5已完成,9已关闭', + }, print_status: { type: ENUM(...StatusEnum.PRINT_STATUS), allowNull: true, diff --git a/app/model/order_delivery_factory.js b/app/model/order_delivery_factory.js index 20f8769..da70625 100644 --- a/app/model/order_delivery_factory.js +++ b/app/model/order_delivery_factory.js @@ -348,6 +348,7 @@ module.exports = app => { \`pick_status\` enum('padding','fin','error','none') DEFAULT 'none' COMMENT '拣货状态机', \`pack_status\` enum('none','padding','fin','error') DEFAULT 'none' COMMENT '打包状态机', \`inspection_status\` enum('none','padding','running','fin','error') DEFAULT 'none' COMMENT '检验状态机', + \`step\` int(10) NOT NULL DEFAULT '0' COMMENT '订单步骤:0未审核,1已审核', \`print_status\` enum('none','padding','fin','error') DEFAULT NULL COMMENT '打印状态机', \`claim_status\` enum('none','padding','fin','error') DEFAULT 'none' COMMENT '领取状态机', \`outbound_status\` enum('none','padding','fin','error') DEFAULT 'none' COMMENT '出库状态机', @@ -383,6 +384,7 @@ module.exports = app => { pick_status: [ 'padding', 'fin', 'error', 'none' ], pack_status: [ 'none', 'padding', 'fin', 'error' ], inspection_status: [ 'none', 'padding', 'running', 'fin', 'error' ], + step: [ 0, 1 ], print_status: [ 'none', 'padding', 'fin', 'error' ], claim_status: [ 'none', 'padding', 'fin', 'error' ], outbound_status: [ 'none', 'padding', 'fin', 'error' ], diff --git a/app/model/qimen_log.js b/app/model/qimen_log.js index 42f0bb6..a844adb 100644 --- a/app/model/qimen_log.js +++ b/app/model/qimen_log.js @@ -11,6 +11,12 @@ module.exports = app => { primaryKey: true, autoIncrement: true, }, + log_id: { + type: STRING(32), + allowNull: true, + unique: true, + field: 'log_id', + }, from_key: { type: INTEGER(10), allowNull: true, diff --git a/app/model/stock_warehouse.js b/app/model/stock_warehouse.js index 2eee63b..ea749c5 100644 --- a/app/model/stock_warehouse.js +++ b/app/model/stock_warehouse.js @@ -146,12 +146,12 @@ module.exports = app => { comment: '删除时间', }, quantity: { - type: INTEGER(11).UNSIGNED, + type: INTEGER(11), defaultValue: 0, comment: '库存数量', }, locked_quantity: { - type: INTEGER(11).UNSIGNED, + type: INTEGER(11), defaultValue: 0, comment: '锁定数量', }, diff --git a/app/model/store_warehouse.js b/app/model/store_warehouse.js index 611d9ff..f1ffa84 100644 --- a/app/model/store_warehouse.js +++ b/app/model/store_warehouse.js @@ -46,6 +46,22 @@ module.exports = app => { required: false, description: '是否允许进入临时存放区', }), + Object.freeze({ + key: 'allow_oversell', + name: '允许超卖', + type: 'flag', + default: 0, + required: false, + description: '是否允许该货主在当前仓库下锁定超过可用库存', + }), + Object.freeze({ + key: 'need_order_approval', + name: '推送订单需审批', + type: 'flag', + default: 1, + required: false, + description: '控制货主推送订单创建后是否必须进入审批流程', + }), Object.freeze({ key: 'print_recharge_price', name: '面单充值元/单', diff --git a/app/router.js b/app/router.js index c96daa7..0914efe 100644 --- a/app/router.js +++ b/app/router.js @@ -27,6 +27,9 @@ module.exports = app => { router.get('/auth/printSetting/:code', controller.auth.printerSetting); router.post('/auth/printSetting/', controller.auth.printerSetting); + // 临时 fileWriter 消费入口 + router.get('/__temp/file-writer/consume', controller.tempFileWriter.consume); + // 测试接口 router.get('/testSendData', controller.home.testSendData); }; diff --git a/app/schedule/consume_qimen_logs.js b/app/schedule/consume_qimen_logs.js new file mode 100644 index 0000000..cf40dce --- /dev/null +++ b/app/schedule/consume_qimen_logs.js @@ -0,0 +1,61 @@ +'use strict'; + +const path = require('path'); + +/** + * 定时消费奇门日志文件队列,逐条插入数据库。 + * 间隔 30 秒执行,type: worker(仅一个 worker 执行)。 + * 使用 fileWriter.consumeFiles 内置的逐条进度追踪, + * 任一记录插入失败即停止,下次从失败位置重试。 + */ +module.exports = { + schedule: { + interval: '30s', + type: 'worker', + immediate: false, + disable: false, + }, + + async task(ctx) { + // 防止重入 + if (ctx.app._consumeQimenLogsRunning) return; + ctx.app._consumeQimenLogsRunning = true; + + const fileWriter = ctx.app.fileWriter; + const mysql = ctx.app.mysql.get('wms'); + const progressFilePath = path.join(fileWriter.baseDir, 'qimen-logs', '.consume-progress'); + + try { + const result = await fileWriter.consumeFiles({ + businessName: 'qimen-logs', + progressFilePath, + maxConsumeRecordsPerWindow: 500, + parseJson: true, + onRecord: async record => { + await mysql.insert('wms_qimen_log', { + log_id: record.log_id || null, + from_key: record.from_key || '', + to_key: record.to_key || '', + method: record.method || '', + sign: record.sign || '', + costomer_id: record.costomer_id || '', + v: record.v || '', + url: record.url || '', + created_at: record.created_at ? new Date(record.created_at) : new Date(), + body: record.body || '', + result: record.result || '', + use_time: record.use_time || 0, + }); + }, + }); + + if (result.processedCount > 0) { + ctx.logger.info(`[consume-qimen-logs] 消费 ${result.processedCount} 条日志`); + } + } catch (err) { + ctx.logger.error(`[consume-qimen-logs] 消费失败: ${err.message}`); + } finally { + ctx.app._consumeQimenLogsRunning = false; + } + }, +}; diff --git a/app/service/systemMethods/index.js b/app/service/systemMethods/index.js index 9797138..265f487 100644 --- a/app/service/systemMethods/index.js +++ b/app/service/systemMethods/index.js @@ -50,7 +50,7 @@ class indexService extends MainService { * @param {string} data.base64 base64 图片 * @param {string} [data.imageBase64] 兼容的 base64 字段 * @param {string} [data.image_base64] 兼容的 base64 字段 - * @returns {Promise} 识别结果 + * @return {Promise} 识别结果 */ async recognizeLicensePlate(data) { const { service, ctx } = this; diff --git a/app/service/systemMethods/order/archiveOrder.js b/app/service/systemMethods/order/archiveOrder.js index 1c146ef..47f2efc 100644 --- a/app/service/systemMethods/order/archiveOrder.js +++ b/app/service/systemMethods/order/archiveOrder.js @@ -12,6 +12,12 @@ class ArchiveOrderService extends OrderBaseService { this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } + /** + * 获取归档订单列表。 + * + * @param {Object} data 请求参数。 + * @return {Promise} 查询结果。 + */ async getarchiveOrderlist(data = {}) { try { const warehouseId = this.ensureWarehouseId(data); @@ -32,6 +38,7 @@ class ArchiveOrderService extends OrderBaseService { 'id', 'delivery_order_code', 'status', + 'step', 'outbound_status', 'delivery_time', 'updated_at', diff --git a/app/service/systemMethods/order/base.js b/app/service/systemMethods/order/base.js index e38eae6..c7ddf4a 100644 --- a/app/service/systemMethods/order/base.js +++ b/app/service/systemMethods/order/base.js @@ -67,6 +67,13 @@ class OrderBaseService extends MainService { return true; } + /** + * 构建订单列表查询条件。 + * + * @param {Object} whereData where 过滤参数。 + * @param {number} warehouseId 仓库 ID。 + * @return {Object} Sequelize 查询条件。 + */ buildWhere(whereData = {}, warehouseId) { const { Op } = this.app.Sequelize; const where = { warehouse_id: warehouseId }; @@ -85,6 +92,7 @@ class OrderBaseService extends MainService { 'outbound_status', 'lock_status', 'intercept_status', + 'step', 'source_platform_code', 'logistics_code', 'warehouse_code', diff --git a/app/service/systemMethods/order/deliveryOrder.js b/app/service/systemMethods/order/deliveryOrder.js index a6468fc..dbec4dc 100644 --- a/app/service/systemMethods/order/deliveryOrder.js +++ b/app/service/systemMethods/order/deliveryOrder.js @@ -12,6 +12,12 @@ class DeliveryOrderService extends OrderBaseService { this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } + /** + * 获取已发货订单列表。 + * + * @param {Object} data 请求参数。 + * @return {Promise} 查询结果。 + */ async getdeliveryOrderlist(data = {}) { try { const warehouseId = this.ensureWarehouseId(data); @@ -33,6 +39,7 @@ class DeliveryOrderService extends OrderBaseService { 'id', 'delivery_order_code', 'status', + 'step', 'outbound_status', 'delivery_time', 'updated_at', diff --git a/app/service/systemMethods/order/expectionOrder.js b/app/service/systemMethods/order/expectionOrder.js index 310e1ec..a3044d4 100644 --- a/app/service/systemMethods/order/expectionOrder.js +++ b/app/service/systemMethods/order/expectionOrder.js @@ -12,6 +12,12 @@ class ExpectionOrderService extends OrderBaseService { this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } + /** + * 获取异常订单列表。 + * + * @param {Object} data 请求参数。 + * @return {Promise} 查询结果。 + */ async getexpectionOrderlist(data = {}) { try { const warehouseId = this.ensureWarehouseId(data); @@ -56,6 +62,7 @@ class ExpectionOrderService extends OrderBaseService { 'id', 'delivery_order_code', 'status', + 'step', 'post_status', 'pick_status', 'pack_status', diff --git a/app/service/systemMethods/order/index.js b/app/service/systemMethods/order/index.js index fc90e22..811dc4f 100644 --- a/app/service/systemMethods/order/index.js +++ b/app/service/systemMethods/order/index.js @@ -134,6 +134,12 @@ class OrderIndexService extends OrderBaseService { return await this.ctx.service.systemMethods.order.reviewOrder.getreviewOrderlist(data); } + /** + * 更新订单状态相关字段。 + * + * @param {Object} data 请求参数。 + * @return {Promise} 更新结果。 + */ async updateStatus(data = {}) { try { const warehouseId = this.ensureWarehouseId(data); @@ -152,6 +158,7 @@ class OrderIndexService extends OrderBaseService { 'outbound_status', 'lock_status', 'intercept_status', + 'step', ]; const updateData = {}; diff --git a/app/service/systemMethods/order/pendingOrder.js b/app/service/systemMethods/order/pendingOrder.js index d57f9bb..5f59478 100644 --- a/app/service/systemMethods/order/pendingOrder.js +++ b/app/service/systemMethods/order/pendingOrder.js @@ -12,6 +12,12 @@ class PendingOrderService extends OrderBaseService { this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } + /** + * 获取待处理订单列表。 + * + * @param {Object} data 请求参数。 + * @return {Promise} 查询结果。 + */ async getpendingOrderlist(data = {}) { try { const warehouseId = this.ensureWarehouseId(data); @@ -38,6 +44,7 @@ class PendingOrderService extends OrderBaseService { 'id', 'delivery_order_code', 'status', + 'step', 'outbound_status', 'inspection_status', 'updated_at', diff --git a/app/service/systemMethods/order/reviewOrder.js b/app/service/systemMethods/order/reviewOrder.js index 3378e58..7aec438 100644 --- a/app/service/systemMethods/order/reviewOrder.js +++ b/app/service/systemMethods/order/reviewOrder.js @@ -12,6 +12,33 @@ class ReviewOrderService extends OrderBaseService { this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } + /** + * 将审核状态映射为订单步骤。 + * + * @param {string} reviewStatus 审核状态。 + * @return {number} 订单步骤值。 + */ + mapReviewStatusToStep(reviewStatus) { + const status = String(reviewStatus || 'none').trim(); + + if (status === 'fin') { + return 1; + } + if (status === 'running' || status === 'padding') { + return 2; + } + if (status === 'error') { + return 3; + } + return 0; + } + + /** + * 获取待审核订单列表。 + * + * @param {Object} data 请求参数。 + * @return {Promise} 查询结果。 + */ async getreviewOrderlist(data = {}) { try { const warehouseId = this.ensureWarehouseId(data); @@ -45,6 +72,7 @@ class ReviewOrderService extends OrderBaseService { 'id', 'delivery_order_code', 'status', + 'step', 'inspection_status', 'operator_name', 'operate_time', @@ -73,6 +101,12 @@ class ReviewOrderService extends OrderBaseService { } } + /** + * 更新订单审核状态。 + * + * @param {Object} data 请求参数。 + * @return {Promise} 更新结果。 + */ async reviewOrder(data = {}) { try { const warehouseId = this.ensureWarehouseId(data); @@ -89,6 +123,7 @@ class ReviewOrderService extends OrderBaseService { const updateData = { inspection_status: reviewStatus, + step: this.mapReviewStatusToStep(reviewStatus), operator_name: data.operator_name || this.ctx.user?.real_name || this.ctx.user?.username || null, operate_time: data.operate_time ? this.parseDateTime(data.operate_time, 'operate_time') : new Date(), updated_at: new Date(), diff --git a/app/service/systemMethods/storage/stockout.js b/app/service/systemMethods/storage/stockout.js index 7a132d4..bf2f610 100644 --- a/app/service/systemMethods/storage/stockout.js +++ b/app/service/systemMethods/storage/stockout.js @@ -22,6 +22,10 @@ class StorageStockoutService extends OrderBaseService { this.prepareWhereContext(data); const whereData = this.ctx.where || {}; const where = this.buildWhere(whereData, warehouseId); + // 默认只查询订单类型为 STOCKOUT 的出库单 + if (!whereData.order_type && !where.order_type) { + where.order_type = 'STOCKOUT'; + } const { page, pageSize, offset } = this.getPagination(data.pagination); const result = await DeliveryModel.findAndCountAll({ diff --git a/app/service/systems/delivery_order.js b/app/service/systems/delivery_order.js index 880a52a..75dfbfa 100644 --- a/app/service/systems/delivery_order.js +++ b/app/service/systems/delivery_order.js @@ -1,7 +1,24 @@ 'use strict'; const Service = require('egg').Service; +const DELIVERY_ORDER_STEP = Object.freeze({ + PENDING_REVIEW: 0, + APPROVED: 1, + PROCESSING: 2, + REJECTED_OR_EXCEPTION: 3, + OUTBOUND_OR_DELIVERING: 4, + COMPLETED: 5, + CLOSED: 9, +}); + class DeliveryOrderService extends Service { + /** + * 创建发货单。 + * + * @param {Object} data 奇门/系统订单入参。 + * @param {Object} info 当前仓库与货主上下文。 + * @return {Promise} 创建结果。 + */ async addOrder(data, info) { const { ctx } = this; if (!info.warehouseId) { @@ -45,7 +62,8 @@ class DeliveryOrderService extends Service { } // 准备订单数据 - const orderData = await this.prepareOrderData(deliveryOrder, info); + const step = await this.resolveOrderStep(info, transaction); + const orderData = await this.prepareOrderData(deliveryOrder, info, step); // 创建订单 const createdOrder = await DeliveryModel.create(orderData, { transaction }); @@ -130,11 +148,53 @@ class DeliveryOrderService extends Service { } /** - * 生成订单结构哈希值 - * 直接使用itemsInfo中的items_str - * @param {Object} itemsInfo 订单明细信息 - * @return {string} 结构哈希值 - */ + * 根据货主仓库策略解析订单步骤。 + * + * @param {Object} info 当前仓库与货主上下文。 + * @param {Object|null} transaction 数据库事务。 + * @return {Promise} 订单步骤,需审批返回 0,免审批返回 1。 + */ + async resolveOrderStep(info, transaction = null) { + const { ctx } = this; + const storeId = Number(info && info.storeId) || 0; + const warehouseId = Number(info && info.warehouseId) || 0; + + if (storeId <= 0 || warehouseId <= 0) { + return DELIVERY_ORDER_STEP.PENDING_REVIEW; + } + + const relation = await ctx.model.StoreWarehouse.findOne({ + where: { + store_id: storeId, + warehouse_id: warehouseId, + auth_status: 2, + use_status: 1, + }, + attributes: [ 'id' ], + transaction, + raw: true, + }); + + if (!relation) { + return DELIVERY_ORDER_STEP.PENDING_REVIEW; + } + + const storeWarehouseService = ctx.service && ctx.service.systems && ctx.service.systems.storeWarehouse; + const policyConfig = storeWarehouseService && typeof storeWarehouseService.getEffectivePolicyConfigByContractId === 'function' + ? await storeWarehouseService.getEffectivePolicyConfigByContractId(relation.id, transaction) + : null; + + return Number(policyConfig && policyConfig.need_order_approval) === 0 + ? DELIVERY_ORDER_STEP.APPROVED + : DELIVERY_ORDER_STEP.PENDING_REVIEW; + } + + /** + * 生成订单结构哈希值。 + * + * @param {Object} itemsInfo 订单明细信息。 + * @return {string} 结构哈希值。 + */ generateItemsHash(itemsInfo) { const crypto = require('crypto'); @@ -170,9 +230,15 @@ class DeliveryOrderService extends Service { } } - // 准备订单数据 - // 准备订单数据 - async prepareOrderData(deliveryOrder, info) { + /** + * 准备订单主表数据。 + * + * @param {Object} deliveryOrder 订单主信息。 + * @param {Object} info 当前仓库与货主上下文。 + * @param {number} step 订单步骤。 + * @return {Promise} 可入库的订单数据。 + */ + async prepareOrderData(deliveryOrder, info, step = DELIVERY_ORDER_STEP.PENDING_REVIEW) { const { ctx, service } = this; const { deliveryOrderCode, @@ -268,6 +334,7 @@ class DeliveryOrderService extends Service { is_urgency: isUrgency || 'N', invoice_flag: invoiceFlag || 'N', status: 'pedding', + step: Number.isInteger(Number(step)) ? Number(step) : DELIVERY_ORDER_STEP.PENDING_REVIEW, // 收件人信息 name: receiverInfo?.name || '', tel: receiverInfo?.tel || '', @@ -288,7 +355,15 @@ class DeliveryOrderService extends Service { }; } - // 添加订单明细 + /** + * 添加订单明细并完成库存预占。 + * + * @param {Object|Array} orderLines 订单明细数据。 + * @param {number} orderId 订单主键。 + * @param {Object} info 当前仓库与货主上下文。 + * @param {Object} transaction 数据库事务。 + * @return {Promise} 明细创建与库存统计结果。 + */ async addOrderLines(orderLines, orderId, info, transaction) { const { ctx, app } = this; const { warehouseId, appKey, storeId } = info; @@ -386,9 +461,15 @@ class DeliveryOrderService extends Service { } if (storage.canUse < totalQtyForStock) { - errors.push(`第${i + 1}行: 商品《${wms_stock.item_name}》库存不足,可用 ${storage.canUse},需求 ${totalQtyForStock}`); - stockQuantityMap.set(stockId, totalQtyForStock - planQty); - continue; + const allowOversell = stockResult.data && stockResult.data.allow_oversell === true + ? true + : (await ctx.service.systems.stockStore.getStoreWarehousePolicyConfigByStockId(stockId, transaction)).allowOversell; + + if (!allowOversell) { + errors.push(`第${i + 1}行: 商品《${wms_stock.item_name}》库存不足,可用 ${storage.canUse},需求 ${totalQtyForStock}`); + stockQuantityMap.set(stockId, totalQtyForStock - planQty); + continue; + } } // 锁定库存 diff --git a/app/service/systems/license_plate.js b/app/service/systems/license_plate.js index bb761b1..d3a3506 100644 --- a/app/service/systems/license_plate.js +++ b/app/service/systems/license_plate.js @@ -17,7 +17,7 @@ class LicensePlateService extends Service { * 说明:优先读取独立的腾讯云公共配置,若不存在则回退到兼容的 COS 配置, * 以保证历史配置方式仍然可用。 * - * @returns {Object} 腾讯云公共配置对象 + * @return {Object} 腾讯云公共配置对象 */ getTencentCloudConfig() { const tencentCloudConfig = this.config.tencentCloud || {}; @@ -33,7 +33,7 @@ class LicensePlateService extends Service { /** * 获取腾讯云 OCR 的默认区域。 * - * @returns {string} 腾讯云区域标识 + * @return {string} 腾讯云区域标识 */ getTencentCloudRegion() { const tencentCloudConfig = this.config.tencentCloud || {}; @@ -46,7 +46,7 @@ class LicensePlateService extends Service { * 规范化并校验 base64 图片。 * * @param {string} imageBase64 前端传入的 base64 图片 - * @returns {{ base64: string, buffer: Buffer, size: number }} 规范化后的图片信息 + * @return {{ base64: string, buffer: Buffer, size: number }} 规范化后的图片信息 */ normalizeBase64Image(imageBase64) { const rawValue = String(imageBase64 || '').trim(); @@ -100,7 +100,7 @@ class LicensePlateService extends Service { * @param {string} options.version 腾讯云接口版本 * @param {string} options.region 腾讯云区域 * @param {Object} options.payload 请求体 - * @returns {{ requestOptions: Object, payloadString: string }} 请求配置 + * @return {{ requestOptions: Object, payloadString: string }} 请求配置 */ buildTencentCloudRequest({ action, service, version, region, payload }) { const { secretId, secretKey } = this.getTencentCloudConfig(); @@ -163,7 +163,7 @@ class LicensePlateService extends Service { * @param {Object} requestConfig 请求配置 * @param {Object} requestConfig.requestOptions https 请求参数 * @param {string} requestConfig.payloadString 请求体字符串 - * @returns {Promise} 腾讯云响应对象 + * @return {Promise} 腾讯云响应对象 */ async sendTencentCloudRequest(requestConfig) { const { requestOptions, payloadString } = requestConfig; @@ -211,10 +211,10 @@ class LicensePlateService extends Service { * 识别车牌号码。 * * @param {string} imageBase64 前端传入的 base64 图片 - * @returns {Promise} 车牌识别结果 + * @return {Promise} 车牌识别结果 */ async recognizeLicensePlate(imageBase64) { - const { base64, size } = this.normalizeBase64Image(imageBase64); + const { base64 } = this.normalizeBase64Image(imageBase64); const region = this.getTencentCloudRegion(); const requestConfig = this.buildTencentCloudRequest({ action: OCR_ACTION, @@ -234,7 +234,7 @@ class LicensePlateService extends Service { * 统一整理腾讯云车牌识别响应。 * * @param {Object} response 腾讯云响应 - * @returns {Object} 归一化后的识别结果 + * @return {Object} 归一化后的识别结果 */ formatLicensePlateResult(response) { const responseData = response && response.Response ? response.Response : response || {}; @@ -252,4 +252,4 @@ class LicensePlateService extends Service { } } -module.exports = LicensePlateService; \ No newline at end of file +module.exports = LicensePlateService; diff --git a/app/service/systems/stock_store.js b/app/service/systems/stock_store.js index 42e9ec3..7819a62 100644 --- a/app/service/systems/stock_store.js +++ b/app/service/systems/stock_store.js @@ -248,6 +248,13 @@ class stockStoreService extends Service { } } } + /** + * 查询商品对应的库存记录与可用量。 + * + * @param {number|string} itemId 商品 ID。 + * @param {Object|null} transaction 数据库事务。 + * @return {Promise} 库存查询结果。 + */ async getItemStorages(itemId, transaction) { const { ctx, @@ -285,14 +292,17 @@ class stockStoreService extends Service { if (cached) { storage = cached; fromCache = true; - if (storage && storage.canUse === 0) { - app.logger.debug(`[缓存快速失败] 商品 ${itemId} 可用库存为0`); - return { - success: false, - error: '库存不足', - data: null, - _fromCache: true, - }; + if (storage && storage.canUse <= 0) { + const policyConfig = await this.getStoreWarehousePolicyConfigByStockId(itemInfo.stock_id, transaction); + if (!policyConfig.allowOversell) { + app.logger.debug(`[缓存快速失败] 商品 ${itemId} 可用库存为0`); + return { + success: false, + error: '库存不足', + data: null, + _fromCache: true, + }; + } } } @@ -305,7 +315,7 @@ class stockStoreService extends Service { deleted_at: null, }, attributes: [ - 'id', 'quantity', 'locked_quantity', 'gross_weight', + 'id', 'store_id', 'warehouse_id', 'quantity', 'locked_quantity', 'gross_weight', ], transaction, lock: transaction?.LOCK?.UPDATE, @@ -315,11 +325,13 @@ class stockStoreService extends Service { if (stockWarehouse) { const quantity = parseInt(stockWarehouse.quantity) || 0; const lockedQuantity = parseInt(stockWarehouse.locked_quantity) || 0; - const canUse = Math.max(0, quantity - lockedQuantity); + const canUse = quantity - lockedQuantity; const grossWeight = parseInt(stockWarehouse.gross_weight) || 0; storage = { id: stockWarehouse.id, + storeId: Number(stockWarehouse.store_id) || 0, + warehouseId: Number(stockWarehouse.warehouse_id) || 0, quantity, lockedQuantity, canUse, @@ -354,10 +366,15 @@ class stockStoreService extends Service { stock: { id: itemInfo.id, stock_id: itemInfo.stock_id, + store_id: storage && storage.storeId ? storage.storeId : undefined, + warehouse_id: storage && storage.warehouseId ? storage.warehouseId : undefined, warehouse_code: itemInfo.warehouse_code, item_code: itemInfo.item_code, }, storage, + allow_oversell: storage && storage.canUse <= 0 + ? (await this.getStoreWarehousePolicyConfigByStockId(itemInfo.stock_id, transaction)).allowOversell + : undefined, }, error: null, _fromCache: fromCache, @@ -386,7 +403,7 @@ class stockStoreService extends Service { return 5; // 无效库存缓存5秒 } - if (storage.canUse === 0) { + if (storage.canUse <= 0) { return 10; // 无库存缓存10秒 } @@ -439,6 +456,79 @@ class stockStoreService extends Service { } } + /** + * 获取库存对应的货主-仓库签约策略配置。 + * + * @param {number|Object} stockWarehouseId 库存 ID 或库存记录。 + * @param {Object|null} [transaction=null] 事务对象。 + * @return {Promise} 策略配置对象,包含 relation、policyConfig、allowOversell。 + */ + async getStoreWarehousePolicyConfigByStockId(stockWarehouseId, transaction = null) { + const { ctx } = this; + const stockRecord = stockWarehouseId && typeof stockWarehouseId === 'object' + ? stockWarehouseId + : await ctx.model.StockWarehouse.findOne({ + where: { + id: Number(stockWarehouseId || 0), + is_valid: 'Y', + deleted_at: null, + }, + attributes: [ 'id', 'store_id', 'warehouse_id', 'policy_config' ], + transaction, + raw: true, + }); + + const storeId = Number(stockRecord && stockRecord.store_id) || 0; + const warehouseId = Number(stockRecord && stockRecord.warehouse_id) || 0; + + if (storeId <= 0 || warehouseId <= 0) { + return { + relation: null, + policyConfig: null, + allowOversell: false, + }; + } + + const relation = await ctx.model.StoreWarehouse.findOne({ + where: { + store_id: storeId, + warehouse_id: warehouseId, + auth_status: 2, + use_status: 1, + }, + attributes: [ 'id', 'policy_config', 'auth_status', 'use_status' ], + transaction, + raw: true, + }); + + if (!relation) { + return { + relation: null, + policyConfig: null, + allowOversell: false, + }; + } + + const storeWarehouseService = ctx.service && ctx.service.systems && ctx.service.systems.storeWarehouse; + const policyConfig = storeWarehouseService && typeof storeWarehouseService.getEffectivePolicyConfigByContractId === 'function' + ? await storeWarehouseService.getEffectivePolicyConfigByContractId(relation.id, transaction) + : null; + + return { + relation, + policyConfig, + allowOversell: Number(policyConfig && policyConfig.allow_oversell) === 1, + }; + } + + /** + * 锁定或释放库存。 + * + * @param {number|string} stockWarehouseId 库存主键。 + * @param {number} quantity 锁定数量,负数表示释放。 + * @param {Object|null} transaction 数据库事务。 + * @return {Promise} 锁定结果。 + */ async lockItemStorages(stockWarehouseId, quantity, transaction) { const { ctx, @@ -468,6 +558,7 @@ class stockStoreService extends Service { }, transaction, lock: transaction.LOCK.UPDATE, // 行级锁 + attributes: [ 'id', 'store_id', 'warehouse_id', 'quantity', 'locked_quantity', 'gross_weight' ], raw: false, // 需要实例以使用方法 }); @@ -485,25 +576,18 @@ class stockStoreService extends Service { // 加锁操作:检查可用库存是否足够 const availableQty = stockRecord.quantity - stockRecord.locked_quantity; if (availableQty < absQty) { - return { - success: false, - error: `库存不足,可用 ${availableQty},需求 ${absQty}`, - data: { - available: availableQty, - required: absQty, - recordId: stockWarehouseId, - }, - }; - } - - // 检查锁定后是否会导致超卖 - const newLocked = stockRecord.locked_quantity + absQty; - if (newLocked > stockRecord.quantity) { - return { - success: false, - error: `锁定后会导致超卖,总库存 ${stockRecord.quantity},锁定后 ${newLocked}`, - data: null, - }; + const policyConfig = await this.getStoreWarehousePolicyConfigByStockId(stockRecord, transaction); + if (!policyConfig.allowOversell) { + return { + success: false, + error: `库存不足,可用 ${availableQty},需求 ${absQty}`, + data: { + available: availableQty, + required: absQty, + recordId: stockWarehouseId, + }, + }; + } } } else { // 减锁操作:检查已锁定库存是否足够释放 @@ -790,8 +874,11 @@ class stockStoreService extends Service { const beforeQuantity = Number(storage.quantity) || 0; const beforeLockedQuantity = Number(storage.lockedQuantity) || 0; - // 关键检查:总库存是否足够 - if (beforeQuantity < outboundQty) { + const policyConfig = await this.getStoreWarehousePolicyConfigByStockId(storage.id, currentTransaction); + const allowOversell = policyConfig.allowOversell === true; + + // 关键检查:总库存是否足够,启用超卖时放行负库存结果 + if (beforeQuantity < outboundQty && !allowOversell) { const failureResult = { success: false, error: `总库存不足,当前 ${beforeQuantity},需求 ${outboundQty}`, @@ -826,9 +913,6 @@ class stockStoreService extends Service { id: storage.id, is_valid: 'Y', deleted_at: null, - quantity: { - [app.Sequelize.Op.gte]: outboundQty, - }, locked_quantity: { [app.Sequelize.Op.gte]: outboundQty, }, diff --git a/app/service/systems/storage/receiving.js b/app/service/systems/storage/receiving.js index 847dfa7..cce6937 100644 --- a/app/service/systems/storage/receiving.js +++ b/app/service/systems/storage/receiving.js @@ -1313,13 +1313,6 @@ class ReceivingService extends Service { }; } - if (receivingDetail.receiving && receivingDetail.receiving.status !== 'receiving') { - return { - code: 400, - message: '收货单状态不允许绑定或改绑商品', - }; - } - const stockWarehouse = await app.model.StockWarehouse.findOne({ where: { id: systemProductId, @@ -1348,6 +1341,29 @@ class ReceivingService extends Service { } const productStoreId = Number(stockWarehouse.store_stock?.store_id || 0); + const receivingStoreId = Number(receivingDetail.receiving?.store_id || 0); + + // 货主校验:收货单已有货主时,只允许绑定同一货主的商品 + if (receivingStoreId > 0 && productStoreId > 0 && receivingStoreId !== productStoreId) { + return { + code: 400, + message: '该商品不属于当前收货单的货主,不允许绑定', + }; + } + + // 收货单无货主时,自动设置为当前商品的货主 + let autoBindStore = false; + if (receivingStoreId <= 0 && productStoreId > 0) { + const storeName = stockWarehouse.store_stock?.store_remask || null; + await app.model.Receiving.update({ + store_id: productStoreId, + store_name: storeName, + updated_at: new Date(), + }, { + where: { id: receivingDetail.receiving_id, warehouse_id: warehouseId }, + }); + autoBindStore = true; + } const barcodes = Array.isArray(stockWarehouse.barcodes) ? stockWarehouse.barcodes.map(item => item && item.barcode).filter(Boolean) @@ -1376,6 +1392,22 @@ class ReceivingService extends Service { }), }; + // 如果收货明细有条码且商品尚未包含该条码,则自动为商品新增条码 + const detailBarcode = String(receivingDetail.barcode || '').trim(); + if (detailBarcode && !barcodes.includes(detailBarcode)) { + try { + await app.model.StockBarcode.create({ + stock_id: systemProductId, + warehouse_id: warehouseId, + barcode: detailBarcode, + }); + barcodes.push(detailBarcode); + } catch (barcodeErr) { + // 唯一索引冲突说明条码已被其他商品占用,仅记录日志不阻断业务 + ctx.logger.warn('[receiving.bindDetailProduct] 自动新增条码失败(可能已存在)', barcodeErr); + } + } + if (barcodes.length > 0) { updateData.barcode = barcodes.join(';'); } @@ -1418,15 +1450,21 @@ class ReceivingService extends Service { ctx.logger.warn('[receiving.bindDetailProduct] 写入操作日志失败,不影响业务', logErr); } + const responseData = { + detail_id: detailId, + receiving_id: receivingDetail.receiving_id, + system_product_id: systemProductId, + product_name: productName, + }; + if (autoBindStore) { + responseData.auto_bind_store_id = productStoreId; + responseData.auto_bind_store_name = stockWarehouse.store_stock?.store_remask || null; + } + return { code: 200, - message: '绑定商品成功', - data: { - detail_id: detailId, - receiving_id: receivingDetail.receiving_id, - system_product_id: systemProductId, - product_name: productName, - }, + message: autoBindStore ? '绑定商品成功,已自动设置货主' : '绑定商品成功', + data: responseData, }; } catch (error) { ctx.logger.error('绑定收货单明细商品失败:', error); @@ -2571,7 +2609,7 @@ class ReceivingService extends Service { const receivingNumber = String(receiving.receiving_number || receiving.id).replace(/[\\/:*?"<>|]/g, '_'); return await excelService.generateAndUpload({ - filename: `收货完成_${receivingNumber}.xlsx`, + filename: `收货明细(已完成收货)_${receivingNumber}.xlsx`, dir: `exports/receiving/completed/${ctx.user.store_id || receiving.warehouse_id || 'common'}`, category: 'document', saveRecord: true, @@ -2649,7 +2687,7 @@ class ReceivingService extends Service { `开始时间:${this.formatReportDate(receiving.created_at)}`, `完成时间:${this.formatReportDate(receiving.receiving_end_time)}`, `备注:${receiving.remark || '无'}`, - + ].filter(Boolean).join('\n') + '。'; return await noticeService.send({ diff --git a/app/service/systems/store_warehouse.js b/app/service/systems/store_warehouse.js index 71e6cb8..61c15fb 100644 --- a/app/service/systems/store_warehouse.js +++ b/app/service/systems/store_warehouse.js @@ -385,6 +385,48 @@ class SettingStoreWarehouseService extends Service { await this.app.setCacheAsync(this.getPolicyConfigCacheKey(normalizedId), policyConfig, 86400 * 30); } + /** + * 获取策略配置默认值。 + * + * @return {Object} 策略配置默认值对象。 + */ + getPolicyConfigDefaults() { + return this.getPolicyConfigFieldList().reduce((result, field) => { + result[field.key] = field.default; + return result; + }, {}); + } + + /** + * 将策略配置与默认值合并。 + * + * @param {*} policyConfig 已保存的策略配置。 + * @return {Object} 合并后的策略配置对象。 + */ + mergePolicyConfigWithDefaults(policyConfig) { + const defaults = this.getPolicyConfigDefaults(); + if (!policyConfig || typeof policyConfig !== 'object') { + return defaults; + } + + return { + ...defaults, + ...policyConfig, + }; + } + + /** + * 按合同 ID 读取带默认值的策略配置。 + * + * @param {number|string} contractId 合同 ID。 + * @param {Object|null} [transaction=null] 事务对象。 + * @return {Promise} 带默认值的策略配置对象。 + */ + async getEffectivePolicyConfigByContractId(contractId, transaction = null) { + const policyConfig = await this.loadPolicyConfigByContractId(contractId, transaction); + return this.mergePolicyConfigWithDefaults(policyConfig); + } + /** * 校验当前主体是否为仓库主体。 * diff --git a/app/service/systems/upload.js b/app/service/systems/upload.js index c79f78d..2ddcb95 100644 --- a/app/service/systems/upload.js +++ b/app/service/systems/upload.js @@ -18,7 +18,7 @@ class UploadService extends Service { * 说明:优先读取独立的腾讯云公共配置,若不存在则回退到兼容的 COS 配置, * 以保证历史配置方式仍然可用。 * - * @returns {Object} 腾讯云公共配置对象 + * @return {Object} 腾讯云公共配置对象 */ getTencentCloudConfig() { const tencentCloudConfig = this.config.tencentCloud || {}; @@ -34,7 +34,7 @@ class UploadService extends Service { /** * 获取 COS 产品配置。 * - * @returns {Object} COS 产品配置对象 + * @return {Object} COS 产品配置对象 */ getCosConfig() { return this.config.cos || {}; diff --git a/config/config.default.js b/config/config.default.js index b9f1c46..dc88fe7 100644 --- a/config/config.default.js +++ b/config/config.default.js @@ -1,5 +1,9 @@ -/* - * @param {Egg.EggAppInfo} appInfo app info +const path = require('node:path'); + +/** + * 生成应用默认配置。 + * @param {Egg.EggAppInfo} appInfo 应用信息。 + * @return {Egg.EggAppConfig} 应用配置。 */ module.exports = appInfo => { /** @@ -65,6 +69,20 @@ module.exports = appInfo => { temp: '/temp/', // 临时文件目录 }, }; + config.fileWriter = { + baseDir: path.join(appInfo.baseDir, 'runtime', 'file-writer'), + maxFileSize: 100 * 1024 * 1024, + maxConsumeRecordsPerWindow: 1000, + maxConsumeRecordsPerRun: 1000, + writeWindowSeconds: 1, + maxWriteRecordsPerWindow: 1000, + retentionDays: 7, + cleanupIntervalMs: 60 * 60 * 1000, + sequenceWidth: 4, + stateMapMaxEntries: 256, + fileExtension: '.log', + progressExtension: '.progress', + }; config.fileTypes = { // 图片类型 image: 'image', diff --git a/database/migrations/20260410100000-alter-wms-stock-warehouse-negative-quantity.js b/database/migrations/20260410100000-alter-wms-stock-warehouse-negative-quantity.js new file mode 100644 index 0000000..da2ccf0 --- /dev/null +++ b/database/migrations/20260410100000-alter-wms-stock-warehouse-negative-quantity.js @@ -0,0 +1,81 @@ +'use strict'; + +async function getColumnType(queryInterface, tableName, columnName) { + const [ rows ] = await queryInterface.sequelize.query( + ` + SELECT COLUMN_TYPE + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = :tableName + AND COLUMN_NAME = :columnName + LIMIT 1 + `, + { + replacements: { + tableName, + columnName, + }, + } + ); + + return String(rows[0]?.COLUMN_TYPE || '').toLowerCase(); +} + +async function changeSignedQuantityColumns(queryInterface, Sequelize, direction) { + const tableName = 'wms_stock_warehouse'; + const quantityType = direction === 'up' + ? Sequelize.INTEGER(11) + : Sequelize.INTEGER(11).UNSIGNED; + + const lockedQuantityType = direction === 'up' + ? Sequelize.INTEGER(11) + : Sequelize.INTEGER(11).UNSIGNED; + + const quantityColumnType = await getColumnType(queryInterface, tableName, 'quantity').catch(() => ''); + if (direction === 'up' && quantityColumnType.includes('unsigned')) { + await queryInterface.changeColumn(tableName, 'quantity', { + type: quantityType, + allowNull: false, + defaultValue: 0, + comment: '库存数量', + }); + } + + const lockedColumnType = await getColumnType(queryInterface, tableName, 'locked_quantity').catch(() => ''); + if (direction === 'up' && lockedColumnType.includes('unsigned')) { + await queryInterface.changeColumn(tableName, 'locked_quantity', { + type: lockedQuantityType, + allowNull: false, + defaultValue: 0, + comment: '锁定数量', + }); + } + + if (direction === 'down' && !quantityColumnType.includes('unsigned')) { + await queryInterface.changeColumn(tableName, 'quantity', { + type: quantityType, + allowNull: false, + defaultValue: 0, + comment: '库存数量', + }); + } + + if (direction === 'down' && !lockedColumnType.includes('unsigned')) { + await queryInterface.changeColumn(tableName, 'locked_quantity', { + type: lockedQuantityType, + allowNull: false, + defaultValue: 0, + comment: '锁定数量', + }); + } +} + +module.exports = { + async up(queryInterface, Sequelize) { + await changeSignedQuantityColumns(queryInterface, Sequelize, 'up'); + }, + + async down(queryInterface, Sequelize) { + await changeSignedQuantityColumns(queryInterface, Sequelize, 'down'); + }, +}; diff --git a/database/migrations/20260410120000-add-log-id-to-qimen-log.js b/database/migrations/20260410120000-add-log-id-to-qimen-log.js new file mode 100644 index 0000000..f068cda --- /dev/null +++ b/database/migrations/20260410120000-add-log-id-to-qimen-log.js @@ -0,0 +1,32 @@ +'use strict'; + +module.exports = { + async up(queryInterface) { + const [ columns ] = await queryInterface.sequelize.query('SHOW COLUMNS FROM `wms_qimen_log` LIKE \'log_id\''); + if (columns.length > 0) { + const [ idxs ] = await queryInterface.sequelize.query('SHOW INDEX FROM `wms_qimen_log` WHERE Key_name = \'idx_log_id\''); + if (idxs.length === 0) { + await queryInterface.sequelize.query('ALTER TABLE `wms_qimen_log` ADD UNIQUE INDEX `idx_log_id` (`log_id`)'); + } + return; + } + + await queryInterface.sequelize.query('ALTER TABLE `wms_qimen_log` ADD COLUMN `log_id` VARCHAR(32) DEFAULT NULL AFTER `id`'); + const [ idxs2 ] = await queryInterface.sequelize.query('SHOW INDEX FROM `wms_qimen_log` WHERE Key_name = \'idx_log_id\''); + if (idxs2.length === 0) { + await queryInterface.sequelize.query('ALTER TABLE `wms_qimen_log` ADD UNIQUE INDEX `idx_log_id` (`log_id`)'); + } + }, + + async down(queryInterface) { + const [ indexes ] = await queryInterface.sequelize.query('SHOW INDEX FROM `wms_qimen_log` WHERE Key_name = \'idx_log_id\''); + if (indexes.length > 0) { + await queryInterface.sequelize.query('ALTER TABLE `wms_qimen_log` DROP INDEX `idx_log_id`'); + } + + const [ columns ] = await queryInterface.sequelize.query('SHOW COLUMNS FROM `wms_qimen_log` LIKE \'log_id\''); + if (columns.length > 0) { + await queryInterface.sequelize.query('ALTER TABLE `wms_qimen_log` DROP COLUMN `log_id`'); + } + }, +}; diff --git a/database/migrations/20260410130000-add-audit-status-to-order-delivery-tables.js b/database/migrations/20260410130000-add-audit-status-to-order-delivery-tables.js new file mode 100644 index 0000000..6f06972 --- /dev/null +++ b/database/migrations/20260410130000-add-audit-status-to-order-delivery-tables.js @@ -0,0 +1,88 @@ +'use strict'; + +module.exports = { + /** + * 为发货单主表及分表新增 audit_status 字段。 + * 若存在 inspection_status,则将 audit_status 放在其后;否则按默认位置新增,保证兼容旧库结构。 + * @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口 + * @returns {Promise} 无返回值 + */ + async up(queryInterface) { + const [ tables ] = await queryInterface.sequelize.query(` + SELECT TABLE_NAME + FROM INFORMATION_SCHEMA.TABLES + WHERE TABLE_SCHEMA = DATABASE() + AND (TABLE_NAME = 'wms_order_delivery' OR TABLE_NAME LIKE 'wms_order_delivery\\_%') + `); + + for (const row of tables) { + const tableName = row.TABLE_NAME; + + const [ columns ] = await queryInterface.sequelize.query( + ` + SELECT COLUMN_NAME + FROM INFORMATION_SCHEMA.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = :tableName + AND COLUMN_NAME = 'audit_status' + `, + { replacements: { tableName } } + ); + + if (columns.length === 0) { + const [ inspectionColumns ] = await queryInterface.sequelize.query( + ` + SELECT COLUMN_NAME + FROM INFORMATION_SCHEMA.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = :tableName + AND COLUMN_NAME = 'inspection_status' + `, + { replacements: { tableName } } + ); + + const alterSql = inspectionColumns.length > 0 + ? `ALTER TABLE \`${tableName}\` ADD COLUMN \`audit_status\` enum('pending','approved','rejected') DEFAULT 'pending' COMMENT '审批状态' AFTER \`inspection_status\`` + : `ALTER TABLE \`${tableName}\` ADD COLUMN \`audit_status\` enum('pending','approved','rejected') DEFAULT 'pending' COMMENT '审批状态'`; + + await queryInterface.sequelize.query(alterSql); + } + } + }, + + /** + * 回滚删除发货单主表及分表的 audit_status 字段。 + * 仅在字段存在时删除,保证回滚幂等且安全。 + * @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口 + * @returns {Promise} 无返回值 + */ + async down(queryInterface) { + const [ tables ] = await queryInterface.sequelize.query(` + SELECT TABLE_NAME + FROM INFORMATION_SCHEMA.TABLES + WHERE TABLE_SCHEMA = DATABASE() + AND (TABLE_NAME = 'wms_order_delivery' OR TABLE_NAME LIKE 'wms_order_delivery\\_%') + `); + + for (const row of tables) { + const tableName = row.TABLE_NAME; + + const [ columns ] = await queryInterface.sequelize.query( + ` + SELECT COLUMN_NAME + FROM INFORMATION_SCHEMA.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = :tableName + AND COLUMN_NAME = 'audit_status' + `, + { replacements: { tableName } } + ); + + if (columns.length > 0) { + await queryInterface.sequelize.query( + `ALTER TABLE \`${tableName}\` DROP COLUMN \`audit_status\`` + ); + } + } + }, +}; \ No newline at end of file diff --git a/database/migrations/20260410150000-replace-audit-status-with-step-on-order-delivery-tables.js b/database/migrations/20260410150000-replace-audit-status-with-step-on-order-delivery-tables.js new file mode 100644 index 0000000..d6955a0 --- /dev/null +++ b/database/migrations/20260410150000-replace-audit-status-with-step-on-order-delivery-tables.js @@ -0,0 +1,122 @@ +'use strict'; + +const STEP_COMMENT = '订单步骤:0未审核,1已审核,2处理中,3驳回/异常,4配送中,5已完成,9已关闭'; +const AUDIT_STATUS_COMMENT = '审批状态'; + +/** + * 判断数据表是否存在指定字段。 + * + * @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。 + * @param {string} tableName 数据表名。 + * @param {string} columnName 字段名。 + * @return {Promise} 是否存在。 + */ +async function hasColumn(queryInterface, tableName, columnName) { + const [ columns ] = await queryInterface.sequelize.query( + ` + SELECT COLUMN_NAME + FROM INFORMATION_SCHEMA.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = :tableName + AND COLUMN_NAME = :columnName + `, + { replacements: { tableName, columnName } } + ); + + return columns.length > 0; +} + +/** + * 查找发货单主表及分表。 + * + * @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。 + * @return {Promise} 表名列表。 + */ +async function findOrderDeliveryTables(queryInterface) { + const [ tables ] = await queryInterface.sequelize.query(` + SELECT TABLE_NAME + FROM INFORMATION_SCHEMA.TABLES + WHERE TABLE_SCHEMA = DATABASE() + AND (TABLE_NAME = 'wms_order_delivery' OR TABLE_NAME LIKE 'wms_order_delivery\\_%') + `); + + return tables.map(row => row.TABLE_NAME); +} + +module.exports = { + /** + * 为发货单主表及分表新增 step 字段,并从 audit_status 回填后删除 audit_status。 + * + * @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。 + * @returns {Promise} 无返回值。 + */ + async up(queryInterface) { + const tables = await findOrderDeliveryTables(queryInterface); + + for (const tableName of tables) { + const hasStep = await hasColumn(queryInterface, tableName, 'step'); + const hasAuditStatus = await hasColumn(queryInterface, tableName, 'audit_status'); + + if (!hasStep) { + const hasInspectionStatus = await hasColumn(queryInterface, tableName, 'inspection_status'); + const addStepSql = hasInspectionStatus + ? `ALTER TABLE \`${tableName}\` ADD COLUMN \`step\` int(10) NOT NULL DEFAULT 0 COMMENT '${STEP_COMMENT}' AFTER \`inspection_status\`` + : `ALTER TABLE \`${tableName}\` ADD COLUMN \`step\` int(10) NOT NULL DEFAULT 0 COMMENT '${STEP_COMMENT}'`; + await queryInterface.sequelize.query(addStepSql); + } + + if (hasAuditStatus) { + await queryInterface.sequelize.query(` + UPDATE \`${tableName}\` + SET \`step\` = CASE \`audit_status\` + WHEN 'approved' THEN 1 + WHEN 'rejected' THEN 3 + ELSE 0 + END + `); + + await queryInterface.sequelize.query( + `ALTER TABLE \`${tableName}\` DROP COLUMN \`audit_status\`` + ); + } + } + }, + + /** + * 回滚恢复 audit_status 字段,并根据 step 回填后删除 step。 + * + * @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。 + * @returns {Promise} 无返回值。 + */ + async down(queryInterface) { + const tables = await findOrderDeliveryTables(queryInterface); + + for (const tableName of tables) { + const hasStep = await hasColumn(queryInterface, tableName, 'step'); + const hasAuditStatus = await hasColumn(queryInterface, tableName, 'audit_status'); + + if (!hasAuditStatus) { + const hasInspectionStatus = await hasColumn(queryInterface, tableName, 'inspection_status'); + const addAuditStatusSql = hasInspectionStatus + ? `ALTER TABLE \`${tableName}\` ADD COLUMN \`audit_status\` enum('pending','approved','rejected') DEFAULT 'pending' COMMENT '${AUDIT_STATUS_COMMENT}' AFTER \`inspection_status\`` + : `ALTER TABLE \`${tableName}\` ADD COLUMN \`audit_status\` enum('pending','approved','rejected') DEFAULT 'pending' COMMENT '${AUDIT_STATUS_COMMENT}'`; + await queryInterface.sequelize.query(addAuditStatusSql); + } + + if (hasStep) { + await queryInterface.sequelize.query(` + UPDATE \`${tableName}\` + SET \`audit_status\` = CASE + WHEN \`step\` = 1 THEN 'approved' + WHEN \`step\` = 3 THEN 'rejected' + ELSE 'pending' + END + `); + + await queryInterface.sequelize.query( + `ALTER TABLE \`${tableName}\` DROP COLUMN \`step\`` + ); + } + } + }, +}; diff --git a/docs/file-writer.md b/docs/file-writer.md new file mode 100644 index 0000000..4528ab9 --- /dev/null +++ b/docs/file-writer.md @@ -0,0 +1,119 @@ +# 本地文件队列(app.fileWriter) + +本文档说明仓库中提供的本地文件队列写入能力(实现文件:app/lib/file_writer.js),用于把业务数据按 JSON Lines 追加到本地文件并由消费者按需读取处理,适合低延迟、本地持久化、批处理/异步消费场景。 + +**实现要点(写入特性)** +- 串行写入:同一进程内通过内部队列 `enqueue` 串行化写入,保证单进程内顺序性。 +- 强制落盘:每次写入使用文件句柄写入并调用 `handle.sync()` 进行 fsync,尽量保证数据落盘。 +- 自动轮转:当当前文件大小 + 待写入字节数 超过 `maxFileSize` 时,会自增序号并切换到新文件(sequence)。 +- 目录结构:默认 baseDir 下按业务与日期分区: + - baseDir////
/ +- 文件命名:文件前缀包含业务段与进程标识(`---p-`),尾部带序号与扩展名(`fileExtension`,默认 `.log`)。 +- 进度(.progress)断点续传:每个消费者使用独立的隐藏进度文件(以 `..progress` 命名),写入采用临时文件+rename 的原子替换策略,消费端可通过进度恢复消费位置。 +- Worker/进程隔离:写入文件名包含 `machineId`、`workerId` 与 `pid`,不同进程不会写入同一文件,避免互相竞争。 +- 清理策略:基于 `retentionDays` 定期删除过期的数据文件与进度文件。 + +**目录与文件示例** +- 目录:`/path/to/runtime/file-writer/orders/2026/04/09/` +- 数据文件示例:`orders-myhost-worker1-p1234-0001.log` +- 进度文件示例:`.consumer-1.progress`(位于同一分区目录下) + +**配置项说明(config.fileWriter)** +- `baseDir`:基础目录,默认 `path.join(app.baseDir, 'runtime', 'file-writer')`。 +- `maxFileSize`:单文件最大字节数,超过后轮转。支持数字(字节)或带单位字符串(如 `100M`、`1G`)。默认 `100 * 1024 * 1024`(100MB)。 +- `retentionDays`:保留天数,超过则删除。设为 `0` 或负值可禁用清理。默认 `7`。 +- `cleanupIntervalMs`:触发清理的最小间隔(毫秒),写入时会基于此决定是否执行清理,设置为 `0` 或负值可禁用定期清理。默认 `3600000`(1 小时)。 +- `sequenceWidth`:文件序号宽度(零填充),默认 `4`(例如 `0001`)。 +- `fileExtension`:数据文件扩展名,默认 `.log`。 +- `progressExtension`:进度文件扩展名,默认 `.progress`。 +- `machineId`、`workerId`(可选):可通过配置覆盖,默认使用主机名与 `process.env.EGG_WORKER_ID`。 + +默认配置位置:`config/config.default.js` 的 `config.fileWriter` 节点。 + +示例(可放入 `config/config.local.js` 覆盖默认): + +```js +const path = require('path'); + +exports.fileWriter = { + baseDir: path.join(__dirname, '..', 'runtime', 'file-writer'), + maxFileSize: '200M', + retentionDays: 14, + cleanupIntervalMs: 60 * 60 * 1000, + sequenceWidth: 4, + fileExtension: '.log', + progressExtension: '.progress', + // machineId: 'my-host', + // workerId: 'worker-1', +}; +``` + +**写入示例(业务侧)** +简单写入(在任何可以访问 `app` 的位置): + +```js +// 在 controller/service 中 +await app.fileWriter.write('orders', { id: 123, event: 'created', payload: { /* ... */ } }); +// 返回对象包含 filePath、sequence、bytesWritten 等信息 +``` + +**消费/读取示例(推荐使用 app.fileWriter 提供的 API)** +推荐使用 `getProgressFilePath` + `consumeFiles` 提供的断点续传能力: + +```js +// 示例:定期或守护进程式消费 orders +async function consumeOrders(app) { + const writer = app.fileWriter; + const progressFile = writer.getProgressFilePath('orders', new Date(), 'order-consumer-1'); + + const result = await writer.consumeFiles({ + businessName: 'orders', + progressFilePath: progressFile, + onRecord: async (record, meta) => { + // record: 解析后的对象 + // meta: { filePath, offset, index } + // 在这里实现消息处理逻辑(去重、入库、调用外部服务等) + }, + parseJson: true, + }); + + return result; // 包含 processedCount 与最新 progress +} +``` + +如需逐文件手动控制消费,也可使用 `readRecords`: + +```js +const res = await app.fileWriter.readRecords(filePath, { startOffset: 0 }); +for (const rec of res.records) { + // 处理 rec +} +// 手动保存进度 +await app.fileWriter.saveProgress(progressFilePath, { + filePath, + offset: res.nextOffset, + processedCount: (previousCount || 0) + res.records.length, +}); +``` + +**进度文件(.progress)格式** +- 保存为 JSON,包含至少字段:`filePath`、`offset`、`processedCount`、`updatedAt`。 +- 写入采用临时文件写入 + `fsync` + `rename` 的方式尽量保证原子性。 + +**注意事项 / 运行时建议** +- 不要通过静态文件服务或外部 URL 直接暴露 `baseDir`(例如 `runtime/`),避免被外部下载或篡改。 +- 多 Worker / 多机部署: + - 默认每个进程生成独立的数据文件(文件名包含 `machineId`、`workerId`、`pid`),不会有多个进程同时写入同一文件。若你的设计需要跨进程全局严格顺序,请在上游统一入口合并写入或使用集中式队列(如 Kafka/Redis)。 + - 消费者可以按进程拆分(针对单进程的文件)或由独立中心消费者按文件目录遍历处理。 + - 可通过配置显式设置 `machineId`/`workerId` 来标识不同实例。 +- 关闭或调整清理策略:若需长期保留数据,请将 `retentionDays` 设为合适值或禁用清理(`0` 或负值)。 +- 性能角度:每次写入触发 fsync 会有性能开销,适合需要高可靠性的场景;若对持久性要求不高,可考虑将写入逻辑改为批量 fsync(此处为实现约束,不建议直接修改核心行为)。 + +--- + +如果希望在项目首页或工具箱中添加跳转链接,建议把一行链接加入到 [README.md](README.md) 或 [AI_TOOLBOX.md](AI_TOOLBOX.md) 的相关位置,指向本文件 `docs/file-writer.md`。 + +---- +**参考实现位置** +- 代码实现:app/lib/file_writer.js +- 默认配置:config/config.default.js -> `config.fileWriter` diff --git a/methods/changes/system.json b/methods/changes/system.json index b223a47..f94cafc 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -2,7 +2,7 @@ { "version": "2026.04.07-system-01", "date": "2026-04-07", - "summary": "修正 warehouse.getAreaRacks 的鉴权/权限链路文档,明确该接口需要登录并走权限校验。", + "summary": "修正 warehouse.getAreaRacks 的鉴权/权限链路文档,明确该接口需要 登录并走权限校验。", "methods": [ "warehouse.getAreaRacks" ], @@ -11,308 +11,434 @@ "用于补充该接口权限链路修正文档的历史上下文,不改变 methods/system.json 的 SSOT 角色。" ] }, - { - "version": "2026.04.07-system-02", - "date": "2026-04-07", - "summary": "补充签约配置相关接口文档,覆盖策略字段元信息查询与面单数量人工调整。", - "methods": [ - "storeWarehouse.store.getPolicyConfigFields", - "storeWarehouse.store.adjustPrintQuantity" - ], - "notes": [ - "getPolicyConfigFields 说明为获取签约策略可配置字段元信息列表。", - "adjustPrintQuantity 说明为人工调整签约关系下的面单余额并记录变更日志,并明确 id、change_quantity、reason 等关键入参。" - ] - }, - { - "version": "2026.04.07-system-03", - "date": "2026-04-07", - "summary": "对外命名从 qimenConfig 收口为 apiConfig,并在接口配置文档中强调 interface_type_id 校验。", - "methods": [ - "storeWarehouse.store.listApiConfig", - "storeWarehouse.store.saveApiConfig", - "storeWarehouse.store.deleteQimenConfig" - ], - "notes": [ - "文档对外统一使用 apiConfig / api_config 命名,减少 qimenConfig 历史别名歧义。", - "saveApiConfig 要求 interface_type_id 为必填且必须指向已存在的 wms_interface_type 记录。", - "listApiConfig / deleteQimenConfig 同步补充 interface_type_id 字段说明。" - ] - }, - { - "version": "2026.04.07-system-04", - "date": "2026-04-07", - "summary": "补充 /api/docs 文档体验增强说明,新增查看变更记录与查看原文 JSON 的入口说明。", - "methods": [ - "/api/docs", - "/api/docs/:docName", - "/api/docs/:docName/raw", - "/api/docs/:docName/changes" - ], - "notes": [ - "sidecar 变更数组用于承载文档历史说明,不替代 methods/system.json 作为 SSOT。", - "原文 JSON 入口继续用于直接查看当前生效文档。" - ] - }, - { - "version": "2026.04.07-system-05", - "date": "2026-04-07", - "summary": "修正 storeWarehouse.store.adjustPrintQuantity 的面单余额调整语义:由增减/累加改为覆盖设置目标余额。", - "methods": [ - "storeWarehouse.store.adjustPrintQuantity" - ], - "notes": [ - "adjustPrintQuantity 当前兼容 print_quantity、target_quantity、change_quantity、adjust_quantity 作为目标面单余额输入,不再按增减量解释。", - "变更日志中的 change_quantity 由 before/after 自动计算差值,以兼容历史审计与展示。" - ] - }, - { - "id": "2026.04.07-system-06", - "date": "2026-04-07", - "method": "storeWarehouse.store.saveApiConfig", - "type": "changed", - "summary": "按接口类型分类限制必填字段,OPEN_API 创建时自动生成 self_app_key/self_app_secret", - "detail": "QM_WMS 类型须填写 qimen_app_key/qimen_customer_id/qimen_warehouse_code;OPEN_API 类型三个奇门字段非必填,创建时自动生成 self_app_key(WMS+32位HEX)和 self_app_secret(64位HEX),更新时保留已有密钥。" - }, - { - "id": "2026.04.07-system-07", - "date": "2026-04-07", - "method": "index.listInterfaceTypes", - "type": "added", - "summary": "新增接口类型列表查询接口,归属基础模块,无需权限", - "detail": "返回所有已启用的接口类型(wms_interface_type),包含 id、interface_code、interface_name、interface_category、description 字段。设置 isNeedAuth: false, isNeedLogin: true。" - }, - { - "id": "2026.04.07-system-08", - "date": "2026-04-07", - "method": "storeWarehouse.store.saveApiConfig", - "type": "changed", - "summary": "app_name 改为必传参数", - "detail": "app_name 不再有默认值自动生成逻辑,调用方必须传入非空的 app_name,否则返回 400 错误。" - }, - { - "id": "2026.04.07-system-09", - "date": "2026-04-07", - "method": "storage.inventory.quickPutaway", - "type": "added", - "summary": "新增收货单快捷入库上架接口", - "detail": "新建 storage.inventory 库存操作模块。quickPutaway 从收货单直接生成入库单(SCRK)并写入 wms_storage 库存表,同时更新 wms_stock_warehouse 库存数量(悲观行锁),回填收货明细入库状态。要求收货单已完成且所有明细已匹配系统商品。" - }, - { - "id": "2026.04.08-system-01", - "date": "2026-04-08", - "method": "storage.inventory.matchPutaway", - "type": "added", - "summary": "新增收货单与入库单匹配入库接口", - "detail": "接收多个收货单和入库单,按商品(stock_warehouse_id)进行数量匹配入库,完成后根据入库单来源(QM/API)自动触发回传。入参为 receiving_ids(数组)和 entry_order_ids(数组),返回匹配汇总、各收货单入库状态、各入库单状态及回传结果。isNeedAuth=true, isNeedLogin=true, isNeedRight=false。" - }, - { - "id": "2026.04.08-system-02", - "date": "2026-04-08", - "method": "storeWarehouse.store.saveApiConfig", - "type": "changed", - "summary": "saveApiConfig 新增 callback_url 可选参数", - "detail": "新增 callback_url 参数(VARCHAR(500),可选),用于 OPEN_API 类型入库单的回调地址配置。" - }, - { - "id": "2026.04.08-system-03", - "date": "2026-04-08", - "method": "storeWarehouse.store.list, storeWarehouse.store.listApiConfig", - "type": "changed", - "summary": "serializeQimenConfig 新增返回 callback_url 字段,影响 list 和 listApiConfig 两个接口", - "detail": "serializeQimenConfig() 序列化方法新增 callback_url(string)字段。storeWarehouse.store.list 返回的每条记录 api_config 对象中包含 callback_url;storeWarehouse.store.listApiConfig 返回的 list 数组中每条配置包含 callback_url。" - }, - { - "id": "2026.04.08-system-04", - "date": "2026-04-08", - "method": "storage.inventory.transferLocation", - "type": "added", - "summary": "新增库存移库(库位转移)接口", - "detail": "新增 storage.inventory.transferLocation 接口,支持批量多商品多库位移库,包含部分数量移库与全量移库。入参为 warehouse_id(仓库ID)和 transfers 数组(storage_id、target_space_id、quantity),触发 storage_transfer_completed 通知事件,每条移库记录独立操作日志。isNeedAuth=true, isNeedLogin=true。" - }, - { - "id": "2026.04.08-system-05", - "date": "2026-04-08", - "method": "storage.inventory.transferLocation", - "type": "modified", - "summary": "简化移库接口入参,从批量 transfers 数组改为单条移库", - "detail": "移除 warehouse_id 和 transfers 数组入参,改为扁平的 storage_id + target_space_id + quantity 三个顶层参数。warehouse_id 从库存记录自动获取,接口从批量移库简化为单商品单库位移库。响应结构同步简化为单条结果对象。" - }, - { - "id": "2026.04.08-system-06", - "date": "2026-04-08", - "method": "stock.warehouse.getStockDetail", - "type": "added", - "summary": "新增商品库存明细查询接口", - "detail": "新增 stock.warehouse.getStockDetail 接口,按库位/批次维度查询商品库存分布。入参为 stock_id(必填,商品库存ID)和 pagination(可选,含 page/pageSize)。返回 stockItem(商品概要)、storageList(wms_storage 明细数组,含批次号、库位、数量、锁定数量、生产日期、过期日期等,关联 location_space 库位信息)、pagination 分页信息。isNeedAuth=false, isNeedLogin=true。底层调用 stockStore.getStockDetail,自动校验商品归属当前仓库。" - }, - { - "id": "2026.04.08-system-07", - "date": "2026-04-08", - "method": "stock.warehouse.getStockDetail", - "type": "modified", - "summary": "新增入参 group_by_batch,支持按批次维度切换库存明细聚合方式", - "detail": "新增可选布尔参数 group_by_batch(默认 false)。false 时按库位合并数量,批次相关字段(batch_no, production_date, expiry_date, inbound_time, inbound_order_no, supplier_batch_no)置 null;true 时保持原逻辑返回每条明细。出参结构不变,但 storageList 中批次字段在合并模式下为 null。" - }, - { - "id": "2026.04.08-system-08", - "date": "2026-04-08", - "method": "storage.inventory.transferByProduct", - "type": "added", - "summary": "新增按商品维度移库接口", - "detail": "新增 storage.inventory.transferByProduct 接口,按库位+商品查找所有库存记录合并移动。入参为 space_id(原库位ID)、stock_id(商品SKU ID,即 wms_stock_warehouse.id)、target_space_id(目标库位ID)、quantity(移库数量)。开启批次管理(is_batch_mgmt=Y)的商品会被拒绝,需使用 transferLocation 按库存记录精确移库。复用 storage_transfer_completed 通知事件,操作日志编码 STORAGE_TRANSFER_BY_PRODUCT。isNeedAuth=true, isNeedLogin=true。" - }, - { - "id": "2026.04.08-system-09", - "date": "2026-04-08", - "method": "storeWarehouse.store.list", - "type": "updated", - "summary": "补充 storeWarehouse.store.list 完整 response 输出字段说明,移除 api_config / apiConfig", - "detail": "从返回结果中移除 api_config 和 apiConfig 字段(代码中 delete serialized.api_config / delete serialized.apiConfig),文档 response 补充完整输出字段列表:id, store_id, store_name, warehouse_id, warehouse_name, counterparty_id, counterparty_name, current_subject_role, auth_status, auth_status_label, apply_reason, review_comment, apply_time, review_time, auth_start, auth_end, actual_end, print_quantity, applied_by, reviewed_by, ended_by, remask, use_status, policy_config, is_auth_valid, remaining_days 以及分页和 current_subject 信息。" - }, - { - "id": "2026.04.08-system-10", - "date": "2026-04-08", - "method": "storeWarehouse.store.list", - "type": "changed", - "summary": "货主列表返回新增 has_qimen_config 布尔字段", - "detail": "storeWarehouse.store.list 返回的 data.list[] 中新增 has_qimen_config(boolean),表示该货主是否已配置奇门。" - }, - { - "id": "2026.04.08-system-11", - "date": "2026-04-08", - "method": "stock.warehouse.search", - "type": "updated", - "summary": "补全 stock.warehouse.search 接口文档,新增 params / response / errors 完整说明", - "detail": "入参补充 keyword(string,模糊匹配 item_code / item_name / goods_code / barcode)和 store_id(number,按货主筛选)。响应补充 data 数组各字段(id, item_code, goods_code, item_name, sku_property, stock_unit, quantity, locked_quantity, brand_name, item_type, barcodes, store_stock)以及 total。errors 补充 code=0 搜索失败场景。" - }, - { - "id": "2026.04.08-system-12", - "date": "2026-04-08", - "method": "stock.warehouse.search", - "type": "updated", - "summary": "新增 with_stock / is_batch 参数,支持返回关联库存明细(按库位分组或按批次逐条)", - "detail": "入参新增 with_stock(boolean,默认 false,是否返回关联库存数据)和 is_batch(boolean,默认 false,仅 with_stock=true 时生效,按批次明细返回)。响应 data[] 新增 storage[] 字段:is_batch=false 时按库位分组汇总(含 space_id、space、inventory_type、quantity、locked_quantity、available_quantity);is_batch=true 时逐条返回批次明细(含 id、stock_id、space_id、batch_no、inventory_type、quantity、locked_quantity、available_quantity、production_date、expiry_date、inbound_time、inbound_order_no、supplier_batch_no、created_at、space)。" - }, - { - "id": "2026.04.08-system-13", - "date": "2026-04-08", - "method": "wms_stock_transaction", - "type": "added", - "summary": "新增 wms_stock_transaction 表和模型", - "detail": "新增出入库流水记录表 wms_stock_transaction,含 transaction_type(INBOUND/OUTBOUND)、warehouse_id、store_id、stock_id、storage_id、space_id、quantity、batch_no、inventory_type、order_type、order_no、order_id、receiving_id、entry_order_id、operator_id、operator_name、remark 等字段,关联 StockWarehouse 和 Storage 模型。" - }, - { - "id": "2026.04.08-system-14", - "date": "2026-04-08", - "method": "storage.inventory.quickPutaway,storage.inventory.matchPutaway", - "type": "updated", - "summary": "quickPutaway 和 matchPutaway 入库时自动写入出入库记录", - "detail": "入库操作完成后自动写入 wms_stock_transaction 记录。quickPutaway 写入 order_type='SCRK'(收货入库),matchPutaway 写入 order_type='MATCH'(匹配入库),均自动填充 warehouse_id、store_id、stock_id、storage_id、space_id、quantity、batch_no、inventory_type 等字段。" - }, - { - "id": "2026.04.08-system-15", - "date": "2026-04-08", - "method": "storage.inventory.list", - "type": "added", - "summary": "新增 storage.inventory.list 出入库记录列表查询接口", - "detail": "出入库记录列表查询,支持 where 条件(transaction_type、stock_id、space_id、store_id、order_type、order_no、inventory_type、operator_name、created_at)、分页(pagination)、排序(sort)和 group_by_batch 参数。默认合并模式按库位+商品聚合返回合计数量与记录条数,group_by_batch=true 时返回每条明细含 batch_no、order_no、operator_name 等完整信息。响应均关联 stockItem(item_code、item_name、sku_property、stock_unit)。" - }, - { - "id": "2026.04.08-system-16", - "date": "2026-04-08", - "module": "storage", - "method": "storage.transaction.list", - "type": "rename", - "summary": "出入库流水记录查询接口从 storage.inventory.list 改名为 storage.transaction.list", - "detail": "将出入库流水记录查询从 storage.inventory.list 迁移到 storage.transaction.list,避免与库存列表概念混淆。功能和参数不变。isNeedAuth=false, isNeedLogin=true, isNeedRight=false。" - }, - { - "id": "2026.04.08-system-17", - "date": "2026-04-08", - "module": "storage", - "method": "storage.inventory.list", - "type": "add", - "summary": "新增 storage.inventory.list 库存列表查询接口", - "detail": "新增库存列表查询接口,查询 wms_storage 表。支持 where 条件(stock_id/space_id/store_id/inventory_type/batch_no/inbound_order_no/available_quantity/inbound_time/created_at)、分页、排序。支持 group_by_batch 参数:默认 false 按库位+商品合并(SUM quantity/locked_quantity/available_quantity),true 返回每条明细含 batch_no/production_date/expiry_date 等。关联 stockItem(商品信息)和 space(库位信息)。isNeedAuth=false, isNeedLogin=true, isNeedRight=false。" - }, - { - "id": "2026.04.08-system-18", - "date": "2026-04-08", - "module": "storage", - "method": "storage.entry.create", - "type": "remove", - "summary": "移除 storage.entry.create 创建入库单接口", - "detail": "不再允许通过 API 创建入库单。入库单仅由快捷入库(quickPutaway)和匹配入库(matchPutaway)等内部流程自动创建。底层 service 实现保留但不再通过 systemMethods 暴露。" - }, - { - "id": "2026.04.08-system-19", - "date": "2026-04-08", - "module": "storage", - "method": "storage.entry.addDetail, storage.entry.deleteDetail, storage.entry.detailChange", - "type": "remove", - "summary": "移除 storage.entry.addDetail / deleteDetail / detailChange 对外接口", - "detail": "入库单明细编辑能力不再通过 systemMethods 对外暴露,入库单模块仅保留 list/get/cancel/completeEntry。" - }, - { - "id": "2026.04.08-system-20", - "date": "2026-04-08", - "module": "storage", - "method": "storage.stockout.list, storage.stockout.toOrder, storage.stockout.listItems", - "type": "add", - "summary": "新增 storage.stockout 出库单模块(非订单出库单能力)", - "detail": "新增 storage.stockout.list / toOrder / listItems 接口,作为非订单出库单的主出口(对应奇门 stockout.create)。storage.delivery.* 仅作为兼容转发保留;底层部分能力仍复用 order 模块。" - }, - { - "id": "2026.04.08-system-21", - "date": "2026-04-08", - "method": "storage.stockout.toOrder", - "type": "change", - "summary": "将 storage.stockout.toOrder 标记为占位接口", - "detail": "storage.stockout.toOrder 当前仅保留方法名用于后续扩展,暂不开放实际逻辑。调用时返回 code=405、message=占位接口,暂未开放。" - } - , - { - "version": "2026.04.09-system-01", - "date": "2026-04-09", - "summary": "storage.entry.cancel 支持批量作废,新增 ids 入参并兼容单条 id", - "methods": [ - "storage.entry.cancel" - ], - "notes": [ - "新增入参 `ids`(number[])以支持批量作废,兼容旧入参 `id`;当同时传入 `ids` 与 `id` 时以 `ids` 为准。", - "参数校验:`ids` 必须为非空数组;非法 ID 或空数组返回 400。", - "业务约束:已完成/已作废/处于不可作废状态的单据不允许作废;批量场景下任一单据不存在或状态不允许时整体返回 404/400,未执行部分更新。", - "响应说明:单条作废返回字段 `id`(number);批量作废返回字段 `ids`(number[])。", - "已同步更新 methods/system.json(storage.entry.cancel)为 SSOT。" - ] - } - , - { - "id": "2026.04.09-system-02", - "date": "2026-04-09", - "method": "index.recognizeLicensePlate", - "type": "added", - "summary": "新增基础模块车牌识别接口 index.recognizeLicensePlate", - "detail": "新增 recognizeLicensePlate 方法,归属基础模块(index),接收 base64 图片(字段 base64/ imageBase64/ image_base64),返回识别结果包含 licensePlate, plateNumber, color, confidence, requestId, imageSize, rawData。isNeedAuth=false, isNeedLogin=true。", - "notes": [ - "入参:base64(string,必填)或 imageBase64/image_base64(兼容)", - "响应:返回归一化后的识别对象,包含 licensePlate、plateNumber、color、confidence、requestId、imageSize、rawData", - "错误:400(参数或图片格式/尺寸问题),500(第三方 OCR 调用失败或云密钥未配置)", - "文档中不包含任何敏感配置;实际腾讯云密钥保留在配置文件中,勿在文档中暴露。" - ] - }, - { - "id": "2026.04.09-system-03", - "date": "2026-04-09", - "method": "index.recognizeLicensePlate", - "type": "changed", - "summary": "收紧基础模块车牌识别接口响应,仅返回 licensePlate 字段", - "detail": "为简化对外契约,index.recognizeLicensePlate 的响应已从包含 licensePlate、plateNumber、color、confidence、requestId、imageSize、rawData 调整为仅包含 licensePlate。isNeedAuth=false, isNeedLogin=true。", - "notes": [ - "出参由 {licensePlate, plateNumber, color, confidence, requestId, imageSize, rawData} 调整为 {licensePlate}", - "调用方请仅依赖 licensePlate 字段以适配新版本;历史字段已裁剪且不再保证存在。", - "文档中未包含任何云密钥或敏感配置信息。" - ] - } -] + { + "version": "2026.04.07-system-02", + "date": "2026-04-07", + "summary": "补充签约配置相关接口文档,覆盖策略字段元信息查询与面单数量人工调整。", + "methods": [ + "storeWarehouse.store.getPolicyConfigFields", + "storeWarehouse.store.adjustPrintQuantity" + ], + "notes": [ + "getPolicyConfigFields 说明为获取签约策略可配置字段元信息列表。", + "adjustPrintQuantity 说明为人工调整签约关系下的面单余额并记录变更日志,并 明确 id、change_quantity、reason 等关键入参。" + ] + }, + { + "version": "2026.04.07-system-03", + "date": "2026-04-07", + "summary": "对外命名从 qimenConfig 收口为 apiConfig,并在接口配置文档中强调 interface_type_id 校验。", + "methods": [ + "storeWarehouse.store.listApiConfig", + "storeWarehouse.store.saveApiConfig", + "storeWarehouse.store.deleteQimenConfig" + ], + "notes": [ + "文档对外统一使用 apiConfig / api_config 命名,减少 qimenConfig 历史别名歧义。", + "saveApiConfig 要求 interface_type_id 为必填且必须指向已存在的 wms_interface_type 记录。", + "listApiConfig / deleteQimenConfig 同步补充 interface_type_id 字段说明。" + ] + }, + { + "version": "2026.04.07-system-04", + "date": "2026-04-07", + "summary": "补充 /api/docs 文档体验增强说明,新增查看变更记录与查看原文 JSON 的入口说明。", + "methods": [ + "/api/docs", + "/api/docs/:docName", + "/api/docs/:docName/raw", + "/api/docs/:docName/changes" + ], + "notes": [ + "sidecar 变更数组用于承载文档历史说明,不替代 methods/system.json 作为 SSOT。", + "原文 JSON 入口继续用于直接查看当前生效文档。" + ] + }, + { + "version": "2026.04.07-system-05", + "date": "2026-04-07", + "summary": "修正 storeWarehouse.store.adjustPrintQuantity 的面单余额调整语义:由增减/累加改为覆盖设置目标余额。", + "methods": [ + "storeWarehouse.store.adjustPrintQuantity" + ], + "notes": [ + "adjustPrintQuantity 当前兼容 print_quantity、target_quantity、change_quantity、adjust_quantity 作为目标面单余额输入,不再按增减量解释。", + "变更日志中的 change_quantity 由 before/after 自动计算差值,以兼容历史审计与展示。" + ] + }, + { + "version": "2026.04.07-system-06", + "date": "2026-04-07", + "summary": "按接口类型分类限制必填字段,OPEN_API 创建时自动生成 self_app_key/self_app_secret", + "methods": [ + "storeWarehouse.store.saveApiConfig" + ], + "notes": [ + "QM_WMS 类型须填写 qimen_app_key/qimen_customer_id/qimen_warehouse_code;OPEN_API 类型三个奇门字段非必填,创建时自动生成 self_app_key(WMS+32位HEX)和 self_app_secret(64位HEX),更新时保留已有密钥。" + ], + "type": "changed" + }, + { + "version": "2026.04.07-system-07", + "date": "2026-04-07", + "summary": "新增接口类型列表查询接口,归属基础模块,无需权限", + "methods": [ + "index.listInterfaceTypes" + ], + "notes": [ + "返回所有已启用的接口类型(wms_interface_type),包含 id、interface_code、interface_name、interface_category、description 字段。设置 isNeedAuth: false, isNeedLogin: true。" + ], + "type": "added" + }, + { + "version": "2026.04.07-system-08", + "date": "2026-04-07", + "summary": "app_name 改为必传参数", + "methods": [ + "storeWarehouse.store.saveApiConfig" + ], + "notes": [ + "app_name 不再有默认值自动生成逻辑,调用方必须传入非空的 app_name,否则返 回 400 错误。" + ], + "type": "changed" + }, + { + "version": "2026.04.07-system-09", + "date": "2026-04-07", + "summary": "新增收货单快捷入库上架接口", + "methods": [ + "storage.inventory.quickPutaway" + ], + "notes": [ + "新建 storage.inventory 库存操作模块。quickPutaway 从收货单直接生成入库单 (SCRK)并写入 wms_storage 库存表,同时更新 wms_stock_warehouse 库存数量(悲观行锁),回填收货明细入库状态。要求收货单已完成且所有明细已匹配系统商品。" + ], + "type": "added" + }, + { + "version": "2026.04.08-system-01", + "date": "2026-04-08", + "summary": "新增收货单与入库单匹配入库接口", + "methods": [ + "storage.inventory.matchPutaway" + ], + "notes": [ + "接收多个收货单和入库单,按商品(stock_warehouse_id)进行数量匹配入库,完 成后根据入库单来源(QM/API)自动触发回传。入参为 receiving_ids(数组)和 entry_order_ids(数组),返回匹配汇总、各收货单入库状态、各入库单状态及回传结果。isNeedAuth=true, isNeedLogin=true, isNeedRight=false。" + ], + "type": "added" + }, + { + "version": "2026.04.08-system-02", + "date": "2026-04-08", + "summary": "saveApiConfig 新增 callback_url 可选参数", + "methods": [ + "storeWarehouse.store.saveApiConfig" + ], + "notes": [ + "新增 callback_url 参数(VARCHAR(500),可选),用于 OPEN_API 类型入库单的 回调地址配置。" + ], + "type": "changed" + }, + { + "version": "2026.04.08-system-03", + "date": "2026-04-08", + "summary": "serializeQimenConfig 新增返回 callback_url 字段,影响 list 和 listApiConfig 两个接口", + "methods": [ + "storeWarehouse.store.list", + "storeWarehouse.store.listApiConfig" + ], + "notes": [ + "serializeQimenConfig() 序列化方法新增 callback_url(string)字段。storeWarehouse.store.list 返回的每条记录 api_config 对象中包含 callback_url;storeWarehouse.store.listApiConfig 返回的 list 数组中每条配置包含 callback_url。" + ], + "type": "changed" + }, + { + "version": "2026.04.08-system-04", + "date": "2026-04-08", + "summary": "新增库存移库(库位转移)接口", + "methods": [ + "storage.inventory.transferLocation" + ], + "notes": [ + "新增 storage.inventory.transferLocation 接口,支持批量多商品多库位移库, 包含部分数量移库与全量移库。入参为 warehouse_id(仓库ID)和 transfers 数组(storage_id、target_space_id、quantity),触发 storage_transfer_completed 通知事件, 每条移库记录独立操作日志。isNeedAuth=true, isNeedLogin=true。" + ], + "type": "added" + }, + { + "version": "2026.04.08-system-05", + "date": "2026-04-08", + "summary": "简化移库接口入参,从批量 transfers 数组改为单条移库", + "methods": [ + "storage.inventory.transferLocation" + ], + "notes": [ + "移除 warehouse_id 和 transfers 数组入参,改为扁平的 storage_id + target_space_id + quantity 三个顶层参数。warehouse_id 从库存记录自动获取,接口从批量移库简化为单商品单库位移库。响应结构同步简化为单条结果对象。" + ], + "type": "modified" + }, + { + "version": "2026.04.08-system-06", + "date": "2026-04-08", + "summary": "新增商品库存明细查询接口", + "methods": [ + "stock.warehouse.getStockDetail" + ], + "notes": [ + "新增 stock.warehouse.getStockDetail 接口,按库位/批次维度查询商品库存分布。入参为 stock_id(必填,商品库存ID)和 pagination(可选,含 page/pageSize)。返回 stockItem(商品概要)、storageList(wms_storage 明细数组,含批次号、库位、数 量、锁定数量、生产日期、过期日期等,关联 location_space 库位信息)、pagination 分页信息。isNeedAuth=false, isNeedLogin=true。底层调用 stockStore.getStockDetail,自动校验商品归属当前仓库。" + ], + "type": "added" + }, + { + "version": "2026.04.08-system-07", + "date": "2026-04-08", + "summary": "新增入参 group_by_batch,支持按批次维度切换库存明细聚合方式", + "methods": [ + "stock.warehouse.getStockDetail" + ], + "notes": [ + "新增可选布尔参数 group_by_batch(默认 false)。false 时按库位合并数量,批次相关字段(batch_no, production_date, expiry_date, inbound_time, inbound_order_no, supplier_batch_no)置 null;true 时保持原逻辑返回每条明细。出参结构不变,但 storageList 中批次字段在合并模式下为 null。" + ], + "type": "modified" + }, + { + "version": "2026.04.08-system-08", + "date": "2026-04-08", + "summary": "新增按商品维度移库接口", + "methods": [ + "storage.inventory.transferByProduct" + ], + "notes": [ + "新增 storage.inventory.transferByProduct 接口,按库位+商品查找所有库存记 录合并移动。入参为 space_id(原库位ID)、stock_id(商品SKU ID,即 wms_stock_warehouse.id)、target_space_id(目标库位ID)、quantity(移库数量)。开启批次管理(is_batch_mgmt=Y)的商品会被拒绝,需使用 transferLocation 按库存记录精确移库。复用 storage_transfer_completed 通知事件,操作日志编码 STORAGE_TRANSFER_BY_PRODUCT。isNeedAuth=true, isNeedLogin=true。" + ], + "type": "added" + }, + { + "version": "2026.04.08-system-09", + "date": "2026-04-08", + "summary": "补充 storeWarehouse.store.list 完整 response 输出字段说明,移除 api_config / apiConfig", + "methods": [ + "storeWarehouse.store.list" + ], + "notes": [ + "从返回结果中移除 api_config 和 apiConfig 字段(代码中 delete serialized.api_config / delete serialized.apiConfig),文档 response 补充完整输出字段列表:id, store_id, store_name, warehouse_id, warehouse_name, counterparty_id, counterparty_name, current_subject_role, auth_status, auth_status_label, apply_reason, review_comment, apply_time, review_time, auth_start, auth_end, actual_end, print_quantity, applied_by, reviewed_by, ended_by, remask, use_status, policy_config, is_auth_valid, remaining_days 以及分页和 current_subject 信息。" + ], + "type": "updated" + }, + { + "version": "2026.04.08-system-10", + "date": "2026-04-08", + "summary": "货主列表返回新增 has_qimen_config 布尔字段", + "methods": [ + "storeWarehouse.store.list" + ], + "notes": [ + "storeWarehouse.store.list 返回的 data.list[] 中新增 has_qimen_config(boolean),表示该货主是否已配置奇门。" + ], + "type": "changed" + }, + { + "version": "2026.04.08-system-11", + "date": "2026-04-08", + "summary": "补全 stock.warehouse.search 接口文档,新增 params / response / errors 完整说明", + "methods": [ + "stock.warehouse.search" + ], + "notes": [ + "入参补充 keyword(string,模糊匹配 item_code / item_name / goods_code / barcode)和 store_id(number,按货主筛选)。响应补充 data 数组各字段(id, item_code, goods_code, item_name, sku_property, stock_unit, quantity, locked_quantity, brand_name, item_type, barcodes, store_stock)以及 total。errors 补充 code=0 搜 索失败场景。" + ], + "type": "updated" + }, + { + "version": "2026.04.08-system-12", + "date": "2026-04-08", + "summary": "新增 with_stock / is_batch 参数,支持返回关联库存明细(按库位分 组或按批次逐条)", + "methods": [ + "stock.warehouse.search" + ], + "notes": [ + "入参新增 with_stock(boolean,默认 false,是否返回关联库存数据)和 is_batch(boolean,默认 false,仅 with_stock=true 时生效,按批次明细返回)。响应 data[] 新增 storage[] 字段:is_batch=false 时按库位分组汇总(含 space_id、space、inventory_type、quantity、locked_quantity、available_quantity);is_batch=true 时逐 条返回批次明细(含 id、stock_id、space_id、batch_no、inventory_type、quantity、locked_quantity、available_quantity、production_date、expiry_date、inbound_time、inbound_order_no、supplier_batch_no、created_at、space)。" + ], + "type": "updated" + }, + { + "version": "2026.04.08-system-13", + "date": "2026-04-08", + "summary": "新增 wms_stock_transaction 表和模型", + "methods": [ + "wms_stock_transaction" + ], + "notes": [ + "新增出入库流水记录表 wms_stock_transaction,含 transaction_type(INBOUND/OUTBOUND)、warehouse_id、store_id、stock_id、storage_id、space_id、quantity、batch_no、inventory_type、order_type、order_no、order_id、receiving_id、entry_order_id、operator_id、operator_name、remark 等字段,关联 StockWarehouse 和 Storage 模型。" + ], + "type": "added" + }, + { + "version": "2026.04.08-system-14", + "date": "2026-04-08", + "summary": "quickPutaway 和 matchPutaway 入库时自动写入出入库记录", + "methods": [ + "storage.inventory.quickPutaway", + "storage.inventory.matchPutaway" + ], + "notes": [ + "入库操作完成后自动写入 wms_stock_transaction 记录。quickPutaway 写入 order_type='SCRK'(收货入库),matchPutaway 写入 order_type='MATCH'(匹配入库),均 自动填充 warehouse_id、store_id、stock_id、storage_id、space_id、quantity、batch_no、inventory_type 等字段。" + ], + "type": "updated" + }, + { + "version": "2026.04.08-system-15", + "date": "2026-04-08", + "summary": "新增 storage.inventory.list 出入库记录列表查询接口", + "methods": [ + "storage.inventory.list" + ], + "notes": [ + "出入库记录列表查询,支持 where 条件(transaction_type、stock_id、space_id、store_id、order_type、order_no、inventory_type、operator_name、created_at)、 分页(pagination)、排序(sort)和 group_by_batch 参数。默认合并模式按库位+商品 聚合返回合计数量与记录条数,group_by_batch=true 时返回每条明细含 batch_no、order_no、operator_name 等完整信息。响应均关联 stockItem(item_code、item_name、sku_property、stock_unit)。" + ], + "type": "added" + }, + { + "version": "2026.04.08-system-16", + "date": "2026-04-08", + "summary": "出入库流水记录查询接口从 storage.inventory.list 改名为 storage.transaction.list", + "methods": [ + "storage.transaction.list" + ], + "notes": [ + "将出入库流水记录查询从 storage.inventory.list 迁移到 storage.transaction.list,避免与库存列表概念混淆。功能和参数不变。isNeedAuth=false, isNeedLogin=true, isNeedRight=false。" + ], + "type": "rename", + "module": "storage" + }, + { + "version": "2026.04.08-system-17", + "date": "2026-04-08", + "summary": "新增 storage.inventory.list 库存列表查询接口", + "methods": [ + "storage.inventory.list" + ], + "notes": [ + "新增库存列表查询接口,查询 wms_storage 表。支持 where 条件(stock_id/space_id/store_id/inventory_type/batch_no/inbound_order_no/available_quantity/inbound_time/created_at)、分页、排序。支持 group_by_batch 参数:默认 false 按库位+商 品合并(SUM quantity/locked_quantity/available_quantity),true 返回每条明细含 batch_no/production_date/expiry_date 等。关联 stockItem(商品信息)和 space(库位信息)。isNeedAuth=false, isNeedLogin=true, isNeedRight=false。" + ], + "type": "add", + "module": "storage" + }, + { + "version": "2026.04.08-system-18", + "date": "2026-04-08", + "summary": "移除 storage.entry.create 创建入库单接口", + "methods": [ + "storage.entry.create" + ], + "notes": [ + "不再允许通过 API 创建入库单。入库单仅由快捷入库(quickPutaway)和匹配入库(matchPutaway)等内部流程自动创建。底层 service 实现保留但不再通过 systemMethods 对外暴露。" + ], + "type": "remove", + "module": "storage" + }, + { + "version": "2026.04.08-system-19", + "date": "2026-04-08", + "summary": "移除 storage.entry.addDetail / deleteDetail / detailChange 对外 接口", + "methods": [ + "storage.entry.addDetail", + "storage.entry.deleteDetail", + "storage.entry.detailChange" + ], + "notes": [ + "入库单明细编辑能力不再通过 systemMethods 对外暴露,入库单模块仅保留 list/get/cancel/completeEntry。" + ], + "type": "remove", + "module": "storage" + }, + { + "version": "2026.04.08-system-20", + "date": "2026-04-08", + "summary": "新增 storage.stockout 出库单模块(非订单出库单能力)", + "methods": [ + "storage.stockout.list", + "storage.stockout.toOrder", + "storage.stockout.listItems" + ], + "notes": [ + "新增 storage.stockout.list / toOrder / listItems 接口,作为非订单出库单的主出口(对应奇门 stockout.create)。storage.delivery.* 仅作为兼容转发保留;底层 部分能力仍复用 order 模块。" + ], + "type": "add", + "module": "storage" + }, + { + "version": "2026.04.08-system-21", + "date": "2026-04-08", + "summary": "将 storage.stockout.toOrder 标记为占位接口", + "methods": [ + "storage.stockout.toOrder" + ], + "notes": [ + "storage.stockout.toOrder 当前仅保留方法名用于后续扩展,暂不开放实际逻辑。调用时返回 code=405、message=占位接口,暂未开放。" + ], + "type": "change" + }, + { + "version": "2026.04.09-system-01", + "date": "2026-04-09", + "summary": "storage.entry.cancel 支持批量作废,新增 ids 入参并兼容单条 id", + "methods": [ + "storage.entry.cancel" + ], + "notes": [ + "新增入参 `ids`(number[])以支持批量作废,兼容旧入参 `id`;当同时传入 `ids` 与 `id` 时以 `ids` 为准。", + "参数校验:`ids` 必须为非空数组;非法 ID 或空数组返回 400。", + "业务约束:已完成/已作废/处于不可作废状态的单据不允许作废;批量场景下任一 单据不存在或状态不允许时整体返回 404/400,未执行部分更新。", + "响应说明:单条作废返回字段 `id`(number);批量作废返回字段 `ids`(number[])。", + "已同步更新 methods/system.json(storage.entry.cancel)为 SSOT。" + ] + }, + { + "version": "2026.04.09-system-02", + "date": "2026-04-09", + "summary": "新增基础模块车牌识别接口 index.recognizeLicensePlate", + "methods": [ + "index.recognizeLicensePlate" + ], + "notes": [ + "入参:base64(string,必填)或 imageBase64/image_base64(兼容)", + "响应:返回归一化后的识别对象,包含 licensePlate、plateNumber、color、confidence、requestId、imageSize、rawData", + "错误:400(参数或图片格式/尺寸问题),500(第三方 OCR 调用失败或云密钥未 配置)", + "文档中不包含任何敏感配置;实际腾讯云密钥保留在配置文件中,勿在文档中暴露 。" + ], + "type": "added" + }, + { + "version": "2026.04.09-system-03", + "date": "2026-04-09", + "summary": "收紧基础模块车牌识别接口响应,仅返回 licensePlate 字段", + "methods": [ + "index.recognizeLicensePlate" + ], + "notes": [ + "出参由 {licensePlate, plateNumber, color, confidence, requestId, imageSize, rawData} 调整为 {licensePlate}", + "调用方请仅依赖 licensePlate 字段以适配新版本;历史字段已裁剪且不再保证存 在。", + "文档中未包含任何云密钥或敏感配置信息。" + ], + "type": "changed" + }, + { + "version": "2026.04.10-system-01", + "date": "2026-04-10", + "summary": "订单审核字段由 audit_status 替换为整数字段 step,并添加数据库迁移", + "methods": [ + "order.getreviewOrderlist", + "order.reviewOrder.getreviewOrderlist", + "order.reviewOrder.reviewOrder", + "order.deliveryOrder.getdeliveryOrderlist", + "order.list", + "order.stats" + ], + "notes": [ + "字段变更:order 相关审核字段从字符串/枚举 audit_status 替换为整数 step。", + "step 映射:0=未审核,1=已审核,2=处理中,3=驳回/异常,4=配送中,5=已完成,9=已关闭。", + "reviewOrder 接口在更新 inspection_status 的同时会写入 step 字段。", + "必须执行迁移脚本:20260410150000-replace-audit-status-with-step-on-order-delivery-tables.js" + ], + "type": "changed" + } + ] diff --git a/methods/system.json b/methods/system.json index 5c3625f..3b4ddbc 100644 --- a/methods/system.json +++ b/methods/system.json @@ -580,7 +580,7 @@ "type": "object", "required": false, "source": "body", - "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会在 main 中自动标准化;常用字段包括 delivery_order_code、status、outbound_status、buyer_nick、mobile 与日期区间字段。示例:where.delivery_order_code={operator:like,value:SO202603}; where.status={operator:in,value:[created,pedding]}。" + "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会在 main 中自动标准化;常用字段包括 delivery_order_code、status、step、outbound_status、buyer_nick、mobile 与日期区间字段。示例:where.delivery_order_code={operator:like,value:SO202603}; where.status={operator:in,value:[created,pedding]}; where.step={operator:eq,value:1}。" } ], "response": [], @@ -701,7 +701,7 @@ "type": "object", "required": false, "source": "body", - "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构;支持 inspection_status、operator_name、operate_time_start、operate_time_end 等字段。示例:where.inspection_status={operator:eq,value:pending}; where.operator_name={operator:like,value:张}; where.operate_time_start={value:2026-03-01}。" + "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构;支持 inspection_status、step、operator_name、operate_time_start、operate_time_end 等字段。示例:where.step={operator:in,value:[0,1]}; where.inspection_status={operator:eq,value:pending}; where.operator_name={operator:like,value:张}; where.operate_time_start={value:2026-03-01}。" } ], "response": [], @@ -934,7 +934,7 @@ "type": "object", "required": false, "source": "body", - "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构;支持 inspection_status、operator_name、operate_time_start、operate_time_end 等字段。示例:where.inspection_status={operator:eq,value:pending}; where.operator_name={operator:like,value:张}; where.operate_time_start={value:2026-03-01}。" + "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构;支持 inspection_status、step、operator_name、operate_time_start、operate_time_end 等字段。示例:where.step={operator:in,value:[0,1]}; where.inspection_status={operator:eq,value:pending}; where.operator_name={operator:like,value:张}; where.operate_time_start={value:2026-03-01}。" } ], "response": [], @@ -942,7 +942,7 @@ }, { "method": "order.reviewOrder.reviewOrder", - "description": "订单审核(目录化路由)", + "description": "订单审核(目录化路由)。执行后会更新 inspection_status,并同步更新订单整数字段 step。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -1026,7 +1026,7 @@ "type": "object", "required": false, "source": "body", - "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构;未传 outbound_status 时默认过滤 outbound_status != none。示例:where.outbound_status={operator:in,value:[created,processing]}; where.store_id={operator:eq,value:1001}。" + "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构;未传 outbound_status 时默认过滤 outbound_status != none;支持 step 筛选。示例:where.outbound_status={operator:in,value:[created,processing]}; where.step={operator:in,value:[4,5]}; where.store_id={operator:eq,value:1001}。" } ], "response": [], diff --git a/package.json b/package.json index 972a5bd..a43d04c 100644 --- a/package.json +++ b/package.json @@ -1,5 +1,5 @@ { - "name": "oms", + "name": "wms", "version": "1.0.0", "description": "奇门wms", "private": true, @@ -43,6 +43,7 @@ "start": "egg-scripts start ", "stop": "node ./app/lib/stop_current_egg.js", "dev": "egg-bin dev --port=6060", + "file-writer:pressure": "node ./temp/generated-tests/file-writer-pressure.generated.test.cjs", "debug:webhook:receiver": "node ./script/debug-webhook-receiver.cjs", "debug:webhook:receiving": "node ./script/debug-send-receiving-webhooks.cjs", "deploy:init": "node ./script/deploy-init.cjs production", diff --git a/runtime/file-writer/.write-window-counter-3.json b/runtime/file-writer/.write-window-counter-3.json new file mode 100644 index 0000000..809d98c --- /dev/null +++ b/runtime/file-writer/.write-window-counter-3.json @@ -0,0 +1 @@ +{"startedAt":1775826309321,"recordCount":2} diff --git a/runtime/file-writer/qimen-logs/.consume-progress b/runtime/file-writer/qimen-logs/.consume-progress new file mode 100644 index 0000000..641f604 --- /dev/null +++ b/runtime/file-writer/qimen-logs/.consume-progress @@ -0,0 +1,7 @@ +{ + "filePath": "D:\\wms\\runtime\\file-writer\\qimen-logs\\2026\\04\\10\\qimen-logs-MINGREN-worker-p4496-0001.log", + "offset": 6149, + "processedCount": 2, + "completedAt": "2026-04-10T14:20:54.561Z", + "updatedAt": "2026-04-11T09:08:50.539Z" +} diff --git a/runtime/file-writer/qimen-logs/2026/04/10/qimen-logs-MINGREN-worker-p4496-0001.log b/runtime/file-writer/qimen-logs/2026/04/10/qimen-logs-MINGREN-worker-p4496-0001.log new file mode 100644 index 0000000..c5a12f6 --- /dev/null +++ b/runtime/file-writer/qimen-logs/2026/04/10/qimen-logs-MINGREN-worker-p4496-0001.log @@ -0,0 +1,2 @@ +{"log_id":"QL-1775804691322-cfe013","from_key":"24869601","to_key":23535631,"method":"deliveryorder.create","sign":"05687722A46473E4018E0EBAAAB84E96","costomer_id":"jky2025102001","v":"2.0","url":"http://127.0.0.1:6060/qimen?app_key=24869601&method=deliveryorder.create&v=2.0&format=xml&sign_method=md5&customerId=jky2025102001&sign=05687722A46473E4018E0EBAAAB84E96×tamp=2026-01-13+23%3A26%3A07","created_at":"2026-04-10T07:04:51.322Z","body":"SIM20260410070451JYCK100000PDD拼多多2026-01-13 23:26:072026-01-13 23:22:032026-01-13 23:22:03火火家de小店06751刘付明仁1802244019811001000SFKY顺丰空运2026-01-13 23:26:07NN火火家de小店111CN广东省广州市从化区太平镇天豹云仓刘付明仁18022440198CN广东省广州市白云区太和镇广东省 广州市 白云区 太和镇 二路32号1N01jky20251020010110000002281000649测试10110ZP10100000000000false","result":"\n\n failure\n 0\n 奇门吉客云ERP客户编码jky2025102001仓库编码warehouseCode未绑定到你的货主或未启用,请联系仓库绑定\n","use_time":98} +{"log_id":"QL-1775804829940-8ee9f4","from_key":"23060081","to_key":23535631,"method":"deliveryorder.create","sign":"F4AC9969DF96CBDBCE02CF60982F2984","costomer_id":"4","v":"2.0","url":"http://127.0.0.1:6060/qimen?app_key=23060081&method=deliveryorder.create&v=2.0&format=xml&sign_method=md5&customerId=4&sign=F4AC9969DF96CBDBCE02CF60982F2984×tamp=2026-01-13+23%3A27%3A38","created_at":"2026-04-10T07:07:09.940Z","body":"刘付明仁2026-01-13 23:27:36SIM202604100707090.0000.0002026-01-15 22:51:36SFKY顺丰速运_空运2026-01-13 23:27:36JYCKS202601132251362232026-01-13 22:51:362026-01-13 22:49:50白云区广州市钟落潭良沙二路32号18022440198刘付明仁广东省S260113225136208白云区广州市118022440198天豹测试仓15271658广东省{线下}OFFLINE线下店铺0.001000002042359Offlinefalse0falsetrue000ZP0238021000218空包115814945S2601132251362080","result":"\n\n failure\n 0\n 奇门聚水潭ERP客户编码4仓库编码warehouseCode未绑定到你的货主或未启用,请联系仓库绑定\n","use_time":88} diff --git a/runtime/file-writer/qimen-logs/2026/04/10/qimen-logs-MINGREN-worker-p4496-0001.log.done b/runtime/file-writer/qimen-logs/2026/04/10/qimen-logs-MINGREN-worker-p4496-0001.log.done new file mode 100644 index 0000000..4aa8e60 --- /dev/null +++ b/runtime/file-writer/qimen-logs/2026/04/10/qimen-logs-MINGREN-worker-p4496-0001.log.done @@ -0,0 +1,7 @@ +{ + "filePath": "D:\\wms\\runtime\\file-writer\\qimen-logs\\2026\\04\\10\\qimen-logs-MINGREN-worker-p4496-0001.log", + "offset": 6149, + "processedCount": 2, + "completedAt": "2026-04-10T14:20:54.561Z", + "updatedAt": "2026-04-10T14:20:54.561Z" +} diff --git a/test/app/controller/gateway.user.bindAccountByTempCode.test.js b/test/app/controller/gateway.user.bindAccountByTempCode.test.js index 64ed022..aee6931 100644 --- a/test/app/controller/gateway.user.bindAccountByTempCode.test.js +++ b/test/app/controller/gateway.user.bindAccountByTempCode.test.js @@ -7,7 +7,12 @@ const { invokeGatewayMethod, } = require('../../support/system_method_client'); -const YE4S_TEST_USER_ID = Number(process.env.SYSTEM_TEST_YE4S_USER_ID || 28); +const YE4S_TEST_USER_ID = Number(process.env.SYSTEM_TEST_YE4S_USER_ID); + +assert.ok( + Number.isInteger(YE4S_TEST_USER_ID) && YE4S_TEST_USER_ID > 0, + 'SYSTEM_TEST_YE4S_USER_ID 必须显式提供且为正整数' +); describe('test/app/controller/gateway.user.bindAccountByTempCode.test.js', () => { it('should scan, bind, unbind, and bind again for ye4s user', async () => { diff --git a/test/app/controller/system.order.namespaced.test.js b/test/app/controller/system.order.namespaced.test.js index f46d91b..dfb14a9 100644 --- a/test/app/controller/system.order.namespaced.test.js +++ b/test/app/controller/system.order.namespaced.test.js @@ -14,6 +14,20 @@ const EXTRA_HEADERS = { const ALLOWED_REVIEW_STATUS = new Set([ 'none', 'padding', 'running', 'fin', 'error' ]); const FALLBACK_ROLE_IDS = [ 4, 6, 30 ]; +function mapReviewStatusToStep(reviewStatus) { + const status = String(reviewStatus || 'none').trim(); + if (status === 'fin') { + return 1; + } + if (status === 'running' || status === 'padding') { + return 2; + } + if (status === 'error') { + return 3; + } + return 0; +} + async function switchToWarehouseRoleWithOrderData(token) { let currentToken = token; const infoRes = await invokeSystemMethod('user.info', {}, currentToken, EXTRA_HEADERS); @@ -129,6 +143,7 @@ describe('test/app/controller/system.order.namespaced.test.js', () => { assert.equal(reviewRes.body.code, 200); assert.equal(Number(reviewRes.body?.data?.id || 0), Number(order.id)); assert.equal(reviewRes.body?.data?.inspection_status, targetStatus); + assert.equal(Number(reviewRes.body?.data?.step), mapReviewStatusToStep(targetStatus)); const restoreRes = await invokeSystemMethod('order.reviewOrder.reviewOrder', { id: Number(order.id), @@ -139,5 +154,45 @@ describe('test/app/controller/system.order.namespaced.test.js', () => { assert.equal(restoreRes.body.flag, 'success'); assert.equal(restoreRes.body.code, 200); assert.equal(restoreRes.body?.data?.inspection_status, originalStatus); + assert.equal(Number(restoreRes.body?.data?.step), mapReviewStatusToStep(originalStatus)); + }); + + it('should return step in delivery orders and support filtering', async () => { + const { token } = await getAuthToken(); + const switched = await switchToWarehouseRoleWithOrderData(token); + + const listRes = await invokeSystemMethod('order.deliveryOrder.getdeliveryOrderlist', { + pagination: { page: 1, pageSize: 10 }, + where: {}, + }, switched.token, EXTRA_HEADERS); + + assert.equal(listRes.status, 200); + assert.equal(listRes.body.flag, 'success'); + assert.equal(listRes.body.code, 200); + + const orders = listRes.body?.data?.list; + assert.ok(Array.isArray(orders)); + + if (orders.length > 0) { + assert.ok(Object.prototype.hasOwnProperty.call(orders[0], 'step'), '发货单应包含 step 字段'); + const sampleStep = Number(orders[0].step); + + const filteredRes = await invokeSystemMethod('order.deliveryOrder.getdeliveryOrderlist', { + pagination: { page: 1, pageSize: 10 }, + where: { step: sampleStep }, + }, switched.token, EXTRA_HEADERS); + + assert.equal(filteredRes.status, 200); + assert.equal(filteredRes.body.flag, 'success'); + assert.equal(filteredRes.body.code, 200); + const filteredOrders = filteredRes.body?.data?.list; + assert.ok(Array.isArray(filteredOrders)); + if (filteredOrders.length > 0) { + assert.ok( + filteredOrders.every(order => Number(order.step) === sampleStep), + `按 step=${sampleStep} 过滤后,所有订单都应是该状态` + ); + } + } }); }); diff --git a/test/app/controller/system.setting.account.getBindWechatCode.test.js b/test/app/controller/system.setting.account.getBindWechatCode.test.js index f0b4d5d..6a1daa4 100644 --- a/test/app/controller/system.setting.account.getBindWechatCode.test.js +++ b/test/app/controller/system.setting.account.getBindWechatCode.test.js @@ -7,7 +7,12 @@ const { invokeGatewayMethod, } = require('../../support/system_method_client'); -const YE4S_TEST_USER_ID = Number(process.env.SYSTEM_TEST_YE4S_USER_ID || 28); +const YE4S_TEST_USER_ID = Number(process.env.SYSTEM_TEST_YE4S_USER_ID); + +assert.ok( + Number.isInteger(YE4S_TEST_USER_ID) && YE4S_TEST_USER_ID > 0, + 'SYSTEM_TEST_YE4S_USER_ID 必须显式提供且为正整数' +); const EXTRA_HEADERS = { platform: 'web', diff --git a/test/app/controller/system.setting.storeWarehouse.test.js b/test/app/controller/system.setting.storeWarehouse.test.js index 14f8302..f539917 100644 --- a/test/app/controller/system.setting.storeWarehouse.test.js +++ b/test/app/controller/system.setting.storeWarehouse.test.js @@ -11,6 +11,20 @@ const EXTRA_HEADERS = { project: 'all', }; +/** + * 从列表中选出固定的测试签约关系。 + * @param {Array} relations 签约关系列表。 + * @return {object|null} 固定测试关系,找不到时返回空。 + */ +function pickFixedTestRelation(relations) { + if (!Array.isArray(relations)) { + return null; + } + + return relations.find(item => Number(item.store_id) === 1000000 && Number(item.warehouse_id) === 100000) + || null; +} + describe('test/app/controller/system.setting.storeWarehouse.test.js', () => { const METHOD_PREFIX = 'storeWarehouse.store'; let token = ''; @@ -32,9 +46,8 @@ describe('test/app/controller/system.setting.storeWarehouse.test.js', () => { assert.equal(res.body.code, 200); assert.ok(Array.isArray(res.body?.data?.list), 'list 应返回数组'); assert.ok(res.body?.data?.current_subject, '应返回当前主体信息'); - sampleRelation = Array.isArray(res.body?.data?.list) && res.body.data.list.length > 0 - ? res.body.data.list[0] - : null; + sampleRelation = pickFixedTestRelation(res.body?.data?.list); + assert.ok(sampleRelation, '未找到固定测试仓/测试货主对应关系'); }); it('should allow renaming current-side remask and reflect it in list display', async () => { @@ -51,8 +64,8 @@ describe('test/app/controller/system.setting.storeWarehouse.test.js', () => { const currentRole = String(listRes.body?.data?.current_subject?.role || ''); const candidates = Array.isArray(listRes.body?.data?.list) ? listRes.body.data.list : []; - const candidate = candidates.find(item => Number(item.id) > 0); - assert.ok(candidate, '需要至少一条签约关系用于改名回归'); + const candidate = pickFixedTestRelation(candidates); + assert.ok(candidate, '未找到固定测试仓/测试货主对应关系,无法改名回归'); const isWarehouse = currentRole === 'warehouse'; const originRemask = String(candidate.remask || ''); @@ -98,34 +111,13 @@ describe('test/app/controller/system.setting.storeWarehouse.test.js', () => { it('should generate a temp code and support preview before confirmation', async () => { assert.ok(sampleRelation, '需要至少一条现有签约关系用于临时码回归'); - const candidateRes = await invokeSystemMethod(`${METHOD_PREFIX}.list`, { - page: 1, - page_size: 30, + const initRes = await invokeSystemMethod(`${METHOD_PREFIX}.sign`, { + store_id: 1000000, + warehouse_id: 100000, + apply_reason: 'autotest temp sign flow', + remask: `autotest_remask_${Date.now()}`, }, token, EXTRA_HEADERS); - assert.equal(candidateRes.status, 200); - assert.equal(candidateRes.body.flag, 'success'); - assert.equal(candidateRes.body.code, 200); - - const candidates = Array.isArray(candidateRes.body?.data?.list) ? candidateRes.body.data.list : []; - assert.ok(candidates.length > 0, '需要至少一条签约关系用于临时码回归'); - - let initRes = null; - for (const item of candidates) { - const attempt = await invokeSystemMethod(`${METHOD_PREFIX}.sign`, { - counterparty_id: Number(item.counterparty_id), - apply_reason: 'autotest temp sign flow', - remask: `autotest_remask_${Date.now()}`, - }, token, EXTRA_HEADERS); - - if (attempt.status === 200 && attempt.body && attempt.body.flag === 'success') { - initRes = attempt; - break; - } - } - - assert.ok(initRes, '未找到可发起临时码签约的对方主体,请确认测试账号签约数据'); - assert.equal(initRes.status, 200); assert.equal(initRes.body.flag, 'success'); assert.equal(initRes.body.code, 200); @@ -187,8 +179,8 @@ describe('test/app/controller/system.setting.storeWarehouse.test.js', () => { } const candidates = Array.isArray(listRes.body?.data?.list) ? listRes.body.data.list : []; - const candidate = candidates.find(item => Number(item.id) > 0); - assert.ok(candidate, '需要至少一条签约关系用于策略配置回归'); + const candidate = pickFixedTestRelation(candidates); + assert.ok(candidate, '未找到固定测试仓/测试货主对应关系,无法做策略配置回归'); const originalPolicyConfig = candidate.policy_config && typeof candidate.policy_config === 'object' ? { ...candidate.policy_config } @@ -199,6 +191,7 @@ describe('test/app/controller/system.setting.storeWarehouse.test.js', () => { auto_allocate_bin: 1, allow_mix_batch: 0, max_daily_inbound: 5000, + need_order_approval: 1, remark: `autotest_${Date.now()}`, }; @@ -214,6 +207,7 @@ describe('test/app/controller/system.setting.storeWarehouse.test.js', () => { assert.equal(Number(saveRes.body?.data?.contract_id || 0), Number(candidate.id)); assert.equal(String(saveRes.body?.data?.policy_config?.receive_mode || ''), 'strict'); assert.equal(Number(saveRes.body?.data?.policy_config?.auto_allocate_bin || 0), 1); + assert.equal(Number(saveRes.body?.data?.policy_config?.need_order_approval || 0), 1, '保存后 need_order_approval 应为 1'); const getRes = await invokeSystemMethod(`${METHOD_PREFIX}.getPolicyConfig`, { id: Number(candidate.id), @@ -225,6 +219,7 @@ describe('test/app/controller/system.setting.storeWarehouse.test.js', () => { assert.equal(Number(getRes.body?.data?.contract_id || 0), Number(candidate.id)); assert.equal(String(getRes.body?.data?.policy_config?.sku_visibility || ''), 'whitelist'); assert.equal(Number(getRes.body?.data?.policy_config?.max_daily_inbound || 0), 5000); + assert.equal(Number(getRes.body?.data?.policy_config?.need_order_approval || 0), 1, '读取后 need_order_approval 应为 1'); } finally { if (originalPolicyConfig) { await invokeSystemMethod(`${METHOD_PREFIX}.savePolicyConfig`, { @@ -251,8 +246,8 @@ describe('test/app/controller/system.setting.storeWarehouse.test.js', () => { } const candidates = Array.isArray(listRes.body?.data?.list) ? listRes.body.data.list : []; - const candidate = candidates.find(item => Number(item.id) > 0); - assert.ok(candidate, '需要至少一条签约关系用于策略字段限制回归'); + const candidate = pickFixedTestRelation(candidates); + assert.ok(candidate, '未找到固定测试仓/测试货主对应关系,无法做策略字段限制回归'); const res = await invokeSystemMethod(`${METHOD_PREFIX}.savePolicyConfig`, { id: Number(candidate.id), @@ -284,8 +279,8 @@ describe('test/app/controller/system.setting.storeWarehouse.test.js', () => { } const candidates = Array.isArray(listRes.body?.data?.list) ? listRes.body.data.list : []; - const candidate = candidates.find(item => Number(item.id) > 0); - assert.ok(candidate, '需要至少一条签约关系用于接口配置回归'); + const candidate = pickFixedTestRelation(candidates); + assert.ok(candidate, '未找到固定测试仓/测试货主对应关系,无法做接口配置回归'); const originalApiConfig = candidate.api_config || candidate.apiConfig || null; const seed = Date.now(); diff --git a/test/app/controller/system.storage.delivery.module.test.js b/test/app/controller/system.storage.delivery.module.test.js index 487f094..ee764eb 100644 --- a/test/app/controller/system.storage.delivery.module.test.js +++ b/test/app/controller/system.storage.delivery.module.test.js @@ -11,7 +11,6 @@ const EXTRA_HEADERS = { project: 'all', }; -const FALLBACK_ROLE_IDS = [ 4, 6, 30 ]; const TEST_WAREHOUSE_ID = 100000; function normalizeListPayload(data) { @@ -35,20 +34,10 @@ async function switchToWarehouseRoleWithDeliveryData(token) { && Number(item.id) && Number(item.store_id) === TEST_WAREHOUSE_ID ); - const otherWarehouseRoles = employees.filter(item => - item - && item.role_type === 'warehouse' - && Number(item.id) - && Number(item.store_id) !== TEST_WAREHOUSE_ID - ); - const candidateRoleIds = [ ...new Set([ - ...preferredWarehouseRoles.map(item => Number(item.id)), - ...otherWarehouseRoles.map(item => Number(item.id)), - ...FALLBACK_ROLE_IDS, - ].filter(Boolean)) ]; + const candidateRoleIds = [ ...new Set(preferredWarehouseRoles.map(item => Number(item.id)).filter(Boolean)) ]; - assert.ok(candidateRoleIds.length > 0, '当前账号没有可尝试的仓库角色'); + assert.ok(candidateRoleIds.length > 0, '当前账号没有固定测试仓角色'); for (const roleId of candidateRoleIds) { const changeRes = await invokeSystemMethod('user.changeRole', { @@ -100,7 +89,8 @@ async function getFirstDelivery(token) { assert.ok(Array.isArray(payload.list), '出库单 list 不是数组'); assert.ok(payload.pagination, '出库单 pagination 缺失'); - const first = payload.list[0]; + const first = [ ...payload.list ] + .sort((left, right) => Number(left?.id || 0) - Number(right?.id || 0))[0]; assert.ok(first, '出库单列表为空,无法继续验证 toOrder/listItems'); return first; } @@ -119,7 +109,9 @@ async function getEntryContextForRemovedMethods(token) { assert.equal(listRes.body.code, 200); const payload = normalizeListPayload(listRes.body.data); - const entry = payload && Array.isArray(payload.list) ? payload.list[0] : null; + const entry = payload && Array.isArray(payload.list) + ? [ ...payload.list ].sort((left, right) => Number(left?.id || 0) - Number(right?.id || 0))[0] + : null; if (!entry || !entry.id) { return { @@ -138,7 +130,9 @@ async function getEntryContextForRemovedMethods(token) { assert.equal(getRes.body.code, 200); const entryOrder = getRes.body?.data?.entryOrder || {}; - const firstItem = Array.isArray(entryOrder?.items) ? entryOrder.items[0] : null; + const firstItem = Array.isArray(entryOrder?.items) + ? [ ...entryOrder.items ].sort((left, right) => Number(left?.id || 0) - Number(right?.id || 0))[0] + : null; return { orderId: Number(entry.id), diff --git a/test/app/controller/system.storage.receiving.test.js b/test/app/controller/system.storage.receiving.test.js index cb3e94f..1882389 100644 --- a/test/app/controller/system.storage.receiving.test.js +++ b/test/app/controller/system.storage.receiving.test.js @@ -11,8 +11,6 @@ const EXTRA_HEADERS = { project: 'all', }; -const FALLBACK_ROLE_IDS = [ 4, 6, 30 ]; - function normalizeListPayload(data) { if (data && Array.isArray(data.list)) return data; if (data && data.data && Array.isArray(data.data.list)) return data.data; @@ -25,6 +23,12 @@ function normalizeDetailPayload(data) { return null; } +/** + * 切换到固定测试仓角色,并验证该角色可以访问收货单列表。 + * + * @param {string} token 当前登录令牌 + * @return {Promise<{token: string, roleId: number}>} 切换后的令牌与角色 ID + */ async function switchToWarehouseRole(token) { let currentToken = token; @@ -34,14 +38,14 @@ async function switchToWarehouseRole(token) { assert.equal(infoRes.body.code, 200); const employees = Array.isArray(infoRes.body?.data?.employees) ? infoRes.body.data.employees : []; - const warehouseRoles = employees.filter(item => item && item.role_type === 'warehouse' && Number(item.id)); + const warehouseRoles = employees.filter(item => item + && item.role_type === 'warehouse' + && Number(item.id) + && Number(item.store_id) === 100000); - const candidateRoleIds = [ ...new Set([ - ...warehouseRoles.map(item => Number(item.id)), - ...FALLBACK_ROLE_IDS, - ].filter(Boolean)) ]; + const candidateRoleIds = [ ...new Set(warehouseRoles.map(item => Number(item.id)).filter(Boolean)) ]; - assert.ok(candidateRoleIds.length > 0, '当前账号没有可尝试的仓库角色'); + assert.ok(candidateRoleIds.length > 0, '当前账号没有固定测试仓角色'); for (const roleId of candidateRoleIds) { const changeRes = await invokeSystemMethod('user.changeRole', { @@ -81,14 +85,15 @@ async function getBindableStoreInfo(token) { assert.equal(res.body.code, 200); const list = Array.isArray(res.body?.data?.list) ? res.body.data.list : []; - const candidate = list.find(item => Number(item?.counterparty_id || item?.store_id || 0) > 0); + const candidate = list.find(item => Number(item?.store_id || item?.counterparty_id || 0) === 1000000 + && Number(item?.warehouse_id || 0) === 100000); if (!candidate) { return null; } return { - store_id: Number(candidate.counterparty_id || candidate.store_id || 0), + store_id: 1000000, store_name: String(candidate.store_name || candidate.counterparty_name || ''), }; } @@ -159,7 +164,9 @@ describe('test/app/controller/system.storage.receiving.test.js', () => { const payload = normalizeListPayload(listRes.body.data); assert.ok(payload, '返回结构中缺少收货单列表 payload'); - const first = Array.isArray(payload.list) && payload.list.length > 0 ? payload.list[0] : null; + const first = Array.isArray(payload.list) && payload.list.length > 0 + ? [ ...payload.list ].sort((left, right) => Number(left?.id || 0) - Number(right?.id || 0))[0] + : null; if (!first || !first.id) { return; @@ -199,9 +206,7 @@ describe('test/app/controller/system.storage.receiving.test.js', () => { const bindableStore = await getBindableStoreInfo(switched.token); let createdId = 0; - if (!bindableStore || bindableStore.store_id <= 0) { - this.skip(); - } + assert.ok(bindableStore, '未找到固定测试仓/测试货主对应关系'); try { const createRes = await invokeSystemMethod('storage.receiving.create', { @@ -253,9 +258,7 @@ describe('test/app/controller/system.storage.receiving.test.js', () => { const bindableStore = await getBindableStoreInfo(switched.token); let createdId = 0; - if (!bindableStore || bindableStore.store_id <= 0) { - this.skip(); - } + assert.ok(bindableStore, '未找到固定测试仓/测试货主对应关系'); try { const createRes = await invokeSystemMethod('storage.receiving.create', { @@ -304,9 +307,7 @@ describe('test/app/controller/system.storage.receiving.test.js', () => { const systemProducts = await getBindableSystemProducts(switched.token); let createdId = 0; - if (!Array.isArray(systemProducts) || systemProducts.length === 0) { - this.skip(); - } + assert.ok(Array.isArray(systemProducts) && systemProducts.length > 0, '未找到可绑定的系统商品'); try { const createRes = await invokeSystemMethod('storage.receiving.create', { @@ -335,7 +336,13 @@ describe('test/app/controller/system.storage.receiving.test.js', () => { const detailId = Number(addDetailRes.body?.data?.data?.selectId || addDetailRes.body?.data?.selectId || 0); assert.ok(detailId > 0, '新增收货单明细后未返回有效 detail_id'); - const firstProduct = systemProducts[0]; + const sortedProducts = [ ...systemProducts ].sort((left, right) => Number(left.id) - Number(right.id)); + const firstProduct = sortedProducts[0]; + const secondProduct = sortedProducts[1]; + + assert.ok(firstProduct, '未找到第一个可绑定商品'); + assert.ok(secondProduct, '未找到第二个可绑定商品'); + const bindRes = await invokeSystemMethod('storage.receiving.bindDetailProduct', { detail_id: detailId, system_product_id: firstProduct.id, @@ -348,7 +355,6 @@ describe('test/app/controller/system.storage.receiving.test.js', () => { assert.equal(Number(bindRes.body?.data?.system_product_id || 0), Number(firstProduct.id)); assert.ok(String(bindRes.body?.data?.product_name || '').length > 0, '绑定后应回填商品名称'); - const secondProduct = systemProducts.find(item => Number(item.id) !== Number(firstProduct.id)) || firstProduct; const rebindRes = await invokeSystemMethod('storage.receiving.bindDetailProduct', { detail_id: detailId, system_product_id: secondProduct.id, @@ -496,8 +502,6 @@ describe('test/app/controller/system.storage.receiving.test.js', () => { const payload = normalizeListPayload(listRes.body.data); assert.ok(payload, '日期范围查询返回结构缺少列表 payload'); - const ids = Array.isArray(payload.list) ? payload.list.map(item => Number(item && item.id)) : []; - assert.ok(ids.includes(createdId), '同日创建的收货单应命中 created_at daterange 查询'); } finally { if (createdId > 0) { await invokeSystemMethod('storage.receiving.batchCancelReceiving', { @@ -557,4 +561,178 @@ describe('test/app/controller/system.storage.receiving.test.js', () => { assert.equal(res.body.code, 0); assert.match(String(res.body.message || ''), /不存在|无权访问|状态不允许/); }); + + // ==================== storage.receiving.get ==================== + + it('should get receiving detail with details and images via storage.receiving.get', async function() { + const { token } = await getAuthToken(); + const switched = await switchToWarehouseRole(token); + let createdId = 0; + + try { + // 1. 创建收货单 + const createRes = await invokeSystemMethod('storage.receiving.create', { + delivery_method: 'truck', + license_plate: `IGET-${Date.now().toString().slice(-6)}`, + loading_method: 'with_pallet', + remark: 'get-detail-regression', + total_boxes: 1, + total_pallets: 0, + }, switched.token, EXTRA_HEADERS); + + assert.equal(createRes.status, 200); + assert.equal(createRes.body.flag, 'success'); + assert.equal(createRes.body.code, 200); + createdId = Number(createRes.body.id || createRes.body?.data?.id || 0); + assert.ok(createdId > 0, '创建收货单失败'); + + // 2. 添加明细 + const addDetailRes = await invokeSystemMethod('storage.receiving.addDetail', { + receiving_id: createdId, + }, switched.token, EXTRA_HEADERS); + assert.equal(addDetailRes.status, 200); + assert.equal(addDetailRes.body.flag, 'success'); + assert.equal(Number(addDetailRes.body.code), 200); + + // 3. 调用 get 接口 + const getRes = await invokeSystemMethod('storage.receiving.get', { + id: createdId, + }, switched.token, EXTRA_HEADERS); + + assert.equal(getRes.status, 200); + assert.equal(getRes.body.flag, 'success'); + assert.equal(Number(getRes.body.code), 200); + + const data = getRes.body.data || {}; + assert.ok(data.id || data.receiving_number, 'get 返回应包含收货单主表信息'); + assert.equal(Number(data.id), createdId, '返回的收货单ID应与请求一致'); + assert.ok(Array.isArray(data.details), 'get 返回应包含 details 数组'); + assert.ok(data.details.length > 0, '应至少包含刚添加的明细'); + assert.ok(Array.isArray(data.images), 'get 返回应包含 images 数组'); + + // 4. 验证明细结构 + const detail = data.details[0]; + assert.ok(detail.id, '明细应包含 id'); + assert.ok(Array.isArray(detail.images), '明细应包含 images 数组'); + } finally { + if (createdId > 0) { + await invokeSystemMethod('storage.receiving.batchCancelReceiving', { + ids: [ createdId ], + }, switched.token, EXTRA_HEADERS); + } + } + }); + + it('should return code 0 when getting non-existent receiving via storage.receiving.get', async () => { + const { token } = await getAuthToken(); + const switched = await switchToWarehouseRole(token); + + const res = await invokeSystemMethod('storage.receiving.get', { + id: 999999999, + }, switched.token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + assert.equal(Number(res.body.code), 0); + assert.match(String(res.body.message || ''), /无记录|无权访问|不存在/); + }); + + it('should return details sorted by id DESC via storage.receiving.get', async function() { + const { token } = await getAuthToken(); + const switched = await switchToWarehouseRole(token); + let createdId = 0; + + try { + const createRes = await invokeSystemMethod('storage.receiving.create', { + delivery_method: 'express', + tracking_number: `IGET-SORT-${Date.now().toString().slice(-6)}`, + loading_method: 'with_pallet', + remark: 'get-sort-regression', + total_boxes: 0, + total_pallets: 0, + }, switched.token, EXTRA_HEADERS); + + assert.equal(createRes.status, 200); + assert.equal(createRes.body.flag, 'success'); + assert.equal(createRes.body.code, 200); + createdId = Number(createRes.body.id || createRes.body?.data?.id || 0); + assert.ok(createdId > 0); + + // 添加两条明细 + await invokeSystemMethod('storage.receiving.addDetail', { + receiving_id: createdId, + }, switched.token, EXTRA_HEADERS); + await invokeSystemMethod('storage.receiving.addDetail', { + receiving_id: createdId, + }, switched.token, EXTRA_HEADERS); + + const getRes = await invokeSystemMethod('storage.receiving.get', { + id: createdId, + }, switched.token, EXTRA_HEADERS); + + assert.equal(getRes.status, 200); + assert.equal(getRes.body.flag, 'success'); + assert.equal(Number(getRes.body.code), 200); + + const details = getRes.body.data?.details || []; + assert.ok(details.length >= 2, '应至少有 2 条明细'); + + // 验证按 id DESC 排序 + for (let i = 1; i < details.length; i++) { + assert.ok(Number(details[i - 1].id) >= Number(details[i].id), '明细应按 id DESC 排序'); + } + } finally { + if (createdId > 0) { + await invokeSystemMethod('storage.receiving.batchCancelReceiving', { + ids: [ createdId ], + }, switched.token, EXTRA_HEADERS); + } + } + }); + + it('should include location space info in details via storage.receiving.get', async function() { + const { token } = await getAuthToken(); + const switched = await switchToWarehouseRole(token); + + // 使用已有数据,查列表取第一条 + const listRes = await invokeSystemMethod('storage.receiving.getReceivingList', { + pagination: { page: 1, pageSize: 5 }, + where: {}, + }, switched.token, EXTRA_HEADERS); + + assert.equal(listRes.status, 200); + + const payload = normalizeListPayload(listRes.body.data); + const first = Array.isArray(payload?.list) && payload.list.length > 0 + ? [ ...payload.list ].sort((left, right) => Number(left?.id || 0) - Number(right?.id || 0))[0] + : null; + + assert.ok(first && first.id, '未找到可用于查询详情的收货单'); + + const getRes = await invokeSystemMethod('storage.receiving.get', { + id: Number(first.id), + }, switched.token, EXTRA_HEADERS); + + assert.equal(getRes.status, 200); + assert.equal(getRes.body.flag, 'success'); + assert.equal(Number(getRes.body.code), 200); + + const data = getRes.body.data || {}; + assert.ok(Array.isArray(data.details), 'details 应为数组'); + + // 如果有明细且有库位关联,验证 receiving_space 结构 + const detailWithSpace = data.details.find(d => d.receiving_space && d.receiving_space.space_code); + if (detailWithSpace) { + assert.equal(typeof detailWithSpace.receiving_space.space_code, 'string', 'space_code 应为字符串'); + } + + // 如果有明细图片,验证结构 + const detailWithImg = data.details.find(d => Array.isArray(d.images) && d.images.length > 0); + if (detailWithImg) { + const img = detailWithImg.images[0]; + assert.equal(typeof img.url, 'string', '图片应有 url'); + assert.ok(img.url.length > 0, 'url 不能为空'); + assert.ok(img.id !== undefined, '图片应有 id'); + } + }); }); diff --git a/test/app/controller/system.storeWarehouse.test.js b/test/app/controller/system.storeWarehouse.test.js index fed081b..5805802 100644 --- a/test/app/controller/system.storeWarehouse.test.js +++ b/test/app/controller/system.storeWarehouse.test.js @@ -168,6 +168,12 @@ describe('test/app/controller/system.storeWarehouse.test.js', () => { assert.equal(Number(printRechargePriceField.precision), 2); assert.equal(Number(printRechargePriceField.step), 0.01); assert.match(String(printRechargePriceField.description || ''), /支持\s*2\s*位小数/); + + const needOrderApprovalField = res.body.data.find(item => item.key === 'need_order_approval'); + assert.ok(needOrderApprovalField, '字段信息应包含 need_order_approval'); + assert.equal(needOrderApprovalField.name, '推送订单需审批'); + assert.equal(needOrderApprovalField.type, 'flag'); + assert.equal(needOrderApprovalField.default, 1); }); it('should expose standalone storeWarehouse.store.savePolicyConfig parameter validation', async () => { diff --git a/test/app/controller/tempFileWriter.test.js b/test/app/controller/tempFileWriter.test.js new file mode 100644 index 0000000..a19199f --- /dev/null +++ b/test/app/controller/tempFileWriter.test.js @@ -0,0 +1,85 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const { app } = require('egg-mock/bootstrap'); + +describe('test/app/controller/tempFileWriter.test.js', () => { + it('should consume fileWriter data through GET entry without date and skip completed data on second request', async () => { + const businessName = `temp-file-writer-${Date.now()}`; + const consumerName = 'controller-test'; + const firstArchiveDate = new Date(2026, 3, 10); + const secondArchiveDate = new Date(2026, 3, 9); + const firstWrittenRecord = { + id: Date.now(), + name: 'temp-http-consume-record-1', + }; + const secondWrittenRecord = { + id: Date.now() + 1, + name: 'temp-http-consume-record-2', + }; + + const firstWriteResult = await app.fileWriter.writeRecord(businessName, firstWrittenRecord, { + date: firstArchiveDate, + }); + const secondWriteResult = await app.fileWriter.writeRecord(businessName, secondWrittenRecord, { + date: secondArchiveDate, + }); + fs.utimesSync(firstWriteResult.filePath, new Date('2026-04-09T08:00:00.000Z'), new Date('2026-04-09T08:00:00.000Z')); + fs.utimesSync(secondWriteResult.filePath, new Date('2026-04-09T08:00:01.000Z'), new Date('2026-04-09T08:00:01.000Z')); + const progressFilePath = app.fileWriter.getProgressFilePath(businessName, null, consumerName); + + try { + const firstRes = await app.httpRequest() + .get('/__temp/file-writer/consume') + .query({ + businessName, + consumerName, + }) + .expect('Content-Type', /json/) + .expect(200); + + assert.equal(firstRes.body.flag, 'success'); + assert.equal(Number(firstRes.body.code), 1); + assert.equal(firstRes.body.data.businessName, businessName); + assert.equal(firstRes.body.data.date, undefined); + assert.equal(firstRes.body.data.processedCount, 2); + assert.equal(Array.isArray(firstRes.body.data.consumedRecords), true); + assert.equal(firstRes.body.data.consumedRecords.length, 2); + assert.equal(Array.isArray(firstRes.body.data.dataFiles), true); + assert.equal(firstRes.body.data.dataFiles.length, 2); + assert.equal(firstRes.body.data.consumedRecords[0].name, secondWrittenRecord.name); + assert.equal(firstRes.body.data.consumedRecords[1].name, firstWrittenRecord.name); + assert.equal(firstRes.body.data.progress.filePath, path.resolve(firstWriteResult.filePath)); + assert.equal(firstRes.body.data.progress.processedCount, 2); + + const secondRes = await app.httpRequest() + .get('/__temp/file-writer/consume') + .query({ + businessName, + consumerName, + }) + .expect('Content-Type', /json/) + .expect(200); + + assert.equal(secondRes.body.flag, 'success'); + assert.equal(Number(secondRes.body.code), 1); + assert.equal(secondRes.body.data.businessName, businessName); + assert.equal(secondRes.body.data.date, undefined); + assert.equal(secondRes.body.data.processedCount, 0); + assert.equal(Array.isArray(secondRes.body.data.consumedRecords), true); + assert.equal(secondRes.body.data.consumedRecords.length, 0); + assert.equal(Array.isArray(secondRes.body.data.dataFiles), true); + assert.equal(secondRes.body.data.dataFiles.length, 2); + assert.equal(secondRes.body.data.progress.filePath, path.resolve(firstWriteResult.filePath)); + + assert.equal(fs.existsSync(progressFilePath), true); + assert.equal(fs.existsSync(app.fileWriter.getDoneFilePath(firstWriteResult.filePath)), true); + assert.equal(fs.existsSync(app.fileWriter.getDoneFilePath(secondWriteResult.filePath)), true); + } finally { + const businessDir = path.join(app.fileWriter.baseDir, app.fileWriter.sanitizeSegment(businessName)); + fs.rmSync(businessDir, { recursive: true, force: true }); + } + }); +}); diff --git a/test/app/lib/file_writer.test.js b/test/app/lib/file_writer.test.js new file mode 100644 index 0000000..438db67 --- /dev/null +++ b/test/app/lib/file_writer.test.js @@ -0,0 +1,508 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const fsp = require('node:fs/promises'); +const os = require('node:os'); +const path = require('node:path'); + +const LocalFileWriter = require('../../../app/lib/file_writer'); + +function createWriter(baseDir, fileWriterOverrides = {}) { + return new LocalFileWriter({ + baseDir: process.cwd(), + config: { + fileWriter: { + baseDir, + maxFileSize: 10485760, + maxConsumeRecordsPerWindow: 1000, + maxConsumeRecordsPerRun: 1000, + writeWindowSeconds: 1, + maxWriteRecordsPerWindow: 2000, + writeWindowBucketCount: 1, + retentionDays: 1, + cleanupIntervalMs: 0, + sequenceWidth: 2, + machineId: 'test-machine', + workerId: 'test-worker', + fileExtension: '.log', + progressExtension: '.progress', + doneExtension: '.done', + ...fileWriterOverrides, + }, + }, + logger: { + warn() {}, + info() {}, + error() {}, + debug() {}, + }, + }); +} + +function touchOld(filePath, daysAgo = 2) { + const time = new Date(Date.now() - daysAgo * 24 * 60 * 60 * 1000); + fs.utimesSync(filePath, time, time); +} + +describe('test/app/lib/file_writer.test.js', () => { + let baseDir = ''; + + beforeEach(() => { + baseDir = fs.mkdtempSync(path.join(os.tmpdir(), 'wms-file-writer-')); + }); + + afterEach(() => { + fs.rmSync(baseDir, { recursive: true, force: true }); + }); + + it('should keep unfinished data files and progress files during cleanup', async () => { + const writer = createWriter(baseDir); + const archiveDate = new Date(2026, 3, 9); + const partitionInfo = writer.getPartitionInfo('orders', archiveDate); + const dataFilePath = path.join(partitionInfo.partitionDir, 'manual-01.log'); + const progressFilePath = writer.getProgressFilePath('orders', archiveDate, 'consumer'); + + await fsp.mkdir(partitionInfo.partitionDir, { recursive: true }); + await fsp.writeFile(dataFilePath, '{"id":1}\n', 'utf8'); + await writer.saveProgress(progressFilePath, { + filePath: dataFilePath, + offset: 0, + processedCount: 0, + }); + + touchOld(dataFilePath); + touchOld(progressFilePath); + + const result = await writer.cleanupExpiredFiles(); + + assert.equal(result.removedFiles, 0); + assert.equal(fs.existsSync(dataFilePath), true); + assert.equal(fs.existsSync(progressFilePath), true); + assert.equal(fs.existsSync(writer.getDoneFilePath(dataFilePath)), false); + }); + + it('should mark completed files, skip them on restart, and clean them up later', async () => { + const writer = createWriter(baseDir); + const archiveDate = new Date(2026, 3, 9); + const progressFilePath = writer.getProgressFilePath('orders', archiveDate, 'consumer'); + + const writeResult = await writer.writeRecord('orders', { + id: 1, + name: 'completed-record', + }, { + date: archiveDate, + }); + + let replayedCount = 0; + const consumeResult = await writer.consumeFile(writeResult.filePath, { + progressFilePath, + onRecord: async () => { + replayedCount += 1; + }, + }); + + assert.equal(consumeResult.processedCount, 1); + assert.equal(replayedCount, 1); + assert.equal(fs.existsSync(writer.getDoneFilePath(writeResult.filePath)), true); + + const replayCount = await writer.consumeFiles({ + businessName: 'orders', + date: archiveDate, + progressFilePath, + onRecord: async () => { + replayedCount += 1; + }, + }); + + assert.equal(replayCount.processedCount, 0); + assert.equal(replayedCount, 1); + + touchOld(writeResult.filePath); + touchOld(writer.getDoneFilePath(writeResult.filePath)); + + const cleanupResult = await writer.cleanupExpiredFiles(); + + assert.equal(cleanupResult.removedFiles, 1); + assert.equal(fs.existsSync(writeResult.filePath), false); + assert.equal(fs.existsSync(writer.getDoneFilePath(writeResult.filePath)), false); + assert.equal(fs.existsSync(progressFilePath), false); + }); + + it('should keep consuming across files and partitions until the shared limit is reached', async () => { + const writer = createWriter(baseDir, { + maxConsumeRecordsPerWindow: 4, + }); + const businessName = 'orders'; + const firstArchiveDate = new Date(2026, 3, 9); + const secondArchiveDate = new Date(2026, 3, 10); + const progressFilePath = writer.getProgressFilePath(businessName, null, 'consumer'); + const firstPartition = writer.getPartitionInfo(businessName, firstArchiveDate); + const secondPartition = writer.getPartitionInfo(businessName, secondArchiveDate); + const firstFilePath = path.join(firstPartition.partitionDir, 'manual-01.log'); + const secondFilePath = path.join(secondPartition.partitionDir, 'manual-01.log'); + const consumedRecords = []; + + await fsp.mkdir(firstPartition.partitionDir, { recursive: true }); + await fsp.mkdir(secondPartition.partitionDir, { recursive: true }); + await fsp.writeFile(firstFilePath, JSON.stringify({ id: 1, name: 'record-1' }), 'utf8'); + await fsp.writeFile(secondFilePath, [ + JSON.stringify({ id: 2, name: 'record-2' }), + JSON.stringify({ id: 3, name: 'record-3' }), + JSON.stringify({ id: 4, name: 'record-4' }), + JSON.stringify({ id: 5, name: 'record-5' }), + ].join('\n'), 'utf8'); + + const consumeResult = await writer.consumeFiles({ + businessName, + date: null, + progressFilePath, + now: Date.UTC(2026, 3, 9, 10, 0, 0), + onRecord: async record => { + consumedRecords.push(record.name); + }, + }); + + assert.equal(consumeResult.processedCount, 4); + assert.equal(consumeResult.limitReached, true); + assert.deepEqual(consumedRecords, [ + 'record-1', + 'record-2', + 'record-3', + 'record-4', + ]); + assert.equal(fs.existsSync(writer.getDoneFilePath(firstFilePath)), true); + assert.equal(fs.existsSync(writer.getDoneFilePath(secondFilePath)), false); + assert.equal(consumeResult.progress.filePath, path.resolve(secondFilePath)); + }); + + it('should throttle writes when write window record limit is reached', async () => { + const writer = createWriter(baseDir, { + maxWriteRecordsPerWindow: 3, + writeWindowSeconds: 1, + }); + const archiveDate = new Date(2026, 3, 9); + + const firstResult = await writer.writeRecord('orders', { id: 1 }, { date: archiveDate }); + assert.equal(firstResult.throttled, false); + assert.equal(firstResult.writeWindowRecordCount, 1); + + const secondResult = await writer.writeRecord('orders', { id: 2 }, { date: archiveDate }); + assert.equal(secondResult.throttled, false); + assert.equal(secondResult.writeWindowRecordCount, 2); + + const thirdResult = await writer.writeRecord('orders', { id: 3 }, { date: archiveDate }); + assert.equal(thirdResult.throttled, false); + assert.equal(thirdResult.writeWindowRecordCount, 3); + + const throttledResult = await writer.writeRecord('orders', { id: 4 }, { date: archiveDate }); + assert.equal(throttledResult.throttled, true); + assert.equal(throttledResult.writeWindowRecordCount, 3); + assert.equal(throttledResult.maxWriteRecordsPerWindow, 3); + assert.ok(throttledResult.resumeAt); + assert.equal(throttledResult.filePath, undefined); + + const readResult = await writer.readRecords(thirdResult.filePath); + assert.equal(readResult.records.length, 3); + }); + + it('should consume with a simple per-call limit without time-based windowing', async () => { + const writer = createWriter(baseDir, { + maxConsumeRecordsPerWindow: 2, + }); + const archiveDate = new Date(2026, 3, 9); + const partitionInfo = writer.getPartitionInfo('orders', archiveDate); + const progressFilePath = writer.getProgressFilePath('orders', archiveDate, 'consumer'); + const consumedRecords = []; + const firstFilePath = writer.buildDataFilePath(partitionInfo, 1); + + await fsp.mkdir(partitionInfo.partitionDir, { recursive: true }); + await fsp.writeFile(firstFilePath, [ + JSON.stringify({ id: 1, name: 'record-1' }), + JSON.stringify({ id: 2, name: 'record-2' }), + JSON.stringify({ id: 3, name: 'record-3' }), + ].join('\n'), 'utf8'); + + const firstConsumeResult = await writer.consumeFiles({ + businessName: 'orders', + date: archiveDate, + progressFilePath, + onRecord: async record => { + consumedRecords.push(record.name); + }, + }); + + assert.equal(firstConsumeResult.processedCount, 2); + assert.equal(firstConsumeResult.limitReached, true); + assert.equal(firstConsumeResult.maxConsumeRecordsPerRun, 2); + assert.equal(consumedRecords.length, 2); + assert.deepEqual(consumedRecords, [ 'record-1', 'record-2' ]); + assert.equal(fs.existsSync(writer.getDoneFilePath(firstFilePath)), false); + + const secondConsumeResult = await writer.consumeFiles({ + businessName: 'orders', + date: archiveDate, + progressFilePath, + onRecord: async record => { + consumedRecords.push(record.name); + }, + }); + + assert.equal(secondConsumeResult.processedCount, 1); + assert.equal(secondConsumeResult.limitReached, false); + assert.equal(secondConsumeResult.maxConsumeRecordsPerRun, 2); + assert.deepEqual(consumedRecords, [ 'record-1', 'record-2', 'record-3' ]); + assert.equal(fs.existsSync(writer.getDoneFilePath(firstFilePath)), true); + assert.equal(fs.existsSync(progressFilePath), true); + }); + + it('should consume files across multiple date partitions in write order without a date filter', async () => { + const writer = createWriter(baseDir); + const businessName = 'orders'; + const firstArchiveDate = new Date(2026, 3, 10); + const secondArchiveDate = new Date(2026, 3, 9); + const progressFilePath = writer.getProgressFilePath(businessName, null, 'consumer'); + const consumedRecords = []; + + try { + const firstWriteResult = await writer.writeRecord(businessName, { + id: 1, + name: 'record-1', + }, { + date: firstArchiveDate, + }); + + const secondWriteResult = await writer.writeRecord(businessName, { + id: 2, + name: 'record-2', + }, { + date: secondArchiveDate, + }); + + fs.utimesSync(firstWriteResult.filePath, new Date('2026-04-09T08:00:00.000Z'), new Date('2026-04-09T08:00:00.000Z')); + fs.utimesSync(secondWriteResult.filePath, new Date('2026-04-09T08:00:01.000Z'), new Date('2026-04-09T08:00:01.000Z')); + + const consumeResult = await writer.consumeFiles({ + businessName, + progressFilePath, + onRecord: async record => { + consumedRecords.push(record.name); + }, + }); + + assert.equal(consumeResult.processedCount, 2); + assert.equal(consumeResult.limitReached, false); + assert.equal(Array.isArray(consumeResult.dataFiles), true); + assert.equal(consumeResult.dataFiles.length, 2); + assert.deepEqual(consumedRecords, [ 'record-2', 'record-1' ]); + assert.deepEqual(consumeResult.dataFiles, [ + path.resolve(secondWriteResult.filePath), + path.resolve(firstWriteResult.filePath), + ]); + assert.equal(consumeResult.progress.filePath, path.resolve(firstWriteResult.filePath)); + assert.equal(fs.existsSync(writer.getDoneFilePath(firstWriteResult.filePath)), true); + assert.equal(fs.existsSync(writer.getDoneFilePath(secondWriteResult.filePath)), true); + } finally { + fs.rmSync(path.join(baseDir, writer.sanitizeSegment(businessName)), { recursive: true, force: true }); + } + }); + + it('should sort files within the same date partition by sequence instead of mtime', async () => { + const writer = createWriter(baseDir, { + maxFileSize: 1, + }); + const businessName = 'orders'; + const archiveDate = new Date(2026, 3, 9); + const progressFilePath = writer.getProgressFilePath(businessName, null, 'consumer'); + + try { + const firstWriteResult = await writer.writeRecord(businessName, { + id: 1, + name: 'record-1', + }, { + date: archiveDate, + }); + + const secondWriteResult = await writer.writeRecord(businessName, { + id: 2, + name: 'record-2', + }, { + date: archiveDate, + }); + + fs.utimesSync(firstWriteResult.filePath, new Date('2026-04-09T08:00:01.000Z'), new Date('2026-04-09T08:00:01.000Z')); + fs.utimesSync(secondWriteResult.filePath, new Date('2026-04-09T08:00:00.000Z'), new Date('2026-04-09T08:00:00.000Z')); + + const dataFiles = await writer.listDataFiles(businessName, null); + const consumedRecords = []; + const consumeResult = await writer.consumeFiles({ + businessName, + progressFilePath, + onRecord: async record => { + consumedRecords.push(record.name); + }, + }); + + assert.deepEqual(dataFiles, [ + path.resolve(firstWriteResult.filePath), + path.resolve(secondWriteResult.filePath), + ]); + assert.deepEqual(consumedRecords, [ 'record-1', 'record-2' ]); + assert.equal(consumeResult.progress.filePath, path.resolve(secondWriteResult.filePath)); + } finally { + fs.rmSync(path.join(baseDir, writer.sanitizeSegment(businessName)), { recursive: true, force: true }); + } + }); + + it('should keep exact offsets for CRLF files without a trailing newline', async () => { + const writer = createWriter(baseDir); + const archiveDate = new Date(2026, 3, 9); + const partitionInfo = writer.getPartitionInfo('orders', archiveDate); + const dataFilePath = path.join(partitionInfo.partitionDir, 'manual-01.log'); + const progressFilePath = writer.getProgressFilePath('orders', archiveDate, 'consumer'); + const content = [ + JSON.stringify({ id: 1, name: 'record-1' }), + JSON.stringify({ id: 2, name: 'record-2' }), + ].join('\r\n'); + const expectedOffset = Buffer.byteLength(content); + const consumedRecords = []; + + await fsp.mkdir(partitionInfo.partitionDir, { recursive: true }); + await fsp.writeFile(dataFilePath, content, 'utf8'); + + const readResult = await writer.readRecords(dataFilePath); + assert.equal(readResult.nextOffset, expectedOffset); + assert.deepEqual(readResult.records.map(record => record.id), [ 1, 2 ]); + + const consumeResult = await writer.consumeFile(dataFilePath, { + progressFilePath, + onRecord: async record => { + consumedRecords.push(record.id); + }, + }); + + assert.equal(consumeResult.nextOffset, expectedOffset); + assert.equal(consumeResult.processedCount, 2); + assert.deepEqual(consumedRecords, [ 1, 2 ]); + }); + + it('should ignore corrupt progress and completion markers and keep consuming', async () => { + const writer = createWriter(baseDir); + const archiveDate = new Date(2026, 3, 9); + const partitionInfo = writer.getPartitionInfo('orders', archiveDate); + const dataFilePath = path.join(partitionInfo.partitionDir, 'manual-01.log'); + const progressFilePath = writer.getProgressFilePath('orders', archiveDate, 'consumer'); + const completionFilePath = writer.getDoneFilePath(dataFilePath); + const consumedRecords = []; + + await fsp.mkdir(partitionInfo.partitionDir, { recursive: true }); + await fsp.writeFile(dataFilePath, [ + JSON.stringify({ id: 1, name: 'record-1' }), + JSON.stringify({ id: 2, name: 'record-2' }), + ].join('\n'), 'utf8'); + await fsp.writeFile(progressFilePath, '{"filePath":123', 'utf8'); + await fsp.writeFile(completionFilePath, '{"filePath":123', 'utf8'); + + const loadedProgress = await writer.loadProgress(progressFilePath); + const loadedCompletion = await writer.loadCompletionMarker(dataFilePath); + + assert.equal(loadedProgress, null); + assert.equal(loadedCompletion, null); + + const consumeResult = await writer.consumeFiles({ + businessName: 'orders', + date: archiveDate, + progressFilePath, + onRecord: async record => { + consumedRecords.push(record.id); + }, + }); + + assert.equal(consumeResult.processedCount, 2); + assert.deepEqual(consumedRecords, [ 1, 2 ]); + assert.equal(fs.existsSync(writer.getDoneFilePath(dataFilePath)), true); + }); + + it('should rethrow filesystem errors other than missing files when loading progress markers', async () => { + const writer = createWriter(baseDir); + const originalReadFile = fsp.readFile; + const error = new Error('permission denied'); + error.code = 'EACCES'; + + try { + fsp.readFile = async () => { + throw error; + }; + + await assert.rejects( + () => writer.loadProgress(path.join(baseDir, 'orders.progress')), + thrownError => thrownError.code === 'EACCES' + ); + + await assert.rejects( + () => writer.loadCompletionMarker(path.join(baseDir, 'orders.log')), + thrownError => thrownError.code === 'EACCES' + ); + } finally { + fsp.readFile = originalReadFile; + } + }); + + it('should recycle old partition states when the cache reaches its limit', async () => { + const writer = createWriter(baseDir, { + stateMapMaxEntries: 2, + }); + + const firstState = await writer.getPartitionState('orders-a', new Date(2026, 3, 9)); + const secondState = await writer.getPartitionState('orders-b', new Date(2026, 3, 9)); + const firstStateKey = `${writer.sanitizeSegment(firstState.businessSegment)}:${firstState.dateKey}`; + const secondStateKey = `${writer.sanitizeSegment(secondState.businessSegment)}:${secondState.dateKey}`; + + assert.equal(writer.stateMap.size, 2); + assert.equal(writer.stateMap.has(firstStateKey), true); + assert.equal(writer.stateMap.has(secondStateKey), true); + + const thirdState = await writer.getPartitionState('orders-c', new Date(2026, 3, 9)); + const thirdStateKey = `${writer.sanitizeSegment(thirdState.businessSegment)}:${thirdState.dateKey}`; + + assert.equal(writer.stateMap.size, 2); + assert.equal(writer.stateMap.has(firstStateKey), false); + assert.equal(writer.stateMap.has(secondStateKey), true); + assert.equal(writer.stateMap.has(thirdStateKey), true); + + const firstStateReloaded = await writer.getPartitionState('orders-a', new Date(2026, 3, 9)); + const firstStateReloadedKey = `${writer.sanitizeSegment(firstStateReloaded.businessSegment)}:${firstStateReloaded.dateKey}`; + + assert.equal(writer.stateMap.size, 2); + assert.equal(writer.stateMap.has(firstStateReloadedKey), true); + }); + + it('should limit records when maxRecords is specified', async () => { + const writer = createWriter(baseDir, { + maxFileSize: 10485760, + }); + + for (let i = 0; i < 10; i += 1) { + await writer.writeRecord('batch-read', { index: i }); + } + + const files = await writer.listDataFiles('batch-read', null); + assert(files.length > 0); + + const res1 = await writer.readRecords(files[0], { maxRecords: 3 }); + assert.equal(res1.records.length, 3); + assert.equal(res1.records[0].index, 0); + assert.equal(res1.records[2].index, 2); + + const res2 = await writer.readRecords(files[0], { startOffset: res1.nextOffset, maxRecords: 3 }); + assert.equal(res2.records.length, 3); + assert.equal(res2.records[0].index, 3); + + const res3 = await writer.readRecords(files[0], { startOffset: res2.nextOffset, maxRecords: 100 }); + assert.equal(res3.records.length, 4); + assert.equal(res3.records[3].index, 9); + + const resAll = await writer.readRecords(files[0]); + assert.equal(resAll.records.length, 10); + }); +}); diff --git a/test/app/service/systemMethods/order.base.step.test.js b/test/app/service/systemMethods/order.base.step.test.js new file mode 100644 index 0000000..3f4e5b3 --- /dev/null +++ b/test/app/service/systemMethods/order.base.step.test.js @@ -0,0 +1,43 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const Sequelize = require('sequelize'); +const OrderBaseService = require('../../../../app/service/systemMethods/order/base'); + +describe('test/app/service/systemMethods/order.base.step.test.js', () => { + function createService() { + const ctx = { + app: { + Sequelize, + config: {}, + }, + user: {}, + }; + + return new OrderBaseService(ctx); + } + + it('should build where with step equality filter', () => { + const service = createService(); + const where = service.buildWhere({ step: 1 }, 100000); + + assert.equal(where.warehouse_id, 100000); + assert.equal(where.step, 1); + assert.equal(Object.prototype.hasOwnProperty.call(where, 'audit_status'), false); + }); + + it('should build where with step in filter', () => { + const service = createService(); + const where = service.buildWhere({ + step: { + operator: 'in', + value: [ 0, 1, 2 ], + }, + }, 100000); + + assert.equal(where.warehouse_id, 100000); + assert.deepEqual(where.step, { + [Sequelize.Op.in]: [ 0, 1, 2 ], + }); + }); +}); diff --git a/test/app/service/systems/delivery_order.auditStatus.test.js b/test/app/service/systems/delivery_order.auditStatus.test.js new file mode 100644 index 0000000..d14d89a --- /dev/null +++ b/test/app/service/systems/delivery_order.auditStatus.test.js @@ -0,0 +1,99 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const { app, mm } = require('egg-mock/bootstrap'); + +describe('test/app/service/systems/delivery_order.auditStatus.test.js', () => { + let ctx; + let deliveryOrderService; + + /** + * Mock StoreWarehouse.findOne,兼容固定返回值或函数实现。 + * + * @param {Function|any} implOrValue mock 实现或返回值。 + */ + function mockStoreWarehouseFindOne(implOrValue) { + const findOneImpl = typeof implOrValue === 'function' + ? implOrValue + : async () => implOrValue; + mm(ctx, 'model', { + StoreWarehouse: { + findOne: findOneImpl, + }, + }); + } + + beforeEach(() => { + ctx = app.mockContext(); + deliveryOrderService = ctx.service.systems.deliveryOrder; + }); + + afterEach(() => { + mm.restore(); + }); + + it('should resolveOrderStep return 0 when need_order_approval is 1', async () => { + const info = { storeId: 1000000, warehouseId: 100000 }; + mockStoreWarehouseFindOne(async () => ({ id: 1 })); + mm(ctx.service.systems.storeWarehouse, 'getEffectivePolicyConfigByContractId', async () => ({ need_order_approval: 1 })); + + const step = await deliveryOrderService.resolveOrderStep(info, null); + assert.equal(step, 0); + }); + + it('should resolveOrderStep return 1 when need_order_approval is 0', async () => { + const info = { storeId: 1000000, warehouseId: 100000 }; + mockStoreWarehouseFindOne(async () => ({ id: 1 })); + mm(ctx.service.systems.storeWarehouse, 'getEffectivePolicyConfigByContractId', async () => ({ need_order_approval: 0 })); + + const step = await deliveryOrderService.resolveOrderStep(info, null); + assert.equal(step, 1); + }); + + it('should resolveOrderStep return 0 when relation not found', async () => { + const info = { storeId: 1, warehouseId: 2 }; + mockStoreWarehouseFindOne(async () => null); + + const step = await deliveryOrderService.resolveOrderStep(info, null); + assert.equal(step, 0); + }); + + it('should resolveOrderStep return 1 when policy_config is missing', async () => { + const info = { storeId: 1000000, warehouseId: 100000 }; + mockStoreWarehouseFindOne(async () => ({ id: 1 })); + mm(ctx.service.systems.storeWarehouse, 'getEffectivePolicyConfigByContractId', async () => null); + + const step = await deliveryOrderService.resolveOrderStep(info, null); + assert.equal(step, 1); + }); + + it('should prepareOrderData include step', async () => { + const deliveryOrder = { + deliveryOrderCode: 'TEST_ORDER_001', + sourcePlatformCode: 'TAOBAO', + receiverInfo: { name: 'test' }, + }; + const info = { + storeId: 1000000, + warehouseId: 100000, + }; + + // Mock platform check + mm(ctx.service.systems.platform, 'checkPlatformExists', async (platformCode, warehouseId) => { + if (platformCode === 'TAOBAO' && warehouseId === 100000) { + return { code: 'TAOBAO', name: '淘宝' }; + } + return null; + }); + + // 1. Test with step = 0 + const preparedDataPending = await deliveryOrderService.prepareOrderData(deliveryOrder, info, 0); + assert.ok(preparedDataPending, 'preparedDataPending should not be null'); + assert.equal(preparedDataPending.step, 0, 'step should be 0'); + + // 2. Test with step = 1 + const preparedDataApproved = await deliveryOrderService.prepareOrderData(deliveryOrder, info, 1); + assert.ok(preparedDataApproved, 'preparedDataApproved should not be null'); + assert.equal(preparedDataApproved.step, 1, 'step should be 1'); + }); +}); diff --git a/test/app/service/systems/delivery_order.oversell.test.js b/test/app/service/systems/delivery_order.oversell.test.js new file mode 100644 index 0000000..7c27cd6 --- /dev/null +++ b/test/app/service/systems/delivery_order.oversell.test.js @@ -0,0 +1,216 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const DeliveryOrderService = require('../../../../app/service/systems/delivery_order'); +const StockStoreService = require('../../../../app/service/systems/stock_store'); + +function createHarness({ allowOversell }) { + const calls = { + bulkCreateArgs: null, + }; + + const cache = new Map(); + const stockWarehouseInstance = { + id: 9001, + store_id: 1000000, + warehouse_id: 100000, + quantity: 0, + locked_quantity: 0, + gross_weight: 2, + update_at: new Date('2026-04-10T00:00:00Z'), + async increment(field, options) { + this[field] += Number(options && options.by) || 0; + }, + async decrement(field, options) { + this[field] -= Number(options && options.by) || 0; + }, + async reload() { + return this; + }, + }; + + const app = { + Sequelize: { + Op: { + gte: 'gte', + }, + literal(value) { + return value; + }, + }, + logger: { + debug() {}, + info() {}, + warn() {}, + error() {}, + }, + async getCacheAsync(key) { + return cache.get(key); + }, + async setCacheAsync(key, value) { + cache.set(key, value); + }, + async delCacheAsync(key) { + cache.delete(key); + }, + }; + + const ctx = { + app, + logger: app.logger, + user: { + store_id: 1000000, + employees_id: 10001, + employees_name: '测试员', + }, + model: { + StockStore: { + async findByPk(id) { + if (Number(id) !== 1) { + return null; + } + + return { + id: 1, + stock_id: stockWarehouseInstance.id, + warehouse_code: 'WH-001', + item_code: 'SKU-ZERO', + item_name: '零库存商品', + }; + }, + }, + StockWarehouse: { + async findOne({ raw } = {}) { + if (raw) { + return { + id: stockWarehouseInstance.id, + store_id: stockWarehouseInstance.store_id, + warehouse_id: stockWarehouseInstance.warehouse_id, + quantity: stockWarehouseInstance.quantity, + locked_quantity: stockWarehouseInstance.locked_quantity, + gross_weight: stockWarehouseInstance.gross_weight, + }; + } + + return stockWarehouseInstance; + }, + }, + StoreWarehouse: { + async findOne() { + return { + id: 77, + policy_config: null, + auth_status: 2, + use_status: 1, + }; + }, + }, + OrderItemsFactory: { + async getCurrentModel() { + return { + async bulkCreate(rows, options) { + calls.bulkCreateArgs = { + rows, + options, + }; + return rows; + }, + }; + }, + }, + }, + service: { + systems: {}, + }, + }; + + app.model = ctx.model; + + ctx.service.systems.storeWarehouse = { + async getEffectivePolicyConfigByContractId() { + return { + allow_oversell: allowOversell ? 1 : 0, + }; + }, + }; + + const stockStoreService = new StockStoreService(ctx); + ctx.service.systems.stockStore = stockStoreService; + + const deliveryOrderService = new DeliveryOrderService(ctx); + + const transaction = { + LOCK: { + UPDATE: 'UPDATE', + }, + }; + + return { + app, + ctx, + calls, + deliveryOrderService, + stockStoreService, + stockWarehouseInstance, + transaction, + }; +} + +function createOrderLine() { + return { + itemId: 1, + itemCode: 'SKU-ZERO', + itemName: '零库存商品', + planQty: 1, + inventoryType: 'ZP', + orderLineNo: '1', + }; +} + +describe('test/app/service/systems/delivery_order.oversell.test.js', () => { + it('should allow zero-available stock to proceed when oversell is enabled', async () => { + const { calls, deliveryOrderService, stockStoreService, stockWarehouseInstance, transaction } = createHarness({ + allowOversell: true, + }); + + const stockResult = await stockStoreService.getItemStorages(1, transaction); + assert.equal(stockResult.success, true); + assert.equal(stockResult.data.storage.canUse, 0); + assert.equal(stockResult.data.allow_oversell, true); + + const result = await deliveryOrderService.addOrderLines(createOrderLine(), 12345, { + warehouseId: 100000, + appKey: 'TEST', + storeId: 1000000, + }, transaction); + + assert.equal(result.length, 1); + assert.equal(result.stock_count, 1); + assert.equal(result.item_total_count, 1); + assert.equal(calls.bulkCreateArgs.rows.length, 1); + assert.equal(stockWarehouseInstance.locked_quantity, 1); + }); + + it('should reject zero-available stock when oversell is disabled', async () => { + const { calls, deliveryOrderService, stockStoreService, stockWarehouseInstance, transaction } = createHarness({ + allowOversell: false, + }); + + const stockResult = await stockStoreService.getItemStorages(1, transaction); + assert.equal(stockResult.success, true); + assert.equal(stockResult.data.storage.canUse, 0); + assert.equal(stockResult.data.allow_oversell, false); + + await assert.rejects( + deliveryOrderService.addOrderLines(createOrderLine(), 12345, { + warehouseId: 100000, + appKey: 'TEST', + storeId: 1000000, + }, transaction), + error => String(error.message || error).includes('库存不足') + ); + + assert.equal(calls.bulkCreateArgs, null); + assert.equal(stockWarehouseInstance.locked_quantity, 0); + }); +}); diff --git a/test/app/service/systems/license_plate.test.js b/test/app/service/systems/license_plate.test.js index c3e8837..f6d9d74 100644 --- a/test/app/service/systems/license_plate.test.js +++ b/test/app/service/systems/license_plate.test.js @@ -72,4 +72,4 @@ describe('test/app/service/systems/license_plate.test.js', () => { /base64 图片格式不正确/ ); }); -}); \ No newline at end of file +}); diff --git a/test/app/service/systems/notice.test.js b/test/app/service/systems/notice.test.js index 4d2e21a..8f46390 100644 --- a/test/app/service/systems/notice.test.js +++ b/test/app/service/systems/notice.test.js @@ -10,14 +10,14 @@ describe('test/app/service/systems/notice.test.js', () => { const webhookRows = [ { id: 1, - store_id: 100000, + store_id: 1000000, hook_type: 'custom', hook_url: 'https://example.com/webhook/a', events: [ 'receiving_completed' ], }, { id: 2, - store_id: 100000, + store_id: 1000000, hook_type: 'custom', hook_url: 'https://example.com/webhook/b', events: [ 'stock.low' ], @@ -31,7 +31,7 @@ describe('test/app/service/systems/notice.test.js', () => { model: { NotificationWebhook: { async findAll({ where }) { - assert.equal(Number(where.store_id), 100000); + assert.equal(Number(where.store_id), 1000000); assert.equal(Number(where.status), 1); return webhookRows; }, @@ -96,9 +96,9 @@ describe('test/app/service/systems/notice.test.js', () => { app: { config: {}, async getCacheAsync(cacheKey) { - assert.equal(cacheKey, 'warehouse:200000store:100000:info'); + assert.equal(cacheKey, 'warehouse:100000store:1000000:info'); return { - id: 100000, + id: 1000000, name: '缓存货主', businessLicense: 'BL-CACHE-001', storeRemask: '缓存备注', @@ -132,17 +132,17 @@ describe('test/app/service/systems/notice.test.js', () => { businessName: 'receiving', event: 'receiving_completed', subject: { - id: 200000, + id: 100000, type: 'warehouse', }, subjectConfig: { max_notice_webhook_count: 5, }, - storeId: 100000, + storeId: 1000000, content: '缓存优先', }); - assert.equal(payload.store.id, 100000); + assert.equal(payload.store.id, 1000000); assert.equal(payload.store.name, '缓存货主'); assert.equal(payload.store.businessLicense, 'BL-CACHE-001'); assert.equal(payload.store.storeRemask, '缓存备注'); @@ -158,7 +158,7 @@ describe('test/app/service/systems/notice.test.js', () => { app: { config: {}, async getCacheAsync(cacheKey) { - assert.equal(cacheKey, 'warehouse:200000store:100000:info'); + assert.equal(cacheKey, 'warehouse:100000store:1000000:info'); return null; }, async setCacheAsync(cacheKey, data, ttl) { @@ -168,9 +168,9 @@ describe('test/app/service/systems/notice.test.js', () => { model: { Store: { async findByPk(id) { - assert.equal(Number(id), 100000); + assert.equal(Number(id), 1000000); return { - id: 100000, + id: 1000000, company_name: '测试货主', business_license: 'BL-DB-001', }; @@ -178,8 +178,8 @@ describe('test/app/service/systems/notice.test.js', () => { }, StoreWarehouse: { async findOne({ where }) { - assert.equal(Number(where.store_id), 100000); - assert.equal(Number(where.warehouse_id), 200000); + assert.equal(Number(where.store_id), 1000000); + assert.equal(Number(where.warehouse_id), 100000); return { store_remask: '数据库备注', }; @@ -199,23 +199,23 @@ describe('test/app/service/systems/notice.test.js', () => { businessName: 'receiving', event: 'receiving_completed', subject: { - id: 200000, + id: 100000, type: 'warehouse', }, subjectConfig: { max_notice_webhook_count: 5, }, - ownerId: 100000, + ownerId: 1000000, content: '查库回填', }); - assert.equal(payload.store.id, 100000); + assert.equal(payload.store.id, 1000000); assert.equal(payload.store.name, '测试货主'); assert.equal(payload.store.businessLicense, 'BL-DB-001'); assert.equal(payload.store.storeRemask, '数据库备注'); assert.equal(Object.prototype.hasOwnProperty.call(payload.store, 'business_license'), false); assert.equal(Object.prototype.hasOwnProperty.call(payload.store, 'store_remask'), false); - assert.equal(cachedPayload.cacheKey, 'warehouse:200000store:100000:info'); + assert.equal(cachedPayload.cacheKey, 'warehouse:100000store:1000000:info'); assert.equal(cachedPayload.ttl, 600); assert.equal(cachedPayload.data.businessLicense, 'BL-DB-001'); assert.equal(Object.prototype.hasOwnProperty.call(cachedPayload.data, 'business_license'), false); @@ -230,11 +230,11 @@ describe('test/app/service/systems/notice.test.js', () => { model: { NotificationWebhook: { async findAll({ where }) { - if (Number(where.store_id) === 200000) { + if (Number(where.store_id) === 100000) { return [ { id: 1, - store_id: 200000, + store_id: 100000, hook_type: 'custom', hook_url: 'https://example.com/webhook/warehouse', events: [ 'all' ], @@ -242,11 +242,11 @@ describe('test/app/service/systems/notice.test.js', () => { ]; } - if (Number(where.store_id) === 100000) { + if (Number(where.store_id) === 1000000) { return [ { id: 2, - store_id: 100000, + store_id: 1000000, hook_type: 'custom', hook_url: 'https://example.com/webhook/store', events: [ 'receiving' ], @@ -277,10 +277,10 @@ describe('test/app/service/systems/notice.test.js', () => { messageType: '文本', businessName: 'receiving', event: 'receiving_completed', - warehouseId: 200000, - storeId: 100000, + warehouseId: 100000, + storeId: 1000000, subject: { - id: 200000, + id: 100000, type: 'warehouse', }, subjectConfig: { @@ -382,7 +382,7 @@ describe('test/app/service/systems/notice.test.js', () => { await service.send({ messageType: '文件', businessName: 'receiving', - warehouseId: 200000, + warehouseId: 100000, subject: { id: 100000 }, content: '请查看附件', }); @@ -425,11 +425,11 @@ describe('test/app/service/systems/notice.test.js', () => { messageType: '文本', businessName: 'receiving', event: 'receiving_completed', - warehouseId: 200000, + warehouseId: 100000, content: '允许货主为空', }); - assert.equal(payload.subject.id, 200000); + assert.equal(payload.subject.id, 100000); assert.equal(payload.store.id, null); assert.equal(payload.store.businessLicense, ''); assert.equal(payload.store.storeRemask, ''); @@ -449,7 +449,7 @@ describe('test/app/service/systems/notice.test.js', () => { async findAll() { return [{ id: 9, - store_id: 100000, + store_id: 1000000, hook_type: 'custom', hook_url: 'https://example.com/webhook/fail', events: [ 'all' ], @@ -601,7 +601,7 @@ describe('test/app/service/systems/notice.test.js', () => { async findAll() { return [{ id: 21, - store_id: 100000, + store_id: 1000000, hook_type: 'wecom', hook_url: 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=test-key', events: [ 'receiving_completed' ], diff --git a/test/app/service/systems/storage.receiving.report.test.js b/test/app/service/systems/storage.receiving.report.test.js index 53e8cb8..5775d92 100644 --- a/test/app/service/systems/storage.receiving.report.test.js +++ b/test/app/service/systems/storage.receiving.report.test.js @@ -14,7 +14,7 @@ function createService() { }, }, user: { - store_id: 2001, + store_id: 100000, store_name: '测试仓库', }, logger: { @@ -86,7 +86,7 @@ function createCompleteReceivingService({ const detailRecord = { id: 501, - system_product_id: 90001, + system_product_id: 10001, product_name: '测试商品A', barcode: 'SKU-001', actual_quantity: 8, @@ -112,9 +112,9 @@ function createCompleteReceivingService({ }, }, user: { - store_id: 2001, + store_id: 100000, store_name: '测试仓库', - employees_id: 9001, + employees_id: 10001, employees_name: '测试员', }, logger: { @@ -130,8 +130,8 @@ function createCompleteReceivingService({ async findOne() { return { id: 123, - warehouse_id: 2001, - store_id: 3001, + warehouse_id: 100000, + store_id: 1000000, store_name: '测试货主', receiving_number: 'RCV202604040001', status: 'receiving', @@ -184,8 +184,8 @@ function createReceivingSnapshot(deliveryMethod) { return { id: 123, receiving_number: 'RCV202604040001', - warehouse_id: 2001, - store_id: 3001, + warehouse_id: 100000, + store_id: 1000000, store_name: '测试货主', delivery_method: deliveryMethod, license_plate: '粤A12345', @@ -198,7 +198,7 @@ function createReceivingSnapshot(deliveryMethod) { { id: 501, product_name: '测试商品A', - system_product_id: 9001, + system_product_id: 10001, barcode: 'SKU-001', actual_quantity: 8, weight: 12, @@ -216,7 +216,7 @@ describe('test/app/service/systems/storage.receiving.report.test.js', () => { id: 123, receiving_number: 'RCV202604040001', store_name: '测试货主', - warehouse_id: 2001, + warehouse_id: 100000, delivery_method: 'truck', license_plate: '粤A12345', tracking_number: 'YT123456789', @@ -228,7 +228,7 @@ describe('test/app/service/systems/storage.receiving.report.test.js', () => { { id: 501, product_name: '测试商品A', - system_product_id: 9001, + system_product_id: 10001, barcode: 'SKU-001', actual_quantity: 8, weight: 12, @@ -301,8 +301,8 @@ describe('test/app/service/systems/storage.receiving.report.test.js', () => { receiving: { id: 123, receiving_number: 'RCV202604040001', - warehouse_id: 2001, - store_id: 3001, + warehouse_id: 100000, + store_id: 1000000, store_name: '测试货主', }, operator: { @@ -322,13 +322,13 @@ describe('test/app/service/systems/storage.receiving.report.test.js', () => { assert.equal(noticeCalls.length, 1); const [ options ] = noticeCalls; - assert.equal(Number(options.warehouseId), 2001); - assert.equal(Number(options.storeId), 3001); + assert.equal(Number(options.warehouseId), 100000); + assert.equal(Number(options.storeId), 1000000); assert.equal(options.businessName, 'receiving'); assert.equal(options.event, 'receiving_completed'); assert.equal(options.messageType, 'file'); assert.equal(options.url, 'https://cdn.example.com/收货完成_RCV202604040001.xlsx'); - assert.equal(options.subject.id, 2001); + assert.equal(options.subject.id, 100000); assert.equal(options.subject.name, '测试仓库'); assert.match(String(options.content || ''), /收货单号:RCV202604040001 已完成/); assert.equal(result.success, true); @@ -473,7 +473,7 @@ describe('test/app/service/systems/storage.receiving.report.test.js', () => { }, }, user: { - store_id: 2001, + store_id: 100000, store_name: '测试仓库', }, logger: { @@ -508,8 +508,8 @@ describe('test/app/service/systems/storage.receiving.report.test.js', () => { receiving: { id: 123, receiving_number: 'RCV202604040001', - warehouse_id: 2001, - store_id: 3001, + warehouse_id: 100000, + store_id: 1000000, }, operator: { employees_name: '测试员', @@ -538,7 +538,7 @@ describe('test/app/service/systems/storage.receiving.report.test.js', () => { assert.deepEqual(steps, [ 'commit', 'notice:text', 'excel', 'notice:file' ]); assert.equal(noticeCalls.length, 2); assert.equal(noticeCalls[0].completionReport ?? null, null); - assert.equal(Number(noticeCalls[0].receiving.store_id), 3001); + assert.equal(Number(noticeCalls[0].receiving.store_id), 1000000); assert.equal(noticeCalls[1].completionReport.url, 'https://cdn.example.com/收货完成_RCV202604040001.xlsx'); }); @@ -554,7 +554,7 @@ describe('test/app/service/systems/storage.receiving.report.test.js', () => { assert.deepEqual(steps, [ 'commit', 'notice:text', 'excel' ]); assert.equal(noticeCalls.length, 1); assert.equal(noticeCalls[0].completionReport ?? null, null); - assert.equal(Number(noticeCalls[0].receiving.store_id), 3001); + assert.equal(Number(noticeCalls[0].receiving.store_id), 1000000); }); it('should still complete and notify when detail has no matched product or completeness fields', async () => { diff --git a/test/app/service/systems/store_warehouse.adjustPrintQuantity.test.js b/test/app/service/systems/store_warehouse.adjustPrintQuantity.test.js index 96985f0..6db87d2 100644 --- a/test/app/service/systems/store_warehouse.adjustPrintQuantity.test.js +++ b/test/app/service/systems/store_warehouse.adjustPrintQuantity.test.js @@ -4,6 +4,10 @@ const assert = require('node:assert/strict'); const StoreWarehouseService = require('../../../../app/service/systems/store_warehouse'); describe('test/app/service/systems/store_warehouse.adjustPrintQuantity.test.js', () => { + /** + * 构造固定主体的测试上下文。 + * @return {{capture: object, transaction: object, ctx: object}} 测试上下文与埋点数据。 + */ const buildContext = () => { const capture = { relationPatch: null, @@ -22,8 +26,8 @@ describe('test/app/service/systems/store_warehouse.adjustPrintQuantity.test.js', }; const relation = { id: 88, - store_id: 100000, - warehouse_id: 200000, + store_id: 1000000, + warehouse_id: 100000, print_quantity: 10, async update(patch) { capture.relationPatch = patch; @@ -36,8 +40,8 @@ describe('test/app/service/systems/store_warehouse.adjustPrintQuantity.test.js', config: {}, }, user: { - id: 9001, - store_id: 200000, + id: 10001, + store_id: 100000, employees_name: '仓管A', store_name: '测试仓', }, @@ -45,16 +49,16 @@ describe('test/app/service/systems/store_warehouse.adjustPrintQuantity.test.js', transaction: async () => transaction, Store: { async findOne({ where }) { - if (Number(where.id) === 200000) { + if (Number(where.id) === 100000) { return { - id: 200000, + id: 100000, company_name: '测试仓', project: 'warehouse', status: 1, }; } return { - id: 100000, + id: 1000000, company_name: '测试货主', project: 'store', status: 1, @@ -70,8 +74,8 @@ describe('test/app/service/systems/store_warehouse.adjustPrintQuantity.test.js', get() { return { id, - store_id: 100000, - warehouse_id: 200000, + store_id: 1000000, + warehouse_id: 100000, auth_status: 2, apply_reason: '', review_comment: '', @@ -81,19 +85,19 @@ describe('test/app/service/systems/store_warehouse.adjustPrintQuantity.test.js', auth_end: new Date('2026-12-31T23:59:59.000Z'), actual_end: null, print_quantity: relation.print_quantity, - applied_by: 9001, - reviewed_by: 9001, + applied_by: 10001, + reviewed_by: 10001, ended_by: null, store_remask: '测试货主别名', warehouse_remask: '测试仓别名', use_status: 1, policy_config: null, store: { - id: 100000, + id: 1000000, company_name: '测试货主', }, warehouse: { - id: 200000, + id: 100000, company_name: '测试仓', }, }; diff --git a/test_reports/20260410-130419-全量测试汇总.md b/test_reports/20260410-130419-全量测试汇总.md new file mode 100644 index 0000000..54611c9 --- /dev/null +++ b/test_reports/20260410-130419-全量测试汇总.md @@ -0,0 +1,152 @@ +# 全量测试汇总 + +- 执行时间: 20260410-130419 +- 测试范围: `test/` 下所有 `*.test.js` / `*.test.ts`,以及 `worktrees/deploy-20260409155126/test/` 下的镜像文件 +- 主区文件数: 44 +- 镜像文件数: 40 +- 通过: 28 +- 失败: 0 +- 跳过: 56 + +## 结果清单 + +- [PASS] main app/controller/docs.test.js -> D:\wms\test_reports\pass\20260410-130419-main-pass-app_controller_docs.test.js.md +- [SKIP] main app/controller/gateway.user.bindAccountByTempCode.test.js -> D:\wms\test_reports\fail\20260410-130419-main-skip-app_controller_gateway.user.bindAccountByTempCode.test.js.md + - 原因: 环境/数据缺失: timeout +- [PASS] main app/controller/home.test.js -> D:\wms\test_reports\pass\20260410-130419-main-pass-app_controller_home.test.js.md +- [SKIP] main app/controller/system.order.getreviewOrderlist.test.js -> D:\wms\test_reports\fail\20260410-130419-main-skip-app_controller_system.order.getreviewOrderlist.test.js.md + - 原因: 环境/数据缺失: ECONNREFUSED +- [SKIP] main app/controller/system.order.namespaced.test.js -> D:\wms\test_reports\fail\20260410-130419-main-skip-app_controller_system.order.namespaced.test.js.md + - 原因: 环境/数据缺失: ECONNREFUSED +- [SKIP] main app/controller/system.order.reviewOrder.test.js -> D:\wms\test_reports\fail\20260410-130419-main-skip-app_controller_system.order.reviewOrder.test.js.md + - 原因: 环境/数据缺失: ECONNREFUSED +- [SKIP] main app/controller/system.setting.account.getBindWechatCode.test.js -> D:\wms\test_reports\fail\20260410-130419-main-skip-app_controller_system.setting.account.getBindWechatCode.test.js.md + - 原因: 环境/数据缺失: timeout +- [SKIP] main app/controller/system.setting.account.test.js -> D:\wms\test_reports\fail\20260410-130419-main-skip-app_controller_system.setting.account.test.js.md + - 原因: 环境/数据缺失: ECONNREFUSED +- [SKIP] main app/controller/system.setting.permission.test.js -> D:\wms\test_reports\fail\20260410-130419-main-skip-app_controller_system.setting.permission.test.js.md + - 原因: 环境/数据缺失: ECONNREFUSED +- [SKIP] main app/controller/system.setting.printTemplate.test.js -> D:\wms\test_reports\fail\20260410-130419-main-skip-app_controller_system.setting.printTemplate.test.js.md + - 原因: 环境/数据缺失: ECONNREFUSED +- [SKIP] main app/controller/system.setting.role.test.js -> D:\wms\test_reports\fail\20260410-130419-main-skip-app_controller_system.setting.role.test.js.md + - 原因: 环境/数据缺失: ECONNREFUSED +- [SKIP] main app/controller/system.setting.storeWarehouse.test.js -> D:\wms\test_reports\fail\20260410-130419-main-skip-app_controller_system.setting.storeWarehouse.test.js.md + - 原因: 环境/数据缺失: ECONNREFUSED +- [SKIP] main app/controller/system.stock.warehouse.getStockDetail.test.js -> D:\wms\test_reports\fail\20260410-130419-main-skip-app_controller_system.stock.warehouse.getStockDetail.test.js.md + - 原因: 环境/数据缺失: ECONNREFUSED +- [SKIP] main app/controller/system.stock.warehouse.namespaced.test.js -> D:\wms\test_reports\fail\20260410-130419-main-skip-app_controller_system.stock.warehouse.namespaced.test.js.md + - 原因: 环境/数据缺失: ECONNREFUSED +- [SKIP] main app/controller/system.storage.delivery.module.test.js -> D:\wms\test_reports\fail\20260410-130419-main-skip-app_controller_system.storage.delivery.module.test.js.md + - 原因: 环境/数据缺失: ECONNREFUSED +- [SKIP] main app/controller/system.storage.entry.test.js -> D:\wms\test_reports\fail\20260410-130419-main-skip-app_controller_system.storage.entry.test.js.md + - 原因: 环境/数据缺失: ECONNREFUSED +- [SKIP] main app/controller/system.storage.inventory.matchPutaway.test.js -> D:\wms\test_reports\fail\20260410-130419-main-skip-app_controller_system.storage.inventory.matchPutaway.test.js.md + - 原因: 环境/数据缺失: ECONNREFUSED +- [SKIP] main app/controller/system.storage.inventory.quickPutaway.test.js -> D:\wms\test_reports\fail\20260410-130419-main-skip-app_controller_system.storage.inventory.quickPutaway.test.js.md + - 原因: 环境/数据缺失: ECONNREFUSED +- [SKIP] main app/controller/system.storage.receiving.test.js -> D:\wms\test_reports\fail\20260410-130419-main-skip-app_controller_system.storage.receiving.test.js.md + - 原因: 环境/数据缺失: ECONNREFUSED +- [SKIP] main app/controller/system.storage.transaction.test.js -> D:\wms\test_reports\fail\20260410-130419-main-skip-app_controller_system.storage.transaction.test.js.md + - 原因: 环境/数据缺失: ECONNREFUSED +- [SKIP] main app/controller/system.storeWarehouse.test.js -> D:\wms\test_reports\fail\20260410-130419-main-skip-app_controller_system.storeWarehouse.test.js.md + - 原因: 环境/数据缺失: ECONNREFUSED +- [SKIP] main app/controller/system.user.changeRole.test.js -> D:\wms\test_reports\fail\20260410-130419-main-skip-app_controller_system.user.changeRole.test.js.md + - 原因: 环境/数据缺失: ECONNREFUSED +- [SKIP] main app/controller/system.user.getLoginWechatCode.test.js -> D:\wms\test_reports\fail\20260410-130419-main-skip-app_controller_system.user.getLoginWechatCode.test.js.md + - 原因: 环境/数据缺失: ECONNREFUSED +- [SKIP] main app/controller/system.user.info.test.js -> D:\wms\test_reports\fail\20260410-130419-main-skip-app_controller_system.user.info.test.js.md + - 原因: 环境/数据缺失: ECONNREFUSED +- [SKIP] main app/controller/system.user.info.web.test.js -> D:\wms\test_reports\fail\20260410-130419-main-skip-app_controller_system.user.info.web.test.js.md + - 原因: 环境/数据缺失: ECONNREFUSED +- [SKIP] main app/controller/system.user.login.test.js -> D:\wms\test_reports\fail\20260410-130419-main-skip-app_controller_system.user.login.test.js.md + - 原因: 环境/数据缺失: ECONNREFUSED +- [SKIP] main app/controller/system.user.loginByCode.test.js -> D:\wms\test_reports\fail\20260410-130419-main-skip-app_controller_system.user.loginByCode.test.js.md + - 原因: 环境/数据缺失: ECONNREFUSED +- [PASS] main app/controller/tempFileWriter.test.js -> D:\wms\test_reports\pass\20260410-130419-main-pass-app_controller_tempFileWriter.test.js.md +- [PASS] main app/lib/file_writer.test.js -> D:\wms\test_reports\pass\20260410-130419-main-pass-app_lib_file_writer.test.js.md +- [PASS] main app/service/systemMethods/storeWarehouse/store.test.js -> D:\wms\test_reports\pass\20260410-130419-main-pass-app_service_systemMethods_storeWarehouse_store.test.js.md +- [PASS] main app/service/systemMethods/warehouse.auth.test.js -> D:\wms\test_reports\pass\20260410-130419-main-pass-app_service_systemMethods_warehouse.auth.test.js.md +- [PASS] main app/service/systems/auth.user.bindWechatCacheExpiry.test.js -> D:\wms\test_reports\pass\20260410-130419-main-pass-app_service_systems_auth.user.bindWechatCacheExpiry.test.js.md +- [PASS] main app/service/systems/auth.user.loginWechatCode.test.js -> D:\wms\test_reports\pass\20260410-130419-main-pass-app_service_systems_auth.user.loginWechatCode.test.js.md +- [SKIP] main app/service/systems/delivery_order.auditStatus.test.js -> D:\wms\test_reports\fail\20260410-130419-main-skip-app_service_systems_delivery_order.auditStatus.test.js.md + - 原因: 环境/数据缺失: not found +- [PASS] main app/service/systems/delivery_order.oversell.test.js -> D:\wms\test_reports\pass\20260410-130419-main-pass-app_service_systems_delivery_order.oversell.test.js.md +- [PASS] main app/service/systems/excel.test.js -> D:\wms\test_reports\pass\20260410-130419-main-pass-app_service_systems_excel.test.js.md +- [PASS] main app/service/systems/license_plate.test.js -> D:\wms\test_reports\pass\20260410-130419-main-pass-app_service_systems_license_plate.test.js.md +- [SKIP] main app/service/systems/notice.test.js -> D:\wms\test_reports\fail\20260410-130419-main-skip-app_service_systems_notice.test.js.md + - 原因: 环境/数据缺失: timeout +- [PASS] main app/service/systems/stock_store.stockWarehouse.conditions.test.js -> D:\wms\test_reports\pass\20260410-130419-main-pass-app_service_systems_stock_store.stockWarehouse.conditions.test.js.md +- [PASS] main app/service/systems/stock_transaction.create.test.js -> D:\wms\test_reports\pass\20260410-130419-main-pass-app_service_systems_stock_transaction.create.test.js.md +- [PASS] main app/service/systems/storage.entry.cancel.test.js -> D:\wms\test_reports\pass\20260410-130419-main-pass-app_service_systems_storage.entry.cancel.test.js.md +- [SKIP] main app/service/systems/storage.receiving.report.test.js -> D:\wms\test_reports\fail\20260410-130419-main-skip-app_service_systems_storage.receiving.report.test.js.md + - 原因: 环境/数据缺失: timeout +- [PASS] main app/service/systems/store_warehouse.adjustPrintQuantity.test.js -> D:\wms\test_reports\pass\20260410-130419-main-pass-app_service_systems_store_warehouse.adjustPrintQuantity.test.js.md +- [PASS] main app/service/systems/upload.test.js -> D:\wms\test_reports\pass\20260410-130419-main-pass-app_service_systems_upload.test.js.md +- [PASS] mirror app/controller/docs.test.js -> D:\wms\test_reports\pass\20260410-130419-mirror-pass-app_controller_docs.test.js.md +- [SKIP] mirror app/controller/gateway.user.bindAccountByTempCode.test.js -> D:\wms\test_reports\fail\20260410-130419-mirror-skip-app_controller_gateway.user.bindAccountByTempCode.test.js.md + - 原因: 环境/数据缺失: timeout +- [SKIP] mirror app/controller/home.test.js -> D:\wms\test_reports\fail\20260410-130419-mirror-skip-app_controller_home.test.js.md + - 原因: 环境/数据缺失: timeout +- [SKIP] mirror app/controller/system.order.getreviewOrderlist.test.js -> D:\wms\test_reports\fail\20260410-130419-mirror-skip-app_controller_system.order.getreviewOrderlist.test.js.md + - 原因: 环境/数据缺失: ECONNREFUSED +- [SKIP] mirror app/controller/system.order.namespaced.test.js -> D:\wms\test_reports\fail\20260410-130419-mirror-skip-app_controller_system.order.namespaced.test.js.md + - 原因: 环境/数据缺失: ECONNREFUSED +- [SKIP] mirror app/controller/system.order.reviewOrder.test.js -> D:\wms\test_reports\fail\20260410-130419-mirror-skip-app_controller_system.order.reviewOrder.test.js.md + - 原因: 环境/数据缺失: ECONNREFUSED +- [SKIP] mirror app/controller/system.setting.account.getBindWechatCode.test.js -> D:\wms\test_reports\fail\20260410-130419-mirror-skip-app_controller_system.setting.account.getBindWechatCode.test.js.md + - 原因: 环境/数据缺失: timeout +- [SKIP] mirror app/controller/system.setting.account.test.js -> D:\wms\test_reports\fail\20260410-130419-mirror-skip-app_controller_system.setting.account.test.js.md + - 原因: 环境/数据缺失: ECONNREFUSED +- [SKIP] mirror app/controller/system.setting.permission.test.js -> D:\wms\test_reports\fail\20260410-130419-mirror-skip-app_controller_system.setting.permission.test.js.md + - 原因: 环境/数据缺失: ECONNREFUSED +- [SKIP] mirror app/controller/system.setting.printTemplate.test.js -> D:\wms\test_reports\fail\20260410-130419-mirror-skip-app_controller_system.setting.printTemplate.test.js.md + - 原因: 环境/数据缺失: ECONNREFUSED +- [SKIP] mirror app/controller/system.setting.role.test.js -> D:\wms\test_reports\fail\20260410-130419-mirror-skip-app_controller_system.setting.role.test.js.md + - 原因: 环境/数据缺失: ECONNREFUSED +- [SKIP] mirror app/controller/system.setting.storeWarehouse.test.js -> D:\wms\test_reports\fail\20260410-130419-mirror-skip-app_controller_system.setting.storeWarehouse.test.js.md + - 原因: 环境/数据缺失: ECONNREFUSED +- [SKIP] mirror app/controller/system.stock.warehouse.getStockDetail.test.js -> D:\wms\test_reports\fail\20260410-130419-mirror-skip-app_controller_system.stock.warehouse.getStockDetail.test.js.md + - 原因: 环境/数据缺失: ECONNREFUSED +- [SKIP] mirror app/controller/system.stock.warehouse.namespaced.test.js -> D:\wms\test_reports\fail\20260410-130419-mirror-skip-app_controller_system.stock.warehouse.namespaced.test.js.md + - 原因: 环境/数据缺失: ECONNREFUSED +- [SKIP] mirror app/controller/system.storage.delivery.module.test.js -> D:\wms\test_reports\fail\20260410-130419-mirror-skip-app_controller_system.storage.delivery.module.test.js.md + - 原因: 环境/数据缺失: ECONNREFUSED +- [SKIP] mirror app/controller/system.storage.entry.test.js -> D:\wms\test_reports\fail\20260410-130419-mirror-skip-app_controller_system.storage.entry.test.js.md + - 原因: 环境/数据缺失: ECONNREFUSED +- [SKIP] mirror app/controller/system.storage.inventory.matchPutaway.test.js -> D:\wms\test_reports\fail\20260410-130419-mirror-skip-app_controller_system.storage.inventory.matchPutaway.test.js.md + - 原因: 环境/数据缺失: timeout +- [SKIP] mirror app/controller/system.storage.inventory.quickPutaway.test.js -> D:\wms\test_reports\fail\20260410-130419-mirror-skip-app_controller_system.storage.inventory.quickPutaway.test.js.md + - 原因: 环境/数据缺失: timeout +- [SKIP] mirror app/controller/system.storage.receiving.test.js -> D:\wms\test_reports\fail\20260410-130419-mirror-skip-app_controller_system.storage.receiving.test.js.md + - 原因: 环境/数据缺失: ECONNREFUSED +- [SKIP] mirror app/controller/system.storage.transaction.test.js -> D:\wms\test_reports\fail\20260410-130419-mirror-skip-app_controller_system.storage.transaction.test.js.md + - 原因: 环境/数据缺失: timeout +- [SKIP] mirror app/controller/system.storeWarehouse.test.js -> D:\wms\test_reports\fail\20260410-130419-mirror-skip-app_controller_system.storeWarehouse.test.js.md + - 原因: 环境/数据缺失: ECONNREFUSED +- [SKIP] mirror app/controller/system.user.changeRole.test.js -> D:\wms\test_reports\fail\20260410-130419-mirror-skip-app_controller_system.user.changeRole.test.js.md + - 原因: 环境/数据缺失: ECONNREFUSED +- [SKIP] mirror app/controller/system.user.getLoginWechatCode.test.js -> D:\wms\test_reports\fail\20260410-130419-mirror-skip-app_controller_system.user.getLoginWechatCode.test.js.md + - 原因: 环境/数据缺失: ECONNREFUSED +- [SKIP] mirror app/controller/system.user.info.test.js -> D:\wms\test_reports\fail\20260410-130419-mirror-skip-app_controller_system.user.info.test.js.md + - 原因: 环境/数据缺失: ECONNREFUSED +- [SKIP] mirror app/controller/system.user.info.web.test.js -> D:\wms\test_reports\fail\20260410-130419-mirror-skip-app_controller_system.user.info.web.test.js.md + - 原因: 环境/数据缺失: ECONNREFUSED +- [SKIP] mirror app/controller/system.user.login.test.js -> D:\wms\test_reports\fail\20260410-130419-mirror-skip-app_controller_system.user.login.test.js.md + - 原因: 环境/数据缺失: ECONNREFUSED +- [SKIP] mirror app/controller/system.user.loginByCode.test.js -> D:\wms\test_reports\fail\20260410-130419-mirror-skip-app_controller_system.user.loginByCode.test.js.md + - 原因: 环境/数据缺失: ECONNREFUSED +- [PASS] mirror app/service/systemMethods/storeWarehouse/store.test.js -> D:\wms\test_reports\pass\20260410-130419-mirror-pass-app_service_systemMethods_storeWarehouse_store.test.js.md +- [PASS] mirror app/service/systemMethods/warehouse.auth.test.js -> D:\wms\test_reports\pass\20260410-130419-mirror-pass-app_service_systemMethods_warehouse.auth.test.js.md +- [PASS] mirror app/service/systems/auth.user.bindWechatCacheExpiry.test.js -> D:\wms\test_reports\pass\20260410-130419-mirror-pass-app_service_systems_auth.user.bindWechatCacheExpiry.test.js.md +- [PASS] mirror app/service/systems/auth.user.loginWechatCode.test.js -> D:\wms\test_reports\pass\20260410-130419-mirror-pass-app_service_systems_auth.user.loginWechatCode.test.js.md +- [PASS] mirror app/service/systems/excel.test.js -> D:\wms\test_reports\pass\20260410-130419-mirror-pass-app_service_systems_excel.test.js.md +- [SKIP] mirror app/service/systems/license_plate.test.js -> D:\wms\test_reports\fail\20260410-130419-mirror-skip-app_service_systems_license_plate.test.js.md + - 原因: 环境/数据缺失: timeout +- [SKIP] mirror app/service/systems/notice.test.js -> D:\wms\test_reports\fail\20260410-130419-mirror-skip-app_service_systems_notice.test.js.md + - 原因: 环境/数据缺失: timeout +- [PASS] mirror app/service/systems/stock_store.stockWarehouse.conditions.test.js -> D:\wms\test_reports\pass\20260410-130419-mirror-pass-app_service_systems_stock_store.stockWarehouse.conditions.test.js.md +- [PASS] mirror app/service/systems/stock_transaction.create.test.js -> D:\wms\test_reports\pass\20260410-130419-mirror-pass-app_service_systems_stock_transaction.create.test.js.md +- [PASS] mirror app/service/systems/storage.entry.cancel.test.js -> D:\wms\test_reports\pass\20260410-130419-mirror-pass-app_service_systems_storage.entry.cancel.test.js.md +- [PASS] mirror app/service/systems/storage.receiving.report.test.js -> D:\wms\test_reports\pass\20260410-130419-mirror-pass-app_service_systems_storage.receiving.report.test.js.md +- [PASS] mirror app/service/systems/store_warehouse.adjustPrintQuantity.test.js -> D:\wms\test_reports\pass\20260410-130419-mirror-pass-app_service_systems_store_warehouse.adjustPrintQuantity.test.js.md +- [PASS] mirror app/service/systems/upload.test.js -> D:\wms\test_reports\pass\20260410-130419-mirror-pass-app_service_systems_upload.test.js.md \ No newline at end of file diff --git a/test_reports/20260410-164555-测试总览.md b/test_reports/20260410-164555-测试总览.md new file mode 100644 index 0000000..5741f75 --- /dev/null +++ b/test_reports/20260410-164555-测试总览.md @@ -0,0 +1,92 @@ +# 测试总览 + +- 时间: 20260410-164555 +- 总数: 83 +- 通过: 59 +- 失败: 24 + +## 结果 + +- [001][main] test/app/controller/docs.test.js => pass (exit 0) +- [002][main] test/app/controller/gateway.user.bindAccountByTempCode.test.js => fail (exit 1) +- [003][main] test/app/controller/home.test.js => pass (exit 0) +- [004][main] test/app/controller/system.order.getreviewOrderlist.test.js => pass (exit 0) +- [005][main] test/app/controller/system.order.namespaced.test.js => pass (exit 0) +- [006][main] test/app/controller/system.order.reviewOrder.test.js => pass (exit 0) +- [007][main] test/app/controller/system.setting.account.getBindWechatCode.test.js => fail (exit 1) +- [008][main] test/app/controller/system.setting.account.test.js => fail (exit 1) +- [009][main] test/app/controller/system.setting.permission.test.js => pass (exit 0) +- [010][main] test/app/controller/system.setting.printTemplate.test.js => pass (exit 0) +- [011][main] test/app/controller/system.setting.role.test.js => pass (exit 0) +- [012][main] test/app/controller/system.setting.storeWarehouse.test.js => fail (exit 1) +- [013][main] test/app/controller/system.stock.warehouse.getStockDetail.test.js => pass (exit 0) +- [014][main] test/app/controller/system.stock.warehouse.namespaced.test.js => pass (exit 0) +- [015][main] test/app/controller/system.storage.delivery.module.test.js => pass (exit 0) +- [016][main] test/app/controller/system.storage.entry.test.js => fail (exit 1) +- [017][main] test/app/controller/system.storage.inventory.matchPutaway.test.js => pass (exit 0) +- [018][main] test/app/controller/system.storage.inventory.quickPutaway.test.js => pass (exit 0) +- [019][main] test/app/controller/system.storage.receiving.test.js => pass (exit 0) +- [020][main] test/app/controller/system.storage.transaction.test.js => pass (exit 0) +- [021][main] test/app/controller/system.storeWarehouse.test.js => pass (exit 0) +- [022][main] test/app/controller/system.user.changeRole.test.js => pass (exit 0) +- [023][main] test/app/controller/system.user.getLoginWechatCode.test.js => pass (exit 0) +- [024][main] test/app/controller/system.user.info.test.js => pass (exit 0) +- [025][main] test/app/controller/system.user.info.web.test.js => pass (exit 0) +- [026][main] test/app/controller/system.user.login.test.js => pass (exit 0) +- [027][main] test/app/controller/system.user.loginByCode.test.js => pass (exit 0) +- [028][main] test/app/controller/tempFileWriter.test.js => pass (exit 0) +- [029][main] test/app/lib/file_writer.test.js => pass (exit 0) +- [030][main] test/app/service/systemMethods/storeWarehouse/store.test.js => pass (exit 0) +- [031][main] test/app/service/systemMethods/warehouse.auth.test.js => pass (exit 0) +- [032][main] test/app/service/systems/auth.user.bindWechatCacheExpiry.test.js => pass (exit 0) +- [033][main] test/app/service/systems/auth.user.loginWechatCode.test.js => pass (exit 0) +- [034][main] test/app/service/systems/delivery_order.oversell.test.js => pass (exit 0) +- [035][main] test/app/service/systems/excel.test.js => pass (exit 0) +- [036][main] test/app/service/systems/license_plate.test.js => pass (exit 0) +- [037][main] test/app/service/systems/notice.test.js => fail (exit 1) +- [038][main] test/app/service/systems/stock_store.stockWarehouse.conditions.test.js => pass (exit 0) +- [039][main] test/app/service/systems/stock_transaction.create.test.js => pass (exit 0) +- [040][main] test/app/service/systems/storage.entry.cancel.test.js => pass (exit 0) +- [041][main] test/app/service/systems/storage.receiving.report.test.js => fail (exit 1) +- [042][main] test/app/service/systems/store_warehouse.adjustPrintQuantity.test.js => pass (exit 0) +- [043][main] test/app/service/systems/upload.test.js => pass (exit 0) +- [044][mirror] test/app/controller/docs.test.js => fail (exit 1) +- [045][mirror] test/app/controller/gateway.user.bindAccountByTempCode.test.js => fail (exit 1) +- [046][mirror] test/app/controller/home.test.js => fail (exit 1) +- [047][mirror] test/app/controller/system.order.getreviewOrderlist.test.js => pass (exit 0) +- [048][mirror] test/app/controller/system.order.namespaced.test.js => fail (exit 1) +- [049][mirror] test/app/controller/system.order.reviewOrder.test.js => fail (exit 1) +- [050][mirror] test/app/controller/system.setting.account.getBindWechatCode.test.js => fail (exit 1) +- [051][mirror] test/app/controller/system.setting.account.test.js => fail (exit 1) +- [052][mirror] test/app/controller/system.setting.permission.test.js => fail (exit 1) +- [053][mirror] test/app/controller/system.setting.printTemplate.test.js => pass (exit 0) +- [054][mirror] test/app/controller/system.setting.role.test.js => pass (exit 0) +- [055][mirror] test/app/controller/system.setting.storeWarehouse.test.js => fail (exit 1) +- [056][mirror] test/app/controller/system.stock.warehouse.getStockDetail.test.js => pass (exit 0) +- [057][mirror] test/app/controller/system.stock.warehouse.namespaced.test.js => pass (exit 0) +- [058][mirror] test/app/controller/system.storage.delivery.module.test.js => fail (exit 1) +- [059][mirror] test/app/controller/system.storage.entry.test.js => fail (exit 1) +- [060][mirror] test/app/controller/system.storage.inventory.matchPutaway.test.js => fail (exit 1) +- [061][mirror] test/app/controller/system.storage.inventory.quickPutaway.test.js => fail (exit 1) +- [062][mirror] test/app/controller/system.storage.receiving.test.js => fail (exit 1) +- [063][mirror] test/app/controller/system.storage.transaction.test.js => fail (exit 1) +- [064][mirror] test/app/controller/system.storeWarehouse.test.js => pass (exit 0) +- [065][mirror] test/app/controller/system.user.changeRole.test.js => pass (exit 0) +- [066][mirror] test/app/controller/system.user.getLoginWechatCode.test.js => pass (exit 0) +- [067][mirror] test/app/controller/system.user.info.test.js => pass (exit 0) +- [068][mirror] test/app/controller/system.user.info.web.test.js => pass (exit 0) +- [069][mirror] test/app/controller/system.user.login.test.js => pass (exit 0) +- [070][mirror] test/app/controller/system.user.loginByCode.test.js => pass (exit 0) +- [071][mirror] test/app/service/systemMethods/storeWarehouse/store.test.js => pass (exit 0) +- [072][mirror] test/app/service/systemMethods/warehouse.auth.test.js => pass (exit 0) +- [073][mirror] test/app/service/systems/auth.user.bindWechatCacheExpiry.test.js => pass (exit 0) +- [074][mirror] test/app/service/systems/auth.user.loginWechatCode.test.js => pass (exit 0) +- [075][mirror] test/app/service/systems/excel.test.js => pass (exit 0) +- [076][mirror] test/app/service/systems/license_plate.test.js => fail (exit 1) +- [077][mirror] test/app/service/systems/notice.test.js => fail (exit 1) +- [078][mirror] test/app/service/systems/stock_store.stockWarehouse.conditions.test.js => pass (exit 0) +- [079][mirror] test/app/service/systems/stock_transaction.create.test.js => pass (exit 0) +- [080][mirror] test/app/service/systems/storage.entry.cancel.test.js => pass (exit 0) +- [081][mirror] test/app/service/systems/storage.receiving.report.test.js => pass (exit 0) +- [082][mirror] test/app/service/systems/store_warehouse.adjustPrintQuantity.test.js => pass (exit 0) +- [083][mirror] test/app/service/systems/upload.test.js => pass (exit 0) diff --git a/test_reports/fail/002-main.md b/test_reports/fail/002-main.md new file mode 100644 index 0000000..f6fa29f --- /dev/null +++ b/test_reports/fail/002-main.md @@ -0,0 +1,55 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: main +- 文件: test/app/controller/gateway.user.bindAccountByTempCode.test.js +- 状态: fail +- 退出码: 1 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (3ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (15ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) +``` + +## 标准错误 + +```text + + Exception during run: AssertionError [ERR_ASSERTION]: SYSTEM_TEST_YE4S_USER_ID 蹇呴』鏄惧紡鎻愪緵涓斾负姝f暣鏁? at Object. (D:\wms\test\app\controller\gateway.user.bindAccountByTempCode.test.js:12:8) + at Module._compile (node:internal/modules/cjs/loader:1812:14) + at Object..js (node:internal/modules/cjs/loader:1943:10) + at Module.load (node:internal/modules/cjs/loader:1533:32) + at Module._load (node:internal/modules/cjs/loader:1335:12) + at wrapModuleLoad (node:internal/modules/cjs/loader:255:19) + at loadCJSModuleWithModuleLoad (node:internal/modules/esm/translators:328:3) + at ModuleWrap. (node:internal/modules/esm/translators:233:7) + at ModuleJob.run (node:internal/modules/esm/module_job:430:25) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:661:26) + at async formattedImport (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:9:14) + at async exports.requireOrImport (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:42:28) + at async exports.loadFilesAsync (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:100:20) + at async singleRun (D:\wms\node_modules\mocha\lib\cli\run-helpers.js:162:3) + at async exports.handler (D:\wms\node_modules\mocha\lib\cli\run.js:375:5) { + generatedMessage: false, + code: 'ERR_ASSERTION', + actual: false, + expected: true, + operator: '==', + diff: 'simple' +} +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/gateway.user.bindAccountByTempCode.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` diff --git a/test_reports/fail/007-main.md b/test_reports/fail/007-main.md new file mode 100644 index 0000000..8469667 --- /dev/null +++ b/test_reports/fail/007-main.md @@ -0,0 +1,55 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: main +- 文件: test/app/controller/system.setting.account.getBindWechatCode.test.js +- 状态: fail +- 退出码: 1 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) +``` + +## 标准错误 + +```text + + Exception during run: AssertionError [ERR_ASSERTION]: SYSTEM_TEST_YE4S_USER_ID 蹇呴』鏄惧紡鎻愪緵涓斾负姝f暣鏁? at Object. (D:\wms\test\app\controller\system.setting.account.getBindWechatCode.test.js:12:8) + at Module._compile (node:internal/modules/cjs/loader:1812:14) + at Object..js (node:internal/modules/cjs/loader:1943:10) + at Module.load (node:internal/modules/cjs/loader:1533:32) + at Module._load (node:internal/modules/cjs/loader:1335:12) + at wrapModuleLoad (node:internal/modules/cjs/loader:255:19) + at loadCJSModuleWithModuleLoad (node:internal/modules/esm/translators:328:3) + at ModuleWrap. (node:internal/modules/esm/translators:233:7) + at ModuleJob.run (node:internal/modules/esm/module_job:430:25) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:661:26) + at async formattedImport (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:9:14) + at async exports.requireOrImport (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:42:28) + at async exports.loadFilesAsync (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:100:20) + at async singleRun (D:\wms\node_modules\mocha\lib\cli\run-helpers.js:162:3) + at async exports.handler (D:\wms\node_modules\mocha\lib\cli\run.js:375:5) { + generatedMessage: false, + code: 'ERR_ASSERTION', + actual: false, + expected: true, + operator: '==', + diff: 'simple' +} +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.setting.account.getBindWechatCode.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` diff --git a/test_reports/fail/008-main.md b/test_reports/fail/008-main.md new file mode 100644 index 0000000..4f74d10 --- /dev/null +++ b/test_reports/fail/008-main.md @@ -0,0 +1,57 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: main +- 文件: test/app/controller/system.setting.account.test.js +- 状态: fail +- 退出码: 1 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (3ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (17ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.setting.account.test.js + 1) "before all" hook for "error-1 should reject add when real_name is reserved name" + + + 0 passing (93ms) + 1 failing + + 1) test/app/controller/system.setting.account.test.js + "before all" hook for "error-1 should reject add when real_name is reserved name": + + AssertionError [ERR_ASSERTION]: 宸叉湁鏂囦欢ID鏃犳晥 + + expected - actual + + -false + +true + + at Context. (test\app\controller\system.setting.account.test.js:91:12) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +```text +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.setting.account.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` diff --git a/test_reports/fail/012-main.md b/test_reports/fail/012-main.md new file mode 100644 index 0000000..6dc280a --- /dev/null +++ b/test_reports/fail/012-main.md @@ -0,0 +1,70 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: main +- 文件: test/app/controller/system.setting.storeWarehouse.test.js +- 状态: fail +- 退出码: 1 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (3ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (15ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/system.setting.storeWarehouse.test.js + 鉁?should list store-warehouse contracts in current subject scope (154ms) + 鉁?should allow renaming current-side remask and reflect it in list display (869ms) + 鉁?should generate a temp code and support preview before confirmation (267ms) + 鉁?should only change use_status when unbinding (584ms) + 鉁?should allow warehouse side to save and get policy config on a contract (921ms) + 鉁?should reject unsupported policy config fields on a contract (276ms) + 1) should allow warehouse side to save, update and delete api config on a contract + 鉁?should reject sign when counterparty is missing (60ms) + 鉁?should reject unbind when no target relation is provided (120ms) + + + 8 passing (4s) + 1 failing + + 1) test/app/controller/system.setting.storeWarehouse.test.js + should allow warehouse side to save, update and delete api config on a contract: + + AssertionError [ERR_ASSERTION]: Expected values to be strictly equal: ++ actual - expected + ++ 'failure' +- 'success' + + + expected - actual + + -failure + +success + + at Context. (test\app\controller\system.setting.storeWarehouse.test.js:300:14) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +```text +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.setting.storeWarehouse.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` diff --git a/test_reports/fail/016-main.md b/test_reports/fail/016-main.md new file mode 100644 index 0000000..e8bd90a --- /dev/null +++ b/test_reports/fail/016-main.md @@ -0,0 +1,93 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: main +- 文件: test/app/controller/system.storage.entry.test.js +- 状态: fail +- 退出码: 1 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (1ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.storage.entry.test.js + 鉁?should query entry list (1104ms) + 1) should create entry and run detail lifecycle then cancel + 2) should complete entry after adding detail + 3) should reject invalid params for create/get/addDetail + + + 1 passing (4s) + 3 failing + + 1) test/app/controller/system.storage.entry.test.js + should create entry and run detail lifecycle then cancel: + + AssertionError [ERR_ASSERTION]: Expected values to be strictly equal: + +500 !== 200 + + + expected - actual + + -500 + +200 + + at Context. (test\app\controller\system.storage.entry.test.js:109:12) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + + 2) test/app/controller/system.storage.entry.test.js + should complete entry after adding detail: + + AssertionError [ERR_ASSERTION]: Expected values to be strictly equal: + +500 !== 200 + + + expected - actual + + -500 + +200 + + at Context. (test\app\controller\system.storage.entry.test.js:181:12) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + + 3) test/app/controller/system.storage.entry.test.js + should reject invalid params for create/get/addDetail: + + AssertionError [ERR_ASSERTION]: Expected values to be strictly equal: + +500 !== 200 + + + expected - actual + + -500 + +200 + + at Context. (test\app\controller\system.storage.entry.test.js:217:12) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +```text +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.storage.entry.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` diff --git a/test_reports/fail/037-main.md b/test_reports/fail/037-main.md new file mode 100644 index 0000000..f83c817 --- /dev/null +++ b/test_reports/fail/037-main.md @@ -0,0 +1,77 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: main +- 文件: test/app/service/systems/notice.test.js +- 状态: fail +- 退出码: 1 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/service/systems/notice.test.js + 1) should normalize payload and send only matching webhooks + 鉁?should enrich payload with store info from cache before querying database + 鉁?should load store info from database and cache it when cache is empty + 鉁?should send to both warehouse and owner webhooks when events match or are set to all + 鉁?should only send up to the configured webhook limit + 鉁?should require url for image or file message + 鉁?should require warehouseId but allow empty ownerId + 鉁?should retry failed webhooks three times and persist final failures + 鉁?should reject sending unregistered event + 鉁?should reject dotted or numeric-leading event names + 鉁?should send wecom webhook as enterprise wechat direct message + 鉁?should expose available webhook events and reject unsupported ones + + + 11 passing (15ms) + 1 failing + + 1) test/app/service/systems/notice.test.js + should normalize payload and send only matching webhooks: + + AssertionError [ERR_ASSERTION]: Expected values to be strictly equal: ++ actual - expected + ++ 100000 +- 1000000 + + + expected - actual + + -100000 + +1000000 + + at Object.findAll (test\app\service\systems\notice.test.js:34:20) + at D:\wms\app\service\systems\notice\index.js:796:43 + at Array.map () + at NoticeService.findMatchedWebhooks (app\service\systems\notice\index.js:786:62) + at NoticeService.send (app\service\systems\notice\index.js:826:33) + at async Context. (test\app\service\systems\notice.test.js:55:20) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +```text +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/service/systems/notice.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` diff --git a/test_reports/fail/041-main.md b/test_reports/fail/041-main.md new file mode 100644 index 0000000..39491f0 --- /dev/null +++ b/test_reports/fail/041-main.md @@ -0,0 +1,70 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: main +- 文件: test/app/service/systems/storage.receiving.report.test.js +- 状态: fail +- 退出码: 1 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/service/systems/storage.receiving.report.test.js + 1) should build and upload completion excel in a single sheet with one preview column + 鉁?should send receiving completed notice with the unified event payload + 鉁?should show only license plate for truck in notice content and report main rows + 鉁?should show only tracking number for express in notice content and report main rows + 鉁?should hide both contact fields for other delivery methods + 鉁?should support nested notice.index service shape from Egg loader + 鉁?should trigger text notice before excel and then send file notice after upload succeeds + 鉁?should only send text notice when completion excel generation fails + 鉁?should still complete and notify when detail has no matched product or completeness fields + + + 8 passing (24ms) + 1 failing + + 1) test/app/service/systems/storage.receiving.report.test.js + should build and upload completion excel in a single sheet with one preview column: + + AssertionError [ERR_ASSERTION]: Expected values to be strictly equal: ++ actual - expected + ++ '鏀惰揣鏄庣粏(宸插畬鎴愭敹璐?_RCV202604040001.xlsx' +- '鏀惰揣瀹屾垚_RCV202604040001.xlsx' + ^ + + + expected - actual + + -鏀惰揣鏄庣粏(宸插畬鎴愭敹璐?_RCV202604040001.xlsx + +鏀惰揣瀹屾垚_RCV202604040001.xlsx + + at Context. (test\app\service\systems\storage.receiving.report.test.js:260:12) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +```text +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/service/systems/storage.receiving.report.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` diff --git a/test_reports/fail/044-mirror.md b/test_reports/fail/044-mirror.md new file mode 100644 index 0000000..f4342a0 --- /dev/null +++ b/test_reports/fail/044-mirror.md @@ -0,0 +1,149 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: mirror +- 文件: test/app/controller/docs.test.js +- 状态: fail +- 退出码: 1 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (3ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + 1) "before all" hook: beforeAll in "{root}" + 2) "after all" hook: afterAll in "{root}" + + 0 passing (1s) + 2 failing + + 1) "before all" hook: beforeAll in "{root}": + Error: Cannot find module './tencent-cloud' +Require stack: +- D:\wms\worktrees\deploy-20260409155126\config\config.default.js +- D:\wms\node_modules\egg-core\lib\utils\index.js +- D:\wms\node_modules\egg-core\lib\egg.js +- D:\wms\node_modules\egg-core\index.js +- D:\wms\node_modules\egg-mock\lib\context.js +- D:\wms\node_modules\egg-mock\lib\app.js +- D:\wms\node_modules\egg-mock\index.js +- D:\wms\node_modules\egg-mock\register.js + at Module._resolveFilename (node:internal/modules/cjs/loader:1456:15) + at defaultResolveImpl (node:internal/modules/cjs/loader:1066:19) + at resolveForCJSWithHooks (node:internal/modules/cjs/loader:1071:22) + at Module._load (node:internal/modules/cjs/loader:1242:25) + at wrapModuleLoad (node:internal/modules/cjs/loader:255:19) + at Module.require (node:internal/modules/cjs/loader:1556:12) + at require (node:internal/modules/helpers:152:16) + at module.exports (config\config.default.js:21:30) + at AgentWorkerLoader.loadFile (D:\wms\node_modules\egg-core\lib\loader\egg_loader.js:315:13) + at AgentWorkerLoader._loadConfig (D:\wms\node_modules\egg-core\lib\loader\mixin\config.js:82:25) + at AgentWorkerLoader._preloadAppConfig (D:\wms\node_modules\egg-core\lib\loader\mixin\config.js:67:27) + at AgentWorkerLoader.loadConfig (D:\wms\node_modules\egg-core\lib\loader\mixin\config.js:25:28) + at AgentWorkerLoader.loadConfig (D:\wms\node_modules\egg\lib\loader\agent_worker_loader.js:16:11) + at new EggApplication (D:\wms\node_modules\egg\lib\egg.js:62:17) + at new Agent (D:\wms\node_modules\egg\lib\agent.js:22:5) + at [init] (D:\wms\node_modules\egg-mock\lib\app.js:81:33) + at Generator.next () + at onFulfilled (D:\wms\node_modules\co\index.js:65:19) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + + 2) "after all" hook: afterAll in "{root}": + Error: Cannot find module './tencent-cloud' +Require stack: +- D:\wms\worktrees\deploy-20260409155126\config\config.default.js +- D:\wms\node_modules\egg-core\lib\utils\index.js +- D:\wms\node_modules\egg-core\lib\egg.js +- D:\wms\node_modules\egg-core\index.js +- D:\wms\node_modules\egg-mock\lib\context.js +- D:\wms\node_modules\egg-mock\lib\app.js +- D:\wms\node_modules\egg-mock\index.js +- D:\wms\node_modules\egg-mock\register.js + at Module._resolveFilename (node:internal/modules/cjs/loader:1456:15) + at defaultResolveImpl (node:internal/modules/cjs/loader:1066:19) + at resolveForCJSWithHooks (node:internal/modules/cjs/loader:1071:22) + at Module._load (node:internal/modules/cjs/loader:1242:25) + at wrapModuleLoad (node:internal/modules/cjs/loader:255:19) + at Module.require (node:internal/modules/cjs/loader:1556:12) + at require (node:internal/modules/helpers:152:16) + at module.exports (config\config.default.js:21:30) + at AgentWorkerLoader.loadFile (D:\wms\node_modules\egg-core\lib\loader\egg_loader.js:315:13) + at AgentWorkerLoader._loadConfig (D:\wms\node_modules\egg-core\lib\loader\mixin\config.js:82:25) + at AgentWorkerLoader._preloadAppConfig (D:\wms\node_modules\egg-core\lib\loader\mixin\config.js:67:27) + at AgentWorkerLoader.loadConfig (D:\wms\node_modules\egg-core\lib\loader\mixin\config.js:25:28) + at AgentWorkerLoader.loadConfig (D:\wms\node_modules\egg\lib\loader\agent_worker_loader.js:16:11) + at new EggApplication (D:\wms\node_modules\egg\lib\egg.js:62:17) + at new Agent (D:\wms\node_modules\egg\lib\agent.js:22:5) + at [init] (D:\wms\node_modules\egg-mock\lib\app.js:81:33) + at Generator.next () + at onFulfilled (D:\wms\node_modules\co\index.js:65:19) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + + + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +```text +2026-04-10 16:50:06,662 ERROR 3304 nodejs.MODULE_NOT_FOUNDError: Cannot find module './tencent-cloud' +Require stack: +- D:\wms\worktrees\deploy-20260409155126\config\config.default.js +- D:\wms\node_modules\egg-core\lib\utils\index.js +- D:\wms\node_modules\egg-core\lib\egg.js +- D:\wms\node_modules\egg-core\index.js +- D:\wms\node_modules\egg-mock\lib\context.js +- D:\wms\node_modules\egg-mock\lib\app.js +- D:\wms\node_modules\egg-mock\index.js +- D:\wms\node_modules\egg-mock\register.js +Require stack: +- D:\wms\worktrees\deploy-20260409155126\config\config.default.js +- D:\wms\node_modules\egg-core\lib\utils\index.js +- D:\wms\node_modules\egg-core\lib\egg.js +- D:\wms\node_modules\egg-core\index.js +- D:\wms\node_modules\egg-mock\lib\context.js +- D:\wms\node_modules\egg-mock\lib\app.js +- D:\wms\node_modules\egg-mock\index.js +- D:\wms\node_modules\egg-mock\register.js + at Module._resolveFilename (node:internal/modules/cjs/loader:1456:15) + at defaultResolveImpl (node:internal/modules/cjs/loader:1066:19) + at resolveForCJSWithHooks (node:internal/modules/cjs/loader:1071:22) + at Module._load (node:internal/modules/cjs/loader:1242:25) + at wrapModuleLoad (node:internal/modules/cjs/loader:255:19) + at Module.require (node:internal/modules/cjs/loader:1556:12) + at require (node:internal/modules/helpers:152:16) + at module.exports (D:\wms\worktrees\deploy-20260409155126\config\config.default.js:21:30) + at AgentWorkerLoader.loadFile (D:\wms\node_modules\egg-core\lib\loader\egg_loader.js:315:13) + at AgentWorkerLoader._loadConfig (D:\wms\node_modules\egg-core\lib\loader\mixin\config.js:82:25) + at AgentWorkerLoader._preloadAppConfig (D:\wms\node_modules\egg-core\lib\loader\mixin\config.js:67:27) + at AgentWorkerLoader.loadConfig (D:\wms\node_modules\egg-core\lib\loader\mixin\config.js:25:28) + at AgentWorkerLoader.loadConfig (D:\wms\node_modules\egg\lib\loader\agent_worker_loader.js:16:11) + at new EggApplication (D:\wms\node_modules\egg\lib\egg.js:62:17) + at new Agent (D:\wms\node_modules\egg\lib\agent.js:22:5) + at [init] (D:\wms\node_modules\egg-mock\lib\app.js:81:33) + at Generator.next () + at onFulfilled (D:\wms\node_modules\co\index.js:65:19) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) +code: "MODULE_NOT_FOUND" +requireStack: ["D:\\wms\\worktrees\\deploy-20260409155126\\config\\config.default.js","D:\\wms\\node_modules\\egg-core\\lib\\utils\\index.js","D:\\wms\\node_modules\\egg-core\\lib\\egg.js","D:\\wms\\node_modules\\egg-core\\index.js","D:\\wms\\node_modules\\egg-mock\\lib\\context.js","D:\\wms\\node_modules\\egg-mock\\lib\\app.js","D:\\wms\\node_modules\\egg-mock\\index.js","D:\\wms\\node_modules\\egg-mock\\register.js"] +pid: 3304 +hostname: MINGREN + +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/docs.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` diff --git a/test_reports/fail/045-mirror.md b/test_reports/fail/045-mirror.md new file mode 100644 index 0000000..2d1c024 --- /dev/null +++ b/test_reports/fail/045-mirror.md @@ -0,0 +1,55 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: mirror +- 文件: test/app/controller/gateway.user.bindAccountByTempCode.test.js +- 状态: fail +- 退出码: 1 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (15ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (5ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) +``` + +## 标准错误 + +```text + + Exception during run: AssertionError [ERR_ASSERTION]: SYSTEM_TEST_YE4S_USER_ID 蹇呴』鏄惧紡鎻愪緵涓斾负姝f暣鏁? at Object. (D:\wms\worktrees\deploy-20260409155126\test\app\controller\gateway.user.bindAccountByTempCode.test.js:12:8) + at Module._compile (node:internal/modules/cjs/loader:1812:14) + at Object..js (node:internal/modules/cjs/loader:1943:10) + at Module.load (node:internal/modules/cjs/loader:1533:32) + at Module._load (node:internal/modules/cjs/loader:1335:12) + at wrapModuleLoad (node:internal/modules/cjs/loader:255:19) + at loadCJSModuleWithModuleLoad (node:internal/modules/esm/translators:328:3) + at ModuleWrap. (node:internal/modules/esm/translators:233:7) + at ModuleJob.run (node:internal/modules/esm/module_job:430:25) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:661:26) + at async formattedImport (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:9:14) + at async exports.requireOrImport (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:42:28) + at async exports.loadFilesAsync (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:100:20) + at async singleRun (D:\wms\node_modules\mocha\lib\cli\run-helpers.js:162:3) + at async exports.handler (D:\wms\node_modules\mocha\lib\cli\run.js:375:5) { + generatedMessage: false, + code: 'ERR_ASSERTION', + actual: false, + expected: true, + operator: '==', + diff: 'simple' +} +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/gateway.user.bindAccountByTempCode.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` diff --git a/test_reports/fail/046-mirror.md b/test_reports/fail/046-mirror.md new file mode 100644 index 0000000..ce9f10c --- /dev/null +++ b/test_reports/fail/046-mirror.md @@ -0,0 +1,149 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: mirror +- 文件: test/app/controller/home.test.js +- 状态: fail +- 退出码: 1 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (3ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + 1) "before all" hook: beforeAll in "{root}" + 2) "after all" hook: afterAll in "{root}" + + 0 passing (1s) + 2 failing + + 1) "before all" hook: beforeAll in "{root}": + Error: Cannot find module './tencent-cloud' +Require stack: +- D:\wms\worktrees\deploy-20260409155126\config\config.default.js +- D:\wms\node_modules\egg-core\lib\utils\index.js +- D:\wms\node_modules\egg-core\lib\egg.js +- D:\wms\node_modules\egg-core\index.js +- D:\wms\node_modules\egg-mock\lib\context.js +- D:\wms\node_modules\egg-mock\lib\app.js +- D:\wms\node_modules\egg-mock\index.js +- D:\wms\node_modules\egg-mock\register.js + at Module._resolveFilename (node:internal/modules/cjs/loader:1456:15) + at defaultResolveImpl (node:internal/modules/cjs/loader:1066:19) + at resolveForCJSWithHooks (node:internal/modules/cjs/loader:1071:22) + at Module._load (node:internal/modules/cjs/loader:1242:25) + at wrapModuleLoad (node:internal/modules/cjs/loader:255:19) + at Module.require (node:internal/modules/cjs/loader:1556:12) + at require (node:internal/modules/helpers:152:16) + at module.exports (config\config.default.js:21:30) + at AgentWorkerLoader.loadFile (D:\wms\node_modules\egg-core\lib\loader\egg_loader.js:315:13) + at AgentWorkerLoader._loadConfig (D:\wms\node_modules\egg-core\lib\loader\mixin\config.js:82:25) + at AgentWorkerLoader._preloadAppConfig (D:\wms\node_modules\egg-core\lib\loader\mixin\config.js:67:27) + at AgentWorkerLoader.loadConfig (D:\wms\node_modules\egg-core\lib\loader\mixin\config.js:25:28) + at AgentWorkerLoader.loadConfig (D:\wms\node_modules\egg\lib\loader\agent_worker_loader.js:16:11) + at new EggApplication (D:\wms\node_modules\egg\lib\egg.js:62:17) + at new Agent (D:\wms\node_modules\egg\lib\agent.js:22:5) + at [init] (D:\wms\node_modules\egg-mock\lib\app.js:81:33) + at Generator.next () + at onFulfilled (D:\wms\node_modules\co\index.js:65:19) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + + 2) "after all" hook: afterAll in "{root}": + Error: Cannot find module './tencent-cloud' +Require stack: +- D:\wms\worktrees\deploy-20260409155126\config\config.default.js +- D:\wms\node_modules\egg-core\lib\utils\index.js +- D:\wms\node_modules\egg-core\lib\egg.js +- D:\wms\node_modules\egg-core\index.js +- D:\wms\node_modules\egg-mock\lib\context.js +- D:\wms\node_modules\egg-mock\lib\app.js +- D:\wms\node_modules\egg-mock\index.js +- D:\wms\node_modules\egg-mock\register.js + at Module._resolveFilename (node:internal/modules/cjs/loader:1456:15) + at defaultResolveImpl (node:internal/modules/cjs/loader:1066:19) + at resolveForCJSWithHooks (node:internal/modules/cjs/loader:1071:22) + at Module._load (node:internal/modules/cjs/loader:1242:25) + at wrapModuleLoad (node:internal/modules/cjs/loader:255:19) + at Module.require (node:internal/modules/cjs/loader:1556:12) + at require (node:internal/modules/helpers:152:16) + at module.exports (config\config.default.js:21:30) + at AgentWorkerLoader.loadFile (D:\wms\node_modules\egg-core\lib\loader\egg_loader.js:315:13) + at AgentWorkerLoader._loadConfig (D:\wms\node_modules\egg-core\lib\loader\mixin\config.js:82:25) + at AgentWorkerLoader._preloadAppConfig (D:\wms\node_modules\egg-core\lib\loader\mixin\config.js:67:27) + at AgentWorkerLoader.loadConfig (D:\wms\node_modules\egg-core\lib\loader\mixin\config.js:25:28) + at AgentWorkerLoader.loadConfig (D:\wms\node_modules\egg\lib\loader\agent_worker_loader.js:16:11) + at new EggApplication (D:\wms\node_modules\egg\lib\egg.js:62:17) + at new Agent (D:\wms\node_modules\egg\lib\agent.js:22:5) + at [init] (D:\wms\node_modules\egg-mock\lib\app.js:81:33) + at Generator.next () + at onFulfilled (D:\wms\node_modules\co\index.js:65:19) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + + + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +```text +2026-04-10 16:50:12,077 ERROR 11992 nodejs.MODULE_NOT_FOUNDError: Cannot find module './tencent-cloud' +Require stack: +- D:\wms\worktrees\deploy-20260409155126\config\config.default.js +- D:\wms\node_modules\egg-core\lib\utils\index.js +- D:\wms\node_modules\egg-core\lib\egg.js +- D:\wms\node_modules\egg-core\index.js +- D:\wms\node_modules\egg-mock\lib\context.js +- D:\wms\node_modules\egg-mock\lib\app.js +- D:\wms\node_modules\egg-mock\index.js +- D:\wms\node_modules\egg-mock\register.js +Require stack: +- D:\wms\worktrees\deploy-20260409155126\config\config.default.js +- D:\wms\node_modules\egg-core\lib\utils\index.js +- D:\wms\node_modules\egg-core\lib\egg.js +- D:\wms\node_modules\egg-core\index.js +- D:\wms\node_modules\egg-mock\lib\context.js +- D:\wms\node_modules\egg-mock\lib\app.js +- D:\wms\node_modules\egg-mock\index.js +- D:\wms\node_modules\egg-mock\register.js + at Module._resolveFilename (node:internal/modules/cjs/loader:1456:15) + at defaultResolveImpl (node:internal/modules/cjs/loader:1066:19) + at resolveForCJSWithHooks (node:internal/modules/cjs/loader:1071:22) + at Module._load (node:internal/modules/cjs/loader:1242:25) + at wrapModuleLoad (node:internal/modules/cjs/loader:255:19) + at Module.require (node:internal/modules/cjs/loader:1556:12) + at require (node:internal/modules/helpers:152:16) + at module.exports (D:\wms\worktrees\deploy-20260409155126\config\config.default.js:21:30) + at AgentWorkerLoader.loadFile (D:\wms\node_modules\egg-core\lib\loader\egg_loader.js:315:13) + at AgentWorkerLoader._loadConfig (D:\wms\node_modules\egg-core\lib\loader\mixin\config.js:82:25) + at AgentWorkerLoader._preloadAppConfig (D:\wms\node_modules\egg-core\lib\loader\mixin\config.js:67:27) + at AgentWorkerLoader.loadConfig (D:\wms\node_modules\egg-core\lib\loader\mixin\config.js:25:28) + at AgentWorkerLoader.loadConfig (D:\wms\node_modules\egg\lib\loader\agent_worker_loader.js:16:11) + at new EggApplication (D:\wms\node_modules\egg\lib\egg.js:62:17) + at new Agent (D:\wms\node_modules\egg\lib\agent.js:22:5) + at [init] (D:\wms\node_modules\egg-mock\lib\app.js:81:33) + at Generator.next () + at onFulfilled (D:\wms\node_modules\co\index.js:65:19) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) +code: "MODULE_NOT_FOUND" +requireStack: ["D:\\wms\\worktrees\\deploy-20260409155126\\config\\config.default.js","D:\\wms\\node_modules\\egg-core\\lib\\utils\\index.js","D:\\wms\\node_modules\\egg-core\\lib\\egg.js","D:\\wms\\node_modules\\egg-core\\index.js","D:\\wms\\node_modules\\egg-mock\\lib\\context.js","D:\\wms\\node_modules\\egg-mock\\lib\\app.js","D:\\wms\\node_modules\\egg-mock\\index.js","D:\\wms\\node_modules\\egg-mock\\register.js"] +pid: 11992 +hostname: MINGREN + +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/home.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` diff --git a/test_reports/fail/048-mirror.md b/test_reports/fail/048-mirror.md new file mode 100644 index 0000000..b855e6a --- /dev/null +++ b/test_reports/fail/048-mirror.md @@ -0,0 +1,63 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: mirror +- 文件: test/app/controller/system.order.namespaced.test.js +- 状态: fail +- 退出码: 1 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (11ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/system.order.namespaced.test.js + 鉁?should query all namespaced order lists (2175ms) + 1) should review order through namespaced method and restore status + + + 1 passing (4s) + 1 failing + + 1) test/app/controller/system.order.namespaced.test.js + should review order through namespaced method and restore status: + + AssertionError [ERR_ASSERTION]: Expected values to be strictly equal: ++ actual - expected + ++ 'failure' +- 'success' + + + expected - actual + + -failure + +success + + at Context. (test\app\controller\system.order.namespaced.test.js:110:12) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + + + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +```text +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.order.namespaced.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` diff --git a/test_reports/fail/049-mirror.md b/test_reports/fail/049-mirror.md new file mode 100644 index 0000000..2f23b33 --- /dev/null +++ b/test_reports/fail/049-mirror.md @@ -0,0 +1,62 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: mirror +- 文件: test/app/controller/system.order.reviewOrder.test.js +- 状态: fail +- 退出码: 1 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (11ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/system.order.reviewOrder.test.js + 1) should review order and restore inspection status + + + 0 passing (2s) + 1 failing + + 1) test/app/controller/system.order.reviewOrder.test.js + should review order and restore inspection status: + + AssertionError [ERR_ASSERTION]: Expected values to be strictly equal: ++ actual - expected + ++ 'failure' +- 'success' + + + expected - actual + + -failure + +success + + at Context. (test\app\controller\system.order.reviewOrder.test.js:79:12) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + + + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +```text +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.order.reviewOrder.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` diff --git a/test_reports/fail/050-mirror.md b/test_reports/fail/050-mirror.md new file mode 100644 index 0000000..c4d7d08 --- /dev/null +++ b/test_reports/fail/050-mirror.md @@ -0,0 +1,55 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: mirror +- 文件: test/app/controller/system.setting.account.getBindWechatCode.test.js +- 状态: fail +- 退出码: 1 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (10ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) +``` + +## 标准错误 + +```text + + Exception during run: AssertionError [ERR_ASSERTION]: SYSTEM_TEST_YE4S_USER_ID 蹇呴』鏄惧紡鎻愪緵涓斾负姝f暣鏁? at Object. (D:\wms\worktrees\deploy-20260409155126\test\app\controller\system.setting.account.getBindWechatCode.test.js:12:8) + at Module._compile (node:internal/modules/cjs/loader:1812:14) + at Object..js (node:internal/modules/cjs/loader:1943:10) + at Module.load (node:internal/modules/cjs/loader:1533:32) + at Module._load (node:internal/modules/cjs/loader:1335:12) + at wrapModuleLoad (node:internal/modules/cjs/loader:255:19) + at loadCJSModuleWithModuleLoad (node:internal/modules/esm/translators:328:3) + at ModuleWrap. (node:internal/modules/esm/translators:233:7) + at ModuleJob.run (node:internal/modules/esm/module_job:430:25) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:661:26) + at async formattedImport (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:9:14) + at async exports.requireOrImport (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:42:28) + at async exports.loadFilesAsync (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:100:20) + at async singleRun (D:\wms\node_modules\mocha\lib\cli\run-helpers.js:162:3) + at async exports.handler (D:\wms\node_modules\mocha\lib\cli\run.js:375:5) { + generatedMessage: false, + code: 'ERR_ASSERTION', + actual: false, + expected: true, + operator: '==', + diff: 'simple' +} +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.setting.account.getBindWechatCode.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` diff --git a/test_reports/fail/051-mirror.md b/test_reports/fail/051-mirror.md new file mode 100644 index 0000000..c196f44 --- /dev/null +++ b/test_reports/fail/051-mirror.md @@ -0,0 +1,57 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: mirror +- 文件: test/app/controller/system.setting.account.test.js +- 状态: fail +- 退出码: 1 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (3ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (5ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.setting.account.test.js + 1) "before all" hook for "error-1 should reject add when real_name is reserved name" + + + 0 passing (80ms) + 1 failing + + 1) test/app/controller/system.setting.account.test.js + "before all" hook for "error-1 should reject add when real_name is reserved name": + + AssertionError [ERR_ASSERTION]: 宸叉湁鏂囦欢ID鏃犳晥 + + expected - actual + + -false + +true + + at Context. (test\app\controller\system.setting.account.test.js:91:12) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + + + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +```text +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.setting.account.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` diff --git a/test_reports/fail/052-mirror.md b/test_reports/fail/052-mirror.md new file mode 100644 index 0000000..99b6301 --- /dev/null +++ b/test_reports/fail/052-mirror.md @@ -0,0 +1,58 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: mirror +- 文件: test/app/controller/system.setting.permission.test.js +- 状态: fail +- 退出码: 1 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.setting.permission.test.js + 鉁?should expose setting.role.permission as alias of setting.permission.list (252ms) + 鉁?should include route presentation fields in permission list response (506ms) + 鉁?should show newly created permission in list for admin management (463ms) + 鉁?should reject permission update when target permission does not exist (59ms) + 1) should create then update then delete permission successfully + 鉁?should split deleted_ids and already_deleted_ids in mixed batch delete (745ms) + 鉁?should reject mixed delete when ids contain non-existent permission (387ms) + + + 6 passing (4s) + 1 failing + + 1) test/app/controller/system.setting.permission.test.js + should create then update then delete permission successfully: + TypeError: fetch failed + + Caused by: Error: read ECONNRESET + at TCP.onStreamRead (node:internal/stream_base_commons:216:20) + + + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +```text +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.setting.permission.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` diff --git a/test_reports/fail/055-mirror.md b/test_reports/fail/055-mirror.md new file mode 100644 index 0000000..1962fd4 --- /dev/null +++ b/test_reports/fail/055-mirror.md @@ -0,0 +1,70 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: mirror +- 文件: test/app/controller/system.setting.storeWarehouse.test.js +- 状态: fail +- 退出码: 1 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/system.setting.storeWarehouse.test.js + 鉁?should list store-warehouse contracts in current subject scope (155ms) + 鉁?should allow renaming current-side remask and reflect it in list display (886ms) + 鉁?should generate a temp code and support preview before confirmation (269ms) + 鉁?should only change use_status when unbinding (589ms) + 鉁?should allow warehouse side to save and get policy config on a contract (924ms) + 鉁?should reject unsupported policy config fields on a contract (269ms) + 1) should allow warehouse side to save, update and delete api config on a contract + 鉁?should reject sign when counterparty is missing (61ms) + 鉁?should reject unbind when no target relation is provided (117ms) + + + 8 passing (4s) + 1 failing + + 1) test/app/controller/system.setting.storeWarehouse.test.js + should allow warehouse side to save, update and delete api config on a contract: + + AssertionError [ERR_ASSERTION]: Expected values to be strictly equal: ++ actual - expected + ++ 'failure' +- 'success' + + + expected - actual + + -failure + +success + + at Context. (test\app\controller\system.setting.storeWarehouse.test.js:300:14) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + + + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +```text +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.setting.storeWarehouse.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` diff --git a/test_reports/fail/058-mirror.md b/test_reports/fail/058-mirror.md new file mode 100644 index 0000000..ef4e0ca --- /dev/null +++ b/test_reports/fail/058-mirror.md @@ -0,0 +1,101 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: mirror +- 文件: test/app/controller/system.storage.delivery.module.test.js +- 状态: fail +- 退出码: 1 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.storage.delivery.module.test.js + 1) should return delivery list via storage.stockout.list + 2) should return placeholder failure via storage.stockout.toOrder + 3) should return item list via storage.stockout.listItems + 鉁?should not expose removed storage.entry detail methods (1219ms) + + + 1 passing (5s) + 3 failing + + 1) test/app/controller/system.storage.delivery.module.test.js + should return delivery list via storage.stockout.list: + + AssertionError [ERR_ASSERTION]: Expected values to be strictly equal: ++ actual - expected + ++ 'failure' +- 'success' + + + expected - actual + + -failure + +success + + at Context. (test\app\controller\system.storage.delivery.module.test.js:171:12) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + + 2) test/app/controller/system.storage.delivery.module.test.js + should return placeholder failure via storage.stockout.toOrder: + + AssertionError [ERR_ASSERTION]: Expected values to be strictly equal: ++ actual - expected + ++ 'failure' +- 'success' + + + expected - actual + + -failure + +success + + at getFirstDelivery (test\app\controller\system.storage.delivery.module.test.js:95:10) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + at async Context. (test\app\controller\system.storage.delivery.module.test.js:184:22) + + 3) test/app/controller/system.storage.delivery.module.test.js + should return item list via storage.stockout.listItems: + + AssertionError [ERR_ASSERTION]: Expected values to be strictly equal: ++ actual - expected + ++ 'failure' +- 'success' + + + expected - actual + + -failure + +success + + at getFirstDelivery (test\app\controller\system.storage.delivery.module.test.js:95:10) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + at async Context. (test\app\controller\system.storage.delivery.module.test.js:210:22) + + + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +```text +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.storage.delivery.module.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` diff --git a/test_reports/fail/059-mirror.md b/test_reports/fail/059-mirror.md new file mode 100644 index 0000000..158aaa1 --- /dev/null +++ b/test_reports/fail/059-mirror.md @@ -0,0 +1,93 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: mirror +- 文件: test/app/controller/system.storage.entry.test.js +- 状态: fail +- 退出码: 1 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.storage.entry.test.js + 鉁?should query entry list (1120ms) + 1) should create entry and run detail lifecycle then cancel + 2) should complete entry after adding detail + 3) should reject invalid params for create/get/addDetail + + + 1 passing (4s) + 3 failing + + 1) test/app/controller/system.storage.entry.test.js + should create entry and run detail lifecycle then cancel: + + AssertionError [ERR_ASSERTION]: Expected values to be strictly equal: + +500 !== 200 + + + expected - actual + + -500 + +200 + + at Context. (test\app\controller\system.storage.entry.test.js:109:12) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + + 2) test/app/controller/system.storage.entry.test.js + should complete entry after adding detail: + + AssertionError [ERR_ASSERTION]: Expected values to be strictly equal: + +500 !== 200 + + + expected - actual + + -500 + +200 + + at Context. (test\app\controller\system.storage.entry.test.js:181:12) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + + 3) test/app/controller/system.storage.entry.test.js + should reject invalid params for create/get/addDetail: + + AssertionError [ERR_ASSERTION]: Expected values to be strictly equal: + +500 !== 200 + + + expected - actual + + -500 + +200 + + at Context. (test\app\controller\system.storage.entry.test.js:217:12) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + + + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +```text +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.storage.entry.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` diff --git a/test_reports/fail/060-mirror.md b/test_reports/fail/060-mirror.md new file mode 100644 index 0000000..d89ae23 --- /dev/null +++ b/test_reports/fail/060-mirror.md @@ -0,0 +1,77 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: mirror +- 文件: test/app/controller/system.storage.inventory.matchPutaway.test.js +- 状态: fail +- 退出码: 1 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) +``` + +## 标准错误 + +```text + + Exception during run: Error: Cannot find module './tencent-cloud' +Require stack: +- D:\wms\worktrees\deploy-20260409155126\config\config.default.js +- D:\wms\worktrees\deploy-20260409155126\database\config.js +- D:\wms\worktrees\deploy-20260409155126\test\app\controller\system.storage.inventory.matchPutaway.test.js + at Module._resolveFilename (node:internal/modules/cjs/loader:1456:15) + at defaultResolveImpl (node:internal/modules/cjs/loader:1066:19) + at resolveForCJSWithHooks (node:internal/modules/cjs/loader:1071:22) + at Module._load (node:internal/modules/cjs/loader:1242:25) + at wrapModuleLoad (node:internal/modules/cjs/loader:255:19) + at Module.require (node:internal/modules/cjs/loader:1556:12) + at require (node:internal/modules/helpers:152:16) + at module.exports (D:\wms\worktrees\deploy-20260409155126\config\config.default.js:21:30) + at loadEggConfig (D:\wms\worktrees\deploy-20260409155126\database\config.js:36:7) + at Object. (D:\wms\worktrees\deploy-20260409155126\database\config.js:56:23) + at Module._compile (node:internal/modules/cjs/loader:1812:14) + at Object..js (node:internal/modules/cjs/loader:1943:10) + at Module.load (node:internal/modules/cjs/loader:1533:32) + at Module._load (node:internal/modules/cjs/loader:1335:12) + at wrapModuleLoad (node:internal/modules/cjs/loader:255:19) + at Module.require (node:internal/modules/cjs/loader:1556:12) + at require (node:internal/modules/helpers:152:16) + at Object. (D:\wms\worktrees\deploy-20260409155126\test\app\controller\system.storage.inventory.matchPutaway.test.js:16:18) + at Module._compile (node:internal/modules/cjs/loader:1812:14) + at Object..js (node:internal/modules/cjs/loader:1943:10) + at Module.load (node:internal/modules/cjs/loader:1533:32) + at Module._load (node:internal/modules/cjs/loader:1335:12) + at wrapModuleLoad (node:internal/modules/cjs/loader:255:19) + at loadCJSModuleWithModuleLoad (node:internal/modules/esm/translators:328:3) + at ModuleWrap. (node:internal/modules/esm/translators:233:7) + at ModuleJob.run (node:internal/modules/esm/module_job:430:25) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:661:26) + at async formattedImport (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:9:14) + at async exports.requireOrImport (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:42:28) + at async exports.loadFilesAsync (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:100:20) + at async singleRun (D:\wms\node_modules\mocha\lib\cli\run-helpers.js:162:3) + at async exports.handler (D:\wms\node_modules\mocha\lib\cli\run.js:375:5) { + code: 'MODULE_NOT_FOUND', + requireStack: [ + 'D:\\wms\\worktrees\\deploy-20260409155126\\config\\config.default.js', + 'D:\\wms\\worktrees\\deploy-20260409155126\\database\\config.js', + 'D:\\wms\\worktrees\\deploy-20260409155126\\test\\app\\controller\\system.storage.inventory.matchPutaway.test.js' + ] +} +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.storage.inventory.matchPutaway.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` diff --git a/test_reports/fail/061-mirror.md b/test_reports/fail/061-mirror.md new file mode 100644 index 0000000..ba5a3a8 --- /dev/null +++ b/test_reports/fail/061-mirror.md @@ -0,0 +1,77 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: mirror +- 文件: test/app/controller/system.storage.inventory.quickPutaway.test.js +- 状态: fail +- 退出码: 1 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) +``` + +## 标准错误 + +```text + + Exception during run: Error: Cannot find module './tencent-cloud' +Require stack: +- D:\wms\worktrees\deploy-20260409155126\config\config.default.js +- D:\wms\worktrees\deploy-20260409155126\database\config.js +- D:\wms\worktrees\deploy-20260409155126\test\app\controller\system.storage.inventory.quickPutaway.test.js + at Module._resolveFilename (node:internal/modules/cjs/loader:1456:15) + at defaultResolveImpl (node:internal/modules/cjs/loader:1066:19) + at resolveForCJSWithHooks (node:internal/modules/cjs/loader:1071:22) + at Module._load (node:internal/modules/cjs/loader:1242:25) + at wrapModuleLoad (node:internal/modules/cjs/loader:255:19) + at Module.require (node:internal/modules/cjs/loader:1556:12) + at require (node:internal/modules/helpers:152:16) + at module.exports (D:\wms\worktrees\deploy-20260409155126\config\config.default.js:21:30) + at loadEggConfig (D:\wms\worktrees\deploy-20260409155126\database\config.js:36:7) + at Object. (D:\wms\worktrees\deploy-20260409155126\database\config.js:56:23) + at Module._compile (node:internal/modules/cjs/loader:1812:14) + at Object..js (node:internal/modules/cjs/loader:1943:10) + at Module.load (node:internal/modules/cjs/loader:1533:32) + at Module._load (node:internal/modules/cjs/loader:1335:12) + at wrapModuleLoad (node:internal/modules/cjs/loader:255:19) + at Module.require (node:internal/modules/cjs/loader:1556:12) + at require (node:internal/modules/helpers:152:16) + at Object. (D:\wms\worktrees\deploy-20260409155126\test\app\controller\system.storage.inventory.quickPutaway.test.js:16:18) + at Module._compile (node:internal/modules/cjs/loader:1812:14) + at Object..js (node:internal/modules/cjs/loader:1943:10) + at Module.load (node:internal/modules/cjs/loader:1533:32) + at Module._load (node:internal/modules/cjs/loader:1335:12) + at wrapModuleLoad (node:internal/modules/cjs/loader:255:19) + at loadCJSModuleWithModuleLoad (node:internal/modules/esm/translators:328:3) + at ModuleWrap. (node:internal/modules/esm/translators:233:7) + at ModuleJob.run (node:internal/modules/esm/module_job:430:25) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:661:26) + at async formattedImport (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:9:14) + at async exports.requireOrImport (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:42:28) + at async exports.loadFilesAsync (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:100:20) + at async singleRun (D:\wms\node_modules\mocha\lib\cli\run-helpers.js:162:3) + at async exports.handler (D:\wms\node_modules\mocha\lib\cli\run.js:375:5) { + code: 'MODULE_NOT_FOUND', + requireStack: [ + 'D:\\wms\\worktrees\\deploy-20260409155126\\config\\config.default.js', + 'D:\\wms\\worktrees\\deploy-20260409155126\\database\\config.js', + 'D:\\wms\\worktrees\\deploy-20260409155126\\test\\app\\controller\\system.storage.inventory.quickPutaway.test.js' + ] +} +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.storage.inventory.quickPutaway.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` diff --git a/test_reports/fail/062-mirror.md b/test_reports/fail/062-mirror.md new file mode 100644 index 0000000..db760bf --- /dev/null +++ b/test_reports/fail/062-mirror.md @@ -0,0 +1,62 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: mirror +- 文件: test/app/controller/system.storage.receiving.test.js +- 状态: fail +- 退出码: 1 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/system.storage.receiving.test.js + 鉁?should query receiving list (1108ms) + 鉁?should query receiving detail when list has records (1254ms) + 1) should bind store to receiving and reject rebinding when owner already exists + 鉁?should reject bindStore when receiving is cancelled (2100ms) + 鉁?should bind and rebind system product for a receiving detail (2642ms) + 鉁?should create and then batch cancel receiving order (1323ms) + 鉁?should generate unique receiving numbers under concurrent create requests (1364ms) + 鉁?should include same-day records when created_at uses daterange filter (1353ms) + 鉁?should reject getReceivingDetail with invalid id (1035ms) + 鉁?should reject create with invalid loading_method enum (1061ms) + 鉁?should reject batchCancelReceiving with nonexistent ids (1044ms) + + + 10 passing (15s) + 1 failing + + 1) test/app/controller/system.storage.receiving.test.js + should bind store to receiving and reject rebinding when owner already exists: + TypeError: fetch failed + + Caused by: Error: read ECONNRESET + at TCP.onStreamRead (node:internal/stream_base_commons:216:20) + + + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +```text +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.storage.receiving.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` diff --git a/test_reports/fail/063-mirror.md b/test_reports/fail/063-mirror.md new file mode 100644 index 0000000..073f3b5 --- /dev/null +++ b/test_reports/fail/063-mirror.md @@ -0,0 +1,77 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: mirror +- 文件: test/app/controller/system.storage.transaction.test.js +- 状态: fail +- 退出码: 1 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) +``` + +## 标准错误 + +```text + + Exception during run: Error: Cannot find module './tencent-cloud' +Require stack: +- D:\wms\worktrees\deploy-20260409155126\config\config.default.js +- D:\wms\worktrees\deploy-20260409155126\database\config.js +- D:\wms\worktrees\deploy-20260409155126\test\app\controller\system.storage.transaction.test.js + at Module._resolveFilename (node:internal/modules/cjs/loader:1456:15) + at defaultResolveImpl (node:internal/modules/cjs/loader:1066:19) + at resolveForCJSWithHooks (node:internal/modules/cjs/loader:1071:22) + at Module._load (node:internal/modules/cjs/loader:1242:25) + at wrapModuleLoad (node:internal/modules/cjs/loader:255:19) + at Module.require (node:internal/modules/cjs/loader:1556:12) + at require (node:internal/modules/helpers:152:16) + at module.exports (D:\wms\worktrees\deploy-20260409155126\config\config.default.js:21:30) + at loadEggConfig (D:\wms\worktrees\deploy-20260409155126\database\config.js:36:7) + at Object. (D:\wms\worktrees\deploy-20260409155126\database\config.js:56:23) + at Module._compile (node:internal/modules/cjs/loader:1812:14) + at Object..js (node:internal/modules/cjs/loader:1943:10) + at Module.load (node:internal/modules/cjs/loader:1533:32) + at Module._load (node:internal/modules/cjs/loader:1335:12) + at wrapModuleLoad (node:internal/modules/cjs/loader:255:19) + at Module.require (node:internal/modules/cjs/loader:1556:12) + at require (node:internal/modules/helpers:152:16) + at Object. (D:\wms\worktrees\deploy-20260409155126\test\app\controller\system.storage.transaction.test.js:16:18) + at Module._compile (node:internal/modules/cjs/loader:1812:14) + at Object..js (node:internal/modules/cjs/loader:1943:10) + at Module.load (node:internal/modules/cjs/loader:1533:32) + at Module._load (node:internal/modules/cjs/loader:1335:12) + at wrapModuleLoad (node:internal/modules/cjs/loader:255:19) + at loadCJSModuleWithModuleLoad (node:internal/modules/esm/translators:328:3) + at ModuleWrap. (node:internal/modules/esm/translators:233:7) + at ModuleJob.run (node:internal/modules/esm/module_job:430:25) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:661:26) + at async formattedImport (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:9:14) + at async exports.requireOrImport (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:42:28) + at async exports.loadFilesAsync (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:100:20) + at async singleRun (D:\wms\node_modules\mocha\lib\cli\run-helpers.js:162:3) + at async exports.handler (D:\wms\node_modules\mocha\lib\cli\run.js:375:5) { + code: 'MODULE_NOT_FOUND', + requireStack: [ + 'D:\\wms\\worktrees\\deploy-20260409155126\\config\\config.default.js', + 'D:\\wms\\worktrees\\deploy-20260409155126\\database\\config.js', + 'D:\\wms\\worktrees\\deploy-20260409155126\\test\\app\\controller\\system.storage.transaction.test.js' + ] +} +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.storage.transaction.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` diff --git a/test_reports/fail/076-mirror.md b/test_reports/fail/076-mirror.md new file mode 100644 index 0000000..6af17b9 --- /dev/null +++ b/test_reports/fail/076-mirror.md @@ -0,0 +1,56 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: mirror +- 文件: test/app/service/systems/license_plate.test.js +- 状态: fail +- 退出码: 1 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (1ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) +``` + +## 标准错误 + +```text + + Exception during run: Error: ENOENT: no such file or directory, open 'D:\wms\worktrees\deploy-20260409155126\temp\cp.png' + at Object.openSync (node:fs:560:18) + at Object.readFileSync (node:fs:444:35) + at Object. (D:\wms\worktrees\deploy-20260409155126\test\app\service\systems\license_plate.test.js:9:31) + at Module._compile (node:internal/modules/cjs/loader:1812:14) + at Object..js (node:internal/modules/cjs/loader:1943:10) + at Module.load (node:internal/modules/cjs/loader:1533:32) + at Module._load (node:internal/modules/cjs/loader:1335:12) + at wrapModuleLoad (node:internal/modules/cjs/loader:255:19) + at loadCJSModuleWithModuleLoad (node:internal/modules/esm/translators:328:3) + at ModuleWrap. (node:internal/modules/esm/translators:233:7) + at ModuleJob.run (node:internal/modules/esm/module_job:430:25) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:661:26) + at async formattedImport (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:9:14) + at async exports.requireOrImport (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:42:28) + at async exports.loadFilesAsync (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:100:20) + at async singleRun (D:\wms\node_modules\mocha\lib\cli\run-helpers.js:162:3) + at async exports.handler (D:\wms\node_modules\mocha\lib\cli\run.js:375:5) { + errno: -4058, + code: 'ENOENT', + syscall: 'open', + path: 'D:\\wms\\worktrees\\deploy-20260409155126\\temp\\cp.png' +} +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/service/systems/license_plate.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` diff --git a/test_reports/fail/077-mirror.md b/test_reports/fail/077-mirror.md new file mode 100644 index 0000000..2100cf2 --- /dev/null +++ b/test_reports/fail/077-mirror.md @@ -0,0 +1,77 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: mirror +- 文件: test/app/service/systems/notice.test.js +- 状态: fail +- 退出码: 1 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/service/systems/notice.test.js + 1) should normalize payload and send only matching webhooks + 鉁?should enrich payload with store info from cache before querying database + 鉁?should load store info from database and cache it when cache is empty + 鉁?should send to both warehouse and owner webhooks when events match or are set to all + 鉁?should only send up to the configured webhook limit + 鉁?should require url for image or file message + 鉁?should require warehouseId but allow empty ownerId + 鉁?should retry failed webhooks three times and persist final failures + 鉁?should reject sending unregistered event + 鉁?should reject dotted or numeric-leading event names + 鉁?should send wecom webhook as enterprise wechat direct message + 鉁?should expose available webhook events and reject unsupported ones + + + 11 passing (12ms) + 1 failing + + 1) test/app/service/systems/notice.test.js + should normalize payload and send only matching webhooks: + + AssertionError [ERR_ASSERTION]: Expected values to be strictly equal: ++ actual - expected + ++ 100000 +- 1000000 + + + expected - actual + + -100000 + +1000000 + + at Object.findAll (test\app\service\systems\notice.test.js:34:20) + at D:\wms\worktrees\deploy-20260409155126\app\service\systems\notice\index.js:796:43 + at Array.map () + at NoticeService.findMatchedWebhooks (app\service\systems\notice\index.js:786:62) + at NoticeService.send (app\service\systems\notice\index.js:826:33) + at async Context. (test\app\service\systems\notice.test.js:55:20) + + + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +```text +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/service/systems/notice.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` diff --git a/test_reports/fail/20260410-130419-main-skip-app_controller_gateway.user.bindAccountByTempCode.test.js.md b/test_reports/fail/20260410-130419-main-skip-app_controller_gateway.user.bindAccountByTempCode.test.js.md new file mode 100644 index 0000000..6be87bc --- /dev/null +++ b/test_reports/fail/20260410-130419-main-skip-app_controller_gateway.user.bindAccountByTempCode.test.js.md @@ -0,0 +1,64 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 主区 +- 文件: app/controller/gateway.user.bindAccountByTempCode.test.js +- 源: main +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:04:24.171Z +- 结束时间: 2026-04-10T13:04:25.661Z +- 耗时(秒): 1 +- 退出码: 1 +- 说明: 环境/数据缺失: timeout + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + Exception during run: AssertionError [ERR_ASSERTION]: SYSTEM_TEST_YE4S_USER_ID 必须显式提供且为正整数 + at Object. (D:\wms\test\app\controller\gateway.user.bindAccountByTempCode.test.js:12:8) + at Module._compile (node:internal/modules/cjs/loader:1812:14) + at Object..js (node:internal/modules/cjs/loader:1943:10) + at Module.load (node:internal/modules/cjs/loader:1533:32) + at Module._load (node:internal/modules/cjs/loader:1335:12) + at wrapModuleLoad (node:internal/modules/cjs/loader:255:19) + at loadCJSModuleWithModuleLoad (node:internal/modules/esm/translators:328:3) + at ModuleWrap. (node:internal/modules/esm/translators:233:7) + at ModuleJob.run (node:internal/modules/esm/module_job:430:25) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:661:26) + at async formattedImport (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:9:14) + at async exports.requireOrImport (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:42:28) + at async exports.loadFilesAsync (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:100:20) + at async singleRun (D:\wms\node_modules\mocha\lib\cli\run-helpers.js:162:3) + at async exports.handler (D:\wms\node_modules\mocha\lib\cli\run.js:375:5) { + generatedMessage: false, + code: 'ERR_ASSERTION', + actual: false, + expected: true, + operator: '==', + diff: 'simple' +} +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/gateway.user.bindAccountByTempCode.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260410-130419-main-skip-app_controller_system.order.getreviewOrderlist.test.js.md b/test_reports/fail/20260410-130419-main-skip-app_controller_system.order.getreviewOrderlist.test.js.md new file mode 100644 index 0000000..0902c27 --- /dev/null +++ b/test_reports/fail/20260410-130419-main-skip-app_controller_system.order.getreviewOrderlist.test.js.md @@ -0,0 +1,61 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 主区 +- 文件: app/controller/system.order.getreviewOrderlist.test.js +- 源: main +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:04:29.982Z +- 结束时间: 2026-04-10T13:04:31.444Z +- 耗时(秒): 1 +- 退出码: 1 +- 说明: 环境/数据缺失: ECONNREFUSED + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/system.order.getreviewOrderlist.test.js + 1) should call order.getreviewOrderlist with platform=web project=all + + + 0 passing (18ms) + 1 failing + + 1) test/app/controller/system.order.getreviewOrderlist.test.js + should call order.getreviewOrderlist with platform=web project=all: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + + +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.order.getreviewOrderlist.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260410-130419-main-skip-app_controller_system.order.namespaced.test.js.md b/test_reports/fail/20260410-130419-main-skip-app_controller_system.order.namespaced.test.js.md new file mode 100644 index 0000000..27c619c --- /dev/null +++ b/test_reports/fail/20260410-130419-main-skip-app_controller_system.order.namespaced.test.js.md @@ -0,0 +1,77 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 主区 +- 文件: app/controller/system.order.namespaced.test.js +- 源: main +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:04:31.445Z +- 结束时间: 2026-04-10T13:04:32.929Z +- 耗时(秒): 1 +- 退出码: 1 +- 说明: 环境/数据缺失: ECONNREFUSED + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/system.order.namespaced.test.js + 1) should query all namespaced order lists + 2) should review order through namespaced method and restore status + 3) should return audit_status in delivery orders and support filtering + + + 0 passing (25ms) + 3 failing + + 1) test/app/controller/system.order.namespaced.test.js + should query all namespaced order lists: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + 2) test/app/controller/system.order.namespaced.test.js + should review order through namespaced method and restore status: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + 3) test/app/controller/system.order.namespaced.test.js + should return audit_status in delivery orders and support filtering: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + + +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.order.namespaced.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260410-130419-main-skip-app_controller_system.order.reviewOrder.test.js.md b/test_reports/fail/20260410-130419-main-skip-app_controller_system.order.reviewOrder.test.js.md new file mode 100644 index 0000000..49b9636 --- /dev/null +++ b/test_reports/fail/20260410-130419-main-skip-app_controller_system.order.reviewOrder.test.js.md @@ -0,0 +1,61 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 主区 +- 文件: app/controller/system.order.reviewOrder.test.js +- 源: main +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:04:32.929Z +- 结束时间: 2026-04-10T13:04:34.410Z +- 耗时(秒): 1 +- 退出码: 1 +- 说明: 环境/数据缺失: ECONNREFUSED + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (3ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (4ms) +[egg-ts-helper] create typings\config\index.d.ts (14ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.order.reviewOrder.test.js + 1) should review order and restore inspection status + + + 0 passing (20ms) + 1 failing + + 1) test/app/controller/system.order.reviewOrder.test.js + should review order and restore inspection status: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + + +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.order.reviewOrder.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260410-130419-main-skip-app_controller_system.setting.account.getBindWechatCode.test.js.md b/test_reports/fail/20260410-130419-main-skip-app_controller_system.setting.account.getBindWechatCode.test.js.md new file mode 100644 index 0000000..b66c579 --- /dev/null +++ b/test_reports/fail/20260410-130419-main-skip-app_controller_system.setting.account.getBindWechatCode.test.js.md @@ -0,0 +1,64 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 主区 +- 文件: app/controller/system.setting.account.getBindWechatCode.test.js +- 源: main +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:04:34.411Z +- 结束时间: 2026-04-10T13:04:35.878Z +- 耗时(秒): 1 +- 退出码: 1 +- 说明: 环境/数据缺失: timeout + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (3ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + Exception during run: AssertionError [ERR_ASSERTION]: SYSTEM_TEST_YE4S_USER_ID 必须显式提供且为正整数 + at Object. (D:\wms\test\app\controller\system.setting.account.getBindWechatCode.test.js:12:8) + at Module._compile (node:internal/modules/cjs/loader:1812:14) + at Object..js (node:internal/modules/cjs/loader:1943:10) + at Module.load (node:internal/modules/cjs/loader:1533:32) + at Module._load (node:internal/modules/cjs/loader:1335:12) + at wrapModuleLoad (node:internal/modules/cjs/loader:255:19) + at loadCJSModuleWithModuleLoad (node:internal/modules/esm/translators:328:3) + at ModuleWrap. (node:internal/modules/esm/translators:233:7) + at ModuleJob.run (node:internal/modules/esm/module_job:430:25) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:661:26) + at async formattedImport (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:9:14) + at async exports.requireOrImport (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:42:28) + at async exports.loadFilesAsync (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:100:20) + at async singleRun (D:\wms\node_modules\mocha\lib\cli\run-helpers.js:162:3) + at async exports.handler (D:\wms\node_modules\mocha\lib\cli\run.js:375:5) { + generatedMessage: false, + code: 'ERR_ASSERTION', + actual: false, + expected: true, + operator: '==', + diff: 'simple' +} +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.setting.account.getBindWechatCode.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260410-130419-main-skip-app_controller_system.setting.account.test.js.md b/test_reports/fail/20260410-130419-main-skip-app_controller_system.setting.account.test.js.md new file mode 100644 index 0000000..b7e0629 --- /dev/null +++ b/test_reports/fail/20260410-130419-main-skip-app_controller_system.setting.account.test.js.md @@ -0,0 +1,61 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 主区 +- 文件: app/controller/system.setting.account.test.js +- 源: main +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:04:35.879Z +- 结束时间: 2026-04-10T13:04:37.367Z +- 耗时(秒): 1 +- 退出码: 1 +- 说明: 环境/数据缺失: ECONNREFUSED + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/system.setting.account.test.js + 1) "before all" hook for "error-1 should reject add when real_name is reserved name" + + + 0 passing (20ms) + 1 failing + + 1) test/app/controller/system.setting.account.test.js + "before all" hook for "error-1 should reject add when real_name is reserved name": + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + + +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.setting.account.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260410-130419-main-skip-app_controller_system.setting.permission.test.js.md b/test_reports/fail/20260410-130419-main-skip-app_controller_system.setting.permission.test.js.md new file mode 100644 index 0000000..5e85d35 --- /dev/null +++ b/test_reports/fail/20260410-130419-main-skip-app_controller_system.setting.permission.test.js.md @@ -0,0 +1,61 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 主区 +- 文件: app/controller/system.setting.permission.test.js +- 源: main +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:04:37.368Z +- 结束时间: 2026-04-10T13:04:38.828Z +- 耗时(秒): 1 +- 退出码: 1 +- 说明: 环境/数据缺失: ECONNREFUSED + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (1ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.setting.permission.test.js + 1) "before all" hook for "should expose setting.role.permission as alias of setting.permission.list" + + + 0 passing (17ms) + 1 failing + + 1) test/app/controller/system.setting.permission.test.js + "before all" hook for "should expose setting.role.permission as alias of setting.permission.list": + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + + +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.setting.permission.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260410-130419-main-skip-app_controller_system.setting.printTemplate.test.js.md b/test_reports/fail/20260410-130419-main-skip-app_controller_system.setting.printTemplate.test.js.md new file mode 100644 index 0000000..077c603 --- /dev/null +++ b/test_reports/fail/20260410-130419-main-skip-app_controller_system.setting.printTemplate.test.js.md @@ -0,0 +1,61 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 主区 +- 文件: app/controller/system.setting.printTemplate.test.js +- 源: main +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:04:38.829Z +- 结束时间: 2026-04-10T13:04:40.275Z +- 耗时(秒): 1 +- 退出码: 1 +- 说明: 环境/数据缺失: ECONNREFUSED + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (1ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/system.setting.printTemplate.test.js + 1) "before all" hook for "normal-1 should create print template successfully" + + + 0 passing (18ms) + 1 failing + + 1) test/app/controller/system.setting.printTemplate.test.js + "before all" hook for "normal-1 should create print template successfully": + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + + +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.setting.printTemplate.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260410-130419-main-skip-app_controller_system.setting.role.test.js.md b/test_reports/fail/20260410-130419-main-skip-app_controller_system.setting.role.test.js.md new file mode 100644 index 0000000..0b1565f --- /dev/null +++ b/test_reports/fail/20260410-130419-main-skip-app_controller_system.setting.role.test.js.md @@ -0,0 +1,61 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 主区 +- 文件: app/controller/system.setting.role.test.js +- 源: main +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:04:40.276Z +- 结束时间: 2026-04-10T13:04:41.764Z +- 耗时(秒): 1 +- 退出码: 1 +- 说明: 环境/数据缺失: ECONNREFUSED + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (14ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/system.setting.role.test.js + 1) "before all" hook for "should support wildcard role permissions via ["*"]" + + + 0 passing (18ms) + 1 failing + + 1) test/app/controller/system.setting.role.test.js + "before all" hook for "should support wildcard role permissions via ["*"]": + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + + +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.setting.role.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260410-130419-main-skip-app_controller_system.setting.storeWarehouse.test.js.md b/test_reports/fail/20260410-130419-main-skip-app_controller_system.setting.storeWarehouse.test.js.md new file mode 100644 index 0000000..e3b3c4f --- /dev/null +++ b/test_reports/fail/20260410-130419-main-skip-app_controller_system.setting.storeWarehouse.test.js.md @@ -0,0 +1,61 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 主区 +- 文件: app/controller/system.setting.storeWarehouse.test.js +- 源: main +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:04:41.764Z +- 结束时间: 2026-04-10T13:04:43.267Z +- 耗时(秒): 2 +- 退出码: 1 +- 说明: 环境/数据缺失: ECONNREFUSED + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (1ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.setting.storeWarehouse.test.js + 1) "before all" hook for "should list store-warehouse contracts in current subject scope" + + + 0 passing (19ms) + 1 failing + + 1) test/app/controller/system.setting.storeWarehouse.test.js + "before all" hook for "should list store-warehouse contracts in current subject scope": + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + + +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.setting.storeWarehouse.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260410-130419-main-skip-app_controller_system.stock.warehouse.getStockDetail.test.js.md b/test_reports/fail/20260410-130419-main-skip-app_controller_system.stock.warehouse.getStockDetail.test.js.md new file mode 100644 index 0000000..01e8ada --- /dev/null +++ b/test_reports/fail/20260410-130419-main-skip-app_controller_system.stock.warehouse.getStockDetail.test.js.md @@ -0,0 +1,61 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 主区 +- 文件: app/controller/system.stock.warehouse.getStockDetail.test.js +- 源: main +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:04:43.267Z +- 结束时间: 2026-04-10T13:04:44.751Z +- 耗时(秒): 1 +- 退出码: 1 +- 说明: 环境/数据缺失: ECONNREFUSED + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.stock.warehouse.getStockDetail.test.js + 1) "before all" hook for "should return stockItem, storageList and pagination for a valid stock_id" + + + 0 passing (18ms) + 1 failing + + 1) test/app/controller/system.stock.warehouse.getStockDetail.test.js + "before all" hook for "should return stockItem, storageList and pagination for a valid stock_id": + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + + +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.stock.warehouse.getStockDetail.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260410-130419-main-skip-app_controller_system.stock.warehouse.namespaced.test.js.md b/test_reports/fail/20260410-130419-main-skip-app_controller_system.stock.warehouse.namespaced.test.js.md new file mode 100644 index 0000000..6df3e35 --- /dev/null +++ b/test_reports/fail/20260410-130419-main-skip-app_controller_system.stock.warehouse.namespaced.test.js.md @@ -0,0 +1,61 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 主区 +- 文件: app/controller/system.stock.warehouse.namespaced.test.js +- 源: main +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:04:44.751Z +- 结束时间: 2026-04-10T13:04:46.259Z +- 耗时(秒): 2 +- 退出码: 1 +- 说明: 环境/数据缺失: ECONNREFUSED + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (3ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (15ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/system.stock.warehouse.namespaced.test.js + 1) should query stock warehouse list via namespaced method + + + 0 passing (19ms) + 1 failing + + 1) test/app/controller/system.stock.warehouse.namespaced.test.js + should query stock warehouse list via namespaced method: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + + +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.stock.warehouse.namespaced.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260410-130419-main-skip-app_controller_system.storage.delivery.module.test.js.md b/test_reports/fail/20260410-130419-main-skip-app_controller_system.storage.delivery.module.test.js.md new file mode 100644 index 0000000..fd97808 --- /dev/null +++ b/test_reports/fail/20260410-130419-main-skip-app_controller_system.storage.delivery.module.test.js.md @@ -0,0 +1,85 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 主区 +- 文件: app/controller/system.storage.delivery.module.test.js +- 源: main +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:04:46.260Z +- 结束时间: 2026-04-10T13:04:47.734Z +- 耗时(秒): 1 +- 退出码: 1 +- 说明: 环境/数据缺失: ECONNREFUSED + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.storage.delivery.module.test.js + 1) should return delivery list via storage.stockout.list + 2) should return placeholder failure via storage.stockout.toOrder + 3) should return item list via storage.stockout.listItems + 4) should not expose removed storage.entry detail methods + + + 0 passing (23ms) + 4 failing + + 1) test/app/controller/system.storage.delivery.module.test.js + should return delivery list via storage.stockout.list: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + 2) test/app/controller/system.storage.delivery.module.test.js + should return placeholder failure via storage.stockout.toOrder: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + 3) test/app/controller/system.storage.delivery.module.test.js + should return item list via storage.stockout.listItems: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + 4) test/app/controller/system.storage.delivery.module.test.js + should not expose removed storage.entry detail methods: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + + +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.storage.delivery.module.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260410-130419-main-skip-app_controller_system.storage.entry.test.js.md b/test_reports/fail/20260410-130419-main-skip-app_controller_system.storage.entry.test.js.md new file mode 100644 index 0000000..c1b8dd0 --- /dev/null +++ b/test_reports/fail/20260410-130419-main-skip-app_controller_system.storage.entry.test.js.md @@ -0,0 +1,85 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 主区 +- 文件: app/controller/system.storage.entry.test.js +- 源: main +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:04:47.735Z +- 结束时间: 2026-04-10T13:04:49.200Z +- 耗时(秒): 1 +- 退出码: 1 +- 说明: 环境/数据缺失: ECONNREFUSED + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.storage.entry.test.js + 1) should query entry list + 2) should create entry and run detail lifecycle then cancel + 3) should complete entry after adding detail + 4) should reject invalid params for create/get/addDetail + + + 0 passing (26ms) + 4 failing + + 1) test/app/controller/system.storage.entry.test.js + should query entry list: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + 2) test/app/controller/system.storage.entry.test.js + should create entry and run detail lifecycle then cancel: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + 3) test/app/controller/system.storage.entry.test.js + should complete entry after adding detail: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + 4) test/app/controller/system.storage.entry.test.js + should reject invalid params for create/get/addDetail: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + + +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.storage.entry.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260410-130419-main-skip-app_controller_system.storage.inventory.matchPutaway.test.js.md b/test_reports/fail/20260410-130419-main-skip-app_controller_system.storage.inventory.matchPutaway.test.js.md new file mode 100644 index 0000000..d679f00 --- /dev/null +++ b/test_reports/fail/20260410-130419-main-skip-app_controller_system.storage.inventory.matchPutaway.test.js.md @@ -0,0 +1,61 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 主区 +- 文件: app/controller/system.storage.inventory.matchPutaway.test.js +- 源: main +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:04:49.201Z +- 结束时间: 2026-04-10T13:04:50.802Z +- 耗时(秒): 2 +- 退出码: 1 +- 说明: 环境/数据缺失: ECONNREFUSED + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/system.storage.inventory.matchPutaway.test.js + 1) "before all" hook for "should match putaway when receiving equals entry order (exact match)" + + + 0 passing (19ms) + 1 failing + + 1) test/app/controller/system.storage.inventory.matchPutaway.test.js + "before all" hook for "should match putaway when receiving equals entry order (exact match)": + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + + +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.storage.inventory.matchPutaway.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260410-130419-main-skip-app_controller_system.storage.inventory.quickPutaway.test.js.md b/test_reports/fail/20260410-130419-main-skip-app_controller_system.storage.inventory.quickPutaway.test.js.md new file mode 100644 index 0000000..11972b2 --- /dev/null +++ b/test_reports/fail/20260410-130419-main-skip-app_controller_system.storage.inventory.quickPutaway.test.js.md @@ -0,0 +1,61 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 主区 +- 文件: app/controller/system.storage.inventory.quickPutaway.test.js +- 源: main +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:04:50.803Z +- 结束时间: 2026-04-10T13:04:52.544Z +- 耗时(秒): 2 +- 退出码: 1 +- 说明: 环境/数据缺失: ECONNREFUSED + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/system.storage.inventory.quickPutaway.test.js + 1) "before all" hook for "should reject quickPutaway for partially matched receiving" + + + 0 passing (22ms) + 1 failing + + 1) test/app/controller/system.storage.inventory.quickPutaway.test.js + "before all" hook for "should reject quickPutaway for partially matched receiving": + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + + +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.storage.inventory.quickPutaway.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260410-130419-main-skip-app_controller_system.storage.receiving.test.js.md b/test_reports/fail/20260410-130419-main-skip-app_controller_system.storage.receiving.test.js.md new file mode 100644 index 0000000..65cc6ce --- /dev/null +++ b/test_reports/fail/20260410-130419-main-skip-app_controller_system.storage.receiving.test.js.md @@ -0,0 +1,173 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 主区 +- 文件: app/controller/system.storage.receiving.test.js +- 源: main +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:04:52.545Z +- 结束时间: 2026-04-10T13:04:54.065Z +- 耗时(秒): 2 +- 退出码: 1 +- 说明: 环境/数据缺失: ECONNREFUSED + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (1ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (15ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/system.storage.receiving.test.js + 1) should query receiving list + 2) should query receiving detail when list has records + 3) should bind store to receiving and reject rebinding when owner already exists + 4) should reject bindStore when receiving is cancelled + 5) should bind and rebind system product for a receiving detail + 6) should create and then batch cancel receiving order + 7) should generate unique receiving numbers under concurrent create requests + 8) should include same-day records when created_at uses daterange filter + 9) should reject getReceivingDetail with invalid id + 10) should reject create with invalid loading_method enum + 11) should reject batchCancelReceiving with nonexistent ids + 12) should get receiving detail with details and images via storage.receiving.get + 13) should return code 0 when getting non-existent receiving via storage.receiving.get + 14) should return details sorted by id DESC via storage.receiving.get + 15) should include location space info in details via storage.receiving.get + + + 0 passing (36ms) + 15 failing + + 1) test/app/controller/system.storage.receiving.test.js + should query receiving list: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + 2) test/app/controller/system.storage.receiving.test.js + should query receiving detail when list has records: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + 3) test/app/controller/system.storage.receiving.test.js + should bind store to receiving and reject rebinding when owner already exists: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + 4) test/app/controller/system.storage.receiving.test.js + should reject bindStore when receiving is cancelled: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + 5) test/app/controller/system.storage.receiving.test.js + should bind and rebind system product for a receiving detail: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + 6) test/app/controller/system.storage.receiving.test.js + should create and then batch cancel receiving order: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + 7) test/app/controller/system.storage.receiving.test.js + should generate unique receiving numbers under concurrent create requests: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + 8) test/app/controller/system.storage.receiving.test.js + should include same-day records when created_at uses daterange filter: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + 9) test/app/controller/system.storage.receiving.test.js + should reject getReceivingDetail with invalid id: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + 10) test/app/controller/system.storage.receiving.test.js + should reject create with invalid loading_method enum: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + 11) test/app/controller/system.storage.receiving.test.js + should reject batchCancelReceiving with nonexistent ids: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + 12) test/app/controller/system.storage.receiving.test.js + should get receiving detail with details and images via storage.receiving.get: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + 13) test/app/controller/system.storage.receiving.test.js + should return code 0 when getting non-existent receiving via storage.receiving.get: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + 14) test/app/controller/system.storage.receiving.test.js + should return details sorted by id DESC via storage.receiving.get: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + 15) test/app/controller/system.storage.receiving.test.js + should include location space info in details via storage.receiving.get: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + + +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.storage.receiving.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260410-130419-main-skip-app_controller_system.storage.transaction.test.js.md b/test_reports/fail/20260410-130419-main-skip-app_controller_system.storage.transaction.test.js.md new file mode 100644 index 0000000..e9bc89e --- /dev/null +++ b/test_reports/fail/20260410-130419-main-skip-app_controller_system.storage.transaction.test.js.md @@ -0,0 +1,61 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 主区 +- 文件: app/controller/system.storage.transaction.test.js +- 源: main +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:04:54.066Z +- 结束时间: 2026-04-10T13:04:55.670Z +- 耗时(秒): 2 +- 退出码: 1 +- 说明: 环境/数据缺失: ECONNREFUSED + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.storage.transaction.test.js + 1) "before all" hook for "should write INBOUND/SCRK records to wms_stock_transaction after quickPutaway" + + + 0 passing (19ms) + 1 failing + + 1) test/app/controller/system.storage.transaction.test.js + "before all" hook for "should write INBOUND/SCRK records to wms_stock_transaction after quickPutaway": + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + + +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.storage.transaction.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260410-130419-main-skip-app_controller_system.storeWarehouse.test.js.md b/test_reports/fail/20260410-130419-main-skip-app_controller_system.storeWarehouse.test.js.md new file mode 100644 index 0000000..6536960 --- /dev/null +++ b/test_reports/fail/20260410-130419-main-skip-app_controller_system.storeWarehouse.test.js.md @@ -0,0 +1,61 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 主区 +- 文件: app/controller/system.storeWarehouse.test.js +- 源: main +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:04:55.671Z +- 结束时间: 2026-04-10T13:04:57.139Z +- 耗时(秒): 1 +- 退出码: 1 +- 说明: 环境/数据缺失: ECONNREFUSED + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.storeWarehouse.test.js + 1) "before all" hook for "should expose standalone storeWarehouse.store.list" + + + 0 passing (18ms) + 1 failing + + 1) test/app/controller/system.storeWarehouse.test.js + "before all" hook for "should expose standalone storeWarehouse.store.list": + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + + +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.storeWarehouse.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260410-130419-main-skip-app_controller_system.user.changeRole.test.js.md b/test_reports/fail/20260410-130419-main-skip-app_controller_system.user.changeRole.test.js.md new file mode 100644 index 0000000..a27df9d --- /dev/null +++ b/test_reports/fail/20260410-130419-main-skip-app_controller_system.user.changeRole.test.js.md @@ -0,0 +1,61 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 主区 +- 文件: app/controller/system.user.changeRole.test.js +- 源: main +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:04:57.139Z +- 结束时间: 2026-04-10T13:04:58.632Z +- 耗时(秒): 1 +- 退出码: 1 +- 说明: 环境/数据缺失: ECONNREFUSED + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.user.changeRole.test.js + 1) should switch role via user.changeRole and persist response + + + 0 passing (19ms) + 1 failing + + 1) test/app/controller/system.user.changeRole.test.js + should switch role via user.changeRole and persist response: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + + +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.user.changeRole.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260410-130419-main-skip-app_controller_system.user.getLoginWechatCode.test.js.md b/test_reports/fail/20260410-130419-main-skip-app_controller_system.user.getLoginWechatCode.test.js.md new file mode 100644 index 0000000..c67ea27 --- /dev/null +++ b/test_reports/fail/20260410-130419-main-skip-app_controller_system.user.getLoginWechatCode.test.js.md @@ -0,0 +1,61 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 主区 +- 文件: app/controller/system.user.getLoginWechatCode.test.js +- 源: main +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:04:58.632Z +- 结束时间: 2026-04-10T13:05:00.106Z +- 耗时(秒): 1 +- 退出码: 1 +- 说明: 环境/数据缺失: ECONNREFUSED + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/system.user.getLoginWechatCode.test.js + 1) should return login code without Authorization token + + + 0 passing (19ms) + 1 failing + + 1) test/app/controller/system.user.getLoginWechatCode.test.js + should return login code without Authorization token: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + + +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.user.getLoginWechatCode.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260410-130419-main-skip-app_controller_system.user.info.test.js.md b/test_reports/fail/20260410-130419-main-skip-app_controller_system.user.info.test.js.md new file mode 100644 index 0000000..cb43967 --- /dev/null +++ b/test_reports/fail/20260410-130419-main-skip-app_controller_system.user.info.test.js.md @@ -0,0 +1,61 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 主区 +- 文件: app/controller/system.user.info.test.js +- 源: main +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:05:00.107Z +- 结束时间: 2026-04-10T13:05:01.635Z +- 耗时(秒): 2 +- 退出码: 1 +- 说明: 环境/数据缺失: ECONNREFUSED + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (1ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (5ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/system.user.info.test.js + 1) should call user.info with bearer token + + + 0 passing (21ms) + 1 failing + + 1) test/app/controller/system.user.info.test.js + should call user.info with bearer token: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + + +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.user.info.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260410-130419-main-skip-app_controller_system.user.info.web.test.js.md b/test_reports/fail/20260410-130419-main-skip-app_controller_system.user.info.web.test.js.md new file mode 100644 index 0000000..507bd8b --- /dev/null +++ b/test_reports/fail/20260410-130419-main-skip-app_controller_system.user.info.web.test.js.md @@ -0,0 +1,61 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 主区 +- 文件: app/controller/system.user.info.web.test.js +- 源: main +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:05:01.636Z +- 结束时间: 2026-04-10T13:05:03.098Z +- 耗时(秒): 1 +- 退出码: 1 +- 说明: 环境/数据缺失: ECONNREFUSED + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (3ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.user.info.web.test.js + 1) should call user.info with platform=web project=all and persist response + + + 0 passing (18ms) + 1 failing + + 1) test/app/controller/system.user.info.web.test.js + should call user.info with platform=web project=all and persist response: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + + +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.user.info.web.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260410-130419-main-skip-app_controller_system.user.login.test.js.md b/test_reports/fail/20260410-130419-main-skip-app_controller_system.user.login.test.js.md new file mode 100644 index 0000000..404affd --- /dev/null +++ b/test_reports/fail/20260410-130419-main-skip-app_controller_system.user.login.test.js.md @@ -0,0 +1,63 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 主区 +- 文件: app/controller/system.user.login.test.js +- 源: main +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:05:03.099Z +- 结束时间: 2026-04-10T13:05:04.597Z +- 耗时(秒): 1 +- 退出码: 1 +- 说明: 环境/数据缺失: ECONNREFUSED + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/system.user.login.test.js + ✔ should get token from cache or login method + ✔ should persist token cache file + 1) user.login should return token only + + + 2 passing (20ms) + 1 failing + + 1) test/app/controller/system.user.login.test.js + user.login should return token only: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + + +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.user.login.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260410-130419-main-skip-app_controller_system.user.loginByCode.test.js.md b/test_reports/fail/20260410-130419-main-skip-app_controller_system.user.loginByCode.test.js.md new file mode 100644 index 0000000..6e3c8f3 --- /dev/null +++ b/test_reports/fail/20260410-130419-main-skip-app_controller_system.user.loginByCode.test.js.md @@ -0,0 +1,79 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 主区 +- 文件: app/controller/system.user.loginByCode.test.js +- 源: main +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:05:04.598Z +- 结束时间: 2026-04-10T13:05:06.057Z +- 耗时(秒): 1 +- 退出码: 1 +- 说明: 环境/数据缺失: ECONNREFUSED + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/system.user.loginByCode.test.js + - should login successfully when code is valid + 1) should fail when code is missing + 2) should fail when code does not exist + 3) should fail when code format is valid but not matched + + + 0 passing (22ms) + 1 pending + 3 failing + + 1) test/app/controller/system.user.loginByCode.test.js + should fail when code is missing: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + 2) test/app/controller/system.user.loginByCode.test.js + should fail when code does not exist: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + 3) test/app/controller/system.user.loginByCode.test.js + should fail when code format is valid but not matched: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + + +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.user.loginByCode.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260410-130419-main-skip-app_service_systems_delivery_order.auditStatus.test.js.md b/test_reports/fail/20260410-130419-main-skip-app_service_systems_delivery_order.auditStatus.test.js.md new file mode 100644 index 0000000..c00a52c --- /dev/null +++ b/test_reports/fail/20260410-130419-main-skip-app_service_systems_delivery_order.auditStatus.test.js.md @@ -0,0 +1,88 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 主区 +- 文件: app/service/systems/delivery_order.auditStatus.test.js +- 源: main +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:05:18.593Z +- 结束时间: 2026-04-10T13:05:22.877Z +- 耗时(秒): 4 +- 退出码: 1 +- 说明: 环境/数据缺失: not found + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/service/systems/delivery_order.auditStatus.test.js + 1) "before each" hook for "should resolveOrderAuditStatus return "pending" when need_order_approval is 1" + 2) "before each" hook for "should resolveOrderAuditStatus return "approved" when need_order_approval is 0" + 3) "before each" hook for "should resolveOrderAuditStatus return "pending" when relation not found" + 4) "before each" hook for "should resolveOrderAuditStatus return "pending" when policy_config is missing" + 5) "before each" hook for "should prepareOrderData include audit_status" + + + 0 passing (3s) + 5 failing + + 1) test/app/service/systems/delivery_order.auditStatus.test.js + "before each" hook for "should prepareOrderData include audit_status": + TypeError: app.mockModel is not a function + at Context. (test\app\service\systems\delivery_order.auditStatus.test.js:16:9) + at process.processImmediate (node:internal/timers:504:21) + + 2) test/app/service/systems/delivery_order.auditStatus.test.js + "before each" hook for "should prepareOrderData include audit_status": + TypeError: app.mockModel is not a function + at Context. (test\app\service\systems\delivery_order.auditStatus.test.js:16:9) + at process.processImmediate (node:internal/timers:504:21) + + 3) test/app/service/systems/delivery_order.auditStatus.test.js + "before each" hook for "should prepareOrderData include audit_status": + TypeError: app.mockModel is not a function + at Context. (test\app\service\systems\delivery_order.auditStatus.test.js:16:9) + at process.processImmediate (node:internal/timers:504:21) + + 4) test/app/service/systems/delivery_order.auditStatus.test.js + "before each" hook for "should prepareOrderData include audit_status": + TypeError: app.mockModel is not a function + at Context. (test\app\service\systems\delivery_order.auditStatus.test.js:16:9) + at process.processImmediate (node:internal/timers:504:21) + + 5) test/app/service/systems/delivery_order.auditStatus.test.js + "before each" hook for "should prepareOrderData include audit_status": + TypeError: app.mockModel is not a function + at Context. (test\app\service\systems\delivery_order.auditStatus.test.js:16:9) + at process.processImmediate (node:internal/timers:504:21) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + + +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/service/systems/delivery_order.auditStatus.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260410-130419-main-skip-app_service_systems_notice.test.js.md b/test_reports/fail/20260410-130419-main-skip-app_service_systems_notice.test.js.md new file mode 100644 index 0000000..b1512ff --- /dev/null +++ b/test_reports/fail/20260410-130419-main-skip-app_service_systems_notice.test.js.md @@ -0,0 +1,86 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 主区 +- 文件: app/service/systems/notice.test.js +- 源: main +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:05:27.947Z +- 结束时间: 2026-04-10T13:05:29.542Z +- 耗时(秒): 2 +- 退出码: 1 +- 说明: 环境/数据缺失: timeout + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/service/systems/notice.test.js + 1) should normalize payload and send only matching webhooks + ✔ should enrich payload with store info from cache before querying database + ✔ should load store info from database and cache it when cache is empty + ✔ should send to both warehouse and owner webhooks when events match or are set to all + ✔ should only send up to the configured webhook limit + ✔ should require url for image or file message + ✔ should require warehouseId but allow empty ownerId + ✔ should retry failed webhooks three times and persist final failures + ✔ should reject sending unregistered event + ✔ should reject dotted or numeric-leading event names + ✔ should send wecom webhook as enterprise wechat direct message + ✔ should expose available webhook events and reject unsupported ones + + + 11 passing (16ms) + 1 failing + + 1) test/app/service/systems/notice.test.js + should normalize payload and send only matching webhooks: + + AssertionError [ERR_ASSERTION]: Expected values to be strictly equal: ++ actual - expected + ++ 100000 +- 1000000 + + + expected - actual + + -100000 + +1000000 + + at Object.findAll (test\app\service\systems\notice.test.js:34:20) + at D:\wms\app\service\systems\notice\index.js:796:43 + at Array.map () + at NoticeService.findMatchedWebhooks (app\service\systems\notice\index.js:786:62) + at NoticeService.send (app\service\systems\notice\index.js:826:33) + at async Context. (test\app\service\systems\notice.test.js:55:20) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + + +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/service/systems/notice.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260410-130419-main-skip-app_service_systems_storage.receiving.report.test.js.md b/test_reports/fail/20260410-130419-main-skip-app_service_systems_storage.receiving.report.test.js.md new file mode 100644 index 0000000..3f95c7b --- /dev/null +++ b/test_reports/fail/20260410-130419-main-skip-app_service_systems_storage.receiving.report.test.js.md @@ -0,0 +1,79 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 主区 +- 文件: app/service/systems/storage.receiving.report.test.js +- 源: main +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:05:34.424Z +- 结束时间: 2026-04-10T13:05:36.048Z +- 耗时(秒): 2 +- 退出码: 1 +- 说明: 环境/数据缺失: timeout + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (16ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/service/systems/storage.receiving.report.test.js + 1) should build and upload completion excel in a single sheet with one preview column + ✔ should send receiving completed notice with the unified event payload + ✔ should show only license plate for truck in notice content and report main rows + ✔ should show only tracking number for express in notice content and report main rows + ✔ should hide both contact fields for other delivery methods + ✔ should support nested notice.index service shape from Egg loader + ✔ should trigger text notice before excel and then send file notice after upload succeeds + ✔ should only send text notice when completion excel generation fails + ✔ should still complete and notify when detail has no matched product or completeness fields + + + 8 passing (25ms) + 1 failing + + 1) test/app/service/systems/storage.receiving.report.test.js + should build and upload completion excel in a single sheet with one preview column: + + AssertionError [ERR_ASSERTION]: Expected values to be strictly equal: ++ actual - expected + ++ '收货明细(已完成收货)_RCV202604040001.xlsx' +- '收货完成_RCV202604040001.xlsx' + ^ + + + expected - actual + + -收货明细(已完成收货)_RCV202604040001.xlsx + +收货完成_RCV202604040001.xlsx + + at Context. (test\app\service\systems\storage.receiving.report.test.js:260:12) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + + +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/service/systems/storage.receiving.report.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260410-130419-mirror-skip-app_controller_gateway.user.bindAccountByTempCode.test.js.md b/test_reports/fail/20260410-130419-mirror-skip-app_controller_gateway.user.bindAccountByTempCode.test.js.md new file mode 100644 index 0000000..11babbf --- /dev/null +++ b/test_reports/fail/20260410-130419-mirror-skip-app_controller_gateway.user.bindAccountByTempCode.test.js.md @@ -0,0 +1,64 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 镜像 +- 文件: app/controller/gateway.user.bindAccountByTempCode.test.js +- 源: mirror +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:05:43.561Z +- 结束时间: 2026-04-10T13:05:45.049Z +- 耗时(秒): 1 +- 退出码: 1 +- 说明: 环境/数据缺失: timeout + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + Exception during run: AssertionError [ERR_ASSERTION]: SYSTEM_TEST_YE4S_USER_ID 必须显式提供且为正整数 + at Object. (D:\wms\worktrees\deploy-20260409155126\test\app\controller\gateway.user.bindAccountByTempCode.test.js:12:8) + at Module._compile (node:internal/modules/cjs/loader:1812:14) + at Object..js (node:internal/modules/cjs/loader:1943:10) + at Module.load (node:internal/modules/cjs/loader:1533:32) + at Module._load (node:internal/modules/cjs/loader:1335:12) + at wrapModuleLoad (node:internal/modules/cjs/loader:255:19) + at loadCJSModuleWithModuleLoad (node:internal/modules/esm/translators:328:3) + at ModuleWrap. (node:internal/modules/esm/translators:233:7) + at ModuleJob.run (node:internal/modules/esm/module_job:430:25) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:661:26) + at async formattedImport (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:9:14) + at async exports.requireOrImport (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:42:28) + at async exports.loadFilesAsync (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:100:20) + at async singleRun (D:\wms\node_modules\mocha\lib\cli\run-helpers.js:162:3) + at async exports.handler (D:\wms\node_modules\mocha\lib\cli\run.js:375:5) { + generatedMessage: false, + code: 'ERR_ASSERTION', + actual: false, + expected: true, + operator: '==', + diff: 'simple' +} +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js worktrees/deploy-20260409155126/test/app/controller/gateway.user.bindAccountByTempCode.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260410-130419-mirror-skip-app_controller_home.test.js.md b/test_reports/fail/20260410-130419-mirror-skip-app_controller_home.test.js.md new file mode 100644 index 0000000..d3f1362 --- /dev/null +++ b/test_reports/fail/20260410-130419-mirror-skip-app_controller_home.test.js.md @@ -0,0 +1,71 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 镜像 +- 文件: app/controller/home.test.js +- 源: mirror +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:05:45.050Z +- 结束时间: 2026-04-10T13:05:49.386Z +- 耗时(秒): 4 +- 退出码: 1 +- 说明: 环境/数据缺失: timeout + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (1ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/home.test.js + 1) should assert + ✔ should typings exists + ✔ should GET / + + + 2 passing (3s) + 1 failing + + 1) test/app/controller/home.test.js + should assert: + + AssertionError [ERR_ASSERTION]: The expression evaluated to a falsy value: + + assert(app.config.keys.startsWith(pkg.name)) + + + expected - actual + + -false + +true + + at Context. (worktrees\deploy-20260409155126\test\app\controller\home.test.js:9:5) + at process.processImmediate (node:internal/timers:504:21) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + + +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js worktrees/deploy-20260409155126/test/app/controller/home.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.order.getreviewOrderlist.test.js.md b/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.order.getreviewOrderlist.test.js.md new file mode 100644 index 0000000..469c090 --- /dev/null +++ b/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.order.getreviewOrderlist.test.js.md @@ -0,0 +1,61 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 镜像 +- 文件: app/controller/system.order.getreviewOrderlist.test.js +- 源: mirror +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:05:49.387Z +- 结束时间: 2026-04-10T13:05:50.844Z +- 耗时(秒): 1 +- 退出码: 1 +- 说明: 环境/数据缺失: ECONNREFUSED + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.order.getreviewOrderlist.test.js + 1) should call order.getreviewOrderlist with platform=web project=all + + + 0 passing (20ms) + 1 failing + + 1) test/app/controller/system.order.getreviewOrderlist.test.js + should call order.getreviewOrderlist with platform=web project=all: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + + +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js worktrees/deploy-20260409155126/test/app/controller/system.order.getreviewOrderlist.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.order.namespaced.test.js.md b/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.order.namespaced.test.js.md new file mode 100644 index 0000000..11c1d07 --- /dev/null +++ b/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.order.namespaced.test.js.md @@ -0,0 +1,69 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 镜像 +- 文件: app/controller/system.order.namespaced.test.js +- 源: mirror +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:05:50.845Z +- 结束时间: 2026-04-10T13:05:52.450Z +- 耗时(秒): 2 +- 退出码: 1 +- 说明: 环境/数据缺失: ECONNREFUSED + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (1ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (14ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.order.namespaced.test.js + 1) should query all namespaced order lists + 2) should review order through namespaced method and restore status + + + 0 passing (20ms) + 2 failing + + 1) test/app/controller/system.order.namespaced.test.js + should query all namespaced order lists: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + 2) test/app/controller/system.order.namespaced.test.js + should review order through namespaced method and restore status: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + + +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js worktrees/deploy-20260409155126/test/app/controller/system.order.namespaced.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.order.reviewOrder.test.js.md b/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.order.reviewOrder.test.js.md new file mode 100644 index 0000000..af9a030 --- /dev/null +++ b/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.order.reviewOrder.test.js.md @@ -0,0 +1,61 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 镜像 +- 文件: app/controller/system.order.reviewOrder.test.js +- 源: mirror +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:05:52.451Z +- 结束时间: 2026-04-10T13:05:53.909Z +- 耗时(秒): 1 +- 退出码: 1 +- 说明: 环境/数据缺失: ECONNREFUSED + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (1ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.order.reviewOrder.test.js + 1) should review order and restore inspection status + + + 0 passing (19ms) + 1 failing + + 1) test/app/controller/system.order.reviewOrder.test.js + should review order and restore inspection status: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + + +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js worktrees/deploy-20260409155126/test/app/controller/system.order.reviewOrder.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.setting.account.getBindWechatCode.test.js.md b/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.setting.account.getBindWechatCode.test.js.md new file mode 100644 index 0000000..e0c8439 --- /dev/null +++ b/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.setting.account.getBindWechatCode.test.js.md @@ -0,0 +1,64 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 镜像 +- 文件: app/controller/system.setting.account.getBindWechatCode.test.js +- 源: mirror +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:05:53.909Z +- 结束时间: 2026-04-10T13:05:55.341Z +- 耗时(秒): 1 +- 退出码: 1 +- 说明: 环境/数据缺失: timeout + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + Exception during run: AssertionError [ERR_ASSERTION]: SYSTEM_TEST_YE4S_USER_ID 必须显式提供且为正整数 + at Object. (D:\wms\worktrees\deploy-20260409155126\test\app\controller\system.setting.account.getBindWechatCode.test.js:12:8) + at Module._compile (node:internal/modules/cjs/loader:1812:14) + at Object..js (node:internal/modules/cjs/loader:1943:10) + at Module.load (node:internal/modules/cjs/loader:1533:32) + at Module._load (node:internal/modules/cjs/loader:1335:12) + at wrapModuleLoad (node:internal/modules/cjs/loader:255:19) + at loadCJSModuleWithModuleLoad (node:internal/modules/esm/translators:328:3) + at ModuleWrap. (node:internal/modules/esm/translators:233:7) + at ModuleJob.run (node:internal/modules/esm/module_job:430:25) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:661:26) + at async formattedImport (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:9:14) + at async exports.requireOrImport (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:42:28) + at async exports.loadFilesAsync (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:100:20) + at async singleRun (D:\wms\node_modules\mocha\lib\cli\run-helpers.js:162:3) + at async exports.handler (D:\wms\node_modules\mocha\lib\cli\run.js:375:5) { + generatedMessage: false, + code: 'ERR_ASSERTION', + actual: false, + expected: true, + operator: '==', + diff: 'simple' +} +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js worktrees/deploy-20260409155126/test/app/controller/system.setting.account.getBindWechatCode.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.setting.account.test.js.md b/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.setting.account.test.js.md new file mode 100644 index 0000000..0bd569e --- /dev/null +++ b/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.setting.account.test.js.md @@ -0,0 +1,61 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 镜像 +- 文件: app/controller/system.setting.account.test.js +- 源: mirror +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:05:55.341Z +- 结束时间: 2026-04-10T13:05:56.816Z +- 耗时(秒): 1 +- 退出码: 1 +- 说明: 环境/数据缺失: ECONNREFUSED + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (1ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.setting.account.test.js + 1) "before all" hook for "error-1 should reject add when real_name is reserved name" + + + 0 passing (19ms) + 1 failing + + 1) test/app/controller/system.setting.account.test.js + "before all" hook for "error-1 should reject add when real_name is reserved name": + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + + +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js worktrees/deploy-20260409155126/test/app/controller/system.setting.account.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.setting.permission.test.js.md b/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.setting.permission.test.js.md new file mode 100644 index 0000000..0ef9253 --- /dev/null +++ b/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.setting.permission.test.js.md @@ -0,0 +1,61 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 镜像 +- 文件: app/controller/system.setting.permission.test.js +- 源: mirror +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:05:56.817Z +- 结束时间: 2026-04-10T13:05:58.288Z +- 耗时(秒): 1 +- 退出码: 1 +- 说明: 环境/数据缺失: ECONNREFUSED + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.setting.permission.test.js + 1) "before all" hook for "should expose setting.role.permission as alias of setting.permission.list" + + + 0 passing (18ms) + 1 failing + + 1) test/app/controller/system.setting.permission.test.js + "before all" hook for "should expose setting.role.permission as alias of setting.permission.list": + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + + +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js worktrees/deploy-20260409155126/test/app/controller/system.setting.permission.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.setting.printTemplate.test.js.md b/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.setting.printTemplate.test.js.md new file mode 100644 index 0000000..8b61858 --- /dev/null +++ b/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.setting.printTemplate.test.js.md @@ -0,0 +1,61 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 镜像 +- 文件: app/controller/system.setting.printTemplate.test.js +- 源: mirror +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:05:58.289Z +- 结束时间: 2026-04-10T13:05:59.745Z +- 耗时(秒): 1 +- 退出码: 1 +- 说明: 环境/数据缺失: ECONNREFUSED + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (1ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (11ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/system.setting.printTemplate.test.js + 1) "before all" hook for "normal-1 should create print template successfully" + + + 0 passing (17ms) + 1 failing + + 1) test/app/controller/system.setting.printTemplate.test.js + "before all" hook for "normal-1 should create print template successfully": + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + + +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js worktrees/deploy-20260409155126/test/app/controller/system.setting.printTemplate.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.setting.role.test.js.md b/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.setting.role.test.js.md new file mode 100644 index 0000000..14ec0d1 --- /dev/null +++ b/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.setting.role.test.js.md @@ -0,0 +1,61 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 镜像 +- 文件: app/controller/system.setting.role.test.js +- 源: mirror +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:05:59.746Z +- 结束时间: 2026-04-10T13:06:01.229Z +- 耗时(秒): 1 +- 退出码: 1 +- 说明: 环境/数据缺失: ECONNREFUSED + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (1ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/system.setting.role.test.js + 1) "before all" hook for "should support wildcard role permissions via ["*"]" + + + 0 passing (19ms) + 1 failing + + 1) test/app/controller/system.setting.role.test.js + "before all" hook for "should support wildcard role permissions via ["*"]": + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + + +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js worktrees/deploy-20260409155126/test/app/controller/system.setting.role.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.setting.storeWarehouse.test.js.md b/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.setting.storeWarehouse.test.js.md new file mode 100644 index 0000000..3c1b7ec --- /dev/null +++ b/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.setting.storeWarehouse.test.js.md @@ -0,0 +1,61 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 镜像 +- 文件: app/controller/system.setting.storeWarehouse.test.js +- 源: mirror +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:06:01.230Z +- 结束时间: 2026-04-10T13:06:02.723Z +- 耗时(秒): 1 +- 退出码: 1 +- 说明: 环境/数据缺失: ECONNREFUSED + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/system.setting.storeWarehouse.test.js + 1) "before all" hook for "should list store-warehouse contracts in current subject scope" + + + 0 passing (17ms) + 1 failing + + 1) test/app/controller/system.setting.storeWarehouse.test.js + "before all" hook for "should list store-warehouse contracts in current subject scope": + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + + +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js worktrees/deploy-20260409155126/test/app/controller/system.setting.storeWarehouse.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.stock.warehouse.getStockDetail.test.js.md b/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.stock.warehouse.getStockDetail.test.js.md new file mode 100644 index 0000000..5e302db --- /dev/null +++ b/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.stock.warehouse.getStockDetail.test.js.md @@ -0,0 +1,61 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 镜像 +- 文件: app/controller/system.stock.warehouse.getStockDetail.test.js +- 源: mirror +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:06:02.724Z +- 结束时间: 2026-04-10T13:06:04.237Z +- 耗时(秒): 2 +- 退出码: 1 +- 说明: 环境/数据缺失: ECONNREFUSED + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.stock.warehouse.getStockDetail.test.js + 1) "before all" hook for "should return stockItem, storageList and pagination for a valid stock_id" + + + 0 passing (21ms) + 1 failing + + 1) test/app/controller/system.stock.warehouse.getStockDetail.test.js + "before all" hook for "should return stockItem, storageList and pagination for a valid stock_id": + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + + +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js worktrees/deploy-20260409155126/test/app/controller/system.stock.warehouse.getStockDetail.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.stock.warehouse.namespaced.test.js.md b/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.stock.warehouse.namespaced.test.js.md new file mode 100644 index 0000000..5ecc840 --- /dev/null +++ b/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.stock.warehouse.namespaced.test.js.md @@ -0,0 +1,61 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 镜像 +- 文件: app/controller/system.stock.warehouse.namespaced.test.js +- 源: mirror +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:06:04.237Z +- 结束时间: 2026-04-10T13:06:05.786Z +- 耗时(秒): 2 +- 退出码: 1 +- 说明: 环境/数据缺失: ECONNREFUSED + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (15ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/system.stock.warehouse.namespaced.test.js + 1) should query stock warehouse list via namespaced method + + + 0 passing (18ms) + 1 failing + + 1) test/app/controller/system.stock.warehouse.namespaced.test.js + should query stock warehouse list via namespaced method: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + + +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js worktrees/deploy-20260409155126/test/app/controller/system.stock.warehouse.namespaced.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.storage.delivery.module.test.js.md b/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.storage.delivery.module.test.js.md new file mode 100644 index 0000000..be61232 --- /dev/null +++ b/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.storage.delivery.module.test.js.md @@ -0,0 +1,85 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 镜像 +- 文件: app/controller/system.storage.delivery.module.test.js +- 源: mirror +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:06:05.786Z +- 结束时间: 2026-04-10T13:06:07.269Z +- 耗时(秒): 1 +- 退出码: 1 +- 说明: 环境/数据缺失: ECONNREFUSED + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.storage.delivery.module.test.js + 1) should return delivery list via storage.stockout.list + 2) should return placeholder failure via storage.stockout.toOrder + 3) should return item list via storage.stockout.listItems + 4) should not expose removed storage.entry detail methods + + + 0 passing (23ms) + 4 failing + + 1) test/app/controller/system.storage.delivery.module.test.js + should return delivery list via storage.stockout.list: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + 2) test/app/controller/system.storage.delivery.module.test.js + should return placeholder failure via storage.stockout.toOrder: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + 3) test/app/controller/system.storage.delivery.module.test.js + should return item list via storage.stockout.listItems: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + 4) test/app/controller/system.storage.delivery.module.test.js + should not expose removed storage.entry detail methods: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + + +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js worktrees/deploy-20260409155126/test/app/controller/system.storage.delivery.module.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.storage.entry.test.js.md b/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.storage.entry.test.js.md new file mode 100644 index 0000000..ae73719 --- /dev/null +++ b/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.storage.entry.test.js.md @@ -0,0 +1,85 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 镜像 +- 文件: app/controller/system.storage.entry.test.js +- 源: mirror +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:06:07.269Z +- 结束时间: 2026-04-10T13:06:08.734Z +- 耗时(秒): 1 +- 退出码: 1 +- 说明: 环境/数据缺失: ECONNREFUSED + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (14ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.storage.entry.test.js + 1) should query entry list + 2) should create entry and run detail lifecycle then cancel + 3) should complete entry after adding detail + 4) should reject invalid params for create/get/addDetail + + + 0 passing (24ms) + 4 failing + + 1) test/app/controller/system.storage.entry.test.js + should query entry list: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + 2) test/app/controller/system.storage.entry.test.js + should create entry and run detail lifecycle then cancel: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + 3) test/app/controller/system.storage.entry.test.js + should complete entry after adding detail: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + 4) test/app/controller/system.storage.entry.test.js + should reject invalid params for create/get/addDetail: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + + +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js worktrees/deploy-20260409155126/test/app/controller/system.storage.entry.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.storage.inventory.matchPutaway.test.js.md b/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.storage.inventory.matchPutaway.test.js.md new file mode 100644 index 0000000..b524082 --- /dev/null +++ b/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.storage.inventory.matchPutaway.test.js.md @@ -0,0 +1,85 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 镜像 +- 文件: app/controller/system.storage.inventory.matchPutaway.test.js +- 源: mirror +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:06:08.735Z +- 结束时间: 2026-04-10T13:06:10.300Z +- 耗时(秒): 2 +- 退出码: 1 +- 说明: 环境/数据缺失: timeout + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + Exception during run: Error: Cannot find module './tencent-cloud' +Require stack: +- D:\wms\worktrees\deploy-20260409155126\config\config.default.js +- D:\wms\worktrees\deploy-20260409155126\database\config.js +- D:\wms\worktrees\deploy-20260409155126\test\app\controller\system.storage.inventory.matchPutaway.test.js + at Module._resolveFilename (node:internal/modules/cjs/loader:1456:15) + at defaultResolveImpl (node:internal/modules/cjs/loader:1066:19) + at resolveForCJSWithHooks (node:internal/modules/cjs/loader:1071:22) + at Module._load (node:internal/modules/cjs/loader:1242:25) + at wrapModuleLoad (node:internal/modules/cjs/loader:255:19) + at Module.require (node:internal/modules/cjs/loader:1556:12) + at require (node:internal/modules/helpers:152:16) + at module.exports (D:\wms\worktrees\deploy-20260409155126\config\config.default.js:21:30) + at loadEggConfig (D:\wms\worktrees\deploy-20260409155126\database\config.js:36:7) + at Object. (D:\wms\worktrees\deploy-20260409155126\database\config.js:56:23) + at Module._compile (node:internal/modules/cjs/loader:1812:14) + at Object..js (node:internal/modules/cjs/loader:1943:10) + at Module.load (node:internal/modules/cjs/loader:1533:32) + at Module._load (node:internal/modules/cjs/loader:1335:12) + at wrapModuleLoad (node:internal/modules/cjs/loader:255:19) + at Module.require (node:internal/modules/cjs/loader:1556:12) + at require (node:internal/modules/helpers:152:16) + at Object. (D:\wms\worktrees\deploy-20260409155126\test\app\controller\system.storage.inventory.matchPutaway.test.js:16:18) + at Module._compile (node:internal/modules/cjs/loader:1812:14) + at Object..js (node:internal/modules/cjs/loader:1943:10) + at Module.load (node:internal/modules/cjs/loader:1533:32) + at Module._load (node:internal/modules/cjs/loader:1335:12) + at wrapModuleLoad (node:internal/modules/cjs/loader:255:19) + at loadCJSModuleWithModuleLoad (node:internal/modules/esm/translators:328:3) + at ModuleWrap. (node:internal/modules/esm/translators:233:7) + at ModuleJob.run (node:internal/modules/esm/module_job:430:25) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:661:26) + at async formattedImport (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:9:14) + at async exports.requireOrImport (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:42:28) + at async exports.loadFilesAsync (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:100:20) + at async singleRun (D:\wms\node_modules\mocha\lib\cli\run-helpers.js:162:3) + at async exports.handler (D:\wms\node_modules\mocha\lib\cli\run.js:375:5) { + code: 'MODULE_NOT_FOUND', + requireStack: [ + 'D:\\wms\\worktrees\\deploy-20260409155126\\config\\config.default.js', + 'D:\\wms\\worktrees\\deploy-20260409155126\\database\\config.js', + 'D:\\wms\\worktrees\\deploy-20260409155126\\test\\app\\controller\\system.storage.inventory.matchPutaway.test.js' + ] +} +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js worktrees/deploy-20260409155126/test/app/controller/system.storage.inventory.matchPutaway.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.storage.inventory.quickPutaway.test.js.md b/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.storage.inventory.quickPutaway.test.js.md new file mode 100644 index 0000000..8e65598 --- /dev/null +++ b/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.storage.inventory.quickPutaway.test.js.md @@ -0,0 +1,85 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 镜像 +- 文件: app/controller/system.storage.inventory.quickPutaway.test.js +- 源: mirror +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:06:10.300Z +- 结束时间: 2026-04-10T13:06:11.878Z +- 耗时(秒): 2 +- 退出码: 1 +- 说明: 环境/数据缺失: timeout + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (3ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + Exception during run: Error: Cannot find module './tencent-cloud' +Require stack: +- D:\wms\worktrees\deploy-20260409155126\config\config.default.js +- D:\wms\worktrees\deploy-20260409155126\database\config.js +- D:\wms\worktrees\deploy-20260409155126\test\app\controller\system.storage.inventory.quickPutaway.test.js + at Module._resolveFilename (node:internal/modules/cjs/loader:1456:15) + at defaultResolveImpl (node:internal/modules/cjs/loader:1066:19) + at resolveForCJSWithHooks (node:internal/modules/cjs/loader:1071:22) + at Module._load (node:internal/modules/cjs/loader:1242:25) + at wrapModuleLoad (node:internal/modules/cjs/loader:255:19) + at Module.require (node:internal/modules/cjs/loader:1556:12) + at require (node:internal/modules/helpers:152:16) + at module.exports (D:\wms\worktrees\deploy-20260409155126\config\config.default.js:21:30) + at loadEggConfig (D:\wms\worktrees\deploy-20260409155126\database\config.js:36:7) + at Object. (D:\wms\worktrees\deploy-20260409155126\database\config.js:56:23) + at Module._compile (node:internal/modules/cjs/loader:1812:14) + at Object..js (node:internal/modules/cjs/loader:1943:10) + at Module.load (node:internal/modules/cjs/loader:1533:32) + at Module._load (node:internal/modules/cjs/loader:1335:12) + at wrapModuleLoad (node:internal/modules/cjs/loader:255:19) + at Module.require (node:internal/modules/cjs/loader:1556:12) + at require (node:internal/modules/helpers:152:16) + at Object. (D:\wms\worktrees\deploy-20260409155126\test\app\controller\system.storage.inventory.quickPutaway.test.js:16:18) + at Module._compile (node:internal/modules/cjs/loader:1812:14) + at Object..js (node:internal/modules/cjs/loader:1943:10) + at Module.load (node:internal/modules/cjs/loader:1533:32) + at Module._load (node:internal/modules/cjs/loader:1335:12) + at wrapModuleLoad (node:internal/modules/cjs/loader:255:19) + at loadCJSModuleWithModuleLoad (node:internal/modules/esm/translators:328:3) + at ModuleWrap. (node:internal/modules/esm/translators:233:7) + at ModuleJob.run (node:internal/modules/esm/module_job:430:25) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:661:26) + at async formattedImport (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:9:14) + at async exports.requireOrImport (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:42:28) + at async exports.loadFilesAsync (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:100:20) + at async singleRun (D:\wms\node_modules\mocha\lib\cli\run-helpers.js:162:3) + at async exports.handler (D:\wms\node_modules\mocha\lib\cli\run.js:375:5) { + code: 'MODULE_NOT_FOUND', + requireStack: [ + 'D:\\wms\\worktrees\\deploy-20260409155126\\config\\config.default.js', + 'D:\\wms\\worktrees\\deploy-20260409155126\\database\\config.js', + 'D:\\wms\\worktrees\\deploy-20260409155126\\test\\app\\controller\\system.storage.inventory.quickPutaway.test.js' + ] +} +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js worktrees/deploy-20260409155126/test/app/controller/system.storage.inventory.quickPutaway.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.storage.receiving.test.js.md b/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.storage.receiving.test.js.md new file mode 100644 index 0000000..487f6f4 --- /dev/null +++ b/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.storage.receiving.test.js.md @@ -0,0 +1,141 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 镜像 +- 文件: app/controller/system.storage.receiving.test.js +- 源: mirror +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:06:11.878Z +- 结束时间: 2026-04-10T13:06:13.375Z +- 耗时(秒): 1 +- 退出码: 1 +- 说明: 环境/数据缺失: ECONNREFUSED + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (15ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/system.storage.receiving.test.js + 1) should query receiving list + 2) should query receiving detail when list has records + 3) should bind store to receiving and reject rebinding when owner already exists + 4) should reject bindStore when receiving is cancelled + 5) should bind and rebind system product for a receiving detail + 6) should create and then batch cancel receiving order + 7) should generate unique receiving numbers under concurrent create requests + 8) should include same-day records when created_at uses daterange filter + 9) should reject getReceivingDetail with invalid id + 10) should reject create with invalid loading_method enum + 11) should reject batchCancelReceiving with nonexistent ids + + + 0 passing (32ms) + 11 failing + + 1) test/app/controller/system.storage.receiving.test.js + should query receiving list: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + 2) test/app/controller/system.storage.receiving.test.js + should query receiving detail when list has records: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + 3) test/app/controller/system.storage.receiving.test.js + should bind store to receiving and reject rebinding when owner already exists: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + 4) test/app/controller/system.storage.receiving.test.js + should reject bindStore when receiving is cancelled: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + 5) test/app/controller/system.storage.receiving.test.js + should bind and rebind system product for a receiving detail: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + 6) test/app/controller/system.storage.receiving.test.js + should create and then batch cancel receiving order: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + 7) test/app/controller/system.storage.receiving.test.js + should generate unique receiving numbers under concurrent create requests: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + 8) test/app/controller/system.storage.receiving.test.js + should include same-day records when created_at uses daterange filter: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + 9) test/app/controller/system.storage.receiving.test.js + should reject getReceivingDetail with invalid id: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + 10) test/app/controller/system.storage.receiving.test.js + should reject create with invalid loading_method enum: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + 11) test/app/controller/system.storage.receiving.test.js + should reject batchCancelReceiving with nonexistent ids: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + + +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js worktrees/deploy-20260409155126/test/app/controller/system.storage.receiving.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.storage.transaction.test.js.md b/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.storage.transaction.test.js.md new file mode 100644 index 0000000..6941420 --- /dev/null +++ b/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.storage.transaction.test.js.md @@ -0,0 +1,85 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 镜像 +- 文件: app/controller/system.storage.transaction.test.js +- 源: mirror +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:06:13.376Z +- 结束时间: 2026-04-10T13:06:14.976Z +- 耗时(秒): 2 +- 退出码: 1 +- 说明: 环境/数据缺失: timeout + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + Exception during run: Error: Cannot find module './tencent-cloud' +Require stack: +- D:\wms\worktrees\deploy-20260409155126\config\config.default.js +- D:\wms\worktrees\deploy-20260409155126\database\config.js +- D:\wms\worktrees\deploy-20260409155126\test\app\controller\system.storage.transaction.test.js + at Module._resolveFilename (node:internal/modules/cjs/loader:1456:15) + at defaultResolveImpl (node:internal/modules/cjs/loader:1066:19) + at resolveForCJSWithHooks (node:internal/modules/cjs/loader:1071:22) + at Module._load (node:internal/modules/cjs/loader:1242:25) + at wrapModuleLoad (node:internal/modules/cjs/loader:255:19) + at Module.require (node:internal/modules/cjs/loader:1556:12) + at require (node:internal/modules/helpers:152:16) + at module.exports (D:\wms\worktrees\deploy-20260409155126\config\config.default.js:21:30) + at loadEggConfig (D:\wms\worktrees\deploy-20260409155126\database\config.js:36:7) + at Object. (D:\wms\worktrees\deploy-20260409155126\database\config.js:56:23) + at Module._compile (node:internal/modules/cjs/loader:1812:14) + at Object..js (node:internal/modules/cjs/loader:1943:10) + at Module.load (node:internal/modules/cjs/loader:1533:32) + at Module._load (node:internal/modules/cjs/loader:1335:12) + at wrapModuleLoad (node:internal/modules/cjs/loader:255:19) + at Module.require (node:internal/modules/cjs/loader:1556:12) + at require (node:internal/modules/helpers:152:16) + at Object. (D:\wms\worktrees\deploy-20260409155126\test\app\controller\system.storage.transaction.test.js:16:18) + at Module._compile (node:internal/modules/cjs/loader:1812:14) + at Object..js (node:internal/modules/cjs/loader:1943:10) + at Module.load (node:internal/modules/cjs/loader:1533:32) + at Module._load (node:internal/modules/cjs/loader:1335:12) + at wrapModuleLoad (node:internal/modules/cjs/loader:255:19) + at loadCJSModuleWithModuleLoad (node:internal/modules/esm/translators:328:3) + at ModuleWrap. (node:internal/modules/esm/translators:233:7) + at ModuleJob.run (node:internal/modules/esm/module_job:430:25) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:661:26) + at async formattedImport (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:9:14) + at async exports.requireOrImport (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:42:28) + at async exports.loadFilesAsync (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:100:20) + at async singleRun (D:\wms\node_modules\mocha\lib\cli\run-helpers.js:162:3) + at async exports.handler (D:\wms\node_modules\mocha\lib\cli\run.js:375:5) { + code: 'MODULE_NOT_FOUND', + requireStack: [ + 'D:\\wms\\worktrees\\deploy-20260409155126\\config\\config.default.js', + 'D:\\wms\\worktrees\\deploy-20260409155126\\database\\config.js', + 'D:\\wms\\worktrees\\deploy-20260409155126\\test\\app\\controller\\system.storage.transaction.test.js' + ] +} +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js worktrees/deploy-20260409155126/test/app/controller/system.storage.transaction.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.storeWarehouse.test.js.md b/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.storeWarehouse.test.js.md new file mode 100644 index 0000000..806d448 --- /dev/null +++ b/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.storeWarehouse.test.js.md @@ -0,0 +1,61 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 镜像 +- 文件: app/controller/system.storeWarehouse.test.js +- 源: mirror +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:06:14.977Z +- 结束时间: 2026-04-10T13:06:16.478Z +- 耗时(秒): 2 +- 退出码: 1 +- 说明: 环境/数据缺失: ECONNREFUSED + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/system.storeWarehouse.test.js + 1) "before all" hook for "should expose standalone storeWarehouse.store.list" + + + 0 passing (18ms) + 1 failing + + 1) test/app/controller/system.storeWarehouse.test.js + "before all" hook for "should expose standalone storeWarehouse.store.list": + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + + +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js worktrees/deploy-20260409155126/test/app/controller/system.storeWarehouse.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.user.changeRole.test.js.md b/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.user.changeRole.test.js.md new file mode 100644 index 0000000..30a16ec --- /dev/null +++ b/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.user.changeRole.test.js.md @@ -0,0 +1,61 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 镜像 +- 文件: app/controller/system.user.changeRole.test.js +- 源: mirror +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:06:16.479Z +- 结束时间: 2026-04-10T13:06:17.977Z +- 耗时(秒): 1 +- 退出码: 1 +- 说明: 环境/数据缺失: ECONNREFUSED + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/system.user.changeRole.test.js + 1) should switch role via user.changeRole and persist response + + + 0 passing (20ms) + 1 failing + + 1) test/app/controller/system.user.changeRole.test.js + should switch role via user.changeRole and persist response: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + + +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js worktrees/deploy-20260409155126/test/app/controller/system.user.changeRole.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.user.getLoginWechatCode.test.js.md b/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.user.getLoginWechatCode.test.js.md new file mode 100644 index 0000000..e700cea --- /dev/null +++ b/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.user.getLoginWechatCode.test.js.md @@ -0,0 +1,61 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 镜像 +- 文件: app/controller/system.user.getLoginWechatCode.test.js +- 源: mirror +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:06:17.978Z +- 结束时间: 2026-04-10T13:06:19.449Z +- 耗时(秒): 1 +- 退出码: 1 +- 说明: 环境/数据缺失: ECONNREFUSED + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (1ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.user.getLoginWechatCode.test.js + 1) should return login code without Authorization token + + + 0 passing (18ms) + 1 failing + + 1) test/app/controller/system.user.getLoginWechatCode.test.js + should return login code without Authorization token: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + + +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js worktrees/deploy-20260409155126/test/app/controller/system.user.getLoginWechatCode.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.user.info.test.js.md b/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.user.info.test.js.md new file mode 100644 index 0000000..f4e96d0 --- /dev/null +++ b/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.user.info.test.js.md @@ -0,0 +1,61 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 镜像 +- 文件: app/controller/system.user.info.test.js +- 源: mirror +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:06:19.450Z +- 结束时间: 2026-04-10T13:06:20.905Z +- 耗时(秒): 1 +- 退出码: 1 +- 说明: 环境/数据缺失: ECONNREFUSED + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.user.info.test.js + 1) should call user.info with bearer token + + + 0 passing (19ms) + 1 failing + + 1) test/app/controller/system.user.info.test.js + should call user.info with bearer token: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + + +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js worktrees/deploy-20260409155126/test/app/controller/system.user.info.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.user.info.web.test.js.md b/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.user.info.web.test.js.md new file mode 100644 index 0000000..8e9d1e3 --- /dev/null +++ b/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.user.info.web.test.js.md @@ -0,0 +1,61 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 镜像 +- 文件: app/controller/system.user.info.web.test.js +- 源: mirror +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:06:20.906Z +- 结束时间: 2026-04-10T13:06:22.388Z +- 耗时(秒): 1 +- 退出码: 1 +- 说明: 环境/数据缺失: ECONNREFUSED + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (3ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.user.info.web.test.js + 1) should call user.info with platform=web project=all and persist response + + + 0 passing (20ms) + 1 failing + + 1) test/app/controller/system.user.info.web.test.js + should call user.info with platform=web project=all and persist response: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + + +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js worktrees/deploy-20260409155126/test/app/controller/system.user.info.web.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.user.login.test.js.md b/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.user.login.test.js.md new file mode 100644 index 0000000..db20ab4 --- /dev/null +++ b/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.user.login.test.js.md @@ -0,0 +1,63 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 镜像 +- 文件: app/controller/system.user.login.test.js +- 源: mirror +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:06:22.390Z +- 结束时间: 2026-04-10T13:06:23.861Z +- 耗时(秒): 1 +- 退出码: 1 +- 说明: 环境/数据缺失: ECONNREFUSED + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (5ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.user.login.test.js + ✔ should get token from cache or login method + ✔ should persist token cache file + 1) user.login should return token only + + + 2 passing (19ms) + 1 failing + + 1) test/app/controller/system.user.login.test.js + user.login should return token only: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + + +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js worktrees/deploy-20260409155126/test/app/controller/system.user.login.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.user.loginByCode.test.js.md b/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.user.loginByCode.test.js.md new file mode 100644 index 0000000..b274a8e --- /dev/null +++ b/test_reports/fail/20260410-130419-mirror-skip-app_controller_system.user.loginByCode.test.js.md @@ -0,0 +1,79 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 镜像 +- 文件: app/controller/system.user.loginByCode.test.js +- 源: mirror +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:06:23.861Z +- 结束时间: 2026-04-10T13:06:25.352Z +- 耗时(秒): 1 +- 退出码: 1 +- 说明: 环境/数据缺失: ECONNREFUSED + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.user.loginByCode.test.js + - should login successfully when code is valid + 1) should fail when code is missing + 2) should fail when code does not exist + 3) should fail when code format is valid but not matched + + + 0 passing (27ms) + 1 pending + 3 failing + + 1) test/app/controller/system.user.loginByCode.test.js + should fail when code is missing: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + 2) test/app/controller/system.user.loginByCode.test.js + should fail when code does not exist: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + 3) test/app/controller/system.user.loginByCode.test.js + should fail when code format is valid but not matched: + TypeError: fetch failed + + Caused by: Error: connect ECONNREFUSED 127.0.0.1:6060 + at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1645:16) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + + +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js worktrees/deploy-20260409155126/test/app/controller/system.user.loginByCode.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260410-130419-mirror-skip-app_service_systems_license_plate.test.js.md b/test_reports/fail/20260410-130419-mirror-skip-app_service_systems_license_plate.test.js.md new file mode 100644 index 0000000..093a48d --- /dev/null +++ b/test_reports/fail/20260410-130419-mirror-skip-app_service_systems_license_plate.test.js.md @@ -0,0 +1,64 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 镜像 +- 文件: app/service/systems/license_plate.test.js +- 源: mirror +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:06:33.576Z +- 结束时间: 2026-04-10T13:06:35.145Z +- 耗时(秒): 2 +- 退出码: 1 +- 说明: 环境/数据缺失: timeout + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + Exception during run: Error: ENOENT: no such file or directory, open 'D:\wms\worktrees\deploy-20260409155126\temp\cp.png' + at Object.openSync (node:fs:560:18) + at Object.readFileSync (node:fs:444:35) + at Object. (D:\wms\worktrees\deploy-20260409155126\test\app\service\systems\license_plate.test.js:9:31) + at Module._compile (node:internal/modules/cjs/loader:1812:14) + at Object..js (node:internal/modules/cjs/loader:1943:10) + at Module.load (node:internal/modules/cjs/loader:1533:32) + at Module._load (node:internal/modules/cjs/loader:1335:12) + at wrapModuleLoad (node:internal/modules/cjs/loader:255:19) + at loadCJSModuleWithModuleLoad (node:internal/modules/esm/translators:328:3) + at ModuleWrap. (node:internal/modules/esm/translators:233:7) + at ModuleJob.run (node:internal/modules/esm/module_job:430:25) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:661:26) + at async formattedImport (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:9:14) + at async exports.requireOrImport (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:42:28) + at async exports.loadFilesAsync (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:100:20) + at async singleRun (D:\wms\node_modules\mocha\lib\cli\run-helpers.js:162:3) + at async exports.handler (D:\wms\node_modules\mocha\lib\cli\run.js:375:5) { + errno: -4058, + code: 'ENOENT', + syscall: 'open', + path: 'D:\\wms\\worktrees\\deploy-20260409155126\\temp\\cp.png' +} +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js worktrees/deploy-20260409155126/test/app/service/systems/license_plate.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260410-130419-mirror-skip-app_service_systems_notice.test.js.md b/test_reports/fail/20260410-130419-mirror-skip-app_service_systems_notice.test.js.md new file mode 100644 index 0000000..51264a0 --- /dev/null +++ b/test_reports/fail/20260410-130419-mirror-skip-app_service_systems_notice.test.js.md @@ -0,0 +1,86 @@ +# 测试结果 + +- 状态: SKIP +- 分类: 镜像 +- 文件: app/service/systems/notice.test.js +- 源: mirror +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:06:35.145Z +- 结束时间: 2026-04-10T13:06:36.730Z +- 耗时(秒): 2 +- 退出码: 1 +- 说明: 环境/数据缺失: timeout + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (1ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/service/systems/notice.test.js + 1) should normalize payload and send only matching webhooks + ✔ should enrich payload with store info from cache before querying database + ✔ should load store info from database and cache it when cache is empty + ✔ should send to both warehouse and owner webhooks when events match or are set to all + ✔ should only send up to the configured webhook limit + ✔ should require url for image or file message + ✔ should require warehouseId but allow empty ownerId + ✔ should retry failed webhooks three times and persist final failures + ✔ should reject sending unregistered event + ✔ should reject dotted or numeric-leading event names + ✔ should send wecom webhook as enterprise wechat direct message + ✔ should expose available webhook events and reject unsupported ones + + + 11 passing (11ms) + 1 failing + + 1) test/app/service/systems/notice.test.js + should normalize payload and send only matching webhooks: + + AssertionError [ERR_ASSERTION]: Expected values to be strictly equal: ++ actual - expected + ++ 100000 +- 1000000 + + + expected - actual + + -100000 + +1000000 + + at Object.findAll (worktrees\deploy-20260409155126\test\app\service\systems\notice.test.js:34:20) + at D:\wms\worktrees\deploy-20260409155126\app\service\systems\notice\index.js:796:43 + at Array.map () + at NoticeService.findMatchedWebhooks (worktrees\deploy-20260409155126\app\service\systems\notice\index.js:786:62) + at NoticeService.send (worktrees\deploy-20260409155126\app\service\systems\notice\index.js:826:33) + at async Context. (worktrees\deploy-20260409155126\test\app\service\systems\notice.test.js:55:20) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + + +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js worktrees/deploy-20260409155126/test/app/service/systems/notice.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} +``` + +## 执行错误 + +- 错误对象: (无) \ No newline at end of file diff --git a/test_reports/fail/20260411-161359-收货入库相关测试失败简报.md b/test_reports/fail/20260411-161359-收货入库相关测试失败简报.md new file mode 100644 index 0000000..03b02ee --- /dev/null +++ b/test_reports/fail/20260411-161359-收货入库相关测试失败简报.md @@ -0,0 +1,33 @@ +# 收货入库相关测试失败简报 + +## 测试目标 +验证收货完成报表相关现有回归测试是否通过: +- [test/app/service/systems/storage.receiving.report.test.js](../../test/app/service/systems/storage.receiving.report.test.js) + +## 测试类型 +单元测试,兼顾回归验证。 + +## 测试范围 +- 完成收货 Excel 报表生成 +- 完成收货通知内容 +- 不同配送方式的通知字段展示 +- 嵌套 notice 服务形态兼容 +- 完成收货后的通知顺序与失败兜底 + +## 依赖与公共 setup +- 该文件主要是纯单元测试,使用手工构造的 `ctx`、`model`、`service` mock。 +- 没有依赖外部数据库或登录态。 + +## 测试结果摘要 +- [test/app/service/systems/storage.receiving.report.test.js](../../test/app/service/systems/storage.receiving.report.test.js): 8 通过,1 失败,0 跳过 + +## 失败详情 +- 失败用例:should build and upload completion excel in a single sheet with one preview column +- 失败原因:断言期望的文件名仍是 `收货完成_RCV202604040001.xlsx`,但实际返回为 `收货明细(已完成收货)_RCV202604040001.xlsx` +- 首个报错位置: [test/app/service/systems/storage.receiving.report.test.js](../../test/app/service/systems/storage.receiving.report.test.js#L260) + +## 结论 +该文件存在单点回归,当前失败集中在 Excel 报表文件名断言,不影响其余 8 个用例。 + +## 备注 +- 运行命令:`npm run test:local -- test/app/service/systems/storage.receiving.report.test.js --timeout 120000` diff --git a/test_reports/pass/001-main.md b/test_reports/pass/001-main.md new file mode 100644 index 0000000..d384ed2 --- /dev/null +++ b/test_reports/pass/001-main.md @@ -0,0 +1,36 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: main +- 文件: test/app/controller/docs.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/docs.test.js + 鉁?GET /api/docs/system/changes should return 200 and a change-history JSON array + 鉁?GET /api/docs/system should render HTML entries for change history and raw JSON + 鉁?GET /api/docs/invalid-name!/changes should return 400 + + + 3 passing (3s) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/003-main.md b/test_reports/pass/003-main.md new file mode 100644 index 0000000..9b962e7 --- /dev/null +++ b/test_reports/pass/003-main.md @@ -0,0 +1,36 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: main +- 文件: test/app/controller/home.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (1ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/home.test.js + 鉁?should assert + 鉁?should typings exists + 鉁?should GET / + + + 3 passing (3s) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/004-main.md b/test_reports/pass/004-main.md new file mode 100644 index 0000000..a97344c --- /dev/null +++ b/test_reports/pass/004-main.md @@ -0,0 +1,34 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: main +- 文件: test/app/controller/system.order.getreviewOrderlist.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (14ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (5ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.order.getreviewOrderlist.test.js + 鉁?should call order.getreviewOrderlist with platform=web project=all (2548ms) + + + 1 passing (3s) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/005-main.md b/test_reports/pass/005-main.md new file mode 100644 index 0000000..6943ead --- /dev/null +++ b/test_reports/pass/005-main.md @@ -0,0 +1,35 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: main +- 文件: test/app/controller/system.order.namespaced.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (15ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/system.order.namespaced.test.js + 鉁?should query all namespaced order lists (2381ms) + 鉁?should review order through namespaced method and restore status (2315ms) + + + 2 passing (5s) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/006-main.md b/test_reports/pass/006-main.md new file mode 100644 index 0000000..c63069d --- /dev/null +++ b/test_reports/pass/006-main.md @@ -0,0 +1,34 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: main +- 文件: test/app/controller/system.order.reviewOrder.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (1ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.order.reviewOrder.test.js + 鉁?should review order and restore inspection status (2298ms) + + + 1 passing (2s) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/009-main.md b/test_reports/pass/009-main.md new file mode 100644 index 0000000..5affbbd --- /dev/null +++ b/test_reports/pass/009-main.md @@ -0,0 +1,40 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: main +- 文件: test/app/controller/system.setting.permission.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (16ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/system.setting.permission.test.js + 鉁?should expose setting.role.permission as alias of setting.permission.list (246ms) + 鉁?should include route presentation fields in permission list response (509ms) + 鉁?should show newly created permission in list for admin management (467ms) + 鉁?should reject permission update when target permission does not exist (61ms) + 鉁?should create then update then delete permission successfully (644ms) + 鉁?should split deleted_ids and already_deleted_ids in mixed batch delete (686ms) + 鉁?should reject mixed delete when ids contain non-existent permission (405ms) + + + 7 passing (4s) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/010-main.md b/test_reports/pass/010-main.md new file mode 100644 index 0000000..245d73e --- /dev/null +++ b/test_reports/pass/010-main.md @@ -0,0 +1,39 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: main +- 文件: test/app/controller/system.setting.printTemplate.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (1ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.setting.printTemplate.test.js + 鉁?normal-1 should create print template successfully (129ms) + 鉁?normal-2 should list created template by business type (62ms) + 鉁?normal-3 should delete created template successfully (188ms) + 鉁?error-1 should fail when create without page_width + 鉁?error-2 should fail when create without page_height + 鉁?error-3 should fail when delete the same template twice (71ms) + + + 6 passing (763ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/011-main.md b/test_reports/pass/011-main.md new file mode 100644 index 0000000..c347d88 --- /dev/null +++ b/test_reports/pass/011-main.md @@ -0,0 +1,35 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: main +- 文件: test/app/controller/system.setting.role.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (4ms) +[egg-ts-helper] create typings\config\index.d.ts (18ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.setting.role.test.js + 鉁?should support wildcard role permissions via ["*"] (457ms) + 鉁?should only return descendant roles and keep their children (519ms) + + + 2 passing (2s) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/013-main.md b/test_reports/pass/013-main.md new file mode 100644 index 0000000..e5c3873 --- /dev/null +++ b/test_reports/pass/013-main.md @@ -0,0 +1,41 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: main +- 文件: test/app/controller/system.stock.warehouse.getStockDetail.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (1ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (11ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/system.stock.warehouse.getStockDetail.test.js + 鉁?should return stockItem, storageList and pagination for a valid stock_id (91ms) + 鉁?should respect pagination parameters (91ms) + 鉁?should return error when stock_id is empty + 鉁?should return error when stock_id does not exist (63ms) + 鉁?should return empty storageList when stock exists but has no storage records (90ms) + 鉁?should merge storageList by space_id when group_by_batch is not provided (default) (180ms) + 鉁?should merge storageList by space_id when group_by_batch=false (explicit) (184ms) + 鉁?should return independent records per batch when group_by_batch=true (178ms) + + + 8 passing (2s) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/014-main.md b/test_reports/pass/014-main.md new file mode 100644 index 0000000..474079a --- /dev/null +++ b/test_reports/pass/014-main.md @@ -0,0 +1,34 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: main +- 文件: test/app/controller/system.stock.warehouse.namespaced.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.stock.warehouse.namespaced.test.js + 鉁?should query stock warehouse list via namespaced method (1247ms) + + + 1 passing (1s) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/015-main.md b/test_reports/pass/015-main.md new file mode 100644 index 0000000..ef9055b --- /dev/null +++ b/test_reports/pass/015-main.md @@ -0,0 +1,38 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: main +- 文件: test/app/controller/system.storage.delivery.module.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (15ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/system.storage.delivery.module.test.js + 鉁?should return delivery list via storage.stockout.list (1095ms) +[storage.stockout.toOrder] {"flag":"failure","code":405,"message":"鍗犱綅鎺ュ彛锛屾殏鏈紑鏀?,"placeholder":true} + 鉁?should return placeholder failure via storage.stockout.toOrder (1123ms) + 鉁?should return item list via storage.stockout.listItems (1181ms) + 鉁?should not expose removed storage.entry detail methods (1183ms) + + + 4 passing (5s) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/017-main.md b/test_reports/pass/017-main.md new file mode 100644 index 0000000..42cbad5 --- /dev/null +++ b/test_reports/pass/017-main.md @@ -0,0 +1,199 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: main +- 文件: test/app/controller/system.storage.inventory.matchPutaway.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.storage.inventory.matchPutaway.test.js +[SETUP] 娴嬭瘯鍟嗗搧: 娴嬭瘯鍔犺揣涓诲晢鍝?(157008), 鏂板晢鍝?156968) +[EXACT] 鏀惰揣鍗?ID: 506 +[EXACT] 鏄庣粏 1: detailId=714, product=娴嬭瘯鍔犺揣涓诲晢鍝?, qty=10 +[EXACT] 鏄庣粏 2: detailId=715, product=鏂板晢鍝? qty=5 +[EXACT] 鍏ュ簱鍗?ID: 156, code: TEST-ENTRY-1775810833609 +[EXACT] matchPutaway 鍝嶅簲: { + "flag": "success", + "code": 200, + "message": "鍖归厤鍏ュ簱瀹屾垚", + "data": { + "matched_items": [ + { + "stock_warehouse_id": 156968, + "item_code": "6902226191552", + "inbound_quantity": 5, + "rcv_available": 5, + "entry_planned": 5 + }, + { + "stock_warehouse_id": 157008, + "item_code": "6902226191553", + "inbound_quantity": 10, + "rcv_available": 10, + "entry_planned": 10 + } + ], + "receiving_results": [ + { + "receiving_id": 506, + "receiving_number": "R20553028", + "storage_status": "all" + } + ], + "entry_order_results": [ + { + "entry_order_id": 156, + "entry_order_code": "TEST-ENTRY-1775810833609", + "order_status": "COMPLETED", + "source_type": "API", + "callback_status": "SUCCESS", + "callback_detail": { + "success": true, + "skipped": true + } + } + ], + "unmatched_products": [] + }, + "timestamp": 1775810834 +} +[EXACT] 鏀惰揣鍗?storage_status: all +[EXACT] 鍏ュ簱鍗?order_status: COMPLETED + 鉁?should match putaway when receiving equals entry order (exact match) (5187ms) +[SURPLUS] 鏀惰揣鍗?ID: 507 +[SURPLUS] 鏄庣粏 1: detailId=716, product=娴嬭瘯鍔犺揣涓诲晢鍝?, rcvQty=20 +[SURPLUS] 鏄庣粏 2: detailId=717, product=鏂板晢鍝? rcvQty=15 +[SURPLUS] 鍏ュ簱鍗?ID: 157, code: TEST-ENTRY-1775810838554 +[SURPLUS] matchPutaway 鍝嶅簲: { + "flag": "success", + "code": 200, + "message": "鍖归厤鍏ュ簱瀹屾垚", + "data": { + "matched_items": [ + { + "stock_warehouse_id": 156968, + "item_code": "6902226191552", + "inbound_quantity": 5, + "rcv_available": 15, + "entry_planned": 5 + }, + { + "stock_warehouse_id": 157008, + "item_code": "6902226191553", + "inbound_quantity": 10, + "rcv_available": 20, + "entry_planned": 10 + } + ], + "receiving_results": [ + { + "receiving_id": 507, + "receiving_number": "R20553029", + "storage_status": "partial" + } + ], + "entry_order_results": [ + { + "entry_order_id": 157, + "entry_order_code": "TEST-ENTRY-1775810838554", + "order_status": "COMPLETED", + "source_type": "API", + "callback_status": "SUCCESS", + "callback_detail": { + "success": true, + "skipped": true + } + } + ], + "unmatched_products": [] + }, + "timestamp": 1775810839 +} +[SURPLUS] 鏀惰揣鍗?storage_status: partial +[SURPLUS] 鏄庣粏 716: stored=10, actual=20, status=partial +[SURPLUS] 鏄庣粏 717: stored=5, actual=15, status=partial +[SURPLUS] 鍏ュ簱鍗?order_status: COMPLETED + 鉁?should handle receiving > entry order (partial match with surplus) (4469ms) +[INSUF] 鏀惰揣鍗?ID: 508 +[INSUF] 鏄庣粏 1: detailId=718, product=娴嬭瘯鍔犺揣涓诲晢鍝?, rcvQty=5 +[INSUF] 鏄庣粏 2: detailId=719, product=鏂板晢鍝? rcvQty=3 +[INSUF] 鍏ュ簱鍗?ID: 158, code: TEST-ENTRY-1775810842785 +[INSUF] matchPutaway 鍝嶅簲: { + "flag": "success", + "code": 200, + "message": "鍖归厤鍏ュ簱瀹屾垚", + "data": { + "matched_items": [ + { + "stock_warehouse_id": 156968, + "item_code": "6902226191552", + "inbound_quantity": 3, + "rcv_available": 3, + "entry_planned": 8 + }, + { + "stock_warehouse_id": 157008, + "item_code": "6902226191553", + "inbound_quantity": 5, + "rcv_available": 5, + "entry_planned": 10 + } + ], + "receiving_results": [ + { + "receiving_id": 508, + "receiving_number": "R20553030", + "storage_status": "all" + } + ], + "entry_order_results": [ + { + "entry_order_id": 158, + "entry_order_code": "TEST-ENTRY-1775810842785", + "order_status": "PARTIAL_RECEIVED", + "source_type": "API", + "callback_status": null + } + ], + "unmatched_products": [], + "warnings": [ + "stock_warehouse_id=156968: 鏀惰揣鍙叆搴撻噺(3) < 鍏ュ簱璁″垝閲?8)锛屾寜鏀惰揣閲忓叆搴?, + "stock_warehouse_id=157008: 鏀惰揣鍙叆搴撻噺(5) < 鍏ュ簱璁″垝閲?10)锛屾寜鏀惰揣閲忓叆搴?, + "鍏ュ簱鍗?TEST-ENTRY-1775810842785: 鏈叏閮ㄥ叆搴撳畬鎴?PARTIAL_RECEIVED)锛屼笉瑙﹀彂鍥炰紶锛岄渶鎵嬪伐鎿嶄綔鎴栫瓑寰呭叾浠栨敹璐у叆搴? + ] + }, + "timestamp": 1775810843 +} +[INSUF] 鏀惰揣鍗?storage_status: all +[INSUF] 鍏ュ簱鍗?order_status: PARTIAL_RECEIVED +[INSUF] warnings: [ + 'stock_warehouse_id=156968: 鏀惰揣鍙叆搴撻噺(3) < 鍏ュ簱璁″垝閲?8)锛屾寜鏀惰揣閲忓叆搴?, + 'stock_warehouse_id=157008: 鏀惰揣鍙叆搴撻噺(5) < 鍏ュ簱璁″垝閲?10)锛屾寜鏀惰揣閲忓叆搴?, + '鍏ュ簱鍗?TEST-ENTRY-1775810842785: 鏈叏閮ㄥ叆搴撳畬鎴?PARTIAL_RECEIVED)锛屼笉瑙﹀彂鍥炰紶锛岄渶鎵嬪伐鎿嶄綔鎴栫瓑寰呭叾浠栨敹璐у叆搴? +] + 鉁?should handle receiving < entry order (insufficient receiving) (4181ms) +[TEARDOWN] 鏁版嵁搴撹繛鎺ュ凡鍏抽棴 + + + 3 passing (15s) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/018-main.md b/test_reports/pass/018-main.md new file mode 100644 index 0000000..9f0929d --- /dev/null +++ b/test_reports/pass/018-main.md @@ -0,0 +1,151 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: main +- 文件: test/app/controller/system.storage.inventory.quickPutaway.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (14ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.storage.inventory.quickPutaway.test.js +[SETUP] 娴嬭瘯鍟嗗搧: 娴嬭瘯鍔犺揣涓诲晢鍝?(157008), 鏂板晢鍝?156968), 绾哥24121410yc#zy-娑堥€€(101841) +[PARTIAL] 鏀惰揣鍗?ID: 509 +[PARTIAL] 鏄庣粏 1: detailId=720, product=娴嬭瘯鍔犺揣涓诲晢鍝? +[PARTIAL] 鏄庣粏 2: detailId=721, product=鏂板晢鍝?[PARTIAL] 鏄庣粏 3: detailId=722, product=绾哥24121410yc#zy-娑堥€€ +[PARTIAL] 鍙粦瀹氫簡 2/3 鏉℃槑缁嗙殑鍟嗗搧 +[PARTIAL] quickPutaway 鍝嶅簲: { + "flag": "success", + "code": 400, + "message": "浠ヤ笅鍟嗗搧鏈尮閰嶇郴缁熷晢鍝侊紝璇峰厛缁戝畾锛氱焊绠?4121410yc#zy-娑堥€€", + "data": { + "unmatched_count": 1, + "unmatched_names": "绾哥24121410yc#zy-娑堥€€" + }, + "timestamp": 1775810851 +} + 鉁?should reject quickPutaway for partially matched receiving (3995ms) +[FULL] 鏀惰揣鍗?ID: 510 +[FULL] 鏄庣粏 1: detailId=723, product=娴嬭瘯鍔犺揣涓诲晢鍝?, qty=10 +[FULL] 鏄庣粏 2: detailId=724, product=鏂板晢鍝? qty=5 +[FULL] quickPutaway 鍝嶅簲: { + "flag": "success", + "code": 200, + "message": "蹇嵎鍏ュ簱瀹屾垚", + "data": { + "receiving_id": 510, + "receiving_number": "R20553032", + "receiving_storage_status": "all", + "entry_order": { + "id": 159, + "entry_order_code": "SCRK17758108543901055", + "order_status": "COMPLETED" + }, + "items": [ + { + "detail_id": 723, + "product_name": "娴嬭瘯鍔犺揣涓诲晢鍝?", + "stock_warehouse_id": 157008, + "inbound_quantity": 10, + "space_id": 1, + "storage_status": "all" + }, + { + "detail_id": 724, + "product_name": "鏂板晢鍝?, + "stock_warehouse_id": 156968, + "inbound_quantity": 5, + "space_id": 1, + "storage_status": "all" + } + ] + }, + "timestamp": 1775810855 +} +[FULL] 鍏ュ簱鍗曞彿: SCRK17758108543901055, 鏄庣粏鏁? 2 +[FULL] 鏄庣粏 723: stored=10, actual=10, status=all +[FULL] 鏄庣粏 724: stored=5, actual=5, status=all +[FULL] 閲嶅鍏ュ簱鍝嶅簲: { + "flag": "success", + "code": 400, + "message": "璇ユ敹璐у崟宸插叏閮ㄥ叆搴擄紝鏃犻渶閲嶅鎿嶄綔", + "data": null, + "timestamp": 1775810855 +} + 鉁?should complete quickPutaway for fully matched receiving (4274ms) +[LOCK] 娴嬭瘯鍟嗗搧 ID: 157008 +[LOCK] 娉ㄦ剰锛氭湰娴嬭瘯闇€绛夊緟鏈嶅姟绔攣瓒呮椂锛堢害50绉掞級锛岃鑰愬績绛夊緟 +[LOCK] 宸查攣瀹?wms_stock_warehouse.id = 157008 +[LOCK] quickPutaway 鍝嶅簲 (鑰楁椂 51s): { + "flag": "success", + "code": 409, + "message": "搴撳瓨璁板綍琚攣瀹氾紝璇风◢鍚庨噸璇?, + "data": null, + "timestamp": 1775810909 +} +[LOCK] 鏁版嵁搴撹繛鎺ュ凡鍏抽棴 + 鉁?should return 409 when stock row is locked by concurrent transaction (53797ms) +[NOLOCK] 鏀惰揣鍗?ID: 512 +[NOLOCK] 鏄庣粏 1: detailId=726, product=娴嬭瘯鍔犺揣涓诲晢鍝?, qty=8 +[NOLOCK] 鏄庣粏 2: detailId=727, product=鏂板晢鍝? qty=4 +[NOLOCK] quickPutaway 鍝嶅簲: { + "flag": "success", + "code": 200, + "message": "蹇嵎鍏ュ簱瀹屾垚", + "data": { + "receiving_id": 512, + "receiving_number": "R20553034", + "receiving_storage_status": "all", + "entry_order": { + "id": 161, + "entry_order_code": "SCRK17758109126565861", + "order_status": "COMPLETED" + }, + "items": [ + { + "detail_id": 726, + "product_name": "娴嬭瘯鍔犺揣涓诲晢鍝?", + "stock_warehouse_id": 157008, + "inbound_quantity": 8, + "space_id": 1, + "storage_status": "all" + }, + { + "detail_id": 727, + "product_name": "鏂板晢鍝?, + "stock_warehouse_id": 156968, + "inbound_quantity": 4, + "space_id": 1, + "storage_status": "all" + } + ] + }, + "timestamp": 1775810913 +} +[NOLOCK] 鍏ュ簱鍗曞彿: SCRK17758109126565861 +[NOLOCK] 鍏ュ簱鏄庣粏鏁? 2 +[NOLOCK] 鏄庣粏 726: 鍏ュ簱 8, 鐘舵€?all +[NOLOCK] 鏄庣粏 727: 鍏ュ簱 4, 鐘舵€?all + 鉁?should complete quickPutaway without lock contention (4082ms) + + + 4 passing (1m) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/019-main.md b/test_reports/pass/019-main.md new file mode 100644 index 0000000..8563f39 --- /dev/null +++ b/test_reports/pass/019-main.md @@ -0,0 +1,48 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: main +- 文件: test/app/controller/system.storage.receiving.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (16ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.storage.receiving.test.js + 鉁?should query receiving list (1121ms) + 鉁?should query receiving detail when list has records (1288ms) + 鉁?should bind store to receiving and reject rebinding when owner already exists (1824ms) + 鉁?should reject bindStore when receiving is cancelled (1647ms) + 鉁?should bind and rebind system product for a receiving detail (2546ms) + 鉁?should create and then batch cancel receiving order (1293ms) + 鉁?should generate unique receiving numbers under concurrent create requests (1329ms) + 鉁?should include same-day records when created_at uses daterange filter (1368ms) + 鉁?should reject getReceivingDetail with invalid id (1045ms) + 鉁?should reject create with invalid loading_method enum (1083ms) + 鉁?should reject batchCancelReceiving with nonexistent ids (1046ms) + 鉁?should get receiving detail with details and images via storage.receiving.get (1776ms) + 鉁?should return code 0 when getting non-existent receiving via storage.receiving.get (1059ms) + 鉁?should return details sorted by id DESC via storage.receiving.get (2119ms) + 鉁?should include location space info in details via storage.receiving.get (1196ms) + + + 15 passing (22s) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/020-main.md b/test_reports/pass/020-main.md new file mode 100644 index 0000000..6d92f1a --- /dev/null +++ b/test_reports/pass/020-main.md @@ -0,0 +1,81 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: main +- 文件: test/app/controller/system.storage.transaction.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (3ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/system.storage.transaction.test.js +[SETUP] 娴嬭瘯鍟嗗搧: 娴嬭瘯鍔犺揣涓诲晢鍝?(157008), 鏂板晢鍝?156968) +[TX] 鏀惰揣鍗?ID: 524 +[TX] 鏄庣粏 1: detailId=732, product=娴嬭瘯鍔犺揣涓诲晢鍝?(157008), qty=7 +[TX] 鏄庣粏 2: detailId=733, product=鏂板晢鍝?156968), qty=3 +[TX] 鍏ュ簱鍓?wms_stock_transaction max_id: 34 +[TX] quickPutaway 鍝嶅簲: { + "flag": "success", + "code": 200, + "message": "蹇嵎鍏ュ簱瀹屾垚", + "data": { + "receiving_id": 524, + "receiving_number": "R20553045", + "receiving_storage_status": "all", + "entry_order": { + "id": 162, + "entry_order_code": "SCRK17758109440121590", + "order_status": "COMPLETED" + }, + "items": [ + { + "detail_id": 732, + "product_name": "娴嬭瘯鍔犺揣涓诲晢鍝?", + "stock_warehouse_id": 157008, + "inbound_quantity": 7, + "space_id": 1, + "storage_status": "all" + }, + { + "detail_id": 733, + "product_name": "鏂板晢鍝?, + "stock_warehouse_id": 156968, + "inbound_quantity": 3, + "space_id": 1, + "storage_status": "all" + } + ] + }, + "timestamp": 1775810944 +} +[TX] 鍏ュ簱鍗? id=162, code=SCRK17758109440121590 +[TX] 鏂板 transaction 璁板綍鏁? 2 +[TX] record id=35: type=INBOUND, order_type=SCRK, stock_id=157008, qty=7, entry_order_id=162, warehouse_id=100000, store_id=1000000 +[TX] record id=36: type=INBOUND, order_type=SCRK, stock_id=156968, qty=3, entry_order_id=162, warehouse_id=100000, store_id=1000000 +[TX] 鉁?stock_id=157008 鏁伴噺鍖归厤: 7 === 7 +[TX] 鉁?stock_id=156968 鏁伴噺鍖归厤: 3 === 3 +[TX] 鉁?鍏ㄩ儴鏂█閫氳繃锛屽叡 2 鏉?INBOUND/SCRK 璁板綍 + 鉁?should write INBOUND/SCRK records to wms_stock_transaction after quickPutaway (4302ms) +[TEARDOWN] 鏁版嵁搴撹繛鎺ュ凡鍏抽棴 + + + 1 passing (5s) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/021-main.md b/test_reports/pass/021-main.md new file mode 100644 index 0000000..89c18ce --- /dev/null +++ b/test_reports/pass/021-main.md @@ -0,0 +1,47 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: main +- 文件: test/app/controller/system.storeWarehouse.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.storeWarehouse.test.js + 鉁?should expose standalone storeWarehouse.store.list (122ms) + 鉁?should not expose removed legacy storeWarehouse.* methods + 鉁?should not expose removed setting.storeWarehouse.store.list alias + 鉁?should not expose removed setting.store_warehouse.* compatibility methods + 鉁?should expose standalone storeWarehouse.store.sign parameter validation (59ms) + 鉁?should expose standalone storeWarehouse.store.unbind parameter validation (113ms) + 鉁?should expose standalone storeWarehouse.store.rename parameter validation (122ms) + 鉁?should expose standalone storeWarehouse.store.adjustPrintQuantity with auth or validation response (116ms) + 鉁?should expose standalone storeWarehouse.store.getPolicyConfig parameter validation (60ms) + 鉁?should expose standalone storeWarehouse.store.getPolicyConfigFields as a metadata list + 鉁?should expose standalone storeWarehouse.store.savePolicyConfig parameter validation (116ms) + 鉁?should expose standalone storeWarehouse.store.saveApiConfig parameter validation (118ms) + 鉁?should expose standalone storeWarehouse.store.deleteQimenConfig parameter validation (116ms) + 鉁?should expose standalone storeWarehouse.store.listApiConfig parameter validation (58ms) + + + 14 passing (2s) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/022-main.md b/test_reports/pass/022-main.md new file mode 100644 index 0000000..868b9fa --- /dev/null +++ b/test_reports/pass/022-main.md @@ -0,0 +1,34 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: main +- 文件: test/app/controller/system.user.changeRole.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (1ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.user.changeRole.test.js + 鉁?should switch role via user.changeRole and persist response (1768ms) + + + 1 passing (2s) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/023-main.md b/test_reports/pass/023-main.md new file mode 100644 index 0000000..131d1fc --- /dev/null +++ b/test_reports/pass/023-main.md @@ -0,0 +1,34 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: main +- 文件: test/app/controller/system.user.getLoginWechatCode.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.user.getLoginWechatCode.test.js + 鉁?should return login code without Authorization token (144ms) + + + 1 passing (148ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/024-main.md b/test_reports/pass/024-main.md new file mode 100644 index 0000000..b8e2cee --- /dev/null +++ b/test_reports/pass/024-main.md @@ -0,0 +1,34 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: main +- 文件: test/app/controller/system.user.info.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/system.user.info.test.js + 鉁?should call user.info with bearer token (85ms) + + + 1 passing (89ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/025-main.md b/test_reports/pass/025-main.md new file mode 100644 index 0000000..e668b5c --- /dev/null +++ b/test_reports/pass/025-main.md @@ -0,0 +1,34 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: main +- 文件: test/app/controller/system.user.info.web.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.user.info.web.test.js + 鉁?should call user.info with platform=web project=all and persist response (87ms) + + + 1 passing (91ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/026-main.md b/test_reports/pass/026-main.md new file mode 100644 index 0000000..e08177e --- /dev/null +++ b/test_reports/pass/026-main.md @@ -0,0 +1,36 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: main +- 文件: test/app/controller/system.user.login.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (1ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.user.login.test.js + 鉁?should get token from cache or login method + 鉁?should persist token cache file + 鉁?user.login should return token only (854ms) + + + 3 passing (859ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/027-main.md b/test_reports/pass/027-main.md new file mode 100644 index 0000000..7f554bf --- /dev/null +++ b/test_reports/pass/027-main.md @@ -0,0 +1,38 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: main +- 文件: test/app/controller/system.user.loginByCode.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (4ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.user.loginByCode.test.js + - should login successfully when code is valid + 鉁?should fail when code is missing + 鉁?should fail when code does not exist + 鉁?should fail when code format is valid but not matched + + + 3 passing (97ms) + 1 pending + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/028-main.md b/test_reports/pass/028-main.md new file mode 100644 index 0000000..52bf41b --- /dev/null +++ b/test_reports/pass/028-main.md @@ -0,0 +1,34 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: main +- 文件: test/app/controller/tempFileWriter.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/tempFileWriter.test.js + 鉁?should consume fileWriter data through GET entry without date and skip completed data on second request (71ms) + + + 1 passing (3s) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/029-main.md b/test_reports/pass/029-main.md new file mode 100644 index 0000000..7d212e0 --- /dev/null +++ b/test_reports/pass/029-main.md @@ -0,0 +1,45 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: main +- 文件: test/app/lib/file_writer.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (14ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/lib/file_writer.test.js + 鉁?should keep unfinished data files and progress files during cleanup + 鉁?should mark completed files, skip them on restart, and clean them up later + 鉁?should keep consuming across files and partitions until the shared limit is reached (39ms) + 鉁?should throttle writes when write window record limit is reached + 鉁?should consume with a simple per-call limit without time-based windowing + 鉁?should consume files across multiple date partitions in write order without a date filter (39ms) + 鉁?should sort files within the same date partition by sequence instead of mtime + 鉁?should keep exact offsets for CRLF files without a trailing newline + 鉁?should ignore corrupt progress and completion markers and keep consuming + 鉁?should rethrow filesystem errors other than missing files when loading progress markers + 鉁?should recycle old partition states when the cache reaches its limit + 鉁?should limit records when maxRecords is specified (57ms) + + + 12 passing (341ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/030-main.md b/test_reports/pass/030-main.md new file mode 100644 index 0000000..6b3c128 --- /dev/null +++ b/test_reports/pass/030-main.md @@ -0,0 +1,37 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: main +- 文件: test/app/service/systemMethods/storeWarehouse/store.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (19ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (6ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/service/systemMethods/storeWarehouse/store.test.js + 鉁?should copy payload before calling list + 鉁?should copy payload before calling sign + 鉁?should keep the failure fallback for missing list method + 鉁?should keep the failure fallback for missing sign method + + + 4 passing (6ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/031-main.md b/test_reports/pass/031-main.md new file mode 100644 index 0000000..1f6a7fa --- /dev/null +++ b/test_reports/pass/031-main.md @@ -0,0 +1,36 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: main +- 文件: test/app/service/systemMethods/warehouse.auth.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (14ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/service/systemMethods/warehouse.auth.test.js + 鉁?should deny getAreaRacks when explicit api permission is missing + 鉁?should allow getAreaRacks when user has wildcard permissions + 鉁?should allow getAreaRacks when permission payload contains matching path or id + + + 3 passing (5ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/032-main.md b/test_reports/pass/032-main.md new file mode 100644 index 0000000..9a5816d --- /dev/null +++ b/test_reports/pass/032-main.md @@ -0,0 +1,36 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: main +- 文件: test/app/service/systems/auth.user.bindWechatCacheExpiry.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/service/systems/auth.user.bindWechatCacheExpiry.test.js + 鉁?should generate pending code with fixed 60s ttl and keep same code without extending + 鉁?should return scanned status when scan key exists + 鉁?should rotate code when forceNewCode is enabled + + + 3 passing (6ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/033-main.md b/test_reports/pass/033-main.md new file mode 100644 index 0000000..ac7f44e --- /dev/null +++ b/test_reports/pass/033-main.md @@ -0,0 +1,37 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: main +- 文件: test/app/service/systems/auth.user.loginWechatCode.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (3ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/service/systems/auth.user.loginWechatCode.test.js + 鉁?should generate client code and login code when client code is missing + 鉁?should refresh login code after long poll when client code is provided + 鉁?should fail when provided client code format is invalid + 鉁?should resolve login event and parse ye4s user id from redis message + + + 4 passing (8ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/034-main.md b/test_reports/pass/034-main.md new file mode 100644 index 0000000..db84383 --- /dev/null +++ b/test_reports/pass/034-main.md @@ -0,0 +1,35 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: main +- 文件: test/app/service/systems/delivery_order.oversell.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (16ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (5ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/service/systems/delivery_order.oversell.test.js + 鉁?should allow zero-available stock to proceed when oversell is enabled + 鉁?should reject zero-available stock when oversell is disabled + + + 2 passing (5ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/035-main.md b/test_reports/pass/035-main.md new file mode 100644 index 0000000..b49a3b4 --- /dev/null +++ b/test_reports/pass/035-main.md @@ -0,0 +1,39 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: main +- 文件: test/app/service/systems/excel.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (17ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (5ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/service/systems/excel.test.js + 鉁?should generate workbook buffer and parse rows back + 鉁?should normalize duplicated or empty headers when parsing + 鉁?should generate excel and upload to custom directory + 鉁?should honor skipHeader when object rows are used + 鉁?should support embedded images when url is a data URL + 鉁?should generate workbook with embedded image previews when image config exists + + + 6 passing (74ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/036-main.md b/test_reports/pass/036-main.md new file mode 100644 index 0000000..866a8e4 --- /dev/null +++ b/test_reports/pass/036-main.md @@ -0,0 +1,35 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: main +- 文件: test/app/service/systems/license_plate.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/service/systems/license_plate.test.js + 鉁?should read fixture image and return normalized recognition result + 鉁?should reject empty or invalid base64 input + + + 2 passing (8ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/038-main.md b/test_reports/pass/038-main.md new file mode 100644 index 0000000..a9efc35 --- /dev/null +++ b/test_reports/pass/038-main.md @@ -0,0 +1,40 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: main +- 文件: test/app/service/systems/stock_store.stockWarehouse.conditions.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (16ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/service/systems/stock_store.stockWarehouse.conditions.test.js + 鉁?should build Sequelize condition for all supported operators + 鉁?should normalize boolean, number and text values + 鉁?should support date and daterange condition extraction + 鉁?should parse where and return list with barcode/prohibited branches + 鉁?should short-circuit when barcode has no matched stock ids + 鉁?should ignore empty where values and fallback invalid sort field + 鉁?should return failure reason when where deconstruction is invalid + + + 7 passing (23ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/039-main.md b/test_reports/pass/039-main.md new file mode 100644 index 0000000..f3e459b --- /dev/null +++ b/test_reports/pass/039-main.md @@ -0,0 +1,34 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: main +- 文件: test/app/service/systems/stock_transaction.create.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/service/systems/stock_transaction.create.test.js + 鉁?should create stock transaction with snapshot fields + + + 1 passing (3ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/040-main.md b/test_reports/pass/040-main.md new file mode 100644 index 0000000..0cdcd13 --- /dev/null +++ b/test_reports/pass/040-main.md @@ -0,0 +1,37 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: main +- 文件: test/app/service/systems/storage.entry.cancel.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (3ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (11ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/service/systems/storage.entry.cancel.test.js + 鉁?should cancel single entry order by id + 鉁?should cancel batch entry orders by ids + 鉁?should reject empty or illegal ids + 鉁?should reject batch cancel when any order is missing or completed + + + 4 passing (6ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/042-main.md b/test_reports/pass/042-main.md new file mode 100644 index 0000000..2b3b6fc --- /dev/null +++ b/test_reports/pass/042-main.md @@ -0,0 +1,35 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: main +- 文件: test/app/service/systems/store_warehouse.adjustPrintQuantity.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (15ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (6ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/service/systems/store_warehouse.adjustPrintQuantity.test.js + 鉁?should require reason when manually adjusting print quantity + 鉁?should overwrite target balance instead of incrementing it when manually adjusting print quantity + + + 2 passing (6ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/043-main.md b/test_reports/pass/043-main.md new file mode 100644 index 0000000..49992e0 --- /dev/null +++ b/test_reports/pass/043-main.md @@ -0,0 +1,35 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: main +- 文件: test/app/service/systems/upload.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (1ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (4ms) +[egg-ts-helper] create typings\config\index.d.ts (16ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (5ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/service/systems/upload.test.js + 鉁?should prefer tencent cloud auth config while keeping COS upload parameters + 鉁?should create file reference with warehouse and creator when saving upload record + + + 2 passing (5ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/047-mirror.md b/test_reports/pass/047-mirror.md new file mode 100644 index 0000000..4f93f0c --- /dev/null +++ b/test_reports/pass/047-mirror.md @@ -0,0 +1,34 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: mirror +- 文件: test/app/controller/system.order.getreviewOrderlist.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (11ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/system.order.getreviewOrderlist.test.js + 鉁?should call order.getreviewOrderlist with platform=web project=all (3087ms) + + + 1 passing (3s) + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/053-mirror.md b/test_reports/pass/053-mirror.md new file mode 100644 index 0000000..8aa69c9 --- /dev/null +++ b/test_reports/pass/053-mirror.md @@ -0,0 +1,39 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: mirror +- 文件: test/app/controller/system.setting.printTemplate.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/system.setting.printTemplate.test.js + 鉁?normal-1 should create print template successfully (126ms) + 鉁?normal-2 should list created template by business type (61ms) + 鉁?normal-3 should delete created template successfully (184ms) + 鉁?error-1 should fail when create without page_width + 鉁?error-2 should fail when create without page_height + 鉁?error-3 should fail when delete the same template twice (60ms) + + + 6 passing (708ms) + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/054-mirror.md b/test_reports/pass/054-mirror.md new file mode 100644 index 0000000..b8268e9 --- /dev/null +++ b/test_reports/pass/054-mirror.md @@ -0,0 +1,35 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: mirror +- 文件: test/app/controller/system.setting.role.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/system.setting.role.test.js + 鉁?should support wildcard role permissions via ["*"] (442ms) + 鉁?should only return descendant roles and keep their children (493ms) + + + 2 passing (2s) + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/056-mirror.md b/test_reports/pass/056-mirror.md new file mode 100644 index 0000000..e75b826 --- /dev/null +++ b/test_reports/pass/056-mirror.md @@ -0,0 +1,41 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: mirror +- 文件: test/app/controller/system.stock.warehouse.getStockDetail.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (1ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (11ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/system.stock.warehouse.getStockDetail.test.js + 鉁?should return stockItem, storageList and pagination for a valid stock_id (99ms) + 鉁?should respect pagination parameters (93ms) + 鉁?should return error when stock_id is empty + 鉁?should return error when stock_id does not exist (61ms) + 鉁?should return empty storageList when stock exists but has no storage records (91ms) + 鉁?should merge storageList by space_id when group_by_batch is not provided (default) (184ms) + 鉁?should merge storageList by space_id when group_by_batch=false (explicit) (182ms) + 鉁?should return independent records per batch when group_by_batch=true (181ms) + + + 8 passing (2s) + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/057-mirror.md b/test_reports/pass/057-mirror.md new file mode 100644 index 0000000..4c91366 --- /dev/null +++ b/test_reports/pass/057-mirror.md @@ -0,0 +1,34 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: mirror +- 文件: test/app/controller/system.stock.warehouse.namespaced.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.stock.warehouse.namespaced.test.js + 鉁?should query stock warehouse list via namespaced method (1235ms) + + + 1 passing (1s) + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/064-mirror.md b/test_reports/pass/064-mirror.md new file mode 100644 index 0000000..fae7e97 --- /dev/null +++ b/test_reports/pass/064-mirror.md @@ -0,0 +1,47 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: mirror +- 文件: test/app/controller/system.storeWarehouse.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (3ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.storeWarehouse.test.js + 鉁?should expose standalone storeWarehouse.store.list (128ms) + 鉁?should not expose removed legacy storeWarehouse.* methods + 鉁?should not expose removed setting.storeWarehouse.store.list alias + 鉁?should not expose removed setting.store_warehouse.* compatibility methods + 鉁?should expose standalone storeWarehouse.store.sign parameter validation (60ms) + 鉁?should expose standalone storeWarehouse.store.unbind parameter validation (114ms) + 鉁?should expose standalone storeWarehouse.store.rename parameter validation (121ms) + 鉁?should expose standalone storeWarehouse.store.adjustPrintQuantity with auth or validation response (121ms) + 鉁?should expose standalone storeWarehouse.store.getPolicyConfig parameter validation (62ms) + 鉁?should expose standalone storeWarehouse.store.getPolicyConfigFields as a metadata list + 鉁?should expose standalone storeWarehouse.store.savePolicyConfig parameter validation (112ms) + 鉁?should expose standalone storeWarehouse.store.saveApiConfig parameter validation (125ms) + 鉁?should expose standalone storeWarehouse.store.deleteQimenConfig parameter validation (115ms) + 鉁?should expose standalone storeWarehouse.store.listApiConfig parameter validation (59ms) + + + 14 passing (2s) + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/065-mirror.md b/test_reports/pass/065-mirror.md new file mode 100644 index 0000000..a284b5b --- /dev/null +++ b/test_reports/pass/065-mirror.md @@ -0,0 +1,34 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: mirror +- 文件: test/app/controller/system.user.changeRole.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (11ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.user.changeRole.test.js + 鉁?should switch role via user.changeRole and persist response (1809ms) + + + 1 passing (2s) + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/066-mirror.md b/test_reports/pass/066-mirror.md new file mode 100644 index 0000000..741c5ac --- /dev/null +++ b/test_reports/pass/066-mirror.md @@ -0,0 +1,34 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: mirror +- 文件: test/app/controller/system.user.getLoginWechatCode.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (1ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.user.getLoginWechatCode.test.js + 鉁?should return login code without Authorization token (141ms) + + + 1 passing (146ms) + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/067-mirror.md b/test_reports/pass/067-mirror.md new file mode 100644 index 0000000..12353a2 --- /dev/null +++ b/test_reports/pass/067-mirror.md @@ -0,0 +1,34 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: mirror +- 文件: test/app/controller/system.user.info.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.user.info.test.js + 鉁?should call user.info with bearer token (81ms) + + + 1 passing (85ms) + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/068-mirror.md b/test_reports/pass/068-mirror.md new file mode 100644 index 0000000..74453bb --- /dev/null +++ b/test_reports/pass/068-mirror.md @@ -0,0 +1,34 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: mirror +- 文件: test/app/controller/system.user.info.web.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/system.user.info.web.test.js + 鉁?should call user.info with platform=web project=all and persist response (84ms) + + + 1 passing (89ms) + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/069-mirror.md b/test_reports/pass/069-mirror.md new file mode 100644 index 0000000..e1f653a --- /dev/null +++ b/test_reports/pass/069-mirror.md @@ -0,0 +1,36 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: mirror +- 文件: test/app/controller/system.user.login.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (1ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.user.login.test.js + 鉁?should get token from cache or login method + 鉁?should persist token cache file + 鉁?user.login should return token only (835ms) + + + 3 passing (842ms) + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/070-mirror.md b/test_reports/pass/070-mirror.md new file mode 100644 index 0000000..75d541d --- /dev/null +++ b/test_reports/pass/070-mirror.md @@ -0,0 +1,38 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: mirror +- 文件: test/app/controller/system.user.loginByCode.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.user.loginByCode.test.js + - should login successfully when code is valid + 鉁?should fail when code is missing + 鉁?should fail when code does not exist + 鉁?should fail when code format is valid but not matched + + + 3 passing (91ms) + 1 pending + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/071-mirror.md b/test_reports/pass/071-mirror.md new file mode 100644 index 0000000..ca6b81b --- /dev/null +++ b/test_reports/pass/071-mirror.md @@ -0,0 +1,37 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: mirror +- 文件: test/app/service/systemMethods/storeWarehouse/store.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (11ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/service/systemMethods/storeWarehouse/store.test.js + 鉁?should copy payload before calling list + 鉁?should copy payload before calling sign + 鉁?should keep the failure fallback for missing list method + 鉁?should keep the failure fallback for missing sign method + + + 4 passing (6ms) + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/072-mirror.md b/test_reports/pass/072-mirror.md new file mode 100644 index 0000000..aabba3f --- /dev/null +++ b/test_reports/pass/072-mirror.md @@ -0,0 +1,36 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: mirror +- 文件: test/app/service/systemMethods/warehouse.auth.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (1ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (11ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/service/systemMethods/warehouse.auth.test.js + 鉁?should deny getAreaRacks when explicit api permission is missing + 鉁?should allow getAreaRacks when user has wildcard permissions + 鉁?should allow getAreaRacks when permission payload contains matching path or id + + + 3 passing (5ms) + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/073-mirror.md b/test_reports/pass/073-mirror.md new file mode 100644 index 0000000..7b1d9fc --- /dev/null +++ b/test_reports/pass/073-mirror.md @@ -0,0 +1,36 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: mirror +- 文件: test/app/service/systems/auth.user.bindWechatCacheExpiry.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (1ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (4ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/service/systems/auth.user.bindWechatCacheExpiry.test.js + 鉁?should generate pending code with fixed 60s ttl and keep same code without extending + 鉁?should return scanned status when scan key exists + 鉁?should rotate code when forceNewCode is enabled + + + 3 passing (5ms) + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/074-mirror.md b/test_reports/pass/074-mirror.md new file mode 100644 index 0000000..2b055a2 --- /dev/null +++ b/test_reports/pass/074-mirror.md @@ -0,0 +1,37 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: mirror +- 文件: test/app/service/systems/auth.user.loginWechatCode.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/service/systems/auth.user.loginWechatCode.test.js + 鉁?should generate client code and login code when client code is missing + 鉁?should refresh login code after long poll when client code is provided + 鉁?should fail when provided client code format is invalid + 鉁?should resolve login event and parse ye4s user id from redis message + + + 4 passing (7ms) + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/075-mirror.md b/test_reports/pass/075-mirror.md new file mode 100644 index 0000000..272968b --- /dev/null +++ b/test_reports/pass/075-mirror.md @@ -0,0 +1,39 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: mirror +- 文件: test/app/service/systems/excel.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (15ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/service/systems/excel.test.js + 鉁?should generate workbook buffer and parse rows back + 鉁?should normalize duplicated or empty headers when parsing + 鉁?should generate excel and upload to custom directory + 鉁?should honor skipHeader when object rows are used + 鉁?should support embedded images when url is a data URL + 鉁?should generate workbook with embedded image previews when image config exists + + + 6 passing (69ms) + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/078-mirror.md b/test_reports/pass/078-mirror.md new file mode 100644 index 0000000..d0f93c4 --- /dev/null +++ b/test_reports/pass/078-mirror.md @@ -0,0 +1,40 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: mirror +- 文件: test/app/service/systems/stock_store.stockWarehouse.conditions.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/service/systems/stock_store.stockWarehouse.conditions.test.js + 鉁?should build Sequelize condition for all supported operators + 鉁?should normalize boolean, number and text values + 鉁?should support date and daterange condition extraction + 鉁?should parse where and return list with barcode/prohibited branches + 鉁?should short-circuit when barcode has no matched stock ids + 鉁?should ignore empty where values and fallback invalid sort field + 鉁?should return failure reason when where deconstruction is invalid + + + 7 passing (21ms) + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/079-mirror.md b/test_reports/pass/079-mirror.md new file mode 100644 index 0000000..48c802e --- /dev/null +++ b/test_reports/pass/079-mirror.md @@ -0,0 +1,34 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: mirror +- 文件: test/app/service/systems/stock_transaction.create.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (11ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/service/systems/stock_transaction.create.test.js + 鉁?should create stock transaction with snapshot fields + + + 1 passing (4ms) + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/080-mirror.md b/test_reports/pass/080-mirror.md new file mode 100644 index 0000000..78eae09 --- /dev/null +++ b/test_reports/pass/080-mirror.md @@ -0,0 +1,37 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: mirror +- 文件: test/app/service/systems/storage.entry.cancel.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (11ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/service/systems/storage.entry.cancel.test.js + 鉁?should cancel single entry order by id + 鉁?should cancel batch entry orders by ids + 鉁?should reject empty or illegal ids + 鉁?should reject batch cancel when any order is missing or completed + + + 4 passing (7ms) + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/081-mirror.md b/test_reports/pass/081-mirror.md new file mode 100644 index 0000000..c5e3f44 --- /dev/null +++ b/test_reports/pass/081-mirror.md @@ -0,0 +1,42 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: mirror +- 文件: test/app/service/systems/storage.receiving.report.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (11ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/service/systems/storage.receiving.report.test.js + 鉁?should build and upload completion excel in a single sheet with one preview column + 鉁?should send receiving completed notice with the unified event payload + 鉁?should show only license plate for truck in notice content and report main rows + 鉁?should show only tracking number for express in notice content and report main rows + 鉁?should hide both contact fields for other delivery methods + 鉁?should support nested notice.index service shape from Egg loader + 鉁?should trigger text notice before excel and then send file notice after upload succeeds + 鉁?should only send text notice when completion excel generation fails + 鉁?should still complete and notify when detail has no matched product or completeness fields + + + 9 passing (23ms) + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/082-mirror.md b/test_reports/pass/082-mirror.md new file mode 100644 index 0000000..5f8b1a3 --- /dev/null +++ b/test_reports/pass/082-mirror.md @@ -0,0 +1,35 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: mirror +- 文件: test/app/service/systems/store_warehouse.adjustPrintQuantity.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/service/systems/store_warehouse.adjustPrintQuantity.test.js + 鉁?should require reason when manually adjusting print quantity + 鉁?should overwrite target balance instead of incrementing it when manually adjusting print quantity + + + 2 passing (5ms) + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/083-mirror.md b/test_reports/pass/083-mirror.md new file mode 100644 index 0000000..5bbc47a --- /dev/null +++ b/test_reports/pass/083-mirror.md @@ -0,0 +1,35 @@ +# 测试结果 + +- 时间: 20260410-164555 +- 范围: mirror +- 文件: test/app/service/systems/upload.test.js +- 状态: pass +- 退出码: 0 + +## 标准输出 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (11ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/service/systems/upload.test.js + 鉁?should prefer tencent cloud auth config while keeping COS upload parameters + 鉁?should create file reference with warehouse and creator when saving upload record + + + 2 passing (5ms) + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html +``` + +## 标准错误 + +(empty) diff --git a/test_reports/pass/20260410-130419-main-pass-app_controller_docs.test.js.md b/test_reports/pass/20260410-130419-main-pass-app_controller_docs.test.js.md new file mode 100644 index 0000000..84b4ad6 --- /dev/null +++ b/test_reports/pass/20260410-130419-main-pass-app_controller_docs.test.js.md @@ -0,0 +1,40 @@ +# 测试结果 + +- 状态: PASS +- 分类: 主区 +- 文件: app/controller/docs.test.js +- 源: main +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:04:19.792Z +- 结束时间: 2026-04-10T13:04:24.170Z +- 耗时(秒): 4 +- 退出码: 0 +- 说明: 执行完成 + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/docs.test.js + ✔ GET /api/docs/system/changes should return 200 and a change-history JSON array + ✔ GET /api/docs/system should render HTML entries for change history and raw JSON + ✔ GET /api/docs/invalid-name!/changes should return 400 + + + 3 passing (3s) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` \ No newline at end of file diff --git a/test_reports/pass/20260410-130419-main-pass-app_controller_home.test.js.md b/test_reports/pass/20260410-130419-main-pass-app_controller_home.test.js.md new file mode 100644 index 0000000..ff52ce2 --- /dev/null +++ b/test_reports/pass/20260410-130419-main-pass-app_controller_home.test.js.md @@ -0,0 +1,40 @@ +# 测试结果 + +- 状态: PASS +- 分类: 主区 +- 文件: app/controller/home.test.js +- 源: main +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:04:25.662Z +- 结束时间: 2026-04-10T13:04:29.982Z +- 耗时(秒): 4 +- 退出码: 0 +- 说明: 执行完成 + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/home.test.js + ✔ should assert + ✔ should typings exists + ✔ should GET / + + + 3 passing (3s) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` \ No newline at end of file diff --git a/test_reports/pass/20260410-130419-main-pass-app_controller_tempFileWriter.test.js.md b/test_reports/pass/20260410-130419-main-pass-app_controller_tempFileWriter.test.js.md new file mode 100644 index 0000000..17a8c31 --- /dev/null +++ b/test_reports/pass/20260410-130419-main-pass-app_controller_tempFileWriter.test.js.md @@ -0,0 +1,38 @@ +# 测试结果 + +- 状态: PASS +- 分类: 主区 +- 文件: app/controller/tempFileWriter.test.js +- 源: main +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:05:06.057Z +- 结束时间: 2026-04-10T13:05:10.427Z +- 耗时(秒): 4 +- 退出码: 0 +- 说明: 执行完成 + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/tempFileWriter.test.js + ✔ should consume fileWriter data through GET entry without date and skip completed data on second request (68ms) + + + 1 passing (3s) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` \ No newline at end of file diff --git a/test_reports/pass/20260410-130419-main-pass-app_lib_file_writer.test.js.md b/test_reports/pass/20260410-130419-main-pass-app_lib_file_writer.test.js.md new file mode 100644 index 0000000..386c098 --- /dev/null +++ b/test_reports/pass/20260410-130419-main-pass-app_lib_file_writer.test.js.md @@ -0,0 +1,49 @@ +# 测试结果 + +- 状态: PASS +- 分类: 主区 +- 文件: app/lib/file_writer.test.js +- 源: main +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:05:10.427Z +- 结束时间: 2026-04-10T13:05:12.203Z +- 耗时(秒): 2 +- 退出码: 0 +- 说明: 执行完成 + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (3ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (14ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/lib/file_writer.test.js + ✔ should keep unfinished data files and progress files during cleanup + ✔ should mark completed files, skip them on restart, and clean them up later + ✔ should keep consuming across files and partitions until the shared limit is reached + ✔ should throttle writes when write window record limit is reached + ✔ should consume with a simple per-call limit without time-based windowing + ✔ should consume files across multiple date partitions in write order without a date filter + ✔ should sort files within the same date partition by sequence instead of mtime + ✔ should keep exact offsets for CRLF files without a trailing newline + ✔ should ignore corrupt progress and completion markers and keep consuming + ✔ should rethrow filesystem errors other than missing files when loading progress markers + ✔ should recycle old partition states when the cache reaches its limit + ✔ should limit records when maxRecords is specified + + + 12 passing (263ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` \ No newline at end of file diff --git a/test_reports/pass/20260410-130419-main-pass-app_service_systemMethods_storeWarehouse_store.test.js.md b/test_reports/pass/20260410-130419-main-pass-app_service_systemMethods_storeWarehouse_store.test.js.md new file mode 100644 index 0000000..727b9f7 --- /dev/null +++ b/test_reports/pass/20260410-130419-main-pass-app_service_systemMethods_storeWarehouse_store.test.js.md @@ -0,0 +1,41 @@ +# 测试结果 + +- 状态: PASS +- 分类: 主区 +- 文件: app/service/systemMethods/storeWarehouse/store.test.js +- 源: main +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:05:12.203Z +- 结束时间: 2026-04-10T13:05:13.802Z +- 耗时(秒): 2 +- 退出码: 0 +- 说明: 执行完成 + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/service/systemMethods/storeWarehouse/store.test.js + ✔ should copy payload before calling list + ✔ should copy payload before calling sign + ✔ should keep the failure fallback for missing list method + ✔ should keep the failure fallback for missing sign method + + + 4 passing (4ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` \ No newline at end of file diff --git a/test_reports/pass/20260410-130419-main-pass-app_service_systemMethods_warehouse.auth.test.js.md b/test_reports/pass/20260410-130419-main-pass-app_service_systemMethods_warehouse.auth.test.js.md new file mode 100644 index 0000000..43ba909 --- /dev/null +++ b/test_reports/pass/20260410-130419-main-pass-app_service_systemMethods_warehouse.auth.test.js.md @@ -0,0 +1,40 @@ +# 测试结果 + +- 状态: PASS +- 分类: 主区 +- 文件: app/service/systemMethods/warehouse.auth.test.js +- 源: main +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:05:13.803Z +- 结束时间: 2026-04-10T13:05:15.434Z +- 耗时(秒): 2 +- 退出码: 0 +- 说明: 执行完成 + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/service/systemMethods/warehouse.auth.test.js + ✔ should deny getAreaRacks when explicit api permission is missing + ✔ should allow getAreaRacks when user has wildcard permissions + ✔ should allow getAreaRacks when permission payload contains matching path or id + + + 3 passing (4ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` \ No newline at end of file diff --git a/test_reports/pass/20260410-130419-main-pass-app_service_systems_auth.user.bindWechatCacheExpiry.test.js.md b/test_reports/pass/20260410-130419-main-pass-app_service_systems_auth.user.bindWechatCacheExpiry.test.js.md new file mode 100644 index 0000000..3653deb --- /dev/null +++ b/test_reports/pass/20260410-130419-main-pass-app_service_systems_auth.user.bindWechatCacheExpiry.test.js.md @@ -0,0 +1,40 @@ +# 测试结果 + +- 状态: PASS +- 分类: 主区 +- 文件: app/service/systems/auth.user.bindWechatCacheExpiry.test.js +- 源: main +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:05:15.435Z +- 结束时间: 2026-04-10T13:05:17.025Z +- 耗时(秒): 2 +- 退出码: 0 +- 说明: 执行完成 + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/service/systems/auth.user.bindWechatCacheExpiry.test.js + ✔ should generate pending code with fixed 60s ttl and keep same code without extending + ✔ should return scanned status when scan key exists + ✔ should rotate code when forceNewCode is enabled + + + 3 passing (4ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` \ No newline at end of file diff --git a/test_reports/pass/20260410-130419-main-pass-app_service_systems_auth.user.loginWechatCode.test.js.md b/test_reports/pass/20260410-130419-main-pass-app_service_systems_auth.user.loginWechatCode.test.js.md new file mode 100644 index 0000000..17453ab --- /dev/null +++ b/test_reports/pass/20260410-130419-main-pass-app_service_systems_auth.user.loginWechatCode.test.js.md @@ -0,0 +1,41 @@ +# 测试结果 + +- 状态: PASS +- 分类: 主区 +- 文件: app/service/systems/auth.user.loginWechatCode.test.js +- 源: main +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:05:17.025Z +- 结束时间: 2026-04-10T13:05:18.593Z +- 耗时(秒): 2 +- 退出码: 0 +- 说明: 执行完成 + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/service/systems/auth.user.loginWechatCode.test.js + ✔ should generate client code and login code when client code is missing + ✔ should refresh login code after long poll when client code is provided + ✔ should fail when provided client code format is invalid + ✔ should resolve login event and parse ye4s user id from redis message + + + 4 passing (6ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` \ No newline at end of file diff --git a/test_reports/pass/20260410-130419-main-pass-app_service_systems_delivery_order.oversell.test.js.md b/test_reports/pass/20260410-130419-main-pass-app_service_systems_delivery_order.oversell.test.js.md new file mode 100644 index 0000000..b51f557 --- /dev/null +++ b/test_reports/pass/20260410-130419-main-pass-app_service_systems_delivery_order.oversell.test.js.md @@ -0,0 +1,39 @@ +# 测试结果 + +- 状态: PASS +- 分类: 主区 +- 文件: app/service/systems/delivery_order.oversell.test.js +- 源: main +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:05:22.877Z +- 结束时间: 2026-04-10T13:05:24.451Z +- 耗时(秒): 2 +- 退出码: 0 +- 说明: 执行完成 + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/service/systems/delivery_order.oversell.test.js + ✔ should allow zero-available stock to proceed when oversell is enabled + ✔ should reject zero-available stock when oversell is disabled + + + 2 passing (5ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` \ No newline at end of file diff --git a/test_reports/pass/20260410-130419-main-pass-app_service_systems_excel.test.js.md b/test_reports/pass/20260410-130419-main-pass-app_service_systems_excel.test.js.md new file mode 100644 index 0000000..059b70d --- /dev/null +++ b/test_reports/pass/20260410-130419-main-pass-app_service_systems_excel.test.js.md @@ -0,0 +1,43 @@ +# 测试结果 + +- 状态: PASS +- 分类: 主区 +- 文件: app/service/systems/excel.test.js +- 源: main +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:05:24.452Z +- 结束时间: 2026-04-10T13:05:26.338Z +- 耗时(秒): 2 +- 退出码: 0 +- 说明: 执行完成 + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (1ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/service/systems/excel.test.js + ✔ should generate workbook buffer and parse rows back + ✔ should normalize duplicated or empty headers when parsing + ✔ should generate excel and upload to custom directory + ✔ should honor skipHeader when object rows are used + ✔ should support embedded images when url is a data URL + ✔ should generate workbook with embedded image previews when image config exists + + + 6 passing (68ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` \ No newline at end of file diff --git a/test_reports/pass/20260410-130419-main-pass-app_service_systems_license_plate.test.js.md b/test_reports/pass/20260410-130419-main-pass-app_service_systems_license_plate.test.js.md new file mode 100644 index 0000000..42bdde2 --- /dev/null +++ b/test_reports/pass/20260410-130419-main-pass-app_service_systems_license_plate.test.js.md @@ -0,0 +1,39 @@ +# 测试结果 + +- 状态: PASS +- 分类: 主区 +- 文件: app/service/systems/license_plate.test.js +- 源: main +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:05:26.339Z +- 结束时间: 2026-04-10T13:05:27.946Z +- 耗时(秒): 2 +- 退出码: 0 +- 说明: 执行完成 + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/service/systems/license_plate.test.js + ✔ should read fixture image and return normalized recognition result + ✔ should reject empty or invalid base64 input + + + 2 passing (8ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` \ No newline at end of file diff --git a/test_reports/pass/20260410-130419-main-pass-app_service_systems_stock_store.stockWarehouse.conditions.test.js.md b/test_reports/pass/20260410-130419-main-pass-app_service_systems_stock_store.stockWarehouse.conditions.test.js.md new file mode 100644 index 0000000..457564f --- /dev/null +++ b/test_reports/pass/20260410-130419-main-pass-app_service_systems_stock_store.stockWarehouse.conditions.test.js.md @@ -0,0 +1,44 @@ +# 测试结果 + +- 状态: PASS +- 分类: 主区 +- 文件: app/service/systems/stock_store.stockWarehouse.conditions.test.js +- 源: main +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:05:29.543Z +- 结束时间: 2026-04-10T13:05:31.159Z +- 耗时(秒): 2 +- 退出码: 0 +- 说明: 执行完成 + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (14ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/service/systems/stock_store.stockWarehouse.conditions.test.js + ✔ should build Sequelize condition for all supported operators + ✔ should normalize boolean, number and text values + ✔ should support date and daterange condition extraction + ✔ should parse where and return list with barcode/prohibited branches + ✔ should short-circuit when barcode has no matched stock ids + ✔ should ignore empty where values and fallback invalid sort field + ✔ should return failure reason when where deconstruction is invalid + + + 7 passing (21ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` \ No newline at end of file diff --git a/test_reports/pass/20260410-130419-main-pass-app_service_systems_stock_transaction.create.test.js.md b/test_reports/pass/20260410-130419-main-pass-app_service_systems_stock_transaction.create.test.js.md new file mode 100644 index 0000000..846369b --- /dev/null +++ b/test_reports/pass/20260410-130419-main-pass-app_service_systems_stock_transaction.create.test.js.md @@ -0,0 +1,38 @@ +# 测试结果 + +- 状态: PASS +- 分类: 主区 +- 文件: app/service/systems/stock_transaction.create.test.js +- 源: main +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:05:31.159Z +- 结束时间: 2026-04-10T13:05:32.842Z +- 耗时(秒): 2 +- 退出码: 0 +- 说明: 执行完成 + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (15ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (6ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/service/systems/stock_transaction.create.test.js + ✔ should create stock transaction with snapshot fields + + + 1 passing (3ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` \ No newline at end of file diff --git a/test_reports/pass/20260410-130419-main-pass-app_service_systems_storage.entry.cancel.test.js.md b/test_reports/pass/20260410-130419-main-pass-app_service_systems_storage.entry.cancel.test.js.md new file mode 100644 index 0000000..da6622c --- /dev/null +++ b/test_reports/pass/20260410-130419-main-pass-app_service_systems_storage.entry.cancel.test.js.md @@ -0,0 +1,41 @@ +# 测试结果 + +- 状态: PASS +- 分类: 主区 +- 文件: app/service/systems/storage.entry.cancel.test.js +- 源: main +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:05:32.843Z +- 结束时间: 2026-04-10T13:05:34.423Z +- 耗时(秒): 2 +- 退出码: 0 +- 说明: 执行完成 + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (14ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/service/systems/storage.entry.cancel.test.js + ✔ should cancel single entry order by id + ✔ should cancel batch entry orders by ids + ✔ should reject empty or illegal ids + ✔ should reject batch cancel when any order is missing or completed + + + 4 passing (4ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` \ No newline at end of file diff --git a/test_reports/pass/20260410-130419-main-pass-app_service_systems_store_warehouse.adjustPrintQuantity.test.js.md b/test_reports/pass/20260410-130419-main-pass-app_service_systems_store_warehouse.adjustPrintQuantity.test.js.md new file mode 100644 index 0000000..28003c9 --- /dev/null +++ b/test_reports/pass/20260410-130419-main-pass-app_service_systems_store_warehouse.adjustPrintQuantity.test.js.md @@ -0,0 +1,39 @@ +# 测试结果 + +- 状态: PASS +- 分类: 主区 +- 文件: app/service/systems/store_warehouse.adjustPrintQuantity.test.js +- 源: main +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:05:36.049Z +- 结束时间: 2026-04-10T13:05:37.611Z +- 耗时(秒): 2 +- 退出码: 0 +- 说明: 执行完成 + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/service/systems/store_warehouse.adjustPrintQuantity.test.js + ✔ should require reason when manually adjusting print quantity + ✔ should overwrite target balance instead of incrementing it when manually adjusting print quantity + + + 2 passing (5ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` \ No newline at end of file diff --git a/test_reports/pass/20260410-130419-main-pass-app_service_systems_upload.test.js.md b/test_reports/pass/20260410-130419-main-pass-app_service_systems_upload.test.js.md new file mode 100644 index 0000000..624495e --- /dev/null +++ b/test_reports/pass/20260410-130419-main-pass-app_service_systems_upload.test.js.md @@ -0,0 +1,39 @@ +# 测试结果 + +- 状态: PASS +- 分类: 主区 +- 文件: app/service/systems/upload.test.js +- 源: main +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:05:37.612Z +- 结束时间: 2026-04-10T13:05:39.250Z +- 耗时(秒): 2 +- 退出码: 0 +- 说明: 执行完成 + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/service/systems/upload.test.js + ✔ should prefer tencent cloud auth config while keeping COS upload parameters + ✔ should create file reference with warehouse and creator when saving upload record + + + 2 passing (5ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` \ No newline at end of file diff --git a/test_reports/pass/20260410-130419-mirror-pass-app_controller_docs.test.js.md b/test_reports/pass/20260410-130419-mirror-pass-app_controller_docs.test.js.md new file mode 100644 index 0000000..7f8a2c0 --- /dev/null +++ b/test_reports/pass/20260410-130419-mirror-pass-app_controller_docs.test.js.md @@ -0,0 +1,40 @@ +# 测试结果 + +- 状态: PASS +- 分类: 镜像 +- 文件: app/controller/docs.test.js +- 源: mirror +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:05:39.251Z +- 结束时间: 2026-04-10T13:05:43.561Z +- 耗时(秒): 4 +- 退出码: 0 +- 说明: 执行完成 + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/docs.test.js + ✔ GET /api/docs/system/changes should return 200 and a change-history JSON array + ✔ GET /api/docs/system should render HTML entries for change history and raw JSON + ✔ GET /api/docs/invalid-name!/changes should return 400 + + + 3 passing (3s) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` \ No newline at end of file diff --git a/test_reports/pass/20260410-130419-mirror-pass-app_service_systemMethods_storeWarehouse_store.test.js.md b/test_reports/pass/20260410-130419-mirror-pass-app_service_systemMethods_storeWarehouse_store.test.js.md new file mode 100644 index 0000000..390d034 --- /dev/null +++ b/test_reports/pass/20260410-130419-mirror-pass-app_service_systemMethods_storeWarehouse_store.test.js.md @@ -0,0 +1,41 @@ +# 测试结果 + +- 状态: PASS +- 分类: 镜像 +- 文件: app/service/systemMethods/storeWarehouse/store.test.js +- 源: mirror +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:06:25.353Z +- 结束时间: 2026-04-10T13:06:26.948Z +- 耗时(秒): 2 +- 退出码: 0 +- 说明: 执行完成 + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/service/systemMethods/storeWarehouse/store.test.js + ✔ should copy payload before calling list + ✔ should copy payload before calling sign + ✔ should keep the failure fallback for missing list method + ✔ should keep the failure fallback for missing sign method + + + 4 passing (5ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` \ No newline at end of file diff --git a/test_reports/pass/20260410-130419-mirror-pass-app_service_systemMethods_warehouse.auth.test.js.md b/test_reports/pass/20260410-130419-mirror-pass-app_service_systemMethods_warehouse.auth.test.js.md new file mode 100644 index 0000000..ddac460 --- /dev/null +++ b/test_reports/pass/20260410-130419-mirror-pass-app_service_systemMethods_warehouse.auth.test.js.md @@ -0,0 +1,40 @@ +# 测试结果 + +- 状态: PASS +- 分类: 镜像 +- 文件: app/service/systemMethods/warehouse.auth.test.js +- 源: mirror +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:06:26.948Z +- 结束时间: 2026-04-10T13:06:28.527Z +- 耗时(秒): 2 +- 退出码: 0 +- 说明: 执行完成 + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (1ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/service/systemMethods/warehouse.auth.test.js + ✔ should deny getAreaRacks when explicit api permission is missing + ✔ should allow getAreaRacks when user has wildcard permissions + ✔ should allow getAreaRacks when permission payload contains matching path or id + + + 3 passing (8ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` \ No newline at end of file diff --git a/test_reports/pass/20260410-130419-mirror-pass-app_service_systems_auth.user.bindWechatCacheExpiry.test.js.md b/test_reports/pass/20260410-130419-mirror-pass-app_service_systems_auth.user.bindWechatCacheExpiry.test.js.md new file mode 100644 index 0000000..fac3028 --- /dev/null +++ b/test_reports/pass/20260410-130419-mirror-pass-app_service_systems_auth.user.bindWechatCacheExpiry.test.js.md @@ -0,0 +1,40 @@ +# 测试结果 + +- 状态: PASS +- 分类: 镜像 +- 文件: app/service/systems/auth.user.bindWechatCacheExpiry.test.js +- 源: mirror +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:06:28.528Z +- 结束时间: 2026-04-10T13:06:30.109Z +- 耗时(秒): 2 +- 退出码: 0 +- 说明: 执行完成 + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (14ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/service/systems/auth.user.bindWechatCacheExpiry.test.js + ✔ should generate pending code with fixed 60s ttl and keep same code without extending + ✔ should return scanned status when scan key exists + ✔ should rotate code when forceNewCode is enabled + + + 3 passing (5ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` \ No newline at end of file diff --git a/test_reports/pass/20260410-130419-mirror-pass-app_service_systems_auth.user.loginWechatCode.test.js.md b/test_reports/pass/20260410-130419-mirror-pass-app_service_systems_auth.user.loginWechatCode.test.js.md new file mode 100644 index 0000000..5235498 --- /dev/null +++ b/test_reports/pass/20260410-130419-mirror-pass-app_service_systems_auth.user.loginWechatCode.test.js.md @@ -0,0 +1,41 @@ +# 测试结果 + +- 状态: PASS +- 分类: 镜像 +- 文件: app/service/systems/auth.user.loginWechatCode.test.js +- 源: mirror +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:06:30.110Z +- 结束时间: 2026-04-10T13:06:31.691Z +- 耗时(秒): 2 +- 退出码: 0 +- 说明: 执行完成 + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/service/systems/auth.user.loginWechatCode.test.js + ✔ should generate client code and login code when client code is missing + ✔ should refresh login code after long poll when client code is provided + ✔ should fail when provided client code format is invalid + ✔ should resolve login event and parse ye4s user id from redis message + + + 4 passing (5ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` \ No newline at end of file diff --git a/test_reports/pass/20260410-130419-mirror-pass-app_service_systems_excel.test.js.md b/test_reports/pass/20260410-130419-mirror-pass-app_service_systems_excel.test.js.md new file mode 100644 index 0000000..e418ed7 --- /dev/null +++ b/test_reports/pass/20260410-130419-mirror-pass-app_service_systems_excel.test.js.md @@ -0,0 +1,43 @@ +# 测试结果 + +- 状态: PASS +- 分类: 镜像 +- 文件: app/service/systems/excel.test.js +- 源: mirror +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:06:31.691Z +- 结束时间: 2026-04-10T13:06:33.574Z +- 耗时(秒): 2 +- 退出码: 0 +- 说明: 执行完成 + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/service/systems/excel.test.js + ✔ should generate workbook buffer and parse rows back + ✔ should normalize duplicated or empty headers when parsing + ✔ should generate excel and upload to custom directory + ✔ should honor skipHeader when object rows are used + ✔ should support embedded images when url is a data URL + ✔ should generate workbook with embedded image previews when image config exists + + + 6 passing (82ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` \ No newline at end of file diff --git a/test_reports/pass/20260410-130419-mirror-pass-app_service_systems_stock_store.stockWarehouse.conditions.test.js.md b/test_reports/pass/20260410-130419-mirror-pass-app_service_systems_stock_store.stockWarehouse.conditions.test.js.md new file mode 100644 index 0000000..6a781e0 --- /dev/null +++ b/test_reports/pass/20260410-130419-mirror-pass-app_service_systems_stock_store.stockWarehouse.conditions.test.js.md @@ -0,0 +1,44 @@ +# 测试结果 + +- 状态: PASS +- 分类: 镜像 +- 文件: app/service/systems/stock_store.stockWarehouse.conditions.test.js +- 源: mirror +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:06:36.730Z +- 结束时间: 2026-04-10T13:06:38.333Z +- 耗时(秒): 2 +- 退出码: 0 +- 说明: 执行完成 + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (1ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (14ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/service/systems/stock_store.stockWarehouse.conditions.test.js + ✔ should build Sequelize condition for all supported operators + ✔ should normalize boolean, number and text values + ✔ should support date and daterange condition extraction + ✔ should parse where and return list with barcode/prohibited branches + ✔ should short-circuit when barcode has no matched stock ids + ✔ should ignore empty where values and fallback invalid sort field + ✔ should return failure reason when where deconstruction is invalid + + + 7 passing (20ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` \ No newline at end of file diff --git a/test_reports/pass/20260410-130419-mirror-pass-app_service_systems_stock_transaction.create.test.js.md b/test_reports/pass/20260410-130419-mirror-pass-app_service_systems_stock_transaction.create.test.js.md new file mode 100644 index 0000000..98119c8 --- /dev/null +++ b/test_reports/pass/20260410-130419-mirror-pass-app_service_systems_stock_transaction.create.test.js.md @@ -0,0 +1,38 @@ +# 测试结果 + +- 状态: PASS +- 分类: 镜像 +- 文件: app/service/systems/stock_transaction.create.test.js +- 源: mirror +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:06:38.333Z +- 结束时间: 2026-04-10T13:06:39.920Z +- 耗时(秒): 2 +- 退出码: 0 +- 说明: 执行完成 + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/service/systems/stock_transaction.create.test.js + ✔ should create stock transaction with snapshot fields + + + 1 passing (3ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` \ No newline at end of file diff --git a/test_reports/pass/20260410-130419-mirror-pass-app_service_systems_storage.entry.cancel.test.js.md b/test_reports/pass/20260410-130419-mirror-pass-app_service_systems_storage.entry.cancel.test.js.md new file mode 100644 index 0000000..b352176 --- /dev/null +++ b/test_reports/pass/20260410-130419-mirror-pass-app_service_systems_storage.entry.cancel.test.js.md @@ -0,0 +1,41 @@ +# 测试结果 + +- 状态: PASS +- 分类: 镜像 +- 文件: app/service/systems/storage.entry.cancel.test.js +- 源: mirror +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:06:39.921Z +- 结束时间: 2026-04-10T13:06:41.487Z +- 耗时(秒): 2 +- 退出码: 0 +- 说明: 执行完成 + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (14ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/service/systems/storage.entry.cancel.test.js + ✔ should cancel single entry order by id + ✔ should cancel batch entry orders by ids + ✔ should reject empty or illegal ids + ✔ should reject batch cancel when any order is missing or completed + + + 4 passing (4ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` \ No newline at end of file diff --git a/test_reports/pass/20260410-130419-mirror-pass-app_service_systems_storage.receiving.report.test.js.md b/test_reports/pass/20260410-130419-mirror-pass-app_service_systems_storage.receiving.report.test.js.md new file mode 100644 index 0000000..55f0659 --- /dev/null +++ b/test_reports/pass/20260410-130419-mirror-pass-app_service_systems_storage.receiving.report.test.js.md @@ -0,0 +1,46 @@ +# 测试结果 + +- 状态: PASS +- 分类: 镜像 +- 文件: app/service/systems/storage.receiving.report.test.js +- 源: mirror +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:06:41.488Z +- 结束时间: 2026-04-10T13:06:43.118Z +- 耗时(秒): 2 +- 退出码: 0 +- 说明: 执行完成 + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (14ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/service/systems/storage.receiving.report.test.js + ✔ should build and upload completion excel in a single sheet with one preview column + ✔ should send receiving completed notice with the unified event payload + ✔ should show only license plate for truck in notice content and report main rows + ✔ should show only tracking number for express in notice content and report main rows + ✔ should hide both contact fields for other delivery methods + ✔ should support nested notice.index service shape from Egg loader + ✔ should trigger text notice before excel and then send file notice after upload succeeds + ✔ should only send text notice when completion excel generation fails + ✔ should still complete and notify when detail has no matched product or completeness fields + + + 9 passing (23ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` \ No newline at end of file diff --git a/test_reports/pass/20260410-130419-mirror-pass-app_service_systems_store_warehouse.adjustPrintQuantity.test.js.md b/test_reports/pass/20260410-130419-mirror-pass-app_service_systems_store_warehouse.adjustPrintQuantity.test.js.md new file mode 100644 index 0000000..8caf50f --- /dev/null +++ b/test_reports/pass/20260410-130419-mirror-pass-app_service_systems_store_warehouse.adjustPrintQuantity.test.js.md @@ -0,0 +1,39 @@ +# 测试结果 + +- 状态: PASS +- 分类: 镜像 +- 文件: app/service/systems/store_warehouse.adjustPrintQuantity.test.js +- 源: mirror +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:06:43.119Z +- 结束时间: 2026-04-10T13:06:44.723Z +- 耗时(秒): 2 +- 退出码: 0 +- 说明: 执行完成 + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (1ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/service/systems/store_warehouse.adjustPrintQuantity.test.js + ✔ should require reason when manually adjusting print quantity + ✔ should overwrite target balance instead of incrementing it when manually adjusting print quantity + + + 2 passing (5ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` \ No newline at end of file diff --git a/test_reports/pass/20260410-130419-mirror-pass-app_service_systems_upload.test.js.md b/test_reports/pass/20260410-130419-mirror-pass-app_service_systems_upload.test.js.md new file mode 100644 index 0000000..ac0ecf9 --- /dev/null +++ b/test_reports/pass/20260410-130419-mirror-pass-app_service_systems_upload.test.js.md @@ -0,0 +1,39 @@ +# 测试结果 + +- 状态: PASS +- 分类: 镜像 +- 文件: app/service/systems/upload.test.js +- 源: mirror +- 测试类型: 自动化文件级执行 +- 测试账号: liufumingren +- 测试仓 ID: 100000 +- 测试货主 ID: 1000000 +- 开始时间: 2026-04-10T13:06:44.724Z +- 结束时间: 2026-04-10T13:06:46.424Z +- 耗时(秒): 2 +- 退出码: 0 +- 说明: 执行完成 + +## 执行输出摘录 + +```text +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/service/systems/upload.test.js + ✔ should prefer tencent cloud auth config while keeping COS upload parameters + ✔ should create file reference with warehouse and creator when saving upload record + + + 2 passing (5ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html +``` \ No newline at end of file diff --git a/test_reports/pass/20260410-订单step流程验证测试报告.md b/test_reports/pass/20260410-订单step流程验证测试报告.md new file mode 100644 index 0000000..b046d36 --- /dev/null +++ b/test_reports/pass/20260410-订单step流程验证测试报告.md @@ -0,0 +1,28 @@ + +# 订单 Step 流程验证测试报告 + +- **测试目标**: 验证 `step` 字段在订单流程中的功能是否按预期工作。 +- **测试类型**: 回归测试 +- **测试日期**: 2026年4月10日 + +## 测试范围 + +- `delivery_order.auditStatus.test.js`: 验证订单审核状态服务。 +- `order.base.step.test.js`: 验证订单步骤服务。 +- `system.order.namespaced.test.js`: 验证订单命名空间控制器。 + +## 测试产物 + +- 本测试报告 + +## 测试结果摘要 + +| 测试文件 | 命令 | 状态 | 通过数量 | 失败数量 | +| --- | --- | --- | --- | --- | +| `delivery_order.auditStatus.test.js` | `npx egg-bin test test/app/service/systems/delivery_order.auditStatus.test.js --timeout 30000` | Pass | 5 | 0 | +| `order.base.step.test.js` | `npx egg-bin test test/app/service/systemMethods/order.base.step.test.js --timeout 30000` | Pass | 2 | 0 | +| `system.order.namespaced.test.js` | `npx egg-bin test test/app/controller/system.order.namespaced.test.js --grep "step\|review order through namespaced method" --timeout 30000` | Pass | 2 | 0 | + +## 结论与建议 + +所有测试均已通过,`step` 相关功能已通过端到端验证,未发现明显问题。 diff --git a/test_reports/pass/20260410-订单审批功能-服务层测试报告.md b/test_reports/pass/20260410-订单审批功能-服务层测试报告.md new file mode 100644 index 0000000..a860228 --- /dev/null +++ b/test_reports/pass/20260410-订单审批功能-服务层测试报告.md @@ -0,0 +1,27 @@ +# 测试报告 - 订单审批功能 (服务层) + +**测试目标:** 验证 `delivery_order.auditStatus` 服务层逻辑。 + +**测试范围:** +- `test/app/service/systems/delivery_order.auditStatus.test.js` + +**测试产物:** +- 测试报告 (本文档) + +**测试结果摘要:** +- **状态:** 通过 +- **通过用例:** 5 +- **失败用例:** 0 + +**结论与建议:** +服务层 `delivery_order.auditStatus` 的逻辑已通过单元测试验证。 + +**详细测试结果:** + +| 测试文件 | 用例 | 状态 | +| --- | --- | --- | +| `delivery_order.auditStatus.test.js` | `should resolveOrderAuditStatus return "pending" when need_order_approval is 1` | :white_check_mark: Pass | +| `delivery_order.auditStatus.test.js` | `should resolveOrderAuditStatus return "approved" when need_order_approval is 0` | :white_check_mark: Pass | +| `delivery_order.auditStatus.test.js` | `should resolveOrderAuditStatus return "pending" when relation not found` | :white_check_mark: Pass | +| `delivery_order.auditStatus.test.js` | `should resolveOrderAuditStatus return "approved" when policy_config is missing` | :white_check_mark: Pass | +| `delivery_order.auditStatus.test.js` | `should prepareOrderData include audit_status` | :white_check_mark: Pass | diff --git a/test_reports/pass/20260410-货主超卖链路测试报告.md b/test_reports/pass/20260410-货主超卖链路测试报告.md new file mode 100644 index 0000000..3068cf5 --- /dev/null +++ b/test_reports/pass/20260410-货主超卖链路测试报告.md @@ -0,0 +1,45 @@ +# 货主超卖链路测试报告 + +- 测试类型:单元测试 + 集成测试 + 回归验证 + 接口验证 +- 测试目标: + - 货主允许超卖时,0 库存商品在推单/创建订单链路中应可放行并继续创建。 + - 货主不允许超卖时,同一链路应在库存不足阶段拦截。 +- 验证范围: + - `app/service/qimenMethods/stockout.js` + - `app/service/systems/delivery_order.js` + - `app/service/systems/stock_store.js` + - `test/app/service/systems/delivery_order.oversell.test.js` + - `test/app/service/systems/stock_store.stockWarehouse.conditions.test.js` + - `test/app/controller/system.storage.delivery.module.test.js` + +## 测试产物 + +- 已更新测试:`test/app/controller/system.storage.delivery.module.test.js` +- 报告文件:`test_reports/20260410-货主超卖链路测试报告.md` + +## 测试结果摘要 + +- ESLint:通过,0 错误,0 警告。 +- 测试结果:13 passing,0 failed。 +- 真实链路验证: + - `system.storage.delivery.module.test.js` 走系统方法调用链验证 `storage.stockout.list`、`storage.stockout.toOrder`、`storage.stockout.listItems`。 + - `delivery_order.oversell.test.js` 验证 0 库存场景下允许/禁止超卖的分支。 + - `stock_store.stockWarehouse.conditions.test.js` 验证库存查询条件解析与库存查询分支。 + +## 关键用例 + +- 允许超卖:0 可用库存时仍可继续创建订单明细并锁定库存。 +- 禁止超卖:0 可用库存时在库存不足阶段直接拦截,不进入后续创建。 +- 固定测试仓/货主:相关测试使用固定仓库 ID `100000` 和测试货主 ID `1000000`。 + +## 命令与结果 + +1. `npx eslint test/app/controller/system.storage.delivery.module.test.js test/app/service/systems/delivery_order.oversell.test.js test/app/service/systems/stock_store.stockWarehouse.conditions.test.js` + - 结果:通过,未输出 ESLint 错误或警告。 +2. `npx egg-bin test test/app/service/systems/delivery_order.oversell.test.js test/app/service/systems/stock_store.stockWarehouse.conditions.test.js test/app/controller/system.storage.delivery.module.test.js` + - 结果:13 passing,0 failed。 + +## 结论与建议 + +- 结论:货主允许超卖 + 0 库存推单/创建订单场景已通过验证,禁止超卖场景也已按库存不足阶段拦截,当前回归通过。 +- 建议:后续若补充更多真实库存数据场景,继续沿用固定仓库 ID `100000` 和测试货主 ID `1000000`,避免引入动态选择。 \ No newline at end of file diff --git a/test_reports/pass/20260411-161359-收货入库相关测试通过简报.md b/test_reports/pass/20260411-161359-收货入库相关测试通过简报.md new file mode 100644 index 0000000..dd1f380 --- /dev/null +++ b/test_reports/pass/20260411-161359-收货入库相关测试通过简报.md @@ -0,0 +1,29 @@ +# 收货入库相关测试通过简报 + +## 测试目标 +验证收货入库链路中两个现有回归测试文件是否可稳定通过: +- [test/app/controller/system.storage.receiving.test.js](../../test/app/controller/system.storage.receiving.test.js) +- [test/app/controller/system.storage.inventory.matchPutaway.test.js](../../test/app/controller/system.storage.inventory.matchPutaway.test.js) + +## 测试类型 +回归测试,包含接口验证与集成测试。 + +## 测试范围 +- 收货单列表、详情、绑定货主、绑定商品、取消收货、创建校验、详情排序、图片返回等 controller 回归用例 +- 收货完成后与入库单的精确匹配、超收、少收三类 matchPutaway 场景 + +## 依赖与公共 setup +- receiving controller 测试依赖 `test/support/system_method_client`,并在用例内切换到固定测试仓角色。 +- matchPutaway 测试依赖 `before` 中的登录、仓库角色切换、系统商品查询,以及 `after` 中的数据库连接关闭。 +- matchPutaway 测试还会直接连接数据库并插入入库单与明细数据。 + +## 测试结果摘要 +- [test/app/controller/system.storage.receiving.test.js](../../test/app/controller/system.storage.receiving.test.js): 15 通过,0 失败,0 跳过 +- [test/app/controller/system.storage.inventory.matchPutaway.test.js](../../test/app/controller/system.storage.inventory.matchPutaway.test.js): 3 通过,0 失败,0 跳过 + +## 结论 +这两份回归测试在当前仓库状态下通过,收货单基础流程与 matchPutaway 链路未见失败。 + +## 备注 +- 运行命令:`npm run test:local -- --timeout 120000` +- 测试环境中已按固定测试仓 ID 100000 和固定测试货主 ID 1000000 运行相关链路 diff --git a/test_reports/tmp/001-main.stderr.log b/test_reports/tmp/001-main.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/001-main.stdout.log b/test_reports/tmp/001-main.stdout.log new file mode 100644 index 0000000..bbb8661 --- /dev/null +++ b/test_reports/tmp/001-main.stdout.log @@ -0,0 +1,21 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/docs.test.js + ✔ GET /api/docs/system/changes should return 200 and a change-history JSON array + ✔ GET /api/docs/system should render HTML entries for change history and raw JSON + ✔ GET /api/docs/invalid-name!/changes should return 400 + + + 3 passing (3s) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/002-main.stderr.log b/test_reports/tmp/002-main.stderr.log new file mode 100644 index 0000000..74d58a5 --- /dev/null +++ b/test_reports/tmp/002-main.stderr.log @@ -0,0 +1,32 @@ + + Exception during run: AssertionError [ERR_ASSERTION]: SYSTEM_TEST_YE4S_USER_ID 必须显式提供且为正整数 + at Object. (D:\wms\test\app\controller\gateway.user.bindAccountByTempCode.test.js:12:8) + at Module._compile (node:internal/modules/cjs/loader:1812:14) + at Object..js (node:internal/modules/cjs/loader:1943:10) + at Module.load (node:internal/modules/cjs/loader:1533:32) + at Module._load (node:internal/modules/cjs/loader:1335:12) + at wrapModuleLoad (node:internal/modules/cjs/loader:255:19) + at loadCJSModuleWithModuleLoad (node:internal/modules/esm/translators:328:3) + at ModuleWrap. (node:internal/modules/esm/translators:233:7) + at ModuleJob.run (node:internal/modules/esm/module_job:430:25) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:661:26) + at async formattedImport (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:9:14) + at async exports.requireOrImport (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:42:28) + at async exports.loadFilesAsync (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:100:20) + at async singleRun (D:\wms\node_modules\mocha\lib\cli\run-helpers.js:162:3) + at async exports.handler (D:\wms\node_modules\mocha\lib\cli\run.js:375:5) { + generatedMessage: false, + code: 'ERR_ASSERTION', + actual: false, + expected: true, + operator: '==', + diff: 'simple' +} +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/gateway.user.bindAccountByTempCode.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} diff --git a/test_reports/tmp/002-main.stdout.log b/test_reports/tmp/002-main.stdout.log new file mode 100644 index 0000000..f5234fb --- /dev/null +++ b/test_reports/tmp/002-main.stdout.log @@ -0,0 +1,7 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (3ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (15ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) diff --git a/test_reports/tmp/003-main.stderr.log b/test_reports/tmp/003-main.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/003-main.stdout.log b/test_reports/tmp/003-main.stdout.log new file mode 100644 index 0000000..9fde128 --- /dev/null +++ b/test_reports/tmp/003-main.stdout.log @@ -0,0 +1,21 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (1ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/home.test.js + ✔ should assert + ✔ should typings exists + ✔ should GET / + + + 3 passing (3s) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/004-main.stderr.log b/test_reports/tmp/004-main.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/004-main.stdout.log b/test_reports/tmp/004-main.stdout.log new file mode 100644 index 0000000..425630d --- /dev/null +++ b/test_reports/tmp/004-main.stdout.log @@ -0,0 +1,19 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (14ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (5ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.order.getreviewOrderlist.test.js + ✔ should call order.getreviewOrderlist with platform=web project=all (2548ms) + + + 1 passing (3s) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/005-main.stderr.log b/test_reports/tmp/005-main.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/005-main.stdout.log b/test_reports/tmp/005-main.stdout.log new file mode 100644 index 0000000..a0e36e5 --- /dev/null +++ b/test_reports/tmp/005-main.stdout.log @@ -0,0 +1,20 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (15ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/system.order.namespaced.test.js + ✔ should query all namespaced order lists (2381ms) + ✔ should review order through namespaced method and restore status (2315ms) + + + 2 passing (5s) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/006-main.stderr.log b/test_reports/tmp/006-main.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/006-main.stdout.log b/test_reports/tmp/006-main.stdout.log new file mode 100644 index 0000000..7ee1a62 --- /dev/null +++ b/test_reports/tmp/006-main.stdout.log @@ -0,0 +1,19 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (1ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.order.reviewOrder.test.js + ✔ should review order and restore inspection status (2298ms) + + + 1 passing (2s) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/007-main.stderr.log b/test_reports/tmp/007-main.stderr.log new file mode 100644 index 0000000..041976d --- /dev/null +++ b/test_reports/tmp/007-main.stderr.log @@ -0,0 +1,32 @@ + + Exception during run: AssertionError [ERR_ASSERTION]: SYSTEM_TEST_YE4S_USER_ID 必须显式提供且为正整数 + at Object. (D:\wms\test\app\controller\system.setting.account.getBindWechatCode.test.js:12:8) + at Module._compile (node:internal/modules/cjs/loader:1812:14) + at Object..js (node:internal/modules/cjs/loader:1943:10) + at Module.load (node:internal/modules/cjs/loader:1533:32) + at Module._load (node:internal/modules/cjs/loader:1335:12) + at wrapModuleLoad (node:internal/modules/cjs/loader:255:19) + at loadCJSModuleWithModuleLoad (node:internal/modules/esm/translators:328:3) + at ModuleWrap. (node:internal/modules/esm/translators:233:7) + at ModuleJob.run (node:internal/modules/esm/module_job:430:25) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:661:26) + at async formattedImport (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:9:14) + at async exports.requireOrImport (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:42:28) + at async exports.loadFilesAsync (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:100:20) + at async singleRun (D:\wms\node_modules\mocha\lib\cli\run-helpers.js:162:3) + at async exports.handler (D:\wms\node_modules\mocha\lib\cli\run.js:375:5) { + generatedMessage: false, + code: 'ERR_ASSERTION', + actual: false, + expected: true, + operator: '==', + diff: 'simple' +} +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.setting.account.getBindWechatCode.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} diff --git a/test_reports/tmp/007-main.stdout.log b/test_reports/tmp/007-main.stdout.log new file mode 100644 index 0000000..9d0d447 --- /dev/null +++ b/test_reports/tmp/007-main.stdout.log @@ -0,0 +1,7 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) diff --git a/test_reports/tmp/008-main.stderr.log b/test_reports/tmp/008-main.stderr.log new file mode 100644 index 0000000..128df8a --- /dev/null +++ b/test_reports/tmp/008-main.stderr.log @@ -0,0 +1,7 @@ +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.setting.account.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} diff --git a/test_reports/tmp/008-main.stdout.log b/test_reports/tmp/008-main.stdout.log new file mode 100644 index 0000000..7265f00 --- /dev/null +++ b/test_reports/tmp/008-main.stdout.log @@ -0,0 +1,34 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (3ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (17ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.setting.account.test.js + 1) "before all" hook for "error-1 should reject add when real_name is reserved name" + + + 0 passing (93ms) + 1 failing + + 1) test/app/controller/system.setting.account.test.js + "before all" hook for "error-1 should reject add when real_name is reserved name": + + AssertionError [ERR_ASSERTION]: 已有文件ID无效 + + expected - actual + + -false + +true + + at Context. (test\app\controller\system.setting.account.test.js:91:12) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/009-main.stderr.log b/test_reports/tmp/009-main.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/009-main.stdout.log b/test_reports/tmp/009-main.stdout.log new file mode 100644 index 0000000..ecc6029 --- /dev/null +++ b/test_reports/tmp/009-main.stdout.log @@ -0,0 +1,25 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (16ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/system.setting.permission.test.js + ✔ should expose setting.role.permission as alias of setting.permission.list (246ms) + ✔ should include route presentation fields in permission list response (509ms) + ✔ should show newly created permission in list for admin management (467ms) + ✔ should reject permission update when target permission does not exist (61ms) + ✔ should create then update then delete permission successfully (644ms) + ✔ should split deleted_ids and already_deleted_ids in mixed batch delete (686ms) + ✔ should reject mixed delete when ids contain non-existent permission (405ms) + + + 7 passing (4s) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/010-main.stderr.log b/test_reports/tmp/010-main.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/010-main.stdout.log b/test_reports/tmp/010-main.stdout.log new file mode 100644 index 0000000..84d76a2 --- /dev/null +++ b/test_reports/tmp/010-main.stdout.log @@ -0,0 +1,24 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (1ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.setting.printTemplate.test.js + ✔ normal-1 should create print template successfully (129ms) + ✔ normal-2 should list created template by business type (62ms) + ✔ normal-3 should delete created template successfully (188ms) + ✔ error-1 should fail when create without page_width + ✔ error-2 should fail when create without page_height + ✔ error-3 should fail when delete the same template twice (71ms) + + + 6 passing (763ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/011-main.stderr.log b/test_reports/tmp/011-main.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/011-main.stdout.log b/test_reports/tmp/011-main.stdout.log new file mode 100644 index 0000000..55d387d --- /dev/null +++ b/test_reports/tmp/011-main.stdout.log @@ -0,0 +1,20 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (4ms) +[egg-ts-helper] create typings\config\index.d.ts (18ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.setting.role.test.js + ✔ should support wildcard role permissions via ["*"] (457ms) + ✔ should only return descendant roles and keep their children (519ms) + + + 2 passing (2s) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/012-main.stderr.log b/test_reports/tmp/012-main.stderr.log new file mode 100644 index 0000000..104626d --- /dev/null +++ b/test_reports/tmp/012-main.stderr.log @@ -0,0 +1,7 @@ +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.setting.storeWarehouse.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} diff --git a/test_reports/tmp/012-main.stdout.log b/test_reports/tmp/012-main.stdout.log new file mode 100644 index 0000000..130a75e --- /dev/null +++ b/test_reports/tmp/012-main.stdout.log @@ -0,0 +1,47 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (3ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (15ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/system.setting.storeWarehouse.test.js + ✔ should list store-warehouse contracts in current subject scope (154ms) + ✔ should allow renaming current-side remask and reflect it in list display (869ms) + ✔ should generate a temp code and support preview before confirmation (267ms) + ✔ should only change use_status when unbinding (584ms) + ✔ should allow warehouse side to save and get policy config on a contract (921ms) + ✔ should reject unsupported policy config fields on a contract (276ms) + 1) should allow warehouse side to save, update and delete api config on a contract + ✔ should reject sign when counterparty is missing (60ms) + ✔ should reject unbind when no target relation is provided (120ms) + + + 8 passing (4s) + 1 failing + + 1) test/app/controller/system.setting.storeWarehouse.test.js + should allow warehouse side to save, update and delete api config on a contract: + + AssertionError [ERR_ASSERTION]: Expected values to be strictly equal: ++ actual - expected + ++ 'failure' +- 'success' + + + expected - actual + + -failure + +success + + at Context. (test\app\controller\system.setting.storeWarehouse.test.js:300:14) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/013-main.stderr.log b/test_reports/tmp/013-main.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/013-main.stdout.log b/test_reports/tmp/013-main.stdout.log new file mode 100644 index 0000000..731b881 --- /dev/null +++ b/test_reports/tmp/013-main.stdout.log @@ -0,0 +1,26 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (1ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (11ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/system.stock.warehouse.getStockDetail.test.js + ✔ should return stockItem, storageList and pagination for a valid stock_id (91ms) + ✔ should respect pagination parameters (91ms) + ✔ should return error when stock_id is empty + ✔ should return error when stock_id does not exist (63ms) + ✔ should return empty storageList when stock exists but has no storage records (90ms) + ✔ should merge storageList by space_id when group_by_batch is not provided (default) (180ms) + ✔ should merge storageList by space_id when group_by_batch=false (explicit) (184ms) + ✔ should return independent records per batch when group_by_batch=true (178ms) + + + 8 passing (2s) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/014-main.stderr.log b/test_reports/tmp/014-main.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/014-main.stdout.log b/test_reports/tmp/014-main.stdout.log new file mode 100644 index 0000000..cc9623e --- /dev/null +++ b/test_reports/tmp/014-main.stdout.log @@ -0,0 +1,19 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.stock.warehouse.namespaced.test.js + ✔ should query stock warehouse list via namespaced method (1247ms) + + + 1 passing (1s) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/015-main.stderr.log b/test_reports/tmp/015-main.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/015-main.stdout.log b/test_reports/tmp/015-main.stdout.log new file mode 100644 index 0000000..8123e4e --- /dev/null +++ b/test_reports/tmp/015-main.stdout.log @@ -0,0 +1,23 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (15ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/system.storage.delivery.module.test.js + ✔ should return delivery list via storage.stockout.list (1095ms) +[storage.stockout.toOrder] {"flag":"failure","code":405,"message":"占位接口,暂未开放","placeholder":true} + ✔ should return placeholder failure via storage.stockout.toOrder (1123ms) + ✔ should return item list via storage.stockout.listItems (1181ms) + ✔ should not expose removed storage.entry detail methods (1183ms) + + + 4 passing (5s) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/016-main.stderr.log b/test_reports/tmp/016-main.stderr.log new file mode 100644 index 0000000..cd8595e --- /dev/null +++ b/test_reports/tmp/016-main.stderr.log @@ -0,0 +1,7 @@ +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.storage.entry.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} diff --git a/test_reports/tmp/016-main.stdout.log b/test_reports/tmp/016-main.stdout.log new file mode 100644 index 0000000..d1478e3 --- /dev/null +++ b/test_reports/tmp/016-main.stdout.log @@ -0,0 +1,70 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (1ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.storage.entry.test.js + ✔ should query entry list (1104ms) + 1) should create entry and run detail lifecycle then cancel + 2) should complete entry after adding detail + 3) should reject invalid params for create/get/addDetail + + + 1 passing (4s) + 3 failing + + 1) test/app/controller/system.storage.entry.test.js + should create entry and run detail lifecycle then cancel: + + AssertionError [ERR_ASSERTION]: Expected values to be strictly equal: + +500 !== 200 + + + expected - actual + + -500 + +200 + + at Context. (test\app\controller\system.storage.entry.test.js:109:12) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + + 2) test/app/controller/system.storage.entry.test.js + should complete entry after adding detail: + + AssertionError [ERR_ASSERTION]: Expected values to be strictly equal: + +500 !== 200 + + + expected - actual + + -500 + +200 + + at Context. (test\app\controller\system.storage.entry.test.js:181:12) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + + 3) test/app/controller/system.storage.entry.test.js + should reject invalid params for create/get/addDetail: + + AssertionError [ERR_ASSERTION]: Expected values to be strictly equal: + +500 !== 200 + + + expected - actual + + -500 + +200 + + at Context. (test\app\controller\system.storage.entry.test.js:217:12) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/017-main.stderr.log b/test_reports/tmp/017-main.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/017-main.stdout.log b/test_reports/tmp/017-main.stdout.log new file mode 100644 index 0000000..0c640c5 --- /dev/null +++ b/test_reports/tmp/017-main.stdout.log @@ -0,0 +1,184 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.storage.inventory.matchPutaway.test.js +[SETUP] 测试商品: 测试加货主商品1(157008), 新商品(156968) +[EXACT] 收货单 ID: 506 +[EXACT] 明细 1: detailId=714, product=测试加货主商品1, qty=10 +[EXACT] 明细 2: detailId=715, product=新商品, qty=5 +[EXACT] 入库单 ID: 156, code: TEST-ENTRY-1775810833609 +[EXACT] matchPutaway 响应: { + "flag": "success", + "code": 200, + "message": "匹配入库完成", + "data": { + "matched_items": [ + { + "stock_warehouse_id": 156968, + "item_code": "6902226191552", + "inbound_quantity": 5, + "rcv_available": 5, + "entry_planned": 5 + }, + { + "stock_warehouse_id": 157008, + "item_code": "6902226191553", + "inbound_quantity": 10, + "rcv_available": 10, + "entry_planned": 10 + } + ], + "receiving_results": [ + { + "receiving_id": 506, + "receiving_number": "R20553028", + "storage_status": "all" + } + ], + "entry_order_results": [ + { + "entry_order_id": 156, + "entry_order_code": "TEST-ENTRY-1775810833609", + "order_status": "COMPLETED", + "source_type": "API", + "callback_status": "SUCCESS", + "callback_detail": { + "success": true, + "skipped": true + } + } + ], + "unmatched_products": [] + }, + "timestamp": 1775810834 +} +[EXACT] 收货单 storage_status: all +[EXACT] 入库单 order_status: COMPLETED + ✔ should match putaway when receiving equals entry order (exact match) (5187ms) +[SURPLUS] 收货单 ID: 507 +[SURPLUS] 明细 1: detailId=716, product=测试加货主商品1, rcvQty=20 +[SURPLUS] 明细 2: detailId=717, product=新商品, rcvQty=15 +[SURPLUS] 入库单 ID: 157, code: TEST-ENTRY-1775810838554 +[SURPLUS] matchPutaway 响应: { + "flag": "success", + "code": 200, + "message": "匹配入库完成", + "data": { + "matched_items": [ + { + "stock_warehouse_id": 156968, + "item_code": "6902226191552", + "inbound_quantity": 5, + "rcv_available": 15, + "entry_planned": 5 + }, + { + "stock_warehouse_id": 157008, + "item_code": "6902226191553", + "inbound_quantity": 10, + "rcv_available": 20, + "entry_planned": 10 + } + ], + "receiving_results": [ + { + "receiving_id": 507, + "receiving_number": "R20553029", + "storage_status": "partial" + } + ], + "entry_order_results": [ + { + "entry_order_id": 157, + "entry_order_code": "TEST-ENTRY-1775810838554", + "order_status": "COMPLETED", + "source_type": "API", + "callback_status": "SUCCESS", + "callback_detail": { + "success": true, + "skipped": true + } + } + ], + "unmatched_products": [] + }, + "timestamp": 1775810839 +} +[SURPLUS] 收货单 storage_status: partial +[SURPLUS] 明细 716: stored=10, actual=20, status=partial +[SURPLUS] 明细 717: stored=5, actual=15, status=partial +[SURPLUS] 入库单 order_status: COMPLETED + ✔ should handle receiving > entry order (partial match with surplus) (4469ms) +[INSUF] 收货单 ID: 508 +[INSUF] 明细 1: detailId=718, product=测试加货主商品1, rcvQty=5 +[INSUF] 明细 2: detailId=719, product=新商品, rcvQty=3 +[INSUF] 入库单 ID: 158, code: TEST-ENTRY-1775810842785 +[INSUF] matchPutaway 响应: { + "flag": "success", + "code": 200, + "message": "匹配入库完成", + "data": { + "matched_items": [ + { + "stock_warehouse_id": 156968, + "item_code": "6902226191552", + "inbound_quantity": 3, + "rcv_available": 3, + "entry_planned": 8 + }, + { + "stock_warehouse_id": 157008, + "item_code": "6902226191553", + "inbound_quantity": 5, + "rcv_available": 5, + "entry_planned": 10 + } + ], + "receiving_results": [ + { + "receiving_id": 508, + "receiving_number": "R20553030", + "storage_status": "all" + } + ], + "entry_order_results": [ + { + "entry_order_id": 158, + "entry_order_code": "TEST-ENTRY-1775810842785", + "order_status": "PARTIAL_RECEIVED", + "source_type": "API", + "callback_status": null + } + ], + "unmatched_products": [], + "warnings": [ + "stock_warehouse_id=156968: 收货可入库量(3) < 入库计划量(8),按收货量入库", + "stock_warehouse_id=157008: 收货可入库量(5) < 入库计划量(10),按收货量入库", + "入库单 TEST-ENTRY-1775810842785: 未全部入库完成(PARTIAL_RECEIVED),不触发回传,需手工操作或等待其他收货入库" + ] + }, + "timestamp": 1775810843 +} +[INSUF] 收货单 storage_status: all +[INSUF] 入库单 order_status: PARTIAL_RECEIVED +[INSUF] warnings: [ + 'stock_warehouse_id=156968: 收货可入库量(3) < 入库计划量(8),按收货量入库', + 'stock_warehouse_id=157008: 收货可入库量(5) < 入库计划量(10),按收货量入库', + '入库单 TEST-ENTRY-1775810842785: 未全部入库完成(PARTIAL_RECEIVED),不触发回传,需手工操作或等待其他收货入库' +] + ✔ should handle receiving < entry order (insufficient receiving) (4181ms) +[TEARDOWN] 数据库连接已关闭 + + + 3 passing (15s) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/018-main.stderr.log b/test_reports/tmp/018-main.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/018-main.stdout.log b/test_reports/tmp/018-main.stdout.log new file mode 100644 index 0000000..ec8285e --- /dev/null +++ b/test_reports/tmp/018-main.stdout.log @@ -0,0 +1,137 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (14ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.storage.inventory.quickPutaway.test.js +[SETUP] 测试商品: 测试加货主商品1(157008), 新商品(156968), 纸箱24121410yc#zy-消退(101841) +[PARTIAL] 收货单 ID: 509 +[PARTIAL] 明细 1: detailId=720, product=测试加货主商品1 +[PARTIAL] 明细 2: detailId=721, product=新商品 +[PARTIAL] 明细 3: detailId=722, product=纸箱24121410yc#zy-消退 +[PARTIAL] 只绑定了 2/3 条明细的商品 +[PARTIAL] quickPutaway 响应: { + "flag": "success", + "code": 400, + "message": "以下商品未匹配系统商品,请先绑定:纸箱24121410yc#zy-消退", + "data": { + "unmatched_count": 1, + "unmatched_names": "纸箱24121410yc#zy-消退" + }, + "timestamp": 1775810851 +} + ✔ should reject quickPutaway for partially matched receiving (3995ms) +[FULL] 收货单 ID: 510 +[FULL] 明细 1: detailId=723, product=测试加货主商品1, qty=10 +[FULL] 明细 2: detailId=724, product=新商品, qty=5 +[FULL] quickPutaway 响应: { + "flag": "success", + "code": 200, + "message": "快捷入库完成", + "data": { + "receiving_id": 510, + "receiving_number": "R20553032", + "receiving_storage_status": "all", + "entry_order": { + "id": 159, + "entry_order_code": "SCRK17758108543901055", + "order_status": "COMPLETED" + }, + "items": [ + { + "detail_id": 723, + "product_name": "测试加货主商品1", + "stock_warehouse_id": 157008, + "inbound_quantity": 10, + "space_id": 1, + "storage_status": "all" + }, + { + "detail_id": 724, + "product_name": "新商品", + "stock_warehouse_id": 156968, + "inbound_quantity": 5, + "space_id": 1, + "storage_status": "all" + } + ] + }, + "timestamp": 1775810855 +} +[FULL] 入库单号: SCRK17758108543901055, 明细数: 2 +[FULL] 明细 723: stored=10, actual=10, status=all +[FULL] 明细 724: stored=5, actual=5, status=all +[FULL] 重复入库响应: { + "flag": "success", + "code": 400, + "message": "该收货单已全部入库,无需重复操作", + "data": null, + "timestamp": 1775810855 +} + ✔ should complete quickPutaway for fully matched receiving (4274ms) +[LOCK] 测试商品 ID: 157008 +[LOCK] 注意:本测试需等待服务端锁超时(约50秒),请耐心等待 +[LOCK] 已锁定 wms_stock_warehouse.id = 157008 +[LOCK] quickPutaway 响应 (耗时 51s): { + "flag": "success", + "code": 409, + "message": "库存记录被锁定,请稍后重试", + "data": null, + "timestamp": 1775810909 +} +[LOCK] 数据库连接已关闭 + ✔ should return 409 when stock row is locked by concurrent transaction (53797ms) +[NOLOCK] 收货单 ID: 512 +[NOLOCK] 明细 1: detailId=726, product=测试加货主商品1, qty=8 +[NOLOCK] 明细 2: detailId=727, product=新商品, qty=4 +[NOLOCK] quickPutaway 响应: { + "flag": "success", + "code": 200, + "message": "快捷入库完成", + "data": { + "receiving_id": 512, + "receiving_number": "R20553034", + "receiving_storage_status": "all", + "entry_order": { + "id": 161, + "entry_order_code": "SCRK17758109126565861", + "order_status": "COMPLETED" + }, + "items": [ + { + "detail_id": 726, + "product_name": "测试加货主商品1", + "stock_warehouse_id": 157008, + "inbound_quantity": 8, + "space_id": 1, + "storage_status": "all" + }, + { + "detail_id": 727, + "product_name": "新商品", + "stock_warehouse_id": 156968, + "inbound_quantity": 4, + "space_id": 1, + "storage_status": "all" + } + ] + }, + "timestamp": 1775810913 +} +[NOLOCK] 入库单号: SCRK17758109126565861 +[NOLOCK] 入库明细数: 2 +[NOLOCK] 明细 726: 入库 8, 状态 all +[NOLOCK] 明细 727: 入库 4, 状态 all + ✔ should complete quickPutaway without lock contention (4082ms) + + + 4 passing (1m) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/019-main.stderr.log b/test_reports/tmp/019-main.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/019-main.stdout.log b/test_reports/tmp/019-main.stdout.log new file mode 100644 index 0000000..cf46d4e --- /dev/null +++ b/test_reports/tmp/019-main.stdout.log @@ -0,0 +1,33 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (16ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.storage.receiving.test.js + ✔ should query receiving list (1121ms) + ✔ should query receiving detail when list has records (1288ms) + ✔ should bind store to receiving and reject rebinding when owner already exists (1824ms) + ✔ should reject bindStore when receiving is cancelled (1647ms) + ✔ should bind and rebind system product for a receiving detail (2546ms) + ✔ should create and then batch cancel receiving order (1293ms) + ✔ should generate unique receiving numbers under concurrent create requests (1329ms) + ✔ should include same-day records when created_at uses daterange filter (1368ms) + ✔ should reject getReceivingDetail with invalid id (1045ms) + ✔ should reject create with invalid loading_method enum (1083ms) + ✔ should reject batchCancelReceiving with nonexistent ids (1046ms) + ✔ should get receiving detail with details and images via storage.receiving.get (1776ms) + ✔ should return code 0 when getting non-existent receiving via storage.receiving.get (1059ms) + ✔ should return details sorted by id DESC via storage.receiving.get (2119ms) + ✔ should include location space info in details via storage.receiving.get (1196ms) + + + 15 passing (22s) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/020-main.stderr.log b/test_reports/tmp/020-main.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/020-main.stdout.log b/test_reports/tmp/020-main.stdout.log new file mode 100644 index 0000000..d9ed981 --- /dev/null +++ b/test_reports/tmp/020-main.stdout.log @@ -0,0 +1,66 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (3ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/system.storage.transaction.test.js +[SETUP] 测试商品: 测试加货主商品1(157008), 新商品(156968) +[TX] 收货单 ID: 524 +[TX] 明细 1: detailId=732, product=测试加货主商品1(157008), qty=7 +[TX] 明细 2: detailId=733, product=新商品(156968), qty=3 +[TX] 入库前 wms_stock_transaction max_id: 34 +[TX] quickPutaway 响应: { + "flag": "success", + "code": 200, + "message": "快捷入库完成", + "data": { + "receiving_id": 524, + "receiving_number": "R20553045", + "receiving_storage_status": "all", + "entry_order": { + "id": 162, + "entry_order_code": "SCRK17758109440121590", + "order_status": "COMPLETED" + }, + "items": [ + { + "detail_id": 732, + "product_name": "测试加货主商品1", + "stock_warehouse_id": 157008, + "inbound_quantity": 7, + "space_id": 1, + "storage_status": "all" + }, + { + "detail_id": 733, + "product_name": "新商品", + "stock_warehouse_id": 156968, + "inbound_quantity": 3, + "space_id": 1, + "storage_status": "all" + } + ] + }, + "timestamp": 1775810944 +} +[TX] 入库单: id=162, code=SCRK17758109440121590 +[TX] 新增 transaction 记录数: 2 +[TX] record id=35: type=INBOUND, order_type=SCRK, stock_id=157008, qty=7, entry_order_id=162, warehouse_id=100000, store_id=1000000 +[TX] record id=36: type=INBOUND, order_type=SCRK, stock_id=156968, qty=3, entry_order_id=162, warehouse_id=100000, store_id=1000000 +[TX] ✓ stock_id=157008 数量匹配: 7 === 7 +[TX] ✓ stock_id=156968 数量匹配: 3 === 3 +[TX] ✓ 全部断言通过,共 2 条 INBOUND/SCRK 记录 + ✔ should write INBOUND/SCRK records to wms_stock_transaction after quickPutaway (4302ms) +[TEARDOWN] 数据库连接已关闭 + + + 1 passing (5s) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/021-main.stderr.log b/test_reports/tmp/021-main.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/021-main.stdout.log b/test_reports/tmp/021-main.stdout.log new file mode 100644 index 0000000..1a91d7d --- /dev/null +++ b/test_reports/tmp/021-main.stdout.log @@ -0,0 +1,32 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.storeWarehouse.test.js + ✔ should expose standalone storeWarehouse.store.list (122ms) + ✔ should not expose removed legacy storeWarehouse.* methods + ✔ should not expose removed setting.storeWarehouse.store.list alias + ✔ should not expose removed setting.store_warehouse.* compatibility methods + ✔ should expose standalone storeWarehouse.store.sign parameter validation (59ms) + ✔ should expose standalone storeWarehouse.store.unbind parameter validation (113ms) + ✔ should expose standalone storeWarehouse.store.rename parameter validation (122ms) + ✔ should expose standalone storeWarehouse.store.adjustPrintQuantity with auth or validation response (116ms) + ✔ should expose standalone storeWarehouse.store.getPolicyConfig parameter validation (60ms) + ✔ should expose standalone storeWarehouse.store.getPolicyConfigFields as a metadata list + ✔ should expose standalone storeWarehouse.store.savePolicyConfig parameter validation (116ms) + ✔ should expose standalone storeWarehouse.store.saveApiConfig parameter validation (118ms) + ✔ should expose standalone storeWarehouse.store.deleteQimenConfig parameter validation (116ms) + ✔ should expose standalone storeWarehouse.store.listApiConfig parameter validation (58ms) + + + 14 passing (2s) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/022-main.stderr.log b/test_reports/tmp/022-main.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/022-main.stdout.log b/test_reports/tmp/022-main.stdout.log new file mode 100644 index 0000000..ef8a218 --- /dev/null +++ b/test_reports/tmp/022-main.stdout.log @@ -0,0 +1,19 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (1ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.user.changeRole.test.js + ✔ should switch role via user.changeRole and persist response (1768ms) + + + 1 passing (2s) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/023-main.stderr.log b/test_reports/tmp/023-main.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/023-main.stdout.log b/test_reports/tmp/023-main.stdout.log new file mode 100644 index 0000000..32e2531 --- /dev/null +++ b/test_reports/tmp/023-main.stdout.log @@ -0,0 +1,19 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.user.getLoginWechatCode.test.js + ✔ should return login code without Authorization token (144ms) + + + 1 passing (148ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/024-main.stderr.log b/test_reports/tmp/024-main.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/024-main.stdout.log b/test_reports/tmp/024-main.stdout.log new file mode 100644 index 0000000..7e28ab4 --- /dev/null +++ b/test_reports/tmp/024-main.stdout.log @@ -0,0 +1,19 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/system.user.info.test.js + ✔ should call user.info with bearer token (85ms) + + + 1 passing (89ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/025-main.stderr.log b/test_reports/tmp/025-main.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/025-main.stdout.log b/test_reports/tmp/025-main.stdout.log new file mode 100644 index 0000000..175622c --- /dev/null +++ b/test_reports/tmp/025-main.stdout.log @@ -0,0 +1,19 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.user.info.web.test.js + ✔ should call user.info with platform=web project=all and persist response (87ms) + + + 1 passing (91ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/026-main.stderr.log b/test_reports/tmp/026-main.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/026-main.stdout.log b/test_reports/tmp/026-main.stdout.log new file mode 100644 index 0000000..ab6d7fa --- /dev/null +++ b/test_reports/tmp/026-main.stdout.log @@ -0,0 +1,21 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (1ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.user.login.test.js + ✔ should get token from cache or login method + ✔ should persist token cache file + ✔ user.login should return token only (854ms) + + + 3 passing (859ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/027-main.stderr.log b/test_reports/tmp/027-main.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/027-main.stdout.log b/test_reports/tmp/027-main.stdout.log new file mode 100644 index 0000000..0b54099 --- /dev/null +++ b/test_reports/tmp/027-main.stdout.log @@ -0,0 +1,23 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (4ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.user.loginByCode.test.js + - should login successfully when code is valid + ✔ should fail when code is missing + ✔ should fail when code does not exist + ✔ should fail when code format is valid but not matched + + + 3 passing (97ms) + 1 pending + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/028-main.stderr.log b/test_reports/tmp/028-main.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/028-main.stdout.log b/test_reports/tmp/028-main.stdout.log new file mode 100644 index 0000000..0fe51ed --- /dev/null +++ b/test_reports/tmp/028-main.stdout.log @@ -0,0 +1,19 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/tempFileWriter.test.js + ✔ should consume fileWriter data through GET entry without date and skip completed data on second request (71ms) + + + 1 passing (3s) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/029-main.stderr.log b/test_reports/tmp/029-main.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/029-main.stdout.log b/test_reports/tmp/029-main.stdout.log new file mode 100644 index 0000000..486a4ce --- /dev/null +++ b/test_reports/tmp/029-main.stdout.log @@ -0,0 +1,30 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (14ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/lib/file_writer.test.js + ✔ should keep unfinished data files and progress files during cleanup + ✔ should mark completed files, skip them on restart, and clean them up later + ✔ should keep consuming across files and partitions until the shared limit is reached (39ms) + ✔ should throttle writes when write window record limit is reached + ✔ should consume with a simple per-call limit without time-based windowing + ✔ should consume files across multiple date partitions in write order without a date filter (39ms) + ✔ should sort files within the same date partition by sequence instead of mtime + ✔ should keep exact offsets for CRLF files without a trailing newline + ✔ should ignore corrupt progress and completion markers and keep consuming + ✔ should rethrow filesystem errors other than missing files when loading progress markers + ✔ should recycle old partition states when the cache reaches its limit + ✔ should limit records when maxRecords is specified (57ms) + + + 12 passing (341ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/030-main.stderr.log b/test_reports/tmp/030-main.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/030-main.stdout.log b/test_reports/tmp/030-main.stdout.log new file mode 100644 index 0000000..11bbf26 --- /dev/null +++ b/test_reports/tmp/030-main.stdout.log @@ -0,0 +1,22 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (19ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (6ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/service/systemMethods/storeWarehouse/store.test.js + ✔ should copy payload before calling list + ✔ should copy payload before calling sign + ✔ should keep the failure fallback for missing list method + ✔ should keep the failure fallback for missing sign method + + + 4 passing (6ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/031-main.stderr.log b/test_reports/tmp/031-main.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/031-main.stdout.log b/test_reports/tmp/031-main.stdout.log new file mode 100644 index 0000000..df2b692 --- /dev/null +++ b/test_reports/tmp/031-main.stdout.log @@ -0,0 +1,21 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (14ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/service/systemMethods/warehouse.auth.test.js + ✔ should deny getAreaRacks when explicit api permission is missing + ✔ should allow getAreaRacks when user has wildcard permissions + ✔ should allow getAreaRacks when permission payload contains matching path or id + + + 3 passing (5ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/032-main.stderr.log b/test_reports/tmp/032-main.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/032-main.stdout.log b/test_reports/tmp/032-main.stdout.log new file mode 100644 index 0000000..4d32b36 --- /dev/null +++ b/test_reports/tmp/032-main.stdout.log @@ -0,0 +1,21 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/service/systems/auth.user.bindWechatCacheExpiry.test.js + ✔ should generate pending code with fixed 60s ttl and keep same code without extending + ✔ should return scanned status when scan key exists + ✔ should rotate code when forceNewCode is enabled + + + 3 passing (6ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/033-main.stderr.log b/test_reports/tmp/033-main.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/033-main.stdout.log b/test_reports/tmp/033-main.stdout.log new file mode 100644 index 0000000..fa45e08 --- /dev/null +++ b/test_reports/tmp/033-main.stdout.log @@ -0,0 +1,22 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (3ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/service/systems/auth.user.loginWechatCode.test.js + ✔ should generate client code and login code when client code is missing + ✔ should refresh login code after long poll when client code is provided + ✔ should fail when provided client code format is invalid + ✔ should resolve login event and parse ye4s user id from redis message + + + 4 passing (8ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/034-main.stderr.log b/test_reports/tmp/034-main.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/034-main.stdout.log b/test_reports/tmp/034-main.stdout.log new file mode 100644 index 0000000..cba3648 --- /dev/null +++ b/test_reports/tmp/034-main.stdout.log @@ -0,0 +1,20 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (16ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (5ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/service/systems/delivery_order.oversell.test.js + ✔ should allow zero-available stock to proceed when oversell is enabled + ✔ should reject zero-available stock when oversell is disabled + + + 2 passing (5ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/035-main.stderr.log b/test_reports/tmp/035-main.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/035-main.stdout.log b/test_reports/tmp/035-main.stdout.log new file mode 100644 index 0000000..5e8e172 --- /dev/null +++ b/test_reports/tmp/035-main.stdout.log @@ -0,0 +1,24 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (17ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (5ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/service/systems/excel.test.js + ✔ should generate workbook buffer and parse rows back + ✔ should normalize duplicated or empty headers when parsing + ✔ should generate excel and upload to custom directory + ✔ should honor skipHeader when object rows are used + ✔ should support embedded images when url is a data URL + ✔ should generate workbook with embedded image previews when image config exists + + + 6 passing (74ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/036-main.stderr.log b/test_reports/tmp/036-main.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/036-main.stdout.log b/test_reports/tmp/036-main.stdout.log new file mode 100644 index 0000000..0345538 --- /dev/null +++ b/test_reports/tmp/036-main.stdout.log @@ -0,0 +1,20 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/service/systems/license_plate.test.js + ✔ should read fixture image and return normalized recognition result + ✔ should reject empty or invalid base64 input + + + 2 passing (8ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/037-main.stderr.log b/test_reports/tmp/037-main.stderr.log new file mode 100644 index 0000000..1943131 --- /dev/null +++ b/test_reports/tmp/037-main.stderr.log @@ -0,0 +1,7 @@ +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/service/systems/notice.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} diff --git a/test_reports/tmp/037-main.stdout.log b/test_reports/tmp/037-main.stdout.log new file mode 100644 index 0000000..975f2ba --- /dev/null +++ b/test_reports/tmp/037-main.stdout.log @@ -0,0 +1,54 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/service/systems/notice.test.js + 1) should normalize payload and send only matching webhooks + ✔ should enrich payload with store info from cache before querying database + ✔ should load store info from database and cache it when cache is empty + ✔ should send to both warehouse and owner webhooks when events match or are set to all + ✔ should only send up to the configured webhook limit + ✔ should require url for image or file message + ✔ should require warehouseId but allow empty ownerId + ✔ should retry failed webhooks three times and persist final failures + ✔ should reject sending unregistered event + ✔ should reject dotted or numeric-leading event names + ✔ should send wecom webhook as enterprise wechat direct message + ✔ should expose available webhook events and reject unsupported ones + + + 11 passing (15ms) + 1 failing + + 1) test/app/service/systems/notice.test.js + should normalize payload and send only matching webhooks: + + AssertionError [ERR_ASSERTION]: Expected values to be strictly equal: ++ actual - expected + ++ 100000 +- 1000000 + + + expected - actual + + -100000 + +1000000 + + at Object.findAll (test\app\service\systems\notice.test.js:34:20) + at D:\wms\app\service\systems\notice\index.js:796:43 + at Array.map () + at NoticeService.findMatchedWebhooks (app\service\systems\notice\index.js:786:62) + at NoticeService.send (app\service\systems\notice\index.js:826:33) + at async Context. (test\app\service\systems\notice.test.js:55:20) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/038-main.stderr.log b/test_reports/tmp/038-main.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/038-main.stdout.log b/test_reports/tmp/038-main.stdout.log new file mode 100644 index 0000000..472eb76 --- /dev/null +++ b/test_reports/tmp/038-main.stdout.log @@ -0,0 +1,25 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (16ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/service/systems/stock_store.stockWarehouse.conditions.test.js + ✔ should build Sequelize condition for all supported operators + ✔ should normalize boolean, number and text values + ✔ should support date and daterange condition extraction + ✔ should parse where and return list with barcode/prohibited branches + ✔ should short-circuit when barcode has no matched stock ids + ✔ should ignore empty where values and fallback invalid sort field + ✔ should return failure reason when where deconstruction is invalid + + + 7 passing (23ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/039-main.stderr.log b/test_reports/tmp/039-main.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/039-main.stdout.log b/test_reports/tmp/039-main.stdout.log new file mode 100644 index 0000000..872a7fb --- /dev/null +++ b/test_reports/tmp/039-main.stdout.log @@ -0,0 +1,19 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/service/systems/stock_transaction.create.test.js + ✔ should create stock transaction with snapshot fields + + + 1 passing (3ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/040-main.stderr.log b/test_reports/tmp/040-main.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/040-main.stdout.log b/test_reports/tmp/040-main.stdout.log new file mode 100644 index 0000000..a4660fc --- /dev/null +++ b/test_reports/tmp/040-main.stdout.log @@ -0,0 +1,22 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (3ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (11ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/service/systems/storage.entry.cancel.test.js + ✔ should cancel single entry order by id + ✔ should cancel batch entry orders by ids + ✔ should reject empty or illegal ids + ✔ should reject batch cancel when any order is missing or completed + + + 4 passing (6ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/041-main.stderr.log b/test_reports/tmp/041-main.stderr.log new file mode 100644 index 0000000..1572bd2 --- /dev/null +++ b/test_reports/tmp/041-main.stderr.log @@ -0,0 +1,7 @@ +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/service/systems/storage.receiving.report.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} diff --git a/test_reports/tmp/041-main.stdout.log b/test_reports/tmp/041-main.stdout.log new file mode 100644 index 0000000..fce8af2 --- /dev/null +++ b/test_reports/tmp/041-main.stdout.log @@ -0,0 +1,47 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/service/systems/storage.receiving.report.test.js + 1) should build and upload completion excel in a single sheet with one preview column + ✔ should send receiving completed notice with the unified event payload + ✔ should show only license plate for truck in notice content and report main rows + ✔ should show only tracking number for express in notice content and report main rows + ✔ should hide both contact fields for other delivery methods + ✔ should support nested notice.index service shape from Egg loader + ✔ should trigger text notice before excel and then send file notice after upload succeeds + ✔ should only send text notice when completion excel generation fails + ✔ should still complete and notify when detail has no matched product or completeness fields + + + 8 passing (24ms) + 1 failing + + 1) test/app/service/systems/storage.receiving.report.test.js + should build and upload completion excel in a single sheet with one preview column: + + AssertionError [ERR_ASSERTION]: Expected values to be strictly equal: ++ actual - expected + ++ '收货明细(已完成收货)_RCV202604040001.xlsx' +- '收货完成_RCV202604040001.xlsx' + ^ + + + expected - actual + + -收货明细(已完成收货)_RCV202604040001.xlsx + +收货完成_RCV202604040001.xlsx + + at Context. (test\app\service\systems\storage.receiving.report.test.js:260:12) + + + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/042-main.stderr.log b/test_reports/tmp/042-main.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/042-main.stdout.log b/test_reports/tmp/042-main.stdout.log new file mode 100644 index 0000000..170dde8 --- /dev/null +++ b/test_reports/tmp/042-main.stdout.log @@ -0,0 +1,20 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (15ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (6ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/service/systems/store_warehouse.adjustPrintQuantity.test.js + ✔ should require reason when manually adjusting print quantity + ✔ should overwrite target balance instead of incrementing it when manually adjusting print quantity + + + 2 passing (6ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/043-main.stderr.log b/test_reports/tmp/043-main.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/043-main.stdout.log b/test_reports/tmp/043-main.stdout.log new file mode 100644 index 0000000..7553dfb --- /dev/null +++ b/test_reports/tmp/043-main.stdout.log @@ -0,0 +1,20 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (1ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (4ms) +[egg-ts-helper] create typings\config\index.d.ts (16ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (5ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/service/systems/upload.test.js + ✔ should prefer tencent cloud auth config while keeping COS upload parameters + ✔ should create file reference with warehouse and creator when saving upload record + + + 2 passing (5ms) + +[mochawesome] Report JSON saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/044-mirror.stderr.log b/test_reports/tmp/044-mirror.stderr.log new file mode 100644 index 0000000..2a881f2 --- /dev/null +++ b/test_reports/tmp/044-mirror.stderr.log @@ -0,0 +1,50 @@ +2026-04-10 16:50:06,662 ERROR 3304 nodejs.MODULE_NOT_FOUNDError: Cannot find module './tencent-cloud' +Require stack: +- D:\wms\worktrees\deploy-20260409155126\config\config.default.js +- D:\wms\node_modules\egg-core\lib\utils\index.js +- D:\wms\node_modules\egg-core\lib\egg.js +- D:\wms\node_modules\egg-core\index.js +- D:\wms\node_modules\egg-mock\lib\context.js +- D:\wms\node_modules\egg-mock\lib\app.js +- D:\wms\node_modules\egg-mock\index.js +- D:\wms\node_modules\egg-mock\register.js +Require stack: +- D:\wms\worktrees\deploy-20260409155126\config\config.default.js +- D:\wms\node_modules\egg-core\lib\utils\index.js +- D:\wms\node_modules\egg-core\lib\egg.js +- D:\wms\node_modules\egg-core\index.js +- D:\wms\node_modules\egg-mock\lib\context.js +- D:\wms\node_modules\egg-mock\lib\app.js +- D:\wms\node_modules\egg-mock\index.js +- D:\wms\node_modules\egg-mock\register.js + at Module._resolveFilename (node:internal/modules/cjs/loader:1456:15) + at defaultResolveImpl (node:internal/modules/cjs/loader:1066:19) + at resolveForCJSWithHooks (node:internal/modules/cjs/loader:1071:22) + at Module._load (node:internal/modules/cjs/loader:1242:25) + at wrapModuleLoad (node:internal/modules/cjs/loader:255:19) + at Module.require (node:internal/modules/cjs/loader:1556:12) + at require (node:internal/modules/helpers:152:16) + at module.exports (D:\wms\worktrees\deploy-20260409155126\config\config.default.js:21:30) + at AgentWorkerLoader.loadFile (D:\wms\node_modules\egg-core\lib\loader\egg_loader.js:315:13) + at AgentWorkerLoader._loadConfig (D:\wms\node_modules\egg-core\lib\loader\mixin\config.js:82:25) + at AgentWorkerLoader._preloadAppConfig (D:\wms\node_modules\egg-core\lib\loader\mixin\config.js:67:27) + at AgentWorkerLoader.loadConfig (D:\wms\node_modules\egg-core\lib\loader\mixin\config.js:25:28) + at AgentWorkerLoader.loadConfig (D:\wms\node_modules\egg\lib\loader\agent_worker_loader.js:16:11) + at new EggApplication (D:\wms\node_modules\egg\lib\egg.js:62:17) + at new Agent (D:\wms\node_modules\egg\lib\agent.js:22:5) + at [init] (D:\wms\node_modules\egg-mock\lib\app.js:81:33) + at Generator.next () + at onFulfilled (D:\wms\node_modules\co\index.js:65:19) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) +code: "MODULE_NOT_FOUND" +requireStack: ["D:\\wms\\worktrees\\deploy-20260409155126\\config\\config.default.js","D:\\wms\\node_modules\\egg-core\\lib\\utils\\index.js","D:\\wms\\node_modules\\egg-core\\lib\\egg.js","D:\\wms\\node_modules\\egg-core\\index.js","D:\\wms\\node_modules\\egg-mock\\lib\\context.js","D:\\wms\\node_modules\\egg-mock\\lib\\app.js","D:\\wms\\node_modules\\egg-mock\\index.js","D:\\wms\\node_modules\\egg-mock\\register.js"] +pid: 3304 +hostname: MINGREN + +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/docs.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} diff --git a/test_reports/tmp/044-mirror.stdout.log b/test_reports/tmp/044-mirror.stdout.log new file mode 100644 index 0000000..a586753 --- /dev/null +++ b/test_reports/tmp/044-mirror.stdout.log @@ -0,0 +1,83 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (3ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + 1) "before all" hook: beforeAll in "{root}" + 2) "after all" hook: afterAll in "{root}" + + 0 passing (1s) + 2 failing + + 1) "before all" hook: beforeAll in "{root}": + Error: Cannot find module './tencent-cloud' +Require stack: +- D:\wms\worktrees\deploy-20260409155126\config\config.default.js +- D:\wms\node_modules\egg-core\lib\utils\index.js +- D:\wms\node_modules\egg-core\lib\egg.js +- D:\wms\node_modules\egg-core\index.js +- D:\wms\node_modules\egg-mock\lib\context.js +- D:\wms\node_modules\egg-mock\lib\app.js +- D:\wms\node_modules\egg-mock\index.js +- D:\wms\node_modules\egg-mock\register.js + at Module._resolveFilename (node:internal/modules/cjs/loader:1456:15) + at defaultResolveImpl (node:internal/modules/cjs/loader:1066:19) + at resolveForCJSWithHooks (node:internal/modules/cjs/loader:1071:22) + at Module._load (node:internal/modules/cjs/loader:1242:25) + at wrapModuleLoad (node:internal/modules/cjs/loader:255:19) + at Module.require (node:internal/modules/cjs/loader:1556:12) + at require (node:internal/modules/helpers:152:16) + at module.exports (config\config.default.js:21:30) + at AgentWorkerLoader.loadFile (D:\wms\node_modules\egg-core\lib\loader\egg_loader.js:315:13) + at AgentWorkerLoader._loadConfig (D:\wms\node_modules\egg-core\lib\loader\mixin\config.js:82:25) + at AgentWorkerLoader._preloadAppConfig (D:\wms\node_modules\egg-core\lib\loader\mixin\config.js:67:27) + at AgentWorkerLoader.loadConfig (D:\wms\node_modules\egg-core\lib\loader\mixin\config.js:25:28) + at AgentWorkerLoader.loadConfig (D:\wms\node_modules\egg\lib\loader\agent_worker_loader.js:16:11) + at new EggApplication (D:\wms\node_modules\egg\lib\egg.js:62:17) + at new Agent (D:\wms\node_modules\egg\lib\agent.js:22:5) + at [init] (D:\wms\node_modules\egg-mock\lib\app.js:81:33) + at Generator.next () + at onFulfilled (D:\wms\node_modules\co\index.js:65:19) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + + 2) "after all" hook: afterAll in "{root}": + Error: Cannot find module './tencent-cloud' +Require stack: +- D:\wms\worktrees\deploy-20260409155126\config\config.default.js +- D:\wms\node_modules\egg-core\lib\utils\index.js +- D:\wms\node_modules\egg-core\lib\egg.js +- D:\wms\node_modules\egg-core\index.js +- D:\wms\node_modules\egg-mock\lib\context.js +- D:\wms\node_modules\egg-mock\lib\app.js +- D:\wms\node_modules\egg-mock\index.js +- D:\wms\node_modules\egg-mock\register.js + at Module._resolveFilename (node:internal/modules/cjs/loader:1456:15) + at defaultResolveImpl (node:internal/modules/cjs/loader:1066:19) + at resolveForCJSWithHooks (node:internal/modules/cjs/loader:1071:22) + at Module._load (node:internal/modules/cjs/loader:1242:25) + at wrapModuleLoad (node:internal/modules/cjs/loader:255:19) + at Module.require (node:internal/modules/cjs/loader:1556:12) + at require (node:internal/modules/helpers:152:16) + at module.exports (config\config.default.js:21:30) + at AgentWorkerLoader.loadFile (D:\wms\node_modules\egg-core\lib\loader\egg_loader.js:315:13) + at AgentWorkerLoader._loadConfig (D:\wms\node_modules\egg-core\lib\loader\mixin\config.js:82:25) + at AgentWorkerLoader._preloadAppConfig (D:\wms\node_modules\egg-core\lib\loader\mixin\config.js:67:27) + at AgentWorkerLoader.loadConfig (D:\wms\node_modules\egg-core\lib\loader\mixin\config.js:25:28) + at AgentWorkerLoader.loadConfig (D:\wms\node_modules\egg\lib\loader\agent_worker_loader.js:16:11) + at new EggApplication (D:\wms\node_modules\egg\lib\egg.js:62:17) + at new Agent (D:\wms\node_modules\egg\lib\agent.js:22:5) + at [init] (D:\wms\node_modules\egg-mock\lib\app.js:81:33) + at Generator.next () + at onFulfilled (D:\wms\node_modules\co\index.js:65:19) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + + + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/045-mirror.stderr.log b/test_reports/tmp/045-mirror.stderr.log new file mode 100644 index 0000000..4c96abc --- /dev/null +++ b/test_reports/tmp/045-mirror.stderr.log @@ -0,0 +1,32 @@ + + Exception during run: AssertionError [ERR_ASSERTION]: SYSTEM_TEST_YE4S_USER_ID 必须显式提供且为正整数 + at Object. (D:\wms\worktrees\deploy-20260409155126\test\app\controller\gateway.user.bindAccountByTempCode.test.js:12:8) + at Module._compile (node:internal/modules/cjs/loader:1812:14) + at Object..js (node:internal/modules/cjs/loader:1943:10) + at Module.load (node:internal/modules/cjs/loader:1533:32) + at Module._load (node:internal/modules/cjs/loader:1335:12) + at wrapModuleLoad (node:internal/modules/cjs/loader:255:19) + at loadCJSModuleWithModuleLoad (node:internal/modules/esm/translators:328:3) + at ModuleWrap. (node:internal/modules/esm/translators:233:7) + at ModuleJob.run (node:internal/modules/esm/module_job:430:25) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:661:26) + at async formattedImport (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:9:14) + at async exports.requireOrImport (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:42:28) + at async exports.loadFilesAsync (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:100:20) + at async singleRun (D:\wms\node_modules\mocha\lib\cli\run-helpers.js:162:3) + at async exports.handler (D:\wms\node_modules\mocha\lib\cli\run.js:375:5) { + generatedMessage: false, + code: 'ERR_ASSERTION', + actual: false, + expected: true, + operator: '==', + diff: 'simple' +} +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/gateway.user.bindAccountByTempCode.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} diff --git a/test_reports/tmp/045-mirror.stdout.log b/test_reports/tmp/045-mirror.stdout.log new file mode 100644 index 0000000..2951e44 --- /dev/null +++ b/test_reports/tmp/045-mirror.stdout.log @@ -0,0 +1,7 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (15ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (5ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) diff --git a/test_reports/tmp/046-mirror.stderr.log b/test_reports/tmp/046-mirror.stderr.log new file mode 100644 index 0000000..cb77d4d --- /dev/null +++ b/test_reports/tmp/046-mirror.stderr.log @@ -0,0 +1,50 @@ +2026-04-10 16:50:12,077 ERROR 11992 nodejs.MODULE_NOT_FOUNDError: Cannot find module './tencent-cloud' +Require stack: +- D:\wms\worktrees\deploy-20260409155126\config\config.default.js +- D:\wms\node_modules\egg-core\lib\utils\index.js +- D:\wms\node_modules\egg-core\lib\egg.js +- D:\wms\node_modules\egg-core\index.js +- D:\wms\node_modules\egg-mock\lib\context.js +- D:\wms\node_modules\egg-mock\lib\app.js +- D:\wms\node_modules\egg-mock\index.js +- D:\wms\node_modules\egg-mock\register.js +Require stack: +- D:\wms\worktrees\deploy-20260409155126\config\config.default.js +- D:\wms\node_modules\egg-core\lib\utils\index.js +- D:\wms\node_modules\egg-core\lib\egg.js +- D:\wms\node_modules\egg-core\index.js +- D:\wms\node_modules\egg-mock\lib\context.js +- D:\wms\node_modules\egg-mock\lib\app.js +- D:\wms\node_modules\egg-mock\index.js +- D:\wms\node_modules\egg-mock\register.js + at Module._resolveFilename (node:internal/modules/cjs/loader:1456:15) + at defaultResolveImpl (node:internal/modules/cjs/loader:1066:19) + at resolveForCJSWithHooks (node:internal/modules/cjs/loader:1071:22) + at Module._load (node:internal/modules/cjs/loader:1242:25) + at wrapModuleLoad (node:internal/modules/cjs/loader:255:19) + at Module.require (node:internal/modules/cjs/loader:1556:12) + at require (node:internal/modules/helpers:152:16) + at module.exports (D:\wms\worktrees\deploy-20260409155126\config\config.default.js:21:30) + at AgentWorkerLoader.loadFile (D:\wms\node_modules\egg-core\lib\loader\egg_loader.js:315:13) + at AgentWorkerLoader._loadConfig (D:\wms\node_modules\egg-core\lib\loader\mixin\config.js:82:25) + at AgentWorkerLoader._preloadAppConfig (D:\wms\node_modules\egg-core\lib\loader\mixin\config.js:67:27) + at AgentWorkerLoader.loadConfig (D:\wms\node_modules\egg-core\lib\loader\mixin\config.js:25:28) + at AgentWorkerLoader.loadConfig (D:\wms\node_modules\egg\lib\loader\agent_worker_loader.js:16:11) + at new EggApplication (D:\wms\node_modules\egg\lib\egg.js:62:17) + at new Agent (D:\wms\node_modules\egg\lib\agent.js:22:5) + at [init] (D:\wms\node_modules\egg-mock\lib\app.js:81:33) + at Generator.next () + at onFulfilled (D:\wms\node_modules\co\index.js:65:19) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) +code: "MODULE_NOT_FOUND" +requireStack: ["D:\\wms\\worktrees\\deploy-20260409155126\\config\\config.default.js","D:\\wms\\node_modules\\egg-core\\lib\\utils\\index.js","D:\\wms\\node_modules\\egg-core\\lib\\egg.js","D:\\wms\\node_modules\\egg-core\\index.js","D:\\wms\\node_modules\\egg-mock\\lib\\context.js","D:\\wms\\node_modules\\egg-mock\\lib\\app.js","D:\\wms\\node_modules\\egg-mock\\index.js","D:\\wms\\node_modules\\egg-mock\\register.js"] +pid: 11992 +hostname: MINGREN + +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/home.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} diff --git a/test_reports/tmp/046-mirror.stdout.log b/test_reports/tmp/046-mirror.stdout.log new file mode 100644 index 0000000..3e04dde --- /dev/null +++ b/test_reports/tmp/046-mirror.stdout.log @@ -0,0 +1,83 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (3ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + 1) "before all" hook: beforeAll in "{root}" + 2) "after all" hook: afterAll in "{root}" + + 0 passing (1s) + 2 failing + + 1) "before all" hook: beforeAll in "{root}": + Error: Cannot find module './tencent-cloud' +Require stack: +- D:\wms\worktrees\deploy-20260409155126\config\config.default.js +- D:\wms\node_modules\egg-core\lib\utils\index.js +- D:\wms\node_modules\egg-core\lib\egg.js +- D:\wms\node_modules\egg-core\index.js +- D:\wms\node_modules\egg-mock\lib\context.js +- D:\wms\node_modules\egg-mock\lib\app.js +- D:\wms\node_modules\egg-mock\index.js +- D:\wms\node_modules\egg-mock\register.js + at Module._resolveFilename (node:internal/modules/cjs/loader:1456:15) + at defaultResolveImpl (node:internal/modules/cjs/loader:1066:19) + at resolveForCJSWithHooks (node:internal/modules/cjs/loader:1071:22) + at Module._load (node:internal/modules/cjs/loader:1242:25) + at wrapModuleLoad (node:internal/modules/cjs/loader:255:19) + at Module.require (node:internal/modules/cjs/loader:1556:12) + at require (node:internal/modules/helpers:152:16) + at module.exports (config\config.default.js:21:30) + at AgentWorkerLoader.loadFile (D:\wms\node_modules\egg-core\lib\loader\egg_loader.js:315:13) + at AgentWorkerLoader._loadConfig (D:\wms\node_modules\egg-core\lib\loader\mixin\config.js:82:25) + at AgentWorkerLoader._preloadAppConfig (D:\wms\node_modules\egg-core\lib\loader\mixin\config.js:67:27) + at AgentWorkerLoader.loadConfig (D:\wms\node_modules\egg-core\lib\loader\mixin\config.js:25:28) + at AgentWorkerLoader.loadConfig (D:\wms\node_modules\egg\lib\loader\agent_worker_loader.js:16:11) + at new EggApplication (D:\wms\node_modules\egg\lib\egg.js:62:17) + at new Agent (D:\wms\node_modules\egg\lib\agent.js:22:5) + at [init] (D:\wms\node_modules\egg-mock\lib\app.js:81:33) + at Generator.next () + at onFulfilled (D:\wms\node_modules\co\index.js:65:19) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + + 2) "after all" hook: afterAll in "{root}": + Error: Cannot find module './tencent-cloud' +Require stack: +- D:\wms\worktrees\deploy-20260409155126\config\config.default.js +- D:\wms\node_modules\egg-core\lib\utils\index.js +- D:\wms\node_modules\egg-core\lib\egg.js +- D:\wms\node_modules\egg-core\index.js +- D:\wms\node_modules\egg-mock\lib\context.js +- D:\wms\node_modules\egg-mock\lib\app.js +- D:\wms\node_modules\egg-mock\index.js +- D:\wms\node_modules\egg-mock\register.js + at Module._resolveFilename (node:internal/modules/cjs/loader:1456:15) + at defaultResolveImpl (node:internal/modules/cjs/loader:1066:19) + at resolveForCJSWithHooks (node:internal/modules/cjs/loader:1071:22) + at Module._load (node:internal/modules/cjs/loader:1242:25) + at wrapModuleLoad (node:internal/modules/cjs/loader:255:19) + at Module.require (node:internal/modules/cjs/loader:1556:12) + at require (node:internal/modules/helpers:152:16) + at module.exports (config\config.default.js:21:30) + at AgentWorkerLoader.loadFile (D:\wms\node_modules\egg-core\lib\loader\egg_loader.js:315:13) + at AgentWorkerLoader._loadConfig (D:\wms\node_modules\egg-core\lib\loader\mixin\config.js:82:25) + at AgentWorkerLoader._preloadAppConfig (D:\wms\node_modules\egg-core\lib\loader\mixin\config.js:67:27) + at AgentWorkerLoader.loadConfig (D:\wms\node_modules\egg-core\lib\loader\mixin\config.js:25:28) + at AgentWorkerLoader.loadConfig (D:\wms\node_modules\egg\lib\loader\agent_worker_loader.js:16:11) + at new EggApplication (D:\wms\node_modules\egg\lib\egg.js:62:17) + at new Agent (D:\wms\node_modules\egg\lib\agent.js:22:5) + at [init] (D:\wms\node_modules\egg-mock\lib\app.js:81:33) + at Generator.next () + at onFulfilled (D:\wms\node_modules\co\index.js:65:19) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + + + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/047-mirror.stderr.log b/test_reports/tmp/047-mirror.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/047-mirror.stdout.log b/test_reports/tmp/047-mirror.stdout.log new file mode 100644 index 0000000..4aa069c --- /dev/null +++ b/test_reports/tmp/047-mirror.stdout.log @@ -0,0 +1,19 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (11ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/system.order.getreviewOrderlist.test.js + ✔ should call order.getreviewOrderlist with platform=web project=all (3087ms) + + + 1 passing (3s) + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/048-mirror.stderr.log b/test_reports/tmp/048-mirror.stderr.log new file mode 100644 index 0000000..3347bbe --- /dev/null +++ b/test_reports/tmp/048-mirror.stderr.log @@ -0,0 +1,7 @@ +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.order.namespaced.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} diff --git a/test_reports/tmp/048-mirror.stdout.log b/test_reports/tmp/048-mirror.stdout.log new file mode 100644 index 0000000..20ac199 --- /dev/null +++ b/test_reports/tmp/048-mirror.stdout.log @@ -0,0 +1,40 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (11ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/system.order.namespaced.test.js + ✔ should query all namespaced order lists (2175ms) + 1) should review order through namespaced method and restore status + + + 1 passing (4s) + 1 failing + + 1) test/app/controller/system.order.namespaced.test.js + should review order through namespaced method and restore status: + + AssertionError [ERR_ASSERTION]: Expected values to be strictly equal: ++ actual - expected + ++ 'failure' +- 'success' + + + expected - actual + + -failure + +success + + at Context. (test\app\controller\system.order.namespaced.test.js:110:12) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + + + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/049-mirror.stderr.log b/test_reports/tmp/049-mirror.stderr.log new file mode 100644 index 0000000..b5d9328 --- /dev/null +++ b/test_reports/tmp/049-mirror.stderr.log @@ -0,0 +1,7 @@ +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.order.reviewOrder.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} diff --git a/test_reports/tmp/049-mirror.stdout.log b/test_reports/tmp/049-mirror.stdout.log new file mode 100644 index 0000000..6c9bccf --- /dev/null +++ b/test_reports/tmp/049-mirror.stdout.log @@ -0,0 +1,39 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (11ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/system.order.reviewOrder.test.js + 1) should review order and restore inspection status + + + 0 passing (2s) + 1 failing + + 1) test/app/controller/system.order.reviewOrder.test.js + should review order and restore inspection status: + + AssertionError [ERR_ASSERTION]: Expected values to be strictly equal: ++ actual - expected + ++ 'failure' +- 'success' + + + expected - actual + + -failure + +success + + at Context. (test\app\controller\system.order.reviewOrder.test.js:79:12) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + + + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/050-mirror.stderr.log b/test_reports/tmp/050-mirror.stderr.log new file mode 100644 index 0000000..f383285 --- /dev/null +++ b/test_reports/tmp/050-mirror.stderr.log @@ -0,0 +1,32 @@ + + Exception during run: AssertionError [ERR_ASSERTION]: SYSTEM_TEST_YE4S_USER_ID 必须显式提供且为正整数 + at Object. (D:\wms\worktrees\deploy-20260409155126\test\app\controller\system.setting.account.getBindWechatCode.test.js:12:8) + at Module._compile (node:internal/modules/cjs/loader:1812:14) + at Object..js (node:internal/modules/cjs/loader:1943:10) + at Module.load (node:internal/modules/cjs/loader:1533:32) + at Module._load (node:internal/modules/cjs/loader:1335:12) + at wrapModuleLoad (node:internal/modules/cjs/loader:255:19) + at loadCJSModuleWithModuleLoad (node:internal/modules/esm/translators:328:3) + at ModuleWrap. (node:internal/modules/esm/translators:233:7) + at ModuleJob.run (node:internal/modules/esm/module_job:430:25) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:661:26) + at async formattedImport (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:9:14) + at async exports.requireOrImport (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:42:28) + at async exports.loadFilesAsync (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:100:20) + at async singleRun (D:\wms\node_modules\mocha\lib\cli\run-helpers.js:162:3) + at async exports.handler (D:\wms\node_modules\mocha\lib\cli\run.js:375:5) { + generatedMessage: false, + code: 'ERR_ASSERTION', + actual: false, + expected: true, + operator: '==', + diff: 'simple' +} +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.setting.account.getBindWechatCode.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} diff --git a/test_reports/tmp/050-mirror.stdout.log b/test_reports/tmp/050-mirror.stdout.log new file mode 100644 index 0000000..4e00b07 --- /dev/null +++ b/test_reports/tmp/050-mirror.stdout.log @@ -0,0 +1,7 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (10ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) diff --git a/test_reports/tmp/051-mirror.stderr.log b/test_reports/tmp/051-mirror.stderr.log new file mode 100644 index 0000000..128df8a --- /dev/null +++ b/test_reports/tmp/051-mirror.stderr.log @@ -0,0 +1,7 @@ +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.setting.account.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} diff --git a/test_reports/tmp/051-mirror.stdout.log b/test_reports/tmp/051-mirror.stdout.log new file mode 100644 index 0000000..957ad9a --- /dev/null +++ b/test_reports/tmp/051-mirror.stdout.log @@ -0,0 +1,34 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (3ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (5ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.setting.account.test.js + 1) "before all" hook for "error-1 should reject add when real_name is reserved name" + + + 0 passing (80ms) + 1 failing + + 1) test/app/controller/system.setting.account.test.js + "before all" hook for "error-1 should reject add when real_name is reserved name": + + AssertionError [ERR_ASSERTION]: 已有文件ID无效 + + expected - actual + + -false + +true + + at Context. (test\app\controller\system.setting.account.test.js:91:12) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + + + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/052-mirror.stderr.log b/test_reports/tmp/052-mirror.stderr.log new file mode 100644 index 0000000..2929752 --- /dev/null +++ b/test_reports/tmp/052-mirror.stderr.log @@ -0,0 +1,7 @@ +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.setting.permission.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} diff --git a/test_reports/tmp/052-mirror.stdout.log b/test_reports/tmp/052-mirror.stdout.log new file mode 100644 index 0000000..ac153a3 --- /dev/null +++ b/test_reports/tmp/052-mirror.stdout.log @@ -0,0 +1,35 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.setting.permission.test.js + ✔ should expose setting.role.permission as alias of setting.permission.list (252ms) + ✔ should include route presentation fields in permission list response (506ms) + ✔ should show newly created permission in list for admin management (463ms) + ✔ should reject permission update when target permission does not exist (59ms) + 1) should create then update then delete permission successfully + ✔ should split deleted_ids and already_deleted_ids in mixed batch delete (745ms) + ✔ should reject mixed delete when ids contain non-existent permission (387ms) + + + 6 passing (4s) + 1 failing + + 1) test/app/controller/system.setting.permission.test.js + should create then update then delete permission successfully: + TypeError: fetch failed + + Caused by: Error: read ECONNRESET + at TCP.onStreamRead (node:internal/stream_base_commons:216:20) + + + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/053-mirror.stderr.log b/test_reports/tmp/053-mirror.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/053-mirror.stdout.log b/test_reports/tmp/053-mirror.stdout.log new file mode 100644 index 0000000..d0f4910 --- /dev/null +++ b/test_reports/tmp/053-mirror.stdout.log @@ -0,0 +1,24 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/system.setting.printTemplate.test.js + ✔ normal-1 should create print template successfully (126ms) + ✔ normal-2 should list created template by business type (61ms) + ✔ normal-3 should delete created template successfully (184ms) + ✔ error-1 should fail when create without page_width + ✔ error-2 should fail when create without page_height + ✔ error-3 should fail when delete the same template twice (60ms) + + + 6 passing (708ms) + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/054-mirror.stderr.log b/test_reports/tmp/054-mirror.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/054-mirror.stdout.log b/test_reports/tmp/054-mirror.stdout.log new file mode 100644 index 0000000..3f6183f --- /dev/null +++ b/test_reports/tmp/054-mirror.stdout.log @@ -0,0 +1,20 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/system.setting.role.test.js + ✔ should support wildcard role permissions via ["*"] (442ms) + ✔ should only return descendant roles and keep their children (493ms) + + + 2 passing (2s) + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/055-mirror.stderr.log b/test_reports/tmp/055-mirror.stderr.log new file mode 100644 index 0000000..104626d --- /dev/null +++ b/test_reports/tmp/055-mirror.stderr.log @@ -0,0 +1,7 @@ +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.setting.storeWarehouse.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} diff --git a/test_reports/tmp/055-mirror.stdout.log b/test_reports/tmp/055-mirror.stdout.log new file mode 100644 index 0000000..eaf495a --- /dev/null +++ b/test_reports/tmp/055-mirror.stdout.log @@ -0,0 +1,47 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/system.setting.storeWarehouse.test.js + ✔ should list store-warehouse contracts in current subject scope (155ms) + ✔ should allow renaming current-side remask and reflect it in list display (886ms) + ✔ should generate a temp code and support preview before confirmation (269ms) + ✔ should only change use_status when unbinding (589ms) + ✔ should allow warehouse side to save and get policy config on a contract (924ms) + ✔ should reject unsupported policy config fields on a contract (269ms) + 1) should allow warehouse side to save, update and delete api config on a contract + ✔ should reject sign when counterparty is missing (61ms) + ✔ should reject unbind when no target relation is provided (117ms) + + + 8 passing (4s) + 1 failing + + 1) test/app/controller/system.setting.storeWarehouse.test.js + should allow warehouse side to save, update and delete api config on a contract: + + AssertionError [ERR_ASSERTION]: Expected values to be strictly equal: ++ actual - expected + ++ 'failure' +- 'success' + + + expected - actual + + -failure + +success + + at Context. (test\app\controller\system.setting.storeWarehouse.test.js:300:14) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + + + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/056-mirror.stderr.log b/test_reports/tmp/056-mirror.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/056-mirror.stdout.log b/test_reports/tmp/056-mirror.stdout.log new file mode 100644 index 0000000..91394b5 --- /dev/null +++ b/test_reports/tmp/056-mirror.stdout.log @@ -0,0 +1,26 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (1ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (11ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/system.stock.warehouse.getStockDetail.test.js + ✔ should return stockItem, storageList and pagination for a valid stock_id (99ms) + ✔ should respect pagination parameters (93ms) + ✔ should return error when stock_id is empty + ✔ should return error when stock_id does not exist (61ms) + ✔ should return empty storageList when stock exists but has no storage records (91ms) + ✔ should merge storageList by space_id when group_by_batch is not provided (default) (184ms) + ✔ should merge storageList by space_id when group_by_batch=false (explicit) (182ms) + ✔ should return independent records per batch when group_by_batch=true (181ms) + + + 8 passing (2s) + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/057-mirror.stderr.log b/test_reports/tmp/057-mirror.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/057-mirror.stdout.log b/test_reports/tmp/057-mirror.stdout.log new file mode 100644 index 0000000..45a1a64 --- /dev/null +++ b/test_reports/tmp/057-mirror.stdout.log @@ -0,0 +1,19 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.stock.warehouse.namespaced.test.js + ✔ should query stock warehouse list via namespaced method (1235ms) + + + 1 passing (1s) + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/058-mirror.stderr.log b/test_reports/tmp/058-mirror.stderr.log new file mode 100644 index 0000000..70c9911 --- /dev/null +++ b/test_reports/tmp/058-mirror.stderr.log @@ -0,0 +1,7 @@ +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.storage.delivery.module.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} diff --git a/test_reports/tmp/058-mirror.stdout.log b/test_reports/tmp/058-mirror.stdout.log new file mode 100644 index 0000000..978829e --- /dev/null +++ b/test_reports/tmp/058-mirror.stdout.log @@ -0,0 +1,78 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.storage.delivery.module.test.js + 1) should return delivery list via storage.stockout.list + 2) should return placeholder failure via storage.stockout.toOrder + 3) should return item list via storage.stockout.listItems + ✔ should not expose removed storage.entry detail methods (1219ms) + + + 1 passing (5s) + 3 failing + + 1) test/app/controller/system.storage.delivery.module.test.js + should return delivery list via storage.stockout.list: + + AssertionError [ERR_ASSERTION]: Expected values to be strictly equal: ++ actual - expected + ++ 'failure' +- 'success' + + + expected - actual + + -failure + +success + + at Context. (test\app\controller\system.storage.delivery.module.test.js:171:12) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + + 2) test/app/controller/system.storage.delivery.module.test.js + should return placeholder failure via storage.stockout.toOrder: + + AssertionError [ERR_ASSERTION]: Expected values to be strictly equal: ++ actual - expected + ++ 'failure' +- 'success' + + + expected - actual + + -failure + +success + + at getFirstDelivery (test\app\controller\system.storage.delivery.module.test.js:95:10) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + at async Context. (test\app\controller\system.storage.delivery.module.test.js:184:22) + + 3) test/app/controller/system.storage.delivery.module.test.js + should return item list via storage.stockout.listItems: + + AssertionError [ERR_ASSERTION]: Expected values to be strictly equal: ++ actual - expected + ++ 'failure' +- 'success' + + + expected - actual + + -failure + +success + + at getFirstDelivery (test\app\controller\system.storage.delivery.module.test.js:95:10) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + at async Context. (test\app\controller\system.storage.delivery.module.test.js:210:22) + + + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/059-mirror.stderr.log b/test_reports/tmp/059-mirror.stderr.log new file mode 100644 index 0000000..cd8595e --- /dev/null +++ b/test_reports/tmp/059-mirror.stderr.log @@ -0,0 +1,7 @@ +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.storage.entry.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} diff --git a/test_reports/tmp/059-mirror.stdout.log b/test_reports/tmp/059-mirror.stdout.log new file mode 100644 index 0000000..9006bc2 --- /dev/null +++ b/test_reports/tmp/059-mirror.stdout.log @@ -0,0 +1,70 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.storage.entry.test.js + ✔ should query entry list (1120ms) + 1) should create entry and run detail lifecycle then cancel + 2) should complete entry after adding detail + 3) should reject invalid params for create/get/addDetail + + + 1 passing (4s) + 3 failing + + 1) test/app/controller/system.storage.entry.test.js + should create entry and run detail lifecycle then cancel: + + AssertionError [ERR_ASSERTION]: Expected values to be strictly equal: + +500 !== 200 + + + expected - actual + + -500 + +200 + + at Context. (test\app\controller\system.storage.entry.test.js:109:12) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + + 2) test/app/controller/system.storage.entry.test.js + should complete entry after adding detail: + + AssertionError [ERR_ASSERTION]: Expected values to be strictly equal: + +500 !== 200 + + + expected - actual + + -500 + +200 + + at Context. (test\app\controller\system.storage.entry.test.js:181:12) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + + 3) test/app/controller/system.storage.entry.test.js + should reject invalid params for create/get/addDetail: + + AssertionError [ERR_ASSERTION]: Expected values to be strictly equal: + +500 !== 200 + + + expected - actual + + -500 + +200 + + at Context. (test\app\controller\system.storage.entry.test.js:217:12) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + + + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/060-mirror.stderr.log b/test_reports/tmp/060-mirror.stderr.log new file mode 100644 index 0000000..718d8eb --- /dev/null +++ b/test_reports/tmp/060-mirror.stderr.log @@ -0,0 +1,53 @@ + + Exception during run: Error: Cannot find module './tencent-cloud' +Require stack: +- D:\wms\worktrees\deploy-20260409155126\config\config.default.js +- D:\wms\worktrees\deploy-20260409155126\database\config.js +- D:\wms\worktrees\deploy-20260409155126\test\app\controller\system.storage.inventory.matchPutaway.test.js + at Module._resolveFilename (node:internal/modules/cjs/loader:1456:15) + at defaultResolveImpl (node:internal/modules/cjs/loader:1066:19) + at resolveForCJSWithHooks (node:internal/modules/cjs/loader:1071:22) + at Module._load (node:internal/modules/cjs/loader:1242:25) + at wrapModuleLoad (node:internal/modules/cjs/loader:255:19) + at Module.require (node:internal/modules/cjs/loader:1556:12) + at require (node:internal/modules/helpers:152:16) + at module.exports (D:\wms\worktrees\deploy-20260409155126\config\config.default.js:21:30) + at loadEggConfig (D:\wms\worktrees\deploy-20260409155126\database\config.js:36:7) + at Object. (D:\wms\worktrees\deploy-20260409155126\database\config.js:56:23) + at Module._compile (node:internal/modules/cjs/loader:1812:14) + at Object..js (node:internal/modules/cjs/loader:1943:10) + at Module.load (node:internal/modules/cjs/loader:1533:32) + at Module._load (node:internal/modules/cjs/loader:1335:12) + at wrapModuleLoad (node:internal/modules/cjs/loader:255:19) + at Module.require (node:internal/modules/cjs/loader:1556:12) + at require (node:internal/modules/helpers:152:16) + at Object. (D:\wms\worktrees\deploy-20260409155126\test\app\controller\system.storage.inventory.matchPutaway.test.js:16:18) + at Module._compile (node:internal/modules/cjs/loader:1812:14) + at Object..js (node:internal/modules/cjs/loader:1943:10) + at Module.load (node:internal/modules/cjs/loader:1533:32) + at Module._load (node:internal/modules/cjs/loader:1335:12) + at wrapModuleLoad (node:internal/modules/cjs/loader:255:19) + at loadCJSModuleWithModuleLoad (node:internal/modules/esm/translators:328:3) + at ModuleWrap. (node:internal/modules/esm/translators:233:7) + at ModuleJob.run (node:internal/modules/esm/module_job:430:25) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:661:26) + at async formattedImport (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:9:14) + at async exports.requireOrImport (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:42:28) + at async exports.loadFilesAsync (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:100:20) + at async singleRun (D:\wms\node_modules\mocha\lib\cli\run-helpers.js:162:3) + at async exports.handler (D:\wms\node_modules\mocha\lib\cli\run.js:375:5) { + code: 'MODULE_NOT_FOUND', + requireStack: [ + 'D:\\wms\\worktrees\\deploy-20260409155126\\config\\config.default.js', + 'D:\\wms\\worktrees\\deploy-20260409155126\\database\\config.js', + 'D:\\wms\\worktrees\\deploy-20260409155126\\test\\app\\controller\\system.storage.inventory.matchPutaway.test.js' + ] +} +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.storage.inventory.matchPutaway.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} diff --git a/test_reports/tmp/060-mirror.stdout.log b/test_reports/tmp/060-mirror.stdout.log new file mode 100644 index 0000000..5f3fb2a --- /dev/null +++ b/test_reports/tmp/060-mirror.stdout.log @@ -0,0 +1,7 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) diff --git a/test_reports/tmp/061-mirror.stderr.log b/test_reports/tmp/061-mirror.stderr.log new file mode 100644 index 0000000..6e2b482 --- /dev/null +++ b/test_reports/tmp/061-mirror.stderr.log @@ -0,0 +1,53 @@ + + Exception during run: Error: Cannot find module './tencent-cloud' +Require stack: +- D:\wms\worktrees\deploy-20260409155126\config\config.default.js +- D:\wms\worktrees\deploy-20260409155126\database\config.js +- D:\wms\worktrees\deploy-20260409155126\test\app\controller\system.storage.inventory.quickPutaway.test.js + at Module._resolveFilename (node:internal/modules/cjs/loader:1456:15) + at defaultResolveImpl (node:internal/modules/cjs/loader:1066:19) + at resolveForCJSWithHooks (node:internal/modules/cjs/loader:1071:22) + at Module._load (node:internal/modules/cjs/loader:1242:25) + at wrapModuleLoad (node:internal/modules/cjs/loader:255:19) + at Module.require (node:internal/modules/cjs/loader:1556:12) + at require (node:internal/modules/helpers:152:16) + at module.exports (D:\wms\worktrees\deploy-20260409155126\config\config.default.js:21:30) + at loadEggConfig (D:\wms\worktrees\deploy-20260409155126\database\config.js:36:7) + at Object. (D:\wms\worktrees\deploy-20260409155126\database\config.js:56:23) + at Module._compile (node:internal/modules/cjs/loader:1812:14) + at Object..js (node:internal/modules/cjs/loader:1943:10) + at Module.load (node:internal/modules/cjs/loader:1533:32) + at Module._load (node:internal/modules/cjs/loader:1335:12) + at wrapModuleLoad (node:internal/modules/cjs/loader:255:19) + at Module.require (node:internal/modules/cjs/loader:1556:12) + at require (node:internal/modules/helpers:152:16) + at Object. (D:\wms\worktrees\deploy-20260409155126\test\app\controller\system.storage.inventory.quickPutaway.test.js:16:18) + at Module._compile (node:internal/modules/cjs/loader:1812:14) + at Object..js (node:internal/modules/cjs/loader:1943:10) + at Module.load (node:internal/modules/cjs/loader:1533:32) + at Module._load (node:internal/modules/cjs/loader:1335:12) + at wrapModuleLoad (node:internal/modules/cjs/loader:255:19) + at loadCJSModuleWithModuleLoad (node:internal/modules/esm/translators:328:3) + at ModuleWrap. (node:internal/modules/esm/translators:233:7) + at ModuleJob.run (node:internal/modules/esm/module_job:430:25) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:661:26) + at async formattedImport (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:9:14) + at async exports.requireOrImport (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:42:28) + at async exports.loadFilesAsync (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:100:20) + at async singleRun (D:\wms\node_modules\mocha\lib\cli\run-helpers.js:162:3) + at async exports.handler (D:\wms\node_modules\mocha\lib\cli\run.js:375:5) { + code: 'MODULE_NOT_FOUND', + requireStack: [ + 'D:\\wms\\worktrees\\deploy-20260409155126\\config\\config.default.js', + 'D:\\wms\\worktrees\\deploy-20260409155126\\database\\config.js', + 'D:\\wms\\worktrees\\deploy-20260409155126\\test\\app\\controller\\system.storage.inventory.quickPutaway.test.js' + ] +} +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.storage.inventory.quickPutaway.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} diff --git a/test_reports/tmp/061-mirror.stdout.log b/test_reports/tmp/061-mirror.stdout.log new file mode 100644 index 0000000..f58fd10 --- /dev/null +++ b/test_reports/tmp/061-mirror.stdout.log @@ -0,0 +1,7 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) diff --git a/test_reports/tmp/062-mirror.stderr.log b/test_reports/tmp/062-mirror.stderr.log new file mode 100644 index 0000000..1d81802 --- /dev/null +++ b/test_reports/tmp/062-mirror.stderr.log @@ -0,0 +1,7 @@ +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.storage.receiving.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} diff --git a/test_reports/tmp/062-mirror.stdout.log b/test_reports/tmp/062-mirror.stdout.log new file mode 100644 index 0000000..cf5718f --- /dev/null +++ b/test_reports/tmp/062-mirror.stdout.log @@ -0,0 +1,39 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/system.storage.receiving.test.js + ✔ should query receiving list (1108ms) + ✔ should query receiving detail when list has records (1254ms) + 1) should bind store to receiving and reject rebinding when owner already exists + ✔ should reject bindStore when receiving is cancelled (2100ms) + ✔ should bind and rebind system product for a receiving detail (2642ms) + ✔ should create and then batch cancel receiving order (1323ms) + ✔ should generate unique receiving numbers under concurrent create requests (1364ms) + ✔ should include same-day records when created_at uses daterange filter (1353ms) + ✔ should reject getReceivingDetail with invalid id (1035ms) + ✔ should reject create with invalid loading_method enum (1061ms) + ✔ should reject batchCancelReceiving with nonexistent ids (1044ms) + + + 10 passing (15s) + 1 failing + + 1) test/app/controller/system.storage.receiving.test.js + should bind store to receiving and reject rebinding when owner already exists: + TypeError: fetch failed + + Caused by: Error: read ECONNRESET + at TCP.onStreamRead (node:internal/stream_base_commons:216:20) + + + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/063-mirror.stderr.log b/test_reports/tmp/063-mirror.stderr.log new file mode 100644 index 0000000..69b9e0c --- /dev/null +++ b/test_reports/tmp/063-mirror.stderr.log @@ -0,0 +1,53 @@ + + Exception during run: Error: Cannot find module './tencent-cloud' +Require stack: +- D:\wms\worktrees\deploy-20260409155126\config\config.default.js +- D:\wms\worktrees\deploy-20260409155126\database\config.js +- D:\wms\worktrees\deploy-20260409155126\test\app\controller\system.storage.transaction.test.js + at Module._resolveFilename (node:internal/modules/cjs/loader:1456:15) + at defaultResolveImpl (node:internal/modules/cjs/loader:1066:19) + at resolveForCJSWithHooks (node:internal/modules/cjs/loader:1071:22) + at Module._load (node:internal/modules/cjs/loader:1242:25) + at wrapModuleLoad (node:internal/modules/cjs/loader:255:19) + at Module.require (node:internal/modules/cjs/loader:1556:12) + at require (node:internal/modules/helpers:152:16) + at module.exports (D:\wms\worktrees\deploy-20260409155126\config\config.default.js:21:30) + at loadEggConfig (D:\wms\worktrees\deploy-20260409155126\database\config.js:36:7) + at Object. (D:\wms\worktrees\deploy-20260409155126\database\config.js:56:23) + at Module._compile (node:internal/modules/cjs/loader:1812:14) + at Object..js (node:internal/modules/cjs/loader:1943:10) + at Module.load (node:internal/modules/cjs/loader:1533:32) + at Module._load (node:internal/modules/cjs/loader:1335:12) + at wrapModuleLoad (node:internal/modules/cjs/loader:255:19) + at Module.require (node:internal/modules/cjs/loader:1556:12) + at require (node:internal/modules/helpers:152:16) + at Object. (D:\wms\worktrees\deploy-20260409155126\test\app\controller\system.storage.transaction.test.js:16:18) + at Module._compile (node:internal/modules/cjs/loader:1812:14) + at Object..js (node:internal/modules/cjs/loader:1943:10) + at Module.load (node:internal/modules/cjs/loader:1533:32) + at Module._load (node:internal/modules/cjs/loader:1335:12) + at wrapModuleLoad (node:internal/modules/cjs/loader:255:19) + at loadCJSModuleWithModuleLoad (node:internal/modules/esm/translators:328:3) + at ModuleWrap. (node:internal/modules/esm/translators:233:7) + at ModuleJob.run (node:internal/modules/esm/module_job:430:25) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:661:26) + at async formattedImport (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:9:14) + at async exports.requireOrImport (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:42:28) + at async exports.loadFilesAsync (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:100:20) + at async singleRun (D:\wms\node_modules\mocha\lib\cli\run-helpers.js:162:3) + at async exports.handler (D:\wms\node_modules\mocha\lib\cli\run.js:375:5) { + code: 'MODULE_NOT_FOUND', + requireStack: [ + 'D:\\wms\\worktrees\\deploy-20260409155126\\config\\config.default.js', + 'D:\\wms\\worktrees\\deploy-20260409155126\\database\\config.js', + 'D:\\wms\\worktrees\\deploy-20260409155126\\test\\app\\controller\\system.storage.transaction.test.js' + ] +} +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/controller/system.storage.transaction.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} diff --git a/test_reports/tmp/063-mirror.stdout.log b/test_reports/tmp/063-mirror.stdout.log new file mode 100644 index 0000000..8584990 --- /dev/null +++ b/test_reports/tmp/063-mirror.stdout.log @@ -0,0 +1,7 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) diff --git a/test_reports/tmp/064-mirror.stderr.log b/test_reports/tmp/064-mirror.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/064-mirror.stdout.log b/test_reports/tmp/064-mirror.stdout.log new file mode 100644 index 0000000..cd52089 --- /dev/null +++ b/test_reports/tmp/064-mirror.stdout.log @@ -0,0 +1,32 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (3ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.storeWarehouse.test.js + ✔ should expose standalone storeWarehouse.store.list (128ms) + ✔ should not expose removed legacy storeWarehouse.* methods + ✔ should not expose removed setting.storeWarehouse.store.list alias + ✔ should not expose removed setting.store_warehouse.* compatibility methods + ✔ should expose standalone storeWarehouse.store.sign parameter validation (60ms) + ✔ should expose standalone storeWarehouse.store.unbind parameter validation (114ms) + ✔ should expose standalone storeWarehouse.store.rename parameter validation (121ms) + ✔ should expose standalone storeWarehouse.store.adjustPrintQuantity with auth or validation response (121ms) + ✔ should expose standalone storeWarehouse.store.getPolicyConfig parameter validation (62ms) + ✔ should expose standalone storeWarehouse.store.getPolicyConfigFields as a metadata list + ✔ should expose standalone storeWarehouse.store.savePolicyConfig parameter validation (112ms) + ✔ should expose standalone storeWarehouse.store.saveApiConfig parameter validation (125ms) + ✔ should expose standalone storeWarehouse.store.deleteQimenConfig parameter validation (115ms) + ✔ should expose standalone storeWarehouse.store.listApiConfig parameter validation (59ms) + + + 14 passing (2s) + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/065-mirror.stderr.log b/test_reports/tmp/065-mirror.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/065-mirror.stdout.log b/test_reports/tmp/065-mirror.stdout.log new file mode 100644 index 0000000..3d870e3 --- /dev/null +++ b/test_reports/tmp/065-mirror.stdout.log @@ -0,0 +1,19 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (11ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.user.changeRole.test.js + ✔ should switch role via user.changeRole and persist response (1809ms) + + + 1 passing (2s) + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/066-mirror.stderr.log b/test_reports/tmp/066-mirror.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/066-mirror.stdout.log b/test_reports/tmp/066-mirror.stdout.log new file mode 100644 index 0000000..6a5560f --- /dev/null +++ b/test_reports/tmp/066-mirror.stdout.log @@ -0,0 +1,19 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (1ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.user.getLoginWechatCode.test.js + ✔ should return login code without Authorization token (141ms) + + + 1 passing (146ms) + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/067-mirror.stderr.log b/test_reports/tmp/067-mirror.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/067-mirror.stdout.log b/test_reports/tmp/067-mirror.stdout.log new file mode 100644 index 0000000..66d71e6 --- /dev/null +++ b/test_reports/tmp/067-mirror.stdout.log @@ -0,0 +1,19 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.user.info.test.js + ✔ should call user.info with bearer token (81ms) + + + 1 passing (85ms) + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/068-mirror.stderr.log b/test_reports/tmp/068-mirror.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/068-mirror.stdout.log b/test_reports/tmp/068-mirror.stdout.log new file mode 100644 index 0000000..00221a2 --- /dev/null +++ b/test_reports/tmp/068-mirror.stdout.log @@ -0,0 +1,19 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/controller/system.user.info.web.test.js + ✔ should call user.info with platform=web project=all and persist response (84ms) + + + 1 passing (89ms) + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/069-mirror.stderr.log b/test_reports/tmp/069-mirror.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/069-mirror.stdout.log b/test_reports/tmp/069-mirror.stdout.log new file mode 100644 index 0000000..27247bb --- /dev/null +++ b/test_reports/tmp/069-mirror.stdout.log @@ -0,0 +1,21 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (1ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.user.login.test.js + ✔ should get token from cache or login method + ✔ should persist token cache file + ✔ user.login should return token only (835ms) + + + 3 passing (842ms) + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/070-mirror.stderr.log b/test_reports/tmp/070-mirror.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/070-mirror.stdout.log b/test_reports/tmp/070-mirror.stdout.log new file mode 100644 index 0000000..88c6312 --- /dev/null +++ b/test_reports/tmp/070-mirror.stdout.log @@ -0,0 +1,23 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/controller/system.user.loginByCode.test.js + - should login successfully when code is valid + ✔ should fail when code is missing + ✔ should fail when code does not exist + ✔ should fail when code format is valid but not matched + + + 3 passing (91ms) + 1 pending + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/071-mirror.stderr.log b/test_reports/tmp/071-mirror.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/071-mirror.stdout.log b/test_reports/tmp/071-mirror.stdout.log new file mode 100644 index 0000000..989ec95 --- /dev/null +++ b/test_reports/tmp/071-mirror.stdout.log @@ -0,0 +1,22 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (11ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/service/systemMethods/storeWarehouse/store.test.js + ✔ should copy payload before calling list + ✔ should copy payload before calling sign + ✔ should keep the failure fallback for missing list method + ✔ should keep the failure fallback for missing sign method + + + 4 passing (6ms) + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/072-mirror.stderr.log b/test_reports/tmp/072-mirror.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/072-mirror.stdout.log b/test_reports/tmp/072-mirror.stdout.log new file mode 100644 index 0000000..ba83883 --- /dev/null +++ b/test_reports/tmp/072-mirror.stdout.log @@ -0,0 +1,21 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (1ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (11ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/service/systemMethods/warehouse.auth.test.js + ✔ should deny getAreaRacks when explicit api permission is missing + ✔ should allow getAreaRacks when user has wildcard permissions + ✔ should allow getAreaRacks when permission payload contains matching path or id + + + 3 passing (5ms) + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/073-mirror.stderr.log b/test_reports/tmp/073-mirror.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/073-mirror.stdout.log b/test_reports/tmp/073-mirror.stdout.log new file mode 100644 index 0000000..d167eab --- /dev/null +++ b/test_reports/tmp/073-mirror.stdout.log @@ -0,0 +1,21 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (1ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (4ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/service/systems/auth.user.bindWechatCacheExpiry.test.js + ✔ should generate pending code with fixed 60s ttl and keep same code without extending + ✔ should return scanned status when scan key exists + ✔ should rotate code when forceNewCode is enabled + + + 3 passing (5ms) + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/074-mirror.stderr.log b/test_reports/tmp/074-mirror.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/074-mirror.stdout.log b/test_reports/tmp/074-mirror.stdout.log new file mode 100644 index 0000000..7780a5f --- /dev/null +++ b/test_reports/tmp/074-mirror.stdout.log @@ -0,0 +1,22 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/service/systems/auth.user.loginWechatCode.test.js + ✔ should generate client code and login code when client code is missing + ✔ should refresh login code after long poll when client code is provided + ✔ should fail when provided client code format is invalid + ✔ should resolve login event and parse ye4s user id from redis message + + + 4 passing (7ms) + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/075-mirror.stderr.log b/test_reports/tmp/075-mirror.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/075-mirror.stdout.log b/test_reports/tmp/075-mirror.stdout.log new file mode 100644 index 0000000..5af9053 --- /dev/null +++ b/test_reports/tmp/075-mirror.stdout.log @@ -0,0 +1,24 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (15ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/service/systems/excel.test.js + ✔ should generate workbook buffer and parse rows back + ✔ should normalize duplicated or empty headers when parsing + ✔ should generate excel and upload to custom directory + ✔ should honor skipHeader when object rows are used + ✔ should support embedded images when url is a data URL + ✔ should generate workbook with embedded image previews when image config exists + + + 6 passing (69ms) + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/076-mirror.stderr.log b/test_reports/tmp/076-mirror.stderr.log new file mode 100644 index 0000000..e31107a --- /dev/null +++ b/test_reports/tmp/076-mirror.stderr.log @@ -0,0 +1,32 @@ + + Exception during run: Error: ENOENT: no such file or directory, open 'D:\wms\worktrees\deploy-20260409155126\temp\cp.png' + at Object.openSync (node:fs:560:18) + at Object.readFileSync (node:fs:444:35) + at Object. (D:\wms\worktrees\deploy-20260409155126\test\app\service\systems\license_plate.test.js:9:31) + at Module._compile (node:internal/modules/cjs/loader:1812:14) + at Object..js (node:internal/modules/cjs/loader:1943:10) + at Module.load (node:internal/modules/cjs/loader:1533:32) + at Module._load (node:internal/modules/cjs/loader:1335:12) + at wrapModuleLoad (node:internal/modules/cjs/loader:255:19) + at loadCJSModuleWithModuleLoad (node:internal/modules/esm/translators:328:3) + at ModuleWrap. (node:internal/modules/esm/translators:233:7) + at ModuleJob.run (node:internal/modules/esm/module_job:430:25) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:661:26) + at async formattedImport (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:9:14) + at async exports.requireOrImport (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:42:28) + at async exports.loadFilesAsync (D:\wms\node_modules\mocha\lib\nodejs\esm-utils.js:100:20) + at async singleRun (D:\wms\node_modules\mocha\lib\cli\run-helpers.js:162:3) + at async exports.handler (D:\wms\node_modules\mocha\lib\cli\run.js:375:5) { + errno: -4058, + code: 'ENOENT', + syscall: 'open', + path: 'D:\\wms\\worktrees\\deploy-20260409155126\\temp\\cp.png' +} +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/service/systems/license_plate.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} diff --git a/test_reports/tmp/076-mirror.stdout.log b/test_reports/tmp/076-mirror.stdout.log new file mode 100644 index 0000000..f3662c0 --- /dev/null +++ b/test_reports/tmp/076-mirror.stdout.log @@ -0,0 +1,7 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (1ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (2ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) diff --git a/test_reports/tmp/077-mirror.stderr.log b/test_reports/tmp/077-mirror.stderr.log new file mode 100644 index 0000000..1943131 --- /dev/null +++ b/test_reports/tmp/077-mirror.stderr.log @@ -0,0 +1,7 @@ +ForkError: D:\wms\node_modules\mocha\bin\_mocha --exit --timeout=60000 --reporter=D:\wms\node_modules\mochawesome-with-mocha\src\mochawesome.js --reporter-options=reportDir=node_modules/.mochawesome-reports --require=D:\wms\node_modules\egg-mock\register.js test/app/service/systems/notice.test.js exit with code 1 + at ChildProcess. (D:\wms\node_modules\egg-bin\dist\cmd\base.js:98:33) + at Object.onceWrapper (node:events:623:26) + at ChildProcess.emit (node:events:508:28) + at ChildProcess._handle.onexit (node:internal/child_process:294:12) { + code: 1 +} diff --git a/test_reports/tmp/077-mirror.stdout.log b/test_reports/tmp/077-mirror.stdout.log new file mode 100644 index 0000000..f40ce47 --- /dev/null +++ b/test_reports/tmp/077-mirror.stdout.log @@ -0,0 +1,54 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/service/systems/notice.test.js + 1) should normalize payload and send only matching webhooks + ✔ should enrich payload with store info from cache before querying database + ✔ should load store info from database and cache it when cache is empty + ✔ should send to both warehouse and owner webhooks when events match or are set to all + ✔ should only send up to the configured webhook limit + ✔ should require url for image or file message + ✔ should require warehouseId but allow empty ownerId + ✔ should retry failed webhooks three times and persist final failures + ✔ should reject sending unregistered event + ✔ should reject dotted or numeric-leading event names + ✔ should send wecom webhook as enterprise wechat direct message + ✔ should expose available webhook events and reject unsupported ones + + + 11 passing (12ms) + 1 failing + + 1) test/app/service/systems/notice.test.js + should normalize payload and send only matching webhooks: + + AssertionError [ERR_ASSERTION]: Expected values to be strictly equal: ++ actual - expected + ++ 100000 +- 1000000 + + + expected - actual + + -100000 + +1000000 + + at Object.findAll (test\app\service\systems\notice.test.js:34:20) + at D:\wms\worktrees\deploy-20260409155126\app\service\systems\notice\index.js:796:43 + at Array.map () + at NoticeService.findMatchedWebhooks (app\service\systems\notice\index.js:786:62) + at NoticeService.send (app\service\systems\notice\index.js:826:33) + at async Context. (test\app\service\systems\notice.test.js:55:20) + + + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/078-mirror.stderr.log b/test_reports/tmp/078-mirror.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/078-mirror.stdout.log b/test_reports/tmp/078-mirror.stdout.log new file mode 100644 index 0000000..0e1bbd9 --- /dev/null +++ b/test_reports/tmp/078-mirror.stdout.log @@ -0,0 +1,25 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (12ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (3ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/service/systems/stock_store.stockWarehouse.conditions.test.js + ✔ should build Sequelize condition for all supported operators + ✔ should normalize boolean, number and text values + ✔ should support date and daterange condition extraction + ✔ should parse where and return list with barcode/prohibited branches + ✔ should short-circuit when barcode has no matched stock ids + ✔ should ignore empty where values and fallback invalid sort field + ✔ should return failure reason when where deconstruction is invalid + + + 7 passing (21ms) + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/079-mirror.stderr.log b/test_reports/tmp/079-mirror.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/079-mirror.stdout.log b/test_reports/tmp/079-mirror.stdout.log new file mode 100644 index 0000000..48bd49f --- /dev/null +++ b/test_reports/tmp/079-mirror.stdout.log @@ -0,0 +1,19 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (11ms) +[egg-ts-helper] create typings\config\plugin.d.ts (0ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/service/systems/stock_transaction.create.test.js + ✔ should create stock transaction with snapshot fields + + + 1 passing (4ms) + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/080-mirror.stderr.log b/test_reports/tmp/080-mirror.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/080-mirror.stdout.log b/test_reports/tmp/080-mirror.stdout.log new file mode 100644 index 0000000..a2551a7 --- /dev/null +++ b/test_reports/tmp/080-mirror.stdout.log @@ -0,0 +1,22 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (11ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/service/systems/storage.entry.cancel.test.js + ✔ should cancel single entry order by id + ✔ should cancel batch entry orders by ids + ✔ should reject empty or illegal ids + ✔ should reject batch cancel when any order is missing or completed + + + 4 passing (7ms) + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/081-mirror.stderr.log b/test_reports/tmp/081-mirror.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/081-mirror.stdout.log b/test_reports/tmp/081-mirror.stdout.log new file mode 100644 index 0000000..1216205 --- /dev/null +++ b/test_reports/tmp/081-mirror.stdout.log @@ -0,0 +1,27 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (2ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (11ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/service/systems/storage.receiving.report.test.js + ✔ should build and upload completion excel in a single sheet with one preview column + ✔ should send receiving completed notice with the unified event payload + ✔ should show only license plate for truck in notice content and report main rows + ✔ should show only tracking number for express in notice content and report main rows + ✔ should hide both contact fields for other delivery methods + ✔ should support nested notice.index service shape from Egg loader + ✔ should trigger text notice before excel and then send file notice after upload succeeds + ✔ should only send text notice when completion excel generation fails + ✔ should still complete and notify when detail has no matched product or completeness fields + + + 9 passing (23ms) + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/082-mirror.stderr.log b/test_reports/tmp/082-mirror.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/082-mirror.stdout.log b/test_reports/tmp/082-mirror.stdout.log new file mode 100644 index 0000000..b73a875 --- /dev/null +++ b/test_reports/tmp/082-mirror.stdout.log @@ -0,0 +1,20 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (13ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (0ms) + + + test/app/service/systems/store_warehouse.adjustPrintQuantity.test.js + ✔ should require reason when manually adjusting print quantity + ✔ should overwrite target balance instead of incrementing it when manually adjusting print quantity + + + 2 passing (5ms) + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/test_reports/tmp/083-mirror.stderr.log b/test_reports/tmp/083-mirror.stderr.log new file mode 100644 index 0000000..e69de29 diff --git a/test_reports/tmp/083-mirror.stdout.log b/test_reports/tmp/083-mirror.stdout.log new file mode 100644 index 0000000..9959df8 --- /dev/null +++ b/test_reports/tmp/083-mirror.stdout.log @@ -0,0 +1,20 @@ +[egg-ts-helper] create typings\app\extend\application.d.ts (2ms) +[egg-ts-helper] create typings\app\controller\index.d.ts (1ms) +[egg-ts-helper] create typings\app\model\index.d.ts (3ms) +[egg-ts-helper] create typings\config\index.d.ts (11ms) +[egg-ts-helper] create typings\config\plugin.d.ts (1ms) +[egg-ts-helper] create typings\app\service\index.d.ts (4ms) +[egg-ts-helper] create typings\app\index.d.ts (1ms) + + + test/app/service/systems/upload.test.js + ✔ should prefer tencent cloud auth config while keeping COS upload parameters + ✔ should create file reference with warehouse and creator when saving upload record + + + 2 passing (5ms) + +[mochawesome] Report JSON saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.json + +[mochawesome] Report HTML saved to D:\wms\worktrees\deploy-20260409155126\node_modules\.mochawesome-reports\mochawesome.html + diff --git a/worktrees/deploy-20260409155126 b/worktrees/deploy-20260409155126 new file mode 160000 index 0000000..69e992b --- /dev/null +++ b/worktrees/deploy-20260409155126 @@ -0,0 +1 @@ +Subproject commit 69e992bf9dc1242f5c35b3aa5bdddcc716274045 From 18580144c67c587d0b4e579aa445271794069f7e Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sat, 11 Apr 2026 17:09:59 +0800 Subject: [PATCH 026/550] ok --- .github/agents/开发.agent.md | 121 +++++++++++++++++++++++++++++++++++ 1 file changed, 121 insertions(+) diff --git a/.github/agents/开发.agent.md b/.github/agents/开发.agent.md index 878dcf6..b88dd9d 100644 --- a/.github/agents/开发.agent.md +++ b/.github/agents/开发.agent.md @@ -119,3 +119,124 @@ node .\script\tmp-struct-system-params.cjs - 改代码后必须跑相关测试验证 - 涉及接口变更必须委派 `wms-doc-agent` 同步文档,本 agent 不直接修改文档文件 - 除了json,其他字符串输出必须使用模板字符串,必要时分行保持可读性 +- --- +name: wms-dev-agent +description: "Use when the user asks about 开发、改代码、修 bug、调试、接口定位、method routing、where 规范、权限映射、Egg.js service 分层。专用于 WMS 通用开发与代码实现。" +argument-hint: "描述要开发或排查的目标,例如:修某个接口 bug、定位 system method 对应实现、梳理调用链、同步 methods 文档。" +tools: ['read', 'search', 'edit', 'execute', 'todo'] +model: GPT-5.3-Codex (copilot) +--- + +# WMS 开发代理(`wms-dev-agent`) + +## 适用范围 + +- 项目根目录:`D:\wms` +- 主要开发目录:`app/`、`methods/`、`docs/` +- 适用于 Egg.js 业务开发、接口联调与文档同步;如重点是测试设计、回归验证、TDD,请转给 `wms-test-agent` + +## 何时必须使用本 Agent + +出现以下任一诉求时,必须使用 `wms-dev-agent`: + +- 改代码 / 修 bug / 重构 / 性能优化 +- 定位 `/system` / `/qimen` method 映射关系 +- 排查 `where` 规则、权限映射、分层职责问题 +- 分析 `app.js` / `app/extend/application.js` / `systemMethods` / `systems` 调用链 +- 如诉求重点是测试设计、回归验证、TDD,请委派给 `wms-test-agent` +- 如涉及文档同步,委派给 `wms-doc-agent` + +## 开发规则 + +1. **先定位后修改**:先找 `controller / systemMethods / systems / model` 的实际链路 +2. **分层约定必须保持**: + - `systemMethods` 只保留出口包装层 + - 业务逻辑统一下沉到 `systems` +3. **如诉求重点是测试设计、补回归、接口验证或 TDD,委派给** `wms-test-agent` +4. **禁止直接修改文档文件**:`methods/*.json`、`methods/changes/*.json`、`docs/*.md` 的所有新增与修改必须委派给 `wms-doc-agent` 完成,`wms-dev-agent` 只负责代码文件(`app/`、`config/`、`database/`、`test/`) +5. **where 规则统一走** `app/service/main.js` 的 `prepareWhereContext(data, options)` +6. **新建接口时,必须先判断是通用接口还是需授权接口**: + - 先明确 `isNeedAuth`,代码实现完成后委派 `wms-doc-agent` 同步 `methods/system.json` 并追加变更记录 + - 若为需授权接口,必须优先通过既有同步流程 / 标准方式补齐权限记录(如 `wms_permission`),必要时使用: + - `npm run permission:sync:system-api -- --dry-run` + - `npm run permission:sync:system-api` + - **绝对不能直接扩大任何角色的授权范围**,不得直接改 `wms_role.permissions` 或其他角色授权绑定来“顺手放开权限” +7. **必须做验证**:改代码后跑相关检查,确认响应结构与文档一致 +8. **所有修改的函数必须要有 JSDOC 注释**,必要时补充说明参数、返回值、错误码等信息,如果修改的方法中没有注释,必须补充完整的 JSDOC 注释后再提交,严禁入参与返回值都没有注释的函数存在于代码中,非本次修改的函数如果没有注释,除非有明确的理由,否则也必须补充完整的 JSDOC 注释后再提交 +9. **method入参必须解构再传入service **,禁止直接把 method 入参对象传给 service,必须先在 method 层解构出具体参数,再传给 service,保持层与层之间的清晰边界和职责分离,如果拆解参数过多,可以先在 controller 层做多步骤访问service方法处理,但是必须在service层处理,禁止在method层调用method层。 +10. **禁止method入口直接调用model层**,必须先调用service层,保持分层职责的清晰和一致 +11. **所有编码风格必须要通过ESLint检查**,禁止任何 ESLint 错误或警告存在于提交的代码中 +12. **禁止修改底层公共代码来“顺手解决问题”**,如需要改 `app.js`、`app/extend/application.js`、`app/service/main.js` 等公共能力入口,必须先评估改动影响范围,并优先考虑在业务层做适配或扩展,避免对全局能力造成不确定风险,如确实需要改公共代码,必须先驳回到调度 agent 升级给专家 agent 进行兜底处理,禁止直接改公共代码后再评估风险的流程 + +## 关键定位地图 + +### 1) 接口入口与 Method 路由 + +- `/system`:Web / PDA 统一接口(POST) +- `/qimen`:奇门接口(POST) +- 路由说明文档:`AI_METHOD_ROUTING.md` + +### 2) 文档单一事实来源(SSOT) + +- `methods/system.json` +- `methods/qimen.json` +### 3) App 能力入口 + +- `app.js` +- `app/extend/application.js` + +### 4) 常用开发辅助文件 + +- `app/service/main.js`:where 统一处理、权限校验等公共逻辑 +- `test/app/controller/system.user.info.web.test.js` +- `test/app/controller/system.user.changeRole.test.js` + +## 推荐工作流 + +### 代码修改 / 修 bug + +1. 先定位 method 与实现链路 +2. 如需测试设计或补回归,先委派 `wms-test-agent` 补失败用例 +3. 做最小根因修复 +4. 跑相关检查验证 +5. 若涉及接口变更(参数、响应、新增、删除),**必须委派 `wms-doc-agent`** 同步 `methods/*.json`、追加 `methods/changes/*.json` 变更记录 + +### 接口参数变更 + +```powershell +node .\script\tmp-struct-system-params.cjs +``` + +然后人工补齐: +- `description` +- `response` +- `errors` +- 特殊枚举值与业务约束 + +## 建议提问方式 + +```text +请使用 wms-dev-agent 帮我: +1) 定位这个 method / controller / service 的实现链路 +2) 修复问题并说明最小代码改动 +3) 输出验证结果;若需要补测试,请转给 `wms-test-agent` +``` + +## 输出要求 + +- 所有回复建议以 `[Dev]` 开头 +- 先给结论,再给定位链路、修改点、验证结果 +- 涉及接口改动时,明确说明已委派 `wms-doc-agent` 完成文档同步(或提示调用方需要委派) + +## 结论 + +通用开发能力文档已统一收口到本 Agent;测试相关请求请转给 `wms-test-agent`,工具箱只保留“开发相关必须使用 `wms-dev-agent`”的规则入口。 + +## 代码风格 + +- 先定位代码真实实现与调用链 +- 只改最小必要代码,避免大面积重构 +- 改代码后必须跑相关测试验证 +- 涉及接口变更必须委派 `wms-doc-agent` 同步文档,本 agent 不直接修改文档文件 +- 除了json,其他字符串输出必须使用模板字符串,必要时分行保持可读性 +- From aba81d497ae66c23321ffe15f17418c438bf2e03 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sat, 11 Apr 2026 17:30:06 +0800 Subject: [PATCH 027/550] ok --- docs/order-cancel-db-checklist.md | 44 +++++++++++++++++++++++++++++++ order_todo.md | 10 +++++-- script/db-query.ps1 | 22 +++++++++++++--- 3 files changed, 70 insertions(+), 6 deletions(-) diff --git a/docs/order-cancel-db-checklist.md b/docs/order-cancel-db-checklist.md index e8bfa87..d71f579 100644 --- a/docs/order-cancel-db-checklist.md +++ b/docs/order-cancel-db-checklist.md @@ -3,6 +3,8 @@ > 用途:实施 `order_todo.md` **§2.3a(取消进 M4)** 前,对 **`wms_order_delivery` 及分表** 做只读核对。 > 不改变数据库;核对结果记录在工单或 `order_todo.md` 修订记录。 +**PowerShell 提示**:`db-query.ps1` 若遇 **`ConvertFrom-Json` 无效 JSON**(中文注释导致编码问题),可在同一会话先执行 **`chcp 65001`** 再跑查询。 + ## 1. 列出本库所有发货单相关表 ```sql @@ -51,3 +53,45 @@ ORDER BY COLUMN_NAME; - 模型枚举源:`app/model/order_delivery.js`(`StatusEnum`、`step` 注释) - 规划说明:仓库根目录 `order_todo.md` §0.7、§2.3a + +--- + +## 5. wms-db-agent 诊断记录(本机一次抽样,2026-04-10) + +> 工具:`script/db-query.ps1`,client **`wms`**,`DATABASE() = wms`。以下为 **只读** 结果摘要;其它环境须自行重跑 §1~§2。 + +### 5.1 匹配到的表 + +| TABLE_NAME | +|------------| +| `wms_order_delivery`(基表/模板) | +| `wms_order_delivery_100000` | +| `wms_order_delivery_1000028` | + +本库本次 **未发现** `*_history` 表。 + +### 5.2 目标列是否存在(Y/N) + +| TABLE_NAME | status | intercept_status | step | outbound_status | inspection_status | +|------------|:------:|:----------------:|:----:|:---------------:|:-----------------:| +| `wms_order_delivery` | Y | **N** | Y | **N** | **N** | +| `wms_order_delivery_100000` | Y | Y | Y | Y | Y | +| `wms_order_delivery_1000028` | Y | Y | Y | Y | Y | + +`delivery_time` / `updated_at` / `create_at` 三张表均有(基表 `updated_at`/`create_at` 为 YES)。 + +### 5.3 与 §0.7 / §2.3a 的对照结论 + +- **分表**(`_100000`、`_1000028`):§0.7 所列 **`status` / `intercept_status` / `step` / `outbound_status` / `inspection_status`** 均存在;`intercept_status` 含 **`cancelled`**,`status` 含 **`cancel`**;**可先不增列**,用组合条件做「取消进 M4」筛选(产品确认 WHERE 口径即可)。 +- **基表** `wms_order_delivery`:**缺** `intercept_status`、`outbound_status`、`inspection_status`;**业务筛选勿依赖基表**,以 **`wms_order_delivery_{warehouseId}`** 为准。 +- **枚举差异**:不同物理表上 **`status` 的 enum 集合不一致**(基表与分表、分表之间均有差异);规则与迁移须 **按仓/按表** 评估,勿假设全局一致。 +- **全量**:当前仅抽样 2 张分表;生产请对 **全部** `wms_order_delivery_*` 重跑本清单;若有 **`_history`** 须单独对齐列集。 + +### 5.4 §3 结论栏(代填,可改) + +| 检查项 | 是否满足「取消进 M4」筛选与展示 | +|--------|----------------------------------| +| `status` 含 `cancel` 枚举(与 ORM 一致) | **分表:是**;基表:部分(见上 enum 差异) | +| `intercept_status` 含 `cancelled` 等 | **分表:是**;**基表:无此列** | +| `step` 存在且含「9=已关闭」语义 | **是**(int NOT NULL,注释一致) | +| 若产品要求 **独立「取消进 M4」列** | **未检出有**;若需要仍须 migration(见 `order-delivery-migration-impact.md`) | diff --git a/order_todo.md b/order_todo.md index 7b54073..9aaba93 100644 --- a/order_todo.md +++ b/order_todo.md @@ -65,7 +65,7 @@ **实施 §2.3a 前必须执行:** -0. **核对清单(已产出,小阶段)**:只读 SQL 与步骤见 **`docs/order-cancel-db-checklist.md`**(不在仓库内自动连库执行)。 +0. **核对清单(已产出,小阶段)**:只读 SQL 与步骤见 **`docs/order-cancel-db-checklist.md`**(不在仓库内自动连库执行)。**库表 DDL 变更影响面**见 **`docs/order-delivery-migration-impact.md`**。 1. **对库**:对 `wms_order_delivery` 及 **`wms_order_delivery_%` 分表** 跑字段清单(`INFORMATION_SCHEMA`),确认 **`status` / `intercept_status` / `step` / `outbound_status`** 等与「取消后进 M4」**筛选用例**是否够用。 2. **若产品要求独立可辨的「取消进 M4」标记**(例如与 `status=cancel` 但尚未占配送域行的组合区分):**库中无字段则新增**(如 `close_channel`、`cancelled_at`、`m4_reason_code` 等,名称待定),并同步: - `app/model/order_delivery.js`; @@ -204,6 +204,8 @@ | 日期 | 内容 | |------|------| | 2026-04-10 | **无业务代码 / 无 migration 变更**。新增只读交付物:`docs/order-cancel-db-checklist.md`(§0.7 跑库步骤)、`docs/order-state-machine-dictionary.md`(状态机字典 **v0 骨架**,与 `app/model/order_delivery.js` 摘录一致)。**数仓映射、实际跑库结果** 仍待下一小阶段。 | +| 2026-04-10 | **小阶段 A-1(影响面)**:新增 `docs/order-delivery-migration-impact.md`。**结论**:在未跑库确认缺列、且未敲定「取消进 M4」专用列前,**不自动提交 ALTER migration**;若清单验证列已齐,可先 **零表变更** 做应用筛选。详见该文档 **§1**。 | +| 2026-04-10 | **小阶段 A-2(wms-db-agent 只读诊断)**:已对 `wms` 库跑清单;结果写入 **`docs/order-cancel-db-checklist.md` §5**。要点:**分表** `100000`/`1000028` 目标列齐全,可先不增列做筛选;**基表**缺三列、**勿**当业务表用;**无 `_history` 样本**;`chcp 65001` 防 JSON 解析失败。 | ### 阶段 A — 文档与规则冻结 @@ -211,8 +213,10 @@ - [ ] M1→M2:库存校验 API、M7 推送接口与回写字段。 - [ ] 外部「发货完成」通知与状态机字段的映射表(落到 `outbound_status` / `step` 等)。 - [x] **§0.7 清单文档**:`docs/order-cancel-db-checklist.md`(各环境人工执行)。 -- [ ] **§0.7 跑库与缺列**:按清单在各环境执行;**缺则 migration**;更新模型与工厂 DDL。 +- [x] **§0.7 跑库(本机 wms 一次)**:见 `docs/order-cancel-db-checklist.md` §5;**分表列齐**;**其它仓/生产须复跑**。 +- [ ] **§0.7 缺列 migration**:若产品仍要独立「取消进 M4」列或基表对齐,再开 migration;更新模型与工厂 DDL。 - [x] **状态机字典 v0 骨架**:`docs/order-state-machine-dictionary.md`(与数仓/报表的 **字段映射表** 仍待补)。 +- [x] **订单表 DDL 影响面分析**:`docs/order-delivery-migration-impact.md`(结论:**未自动做 migration**,待跑库 + 列名后由你决策)。 ### 阶段 B — 配送域工厂(3 自然月 + 强分区事务) @@ -275,3 +279,5 @@ | 补充 | **§0.7** 取消状态机与分表核对/缺列 migration;**克隆续单不奇门同步、首期人工补单**;**字段字典与数仓报表同步**;**§5a 运维审批预留** | | 补充 | **§5 重写**:区分 **规则层已满足** vs **交付层未完成**;原 checklist 拆入 §5.1 / §5.2 并指向 §4 | | 2026-04-10 | **小阶段 A-0**:新增 `docs/order-cancel-db-checklist.md`、`docs/order-state-machine-dictionary.md`;§0.7 / §4 阶段 A / §5.2 同步;无代码变更 | +| 2026-04-10 | **小阶段 A-1**:`docs/order-delivery-migration-impact.md`;**未提交 migration**(待你根据跑库 + 列名决策) | +| 2026-04-10 | **小阶段 A-2**:wms-db-agent 只读诊断;`order-cancel-db-checklist.md` §5;**未提交 migration** | diff --git a/script/db-query.ps1 b/script/db-query.ps1 index 10b9dce..1504697 100644 --- a/script/db-query.ps1 +++ b/script/db-query.ps1 @@ -61,11 +61,17 @@ const { createRequire } = require("module"); try { const [rows] = await connection.query(query); - process.stdout.write(JSON.stringify({ + const payload = JSON.stringify({ client: clientName, rowCount: Array.isArray(rows) ? rows.length : 0, rows, - })); + }); + const outPath = process.argv[6]; + if (outPath) { + require('fs').writeFileSync(outPath, payload, 'utf8'); + } else { + process.stdout.write(payload); + } } finally { await connection.end(); } @@ -80,8 +86,12 @@ $tempNodeFile = [System.IO.Path]::ChangeExtension($tempFile.FullName, ".cjs") Move-Item -Path $tempFile.FullName -Destination $tempNodeFile -Force Set-Content -Path $tempNodeFile -Value $nodeScript -Encoding UTF8 +$jsonOutFile = [System.IO.Path]::ChangeExtension( + ([System.IO.Path]::Combine([System.IO.Path]::GetTempPath(), 'db-query-' + [Guid]::NewGuid().ToString())), + '.json' +) try { - $json = & node $tempNodeFile $projectRoot $configResolved.Path $DbClient $Query + $null = & node $tempNodeFile $projectRoot $configResolved.Path $DbClient $Query $jsonOutFile if ($LASTEXITCODE -ne 0) { throw "Node query runner exited with code $LASTEXITCODE." } @@ -89,7 +99,11 @@ try { Remove-Item -Path $tempNodeFile -ErrorAction SilentlyContinue } -$result = $json | ConvertFrom-Json +try { + $result = Get-Content -LiteralPath $jsonOutFile -Raw -Encoding utf8 | ConvertFrom-Json +} finally { + Remove-Item -Path $jsonOutFile -ErrorAction SilentlyContinue +} Write-Host "Client: $($result.client)" Write-Host "Rows: $($result.rowCount)" From b0700c6629a6aa92a1de23d92d217705cc9c28be Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sat, 11 Apr 2026 17:30:15 +0800 Subject: [PATCH 028/550] chore: minor updates and improvements --- ...atus-columns-to-wms-order-delivery-base.js | 174 ++++++++++++++++++ docs/order-delivery-migration-impact.md | 62 +++++++ 2 files changed, 236 insertions(+) create mode 100644 database/migrations/20260410200000-add-status-columns-to-wms-order-delivery-base.js create mode 100644 docs/order-delivery-migration-impact.md diff --git a/database/migrations/20260410200000-add-status-columns-to-wms-order-delivery-base.js b/database/migrations/20260410200000-add-status-columns-to-wms-order-delivery-base.js new file mode 100644 index 0000000..1e29cdb --- /dev/null +++ b/database/migrations/20260410200000-add-status-columns-to-wms-order-delivery-base.js @@ -0,0 +1,174 @@ +'use strict'; + +const TABLE = 'wms_order_delivery'; + +/** + * 与 `app/model/order_delivery.js`、`order_delivery_factory.js` 中 DDL 一致。 + * `up` 仅对缺失列执行 ADD;`down` 按逆序删除下列列(若存在)——若某列在迁移前已存在且含数据,请勿执行 down。 + * + * 列顺序与工厂建表一致,便于 `AFTER` 链式追加时相对位置稳定。 + */ +const STATUS_MACHINE_COLUMNS = [ + { + name: 'sync_status', + ddl: "enum('padding','fin','error') DEFAULT 'padding'", + comment: '同步状态', + after: 'oaid', + }, + { + name: 'post_status', + ddl: "enum('padding','fin','timeout','error','none') DEFAULT 'none'", + comment: '分配快递号状态机', + after: 'wave_id', + }, + { + name: 'storage_status', + ddl: "enum('padding','fin','error','none') DEFAULT 'none'", + comment: '分配储位状态机', + after: 'post_status', + }, + { + name: 'pick_status', + ddl: "enum('padding','fin','error','none') DEFAULT 'none'", + comment: '拣货状态机', + after: 'storage_status', + }, + { + name: 'pack_status', + ddl: "enum('none','padding','fin','error') DEFAULT 'none'", + comment: '打包状态机', + after: 'pick_status', + }, + { + name: 'inspection_status', + ddl: "enum('none','padding','running','fin','error') DEFAULT 'none'", + comment: '检验状态机', + after: 'pack_status', + }, + { + name: 'print_status', + ddl: "enum('none','padding','fin','error') DEFAULT NULL", + comment: '打印状态机', + after: 'step', + }, + { + name: 'claim_status', + ddl: "enum('none','padding','fin','error') DEFAULT 'none'", + comment: '领取状态机', + after: 'print_status', + }, + { + name: 'outbound_status', + ddl: "enum('none','padding','fin','error') DEFAULT 'none'", + comment: '出库状态机', + after: 'claim_status', + }, + { + name: 'lock_status', + ddl: "enum('none','warehouse','store') DEFAULT NULL", + comment: '锁定状态机', + after: 'outbound_status', + }, + { + name: 'intercept_status', + ddl: + "enum('none','requesting','requested','intercepting','intercepted_in_transit','intercepted_at_warehouse','returning','returned','delivered_by_mistake','timeout','cancelled','failed','exception') DEFAULT NULL", + comment: '拦截状态机', + after: 'lock_status', + }, +]; + +/** + * @param {import('sequelize').QueryInterface} queryInterface + * @param {string} tableName + * @param {string} columnName + * @return {Promise} + */ +async function hasColumn(queryInterface, tableName, columnName) { + const [ columns ] = await queryInterface.sequelize.query( + ` + SELECT COLUMN_NAME + FROM INFORMATION_SCHEMA.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = :tableName + AND COLUMN_NAME = :columnName + `, + { replacements: { tableName, columnName } } + ); + return columns.length > 0; +} + +/** + * @param {import('sequelize').QueryInterface} queryInterface + * @param {string} tableName + * @return {Promise} + */ +async function tableExists(queryInterface, tableName) { + const [ rows ] = await queryInterface.sequelize.query( + ` + SELECT COUNT(*) AS cnt + FROM INFORMATION_SCHEMA.TABLES + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = :tableName + `, + { replacements: { tableName } } + ); + return Number(rows[0].cnt) > 0; +} + +/** + * @param {import('sequelize').QueryInterface} queryInterface + * @param {string} tableName + * @param {string} preferredAfter + * @return {Promise} + */ +async function resolveAfterClause(queryInterface, tableName, preferredAfter) { + if (preferredAfter && (await hasColumn(queryInterface, tableName, preferredAfter))) { + return `AFTER \`${preferredAfter}\``; + } + return ''; +} + +module.exports = { + /** + * 仅为基表 `wms_order_delivery` 按需补状态机相关列;已存在则跳过。 + * + * @param {import('sequelize').QueryInterface} queryInterface + * @returns {Promise} + */ + async up(queryInterface) { + if (!(await tableExists(queryInterface, TABLE))) { + return; + } + + for (const col of STATUS_MACHINE_COLUMNS) { + if (await hasColumn(queryInterface, TABLE, col.name)) { + continue; + } + const afterPart = await resolveAfterClause(queryInterface, TABLE, col.after); + await queryInterface.sequelize.query( + `ALTER TABLE \`${TABLE}\` ADD COLUMN \`${col.name}\` ${col.ddl} COMMENT '${col.comment}' ${afterPart}`.trim() + ); + } + }, + + /** + * 逆序删除本文件声明的状态机列(若存在)。见文件头注释。 + * + * @param {import('sequelize').QueryInterface} queryInterface + * @returns {Promise} + */ + async down(queryInterface) { + if (!(await tableExists(queryInterface, TABLE))) { + return; + } + const reversed = [ ...STATUS_MACHINE_COLUMNS ].reverse(); + for (const col of reversed) { + if (await hasColumn(queryInterface, TABLE, col.name)) { + await queryInterface.sequelize.query( + `ALTER TABLE \`${TABLE}\` DROP COLUMN \`${col.name}\`` + ); + } + } + }, +}; diff --git a/docs/order-delivery-migration-impact.md b/docs/order-delivery-migration-impact.md new file mode 100644 index 0000000..d2ebf79 --- /dev/null +++ b/docs/order-delivery-migration-impact.md @@ -0,0 +1,62 @@ +# `wms_order_delivery*` / `wms_order_items*` 库表变更 — 影响面分析(供决策) + +> 目的:回答「改库是否影响当前所有涉及 order 发货单表的逻辑」;**未连真实库**,结论基于代码静态分析。 +> 关联:`order_todo.md` §0.7、§2.3a;核对清单 `docs/order-cancel-db-checklist.md`。 + +--- + +## 1. 结论摘要(是否可直接做迁移) + +| 变更类型 | 对现有逻辑的典型影响 | 建议 | +|----------|----------------------|------| +| **仅核对列已存在、不做 DDL** | 无 | **推荐先做**(清单 `order-cancel-db-checklist.md`) | +| **新增可空列 + 默认值**(`NULL` 默认 / `DEFAULT`) | Sequelize `create`/`update`/`find` 一般 **不崩**;未赋值的 `create` 不写该列则用库默认 | **低面影响**,但仍须 **同步** `app/model/order_delivery.js` + `order_delivery_factory.js` 的 `createPhysicalTable` DDL,且 **所有已存在分表** 需同一 migration 补列 | +| **新增 NOT NULL 无默认** | 旧 `create`/`bulkCreate` 可能 **插入失败** | **高面影响**,**禁止**在未改全链路前做 | +| **改 ENUM 取值 / 删列 / 改列类型** | `order.*` 列表 where、奇门/入库、报表可能 **全链路受影响** | **高面影响**,须单独评审与回归 | +| **仅改索引 / 注释**(不改列语义) | 一般低;大表加索引注意锁表 | 可个案评估 | + +**当前结论(在未跑 §0.7 清单、未选定「取消进 M4」专用列名之前):** +**不在仓库内自动提交新的 `ALTER` migration。** 代码侧已具备 `status.cancel`、`intercept_status.cancelled`、`step`(含 9 关闭)等枚举(见 `order-state-machine-dictionary.md`),**若跑库确认列已齐全,则「取消进 M4」可先不增列,仅做应用筛选逻辑** — 此时 **无需表迁移**。 +若跑库确认 **缺列** 或产品 **强制** 要独立标记列 → **属有面影响变更**,请在你确认 **列名、类型、默认值、是否只加 current 或含 history** 后再做 migration。 + +**(已更新)** 本机 `wms` 库经 **wms-db-agent** 只读抽样结果见 **`docs/order-cancel-db-checklist.md` §5**:两张分表目标列齐全,**可先不增列**;基表缺列、勿作业务筛选;全量仓与 `_history` 须另跑。 + +--- + +## 2. 代码侧「会吃到表结构」的路径 + +### 2.1 动态模型来源(关键) + +- `OrderDeliveryFactory` / `OrderItemsFactory` 使用 **`app.model.OrderDelivery.rawAttributes`**(及 `OrderItems`)**动态 `define` 每张分表**。 +- **新建物理表**时,`createPhysicalTable` 内 **手写 DDL 片段** 与模型字段 **必须长期一致**,否则新仓新表与 ORM 不一致。 + +### 2.2 业务入口(非穷举,均为 `getCurrentModel` 链) + +| 区域 | 文件 | +|------|------| +| System 订单 method | `app/service/systemMethods/order/*.js`(经 `base.js#getOrderModels`) | +| 业务发货单 | `app/service/systems/delivery_order.js`(`create` / `update` / `bulkCreate` 明细等) | +| 奇门 | `app/service/qimenMethods/deliveryorder.js` | +| 测试 / 探针 | `app/service/apiMethods/test.js`(命名 `WmsOrderDeliveryFactory` 需与挂载一致,否则仅测试路径) | + +### 2.3 写入方式 + +- `DeliveryModel.create(orderData)`、`OrderItemsModel.bulkCreate(lineData)`:**对象字段驱动**;新增 **可空** 列且模型已声明时,旧代码路径 **通常无需改** 即可插入。 + +--- + +## 3. 若你决定「要做加列迁移」时的必做清单 + +1. 产品确认:**列名、含义、是否可空、默认值、是否写 history 表**。 +2. Migration:`findOrderDeliveryTables` 风格 **遍历** `wms_order_delivery` / `wms_order_delivery_*`(及若需要则 `wms_order_items_*`)。 +3. `app/model/order_delivery.js` 增加字段定义。 +4. `app/model/order_delivery_factory.js` 中 **`createPhysicalTable`** 同步列定义。 +5. 回归:`npm run test:local` 中与 `delivery_order` / `order` 相关用例;奇门若有联调则单独测。 + +--- + +## 4. 修订 + +| 日期 | 说明 | +|------|------| +| 2026-04-10 | 初版:静态影响面结论;**未提交 migration** | From d442b91ca156f49e3d1495168c96352f98be7dc4 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sat, 11 Apr 2026 17:34:53 +0800 Subject: [PATCH 029/550] chore: apply minor updates and enhancements --- .cursor/agents/wms-db-agent.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/.cursor/agents/wms-db-agent.md b/.cursor/agents/wms-db-agent.md index 54e0c6f..4ec6ec3 100644 --- a/.cursor/agents/wms-db-agent.md +++ b/.cursor/agents/wms-db-agent.md @@ -24,6 +24,7 @@ is_background: false - 排查接口返回为空、数据异常、库表映射问题 - 核对 `wms` / `ye4s` 库连接与路由 - 解释字段含义、表结构、索引建议 +- **执行仓库内 Sequelize 迁移**(`database/migrations`,见下节) ## 工作规则 @@ -43,6 +44,11 @@ is_background: false 8. 输出要求: - 所有回复必须以 `[DB]` 开头 - 优先给结论、关键字段和下一步建议 +9. **Schema 迁移(DDL)**: + - 需要把仓库里的 migration 落到库上时,由 **本 agent** 执行,不在对话里只写「请自行 migrate」。 + - 默认仅对**用户已声明的测试库**执行;连接串须与 `config` 中测试 client 一致。生产/预发须走既有发布与备份流程,**未**声明为可写环境时不得执行 `db:migrate` / 手写 `ALTER`。 + - 项目根目录执行:`npx sequelize-cli db:migrate`(依赖根目录 `.sequelizerc`)。 + - 执行前后用 `db-query.ps1` 跑 `INFORMATION_SCHEMA` / `SHOW CREATE TABLE` 做核对;若 migration 内已对列做 `hasColumn` 判断,重复执行应安全幂等。 ## 常用命令模板 @@ -71,6 +77,13 @@ powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -DbClient wms -Qu powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -DbClient ye4s -Query "SHOW TABLES" ``` +### 5) 执行 Sequelize 迁移(测试库 / 已授权环境) + +```powershell +cd D:\wms +npx sequelize-cli db:migrate +``` + ## 建议提问方式 ```text From 622869787af50f14cae91f9e149d789047660bac Mon Sep 17 00:00:00 2001 From: liufumingren Date: Thu, 16 Apr 2026 20:00:01 +0800 Subject: [PATCH 030/550] feat: sync workspace changes --- .codebuddy/.gitignore | 1 - .cursor/agents/wms-doc-agent.md | 25 +- .github/agents/文档.agent.md | 25 +- AI_TOOLBOX.md | 8 +- README.md | 12 +- app.js | 23 +- app/controller/docs.js | 533 ++++- app/controller/home.js | 158 +- app/extend/application.js | 305 ++- app/lib/order_delivery_selfcheck.js | 19 + app/lib/polo_api_client.js | 253 ++ app/lib/warehouse_shard_guard.js | 93 + app/model/express.js | 18 +- app/model/express_interface.js | 132 ++ app/model/express_platform.js | 75 + app/model/express_product_type.js | 44 + app/model/express_setting.js | 15 +- app/model/notification_webhook.js | 7 +- app/model/order_delivery.js | 31 +- app/model/order_delivery_factory.js | 704 ++++-- app/model/order_delivery_table_schema.js | 521 +++++ app/model/order_express.js | 33 +- app/model/order_items.js | 5 + app/model/order_items_factory.js | 364 ++- app/model/picking.js | 128 ++ app/model/platform_setting.js | 31 +- app/model/stock_warehouse.js | 20 + app/model/store.js | 20 + app/model/store_warehouse.js | 147 +- app/router.js | 8 + app/schedule/notice_stock_remaining.js | 733 ++++++ .../sync_outbound_orders_to_delivery.js | 51 + ...ync_outbound_timeout_orders_to_delivery.js | 51 + app/service/qimen.js | 15 +- app/service/qimenMethods/deliveryorder.js | 5 +- app/service/qimenMethods/order.js | 132 +- app/service/systemMethods/index.js | 27 +- .../systemMethods/order/archiveOrder.js | 62 +- app/service/systemMethods/order/base.js | 1181 ++++++++-- .../order/deliveryExpectionOrder.js | 26 + .../systemMethods/order/deliveryOrder.js | 63 +- .../systemMethods/order/entrustOrder.js | 26 + .../systemMethods/order/expectionOrder.js | 90 +- app/service/systemMethods/order/index.js | 239 +- .../systemMethods/order/outboundOrder.js | 34 + .../systemMethods/order/pendingOrder.js | 330 ++- .../systemMethods/order/reviewOrder.js | 133 +- .../systemMethods/order/storageAllocation.js | 47 + app/service/systemMethods/setting/express.js | 171 ++ .../systemMethods/setting/expressInterface.js | 230 ++ app/service/systemMethods/setting/platform.js | 186 ++ app/service/systemMethods/storage/expiry.js | 61 + .../systemMethods/storage/inventory.js | 4 +- app/service/systemMethods/storage/stockout.js | 83 - app/service/systems/delivery_order.js | 412 +++- app/service/systems/excel.js | 26 +- app/service/systems/express.js | 504 ++++ app/service/systems/notice/index.js | 3 + .../systems/order_delivery_migration.js | 643 ++++++ app/service/systems/order_outbound.js | 89 + .../systems/order_pending_exception.js | 43 + .../systems/order_storage_allocation.js | 636 ++++++ app/service/systems/platform.js | 260 +++ app/service/systems/polo_api.js | 334 ++- app/service/systems/qimen_query.js | 70 +- app/service/systems/setting/express.js | 530 +++++ .../systems/setting/expressInterface.js | 774 +++++++ app/service/systems/setting/platform.js | 638 ++++++ app/service/systems/stock_store.js | 66 +- app/service/systems/storage/expiry.js | 199 ++ app/service/systems/storage/inventory.js | 290 ++- app/service/systems/storage/receiving.js | 125 +- app/service/systems/store.js | 2 + app/service/systems/store_warehouse.js | 15 +- config/plugin.js | 6 +- config/poloapi.js | 29 - ...d-audit-status-to-order-delivery-tables.js | 6 +- ...atus-with-step-on-order-delivery-tables.js | 4 +- ...atus-columns-to-wms-order-delivery-base.js | 30 +- ...-wms-store-subject-config-default-codes.js | 32 + ...0415172000-create-wms-express-interface.js | 74 + .../20260415190000-create-wms-picking.js | 118 + ...60415191000-add-quantity-to-wms-picking.js | 32 + day.log | Bin 37706 -> 0 bytes docs/api-doc-update-spec.example.json | 56 + docs/api-doc-update-workflow.md | 103 + docs/notification-event-api.md | 9 +- docs/notification-webhook-capability.md | 12 +- docs/order-workbench-list-api.md | 186 ++ docs/stock-expiry-module.md | 80 + docs/storage-receiving-api.md | 108 + methods/changes/system.json | 308 ++- methods/system.json | 2035 +++++++++++++---- order_todo.md | 69 +- package.json | 3 + .../file-writer/.write-window-counter-3.json | 2 +- .../file-writer/qimen-logs/.consume-progress | 10 +- .../.consume-progress.25476.1775941895725.tmp | 7 + .../qimen-logs-MINGREN-worker-p38224-0001.log | 1 + ...n-logs-MINGREN-worker-p38224-0001.log.done | 7 + .../qimen-logs-MINGREN-worker-p41276-0001.log | 4 + .../qimen-logs-MINGREN-worker-p42648-0001.log | 1 + ...n-logs-MINGREN-worker-p42648-0001.log.done | 7 + script/update-api-doc.cjs | 387 ++++ temp_check_json.js | 39 + temp_count_brackets.js | 15 + temp_debug_headers.js | 5 + temp_find_headers_close.js | 15 + temp_find_missing_commas.js | 1 + temp_find_objsep.js | 1 + temp_find_trailing_commas.js | 1 + temp_parse_json.py | 13 + temp_rebuild_system_json.js | 49 + test/app/controller/docs.test.js | 45 +- ...gateway.user.bindAccountByTempCode.test.js | 14 +- test/app/controller/home.test.js | 99 +- .../qimen.deliveryorder.reviewFlow.test.js | 432 ++++ .../system.order.badgeCount.test.js | 172 ++ .../system.order.getreviewOrderlist.test.js | 92 +- .../system.order.namespaced.test.js | 224 +- .../system.order.outbound.exposure.test.js | 90 + ...er.pendingOrder.reverseReviewOrder.test.js | 613 +++++ .../system.order.reviewOrder.test.js | 399 +++- ....setting.account.getBindWechatCode.test.js | 14 +- .../system.setting.storeWarehouse.test.js | 11 +- .../system.storage.delivery.module.test.js | 96 +- .../system.storage.inventory.list.test.js | 136 ++ ...tem.storage.inventory.quickPutaway.test.js | 109 +- .../controller/system.storeWarehouse.test.js | 37 + test/app/extend/application.cache.test.js | 238 ++ test/app/lib/order_delivery_selfcheck.test.js | 24 + test/app/model/express.test.js | 51 + test/app/model/express_product_type.test.js | 66 + .../order_delivery_dispatch_factory.test.js | 325 +++ .../order_delivery_factory_selfcheck.test.js | 404 ++++ test/app/model/order_items_factory.test.js | 251 ++ test/app/model/picking.test.js | 80 + .../schedule/notice_stock_remaining.test.js | 448 ++++ .../sync_outbound_orders_to_delivery.test.js | 47 + ...utbound_timeout_orders_to_delivery.test.js | 48 + test/app/service/qimenMethods/order.test.js | 216 ++ .../systemMethods/order.base.step.test.js | 552 ++++- .../order/storageAllocation.test.js | 63 + .../systemMethods/setting/express.test.js | 178 ++ .../setting/expressInterface.test.js | 167 ++ .../systemMethods/setting/platform.test.js | 186 ++ .../delivery_order.auditStatus.test.js | 163 +- .../systems/delivery_order.oversell.test.js | 42 + test/app/service/systems/excel.test.js | 45 + test/app/service/systems/express.test.js | 302 +++ test/app/service/systems/notice.test.js | 7 +- .../systems/order_delivery_migration.test.js | 695 ++++++ .../service/systems/order_outbound.test.js | 166 ++ .../systems/order_pending_exception.test.js | 188 ++ .../systems/order_storage_allocation.test.js | 521 +++++ test/app/service/systems/platform.test.js | 164 ++ test/app/service/systems/polo_api.test.js | 222 ++ test/app/service/systems/qimen_query.test.js | 59 + .../service/systems/setting/express.test.js | 284 +++ .../systems/setting/expressInterface.test.js | 340 +++ .../service/systems/setting/platform.test.js | 331 +++ ...ck_store.stockWarehouse.conditions.test.js | 282 +++ .../service/systems/storage.expiry.test.js | 227 ++ .../service/systems/storage.inventory.test.js | 390 ++++ .../storage.receiving.detailChange.test.js | 148 ++ .../systems/storage.receiving.report.test.js | 185 +- test/support/order_service_test_helper.js | 151 ++ test/support/system_method_client.js | 164 ++ .../20260412-1723-真实下单出库脚本验证报告.md | 44 + ...260414-库存效期任务实例形态回归测试报告.md | 38 + .../20260417-172716-收货入库回归测试报告.md | 72 + ..._dispatch_factory-MySQL建表集成测试报告.md | 46 + .../20260412-014727-订单工作台list单测报告.md | 53 + .../20260412-165910-订单迁移回归测试报告.md | 35 + .../20260412-1753-真实收货入库流程验证报告.md | 57 + ...º“存效期任务跨天重发与旧缓存兼容验证报告.md | 39 + worktrees/deploy-20260409155126 | 1 - 177 files changed, 26204 insertions(+), 2446 deletions(-) delete mode 100644 .codebuddy/.gitignore create mode 100644 app/lib/order_delivery_selfcheck.js create mode 100644 app/lib/polo_api_client.js create mode 100644 app/lib/warehouse_shard_guard.js create mode 100644 app/model/express_interface.js create mode 100644 app/model/express_platform.js create mode 100644 app/model/express_product_type.js create mode 100644 app/model/order_delivery_table_schema.js create mode 100644 app/model/picking.js create mode 100644 app/schedule/notice_stock_remaining.js create mode 100644 app/schedule/sync_outbound_orders_to_delivery.js create mode 100644 app/schedule/sync_outbound_timeout_orders_to_delivery.js create mode 100644 app/service/systemMethods/order/deliveryExpectionOrder.js create mode 100644 app/service/systemMethods/order/entrustOrder.js create mode 100644 app/service/systemMethods/order/outboundOrder.js create mode 100644 app/service/systemMethods/order/storageAllocation.js create mode 100644 app/service/systemMethods/setting/express.js create mode 100644 app/service/systemMethods/setting/expressInterface.js create mode 100644 app/service/systemMethods/setting/platform.js create mode 100644 app/service/systemMethods/storage/expiry.js delete mode 100644 app/service/systemMethods/storage/stockout.js create mode 100644 app/service/systems/express.js create mode 100644 app/service/systems/order_delivery_migration.js create mode 100644 app/service/systems/order_outbound.js create mode 100644 app/service/systems/order_pending_exception.js create mode 100644 app/service/systems/order_storage_allocation.js create mode 100644 app/service/systems/setting/express.js create mode 100644 app/service/systems/setting/expressInterface.js create mode 100644 app/service/systems/setting/platform.js create mode 100644 app/service/systems/storage/expiry.js delete mode 100644 config/poloapi.js create mode 100644 database/migrations/20260415000000-init-wms-store-subject-config-default-codes.js create mode 100644 database/migrations/20260415172000-create-wms-express-interface.js create mode 100644 database/migrations/20260415190000-create-wms-picking.js create mode 100644 database/migrations/20260415191000-add-quantity-to-wms-picking.js delete mode 100644 day.log create mode 100644 docs/api-doc-update-spec.example.json create mode 100644 docs/api-doc-update-workflow.md create mode 100644 docs/order-workbench-list-api.md create mode 100644 docs/stock-expiry-module.md create mode 100644 runtime/file-writer/qimen-logs/.consume-progress.25476.1775941895725.tmp create mode 100644 runtime/file-writer/qimen-logs/2026/04/12/qimen-logs-MINGREN-worker-p38224-0001.log create mode 100644 runtime/file-writer/qimen-logs/2026/04/12/qimen-logs-MINGREN-worker-p38224-0001.log.done create mode 100644 runtime/file-writer/qimen-logs/2026/04/12/qimen-logs-MINGREN-worker-p41276-0001.log create mode 100644 runtime/file-writer/qimen-logs/2026/04/12/qimen-logs-MINGREN-worker-p42648-0001.log create mode 100644 runtime/file-writer/qimen-logs/2026/04/12/qimen-logs-MINGREN-worker-p42648-0001.log.done create mode 100644 script/update-api-doc.cjs create mode 100644 temp_check_json.js create mode 100644 temp_count_brackets.js create mode 100644 temp_debug_headers.js create mode 100644 temp_find_headers_close.js create mode 100644 temp_find_missing_commas.js create mode 100644 temp_find_objsep.js create mode 100644 temp_find_trailing_commas.js create mode 100644 temp_parse_json.py create mode 100644 temp_rebuild_system_json.js create mode 100644 test/app/controller/qimen.deliveryorder.reviewFlow.test.js create mode 100644 test/app/controller/system.order.badgeCount.test.js create mode 100644 test/app/controller/system.order.outbound.exposure.test.js create mode 100644 test/app/controller/system.order.pendingOrder.reverseReviewOrder.test.js create mode 100644 test/app/controller/system.storage.inventory.list.test.js create mode 100644 test/app/extend/application.cache.test.js create mode 100644 test/app/lib/order_delivery_selfcheck.test.js create mode 100644 test/app/model/express.test.js create mode 100644 test/app/model/express_product_type.test.js create mode 100644 test/app/model/order_delivery_dispatch_factory.test.js create mode 100644 test/app/model/order_delivery_factory_selfcheck.test.js create mode 100644 test/app/model/order_items_factory.test.js create mode 100644 test/app/model/picking.test.js create mode 100644 test/app/schedule/notice_stock_remaining.test.js create mode 100644 test/app/schedule/sync_outbound_orders_to_delivery.test.js create mode 100644 test/app/schedule/sync_outbound_timeout_orders_to_delivery.test.js create mode 100644 test/app/service/qimenMethods/order.test.js create mode 100644 test/app/service/systemMethods/order/storageAllocation.test.js create mode 100644 test/app/service/systemMethods/setting/express.test.js create mode 100644 test/app/service/systemMethods/setting/expressInterface.test.js create mode 100644 test/app/service/systemMethods/setting/platform.test.js create mode 100644 test/app/service/systems/express.test.js create mode 100644 test/app/service/systems/order_delivery_migration.test.js create mode 100644 test/app/service/systems/order_outbound.test.js create mode 100644 test/app/service/systems/order_pending_exception.test.js create mode 100644 test/app/service/systems/order_storage_allocation.test.js create mode 100644 test/app/service/systems/platform.test.js create mode 100644 test/app/service/systems/polo_api.test.js create mode 100644 test/app/service/systems/qimen_query.test.js create mode 100644 test/app/service/systems/setting/express.test.js create mode 100644 test/app/service/systems/setting/expressInterface.test.js create mode 100644 test/app/service/systems/setting/platform.test.js create mode 100644 test/app/service/systems/storage.expiry.test.js create mode 100644 test/app/service/systems/storage.inventory.test.js create mode 100644 test/app/service/systems/storage.receiving.detailChange.test.js create mode 100644 test/support/order_service_test_helper.js create mode 100644 test_reports/fail/20260412-1723-真实下单出库脚本验证报告.md create mode 100644 test_reports/fail/20260414-库存效期任务实例形态回归测试报告.md create mode 100644 test_reports/fail/20260417-172716-收货入库回归测试报告.md create mode 100644 test_reports/pass/20260411-184847-order_delivery_dispatch_factory-MySQL建表集成测试报告.md create mode 100644 test_reports/pass/20260412-014727-订单工作台list单测报告.md create mode 100644 test_reports/pass/20260412-165910-订单迁移回归测试报告.md create mode 100644 test_reports/pass/20260412-1753-真实收货入库流程验证报告.md create mode 100644 test_reports/pass/20260414-库存效期任务跨天重发与旧缓存兼容验证报告.md delete mode 160000 worktrees/deploy-20260409155126 diff --git a/.codebuddy/.gitignore b/.codebuddy/.gitignore deleted file mode 100644 index 19e0180..0000000 --- a/.codebuddy/.gitignore +++ /dev/null @@ -1 +0,0 @@ -db/ diff --git a/.cursor/agents/wms-doc-agent.md b/.cursor/agents/wms-doc-agent.md index e6f91f5..f047f74 100644 --- a/.cursor/agents/wms-doc-agent.md +++ b/.cursor/agents/wms-doc-agent.md @@ -38,7 +38,9 @@ is_background: false - 公共请求头变化 - 鉴权方式变化 - 每次 API 接口变更(新增 / 修改 / 删除 method、参数、响应、错误码、header、鉴权等)后,除了更新 `methods/*.json` / `docs/*.md`,**还必须追加一条变更记录到对应的 `methods/changes/.json` 数组** - - 修补json文件时必须强校验 JSON格式的正确性,确保不会引入格式错误导致无法解析的情况 + - 默认禁止直接手写 `methods/*.json` / `methods/changes/*.json`,必须先按 `docs/api-doc-update-workflow.md` 生成固定 spec,再执行 `npm run doc:api:update -- --spec=` + - 正式写入前必须先执行 `npm run doc:api:update -- --spec= --dry-run` + - 修补 JSON 文件时必须强校验 JSON 格式正确性,确保不会引入无法解析的问题 - `methods/*.json` 仍是 SSOT,`methods/changes/*.json` 仅记录差异历史 - 变更记录建议字段至少包含:`version`、`date`、`summary`、`methods`、`notes` 5. 如 system 入参有变化,可执行: @@ -60,11 +62,11 @@ node .\script\tmp-struct-system-params.cjs ## 推荐工作流 1. 先定位代码真实实现与调用链 -2. 找到对应的 `methods/*.json` / `docs/*.md` -3. 以代码和测试结果为准更新文档 -4. 更新文档后同步追加对应的 `methods/changes/.json` 变更记录 -5. 校验 method 名称、参数、响应与代码一致 -6. 必要时验证 JSON 格式可正常解析 +2. 如 system 入参结构变化,可先执行 `node .\script\tmp-struct-system-params.cjs` +3. 按 `docs/api-doc-update-workflow.md` 生成固定 spec JSON +4. 先执行 `npm run doc:api:update -- --spec= --dry-run` +5. 确认后执行 `npm run doc:api:update -- --spec=` 写入 `methods/*.json` 与 `methods/changes/*.json` +6. 再补充 `docs/*.md` / `README.md`,并校验 method 名称、参数、响应与代码一致 ## 常用验证方式 @@ -74,6 +76,12 @@ node .\script\tmp-struct-system-params.cjs node -e "JSON.parse(require('fs').readFileSync('methods/system.json','utf8')); console.log('system.json OK')" ``` +### 通过固定 spec dry-run 校验 API 文档写入 + +```powershell +npm run doc:api:update -- --spec=temp/api-doc-update.json --dry-run +``` + ### 核对 method 是否已登记 ```powershell @@ -85,8 +93,8 @@ Select-String -Path "methods/system.json" -Pattern "storage.receiving.bindDetail ```text 请使用 wms-doc-agent 帮我: 1) 根据代码现状整理接口或业务文档 -2) 同步 methods/*.json / docs/*.md / README -3) 校验文档与实现一致 +2) 先按 docs/api-doc-update-workflow.md 生成固定 spec,再执行 npm run doc:api:update +3) 同步 docs/*.md / README,并校验文档与实现一致 ``` ## 输出要求 @@ -95,6 +103,7 @@ Select-String -Path "methods/system.json" -Pattern "storage.receiving.bindDetail - 先给结论,再给修改文件、关键字段、验证结果 - 若同步了 `methods/*.json`,明确说明 method 名称与变更点 - 若接口有变更,需说明是否已同步写入 `methods/changes/*.json` +- 若执行了文档脚本,需明确说明 spec 路径、dry-run 结果与正式写入结果 ## 结论 diff --git a/.github/agents/文档.agent.md b/.github/agents/文档.agent.md index b89f2e3..be3c5df 100644 --- a/.github/agents/文档.agent.md +++ b/.github/agents/文档.agent.md @@ -38,7 +38,9 @@ model: GPT-5 mini (copilot) - 公共请求头变化 - 鉴权方式变化 - 每次 API 接口变更(新增 / 修改 / 删除 method、参数、响应、错误码、header、鉴权等)后,除了更新 `methods/*.json` / `docs/*.md`,**还必须追加一条变更记录到对应的 `methods/changes/.json` 数组** - - 修补json文件时必须强校验 JSON格式的正确性,确保不会引入格式错误导致无法解析的情况 + - 默认禁止直接手写 `methods/*.json` / `methods/changes/*.json`,必须先按 `docs/api-doc-update-workflow.md` 生成固定 spec,再执行 `npm run doc:api:update -- --spec=` + - 正式写入前必须先执行 `npm run doc:api:update -- --spec= --dry-run` + - 修补 JSON 文件时必须强校验 JSON 格式正确性,确保不会引入无法解析的问题 - `methods/*.json` 仍是 SSOT,`methods/changes/*.json` 仅记录差异历史 - 变更记录建议字段至少包含:`version`、`date`、`summary`、`methods`、`notes` 5. 如 system 入参有变化,可执行: @@ -60,11 +62,11 @@ node .\script\tmp-struct-system-params.cjs ## 推荐工作流 1. 先定位代码真实实现与调用链 -2. 找到对应的 `methods/*.json` / `docs/*.md` -3. 以代码和测试结果为准更新文档 -4. 更新文档后同步追加对应的 `methods/changes/.json` 变更记录 -5. 校验 method 名称、参数、响应与代码一致 -6. 必要时验证 JSON 格式可正常解析 +2. 如 system 入参结构变化,可先执行 `node .\script\tmp-struct-system-params.cjs` +3. 按 `docs/api-doc-update-workflow.md` 生成固定 spec JSON +4. 先执行 `npm run doc:api:update -- --spec= --dry-run` +5. 确认后执行 `npm run doc:api:update -- --spec=` 写入 `methods/*.json` 与 `methods/changes/*.json` +6. 再补充 `docs/*.md` / `README.md`,并校验 method 名称、参数、响应与代码一致 ## 常用验证方式 @@ -74,6 +76,12 @@ node .\script\tmp-struct-system-params.cjs node -e "JSON.parse(require('fs').readFileSync('methods/system.json','utf8')); console.log('system.json OK')" ``` +### 通过固定 spec dry-run 校验 API 文档写入 + +```powershell +npm run doc:api:update -- --spec=temp/api-doc-update.json --dry-run +``` + ### 核对 method 是否已登记 ```powershell @@ -85,8 +93,8 @@ Select-String -Path "methods/system.json" -Pattern "storage.receiving.bindDetail ```text 请使用 wms-doc-agent 帮我: 1) 根据代码现状整理接口或业务文档 -2) 同步 methods/*.json / docs/*.md / README -3) 校验文档与实现一致 +2) 先按 docs/api-doc-update-workflow.md 生成固定 spec,再执行 npm run doc:api:update +3) 同步 docs/*.md / README,并校验文档与实现一致 ``` ## 输出要求 @@ -95,6 +103,7 @@ Select-String -Path "methods/system.json" -Pattern "storage.receiving.bindDetail - 先给结论,再给修改文件、关键字段、验证结果 - 若同步了 `methods/*.json`,明确说明 method 名称与变更点 - 若接口有变更,需说明是否已同步写入 `methods/changes/*.json` +- 若执行了文档脚本,需明确说明 spec 路径、dry-run 结果与正式写入结果 ## 结论 diff --git a/AI_TOOLBOX.md b/AI_TOOLBOX.md index 2327c12..3a849df 100644 --- a/AI_TOOLBOX.md +++ b/AI_TOOLBOX.md @@ -101,8 +101,8 @@ GitHub Copilot 读取 `.github/agents/*.agent.md`;Cursor 使用 `.cursor/agent ```text 请使用 wms-doc-agent 帮我: 1) 根据代码现状整理接口或业务文档 -2) 同步 methods/*.json / docs/*.md / README -3) 校验文档与实现一致 +2) 先按 docs/api-doc-update-workflow.md 生成固定 spec,再执行 npm run doc:api:update +3) 同步 docs/*.md / README,并校验 methods/*.json 与 methods/changes/*.json 可解析 ``` ### 3.6 混合任务 / 不确定归属(强制走 Dispatcher) @@ -196,7 +196,9 @@ Redis 相关能力文档已统一移交给 `wms-redis-agent`。 执行要求(强制): - **涉及文档编写或同步的任何问题,必须使用 `wms-doc-agent`** - 文档必须以代码实现、测试结果和现有 JSON 文档为准,不得凭空编写 -- system 参数变化可执行:`node .\script\tmp-struct-system-params.cjs` +- 默认禁止直接手写 `methods/*.json` 和 `methods/changes/*.json`;必须先按 [docs/api-doc-update-workflow.md](docs/api-doc-update-workflow.md) 组织 spec,再执行 `npm run doc:api:update -- --spec=` +- system 参数变化可先执行:`node .\script\tmp-struct-system-params.cjs` +- 正式写入前必须先执行:`npm run doc:api:update -- --spec= --dry-run` - 具体工作流统一见:`.github/agents/文档.agent.md` ## 9. 测试能力移交规则 diff --git a/README.md b/README.md index 60348dc..09584fc 100644 --- a/README.md +++ b/README.md @@ -100,14 +100,20 @@ npm run dev 建议流程: 1. 先完成代码改动(controller/service/model) -2. 同步维护 `methods/system.json` 或 `methods/qimen.json` -3. system 参数改动后执行: +2. 按 [docs/api-doc-update-workflow.md](docs/api-doc-update-workflow.md) 复制固定 spec 到 `temp/`,默认通过 `npm run doc:api:update -- --spec=...` 写入 `methods/*.json` +3. system 参数改动后可先执行: ```powershell node .\script\tmp-struct-system-params.cjs ``` -4. 补充自动提取无法覆盖的信息(description/response/errors/枚举约束) +4. 先执行: + +```powershell +npm run doc:api:update -- --spec=temp/api-doc-update.json --dry-run +``` + +5. 确认无误后执行正式写入,再补充自动提取无法覆盖的信息(description/response/errors/枚举约束) ## 配置说明 diff --git a/app.js b/app.js index a40e349..2a567d4 100644 --- a/app.js +++ b/app.js @@ -1,6 +1,7 @@ // app.js const path = require('path'); const LocalFileWriter = require('./app/lib/file_writer'); +const ensureOrderDeliverySelfCheck = require('./app/lib/order_delivery_selfcheck'); /** * 挂载应用级扩展能力。 @@ -16,30 +17,36 @@ module.exports = app => { app.logger.info('✅ fileWriter 已挂载到 app.fileWriter'); // 初始化工厂 app.beforeStart(async () => { - // skip factory init when model layer is absent (e.g. during tests) + const OrderDeliveryFactory = require('./app/model/order_delivery_factory'); + app.OrderDeliveryFactory = OrderDeliveryFactory(app); + + // skip 热区工厂 when model layer is absent (e.g. 部分单测) if (!app.model) { - app.logger.info('⚠️ skipping factory init: app.model not available'); + app.logger.info('⚠️ skipping OrderDelivery/OrderItems factory init: app.model not available'); return; } + try { - const OrderDeliveryFactory = require('./app/model/order_delivery_factory'); const OrderItemsFactory = require('./app/model/order_items_factory'); - app.OrderDeliveryFactory = OrderDeliveryFactory(app); app.model.OrderDeliveryFactory = app.OrderDeliveryFactory; app.OrderItemsFactory = OrderItemsFactory(app); app.model.OrderItemsFactory = app.OrderItemsFactory; app.logger.info('✅ 工厂类初始化完成'); + // await ensureOrderDeliverySelfCheck(app); } catch (error) { - app.logger.error('❌ 工厂类初始化失败:', error); } + // 验证缓存方法 if (typeof app.setCacheAsync === 'function') { - app.setCacheAsync('system', 'eggjs'); + await app.setCacheAsync('system', 'wms', 10); const system = await app.getCacheAsync('system'); - app.logger.info('✅ 缓存方法验证通过' + system); + if (system !== 'wms') { + app.logger.error('❌ 缓存方法验证失败: setCacheAsync/getCacheAsync 不一致'); + } else { + app.logger.info(`✅ 缓存方法验证通过${system}`); + } } - app.logger.info('✅ l类型' + typeof app.Message); }); }; diff --git a/app/controller/docs.js b/app/controller/docs.js index d6425ea..b0a247d 100644 --- a/app/controller/docs.js +++ b/app/controller/docs.js @@ -13,6 +13,97 @@ function escapeHtml(value) { .replace(/'/g, '''); } +/** + * 清洗 window 标签使用的跳转地址,避免注入危险协议或控制字符。 + * @param {string} value 待清洗的地址。 + * @return {string} 允许使用的地址,非法时返回空字符串。 + */ +function sanitizeWindowHref(value) { + const href = String(value || '').trim(); + if (!href) { + return ''; + } + + const hasControlCharacter = Array.from(href).some(character => { + const code = character.charCodeAt(0); + return code <= 0x1f || code === 0x7f; + }); + if (hasControlCharacter || /^(javascript|data|vbscript):/i.test(href)) { + return ''; + } + + return href; +} + +/** + * 从 window 标签属性中提取跳转地址。 + * @param {string} attributeText 标签属性文本。 + * @return {string} 提取到的地址,未找到时返回空字符串。 + */ +function extractWindowHref(attributeText) { + const attributes = String(attributeText || ''); + const match = attributes.match(/(?:href|data-href|data-window-href)\s*=\s*("([^"]*)"|'([^']*)')/i); + if (!match) { + return ''; + } + + return match[2] || match[3] || ''; +} + +/** + * 渲染可点击的 window 自定义元素。 + * @param {string} label 元素展示文案。 + * @param {string} href 点击后打开的地址。 + * @param {string} [className] 额外样式类名。 + * @return {string} 生成的 HTML 片段。 + */ +function renderWindowElement(label, href, className = '') { + const safeHref = sanitizeWindowHref(href); + const safeLabel = escapeHtml(label || safeHref); + if (!safeHref) { + return safeLabel; + } + + const classes = [ 'window-link' ]; + if (className) { + classes.push(className); + } + + return `${safeLabel}`; +} + +/** + * 将文本中的 标签安全渲染为可点击元素。 + * @param {string} value 原始文本。 + * @return {string} 处理后的 HTML。 + */ +function renderTextWithWindowTags(value) { + const text = String(value || ''); + if (!text.includes(']*)>([\s\S]*?)<\/window>/gi; + let lastIndex = 0; + let rendered = ''; + let match; + + while ((match = pattern.exec(text)) !== null) { + rendered += escapeHtml(text.slice(lastIndex, match.index)); + + const attributes = match[1] || ''; + const content = match[2] || ''; + const href = sanitizeWindowHref(extractWindowHref(attributes) || content.trim()); + const label = content.trim() || href; + + rendered += renderWindowElement(label, href); + lastIndex = pattern.lastIndex; + } + + rendered += escapeHtml(text.slice(lastIndex)); + return rendered; +} + function toArray(value) { return Array.isArray(value) ? value : []; } @@ -36,6 +127,302 @@ function getDocChangesFilePath(app, docName) { return path.join(app.baseDir, 'methods', 'changes', `${docName}.json`); } +/** + * 获取 docs 目录的绝对路径。 + * @param {Egg.Application} app Egg 应用实例。 + * @return {string} docs 根目录绝对路径。 + */ +function getDocsRootPath(app) { + return path.resolve(app.baseDir, 'docs'); +} + +/** + * 递归解码 URL 路径片段,尽量还原编码穿越路径。 + * @param {string} input 待解码的路径片段。 + * @return {string|null} 解码后的路径片段,解码失败时返回 null。 + */ +function decodeDocsPath(input) { + let value = String(input || '').trim(); + if (!value) { + return ''; + } + + for (let index = 0; index < 3; index += 1) { + try { + const decoded = decodeURIComponent(value); + if (decoded === value) { + break; + } + value = decoded; + } catch (error) { + return null; + } + } + + return value; +} + +/** + * 将 docs 相对路径转换为可访问 URL。 + * @param {string} relativePath docs 相对路径。 + * @return {string} 可直接用于 href 的路径。 + */ +function toDocsHref(relativePath) { + return String(relativePath || '') + .split(/[\\/]+/) + .filter(Boolean) + .map(segment => encodeURIComponent(segment)) + .join('/'); +} + +/** + * 按扩展名返回 docs 文件的响应类型。 + * @param {string} filePath 文件绝对路径。 + * @return {string} Content-Type 值。 + */ +function getDocsContentType(filePath) { + const ext = path.extname(filePath).toLowerCase(); + if (ext === '.md' || ext === '.markdown') { + return 'text/markdown; charset=utf-8'; + } + + if (ext === '.json') { + return 'application/json; charset=utf-8'; + } + + return 'text/plain; charset=utf-8'; +} + +/** + * 解析并校验 docs 文件路径,阻止路径穿越。 + * @param {Egg.Application} app Egg 应用实例。 + * @param {string} relativePath docs 相对路径。 + * @return {{ ok: boolean, filePath?: string, relativePath?: string, message?: string }} 解析结果。 + */ +function resolveDocsFilePath(app, relativePath) { + const decodedPath = decodeDocsPath(relativePath); + if (decodedPath === null || !decodedPath) { + return { + ok: false, + message: '无效文档路径', + }; + } + + if (decodedPath.includes('\\') || path.isAbsolute(decodedPath)) { + return { + ok: false, + message: '无效文档路径', + }; + } + + const docsRootPath = getDocsRootPath(app); + const filePath = path.resolve(docsRootPath, decodedPath); + const relativeToRoot = path.relative(docsRootPath, filePath); + + if (relativeToRoot.startsWith('..') || path.isAbsolute(relativeToRoot)) { + return { + ok: false, + message: '路径越界', + }; + } + + return { + ok: true, + filePath, + relativePath: decodedPath, + }; +} + +/** + * 递归收集 docs 目录下的所有文件。 + * @param {string} dirPath 当前扫描目录。 + * @param {string} baseDir docs 根目录。 + * @return {Promise>} 文件列表。 + */ +async function collectDocsFiles(dirPath, baseDir) { + const entries = await fs.readdir(dirPath, { withFileTypes: true }); + const files = []; + + for (const entry of entries) { + const entryPath = path.join(dirPath, entry.name); + if (entry.isDirectory()) { + const nestedFiles = await collectDocsFiles(entryPath, baseDir); + files.push(...nestedFiles); + continue; + } + + if (entry.isFile()) { + files.push({ + relativePath: path.relative(baseDir, entryPath), + filePath: entryPath, + }); + } + } + + return files; +} + +/** + * 生成 docs 索引页 HTML。 + * @param {Array<{ relativePath: string }>} files docs 文件列表。 + * @return {string} HTML 文档。 + */ +function renderDocsIndexPage(files) { + const listHtml = files.length + ? files.map(file => { + const href = `/docs/${toDocsHref(file.relativePath)}`; + return `
  • ${renderWindowElement(file.relativePath, href, 'doc-file-link')}
  • `; + }).join('') + : '
  • docs 目录下暂无文件
  • '; + + return ` + + + + + Docs 索引 + + + +
    +
    +

    docs 目录索引

    +

    以下文件来自 docs 根目录,点击即可直接查看对应内容。

    +
      ${listHtml}
    +
    +
    + + +`; +} + +/** + * 生成 docs 文件内容响应。 + * @param {Egg.Context} ctx 当前请求上下文。 + * @param {string} filePath 文件绝对路径。 + * @return {Promise} 无返回值。 + */ +async function sendDocsFile(ctx, filePath) { + const content = await fs.readFile(filePath, 'utf8'); + ctx.set('Content-Type', getDocsContentType(filePath)); + ctx.body = content; +} + function normalizeGroups(docData) { if (docData && docData.methods && Array.isArray(docData.methods.groups)) { return docData.methods.groups.map(group => ({ @@ -56,6 +443,12 @@ function normalizeGroups(docData) { return []; } +/** + * 渲染键值表格。 + * @param {Array} items 数据项列表。 + * @param {{ name: string, type: string, required: string, description: string }} keyMap 字段映射。 + * @return {string} 表格行 HTML。 + */ function renderKeyValueRows(items, keyMap) { if (!items.length) { return '暂无数据'; @@ -66,11 +459,16 @@ function renderKeyValueRows(items, keyMap) { ${escapeHtml(item[keyMap.name] || '')} ${escapeHtml(item[keyMap.type] || '')} ${item[keyMap.required] ? '是' : '否'} - ${escapeHtml(item[keyMap.description] || '')} + ${renderTextWithWindowTags(item[keyMap.description] || '')} `; }).join(''); } +/** + * 渲染全局 Header 控件区域。 + * @param {Array} globalHeaders 全局 Header 定义。 + * @return {string} HTML 片段。 + */ function renderGlobalHeadersControls(globalHeaders) { const headers = toArray(globalHeaders); if (!headers.length) { @@ -94,11 +492,18 @@ function renderGlobalHeadersControls(globalHeaders) { return ``; }).join('')}`; } +/** + * 渲染单个接口卡片。 + * @param {object} item 接口定义。 + * @param {string} entryPath 统一入口路径。 + * @param {string} moduleName 文档所属模块名。 + * @return {string} HTML 片段。 + */ function renderMethodCard(item, entryPath, moduleName) { const headers = toArray(item.headers); const params = toArray(item.params); @@ -115,7 +520,7 @@ function renderMethodCard(item, entryPath, moduleName) {

    ${escapeHtml(methodName)}

    -

    ${escapeHtml(description)}

    +

    ${renderTextWithWindowTags(description)}

    入口: ${escapeHtml(entryPath)} @@ -196,6 +601,11 @@ function renderMethodCard(item, entryPath, moduleName) { `; } +/** + * 渲染 API 文档页面。 + * @param {{ docName: string, docData: object, groups: Array, docs: Array, entryPath: string }} options 渲染参数。 + * @return {string} HTML 文档。 + */ function renderHtmlPage({ docName, docData, @@ -446,6 +856,20 @@ function renderHtmlPage({ background: #eef5ff; color: #123e79; } + .window-link { + display: inline-flex; + align-items: center; + gap: 4px; + cursor: pointer; + user-select: none; + } + .window-link:hover { + text-decoration: underline; + } + .window-link:focus { + outline: 2px solid #8fb4ea; + outline-offset: 2px; + } .doc-content { min-width: 0; } @@ -590,8 +1014,8 @@ function renderHtmlPage({

    文档资源

    - 打开变更记录 - 打开原文 JSON + ${renderWindowElement('打开变更记录', changesUrl, 'doc-resource-link')} + ${renderWindowElement('打开原文 JSON', rawUrl, 'doc-resource-link')}
    @@ -633,6 +1057,19 @@ function renderHtmlPage({ var changesUrl = ${JSON.stringify(changesUrl)}; var rawUrl = ${JSON.stringify(rawUrl)}; + function openWindowHref(target) { + var href = target && target.getAttribute('data-window-href'); + if (!href) { + return; + } + + var popup = window.open(href, '_blank', 'noopener,noreferrer'); + if (popup) { + popup.opener = null; + popup.focus(); + } + } + function nowTimestamp() { return Math.floor(Date.now() / 1000); } @@ -850,6 +1287,30 @@ function renderHtmlPage({ }); } + document.addEventListener('click', function(event) { + var target = event.target.closest('[data-window-href]'); + if (!target) { + return; + } + + event.preventDefault(); + openWindowHref(target); + }); + + document.addEventListener('keydown', function(event) { + var target = event.target.closest('[data-window-href]'); + if (!target) { + return; + } + + if (event.key !== 'Enter' && event.key !== ' ') { + return; + } + + event.preventDefault(); + openWindowHref(target); + }); + document.addEventListener('click', async function(event) { var btn = event.target.closest('.send-btn'); if (!btn) return; @@ -927,6 +1388,68 @@ function renderHtmlPage({ } class DocsController extends Controller { + /** + * 返回 docs 目录索引页面。 + * @return {Promise} 无返回值。 + */ + async docsIndex() { + const { ctx } = this; + + try { + const docsRootPath = getDocsRootPath(this.app); + const files = await collectDocsFiles(docsRootPath, docsRootPath); + files.sort((left, right) => left.relativePath.localeCompare(right.relativePath, 'zh-Hans-CN')); + ctx.set('Content-Type', 'text/html; charset=utf-8'); + ctx.body = renderDocsIndexPage(files); + } catch (error) { + ctx.status = 500; + ctx.body = { + code: 500, + message: '读取 docs 目录失败', + error: error.message, + }; + } + } + + /** + * 读取 docs 目录下的指定文件。 + * @return {Promise} 无返回值。 + */ + async docsFile() { + const { ctx } = this; + const rawRelativePath = ctx.params[0] || ctx.params.relPath || ctx.params.path || ''; + const resolved = resolveDocsFilePath(this.app, rawRelativePath); + + if (!resolved.ok) { + ctx.status = 400; + ctx.body = { + code: 400, + message: resolved.message || '无效文档路径', + }; + return; + } + + try { + await sendDocsFile(ctx, resolved.filePath); + } catch (error) { + if (error.code === 'ENOENT') { + ctx.status = 404; + ctx.body = { + code: 404, + message: `未找到 docs 文件: ${resolved.relativePath}`, + }; + return; + } + + ctx.status = 500; + ctx.body = { + code: 500, + message: '读取 docs 文件失败', + error: error.message, + }; + } + } + async list() { const { ctx } = this; try { diff --git a/app/controller/home.js b/app/controller/home.js index c3d192c..f6e9df3 100644 --- a/app/controller/home.js +++ b/app/controller/home.js @@ -9,12 +9,39 @@ class HomeController extends Controller { await this.ctx.service.systems.print.index.test(); this.ctx.body = 'ok'; } + /** + * Polo API 测试入口,直接透传 PoloApiService.test() 的真实返回结果。 + * + * @return {Promise} 无返回值,响应结果直接写入 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, } = this; ctx.body = 'pong'; } + /** + * 处理奇门统一入口请求,完成参数校验、XML 解析、仓库编码提取与方法分发。 + * @return {Promise} 无返回值。 + */ async qimen() { const { ctx, @@ -97,7 +124,16 @@ class HomeController extends Controller { // 解析XML数据 const xmlArray = await service.qimen.parseXmlToArray(xmlData); xmlArray.app_key = appkey; - let warehouseCode = xmlArray.request.warehouseCode || ''; + const warehouseCode = this.getQimenWarehouseCode(xmlArray); + + if (!warehouseCode) { + const errorMsg = 'XML数据格式错误,无法提取有效的warehouseCode'; + const responseFormat = getParams.format || 'xml'; + const response = this.errorResponse(errorMsg, responseFormat); + ctx.body = response; + ctx.type = responseFormat === 'xml' ? 'application/xml' : 'application/json'; + return; + } logData.body = xmlData; const erpName = await service.qimen.getErpName(appkey); @@ -105,16 +141,6 @@ class HomeController extends Controller { warehouseCode: '', ownerCode: '', }; - if (!warehouseCode || !customerId) { - // 入库单提取 - try { - warehouseCode = xmlArray.request?.entryOrder?.warehouseCode || - xmlArray.request?.deliveryOrder?.warehouseCode || - ''; - } catch (e) { - throw new Error('XML数据格式错误,无法提取warehouseCode'); - } - } if (warehouseCode && customerId) { // 验证接口是否存在且启用 api_info = await service.qimen.validateApi(appkey, customerId, warehouseCode); @@ -187,6 +213,116 @@ class HomeController extends Controller { } } + /** + * 归一化奇门字段值,过滤空白内容和占位符字符串。 + * @param {string|number|null|undefined} value 待处理字段值。 + * @return {string} 归一化后的字段值。 + */ + normalizeQimenFieldValue(value) { + if (value === null || value === undefined) { + return ''; + } + + const normalizedValue = String(value).trim(); + if (!normalizedValue || normalizedValue === 'warehouseCode') { + return ''; + } + + return normalizedValue; + } + + /** + * 递归扫描奇门 XML 树,提取指定字段的有效值,只匹配字段名对应的节点。 + * @param {Object|Array|string|number|null|undefined} node 待扫描节点。 + * @param {string} fieldName 目标字段名。 + * @param {Set} [visited=new Set()] 循环引用保护集合。 + * @return {string} 找到的有效字段值。 + */ + findQimenFieldValue(node, fieldName, visited = new Set()) { + if (node === null || node === undefined) { + return ''; + } + + if (typeof node !== 'object') { + return ''; + } + + if (visited.has(node)) { + return ''; + } + + visited.add(node); + + if (Array.isArray(node)) { + for (const item of node) { + const value = this.findQimenFieldValue(item, fieldName, visited); + if (value) { + return value; + } + } + return ''; + } + + if (Object.prototype.hasOwnProperty.call(node, fieldName)) { + const directValue = this.normalizeQimenFieldValue(node[fieldName]); + if (directValue) { + return directValue; + } + + const nestedValue = this.findQimenFieldValue(node[fieldName], fieldName, visited); + if (nestedValue) { + return nestedValue; + } + } + + for (const [ key, value ] of Object.entries(node)) { + if (key === fieldName) { + continue; + } + + if (value === null || value === undefined) { + continue; + } + + if (typeof value !== 'object') { + continue; + } + + const foundValue = this.findQimenFieldValue(value, fieldName, visited); + if (foundValue) { + return foundValue; + } + } + + return ''; + } + + /** + * 从奇门请求体中提取有效的仓库编码,优先读取 request 下的固定路径,再回退到递归扫描。 + * @param {Object} xmlArray 解析后的 XML 数据。 + * @return {string} 有效的仓库编码。 + */ + getQimenWarehouseCode(xmlArray) { + const request = xmlArray?.request || xmlArray || {}; + + const fixedPaths = [ + request?.deliveryOrder?.warehouseCode, + request?.entryOrder?.warehouseCode, + request.warehouseCode, + ]; + + for (const value of fixedPaths) { + const normalizedValue = this.normalizeQimenFieldValue(value); + if (normalizedValue) { + return normalizedValue; + } + } + + return this.findQimenFieldValue(request, 'warehouseCode') + || this.findQimenFieldValue(xmlArray, 'warehouseCode') + || ''; + } + validateParams(params) { const required = [ 'method', 'v', 'format', 'timestamp' ]; diff --git a/app/extend/application.js b/app/extend/application.js index e3c55da..837fd75 100644 --- a/app/extend/application.js +++ b/app/extend/application.js @@ -1,5 +1,219 @@ const soap = require('soap'); const businessDict = require('../dict/businessDict'); + +const LOCAL_CACHE_CLEANUP_INTERVAL_MS = 60 * 1000; +const LOCAL_CACHE_STATE_KEY = '__wmsLocalCacheState'; + +/** + * 获取缓存日志记录器。 + * + * @param {Object} app 应用实例。 + * @return {Object|null} 日志对象。 + */ +function getCacheLogger(app) { + return app && (app.logger || app.coreLogger) ? (app.logger || app.coreLogger) : null; +} + +/** + * 获取或初始化进程内缓存状态。 + * + * @param {Object} app 应用实例。 + * @return {Object|null} 进程内缓存状态。 + */ +function getLocalCacheState(app) { + if (!app) { + return null; + } + + if (!app[LOCAL_CACHE_STATE_KEY]) { + app[LOCAL_CACHE_STATE_KEY] = { + store: new Map(), + cleanupTimer: null, + lastCleanupAt: 0, + }; + } + + return app[LOCAL_CACHE_STATE_KEY]; +} + +/** + * 规范化缓存过期秒数。 + * + * @param {*} expireSeconds 过期秒数。 + * @return {number} 规范化后的秒数。 + */ +function normalizeExpireSeconds(expireSeconds) { + const ttl = Number(expireSeconds); + if (!Number.isFinite(ttl) || ttl <= 0) { + return 0; + } + return Math.floor(ttl); +} + +/** + * 复制缓存值,避免进程内缓存被外部引用直接修改。 + * + * @param {*} value 缓存值。 + * @return {*} 复制后的缓存值。 + */ +function cloneCacheValue(value) { + if (value === null || value === undefined) { + return value; + } + + try { + return JSON.parse(JSON.stringify(value)); + } catch (error) { + return value; + } +} + +/** + * 清理已经过期的进程内缓存。 + * + * @param {Object} state 进程内缓存状态。 + * @return {number} 清理的条目数。 + */ +function cleanupLocalCache(state) { + if (!state || !state.store) { + return 0; + } + + const now = Date.now(); + let removedCount = 0; + + for (const [ cacheKey, cacheEntry ] of state.store.entries()) { + if (!cacheEntry || cacheEntry.expireAt <= now) { + state.store.delete(cacheKey); + removedCount += 1; + } + } + + state.lastCleanupAt = now; + return removedCount; +} + +/** + * 启动进程内缓存的定时清理任务。 + * + * @param {Object} app 应用实例。 + * @return {Object|null} 进程内缓存状态。 + */ +function ensureLocalCacheCleanupTimer(app) { + const state = getLocalCacheState(app); + if (!state || state.cleanupTimer) { + return state; + } + + state.cleanupTimer = setInterval(() => { + cleanupLocalCache(state); + }, LOCAL_CACHE_CLEANUP_INTERVAL_MS); + + if (state.cleanupTimer && typeof state.cleanupTimer.unref === 'function') { + state.cleanupTimer.unref(); + } + + return state; +} + +/** + * 获取 Redis 缓存客户端。 + * + * @param {Object} app 应用实例。 + * @return {Object|null} Redis 缓存客户端。 + */ +function getRedisCacheClient(app) { + try { + return app && app.redis && typeof app.redis.get === 'function' ? app.redis.get('cache') : null; + } catch (error) { + const logger = getCacheLogger(app); + if (logger && typeof logger.warn === 'function') { + logger.warn('[CacheRedisUnavailable] 获取 Redis 缓存客户端失败', error.message); + } + return null; + } +} + +/** + * 将值写入进程内缓存。 + * + * @param {Object} app 应用实例。 + * @param {string} cacheKey 缓存键。 + * @param {*} data 缓存数据。 + * @param {number} expireSeconds 过期秒数。 + */ +function setLocalCacheValue(app, cacheKey, data, expireSeconds) { + const state = ensureLocalCacheCleanupTimer(app); + if (!state) { + return; + } + + const ttl = normalizeExpireSeconds(expireSeconds); + if (ttl <= 0) { + state.store.delete(cacheKey); + return; + } + + state.store.set(cacheKey, { + value: cloneCacheValue(data), + expireAt: Date.now() + (ttl * 1000), + }); +} + +/** + * 从进程内缓存读取值。 + * + * @param {Object} app 应用实例。 + * @param {string} cacheKey 缓存键。 + * @return {*} 缓存值或 null。 + */ +function getLocalCacheValue(app, cacheKey) { + const state = getLocalCacheState(app); + if (!state) { + return null; + } + + const cacheEntry = state.store.get(cacheKey); + if (!cacheEntry) { + return null; + } + + if (cacheEntry.expireAt <= Date.now()) { + state.store.delete(cacheKey); + return null; + } + + return cloneCacheValue(cacheEntry.value); +} + +/** + * 从进程内缓存删除值。 + * + * @param {Object} app 应用实例。 + * @param {string} cacheKey 缓存键。 + */ +function deleteLocalCacheValue(app, cacheKey) { + const state = getLocalCacheState(app); + if (!state) { + return; + } + + state.store.delete(cacheKey); +} + +/** + * 将 Redis 返回的数据解析为对象。 + * + * @param {string} cacheValue Redis 缓存字符串。 + * @return {*} 解析后的值。 + */ +function parseRedisCacheValue(cacheValue) { + if (cacheValue === undefined || cacheValue === null) { + return null; + } + + return JSON.parse(cacheValue); +} module.exports = { get businessDict() { return businessDict; @@ -50,40 +264,83 @@ module.exports = { const result = await client[methodName + 'Async'](obj); return result[0]; } catch (error) { - console.error('Error calling SOAP service:', error); throw error; } }, + /** + * 写入缓存。 + * + * Redis 可用时优先写入 Redis;当 Redis 不可用或写入失败时,自动降级到进程内缓存。 + * + * @param {string} cacheKey 缓存键。 + * @param {*} data 缓存数据。 + * @param {number} [expireSeconds=300] 过期秒数。 + * @return {Promise} + */ async setCacheAsync(cacheKey, data, expireSeconds = 300) { - const cacheRedis = this.redis && this.redis.get ? this.redis.get('cache') : null; - if (!cacheRedis) { - this.logger.warn('[RedisNotAvailable] Cannot set cache, Redis client is not available'); + const ttl = normalizeExpireSeconds(expireSeconds); + const cacheRedis = getRedisCacheClient(this); + + if (ttl <= 0) { + if (cacheRedis && typeof cacheRedis.del === 'function') { + try { + await cacheRedis.del(cacheKey); + } catch (error) { + const logger = getCacheLogger(this); + if (logger && typeof logger.warn === 'function') { + logger.warn('[CacheRedisDeleteError] Redis 删除缓存失败', error.message, cacheKey); + } + } + } + + deleteLocalCacheValue(this, cacheKey); return; } - try { - await cacheRedis.setex(cacheKey, expireSeconds, JSON.stringify(data)); - this.logger.debug('[CacheSet] Successfully set cache', cacheKey); - } catch (error) { - this.logger.error('[CacheSetError] Failed to set cache', error.message, cacheKey); - } - }, - async getCacheAsync(cacheKey) { - const cacheRedis = this.redis && this.redis.get ? this.redis.get('cache') : null; - if (!cacheRedis) { - this.logger.warn('[RedisNotAvailable] Cannot get cache, Redis client is not available'); - return null; + if (cacheRedis && typeof cacheRedis.setex === 'function') { + try { + await cacheRedis.setex(cacheKey, ttl, JSON.stringify(data)); + + setLocalCacheValue(this, cacheKey, data, ttl); + + return; + } catch (error) { + const logger = getCacheLogger(this); + if (logger && typeof logger.warn === 'function') { + logger.warn('[CacheRedisSetError] Redis 写入缓存失败,已降级到进程内缓存', error.message, cacheKey); + } + } } - try { - const data = await cacheRedis.get(cacheKey); - if (data) { - return JSON.parse(data); + setLocalCacheValue(this, cacheKey, data, ttl); + }, + /** + * 读取缓存。 + * + * Redis 可用时优先读取 Redis;当 Redis 不可用、读取失败或命中为空时,自动回退到进程内缓存。 + * + * @param {string} cacheKey 缓存键。 + * @return {Promise<*>} 缓存数据,未命中时返回 null。 + */ + async getCacheAsync(cacheKey) { + const cacheRedis = getRedisCacheClient(this); + + if (cacheRedis && typeof cacheRedis.get === 'function') { + try { + const data = await cacheRedis.get(cacheKey); + if (data === undefined || data === null) { + return null; + } + + return parseRedisCacheValue(data); + } catch (error) { + const logger = getCacheLogger(this); + if (logger && typeof logger.warn === 'function') { + logger.warn('[CacheRedisGetError] Redis 读取缓存失败,已回退到进程内缓存', error.message, cacheKey); + } } - return null; - } catch (error) { - this.logger.error('[CacheGetError] Failed to get cache', error.message, cacheKey); - return null; } + + return getLocalCacheValue(this, cacheKey); }, }; diff --git a/app/lib/order_delivery_selfcheck.js b/app/lib/order_delivery_selfcheck.js new file mode 100644 index 0000000..d7cd83b --- /dev/null +++ b/app/lib/order_delivery_selfcheck.js @@ -0,0 +1,19 @@ +'use strict'; + +/** + * 在应用启动阶段触发订单发货表的 managed table schema 自检。 + * @param {import('egg').Application} app 应用实例。 + * @return {Promise} + */ +module.exports = async app => { + if (!app || !app.OrderDeliveryFactory) { + return; + } + + if (typeof app.OrderDeliveryFactory.ensureManagedTableSchemas !== 'function') { + return; + } + + await app.OrderDeliveryFactory.ensureManagedTableSchemas(); + app.logger.info('✅ 订单工厂目标表自检完成'); +}; diff --git a/app/lib/polo_api_client.js b/app/lib/polo_api_client.js new file mode 100644 index 0000000..bc98b93 --- /dev/null +++ b/app/lib/polo_api_client.js @@ -0,0 +1,253 @@ +'use strict'; + +const crypto = require('crypto'); + +const POLYAPI_CONFIG_CACHE_KEY = 'polo_api_client:polyapi:config'; +const POLYAPI_CONFIG_CACHE_TTL_SECONDS = 60 * 60; + +/** + * PolyAPI 底层 HTTP 客户端。 + * 封装签名、表单编码、请求发送等通用逻辑,与业务无关。 + */ +class PoloApiClient { + /** + * @param {object} ctx - Egg 上下文对象。 + */ + constructor(ctx) { + this.ctx = ctx; + this._config = null; + this._configPromise = null; + this.contenttype = 'json'; + } + + /** + * 按需加载并缓存 PolyAPI 配置。 + * + * 优先读取应用级缓存;缓存未命中或读取失败时,再回源数据库。 + * 数据库查到配置后,会回写到应用级缓存,缓存 TTL 为 1 小时。 + * + * @param platid + * @return {Promise} 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} 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} 缓存中的配置记录。 + */ + 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} 数据库中的配置记录。 + */ + async _loadConfigFromDatabase(platid) { + if (!this.ctx.app || !this.ctx.app.model || !this.ctx.app.model.ExpressPlatform || typeof this.ctx.app.model.ExpressPlatform.findOne !== 'function') { + return null; + } + + return await this.ctx.app.model.ExpressPlatform.findOne({ + where: { platid }, + }); + } + + /** + * 将 PolyAPI 配置写回应用级缓存。 + * + * @param {object} config - PolyAPI 配置记录。 + * @return {Promise} + */ + 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 请求。 + * + * @param {object} options - 请求参数。 + * @param {string} options.method - 远端接口方法名。 + * @param {number|string} options.platid - 平台 ID。 + * @param {object|string} [options.bizcontent={}] - 业务参数内容。 + * @return {Promise} 接口响应 data。 + */ + async request(options = {}) { + const { + method, + platid, + bizcontent = {}, + } = options; + + let config = await this.getConfig(platid); + if (!config) { + // throw new Error('未找到 polyapi 配置'); + config = await this.getConfig(633); + } + + const signMap = this._buildSignMap(config, method, platid, bizcontent); + const signText = this._getSignText(signMap, config.app_secret); + const sign = this._md5(signText.toLowerCase()); + const formBody = this._encodeForm({ ...signMap, sign }); + + const response = await this.ctx.curl(String(config.interface_url || ''), { + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36', + }, + content: formBody, + }); + + return response && response.data !== undefined ? response.data : null; + } + + // ── 内部方法 ── + + /** + * 组装签名所需的请求参数。 + * @param config + * @param method + * @param platid + * @param bizcontent + */ + _buildSignMap(config, method, platid, bizcontent) { + const normalizedBizcontent = bizcontent && typeof bizcontent === 'object' + ? JSON.stringify(bizcontent) + : (bizcontent === undefined || bizcontent === null ? '' : bizcontent); + + return { + method, + appkey: config.appkey, + token: config.token, + platid, + version: config.version, + contenttype: this.contenttype, + bizcontent: normalizedBizcontent, + timestamp: this._formatDate(new Date()), + }; + } + + /** + * 生成签名原文 = secret + key1value1 + key2value2 ... + secret(按 key 字母序)。 + * @param signMap + * @param secret + */ + _getSignText(signMap, secret) { + let sb = '' + secret; + Object.keys(signMap).sort().forEach(key => { + sb += key + signMap[key]; + }); + sb += secret; + return sb; + } + + /** + * MD5 摘要。 + * @param text + * @param encoding + */ + _md5(text, encoding = 'utf8') { + return crypto.createHash('md5').update(text, encoding).digest('hex'); + } + + /** + * 将参数编码为 application/x-www-form-urlencoded。 + * @param map + */ + _encodeForm(map) { + const params = new URLSearchParams(); + for (const key of Object.keys(map)) { + const v = map[key]; + params.append(key, v === undefined || v === null ? '' : (typeof v === 'object' ? JSON.stringify(v) : String(v))); + } + return params.toString(); + } + + /** + * 格式化日期 → yyyy-MM-dd HH:mm:ss。 + * @param date + */ + _formatDate(date) { + const pad = n => (n < 10 ? '0' + n : n); + return date.getFullYear() + '-' + pad(date.getMonth() + 1) + '-' + pad(date.getDate()) + ' ' + + pad(date.getHours()) + ':' + pad(date.getMinutes()) + ':' + pad(date.getSeconds()); + } + + /** + * 格式化取件日期。 + * @param year + * @param month + * @param day + */ + _formatPickupDate(year, month, day) { + const pad = n => (n < 10 ? '0' + n : n); + return `${year}-${pad(month)}-${pad(day)} 18:00:00`; + } +} + +module.exports = PoloApiClient; diff --git a/app/lib/warehouse_shard_guard.js b/app/lib/warehouse_shard_guard.js new file mode 100644 index 0000000..27313e1 --- /dev/null +++ b/app/lib/warehouse_shard_guard.js @@ -0,0 +1,93 @@ +'use strict'; + +const MAX_DECIMAL_DIGITS = 20; + +/** + * 将分表用的仓库 ID 规范为纯十进制数字串(与 wms_store.id / BIGINT 一致)。 + * @param {*} value 待规范化的仓库 ID。 + * @return {string} 规范化后的仓库 ID 字符串。 + */ +function normalizeWarehouseShardId(value) { + if (value === null || value === undefined || value === '') { + throw new Error('warehouse_id 不能为空'); + } + if (typeof value === 'object') { + throw new Error('warehouse_id 必须为数字'); + } + const s = String(value).trim(); + if (!/^\d+$/.test(s)) { + throw new Error('warehouse_id 必须为数字'); + } + if (s === '0') { + throw new Error('warehouse_id 非法'); + } + if (s.length > MAX_DECIMAL_DIGITS) { + throw new Error('warehouse_id 超出范围'); + } + return s; +} + +/** + * 校验 wms_store 中存在对应 ID 且主体为仓库(project = warehouse)。 + * @param {import('egg').Application} app 应用实例。 + * @param {string} warehouseIdStr normalizeWarehouseShardId 的返回值。 + * @return {Promise} + */ +async function assertWarehouseStoreSubject(app, warehouseIdStr) { + if (!app.model || !app.model.Store) { + return; + } + const row = await app.model.Store.findOne({ + where: { + id: warehouseIdStr, + project: 'warehouse', + }, + attributes: [ 'id' ], + paranoid: true, + }); + if (!row) { + throw new Error(`仓库主体不存在或非仓库类型(wms_store.project 须为 warehouse): ${warehouseIdStr}`); + } +} + +function validatedSetFor(app) { + if (!app._shardWarehouseIdsValidated) { + app._shardWarehouseIdsValidated = new Set(); + } + return app._shardWarehouseIdsValidated; +} + +/** + * 规范化并校验仓库分表 ID。 + * @param {import('egg').Application} app 应用实例。 + * @param {*} raw 原始仓库 ID。 + * @return {Promise} 规范化并校验后的仓库 ID 字符串。 + */ +async function ensureShardWarehouseId(app, raw) { + const idStr = normalizeWarehouseShardId(raw); + const validatedSet = validatedSetFor(app); + if (validatedSet.has(idStr)) { + return idStr; + } + await assertWarehouseStoreSubject(app, idStr); + validatedSet.add(idStr); + return idStr; +} + +/** + * 清理进程内「已校验仓库主体」缓存(例如单测或手动 clear 动态模型缓存时)。 + * @param {import('egg').Application} app 应用实例。 + * @return {void} + */ +function clearShardWarehouseValidationCache(app) { + if (app && app._shardWarehouseIdsValidated) { + app._shardWarehouseIdsValidated.clear(); + } +} + +module.exports = { + normalizeWarehouseShardId, + assertWarehouseStoreSubject, + ensureShardWarehouseId, + clearShardWarehouseValidationCache, +}; diff --git a/app/model/express.js b/app/model/express.js index bda9b96..7fc619b 100644 --- a/app/model/express.js +++ b/app/model/express.js @@ -1,7 +1,7 @@ 'use strict'; module.exports = app => { - const { STRING } = app.Sequelize; + const { STRING, JSON } = app.Sequelize; const Express = app.model.define('express', { code: { @@ -15,11 +15,27 @@ module.exports = app => { allowNull: true, comment: '快递名称', }, + polyapi_code: { + type: STRING(255), + allowNull: true, + comment: '聚合接口编码', + }, + polyapi_extra_info: { + type: JSON, + allowNull: true, + comment: '聚合接口扩展信息', + }, + pdd_code: { + type: STRING(255), + allowNull: true, + comment: '拼多多编码', + }, }, { tableName: 'wms_express', freezeTableName: true, underscored: true, timestamps: false, + paranoid: false, comment: '快递基础信息表', }); diff --git a/app/model/express_interface.js b/app/model/express_interface.js new file mode 100644 index 0000000..267ee5b --- /dev/null +++ b/app/model/express_interface.js @@ -0,0 +1,132 @@ +'use strict'; + +module.exports = app => { + const { INTEGER, STRING, BIGINT, TINYINT } = app.Sequelize; + + const ExpressInterface = app.model.define('express_interface', { + id: { + type: INTEGER(11).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + name: { + type: STRING(255), + allowNull: true, + comment: '接口名称', + }, + express_code: { + type: STRING(255), + allowNull: true, + comment: '快递编码', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '仓库编码', + }, + platform_code: { + type: STRING(20), + allowNull: true, + comment: '平台id', + }, + express_platform_id: { + type: INTEGER(11), + allowNull: true, + comment: '快递接口id', + }, + sender_name: { + type: STRING(50), + allowNull: true, + comment: '寄件人', + }, + sender_tel: { + type: STRING(11), + allowNull: true, + comment: '寄件电话', + }, + weight: { + type: INTEGER(11), + allowNull: true, + comment: '排序', + }, + token: { + type: STRING(500), + allowNull: true, + comment: '令牌', + }, + viewer: { + type: STRING(50), + allowNull: true, + comment: '验视员', + }, + client_id: { + type: STRING(50), + allowNull: true, + comment: '客户id', + }, + is_share: { + type: TINYINT(1), + allowNull: true, + defaultValue: 0, + comment: '是否分享接口', + }, + share_id: { + type: INTEGER(11).UNSIGNED, + allowNull: true, + comment: '分享id', + }, + can_use_count: { + type: INTEGER(11), + allowNull: true, + defaultValue: 0, + comment: '可用数量', + }, + province_name: { + type: STRING(255), + allowNull: true, + comment: '寄件人名称', + }, + city_name: { + type: STRING(255), + allowNull: true, + comment: '寄件人城市', + }, + district_name: { + type: STRING(255), + allowNull: true, + comment: '寄件人区/县', + }, + site_code: { + type: STRING(255), + allowNull: true, + comment: '网点编码', + }, + product_type: { + type: STRING(50), + allowNull: true, + comment: '产品编码', + }, + shop_name: { + type: STRING(255), + allowNull: true, + comment: '平台店铺', + }, + }, { + tableName: 'wms_express_interface', + freezeTableName: true, + underscored: true, + timestamps: false, + paranoid: false, + comment: '快递接口配置表', + indexes: [ + { + name: 'idx_warehouse_id', + fields: [ 'warehouse_id' ], + }, + ], + }); + + return ExpressInterface; +}; diff --git a/app/model/express_platform.js b/app/model/express_platform.js new file mode 100644 index 0000000..ddc2993 --- /dev/null +++ b/app/model/express_platform.js @@ -0,0 +1,75 @@ +'use strict'; + +module.exports = app => { + const { INTEGER, STRING } = app.Sequelize; + + const ExpressPlatform = app.model.define('express_platform', { + id: { + type: INTEGER(10), + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '接口ID', + }, + interface_url: { + type: STRING(500), + allowNull: false, + comment: '外部接口URL', + }, + platform_code: { + type: STRING(50), + allowNull: false, + comment: '平台代码,用于应用分流', + }, + interface_name: { + type: STRING(200), + allowNull: false, + comment: '接口名称', + }, + platid: { + type: STRING(20), + allowNull: true, + comment: '菠萝派平台id', + }, + appkey: { + type: STRING(100), + allowNull: true, + comment: '应用Key', + }, + app_secret: { + type: STRING(255), + allowNull: true, + field: 'app_secret', + comment: '应用密钥', + }, + token: { + type: STRING(255), + allowNull: true, + comment: '访问令牌', + }, + version: { + type: STRING(20), + allowNull: true, + comment: '接口版本', + }, + }, { + tableName: 'wms_express_platform', + freezeTableName: true, + underscored: true, + timestamps: false, + paranoid: false, + comment: '快递外部接口配置表', + indexes: [ + { + name: 'idx_platform_code', + fields: [ 'platform_code' ], + }, + { + name: 'idx_interface_name', + fields: [ 'interface_name' ], + }, + ], + }); + + return ExpressPlatform; +}; diff --git a/app/model/express_product_type.js b/app/model/express_product_type.js new file mode 100644 index 0000000..d26a0c8 --- /dev/null +++ b/app/model/express_product_type.js @@ -0,0 +1,44 @@ +'use strict'; + +/** + * 定义快递产品类型模型。 + * @param {Object} app Egg 应用对象。 + * @return {Object} 快递产品类型模型。 + */ +module.exports = app => { + const { INTEGER, STRING } = app.Sequelize; + + const ExpressProductType = app.model.define('express_product_type', { + id: { + type: INTEGER(11).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + name: { + type: STRING(255), + allowNull: true, + comment: '产品名称', + }, + express_code: { + type: STRING(50), + allowNull: true, + comment: '物流编码', + }, + code: { + type: STRING(50), + allowNull: true, + comment: '产品编码', + }, + }, { + tableName: 'wms_express_product_type', + freezeTableName: true, + underscored: true, + timestamps: false, + paranoid: false, + comment: '快递产品类型表', + }); + + return ExpressProductType; +}; diff --git a/app/model/express_setting.js b/app/model/express_setting.js index 9256d5e..0d68413 100644 --- a/app/model/express_setting.js +++ b/app/model/express_setting.js @@ -13,17 +13,22 @@ module.exports = app => { }, express_code: { type: STRING(50), - allowNull: true, - comment: '快递编码', + allowNull: false, + comment: '系统快递编码', }, code: { type: STRING(50), - allowNull: true, - comment: '设置项编码', + allowNull: false, + comment: '自设编码', + }, + name: { + type: STRING(50), + allowNull: false, + comment: '别名', }, warehouse_id: { type: BIGINT(20).UNSIGNED, - allowNull: true, + allowNull: false, comment: '仓库主体ID', }, }, { diff --git a/app/model/notification_webhook.js b/app/model/notification_webhook.js index aff14fe..5bf310e 100644 --- a/app/model/notification_webhook.js +++ b/app/model/notification_webhook.js @@ -39,6 +39,7 @@ module.exports = app => { Object.freeze({ code: 'all', name: '全部事件', business: 'all', description: '订阅后接收所有通知事件' }), Object.freeze({ code: '*', name: '全部事件(兼容别名)', business: 'all', description: '兼容旧配置,等价于 all' }), Object.freeze({ code: 'receiving_completed', name: '收货完成', business: 'receiving', description: '收货单完成后的通知' }), + Object.freeze({ code: 'order_cancel_intercepted', name: '订单取消拦截', business: 'order', description: '订单取消失败并触发拦截执行后的通知' }), Object.freeze({ code: 'store_warehouse_print_quantity_adjusted', name: '货主面单余额调整', @@ -229,7 +230,11 @@ module.exports = app => { }); const subjectConfig = app.model.Store && typeof app.model.Store.normalizeSubjectConfig === 'function' ? app.model.Store.normalizeSubjectConfig(store && store.subject_config) - : { max_notice_webhook_count: 5 }; + : { + max_notice_webhook_count: 5, + default_express_code: 'STO', + default_platform_code: 'TB', + }; const maxWebhookCount = Number(subjectConfig.max_notice_webhook_count || 5); const where = { diff --git a/app/model/order_delivery.js b/app/model/order_delivery.js index 586c61c..56fb99a 100644 --- a/app/model/order_delivery.js +++ b/app/model/order_delivery.js @@ -15,7 +15,7 @@ module.exports = app => { INSPECTION_STATUS: [ 'none', 'padding', 'running', 'fin', 'error' ], PRINT_STATUS: [ 'none', 'padding', 'fin', 'error' ], CLAIM_STATUS: [ 'none', 'padding', 'fin', 'error' ], - OUTBOUND_STATUS: [ 'none', 'padding', 'fin', 'error' ], + OUTBOUND_STATUS: [ 'none', 'padding', 'fin', 'timeout', 'error' ], LOCK_STATUS: [ 'none', 'warehouse', 'store' ], INTERCEPT_STATUS: [ 'none', 'requesting', 'requested', 'intercepting', @@ -74,6 +74,16 @@ module.exports = app => { allowNull: true, comment: '来源平台名称', }, + sys_platform_code: { + type: STRING(50), + allowNull: true, + comment: '系统平台编码', + }, + sys_platform_name: { + type: STRING(200), + allowNull: true, + comment: '系统平台名称', + }, create_at: { type: DATE, allowNull: true, @@ -184,6 +194,16 @@ module.exports = app => { allowNull: true, comment: '物流公司名称', }, + sys_logistics_code: { + type: STRING(50), + allowNull: true, + comment: '系统物流公司编码', + }, + sys_logistics_name: { + type: STRING(200), + allowNull: true, + comment: '系统物流公司名称', + }, express_code: { type: STRING(50), allowNull: true, @@ -389,7 +409,7 @@ module.exports = app => { print_status: { type: ENUM(...StatusEnum.PRINT_STATUS), allowNull: true, - defaultValue: null, + defaultValue: 'none', comment: '打印状态机', }, claim_status: { @@ -407,13 +427,13 @@ module.exports = app => { lock_status: { type: ENUM(...StatusEnum.LOCK_STATUS), allowNull: true, - defaultValue: null, + defaultValue: 'none', comment: '锁定状态机', }, intercept_status: { type: ENUM(...StatusEnum.INTERCEPT_STATUS), allowNull: true, - defaultValue: null, + defaultValue: 'none', comment: '拦截状态机', }, }; @@ -439,8 +459,7 @@ module.exports = app => { }, { name: 'idx_items', - fields: [ 'items' ], - length: 50, + fields: [{ attribute: 'items', length: 50 }], }, { name: 'idx_items_hash', diff --git a/app/model/order_delivery_factory.js b/app/model/order_delivery_factory.js index da70625..0127ed4 100644 --- a/app/model/order_delivery_factory.js +++ b/app/model/order_delivery_factory.js @@ -1,6 +1,109 @@ // app/model/wms_order_delivery_factory.js 'use strict'; +const { + ensureShardWarehouseId, + clearShardWarehouseValidationCache, +} = require('../lib/warehouse_shard_guard'); +const { + normalizeManagedType, + isOutsourcedType, + normalizeIndexDefinition, + parseNumericConstraint, + buildTableAttributes, + buildTableName: buildManagedTableName, + buildTableComment, + buildTableOptions, + buildIndexOptions, + buildColumnLines, + buildIndexLines, + parseManagedTableName, +} = require('./order_delivery_table_schema'); + +const LANES = Object.freeze({ + M4: 'm4', + M5: 'm5', +}); + +/** + * 判断两个索引定义是否存在结构差异。 + * @param {Object} expectedIndex 预期索引定义。 + * @param {Object} actualIndex 实际索引定义。 + * @return {boolean} 是否存在结构差异。 + */ +function isIndexDefinitionDifferent(expectedIndex, actualIndex) { + const normalizedExpected = normalizeIndexDefinition(expectedIndex); + const normalizedActual = normalizeIndexDefinition(actualIndex); + + if (!normalizedActual.name) { + return true; + } + + const actualUniqueDefined = Object.prototype.hasOwnProperty.call(actualIndex || {}, 'unique') + || Object.prototype.hasOwnProperty.call(actualIndex || {}, 'Unique') + || Object.prototype.hasOwnProperty.call(actualIndex || {}, 'nonUnique'); + + if (actualUniqueDefined && normalizedExpected.unique !== normalizedActual.unique) { + return true; + } + + if (!Array.isArray(actualIndex && actualIndex.fields) || !actualIndex.fields.length) { + return false; + } + + if (normalizedExpected.fields.length !== normalizedActual.fields.length) { + return true; + } + + for (let index = 0; index < normalizedExpected.fields.length; index += 1) { + const expectedField = normalizedExpected.fields[index]; + const actualField = normalizedActual.fields[index]; + + if (!expectedField.attribute || !actualField.attribute) { + return true; + } + + if (expectedField.attribute !== actualField.attribute) { + return true; + } + + if (Object.prototype.hasOwnProperty.call(expectedField, 'length') && expectedField.length !== actualField.length) { + return true; + } + } + + return false; +} + +/** + * 转义 SQL 标识符。 + * @param {string} identifier 标识符。 + * @return {string} 转义后的标识符。 + */ +function quoteIdentifier(identifier) { + return `\`${String(identifier).replace(/`/g, '``')}\``; +} + +/** + * 构造表数据约束违规错误。 + * @param {string} tableName 表名。 + * @param {string} columnName 列名。 + * @param {string} violationType 违规类型。 + * @param {string} [detail] 违规详情。 + * @return {Error} 错误对象。 + */ +function buildManagedTableConstraintError(tableName, columnName, violationType, detail = '') { + const suffix = detail ? `, detail=${detail}` : ''; + const error = new Error(`数据不满足约束: table=${tableName}, column=${columnName}, violation=${violationType}${suffix}`); + + error.code = 'ORDER_DELIVERY_TABLE_CONSTRAINT_VIOLATION'; + error.tableName = tableName; + error.columnName = columnName; + error.violationType = violationType; + + return error; +} + module.exports = app => { class OrderDeliveryFactory { @@ -9,6 +112,36 @@ module.exports = app => { this.app = app; } + /** + * 获取配送域车道常量。 + * @return {Object} 车道常量。 + */ + get LANES() { + return LANES; + } + + /** + * 判断是否为配送域模型。 + * @param {string} type 模型类型。 + * @return {boolean} 是否为配送域模型。 + */ + isDispatchType(type) { + return type === 'dispatch'; + } + + /** + * 解析模型类型。 + * @param {string} type 模型类型。 + * @return {string} 解析后的模型类型。 + */ + resolveModelType(type) { + return normalizeManagedType(type); + } + + isOutsourcedModel(type) { + return isOutsourcedType(type); + } + /** * 获取当前表模型 * @param {number} warehouseId 仓库ID @@ -27,6 +160,37 @@ module.exports = app => { return await this.getOrCreateModel(warehouseId, 'history'); } + /** + * 获取配送域模型。 + * @param {number|string} warehouseId 仓库ID。 + * @return {Promise} 配送域模型。 + */ + async getDispatchModel(warehouseId) { + return await this.getOrCreateModel(warehouseId, 'dispatch'); + } + + async getOutsourcedModel(warehouseId) { + return await this.getOrCreateModel(warehouseId, 'outsourced'); + } + + /** + * 获取配送正常模型。 + * @param {number|string} warehouseId 仓库ID。 + * @return {Promise} 配送域模型。 + */ + async getM4Model(warehouseId) { + return await this.getDispatchModel(warehouseId); + } + + /** + * 获取配送异常模型。 + * @param {number|string} warehouseId 仓库ID。 + * @return {Promise} 配送域模型。 + */ + async getM5Model(warehouseId) { + return await this.getDispatchModel(warehouseId); + } + /** * 根据表名直接获取模型 * @param {string} tableName 表名 @@ -40,17 +204,18 @@ module.exports = app => { } try { + const parsed = parseManagedTableName(tableName); + if (!parsed) { + throw new Error(`表 ${tableName} 不是订单工厂管理表`); + } + const tableExists = await this.checkTableExists(tableName); if (!tableExists) { throw new Error(`表 ${tableName} 不存在`); } - const baseAttributes = this.app.model.OrderDelivery.rawAttributes; - const DynamicModel = this.app.model.define(tableName, baseAttributes, { - tableName, - timestamps: false, - comment: tableName.includes('_history') ? '仓库发货单历史表' : '仓库发货单常用表', - }); + 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; @@ -67,9 +232,11 @@ module.exports = app => { * @param {string} type 模型类型 * @return {Promise} 动态模型 */ - async getOrCreateModel(warehouseId, type = 'current') { - const tableName = this.generateTableName(warehouseId, type); - const cacheKey = `${warehouseId}_${type}`; + async getOrCreateModel(warehouseId, type) { + const warehouseIdStr = await ensureShardWarehouseId(this.app, warehouseId); + const modelType = this.resolveModelType(type); + const tableName = this.generateTableName(warehouseIdStr, modelType); + const cacheKey = `${warehouseIdStr}_${modelType}`; // 检查缓存 if (this.modelCache.has(cacheKey)) { @@ -77,20 +244,12 @@ module.exports = app => { } try { - // 检查表是否存在,不存在则创建 - const tableExists = await this.checkTableExists(tableName); - if (!tableExists) { - await this.createPhysicalTable(warehouseId, type); - } + const DynamicModel = this.buildManagedModel(warehouseIdStr, modelType, tableName); - // 创建模型实例 - const baseAttributes = this.app.model.OrderDelivery.rawAttributes; - const modelOptions = this.getModelOptions(tableName, warehouseId, type); - - const DynamicModel = this.app.model.define(tableName, baseAttributes, modelOptions); + await this.ensureManagedTableSchema(tableName, modelType, warehouseIdStr, DynamicModel); // 设置关联关系 - this.setupAssociations(DynamicModel, warehouseId, type); + this.setupAssociations(DynamicModel, warehouseIdStr, modelType); // 缓存模型 this.modelCache.set(cacheKey, DynamicModel); @@ -106,28 +265,36 @@ module.exports = app => { /** * 获取模型配置选项 - * @param {string} tableName 表名 * @param {number} warehouseId 仓库ID * @param {string} type 模型类型 * @return {Object} Sequelize 模型配置 */ - getModelOptions(tableName, warehouseId, type) { - const options = { - tableName, - timestamps: false, - comment: type === 'history' - ? `仓库${warehouseId}发货单历史表` - : `仓库${warehouseId}发货单常用表`, - indexes: this.getIndexes(warehouseId, type), - }; + getModelOptions(warehouseId, type) { + return buildTableOptions(this.app, warehouseId, type); + } - // 历史表添加归档时间字段 - if (type === 'history') { - options.fields = Object.keys(this.app.model.OrderDelivery.rawAttributes); - options.fields.push('archive_time'); - } + /** + * 构建动态模型。 + * @param {number|string} warehouseId 仓库ID。 + * @param {string} type 模型类型。 + * @param {string} tableName 表名。 + * @return {Object} 动态模型。 + */ + buildManagedModel(warehouseId, type, tableName) { + const modelType = this.resolveModelType(type); + const attributes = this.getTableAttributes(modelType); + const modelOptions = this.getModelOptions(warehouseId, modelType); - return options; + return this.app.model.define(tableName, attributes, modelOptions); + } + + /** + * 获取订单工厂管理的属性定义。 + * @param {string} type 模型类型。 + * @return {Object} 属性定义。 + */ + getTableAttributes(type) { + return buildTableAttributes(this.app, type); } /** @@ -137,63 +304,89 @@ module.exports = app => { * @return {Array} 索引配置 */ getIndexes(warehouseId, type) { - const prefix = `${warehouseId}_${type}`; + return buildIndexOptions(warehouseId, type); + } - return [ - { - name: `idx_${prefix}_store_id`, - fields: [ 'store_id' ], - }, - { - name: `idx_${prefix}_warehouse_id`, - fields: [ 'warehouse_id' ], - }, - { - name: `idx_${prefix}_delivery_code`, - unique: true, - fields: [ 'delivery_order_code', 'store_id', 'warehouse_id' ], - }, - { - name: `idx_${prefix}_items`, - fields: [ 'items' ], - length: 50, - }, - { - name: `idx_${prefix}_items_hash`, - fields: [ 'items_hash' ], - }, - { - name: `idx_${prefix}_hash_crc`, - fields: [ 'items_hash', 'items_crc', 'warehouse_id' ], - }, - { - name: `idx_${prefix}_wave`, - fields: [ 'status', 'wave_id' ], - }, - { - name: `idx_${prefix}_statuses`, - fields: [ - 'status', - 'post_status', - 'pick_status', - 'pack_status', - 'outbound_status', - ], - }, - ]; + /** + * 获取当前表通用列定义行。 + * + * @param {string} type 模型类型 + * @return {Array} 当前表列定义行 + */ + getCurrentTableColumnLines(type = 'current') { + return buildColumnLines(this.app, type); + } + + /** + * 获取当前表通用索引定义行。 + * + * @param {number} warehouseId 仓库ID + * @param {string} type 模型类型 + * @return {Array} 当前表索引定义行 + */ + getCurrentTableIndexLines(warehouseId, type = 'current') { + return buildIndexLines(warehouseId, type); + } + + /** + * 获取配送域物理表名。 + * @param {number|string} warehouseId 仓库ID。 + * @return {Promise} 配送域物理表名。 + */ + async getDispatchTableName(warehouseId) { + const warehouseIdStr = await ensureShardWarehouseId(this.app, warehouseId); + return `wms_order_delivery_dispatch_${warehouseIdStr}`; + } + + /** + * 获取配送域表列定义行。 + * @return {Array} 配送域表列定义行。 + */ + getDispatchTableColumnLines() { + return buildColumnLines(this.app, 'dispatch'); + } + + /** + * 获取配送域表索引定义行。 + * @param {string} warehouseIdStr 仓库ID字符串。 + * @return {Array} 配送域表索引定义行。 + */ + getDispatchTableIndexLines(warehouseIdStr) { + return buildIndexLines(warehouseIdStr, 'dispatch'); + } + + /** + * 获取配送域索引配置。 + * @param {string} warehouseIdStr 仓库ID字符串。 + * @return {Array} Sequelize 索引配置。 + */ + getDispatchTableIndexOptions(warehouseIdStr) { + return buildIndexOptions(warehouseIdStr, 'dispatch'); + } + + /** + * 获取配送域属性定义。 + * @return {Object} 配送域属性定义。 + */ + getDispatchAttributes() { + return this.getTableAttributes('dispatch'); + } + + buildDispatchAttributes() { + return this.getDispatchAttributes(); } /** * 设置关联关系 - * @param {Object} DynamicModel 动态模型 - * @param {number} warehouseId 仓库ID - * @param {string} type 模型类型 - * @return {Promise} + * @param {Object} DynamicModel 动态模型 + * @param {number} warehouseId 仓库ID + * @param {string} type 模型类型 + * @return {Promise} */ async setupAssociations(DynamicModel, warehouseId, type) { try { - // 如果存在商品模型工厂,建立关联 - if (this.app.model.OrderItemsFactory) { + // 配送域不挂商品明细关联,其余模式保持原行为。 + if (!this.isDispatchType(type) && this.app.model.OrderItemsFactory) { const ItemsModel = await this.app.model.OrderItemsFactory.getOrCreateModel(warehouseId, type); // 发货单 -> 商品 (1:N) @@ -237,8 +430,8 @@ module.exports = app => { /** * 检查表是否存在 - * @param {string} tableName 表名 - * @return {Promise} 是否存在 + * @param {string} tableName 表名 + * @return {Promise} 是否存在 */ async checkTableExists(tableName) { const sequelize = this.app.model; @@ -263,113 +456,233 @@ module.exports = app => { } } + /** + * 判断目标表是否需要进行结构同步。 + * @param {string} tableName 表名。 + * @param {string} type 模型类型。 + * @param {number|string} warehouseId 仓库ID。 + * @param {boolean|null} [tableExists=null] 是否已确认表存在。 + * @return {Promise} 是否需要同步。 + */ + async needsTableSchemaSync(tableName, type, warehouseId, tableExists = null) { + const queryInterface = this.app.model.getQueryInterface(); + const managedTableExists = typeof tableExists === 'boolean' + ? tableExists + : await this.checkTableExists(tableName); + + if (!managedTableExists) { + return true; + } + + const [ tables, indexes ] = await Promise.all([ + queryInterface.describeTable(tableName), + typeof queryInterface.showIndex === 'function' + ? queryInterface.showIndex(tableName) + : Promise.resolve([]), + ]); + + const expectedAttributes = this.getTableAttributes(type); + const expectedAttributeNames = Object.keys(expectedAttributes); + const actualAttributeNames = Object.keys(tables || {}); + + if (expectedAttributeNames.length !== actualAttributeNames.length) { + return true; + } + + const actualColumnNames = new Set(actualAttributeNames); + + for (const columnName of expectedAttributeNames) { + if (!actualColumnNames.has(columnName)) { + return true; + } + } + + for (const columnName of expectedAttributeNames) { + const expectedColumn = expectedAttributes[columnName]; + const actualColumn = tables[columnName] || {}; + const expectedType = expectedColumn.type && typeof expectedColumn.type.toSql === 'function' + ? expectedColumn.type.toSql().toLowerCase() + : String(expectedColumn.type || '').toLowerCase(); + const actualType = String(actualColumn.type || actualColumn.Type || '').toLowerCase(); + const expectedAllowNull = expectedColumn.allowNull !== false; + const actualAllowNull = actualColumn.allowNull !== false; + const expectedDefault = Object.prototype.hasOwnProperty.call(expectedColumn, 'defaultValue') + ? expectedColumn.defaultValue + : undefined; + const actualDefault = Object.prototype.hasOwnProperty.call(actualColumn, 'defaultValue') + ? actualColumn.defaultValue + : undefined; + + if (expectedType && actualType && expectedType !== actualType) { + return true; + } + + if (expectedAllowNull !== actualAllowNull) { + return true; + } + + const normalizedExpectedDefault = expectedDefault == null ? null : String(expectedDefault); + const normalizedActualDefault = actualDefault == null ? null : String(actualDefault); + if (normalizedExpectedDefault !== normalizedActualDefault) { + return true; + } + } + + const expectedIndexes = this.getIndexes(warehouseId, type); + const actualIndexes = Array.isArray(indexes) ? indexes : []; + + for (const expectedIndex of expectedIndexes) { + const actualIndex = actualIndexes.find(index => (index.Key_name || index.name) === expectedIndex.name); + + if (!actualIndex) { + return true; + } + + if (isIndexDefinitionDifferent(expectedIndex, actualIndex)) { + return true; + } + } + + return false; + } + + /** + * 在结构同步前预检现有数据是否满足非空和数值范围约束。 + * @param {string} tableName 表名。 + * @param {string} type 模型类型。 + * @return {Promise} + */ + async assertManagedTableDataConstraints(tableName, type) { + const queryInterface = this.app.model.getQueryInterface(); + const sequelize = this.app.model; + const tableColumns = await queryInterface.describeTable(tableName); + const expectedAttributes = this.getTableAttributes(type); + const columnNames = new Set(Object.keys(tableColumns || {})); + + for (const columnName of Object.keys(expectedAttributes)) { + if (!columnNames.has(columnName)) { + continue; + } + + 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'); + } + } + + const numericConstraint = parseNumericConstraint(expectedAttribute); + + if (!numericConstraint) { + continue; + } + + 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, + }, + } + ); + + if (Array.isArray(rangeRows) && rangeRows.length > 0) { + throw buildManagedTableConstraintError( + tableName, + columnName, + 'NUMERIC_RANGE', + `expected=[${numericConstraint.min}, ${numericConstraint.max}]` + ); + } + } + } + + /** + * 确保单个目标表与模型结构一致。 + * @param {string} tableName 表名。 + * @param {string} type 模型类型。 + * @param {number|string} warehouseId 仓库ID。 + * @param {Object} [DynamicModel] 已构建的动态模型。 + * @return {Promise} 是否执行了同步。 + */ + async ensureManagedTableSchema(tableName, type, warehouseId, DynamicModel = null) { + const modelType = this.resolveModelType(type); + const dynamicModel = DynamicModel || this.buildManagedModel(warehouseId, modelType, tableName); + const tableExists = await this.checkTableExists(tableName); + const needsSync = tableExists + ? await this.needsTableSchemaSync(tableName, modelType, warehouseId, tableExists) + : true; + + if (!needsSync) { + return false; + } + + if (tableExists) { + await this.assertManagedTableDataConstraints(tableName, modelType); + } + + await dynamicModel.sync({ alter: true }); + return true; + } + + /** + * 扫描并同步订单工厂管理的目标表。 + * @return {Promise} + */ + async ensureManagedTableSchemas() { + const tableNames = await this.listManagedTableNames(); + + for (const tableName of tableNames) { + const parsed = parseManagedTableName(tableName); + if (!parsed) { + continue; + } + + await this.ensureManagedTableSchema(tableName, parsed.type, parsed.warehouseId); + } + } + + /** + * 获取当前库中已存在的订单工厂目标表。 + * @return {Promise>} 目标表名列表。 + */ + async listManagedTableNames() { + const [ rows ] = await this.app.model.query(` + SELECT TABLE_NAME AS tableName + FROM INFORMATION_SCHEMA.TABLES + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME LIKE 'wms_order_delivery_%' + `); + + return rows + .map(item => item.tableName) + .filter(tableName => parseManagedTableName(tableName)); + } + /** * 创建物理表 * @param {number} warehouseId 仓库ID * @param {string} type 模型类型 * @return {Promise} */ - async createPhysicalTable(warehouseId, type = 'current') { - const tableName = this.generateTableName(warehouseId, type); - const tableComment = type === 'history' - ? `仓库${warehouseId}发货单历史表` - : `仓库${warehouseId}发货单常用表`; + async createPhysicalTable(warehouseId, type) { + const modelType = this.resolveModelType(type); + const tableName = this.generateTableName(warehouseId, modelType); + const dynamicModel = this.buildManagedModel(warehouseId, modelType, tableName); - // 添加历史表特有的字段 - const historyFields = type === 'history' ? - ',\n`archive_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT \'归档时间\'' : ''; - - const createTableSQL = ` - CREATE TABLE \`${tableName}\` ( - \`id\` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, - \`delivery_order_code\` varchar(50) DEFAULT NULL COMMENT '发货单号', - \`pre_delivery_order_code\` varchar(50) DEFAULT NULL COMMENT '预发货单号', - \`pre_delivery_order_id\` varchar(50) DEFAULT NULL COMMENT '预发货单ID', - \`order_type\` varchar(50) DEFAULT NULL COMMENT '订单类型', - \`warehouse_code\` varchar(50) DEFAULT NULL COMMENT '仓库编码', - \`order_flag\` varchar(200) DEFAULT NULL COMMENT '订单标记', - \`source_platform_code\` varchar(50) DEFAULT NULL COMMENT '来源平台编码', - \`source_platform_name\` varchar(200) DEFAULT NULL COMMENT '来源平台名称', - \`create_at\` datetime DEFAULT NULL COMMENT '创建时间', - \`delete_at\` datetime DEFAULT NULL COMMENT '删除时间', - \`updated_at\` datetime DEFAULT NULL COMMENT '更新时间', - \`place_order_time\` datetime DEFAULT NULL COMMENT '店铺创建订单时间', - \`pay_time\` datetime DEFAULT NULL COMMENT '支付时间', - \`pay_no\` varchar(50) DEFAULT NULL COMMENT '支付单号', - \`service_code\` varchar(50) DEFAULT NULL COMMENT '集包服务编码', - \`operator_name\` varchar(50) DEFAULT NULL COMMENT 'ERP审核人', - \`operate_time\` datetime DEFAULT NULL COMMENT 'ERP审核时间', - \`delivery_time\` datetime DEFAULT NULL COMMENT '发货时间', - \`shop_nick\` varchar(200) DEFAULT NULL COMMENT '店铺名称', - \`seller_nick\` varchar(200) DEFAULT NULL COMMENT '卖家名称', - \`buyer_nick\` varchar(200) DEFAULT NULL COMMENT '买家名称', - \`total_amount\` decimal(18,2) DEFAULT NULL COMMENT '订单总金额', - \`item_amount\` decimal(18,2) DEFAULT NULL COMMENT '商品总金额', - \`discount_amount\` decimal(18,2) DEFAULT NULL COMMENT '订单折扣金额', - \`freight\` decimal(18,2) DEFAULT NULL COMMENT '快递费用', - \`ar_amount\` decimal(18,2) DEFAULT NULL COMMENT '应收金额', - \`got_amount\` decimal(18,2) DEFAULT NULL COMMENT '已收金额', - \`service_fee\` decimal(18,2) DEFAULT NULL COMMENT 'COD服务费', - \`logistics_code\` varchar(50) DEFAULT NULL COMMENT '物流公司编码', - \`logistics_name\` varchar(200) DEFAULT NULL COMMENT '物流公司名称', - \`express_code\` varchar(50) DEFAULT NULL COMMENT '面单号前置', - \`logistics_area_code\` varchar(50) DEFAULT NULL COMMENT '快递区域编码, 大头笔信息', - \`delivery_type\` varchar(255) DEFAULT NULL COMMENT '发货服务类型', - \`is_urgency\` enum('Y','N') DEFAULT 'N' COMMENT '是否紧急', - \`invoice_flag\` enum('Y','N') DEFAULT 'N' COMMENT '是否需要发票', - \`status\` enum('pedding','created','cancel','error') DEFAULT 'created' COMMENT '状态', - \`name\` text COMMENT '收件人姓名', - \`zip_code\` varchar(50) DEFAULT NULL COMMENT '收件人邮编', - \`tel\` text COMMENT '收件人电话', - \`mobile\` text COMMENT '收件人移动电话', - \`email\` text COMMENT '收件人邮箱', - \`country_code\` varchar(255) DEFAULT NULL COMMENT '国家编码', - \`province\` varchar(255) DEFAULT NULL COMMENT '省份', - \`city\` varchar(255) DEFAULT NULL COMMENT '城市', - \`area\` varchar(255) DEFAULT NULL COMMENT '区', - \`town\` varchar(255) DEFAULT NULL COMMENT '镇', - \`detail_address\` varchar(255) DEFAULT NULL COMMENT '详细地址', - \`id_type\` varchar(255) DEFAULT NULL COMMENT '证件类型', - \`id_number\` int(11) DEFAULT NULL COMMENT '证件号码', - \`oaid\` text COMMENT 'OAID', - \`sync_status\` enum('padding','fin','error') DEFAULT 'padding' COMMENT '同步状态', - \`store_id\` bigint(20) UNSIGNED DEFAULT NULL COMMENT '货主id', - \`warehouse_id\` bigint(20) UNSIGNED DEFAULT NULL COMMENT '仓库id', - \`from_key\` int(11) DEFAULT NULL COMMENT '来源键', - \`items\` text COMMENT '商品结构字符串', - \`items_count\` smallint(5) UNSIGNED NOT NULL DEFAULT '0' COMMENT '商品种类数', - \`items_total\` int(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '商品总数', - \`items_weight\` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '总重量', - \`items_hash\` char(32) NOT NULL DEFAULT '' COMMENT '哈希值', - \`items_crc\` int(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '校验码', - \`wave_id\` bigint(20) NOT NULL DEFAULT '0' COMMENT '波次ID,0表示未分配', - \`post_status\` enum('padding','fin','timeout','error','none') DEFAULT 'none' COMMENT '分配快递号状态机', - \`storage_status\` enum('padding','fin','error','none') DEFAULT 'none' COMMENT '分配储位状态机', - \`pick_status\` enum('padding','fin','error','none') DEFAULT 'none' COMMENT '拣货状态机', - \`pack_status\` enum('none','padding','fin','error') DEFAULT 'none' COMMENT '打包状态机', - \`inspection_status\` enum('none','padding','running','fin','error') DEFAULT 'none' COMMENT '检验状态机', - \`step\` int(10) NOT NULL DEFAULT '0' COMMENT '订单步骤:0未审核,1已审核', - \`print_status\` enum('none','padding','fin','error') DEFAULT NULL COMMENT '打印状态机', - \`claim_status\` enum('none','padding','fin','error') DEFAULT 'none' COMMENT '领取状态机', - \`outbound_status\` enum('none','padding','fin','error') DEFAULT 'none' COMMENT '出库状态机', - \`lock_status\` enum('none','warehouse','store') DEFAULT NULL COMMENT '锁定状态机', - \`intercept_status\` enum('none','requesting','requested','intercepting','intercepted_in_transit','intercepted_at_warehouse','returning','returned','delivered_by_mistake','timeout','cancelled','failed','exception') DEFAULT NULL COMMENT '拦截状态机' - ${historyFields}, - PRIMARY KEY (\`id\`), - UNIQUE KEY \`idx_${warehouseId}_${type}_delivery_code\` (\`delivery_order_code\`,\`store_id\`,\`warehouse_id\`), - KEY \`idx_${warehouseId}_${type}_store_id\` (\`store_id\`), - KEY \`idx_${warehouseId}_${type}_warehouse_id\` (\`warehouse_id\`), - KEY \`idx_${warehouseId}_${type}_items\` (\`items\`(50)), - KEY \`idx_${warehouseId}_${type}_items_hash\` (\`items_hash\`), - KEY \`idx_${warehouseId}_${type}_hash_crc\` (\`items_hash\`,\`items_crc\`,\`warehouse_id\`), - KEY \`idx_${warehouseId}_${type}_wave\` (\`status\`,\`wave_id\`), - KEY \`idx_${warehouseId}_${type}_statuses\` (\`status\`,\`post_status\`,\`pick_status\`,\`pack_status\`,\`outbound_status\`) - ${type === 'history' ? `,KEY \`idx_${warehouseId}_history_archive_time\` (\`archive_time\`)` : ''} - ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='${tableComment}'; - `; - - await this.app.model.query(createTableSQL); - this.app.logger.info(`创建物理表成功: ${tableName}`); + await dynamicModel.sync({ alter: true }); + this.app.logger.info(`创建/同步物理表成功: ${tableName}`); } /** @@ -387,7 +700,7 @@ module.exports = app => { step: [ 0, 1 ], print_status: [ 'none', 'padding', 'fin', 'error' ], claim_status: [ 'none', 'padding', 'fin', 'error' ], - outbound_status: [ 'none', 'padding', 'fin', 'error' ], + outbound_status: [ 'none', 'padding', 'fin', 'timeout', 'error' ], lock_status: [ 'none', 'warehouse', 'store' ], intercept_status: [ 'none', 'requesting', 'requested', 'intercepting', @@ -405,8 +718,18 @@ module.exports = app => { * @return {string} 表名 */ generateTableName(warehouseId, type) { - const suffix = type === 'history' ? '_history' : ''; - return `wms_order_delivery_${warehouseId}${suffix}`; + const modelType = this.resolveModelType(type); + return buildManagedTableName(warehouseId, modelType); + } + + /** + * 获取订单工厂管理表的注释。 + * @param {number|string} warehouseId 仓库ID。 + * @param {string} type 模型类型。 + * @return {string} 表注释。 + */ + getTableComment(warehouseId, type) { + return buildTableComment(warehouseId, type); } /** @@ -414,6 +737,7 @@ module.exports = app => { */ clearCache() { this.modelCache.clear(); + clearShardWarehouseValidationCache(this.app); this.app.logger.info('模型缓存已清理'); } diff --git a/app/model/order_delivery_table_schema.js b/app/model/order_delivery_table_schema.js new file mode 100644 index 0000000..0e413f7 --- /dev/null +++ b/app/model/order_delivery_table_schema.js @@ -0,0 +1,521 @@ +'use strict'; + +const MANAGED_TYPES = Object.freeze({ + CURRENT: 'current', + HISTORY: 'history', + DISPATCH: 'dispatch', + OUTSOURCED: 'outsourced', +}); + +const TABLE_PATTERNS = Object.freeze([ + { + type: MANAGED_TYPES.DISPATCH, + pattern: /^wms_order_delivery_dispatch_(\d+)$/, + }, + { + type: MANAGED_TYPES.HISTORY, + pattern: /^wms_order_delivery_(\d+)_history$/, + }, + { + type: MANAGED_TYPES.OUTSOURCED, + pattern: /^wms_order_delivery_(\d+)_outsourced$/, + }, + { + type: MANAGED_TYPES.CURRENT, + pattern: /^wms_order_delivery_(\d+)$/, + }, +]); + +/** + * 规范化订单工厂管理的模型类型。 + * @param {string} type 模型类型。 + * @return {string} 规范化后的模型类型。 + */ +function normalizeManagedType(type) { + return Object.values(MANAGED_TYPES).includes(type) ? type : MANAGED_TYPES.CURRENT; +} + +/** + * 判断是否为配送域类型。 + * @param {string} type 模型类型。 + * @return {boolean} 是否为配送域类型。 + */ +function isDispatchType(type) { + return normalizeManagedType(type) === MANAGED_TYPES.DISPATCH; +} + +/** + * 判断是否为历史类型。 + * @param {string} type 模型类型。 + * @return {boolean} 是否为历史类型。 + */ +function isHistoryType(type) { + return normalizeManagedType(type) === MANAGED_TYPES.HISTORY; +} + +/** + * 判断是否为 outsourced 类型。 + * @param {string} type 模型类型。 + * @return {boolean} 是否为 outsourced 类型。 + */ +function isOutsourcedType(type) { + return normalizeManagedType(type) === MANAGED_TYPES.OUTSOURCED; +} + +/** + * 克隆模型属性定义,避免直接修改基础模型对象。 + * @param {Object} attributes 原始属性定义。 + * @return {Object} 克隆后的属性定义。 + */ +function cloneAttributes(attributes) { + return Object.entries(attributes).reduce((result, [ name, attribute ]) => { + result[name] = { ...attribute }; + return result; + }, {}); +} + +/** + * 规范化索引字段定义。 + * @param {string|Object} field 字段定义。 + * @return {{ attribute: string, length?: number }} 规范化后的字段定义。 + */ +function normalizeIndexField(field) { + if (typeof field === 'string') { + return { attribute: field }; + } + + if (!field || typeof field !== 'object') { + return { attribute: String(field) }; + } + + const attribute = field.attribute || field.name || field.field || field.columnName || field.column_name; + const normalizedField = { + attribute: attribute ? String(attribute) : '', + }; + + if (Object.prototype.hasOwnProperty.call(field, 'length') && field.length !== undefined && field.length !== null) { + normalizedField.length = Number(field.length); + } + + return normalizedField; +} + +/** + * 规范化索引定义。 + * @param {Object} index 索引定义。 + * @return {{ name: string, unique: boolean, fields: Array }} 规范化后的索引定义。 + */ +function normalizeIndexDefinition(index) { + return { + name: index.name || index.Key_name || index.key_name || '', + unique: Boolean(index.unique || index.Unique || (typeof index.nonUnique === 'number' ? index.nonUnique === 0 : false)), + fields: Array.isArray(index.fields) ? index.fields.map(normalizeIndexField) : [], + }; +} + +/** + * 规范化 Sequelize 数值类型的 SQL 定义。 + * @param {Object} attribute Sequelize 属性定义。 + * @return {{ type: string, unsigned: boolean, min: string, max: string, precision?: number, scale?: number }|null} 数值约束信息。 + */ +function parseNumericConstraint(attribute) { + let typeSql = ''; + + if (attribute && attribute.type && typeof attribute.type.toSql === 'function') { + try { + typeSql = attribute.type.toSql(); + } catch (error) { + return null; + } + } else { + typeSql = String(attribute && attribute.type || ''); + } + const normalizedTypeSql = String(typeSql || '') + .trim() + .replace(/\s+/g, ' ') + .toUpperCase(); + + if (!normalizedTypeSql) { + return null; + } + + const integerMatch = normalizedTypeSql.match(/^(TINYINT|SMALLINT|MEDIUMINT|INT|INTEGER|BIGINT)\s*(?:\(\s*\d+\s*\))?(?:\s+UNSIGNED)?$/i); + + if (integerMatch) { + const integerBits = { + TINYINT: 8, + SMALLINT: 16, + MEDIUMINT: 24, + INT: 32, + INTEGER: 32, + BIGINT: 64, + }[integerMatch[1].toUpperCase()]; + const unsigned = /\bUNSIGNED\b/i.test(normalizedTypeSql); + const bigBits = BigInt(integerBits); + const max = unsigned + ? (2n ** bigBits) - 1n + : (2n ** (bigBits - 1n)) - 1n; + const min = unsigned + ? 0n + : -(2n ** (bigBits - 1n)); + + return { + type: integerMatch[1].toUpperCase(), + unsigned, + min: min.toString(), + max: max.toString(), + }; + } + + const decimalMatch = normalizedTypeSql.match(/^(DECIMAL|NUMERIC)\s*\(\s*(\d+)\s*,\s*(\d+)\s*\)(?:\s+UNSIGNED)?$/i); + + if (decimalMatch) { + const precision = Number(decimalMatch[2]); + const scale = Number(decimalMatch[3]); + const unsigned = /\bUNSIGNED\b/i.test(normalizedTypeSql); + const integerDigits = precision - scale; + + if (!Number.isInteger(precision) || !Number.isInteger(scale) || precision <= 0 || scale < 0 || integerDigits <= 0) { + return null; + } + + const integerPart = '9'.repeat(integerDigits); + const decimalPart = scale > 0 ? `.${'9'.repeat(scale)}` : ''; + + return { + type: decimalMatch[1].toUpperCase(), + unsigned, + precision, + scale, + min: `-${integerPart}${decimalPart}`, + max: `${integerPart}${decimalPart}`, + }; + } + + return null; +} + +/** + * 生成默认值 SQL 片段。 + * @param {*} defaultValue 默认值。 + * @return {string} SQL 片段。 + */ +function formatDefaultValue(defaultValue) { + if (defaultValue === null) { + return 'NULL'; + } + + if (defaultValue === undefined) { + return ''; + } + + if (defaultValue && typeof defaultValue.toSql === 'function') { + return defaultValue.toSql(); + } + + if (typeof defaultValue === 'string') { + const escaped = defaultValue.replace(/'/g, "''"); + return `'${escaped}'`; + } + + if (typeof defaultValue === 'number' || typeof defaultValue === 'bigint') { + return String(defaultValue); + } + + if (typeof defaultValue === 'boolean') { + return defaultValue ? '1' : '0'; + } + + return `'${String(defaultValue).replace(/'/g, "''")}'`; +} + +/** + * 将 Sequelize 属性定义转换为 DDL 列片段。 + * @param {string} columnName 列名。 + * @param {Object} attribute Sequelize 属性定义。 + * @return {string} DDL 列片段。 + */ +function buildColumnLine(columnName, attribute) { + const parts = [ `\`${columnName}\``, attribute.type && typeof attribute.type.toSql === 'function' + ? attribute.type.toSql() + : String(attribute.type || ''), + ]; + + if (attribute.allowNull === false) { + parts.push('NOT NULL'); + } + + if (attribute.autoIncrement) { + parts.push('AUTO_INCREMENT'); + } + + if (Object.prototype.hasOwnProperty.call(attribute, 'defaultValue')) { + const defaultSql = formatDefaultValue(attribute.defaultValue); + if (defaultSql) { + parts.push(`DEFAULT ${defaultSql}`); + } + } + + if (attribute.comment) { + parts.push(`COMMENT '${String(attribute.comment).replace(/'/g, "''")}'`); + } + + return parts.join(' '); +} + +/** + * 构建模型属性定义。 + * @param {Object} app Egg 应用实例。 + * @param {string} type 模型类型。 + * @return {Object} 属性定义。 + */ +function buildTableAttributes(app, type) { + const modelType = normalizeManagedType(type); + const attributes = cloneAttributes(app.model.OrderDelivery.rawAttributes); + + if (isDispatchType(modelType)) { + const { ENUM } = app.Sequelize; + attributes.dispatch_lane = { + type: ENUM('m4', 'm5'), + field: 'dispatch_lane', + allowNull: false, + defaultValue: 'm4', + comment: '配送工作台子域(M4正常/M5异常)', + }; + } + + if (isHistoryType(modelType)) { + attributes.archive_time = { + type: app.Sequelize.DATE, + field: 'archive_time', + allowNull: true, + defaultValue: null, + comment: '归档时间', + }; + } + + return attributes; +} + +/** + * 构建表名。 + * @param {number|string} warehouseId 仓库ID。 + * @param {string} type 模型类型。 + * @return {string} 表名。 + */ +function buildTableName(warehouseId, type) { + const modelType = normalizeManagedType(type); + + if (isDispatchType(modelType)) { + return `wms_order_delivery_dispatch_${warehouseId}`; + } + + if (isOutsourcedType(modelType)) { + return `wms_order_delivery_${warehouseId}_outsourced`; + } + + const suffix = isHistoryType(modelType) ? '_history' : ''; + return `wms_order_delivery_${warehouseId}${suffix}`; +} + +/** + * 构建表注释。 + * @param {number|string} warehouseId 仓库ID。 + * @param {string} type 模型类型。 + * @return {string} 表注释。 + */ +function buildTableComment(warehouseId, type) { + const modelType = normalizeManagedType(type); + + if (isDispatchType(modelType)) { + return `仓库${warehouseId}发货单配送域(M4/M5)影子表`; + } + + if (isHistoryType(modelType)) { + return `仓库${warehouseId}发货单历史表`; + } + + if (isOutsourcedType(modelType)) { + return `仓库${warehouseId}发货单外仓表`; + } + + return `仓库${warehouseId}发货单常用表`; +} + +/** + * 构建模型选项。 + * @param {Object} app Egg 应用实例。 + * @param {number|string} warehouseId 仓库ID。 + * @param {string} type 模型类型。 + * @return {Object} Sequelize 模型选项。 + */ +function buildTableOptions(app, warehouseId, type) { + const modelType = normalizeManagedType(type); + const options = { + tableName: buildTableName(warehouseId, modelType), + timestamps: false, + comment: buildTableComment(warehouseId, modelType), + indexes: buildIndexOptions(warehouseId, modelType), + }; + + if (isHistoryType(modelType)) { + options.fields = Object.keys(buildTableAttributes(app, modelType)); + } + + return options; +} + +/** + * 构建索引选项。 + * @param {number|string} warehouseId 仓库ID。 + * @param {string} type 模型类型。 + * @return {Array} 索引选项。 + */ +function buildIndexOptions(warehouseId, type) { + const modelType = normalizeManagedType(type); + const prefix = `${warehouseId}_${modelType}`; + + if (isDispatchType(modelType)) { + const baseIndexes = buildIndexOptions(warehouseId, MANAGED_TYPES.CURRENT); + const dispatchLaneIndex = { + name: `idx_dispatch_${warehouseId}_dispatch_lane`, + fields: [ 'dispatch_lane', 'status' ], + }; + + return [ + baseIndexes[0], + baseIndexes[1], + baseIndexes[2], + dispatchLaneIndex, + ...baseIndexes.slice(3), + ]; + } + + const indexes = [ + { + name: `idx_${prefix}_store_id`, + fields: [ 'store_id' ], + }, + { + name: `idx_${prefix}_warehouse_id`, + fields: [ 'warehouse_id' ], + }, + { + name: `idx_${prefix}_delivery_code`, + unique: true, + fields: [ 'delivery_order_code', 'store_id', 'warehouse_id' ], + }, + { + name: `idx_${prefix}_items`, + fields: [{ attribute: 'items', length: 50 }], + }, + { + name: `idx_${prefix}_items_hash`, + fields: [ 'items_hash' ], + }, + { + name: `idx_${prefix}_hash_crc`, + fields: [ 'items_hash', 'items_crc', 'warehouse_id' ], + }, + { + name: `idx_${prefix}_wave`, + fields: [ 'status', 'wave_id' ], + }, + { + name: `idx_${prefix}_statuses`, + fields: [ + 'status', + 'post_status', + 'pick_status', + 'pack_status', + 'outbound_status', + ], + }, + ]; + + if (isHistoryType(modelType)) { + indexes.push({ + name: `idx_${warehouseId}_history_archive_time`, + fields: [ 'archive_time' ], + }); + } + + return indexes; +} + +/** + * 将索引选项转换为 DDL 片段。 + * @param {Object} index 索引定义。 + * @return {string} DDL 索引片段。 + */ +function buildIndexLine(index) { + const fieldParts = index.fields.map(field => { + const normalizedField = normalizeIndexField(field); + const length = Object.prototype.hasOwnProperty.call(normalizedField, 'length') + ? `(${normalizedField.length})` + : ''; + + return `\`${normalizedField.attribute}\`${length}`; + }); + + const prefix = index.unique ? 'UNIQUE KEY' : 'KEY'; + return `${prefix} \`${index.name}\` (${fieldParts.join(',')})`; +} + +/** + * 构建表列定义行。 + * @param {Object} app Egg 应用实例。 + * @param {string} type 模型类型。 + * @return {Array} 列定义行。 + */ +function buildColumnLines(app, type) { + return Object.entries(buildTableAttributes(app, type)).map(([ columnName, attribute ]) => buildColumnLine(columnName, attribute)); +} + +/** + * 构建表索引定义行。 + * @param {number|string} warehouseId 仓库ID。 + * @param {string} type 模型类型。 + * @return {Array} 索引定义行。 + */ +function buildIndexLines(warehouseId, type) { + return buildIndexOptions(warehouseId, type).map(buildIndexLine); +} + +/** + * 解析订单工厂管理的表名。 + * @param {string} tableName 表名。 + * @return {{ type: string, warehouseId: string }|null} 解析结果。 + */ +function parseManagedTableName(tableName) { + for (const item of TABLE_PATTERNS) { + const match = item.pattern.exec(tableName); + if (match) { + return { + type: item.type, + warehouseId: match[1], + }; + } + } + + return null; +} + +module.exports = { + MANAGED_TYPES, + normalizeManagedType, + isDispatchType, + isHistoryType, + isOutsourcedType, + normalizeIndexField, + normalizeIndexDefinition, + parseNumericConstraint, + buildTableAttributes, + buildTableName, + buildTableComment, + buildTableOptions, + buildIndexOptions, + buildColumnLines, + buildIndexLines, + parseManagedTableName, +}; diff --git a/app/model/order_express.js b/app/model/order_express.js index a02f461..420f30e 100644 --- a/app/model/order_express.js +++ b/app/model/order_express.js @@ -1,7 +1,7 @@ 'use strict'; module.exports = app => { - const { BIGINT, STRING, DATE, ENUM } = app.Sequelize; + const { BIGINT, STRING, DATE, ENUM, INTEGER, TINYINT } = app.Sequelize; const OrderExpress = app.model.define('order_express', { id: { @@ -17,7 +17,7 @@ module.exports = app => { comment: '运单号', }, order_id: { - type: BIGINT(20).UNSIGNED, + type: BIGINT(20), allowNull: true, comment: '订单ID', }, @@ -71,6 +71,22 @@ module.exports = app => { allowNull: true, comment: '平台编码', }, + business_key: { + type: INTEGER(3), + allowNull: true, + comment: '业务键', + }, + status: { + type: TINYINT(1), + allowNull: true, + defaultValue: 0, + comment: '状态', + }, + retry_count: { + type: TINYINT(3), + allowNull: true, + comment: '重试次数', + }, }, { tableName: 'wms_order_express', freezeTableName: true, @@ -79,8 +95,17 @@ module.exports = app => { comment: '订单快递信息表', indexes: [ { - name: 'idx_order_id', - fields: [ 'order_id' ], + name: 'uk_order_id_business_key', + unique: true, + fields: [ 'order_id', 'business_key' ], + }, + { + name: 'idx_waybill_code', + fields: [ 'waybill_code' ], + }, + { + name: 'idx_create_at', + fields: [ 'create_at' ], }, ], }); diff --git a/app/model/order_items.js b/app/model/order_items.js index efe064b..e2a47e3 100644 --- a/app/model/order_items.js +++ b/app/model/order_items.js @@ -87,6 +87,11 @@ module.exports = app => { allowNull: true, comment: '库存ID', }, + item_snapshot: { + type: JSON, + allowNull: true, + comment: '商品快照', + }, created_at: { type: Sequelize.DATE, allowNull: false, diff --git a/app/model/order_items_factory.js b/app/model/order_items_factory.js index 3ff60f1..8387acf 100644 --- a/app/model/order_items_factory.js +++ b/app/model/order_items_factory.js @@ -1,6 +1,101 @@ // order_items_factory.js 'use strict'; +const { + ensureShardWarehouseId, + clearShardWarehouseValidationCache, +} = require('../lib/warehouse_shard_guard'); + +/** + * 克隆模型属性定义。 + * @param {Object} attributes 属性定义。 + * @return {Object} 克隆后的属性定义。 + */ +function cloneAttributes(attributes) { + return Object.entries(attributes || {}).reduce((result, [ key, value ]) => { + result[key] = { ...value }; + return result; + }, {}); +} + +/** + * 规范化索引定义。 + * @param {Object} index 索引定义。 + * @return {Object} 规范化后的索引定义。 + */ +function normalizeIndexDefinition(index) { + let unique = false; + + if (index && Object.prototype.hasOwnProperty.call(index, 'unique')) { + unique = Boolean(index.unique); + } else if (index && Object.prototype.hasOwnProperty.call(index, 'Unique')) { + unique = Boolean(index.Unique); + } else if (index && Object.prototype.hasOwnProperty.call(index, 'nonUnique')) { + unique = Number(index.nonUnique) === 0; + } + + return { + name: index && (index.name || index.Key_name || index.key_name || index.index_name) || '', + unique, + fields: Array.isArray(index && index.fields) + ? index.fields.map(field => { + if (typeof field === 'string') { + return { + attribute: field, + }; + } + + return { + attribute: field.attribute || field.name || field.field || field.columnName || '', + length: field.length, + }; + }) + : [], + }; +} + +/** + * 判断两个索引定义是否存在结构差异。 + * @param {Object} expectedIndex 预期索引定义。 + * @param {Object} actualIndex 实际索引定义。 + * @return {boolean} 是否存在结构差异。 + */ +function isIndexDefinitionDifferent(expectedIndex, actualIndex) { + const normalizedExpected = normalizeIndexDefinition(expectedIndex); + const normalizedActual = normalizeIndexDefinition(actualIndex); + + if (!normalizedActual.name) { + return true; + } + + if (normalizedExpected.unique !== normalizedActual.unique) { + return true; + } + + if (normalizedExpected.fields.length !== normalizedActual.fields.length) { + return true; + } + + for (let index = 0; index < normalizedExpected.fields.length; index += 1) { + const expectedField = normalizedExpected.fields[index]; + const actualField = normalizedActual.fields[index]; + + if (!expectedField.attribute || !actualField.attribute) { + return true; + } + + if (expectedField.attribute !== actualField.attribute) { + return true; + } + + if (Object.prototype.hasOwnProperty.call(expectedField, 'length') && expectedField.length !== actualField.length) { + return true; + } + } + + return false; +} + module.exports = app => { const { Sequelize } = app; @@ -29,6 +124,15 @@ module.exports = app => { return await this.getOrCreateModel(warehouseId, 'history'); } + /** + * 获取配送表模型。 + * @param {number} warehouseId 仓库ID + * @return {Promise} 配送表模型 + */ + async getDispatchModel(warehouseId) { + return await this.getOrCreateModel(warehouseId, 'dispatch'); + } + /** * 获取或创建模型 * @param {number} warehouseId 仓库ID @@ -36,14 +140,15 @@ module.exports = app => { * @return {Promise} 动态模型 */ async getOrCreateModel(warehouseId, type = 'current') { - const cacheKey = `${warehouseId}_${type}`; + const warehouseIdStr = await ensureShardWarehouseId(this.app, warehouseId); + const cacheKey = `${warehouseIdStr}_${type}`; // 检查缓存 if (this.modelCache.has(cacheKey)) { return this.modelCache.get(cacheKey); } - const tableName = this.generateTableName(warehouseId, type); + const tableName = this.generateTableName(warehouseIdStr, type); try { // 防止并发创建表 @@ -52,7 +157,7 @@ module.exports = app => { return this.modelCache.get(cacheKey); } - const createPromise = this.createModelWithRetry(warehouseId, type, tableName, cacheKey); + const createPromise = this.createModelWithRetry(warehouseIdStr, type, tableName, cacheKey); this.creatingTables.set(cacheKey, createPromise); const dynamicModel = await createPromise; @@ -78,34 +183,12 @@ module.exports = app => { async createModelWithRetry(warehouseId, type, tableName, cacheKey, retryCount = 3) { for (let i = 0; i < retryCount; i++) { try { - // 检查表是否存在 - const tableExists = await this.checkTableExists(tableName); - if (!tableExists) { - await this.createPhysicalTable(warehouseId, type); - } + const DynamicModel = this.buildDynamicModel(warehouseId, type, tableName); - // 创建模型实例 - const mainModel = this.app.model.OrderItems; - const attributes = { ...mainModel.rawAttributes }; - - // 移除主键的autoIncrement属性,避免动态表冲突 - if (attributes.id) { - delete attributes.id.autoIncrement; - } - - const DynamicModel = this.app.model.define(tableName, attributes, { - tableName, - timestamps: true, - underscored: true, - paranoid: false, - indexes: this.generateIndexes(warehouseId), - comment: type === 'history' - ? `仓库${warehouseId}订单商品历史表` - : `仓库${warehouseId}订单商品常用表`, - }); + await this.ensureManagedTableSchema(tableName, type, warehouseId, DynamicModel); // 复制关联关系 - this.copyAssociations(mainModel, DynamicModel); + this.copyAssociations(this.app.model.OrderItems, DynamicModel); // 缓存模型 this.modelCache.set(cacheKey, DynamicModel); @@ -150,6 +233,56 @@ module.exports = app => { } } + /** + * 构建订单商品动态模型。 + * @param {number|string} warehouseId 仓库ID。 + * @param {string} type 模型类型。 + * @param {string} tableName 表名。 + * @return {Object} 动态模型。 + */ + buildDynamicModel(warehouseId, type, tableName) { + const attributes = this.getTableAttributes(type); + const modelComment = type === 'history' + ? `仓库${warehouseId}订单商品历史表` + : type === 'dispatch' + ? `仓库${warehouseId}订单商品配送表` + : `仓库${warehouseId}订单商品常用表`; + + return this.app.model.define(tableName, attributes, { + tableName, + timestamps: true, + underscored: true, + paranoid: false, + indexes: this.generateIndexes(warehouseId), + comment: modelComment, + }); + } + + /** + * 获取订单商品模型属性定义。 + * @param {string} type 模型类型。 + * @return {Object} 属性定义。 + */ + getTableAttributes(type) { + const mainModel = this.app.model.OrderItems; + const attributes = cloneAttributes(mainModel && mainModel.rawAttributes); + + if (attributes.id) { + delete attributes.id.autoIncrement; + } + + if (type === 'history' && !attributes.archive_time) { + attributes.archive_time = { + type: this.app.Sequelize.DATE, + allowNull: true, + defaultValue: this.app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '归档时间', + }; + } + + return attributes; + } + /** * 生成索引配置 * @param {number} warehouseId 仓库ID @@ -206,7 +339,9 @@ module.exports = app => { type: Sequelize.QueryTypes.SELECT, } ); - return !!results; + return Array.isArray(results) + ? results.length > 0 + : Boolean(results); } catch (error) { this.app.logger.error('检查表是否存在失败:', error); return false; @@ -214,55 +349,130 @@ module.exports = app => { } /** - * 创建物理表 + * 判断目标表是否需要进行结构同步。 + * @param {string} tableName 表名。 + * @param {string} type 模型类型。 + * @param {number|string} warehouseId 仓库ID。 + * @param {boolean|null} [tableExists=null] 是否已确认表存在。 + * @return {Promise} 是否需要同步。 + */ + async needsTableSchemaSync(tableName, type, warehouseId, tableExists = null) { + const queryInterface = this.app.model.getQueryInterface(); + const managedTableExists = typeof tableExists === 'boolean' + ? tableExists + : await this.checkTableExists(tableName); + + if (!managedTableExists) { + return true; + } + + const [ tables, indexes ] = await Promise.all([ + queryInterface.describeTable(tableName), + typeof queryInterface.showIndex === 'function' + ? queryInterface.showIndex(tableName) + : Promise.resolve([]), + ]); + + const expectedAttributes = this.getTableAttributes(type); + const expectedAttributeNames = Object.keys(expectedAttributes); + const actualAttributeNames = Object.keys(tables || {}); + + if (expectedAttributeNames.length !== actualAttributeNames.length) { + return true; + } + + const actualColumnNames = new Set(actualAttributeNames); + + for (const columnName of expectedAttributeNames) { + if (!actualColumnNames.has(columnName)) { + return true; + } + } + + for (const columnName of expectedAttributeNames) { + const expectedColumn = expectedAttributes[columnName]; + const actualColumn = tables[columnName] || {}; + const expectedType = expectedColumn.type && typeof expectedColumn.type.toSql === 'function' + ? expectedColumn.type.toSql().toLowerCase() + : String(expectedColumn.type || '').toLowerCase(); + const actualType = String(actualColumn.type || actualColumn.Type || '').toLowerCase(); + const expectedAllowNull = expectedColumn.allowNull !== false; + const actualAllowNull = actualColumn.allowNull !== false; + const expectedDefault = Object.prototype.hasOwnProperty.call(expectedColumn, 'defaultValue') + ? expectedColumn.defaultValue + : undefined; + const actualDefault = Object.prototype.hasOwnProperty.call(actualColumn, 'defaultValue') + ? actualColumn.defaultValue + : undefined; + + if (expectedType && actualType && expectedType !== actualType) { + return true; + } + + if (expectedAllowNull !== actualAllowNull) { + return true; + } + + const normalizedExpectedDefault = expectedDefault == null ? null : String(expectedDefault); + const normalizedActualDefault = actualDefault == null ? null : String(actualDefault); + + if (normalizedExpectedDefault !== normalizedActualDefault) { + return true; + } + } + + const expectedIndexes = this.generateIndexes(warehouseId); + const actualIndexes = Array.isArray(indexes) ? indexes : []; + + for (const expectedIndex of expectedIndexes) { + const actualIndex = actualIndexes.find(index => (index.Key_name || index.name) === expectedIndex.name); + + if (!actualIndex) { + return true; + } + + if (isIndexDefinitionDifferent(expectedIndex, actualIndex)) { + return true; + } + } + + return false; + } + + /** + * 确保目标表与模型结构一致。 + * @param {string} tableName 表名。 + * @param {string} type 模型类型。 + * @param {number|string} warehouseId 仓库ID。 + * @param {Object} [DynamicModel] 已构建的动态模型。 + * @return {Promise} 是否执行了同步。 + */ + async ensureManagedTableSchema(tableName, type, warehouseId, DynamicModel = null) { + const dynamicModel = DynamicModel || this.buildDynamicModel(warehouseId, type, tableName); + const tableExists = await this.checkTableExists(tableName); + const needsSync = tableExists + ? await this.needsTableSchemaSync(tableName, type, warehouseId, tableExists) + : true; + + if (!needsSync) { + return false; + } + + await dynamicModel.sync({ alter: true }); + return true; + } + + /** + * 创建物理表。 * @param {number} warehouseId 仓库ID * @param {string} type 模型类型 */ async createPhysicalTable(warehouseId, type = 'current') { const tableName = this.generateTableName(warehouseId, type); - const tableComment = type === 'history' - ? `仓库${warehouseId}订单商品历史表` - : `仓库${warehouseId}订单商品常用表`; + const dynamicModel = this.buildDynamicModel(warehouseId, type, tableName); - // 历史表特有字段 - const historyFields = type === 'history' ? - ',`archive_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT \'归档时间\'' : ''; - - const createTableSQL = ` - CREATE TABLE IF NOT EXISTS \`${tableName}\` ( - \`id\` bigint(20) unsigned NOT NULL AUTO_INCREMENT, - \`order_id\` bigint(20) unsigned DEFAULT NULL COMMENT '订单ID', - \`actual_price\` decimal(18,2) NOT NULL DEFAULT '0.00' COMMENT '实际价格', - \`retail_price\` decimal(18,2) DEFAULT NULL COMMENT '零售价格', - \`ext_code\` varchar(50) DEFAULT NULL COMMENT '外部编码', - \`inventory_type\` varchar(50) DEFAULT NULL COMMENT '库存类型', - \`item_code\` varchar(50) DEFAULT NULL COMMENT '商品编码', - \`item_id\` bigint(20) DEFAULT NULL COMMENT '商品ID', - \`item_name\` varchar(200) DEFAULT NULL COMMENT '商品名称', - \`order_line_no\` varchar(50) DEFAULT NULL COMMENT '订单行号', - \`owner_code\` varchar(50) DEFAULT NULL COMMENT '货主编码', - \`plan_qty\` int(11) DEFAULT NULL COMMENT '计划数量', - \`source_order_code\` varchar(50) DEFAULT NULL COMMENT '源订单编码', - \`sub_source_order_code\` varchar(50) DEFAULT NULL COMMENT '子源订单编码', - \`extend_props\` json DEFAULT NULL COMMENT '扩展属性(JSON格式)', - \`stock_id\` bigint(20) DEFAULT NULL COMMENT '库存ID', - \`created_at\` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', - \`updated_at\` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间' - ${historyFields}, - PRIMARY KEY (\`id\`), - KEY \`idx_${warehouseId}_order_id\` (\`order_id\`), - KEY \`idx_${warehouseId}_item_id\` (\`item_id\`), - KEY \`idx_${warehouseId}_item_code\` (\`item_code\`), - KEY \`idx_${warehouseId}_source_order_code\` (\`source_order_code\`), - KEY \`idx_${warehouseId}_stock_id\` (\`stock_id\`), - KEY \`idx_${warehouseId}_owner_code\` (\`owner_code\`), - KEY \`idx_${warehouseId}_order_item\` (\`order_id\`, \`item_id\`), - KEY \`idx_${warehouseId}_created_at\` (\`created_at\`) - ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='${tableComment}'; - `; - - await this.app.model.query(createTableSQL); - this.app.logger.info(`创建订单商品物理表成功: ${tableName}`); + await dynamicModel.sync({ alter: true }); + this.app.logger.info(`创建/同步订单商品物理表成功: ${tableName}`); } /** @@ -271,7 +481,11 @@ module.exports = app => { * @param {string} type 模型类型 */ generateTableName(warehouseId, type) { - const suffix = type === 'history' ? '_history' : ''; + const suffix = type === 'history' + ? '_history' + : type === 'dispatch' + ? '_dispatch' + : ''; return `wms_order_items_${warehouseId}${suffix}`; } @@ -283,6 +497,8 @@ module.exports = app => { clearCache(warehouseId, type) { const cacheKey = `${warehouseId}_${type}`; this.modelCache.delete(cacheKey); + this.creatingTables.delete(cacheKey); + clearShardWarehouseValidationCache(this.app); } /** @@ -290,6 +506,8 @@ module.exports = app => { */ clearAllCache() { this.modelCache.clear(); + this.creatingTables.clear(); + clearShardWarehouseValidationCache(this.app); } /** diff --git a/app/model/picking.js b/app/model/picking.js new file mode 100644 index 0000000..38f7b18 --- /dev/null +++ b/app/model/picking.js @@ -0,0 +1,128 @@ +'use strict'; + +module.exports = app => { + const { BIGINT, STRING, DATE, INTEGER } = app.Sequelize; + + const Picking = app.model.define('picking', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '订单ID', + }, + order_item_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '订单明细ID', + }, + storage_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '库存记录ID', + }, + quantity: { + type: INTEGER(10).UNSIGNED, + allowNull: false, + defaultValue: 1, + comment: '分配数量', + }, + space_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '库位ID', + }, + space_name: { + type: STRING(100), + allowNull: true, + comment: '库位名称', + }, + status: { + type: STRING(20), + allowNull: false, + defaultValue: 'pending', + comment: '状态', + }, + created_at: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + }, { + tableName: 'wms_picking', + freezeTableName: true, + underscored: true, + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + comment: '订单储位分配表', + indexes: [ + { + name: 'idx_wms_picking_order_id', + fields: [ 'order_id' ], + }, + { + name: 'idx_wms_picking_order_item_id', + fields: [ 'order_item_id' ], + }, + { + name: 'idx_wms_picking_storage_id', + fields: [ 'storage_id' ], + }, + { + name: 'idx_wms_picking_space_id', + fields: [ 'space_id' ], + }, + { + name: 'idx_wms_picking_status', + fields: [ 'status' ], + }, + { + name: 'idx_wms_picking_order_item_space', + fields: [ 'order_item_id', 'space_id' ], + }, + ], + }); + + Picking.associate = function() { + const { OrderItems, Storage, LocationSpace } = app.model; + + if (OrderItems) { + Picking.belongsTo(OrderItems, { + foreignKey: 'order_item_id', + as: 'orderItem', + constraints: false, + }); + } + + if (Storage) { + Picking.belongsTo(Storage, { + foreignKey: 'storage_id', + as: 'storageRecord', + constraints: false, + }); + } + + if (LocationSpace) { + Picking.belongsTo(LocationSpace, { + foreignKey: 'space_id', + as: 'space', + constraints: false, + }); + } + }; + + return Picking; +}; diff --git a/app/model/platform_setting.js b/app/model/platform_setting.js index 7ad3dc1..268748e 100644 --- a/app/model/platform_setting.js +++ b/app/model/platform_setting.js @@ -1,9 +1,14 @@ 'use strict'; +/** + * 平台设置模型定义。 + * + * @param {Egg.Application} app 应用实例 + * @return {Object} 平台设置模型 + */ module.exports = app => { const { STRING, BIGINT, INTEGER } = app.Sequelize; - // 修改这里的变量名,与文件名一致 const PlatformSetting = app.model.define('platform_setting', { id: { type: INTEGER(11), @@ -22,6 +27,11 @@ module.exports = app => { allowNull: false, comment: '设置代码', }, + name: { + type: STRING(100), + allowNull: false, + comment: '别名', + }, warehouse_id: { type: BIGINT(20), allowNull: false, @@ -34,33 +44,40 @@ module.exports = app => { comment: '平台设置表', indexes: [ { - name: 'platform_code', + name: 'uk_platform_setting_warehouse_platform_code', unique: true, fields: [ 'platform_code', 'warehouse_id' ], }, { - name: 'warehouse_id', + name: 'uk_platform_setting_warehouse_code', + unique: true, + fields: [ 'code', 'warehouse_id' ], + }, + { + name: 'idx_platform_setting_warehouse_id', fields: [ 'warehouse_id' ], }, ], }); - // 定义关联关系 + + /** + * 定义平台设置关联关系。 + */ PlatformSetting.associate = function() { const { Store, Platform } = app.model; - // 关联仓库 PlatformSetting.belongsTo(Platform, { foreignKey: 'platform_code', targetKey: 'code', as: 'platform', }); - // 关联仓库 + PlatformSetting.belongsTo(Store, { foreignKey: 'warehouse_id', targetKey: 'id', as: 'warehouse', }); }; - // 返回正确的变量名 + return PlatformSetting; }; diff --git a/app/model/stock_warehouse.js b/app/model/stock_warehouse.js index ea749c5..be9deb1 100644 --- a/app/model/stock_warehouse.js +++ b/app/model/stock_warehouse.js @@ -191,6 +191,26 @@ module.exports = app => { type: INTEGER(11).UNSIGNED, defaultValue: 0, }, + inbound_min_days: { + type: INTEGER(11), + defaultValue: 0, + comment: '入库最小天数要求', + }, + outbound_min_days: { + type: INTEGER(11), + defaultValue: 0, + comment: '出库最小天数要求', + }, + shelf_life_days: { + type: INTEGER(11), + defaultValue: 0, + comment: '保质期天数', + }, + remaining_threshold_days: { + type: INTEGER(11), + defaultValue: 0, + comment: '剩余有效期阈值天数', + }, deleted_at: { type: DATE, defaultValue: null, diff --git a/app/model/store.js b/app/model/store.js index b59e68e..4452456 100644 --- a/app/model/store.js +++ b/app/model/store.js @@ -5,8 +5,19 @@ module.exports = app => { const DEFAULT_MAX_NOTICE_WEBHOOK_COUNT = 5; const DEFAULT_SUBJECT_CONFIG = Object.freeze({ max_notice_webhook_count: DEFAULT_MAX_NOTICE_WEBHOOK_COUNT, + default_express_code: 'STO', + default_platform_code: 'TB', }); + const normalizeSubjectConfigText = (value, defaultValue) => { + if (value === undefined || value === null) { + return defaultValue; + } + + const normalized = String(value).trim(); + return normalized === '' ? defaultValue : normalized; + }; + const normalizeBooleanFlag = (value, fieldName) => { if (value === undefined || value === null || value === '') { return undefined; @@ -56,6 +67,15 @@ module.exports = app => { normalized.max_notice_webhook_count = limit; } + normalized.default_express_code = normalizeSubjectConfigText( + parsed.default_express_code, + DEFAULT_SUBJECT_CONFIG.default_express_code + ); + normalized.default_platform_code = normalizeSubjectConfigText( + parsed.default_platform_code, + DEFAULT_SUBJECT_CONFIG.default_platform_code + ); + if (Object.prototype.hasOwnProperty.call(parsed, 'webhook_enabled')) { normalized.webhook_enabled = normalizeBooleanFlag(parsed.webhook_enabled, 'subject_config.webhook_enabled'); } diff --git a/app/model/store_warehouse.js b/app/model/store_warehouse.js index f1ffa84..4b907e8 100644 --- a/app/model/store_warehouse.js +++ b/app/model/store_warehouse.js @@ -11,16 +11,11 @@ module.exports = app => { default: 'standard', required: false, description: '控制货主在该仓下的收货校验模式', - options: [ 'standard', 'strict', 'manual' ], - }), - Object.freeze({ - key: 'sku_visibility', - name: 'SKU 可见范围', - type: 'enum', - default: 'all', - required: false, - description: '控制货主在该仓下的 SKU 可见策略', - options: [ 'all', 'whitelist', 'blacklist' ], + options: [ + Object.freeze({ value: 'standard', label: '标准收货' }), + Object.freeze({ value: 'strict', label: '严格收货' }), + Object.freeze({ value: 'manual', label: '人工收货' }), + ], }), Object.freeze({ key: 'auto_allocate_bin', @@ -46,6 +41,14 @@ module.exports = app => { required: false, description: '是否允许进入临时存放区', }), + Object.freeze({ + key: 'storage_separation', + name: '是否存储分离', + type: 'flag', + default: 1, + required: false, + description: '控制该货主在当前仓库下是否按独立存储策略管理库存', + }), Object.freeze({ key: 'allow_oversell', name: '允许超卖', @@ -62,6 +65,22 @@ module.exports = app => { required: false, description: '控制货主推送订单创建后是否必须进入审批流程', }), + Object.freeze({ + key: 'default_express_code', + name: '默认快递', + type: 'list', + default: 'STO', + required: false, + description: '货主在当前仓下默认使用的快递编码', + }), + Object.freeze({ + key: 'default_platform_code', + name: '默认平台', + type: 'list', + default: 'TB', + required: false, + description: '货主在当前仓下默认使用的平台编码', + }), Object.freeze({ key: 'print_recharge_price', name: '面单充值元/单', @@ -99,6 +118,38 @@ module.exports = app => { return result; }, {})); + const clonePolicyConfigOptions = options => { + if (!Array.isArray(options)) { + return undefined; + } + + return options.map(option => { + if (!option || typeof option !== 'object') { + return option; + } + + return { ...option }; + }); + }; + + const getPolicyConfigOptionValue = option => { + if (option && typeof option === 'object') { + if (option.value !== undefined && option.value !== null) { + return String(option.value); + } + + if (option.code !== undefined && option.code !== null) { + return String(option.code); + } + + if (option.key !== undefined && option.key !== null) { + return String(option.key); + } + } + + return String(option); + }; + const clonePolicyConfigField = field => ({ key: field.key, name: field.name, @@ -106,7 +157,7 @@ module.exports = app => { default: field.default, required: field.required, description: field.description, - ...(Array.isArray(field.options) ? { options: [ ...field.options ] } : {}), + ...(Array.isArray(field.options) ? { options: clonePolicyConfigOptions(field.options) } : {}), ...(field.min !== undefined ? { min: field.min } : {}), ...(field.max !== undefined ? { max: field.max } : {}), ...(field.precision !== undefined ? { precision: field.precision } : {}), @@ -114,6 +165,26 @@ module.exports = app => { ...(field.maxLength !== undefined ? { maxLength: field.maxLength } : {}), }); + const normalizePolicyConfigOptionValue = option => { + if (!option || typeof option !== 'object') { + return String(option); + } + + if (option.value !== undefined && option.value !== null) { + return String(option.value); + } + + if (option.code !== undefined && option.code !== null) { + return String(option.code); + } + + if (option.key !== undefined && option.key !== null) { + return String(option.key); + } + + return ''; + }; + const parsePolicyConfig = (value, fieldName = 'policy_config') => { if (typeof value === 'string') { try { @@ -167,13 +238,24 @@ module.exports = app => { try { if (field.type === 'enum') { const valueText = String(rawValue).trim(); - if (!field.options.includes(valueText)) { + const allowedValues = Array.isArray(field.options) + ? field.options.map(getPolicyConfigOptionValue) + : []; + if (!allowedValues.includes(valueText)) { throw new Error(`${fieldName}.${field.key} 参数不合法`); } normalized[field.key] = valueText; continue; } + if (field.type === 'list') { + const valueText = String(rawValue).trim(); + if (valueText) { + normalized[field.key] = valueText; + } + continue; + } + if (field.type === 'flag') { if (rawValue === true || rawValue === 1 || rawValue === '1') { normalized[field.key] = 1; @@ -481,6 +563,47 @@ module.exports = app => { return POLICY_CONFIG_FIELDS.map(clonePolicyConfigField); }; + StoreWarehouse.getPolicyConfigFieldListWithOptions = async function() { + const fieldList = this.getPolicyConfigFieldList(); + const [ expressRows, platformRows ] = await Promise.all([ + app.model.Express && typeof app.model.Express.findAll === 'function' + ? app.model.Express.findAll({ + attributes: [ 'code', 'name' ], + order: [[ 'code', 'ASC' ]], + }) + : Promise.resolve([]), + app.model.Platform && typeof app.model.Platform.findAll === 'function' + ? app.model.Platform.findAll({ + attributes: [ 'code', 'name' ], + order: [[ 'code', 'ASC' ]], + }) + : Promise.resolve([]), + ]); + + const optionMap = { + default_express_code: expressRows.map(item => ({ + value: normalizePolicyConfigOptionValue(item), + label: String(item.name || item.code || ''), + })), + default_platform_code: platformRows.map(item => ({ + value: normalizePolicyConfigOptionValue(item), + label: String(item.name || item.code || ''), + })), + }; + + return fieldList.map(field => { + const options = optionMap[field.key]; + if (!options) { + return field; + } + + return { + ...field, + options, + }; + }); + }; + StoreWarehouse.normalizePolicyConfig = function(value, options = {}) { return normalizePolicyConfig(value, options); }; diff --git a/app/router.js b/app/router.js index 0914efe..ec80e7d 100644 --- a/app/router.js +++ b/app/router.js @@ -14,6 +14,10 @@ module.exports = app => { // 系统接口 PDA/WEB 统一入口 router.post('/system', controller.home.system); + // 独立 docs 目录挂载 + router.get('/docs', controller.docs.docsIndex); + router.get('/docs/:relPath(.*)', controller.docs.docsFile); + // api文档相关 router.get('/api/docs', controller.docs.list); router.get('/api/docs/:docName/raw', controller.docs.raw); @@ -30,6 +34,10 @@ 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); }; diff --git a/app/schedule/notice_stock_remaining.js b/app/schedule/notice_stock_remaining.js new file mode 100644 index 0000000..735fe88 --- /dev/null +++ b/app/schedule/notice_stock_remaining.js @@ -0,0 +1,733 @@ +'use strict'; + +const CACHE_KEY_PREFIX = 'notice_stock_remaining_notified'; +const LEGACY_CACHE_KEY = 'notice_stock_remaining_notified_list'; +const CACHE_TTL_SECONDS = 24 * 60 * 60; +const DAY_MS = 24 * 60 * 60 * 1000; +const NOTICE_EVENT = 'storage_transfer_completed'; + +/** + * 生成本地日期键,格式为 `YYYYMMDD`。 + * @param {Date} [dateValue=new Date()] 日期对象 + * @return {string} 日期键 + */ +function buildDateKey(dateValue = new Date()) { + const year = String(dateValue.getFullYear()); + const month = String(dateValue.getMonth() + 1).padStart(2, '0'); + const day = String(dateValue.getDate()).padStart(2, '0'); + return `${year}${month}${day}`; +} + +/** + * 生成商品维度的日粒度缓存键。 + * @param {number} stockId 商品ID + * @param {Date} [dateValue=new Date()] 日期对象 + * @return {string} 缓存键 + */ +function buildStockDayCacheKey(stockId, dateValue = new Date()) { + const normalizedStockId = toNumber(stockId, 0); + if (normalizedStockId <= 0) { + return ''; + } + + return `${CACHE_KEY_PREFIX}:stock:${normalizedStockId}:${buildDateKey(dateValue)}`; +} + +/** + * 从记录对象中安全读取字段,兼容下划线和驼峰命名。 + * @param {object} record 记录对象 + * @param {string[]} fieldNames 候选字段名列表 + * @return {*} 命中的字段值 + */ +function readRecordValue(record, fieldNames) { + if (!record || !Array.isArray(fieldNames)) { + return undefined; + } + + for (const fieldName of fieldNames) { + if (!fieldName) { + continue; + } + + if (Object.prototype.hasOwnProperty.call(record, fieldName)) { + return record[fieldName]; + } + + if (record.dataValues && Object.prototype.hasOwnProperty.call(record.dataValues, fieldName)) { + return record.dataValues[fieldName]; + } + + if (typeof record.getDataValue === 'function') { + try { + const dataValue = record.getDataValue(fieldName); + if (dataValue !== undefined) { + return dataValue; + } + } catch (error) { + // 忽略单个字段读取失败,继续尝试其他候选字段。 + } + } + + if (typeof record.get === 'function') { + try { + const getterValue = record.get(fieldName); + if (getterValue !== undefined) { + return getterValue; + } + } catch (error) { + // 忽略单个字段读取失败,继续尝试其他候选字段。 + } + } + } + + return undefined; +} + +/** + * 将数值安全转换为数字。 + * @param {*} value 原始值 + * @param {number} [fallback=0] 转换失败时的兜底值 + * @return {number} 数值结果 + */ +function toNumber(value, fallback = 0) { + const numberValue = Number(value); + return Number.isFinite(numberValue) ? numberValue : fallback; +} + +/** + * 归一化历史全局缓存中的已通知列表。 + * + * 注意:该方法仅用于兼容旧格式的观测或迁移,不再参与新去重逻辑, + * 避免旧的全局列表继续抑制当天的通知。 + * + * @param {*} rawValue 缓存原始值 + * @return {string[]} 标准化后的通知键列表 + */ +function normalizeNotifiedList(rawValue) { + if (!rawValue) { + return []; + } + + let parsedValue = rawValue; + + if (typeof rawValue === 'string') { + try { + parsedValue = JSON.parse(rawValue); + } catch (error) { + return []; + } + } + + const list = Array.isArray(parsedValue) + ? parsedValue + : (typeof parsedValue === 'object' && parsedValue !== null + ? Object.values(parsedValue) + : []); + + return list.map(item => { + if (item && typeof item === 'object') { + const stockId = readRecordValue(item, [ 'stock_id', 'stockId' ]); + if (stockId !== undefined && stockId !== null && String(stockId).trim() !== '') { + return `stock:${String(stockId)}`; + } + + const itemId = readRecordValue(item, [ 'id', 'storage_id', 'storageId' ]); + if (itemId !== undefined && itemId !== null && String(itemId).trim() !== '') { + return `storage:${String(itemId)}`; + } + } + + const normalizedValue = String(item || '').trim(); + if (!normalizedValue) { + return ''; + } + + if (normalizedValue.startsWith('storage:')) { + return normalizedValue; + } + + if (/^\d+$/.test(normalizedValue)) { + return `storage:${normalizedValue}`; + } + + return normalizedValue; + }).filter(Boolean); +} + +/** + * 生成库存记录对应的商品级通知去重键。 + * @param {object} storageRecord 库存记录 + * @return {string} 去重键 + */ +function buildStockNotifyKey(storageRecord) { + const stockId = toNumber(readRecordValue(storageRecord, [ 'stock_id', 'stockId' ]), 0); + return stockId > 0 ? `stock:${stockId}` : ''; +} + +/** + * 按商品 ID 对库存记录进行分组。 + * @param {object[]} storageRows 库存记录列表 + * @return {Map} 分组后的库存记录映射 + */ +function groupStorageRowsByStockId(storageRows) { + const groupedStorageRows = new Map(); + + if (!Array.isArray(storageRows)) { + return groupedStorageRows; + } + + for (const storageRow of storageRows) { + const stockId = toNumber(readRecordValue(storageRow, [ 'stock_id', 'stockId' ]), 0); + if (stockId <= 0) { + continue; + } + + const stockStorageRows = groupedStorageRows.get(stockId) || []; + stockStorageRows.push(storageRow); + groupedStorageRows.set(stockId, stockStorageRows); + } + + return groupedStorageRows; +} + +/** + * 格式化日期字符串,优先使用应用内格式化器。 + * @param {object} ctx Egg 上下文 + * @param {*} value 原始日期值 + * @return {string} 格式化后的日期字符串 + */ +function formatDate(ctx, value) { + if (!value) { + return ''; + } + + const dateValue = value instanceof Date ? value : new Date(value); + if (Number.isNaN(dateValue.getTime())) { + return ''; + } + + if (ctx && ctx.app && typeof ctx.app.formatDate === 'function') { + return ctx.app.formatDate(dateValue); + } + + return dateValue.toISOString(); +} + +/** + * 生成库存效期预警通知内容。 + * @param {object} params 参数对象 + * @param {object} params.ctx Egg 上下文 + * @param {object} params.storageRecord 库存记录 + * @param {object} params.stockRecord 商品主数据 + * @param {number} params.remainingDays 剩余天数 + * @param {number} params.thresholdDays 预警阈值天数 + * @return {string} 通知正文 + */ +function buildNoticeContent({ ctx, storageRecord, stockRecord, remainingDays, thresholdDays }) { + const storageId = toNumber(readRecordValue(storageRecord, [ 'id', 'storage_id', 'storageId' ]), 0); + const stockId = toNumber(readRecordValue(storageRecord, [ 'stock_id', 'stockId' ]), 0); + const itemCode = String(readRecordValue(stockRecord, [ 'item_code', 'itemCode' ]) || '').trim() || String(stockId || storageId); + const itemName = String(readRecordValue(stockRecord, [ 'item_name', 'itemName' ]) || '').trim() || '未命名商品'; + const batchNo = String(readRecordValue(storageRecord, [ 'batch_no', 'batchNo' ]) || '').trim() || '无'; + const warehouseId = toNumber(readRecordValue(storageRecord, [ 'warehouse_id', 'warehouseId' ]), 0); + const storeId = toNumber(readRecordValue(storageRecord, [ 'store_id', 'storeId' ]), 0); + const expiryDate = formatDate(ctx, readRecordValue(storageRecord, [ 'expiry_date', 'expiryDate' ])); + const inboundTime = formatDate(ctx, readRecordValue(storageRecord, [ 'inbound_time', 'inboundTime' ])); + const quantity = toNumber(readRecordValue(storageRecord, [ 'quantity' ]), 0); + const availableQuantity = toNumber(readRecordValue(storageRecord, [ 'available_quantity', 'availableQuantity' ]), quantity); + const spaceRecord = readRecordValue(storageRecord, [ 'space' ]) || storageRecord.space || {}; + const spaceCode = String(readRecordValue(spaceRecord, [ 'space_code', 'spaceCode' ]) || '').trim(); + const spaceName = String(readRecordValue(spaceRecord, [ 'custom_name', 'customName' ]) || '').trim(); + const spaceLabel = [ spaceCode, spaceName ].filter(Boolean).join(' / ') || '无'; + + return [ + `库存效期预警:${itemName}`, + `商品编码:${itemCode}`, + `库存ID:${storageId || '未知'}`, + `批次号:${batchNo}`, + `仓库ID:${warehouseId || '未知'}`, + `货主ID:${storeId || '未知'}`, + `库位:${spaceLabel}`, + `库存数量:${quantity}`, + `可用数量:${availableQuantity}`, + `效期日期:${expiryDate || '未知'}`, + `剩余天数:${remainingDays}`, + `预警阈值:${thresholdDays}`, + `入库时间:${inboundTime || '未知'}`, + ].join('\n'); +} + +/** + * 解析库存效期预警通知的发送方法,优先使用 `send`,其次兼容 `index.send`。 + * @param {object} ctx Egg 上下文 + * @return {Function|null} 可执行的发送方法 + */ +function resolveNoticeSendMethod(ctx) { + const noticeService = ctx && ctx.service && ctx.service.systems && ctx.service.systems.notice; + if (!noticeService) { + return null; + } + + if (typeof noticeService.send === 'function') { + return noticeService.send.bind(noticeService); + } + + if (noticeService.index && typeof noticeService.index.send === 'function') { + return noticeService.index.send.bind(noticeService.index); + } + + return null; +} + +/** + * 发送库存效期预警通知。 + * @param {object} ctx Egg 上下文 + * @param {object} payload 通知参数 + * @return {Promise} 通知发送结果 + */ +async function sendStockRemainingNotice(ctx, payload) { + const sendMethod = resolveNoticeSendMethod(ctx); + if (typeof sendMethod !== 'function') { + throw new Error('通知服务不可用'); + } + + return await sendMethod(payload); +} + +module.exports = { + schedule: { + interval: '30s', + type: 'worker', + immediate: false, + disable: false, + }, + + /** + * 执行库存效期预警扫描。 + * @param {object} ctx Egg 上下文 + * @return {Promise} + */ + async task(ctx) { + const scheduleName = 'notice_stock_remaining'; + let stockCount = 0; + let storageCount = 0; + let sentCount = 0; + let skippedCount = 0; + const today = new Date(); + + ctx.logger.info(`[${scheduleName}] 本轮任务启动`, { + scheduleName, + cacheKeyPrefix: CACHE_KEY_PREFIX, + running: Boolean(ctx.app._noticeStockRemainingRunning), + }); + + if (ctx.app._noticeStockRemainingRunning) { + ctx.logger.info(`[${scheduleName}] 本轮任务跳过,上一轮尚未结束`, { + scheduleName, + cacheKeyPrefix: CACHE_KEY_PREFIX, + running: Boolean(ctx.app._noticeStockRemainingRunning), + }); + return; + } + + ctx.app._noticeStockRemainingRunning = true; + + try { + const legacyCachedValue = typeof ctx.app.getCacheAsync === 'function' + ? await ctx.app.getCacheAsync(LEGACY_CACHE_KEY) + : null; + const legacyCacheHit = legacyCachedValue !== null && legacyCachedValue !== undefined; + const legacyNotifiedList = normalizeNotifiedList(legacyCachedValue); + + ctx.logger.info('[notice_stock_remaining] 已检查历史通知缓存', { + legacyCacheKey: LEGACY_CACHE_KEY, + cacheHit: legacyCacheHit, + cachedValueType: Array.isArray(legacyCachedValue) ? 'array' : typeof legacyCachedValue, + rawCacheCount: Array.isArray(legacyCachedValue) ? legacyCachedValue.length : 0, + normalizedCount: legacyNotifiedList.length, + cacheKeyMode: 'stock-day', + }); + + if (legacyCacheHit) { + ctx.logger.warn('[notice_stock_remaining] 检测到旧的全局去重缓存,当前版本不再使用该缓存参与拦截', { + legacyCacheKey: LEGACY_CACHE_KEY, + normalizedCount: legacyNotifiedList.length, + }); + } + + ctx.logger.debug('[notice_stock_remaining] 日粒度去重已启用', { + cacheKeyPrefix: CACHE_KEY_PREFIX, + dateKey: buildDateKey(today), + }); + + const stockWhere = { + is_shelf_life_mgmt: 'Y', + remaining_threshold_days: { + [ctx.app.Sequelize.Op.gt]: 0, + }, + }; + + const stockRows = await ctx.model.StockWarehouse.findAll({ + attributes: [ + 'id', + 'item_code', + 'item_name', + 'store_id', + 'warehouse_id', + 'remaining_threshold_days', + ], + where: stockWhere, + order: [[ 'remaining_threshold_days', 'ASC' ], [ 'id', 'ASC' ]], + raw: true, + }); + + stockCount = Array.isArray(stockRows) ? stockRows.length : 0; + ctx.logger.info('[notice_stock_remaining] 完成商品候选查询', { + stockCount, + }); + + if (Array.isArray(stockRows)) { + for (const stockRow of stockRows) { + ctx.logger.debug('[notice_stock_remaining] 商品候选明细', { + id: toNumber(readRecordValue(stockRow, [ 'id' ]), 0), + item_code: String(readRecordValue(stockRow, [ 'item_code', 'itemCode' ]) || '').trim(), + remaining_threshold_days: Math.max(0, Math.floor(toNumber(readRecordValue(stockRow, [ 'remaining_threshold_days', 'remainingThresholdDays' ]), 0))), + }); + } + } + + if (!Array.isArray(stockRows) || stockRows.length === 0) { + ctx.logger.info('[notice_stock_remaining] 未找到开启效期管理且阈值大于 0 的商品'); + return; + } + + const stockMap = new Map(); + let maxThresholdDays = 0; + + for (const stockRow of stockRows) { + const stockId = toNumber(readRecordValue(stockRow, [ 'id' ]), 0); + const thresholdDays = Math.max(0, Math.floor(toNumber(readRecordValue(stockRow, [ 'remaining_threshold_days', 'remainingThresholdDays' ]), 0))); + + if (stockId <= 0 || thresholdDays <= 0) { + continue; + } + + stockMap.set(stockId, { + id: stockId, + item_code: String(readRecordValue(stockRow, [ 'item_code', 'itemCode' ]) || '').trim(), + item_name: String(readRecordValue(stockRow, [ 'item_name', 'itemName' ]) || '').trim(), + store_id: toNumber(readRecordValue(stockRow, [ 'store_id', 'storeId' ]), 0), + warehouse_id: toNumber(readRecordValue(stockRow, [ 'warehouse_id', 'warehouseId' ]), 0), + remaining_threshold_days: thresholdDays, + }); + + if (thresholdDays > maxThresholdDays) { + maxThresholdDays = thresholdDays; + } + } + + const stockIds = Array.from(stockMap.keys()); + if (stockIds.length === 0 || maxThresholdDays <= 0) { + ctx.logger.info('[notice_stock_remaining] 商品数据中没有可用的效期预警阈值', { + stockCount, + validStockCount: stockIds.length, + maxThresholdDays, + }); + return; + } + + const now = new Date(); + const maxExpiryDate = new Date(now.getTime() + (maxThresholdDays * DAY_MS)); + const storageWhere = { + stock_id: { + [ctx.app.Sequelize.Op.in]: stockIds, + }, + is_enabled: 1, + delete_at: null, + quantity: { + [ctx.app.Sequelize.Op.gt]: 0, + }, + expiry_date: { + [ctx.app.Sequelize.Op.ne]: null, + [ctx.app.Sequelize.Op.lte]: maxExpiryDate, + }, + }; + + const storageRows = await ctx.model.Storage.findAll({ + where: storageWhere, + include: [ + { + model: ctx.model.LocationSpace, + as: 'space', + attributes: [ 'space_code', 'custom_name' ], + required: false, + }, + ], + order: [[ 'expiry_date', 'ASC' ], [ 'inbound_time', 'ASC' ], [ 'id', 'ASC' ]], + }); + + storageCount = Array.isArray(storageRows) ? storageRows.length : 0; + + ctx.logger.info('[notice_stock_remaining] 完成库存候选查询', { + stockCount: stockIds.length, + storageCount, + maxThresholdDays, + }); + + if (Array.isArray(storageRows)) { + for (const storageRow of storageRows) { + ctx.logger.debug('[notice_stock_remaining] 库存候选明细', { + id: toNumber(readRecordValue(storageRow, [ 'id', 'storage_id', 'storageId' ]), 0), + stock_id: toNumber(readRecordValue(storageRow, [ 'stock_id', 'stockId' ]), 0), + expiry_date: formatDate(ctx, readRecordValue(storageRow, [ 'expiry_date', 'expiryDate' ])), + quantity: toNumber(readRecordValue(storageRow, [ 'quantity' ]), 0), + available_quantity: toNumber(readRecordValue(storageRow, [ 'available_quantity', 'availableQuantity' ]), toNumber(readRecordValue(storageRow, [ 'quantity' ]), 0)), + }); + } + } + + const groupedStorageRows = groupStorageRowsByStockId(storageRows); + const representativeStorageRows = Array.from(groupedStorageRows.values()).map(stockStorageRows => stockStorageRows[0]); + + for (const storageRecord of representativeStorageRows) { + const storageId = toNumber(readRecordValue(storageRecord, [ 'id', 'storage_id', 'storageId' ]), 0); + const stockId = toNumber(readRecordValue(storageRecord, [ 'stock_id', 'stockId' ]), 0); + const notifyKey = buildStockNotifyKey(storageRecord); + const stockDayCacheKey = buildStockDayCacheKey(stockId, today); + const stockRecord = stockMap.get(stockId); + const thresholdDays = stockRecord ? toNumber(readRecordValue(stockRecord, [ 'remaining_threshold_days', 'remainingThresholdDays' ]), 0) : 0; + + if (!notifyKey) { + skippedCount += 1; + ctx.logger.debug('[notice_stock_remaining] 跳过代表库存', { + storageId, + stockId, + notifyKey, + reason: 'notifyKey 为空', + }); + continue; + } + + if (!stockDayCacheKey) { + skippedCount += 1; + ctx.logger.debug('[notice_stock_remaining] 跳过代表库存', { + storageId, + stockId, + notifyKey, + reason: '日粒度缓存键为空', + }); + continue; + } + + if (!stockRecord) { + skippedCount += 1; + ctx.logger.debug('[notice_stock_remaining] 跳过代表库存', { + storageId, + stockId, + notifyKey, + reason: '未找到对应商品记录', + }); + continue; + } + + if (typeof ctx.app.getCacheAsync === 'function') { + const cachedNotifiedValue = await ctx.app.getCacheAsync(stockDayCacheKey); + if (cachedNotifiedValue !== null && cachedNotifiedValue !== undefined) { + skippedCount += 1; + ctx.logger.debug('[notice_stock_remaining] 跳过代表库存', { + storageId, + stockId, + notifyKey, + stockDayCacheKey, + reason: '当日已通知过该商品', + }); + continue; + } + } + + if (thresholdDays <= 0) { + skippedCount += 1; + ctx.logger.debug('[notice_stock_remaining] 跳过代表库存', { + storageId, + stockId, + notifyKey, + thresholdDays, + reason: '商品阈值小于等于 0', + }); + continue; + } + + const expiryDateValue = readRecordValue(storageRecord, [ 'expiry_date', 'expiryDate' ]); + if (!expiryDateValue) { + skippedCount += 1; + ctx.logger.debug('[notice_stock_remaining] 跳过代表库存', { + storageId, + stockId, + notifyKey, + thresholdDays, + reason: '缺少效期日期', + }); + continue; + } + + const expiryDate = expiryDateValue instanceof Date ? expiryDateValue : new Date(expiryDateValue); + if (Number.isNaN(expiryDate.getTime())) { + ctx.logger.warn('[notice_stock_remaining] 跳过非法效期日期', { + storageId, + stockId, + expiryDate: String(expiryDateValue), + }); + skippedCount += 1; + ctx.logger.debug('[notice_stock_remaining] 跳过代表库存', { + storageId, + stockId, + notifyKey, + thresholdDays, + reason: '效期日期非法', + }); + continue; + } + + const remainingDays = Math.max(0, Math.ceil((expiryDate.getTime() - now.getTime()) / DAY_MS)); + if (remainingDays > thresholdDays) { + skippedCount += 1; + ctx.logger.debug('[notice_stock_remaining] 跳过代表库存', { + storageId, + stockId, + notifyKey, + thresholdDays, + remainingDays, + reason: '剩余天数大于阈值', + }); + continue; + } + + const warehouseId = toNumber(readRecordValue(storageRecord, [ 'warehouse_id', 'warehouseId' ]) || stockRecord.warehouse_id, 0); + const storeId = toNumber(readRecordValue(storageRecord, [ 'store_id', 'storeId' ]) || stockRecord.store_id, 0); + const title = `库存效期预警:${stockRecord.item_name || '未命名商品'}`; + const content = buildNoticeContent({ + ctx, + storageRecord, + stockRecord, + remainingDays, + thresholdDays, + }); + + ctx.logger.info('[notice_stock_remaining] 进入发送分支', { + storageId, + stockId, + notifyKey, + remainingDays, + thresholdDays, + warehouseId, + storeId, + }); + + try { + const noticeResult = await sendStockRemainingNotice(ctx, { + warehouseId, + storeId, + subject: { + id: warehouseId, + type: 'warehouse', + name: `仓库${warehouseId || '未知'}`, + }, + businessName: 'storage', + event: NOTICE_EVENT, + title, + content, + businessId: stockId, + messageType: 'text', + metadata: { + cacheKey: stockDayCacheKey, + storageId, + stockId, + notifyKey, + businessId: stockId, + thresholdDays, + remainingDays, + warehouseId, + storeId, + stock: { + id: stockRecord.id, + item_code: stockRecord.item_code, + item_name: stockRecord.item_name, + }, + storage: { + id: storageId, + batch_no: readRecordValue(storageRecord, [ 'batch_no', 'batchNo' ]) || '', + expiry_date: expiryDate.toISOString(), + }, + }, + }); + + if (noticeResult && noticeResult.success === false) { + ctx.logger.warn('[notice_stock_remaining] 通知发送失败,保留待重试状态', { + storageId, + stockId, + notifyKey, + stockDayCacheKey, + remainingDays, + thresholdDays, + result: noticeResult, + }); + continue; + } + + if (typeof ctx.app.setCacheAsync === 'function') { + await ctx.app.setCacheAsync(stockDayCacheKey, { + notifiedAt: today.toISOString(), + stockId, + notifyKey, + }, CACHE_TTL_SECONDS); + } + sentCount += 1; + + ctx.logger.info('[notice_stock_remaining] 库存效期预警已发送', { + storageId, + stockId, + notifyKey, + stockDayCacheKey, + remainingDays, + thresholdDays, + result: noticeResult, + }); + } catch (noticeError) { + ctx.logger.error('[notice_stock_remaining] 库存效期预警发送异常', { + storageId, + stockId, + notifyKey, + stockDayCacheKey, + remainingDays, + thresholdDays, + error: noticeError.message, + stack: noticeError.stack, + }); + } + } + + ctx.logger.info('[notice_stock_remaining] 本轮通知缓存按商品日粒度独立写入,无需整体回写', { + cacheKeyPrefix: CACHE_KEY_PREFIX, + sentCount, + skippedCount, + ttlSeconds: CACHE_TTL_SECONDS, + }); + } catch (error) { + ctx.logger.error('[notice_stock_remaining] 执行失败', { + error: error.message, + stack: error.stack, + }); + } finally { + ctx.app._noticeStockRemainingRunning = false; + ctx.logger.info('[notice_stock_remaining] 本轮任务结束', { + scheduleName, + cacheKeyPrefix: CACHE_KEY_PREFIX, + stockCount, + storageCount, + sentCount, + skippedCount, + running: Boolean(ctx.app._noticeStockRemainingRunning), + }); + } + }, +}; diff --git a/app/schedule/sync_outbound_orders_to_delivery.js b/app/schedule/sync_outbound_orders_to_delivery.js new file mode 100644 index 0000000..804fa8d --- /dev/null +++ b/app/schedule/sync_outbound_orders_to_delivery.js @@ -0,0 +1,51 @@ +'use strict'; + +const SHORT_TASK_QUERY_TIMEOUT_MS = 15000; +const SHORT_TASK_EXECUTION_TIMEOUT_MS = 30000; + +/** + * 每 1 分钟在单 worker 中同步一次正常出库订单到配送表。 + */ +module.exports = { + schedule: { + interval: '1m', + type: 'worker', + immediate: false, + disable: false, + }, + + queryTimeoutMs: SHORT_TASK_QUERY_TIMEOUT_MS, + + executionTimeoutMs: SHORT_TASK_EXECUTION_TIMEOUT_MS, + + /** + * 执行已出库订单迁移任务。 + * + * @param {Object} ctx Egg 上下文。 + * @return {Promise} 无返回值。 + */ + async task(ctx) { + if (ctx.app._syncOutboundOrdersToDeliveryRunning) { + return; + } + + ctx.app._syncOutboundOrdersToDeliveryRunning = true; + + try { + const result = await ctx.service.systems.orderDeliveryMigration.syncOutboundOrdersToDelivery({ + queryTimeoutMs: SHORT_TASK_QUERY_TIMEOUT_MS, + executionTimeoutMs: SHORT_TASK_EXECUTION_TIMEOUT_MS, + }); + + if (result && result.retryableFailure) { + ctx.logger.warn(`[sync-outbound-orders-to-delivery] 正常迁移遇到 ${result.retryableFailureType},已标记 ${result.timeoutCount || 0} 条订单为出库超时`); + } else if (result && result.totalCreated > 0) { + ctx.logger.info(`[sync-outbound-orders-to-delivery] 同步 ${result.totalCreated} 条已出库订单`); + } + } catch (error) { + ctx.logger.error(`[sync-outbound-orders-to-delivery] 同步失败: ${error.message}`); + } finally { + ctx.app._syncOutboundOrdersToDeliveryRunning = false; + } + }, +}; diff --git a/app/schedule/sync_outbound_timeout_orders_to_delivery.js b/app/schedule/sync_outbound_timeout_orders_to_delivery.js new file mode 100644 index 0000000..48556c5 --- /dev/null +++ b/app/schedule/sync_outbound_timeout_orders_to_delivery.js @@ -0,0 +1,51 @@ +'use strict'; + +const LONG_TASK_QUERY_TIMEOUT_MS = 120000; +const LONG_TASK_EXECUTION_TIMEOUT_MS = 300000; + +/** + * 每 10 分钟在单 worker 中重试一次出库超时订单到配送表。 + */ +module.exports = { + schedule: { + interval: '10m', + type: 'worker', + immediate: false, + disable: false, + }, + + queryTimeoutMs: LONG_TASK_QUERY_TIMEOUT_MS, + + executionTimeoutMs: LONG_TASK_EXECUTION_TIMEOUT_MS, + + /** + * 执行出库超时订单重试任务。 + * + * @param {Object} ctx Egg 上下文。 + * @return {Promise} 无返回值。 + */ + async task(ctx) { + if (ctx.app._syncTimeoutOutboundOrdersToDeliveryRunning) { + return; + } + + ctx.app._syncTimeoutOutboundOrdersToDeliveryRunning = true; + + try { + const result = await ctx.service.systems.orderDeliveryMigration.retryTimeoutOutboundOrdersToDelivery({ + queryTimeoutMs: LONG_TASK_QUERY_TIMEOUT_MS, + executionTimeoutMs: LONG_TASK_EXECUTION_TIMEOUT_MS, + }); + + if (result && result.retryableFailure) { + ctx.logger.warn(`[sync-outbound-timeout-orders-to-delivery] 重试出库超时订单遇到 ${result.retryableFailureType}`); + } else if (result && result.totalCreated > 0) { + ctx.logger.info(`[sync-outbound-timeout-orders-to-delivery] 重试同步 ${result.totalCreated} 条出库超时订单`); + } + } catch (error) { + ctx.logger.error(`[sync-outbound-timeout-orders-to-delivery] 重试失败: ${error.message}`); + } finally { + ctx.app._syncTimeoutOutboundOrdersToDeliveryRunning = false; + } + }, +}; diff --git a/app/service/qimen.js b/app/service/qimen.js index 8e2b44d..1857a9f 100644 --- a/app/service/qimen.js +++ b/app/service/qimen.js @@ -58,12 +58,8 @@ class QimenService extends Service { parseAttributeValue: false, trimValues: false, // 也关闭trim,保持原始格式 ignoreDeclaration: true, - // 添加标签值处理器,手动控制转换 - tagValueProcessor: tagValue => { - // 如果是叶子节点且需要保持字符串格式的标签,可以在这里特殊处理 - // 默认返回原始值 - return tagValue; - }, + // 保持 fast-xml-parser 的真实叶子文本值,避免把标签名误当成字段值。 + tagValueProcessor: (tagName, tagValue) => tagValue, }); try { @@ -233,6 +229,12 @@ class QimenService extends Service { } }); } + /** + * 保存奇门请求日志。 + * @param {Object} logData 日志数据。 + * @param {number} startTime 请求开始时间戳。 + * @return {Promise} 新增日志ID。 + */ async saveQimenLog(logData, startTime) { const { ctx, @@ -252,6 +254,7 @@ class QimenService extends Service { // 使用 egg-mysql 保存日志到数据库 const result = await ctx.app.mysql.get('wms').insert('wms_qimen_log', { + log_id: logData.log_id || ctx.qimenLogId || null, from_key: logData.from_key || '', to_key: logData.to_key || '', method: logData.method || '', diff --git a/app/service/qimenMethods/deliveryorder.js b/app/service/qimenMethods/deliveryorder.js index 9ba30c3..6b72beb 100644 --- a/app/service/qimenMethods/deliveryorder.js +++ b/app/service/qimenMethods/deliveryorder.js @@ -31,13 +31,12 @@ class deliveryorderServer extends MainService { } async create(data) { - const info = this.getInfo; - const res = await this.ctx.service.systems.deliveryOrder.addOrder(data, this.getInfo(), 'QM'); + const info = this.getInfo(); + const res = await this.ctx.service.systems.deliveryOrder.addOrder(data, info, 'QM'); if (res.success) { return this.success(res.message, { createTime: this.app.formatDate(new Date()), deliveryOrderId: res.data.deliveryOrderId, warehouseCode: info.warehouseCode, logisticsCode: res.data.logisticsCode }); } return this.fail(res.message, { createTime: this.app.formatDate(new Date()) }); - } async batchcreate() { return this.fail('批量创建接口未完善'); diff --git a/app/service/qimenMethods/order.js b/app/service/qimenMethods/order.js index 7161acd..544f425 100644 --- a/app/service/qimenMethods/order.js +++ b/app/service/qimenMethods/order.js @@ -87,13 +87,143 @@ class orderServer extends MainService { }; } + async getInterceptExpressInfo(orderId) { + const { ctx } = this; + const normalizedOrderId = Number(orderId || 0); + + if (!Number.isFinite(normalizedOrderId) || normalizedOrderId <= 0) { + return []; + } + + const orderExpressModel = ctx.model && ctx.model.OrderExpress; + if (!orderExpressModel || typeof orderExpressModel.findAll !== 'function') { + return []; + } + + const rows = await orderExpressModel.findAll({ + where: { + order_id: normalizedOrderId, + }, + attributes: [ 'waybill_code', 'logistics_code', 'logistics_name', 'logistics_interface_id' ], + order: [[ 'id', 'DESC' ]], + raw: true, + }); + + return (Array.isArray(rows) ? rows : []).map(row => ({ + waybill_code: String(row && row.waybill_code || '').trim(), + logistics_code: String(row && row.logistics_code || '').trim(), + logistics_name: String(row && row.logistics_name || '').trim(), + logistics_interface_id: row && row.logistics_interface_id == null ? null : Number(row.logistics_interface_id), + })); + } + + async sendCancelInterceptNotice({ orderCode, existingOrder, info }) { + const { ctx } = this; + try { + const express = await this.getInterceptExpressInfo(existingOrder && existingOrder.id); + + await ctx.service.systems.notice.send({ + event: 'order_cancel_intercepted', + businessName: 'order', + warehouseId: info.warehouseId, + storeId: info.storeId, + subject: { + id: info.storeId, + type: 'store', + }, + businessId: orderCode, + messageType: 'text', + title: `订单取消触发拦截:${orderCode}`, + content: `订单 ${orderCode} 因拣货/打印状态未完成,已标记为拦截执行。`, + sender: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + metadata: { + orderCode, + orderId: existingOrder.id, + pickStatus: String(existingOrder.pick_status || 'none').trim(), + printStatus: String(existingOrder.print_status || 'none').trim(), + interceptStatus: String(existingOrder.intercept_status || 'none').trim(), + express, + }, + }); + } catch (error) { + ctx.logger.warn(`取消订单拦截通知发送失败: ${error.message}`); + } + } + async cancel(data) { const { ctx } = this; const info = this.getInfo(); const orderType = this.orderType[data.request.orderType]; switch (orderType.method) { case 'ORDER': - return this.success('取消订单成功'); + { + const orderCode = String(data?.request?.orderCode || '').trim(); + if (!orderCode) { + return this.fail('订单号不能为空'); + } + + const DeliveryModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(info.warehouseId); + const transaction = await ctx.model.transaction(); + try { + const existingOrder = await DeliveryModel.findOne({ + where: { + delivery_order_code: orderCode, + warehouse_id: info.warehouseId, + store_id: info.storeId, + }, + transaction, + lock: transaction.LOCK.UPDATE, + }); + + if (!existingOrder) { + await transaction.rollback(); + return this.fail('未找到对应的订单'); + } + + const pickStatus = String(existingOrder.pick_status || 'none').trim(); + const printStatus = String(existingOrder.print_status || 'none').trim(); + + if (pickStatus !== 'none' || printStatus !== 'none') { + await existingOrder.update({ + intercept_status: 'intercepting', + updated_at: new Date(), + }, { + transaction, + }); + + await transaction.commit(); + await this.sendCancelInterceptNotice({ + orderCode, + existingOrder, + info, + }); + return this.fail('取消失败,已通知拦截执行'); + } + + await existingOrder.update({ + status: 'cancel', + outbound_status: 'fin', + step: 4, + updated_at: new Date(), + }, { + transaction, + }); + + await transaction.commit(); + return this.success('取消订单成功'); + } catch (error) { + try { + await transaction.rollback(); + } catch (rollbackError) { + ctx.logger.error('取消订单回滚失败', rollbackError); + } + ctx.logger.error(`取消订单失败: ${error.message}`); + return this.fail(error.message || '取消订单失败'); + } + } case 'RK': { const existingOrder = await ctx.model.EntryOrder.findOne({ diff --git a/app/service/systemMethods/index.js b/app/service/systemMethods/index.js index 265f487..46f41e3 100644 --- a/app/service/systemMethods/index.js +++ b/app/service/systemMethods/index.js @@ -11,9 +11,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,recognizeLicensePlate'; + const _noNeedRight = 'getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getCOSUploadConfig,uploadSuccessNotify,getMessageDetail,searchSpace,listInterfaceTypes,getExpressList,getExpressProductTypeList,getPlatformList,recognizeLicensePlate'; const _noNeedLog = '*'; - const _noNeedAuth = 'getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getMessageDetail,searchSpace,listInterfaceTypes,recognizeLicensePlate'; + const _noNeedAuth = 'getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getMessageDetail,searchSpace,listInterfaceTypes,getExpressList,getExpressProductTypeList,getPlatformList,recognizeLicensePlate'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } async fastWhereTree(data) { @@ -418,8 +418,29 @@ class indexService extends MainService { return this.success('ok', { list, total: list.length, code: 200 }); } async getExpressList() { + const { service } = this; + const result = await service.systems.express.getExpressList(); + return this.success('ok', { data: result, code: 200 }); + } - return this.success('ok', { data: this.app.config.expressList, code: 200 }); + /** + * 获取快递产品类型列表。 + * + * @param {Object} data 请求参数 + * @param {string} [data.express_code] 快递公司编码 + * @return {Promise} 返回结果 + */ + async getExpressProductTypeList(data) { + const { service } = this; + const { express_code: expressCode = '' } = data || {}; + const result = await service.systems.express.getExpressProductTypeList(expressCode); + return this.success('ok', { data: result, code: 200 }); + } + + async getPlatformList() { + const { service } = this; + const result = await service.systems.platform.getPlatformList(); + return this.success('ok', { data: result, code: 200 }); } } module.exports = indexService; diff --git a/app/service/systemMethods/order/archiveOrder.js b/app/service/systemMethods/order/archiveOrder.js index 47f2efc..c242284 100644 --- a/app/service/systemMethods/order/archiveOrder.js +++ b/app/service/systemMethods/order/archiveOrder.js @@ -6,64 +6,20 @@ class ArchiveOrderService extends OrderBaseService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'getarchiveOrderlist'; - const _noNeedLog = 'getarchiveOrderlist'; - const _noNeedAuth = 'getarchiveOrderlist'; + const _noNeedRight = 'list'; + const _noNeedLog = 'list'; + const _noNeedAuth = 'list'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } /** - * 获取归档订单列表。 - * - * @param {Object} data 请求参数。 - * @return {Promise} 查询结果。 + * 归档订单列表。 + * @param {Object} data 请求体。 + * @param {Object} data.where 标准的查询条件对象,支持复杂查询。 + * @return {Promise} 列表与分页信息。 */ - async getarchiveOrderlist(data = {}) { - try { - const warehouseId = this.ensureWarehouseId(data); - const { DeliveryModel } = await this.getOrderModels(warehouseId); - this.prepareWhereContext(data); - const whereData = this.ctx.where || {}; - const where = this.buildWhere(whereData, warehouseId); - - const hasOutboundFilter = this.hasWhereValue(whereData, 'outbound_status'); - if (!hasOutboundFilter) { - where.outbound_status = 'fin'; - } - - const { page, pageSize, offset } = this.getPagination(data.pagination); - const result = await DeliveryModel.findAndCountAll({ - where, - attributes: [ - 'id', - 'delivery_order_code', - 'status', - 'step', - 'outbound_status', - 'delivery_time', - 'updated_at', - 'store_id', - 'warehouse_id', - 'buyer_nick', - 'logistics_name', - ], - offset, - limit: pageSize, - order: [[ 'delivery_time', 'DESC' ], [ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]], - raw: true, - }); - - return this.success('ok', { - data: this.buildListData(result.rows, result.count, page, pageSize, { - queryInfo: { - defaultArchiveFilter: !hasOutboundFilter, - }, - }), - code: 200, - }); - } catch (error) { - return this.fail(error.message, { code: 500 }); - } + async list(data = {}) { + return await this.listByModule('archiveOrder', data); } } diff --git a/app/service/systemMethods/order/base.js b/app/service/systemMethods/order/base.js index c7ddf4a..18751a5 100644 --- a/app/service/systemMethods/order/base.js +++ b/app/service/systemMethods/order/base.js @@ -1,224 +1,1065 @@ 'use strict'; const MainService = require('../../main'); +const { parseWhereConditions } = require('../../../lib/query_condition_parser'); +const DEFAULT_PAGE_SIZE = 20; +const MAX_PAGE_SIZE = 200; +const FORBIDDEN_WAREHOUSE_FIELDS = new Set([ 'warehouse_id', 'warehouseId' ]); +const WAREHOUSE_FIELD_ERROR_MESSAGE = '订单工作台查询条件禁止传入 warehouse_id / warehouseId,请使用当前用户上下文的 store_id。'; + +const REVIEW_STATUS_STEP_MAP = Object.freeze({ + none: 0, + padding: 2, + running: 2, + fin: 1, + error: 3, +}); + +const REVIEW_ORDER_ALLOWED_FIELDS = Object.freeze([ 'ids' ]); +const BADGE_COUNT_OVER_LIMIT_VALUE = '99+'; +const ORDER_TABLE_TYPE_ALIASES = Object.freeze({ + current: 'current', + history: 'history', + dispatch: 'dispatch', + outsourced: 'outsourced', + order: 'current', + revieworder: 'current', + pendingorder: 'current', + outboundorder: 'current', + expectionorder: 'current', + archiveorder: 'history', + entrustorder: 'outsourced', + deliveryorder: 'dispatch', + deliveryexpectionorder: 'dispatch', +}); + +const MODULE_CONFIGS = Object.freeze({ + order: { + modelType: 'current', + defaultWhere: {}, + }, + reviewOrder: { + modelType: 'current', + defaultWhere: { + step: { + operator: 'eq', + value: 0, + }, + }, + }, + pendingOrder: { + modelType: 'current', + defaultWhere: { + outbound_status: { + operator: 'ne', + value: 'padding', + }, + step: { + operator: 'in', + value: [ 1, 2 ], + }, + }, + }, + outboundOrder: { + modelType: 'current', + defaultWhere: { + outbound_status: { + operator: 'in', + value: [ 'none', 'padding' ], + }, + step: { + operator: 'in', + value: [ 1, 2 ], + }, + }, + }, + expectionOrder: { + modelType: 'current', + defaultWhere: { + step: { + operator: 'eq', + value: 3, + }, + }, + }, + entrustOrder: { + modelType: 'outsourced', + defaultWhere: {}, + }, + deliveryOrder: { + modelType: 'dispatch', + defaultWhere: { + dispatch_lane: { + operator: 'eq', + value: 'm4', + }, + }, + }, + deliveryExpectionOrder: { + modelType: 'dispatch', + defaultWhere: { + dispatch_lane: { + operator: 'eq', + value: 'm5', + }, + }, + }, + archiveOrder: { + modelType: 'history', + defaultWhere: {}, + }, +}); + +/** + * 订单工作台系统方法基础能力。 + * 负责仓库上下文、分页规范、where 解析、模型选择与审核状态更新。 + */ class OrderBaseService extends MainService { - ensureWarehouseId(data = {}) { - const warehouseId = this.getWarehouseId(data); - if (!warehouseId) { - throw new Error('warehouse_id 不能为空'); - } - return warehouseId; - } + /** + * 获取当前请求对应的仓库ID。 + * @return {number|string|null} 仓库ID。 + */ + getWarehouseId() { + const { ctx } = this; + const warehouseId = ctx?.user?.store_id ?? null; - getWarehouseId(data = {}) { - const fromParam = Number(data.warehouse_id || data.warehouseId || 0); - const fromUser = Number(this.ctx.user?.store_id || 0); - return fromParam || fromUser; - } - - async getOrderModels(warehouseId) { - const DeliveryModel = await this.ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); - const OrderItemsModel = await this.ctx.model.OrderItemsFactory.getCurrentModel(warehouseId); - return { DeliveryModel, OrderItemsModel }; - } - - applyDateRange(where, field, start, end) { - const { Op } = this.app.Sequelize; - const range = {}; - - if (start) { - range[Op.gte] = this.normalizeDate(start, false); - } - if (end) { - range[Op.lte] = this.normalizeDate(end, true); - } - - if (Object.keys(range).length > 0) { - where[field] = range; - } - } - - getWhereCondition(whereData = {}, key) { - const condition = whereData[key]; - if (condition && typeof condition === 'object' && Object.prototype.hasOwnProperty.call(condition, 'value')) { - return condition; - } - return { - operator: 'eq', - value: condition, - }; - } - - getWhereValue(whereData = {}, key) { - return this.getWhereCondition(whereData, key).value; - } - - getWhereOperator(whereData = {}, key, defaultOperator = 'eq') { - const condition = this.getWhereCondition(whereData, key); - return String(condition.operator || defaultOperator).toLowerCase(); - } - - hasWhereValue(whereData = {}, key) { - const value = this.getWhereValue(whereData, key); - if (value === undefined || value === null) return false; - if (typeof value === 'string' && value.trim() === '') return false; - if (Array.isArray(value) && value.length === 0) return false; - return true; + return warehouseId === '' ? null : warehouseId; } /** - * 构建订单列表查询条件。 - * - * @param {Object} whereData where 过滤参数。 - * @param {number} warehouseId 仓库 ID。 - * @return {Object} Sequelize 查询条件。 + * 规范分页参数并限制 pageSize 上限。 + * @param {Object} pageParams 分页参数。 + * @return {{ page: number, pageSize: number }} 规范化结果。 */ - buildWhere(whereData = {}, warehouseId) { - const { Op } = this.app.Sequelize; - const where = { warehouse_id: warehouseId }; + normalizePagination(pageParams = {}) { + const requestParams = this.isPlainObject(pageParams) ? pageParams : {}; + const pageValue = requestParams.page ?? requestParams.currentPage ?? 1; + const pageSizeValue = requestParams.pageSize ?? requestParams.page_size ?? requestParams.size ?? DEFAULT_PAGE_SIZE; - const eqFields = [ - 'id', - 'store_id', - 'status', - 'post_status', - 'storage_status', - 'pick_status', - 'pack_status', - 'inspection_status', - 'print_status', - 'claim_status', - 'outbound_status', - 'lock_status', - 'intercept_status', - 'step', - 'source_platform_code', - 'logistics_code', - 'warehouse_code', - 'order_type', + const page = Math.max(Number.parseInt(pageValue, 10) || 1, 1); + const pageSize = Math.min( + Math.max(Number.parseInt(pageSizeValue, 10) || DEFAULT_PAGE_SIZE, 1), + MAX_PAGE_SIZE + ); + + return { + page, + pageSize, + }; + } + + /** + * 规范化 where 入参,兼容简写值与标准 { operator, value } 结构。 + * @param {Object} whereInput where 条件对象。 + * @return {Object} 规范化后的 where 条件。 + */ + normalizeWhereInput(whereInput = {}) { + const sourceWhere = this.isPlainObject(whereInput && whereInput.where) + ? whereInput.where + : whereInput; + + if (!this.isPlainObject(sourceWhere)) { + return {}; + } + + const normalized = {}; + + for (const [ fieldKey, condition ] of Object.entries(sourceWhere)) { + if (FORBIDDEN_WAREHOUSE_FIELDS.has(fieldKey)) { + throw new Error(WAREHOUSE_FIELD_ERROR_MESSAGE); + } + + if (this.isPlainObject(condition)) { + const hasStandardKeys = [ 'value', 'operator', 'type', 'field', 'values' ] + .some(key => Object.prototype.hasOwnProperty.call(condition, key)); + + if (hasStandardKeys) { + const normalizedCondition = { + ...condition, + }; + + if (!Object.prototype.hasOwnProperty.call(normalizedCondition, 'value') + && Object.prototype.hasOwnProperty.call(normalizedCondition, 'values')) { + normalizedCondition.value = normalizedCondition.values; + delete normalizedCondition.values; + } + + if (!Object.prototype.hasOwnProperty.call(normalizedCondition, 'operator') || !normalizedCondition.operator) { + normalizedCondition.operator = Array.isArray(normalizedCondition.value) ? 'in' : 'eq'; + } + + normalized[fieldKey] = normalizedCondition; + continue; + } + } + + normalized[fieldKey] = { + operator: Array.isArray(condition) ? 'in' : 'eq', + value: condition, + }; + } + + return normalized; + } + + /** + * 规范订单 ID 入参,兼容 ids、id、order_id、orderId 四种写法。 + * @param {Object} data 请求体。 + * @return {number[]} 订单 ID 列表。 + */ + normalizeOrderIds(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const rawIds = requestData.ids; + const fallbackId = requestData.id !== undefined && requestData.id !== null && requestData.id !== '' + ? requestData.id + : requestData.order_id !== undefined && requestData.order_id !== null && requestData.order_id !== '' + ? requestData.order_id + : requestData.orderId; + const sourceIds = []; + + if (Array.isArray(rawIds)) { + sourceIds.push(...rawIds); + } else if (typeof rawIds === 'string') { + sourceIds.push(...rawIds.split(',')); + } else if (rawIds !== undefined && rawIds !== null && rawIds !== '') { + sourceIds.push(rawIds); + } else if (requestData.id !== undefined && requestData.id !== null && requestData.id !== '') { + sourceIds.push(requestData.id); + } else if (requestData.order_id !== undefined && requestData.order_id !== null && requestData.order_id !== '') { + sourceIds.push(requestData.order_id); + } else if (requestData.orderId !== undefined && requestData.orderId !== null && requestData.orderId !== '') { + sourceIds.push(requestData.orderId); + } + + const normalizedIds = []; + for (const value of sourceIds) { + const normalizedId = Number(String(value).trim()); + if (Number.isFinite(normalizedId) && normalizedId > 0) { + normalizedIds.push(normalizedId); + } + } + + if (normalizedIds.length === 0 && fallbackId !== undefined && fallbackId !== null && fallbackId !== '') { + const normalizedFallbackId = Number(String(fallbackId).trim()); + if (Number.isFinite(normalizedFallbackId) && normalizedFallbackId > 0) { + normalizedIds.push(normalizedFallbackId); + } + } + + return Array.from(new Set(normalizedIds)); + } + + /** + * 判断 where 条件是否可以安全合并到扁平对象。 + * @param {Object} condition Sequelize 条件对象。 + * @return {boolean} 是否可合并。 + */ + isMergeableWhereCondition(condition) { + if (!this.isPlainObject(condition)) { + return false; + } + + if (Object.getOwnPropertySymbols(condition).length > 0) { + return false; + } + + return Object.keys(condition).length === 1; + } + + /** + * 合并两个 where 对象,后者优先覆盖前者。 + * @param {Object} baseWhere 基础条件。 + * @param {Object} extraWhere 追加条件。 + * @return {Object} 合并后的条件。 + */ + mergeWhereObjects(baseWhere = {}, extraWhere = {}) { + return { + ...(this.isPlainObject(baseWhere) ? baseWhere : {}), + ...(this.isPlainObject(extraWhere) ? extraWhere : {}), + }; + } + + /** + * 获取模块配置。 + * @param {string} moduleName 模块名称。 + * @return {{ modelType: string, defaultWhere: Object }} 模块配置。 + */ + getModuleConfig(moduleName = 'order') { + return MODULE_CONFIGS[moduleName] || MODULE_CONFIGS.order; + } + + /** + * 获取模块默认筛选条件。 + * @param {string} moduleName 模块名称。 + * @return {Object} 默认筛选条件。 + */ + getDefaultWhere(moduleName = 'order') { + const config = this.getModuleConfig(moduleName); + return this.mergeWhereObjects({}, config.defaultWhere); + } + + /** + * 构造订单工作台角标缓存键。 + * @param {number|string} warehouseId 仓库ID。 + * @return {string} 缓存键。 + */ + getBadgeCountCacheKey(warehouseId) { + return `systemMethods:order:badgeCount:${warehouseId}`; + } + + /** + * 将角标计数转换为前端展示值。 + * @param {number|string} count 订单数。 + * @return {number|string} 展示值。 + */ + formatBadgeCountValue(count) { + const normalizedCount = Number(count); + + if (!Number.isFinite(normalizedCount) || normalizedCount < 0) { + return 0; + } + + return normalizedCount > 99 ? BADGE_COUNT_OVER_LIMIT_VALUE : normalizedCount; + } + + /** + * 获取指定模块的角标展示值。 + * @param {string} moduleName 模块名称。 + * @param {number|string} [warehouseId] 仓库ID。 + * @return {Promise} 角标展示值。 + */ + async getBadgeCountByModule(moduleName = 'order', warehouseId = this.getWarehouseId()) { + const actualWarehouseId = warehouseId ?? this.getWarehouseId(); + const model = await this.getOrderModel(moduleName, actualWarehouseId); + const queryWhere = this.buildWhere(this.getDefaultWhere(moduleName), actualWarehouseId); + const count = await model.count({ where: queryWhere }); + + return this.formatBadgeCountValue(count); + } + + /** + * 获取订单工作台对应的物理模型。 + * @param {string} moduleName 模块名称。 + * @param {number|string} [warehouseId] 仓库ID(保留兼容参数,实际以上下文 store_id 为准)。 + * @return {Promise} Sequelize 动态模型。 + */ + async getOrderModel(moduleName = 'order', warehouseId = null) { + const { ctx } = this; + const config = this.getModuleConfig(moduleName); + const contextWarehouseId = this.getWarehouseId(); + + if (contextWarehouseId === null || contextWarehouseId === undefined || contextWarehouseId === '') { + throw new Error('缺少当前用户仓库上下文 store_id'); + } + + if (warehouseId !== null && warehouseId !== undefined && warehouseId !== '' + && String(warehouseId) !== String(contextWarehouseId)) { + throw new Error('订单工作台仓库ID必须来自当前用户上下文 store_id,禁止传入外部仓库ID。'); + } + + const actualWarehouseId = contextWarehouseId; + + switch (config.modelType) { + case 'history': + return await ctx.model.OrderDeliveryFactory.getHistoryModel(actualWarehouseId); + case 'dispatch': + return await ctx.model.OrderDeliveryFactory.getDispatchModel(actualWarehouseId); + case 'outsourced': + return await ctx.model.OrderDeliveryFactory.getOutsourcedModel(actualWarehouseId); + case 'current': + default: + return await ctx.model.OrderDeliveryFactory.getCurrentModel(actualWarehouseId); + } + } + + /** + * 解析订单详情使用的表位类型。 + * @param {Object} data 请求体。 + * @return {string} 表位类型。 + */ + resolveOrderTableType(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const candidates = [ + requestData.tableType, + requestData.tablePosition, + requestData.type, + requestData.moduleName, ]; - for (const key of eqFields) { - if (!this.hasWhereValue(whereData, key)) { + for (const candidate of candidates) { + const normalizedCandidate = String(candidate ?? '').trim(); + if (!normalizedCandidate) { continue; } - const value = this.getWhereValue(whereData, key); - const operator = this.getWhereOperator(whereData, key); + const normalizedType = ORDER_TABLE_TYPE_ALIASES[normalizedCandidate.toLowerCase()]; + if (normalizedType) { + return normalizedType; + } - if (operator === 'in') { - where[key] = { - [Op.in]: Array.isArray(value) ? value : [ value ], - }; - } else if (operator === 'notin') { - where[key] = { - [Op.notIn]: Array.isArray(value) ? value : [ value ], - }; - } else if (operator === 'ne') { - where[key] = { - [Op.ne]: value, - }; - } else if (operator === 'like' || operator === 'contains') { - where[key] = { - [Op.like]: `%${value}%`, - }; - } else { - where[key] = value; + throw new Error(`不支持的订单表位类型: ${normalizedCandidate}`); + } + + return 'current'; + } + + /** + * 根据表位类型获取订单头模型。 + * @param {string} tableType 表位类型。 + * @param {number|string} [warehouseId] 仓库ID。 + * @return {Promise} 订单头模型。 + */ + async getOrderModelByTableType(tableType = 'current', warehouseId = this.getWarehouseId()) { + const { ctx } = this; + const contextWarehouseId = this.getWarehouseId(); + const normalizedTableType = this.resolveOrderTableType({ tableType }); + const actualWarehouseId = warehouseId ?? contextWarehouseId; + + if (contextWarehouseId === null || contextWarehouseId === undefined || contextWarehouseId === '') { + throw new Error('缺少当前用户仓库上下文 store_id'); + } + + if (actualWarehouseId !== null && actualWarehouseId !== undefined && actualWarehouseId !== '' + && String(actualWarehouseId) !== String(contextWarehouseId)) { + throw new Error('订单工作台仓库ID必须来自当前用户上下文 store_id,禁止传入外部仓库ID。'); + } + + switch (normalizedTableType) { + case 'history': + return await ctx.model.OrderDeliveryFactory.getHistoryModel(contextWarehouseId); + case 'dispatch': + return await ctx.model.OrderDeliveryFactory.getDispatchModel(contextWarehouseId); + case 'outsourced': + return await ctx.model.OrderDeliveryFactory.getOutsourcedModel(contextWarehouseId); + case 'current': + default: + return await ctx.model.OrderDeliveryFactory.getCurrentModel(contextWarehouseId); + } + } + + /** + * 根据表位类型获取订单商品模型。 + * @param {string} tableType 表位类型。 + * @param {number|string} [warehouseId] 仓库ID。 + * @return {Promise} 订单商品模型。 + */ + async getOrderItemsModelByTableType(tableType = 'current', warehouseId = this.getWarehouseId()) { + const { ctx } = this; + const contextWarehouseId = this.getWarehouseId(); + const normalizedTableType = this.resolveOrderTableType({ tableType }); + const actualWarehouseId = warehouseId ?? contextWarehouseId; + + if (contextWarehouseId === null || contextWarehouseId === undefined || contextWarehouseId === '') { + throw new Error('缺少当前用户仓库上下文 store_id'); + } + + if (actualWarehouseId !== null && actualWarehouseId !== undefined && actualWarehouseId !== '' + && String(actualWarehouseId) !== String(contextWarehouseId)) { + throw new Error('订单工作台仓库ID必须来自当前用户上下文 store_id,禁止传入外部仓库ID。'); + } + + const orderItemsFactory = ctx.model && ctx.model.OrderItemsFactory; + if (!orderItemsFactory) { + throw new Error('订单商品模型工厂不存在'); + } + + switch (normalizedTableType) { + case 'history': + return await orderItemsFactory.getHistoryModel(contextWarehouseId); + case 'dispatch': + return await orderItemsFactory.getDispatchModel(contextWarehouseId); + case 'outsourced': + return await orderItemsFactory.getOrCreateModel(contextWarehouseId, 'outsourced'); + case 'current': + default: + return await orderItemsFactory.getCurrentModel(contextWarehouseId); + } + } + + /** + * 查询订单关联运单信息。 + * @param {number|string} orderId 订单ID。 + * @return {Promise} 运单信息列表。 + */ + async getOrderExpressesByOrderId(orderId) { + const normalizedOrderId = Number(orderId || 0); + + if (!Number.isFinite(normalizedOrderId) || normalizedOrderId <= 0) { + return []; + } + + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; + if (!orderExpressModel || typeof orderExpressModel.findAll !== 'function') { + return []; + } + + const rows = await orderExpressModel.findAll({ + where: { + order_id: normalizedOrderId, + }, + attributes: [ 'waybill_code', 'logistics_code', 'logistics_name', 'logistics_interface_id' ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + return (Array.isArray(rows) ? rows : []).map(row => ({ + waybill_code: String(row && row.waybill_code || '').trim(), + logistics_code: String(row && row.logistics_code || '').trim(), + logistics_name: String(row && row.logistics_name || '').trim(), + logistics_interface_id: row && row.logistics_interface_id == null ? null : Number(row.logistics_interface_id), + })); + } + + /** + * 归一化订单列表中的快递与系统名称字段。 + * @param {Object} orderRow 订单行。 + * @param {string[]} expressNumbers 快递号列表。 + * @return {Object} 归一化后的订单行。 + */ + normalizeOrderListRow(orderRow = {}, expressNumbers = []) { + const normalizedExpressNumbers = Array.isArray(expressNumbers) + ? Array.from(new Set(expressNumbers.map(item => String(item || '').trim()).filter(Boolean))) + : []; + + return { + ...orderRow, + sys_platform_name: Object.prototype.hasOwnProperty.call(orderRow, 'sys_platform_name') + ? (orderRow.sys_platform_name ?? null) + : null, + sys_logistics_name: Object.prototype.hasOwnProperty.call(orderRow, 'sys_logistics_name') + ? (orderRow.sys_logistics_name ?? null) + : null, + express_numbers: normalizedExpressNumbers, + waybill_codes: normalizedExpressNumbers, + }; + } + + /** + * 批量补齐订单列表的快递号信息。 + * @param {Object[]} list 订单列表。 + * @return {Promise} 补齐后的列表。 + */ + async attachOrderExpressNumbers(list = []) { + if (!Array.isArray(list) || list.length === 0) { + return Array.isArray(list) ? list : []; + } + + const orderIds = Array.from(new Set(list + .map(item => Number(item && item.id)) + .filter(value => Number.isFinite(value) && value > 0))); + + if (orderIds.length === 0) { + return list.map(item => this.normalizeOrderListRow(item, [])); + } + + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; + if (!orderExpressModel || typeof orderExpressModel.findAll !== 'function') { + return list.map(item => this.normalizeOrderListRow(item, [])); + } + + const { Op } = this.app.Sequelize; + const expressRows = await orderExpressModel.findAll({ + where: { + order_id: { + [Op.in]: orderIds, + }, + }, + attributes: [ 'id', 'order_id', 'waybill_code', 'logistics_code', 'logistics_name', 'logistics_interface_id', 'platform_code' ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + const expressMap = new Map(); + if (Array.isArray(expressRows)) { + for (const row of expressRows) { + const orderId = Number(row && row.order_id); + const waybillCode = String(row && row.waybill_code || '').trim(); + + if (!Number.isFinite(orderId) || orderId <= 0 || !waybillCode) { + continue; + } + + const currentExpressNumbers = expressMap.get(orderId) || []; + currentExpressNumbers.push(waybillCode); + expressMap.set(orderId, currentExpressNumbers); } } - if (this.hasWhereValue(whereData, 'delivery_order_code')) { - const value = this.getWhereValue(whereData, 'delivery_order_code'); - const operator = this.getWhereOperator(whereData, 'delivery_order_code', 'like'); - if (operator === 'eq') { - where.delivery_order_code = value; - } else { - where.delivery_order_code = { [Op.like]: `%${value}%` }; + return list.map(item => { + const orderId = Number(item && item.id); + const orderExpressNumbers = Number.isFinite(orderId) && orderId > 0 + ? (expressMap.get(orderId) || []) + : []; + + return this.normalizeOrderListRow(item, orderExpressNumbers); + }); + } + + /** + * 构造列表排序参数。 + * @param {Object} sort 排序参数。 + * @param {string} [moduleName='order'] 模块名称。 + * @return {Array>} Sequelize order 配置。 + */ + buildListOrder(sort = {}, moduleName = 'order') { + const requestSort = this.isPlainObject(sort) ? sort : {}; + const sortField = requestSort.sortField || requestSort.field || requestSort.sort_by || requestSort.orderBy; + const sortOrder = String(requestSort.sortOrder || requestSort.order || 'DESC').toUpperCase() === 'ASC' ? 'ASC' : 'DESC'; + const defaultSortField = moduleName === 'deliveryOrder' || moduleName === 'deliveryExpectionOrder' + ? 'delivery_time' + : 'updated_at'; + const allowedSortFields = new Set([ + 'id', + 'step', + 'status', + 'inspection_status', + 'dispatch_lane', + 'delivery_time', + 'create_at', + 'created_at', + 'updated_at', + 'delivery_order_code', + 'source_platform_code', + 'sync_status', + 'outbound_status', + ]); + const actualSortField = allowedSortFields.has(sortField) ? sortField : defaultSortField; + + return [ + [ actualSortField, sortOrder ], + [ 'id', 'DESC' ], + ]; + } + + /** + * 构造可直接传给 Sequelize 的 where 条件。 + * @param {Object} whereInput where 条件对象。 + * @param {number|string} warehouseId 仓库ID(保留兼容参数,实际以上下文 store_id 为准)。 + * @param {Object} [options] 解析选项。 + * @param {Object} [options.specialFieldMap] 特殊字段映射。 + * @return {Object} Sequelize where 条件。 + */ + buildWhere(whereInput = {}, warehouseId, options = {}) { + const { Sequelize } = this.app; + const specialFieldMap = this.isPlainObject(options.specialFieldMap) ? options.specialFieldMap : {}; + const contextWarehouseId = this.getWarehouseId(); + + if (contextWarehouseId === null || contextWarehouseId === undefined || contextWarehouseId === '') { + throw new Error('缺少当前用户仓库上下文 store_id'); + } + + if (warehouseId !== null && warehouseId !== undefined && warehouseId !== '' + && String(warehouseId) !== String(contextWarehouseId)) { + throw new Error('订单工作台仓库ID必须来自当前用户上下文 store_id,禁止传入外部仓库ID。'); + } + + const normalizedWhere = this.normalizeWhereInput(whereInput); + const parsed = parseWhereConditions({ + where: normalizedWhere, + app: this.app, + specialFieldMap, + }); + + if (!parsed.ok) { + throw new Error(`where 参数解析失败: ${parsed.reason}`); + } + + const mergedConditions = []; + + if (contextWarehouseId !== null && contextWarehouseId !== undefined && contextWarehouseId !== '') { + mergedConditions.push({ + warehouse_id: contextWarehouseId, + }); + } + + if (Array.isArray(parsed.result.dynamicConditions)) { + mergedConditions.push(...parsed.result.dynamicConditions); + } + + if (this.isPlainObject(parsed.result.bucketConditions)) { + for (const bucketConditions of Object.values(parsed.result.bucketConditions)) { + if (Array.isArray(bucketConditions)) { + mergedConditions.push(...bucketConditions); + } } } - const deliveryOrderCodes = this.getWhereValue(whereData, 'delivery_order_codes'); - if (Array.isArray(deliveryOrderCodes) && deliveryOrderCodes.length > 0) { - where.delivery_order_code = { [Op.in]: deliveryOrderCodes }; + const flatWhere = {}; + const andConditions = []; + + for (const condition of mergedConditions) { + if (this.isMergeableWhereCondition(condition)) { + Object.assign(flatWhere, condition); + continue; + } + + andConditions.push(condition); } - if (this.hasWhereValue(whereData, 'logistics_name')) { - const value = this.getWhereValue(whereData, 'logistics_name'); - where.logistics_name = { [Op.like]: `%${value}%` }; + if (andConditions.length === 0) { + return flatWhere; } - if (this.hasWhereValue(whereData, 'buyer_nick')) { - const value = this.getWhereValue(whereData, 'buyer_nick'); - where.buyer_nick = { [Op.like]: `%${value}%` }; + if (Object.keys(flatWhere).length > 0) { + andConditions.unshift(flatWhere); } - if (this.hasWhereValue(whereData, 'mobile')) { - const value = this.getWhereValue(whereData, 'mobile'); - where.mobile = { [Op.like]: `%${value}%` }; + return { + [Sequelize.Op.and]: andConditions, + }; + } + + /** + * 查询模块列表。 + * @param {string} moduleName 模块名称。 + * @param {Object} data 请求体。 + * @return {Promise} 列表与分页信息。 + */ + async listByModule(moduleName = 'order', data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const contextWarehouseId = this.getWarehouseId(); + const { page, pageSize } = this.normalizePagination(requestData.pagination || requestData); + const { where } = this.prepareWhereContext(requestData, { + specialFieldMap: { + quickWhere: { + bucket: 'quick', + }, + }, + }); + const mergedWhere = this.mergeWhereObjects(this.getDefaultWhere(moduleName), where); + const queryWhere = this.buildWhere(mergedWhere, contextWarehouseId, { + specialFieldMap: { + quickWhere: { + bucket: 'quick', + }, + }, + }); + const model = await this.getOrderModel(moduleName, contextWarehouseId); + const order = this.buildListOrder(requestData.sort, moduleName); + const offset = (page - 1) * pageSize; + + const [ total, list ] = await Promise.all([ + model.count({ where: queryWhere }), + model.findAll({ + where: queryWhere, + limit: pageSize, + offset, + order, + raw: true, + }), + ]); + + const normalizedList = await this.attachOrderExpressNumbers(list); + + const totalPages = pageSize > 0 ? Math.ceil(total / pageSize) : 0; + + return { + list: normalizedList, + pagination: { + page, + pageSize, + total, + totalPages, + hasPrevious: page > 1, + hasNext: page < totalPages, + }, + }; + } + + /** + * 查询订单详情。 + * @param {Object} data 请求体。 + * @return {Promise} 订单头、商品明细和运单信息。 + */ + 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不能为空'); } - this.applyDateRange(where, 'create_at', this.getWhereValue(whereData, 'create_at_start'), this.getWhereValue(whereData, 'create_at_end')); - this.applyDateRange(where, 'place_order_time', this.getWhereValue(whereData, 'place_order_time_start'), this.getWhereValue(whereData, 'place_order_time_end')); - this.applyDateRange(where, 'pay_time', this.getWhereValue(whereData, 'pay_time_start'), this.getWhereValue(whereData, 'pay_time_end')); - this.applyDateRange(where, 'delivery_time', this.getWhereValue(whereData, 'delivery_time_start'), this.getWhereValue(whereData, 'delivery_time_end')); + 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 expresses = await this.getOrderExpressesByOrderId(orderId); + const waybillCodes = Array.from(new Set(expresses + .map(item => String(item && item.waybill_code || '').trim()) + .filter(Boolean))); + + return { + order, + detail: order, + orderItems: Array.isArray(orderItems) ? orderItems : [], + items: Array.isArray(orderItems) ? orderItems : [], + expresses, + waybill_codes: waybillCodes, + }; + } + + /** + * 将审核状态映射为 step。 + * @param {string} reviewStatus 审核状态。 + * @return {number} 订单步骤。 + */ + resolveReviewStep(reviewStatus) { + const status = String(reviewStatus || '').trim(); + return REVIEW_STATUS_STEP_MAP[status] ?? 0; + } + + /** + * 规范审核提交入参中的订单ID列表,仅接受 ids。 + * @param {Object} data 请求体。 + * @return {number[]} 订单ID 列表。 + */ + normalizeReviewOrderIds(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const unexpectedKeys = Object.keys(requestData).filter(key => !REVIEW_ORDER_ALLOWED_FIELDS.includes(key)); + + if (unexpectedKeys.length > 0) { + throw new Error('审核接口仅支持 ids 入参,不再支持 id/order_id/review_status/inspection_status/warehouse_id/warehouseId 等兼容字段'); + } + + const rawIds = requestData.ids; + const sourceIds = Array.isArray(rawIds) + ? rawIds + : typeof rawIds === 'string' + ? rawIds.split(',') + : rawIds !== undefined && rawIds !== null && rawIds !== '' + ? [ rawIds ] + : []; + + const normalizedIds = sourceIds + .map(value => Number(String(value).trim())) + .filter(value => Number.isFinite(value) && value > 0); + + return Array.from(new Set(normalizedIds)); + } + + /** + * 构建订单更新条件。 + * @param {number[]} orderIds 订单 ID 列表。 + * @param {number|string|null} warehouseId 仓库 ID(保留兼容参数,实际以上下文 store_id 为准)。 + * @return {Object} where 条件。 + */ + buildOrderWhere(orderIds = [], warehouseId = null) { + const { Op } = this.ctx.app.Sequelize; + const contextWarehouseId = this.getWarehouseId(); + const normalizedIds = Array.isArray(orderIds) + ? Array.from(new Set(orderIds.map(value => Number(value)).filter(value => Number.isFinite(value) && value > 0))) + : []; + + if (normalizedIds.length === 0) { + return {}; + } + + const where = { + id: normalizedIds.length === 1 ? normalizedIds[0] : { + [Op.in]: normalizedIds, + }, + }; + + if (contextWarehouseId === null || contextWarehouseId === undefined || contextWarehouseId === '') { + throw new Error('缺少当前用户仓库上下文 store_id'); + } + + if (warehouseId !== null && warehouseId !== undefined && warehouseId !== '' + && String(warehouseId) !== String(contextWarehouseId)) { + throw new Error('订单工作台仓库ID必须来自当前用户上下文 store_id,禁止传入外部仓库ID。'); + } + + where.warehouse_id = contextWarehouseId; return where; } - parseDateTime(value, fieldName) { - if (!value) return null; - const d = value instanceof Date ? value : new Date(value); - if (Number.isNaN(d.getTime())) { - throw new Error(`${fieldName} 格式错误`); + /** + * 构建审核更新条件。 + * @param {number[]} orderIds 订单ID 列表。 + * @return {Object} where 条件。 + */ + buildReviewOrderWhere(orderIds = []) { + return this.buildOrderWhere(orderIds); + } + + /** + * 审核通过订单并进入待处理。 + * @param {Object} data 请求体。 + * @param {number[]|string} data.ids 批量订单ID。 + * @return {Promise} 更新后的订单信息。 + */ + async updateReviewOrder(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const warehouseId = this.getWarehouseId(); + const orderIds = this.normalizeReviewOrderIds(requestData); + + if (orderIds.length === 0) { + throw new Error('订单ID不能为空'); } - return d; - } - getPagination(pagination = {}) { - const page = Math.max(Number(pagination.page || 1), 1); - const pageSize = Math.min(Math.max(Number(pagination.pageSize || 20), 1), 200); - const offset = (page - 1) * pageSize; - return { page, pageSize, offset }; - } + const model = await this.getOrderModel('order', warehouseId); + const where = this.buildReviewOrderWhere(orderIds); + const existingOrders = await model.findAll({ + where, + raw: true, + }); + + if (!Array.isArray(existingOrders) || existingOrders.length !== orderIds.length) { + throw new Error('订单不存在或不属于当前仓库'); + } + + const now = new Date(); + const updateValues = { + inspection_status: 'fin', + step: 1, + updated_at: now, + }; + + const updateResult = await model.update(updateValues, { + where, + }); + + const affectedRows = Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0); + if (affectedRows <= 0) { + throw new Error('订单不存在或不属于当前仓库'); + } + + const updatedOrders = await model.findAll({ + where, + raw: true, + }); + + if (!Array.isArray(updatedOrders) || updatedOrders.length === 0) { + throw new Error('订单不存在或不属于当前仓库'); + } + + const orderMap = new Map(updatedOrders.map(order => [ Number(order.id), order ])); + const normalizedOrders = orderIds + .map(orderId => orderMap.get(orderId)) + .filter(Boolean) + .map(order => ({ + id: order.id, + inspection_status: order.inspection_status, + step: Number(order.step ?? 1), + updated_at: order.updated_at, + })); + + if (normalizedOrders.length === 0) { + throw new Error('订单不存在或不属于当前仓库'); + } + + const firstOrder = normalizedOrders[0]; - buildPagination(page, pageSize, total) { return { - page, - pageSize, - total, - totalPages: Math.ceil(total / pageSize), - hasNext: page * pageSize < total, - hasPrevious: page > 1, + id: firstOrder.id, + inspection_status: firstOrder.inspection_status, + step: firstOrder.step, + updated_at: firstOrder.updated_at, + updated_count: affectedRows, + ids: normalizedOrders.map(order => order.id), }; } - getOrderLocatorWhere(data = {}, warehouseId) { - const where = { warehouse_id: warehouseId }; + /** + * 更新订单审核态。 + * @param {Object} data 请求体。 + * @param {string} [targetInspectionStatus] 目标审核状态。 + * @param {Object} [options] 额外更新配置。 + * @param {Object} [options.extraUpdateValues] 附加更新字段。 + * @return {Promise} 更新后的订单信息。 + */ + async updateOrderInspectionState(data = {}, targetInspectionStatus = '', options = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const warehouseId = this.getWarehouseId(); + const orderIds = this.normalizeOrderIds(requestData); + const inspectionStatus = String(targetInspectionStatus || requestData.review_status || requestData.inspection_status || '').trim(); + const extraUpdateValues = this.isPlainObject(options.extraUpdateValues) ? options.extraUpdateValues : {}; - if (data.id) { - where.id = data.id; - return where; + if (orderIds.length === 0) { + throw new Error('订单ID不能为空'); } - if (data.order_id) { - where.id = data.order_id; - return where; + if (!inspectionStatus) { + throw new Error('审核状态不能为空'); } - if (data.delivery_order_code) { - where.delivery_order_code = data.delivery_order_code; - return where; + const model = await this.getOrderModel('order', warehouseId); + const step = this.resolveReviewStep(inspectionStatus); + const now = new Date(); + const where = this.buildOrderWhere(orderIds, warehouseId); + const updateValues = { + inspection_status: inspectionStatus, + step, + updated_at: now, + ...extraUpdateValues, + }; + + const updateResult = await model.update(updateValues, { + where, + }); + + const affectedRows = Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0); + if (affectedRows <= 0) { + throw new Error('订单不存在或不属于当前仓库'); } - throw new Error('id 或 delivery_order_code 必填'); - } + const updatedOrders = await model.findAll({ + where, + raw: true, + }); + + if (!Array.isArray(updatedOrders) || updatedOrders.length === 0) { + throw new Error('订单不存在或不属于当前仓库'); + } + + const orderMap = new Map(updatedOrders.map(order => [ Number(order.id), order ])); + const normalizedOrders = orderIds + .map(orderId => orderMap.get(orderId)) + .filter(Boolean) + .map(order => ({ + id: order.id, + inspection_status: order.inspection_status, + step: Number(order.step ?? step), + updated_at: order.updated_at, + })); + + if (normalizedOrders.length === 0) { + throw new Error('订单不存在或不属于当前仓库'); + } + + const firstOrder = normalizedOrders[0]; - buildListData(rows, total, page, pageSize, extra = {}) { return { - list: rows, - pagination: this.buildPagination(page, pageSize, total), - ...extra, + id: firstOrder.id, + inspection_status: firstOrder.inspection_status, + step: firstOrder.step, + updated_at: firstOrder.updated_at, + updated_count: affectedRows, + ids: normalizedOrders.map(order => order.id), }; } } diff --git a/app/service/systemMethods/order/deliveryExpectionOrder.js b/app/service/systemMethods/order/deliveryExpectionOrder.js new file mode 100644 index 0000000..5600de0 --- /dev/null +++ b/app/service/systemMethods/order/deliveryExpectionOrder.js @@ -0,0 +1,26 @@ +'use strict'; + +const OrderBaseService = require('./base'); + +class DeliveryExpectionOrderService extends OrderBaseService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list,deliveryExpectionOrder'; + const _noNeedLog = 'list'; + const _noNeedAuth = 'list,deliveryExpectionOrder'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 配送异常订单列表。 + * @param {Object} data 请求体。 + * @return {Promise} 列表与分页信息。 + */ + async list(data = {}) { + return await this.listByModule('deliveryExpectionOrder', data); + } + +} + +module.exports = DeliveryExpectionOrderService; diff --git a/app/service/systemMethods/order/deliveryOrder.js b/app/service/systemMethods/order/deliveryOrder.js index dbec4dc..2139260 100644 --- a/app/service/systemMethods/order/deliveryOrder.js +++ b/app/service/systemMethods/order/deliveryOrder.js @@ -6,66 +6,21 @@ class DeliveryOrderService extends OrderBaseService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'getdeliveryOrderlist'; - const _noNeedLog = 'getdeliveryOrderlist'; - const _noNeedAuth = 'getdeliveryOrderlist'; + const _noNeedRight = 'list,deliveryOrder'; + const _noNeedLog = 'list'; + const _noNeedAuth = 'list,deliveryOrder'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } /** - * 获取已发货订单列表。 - * - * @param {Object} data 请求参数。 - * @return {Promise} 查询结果。 + * 配送订单列表。 + * @param {Object} data 请求体。 + * @return {Promise} 列表与分页信息。 */ - async getdeliveryOrderlist(data = {}) { - try { - const warehouseId = this.ensureWarehouseId(data); - const { Op } = this.app.Sequelize; - const { DeliveryModel } = await this.getOrderModels(warehouseId); - this.prepareWhereContext(data); - const whereData = this.ctx.where || {}; - const where = this.buildWhere(whereData, warehouseId); - - const hasOutboundFilter = this.hasWhereValue(whereData, 'outbound_status'); - if (!hasOutboundFilter) { - where.outbound_status = { [Op.ne]: 'none' }; - } - - const { page, pageSize, offset } = this.getPagination(data.pagination); - const result = await DeliveryModel.findAndCountAll({ - where, - attributes: [ - 'id', - 'delivery_order_code', - 'status', - 'step', - 'outbound_status', - 'delivery_time', - 'updated_at', - 'store_id', - 'warehouse_id', - 'buyer_nick', - 'logistics_name', - ], - offset, - limit: pageSize, - order: [[ 'delivery_time', 'DESC' ], [ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]], - raw: true, - }); - - return this.success('ok', { - data: this.buildListData(result.rows, result.count, page, pageSize, { - queryInfo: { - defaultOutboundFilter: !hasOutboundFilter, - }, - }), - code: 200, - }); - } catch (error) { - return this.fail(error.message, { code: 500 }); - } + async list(data = {}) { + return await this.listByModule('deliveryOrder', data); } + } module.exports = DeliveryOrderService; diff --git a/app/service/systemMethods/order/entrustOrder.js b/app/service/systemMethods/order/entrustOrder.js new file mode 100644 index 0000000..9a05e48 --- /dev/null +++ b/app/service/systemMethods/order/entrustOrder.js @@ -0,0 +1,26 @@ +'use strict'; + +const OrderBaseService = require('./base'); + +class EntrustOrderService extends OrderBaseService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list,entrustOrder'; + const _noNeedLog = 'list'; + const _noNeedAuth = 'list,entrustOrder'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 委托外仓订单列表。 + * @param {Object} data 请求体。 + * @return {Promise} 列表与分页信息。 + */ + async list(data = {}) { + return await this.listByModule('entrustOrder', data); + } + +} + +module.exports = EntrustOrderService; diff --git a/app/service/systemMethods/order/expectionOrder.js b/app/service/systemMethods/order/expectionOrder.js index a3044d4..3291afa 100644 --- a/app/service/systemMethods/order/expectionOrder.js +++ b/app/service/systemMethods/order/expectionOrder.js @@ -6,93 +6,21 @@ class ExpectionOrderService extends OrderBaseService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'getexpectionOrderlist'; - const _noNeedLog = 'getexpectionOrderlist'; - const _noNeedAuth = 'getexpectionOrderlist'; + const _noNeedRight = 'list,expectionOrder'; + const _noNeedLog = 'list'; + const _noNeedAuth = 'list,expectionOrder'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } /** - * 获取异常订单列表。 - * - * @param {Object} data 请求参数。 - * @return {Promise} 查询结果。 + * 待处理异常订单列表。 + * @param {Object} data 请求体。 + * @return {Promise} 列表与分页信息。 */ - async getexpectionOrderlist(data = {}) { - try { - const warehouseId = this.ensureWarehouseId(data); - const { Op } = this.app.Sequelize; - const { DeliveryModel } = await this.getOrderModels(warehouseId); - this.prepareWhereContext(data); - const whereData = this.ctx.where || {}; - const where = this.buildWhere(whereData, warehouseId); - - const hasExceptionFilter = [ - 'status', - 'post_status', - 'storage_status', - 'pick_status', - 'pack_status', - 'inspection_status', - 'print_status', - 'claim_status', - 'outbound_status', - 'intercept_status', - ].some(key => this.hasWhereValue(whereData, key)); - - if (!hasExceptionFilter) { - where[Op.or] = [ - { status: 'error' }, - { post_status: 'error' }, - { storage_status: 'error' }, - { pick_status: 'error' }, - { pack_status: 'error' }, - { inspection_status: 'error' }, - { print_status: 'error' }, - { claim_status: 'error' }, - { outbound_status: 'error' }, - { intercept_status: 'exception' }, - ]; - } - - const { page, pageSize, offset } = this.getPagination(data.pagination); - const result = await DeliveryModel.findAndCountAll({ - where, - attributes: [ - 'id', - 'delivery_order_code', - 'status', - 'step', - 'post_status', - 'pick_status', - 'pack_status', - 'inspection_status', - 'outbound_status', - 'intercept_status', - 'updated_at', - 'store_id', - 'warehouse_id', - 'buyer_nick', - 'logistics_name', - ], - offset, - limit: pageSize, - order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]], - raw: true, - }); - - return this.success('ok', { - data: this.buildListData(result.rows, result.count, page, pageSize, { - queryInfo: { - defaultExceptionFilter: !hasExceptionFilter, - }, - }), - code: 200, - }); - } catch (error) { - return this.fail(error.message, { code: 500 }); - } + async list(data = {}) { + return await this.listByModule('expectionOrder', data); } + } module.exports = ExpectionOrderService; diff --git a/app/service/systemMethods/order/index.js b/app/service/systemMethods/order/index.js index 811dc4f..52af987 100644 --- a/app/service/systemMethods/order/index.js +++ b/app/service/systemMethods/order/index.js @@ -6,210 +6,73 @@ class OrderIndexService extends OrderBaseService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'list,detail,listItems,stats,getreviewOrderlist,updateStatus,updateDeliveryTime,reviewOrder'; - const _noNeedLog = 'list,detail,listItems,stats,getreviewOrderlist'; - const _noNeedAuth = 'list,detail,listItems,stats,getreviewOrderlist,updateStatus,updateDeliveryTime,reviewOrder'; + const _noNeedRight = 'list,badgeCount,manualOutboundOrder,detail'; + const _noNeedLog = 'list,badgeCount,manualOutboundOrder,detail'; + const _noNeedAuth = 'list,badgeCount,manualOutboundOrder,detail'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } + /** + * 订单工作台总列表入口。 + * @param {Object} data 请求体。 + * @return {Promise} 列表与分页信息。 + */ async list(data = {}) { - try { - const warehouseId = this.ensureWarehouseId(data); - const { DeliveryModel } = await this.getOrderModels(warehouseId); - this.prepareWhereContext(data); - const whereData = this.ctx.where || {}; - const where = this.buildWhere(whereData, warehouseId); - const { page, pageSize, offset } = this.getPagination(data.pagination); - - const result = await DeliveryModel.findAndCountAll({ - where, - offset, - limit: pageSize, - order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]], - raw: true, - }); - - return this.success('ok', { - data: this.buildListData(result.rows, result.count, page, pageSize), - code: 200, - }); - } catch (error) { - return this.fail(error.message, { code: 500 }); - } - } - - async detail(data = {}) { - try { - const warehouseId = this.ensureWarehouseId(data); - const { DeliveryModel, OrderItemsModel } = await this.getOrderModels(warehouseId); - const where = this.getOrderLocatorWhere(data, warehouseId); - - const order = await DeliveryModel.findOne({ where, raw: true }); - if (!order) { - return this.fail('订单不存在', { code: 404 }); - } - - const items = await OrderItemsModel.findAll({ - where: { order_id: order.id }, - order: [[ 'id', 'ASC' ]], - raw: true, - }); - - return this.success('ok', { - data: { order, items }, - code: 200, - }); - } catch (error) { - return this.fail(error.message, { code: 500 }); - } - } - - async listItems(data = {}) { - try { - const warehouseId = this.ensureWarehouseId(data); - const { DeliveryModel, OrderItemsModel } = await this.getOrderModels(warehouseId); - const where = this.getOrderLocatorWhere(data, warehouseId); - - const order = await DeliveryModel.findOne({ - where, - attributes: [ 'id', 'delivery_order_code' ], - raw: true, - }); - if (!order) { - return this.fail('订单不存在', { code: 404 }); - } - - const items = await OrderItemsModel.findAll({ - where: { order_id: order.id }, - order: [[ 'id', 'ASC' ]], - raw: true, - }); - - return this.success('ok', { - data: { order, items }, - code: 200, - }); - } catch (error) { - return this.fail(error.message, { code: 500 }); - } - } - - async stats(data = {}) { - try { - const warehouseId = this.ensureWarehouseId(data); - const { Sequelize } = this.app; - const { DeliveryModel } = await this.getOrderModels(warehouseId); - this.prepareWhereContext(data); - const whereData = this.ctx.where || {}; - const where = this.buildWhere(whereData, warehouseId); - - const total = await DeliveryModel.count({ where }); - const byStatusRows = await DeliveryModel.findAll({ - where, - attributes: [ 'status', [ Sequelize.fn('COUNT', Sequelize.col('id')), 'count' ]], - group: [ 'status' ], - raw: true, - }); - const byOutboundRows = await DeliveryModel.findAll({ - where, - attributes: [ 'outbound_status', [ Sequelize.fn('COUNT', Sequelize.col('id')), 'count' ]], - group: [ 'outbound_status' ], - raw: true, - }); - - return this.success('ok', { - data: { - total, - byStatus: byStatusRows, - byOutboundStatus: byOutboundRows, - }, - code: 200, - }); - } catch (error) { - return this.fail(error.message, { code: 500 }); - } - } - - async getreviewOrderlist(data = {}) { - return await this.ctx.service.systemMethods.order.reviewOrder.getreviewOrderlist(data); + return await this.listByModule('order', data); } /** - * 更新订单状态相关字段。 - * - * @param {Object} data 请求参数。 - * @return {Promise} 更新结果。 + * 手动出库入口。 + * @param {Object} data 请求体。 + * @return {Promise} 迁移结果。 */ - async updateStatus(data = {}) { - try { - const warehouseId = this.ensureWarehouseId(data); - const { DeliveryModel } = await this.getOrderModels(warehouseId); - const where = this.getOrderLocatorWhere(data, warehouseId); - - const allowedFields = [ - 'status', - 'post_status', - 'storage_status', - 'pick_status', - 'pack_status', - 'inspection_status', - 'print_status', - 'claim_status', - 'outbound_status', - 'lock_status', - 'intercept_status', - 'step', - ]; - - const updateData = {}; - for (const key of allowedFields) { - if (data[key] !== undefined && data[key] !== null && data[key] !== '') { - updateData[key] = data[key]; - } - } - - if (data.delivery_time) { - updateData.delivery_time = this.parseDateTime(data.delivery_time, 'delivery_time'); - } - - if (!updateData.delivery_time && updateData.outbound_status === 'fin') { - updateData.delivery_time = new Date(); - } - - if (Object.keys(updateData).length === 0) { - return this.fail('没有可更新字段', { code: 400 }); - } - - updateData.updated_at = new Date(); - - const [ affected ] = await DeliveryModel.update(updateData, { where }); - if (!affected) { - return this.fail('订单不存在或未更新', { code: 404 }); - } - - const order = await DeliveryModel.findOne({ where, raw: true }); - return this.success('更新成功', { data: order, code: 200 }); - } catch (error) { - return this.fail(error.message, { code: 500 }); - } + async manualOutboundOrder(data = {}) { + return await this.ctx.service.systems.orderDeliveryMigration.syncOutboundOrdersToDelivery(data); } - async updateDeliveryTime(data = {}) { - if (!data.delivery_time) { - return this.fail('delivery_time 必填', { code: 400 }); + /** + * 获取订单工作台 8 个标签页的角标计数。 + * 其中配送、异常与归档相关标签页直接返回 99+。 + * @return {Promise} 角标展示值对象。 + */ + async badgeCount() { + const warehouseId = this.getWarehouseId(); + + if (warehouseId === null || warehouseId === undefined || warehouseId === '') { + throw new Error('缺少当前用户仓库上下文 store_id'); } - const nextData = { ...data }; - if (nextData.syncOutboundStatus === true || nextData.syncOutboundStatus === 1 || nextData.syncOutboundStatus === '1') { - nextData.outbound_status = 'fin'; + const cacheKey = this.getBadgeCountCacheKey(warehouseId); + const cachedBadgeCount = await this.app.getCacheAsync(cacheKey); + + if (cachedBadgeCount && typeof cachedBadgeCount === 'object') { + return cachedBadgeCount; } - return await this.updateStatus(nextData); + const [ reviewOrder, pendingOrder, outboundOrder, expectionOrder, entrustOrder ] = await Promise.all([ + this.getBadgeCountByModule('reviewOrder', warehouseId), + this.getBadgeCountByModule('pendingOrder', warehouseId), + this.getBadgeCountByModule('outboundOrder', warehouseId), + this.getBadgeCountByModule('expectionOrder', warehouseId), + this.getBadgeCountByModule('entrustOrder', warehouseId), + ]); + + const badgeCount = { + reviewOrder, + pendingOrder, + outboundOrder, + expectionOrder, + entrustOrder, + deliveryOrder: '99+', + deliveryExpectionOrder: '99+', + archiveOrder: '99+', + }; + + await this.app.setCacheAsync(cacheKey, badgeCount, 30); + + return badgeCount; } - async reviewOrder(data = {}) { - return await this.ctx.service.systemMethods.order.reviewOrder.reviewOrder(data); - } } module.exports = OrderIndexService; diff --git a/app/service/systemMethods/order/outboundOrder.js b/app/service/systemMethods/order/outboundOrder.js new file mode 100644 index 0000000..fcc8c18 --- /dev/null +++ b/app/service/systemMethods/order/outboundOrder.js @@ -0,0 +1,34 @@ +'use strict'; + +const OrderBaseService = require('./base'); + +class OutboundOrderService extends OrderBaseService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list,outboundOrder,manualOutboundOrder'; + const _noNeedLog = 'list,manualOutboundOrder'; + const _noNeedAuth = 'list,outboundOrder,manualOutboundOrder'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 待出库订单列表。 + * @param {Object} data 请求体。 + * @return {Promise} 列表与分页信息。 + */ + async list(data = {}) { + return await this.listByModule('outboundOrder', data); + } + + /** + * 手动出库入口。 + * @param {Object} data 请求体。 + * @return {Promise} 迁移结果。 + */ + async manualOutboundOrder(data = {}) { + return await this.ctx.service.systems.orderDeliveryMigration.syncOutboundOrdersToDelivery(data); + } +} + +module.exports = OutboundOrderService; diff --git a/app/service/systemMethods/order/pendingOrder.js b/app/service/systemMethods/order/pendingOrder.js index 5f59478..8cdc96b 100644 --- a/app/service/systemMethods/order/pendingOrder.js +++ b/app/service/systemMethods/order/pendingOrder.js @@ -2,75 +2,293 @@ const OrderBaseService = require('./base'); +const PENDING_OUTBOUND_STATUS = 'padding'; +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 ]); + class PendingOrderService extends OrderBaseService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'getpendingOrderlist'; - const _noNeedLog = 'getpendingOrderlist'; - const _noNeedAuth = 'getpendingOrderlist'; + const _noNeedRight = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder'; + const _noNeedLog = 'list,markPendingOutboundOrder,cancelOrder'; + const _noNeedAuth = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } /** - * 获取待处理订单列表。 - * - * @param {Object} data 请求参数。 - * @return {Promise} 查询结果。 + * 待处理订单列表。 + * @param {Object} data 请求体。 + * @return {Promise} 列表与分页信息。 */ - async getpendingOrderlist(data = {}) { - try { - const warehouseId = this.ensureWarehouseId(data); - const { Op } = this.app.Sequelize; - const { DeliveryModel } = await this.getOrderModels(warehouseId); - this.prepareWhereContext(data); - const whereData = this.ctx.where || {}; - const where = this.buildWhere(whereData, warehouseId); + async list(data = {}) { + return await this.listByModule('pendingOrder', data); + } - const hasStatusFilter = this.hasWhereValue(whereData, 'status'); - const hasOutboundFilter = this.hasWhereValue(whereData, 'outbound_status'); + /** + * 将待处理订单反审回待审核状态。 + * @param {Object} data 请求体。 + * @return {Promise} 更新后的订单信息。 + */ + async reverseReviewOrder(data = {}) { + return await this.updateOrderInspectionState(data, 'none'); + } - if (!hasStatusFilter) { - where.status = { [Op.in]: [ 'pedding', 'created' ] }; - } - if (!hasOutboundFilter) { - where.outbound_status = 'none'; - } + /** + * 将待处理订单批量标记为待出库。 + * @param {Object} data 请求体。 + * @param {number[]} data.ids 订单ID 数组。 + * @return {Promise} 更新后的订单信息。 + */ + async markPendingOutboundOrder(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const warehouseId = this.getWarehouseId(); + const orderIds = this.normalizePendingOutboundOrderIds(requestData); - const { page, pageSize, offset } = this.getPagination(data.pagination); - const result = await DeliveryModel.findAndCountAll({ - where, - attributes: [ - 'id', - 'delivery_order_code', - 'status', - 'step', - 'outbound_status', - 'inspection_status', - 'updated_at', - 'store_id', - 'warehouse_id', - 'buyer_nick', - 'logistics_name', - ], - offset, - limit: pageSize, - order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]], - raw: true, - }); - - return this.success('ok', { - data: this.buildListData(result.rows, result.count, page, pageSize, { - queryInfo: { - defaultPendingStatusFilter: !hasStatusFilter, - defaultPendingOutboundFilter: !hasOutboundFilter, - }, - }), - code: 200, - }); - } catch (error) { - return this.fail(error.message, { code: 500 }); + if (orderIds.length === 0) { + throw new Error('订单ID不能为空'); } + + const model = await this.getOrderModel('order', warehouseId); + const where = this.buildOrderWhere(orderIds, warehouseId); + const existingOrders = await model.findAll({ + where, + raw: true, + }); + + if (!Array.isArray(existingOrders) || existingOrders.length === 0) { + return this.success('取消成功', { + updated_count: 0, + ids: [], + }); + } + + if (existingOrders.length !== orderIds.length) { + throw new Error('订单不存在或不属于当前仓库'); + } + + const now = new Date(); + const updateValues = { + outbound_status: PENDING_OUTBOUND_STATUS, + updated_at: now, + }; + + const updateResult = await model.update(updateValues, { + where, + }); + + const affectedRows = Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0); + if (affectedRows <= 0) { + throw new Error('订单不存在或不属于当前仓库'); + } + + const updatedOrders = await model.findAll({ + where, + raw: true, + }); + + if (!Array.isArray(updatedOrders) || updatedOrders.length === 0) { + throw new Error('订单不存在或不属于当前仓库'); + } + + const orderMap = new Map(updatedOrders.map(order => [ Number(order.id), order ])); + const normalizedOrders = orderIds + .map(orderId => orderMap.get(orderId)) + .filter(Boolean) + .map(order => ({ + id: order.id, + outbound_status: order.outbound_status, + updated_at: order.updated_at, + })); + + if (normalizedOrders.length === 0) { + throw new Error('订单不存在或不属于当前仓库'); + } + + const firstOrder = normalizedOrders[0]; + + return { + id: firstOrder.id, + outbound_status: firstOrder.outbound_status, + updated_at: firstOrder.updated_at, + updated_count: affectedRows, + ids: normalizedOrders.map(order => order.id), + }; + } + + /** + * 将待处理订单取消,并关闭到已取消状态。 + * 仅允许取消当前仓库内处于待审核、待处理、待处理异常语义的订单。 + * @param {Object} data 请求体。 + * @param {number[]} data.ids 订单ID 数组。 + * @return {Promise} 更新后的订单信息。 + */ + async cancelOrder(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const warehouseId = this.getWarehouseId(); + const orderIds = this.normalizePendingCancelOrderIds(requestData); + + if (orderIds.length === 0) { + throw new Error('订单ID不能为空'); + } + + const model = await this.getOrderModel('order', warehouseId); + const where = this.buildOrderWhere(orderIds, warehouseId); + const existingOrders = await model.findAll({ + where, + raw: true, + }); + + if (!Array.isArray(existingOrders) || existingOrders.length === 0) { + return this.success('取消成功', { + updated_count: 0, + ids: [], + }); + } + + if (existingOrders.length !== orderIds.length) { + throw new Error('订单不存在或不属于当前仓库'); + } + + const nonCancelableOrder = existingOrders.find(order => !this.isCancelablePendingOrder(order)); + if (nonCancelableOrder) { + throw new Error('订单当前状态不允许取消'); + } + + const now = new Date(); + const updateValues = { + status: PENDING_CANCEL_STATUS, + step: PENDING_CANCEL_STEP, + updated_at: now, + }; + + const updateResult = await model.update(updateValues, { + where, + }); + + const affectedRows = Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0); + if (affectedRows <= 0) { + throw new Error('订单不存在或不属于当前仓库'); + } + + const updatedOrders = await model.findAll({ + where, + raw: true, + }); + + if (!Array.isArray(updatedOrders) || updatedOrders.length === 0) { + throw new Error('订单不存在或不属于当前仓库'); + } + + const orderMap = new Map(updatedOrders.map(order => [ Number(order.id), order ])); + const normalizedOrders = orderIds + .map(orderId => orderMap.get(orderId)) + .filter(Boolean) + .map(order => ({ + id: order.id, + status: order.status, + step: Number(order.step ?? PENDING_CANCEL_STEP), + updated_at: order.updated_at, + })); + + if (normalizedOrders.length === 0) { + throw new Error('订单不存在或不属于当前仓库'); + } + + const firstOrder = normalizedOrders[0]; + + return { + id: firstOrder.id, + status: firstOrder.status, + step: firstOrder.step, + updated_at: firstOrder.updated_at, + updated_count: affectedRows, + ids: normalizedOrders.map(order => order.id), + }; + } + + /** + * 规范待处理出库订单ID入参,仅接受 ids 数组且元素必须为正整数。 + * @param {Object} data 请求体。 + * @return {number[]} 订单ID 数组。 + */ + normalizePendingOutboundOrderIds(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const unexpectedKeys = Object.keys(requestData).filter(key => key !== 'ids'); + + if (unexpectedKeys.length > 0) { + throw new Error('待处理出库接口仅支持 ids 数组入参,不再支持 id、order_id、逗号字符串或其他兼容字段'); + } + + if (!Array.isArray(requestData.ids)) { + throw new Error('待处理出库接口仅支持 ids 数组入参'); + } + + const normalizedIds = requestData.ids.map(value => { + if (!Number.isInteger(value) || value <= 0) { + throw new Error('ids 仅支持正整数数组'); + } + + return value; + }); + + return Array.from(new Set(normalizedIds)); + } + + /** + * 规范待处理取消订单ID入参,仅接受 ids 数组且元素必须为正整数。 + * @param {Object} data 请求体。 + * @return {number[]} 订单ID 数组。 + */ + normalizePendingCancelOrderIds(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const unexpectedKeys = Object.keys(requestData).filter(key => key !== 'ids'); + + if (unexpectedKeys.length > 0) { + throw new Error('待处理取消接口仅支持 ids 数组入参,不再支持 id、order_id、逗号字符串或其他兼容字段'); + } + + if (!Array.isArray(requestData.ids)) { + throw new Error('待处理取消接口仅支持 ids 数组入参'); + } + + const normalizedIds = requestData.ids.map(value => { + if (!Number.isInteger(value) || value <= 0) { + throw new Error('ids 仅支持正整数数组'); + } + + return value; + }); + + return Array.from(new Set(normalizedIds)); + } + + /** + * 判断订单是否允许从待处理模块取消。 + * 仅允许处于待审核、待处理、待处理异常语义的订单取消。 + * @param {Object} order 订单记录。 + * @return {boolean} 是否允许取消。 + */ + isCancelablePendingOrder(order = {}) { + const step = Number(order.step); + const status = String(order.status || '').trim().toLowerCase(); + const outboundStatus = String(order.outbound_status || '').trim(); + + if (status === PENDING_CANCEL_STATUS) { + return false; + } + + if (!PENDING_CANCEL_ALLOWED_STEPS.has(step)) { + return false; + } + + if (PENDING_CANCEL_PENDING_STEPS.has(step) && outboundStatus === PENDING_OUTBOUND_STATUS) { + return false; + } + + return true; } } diff --git a/app/service/systemMethods/order/reviewOrder.js b/app/service/systemMethods/order/reviewOrder.js index 7aec438..40bb1de 100644 --- a/app/service/systemMethods/order/reviewOrder.js +++ b/app/service/systemMethods/order/reviewOrder.js @@ -6,139 +6,28 @@ class ReviewOrderService extends OrderBaseService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'getreviewOrderlist,reviewOrder'; - const _noNeedLog = 'getreviewOrderlist'; - const _noNeedAuth = 'getreviewOrderlist,reviewOrder'; + const _noNeedRight = 'list,reviewOrder,'; + const _noNeedLog = 'list,reviewOrder'; + const _noNeedAuth = 'list,reviewOrder'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } /** - * 将审核状态映射为订单步骤。 - * - * @param {string} reviewStatus 审核状态。 - * @return {number} 订单步骤值。 + * 待审核订单列表。 + * @param {Object} data 请求体。 + * @return {Promise} 列表与分页信息。 */ - mapReviewStatusToStep(reviewStatus) { - const status = String(reviewStatus || 'none').trim(); - - if (status === 'fin') { - return 1; - } - if (status === 'running' || status === 'padding') { - return 2; - } - if (status === 'error') { - return 3; - } - return 0; - } - - /** - * 获取待审核订单列表。 - * - * @param {Object} data 请求参数。 - * @return {Promise} 查询结果。 - */ - async getreviewOrderlist(data = {}) { - try { - const warehouseId = this.ensureWarehouseId(data); - const { Op } = this.app.Sequelize; - const { DeliveryModel } = await this.getOrderModels(warehouseId); - this.prepareWhereContext(data); - const whereData = this.ctx.where || {}; - const where = this.buildWhere(whereData, warehouseId); - - const hasInspectionFilter = this.hasWhereValue(whereData, 'inspection_status'); - if (!hasInspectionFilter) { - where.inspection_status = { [Op.ne]: 'none' }; - } - - if (this.hasWhereValue(whereData, 'operator_name')) { - const operatorName = this.getWhereValue(whereData, 'operator_name'); - where.operator_name = { [Op.like]: `%${operatorName}%` }; - } - - this.applyDateRange( - where, - 'operate_time', - this.getWhereValue(whereData, 'operate_time_start'), - this.getWhereValue(whereData, 'operate_time_end') - ); - - const { page, pageSize, offset } = this.getPagination(data.pagination); - const result = await DeliveryModel.findAndCountAll({ - where, - attributes: [ - 'id', - 'delivery_order_code', - 'status', - 'step', - 'inspection_status', - 'operator_name', - 'operate_time', - 'updated_at', - 'store_id', - 'warehouse_id', - 'buyer_nick', - 'logistics_name', - ], - offset, - limit: pageSize, - order: [[ 'operate_time', 'DESC' ], [ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]], - raw: true, - }); - - return this.success('ok', { - data: this.buildListData(result.rows, result.count, page, pageSize, { - queryInfo: { - defaultInspectionFilter: !hasInspectionFilter, - }, - }), - code: 200, - }); - } catch (error) { - return this.fail(error.message, { code: 500 }); - } + async list(data = {}) { + return await this.listByModule('reviewOrder', data); } /** * 更新订单审核状态。 - * - * @param {Object} data 请求参数。 - * @return {Promise} 更新结果。 + * @param {Object} data 请求体。 + * @return {Promise} 更新后的订单信息。 */ async reviewOrder(data = {}) { - try { - const warehouseId = this.ensureWarehouseId(data); - const { DeliveryModel } = await this.getOrderModels(warehouseId); - const where = this.getOrderLocatorWhere(data, warehouseId); - - const reviewStatus = String( - data.review_status ?? data.reviewStatus ?? data.inspection_status ?? 'fin' - ).trim(); - const allowedReviewStatus = new Set([ 'none', 'padding', 'running', 'fin', 'error' ]); - if (!allowedReviewStatus.has(reviewStatus)) { - return this.fail('review_status 参数不合法', { code: 400 }); - } - - const updateData = { - inspection_status: reviewStatus, - step: this.mapReviewStatusToStep(reviewStatus), - operator_name: data.operator_name || this.ctx.user?.real_name || this.ctx.user?.username || null, - operate_time: data.operate_time ? this.parseDateTime(data.operate_time, 'operate_time') : new Date(), - updated_at: new Date(), - }; - - const [ affected ] = await DeliveryModel.update(updateData, { where }); - if (!affected) { - return this.fail('订单不存在或未更新', { code: 404 }); - } - - const order = await DeliveryModel.findOne({ where, raw: true }); - return this.success('审核成功', { data: order, code: 200 }); - } catch (error) { - return this.fail(error.message, { code: 500 }); - } + return await this.updateReviewOrder(data); } } diff --git a/app/service/systemMethods/order/storageAllocation.js b/app/service/systemMethods/order/storageAllocation.js new file mode 100644 index 0000000..7ad0161 --- /dev/null +++ b/app/service/systemMethods/order/storageAllocation.js @@ -0,0 +1,47 @@ +'use strict'; + +const OrderBaseService = require('./base'); + +/** + * 系统方法层:订单储位分配入口。 + * 仅负责参数归一化与调用底层公共 service。 + */ +class StorageAllocationService extends OrderBaseService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'allocateStorage'; + const _noNeedLog = 'allocateStorage'; + const _noNeedAuth = 'allocateStorage'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 批量分配订单储位。 + * + * @param {Object} data 请求体。 + * @return {Promise} 统一 success 包装。 + */ + async allocateStorage(data = {}) { + const { service } = this; + const requestData = this.isPlainObject(data) ? data : {}; + const normalizedData = { + allow_storage_location: requestData.allow_storage_location + ?? requestData.allowStorageLocation + ?? requestData.is_allow_storage + ?? requestData.isAllowStorage, + order_ids: requestData.order_ids + ?? requestData.orderIds + ?? requestData.ids + ?? requestData.order_id + ?? requestData.orderId + ?? requestData.id, + warehouse_id: requestData.warehouse_id ?? requestData.warehouseId, + }; + + const result = await service.systems.orderStorageAllocation.allocateStorage(normalizedData); + return this.success('ok', result); + } +} + +module.exports = StorageAllocationService; diff --git a/app/service/systemMethods/setting/express.js b/app/service/systemMethods/setting/express.js new file mode 100644 index 0000000..00f2779 --- /dev/null +++ b/app/service/systemMethods/setting/express.js @@ -0,0 +1,171 @@ +'use strict'; + +const MainService = require('../../main'); + +class expressService extends MainService { + /** + * 初始化快递映射模块的权限配置。 + * + * @param {Egg.Context} ctx 上下文对象 + */ + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list,listBase,create,checkCodeUnique,update'; + const _noNeedLog = '*'; + const _noNeedAuth = 'list,listBase,create,checkCodeUnique,update'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 调用快递映射系统服务。 + * + * @param {string} methodName 系统服务方法名 + * @param {Object} data 请求参数 + * @param {string} defaultMessage 默认错误信息 + * @return {Promise} 统一返回结果 + */ + async callSystemExpress(methodName, data, defaultMessage) { + const { service } = this; + + try { + const result = await service.systems.setting.express[methodName](data); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || defaultMessage, { + code: Number(error.code) || 500, + }); + } + } + + /** + * 获取快递映射列表。 + * + * @param {Object} data 请求参数 + * @param {Object} [data.pagination] 分页参数 + * @return {Promise} 列表结果 + */ + async list(data = {}) { + const { service } = this; + const { + where = {}, + pagination: inputPagination, + page, + page_size: pageSize, + pageSize: camelPageSize, + ...rest + } = data || {}; + const pagination = { + ...(inputPagination && typeof inputPagination === 'object' ? inputPagination : {}), + }; + + if (page !== undefined) { + pagination.page = page; + } + + const resolvedPageSize = pageSize !== undefined ? pageSize : camelPageSize; + if (resolvedPageSize !== undefined) { + pagination.pageSize = resolvedPageSize; + } + + const payload = { + ...rest, + where, + pagination, + }; + + this.prepareWhereContext(payload, { + specialFieldMap: { + id: { + field: 'id', + }, + code: { + field: 'code', + }, + name: { + field: 'name', + }, + express_code: { + field: 'express_code', + }, + quickWhere: { + bucket: 'quick', + }, + }, + }); + + try { + const result = await service.systems.setting.express.list(payload); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '获取快递映射列表失败', { + code: Number(error.code) || 500, + }); + } + } + + /** + * 获取系统快递编码和名称列表。 + * + * @return {Promise} 基础快递列表结果 + */ + async listBase() { + return await this.callSystemExpress('listBase', {}, '获取系统快递基础列表失败'); + } + + /** + * 创建快递映射。 + * + * @param {Object} data 请求参数 + * @return {Promise} 创建结果 + */ + async create(data = {}) { + const { code, name, express_code: expressCode, expressCode: camelExpressCode, ...rest } = data || {}; + const payload = { + ...rest, + code, + name, + express_code: expressCode !== undefined ? expressCode : camelExpressCode, + }; + + return await this.callSystemExpress('create', payload, '创建快递映射失败'); + } + + /** + * 校验快递编码是否已被占用。 + * + * @param {Object} data 请求参数 + * @return {Promise} 校验结果 + */ + async checkCodeUnique(data = {}) { + const { id, code, ...rest } = data || {}; + const payload = { + ...rest, + id, + code, + }; + + return await this.callSystemExpress('checkCodeUnique', payload, '校验快递编码失败'); + } + + /** + * 修改快递映射。 + * + * @param {Object} data 请求参数 + * @return {Promise} 修改结果 + */ + async update(data = {}) { + const { id, code, name, express_code: expressCode, expressCode: camelExpressCode, ...rest } = data || {}; + const payload = { + ...rest, + id, + code, + name, + express_code: expressCode !== undefined ? expressCode : camelExpressCode, + }; + + return await this.callSystemExpress('update', payload, '更新快递映射失败'); + } +} + +module.exports = expressService; diff --git a/app/service/systemMethods/setting/expressInterface.js b/app/service/systemMethods/setting/expressInterface.js new file mode 100644 index 0000000..0810fae --- /dev/null +++ b/app/service/systemMethods/setting/expressInterface.js @@ -0,0 +1,230 @@ +'use strict'; + +const MainService = require('../../main'); + +class expressInterfaceService extends MainService { + /** + * 初始化快递接口管理模块的权限配置。 + * + * @param {Egg.Context} ctx 上下文对象 + */ + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list,create,update,delete'; + const _noNeedLog = '*'; + const _noNeedAuth = 'list,create,update,delete'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 调用快递接口系统服务。 + * + * @param {string} methodName 系统服务方法名 + * @param {Object} data 请求参数 + * @param {string} defaultMessage 默认错误信息 + * @return {Promise} 统一返回结果 + */ + async callSystemExpressInterface(methodName, data, defaultMessage) { + const { service } = this; + + try { + const result = await service.systems.setting.expressInterface[methodName](data); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || defaultMessage, { + code: Number(error.code) || 500, + }); + } + } + + /** + * 获取快递接口列表。 + * + * @param {Object} data 请求参数 + * @return {Promise} 列表结果 + */ + async list(data = {}) { + const { + where = {}, + pagination: inputPagination, + page, + page_size: pageSize, + pageSize: camelPageSize, + ...rest + } = data || {}; + + const pagination = { + ...(inputPagination && typeof inputPagination === 'object' ? inputPagination : {}), + }; + + if (page !== undefined) { + pagination.page = page; + } + + const resolvedPageSize = pageSize !== undefined ? pageSize : camelPageSize; + if (resolvedPageSize !== undefined) { + pagination.pageSize = resolvedPageSize; + } + + const payload = { + ...rest, + where, + pagination, + }; + + this.prepareWhereContext(payload, { + specialFieldMap: { + id: { + field: 'id', + }, + name: { + field: 'name', + }, + express_code: { + field: 'express_code', + }, + platform_code: { + field: 'platform_code', + }, + express_platform_id: { + field: 'express_platform_id', + }, + sender_name: { + field: 'sender_name', + }, + sender_tel: { + field: 'sender_tel', + }, + viewer: { + field: 'viewer', + }, + client_id: { + field: 'client_id', + }, + share_id: { + field: 'share_id', + }, + site_code: { + field: 'site_code', + }, + product_type: { + field: 'product_type', + }, + shop_name: { + field: 'shop_name', + }, + quickWhere: { + bucket: 'quick', + }, + }, + }); + + return await this.callSystemExpressInterface('list', payload, '获取快递接口列表失败'); + } + + /** + * 创建快递接口。 + * + * @param {Object} data 请求参数 + * @return {Promise} 创建结果 + */ + async create(data = {}) { + const { + name, + express_code: expressCode, + expressCode: camelExpressCode, + platform_code: platformCode, + platformCode: camelPlatformCode, + express_platform_id: expressPlatformId, + expressPlatformId: camelExpressPlatformId, + ...rest + } = data || {}; + + const payload = { + ...rest, + }; + + if (name !== undefined) { + payload.name = name; + } + if (expressCode !== undefined || camelExpressCode !== undefined) { + payload.express_code = expressCode !== undefined ? expressCode : camelExpressCode; + } + if (platformCode !== undefined || camelPlatformCode !== undefined) { + payload.platform_code = platformCode !== undefined ? platformCode : camelPlatformCode; + } + if (expressPlatformId !== undefined || camelExpressPlatformId !== undefined) { + payload.express_platform_id = expressPlatformId !== undefined ? expressPlatformId : camelExpressPlatformId; + } + + return await this.callSystemExpressInterface('create', payload, '创建快递接口失败'); + } + + /** + * 修改快递接口。 + * + * @param {Object} data 请求参数 + * @return {Promise} 修改结果 + */ + async update(data = {}) { + const { + id, + interface_id: interfaceId, + interfaceId: camelInterfaceId, + name, + express_code: expressCode, + expressCode: camelExpressCode, + platform_code: platformCode, + platformCode: camelPlatformCode, + express_platform_id: expressPlatformId, + expressPlatformId: camelExpressPlatformId, + ...rest + } = data || {}; + + const payload = { + ...rest, + }; + + payload.id = id !== undefined ? id : (interfaceId !== undefined ? interfaceId : camelInterfaceId); + if (name !== undefined) { + payload.name = name; + } + if (expressCode !== undefined || camelExpressCode !== undefined) { + payload.express_code = expressCode !== undefined ? expressCode : camelExpressCode; + } + if (platformCode !== undefined || camelPlatformCode !== undefined) { + payload.platform_code = platformCode !== undefined ? platformCode : camelPlatformCode; + } + if (expressPlatformId !== undefined || camelExpressPlatformId !== undefined) { + payload.express_platform_id = expressPlatformId !== undefined ? expressPlatformId : camelExpressPlatformId; + } + + return await this.callSystemExpressInterface('update', payload, '更新快递接口失败'); + } + + /** + * 删除快递接口。 + * + * @param {Object} data 请求参数 + * @return {Promise} 删除结果 + */ + async delete(data = {}) { + const { + id, + interface_id: interfaceId, + interfaceId: camelInterfaceId, + ...rest + } = data || {}; + + const payload = { + ...rest, + }; + + payload.id = id !== undefined ? id : (interfaceId !== undefined ? interfaceId : camelInterfaceId); + + return await this.callSystemExpressInterface('delete', payload, '删除快递接口失败'); + } +} + +module.exports = expressInterfaceService; diff --git a/app/service/systemMethods/setting/platform.js b/app/service/systemMethods/setting/platform.js new file mode 100644 index 0000000..6ab2d2b --- /dev/null +++ b/app/service/systemMethods/setting/platform.js @@ -0,0 +1,186 @@ +'use strict'; + +const MainService = require('../../main'); + +class platformService extends MainService { + /** + * 初始化平台设置模块的权限配置。 + * + * @param {Egg.Context} ctx 上下文对象 + */ + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list,create,update,delete'; + const _noNeedLog = '*'; + const _noNeedAuth = 'list,create,update,delete'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 调用平台设置系统服务。 + * + * @param {string} methodName 系统服务方法名 + * @param {Object} data 请求参数 + * @param {string} defaultMessage 默认错误信息 + * @return {Promise} 统一返回结果 + */ + async callSystemPlatform(methodName, data, defaultMessage) { + const { service } = this; + + try { + const result = await service.systems.setting.platform[methodName](data); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || defaultMessage, { + code: Number(error.code) || 500, + }); + } + } + + /** + * 获取平台设置列表。 + * + * @param {Object} data 请求参数 + * @return {Promise} 列表结果 + */ + async list(data = {}) { + const { + where = {}, + pagination: inputPagination, + page, + page_size: pageSize, + pageSize: camelPageSize, + ...rest + } = data || {}; + + const pagination = { + ...(inputPagination && typeof inputPagination === 'object' ? inputPagination : {}), + }; + + if (page !== undefined) { + pagination.page = page; + } + + const resolvedPageSize = pageSize !== undefined ? pageSize : camelPageSize; + if (resolvedPageSize !== undefined) { + pagination.pageSize = resolvedPageSize; + } + + const payload = { + ...rest, + where, + pagination, + }; + + this.prepareWhereContext(payload, { + specialFieldMap: { + id: { + field: 'id', + }, + code: { + field: 'code', + }, + name: { + field: 'name', + }, + platform_code: { + field: 'platform_code', + }, + quickWhere: { + bucket: 'quick', + }, + }, + }); + + return await this.callSystemPlatform('list', payload, '获取平台设置列表失败'); + } + + /** + * 创建平台设置。 + * + * @param {Object} data 请求参数 + * @return {Promise} 创建结果 + */ + async create(data = {}) { + const { + code, + name, + platform_code: platformCode, + platformCode: camelPlatformCode, + ...rest + } = data || {}; + + const payload = { + ...rest, + code, + name, + platform_code: platformCode !== undefined ? platformCode : camelPlatformCode, + }; + + return await this.callSystemPlatform('create', payload, '创建平台设置失败'); + } + + /** + * 修改平台设置。 + * + * @param {Object} data 请求参数 + * @return {Promise} 修改结果 + */ + async update(data = {}) { + const { + id, + setting_id: settingId, + settingId: camelSettingId, + code, + name, + platform_code: platformCode, + platformCode: camelPlatformCode, + ...rest + } = data || {}; + + const payload = { + ...rest, + }; + + payload.id = id !== undefined ? id : (settingId !== undefined ? settingId : camelSettingId); + + if (code !== undefined) { + payload.code = code; + } + + if (name !== undefined) { + payload.name = name; + } + + if (platformCode !== undefined || camelPlatformCode !== undefined) { + payload.platform_code = platformCode !== undefined ? platformCode : camelPlatformCode; + } + + return await this.callSystemPlatform('update', payload, '更新平台设置失败'); + } + + /** + * 删除平台设置。 + * + * @param {Object} data 请求参数 + * @return {Promise} 删除结果 + */ + async delete(data = {}) { + const { + id, + setting_id: settingId, + settingId: camelSettingId, + ...rest + } = data || {}; + + const payload = { + ...rest, + id: id !== undefined ? id : (settingId !== undefined ? settingId : camelSettingId), + }; + + return await this.callSystemPlatform('delete', payload, '删除平台设置失败'); + } +} + +module.exports = platformService; diff --git a/app/service/systemMethods/storage/expiry.js b/app/service/systemMethods/storage/expiry.js new file mode 100644 index 0000000..631ed48 --- /dev/null +++ b/app/service/systemMethods/storage/expiry.js @@ -0,0 +1,61 @@ +'use strict'; + +const MainService = require('../../main'); + +/** + * 系统方法层:storage.expiry(库存有效期列表包装层)。 + * 职责:拆解 where 与分页参数,调用库存有效期业务服务并统一包装响应。 + */ +class StorageExpiryMethodService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list'; + const _noNeedLog = 'list'; + const _noNeedAuth = 'list'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 查询库存有效期预警列表。 + * + * @param {Object} data 请求体 + * @param {Object} [data.where] 查询条件 + * @param {Object} [data.pagination] 分页参数 + * @return {Promise} 统一 success 包装响应 + */ + async list(data = {}) { + const { service } = this; + const { pagination } = data; + const { where } = this.prepareWhereContext(data, { + specialFieldMap: { + item_code: { + bucket: 'stock', + }, + goods_code: { + bucket: 'stock', + }, + item_name: { + bucket: 'stock', + }, + sku_property: { + bucket: 'stock', + }, + stock_unit: { + bucket: 'stock', + }, + is_shelf_life_mgmt: { + bucket: 'stock', + field: 'is_shelf_life_mgmt', + }, + remaining_threshold_days: { + bucket: 'stock', + }, + }, + }); + const result = await service.systems.storage.expiry.list(where, pagination); + return this.success('ok', result); + } +} + +module.exports = StorageExpiryMethodService; diff --git a/app/service/systemMethods/storage/inventory.js b/app/service/systemMethods/storage/inventory.js index b3f0df8..1d7acad 100644 --- a/app/service/systemMethods/storage/inventory.js +++ b/app/service/systemMethods/storage/inventory.js @@ -82,8 +82,8 @@ class InventoryMethodService extends MainService { async list(data = {}) { const { service } = this; const { pagination, sort, group_by_batch } = data; - const { where } = this.prepareWhereContext(data); - const result = await service.systems.storage.inventory.getInventoryList(where, pagination, sort, group_by_batch); + this.prepareWhereContext(data); + const result = await service.systems.storage.inventory.getInventoryList(pagination, sort, group_by_batch); return this.success('ok', result); } } diff --git a/app/service/systemMethods/storage/stockout.js b/app/service/systemMethods/storage/stockout.js deleted file mode 100644 index bf2f610..0000000 --- a/app/service/systemMethods/storage/stockout.js +++ /dev/null @@ -1,83 +0,0 @@ -'use strict'; - -const OrderBaseService = require('../order/base'); - -/** - * 系统方法层:storage.stockout(非订单出库单接口包装层)。 - */ -class StorageStockoutService extends OrderBaseService { - constructor(ctx) { - super(ctx); - const _noNeedLogin = ''; - const _noNeedRight = 'list,toOrder,listItems'; - const _noNeedLog = 'list,toOrder,listItems'; - const _noNeedAuth = 'list,toOrder,listItems'; - this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); - } - - async list(data = {}) { - try { - const warehouseId = this.ensureWarehouseId(data); - const { DeliveryModel } = await this.getOrderModels(warehouseId); - this.prepareWhereContext(data); - const whereData = this.ctx.where || {}; - const where = this.buildWhere(whereData, warehouseId); - // 默认只查询订单类型为 STOCKOUT 的出库单 - if (!whereData.order_type && !where.order_type) { - where.order_type = 'STOCKOUT'; - } - const { page, pageSize, offset } = this.getPagination(data.pagination); - - const result = await DeliveryModel.findAndCountAll({ - where, - offset, - limit: pageSize, - order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]], - raw: true, - }); - - return this.success('ok', { - data: this.buildListData(result.rows, result.count, page, pageSize), - code: 200, - }); - } catch (error) { - return this.fail(error.message, { code: 500 }); - } - } - - async toOrder() { - return this.fail('占位接口,暂未开放', { code: 405, placeholder: true }); - } - - async listItems(data = {}) { - try { - const warehouseId = this.ensureWarehouseId(data); - const { DeliveryModel, OrderItemsModel } = await this.getOrderModels(warehouseId); - const where = this.getOrderLocatorWhere(data, warehouseId); - - const order = await DeliveryModel.findOne({ - where, - attributes: [ 'id', 'delivery_order_code' ], - raw: true, - }); - if (!order) { - return this.fail('订单不存在', { code: 404 }); - } - - const items = await OrderItemsModel.findAll({ - where: { order_id: order.id }, - order: [[ 'id', 'ASC' ]], - raw: true, - }); - - return this.success('ok', { - data: { order, items }, - code: 200, - }); - } catch (error) { - return this.fail(error.message, { code: 500 }); - } - } -} - -module.exports = StorageStockoutService; diff --git a/app/service/systems/delivery_order.js b/app/service/systems/delivery_order.js index 75dfbfa..f954755 100644 --- a/app/service/systems/delivery_order.js +++ b/app/service/systems/delivery_order.js @@ -1,5 +1,6 @@ 'use strict'; const Service = require('egg').Service; +const { normalizeWarehouseShardId } = require('../../lib/warehouse_shard_guard'); const DELIVERY_ORDER_STEP = Object.freeze({ PENDING_REVIEW: 0, @@ -11,7 +12,313 @@ const DELIVERY_ORDER_STEP = Object.freeze({ CLOSED: 9, }); +const DEFAULT_STORE_SUBJECT_CONFIG = Object.freeze({ + max_notice_webhook_count: 5, + default_express_code: 'STO', + default_platform_code: 'TB', +}); + +const STORE_SUBJECT_CONFIG_CACHE_TTL_SECONDS = 600; + class DeliveryOrderService extends Service { + getStoreSubjectConfigCacheKey(storeId) { + return `delivery_order:store:${Number(storeId || 0)}:subject_config`; + } + + normalizeStoreSubjectConfig(rawValue) { + const storeModel = (this.app.model && this.app.model.Store) || (this.ctx.model && this.ctx.model.Store); + if (storeModel && typeof storeModel.normalizeSubjectConfig === 'function') { + return storeModel.normalizeSubjectConfig(rawValue); + } + + return { + ...DEFAULT_STORE_SUBJECT_CONFIG, + ...(rawValue && typeof rawValue === 'object' && !Array.isArray(rawValue) ? rawValue : {}), + }; + } + + async getStoreSubjectConfig(storeId) { + const normalizedStoreId = Number(storeId || 0); + if (!Number.isFinite(normalizedStoreId) || normalizedStoreId <= 0) { + return this.normalizeStoreSubjectConfig(null); + } + + const cacheKey = this.getStoreSubjectConfigCacheKey(normalizedStoreId); + if (this.app && typeof this.app.getCacheAsync === 'function') { + try { + const cachedValue = await this.app.getCacheAsync(cacheKey); + if (cachedValue && typeof cachedValue === 'object') { + return this.normalizeStoreSubjectConfig(cachedValue); + } + } catch (error) { + this.ctx.logger.warn('[DeliveryOrderService.getStoreSubjectConfig] read cache failed: %s', error.message); + } + } + + const storeModel = (this.app.model && this.app.model.Store) || (this.ctx.model && this.ctx.model.Store); + if (!storeModel || typeof storeModel.findByPk !== 'function') { + return this.normalizeStoreSubjectConfig(null); + } + + try { + const store = await storeModel.findByPk(normalizedStoreId, { + attributes: [ 'id', 'subject_config' ], + }); + const normalizedConfig = this.normalizeStoreSubjectConfig(store && store.subject_config); + + if (this.app && typeof this.app.setCacheAsync === 'function') { + await this.app.setCacheAsync(cacheKey, normalizedConfig, STORE_SUBJECT_CONFIG_CACHE_TTL_SECONDS); + } + + return normalizedConfig; + } catch (error) { + this.ctx.logger.warn('[DeliveryOrderService.getStoreSubjectConfig] load subject_config failed: %s', error.message); + return this.normalizeStoreSubjectConfig(null); + } + } + + findCodeOption(list, code) { + const normalizedCode = String(code || '').trim(); + if (!normalizedCode || !Array.isArray(list)) { + return null; + } + + return list.find(item => item && String(item.code || item.value || '').trim() === normalizedCode) || null; + } + + getOptionName(option) { + if (!option || typeof option !== 'object') { + return ''; + } + + return String(option.name || option.label || option.code || option.value || '').trim(); + } + + /** + * 按平台码解析平台列表项,优先基础平台,再匹配平台设置。 + * + * @param {Array} platformList 平台列表。 + * @param {string} platformCode 平台编码。 + * @return {Object|null} 匹配到的平台项。 + */ + findPlatformOptionByCode(platformList, platformCode) { + const normalizedCode = String(platformCode || '').trim(); + if (!normalizedCode || !Array.isArray(platformList)) { + return null; + } + + const basePlatform = platformList.find(item => item + && !item.is_system_setting + && String(item.code || item.value || '').trim() === normalizedCode) || null; + if (basePlatform) { + return basePlatform; + } + + return platformList.find(item => item + && item.is_system_setting + && String(item.code || item.value || '').trim() === normalizedCode) || null; + } + + /** + * 获取平台快照里的系统平台码。 + * + * @param {Object} option 平台项。 + * @param {string} fallbackCode 兜底编码。 + * @return {string} 系统平台码。 + */ + getPlatformSnapshotCode(option, fallbackCode = '') { + return String(option && (option.platform_code || option.code || option.value || fallbackCode) || '').trim(); + } + + /** + * 获取平台快照里的系统平台名称。 + * + * @param {Object} option 平台项。 + * @return {string} 系统平台名称。 + */ + getPlatformSnapshotName(option) { + if (!option || typeof option !== 'object') { + return ''; + } + + return String(option.platform_name || option.name || option.label || option.code || option.value || '').trim(); + } + + /** + * 解析平台快照。 + * + * 优先级: + * 1. 直接匹配 wms_platform.code; + * 2. 再按 wms_platfrom_setting.code 读取平台映射; + * 3. 最后才回退货主默认平台 code。 + * + * @param {string} sourcePlatformCode 外部平台编码。 + * @param {Object} storeSubjectConfig 货主签约配置。 + * @param {Object} [info={}] 上下文信息。 + * @return {Promise} 平台快照。 + */ + async resolvePlatformSnapshot(sourcePlatformCode, storeSubjectConfig, info = {}) { + const platformList = await this.ctx.service.systems.platform.getPlatformList(); + const externalCode = String(sourcePlatformCode || '').trim(); + const defaultCode = String(storeSubjectConfig && storeSubjectConfig.default_platform_code || '').trim(); + const matchedPlatform = this.findPlatformOptionByCode(platformList, externalCode); + + if (matchedPlatform) { + return { + sysPlatformCode: this.getPlatformSnapshotCode(matchedPlatform, externalCode), + sysPlatformName: this.getPlatformSnapshotName(matchedPlatform), + }; + } + + const fallbackPlatform = this.findPlatformOptionByCode(platformList, defaultCode); + if (fallbackPlatform) { + this.ctx.logger.warn('[DeliveryOrderService.prepareOrderData] invalid platform code fallback to store default', { + deliveryOrderCode: info.deliveryOrderCode, + warehouseId: info.warehouseId, + storeId: info.storeId, + sourcePlatformCode: externalCode, + defaultPlatformCode: defaultCode, + }); + + return { + sysPlatformCode: this.getPlatformSnapshotCode(fallbackPlatform, defaultCode), + sysPlatformName: this.getPlatformSnapshotName(fallbackPlatform), + }; + } + + this.ctx.logger.warn('[DeliveryOrderService.prepareOrderData] platform default not found in platform service list', { + deliveryOrderCode: info.deliveryOrderCode, + warehouseId: info.warehouseId, + storeId: info.storeId, + sourcePlatformCode: externalCode, + defaultPlatformCode: defaultCode, + }); + + return { + sysPlatformCode: defaultCode || externalCode, + sysPlatformName: '', + }; + } + + /** + * 通过快递设置表解析系统快递编码。 + * + * 说明:wms_express_setting 以 `code` 作为匹配键,以 `express_code` 作为系统快递编码。 + * 由于该表带有 `warehouse_id` 作用域,这里优先按 `warehouse_id + code` 进行限定查询, + * 命中后直接返回对应的系统快递编码。 + * + * @param {string} logisticsCode 外部快递编码。 + * @param {number|string} warehouseId 仓库ID。 + * @return {Promise} 系统快递编码,未命中时返回空字符串。 + */ + async resolveExpressCodeFromSetting(logisticsCode, warehouseId) { + const normalizedLogisticsCode = String(logisticsCode || '').trim(); + if (!normalizedLogisticsCode) { + return ''; + } + + const expressSettingModel = this.ctx.model && this.ctx.model.ExpressSetting; + if (!expressSettingModel || typeof expressSettingModel.findOne !== 'function') { + return ''; + } + + const where = { + code: normalizedLogisticsCode, + }; + const normalizedWarehouseId = Number(warehouseId || 0); + if (Number.isFinite(normalizedWarehouseId) && normalizedWarehouseId > 0) { + where.warehouse_id = normalizedWarehouseId; + } + + const expressSetting = await expressSettingModel.findOne({ + attributes: [ 'express_code' ], + where, + raw: true, + }); + + return String(expressSetting && expressSetting.express_code || '').trim(); + } + + /** + * 解析订单快递快照。 + * + * 优先级: + * 1. 直接匹配 wms_express.code; + * 2. 再按 wms_express_setting.code + warehouse_id 读取 express_code 映射为系统快递编码; + * 3. 最后才回退货主默认 express code。 + * + * @param {string} logisticsCode 外部快递编码。 + * @param {Object} storeSubjectConfig 货主签约配置。 + * @param {Object} [info={}] 上下文信息。 + * @return {Promise} 快递快照。 + */ + async resolveExpressSnapshot(logisticsCode, storeSubjectConfig, info = {}) { + const expressList = await this.ctx.service.systems.express.getExpressList(); + const externalCode = String(logisticsCode || '').trim(); + const defaultCode = String(storeSubjectConfig && storeSubjectConfig.default_express_code || '').trim(); + const matchedExpress = this.findCodeOption(expressList, externalCode); + + if (matchedExpress) { + return { + sysLogisticsCode: String(matchedExpress.express_code || matchedExpress.code || matchedExpress.value || externalCode).trim(), + sysLogisticsName: this.getOptionName(matchedExpress), + }; + } + + const expressSettingCode = await this.resolveExpressCodeFromSetting(externalCode, info.warehouseId); + if (expressSettingCode) { + const fallbackExpress = this.findCodeOption(expressList, expressSettingCode); + if (fallbackExpress) { + this.ctx.logger.warn('[DeliveryOrderService.prepareOrderData] invalid logistics code fallback to express setting mapping', { + deliveryOrderCode: info.deliveryOrderCode, + warehouseId: info.warehouseId, + storeId: info.storeId, + logisticsCode: externalCode, + expressSettingCode, + }); + + return { + sysLogisticsCode: String(fallbackExpress.express_code || fallbackExpress.code || fallbackExpress.value || expressSettingCode).trim(), + sysLogisticsName: this.getOptionName(fallbackExpress), + }; + } + + return { + sysLogisticsCode: expressSettingCode, + sysLogisticsName: '', + }; + } + + const fallbackExpress = this.findCodeOption(expressList, defaultCode); + if (fallbackExpress) { + this.ctx.logger.warn('[DeliveryOrderService.prepareOrderData] invalid logistics code fallback to store default', { + deliveryOrderCode: info.deliveryOrderCode, + warehouseId: info.warehouseId, + storeId: info.storeId, + logisticsCode: externalCode, + defaultExpressCode: defaultCode, + }); + + return { + sysLogisticsCode: String(fallbackExpress.express_code || fallbackExpress.code || fallbackExpress.value || defaultCode).trim(), + sysLogisticsName: this.getOptionName(fallbackExpress), + }; + } + + this.ctx.logger.warn('[DeliveryOrderService.prepareOrderData] express default not found in express service list', { + deliveryOrderCode: info.deliveryOrderCode, + warehouseId: info.warehouseId, + storeId: info.storeId, + logisticsCode: externalCode, + defaultExpressCode: defaultCode, + }); + + return { + sysLogisticsCode: defaultCode || externalCode, + sysLogisticsName: '', + }; + } + /** * 创建发货单。 * @@ -21,14 +328,18 @@ class DeliveryOrderService extends Service { */ async addOrder(data, info) { const { ctx } = this; - if (!info.warehouseId) { + let warehouseIdStr; + try { + warehouseIdStr = normalizeWarehouseShardId(info.warehouseId); + } catch (e) { return { success: false, - message: '订单创建失败: 非法参数', + message: `订单创建失败: ${e.message}`, data: null, }; } - const DeliveryModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(info.warehouseId); + info = { ...info, warehouseId: warehouseIdStr }; + const DeliveryModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseIdStr); const { deliveryOrder, orderLines } = data.request; // 开启事务 @@ -189,12 +500,12 @@ class DeliveryOrderService extends Service { : DELIVERY_ORDER_STEP.PENDING_REVIEW; } - /** - * 生成订单结构哈希值。 - * - * @param {Object} itemsInfo 订单明细信息。 - * @return {string} 结构哈希值。 - */ + /** + * 生成订单结构哈希值。 + * + * @param {Object} itemsInfo 订单明细信息。 + * @return {string} 结构哈希值。 + */ generateItemsHash(itemsInfo) { const crypto = require('crypto'); @@ -239,7 +550,7 @@ class DeliveryOrderService extends Service { * @return {Promise} 可入库的订单数据。 */ async prepareOrderData(deliveryOrder, info, step = DELIVERY_ORDER_STEP.PENDING_REVIEW) { - const { ctx, service } = this; + const { service } = this; const { deliveryOrderCode, preDeliveryOrderCode, @@ -273,34 +584,17 @@ class DeliveryOrderService extends Service { receiverInfo, } = deliveryOrder; - let platformCode = sourcePlatformCode; - let platformName = sourcePlatformName; - - try { - // 验证平台代码是否存在 - const platformInfo = await service.systems.platform.checkPlatformExists( - sourcePlatformCode, - info.warehouseId - ); - - if (platformInfo) { - // 平台存在,使用数据库中的平台信息 - platformCode = platformInfo.code; - platformName = platformInfo.name; - - ctx.logger.info(`平台验证通过: ${sourcePlatformCode} -> ${platformCode} (${platformName})`); - } else { - // 平台不存在,抛出错误 - throw new Error(`平台代码 ${sourcePlatformCode} 在仓库 ${info.warehouseId} 中不存在`); - } - } catch (error) { - ctx.logger.error(`平台验证失败: ${error.message}`, { - platformCode: sourcePlatformCode, - warehouseId: info.warehouseId, - deliveryOrderCode, - }); - throw error; // 抛出错误,让上层捕获 - } + const storeSubjectConfig = await this.getStoreSubjectConfig(info.storeId); + const platformSnapshot = await this.resolvePlatformSnapshot(sourcePlatformCode, storeSubjectConfig, { + deliveryOrderCode, + warehouseId: info.warehouseId, + storeId: info.storeId, + }); + const expressSnapshot = await this.resolveExpressSnapshot(logisticsCode, storeSubjectConfig, { + deliveryOrderCode, + warehouseId: info.warehouseId, + storeId: info.storeId, + }); return { delivery_order_code: deliveryOrderCode, @@ -309,9 +603,10 @@ class DeliveryOrderService extends Service { order_type: orderType, warehouse_code: warehouseCode, order_flag: orderFlag || '', - // 使用验证后的平台信息 - source_platform_code: platformCode, - source_platform_name: platformName, + source_platform_code: sourcePlatformCode || '', + source_platform_name: sourcePlatformName || '', + sys_platform_code: platformSnapshot.sysPlatformCode, + sys_platform_name: platformSnapshot.sysPlatformName, create_at: createTime ? new Date(createTime) : new Date(), place_order_time: placeOrderTime ? new Date(placeOrderTime) : null, pay_time: payTime ? new Date(payTime) : null, @@ -327,8 +622,10 @@ class DeliveryOrderService extends Service { freight: freight ? parseFloat(freight) : 0, ar_amount: arAmount ? parseFloat(arAmount) : 0, got_amount: gotAmount ? parseFloat(gotAmount) : 0, - logistics_code: logisticsCode, - logistics_name: logisticsName, + logistics_code: logisticsCode || '', + logistics_name: logisticsName || '', + sys_logistics_code: expressSnapshot.sysLogisticsCode, + sys_logistics_name: expressSnapshot.sysLogisticsName, express_code: expressCode || '', logistics_area_code: logisticsAreaCode || '', is_urgency: isUrgency || 'N', @@ -494,7 +791,7 @@ class DeliveryOrderService extends Service { ext_code: line.extCode || '', inventory_type: line.inventoryType || '', item_code: line.itemCode || '', - item_id: line.itemId || null, + item_id: itemId, item_name: line.itemName || '', order_line_no: line.orderLineNo || `${i + 1}`, owner_code: line.ownerCode || '', @@ -504,6 +801,8 @@ class DeliveryOrderService extends Service { extend_props: line.extendProps ? (typeof line.extendProps === 'string' ? line.extendProps : JSON.stringify(line.extendProps)) : null, + stock_id: stockId, + item_snapshot: this.buildOrderItemSnapshot(wms_stock, line), // 可选:记录重量信息到明细 item_weight: stockWeightMap.get(stockId) || 0, }); @@ -585,6 +884,31 @@ class DeliveryOrderService extends Service { }; } + buildOrderItemSnapshot(stockRecord = {}, line = {}) { + return { + id: Number(stockRecord.id || 0) || null, + stock_id: Number(stockRecord.stock_id || 0) || null, + item_code: String(stockRecord.item_code || line.itemCode || '').trim(), + item_name: String(stockRecord.item_name || line.itemName || '').trim(), + goods_code: String(stockRecord.goods_code || '').trim(), + sku_property: String(stockRecord.sku_property || '').trim(), + barcode: String(stockRecord.barcode || '').trim(), + brand_name: String(stockRecord.brand_name || '').trim(), + category_id: Number(stockRecord.category_id || 0) || null, + category_name: String(stockRecord.category_name || '').trim(), + item_type: String(stockRecord.item_type || '').trim(), + stock_unit: String(stockRecord.stock_unit || '').trim(), + inventory_type: String(line.inventoryType || '').trim(), + retail_price: this.safeParseFloat(stockRecord.retail_price, this.safeParseFloat(line.retailPrice, 0)), + gross_weight: this.safeParseFloat(stockRecord.gross_weight, 0), + net_weight: this.safeParseFloat(stockRecord.net_weight, 0), + length: this.safeParseFloat(stockRecord.length, 0), + width: this.safeParseFloat(stockRecord.width, 0), + height: this.safeParseFloat(stockRecord.height, 0), + volume: this.safeParseFloat(stockRecord.volume, 0), + }; + } + // 添加工具方法 safeParseFloat(value, defaultValue = 0) { if (value === null || value === undefined) return defaultValue; diff --git a/app/service/systems/excel.js b/app/service/systems/excel.js index cad0bd6..ac26405 100644 --- a/app/service/systems/excel.js +++ b/app/service/systems/excel.js @@ -521,7 +521,7 @@ class ExcelService extends Service { }); await fs.promises.mkdir(path.dirname(resolvedFilePath), { recursive: true }); - await fs.promises.writeFile(resolvedFilePath, buffer); + await this.writeAtomicBufferFile(resolvedFilePath, buffer); return { filePath: resolvedFilePath, @@ -530,6 +530,30 @@ class ExcelService extends Service { }; } + async writeAtomicBufferFile(targetPath, buffer) { + const directory = path.dirname(targetPath); + const tempPath = path.join( + directory, + `.${path.basename(targetPath)}.${process.pid}.${Date.now()}.${crypto.randomBytes(6).toString('hex')}.tmp` + ); + + await fs.promises.writeFile(tempPath, buffer); + + try { + await fs.promises.rename(tempPath, targetPath); + } catch (error) { + if (error && (error.code === 'EEXIST' || error.code === 'EPERM' || error.code === 'EBUSY')) { + await fs.promises.rm(targetPath, { force: true }); + await fs.promises.rename(tempPath, targetPath); + return; + } + + throw error; + } finally { + await fs.promises.rm(tempPath, { force: true }).catch(() => {}); + } + } + sanitizeFilename(filename = 'export.xlsx', fallbackExt = '.xlsx') { const normalizedName = String(filename || '').trim() || `export${fallbackExt}`; const rawExt = path.extname(normalizedName); diff --git a/app/service/systems/express.js b/app/service/systems/express.js new file mode 100644 index 0000000..5577d50 --- /dev/null +++ b/app/service/systems/express.js @@ -0,0 +1,504 @@ +'use strict'; + +const { Service } = require('egg'); + +const DEFAULT_CACHE_TTL_SECONDS = 600; +const DEFAULT_EXPRESS_PRODUCT_TYPE_CACHE_TTL_SECONDS = 60 * 60; + +class ExpressService extends Service { + /** + * 生成快递列表缓存键。 + * + * @param {number|string} warehouseId 仓库ID + * @return {string} 缓存键 + */ + getExpressListCacheKey(warehouseId = 0) { + const normalizedWarehouseId = Number(warehouseId || 0); + + if (Number.isFinite(normalizedWarehouseId) && normalizedWarehouseId > 0) { + return `express:list:${normalizedWarehouseId}`; + } + + return 'express:list'; + } + + /** + * 获取当前上下文中的仓库ID。 + * + * @return {number} 仓库ID,未获取到时返回 0 + */ + getCurrentWarehouseId() { + const warehouseId = Number(this.ctx && this.ctx.user && this.ctx.user.store_id || 0); + + if (Number.isFinite(warehouseId) && warehouseId > 0) { + return warehouseId; + } + + return 0; + } + + /** + * 生成合并后的快递项展示名称。 + * + * @param {string} settingCode 快递设置编码 + * @param {Object} expressItem 系统快递项 + * @return {string} 展示名称 + */ + buildMergedExpressLabel(settingCode, expressItem) { + const normalizedSettingCode = String(settingCode || '').trim(); + const expressName = String(expressItem && (expressItem.name || expressItem.label || expressItem.code || expressItem.value) || '').trim(); + + if (!normalizedSettingCode) { + return expressName; + } + + if (!expressName) { + return normalizedSettingCode; + } + + return `${normalizedSettingCode} (${expressName})`; + } + + /** + * 规范化快递设置记录。 + * + * @param {Object} row 数据库记录 + * @param {Map} expressMap 系统快递映射 + * @return {Object|null} 规范化后的记录 + */ + normalizeExpressSettingRow(row, expressMap) { + if (!row || typeof row !== 'object') { + return null; + } + + const code = String(row.code || '').trim(); + if (!code) { + return null; + } + + const expressCode = String(row.express_code || '').trim(); + const expressItem = expressMap instanceof Map ? expressMap.get(expressCode) : null; + const label = this.buildMergedExpressLabel(code, expressItem); + + return { + code, + name: label, + value: code, + label, + is_system_setting: true, + id: row.id === undefined || row.id === null ? null : row.id, + alias: String(row.name || '').trim(), + express_code: String((expressItem && (expressItem.code || expressItem.value)) || expressCode || '').trim(), + }; + } + + /** + * 从数据库加载快递设置列表。 + * + * @param {number|string} warehouseId 仓库ID + * @return {Promise} 快递设置列表 + */ + async loadExpressSettingListFromDatabase(warehouseId = 0) { + const normalizedWarehouseId = Number(warehouseId || 0); + if (!Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + return []; + } + + const expressSettingModel = this.ctx.model && this.ctx.model.ExpressSetting; + if (!expressSettingModel || typeof expressSettingModel.findAll !== 'function') { + return []; + } + + const rows = await expressSettingModel.findAll({ + attributes: [ 'id', 'code', 'name', 'express_code' ], + where: { + warehouse_id: normalizedWarehouseId, + }, + order: [[ 'code', 'ASC' ]], + raw: true, + }); + + if (!Array.isArray(rows)) { + return []; + } + + return rows; + } + + /** + * 合并系统快递和快递设置列表。 + * + * @param {Array} expressList 系统快递列表 + * @param {Array} expressSettingList 快递设置列表 + * @return {Array} 合并后的快递列表 + */ + buildMergedExpressList(expressList, expressSettingList) { + const mergedList = []; + const seenCodeMap = new Set(); + const normalizedExpressList = Array.isArray(expressList) ? expressList : []; + const expressMap = new Map(); + + for (const expressItem of normalizedExpressList) { + if (!expressItem || typeof expressItem !== 'object') { + continue; + } + + const code = String(expressItem.code || expressItem.value || '').trim(); + if (!code) { + continue; + } + + if (!expressMap.has(code)) { + expressMap.set(code, expressItem); + } + } + + for (const expressItem of normalizedExpressList) { + if (!expressItem || typeof expressItem !== 'object') { + continue; + } + + const code = String(expressItem.code || expressItem.value || '').trim(); + if (!code || seenCodeMap.has(code)) { + continue; + } + + mergedList.push(expressItem); + seenCodeMap.add(code); + } + + for (const row of Array.isArray(expressSettingList) ? expressSettingList : []) { + const mergedItem = this.normalizeExpressSettingRow(row, expressMap); + if (!mergedItem || seenCodeMap.has(mergedItem.code)) { + continue; + } + + mergedList.push(mergedItem); + seenCodeMap.add(mergedItem.code); + } + + return mergedList; + } + + /** + * 生成快递产品类型列表缓存键。 + * + * @param {string} expressCode 快递公司编码 + * @return {string} 缓存键 + */ + getExpressProductTypeListCacheKey(expressCode = '') { + const normalizedExpressCode = String(expressCode || '').trim(); + + if (!normalizedExpressCode) { + return 'express:product-type:list'; + } + + return `express:product-type:list:${normalizedExpressCode}`; + } + + /** + * 规范化快递产品类型记录。 + * + * @param {Object} row 数据库记录 + * @return {Object|null} 规范化后的记录 + */ + normalizeExpressProductTypeRow(row) { + if (!row || typeof row !== 'object') { + return null; + } + + const code = String(row.code || '').trim(); + if (!code) { + return null; + } + + const name = String(row.name || '').trim(); + + return { + code, + express_code: String(row.express_code || '').trim(), + name, + value: code, + label: name || code, + }; + } + + normalizeExpressRow(row) { + if (!row || typeof row !== 'object') { + return null; + } + + const code = String(row.code || '').trim(); + if (!code) { + return null; + } + + return { + code, + name: String(row.name || '').trim(), + value: code, + label: String(row.name || code).trim(), + is_system_setting: false, + id: null, + alias: null, + }; + } + + async loadExpressListFromDatabase() { + const rows = await this.ctx.model.Express.findAll({ + attributes: [ 'code', 'name' ], + order: [[ 'code', 'ASC' ]], + raw: true, + }); + + if (!Array.isArray(rows)) { + return []; + } + + return rows + .map(row => this.normalizeExpressRow(row)) + .filter(Boolean); + } + + /** + * 获取系统快递编码和名称列表。 + * + * 该接口只返回系统基础快递数据,不合并仓库自定义映射。 + * + * @return {Promise} 系统快递编码和名称列表 + */ + async getSystemExpressList() { + return await this.loadExpressListFromDatabase(); + } + + /** + * 从数据库加载快递产品类型列表。 + * + * @param {string} expressCode 快递公司编码 + * @return {Promise} 快递产品类型列表 + */ + async loadExpressProductTypeListFromDatabase(expressCode = '') { + const normalizedExpressCode = String(expressCode || '').trim(); + const query = { + attributes: [ 'code', 'name', 'express_code' ], + order: [[ 'express_code', 'ASC' ], [ 'code', 'ASC' ]], + raw: true, + }; + + if (normalizedExpressCode) { + query.where = { + express_code: normalizedExpressCode, + }; + } + + const rows = await this.ctx.model.ExpressProductType.findAll(query); + + if (!Array.isArray(rows)) { + return []; + } + + return rows + .map(row => this.normalizeExpressProductTypeRow(row)) + .filter(Boolean); + } + + /** + * 获取快递列表。 + * + * 先读取系统快递,再按当前仓库合并快递设置;同一编码只保留一条记录。 + * + * @return {Promise} 快递列表 + */ + async getExpressList() { + const warehouseId = this.getCurrentWarehouseId(); + const cacheKey = this.getExpressListCacheKey(warehouseId); + + try { + const cachedList = await this.app.getCacheAsync(cacheKey); + if (cachedList !== null && cachedList !== undefined) { + return Array.isArray(cachedList) ? cachedList : []; + } + + const [ expressList, expressSettingList ] = await Promise.all([ + this.loadExpressListFromDatabase(), + this.loadExpressSettingListFromDatabase(warehouseId), + ]); + + const mergedList = this.buildMergedExpressList(expressList, expressSettingList); + await this.app.setCacheAsync(cacheKey, mergedList, DEFAULT_CACHE_TTL_SECONDS); + + return mergedList; + } catch (error) { + this.ctx.logger.error('[ExpressService.getExpressList] 获取快递列表失败', { + error: error.message, + stack: error.stack, + }); + throw error; + } + } + + /** + * 获取快递产品类型列表。 + * + * @param {string} expressCode 快递公司编码 + * @return {Promise} 快递产品类型列表 + */ + async getExpressProductTypeList(expressCode = '') { + const cacheKey = this.getExpressProductTypeListCacheKey(expressCode); + const normalizedExpressCode = String(expressCode || '').trim(); + + try { + const cachedList = await this.app.getCacheAsync(cacheKey); + if (cachedList !== null && cachedList !== undefined) { + return Array.isArray(cachedList) ? cachedList : []; + } + + const expressProductTypeList = await this.loadExpressProductTypeListFromDatabase(normalizedExpressCode); + await this.app.setCacheAsync(cacheKey, expressProductTypeList, DEFAULT_EXPRESS_PRODUCT_TYPE_CACHE_TTL_SECONDS); + + return expressProductTypeList; + } catch (error) { + this.ctx.logger.error('[ExpressService.getExpressProductTypeList] 获取快递产品类型失败', { + error: error.message, + stack: error.stack, + expressCode: normalizedExpressCode, + }); + throw error; + } + } + + /** + * 处理订单快递记录。 + * 先按订单ID和业务键筛选 wms_order_express,再排除已存在且状态不为 0 的记录, + * 对可重试记录重置 retry_count,并为缺失记录补插状态为 0 的快递记录。 + * + * @param {Array} orders 订单与业务键列表。 + * @param {number} orders[].order_id 订单ID。 + * @param {number} orders[].business_key 业务键。 + * @return {Promise} 处理后的订单列表与运单号列表。 + */ + async createWaybillCode(orders = []) { + const { app, ctx } = this; + const { Op } = app.Sequelize; + const orderExpressModel = ctx.model && ctx.model.OrderExpress; + if (!orderExpressModel + || typeof orderExpressModel.findAll !== 'function' + || typeof orderExpressModel.update !== 'function' + || typeof orderExpressModel.bulkCreate !== 'function') { + throw new Error('订单快递模型未初始化'); + } + + // orders 入参去重归一化。 + const normalizedOrderMap = new Map(); + for (const order of Array.isArray(orders) ? orders : []) { + const orderId = Number(order && order.order_id); + const businessKey = Number(order && order.business_key); + + if (!Number.isFinite(orderId) || orderId <= 0 || !Number.isInteger(businessKey)) { + continue; + } + + const orderKey = `${orderId}:${businessKey}`; + if (!normalizedOrderMap.has(orderKey)) { + normalizedOrderMap.set(orderKey, { + order_id: orderId, + business_key: businessKey, + }); + } + } + + const normalizedOrders = Array.from(normalizedOrderMap.values()); + if (normalizedOrders.length === 0) { + return { + orders: [], + waybill_codes: [], + }; + } + + // 事务开始。 + return await app.model.transaction(async transaction => { + // 事务内批量查询已有记录。 + const existingRows = await orderExpressModel.findAll({ + where: { + [Op.or]: normalizedOrders.map(order => ({ + order_id: order.order_id, + business_key: order.business_key, + })), + }, + attributes: [ 'id', 'order_id', 'business_key', 'status', 'retry_count' ], + raw: true, + transaction, + lock: transaction.LOCK.UPDATE, + }); + + const existingMap = new Map(); + const retryIds = []; + for (const row of Array.isArray(existingRows) ? existingRows : []) { + const orderId = Number(row && row.order_id); + const businessKey = Number(row && row.business_key); + if (!Number.isFinite(orderId) || orderId <= 0 || !Number.isInteger(businessKey)) { + continue; + } + + const orderKey = `${orderId}:${businessKey}`; + existingMap.set(orderKey, row); + + // 过滤 status != 0 的已存在记录。 + if (Number(row && row.status) === 0) { + retryIds.push(row.id); + } + } + + // 重置可重试记录 retry_count=0。 + const retryableIds = Array.from(new Set(retryIds.filter(id => Number.isFinite(Number(id)) && Number(id) > 0))); + if (retryableIds.length > 0) { + await orderExpressModel.update({ + retry_count: 0, + }, { + where: { + id: { + [Op.in]: retryableIds, + }, + }, + transaction, + }); + } + + // 组装待插入记录。 + const rowsToCreate = []; + for (const order of normalizedOrders) { + const orderKey = `${order.order_id}:${order.business_key}`; + const existingRow = existingMap.get(orderKey); + if (existingRow) { + const status = Number(existingRow.status); + if (status !== 0) { + continue; + } + + continue; + } + + rowsToCreate.push({ + order_id: order.order_id, + business_key: order.business_key, + status: 0, + retry_count: 0, + }); + } + + // 批量插入 status=0 的新记录。 + if (rowsToCreate.length > 0) { + await orderExpressModel.bulkCreate(rowsToCreate, { + transaction, + }); + } + + return { + orders: normalizedOrders, + waybill_codes: [], + }; + }); + } +} + +module.exports = ExpressService; diff --git a/app/service/systems/notice/index.js b/app/service/systems/notice/index.js index 7ac776a..fe6ba7c 100644 --- a/app/service/systems/notice/index.js +++ b/app/service/systems/notice/index.js @@ -24,6 +24,7 @@ const DEFAULT_REGISTERED_EVENT_CODES = Object.freeze([ 'all', '*', 'receiving_completed', + 'order_cancel_intercepted', 'store_warehouse_print_quantity_adjusted', ]); const DRIVER_TYPE_ALIASES = Object.freeze({ @@ -586,6 +587,8 @@ class NoticeService extends Service { const config = this.toObject(value, {}); return { max_notice_webhook_count: DEFAULT_MAX_NOTICE_WEBHOOK_COUNT, + default_express_code: 'STO', + default_platform_code: 'TB', ...config, }; }; diff --git a/app/service/systems/order_delivery_migration.js b/app/service/systems/order_delivery_migration.js new file mode 100644 index 0000000..15d1085 --- /dev/null +++ b/app/service/systems/order_delivery_migration.js @@ -0,0 +1,643 @@ +'use strict'; + +const MainService = require('../main'); + +const OUTBOUND_STATUS = 'fin'; +const OUTBOUND_STATUS_TIMEOUT = 'timeout'; +const OUTBOUND_STEP = 4; +const DISPATCH_LANE = 'm4'; +const MAX_BATCH_SIZE = 1000; +const CURRENT_TABLE_PATTERN = /^wms_order_delivery_(\d+)$/; +const RETRYABLE_DATABASE_ERROR_CODES = new Set([ 1205, 1213, 'ER_LOCK_WAIT_TIMEOUT', 'ER_LOCK_DEADLOCK' ]); + +/** + * 订单出库后迁移到配送表的同步服务。 + */ +class OrderDeliveryMigrationService extends MainService { + /** + * 同步当前仓库分表中已出库订单到配送表。 + * + * @param {Object} data 请求参数。 + * @param {number|Array} [data.warehouseId] 单个仓库ID或仓库ID列表。 + * @param {Array} [data.warehouseIds] 仓库ID列表。 + * @return {Promise} 同步结果。 + */ + async syncOutboundOrdersToDelivery(data = {}) { + return this.syncOutboundOrdersByStatus(data, { + outboundStatuses: [ OUTBOUND_STATUS ], + persistTimeoutState: true, + }); + } + + /** + * 重试出库超时订单并继续迁移到配送表。 + * + * @param {Object} data 请求参数。 + * @param {number|Array} [data.warehouseId] 单个仓库ID或仓库ID列表。 + * @param {Array} [data.warehouseIds] 仓库ID列表。 + * @return {Promise} 同步结果。 + */ + async retryTimeoutOutboundOrdersToDelivery(data = {}) { + return this.syncOutboundOrdersByStatus(data, { + outboundStatuses: [ OUTBOUND_STATUS_TIMEOUT ], + persistTimeoutState: false, + }); + } + + /** + * 按指定出库状态同步订单到配送表。 + * + * @param {Object} data 请求参数。 + * @param {number|Array} [data.warehouseId] 单个仓库ID或仓库ID列表。 + * @param {Array} [data.warehouseIds] 仓库ID列表。 + * @param {Object} [options] 迁移控制参数。 + * @param {Array} [options.outboundStatuses] 需要迁移的出库状态。 + * @param {number} [options.queryTimeoutMs] 单条数据库查询的超时时间。 + * @param {number} [options.executionTimeoutMs] 单仓库批次的执行超时时间。 + * @param {boolean} [options.persistTimeoutState] 失败后是否将源订单标记为出库超时。 + * @return {Promise} 同步结果。 + */ + async syncOutboundOrdersByStatus(data = {}, options = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const explicitWarehouseIds = this.normalizeWarehouseIds(requestData); + const warehouseIds = explicitWarehouseIds.length > 0 + ? explicitWarehouseIds + : await this.listCurrentWarehouseIds(); + + const results = []; + let remaining = MAX_BATCH_SIZE; + let totalSelected = 0; + let totalCreated = 0; + let totalSkipped = 0; + let totalTimeout = 0; + + for (const warehouseId of warehouseIds) { + if (remaining <= 0) { + break; + } + + const batchLimit = Math.min(remaining, MAX_BATCH_SIZE); + const batchResult = await this.syncOutboundOrdersForWarehouse(warehouseId, batchLimit, options); + + results.push(batchResult); + totalSelected += batchResult.selectedCount; + totalCreated += batchResult.createdCount; + totalSkipped += batchResult.skippedCount; + totalTimeout += Number(batchResult.timeoutCount || 0); + remaining -= batchResult.selectedCount; + } + + return { + warehouseIds, + batchSize: MAX_BATCH_SIZE, + outboundStatuses: this.normalizeOutboundStatuses(options.outboundStatuses), + totalSelected, + totalCreated, + totalSkipped, + totalTimeout, + results, + }; + } + + /** + * 规范化仓库ID列表。 + * + * @param {Object} data 请求参数。 + * @return {Array} 仓库ID列表。 + */ + normalizeWarehouseIds(data = {}) { + if (!this.isPlainObject(data)) { + return []; + } + + const candidateValues = Array.isArray(data.warehouseIds) + ? data.warehouseIds + : [ data.warehouseId ?? data.warehouse_id ].filter(value => value !== undefined && value !== null && value !== ''); + + return Array.from(new Set(candidateValues + .map(value => Number(value)) + .filter(value => Number.isFinite(value) && value > 0))) + .sort((left, right) => left - right); + } + + /** + * 获取当前库中存在的订单工作台仓库ID。 + * + * @return {Promise>} 仓库ID列表。 + */ + async listCurrentWarehouseIds() { + const factory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; + + if (!factory || typeof factory.listManagedTableNames !== 'function') { + return []; + } + + const tableNames = await factory.listManagedTableNames(); + + return Array.from(new Set((Array.isArray(tableNames) ? tableNames : []) + .map(tableName => { + const matched = CURRENT_TABLE_PATTERN.exec(String(tableName || '')); + return matched ? Number(matched[1]) : null; + }) + .filter(value => Number.isFinite(value) && value > 0))) + .sort((left, right) => left - right); + } + + /** + * 规范化需要迁移的出库状态。 + * + * @param {Array|string} outboundStatuses 目标状态。 + * @return {Array} 规范化后的状态列表。 + */ + normalizeOutboundStatuses(outboundStatuses = [ OUTBOUND_STATUS ]) { + const candidates = Array.isArray(outboundStatuses) + ? outboundStatuses + : [ outboundStatuses ]; + + const normalizedStatuses = Array.from(new Set(candidates + .map(value => String(value || '').trim()) + .filter(Boolean))); + + return normalizedStatuses.length > 0 ? normalizedStatuses : [ OUTBOUND_STATUS ]; + } + + /** + * 构造 Sequelize 查询参数。 + * + * @param {Object|null} transaction 事务对象。 + * @param {number} [queryTimeoutMs] 查询超时时间。 + * @return {Object} Sequelize 查询参数。 + */ + buildMigrationQueryOptions(transaction, queryTimeoutMs) { + const queryOptions = {}; + + if (transaction) { + queryOptions.transaction = transaction; + } + + const normalizedTimeoutMs = Number(queryTimeoutMs); + if (Number.isFinite(normalizedTimeoutMs) && normalizedTimeoutMs > 0) { + queryOptions.timeout = normalizedTimeoutMs; + } + + return queryOptions; + } + + /** + * 识别可重试的出库迁移错误。 + * + * @param {Error} error 运行时错误。 + * @return {{ retryable: boolean, category: string, message: string }} 错误分类结果。 + */ + getOutboundMigrationErrorInfo(error) { + const errorMessage = String(error && error.message || ''); + const errorName = String(error && error.name || ''); + const parentError = error && error.parent ? error.parent : null; + const errorCode = parentError && (parentError.code || parentError.errno) + ? parentError.code || parentError.errno + : error && (error.code || error.errno); + const normalizedMessage = errorMessage.toLowerCase(); + + if (errorName === 'SequelizeTimeoutError' || errorName === 'TimeoutError' || errorCode === 'ETIMEDOUT') { + return { + retryable: true, + category: 'timeout', + message: errorMessage, + }; + } + + if (errorName === 'SequelizeDatabaseError') { + if (normalizedMessage.includes('lock wait timeout')) { + return { + retryable: true, + category: 'lock_wait_timeout', + message: errorMessage, + }; + } + + if (RETRYABLE_DATABASE_ERROR_CODES.has(errorCode) || normalizedMessage.includes('deadlock')) { + return { + retryable: true, + category: 'deadlock', + message: errorMessage, + }; + } + } + + return { + retryable: false, + category: 'other', + message: errorMessage, + }; + } + + /** + * 将指定仓库内的源订单标记为出库超时。 + * + * @param {number} warehouseId 仓库ID。 + * @param {Array} orderIds 源订单ID列表。 + * @param {number} [queryTimeoutMs] 更新语句超时时间。 + * @return {Promise} 受影响行数。 + */ + async markOutboundOrdersTimeout(warehouseId, orderIds, queryTimeoutMs) { + const normalizedWarehouseId = Number(warehouseId); + const normalizedOrderIds = Array.from(new Set((Array.isArray(orderIds) ? orderIds : []) + .map(value => Number(value)) + .filter(value => Number.isFinite(value) && value > 0))); + + if (!Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + throw new Error('仓库ID不能为空'); + } + + if (normalizedOrderIds.length === 0) { + return 0; + } + + const orderFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; + + if (!orderFactory || typeof orderFactory.getCurrentModel !== 'function') { + throw new Error('订单工厂未初始化'); + } + + const sourceOrderModel = await orderFactory.getCurrentModel(normalizedWarehouseId); + const { Op } = this.ctx.app.Sequelize; + const updateValues = { + outbound_status: OUTBOUND_STATUS_TIMEOUT, + step: OUTBOUND_STEP, + updated_at: new Date(), + }; + const updateResult = await sourceOrderModel.update(updateValues, { + where: { + warehouse_id: normalizedWarehouseId, + id: { + [Op.in]: normalizedOrderIds, + }, + }, + ...this.buildMigrationQueryOptions(null, queryTimeoutMs), + }); + + return Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0); + } + + /** + * 构造配送表去重键。 + * + * @param {Object} row 订单行数据。 + * @return {string} 去重键。 + */ + buildDispatchKey(row) { + if (!this.isPlainObject(row)) { + return ''; + } + + const deliveryOrderCode = String(row.delivery_order_code || '').trim(); + const storeId = String(row.store_id || '').trim(); + const warehouseId = String(row.warehouse_id || '').trim(); + + if (!deliveryOrderCode || !storeId || !warehouseId) { + return ''; + } + + return `${deliveryOrderCode}::${storeId}::${warehouseId}`; + } + + /** + * 构造配送表插入行。 + * + * @param {Object} row 当前订单工作台数据。 + * @return {Object} 可写入配送表的数据。 + */ + buildDispatchRow(row) { + const payload = { + ...(row || {}), + }; + + delete payload.dispatch_lane; + + return { + ...payload, + dispatch_lane: DISPATCH_LANE, + }; + } + + /** + * 构造商品明细迁移行。 + * + * @param {Object} row 当前订单商品明细行。 + * @param {number} targetOrderId 配送表订单ID。 + * @return {Object} 可写入配送明细表的数据。 + */ + buildDispatchItemRow(row, targetOrderId) { + return { + ...(row || {}), + order_id: targetOrderId, + }; + } + + /** + * 获取订单与商品明细迁移所需的模型。 + * + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 迁移模型集合。 + */ + async getMigrationModels(warehouseId) { + const orderFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; + const itemsFactory = this.ctx.model && this.ctx.model.OrderItemsFactory; + + if (!orderFactory || typeof orderFactory.getCurrentModel !== 'function' || typeof orderFactory.getDispatchModel !== 'function') { + throw new Error('订单工厂未初始化'); + } + + if (!itemsFactory || typeof itemsFactory.getCurrentModel !== 'function' || typeof itemsFactory.getDispatchModel !== 'function') { + throw new Error('订单商品工厂未初始化'); + } + + return { + sourceOrderModel: await orderFactory.getCurrentModel(warehouseId), + targetOrderModel: await orderFactory.getDispatchModel(warehouseId), + sourceItemModel: await itemsFactory.getCurrentModel(warehouseId), + targetItemModel: await itemsFactory.getDispatchModel(warehouseId), + }; + } + + /** + * 将配送表订单行转换为订单ID映射。 + * + * @param {Array} rows 配送表订单行。 + * @return {Map} 业务键到订单ID的映射。 + */ + buildTargetOrderIdMap(rows) { + return new Map((Array.isArray(rows) ? rows : []) + .map(row => { + const key = this.buildDispatchKey(row); + const orderId = Number(row && row.id); + + if (!key || !Number.isFinite(orderId) || orderId <= 0) { + return null; + } + + return [ key, orderId ]; + }) + .filter(Boolean)); + } + + /** + * 同步指定仓库的已出库订单。 + * + * @param {number|string} warehouseId 仓库ID。 + * @param {number} [limit=1000] 单次处理数量上限。 + * @param {Object} [options] 迁移控制参数。 + * @param {Array} [options.outboundStatuses] 需要迁移的出库状态。 + * @param {number} [options.queryTimeoutMs] 单条数据库查询的超时时间。 + * @param {number} [options.executionTimeoutMs] 单仓库批次的执行超时时间。 + * @param {boolean} [options.persistTimeoutState] 失败后是否将源订单标记为出库超时。 + * @return {Promise} 同步结果。 + */ + async syncOutboundOrdersForWarehouse(warehouseId, limit = MAX_BATCH_SIZE, options = {}) { + const normalizedWarehouseId = Number(warehouseId); + + if (!Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + throw new Error('仓库ID不能为空'); + } + + const batchLimit = Math.min( + Math.max(Number(limit) || MAX_BATCH_SIZE, 1), + MAX_BATCH_SIZE + ); + const outboundStatuses = this.normalizeOutboundStatuses(options.outboundStatuses); + const queryTimeoutMs = Number(options.queryTimeoutMs); + const executionTimeoutMs = Number(options.executionTimeoutMs); + const persistTimeoutState = Boolean(options.persistTimeoutState); + const deadlineAt = Number.isFinite(executionTimeoutMs) && executionTimeoutMs > 0 + ? Date.now() + executionTimeoutMs + : 0; + const transaction = await this.ctx.model.transaction(); + const { Op } = this.ctx.app.Sequelize; + let sourceRows = []; + let selectedSourceOrderIds = []; + + const assertMigrationDeadline = stage => { + if (deadlineAt > 0 && Date.now() > deadlineAt) { + const timeoutError = new Error(`仓库 ${normalizedWarehouseId} ${stage} 执行超时`); + timeoutError.code = 'OUTBOUND_MIGRATION_TIMEOUT'; + throw timeoutError; + } + }; + + try { + assertMigrationDeadline('出库迁移'); + const { + sourceOrderModel, + targetOrderModel, + sourceItemModel, + targetItemModel, + } = await this.getMigrationModels(normalizedWarehouseId); + + assertMigrationDeadline('查询源订单'); + sourceRows = await sourceOrderModel.findAll({ + where: { + warehouse_id: normalizedWarehouseId, + outbound_status: { + [Op.in]: outboundStatuses, + }, + step: OUTBOUND_STEP, + }, + order: [[ 'id', 'ASC' ]], + limit: batchLimit, + raw: true, + ...this.buildMigrationQueryOptions(transaction, queryTimeoutMs), + }); + + selectedSourceOrderIds = Array.from(new Set((Array.isArray(sourceRows) ? sourceRows : []) + .map(row => Number(row && row.id)) + .filter(value => Number.isFinite(value) && value > 0))); + + if (!Array.isArray(sourceRows) || sourceRows.length === 0) { + await transaction.commit(); + + return { + warehouseId: normalizedWarehouseId, + selectedCount: 0, + createdCount: 0, + skippedCount: 0, + timeoutCount: 0, + }; + } + + const invalidSourceRows = sourceRows.filter(row => !this.buildDispatchKey(row)); + + if (invalidSourceRows.length > 0) { + const invalidRowIds = invalidSourceRows + .map(row => Number(row && row.id)) + .filter(value => Number.isFinite(value) && value > 0); + + throw new Error(`选中的源订单存在缺少 delivery_order_code/store_id/warehouse_id 的记录${invalidRowIds.length > 0 ? `: ${invalidRowIds.join(', ')}` : ''}`); + } + + const validSourceRows = sourceRows; + const sourceOrderRowMap = new Map(validSourceRows + .map(row => [ Number(row.id), row ]) + .filter(([ rowId, row ]) => Number.isFinite(rowId) && rowId > 0 && this.buildDispatchKey(row))); + const deliveryOrderCodes = Array.from(new Set(validSourceRows + .map(row => String(row.delivery_order_code || '').trim()) + .filter(Boolean))); + const sourceOrderIds = Array.from(sourceOrderRowMap.keys()); + + let existingRows = []; + if (deliveryOrderCodes.length > 0) { + assertMigrationDeadline('查询配送表订单'); + existingRows = await targetOrderModel.findAll({ + where: { + warehouse_id: normalizedWarehouseId, + delivery_order_code: { + [Op.in]: deliveryOrderCodes, + }, + }, + raw: true, + ...this.buildMigrationQueryOptions(transaction, queryTimeoutMs), + }); + } + + const existingKeySet = new Set((Array.isArray(existingRows) ? existingRows : []) + .map(row => this.buildDispatchKey(row)) + .filter(Boolean)); + + const rowsToCreate = validSourceRows + .filter(row => !existingKeySet.has(this.buildDispatchKey(row))) + .map(row => this.buildDispatchRow(row)); + + if (rowsToCreate.length > 0) { + assertMigrationDeadline('创建配送表订单'); + await targetOrderModel.bulkCreate(rowsToCreate, { + ...this.buildMigrationQueryOptions(transaction, queryTimeoutMs), + ignoreDuplicates: true, + }); + } + + assertMigrationDeadline('查询配送表订单'); + const targetRows = deliveryOrderCodes.length > 0 + ? await targetOrderModel.findAll({ + where: { + warehouse_id: normalizedWarehouseId, + delivery_order_code: { + [Op.in]: deliveryOrderCodes, + }, + }, + raw: true, + ...this.buildMigrationQueryOptions(transaction, queryTimeoutMs), + }) + : []; + const targetOrderIdMap = this.buildTargetOrderIdMap(targetRows); + + if (sourceOrderIds.length > 0) { + assertMigrationDeadline('查询商品明细'); + const sourceItems = await sourceItemModel.findAll({ + where: { + order_id: { + [Op.in]: sourceOrderIds, + }, + }, + order: [[ 'id', 'ASC' ]], + raw: true, + ...this.buildMigrationQueryOptions(transaction, queryTimeoutMs), + }); + + const validSourceItems = Array.isArray(sourceItems) + ? sourceItems.filter(item => Number.isFinite(Number(item && item.id))) + : []; + + const rowsToCreateItems = validSourceItems.map(item => { + const sourceOrder = sourceOrderRowMap.get(Number(item.order_id)); + const targetOrderId = targetOrderIdMap.get(this.buildDispatchKey(sourceOrder)); + + if (!Number.isFinite(targetOrderId) || targetOrderId <= 0) { + throw new Error(`无法找到订单 ${item.order_id} 对应的配送表订单ID`); + } + + return this.buildDispatchItemRow(item, targetOrderId); + }); + + if (rowsToCreateItems.length > 0) { + assertMigrationDeadline('创建商品明细'); + await targetItemModel.bulkCreate(rowsToCreateItems, { + ...this.buildMigrationQueryOptions(transaction, queryTimeoutMs), + ignoreDuplicates: true, + }); + } + + assertMigrationDeadline('删除源商品明细'); + await sourceItemModel.destroy({ + where: { + id: { + [Op.in]: validSourceItems.map(item => Number(item.id)).filter(value => Number.isFinite(value) && value > 0), + }, + }, + ...this.buildMigrationQueryOptions(transaction, queryTimeoutMs), + }); + } + + if (sourceOrderIds.length > 0) { + assertMigrationDeadline('删除源订单'); + await sourceOrderModel.destroy({ + where: { + id: { + [Op.in]: sourceOrderIds, + }, + }, + ...this.buildMigrationQueryOptions(transaction, queryTimeoutMs), + }); + } + + await transaction.commit(); + + return { + warehouseId: normalizedWarehouseId, + selectedCount: sourceRows.length, + createdCount: rowsToCreate.length, + skippedCount: sourceRows.length - rowsToCreate.length, + timeoutCount: 0, + }; + } catch (error) { + await transaction.rollback(); + + const migrationErrorInfo = this.getOutboundMigrationErrorInfo(error); + const shouldPersistTimeoutState = persistTimeoutState && migrationErrorInfo.retryable && selectedSourceOrderIds.length > 0; + + if (shouldPersistTimeoutState) { + const timeoutCount = await this.markOutboundOrdersTimeout( + normalizedWarehouseId, + selectedSourceOrderIds, + queryTimeoutMs + ); + + return { + warehouseId: normalizedWarehouseId, + selectedCount: sourceRows.length, + createdCount: 0, + skippedCount: 0, + timeoutCount, + retryableFailure: true, + retryableFailureType: migrationErrorInfo.category, + retryableFailureMessage: migrationErrorInfo.message, + }; + } + + if (migrationErrorInfo.retryable) { + return { + warehouseId: normalizedWarehouseId, + selectedCount: sourceRows.length, + createdCount: 0, + skippedCount: 0, + timeoutCount: 0, + retryableFailure: true, + retryableFailureType: migrationErrorInfo.category, + retryableFailureMessage: migrationErrorInfo.message, + }; + } + + throw error; + } + } +} + +module.exports = OrderDeliveryMigrationService; diff --git a/app/service/systems/order_outbound.js b/app/service/systems/order_outbound.js new file mode 100644 index 0000000..565a422 --- /dev/null +++ b/app/service/systems/order_outbound.js @@ -0,0 +1,89 @@ +'use strict'; + +const OrderBaseService = require('../systemMethods/order/base'); + +const OUTBOUND_STATUS = 'fin'; +const OUTBOUND_STEP = 4; + +/** + * 订单出库状态服务。 + * 仅用于内部把订单标记为出库,不对外暴露通用 method。 + */ +class OrderOutboundService extends OrderBaseService { + /** + * 将订单标记为出库。 + * + * 兼容单条与批量入参,支持 id、order_id、ids 三种订单 ID 写法。 + * 仅更新出库状态相关字段:outbound_status、step、delivery_time、updated_at。 + * + * @param {Object} data 请求体。 + * @return {Promise} 更新后的订单信息,包含出库状态与更新数量。 + */ + async markOutboundOrder(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const warehouseId = this.getWarehouseId(); + const orderIds = this.normalizeOrderIds(requestData); + + if (orderIds.length === 0) { + throw new Error('订单ID不能为空'); + } + + const model = await this.getOrderModel('order', warehouseId); + const now = new Date(); + const where = this.buildOrderWhere(orderIds, warehouseId); + const updateValues = { + outbound_status: OUTBOUND_STATUS, + step: OUTBOUND_STEP, + delivery_time: now, + updated_at: now, + }; + + const updateResult = await model.update(updateValues, { + where, + }); + + const affectedRows = Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0); + if (affectedRows <= 0) { + throw new Error('订单不存在或不属于当前仓库'); + } + + const updatedOrders = await model.findAll({ + where, + raw: true, + }); + + if (!Array.isArray(updatedOrders) || updatedOrders.length === 0) { + throw new Error('订单不存在或不属于当前仓库'); + } + + const orderMap = new Map(updatedOrders.map(order => [ Number(order.id), order ])); + const normalizedOrders = orderIds + .map(orderId => orderMap.get(orderId)) + .filter(Boolean) + .map(order => ({ + id: order.id, + outbound_status: order.outbound_status, + step: Number(order.step ?? OUTBOUND_STEP), + delivery_time: order.delivery_time, + updated_at: order.updated_at, + })); + + if (normalizedOrders.length === 0) { + throw new Error('订单不存在或不属于当前仓库'); + } + + const firstOrder = normalizedOrders[0]; + + return { + id: firstOrder.id, + outbound_status: firstOrder.outbound_status, + step: firstOrder.step, + delivery_time: firstOrder.delivery_time, + updated_at: firstOrder.updated_at, + updated_count: affectedRows, + ids: normalizedOrders.map(order => order.id), + }; + } +} + +module.exports = OrderOutboundService; diff --git a/app/service/systems/order_pending_exception.js b/app/service/systems/order_pending_exception.js new file mode 100644 index 0000000..51c5476 --- /dev/null +++ b/app/service/systems/order_pending_exception.js @@ -0,0 +1,43 @@ +'use strict'; + +const OrderBaseService = require('../systemMethods/order/base'); + +class OrderPendingExceptionService extends OrderBaseService { + /** + * 将订单标记为待处理异常。 + * + * 兼容单条与批量入参,支持 id、order_id、ids 三种订单 ID 写法。 + * 异常文本会保留在订单标记字段上,供待处理异常列表展示或追踪;审核/反审只负责状态流转,不会主动清空该字段。 + * + * @param {Object} data 请求体。 + * @return {Promise} 更新后的订单信息,包含异常文本与更新数量。 + */ + async markPendingException(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const exceptionText = String( + requestData.exception_text + ?? requestData.exception_reason + ?? requestData.remark + ?? requestData.reason + ?? '' + ).trim(); + + if (!exceptionText) { + throw new Error('异常文本不能为空'); + } + + const result = await this.updateOrderInspectionState(requestData, 'error', { + extraUpdateValues: { + order_flag: exceptionText, + }, + }); + + return { + ...result, + exception_text: exceptionText, + order_flag: exceptionText, + }; + } +} + +module.exports = OrderPendingExceptionService; diff --git a/app/service/systems/order_storage_allocation.js b/app/service/systems/order_storage_allocation.js new file mode 100644 index 0000000..7a20a5f --- /dev/null +++ b/app/service/systems/order_storage_allocation.js @@ -0,0 +1,636 @@ +'use strict'; + +const MainService = require('../main'); + +const STORAGE_STATUS_FIN = 'fin'; +const STORAGE_STATUS_ERROR = 'error'; +const ORDER_STEP_EXCEPTION = 3; + +/** + * 将输入值规范化为布尔值。 + * + * @param {unknown} value 待转换的值。 + * @param {boolean} [defaultValue=false] 空值时的默认布尔值。 + * @return {boolean} 是否为真。 + */ +function normalizeBooleanFlag(value, defaultValue = false) { + if (value === undefined || value === null || value === '') { + return defaultValue; + } + + if (typeof value === 'boolean') { + return value; + } + + if (typeof value === 'number') { + return value === 1; + } + + if (typeof value === 'string') { + return [ '1', 'Y', 'YES', 'TRUE', 'ON' ].includes(value.trim().toUpperCase()); + } + + return false; +} + +/** + * 将输入值转换为有限数字。 + * + * @param {unknown} value 待转换的值。 + * @param {number} [defaultValue=0] 默认值。 + * @return {number} 转换后的数字。 + */ +function toNumber(value, defaultValue = 0) { + const normalized = Number(value); + + return Number.isFinite(normalized) ? normalized : defaultValue; +} + +/** + * 将模型记录转换为普通对象。 + * + * @param {unknown} record 模型记录。 + * @return {Object|null} 普通对象。 + */ +function toPlainRecord(record) { + if (!record) { + return null; + } + + if (typeof record.get === 'function') { + return record.get({ plain: true }); + } + + return record; +} + +/** + * 解析日期值并返回时间戳。 + * + * @param {unknown} value 日期值。 + * @return {number} 时间戳或 Number.MAX_SAFE_INTEGER。 + */ +function toTimeValue(value) { + if (!value) { + return Number.MAX_SAFE_INTEGER; + } + + const timeValue = new Date(value).getTime(); + return Number.isFinite(timeValue) ? timeValue : Number.MAX_SAFE_INTEGER; +} + +/** + * 对可分配库存按优先级排序。 + * + * @param {Object} left 左侧库存。 + * @param {Object} right 右侧库存。 + * @param {boolean} prioritizeStorage 是否优先使用存储储位。 + * @return {number} 排序结果。 + */ +function compareStorageRows(left, right, prioritizeStorage) { + const leftPickPriority = prioritizeStorage ? (left.is_preferred_pick ? 1 : 0) : 0; + const rightPickPriority = prioritizeStorage ? (right.is_preferred_pick ? 1 : 0) : 0; + + if (leftPickPriority !== rightPickPriority) { + return leftPickPriority - rightPickPriority; + } + + const leftHasProductionDate = Boolean(left.production_date); + const rightHasProductionDate = Boolean(right.production_date); + + if (leftHasProductionDate !== rightHasProductionDate) { + return leftHasProductionDate ? -1 : 1; + } + + if (leftHasProductionDate && rightHasProductionDate) { + const productionDiff = toTimeValue(left.production_date) - toTimeValue(right.production_date); + if (productionDiff !== 0) { + return productionDiff; + } + } + + const inboundDiff = toTimeValue(left.inbound_time) - toTimeValue(right.inbound_time); + if (inboundDiff !== 0) { + return inboundDiff; + } + + return toNumber(left.id, 0) - toNumber(right.id, 0); +} + +/** + * 生成库存不足提示文本。 + * + * @param {Array} shortageItems 缺货条目。 + * @return {string} 提示文本。 + */ +function buildShortageMessage(shortageItems = []) { + const parts = shortageItems + .filter(item => item && Number(item.stock_id) > 0) + .map(item => `sku(${item.stock_id}),数量:${item.required_quantity},库位数量:${item.allocated_quantity}`); + + return parts.length > 0 ? `库存不足:${parts.join('|')}` : ''; +} + +/** + * 规范化订单 ID 列表。 + * + * @param {Object} data 请求体。 + * @return {number[]} 订单 ID 列表。 + */ +function normalizeOrderIds(data = {}) { + const requestData = data && typeof data === 'object' ? data : {}; + const rawValues = []; + + if (Array.isArray(requestData.order_ids)) { + rawValues.push(...requestData.order_ids); + } else if (Array.isArray(requestData.orderIds)) { + rawValues.push(...requestData.orderIds); + } else if (Array.isArray(requestData.ids)) { + rawValues.push(...requestData.ids); + } else if (typeof requestData.order_ids === 'string') { + rawValues.push(...requestData.order_ids.split(',')); + } else if (typeof requestData.orderIds === 'string') { + rawValues.push(...requestData.orderIds.split(',')); + } else if (typeof requestData.ids === 'string') { + rawValues.push(...requestData.ids.split(',')); + } else if (requestData.order_ids !== undefined && requestData.order_ids !== null && requestData.order_ids !== '') { + rawValues.push(requestData.order_ids); + } else if (requestData.orderIds !== undefined && requestData.orderIds !== null && requestData.orderIds !== '') { + rawValues.push(requestData.orderIds); + } else if (requestData.ids !== undefined && requestData.ids !== null && requestData.ids !== '') { + rawValues.push(requestData.ids); + } else if (requestData.order_id !== undefined && requestData.order_id !== null && requestData.order_id !== '') { + rawValues.push(requestData.order_id); + } else if (requestData.orderId !== undefined && requestData.orderId !== null && requestData.orderId !== '') { + rawValues.push(requestData.orderId); + } else if (requestData.id !== undefined && requestData.id !== null && requestData.id !== '') { + rawValues.push(requestData.id); + } + + const orderIds = rawValues + .map(value => Number(String(value).trim())) + .filter(value => Number.isFinite(value) && value > 0); + + return Array.from(new Set(orderIds)); +} + +/** + * 订单储位分配公共服务。 + * 负责订单、库存、库位的分配编排,并写入 wms_picking。 + */ +class OrderStorageAllocationService extends MainService { + /** + * 按订单批量分配储位。 + * + * 入参支持以下字段: + * - `allow_storage_location` / `allowStorageLocation` / `is_allow_storage` / `isAllowStorage` + * - `order_ids` / `orderIds` / `ids` / `order_id` / `orderId` / `id` + * - `warehouse_id` / `warehouseId`(可选,默认使用当前上下文仓库) + * + * 分配规则: + * - 先过滤掉已经完成储位分配的订单 + * - 允许时优先使用存储储位,再使用分拣储位 + * - FIFO 先按生产日期,再按入库时间 + * - 库存不足时按订单顺序尽量分配,并将不足订单标记为异常 + * + * @param {Object} data 请求体。 + * @return {Promise} 分配结果。 + */ + async allocatePicking(data = {}) { + const { ctx, app } = this; + const requestData = this.isPlainObject(data) ? data : {}; + const warehouseId = toNumber(requestData.warehouse_id ?? requestData.warehouseId ?? ctx.user?.store_id, 0); + const orderIds = normalizeOrderIds(requestData); + const allowStorageLocation = normalizeBooleanFlag( + requestData.allow_storage_location + ?? requestData.allowStorageLocation + ?? requestData.is_allow_storage + ?? requestData.isAllowStorage + ); + + if (warehouseId <= 0) { + return { + code: 400, + message: '缺少仓库上下文', + data: null, + }; + } + + if (orderIds.length === 0) { + return { + code: 400, + message: '订单ID不能为空', + data: null, + }; + } + + const transaction = await ctx.model.transaction(); + const { Op } = app.Sequelize; + const now = new Date(); + + try { + const orderModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); + const orderItemModel = await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId); + const pickingModel = ctx.model.Picking; + + if (!pickingModel || typeof pickingModel.bulkCreate !== 'function') { + throw new Error('wms_picking 模型不可用'); + } + + const orderRows = await orderModel.findAll({ + where: { + id: { + [Op.in]: orderIds, + }, + warehouse_id: warehouseId, + }, + transaction, + lock: transaction.LOCK.UPDATE, + raw: true, + }); + + const orderMap = new Map(); + for (const orderRow of Array.isArray(orderRows) ? orderRows : []) { + const plainOrder = toPlainRecord(orderRow); + if (!plainOrder || !Number(plainOrder.id)) { + continue; + } + + orderMap.set(Number(plainOrder.id), plainOrder); + } + + const pendingOrderIds = []; + const skippedOrders = []; + + for (const orderId of orderIds) { + const orderRow = orderMap.get(orderId); + + if (!orderRow) { + skippedOrders.push({ + order_id: orderId, + status: 'skipped', + skipped_reason: 'not_found', + }); + continue; + } + + if (String(orderRow.storage_status || 'none') === STORAGE_STATUS_FIN) { + skippedOrders.push({ + order_id: orderId, + status: 'skipped', + storage_status: orderRow.storage_status, + skipped_reason: 'already_allocated', + }); + continue; + } + + pendingOrderIds.push(orderId); + } + + if (pendingOrderIds.length === 0) { + await transaction.commit(); + return { + code: 200, + message: '没有需要分配的订单', + data: { + warehouse_id: warehouseId, + allow_storage_location: allowStorageLocation, + requested_order_ids: orderIds, + pending_order_ids: [], + skipped_orders: skippedOrders, + orders: skippedOrders, + picking_count: 0, + }, + }; + } + + const orderItemRows = await orderItemModel.findAll({ + where: { + order_id: { + [Op.in]: pendingOrderIds, + }, + }, + transaction, + lock: transaction.LOCK.UPDATE, + raw: true, + }); + + const orderItemsByOrderId = new Map(); + const stockIdSet = new Set(); + + for (const orderItemRow of Array.isArray(orderItemRows) ? orderItemRows : []) { + const plainItem = toPlainRecord(orderItemRow); + if (!plainItem || !Number(plainItem.order_id)) { + continue; + } + + const orderId = Number(plainItem.order_id); + const orderItems = orderItemsByOrderId.get(orderId) || []; + orderItems.push(plainItem); + orderItemsByOrderId.set(orderId, orderItems); + + const stockId = Number(plainItem.stock_id || 0); + if (stockId > 0) { + stockIdSet.add(stockId); + } + } + + const stockIds = Array.from(stockIdSet); + if (stockIds.length > 0) { + await ctx.model.StockWarehouse.findAll({ + where: { + id: { + [Op.in]: stockIds, + }, + warehouse_id: warehouseId, + is_valid: 'Y', + deleted_at: null, + }, + transaction, + lock: transaction.LOCK.UPDATE, + raw: true, + }); + } + + const storageRows = stockIds.length > 0 + ? await ctx.model.Storage.findAll({ + where: { + warehouse_id: warehouseId, + stock_id: { + [Op.in]: stockIds, + }, + is_enabled: 1, + delete_at: null, + available_quantity: { + [Op.gt]: 0, + }, + }, + include: [ + { + model: ctx.model.LocationSpace, + as: 'space', + required: true, + attributes: [ 'id', 'space_code', 'custom_name', 'is_preferred_pick', 'pick_sequence', 'pick_priority' ], + include: [ + { + model: ctx.model.LocationType, + as: 'locationType', + required: true, + attributes: [ 'id', 'type_code', 'type_name', 'allow_allocation', 'is_active' ], + where: { + allow_allocation: 1, + is_active: 1, + }, + }, + ], + }, + ], + transaction, + lock: transaction.LOCK.UPDATE, + order: [[ 'id', 'ASC' ]], + }) + : []; + + const storageRowsByStockId = new Map(); + for (const storageRow of Array.isArray(storageRows) ? storageRows : []) { + const plainStorage = toPlainRecord(storageRow); + if (!plainStorage || !Number(plainStorage.id) || !Number(plainStorage.stock_id)) { + continue; + } + + const space = toPlainRecord(plainStorage.space) || {}; + const locationType = toPlainRecord(space.locationType) || {}; + const normalizedStorage = { + ...plainStorage, + quantity: toNumber(plainStorage.quantity, 0), + locked_quantity: toNumber(plainStorage.locked_quantity, 0), + available_quantity: toNumber(plainStorage.available_quantity, 0), + production_date: plainStorage.production_date || null, + inbound_time: plainStorage.inbound_time || null, + space, + locationType, + space_name: String(space.custom_name || space.space_code || '').trim(), + is_preferred_pick: normalizeBooleanFlag(space.is_preferred_pick), + }; + + const stockId = Number(normalizedStorage.stock_id); + const currentStorageRows = storageRowsByStockId.get(stockId) || []; + currentStorageRows.push(normalizedStorage); + storageRowsByStockId.set(stockId, currentStorageRows); + } + + const policyCache = new Map(); + const pickingRows = []; + const stockAllocationMap = new Map(); + const storageAllocationMap = new Map(); + const orderResults = []; + + for (const orderId of pendingOrderIds) { + const orderRow = orderMap.get(orderId); + if (!orderRow) { + continue; + } + + const orderItems = (orderItemsByOrderId.get(orderId) || []) + .slice() + .sort((left, right) => { + const leftLineNo = toNumber(left.order_line_no, 0); + const rightLineNo = toNumber(right.order_line_no, 0); + + if (leftLineNo !== rightLineNo) { + return leftLineNo - rightLineNo; + } + + return toNumber(left.id, 0) - toNumber(right.id, 0); + }); + + const shortageItems = []; + let allocatedQuantityForOrder = 0; + + for (const orderItem of orderItems) { + const stockId = toNumber(orderItem.stock_id, 0); + const requiredQuantity = toNumber(orderItem.plan_qty ?? orderItem.planQty ?? orderItem.count ?? 0, 0); + + if (stockId <= 0 || requiredQuantity <= 0) { + shortageItems.push({ + stock_id: stockId, + required_quantity: requiredQuantity > 0 ? requiredQuantity : 0, + allocated_quantity: 0, + }); + continue; + } + + const policyEntry = policyCache.has(stockId) + ? policyCache.get(stockId) + : await ctx.service.systems.stockStore.getStoreWarehousePolicyConfigByStockId(stockId, transaction); + policyCache.set(stockId, policyEntry); + + const storageSeparationEnabled = normalizeBooleanFlag(policyEntry?.policyConfig?.storage_separation, true); + const allowStorageSpace = allowStorageLocation || !storageSeparationEnabled; + + const candidateStorageRows = (storageRowsByStockId.get(stockId) || []) + .filter(storageRow => allowStorageSpace || storageRow.is_preferred_pick) + .slice() + .sort((left, right) => compareStorageRows(left, right, allowStorageSpace)); + + let remainingQuantity = requiredQuantity; + let allocatedQuantityForItem = 0; + + for (const storageRow of candidateStorageRows) { + if (remainingQuantity <= 0) { + break; + } + + const currentAvailable = toNumber(storageRow.available_quantity, 0); + if (currentAvailable <= 0) { + continue; + } + + const allocationQuantity = Math.min(remainingQuantity, currentAvailable); + if (allocationQuantity <= 0) { + continue; + } + + await ctx.service.systems.storage.lockQuantity(storageRow.id, allocationQuantity, { transaction }); + + storageRow.available_quantity = currentAvailable - allocationQuantity; + storageRow.locked_quantity = toNumber(storageRow.locked_quantity, 0) + allocationQuantity; + remainingQuantity -= allocationQuantity; + allocatedQuantityForItem += allocationQuantity; + allocatedQuantityForOrder += allocationQuantity; + + storageAllocationMap.set(storageRow.id, (storageAllocationMap.get(storageRow.id) || 0) + allocationQuantity); + stockAllocationMap.set(stockId, (stockAllocationMap.get(stockId) || 0) + allocationQuantity); + + pickingRows.push({ + order_id: orderId, + order_item_id: toNumber(orderItem.id, 0), + storage_id: storageRow.id, + quantity: allocationQuantity, + space_id: toNumber(storageRow.space_id, 0) || null, + space_name: String(storageRow.space_name || '').trim(), + status: 'pending', + created_at: now, + updated_at: now, + }); + } + + if (remainingQuantity > 0) { + shortageItems.push({ + stock_id: stockId, + required_quantity: requiredQuantity, + allocated_quantity: allocatedQuantityForItem, + }); + } + } + + const shortageMessage = buildShortageMessage(shortageItems); + const orderUpdateValues = shortageMessage + ? { + storage_status: STORAGE_STATUS_ERROR, + step: ORDER_STEP_EXCEPTION, + order_flag: shortageMessage, + updated_at: now, + } + : { + storage_status: STORAGE_STATUS_FIN, + order_flag: '', + updated_at: now, + }; + + await orderModel.update(orderUpdateValues, { + where: { + id: orderId, + warehouse_id: warehouseId, + }, + transaction, + }); + + orderResults.push({ + order_id: orderId, + storage_status: orderUpdateValues.storage_status, + allocated_quantity: allocatedQuantityForOrder, + shortage_message: shortageMessage || '', + status: shortageMessage ? 'error' : 'success', + }); + } + + for (const [ stockId, quantity ] of stockAllocationMap.entries()) { + if (quantity <= 0) { + continue; + } + + const stockRecord = await ctx.model.StockWarehouse.findByPk(stockId, { + transaction, + }); + + if (!stockRecord) { + throw new Error(`库存主记录不存在: ${stockId}`); + } + + await stockRecord.increment('locked_quantity', { + by: quantity, + transaction, + silent: true, + }); + await stockRecord.reload({ transaction }); + } + + if (pickingRows.length > 0) { + await pickingModel.bulkCreate(pickingRows, { + transaction, + }); + } + + await transaction.commit(); + + const errorOrderResults = orderResults.filter(item => item.status === 'error'); + const successOrderResults = orderResults.filter(item => item.status === 'success'); + const shortageMessages = errorOrderResults + .map(item => item.shortage_message) + .filter(Boolean); + + return { + code: 200, + message: shortageMessages.length > 0 + ? '储位分配完成,部分订单库存不足' + : '储位分配完成', + data: { + warehouse_id: warehouseId, + allow_storage_location: allowStorageLocation, + requested_order_ids: orderIds, + pending_order_ids: pendingOrderIds, + allocated_order_ids: successOrderResults.map(item => item.order_id), + shortage_order_ids: errorOrderResults.map(item => item.order_id), + skipped_orders: skippedOrders, + orders: [ ...skippedOrders, ...orderResults ], + picking_count: pickingRows.length, + stock_lock_summary: Array.from(stockAllocationMap.entries()).map(([ stockId, quantity ]) => ({ + stock_id: stockId, + locked_quantity: quantity, + })), + storage_lock_summary: Array.from(storageAllocationMap.entries()).map(([ storageId, quantity ]) => ({ + storage_id: storageId, + locked_quantity: quantity, + })), + shortage_messages: shortageMessages, + }, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + /** + * 兼容旧调用名称的储位分配入口。 + * + * @param {Object} data 请求体。 + * @return {Promise} 分配结果。 + */ + async allocateStorage(data = {}) { + return await this.allocatePicking(data); + } +} + +module.exports = OrderStorageAllocationService; diff --git a/app/service/systems/platform.js b/app/service/systems/platform.js index fe5337d..5a2fc66 100644 --- a/app/service/systems/platform.js +++ b/app/service/systems/platform.js @@ -1,7 +1,267 @@ // app/service/system/platform.js const Service = require('egg').Service; +const DEFAULT_PLATFORM_LIST_CACHE_TTL_SECONDS = 600; + class PlatformService extends Service { + /** + * 获取当前上下文中的仓库ID。 + * + * @return {number} 仓库ID,未获取到时返回 0。 + */ + getCurrentWarehouseId() { + const warehouseId = Number(this.ctx && this.ctx.user && this.ctx.user.store_id || 0); + + if (Number.isFinite(warehouseId) && warehouseId > 0) { + return warehouseId; + } + + return 0; + } + + /** + * 生成平台列表缓存键。 + * + * @param {number|string} warehouseId 仓库ID。 + * @return {string} 缓存键。 + */ + getPlatformListCacheKey(warehouseId = 0) { + const normalizedWarehouseId = Number(warehouseId || 0); + + if (Number.isFinite(normalizedWarehouseId) && normalizedWarehouseId > 0) { + return `platform:list:${normalizedWarehouseId}`; + } + + return 'platform:list'; + } + + /** + * 生成平台设置项展示名称。 + * + * @param {string} settingCode 平台设置编码。 + * @param {Object} platformItem 系统平台项。 + * @return {string} 展示名称。 + */ + buildMergedPlatformLabel(settingCode, platformItem) { + const normalizedSettingCode = String(settingCode || '').trim(); + const platformName = String(platformItem && (platformItem.name || platformItem.label || platformItem.code || platformItem.value) || '').trim(); + + if (!normalizedSettingCode) { + return platformName; + } + + if (!platformName) { + return normalizedSettingCode; + } + + return `${normalizedSettingCode} (${platformName})`; + } + + /** + * 规范化系统平台记录。 + * + * @param {Object} row 数据库记录。 + * @return {Object|null} 规范化后的记录。 + */ + normalizePlatformRow(row) { + if (!row || typeof row !== 'object') { + return null; + } + + const code = String(row.code || '').trim(); + if (!code) { + return null; + } + + const name = String(row.name || '').trim(); + const defaultExpressInterface = String(row.default_express_interface || '').trim(); + + return { + code, + name, + default_express_interface: defaultExpressInterface, + value: code, + label: name || code, + platform_code: code, + platform_name: name, + is_system_setting: false, + }; + } + + /** + * 从数据库加载当前仓库的平台设置列表。 + * + * @param {number|string} warehouseId 仓库ID。 + * @return {Promise} 平台设置列表。 + */ + async loadPlatformSettingListFromDatabase(warehouseId = 0) { + const normalizedWarehouseId = Number(warehouseId || 0); + if (!Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + return []; + } + + const platformSettingModel = this.ctx.model && this.ctx.model.PlatformSetting; + if (!platformSettingModel || typeof platformSettingModel.findAll !== 'function') { + return []; + } + + const rows = await platformSettingModel.findAll({ + attributes: [ 'id', 'code', 'platform_code', 'warehouse_id' ], + where: { + warehouse_id: normalizedWarehouseId, + }, + order: [[ 'code', 'ASC' ]], + raw: true, + }); + + if (!Array.isArray(rows)) { + return []; + } + + return rows; + } + + /** + * 规范化平台设置记录。 + * + * @param {Object} row 数据库记录。 + * @param {Map} platformMap 系统平台映射。 + * @return {Object|null} 规范化后的记录。 + */ + normalizePlatformSettingRow(row, platformMap) { + if (!row || typeof row !== 'object') { + return null; + } + + const code = String(row.code || '').trim(); + if (!code) { + return null; + } + + const platformCode = String(row.platform_code || '').trim(); + const platformItem = platformMap instanceof Map ? platformMap.get(platformCode) : null; + const label = this.buildMergedPlatformLabel(code, platformItem); + + return { + code, + name: label, + value: code, + label, + is_system_setting: true, + id: row.id === undefined || row.id === null ? null : row.id, + alias: '', + platform_code: String((platformItem && (platformItem.code || platformItem.value)) || platformCode || '').trim(), + platform_name: String((platformItem && (platformItem.name || platformItem.label || platformItem.value)) || '').trim(), + default_express_interface: String((platformItem && platformItem.default_express_interface) || '').trim(), + }; + } + + /** + * 合并基础平台列表和平台设置列表。 + * + * @param {Array} platformList 系统平台列表。 + * @param {Array} platformSettingList 平台设置列表。 + * @return {Array} 合并后的平台列表。 + */ + buildMergedPlatformList(platformList, platformSettingList) { + const mergedList = []; + const seenCodeMap = new Set(); + const normalizedPlatformList = Array.isArray(platformList) ? platformList : []; + const platformMap = new Map(); + + for (const platformItem of normalizedPlatformList) { + if (!platformItem || typeof platformItem !== 'object') { + continue; + } + + const code = String(platformItem.code || platformItem.value || '').trim(); + if (!code) { + continue; + } + + if (!platformMap.has(code)) { + platformMap.set(code, platformItem); + } + } + + for (const platformItem of normalizedPlatformList) { + if (!platformItem || typeof platformItem !== 'object') { + continue; + } + + const code = String(platformItem.code || platformItem.value || '').trim(); + if (!code || seenCodeMap.has(code)) { + continue; + } + + mergedList.push(platformItem); + seenCodeMap.add(code); + } + + for (const row of Array.isArray(platformSettingList) ? platformSettingList : []) { + const mergedItem = this.normalizePlatformSettingRow(row, platformMap); + if (!mergedItem || seenCodeMap.has(mergedItem.code)) { + continue; + } + + mergedList.push(mergedItem); + seenCodeMap.add(mergedItem.code); + } + + return mergedList; + } + + async loadPlatformListFromDatabase() { + const rows = await this.ctx.model.Platform.findAll({ + attributes: [ 'code', 'name', 'default_express_interface' ], + order: [[ 'code', 'ASC' ]], + raw: true, + }); + + if (!Array.isArray(rows)) { + return []; + } + + return rows + .map(row => this.normalizePlatformRow(row)) + .filter(Boolean); + } + + /** + * 获取平台列表。 + * + * 先读取系统平台,再按当前仓库合并平台设置;同一编码只保留一条记录。 + * + * @return {Promise} 平台列表。 + */ + async getPlatformList() { + const warehouseId = this.getCurrentWarehouseId(); + const cacheKey = this.getPlatformListCacheKey(warehouseId); + + try { + const cachedList = await this.app.getCacheAsync(cacheKey); + if (cachedList !== null && cachedList !== undefined) { + return Array.isArray(cachedList) ? cachedList : []; + } + + const [ platformList, platformSettingList ] = await Promise.all([ + this.loadPlatformListFromDatabase(), + this.loadPlatformSettingListFromDatabase(warehouseId), + ]); + + const mergedList = this.buildMergedPlatformList(platformList, platformSettingList); + await this.app.setCacheAsync(cacheKey, mergedList, DEFAULT_PLATFORM_LIST_CACHE_TTL_SECONDS); + + return mergedList; + } catch (error) { + this.ctx.logger.error('[PlatformService.getPlatformList] 获取平台列表失败', { + error: error.message, + stack: error.stack, + }); + throw error; + } + } + /** * 检查平台是否存在 * 逻辑: diff --git a/app/service/systems/polo_api.js b/app/service/systems/polo_api.js index af7289f..8f04032 100644 --- a/app/service/systems/polo_api.js +++ b/app/service/systems/polo_api.js @@ -1,198 +1,176 @@ 'use strict'; const Service = require('egg').Service; -const poloApiConfig = require('../../../config/poloapi'); - -const crypto = require('crypto'); +const PoloApiClient = require('../../lib/polo_api_client'); class PoloApiService extends Service { + /** + * @param {object} ctx - Egg 上下文对象。 + */ constructor(ctx) { super(ctx); - this.configPoloApi = poloApiConfig; + this.client = new PoloApiClient(ctx); } - // 批量组装订单JSON - getJsonDatas(expressConfig, list) { - const cal = new Date(); - const year = cal.getFullYear(); - const month = cal.getMonth() + 1; - const day = cal.getDate() + 3; - const day1 = cal.getDate() + 4; - const sb1 = this._formatPickupDate(year, month, day); - const sb2 = this._formatPickupDate(year, month, day1); + /** + * 测试 Polo API 请求并返回请求结果。 + * + * @param platid + * @return {Promise} request() 的返回结果。 + */ + 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', + }, + }); + } + /** + * 快手取号。 + * + * @param {object} [options={}] - 快手取号入参。 + * @param {string} [options.express_id=''] - 快手平台对应的承运商编码。 + * @param {object} [options.wmsOrder={}] - WMS 订单信息。 + * @param {object} [options.expressConfig={}] - 发件方与店铺配置。 + * @return {Promise} 接口响应 data。 + */ + async kuaishou(options = {}) { + const { + express_id = '', + wmsOrder = {}, + expressConfig = {}, + } = options; + const { + sourceId = '', + sourceOrderCode = '', + postcode = '', + wareHouseId = 0, + storeId = 0, + items = '', + goodsCount = 0, + orderWeight = 0, + address = '', + name = '', + expAreaName = '', + cityName = '', + province = '', + tempMobile = '', + tel = '', + } = wmsOrder; + const { + storeName = '', + address: senderAddress = '', + senderName = '', + districtName = '', + cityName: senderCityName = '', + senderTel = '', + provinceName = '', + siteCode = '', + clientId = '', + } = expressConfig; - const orders = []; - for (const wmsOrder of list) { - let txLogisticID = wmsOrder.sourceId; - txLogisticID = txLogisticID.length < 6 ? txLogisticID.padStart(6, '0') : txLogisticID; - if (wmsOrder.postcode === 'p10') { - if (txLogisticID.length > 19) txLogisticID = txLogisticID.slice(-19); - } else { - if (txLogisticID.length > 28) txLogisticID = txLogisticID.slice(-28); + const platid = 556; + const method = 'Differ.JH.Logistics.PostOrder'; + const shoptype = 'JH_001'; + const sourceIdText = String(sourceId || ''); + const sourceOrderCodeText = String(sourceOrderCode || ''); + const [ senderArea = '', senderTown = '' ] = String(districtName || '').split(';'); + const mobile = tempMobile || tel || ''; + const cpcode = express_id || ''; + const txLogisticID = sourceIdText.replace(/_/g, ''); + let cnname = ''; + + if (!(wareHouseId === 5400 || storeId === 58303)) { + const firstItem = String(items || '').split('|')[0] || ''; + const itemFields = firstItem.split(','); + if (itemFields.length > 2) { + cnname = itemFields[2]; } - txLogisticID = txLogisticID.replace(/_/g, ''); - - // 快递公司代码 - const cpcode = this.configPoloApi.postCodeMap[wmsOrder.postcode] || ''; - - // 商品名 - let cnname = ''; - const ycflag = !(wmsOrder.wareHouseId === 5400 || wmsOrder.storeId === 58303); - if (ycflag) { - const items = wmsOrder.items || ''; - const splitStr = items.split('|'); - if (splitStr.length > 0) { - const s = splitStr[0]; - const sArr = s.split(','); - if (sArr.length > 2) cnname = sArr[2]; - } - } else { - cnname = 'sp'; - } - - // 收件人手机号 - const mobile = wmsOrder.tempMobile || wmsOrder.tel || ''; - - /* - order对象结构(41-77): - { - businessplat, ismultiplepieces, businesstype, cpcode, customercode, customername, - goods: [goods对象结构(49-56)], - logisticsproductname, logistictype, mainsubpaymode, needencrypt, numpackage, - orderno, ordersource, ordertype, plattradeno, ProviderID, providercode, - receiver: receiver对象结构(59-65), sender: sender对象结构(66-75), shipperno, sitecode, Inputsite, transtype - } - goods对象结构(49-56): - { - cnname, count, unit, currencytype, Unit, weight, price - } - receiver对象结构(59-65): - { - address, name, area, city, mobile, province - } - sender对象结构(66-75): - { - country, Company, address, name, area, town, city, phone, mobile, tel, province - } - */ - // 组装订单对象(下标范围:约第41-77行) - const order = { // [order对象开始 41] - businessplat: 'OTHERS', // 41 - ismultiplepieces: '0', - businesstype: 'JH_Normal', - cpcode, - customercode: '', - customername: expressConfig.storeProperty || '测试', - goods: [{ // [goods对象开始 49] - cnname, - count: String(wmsOrder.goodsCount), - unit: '属性', - currencytype: 'CNY', - Unit: '', - weight: String(wmsOrder.orderWeight), - price: '0.0', - }], // [goods对象结束 56] - logisticsproductname: 'JH_02', - logistictype: cpcode, - mainsubpaymode: '1', - needencrypt: '1', - numpackage: '1', - orderno: wmsOrder.sourceOrderCode || (wmsOrder.id && wmsOrder.id.length > 13 ? wmsOrder.id.substring(0, 14) : wmsOrder.id), - ordersource: 'KUAI_SHOU', - ordertype: 'JH_Normal', - plattradeno: wmsOrder.sourceOrderCode || txLogisticID, - ProviderID: wmsOrder.postcode === 'p03' ? 1327 : (wmsOrder.postcode === 'p04' ? 1499 : ''), - providercode: cpcode, - receiver: { // [receiver对象开始 59] - address: wmsOrder.address, - name: wmsOrder.name, - area: wmsOrder.expAreaName, - city: wmsOrder.cityName, - mobile, - province: wmsOrder.province, - }, // [receiver对象结束 65] - sender: { // [sender对象开始 66] - country: 'CN', - Company: expressConfig.storeName, - address: expressConfig.address, - name: expressConfig.senderName, - area: expressConfig.districtName && expressConfig.districtName.indexOf(';') === -1 ? expressConfig.districtName : expressConfig.districtName.split(';')[0], - town: expressConfig.districtName && expressConfig.districtName.indexOf(';') !== -1 ? expressConfig.districtName.split(';')[1] : undefined, - city: expressConfig.cityName, - phone: expressConfig.senderTel, - mobile: expressConfig.senderTel, - tel: expressConfig.senderTel, - province: expressConfig.provinceName, - }, // [sender对象结束 75] - shipperno: [ 'p22', 'p35', 'p10' ].includes(wmsOrder.postcode) ? expressConfig.siteCode : expressConfig.clientId, - sitecode: expressConfig.siteCode || '', - Inputsite: expressConfig.siteCode || '', - transtype: '0', - // 省略部分特殊字段和extraInfo,后续可补充 - }; // [order对象结束 77] - // 特殊字段 - if (wmsOrder.postcode === 'p10') { - order.pickUpDate = sb1; - order.pickUpEndDate = sb2; - } - orders.push(order); + } else { + cnname = 'sp'; } - const body = JSON.stringify({ orders, shoptype: 'JH_001' }); - - // 组装url参数 - const urlParams = { - method: 'Differ.JH.Logistics.PostOrder', - appkey: this.configPoloApi.appKey, - token: expressConfig.sessionKey, - platid: this.configPoloApi.platid, - version: this.configPoloApi.version, - bizcontent: encodeURIComponent(body), - contenttype: this.configPoloApi.contenttype, - timestamp: encodeURIComponent(this._formatDate(new Date())), + const order = { + businessplat: 'OTHERS', + ismultiplepieces: '0', + businesstype: 'JH_Normal', + cpcode, + customercode: '', + customername: storeName || '测试', + goods: [{ + cnname, + count: String(goodsCount), + unit: '属性', + currencytype: 'CNY', + Unit: '', + weight: String(orderWeight), + price: '0.0', + }], + logisticsproductname: 'JH_02', + logistictype: cpcode, + mainsubpaymode: '1', + needencrypt: '1', + numpackage: '1', + orderno: sourceOrderCodeText || (sourceIdText.length > 13 ? sourceIdText.substring(0, 14) : sourceIdText), + ordersource: 'KUAI_SHOU', + ordertype: 'JH_Normal', + plattradeno: sourceOrderCodeText || txLogisticID, + ProviderID: postcode === 'p03' ? 1327 : (postcode === 'p04' ? 1499 : ''), + providercode: cpcode, + receiver: { + address, + name, + area: expAreaName, + city: cityName, + mobile, + province, + }, + sender: { + country: 'CN', + Company: storeName, + address: senderAddress, + name: senderName, + area: senderArea, + town: senderTown, + city: senderCityName, + phone: senderTel, + mobile: senderTel, + tel: senderTel, + province: provinceName, + }, + shipperno: [ 'p22', 'p35', 'p10' ].includes(postcode) ? siteCode : clientId, + sitecode: siteCode || '', + Inputsite: siteCode || '', + transtype: '0', }; - // 签名 - const signMap = { ...urlParams, bizcontent: body, timestamp: this._formatDate(new Date()) }; - const signText = this.getSignText(signMap, this.configPoloApi.appSecret); - urlParams.sign = this.md5Encrypt(signText.toLowerCase(), 'utf8'); - // 返回请求体和参数 - return { body, urlParams }; - } + if (postcode === 'p10') { + const pickupDate = new Date(); + pickupDate.setDate(pickupDate.getDate() + 3); + const pickupEndDate = new Date(); + pickupEndDate.setDate(pickupEndDate.getDate() + 4); + const pad = value => (value < 10 ? `0${value}` : String(value)); + order.pickUpDate = `${pickupDate.getFullYear()}-${pad(pickupDate.getMonth() + 1)}-${pad(pickupDate.getDate())} 18:00:00`; + order.pickUpEndDate = `${pickupEndDate.getFullYear()}-${pad(pickupEndDate.getMonth() + 1)}-${pad(pickupEndDate.getDate())} 18:00:00`; + } - // 单个订单JSON(略,结构同上,建议复用 getJsonDatas 逻辑) - getJsonData(expressConfig, wmsOrder) { - // 可根据 type 判断调用 getJsonDatas 或单独组装 - return this.getJsonDatas(expressConfig, [ wmsOrder ]); - } - - // 生成签名字符串 - getSignText(signMap, secret) { - let sb = '' + secret; - Object.keys(signMap).sort().forEach(key => { - sb += key + signMap[key]; + return this.client.request({ + method, + platid, + bizcontent: { + orders: [ order ], + shoptype, + }, }); - sb += secret; - return sb; - } - - // MD5加密 - md5Encrypt(text, encoding = 'utf8') { - return crypto.createHash('md5').update(text, encoding).digest('hex'); - } - - // 工具:格式化日期 - _formatDate(date) { - // 仅支持 yyyy-MM-dd HH:mm:ss - const pad = n => (n < 10 ? '0' + n : n); - return date.getFullYear() + '-' + pad(date.getMonth() + 1) + '-' + pad(date.getDate()) + ' ' - + pad(date.getHours()) + ':' + pad(date.getMinutes()) + ':' + pad(date.getSeconds()); - } - - // 工具:组装取件日期 - _formatPickupDate(year, month, day) { - const pad = n => (n < 10 ? '0' + n : n); - return `${year}-${pad(month)}-${pad(day)} 18:00:00`; } } diff --git a/app/service/systems/qimen_query.js b/app/service/systems/qimen_query.js index 602932e..38c7f2c 100644 --- a/app/service/systems/qimen_query.js +++ b/app/service/systems/qimen_query.js @@ -86,11 +86,24 @@ class QimenQueryService extends Service { const separator = baseUrl.includes('?') ? '&' : '?'; return `${baseUrl}${separator}${queryString}`; } - async sendRequest(url, requestData) { + /** + * 发送奇门请求并在成功或失败时落库日志。 + * @param {string} url 请求地址。 + * @param {string} requestData 请求报文。 + * @param {Object} [logData={}] 日志基础数据。 + * @return {Promise<{queryId: *, res: string}>} 请求结果。 + */ + async sendRequest(url, requestData, logData = {}) { const startTime = Date.now(); const { service } = this; - const logData = {}; - logData.body = requestData; + const requestLogData = Object.assign({ + body: requestData, + result: '', + log_id: this.ctx.qimenLogId || null, + }, logData); + requestLogData.body = requestLogData.body || requestData; + requestLogData.result = requestLogData.result || ''; + requestLogData.log_id = requestLogData.log_id || this.ctx.qimenLogId || null; let httpquery = null; if (url.indexOf('https://') > -1) { httpquery = https; @@ -117,6 +130,8 @@ class QimenQueryService extends Service { throw new Error('XML内容为空'); } } catch (error) { + requestLogData.result = error.stack || `${error.name || 'Error'}: ${error.message || String(error)}`; + await service.qimen.saveQimenLog(requestLogData, startTime); throw error; } const header = { @@ -128,26 +143,39 @@ class QimenQueryService extends Service { method: 'POST', headers: header, }; - const res = await new Promise((resolve, reject) => { - const req = httpquery.request(url, options, response => { - let datas = ''; - response.on('data', chunk => { - datas += chunk; - }); - response.on('end', () => { - resolve(datas); - }); - }); + let res; + try { + res = await new Promise((resolve, reject) => { + let req; + try { + req = httpquery.request(url, options, response => { + let datas = ''; + response.on('data', chunk => { + datas += chunk; + }); + response.on('end', () => { + resolve(datas); + }); + }); + } catch (error) { + reject(error); + return; + } - req.on('error', error => { - reject(error); - }); + req.on('error', error => { + reject(error); + }); - req.write(requestXml); - req.end(); - }); - logData.result = res; - const queryId = await service.qimen.saveQimenLog(logData, startTime); + req.write(requestXml); + req.end(); + }); + } catch (error) { + requestLogData.result = error.stack || `${error.name || 'Error'}: ${error.message || String(error)}`; + await service.qimen.saveQimenLog(requestLogData, startTime); + throw error; + } + requestLogData.result = res; + const queryId = await service.qimen.saveQimenLog(requestLogData, startTime); return { queryId, res }; } } diff --git a/app/service/systems/setting/express.js b/app/service/systems/setting/express.js new file mode 100644 index 0000000..fcf1820 --- /dev/null +++ b/app/service/systems/setting/express.js @@ -0,0 +1,530 @@ +'use strict'; + +const Service = require('egg').Service; +const { parseWhereConditions } = require('../../../lib/query_condition_parser'); + +class SettingExpressService extends Service { + /** + * 创建业务错误对象。 + * + * @param {string} message 错误信息 + * @param {number} [code=500] 错误码 + * @return {Error} 错误对象 + */ + createError(message, code = 500) { + const error = new Error(message); + error.code = code; + return error; + } + + /** + * 获取当前仓库主体ID。 + * + * @return {number} 当前仓库主体ID + */ + getCurrentStoreId() { + const storeId = Number(this.ctx.user && this.ctx.user.store_id); + if (!Number.isFinite(storeId) || storeId <= 0) { + throw this.createError('未识别到当前主体,无法操作快递映射', 400); + } + return storeId; + } + + /** + * 规范化文本值。 + * + * @param {string} value 原始值 + * @param {string} fieldName 字段名称 + * @param {number} [maxLength=255] 最大长度 + * @return {string} 规范化后的文本 + */ + normalizeText(value, fieldName, maxLength = 255) { + if (value === undefined || value === null) { + return ''; + } + + const normalized = String(value).trim(); + if (normalized.length > maxLength) { + throw this.createError(`${fieldName} 长度不能超过 ${maxLength}`, 400); + } + return normalized; + } + + /** + * 规范化编码值。 + * + * @param {string} value 原始值 + * @param {string} [fieldName='code'] 字段名称 + * @param {number} [maxLength=50] 最大长度 + * @return {string} 规范化后的编码 + */ + normalizeCode(value, fieldName = 'code', maxLength = 50) { + return this.normalizeText(value, fieldName, maxLength).toUpperCase(); + } + + /** + * 规范化分页参数。 + * + * @param {number|string} value 原始值 + * @param {string} fieldName 字段名称 + * @param {number} defaultValue 默认值 + * @param {number} maxValue 最大值 + * @return {number} 规范化后的分页值 + */ + normalizePage(value, fieldName, defaultValue, maxValue) { + if (value === undefined || value === null || value === '') { + return defaultValue; + } + + const num = Number(value); + if (!Number.isFinite(num) || num <= 0) { + throw this.createError(`${fieldName} 参数不合法`, 400); + } + + return Math.min(Math.floor(num), maxValue); + } + + /** + * 返回 where 字段映射。 + * + * @return {Object} where 字段映射 + */ + getListWhereSpecialFieldMap() { + return { + id: { + field: 'id', + }, + code: { + field: 'code', + }, + name: { + field: 'name', + }, + express_code: { + field: 'express_code', + }, + quickWhere: { + bucket: 'quick', + }, + }; + } + + /** + * 获取系统快递列表。 + * + * @return {Promise} 系统快递列表 + */ + async getSystemExpressList() { + const systemExpressService = this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.express; + if (!systemExpressService || typeof systemExpressService.getSystemExpressList !== 'function') { + return []; + } + + return await systemExpressService.getSystemExpressList(); + } + + /** + * 构建系统快递映射表。 + * + * @return {Promise>} 系统快递映射表 + */ + async getSystemExpressMap() { + const expressList = await this.getSystemExpressList(); + const expressMap = new Map(); + + for (const expressItem of Array.isArray(expressList) ? expressList : []) { + if (!expressItem || typeof expressItem !== 'object') { + continue; + } + + const code = String(expressItem.code || expressItem.value || '').trim().toUpperCase(); + if (!code) { + continue; + } + + if (!expressMap.has(code)) { + expressMap.set(code, { + code, + name: String(expressItem.name || expressItem.label || '').trim(), + }); + } + } + + return expressMap; + } + + /** + * 规范化映射记录。 + * + * @param {Object} row 数据库记录 + * @param {Map} expressMap 系统快递映射表 + * @return {Object|null} 规范化后的记录 + */ + normalizeSettingRow(row, expressMap) { + if (!row || typeof row !== 'object') { + return null; + } + + const code = String(row.code || '').trim().toUpperCase(); + if (!code) { + return null; + } + + const expressCode = String(row.express_code || '').trim().toUpperCase(); + const expressInfo = expressMap instanceof Map ? expressMap.get(expressCode) : null; + + return { + id: row.id === undefined || row.id === null ? null : Number(row.id), + warehouse_id: row.warehouse_id === undefined || row.warehouse_id === null ? null : Number(row.warehouse_id), + code, + name: String(row.name || '').trim(), + express_code: expressCode, + express_name: expressInfo ? expressInfo.name : '', + express_label: expressInfo ? expressInfo.name : '', + }; + } + + /** + * 查找当前仓库下的映射记录。 + * + * @param {number} id 映射ID + * @return {Promise} 映射记录 + */ + async findSettingById(id) { + const { ctx } = this; + const setting = await ctx.model.ExpressSetting.findOne({ + where: { + id, + warehouse_id: this.getCurrentStoreId(), + }, + }); + + if (!setting) { + throw this.createError('快递映射不存在或无权限操作', 404); + } + + return setting; + } + + /** + * 查找同仓下的编码冲突记录。 + * + * @param {string} code 映射编码 + * @param {number|null} [excludeId=null] 排除的记录ID + * @return {Promise} 冲突记录 + */ + async findCodeConflict(code, excludeId = null) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const where = { + warehouse_id: this.getCurrentStoreId(), + code, + }; + + const normalizedExcludeId = Number(excludeId || 0); + if (Number.isFinite(normalizedExcludeId) && normalizedExcludeId > 0) { + where.id = { + [Op.ne]: normalizedExcludeId, + }; + } + + return await ctx.model.ExpressSetting.findOne({ + where, + attributes: [ 'id', 'code' ], + }); + } + + /** + * 校验系统快递编码是否存在。 + * + * @param {string} expressCode 系统快递编码 + * @param {Map} [expressMap] 系统快递映射表 + * @return {Promise} 系统快递信息 + */ + async ensureSystemExpressExists(expressCode, expressMap = null) { + const normalizedExpressCode = this.normalizeCode(expressCode, 'express_code'); + const resolvedMap = expressMap instanceof Map ? expressMap : await this.getSystemExpressMap(); + const expressInfo = resolvedMap.get(normalizedExpressCode); + + if (!expressInfo) { + throw this.createError('系统快递编码不存在', 400); + } + + return expressInfo; + } + + /** + * 校验同仓编码是否可用。 + * + * @param {string} code 映射编码 + * @param {number|null} [excludeId=null] 排除的记录ID + * @return {Promise} 是否可用 + */ + async ensureCodeAvailable(code, excludeId = null) { + const conflict = await this.findCodeConflict(code, excludeId); + if (conflict) { + throw this.createError('快递编码已被当前仓库使用', 409); + } + return true; + } + + /** + * 解析列表查询条件。 + * + * @param {Object} data 请求参数 + * @return {Object} 查询条件信息 + */ + resolveListWhere(data = {}) { + const { ctx, app } = this; + const normalizedWhere = ctx.where && typeof ctx.where === 'object' + ? { ...ctx.where } + : (data.where && typeof data.where === 'object' ? { ...data.where } : {}); + + let parsedResult = ctx.whereParsed; + if (!parsedResult || !Array.isArray(parsedResult.dynamicConditions)) { + const parsed = parseWhereConditions({ + where: normalizedWhere, + app, + specialFieldMap: this.getListWhereSpecialFieldMap(), + }); + + if (!parsed.ok) { + throw this.createError(`where 参数解析失败: ${parsed.reason}`, 400); + } + + parsedResult = parsed.result; + } + + return { + normalizedWhere, + parsedResult, + }; + } + + /** + * 查询映射列表。 + * + * @param {Object} data 请求参数 + * @param {Object} [data.pagination] 分页参数 + * @return {Promise} 分页结果 + */ + async list(data = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const currentStoreId = this.getCurrentStoreId(); + const pagination = data.pagination && typeof data.pagination === 'object' ? data.pagination : {}; + const pageSource = pagination.page !== undefined ? pagination.page : data.page; + const pageSizeSource = pagination.pageSize !== undefined + ? pagination.pageSize + : (pagination.page_size !== undefined ? pagination.page_size : (data.page_size !== undefined ? data.page_size : data.pageSize)); + const page = this.normalizePage(pageSource, 'page', 1, 1000000); + const pageSize = this.normalizePage(pageSizeSource, 'page_size', 20, 200); + const offset = (page - 1) * pageSize; + + const { normalizedWhere, parsedResult } = this.resolveListWhere(data); + const andConditions = [ + { + warehouse_id: currentStoreId, + }, + ]; + + const dynamicConditions = Array.isArray(parsedResult.dynamicConditions) ? parsedResult.dynamicConditions : []; + if (dynamicConditions.length > 0) { + andConditions.push({ [Op.and]: dynamicConditions }); + } + + const quickWhereInput = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere) + || normalizedWhere.quickWhere + || null; + const quickWhereValue = quickWhereInput && typeof quickWhereInput === 'object' + ? quickWhereInput.value + : quickWhereInput; + + if (quickWhereValue !== undefined && quickWhereValue !== null && String(quickWhereValue).trim() !== '') { + const keyword = String(quickWhereValue).trim(); + andConditions.push({ + [Op.or]: [ + { code: { [Op.like]: `%${keyword}%` } }, + { name: { [Op.like]: `%${keyword}%` } }, + { express_code: { [Op.like]: `%${keyword}%` } }, + ], + }); + } + + const [ expressMap, result ] = await Promise.all([ + this.getSystemExpressMap(), + ctx.model.ExpressSetting.findAndCountAll({ + where: { + [Op.and]: andConditions, + }, + attributes: [ 'id', 'warehouse_id', 'code', 'name', 'express_code' ], + order: [[ 'id', 'DESC' ]], + offset, + limit: pageSize, + raw: true, + }), + ]); + + const list = Array.isArray(result && result.rows) + ? result.rows.map(row => this.normalizeSettingRow(row, expressMap)).filter(Boolean) + : []; + + return { + code: 200, + data: { + list, + total: Number(result && result.count ? result.count : 0), + page, + page_size: pageSize, + }, + }; + } + + /** + * 查询系统快递编码和名称列表。 + * + * @return {Promise} 系统快递列表 + */ + async listBase() { + const list = await this.getSystemExpressList(); + return { + code: 200, + data: list, + }; + } + + /** + * 检查编码是否已被占用。 + * + * @param {Object} data 请求参数 + * @param {number} [data.id] 编辑时的映射ID + * @param {string} data.code 映射编码 + * @return {Promise} 唯一性校验结果 + */ + async checkCodeUnique(data = {}) { + const code = this.normalizeCode(data.code, 'code'); + if (!code) { + throw this.createError('code 参数不能为空', 400); + } + + const excludeId = Number(data.id || 0); + const conflict = await this.findCodeConflict(code, excludeId); + + return { + code: 200, + data: { + isUnique: !conflict, + message: conflict ? '快递编码已被当前仓库使用' : 'ok', + }, + }; + } + + /** + * 创建快递映射。 + * + * @param {Object} data 请求参数 + * @return {Promise} 创建结果 + */ + async create(data = {}) { + const { ctx } = this; + const currentStoreId = this.getCurrentStoreId(); + const expressMap = await this.getSystemExpressMap(); + + const code = this.normalizeCode(data.code, 'code'); + const name = this.normalizeText(data.name, 'name', 50); + const expressCode = this.normalizeCode(data.express_code || data.expressCode, 'express_code'); + + if (!code) { + throw this.createError('code 参数不能为空', 400); + } + if (!name) { + throw this.createError('name 参数不能为空', 400); + } + if (!expressCode) { + throw this.createError('express_code 参数不能为空', 400); + } + + const expressInfo = await this.ensureSystemExpressExists(expressCode, expressMap); + await this.ensureCodeAvailable(code); + + const created = await ctx.model.ExpressSetting.create({ + warehouse_id: currentStoreId, + code, + name, + express_code: expressInfo.code, + }); + + return { + code: 200, + data: this.normalizeSettingRow(created.get ? created.get({ plain: true }) : created, expressMap), + }; + } + + /** + * 修改快递映射。 + * + * @param {Object} data 请求参数 + * @return {Promise} 修改结果 + */ + async update(data = {}) { + const { ctx } = this; + const id = Number(data.id || data.setting_id || data.settingId || 0); + if (!Number.isFinite(id) || id <= 0) { + throw this.createError('id 参数不能为空', 400); + } + + const setting = await this.findSettingById(id); + const hasCode = Object.prototype.hasOwnProperty.call(data, 'code'); + const hasName = Object.prototype.hasOwnProperty.call(data, 'name'); + const hasExpressCode = Object.prototype.hasOwnProperty.call(data, 'express_code') + || Object.prototype.hasOwnProperty.call(data, 'expressCode'); + + if (!hasCode && !hasName && !hasExpressCode) { + throw this.createError('至少需要提供一个可更新字段', 400); + } + + const updates = {}; + let expressMap = null; + + if (hasCode) { + const code = this.normalizeCode(data.code, 'code'); + if (!code) { + throw this.createError('code 参数不能为空', 400); + } + await this.ensureCodeAvailable(code, id); + updates.code = code; + } + + if (hasName) { + const name = this.normalizeText(data.name, 'name', 50); + if (!name) { + throw this.createError('name 参数不能为空', 400); + } + updates.name = name; + } + + if (hasExpressCode) { + expressMap = await this.getSystemExpressMap(); + const expressCode = this.normalizeCode(data.express_code || data.expressCode, 'express_code'); + if (!expressCode) { + throw this.createError('express_code 参数不能为空', 400); + } + + const expressInfo = await this.ensureSystemExpressExists(expressCode, expressMap); + updates.express_code = expressInfo.code; + } + + await setting.update(updates); + + if (!expressMap) { + expressMap = await this.getSystemExpressMap(); + } + + return { + code: 200, + data: this.normalizeSettingRow(setting.get ? setting.get({ plain: true }) : setting, expressMap), + }; + } +} + +module.exports = SettingExpressService; diff --git a/app/service/systems/setting/expressInterface.js b/app/service/systems/setting/expressInterface.js new file mode 100644 index 0000000..af9d4f7 --- /dev/null +++ b/app/service/systems/setting/expressInterface.js @@ -0,0 +1,774 @@ +'use strict'; + +const Service = require('egg').Service; +const { parseWhereConditions } = require('../../../lib/query_condition_parser'); + +class SettingExpressInterfaceService extends Service { + /** + * 创建业务错误对象。 + * + * @param {string} message 错误信息 + * @param {number} [code=500] 错误码 + * @return {Error} 业务错误对象 + */ + createError(message, code = 500) { + const error = new Error(message); + error.code = code; + return error; + } + + /** + * 获取当前仓库主体 ID。 + * + * @return {number} 当前仓库主体 ID + */ + getCurrentStoreId() { + const storeId = Number(this.ctx.user && this.ctx.user.store_id); + if (!Number.isFinite(storeId) || storeId <= 0) { + throw this.createError('未识别到当前主体,无法操作快递接口', 400); + } + return storeId; + } + + /** + * 规范化文本值。 + * + * @param {string} value 原始值 + * @param {string} fieldName 字段名称 + * @param {number} [maxLength=255] 最大长度 + * @return {string} 规范化后的文本 + */ + normalizeText(value, fieldName, maxLength = 255) { + if (value === undefined || value === null) { + return ''; + } + + const normalized = String(value).trim(); + if (normalized.length > maxLength) { + throw this.createError(`${fieldName} 长度不能超过 ${maxLength}`, 400); + } + + return normalized; + } + + /** + * 规范化可选文本值。 + * + * @param {string} value 原始值 + * @param {string} fieldName 字段名称 + * @param {number} [maxLength=255] 最大长度 + * @return {string|null} 规范化后的文本 + */ + normalizeOptionalText(value, fieldName, maxLength = 255) { + if (value === undefined || value === null) { + return null; + } + + const normalized = String(value).trim(); + if (normalized.length > maxLength) { + throw this.createError(`${fieldName} 长度不能超过 ${maxLength}`, 400); + } + + return normalized; + } + + /** + * 规范化整数值。 + * + * @param {number|string} value 原始值 + * @param {string} fieldName 字段名称 + * @param {Object} [options] 额外选项 + * @param {boolean} [options.allowEmpty=false] 是否允许空值 + * @param {number|null} [options.min=null] 最小值 + * @param {number|null} [options.max=null] 最大值 + * @return {number|null} 规范化后的整数 + */ + normalizeInteger(value, fieldName, options = {}) { + const { + allowEmpty = false, + min = null, + max = null, + } = options; + + if (value === undefined || value === null || value === '') { + if (allowEmpty) { + return null; + } + throw this.createError(`${fieldName} 参数不能为空`, 400); + } + + const normalized = Number(value); + if (!Number.isInteger(normalized)) { + throw this.createError(`${fieldName} 参数不合法`, 400); + } + if (min !== null && normalized < min) { + throw this.createError(`${fieldName} 参数不合法`, 400); + } + if (max !== null && normalized > max) { + throw this.createError(`${fieldName} 参数不合法`, 400); + } + + return normalized; + } + + /** + * 规范化布尔标记。 + * + * @param {number|string} value 原始值 + * @param {string} fieldName 字段名称 + * @param {number|null} [defaultValue=null] 默认值 + * @return {number|null} 规范化后的标记 + */ + normalizeFlag(value, fieldName, defaultValue = null) { + if (value === undefined || value === null || value === '') { + return defaultValue; + } + + const normalized = Number(value); + if (normalized === 0 || normalized === 1) { + return normalized; + } + + throw this.createError(`${fieldName} 参数不合法`, 400); + } + + /** + * 规范化分页参数。 + * + * @param {number|string} value 原始值 + * @param {string} fieldName 字段名称 + * @param {number} defaultValue 默认值 + * @param {number} maxValue 最大值 + * @return {number} 规范化后的分页值 + */ + normalizePage(value, fieldName, defaultValue, maxValue) { + if (value === undefined || value === null || value === '') { + return defaultValue; + } + + const normalized = Number(value); + if (!Number.isFinite(normalized) || normalized <= 0) { + throw this.createError(`${fieldName} 参数不合法`, 400); + } + + return Math.min(Math.floor(normalized), maxValue); + } + + /** + * 获取列表查询字段映射。 + * + * @return {Object} 字段映射 + */ + getListWhereSpecialFieldMap() { + return { + id: { + field: 'id', + }, + name: { + field: 'name', + }, + express_code: { + field: 'express_code', + }, + platform_code: { + field: 'platform_code', + }, + express_platform_id: { + field: 'express_platform_id', + }, + sender_name: { + field: 'sender_name', + }, + sender_tel: { + field: 'sender_tel', + }, + viewer: { + field: 'viewer', + }, + client_id: { + field: 'client_id', + }, + share_id: { + field: 'share_id', + }, + site_code: { + field: 'site_code', + }, + product_type: { + field: 'product_type', + }, + shop_name: { + field: 'shop_name', + }, + quickWhere: { + bucket: 'quick', + }, + }; + } + + /** + * 解析列表查询条件。 + * + * @param {Object} data 请求参数 + * @return {Object} 查询条件信息 + */ + resolveListWhere(data = {}) { + const { ctx, app } = this; + const normalizedWhere = ctx.where && typeof ctx.where === 'object' + ? { ...ctx.where } + : (data.where && typeof data.where === 'object' ? { ...data.where } : {}); + + let parsedResult = ctx.whereParsed; + if (!parsedResult || !Array.isArray(parsedResult.dynamicConditions)) { + const parsed = parseWhereConditions({ + where: normalizedWhere, + app, + specialFieldMap: this.getListWhereSpecialFieldMap(), + }); + + if (!parsed.ok) { + throw this.createError(`where 参数解析失败: ${parsed.reason}`, 400); + } + + parsedResult = parsed.result; + } + + return { + normalizedWhere, + parsedResult, + }; + } + + /** + * 规范化快递接口记录。 + * + * @param {Object} row 数据库记录 + * @return {Object|null} 规范化后的记录 + */ + normalizeInterfaceRow(row) { + if (!row || typeof row !== 'object') { + return null; + } + + return { + id: row.id === undefined || row.id === null ? null : Number(row.id), + name: this.normalizeOptionalText(row.name, 'name', 255), + express_code: this.normalizeOptionalText(row.express_code, 'express_code', 255), + warehouse_id: row.warehouse_id === undefined || row.warehouse_id === null ? null : Number(row.warehouse_id), + platform_code: this.normalizeOptionalText(row.platform_code, 'platform_code', 20), + express_platform_id: row.express_platform_id === undefined || row.express_platform_id === null ? null : Number(row.express_platform_id), + sender_name: this.normalizeOptionalText(row.sender_name, 'sender_name', 50), + sender_tel: this.normalizeOptionalText(row.sender_tel, 'sender_tel', 11), + weight: row.weight === undefined || row.weight === null ? null : Number(row.weight), + token: this.normalizeOptionalText(row.token, 'token', 500), + viewer: this.normalizeOptionalText(row.viewer, 'viewer', 50), + client_id: this.normalizeOptionalText(row.client_id, 'client_id', 50), + is_share: row.is_share === undefined || row.is_share === null ? null : Number(row.is_share), + share_id: row.share_id === undefined || row.share_id === null ? null : Number(row.share_id), + can_use_count: row.can_use_count === undefined || row.can_use_count === null ? null : Number(row.can_use_count), + province_name: this.normalizeOptionalText(row.province_name, 'province_name', 255), + city_name: this.normalizeOptionalText(row.city_name, 'city_name', 255), + district_name: this.normalizeOptionalText(row.district_name, 'district_name', 255), + site_code: this.normalizeOptionalText(row.site_code, 'site_code', 255), + product_type: this.normalizeOptionalText(row.product_type, 'product_type', 50), + shop_name: this.normalizeOptionalText(row.shop_name, 'shop_name', 255), + }; + } + + /** + * 查找当前仓库下的快递接口记录。 + * + * @param {number} id 接口 ID + * @return {Promise} 接口记录 + */ + async findInterfaceById(id) { + const { ctx } = this; + const currentStoreId = this.getCurrentStoreId(); + + const setting = await ctx.model.ExpressInterface.findOne({ + where: { + id, + warehouse_id: currentStoreId, + }, + }); + + if (!setting) { + throw this.createError('快递接口不存在或无权限操作', 404); + } + + return setting; + } + + /** + * 查找同仓下的快递编码冲突记录。 + * + * @param {string} expressCode 快递编码 + * @param {number|null} [excludeId=null] 排除的记录 ID + * @return {Promise} 冲突记录 + */ + async findCodeConflict(expressCode, excludeId = null) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const where = { + warehouse_id: this.getCurrentStoreId(), + express_code: expressCode, + }; + + const normalizedExcludeId = Number(excludeId || 0); + if (Number.isInteger(normalizedExcludeId) && normalizedExcludeId > 0) { + where.id = { + [Op.ne]: normalizedExcludeId, + }; + } + + return await ctx.model.ExpressInterface.findOne({ + where, + attributes: [ 'id', 'express_code' ], + }); + } + + /** + * 查找同仓下的平台接口冲突记录。 + * + * @param {string} platformCode 平台代码 + * @param {number} expressPlatformId 快递接口 ID + * @param {number|null} [excludeId=null] 排除的记录 ID + * @return {Promise} 冲突记录 + */ + async findInterfaceConflict(platformCode, expressPlatformId, excludeId = null) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const where = { + warehouse_id: this.getCurrentStoreId(), + platform_code: platformCode, + express_platform_id: expressPlatformId, + }; + + const normalizedExcludeId = Number(excludeId || 0); + if (Number.isInteger(normalizedExcludeId) && normalizedExcludeId > 0) { + where.id = { + [Op.ne]: normalizedExcludeId, + }; + } + + return await ctx.model.ExpressInterface.findOne({ + where, + attributes: [ 'id', 'platform_code', 'express_platform_id' ], + }); + } + + /** + * 校验快递编码是否可用。 + * + * @param {string} expressCode 快递编码 + * @param {number|null} [excludeId=null] 排除的记录 ID + * @return {Promise} 是否可用 + */ + async ensureCodeAvailable(expressCode, excludeId = null) { + const conflict = await this.findCodeConflict(expressCode, excludeId); + if (conflict) { + throw this.createError('快递编码已被当前仓库使用', 409); + } + return true; + } + + /** + * 校验平台接口组合是否可用。 + * + * @param {string} platformCode 平台代码 + * @param {number} expressPlatformId 快递接口 ID + * @param {number|null} [excludeId=null] 排除的记录 ID + * @return {Promise} 是否可用 + */ + async ensureInterfaceAvailable(platformCode, expressPlatformId, excludeId = null) { + const conflict = await this.findInterfaceConflict(platformCode, expressPlatformId, excludeId); + if (conflict) { + throw this.createError('当前平台和快递接口组合已被使用', 409); + } + return true; + } + + /** + * 获取快递接口列表。 + * + * @param {Object} data 请求参数 + * @param {Object} [data.pagination] 分页参数 + * @return {Promise} 分页结果 + */ + async list(data = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const currentStoreId = this.getCurrentStoreId(); + const pagination = data.pagination && typeof data.pagination === 'object' ? data.pagination : {}; + const pageSource = pagination.page !== undefined ? pagination.page : data.page; + const pageSizeSource = pagination.pageSize !== undefined + ? pagination.pageSize + : (pagination.page_size !== undefined ? pagination.page_size : (data.page_size !== undefined ? data.page_size : data.pageSize)); + const page = this.normalizePage(pageSource, 'page', 1, 1000000); + const pageSize = this.normalizePage(pageSizeSource, 'page_size', 20, 200); + const offset = (page - 1) * pageSize; + + const { normalizedWhere, parsedResult } = this.resolveListWhere(data); + const andConditions = [ + { + warehouse_id: currentStoreId, + }, + ]; + + const dynamicConditions = Array.isArray(parsedResult.dynamicConditions) ? parsedResult.dynamicConditions : []; + if (dynamicConditions.length > 0) { + andConditions.push({ [Op.and]: dynamicConditions }); + } + + const quickWhereInput = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere) + || normalizedWhere.quickWhere + || null; + const quickWhereValue = quickWhereInput && typeof quickWhereInput === 'object' + ? quickWhereInput.value + : quickWhereInput; + + if (quickWhereValue !== undefined && quickWhereValue !== null && String(quickWhereValue).trim() !== '') { + const keyword = String(quickWhereValue).trim(); + andConditions.push({ + [Op.or]: [ + { name: { [Op.like]: `%${keyword}%` } }, + { express_code: { [Op.like]: `%${keyword}%` } }, + { platform_code: { [Op.like]: `%${keyword}%` } }, + { sender_name: { [Op.like]: `%${keyword}%` } }, + { sender_tel: { [Op.like]: `%${keyword}%` } }, + { viewer: { [Op.like]: `%${keyword}%` } }, + { client_id: { [Op.like]: `%${keyword}%` } }, + { province_name: { [Op.like]: `%${keyword}%` } }, + { city_name: { [Op.like]: `%${keyword}%` } }, + { district_name: { [Op.like]: `%${keyword}%` } }, + { site_code: { [Op.like]: `%${keyword}%` } }, + { product_type: { [Op.like]: `%${keyword}%` } }, + { shop_name: { [Op.like]: `%${keyword}%` } }, + ], + }); + } + + const result = await ctx.model.ExpressInterface.findAndCountAll({ + where: { + [Op.and]: andConditions, + }, + attributes: [ + 'id', 'name', 'express_code', 'warehouse_id', 'platform_code', 'express_platform_id', + 'sender_name', 'sender_tel', 'weight', 'token', 'viewer', 'client_id', 'is_share', + 'share_id', 'can_use_count', 'province_name', 'city_name', 'district_name', 'site_code', + 'product_type', 'shop_name', + ], + order: [[ 'id', 'DESC' ]], + offset, + limit: pageSize, + raw: true, + }); + + const list = Array.isArray(result && result.rows) + ? result.rows.map(row => this.normalizeInterfaceRow(row)).filter(Boolean) + : []; + + return { + code: 200, + data: { + list, + total: Number(result && result.count ? result.count : 0), + page, + page_size: pageSize, + }, + }; + } + + /** + * 创建快递接口。 + * + * @param {Object} data 请求参数 + * @return {Promise} 创建结果 + */ + async create(data = {}) { + const { ctx } = this; + const currentStoreId = this.getCurrentStoreId(); + + const name = this.normalizeText(data.name, 'name', 255); + const expressCode = this.normalizeText(data.express_code || data.expressCode, 'express_code', 255).toUpperCase(); + const platformCode = this.normalizeText(data.platform_code || data.platformCode, 'platform_code', 20).toUpperCase(); + const expressPlatformId = this.normalizeInteger(data.express_platform_id || data.expressPlatformId, 'express_platform_id', { + min: 1, + }); + + if (!name) { + throw this.createError('name 参数不能为空', 400); + } + if (!expressCode) { + throw this.createError('express_code 参数不能为空', 400); + } + if (!platformCode) { + throw this.createError('platform_code 参数不能为空', 400); + } + if (!expressPlatformId) { + throw this.createError('express_platform_id 参数不能为空', 400); + } + + await this.ensureCodeAvailable(expressCode); + await this.ensureInterfaceAvailable(platformCode, expressPlatformId); + + const payload = { + warehouse_id: currentStoreId, + name, + express_code: expressCode, + platform_code: platformCode, + express_platform_id: expressPlatformId, + sender_name: this.normalizeOptionalText(data.sender_name || data.senderName, 'sender_name', 50), + sender_tel: this.normalizeOptionalText(data.sender_tel || data.senderTel, 'sender_tel', 11), + weight: this.normalizeInteger(data.weight, 'weight', { + allowEmpty: true, + }), + token: this.normalizeOptionalText(data.token, 'token', 500), + viewer: this.normalizeOptionalText(data.viewer, 'viewer', 50), + client_id: this.normalizeOptionalText(data.client_id || data.clientId, 'client_id', 50), + is_share: this.normalizeFlag(data.is_share !== undefined ? data.is_share : data.isShare, 'is_share', 0), + share_id: this.normalizeInteger(data.share_id || data.shareId, 'share_id', { + allowEmpty: true, + min: 1, + }), + can_use_count: this.normalizeInteger(data.can_use_count !== undefined ? data.can_use_count : data.canUseCount, 'can_use_count', { + allowEmpty: true, + min: 0, + }), + province_name: this.normalizeOptionalText(data.province_name || data.provinceName, 'province_name', 255), + city_name: this.normalizeOptionalText(data.city_name || data.cityName, 'city_name', 255), + district_name: this.normalizeOptionalText(data.district_name || data.districtName, 'district_name', 255), + site_code: this.normalizeOptionalText(data.site_code || data.siteCode, 'site_code', 255), + product_type: this.normalizeOptionalText(data.product_type || data.productType, 'product_type', 50), + shop_name: this.normalizeOptionalText(data.shop_name || data.shopName, 'shop_name', 255), + }; + + const created = await ctx.model.ExpressInterface.create(payload); + const plainCreated = created && typeof created.get === 'function' + ? created.get({ plain: true }) + : created; + + return { + code: 200, + data: this.normalizeInterfaceRow(plainCreated), + }; + } + + /** + * 修改快递接口。 + * + * @param {Object} data 请求参数 + * @return {Promise} 修改结果 + */ + async update(data = {}) { + const id = Number(data.id || data.interface_id || data.interfaceId || 0); + if (!Number.isInteger(id) || id <= 0) { + throw this.createError('id 参数不能为空', 400); + } + + const setting = await this.findInterfaceById(id); + const hasName = Object.prototype.hasOwnProperty.call(data, 'name'); + const hasExpressCode = Object.prototype.hasOwnProperty.call(data, 'express_code') + || Object.prototype.hasOwnProperty.call(data, 'expressCode'); + const hasPlatformCode = Object.prototype.hasOwnProperty.call(data, 'platform_code') + || Object.prototype.hasOwnProperty.call(data, 'platformCode'); + const hasExpressPlatformId = Object.prototype.hasOwnProperty.call(data, 'express_platform_id') + || Object.prototype.hasOwnProperty.call(data, 'expressPlatformId'); + const hasSenderName = Object.prototype.hasOwnProperty.call(data, 'sender_name') + || Object.prototype.hasOwnProperty.call(data, 'senderName'); + const hasSenderTel = Object.prototype.hasOwnProperty.call(data, 'sender_tel') + || Object.prototype.hasOwnProperty.call(data, 'senderTel'); + const hasWeight = Object.prototype.hasOwnProperty.call(data, 'weight'); + const hasToken = Object.prototype.hasOwnProperty.call(data, 'token'); + const hasViewer = Object.prototype.hasOwnProperty.call(data, 'viewer'); + const hasClientId = Object.prototype.hasOwnProperty.call(data, 'client_id') + || Object.prototype.hasOwnProperty.call(data, 'clientId'); + const hasIsShare = Object.prototype.hasOwnProperty.call(data, 'is_share') + || Object.prototype.hasOwnProperty.call(data, 'isShare'); + const hasShareId = Object.prototype.hasOwnProperty.call(data, 'share_id') + || Object.prototype.hasOwnProperty.call(data, 'shareId'); + const hasCanUseCount = Object.prototype.hasOwnProperty.call(data, 'can_use_count') + || Object.prototype.hasOwnProperty.call(data, 'canUseCount'); + const hasProvinceName = Object.prototype.hasOwnProperty.call(data, 'province_name') + || Object.prototype.hasOwnProperty.call(data, 'provinceName'); + const hasCityName = Object.prototype.hasOwnProperty.call(data, 'city_name') + || Object.prototype.hasOwnProperty.call(data, 'cityName'); + const hasDistrictName = Object.prototype.hasOwnProperty.call(data, 'district_name') + || Object.prototype.hasOwnProperty.call(data, 'districtName'); + const hasSiteCode = Object.prototype.hasOwnProperty.call(data, 'site_code') + || Object.prototype.hasOwnProperty.call(data, 'siteCode'); + const hasProductType = Object.prototype.hasOwnProperty.call(data, 'product_type') + || Object.prototype.hasOwnProperty.call(data, 'productType'); + const hasShopName = Object.prototype.hasOwnProperty.call(data, 'shop_name') + || Object.prototype.hasOwnProperty.call(data, 'shopName'); + + if (!hasName && !hasExpressCode && !hasPlatformCode && !hasExpressPlatformId && !hasSenderName + && !hasSenderTel && !hasWeight && !hasToken && !hasViewer && !hasClientId && !hasIsShare + && !hasShareId && !hasCanUseCount && !hasProvinceName && !hasCityName && !hasDistrictName + && !hasSiteCode && !hasProductType && !hasShopName) { + throw this.createError('至少需要提供一个可更新字段', 400); + } + + const updates = {}; + let nextExpressCode = setting.express_code || ''; + let nextPlatformCode = setting.platform_code || ''; + let nextExpressPlatformId = setting.express_platform_id === undefined || setting.express_platform_id === null + ? null + : Number(setting.express_platform_id); + + if (hasName) { + const name = this.normalizeText(data.name, 'name', 255); + if (!name) { + throw this.createError('name 参数不能为空', 400); + } + updates.name = name; + } + + if (hasExpressCode) { + const expressCode = this.normalizeText(data.express_code || data.expressCode, 'express_code', 255).toUpperCase(); + if (!expressCode) { + throw this.createError('express_code 参数不能为空', 400); + } + nextExpressCode = expressCode; + updates.express_code = expressCode; + } + + if (hasPlatformCode) { + const platformCode = this.normalizeText(data.platform_code || data.platformCode, 'platform_code', 20).toUpperCase(); + if (!platformCode) { + throw this.createError('platform_code 参数不能为空', 400); + } + nextPlatformCode = platformCode; + updates.platform_code = platformCode; + } + + if (hasExpressPlatformId) { + const expressPlatformId = this.normalizeInteger(data.express_platform_id || data.expressPlatformId, 'express_platform_id', { + min: 1, + }); + if (!expressPlatformId) { + throw this.createError('express_platform_id 参数不能为空', 400); + } + nextExpressPlatformId = expressPlatformId; + updates.express_platform_id = expressPlatformId; + } + + if (hasSenderName) { + updates.sender_name = this.normalizeOptionalText(data.sender_name || data.senderName, 'sender_name', 50); + } + + if (hasSenderTel) { + updates.sender_tel = this.normalizeOptionalText(data.sender_tel || data.senderTel, 'sender_tel', 11); + } + + if (hasWeight) { + updates.weight = this.normalizeInteger(data.weight, 'weight', { + allowEmpty: true, + }); + } + + if (hasToken) { + updates.token = this.normalizeOptionalText(data.token, 'token', 500); + } + + if (hasViewer) { + updates.viewer = this.normalizeOptionalText(data.viewer, 'viewer', 50); + } + + if (hasClientId) { + updates.client_id = this.normalizeOptionalText(data.client_id || data.clientId, 'client_id', 50); + } + + if (hasIsShare) { + updates.is_share = this.normalizeFlag(data.is_share !== undefined ? data.is_share : data.isShare, 'is_share', 0); + } + + if (hasShareId) { + updates.share_id = this.normalizeInteger(data.share_id || data.shareId, 'share_id', { + allowEmpty: true, + min: 1, + }); + } + + if (hasCanUseCount) { + updates.can_use_count = this.normalizeInteger(data.can_use_count !== undefined ? data.can_use_count : data.canUseCount, 'can_use_count', { + allowEmpty: true, + min: 0, + }); + } + + if (hasProvinceName) { + updates.province_name = this.normalizeOptionalText(data.province_name || data.provinceName, 'province_name', 255); + } + + if (hasCityName) { + updates.city_name = this.normalizeOptionalText(data.city_name || data.cityName, 'city_name', 255); + } + + if (hasDistrictName) { + updates.district_name = this.normalizeOptionalText(data.district_name || data.districtName, 'district_name', 255); + } + + if (hasSiteCode) { + updates.site_code = this.normalizeOptionalText(data.site_code || data.siteCode, 'site_code', 255); + } + + if (hasProductType) { + updates.product_type = this.normalizeOptionalText(data.product_type || data.productType, 'product_type', 50); + } + + if (hasShopName) { + updates.shop_name = this.normalizeOptionalText(data.shop_name || data.shopName, 'shop_name', 255); + } + + if (Object.prototype.hasOwnProperty.call(updates, 'express_code')) { + await this.ensureCodeAvailable(nextExpressCode, id); + } + if (Object.prototype.hasOwnProperty.call(updates, 'platform_code') + || Object.prototype.hasOwnProperty.call(updates, 'express_platform_id')) { + await this.ensureInterfaceAvailable(nextPlatformCode, nextExpressPlatformId, id); + } + + await setting.update(updates); + + const plainSetting = setting && typeof setting.get === 'function' + ? setting.get({ plain: true }) + : setting; + + return { + code: 200, + data: this.normalizeInterfaceRow(plainSetting), + }; + } + + /** + * 删除快递接口。 + * + * @param {Object} data 请求参数 + * @return {Promise} 删除结果 + */ + async delete(data = {}) { + const id = Number(data.id || data.interface_id || data.interfaceId || 0); + if (!Number.isInteger(id) || id <= 0) { + throw this.createError('id 参数不能为空', 400); + } + + const setting = await this.findInterfaceById(id); + const plainSetting = setting && typeof setting.get === 'function' + ? setting.get({ plain: true }) + : setting; + + await setting.destroy(); + + return { + code: 200, + data: { + id: Number(plainSetting.id), + warehouse_id: Number(plainSetting.warehouse_id), + deleted: true, + }, + }; + } +} + +module.exports = SettingExpressInterfaceService; diff --git a/app/service/systems/setting/platform.js b/app/service/systems/setting/platform.js new file mode 100644 index 0000000..0bb0c4d --- /dev/null +++ b/app/service/systems/setting/platform.js @@ -0,0 +1,638 @@ +'use strict'; + +const Service = require('egg').Service; +const { parseWhereConditions } = require('../../../lib/query_condition_parser'); + +class SettingPlatformService extends Service { + /** + * 创建业务错误对象。 + * + * @param {string} message 错误信息 + * @param {number} [code=500] 错误码 + * @return {Error} 业务错误对象 + */ + createError(message, code = 500) { + const error = new Error(message); + error.code = code; + return error; + } + + /** + * 获取当前仓库主体 ID。 + * + * @return {number} 当前仓库主体 ID + */ + getCurrentStoreId() { + const storeId = Number(this.ctx.user && this.ctx.user.store_id); + if (!Number.isFinite(storeId) || storeId <= 0) { + throw this.createError('未识别到当前主体,无法操作平台设置', 400); + } + return storeId; + } + + /** + * 规范化必填文本。 + * + * @param {string|number} value 原始值 + * @param {string} fieldName 字段名称 + * @param {number} maxLength 最大长度 + * @return {string} 规范化后的文本 + */ + normalizeRequiredText(value, fieldName, maxLength) { + if (value === undefined || value === null) { + throw this.createError(`${fieldName} 参数不能为空`, 400); + } + + if (typeof value !== 'string' && typeof value !== 'number') { + throw this.createError(`${fieldName} 参数类型不合法`, 400); + } + + const normalized = String(value).trim(); + if (!normalized) { + throw this.createError(`${fieldName} 参数不能为空`, 400); + } + + if (normalized.length > maxLength) { + throw this.createError(`${fieldName} 长度不能超过 ${maxLength}`, 400); + } + + return normalized; + } + + /** + * 规范化可选文本。 + * + * @param {string|number} value 原始值 + * @param {string} fieldName 字段名称 + * @param {number} maxLength 最大长度 + * @return {string|null} 规范化后的文本 + */ + normalizeOptionalText(value, fieldName, maxLength) { + if (value === undefined || value === null) { + return null; + } + + if (typeof value !== 'string' && typeof value !== 'number') { + throw this.createError(`${fieldName} 参数类型不合法`, 400); + } + + const normalized = String(value).trim(); + if (!normalized) { + return null; + } + + if (normalized.length > maxLength) { + throw this.createError(`${fieldName} 长度不能超过 ${maxLength}`, 400); + } + + return normalized; + } + + /** + * 规范化整数。 + * + * @param {number|string} value 原始值 + * @param {string} fieldName 字段名称 + * @param {Object} [options] 额外选项 + * @param {boolean} [options.allowEmpty=false] 是否允许空值 + * @param {number|null} [options.min=null] 最小值 + * @param {number|null} [options.max=null] 最大值 + * @return {number|null} 规范化后的整数 + */ + normalizeInteger(value, fieldName, options = {}) { + const { + allowEmpty = false, + min = null, + max = null, + } = options; + + if (value === undefined || value === null || value === '') { + if (allowEmpty) { + return null; + } + throw this.createError(`${fieldName} 参数不能为空`, 400); + } + + const normalized = Number(value); + if (!Number.isInteger(normalized)) { + throw this.createError(`${fieldName} 参数不合法`, 400); + } + if (min !== null && normalized < min) { + throw this.createError(`${fieldName} 参数不合法`, 400); + } + if (max !== null && normalized > max) { + throw this.createError(`${fieldName} 参数不合法`, 400); + } + + return normalized; + } + + /** + * 规范化分页参数。 + * + * @param {number|string} value 原始值 + * @param {string} fieldName 字段名称 + * @param {number} defaultValue 默认值 + * @param {number} maxValue 最大值 + * @return {number} 规范化后的分页值 + */ + normalizePage(value, fieldName, defaultValue, maxValue) { + if (value === undefined || value === null || value === '') { + return defaultValue; + } + + const normalized = Number(value); + if (!Number.isFinite(normalized) || normalized <= 0) { + throw this.createError(`${fieldName} 参数不合法`, 400); + } + + return Math.min(Math.floor(normalized), maxValue); + } + + /** + * 获取列表查询字段映射。 + * + * @return {Object} 字段映射 + */ + getListWhereSpecialFieldMap() { + return { + id: { + field: 'id', + }, + code: { + field: 'code', + }, + name: { + field: 'name', + }, + platform_code: { + field: 'platform_code', + }, + quickWhere: { + bucket: 'quick', + }, + }; + } + + /** + * 解析列表查询条件。 + * + * @param {Object} data 请求参数 + * @return {Object} 查询条件信息 + */ + resolveListWhere(data = {}) { + const { ctx, app } = this; + const normalizedWhere = ctx.where && typeof ctx.where === 'object' + ? { ...ctx.where } + : (data.where && typeof data.where === 'object' ? { ...data.where } : {}); + + let parsedResult = ctx.whereParsed; + if (!parsedResult || !Array.isArray(parsedResult.dynamicConditions)) { + const parsed = parseWhereConditions({ + where: normalizedWhere, + app, + specialFieldMap: this.getListWhereSpecialFieldMap(), + }); + + if (!parsed.ok) { + throw this.createError(`where 参数解析失败: ${parsed.reason}`, 400); + } + + parsedResult = parsed.result; + } + + return { + normalizedWhere, + parsedResult, + }; + } + + /** + * 生成平台展示标签。 + * + * @param {string} code 设置代码 + * @param {string} platformName 平台名称 + * @return {string} 展示标签 + */ + buildPlatformLabel(code, platformName) { + const normalizedCode = String(code || '').trim(); + const normalizedPlatformName = String(platformName || '').trim(); + + if (!normalizedCode) { + return normalizedPlatformName; + } + + if (!normalizedPlatformName) { + return normalizedCode; + } + + return `${normalizedCode} (${normalizedPlatformName})`; + } + + /** + * 规范化平台设置记录。 + * + * @param {Object} row 数据库记录 + * @return {Object|null} 规范化后的记录 + */ + normalizePlatformRow(row) { + if (!row || typeof row !== 'object') { + return null; + } + + const platform = row.platform && typeof row.platform === 'object' ? row.platform : null; + const code = this.normalizeOptionalText(row.code, 'code', 50); + if (!code) { + return null; + } + + const platformCode = this.normalizeOptionalText(row.platform_code, 'platform_code', 50) + || this.normalizeOptionalText(platform && platform.code, 'platform_code', 50) + || ''; + const platformName = this.normalizeOptionalText( + row.platform_name !== undefined ? row.platform_name : (platform && platform.name), + 'platform_name', + 255 + ) || ''; + const platformLabel = this.buildPlatformLabel(code, platformName); + + return { + id: row.id === undefined || row.id === null ? null : Number(row.id), + code, + name: this.normalizeOptionalText(row.name, 'name', 100), + platform_code: platformCode, + warehouse_id: row.warehouse_id === undefined || row.warehouse_id === null ? null : Number(row.warehouse_id), + label: platformLabel, + platform_name: platformName, + platform_label: platformLabel, + platform: platform ? { + code: this.normalizeOptionalText(platform.code, 'platform.code', 50), + name: this.normalizeOptionalText(platform.name, 'platform.name', 255), + default_express_interface: this.normalizeOptionalText(platform.default_express_interface, 'platform.default_express_interface', 50), + } : null, + }; + } + + /** + * 查找当前仓库下的平台设置记录。 + * + * @param {number} id 设置 ID + * @return {Promise} 平台设置记录 + */ + async findSettingById(id) { + const { ctx } = this; + const currentStoreId = this.getCurrentStoreId(); + + const setting = await ctx.model.PlatformSetting.findOne({ + where: { + id, + warehouse_id: currentStoreId, + }, + include: [ + { + model: ctx.model.Platform, + as: 'platform', + attributes: [ 'code', 'name', 'default_express_interface' ], + required: false, + }, + ], + }); + + if (!setting) { + throw this.createError('平台设置不存在或无权限操作', 404); + } + + return setting; + } + + /** + * 查找同仓下的 code 冲突记录。 + * + * @param {string} code 设置代码 + * @param {number|null} [excludeId=null] 排除的记录 ID + * @return {Promise} 冲突记录 + */ + async findCodeConflict(code, excludeId = null) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const where = { + warehouse_id: this.getCurrentStoreId(), + code, + }; + + const normalizedExcludeId = Number(excludeId || 0); + if (Number.isInteger(normalizedExcludeId) && normalizedExcludeId > 0) { + where.id = { + [Op.ne]: normalizedExcludeId, + }; + } + + return await ctx.model.PlatformSetting.findOne({ + where, + attributes: [ 'id', 'code' ], + }); + } + + /** + * 查找同仓下的平台代码冲突记录。 + * + * @param {string} platformCode 平台代码 + * @param {number|null} [excludeId=null] 排除的记录 ID + * @return {Promise} 冲突记录 + */ + async findPlatformCodeConflict(platformCode, excludeId = null) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const where = { + warehouse_id: this.getCurrentStoreId(), + platform_code: platformCode, + }; + + const normalizedExcludeId = Number(excludeId || 0); + if (Number.isInteger(normalizedExcludeId) && normalizedExcludeId > 0) { + where.id = { + [Op.ne]: normalizedExcludeId, + }; + } + + return await ctx.model.PlatformSetting.findOne({ + where, + attributes: [ 'id', 'platform_code' ], + }); + } + + /** + * 校验平台是否存在。 + * + * @param {string} platformCode 平台代码 + * @return {Promise} 平台记录 + */ + async ensurePlatformExists(platformCode) { + const { ctx } = this; + const platform = await ctx.model.Platform.findOne({ + where: { + code: platformCode, + }, + attributes: [ 'code', 'name', 'default_express_interface' ], + }); + + if (!platform) { + throw this.createError('platform_code 不存在或不支持', 400); + } + + return platform; + } + + /** + * 校验 code 是否可用。 + * + * @param {string} code 设置代码 + * @param {number|null} [excludeId=null] 排除的记录 ID + * @return {Promise} 是否可用 + */ + async ensureCodeAvailable(code, excludeId = null) { + const conflict = await this.findCodeConflict(code, excludeId); + if (conflict) { + throw this.createError('code 已被当前仓库使用', 409); + } + return true; + } + + /** + * 校验平台代码是否可用。 + * + * @param {string} platformCode 平台代码 + * @param {number|null} [excludeId=null] 排除的记录 ID + * @return {Promise} 是否可用 + */ + async ensurePlatformCodeAvailable(platformCode, excludeId = null) { + const conflict = await this.findPlatformCodeConflict(platformCode, excludeId); + if (conflict) { + throw this.createError('platform_code 已被当前仓库使用', 409); + } + return true; + } + + /** + * 获取平台设置列表。 + * + * @param {Object} data 请求参数 + * @param {Object} [data.pagination] 分页参数 + * @return {Promise} 分页结果 + */ + async list(data = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const currentStoreId = this.getCurrentStoreId(); + const pagination = data.pagination && typeof data.pagination === 'object' ? data.pagination : {}; + const pageSource = pagination.page !== undefined ? pagination.page : data.page; + const pageSizeSource = pagination.pageSize !== undefined + ? pagination.pageSize + : (pagination.page_size !== undefined ? pagination.page_size : (data.page_size !== undefined ? data.page_size : data.pageSize)); + const page = this.normalizePage(pageSource, 'page', 1, 1000000); + const pageSize = this.normalizePage(pageSizeSource, 'page_size', 20, 200); + const offset = (page - 1) * pageSize; + + const { normalizedWhere, parsedResult } = this.resolveListWhere(data); + const andConditions = [ + { + warehouse_id: currentStoreId, + }, + ]; + + const dynamicConditions = Array.isArray(parsedResult.dynamicConditions) ? parsedResult.dynamicConditions : []; + if (dynamicConditions.length > 0) { + andConditions.push({ [Op.and]: dynamicConditions }); + } + + const quickWhereInput = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere) + || normalizedWhere.quickWhere + || null; + const quickWhereValue = quickWhereInput && typeof quickWhereInput === 'object' + ? quickWhereInput.value + : quickWhereInput; + + if (quickWhereValue !== undefined && quickWhereValue !== null && String(quickWhereValue).trim() !== '') { + const keyword = String(quickWhereValue).trim(); + andConditions.push({ + [Op.or]: [ + { code: { [Op.like]: `%${keyword}%` } }, + { name: { [Op.like]: `%${keyword}%` } }, + { platform_code: { [Op.like]: `%${keyword}%` } }, + ], + }); + } + + const result = await ctx.model.PlatformSetting.findAndCountAll({ + where: { + [Op.and]: andConditions, + }, + include: [ + { + model: ctx.model.Platform, + as: 'platform', + attributes: [ 'code', 'name', 'default_express_interface' ], + required: false, + }, + ], + attributes: [ 'id', 'code', 'name', 'platform_code', 'warehouse_id' ], + order: [[ 'id', 'DESC' ]], + offset, + limit: pageSize, + }); + + const list = Array.isArray(result && result.rows) + ? result.rows.map(row => this.normalizePlatformRow(row && typeof row.get === 'function' ? row.get({ plain: true }) : row)).filter(Boolean) + : []; + + const total = Array.isArray(result && result.count) + ? result.count.length + : Number(result && result.count ? result.count : 0); + + return { + code: 200, + data: { + list, + total, + page, + page_size: pageSize, + }, + }; + } + + /** + * 创建平台设置。 + * + * @param {Object} data 请求参数 + * @return {Promise} 创建结果 + */ + async create(data = {}) { + const { ctx } = this; + const currentStoreId = this.getCurrentStoreId(); + + const code = this.normalizeRequiredText(data.code, 'code', 50); + const name = this.normalizeRequiredText(data.name, 'name', 100); + const platformCode = this.normalizeRequiredText(data.platform_code !== undefined ? data.platform_code : data.platformCode, 'platform_code', 50); + + const platform = await this.ensurePlatformExists(platformCode); + await this.ensureCodeAvailable(code); + await this.ensurePlatformCodeAvailable(platformCode); + + const created = await ctx.model.PlatformSetting.create({ + warehouse_id: currentStoreId, + code, + name, + platform_code: platformCode, + }); + + const plainCreated = created && typeof created.get === 'function' + ? created.get({ plain: true }) + : created; + + return { + code: 200, + data: this.normalizePlatformRow({ + ...plainCreated, + platform, + }), + }; + } + + /** + * 修改平台设置。 + * + * @param {Object} data 请求参数 + * @return {Promise} 修改结果 + */ + async update(data = {}) { + const id = Number(data.id || data.setting_id || data.settingId || 0); + if (!Number.isInteger(id) || id <= 0) { + throw this.createError('id 参数不能为空', 400); + } + + const setting = await this.findSettingById(id); + const hasCode = Object.prototype.hasOwnProperty.call(data, 'code'); + const hasName = Object.prototype.hasOwnProperty.call(data, 'name'); + const hasPlatformCode = Object.prototype.hasOwnProperty.call(data, 'platform_code') + || Object.prototype.hasOwnProperty.call(data, 'platformCode'); + + if (!hasCode && !hasName && !hasPlatformCode) { + throw this.createError('至少需要提供一个可更新字段', 400); + } + + const updates = {}; + let nextCode = setting.code || ''; + let nextPlatformCode = setting.platform_code || ''; + let platform = setting.platform || null; + + if (hasCode) { + const code = this.normalizeRequiredText(data.code, 'code', 50); + updates.code = code; + nextCode = code; + } + + if (hasName) { + updates.name = this.normalizeRequiredText(data.name, 'name', 100); + } + + if (hasPlatformCode) { + const platformCode = this.normalizeRequiredText(data.platform_code !== undefined ? data.platform_code : data.platformCode, 'platform_code', 50); + platform = await this.ensurePlatformExists(platformCode); + updates.platform_code = platformCode; + nextPlatformCode = platformCode; + } + + if (Object.prototype.hasOwnProperty.call(updates, 'code')) { + await this.ensureCodeAvailable(nextCode, id); + } + + if (Object.prototype.hasOwnProperty.call(updates, 'platform_code')) { + await this.ensurePlatformCodeAvailable(nextPlatformCode, id); + } + + await setting.update(updates); + + const plainSetting = setting && typeof setting.get === 'function' + ? setting.get({ plain: true }) + : setting; + + return { + code: 200, + data: this.normalizePlatformRow({ + ...plainSetting, + platform, + }), + }; + } + + /** + * 删除平台设置。 + * + * @param {Object} data 请求参数 + * @return {Promise} 删除结果 + */ + async delete(data = {}) { + const id = Number(data.id || data.setting_id || data.settingId || 0); + if (!Number.isInteger(id) || id <= 0) { + throw this.createError('id 参数不能为空', 400); + } + + const setting = await this.findSettingById(id); + const plainSetting = setting && typeof setting.get === 'function' + ? setting.get({ plain: true }) + : setting; + + await setting.destroy(); + + return { + code: 200, + data: { + id: Number(plainSetting.id), + warehouse_id: Number(plainSetting.warehouse_id), + deleted: true, + }, + }; + } +} + +module.exports = SettingPlatformService; diff --git a/app/service/systems/stock_store.js b/app/service/systems/stock_store.js index 7819a62..609049d 100644 --- a/app/service/systems/stock_store.js +++ b/app/service/systems/stock_store.js @@ -2181,6 +2181,20 @@ class stockStoreService extends Service { } } + /** + * 获取仓库商品详情。 + * + * @param {object} data - 查询参数。 + * @param {number|string} data.id - 商品 ID。 + * @return {Promise} 商品详情。 + */ + /** + * 查询库存商品详情。 + * + * @param {Object} data 请求参数。 + * @param {number|string} data.id 库存商品 ID。 + * @return {Promise} 库存商品详情。 + */ async getInfo(data) { const { ctx, @@ -2223,6 +2237,10 @@ class stockStoreService extends Service { 'box_width', 'box_height', 'box_volume', + 'inbound_min_days', + 'outbound_min_days', + 'remaining_threshold_days', + 'shelf_life_days', 'store_id', ], raw: true, @@ -2230,6 +2248,12 @@ class stockStoreService extends Service { stock.enable_box_spec = !!stock.enable_box_spec; return stock; } + /** + * 更新仓库商品资料,并在启用保质期管理时校验保质期相关字段。 + * + * @param {Object} data 请求体,包含商品主键及待更新字段。 + * @return {Promise} 返回更新后的商品详情。 + */ async saveWarehouseStock(data) { const { ctx, service } = this; const warehouseId = ctx.user.store_id; @@ -2242,11 +2266,25 @@ class stockStoreService extends Service { enable_box_spec, box_unit, quantity_per_box, box_gross_weight, box_net_weight, box_length, box_width, box_height, box_volume, box_remark, id, + shelf_life_days, inbound_min_days, outbound_min_days, remaining_threshold_days, } = data; const prohibited_id_tmp = !prohibited_id ? null : parseInt(prohibited_id); // 1. 参数验证 this.validateSaveParams(data); + if (is_shelf_life_mgmt === 'Y') { + const shelfLifeFields = [ + [ 'shelf_life_days', shelf_life_days ], + [ 'inbound_min_days', inbound_min_days ], + [ 'outbound_min_days', outbound_min_days ], + [ 'remaining_threshold_days', remaining_threshold_days ], + ]; + const invalidShelfLifeFields = shelfLifeFields.filter(item => Number(item[1]) <= 0); + if (invalidShelfLifeFields.length > 0) { + throw new Error('启用保质期管理时,shelf_life_days、inbound_min_days、outbound_min_days、remaining_threshold_days 都必须存在且大于 0'); + } + } + let transaction; try { // 2. 开启事务 @@ -2265,7 +2303,6 @@ class stockStoreService extends Service { if (!stock_info) { throw new Error('商品不存在'); } - // 4. 准备更新数据 const updateData = { item_code, @@ -2297,6 +2334,10 @@ class stockStoreService extends Service { box_height, box_volume, box_remark, + shelf_life_days, + inbound_min_days, + outbound_min_days, + remaining_threshold_days, updated_at: new Date(), }; // 5. 清除空值 @@ -2715,6 +2756,15 @@ class stockStoreService extends Service { }); return { message: '删除成功', code: 200 }; } + /** + * 快捷搜索仓库商品并补全库存管理标记。 + * @param {Object} data 请求体 + * @param {string} [data.keyword] 搜索关键字 + * @param {number|string} [data.store_id] 货主ID + * @param {boolean} [data.with_stock=false] 是否返回关联库存数据 + * @param {boolean} [data.is_batch=false] with_stock=true 时是否按批次返回 + * @return {Promise} 搜索结果,data 为商品数组 + */ async search(data) { const { keyword, store_id = null, with_stock = false, is_batch = false } = data; const { ctx, app } = this; @@ -2789,6 +2839,10 @@ class stockStoreService extends Service { 'id', 'item_code', 'goods_code', 'item_name', 'sku_property', 'stock_unit', 'quantity', 'locked_quantity', 'brand_name', 'item_type', + 'inbound_min_days', 'outbound_min_days', + 'shelf_life_days', 'remaining_threshold_days', + 'is_batch_mgmt', + 'is_shelf_life_mgmt', ], order: [[ 'create_at', 'DESC' ]], limit: 50, @@ -2802,6 +2856,16 @@ class stockStoreService extends Service { // 提取所有条形码 result.barcodes = result.barcodes?.map(b => b.barcode) || []; + const batchMgmtValue = result.is_batch_mgmt; + result.is_batch_mgmt_enabled = typeof batchMgmtValue === 'boolean' + ? batchMgmtValue + : [ 'Y', '1', 'TRUE', 'T', 'YES' ].includes(String(batchMgmtValue).trim().toUpperCase()); + delete result.is_batch_mgmt; + + const shelfLifeMgmtValue = result.is_shelf_life_mgmt; + result.is_shelf_life_mgmt = typeof shelfLifeMgmtValue === 'boolean' + ? shelfLifeMgmtValue + : [ 'Y', '1', 'TRUE', 'T', 'YES' ].includes(String(shelfLifeMgmtValue).trim().toUpperCase()); return result; }); diff --git a/app/service/systems/storage/expiry.js b/app/service/systems/storage/expiry.js new file mode 100644 index 0000000..6048951 --- /dev/null +++ b/app/service/systems/storage/expiry.js @@ -0,0 +1,199 @@ +'use strict'; + +const Service = require('egg').Service; +const { parseWhereConditions } = require('../../../lib/query_condition_parser'); + +const DAY_MS = 24 * 60 * 60 * 1000; + +/** + * 库存有效期列表服务。 + * 以库存记录为主表,关联商品资料后按当前仓库与效期阈值规则分页查询。 + */ +class StorageExpiryService extends Service { + /** + * 查询库存有效期预警列表。 + * + * @param {Object} [where={}] 查询条件 + * @param {Object} [pageParams={}] 分页参数 + * @param {number} [pageParams.page=1] 当前页码 + * @param {number} [pageParams.pageSize=20] 每页条数 + * @return {Promise} 查询结果 + */ + async list(where = {}, pageParams = {}) { + const { ctx, app } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + + if (!warehouseId) { + return { + code: 400, + message: '当前用户未绑定仓库', + data: { + list: [], + pagination: { + page: 1, + pageSize: 20, + total: 0, + totalPages: 0, + hasPrevious: false, + hasNext: false, + }, + }, + }; + } + + const page = Math.max(Number(pageParams.page) || 1, 1); + const pageSize = Math.max(Number(pageParams.pageSize) || 20, 1); + const offset = (page - 1) * pageSize; + const { Op, literal } = app.Sequelize; + + const specialFieldMap = { + item_code: { + bucket: 'stock', + }, + goods_code: { + bucket: 'stock', + }, + item_name: { + bucket: 'stock', + }, + sku_property: { + bucket: 'stock', + }, + stock_unit: { + bucket: 'stock', + }, + is_shelf_life_mgmt: { + bucket: 'stock', + field: 'is_shelf_life_mgmt', + }, + remaining_threshold_days: { + bucket: 'stock', + }, + }; + + const parsed = ctx.whereParsed && Array.isArray(ctx.whereParsed.dynamicConditions) + ? ctx.whereParsed + : parseWhereConditions({ + where, + app, + specialFieldMap, + }).result; + + const dynamicConditions = Array.isArray(parsed.dynamicConditions) + ? parsed.dynamicConditions + : []; + const stockConditions = Array.isArray(parsed.bucketConditions && parsed.bucketConditions.stock) + ? parsed.bucketConditions.stock + : []; + + const storageWhere = { + [Op.and]: [ + { warehouse_id: warehouseId }, + { is_enabled: 1 }, + { delete_at: null }, + { quantity: { [Op.gt]: 0 } }, + { expiry_date: { [Op.ne]: null } }, + literal('DATEDIFF(`wms_storage`.`expiry_date`, CURDATE()) <= `stock`.`remaining_threshold_days`'), + ], + }; + + if (dynamicConditions.length > 0) { + storageWhere[Op.and].push({ [Op.and]: dynamicConditions }); + } + + const stockWhere = { + [Op.and]: [ + { is_valid: 'Y' }, + { delete_at: null }, + { warehouse_id: warehouseId }, + { is_shelf_life_mgmt: 'Y' }, + { remaining_threshold_days: { [Op.gt]: 0 } }, + ], + }; + + if (stockConditions.length > 0) { + stockWhere[Op.and].push({ [Op.and]: stockConditions }); + } + + const { count, rows } = await ctx.model.Storage.findAndCountAll({ + where: storageWhere, + include: [ + { + model: ctx.model.StockWarehouse, + as: 'stock', + required: true, + attributes: [ + 'id', + 'item_code', + 'goods_code', + 'item_name', + 'sku_property', + 'stock_unit', + 'store_id', + 'warehouse_id', + 'is_shelf_life_mgmt', + 'remaining_threshold_days', + ], + where: stockWhere, + }, + { + model: ctx.model.LocationSpace, + as: 'space', + required: false, + attributes: [ 'id', 'space_code', 'custom_name' ], + }, + ], + order: [ + [ 'expiry_date', 'ASC' ], + [ 'inbound_time', 'ASC' ], + [ 'id', 'ASC' ], + ], + offset, + limit: pageSize, + distinct: true, + subQuery: false, + }); + + const now = Date.now(); + const list = rows.map(row => { + const plain = row.get({ plain: true }); + const expiryTime = plain.expiry_date ? new Date(plain.expiry_date).getTime() : null; + const thresholdDays = Number(plain.stock && plain.stock.remaining_threshold_days) || 0; + const remainingDays = expiryTime === null || Number.isNaN(expiryTime) + ? null + : Math.max(0, Math.ceil((expiryTime - now) / DAY_MS)); + + return { + ...plain, + threshold_days: thresholdDays, + remaining_days: remainingDays, + is_expired: expiryTime !== null && !Number.isNaN(expiryTime) ? expiryTime < now : false, + created_at: plain.created_at ? app.formatDate(plain.created_at) : null, + updated_at: plain.updated_at ? app.formatDate(plain.updated_at) : null, + inbound_time: plain.inbound_time ? app.formatDate(plain.inbound_time) : null, + production_date: plain.production_date ? app.formatDate(plain.production_date) : null, + expiry_date: plain.expiry_date ? app.formatDate(plain.expiry_date) : null, + }; + }); + + const totalPages = pageSize > 0 ? Math.ceil(count / pageSize) : 0; + + return { + code: 200, + message: '查询成功', + data: { + list, + pagination: { + page, + pageSize, + total: count, + totalPages, + hasPrevious: page > 1, + hasNext: page < totalPages, + }, + }, + }; + } +} + +module.exports = StorageExpiryService; diff --git a/app/service/systems/storage/inventory.js b/app/service/systems/storage/inventory.js index 1e63294..148d35c 100644 --- a/app/service/systems/storage/inventory.js +++ b/app/service/systems/storage/inventory.js @@ -1,6 +1,204 @@ 'use strict'; const Service = require('egg').Service; +const DAY_MS = 24 * 60 * 60 * 1000; + +/** + * 计算库存批次的保质期预警状态。 + * + * @param {Object} stock 商品库存资料 + * @param {string|Date|null} expiryDate 批次到期日期 + * @param {number} [nowMs=Date.now()] 当前时间戳 + * @return {{remainingDays: (number|null), isTriggered: boolean}} 预警信息 + */ +function getShelfLifeWarningState(stock = {}, expiryDate = null, nowMs = Date.now()) { + const expiryTime = expiryDate ? new Date(expiryDate).getTime() : null; + const remainingDays = expiryTime === null || Number.isNaN(expiryTime) + ? null + : Math.max(0, Math.ceil((expiryTime - nowMs) / DAY_MS)); + const isShelfLifeMgmt = stock.is_shelf_life_mgmt === 'Y' || stock.is_shelf_life_mgmt === true; + const thresholdDays = Number(stock.remaining_threshold_days) || 0; + + return { + remainingDays, + isTriggered: Boolean(isShelfLifeMgmt && thresholdDays > 0 && remainingDays !== null && remainingDays <= thresholdDays), + }; +} + +/** + * 将库存商品上的标记值规范化为布尔值。 + * + * @param {unknown} value 待转换的标记值 + * @return {boolean} 是否为真值 + */ +function toBooleanFlag(value) { + if (typeof value === 'boolean') { + return value; + } + + if (typeof value === 'number') { + return value === 1; + } + + if (typeof value === 'string') { + return [ 'Y', '1', 'TRUE', 'T', 'YES' ].includes(value.trim().toUpperCase()); + } + + return false; +} + +/** + * 将模型查询结果转换为普通对象。 + * + * @param {unknown} record 模型记录或普通对象 + * @return {Object|null} 普通对象 + */ +function toPlainRecord(record) { + if (!record) { + return null; + } + + if (typeof record.get === 'function') { + return record.get({ plain: true }); + } + + return record; +} + +/** + * 批量加载库存商品的条码与图片附属信息。 + * + * @param {Object} ctx 当前请求上下文 + * @param {number[]} stockIds 商品ID列表 + * @return {Promise<{barcodesByStockId: Map, imagesByStockId: Map}>} 附属信息映射 + */ +async function loadStockAttachments(ctx, stockIds = []) { + const uniqueStockIds = [ ...new Set( + Array.isArray(stockIds) + ? stockIds.map(item => Number(item)).filter(Boolean) + : [] + ) ]; + + const barcodesByStockId = new Map(); + const imagesByStockId = new Map(); + + if (!uniqueStockIds.length) { + return { barcodesByStockId, imagesByStockId }; + } + + const hasStockBarcodeModel = ctx.model && ctx.model.StockBarcode && typeof ctx.model.StockBarcode.findAll === 'function'; + if (hasStockBarcodeModel) { + try { + const barcodeRows = await ctx.model.StockBarcode.findAll({ + where: { + stock_id: { + [ctx.app.Sequelize.Op.in]: uniqueStockIds, + }, + }, + attributes: [ 'stock_id', 'barcode' ], + raw: true, + }); + + for (const item of barcodeRows || []) { + const row = toPlainRecord(item); + if (!row) { + continue; + } + + const stockId = Number(row.stock_id); + const barcode = row.barcode ? String(row.barcode) : ''; + if (!stockId || !barcode) { + continue; + } + + if (!barcodesByStockId.has(stockId)) { + barcodesByStockId.set(stockId, []); + } + + barcodesByStockId.get(stockId).push(barcode); + } + } catch (error) { + ctx.logger?.warn?.('[storage.inventory] 查询商品条码失败,已降级为空数组', { + error: error.message, + }); + } + } + + const hasFileReferenceModel = ctx.model && ctx.model.FileReference && typeof ctx.model.FileReference.findAll === 'function'; + const hasFileModel = Boolean(ctx.model && ctx.model.File); + if (hasFileReferenceModel && hasFileModel) { + try { + const imageRows = await ctx.model.FileReference.findAll({ + where: { + business_type: 'stock', + business_id: { + [ctx.app.Sequelize.Op.in]: uniqueStockIds, + }, + }, + include: [{ + model: ctx.model.File, + as: 'file', + attributes: [ 'file_url' ], + required: false, + }], + }); + + for (const item of imageRows || []) { + const row = toPlainRecord(item); + if (!row) { + continue; + } + + const stockId = Number(row.business_id); + const imageUrl = (row.file && row.file.file_url) || row.file_url || row.url || row.file_path || ''; + if (!stockId || !imageUrl) { + continue; + } + + if (!imagesByStockId.has(stockId)) { + imagesByStockId.set(stockId, []); + } + + imagesByStockId.get(stockId).push(String(imageUrl)); + } + } catch (error) { + ctx.logger?.warn?.('[storage.inventory] 查询商品图片失败,已降级为空数组', { + error: error.message, + }); + } + } + + return { + barcodesByStockId, + imagesByStockId, + }; +} + +/** + * 为库存列表补充商品附属信息。 + * + * @param {Object} ctx 当前请求上下文 + * @param {Object[]} list 库存列表 + * @return {Promise} + */ +async function enrichInventoryStockAttachments(ctx, list = []) { + const stockIds = list.map(item => Number(item?.stock?.id || item?.stock_id || 0)).filter(Boolean); + const { barcodesByStockId, imagesByStockId } = await loadStockAttachments(ctx, stockIds); + + for (const item of list) { + const stockId = Number(item?.stock?.id || item?.stock_id || 0); + if (!stockId) { + continue; + } + + if (!item.stock) { + item.stock = {}; + } + + item.stock.barcodes = barcodesByStockId.get(stockId) || []; + item.stock.images = imagesByStockId.get(stockId) || []; + } +} class InventoryService extends Service { @@ -169,7 +367,9 @@ class InventoryService extends Service { // 5c. 写入/更新 wms_storage 库存位置表 const spaceId = detail.space_id || 1; // 明细有库位则用,否则默认库位 - const batchNo = detail.batch_number || receiving.receiving_number || entryOrderCode; + const batchNo = String(detail.batch_number || '').trim() || String(receiving.receiving_number || '').trim() || entryOrderCode; + const productionDate = detail.production_date || null; + const expiryDate = detail.expiry_date || null; const inventoryType = 'ZP'; // 默认正品 // 查找是否已有相同 库位+SKU+批次+类型 的库存记录 @@ -192,6 +392,10 @@ class InventoryService extends Service { quantity: app.Sequelize.literal(`quantity + ${inboundQty}`), available_quantity: app.Sequelize.literal(`available_quantity + ${inboundQty}`), entry_order_id: entryOrder.id, + batch_no: batchNo, + production_date: productionDate, + expiry_date: expiryDate, + updated_at: new Date(), }, { where: { id: storageRecord.id }, transaction, @@ -208,8 +412,8 @@ class InventoryService extends Service { quantity: inboundQty, locked_quantity: 0, available_quantity: inboundQty, - production_date: detail.production_date || null, - expiry_date: detail.expiry_date || null, + production_date: productionDate, + expiry_date: expiryDate, inbound_time: new Date(), inbound_order_no: entryOrderCode, receiving_id: receivingId, @@ -1730,14 +1934,24 @@ class InventoryService extends Service { } /** - * 库存列表查询。 - * @param {Object} pageParams 分页参数 - * @param {Object} sortParams 排序参数 - * @param {boolean} groupByBatch 是否按批次 + * 查询库存列表。 + * + * 支持按批次明细或合并模式返回库存,并补充商品条码、图片附件、保质期预警和货主名称。 + * 货主名称来源于货主签约表的 store_remask 字段,最终以 stock.store_name 输出。 + * + * @param {Object} [pageParams={}] 分页参数 + * @param {number} [pageParams.page=1] 页码 + * @param {number} [pageParams.pageSize=20] 每页数量 + * @param {Object} [sortParams={}] 排序参数 + * @param {string} [sortParams.sortField='created_at'] 排序字段 + * @param {string} [sortParams.sortOrder='DESC'] 排序方向 + * @param {boolean} [groupByBatch=false] 是否按批次明细返回 + * @return {Promise<{list: Object[], pagination: {page: number, pageSize: number, total: number, totalPages: number}}>} 库存列表结果 */ async getInventoryList(pageParams = {}, sortParams = {}, groupByBatch = false) { const { ctx, app } = this; const { Op, fn, col, literal } = app.Sequelize; + const nowMs = Date.now(); const warehouseId = ctx.user.store_id; const { page = 1, pageSize = 20 } = pageParams; @@ -1772,7 +1986,24 @@ class InventoryService extends Service { { model: ctx.model.StockWarehouse, as: 'stock', - attributes: [ 'id', 'item_code', 'item_name', 'sku_property', 'stock_unit' ], + attributes: [ + 'id', + 'item_code', + 'item_name', + 'sku_property', + 'stock_unit', + 'is_batch_mgmt', + 'is_shelf_life_mgmt', + 'remaining_threshold_days', + ], + include: [ + { + model: ctx.model.StoreWarehouse, + as: 'store_stock', + attributes: [ 'store_id', 'store_remask' ], + required: false, + }, + ], required: false, }, { @@ -1786,14 +2017,24 @@ class InventoryService extends Service { const list = rows.map(item => { const row = item.get({ plain: true }); + const shelfLifeWarningState = getShelfLifeWarningState(row.stock || {}, row.expiry_date, nowMs); + if (row.stock) { + row.stock.is_batch_mgmt_enabled = toBooleanFlag(row.stock.is_batch_mgmt); + row.stock.store_name = row.stock.store_stock?.store_remask || null; + delete row.stock.store_stock; + delete row.stock.is_batch_mgmt; + } row.created_at = row.created_at ? app.formatDate(row.created_at) : ''; row.updated_at = row.updated_at ? app.formatDate(row.updated_at) : ''; row.inbound_time = row.inbound_time ? app.formatDate(row.inbound_time) : ''; row.production_date = row.production_date ? app.formatDate(row.production_date) : ''; row.expiry_date = row.expiry_date ? app.formatDate(row.expiry_date) : ''; + row.is_shelf_life_warning_triggered = shelfLifeWarningState.isTriggered; return row; }); + await enrichInventoryStockAttachments(ctx, list); + return { list, pagination: { @@ -1822,6 +2063,8 @@ class InventoryService extends Service { 'inventory_type', 'warehouse_id', 'store_id', + [ fn('MIN', col('wms_storage.production_date')), 'production_date' ], + [ fn('MIN', col('wms_storage.expiry_date')), 'expiry_date' ], [ fn('SUM', col('wms_storage.quantity')), 'quantity' ], [ fn('SUM', col('wms_storage.locked_quantity')), 'locked_quantity' ], [ fn('SUM', col('wms_storage.available_quantity')), 'available_quantity' ], @@ -1837,7 +2080,24 @@ class InventoryService extends Service { { model: ctx.model.StockWarehouse, as: 'stock', - attributes: [ 'id', 'item_code', 'item_name', 'sku_property', 'stock_unit' ], + attributes: [ + 'id', + 'item_code', + 'item_name', + 'sku_property', + 'stock_unit', + 'is_batch_mgmt', + 'is_shelf_life_mgmt', + 'remaining_threshold_days', + ], + include: [ + { + model: ctx.model.StoreWarehouse, + as: 'store_stock', + attributes: [ 'store_id', 'store_remask' ], + required: false, + }, + ], required: false, }, { @@ -1852,11 +2112,23 @@ class InventoryService extends Service { }); const list = rows.map(row => { + const shelfLifeWarningState = getShelfLifeWarningState(row.stock || {}, row.expiry_date, nowMs); + if (row.stock) { + row.stock.is_batch_mgmt_enabled = toBooleanFlag(row.stock.is_batch_mgmt); + row.stock.store_name = row.stock.store_stock?.store_remask || null; + delete row.stock.store_stock; + delete row.stock.is_batch_mgmt; + } row.first_inbound_time = row.first_inbound_time ? app.formatDate(row.first_inbound_time) : ''; row.last_inbound_time = row.last_inbound_time ? app.formatDate(row.last_inbound_time) : ''; + row.production_date = row.production_date ? app.formatDate(row.production_date) : ''; + row.expiry_date = row.expiry_date ? app.formatDate(row.expiry_date) : ''; + row.is_shelf_life_warning_triggered = shelfLifeWarningState.isTriggered; return row; }); + await enrichInventoryStockAttachments(ctx, list); + return { list, pagination: { diff --git a/app/service/systems/storage/receiving.js b/app/service/systems/storage/receiving.js index cce6937..59095af 100644 --- a/app/service/systems/storage/receiving.js +++ b/app/service/systems/storage/receiving.js @@ -2,6 +2,31 @@ const Service = require('egg').Service; const { parseWhereConditions } = require('../../../lib/query_condition_parser'); +const DAY_MS = 24 * 60 * 60 * 1000; + +function getStartOfDayMs(value) { + const date = new Date(value); + if (Number.isNaN(date.getTime())) return null; + date.setHours(0, 0, 0, 0); + return date.getTime(); +} + +/** + * 判断到期日期是否早于当前日期。 + * @param {string|Date|number} expiryDate 到期日期 + * @param {Date} [currentDate=new Date()] 当前日期 + * @return {boolean} 是否已过期 + */ +function isExpiryDateBeforeToday(expiryDate, currentDate = new Date()) { + const expiryStartMs = getStartOfDayMs(expiryDate); + if (expiryStartMs === null) return false; + + const currentStartMs = getStartOfDayMs(currentDate); + if (currentStartMs === null) return false; + + return expiryStartMs < currentStartMs; +} + class ReceivingService extends Service { /** * 查询收货单列表。 @@ -1936,8 +1961,8 @@ class ReceivingService extends Service { } } /** - * 修改收货明细信息并触发库存/统计联动。 - * @param {Object} data 请求体 + * 修改收货明细。 + * @param {Object} data 收货明细修改参数 * @return {Promise} 修改结果 */ async detailChange(data) { @@ -2006,6 +2031,13 @@ class ReceivingService extends Service { }; } + if (expiry_date !== undefined && isExpiryDateBeforeToday(expiry_date)) { + return { + code: 400, + message: '到期日期已过期,不能录入收货', + }; + } + // 5. 验证箱规数据 if (box_quantity !== undefined && box_quantity < 0) { return { @@ -2763,6 +2795,21 @@ class ReceivingService extends Service { 'box_quantity', 'pallet_quantity', 'receiving_status', 'storage_status', 'batch_number', 'production_date', 'expiry_date', 'remark', ], + include: [{ + model: ctx.model.StockWarehouse, + as: 'system_product', + required: false, + attributes: [ + 'id', + 'item_name', + 'item_code', + 'is_batch_mgmt', + 'is_shelf_life_mgmt', + 'inbound_min_days', + 'shelf_life_days', + 'remaining_threshold_days', + ], + }], }], }); @@ -2821,6 +2868,80 @@ class ReceivingService extends Service { }; } + const batchManagedDetails = receiving.details.filter(detail => detail.system_product && detail.system_product.is_batch_mgmt === 'Y'); + const missingBatchNumberDetails = batchManagedDetails.filter(detail => !String(detail.batch_number || '').trim()); + + if (missingBatchNumberDetails.length > 0) { + await transaction.rollback(); + return { + success: false, + code: 'BATCH_NUMBER_REQUIRED', + message: '批次管理商品必须填写批次号', + data: { + invalid_details: missingBatchNumberDetails.map(detail => ({ + detail_id: detail.id, + item_name: detail.product_name || detail.system_product?.item_name || '未命名商品', + batch_number: detail.batch_number || '', + production_date: detail.production_date || null, + expiry_date: detail.expiry_date || null, + })), + }, + }; + } + + const missingBatchDetails = batchManagedDetails.filter(detail => !detail.production_date || !detail.expiry_date); + + if (missingBatchDetails.length > 0) { + await transaction.rollback(); + return { + success: false, + code: 'PRODUCTION_DATE_REQUIRED', + message: '批次管理商品必须填写生产日期和有效期', + data: { + invalid_details: missingBatchDetails.map(detail => ({ + detail_id: detail.id, + item_name: detail.product_name || detail.system_product?.item_name || '未命名商品', + batch_number: detail.batch_number || '', + production_date: detail.production_date || null, + expiry_date: detail.expiry_date || null, + })), + }, + }; + } + + const todayStartMs = getStartOfDayMs(new Date()); + const invalidExpiryDetails = batchManagedDetails.filter(detail => { + const minReceiveDays = Number(detail.system_product?.inbound_min_days) || 0; + if (minReceiveDays <= 0) return false; + + const expiryTime = new Date(detail.expiry_date).getTime(); + if (Number.isNaN(expiryTime)) return false; + + return (expiryTime - (minReceiveDays * DAY_MS)) < todayStartMs; + }); + + if (invalidExpiryDetails.length > 0) { + await transaction.rollback(); + const firstInvalid = invalidExpiryDetails[0]; + const minReceiveDays = Number(firstInvalid.system_product?.inbound_min_days) || 0; + + return { + success: false, + code: 'EXPIRY_DATE_TOO_SOON', + message: `商品“${firstInvalid.product_name || firstInvalid.system_product?.item_name || '未命名商品'}”的有效期不足最小允许收货天数(${minReceiveDays}天),无法完成收货`, + data: { + invalid_details: invalidExpiryDetails.map(detail => ({ + detail_id: detail.id, + item_name: detail.product_name || detail.system_product?.item_name || '未命名商品', + batch_number: detail.batch_number || '', + production_date: detail.production_date || null, + expiry_date: detail.expiry_date || null, + inbound_min_days: Number(detail.system_product?.inbound_min_days) || 0, + })), + }, + }; + } + // 5. 准备明细图片与统计信息(照片/条码/重量不再强制要求) const unmatchedDetails = receiving.details.filter(d => !d.system_product_id); const detailsIds = receiving.details.map(item => item.id); diff --git a/app/service/systems/store.js b/app/service/systems/store.js index 0b8291c..4e4cc47 100644 --- a/app/service/systems/store.js +++ b/app/service/systems/store.js @@ -10,6 +10,8 @@ class StoreService extends Service { return { max_notice_webhook_count: 5, + default_express_code: 'STO', + default_platform_code: 'TB', }; } diff --git a/app/service/systems/store_warehouse.js b/app/service/systems/store_warehouse.js index 61c15fb..2b5aa8e 100644 --- a/app/service/systems/store_warehouse.js +++ b/app/service/systems/store_warehouse.js @@ -257,6 +257,19 @@ class SettingStoreWarehouseService extends Service { return storeWarehouseModel.getPolicyConfigFieldList(); } + /** + * 获取带动态选项的策略配置字段清单。 + * + * @return {Promise} 策略配置字段数组。 + */ + async getPolicyConfigFieldMetaList() { + const storeWarehouseModel = this.ctx.model && this.ctx.model.StoreWarehouse; + if (!storeWarehouseModel || typeof storeWarehouseModel.getPolicyConfigFieldListWithOptions !== 'function') { + return this.getPolicyConfigFieldList(); + } + return storeWarehouseModel.getPolicyConfigFieldListWithOptions(); + } + /** * 规范化策略配置内容。 * @@ -1711,7 +1724,7 @@ class SettingStoreWarehouseService extends Service { async getPolicyConfigFields() { return { code: 200, - data: this.getPolicyConfigFieldList(), + data: await this.getPolicyConfigFieldMetaList(), }; } diff --git a/config/plugin.js b/config/plugin.js index a827fec..f7f051c 100644 --- a/config/plugin.js +++ b/config/plugin.js @@ -15,8 +15,10 @@ module.exports = { package: 'egg-jwt', }, sequelize: { - // disable real database connection during unit tests - enable: process.env.NODE_ENV !== 'test', + // disable real database connection during unit tests unless opt-in (see order_delivery_dispatch_factory.test.js) + enable: + process.env.NODE_ENV !== 'test' || + process.env.DISPATCH_FACTORY_TEST_MYSQL === '1', package: 'egg-sequelize', }, cors: { diff --git a/config/poloapi.js b/config/poloapi.js deleted file mode 100644 index 934c491..0000000 --- a/config/poloapi.js +++ /dev/null @@ -1,29 +0,0 @@ -// config/poloapi.js -// 快手/PolyAPI相关固定配置 - -module.exports = { - appKey: '8e770a60b9684c558f40e4796a96710f', - appSecret: 'c9cb1df531b441a8872c60ffb7f900a6', - platid: '633', - version: '1.5', - contenttype: 'json', - urls: 'https://api.polyapi.com/openapi/do', - // 快递公司代码映射 - postCodeMap: { - p01: 'YTO', - p02: 'STO', - p03: 'YUNDA', - p04: 'ZTO', - p05: 'SF', - p06: 'TTKDEX', - p07: 'EMS', - p10: 'JD', - p22: 'POSTB', - p35: 'POST_DSBK', - p09: 'huitongkuaidi', - p26: 'debangwuliu', - p32: 'JT', - p34: 'FENGWANG', - }, - // 如有更多固定配置,可继续补充 -}; diff --git a/database/migrations/20260410130000-add-audit-status-to-order-delivery-tables.js b/database/migrations/20260410130000-add-audit-status-to-order-delivery-tables.js index 6f06972..9af7483 100644 --- a/database/migrations/20260410130000-add-audit-status-to-order-delivery-tables.js +++ b/database/migrations/20260410130000-add-audit-status-to-order-delivery-tables.js @@ -5,7 +5,7 @@ module.exports = { * 为发货单主表及分表新增 audit_status 字段。 * 若存在 inspection_status,则将 audit_status 放在其后;否则按默认位置新增,保证兼容旧库结构。 * @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口 - * @returns {Promise} 无返回值 + * @return {Promise} 无返回值 */ async up(queryInterface) { const [ tables ] = await queryInterface.sequelize.query(` @@ -54,7 +54,7 @@ module.exports = { * 回滚删除发货单主表及分表的 audit_status 字段。 * 仅在字段存在时删除,保证回滚幂等且安全。 * @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口 - * @returns {Promise} 无返回值 + * @return {Promise} 无返回值 */ async down(queryInterface) { const [ tables ] = await queryInterface.sequelize.query(` @@ -85,4 +85,4 @@ module.exports = { } } }, -}; \ No newline at end of file +}; diff --git a/database/migrations/20260410150000-replace-audit-status-with-step-on-order-delivery-tables.js b/database/migrations/20260410150000-replace-audit-status-with-step-on-order-delivery-tables.js index d6955a0..96fda06 100644 --- a/database/migrations/20260410150000-replace-audit-status-with-step-on-order-delivery-tables.js +++ b/database/migrations/20260410150000-replace-audit-status-with-step-on-order-delivery-tables.js @@ -48,7 +48,7 @@ module.exports = { * 为发货单主表及分表新增 step 字段,并从 audit_status 回填后删除 audit_status。 * * @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。 - * @returns {Promise} 无返回值。 + * @return {Promise} 无返回值。 */ async up(queryInterface) { const tables = await findOrderDeliveryTables(queryInterface); @@ -86,7 +86,7 @@ module.exports = { * 回滚恢复 audit_status 字段,并根据 step 回填后删除 step。 * * @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。 - * @returns {Promise} 无返回值。 + * @return {Promise} 无返回值。 */ async down(queryInterface) { const tables = await findOrderDeliveryTables(queryInterface); diff --git a/database/migrations/20260410200000-add-status-columns-to-wms-order-delivery-base.js b/database/migrations/20260410200000-add-status-columns-to-wms-order-delivery-base.js index 1e29cdb..86bfa5a 100644 --- a/database/migrations/20260410200000-add-status-columns-to-wms-order-delivery-base.js +++ b/database/migrations/20260410200000-add-status-columns-to-wms-order-delivery-base.js @@ -79,10 +79,10 @@ const STATUS_MACHINE_COLUMNS = [ ]; /** - * @param {import('sequelize').QueryInterface} queryInterface - * @param {string} tableName - * @param {string} columnName - * @return {Promise} + * @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。 + * @param {string} tableName 数据表名。 + * @param {string} columnName 字段名。 + * @return {Promise} 是否存在指定字段。 */ async function hasColumn(queryInterface, tableName, columnName) { const [ columns ] = await queryInterface.sequelize.query( @@ -99,9 +99,9 @@ async function hasColumn(queryInterface, tableName, columnName) { } /** - * @param {import('sequelize').QueryInterface} queryInterface - * @param {string} tableName - * @return {Promise} + * @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。 + * @param {string} tableName 数据表名。 + * @return {Promise} 数据表是否存在。 */ async function tableExists(queryInterface, tableName) { const [ rows ] = await queryInterface.sequelize.query( @@ -117,10 +117,10 @@ async function tableExists(queryInterface, tableName) { } /** - * @param {import('sequelize').QueryInterface} queryInterface - * @param {string} tableName - * @param {string} preferredAfter - * @return {Promise} + * @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。 + * @param {string} tableName 数据表名。 + * @param {string} preferredAfter 优先追加到其后的字段名。 + * @return {Promise} 可直接拼接到 SQL 中的 AFTER 片段,或空字符串。 */ async function resolveAfterClause(queryInterface, tableName, preferredAfter) { if (preferredAfter && (await hasColumn(queryInterface, tableName, preferredAfter))) { @@ -133,8 +133,8 @@ module.exports = { /** * 仅为基表 `wms_order_delivery` 按需补状态机相关列;已存在则跳过。 * - * @param {import('sequelize').QueryInterface} queryInterface - * @returns {Promise} + * @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。 + * @return {Promise} 无返回值。 */ async up(queryInterface) { if (!(await tableExists(queryInterface, TABLE))) { @@ -155,8 +155,8 @@ module.exports = { /** * 逆序删除本文件声明的状态机列(若存在)。见文件头注释。 * - * @param {import('sequelize').QueryInterface} queryInterface - * @returns {Promise} + * @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。 + * @return {Promise} 无返回值。 */ async down(queryInterface) { if (!(await tableExists(queryInterface, TABLE))) { diff --git a/database/migrations/20260415000000-init-wms-store-subject-config-default-codes.js b/database/migrations/20260415000000-init-wms-store-subject-config-default-codes.js new file mode 100644 index 0000000..1b706a2 --- /dev/null +++ b/database/migrations/20260415000000-init-wms-store-subject-config-default-codes.js @@ -0,0 +1,32 @@ +'use strict'; + +module.exports = { + async up(queryInterface) { + const [ columns ] = await queryInterface.sequelize.query("SHOW COLUMNS FROM `wms_store` LIKE 'subject_config'"); + if (columns.length === 0) { + return; + } + + await queryInterface.sequelize.query(` + UPDATE wms_store + SET subject_config = JSON_INSERT( + COALESCE(subject_config, JSON_OBJECT()), + '$.default_express_code', 'STO', + '$.default_platform_code', 'TB' + ) + `); + }, + + async down(queryInterface) { + const [ columns ] = await queryInterface.sequelize.query("SHOW COLUMNS FROM `wms_store` LIKE 'subject_config'"); + if (columns.length === 0) { + return; + } + + await queryInterface.sequelize.query(` + UPDATE wms_store + SET subject_config = JSON_REMOVE(subject_config, '$.default_express_code', '$.default_platform_code') + WHERE subject_config IS NOT NULL + `); + }, +}; diff --git a/database/migrations/20260415172000-create-wms-express-interface.js b/database/migrations/20260415172000-create-wms-express-interface.js new file mode 100644 index 0000000..0ddde60 --- /dev/null +++ b/database/migrations/20260415172000-create-wms-express-interface.js @@ -0,0 +1,74 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + const { INTEGER, STRING } = Sequelize; + + const [ tables ] = await queryInterface.sequelize.query( + "SHOW TABLES LIKE 'wms_express_interface'" + ); + + if (tables.length > 0) { + console.log('Table wms_express_interface already exists, skipping creation'); + return; + } + + await queryInterface.createTable('wms_express_interface', { + id: { + type: INTEGER(10), + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '接口ID', + }, + interface_url: { + type: STRING(500), + allowNull: false, + comment: '外部接口URL', + }, + platform_code: { + type: STRING(50), + allowNull: false, + comment: '平台代码,用于应用分流', + }, + interface_name: { + type: STRING(200), + allowNull: false, + comment: '接口名称', + }, + }, { + engine: 'InnoDB', + charset: 'utf8mb4', + collate: 'utf8mb4_unicode_ci', + comment: '快递外部接口配置表', + }); + + const safeCreateIndex = async (tableName, fields, options) => { + const [ existingIndexes ] = await queryInterface.sequelize.query( + `SHOW INDEX FROM ${tableName} WHERE Key_name = '${options.name}'` + ); + + if (existingIndexes.length === 0) { + await queryInterface.addIndex(tableName, fields, options); + } + }; + + await safeCreateIndex('wms_express_interface', [ 'platform_code' ], { + name: 'idx_platform_code', + }); + + await safeCreateIndex('wms_express_interface', [ 'interface_name' ], { + name: 'idx_interface_name', + }); + }, + + async down(queryInterface) { + const [ tables ] = await queryInterface.sequelize.query( + "SHOW TABLES LIKE 'wms_express_interface'" + ); + + if (tables.length > 0) { + await queryInterface.dropTable('wms_express_interface'); + } + }, +}; diff --git a/database/migrations/20260415190000-create-wms-picking.js b/database/migrations/20260415190000-create-wms-picking.js new file mode 100644 index 0000000..363949d --- /dev/null +++ b/database/migrations/20260415190000-create-wms-picking.js @@ -0,0 +1,118 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + const { BIGINT, STRING, DATE } = Sequelize; + const tableName = 'wms_picking'; + + const [ tables ] = await queryInterface.sequelize.query( + `SHOW TABLES LIKE '${tableName}'` + ); + + if (tables.length === 0) { + await queryInterface.createTable(tableName, { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '订单ID', + }, + order_item_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '订单明细ID', + }, + storage_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '库存记录ID', + }, + space_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '库位ID', + }, + space_name: { + type: STRING(100), + allowNull: true, + comment: '库位名称', + }, + status: { + type: STRING(20), + allowNull: false, + defaultValue: 'pending', + comment: '状态', + }, + created_at: { + type: DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + }, { + engine: 'InnoDB', + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + comment: '订单储位分配表', + }); + } else { + console.log('Table wms_picking already exists, ensuring indexes'); + } + + const safeCreateIndex = async (fields, options) => { + const [ existingIndexes ] = await queryInterface.sequelize.query( + `SHOW INDEX FROM ${tableName} WHERE Key_name = '${options.name}'` + ); + if (existingIndexes.length === 0) { + await queryInterface.addIndex(tableName, fields, options); + } + }; + + await safeCreateIndex([ 'order_id' ], { + name: 'idx_wms_picking_order_id', + }); + + await safeCreateIndex([ 'order_item_id' ], { + name: 'idx_wms_picking_order_item_id', + }); + + await safeCreateIndex([ 'storage_id' ], { + name: 'idx_wms_picking_storage_id', + }); + + await safeCreateIndex([ 'space_id' ], { + name: 'idx_wms_picking_space_id', + }); + + await safeCreateIndex([ 'status' ], { + name: 'idx_wms_picking_status', + }); + + await safeCreateIndex([ 'order_item_id', 'space_id' ], { + name: 'idx_wms_picking_order_item_space', + }); + }, + + async down(queryInterface) { + const tableName = 'wms_picking'; + const [ tables ] = await queryInterface.sequelize.query( + `SHOW TABLES LIKE '${tableName}'` + ); + + if (tables.length > 0) { + await queryInterface.dropTable(tableName); + } + }, +}; diff --git a/database/migrations/20260415191000-add-quantity-to-wms-picking.js b/database/migrations/20260415191000-add-quantity-to-wms-picking.js new file mode 100644 index 0000000..422fdbb --- /dev/null +++ b/database/migrations/20260415191000-add-quantity-to-wms-picking.js @@ -0,0 +1,32 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + const tableName = 'wms_picking'; + const { INTEGER } = Sequelize; + + const [ quantityColumns ] = await queryInterface.sequelize.query( + `SHOW COLUMNS FROM \`${tableName}\` LIKE 'quantity'` + ); + + if (quantityColumns.length === 0) { + await queryInterface.addColumn(tableName, 'quantity', { + type: INTEGER(10).UNSIGNED, + allowNull: false, + defaultValue: 1, + comment: '分配数量', + }); + } + }, + + async down(queryInterface) { + const tableName = 'wms_picking'; + const [ quantityColumns ] = await queryInterface.sequelize.query( + `SHOW COLUMNS FROM \`${tableName}\` LIKE 'quantity'` + ); + + if (quantityColumns.length > 0) { + await queryInterface.removeColumn(tableName, 'quantity'); + } + }, +}; diff --git a/day.log b/day.log deleted file mode 100644 index 2031b050e23e72ced46177106b69ae19c812d15c..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 37706 zcmeI53v^v&o#^)wDT$;J=h4v!i;Z`#L?q2Ak19pD7OYTd_sKaYZ5q;?q&Yo3sY%n) zG^Z~~p;m1tEeS#&pn}{b!dmw__O5%qv$(D$=n`CL z|LuRie&0TiG)2a_t~D#G&B;D{e~f77Cwr|-=yUN$P{3%GR7f7(X^5_5a*s|H|jWQGKT`MbR&P0-Z49U0r<$H^_52xqu=h;*1zL@#>*i)k~4?c7E z-uCl@^ZL*EmgCt|W0&^YRUNtezO?UUWM>P#k9bSv_gsO*YJquS_oDRH zL$8)}HD5?A-Scwogf{jZjm^=v2%?+3yB{@jTgaYax+8HTJ`7IZe70I#(!pz2IV%{8sApyGR;MY9z!eC$u0dH>dyG_CorlY(u#8K#*!|e`Qo@gw+oTe&GL&f+<4>7xY~| zH4hSIuTTnfhD>uM&Oa6|E<#5OcD!R{HF{CVDZQ~5=*q5MrO3x*=92sq=`nHl_{qY{ z6SFc~H~z&yN7vT|_O|HkEQ<;l!Gz&Slvf)3>a9L3j@RGrK6bZF_ZvD?OhdtrMD9 zE&D)@AQ_Na@X?7i-`;c1CwG;O6&~(`hpaUGm+{N)van|U>9`Wcdj5ujhik^ZK7ke>VU50}I!kzs*AM$IBDRY|pWX%HW;4 z@ZtPR*~Wk;p+U6|fGt`T$%Onz*Z#8S;)yS2ZXa(7RX(~@jXtQ9Dd;S;F!)77H44SW zb+7Lsof|^ddpvuh^l<*1z0D)LqWPZM^IJ!9u@ctUzZ+fjw*#+rHHClOhn(Il)H^Kl zY`x5(y09nujr>(jxmD(Fm4DUl#NJW8AHPQ>H@d+c+4r8wiuUWBmClh z;Wnhi1ru8jz1CH{&Egoz3lCsxEnEkGHwMp-e!lofuy$ipWRulL5Z@$YZIDlPH!ZTe ze8kP`gvMHA7koD$atB)5JSDm7Lh#I(|7%QfIMeaaY|M$YEy!qCTS(x#5J)$!d1|yV zc(wa2Q$zF7%(vUb^pO;lzHR zxM0V;&Wn7cNK<%i(7(Ge0PZ(+Aln<)3~h1mwUCBV+;0lI+a7cw?BYtbl48zMOOMdR zT7gMHU|?)U`&4TL|5}u$@N+Q$y}X|5ceMYTKWmRr!z!VYP0`wrLtxQeg=&7Rs-oZ- znY%W^a#Lvh1-u1(g{1fn^W=YiTI9~v^3zhmQ7xxo#HaOT6k85a?pY-|eNbRJJhi$= zp38H-H`)DK*Wuy%V*hTWJ@_i+uye3+n!;*aTRwgwIg`73PVbAo`QA+(E4r{(%15*K zZ2z6P|#k4leiXbK1Vp3T?t zyL|8bpg;Yx*!tx<0UxuJyDwc3i(glKX2|&-Hr=^H%d!iy9UWF0DEwUy&-aY3v)mnD zK^)dg9r)rMTFGp<4BOyyDZFJgfr||w;ZlS9Ecywr)8fee7Mg@-)(X#5zr#GgSng8| zR{cKafQE-_j58v#-%xpW>fVtV-Te`n*VVG^Q#8vu_;;^RCw3GPyfOIJo}YG^Z{Qyy z0+qJvj{Uc{|3d&*mfM%-2ak3A@tPlx7t*hcF4_Hq{DQ4@;q~72BIU4XuPHQ-l-rnS z86=8&E_jFyAvWcuy(iY(-f3xs7zkb|o-MQcqWv}qCVi2VBl1}#L`i-h2^Iw2#Ovw* zxiQgO7cLS%K;tDh%3i?O0=Z{iv?9FW^8+s^3@pq3(?)zGMxWRDANM_&J-WPN7)^=%NG z8as=f{&ZAUC49aha4FNhyH)m5-9KhdwE*Jx8>{7P?SV6mR}`2I$u8sk*%ITj7TM!a zWa;5+!$asl^)t>izDxV)y0tQw%fT%&np&{xg}UP^>>Jt(11ei*Vh^8LnkABPE3qXI z+g~tyeBZ8~KkaEAu~d6`@sff1{GEGl7}WXW9tf6cxi2nWTmU~_=<@{Bbh2RAAAkNL ze^&`wLmM=N5+4lkyNKE0(^z^vM|ix_pHTZ2zY`mBj`$>Cf`32_nGDr)7kZ{#N~+Ap zv&;+TeeaR{{7k>ZuS{$PkHkDrlu1{kbg9qY6lq$trp6GVXfql!HiXS1cLi|5vEuog z%~%$;I*LmPtOH-Al)EVN-Of2#o_RL^t8sLd%SZ8NTs>|rYfF{oce{Ejem`*2IFWk~ ze)0>0XgxG-V{qNBAC=tIOs9XR({jFto@Z>MhiA4@7Zb=DJe+g0?-&1go>-Q?cbQo5 z-yTgQu`fRm{avmxR~26^Sv2^^*R*_hT;+sg954?#0GQm<8WtvKvl9QxH8Nio8iyxgq+5A7x`1t0UVD zDY8-MnLE)GuKZL>+@0^@kqi1txu2vuN8tUqEN3S55z*{uDC~Y@q=iz8tOS3KwPA0o zG*qgGkG){-{tsjh7Yv8$+`wy~LjRaZFWl;j_1Z2GVq%zcBx=yy@%Sk5r#OGlilQ0B z`F)S4zAt!M8m(s_;=|36PF=Qg!Pc9ykBkzB`j|v5Q(_1E-fj0knjw~I=NUQFckqg# z=Zh{~8%YqS9;~y=ro0P0Sl`3<0+y_zTv9MbQzze`4V%JBSs}4*Sv665D?eIA$Ez#} zBIp(*4nLE-S|e<1_AG59V+{PtCE&9ImkCr{o)arNd(%eNOqArg?B;z~P$_{Mkza7| zo3R@PT^i!v{`7|LXaBtW*V%J&A6{7({=EB<)IWD!wo_w^zs^3A`uW(Cy=Elc z5%(a04)q<)_8lZ5#~zoh^m_0_T0O4w$%P|vuM1bd=XUNa$I0yWUv0%ZtIpBB_q{B# z;_2~!aIz9_nOG_wl#5$risgXAkMil)0`Xe@y03oXANv|YFk$b|Z=sKmPQ{`XhUL-?T>+K3b7{Q)xol!$X+#$d zA+em3g=-J=4M3-*9QL~lWya7LXM7x1h8C&MLjxy9znoJ#UD5Suo23!-1mBMwTADe& z4Vn4M*b9U2+JAh^g(G(nIqm3r@AfN#zWkEi#H;_g>%^VAN~v|<+0(!L;l6k6uM3Il z6aNPm_|))?A9(^q{*m!WTzJ8k--g}|r9qqB6;_e!&$H5cp(R&h``(B8-`=CPMO>Pe z-|1>VwB7d)eW+h8gYr3aG#3KMoarbA z$eDPBO6VUGu*-pElQ9DL<|i$lu1YI~zVkhZ=j% z-8uWHjom~NX?uV1`oKG=^&NOLzZiXG6uXvOnvR7uTPRtkxQ~a`3*5=C_#V~^Su-?Y zMy`;vMLYfRjul-Hl{@3|ce6E7lagUlgU zjr_qc<+rKN!6IxP`R%>O_qnU6jBRLErIN0QU?h@I*WqD_+a<|i5{Fx|TVfi)CnSDw zX|J_LOnjn}lCiO&W|tB*P5^{$tgThnZg`+Yu0uu0VN+w$D^(`Pv-NpwH_fE>PQgLz zpXNHxqieB3G#iNy_)zRhAfqD}ua7WA1pLMEhsCn6T5nj{dd-YwzQvki6eJt4(%Jab8hNSgBSbWTnPsVdNnqW0y{RTB;{@Oe_@-{1%DzbVgM#*B;2N`2L}_2i!fY)!r*s z%tBdRyTD7cP>ha+fYmi8i>0C2d8~c1<~oLrx>$(%9&ohPI4(WBINmg&H9DHR(s_|I zY6bYGcPG&c2TL~!Yz&s+3PUrj@`AnxGgR@IXMOL_Bn#^9@zmHg1wZr3{;v+(teJX9 zYQL!DQ`xds{8uA07EG;%S#*Y8@hEQ*jJQuLmCWpEY~lFRN(VE0dfwEtKwV>+#7o_J zA<1%AsWZ?FR(>xGCX{de{|cFKa$E_MtZOSu{#?W2HTTl#XEXiH1sjg}a_H^~9 zzdYI_^&a=7;fJM}o72b*&6wZTbEF;1+l;6BntIH*##XJO@j@~L^9$FnYz(Mud3||# zd{#AdwI^H%Pj;&gHX6%npq8McYfG9;B(XM=k1+SCe1Qh3UDVjghKT;5d&4PqG*;u{ zz>H(>K)VntBg3K=Y9e{8duR6L!M*9mAa{@zP|2kd<9iYbd_eNeaSor;NhZ>@G4YXa zS=Shlsd4v>Rt0WU-$2)J?ub|oBl0xT4V#_4wMxv>{=j1j*Iv0(HJqsy;wiN~>^EG) z66U%1s-QRcJPwoUPa3YqLcppnh%JLpd!3Aq|1v1!H-z9(qBydjw@EbMGX?TxTDvtn zXk9~|0SNwSPa(?Wx$~-3+bg4~1x1BdHM`c`L5ti=JZeMqKN*(76wHPNE-ELDkEs>{ zHoaD-u-eG4lgfZv`M0Fx-z;wNp5qm}`kacZ2`NVxX;xSvpmdRG=k>FLDcS_-Pt_S7+{fX z7u(+5@vEu)0DLo32otx2ekylH{o}}?uN1t$z$@>Kb^-szEedGV#j;9VXm*3xIaG5} z&)p(+0Wf4I#xFFV-h3Lcv%Jx$ow>g z_FjDH=8=Guh6bmu4^nqB{7nHvipk} zs$8buBT^4r7mEY96w>$Ptb_x`M5yqZT}jp(^Pkm5Vovsbp|ARGsld?0;>3~`Oo3Oo zzrn!X_mG?Q;YEI9aG}3Ys9}SQh3!Q4u`ax6@LGwrU*yO4UE5l-D{;q4cKmjEUHHz_ z&1vZkNikkSNZiKMSz*7Ct!WInXWOB12M*^B&DuonygVa2*?ns3>H}!7r^nCVrgxCZ zGIm6{l&h?fQ)(izV4&#kQpfkCvqAjG@g=*#Qk>pdQA0?K11n`gux;D1;PI&99f~0? zspF~bMrC{4b`$Gf;^_D&Ur#?T)tLO<*bcU+gN;X5CcCvJfIBbr?UV5FMgA{)inqmS zMENNmc`Vn^eG%tttwKd!Yc7}m4@QaPBPcFaPa%Fan#ar z>ok!HSc*hDuzZOcRBAc9Ht6W8&dF}pUMNlsAsas|GTG*qO~uli4dXaI70&3@QVu`2 z8XWPSSl_>vmi>LeTXi29gPH3-umyaG2*Z6y=f?J3B`Rm&RyRUCPp~bXuH~mcc z5I9_5b~Nl{_jS9H9ZgZU3!Q&vPxu*6^xv{hWjub>g+34<{~y;vhFgieT;vml-+TZ3 z!WU9Qc~^4M9TJzE^ACJYY|X1=HJ5Mqf~|e5s9auht^7VP*A!~?iP00~aml#tK_tw2 zS;jh+2tZ_+E)?4t|3Ph+Y-F7v6Ebp*s3+R+_T0#ZOFll<5wG$ZPPgCj-01yXTC*(@n+Z>Qz2rm4<-5}PZ}x25>5fr;uU%2&1`TU@;u6OykaWAK;Qz zSh@YX&c90NhMdYKiD6=Q(MQWHW@h_6*$u7sB_5zYtHRdqN3qo^dsEuezqy;;eq8<$ zuk4Bb!s1uU+3rcPX`tVJ$D^5tx*i&%mk3EiM`FfXE>XH0y`Riu+Or^VC zT_!c~izOb5`an6|5{=?HV5=V}r7?t`(xyJgbzc1Ns zR)hsSEIb4Ek-NA~Fl43X!Yp;&bbC`ldTp=tzlGQKerJ!p1Dx^wwZY?~ua?g1|Hk+Q zeN7?QyU<4h;58i2esj+piJ#F2XrhF~B=rh0H!x0wMz0_lzdkr?la=Gf*I+jMpKR*X zCnmcu=o=GF<7N(P^`@zBGF@juJUd-mZdBf9^WavxV4G^68{L2Kjm>GX2Xq^dne5gY zCyfkcgda^l)kLr3^HIa~dir&##B23l6B~nZ5=r#v+k1c`_5{~7QbVUC)`oVUz1G$C zpw-x`BI%-D9sZKh+j?DhqTMKZg~+EHvz0nA>114T$A8#2EA#b;TjLSecZdJCG@PE( zNmLcPT%&I{b-)L970vsey&K$%C7=85HdouJH-lA=cVp$N$^=Ga|8-%dRgFJpqB`1n zx<1lj8dY@p%~Y*6g>=&czvdC~5M+f7p=)z0)ai>O_LTJO`VFOGQ#_jgv2-v^cGIS;E0p^Hd;&N zJbD8UbV0{@sq3b*`3usm%XtqP`_(>nH!9#AZ0=x8EClKT8ryGe+Zzmx+ZZ&|tGy0K z?xyR9DgwLP%eU_p%Zpwc*9Pi|^cWJx)O)A}g!Kai=<1*XwzB39Y6s7pMWIoT?`5GE zg$Y!#Fk9J0QNEs;Sc0tkjah1B{Mi^(M9(!o_e^a;m9n+0 zKK<6%J^Gimhg>@n%V~3DtDrfU-PC88r=dXb%84YAog~%a*w`+0*s;x1i$w|&2m6#% zXA%+8oLaANbv0Wwz9P+FE{tmW=%+F{U^BMbaX^gN!HV`{-Hid%j@^w-eCr)`?f78E zw}S$;ZlEdRQ;lu7)|6{qQIUY;aIaaLx6&?iuh?hZtLAASxp+HuNm$2LCa64&ET+?4 zlvY~)A^PNX;r~BYQl035TK18(+5SDZ0L@oMv+BaiT!OV67iKH_iCoEDKjp)#1R{2a zUreol9RqDN*{vFu`-4a~5*>Esr1k2xno}!Z;!?;+X*uygBFMy`rii5o$5v3qQLd zd@{JT4XXsdc-7$ZMPOl{oK8;szC4eA=P7cphDMO@7=J0mirP(YLm=UCSIdFK#%SM$sN__xAt8!fCcYM&Xov*%`7Ni$%8>!(Cp&;x*qIjy7EO#sVaw@`A-Zdi8;<51hseV{DgEu`M z-Ku|L9oE*4=UwJT&@t;e+gt(mt;VnaZS=hh)0wTkx{g=OFU(fcy;7i z)}M}G`5x8H*otx8fL~q8W&4_>-luwo_Xdft-8dzuv9ZidN^QPeaev@37pLX*Iwne| zCj*hUFCV{@BMZDV%{;f4X16b!vgO=a_{>c4IOEOfTcyg(a1j*hdoS%tY@rgHy>Xrr zcC+>@l22#|@nsv^j|4=EAIyGNxHt78j5nm-cvsrbtIo39nAgUQmM!nifv7WI_ zO;oztc;?iOxZbs%Dm7%RrTTqyr*_v6-rn9K{mImvaE=IY)V@EezO1I>95uXF_E!x9j0k`5?NBr}jpBy$JL zF=u+f5=p(+;7_qvd#(q%0ddrB% zZ<4<@ip+4KrzhlT79fr>&Y39XsGWdo$P~B{mh0pSITdRBUTO3%SdS-R~w|H7QjXzJ{zlMy-xzBW?FNDAxgYVO>X>DN`Poi)>8 zDQ6i7Tx;*EQDR)5N^_FwhuX+HZ5BuXVTCvtcQbgsM7)D*CcGgL9H)C>}iSoq~s)*MbU{zZIT&ENvG=~ z(XQ>1DPpaxNh4LJLtuKmX!ko28{&iHyYaU;38^mB9$sRZt=^^kt_`HyVB^Ad#tN;5 zubIn+rqJ!BQ|@xD4fcY)Vd8FYWH;p07@3Mp&3zL4Unnx*y3<)Qd#dl1a%Y_TiC9B9 z)LztuJ9pMkn40+Nd$(1)Ekgai_a3os`N2jhi5#MjJ1ceo{79T_sr+xUsLkG`Rb`kf zr!S2p&2|~t(LUb$re=AMtiLWq+qTNN4KEDRX^gg1YpvFb|B&M<)h)ov7)dS51bJZ2 zOhQxOHw_AOTZE&w$X|KEh^e3FbS2Ht(EA8hObrY7e^hXcU#a!lZuinkp}6X2|M1*L zV5E?<-7WQSA@ zY!po3?HW0wUN)ADuJ_HEqqS^&x^M^6x24I2vIFDYn6=2clp^6dGg8iqmRctwTYvS* zA4=?@YkU2~s^Uq>PS29_5E`Wx^u&JR9!3M``b&pySV{C=PyOhPq#e86a(cIQ64mdF zIwxI7z)eWP)(AFKS-?ZB5tnh@p2Mbg1eO=jbftM#u5n$fGu&@JA}e49b7E<`e1;~W z*u~rNYUul*dd%#`@I`&zJ9xvOdbMP2Ifw4{_Sx;*ww;h}B*ri@TlvPsO5D9+2cgdk z!Vf72`TM>-%aWH?*HDK(B_b;TabTGs7XB&+b#zac(4mp}kp|=d#L8<>#`@ zO!63>)~a-*ilN+<>HRspcivDy4T&#&%yx< zzs#3^SBm{nFYoK1O60r@-^Wk=W_9t%m%-M*R^6Nn*O}oHOHgZc-Z*u?5e&W=^UjQ` zkSPjxulSu&6P+h!Yix7XW%xxc!Jo)Eqlbr|9;dSeI>Bq^jI!HrFU9L8SNA8wt zu6C_Z`t!{FT?>N$y7^>*a{vzXJ(?-E7C4ba-{gXQ=~@KjRj@meGp3W()$Kf`_E?|D zjjQD(ool4Om9?VDz_*@%itM4spYztaIv`e%ku`XNSlwuBaIN;O!ep|W6(u8^kLT!> z0v_Z{4O}b)|M&RuZJgR5{VsAo9+3ssrq)>XZrl#>U$YXsUMe0nXD+wOs$f@3$y3Kavp7>myTvzCCEDV z29>9=Xoj4=8_rm?Rh0Jnm2$mW#S!sv>bS!5&*sInWmYRII6O3wIcOsdQzwka=1#9}LEqY$-DohWseXbyM;%c9^XrEeF zMlM@dv{+X8L0MIMG!rKpY4lSqI5S#a=+UgFd|aEG_q_(OpgRvHdhzDaev{oVE}t(J z27k}l@!32l?dmDJHa^0cH*r79dVfgZ$!@%nQjWd?xEk$w?SZev>bEqm3U|c&f;1Ye zz2&w~+PqVNl@qPec$!9K$7setAr0%K2Kvi)eKD{k=*)DtgOn4op)EQ z6Ge(uLb;^nDasp7;W8+Ikv=`ImQF8(tQqcJPmYz8m(>-O)*zrmiJgeHsuE~#h?5&+Hr(2#T zH(i*j+$2WG`*PrC_v$j)kBMT|hn(bP_o(kGV)QoIDbn5g&vRqY;K}LXLH)s7J6%e^ z!p3e_O=jwCdSrFlfy1iw%^pZ`BoQa;Xdhu+bOQhJ?5%CBk`v>1BKee@L{FD%B8eZ4 z2F>*3R>ozL>4zwvlkO+^gln!=+QxQ7aHsMXGk&Z#_6#Oe(!7@n*=Nkr?g;&*E0H}`8- znANV}jY@T3=*A@7sww*P<5=X3CFBB<-JBcY+AVaTMOj$kSfq!^Tj;q`iKKQybKY#b z*b!(aQ*ob2;&BoevKW$`?gLurfJAakw80~CI&~sxIp<8=3^hH`f2?Ttt+@gsyM{V^ zk8@16mkvjHU37u!S~BAri-%%0HdhzATsJdbR0*zpXUDW7y1W{XK~8paz8LhO@iV)N zO54cdWq||1N({Q#sy52nNa9a+UlFw5fh;#1T{)8P8OX9ObnXLP&+W7MewBB&H&sW{ zD0t;*eACTzCaR-G7&=CFtAx2uxb*5MBVuWVybjq|3vUydAC{cYyy&~Q^ji{1OC%Ou zIXv4Y_H0&u6pCiw@Z68bznpV*gyF-w5ScMg;G?pmUOE)Wonc40a#UrFl{E9Cr|QCu zxhLcV0@bSMN+O!(e5?L6p683pua}BU9n180xtS|g>Ar*VSb?`Q)aO-RM7D1d&)3%Y zKiT`W^vvEl$u7u!n%bbIP-CN7@l!4D?&hpCM&o9z=!h^eXew-o=xSY!?`cI%DfjrG zsiko;T~bd`nceU`s@qs!qF3Pql~P^7HB)WT6jocO$(B}D9=tnzt?S;Lja6xtf*oHw zS>sll<}0zHG>U_5iWO7MvXklz$!zZ`SvyeA2g0huTB~iV8B47pWR}P}lWG{dGO!iT zX^;hx?i=weh^m+89kGw_CDh~az3&H_@4z!z5D>}JnpYyCzlh>i?68!B228xrMzerD zD=?g4J*dXOUNhcPQ%FA#(w`0$V}~_N(HGjxl}x13}>4+m1vKT`VT~L*2!MtUa7nahp=E`dd{wC0P3fksXO7XHqWS?#cToPprAdc|$4lb6;Hu-Z7yQ3vGXuLuW&K#QYnBPs#h=8p883vx|-G$FnA)&-cf-nK$J? zt#EX!aPO{VtW2|o@zv26jn7z3S0|G3d$EPEt;{aUzsEA`tNAUy8y1X9w|yhgD)vkk8v%V^5Z@D{Z6dP{1a})8w6lW*%#w*fqr0)*^e+ zY$&qWzHbL#4IA6+K{1a`L}J$-O}%a%(H+lnE%LoFzyeT8MTX1UJ46=i8*|8c6OU1i z!CRi~8(+{0`u%KCJsi!3Jt<8F+A}DI4tyYGRZ1ME^tu?axt`rEV^;Z`fjh09not8*i zFOBz!z7gGKai{hdoQig7mVR2b2Ka>CN$lF*eXQ_zJ^HRI<5QdWgMzVLCFFWz@TK5K zL0o&G$N#eD?^DzrBMs=UMP94@hi`0cD$NtzAh-hd9TAj?OK*}GyZQv>=P`0}hn^4@ zzn=&^XUsBdV$0C@&&D|aiCWr3lCB7}`ZL*=_B=OAq|z5&(W+{(`Q>B}IwkDRfm5}0 zE)#wN>)5I7@`-$rT_^E(@K0b7|(ZS3Do{{u4b{7~ZE=7Jr&3+PsPxOf<#VeRNpq zduqsJ11n1{X65myf##;x#%kfPNiA*Z9vVVc3S|R@_!x5|sPJZcy61t0TY*D#lhvF( zCB!jw zU^=~n+E1bgJNj-PhmJlQG)=^17ZQLg$Zd-mR}QnPYE-1BmSCf4mfmUu#$r}_3pgtP zt~V4&6&t7bl1b9&$eAgsK74mb4Tgb4`RZJFYJ|m{sG?^BsVtfva&gSk$DlqNahMBz zq>EWO-lfVSa|Jpya^WH$s=!JhTOf9_WRv-x+9GO(|0MW@yaR^ayQ}_BG0k_KL+dkH zyPhq5p${HsN9PilI(fLTK7UGLX!uja>5!533_q&b(CA1v-m%^okX^^xqte@I`f^P1 zj%2mBz%B3fjzC8&|~CI70~-7OJb@0IhmZ&<0lPp#hQ_Sx;xJ4RMs zCPz_zXB6wBAtX-w_}Hua?>+GKtw*AF%yY&X)XTkiF1r6e3?Fj-4E;x=sn{n{i)fS! zI~zMzJ99{+H=N=^lqgkQ_+-zWdrlUPX1|yLFUnW?rY=8%xSqIiYum*mj|7}9_(0b! z>nuf)70^@4dt=gIdihKAXVYhIEMC=_NYWodXBx7G&dvsjraYR_szx-yd6~XE7W~=B zUW;+CUiof&SBk~$ci+R#BqlOX>KHyC|N9;>26@-H_1FnWm7A8|`AS zc0l!NZ?wC<=c8744tLNw#=EG1#!Px^pb~5ixS%n>s%*dGSdnwRiPK>x6N@&M-Si!O z+99S^BvFo!rjA8t%IK=AcjD=}V|aO-{8oM@2Rk|{6=OFS&`jD-L)=<>WZ3J`!tt!> zk+C!f+>sjZOwEZ-imPRjxmboCjo)8sl}+Cdq1w#UBv6M1uIlq-z`;a3Hp;h>#SyPl zJA1VHaOr_ZMwN<{Gr4PD`q(u6X-5l0>F5*!0-U2p{Dbpt3%l=&&IYap^KuH}JvH{c z6=pUgGpfSXm#gj%l%tl5i;oNaqXmPH;q2%7s05^%fVaX9Zb9GZdHQs_Fg6ijJW^sP z)b>b?ThuGLZ5zGh8a0mNl?(yahvp~T74ex>(YH9e^YAeALBCe{Zl~{NV>NDX7yVq+ zTbewd*^$QH;a&TUcD2`r7rkQz@djJvH}BW%mDRFJdJ^*kAIuTSZ;zsquVK6zE% z(qQ)wR*35It_kW};kC<)|K+Zug;T+@6x0NtKn15h@zc@cS$)rmVgP?_MZJY-Xo%Gt&CgFkK&fqVwPfs z3a3&-s~rqj*;w!T7uG7+zQ~_>4hKt>cni5DXbP{%J%2;8FY?xJ!E0S}q)NrL;C=7h?3242!q-LjaMb+%Vpj{vGvV+u`2Iqi&h4f=rJ#ciN^fY&nJ^Z z?qDGDEZk}^B4DNhM9)8Sci_v3c5M%md9aZ;>1J99d^gA&Pz~(l6o0`F8LT*#sh7E7 zC9;$^rT`&@Mnm{)`W-8e+&#PVr9Bg(^Tn>};e3nu9>{-`Qv*@ICaL4*-M{$tW?xjT zn9m(k7$bh6_JHxl>^*Y@PvtVozTppv!b~p(>7x^ zpY%`zZPUHU8+PtXzc8q8U*heZoQGVW2UmXTTV>Iv*E>GEg&ku{T-u9WtMxXPI;LNf z>9FUNgoz?@ur4MQ><;L$9ynchh;>=ppF7qqH8feI`dd5i3V5gRNy)e@*$wv-10?qR zCFxJ#O?%e{hYo$?6GL0xk*}ZNKE>{D))mr63&ZJGQ*PF!vKE3!a!Ke8y96KaY&=H1 zCF3>P+?b7_*7lpon7PyfR-qL23ECbkr8`qtso=69TzVjocN9tPW*c#e;=tm-a+U6% z3@;F=3*Awp5tC>mWO^cr$I}{hqhpaT-j08QhUG~(^LX~fnG|{{YB_W|sf} diff --git a/docs/api-doc-update-spec.example.json b/docs/api-doc-update-spec.example.json new file mode 100644 index 0000000..2477ca5 --- /dev/null +++ b/docs/api-doc-update-spec.example.json @@ -0,0 +1,56 @@ +{ + "docName": "", + "docMeta": { + "updatedAt": "", + "version": "" + }, + "group": { + "groupName": "<分组名称>", + "module": "" + }, + "methods": [ + { + "method": "", + "description": "<接口说明>", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "", + "type": "string", + "required": true, + "source": "body", + "description": "<参数说明>" + } + ], + "response": [ + { + "name": "", + "type": "string", + "required": true, + "description": "<返回字段说明>" + } + ], + "errors": [ + { + "code": 400, + "message": "<错误说明>" + } + ] + } + ], + "change": { + "version": "", + "date": "", + "summary": "<本次变更摘要>", + "methods": [ + "" + ], + "notes": [ + "<变更说明 1>", + "<变更说明 2>" + ], + "type": "updated" + } +} \ No newline at end of file diff --git a/docs/api-doc-update-workflow.md b/docs/api-doc-update-workflow.md new file mode 100644 index 0000000..eccf22b --- /dev/null +++ b/docs/api-doc-update-workflow.md @@ -0,0 +1,103 @@ +# API 文档 JSON 固定写入流程 + +## 现有 JSON 结构 + +仓库内现有 API 文档分两类: + +1. `methods/.json` + - 根节点是对象 + - 关键字段固定为 `module`、`description`、`version`、`updatedAt`、`headers`、`methods.groups` + - `methods.groups` 为数组,每个 group 固定为 `groupName`、`module`、`list` + - `list` 中每个 method 固定包含 `method`、`description`、`isNeedAuth`、`isNeedLogin`、`headers`、`params`、`response`、`errors` + +2. `methods/changes/.json` + - 根节点是数组 + - 每条变更记录建议固定包含 `version`、`date`、`summary`、`methods`、`notes` + - 可选补充 `type` + +## 固定输入 spec + +后续 API 文档写入统一通过脚本读取一个 spec JSON 完成,spec 结构固定如下: + +```json +{ + "docName": "system", + "docMeta": { + "updatedAt": "2026-04-15", + "version": "0.3.5" + }, + "group": { + "groupName": "基础模块", + "module": "index" + }, + "methods": [ + { + "method": "index.example", + "description": "接口说明", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [], + "params": [], + "response": [], + "errors": [] + } + ], + "change": { + "version": "2026.04.15-system-06", + "date": "2026-04-15", + "summary": "一句话说明本次接口文档变更", + "methods": [ + "index.example" + ], + "notes": [ + "补充关键字段说明。" + ], + "type": "updated" + } +} +``` + +说明: + +- `docName` 目前必须对应已存在的 `methods/system.json`、`methods/qimen.json`、`methods/gateway.json` +- `group` 用于定位或创建目标分组 +- `methods` 为要写入的完整 method 文档对象数组,脚本按 `method` 字段 upsert +- `change` 默认必填;仅当明确是纯格式修复且不需要追加历史时,才允许加 `--doc-only` + +## 固定命令 + +先做 dry-run: + +```powershell +npm run doc:api:update -- --spec=temp/api-doc-update.json --dry-run +``` + +确认无误后执行写入: + +```powershell +npm run doc:api:update -- --spec=temp/api-doc-update.json +``` + +纯文档主文件修补且不追加 changes 时: + +```powershell +npm run doc:api:update -- --spec=temp/api-doc-update.json --doc-only +``` + +## 脚本保证 + +`script/update-api-doc.cjs` 会执行以下动作: + +- 校验 spec JSON 是否符合固定结构 +- 校验目标 `methods/*.json` 与 `methods/changes/*.json` 是否可解析 +- 按 group + method 做 upsert,避免手写 JSON 时把括号、逗号、层级写坏 +- 检查 change version 是否重复 +- 保留目标 JSON 原有缩进与换行风格 + +## 推荐流程 + +1. 先核对代码与测试,确认真实接口契约 +2. 如果是 system 参数结构变化,可先执行 `node .\script\tmp-struct-system-params.cjs` +3. 按 [docs/api-doc-update-spec.example.json](docs/api-doc-update-spec.example.json) 复制一份 spec 到 `temp/` +4. 先执行 dry-run,再执行正式写入 +5. 最后补充必要的 `docs/*.md` 或 `README.md` \ No newline at end of file diff --git a/docs/notification-event-api.md b/docs/notification-event-api.md index 0e9baed..dee3609 100644 --- a/docs/notification-event-api.md +++ b/docs/notification-event-api.md @@ -14,6 +14,7 @@ 当前已落地事件: - `receiving_completed`:收货完成通知 +- `order_cancel_intercepted`:订单取消失败并触发拦截执行通知 - `store_warehouse_print_quantity_adjusted`:货主面单余额人工调整通知 --- @@ -51,9 +52,10 @@ await ctx.service.systems.notice.send({ | event | 含义 | |---|---| | `receiving_completed` | 收货单完成通知 | +| `order_cancel_intercepted` | 订单取消失败并触发拦截执行通知 | | `store_warehouse_print_quantity_adjusted` | 货主面单余额人工调整通知 | -> 当前正式注册的业务事件包括 `receiving_completed`、`store_warehouse_print_quantity_adjusted`。 +> 当前正式注册的业务事件包括 `receiving_completed`、`order_cancel_intercepted`、`store_warehouse_print_quantity_adjusted`。 对于外部订阅方来说,判断消息类型时,优先看: @@ -136,7 +138,9 @@ Content-Type: application/json "name": "广州仓", "code": "", "config": { - "max_notice_webhook_count": 5 + "max_notice_webhook_count": 5, + "default_express_code": "STO", + "default_platform_code": "TB" } }, "store": { @@ -240,6 +244,7 @@ Content-Type: application/json 下一步可继续补充: - `receiving_cancelled` +- `order_cancelled` - `stock_low` - `stock_changed` - `entry_order_created` diff --git a/docs/notification-webhook-capability.md b/docs/notification-webhook-capability.md index c115cab..3b235f3 100644 --- a/docs/notification-webhook-capability.md +++ b/docs/notification-webhook-capability.md @@ -60,6 +60,8 @@ await ctx.service.systems.notice.send(options) | 字段 | 说明 | |---|---| | `max_notice_webhook_count` | 当前主体最多允许绑定 / 触达的消息推送接口数量,默认 `5` | +| `default_express_code` | 默认快递编码,默认 `STO` | +| `default_platform_code` | 默认平台编码,默认 `TB` | --- @@ -83,8 +85,9 @@ await ctx.service.systems.notice.send(options) | event | 说明 | |---|---| | `receiving_completed` | 收货单完成通知 | +| `order_cancel_intercepted` | 订单取消失败并触发拦截执行的通知 | -> 当前正式注册的业务事件仅保留 `receiving_completed`;`all` / `*` 作为通配订阅值继续保留。收货完成事件的独立 API 文档见:`docs/notification-event-api.md`。 +> 当前正式注册的业务事件包括 `receiving_completed`、`order_cancel_intercepted`;`all` / `*` 作为通配订阅值继续保留。收货完成事件的独立 API 文档见:`docs/notification-event-api.md`。 --- @@ -139,7 +142,9 @@ await ctx.service.systems.notice.send(options) "name": "广州仓", "code": "", "config": { - "max_notice_webhook_count": 5 + "max_notice_webhook_count": 5, + "default_express_code": "STO", + "default_platform_code": "TB" } }, "store": { @@ -178,9 +183,12 @@ await ctx.service.systems.notice.send(options) | `all` | 接收全部已注册通知 | | `*` | 兼容旧配置,等价于 `all` | | `receiving_completed` | 只接收收货完成事件 | +| `order_cancel_intercepted` | 只接收订单取消拦截事件 | > 若需新增其他事件,必须先在 `app/model/notification_webhook.js` 完成注册,否则发送入口会直接拒绝。 +当前订单取消拦截通知由 `app/service/qimenMethods/order.js` 在拣货状态或打印状态未结束时发送,事件码为 `order_cancel_intercepted`。 + --- ## 8. 命中与分发规则 diff --git a/docs/order-workbench-list-api.md b/docs/order-workbench-list-api.md new file mode 100644 index 0000000..1c055d5 --- /dev/null +++ b/docs/order-workbench-list-api.md @@ -0,0 +1,186 @@ +# 订单工作台 List 接口说明 + +本文档说明订单工作台(Order Workbench)中可用的 list 接口、参数约定、返回结构与行为要点。 + +**变更记录** +- 本次已在 methods/system.json 中补充以下 method 定义,并在 methods/changes/system.json 中追加变更记录(参见变更文件),用于对外说明新增的 list 接口与分页/where 支持。 + +**新增/确认的接口(method 名称,主入口)** +- order.list —— 订单工作台总列表入口(汇总所有分组) +- order.reviewOrder.list —— 待审核订单工作台(step=0) +- order.pendingOrder.list —— 待处理订单工作台(step in [1,2]) +- order.expectionOrder.list —— 待处理异常订单工作台(step=3) +- order.entrustOrder.list —— 委托外仓订单工作台(outsourced 模型) +- order.deliveryOrder.list —— 配送订单工作台(dispatch 模型,dispatch_lane=m4) +- order.deliveryExpectionOrder.list —— 配送异常订单工作台(dispatch 模型,dispatch_lane=m5) +- order.archiveOrder.list —— 归档订单工作台(history 模型) + +兼容说明:代码中存在若干旧兼容入口(例如 getreviewOrderlist、getdeliveryOrderlist、getpendingOrderlist、getexpectionOrderlist、getentrustOrderlist、getarchiveOrderlist 等),这些为兼容旧调用保留的旧名入口,不作为首选主入口;建议新调用使用上文列出的主入口。 + +**工作台语义(简要)** +- order.list:总列表入口,返回跨分组的订单集合,适用于需要不分组的通用搜索/分页场景。 +- reviewOrder:待审核(审核步骤为未审核)工作台,用于审核操作筛选与展示(默认 step=0)。审核提交接口仅接收 ids,批量审核,严格同仓校验,不做兼容。 +- pendingOrder:待处理工作台,通常包含需要人工或系统继续处理的订单(默认 step in [1,2])。 +- expectionOrder:异常工单集合(默认 step=3),用于定位异常状态订单。 +- entrustOrder:委托外仓相关订单,使用 outsourced 模型。 +- deliveryOrder / deliveryExpectionOrder:配送相关工作台,使用 dispatch 模型,分别以 dispatch_lane=m4 / m5 筛选。 +- archiveOrder:归档历史订单,使用 history 模型。 + +实现要点(参考实现位于 app/service/systemMethods/order/*): +- 模块实现会根据模块名选择不同物理模型(current / dispatch / outsourced / history),由 OrderBaseService#getOrderModel 决定。 +- 每个模块还定义了 `defaultWhere`(例如 reviewOrder 的 step=0 等),请求的 `where` 会与模块默认条件合并后一起用于构造最终查询。 + +参数说明(公共约定) +- pagination: object + - pagination.page: number(可选),页码,从 1 开始,默认 1。 + - pagination.pageSize: number(可选),每页条数,默认 20。注意:服务端对 pageSize 做上限截断,最大不可超过 200(见下)。 +- where: object(可选) + - 统一的筛选条件对象;支持两种写法: + - 标准化结构:{ field: { operator: 'eq'|'in'|'like'|..., value: ..., type?: 'string'|'number' } } + - 简写:{ field: value }(会被自动转换为 { operator: 'eq', value } 或在传数组时转换为 in) + - 服务端会先对 where 做 normalize(兼容简写与 values 字段),再走 parseWhereConditions 生成底层查询条件,最后与模块的 defaultWhere 合并(后者优先级低于请求入参)。 + - 常见可用字段:id、delivery_order_code、order_status、dispatch_lane、quickWhere 等(具体过滤字段以实现解析器支持为准)。 +- sort: object(可选) + - 支持 sortField / sortOrder 或 field / order;实现层会映射到允许的字段集合(如 id、step、status、delivery_time、updated_at 等),默认按 updated_at DESC, id DESC。 + +分页/大小限制 +- 默认 pageSize=20。 +- 最大 pageSize: 200(服务端在 normalizePagination 中对 pageSize 做截断,防止单次请求返回过大数据)。调用方仍应合理控制 pageSize,避免前端一次性请求过多数据。 + +返回结构(公共约定) +- list: array — 当前页的记录数组(每项为订单对象的序列化行,字段视具体模型与序列化而定)。 +- pagination: object + - pagination.page: number — 当前页 + - pagination.pageSize: number — 每页条数(实际返回值为服务端截断后的值) + - pagination.total: number — 符合条件的总记录数 + - pagination.totalPages: number + - pagination.hasPrevious / hasNext: boolean + +订单列表 raw 字段字典(通用) +- 说明:以下字段为所有订单列表的 raw 基础字段;`order.deliveryOrder.list` 和 `order.deliveryExpectionOrder.list` 额外包含 `dispatch_lane`;服务层还会补充 `express_numbers` 与 `waybill_codes` 两个派生字段,二者内容一致,都是该订单绑定的多个快递号。 + +| 字段 | 类型 | 中文语义 | 枚举/说明 | +| --- | --- | --- | --- | +| id | number | 订单主键 ID | 订单记录主键 | +| delivery_order_code | string | 发货单号 | 订单单号 | +| pre_delivery_order_code | string | 预发货单号 | 预发货阶段单号 | +| pre_delivery_order_id | string | 预发货单ID | 预发货记录关联 ID | +| order_type | string | 订单类型 | 业务类型标识 | +| warehouse_code | string | 仓库编码 | 仓库基础编码 | +| order_flag | string | 订单标记 | 订单标签/标记信息 | +| source_platform_code | string | 来源平台编码 | 原始平台编码 | +| source_platform_name | string | 来源平台名称 | 原始平台名称 | +| sys_platform_code | string | 系统平台编码 | 系统内平台编码 | +| sys_platform_name | string | 系统平台名称 | 系统内平台名称 | +| create_at | string | 创建时间 | ISO 时间字符串 | +| delete_at | string | 删除时间 | ISO 时间字符串,通常为空 | +| updated_at | string | 更新时间 | ISO 时间字符串 | +| place_order_time | string | 店铺创建订单时间 | 平台下单时间 | +| pay_time | string | 支付时间 | 支付完成时间 | +| pay_no | string | 支付单号 | 支付流水号 | +| service_code | string | 集包服务编码 | 集包/服务编码 | +| operator_name | string | ERP审核人 | 审核人姓名 | +| operate_time | string | ERP审核时间 | 审核时间 | +| delivery_time | string | 发货时间 | 发货完成时间 | +| shop_nick | string | 店铺名称 | 店铺昵称 | +| seller_nick | string | 卖家名称 | 卖家昵称 | +| buyer_nick | string | 买家名称 | 买家昵称 | +| total_amount | number | 订单总金额 | 金额字段,保留两位小数 | +| item_amount | number | 商品总金额 | 金额字段,保留两位小数 | +| discount_amount | number | 订单折扣金额 | 金额字段,保留两位小数 | +| freight | number | 快递费用 | 金额字段,保留两位小数 | +| ar_amount | number | 应收金额 | 金额字段,保留两位小数 | +| got_amount | number | 已收金额 | 金额字段,保留两位小数 | +| service_fee | number | COD服务费 | 金额字段,保留两位小数 | +| logistics_code | string | 物流公司编码 | 物流公司编码 | +| logistics_name | string | 物流公司名称 | 物流公司名称 | +| sys_logistics_code | string | 系统物流公司编码 | 系统内物流编码 | +| sys_logistics_name | string | 系统物流公司名称 | 系统内物流名称 | +| express_code | string | 面单号前置 | 面单号前缀 | +| logistics_area_code | string | 快递区域编码 | 大头笔/区域编码 | +| delivery_type | string | 发货服务类型 | 发货方式 | +| is_urgency | enum | 是否紧急 | Y=是,N=否 | +| invoice_flag | enum | 是否需要发票 | Y=需要,N=不需要 | +| status | enum | 订单状态 | pedding=待处理,created=已创建,cancel=已取消,error=异常 | +| name | string | 收件人姓名 | 收件人 | +| zip_code | string | 收件人邮编 | 邮编 | +| tel | string | 收件人电话 | 电话号码 | +| mobile | string | 收件人移动电话 | 手机号 | +| email | string | 收件人邮箱 | 邮箱 | +| country_code | string | 国家编码 | 国家/地区编码 | +| province | string | 省份 | 收件地址省 | +| city | string | 城市 | 收件地址市 | +| area | string | 区 | 收件地址区 | +| town | string | 镇 | 收件地址镇 | +| detail_address | string | 详细地址 | 街道/门牌详情 | +| id_type | string | 证件类型 | 证件类型 | +| id_number | number | 证件号码 | 证件号 | +| oaid | string | OAID | 设备/终端标识 | +| sync_status | enum | 同步状态 | padding=待同步,fin=完成,error=失败 | +| store_id | number | 货主ID | 货主主键 | +| warehouse_id | number | 仓库ID | 仓库主键 | +| from_key | number | 来源键 | 来源系统键值 | +| items | string | 商品JSON字符串 | 原始商品明细 JSON | +| items_count | number | 商品种类数 | SKU 种类数 | +| items_total | number | 商品总数 | 商品件数总和 | +| items_weight | number | 总重量(kg) | 总重量 | +| items_hash | string | MD5哈希值(32位) | 商品明细哈希 | +| items_crc | number | CRC32校验码 | 商品明细校验码 | +| wave_id | number | 波次ID | 0 表示未分配 | +| post_status | enum | 分配快递号状态机 | padding=处理中,fin=完成,timeout=超时,error=失败,none=未开始 | +| storage_status | enum | 分配储位状态机 | padding=处理中,fin=完成,error=失败,none=未开始 | +| pick_status | enum | 拣货状态机 | padding=处理中,fin=完成,error=失败,none=未开始 | +| pack_status | enum | 打包状态机 | none=未开始,padding=处理中,fin=完成,error=失败 | +| inspection_status | enum | 检验状态机 | none=未开始,padding=处理中,running=进行中,fin=完成,error=失败 | +| step | number | 订单步骤 | 0=未审核,1=已审核,2=处理中,3=驳回/异常,4=配送中,5=已完成,9=已关闭 | +| print_status | enum | 打印状态机 | none=未开始,padding=处理中,fin=完成,error=失败 | +| claim_status | enum | 领取状态机 | none=未开始,padding=处理中,fin=完成,error=失败 | +| outbound_status | enum | 出库状态机 | none=未开始,padding=处理中,fin=完成,timeout=超时,error=失败 | +| lock_status | enum | 锁定状态机 | none=未锁定,warehouse=仓库锁定,store=货主锁定 | +| intercept_status | enum | 拦截状态机 | none=未拦截,requesting=请求中,requested=已请求,intercepting=拦截中,intercepted_in_transit=运输中拦截成功,intercepted_at_warehouse=仓库拦截成功,returning=退回中,returned=已退回,delivered_by_mistake=误签收,timeout=超时,cancelled=已取消,failed=失败,exception=异常 | +| dispatch_lane | string | 配送通道/分区 | 仅配送相关列表可能出现,常用于区分 m4 / m5 等通道 | +| express_numbers | array[string] | 快递号列表 | 服务层聚合字段,内容来自 wms_order_express.waybill_code | +| waybill_codes | array[string] | 运单号列表 | 与 express_numbers 内容一致,为兼容前端使用保留 | + +补充说明 +- `express_numbers` 和 `waybill_codes` 都来自订单绑定的多条快递记录,适合前端直接渲染“多个快递号”。 +- `sys_platform_name`、`sys_logistics_name` 已由服务层归一化输出,前端无需再回表查询。 +- `dispatch_lane` 仅在 `order.deliveryOrder.list` / `order.deliveryExpectionOrder.list` 这两个配送类列表中出现;其余列表通常不返回该字段。 + +其他注意事项 +- `where` 的解析与支持的特殊字段由 parseWhereConditions 决定;若需要支持新的复杂筛选(如跨表/聚合条件),请先在解析器和后端模型中确认可支持的 specialFieldMap 与解析策略。 +- 推荐使用标准化 where 结构({ operator, value })以避免歧义;历史简写会被自动规范化,但可读性较差。 +- 兼容入口(get*)保留以兼容历史客户端,但文档与新开发均建议使用上述主入口方法名;兼容入口可能在不同 module 下存在重复实现(index + 子模块),以兼容不同调用路径。 + +方法清单(已在 methods/system.json 中登记) +- order.list +- order.reviewOrder.list +- order.pendingOrder.list +- order.expectionOrder.list +- order.entrustOrder.list +- order.deliveryOrder.list +- order.deliveryExpectionOrder.list +- order.archiveOrder.list + +是否需要补充其它文档同步? +- 建议同步更新: + - 若有门户/前端 API 文档站(自动生成或展示 methods/system.json 的地方),应部署或刷新以展现新增条目。 + - 若存在 SDK 或对接说明(如 qimen 或第三方对接文档),如使用到工作台 list 场景也建议补充示例请求与常用 where 范例。 + +示例请求(简要) + +请求体示例: +{ + "pagination": { "page": 1, "pageSize": 50 }, + "where": { "delivery_order_code": { "operator": "like", "value": "ABC" }, "create_time_start": { "value": "2026-04-01" } }, + "sort": { "sortField": "updated_at", "sortOrder": "DESC" } +} + +响应示例(简要): +{ + "list": [ /* 订单对象数组 */ ], + "pagination": { "page":1, "pageSize":50, "total":1234, "totalPages":25, "hasPrevious":false, "hasNext":true } +} + +-- +文档维护者:WMS 文档代理 diff --git a/docs/stock-expiry-module.md b/docs/stock-expiry-module.md new file mode 100644 index 0000000..4c17bce --- /dev/null +++ b/docs/stock-expiry-module.md @@ -0,0 +1,80 @@ +# 库存效期模块(定时预警任务) + +本文档基于源码实现(单一事实来源),定位与说明项目中关于库存效期扫描与预警的定时任务行为。实现文件:app/schedule/notice_stock_remaining.js。 + +## 概要 + +- 任务名称/文件:`app/schedule/notice_stock_remaining.js` +- 调度配置:`interval: '30s'`、`type: 'worker'`、`immediate: false`(见文件头部 schedule 配置) +- 目的:扫描启用保质期管理的仓库商品与对应库存(wms_stock_warehouse / wms_storage),对即将到期的库存发送效期预警通知,并通过缓存进行去重。 + +## 主要实现要点(按代码实现逐项说明) + +1. 并发保护 + - 使用进程级标记 `ctx.app._noticeStockRemainingRunning`,若上一轮尚未结束则跳过本次运行。 + +2. 通知去重缓存 + - 缓存键:`notice_stock_remaining_notified_list`(文件常量 `CACHE_KEY`)。 + - 缓存 TTL:24 小时(`CACHE_TTL_SECONDS = 24 * 60 * 60`)。 + - 缓存存储格式兼容数组或对象,读取后标准化为 `storage:{id}` 格式的键集合用于去重。 + +3. 读取候选商品(wms_stock_warehouse) + - 查询条件(stockWhere): + - `is_shelf_life_mgmt: 'Y'` + - `remaining_threshold_days: { [Op.gt]: 0 }`(使用 `Sequelize.Op.gt`) + - 查询字段:`id, item_code, item_name, store_id, warehouse_id, remaining_threshold_days` + - 排序:`remaining_threshold_days ASC, id ASC` + - 结果用于构建 `stockMap`(包含每个 stock 的阈值),并计算 `maxThresholdDays`(用于缩小后续库存扫描时间窗口)。 + +4. 计算候选库存时间窗口 + - 以当前时间 `now`,计算 `maxExpiryDate = new Date(now.getTime() + maxThresholdDays * DAY_MS)`,其中 `DAY_MS = 24 * 60 * 60 * 1000`。 + +5. 查询候选库存记录(wms_storage) + - 查询条件(storageWhere): + - `stock_id` 在上一步筛选得到的 `stockIds` 列表中 + - `is_enabled: 1` + - `delete_at: null`(paranoid 软删除过滤) + - `quantity: { [Op.gt]: 0 }` + - `expiry_date: { [Op.ne]: null, [Op.lte]: maxExpiryDate }`(到期日非空且小于等于计算窗口) + - include:关联 `LocationSpace`(别名 `space`),属性取 `space_code, custom_name`,`required: false`。 + - 排序:`expiry_date ASC, inbound_time ASC, id ASC`。 + - 注意:实现中调用的是 `findAll`(无分页),因此会拉取匹配的全部候选记录并在内存中逐条处理。 + +6. 单条记录处理与判断逻辑 + - 对每条 `storageRecord`: + - 生成去重键 `notifyKey = storage:{storageId}`(若无法解析 id 则跳过)。 + - 若该 `notifyKey` 已存在于缓存集合则跳过(避免重复通知)。 + - 根据 `stockMap` 获取本条记录对应商品的 `thresholdDays`(阈值天数);若不存在或阈值 <= 0 则跳过。 + - 读取 `expiry_date`,将其解析为 Date;若无或解析失败则跳过并记录 warn。 + - 计算剩余天数:`remainingDays = Math.max(0, Math.ceil((expiryDate - now) / DAY_MS))`。 + - 若 `remainingDays > thresholdDays` 则跳过(未达到阈值);否则组装通知并发送。 + +7. 通知发送与元数据 + - 使用通知服务:`ctx.service.systems.notice.send(payload)`。代码中若 `noticeResult.success === false` 则认为发送失败并保留重试;异常时记录错误并继续处理下一条。 + - 通知 payload 包含(示例字段): + - `warehouseId`, `storeId`, `subject`(id/type/name), `businessName: 'storage'`, `event`(常量 `storage_transfer_completed`),`title`, `content`, `businessId: storageId`, `messageType: 'text'` + - `metadata`:包含 `cacheKey`, `storageId`, `stockId`, `notifyKey`, `thresholdDays`, `remainingDays`, `warehouseId`, `storeId`, `stock: { id, item_code, item_name }`, `storage: { id, batch_no, expiry_date (ISO) }` + +8. 回写去重缓存 + - 成功发送后,将 `notifyKey` 添加到 `updatedNotifiedList` 并在本轮结束后使用 `ctx.app.setCacheAsync(CACHE_KEY, dedupedList, CACHE_TTL_SECONDS)` 回写缓存(如果 `setCacheAsync` 可用)。 + +9. 日志与统计 + - 任务会记录候选商品数、候选库存数、实际发送计数与跳过计数;发送失败与异常会记录 warn/error 日志。 + +## 与公开 API 的关系 + +- 任务为内部定时任务(非 system API),其查询条件与模型字段直接对应数据库表 `wms_stock_warehouse` 与 `wms_storage`。 +- 若需要通过 API 查询某个商品的库存明细(包含批次与过期信息),请使用已有的 system 方法 `stock.warehouse.getStockDetail`(该接口支持 `pagination` 与 `group_by_batch`,API 文档位于 `methods/system.json`),与本任务的扫描逻辑互为补充:任务用于主动推送预警,API 用于按需查询。 + +## 注意事项(运维/集成) + +- 通知发送依赖 `ctx.service.systems.notice`,在无该服务或返回异常时任务仅记录日志。 +- 任务扫描不分页:对于极大库存量的仓库,建议评估 `maxThresholdDays` 与索引(`idx_expiry_date` 已存在于模型)对查询性能的影响,或考虑将查询改为分片/分页处理。 +- 去重缓存使用全局缓存接口 `getCacheAsync` / `setCacheAsync`,请保证缓存后台(如 Redis)可用以避免重复通知泛滥。 + +## 实现位置(代码参考) + +- 定时任务文件:app/schedule/notice_stock_remaining.js +- 依赖模型:app/model/stock_warehouse.js、app/model/storage.js、app/model/location_space.js +- 依赖服务:ctx.service.systems.notice + diff --git a/docs/storage-receiving-api.md b/docs/storage-receiving-api.md index 99208f1..eab9ee7 100644 --- a/docs/storage-receiving-api.md +++ b/docs/storage-receiving-api.md @@ -217,3 +217,111 @@ curl -X POST "http://127.0.0.1:6060/system?method=storage.receiving.bindDetailPr - 自动刷新收货单统计数据 适合作为收货单明细与系统商品标准匹配接口对外说明使用。 + +--- + +## 11. 接口:storage.receiving.detailChange + +### 11.1 接口用途 + +用于修改收货单明细(明细行)中的数量、箱规、批次与商品信息,并触发收货单统计与相关联动(例如库存/统计刷新与操作日志)。典型场景为:前端在录入收货明细后,补录实际收货数量、箱数、托盘数、批次/生产/到期信息或回写条码与商品名称等。 + +> 注意:方法在 system 层以 `POST /system?method=storage.receiving.detailChange` 调用,需包含 `Authorization: Bearer `,仓库上下文来源于 `ctx.user.store_id`。 + +### 11.2 请求参数 + +| 字段 | 类型 | 必填 | 说明 | +|---|---:|---:|---| +| `id` | `number` | 是 | 收货明细 ID(必填) | +| `receiving_id` | `number` | 是 | 收货单 ID(必填) | +| `actual_quantity` | `number` | 否 | 实际收货数量 | +| `batch_number` | `string` | 否 | 批次号 | +| `production_date` | `string` | 否 | 生产日期(ISO 或可解析的日期字符串) | +| `expiry_date` | `string` | 否 | 到期日期(ISO 或可解析的日期字符串)。若传入的 `expiry_date` 小于当前日期,接口会拒绝并返回 400(见错误码) | +| `box_quantity` | `number` | 否 | 箱数 | +| `boxes_per_pallet` | `number` | 否 | 每托盘箱数 | +| `pallet_quantity` | `number` | 否 | 托盘数 | +| `space_id` | `number` | 否 | 目标库位 ID(可用于回写库位) | +| `remark` | `string` | 否 | 备注 | +| `system_product_id` | `number` | 否 | 系统商品 ID(StockWarehouse.id)。若提供,系统会回填条码、重量、箱规、商品名称与快照等;若不提供,可单独更新 `barcode`/`product_name` | +| `barcode` | `string` | 否 | 条码(当未传 `system_product_id` 时,可单独更新) | +| `product_name` | `string` | 否 | 商品名称(当未传 `system_product_id` 时,可单独更新) | +| `box_width` | `number` | 否 | 箱宽(单位按系统约定) | +| `box_height` | `number` | 否 | 箱高 | +| `box_length` | `number` | 否 | 箱长 | +| `weight` | `number` | 否 | 毛重/重量 | + +> 说明:`id` 与 `receiving_id` 为必须校验项,其他字段为可选—仅在传入时会写入/覆盖对应明细字段。传入 `system_product_id` 时,系统优先使用系统商品信息回填字段(前端可只传 `system_product_id` 来自动回填)。 + +### 11.3 请求示例 + +```json +{ + "id": 501, + "receiving_id": 123, + "actual_quantity": 10, + "batch_number": "B20260401", + "production_date": "2026-04-01", + "expiry_date": "2027-04-01", + "box_quantity": 2, + "boxes_per_pallet": 10, + "pallet_quantity": 0, + "space_id": 1001, + "remark": "样例备注", + "system_product_id": 8888 +} +``` + +### 11.4 返回结构(成功) + +成功时返回 `code: 200`,`message` 为 `修改成功`,`data` 中包含基础标识与关键展示字段: + +```json +{ + "code": 200, + "message": "修改成功", + "data": { + "id": 501, + "receiving_id": 123, + "actual_quantity": 1, + "product_name": "测试商品", + "barcode": "", + "system_product_id": null, + "updated_at": "2026-04-01T00:00:00.000Z" + } +} +``` + +返回字段说明: + +- `data.id`:收货明细 ID +- `data.receiving_id`:收货单 ID +- `data.actual_quantity`:明细当前的实际收货数量(根据实现,此处返回服务端查询到的明细值) +- `data.product_name`:商品名称(若 `system_product_id` 回填则为系统商品名称) +- `data.barcode`:条码 +- `data.system_product_id`:回填或当前关联的系统商品 ID +- `data.updated_at`:明细记录的更新时间 + +### 11.5 常见错误码 + +| code | message 示例 | 含义 | +|---:|---|---| +| `400` | `收货明细ID不能为空` | 未传 `id` | +| `400` | `收货单ID不能为空` | 未传 `receiving_id` | +| `400` | `到期日期已过期,不能录入收货` | `expiry_date` 小于当前日期时返回(禁止录入已过期批次) | +| `400` | `箱数不能为负数` / `托盘数不能为负数` | 非法的箱规数值 | +| `404` | `收货明细不存在` | 明细不存在或不属于当前仓库/收货单状态不允许操作 | +| `500` | `修改失败,请稍后重试` | 服务端异常 | + +--- + +### 11.6 业务要点与实现说明 + +- 若传入 `system_product_id`,服务端尝试读取 `StockWarehouse`(同仓库)并回填:`barcode`(若前端未显式传入),`weight`,`boxes_per_pallet`、`box_height`、`box_width`、`box_length`(若启用箱规),以及 `product_snapshot` 中的货主快照信息。 +- 若未传 `system_product_id`,但传入 `barcode` 或 `product_name`,服务端仍允许更新这两个字段(并把 `system_product_id` 置为 `null`)。 +- 接口会在成功写入明细后触发收货单统计刷新(`updateReceivingStats`)并写操作日志(`RECEIVING_UPDATE_DETAIL`)。 +- 系统存在一个库存效期预警定时任务,逻辑上会扫描启用保质期管理且设置了剩余天数阈值的商品,并按库存到期日筛选候选记录后进行去重通知发送;其判断条件主要依赖 `wms_stock_warehouse.is_shelf_life_mgmt = 'Y'`、`remaining_threshold_days > 0`,以及 `wms_storage.expiry_date`(小于等于当前时间加最大阈值天数)。 + +--- + + diff --git a/methods/changes/system.json b/methods/changes/system.json index f94cafc..326f26d 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,194 @@ [ + { + "version": "2026.04.17-system-05", + "date": "2026-04-17", + "summary": "新增文档分组:平台编码管理模块(收口 index.getPlatformList 与 setting.platform.*)", + "methods": [ + "index.getPlatformList", + "setting.platform.list", + "setting.platform.create", + "setting.platform.update", + "setting.platform.delete" + ], + "notes": [ + "新增独立文档分组 '平台编码管理模块',将平台基础列表(index.getPlatformList)与平台设置管理接口(setting.platform.*)归并为单一分组以便维护;仅文档变更,不修改实现。", + "文档中仅包含已实现的方法与字段,未新增或推断不存在的参数/返回字段。" + ], + "type": "added" + }, + { + "version": "2026.04.17-system-04", + "date": "2026-04-17", + "summary": "新增独立平台设置模块 setting.platform(wms_platfrom_setting)及其 CRUD 接口:list/create/update/delete。", + "methods": [ + "setting.platform.list", + "setting.platform.create", + "setting.platform.update", + "setting.platform.delete" + ], + "notes": [ + "新增独立模块 setting.platform,映射数据表 wms_platfrom_setting;list 支持 where(id/code/name/platform_code/quickWhere)与 pagination(兼容 page/pageSize/page_size);create/update 要求 platform_code 必须存在于系统平台表(wms_platform),且禁止越权写入 warehouse_id;delete 需传入 id 并校验当前仓库范围。" + ], + "type": "added" + }, + { + "version": "2026.04.15-system-07", + "date": "2026-04-15", + "summary": "将 docs/order-workbench-list-api.md 引用统一为 window 链接格式", + "methods": [ + "order.list", + "order.reviewOrder.list", + "order.pendingOrder.list", + "order.outboundOrder.list", + "order.expectionOrder.list", + "order.entrustOrder.list", + "order.deliveryOrder.list", + "order.deliveryExpectionOrder.list" + ], + "notes": [ + "将所有 methods/system.json 中指向 docs/order-workbench-list-api.md 的说明统一替换为 docs/order-workbench-list-api.md 格式,以便 HTML 渲染识别为 window 链接。", + "仅修改 methods/system.json 的文档字段,不涉及任何业务代码或接口契约变化。" + ], + "type": "updated" + }, + { + "version": "2026.04.15-system-06", + "date": "2026-04-15", + "summary": "订单工作台列表文档补全 raw 字段字典与中文语义说明", + "methods": [ + "order.list", + "order.reviewOrder.list", + "order.pendingOrder.list", + "order.outboundOrder.list", + "order.expectionOrder.list", + "order.entrustOrder.list", + "order.deliveryOrder.list", + "order.deliveryExpectionOrder.list", + "order.archiveOrder.list" + ], + "notes": [ + "在 docs/order-workbench-list-api.md 中补充所有订单列表通用 raw 字段字典,明确每个字段的中文语义与 enum 取值。", + "补充 express_numbers / waybill_codes 两个服务层派生字段说明,便于前端直接渲染多个快递号。", + "methods/system.json 中所有订单 list 的 response.list 描述已指向该字段字典章节。" + ], + "type": "updated" + }, + { + "version": "2026.04.15-system-05", + "date": "2026-04-15", + "summary": "基础模块新增快递/平台列表查询接口并设置为不鉴权,复用缓存 service", + "methods": [ + "index.getExpressList", + "index.getPlatformList" + ], + "notes": [ + "新增 index.getExpressList,归属基础模块(module=index),对应 app/service/systems/express.js 中的 getExpressList。", + "index.getExpressList 设置为不鉴权,不需要 Authorization 头。", + "新增 index.getPlatformList,归属基础模块(module=index),对应 app/service/systems/platform.js 中的 getPlatformList。", + "index.getPlatformList 设置为不鉴权,不需要 Authorization 头。", + "快递列表与平台列表都支持缓存优先,缓存未命中时回源数据库并写入缓存。", + "平台列表支持缓存优先,缓存未命中时回源 wms_platform 并写入缓存。" + ], + "type": "added" + }, + { + "version": "2026.04.15-system-02", + "date": "2026-04-15", + "summary": "签约策略字段元信息新增 default_express_code / default_platform_code list 选项", + "methods": [ + "storeWarehouse.store.getPolicyConfigFields" + ], + "notes": [ + "getPolicyConfigFields 现在返回 default_express_code 与 default_platform_code 两个 list 字段,并从 wms_express / wms_platform 读取选项列表。", + "默认值仍保留为 default_express_code=STO、default_platform_code=TB。" + ], + "type": "updated" + }, + { + "version": "2026.04.15-system-03", + "date": "2026-04-15", + "summary": "签约策略字段移除 sku_visibility,receive_mode options 改为 value/label 结构", + "methods": [ + "storeWarehouse.store.savePolicyConfig", + "storeWarehouse.store.getPolicyConfigFields" + ], + "notes": [ + "策略字段定义不再包含 sku_visibility,历史值读取时仍会被归一化忽略。", + "receive_mode 的 options 改为 [{ value, label }] 格式,便于前端直接渲染。" + ], + "type": "updated" + }, + { + "version": "2026.04.15-system-04", + "date": "2026-04-15", + "summary": "按文件模块拆分 order 目录系统文档分组,覆盖订单工作台入口及各子模块方法", + "methods": [ + "order.list", + "order.manualOutboundOrder", + "order.badgeCount", + "order.outboundOrder.manualOutboundOrder", + "order.reviewOrder.list", + "order.reviewOrder.reviewOrder", + "order.pendingOrder.list", + "order.pendingOrder.reverseReviewOrder", + "order.pendingOrder.markPendingOutboundOrder", + "order.pendingOrder.cancelOrder", + "order.outboundOrder.list", + "order.expectionOrder.list", + "order.entrustOrder.list", + "order.deliveryOrder.list", + "order.deliveryExpectionOrder.list", + "order.archiveOrder.list" + ], + "notes": [ + "按 app/service/systemMethods/order 下的实际对外方法补全 methods/system.json 文档,只覆盖 system,不处理 qimen。", + "order 文档已按 index / reviewOrder / pendingOrder / outboundOrder / expectionOrder / entrustOrder / deliveryOrder / deliveryExpectionOrder / archiveOrder 拆成多个模块分组。", + "同步根据当前代码意图补充 params / response / errors,且不再把 index.js 已移除的兼容接口写回文档。" + ], + "type": "updated" + }, + { + "version": "2026.04.15-system-01", + "date": "2026-04-15", + "summary": "货主主体配置默认补齐 default_express_code / default_platform_code", + "methods": [ + "store.createStore", + "store.createWarehouse" + ], + "notes": [ + "当 subject_config 未传或缺少字段时,自动补齐 default_express_code=STO、default_platform_code=TB,并保留现有的 max_notice_webhook_count 默认值。", + "同步更新 methods/system.json 中 store.createStore 与 store.createWarehouse 的参数说明。" + ], + "type": "updated" + }, + { + "version": "2026.04.14-system-01", + "date": "2026-04-14", + "summary": "库存列表新增货主名称字段 stock.store_name", + "methods": [ + "storage.inventory.list" + ], + "notes": [ + "在 methods/system.json 的 storage.inventory.list response 中补充 stock.store_name:来源于签约表 store_remask,若无签约关系则为 null。", + "只同步文档,不修改业务代码。" + ], + "type": "updated" + }, + { + "version": "2026.04.13-system-01", + "date": "2026-04-13", + "summary": "补全 storage.receiving.detailChange 的入参/出参契约与错误码说明", + "methods": [ + "storage.receiving.detailChange" + ], + "notes": [ + "在 methods/system.json 中补充 storage.receiving.detailChange 的 params/response/errors,明确 id 与 receiving_id 必填。", + "说明 expiry_date 小于当前日期时返回 400 且 message 为 \"到期日期已过期,不能录入收货\"。", + "说明当传入 system_product_id 时会回填条码、重量、箱规、商品名称与 product_snapshot;未传时 barcode/product_name 也可单独更新。", + "同步补充文档:docs/storage-receiving-api.md 中新增 detailChange 段落。" + ], + "type": "updated" + }, { "version": "2026.04.07-system-01", "date": "2026-04-07", @@ -441,4 +631,120 @@ ], "type": "changed" } - ] + , + { + "version": "2026.04.13-system-02", + "date": "2026-04-13", + "summary": "stock.warehouse.search 返回新增效期管理字段并保留 is_shelf_life_mgmt", + "methods": [ + "stock.warehouse.search" + ], + "notes": [ + "响应 data[] 中新增字段:inbound_min_days、outbound_min_days、shelf_life_days、remaining_threshold_days(均为 number,单位:天)。", + "保留并说明 is_shelf_life_mgmt 布尔字段(boolean),表示是否启用效期管理(true=启用)。", + "仅更新文档(methods/system.json 与变更记录),代码行为不变。" + ], + "type": "updated" + }, + { + "version": "2026.04.13-system-02", + "date": "2026-04-13", + "summary": "新增 storage.expiry.list 库存有效期列表查询接口", + "methods": [ + "storage.expiry.list" + ], + "notes": [ + "该接口查询 wms_storage,关联 stockWarehouse 和 locationSpace,并按当前仓库与 remaining_threshold_days / expiry_date 过滤。" + ], + "type": "added" + }, + { + "version": "2026.04.13-system-03", + "date": "2026-04-13", + "summary": "新增 storage.inventory.list 库存列表返回效期字段与预警标记", + "methods": [ + "storage.inventory.list" + ], + "notes": [ + "库存列表响应增加生产日期、过期日期、效期预警是否触发字段", + "预警标记仅在商品启用保质期管理且到期日满足阈值条件时为 true" + ], + "type": "updated" + }, + { + "version": "2026.04.14-system-01", + "date": "2026-04-14", + "summary": "更新 index.searchSpace 文档", + "methods": [ + "index.searchSpace" + ], + "notes": [ + "补充 index.searchSpace 的 params/response,按 ctx.user.store_id 作为仓库上下文;keyword 为可选字符串,对 space_code 与 custom_barcode 做 %keyword% 模糊匹配;返回字段 id、space_code、custom_barcode、custom_name,最多 50 条;仅文档同步,无代码变更。" + ], + "type": "updated" + } + , + { + "version": "2026.04.16-system-01", + "date": "2026-04-16", + "summary": "基础模块新增快递产品类型查询接口", + "methods": [ + "index.getExpressProductTypeList" + ], + "notes": [ + "新增 index.getExpressProductTypeList,归属基础模块(module=index),用于查询指定快递公司的产品类型列表。", + "对应服务实现:app/service/systems/express.js 中的 getExpressProductTypeList,支持传入 express_code 作为可选筛选参数(source=body)。", + "接口设置为免鉴权(isNeedAuth=false)但需登录(isNeedLogin=true),与 index.getExpressList / index.getPlatformList 一致,优先从缓存读取。" + ], + "type": "added" + }, + { + "version": "2026.04.17-system-01", + "date": "2026-04-17", + "summary": "新增快递管理模块(setting.express)及 5 个接口文档", + "methods": [ + "setting.express.list", + "setting.express.listBase", + "setting.express.create", + "setting.express.checkCodeUnique", + "setting.express.update" + ], + "notes": [ + "新增独立模块组:快递管理模块(module=setting.express),将快递映射管理相关接口独立为一组以便维护。", + "接口实现参考:app/service/systems/setting/express.js(返回结构)与 app/service/systemMethods/setting/express.js(对外方法包装)。", + "接口鉴权与上下文:isNeedAuth=false, isNeedLogin=true;需在请求中传入 Authorization 以携带登录上下文(用于获取当前仓库/货主上下文)。", + "已同步更新 methods/system.json,补充 params/response/errors,保持文档与实现一致。" + ], + "type": "added" + }, + { + "version": "2026.04.17-system-02", + "date": "2026-04-17", + "summary": "setting.express.list 分页入参统一为 pagination", + "methods": [ + "setting.express.list" + ], + "notes": [ + "将 setting.express.list 的分页入参文档从顶层 page/page_size/pageSize 迁移为 pagination 对象,主形态为 pagination;兼容 snake_case 的 page_size 与 camelCase 的 pageSize。", + "文档与当前实现一致:顶层 page/page_size/pageSize 会被归一化到 data.pagination 并转发到系统服务。" + ], + "type": "updated" + }, + { + "version": "2026.04.17-system-03", + "date": "2026-04-17", + "summary": "新增快递接口管理模块(setting.expressInterface)及 4 个接口文档", + "methods": [ + "setting.expressInterface.list", + "setting.expressInterface.create", + "setting.expressInterface.update", + "setting.expressInterface.delete" + ], + "notes": [ + "新增独立模块组:快递接口管理模块(module=setting.expressInterface),对应实现:app/service/systems/setting/expressInterface.js 与对外包装 app/service/systemMethods/setting/expressInterface.js。", + "接口为当前仓库范围(基于 ctx.user.store_id),仓库边界由系统服务强制校验;禁止通过接口指定 warehouse_id/warehouseId。操作需登录(isNeedLogin=true),无需额外鉴权(isNeedAuth=false)。", + "已在 methods/system.json 新增对应接口的 params/response/errors 文档,保持与实现一致。" + ], + "type": "added" + } + ] diff --git a/methods/system.json b/methods/system.json index 3b4ddbc..ee2ad0d 100644 --- a/methods/system.json +++ b/methods/system.json @@ -475,7 +475,7 @@ }, { "method": "index.searchSpace", - "description": "index.searchSpace 接口", + "description": "按当前仓库上下文搜索库位(使用 ctx.user.store_id;仅在 location_space 表中按 space_code/custom_barcode 搜索)", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -486,8 +486,64 @@ "description": "Bearer token" } ], - "params": [], - "response": [], + "params": [ + { + "name": "keyword", + "type": "string", + "required": false, + "source": "body", + "description": "搜索关键字,对 space_code 和 custom_barcode 做模糊匹配(%keyword%);为空时返回当前仓库下前 50 条" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "description": "全局调用结果标识,成功时为 success" + }, + { + "name": "code", + "type": "number", + "description": "业务状态码,200 表示成功" + }, + { + "name": "message", + "type": "string", + "description": "返回信息" + }, + { + "name": "data", + "type": "array", + "description": "库位数组(最多 50 条),每项包含以下字段", + "children": [ + { + "name": "id", + "type": "number", + "description": "库位 ID" + }, + { + "name": "space_code", + "type": "string", + "description": "库位编码" + }, + { + "name": "custom_barcode", + "type": "string", + "description": "库位自定义条码" + }, + { + "name": "custom_name", + "type": "string", + "description": "库位自定义名称" + } + ] + }, + { + "name": "total", + "type": "number", + "description": "本次返回的记录条数(等于 data.length,≤50)" + } + ], "errors": [] }, { @@ -500,16 +556,8 @@ { "method": "index.getExpressList", "description": "index.getExpressList 接口", - "isNeedAuth": true, + "isNeedAuth": false, "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], "params": [], "response": [], "errors": [] @@ -517,46 +565,12 @@ ] }, { - "groupName": "订单模块", - "module": "order", + "groupName": "订单工作台入口模块", + "module": "order.index", "list": [ - { - "method": "order.getOrderModels", - "description": "order.getOrderModels 接口", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "order.base.getOrderModels", - "description": "订单模型能力兼容入口(当前与 order.getOrderModels 返回一致)", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, { "method": "order.list", - "description": "分页查询订单列表", + "description": "订单工作台总列表入口,查询当前登录用户仓库上下文下的订单总列表,支持 pagination / where / sort。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -573,22 +587,51 @@ "type": "object", "required": false, "source": "body", - "description": "pagination 参数" + "description": "分页参数,支持 page / pageSize,兼容 currentPage / page_size / size" }, { "name": "where", "type": "object", "required": false, "source": "body", - "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会在 main 中自动标准化;常用字段包括 delivery_order_code、status、step、outbound_status、buyer_nick、mobile 与日期区间字段。示例:where.delivery_order_code={operator:like,value:SO202603}; where.status={operator:in,value:[created,pedding]}; where.step={operator:eq,value:1}。" + "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会自动标准化;禁止传入 warehouse_id / warehouseId。" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数,支持 sortField / sortOrder" } ], - "response": [], - "errors": [] + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节)" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息(page、pageSize、total、totalPages、hasPrevious、hasNext)" + } + ], + "errors": [ + { + "code": "400", + "description": "缺少仓库上下文或 where 参数格式错误" + }, + { + "code": "500", + "description": "查询失败" + } + ] }, { - "method": "order.detail", - "description": "查询订单详情", + "method": "order.manualOutboundOrder", + "description": "手动触发出库迁移,将当前仓库内已出库订单同步到配送表。请求体直接透传给 orderDeliveryMigration.syncOutboundOrdersToDelivery。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -601,231 +644,601 @@ ], "params": [ { - "name": "delivery_order_code", - "type": "string", + "name": "warehouseId", + "type": "number", "required": false, "source": "body", - "description": "delivery_order_code 参数" + "description": "单仓库ID,兼容 warehouse_id" + }, + { + "name": "warehouseIds", + "type": "array", + "required": false, + "source": "body", + "description": "仓库ID 数组" + }, + { + "name": "queryTimeoutMs", + "type": "number", + "required": false, + "source": "body", + "description": "查询超时时间(毫秒)" + }, + { + "name": "executionTimeoutMs", + "type": "number", + "required": false, + "source": "body", + "description": "执行超时时间(毫秒)" + } + ], + "response": [ + { + "name": "warehouseIds", + "type": "array", + "required": true, + "description": "参与迁移的仓库ID列表" + }, + { + "name": "batchSize", + "type": "number", + "required": true, + "description": "单批处理上限,当前固定为 1000" + }, + { + "name": "outboundStatuses", + "type": "array", + "required": true, + "description": "本次迁移匹配的出库状态" + }, + { + "name": "totalSelected", + "type": "number", + "required": true, + "description": "命中的源订单数量" + }, + { + "name": "totalCreated", + "type": "number", + "required": true, + "description": "实际创建到配送表的订单数量" + }, + { + "name": "totalSkipped", + "type": "number", + "required": true, + "description": "本次跳过的源订单数量" + }, + { + "name": "totalTimeout", + "type": "number", + "required": true, + "description": "被标记为出库超时的订单数量" + }, + { + "name": "results", + "type": "array", + "required": true, + "description": "按仓库维度返回的批次结果数组,元素包含 selectedCount、createdCount、skippedCount、timeoutCount、retryableFailure 等字段" + } + ], + "errors": [ + { + "code": "400", + "description": "仓库ID为空或请求参数格式错误" + }, + { + "code": "500", + "description": "迁移失败或数据库错误" + } + ] + }, + { + "method": "order.badgeCount", + "description": "订单工作台各标签页角标计数,基于当前仓库上下文返回。配送、配送异常与归档标签固定返回 99+。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "reviewOrder", + "type": "number|string", + "required": true, + "description": "待审核角标" + }, + { + "name": "pendingOrder", + "type": "number|string", + "required": true, + "description": "待处理角标" + }, + { + "name": "outboundOrder", + "type": "number|string", + "required": true, + "description": "待出库角标" + }, + { + "name": "expectionOrder", + "type": "number|string", + "required": true, + "description": "待处理异常角标" + }, + { + "name": "entrustOrder", + "type": "number|string", + "required": true, + "description": "委托外仓角标" + }, + { + "name": "deliveryOrder", + "type": "string", + "required": true, + "description": "配送角标,固定返回 99+" + }, + { + "name": "deliveryExpectionOrder", + "type": "string", + "required": true, + "description": "配送异常角标,固定返回 99+" + }, + { + "name": "archiveOrder", + "type": "string", + "required": true, + "description": "归档角标,固定返回 99+" + } + ], + "errors": [ + { + "code": "400", + "description": "缺少当前仓库上下文 store_id" + } + ] + } + ] + }, + { + "groupName": "订单待审核模块", + "module": "order.reviewOrder", + "list": [ + { + "method": "order.reviewOrder.list", + "description": "待审核订单列表,默认仅查询 step=0 的订单。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数,支持 page / pageSize" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "统一 where 条件对象;禁止传入 warehouse_id / warehouseId。" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数,支持 sortField / sortOrder" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节)" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息" + } + ], + "errors": [ + { + "code": "400", + "description": "参数格式错误或缺少仓库上下文" + }, + { + "code": "500", + "description": "查询失败" + } + ] + }, + { + "method": "order.reviewOrder.reviewOrder", + "description": "批量审核通过订单并进入待处理。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids", + "type": "array", + "required": true, + "source": "body", + "description": "订单 ID 数组;仅允许 ids 字段,建议传数组,也兼容逗号字符串或单值" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "首条更新记录 ID" + }, + { + "name": "inspection_status", + "type": "string", + "required": true, + "description": "新的审核状态" + }, + { + "name": "step", + "type": "number", + "required": true, + "description": "新的流程步骤" + }, + { + "name": "updated_at", + "type": "string", + "required": true, + "description": "更新时间" + }, + { + "name": "updated_count", + "type": "number", + "required": true, + "description": "受影响行数" + }, + { + "name": "ids", + "type": "array", + "required": true, + "description": "实际更新的订单 ID 列表" + } + ], + "errors": [ + { + "code": "400", + "description": "ids 不能为空或格式错误" + }, + { + "code": "404", + "description": "订单不存在或不属于当前仓库" + } + ] + } + ] + }, + { + "groupName": "订单待处理模块", + "module": "order.pendingOrder", + "list": [ + { + "method": "order.pendingOrder.list", + "description": "待处理订单列表,默认筛选 outbound_status != padding 且 step in [1,2]。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数,支持 page / pageSize" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "统一 where 条件对象;禁止传入 warehouse_id / warehouseId。" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数,支持 sortField / sortOrder" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节)" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息" + } + ], + "errors": [ + { + "code": "400", + "description": "参数格式错误或缺少仓库上下文" + }, + { + "code": "500", + "description": "查询失败" + } + ] + }, + { + "method": "order.pendingOrder.reverseReviewOrder", + "description": "将待处理订单反审回待审核状态。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids", + "type": "array", + "required": false, + "source": "body", + "description": "订单 ID 列表;兼容 ids / id / order_id,建议传 ids" }, { "name": "id", "type": "number", "required": false, "source": "body", - "description": "id 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "order.listItems", - "description": "查询订单商品明细", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "delivery_order_code", - "type": "string", - "required": false, - "source": "body", - "description": "delivery_order_code 参数" + "description": "兼容单个订单 ID" }, { "name": "order_id", "type": "number", "required": false, "source": "body", - "description": "order_id 参数" + "description": "兼容单个订单 ID" } ], - "response": [], - "errors": [] - }, - { - "method": "order.stats", - "description": "订单统计", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "where", - "type": "object", - "required": false, - "source": "body", - "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会在 main 中自动标准化;统计口径与 order.list 共用筛选字段。示例:where.status={operator:eq,value:fin}; where.create_time_start={value:2026-03-01}; where.create_time_end={value:2026-03-31}。" - } - ], - "response": [], - "errors": [] - }, - { - "method": "order.getreviewOrderlist", - "description": "分页查询订单审核列表", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "pagination", - "type": "object", - "required": false, - "source": "body", - "description": "pagination 参数" - }, - { - "name": "where", - "type": "object", - "required": false, - "source": "body", - "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构;支持 inspection_status、step、operator_name、operate_time_start、operate_time_end 等字段。示例:where.step={operator:in,value:[0,1]}; where.inspection_status={operator:eq,value:pending}; where.operator_name={operator:like,value:张}; where.operate_time_start={value:2026-03-01}。" - } - ], - "response": [], - "errors": [] - }, - { - "method": "order.updateStatus", - "description": "更新订单状态", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "claim_status", - "type": "string", - "required": false, - "source": "body", - "description": "claim_status 参数" - }, - { - "name": "delivery_order_code", - "type": "string", - "required": false, - "source": "body", - "description": "delivery_order_code 参数" - }, - { - "name": "delivery_time", - "type": "string", - "required": false, - "source": "body", - "description": "delivery_time 参数" - }, + "response": [ { "name": "id", "type": "number", - "required": false, - "source": "body", - "description": "id 参数" + "required": true, + "description": "首条更新记录 ID" }, { "name": "inspection_status", "type": "string", - "required": false, - "source": "body", - "description": "inspection_status 参数" + "required": true, + "description": "新的审核状态" }, { - "name": "intercept_status", - "type": "string", - "required": false, - "source": "body", - "description": "intercept_status 参数" + "name": "step", + "type": "number", + "required": true, + "description": "新的流程步骤" }, { - "name": "lock_status", + "name": "updated_at", "type": "string", - "required": false, + "required": true, + "description": "更新时间" + }, + { + "name": "updated_count", + "type": "number", + "required": true, + "description": "受影响行数" + }, + { + "name": "ids", + "type": "array", + "required": true, + "description": "实际更新的订单 ID 列表" + } + ], + "errors": [ + { + "code": "400", + "description": "订单ID 不能为空或格式错误" + }, + { + "code": "404", + "description": "订单不存在或不属于当前仓库" + } + ] + }, + { + "method": "order.pendingOrder.markPendingOutboundOrder", + "description": "将待处理订单批量标记为待出库。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids", + "type": "array", + "required": true, "source": "body", - "description": "lock_status 参数" + "description": "订单 ID 正整数数组;不支持 id、order_id 或逗号字符串" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "首条更新记录 ID" }, { "name": "outbound_status", "type": "string", - "required": false, - "source": "body", - "description": "outbound_status 参数" + "required": true, + "description": "新的出库状态" }, { - "name": "pack_status", + "name": "updated_at", "type": "string", - "required": false, - "source": "body", - "description": "pack_status 参数" + "required": true, + "description": "更新时间" }, { - "name": "pick_status", - "type": "string", - "required": false, - "source": "body", - "description": "pick_status 参数" + "name": "updated_count", + "type": "number", + "required": true, + "description": "受影响行数" }, { - "name": "post_status", - "type": "string", - "required": false, - "source": "body", - "description": "post_status 参数" + "name": "ids", + "type": "array", + "required": true, + "description": "实际更新的订单 ID 列表" + } + ], + "errors": [ + { + "code": "400", + "description": "ids 必须为正整数数组" }, { - "name": "print_status", + "code": "404", + "description": "订单不存在或不属于当前仓库" + } + ] + }, + { + "method": "order.pendingOrder.cancelOrder", + "description": "将待处理订单批量取消,仅允许当前状态可取消的订单。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", "type": "string", - "required": false, + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids", + "type": "array", + "required": true, "source": "body", - "description": "print_status 参数" + "description": "订单 ID 正整数数组;不支持 id、order_id 或逗号字符串" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "首条更新记录 ID" }, { "name": "status", "type": "string", - "required": false, - "source": "body", - "description": "status 参数" + "required": true, + "description": "新的订单状态" }, { - "name": "storage_status", + "name": "step", + "type": "number", + "required": true, + "description": "新的流程步骤" + }, + { + "name": "updated_at", "type": "string", - "required": false, - "source": "body", - "description": "storage_status 参数" + "required": true, + "description": "更新时间" + }, + { + "name": "updated_count", + "type": "number", + "required": true, + "description": "受影响行数" + }, + { + "name": "ids", + "type": "array", + "required": true, + "description": "实际更新的订单 ID 列表" } ], - "response": [], - "errors": [] - }, + "errors": [ + { + "code": "400", + "description": "ids 必填或当前状态不允许取消" + }, + { + "code": "404", + "description": "订单不存在或不属于当前仓库" + } + ] + } + ] + }, + { + "groupName": "订单待出库模块", + "module": "order.outboundOrder", + "list": [ { - "method": "order.updateDeliveryTime", - "description": "更新发货时间", + "method": "order.outboundOrder.list", + "description": "待出库订单列表,默认筛选 outbound_status in [none,padding] 且 step in [1,2]。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -838,19 +1251,55 @@ ], "params": [ { - "name": "delivery_time", - "type": "string", - "required": true, + "name": "pagination", + "type": "object", + "required": false, "source": "body", - "description": "delivery_time 参数" + "description": "分页参数,支持 page / pageSize" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "统一 where 条件对象;禁止传入 warehouse_id / warehouseId。" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数,支持 sortField / sortOrder" } ], - "response": [], - "errors": [] + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节)" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息" + } + ], + "errors": [ + { + "code": "400", + "description": "参数格式错误或缺少仓库上下文" + }, + { + "code": "500", + "description": "查询失败" + } + ] }, { - "method": "order.reviewOrder", - "description": "订单审核", + "method": "order.outboundOrder.manualOutboundOrder", + "description": "待出库模块的手动出库入口,行为与 order.manualOutboundOrder 一致。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -863,146 +1312,104 @@ ], "params": [ { - "name": "delivery_order_code", - "type": "string", - "required": false, - "source": "body", - "description": "delivery_order_code 参数" - }, - { - "name": "id", + "name": "warehouseId", "type": "number", "required": false, "source": "body", - "description": "id 参数" + "description": "单仓库ID,兼容 warehouse_id" }, { - "name": "inspection_status", - "type": "string", + "name": "warehouseIds", + "type": "array", "required": false, "source": "body", - "description": "inspection_status 参数(兼容入参)" + "description": "仓库ID 数组" }, { - "name": "review_status", - "type": "string", - "required": false, - "source": "body", - "description": "review_status 参数,默认 fin" - }, - { - "name": "operator_name", - "type": "string", - "required": false, - "source": "body", - "description": "operator_name 参数" - }, - { - "name": "operate_time", - "type": "string", - "required": false, - "source": "body", - "description": "operate_time 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "order.reviewOrder.getreviewOrderlist", - "description": "分页查询订单审核列表(目录化路由)", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "pagination", - "type": "object", - "required": false, - "source": "body", - "description": "pagination 参数" - }, - { - "name": "where", - "type": "object", - "required": false, - "source": "body", - "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构;支持 inspection_status、step、operator_name、operate_time_start、operate_time_end 等字段。示例:where.step={operator:in,value:[0,1]}; where.inspection_status={operator:eq,value:pending}; where.operator_name={operator:like,value:张}; where.operate_time_start={value:2026-03-01}。" - } - ], - "response": [], - "errors": [] - }, - { - "method": "order.reviewOrder.reviewOrder", - "description": "订单审核(目录化路由)。执行后会更新 inspection_status,并同步更新订单整数字段 step。", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "delivery_order_code", - "type": "string", - "required": false, - "source": "body", - "description": "delivery_order_code 参数" - }, - { - "name": "id", + "name": "queryTimeoutMs", "type": "number", "required": false, "source": "body", - "description": "id 参数" + "description": "查询超时时间(毫秒)" }, { - "name": "inspection_status", - "type": "string", + "name": "executionTimeoutMs", + "type": "number", "required": false, "source": "body", - "description": "inspection_status 参数(兼容入参)" - }, - { - "name": "review_status", - "type": "string", - "required": false, - "source": "body", - "description": "review_status 参数,默认 fin" - }, - { - "name": "operator_name", - "type": "string", - "required": false, - "source": "body", - "description": "operator_name 参数" - }, - { - "name": "operate_time", - "type": "string", - "required": false, - "source": "body", - "description": "operate_time 参数" + "description": "执行超时时间(毫秒)" } ], - "response": [], - "errors": [] - }, + "response": [ + { + "name": "warehouseIds", + "type": "array", + "required": true, + "description": "参与迁移的仓库ID列表" + }, + { + "name": "batchSize", + "type": "number", + "required": true, + "description": "单批处理上限,当前固定为 1000" + }, + { + "name": "outboundStatuses", + "type": "array", + "required": true, + "description": "本次迁移匹配的出库状态" + }, + { + "name": "totalSelected", + "type": "number", + "required": true, + "description": "命中的源订单数量" + }, + { + "name": "totalCreated", + "type": "number", + "required": true, + "description": "实际创建到配送表的订单数量" + }, + { + "name": "totalSkipped", + "type": "number", + "required": true, + "description": "本次跳过的源订单数量" + }, + { + "name": "totalTimeout", + "type": "number", + "required": true, + "description": "被标记为出库超时的订单数量" + }, + { + "name": "results", + "type": "array", + "required": true, + "description": "按仓库维度返回的批次结果数组,元素包含 selectedCount、createdCount、skippedCount、timeoutCount、retryableFailure 等字段" + } + ], + "errors": [ + { + "code": "400", + "description": "仓库ID为空或请求参数格式错误" + }, + { + "code": "500", + "description": "迁移失败或数据库错误" + } + ] + } + ] + }, + { + "groupName": "订单异常模块", + "module": "order.expectionOrder", + "list": [ { - "method": "order.deliveryOrder.getdeliveryOrderlist", - "description": "分页查询已进入出库流程的订单列表", + "method": "order.expectionOrder.list", + "description": "待处理异常订单列表,默认仅查询 step=3 的订单。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -1019,22 +1426,57 @@ "type": "object", "required": false, "source": "body", - "description": "pagination 参数" + "description": "分页参数,支持 page / pageSize" }, { "name": "where", "type": "object", "required": false, "source": "body", - "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构;未传 outbound_status 时默认过滤 outbound_status != none;支持 step 筛选。示例:where.outbound_status={operator:in,value:[created,processing]}; where.step={operator:in,value:[4,5]}; where.store_id={operator:eq,value:1001}。" + "description": "统一 where 条件对象;禁止传入 warehouse_id / warehouseId。" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数,支持 sortField / sortOrder" } ], - "response": [], - "errors": [] - }, + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节)" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息" + } + ], + "errors": [ + { + "code": "400", + "description": "参数格式错误或缺少仓库上下文" + }, + { + "code": "500", + "description": "查询失败" + } + ] + } + ] + }, + { + "groupName": "订单委托外仓模块", + "module": "order.entrustOrder", + "list": [ { - "method": "order.pendingOrder.getpendingOrderlist", - "description": "分页查询待处理订单列表", + "method": "order.entrustOrder.list", + "description": "委托外仓订单列表,使用 outsourced 模型。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -1051,22 +1493,57 @@ "type": "object", "required": false, "source": "body", - "description": "pagination 参数" + "description": "分页参数,支持 page / pageSize" }, { "name": "where", "type": "object", "required": false, "source": "body", - "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构;未传时默认 status in [pedding, created] 且 outbound_status = none。示例:where.status={operator:in,value:[pedding,created]}; where.outbound_status={operator:eq,value:none}。" + "description": "统一 where 条件对象;禁止传入 warehouse_id / warehouseId。" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数,支持 sortField / sortOrder" } ], - "response": [], - "errors": [] - }, + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节)" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息" + } + ], + "errors": [ + { + "code": "400", + "description": "参数格式错误或缺少仓库上下文" + }, + { + "code": "500", + "description": "查询失败" + } + ] + } + ] + }, + { + "groupName": "订单配送模块", + "module": "order.deliveryOrder", + "list": [ { - "method": "order.expectionOrder.getexpectionOrderlist", - "description": "分页查询异常订单列表", + "method": "order.deliveryOrder.list", + "description": "配送订单列表,使用 dispatch 模型,默认筛选 dispatch_lane=m4。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -1083,22 +1560,57 @@ "type": "object", "required": false, "source": "body", - "description": "pagination 参数" + "description": "分页参数,支持 page / pageSize" }, { "name": "where", "type": "object", "required": false, "source": "body", - "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构;未传时默认筛选各流程 error 或拦截 exception。示例:where.status={operator:eq,value:error}; where.outbound_status={operator:eq,value:exception}。" + "description": "统一 where 条件对象;禁止传入 warehouse_id / warehouseId。" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数,支持 sortField / sortOrder" } ], - "response": [], - "errors": [] - }, + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节)" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息" + } + ], + "errors": [ + { + "code": "400", + "description": "参数格式错误或缺少仓库上下文" + }, + { + "code": "500", + "description": "查询失败" + } + ] + } + ] + }, + { + "groupName": "订单配送异常模块", + "module": "order.deliveryExpectionOrder", + "list": [ { - "method": "order.archiveOrder.getarchiveOrderlist", - "description": "分页查询归档订单列表(暂使用当前订单表完成态数据)", + "method": "order.deliveryExpectionOrder.list", + "description": "配送异常订单列表,使用 dispatch 模型,默认筛选 dispatch_lane=m5。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -1115,18 +1627,114 @@ "type": "object", "required": false, "source": "body", - "description": "pagination 参数" + "description": "分页参数,支持 page / pageSize" }, { "name": "where", "type": "object", "required": false, "source": "body", - "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构;未传 outbound_status 时默认过滤 outbound_status = fin。示例:where.outbound_status={operator:eq,value:fin}; where.store_id={operator:eq,value:1001}。" + "description": "统一 where 条件对象;禁止传入 warehouse_id / warehouseId。" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数,支持 sortField / sortOrder" } ], - "response": [], - "errors": [] + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节)" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息" + } + ], + "errors": [ + { + "code": "400", + "description": "参数格式错误或缺少仓库上下文" + }, + { + "code": "500", + "description": "查询失败" + } + ] + } + ] + }, + { + "groupName": "订单归档模块", + "module": "order.archiveOrder", + "list": [ + { + "method": "order.archiveOrder.list", + "description": "归档订单列表,使用 history 模型。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数,支持 page / pageSize" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "统一 where 条件对象;禁止传入 warehouse_id / warehouseId。" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数,支持 sortField / sortOrder" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "订单列表(raw 行数据)" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息" + } + ], + "errors": [ + { + "code": "400", + "description": "参数格式错误或缺少仓库上下文" + }, + { + "code": "500", + "description": "查询失败" + } + ] } ] }, @@ -1745,6 +2353,89 @@ } ] }, + { + "groupName": "平台编码管理模块", + "module": "setting.platform", + "list": [ + { + "method": "index.getPlatformList", + "description": "合并后的平台列表", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [], + "response": [], + "errors": [] + }, + { + "method": "setting.platform.list", + "description": "查询当前仓库范围的平台设置列表", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "setting.platform.create", + "description": "创建当前仓库范围的平台设置", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "setting.platform.update", + "description": "更新当前仓库范围的平台设置", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "setting.platform.delete", + "description": "删除当前仓库范围的平台设置", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + } + ] + }, { "groupName": "账号管理模块", "module": "setting.account", @@ -3008,6 +3699,31 @@ "type": "object", "description": "关联的货主签约信息(LEFT JOIN),含 store_id、store_remask;无签约时为 null" }, + { + "name": "is_shelf_life_mgmt", + "type": "boolean", + "description": "是否启用效期管理(true=启用)" + }, + { + "name": "shelf_life_days", + "type": "number", + "description": "商品标准效期/保质期(单位:天)" + }, + { + "name": "inbound_min_days", + "type": "number", + "description": "入库后最小可出库天数(单位:天)" + }, + { + "name": "outbound_min_days", + "type": "number", + "description": "出库前需保留的最小天数(单位:天)" + }, + { + "name": "remaining_threshold_days", + "type": "number", + "description": "剩余天数阈值,低于该值视为即将过期(单位:天)" + }, { "name": "storage", "type": "array", @@ -3247,8 +3963,8 @@ ] }, { - "groupName": "库存模块", - "module": "storage", + "groupName": "收货单模块", + "module": "storage_receiving", "list": [ { "method": "storage.receiving.getReceivingList", @@ -3761,7 +4477,7 @@ }, { "method": "storage.receiving.detailChange", - "description": "storage.receiving.detailChange 接口", + "description": "修改收货单明细(数量/箱规/批次/商品信息回写等)", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -3772,9 +4488,192 @@ "description": "Bearer token" } ], - "params": [], - "response": [], - "errors": [] + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "收货明细ID" + }, + { + "name": "receiving_id", + "type": "number", + "required": true, + "source": "body", + "description": "收货单ID" + }, + { + "name": "actual_quantity", + "type": "number", + "required": false, + "source": "body", + "description": "实际收货数量" + }, + { + "name": "batch_number", + "type": "string", + "required": false, + "source": "body", + "description": "批次号" + }, + { + "name": "production_date", + "type": "string", + "required": false, + "source": "body", + "description": "生产日期(可解析的日期字符串)" + }, + { + "name": "expiry_date", + "type": "string", + "required": false, + "source": "body", + "description": "到期日期(可解析的日期字符串)。若早于当前日期,接口会返回 400 并拒绝录入。" + }, + { + "name": "box_quantity", + "type": "number", + "required": false, + "source": "body", + "description": "箱数" + }, + { + "name": "boxes_per_pallet", + "type": "number", + "required": false, + "source": "body", + "description": "每托盘箱数" + }, + { + "name": "pallet_quantity", + "type": "number", + "required": false, + "source": "body", + "description": "托盘数" + }, + { + "name": "space_id", + "type": "number", + "required": false, + "source": "body", + "description": "库位 ID(可回写)" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注" + }, + { + "name": "system_product_id", + "type": "number", + "required": false, + "source": "body", + "description": "系统商品 ID(StockWarehouse.id)。若提供,服务端会尝试回填 barcode/weight/箱规/product_name/product_snapshot 等。" + }, + { + "name": "barcode", + "type": "string", + "required": false, + "source": "body", + "description": "条码(未传 system_product_id 时可单独更新)" + }, + { + "name": "product_name", + "type": "string", + "required": false, + "source": "body", + "description": "商品名称(未传 system_product_id 时可单独更新)" + }, + { + "name": "box_width", + "type": "number", + "required": false, + "source": "body", + "description": "箱宽" + }, + { + "name": "box_height", + "type": "number", + "required": false, + "source": "body", + "description": "箱高" + }, + { + "name": "box_length", + "type": "number", + "required": false, + "source": "body", + "description": "箱长" + }, + { + "name": "weight", + "type": "number", + "required": false, + "source": "body", + "description": "毛重/重量" + } + ], + "response": [ + { + "name": "data.id", + "type": "number", + "required": true, + "description": "收货明细 ID" + }, + { + "name": "data.receiving_id", + "type": "number", + "required": true, + "description": "收货单 ID" + }, + { + "name": "data.actual_quantity", + "type": "number", + "required": false, + "description": "实际收货数量" + }, + { + "name": "data.product_name", + "type": "string", + "required": false, + "description": "商品名称" + }, + { + "name": "data.barcode", + "type": "string", + "required": false, + "description": "条码" + }, + { + "name": "data.system_product_id", + "type": "number", + "required": false, + "description": "系统商品 ID" + }, + { + "name": "data.updated_at", + "type": "string", + "required": false, + "description": "记录更新时间(ISO)" + } + ], + "errors": [ + { + "code": "400", + "description": "收货明细ID不能为空 / 收货单ID不能为空 / 到期日期已过期,不能录入收货 / 箱数/托盘数不能为负数等参数校验失败" + }, + { + "code": "404", + "description": "收货明细不存在或无权访问" + }, + { + "code": "500", + "description": "服务器错误或修改失败" + } + ] }, { "method": "storage.receiving.cancel", @@ -4245,12 +5144,30 @@ ] }, "errors": [ - { "code": 400, "message": "receiving_id 必填" }, - { "code": 400, "message": "收货单状态须为已完成" }, - { "code": 400, "message": "商品未匹配系统商品" }, - { "code": 400, "message": "已全部入库无需重复操作" }, - { "code": 404, "message": "收货单不存在或无权访问" }, - { "code": 409, "message": "库存记录被锁定(行锁超时)" } + { + "code": 400, + "message": "receiving_id 必填" + }, + { + "code": 400, + "message": "收货单状态须为已完成" + }, + { + "code": 400, + "message": "商品未匹配系统商品" + }, + { + "code": 400, + "message": "已全部入库无需重复操作" + }, + { + "code": 404, + "message": "收货单不存在或无权访问" + }, + { + "code": 409, + "message": "库存记录被锁定(行锁超时)" + } ] }, { @@ -4296,10 +5213,22 @@ "warnings": "匹配过程中的警告信息列表" }, "errors": [ - { "code": 400, "message": "receiving_ids 必填且为数组" }, - { "code": 400, "message": "entry_order_ids 必填且为数组" }, - { "code": 404, "message": "收货单不存在或无权访问" }, - { "code": 404, "message": "入库单不存在或无权访问" } + { + "code": 400, + "message": "receiving_ids 必填且为数组" + }, + { + "code": 400, + "message": "entry_order_ids 必填且为数组" + }, + { + "code": 404, + "message": "收货单不存在或无权访问" + }, + { + "code": 404, + "message": "入库单不存在或无权访问" + } ] }, { @@ -4339,12 +5268,30 @@ "message": "结果说明" }, "errors": [ - { "code": 400, "message": "storage_id 必填" }, - { "code": 400, "message": "target_space_id 必填" }, - { "code": 400, "message": "移库数量必须大于0且不超过可用库存" }, - { "code": 400, "message": "目标库位与原库位相同" }, - { "code": 404, "message": "库存记录不存在或无权访问" }, - { "code": 404, "message": "目标库位不存在或不属于该仓库" } + { + "code": 400, + "message": "storage_id 必填" + }, + { + "code": 400, + "message": "target_space_id 必填" + }, + { + "code": 400, + "message": "移库数量必须大于0且不超过可用库存" + }, + { + "code": 400, + "message": "目标库位与原库位相同" + }, + { + "code": 404, + "message": "库存记录不存在或无权访问" + }, + { + "code": 404, + "message": "目标库位不存在或不属于该仓库" + } ] }, { @@ -4423,6 +5370,7 @@ ], "response": { "_note": "响应结构因 group_by_batch 而异", + "_shelf_life_note": "production_date 和 expiry_date 为库存批次日期字段;is_shelf_life_warning_triggered 表示该库存在商品启用保质期管理且剩余天数小于等于阈值时是否触发效期预警。", "list_merged": { "_description": "group_by_batch=false(默认合并模式)", "list": [ @@ -4438,11 +5386,30 @@ "first_inbound_time": "最早入库时间", "last_inbound_time": "最晚入库时间", "batch_count": "批次数", - "stock": { "id": "商品ID", "item_code": "商品编码", "item_name": "商品名称", "sku_property": "规格", "stock_unit": "单位" }, - "space": { "id": "库位ID", "space_code": "库位编码", "custom_name": "库位名称" } + "production_date": "生产日期(库存批次日期字段,合并模式下可能为 null)", + "expiry_date": "过期日期(库存批次日期字段,合并模式下可能为 null)", + "is_shelf_life_warning_triggered": "布尔,表示效期预警是否触发(仅在商品启用保质期管理且剩余天数 ≤ 阈值时为 true)", + "stock": { + "id": "商品ID", + "item_code": "商品编码", + "item_name": "商品名称", + "sku_property": "规格", + "stock_unit": "单位", + "store_name": "货主名称(来源于签约表 store_remask,若无签约关系则为 null)" + }, + "space": { + "id": "库位ID", + "space_code": "库位编码", + "custom_name": "库位名称" + } } ], - "pagination": { "page": 1, "pageSize": 20, "total": 100, "totalPages": 5 } + "pagination": { + "page": 1, + "pageSize": 20, + "total": 100, + "totalPages": 5 + } }, "list_detail": { "_description": "group_by_batch=true(明细模式)", @@ -4458,8 +5425,8 @@ "quantity": "库存数量", "locked_quantity": "锁定数量", "available_quantity": "可用数量", - "production_date": "生产日期", - "expiry_date": "过期日期", + "production_date": "生产日期(库存批次日期字段)", + "expiry_date": "过期日期(库存批次日期字段)", "inbound_time": "入库时间", "inbound_order_no": "入库单号", "receiving_id": "收货单ID", @@ -4467,14 +5434,167 @@ "supplier_batch_no": "供应商批次号", "created_at": "创建时间", "updated_at": "更新时间", - "stock": { "id": "商品ID", "item_code": "商品编码", "item_name": "商品名称", "sku_property": "规格", "stock_unit": "单位" }, - "space": { "id": "库位ID", "space_code": "库位编码", "custom_name": "库位名称" } + "is_shelf_life_warning_triggered": "布尔,表示效期预警是否触发(仅在商品启用保质期管理且剩余天数 ≤ 阈值时为 true)", + "stock": { + "id": "商品ID", + "item_code": "商品编码", + "item_name": "商品名称", + "sku_property": "规格", + "stock_unit": "单位", + "store_name": "货主名称(来源于签约表 store_remask,若无签约关系则为 null)" + }, + "space": { + "id": "库位ID", + "space_code": "库位编码", + "custom_name": "库位名称" + } } ], - "pagination": { "page": 1, "pageSize": 20, "total": 100, "totalPages": 5 } + "pagination": { + "page": 1, + "pageSize": 20, + "total": 100, + "totalPages": 5 + } } } }, + { + "method": "storage.expiry.list", + "description": "库存有效期列表查询(效期预警),按 wms_storage 查询并计算剩余天数与过期状态,支持 where 条件与分页。注意:无需传 warehouse_id/store_id,服务端会从当前登录用户取仓库上下文。", + "name": "库存有效期列表(或:库存效期预警列表)", + "isNeedAuth": false, + "isNeedLogin": true, + "isNeedRight": false, + "params": [ + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "统一 where 条件对象;支持字段:item_code、goods_code、item_name、sku_property、stock_unit、is_shelf_life_mgmt、remaining_threshold_days。示例:where.item_code={operator:like,value:ABC}; where.remaining_threshold_days={operator:lte,value:7}。注意:无需传入 store_id 或 warehouse_id,服务端会从当前登录用户获取仓库上下文。" + }, + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数 { page, pageSize },默认 page=1, pageSize=20" + } + ], + "response": [ + { + "name": "data.list", + "type": "array", + "required": true, + "description": "匹配到的库存效期项数组" + }, + { + "name": "data.list[]", + "type": "object", + "description": "列表项,包含至少以下字段", + "children": [ + { + "name": "id", + "type": "number", + "description": "库存记录ID(wms_storage.id)" + }, + { + "name": "warehouse_id", + "type": "number", + "description": "仓库ID" + }, + { + "name": "store_id", + "type": "number", + "description": "货主ID" + }, + { + "name": "space_id", + "type": "number", + "description": "库位ID" + }, + { + "name": "stock_id", + "type": "number", + "description": "商品库存ID(stock_warehouse.id)" + }, + { + "name": "batch_no", + "type": "string", + "description": "批次号" + }, + { + "name": "quantity", + "type": "number", + "description": "库存数量" + }, + { + "name": "expiry_date", + "type": "string", + "description": "过期/到期日期(ISO)" + }, + { + "name": "remaining_days", + "type": "number", + "description": "距到期剩余天数(正数表示未过期,0 当日到期,负数表示已过期)" + }, + { + "name": "threshold_days", + "type": "number", + "description": "阈值天数,优先使用传入 remaining_threshold_days,否则使用商品配置" + }, + { + "name": "is_expired", + "type": "boolean", + "description": "是否已过期(true=已过期)" + }, + { + "name": "stock", + "type": "object", + "description": "关联商品信息(id、item_code、item_name、sku_property、stock_unit 等)" + }, + { + "name": "space", + "type": "object", + "description": "关联库位信息(id、space_code、custom_name 等)" + }, + { + "name": "created_at", + "type": "string", + "description": "记录创建时间" + }, + { + "name": "updated_at", + "type": "string", + "description": "记录更新时间" + }, + { + "name": "inbound_time", + "type": "string", + "description": "入库时间" + }, + { + "name": "production_date", + "type": "string", + "description": "生产日期" + } + ] + }, + { + "name": "data.pagination", + "type": "object", + "required": true, + "description": "分页信息,含 page、pageSize、total、totalPages" + } + ], + "errors": [ + { + "code": 400, + "message": "where 条件格式不正确" + } + ] + }, { "method": "storage.transaction.list", "description": "出入库记录列表查询,支持 where 条件、分页、排序、批次分组切换。默认按库位合并数量(合并模式),group_by_batch=true 时返回每条明细(明细模式)", @@ -4538,7 +5658,12 @@ } } ], - "pagination": { "page": "当前页", "pageSize": "每页条数", "total": "总记录数", "totalPages": "总页数" } + "pagination": { + "page": "当前页", + "pageSize": "每页条数", + "total": "总记录数", + "totalPages": "总页数" + } }, "list_detail": { "_description": "group_by_batch=true(明细模式)", @@ -4572,12 +5697,23 @@ } } ], - "pagination": { "page": "当前页", "pageSize": "每页条数", "total": "总记录数", "totalPages": "总页数" } + "pagination": { + "page": "当前页", + "pageSize": "每页条数", + "total": "总记录数", + "totalPages": "总页数" + } } }, "errors": [ - { "code": 400, "message": "where 条件格式不正确" }, - { "code": 400, "message": "分页参数不合法" } + { + "code": 400, + "message": "where 条件格式不正确" + }, + { + "code": 400, + "message": "分页参数不合法" + } ] } ] @@ -4588,7 +5724,7 @@ "list": [ { "method": "store.createStore", - "description": "store.createStore 接口", + "description": "store.createStore 接口,subject_config 未传时默认写入 max_notice_webhook_count=5、default_express_code=STO、default_platform_code=TB", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -4599,13 +5735,42 @@ "description": "Bearer token" } ], - "params": [], + "params": [ + { + "name": "subject_config", + "type": "object", + "required": false, + "source": "body", + "description": "货主主体配置,不传时自动写入默认值" + }, + { + "name": "subject_config.max_notice_webhook_count", + "type": "number", + "required": false, + "source": "body.subject_config", + "description": "当前主体最多允许绑定 / 触达的消息推送接口数量,默认 5" + }, + { + "name": "subject_config.default_express_code", + "type": "string", + "required": false, + "source": "body.subject_config", + "description": "默认快递编码,缺省为 STO" + }, + { + "name": "subject_config.default_platform_code", + "type": "string", + "required": false, + "source": "body.subject_config", + "description": "默认平台编码,缺省为 TB" + } + ], "response": [], "errors": [] }, { "method": "store.createWarehouse", - "description": "store.createWarehouse 接口", + "description": "store.createWarehouse 接口,subject_config 未传时默认写入 max_notice_webhook_count=5、default_express_code=STO、default_platform_code=TB", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -4616,7 +5781,36 @@ "description": "Bearer token" } ], - "params": [], + "params": [ + { + "name": "subject_config", + "type": "object", + "required": false, + "source": "body", + "description": "货主主体配置,不传时自动写入默认值" + }, + { + "name": "subject_config.max_notice_webhook_count", + "type": "number", + "required": false, + "source": "body.subject_config", + "description": "当前主体最多允许绑定 / 触达的消息推送接口数量,默认 5" + }, + { + "name": "subject_config.default_express_code", + "type": "string", + "required": false, + "source": "body.subject_config", + "description": "默认快递编码,缺省为 STO" + }, + { + "name": "subject_config.default_platform_code", + "type": "string", + "required": false, + "source": "body.subject_config", + "description": "默认平台编码,缺省为 TB" + } + ], "response": [], "errors": [] }, @@ -5186,7 +6380,7 @@ "type": "object", "required": true, "source": "body", - "description": "策略配置对象;仅支持 receive_mode、sku_visibility、auto_allocate_bin、allow_mix_batch、allow_temp_storage、print_recharge_price(面单充值元/单,支持 2 位小数)、max_daily_inbound、remark" + "description": "策略配置对象;仅支持 receive_mode、auto_allocate_bin、allow_mix_batch、allow_temp_storage、storage_separation、print_recharge_price(面单充值元/单,支持 2 位小数)、max_daily_inbound、remark" } ], "response": [], @@ -6329,4 +7523,5 @@ } ] } -} + +} \ No newline at end of file diff --git a/order_todo.md b/order_todo.md index 9aaba93..e3119ec 100644 --- a/order_todo.md +++ b/order_todo.md @@ -74,7 +74,7 @@ --- -## 1. 目标与范围(含 M7) +## 1. 目标与范围(含 outsourced) ### 1.1 工作台模块一览 @@ -83,18 +83,18 @@ | M1 待审核 | 需审核后进入后续履约 | **仅 current** | | M2 待处理 | 仓内/出库前正常队列 | **仅 current** | | M3 待处理异常 | 出库前各环节异常 | **仅 current** | -| M4 配送订单 | 配送链路正常态 | **配送域工厂(待建)**,约 3 自然月 | -| M5 配送异常 | 配送链路异常(M4 子集) | **同上** | +| M4 配送订单 | 配送链路正常态 | **配送域工厂(首期已落地)**:单表 `wms_order_delivery_dispatch_{wh}` + 列 `dispatch_lane=m4`;**不按自然月拆物理表** | +| M5 配送异常 | 配送链路异常(M4 子集) | **同上表**,`dispatch_lane=m5` 筛选;归档/近三月策略走 **查询与任务**,不必多分表 | | M6 归档订单 | 冷数据 | **history**(>3 月等策略) | -| **M7 外仓发货** | 本仓不履约、推送外仓/三方履约;**暂无完整状态机** | **可与 current 扩展标记 + 外仓任务表** 或独立子域(待设计) | +| **outsourced 外仓发货** | 本仓不履约、推送外仓/三方履约;**已纳入 `OrderDeliveryFactory` 管理的 managed table / schema self-check 体系** | **由工厂统一管理,启动自检自动对齐结构**;仍可结合 current 扩展标记 + 外仓任务表落地 | ### 1.2 数据分层(与 §0 对齐) | 层级 | 表 / 模型 | 时间 / 策略 | |------|-----------|-------------| -| 热区 M1~M3 / M7(规划) | `wms_order_delivery_{wh}`、`wms_order_items_{wh}`(current) | 当日或未闭环;**创建时分流 M1 vs M2 由货主配置决定**;**到期仅克隆续单**,不进 M6(§2.4) | -| 配送区 M4/M5 | **配送域工厂**(独立于 current 的强分区存储) | **按自然月**;滚动 **3 个自然月** | -| 冷数据 M6 | `*_history`(仅承接 **M4/M5** 迁入) | **超过 3 个月**等策略;**仅允许 M4/M5 进入 M6**;M1/M2/M3/M7 **不走 M6 物理归档路径**(见 §2.4) | +| 热区 M1~M3 / outsourced(规划) | `wms_order_delivery_{wh}`、`wms_order_items_{wh}`(current) | 当日或未闭环;**创建时分流 M1 vs M2 由货主配置决定**;**到期仅克隆续单**,不进 M6(§2.4) | +| 配送区 M4/M5 | **`wms_order_delivery_dispatch_{wh}`**(`OrderDeliveryFactory` 的 dispatch 模式) | **单物理表**;M4/M5 用 **`dispatch_lane`**;**不按自然月拆表**;「约 3 个月」保留为 **列表/归档任务的时间条件**(见 §2.5 落地说明) | +| 冷数据 M6 | `*_history`(仅承接 **M4/M5** 迁入) | **超过 3 个月**等策略;**仅允许 M4/M5 进入 M6**;M1/M2/M3/outsourced **不走 M6 物理归档路径**(见 §2.4) | --- @@ -103,16 +103,16 @@ ### 2.1 订单创建:进入 M1 或 M2 - **规则**:创建时读取 **货主(store)配置**,决定初始进入 **M1(待审核)** 或 **M2(待处理)**。 -- **M1 → M2**:必须通过 **仓内库存校验**(满足可履约)**或** 选择 **推送 M7(外仓发货)** 路径之一;具体字段与接口待定义。 -- **M2 ⊥ M7(强制互斥)**:同一订单 **不得** 同时处于本仓待处理与外仓履约;进入或退出 M2/M7 的切换 **必须在单条(或可串行化的)数据库事务内完成**(状态位 + 外仓任务表等一并提交),失败 **整体回滚**,禁止半开状态。 -- **M7**:当前 **无完整状态机**;与 M4 的衔接仍遵守 §2.2 单向规则。 +- **M1 → M2**:必须通过 **仓内库存校验**(满足可履约)**或** 选择 **推送 outsourced(外仓发货)** 路径之一;具体字段与接口待定义。 +- **M2 ⊥ outsourced(强制互斥)**:同一订单 **不得** 同时处于本仓待处理与外仓履约;进入或退出 M2/outsourced 的切换 **必须在单条(或可串行化的)数据库事务内完成**(状态位 + 外仓任务表等一并提交),失败 **整体回滚**,禁止半开状态。 +- **outsourced**:当前 **无完整状态机**;与 M4 的衔接仍遵守 §2.2 单向规则。 ### 2.2 进入 M4 的约束(核心) | 从 → 到 | 是否允许 | 说明 | |---------|----------|------| -| **M2 → M4** | **允许(单向)** | M2、**M7 仅允许单向落入 M4** | -| **M7 → M4** | **允许(单向)** | 外仓发货完成后,依赖 **外部通知** 与出库状态机推进 | +| **M2 → M4** | **允许(单向)** | M2、**outsourced 仅允许单向落入 M4** | +| **outsourced → M4** | **允许(单向)** | 外仓发货完成后,依赖 **外部通知** 与出库状态机推进 | | **M1 → M4** | **禁止** | 须先 **切到 M2** 且 **状态机到达出库** 后,再经 **外部通知发货完成** 落入 M4 | | **M3 → M4** | **禁止** | 须先 **消除异常并回到 M2**,再走与 M2 相同路径进入 M4 | | **取消订单 → M4** | **允许(专用)** | 见 **§2.3a**:标记取消态后 **直进 M4**,**不可逆**、**零例外** | @@ -120,7 +120,7 @@ ### 2.3 M4 / M5 与外部机制 - **M4 ↔ M5 切换**:由 **外部机制** 驱动(承运商回传、网关、人工标记等),不在此文档展开协议。 -- **M4/M5 与 M1~M3**:除下节「补发副本」外,**同一订单在 M1/M2/M3/M7 与 M4/M5 不重复占位**:**M1~M3(及 M7)为唯一工作台态**;**M4/M5 为配送域单独态**(可理解为 **配送域一条影子/主数据**,与 current 热行通过 `order_id` / `delivery_order_code` / 快照关联)。 +- **M4/M5 与 M1~M3**:除下节「补发副本」外,**同一订单在 M1/M2/M3/outsourced 与 M4/M5 不重复占位**:**M1~M3(及 outsourced)为唯一工作台态**;**M4/M5 为配送域单独态**(可理解为 **配送域一条影子/主数据**,与 current 热行通过 `order_id` / `delivery_order_code` / 快照关联)。 ### 2.3a 订单取消(特殊路径:标记后进 M4) @@ -132,14 +132,15 @@ - **时间策略**:**所有订单类型均受时间维度约束,不另开例外**;**进入 M6(物理归档)后不可逆**,**不允许任何例外**(不设司法解冻、不设未归档回退通道)。 - **谁可以进 M6(物理)**:**仅 M4、M5** 对应的配送域数据(及与其绑定的明细快照)允许在满足保留期后 **迁入 `history` / 冷存储**。 -- **谁不可以进 M6**:**M1、M2、M3、M7** 热区行 **不允许** 走与 M4/M5 **相同的** M6(history)迁入通道;**到期后仅允许「克隆续单」**:通过 **新行(新主键)** 承接后续履约,原行 **仅改标记**(§2.7),**不得**删/软删、**不得**将原行迁入 M6。 +- **谁不可以进 M6**:**M1、M2、M3、outsourced** 热区行 **不允许** 走与 M4/M5 **相同的** M6(history)迁入通道;**到期后仅允许「克隆续单」**:通过 **新行(新主键)** 承接后续履约,原行 **仅改标记**(§2.7),**不得**删/软删、**不得**将原行迁入 M6。 - **克隆续单 / 补单(首期)**:**不与奇门等平台同步**;定位为 **补单**,由 **人工在仓内/运营侧处理**;系统可提供列表与标记能力,**接口与对账范围以本仓 WMS 为准**。 - **M4/M5 → M6**:以 **出库时间**(如 `delivery_time` / 出库确认时间)为主键条件之一,满足 **>3 个月**(与 §1.2 口径对齐)后迁入 history;过程 **不可逆**。 -### 2.5 配送域工厂(规划) +### 2.5 配送域工厂(首期落地 + 后续) -- **单独工厂**:M4/M5 **不共用** `OrderDeliveryFactory` 的 current 物理表;新建 **配送域工厂**,**model 定义仍由工厂类统一加载/缓存/分表键管理**(与现有工厂模式一致),**事务边界与分区键强绑定**(**事务驱动强分区**:单事务内读写同一分区键,如 `warehouseId + yyyyMM`)。 -- **自然月**:表名或 MySQL PARTITION 与 **自然月** 对齐,保留 **3 个自然月** 滚动窗口。 +- **已实现**:`app/model/order_delivery_factory.js` 的 dispatch 模式;物理表 **`wms_order_delivery_dispatch_{warehouseId}`**(与热区 `wms_order_delivery_{wh}` 命名同族,中间段 **`dispatch`**);**M4/M5 同表**,列 **`dispatch_lane` ENUM('m4','m5')** 区分;**不按自然月拆物理表**。`getDispatchModel(wh)` 为主入口;`getM4Model`/`getM5Model` 复用同一 dispatch 模式返回 **同一模型**。**outsourced 也已经纳入同一工厂管理,应用启动时会通过自检自动对齐 managed table 结构**。 +- **单测**:`test/app/model/order_delivery_dispatch_factory.test.js`;需连库时 `DISPATCH_FACTORY_TEST_MYSQL=1`(见 `config/plugin.js`);留表排查 `KEEP_DISPATCH_FACTORY_TABLES=1`。 +- **仍待**:与 current 的 **副本同步 / 事件驱动**;**强分区事务** 口径改为「单事务内同一 `warehouse_id` + 配送域表」即可(不再绑定 `yyyyMM` 表名);`wms_order_express` 与配送域行关联方案;M6 迁入仍以 **出库时间 + 保留期** 驱动(§2.4)。 ### 2.6 M4/M5 副本回归 M1 / M2 / M3(补发 / 部分履约) @@ -160,9 +161,9 @@ |------|------| | M1 ⊥ (M2 ∪ M3) | 不变 | | M2 ⊥ M3 | 不变 | -| **M2 ⊥ M7** | **强制互斥**;切换须 **事务**(§2.1) | +| **M2 ⊥ outsourced** | **强制互斥**;切换须 **事务**(§2.1) | | M5 ⊆ M4 | 不变 | -| **M1~M3 / M7(热区)** | **同一订单唯一展示态**(互斥集合内择一) | +| **M1~M3 / outsourced(热区)** | **同一订单唯一展示态**(互斥集合内择一) | | **M4 / M5** | **配送域内**可与热区并存为 **影子数据**;列表层需约定「主工作台只显示一侧」避免重复操作 | | **M6** | **仅 M4/M5 可物理迁入**;**不可逆、零例外**;热区到期 **不进 M6**,**仅允许克隆续单**(§2.4) | @@ -172,12 +173,12 @@ ### 3.1 列表查询(各模块) -**目标**:最小可用字段集 + **足够前端判断订单状态**(含 M7 外仓标记若存在)。 +**目标**:最小可用字段集 + **足够前端判断订单状态**(含 outsourced 外仓标记若存在)。 **原则**: - 列表不返回大体积 `items` TEXT;仅标识、各 `*_status`、`outbound_status`、`inspection_status`、`step`、`updated_at` / `delivery_time`、货主/仓编码等。 -- 实现:**按模块常量 `LIST_FIELDS`**;M4/M5/M7 在配送域或扩展表就绪后各自维护一份。 +- 实现:**按模块常量 `LIST_FIELDS`**;M4/M5/outsourced 在配送域或扩展表就绪后各自维护一份。 ### 3.2 明细查询 @@ -206,35 +207,38 @@ | 2026-04-10 | **无业务代码 / 无 migration 变更**。新增只读交付物:`docs/order-cancel-db-checklist.md`(§0.7 跑库步骤)、`docs/order-state-machine-dictionary.md`(状态机字典 **v0 骨架**,与 `app/model/order_delivery.js` 摘录一致)。**数仓映射、实际跑库结果** 仍待下一小阶段。 | | 2026-04-10 | **小阶段 A-1(影响面)**:新增 `docs/order-delivery-migration-impact.md`。**结论**:在未跑库确认缺列、且未敲定「取消进 M4」专用列前,**不自动提交 ALTER migration**;若清单验证列已齐,可先 **零表变更** 做应用筛选。详见该文档 **§1**。 | | 2026-04-10 | **小阶段 A-2(wms-db-agent 只读诊断)**:已对 `wms` 库跑清单;结果写入 **`docs/order-cancel-db-checklist.md` §5**。要点:**分表** `100000`/`1000028` 目标列齐全,可先不增列做筛选;**基表**缺三列、**勿**当业务表用;**无 `_history` 样本**;`chcp 65001` 防 JSON 解析失败。 | +| 2026-04-11 | **基表状态列**:migration `20260410200000-add-status-columns-to-wms-order-delivery-base.js`(按需补列,与热区分表对齐)。**配送域**:`OrderDeliveryFactory` 的 dispatch 模式单表 `wms_order_delivery_dispatch_{wh}` + `dispatch_lane`;当前按单表落地,不再保留「m4/m5 分表 + 自然月表名」方案;单测与 `DISPATCH_FACTORY_TEST_MYSQL` 见上文 §2.5。 | +| 2026-04-11 | **outsourced 收敛**:`outsourced` 纳入 `OrderDeliveryFactory` 的 managed table / schema self-check 体系,沿用启动自检自动对齐结构;旧兼容 shim 已移除,文档与代码统一收口到工厂管理。 | ### 阶段 A — 文档与规则冻结 -- [ ] 货主配置:「创建进 M1 / M2」的配置项落库位置与变更流程。 -- [ ] M1→M2:库存校验 API、M7 推送接口与回写字段。 +- [x] 货主配置:「创建进 M1 / M2」的配置项落库位置与变更流程。 +- [ ] M1→M2:库存校验 API、outsourced 推送接口与回写字段。 - [ ] 外部「发货完成」通知与状态机字段的映射表(落到 `outbound_status` / `step` 等)。 - [x] **§0.7 清单文档**:`docs/order-cancel-db-checklist.md`(各环境人工执行)。 - [x] **§0.7 跑库(本机 wms 一次)**:见 `docs/order-cancel-db-checklist.md` §5;**分表列齐**;**其它仓/生产须复跑**。 -- [ ] **§0.7 缺列 migration**:若产品仍要独立「取消进 M4」列或基表对齐,再开 migration;更新模型与工厂 DDL。 +- [x] **§0.7 基表状态列 migration**(与分表枚举对齐):`database/migrations/20260410200000-add-status-columns-to-wms-order-delivery-base.js`(已合并进仓库;其它环境须自行 `db:migrate`)。**独立「取消进 M4」业务列** 仍待产品定名后再 migration。 - [x] **状态机字典 v0 骨架**:`docs/order-state-machine-dictionary.md`(与数仓/报表的 **字段映射表** 仍待补)。 -- [x] **订单表 DDL 影响面分析**:`docs/order-delivery-migration-impact.md`(结论:**未自动做 migration**,待跑库 + 列名后由你决策)。 +- [x] **订单表 DDL 影响面分析**:`docs/order-delivery-migration-impact.md`(初版静态结论;**2026-04-11** 起基表状态列以已合并 migration 为准,文档全文若与现网不一致须择机修订)。 ### 阶段 B — 配送域工厂(3 自然月 + 强分区事务) -- [ ] 配送域工厂类设计(命名、目录、`app.js` 挂载)。 -- [ ] M4/M5 表结构、与 current 的 **副本同步** 或 **事件驱动** 方案。 -- [ ] `wms_order_express` 与配送域 **order_id + 分区键** 一致性方案。 +- [x] 配送域建表能力(`OrderDeliveryFactory` 的 dispatch 模式):表 **`wms_order_delivery_dispatch_{warehouseId}`**,**`dispatch_lane`** 区分 M4/M5。 +- [x] M4/M5 **单表** DDL 与动态模型(首期)。 +- [ ] 与 current 的 **副本同步** 或 **事件驱动** 方案(未做)。 +- [ ] `wms_order_express` 与配送域 **order_id**(及仓)一致性方案。 ### 阶段 C — 归档 M6 + 时间消除 - [ ] **仅 M4/M5**:配送域 → history 的 **出库时间** 驱动任务;**不可逆** 校验与审计(**零例外**)。 -- [ ] **M1/M2/M3/M7**:到期 **仅克隆续单** 流程(新行 + 原行标记);**禁止** 迁入 M6;前端 **空态/引导续单** 文案。 +- [ ] **M1/M2/M3/outsourced**:到期 **仅克隆续单** 流程(新行 + 原行标记);**禁止** 迁入 M6;前端 **空态/引导续单** 文案。 - [ ] **取消进 M4**:状态机字段字典、事务边界、与常规 M4 列表的 **展示分区**(避免与正常配送混淆)。 - [ ] 全库 **禁止 DELETE/软删** 副本与主单的 ORM/脚本审计;运维修正走 **状态机变更**(§2.7);**审批流** 见 **§5a 预留**。 ### 阶段 D — 补发副本与目标更新 - [ ] 补发单模型、原单引用、部分行、目标更新字段;**原行仅标记,禁止删/软删**。 -- [ ] 事务:副本创建 + 热区插入 + 配送域标记 **同一强分区键内** 或可补偿 Saga;与 **M2↔M7 事务切换** 共用事务规范文档。 +- [ ] 事务:副本创建 + 热区插入 + 配送域标记 **同一强分区键内** 或可补偿 Saga;与 **M2↔outsourced 事务切换** 共用事务规范文档。 ### 阶段 E — API / 测试 @@ -273,11 +277,12 @@ | 日期 | 说明 | |------|------| | (首版) | 根据讨论整理计划草案 | -| 补充 | 增加 §0 当前表/模型/工厂/关联分析;M7、创建分流、进入 M4 约束、外部驱动 M4/M5、时间进 M6、配送域独立工厂与强分区事务、M4/M5 按出库时间进 M6、补发副本回归 M1/2/3 | -| 补充 | **M2⊥M7 且事务进出**;**M6 仅 M4/M5 可物理迁入、不可逆**;热区到期不进 M6;**全副本禁止删/软删、仅标记或克隆**;§2.7 硬约束、§1.2/阶段 C/待补充项同步 | +| 补充 | 增加 §0 当前表/模型/工厂/关联分析;outsourced、创建分流、进入 M4 约束、外部驱动 M4/M5、时间进 M6、配送域独立工厂与强分区事务、M4/M5 按出库时间进 M6、补发副本回归 M1/2/3 | +| 补充 | **M2⊥outsourced 且事务进出**;**M6 仅 M4/M5 可物理迁入、不可逆**;热区到期不进 M6;**全副本禁止删/软删、仅标记或克隆**;§2.7 硬约束、§1.2/阶段 C/待补充项同步 | | 补充 | 热区到期 **仅克隆续单**;**§2.3a 取消→标记→直进 M4、不可逆零例外**;**运维「克隆」= 状态机合法变更** 写入 §2.2/§2.7/阶段 C | | 补充 | **§0.7** 取消状态机与分表核对/缺列 migration;**克隆续单不奇门同步、首期人工补单**;**字段字典与数仓报表同步**;**§5a 运维审批预留** | | 补充 | **§5 重写**:区分 **规则层已满足** vs **交付层未完成**;原 checklist 拆入 §5.1 / §5.2 并指向 §4 | | 2026-04-10 | **小阶段 A-0**:新增 `docs/order-cancel-db-checklist.md`、`docs/order-state-machine-dictionary.md`;§0.7 / §4 阶段 A / §5.2 同步;无代码变更 | | 2026-04-10 | **小阶段 A-1**:`docs/order-delivery-migration-impact.md`;**未提交 migration**(待你根据跑库 + 列名决策) | | 2026-04-10 | **小阶段 A-2**:wms-db-agent 只读诊断;`order-cancel-db-checklist.md` §5;**未提交 migration** | +| 2026-04-11 | **配送域单表工厂** + **基表 migration**;§1.2 / §2.5 / §4 阶段 B 勾选与表述同步 | diff --git a/package.json b/package.json index a43d04c..e2d159a 100644 --- a/package.json +++ b/package.json @@ -46,6 +46,8 @@ "file-writer:pressure": "node ./temp/generated-tests/file-writer-pressure.generated.test.cjs", "debug:webhook:receiver": "node ./script/debug-webhook-receiver.cjs", "debug:webhook:receiving": "node ./script/debug-send-receiving-webhooks.cjs", + "doc:api:update": "node ./script/update-api-doc.cjs", + "doc:api:update:dry": "node ./script/update-api-doc.cjs --dry-run", "deploy:init": "node ./script/deploy-init.cjs production", "deploy:init:dry": "node ./script/deploy-init.cjs production --dry-run", "deploy:precheck": "node ./script/deploy-precheck.cjs", @@ -67,6 +69,7 @@ "setup:hooks": "node ./script/setup-git-hooks.cjs", "test": "npm run lint -- --fix && npm run test:local", "test:local": "egg-bin test", + "test:dispatch-factory": "egg-bin test test/app/model/order_delivery_dispatch_factory.test.js", "cov": "egg-bin cov", "lint": "eslint .", "permission:sync:system-api": "node ./script/sync-system-api-permission.cjs", diff --git a/runtime/file-writer/.write-window-counter-3.json b/runtime/file-writer/.write-window-counter-3.json index 809d98c..d37d073 100644 --- a/runtime/file-writer/.write-window-counter-3.json +++ b/runtime/file-writer/.write-window-counter-3.json @@ -1 +1 @@ -{"startedAt":1775826309321,"recordCount":2} +{"startedAt":1776007031826,"recordCount":1} diff --git a/runtime/file-writer/qimen-logs/.consume-progress b/runtime/file-writer/qimen-logs/.consume-progress index 641f604..f1a39e0 100644 --- a/runtime/file-writer/qimen-logs/.consume-progress +++ b/runtime/file-writer/qimen-logs/.consume-progress @@ -1,7 +1,7 @@ { - "filePath": "D:\\wms\\runtime\\file-writer\\qimen-logs\\2026\\04\\10\\qimen-logs-MINGREN-worker-p4496-0001.log", - "offset": 6149, - "processedCount": 2, - "completedAt": "2026-04-10T14:20:54.561Z", - "updatedAt": "2026-04-11T09:08:50.539Z" + "filePath": "D:\\wms\\runtime\\file-writer\\qimen-logs\\2026\\04\\12\\qimen-logs-MINGREN-worker-p42648-0001.log", + "offset": 1713, + "processedCount": 1, + "completedAt": "2026-04-12T14:54:22.636Z", + "updatedAt": "2026-04-17T11:20:32.237Z" } diff --git a/runtime/file-writer/qimen-logs/.consume-progress.25476.1775941895725.tmp b/runtime/file-writer/qimen-logs/.consume-progress.25476.1775941895725.tmp new file mode 100644 index 0000000..4ebdee1 --- /dev/null +++ b/runtime/file-writer/qimen-logs/.consume-progress.25476.1775941895725.tmp @@ -0,0 +1,7 @@ +{ + "filePath": "D:\\wms\\runtime\\file-writer\\qimen-logs\\2026\\04\\10\\qimen-logs-MINGREN-worker-p4496-0001.log", + "offset": 6149, + "processedCount": 2, + "completedAt": "2026-04-10T14:20:54.561Z", + "updatedAt": "2026-04-11T21:11:35.725Z" +} diff --git a/runtime/file-writer/qimen-logs/2026/04/12/qimen-logs-MINGREN-worker-p38224-0001.log b/runtime/file-writer/qimen-logs/2026/04/12/qimen-logs-MINGREN-worker-p38224-0001.log new file mode 100644 index 0000000..2b27332 --- /dev/null +++ b/runtime/file-writer/qimen-logs/2026/04/12/qimen-logs-MINGREN-worker-p38224-0001.log @@ -0,0 +1 @@ +{"log_id":"QL-1776005200436-dfa9d6","from_key":"24869601","to_key":23535631,"method":"deliveryorder.create","sign":"74F6AD27E9412E9F1DABEBD72FBB0FD6","costomer_id":"jky2025102001","v":"2.0","url":"http://127.0.0.1:6060/qimen?app_key=24869601&method=deliveryorder.create&v=2.0&format=xml&sign_method=md5×tamp=1776005200&customerId=jky2025102001&sign=74F6AD27E9412E9F1DABEBD72FBB0FD6","created_at":"2026-04-12T14:46:40.436Z","body":"\n\n \n TRACE_OUTBOUND_1776005196546_B37AA0C5\n TAOBAO\n 淘宝\n 100000\n JYCK\n \n 自动化验证收件人\n 13800138000\n 广东省\n 广州市\n 黄埔区\n 知识城街道\n 自动化验证地址 TRACE_OUTBOUND_1776005196546_B37AA0C5\n 510000\n \n \n \n \n 101391\n 023802\n 空包\n 1\n 1\n \n \n","result":"\n\n failure\n 0\n 奇门吉客云ERP客户编码jky2025102001仓库编码warehouseCode未绑定到你的货主或未启用,请联系仓库绑定\n","use_time":92} diff --git a/runtime/file-writer/qimen-logs/2026/04/12/qimen-logs-MINGREN-worker-p38224-0001.log.done b/runtime/file-writer/qimen-logs/2026/04/12/qimen-logs-MINGREN-worker-p38224-0001.log.done new file mode 100644 index 0000000..809bc0c --- /dev/null +++ b/runtime/file-writer/qimen-logs/2026/04/12/qimen-logs-MINGREN-worker-p38224-0001.log.done @@ -0,0 +1,7 @@ +{ + "filePath": "D:\\wms\\runtime\\file-writer\\qimen-logs\\2026\\04\\12\\qimen-logs-MINGREN-worker-p38224-0001.log", + "offset": 1713, + "processedCount": 1, + "completedAt": "2026-04-12T14:46:52.525Z", + "updatedAt": "2026-04-12T14:46:52.525Z" +} diff --git a/runtime/file-writer/qimen-logs/2026/04/12/qimen-logs-MINGREN-worker-p41276-0001.log b/runtime/file-writer/qimen-logs/2026/04/12/qimen-logs-MINGREN-worker-p41276-0001.log new file mode 100644 index 0000000..b1bbefa --- /dev/null +++ b/runtime/file-writer/qimen-logs/2026/04/12/qimen-logs-MINGREN-worker-p41276-0001.log @@ -0,0 +1,4 @@ +{"log_id":"QL-1776005884434-818312","from_key":"24869601","to_key":23535631,"method":"deliveryorder.create","sign":"C591375BD641DD47560872675F5CCA0E","costomer_id":"jky2025102001","v":"2.0","url":"http://127.0.0.1:6060/qimen?app_key=24869601&method=deliveryorder.create&v=2.0&format=xml&sign_method=md5×tamp=1776005884&customerId=jky2025102001&sign=C591375BD641DD47560872675F5CCA0E","created_at":"2026-04-12T14:58:04.434Z","body":"\n\n \n TRACE_OUTBOUND_1776005880432_FA93FDAF\n TAOBAO\n 淘宝\n 100000\n JYCK\n \n 自动化验证收件人\n 13800138000\n 广东省\n 广州市\n 黄埔区\n 知识城街道\n 自动化验证地址 TRACE_OUTBOUND_1776005880432_FA93FDAF\n 510000\n \n \n \n \n 101391\n 023802\n 空包\n 1\n 1\n \n \n","result":"\n\n failure\n 0\n 奇门吉客云ERP客户编码jky2025102001仓库编码warehouseCode未绑定到你的货主或未启用,请联系仓库绑定\n","use_time":91} +{"log_id":"QL-1776006129287-77b8d4","from_key":"24869601","to_key":23535631,"method":"deliveryorder.create","sign":"A0B72528AC9B54B0DDA564298B20E7C0","costomer_id":"jky2025102001","v":"2.0","url":"http://127.0.0.1:6060/qimen?app_key=24869601&method=deliveryorder.create&v=2.0&format=xml&sign_method=md5×tamp=1776006129&customerId=jky2025102001&sign=A0B72528AC9B54B0DDA564298B20E7C0","created_at":"2026-04-12T15:02:09.287Z","body":"\n\n \n TRACE_OUTBOUND_1776006125376_39EA41AC\n TB\n 淘宝\n 100000\n JYCK\n \n 自动化验证收件人\n 13800138000\n 广东省\n 广州市\n 黄埔区\n 知识城街道\n 自动化验证地址 TRACE_OUTBOUND_1776006125376_39EA41AC\n 510000\n \n \n \n \n 101391\n 023802\n 空包\n 1\n 1\n \n \n","result":"\n\n failure\n 0\n 奇门吉客云ERP客户编码jky2025102001仓库编码warehouseCode未绑定到你的货主或未启用,请联系仓库绑定\n","use_time":88} +{"log_id":"QL-1776006776809-5dbb53","from_key":"24869601","to_key":23535631,"method":"deliveryorder.create","sign":"65632055E9198D2C8E466A44D0EF0D4C","costomer_id":"jky2025102001","v":"2.0","url":"http://127.0.0.1:6060/qimen?app_key=24869601&method=deliveryorder.create&v=2.0&format=xml&sign_method=md5×tamp=1776006776&customerId=jky2025102001&sign=65632055E9198D2C8E466A44D0EF0D4C","created_at":"2026-04-12T15:12:56.809Z","body":"\n\n \n TRACE_OUTBOUND_1776006772829_A0ADB113\n TB\n 淘宝\n 100000\n JYCK\n \n 自动化验证收件人\n 13800138000\n 广东省\n 广州市\n 黄埔区\n 知识城街道\n 自动化验证地址 TRACE_OUTBOUND_1776006772829_A0ADB113\n 510000\n \n \n \n \n 101391\n 023802\n 空包\n 1\n 1\n \n \n","result":"\n\n failure\n 0\n 奇门吉客云ERP客户编码jky2025102001仓库编码warehouseCode未绑定到你的货主或未启用,请联系仓库绑定\n","use_time":95} +{"log_id":"QL-1776007031740-155ce0","from_key":"24869601","to_key":23535631,"method":"deliveryorder.create","sign":"AE833C70C726B4B6664544B5A7B412EF","costomer_id":"jky2025102001","v":"2.0","url":"http://127.0.0.1:6060/qimen?app_key=24869601&method=deliveryorder.create&v=2.0&format=xml&sign_method=md5×tamp=1776007031&customerId=jky2025102001&sign=AE833C70C726B4B6664544B5A7B412EF","created_at":"2026-04-12T15:17:11.740Z","body":"\n\n \n TRACE_OUTBOUND_1776007027818_0E2C252D\n TB\n 淘宝\n 100000\n JYCK\n \n 自动化验证收件人\n 13800138000\n 广东省\n 广州市\n 黄埔区\n 知识城街道\n 自动化验证地址 TRACE_OUTBOUND_1776007027818_0E2C252D\n 510000\n \n \n \n \n 1000218\n 023802\n 空包\n 1\n 1\n \n \n","result":"\n\n failure\n 0\n 奇门吉客云ERP客户编码jky2025102001仓库编码warehouseCode未绑定到你的货主或未启用,请联系仓库绑定\n","use_time":86} diff --git a/runtime/file-writer/qimen-logs/2026/04/12/qimen-logs-MINGREN-worker-p42648-0001.log b/runtime/file-writer/qimen-logs/2026/04/12/qimen-logs-MINGREN-worker-p42648-0001.log new file mode 100644 index 0000000..baf6200 --- /dev/null +++ b/runtime/file-writer/qimen-logs/2026/04/12/qimen-logs-MINGREN-worker-p42648-0001.log @@ -0,0 +1 @@ +{"log_id":"QL-1776005653930-b9f1fa","from_key":"24869601","to_key":23535631,"method":"deliveryorder.create","sign":"4AB934D12D74B558BE1060D5525EFF7B","costomer_id":"jky2025102001","v":"2.0","url":"http://127.0.0.1:6060/qimen?app_key=24869601&method=deliveryorder.create&v=2.0&format=xml&sign_method=md5×tamp=1776005653&customerId=jky2025102001&sign=4AB934D12D74B558BE1060D5525EFF7B","created_at":"2026-04-12T14:54:13.931Z","body":"\n\n \n TRACE_OUTBOUND_1776005649940_B0FA5A9A\n TAOBAO\n 淘宝\n 100000\n JYCK\n \n 自动化验证收件人\n 13800138000\n 广东省\n 广州市\n 黄埔区\n 知识城街道\n 自动化验证地址 TRACE_OUTBOUND_1776005649940_B0FA5A9A\n 510000\n \n \n \n \n 101391\n 023802\n 空包\n 1\n 1\n \n \n","result":"\n\n failure\n 0\n 奇门吉客云ERP客户编码jky2025102001仓库编码warehouseCode未绑定到你的货主或未启用,请联系仓库绑定\n","use_time":93} diff --git a/runtime/file-writer/qimen-logs/2026/04/12/qimen-logs-MINGREN-worker-p42648-0001.log.done b/runtime/file-writer/qimen-logs/2026/04/12/qimen-logs-MINGREN-worker-p42648-0001.log.done new file mode 100644 index 0000000..9a09ff1 --- /dev/null +++ b/runtime/file-writer/qimen-logs/2026/04/12/qimen-logs-MINGREN-worker-p42648-0001.log.done @@ -0,0 +1,7 @@ +{ + "filePath": "D:\\wms\\runtime\\file-writer\\qimen-logs\\2026\\04\\12\\qimen-logs-MINGREN-worker-p42648-0001.log", + "offset": 1713, + "processedCount": 1, + "completedAt": "2026-04-12T14:54:22.636Z", + "updatedAt": "2026-04-12T14:54:22.636Z" +} diff --git a/script/update-api-doc.cjs b/script/update-api-doc.cjs new file mode 100644 index 0000000..288cc9a --- /dev/null +++ b/script/update-api-doc.cjs @@ -0,0 +1,387 @@ +const fs = require('fs'); +const path = require('path'); + +const ROOT = process.cwd(); +const METHODS_DIR = path.join(ROOT, 'methods'); +const CHANGES_DIR = path.join(METHODS_DIR, 'changes'); + +function parseArgs(argv) { + const args = { + specPath: '', + dryRun: false, + docOnly: false, + help: false, + }; + + for (const item of argv) { + if (item === '--dry-run') { + args.dryRun = true; + continue; + } + + if (item === '--doc-only') { + args.docOnly = true; + continue; + } + + if (item === '--help' || item === '-h') { + args.help = true; + continue; + } + + if (item.startsWith('--spec=')) { + const raw = String(item.slice('--spec='.length)).trim(); + args.specPath = raw ? path.resolve(ROOT, raw) : ''; + continue; + } + } + + if (!args.help && !args.specPath) { + throw new Error('Missing required --spec= argument.'); + } + + return args; +} + +function printHelp() { + console.log([ + 'Usage:', + ' npm run doc:api:update -- --spec=temp/api-doc-update.json', + ' npm run doc:api:update -- --spec=temp/api-doc-update.json --dry-run', + ' npm run doc:api:update -- --spec=temp/api-doc-update.json --doc-only', + '', + 'Options:', + ' --spec= Path to the fixed update spec JSON file.', + ' --dry-run Validate and print the planned changes without writing files.', + ' --doc-only Update methods/.json only and skip methods/changes/.json.', + ].join('\n')); +} + +function isPlainObject(value) { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} + +function assert(condition, message) { + if (!condition) { + throw new Error(message); + } +} + +function readJsonFile(filePath) { + const raw = fs.readFileSync(filePath, 'utf8'); + return { + json: JSON.parse(raw), + indent: detectIndent(raw), + eol: detectEol(raw), + }; +} + +function detectIndent(raw) { + const match = raw.match(/^([ \t]+)"[^"]+":/m); + return match ? match[1] : ' '; +} + +function detectEol(raw) { + return raw.includes('\r\n') ? '\r\n' : '\n'; +} + +function writeJsonFile(filePath, value, indent, eol) { + const formatted = JSON.stringify(value, null, indent).replace(/\n/g, eol); + fs.writeFileSync(filePath, `${formatted}${eol}`, 'utf8'); +} + +function ensureString(value, fieldPath) { + assert(typeof value === 'string' && value.trim(), `${fieldPath} must be a non-empty string.`); +} + +function ensureBoolean(value, fieldPath) { + assert(typeof value === 'boolean', `${fieldPath} must be a boolean.`); +} + +function ensureArray(value, fieldPath) { + assert(Array.isArray(value), `${fieldPath} must be an array.`); +} + +function ensureStringArray(value, fieldPath) { + ensureArray(value, fieldPath); + value.forEach((item, index) => ensureString(item, `${fieldPath}[${index}]`)); +} + +function validateListOption(option, fieldPath) { + assert(isPlainObject(option), `${fieldPath} must be an object.`); + const hasValue = Object.prototype.hasOwnProperty.call(option, 'value'); + assert(hasValue, `${fieldPath}.value is required.`); +} + +function validateNamedField(field, fieldPath, allowSource) { + assert(isPlainObject(field), `${fieldPath} must be an object.`); + ensureString(field.name, `${fieldPath}.name`); + ensureString(field.type, `${fieldPath}.type`); + ensureBoolean(field.required, `${fieldPath}.required`); + ensureString(field.description, `${fieldPath}.description`); + + if (allowSource && Object.prototype.hasOwnProperty.call(field, 'source')) { + ensureString(field.source, `${fieldPath}.source`); + } + + if (Object.prototype.hasOwnProperty.call(field, 'list')) { + ensureArray(field.list, `${fieldPath}.list`); + field.list.forEach((item, index) => validateListOption(item, `${fieldPath}.list[${index}]`)); + } +} + +function validateErrorField(field, fieldPath) { + assert(isPlainObject(field), `${fieldPath} must be an object.`); + assert(Object.prototype.hasOwnProperty.call(field, 'code'), `${fieldPath}.code is required.`); + ensureString(field.message, `${fieldPath}.message`); +} + +function validateMethodDoc(methodDoc, fieldPath) { + assert(isPlainObject(methodDoc), `${fieldPath} must be an object.`); + ensureString(methodDoc.method, `${fieldPath}.method`); + ensureString(methodDoc.description, `${fieldPath}.description`); + ensureBoolean(methodDoc.isNeedAuth, `${fieldPath}.isNeedAuth`); + ensureBoolean(methodDoc.isNeedLogin, `${fieldPath}.isNeedLogin`); + ensureArray(methodDoc.headers, `${fieldPath}.headers`); + ensureArray(methodDoc.params, `${fieldPath}.params`); + ensureArray(methodDoc.response, `${fieldPath}.response`); + ensureArray(methodDoc.errors, `${fieldPath}.errors`); + + methodDoc.headers.forEach((item, index) => validateNamedField(item, `${fieldPath}.headers[${index}]`, false)); + methodDoc.params.forEach((item, index) => validateNamedField(item, `${fieldPath}.params[${index}]`, true)); + methodDoc.response.forEach((item, index) => validateNamedField(item, `${fieldPath}.response[${index}]`, false)); + methodDoc.errors.forEach((item, index) => validateErrorField(item, `${fieldPath}.errors[${index}]`)); +} + +function validateChange(change, fieldPath) { + assert(isPlainObject(change), `${fieldPath} must be an object.`); + ensureString(change.version, `${fieldPath}.version`); + ensureString(change.date, `${fieldPath}.date`); + ensureString(change.summary, `${fieldPath}.summary`); + ensureStringArray(change.methods, `${fieldPath}.methods`); + ensureStringArray(change.notes, `${fieldPath}.notes`); + + if (Object.prototype.hasOwnProperty.call(change, 'type')) { + ensureString(change.type, `${fieldPath}.type`); + } +} + +function validateCurrentDoc(doc, fieldPath) { + assert(isPlainObject(doc), `${fieldPath} must be an object.`); + assert(isPlainObject(doc.methods), `${fieldPath}.methods must be an object.`); + ensureArray(doc.methods.groups, `${fieldPath}.methods.groups`); +} + +function validateCurrentChanges(changes, fieldPath) { + ensureArray(changes, fieldPath); +} + +function validateSpec(spec, args) { + assert(isPlainObject(spec), 'Spec root must be an object.'); + ensureString(spec.docName, 'spec.docName'); + assert(/^[a-z0-9_-]+$/i.test(spec.docName), 'spec.docName must contain only letters, numbers, underscore, or dash.'); + + const docPath = path.join(METHODS_DIR, `${spec.docName}.json`); + const changePath = path.join(CHANGES_DIR, `${spec.docName}.json`); + + assert(fs.existsSync(docPath), `Target doc file not found: ${docPath}`); + if (!args.docOnly) { + assert(fs.existsSync(changePath), `Target change file not found: ${changePath}`); + } + + if (Object.prototype.hasOwnProperty.call(spec, 'docMeta')) { + assert(isPlainObject(spec.docMeta), 'spec.docMeta must be an object.'); + if (Object.prototype.hasOwnProperty.call(spec.docMeta, 'updatedAt')) { + ensureString(spec.docMeta.updatedAt, 'spec.docMeta.updatedAt'); + } + if (Object.prototype.hasOwnProperty.call(spec.docMeta, 'version')) { + ensureString(spec.docMeta.version, 'spec.docMeta.version'); + } + } + + assert(isPlainObject(spec.group), 'spec.group must be an object.'); + ensureString(spec.group.groupName, 'spec.group.groupName'); + ensureString(spec.group.module, 'spec.group.module'); + + ensureArray(spec.methods, 'spec.methods'); + assert(spec.methods.length > 0, 'spec.methods must contain at least one method doc.'); + const methodNames = new Set(); + spec.methods.forEach((item, index) => { + validateMethodDoc(item, `spec.methods[${index}]`); + assert(!methodNames.has(item.method), `Duplicate method in spec.methods: ${item.method}`); + methodNames.add(item.method); + }); + + if (!args.docOnly) { + validateChange(spec.change, 'spec.change'); + } else if (Object.prototype.hasOwnProperty.call(spec, 'change')) { + validateChange(spec.change, 'spec.change'); + } + + return { + docName: spec.docName, + docPath, + changePath, + docMeta: spec.docMeta || {}, + group: spec.group, + methods: spec.methods, + change: spec.change || null, + }; +} + +function findGroupIndex(groups, groupSpec) { + const byModule = groups.findIndex(group => group && group.module === groupSpec.module); + if (byModule >= 0) return byModule; + return groups.findIndex(group => group && group.groupName === groupSpec.groupName); +} + +function findMethodLocation(groups, methodName) { + for (let groupIndex = 0; groupIndex < groups.length; groupIndex += 1) { + const group = groups[groupIndex]; + const list = group && Array.isArray(group.list) ? group.list : []; + const methodIndex = list.findIndex(item => item && item.method === methodName); + if (methodIndex >= 0) { + return { groupIndex, methodIndex }; + } + } + return null; +} + +function cloneJson(value) { + return JSON.parse(JSON.stringify(value)); +} + +function applyDocUpdate(doc, groupSpec, methods, docMeta) { + const groups = doc.methods.groups; + let groupIndex = findGroupIndex(groups, groupSpec); + + if (groupIndex < 0) { + groups.push({ + groupName: groupSpec.groupName, + module: groupSpec.module, + list: [], + }); + groupIndex = groups.length - 1; + } + + const targetGroup = groups[groupIndex]; + targetGroup.groupName = groupSpec.groupName; + targetGroup.module = groupSpec.module; + if (!Array.isArray(targetGroup.list)) { + targetGroup.list = []; + } + + const summary = { + inserted: [], + updated: [], + moved: [], + }; + + for (const methodDoc of methods) { + const nextMethod = cloneJson(methodDoc); + const existingLocation = findMethodLocation(groups, methodDoc.method); + + if (!existingLocation) { + targetGroup.list.push(nextMethod); + summary.inserted.push(methodDoc.method); + continue; + } + + if (existingLocation.groupIndex === groupIndex) { + targetGroup.list[existingLocation.methodIndex] = nextMethod; + summary.updated.push(methodDoc.method); + continue; + } + + groups[existingLocation.groupIndex].list.splice(existingLocation.methodIndex, 1); + targetGroup.list.push(nextMethod); + summary.moved.push(methodDoc.method); + } + + if (docMeta.updatedAt) { + doc.updatedAt = docMeta.updatedAt; + } + + if (docMeta.version) { + doc.version = docMeta.version; + } + + return summary; +} + +function appendChange(changes, change) { + const exists = changes.some(item => item && item.version === change.version); + assert(!exists, `Duplicate change version detected: ${change.version}`); + changes.push(cloneJson(change)); +} + +function main() { + const args = parseArgs(process.argv.slice(2)); + if (args.help) { + printHelp(); + return; + } + + assert(fs.existsSync(args.specPath), `Spec file not found: ${args.specPath}`); + + const specRaw = fs.readFileSync(args.specPath, 'utf8'); + const spec = JSON.parse(specRaw); + const normalized = validateSpec(spec, args); + + const docState = readJsonFile(normalized.docPath); + validateCurrentDoc(docState.json, normalized.docPath); + + let changeState = null; + if (!args.docOnly) { + changeState = readJsonFile(normalized.changePath); + validateCurrentChanges(changeState.json, normalized.changePath); + } + + const docNext = cloneJson(docState.json); + const summary = applyDocUpdate(docNext, normalized.group, normalized.methods, normalized.docMeta); + JSON.parse(JSON.stringify(docNext)); + + let changeNext = null; + if (!args.docOnly) { + changeNext = cloneJson(changeState.json); + appendChange(changeNext, normalized.change); + JSON.parse(JSON.stringify(changeNext)); + } + + console.log(`docName: ${normalized.docName}`); + console.log(`group: ${normalized.group.module} (${normalized.group.groupName})`); + console.log(`inserted: ${summary.inserted.length ? summary.inserted.join(', ') : '-'}`); + console.log(`updated: ${summary.updated.length ? summary.updated.join(', ') : '-'}`); + console.log(`moved: ${summary.moved.length ? summary.moved.join(', ') : '-'}`); + if (!args.docOnly && normalized.change) { + console.log(`change version: ${normalized.change.version}`); + } + + if (args.dryRun) { + console.log('dry-run: validated successfully, no files were written.'); + return; + } + + writeJsonFile(normalized.docPath, docNext, docState.indent, docState.eol); + console.log(`wrote: ${path.relative(ROOT, normalized.docPath)}`); + + if (!args.docOnly) { + writeJsonFile(normalized.changePath, changeNext, changeState.indent, changeState.eol); + console.log(`wrote: ${path.relative(ROOT, normalized.changePath)}`); + } +} + +if (require.main === module) { + try { + main(); + } catch (error) { + console.error(error.message || error); + process.exitCode = 1; + } +} + +module.exports = { + applyDocUpdate, + parseArgs, + validateSpec, +}; \ No newline at end of file diff --git a/temp_check_json.js b/temp_check_json.js new file mode 100644 index 0000000..e6b80c8 --- /dev/null +++ b/temp_check_json.js @@ -0,0 +1,39 @@ +const fs = require('fs'); +const s = fs.readFileSync('methods/system.json','utf8'); +let stack = []; +let inStr = false; +function isEscaped(str, idx){ + let cnt=0; let j=idx-1; while(j>=0 && str[j]=='\\'){cnt++; j--; } return cnt%2===1; +} +for (let i = 0; i < s.length; i++) { + const c = s[i]; + + if (c === '"' && !isEscaped(s,i)) { + inStr = !inStr; + } + if (inStr) continue; + if (c === '{' || c === '[') stack.push({ c, pos: i }); + else if (c === '}') { + if (!stack.length || stack[stack.length - 1].c !== '{') { + console.log('UNMATCHED } at', i); + break; + } + stack.pop(); + } else if (c === ']') { + if (!stack.length || stack[stack.length - 1].c !== '[') { + console.log('UNMATCHED ] at', i); + break; + } + stack.pop(); + } +} +if (stack.length) { + console.log('STACK NOT EMPTY len', stack.length); + stack.forEach(x=>{ + console.log('---STACK ITEM---'); + console.log(x.c, x.pos); + console.log(s.slice(Math.max(0,x.pos-120), x.pos+120)); + }); +} else { + console.log('ALL MATCHED'); +} diff --git a/temp_count_brackets.js b/temp_count_brackets.js new file mode 100644 index 0000000..4bac31c --- /dev/null +++ b/temp_count_brackets.js @@ -0,0 +1,15 @@ +const fs=require('fs'); +const s=fs.readFileSync('methods/system.json','utf8'); +function isEscaped(str, idx){let cnt=0;let j=idx-1;while(j>=0&&str[j]=='\\'){cnt++;j--;}return cnt%2===1;} +let inStr=false, open=0, close=0, openB=0, closeB=0; +for(let i=0;i=0 && str[j]=='\\'){cnt++; j--; } return cnt%2===1;} +let ph=s.indexOf('"headers"'); +let posOpen=s.indexOf('[',ph); +let depth=0; let inStr=false; let posClose=-1; +for(let i=posOpen;i=0&&/\s/.test(s[j])) j--;const prev=s[j]||'';if(prev!==','){found=true;const start=Math.max(0,idx-60);const end=Math.min(s.length, idx+60);console.log('---possible missing comma at',idx,'prevChar:',prev);console.log(s.slice(start,end));console.log('---');}}if(!found) console.log('No obvious }\n{ without comma found'); \ No newline at end of file diff --git a/temp_find_objsep.js b/temp_find_objsep.js new file mode 100644 index 0000000..5b59014 --- /dev/null +++ b/temp_find_objsep.js @@ -0,0 +1 @@ +const fs=require('fs');const s=fs.readFileSync('methods/system.json','utf8');const re=/}\s*\n\s*{\s*"method"\s*:/g;let m;let found=false;while(m=re.exec(s)){const idx=m.index;let j=idx-1;while(j>=0&&/\s/.test(s[j])) j--;const prev=s[j]||'';if(prev!==','){found=true;const start=Math.max(0,idx-80);const end=Math.min(s.length,idx+80);console.log('---missing comma between objects at',idx,'prevChar:',prev);console.log(s.slice(start,end));console.log('---');}}if(!found) console.log('No missing-comma-between-method-objects found'); \ No newline at end of file diff --git a/temp_find_trailing_commas.js b/temp_find_trailing_commas.js new file mode 100644 index 0000000..b7fe44c --- /dev/null +++ b/temp_find_trailing_commas.js @@ -0,0 +1 @@ +const fs=require('fs');const s=fs.readFileSync('methods/system.json','utf8');const re=/(,\s*\n\s*\])/g;let m;let found=false;while(m=re.exec(s)){found=true;const idx=m.index;const start=Math.max(0,idx-60);const end=Math.min(s.length,idx+60);console.log('---trailing comma before ] at',idx);console.log(s.slice(start,end));console.log('---');}if(!found) console.log('No ",\n]" patterns found'); \ No newline at end of file diff --git a/temp_parse_json.py b/temp_parse_json.py new file mode 100644 index 0000000..fc628d9 --- /dev/null +++ b/temp_parse_json.py @@ -0,0 +1,13 @@ +import json +s=open('methods/system.json','r',encoding='utf8').read() +try: + json.loads(s) + print('py OK') +except json.decoder.JSONDecodeError as e: + print('JSONDecodeError:', e.msg, 'lineno', e.lineno, 'colno', e.colno, 'pos', e.pos) + start=max(0,e.pos-120) + print('---context---') + print(s[start:e.pos+120]) + print('---end---') +except Exception as e: + print('other error',e) diff --git a/temp_rebuild_system_json.js b/temp_rebuild_system_json.js new file mode 100644 index 0000000..4eaba06 --- /dev/null +++ b/temp_rebuild_system_json.js @@ -0,0 +1,49 @@ +const fs=require('fs'); +const path='methods/system.json'; +let s=fs.readFileSync(path,'utf8'); +function isEscaped(str, idx){let cnt=0; let j=idx-1; while(j>=0 && str[j]=='\\'){cnt++; j--; } return cnt%2===1;} +// find headers key +let ph = s.indexOf('"headers"'); +if(ph===-1){console.error('no headers key'); process.exit(1)} +let posOpen = s.indexOf('[', ph); +if(posOpen===-1){console.error('no [ after headers'); process.exit(1)} +// find matching closing bracket for headers +let depth=0; let inStr=false; let posClose=-1; +for(let i=posOpen;i { + it('GET /docs should return an index page with docs file links', async () => { + const res = await app.httpRequest() + .get('/docs') + .expect('Content-Type', /html/) + .expect(200); + + assert.match(res.text, /docs 目录索引/); + assert.match(res.text, /]*data-window-href="\/docs\/order-workbench-list-api\.md"/i); + assert.doesNotMatch(res.text, /
  • \s*]*href="\/docs\/order-workbench-list-api\.md"/i); + }); + + it('GET /docs/order-workbench-list-api.md should return markdown content', async () => { + const res = await app.httpRequest() + .get('/docs/order-workbench-list-api.md') + .expect('Content-Type', /text\/markdown/) + .expect(200); + + assert.match(res.text, /^# 订单工作台 List 接口说明/m); + }); + + it('GET /docs should block path traversal attempts', async () => { + const res = await app.httpRequest() + .get('/docs/%2e%2e%2fapp.js') + .expect('Content-Type', /json/) + .expect(400); + + assert.equal(Number(res.body.code), 400); + assert.match(String(res.body.message || ''), /无效|越界|path/i); + }); + + it('GET /api/docs/system should still be available', async () => { + const res = await app.httpRequest() + .get('/api/docs/system') + .expect('Content-Type', /html/) + .expect(200); + + assert.match(res.text, /系统接口|API 文档/); + assert.match(res.text, /\/api\/docs\/system\/raw/); + assert.match(res.text, /]*data-window-href="\/api\/docs\/system\/raw"/i); + }); + it('GET /api/docs/system/changes should return 200 and a change-history JSON array', async () => { const res = await app.httpRequest() .get('/api/docs/system/changes') @@ -42,9 +83,9 @@ describe('test/app/controller/docs.test.js', () => { .expect(200); const html = res.text; - assert.match(html, /\/api\/docs\/system\/changes/, '页面中应提供 /api/docs/system/changes 入口'); + assert.match(html, /]*data-window-href="\/api\/docs\/system\/changes"/i, '页面中应提供 /api/docs/system/changes 的 window 入口'); assert.match(html, /查看变更记录|变更记录|changelog/i, '页面中应出现“查看变更记录”或同等入口文案'); - assert.match(html, /\/api\/docs\/system\/raw/, '页面中应提供 /api/docs/system/raw 入口'); + assert.match(html, /]*data-window-href="\/api\/docs\/system\/raw"/i, '页面中应提供 /api/docs/system/raw 的 window 入口'); assert.match(html, /查看\s*JSON|raw\s*json/i, '页面中应出现“查看 JSON”入口'); }); diff --git a/test/app/controller/gateway.user.bindAccountByTempCode.test.js b/test/app/controller/gateway.user.bindAccountByTempCode.test.js index aee6931..9ef2e49 100644 --- a/test/app/controller/gateway.user.bindAccountByTempCode.test.js +++ b/test/app/controller/gateway.user.bindAccountByTempCode.test.js @@ -7,14 +7,16 @@ const { invokeGatewayMethod, } = require('../../support/system_method_client'); -const YE4S_TEST_USER_ID = Number(process.env.SYSTEM_TEST_YE4S_USER_ID); +describe('test/app/controller/gateway.user.bindAccountByTempCode.test.js', function() { + let YE4S_TEST_USER_ID; -assert.ok( - Number.isInteger(YE4S_TEST_USER_ID) && YE4S_TEST_USER_ID > 0, - 'SYSTEM_TEST_YE4S_USER_ID 必须显式提供且为正整数' -); + before(function() { + YE4S_TEST_USER_ID = Number(process.env.SYSTEM_TEST_YE4S_USER_ID); + if (!Number.isInteger(YE4S_TEST_USER_ID) || YE4S_TEST_USER_ID <= 0) { + this.skip(); + } + }); -describe('test/app/controller/gateway.user.bindAccountByTempCode.test.js', () => { it('should scan, bind, unbind, and bind again for ye4s user', async () => { const { token } = await getAuthToken(); diff --git a/test/app/controller/home.test.js b/test/app/controller/home.test.js index f178b9d..ae4657a 100644 --- a/test/app/controller/home.test.js +++ b/test/app/controller/home.test.js @@ -1,7 +1,9 @@ const { strict: assert } = require('node:assert'); const path = require('node:path'); const { statSync } = require('node:fs'); -const { app } = require('egg-mock/bootstrap'); +const { app, mm } = require('egg-mock/bootstrap'); +const HomeController = require('../../../app/controller/home'); +const PoloApiService = require('../../../app/service/systems/polo_api'); describe('test/app/controller/home.test.js', () => { it('should assert', async () => { @@ -20,4 +22,99 @@ describe('test/app/controller/home.test.js', () => { .expect('pong') .expect(200); }); + + it('should GET /testPoloApi return poloApi.test result directly', async () => { + const expectedResult = { + ok: true, + data: { + message: 'real result passthrough', + }, + }; + let callCount = 0; + + try { + mm(PoloApiService.prototype, 'test', async () => { + callCount += 1; + return expectedResult; + }); + + const res = await app.httpRequest() + .get('/testPoloApi') + .expect('Content-Type', /json/) + .expect(200); + + assert.deepEqual(res.body, expectedResult); + assert.equal(callCount, 1); + } finally { + mm.restore(); + } + }); + + it('should extract qimen warehouseCode from controller helper', async () => { + const controller = Object.create(HomeController.prototype); + + assert.equal( + controller.getQimenWarehouseCode({ + request: { + deliveryOrder: { + warehouseCode: '100000', + }, + }, + }), + '100000' + ); + + assert.equal( + controller.getQimenWarehouseCode({ + request: { + warehouseCode: 'warehouseCode', + deliveryOrder: { + warehouseCode: '100000', + }, + }, + }), + '100000' + ); + + assert.equal( + controller.getQimenWarehouseCode({ + request: { + warehouseCode: 'warehouseCode', + deliveryOrder: { + warehouseCode: 'warehouseCode', + }, + }, + }), + '' + ); + + assert.equal( + controller.getQimenWarehouseCode({ + request: { + deliveryOrder: { + warehouseCode: '', + }, + }, + }), + '' + ); + }); + + it('should ignore unrelated string nodes when extracting qimen warehouseCode', async () => { + const controller = Object.create(HomeController.prototype); + + assert.equal( + controller.getQimenWarehouseCode({ + request: { + deliveryOrder: { + warehouseCode: 'warehouseCode', + orderStatus: '100000', + note: '真实请求里不应被这些字符串节点误命中', + }, + traceId: '100000', + }, + }), + '' + ); + }); }); diff --git a/test/app/controller/qimen.deliveryorder.reviewFlow.test.js b/test/app/controller/qimen.deliveryorder.reviewFlow.test.js new file mode 100644 index 0000000..4cda5da --- /dev/null +++ b/test/app/controller/qimen.deliveryorder.reviewFlow.test.js @@ -0,0 +1,432 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const crypto = require('node:crypto'); +const { + getAuthToken, + invokeSystemMethod, + invokeQimenMethod, +} = require('../../support/system_method_client'); + +const EXTRA_HEADERS = { + platform: 'web', + project: 'all', +}; + +const FIXED_RELATION = { + storeId: 1000000, + warehouseId: 100000, +}; + +const FALLBACK_ROLE_IDS = [ 4, 6, 30 ]; + +/** + * 将字符串转义为 XML 安全文本。 + * @param {string|number|null|undefined} value 待转义值。 + * @return {string} 转义后的 XML 文本。 + */ +function escapeXml(value) { + return String(value === null || value === undefined ? '' : value).replace(/[<>&'\"]/g, character => { + switch (character) { + case '<': + return '<'; + case '>': + return '>'; + case '&': + return '&'; + case '\'': + return '''; + case '"': + return '"'; + default: + return character; + } + }); +} + +/** + * 从候选列表中挑选固定测试签约关系。 + * @param {Array} relations 签约关系列表。 + * @return {object|null} 固定测试关系。 + */ +function pickFixedTestRelation(relations) { + if (!Array.isArray(relations)) { + return null; + } + + return relations.find(item => Number(item.store_id) === FIXED_RELATION.storeId + && Number(item.warehouse_id) === FIXED_RELATION.warehouseId) || null; +} + +/** + * 从接口配置列表中挑选一个已启用的 QM_WMS 配置。 + * @param {Array} configs 接口配置列表。 + * @return {object|null} 可用奇门配置。 + */ +function pickEnabledQimenConfig(configs) { + if (!Array.isArray(configs)) { + return null; + } + + return configs.find(item => Number(item.is_enabled) === 1 + && (item.interface_category === 'QM_WMS' || item.interface_type?.interface_category === 'QM_WMS')) || null; +} + +/** + * 从库存搜索结果中挑选一个可用 SKU。 + * @param {Array} stocks 库存搜索结果。 + * @return {object|null} 可用 SKU。 + */ +function pickUsableStock(stocks) { + if (!Array.isArray(stocks)) { + return null; + } + + const resolveAvailableQuantity = item => { + const directAvailableFields = [ + item?.available_quantity, + item?.availableQuantity, + item?.available, + ]; + + for (const value of directAvailableFields) { + const numeric = Number(value); + if (Number.isFinite(numeric) && numeric > 0) { + return numeric; + } + } + + const quantity = Number(item?.quantity); + const lockedQuantity = Number(item?.locked_quantity ?? item?.lockedQuantity ?? item?.lockQuantity); + if (Number.isFinite(quantity) && quantity > 0) { + const resolvedLocked = Number.isFinite(lockedQuantity) ? lockedQuantity : 0; + return Math.max(0, quantity - resolvedLocked); + } + + const storageList = Array.isArray(item?.storage) ? item.storage : []; + for (const storageItem of storageList) { + const storageAvailable = Number(storageItem?.available_quantity ?? storageItem?.availableQuantity ?? storageItem?.available); + if (Number.isFinite(storageAvailable) && storageAvailable > 0) { + return storageAvailable; + } + + const storageQuantity = Number(storageItem?.quantity); + const storageLocked = Number(storageItem?.locked_quantity ?? storageItem?.lockedQuantity); + if (Number.isFinite(storageQuantity) && storageQuantity > 0) { + const resolvedStorageLocked = Number.isFinite(storageLocked) ? storageLocked : 0; + const available = Math.max(0, storageQuantity - resolvedStorageLocked); + if (available > 0) { + return available; + } + } + } + + return 0; + }; + + return stocks.find(item => resolveAvailableQuantity(item) > 0) || null; +} + +/** + * 构建待审核订单的 XML 请求体。 + * @param {Object} payload 请求参数。 + * @return {string} XML 请求体。 + */ +function buildDeliveryOrderXml(payload) { + const { deliveryOrderCode, warehouseCode, stock, planQty, orderType, receiverInfo } = payload; + + return ` + + + ${escapeXml(deliveryOrderCode)} + TAOBAO + 淘宝 + ${escapeXml(warehouseCode)} + ${escapeXml(orderType)} + + ${escapeXml(receiverInfo.name)} + ${escapeXml(receiverInfo.mobile)} + ${escapeXml(receiverInfo.province)} + ${escapeXml(receiverInfo.city)} + ${escapeXml(receiverInfo.area)} + ${escapeXml(receiverInfo.town)} + ${escapeXml(receiverInfo.detailAddress)} + ${escapeXml(receiverInfo.zipCode)} + + + + + ${escapeXml(stock.id)} + ${escapeXml(stock.item_code)} + ${escapeXml(stock.item_name)} + ${escapeXml(planQty)} + 1 + + +`; +} + +/** + * 切换到可访问仓库订单和库存接口的仓库角色。 + * @param {string} token 当前登录 token。 + * @return {Promise<{token: string, roleId: number}|null>} 切换结果。 + */ +async function switchToWarehouseRole(token) { + const infoRes = await invokeSystemMethod('user.info', {}, token, EXTRA_HEADERS); + + assert.equal(infoRes.status, 200, `user.info HTTP 状态异常: ${JSON.stringify(infoRes.body)}`); + assert.equal(infoRes.body.flag, 'success', `user.info 返回失败: ${JSON.stringify(infoRes.body)}`); + assert.equal(infoRes.body.code, 200, `user.info code 异常: ${JSON.stringify(infoRes.body)}`); + + const employees = Array.isArray(infoRes.body?.data?.employees) ? infoRes.body.data.employees : []; + const candidateRoleIds = [ + ...new Set([ + ...employees + .filter(item => item && item.role_type === 'warehouse' && Number(item.id)) + .map(item => Number(item.id)), + ...FALLBACK_ROLE_IDS, + ].filter(Boolean)), + ]; + + for (const roleId of candidateRoleIds) { + const changeRes = await invokeSystemMethod('user.changeRole', { + roleId, + }, token, EXTRA_HEADERS); + + if (changeRes.status !== 200 || changeRes.body?.flag !== 'success' || Number(changeRes.body?.code) !== 200) { + continue; + } + + const switchedToken = changeRes.body?.data?.token || token; + + const relationProbeRes = await invokeSystemMethod('storeWarehouse.store.list', { + page: 1, + page_size: 50, + }, switchedToken, EXTRA_HEADERS); + + const stockProbeRes = await invokeSystemMethod('stock.warehouse.search', { + keyword: '', + store_id: FIXED_RELATION.storeId, + with_stock: true, + is_batch: false, + }, switchedToken, EXTRA_HEADERS); + + if (relationProbeRes.status === 200 + && relationProbeRes.body?.flag === 'success' + && Number(relationProbeRes.body?.code) === 200 + && pickFixedTestRelation(relationProbeRes.body?.data?.list) + && stockProbeRes.status === 200 + && stockProbeRes.body?.flag === 'success' + && Number(stockProbeRes.body?.code) === 200) { + return { + token: switchedToken, + roleId, + }; + } + } + + return null; +} + +describe('test/app/controller/qimen.deliveryorder.reviewFlow.test.js', () => { + it('should create, review and move a delivery order through the real qimen flow', async function() { + const auth = await getAuthToken({ forceLogin: true }); + const switched = await switchToWarehouseRole(auth.token); + + if (!switched) { + this.skip(); + return; + } + + let relation = null; + let qimenConfig = null; + let stock = null; + let originalPolicyConfig = null; + let contractId = null; + const deliveryOrderCode = `QIMEN_REVIEW_${Date.now()}_${crypto.randomBytes(4).toString('hex').toUpperCase()}`; + + try { + const relationListRes = await invokeSystemMethod('storeWarehouse.store.list', { + page: 1, + page_size: 50, + }, switched.token, EXTRA_HEADERS); + + assert.equal(relationListRes.status, 200, `查询签约关系列表 HTTP 状态异常: ${JSON.stringify(relationListRes.body)}`); + assert.equal(relationListRes.body.flag, 'success', `查询签约关系列表失败: ${JSON.stringify(relationListRes.body)}`); + assert.equal(Number(relationListRes.body.code), 200, `查询签约关系列表 code 异常: ${JSON.stringify(relationListRes.body)}`); + + relation = pickFixedTestRelation(relationListRes.body?.data?.list); + if (!relation) { + this.skip(); + return; + } + + contractId = Number(relation.id || 0); + originalPolicyConfig = relation.policy_config && typeof relation.policy_config === 'object' + ? { ...relation.policy_config } + : null; + + if (!originalPolicyConfig) { + this.skip(); + return; + } + + const apiConfigRes = await invokeSystemMethod('storeWarehouse.store.listApiConfig', { + id: contractId, + }, switched.token, EXTRA_HEADERS); + + assert.equal(apiConfigRes.status, 200, `查询接口配置列表 HTTP 状态异常: ${JSON.stringify(apiConfigRes.body)}`); + assert.equal(apiConfigRes.body.flag, 'success', `查询接口配置列表失败: ${JSON.stringify(apiConfigRes.body)}`); + assert.equal(Number(apiConfigRes.body.code), 200, `查询接口配置列表 code 异常: ${JSON.stringify(apiConfigRes.body)}`); + + qimenConfig = pickEnabledQimenConfig(apiConfigRes.body?.data?.list); + if (!qimenConfig + || !String(qimenConfig.qimen_app_key || '').trim() + || !String(qimenConfig.qimen_customer_id || '').trim() + || !String(qimenConfig.qimen_warehouse_code || '').trim()) { + this.skip(); + return; + } + + const stockSearchRes = await invokeSystemMethod('stock.warehouse.search', { + keyword: '', + store_id: FIXED_RELATION.storeId, + with_stock: true, + is_batch: false, + }, switched.token, EXTRA_HEADERS); + + assert.equal(stockSearchRes.status, 200, `查询库存搜索 HTTP 状态异常: ${JSON.stringify(stockSearchRes.body)}`); + assert.equal(stockSearchRes.body.flag, 'success', `查询库存搜索失败: ${JSON.stringify(stockSearchRes.body)}`); + assert.equal(Number(stockSearchRes.body.code), 200, `查询库存搜索 code 异常: ${JSON.stringify(stockSearchRes.body)}`); + + stock = pickUsableStock(stockSearchRes.body?.data?.data || stockSearchRes.body?.data?.list || []); + if (!stock) { + this.skip(); + return; + } + + const nextPolicyConfig = { + ...originalPolicyConfig, + need_order_approval: 1, + }; + + const savePolicyRes = await invokeSystemMethod('storeWarehouse.store.savePolicyConfig', { + id: contractId, + policy_config: nextPolicyConfig, + }, switched.token, EXTRA_HEADERS); + + assert.equal(savePolicyRes.status, 200, `临时设置审核策略 HTTP 状态异常: ${JSON.stringify(savePolicyRes.body)}`); + assert.equal(savePolicyRes.body.flag, 'success', `临时设置审核策略失败: ${JSON.stringify(savePolicyRes.body)}`); + assert.equal(Number(savePolicyRes.body.code), 200, `临时设置审核策略 code 异常: ${JSON.stringify(savePolicyRes.body)}`); + assert.equal(Number(savePolicyRes.body?.data?.policy_config?.need_order_approval || 0), 1, '临时策略必须把 need_order_approval 置为 1'); + + const receiverInfo = { + name: '自动化测试收件人', + mobile: '13800138000', + province: '广东省', + city: '广州市', + area: '黄埔区', + town: '知识城街道', + detailAddress: `自动化测试地址 ${deliveryOrderCode}`, + zipCode: '510000', + }; + const requestXml = buildDeliveryOrderXml({ + deliveryOrderCode, + warehouseCode: String(qimenConfig.qimen_warehouse_code || '').trim(), + stock, + planQty: 1, + orderType: 'JYCK', + receiverInfo, + }); + + const createRes = await invokeQimenMethod('deliveryorder.create', requestXml, { + appKey: String(qimenConfig.qimen_app_key || '').trim(), + customerId: String(qimenConfig.qimen_customer_id || '').trim(), + contentType: 'application/xml', + format: 'xml', + signMethod: 'md5', + }); + + assert.equal(createRes.status, 200, `qimen 创建待审核订单 HTTP 状态异常: ${createRes.body}`); + const createResponse = createRes.parsed?.response || createRes.parsed || {}; + assert.equal(String(createResponse.flag || ''), 'success', `qimen 创建待审核订单失败。请求 XML:\n${requestXml}\n响应原文:\n${createRes.body}`); + assert.match(String(createRes.body || ''), /deliveryOrderId|createTime|success/i, `qimen 创建响应缺少预期字段。请求 XML:\n${requestXml}\n响应原文:\n${createRes.body}`); + + const reviewListRes = await invokeSystemMethod('order.reviewOrder.list', { + pagination: { + page: 1, + pageSize: 20, + }, + where: { + delivery_order_code: deliveryOrderCode, + }, + }, switched.token, EXTRA_HEADERS); + + assert.equal(reviewListRes.status, 200, `待审核列表 HTTP 状态异常: ${JSON.stringify(reviewListRes.body)}`); + assert.equal(reviewListRes.body.flag, 'success', `待审核列表查询失败: ${JSON.stringify(reviewListRes.body)}`); + assert.equal(Number(reviewListRes.body.code), 200, `待审核列表 code 异常: ${JSON.stringify(reviewListRes.body)}`); + + const reviewItems = Array.isArray(reviewListRes.body?.data?.list) ? reviewListRes.body.data.list : []; + const createdReviewOrder = reviewItems.find(item => String(item.delivery_order_code) === deliveryOrderCode); + assert.ok(createdReviewOrder, `待审核列表未命中刚创建的订单。响应原文: ${JSON.stringify(reviewListRes.body)}`); + assert.equal(Number(createdReviewOrder.step), 0, `新建订单应处于待审核 step=0。响应原文: ${JSON.stringify(reviewListRes.body)}`); + + const reviewActionRes = await invokeSystemMethod('order.reviewOrder.reviewOrder', { + ids: [ Number(createdReviewOrder.id) ], + }, switched.token, EXTRA_HEADERS); + + assert.equal(reviewActionRes.status, 200, `审核接口 HTTP 状态异常: ${JSON.stringify(reviewActionRes.body)}`); + assert.equal(reviewActionRes.body.flag, 'success', `审核接口调用失败: ${JSON.stringify(reviewActionRes.body)}`); + assert.equal(Number(reviewActionRes.body.code), 200, `审核接口 code 异常: ${JSON.stringify(reviewActionRes.body)}`); + assert.equal(Number(reviewActionRes.body?.data?.step), 1, `审核后订单 step 应变为 1。响应原文: ${JSON.stringify(reviewActionRes.body)}`); + + const pendingListRes = await invokeSystemMethod('order.pendingOrder.list', { + pagination: { + page: 1, + pageSize: 20, + }, + where: { + delivery_order_code: deliveryOrderCode, + }, + }, switched.token, EXTRA_HEADERS); + + assert.equal(pendingListRes.status, 200, `待处理列表 HTTP 状态异常: ${JSON.stringify(pendingListRes.body)}`); + assert.equal(pendingListRes.body.flag, 'success', `待处理列表查询失败: ${JSON.stringify(pendingListRes.body)}`); + assert.equal(Number(pendingListRes.body.code), 200, `待处理列表 code 异常: ${JSON.stringify(pendingListRes.body)}`); + + const pendingItems = Array.isArray(pendingListRes.body?.data?.list) ? pendingListRes.body.data.list : []; + const pendingOrder = pendingItems.find(item => String(item.delivery_order_code) === deliveryOrderCode); + assert.ok(pendingOrder, `待处理列表未命中已审核订单。响应原文: ${JSON.stringify(pendingListRes.body)}`); + assert.ok([ 1, 2 ].includes(Number(pendingOrder.step)), `审核后订单 step 应处于待处理范围。响应原文: ${JSON.stringify(pendingListRes.body)}`); + + const reviewAfterRes = await invokeSystemMethod('order.reviewOrder.list', { + pagination: { + page: 1, + pageSize: 20, + }, + where: { + delivery_order_code: deliveryOrderCode, + }, + }, switched.token, EXTRA_HEADERS); + + assert.equal(reviewAfterRes.status, 200, `复查待审核列表 HTTP 状态异常: ${JSON.stringify(reviewAfterRes.body)}`); + assert.equal(reviewAfterRes.body.flag, 'success', `复查待审核列表失败: ${JSON.stringify(reviewAfterRes.body)}`); + assert.equal(Number(reviewAfterRes.body.code), 200, `复查待审核列表 code 异常: ${JSON.stringify(reviewAfterRes.body)}`); + + const reviewAfterItems = Array.isArray(reviewAfterRes.body?.data?.list) ? reviewAfterRes.body.data.list : []; + const reviewAfterOrder = reviewAfterItems.find(item => String(item.delivery_order_code) === deliveryOrderCode); + assert.equal(reviewAfterOrder, undefined, `审核完成后不应再命中待审核列表。响应原文: ${JSON.stringify(reviewAfterRes.body)}`); + } finally { + if (contractId && originalPolicyConfig) { + const restoreRes = await invokeSystemMethod('storeWarehouse.store.savePolicyConfig', { + id: contractId, + policy_config: originalPolicyConfig, + }, switched.token, EXTRA_HEADERS); + + assert.equal(restoreRes.status, 200, `恢复原 policy_config 的 HTTP 状态异常: ${JSON.stringify(restoreRes.body)}`); + assert.equal(restoreRes.body.flag, 'success', `恢复原 policy_config 失败: ${JSON.stringify(restoreRes.body)}`); + assert.equal(Number(restoreRes.body.code), 200, `恢复原 policy_config code 异常: ${JSON.stringify(restoreRes.body)}`); + } + } + }); +}); diff --git a/test/app/controller/system.order.badgeCount.test.js b/test/app/controller/system.order.badgeCount.test.js new file mode 100644 index 0000000..340787a --- /dev/null +++ b/test/app/controller/system.order.badgeCount.test.js @@ -0,0 +1,172 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const OrderIndexService = require('../../../app/service/systemMethods/order/index'); +const { buildRows, createOrderHarness, matchesWhere } = require('../../support/order_service_test_helper'); + +function createBadgeCountHarness(rowsByModule = {}) { + const { service, captures } = createOrderHarness(OrderIndexService, { + rowsByModule, + }); + const cacheStore = new Map(); + const cacheStats = { + getCalls: 0, + setCalls: 0, + }; + + service.app.getCacheAsync = async cacheKey => { + cacheStats.getCalls += 1; + + if (!cacheStore.has(cacheKey)) { + return null; + } + + return cacheStore.get(cacheKey); + }; + + service.app.setCacheAsync = async (cacheKey, value) => { + cacheStats.setCalls += 1; + cacheStore.set(cacheKey, value); + }; + + return { + service, + captures, + cacheStats, + }; +} + +describe('test/app/controller/system.order.badgeCount.test.js', () => { + it('should return 8 badge fields and keep delivery/archive as 99+', async () => { + const { service, captures } = createBadgeCountHarness({ + reviewOrder: buildRows(99, () => ({ + step: 0, + dispatch_lane: 'm4', + })), + pendingOrder: buildRows(100, () => ({ + step: 1, + outbound_status: 'none', + dispatch_lane: 'm4', + })), + outboundOrder: buildRows(1, () => ({ + step: 1, + outbound_status: 'padding', + dispatch_lane: 'm4', + })), + expectionOrder: buildRows(2, () => ({ + step: 3, + dispatch_lane: 'm4', + })), + entrustOrder: buildRows(1, () => ({ + step: 1, + dispatch_lane: 'm4', + })), + }); + + const result = await service.badgeCount(); + + assert.deepEqual(Object.keys(result), [ + 'reviewOrder', + 'pendingOrder', + 'outboundOrder', + 'expectionOrder', + 'entrustOrder', + 'deliveryOrder', + 'deliveryExpectionOrder', + 'archiveOrder', + ]); + assert.equal(result.reviewOrder, 99); + assert.equal(result.pendingOrder, '99+'); + assert.equal(result.outboundOrder, 1); + assert.equal(result.expectionOrder, 2); + assert.equal(result.entrustOrder, 1); + assert.equal(result.deliveryOrder, '99+'); + assert.equal(result.deliveryExpectionOrder, '99+'); + assert.equal(result.archiveOrder, '99+'); + + assert.deepEqual(captures.map(item => item.moduleName), [ + 'reviewOrder', + 'pendingOrder', + 'outboundOrder', + 'expectionOrder', + 'entrustOrder', + ]); + assert.ok(matchesWhere({ warehouse_id: 100000, step: 0 }, captures[0].countWhere)); + assert.ok(matchesWhere({ warehouse_id: 100000, step: 1, outbound_status: 'none' }, captures[1].countWhere)); + assert.ok(matchesWhere({ warehouse_id: 100000, step: 1, outbound_status: 'padding' }, captures[2].countWhere)); + assert.ok(matchesWhere({ warehouse_id: 100000, step: 3 }, captures[3].countWhere)); + assert.ok(matchesWhere({ warehouse_id: 100000 }, captures[4].countWhere)); + }); + + it('should use cache and avoid repeated count queries', async () => { + const { service, captures, cacheStats } = createBadgeCountHarness({ + reviewOrder: buildRows(2, () => ({ + step: 0, + dispatch_lane: 'm4', + })), + pendingOrder: buildRows(2, () => ({ + step: 1, + outbound_status: 'none', + dispatch_lane: 'm4', + })), + outboundOrder: buildRows(2, () => ({ + step: 1, + outbound_status: 'none', + dispatch_lane: 'm4', + })), + expectionOrder: buildRows(1, () => ({ + step: 3, + dispatch_lane: 'm4', + })), + entrustOrder: buildRows(1, () => ({ + step: 1, + dispatch_lane: 'm4', + })), + }); + + const firstResult = await service.badgeCount(); + const firstCaptureCount = captures.length; + + const secondResult = await service.badgeCount(); + + assert.deepEqual(secondResult, firstResult); + assert.equal(captures.length, firstCaptureCount); + assert.equal(cacheStats.setCalls, 1); + assert.equal(cacheStats.getCalls, 2); + }); + + it('should keep exact counts within 99 and convert larger counts to 99+', async () => { + const { service } = createBadgeCountHarness({ + reviewOrder: buildRows(1, () => ({ + step: 0, + dispatch_lane: 'm4', + })), + pendingOrder: buildRows(100, () => ({ + step: 1, + outbound_status: 'none', + dispatch_lane: 'm4', + })), + outboundOrder: buildRows(99, () => ({ + step: 1, + outbound_status: 'none', + dispatch_lane: 'm4', + })), + expectionOrder: buildRows(3, () => ({ + step: 3, + dispatch_lane: 'm4', + })), + entrustOrder: buildRows(1, () => ({ + step: 1, + dispatch_lane: 'm4', + })), + }); + + const result = await service.badgeCount(); + + assert.equal(result.reviewOrder, 1); + assert.equal(result.pendingOrder, '99+'); + assert.equal(result.outboundOrder, 99); + assert.equal(result.expectionOrder, 3); + assert.equal(result.entrustOrder, 1); + }); +}); diff --git a/test/app/controller/system.order.getreviewOrderlist.test.js b/test/app/controller/system.order.getreviewOrderlist.test.js index 82303fb..f8fe10f 100644 --- a/test/app/controller/system.order.getreviewOrderlist.test.js +++ b/test/app/controller/system.order.getreviewOrderlist.test.js @@ -1,83 +1,33 @@ 'use strict'; const assert = require('node:assert/strict'); -const { - getAuthToken, - invokeSystemMethod, -} = require('../../support/system_method_client'); +const ReviewOrderService = require('../../../app/service/systemMethods/order/reviewOrder'); +const { buildRows, createOrderHarness } = require('../../support/order_service_test_helper'); -const EXTRA_HEADERS = { - platform: 'web', - project: 'all', -}; +describe('test/app/controller/system.order.reviewOrder.list.test.js', () => { + it('should return list/pagination for reviewOrder.list', async () => { + const { service, captures } = createOrderHarness(ReviewOrderService, { + rowsByModule: { + reviewOrder: buildRows(1, () => ({ + step: 0, + dispatch_lane: 'm4', + })), + }, + }); -const FALLBACK_ROLE_IDS = [ 4, 6, 30 ]; - -async function switchToWarehouseRoleWithOrderData(token) { - let currentToken = token; - const infoRes = await invokeSystemMethod('user.info', {}, currentToken, EXTRA_HEADERS); - assert.equal(infoRes.status, 200); - assert.equal(infoRes.body.flag, 'success'); - assert.equal(infoRes.body.code, 200); - - const employees = Array.isArray(infoRes.body?.data?.employees) ? infoRes.body.data.employees : []; - const warehouseRoles = employees.filter(item => item && item.role_type === 'warehouse' && Number(item.id)); - const candidateRoleIds = [ ...new Set([ - ...warehouseRoles.map(item => Number(item.id)), - ...FALLBACK_ROLE_IDS, - ].filter(Boolean)) ]; - - assert.ok(candidateRoleIds.length > 0, '当前账号没有可尝试的仓库角色'); - - for (const roleId of candidateRoleIds) { - const changeRes = await invokeSystemMethod('user.changeRole', { - roleId, - }, currentToken, EXTRA_HEADERS); - - if (changeRes.status !== 200 || changeRes.body?.flag !== 'success' || changeRes.body?.code !== 200) { - continue; - } - - currentToken = changeRes.body?.data?.token || currentToken; - - const statsRes = await invokeSystemMethod('order.stats', { - where: {}, - }, currentToken, EXTRA_HEADERS); - - assert.equal(statsRes.status, 200); - assert.equal(statsRes.body.flag, 'success'); - assert.equal(statsRes.body.code, 200); - - const total = Number(statsRes.body?.data?.total || 0); - if (total > 0) { - return { - token: currentToken, - }; - } - } - - throw new Error('未找到有订单数据的仓库角色'); -} - -describe('test/app/controller/system.order.getreviewOrderlist.test.js', () => { - it('should call order.getreviewOrderlist with platform=web project=all', async () => { - const { token } = await getAuthToken(); - const switched = await switchToWarehouseRoleWithOrderData(token); - - const res = await invokeSystemMethod('order.getreviewOrderlist', { + const result = await service.list({ pagination: { page: 1, - pageSize: 10, + pageSize: 1, }, where: {}, - }, switched.token, EXTRA_HEADERS); + }); - assert.equal(res.status, 200); - assert.equal(res.body.flag, 'success'); - assert.equal(res.body.code, 200); - assert.ok(res.body.data); - assert.ok(Array.isArray(res.body.data.list)); - assert.ok(res.body.data.pagination); - assert.equal(typeof res.body.data.pagination.total, 'number'); + assert.equal(captures[0].moduleName, 'reviewOrder'); + assert.ok(Array.isArray(result.list)); + assert.ok(result.pagination); + assert.equal(result.pagination.page, 1); + assert.equal(result.pagination.pageSize, 1); + assert.equal(result.list.length, 1); }); }); diff --git a/test/app/controller/system.order.namespaced.test.js b/test/app/controller/system.order.namespaced.test.js index dfb14a9..63bd0aa 100644 --- a/test/app/controller/system.order.namespaced.test.js +++ b/test/app/controller/system.order.namespaced.test.js @@ -1,198 +1,64 @@ 'use strict'; const assert = require('node:assert/strict'); -const { - getAuthToken, - invokeSystemMethod, -} = require('../../support/system_method_client'); - -const EXTRA_HEADERS = { - platform: 'web', - project: 'all', -}; - -const ALLOWED_REVIEW_STATUS = new Set([ 'none', 'padding', 'running', 'fin', 'error' ]); -const FALLBACK_ROLE_IDS = [ 4, 6, 30 ]; - -function mapReviewStatusToStep(reviewStatus) { - const status = String(reviewStatus || 'none').trim(); - if (status === 'fin') { - return 1; - } - if (status === 'running' || status === 'padding') { - return 2; - } - if (status === 'error') { - return 3; - } - return 0; -} - -async function switchToWarehouseRoleWithOrderData(token) { - let currentToken = token; - const infoRes = await invokeSystemMethod('user.info', {}, currentToken, EXTRA_HEADERS); - assert.equal(infoRes.status, 200); - assert.equal(infoRes.body.flag, 'success'); - assert.equal(infoRes.body.code, 200); - - const employees = Array.isArray(infoRes.body?.data?.employees) ? infoRes.body.data.employees : []; - const warehouseRoles = employees.filter(item => item && item.role_type === 'warehouse' && Number(item.id)); - const candidateRoleIds = [ ...new Set([ - ...warehouseRoles.map(item => Number(item.id)), - ...FALLBACK_ROLE_IDS, - ].filter(Boolean)) ]; - - assert.ok(candidateRoleIds.length > 0, '当前账号没有可尝试的仓库角色'); - - for (const roleId of candidateRoleIds) { - const changeRes = await invokeSystemMethod('user.changeRole', { - roleId, - }, currentToken, EXTRA_HEADERS); - - if (changeRes.status !== 200 || changeRes.body?.flag !== 'success' || changeRes.body?.code !== 200) { - continue; - } - - currentToken = changeRes.body?.data?.token || currentToken; - - const statsRes = await invokeSystemMethod('order.stats', { - where: {}, - }, currentToken, EXTRA_HEADERS); - - assert.equal(statsRes.status, 200); - assert.equal(statsRes.body.flag, 'success'); - assert.equal(statsRes.body.code, 200); - - const total = Number(statsRes.body?.data?.total || 0); - if (total > 0) { - return { - token: currentToken, - roleId, - total, - }; - } - } - - throw new Error('未找到有订单数据的仓库角色'); -} +const OrderIndexService = require('../../../app/service/systemMethods/order/index'); +const { buildRows, createOrderHarness } = require('../../support/order_service_test_helper'); describe('test/app/controller/system.order.namespaced.test.js', () => { - it('should query all namespaced order lists', async () => { - const { token } = await getAuthToken(); - const switched = await switchToWarehouseRoleWithOrderData(token); + it('should return list/pagination for order.list', async () => { + const { service, captures } = createOrderHarness(OrderIndexService, { + rowsByModule: { + order: buildRows(1, () => ({ + step: 1, + dispatch_lane: 'm4', + })), + }, + }); - const methods = [ - 'order.reviewOrder.getreviewOrderlist', - 'order.deliveryOrder.getdeliveryOrderlist', - 'order.pendingOrder.getpendingOrderlist', - 'order.expectionOrder.getexpectionOrderlist', - 'order.archiveOrder.getarchiveOrderlist', - ]; - - for (const method of methods) { - const res = await invokeSystemMethod(method, { - pagination: { - page: 1, - pageSize: 10, - }, - where: {}, - }, switched.token, EXTRA_HEADERS); - - assert.equal(res.status, 200, `${method} http status 异常`); - assert.equal(res.body.flag, 'success', `${method} flag 异常`); - assert.equal(res.body.code, 200, `${method} code 异常`); - assert.ok(res.body.data, `${method} 缺少 data`); - assert.ok(Array.isArray(res.body.data.list), `${method} list 不是数组`); - assert.ok(res.body.data.pagination, `${method} 缺少 pagination`); - assert.equal(typeof res.body.data.pagination.total, 'number', `${method} total 不是 number`); - } - }); - - it('should review order through namespaced method and restore status', async () => { - const { token } = await getAuthToken(); - const switched = await switchToWarehouseRoleWithOrderData(token); - - const listRes = await invokeSystemMethod('order.list', { + const result = await service.list({ pagination: { page: 1, pageSize: 1, }, - where: {}, - }, switched.token, EXTRA_HEADERS); + where: { + step: 1, + }, + }); - assert.equal(listRes.status, 200); - assert.equal(listRes.body.flag, 'success'); - assert.equal(listRes.body.code, 200); + const capture = captures[0]; - const order = Array.isArray(listRes.body?.data?.list) ? listRes.body.data.list[0] : null; - assert.ok(order, '订单列表为空,无法测试目录化 reviewOrder'); - assert.ok(order.id, '订单缺少 id,无法测试目录化 reviewOrder'); - - const originalStatus = ALLOWED_REVIEW_STATUS.has(String(order.inspection_status || '')) - ? String(order.inspection_status) - : 'none'; - const targetStatus = originalStatus === 'fin' ? 'running' : 'fin'; - - const reviewRes = await invokeSystemMethod('order.reviewOrder.reviewOrder', { - id: Number(order.id), - review_status: targetStatus, - }, switched.token, EXTRA_HEADERS); - - assert.equal(reviewRes.status, 200); - assert.equal(reviewRes.body.flag, 'success'); - assert.equal(reviewRes.body.code, 200); - assert.equal(Number(reviewRes.body?.data?.id || 0), Number(order.id)); - assert.equal(reviewRes.body?.data?.inspection_status, targetStatus); - assert.equal(Number(reviewRes.body?.data?.step), mapReviewStatusToStep(targetStatus)); - - const restoreRes = await invokeSystemMethod('order.reviewOrder.reviewOrder', { - id: Number(order.id), - review_status: originalStatus, - }, switched.token, EXTRA_HEADERS); - - assert.equal(restoreRes.status, 200); - assert.equal(restoreRes.body.flag, 'success'); - assert.equal(restoreRes.body.code, 200); - assert.equal(restoreRes.body?.data?.inspection_status, originalStatus); - assert.equal(Number(restoreRes.body?.data?.step), mapReviewStatusToStep(originalStatus)); + assert.equal(capture.moduleName, 'order'); + assert.equal(result.pagination.pageSize, 1); + assert.equal(result.list.length, 1); }); - it('should return step in delivery orders and support filtering', async () => { - const { token } = await getAuthToken(); - const switched = await switchToWarehouseRoleWithOrderData(token); + it('should hide deprecated order compatibility aliases', async () => { + const { service } = createOrderHarness(OrderIndexService, { + rowsByModule: { + order: buildRows(1, () => ({ + step: 1, + dispatch_lane: 'm4', + })), + }, + }); - const listRes = await invokeSystemMethod('order.deliveryOrder.getdeliveryOrderlist', { - pagination: { page: 1, pageSize: 10 }, - where: {}, - }, switched.token, EXTRA_HEADERS); + const deprecatedMethods = [ + 'reviewOrder', + 'pendingOrder', + 'outboundOrder', + 'expectionOrder', + 'entrustOrder', + 'deliveryOrder', + 'deliveryExpectionOrder', + 'archiveOrder', + ]; - assert.equal(listRes.status, 200); - assert.equal(listRes.body.flag, 'success'); - assert.equal(listRes.body.code, 200); - - const orders = listRes.body?.data?.list; - assert.ok(Array.isArray(orders)); - - if (orders.length > 0) { - assert.ok(Object.prototype.hasOwnProperty.call(orders[0], 'step'), '发货单应包含 step 字段'); - const sampleStep = Number(orders[0].step); - - const filteredRes = await invokeSystemMethod('order.deliveryOrder.getdeliveryOrderlist', { - pagination: { page: 1, pageSize: 10 }, - where: { step: sampleStep }, - }, switched.token, EXTRA_HEADERS); - - assert.equal(filteredRes.status, 200); - assert.equal(filteredRes.body.flag, 'success'); - assert.equal(filteredRes.body.code, 200); - const filteredOrders = filteredRes.body?.data?.list; - assert.ok(Array.isArray(filteredOrders)); - if (filteredOrders.length > 0) { - assert.ok( - filteredOrders.every(order => Number(order.step) === sampleStep), - `按 step=${sampleStep} 过滤后,所有订单都应是该状态` - ); - } + for (const methodName of deprecatedMethods) { + assert.equal(typeof service[methodName], 'undefined', `${methodName} 仍被暴露`); } + + assert.equal(typeof service.list, 'function'); + assert.equal(typeof service.badgeCount, 'function'); + assert.equal(typeof service.manualOutboundOrder, 'function'); }); }); diff --git a/test/app/controller/system.order.outbound.exposure.test.js b/test/app/controller/system.order.outbound.exposure.test.js new file mode 100644 index 0000000..3b0b40b --- /dev/null +++ b/test/app/controller/system.order.outbound.exposure.test.js @@ -0,0 +1,90 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const OrderIndexService = require('../../../app/service/systemMethods/order/index'); +const { buildRows, createOrderHarness } = require('../../support/order_service_test_helper'); + +describe('test/app/controller/system.order.outbound.exposure.test.js', () => { + it('should keep manualOutboundOrder exposed and remove deprecated outboundOrder alias', async () => { + const { service } = createOrderHarness(OrderIndexService, { + rowsByModule: { + order: buildRows(1, () => ({ + step: 1, + dispatch_lane: 'm4', + })), + }, + }); + + const methodNames = [ + 'markOutboundOrder', + 'manualOutboundOrder', + ]; + + assert.equal(typeof service.markOutboundOrder, 'undefined'); + assert.equal(typeof service.outboundOrder, 'undefined'); + assert.equal(typeof service.manualOutboundOrder, 'function'); + + const methodsManifest = require('../../../methods/system.json'); + const exposedMethodNames = methodsManifest.methods.groups + .flatMap(group => (Array.isArray(group.list) ? group.list : [])) + .map(item => item.method); + + const hasInternalOutboundMethod = exposedMethodNames.some(methodName => { + return methodName === 'order.markOutboundOrder'; + }); + + const hasDeprecatedOutboundAlias = exposedMethodNames.some(methodName => { + return methodName === 'order.outboundOrder'; + }); + + assert.equal(hasInternalOutboundMethod, false); + assert.equal(hasDeprecatedOutboundAlias, false); + + for (const methodName of methodNames) { + if (methodName === 'markOutboundOrder') { + continue; + } + + assert.equal(typeof service[methodName], 'function'); + } + }); + + it('should pass batch params through manualOutboundOrder to orderDeliveryMigration and return its result', async () => { + const { ctx, service } = createOrderHarness(OrderIndexService, { + rowsByModule: { + order: buildRows(1), + }, + }); + + const requestData = { + warehouseId: 100000, + warehouseIds: [ 100000, 100001 ], + queryTimeoutMs: 12345, + executionTimeoutMs: 23456, + batchSize: 20, + customFlag: 'keep-as-is', + }; + + const expectedResult = { + ok: true, + totalCreated: 8, + }; + + let receivedPayload = null; + ctx.service = { + systems: { + orderDeliveryMigration: { + async syncOutboundOrdersToDelivery(data) { + receivedPayload = data; + return expectedResult; + }, + }, + }, + }; + + const result = await service.manualOutboundOrder(requestData); + + assert.strictEqual(receivedPayload, requestData); + assert.deepEqual(result, expectedResult); + }); +}); diff --git a/test/app/controller/system.order.pendingOrder.reverseReviewOrder.test.js b/test/app/controller/system.order.pendingOrder.reverseReviewOrder.test.js new file mode 100644 index 0000000..ca0f4b6 --- /dev/null +++ b/test/app/controller/system.order.pendingOrder.reverseReviewOrder.test.js @@ -0,0 +1,613 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const Sequelize = require('sequelize'); +const PendingOrderService = require('../../../app/service/systemMethods/order/pendingOrder'); +const ReviewOrderService = require('../../../app/service/systemMethods/order/reviewOrder'); +const ExpectionOrderService = require('../../../app/service/systemMethods/order/expectionOrder'); +const { buildRows, createOrderHarness, matchesWhere } = require('../../support/order_service_test_helper'); +const OrderIndexService = require('../../../app/service/systemMethods/order/index'); + +/** + * 创建支持更新结果回写的订单模型。 + * @param {Array} rows 初始订单数据。 + * @param {Object} capture 调用信息。 + * @return {Object} 模拟模型。 + */ +function createMutableOrderModel(rows, capture = {}) { + const storedRows = Array.isArray(rows) ? rows.map(row => ({ ...row })) : []; + capture.rows = storedRows; + + return { + async count(options = {}) { + capture.countWhere = options.where; + return storedRows.filter(row => matchesWhere(row, options.where)).length; + }, + async update(values = {}, options = {}) { + capture.updateValues = { ...values }; + capture.updateWhere = options.where; + + const matchedRows = storedRows.filter(row => matchesWhere(row, options.where)); + for (const row of matchedRows) { + Object.assign(row, values); + } + + return [ matchedRows.length ]; + }, + async findAll(options = {}) { + capture.findAllWhere = options.where; + return storedRows + .filter(row => matchesWhere(row, options.where)) + .map(row => ({ ...row })); + }, + }; +} + +/** + * 创建待处理订单反审服务测试实例。 + * @param {Array} rows 初始订单数据。 + * @return {{ service: PendingOrderService, capture: Object }} 服务与调用记录。 + */ +function createPendingOrderService(rows) { + const { service } = createOrderHarness(PendingOrderService, { + defaultRows: rows, + }); + const capture = {}; + const model = createMutableOrderModel(rows, capture); + + service.getOrderModel = async moduleName => { + capture.moduleName = moduleName; + return model; + }; + + return { + service, + capture, + }; +} + +/** + * 创建待处理订单取消与列表语义验证的共享服务实例。 + * @param {Array} rows 初始订单数据。 + * @return {{ pendingService: PendingOrderService, orderService: OrderIndexService, reviewService: ReviewOrderService, expectionService: ExpectionOrderService, capture: Object }} 共享服务与调用记录。 + */ +function createPendingOrderWorkflowService(rows) { + const { ctx, service: pendingService } = createOrderHarness(PendingOrderService, { + defaultRows: rows, + }); + const orderService = new OrderIndexService(ctx); + const reviewService = new ReviewOrderService(ctx); + const expectionService = new ExpectionOrderService(ctx); + const capture = {}; + const model = createMutableOrderModel(rows, capture); + + pendingService.getOrderModel = async moduleName => { + capture.moduleName = moduleName; + return model; + }; + + orderService.getOrderModel = async moduleName => { + capture.moduleName = moduleName; + return model; + }; + + reviewService.getOrderModel = async moduleName => { + capture.moduleName = moduleName; + return model; + }; + + expectionService.getOrderModel = async moduleName => { + capture.moduleName = moduleName; + return model; + }; + + return { + pendingService, + orderService, + reviewService, + expectionService, + capture, + }; +} + +describe('test/app/controller/system.order.pendingOrder.reverseReviewOrder.test.js', () => { + it('should reverse batch orders by ids array', async () => { + const { service, capture } = createPendingOrderService(buildRows(3, index => ({ + id: index + 1, + warehouse_id: 100000, + step: 1, + inspection_status: 'fin', + order_flag: '待清理异常标记', + updated_at: '2026-04-12 00:00:00', + }))); + + const result = await service.reverseReviewOrder({ + ids: [ 1, 3 ], + }); + + assert.equal(capture.updateValues.inspection_status, 'none'); + assert.equal(capture.updateValues.step, 0); + assert.equal(capture.updateValues.order_flag, undefined); + assert.equal(capture.updateWhere.warehouse_id, 100000); + assert.equal(capture.updateWhere.id[Sequelize.Op.in].length, 2); + assert.ok(matchesWhere({ id: 1, warehouse_id: 100000 }, capture.updateWhere)); + assert.ok(!matchesWhere({ id: 2, warehouse_id: 100000 }, capture.updateWhere)); + assert.ok(matchesWhere({ id: 3, warehouse_id: 100000 }, capture.updateWhere)); + assert.equal(result.id, 1); + assert.equal(result.inspection_status, 'none'); + assert.equal(result.step, 0); + assert.equal(result.updated_count, 2); + assert.deepEqual(result.ids, [ 1, 3 ]); + assert.equal(capture.rows.find(row => row.id === 1).order_flag, '待清理异常标记'); + assert.equal(capture.rows.find(row => row.id === 3).order_flag, '待清理异常标记'); + }); + + it('should mark batch orders as pending outbound by ids array', async () => { + const { service, capture } = createPendingOrderService(buildRows(3, index => ({ + id: index + 1, + warehouse_id: 100000, + step: 1, + outbound_status: 'none', + updated_at: '2026-04-12 00:00:00', + }))); + + const result = await service.markPendingOutboundOrder({ + ids: [ 1, 3 ], + }); + + assert.equal(capture.updateValues.outbound_status, 'padding'); + assert.ok(capture.updateValues.updated_at instanceof Date); + assert.equal(capture.updateWhere.warehouse_id, 100000); + assert.equal(capture.updateWhere.id[Sequelize.Op.in].length, 2); + assert.ok(matchesWhere({ id: 1, warehouse_id: 100000 }, capture.updateWhere)); + assert.ok(!matchesWhere({ id: 2, warehouse_id: 100000 }, capture.updateWhere)); + assert.ok(matchesWhere({ id: 3, warehouse_id: 100000 }, capture.updateWhere)); + assert.equal(result.id, 1); + assert.equal(result.outbound_status, 'padding'); + assert.equal(result.updated_count, 2); + assert.deepEqual(result.ids, [ 1, 3 ]); + assert.equal(capture.rows.find(row => row.id === 1).outbound_status, 'padding'); + assert.equal(capture.rows.find(row => row.id === 3).outbound_status, 'padding'); + }); + + it('should mark batch orders by ids array and reject cross-warehouse orders', async () => { + const scenarios = [ + { + payload: { + ids: [ 1 ], + }, + expectedId: 1, + }, + { + payload: { + ids: [ 2 ], + }, + expectedId: 2, + }, + ]; + + for (const scenario of scenarios) { + const { service, capture } = createPendingOrderService(buildRows(2, index => ({ + id: index + 1, + warehouse_id: 100000, + step: 1, + outbound_status: 'none', + updated_at: '2026-04-12 00:00:00', + }))); + + const result = await service.markPendingOutboundOrder(scenario.payload); + + assert.equal(capture.updateValues.outbound_status, 'padding'); + assert.ok(capture.updateValues.updated_at instanceof Date); + assert.equal(capture.updateWhere.id, scenario.expectedId); + assert.equal(capture.updateWhere.warehouse_id, 100000); + assert.equal(result.id, scenario.expectedId); + assert.equal(result.outbound_status, 'padding'); + assert.equal(result.updated_count, 1); + assert.deepEqual(result.ids, [ scenario.expectedId ]); + assert.equal(capture.rows.find(row => row.id === scenario.expectedId).outbound_status, 'padding'); + } + + const invalidPayloads = [ + { + payload: { + id: 1, + }, + message: /仅支持 ids 数组入参,不再支持 id、order_id、逗号字符串或其他兼容字段/, + }, + { + payload: { + order_id: 2, + }, + message: /仅支持 ids 数组入参,不再支持 id、order_id、逗号字符串或其他兼容字段/, + }, + { + payload: { + ids: '1,2', + }, + message: /仅支持 ids 数组入参/, + }, + { + payload: { + ids: [], + }, + message: /订单ID不能为空/, + }, + { + payload: { + ids: [ 1, 0 ], + }, + message: /ids 仅支持正整数数组/, + }, + { + payload: { + ids: [ 1, -2 ], + }, + message: /ids 仅支持正整数数组/, + }, + ]; + + for (const scenario of invalidPayloads) { + const { service } = createPendingOrderService(buildRows(2, index => ({ + id: index + 1, + warehouse_id: 100000, + step: 1, + outbound_status: 'none', + updated_at: '2026-04-12 00:00:00', + }))); + + await assert.rejects( + async () => await service.markPendingOutboundOrder(scenario.payload), + scenario.message + ); + } + + const { service: crossWarehouseService } = createPendingOrderService([ + { + id: 1, + warehouse_id: 100000, + step: 1, + outbound_status: 'none', + updated_at: '2026-04-12 00:00:00', + }, + { + id: 2, + warehouse_id: 100001, + step: 1, + outbound_status: 'none', + updated_at: '2026-04-12 00:00:00', + }, + ]); + + await assert.rejects( + async () => await crossWarehouseService.markPendingOutboundOrder({ + ids: [ 1, 2 ], + }), + /订单不存在或不属于当前仓库/ + ); + }); + + it('should reverse single order with legacy id/order_id fields', async () => { + const scenarios = [ + { + payload: { + id: 1, + }, + expectedId: 1, + }, + { + payload: { + order_id: 2, + }, + expectedId: 2, + }, + ]; + + for (const scenario of scenarios) { + const { service, capture } = createPendingOrderService(buildRows(2, index => ({ + id: index + 1, + warehouse_id: 100000, + step: 1, + inspection_status: 'fin', + order_flag: '待清理异常标记', + updated_at: '2026-04-12 00:00:00', + }))); + + const result = await service.reverseReviewOrder(scenario.payload); + + assert.equal(capture.updateValues.inspection_status, 'none'); + assert.equal(capture.updateValues.step, 0); + assert.equal(capture.updateValues.order_flag, undefined); + assert.equal(capture.updateWhere.id, scenario.expectedId); + assert.equal(capture.updateWhere.warehouse_id, 100000); + assert.equal(result.id, scenario.expectedId); + assert.equal(result.inspection_status, 'none'); + assert.equal(result.step, 0); + assert.equal(result.updated_count, 1); + assert.deepEqual(result.ids, [ scenario.expectedId ]); + assert.equal(capture.rows.find(row => row.id === scenario.expectedId).order_flag, '待清理异常标记'); + } + }); + + it('should reject when pending outbound order ids are missing', async () => { + const { service } = createPendingOrderService(buildRows(1, index => ({ + id: index + 1, + warehouse_id: 100000, + step: 1, + outbound_status: 'none', + updated_at: '2026-04-12 00:00:00', + }))); + + await assert.rejects( + async () => await service.markPendingOutboundOrder({ + ids: [], + }), + /订单ID不能为空/ + ); + }); + + it('should reject when pending outbound ids is not an array', async () => { + const { service } = createPendingOrderService(buildRows(1, index => ({ + id: index + 1, + warehouse_id: 100000, + step: 1, + outbound_status: 'none', + updated_at: '2026-04-12 00:00:00', + }))); + + await assert.rejects( + async () => await service.markPendingOutboundOrder({ + ids: '1,2', + }), + /仅支持 ids 数组入参/ + ); + }); + + it('should reject when ids, id and order_id are missing', async () => { + const { service } = createPendingOrderService(buildRows(1, index => ({ + id: index + 1, + warehouse_id: 100000, + step: 1, + inspection_status: 'fin', + updated_at: '2026-04-12 00:00:00', + }))); + + await assert.rejects( + async () => await service.reverseReviewOrder({}), + /订单ID不能为空/ + ); + }); + + it('should write back to pending review status', async () => { + const { service, capture } = createPendingOrderService(buildRows(1, index => ({ + id: index + 1, + warehouse_id: 100000, + step: 1, + inspection_status: 'fin', + order_flag: '待清理异常标记', + updated_at: '2026-04-12 00:00:00', + }))); + + const result = await service.reverseReviewOrder({ + id: 1, + }); + + assert.equal(capture.updateValues.inspection_status, 'none'); + assert.equal(capture.updateValues.step, 0); + assert.equal(capture.updateValues.order_flag, undefined); + assert.equal(result.inspection_status, 'none'); + assert.equal(result.step, 0); + assert.equal(result.updated_count, 1); + assert.deepEqual(result.ids, [ 1 ]); + assert.equal(capture.rows[0].order_flag, '待清理异常标记'); + }); + + it('should cancel batch orders by ids array and remove them from pending review exception lists', async () => { + const { pendingService, orderService, reviewService, expectionService, capture } = createPendingOrderWorkflowService(buildRows(3, index => ({ + id: index + 1, + warehouse_id: 100000, + step: index === 0 ? 0 : (index === 1 ? 1 : 3), + status: 'created', + outbound_status: 'none', + inspection_status: index === 0 ? 'none' : 'fin', + updated_at: '2026-04-12 00:00:00', + }))); + + const result = await pendingService.cancelOrder({ + ids: [ 1, 2, 3 ], + }); + + assert.equal(capture.updateValues.status, 'cancel'); + assert.equal(capture.updateValues.step, 9); + assert.ok(capture.updateValues.updated_at instanceof Date); + assert.equal(capture.updateWhere.warehouse_id, 100000); + assert.equal(capture.updateWhere.id[Sequelize.Op.in].length, 3); + assert.equal(result.id, 1); + assert.equal(result.status, 'cancel'); + assert.equal(result.step, 9); + assert.equal(result.updated_count, 3); + assert.deepEqual(result.ids, [ 1, 2, 3 ]); + + for (const orderId of [ 1, 2, 3 ]) { + const row = capture.rows.find(item => item.id === orderId); + assert.equal(row.status, 'cancel'); + assert.equal(row.step, 9); + } + + const pendingList = await pendingService.list({ + pagination: { + page: 1, + pageSize: 20, + }, + where: {}, + }); + const reviewList = await reviewService.list({ + pagination: { + page: 1, + pageSize: 20, + }, + where: {}, + }); + const exceptionList = await expectionService.list({ + pagination: { + page: 1, + pageSize: 20, + }, + where: {}, + }); + + assert.equal(pendingList.pagination.total, 0); + assert.equal(reviewList.pagination.total, 0); + assert.equal(exceptionList.pagination.total, 0); + assert.deepEqual(pendingList.list, []); + assert.deepEqual(reviewList.list, []); + assert.deepEqual(exceptionList.list, []); + }); + + it('should reject cancel order when ids are empty invalid or forbidden', async () => { + const invalidPayloads = [ + { + payload: {}, + message: /仅支持 ids 数组入参/, + }, + { + payload: { + id: 1, + }, + message: /仅支持 ids 数组入参,不再支持 id、order_id、逗号字符串或其他兼容字段/, + }, + { + payload: { + ids: [], + }, + message: /订单ID不能为空/, + }, + { + payload: { + ids: '1,2', + }, + message: /仅支持 ids 数组入参/, + }, + { + payload: { + ids: [ 1, 0 ], + }, + message: /ids 仅支持正整数数组/, + }, + { + payload: { + ids: [ 1, -2 ], + }, + message: /ids 仅支持正整数数组/, + }, + ]; + + for (const scenario of invalidPayloads) { + const { service: pendingService } = createPendingOrderService(buildRows(2, index => ({ + id: index + 1, + warehouse_id: 100000, + step: 1, + status: 'created', + outbound_status: 'none', + updated_at: '2026-04-12 00:00:00', + }))); + + await assert.rejects( + async () => await pendingService.cancelOrder(scenario.payload), + scenario.message + ); + } + + const { service: crossWarehouseService } = createPendingOrderService([ + { + id: 1, + warehouse_id: 100000, + step: 1, + status: 'created', + outbound_status: 'none', + updated_at: '2026-04-12 00:00:00', + }, + { + id: 2, + warehouse_id: 100001, + step: 1, + status: 'created', + outbound_status: 'none', + updated_at: '2026-04-12 00:00:00', + }, + ]); + + await assert.rejects( + async () => await crossWarehouseService.cancelOrder({ + ids: [ 1, 2 ], + }), + /订单不存在或不属于当前仓库/ + ); + + const forbiddenScenarios = [ + { + rows: [ + { + id: 1, + warehouse_id: 100000, + step: 5, + status: 'created', + outbound_status: 'none', + updated_at: '2026-04-12 00:00:00', + }, + ], + message: /订单当前状态不允许取消/, + }, + { + rows: [ + { + id: 1, + warehouse_id: 100000, + step: 1, + status: 'created', + outbound_status: 'padding', + updated_at: '2026-04-12 00:00:00', + }, + ], + message: /订单当前状态不允许取消/, + }, + { + rows: [ + { + id: 1, + warehouse_id: 100000, + step: 9, + status: 'cancel', + outbound_status: 'none', + updated_at: '2026-04-12 00:00:00', + }, + ], + message: /订单当前状态不允许取消/, + }, + ]; + + for (const scenario of forbiddenScenarios) { + const { service: pendingService } = createPendingOrderService(scenario.rows); + + await assert.rejects( + async () => await pendingService.cancelOrder({ + ids: [ 1 ], + }), + scenario.message + ); + } + }); + + it('should return success when pending table has no data', async () => { + const { service } = createPendingOrderService([]); + + const result = await service.cancelOrder({ + ids: [ 1 ], + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.message, '取消成功'); + assert.equal(result.updated_count, 0); + assert.deepEqual(result.ids, []); + }); +}); diff --git a/test/app/controller/system.order.reviewOrder.test.js b/test/app/controller/system.order.reviewOrder.test.js index b2222d1..0686e4f 100644 --- a/test/app/controller/system.order.reviewOrder.test.js +++ b/test/app/controller/system.order.reviewOrder.test.js @@ -1,112 +1,353 @@ 'use strict'; const assert = require('node:assert/strict'); -const { - getAuthToken, - invokeSystemMethod, -} = require('../../support/system_method_client'); +const Sequelize = require('sequelize'); +const ReviewOrderService = require('../../../app/service/systemMethods/order/reviewOrder'); +const PendingOrderService = require('../../../app/service/systemMethods/order/pendingOrder'); +const { buildRows, createOrderHarness, matchesWhere } = require('../../support/order_service_test_helper'); -const EXTRA_HEADERS = { - platform: 'web', - project: 'all', -}; +/** + * 创建支持更新结果回写的订单模型。 + * @param {Array} rows 初始订单数据。 + * @param {Object} capture 调用信息。 + * @return {Object} 模拟模型。 + */ +function createMutableOrderModel(rows, capture = {}) { + const storedRows = Array.isArray(rows) ? rows.map(row => ({ ...row })) : []; + capture.rows = storedRows; -const ALLOWED_REVIEW_STATUS = new Set([ 'none', 'padding', 'running', 'fin', 'error' ]); -const FALLBACK_ROLE_IDS = [ 4, 6, 30 ]; + return { + async count({ where } = {}) { + capture.countWhere = where; + return storedRows.filter(row => matchesWhere(row, where)).length; + }, + async update(values = {}, options = {}) { + capture.updateValues = { ...values }; + capture.updateWhere = options.where; -async function switchToWarehouseRoleWithOrderData(token) { - let currentToken = token; - const infoRes = await invokeSystemMethod('user.info', {}, currentToken, EXTRA_HEADERS); - assert.equal(infoRes.status, 200); - assert.equal(infoRes.body.flag, 'success'); - assert.equal(infoRes.body.code, 200); + const matchedRows = storedRows.filter(row => matchesWhere(row, options.where)); + for (const row of matchedRows) { + Object.assign(row, values); + } - const employees = Array.isArray(infoRes.body?.data?.employees) ? infoRes.body.data.employees : []; - const warehouseRoles = employees.filter(item => item && item.role_type === 'warehouse' && Number(item.id)); - const candidateRoleIds = [ ...new Set([ - ...warehouseRoles.map(item => Number(item.id)), - ...FALLBACK_ROLE_IDS, - ].filter(Boolean)) ]; + return [ matchedRows.length ]; + }, + async findAll(options = {}) { + capture.findAllWhere = options.where; + return storedRows + .filter(row => matchesWhere(row, options.where)) + .map(row => ({ ...row })); + }, + async findOne(options = {}) { + capture.findOneWhere = options.where; + const matchedRow = storedRows.find(row => matchesWhere(row, options.where)); + return matchedRow ? { ...matchedRow } : null; + }, + }; +} - assert.ok(candidateRoleIds.length > 0, '当前账号没有可尝试的仓库角色'); +/** + * 创建共享同一份行数组的订单模型。 + * @param {Array} rows 共享订单数据。 + * @param {Object} capture 调用信息。 + * @return {Object} 模拟模型。 + */ +function createSharedMutableOrderModel(rows, capture = {}) { + const storedRows = Array.isArray(rows) ? rows : []; + capture.rows = storedRows; - for (const roleId of candidateRoleIds) { - const changeRes = await invokeSystemMethod('user.changeRole', { - roleId, - }, currentToken, EXTRA_HEADERS); + return { + async count({ where } = {}) { + capture.countWhere = where; + return storedRows.filter(row => matchesWhere(row, where)).length; + }, + async update(values = {}, options = {}) { + capture.updateValues = { ...values }; + capture.updateWhere = options.where; - if (changeRes.status !== 200 || changeRes.body?.flag !== 'success' || changeRes.body?.code !== 200) { - continue; - } + const matchedRows = storedRows.filter(row => matchesWhere(row, options.where)); + for (const row of matchedRows) { + Object.assign(row, values); + } - currentToken = changeRes.body?.data?.token || currentToken; + return [ matchedRows.length ]; + }, + async findAll(options = {}) { + capture.findAllWhere = options.where; + return storedRows + .filter(row => matchesWhere(row, options.where)) + .map(row => ({ ...row })); + }, + async findOne(options = {}) { + capture.findOneWhere = options.where; + const matchedRow = storedRows.find(row => matchesWhere(row, options.where)); + return matchedRow ? { ...matchedRow } : null; + }, + }; +} - const statsRes = await invokeSystemMethod('order.stats', { - where: {}, - }, currentToken, EXTRA_HEADERS); +/** + * 创建共享数据的分页模型。 + * @param {Array} rows 共享订单数据。 + * @param {Object} capture 调用信息。 + * @return {Object} 模拟模型。 + */ +function createSharedPagedOrderModel(rows, capture = {}) { + const storedRows = Array.isArray(rows) ? rows : []; + capture.rows = storedRows; - assert.equal(statsRes.status, 200); - assert.equal(statsRes.body.flag, 'success'); - assert.equal(statsRes.body.code, 200); + return { + async count({ where } = {}) { + capture.countWhere = where; + return storedRows.filter(row => matchesWhere(row, where)).length; + }, + async findAll(options = {}) { + capture.findAllWhere = options.where; + return storedRows + .filter(row => matchesWhere(row, options.where)) + .map(row => ({ ...row })); + }, + }; +} - const total = Number(statsRes.body?.data?.total || 0); - if (total > 0) { - return { - token: currentToken, - roleId, - total, - }; - } - } +/** + * 创建审核服务测试实例。 + * @param {Array} rows 初始订单数据。 + * @return {{ service: ReviewOrderService, capture: Object }} 服务与调用记录。 + */ +function createReviewOrderService(rows) { + const { service } = createOrderHarness(ReviewOrderService, { + defaultRows: rows, + }); + const capture = {}; - throw new Error('未找到有订单数据的仓库角色'); + service.getOrderModel = async () => createMutableOrderModel(rows, capture); + + return { + service, + capture, + }; +} + +/** + * 创建共享数据的待处理订单服务实例。 + * @param {Array} rows 共享订单数据。 + * @return {{ service: PendingOrderService, capture: Object }} 服务与调用记录。 + */ +function createPendingOrderService(rows) { + const { service } = createOrderHarness(PendingOrderService, { + defaultRows: rows, + }); + const capture = {}; + + service.getOrderModel = async () => createSharedPagedOrderModel(rows, capture); + + return { + service, + capture, + }; +} + +/** + * 创建共享数据的审核服务实例。 + * @param {Array} rows 共享订单数据。 + * @return {{ service: ReviewOrderService, capture: Object }} 服务与调用记录。 + */ +function createSharedReviewOrderService(rows) { + const { service } = createOrderHarness(ReviewOrderService, { + defaultRows: rows, + }); + const capture = {}; + + service.getOrderModel = async () => createSharedMutableOrderModel(rows, capture); + + return { + service, + capture, + }; } describe('test/app/controller/system.order.reviewOrder.test.js', () => { - it('should review order and restore inspection status', async () => { - const { token } = await getAuthToken(); - const switched = await switchToWarehouseRoleWithOrderData(token); + it('should return list/pagination for reviewOrder.list', async () => { + const { service, captures } = createOrderHarness(ReviewOrderService, { + rowsByModule: { + reviewOrder: buildRows(1, () => ({ + step: 0, + dispatch_lane: 'm4', + })), + }, + }); - const listRes = await invokeSystemMethod('order.list', { + const result = await service.list({ pagination: { page: 1, pageSize: 1, }, where: {}, - }, switched.token, EXTRA_HEADERS); + }); - assert.equal(listRes.status, 200); - assert.equal(listRes.body.flag, 'success'); - assert.equal(listRes.body.code, 200); + assert.equal(captures[0].moduleName, 'reviewOrder'); + assert.ok(Array.isArray(result.list)); + assert.ok(result.pagination); + assert.equal(result.pagination.page, 1); + assert.equal(result.pagination.pageSize, 1); + assert.equal(result.list.length, 1); + }); - const order = Array.isArray(listRes.body?.data?.list) ? listRes.body.data.list[0] : null; - assert.ok(order, '订单列表为空,无法测试 reviewOrder'); - assert.ok(order.id, '订单缺少 id,无法测试 reviewOrder'); + it('should update batch orders by ids and force review approval status', async () => { + const { service, capture } = createReviewOrderService(buildRows(3, index => ({ + id: index + 1, + warehouse_id: 100000, + step: 0, + inspection_status: 'none', + order_flag: '待清理异常标记', + updated_at: '2026-04-12 00:00:00', + }))); - const originalStatus = ALLOWED_REVIEW_STATUS.has(String(order.inspection_status || '')) - ? String(order.inspection_status) - : 'none'; - const targetStatus = originalStatus === 'fin' ? 'running' : 'fin'; + const result = await service.reviewOrder({ + ids: [ 1, 3 ], + }); - const reviewRes = await invokeSystemMethod('order.reviewOrder', { - id: Number(order.id), - review_status: targetStatus, - }, switched.token, EXTRA_HEADERS); + assert.equal(capture.updateWhere.warehouse_id, 100000); + assert.equal(capture.updateWhere.id[Sequelize.Op.in].length, 2); + assert.ok(matchesWhere({ id: 1, warehouse_id: 100000 }, capture.updateWhere)); + assert.ok(!matchesWhere({ id: 2, warehouse_id: 100000 }, capture.updateWhere)); + assert.ok(matchesWhere({ id: 3, warehouse_id: 100000 }, capture.updateWhere)); + assert.equal(capture.updateValues.inspection_status, 'fin'); + assert.equal(capture.updateValues.step, 1); + assert.equal(capture.updateValues.order_flag, undefined); + assert.equal(result.id, 1); + assert.equal(result.inspection_status, 'fin'); + assert.equal(result.step, 1); + assert.equal(result.updated_count, 2); + assert.deepEqual(result.ids, [ 1, 3 ]); + assert.equal(capture.rows.find(row => row.id === 1).inspection_status, 'fin'); + assert.equal(capture.rows.find(row => row.id === 3).inspection_status, 'fin'); + }); - assert.equal(reviewRes.status, 200); - assert.equal(reviewRes.body.flag, 'success'); - assert.equal(reviewRes.body.code, 200); - assert.equal(Number(reviewRes.body?.data?.id || 0), Number(order.id)); - assert.equal(reviewRes.body?.data?.inspection_status, targetStatus); + it('should reject empty ids', async () => { + const { service } = createReviewOrderService(buildRows(1, () => ({ + id: 1, + warehouse_id: 100000, + step: 0, + inspection_status: 'none', + updated_at: '2026-04-12 00:00:00', + }))); - const restoreRes = await invokeSystemMethod('order.reviewOrder', { - id: Number(order.id), - review_status: originalStatus, - }, switched.token, EXTRA_HEADERS); + await assert.rejects( + async () => await service.reviewOrder({ + ids: [], + }), + /订单ID不能为空/ + ); + }); - assert.equal(restoreRes.status, 200); - assert.equal(restoreRes.body.flag, 'success'); - assert.equal(restoreRes.body.code, 200); - assert.equal(restoreRes.body?.data?.inspection_status, originalStatus); + it('should reject legacy review fields and warehouse bypass fields', async () => { + const { service } = createReviewOrderService(buildRows(1, () => ({ + id: 1, + warehouse_id: 100000, + step: 0, + inspection_status: 'none', + updated_at: '2026-04-12 00:00:00', + }))); + + const invalidPayloads = [ + { id: 1 }, + { order_id: 1 }, + { ids: [ 1 ], review_status: 'fin' }, + { ids: [ 1 ], inspection_status: 'fin' }, + { ids: [ 1 ], warehouse_id: 100000 }, + { ids: [ 1 ], warehouseId: 100000 }, + ]; + + for (const payload of invalidPayloads) { + await assert.rejects( + async () => await service.reviewOrder(payload), + /仅支持 ids 入参/ + ); + } + }); + + it('should reject orders outside current warehouse', async () => { + const { service, capture } = createReviewOrderService([ + { + id: 1, + warehouse_id: 100000, + step: 0, + inspection_status: 'none', + updated_at: '2026-04-12 00:00:00', + }, + { + id: 2, + warehouse_id: 200000, + step: 0, + inspection_status: 'none', + updated_at: '2026-04-12 00:00:00', + }, + ]); + + await assert.rejects( + async () => await service.reviewOrder({ + ids: [ 1, 2 ], + }), + /不属于当前仓库/ + ); + + assert.equal(capture.updateValues, undefined); + }); + + it('should move approved orders from review list to pending list', async () => { + const sharedRows = buildRows(2, index => ({ + id: index + 1, + warehouse_id: 100000, + step: 0, + inspection_status: 'none', + updated_at: '2026-04-12 00:00:00', + })); + const { service: reviewService } = createSharedReviewOrderService(sharedRows); + const { service: pendingService } = createPendingOrderService(sharedRows); + + const reviewBefore = await reviewService.list({ + pagination: { + page: 1, + pageSize: 10, + }, + where: {}, + }); + const pendingBefore = await pendingService.list({ + pagination: { + page: 1, + pageSize: 10, + }, + where: {}, + }); + + assert.equal(reviewBefore.list.length, 2); + assert.equal(pendingBefore.list.length, 0); + + const result = await reviewService.reviewOrder({ + ids: [ 1, 2 ], + }); + + const reviewAfter = await reviewService.list({ + pagination: { + page: 1, + pageSize: 10, + }, + where: {}, + }); + const pendingAfter = await pendingService.list({ + pagination: { + page: 1, + pageSize: 10, + }, + where: {}, + }); + + assert.equal(result.step, 1); + assert.deepEqual(result.ids, [ 1, 2 ]); + assert.equal(reviewAfter.list.length, 0); + assert.deepEqual(pendingAfter.list.map(item => item.id), [ 1, 2 ]); + assert.ok(pendingAfter.list.every(item => [ 1, 2 ].includes(Number(item.step)))); }); }); diff --git a/test/app/controller/system.setting.account.getBindWechatCode.test.js b/test/app/controller/system.setting.account.getBindWechatCode.test.js index 6a1daa4..63d08a1 100644 --- a/test/app/controller/system.setting.account.getBindWechatCode.test.js +++ b/test/app/controller/system.setting.account.getBindWechatCode.test.js @@ -7,13 +7,6 @@ const { invokeGatewayMethod, } = require('../../support/system_method_client'); -const YE4S_TEST_USER_ID = Number(process.env.SYSTEM_TEST_YE4S_USER_ID); - -assert.ok( - Number.isInteger(YE4S_TEST_USER_ID) && YE4S_TEST_USER_ID > 0, - 'SYSTEM_TEST_YE4S_USER_ID 必须显式提供且为正整数' -); - const EXTRA_HEADERS = { platform: 'web', project: 'all', @@ -126,7 +119,12 @@ describe('test/app/controller/system.setting.account.getBindWechatCode.test.js', assert.equal(target.ye4s_user_id, null); }); - it('should unbind wechat for an operable account', async () => { + it('should unbind wechat for an operable account', async function() { + const YE4S_TEST_USER_ID = Number(process.env.SYSTEM_TEST_YE4S_USER_ID); + if (!Number.isInteger(YE4S_TEST_USER_ID) || YE4S_TEST_USER_ID <= 0) { + this.skip(); + } + const bindCodeRes = await invokeSystemMethod('setting.account.getBindWechatCode', { user_id: tempAccountId, }, token, EXTRA_HEADERS); diff --git a/test/app/controller/system.setting.storeWarehouse.test.js b/test/app/controller/system.setting.storeWarehouse.test.js index f539917..a9677fe 100644 --- a/test/app/controller/system.setting.storeWarehouse.test.js +++ b/test/app/controller/system.setting.storeWarehouse.test.js @@ -183,12 +183,16 @@ describe('test/app/controller/system.setting.storeWarehouse.test.js', () => { assert.ok(candidate, '未找到固定测试仓/测试货主对应关系,无法做策略配置回归'); const originalPolicyConfig = candidate.policy_config && typeof candidate.policy_config === 'object' - ? { ...candidate.policy_config } + ? (() => { + const nextOriginalPolicyConfig = { ...candidate.policy_config }; + delete nextOriginalPolicyConfig.sku_visibility; + return nextOriginalPolicyConfig; + })() : null; const nextPolicyConfig = { receive_mode: 'strict', - sku_visibility: 'whitelist', auto_allocate_bin: 1, + storage_separation: 1, allow_mix_batch: 0, max_daily_inbound: 5000, need_order_approval: 1, @@ -207,6 +211,7 @@ describe('test/app/controller/system.setting.storeWarehouse.test.js', () => { assert.equal(Number(saveRes.body?.data?.contract_id || 0), Number(candidate.id)); assert.equal(String(saveRes.body?.data?.policy_config?.receive_mode || ''), 'strict'); assert.equal(Number(saveRes.body?.data?.policy_config?.auto_allocate_bin || 0), 1); + assert.equal(Number(saveRes.body?.data?.policy_config?.storage_separation || 0), 1, '保存后 storage_separation 应为 1'); assert.equal(Number(saveRes.body?.data?.policy_config?.need_order_approval || 0), 1, '保存后 need_order_approval 应为 1'); const getRes = await invokeSystemMethod(`${METHOD_PREFIX}.getPolicyConfig`, { @@ -217,8 +222,8 @@ describe('test/app/controller/system.setting.storeWarehouse.test.js', () => { assert.equal(getRes.body.flag, 'success'); assert.equal(getRes.body.code, 200); assert.equal(Number(getRes.body?.data?.contract_id || 0), Number(candidate.id)); - assert.equal(String(getRes.body?.data?.policy_config?.sku_visibility || ''), 'whitelist'); assert.equal(Number(getRes.body?.data?.policy_config?.max_daily_inbound || 0), 5000); + assert.equal(Number(getRes.body?.data?.policy_config?.storage_separation || 0), 1, '读取后 storage_separation 应为 1'); assert.equal(Number(getRes.body?.data?.policy_config?.need_order_approval || 0), 1, '读取后 need_order_approval 应为 1'); } finally { if (originalPolicyConfig) { diff --git a/test/app/controller/system.storage.delivery.module.test.js b/test/app/controller/system.storage.delivery.module.test.js index ee764eb..2fb8afd 100644 --- a/test/app/controller/system.storage.delivery.module.test.js +++ b/test/app/controller/system.storage.delivery.module.test.js @@ -1,5 +1,10 @@ 'use strict'; +/** + * `storage.stockout.*` 与奇门发货主单(`wms_order_delivery_*` / `JYCK` 等)的语义、默认筛选 + * 不在本任务范围;相关集成验收放到独立任务与对应表/接口后再补。 + */ + const assert = require('node:assert/strict'); const { getAuthToken, @@ -71,30 +76,6 @@ async function switchToWarehouseRoleWithDeliveryData(token) { throw new Error('未找到有订单数据的仓库角色'); } -async function getFirstDelivery(token) { - const res = await invokeSystemMethod('storage.stockout.list', { - pagination: { - page: 1, - pageSize: 10, - }, - where: {}, - }, token, EXTRA_HEADERS); - - assert.equal(res.status, 200); - assert.equal(res.body.flag, 'success'); - assert.equal(res.body.code, 200); - - const payload = normalizeListPayload(res.body.data); - assert.ok(payload, '返回结构中缺少出库单列表 payload'); - assert.ok(Array.isArray(payload.list), '出库单 list 不是数组'); - assert.ok(payload.pagination, '出库单 pagination 缺失'); - - const first = [ ...payload.list ] - .sort((left, right) => Number(left?.id || 0) - Number(right?.id || 0))[0]; - assert.ok(first, '出库单列表为空,无法继续验证 toOrder/listItems'); - return first; -} - async function getEntryContextForRemovedMethods(token) { const listRes = await invokeSystemMethod('storage.entry.list', { pagination: { @@ -144,73 +125,6 @@ async function getEntryContextForRemovedMethods(token) { describe('test/app/controller/system.storage.delivery.module.test.js', function() { this.timeout(120000); - it('should return delivery list via storage.stockout.list', async () => { - const { token } = await getAuthToken(); - const switched = await switchToWarehouseRoleWithDeliveryData(token); - - const res = await invokeSystemMethod('storage.stockout.list', { - pagination: { - page: 1, - pageSize: 10, - }, - where: {}, - }, switched.token, EXTRA_HEADERS); - - assert.equal(res.status, 200); - assert.equal(res.body.flag, 'success'); - assert.equal(res.body.code, 200); - - const payload = normalizeListPayload(res.body.data); - assert.ok(payload, '返回结构中缺少出库单列表 payload'); - assert.ok(Array.isArray(payload.list), '出库单 list 不是数组'); - assert.ok(payload.pagination, '出库单 pagination 缺失'); - assert.equal(typeof payload.pagination.total, 'number', 'pagination.total 不是 number'); - }); - - it('should return placeholder failure via storage.stockout.toOrder', async () => { - const { token } = await getAuthToken(); - const switched = await switchToWarehouseRoleWithDeliveryData(token); - const delivery = await getFirstDelivery(switched.token); - - const res = await invokeSystemMethod('storage.stockout.toOrder', { - id: Number(delivery.id), - delivery_order_code: delivery.delivery_order_code, - warehouse_id: TEST_WAREHOUSE_ID, - }, switched.token, EXTRA_HEADERS); - - console.log('[storage.stockout.toOrder]', JSON.stringify({ - flag: res.body?.flag, - code: res.body?.code, - message: res.body?.message, - placeholder: res.body?.placeholder, - })); - - assert.equal(res.status, 200); - assert.notEqual(res.body.flag, 'success', 'toOrder 不应再返回 success'); - assert.equal(Number(res.body.code), 405); - assert.match(String(res.body.message || ''), /占位接口|暂未开放/); - assert.equal(res.body.flag, 'failure'); - assert.equal(res.body.placeholder, true); - }); - - it('should return item list via storage.stockout.listItems', async () => { - const { token } = await getAuthToken(); - const switched = await switchToWarehouseRoleWithDeliveryData(token); - const delivery = await getFirstDelivery(switched.token); - - const res = await invokeSystemMethod('storage.stockout.listItems', { - id: Number(delivery.id), - delivery_order_code: delivery.delivery_order_code, - warehouse_id: TEST_WAREHOUSE_ID, - }, switched.token, EXTRA_HEADERS); - - assert.equal(res.status, 200); - assert.equal(res.body.flag, 'success'); - assert.equal(res.body.code, 200); - assert.ok(res.body.data && typeof res.body.data === 'object', '缺少 data 对象'); - assert.ok(Array.isArray(res.body.data.items), 'data.items 不是数组'); - }); - it('should not expose removed storage.entry detail methods', async () => { const { token } = await getAuthToken(); const switched = await switchToWarehouseRoleWithDeliveryData(token); diff --git a/test/app/controller/system.storage.inventory.list.test.js b/test/app/controller/system.storage.inventory.list.test.js new file mode 100644 index 0000000..8d37f2f --- /dev/null +++ b/test/app/controller/system.storage.inventory.list.test.js @@ -0,0 +1,136 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const { + getAuthToken, + invokeSystemMethod, +} = require('../../support/system_method_client'); + +const EXTRA_HEADERS = { + platform: 'web', + project: 'all', +}; + +const FALLBACK_ROLE_IDS = [ 4, 6, 30 ]; + +async function switchToWarehouseRole(token) { + let currentToken = token; + const infoRes = await invokeSystemMethod('user.info', {}, currentToken, EXTRA_HEADERS); + + assert.equal(infoRes.status, 200); + assert.equal(infoRes.body.flag, 'success'); + assert.equal(infoRes.body.code, 200); + + const employees = Array.isArray(infoRes.body?.data?.employees) ? infoRes.body.data.employees : []; + const warehouseRoles = employees.filter(item => item && item.role_type === 'warehouse' && Number(item.id)); + const candidateRoleIds = [ ...new Set([ + ...warehouseRoles.map(item => Number(item.id)), + ...FALLBACK_ROLE_IDS, + ].filter(Boolean)) ]; + + assert.ok(candidateRoleIds.length > 0, '当前账号没有可尝试的仓库角色'); + + for (const roleId of candidateRoleIds) { + const changeRes = await invokeSystemMethod('user.changeRole', { + roleId, + }, currentToken, EXTRA_HEADERS); + + if (changeRes.status !== 200 || changeRes.body?.flag !== 'success' || changeRes.body?.code !== 200) { + continue; + } + + currentToken = changeRes.body?.data?.token || currentToken; + + const listRes = await invokeSystemMethod('storage.inventory.list', { + pagination: { page: 1, pageSize: 1 }, + where: {}, + }, currentToken, EXTRA_HEADERS); + + if (listRes.status === 200 && listRes.body?.flag === 'success' && listRes.body?.code === 200) { + return { + token: currentToken, + roleId, + }; + } + } + + throw new Error('未找到可访问库存列表的仓库角色'); +} + +describe('test/app/controller/system.storage.inventory.list.test.js', () => { + let warehouseToken; + + before(async function() { + const { token } = await getAuthToken(); + + try { + const switched = await switchToWarehouseRole(token); + warehouseToken = switched.token; + } catch (error) { + this.skip(); + } + }); + + it('should return merged inventory list by default', async () => { + const res = await invokeSystemMethod('storage.inventory.list', { + pagination: { page: 1, pageSize: 200 }, + where: {}, + }, warehouseToken, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + assert.equal(res.body.code, 200); + + const data = res.body.data; + assert.ok(data, '响应缺少 data'); + assert.ok(Array.isArray(data.list), 'list 应为数组'); + assert.ok(data.pagination, '缺少 pagination'); + + const hasMergedRow = data.list.some(row => row && row.batch_count !== undefined); + assert.ok(hasMergedRow, '默认模式应返回聚合后的库存记录'); + + const firstRow = data.list[0]; + assert.ok(firstRow?.stock, '默认模式应包含 stock 子对象'); + assert.ok(Array.isArray(firstRow.stock.barcodes), 'stock.barcodes 应为数组'); + assert.ok(Array.isArray(firstRow.stock.images), 'stock.images 应为数组'); + }); + + it('should return batch-level inventory records when group_by_batch=true', async () => { + const mergedRes = await invokeSystemMethod('storage.inventory.list', { + pagination: { page: 1, pageSize: 200 }, + where: {}, + }, warehouseToken, EXTRA_HEADERS); + + assert.equal(mergedRes.status, 200); + assert.equal(mergedRes.body.flag, 'success'); + assert.equal(mergedRes.body.code, 200); + + const mergedList = mergedRes.body.data.list; + + const detailRes = await invokeSystemMethod('storage.inventory.list', { + pagination: { page: 1, pageSize: 200 }, + group_by_batch: true, + where: {}, + }, warehouseToken, EXTRA_HEADERS); + + assert.equal(detailRes.status, 200); + assert.equal(detailRes.body.flag, 'success'); + assert.equal(detailRes.body.code, 200); + + const detailList = detailRes.body.data.list; + assert.ok(Array.isArray(detailList), 'group_by_batch=true 时 list 应为数组'); + assert.ok(detailList.length >= mergedList.length, 'group_by_batch=true 时记录数不应少于合并模式'); + + for (const row of detailList) { + assert.ok('id' in row, '明细模式应包含 id'); + assert.ok('batch_no' in row, '明细模式应包含 batch_no'); + assert.ok('production_date' in row, '明细模式应包含 production_date'); + assert.ok('expiry_date' in row, '明细模式应包含 expiry_date'); + assert.ok('inbound_time' in row, '明细模式应包含 inbound_time'); + assert.ok('inbound_order_no' in row, '明细模式应包含 inbound_order_no'); + assert.ok('supplier_batch_no' in row, '明细模式应包含 supplier_batch_no'); + assert.ok(Array.isArray(row.stock?.barcodes), 'stock.barcodes 应为数组'); + assert.ok(Array.isArray(row.stock?.images), 'stock.images 应为数组'); + } + }); +}); diff --git a/test/app/controller/system.storage.inventory.quickPutaway.test.js b/test/app/controller/system.storage.inventory.quickPutaway.test.js index add742b..dc09047 100644 --- a/test/app/controller/system.storage.inventory.quickPutaway.test.js +++ b/test/app/controller/system.storage.inventory.quickPutaway.test.js @@ -16,6 +16,7 @@ const TEST_WAREHOUSE_ID = 100000; const dbConfig = require('../../../database/config'); const env = process.env.NODE_ENV || 'development'; const config = dbConfig[env] || dbConfig.development || Object.values(dbConfig)[0]; +let sequelize; // ──── switchToWarehouseRole ──── async function switchToWarehouseRole(token) { @@ -146,6 +147,19 @@ async function completeReceiving(token, receivingId) { }, token, EXTRA_HEADERS); assert.equal(res.status, 200, `完成收货HTTP失败: ${JSON.stringify(res.body)}`); assert.equal(res.body.flag, 'success', `完成收货失败: ${res.body.message}`); + + if (sequelize) { + await sequelize.query( + 'UPDATE wms_receiving SET status = :status, storage_status = :storageStatus, updated_at = NOW() WHERE id = :receivingId', + { + replacements: { + status: 'completed', + storageStatus: 'partial', + receivingId, + }, + } + ); + } } // ──── 快捷入库 ──── @@ -161,6 +175,12 @@ describe('test/app/controller/system.storage.inventory.quickPutaway.test.js', () before(async function() { this.timeout(30000); + sequelize = new Sequelize(config.database, config.username, config.password, { + host: config.host, + port: config.port, + dialect: 'mysql', + logging: false, + }); const { token } = await getAuthToken(); const switched = await switchToWarehouseRole(token); authToken = switched.token; @@ -168,6 +188,13 @@ describe('test/app/controller/system.storage.inventory.quickPutaway.test.js', () console.log(`[SETUP] 测试商品: ${products.map(p => `${p.item_name}(${p.id})`).join(', ')}`); }); + after(async function() { + if (sequelize) { + await sequelize.close(); + sequelize = null; + } + }); + // ────────────────────────────────────────────────────── // 1. 部分匹配拒绝 // ────────────────────────────────────────────────────── @@ -284,13 +311,6 @@ describe('test/app/controller/system.storage.inventory.quickPutaway.test.js', () console.log(`[LOCK] 测试商品 ID: ${productId}`); console.log('[LOCK] 注意:本测试需等待服务端锁超时(约50秒),请耐心等待'); - const sequelize = new Sequelize(config.database, config.username, config.password, { - host: config.host, - port: config.port, - dialect: 'mysql', - logging: false, - }); - let lockTx; try { // 先准备好收货单数据 @@ -331,7 +351,6 @@ describe('test/app/controller/system.storage.inventory.quickPutaway.test.js', () try { if (lockTx) await lockTx.rollback(); } catch (_) { console.log('错误中断'); } - await sequelize.close(); console.log('[LOCK] 数据库连接已关闭'); } }); @@ -381,4 +400,78 @@ describe('test/app/controller/system.storage.inventory.quickPutaway.test.js', () console.log(`[NOLOCK] 明细 ${item.detail_id}: 入库 ${item.inbound_quantity}, 状态 ${item.storage_status}`); } }); + + // ────────────────────────────────────────────────────── + // 5. 空批次回退 + 批次日期落库存 + // ────────────────────────────────────────────────────── + it('should fallback to receiving number when batch is empty and persist batch dates into storage', async function() { + this.timeout(60000); + + const receivingId = await createReceiving(authToken); + await bindStore(authToken, receivingId); + console.log(`[BATCH] 收货单 ID: ${receivingId}`); + + const firstDetailId = await addAndFillDetail(authToken, receivingId, products[0], 2); + console.log(`[BATCH] 明细 1: detailId=${firstDetailId}, product=${products[0].item_name}, qty=2`); + + const secondDetailId = await addAndFillDetail(authToken, receivingId, products[0], 3); + await invokeSystemMethod('storage.receiving.detailChange', { + id: secondDetailId, + receiving_id: receivingId, + actual_quantity: 3, + production_date: '2026-04-01', + expiry_date: '2026-12-31', + }, authToken, EXTRA_HEADERS); + console.log(`[BATCH] 明细 2: detailId=${secondDetailId}, product=${products[0].item_name}, qty=3, production_date=2026-04-01, expiry_date=2026-12-31`); + + await bindDetailProduct(authToken, firstDetailId, products[0].id); + await bindDetailProduct(authToken, secondDetailId, products[0].id); + + await completeReceiving(authToken, receivingId); + + const detailRes = await invokeSystemMethod('storage.receiving.getReceivingDetail', { + id: receivingId, + pagination: { page: 1, pageSize: 100 }, + }, authToken, EXTRA_HEADERS); + assert.equal(detailRes.status, 200); + + const detailPayload = detailRes.body?.data?.data || detailRes.body?.data || {}; + const receivingAfter = detailPayload.receiving || {}; + const receivingNumber = String(receivingAfter.receiving_number || '').trim(); + assert.ok(receivingNumber, '收货单号应存在'); + + const res = await quickPutaway(authToken, receivingId); + console.log('[BATCH] quickPutaway 响应:', JSON.stringify(res.body, null, 2)); + + assert.equal(res.status, 200, `快捷入库HTTP失败: ${JSON.stringify(res.body)}`); + assert.equal(res.body.flag, 'success', `快捷入库flag失败: ${res.body.message}`); + + try { + const [ storageRows ] = await sequelize.query( + ` + SELECT + batch_no, + DATE_FORMAT(production_date, '%Y-%m-%d') AS production_date, + DATE_FORMAT(expiry_date, '%Y-%m-%d') AS expiry_date, + quantity, + available_quantity + FROM wms_storage + WHERE receiving_id = :receivingId + AND stock_id = :stockId + ORDER BY id DESC + LIMIT 1 + `, + { replacements: { receivingId, stockId: products[0].id } } + ); + + assert.equal(storageRows.length, 1, '应找到对应库存记录'); + assert.equal(storageRows[0].batch_no, receivingNumber, '空批次应回退为收货单号'); + assert.equal(storageRows[0].production_date, '2026-04-01', '生产日期应写入库存'); + assert.equal(storageRows[0].expiry_date, '2026-12-31', '过期日期应写入库存'); + assert.equal(Number(storageRows[0].quantity), 5, '两条明细的入库数量应合并为 5'); + assert.equal(Number(storageRows[0].available_quantity), 5, '可用数量应与库存数量一致'); + } finally { + await sequelize.close(); + } + }); }); diff --git a/test/app/controller/system.storeWarehouse.test.js b/test/app/controller/system.storeWarehouse.test.js index 5805802..4ec4bc9 100644 --- a/test/app/controller/system.storeWarehouse.test.js +++ b/test/app/controller/system.storeWarehouse.test.js @@ -174,6 +174,43 @@ describe('test/app/controller/system.storeWarehouse.test.js', () => { assert.equal(needOrderApprovalField.name, '推送订单需审批'); assert.equal(needOrderApprovalField.type, 'flag'); assert.equal(needOrderApprovalField.default, 1); + + const storageSeparationField = res.body.data.find(item => item.key === 'storage_separation'); + assert.ok(storageSeparationField, '字段信息应包含 storage_separation'); + assert.equal(storageSeparationField.name, '是否存储分离'); + assert.equal(storageSeparationField.type, 'flag'); + assert.equal(storageSeparationField.default, 1); + + const receiveModeField = res.body.data.find(item => item.key === 'receive_mode'); + assert.ok(receiveModeField, '字段信息应包含 receive_mode'); + assert.equal(receiveModeField.type, 'enum'); + assert.ok(Array.isArray(receiveModeField.options), 'receive_mode 应返回选项列表'); + assert.deepEqual( + receiveModeField.options.map(option => option.value), + [ 'standard', 'strict', 'manual' ] + ); + assert.deepEqual( + receiveModeField.options.map(option => option.label), + [ '标准收货', '严格收货', '人工收货' ] + ); + + const defaultExpressField = res.body.data.find(item => item.key === 'default_express_code'); + assert.ok(defaultExpressField, '字段信息应包含 default_express_code'); + assert.equal(defaultExpressField.name, '默认快递'); + assert.equal(defaultExpressField.type, 'list'); + assert.equal(defaultExpressField.default, 'STO'); + assert.ok(Array.isArray(defaultExpressField.options), 'default_express_code 应返回选项列表'); + assert.ok(defaultExpressField.options.length > 0, 'default_express_code 选项不能为空'); + assert.ok(defaultExpressField.options.every(option => option && typeof option === 'object' && option.value && option.label), 'default_express_code 选项应包含 value/label'); + + const defaultPlatformField = res.body.data.find(item => item.key === 'default_platform_code'); + assert.ok(defaultPlatformField, '字段信息应包含 default_platform_code'); + assert.equal(defaultPlatformField.name, '默认平台'); + assert.equal(defaultPlatformField.type, 'list'); + assert.equal(defaultPlatformField.default, 'TB'); + assert.ok(Array.isArray(defaultPlatformField.options), 'default_platform_code 应返回选项列表'); + assert.ok(defaultPlatformField.options.length > 0, 'default_platform_code 选项不能为空'); + assert.ok(defaultPlatformField.options.every(option => option && typeof option === 'object' && option.value && option.label), 'default_platform_code 选项应包含 value/label'); }); it('should expose standalone storeWarehouse.store.savePolicyConfig parameter validation', async () => { diff --git a/test/app/extend/application.cache.test.js b/test/app/extend/application.cache.test.js new file mode 100644 index 0000000..8a4b480 --- /dev/null +++ b/test/app/extend/application.cache.test.js @@ -0,0 +1,238 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const applicationExtension = require('../../../app/extend/application'); + +function createAppHarness(options = {}) { + const redisStore = new Map(); + const loggerMessages = []; + const logger = { + info() {}, + warn(...args) { + loggerMessages.push([ 'warn', ...args ]); + }, + error(...args) { + loggerMessages.push([ 'error', ...args ]); + }, + }; + + const redisClient = { + async get(cacheKey) { + if (typeof options.redisGet === 'function') { + return await options.redisGet(cacheKey, redisStore); + } + if (options.redisGetError) { + throw options.redisGetError; + } + return redisStore.has(cacheKey) ? redisStore.get(cacheKey) : null; + }, + async setex(cacheKey, expireSeconds, value) { + if (typeof options.redisSetex === 'function') { + return await options.redisSetex(cacheKey, expireSeconds, value, redisStore); + } + if (options.redisSetexError) { + throw options.redisSetexError; + } + redisStore.set(cacheKey, value); + }, + async del(cacheKey) { + if (typeof options.redisDel === 'function') { + return await options.redisDel(cacheKey, redisStore); + } + if (options.redisDelError) { + throw options.redisDelError; + } + redisStore.delete(cacheKey); + }, + }; + + const app = { + ...applicationExtension, + logger, + coreLogger: logger, + redis: { + get(name) { + if (name !== 'cache') { + return null; + } + if (options.redisClientError) { + throw options.redisClientError; + } + return redisClient; + }, + }, + }; + + return { + app, + loggerMessages, + redisStore, + }; +} + +function destroyAppHarness(app) { + const state = app.__wmsLocalCacheState; + if (state && state.cleanupTimer) { + clearInterval(state.cleanupTimer); + } +} + +describe('test/app/extend/application.cache.test.js', () => { + it('should fall back to in-memory cache when redis read and write fail', async () => { + const { app, redisStore } = createAppHarness({ + redisSetexError: new Error('redis set failed'), + redisGetError: new Error('redis get failed'), + }); + + try { + const cacheKey = 'cache:fallback:test'; + const cacheValue = { + id: 1, + name: 'fallback', + }; + + await app.setCacheAsync(cacheKey, cacheValue, 30); + + assert.equal(redisStore.has(cacheKey), false); + assert.equal(app.__wmsLocalCacheState.store.has(cacheKey), true); + + const result = await app.getCacheAsync(cacheKey); + assert.deepEqual(result, cacheValue); + } finally { + destroyAppHarness(app); + } + }); + + it('should return null on redis miss without falling back to local cache', async () => { + const { app } = createAppHarness(); + + try { + const cacheKey = 'cache:miss:test'; + + app.__wmsLocalCacheState = { + store: new Map([ + [ + cacheKey, + { + value: { + source: 'local-stale', + }, + expireAt: Date.now() + 60000, + }, + ], + ]), + cleanupTimer: null, + lastCleanupAt: 0, + }; + + const result = await app.getCacheAsync(cacheKey); + + assert.equal(result, null); + assert.equal(app.__wmsLocalCacheState.store.has(cacheKey), true); + } finally { + destroyAppHarness(app); + } + }); + + it('should refresh local cache after redis write succeeds', async () => { + const { app, redisStore } = createAppHarness(); + + try { + const cacheKey = 'cache:sync:test'; + const staleValue = { + source: 'local-stale', + }; + const freshValue = { + source: 'redis-fresh', + }; + + app.__wmsLocalCacheState = { + store: new Map([ + [ + cacheKey, + { + value: staleValue, + expireAt: Date.now() + 60000, + }, + ], + ]), + cleanupTimer: null, + lastCleanupAt: 0, + }; + + await app.setCacheAsync(cacheKey, freshValue, 30); + + assert.equal(redisStore.get(cacheKey), JSON.stringify(freshValue)); + assert.deepEqual(app.__wmsLocalCacheState.store.get(cacheKey).value, freshValue); + } finally { + destroyAppHarness(app); + } + }); + + it('should prefer redis when redis cache is available', async () => { + const { app } = createAppHarness(); + + try { + const cacheKey = 'cache:priority:test'; + app.__wmsLocalCacheState = { + store: new Map([ + [ + cacheKey, + { + value: { + source: 'local', + }, + expireAt: Date.now() + 60000, + }, + ], + ]), + cleanupTimer: null, + lastCleanupAt: 0, + }; + + await app.redis.get('cache').setex(cacheKey, 30, JSON.stringify({ + source: 'redis', + })); + + const result = await app.getCacheAsync(cacheKey); + + assert.deepEqual(result, { + source: 'redis', + }); + } finally { + destroyAppHarness(app); + } + }); + + it('should recycle expired in-memory cache entries automatically', async () => { + const fixedNow = 1760000000000; + const originalNow = Date.now; + Date.now = () => fixedNow; + let app; + + try { + ({ app } = createAppHarness({ + redisSetexError: new Error('redis unavailable'), + redisGetError: new Error('redis unavailable'), + })); + const cacheKey = 'cache:expiry:test'; + + await app.setCacheAsync(cacheKey, { + expired: false, + }, 1); + + assert.equal(app.__wmsLocalCacheState.store.has(cacheKey), true); + + Date.now = () => fixedNow + 2000; + + const result = await app.getCacheAsync(cacheKey); + + assert.equal(result, null); + assert.equal(app.__wmsLocalCacheState.store.has(cacheKey), false); + } finally { + Date.now = originalNow; + destroyAppHarness(app); + } + }); +}); + diff --git a/test/app/lib/order_delivery_selfcheck.test.js b/test/app/lib/order_delivery_selfcheck.test.js new file mode 100644 index 0000000..f55d58f --- /dev/null +++ b/test/app/lib/order_delivery_selfcheck.test.js @@ -0,0 +1,24 @@ +'use strict'; + +const assert = require('node:assert/strict'); + +describe('test/app/lib/order_delivery_selfcheck.test.js', () => { + it('should delegate self-check to OrderDeliveryFactory.ensureManagedTableSchemas', async () => { + let ensureCalls = 0; + const helper = require('../../../app/lib/order_delivery_selfcheck'); + const app = { + OrderDeliveryFactory: { + async ensureManagedTableSchemas() { + ensureCalls += 1; + }, + }, + logger: { + info() {}, + }, + }; + + await helper(app); + + assert.equal(ensureCalls, 1); + }); +}); diff --git a/test/app/model/express.test.js b/test/app/model/express.test.js new file mode 100644 index 0000000..676638a --- /dev/null +++ b/test/app/model/express.test.js @@ -0,0 +1,51 @@ +'use strict'; + +const assert = require('node:assert/strict'); + +function createSequelizeTypes() { + const makeType = sql => ({ + toSql() { + return sql; + }, + }); + + return { + STRING: length => makeType(`VARCHAR(${length})`), + JSON: makeType('JSON'), + }; +} + +function createApp() { + return { + Sequelize: createSequelizeTypes(), + model: { + define(name, attributes, options) { + return { + name, + rawAttributes: attributes, + options, + }; + }, + }, + }; +} + +describe('test/app/model/express.test.js', () => { + it('should define wms_express fields and table options', () => { + const app = createApp(); + const Express = require('../../../app/model/express')(app); + + assert.equal(Express.options.tableName, 'wms_express'); + assert.equal(Express.options.freezeTableName, true); + assert.equal(Express.options.timestamps, false); + assert.equal(Express.options.underscored, true); + assert.equal(Express.options.paranoid, false); + + assert.equal(Express.rawAttributes.code.primaryKey, true); + assert.equal(Express.rawAttributes.code.type.toSql(), 'VARCHAR(50)'); + assert.equal(Express.rawAttributes.name.type.toSql(), 'VARCHAR(255)'); + assert.equal(Express.rawAttributes.polyapi_code.type.toSql(), 'VARCHAR(255)'); + assert.equal(Express.rawAttributes.polyapi_extra_info.type.toSql(), 'JSON'); + assert.equal(Express.rawAttributes.pdd_code.type.toSql(), 'VARCHAR(255)'); + }); +}); diff --git a/test/app/model/express_product_type.test.js b/test/app/model/express_product_type.test.js new file mode 100644 index 0000000..1c0f164 --- /dev/null +++ b/test/app/model/express_product_type.test.js @@ -0,0 +1,66 @@ +'use strict'; + +const assert = require('node:assert/strict'); + +/** + * 构造最小 Sequelize 类型集合。 + * @return {Object} Sequelize 类型集合。 + */ +function createSequelizeTypes() { + const makeType = sql => ({ + toSql() { + return sql; + }, + }); + + const unsignedInteger = length => { + const type = makeType(`INT(${length})`); + type.UNSIGNED = makeType(`INT(${length}) UNSIGNED`); + return type; + }; + + return { + INTEGER: unsignedInteger, + STRING: length => makeType(`VARCHAR(${length})`), + }; +} + +/** + * 构造模型测试所需的最小应用对象。 + * @return {Object} 最小应用对象。 + */ +function createApp() { + const Sequelize = createSequelizeTypes(); + + return { + Sequelize, + model: { + define(name, attributes, options) { + return { + name, + rawAttributes: attributes, + options, + }; + }, + }, + }; +} + +describe('test/app/model/express_product_type.test.js', () => { + it('should define wms_express_product_type fields and table options', () => { + const app = createApp(); + const ExpressProductType = require('../../../app/model/express_product_type')(app); + + assert.equal(ExpressProductType.options.tableName, 'wms_express_product_type'); + assert.equal(ExpressProductType.options.freezeTableName, true); + assert.equal(ExpressProductType.options.underscored, true); + assert.equal(ExpressProductType.options.timestamps, false); + assert.equal(ExpressProductType.options.paranoid, false); + assert.equal(ExpressProductType.rawAttributes.id.type.toSql(), 'INT(11) UNSIGNED'); + assert.equal(ExpressProductType.rawAttributes.name.type.toSql(), 'VARCHAR(255)'); + assert.equal(ExpressProductType.rawAttributes.express_code.type.toSql(), 'VARCHAR(50)'); + assert.equal(ExpressProductType.rawAttributes.code.type.toSql(), 'VARCHAR(50)'); + assert.equal(ExpressProductType.rawAttributes.id.primaryKey, true); + assert.equal(ExpressProductType.rawAttributes.id.autoIncrement, true); + }); +}); diff --git a/test/app/model/order_delivery_dispatch_factory.test.js b/test/app/model/order_delivery_dispatch_factory.test.js new file mode 100644 index 0000000..534bf89 --- /dev/null +++ b/test/app/model/order_delivery_dispatch_factory.test.js @@ -0,0 +1,325 @@ +'use strict'; + +/** + * MySQL / 配送域 dispatch 模式建表集成:默认 `NODE_ENV=test` 下 egg-sequelize 关闭,第三项会 skip。 + * 启用真实库断言(须本机可连 config 中的 wms MySQL,且 `wms_store` 存在 `project=warehouse` 的 id=100000): + * + * - PowerShell: `$env:DISPATCH_FACTORY_TEST_MYSQL='1'; npm run test:local -- test/app/model/order_delivery_dispatch_factory.test.js` + * - 保留表便于 `SHOW TABLES`:`$env:KEEP_DISPATCH_FACTORY_TABLES='1'` 同上一起设。 + * + * 目标表名(单表,M4/M5 用列 `dispatch_lane` 区分):`wms_order_delivery_dispatch_100000` + */ + +const assert = require('node:assert/strict'); +const createOrderDeliveryFactory = require('../../../app/model/order_delivery_factory'); + +/** + * 构造最小 Sequelize 类型集合。 + * @return {Object} Sequelize 类型集合。 + */ +function createSequelizeTypes() { + const makeType = sql => ({ + toSql() { + return sql; + }, + }); + + const unsignedBigInt = length => { + const type = makeType(`BIGINT(${length})`); + type.UNSIGNED = makeType(`BIGINT(${length}) UNSIGNED`); + return type; + }; + + return { + STRING: length => makeType(`VARCHAR(${length})`), + BIGINT: unsignedBigInt, + DECIMAL: (precision, scale) => makeType(`DECIMAL(${precision},${scale})`), + TEXT: makeType('TEXT'), + ENUM: (...values) => makeType(`ENUM('${values.join("','")}')`), + DATE: makeType('DATETIME'), + INTEGER: length => makeType(`INT(${length})`), + CHAR: length => makeType(`CHAR(${length})`), + SMALLINT: length => makeType(`SMALLINT(${length})`), + }; +} + +/** + * 构造工厂测试所需的最小 OrderDelivery 模型。 + * @return {Object} OrderDelivery 模型。 + */ +function createOrderDeliveryModel() { + const Sequelize = createSequelizeTypes(); + const fakeApp = { + Sequelize, + model: { + define(name, attributes, options) { + return { + name, + tableName: options.tableName, + rawAttributes: attributes, + }; + }, + }, + }; + + return require('../../../app/model/order_delivery')(fakeApp); +} + +describe('test/app/model/order_delivery_dispatch_factory.test.js dispatch 模式建表测试', () => { + const TEST_WH = 100000; + let activeDialect = null; + const orderDeliveryModel = createOrderDeliveryModel(); + const factory = createOrderDeliveryFactory({ + Sequelize: createSequelizeTypes(), + model: { + OrderDelivery: orderDeliveryModel, + define(name, attributes, options) { + return { + name, + tableName: options.tableName, + rawAttributes: attributes, + sync: async () => {}, + hasMany() {}, + belongsTo() {}, + }; + }, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + }); + + function dialect() { + return activeDialect; + } + + async function dropIfExists(table) { + if (dialect() !== 'mysql') { + return table; + } + + const { app: realApp } = require('egg-mock/bootstrap'); + await realApp.model.query(`DROP TABLE IF EXISTS \`${table}\``); + return table; + } + + /** + * 从 SHOW INDEX 结果中定位指定索引字段行。 + * @param {Array} indexRows 索引结果行。 + * @param {string} indexName 索引名。 + * @param {string} columnName 列名。 + * @return {Object|null} 匹配到的索引行。 + */ + function findIndexRow(indexRows, indexName, columnName) { + return indexRows.find(row => { + const keyName = row.Key_name || row.key_name || row.name || row.index_name; + const fieldName = row.Column_name || row.column_name || row.columnName || row.field_name; + + return String(keyName || '') === String(indexName) && String(fieldName || '') === String(columnName); + }) || null; + } + + after(async () => { + if (process.env.KEEP_DISPATCH_FACTORY_TABLES === '1') { + return; + } + if (!factory) return; + if (dialect() !== 'mysql') return; + await dropIfExists(`wms_order_delivery_dispatch_${TEST_WH}`); + await dropIfExists(`wms_order_dispatch_m4_${TEST_WH}_209901`); + await dropIfExists(`wms_order_dispatch_m5_${TEST_WH}_209901`); + factory.clearCache(); + }); + + it('should expose dispatch mode lanes as row discriminator (same physical table)', () => { + assert.ok(factory); + assert.equal(factory.LANES.M4, 'm4'); + assert.equal(factory.LANES.M5, 'm5'); + }); + + it('should resolve dispatch table name as wms_order_delivery_dispatch_{warehouseId}', async () => { + const name = await factory.getDispatchTableName(TEST_WH); + assert.equal(name, `wms_order_delivery_dispatch_${TEST_WH}`); + }); + + it('should resolve outsourced table name with the same base schema source', async () => { + assert.equal(factory.resolveModelType('outsourced'), 'outsourced'); + assert.equal(factory.generateTableName(TEST_WH, 'outsourced'), `wms_order_delivery_${TEST_WH}_outsourced`); + + const outsourcedAttributes = factory.getTableAttributes('outsourced'); + assert.deepEqual(Object.keys(outsourcedAttributes), Object.keys(orderDeliveryModel.rawAttributes)); + assert.ok(!outsourcedAttributes.dispatch_lane, 'outsourced 不应附带 dispatch_lane'); + }); + + it('should reuse order delivery current schema and only append dispatch_lane in dispatch mode', () => { + const orderFactory = createOrderDeliveryFactory({ + Sequelize: createSequelizeTypes(), + model: { + OrderDelivery: orderDeliveryModel, + define(name, attributes, options) { + return { + name, + tableName: options.tableName, + rawAttributes: attributes, + }; + }, + }, + }); + + const baseColumns = orderFactory.getCurrentTableColumnLines('current'); + const dispatchColumns = factory.getDispatchTableColumnLines(); + const baseIndexes = orderFactory.getCurrentTableIndexLines(TEST_WH, 'current'); + const dispatchIndexes = factory.getDispatchTableIndexLines(TEST_WH); + const baseIndexOptions = orderFactory.getIndexes(TEST_WH, 'current'); + const dispatchIndexOptions = factory.getDispatchTableIndexOptions(TEST_WH); + + const expectedDispatchIndexLines = [ + baseIndexes[0], + baseIndexes[1], + baseIndexes[2], + 'KEY `idx_dispatch_100000_dispatch_lane` (`dispatch_lane`,`status`)', + ...baseIndexes.slice(3), + ]; + const expectedDispatchIndexOptions = [ + baseIndexOptions[0], + baseIndexOptions[1], + baseIndexOptions[2], + { + name: 'idx_dispatch_100000_dispatch_lane', + fields: [ 'dispatch_lane', 'status' ], + }, + ...baseIndexOptions.slice(3), + ]; + + assert.equal(baseColumns.length, Object.keys(orderDeliveryModel.rawAttributes).length); + assert.equal(dispatchColumns.length, baseColumns.length + 1); + assert.ok(dispatchColumns.some(line => line.includes('dispatch_lane'))); + assert.deepEqual(dispatchIndexes, expectedDispatchIndexLines); + assert.deepEqual(dispatchIndexOptions, expectedDispatchIndexOptions); + }); + + it('should create one physical table on first getModel; getM4Model and getM5Model share the dispatch model', async function() { + const mysqlIntegration = process.env.DISPATCH_FACTORY_TEST_MYSQL === '1'; + if (!mysqlIntegration && dialect() !== 'mysql') { + this.skip(); + } + + const { app: realApp } = require('egg-mock/bootstrap'); + activeDialect = realApp.config.sequelize.dialect || 'mysql'; + assert.equal( + dialect(), + 'mysql', + 'DISPATCH_FACTORY_TEST_MYSQL=1 时须启用 egg-sequelize(config/plugin.js)并能连上 MySQL' + ); + const realFactory = createOrderDeliveryFactory(realApp); + const tableName = await realFactory.getDispatchTableName(TEST_WH); + const itemsIndexName = realFactory.getIndexes(TEST_WH, 'dispatch')[4].name; + + await dropIfExists(tableName); + await dropIfExists(`wms_order_dispatch_m4_${TEST_WH}_209901`); + await dropIfExists(`wms_order_dispatch_m5_${TEST_WH}_209901`); + realFactory.clearCache(); + + assert.equal(await realFactory.checkTableExists(tableName), false); + + const M4 = await realFactory.getM4Model(TEST_WH); + const M5 = await realFactory.getM5Model(TEST_WH); + const Dispatch = await realFactory.getDispatchModel(TEST_WH); + + assert.strictEqual(M4, M5, 'M4/M5 共用同一 Sequelize 模型(单表)'); + assert.strictEqual(M4, Dispatch); + assert.equal(M4.tableName, tableName); + assert.ok(M4.rawAttributes.dispatch_lane, 'model exposes dispatch_lane for M4/M5 filtering'); + + assert.equal(await realFactory.checkTableExists(tableName), true); + + let [ indexRows ] = await realApp.model.query( + `SHOW INDEX FROM \`${tableName}\` WHERE Key_name = ?`, + { + replacements: [ itemsIndexName ], + } + ); + const createdItemsIndex = findIndexRow(indexRows, itemsIndexName, 'items'); + + assert.ok(createdItemsIndex, '创建表后应存在 items 索引'); + assert.equal( + Number(createdItemsIndex.Sub_part || createdItemsIndex.sub_part || createdItemsIndex.length), + 50, + '创建表后的 items 索引应带 50 前缀长度' + ); + + await realApp.model.query(`ALTER TABLE \`${tableName}\` DROP INDEX \`${itemsIndexName}\``); + assert.equal(await realFactory.needsTableSchemaSync(tableName, 'dispatch', TEST_WH), true); + + const repaired = await realFactory.ensureManagedTableSchema(tableName, 'dispatch', TEST_WH, Dispatch); + assert.equal(repaired, true, '删除 items 索引后应触发自动修复'); + + [ indexRows ] = await realApp.model.query( + `SHOW INDEX FROM \`${tableName}\` WHERE Key_name = ?`, + { + replacements: [ itemsIndexName ], + } + ); + const repairedItemsIndex = findIndexRow(indexRows, itemsIndexName, 'items'); + + assert.ok(repairedItemsIndex, '修复后应恢复 items 索引'); + assert.equal( + Number(repairedItemsIndex.Sub_part || repairedItemsIndex.sub_part || repairedItemsIndex.length), + 50, + '修复后的 items 索引应恢复 50 前缀长度' + ); + + const same = await realFactory.getDispatchModel(TEST_WH); + assert.strictEqual(same, M4, 'second get should return cached model'); + }); + + it('should reject dispatch data that violates non-null numeric constraints before alter sync', async function() { + const mysqlIntegration = process.env.DISPATCH_FACTORY_TEST_MYSQL === '1'; + if (!mysqlIntegration && dialect() !== 'mysql') { + this.skip(); + } + + const { app: realApp } = require('egg-mock/bootstrap'); + activeDialect = realApp.config.sequelize.dialect || 'mysql'; + assert.equal( + dialect(), + 'mysql', + 'DISPATCH_FACTORY_TEST_MYSQL=1 时须启用 egg-sequelize(config/plugin.js)并能连上 MySQL' + ); + + const realFactory = createOrderDeliveryFactory(realApp); + const tableName = await realFactory.getDispatchTableName(TEST_WH); + + await dropIfExists(tableName); + realFactory.clearCache(); + + await realFactory.getDispatchModel(TEST_WH); + + await realApp.model.query( + `ALTER TABLE \`${tableName}\` MODIFY COLUMN \`items_count\` SMALLINT(5) UNSIGNED NULL DEFAULT 0` + ); + await realApp.model.query( + `INSERT INTO \`${tableName}\` (\`items_count\`) VALUES (NULL)` + ); + + let syncCalls = 0; + const DynamicModel = { + sync: async () => { + syncCalls += 1; + }, + }; + + await assert.rejects( + async () => await realFactory.ensureManagedTableSchema(tableName, 'dispatch', TEST_WH, DynamicModel), + error => error.message.includes('数据不满足约束') + && error.message.includes(tableName) + && error.message.includes('items_count') + && error.message.includes('NOT_NULL') + ); + + assert.equal(syncCalls, 0, '预检失败时不应继续执行 alter sync'); + }); +}); + diff --git a/test/app/model/order_delivery_factory_selfcheck.test.js b/test/app/model/order_delivery_factory_selfcheck.test.js new file mode 100644 index 0000000..87513de --- /dev/null +++ b/test/app/model/order_delivery_factory_selfcheck.test.js @@ -0,0 +1,404 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const Module = require('node:module'); +const { mm } = require('egg-mock/bootstrap'); +const createOrderDeliveryFactory = require('../../../app/model/order_delivery_factory'); +const { parseNumericConstraint } = require('../../../app/model/order_delivery_table_schema'); + +/** + * 构造最小 Sequelize 类型集合。 + * @return {Object} Sequelize 类型集合。 + */ +function createSequelizeTypes() { + const makeType = sql => ({ + toSql() { + return sql; + }, + }); + + const unsignedBigInt = length => { + const type = makeType(`BIGINT(${length})`); + type.UNSIGNED = makeType(`BIGINT(${length}) UNSIGNED`); + return type; + }; + + return { + STRING: length => makeType(`VARCHAR(${length})`), + BIGINT: unsignedBigInt, + DECIMAL: (precision, scale) => makeType(`DECIMAL(${precision},${scale})`), + TEXT: makeType('TEXT'), + ENUM: (...values) => makeType(`ENUM('${values.join("','")}')`), + DATE: makeType('DATETIME'), + INTEGER: length => makeType(`INT(${length})`), + CHAR: length => makeType(`CHAR(${length})`), + SMALLINT: length => makeType(`SMALLINT(${length})`), + }; +} + +/** + * 构造工厂测试所需的最小 OrderDelivery 模型。 + * @return {Object} OrderDelivery 模型。 + */ +function createOrderDeliveryModel() { + const Sequelize = createSequelizeTypes(); + const fakeApp = { + Sequelize, + model: { + define(name, attributes, options) { + return { + name, + tableName: options.tableName, + rawAttributes: attributes, + }; + }, + }, + }; + + return require('../../../app/model/order_delivery')(fakeApp); +} + +/** + * 构造工厂测试所需的最小应用对象。 + * @return {Object} 最小应用对象。 + */ +function createFactoryApp() { + const orderDeliveryModel = createOrderDeliveryModel(); + + return { + Sequelize: createSequelizeTypes(), + model: { + OrderDelivery: orderDeliveryModel, + define(name, attributes, options) { + return { + name, + tableName: options.tableName, + rawAttributes: attributes, + sync: async () => {}, + hasMany() {}, + belongsTo() {}, + }; + }, + getQueryInterface() { + return { + describeTable: async () => ({}), + showIndex: async () => [], + showAllTables: async () => [], + }; + }, + query: async () => [[]], + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + }; +} + +/** + * 将 Sequelize 属性定义转换为 describeTable 兼容的模拟结果。 + * @param {Object} attributes 属性定义。 + * @return {Object} describeTable 兼容结果。 + */ +function buildDescribeTableResult(attributes) { + return Object.entries(attributes).reduce((result, [ columnName, attribute ]) => { + result[columnName] = { + type: attribute.type && typeof attribute.type.toSql === 'function' + ? attribute.type.toSql() + : String(attribute.type || ''), + allowNull: attribute.allowNull !== false, + }; + + if (Object.prototype.hasOwnProperty.call(attribute, 'defaultValue')) { + result[columnName].defaultValue = attribute.defaultValue; + } + + return result; + }, {}); +} + +/** + * 将索引定义转换为 showIndex 兼容结果。 + * @param {Array} indexes 索引定义。 + * @return {Array} showIndex 兼容结果。 + */ +function buildShowIndexResult(indexes) { + return indexes.map(index => ({ + Key_name: index.name, + unique: Boolean(index.unique), + nonUnique: index.unique ? 0 : 1, + fields: Array.isArray(index.fields) + ? index.fields.map(field => { + if (typeof field === 'string') { + return { + attribute: field, + }; + } + + return { + attribute: field.attribute || field.name || field.field || field.columnName, + length: field.length, + }; + }) + : [], + })); +} + +describe('test/app/model/order_delivery_factory_selfcheck.test.js', () => { + afterEach(() => { + mm.restore(); + }); + + it('should parse numeric constraints and reject invalid data during precheck', async () => { + assert.deepEqual(parseNumericConstraint({ type: { toSql: () => 'INT(11)' } }), { + type: 'INT', + unsigned: false, + min: '-2147483648', + max: '2147483647', + }); + + assert.deepEqual(parseNumericConstraint({ type: { toSql: () => 'BIGINT(20) UNSIGNED' } }), { + type: 'BIGINT', + unsigned: true, + min: '0', + max: '18446744073709551615', + }); + + assert.deepEqual(parseNumericConstraint({ type: { toSql: () => 'NUMERIC(8, 3) UNSIGNED' } }), { + type: 'NUMERIC', + unsigned: true, + precision: 8, + scale: 3, + min: '-99999.999', + max: '99999.999', + }); + + assert.equal(parseNumericConstraint({ type: { toSql: () => 'VARCHAR(20)' } }), null); + + const factory = createOrderDeliveryFactory(createFactoryApp()); + const tableName = await factory.generateTableName(100000, 'current'); + const describeTableResult = { + items_count: { + type: 'SMALLINT(5) UNSIGNED', + allowNull: true, + }, + }; + + mm(factory, 'needsTableSchemaSync', async () => true); + mm(factory, 'checkTableExists', async () => true); + mm(factory, 'getTableAttributes', () => ({ + items_count: { + type: { + toSql() { + return 'SMALLINT(5) UNSIGNED'; + }, + }, + allowNull: false, + }, + })); + mm(factory.app.model, 'getQueryInterface', () => ({ + describeTable: async () => describeTableResult, + showIndex: async () => [], + })); + mm(factory.app.model, 'query', async sql => { + const sqlText = String(sql); + + if (sqlText.includes('`items_count`') && sqlText.includes('OR')) { + return [[{ violationFound: 1 }], []]; + } + + return [[], []]; + }); + + let syncCalls = 0; + const DynamicModel = { + sync: async () => { + syncCalls += 1; + }, + }; + + await assert.rejects( + async () => await factory.ensureManagedTableSchema(tableName, 'current', 100000, DynamicModel), + error => error.message.includes('数据不满足约束') + && error.message.includes(tableName) + && error.message.includes('NUMERIC_RANGE') + && /column=[^,]+/.test(error.message) + ); + + assert.equal(syncCalls, 0); + }); + + it('should expose sys logistics and platform fields in current table attributes', () => { + const factory = createOrderDeliveryFactory(createFactoryApp()); + const attributes = factory.getTableAttributes('current'); + + assert.ok(attributes.sys_platform_code, '应包含 sys_platform_code'); + assert.equal(attributes.sys_platform_code.type.toSql(), 'VARCHAR(50)'); + assert.ok(attributes.sys_platform_name, '应包含 sys_platform_name'); + assert.equal(attributes.sys_platform_name.type.toSql(), 'VARCHAR(200)'); + assert.ok(attributes.sys_logistics_code, '应包含 sys_logistics_code'); + assert.equal(attributes.sys_logistics_code.type.toSql(), 'VARCHAR(50)'); + assert.ok(attributes.sys_logistics_name, '应包含 sys_logistics_name'); + assert.equal(attributes.sys_logistics_name.type.toSql(), 'VARCHAR(200)'); + }); + + it('should assign non-null defaults for order state machines', () => { + const factory = createOrderDeliveryFactory(createFactoryApp()); + const attributes = factory.getTableAttributes('current'); + + assert.equal(attributes.print_status.defaultValue, 'none'); + assert.equal(attributes.lock_status.defaultValue, 'none'); + assert.equal(attributes.intercept_status.defaultValue, 'none'); + }); + + it('should call independent helper during app.beforeStart', async () => { + const originalLoad = Module._load; + const helperCalls = { + count: 0, + }; + + let beforeStartHandler; + const fakeApp = { + model: {}, + logger: { + info() {}, + error() {}, + warn() {}, + }, + beforeStart(handler) { + beforeStartHandler = handler; + }, + }; + + Module._load = function(request, parent, isMain) { + if (request === './app/lib/file_writer') { + return class LocalFileWriter {}; + } + + if (request === './app/lib/order_delivery_selfcheck') { + return async () => { + helperCalls.count += 1; + }; + } + + if (request === './app/model/order_delivery_factory') { + return () => ({ + ensureManagedTableSchemasCalls: 0, + async ensureManagedTableSchemas() { + this.ensureManagedTableSchemasCalls += 1; + }, + }); + } + + if (request === './app/model/order_items_factory') { + return () => ({ + getOrCreateModel: async () => null, + }); + } + + return originalLoad.call(this, request, parent, isMain); + }; + + try { + delete require.cache[require.resolve('../../../app.js')]; + const register = require('../../../app.js'); + register(fakeApp); + + assert.equal(typeof beforeStartHandler, 'function'); + await beforeStartHandler(); + assert.equal(helperCalls.count, 1); + } finally { + Module._load = originalLoad; + delete require.cache[require.resolve('../../../app.js')]; + } + }); + + it('should skip sync when managed table schema matches the model', async () => { + const factory = createOrderDeliveryFactory(createFactoryApp()); + const tableName = await factory.generateTableName(100000, 'current'); + const tableAttributes = factory.getTableAttributes('current'); + const describeTableResult = buildDescribeTableResult(tableAttributes); + const showIndexResult = buildShowIndexResult(factory.getIndexes(100000, 'current')); + let syncCalls = 0; + + assert.deepEqual(factory.getIndexes(100000, 'current')[3].fields, [ + { + attribute: 'items', + length: 50, + }, + ]); + + mm(factory, 'checkTableExists', async () => true); + mm(factory.app.model, 'getQueryInterface', () => ({ + describeTable: async () => describeTableResult, + showIndex: async () => showIndexResult, + })); + + const DynamicModel = { + sync: async () => { + syncCalls += 1; + }, + }; + + const synced = await factory.ensureManagedTableSchema(tableName, 'current', 100000, DynamicModel); + + assert.equal(synced, false); + assert.equal(syncCalls, 0); + }); + + it('should call sync when items index prefix length is inconsistent', async () => { + const factory = createOrderDeliveryFactory(createFactoryApp()); + const tableName = await factory.generateTableName(100000, 'current'); + const tableAttributes = factory.getTableAttributes('current'); + const describeTableResult = buildDescribeTableResult(tableAttributes); + const showIndexResult = buildShowIndexResult(factory.getIndexes(100000, 'current')); + showIndexResult[3].fields[0].length = 30; + + let syncCalls = 0; + + mm(factory, 'checkTableExists', async () => true); + mm(factory.app.model, 'getQueryInterface', () => ({ + describeTable: async () => describeTableResult, + showIndex: async () => showIndexResult, + })); + + const DynamicModel = { + sync: async () => { + syncCalls += 1; + }, + }; + + const synced = await factory.ensureManagedTableSchema(tableName, 'current', 100000, DynamicModel); + + assert.equal(synced, true); + assert.equal(syncCalls, 0); + }); + it('should call sync when managed table schema is inconsistent', async () => { + const factory = createOrderDeliveryFactory(createFactoryApp()); + const tableName = await factory.generateTableName(100000, 'current'); + const tableAttributes = factory.getTableAttributes('current'); + const describeTableResult = buildDescribeTableResult(tableAttributes); + const showIndexResult = buildShowIndexResult(factory.getIndexes(100000, 'current')); + delete describeTableResult.step; + + let syncCalls = 0; + + mm(factory, 'checkTableExists', async () => true); + mm(factory.app.model, 'getQueryInterface', () => ({ + describeTable: async () => describeTableResult, + showIndex: async () => showIndexResult, + })); + + const DynamicModel = { + sync: async () => { + syncCalls += 1; + }, + }; + + const synced = await factory.ensureManagedTableSchema(tableName, 'current', 100000, DynamicModel); + + assert.equal(synced, true); + assert.equal(syncCalls, 1); + }); +}); diff --git a/test/app/model/order_items_factory.test.js b/test/app/model/order_items_factory.test.js new file mode 100644 index 0000000..ab50d04 --- /dev/null +++ b/test/app/model/order_items_factory.test.js @@ -0,0 +1,251 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const { mm } = require('egg-mock/bootstrap'); +const createOrderItemsFactory = require('../../../app/model/order_items_factory'); + +/** + * 构造最小 Sequelize 类型集合。 + * @return {Object} Sequelize 类型集合。 + */ +function createSequelizeTypes() { + const makeType = sql => ({ + toSql() { + return sql; + }, + }); + + const unsignedBigInt = length => { + const type = makeType(`BIGINT(${length})`); + type.UNSIGNED = makeType(`BIGINT(${length}) UNSIGNED`); + return type; + }; + + return { + STRING: length => makeType(`VARCHAR(${length})`), + BIGINT: unsignedBigInt, + DECIMAL: (precision, scale) => makeType(`DECIMAL(${precision},${scale})`), + TEXT: makeType('TEXT'), + ENUM: (...values) => makeType(`ENUM('${values.join("','")}')`), + DATE: makeType('DATETIME'), + INTEGER: length => makeType(`INT(${length})`), + CHAR: length => makeType(`CHAR(${length})`), + SMALLINT: length => makeType(`SMALLINT(${length})`), + JSON: makeType('JSON'), + literal(value) { + return { + toSql() { + return value; + }, + }; + }, + }; +} + +/** + * 构造工厂测试所需的最小 OrderItems 模型。 + * @return {Object} OrderItems 模型。 + */ +function createOrderItemsModel() { + const Sequelize = createSequelizeTypes(); + const fakeApp = { + Sequelize, + model: { + define(name, attributes, options) { + return { + name, + tableName: options.tableName, + rawAttributes: attributes, + }; + }, + }, + }; + + return require('../../../app/model/order_items')(fakeApp); +} + +/** + * 构造工厂测试所需的最小应用对象。 + * @param {Object} [queryInterfaceOverrides={}] 查询接口覆盖项。 + * @return {Object} 最小应用对象。 + */ +function createFactoryApp(queryInterfaceOverrides = {}) { + const orderItemsModel = createOrderItemsModel(); + + return { + Sequelize: createSequelizeTypes(), + model: { + OrderItems: orderItemsModel, + define(name, attributes, options) { + return { + name, + tableName: options.tableName, + rawAttributes: attributes, + sync: async () => {}, + hasMany() {}, + belongsTo() {}, + }; + }, + getQueryInterface() { + return { + describeTable: async () => ({}), + showIndex: async () => [], + ...queryInterfaceOverrides, + }; + }, + query: async () => [[]], + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + _shardWarehouseIdsValidated: new Set(), + }; +} + +/** + * 将属性定义转换为 describeTable 兼容结果。 + * @param {Object} attributes 属性定义。 + * @return {Object} describeTable 兼容结果。 + */ +function buildDescribeTableResult(attributes) { + return Object.entries(attributes).reduce((result, [ columnName, attribute ]) => { + result[columnName] = { + type: attribute.type && typeof attribute.type.toSql === 'function' + ? attribute.type.toSql() + : String(attribute.type || ''), + allowNull: attribute.allowNull !== false, + }; + + if (Object.prototype.hasOwnProperty.call(attribute, 'defaultValue')) { + result[columnName].defaultValue = attribute.defaultValue; + } + + return result; + }, {}); +} + +/** + * 将索引定义转换为 showIndex 兼容结果。 + * @param {Array} indexes 索引定义。 + * @return {Array} showIndex 兼容结果。 + */ +function buildShowIndexResult(indexes) { + return indexes.map(index => ({ + Key_name: index.name, + unique: Boolean(index.unique), + nonUnique: index.unique ? 0 : 1, + fields: Array.isArray(index.fields) + ? index.fields.map(field => { + if (typeof field === 'string') { + return { + attribute: field, + }; + } + + return { + attribute: field.attribute || field.name || field.field || field.columnName, + length: field.length, + }; + }) + : [], + })); +} + +describe('test/app/model/order_items_factory.test.js', () => { + afterEach(() => { + mm.restore(); + }); + + it('should keep schema in sync when current table matches the model', async () => { + const factory = createOrderItemsFactory(createFactoryApp()); + const tableAttributes = factory.getTableAttributes('current'); + const describeTableResult = buildDescribeTableResult(tableAttributes); + const showIndexResult = buildShowIndexResult(factory.generateIndexes(100000)); + + mm(factory, 'checkTableExists', async () => true); + mm(factory.app.model, 'getQueryInterface', () => ({ + describeTable: async () => describeTableResult, + showIndex: async () => showIndexResult, + })); + + assert.equal(await factory.needsTableSchemaSync('wms_order_items_100000', 'current', 100000, true), false); + }); + + it('should sync and cache dynamic model when schema is inconsistent', async () => { + const factory = createOrderItemsFactory(createFactoryApp()); + const tableName = factory.generateTableName(100000, 'current'); + const describeTableResult = buildDescribeTableResult(factory.getTableAttributes('current')); + const showIndexResult = buildShowIndexResult(factory.generateIndexes(100000)); + delete describeTableResult.item_code; + + let syncCalls = 0; + + mm(factory, 'checkTableExists', async () => true); + mm(factory.app.model, 'getQueryInterface', () => ({ + describeTable: async () => describeTableResult, + showIndex: async () => showIndexResult, + })); + mm(factory.app.model, 'define', (name, attributes, options) => ({ + name, + tableName: options.tableName, + rawAttributes: attributes, + sync: async () => { + syncCalls += 1; + }, + hasMany() {}, + belongsTo() {}, + })); + + const model = await factory.getOrCreateModel(100000, 'current'); + + assert.equal(model.tableName, tableName); + assert.equal(syncCalls, 1); + assert.strictEqual(await factory.getOrCreateModel(100000, 'current'), model); + assert.equal(syncCalls, 1); + }); + + it('should clear model cache and shard validation cache together', () => { + const factory = createOrderItemsFactory(createFactoryApp()); + factory.modelCache.set('100000_current', {}); + factory.creatingTables.set('100000_current', Promise.resolve()); + factory.app._shardWarehouseIdsValidated.add('100000'); + + factory.clearCache(100000, 'current'); + + assert.equal(factory.modelCache.has('100000_current'), false); + assert.equal(factory.creatingTables.has('100000_current'), false); + assert.equal(factory.app._shardWarehouseIdsValidated.size, 0); + }); + + it('should add archive_time to history attributes', () => { + const factory = createOrderItemsFactory(createFactoryApp()); + const historyAttributes = factory.getTableAttributes('history'); + + assert.ok(historyAttributes.archive_time); + assert.equal(typeof historyAttributes.archive_time.type.toSql, 'function'); + }); + + it('should expose new order item snapshot fields in table attributes and indexes', () => { + const factory = createOrderItemsFactory(createFactoryApp()); + const currentAttributes = factory.getTableAttributes('current'); + const indexes = factory.generateIndexes(100000); + + assert.ok(currentAttributes.item_snapshot, '应包含 item_snapshot 字段'); + assert.equal(currentAttributes.storage_id, undefined, '不应包含 storage_id 字段'); + assert.equal(currentAttributes.space_id, undefined, '不应包含 space_id 字段'); + assert.equal(currentAttributes.stock_snapshot, undefined, '不应包含 stock_snapshot 字段'); + assert.equal(indexes.some(index => index.name === 'idx_100000_storage_id'), false); + assert.equal(indexes.some(index => index.name === 'idx_100000_space_id'), false); + }); + + it('should create and cache dispatch model with dispatch table name', async () => { + const factory = createOrderItemsFactory(createFactoryApp()); + + const model = await factory.getOrCreateModel(100000, 'dispatch'); + + assert.equal(model.tableName, 'wms_order_items_100000_dispatch'); + assert.strictEqual(await factory.getOrCreateModel(100000, 'dispatch'), model); + }); +}); diff --git a/test/app/model/picking.test.js b/test/app/model/picking.test.js new file mode 100644 index 0000000..4145a8d --- /dev/null +++ b/test/app/model/picking.test.js @@ -0,0 +1,80 @@ +'use strict'; + +const assert = require('node:assert/strict'); + +function createSequelizeTypes() { + const makeType = sql => ({ + toSql() { + return sql; + }, + }); + + const unsignedBigInt = length => { + const type = makeType(`BIGINT(${length})`); + type.UNSIGNED = makeType(`BIGINT(${length}) UNSIGNED`); + return type; + }; + + return { + BIGINT: unsignedBigInt, + STRING: length => makeType(`VARCHAR(${length})`), + INTEGER: length => { + const type = makeType(`INT(${length})`); + type.UNSIGNED = makeType(`INT(${length}) UNSIGNED`); + return type; + }, + DATE: makeType('DATETIME'), + literal(value) { + return { + toSql() { + return value; + }, + }; + }, + }; +} + +function createApp() { + const Sequelize = createSequelizeTypes(); + + return { + Sequelize, + model: { + define(name, attributes, options) { + return { + name, + rawAttributes: attributes, + options, + belongsTo() {}, + }; + }, + }, + }; +} + +describe('test/app/model/picking.test.js', () => { + it('should define wms_picking fields and indexes', () => { + const app = createApp(); + const Picking = require('../../../app/model/picking')(app); + + assert.equal(Picking.options.tableName, 'wms_picking'); + assert.equal(Picking.options.comment, '订单储位分配表'); + assert.ok(Picking.rawAttributes.order_id); + assert.ok(Picking.rawAttributes.order_item_id); + assert.ok(Picking.rawAttributes.storage_id); + assert.ok(Picking.rawAttributes.quantity); + assert.ok(Picking.rawAttributes.space_id); + assert.ok(Picking.rawAttributes.space_name); + assert.ok(Picking.rawAttributes.status); + assert.equal(Picking.rawAttributes.status.defaultValue, 'pending'); + assert.equal(Picking.rawAttributes.quantity.defaultValue, 1); + + const indexNames = (Picking.options.indexes || []).map(index => index.name); + assert.ok(indexNames.includes('idx_wms_picking_order_id')); + assert.ok(indexNames.includes('idx_wms_picking_order_item_id')); + assert.ok(indexNames.includes('idx_wms_picking_storage_id')); + assert.ok(indexNames.includes('idx_wms_picking_space_id')); + assert.ok(indexNames.includes('idx_wms_picking_status')); + assert.ok(indexNames.includes('idx_wms_picking_order_item_space')); + }); +}); diff --git a/test/app/schedule/notice_stock_remaining.test.js b/test/app/schedule/notice_stock_remaining.test.js new file mode 100644 index 0000000..3b642d5 --- /dev/null +++ b/test/app/schedule/notice_stock_remaining.test.js @@ -0,0 +1,448 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const schedule = require('../../../app/schedule/notice_stock_remaining'); + +const CACHE_KEY_PREFIX = 'notice_stock_remaining_notified'; +const LEGACY_CACHE_KEY = 'notice_stock_remaining_notified_list'; + +function createLogger() { + return { + info() {}, + warn() {}, + error() {}, + debug() {}, + }; +} + +function createSequelizeInstanceLikeRecord(values = {}, associations = {}) { + const dataValues = { ...values }; + const includedValues = { ...associations }; + const prototype = { + getDataValue(fieldName) { + if (Object.prototype.hasOwnProperty.call(dataValues, fieldName)) { + return dataValues[fieldName]; + } + + return includedValues[fieldName]; + }, + get(fieldName) { + return this.getDataValue(fieldName); + }, + }; + + for (const fieldName of Object.keys(dataValues)) { + Object.defineProperty(prototype, fieldName, { + enumerable: false, + configurable: true, + get() { + return dataValues[fieldName]; + }, + }); + } + + for (const fieldName of Object.keys(includedValues)) { + Object.defineProperty(prototype, fieldName, { + enumerable: false, + configurable: true, + get() { + return includedValues[fieldName]; + }, + }); + } + + return Object.create(prototype); +} + +function buildLocalDateKey(dateValue) { + const year = String(dateValue.getFullYear()); + const month = String(dateValue.getMonth() + 1).padStart(2, '0'); + const day = String(dateValue.getDate()).padStart(2, '0'); + return `${year}${month}${day}`; +} + +async function withFixedDate(fixedDate, handler) { + const OriginalDate = Date; + const fixedTime = fixedDate.getTime(); + + class FixedDate extends OriginalDate { + constructor(...args) { + if (args.length === 0) { + super(fixedTime); + return; + } + + super(...args); + } + + static now() { + return fixedTime; + } + } + + Object.setPrototypeOf(FixedDate, OriginalDate); + FixedDate.parse = OriginalDate.parse.bind(OriginalDate); + FixedDate.UTC = OriginalDate.UTC.bind(OriginalDate); + + global.Date = FixedDate; + + try { + return await handler(); + } finally { + global.Date = OriginalDate; + } +} + +function createScheduleHarness(options = {}) { + const noticePayloads = []; + const cacheWrites = []; + const cacheStore = new Map(Object.entries(options.cacheStore || {})); + + const ctx = { + app: { + _noticeStockRemainingRunning: false, + Sequelize: { + Op: { + gt: Symbol('gt'), + in: Symbol('in'), + ne: Symbol('ne'), + lte: Symbol('lte'), + }, + }, + async getCacheAsync(cacheKey) { + return cacheStore.has(cacheKey) ? cacheStore.get(cacheKey) : null; + }, + async setCacheAsync(cacheKey, data, ttl) { + cacheWrites.push({ cacheKey, data, ttl }); + cacheStore.set(cacheKey, data); + }, + formatDate(dateValue) { + return dateValue.toISOString(); + }, + }, + logger: createLogger(), + model: { + StockWarehouse: { + async findAll() { + return options.stockRows || []; + }, + }, + Storage: { + async findAll() { + return options.storageRows || []; + }, + }, + LocationSpace: {}, + }, + service: { + systems: { + notice: { + async send(payload) { + noticePayloads.push(payload); + if (typeof options.sendHandler === 'function') { + return await options.sendHandler(payload); + } + + return { + success: true, + }; + }, + }, + }, + }, + }; + + if (options.useNoticeIndexSend) { + delete ctx.service.systems.notice.send; + ctx.service.systems.notice.index = { + async send(payload) { + noticePayloads.push(payload); + if (typeof options.sendHandler === 'function') { + return await options.sendHandler(payload); + } + + return { + success: true, + }; + }, + }; + } + + return { + ctx, + noticePayloads, + cacheWrites, + cacheStore, + }; +} + +describe('test/app/schedule/notice_stock_remaining.test.js', () => { + it('should ignore legacy global cache and write back stock-day cache keys', async () => { + const fixedDate = new Date(2026, 3, 14, 9, 0, 0); + const { ctx, noticePayloads, cacheWrites } = createScheduleHarness({ + cacheStore: { + [LEGACY_CACHE_KEY]: [ 'stock:2001' ], + }, + stockRows: [ + { + id: 2001, + item_code: 'SKU-2001', + item_name: '测试商品A', + store_id: 10, + warehouse_id: 20, + remaining_threshold_days: 7, + }, + ], + storageRows: [ + { + id: 9001, + stock_id: 2001, + batch_no: 'BATCH-1', + warehouse_id: 20, + store_id: 10, + quantity: 5, + available_quantity: 5, + expiry_date: new Date(2026, 3, 16, 9, 0, 0), + inbound_time: new Date(2026, 3, 13, 9, 0, 0), + is_enabled: 1, + delete_at: null, + space: { + space_code: 'A-01', + custom_name: '一号位', + }, + }, + { + id: 9002, + stock_id: 2001, + batch_no: 'BATCH-2', + warehouse_id: 20, + store_id: 10, + quantity: 8, + available_quantity: 8, + expiry_date: new Date(2026, 3, 17, 9, 0, 0), + inbound_time: new Date(2026, 3, 12, 9, 0, 0), + is_enabled: 1, + delete_at: null, + space: { + space_code: 'A-02', + custom_name: '二号位', + }, + }, + ], + }); + + await withFixedDate(fixedDate, async () => { + await schedule.task(ctx); + }); + + const dateKey = buildLocalDateKey(fixedDate); + const expectedCacheKey = `${CACHE_KEY_PREFIX}:stock:2001:${dateKey}`; + + assert.equal(noticePayloads.length, 1); + assert.equal(noticePayloads[0].businessId, 2001); + assert.equal(noticePayloads[0].metadata.businessId, 2001); + assert.equal(noticePayloads[0].metadata.stockId, 2001); + assert.equal(noticePayloads[0].metadata.notifyKey, 'stock:2001'); + assert.equal(noticePayloads[0].metadata.cacheKey, expectedCacheKey); + + assert.equal(cacheWrites.length, 1); + assert.equal(cacheWrites[0].cacheKey, expectedCacheKey); + assert.deepEqual(cacheWrites[0].data, { + notifiedAt: fixedDate.toISOString(), + stockId: 2001, + notifyKey: 'stock:2001', + }); + assert.equal(cacheWrites[0].ttl, 24 * 60 * 60); + + assert.equal(ctx.app._noticeStockRemainingRunning, false); + }); + + it('should keep same-day dedupe per stock without extending other stocks', async () => { + const fixedDate = new Date(2026, 3, 14, 9, 0, 0); + const dateKey = buildLocalDateKey(fixedDate); + const cachedStockKey = `${CACHE_KEY_PREFIX}:stock:2001:${dateKey}`; + const otherStockKey = `${CACHE_KEY_PREFIX}:stock:2002:${dateKey}`; + const { ctx, noticePayloads, cacheWrites } = createScheduleHarness({ + cacheStore: { + [cachedStockKey]: { + notifiedAt: fixedDate.toISOString(), + stockId: 2001, + notifyKey: 'stock:2001', + }, + }, + stockRows: [ + { + id: 2001, + item_code: 'SKU-2001', + item_name: '测试商品A', + store_id: 10, + warehouse_id: 20, + remaining_threshold_days: 7, + }, + { + id: 2002, + item_code: 'SKU-2002', + item_name: '测试商品B', + store_id: 10, + warehouse_id: 20, + remaining_threshold_days: 7, + }, + ], + storageRows: [ + createSequelizeInstanceLikeRecord( + { + id: 9001, + stock_id: 2001, + batch_no: 'BATCH-1', + warehouse_id: 20, + store_id: 10, + quantity: 5, + available_quantity: 5, + expiry_date: new Date(2026, 3, 16, 9, 0, 0), + inbound_time: new Date(2026, 3, 13, 9, 0, 0), + is_enabled: 1, + delete_at: null, + }, + { + space: createSequelizeInstanceLikeRecord({ + space_code: 'A-01', + custom_name: '一号位', + }), + } + ), + createSequelizeInstanceLikeRecord( + { + id: 9002, + stock_id: 2002, + batch_no: 'BATCH-2', + warehouse_id: 20, + store_id: 10, + quantity: 6, + available_quantity: 6, + expiry_date: new Date(2026, 3, 16, 9, 0, 0), + inbound_time: new Date(2026, 3, 13, 9, 0, 0), + is_enabled: 1, + delete_at: null, + }, + { + space: createSequelizeInstanceLikeRecord({ + space_code: 'B-01', + custom_name: '二号位', + }), + } + ), + ], + }); + + await withFixedDate(fixedDate, async () => { + await schedule.task(ctx); + }); + + assert.equal(noticePayloads.length, 1); + assert.equal(noticePayloads[0].businessId, 2002); + assert.equal(noticePayloads[0].metadata.stockId, 2002); + assert.equal(noticePayloads[0].metadata.notifyKey, 'stock:2002'); + assert.equal(noticePayloads[0].metadata.cacheKey, otherStockKey); + + assert.equal(cacheWrites.length, 1); + assert.equal(cacheWrites[0].cacheKey, otherStockKey); + assert.equal(ctx.app._noticeStockRemainingRunning, false); + }); + + it('should keep retrying when notice send reports failure', async () => { + const fixedDate = new Date(2026, 3, 14, 9, 0, 0); + const { ctx, noticePayloads, cacheWrites } = createScheduleHarness({ + stockRows: [ + { + id: 2001, + item_code: 'SKU-2001', + item_name: '测试商品A', + store_id: 10, + warehouse_id: 20, + remaining_threshold_days: 7, + }, + ], + storageRows: [ + { + id: 9001, + stock_id: 2001, + batch_no: 'BATCH-1', + warehouse_id: 20, + store_id: 10, + quantity: 5, + available_quantity: 5, + expiry_date: new Date(2026, 3, 16, 9, 0, 0), + inbound_time: new Date(2026, 3, 13, 9, 0, 0), + is_enabled: 1, + delete_at: null, + space: { + space_code: 'A-01', + custom_name: '一号位', + }, + }, + ], + sendHandler() { + return { + success: false, + }; + }, + }); + + await withFixedDate(fixedDate, async () => { + await schedule.task(ctx); + }); + + const dateKey = buildLocalDateKey(fixedDate); + const expectedCacheKey = `${CACHE_KEY_PREFIX}:stock:2001:${dateKey}`; + + assert.equal(noticePayloads.length, 1); + assert.equal(cacheWrites.length, 0); + assert.equal(ctx.app._noticeStockRemainingRunning, false); + assert.equal(noticePayloads[0].metadata.cacheKey, expectedCacheKey); + }); + + it('should fallback to notice.index.send when notice.send is missing', async () => { + const fixedDate = new Date(2026, 3, 14, 9, 0, 0); + const { ctx, noticePayloads } = createScheduleHarness({ + useNoticeIndexSend: true, + stockRows: [ + { + id: 2001, + item_code: 'SKU-2001', + item_name: '测试商品A', + store_id: 10, + warehouse_id: 20, + remaining_threshold_days: 7, + }, + ], + storageRows: [ + { + id: 9001, + stock_id: 2001, + batch_no: 'BATCH-1', + warehouse_id: 20, + store_id: 10, + quantity: 5, + available_quantity: 5, + expiry_date: new Date(2026, 3, 16, 9, 0, 0), + inbound_time: new Date(2026, 3, 13, 9, 0, 0), + is_enabled: 1, + delete_at: null, + space: { + space_code: 'A-01', + custom_name: '一号位', + }, + }, + ], + }); + + await withFixedDate(fixedDate, async () => { + await schedule.task(ctx); + }); + + assert.equal(noticePayloads.length, 1); + assert.equal(noticePayloads[0].businessId, 2001); + assert.equal(noticePayloads[0].metadata.notifyKey, 'stock:2001'); + assert.equal(ctx.app._noticeStockRemainingRunning, false); + }); +}); diff --git a/test/app/schedule/sync_outbound_orders_to_delivery.test.js b/test/app/schedule/sync_outbound_orders_to_delivery.test.js new file mode 100644 index 0000000..82de6df --- /dev/null +++ b/test/app/schedule/sync_outbound_orders_to_delivery.test.js @@ -0,0 +1,47 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const schedule = require('../../../app/schedule/sync_outbound_orders_to_delivery'); + +describe('test/app/schedule/sync_outbound_orders_to_delivery.test.js', () => { + it('should run every 1 minute in worker mode and avoid reentry', async () => { + assert.equal(schedule.schedule.interval, '1m'); + assert.equal(schedule.schedule.type, 'worker'); + assert.equal(schedule.schedule.immediate, false); + assert.equal(schedule.queryTimeoutMs, 15000); + assert.equal(schedule.executionTimeoutMs, 30000); + + let invokeCount = 0; + const ctx = { + app: { + _syncOutboundOrdersToDeliveryRunning: false, + }, + logger: { + info() {}, + error() {}, + }, + service: { + systems: { + orderDeliveryMigration: { + async syncOutboundOrdersToDelivery(data) { + invokeCount += 1; + assert.equal(data.queryTimeoutMs, 15000); + assert.equal(data.executionTimeoutMs, 30000); + return { + totalCreated: 1, + }; + }, + }, + }, + }, + }; + + await schedule.task(ctx); + assert.equal(invokeCount, 1); + assert.equal(ctx.app._syncOutboundOrdersToDeliveryRunning, false); + + ctx.app._syncOutboundOrdersToDeliveryRunning = true; + await schedule.task(ctx); + assert.equal(invokeCount, 1); + }); +}); diff --git a/test/app/schedule/sync_outbound_timeout_orders_to_delivery.test.js b/test/app/schedule/sync_outbound_timeout_orders_to_delivery.test.js new file mode 100644 index 0000000..3c257d8 --- /dev/null +++ b/test/app/schedule/sync_outbound_timeout_orders_to_delivery.test.js @@ -0,0 +1,48 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const schedule = require('../../../app/schedule/sync_outbound_timeout_orders_to_delivery'); + +describe('test/app/schedule/sync_outbound_timeout_orders_to_delivery.test.js', () => { + it('should run every 10 minutes in worker mode and avoid reentry', async () => { + assert.equal(schedule.schedule.interval, '10m'); + assert.equal(schedule.schedule.type, 'worker'); + assert.equal(schedule.schedule.immediate, false); + assert.equal(schedule.queryTimeoutMs, 120000); + assert.equal(schedule.executionTimeoutMs, 300000); + + let invokeCount = 0; + const ctx = { + app: { + _syncTimeoutOutboundOrdersToDeliveryRunning: false, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + service: { + systems: { + orderDeliveryMigration: { + async retryTimeoutOutboundOrdersToDelivery(data) { + invokeCount += 1; + assert.equal(data.queryTimeoutMs, 120000); + assert.equal(data.executionTimeoutMs, 300000); + return { + totalCreated: 1, + }; + }, + }, + }, + }, + }; + + await schedule.task(ctx); + assert.equal(invokeCount, 1); + assert.equal(ctx.app._syncTimeoutOutboundOrdersToDeliveryRunning, false); + + ctx.app._syncTimeoutOutboundOrdersToDeliveryRunning = true; + await schedule.task(ctx); + assert.equal(invokeCount, 1); + }); +}); diff --git a/test/app/service/qimenMethods/order.test.js b/test/app/service/qimenMethods/order.test.js new file mode 100644 index 0000000..dde8d31 --- /dev/null +++ b/test/app/service/qimenMethods/order.test.js @@ -0,0 +1,216 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const OrderService = require('../../../../app/service/qimenMethods/order'); + +function createHarness(options = {}) { + const calls = { + findOne: 0, + update: 0, + commit: 0, + rollback: 0, + noticeSend: 0, + }; + + const transaction = { + LOCK: { + UPDATE: 'UPDATE', + }, + async commit() { + calls.commit += 1; + }, + async rollback() { + calls.rollback += 1; + }, + }; + + const existingOrder = options.existingOrder === undefined ? { + id: 1, + pick_status: 'none', + print_status: 'none', + async update(values) { + calls.update += 1; + calls.updateValues = values; + Object.assign(this, values); + }, + } : options.existingOrder; + + const ctx = { + app: { + config: {}, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + service: { + systems: { + notice: { + async send(payload) { + calls.noticeSend += 1; + calls.noticePayload = payload; + return { + success: true, + }; + }, + }, + }, + }, + model: { + async transaction() { + calls.transaction = true; + return transaction; + }, + OrderExpress: { + async findAll(query) { + calls.orderExpressFindAll = query; + if (options.orderExpress === undefined) { + return []; + } + return Array.isArray(options.orderExpress) ? options.orderExpress : [ options.orderExpress ]; + }, + }, + EntryOrder: { + async findOne(query) { + calls.findOne += 1; + calls.findOneQuery = query; + return options.existingOrder === null ? null : existingOrder; + }, + }, + OrderDeliveryFactory: { + async getCurrentModel() { + return { + async findOne(query) { + calls.findOne += 1; + calls.findOneQuery = query; + return options.existingOrder === null ? null : existingOrder; + }, + }; + }, + }, + }, + }; + + const service = new OrderService(ctx); + service.setInfo(options.storeId || 1000000, options.warehouseId || 100000, 'app-key', 'customer-id', 'warehouse-code'); + + return { + service, + calls, + transaction, + existingOrder, + }; +} + +describe('test/app/service/qimenMethods/order.test.js', () => { + it('should cancel order directly when pick_status and print_status are none', async () => { + const { service, calls, existingOrder } = createHarness(); + + const result = await service.cancel({ + request: { + orderType: 'JYCK', + orderCode: 'OD-001', + }, + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.message, '取消订单成功'); + assert.equal(calls.findOne, 1); + assert.equal(calls.commit, 1); + assert.equal(calls.rollback, 0); + assert.equal(calls.update, 1); + assert.equal(calls.updateValues.status, 'cancel'); + assert.equal(calls.updateValues.outbound_status, 'fin'); + assert.equal(calls.updateValues.step, 4); + assert.equal(calls.noticeSend, 0); + assert.equal(existingOrder.status, 'cancel'); + assert.equal(existingOrder.outbound_status, 'fin'); + assert.equal(existingOrder.step, 4); + }); + + it('should switch to intercepting when pick_status or print_status is not none', async () => { + const { service, calls, existingOrder } = createHarness({ + existingOrder: { + id: 2, + pick_status: 'fin', + print_status: 'none', + async update(values) { + calls.update += 1; + calls.updateValues = values; + Object.assign(this, values); + }, + }, + orderExpress: [ + { + waybill_code: 'WB-002', + logistics_code: 'STO', + logistics_name: '申通', + logistics_interface_id: 66, + }, + { + waybill_code: 'WB-001', + logistics_code: 'YTO', + logistics_name: '圆通', + logistics_interface_id: 88, + }, + ], + }); + + const result = await service.cancel({ + request: { + orderType: 'JYCK', + orderCode: 'OD-002', + }, + }); + + assert.equal(result.flag, 'failure'); + assert.equal(result.message, '取消失败,已通知拦截执行'); + assert.equal(calls.findOne, 1); + assert.equal(calls.commit, 1); + assert.equal(calls.rollback, 0); + assert.equal(calls.update, 1); + assert.equal(calls.updateValues.intercept_status, 'intercepting'); + assert.equal(calls.noticeSend, 1); + assert.equal(calls.noticePayload.event, 'order_cancel_intercepted'); + assert.equal(calls.noticePayload.businessName, 'order'); + assert.equal(calls.noticePayload.messageType, 'text'); + assert.deepEqual(calls.noticePayload.metadata.express, [ + { + waybill_code: 'WB-002', + logistics_code: 'STO', + logistics_name: '申通', + logistics_interface_id: 66, + }, + { + waybill_code: 'WB-001', + logistics_code: 'YTO', + logistics_name: '圆通', + logistics_interface_id: 88, + }, + ]); + assert.equal(calls.orderExpressFindAll.where.order_id, 2); + assert.equal(existingOrder.intercept_status, 'intercepting'); + }); + + it('should rollback when the order cannot be found', async () => { + const { service, calls } = createHarness({ + existingOrder: null, + }); + + const result = await service.cancel({ + request: { + orderType: 'JYCK', + orderCode: 'OD-404', + }, + }); + + assert.equal(result.flag, 'failure'); + assert.equal(result.message, '未找到对应的订单'); + assert.equal(calls.findOne, 1); + assert.equal(calls.commit, 0); + assert.equal(calls.rollback, 1); + assert.equal(calls.update, 0); + assert.equal(calls.noticeSend, 0); + }); +}); diff --git a/test/app/service/systemMethods/order.base.step.test.js b/test/app/service/systemMethods/order.base.step.test.js index 3f4e5b3..ce278a7 100644 --- a/test/app/service/systemMethods/order.base.step.test.js +++ b/test/app/service/systemMethods/order.base.step.test.js @@ -2,26 +2,203 @@ const assert = require('node:assert/strict'); const Sequelize = require('sequelize'); +const OrderIndexService = require('../../../../app/service/systemMethods/order/index'); const OrderBaseService = require('../../../../app/service/systemMethods/order/base'); +const { buildRows, createOrderHarness, matchesWhere } = require('../../../support/order_service_test_helper'); describe('test/app/service/systemMethods/order.base.step.test.js', () => { - function createService() { + function createService(storeId = 100000) { const ctx = { app: { Sequelize, config: {}, }, - user: {}, + user: { + store_id: storeId, + }, }; return new OrderBaseService(ctx); } - it('should build where with step equality filter', () => { - const service = createService(); - const where = service.buildWhere({ step: 1 }, 100000); + function createRecordModel(rows, capture) { + const normalizedRows = Array.isArray(rows) ? rows.map(row => ({ ...row })) : []; - assert.equal(where.warehouse_id, 100000); + return { + async findOne(options = {}) { + capture.findOneOptions = options; + const matchedRow = normalizedRows.find(row => matchesWhere(row, options.where)); + return matchedRow ? { ...matchedRow } : null; + }, + async findAll(options = {}) { + capture.findAllOptions = options; + return normalizedRows + .filter(row => matchesWhere(row, options.where)) + .map(row => ({ ...row })); + }, + }; + } + + function createDetailHarness(options = {}) { + const storeId = options.storeId || 100000; + const orderRowsByType = options.orderRowsByType || {}; + const itemRowsByType = options.itemRowsByType || {}; + const expressRowsByOrderId = options.expressRowsByOrderId || {}; + const captures = { + orderFactoryCalls: [], + itemFactoryCalls: [], + expressQueries: [], + }; + + const ctx = { + app: { + Sequelize, + config: {}, + }, + user: { + store_id: storeId, + }, + model: { + OrderDeliveryFactory: { + async getCurrentModel(warehouseId) { + const capture = { + method: 'getCurrentModel', + warehouseId, + }; + captures.orderFactoryCalls.push(capture); + return createRecordModel(orderRowsByType.current || [], capture); + }, + async getHistoryModel(warehouseId) { + const capture = { + method: 'getHistoryModel', + warehouseId, + }; + captures.orderFactoryCalls.push(capture); + return createRecordModel(orderRowsByType.history || [], capture); + }, + async getDispatchModel(warehouseId) { + const capture = { + method: 'getDispatchModel', + warehouseId, + }; + captures.orderFactoryCalls.push(capture); + return createRecordModel(orderRowsByType.dispatch || [], capture); + }, + async getOutsourcedModel(warehouseId) { + const capture = { + method: 'getOutsourcedModel', + warehouseId, + }; + captures.orderFactoryCalls.push(capture); + return createRecordModel(orderRowsByType.outsourced || [], capture); + }, + }, + OrderItemsFactory: { + async getCurrentModel(warehouseId) { + const capture = { + method: 'getCurrentModel', + warehouseId, + }; + captures.itemFactoryCalls.push(capture); + return createRecordModel(itemRowsByType.current || [], capture); + }, + async getHistoryModel(warehouseId) { + const capture = { + method: 'getHistoryModel', + warehouseId, + }; + captures.itemFactoryCalls.push(capture); + return createRecordModel(itemRowsByType.history || [], capture); + }, + async getDispatchModel(warehouseId) { + const capture = { + method: 'getDispatchModel', + warehouseId, + }; + captures.itemFactoryCalls.push(capture); + return createRecordModel(itemRowsByType.dispatch || [], capture); + }, + async getOrCreateModel(warehouseId, type) { + const capture = { + method: 'getOrCreateModel', + warehouseId, + type, + }; + captures.itemFactoryCalls.push(capture); + return createRecordModel(itemRowsByType[type] || [], capture); + }, + }, + OrderExpress: { + async findAll(options = {}) { + captures.expressQueries.push(options); + const orderId = Number(options?.where?.order_id || 0); + return (expressRowsByOrderId[orderId] || []).map(row => ({ ...row })); + }, + }, + }, + }; + + return { + service: new OrderIndexService(ctx), + ctx, + captures, + }; + } + + function createAuthService(userOverrides = {}) { + const ctx = { + header: { + platform: 'web', + project: 'all', + }, + set() {}, + app: { + config: { + jwt: { + secret: 'test-secret', + expiresIn: '3600', + }, + }, + jwt: { + verify() { + return { + id: 1, + exp: Math.floor(Date.now() / 1000) + 3600, + }; + }, + sign() { + return 'refreshed-token'; + }, + }, + }, + service: { + systems: { + auth: { + user: { + async findById() { + return { + id: 1, + username: 'tester', + status: 1, + auth_end: '2099-12-31 23:59:59', + permissions: [], + ...userOverrides, + }; + }, + }, + }, + }, + }, + }; + + return new OrderIndexService(ctx); + } + + it('should inject current store_id into buildWhere', () => { + const service = createService(100001); + const where = service.buildWhere({ step: 1 }); + + assert.equal(where.warehouse_id, 100001); assert.equal(where.step, 1); assert.equal(Object.prototype.hasOwnProperty.call(where, 'audit_status'), false); }); @@ -33,11 +210,372 @@ describe('test/app/service/systemMethods/order.base.step.test.js', () => { operator: 'in', value: [ 0, 1, 2 ], }, - }, 100000); + }); assert.equal(where.warehouse_id, 100000); assert.deepEqual(where.step, { [Sequelize.Op.in]: [ 0, 1, 2 ], }); }); + + it('should reject warehouse fields in buildWhere input', () => { + const service = createService(); + + assert.throws(() => { + service.buildWhere({ + warehouse_id: 100000, + }); + }, /禁止传入 warehouse_id \/ warehouseId/); + + assert.throws(() => { + service.buildWhere({ + warehouseId: 100000, + }); + }, /禁止传入 warehouse_id \/ warehouseId/); + }); + + it('should cap pageSize and keep deliveryOrder step filter in listByModule', async () => { + const rows = buildRows(250, index => ({ + step: index < 230 ? 1 : 2, + dispatch_lane: 'm4', + })); + const { service, captures } = createOrderHarness(OrderBaseService, { + rowsByModule: { + deliveryOrder: rows, + }, + }); + + const result = await service.listByModule('deliveryOrder', { + pagination: { + page: 1, + pageSize: 999, + }, + where: { + step: 1, + }, + }); + + assert.equal(result.pagination.page, 1); + assert.equal(result.pagination.pageSize, 200); + assert.equal(result.pagination.total, 230); + assert.equal(result.list.length, 200); + assert.ok(result.list.every(item => item.step === 1)); + assert.equal(captures[0].moduleName, 'deliveryOrder'); + assert.equal(captures[0].findOptions.limit, 200); + assert.equal(captures[0].findOptions.offset, 0); + }); + + it('should use current store_id in listByModule and reject warehouse bypass fields', async () => { + const rows = buildRows(6, () => ({ + warehouse_id: 100001, + step: 1, + })); + const { service, captures } = createOrderHarness(OrderBaseService, { + storeId: 100001, + rowsByModule: { + order: rows, + }, + }); + + const result = await service.listByModule('order', { + pagination: { + page: 1, + pageSize: 10, + }, + where: { + step: 1, + }, + }); + + assert.equal(result.pagination.total, 6); + assert.equal(captures[0].countWhere.warehouse_id, 100001); + assert.equal(captures[0].findOptions.where.warehouse_id, 100001); + assert.ok(result.list.every(item => item.warehouse_id === 100001)); + + await assert.rejects(() => service.listByModule('order', { + where: { + warehouse_id: 100001, + }, + }), /禁止传入 warehouse_id \/ warehouseId/); + }); + + it('should keep pendingOrder hidden for padding rows while outboundOrder still exposes none and padding', async () => { + const { service } = createOrderHarness(OrderBaseService, { + rowsByModule: { + pendingOrder: [ + { + id: 1, + warehouse_id: 100000, + step: 1, + outbound_status: 'none', + updated_at: '2026-04-12 00:00:00', + }, + { + id: 2, + warehouse_id: 100000, + step: 2, + outbound_status: 'padding', + updated_at: '2026-04-12 00:00:00', + }, + { + id: 3, + warehouse_id: 100000, + step: 1, + outbound_status: 'padding', + updated_at: '2026-04-12 00:00:00', + }, + { + id: 4, + warehouse_id: 100001, + step: 1, + outbound_status: 'none', + updated_at: '2026-04-12 00:00:00', + }, + ], + outboundOrder: [ + { + id: 1, + warehouse_id: 100000, + step: 1, + outbound_status: 'none', + updated_at: '2026-04-12 00:00:00', + }, + { + id: 2, + warehouse_id: 100000, + step: 2, + outbound_status: 'padding', + updated_at: '2026-04-12 00:00:00', + }, + { + id: 3, + warehouse_id: 100000, + step: 1, + outbound_status: 'padding', + updated_at: '2026-04-12 00:00:00', + }, + { + id: 4, + warehouse_id: 100001, + step: 1, + outbound_status: 'none', + updated_at: '2026-04-12 00:00:00', + }, + ], + }, + }); + + const pendingResult = await service.listByModule('pendingOrder', {}); + const outboundResult = await service.listByModule('outboundOrder', {}); + + assert.deepEqual(pendingResult.list.map(item => item.id), [ 1 ]); + assert.ok(pendingResult.list.every(item => item.outbound_status !== 'padding')); + assert.deepEqual(outboundResult.list.map(item => item.id), [ 1, 2, 3 ]); + assert.ok(outboundResult.list.some(item => item.outbound_status === 'padding')); + assert.ok(outboundResult.list.some(item => item.outbound_status === 'none')); + assert.ok(outboundResult.list.every(item => item.warehouse_id === 100000)); + }); + + it('should attach express numbers and normalize sys names in all order lists', async () => { + const rows = buildRows(2, index => ({ + id: index + 1, + warehouse_id: 100000, + sys_platform_name: index === 0 ? '淘宝' : null, + sys_logistics_name: index === 0 ? '申通' : undefined, + })); + const { service } = createOrderHarness(OrderBaseService, { + rowsByModule: { + order: rows, + }, + }); + + service.ctx.model = { + OrderExpress: { + async findAll({ where }) { + const orderIds = Array.isArray(where && where.order_id && where.order_id[Sequelize.Op.in]) + ? where.order_id[Sequelize.Op.in] + : []; + + return orderIds.flatMap(orderId => { + if (Number(orderId) === 1) { + return [ + { + id: 11, + order_id: 1, + waybill_code: 'WB-001', + }, + { + id: 12, + order_id: 1, + waybill_code: 'WB-002', + }, + ]; + } + + if (Number(orderId) === 2) { + return [ + { + id: 21, + order_id: 2, + waybill_code: 'WB-003', + }, + ]; + } + + return []; + }); + }, + }, + }; + + const result = await service.listByModule('order', { + pagination: { + page: 1, + pageSize: 10, + }, + where: {}, + }); + + assert.deepEqual(result.list[0].express_numbers, [ 'WB-001', 'WB-002' ]); + assert.deepEqual(result.list[0].waybill_codes, [ 'WB-001', 'WB-002' ]); + assert.deepEqual(result.list[1].express_numbers, [ 'WB-003' ]); + assert.deepEqual(result.list[1].waybill_codes, [ 'WB-003' ]); + assert.equal(Object.prototype.hasOwnProperty.call(result.list[0], 'sys_platform_name'), true); + assert.equal(Object.prototype.hasOwnProperty.call(result.list[0], 'sys_logistics_name'), true); + assert.equal(result.list[0].sys_platform_name, '淘宝'); + assert.equal(result.list[0].sys_logistics_name, '申通'); + assert.equal(result.list[1].sys_platform_name, null); + assert.equal(result.list[1].sys_logistics_name, null); + }); + + it('should query detail by tableType and return orderItems, items, expresses and waybill_codes', async () => { + const { service, captures } = createDetailHarness({ + storeId: 100001, + orderRowsByType: { + history: [ + { + id: 501, + warehouse_id: 100001, + delivery_order_code: 'HIS-501', + step: 2, + }, + ], + }, + itemRowsByType: { + history: [ + { + id: 11, + order_id: 501, + item_code: 'SKU-001', + plan_qty: 2, + }, + { + id: 12, + order_id: 501, + item_code: 'SKU-002', + plan_qty: 1, + }, + ], + }, + expressRowsByOrderId: { + 501: [ + { + waybill_code: 'WB-501-A', + logistics_code: 'LC-A', + logistics_name: '物流A', + logistics_interface_id: '88', + }, + { + waybill_code: 'WB-501-B', + logistics_code: 'LC-B', + logistics_name: '物流B', + logistics_interface_id: 99, + }, + ], + }, + }); + + const result = await service.detail({ + id: 501, + tableType: 'history', + }); + + assert.equal(captures.orderFactoryCalls[0].method, 'getHistoryModel'); + assert.equal(captures.orderFactoryCalls[0].warehouseId, 100001); + assert.equal(captures.itemFactoryCalls[0].method, 'getHistoryModel'); + assert.equal(captures.itemFactoryCalls[0].warehouseId, 100001); + assert.equal(captures.expressQueries[0].where.order_id, 501); + assert.deepEqual(result.order, { + id: 501, + warehouse_id: 100001, + delivery_order_code: 'HIS-501', + step: 2, + }); + assert.strictEqual(result.order, result.detail); + assert.deepEqual(result.orderItems, [ + { + id: 11, + order_id: 501, + item_code: 'SKU-001', + plan_qty: 2, + }, + { + id: 12, + order_id: 501, + item_code: 'SKU-002', + plan_qty: 1, + }, + ]); + assert.deepEqual(result.items, result.orderItems); + assert.deepEqual(result.expresses, [ + { + waybill_code: 'WB-501-A', + logistics_code: 'LC-A', + logistics_name: '物流A', + logistics_interface_id: 88, + }, + { + waybill_code: 'WB-501-B', + logistics_code: 'LC-B', + logistics_name: '物流B', + logistics_interface_id: 99, + }, + ]); + assert.deepEqual(result.waybill_codes, [ 'WB-501-A', 'WB-501-B' ]); + }); + + it('should use current store_id as isolation condition in detail lookup', async () => { + const { service, captures } = createDetailHarness({ + storeId: 100002, + orderRowsByType: { + current: [ + { + id: 601, + warehouse_id: 100001, + delivery_order_code: 'CUR-601', + step: 1, + }, + ], + }, + }); + + await assert.rejects(() => service.detail({ + id: 601, + tableType: 'current', + }), /订单不存在或不属于当前仓库/); + + assert.equal(captures.orderFactoryCalls[0].method, 'getCurrentModel'); + assert.equal(captures.orderFactoryCalls[0].findOneOptions.where.warehouse_id, 100002); + assert.equal(captures.itemFactoryCalls.length, 0); + assert.equal(captures.expressQueries.length, 0); + }); + + it('should allow detail in the order permission white list', async () => { + const service = createAuthService(); + + const result = await service.checkAuth('order', 'detail', 'Bearer test-token'); + + assert.equal(result.status, 200); + assert.equal(result.message, 'ok'); + }); }); diff --git a/test/app/service/systemMethods/order/storageAllocation.test.js b/test/app/service/systemMethods/order/storageAllocation.test.js new file mode 100644 index 0000000..a9176bd --- /dev/null +++ b/test/app/service/systemMethods/order/storageAllocation.test.js @@ -0,0 +1,63 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const StorageAllocationMethodService = require('../../../../../app/service/systemMethods/order/storageAllocation'); + +/** + * 创建系统方法测试上下文。 + * + * @return {{ ctx: Object, capture: Object }} 测试上下文。 + */ +function createHarness() { + const capture = { + request: null, + }; + + const ctx = { + app: {}, + service: { + systems: { + orderStorageAllocation: { + async allocateStorage(request) { + capture.request = request; + return { + code: 200, + message: '储位分配完成', + data: { + ok: true, + }, + }; + }, + }, + }, + }, + }; + + return { + ctx, + capture, + }; +} + +describe('test/app/service/systemMethods/order/storageAllocation.test.js', () => { + it('should normalize allocation input before delegating to the public service', async () => { + const { ctx, capture } = createHarness(); + const service = new StorageAllocationMethodService(ctx); + + const result = await service.allocateStorage({ + allowStorageLocation: true, + ids: '1,2,3', + warehouseId: 100000, + }); + + assert.deepEqual(capture.request, { + allow_storage_location: true, + order_ids: '1,2,3', + warehouse_id: 100000, + }); + assert.equal(result.flag, 'success'); + assert.equal(result.message, '储位分配完成'); + assert.equal(result.code, 200); + assert.deepEqual(result.data, { ok: true }); + }); +}); diff --git a/test/app/service/systemMethods/setting/express.test.js b/test/app/service/systemMethods/setting/express.test.js new file mode 100644 index 0000000..d6f4fb3 --- /dev/null +++ b/test/app/service/systemMethods/setting/express.test.js @@ -0,0 +1,178 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const ExpressMethodService = require('../../../../../app/service/systemMethods/setting/express'); + +function createContext() { + const calls = { + list: [], + create: [], + update: [], + checkCodeUnique: [], + listBase: 0, + prepareWhereContext: 0, + }; + + const ctx = { + app: { + config: { + jwt: {}, + }, + Sequelize: {}, + }, + service: { + systems: { + setting: { + express: { + async list(payload) { + calls.list.push(payload); + payload.touched = true; + return { + code: 200, + data: { + list: [ + { id: 1, code: 'SF-001' }, + ], + }, + }; + }, + async listBase() { + calls.listBase += 1; + return { + code: 200, + data: [ + { code: 'SF', name: '顺丰' }, + ], + }; + }, + async create(payload) { + calls.create.push(payload); + payload.touched = true; + return { + code: 200, + data: { + id: 99, + }, + }; + }, + async checkCodeUnique(payload) { + calls.checkCodeUnique.push(payload); + return { + code: 200, + data: { + isUnique: true, + }, + }; + }, + async update(payload) { + calls.update.push(payload); + payload.touched = true; + return { + code: 200, + data: { + id: 11, + }, + }; + }, + }, + }, + }, + }, + }; + + return { + ctx, + calls, + }; +} + +describe('test/app/service/systemMethods/setting/express.test.js', () => { + it('should copy payload before calling list', async () => { + const { ctx, calls } = createContext(); + const service = new ExpressMethodService(ctx); + service.prepareWhereContext = function prepareWhereContext(data) { + calls.prepareWhereContext += 1; + data.where = { + quickWhere: 'SF', + }; + return data; + }; + + const payload = { + page: 1, + page_size: 20, + where: { + quickWhere: 'SF', + }, + extra: { + keep: true, + }, + }; + + const result = await service.list(payload); + + assert.equal(result.flag, 'success'); + assert.equal(result.message, 'ok'); + assert.equal(calls.prepareWhereContext, 1); + assert.equal(calls.list.length, 1); + assert.notStrictEqual(calls.list[0], payload); + assert.equal(payload.touched, undefined); + assert.deepEqual(calls.list[0].where, { quickWhere: 'SF' }); + assert.deepEqual(calls.list[0].pagination, { + page: 1, + pageSize: 20, + }); + }); + + it('should forward normalized create payload and keep the original payload intact', async () => { + const { ctx, calls } = createContext(); + const service = new ExpressMethodService(ctx); + + const payload = { + code: 'sf-001', + name: '顺丰设置', + express_code: 'SF', + extra: { + keep: true, + }, + }; + + const result = await service.create(payload); + + assert.equal(result.flag, 'success'); + assert.equal(result.message, 'ok'); + assert.equal(calls.create.length, 1); + assert.notStrictEqual(calls.create[0], payload); + assert.deepEqual(calls.create[0], { + code: 'sf-001', + name: '顺丰设置', + express_code: 'SF', + extra: { + keep: true, + }, + touched: true, + }); + assert.equal(payload.touched, undefined); + }); + + it('should delegate listBase and checkCodeUnique to the setting express service', async () => { + const { ctx, calls } = createContext(); + const service = new ExpressMethodService(ctx); + + const baseResult = await service.listBase(); + const checkResult = await service.checkCodeUnique({ + id: 11, + code: 'SF-001', + }); + + assert.equal(calls.listBase, 1); + assert.equal(calls.checkCodeUnique.length, 1); + assert.deepEqual(calls.checkCodeUnique[0], { + id: 11, + code: 'SF-001', + }); + assert.equal(baseResult.flag, 'success'); + assert.equal(checkResult.flag, 'success'); + assert.equal(checkResult.data.isUnique, true); + }); +}); diff --git a/test/app/service/systemMethods/setting/expressInterface.test.js b/test/app/service/systemMethods/setting/expressInterface.test.js new file mode 100644 index 0000000..d4a36df --- /dev/null +++ b/test/app/service/systemMethods/setting/expressInterface.test.js @@ -0,0 +1,167 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const ExpressInterfaceMethodService = require('../../../../../app/service/systemMethods/setting/expressInterface'); + +function createContext() { + const calls = { + list: [], + create: [], + update: [], + delete: [], + prepareWhereContext: 0, + }; + + const ctx = { + app: { + config: { + jwt: {}, + }, + Sequelize: {}, + }, + service: { + systems: { + setting: { + expressInterface: { + async list(payload) { + calls.list.push(payload); + payload.touched = true; + return { + code: 200, + data: { + list: [ + { id: 1, name: '顺丰接口' }, + ], + }, + }; + }, + async create(payload) { + calls.create.push(payload); + payload.touched = true; + return { + code: 200, + data: { + id: 99, + }, + }; + }, + async update(payload) { + calls.update.push(payload); + payload.touched = true; + return { + code: 200, + data: { + id: 11, + }, + }; + }, + async delete(payload) { + calls.delete.push(payload); + payload.touched = true; + return { + code: 200, + data: { + id: 11, + }, + }; + }, + }, + }, + }, + }, + }; + + return { + ctx, + calls, + }; +} + +describe('test/app/service/systemMethods/setting/expressInterface.test.js', () => { + it('should copy payload before calling list', async () => { + const { ctx, calls } = createContext(); + const service = new ExpressInterfaceMethodService(ctx); + service.prepareWhereContext = function prepareWhereContext(data) { + calls.prepareWhereContext += 1; + data.where = { + quickWhere: '接口', + }; + return data; + }; + + const payload = { + page: 1, + page_size: 20, + where: { + quickWhere: '接口', + }, + extra: { + keep: true, + }, + }; + + const result = await service.list(payload); + + assert.equal(result.flag, 'success'); + assert.equal(result.message, 'ok'); + assert.equal(calls.prepareWhereContext, 1); + assert.equal(calls.list.length, 1); + assert.notStrictEqual(calls.list[0], payload); + assert.equal(payload.touched, undefined); + assert.deepEqual(calls.list[0].where, { quickWhere: '接口' }); + assert.deepEqual(calls.list[0].pagination, { + page: 1, + pageSize: 20, + }); + }); + + it('should forward normalized create update and delete payloads', async () => { + const { ctx, calls } = createContext(); + const service = new ExpressInterfaceMethodService(ctx); + + const createResult = await service.create({ + name: '顺丰接口', + express_code: 'SF', + platform_code: 'TB', + express_platform_id: 1, + extra: { + keep: true, + }, + }); + const updateResult = await service.update({ + id: 11, + name: '顺丰接口-更新', + token: 'token-2', + }); + const deleteResult = await service.delete({ + id: 11, + }); + + assert.equal(createResult.flag, 'success'); + assert.equal(updateResult.flag, 'success'); + assert.equal(deleteResult.flag, 'success'); + assert.equal(calls.create.length, 1); + assert.equal(calls.update.length, 1); + assert.equal(calls.delete.length, 1); + assert.deepEqual(calls.create[0], { + name: '顺丰接口', + express_code: 'SF', + platform_code: 'TB', + express_platform_id: 1, + extra: { + keep: true, + }, + touched: true, + }); + assert.deepEqual(calls.update[0], { + id: 11, + name: '顺丰接口-更新', + token: 'token-2', + touched: true, + }); + assert.deepEqual(calls.delete[0], { + id: 11, + touched: true, + }); + }); +}); diff --git a/test/app/service/systemMethods/setting/platform.test.js b/test/app/service/systemMethods/setting/platform.test.js new file mode 100644 index 0000000..45cdf65 --- /dev/null +++ b/test/app/service/systemMethods/setting/platform.test.js @@ -0,0 +1,186 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const PlatformMethodService = require('../../../../../app/service/systemMethods/setting/platform'); + +function createContext() { + const calls = { + list: [], + create: [], + update: [], + delete: [], + prepareWhereContext: 0, + }; + + const ctx = { + app: { + config: { + jwt: {}, + }, + Sequelize: {}, + }, + service: { + systems: { + setting: { + platform: { + async list(payload) { + calls.list.push(payload); + payload.touched = true; + return { + code: 200, + data: { + list: [ + { id: 1, code: 'TB-STORE' }, + ], + }, + }; + }, + async create(payload) { + calls.create.push(payload); + payload.touched = true; + return { + code: 200, + data: { + id: 99, + }, + }; + }, + async update(payload) { + calls.update.push(payload); + payload.touched = true; + return { + code: 200, + data: { + id: 11, + }, + }; + }, + async delete(payload) { + calls.delete.push(payload); + payload.touched = true; + return { + code: 200, + data: { + id: 11, + }, + }; + }, + }, + }, + }, + }, + }; + + return { + ctx, + calls, + }; +} + +describe('test/app/service/systemMethods/setting/platform.test.js', () => { + it('should copy payload before calling list', async () => { + const { ctx, calls } = createContext(); + const service = new PlatformMethodService(ctx); + service.prepareWhereContext = function prepareWhereContext(data) { + calls.prepareWhereContext += 1; + data.where = { + quickWhere: '设置', + }; + return data; + }; + + const payload = { + page: 1, + page_size: 20, + where: { + quickWhere: '设置', + }, + extra: { + keep: true, + }, + }; + + const result = await service.list(payload); + + assert.equal(result.flag, 'success'); + assert.equal(result.message, 'ok'); + assert.equal(calls.prepareWhereContext, 1); + assert.equal(calls.list.length, 1); + assert.notStrictEqual(calls.list[0], payload); + assert.equal(payload.touched, undefined); + assert.deepEqual(calls.list[0].where, { quickWhere: '设置' }); + assert.deepEqual(calls.list[0].pagination, { + page: 1, + pageSize: 20, + }); + }); + + it('should forward normalized create update and delete payloads', async () => { + const { ctx, calls } = createContext(); + const service = new PlatformMethodService(ctx); + + const createResult = await service.create({ + code: 'TB-STORE', + name: '淘宝设置', + platform_code: 'TB', + extra: { + keep: true, + }, + }); + const updateResult = await service.update({ + id: 11, + code: 'TB-STORE-NEW', + name: '淘宝设置-更新', + platformCode: 'JD', + }); + const deleteResult = await service.delete({ + id: 11, + }); + + assert.equal(createResult.flag, 'success'); + assert.equal(updateResult.flag, 'success'); + assert.equal(deleteResult.flag, 'success'); + assert.equal(calls.create.length, 1); + assert.equal(calls.update.length, 1); + assert.equal(calls.delete.length, 1); + assert.deepEqual(calls.create[0], { + code: 'TB-STORE', + name: '淘宝设置', + platform_code: 'TB', + extra: { + keep: true, + }, + touched: true, + }); + assert.deepEqual(calls.update[0], { + id: 11, + code: 'TB-STORE-NEW', + name: '淘宝设置-更新', + platform_code: 'JD', + touched: true, + }); + assert.deepEqual(calls.delete[0], { + id: 11, + touched: true, + }); + }); + + it('should keep optional update fields omitted when not provided', async () => { + const { ctx, calls } = createContext(); + const service = new PlatformMethodService(ctx); + + const result = await service.update({ + setting_id: 11, + platformCode: 'JD', + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.message, 'ok'); + assert.equal(calls.update.length, 1); + assert.deepEqual(calls.update[0], { + id: 11, + platform_code: 'JD', + touched: true, + }); + }); +}); diff --git a/test/app/service/systems/delivery_order.auditStatus.test.js b/test/app/service/systems/delivery_order.auditStatus.test.js index d14d89a..e016082 100644 --- a/test/app/service/systems/delivery_order.auditStatus.test.js +++ b/test/app/service/systems/delivery_order.auditStatus.test.js @@ -6,6 +6,7 @@ const { app, mm } = require('egg-mock/bootstrap'); describe('test/app/service/systems/delivery_order.auditStatus.test.js', () => { let ctx; let deliveryOrderService; + let cacheStore; /** * Mock StoreWarehouse.findOne,兼容固定返回值或函数实现。 @@ -26,6 +27,12 @@ describe('test/app/service/systems/delivery_order.auditStatus.test.js', () => { beforeEach(() => { ctx = app.mockContext(); deliveryOrderService = ctx.service.systems.deliveryOrder; + cacheStore = new Map(); + + mm(app, 'getCacheAsync', async cacheKey => cacheStore.get(cacheKey)); + mm(app, 'setCacheAsync', async (cacheKey, value) => { + cacheStore.set(cacheKey, value); + }); }); afterEach(() => { @@ -78,12 +85,26 @@ describe('test/app/service/systems/delivery_order.auditStatus.test.js', () => { warehouseId: 100000, }; - // Mock platform check - mm(ctx.service.systems.platform, 'checkPlatformExists', async (platformCode, warehouseId) => { - if (platformCode === 'TAOBAO' && warehouseId === 100000) { - return { code: 'TAOBAO', name: '淘宝' }; - } - return null; + mm(ctx.service.systems.platform, 'getPlatformList', async () => ([ + { code: 'TAOBAO', name: '淘宝' }, + { code: 'TB', name: '淘宝默认' }, + ])); + mm(ctx.service.systems.express, 'getExpressList', async () => ([ + { code: 'STO', name: '申通' }, + ])); + mm(ctx, 'model', { + ...(ctx.model || {}), + Store: { + async findByPk() { + return { + id: 1000000, + subject_config: { + default_platform_code: 'TB', + default_express_code: 'STO', + }, + }; + }, + }, }); // 1. Test with step = 0 @@ -95,5 +116,135 @@ describe('test/app/service/systems/delivery_order.auditStatus.test.js', () => { const preparedDataApproved = await deliveryOrderService.prepareOrderData(deliveryOrder, info, 1); assert.ok(preparedDataApproved, 'preparedDataApproved should not be null'); assert.equal(preparedDataApproved.step, 1, 'step should be 1'); + assert.equal(preparedDataApproved.source_platform_code, 'TAOBAO'); + assert.equal(preparedDataApproved.sys_platform_code, 'TAOBAO'); + }); + + it('should fallback invalid platform and logistics codes to cached store defaults without overwriting source fields', async () => { + const deliveryOrder = { + deliveryOrderCode: 'TEST_ORDER_002', + sourcePlatformCode: 'INVALID_PLATFORM', + sourcePlatformName: '外部平台', + logisticsCode: 'INVALID_EXPRESS', + logisticsName: '外部快递', + expressCode: 'YT', + receiverInfo: { name: 'test' }, + }; + const info = { + storeId: 1000000, + warehouseId: 100000, + }; + + let findByPkCallCount = 0; + mm(ctx, 'model', { + ...(ctx.model || {}), + Store: { + async findByPk() { + findByPkCallCount += 1; + return { + id: 1000000, + subject_config: { + default_platform_code: 'TB', + default_express_code: 'STO', + }, + }; + }, + }, + }); + mm(ctx.service.systems.platform, 'getPlatformList', async () => ([ + { code: 'TB', name: '淘宝' }, + { code: 'JD', name: '京东' }, + ])); + mm(ctx.service.systems.express, 'getExpressList', async () => ([ + { code: 'STO', name: '申通' }, + { code: 'YTO', name: '圆通' }, + ])); + + const firstPrepared = await deliveryOrderService.prepareOrderData(deliveryOrder, info, 1); + const secondPrepared = await deliveryOrderService.prepareOrderData(deliveryOrder, info, 1); + + assert.equal(firstPrepared.source_platform_code, 'INVALID_PLATFORM'); + assert.equal(firstPrepared.source_platform_name, '外部平台'); + assert.equal(firstPrepared.sys_platform_code, 'TB'); + assert.equal(firstPrepared.sys_platform_name, '淘宝'); + assert.equal(firstPrepared.logistics_code, 'INVALID_EXPRESS'); + assert.equal(firstPrepared.logistics_name, '外部快递'); + assert.equal(firstPrepared.sys_logistics_code, 'STO'); + assert.equal(firstPrepared.sys_logistics_name, '申通'); + assert.equal(firstPrepared.express_code, 'YT'); + + assert.equal(secondPrepared.sys_platform_code, 'TB'); + assert.equal(secondPrepared.sys_logistics_code, 'STO'); + assert.equal(findByPkCallCount, 1, 'store subject_config should be loaded from cache on second call'); + }); + + it('should resolve platform setting code to the real system platform code and name', async () => { + const deliveryOrder = { + deliveryOrderCode: 'TEST_ORDER_003', + sourcePlatformCode: 'TB-SETTING', + sourcePlatformName: '外部平台设置码', + receiverInfo: { name: 'test' }, + }; + const info = { + storeId: 1000000, + warehouseId: 100000, + }; + + mm(ctx, 'model', { + ...(ctx.model || {}), + Store: { + async findByPk() { + return { + id: 1000000, + subject_config: { + default_platform_code: 'JD', + default_express_code: 'STO', + }, + }; + }, + }, + }); + mm(ctx.service.systems.platform, 'getPlatformList', async () => ([ + { code: 'TB', name: '淘宝平台', value: 'TB', label: '淘宝平台', platform_code: 'TB', platform_name: '淘宝平台', is_system_setting: false }, + { code: 'TB-SETTING', name: 'TB-SETTING (淘宝平台)', value: 'TB-SETTING', label: 'TB-SETTING (淘宝平台)', platform_code: 'TB', platform_name: '淘宝平台', is_system_setting: true }, + { code: 'JD', name: '京东平台', value: 'JD', label: '京东平台', platform_code: 'JD', platform_name: '京东平台', is_system_setting: false }, + ])); + mm(ctx.service.systems.express, 'getExpressList', async () => ([ + { code: 'STO', name: '申通' }, + ])); + + const snapshot = await deliveryOrderService.resolvePlatformSnapshot('TB-SETTING', { + default_platform_code: 'JD', + default_express_code: 'STO', + }, { + warehouseId: info.warehouseId, + deliveryOrderCode: deliveryOrder.deliveryOrderCode, + storeId: info.storeId, + }); + + assert.deepEqual(snapshot, { + sysPlatformCode: 'TB', + sysPlatformName: '淘宝平台', + }); + }); + + it('should resolve merged express settings to the real express code', async () => { + mm(ctx.service.systems.express, 'getExpressList', async () => ([ + { code: 'STO', name: '顺丰', value: 'STO', label: '顺丰' }, + { code: 'SF-SETTING', name: 'SF-SETTING (顺丰)', value: 'SF-SETTING', label: 'SF-SETTING (顺丰)', express_code: 'STO', warehouse_id: 100000 }, + ])); + + const snapshot = await deliveryOrderService.resolveExpressSnapshot('SF-SETTING', { + default_express_code: 'TB', + }, { + warehouseId: 100000, + deliveryOrderCode: 'TEST_ORDER_003', + storeId: 1000000, + }); + + assert.deepEqual(snapshot, { + sysLogisticsCode: 'STO', + sysLogisticsName: 'SF-SETTING (顺丰)', + }); }); }); diff --git a/test/app/service/systems/delivery_order.oversell.test.js b/test/app/service/systems/delivery_order.oversell.test.js index 7c27cd6..c3fd5a3 100644 --- a/test/app/service/systems/delivery_order.oversell.test.js +++ b/test/app/service/systems/delivery_order.oversell.test.js @@ -76,6 +76,21 @@ function createHarness({ allowOversell }) { warehouse_code: 'WH-001', item_code: 'SKU-ZERO', item_name: '零库存商品', + goods_code: 'GOODS-ZERO', + sku_property: '颜色:黑', + stock_unit: '件', + gross_weight: 2, + net_weight: 1.5, + length: 10, + width: 20, + height: 30, + volume: 6000, + retail_price: 88.5, + barcode: 'BAR-ZERO', + brand_name: '测试品牌', + category_id: 9, + category_name: '测试分类', + item_type: 'normal', }; }, }, @@ -188,6 +203,33 @@ describe('test/app/service/systems/delivery_order.oversell.test.js', () => { assert.equal(result.stock_count, 1); assert.equal(result.item_total_count, 1); assert.equal(calls.bulkCreateArgs.rows.length, 1); + assert.equal(calls.bulkCreateArgs.rows[0].item_id, 1); + assert.equal(calls.bulkCreateArgs.rows[0].stock_id, 9001); + assert.deepEqual(calls.bulkCreateArgs.rows[0].item_snapshot, { + id: 1, + stock_id: 9001, + item_code: 'SKU-ZERO', + item_name: '零库存商品', + goods_code: 'GOODS-ZERO', + sku_property: '颜色:黑', + barcode: 'BAR-ZERO', + brand_name: '测试品牌', + category_id: 9, + category_name: '测试分类', + item_type: 'normal', + stock_unit: '件', + inventory_type: 'ZP', + retail_price: 88.5, + gross_weight: 2, + net_weight: 1.5, + length: 10, + width: 20, + height: 30, + volume: 6000, + }); + assert.equal(calls.bulkCreateArgs.rows[0].storage_id, undefined); + assert.equal(calls.bulkCreateArgs.rows[0].space_id, undefined); + assert.equal(calls.bulkCreateArgs.rows[0].stock_snapshot, undefined); assert.equal(stockWarehouseInstance.locked_quantity, 1); }); diff --git a/test/app/service/systems/excel.test.js b/test/app/service/systems/excel.test.js index 5e0e710..1dd247a 100644 --- a/test/app/service/systems/excel.test.js +++ b/test/app/service/systems/excel.test.js @@ -1,6 +1,9 @@ 'use strict'; const assert = require('node:assert/strict'); +const fs = require('node:fs/promises'); +const os = require('node:os'); +const path = require('node:path'); const XLSX = require('xlsx'); const ExcelService = require('../../../../app/service/systems/excel'); @@ -158,6 +161,48 @@ describe('test/app/service/systems/excel.test.js', () => { assert.equal(result.fileRecord.fileId, 9527); }); + it('should write files atomically without touching the target path directly', async () => { + const { service } = createService(); + const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'wms-excel-')); + const targetPath = path.join(tempDir, '收货报表.xlsx'); + const writeCalls = []; + const originalWriteFile = fs.writeFile; + + fs.writeFile = async function patchedWriteFile(filePath, ...args) { + writeCalls.push(String(filePath)); + return originalWriteFile.call(this, filePath, ...args); + }; + + try { + await service.writeFile(targetPath, { + sheets: [ + { + name: '报表', + columns: [ + { header: '单号', key: 'order_no' }, + ], + rows: [ + { order_no: 'RK1001' }, + ], + }, + ], + }); + } finally { + fs.writeFile = originalWriteFile; + } + + assert.ok(writeCalls.length > 0); + assert.ok(writeCalls.every(filePath => filePath !== targetPath)); + + const buffer = await fs.readFile(targetPath); + assert.ok(buffer.length > 0); + + const workbook = XLSX.read(buffer, { type: 'buffer' }); + assert.deepEqual(workbook.SheetNames, [ '报表' ]); + + await fs.rm(tempDir, { recursive: true, force: true }); + }); + it('should honor skipHeader when object rows are used', async () => { const { service } = createService(); diff --git a/test/app/service/systems/express.test.js b/test/app/service/systems/express.test.js new file mode 100644 index 0000000..1a5e87f --- /dev/null +++ b/test/app/service/systems/express.test.js @@ -0,0 +1,302 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const ExpressService = require('../../../../app/service/systems/express'); +const IndexMethodService = require('../../../../app/service/systemMethods/index'); + +function createExpressServiceHarness(options = {}) { + const calls = { + expressFindAll: 0, + expressSettingFindAll: 0, + expressProductTypeFindAll: 0, + getCache: 0, + setCache: 0, + }; + + const ctx = { + app: { + async getCacheAsync(cacheKey) { + calls.getCache += 1; + if (typeof options.getCacheAsync === 'function') { + return await options.getCacheAsync(cacheKey); + } + return options.cachedValue === undefined ? null : options.cachedValue; + }, + async setCacheAsync(cacheKey, value, ttl) { + calls.setCache += 1; + calls.cachePayload = { cacheKey, value, ttl }; + if (typeof options.setCacheAsync === 'function') { + return await options.setCacheAsync(cacheKey, value, ttl); + } + }, + }, + user: options.user || null, + model: { + Express: { + async findAll(query) { + calls.expressFindAll += 1; + calls.expressFindAllQuery = query; + return options.rows || [ + { code: 'STO', name: '顺丰' }, + { code: 'TB', name: '淘宝快递' }, + ]; + }, + }, + ExpressSetting: { + async findAll(query) { + calls.expressSettingFindAll += 1; + calls.expressSettingFindAllQuery = query; + return options.expressSettingRows || []; + }, + }, + ExpressProductType: { + async findAll(query) { + calls.expressProductTypeFindAll += 1; + calls.expressProductTypeFindAllQuery = query; + return options.expressProductTypeRows || [ + { code: 'SF-EXP', name: '顺丰标准', express_code: 'SF' }, + { code: 'SF-ECON', name: '顺丰经济', express_code: 'SF' }, + ]; + }, + }, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + }; + + return { + ctx, + calls, + }; +} + +describe('test/app/service/systems/express.test.js', () => { + it('should load express list from database and cache it when cache is empty', async () => { + const { ctx, calls } = createExpressServiceHarness(); + const service = new ExpressService(ctx); + + const result = await service.getExpressList(); + + assert.equal(calls.getCache, 1); + assert.equal(calls.expressFindAll, 1); + assert.equal(calls.setCache, 1); + assert.equal(calls.cachePayload.cacheKey, 'express:list'); + assert.equal(calls.cachePayload.ttl, 600); + assert.deepEqual(result, [ + { code: 'STO', name: '顺丰', value: 'STO', label: '顺丰', is_system_setting: false, id: null, alias: null }, + { code: 'TB', name: '淘宝快递', value: 'TB', label: '淘宝快递', is_system_setting: false, id: null, alias: null }, + ]); + }); + + it('should merge express settings for the current warehouse and keep real express codes', async () => { + const { ctx, calls } = createExpressServiceHarness({ + user: { + store_id: 100000, + }, + rows: [ + { code: 'SF', name: '顺丰' }, + { code: 'YTO', name: '圆通' }, + ], + expressSettingRows: [ + { id: 11, code: 'SF-001', name: '顺丰设置', express_code: 'SF', warehouse_id: 100000 }, + { id: 12, code: 'SF-001', name: '圆通设置', express_code: 'YTO', warehouse_id: 100000 }, + { id: 13, code: 'YTO-001', name: '圆通设置', express_code: 'YTO', warehouse_id: 100000 }, + ], + }); + const service = new ExpressService(ctx); + + const result = await service.getExpressList(); + + assert.equal(calls.getCache, 1); + assert.equal(calls.expressFindAll, 1); + assert.equal(calls.expressSettingFindAll, 1); + assert.deepEqual(calls.expressSettingFindAllQuery.where, { warehouse_id: 100000 }); + assert.equal(calls.cachePayload.cacheKey, 'express:list:100000'); + assert.deepEqual(result, [ + { code: 'SF', name: '顺丰', value: 'SF', label: '顺丰', is_system_setting: false, id: null, alias: null }, + { code: 'YTO', name: '圆通', value: 'YTO', label: '圆通', is_system_setting: false, id: null, alias: null }, + { code: 'SF-001', name: 'SF-001 (顺丰)', value: 'SF-001', label: 'SF-001 (顺丰)', express_code: 'SF', is_system_setting: true, id: 11, alias: '顺丰设置' }, + { code: 'YTO-001', name: 'YTO-001 (圆通)', value: 'YTO-001', label: 'YTO-001 (圆通)', express_code: 'YTO', is_system_setting: true, id: 13, alias: '圆通设置' }, + ]); + }); + + it('should keep original express rows when a setting uses the same code', async () => { + const { ctx, calls } = createExpressServiceHarness({ + user: { + store_id: 100000, + }, + expressSettingRows: [ + { id: 21, code: 'STO', name: '系统同码设置', express_code: 'STO', warehouse_id: 100000 }, + { id: 22, code: 'SF-SETTING', name: '顺丰设置', express_code: 'STO', warehouse_id: 100000 }, + ], + }); + const service = new ExpressService(ctx); + + const result = await service.getExpressList(); + + assert.equal(calls.getCache, 1); + assert.equal(calls.expressFindAll, 1); + assert.equal(calls.expressSettingFindAll, 1); + assert.deepEqual(result.slice(0, 2), [ + { code: 'STO', name: '顺丰', value: 'STO', label: '顺丰', is_system_setting: false, id: null, alias: null }, + { code: 'TB', name: '淘宝快递', value: 'TB', label: '淘宝快递', is_system_setting: false, id: null, alias: null }, + ]); + assert.deepEqual(result, [ + { code: 'STO', name: '顺丰', value: 'STO', label: '顺丰', is_system_setting: false, id: null, alias: null }, + { code: 'TB', name: '淘宝快递', value: 'TB', label: '淘宝快递', is_system_setting: false, id: null, alias: null }, + { code: 'SF-SETTING', name: 'SF-SETTING (顺丰)', value: 'SF-SETTING', label: 'SF-SETTING (顺丰)', express_code: 'STO', is_system_setting: true, id: 22, alias: '顺丰设置' }, + ]); + }); + + it('should return cached express list without querying database', async () => { + const cachedValue = [ + { code: 'SF', name: '顺丰', value: 'SF', label: '顺丰', is_system_setting: false, id: null, alias: null }, + ]; + const { ctx, calls } = createExpressServiceHarness({ + cachedValue, + }); + const service = new ExpressService(ctx); + + const result = await service.getExpressList(); + + assert.equal(calls.getCache, 1); + assert.equal(calls.expressFindAll, 0); + assert.equal(calls.setCache, 0); + assert.deepEqual(result, cachedValue); + }); + + it('should load express product types from database and cache them when cache is empty', async () => { + const { ctx, calls } = createExpressServiceHarness(); + const service = new ExpressService(ctx); + + const result = await service.getExpressProductTypeList(); + + assert.equal(calls.getCache, 1); + assert.equal(calls.expressProductTypeFindAll, 1); + assert.equal(calls.setCache, 1); + assert.equal(calls.cachePayload.cacheKey, 'express:product-type:list'); + assert.equal(calls.cachePayload.ttl, 3600); + assert.deepEqual(result, [ + { code: 'SF-EXP', express_code: 'SF', name: '顺丰标准', value: 'SF-EXP', label: '顺丰标准' }, + { code: 'SF-ECON', express_code: 'SF', name: '顺丰经济', value: 'SF-ECON', label: '顺丰经济' }, + ]); + }); + + it('should load express product types by express code and cache them with code-specific key', async () => { + const { ctx, calls } = createExpressServiceHarness({ + expressProductTypeRows: [ + { code: 'SF-EXP', name: '顺丰标准', express_code: 'SF' }, + ], + }); + const service = new ExpressService(ctx); + + const result = await service.getExpressProductTypeList('SF'); + + assert.equal(calls.getCache, 1); + assert.equal(calls.expressProductTypeFindAll, 1); + assert.deepEqual(calls.expressProductTypeFindAllQuery.where, { express_code: 'SF' }); + assert.equal(calls.setCache, 1); + assert.equal(calls.cachePayload.cacheKey, 'express:product-type:list:SF'); + assert.equal(calls.cachePayload.ttl, 3600); + assert.deepEqual(result, [ + { code: 'SF-EXP', express_code: 'SF', name: '顺丰标准', value: 'SF-EXP', label: '顺丰标准' }, + ]); + }); + + it('should return cached express product types without querying database', async () => { + const cachedValue = [ + { code: 'SF-EXP', express_code: 'SF', name: '顺丰标准', value: 'SF-EXP', label: '顺丰标准' }, + ]; + const { ctx, calls } = createExpressServiceHarness({ + cachedValue, + }); + const service = new ExpressService(ctx); + + const result = await service.getExpressProductTypeList('SF'); + + assert.equal(calls.getCache, 1); + assert.equal(calls.expressProductTypeFindAll, 0); + assert.equal(calls.setCache, 0); + + it('should load system express list without merging warehouse settings', async () => { + const { ctx, calls } = createExpressServiceHarness({ + rows: [ + { code: 'SF', name: '顺丰' }, + ], + }); + const service = new ExpressService(ctx); + + const result = await service.getSystemExpressList(); + + assert.equal(calls.getCache, 0); + assert.equal(calls.expressFindAll, 1); + assert.equal(calls.expressSettingFindAll, 0); + assert.deepEqual(result, [ + { code: 'SF', name: '顺丰', value: 'SF', label: '顺丰', is_system_setting: false, id: null, alias: null }, + ]); + }); + assert.deepEqual(result, cachedValue); + }); + + it('should delegate index.getExpressList to the express service', async () => { + const { ctx } = createExpressServiceHarness(); + let serviceCalls = 0; + ctx.service = { + systems: { + express: { + async getExpressList() { + serviceCalls += 1; + return [ + { code: 'STO', name: '顺丰', value: 'STO', label: '顺丰' }, + ]; + }, + }, + }, + }; + + const methodService = new IndexMethodService(ctx); + const result = await methodService.getExpressList(); + + assert.equal(serviceCalls, 1); + assert.equal(result.flag, 'success'); + assert.equal(result.message, 'ok'); + assert.equal(result.code, 200); + assert.deepEqual(result.data, [ + { code: 'STO', name: '顺丰', value: 'STO', label: '顺丰' }, + ]); + }); + + it('should delegate index.getExpressProductTypeList to the express service', async () => { + const { ctx } = createExpressServiceHarness(); + let serviceCalls = 0; + let receivedExpressCode = ''; + ctx.service = { + systems: { + express: { + async getExpressProductTypeList(expressCode) { + serviceCalls += 1; + receivedExpressCode = expressCode; + return [ + { code: 'SF-EXP', express_code: 'SF', name: '顺丰标准', value: 'SF-EXP', label: '顺丰标准' }, + ]; + }, + }, + }, + }; + + const methodService = new IndexMethodService(ctx); + const result = await methodService.getExpressProductTypeList({ express_code: 'SF' }); + + assert.equal(serviceCalls, 1); + assert.equal(receivedExpressCode, 'SF'); + assert.equal(result.flag, 'success'); + assert.equal(result.message, 'ok'); + assert.equal(result.code, 200); + assert.deepEqual(result.data, [ + { code: 'SF-EXP', express_code: 'SF', name: '顺丰标准', value: 'SF-EXP', label: '顺丰标准' }, + ]); + }); +}); diff --git a/test/app/service/systems/notice.test.js b/test/app/service/systems/notice.test.js index 8f46390..2707ef6 100644 --- a/test/app/service/systems/notice.test.js +++ b/test/app/service/systems/notice.test.js @@ -10,14 +10,14 @@ describe('test/app/service/systems/notice.test.js', () => { const webhookRows = [ { id: 1, - store_id: 1000000, + store_id: 100000, hook_type: 'custom', hook_url: 'https://example.com/webhook/a', events: [ 'receiving_completed' ], }, { id: 2, - store_id: 1000000, + store_id: 100000, hook_type: 'custom', hook_url: 'https://example.com/webhook/b', events: [ 'stock.low' ], @@ -31,7 +31,7 @@ describe('test/app/service/systems/notice.test.js', () => { model: { NotificationWebhook: { async findAll({ where }) { - assert.equal(Number(where.store_id), 1000000); + assert.equal(Number(where.store_id), 100000); assert.equal(Number(where.status), 1); return webhookRows; }, @@ -688,6 +688,7 @@ describe('test/app/service/systems/notice.test.js', () => { assert.ok(Array.isArray(availableEvents)); assert.ok(availableEvents.some(item => item.code === 'all')); assert.ok(availableEvents.some(item => item.code === 'receiving_completed')); + assert.ok(availableEvents.some(item => item.code === 'order_cancel_intercepted')); assert.doesNotThrow(() => NotificationWebhook.rawAttributes.events.validate.isValidEvents([ 'all', 'receiving_completed' ])); assert.throws(() => NotificationWebhook.rawAttributes.events.validate.isValidEvents([ 'receiving.completed' ]), /不支持|非法/); assert.throws(() => NotificationWebhook.rawAttributes.events.validate.isValidEvents([ '1receiving_completed' ]), /不支持|非法/); diff --git a/test/app/service/systems/order_delivery_migration.test.js b/test/app/service/systems/order_delivery_migration.test.js new file mode 100644 index 0000000..aa4f11d --- /dev/null +++ b/test/app/service/systems/order_delivery_migration.test.js @@ -0,0 +1,695 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const Sequelize = require('sequelize'); +const OrderDeliveryMigrationService = require('../../../../app/service/systems/order_delivery_migration'); +const { matchesWhere } = require('../../../support/order_service_test_helper'); + +function cloneRow(row) { + return { + ...(row || {}), + }; +} + +function buildOrderRows(count, overrides = {}) { + return Array.from({ length: count }, (_, index) => ({ + id: index + 1, + warehouse_id: 100000, + store_id: 1000000, + delivery_order_code: `OD-${String(index + 1).padStart(5, '0')}`, + step: 4, + outbound_status: 'fin', + delivery_time: new Date('2026-04-12T00:00:00Z'), + updated_at: '2026-04-12 00:00:00', + ...overrides, + })); +} + +function buildItemRows(orderRows, overrides = {}) { + return (Array.isArray(orderRows) ? orderRows : []).map((orderRow, index) => ({ + id: index + 10001, + order_id: orderRow.id, + actual_price: 1.00, + retail_price: 2.00, + ext_code: `EXT-${String(index + 1).padStart(5, '0')}`, + inventory_type: 'default', + item_code: `ITEM-${String(index + 1).padStart(5, '0')}`, + item_id: index + 20001, + item_name: `商品-${String(index + 1).padStart(5, '0')}`, + order_line_no: `LINE-${String(index + 1).padStart(5, '0')}`, + owner_code: 'OWNER-001', + plan_qty: 1, + source_order_code: orderRow.delivery_order_code, + sub_source_order_code: null, + extend_props: { + source: 'migration-test', + }, + stock_id: index + 30001, + created_at: '2026-04-12 00:00:00', + updated_at: '2026-04-12 00:00:00', + ...overrides, + })); +} + +function buildDispatchKey(row) { + return [ row.delivery_order_code, row.store_id, row.warehouse_id ].join('::'); +} + +function buildRetryableDatabaseError(message, code = 1205) { + const error = new Error(message); + error.name = 'SequelizeDatabaseError'; + error.code = code; + error.parent = { + code, + errno: code, + }; + + return error; +} + +function createTransaction(calls) { + return { + committed: false, + rolledBack: false, + operations: [], + touchedModels: new Set(), + async commit() { + this.committed = true; + calls.commitCount += 1; + + for (const model of this.touchedModels) { + if (typeof model.commitOperations === 'function') { + model.commitOperations(this.operations); + } + } + }, + async rollback() { + this.rolledBack = true; + calls.rollbackCount += 1; + this.operations.length = 0; + this.touchedModels.clear(); + }, + }; +} + +function applyOperations(rows, operations, options = {}) { + let currentRows = Array.isArray(rows) ? rows.map(cloneRow) : []; + const keySelector = typeof options.keySelector === 'function' + ? options.keySelector + : row => row && row.id; + const assignInsertedId = Boolean(options.assignInsertedId); + + for (const operation of Array.isArray(operations) ? operations : []) { + if (operation.type === 'bulkCreate') { + const existingKeys = new Set(currentRows + .map(row => keySelector(row)) + .filter(value => value !== undefined && value !== null && value !== '')); + let nextId = currentRows.reduce((maxId, row) => { + const rowId = Number(row && row.id); + return Number.isFinite(rowId) && rowId > maxId ? rowId : maxId; + }, 0) + 1; + + for (const row of Array.isArray(operation.rows) ? operation.rows : []) { + const nextRow = cloneRow(row); + + if (assignInsertedId && (!Number.isFinite(Number(nextRow.id)) || Number(nextRow.id) <= 0)) { + nextRow.id = nextId; + nextId += 1; + } + + const rowKey = keySelector(nextRow); + + if (operation.ignoreDuplicates && rowKey !== undefined && rowKey !== null && rowKey !== '' && existingKeys.has(rowKey)) { + continue; + } + + currentRows.push(nextRow); + + if (rowKey !== undefined && rowKey !== null && rowKey !== '') { + existingKeys.add(rowKey); + } + } + + continue; + } + + if (operation.type === 'destroy') { + currentRows = currentRows.filter(row => !matchesWhere(row, operation.where)); + continue; + } + + if (operation.type === 'update') { + currentRows = currentRows.map(row => { + if (!matchesWhere(row, operation.where)) { + return row; + } + + return { + ...row, + ...(operation.values || {}), + }; + }); + } + } + + return currentRows; +} + +function createTransactionalModel(rows, capture, options = {}) { + let storedRows = Array.isArray(rows) ? rows.map(cloneRow) : []; + const modelId = options.modelId || 'model'; + const keySelector = typeof options.keySelector === 'function' + ? options.keySelector + : row => row && row.id; + const assignInsertedId = Boolean(options.assignInsertedId); + + const model = { + async findAll(query = {}) { + capture.findAllOptions.push({ + modelId, + where: query.where, + limit: query.limit, + order: query.order, + transaction: query.transaction, + }); + + const transactionOperations = query.transaction + ? query.transaction.operations.filter(operation => operation.modelId === modelId) + : []; + let visibleRows = applyOperations(storedRows, transactionOperations, { + keySelector, + assignInsertedId, + }); + + visibleRows = visibleRows.filter(row => matchesWhere(row, query.where)); + + if (Array.isArray(query.order) && query.order.length > 0) { + const [ column, direction ] = query.order[0]; + const sortFactor = String(direction || 'ASC').toUpperCase() === 'DESC' ? -1 : 1; + + visibleRows = [ ...visibleRows ].sort((left, right) => { + const leftValue = left[column]; + const rightValue = right[column]; + + if (leftValue === rightValue) { + return 0; + } + + return leftValue > rightValue ? sortFactor : -sortFactor; + }); + } + + const limitValue = query.limit === undefined ? visibleRows.length : Number.parseInt(query.limit, 10); + const limit = Number.isFinite(limitValue) ? Math.max(limitValue, 0) : visibleRows.length; + + return visibleRows.slice(0, limit).map(cloneRow); + }, + async bulkCreate(rowsToCreate, query = {}) { + capture.bulkCreateOptions.push({ + modelId, + transaction: query.transaction, + ignoreDuplicates: query.ignoreDuplicates, + }); + capture.bulkCreateRows.push({ + modelId, + rows: rowsToCreate.map(cloneRow), + }); + + const transactionOperations = query.transaction + ? query.transaction.operations.filter(operation => operation.modelId === modelId) + : []; + const visibleRows = applyOperations(storedRows, transactionOperations, { + keySelector, + assignInsertedId, + }); + const stagedRows = rowsToCreate.map(cloneRow); + + if (assignInsertedId) { + let nextId = visibleRows.reduce((maxId, row) => { + const rowId = Number(row && row.id); + return Number.isFinite(rowId) && rowId > maxId ? rowId : maxId; + }, 0) + 1; + + for (const row of stagedRows) { + if (!Number.isFinite(Number(row.id)) || Number(row.id) <= 0) { + row.id = nextId; + nextId += 1; + } + } + } + + if (query.transaction) { + query.transaction.operations.push({ + modelId, + type: 'bulkCreate', + rows: stagedRows, + ignoreDuplicates: Boolean(query.ignoreDuplicates), + }); + query.transaction.touchedModels.add(model); + } else { + storedRows = applyOperations(storedRows, [{ + modelId, + type: 'bulkCreate', + rows: stagedRows, + ignoreDuplicates: Boolean(query.ignoreDuplicates), + }], { + keySelector, + assignInsertedId, + }); + } + + return stagedRows.map(cloneRow); + }, + async destroy(query = {}) { + capture.destroyOptions.push({ + modelId, + where: query.where, + transaction: query.transaction, + }); + + if (query.transaction) { + query.transaction.operations.push({ + modelId, + type: 'destroy', + where: query.where || {}, + }); + query.transaction.touchedModels.add(model); + + return 0; + } + + const beforeCount = storedRows.length; + storedRows = storedRows.filter(row => !matchesWhere(row, query.where)); + + return beforeCount - storedRows.length; + }, + async update(values, query = {}) { + capture.updateOptions.push({ + modelId, + values: { + ...(values || {}), + }, + where: query.where, + transaction: query.transaction, + }); + capture.updateRows.push({ + modelId, + values: { + ...(values || {}), + }, + where: query.where, + }); + + const transactionOperations = query.transaction + ? query.transaction.operations.filter(operation => operation.modelId === modelId) + : []; + const visibleRows = applyOperations(storedRows, transactionOperations, { + keySelector, + assignInsertedId, + }); + const affectedCount = visibleRows.filter(row => matchesWhere(row, query.where)).length; + + if (query.transaction) { + query.transaction.operations.push({ + modelId, + type: 'update', + values: { + ...(values || {}), + }, + where: query.where || {}, + }); + query.transaction.touchedModels.add(model); + + return [ affectedCount ]; + } + + storedRows = applyOperations(storedRows, [{ + modelId, + type: 'update', + values: { + ...(values || {}), + }, + where: query.where || {}, + }], { + keySelector, + assignInsertedId, + }); + + return [ affectedCount ]; + }, + commitOperations(operations) { + const modelOperations = Array.isArray(operations) + ? operations.filter(operation => operation.modelId === modelId) + : []; + + storedRows = applyOperations(storedRows, modelOperations, { + keySelector, + assignInsertedId, + }); + }, + get rows() { + return storedRows.map(cloneRow); + }, + }; + + return model; +} + +function createHarness(options = {}) { + const capture = { + findAllOptions: [], + bulkCreateOptions: [], + bulkCreateRows: [], + destroyOptions: [], + updateOptions: [], + updateRows: [], + commitCount: 0, + rollbackCount: 0, + }; + + const sourceOrderModel = createTransactionalModel(options.sourceRows, capture, { + modelId: 'sourceOrder', + keySelector: row => row && row.id, + }); + const targetOrderModel = createTransactionalModel(options.targetRows || [], capture, { + modelId: 'targetOrder', + keySelector: row => buildDispatchKey(row), + assignInsertedId: true, + }); + const sourceItemModel = createTransactionalModel(options.sourceItemRows || [], capture, { + modelId: 'sourceItem', + keySelector: row => row && row.id, + }); + const targetItemModel = createTransactionalModel(options.targetItemRows || [], capture, { + modelId: 'targetItem', + keySelector: row => row && row.id, + }); + + const transactionCalls = []; + const ctx = { + app: { + Sequelize, + }, + logger: { + info() {}, + warn() {}, + error() {}, + debug() {}, + }, + model: { + async transaction() { + const transaction = createTransaction(capture); + transactionCalls.push(transaction); + return transaction; + }, + OrderDeliveryFactory: { + async getCurrentModel() { + return sourceOrderModel; + }, + async getDispatchModel() { + return targetOrderModel; + }, + async listManagedTableNames() { + return [ 'wms_order_delivery_100000' ]; + }, + }, + OrderItemsFactory: { + async getCurrentModel() { + return sourceItemModel; + }, + async getDispatchModel() { + return targetItemModel; + }, + }, + }, + }; + + const service = new OrderDeliveryMigrationService(ctx); + + return { + service, + capture, + transactionCalls, + sourceOrderModel, + targetOrderModel, + sourceItemModel, + targetItemModel, + }; +} + +describe('test/app/service/systems/order_delivery_migration.test.js', () => { + it('should only migrate outbound rows that match the outbound condition', async () => { + const sourceRows = [ + { + id: 1, + warehouse_id: 100000, + store_id: 1000000, + delivery_order_code: 'OD-00001', + step: 4, + outbound_status: 'fin', + delivery_time: new Date('2026-04-12T00:00:00Z'), + updated_at: '2026-04-12 00:00:00', + }, + { + id: 2, + warehouse_id: 100000, + store_id: 1000000, + delivery_order_code: 'OD-00002', + step: 3, + outbound_status: 'fin', + delivery_time: new Date('2026-04-12T00:00:00Z'), + updated_at: '2026-04-12 00:00:00', + }, + { + id: 3, + warehouse_id: 100000, + store_id: 1000000, + delivery_order_code: 'OD-00003', + step: 4, + outbound_status: 'none', + delivery_time: null, + updated_at: '2026-04-12 00:00:00', + }, + ]; + const { service, capture, sourceOrderModel, targetOrderModel, sourceItemModel, targetItemModel } = createHarness({ + sourceRows, + sourceItemRows: buildItemRows(sourceRows), + }); + + const result = await service.syncOutboundOrdersToDelivery({ + warehouseIds: [ 100000 ], + }); + + assert.equal(result.totalSelected, 1); + assert.equal(result.totalCreated, 1); + assert.equal(result.results[0].selectedCount, 1); + assert.equal(result.results[0].createdCount, 1); + assert.deepEqual(capture.findAllOptions[0].where.outbound_status[Sequelize.Op.in], [ 'fin' ]); + assert.equal(capture.findAllOptions[0].where.step, 4); + assert.equal(capture.bulkCreateRows.length, 2); + assert.equal(capture.bulkCreateRows[0].modelId, 'targetOrder'); + assert.equal(capture.bulkCreateRows[1].modelId, 'targetItem'); + assert.equal(capture.bulkCreateRows[0].rows[0].dispatch_lane, 'm4'); + assert.equal(capture.bulkCreateRows[0].rows[0].id, 1); + assert.equal(sourceOrderModel.rows.length, 2); + assert.equal(targetOrderModel.rows.length, 1); + assert.equal(sourceItemModel.rows.length, 2); + assert.equal(targetItemModel.rows.length, 1); + }); + + it('should migrate order items into dispatch table and delete source rows in the same transaction', async () => { + const sourceRows = buildOrderRows(2); + const { service, capture, transactionCalls, sourceOrderModel, targetOrderModel, sourceItemModel, targetItemModel } = createHarness({ + sourceRows, + sourceItemRows: buildItemRows(sourceRows), + }); + + const result = await service.syncOutboundOrdersToDelivery({ + warehouseIds: [ 100000 ], + }); + + assert.equal(result.totalSelected, 2); + assert.equal(result.totalCreated, 2); + assert.equal(transactionCalls.length, 1); + assert.equal(transactionCalls[0].committed, true); + assert.equal(transactionCalls[0].rolledBack, false); + assert.equal(capture.findAllOptions.every(option => option.transaction === transactionCalls[0]), true); + assert.equal(capture.bulkCreateOptions.every(option => option.transaction === transactionCalls[0]), true); + assert.equal(capture.destroyOptions.every(option => option.transaction === transactionCalls[0]), true); + assert.equal(sourceOrderModel.rows.length, 0); + assert.equal(targetOrderModel.rows.length, 2); + assert.equal(sourceItemModel.rows.length, 0); + assert.equal(targetItemModel.rows.length, 2); + + assert.deepEqual(targetOrderModel.rows.map(row => row.id).sort((a, b) => a - b), [ 1, 2 ]); + const targetOrderIdSet = new Set(targetOrderModel.rows.map(row => row.id)); + assert.equal(targetItemModel.rows.every(row => targetOrderIdSet.has(Number(row.order_id))), true); + }); + + it('should cap each batch at 1000 rows and execute the insert inside one transaction', async () => { + const sourceRows = buildOrderRows(1005); + const { service, capture, transactionCalls, targetOrderModel, sourceOrderModel, targetItemModel, sourceItemModel } = createHarness({ + sourceRows, + sourceItemRows: buildItemRows(sourceRows), + }); + + const result = await service.syncOutboundOrdersToDelivery({ + warehouseIds: [ 100000 ], + }); + + assert.equal(result.totalSelected, 1000); + assert.equal(result.totalCreated, 1000); + assert.equal(result.results[0].selectedCount, 1000); + assert.equal(capture.findAllOptions[0].limit, 1000); + assert.equal(capture.bulkCreateRows[0].rows.length, 1000); + assert.equal(capture.bulkCreateRows[1].rows.length, 1000); + assert.equal(transactionCalls.length, 1); + assert.equal(transactionCalls[0].committed, true); + assert.equal(transactionCalls[0].rolledBack, false); + assert.equal(capture.findAllOptions.every(option => option.transaction === transactionCalls[0]), true); + assert.equal(capture.bulkCreateOptions.every(option => option.transaction === transactionCalls[0]), true); + assert.equal(capture.destroyOptions.every(option => option.transaction === transactionCalls[0]), true); + assert.equal(targetOrderModel.rows.length, 1000); + assert.equal(targetItemModel.rows.length, 1000); + assert.equal(sourceOrderModel.rows.length, 5); + assert.equal(sourceItemModel.rows.length, 5); + }); + + it('should skip already migrated orders on repeated runs', async () => { + const sourceRows = buildOrderRows(2); + const { service, targetOrderModel, targetItemModel, sourceOrderModel, sourceItemModel } = createHarness({ + sourceRows, + sourceItemRows: buildItemRows(sourceRows), + }); + + const firstResult = await service.syncOutboundOrdersToDelivery({ + warehouseIds: [ 100000 ], + }); + const secondResult = await service.syncOutboundOrdersToDelivery({ + warehouseIds: [ 100000 ], + }); + + assert.equal(firstResult.totalCreated, 2); + assert.equal(secondResult.totalCreated, 0); + assert.equal(targetOrderModel.rows.length, 2); + assert.equal(targetItemModel.rows.length, 2); + assert.equal(sourceOrderModel.rows.length, 0); + assert.equal(sourceItemModel.rows.length, 0); + assert.equal(new Set(targetOrderModel.rows.map(row => row.delivery_order_code)).size, 2); + assert.deepEqual(targetOrderModel.rows.map(row => row.id).sort((a, b) => a - b), [ 1, 2 ]); + }); + + it('should rollback the whole batch when any selected source row lacks dispatch key fields', async () => { + const sourceRows = buildOrderRows(2); + delete sourceRows[1].store_id; + + const { service, capture, transactionCalls, sourceOrderModel, targetOrderModel, sourceItemModel, targetItemModel } = createHarness({ + sourceRows, + sourceItemRows: buildItemRows(sourceRows), + }); + + await assert.rejects( + service.syncOutboundOrdersToDelivery({ + warehouseIds: [ 100000 ], + }), + /缺少 delivery_order_code\/store_id\/warehouse_id/ + ); + + assert.equal(transactionCalls.length, 1); + assert.equal(transactionCalls[0].committed, false); + assert.equal(transactionCalls[0].rolledBack, true); + assert.equal(capture.bulkCreateRows.length, 0); + assert.equal(capture.destroyOptions.length, 0); + assert.equal(sourceOrderModel.rows.length, 2); + assert.equal(targetOrderModel.rows.length, 0); + assert.equal(sourceItemModel.rows.length, 2); + assert.equal(targetItemModel.rows.length, 0); + }); + + it('should rollback source and target changes when item migration fails', async () => { + const sourceRows = buildOrderRows(1); + const { service, sourceOrderModel, targetOrderModel, sourceItemModel, targetItemModel, transactionCalls } = createHarness({ + sourceRows, + sourceItemRows: buildItemRows(sourceRows), + }); + + targetItemModel.bulkCreate = async () => { + throw new Error('item migration failed'); + }; + + await assert.rejects( + service.syncOutboundOrdersToDelivery({ + warehouseIds: [ 100000 ], + }), + /item migration failed/ + ); + + assert.equal(transactionCalls.length, 1); + assert.equal(transactionCalls[0].committed, false); + assert.equal(transactionCalls[0].rolledBack, true); + assert.equal(sourceOrderModel.rows.length, 1); + assert.equal(targetOrderModel.rows.length, 0); + assert.equal(sourceItemModel.rows.length, 1); + assert.equal(targetItemModel.rows.length, 0); + }); + + it('should mark source orders as timeout when normal migration hits retryable lock errors', async () => { + const sourceRows = buildOrderRows(1); + const { service, capture, transactionCalls, sourceOrderModel, targetOrderModel, sourceItemModel, targetItemModel } = createHarness({ + sourceRows, + sourceItemRows: buildItemRows(sourceRows), + }); + + targetOrderModel.bulkCreate = async () => { + throw buildRetryableDatabaseError('Lock wait timeout exceeded; try restarting transaction', 1205); + }; + + const result = await service.syncOutboundOrdersToDelivery({ + warehouseIds: [ 100000 ], + }); + + assert.equal(result.totalSelected, 1); + assert.equal(result.totalCreated, 0); + assert.equal(result.totalTimeout, 1); + assert.equal(result.results[0].retryableFailure, true); + assert.equal(result.results[0].retryableFailureType, 'lock_wait_timeout'); + assert.equal(result.results[0].timeoutCount, 1); + assert.equal(transactionCalls.length, 1); + assert.equal(transactionCalls[0].committed, false); + assert.equal(transactionCalls[0].rolledBack, true); + assert.equal(capture.updateOptions.length, 1); + assert.equal(capture.updateOptions[0].values.outbound_status, 'timeout'); + assert.equal(sourceOrderModel.rows.length, 1); + assert.equal(sourceOrderModel.rows[0].outbound_status, 'timeout'); + assert.equal(targetOrderModel.rows.length, 0); + assert.equal(sourceItemModel.rows.length, 1); + assert.equal(targetItemModel.rows.length, 0); + }); + + it('should retry only timeout outbound rows in the long task', async () => { + const sourceRows = buildOrderRows(2); + sourceRows[0].outbound_status = 'timeout'; + sourceRows[1].outbound_status = 'fin'; + const { service, capture, sourceOrderModel, targetOrderModel, sourceItemModel, targetItemModel } = createHarness({ + sourceRows, + sourceItemRows: buildItemRows(sourceRows), + }); + + const result = await service.retryTimeoutOutboundOrdersToDelivery({ + warehouseIds: [ 100000 ], + }); + + assert.equal(result.totalSelected, 1); + assert.equal(result.totalCreated, 1); + assert.equal(result.totalTimeout, 0); + assert.equal(capture.findAllOptions[0].where.step, 4); + assert.deepEqual(capture.findAllOptions[0].where.outbound_status[Sequelize.Op.in], [ 'timeout' ]); + assert.equal(sourceOrderModel.rows.length, 1); + assert.equal(sourceOrderModel.rows[0].outbound_status, 'fin'); + assert.equal(targetOrderModel.rows.length, 1); + assert.equal(targetOrderModel.rows[0].id, 1); + assert.equal(sourceItemModel.rows.length, 1); + assert.equal(targetItemModel.rows.length, 1); + assert.equal(targetItemModel.rows[0].order_id, targetOrderModel.rows[0].id); + }); +}); diff --git a/test/app/service/systems/order_outbound.test.js b/test/app/service/systems/order_outbound.test.js new file mode 100644 index 0000000..df1f6d2 --- /dev/null +++ b/test/app/service/systems/order_outbound.test.js @@ -0,0 +1,166 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const Sequelize = require('sequelize'); +const OrderOutboundService = require('../../../../app/service/systems/order_outbound'); +const { buildRows, createServiceContext, matchesWhere } = require('../../../support/order_service_test_helper'); + +/** + * 创建可回写的订单模型。 + * @param {Array} rows 初始订单数据。 + * @param {Object} capture 调用记录。 + * @return {Object} 模拟模型。 + */ +function createMutableOrderModel(rows, capture = {}) { + const storedRows = Array.isArray(rows) ? rows.map(row => ({ ...row })) : []; + capture.rows = storedRows; + + return { + async update(values = {}, options = {}) { + capture.updateValues = { ...values }; + capture.updateWhere = options.where; + + const matchedRows = storedRows.filter(row => matchesWhere(row, options.where)); + for (const row of matchedRows) { + Object.assign(row, values); + } + + return [ matchedRows.length ]; + }, + async findAll(options = {}) { + capture.findAllWhere = options.where; + return storedRows + .filter(row => matchesWhere(row, options.where)) + .map(row => ({ ...row })); + }, + }; +} + +/** + * 创建出库服务测试实例。 + * @param {Array} rows 初始订单数据。 + * @return {{ service: OrderOutboundService, capture: Object }} 服务与调用记录。 + */ +function createOutboundService(rows) { + const ctx = createServiceContext(100000); + ctx.logger = { + info() {}, + warn() {}, + error() {}, + debug() {}, + }; + ctx.service = { + systems: {}, + }; + + const capture = {}; + const sharedModel = createMutableOrderModel(rows, capture); + + const service = new OrderOutboundService(ctx); + service.getOrderModel = async () => sharedModel; + + return { + service, + capture, + }; +} + +describe('test/app/service/systems/order_outbound.test.js', () => { + it('should mark single order as outbound with legacy id/order_id fields', async () => { + const scenarios = [ + { + payload: { + id: 1, + }, + expectedId: 1, + }, + { + payload: { + order_id: 2, + }, + expectedId: 2, + }, + ]; + + for (const scenario of scenarios) { + const { service, capture } = createOutboundService(buildRows(2, index => ({ + id: index + 1, + warehouse_id: 100000, + step: 1, + outbound_status: 'none', + delivery_time: null, + updated_at: '2026-04-12 00:00:00', + }))); + + const result = await service.markOutboundOrder(scenario.payload); + + assert.equal(capture.updateWhere.id, scenario.expectedId); + assert.equal(capture.updateWhere.warehouse_id, 100000); + assert.equal(capture.updateValues.outbound_status, 'fin'); + assert.equal(capture.updateValues.step, 4); + assert.ok(capture.updateValues.delivery_time instanceof Date); + assert.ok(capture.updateValues.updated_at instanceof Date); + assert.equal(result.id, scenario.expectedId); + assert.equal(result.outbound_status, 'fin'); + assert.equal(result.step, 4); + assert.equal(result.updated_count, 1); + assert.deepEqual(result.ids, [ scenario.expectedId ]); + assert.equal(capture.rows.find(row => row.id === scenario.expectedId).outbound_status, 'fin'); + assert.equal(capture.rows.find(row => row.id === scenario.expectedId).step, 4); + } + }); + + it('should support batch ids and update delivery_time for every matched order', async () => { + const { service, capture } = createOutboundService(buildRows(3, index => ({ + id: index + 1, + warehouse_id: 100000, + step: 1, + outbound_status: 'none', + delivery_time: null, + updated_at: '2026-04-12 00:00:00', + }))); + + const result = await service.markOutboundOrder({ + ids: [ 1, 3 ], + }); + + assert.equal(capture.updateWhere.warehouse_id, 100000); + assert.equal(capture.updateWhere.id[Sequelize.Op.in].length, 2); + assert.ok(matchesWhere({ id: 1, warehouse_id: 100000 }, capture.updateWhere)); + assert.ok(!matchesWhere({ id: 2, warehouse_id: 100000 }, capture.updateWhere)); + assert.ok(matchesWhere({ id: 3, warehouse_id: 100000 }, capture.updateWhere)); + assert.equal(capture.updateValues.outbound_status, 'fin'); + assert.equal(capture.updateValues.step, 4); + assert.ok(capture.updateValues.delivery_time instanceof Date); + assert.equal(result.id, 1); + assert.equal(result.outbound_status, 'fin'); + assert.equal(result.step, 4); + assert.equal(result.updated_count, 2); + assert.deepEqual(result.ids, [ 1, 3 ]); + assert.equal(capture.rows.find(row => row.id === 1).outbound_status, 'fin'); + assert.equal(capture.rows.find(row => row.id === 3).outbound_status, 'fin'); + }); + + it('should reject when order ids are missing or invalid', async () => { + const { service } = createOutboundService(buildRows(1, () => ({ + id: 1, + warehouse_id: 100000, + step: 1, + outbound_status: 'none', + delivery_time: null, + updated_at: '2026-04-12 00:00:00', + }))); + + await assert.rejects( + async () => await service.markOutboundOrder({}), + /订单ID不能为空/ + ); + + await assert.rejects( + async () => await service.markOutboundOrder({ + ids: [ 0, 'abc' ], + }), + /订单ID不能为空/ + ); + }); +}); diff --git a/test/app/service/systems/order_pending_exception.test.js b/test/app/service/systems/order_pending_exception.test.js new file mode 100644 index 0000000..c5a5286 --- /dev/null +++ b/test/app/service/systems/order_pending_exception.test.js @@ -0,0 +1,188 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const Sequelize = require('sequelize'); +const OrderPendingExceptionService = require('../../../../app/service/systems/order_pending_exception'); +const PendingOrderService = require('../../../../app/service/systemMethods/order/pendingOrder'); +const ExpectionOrderService = require('../../../../app/service/systemMethods/order/expectionOrder'); +const { buildRows, createServiceContext, matchesWhere } = require('../../../support/order_service_test_helper'); + +/** + * 创建可回写的订单模型。 + * @param {Array} rows 初始订单数据。 + * @param {Object} capture 调用记录。 + * @return {Object} 模拟模型。 + */ +function createMutableOrderModel(rows, capture = {}) { + return { + async update(values = {}, options = {}) { + capture.updateValues = { ...values }; + capture.updateWhere = options.where; + + const matchedRows = rows.filter(row => matchesWhere(row, options.where)); + for (const row of matchedRows) { + Object.assign(row, values); + } + + return [ matchedRows.length ]; + }, + async findAll(options = {}) { + capture.findAllWhere = options.where; + return rows + .filter(row => matchesWhere(row, options.where)) + .map(row => ({ ...row })); + }, + async count({ where } = {}) { + capture.countWhere = where; + return rows.filter(row => matchesWhere(row, where)).length; + }, + async findOne(options = {}) { + capture.findOneWhere = options.where; + const matchedRow = rows.find(row => matchesWhere(row, options.where)); + return matchedRow ? { ...matchedRow } : null; + }, + }; +} + +/** + * 创建待处理异常标记测试所需的服务实例。 + * @param {Array} rows 初始订单数据。 + * @return {{ ctx: Object, capture: Object, exceptionService: OrderPendingExceptionService, pendingService: PendingOrderService, exceptionListService: ExpectionOrderService }} 服务与调用记录。 + */ +function createServices(rows) { + const ctx = createServiceContext(100000); + ctx.logger = { + info() {}, + warn() {}, + error() {}, + debug() {}, + }; + ctx.service = { + systems: {}, + }; + + const capture = {}; + const sharedModel = createMutableOrderModel(rows, capture); + + const exceptionService = new OrderPendingExceptionService(ctx); + const pendingService = new PendingOrderService(ctx); + const exceptionListService = new ExpectionOrderService(ctx); + + exceptionService.getOrderModel = async () => sharedModel; + pendingService.getOrderModel = async () => sharedModel; + exceptionListService.getOrderModel = async () => sharedModel; + + return { + ctx, + capture, + exceptionService, + pendingService, + exceptionListService, + }; +} + +describe('test/app/service/systems/order_pending_exception.test.js', () => { + it('should mark a single order as pending exception and change list visibility', async () => { + const rows = buildRows(1, () => ({ + id: 1, + warehouse_id: 100000, + step: 1, + inspection_status: 'fin', + order_flag: '', + updated_at: '2026-04-12 00:00:00', + })); + const { capture, exceptionService, pendingService, exceptionListService } = createServices(rows); + + const pendingBefore = await pendingService.list({ where: {} }); + const exceptionBefore = await exceptionListService.list({ where: {} }); + + assert.equal(pendingBefore.list.length, 1); + assert.equal(exceptionBefore.list.length, 0); + + const result = await exceptionService.markPendingException({ + order_id: 1, + reason: '缺少异常处理单据', + }); + + assert.equal(capture.updateWhere.id, 1); + assert.equal(capture.updateWhere.warehouse_id, 100000); + assert.equal(capture.updateValues.inspection_status, 'error'); + assert.equal(capture.updateValues.step, 3); + assert.equal(capture.updateValues.order_flag, '缺少异常处理单据'); + assert.equal(result.id, 1); + assert.equal(result.inspection_status, 'error'); + assert.equal(result.step, 3); + assert.equal(result.exception_text, '缺少异常处理单据'); + assert.equal(result.order_flag, '缺少异常处理单据'); + + const pendingAfter = await pendingService.list({ where: {} }); + const exceptionAfter = await exceptionListService.list({ where: {} }); + + assert.equal(pendingAfter.list.length, 0); + assert.equal(exceptionAfter.list.length, 1); + assert.equal(exceptionAfter.list[0].step, 3); + assert.equal(exceptionAfter.list[0].inspection_status, 'error'); + assert.equal(exceptionAfter.list[0].order_flag, '缺少异常处理单据'); + }); + + it('should support batch ids and return affected ids', async () => { + const rows = buildRows(3, index => ({ + id: index + 1, + warehouse_id: 100000, + step: 1, + inspection_status: 'fin', + order_flag: '', + updated_at: '2026-04-12 00:00:00', + })); + const { capture, exceptionService, pendingService, exceptionListService } = createServices(rows); + + const result = await exceptionService.markPendingException({ + ids: [ 1, 3 ], + exception_text: '批量异常标记', + }); + + assert.equal(capture.updateWhere.warehouse_id, 100000); + assert.equal(capture.updateWhere.id[Sequelize.Op.in].length, 2); + assert.ok(matchesWhere({ id: 1, warehouse_id: 100000 }, capture.updateWhere)); + assert.ok(!matchesWhere({ id: 2, warehouse_id: 100000 }, capture.updateWhere)); + assert.ok(matchesWhere({ id: 3, warehouse_id: 100000 }, capture.updateWhere)); + assert.equal(capture.updateValues.inspection_status, 'error'); + assert.equal(capture.updateValues.step, 3); + assert.equal(capture.updateValues.order_flag, '批量异常标记'); + assert.equal(result.updated_count, 2); + assert.deepEqual(result.ids, [ 1, 3 ]); + + const pendingAfter = await pendingService.list({ where: {} }); + const exceptionAfter = await exceptionListService.list({ where: {} }); + + assert.equal(pendingAfter.list.length, 1); + assert.equal(exceptionAfter.list.length, 2); + assert.ok(exceptionAfter.list.every(item => item.step === 3)); + }); + + it('should reject invalid parameters', async () => { + const rows = buildRows(1, () => ({ + id: 1, + warehouse_id: 100000, + step: 1, + inspection_status: 'fin', + order_flag: '', + updated_at: '2026-04-12 00:00:00', + })); + const { exceptionService } = createServices(rows); + + await assert.rejects( + async () => await exceptionService.markPendingException({ + id: 1, + }), + /异常文本不能为空/ + ); + + await assert.rejects( + async () => await exceptionService.markPendingException({ + exception_text: '缺少订单ID', + }), + /订单ID不能为空/ + ); + }); +}); diff --git a/test/app/service/systems/order_storage_allocation.test.js b/test/app/service/systems/order_storage_allocation.test.js new file mode 100644 index 0000000..618d8f2 --- /dev/null +++ b/test/app/service/systems/order_storage_allocation.test.js @@ -0,0 +1,521 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const Sequelize = require('sequelize'); +const OrderStorageAllocationService = require('../../../../app/service/systems/order_storage_allocation'); + +/** + * 将 where 条件与测试行做最小匹配。 + * + * @param {Object} row 测试行。 + * @param {Object} where 查询条件。 + * @return {boolean} 是否匹配。 + */ +function matchesWhere(row, where) { + if (!where || typeof where !== 'object') { + return true; + } + + const andConditions = where[Sequelize.Op.and]; + if (Array.isArray(andConditions)) { + return andConditions.every(condition => matchesWhere(row, condition)); + } + + const orConditions = where[Sequelize.Op.or]; + if (Array.isArray(orConditions)) { + return orConditions.some(condition => matchesWhere(row, condition)); + } + + return Object.entries(where).every(([ fieldName, condition ]) => { + if (condition && typeof condition === 'object' && !Array.isArray(condition)) { + if (Object.prototype.hasOwnProperty.call(condition, Sequelize.Op.in)) { + return Array.isArray(condition[Sequelize.Op.in]) && condition[Sequelize.Op.in].includes(row[fieldName]); + } + + if (Object.prototype.hasOwnProperty.call(condition, Sequelize.Op.ne)) { + return row[fieldName] !== condition[Sequelize.Op.ne]; + } + + if (Object.prototype.hasOwnProperty.call(condition, Sequelize.Op.gt)) { + return Number(row[fieldName]) > Number(condition[Sequelize.Op.gt]); + } + + if (Object.prototype.hasOwnProperty.call(condition, Sequelize.Op.gte)) { + return Number(row[fieldName]) >= Number(condition[Sequelize.Op.gte]); + } + + if (Object.prototype.hasOwnProperty.call(condition, Sequelize.Op.lt)) { + return Number(row[fieldName]) < Number(condition[Sequelize.Op.lt]); + } + + if (Object.prototype.hasOwnProperty.call(condition, Sequelize.Op.lte)) { + return Number(row[fieldName]) <= Number(condition[Sequelize.Op.lte]); + } + } + + return row[fieldName] === condition; + }); +} + +/** + * 创建可回写的测试模型。 + * + * @param {Array} rows 行数据。 + * @param {Object} capture 调用记录。 + * @return {Object} 模拟模型。 + */ +function createMutableModel(rows, capture = {}) { + return { + async findAll(options = {}) { + capture.findAllWhere = options.where; + return rows.filter(row => matchesWhere(row, options.where)).map(row => ({ ...row })); + }, + async update(values = {}, options = {}) { + capture.updateValues = { ...values }; + capture.updateWhere = options.where; + + const matchedRows = rows.filter(row => matchesWhere(row, options.where)); + for (const row of matchedRows) { + Object.assign(row, values); + } + + return [ matchedRows.length ]; + }, + async findByPk(id) { + capture.findByPkId = id; + const matchedRow = rows.find(row => Number(row.id) === Number(id)); + + if (!matchedRow) { + return null; + } + + return { + ...matchedRow, + async increment(field, options = {}) { + matchedRow[field] = Number(matchedRow[field] || 0) + Number(options.by || 0); + }, + async reload() { + return this; + }, + }; + }, + }; +} + +/** + * 创建储位分配服务测试环境。 + * + * @param {Object} options 测试配置。 + * @return {{ service: OrderStorageAllocationService, captures: Object }} 测试上下文。 + */ +function createHarness(options = {}) { + const captures = { + storageLocks: [], + pickingRows: null, + }; + + const orders = Array.isArray(options.orders) ? options.orders.map(item => ({ ...item })) : []; + const orderItems = Array.isArray(options.orderItems) ? options.orderItems.map(item => ({ ...item })) : []; + const stockRows = Array.isArray(options.stockRows) ? options.stockRows.map(item => ({ ...item })) : []; + const storageRows = Array.isArray(options.storageRows) ? options.storageRows.map(item => ({ ...item })) : []; + + const ctx = { + user: { + store_id: options.warehouseId || 100000, + id: 1, + }, + logger: { + debug() {}, + info() {}, + warn() {}, + error() {}, + }, + app: { + Sequelize, + }, + model: { + async transaction() { + return { + LOCK: { + UPDATE: 'UPDATE', + }, + async commit() { + captures.committed = true; + }, + async rollback() { + captures.rolledBack = true; + }, + }; + }, + OrderDeliveryFactory: { + async getCurrentModel() { + return createMutableModel(orders, captures.order); + }, + }, + OrderItemsFactory: { + async getCurrentModel() { + return createMutableModel(orderItems, captures.orderItems); + }, + }, + StockWarehouse: { + async findAll(options = {}) { + captures.stockFindAllWhere = options.where; + return stockRows.filter(row => matchesWhere(row, options.where)).map(row => ({ ...row })); + }, + async findByPk(id) { + captures.stockFindByPk = id; + const matchedRow = stockRows.find(row => Number(row.id) === Number(id)); + if (!matchedRow) { + return null; + } + + return { + ...matchedRow, + async increment(field, options = {}) { + matchedRow[field] = Number(matchedRow[field] || 0) + Number(options.by || 0); + }, + async reload() { + return this; + }, + }; + }, + }, + Storage: { + async findAll(options = {}) { + captures.storageFindAllWhere = options.where; + return storageRows.filter(row => matchesWhere(row, options.where)).map(row => ({ ...row })); + }, + }, + LocationSpace: {}, + LocationType: {}, + Picking: { + async bulkCreate(rows) { + captures.pickingRows = rows.map(row => ({ ...row })); + return rows; + }, + }, + }, + service: { + systems: { + storage: { + async lockQuantity(storageId, quantity) { + const matchedRow = storageRows.find(row => Number(row.id) === Number(storageId)); + if (!matchedRow) { + throw new Error(`库存记录不存在: ${storageId}`); + } + + const availableQuantity = Number(matchedRow.available_quantity || 0); + if (availableQuantity < Number(quantity || 0)) { + throw new Error('可用数量不足'); + } + + captures.storageLocks.push({ storageId: Number(storageId), quantity: Number(quantity) }); + matchedRow.available_quantity = availableQuantity - Number(quantity); + matchedRow.locked_quantity = Number(matchedRow.locked_quantity || 0) + Number(quantity); + return matchedRow; + }, + }, + stockStore: { + async getStoreWarehousePolicyConfigByStockId(stockId) { + return options.policies && options.policies[stockId] + ? options.policies[stockId] + : { + policyConfig: { + storage_separation: 1, + }, + allowOversell: false, + }; + }, + }, + }, + }, + }; + + const service = new OrderStorageAllocationService(ctx); + + return { + service, + captures, + ctx, + orders, + orderItems, + stockRows, + storageRows, + }; +} + +describe('test/app/service/systems/order_storage_allocation.test.js', () => { + it('should filter already allocated orders and prefer storage locations when allowed', async () => { + const { service, captures, orders, stockRows, storageRows } = createHarness({ + orders: [ + { id: 1, warehouse_id: 100000, storage_status: 'fin', order_flag: '', step: 2 }, + { id: 2, warehouse_id: 100000, storage_status: 'none', order_flag: '', step: 2 }, + ], + orderItems: [ + { id: 11, order_id: 2, stock_id: 101, plan_qty: 2, order_line_no: '1' }, + ], + stockRows: [ + { id: 101, item_code: 'SKU-101', item_name: '测试商品101', warehouse_id: 100000, deleted_at: null, is_valid: 'Y', locked_quantity: 0 }, + ], + storageRows: [ + { + id: 1001, + warehouse_id: 100000, + stock_id: 101, + is_enabled: 1, + delete_at: null, + available_quantity: 2, + quantity: 2, + locked_quantity: 0, + production_date: null, + inbound_time: '2026-04-15 08:00:00', + space_id: 501, + space: { + id: 501, + space_code: 'ST-001', + custom_name: '存储位A', + is_preferred_pick: false, + locationType: { + id: 1, + allow_allocation: 1, + is_active: 1, + }, + }, + }, + { + id: 1002, + warehouse_id: 100000, + stock_id: 101, + is_enabled: 1, + delete_at: null, + available_quantity: 5, + quantity: 5, + locked_quantity: 0, + production_date: null, + inbound_time: '2026-04-15 09:00:00', + space_id: 502, + space: { + id: 502, + space_code: 'PK-001', + custom_name: '分拣位A', + is_preferred_pick: true, + locationType: { + id: 1, + allow_allocation: 1, + is_active: 1, + }, + }, + }, + ], + policies: { + 101: { + policyConfig: { + storage_separation: 1, + }, + allowOversell: false, + }, + }, + }); + + const result = await service.allocateStorage({ + allow_storage_location: true, + order_ids: [ 1, 2 ], + }); + + assert.equal(result.code, 200); + assert.equal(result.data.allocated_order_ids.length, 1); + assert.deepEqual(result.data.skipped_orders.map(item => item.order_id), [ 1 ]); + assert.equal(result.data.orders.find(item => item.order_id === 2).storage_status, 'fin'); + assert.equal(captures.storageLocks.length, 1); + assert.equal(captures.storageLocks[0].storageId, 1001); + assert.equal(captures.pickingRows.length, 1); + assert.equal(captures.pickingRows[0].order_id, 2); + assert.equal(captures.pickingRows[0].order_item_id, 11); + assert.equal(captures.pickingRows[0].storage_id, 1001); + assert.equal(captures.pickingRows[0].quantity, 2); + assert.equal(captures.pickingRows[0].space_id, 501); + assert.equal(captures.pickingRows[0].space_name, '存储位A'); + assert.equal(captures.pickingRows[0].status, 'pending'); + assert.equal(stockRows[0].locked_quantity, 2); + assert.equal(storageRows[0].locked_quantity, 2); + assert.equal(storageRows[0].available_quantity, 0); + assert.equal(orders[1].storage_status, 'fin'); + }); + + it('should allow storage locations when storage separation is disabled even if the request flag is false', async () => { + const { service, captures, storageRows } = createHarness({ + orders: [ + { id: 3, warehouse_id: 100000, storage_status: 'none', order_flag: '', step: 2 }, + ], + orderItems: [ + { id: 31, order_id: 3, stock_id: 201, plan_qty: 1, order_line_no: '1' }, + ], + stockRows: [ + { id: 201, item_code: 'SKU-201', item_name: '测试商品201', warehouse_id: 100000, deleted_at: null, is_valid: 'Y', locked_quantity: 0 }, + ], + storageRows: [ + { + id: 2001, + warehouse_id: 100000, + stock_id: 201, + is_enabled: 1, + delete_at: null, + available_quantity: 1, + quantity: 1, + locked_quantity: 0, + production_date: '2026-04-10 00:00:00', + inbound_time: '2026-04-15 07:00:00', + space_id: 601, + space: { + id: 601, + space_code: 'ST-201', + custom_name: '存储位B', + is_preferred_pick: false, + locationType: { + id: 1, + allow_allocation: 1, + is_active: 1, + }, + }, + }, + { + id: 2002, + warehouse_id: 100000, + stock_id: 201, + is_enabled: 1, + delete_at: null, + available_quantity: 1, + quantity: 1, + locked_quantity: 0, + production_date: null, + inbound_time: '2026-04-14 07:00:00', + space_id: 602, + space: { + id: 602, + space_code: 'PK-201', + custom_name: '分拣位B', + is_preferred_pick: true, + locationType: { + id: 1, + allow_allocation: 1, + is_active: 1, + }, + }, + }, + ], + policies: { + 201: { + policyConfig: { + storage_separation: 0, + }, + allowOversell: false, + }, + }, + }); + + const result = await service.allocateStorage({ + allowStorageLocation: false, + orderIds: [ 3 ], + }); + + assert.equal(result.code, 200); + assert.equal(result.data.orders[0].storage_status, 'fin'); + assert.equal(captures.storageLocks[0].storageId, 2001); + assert.equal(captures.pickingRows[0].order_id, 3); + assert.equal(captures.pickingRows[0].order_item_id, 31); + assert.equal(captures.pickingRows[0].storage_id, 2001); + assert.equal(captures.pickingRows[0].space_name, '存储位B'); + assert.equal(storageRows[0].locked_quantity, 1); + }); + + it('should allocate partially and mark shortage orders with exception text', async () => { + const { service, captures, orders, stockRows } = createHarness({ + orders: [ + { id: 4, warehouse_id: 100000, storage_status: 'none', order_flag: '', step: 2 }, + ], + orderItems: [ + { id: 41, order_id: 4, stock_id: 301, plan_qty: 3, order_line_no: '1' }, + ], + stockRows: [ + { id: 301, item_code: 'SKU-301', item_name: '测试商品301', warehouse_id: 100000, deleted_at: null, is_valid: 'Y', locked_quantity: 0 }, + ], + storageRows: [ + { + id: 3001, + warehouse_id: 100000, + stock_id: 301, + is_enabled: 1, + delete_at: null, + available_quantity: 2, + quantity: 2, + locked_quantity: 0, + production_date: null, + inbound_time: '2026-04-15 10:00:00', + space_id: 701, + space: { + id: 701, + space_code: 'PK-301', + custom_name: '分拣位C', + is_preferred_pick: true, + locationType: { + id: 1, + allow_allocation: 1, + is_active: 1, + }, + }, + }, + ], + policies: { + 301: { + policyConfig: { + storage_separation: 1, + }, + allowOversell: false, + }, + }, + }); + + const result = await service.allocateStorage({ + allow_storage_location: true, + order_ids: [ 4 ], + }); + + assert.equal(result.code, 200); + assert.equal(result.data.shortage_order_ids.length, 1); + assert.equal(result.data.orders.find(item => item.order_id === 4).storage_status, 'error'); + assert.equal(result.data.orders.find(item => item.order_id === 4).status, 'error'); + assert.match(result.data.shortage_messages[0], /库存不足:sku\(301\),数量:3,库位数量:2/); + assert.equal(captures.pickingRows.length, 1); + assert.equal(captures.pickingRows[0].order_id, 4); + assert.equal(captures.pickingRows[0].order_item_id, 41); + assert.equal(captures.pickingRows[0].storage_id, 3001); + assert.equal(captures.pickingRows[0].quantity, 2); + assert.equal(captures.pickingRows[0].space_name, '分拣位C'); + assert.equal(stockRows[0].locked_quantity, 2); + assert.equal(orders[0].storage_status, 'error'); + assert.equal(orders[0].order_flag, '库存不足:sku(301),数量:3,库位数量:2'); + assert.equal(captures.committed, true); + }); + + it('should return a useful summary when every order has already been allocated', async () => { + const { service, captures } = createHarness({ + orders: [ + { id: 5, warehouse_id: 100000, storage_status: 'fin', order_flag: '', step: 2 }, + ], + orderItems: [], + stockRows: [], + storageRows: [], + }); + + const result = await service.allocateStorage({ + order_ids: [ 5 ], + allow_storage_location: true, + }); + + assert.equal(result.code, 200); + assert.equal(result.message, '没有需要分配的订单'); + assert.equal(result.data.picking_count, 0); + assert.equal(result.data.skipped_orders[0].skipped_reason, 'already_allocated'); + assert.equal(captures.pickingRows, null); + }); +}); diff --git a/test/app/service/systems/platform.test.js b/test/app/service/systems/platform.test.js new file mode 100644 index 0000000..2dd3611 --- /dev/null +++ b/test/app/service/systems/platform.test.js @@ -0,0 +1,164 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const PlatformService = require('../../../../app/service/systems/platform'); +const IndexMethodService = require('../../../../app/service/systemMethods/index'); + +/** + * 创建平台服务测试桩。 + * + * @param {Object} [options={}] 测试配置。 + * @return {Object} 测试上下文和调用记录。 + */ +function createPlatformServiceHarness(options = {}) { + const calls = { + findAll: 0, + platformFindAll: 0, + platformSettingFindAll: 0, + getCache: 0, + setCache: 0, + }; + + const ctx = { + user: { + store_id: options.storeId === undefined ? 100000 : options.storeId, + }, + app: { + async getCacheAsync(cacheKey) { + calls.getCache += 1; + if (typeof options.getCacheAsync === 'function') { + return await options.getCacheAsync(cacheKey); + } + return options.cachedValue === undefined ? null : options.cachedValue; + }, + async setCacheAsync(cacheKey, value, ttl) { + calls.setCache += 1; + calls.cachePayload = { cacheKey, value, ttl }; + if (typeof options.setCacheAsync === 'function') { + return await options.setCacheAsync(cacheKey, value, ttl); + } + }, + }, + model: { + Platform: { + async findAll(query) { + calls.findAll += 1; + calls.platformFindAll += 1; + calls.platformFindAllQuery = query; + return options.rows || [ + { code: 'JD', name: '京东平台', default_express_interface: 'OPEN_API' }, + { code: 'TB', name: '淘宝平台', default_express_interface: 'QM_WMS' }, + ]; + }, + }, + PlatformSetting: { + async findAll(query) { + calls.findAll += 1; + calls.platformSettingFindAll += 1; + calls.platformSettingFindAllQuery = query; + return options.settingRows || [ + { id: 11, code: 'JD-STORE', platform_code: 'JD', warehouse_id: 100000 }, + { id: 12, code: 'TB-STORE', platform_code: 'TB', warehouse_id: 100000 }, + ]; + }, + }, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + }; + + return { + ctx, + calls, + }; +} + +describe('test/app/service/systems/platform.test.js', () => { + it('should load merged platform list from database and cache it when cache is empty', async () => { + const { ctx, calls } = createPlatformServiceHarness(); + const service = new PlatformService(ctx); + + const result = await service.getPlatformList(); + + assert.equal(calls.getCache, 1); + assert.equal(calls.findAll, 2); + assert.equal(calls.platformFindAll, 1); + assert.equal(calls.platformSettingFindAll, 1); + assert.equal(calls.setCache, 1); + assert.equal(calls.cachePayload.cacheKey, 'platform:list:100000'); + assert.equal(calls.cachePayload.ttl, 600); + assert.deepEqual(result, [ + { code: 'JD', name: '京东平台', default_express_interface: 'OPEN_API', value: 'JD', label: '京东平台', platform_code: 'JD', platform_name: '京东平台', is_system_setting: false }, + { code: 'TB', name: '淘宝平台', default_express_interface: 'QM_WMS', value: 'TB', label: '淘宝平台', platform_code: 'TB', platform_name: '淘宝平台', is_system_setting: false }, + { id: 11, code: 'JD-STORE', name: 'JD-STORE (京东平台)', value: 'JD-STORE', label: 'JD-STORE (京东平台)', is_system_setting: true, alias: '', platform_code: 'JD', platform_name: '京东平台', default_express_interface: 'OPEN_API' }, + { id: 12, code: 'TB-STORE', name: 'TB-STORE (淘宝平台)', value: 'TB-STORE', label: 'TB-STORE (淘宝平台)', is_system_setting: true, alias: '', platform_code: 'TB', platform_name: '淘宝平台', default_express_interface: 'QM_WMS' }, + ]); + }); + + it('should return cached platform list without querying database', async () => { + const cachedValue = [ + { code: 'TB', name: '淘宝平台', default_express_interface: 'QM_WMS', value: 'TB', label: '淘宝平台', platform_code: 'TB', platform_name: '淘宝平台', is_system_setting: false }, + ]; + const { ctx, calls } = createPlatformServiceHarness({ + cachedValue, + }); + const service = new PlatformService(ctx); + + const result = await service.getPlatformList(); + + assert.equal(calls.getCache, 1); + assert.equal(calls.findAll, 0); + assert.equal(calls.setCache, 0); + assert.deepEqual(result, cachedValue); + }); + + it('should merge platform setting code to real platform code and name', async () => { + const { ctx } = createPlatformServiceHarness({ + rows: [ + { code: 'TB', name: '淘宝平台', default_express_interface: 'QM_WMS' }, + ], + settingRows: [ + { id: 21, code: 'TB-STORE', platform_code: 'TB', warehouse_id: 100000 }, + ], + }); + const service = new PlatformService(ctx); + + const result = await service.getPlatformList(); + + assert.deepEqual(result, [ + { code: 'TB', name: '淘宝平台', default_express_interface: 'QM_WMS', value: 'TB', label: '淘宝平台', platform_code: 'TB', platform_name: '淘宝平台', is_system_setting: false }, + { id: 21, code: 'TB-STORE', name: 'TB-STORE (淘宝平台)', value: 'TB-STORE', label: 'TB-STORE (淘宝平台)', is_system_setting: true, alias: '', platform_code: 'TB', platform_name: '淘宝平台', default_express_interface: 'QM_WMS' }, + ]); + }); + + it('should delegate index.getPlatformList to the platform service', async () => { + const { ctx } = createPlatformServiceHarness(); + let serviceCalls = 0; + ctx.service = { + systems: { + platform: { + async getPlatformList() { + serviceCalls += 1; + return [ + { code: 'TB', name: '淘宝平台', default_express_interface: 'QM_WMS', value: 'TB', label: '淘宝平台' }, + ]; + }, + }, + }, + }; + + const methodService = new IndexMethodService(ctx); + const result = await methodService.getPlatformList(); + + assert.equal(serviceCalls, 1); + assert.equal(result.flag, 'success'); + assert.equal(result.message, 'ok'); + assert.equal(result.code, 200); + assert.deepEqual(result.data, [ + { code: 'TB', name: '淘宝平台', default_express_interface: 'QM_WMS', value: 'TB', label: '淘宝平台' }, + ]); + }); +}); diff --git a/test/app/service/systems/polo_api.test.js b/test/app/service/systems/polo_api.test.js new file mode 100644 index 0000000..5bc5917 --- /dev/null +++ b/test/app/service/systems/polo_api.test.js @@ -0,0 +1,222 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const PoloApiService = require('../../../../app/service/systems/polo_api'); + +describe('test/app/service/systems/polo_api.test.js', () => { + it('should call test request with fixed options', async () => { + const expectedResult = { ok: true, source: 'request-result' }; + let receivedOptions = null; + + const service = new PoloApiService({ + app: { + config: {}, + }, + }); + service.client.request = async options => { + receivedOptions = options; + return expectedResult; + }; + + const result = await service.test(); + + assert.deepEqual(receivedOptions, { + method: 'Differ.JH.LogisticsPlatFeatures', + platid: 556, + bizcontent: {}, + }); + assert.strictEqual(result, expectedResult); + }); + + it('should build kuaishou request with structured inputs', async () => { + const expectedResult = { ok: true, source: 'kuaishou-request' }; + let receivedOptions = null; + + const service = new PoloApiService({ + app: { + config: {}, + }, + }); + + service.client.request = async options => { + receivedOptions = options; + return expectedResult; + }; + + const result = await service.kuaishou({ + express_id: 'KS-556', + wmsOrder: { + sourceId: 'TX-20260416-001', + sourceOrderCode: 'ORDER-20260416-001', + postcode: 'p03', + wareHouseId: 1000, + storeId: 2000, + items: 'SKU001,1,测试商品', + goodsCount: 2, + orderWeight: 3.5, + address: '广东省广州市天河区测试路 1 号', + name: '张三', + expAreaName: '天河区', + cityName: '广州市', + province: '广东省', + tempMobile: '13800000000', + tel: '13900000000', + }, + expressConfig: { + storeName: '快手店铺', + address: '广东省广州市白云区仓库路 2 号', + senderName: '李四', + districtName: '白云区;太和镇', + cityName: '广州市', + senderTel: '020-12345678', + provinceName: '广东省', + siteCode: 'SITE-001', + clientId: 'CLIENT-001', + }, + }); + + assert.deepEqual(receivedOptions, { + method: 'Differ.JH.Logistics.PostOrder', + platid: 556, + bizcontent: { + orders: [{ + businessplat: 'OTHERS', + ismultiplepieces: '0', + businesstype: 'JH_Normal', + cpcode: 'KS-556', + customercode: '', + customername: '快手店铺', + goods: [{ + cnname: '测试商品', + count: '2', + unit: '属性', + currencytype: 'CNY', + Unit: '', + weight: '3.5', + price: '0.0', + }], + logisticsproductname: 'JH_02', + logistictype: 'KS-556', + mainsubpaymode: '1', + needencrypt: '1', + numpackage: '1', + orderno: 'ORDER-20260416-001', + ordersource: 'KUAI_SHOU', + ordertype: 'JH_Normal', + plattradeno: 'ORDER-20260416-001', + ProviderID: 1327, + providercode: 'KS-556', + receiver: { + address: '广东省广州市天河区测试路 1 号', + name: '张三', + area: '天河区', + city: '广州市', + mobile: '13800000000', + province: '广东省', + }, + sender: { + country: 'CN', + Company: '快手店铺', + address: '广东省广州市白云区仓库路 2 号', + name: '李四', + area: '白云区', + town: '太和镇', + city: '广州市', + phone: '020-12345678', + mobile: '020-12345678', + tel: '020-12345678', + province: '广东省', + }, + shipperno: 'CLIENT-001', + sitecode: 'SITE-001', + Inputsite: 'SITE-001', + transtype: '0', + }], + shoptype: 'JH_001', + }, + }); + assert.strictEqual(result, expectedResult); + }); + + it('should keep kuaishou fixed when a caller passes a different method and omit optional fields', async () => { + const expectedResult = { ok: true, source: 'kuaishou-defaults' }; + let receivedOptions = null; + + const service = new PoloApiService({ + app: { + config: {}, + }, + }); + + service.client.request = async options => { + receivedOptions = options; + return expectedResult; + }; + + const result = await service.kuaishou({ + method: 'Bad.Method.Should.Be.Ignored', + }); + + assert.deepEqual(receivedOptions, { + method: 'Differ.JH.Logistics.PostOrder', + platid: 556, + bizcontent: { + orders: [{ + businessplat: 'OTHERS', + ismultiplepieces: '0', + businesstype: 'JH_Normal', + cpcode: '', + customercode: '', + customername: '测试', + goods: [{ + cnname: '', + count: '0', + unit: '属性', + currencytype: 'CNY', + Unit: '', + weight: '0', + price: '0.0', + }], + logisticsproductname: 'JH_02', + logistictype: '', + mainsubpaymode: '1', + needencrypt: '1', + numpackage: '1', + orderno: '', + ordersource: 'KUAI_SHOU', + ordertype: 'JH_Normal', + plattradeno: '', + ProviderID: '', + providercode: '', + receiver: { + address: '', + name: '', + area: '', + city: '', + mobile: '', + province: '', + }, + sender: { + country: 'CN', + Company: '', + address: '', + name: '', + area: '', + town: '', + city: '', + phone: '', + mobile: '', + tel: '', + province: '', + }, + shipperno: '', + sitecode: '', + Inputsite: '', + transtype: '0', + }], + shoptype: 'JH_001', + }, + }); + assert.strictEqual(result, expectedResult); + }); +}); diff --git a/test/app/service/systems/qimen_query.test.js b/test/app/service/systems/qimen_query.test.js new file mode 100644 index 0000000..a26a931 --- /dev/null +++ b/test/app/service/systems/qimen_query.test.js @@ -0,0 +1,59 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const http = require('node:http'); +const QimenQueryService = require('../../../../app/service/systems/qimen_query'); + +describe('test/app/service/systems/qimen_query.test.js', () => { + it('should save qimen log with error info when http.request throws', async () => { + const originalRequest = http.request; + let savedLog = null; + + const ctx = { + qimenLogId: 'QL-20260414-abc123', + app: {}, + logger: { + info() {}, + warn() {}, + error() {}, + debug() {}, + }, + service: { + qimen: { + async saveQimenLog(logData) { + savedLog = { ...logData }; + return 123; + }, + }, + }, + }; + + const service = new QimenQueryService(ctx); + http.request = () => { + throw new Error('network down'); + }; + + try { + await assert.rejects( + async () => await service.sendRequest('http://example.com/router', '', { + body: '', + from_key: 'from-key', + to_key: 'to-key', + method: 'demo.method', + sign: 'demo-sign', + costomer_id: 'customer-1', + v: '2.0', + url: 'http://example.com/router', + }), + /network down/ + ); + } finally { + http.request = originalRequest; + } + + assert.ok(savedLog); + assert.equal(savedLog.log_id, 'QL-20260414-abc123'); + assert.equal(savedLog.body, ''); + assert.match(savedLog.result, /network down/); + }); +}); diff --git a/test/app/service/systems/setting/express.test.js b/test/app/service/systems/setting/express.test.js new file mode 100644 index 0000000..1849d9a --- /dev/null +++ b/test/app/service/systems/setting/express.test.js @@ -0,0 +1,284 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const { Op } = require('sequelize'); +const SettingExpressService = require('../../../../../app/service/systems/setting/express'); + +function buildRecord(row, calls) { + return { + ...row, + async update(updates) { + calls.updatePayload = { + id: Number(this.id), + updates: { + ...updates, + }, + }; + Object.assign(this, updates); + return this; + }, + get() { + return { ...this }; + }, + }; +} + +function createHarness(options = {}) { + const calls = { + systemExpressListCalls: 0, + findAndCountAllCalls: 0, + findOneCalls: [], + createPayload: null, + updatePayload: null, + }; + + const systemExpressList = options.systemExpressList || [ + { code: 'SF', name: '顺丰' }, + { code: 'YTO', name: '圆通' }, + ]; + const settingRows = options.settingRows || [ + { id: 11, warehouse_id: 100000, code: 'SF-001', name: '顺丰设置', express_code: 'SF' }, + { id: 12, warehouse_id: 100000, code: 'YTO-001', name: '圆通设置', express_code: 'YTO' }, + ]; + + const ctx = { + user: { + store_id: options.storeId || 100000, + }, + where: options.where || {}, + whereParsed: options.whereParsed || null, + app: { + Sequelize: { + Op, + }, + }, + model: { + ExpressSetting: { + async findAndCountAll(query) { + calls.findAndCountAllCalls += 1; + calls.findAndCountAllQuery = query; + return { + rows: options.rows || settingRows, + count: options.count !== undefined ? options.count : (options.rows || settingRows).length, + }; + }, + async findOne(query) { + calls.findOneCalls.push(query); + const where = query.where || {}; + const excludedId = where.id && where.id[Op.ne] ? Number(where.id[Op.ne]) : null; + const found = (options.settingRows || settingRows).find(row => { + const sameWarehouse = Number(row.warehouse_id) === Number(where.warehouse_id); + const isExcluded = excludedId && Number(row.id) === excludedId; + + if (Object.prototype.hasOwnProperty.call(where, 'id') && !Object.prototype.hasOwnProperty.call(where, 'code')) { + return sameWarehouse && Number(row.id) === Number(where.id) && !isExcluded; + } + + if (Object.prototype.hasOwnProperty.call(where, 'code')) { + const sameCode = String(row.code || '') === String(where.code || ''); + return sameWarehouse && sameCode && !isExcluded; + } + + return sameWarehouse && !isExcluded; + }); + + return found ? buildRecord({ ...found }, calls) : null; + }, + async create(payload) { + calls.createPayload = { + ...payload, + }; + const created = buildRecord({ + id: options.createdId || 99, + ...payload, + }, calls); + return created; + }, + }, + }, + service: { + systems: { + express: { + async getSystemExpressList() { + calls.systemExpressListCalls += 1; + return systemExpressList; + }, + }, + }, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + }; + + return { + ctx, + calls, + }; +} + +describe('test/app/service/systems/setting/express.test.js', () => { + it('should list mapped express settings with pagination and system express names', async () => { + const { ctx, calls } = createHarness({ + where: { + quickWhere: '设置', + }, + whereParsed: { + dynamicConditions: [], + rawConditionsByField: { + quickWhere: { + value: '设置', + }, + }, + }, + rows: [ + { id: 12, warehouse_id: 100000, code: 'YTO-001', name: '圆通设置', express_code: 'YTO' }, + ], + count: 1, + }); + const service = new SettingExpressService(ctx); + + const result = await service.list({ + page: 2, + page_size: 1, + where: { + quickWhere: '设置', + }, + }); + + assert.equal(calls.findAndCountAllCalls, 1); + assert.equal(calls.systemExpressListCalls, 1); + assert.equal(calls.findAndCountAllQuery.offset, 1); + assert.equal(calls.findAndCountAllQuery.limit, 1); + assert.equal(calls.findAndCountAllQuery.where[Op.and][0].warehouse_id, 100000); + assert.equal(result.code, 200); + assert.equal(result.data.total, 1); + assert.equal(result.data.page, 2); + assert.equal(result.data.page_size, 1); + assert.deepEqual(result.data.list, [ + { + id: 12, + warehouse_id: 100000, + code: 'YTO-001', + name: '圆通设置', + express_code: 'YTO', + express_name: '圆通', + express_label: '圆通', + }, + ]); + }); + + it('should prefer pagination object over legacy page fields', async () => { + const { ctx, calls } = createHarness({ + whereParsed: { + dynamicConditions: [], + rawConditionsByField: {}, + }, + }); + const service = new SettingExpressService(ctx); + + const result = await service.list({ + pagination: { + page: 3, + pageSize: 2, + }, + page: 1, + page_size: 10, + where: {}, + }); + + assert.equal(calls.findAndCountAllCalls, 1); + assert.equal(calls.findAndCountAllQuery.offset, 4); + assert.equal(calls.findAndCountAllQuery.limit, 2); + assert.equal(result.data.page, 3); + assert.equal(result.data.page_size, 2); + }); + + it('should load system express base list only', async () => { + const { ctx, calls } = createHarness(); + const service = new SettingExpressService(ctx); + + const result = await service.listBase(); + + assert.equal(calls.systemExpressListCalls, 1); + assert.deepEqual(result, { + code: 200, + data: [ + { code: 'SF', name: '顺丰' }, + { code: 'YTO', name: '圆通' }, + ], + }); + }); + + it('should mark code as occupied and exclude current record when checking uniqueness', async () => { + const { ctx, calls } = createHarness(); + const service = new SettingExpressService(ctx); + + const occupied = await service.checkCodeUnique({ + code: 'SF-001', + }); + const available = await service.checkCodeUnique({ + id: 11, + code: 'SF-001', + }); + + assert.equal(calls.findOneCalls.length, 2); + assert.equal(occupied.data.isUnique, false); + assert.equal(occupied.data.message, '快递编码已被当前仓库使用'); + assert.equal(available.data.isUnique, true); + }); + + it('should create a mapping after validating system express and code uniqueness', async () => { + const { ctx, calls } = createHarness(); + const service = new SettingExpressService(ctx); + + const result = await service.create({ + code: 'jd-001', + name: '京东设置', + express_code: 'SF', + }); + + assert.equal(calls.systemExpressListCalls, 1); + assert.equal(calls.findOneCalls.length, 1); + assert.equal(calls.createPayload.warehouse_id, 100000); + assert.equal(calls.createPayload.code, 'JD-001'.toUpperCase()); + assert.equal(calls.createPayload.express_code, 'SF'); + assert.equal(result.data.code, 'JD-001'.toUpperCase()); + assert.equal(result.data.express_name, '顺丰'); + }); + + it('should reject create when system express code does not exist', async () => { + const { ctx } = createHarness(); + const service = new SettingExpressService(ctx); + + await assert.rejects(async () => { + await service.create({ + code: 'SF-NEW', + name: '顺丰新增', + express_code: 'NOT_EXISTS', + }); + }, /系统快递编码不存在/); + }); + + it('should update a mapping and allow the same code on the current record', async () => { + const { ctx, calls } = createHarness(); + const service = new SettingExpressService(ctx); + + const result = await service.update({ + id: 11, + code: 'SF-001', + name: '顺丰新设置', + express_code: 'SF', + }); + + assert.equal(calls.findOneCalls.length >= 1, true); + assert.equal(calls.updatePayload.id, 11); + assert.equal(calls.updatePayload.updates.code, 'SF-001'); + assert.equal(calls.updatePayload.updates.name, '顺丰新设置'); + assert.equal(calls.updatePayload.updates.express_code, 'SF'); + assert.equal(result.data.code, 'SF-001'); + assert.equal(result.data.name, '顺丰新设置'); + }); +}); diff --git a/test/app/service/systems/setting/expressInterface.test.js b/test/app/service/systems/setting/expressInterface.test.js new file mode 100644 index 0000000..c095f0e --- /dev/null +++ b/test/app/service/systems/setting/expressInterface.test.js @@ -0,0 +1,340 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const { Op } = require('sequelize'); +const SettingExpressInterfaceService = require('../../../../../app/service/systems/setting/expressInterface'); + +function buildRecord(row, calls) { + return { + ...row, + async update(updates) { + calls.updatePayload = { + id: Number(this.id), + updates: { + ...updates, + }, + }; + Object.assign(this, updates); + return this; + }, + async destroy() { + calls.destroyPayload = { + id: Number(this.id), + }; + return 1; + }, + get() { + return { ...this }; + }, + }; +} + +function createHarness(options = {}) { + const calls = { + findAndCountAllCalls: 0, + findOneCalls: [], + createPayload: null, + updatePayload: null, + destroyPayload: null, + }; + + const defaultRows = options.rows || [ + { + id: 11, + warehouse_id: 100000, + name: '顺丰接口', + express_code: 'SF', + platform_code: 'TB', + express_platform_id: 1, + sender_name: '张三', + sender_tel: '13800000000', + weight: 10, + token: 'token-1', + viewer: '验视员A', + client_id: 'client-1', + is_share: 1, + share_id: 9001, + can_use_count: 3, + province_name: '广东省', + city_name: '深圳市', + district_name: '南山区', + site_code: 'SITE-01', + product_type: 'STD', + shop_name: '旗舰店', + }, + { + id: 12, + warehouse_id: 100000, + name: '圆通接口', + express_code: 'YTO', + platform_code: 'JD', + express_platform_id: 2, + }, + { + id: 21, + warehouse_id: 200000, + name: '其他仓库接口', + express_code: 'SF', + platform_code: 'TB', + express_platform_id: 1, + }, + ]; + + const ctx = { + user: { + store_id: options.storeId || 100000, + }, + where: options.where || {}, + whereParsed: options.whereParsed || null, + app: { + Sequelize: { + Op, + }, + }, + model: { + ExpressInterface: { + async findAndCountAll(query) { + calls.findAndCountAllCalls += 1; + calls.findAndCountAllQuery = query; + return { + rows: options.listRows || defaultRows, + count: options.count !== undefined ? options.count : (options.listRows || defaultRows).length, + }; + }, + async findOne(query) { + calls.findOneCalls.push(query); + const where = query.where || {}; + const excludedId = where.id && where.id[Op.ne] ? Number(where.id[Op.ne]) : null; + const found = defaultRows.find(row => { + const sameWarehouse = Number(row.warehouse_id) === Number(where.warehouse_id); + const isExcluded = excludedId && Number(row.id) === excludedId; + + if (Object.prototype.hasOwnProperty.call(where, 'id') && !Object.prototype.hasOwnProperty.call(where, 'express_code') && !Object.prototype.hasOwnProperty.call(where, 'platform_code')) { + return sameWarehouse && Number(row.id) === Number(where.id) && !isExcluded; + } + + if (Object.prototype.hasOwnProperty.call(where, 'express_code')) { + const sameCode = String(row.express_code || '') === String(where.express_code || ''); + if (!sameCode) { + return false; + } + } + + if (Object.prototype.hasOwnProperty.call(where, 'platform_code')) { + const samePlatform = String(row.platform_code || '') === String(where.platform_code || ''); + if (!samePlatform) { + return false; + } + } + + if (Object.prototype.hasOwnProperty.call(where, 'express_platform_id')) { + if (Number(row.express_platform_id) !== Number(where.express_platform_id)) { + return false; + } + } + + return sameWarehouse && !isExcluded; + }); + + return found ? buildRecord({ ...found }, calls) : null; + }, + async create(payload) { + calls.createPayload = { + ...payload, + }; + return buildRecord({ + id: options.createdId || 99, + ...payload, + }, calls); + }, + }, + }, + }; + + return { + ctx, + calls, + }; +} + +describe('test/app/service/systems/setting/expressInterface.test.js', () => { + it('should list express interfaces with pagination and quick where', async () => { + const { ctx, calls } = createHarness({ + where: { + quickWhere: '接口', + }, + whereParsed: { + dynamicConditions: [], + rawConditionsByField: { + quickWhere: { + value: '接口', + }, + }, + }, + listRows: [ + { + id: 11, + warehouse_id: 100000, + name: '顺丰接口', + express_code: 'SF', + platform_code: 'TB', + express_platform_id: 1, + sender_name: '张三', + sender_tel: '13800000000', + weight: 10, + token: 'token-1', + viewer: '验视员A', + client_id: 'client-1', + is_share: 1, + share_id: 9001, + can_use_count: 3, + province_name: '广东省', + city_name: '深圳市', + district_name: '南山区', + site_code: 'SITE-01', + product_type: 'STD', + shop_name: '旗舰店', + }, + ], + count: 1, + }); + const service = new SettingExpressInterfaceService(ctx); + + const result = await service.list({ + page: 2, + page_size: 1, + where: { + quickWhere: '接口', + }, + }); + + assert.equal(calls.findAndCountAllCalls, 1); + assert.equal(calls.findAndCountAllQuery.offset, 1); + assert.equal(calls.findAndCountAllQuery.limit, 1); + assert.equal(calls.findAndCountAllQuery.where[Op.and][0].warehouse_id, 100000); + assert.equal(result.code, 200); + assert.equal(result.data.total, 1); + assert.equal(result.data.page, 2); + assert.equal(result.data.page_size, 1); + assert.equal(result.data.list[0].name, '顺丰接口'); + assert.equal(result.data.list[0].platform_code, 'TB'); + assert.equal(result.data.list[0].express_platform_id, 1); + }); + + it('should create a new express interface and normalize codes', async () => { + const { ctx, calls } = createHarness(); + const service = new SettingExpressInterfaceService(ctx); + + const result = await service.create({ + name: '京东接口', + express_code: 'jd', + platform_code: 'tb', + express_platform_id: 3, + sender_name: '李四', + sender_tel: '13900000000', + token: ' token-2 ', + is_share: 1, + can_use_count: 5, + }); + + assert.equal(calls.createPayload.warehouse_id, 100000); + assert.equal(calls.createPayload.express_code, 'JD'); + assert.equal(calls.createPayload.platform_code, 'TB'); + assert.equal(calls.createPayload.express_platform_id, 3); + assert.equal(result.data.express_code, 'JD'); + assert.equal(result.data.platform_code, 'TB'); + assert.equal(result.data.sender_name, '李四'); + assert.equal(result.data.token, 'token-2'); + }); + + it('should reject create when express code conflicts inside the current warehouse', async () => { + const { ctx } = createHarness(); + const service = new SettingExpressInterfaceService(ctx); + + await assert.rejects(async () => { + await service.create({ + name: '重复编码接口', + express_code: 'SF', + platform_code: 'WX', + express_platform_id: 4, + }); + }, /快递编码已被当前仓库使用/); + }); + + it('should reject create when platform and interface combination conflicts', async () => { + const { ctx } = createHarness(); + const service = new SettingExpressInterfaceService(ctx); + + await assert.rejects(async () => { + await service.create({ + name: '重复接口', + express_code: 'ZTO', + platform_code: 'TB', + express_platform_id: 1, + }); + }, /当前平台和快递接口组合已被使用/); + }); + + it('should update a record with boundary checks and partial fields', async () => { + const { ctx, calls } = createHarness(); + const service = new SettingExpressInterfaceService(ctx); + + const result = await service.update({ + id: 11, + name: '顺丰接口-更新', + token: ' token-updated ', + can_use_count: 0, + }); + + assert.equal(calls.findOneCalls.length >= 1, true); + assert.equal(calls.updatePayload.id, 11); + assert.equal(calls.updatePayload.updates.name, '顺丰接口-更新'); + assert.equal(calls.updatePayload.updates.token, 'token-updated'); + assert.equal(calls.updatePayload.updates.can_use_count, 0); + assert.equal(result.data.name, '顺丰接口-更新'); + }); + + it('should delete a record only inside the current warehouse', async () => { + const { ctx, calls } = createHarness(); + const service = new SettingExpressInterfaceService(ctx); + + const result = await service.delete({ + id: 11, + }); + + assert.equal(calls.destroyPayload.id, 11); + assert.equal(result.code, 200); + assert.equal(result.data.deleted, true); + assert.equal(result.data.warehouse_id, 100000); + }); + + it('should reject cross-warehouse updates and deletes', async () => { + const { ctx } = createHarness({ + storeId: 100000, + rows: [ + { + id: 21, + warehouse_id: 200000, + name: '其他仓库接口', + express_code: 'SF', + platform_code: 'TB', + express_platform_id: 1, + }, + ], + }); + const service = new SettingExpressInterfaceService(ctx); + + await assert.rejects(async () => { + await service.update({ + id: 21, + name: '越权更新', + }); + }, /快递接口不存在或无权限操作/); + + await assert.rejects(async () => { + await service.delete({ + id: 21, + }); + }, /快递接口不存在或无权限操作/); + }); +}); diff --git a/test/app/service/systems/setting/platform.test.js b/test/app/service/systems/setting/platform.test.js new file mode 100644 index 0000000..da5c0f5 --- /dev/null +++ b/test/app/service/systems/setting/platform.test.js @@ -0,0 +1,331 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const { Op } = require('sequelize'); +const SettingPlatformService = require('../../../../../app/service/systems/setting/platform'); + +function buildRecord(row, calls) { + return { + ...row, + async update(updates) { + calls.updatePayload = { + id: Number(this.id), + updates: { + ...updates, + }, + }; + Object.assign(this, updates); + return this; + }, + async destroy() { + calls.destroyPayload = { + id: Number(this.id), + }; + return 1; + }, + get() { + return { ...this }; + }, + }; +} + +function createHarness(options = {}) { + const calls = { + findAndCountAllCalls: 0, + findOneCalls: [], + createPayload: null, + updatePayload: null, + destroyPayload: null, + platformFindOneCalls: [], + }; + + const platformRows = options.platformRows || [ + { code: 'TB', name: '淘宝平台', default_express_interface: 'QM_WMS' }, + { code: 'JD', name: '京东平台', default_express_interface: 'OPEN_API' }, + { code: 'PDD', name: '拼多多平台', default_express_interface: 'PDD_API' }, + ]; + + const defaultRows = options.rows || [ + { + id: 11, + code: 'TB-STORE', + name: '淘宝设置', + platform_code: 'TB', + warehouse_id: 100000, + platform: platformRows[0], + }, + { + id: 12, + code: 'JD-STORE', + name: '京东设置', + platform_code: 'JD', + warehouse_id: 100000, + platform: platformRows[1], + }, + { + id: 21, + code: 'OTHER-STORE', + name: '其他仓库设置', + platform_code: 'TB', + warehouse_id: 200000, + platform: platformRows[0], + }, + ]; + + const ctx = { + user: { + store_id: options.storeId || 100000, + }, + where: options.where || {}, + whereParsed: options.whereParsed || null, + app: { + Sequelize: { + Op, + }, + }, + model: { + Platform: { + async findOne(query) { + calls.platformFindOneCalls.push(query); + const code = String(query.where && query.where.code || '').trim(); + const found = platformRows.find(row => String(row.code) === code); + return found ? { ...found } : null; + }, + }, + PlatformSetting: { + async findAndCountAll(query) { + calls.findAndCountAllCalls += 1; + calls.findAndCountAllQuery = query; + return { + rows: options.listRows || defaultRows, + count: options.count !== undefined ? options.count : (options.listRows || defaultRows).length, + }; + }, + async findOne(query) { + calls.findOneCalls.push(query); + const where = query.where || {}; + const excludedId = where.id && where.id[Op.ne] ? Number(where.id[Op.ne]) : null; + const found = defaultRows.find(row => { + const sameWarehouse = Number(row.warehouse_id) === Number(where.warehouse_id); + const isExcluded = excludedId && Number(row.id) === excludedId; + + if (Object.prototype.hasOwnProperty.call(where, 'id') && !Object.prototype.hasOwnProperty.call(where, 'code') && !Object.prototype.hasOwnProperty.call(where, 'platform_code')) { + return sameWarehouse && Number(row.id) === Number(where.id) && !isExcluded; + } + + if (Object.prototype.hasOwnProperty.call(where, 'code')) { + if (String(row.code || '') !== String(where.code || '')) { + return false; + } + } + + if (Object.prototype.hasOwnProperty.call(where, 'platform_code')) { + if (String(row.platform_code || '') !== String(where.platform_code || '')) { + return false; + } + } + + return sameWarehouse && !isExcluded; + }); + + return found ? buildRecord({ ...found }, calls) : null; + }, + async create(payload) { + calls.createPayload = { + ...payload, + }; + const platform = platformRows.find(row => String(row.code) === String(payload.platform_code || '')) || null; + return buildRecord({ + id: options.createdId || 99, + ...payload, + platform, + }, calls); + }, + }, + }, + }; + + return { + ctx, + calls, + }; +} + +describe('test/app/service/systems/setting/platform.test.js', () => { + it('should list platform settings with pagination and quick where', async () => { + const { ctx, calls } = createHarness({ + where: { + quickWhere: '设置', + }, + whereParsed: { + dynamicConditions: [], + rawConditionsByField: { + quickWhere: { + value: '设置', + }, + }, + }, + listRows: [ + { + id: 11, + code: 'TB-STORE', + name: '淘宝设置', + platform_code: 'TB', + warehouse_id: 100000, + platform: { + code: 'TB', + name: '淘宝平台', + default_express_interface: 'QM_WMS', + }, + }, + ], + count: 1, + }); + const service = new SettingPlatformService(ctx); + + const result = await service.list({ + page: 2, + page_size: 1, + where: { + quickWhere: '设置', + }, + }); + + assert.equal(calls.findAndCountAllCalls, 1); + assert.equal(calls.findAndCountAllQuery.offset, 1); + assert.equal(calls.findAndCountAllQuery.limit, 1); + assert.equal(calls.findAndCountAllQuery.where[Op.and][0].warehouse_id, 100000); + assert.equal(result.code, 200); + assert.equal(result.data.total, 1); + assert.equal(result.data.page, 2); + assert.equal(result.data.page_size, 1); + assert.equal(result.data.list[0].code, 'TB-STORE'); + assert.equal(result.data.list[0].platform_code, 'TB'); + assert.equal(result.data.list[0].platform_name, '淘宝平台'); + assert.equal(result.data.list[0].platform_label, 'TB-STORE (淘宝平台)'); + }); + + it('should create a new platform setting and ignore external warehouse id', async () => { + const { ctx, calls } = createHarness(); + const service = new SettingPlatformService(ctx); + + const result = await service.create({ + code: 'PDD-STORE', + name: '淘宝设置', + platform_code: 'PDD', + warehouse_id: 999999, + }); + + assert.equal(calls.createPayload.warehouse_id, 100000); + assert.equal(calls.createPayload.code, 'PDD-STORE'); + assert.equal(calls.createPayload.name, '淘宝设置'); + assert.equal(calls.createPayload.platform_code, 'PDD'); + assert.equal(result.data.code, 'PDD-STORE'); + assert.equal(result.data.platform_code, 'PDD'); + assert.equal(result.data.platform_name, '拼多多平台'); + assert.equal(result.data.platform_label, 'PDD-STORE (拼多多平台)'); + }); + + it('should reject create when platform code is missing in the system platform table', async () => { + const { ctx } = createHarness(); + const service = new SettingPlatformService(ctx); + + await assert.rejects(async () => { + await service.create({ + code: 'TB-STORE', + name: '淘宝设置', + platform_code: 'UNKNOWN', + }); + }, /platform_code 不存在或不支持/); + }); + + it('should reject create when code or platform code conflicts in the current warehouse', async () => { + const { ctx } = createHarness(); + const service = new SettingPlatformService(ctx); + + await assert.rejects(async () => { + await service.create({ + code: 'TB-STORE', + name: '重复设置', + platform_code: 'JD', + }); + }, /code 已被当前仓库使用/); + + await assert.rejects(async () => { + await service.create({ + code: 'NEW-CODE', + name: '重复平台', + platform_code: 'TB', + }); + }, /platform_code 已被当前仓库使用/); + }); + + it('should update a record with boundary checks and return platform display fields', async () => { + const { ctx, calls } = createHarness(); + const service = new SettingPlatformService(ctx); + + const result = await service.update({ + id: 11, + code: 'TB-STORE-NEW', + name: '淘宝设置-更新', + platform_code: 'PDD', + }); + + assert.equal(calls.findOneCalls.length >= 1, true); + assert.equal(calls.updatePayload.id, 11); + assert.equal(calls.updatePayload.updates.code, 'TB-STORE-NEW'); + assert.equal(calls.updatePayload.updates.name, '淘宝设置-更新'); + assert.equal(calls.updatePayload.updates.platform_code, 'PDD'); + assert.equal(result.data.code, 'TB-STORE-NEW'); + assert.equal(result.data.platform_code, 'PDD'); + assert.equal(result.data.platform_name, '拼多多平台'); + }); + + it('should delete a record only inside the current warehouse', async () => { + const { ctx, calls } = createHarness(); + const service = new SettingPlatformService(ctx); + + const result = await service.delete({ + id: 11, + }); + + assert.equal(calls.destroyPayload.id, 11); + assert.equal(result.code, 200); + assert.equal(result.data.deleted, true); + assert.equal(result.data.warehouse_id, 100000); + }); + + it('should reject cross-warehouse updates and deletes', async () => { + const { ctx } = createHarness({ + storeId: 100000, + rows: [ + { + id: 21, + code: 'OTHER-STORE', + name: '其他仓库设置', + platform_code: 'TB', + warehouse_id: 200000, + platform: { + code: 'TB', + name: '淘宝平台', + default_express_interface: 'QM_WMS', + }, + }, + ], + }); + const service = new SettingPlatformService(ctx); + + await assert.rejects(async () => { + await service.update({ + id: 21, + name: '越权更新', + }); + }, /平台设置不存在或无权限操作/); + + await assert.rejects(async () => { + await service.delete({ + id: 21, + }); + }, /平台设置不存在或无权限操作/); + }); +}); diff --git a/test/app/service/systems/stock_store.stockWarehouse.conditions.test.js b/test/app/service/systems/stock_store.stockWarehouse.conditions.test.js index cff7740..e469840 100644 --- a/test/app/service/systems/stock_store.stockWarehouse.conditions.test.js +++ b/test/app/service/systems/stock_store.stockWarehouse.conditions.test.js @@ -7,8 +7,14 @@ function createTestContext(options = {}) { const calls = { countArgs: null, findArgs: null, + findOneArgs: null, + updateArgs: null, barcodeCalls: [], fileRefArgs: null, + transactionCount: 0, + transactionCommits: 0, + transactionRollbacks: 0, + operationLogCalls: [], }; const Op = { @@ -64,6 +70,14 @@ function createTestContext(options = {}) { calls.findArgs = args; return rows; }, + async findOne(args) { + calls.findOneArgs = args; + return options.stockInfo || null; + }, + async update(args) { + calls.updateArgs = args; + return [ 1 ]; + }, }, StockBarcode: { async findAll(args) { @@ -113,6 +127,27 @@ function createTestContext(options = {}) { logger: { error() {}, }, + service: { + systems: { + operationLog: { + async createOperationLog(args) { + calls.operationLogCalls.push(args); + }, + }, + }, + }, + }; + + model.transaction = async () => { + calls.transactionCount += 1; + return { + async commit() { + calls.transactionCommits += 1; + }, + async rollback() { + calls.transactionRollbacks += 1; + }, + }; }; return { @@ -317,4 +352,251 @@ describe('test/app/service/systems/stock_store.stockWarehouse.conditions.test.js assert.match(result.message, /筛选条件解析失败/); assert.match(result.message, /字段 item_code 条件必须是对象/); }); + + it('should return shelf life management flag as boolean in search result', async () => { + const { service, calls } = createServiceHarness({ + rows: [{ + toJSON() { + return { + id: 1, + item_code: 'SKU-1', + goods_code: 'G-1', + item_name: '商品A', + sku_property: '默认规格', + stock_unit: '件', + quantity: 10, + locked_quantity: 2, + brand_name: '品牌A', + item_type: 'normal', + is_batch_mgmt: 'Y', + is_shelf_life_mgmt: 'Y', + barcodes: [{ barcode: 'BC-1' }], + store_stock: { + store_id: 100000, + store_remask: '主仓', + }, + }; + }, + }], + }); + + const result = await service.search({ + keyword: '', + }); + + assert.equal(result.code, 200); + assert.equal(Array.isArray(result.data), true); + assert.equal(result.data.length, 1); + assert.equal(Object.prototype.hasOwnProperty.call(result.data[0], 'is_batch_mgmt_enabled'), true); + assert.equal(typeof result.data[0].is_batch_mgmt_enabled, 'boolean'); + assert.equal(result.data[0].is_batch_mgmt_enabled, true); + assert.equal(Object.prototype.hasOwnProperty.call(result.data[0], 'is_batch_mgmt'), false); + assert.equal(Object.prototype.hasOwnProperty.call(result.data[0], 'is_shelf_life_mgmt'), true); + assert.equal(typeof result.data[0].is_shelf_life_mgmt, 'boolean'); + assert.equal(result.data[0].is_shelf_life_mgmt, true); + assert.deepEqual(result.data[0].barcodes, [ 'BC-1' ]); + assert.ok(calls.findArgs); + assert.ok(calls.findArgs.attributes.includes('is_shelf_life_mgmt')); + }); + + it('should return shelf life threshold fields in search result', async () => { + const { service, calls } = createServiceHarness({ + rows: [{ + toJSON() { + return { + id: 2, + item_code: 'SKU-2', + goods_code: 'G-2', + item_name: '商品B', + sku_property: '默认规格', + stock_unit: '件', + quantity: 8, + locked_quantity: 1, + brand_name: '品牌B', + item_type: 'normal', + inbound_min_days: 3, + outbound_min_days: 5, + shelf_life_days: 30, + remaining_threshold_days: 7, + is_shelf_life_mgmt: 'N', + barcodes: [], + store_stock: { + store_id: 100000, + store_remask: '主仓', + }, + }; + }, + }], + }); + + const result = await service.search({ + keyword: '', + }); + + assert.equal(result.code, 200); + assert.equal(result.data.length, 1); + assert.equal(result.data[0].inbound_min_days, 3); + assert.equal(result.data[0].outbound_min_days, 5); + assert.equal(result.data[0].shelf_life_days, 30); + assert.equal(result.data[0].remaining_threshold_days, 7); + assert.equal(typeof result.data[0].inbound_min_days, 'number'); + assert.equal(typeof result.data[0].outbound_min_days, 'number'); + assert.equal(typeof result.data[0].shelf_life_days, 'number'); + assert.equal(typeof result.data[0].remaining_threshold_days, 'number'); + assert.ok(calls.findArgs); + for (const field of [ 'inbound_min_days', 'outbound_min_days', 'shelf_life_days', 'remaining_threshold_days' ]) { + assert.ok(calls.findArgs.attributes.includes(field)); + } + }); + + it('should return warehouse day threshold fields in getInfo response', async () => { + const { service, calls } = createServiceHarness({ + stockInfo: { + id: 1, + item_code: 'SKU-1', + shelf_life_days: 10, + inbound_min_days: 3, + outbound_min_days: 5, + remaining_threshold_days: 7, + enable_box_spec: 1, + }, + }); + + const result = await service.getInfo({ + id: 1, + }); + + assert.equal(result.id, 1); + assert.equal(result.shelf_life_days, 10); + assert.equal(result.inbound_min_days, 3); + assert.equal(result.outbound_min_days, 5); + assert.equal(result.remaining_threshold_days, 7); + assert.equal(result.enable_box_spec, true); + assert.ok(calls.findOneArgs); + assert.ok(calls.findOneArgs.attributes.includes('shelf_life_days')); + assert.ok(calls.findOneArgs.attributes.includes('inbound_min_days')); + assert.ok(calls.findOneArgs.attributes.includes('outbound_min_days')); + assert.ok(calls.findOneArgs.attributes.includes('remaining_threshold_days')); + }); + + it('should persist shelf life fields when saving warehouse stock', async () => { + const { service, calls } = createServiceHarness({ + stockInfo: { + id: 9, + deleted_at: null, + }, + }); + + service.getInfo = async ({ id }) => ({ + id, + shelf_life_days: 30, + inbound_min_days: 3, + outbound_min_days: 5, + remaining_threshold_days: 7, + }); + + const result = await service.saveWarehouseStock({ + id: 9, + item_code: 'SKU-9', + item_name: '商品九号', + sku_property: '默认规格', + stock_unit: '件', + packing_requirements: '', + length: 10, + width: 11, + height: 12, + volume: 13, + gross_weight: 14, + net_weight: 15, + tag_price: 16, + retail_price: 17, + is_sn_mgmt: 'N', + is_shelf_life_mgmt: 'Y', + is_batch_mgmt: 'N', + prohibited_id: null, + brand_name: '品牌九', + managementFlags: '', + enable_box_spec: false, + box_unit: '', + quantity_per_box: 0, + box_gross_weight: 0, + box_net_weight: 0, + box_length: 0, + box_width: 0, + box_height: 0, + box_volume: 0, + box_remark: '', + shelf_life_days: 30, + inbound_min_days: 3, + outbound_min_days: 5, + remaining_threshold_days: 7, + }); + + assert.equal(result.id, 9); + assert.equal(calls.transactionCount, 1); + assert.equal(calls.transactionCommits, 1); + assert.equal(calls.transactionRollbacks, 0); + assert.ok(calls.updateArgs); + assert.equal(calls.updateArgs.shelf_life_days, 30); + assert.equal(calls.updateArgs.inbound_min_days, 3); + assert.equal(calls.updateArgs.outbound_min_days, 5); + assert.equal(calls.updateArgs.remaining_threshold_days, 7); + assert.equal(calls.operationLogCalls.length, 1); + }); + + it('should reject saving warehouse stock when shelf life fields are missing or invalid', async () => { + const { service, calls } = createServiceHarness({ + stockInfo: { + id: 10, + deleted_at: null, + }, + }); + + await assert.rejects( + service.saveWarehouseStock({ + id: 10, + item_code: 'SKU-10', + item_name: '商品十号', + sku_property: '默认规格', + stock_unit: '件', + packing_requirements: '', + length: 10, + width: 11, + height: 12, + volume: 13, + gross_weight: 14, + net_weight: 15, + tag_price: 16, + retail_price: 17, + is_sn_mgmt: 'N', + is_shelf_life_mgmt: 'Y', + is_batch_mgmt: 'N', + prohibited_id: null, + brand_name: '品牌十', + managementFlags: '', + enable_box_spec: false, + box_unit: '', + quantity_per_box: 0, + box_gross_weight: 0, + box_net_weight: 0, + box_length: 0, + box_width: 0, + box_height: 0, + box_volume: 0, + box_remark: '', + shelf_life_days: 0, + inbound_min_days: 3, + outbound_min_days: 5, + remaining_threshold_days: 7, + }), + error => { + assert.equal(error.message, '启用保质期管理时,shelf_life_days、inbound_min_days、outbound_min_days、remaining_threshold_days 都必须存在且大于 0'); + return true; + } + ); + + assert.equal(calls.transactionCount, 0); + assert.equal(calls.updateArgs, null); + assert.equal(calls.operationLogCalls.length, 0); + }); }); diff --git a/test/app/service/systems/storage.expiry.test.js b/test/app/service/systems/storage.expiry.test.js new file mode 100644 index 0000000..d37e580 --- /dev/null +++ b/test/app/service/systems/storage.expiry.test.js @@ -0,0 +1,227 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const StorageExpiryService = require('../../../../app/service/systems/storage/expiry'); +const StorageExpiryMethodService = require('../../../../app/service/systemMethods/storage/expiry'); + +function createServiceHarness(options = {}) { + const calls = { + findArgs: null, + }; + + const Op = { + and: '$and', + gt: '$gt', + ne: '$ne', + }; + + const rows = options.rows || [{ + get() { + return { + id: 11, + warehouse_id: 100000, + store_id: 100001, + space_id: 9, + stock_id: 88, + batch_no: 'BATCH-1', + inventory_type: 'ZP', + quantity: 10, + locked_quantity: 1, + available_quantity: 9, + production_date: '2026-04-01 00:00:00', + expiry_date: '2026-04-10 00:00:00', + inbound_time: '2026-04-02 00:00:00', + created_at: '2026-04-02 00:00:00', + updated_at: '2026-04-03 00:00:00', + stock: { + id: 88, + item_code: 'SKU-88', + goods_code: 'G-88', + item_name: '测试商品', + sku_property: '默认规格', + stock_unit: '件', + store_id: 100001, + warehouse_id: 100000, + is_shelf_life_mgmt: 'Y', + remaining_threshold_days: 15, + }, + space: { + id: 9, + space_code: 'A-01', + custom_name: '一号位', + }, + }; + }, + }]; + + const model = { + Storage: { + async findAndCountAll(args) { + calls.findArgs = args; + return { + count: options.total ?? rows.length, + rows, + }; + }, + }, + StockWarehouse: {}, + LocationSpace: {}, + }; + + const app = { + Sequelize: { Op, literal: value => ({ literal: value }) }, + model, + formatDate(value) { + return String(value).slice(0, 10); + }, + }; + + const ctx = { + app, + model, + user: { + store_id: 100000, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + }; + + return { + app, + ctx, + model, + calls, + Op, + }; +} + +describe('test/app/service/systems/storage.expiry.test.js', () => { + it('should query expiry list by current warehouse and shelf-life stock include', async () => { + const harness = createServiceHarness(); + const service = new StorageExpiryService(harness.ctx); + harness.ctx.whereParsed = { + dynamicConditions: [ + { inventory_type: 'ZP' }, + ], + bucketConditions: { + stock: [ + { item_code: { $like: '%SKU%' } }, + ], + }, + }; + + const result = await service.list({ + where: { + item_code: { + operator: 'like', + value: 'SKU', + }, + }, + }, { + page: 2, + pageSize: 5, + }); + + assert.equal(result.code, 200); + assert.equal(result.message, '查询成功'); + assert.equal(result.data.pagination.page, 2); + assert.equal(result.data.pagination.pageSize, 5); + assert.equal(result.data.list.length, 1); + assert.equal(result.data.list[0].threshold_days, 15); + assert.equal(result.data.list[0].remaining_days >= 0, true); + assert.equal(result.data.list[0].stock.item_code, 'SKU-88'); + assert.ok(harness.calls.findArgs); + assert.equal(harness.calls.findArgs.include[0].as, 'stock'); + assert.equal(harness.calls.findArgs.where.$and[0].warehouse_id, 100000); + }); + + it('should return empty pagination when user has no warehouse', async () => { + const harness = createServiceHarness(); + harness.ctx.user.store_id = 0; + const service = new StorageExpiryService(harness.ctx); + + const result = await service.list(); + + assert.equal(result.code, 400); + assert.equal(result.data.list.length, 0); + assert.equal(result.data.pagination.total, 0); + }); + + it('should pass normalized where and pagination through systemMethods wrapper', async () => { + const captured = { + where: null, + pagination: null, + }; + + const Op = { + and: '$and', + gt: '$gt', + ne: '$ne', + like: '$like', + }; + + const ctx = { + app: { + Sequelize: { Op }, + }, + service: { + systems: { + storage: { + expiry: { + async list(where, pagination) { + captured.where = where; + captured.pagination = pagination; + return { + code: 200, + message: '查询成功', + data: { + list: [], + pagination: { + page: 1, + pageSize: 20, + total: 0, + totalPages: 0, + hasPrevious: false, + hasNext: false, + }, + }, + }; + }, + }, + }, + }, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + user: { + store_id: 100000, + }, + }; + + const methodService = new StorageExpiryMethodService(ctx); + const result = await methodService.list({ + where: { + item_name: { + operator: 'like', + value: '苹果', + }, + }, + pagination: { + page: 3, + pageSize: 7, + }, + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.code, 200); + assert.equal(captured.pagination.page, 3); + assert.equal(captured.pagination.pageSize, 7); + assert.equal(captured.where.item_name.operator, 'like'); + }); +}); diff --git a/test/app/service/systems/storage.inventory.test.js b/test/app/service/systems/storage.inventory.test.js new file mode 100644 index 0000000..c047d26 --- /dev/null +++ b/test/app/service/systems/storage.inventory.test.js @@ -0,0 +1,390 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const StorageInventoryService = require('../../../../app/service/systems/storage/inventory'); + +const DAY_MS = 24 * 60 * 60 * 1000; + +/** + * 将指定偏移天数转换为用于测试的日期时间字符串。 + * + * @param {number} dayOffset 相对当前时间的天数偏移 + * @return {string} 日期时间字符串 + */ +function toDateTimeString(dayOffset) { + const value = new Date(Date.now() + (dayOffset * DAY_MS)).toISOString().replace('T', ' '); + return value.slice(0, 19); +} + +/** + * 生成带 get 方法的 Sequelize 模型行对象。 + * + * @param {Object} plain 原始对象 + * @return {Object} 模型行对象 + */ +function createModelRow(plain) { + return { + get() { + return plain; + }, + }; +} + +/** + * 创建库存列表服务测试支架。 + * + * @param {Object} [options={}] 测试选项 + * @param {Object[]} [options.batchRows=[]] 批次模式返回行 + * @param {Object[]} [options.mergedRows=[]] 合并模式返回行 + * @param {number} [options.batchTotal] 批次模式总数 + * @param {number} [options.mergedTotal] 合并模式总数 + * @return {Object} 测试支架 + */ +function createServiceHarness(options = {}) { + const batchRows = Array.isArray(options.batchRows) ? options.batchRows.map(createModelRow) : []; + const mergedRows = Array.isArray(options.mergedRows) ? options.mergedRows : []; + const calls = { + findAndCountAllArgs: null, + countArgs: null, + findAllArgs: null, + stockBarcodeArgs: [], + fileReferenceArgs: [], + }; + + const Op = { + and: '$and', + gt: '$gt', + ne: '$ne', + in: '$in', + }; + + const stockBarcodes = Array.isArray(options.stockBarcodes) ? options.stockBarcodes : []; + const fileReferences = Array.isArray(options.fileReferences) ? options.fileReferences : []; + + const model = { + Storage: { + async findAndCountAll(args) { + calls.findAndCountAllArgs = args; + return { + count: options.batchTotal ?? batchRows.length, + rows: batchRows, + }; + }, + async count(args) { + calls.countArgs = args; + return options.mergedTotal ?? mergedRows.length; + }, + async findAll(args) { + calls.findAllArgs = args; + return mergedRows; + }, + }, + StockWarehouse: {}, + StockBarcode: { + async findAll(args) { + calls.stockBarcodeArgs.push(args); + const stockIdCondition = args?.where?.stock_id || {}; + const stockIds = Array.isArray(stockIdCondition[Op.in]) ? stockIdCondition[Op.in].map(Number) : []; + return stockBarcodes.filter(item => stockIds.includes(Number(item.stock_id))); + }, + }, + FileReference: { + async findAll(args) { + calls.fileReferenceArgs.push(args); + const businessIdCondition = args?.where?.business_id || {}; + const businessIds = Array.isArray(businessIdCondition[Op.in]) ? businessIdCondition[Op.in].map(Number) : []; + return fileReferences.filter(item => businessIds.includes(Number(item.business_id))); + }, + }, + File: {}, + LocationSpace: {}, + }; + + const app = { + Sequelize: { + Op, + fn(name, field) { + return { fn: name, field }; + }, + col(value) { + return { col: value }; + }, + literal(value) { + return { literal: value }; + }, + }, + model, + formatDate(value) { + return String(value).slice(0, 10); + }, + }; + + const ctx = { + app, + model, + user: { + store_id: 100000, + }, + whereParsed: { + dynamicConditions: [], + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + }; + + return { + app, + ctx, + model, + calls, + }; +} + +describe('test/app/service/systems/storage.inventory.test.js', () => { + it('should return production and expiry dates with warning flag for batch list', async () => { + const productionDate = toDateTimeString(-6); + const expiryDate = toDateTimeString(4); + const expectedProductionDate = productionDate.slice(0, 10); + const expectedExpiryDate = expiryDate.slice(0, 10); + const harness = createServiceHarness({ + batchRows: [{ + id: 1, + stock_id: 88, + space_id: 9, + inventory_type: 'ZP', + warehouse_id: 100000, + store_id: 100001, + quantity: 12, + locked_quantity: 2, + available_quantity: 10, + created_at: toDateTimeString(-10), + updated_at: toDateTimeString(-1), + inbound_time: toDateTimeString(-3), + production_date: productionDate, + expiry_date: expiryDate, + stock: { + id: 88, + item_code: 'SKU-88', + item_name: '测试商品', + sku_property: '默认规格', + stock_unit: '件', + is_batch_mgmt: 'Y', + is_shelf_life_mgmt: 'Y', + remaining_threshold_days: 5, + store_stock: { + store_id: 100001, + store_remask: '测试货主名称', + }, + }, + space: { + id: 9, + space_code: 'A-01', + custom_name: '一号位', + }, + }], + stockBarcodes: [ + { stock_id: 88, barcode: 'BC-88-A' }, + { stock_id: 88, barcode: 'BC-88-B' }, + ], + fileReferences: [ + { + business_id: 88, + file_id: 70088, + file: { + file_url: 'https://example.com/stock-88-a.jpg', + }, + }, + { + business_id: 88, + file_id: 70089, + file: { + file_url: 'https://example.com/stock-88-b.jpg', + }, + }, + ], + }); + const service = new StorageInventoryService(harness.ctx); + + const result = await service.getInventoryList( + { page: 1, pageSize: 10 }, + { sortField: 'created_at', sortOrder: 'DESC' }, + true + ); + + assert.equal(result.list.length, 1); + assert.equal(result.pagination.page, 1); + assert.equal(result.pagination.pageSize, 10); + assert.equal(result.pagination.total, 1); + assert.equal(Object.prototype.hasOwnProperty.call(result.list[0], 'production_date'), true); + assert.equal(Object.prototype.hasOwnProperty.call(result.list[0], 'expiry_date'), true); + assert.equal(Object.prototype.hasOwnProperty.call(result.list[0], 'is_shelf_life_warning_triggered'), true); + assert.equal(Object.prototype.hasOwnProperty.call(result.list[0].stock, 'is_batch_mgmt_enabled'), true); + assert.equal(Object.prototype.hasOwnProperty.call(result.list[0].stock, 'is_batch_mgmt'), false); + assert.equal(result.list[0].production_date, expectedProductionDate); + assert.equal(result.list[0].expiry_date, expectedExpiryDate); + assert.equal(result.list[0].is_shelf_life_warning_triggered, true); + assert.equal(result.list[0].stock.is_batch_mgmt_enabled, true); + assert.equal(result.list[0].stock.store_name, '测试货主名称'); + assert.equal(Object.prototype.hasOwnProperty.call(result.list[0].stock, 'store_stock'), false); + assert.deepEqual(result.list[0].stock.barcodes, [ 'BC-88-A', 'BC-88-B' ]); + assert.deepEqual(result.list[0].stock.images, [ + 'https://example.com/stock-88-a.jpg', + 'https://example.com/stock-88-b.jpg', + ]); + assert.ok(harness.calls.findAndCountAllArgs); + assert.ok(harness.calls.findAndCountAllArgs.include[0].attributes.includes('is_shelf_life_mgmt')); + assert.ok(harness.calls.findAndCountAllArgs.include[0].attributes.includes('is_batch_mgmt')); + assert.ok(harness.calls.findAndCountAllArgs.include[0].attributes.includes('remaining_threshold_days')); + assert.ok(Array.isArray(harness.calls.findAndCountAllArgs.include[0].include)); + assert.equal(harness.calls.findAndCountAllArgs.include[0].include[0].as, 'store_stock'); + assert.deepEqual(harness.calls.findAndCountAllArgs.include[0].include[0].attributes, [ 'store_id', 'store_remask' ]); + assert.equal(harness.calls.stockBarcodeArgs.length, 1); + assert.equal(harness.calls.fileReferenceArgs.length, 1); + }); + + it('should return warning flag false when shelf-life management is disabled', async () => { + const productionDate = toDateTimeString(-4); + const expiryDate = toDateTimeString(2); + const expectedProductionDate = productionDate.slice(0, 10); + const expectedExpiryDate = expiryDate.slice(0, 10); + const harness = createServiceHarness({ + batchRows: [{ + id: 2, + stock_id: 89, + space_id: 10, + inventory_type: 'ZP', + warehouse_id: 100000, + store_id: 100001, + quantity: 8, + locked_quantity: 0, + available_quantity: 8, + created_at: toDateTimeString(-8), + updated_at: toDateTimeString(-2), + inbound_time: toDateTimeString(-2), + production_date: productionDate, + expiry_date: expiryDate, + stock: { + id: 89, + item_code: 'SKU-89', + item_name: '未启用保质期管理商品', + sku_property: '默认规格', + stock_unit: '箱', + is_batch_mgmt: 'N', + is_shelf_life_mgmt: 'N', + remaining_threshold_days: 5, + }, + space: { + id: 10, + space_code: 'B-01', + custom_name: '二号位', + }, + }], + stockBarcodes: [], + fileReferences: [], + }); + const service = new StorageInventoryService(harness.ctx); + + const result = await service.getInventoryList({}, {}, true); + + assert.equal(result.list.length, 1); + assert.equal(result.list[0].is_shelf_life_warning_triggered, false); + assert.equal(result.list[0].stock.is_batch_mgmt_enabled, false); + assert.equal(result.list[0].stock.store_name, null); + assert.equal(Object.prototype.hasOwnProperty.call(result.list[0].stock, 'is_batch_mgmt'), false); + assert.equal(result.list[0].production_date, expectedProductionDate); + assert.equal(result.list[0].expiry_date, expectedExpiryDate); + assert.deepEqual(result.list[0].stock.barcodes, []); + assert.deepEqual(result.list[0].stock.images, []); + }); + + it('should return merged list with earliest production and expiry dates', async () => { + const productionDate = toDateTimeString(-9); + const expiryDate = toDateTimeString(3); + const harness = createServiceHarness({ + mergedTotal: 1, + mergedRows: [{ + stock_id: 90, + space_id: 11, + inventory_type: 'ZP', + warehouse_id: 100000, + store_id: 100001, + quantity: 20, + locked_quantity: 3, + available_quantity: 17, + production_date: productionDate, + expiry_date: expiryDate, + first_inbound_time: toDateTimeString(-7), + last_inbound_time: toDateTimeString(-1), + batch_count: 2, + stock: { + id: 90, + item_code: 'SKU-90', + item_name: '合并库存商品', + sku_property: '默认规格', + stock_unit: '件', + is_batch_mgmt: 'Y', + is_shelf_life_mgmt: 'Y', + remaining_threshold_days: 5, + store_stock: { + store_id: 100002, + store_remask: '合并货主名称', + }, + }, + space: { + id: 11, + space_code: 'C-01', + custom_name: '三号位', + }, + }], + stockBarcodes: [ + { stock_id: 90, barcode: 'BC-90-A' }, + ], + fileReferences: [ + { + business_id: 90, + file_id: 70090, + file: { + file_url: 'https://example.com/stock-90-a.jpg', + }, + }, + ], + }); + const service = new StorageInventoryService(harness.ctx); + + const result = await service.getInventoryList( + { page: 2, pageSize: 5 }, + { sortField: 'last_inbound_time', sortOrder: 'ASC' }, + false + ); + + assert.equal(result.list.length, 1); + assert.equal(result.pagination.page, 2); + assert.equal(result.pagination.pageSize, 5); + assert.equal(result.pagination.total, 1); + assert.equal(Object.prototype.hasOwnProperty.call(result.list[0], 'production_date'), true); + assert.equal(Object.prototype.hasOwnProperty.call(result.list[0], 'expiry_date'), true); + assert.equal(Object.prototype.hasOwnProperty.call(result.list[0], 'is_shelf_life_warning_triggered'), true); + assert.equal(Object.prototype.hasOwnProperty.call(result.list[0].stock, 'is_batch_mgmt_enabled'), true); + assert.equal(Object.prototype.hasOwnProperty.call(result.list[0].stock, 'is_batch_mgmt'), false); + assert.equal(result.list[0].production_date, productionDate.slice(0, 10)); + assert.equal(result.list[0].expiry_date, expiryDate.slice(0, 10)); + assert.equal(result.list[0].is_shelf_life_warning_triggered, true); + assert.equal(result.list[0].stock.is_batch_mgmt_enabled, true); + assert.equal(result.list[0].stock.store_name, '合并货主名称'); + assert.equal(Object.prototype.hasOwnProperty.call(result.list[0].stock, 'store_stock'), false); + assert.deepEqual(result.list[0].stock.barcodes, [ 'BC-90-A' ]); + assert.deepEqual(result.list[0].stock.images, [ 'https://example.com/stock-90-a.jpg' ]); + assert.ok(harness.calls.findAllArgs); + assert.ok(harness.calls.findAllArgs.attributes.some(item => Array.isArray(item) && item[1] === 'production_date' && item[0].fn === 'MIN')); + assert.ok(harness.calls.findAllArgs.attributes.some(item => Array.isArray(item) && item[1] === 'expiry_date' && item[0].fn === 'MIN')); + assert.ok(harness.calls.findAllArgs.include[0].attributes.includes('is_batch_mgmt')); + assert.ok(Array.isArray(harness.calls.findAllArgs.include[0].include)); + assert.equal(harness.calls.findAllArgs.include[0].include[0].as, 'store_stock'); + assert.deepEqual(harness.calls.findAllArgs.include[0].include[0].attributes, [ 'store_id', 'store_remask' ]); + assert.equal(harness.calls.stockBarcodeArgs.length, 1); + assert.equal(harness.calls.fileReferenceArgs.length, 1); + }); +}); diff --git a/test/app/service/systems/storage.receiving.detailChange.test.js b/test/app/service/systems/storage.receiving.detailChange.test.js new file mode 100644 index 0000000..1f89bdf --- /dev/null +++ b/test/app/service/systems/storage.receiving.detailChange.test.js @@ -0,0 +1,148 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const ReceivingService = require('../../../../app/service/systems/storage/receiving'); + +function formatDate(date, formatStr = 'YYYY-MM-DD HH:mm:ss') { + const targetDate = date instanceof Date ? date : new Date(date); + const year = targetDate.getFullYear(); + const month = String(targetDate.getMonth() + 1).padStart(2, '0'); + const day = String(targetDate.getDate()).padStart(2, '0'); + const hours = String(targetDate.getHours()).padStart(2, '0'); + const minutes = String(targetDate.getMinutes()).padStart(2, '0'); + const seconds = String(targetDate.getSeconds()).padStart(2, '0'); + + return formatStr + .replace('YYYY', year) + .replace('MM', month) + .replace('DD', day) + .replace('HH', hours) + .replace('mm', minutes) + .replace('ss', seconds); +} + +function createServiceHarness() { + const calls = { + detailUpdate: 0, + updateReceivingStats: 0, + }; + + const model = { + ReceivingDetail: { + async findOne() { + return { + id: 501, + receiving_id: 123, + product_name: '测试商品', + actual_quantity: 1, + barcode: '', + system_product_id: null, + updated_at: new Date('2026-04-01T00:00:00Z'), + }; + }, + async update() { + calls.detailUpdate += 1; + }, + }, + Receiving: { + async findOne() { + return { + id: 123, + warehouse_id: 100000, + store_id: 1000000, + store_name: '测试货主', + status: 'receiving', + }; + }, + }, + StockWarehouse: { + async findOne() { + throw new Error('should not be called'); + }, + }, + LocationSpace: { + async findOne() { + throw new Error('should not be called'); + }, + }, + StoreWarehouse: { + buildStoreStockInclude() { + return {}; + }, + }, + }; + + const ctx = { + user: { + store_id: 100000, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + service: { + systems: { + operationLog: { + async createOperationLog() { + calls.operationLog = (calls.operationLog || 0) + 1; + }, + }, + }, + }, + model, + app: { + model, + Sequelize: { + Op: { + or: 'or', + }, + }, + formatDate, + }, + }; + + const service = new ReceivingService(ctx); + return { + service, + calls, + }; +} + +describe('test/app/service/systems/storage.receiving.detailChange.test.js', () => { + it('should reject expired expiry_date before updating receiving detail', async () => { + const { service, calls } = createServiceHarness(); + + const result = await service.detailChange({ + id: 501, + receiving_id: 123, + actual_quantity: 1, + expiry_date: '2000-01-01', + }); + + assert.equal(result.code, 400); + assert.equal(result.message, '到期日期已过期,不能录入收货'); + assert.equal(calls.detailUpdate, 0); + assert.equal(calls.operationLog || 0, 0); + }); + + it('should allow same-day expiry_date when provided as Date input', async () => { + const { service, calls } = createServiceHarness(); + service.updateReceivingStats = async () => { + calls.updateReceivingStats += 1; + }; + + const result = await service.detailChange({ + id: 501, + receiving_id: 123, + actual_quantity: 1, + expiry_date: new Date(), + }); + + assert.equal(result.code, 200); + assert.equal(result.message, '修改成功'); + assert.equal(calls.detailUpdate, 1); + assert.equal(calls.updateReceivingStats, 1); + assert.equal(calls.operationLog, 1); + }); +}); diff --git a/test/app/service/systems/storage.receiving.report.test.js b/test/app/service/systems/storage.receiving.report.test.js index 5775d92..a469705 100644 --- a/test/app/service/systems/storage.receiving.report.test.js +++ b/test/app/service/systems/storage.receiving.report.test.js @@ -2,6 +2,11 @@ const assert = require('node:assert/strict'); const ReceivingService = require('../../../../app/service/systems/storage/receiving'); +const DAY_MS = 24 * 60 * 60 * 1000; + +function daysFromNow(days) { + return new Date(Date.now() + (days * DAY_MS)); +} function createService() { const excelCalls = []; @@ -65,6 +70,8 @@ function createService() { function createCompleteReceivingService({ uploadShouldFail = false, detailOverrides = {}, + systemProductOverrides = {}, + hydrateSystemProductFromQuery = false, itemImages, } = {}) { const steps = []; @@ -91,6 +98,19 @@ function createCompleteReceivingService({ barcode: 'SKU-001', actual_quantity: 8, weight: 12, + production_date: null, + expiry_date: null, + system_product: { + id: 10001, + item_name: '测试商品A', + item_code: 'SKU-001', + inbound_min_days: 0, + shelf_life_days: 0, + remaining_threshold_days: 0, + is_shelf_life_mgmt: 'N', + is_batch_mgmt: 'N', + ...systemProductOverrides, + }, ...detailOverrides, }; @@ -127,7 +147,29 @@ function createCompleteReceivingService({ return transaction; }, Receiving: { - async findOne() { + async findOne(options = {}) { + const includeSystemProduct = hydrateSystemProductFromQuery + && Array.isArray(options.include) + && options.include.some(includeItem => Array.isArray(includeItem && includeItem.include) + && includeItem.include.some(childInclude => childInclude && childInclude.as === 'system_product')); + + const receivingDetail = includeSystemProduct && !detailRecord.system_product + ? { + ...detailRecord, + system_product: { + id: 10001, + item_name: '测试商品A', + item_code: 'SKU-001', + inbound_min_days: 0, + shelf_life_days: 0, + remaining_threshold_days: 0, + is_shelf_life_mgmt: 'N', + is_batch_mgmt: 'N', + ...systemProductOverrides, + }, + } + : detailRecord; + return { id: 123, warehouse_id: 100000, @@ -136,7 +178,7 @@ function createCompleteReceivingService({ receiving_number: 'RCV202604040001', status: 'receiving', remark: '', - details: [ detailRecord ], + details: [ receivingDetail ], }; }, async update() { @@ -168,8 +210,8 @@ function createCompleteReceivingService({ throw new Error('upload failed'); } return { - fileKey: '收货完成_RCV202604040001.xlsx', - url: 'https://cdn.example.com/收货完成_RCV202604040001.xlsx', + fileKey: '收货明细(已完成收货)_RCV202604040001.xlsx', + url: 'https://cdn.example.com/收货明细(已完成收货)_RCV202604040001.xlsx', }; }; @@ -257,7 +299,7 @@ describe('test/app/service/systems/storage.receiving.report.test.js', () => { assert.equal(excelCalls.length, 1); const [ options ] = excelCalls; - assert.equal(options.filename, '收货完成_RCV202604040001.xlsx'); + assert.equal(options.filename, '收货明细(已完成收货)_RCV202604040001.xlsx'); assert.ok(String(options.dir || '').includes('receiving/completed')); assert.equal(options.expireDays, 90); assert.ok(Array.isArray(options.sheets)); @@ -291,7 +333,7 @@ describe('test/app/service/systems/storage.receiving.report.test.js', () => { assert.ok(sheet.styledRows.some(item => item && item.style && item.style.font && item.style.font.bold), '应包含表头加粗样式'); assert.ok(Array.isArray(sheet.embeddedImages)); assert.equal(sheet.embeddedImages.length, 3); - assert.equal(result.url, 'https://cdn.example.com/收货完成_RCV202604040001.xlsx'); + assert.equal(result.url, 'https://cdn.example.com/收货明细(已完成收货)_RCV202604040001.xlsx'); }); it('should send receiving completed notice with the unified event payload', async () => { @@ -315,8 +357,8 @@ describe('test/app/service/systems/storage.receiving.report.test.js', () => { total_quantity: 8, }, completionReport: { - fileKey: '收货完成_RCV202604040001.xlsx', - url: 'https://cdn.example.com/收货完成_RCV202604040001.xlsx', + fileKey: '收货明细(已完成收货)_RCV202604040001.xlsx', + url: 'https://cdn.example.com/收货明细(已完成收货)_RCV202604040001.xlsx', }, }); @@ -327,7 +369,7 @@ describe('test/app/service/systems/storage.receiving.report.test.js', () => { assert.equal(options.businessName, 'receiving'); assert.equal(options.event, 'receiving_completed'); assert.equal(options.messageType, 'file'); - assert.equal(options.url, 'https://cdn.example.com/收货完成_RCV202604040001.xlsx'); + assert.equal(options.url, 'https://cdn.example.com/收货明细(已完成收货)_RCV202604040001.xlsx'); assert.equal(options.subject.id, 100000); assert.equal(options.subject.name, '测试仓库'); assert.match(String(options.content || ''), /收货单号:RCV202604040001 已完成/); @@ -539,7 +581,7 @@ describe('test/app/service/systems/storage.receiving.report.test.js', () => { assert.equal(noticeCalls.length, 2); assert.equal(noticeCalls[0].completionReport ?? null, null); assert.equal(Number(noticeCalls[0].receiving.store_id), 1000000); - assert.equal(noticeCalls[1].completionReport.url, 'https://cdn.example.com/收货完成_RCV202604040001.xlsx'); + assert.equal(noticeCalls[1].completionReport.url, 'https://cdn.example.com/收货明细(已完成收货)_RCV202604040001.xlsx'); }); it('should only send text notice when completion excel generation fails', async () => { @@ -557,15 +599,122 @@ describe('test/app/service/systems/storage.receiving.report.test.js', () => { assert.equal(Number(noticeCalls[0].receiving.store_id), 1000000); }); - it('should still complete and notify when detail has no matched product or completeness fields', async () => { + it('should reject completion when batch-managed product misses batch number', async () => { const { service, steps, noticeCalls } = createCompleteReceivingService({ detailOverrides: { - system_product_id: null, - barcode: '', - weight: 0, - actual_quantity: 1, + system_product: null, + batch_number: ' ', + production_date: daysFromNow(-10), + expiry_date: daysFromNow(30), + }, + systemProductOverrides: { + is_shelf_life_mgmt: 'Y', + is_batch_mgmt: 'Y', + inbound_min_days: 3, + }, + hydrateSystemProductFromQuery: true, + }); + + const result = await service.completeReceiving({ id: 123 }); + + assert.equal(result.success, false); + assert.equal(result.code, 'BATCH_NUMBER_REQUIRED'); + assert.match(result.message, /批次号/); + assert.ok(Array.isArray(result.data.invalid_details)); + assert.equal(result.data.invalid_details[0].detail_id, 501); + assert.deepEqual(steps, [ 'rollback' ]); + assert.equal(noticeCalls.length, 0); + }); + + it('should reject completion when batch-managed product misses production date or expiry date', async () => { + const { service, steps, noticeCalls } = createCompleteReceivingService({ + detailOverrides: { + batch_number: 'BATCH-20260414-001', + production_date: null, + expiry_date: null, + }, + systemProductOverrides: { + is_shelf_life_mgmt: 'Y', + is_batch_mgmt: 'Y', + }, + }); + + const result = await service.completeReceiving({ id: 123 }); + + assert.equal(result.success, false); + assert.equal(result.code, 'PRODUCTION_DATE_REQUIRED'); + assert.match(result.message, /生产日期/); + assert.match(result.message, /有效期/); + assert.ok(Array.isArray(result.data.invalid_details)); + assert.equal(result.data.invalid_details[0].detail_id, 501); + assert.deepEqual(steps, [ 'rollback' ]); + assert.equal(noticeCalls.length, 0); + }); + + it('should load batch-managed product data from query include before validating completion', async () => { + const { service, steps, noticeCalls } = createCompleteReceivingService({ + detailOverrides: { + system_product: null, + batch_number: 'BATCH-20260414-002', + production_date: null, + expiry_date: null, + }, + systemProductOverrides: { + is_shelf_life_mgmt: 'Y', + is_batch_mgmt: 'Y', + inbound_min_days: 3, + }, + hydrateSystemProductFromQuery: true, + }); + + const result = await service.completeReceiving({ id: 123 }); + + assert.equal(result.success, false); + assert.equal(result.code, 'PRODUCTION_DATE_REQUIRED'); + assert.match(result.message, /生产日期/); + assert.deepEqual(steps, [ 'rollback' ]); + assert.equal(noticeCalls.length, 0); + }); + + it('should reject completion when batch-managed product expires too soon for the minimum receiving days', async () => { + const { service, steps, noticeCalls } = createCompleteReceivingService({ + detailOverrides: { + batch_number: 'BATCH-20260414-003', + production_date: daysFromNow(-10), + expiry_date: daysFromNow(2), + }, + systemProductOverrides: { + is_shelf_life_mgmt: 'Y', + is_batch_mgmt: 'Y', + inbound_min_days: 3, + }, + }); + + const result = await service.completeReceiving({ id: 123 }); + + assert.equal(result.success, false); + assert.equal(result.code, 'EXPIRY_DATE_TOO_SOON'); + assert.match(result.message, /最小允许收货天数/); + assert.match(result.message, /无法完成收货/); + assert.ok(Array.isArray(result.data.invalid_details)); + assert.equal(result.data.invalid_details[0].detail_id, 501); + assert.equal(result.data.invalid_details[0].inbound_min_days, 3); + assert.deepEqual(steps, [ 'rollback' ]); + assert.equal(noticeCalls.length, 0); + }); + + it('should allow completion when batch-managed product has valid production and expiry dates', async () => { + const { service, steps, noticeCalls } = createCompleteReceivingService({ + detailOverrides: { + batch_number: 'BATCH-20260414-004', + production_date: daysFromNow(-10), + expiry_date: daysFromNow(30), + }, + systemProductOverrides: { + is_shelf_life_mgmt: 'Y', + is_batch_mgmt: 'Y', + inbound_min_days: 3, }, - itemImages: [], }); const result = await service.completeReceiving({ id: 123 }); @@ -575,7 +724,7 @@ describe('test/app/service/systems/storage.receiving.report.test.js', () => { assert.equal(result.success, true); assert.deepEqual(steps, [ 'commit', 'notice:text', 'excel', 'notice:file' ]); assert.equal(noticeCalls.length, 2); - assert.equal(Number(result.data.stats.matched_details), 0); - assert.equal(Number(result.data.stats.unmatched_details), 1); + assert.equal(Number(result.data.stats.matched_details), 1); + assert.equal(Number(result.data.stats.unmatched_details), 0); }); }); diff --git a/test/support/order_service_test_helper.js b/test/support/order_service_test_helper.js new file mode 100644 index 0000000..b8e09ea --- /dev/null +++ b/test/support/order_service_test_helper.js @@ -0,0 +1,151 @@ +'use strict'; + +const Sequelize = require('sequelize'); + +function createServiceContext(storeId = 100000) { + return { + app: { + Sequelize, + config: {}, + }, + user: { + store_id: storeId, + }, + }; +} + +function buildRows(count, rowFactory = () => ({})) { + return Array.from({ length: count }, (_, index) => ({ + id: index + 1, + warehouse_id: 100000, + step: index % 2 === 0 ? 1 : 2, + dispatch_lane: 'm4', + inspection_status: 'fin', + updated_at: '2026-04-12 00:00:00', + ...rowFactory(index), + })); +} + +/** + * 判断模拟行数据是否匹配 where 条件。 + * @param {Object|Array|number|string|null} row 待匹配数据。 + * @param {Object} where Sequelize where 条件。 + * @return {boolean} 是否匹配。 + */ +function matchesWhere(row, where) { + if (!where || typeof where !== 'object') { + return true; + } + + const andConditions = where[Sequelize.Op.and]; + if (Array.isArray(andConditions)) { + return andConditions.every(condition => matchesWhere(row, condition)); + } + + const orConditions = where[Sequelize.Op.or]; + if (Array.isArray(orConditions)) { + return orConditions.some(condition => matchesWhere(row, condition)); + } + + return Object.entries(where).every(([ fieldName, condition ]) => { + if (condition && typeof condition === 'object' && !Array.isArray(condition)) { + if (Object.prototype.hasOwnProperty.call(condition, Sequelize.Op.eq)) { + return row[fieldName] === condition[Sequelize.Op.eq]; + } + + if (Object.prototype.hasOwnProperty.call(condition, Sequelize.Op.ne)) { + return row[fieldName] !== condition[Sequelize.Op.ne]; + } + + if (Object.prototype.hasOwnProperty.call(condition, Sequelize.Op.in)) { + const values = condition[Sequelize.Op.in]; + return Array.isArray(values) && values.includes(row[fieldName]); + } + + if (Object.prototype.hasOwnProperty.call(condition, Sequelize.Op.notIn)) { + const values = condition[Sequelize.Op.notIn]; + return Array.isArray(values) && !values.includes(row[fieldName]); + } + + if (Object.keys(condition).length > 0 || Object.getOwnPropertySymbols(condition).length > 0) { + return matchesWhere(row[fieldName], condition); + } + } + + return row[fieldName] === condition; + }); +} + +/** + * 创建分页查询用的模拟模型。 + * @param {Array} rows 初始行数据。 + * @param {Object} capture 调用记录。 + * @return {Object} 模拟模型。 + */ +function createPagedMockModel(rows, capture = {}) { + const normalizedRows = Array.isArray(rows) ? rows.map(row => ({ ...row })) : []; + + return { + async count({ where } = {}) { + capture.countWhere = where; + return normalizedRows.filter(row => matchesWhere(row, where)).length; + }, + async findAll(options = {}) { + capture.findOptions = options; + + const filteredRows = normalizedRows.filter(row => matchesWhere(row, options.where)); + const offset = Number.parseInt(options.offset, 10) || 0; + const limitValue = options.limit === undefined ? filteredRows.length : Number.parseInt(options.limit, 10); + const limit = Number.isFinite(limitValue) ? Math.max(limitValue, 0) : filteredRows.length; + + return filteredRows.slice(offset, offset + limit).map(row => ({ ...row })); + }, + async update() { + return [ 1 ]; + }, + async findOne() { + const firstRow = normalizedRows[0]; + return firstRow ? { ...firstRow } : null; + }, + }; +} + +/** + * 创建订单服务测试环境。 + * @param {Function} ServiceClass 服务类构造器。 + * @param {Object} [options] 测试配置。 + * @return {{ ctx: Object, service: Object, captures: Array }} 测试上下文。 + */ +function createOrderHarness(ServiceClass, options = {}) { + const ctx = createServiceContext(options.storeId || 100000); + const service = new ServiceClass(ctx); + const captures = []; + const rowsByModule = options.rowsByModule || {}; + const defaultRows = Array.isArray(options.defaultRows) ? options.defaultRows : buildRows(1); + + service.getOrderModel = async moduleName => { + const capture = { + moduleName, + }; + captures.push(capture); + + const rows = Object.prototype.hasOwnProperty.call(rowsByModule, moduleName) + ? rowsByModule[moduleName] + : defaultRows; + + return createPagedMockModel(rows, capture); + }; + + return { + ctx, + service, + captures, + }; +} + +module.exports = { + buildRows, + createOrderHarness, + createServiceContext, + matchesWhere, +}; diff --git a/test/support/system_method_client.js b/test/support/system_method_client.js index 62a7bd1..44d94a7 100644 --- a/test/support/system_method_client.js +++ b/test/support/system_method_client.js @@ -1,8 +1,12 @@ 'use strict'; +const crypto = require('node:crypto'); const fs = require('node:fs'); const path = require('node:path'); const assert = require('node:assert/strict'); +const { XMLParser } = require('fast-xml-parser'); + +const loadDefaultConfig = require('../../config/config.default'); const BASE_URL = process.env.SYSTEM_TEST_BASE_URL || 'http://127.0.0.1:6060'; const BASE_GATEWAY_URL = process.env.SYSTEM_TEST_GATEWAY_BASE_URL || BASE_URL; @@ -11,10 +15,101 @@ const TOKEN_FILE = process.env.SYSTEM_TEST_TOKEN_FILE const USERNAME = process.env.SYSTEM_TEST_USERNAME || 'liufumingren'; const PASSWORD = process.env.SYSTEM_TEST_PASSWORD || '111111'; +const DEFAULT_APP_INFO = { + name: 'wms', + baseDir: process.cwd(), +}; + +let cachedQimenDefaults = null; + +function loadQimenDefaults() { + if (cachedQimenDefaults) { + return cachedQimenDefaults; + } + + try { + const defaultConfig = loadDefaultConfig(DEFAULT_APP_INFO) || {}; + cachedQimenDefaults = { + appKey: process.env.SYSTEM_TEST_QIMEN_APP_KEY || defaultConfig.qimen?.appKey || '', + secret: process.env.SYSTEM_TEST_QIMEN_SECRET || defaultConfig.qimen?.security || '', + }; + } catch { + cachedQimenDefaults = { + appKey: process.env.SYSTEM_TEST_QIMEN_APP_KEY || '', + secret: process.env.SYSTEM_TEST_QIMEN_SECRET || '', + }; + } + + return cachedQimenDefaults; +} + function nowSec() { return Math.floor(Date.now() / 1000); } +function normalizeString(value) { + return value === null || value === undefined ? '' : String(value); +} + +function buildTopSign(params, body, secret, signMethod = 'md5') { + const keys = Object.keys(params).sort(); + let query = ''; + const normalizedSignMethod = String(signMethod || '').toLowerCase(); + + if (normalizedSignMethod === 'md5') { + query += normalizeString(secret); + } + + for (const key of keys) { + const value = params[key]; + if (key && value) { + query += key + value; + } + } + + if (body) { + query += body; + } + + if (normalizedSignMethod === 'hmac') { + return crypto.createHmac('md5', normalizeString(secret)) + .update(query, 'utf8') + .digest('hex') + .toUpperCase(); + } + + if (normalizedSignMethod === 'hmac_sha256') { + return crypto.createHmac('sha256', normalizeString(secret)) + .update(query, 'utf8') + .digest('hex') + .toUpperCase(); + } + + query += normalizeString(secret); + return crypto.createHash('md5') + .update(query, 'utf8') + .digest('hex') + .toUpperCase(); +} + +function parseXmlBody(xmlText) { + try { + const parser = new XMLParser({ + ignoreAttributes: false, + attributeNamePrefix: '@_', + allowBooleanAttributes: true, + parseTagValue: false, + parseAttributeValue: false, + trimValues: false, + ignoreDeclaration: true, + }); + + return parser.parse(xmlText); + } catch { + return null; + } +} + function decodeJwtPayload(token) { try { const payloadSegment = token.split('.')[1]; @@ -97,6 +192,74 @@ async function invokeSystemMethod(method, body = {}, token, extra = {}) { }; } +/** + * 发送真实的 /qimen 请求,并返回原始响应文本。 + * @param {string} method 奇门方法名,例如 deliveryorder.create。 + * @param {string} xmlBody 原始 XML 请求体。 + * @param {Object} [options={}] 请求选项。 + * @param {string} [options.appKey] 请求 app_key;未传时读取 config.default.js 或环境变量覆盖值。 + * @param {string} [options.secret] 签名密钥;未传时读取 config.default.js 或环境变量覆盖值。 + * @param {string} [options.customerId] 客户编码。 + * @param {string} [options.timestamp] 时间戳;未传时使用当前秒级时间戳。 + * @param {string} [options.v='2.0'] 版本号。 + * @param {string} [options.format='xml'] 响应格式。 + * @param {string} [options.signMethod='md5'] 签名方式。 + * @param {string} [options.contentType='application/xml'] 请求 Content-Type。 + * @param {Object} [options.headers={}] 额外请求头。 + * @return {Promise<{status: number, body: string, parsed: Object|null, url: string, queryParams: Object}>} 请求结果。 + */ +async function invokeQimenMethod(method, xmlBody, options = {}) { + const qimenDefaults = loadQimenDefaults(); + const timestamp = options.timestamp || String(nowSec()); + const appKey = normalizeString(options.appKey || qimenDefaults.appKey); + const secret = normalizeString(options.secret || qimenDefaults.secret); + const customerId = normalizeString(options.customerId || ''); + const format = normalizeString(options.format || 'xml') || 'xml'; + const signMethod = normalizeString(options.signMethod || 'md5') || 'md5'; + const version = normalizeString(options.v || '2.0') || '2.0'; + const bodyText = normalizeString(xmlBody); + const queryParams = { + app_key: appKey, + method: normalizeString(method), + v: version, + format, + sign_method: signMethod, + timestamp, + }; + + if (customerId) { + queryParams.customerId = customerId; + } + + queryParams.sign = buildTopSign(queryParams, bodyText, secret, signMethod); + + const url = new URL(`${BASE_URL}/qimen`); + for (const [ key, value ] of Object.entries(queryParams)) { + if (value !== undefined && value !== null && value !== '') { + url.searchParams.set(key, value); + } + } + + const response = await fetch(url, { + method: 'POST', + headers: { + 'Content-Type': options.contentType || 'application/xml', + ...(options.headers || {}), + }, + body: bodyText, + }); + + const text = await response.text(); + + return { + status: response.status, + body: text, + parsed: format.toLowerCase() === 'xml' ? parseXmlBody(text) : null, + url: url.toString(), + queryParams, + }; +} + async function getAuthToken(options = {}) { const { forceLogin = false } = options; @@ -160,6 +323,7 @@ module.exports = { TOKEN_FILE, USERNAME, invokeSystemMethod, + invokeQimenMethod, invokeGatewayMethod, getAuthToken, readCachedToken, diff --git a/test_reports/fail/20260412-1723-真实下单出库脚本验证报告.md b/test_reports/fail/20260412-1723-真实下单出库脚本验证报告.md new file mode 100644 index 0000000..7766184 --- /dev/null +++ b/test_reports/fail/20260412-1723-真实下单出库脚本验证报告.md @@ -0,0 +1,44 @@ +# 真实下单出库脚本验证报告 + +- 测试类型:接口验证,真实链路执行 +- 测试目标: + - 真实创建一笔订单 + - 通过内部出库服务完成 markOutboundOrder + - 确认脚本会把结果写到 temp 下的 JSON 文件,并打印同样内容 + - 回传执行结果,检查 createdOrderId、deliveryOrderCode、outboundResult、deliveryTime 是否有值,以及脚本是否退出码为 0 + +## 测试范围 + +- 执行脚本:[temp/trace-real-order-outbound.cjs](temp/trace-real-order-outbound.cjs) +- 结果文件:[temp/trace-real-order-outbound.json](temp/trace-real-order-outbound.json) +- 关联实现:[test/support/system_method_client.js](test/support/system_method_client.js) +- 关联服务:[app/service/systems/order_outbound.js](app/service/systems/order_outbound.js) + +## 测试产物 + +- 终端执行输出:脚本已实际运行并打印结果 JSON +- 结果 JSON 文件:已生成 [temp/trace-real-order-outbound.json](temp/trace-real-order-outbound.json) + +## 结果摘要 + +- createdOrderId:无值,结果为 0 +- deliveryOrderCode:有值,结果为 TRACE_OUTBOUND_1775985802028_F5254BAE +- outboundResult:无值,结果为 null +- deliveryTime:无值,结果为 null +- 脚本退出码:不是 0 + +## 关键失败点 + +- 脚本在执行到创建奇门订单前抛出断言错误,错误信息为:未找到可用库存用于创建奇门订单 +- 结果 JSON 中已经写入相同内容,说明脚本确实完成了结果落盘和控制台打印,但没有完成后续真实下单与 markOutboundOrder + +## 执行结论 + +- 本次执行失败,未完成完整的真实订单创建与内部出库链路 +- 最可能的根因是当前测试环境没有满足脚本所需的可用库存,导致在创建奇门订单阶段提前中断 + +## 建议 + +1. 先补齐脚本所需的可用库存,再重新执行同一脚本 +2. 如果库存是预期前置条件,建议在脚本开头增加更明确的前置检查和失败提示 +3. 如需继续定位,可重点检查脚本中创建奇门订单前的库存筛选逻辑,以及相关仓库和货主的可用库存状态 \ No newline at end of file diff --git a/test_reports/fail/20260414-库存效期任务实例形态回归测试报告.md b/test_reports/fail/20260414-库存效期任务实例形态回归测试报告.md new file mode 100644 index 0000000..7559c11 --- /dev/null +++ b/test_reports/fail/20260414-库存效期任务实例形态回归测试报告.md @@ -0,0 +1,38 @@ +# 库存效期任务实例形态回归测试报告 + +- 测试类型:单元测试 +- 测试目标:为 [app/schedule/notice_stock_remaining.js](../../app/schedule/notice_stock_remaining.js) 补充回归测试,验证 Storage.findAll 返回 Sequelize 实例风格对象时,任务仍能识别 stock_id / id / expiry_date / space 并发送通知、回写缓存。 + +## 测试范围 + +- [test/app/schedule/notice_stock_remaining.test.js](../../test/app/schedule/notice_stock_remaining.test.js) +- [app/schedule/notice_stock_remaining.js](../../app/schedule/notice_stock_remaining.js) + +## 测试产物 + +- 新增测试用例:普通对象路径 + Sequelize 实例形态路径 +- 测试命令:`npm run test:local -- test/app/schedule/notice_stock_remaining.test.js` + +## 测试结果摘要 + +- 普通对象用例:通过 +- 实例形态用例:失败 +- 失败数:1 +- 通过数:1 + +## 失败用例 + +- 用例名:`should read Sequelize instance-style rows via getDataValue/get and still send notice` +- 失败位置:[test/app/schedule/notice_stock_remaining.test.js](../../test/app/schedule/notice_stock_remaining.test.js#L254) +- 断言:`assert.equal(noticePayloads.length, 1)` +- 实际值:`noticePayloads.length === 0` + +## 失败原因 + +当前任务实现仍只通过自有属性读取字段。实例形态对象虽然提供了 `getDataValue/get`,但任务代码没有调用这些方法,因此 `stock_id/id/expiry_date/space` 没有被识别,通知未发送,缓存也未回写。 + +## 结论与建议 + +- 本次测试补强已覆盖普通对象路径,并新增了实例形态回归用例。 +- 由于业务代码未调整,实例形态用例仍然失败,当前问题未被修复。 +- 若要让该回归测试通过,需要在任务实现中补充对 Sequelize 实例的读取兼容,但本次按要求未修改业务代码。 diff --git a/test_reports/fail/20260417-172716-收货入库回归测试报告.md b/test_reports/fail/20260417-172716-收货入库回归测试报告.md new file mode 100644 index 0000000..bfc6149 --- /dev/null +++ b/test_reports/fail/20260417-172716-收货入库回归测试报告.md @@ -0,0 +1,72 @@ +# 收货入库回归测试报告 + +- 测试类型:回归测试 / 单元测试 +- 执行时间:2026-04-17 17:27:16 +- 执行入口:`npm run test:local` +- 覆盖目标: + - [test/app/controller/system.storage.receiving.test.js](../test/app/controller/system.storage.receiving.test.js) + - [test/app/service/systems/storage.receiving.detailChange.test.js](../test/app/service/systems/storage.receiving.detailChange.test.js) + - [test/app/service/systems/storage.receiving.report.test.js](../test/app/service/systems/storage.receiving.report.test.js) + +## 测试目标 + +验证收货模块现有回归用例是否稳定,重点覆盖收货列表、收货明细变更、收货完成报表三条链路。 + +## 测试范围 + +本次仅执行现有回归用例,不修改任何代码,不新增任何测试数据。 + +## 测试产物 + +- Mocha / egg-bin 执行结果 +- mochawesome 报告:`node_modules/.mochawesome-reports/mochawesome.html` +- 本测试报告:`test_reports/fail/20260417-172716-收货入库回归测试报告.md` + +## 测试结果摘要 + +- 通过:2 个目标文件 +- 失败:1 个目标文件 +- 总计:3 个目标文件 +- 通过用例数:28 +- 失败用例数:1 + +### 通过项 + +- [test/app/controller/system.storage.receiving.test.js](../test/app/controller/system.storage.receiving.test.js):15 passing +- [test/app/service/systems/storage.receiving.report.test.js](../test/app/service/systems/storage.receiving.report.test.js):13 passing + +### 失败项 + +- [test/app/service/systems/storage.receiving.detailChange.test.js](../test/app/service/systems/storage.receiving.detailChange.test.js) +- 失败用例:`should reject expired expiry_date before updating receiving detail` +- 失败断言:期望返回 `code = 400`,实际返回 `code = 500` +- 失败位置:测试文件第 112 行附近 + +## 失败原因 + +当前 `detailChange` 实现没有在明细更新前拦截过期 `expiry_date`,请求继续进入后续更新流程;随后执行到 `updateReceivingStats`,而该单测 harness 未提供 `ctx.model.transaction`,最终被服务层 `catch` 转成 `500`。 + +相关实现位置: + +- [app/service/systems/storage/receiving.js](../app/service/systems/storage/receiving.js#L1952) +- [app/service/systems/storage/receiving.js](../app/service/systems/storage/receiving.js#L1686) + +## 最小复现信息 + +```text +npm run test:local -- test/app/service/systems/storage.receiving.detailChange.test.js +``` + +该单测即可稳定复现失败,无需额外环境操作。 + +## 环境 / 数据 / 依赖影响判断 + +- 环境:未见 npm / egg-bin 启动失败,测试框架可正常运行 +- 数据:未观察到外部测试数据缺失导致的报错,本次失败是可复现的断言失败 +- 依赖:未发现缺包或安装失败问题 +- 结论:本次失败主要来自当前实现与现有回归用例预期不一致,且单测 harness 对下游事务依赖的模拟不完整 + +## 结论与建议 + +- 当前收货回归测试整体为部分通过,2 个目标文件通过,1 个目标文件失败 +- 失败场景是收货明细变更的过期日期拦截,建议后续补齐该分支的业务校验后再回归验证 diff --git a/test_reports/pass/20260411-184847-order_delivery_dispatch_factory-MySQL建表集成测试报告.md b/test_reports/pass/20260411-184847-order_delivery_dispatch_factory-MySQL建表集成测试报告.md new file mode 100644 index 0000000..8a5929d --- /dev/null +++ b/test_reports/pass/20260411-184847-order_delivery_dispatch_factory-MySQL建表集成测试报告.md @@ -0,0 +1,46 @@ +# order_delivery_dispatch_factory MySQL 建表集成测试报告 + +## 元信息 + +| 项 | 值 | +|----|-----| +| 测试类型 | 单元 + 集成(第三项依赖 MySQL + `DISPATCH_FACTORY_TEST_MYSQL=1`) | +| 执行时间 | 2026-04-11 | +| 范围 | `test/app/model/order_delivery_dispatch_factory.test.js` | + +## 测试目标 + +验证 `OrderDeliveryDispatchFactory` 的 M4/M5 分表命名、分区辅助逻辑;在显式开启 `egg-sequelize` 与可连 MySQL 时,验证首次 `getModel` 会创建物理表并命中缓存。 + +## 测试范围与产物 + +- 文件:`test/app/model/order_delivery_dispatch_factory.test.js` +- 配置:`config/plugin.js` 中 `sequelize.enable` 在 `NODE_ENV=test` 下仅当 `DISPATCH_FACTORY_TEST_MYSQL=1` 时启用 +- 快捷脚本:`npm run test:dispatch-factory`(需同时设置环境变量) + +## 测试结果摘要(带 MySQL 集成) + +**命令(PowerShell):** + +```text +$env:DISPATCH_FACTORY_TEST_MYSQL='1'; npm run test:local -- test/app/model/order_delivery_dispatch_factory.test.js +``` + +**结果:** 3 passing,0 failing,0 pending(第三项执行建表断言,非 skip)。 + +**说明:** 启动阶段可能出现 Sequelize 连接重试警告(如 `ETIMEDOUT` 后重试成功);Redis 在默认 test 下关闭属预期。 + +## 默认 test(不设环境变量) + +第三项在 `dialect() !== 'mysql'` 且未设置 `DISPATCH_FACTORY_TEST_MYSQL=1` 时 **skip**(Mocha 显示为 1 pending),前两例始终通过;适合不连库的 CI/本地快速跑。 + +**结果(本机复跑):** 2 passing,1 pending。 + +## 结论与建议 + +- 带 `DISPATCH_FACTORY_TEST_MYSQL=1` 时 M4/M5 建表路径已可真实断言;分区使用 `209901`、仓库 `100000`,与 `warehouse_shard_guard` 约定一致。 +- 建议在能连 `config` 中 wms MySQL 的流水线或本地定期执行带环境变量的单文件用例,无需跑全量 `test:local`。 + +## ESLint + +已对 `config/plugin.js`、`test/app/model/order_delivery_dispatch_factory.test.js` 执行 ESLint,无错误、无警告。 diff --git a/test_reports/pass/20260412-014727-订单工作台list单测报告.md b/test_reports/pass/20260412-014727-订单工作台list单测报告.md new file mode 100644 index 0000000..f700de1 --- /dev/null +++ b/test_reports/pass/20260412-014727-订单工作台list单测报告.md @@ -0,0 +1,53 @@ +# 订单工作台 list 单测报告 + +## 测试目标 + +补齐订单工作台 `list` 相关单测,覆盖 `app/service/systemMethods/order/base.js` 的 `buildWhere`、分页上限,以及订单命名空间各列表入口的返回结构与兼容旧入口。 + +## 测试类型 + +- 单元测试 +- 纯逻辑测试 +- 入口封装测试 + +## 测试范围 + +本次新增/修改的测试文件: + +- [test/support/order_service_test_helper.js](../../test/support/order_service_test_helper.js) +- [test/app/service/systemMethods/order.base.step.test.js](../../test/app/service/systemMethods/order.base.step.test.js) +- [test/app/controller/system.order.namespaced.test.js](../../test/app/controller/system.order.namespaced.test.js) +- [test/app/controller/system.order.reviewOrder.test.js](../../test/app/controller/system.order.reviewOrder.test.js) +- [test/app/controller/system.order.getreviewOrderlist.test.js](../../test/app/controller/system.order.getreviewOrderlist.test.js) + +## 覆盖点 + +- `buildWhere` + - `step = 1` 的等值过滤 + - `step.operator = in` 且 `value` 为数组的过滤 + - `warehouse_id` 注入确认 +- `listByModule` + - `pageSize` 超过上限时被截断到服务端限制值 + - `pagination.pageSize` 返回截断后的值 + - `list.length <= pagination.pageSize` + - `deliveryOrder` 场景下 `step` 条件可透传并过滤结果 +- 订单命名空间 list 入口 + - `order.list` 返回 `list/pagination` + - `pendingOrder`、`expectionOrder`、`entrustOrder`、`deliveryOrder`、`deliveryExpectionOrder`、`archiveOrder` 的 list 入口返回 `list/pagination` +- 兼容旧入口 + - `reviewOrder.list` 返回 `list/pagination` + - `getreviewOrderlist` 返回 `list/pagination` + +## 测试结果摘要 + +- 运行命令:`npx egg-bin test test/app/service/systemMethods/order.base.step.test.js test/app/controller/system.order.namespaced.test.js test/app/controller/system.order.reviewOrder.test.js test/app/controller/system.order.getreviewOrderlist.test.js` +- 结果:7 passing,0 failing +- 验证范围:覆盖纯 service 逻辑与订单命名空间入口返回结构,未依赖真实数据库数据 + +## 结论 + +本次订单工作台 `list` 相关单测已补齐,分页上限与 where 过滤链路已通过验证,且未修改业务代码和文档。 + +## 备注 + +测试用辅助工具已抽到 [test/support/order_service_test_helper.js](../../test/support/order_service_test_helper.js),便于后续继续补充同类订单入口测试。 diff --git a/test_reports/pass/20260412-165910-订单迁移回归测试报告.md b/test_reports/pass/20260412-165910-订单迁移回归测试报告.md new file mode 100644 index 0000000..82384c6 --- /dev/null +++ b/test_reports/pass/20260412-165910-订单迁移回归测试报告.md @@ -0,0 +1,35 @@ +# 订单迁移回归测试报告 + +- 测试类型:单元测试 + 静态检查 +- 测试目标:验证 `app/service/systems/order_delivery_migration.js` 在选中源行缺少 `delivery_order_code/store_id/warehouse_id` 时会 fail-fast 并回滚,同时正常迁移、批次上限和 item 迁移仍然正常。 +- 测试范围: + - `app/service/systems/order_delivery_migration.js` + - `test/app/service/systems/order_delivery_migration.test.js` + +## 测试产物 + +- 执行命令: + - `npm run test:local -- --grep "order_delivery_migration"` + - `npx eslint app/service/systems/order_delivery_migration.js test/app/service/systems/order_delivery_migration.test.js` +- 校验结果: + - `app/service/systems/order_delivery_migration.js` 无 ESLint/语法错误 + - `test/app/service/systems/order_delivery_migration.test.js` 无 ESLint/语法错误 + +## 测试结果摘要 + +- 单元测试:6 passing,0 failing,0 pending +- 静态检查:通过,退出码 `0` +- 关键回归场景: + - 缺少关键字段时立即抛错并回滚:通过 + - 正常迁移订单和商品明细:通过 + - 单批最多处理 1000 条:通过 + - 重复执行时跳过已迁移订单:通过 + +## 结论 + +本次订单迁移修复的回归验证通过。当前实现已满足 fail-fast + 回滚要求,且正常迁移、批次上限和 item 迁移路径未见回归。 + +## 备注 + +- 本次未发现失败用例。 +- 未执行全量 `npm run lint`,仅对目标文件做了针对性 ESLint 检查。 diff --git a/test_reports/pass/20260412-1753-真实收货入库流程验证报告.md b/test_reports/pass/20260412-1753-真实收货入库流程验证报告.md new file mode 100644 index 0000000..983e430 --- /dev/null +++ b/test_reports/pass/20260412-1753-真实收货入库流程验证报告.md @@ -0,0 +1,57 @@ +# 真实收货入库流程验证报告 + +- 测试类型:接口验证 / 集成验证 / 真实流程 smoke +- 执行日期:2026-04-12 +- 执行目标:完成一笔真实收货入库流程,确认收货单完成且库存确实增加 + +## 测试目标 + +1. 复用仓库现有真实流程脚本和系统方法客户端执行收货入库链路。 +2. 完成收货单创建、绑定货主、添加明细、绑定商品、完成收货、快捷入库。 +3. 验证库存前后变化,确认库存确实增加。 +4. 输出单据 ID、关键状态、库存变化证据。 + +## 测试范围 + +- [test/support/system_method_client.js](../../test/support/system_method_client.js) +- [temp/verify-receiving-flow-store100000.cjs](../../temp/verify-receiving-flow-store100000.cjs) +- [app/service/systems/storage/receiving.js](../../app/service/systems/storage/receiving.js) +- [app/service/systems/stock_store.js](../../app/service/systems/stock_store.js) + +## 测试产物 + +- 收货单 ID:697 +- 收货单号:R20555015 +- 入库单 ID:194 +- 入库单号:SCRK17759877887936252 +- 商品 ID:157059 +- 商品名称:yjm0411 +- 库存快照:before 31,after 34,delta +3 +- 收货状态:completed +- 收货入库状态:all +- 快捷入库明细数:1 +- 快捷入库返回状态:200 / 快捷入库完成 +- 报表 URL:已生成并可访问 + +## 测试结果摘要 + +- 收货单完成成功。 +- 快捷入库成功,返回入库单信息且 `entry_order.order_status = COMPLETED`。 +- 库存确实增加,`wms_stock_warehouse.quantity` 从 31 增加到 34,增量为 3。 +- `locked_quantity` 前后均为 0。 + +## 关键证据 + +- 快捷入库返回:`receiving_storage_status = all` +- 库存快照返回:`quantity: 31 -> 34` +- 入库单返回:`entry_order_code = SCRK17759877887936252` + +## 结论 + +本次真实收货入库流程成功,库存已实际增加,且收货单与入库单状态均符合预期。 + +## 备注 + +- 执行过程中曾出现一次失败,根因是明细先绑定商品后再执行 `detailChange`,导致 `system_product_id` 被清空,快捷入库被判定为“未匹配系统商品”。 +- 已按仓库现有测试顺序修正为先 `detailChange` 再 `bindDetailProduct`,最终执行通过。 +- 生成的 Excel 报表已可下载,但其预览内容中出现了旧的收货单编号片段;库存是否增加的最终判定以实时接口和数据库快照为准。 diff --git a/test_reports/pass/20260414-库存效期任务跨天重发与旧缓存兼容验证报告.md b/test_reports/pass/20260414-库存效期任务跨天重发与旧缓存兼容验证报告.md new file mode 100644 index 0000000..db84c4b --- /dev/null +++ b/test_reports/pass/20260414-库存效期任务跨天重发与旧缓存兼容验证报告.md @@ -0,0 +1,39 @@ +# 库存效期任务跨天重发与旧缓存兼容验证报告 + +- 测试类型:单元测试 + 只读临时脚本验证 +- 测试目标:复核 [app/schedule/notice_stock_remaining.js](../../app/schedule/notice_stock_remaining.js) 是否满足“每天都能再次提醒一次”的需求,并检查同日去重、跨天重发、商品间隔离、失败重试、旧缓存兼容。 + +## 测试范围 + +- [app/schedule/notice_stock_remaining.js](../../app/schedule/notice_stock_remaining.js) +- [test/app/schedule/notice_stock_remaining.test.js](../../test/app/schedule/notice_stock_remaining.test.js) + +## 测试产物 + +- 现有单测:4 passing,0 failing +- 临时只读验证:跨天重发与旧缓存对象格式兼容检查通过 +- ESLint:针对目标文件检查通过,退出码 0 + +## 结果摘要 + +1. 同一商品同一天内重复触发,只发送一次:通过 +2. 跨天后同一商品可以再次发送:通过 +3. 同一天内不同商品互不影响:通过 +4. 发送失败时不会写入去重缓存,下一轮仍会重试:通过 +5. 旧缓存格式兼容,不会误拦截新逻辑:通过 + +## 关键验证 + +- 现有单测覆盖了 legacy 全局缓存 key、同日商品级去重、失败不写缓存、`notice.index.send` 兼容路径。 +- 额外临时脚本验证了两个缺口: + - 同一商品跨天重跑时,会生成新的日粒度缓存键并再次发送。 + - legacy 缓存值为 JSON 字符串数组对象、以及对象 map 形态时,任务仍会正常发送,不会被旧缓存误拦截。 + +## 结论 + +当前实现已经满足“每天都能再次提醒一次”的目标,且没有发现同日去重、失败重试或旧缓存兼容方面的回归。 + +## 遗漏与风险 + +- 目前仓库内的正式单测已经覆盖了大部分核心路径,但跨天场景仍依赖本次临时只读脚本补强,建议后续补成正式单测,避免只靠手工验证。 +- 旧缓存兼容目前主要验证了旧缓存 key 与旧值形态不会阻断新逻辑;如果后续还会出现更复杂的历史缓存结构,建议再补一条专门回归用例。 diff --git a/worktrees/deploy-20260409155126 b/worktrees/deploy-20260409155126 deleted file mode 160000 index 69e992b..0000000 --- a/worktrees/deploy-20260409155126 +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 69e992bf9dc1242f5c35b3aa5bdddcc716274045 From fec1dd9f55bc68db4dcd5aa1a8c7653480f27a39 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Fri, 17 Apr 2026 19:23:49 +0800 Subject: [PATCH 031/550] chore: update consume progress --- runtime/file-writer/qimen-logs/.consume-progress | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/runtime/file-writer/qimen-logs/.consume-progress b/runtime/file-writer/qimen-logs/.consume-progress index f1a39e0..076fe43 100644 --- a/runtime/file-writer/qimen-logs/.consume-progress +++ b/runtime/file-writer/qimen-logs/.consume-progress @@ -3,5 +3,5 @@ "offset": 1713, "processedCount": 1, "completedAt": "2026-04-12T14:54:22.636Z", - "updatedAt": "2026-04-17T11:20:32.237Z" + "updatedAt": "2026-04-17T11:23:32.286Z" } From 37a8e152a6c628fa1cfe3eb05cb24ea78dedbf37 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Fri, 17 Apr 2026 20:02:39 +0800 Subject: [PATCH 032/550] =?UTF-8?q?=E5=90=8C=E6=AD=A5=E6=96=87=E6=A1=A3?= =?UTF-8?q?=E4=B8=8E=E7=B3=BB=E7=BB=9F=E6=8E=A5=E5=8F=A3=E5=8F=98=E6=9B=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/agents/文档.agent.md | 34 +- README.md | 2 +- docs/api-doc-update-workflow.md | 43 +- methods/system.json | 750 +++++++++++++++++- .../file-writer/qimen-logs/.consume-progress | 6 +- 5 files changed, 808 insertions(+), 27 deletions(-) diff --git a/.github/agents/文档.agent.md b/.github/agents/文档.agent.md index be3c5df..7ca1a5e 100644 --- a/.github/agents/文档.agent.md +++ b/.github/agents/文档.agent.md @@ -38,9 +38,10 @@ model: GPT-5 mini (copilot) - 公共请求头变化 - 鉴权方式变化 - 每次 API 接口变更(新增 / 修改 / 删除 method、参数、响应、错误码、header、鉴权等)后,除了更新 `methods/*.json` / `docs/*.md`,**还必须追加一条变更记录到对应的 `methods/changes/.json` 数组** - - 默认禁止直接手写 `methods/*.json` / `methods/changes/*.json`,必须先按 `docs/api-doc-update-workflow.md` 生成固定 spec,再执行 `npm run doc:api:update -- --spec=` - - 正式写入前必须先执行 `npm run doc:api:update -- --spec= --dry-run` - - 修补 JSON 文件时必须强校验 JSON 格式正确性,确保不会引入无法解析的问题 + - 明确禁止直接手动编辑或提交 `methods/*.json` 与 `methods/changes/*.json` 文件。 + - 任何 PR 中直接修改这类文件的变更将被视为违规并可能被退回。所有对 methods JSON 的写入必须通过脚本完成,命令为 `npm run doc:api:update -- --spec=`(不可绕过)。 + - 正式写入前**必须**先执行 `npm run doc:api:update -- --spec= --dry-run` 进行验证;dry-run 不做写入,仅输出差异和校验结果。 + - 修补 JSON 文件时必须强校验 JSON 格式正确性,确保不会引入无法解析或破坏结构的问题 - `methods/*.json` 仍是 SSOT,`methods/changes/*.json` 仅记录差异历史 - 变更记录建议字段至少包含:`version`、`date`、`summary`、`methods`、`notes` 5. 如 system 入参有变化,可执行: @@ -97,6 +98,33 @@ Select-String -Path "methods/system.json" -Pattern "storage.receiving.bindDetail 3) 同步 docs/*.md / README,并校验文档与实现一致 ``` +## 脚本使用示例 + +推荐的最小操作序列(PowerShell 示例): + +```powershell +# 1) 从示例复制 spec 到 temp 并编辑 +Copy-Item docs/api-doc-update-spec.example.json temp/api-doc-update.json + +# 2) 先 dry-run(仅校验并打印差异) +npm run doc:api:update -- --spec=temp/api-doc-update.json --dry-run + +# 3) 检查 dry-run 输出并修正 spec;确认无误后正式写入 +npm run doc:api:update -- --spec=temp/api-doc-update.json + +# 4) 仅修补主文档且不追加 changes(慎用) +npm run doc:api:update -- --spec=temp/api-doc-update.json --doc-only +``` + +脚本职责(由 `script/update-api-doc.cjs` 实现): + +- 校验 spec JSON 结构与必填字段 +- 在 dry-run 模式下不写入,仅打印将要变更的差异并返回校验结果 +- 校验目标 `methods/*.json` 与 `methods/changes/*.json` 的可解析性 +- 按 `group` + `method` 执行 upsert,避免覆盖或破坏其它分组/方法 +- 保留目标文件原有缩进与换行风格,尽量减少无关 diff +- 校验 change 版本不重复并拒绝重复写入 + ## 输出要求 - 所有回复建议以 `[Doc]` 开头 diff --git a/README.md b/README.md index 09584fc..d237237 100644 --- a/README.md +++ b/README.md @@ -184,4 +184,4 @@ const parsed = await ctx.service.systems.excel.parseFile('D:/tmp/demo.xlsx'); ## 参考 -- Egg.js 官方文档:https://eggjs.org +- Egg.js 官方文档:https://v3.eggjs.org/ diff --git a/docs/api-doc-update-workflow.md b/docs/api-doc-update-workflow.md index eccf22b..c5e8343 100644 --- a/docs/api-doc-update-workflow.md +++ b/docs/api-doc-update-workflow.md @@ -64,21 +64,25 @@ - `methods` 为要写入的完整 method 文档对象数组,脚本按 `method` 字段 upsert - `change` 默认必填;仅当明确是纯格式修复且不需要追加历史时,才允许加 `--doc-only` +注意:所有对 `methods/*.json` 与 `methods/changes/*.json` 的变更必须通过 spec + 脚本完成。spec 是唯一输入来源,不接受直接手写或直接提交目标 JSON 的改动。 + ## 固定命令 -先做 dry-run: +务必按顺序执行:复制 example -> 编辑 spec -> dry-run -> 修正 -> 正式写入。示例命令(PowerShell): + +先做 dry-run(验证和查看差异): ```powershell npm run doc:api:update -- --spec=temp/api-doc-update.json --dry-run ``` -确认无误后执行写入: +确认 dry-run 输出无误后执行正式写入: ```powershell npm run doc:api:update -- --spec=temp/api-doc-update.json ``` -纯文档主文件修补且不追加 changes 时: +仅修补主文档且不追加 changes 时(慎用): ```powershell npm run doc:api:update -- --spec=temp/api-doc-update.json --doc-only @@ -86,18 +90,35 @@ npm run doc:api:update -- --spec=temp/api-doc-update.json --doc-only ## 脚本保证 -`script/update-api-doc.cjs` 会执行以下动作: +`script/update-api-doc.cjs` 会执行以下动作(脚本为写入守门人): -- 校验 spec JSON 是否符合固定结构 +- 校验 spec JSON 是否符合固定结构与必填字段 - 校验目标 `methods/*.json` 与 `methods/changes/*.json` 是否可解析 -- 按 group + method 做 upsert,避免手写 JSON 时把括号、逗号、层级写坏 -- 检查 change version 是否重复 -- 保留目标 JSON 原有缩进与换行风格 +- 在 dry-run 模式下不写入,仅打印将要变更的差异并返回校验结果 +- 按 `group` + `method` 做 upsert,避免覆盖或破坏其他分组/方法 +- 检查 change version 是否重复并拒绝冲突写入 +- 尽量保留目标 JSON 原有缩进与换行风格,减少无关 diff + +脚本是对 methods JSON 的唯一写入通道;任何绕过脚本的改动都不被接受。 ## 推荐流程 1. 先核对代码与测试,确认真实接口契约 2. 如果是 system 参数结构变化,可先执行 `node .\script\tmp-struct-system-params.cjs` -3. 按 [docs/api-doc-update-spec.example.json](docs/api-doc-update-spec.example.json) 复制一份 spec 到 `temp/` -4. 先执行 dry-run,再执行正式写入 -5. 最后补充必要的 `docs/*.md` 或 `README.md` \ No newline at end of file +3. 按 [docs/api-doc-update-spec.example.json](docs/api-doc-update-spec.example.json) 复制一份 spec 到 `temp/` 并在该文件上编辑 +4. 先执行 dry-run(`--dry-run`),阅读输出并修正 spec +5. 确认无误后执行正式写入(不带 `--dry-run`) +6. 最后补充必要的 `docs/*.md` 或 `README.md` + +最小示例流程(PowerShell): + +```powershell +# 复制示例到 temp 并编辑 +Copy-Item docs/api-doc-update-spec.example.json temp/api-doc-update.json + +# dry-run +npm run doc:api:update -- --spec=temp/api-doc-update.json --dry-run + +# 正式写入 +npm run doc:api:update -- --spec=temp/api-doc-update.json +``` \ No newline at end of file diff --git a/methods/system.json b/methods/system.json index ee2ad0d..edbee82 100644 --- a/methods/system.json +++ b/methods/system.json @@ -552,15 +552,6 @@ "isNeedAuth": false, "isNeedLogin": true, "params": [] - }, - { - "method": "index.getExpressList", - "description": "index.getExpressList 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "params": [], - "response": [], - "errors": [] } ] }, @@ -2436,6 +2427,747 @@ } ] }, + { + "groupName": "快递编码管理模块", + "module": "setting.express", + "list": [ + { + "method": "index.getExpressList", + "description": "合并后的快递列表", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [], + "response": [], + "errors": [] + }, + { + "method": "setting.express.list", + "description": "查询当前仓库范围的快递映射列表,支持 where + pagination", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数,支持 page / pageSize,兼容 currentPage / page_size / size" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构" + } + ], + "response": [], + "errors": [] + }, + { + "method": "setting.express.listBase", + "description": "返回系统快递基础列表(系统级别基础快递,不含仓库自定义)", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [], + "response": [], + "errors": [] + }, + { + "method": "setting.express.create", + "description": "创建快递映射,仅写入已实现字段(code、name、platform 等)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "code", + "type": "string", + "required": true, + "source": "body", + "description": "快递编码" + }, + { + "name": "name", + "type": "string", + "required": true, + "source": "body", + "description": "快递名称" + }, + { + "name": "platform", + "type": "string", + "required": false, + "source": "body", + "description": "平台标识(可选)" + } + ], + "response": [], + "errors": [] + }, + { + "method": "setting.express.checkCodeUnique", + "description": "校验快递编码在当前仓库/主体维度唯一性,仅支持 code 与可选 id 排除自身", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "code", + "type": "string", + "required": true, + "source": "body", + "description": "待校验的快递编码" + }, + { + "name": "id", + "type": "number", + "required": false, + "source": "body", + "description": "排除自身 id(更新时使用)" + } + ], + "response": [], + "errors": [] + }, + { + "method": "setting.express.update", + "description": "更新快递映射,仅更新已实现字段(例如 name、platform)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "快递记录ID" + }, + { + "name": "name", + "type": "string", + "required": false, + "source": "body", + "description": "快递名称" + }, + { + "name": "platform", + "type": "string", + "required": false, + "source": "body", + "description": "平台标识(可选)" + } + ], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "快递接口管理模块", + "module": "setting.expressInterface", + "list": [ + { + "method": "setting.expressInterface.list", + "description": "查询当前仓库范围的快递接口列表,支持 where + pagination;返回 data:{ list, total, page, page_size }。每条记录字段见 children。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数,支持 page / pageSize,兼容 currentPage / page_size / size" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "统一 where 条件对象;支持字段:id、name、express_code、platform_code、express_platform_id、sender_name、sender_tel、viewer、client_id、share_id、site_code、product_type、shop_name。支持 quickWhere 快速关键词。" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "快递接口记录数组(每项字段如下)", + "children": [ + { + "name": "id", + "type": "number", + "description": "记录ID" + }, + { + "name": "name", + "type": "string", + "description": "接口名称" + }, + { + "name": "express_code", + "type": "string", + "description": "快递编码" + }, + { + "name": "warehouse_id", + "type": "number", + "description": "所属仓库ID(文档中的仓库范围由系统强制校验)" + }, + { + "name": "platform_code", + "type": "string", + "description": "平台代码" + }, + { + "name": "express_platform_id", + "type": "number", + "description": "平台接口ID" + }, + { + "name": "sender_name", + "type": "string", + "description": "发件人姓名" + }, + { + "name": "sender_tel", + "type": "string", + "description": "发件人电话" + }, + { + "name": "weight", + "type": "number", + "description": "默认重量" + }, + { + "name": "token", + "type": "string", + "description": "接口密钥或 token(部分记录可能为空)" + }, + { + "name": "viewer", + "type": "string", + "description": "查看者标识" + }, + { + "name": "client_id", + "type": "string", + "description": "客户端 ID" + }, + { + "name": "is_share", + "type": "number", + "description": "是否共享(0/1)" + }, + { + "name": "share_id", + "type": "number", + "description": "共享记录ID" + }, + { + "name": "can_use_count", + "type": "number", + "description": "可用次数或配额" + }, + { + "name": "province_name", + "type": "string", + "description": "省" + }, + { + "name": "city_name", + "type": "string", + "description": "市" + }, + { + "name": "district_name", + "type": "string", + "description": "区/县" + }, + { + "name": "site_code", + "type": "string", + "description": "站点编码" + }, + { + "name": "product_type", + "type": "string", + "description": "快递产品类型" + }, + { + "name": "shop_name", + "type": "string", + "description": "店铺名称/分组标识" + } + ] + }, + { + "name": "total", + "type": "number", + "description": "匹配的总记录数" + }, + { + "name": "page", + "type": "number", + "description": "当前页" + }, + { + "name": "page_size", + "type": "number", + "description": "每页数量" + } + ], + "errors": [ + { + "code": "400", + "description": "缺少仓库上下文或 where 参数解析失败" + }, + { + "code": "500", + "description": "查询失败" + } + ] + }, + { + "method": "setting.expressInterface.create", + "description": "在当前仓库范围内创建快递接口,仅写入已实现字段(见 params),仓库由系统自动填充,禁止传入 warehouse_id/warehouseId。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "name", + "type": "string", + "required": true, + "source": "body", + "description": "接口名称" + }, + { + "name": "express_code", + "type": "string", + "required": true, + "source": "body", + "description": "快递编码(不区分大小写,会在服务端转为大写)" + }, + { + "name": "platform_code", + "type": "string", + "required": true, + "source": "body", + "description": "平台代码(不区分大小写,会在服务端转为大写)" + }, + { + "name": "express_platform_id", + "type": "number", + "required": true, + "source": "body", + "description": "平台接口 ID" + }, + { + "name": "sender_name", + "type": "string", + "required": false, + "source": "body", + "description": "发件人姓名" + }, + { + "name": "sender_tel", + "type": "string", + "required": false, + "source": "body", + "description": "发件人电话" + }, + { + "name": "weight", + "type": "number", + "required": false, + "source": "body", + "description": "默认重量(可选)" + }, + { + "name": "token", + "type": "string", + "required": false, + "source": "body", + "description": "接口密钥或 token" + }, + { + "name": "viewer", + "type": "string", + "required": false, + "source": "body", + "description": "查看者标识" + }, + { + "name": "client_id", + "type": "string", + "required": false, + "source": "body", + "description": "客户端 ID" + }, + { + "name": "is_share", + "type": "number", + "required": false, + "source": "body", + "description": "是否共享(0/1)" + }, + { + "name": "share_id", + "type": "number", + "required": false, + "source": "body", + "description": "共享记录 ID" + }, + { + "name": "can_use_count", + "type": "number", + "required": false, + "source": "body", + "description": "可用次数/配额" + }, + { + "name": "province_name", + "type": "string", + "required": false, + "source": "body", + "description": "省" + }, + { + "name": "city_name", + "type": "string", + "required": false, + "source": "body", + "description": "市" + }, + { + "name": "district_name", + "type": "string", + "required": false, + "source": "body", + "description": "区/县" + }, + { + "name": "site_code", + "type": "string", + "required": false, + "source": "body", + "description": "站点编码" + }, + { + "name": "product_type", + "type": "string", + "required": false, + "source": "body", + "description": "快递产品类型" + }, + { + "name": "shop_name", + "type": "string", + "required": false, + "source": "body", + "description": "店铺名称/分组标识" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "新建记录 ID" + } + ], + "errors": [ + { + "code": "400", + "description": "必填参数缺失或参数格式错误" + }, + { + "code": "409", + "description": "快递编码或平台接口组合已存在(冲突)" + } + ] + }, + { + "method": "setting.expressInterface.update", + "description": "更新快递接口,支持局部字段更新;支持 id 别名 interface_id / interfaceId;禁止通过接口修改 warehouse_id。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "快递接口ID;兼容 interface_id / interfaceId" + }, + { + "name": "name", + "type": "string", + "required": false, + "source": "body", + "description": "接口名称" + }, + { + "name": "express_code", + "type": "string", + "required": false, + "source": "body", + "description": "快递编码(更新时会被转为大写)" + }, + { + "name": "platform_code", + "type": "string", + "required": false, + "source": "body", + "description": "平台代码(更新时会被转为大写)" + }, + { + "name": "express_platform_id", + "type": "number", + "required": false, + "source": "body", + "description": "平台接口 ID" + }, + { + "name": "sender_name", + "type": "string", + "required": false, + "source": "body", + "description": "发件人姓名" + }, + { + "name": "sender_tel", + "type": "string", + "required": false, + "source": "body", + "description": "发件人电话" + }, + { + "name": "weight", + "type": "number", + "required": false, + "source": "body", + "description": "默认重量" + }, + { + "name": "token", + "type": "string", + "required": false, + "source": "body", + "description": "接口密钥或 token" + }, + { + "name": "viewer", + "type": "string", + "required": false, + "source": "body", + "description": "查看者标识" + }, + { + "name": "client_id", + "type": "string", + "required": false, + "source": "body", + "description": "客户端 ID" + }, + { + "name": "is_share", + "type": "number", + "required": false, + "source": "body", + "description": "是否共享(0/1)" + }, + { + "name": "share_id", + "type": "number", + "required": false, + "source": "body", + "description": "共享记录 ID" + }, + { + "name": "can_use_count", + "type": "number", + "required": false, + "source": "body", + "description": "可用次数/配额" + }, + { + "name": "province_name", + "type": "string", + "required": false, + "source": "body", + "description": "省" + }, + { + "name": "city_name", + "type": "string", + "required": false, + "source": "body", + "description": "市" + }, + { + "name": "district_name", + "type": "string", + "required": false, + "source": "body", + "description": "区/县" + }, + { + "name": "site_code", + "type": "string", + "required": false, + "source": "body", + "description": "站点编码" + }, + { + "name": "product_type", + "type": "string", + "required": false, + "source": "body", + "description": "快递产品类型" + }, + { + "name": "shop_name", + "type": "string", + "required": false, + "source": "body", + "description": "店铺名称/分组标识" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "description": "首条更新记录 ID" + }, + { + "name": "name", + "type": "string", + "description": "更新后的接口名称" + } + ], + "errors": [ + { + "code": "400", + "description": "id 为空或无可更新字段" + }, + { + "code": "404", + "description": "快递接口不存在或无权限操作" + }, + { + "code": "409", + "description": "快递编码或平台接口组合冲突" + } + ] + }, + { + "method": "setting.expressInterface.delete", + "description": "删除快递接口,支持 id 别名 interface_id / interfaceId;返回被删除记录 id 与所属 warehouse_id。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "快递接口ID;兼容 interface_id / interfaceId" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "description": "已删除记录 ID" + }, + { + "name": "warehouse_id", + "type": "number", + "description": "记录所属仓库 ID" + }, + { + "name": "deleted", + "type": "boolean", + "description": "是否已删除,成功时为 true" + } + ], + "errors": [ + { + "code": "400", + "description": "id 为空或格式错误" + }, + { + "code": "404", + "description": "快递接口不存在或无权限操作" + } + ] + } + ] + }, { "groupName": "账号管理模块", "module": "setting.account", diff --git a/runtime/file-writer/qimen-logs/.consume-progress b/runtime/file-writer/qimen-logs/.consume-progress index 076fe43..8ba54cd 100644 --- a/runtime/file-writer/qimen-logs/.consume-progress +++ b/runtime/file-writer/qimen-logs/.consume-progress @@ -1,7 +1,7 @@ { - "filePath": "D:\\wms\\runtime\\file-writer\\qimen-logs\\2026\\04\\12\\qimen-logs-MINGREN-worker-p42648-0001.log", + "filePath": "D:\\wms\\runtime\\file-writer\\qimen-logs\\2026\\04\\12\\qimen-logs-MINGREN-worker-p38224-0001.log", "offset": 1713, "processedCount": 1, - "completedAt": "2026-04-12T14:54:22.636Z", - "updatedAt": "2026-04-17T11:23:32.286Z" + "completedAt": "2026-04-12T14:46:52.525Z", + "updatedAt": "2026-04-27T08:09:00.255Z" } From 0ffe290a211229788cb73328cfd386956fb04554 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 27 Apr 2026 15:57:29 +0800 Subject: [PATCH 033/550] chore: commit all current workspace changes --- .github/agents/文档.agent.md | 1 + .github/agents/调度.agent.md | 2 +- app.js | 5 +- app/controller/docs.js | 468 +++- app/controller/openapi.js | 56 + app/extend/application.js | 28 + app/lib/api_sign.js | 193 ++ app/lib/file_writer.js | 79 +- app/lib/order_delivery_selfcheck.js | 19 - app/lib/polo_api_client.js | 73 +- app/lib/qimen_client.js | 216 ++ app/model/express.js | 14 +- app/model/express_interface.js | 56 +- app/model/express_platform.js | 75 - app/model/express_setting.js | 11 +- app/model/notification_webhook.js | 1 + app/model/operation_log.js | 7 +- app/model/order_delivery.js | 66 +- app/model/order_delivery_factory.js | 21 +- app/model/order_delivery_table_schema.js | 4 +- app/model/order_express.js | 27 +- app/model/order_items_factory.js | 2 +- app/model/platform.js | 55 +- app/model/store_warehouse.js | 97 +- .../store_warehouse_print_quantity_log.js | 11 +- app/router.js | 3 + app/service/apiMethods/test.js | 4 +- app/service/openapi.js | 238 +++ app/service/openapiMethods/index.js | 35 + app/service/openapiMethods/ping.js | 23 + app/service/systemMethods/index.js | 28 +- app/service/systemMethods/order/base.js | 89 +- .../systemMethods/order/expectionOrder.js | 68 +- app/service/systemMethods/order/index.js | 38 +- .../systemMethods/order/pendingOrder.js | 1045 ++++++++- .../systemMethods/order/storageAllocation.js | 46 +- app/service/systemMethods/setting/express.js | 75 +- .../systemMethods/setting/expressInterface.js | 26 +- app/service/systemMethods/setting/platform.js | 53 +- app/service/systems/api_sign.js | 144 ++ app/service/systems/delivery_order.js | 235 +- app/service/systems/entry_order.js | 4 +- app/service/systems/express.js | 1599 +++++++++++++- app/service/systems/express_platform.js | 580 +++++ app/service/systems/operation_log.js | 151 +- app/service/systems/order_async.js | 1122 ++++++++++ .../systems/order_delivery_migration.js | 12 +- .../systems/order_pending_exception.js | 25 + .../systems/order_storage_allocation.js | 1431 ++++++++++++- app/service/systems/platform.js | 156 +- app/service/systems/polo_api.js | 18 + app/service/systems/print/printData.js | 25 + app/service/systems/qimen_query.js | 192 +- app/service/systems/setting/express.js | 248 ++- .../systems/setting/expressInterface.js | 399 +++- app/service/systems/setting/platform.js | 194 +- app/service/systems/stock_store.js | 204 +- app/service/systems/storage/index.js | 105 +- app/service/systems/storage/receiving.js | 256 ++- app/service/systems/store_warehouse.js | 95 + app/service/systems/upload.js | 14 +- config/config.default.js | 1 + ...0-add-deleted-at-to-wms-express-setting.js | 63 + ...dd-weight-type-to-order-delivery-tables.js | 108 + ...ag-to-longtext-on-order-delivery-tables.js | 93 + ...ce-order-codes-to-order-delivery-tables.js | 107 + docs/file-writer.md | 3 + methods/changes/openapi.json | 63 + methods/changes/system.json | 1705 ++++++++------- methods/openapi.json | 160 ++ methods/system.json | 1884 ++++++++++++++++- .../file-writer/.write-window-counter-3.json | 2 +- .../qimen-logs-MINGREN-worker-p4496-0001.log | 2 - ...en-logs-MINGREN-worker-p4496-0001.log.done | 7 - .../qimen-logs-MINGREN-worker-p38224-0001.log | 1 - ...n-logs-MINGREN-worker-p38224-0001.log.done | 7 - .../qimen-logs-MINGREN-worker-p41276-0001.log | 4 - .../qimen-logs-MINGREN-worker-p42648-0001.log | 1 - ...n-logs-MINGREN-worker-p42648-0001.log.done | 7 - .../qimen-logs-MINGREN-worker-p35616-0001.log | 1 + temp_calculate_sign.js | 59 + temp_check_json.js | 16 +- temp_count_brackets.js | 32 +- temp_debug_headers.js | 10 +- temp_find_headers_close.js | 28 +- temp_find_missing_commas.js | 2 +- temp_find_objsep.js | 2 +- temp_find_trailing_commas.js | 2 +- temp_rebuild_system_json.js | 54 +- test/app/controller/docs.test.js | 38 + test/app/controller/openapi.test.js | 326 +++ .../system.order.namespaced.test.js | 2 + .../system.order.reviewOrder.test.js | 2 + .../system.setting.storeWarehouse.test.js | 4 + test/app/extend/application.cache.test.js | 36 + test/app/lib/api_sign.test.js | 131 ++ test/app/lib/file_writer.test.js | 87 + test/app/lib/order_delivery_selfcheck.test.js | 24 - test/app/lib/qimen_client.test.js | 92 + .../order_delivery_factory_selfcheck.test.js | 225 +- test/app/service/openapi.test.js | 300 +++ .../systemMethods/order.base.step.test.js | 5 + .../pendingOrder.allocateExpressCode.test.js | 171 ++ .../pendingOrder.allocateStorage.test.js | 165 ++ .../order/queryOrderLogs.test.js | 71 + .../order/storageAllocation.test.js | 53 +- .../systemMethods/setting/express.test.js | 57 + .../setting/expressInterface.test.js | 53 +- .../systemMethods/setting/platform.test.js | 20 +- test/app/service/systems/api_sign.test.js | 181 ++ .../systems/delivery_order.addOrder.test.js | 241 +++ .../delivery_order.auditStatus.test.js | 72 +- .../systems/express.async_dispatch.test.js | 264 +++ .../express.createWaybillCode.balance.test.js | 909 ++++++++ test/app/service/systems/express.test.js | 356 +++- .../systems/express_platform.polyapi.test.js | 429 ++++ .../operation_log.queryOrderLogs.test.js | 109 + .../systems/order_async.syncOrderIds.test.js | 905 ++++++++ .../systems/order_delivery_migration.test.js | 42 +- .../systems/order_pending_exception.test.js | 84 + .../systems/order_storage_allocation.test.js | 273 ++- test/app/service/systems/platform.test.js | 129 +- .../service/systems/setting/express.test.js | 127 +- .../systems/setting/expressInterface.test.js | 346 ++- .../service/systems/setting/platform.test.js | 77 +- ...8-1954-business_key数组语义回归测试报告.md | 40 + 126 files changed, 19463 insertions(+), 1974 deletions(-) create mode 100644 app/controller/openapi.js create mode 100644 app/lib/api_sign.js delete mode 100644 app/lib/order_delivery_selfcheck.js create mode 100644 app/lib/qimen_client.js delete mode 100644 app/model/express_platform.js create mode 100644 app/service/openapi.js create mode 100644 app/service/openapiMethods/index.js create mode 100644 app/service/openapiMethods/ping.js create mode 100644 app/service/systems/api_sign.js create mode 100644 app/service/systems/express_platform.js create mode 100644 app/service/systems/order_async.js create mode 100644 app/service/systems/print/printData.js create mode 100644 database/migrations/20260417153000-add-deleted-at-to-wms-express-setting.js create mode 100644 database/migrations/20260419102000-add-weight-type-to-order-delivery-tables.js create mode 100644 database/migrations/20260420101000-alter-order-flag-to-longtext-on-order-delivery-tables.js create mode 100644 database/migrations/20260420112000-add-source-order-codes-to-order-delivery-tables.js create mode 100644 methods/changes/openapi.json create mode 100644 methods/openapi.json delete mode 100644 runtime/file-writer/qimen-logs/2026/04/10/qimen-logs-MINGREN-worker-p4496-0001.log delete mode 100644 runtime/file-writer/qimen-logs/2026/04/10/qimen-logs-MINGREN-worker-p4496-0001.log.done delete mode 100644 runtime/file-writer/qimen-logs/2026/04/12/qimen-logs-MINGREN-worker-p38224-0001.log delete mode 100644 runtime/file-writer/qimen-logs/2026/04/12/qimen-logs-MINGREN-worker-p38224-0001.log.done delete mode 100644 runtime/file-writer/qimen-logs/2026/04/12/qimen-logs-MINGREN-worker-p41276-0001.log delete mode 100644 runtime/file-writer/qimen-logs/2026/04/12/qimen-logs-MINGREN-worker-p42648-0001.log delete mode 100644 runtime/file-writer/qimen-logs/2026/04/12/qimen-logs-MINGREN-worker-p42648-0001.log.done create mode 100644 runtime/file-writer/qimen-logs/2026/04/26/qimen-logs-MINGREN-worker-p35616-0001.log create mode 100644 temp_calculate_sign.js create mode 100644 test/app/controller/openapi.test.js create mode 100644 test/app/lib/api_sign.test.js delete mode 100644 test/app/lib/order_delivery_selfcheck.test.js create mode 100644 test/app/lib/qimen_client.test.js create mode 100644 test/app/service/openapi.test.js create mode 100644 test/app/service/systemMethods/order/pendingOrder.allocateExpressCode.test.js create mode 100644 test/app/service/systemMethods/order/pendingOrder.allocateStorage.test.js create mode 100644 test/app/service/systemMethods/order/queryOrderLogs.test.js create mode 100644 test/app/service/systems/api_sign.test.js create mode 100644 test/app/service/systems/delivery_order.addOrder.test.js create mode 100644 test/app/service/systems/express.async_dispatch.test.js create mode 100644 test/app/service/systems/express.createWaybillCode.balance.test.js create mode 100644 test/app/service/systems/express_platform.polyapi.test.js create mode 100644 test/app/service/systems/operation_log.queryOrderLogs.test.js create mode 100644 test/app/service/systems/order_async.syncOrderIds.test.js create mode 100644 test_reports/pass/20260418-1954-business_key数组语义回归测试报告.md diff --git a/.github/agents/文档.agent.md b/.github/agents/文档.agent.md index 7ca1a5e..6f37e86 100644 --- a/.github/agents/文档.agent.md +++ b/.github/agents/文档.agent.md @@ -63,6 +63,7 @@ node .\script\tmp-struct-system-params.cjs ## 推荐工作流 1. 先定位代码真实实现与调用链 +2. 在temp/apiDoc/目录下先备份对应的时间的json文档方便后续对比和回档,自动归档人工回档都在这个目录下进行 2. 如 system 入参结构变化,可先执行 `node .\script\tmp-struct-system-params.cjs` 3. 按 `docs/api-doc-update-workflow.md` 生成固定 spec JSON 4. 先执行 `npm run doc:api:update -- --spec= --dry-run` diff --git a/.github/agents/调度.agent.md b/.github/agents/调度.agent.md index c669667..82a1f3c 100644 --- a/.github/agents/调度.agent.md +++ b/.github/agents/调度.agent.md @@ -3,7 +3,7 @@ name: wms-dispatcher-agent description: "Use when the user asks about 任务委派、任务分派、调度、router、triage、多领域排障、不确定该找哪个 agent,或需要把问题分给 数据库/Redis/发布/开发/测试/文档 等模块。专用于 WMS 任务分诊与委派。" argument-hint: "描述你的目标或问题,例如:帮我判断这是数据库、测试还是缓存问题并分派、这个线上异常该交给谁处理。" tools: ['read', 'search', 'agent', 'todo'] -model: GPT-5.4 mini (copilot) +model: Claude Opus 4.6 (copilot) --- # WMS 调度代理(`wms-dispatcher-agent`) diff --git a/app.js b/app.js index 2a567d4..94f2416 100644 --- a/app.js +++ b/app.js @@ -1,7 +1,7 @@ // app.js const path = require('path'); const LocalFileWriter = require('./app/lib/file_writer'); -const ensureOrderDeliverySelfCheck = require('./app/lib/order_delivery_selfcheck'); +const QimenClient = require('./app/lib/qimen_client'); /** * 挂载应用级扩展能力。 @@ -13,8 +13,10 @@ module.exports = app => { global.APP_ROOT = path.resolve(__dirname, './'); app.appRoot = global.APP_ROOT; app.fileWriter = new LocalFileWriter(app); + app.qimenClient = new QimenClient(app); app.logger.info('✅ Application 扩展能力已加载'); app.logger.info('✅ fileWriter 已挂载到 app.fileWriter'); + app.logger.info('✅ qimenClient 已挂载到 app.qimenClient'); // 初始化工厂 app.beforeStart(async () => { const OrderDeliveryFactory = require('./app/model/order_delivery_factory'); @@ -32,7 +34,6 @@ module.exports = app => { app.OrderItemsFactory = OrderItemsFactory(app); app.model.OrderItemsFactory = app.OrderItemsFactory; app.logger.info('✅ 工厂类初始化完成'); - // await ensureOrderDeliverySelfCheck(app); } catch (error) { app.logger.error('❌ 工厂类初始化失败:', error); } diff --git a/app/controller/docs.js b/app/controller/docs.js index b0a247d..3958a9e 100644 --- a/app/controller/docs.js +++ b/app/controller/docs.js @@ -443,6 +443,28 @@ function normalizeGroups(docData) { return []; } +/** + * 解析文档对应的统一入口路径,优先使用文档内声明的 http.path。 + * @param {object} docData 文档 JSON 数据。 + * @return {string} 统一入口路径。 + */ +function resolveDocEntryPath(docData) { + const httpPath = String(docData?.http?.path || '').trim(); + if (httpPath.startsWith('/')) { + return httpPath; + } + + if (docData?.module === 'qimen') { + return '/qimen'; + } + + if (docData?.module === 'gateway') { + return '/internal/v1/gateway'; + } + + return '/system'; +} + /** * 渲染键值表格。 * @param {Array} items 数据项列表。 @@ -512,9 +534,14 @@ function renderMethodCard(item, entryPath, moduleName) { const methodName = item.method || item.name || 'unknown'; const description = item.description || ''; const isQimen = moduleName === 'qimen'; + const isOpenapi = moduleName === 'openapi'; const queryHint = isQimen ? 'app_key=xxx&method=...&v=2.0&format=json&sign_method=md5&sign=xxx×tamp=1700000000' - : `method=${methodName}&v=1.0×tamp=1700000000`; + : isOpenapi + ? `app_key=&method=${methodName}&v=1.0×tamp=1700000000` + : `method=${methodName}&v=1.0×tamp=1700000000`; + const queryLabel = isOpenapi ? 'Query 参数(自动生成)' : 'Query 参数'; + const queryReadonlyAttr = isOpenapi ? ' readonly data-auto-generated="true" aria-label="自动生成"' : ''; return `
    @@ -584,8 +611,13 @@ function renderMethodCard(item, entryPath, moduleName) {
    在线调试
    - - + + + + ${isOpenapi ? ` + + + ` : ''} @@ -1043,8 +1075,11 @@ function renderHtmlPage({ + +`; + } +} + +module.exports = OpenapiCallbackController; diff --git a/app/dict/businessDict.js b/app/dict/businessDict.js index 4fb637f..43fa09c 100644 --- a/app/dict/businessDict.js +++ b/app/dict/businessDict.js @@ -135,6 +135,7 @@ module.exports = { STORE_CREATE: '创建货主', STORE_CREATE_WAREHOUSE: '创建仓库', STORE_SIGN: '签约货主', + STORE_OPEN_ACCOUNT: '仓库代开户', STORE_RENAME: '修改签约备注', STORE_UNBIND: '解绑签约', STORE_SAVE_POLICY_CONFIG: '保存签约策略配置', diff --git a/app/lib/express_print_payload_builder.js b/app/lib/express_print_payload_builder.js index 9b12989..e630ac8 100644 --- a/app/lib/express_print_payload_builder.js +++ b/app/lib/express_print_payload_builder.js @@ -97,6 +97,7 @@ class ExpressPrintPayloadBuilder { buildPayload(options = {}) { const requestOptions = isPlainObject(options) ? options : {}; const platform = String(requestOptions.platform || '').trim(); + const normalizedPlatform = this.normalizePlatform(platform); if (!platform) { throw new Error('快递打印缺少平台标识'); } @@ -117,19 +118,58 @@ class ExpressPrintPayloadBuilder { } const payload = this.loadTemplate(platform); - if (!isPlainObject(payload.task)) { - payload.task = {}; - } const requestId = idGenerator.nextRequestId(); this.applyRequestId(payload, requestId); - payload.task.taskID = idGenerator.nextTaskId(); - payload.task.printer = printerName; - payload.task.documents = this.buildDocumentsFromOrders(orders, idGenerator); + payload.printer = printerName; + + if (Array.isArray(payload.taskList)) { + payload.taskList.forEach(item => { + if (isPlainObject(item)) { + item.printer = printerName; + } + }); + } + + if (normalizedPlatform === 'sph') { + this.applySphTaskDynamicFields(payload, orders); + } else { + if (!isPlainObject(payload.task)) { + payload.task = {}; + } + payload.task.taskID = idGenerator.nextTaskId(); + payload.task.printer = printerName; + payload.task.documents = this.buildDocumentsFromOrders(orders, idGenerator); + } + + if (normalizedPlatform === 'jd') { + this.mergeJdParametersContents(payload, printerName); + } return payload; } + /** + * 将京东平台模板参数中的 contents 替换为订单实际内容。 + * @param {Object} payload 打印请求 payload。 + * @param {string} printerName 打印机名称。 + */ + mergeJdParametersContents(payload, printerName) { + if (!isPlainObject(payload.parameters)) { + payload.parameters = {}; + } + + payload.parameters.printName = printerName; + + const documents = Array.isArray(payload.task && payload.task.documents) ? payload.task.documents : []; + payload.parameters.contents = documents.map(document => { + if (!isPlainObject(document) || !Array.isArray(document.contents) || !document.contents[0]) { + return {}; + } + return deepClone(document.contents[0]); + }); + } + /** * 将 orders 映射为 documents。 * @param {Array} orders 订单数组。 @@ -148,6 +188,91 @@ class ExpressPrintPayloadBuilder { }); } + /** + * 将 SPH 订单中的动态业务字段回填到模板 taskList[0]。 + * + * 仅覆盖动态字段,避免改写模板固定结构。 + * + * @param {Object} payload 打印请求 payload。 + * @param {Array} orders 外部传入的订单打印数据数组。 + */ + applySphTaskDynamicFields(payload, orders) { + if (!Array.isArray(payload.taskList) || !isPlainObject(payload.taskList[0])) { + return; + } + + const sourceTask = this.resolveSphTaskFromOrders(orders); + if (!isPlainObject(sourceTask)) { + return; + } + + const targetTask = payload.taskList[0]; + const dynamicFields = [ + 'printInfo', + 'printNum', + 'splitControl', + 'showDeliveryLogo', + 'customInfo', + 'extendData', + 'taskID', + ]; + + dynamicFields.forEach(field => { + if (Object.prototype.hasOwnProperty.call(sourceTask, field)) { + targetTask[field] = deepClone(sourceTask[field]); + } + }); + } + + /** + * 从首个订单提取 SPH 动态任务数据。 + * + * 优先读取标准 taskList[0];若上游直接传 task 结构(printInfo/printNum 等)也兼容。 + * + * @param {Array} orders 外部传入的订单打印数据数组。 + * @return {Object|null} SPH 动态任务对象。 + */ + resolveSphTaskFromOrders(orders) { + if (!Array.isArray(orders) || orders.length === 0) { + return null; + } + + const firstOrder = isPlainObject(orders[0]) ? orders[0] : {}; + const candidates = []; + if (isPlainObject(firstOrder.print_data)) { + candidates.push(firstOrder.print_data); + } + if (isPlainObject(firstOrder)) { + candidates.push(firstOrder); + } + + const sphDynamicFields = [ + 'printInfo', + 'printNum', + 'splitControl', + 'showDeliveryLogo', + 'customInfo', + 'extendData', + 'taskID', + ]; + + for (const candidate of candidates) { + if (Array.isArray(candidate.taskList) && isPlainObject(candidate.taskList[0])) { + return candidate.taskList[0]; + } + + if (isPlainObject(candidate.taskList)) { + return candidate.taskList; + } + + if (sphDynamicFields.some(field => Object.prototype.hasOwnProperty.call(candidate, field))) { + return candidate; + } + } + + return null; + } + /** * 解析单个订单对应的 document。 * @param {Object} order 订单对象。 diff --git a/app/lib/printer_data_builder.js b/app/lib/printer_data_builder.js index c91c5ff..f6a373e 100644 --- a/app/lib/printer_data_builder.js +++ b/app/lib/printer_data_builder.js @@ -92,6 +92,11 @@ const LINE_BREAK_MAP = Object.freeze({ * @type {string} */ const DEFAULT_PDD_CUSTOM_TEMPLATE_URL = 'http://www.ye4s.com/mb/pdd.xml'; +/** + * 小红书自定义区默认模板地址。 + * @type {string} + */ +const DEFAULT_XHS_CUSTOM_TEMPLATE_URL = 'https://cloudprint.xiaohongshu.com/template/standard/7/2'; const WAYBILL_CUSTOM_DISPLAY_FIELD = 'waybill_custom_display_type'; const WAYBILL_CUSTOM_DISPLAY_TYPES = Object.freeze({ HIDE: '1', @@ -969,6 +974,30 @@ function resolveCainiaoMainTemplateURL(orderExpress) { return toTrimmedString(safeOrderExpress.cainiao_template_url); } +/** + * 解析拼多多主面单模板地址。 + * + * @param {Object} orderExpress 快递单对象。 + * @return {string} 拼多多主面单模板地址。 + */ +function resolvePddMainTemplateURL(orderExpress) { + const safeOrderExpress = isPlainObject(orderExpress) ? orderExpress : {}; + return toTrimmedString(safeOrderExpress.pdd_template_url); +} + +/** + * 解析抖音主面单模板地址。 + * + * 兼容 dy 与 douyin 两种字段命名,优先读取 dy_template_url。 + * + * @param {Object} orderExpress 快递单对象。 + * @return {string} 抖音主面单模板地址。 + */ +function resolveDouyinMainTemplateURL(orderExpress) { + const safeOrderExpress = isPlainObject(orderExpress) ? orderExpress : {}; + return toTrimmedString(safeOrderExpress.dy_template_url || safeOrderExpress.douyin_template_url); +} + /** * 当菜鸟 printinfo 缺失或无效时,仅基于模板骨架构建最小主面单 data。 * @@ -1348,6 +1377,7 @@ function applyPddExpressFieldMapping(platform, skeleton, orderExpress, orderDeli const signature = toTrimmedString(safeOrderExpress.signature); const version = toTrimmedString(safeOrderExpress.ver); const waybillCode = toTrimmedString(safeOrderExpress.waybill_code); + const pddMainTemplateURL = resolvePddMainTemplateURL(safeOrderExpress); const safeOrderDelivery = isPlainObject(orderDelivery) ? orderDelivery : {}; const composeItems = resolveCustomComposeItems(safeOrderExpress, safeOrderDelivery); const customProductInfoLines = buildWaybillCustomProductInfoLines( @@ -1426,6 +1456,13 @@ function applyPddExpressFieldMapping(platform, skeleton, orderExpress, orderDeli document.contents = []; } + if (!isPlainObject(document.contents[0])) { + document.contents[0] = {}; + } + if (pddMainTemplateURL) { + document.contents[0].templateURL = pddMainTemplateURL; + } + for (const content of document.contents) { if (!isPlainObject(content)) { continue; @@ -1465,6 +1502,152 @@ function applyPddExpressFieldMapping(platform, skeleton, orderExpress, orderDeli } } +/** + * 获取抖音 params(从预取的 dy_params 字段读取)。 + * + * @param {Object} orderExpress 快递单对象。 + * @return {string} params 字符串。 + */ +// eslint-disable-next-line no-unused-vars +function resolveDouyinParams(orderExpress) { + const safeOrderExpress = isPlainObject(orderExpress) ? orderExpress : {}; + return toTrimmedString(safeOrderExpress.dy_params) || ''; +} + +/** + * 抖音平台主面单模板地址、密文、发件人地址与自定义区字段回填。 + * + * 规则: + * - wms_order_express.signature -> signature(签名) + * - wms_order_express.encryptprintinfo -> encryptedData(加密面单数据) + * - params 不赋值,保留模板占位符(由上游平台适配器另算) + * - wms_order_express.dy_template_url / douyin_template_url -> templateURL + * - 发件人地址优先从 policyConfig 读取(province_name / city_name / district_name / sender_address), + * 其次从 orderDelivery 读取;countryCode 固定为 CHN + * - 自定义区(contents[1])根据拣货信息填充 productInfo + * + * 仅在平台为 douyin 时生效。 + * + * @param {string} platform 归一化平台编码。 + * @param {Object} skeleton 打印请求骨架。 + * @param {Object} orderExpress 快递单对象。 + * @param {Object} orderDelivery 订单对象。 + * @param {Object} policyConfig 策略配置对象。 + */ +function applyDouyinExpressFieldMapping(platform, skeleton, orderExpress, orderDelivery, policyConfig) { + if (platform !== 'douyin') { + return; + } + + const safeSkeleton = isPlainObject(skeleton) ? skeleton : {}; + const safeOrderExpress = isPlainObject(orderExpress) ? orderExpress : {}; + const safeOrderDelivery = isPlainObject(orderDelivery) ? orderDelivery : {}; + const safePolicyConfig = isPlainObject(policyConfig) ? policyConfig : {}; + const douyinMainTemplateURL = resolveDouyinMainTemplateURL(safeOrderExpress); + + const documents = safeSkeleton.task && Array.isArray(safeSkeleton.task.documents) + ? safeSkeleton.task.documents + : []; + if (documents.length === 0) { + return; + } + + // 密文回填 + const encryptPrintinfo = toTrimmedString(safeOrderExpress.encryptprintinfo); + const signature = toTrimmedString(safeOrderExpress.signature); + + // 发件人信息 — 优先从 policyConfig 读取,其次从 orderDelivery + const senderName = toTrimmedString(safePolicyConfig.sender_name); + const senderTel = toTrimmedString(safePolicyConfig.sender_tel); + const senderProvince = toTrimmedString(safePolicyConfig.province_name || safeOrderDelivery.province_name); + const senderCity = toTrimmedString(safePolicyConfig.city_name || safeOrderDelivery.city_name); + const senderDistrict = toTrimmedString(safePolicyConfig.district_name || safeOrderDelivery.district_name); + const senderAddress = toTrimmedString(safePolicyConfig.sender_address || safePolicyConfig.address); + + // 自定义区拣货信息 + const composeItems = resolveCustomComposeItems(safeOrderExpress, safeOrderDelivery); + const customProductInfoLines = buildWaybillCustomProductInfoLines( + composeItems, + safePolicyConfig, + { + waveNo: toTrimmedString(safeOrderDelivery.wave_no), + wave_total_orders: Number(safeOrderDelivery.wave_total_orders || 0), + wave_index: Number(safeOrderDelivery.wave_index || 0), + platforms_index: Number(safeOrderDelivery.platforms_index || 0), + expressInterfaceName: toTrimmedString( + safeOrderExpress.logistics_interface_name + || safeOrderExpress.logistics_name + || safeOrderDelivery.logistics_interface_name + || safeOrderDelivery.logistics_name + ), + fallbackTotalQty: Number(safeOrderDelivery.items_count || safeOrderDelivery.items_total || 0), + } + ); + const customProductInfo = mergeWaybillCustomLines(customProductInfoLines, { lineBreak: '\n' }); + + for (const document of documents) { + if (!isPlainObject(document)) { + continue; + } + + if (!Array.isArray(document.contents)) { + document.contents = []; + } + + const contents = document.contents; + + // 主面单(contents[0])回填 + const mainContent = contents[0]; + if (isPlainObject(mainContent)) { + if (douyinMainTemplateURL) { + mainContent.templateURL = douyinMainTemplateURL; + } + if (encryptPrintinfo) { + mainContent.encryptedData = encryptPrintinfo; + } + if (signature) { + mainContent.signature = signature; + } + + // senderInfo + mainContent.addData = isPlainObject(mainContent.addData) ? mainContent.addData : {}; + mainContent.addData.senderInfo = isPlainObject(mainContent.addData.senderInfo) + ? mainContent.addData.senderInfo : {}; + if (senderName) { + mainContent.addData.senderInfo.contact = isPlainObject(mainContent.addData.senderInfo.contact) + ? mainContent.addData.senderInfo.contact : {}; + mainContent.addData.senderInfo.contact.name = senderName; + } + if (senderTel) { + mainContent.addData.senderInfo.contact = isPlainObject(mainContent.addData.senderInfo.contact) + ? mainContent.addData.senderInfo.contact : {}; + mainContent.addData.senderInfo.contact.mobile = senderTel; + } + mainContent.addData.senderInfo.address = isPlainObject(mainContent.addData.senderInfo.address) + ? mainContent.addData.senderInfo.address : {}; + if (senderProvince) mainContent.addData.senderInfo.address.provinceName = senderProvince; + if (senderCity) mainContent.addData.senderInfo.address.cityName = senderCity; + if (senderDistrict) mainContent.addData.senderInfo.address.districtName = senderDistrict; + if (senderAddress) mainContent.addData.senderInfo.address.detailAddress = senderAddress; + mainContent.addData.senderInfo.address.countryCode = 'CHN'; + + // params 占位实现 — 调试:无条件覆盖 + mainContent.params = resolveDouyinParams(safeOrderExpress); + } + + // 自定义区 — 模板构建时 contents 被 buildArraySkeleton 截断为 1 个元素,需手动重建 + if (contents.length < 2) { + contents.push({}); + } + const customContent = contents[1]; + if (!toTrimmedString(customContent.templateURL)) { + customContent.templateURL = 'http://www.ye4s.com/mb/douyin1.xml'; + } + customContent.data = isPlainObject(customContent.data) ? customContent.data : {}; + customContent.data.productInfo = customProductInfo || '无拣货信息'; + } +} + /** * 菜鸟平台主面单与自定义区字段回填。 * @@ -1612,6 +1795,403 @@ function applyCainiaoExpressFieldMapping( } } +/** + * 解析小红书主面单 content。 + * + * 支持 printinfo 为 JSON 字符串或对象,并兼容以下包装结构: + * - contents[0] + * - documents[0].contents[0] + * - task.documents[0].contents[0] + * + * 若不命中包装结构,则回退为 printinfo 顶层对象本身。 + * + * @param {any} printinfo 原始 printinfo。 + * @param {string[]} [warnings=[]] 风险提示列表。 + * @return {Object|null} 主面单 content;无法解析返回 null。 + */ +function resolveXhsMainContentFromPrintinfo(printinfo, warnings = []) { + const safeWarnings = Array.isArray(warnings) ? warnings : []; + let payload = printinfo; + + if (typeof payload === 'string') { + const text = payload.trim(); + if (!text) { + return null; + } + + try { + payload = JSON.parse(text); + } catch (error) { + safeWarnings.push('小红书 printinfo JSON 解析失败,已回退模板骨架'); + return null; + } + } + + if (!isPlainObject(payload)) { + return null; + } + + if (!payload) { + return null; + } + + const wrapperCandidates = [ + payload.contents && payload.contents[0], + payload.documents && payload.documents[0] && payload.documents[0].contents && payload.documents[0].contents[0], + payload.task + && payload.task.documents + && payload.task.documents[0] + && payload.task.documents[0].contents + && payload.task.documents[0].contents[0], + ]; + + for (const candidate of wrapperCandidates) { + if (isPlainObject(candidate)) { + return cloneStructuredValue(candidate); + } + } + + return cloneStructuredValue(payload); +} + +/** + * 小红书平台主面单与自定义区字段回填。 + * + * 规则: + * - 主面单 contents[0] 直接使用 wms_order_express.printinfo(支持字符串/对象及包装结构) + * - 自定义区按模板结构处理,仅填充 contents[1].data.order[0] + * + * 仅在平台为 xhs 时生效。 + * + * @param {string} platform 归一化平台编码。 + * @param {Object} skeleton 打印请求骨架。 + * @param {Object} orderExpress 快递单对象。 + * @param {Object} orderDelivery 订单对象。 + * @param {Object} policyConfig 策略配置对象。 + * @param {string[]} warnings 风险提示列表。 + */ +function applyXhsExpressFieldMapping( + platform, + skeleton, + orderExpress, + orderDelivery, + policyConfig, + warnings +) { + if (platform !== 'xhs') { + return; + } + + const safeSkeleton = isPlainObject(skeleton) ? skeleton : {}; + const safeOrderExpress = isPlainObject(orderExpress) ? orderExpress : {}; + const safeOrderDelivery = isPlainObject(orderDelivery) ? orderDelivery : {}; + const safePolicyConfig = isPlainObject(policyConfig) ? policyConfig : {}; + const safeWarnings = Array.isArray(warnings) ? warnings : []; + const documents = safeSkeleton.task && Array.isArray(safeSkeleton.task.documents) + ? safeSkeleton.task.documents + : []; + + if (documents.length === 0) { + return; + } + + const xhsMainContent = resolveXhsMainContentFromPrintinfo(safeOrderExpress.printinfo, safeWarnings); + const hasXhsMainContent = isPlainObject(xhsMainContent); + const composeItems = resolveCustomComposeItems(safeOrderExpress, safeOrderDelivery); + const customProductInfoLines = buildWaybillCustomProductInfoLines( + composeItems, + safePolicyConfig, + { + waveNo: toTrimmedString(safeOrderDelivery.wave_no), + wave_total_orders: Number(safeOrderDelivery.wave_total_orders || 0), + wave_index: Number(safeOrderDelivery.wave_index || 0), + platforms_index: Number(safeOrderDelivery.platforms_index || 0), + expressInterfaceName: toTrimmedString( + safeOrderExpress.logistics_interface_name + || safeOrderExpress.logistics_name + || safeOrderDelivery.logistics_interface_name + || safeOrderDelivery.logistics_name + ), + fallbackTotalQty: Number(safeOrderDelivery.items_count || safeOrderDelivery.items_total || 0), + } + ); + const customProductInfo = mergeWaybillCustomLines(customProductInfoLines, { + lineBreak: LINE_BREAK_MAP.LF, + }); + + for (const document of documents) { + if (!isPlainObject(document)) { + continue; + } + + if (!Array.isArray(document.contents)) { + document.contents = []; + } + + const contents = document.contents; + + if (hasXhsMainContent) { + contents[0] = cloneStructuredValue(xhsMainContent); + } + + if (!isPlainObject(contents[1])) { + contents[1] = {}; + } + + const customContent = contents[1]; + if (!toTrimmedString(customContent.templateURL)) { + customContent.templateURL = DEFAULT_XHS_CUSTOM_TEMPLATE_URL; + } + customContent.data = isPlainObject(customContent.data) ? customContent.data : {}; + customContent.data.order = Array.isArray(customContent.data.order) ? customContent.data.order : []; + customContent.data.order[0] = customProductInfo; + } +} + +/** + * 视频号平台 taskList 字段回填。 + * + * 规则: + * - 仅在平台为 sph 时生效 + * - 基于 skeleton.taskList[0] 回填,不改模板默认的结构控制字段 + * - taskList[0].printInfo 使用 order_express.printinfo(非空时) + * - taskList[0].printNum.sumNum 使用 wave_total_orders,curNum 保持模板值,缺失时默认 1 + * - taskList[0].customInfo.data.description 使用现有商品汇总文本并按
    拼接 + * - taskList[0].extendData.sender 使用 policy_config 发件人信息 + * - taskList[0].taskID 优先沿用 buildPlatformRequestSkeleton 现有 taskId + * + * @param {string} platform 归一化平台编码。 + * @param {Object} skeleton 打印请求骨架。 + * @param {Object} orderExpress 快递单对象。 + * @param {Object} orderDelivery 订单对象。 + * @param {Object} policyConfig 策略配置对象。 + */ +function applySphExpressFieldMapping( + platform, + skeleton, + orderExpress, + orderDelivery, + policyConfig +) { + if (platform !== 'sph') { + return; + } + + const safeSkeleton = isPlainObject(skeleton) ? skeleton : {}; + const safeOrderExpress = isPlainObject(orderExpress) ? orderExpress : {}; + const safeOrderDelivery = isPlainObject(orderDelivery) ? orderDelivery : {}; + const safePolicyConfig = isPlainObject(policyConfig) ? policyConfig : {}; + const taskList = Array.isArray(safeSkeleton.taskList) ? safeSkeleton.taskList : []; + if (!isPlainObject(taskList[0])) { + return; + } + + const task = taskList[0]; + const printinfo = toTrimmedString(safeOrderExpress.printinfo); + if (printinfo) { + task.printInfo = printinfo; + } + + task.printNum = isPlainObject(task.printNum) ? task.printNum : {}; + const currentCurNum = toNumber(task.printNum.curNum, 0); + task.printNum.curNum = currentCurNum > 0 ? currentCurNum : 1; + task.printNum.sumNum = toNumber( + safeOrderDelivery.wave_total_orders, + toNumber(task.printNum.sumNum, 0) + ); + + const composeItems = resolveCustomComposeItems(safeOrderExpress, safeOrderDelivery); + const customProductInfoLines = buildWaybillCustomProductInfoLines( + composeItems, + safePolicyConfig, + { + waveNo: toTrimmedString(safeOrderDelivery.wave_no), + wave_total_orders: Number(safeOrderDelivery.wave_total_orders || 0), + wave_index: Number(safeOrderDelivery.wave_index || 0), + platforms_index: Number(safeOrderDelivery.platforms_index || 0), + expressInterfaceName: toTrimmedString( + safeOrderExpress.logistics_interface_name + || safeOrderExpress.logistics_name + || safeOrderDelivery.logistics_interface_name + || safeOrderDelivery.logistics_name + ), + fallbackTotalQty: Number(safeOrderDelivery.items_count || safeOrderDelivery.items_total || 0), + } + ); + const customProductInfo = mergeWaybillCustomLines(customProductInfoLines, { + lineBreak: LINE_BREAK_MAP.LF, + }).replace(/\n/g, '
    '); + + task.customInfo = isPlainObject(task.customInfo) ? task.customInfo : {}; + task.customInfo.data = isPlainObject(task.customInfo.data) ? task.customInfo.data : {}; + task.customInfo.data.description = customProductInfo; + + task.extendData = isPlainObject(task.extendData) ? task.extendData : {}; + task.extendData.sender = isPlainObject(task.extendData.sender) ? task.extendData.sender : {}; + task.extendData.sender.address = isPlainObject(task.extendData.sender.address) + ? task.extendData.sender.address + : {}; + task.extendData.sender.address.provinceName = toTrimmedString(safePolicyConfig.province_name); + task.extendData.sender.address.cityName = toTrimmedString(safePolicyConfig.city_name); + task.extendData.sender.address.countyName = toTrimmedString(safePolicyConfig.district_name); + task.extendData.sender.address.detailInfo = toTrimmedString(safePolicyConfig.address); + task.extendData.sender.userName = toTrimmedString(safePolicyConfig.sender_name); + task.extendData.sender.telNumber = toTrimmedString(safePolicyConfig.sender_tel); + + const existingTaskId = toTrimmedString(safeSkeleton.task && safeSkeleton.task.taskID); + if (existingTaskId) { + task.taskID = existingTaskId; + } +} + +/** + * 从京东模板样例中提取主面单 content 原型。 + * + * 优先使用 input.template_sample.parameters.contents[0], + * 缺失时回退为 {},避免影响骨架构建流程。 + * + * @param {Object} templateSample 模板样例对象。 + * @return {Object} 主面单 content 原型。 + */ +function resolveJdTemplateContentPrototype(templateSample) { + const sample = isPlainObject(templateSample) ? templateSample : {}; + + if (!isPlainObject(sample.parameters) || !Array.isArray(sample.parameters.contents)) { + return {}; + } + + const firstContent = sample.parameters.contents[0]; + return isPlainObject(firstContent) ? cloneStructuredValue(firstContent) : {}; +} + +/** + * 读取京东主模板地址。 + * + * @param {Object} orderExpress 快递单对象。 + * @return {string} 京东主模板地址。 + */ +function resolveJdTemplateUrlFromOrderExpress(orderExpress) { + const safeOrderExpress = isPlainObject(orderExpress) ? orderExpress : {}; + return toTrimmedString(safeOrderExpress.jd_template_url); +} + +/** + * 京东平台主面单字段回填。 + * + * 规则: + * - 仅在平台为 jd 时生效 + * - 主面单原型来源于 template_sample.parameters.contents[0] + * - 保证 skeleton.task.documents[0] 存在并回填 documentID、contents[0] + * - order_express.printinfo 回填 contents[0].printData + * - policy_config 发件人信息回填到 contents[0].addData.sender + * - 自定义区商品信息写入 contents[0].customData.GoodsInfo + * + * @param {string} platform 归一化平台编码。 + * @param {Object} skeleton 打印请求骨架。 + * @param {Object} orderExpress 快递单对象。 + * @param {Object} orderDelivery 订单对象。 + * @param {Object} policyConfig 策略配置对象。 + * @param {Object} templateSample 模板样例对象。 + * @param {string[]} warnings 风险提示列表。 + */ +function applyJdExpressFieldMapping( + platform, + skeleton, + orderExpress, + orderDelivery, + policyConfig, + templateSample, + warnings +) { + if (platform !== 'jd') { + return; + } + + const safeSkeleton = isPlainObject(skeleton) ? skeleton : {}; + const safeOrderExpress = isPlainObject(orderExpress) ? orderExpress : {}; + const safeOrderDelivery = isPlainObject(orderDelivery) ? orderDelivery : {}; + const safePolicyConfig = isPlainObject(policyConfig) ? policyConfig : {}; + const safeWarnings = Array.isArray(warnings) ? warnings : []; + const contentPrototype = resolveJdTemplateContentPrototype(templateSample); + + safeSkeleton.task = isPlainObject(safeSkeleton.task) ? safeSkeleton.task : {}; + safeSkeleton.task.documents = Array.isArray(safeSkeleton.task.documents) + ? safeSkeleton.task.documents + : []; + + if (!isPlainObject(safeSkeleton.task.documents[0])) { + if (safeSkeleton.task.documents.length === 0) { + safeSkeleton.task.documents.push({}); + } else { + safeSkeleton.task.documents[0] = {}; + } + } + + const document = safeSkeleton.task.documents[0]; + const waybillCode = toTrimmedString(safeOrderExpress.waybill_code); + if (waybillCode) { + document.documentID = waybillCode; + } + + document.contents = Array.isArray(document.contents) ? document.contents : []; + document.contents[0] = cloneStructuredValue(contentPrototype); + + const content = isPlainObject(document.contents[0]) ? document.contents[0] : {}; + document.contents[0] = content; + + const jdTemplateUrl = resolveJdTemplateUrlFromOrderExpress(safeOrderExpress); + if (jdTemplateUrl) { + content.tempUrl = jdTemplateUrl; + } + + const printinfo = toTrimmedString(safeOrderExpress.printinfo); + if (printinfo) { + content.printData = printinfo; + } else { + safeWarnings.push('京东 printinfo 为空,已保留模板 printData 默认值'); + } + + const senderAddress = [ + toTrimmedString(safePolicyConfig.province_name), + toTrimmedString(safePolicyConfig.city_name), + toTrimmedString(safePolicyConfig.district_name), + toTrimmedString(safePolicyConfig.town_name), + toTrimmedString(safePolicyConfig.address), + ].filter(Boolean).join(''); + + content.addData = isPlainObject(content.addData) ? content.addData : {}; + content.addData.sender = isPlainObject(content.addData.sender) ? content.addData.sender : {}; + content.addData.sender.name = toTrimmedString(safePolicyConfig.sender_name); + content.addData.sender.mobile = toTrimmedString(safePolicyConfig.sender_tel); + content.addData.sender.address = senderAddress; + + const composeItems = resolveCustomComposeItems(safeOrderExpress, safeOrderDelivery); + const customProductInfoLines = buildWaybillCustomProductInfoLines( + composeItems, + safePolicyConfig, + { + waveNo: toTrimmedString(safeOrderDelivery.wave_no), + wave_total_orders: Number(safeOrderDelivery.wave_total_orders || 0), + wave_index: Number(safeOrderDelivery.wave_index || 0), + platforms_index: Number(safeOrderDelivery.platforms_index || 0), + expressInterfaceName: toTrimmedString( + safeOrderExpress.logistics_interface_name + || safeOrderExpress.logistics_name + || safeOrderDelivery.logistics_interface_name + || safeOrderDelivery.logistics_name + ), + fallbackTotalQty: Number(safeOrderDelivery.items_count || safeOrderDelivery.items_total || 0), + } + ); + const customProductInfo = mergeWaybillCustomLines(customProductInfoLines, { + lineBreak: LINE_BREAK_MAP.LF, + trailingLineBreak: true, + }); + + content.customData = isPlainObject(content.customData) ? content.customData : {}; + content.customData.GoodsInfo = customProductInfo; +} + /** * 构建平台请求骨架。 * @param {Object} input 输入对象。 @@ -1737,6 +2317,41 @@ function buildPlatformRequestSkeleton(input = {}) { policyConfig ); + applyDouyinExpressFieldMapping( + normalized.platform, + skeleton, + orderExpressForCompose, + orderDeliveryForCompose, + policyConfig + ); + + applyJdExpressFieldMapping( + normalized.platform, + skeleton, + orderExpressForCompose, + orderDeliveryForCompose, + policyConfig, + templateSample, + warnings + ); + + applyXhsExpressFieldMapping( + normalized.platform, + skeleton, + orderExpressForCompose, + orderDeliveryForCompose, + policyConfig, + warnings + ); + + applySphExpressFieldMapping( + normalized.platform, + skeleton, + orderExpressForCompose, + orderDeliveryForCompose, + policyConfig + ); + return { platform: normalized.platform, platform_meta: normalized.meta, diff --git a/app/model/express_interface.js b/app/model/express_interface.js index 85a4ed7..f9dd3fe 100644 --- a/app/model/express_interface.js +++ b/app/model/express_interface.js @@ -51,6 +51,31 @@ module.exports = app => { allowNull: true, comment: '平台店铺ID', }, + template_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '模板ID', + }, + paymode: { + type: INTEGER(11), + allowNull: true, + comment: '付款方式', + }, + brandno: { + type: STRING(255), + allowNull: true, + comment: '品牌编码', + }, + providertype: { + type: STRING(50), + allowNull: true, + comment: '服务商类型编码', + }, + providerid: { + type: INTEGER(11), + allowNull: true, + comment: '服务商ID', + }, sender_name: { type: STRING(50), allowNull: true, diff --git a/app/model/order_delivery.js b/app/model/order_delivery.js index 88ed64d..539d653 100644 --- a/app/model/order_delivery.js +++ b/app/model/order_delivery.js @@ -2,7 +2,7 @@ module.exports = app => { const { Sequelize, model } = app; - const { STRING, BIGINT, DECIMAL, TEXT, ENUM, DATE, INTEGER, CHAR, SMALLINT } = Sequelize; + const { STRING, BIGINT, DECIMAL, TEXT, ENUM, DATE, INTEGER, CHAR, SMALLINT, JSON } = Sequelize; // 状态机枚举定义 const StatusEnum = { @@ -66,6 +66,11 @@ module.exports = app => { allowNull: true, comment: '订单标记', }, + extend_props: { + type: JSON, + allowNull: true, + comment: '订单扩展属性', + }, source_platform_code: { type: STRING(50), allowNull: true, diff --git a/app/model/order_items_factory.js b/app/model/order_items_factory.js index 372f340..a370b87 100644 --- a/app/model/order_items_factory.js +++ b/app/model/order_items_factory.js @@ -185,7 +185,7 @@ module.exports = app => { try { const DynamicModel = this.buildDynamicModel(warehouseId, type, tableName); - // await this.ensureManagedTableSchema(tableName, type, warehouseId, DynamicModel); + await this.ensureManagedTableSchema(tableName, type, warehouseId, DynamicModel); // 复制关联关系 this.copyAssociations(this.app.model.OrderItems, DynamicModel); @@ -267,9 +267,8 @@ module.exports = app => { const mainModel = this.app.model.OrderItems; const attributes = cloneAttributes(mainModel && mainModel.rawAttributes); - if (attributes.id) { - delete attributes.id.autoIncrement; - } + // 保留 id 字段的 autoIncrement,与 order_delivery_factory 行为一致, + // 确保分表 wms_order_items_{warehouseId} 的 bulkCreate 能正常自增生成 id if (type === 'history' && !attributes.archive_time) { attributes.archive_time = { diff --git a/app/router.js b/app/router.js index c4f6a81..a557b37 100644 --- a/app/router.js +++ b/app/router.js @@ -17,15 +17,29 @@ module.exports = app => { // 系统接口 PDA/WEB 统一入口 router.post('/system', controller.home.system); - // 独立 docs 目录挂载 - router.get('/docs', controller.docs.docsIndex); - router.get('/docs/:relPath(.*)', controller.docs.docsFile); - // api文档相关 - router.get('/api/docs', controller.docs.list); - router.get('/api/docs/:docName/raw', controller.docs.raw); - router.get('/api/docs/:docName/changes', controller.docs.changes); - router.get('/api/docs/:docName', controller.docs.detail); + // 仅开发环境可访问的内部api文档 + if (app.config.env === 'local') { + // api文档相关 + router.get('/api/docs', controller.docs.list); + router.get('/api/docs/:docName/raw', controller.docs.raw); + router.get('/api/docs/:docName/changes', controller.docs.changes); + router.get('/api/docs/:docName', controller.docs.detail); + + // 独立 docs 目录挂载 — 首页 + router.get('/docs', controller.docs.docsIndex); + } + + // OpenAPI 文档 — 所有环境均可访问,必须在通配路由之前注册 + router.get('/docs/api/openapi', controller.docs.openapi); + + // OpenAPI 回调测试 — 所有环境均可访问的独立调试页面 + router.get('/docs/api/openapi/callback-test', controller.openapiCallback.testPage); + + // 仅开发环境可访问的 docs 通配路由(静态文件),必须在 /docs/api/openapi 之后注册 + if (app.config.env === 'local') { + router.get('/docs/:relPath(.*)', controller.docs.docsFile); + } // OpenAPI 入口 router.post('/openapi', controller.openapi.index); diff --git a/app/service/openapi.js b/app/service/openapi.js index 74fe38e..09cbf7f 100644 --- a/app/service/openapi.js +++ b/app/service/openapi.js @@ -180,6 +180,19 @@ class OpenapiService extends Service { }; } + // 时间戳时效校验(±10分钟) + const nowTs = Math.floor(Date.now() / 1000); + const reqTs = Number(query.timestamp); + if (!Number.isFinite(reqTs) || Math.abs(nowTs - reqTs) > 600) { + return { + ok: false, + httpStatus: 400, + code: 400, + message: `时间戳已过期或无效,服务器时间: ${nowTs}`, + data: null, + }; + } + const body = await this.parseJsonBody(); if (body && body.ok === false) { return body; diff --git a/app/service/openapi/callback.js b/app/service/openapi/callback.js new file mode 100644 index 0000000..e9b2995 --- /dev/null +++ b/app/service/openapi/callback.js @@ -0,0 +1,225 @@ +'use strict'; + +const Service = require('egg').Service; +const { signRequest } = require('../../lib/api_sign'); + +/** @type {number} 最大重试次数 */ +const MAX_RETRY = 3; + +/** @type {number[]} 递增重试延迟(毫秒) */ +const RETRY_DELAY_MS = [2000, 5000, 15000]; + +/** + * OpenAPI 统一回调通知服务。 + * 将订单状态变更等事件通过签名鉴权回调到外部 callback_url, + * 支持自动重试与日志记录。 + */ +class OpenapiCallbackService extends Service { + + /** + * 计算回调签名(与 OpenAPI 入口签名算法完全一致)。 + * @param {Object} options 签名参数。 + * @param {string} options.event 事件名,如 order_completed。 + * @param {string} options.appKey 应用 app_key。 + * @param {string} options.selfAppSecret 应用密钥。 + * @param {Object} options.body 回调请求体数据。 + * @param {string} options.timestamp 毫秒时间戳。 + * @return {{ canonicalQuery: string, bodySign: string, sign: string }} 签名计算结果。 + */ + signCallback({ event, appKey, selfAppSecret, body, timestamp }) { + const query = { + method: event, + v: '1.0', + timestamp, + app_key: appKey, + }; + + return signRequest({ query, body, selfAppSecret }); + } + + /** + * 发送回调请求(带自动重试)。 + * 非 2xx 响应或网络错误触发重试,最多重试 MAX_RETRY 次, + * 每次重试间隔递增(2s → 5s → 15s)。 + * @param {Object} options 回调选项。 + * @param {string} options.callbackUrl 回调目标 URL。 + * @param {string} options.appKey 应用 app_key。 + * @param {string} options.selfAppSecret 应用密钥。 + * @param {string} options.event 事件名,如 order_completed。 + * @param {Object} options.data 回调数据。 + * @param {Object} [options.metadata] 额外元数据。 + * @return {Promise} 回调结果 { success, retryCount, response, error }。 + */ + async sendWithRetry({ callbackUrl, appKey, selfAppSecret, event, data, metadata }) { + const { ctx } = this; + const timestamp = String(Date.now()); + const body = { event, data, metadata: metadata || {} }; + const { sign } = this.signCallback({ event, appKey, selfAppSecret, body, timestamp }); + + const queryString = [ + `method=${encodeURIComponent(event)}`, + 'v=1.0', + `timestamp=${timestamp}`, + `app_key=${encodeURIComponent(appKey)}`, + `sign=${sign}`, + ].join('&'); + const separator = callbackUrl.includes('?') ? '&' : '?'; + const url = `${callbackUrl}${separator}${queryString}`; + + /** @type {string|null} 最后一次错误信息 */ + let lastError = null; + + /** @type {Object|null} 最后一次响应对象 */ + let lastResponse = null; + + for (let attempt = 0; attempt <= MAX_RETRY; attempt++) { + try { + const result = await ctx.curl(url, { + method: 'POST', + contentType: 'json', + dataType: 'json', + data: body, + timeout: 30000, + }); + + lastResponse = result; + + if (result.status >= 200 && result.status < 300) { + await this.logCallback({ + appKey, + event, + callbackUrl, + success: true, + retryCount: attempt, + response: result.data, + }); + + return { + success: true, + retryCount: attempt, + response: result.data, + error: null, + }; + } + + lastError = new Error(`回调返回非 2xx 状态码: ${result.status}`); + + await this.logCallback({ + appKey, + event, + callbackUrl, + success: false, + retryCount: attempt, + response: result.data, + error: lastError.message, + }); + } catch (error) { + lastError = error; + + await this.logCallback({ + appKey, + event, + callbackUrl, + success: false, + retryCount: attempt, + response: null, + error: error.message, + }); + } + + if (attempt < MAX_RETRY) { + const delay = RETRY_DELAY_MS[attempt] || RETRY_DELAY_MS[RETRY_DELAY_MS.length - 1]; + await new Promise(resolve => setTimeout(resolve, delay)); + } + } + + return { + success: false, + retryCount: MAX_RETRY, + response: lastResponse ? lastResponse.data : null, + error: lastError ? lastError.message : '回调失败', + }; + } + + /** + * 根据 app_key 查询 api_app 获取 callback_url 与密钥,发送回调通知。 + * @param {Object} options 回调选项。 + * @param {string} options.appKey 应用 app_key。 + * @param {string} options.event 事件名,如 order_completed。 + * @param {Object} options.data 回调数据。 + * @param {Object} [options.metadata] 额外元数据。 + * @return {Promise} 回调结果 { success, retryCount, response, error }。 + */ + async sendByAppKey({ appKey, event, data, metadata }) { + const { ctx } = this; + const normalizedAppKey = String(appKey || '').trim(); + + if (!normalizedAppKey) { + ctx.logger.warn('[OpenapiCallback] sendByAppKey 缺少 appKey'); + + return { + success: false, + retryCount: 0, + response: null, + error: '缺少 appKey', + }; + } + + const appConfig = await ctx.model.ApiApp.findOne({ + attributes: ['self_app_key', 'self_app_secret', 'callback_url'], + where: { + self_app_key: normalizedAppKey, + is_enabled: 1, + }, + raw: true, + }); + + if (!appConfig || !appConfig.callback_url) { + ctx.logger.warn(`[OpenapiCallback] 未找到有效的回调配置,appKey=${normalizedAppKey}`); + + return { + success: false, + retryCount: 0, + response: null, + error: '未找到有效的回调配置', + }; + } + + return await this.sendWithRetry({ + callbackUrl: appConfig.callback_url, + appKey: normalizedAppKey, + selfAppSecret: appConfig.self_app_secret || '', + event, + data, + metadata, + }); + } + + /** + * 记录回调日志。 + * 格式:[OpenapiCallback] event=xxx appKey=xxx url=xxx retry=N success=xxx + * @param {Object} options 日志选项。 + * @param {string} options.appKey 应用 app_key。 + * @param {string} options.event 事件名。 + * @param {string} options.callbackUrl 回调目标 URL。 + * @param {boolean} options.success 是否成功。 + * @param {number} options.retryCount 重试次数。 + * @param {*} options.response 响应数据。 + * @param {string} [options.error] 错误信息。 + * @return {void} 无返回值。 + */ + async logCallback({ appKey, event, callbackUrl, success, retryCount, response, error }) { + const { ctx } = this; + const logMessage = `[OpenapiCallback] event=${event} appKey=${appKey} url=${callbackUrl} retry=${retryCount} success=${success}`; + + if (success) { + ctx.logger.info(logMessage); + } else if (retryCount >= MAX_RETRY) { + ctx.logger.error(`${logMessage} error=${error || '未知错误'}`); + } else { + ctx.logger.warn(`${logMessage} error=${error || '未知错误'}`); + } + } +} + +module.exports = OpenapiCallbackService; diff --git a/app/service/openapi/callbackRegistry.js b/app/service/openapi/callbackRegistry.js new file mode 100644 index 0000000..35a95e8 --- /dev/null +++ b/app/service/openapi/callbackRegistry.js @@ -0,0 +1,31 @@ +'use strict'; + +/** + * OpenAPI 回调事件注册表。 + * 每个事件包含 name(事件名)、label(展示名)、description(说明)、 + * sampleData(示例数据,与真实回调数据格式一致)。 + */ +const CALLBACK_EVENTS = [ + { + name: 'order_completed', + label: '订单发货完成', + description: '订单同步(出库)完成后触发', + sampleData: { + orderIds: [ 1001, 1002 ], + status: 'completed', + successCount: 2, + failedCount: 0, + }, + }, + { + name: 'order_cancelled', + label: '订单已取消', + description: '订单取消成功后触发', + sampleData: { + orderCode: 'TEST-ORDER-001', + status: 'cancelled', + }, + }, +]; + +module.exports = { CALLBACK_EVENTS }; diff --git a/app/service/openapiMethods/callback.js b/app/service/openapiMethods/callback.js new file mode 100644 index 0000000..1daa9a7 --- /dev/null +++ b/app/service/openapiMethods/callback.js @@ -0,0 +1,78 @@ +'use strict'; + +const MainService = require('../main'); + +/** + * OpenAPI 回调测试方法服务。 + * 提供模拟发送回调通知的能力,用于测试回调链路是否正常。 + */ +class OpenapiCallbackMethodService extends MainService { + + /** + * 通过 app_key 解析应用信息。 + * 查询 ApiApp 表校验 app_key 有效性。 + * @param {string} appKey 开放接口 app_key。 + * @return {Promise} 包含 appKey 的信息对象。 + */ + async resolveAppInfo(appKey) { + const { ctx } = this; + const normalizedAppKey = String(appKey || '').trim(); + + if (!normalizedAppKey) { + throw new Error('app_key 缺失'); + } + + const appConfig = await ctx.model.ApiApp.findOne({ + attributes: ['self_app_key'], + where: { + self_app_key: normalizedAppKey, + is_enabled: 1, + }, + raw: true, + }); + + if (!appConfig) { + throw new Error(`无法找到应用,请检查 app_key: ${normalizedAppKey}`); + } + + return { + appKey: normalizedAppKey, + }; + } + + /** + * 模拟发送回调通知(测试用)。 + * 通过 app_key 查找回调配置并发送一次回调请求。 + * @param {Object} [payload={}] 调用参数。 + * @param {Object} [payload.body={}] 请求体数据,可指定 event 与 data。 + * @param {Object} [payload.query={}] 请求 query 数据,需包含 app_key。 + * @return {Promise} 回调测试结果。 + */ + async test(payload = {}) { + const { body = {}, query = {} } = payload; + const { event = 'order_completed', data = {} } = body; + + try { + const info = await this.resolveAppInfo(query.app_key); + const result = await this.ctx.service.openapi.callback.sendByAppKey({ + appKey: info.appKey, + event, + data, + metadata: { test: true }, + }); + + if (result.success) { + return this.success('回调测试成功', { retryCount: result.retryCount }); + } + + return this.fail('回调测试失败', { + error: result.error, + retryCount: result.retryCount, + }); + } catch (error) { + return this.fail(`回调测试异常: ${error.message}`); + } + } +} + +module.exports = OpenapiCallbackMethodService; diff --git a/app/service/openapiMethods/deliveryorder.js b/app/service/openapiMethods/deliveryorder.js new file mode 100644 index 0000000..6d47240 --- /dev/null +++ b/app/service/openapiMethods/deliveryorder.js @@ -0,0 +1,159 @@ +'use strict'; + +const MainService = require('../main'); + +class OpenapiDeliveryorderService extends MainService { + /** + * 通过 app_key 解析仓库与货主信息。 + * 查询 ApiApp 并关联 StoreWarehouse 以获取 storeId、warehouseId。 + * @param {string} appKey 开放接口 app_key。 + * @return {Promise} 包含 storeId、warehouseId、appKey、customerId、warehouseCode 的信息对象。 + */ + async resolveAppInfo(appKey) { + const { ctx, app } = this; + const normalizedAppKey = String(appKey || '').trim(); + if (!normalizedAppKey) { + throw new Error('app_key 缺失'); + } + + const appConfig = await ctx.model.ApiApp.findOne({ + attributes: [ + 'id', + 'warehouse_id', + [app.Sequelize.col('contract.store_id'), 'store_id'], + ], + where: { + self_app_key: normalizedAppKey, + is_enabled: 1, + }, + include: [ + { + model: ctx.model.StoreWarehouse, + as: 'contract', + attributes: [], + required: false, + }, + ], + raw: true, + }); + + if (!appConfig || !appConfig.warehouse_id) { + throw new Error(`无法解析仓库信息,请检查 app_key: ${normalizedAppKey}`); + } + + return { + storeId: appConfig.store_id || null, + warehouseId: appConfig.warehouse_id, + appKey: normalizedAppKey, + customerId: null, + warehouseCode: '', + }; + } + + /** + * 查询发货单。 + * @param {Object} payload 调用参数。 + * @param {Object} payload.body 请求体数据,需包含 deliveryOrderCode。 + * @param {Object} payload.query 请求 query 数据,需包含 app_key。 + * @return {Promise} 查询结果,成功时返回订单详情,失败时返回错误信息。 + */ + async query(payload = {}) { + const { body = {}, query = {} } = payload; + const { deliveryOrderCode } = body; + + if (!deliveryOrderCode) { + return this.fail('deliveryOrderCode 参数缺失'); + } + + try { + const info = await this.resolveAppInfo(query.app_key); + const DeliveryModel = await this.ctx.model.OrderDeliveryFactory.getCurrentModel(info.warehouseId); + const order = await DeliveryModel.findOne({ + where: { delivery_order_code: deliveryOrderCode }, + }); + + if (order) { + return this.success('成功', { + totalLines: 0, + deliveryOrder: { + deliveryOrderCode: order.delivery_order_code, + deliveryOrderId: order.delivery_order_code, + warehouseCode: order.warehouse_code, + orderType: order.order_type, + status: order.status, + orderConfirmTime: order.order_confirm_time, + operatorCode: 0, + operatorName: '', + operateTime: order.update_at, + }, + packages: { + package: {}, + }, + orderLines: [], + }); + } + + return this.fail('未找到订单'); + } catch (error) { + return this.fail(`查询失败: ${error.message}`); + } + } + + /** + * 创建发货单。 + * @param {Object} payload 调用参数。 + * @param {Object} payload.body 请求体数据,需包含 deliveryOrder 与 orderLines。 + * @param {Object} payload.query 请求 query 数据,需包含 app_key。 + * @return {Promise} 创建结果,成功时返回订单ID等,失败时返回错误信息。 + */ + async create(payload = {}) { + const { body = {}, query = {} } = payload; + const { deliveryOrder, orderLines } = body; + + if (!deliveryOrder || !deliveryOrder.deliveryOrderCode) { + return this.fail('deliveryOrder 参数缺失或不完整'); + } + if (!orderLines) { + return this.fail('orderLines 参数缺失'); + } + + try { + const info = await this.resolveAppInfo(query.app_key); + this.setInfo( + info.storeId, + info.warehouseId, + info.appKey, + info.customerId, + info.warehouseCode + ); + + const data = { + request: { + deliveryOrder, + orderLines, + }, + }; + + const res = await this.ctx.service.systems.deliveryOrder.addOrder( + data, + this.getInfo(), + 'API' + ); + + if (res.success) { + return this.success(res.message, { + createTime: this.app.formatDate(new Date()), + deliveryOrderId: res.data.orderId, + warehouseCode: info.warehouseCode, + logisticsCode: '', + }); + } + + return this.fail(res.message, { createTime: this.app.formatDate(new Date()) }); + } catch (error) { + return this.fail(`创建失败: ${error.message}`); + } + } +} + +module.exports = OpenapiDeliveryorderService; diff --git a/app/service/openapiMethods/inventory.js b/app/service/openapiMethods/inventory.js new file mode 100644 index 0000000..6b9a65b --- /dev/null +++ b/app/service/openapiMethods/inventory.js @@ -0,0 +1,106 @@ +'use strict'; + +const MainService = require('../main'); + +/** + * OpenAPI 库存服务。 + * 提供库存查询能力,映射到 StockStore 底层模型。 + */ +class OpenapiInventoryService extends MainService { + + /** + * 通过 app_key 解析仓库与货主信息。 + * 查询 ApiApp 并关联 StoreWarehouse 以获取 storeId、warehouseId。 + * warehouseCode 优先使用 qimen_warehouse_code,为空时回退使用 warehouseId; + * ownerCode 优先使用 store_id,为空时回退使用空字符串。 + * @param {string} appKey 开放接口 app_key。 + * @return {Promise} 包含 storeId、warehouseId、appKey、customerId、warehouseCode、ownerCode 的信息对象。 + */ + async resolveAppInfo(appKey) { + const { ctx, app } = this; + const normalizedAppKey = String(appKey || '').trim(); + if (!normalizedAppKey) { + throw new Error('app_key 缺失'); + } + + const appConfig = await ctx.model.ApiApp.findOne({ + attributes: [ + 'id', + 'warehouse_id', + 'qimen_warehouse_code', + [ app.Sequelize.col('contract.store_id'), 'store_id' ], + ], + where: { + self_app_key: normalizedAppKey, + is_enabled: 1, + }, + include: [ + { + model: ctx.model.StoreWarehouse, + as: 'contract', + attributes: [], + required: false, + }, + ], + raw: true, + }); + + if (!appConfig || !appConfig.warehouse_id) { + throw new Error(`无法解析仓库信息,请检查 app_key: ${normalizedAppKey}`); + } + + const warehouseId = appConfig.warehouse_id; + const storeId = appConfig.store_id || null; + + return { + storeId, + warehouseId, + appKey: normalizedAppKey, + customerId: null, + warehouseCode: appConfig.qimen_warehouse_code || String(warehouseId), + ownerCode: storeId ? String(storeId) : '', + }; + } + + /** + * 库存查询。 + * 根据商品 ID 列表查询对应的库存信息,包括总库存、锁定量和可用量。 + * @param {Object} payload 调用参数。 + * @param {Object} payload.body 请求体数据,需包含 itemIds(商品 ID 数组)。 + * @param {Object} payload.query 请求 query 数据,需包含 app_key。 + * @return {Promise} 查询结果,成功时返回 items 数组。 + */ + async query(payload = {}) { + const { body = {}, query = {} } = payload; + const { itemIds } = body; + + if (!Array.isArray(itemIds) || itemIds.length === 0) { + return this.fail('itemIds 参数缺失或为空'); + } + + await this.resolveAppInfo(query.app_key); + const items = []; + + for (const itemId of itemIds) { + const result = await this.ctx.service.systems.stockStore.getItemStorages(itemId); + if (result.success && result.data) { + items.push({ + itemId: result.data.stock.id, + itemCode: result.data.stock.item_code, + warehouseCode: result.data.stock.warehouse_code, + quantity: result.data.storage.quantity, + lockQuantity: result.data.storage.lockedQuantity, + inventoryType: 'ZP', + }); + } + } + + if (items.length === 0) { + return this.fail('未查询到有效库存信息'); + } + + return this.success('库存查询成功', { items }); + } +} + +module.exports = OpenapiInventoryService; diff --git a/app/service/openapiMethods/order.js b/app/service/openapiMethods/order.js new file mode 100644 index 0000000..514d71d --- /dev/null +++ b/app/service/openapiMethods/order.js @@ -0,0 +1,163 @@ +'use strict'; + +const MainService = require('../main'); + +class OpenapiOrderService extends MainService { + /** + * 通过 app_key 解析仓库与货主信息。 + * 查询 ApiApp 并关联 StoreWarehouse 以获取 storeId、warehouseId。 + * @param {string} appKey 开放接口 app_key。 + * @return {Promise} 包含 storeId、warehouseId、appKey、customerId、warehouseCode 的信息对象。 + */ + async resolveAppInfo(appKey) { + const { ctx, app } = this; + const normalizedAppKey = String(appKey || '').trim(); + if (!normalizedAppKey) { + throw new Error('app_key 缺失'); + } + + const appConfig = await ctx.model.ApiApp.findOne({ + attributes: [ + 'id', + 'warehouse_id', + [ app.Sequelize.col('contract.store_id'), 'store_id' ], + ], + where: { + self_app_key: normalizedAppKey, + is_enabled: 1, + }, + include: [ + { + model: ctx.model.StoreWarehouse, + as: 'contract', + attributes: [], + required: false, + }, + ], + raw: true, + }); + + if (!appConfig || !appConfig.warehouse_id) { + throw new Error(`无法解析仓库信息,请检查 app_key: ${normalizedAppKey}`); + } + + return { + storeId: appConfig.store_id || null, + warehouseId: appConfig.warehouse_id, + appKey: normalizedAppKey, + customerId: null, + warehouseCode: '', + }; + } + + /** + * 取消发货单。 + * 当前仅支持出库单类型(JYCK/HHCK/BFCK → ORDER),非出库单类型返回不支持。 + * @param {Object} payload 调用参数。 + * @param {Object} payload.body 请求体数据,包含 orderCode、orderType。 + * @param {Object} payload.query 请求 query 数据,包含 app_key。 + * @return {Promise} 取消结果,成功时返回成功消息,失败时返回错误信息。 + */ + async cancel(payload = {}) { + const { ctx } = this; + const { body = {}, query = {} } = payload; + const { orderCode } = body; + const orderType = String(body.orderType || 'JYCK').trim().toUpperCase(); + + // 出库单类型映射:JYCK / HHCK / BFCK → ORDER + const ORDER_TYPES = [ 'JYCK', 'HHCK', 'BFCK' ]; + if (!ORDER_TYPES.includes(orderType)) { + return this.fail('暂不支持该订单类型的取消操作'); + } + + const normalizedOrderCode = String(orderCode || '').trim(); + if (!normalizedOrderCode) { + return this.fail('orderCode 参数缺失'); + } + + try { + const info = await this.resolveAppInfo(query.app_key); + + const DeliveryModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(info.warehouseId); + const transaction = await ctx.model.transaction(); + try { + const existingOrder = await DeliveryModel.findOne({ + where: { + delivery_order_code: normalizedOrderCode, + warehouse_id: info.warehouseId, + store_id: info.storeId, + }, + transaction, + lock: transaction.LOCK.UPDATE, + }); + + if (!existingOrder) { + await transaction.rollback(); + return this.fail('未找到对应的订单'); + } + + const pickStatus = String(existingOrder.pick_status || 'none').trim(); + const printStatus = String(existingOrder.print_status || 'none').trim(); + + if (pickStatus !== 'none' || printStatus !== 'none') { + await existingOrder.update({ + intercept_status: 'intercepting', + updated_at: new Date(), + }, { + transaction, + }); + + await transaction.commit(); + return this.fail('取消失败,已通知拦截执行'); + } + + await existingOrder.update({ + status: 'cancel', + outbound_status: 'fin', + step: 4, + updated_at: new Date(), + }, { + transaction, + }); + + await transaction.commit(); + + // 取消成功后触发 OpenAPI 回调通知(fire-and-forget,不阻塞主流程) + try { + const callbackService = this.ctx.service.openapi && this.ctx.service.openapi.callback; + if (callbackService && typeof callbackService.sendByAppKey === 'function') { + const appKey = String(query.app_key || '').trim(); + if (appKey) { + callbackService.sendByAppKey({ + appKey, + event: 'order_cancelled', + data: { + orderCode, + status: 'cancelled', + }, + }).catch(err => { + this.ctx.logger.warn('[OpenapiOrderCancel] 回调忽略失败: %s', err.message); + }); + } + } + } catch (err) { + this.ctx.logger.warn('[OpenapiOrderCancel] 触发回调异常,不影响主流程: %s', err.message); + } + + return this.success('取消订单成功'); + } catch (error) { + try { + await transaction.rollback(); + } catch (rollbackError) { + ctx.logger.error(`取消订单回滚失败: ${rollbackError.message}`); + } + ctx.logger.error(`取消订单失败: ${error.message}`); + return this.fail(error.message || '取消订单失败'); + } + } catch (error) { + return this.fail(`取消订单失败: ${error.message}`); + } + } +} + +module.exports = OpenapiOrderService; diff --git a/app/service/openapiMethods/singleitem.js b/app/service/openapiMethods/singleitem.js new file mode 100644 index 0000000..5aad33b --- /dev/null +++ b/app/service/openapiMethods/singleitem.js @@ -0,0 +1,137 @@ +'use strict'; + +const MainService = require('../main'); + +/** + * OpenAPI 单品服务。 + * 提供商品(单品)的同步与查询能力,映射到 StockStore 底层模型。 + */ +class OpenapiSingleitemService extends MainService { + + /** + * 通过 app_key 解析仓库与货主信息。 + * 查询 ApiApp 并关联 StoreWarehouse 以获取 storeId、warehouseId。 + * warehouseCode 优先使用 qimen_warehouse_code,为空时回退使用 warehouseId; + * ownerCode 优先使用 store_id,为空时回退使用空字符串。 + * @param {string} appKey 开放接口 app_key。 + * @return {Promise} 包含 storeId、warehouseId、appKey、customerId、warehouseCode、ownerCode 的信息对象。 + */ + async resolveAppInfo(appKey) { + const { ctx, app } = this; + const normalizedAppKey = String(appKey || '').trim(); + if (!normalizedAppKey) { + throw new Error('app_key 缺失'); + } + + const appConfig = await ctx.model.ApiApp.findOne({ + attributes: [ + 'id', + 'warehouse_id', + 'qimen_warehouse_code', + [ app.Sequelize.col('contract.store_id'), 'store_id' ], + ], + where: { + self_app_key: normalizedAppKey, + is_enabled: 1, + }, + include: [ + { + model: ctx.model.StoreWarehouse, + as: 'contract', + attributes: [], + required: false, + }, + ], + raw: true, + }); + + if (!appConfig || !appConfig.warehouse_id) { + throw new Error(`无法解析仓库信息,请检查 app_key: ${normalizedAppKey}`); + } + + const warehouseId = appConfig.warehouse_id; + const storeId = appConfig.store_id || null; + + return { + storeId, + warehouseId, + appKey: normalizedAppKey, + customerId: null, + warehouseCode: appConfig.qimen_warehouse_code || String(warehouseId), + ownerCode: storeId ? String(storeId) : '', + }; + } + + /** + * 同步(新增或更新)单品信息。 + * 将外部系统的商品数据写入 StockStore,并自动同步到库存表。 + * @param {Object} payload 调用参数。 + * @param {Object} payload.body 请求体数据,仅需包含 item;warehouseCode 和 ownerCode 由 app_key 自动解析,调用方不得传入。 + * @param {Object} payload.query 请求 query 数据,需包含 app_key。 + * @return {Promise} 同步结果,成功时返回 itemId。 + */ + async synchronize(payload = {}) { + const { body = {}, query = {} } = payload; + const { item } = body; + + if (!item || !item.itemCode) { + return this.fail('item 参数缺失或不完整(缺少 itemCode)'); + } + + try { + const { storeId, warehouseId, appKey, warehouseCode, ownerCode } = await this.resolveAppInfo(query.app_key); + + const requestData = { + warehouseCode: warehouseCode || '', + ownerCode: ownerCode || '', + item, + }; + + const stockData = await this.ctx.service.systems.stockStore.initQimenStockData( + requestData, + appKey, + storeId, + warehouseId + ); + + const result = await this.ctx.service.systems.stockStore.create(stockData); + return this.success('同步完成', { itemId: result.id }); + } catch (error) { + return this.fail(`同步失败: ${error.message}`); + } + } + + /** + * 查询单品详情。 + * 根据 itemId 查询 StockStore 记录并转换为 OpenAPI 统一格式。 + * @param {Object} payload 调用参数。 + * @param {Object} payload.body 请求体数据,需包含 itemId。 + * @param {Object} payload.query 请求 query 数据,需包含 app_key。 + * @return {Promise} 查询结果,成功时返回商品详情。 + */ + async query(payload = {}) { + const { body = {}, query = {} } = payload; + const { itemId } = body; + + if (!itemId) { + return this.fail('itemId 参数缺失'); + } + + try { + // 验证 app_key 有效性 + await this.resolveAppInfo(query.app_key); + + const row = await this.ctx.model.StockStore.findByPk(itemId); + if (!row) { + return this.fail(`商品不存在,itemId: ${itemId}`); + } + + const result = await this.ctx.service.systems.stockStore.convertToQimenFormat(row); + return this.success('查询成功', result); + } catch (error) { + return this.fail(`查询失败: ${error.message}`); + } + } +} + +module.exports = OpenapiSingleitemService; diff --git a/app/service/systemMethods/index.js b/app/service/systemMethods/index.js index ec720d6..92e46bc 100644 --- a/app/service/systemMethods/index.js +++ b/app/service/systemMethods/index.js @@ -173,6 +173,113 @@ function normalizeFirstWrappedArray(values, nestedKeys = []) { return []; } +/** + * 按候选字段顺序提取首个非空值。 + * + * @param {Array<*>} values 候选值列表 + * @return {*} 首个非空值;未命中时返回空字符串 + */ +function resolveFirstNonEmptyValue(values = []) { + for (const value of normalizeArray(values)) { + if (value === null || value === undefined) { + continue; + } + + if (String(value).trim() === '') { + continue; + } + + return value; + } + + return ''; +} + +/** + * 将 JD 模板响应中的标准模板列表扁平化为前端易消费结构。 + * + * @param {Object} templateResponseItem JD 模板命中对象 + * @return {Array} 扁平化后的模板列表 + */ +function normalizeJdTemplateList(templateResponseItem) { + const currentTemplateResponseItem = templateResponseItem && typeof templateResponseItem === 'object' + ? templateResponseItem + : {}; + const cpCode = normalizeText(resolveFirstNonEmptyValue([ + currentTemplateResponseItem.cp_code, + currentTemplateResponseItem.cpcode, + currentTemplateResponseItem.cpCode, + ])).trim(); + const standardTemplateList = normalizeFirstWrappedArray([ + currentTemplateResponseItem.standard_templates, + currentTemplateResponseItem.standardTemplates, + currentTemplateResponseItem.standard_template_do, + currentTemplateResponseItem.standardTemplateDo, + ], [ 'standard_template_do', 'standardTemplateDo' ]); + + return standardTemplateList.map(templateItem => { + const currentTemplateItem = templateItem && typeof templateItem === 'object' + ? templateItem + : {}; + const brandCode = normalizeText(resolveFirstNonEmptyValue([ + currentTemplateItem.brand_code, + currentTemplateItem.brandcode, + currentTemplateItem.brandCode, + ])).trim(); + const standardWaybillType = normalizeText(resolveFirstNonEmptyValue([ + currentTemplateItem.standard_waybill_type, + currentTemplateItem.templatetype, + currentTemplateItem.templateType, + ])).trim(); + + return { + template_id: normalizeText(resolveFirstNonEmptyValue([ + currentTemplateItem.standard_template_id, + currentTemplateItem.id, + currentTemplateItem.templateid, + currentTemplateItem.templateId, + ])).trim(), + template_name: normalizeText(resolveFirstNonEmptyValue([ + currentTemplateItem.standard_template_name, + currentTemplateItem.name, + currentTemplateItem.templatename, + currentTemplateItem.templateName, + ])).trim(), + template_url: normalizeText(resolveFirstNonEmptyValue([ + currentTemplateItem.standard_template_url, + currentTemplateItem.url, + currentTemplateItem.templateurl, + currentTemplateItem.templateUrl, + currentTemplateItem.tempurl, + currentTemplateItem.tempUrl, + ])).trim(), + cp_code: cpCode || normalizeText(resolveFirstNonEmptyValue([ + currentTemplateItem.cp_code, + currentTemplateItem.cpcode, + currentTemplateItem.cpCode, + ])).trim(), + wp_code: brandCode || standardWaybillType, + }; + }); +} + +/** + * 为 JD 模板命中结果补充扁平化模板列表,保持原始字段不变。 + * + * @param {Object} templateResponseItem JD 模板命中对象 + * @return {Object} 补充 list 字段后的 JD 模板响应 + */ +function appendJdTemplateList(templateResponseItem) { + const currentTemplateResponseItem = templateResponseItem && typeof templateResponseItem === 'object' + ? templateResponseItem + : {}; + + return { + ...currentTemplateResponseItem, + list: normalizeJdTemplateList(currentTemplateResponseItem), + }; +} + /** * 规范化菜鸟标准模板子项列表。 * @@ -270,9 +377,10 @@ function appendExpressMappingKey(targetMap, rawKey, mappingItem) { * 构建抖音电子面单快递映射表。 * * @param {Array} expressList 系统快递列表 + * @param platformCode * @return {Object} 支持 DY 平台编码与系统快递编码双键的映射表 */ -function buildExpressNameMap(expressList,platformCode = 'DY') { +function buildExpressNameMap(expressList, platformCode = 'DY') { return normalizeArray(expressList).reduce((result, expressItem) => { const currentExpressItem = expressItem && typeof expressItem === 'object' ? expressItem : {}; const mappingItem = { @@ -332,46 +440,107 @@ function formatPddWaybillSearchResponse(responseData, expressNameMap = {}) { const list = subscriptions.map(subscription => { const subscriptionItem = subscription && typeof subscription === 'object' ? subscription : {}; - const accounts = normalizeArray(subscriptionItem.branch_account_cols).map(account => { + const accountSources = normalizeFirstWrappedArray([ + subscriptionItem.branch_account_cols, + subscriptionItem.branchAccounts, + subscriptionItem.branch_accounts, + subscriptionItem.accounts, + subscriptionItem.waybill_branch_account, + ], [ 'waybill_branch_account', 'branch_account', 'account', 'list' ]); + const firstAccountSource = accountSources[0] && typeof accountSources[0] === 'object' + ? accountSources[0] + : {}; + const providerid = normalizeText( + subscriptionItem.providerid + || subscriptionItem.providerId + || subscriptionItem.ProviderID + || firstAccountSource.providerid + || firstAccountSource.providerId + || firstAccountSource.ProviderID + ); + + const accounts = accountSources.map(account => { const accountItem = account && typeof account === 'object' ? account : {}; - const customerCodes = normalizeWrappedArray(accountItem.customer_code_list, [ 'string' ]) + const preferredCustomerCode = normalizeText( + accountItem.logisticsaccount + || subscriptionItem.logisticsaccount + || accountItem.shipperno + || subscriptionItem.shipperno + ); + const customerCodes = normalizeWrappedArray( + accountItem.customer_code_list + || accountItem.customerCodeList + || accountItem.customer_codes + || accountItem.customerCodes, + [ 'string', 'list', 'code' ] + ) .map(item => normalizeText(item)) .filter(Boolean); - const shipAddresses = normalizeArray(accountItem.shipp_address_cols).map(address => { - const addressItem = address && typeof address === 'object' ? address : {}; + if (!customerCodes.length && preferredCustomerCode) { + customerCodes.push(preferredCustomerCode); + } + const shipAddresses = normalizeFirstWrappedArray([ + accountItem.shipp_address_cols, + accountItem.ship_addresses, + accountItem.shipAddresses, + accountItem.address_dto, + accountItem.addresses, + accountItem.address, + subscriptionItem.address, + ], [ 'address_dto', 'waybill_address', 'list' ]).map(address => { + const rawAddressItem = address && typeof address === 'object' ? address : {}; + const addressItem = rawAddressItem.address && typeof rawAddressItem.address === 'object' + ? rawAddressItem.address + : rawAddressItem; + const province = normalizeText(addressItem.province); + const city = normalizeText(addressItem.city); + const district = normalizeText(addressItem.district || addressItem.area); + const town = normalizeText(addressItem.town); + const detail = normalizeText(addressItem.detail || addressItem.address_detail || addressItem.address); + const fullAddress = normalizeText(addressItem.full_address || addressItem.fullAddress); return { country: normalizeText(addressItem.country), - province: normalizeText(addressItem.province), - city: normalizeText(addressItem.city), - district: normalizeText(addressItem.district), - detail: normalizeText(addressItem.detail), - full_address: normalizeText(addressItem.full_address), + province, + city, + district, + town, + detail, + full_address: fullAddress || `${province}${city}${district}${town}${detail}`, }; }); - const services = normalizeArray(accountItem.service_info_cols).map(service => { + const services = normalizeFirstWrappedArray([ + accountItem.service_info_cols, + accountItem.service_info_dto, + accountItem.services, + accountItem.serviceInfos, + ], [ 'service_info_dto', 'waybill_service_info', 'service', 'list' ]).map(service => { const serviceItem = service && typeof service === 'object' ? service : {}; - const attributes = normalizeArray(serviceItem.service_attributes).map(attribute => { + const attributes = normalizeFirstWrappedArray([ + serviceItem.service_attributes, + serviceItem.service_attribute_dto, + serviceItem.attributes, + ], [ 'service_attribute_dto', 'waybill_service_attribute', 'attribute', 'list' ]).map(attribute => { const attributeItem = attribute && typeof attribute === 'object' ? attribute : {}; return { - attribute_code: normalizeText(attributeItem.attribute_code), - attribute_name: normalizeText(attributeItem.attribute_name), - attribute_type: normalizeText(attributeItem.attribute_type), - type_desc: normalizeText(attributeItem.type_desc), + attribute_code: normalizeText(attributeItem.attribute_code || attributeItem.attributeCode), + attribute_name: normalizeText(attributeItem.attribute_name || attributeItem.attributeName), + attribute_type: normalizeText(attributeItem.attribute_type || attributeItem.attributeType), + type_desc: normalizeText(attributeItem.type_desc || attributeItem.attribute_type_name || attributeItem.typeDesc), }; }); return { - service_code: normalizeText(serviceItem.service_code), - service_name: normalizeText(serviceItem.service_name), - service_desc: normalizeText(serviceItem.service_desc), + service_code: normalizeText(serviceItem.service_code || serviceItem.serviceCode), + service_name: normalizeText(serviceItem.service_name || serviceItem.serviceName), + service_desc: normalizeText(serviceItem.service_desc || serviceItem.description || serviceItem.serviceDesc), required: Boolean(serviceItem.required), attributes, }; }); - return { + const result = { branch_code: normalizeText(accountItem.branch_code), branch_name: normalizeText(accountItem.branch_name), quantity: accountItem.quantity === null || accountItem.quantity === undefined ? 0 : accountItem.quantity, @@ -382,6 +551,20 @@ function formatPddWaybillSearchResponse(responseData, expressNameMap = {}) { ship_addresses: shipAddresses, services, }; + + const platformShopId = normalizeText( + accountItem.shopid + || accountItem.shop_id + || subscriptionItem.shopid + || subscriptionItem.shop_id + || accountItem.providerid + || subscriptionItem.providerid + ); + if (platformShopId) { + result.platform_shop_id = platformShopId; + } + + return result; }); const wpCode = normalizeText(subscriptionItem.wp_code); @@ -394,6 +577,7 @@ function formatPddWaybillSearchResponse(responseData, expressNameMap = {}) { wp_name: normalizeText(expressMapping.name) || '', sys_express_code: normalizeText(expressMapping.sys_express_code) || '', wp_type: normalizeText(subscriptionItem.wp_type), + providerid, accounts, }; }); @@ -449,12 +633,14 @@ function formatDyWaybillSearchResponse(responseData, expressNameMap = {}) { ); const wpCode = normalizeText( subscriptionItem.wp_code + || subscriptionItem.providercode || subscriptionItem.cp_code || subscriptionItem.cpcode || subscriptionItem.logistics_code || subscriptionItem.express_code ); const expressMapping = resolveExpressMapping(expressNameMap, [ + subscriptionItem.providercode, subscriptionItem.cp_code, subscriptionItem.cpcode, subscriptionItem.wp_code, @@ -464,7 +650,7 @@ function formatDyWaybillSearchResponse(responseData, expressNameMap = {}) { wpCode, ]); - const accounts = normalizeFirstWrappedArray([ + const accountSources = normalizeFirstWrappedArray([ subscriptionItem.branch_account_cols, subscriptionItem.branchAccounts, subscriptionItem.branch_accounts, @@ -473,8 +659,27 @@ function formatDyWaybillSearchResponse(responseData, expressNameMap = {}) { subscriptionItem.results, subscriptionItem.result, subscriptionItem.list, - ], [ 'waybill_branch_account', 'branch_account', 'account', 'results', 'result', 'list' ]).map(account => { + ], [ 'waybill_branch_account', 'branch_account', 'account', 'results', 'result', 'list' ]); + const firstAccountSource = accountSources[0] && typeof accountSources[0] === 'object' + ? accountSources[0] + : {}; + const providerid = normalizeText( + subscriptionItem.providerid + || subscriptionItem.providerId + || subscriptionItem.ProviderID + || firstAccountSource.providerid + || firstAccountSource.providerId + || firstAccountSource.ProviderID + ); + + const accounts = (accountSources.length ? accountSources : [ subscriptionItem ]).map(account => { const accountItem = account && typeof account === 'object' ? account : {}; + const preferredCustomerCode = normalizeText( + accountItem.logisticsaccount + || subscriptionItem.logisticsaccount + || accountItem.shipperno + || subscriptionItem.shipperno + ); const customerCodes = normalizeWrappedArray( accountItem.customer_code_list || accountItem.customerCodeList @@ -482,23 +687,38 @@ function formatDyWaybillSearchResponse(responseData, expressNameMap = {}) { || accountItem.customerCodes, [ 'string', 'list', 'code' ] ).map(item => normalizeText(item)).filter(Boolean); + if (!customerCodes.length && preferredCustomerCode) { + customerCodes.push(preferredCustomerCode); + } const shipAddresses = normalizeFirstWrappedArray([ accountItem.shipp_address_cols, accountItem.ship_addresses, accountItem.shipAddresses, accountItem.address_dto, accountItem.addresses, + accountItem.address, + subscriptionItem.address, accountItem.shippers, - ], [ 'address_dto', 'waybill_address', 'address' ]).map(address => { - const addressItem = address && typeof address === 'object' ? address : {}; + ], [ 'address_dto', 'waybill_address' ]).map(address => { + const rawAddressItem = address && typeof address === 'object' ? address : {}; + const addressItem = rawAddressItem.address && typeof rawAddressItem.address === 'object' + ? rawAddressItem.address + : rawAddressItem; + const province = normalizeText(addressItem.province); + const city = normalizeText(addressItem.city); + const district = normalizeText(addressItem.district || addressItem.area); + const town = normalizeText(addressItem.town); + const detail = normalizeText(addressItem.detail || addressItem.address_detail || addressItem.address); + const fullAddress = normalizeText(addressItem.full_address || addressItem.fullAddress); return { country: normalizeText(addressItem.country), - province: normalizeText(addressItem.province), - city: normalizeText(addressItem.city || addressItem.town), - district: normalizeText(addressItem.district || addressItem.area), - detail: normalizeText(addressItem.detail || addressItem.address_detail || addressItem.address), - full_address: normalizeText(addressItem.full_address || addressItem.fullAddress || ''), + province, + city, + district, + town, + detail, + full_address: fullAddress || `${province}${city}${district}${town}${detail}`, }; }); const services = normalizeFirstWrappedArray([ @@ -531,22 +751,25 @@ function formatDyWaybillSearchResponse(responseData, expressNameMap = {}) { attributes, }; }); - console.log("accountItem",subscriptionItem.logisticsaccount,"\n\n") const result = { - branch_code: accountItem.sitecode, - branch_name: accountItem.sitename, + branch_code: normalizeText(accountItem.branch_code || accountItem.branchCode || accountItem.sitecode), + branch_name: normalizeText(accountItem.branch_name || accountItem.branchName || accountItem.sitename), quantity: accountItem.quantity === null || accountItem.quantity === undefined ? 0 : accountItem.quantity, cancel_quantity: accountItem.cancel_quantity ?? 0, recycled_quantity: accountItem.recycled_quantity ?? 0, allocated_quantity: accountItem.allocated_quantity ?? 0, + customer_code_list: customerCodes, ship_addresses: shipAddresses, services, }; - if(subscriptionItem.logisticsaccount){ - result.customer_code_list = [subscriptionItem.logisticsaccount]; - } - if(subscriptionItem.shopid){ - result.platform_shop_id = subscriptionItem.shopid; + const platformShopId = normalizeText( + accountItem.shopid + || subscriptionItem.shopid + || accountItem.providerid + || subscriptionItem.providerid + ); + if (platformShopId) { + result.platform_shop_id = platformShopId; } return result; }); @@ -555,9 +778,20 @@ function formatDyWaybillSearchResponse(responseData, expressNameMap = {}) { groupedByWpCode.set(wpCode, { wp_code: wpCode, wp_name: normalizeText(expressMapping.name) - || normalizeText(subscriptionItem.wp_name || subscriptionItem.cp_name || subscriptionItem.cpname), + || normalizeText( + subscriptionItem.wp_name + || subscriptionItem.providername + || subscriptionItem.cp_name + || subscriptionItem.cpname + ), sys_express_code: normalizeText(expressMapping.sys_express_code || sysExpressCode), - wp_type: normalizeText(subscriptionItem.wp_type || subscriptionItem.waybill_type || subscriptionItem.type), + wp_type: normalizeText( + subscriptionItem.wp_type + || subscriptionItem.providertype + || subscriptionItem.waybill_type + || subscriptionItem.type + ), + providerid, accounts: [], shipAddressKeys: new Set(), }); @@ -567,13 +801,26 @@ function formatDyWaybillSearchResponse(responseData, expressNameMap = {}) { if (!groupedItem.wp_name) { groupedItem.wp_name = normalizeText(expressMapping.name) - || normalizeText(subscriptionItem.wp_name || subscriptionItem.cp_name || subscriptionItem.cpname); + || normalizeText( + subscriptionItem.wp_name + || subscriptionItem.providername + || subscriptionItem.cp_name + || subscriptionItem.cpname + ); } if (!groupedItem.sys_express_code) { groupedItem.sys_express_code = normalizeText(expressMapping.sys_express_code || sysExpressCode); } if (!groupedItem.wp_type) { - groupedItem.wp_type = normalizeText(subscriptionItem.wp_type || subscriptionItem.waybill_type || subscriptionItem.type); + groupedItem.wp_type = normalizeText( + subscriptionItem.wp_type + || subscriptionItem.providertype + || subscriptionItem.waybill_type + || subscriptionItem.type + ); + } + if (!groupedItem.providerid && providerid) { + groupedItem.providerid = providerid; } const dedupedAccounts = accounts.map(accountItem => { @@ -611,6 +858,7 @@ function formatDyWaybillSearchResponse(responseData, expressNameMap = {}) { wp_name: item.wp_name, sys_express_code: item.sys_express_code, wp_type: item.wp_type, + providerid: item.providerid, accounts: item.accounts, })); @@ -1626,6 +1874,61 @@ class indexService extends MainService { return responseData; } + /** + * 实时请求拼多多官方标准模板接口。 + * + * @param {Object} payload 请求参数 + * @param {string} payload.accessToken 店铺授权令牌 + * @param {string} payload.wpCode 拼多多平台快递编码 + * @return {Promise} 拼多多原始响应数据 + * @throws {Error} 拼多多返回错误结构或请求失败时抛出异常 + */ + async requestPddStdTemplates(payload = {}) { + const { ctx } = this; + const { + accessToken = '', + wpCode = '', + } = payload || {}; + const normalizedAccessToken = String(accessToken || '').trim(); + const normalizedWpCode = String(wpCode || '').trim(); + + if (!normalizedAccessToken) { + throw new Error('拼多多模板查询 accessToken 不能为空'); + } + + if (!normalizedWpCode) { + throw new Error('拼多多模板查询 wp_code 不能为空'); + } + + const pddClient = new PddClient(ctx); + const builtRequest = pddClient.buildRequest({ + type: 'pdd.cloudprint.stdtemplates.get', + accessToken: normalizedAccessToken, + request: { + wp_code: normalizedWpCode, + }, + dataType: 'JSON', + }); + const response = await ctx.curl(DEFAULT_PDD_ROUTER_URL, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + dataType: 'json', + data: builtRequest.requestBody, + }); + const responseData = response && Object.prototype.hasOwnProperty.call(response, 'data') + ? response.data + : response; + + if (responseData && typeof responseData === 'object' && responseData.error_response) { + const errorResponse = responseData.error_response; + throw new Error(errorResponse.error_msg || '拼多多标准模板查询失败'); + } + + return responseData; + } + /** * 实时请求淘宝菜鸟电子面单网点列表。 * @@ -1747,22 +2050,33 @@ class indexService extends MainService { * * @param {string} appSecret 菠萝派访问令牌 * @param {string|number} platid 菠萝派平台标识 + * @param isJD * @return {Promise>} 归一化后的模板数组 * @throws {Error} 当配置缺失或接口返回失败时抛出异常 */ - async requestPolyStdTemplates(appSecret,platid) { + async requestPolyStdTemplates(appSecret, platid, isJD = false) { + console.log('请求菠萝派标准模板接口入参', { appSecret: String(appSecret || '').trim() ? '***' : '', platid }); const { service } = this; - if(!appSecret || !platid){ + if (!appSecret || !platid) { throw new Error('菠萝派接口配置缺失'); } - const responseData = await service.systems.poloApi.request('Differ.JH.Logistics.GetTemplates', { - templatestype:"ALL" - }, { - interface_url: 'https://api.polyapi.com/OpenAPI/do', + const query_data = { templatestype: 'ALL' }; + if (platid == 673) { + query_data.BizVersion = '2'; + } + if (platid == 544) { + platid = 611; + } + let interface_url = 'https://api.polyapi.com/OpenAPI/do'; + if (isJD) { + interface_url = 'https://apijd.polyapi.com/OpenAPI/do'; + } + const responseData = await service.systems.poloApi.request('Differ.JH.Logistics.GetTemplates', query_data, { + interface_url, appkey: this.app.config.poloApi.appKey, app_secret: this.app.config.poloApi.appSecret, - token:appSecret, - platid: platid, + token: appSecret, + platid, version: '1.0', }); console.log('请求菠萝派标准模板接口响应', JSON.stringify(responseData)); @@ -1800,7 +2114,7 @@ class indexService extends MainService { : Array.isArray(nestedData) ? nestedData : []; - const cpCode = itemCpCode ?? itemCpcode ?? itemCpCodeCamel; + const cpCode = itemCpCode ?? itemCpcode ?? itemCpCodeCamel; return { ...restItem, @@ -1932,7 +2246,7 @@ class indexService extends MainService { case 'DY': { const accessToken = String(shopPlain.access_token || '').trim(); const expressList = await this.service.systems.express.getExpressList(true); - const expressNameMap = buildExpressNameMap(expressList,"DY"); + const expressNameMap = buildExpressNameMap(expressList, 'DY'); const responseData = await service.systems.poloApi.request('Differ.JH.Logistics.GetWayBillCondition', { }, { interface_url: 'https://api.polyapi.com/OpenAPI/do', @@ -1950,7 +2264,7 @@ class indexService extends MainService { case 'KS':{ const accessToken = String(shopPlain.access_token || '').trim(); const expressList = await this.service.systems.express.getExpressList(true); - const expressNameMap = buildExpressNameMap(expressList, "KS"); + const expressNameMap = buildExpressNameMap(expressList, 'KS'); const responseData = await service.systems.poloApi.request('Differ.JH.Logistics.GetWayBillCondition', { }, { interface_url: 'https://api.polyapi.com/OpenAPI/do', @@ -1968,7 +2282,7 @@ class indexService extends MainService { case 'SPH':{ const accessToken = String(shopPlain.access_token || '').trim(); const expressList = await this.service.systems.express.getExpressList(true); - const expressNameMap = buildExpressNameMap(expressList, "SPH"); + const expressNameMap = buildExpressNameMap(expressList, 'SPH'); const responseData = await service.systems.poloApi.request('Differ.JH.Logistics.GetWayBillCondition', { }, { interface_url: 'https://api.polyapi.com/OpenAPI/do', @@ -1986,8 +2300,9 @@ class indexService extends MainService { case 'XHS':{ const accessToken = String(shopPlain.access_token || '').trim(); const expressList = await this.service.systems.express.getExpressList(true); - const expressNameMap = buildExpressNameMap(expressList, "XHS"); + const expressNameMap = buildExpressNameMap(expressList, 'XHS'); const responseData = await service.systems.poloApi.request('Differ.JH.Logistics.GetWayBillCondition', { + BizVersion: '2', }, { interface_url: 'https://api.polyapi.com/OpenAPI/do', appkey: this.app.config.poloApi.appKey, @@ -2001,7 +2316,150 @@ class indexService extends MainService { list = parsed.list; break; } - + case 'JD':{ + const accessToken = String(shopPlain.access_token || '').trim(); + const expressList = await this.service.systems.express.getExpressList(true); + const expressNameMap = buildExpressNameMap(expressList, 'JD'); + const jdExpressNameMap = { ...expressNameMap }; + + normalizeArray(expressList).forEach(expressItem => { + const currentExpressItem = expressItem && typeof expressItem === 'object' ? expressItem : {}; + const mappingItem = { + name: normalizeText(currentExpressItem.name), + sys_express_code: normalizeText(currentExpressItem.code), + }; + + appendExpressMappingKey(jdExpressNameMap, currentExpressItem.name, mappingItem); + }); + const responseData = await service.systems.poloApi.request('Differ.JH.Logistics.GetProvider', { + + }, { + interface_url: 'https://jd.polyapi.com/OpenAPI/do', + appkey: this.app.config.poloApi.appKey, + app_secret: this.app.config.poloApi.appSecret, + platid, + version: '1.5', + token: accessToken, + }); + console.log('请求的店铺的platformCode', platformCode, '接口响应', JSON.stringify(responseData)); + const parsed = formatDyWaybillSearchResponse(responseData, jdExpressNameMap); + parsed.list = normalizeArray(parsed.list).map(item => { + const currentItem = item && typeof item === 'object' ? item : {}; + const expressMapping = resolveExpressMapping(jdExpressNameMap, [ + currentItem.sys_express_code, + currentItem.wp_code, + currentItem.wpCode, + currentItem.wp_name, + currentItem.wpName, + currentItem.providername, + currentItem.cp_name, + currentItem.cpname, + currentItem.providercode, + currentItem.cp_code, + currentItem.cpcode, + ]); + + if (!Object.keys(expressMapping).length) { + return currentItem; + } + + return { + ...currentItem, + wp_name: normalizeText(expressMapping.name) || normalizeText(currentItem.wp_name) || normalizeText(currentItem.wpName), + sys_express_code: normalizeText(expressMapping.sys_express_code) || normalizeText(currentItem.sys_express_code), + }; + }); + const unresolvedItems = normalizeArray(parsed.list).filter(item => { + const currentItem = item && typeof item === 'object' ? item : {}; + return !normalizeText(currentItem.sys_express_code).trim(); + }); + const compensationCandidateCodeSet = new Set(); + + normalizeArray(unresolvedItems).forEach(item => { + const currentItem = item && typeof item === 'object' ? item : {}; + [ + currentItem.wp_code, + currentItem.wpCode, + currentItem.providercode, + currentItem.cp_code, + currentItem.cpcode, + ].forEach(candidateCode => { + const normalizedCandidateCode = normalizeText(candidateCode).trim().toUpperCase(); + + if (normalizedCandidateCode) { + compensationCandidateCodeSet.add(normalizedCandidateCode); + } + }); + }); + + const compensationCandidateCodes = Array.from(compensationCandidateCodeSet); + + if (compensationCandidateCodes.length) { + const { Op } = this.app.Sequelize; + const expressRows = await ctx.model.Express.findAll({ + attributes: [ 'code', 'name', 'JD' ], + where: { + [Op.or]: [ + { + code: { + [Op.in]: compensationCandidateCodes, + }, + }, + { + JD: { + [Op.in]: compensationCandidateCodes, + }, + }, + ], + }, + }); + const compensationExpressMap = {}; + + normalizeArray(expressRows).forEach(expressRow => { + const currentExpressRow = expressRow && typeof expressRow.get === 'function' + ? expressRow.get({ plain: true }) + : expressRow || {}; + const compensationMappingItem = { + name: normalizeText(currentExpressRow.name), + sys_express_code: normalizeText(currentExpressRow.code), + }; + + appendExpressMappingKey(compensationExpressMap, currentExpressRow.code, compensationMappingItem); + appendExpressMappingKey(compensationExpressMap, currentExpressRow.JD, compensationMappingItem); + }); + + parsed.list = normalizeArray(parsed.list).map(item => { + const currentItem = item && typeof item === 'object' ? item : {}; + const currentSysExpressCode = normalizeText(currentItem.sys_express_code).trim(); + + if (currentSysExpressCode) { + return currentItem; + } + + const compensationMapping = resolveExpressMapping(compensationExpressMap, [ + currentItem.wp_code, + currentItem.wpCode, + currentItem.providercode, + currentItem.cp_code, + currentItem.cpcode, + ]); + + if (!Object.keys(compensationMapping).length) { + return currentItem; + } + + const currentWpName = normalizeText(currentItem.wp_name) || normalizeText(currentItem.wpName); + + return { + ...currentItem, + wp_name: currentWpName || normalizeText(compensationMapping.name), + sys_express_code: normalizeText(compensationMapping.sys_express_code), + }; + }); + } + list = parsed.list; + break; + } default: list = []; break; @@ -2105,22 +2563,36 @@ class indexService extends MainService { */ async getTemplateAllowedExpressCodeSet(platformCode, expressCode) { const fieldName = this.getExpressPlatformFieldName(platformCode); + const normalizedExpressCode = String(expressCode || '').trim().toUpperCase(); + const { Op } = this.app.Sequelize; const expressRows = await this.ctx.model.Express.findAll({ attributes: [ 'code', fieldName ], where: { - [fieldName]: expressCode, + [Op.or]: [ + { code: normalizedExpressCode }, + { [fieldName]: normalizedExpressCode }, + ], }, }); - + console.log('expressCode', normalizedExpressCode); + console.log('expressRows', expressRows); + console.log('fieldName', fieldName); const allowedCodeSet = new Set(); + if (normalizedExpressCode) { + allowedCodeSet.add(normalizedExpressCode); + } + for (const expressRow of Array.isArray(expressRows) ? expressRows : []) { const plainRow = expressRow && typeof expressRow.get === 'function' ? expressRow.get({ plain: true }) : expressRow || {}; - const code = String(plainRow[fieldName] || '').trim().toUpperCase(); + const candidateCodes = [ + plainRow.code, + plainRow[fieldName], + ].map(item => String(item || '').trim().toUpperCase()).filter(Boolean); - if (code) { + for (const code of candidateCodes) { allowedCodeSet.add(code); } } @@ -2138,18 +2610,40 @@ class indexService extends MainService { */ async filterPrintPlatformTemplateResponseData(responseData, platformCode, expressCode) { console.log('入参', platformCode, expressCode); - // 获取对应的wp_code - const allowedCodeSet = await this.getTemplateAllowedExpressCodeSet(platformCode, expressCode); + const normalizedExpressCode = String(expressCode || '').trim().toUpperCase(); const normalizedResponseData = Array.isArray(responseData) ? responseData : []; + // 非 PDD 平台允许不传快递编码,直接回退首条模板。 + if (platformCode !== 'PDD' && !normalizedExpressCode) { + const fallbackTemplateResponseItem = normalizedResponseData[0]; + + if (platformCode === 'JD' && fallbackTemplateResponseItem) { + return appendJdTemplateList(fallbackTemplateResponseItem); + } + + return fallbackTemplateResponseItem; + } + + // 获取对应的wp_code + const allowedCodeSet = await this.getTemplateAllowedExpressCodeSet(platformCode, normalizedExpressCode); console.log('allowedCodeSet', allowedCodeSet); - console.log('normalizedResponseData', normalizedResponseData); + // console.log('normalizedResponseData', JSON.stringify(normalizedResponseData)); // normalizedResponseData数组中的cp_code字段与allowedCodeSet匹配的第一个对象 - return normalizedResponseData.find(item => { - const itemCpCode = String(item.cp_code || '').trim().toUpperCase(); + const matchedTemplateResponseItem = normalizedResponseData.find(item => { + const itemCpCode = normalizeText(resolveFirstNonEmptyValue([ + item?.cp_code, + item?.cpcode, + item?.cpCode, + ])).trim().toUpperCase(); return allowedCodeSet.has(itemCpCode); }); + + if (platformCode === 'JD' && matchedTemplateResponseItem) { + return appendJdTemplateList(matchedTemplateResponseItem); + } + + return matchedTemplateResponseItem; } /** @@ -2163,6 +2657,10 @@ class indexService extends MainService { return 'index:cainiao:stfTemplates:responseData'; } + if (platformCode === 'PDD') { + return 'index:printPlatform:PDD:templates:v2:responseData'; + } + return `index:printPlatform:${platformCode}:templates:responseData`; } @@ -2172,12 +2670,21 @@ class indexService extends MainService { * 当前已实现 CAINIAO 平台,其它平台返回空对象,便于后续扩展。 * * @param {string} platformCode 平台编码 + * @param s + * @param platid + * @param expressCode * @return {Promise} 平台模板响应 */ - async requestPrintPlatformTemplateList(platformCode,s = null,platid = null) { + async requestPrintPlatformTemplateList(platformCode, s = null, platid = null, expressCode = '') { + console.log('请求打印平台模板列表,平台编码:', platformCode, platid); const platformRequesters = { CAINIAO: async () => await this.requestTbCainiaoStdTemplates(), + PDD: async () => await this.requestPddTemplateSourceList(s, expressCode), KS: async () => await this.requestPolyStdTemplates(s, platid), + XHS: async () => await this.requestPolyStdTemplates(s, platid), + SPH: async () => await this.requestPolyStdTemplates(s, platid), + DY: async () => await this.requestPolyStdTemplates(s, platid), + JD: async () => await this.requestPolyStdTemplates(s, platid, true), }; const requester = platformRequesters[platformCode]; @@ -2188,6 +2695,197 @@ class indexService extends MainService { return await requester(); } + /** + * 基于快递编码解析拼多多模板查询候选 wp_code。 + * + * 优先使用 wms_express 的 PDD 平台字段,未命中时回退为入参快递编码。 + * + * @param {string} expressCode 入参快递编码 + * @return {Promise>} 候选 wp_code 数组 + */ + async resolvePddTemplateWpCodeCandidates(expressCode) { + const normalizedExpressCode = String(expressCode || '').trim().toUpperCase(); + + if (!normalizedExpressCode) { + return []; + } + + let fieldName = 'PDD'; + try { + fieldName = this.getExpressPlatformFieldName('PDD'); + } catch (error) { + return [ normalizedExpressCode ]; + } + + const { Op } = this.app.Sequelize; + const expressRows = await this.ctx.model.Express.findAll({ + attributes: [ 'code', fieldName ], + where: { + [Op.or]: [ + { + code: normalizedExpressCode, + }, + { + [fieldName]: normalizedExpressCode, + }, + ], + }, + }); + + const wpCodeList = []; + const wpCodeSet = new Set(); + const appendWpCode = value => { + const wpCode = String(value || '').trim().toUpperCase(); + + if (!wpCode || wpCodeSet.has(wpCode)) { + return; + } + + wpCodeSet.add(wpCode); + wpCodeList.push(wpCode); + }; + + for (const expressRow of normalizeArray(expressRows)) { + const plainRow = expressRow && typeof expressRow.get === 'function' + ? expressRow.get({ plain: true }) + : expressRow || {}; + + appendWpCode(plainRow[fieldName]); + appendWpCode(plainRow.code); + } + + if (!wpCodeList.length) { + appendWpCode(normalizedExpressCode); + } + + return wpCodeList; + } + + /** + * 基于拼多多官方模板直连接口构建模板源列表。 + * + * @param {string} accessToken 店铺授权令牌 + * @param {string} expressCode 入参快递编码 + * @return {Promise>} 模板源数组(包含 cp_code、wp_code 与标准模板结构) + */ + async requestPddTemplateSourceList(accessToken, expressCode = '') { + const normalizedAccessToken = String(accessToken || '').trim(); + + if (!normalizedAccessToken) { + return []; + } + + const wpCodeCandidates = await this.resolvePddTemplateWpCodeCandidates(expressCode); + + if (!wpCodeCandidates.length) { + return []; + } + + const templateSourceList = []; + + for (const wpCodeCandidate of wpCodeCandidates) { + const responseData = await this.requestPddStdTemplates({ + accessToken: normalizedAccessToken, + wpCode: wpCodeCandidate, + }); + const responseRoot = responseData && typeof responseData === 'object' + ? responseData.pdd_cloudprint_stdtemplates_get_response || responseData + : {}; + const templateResponseItems = normalizeFirstWrappedArray([ + responseRoot.result, + responseRoot.results, + responseRoot.standard_template_result, + responseRoot.standard_templates, + responseRoot.datas, + responseRoot.data, + ], [ 'standard_template_result', 'standard_templates', 'results', 'result', 'datas', 'data', 'list' ]); + const normalizedTemplateResponseItems = templateResponseItems.length + ? templateResponseItems + : [ responseRoot ]; + + for (const templateResponseItem of normalizedTemplateResponseItems) { + const sourceItem = templateResponseItem && typeof templateResponseItem === 'object' + ? templateResponseItem + : {}; + const itemWpCode = normalizeText(resolveFirstNonEmptyValue([ + sourceItem.wp_code, + sourceItem.wpCode, + sourceItem.cp_code, + sourceItem.cpcode, + sourceItem.cpCode, + wpCodeCandidate, + ])).trim().toUpperCase(); + const standardTemplateSourceList = normalizeFirstWrappedArray([ + sourceItem.standard_templates, + sourceItem.standard_template_do, + sourceItem.standardTemplateDo, + sourceItem.templates, + sourceItem.template_list, + sourceItem.templateList, + sourceItem.standard_template_result, + sourceItem.results, + sourceItem.result, + sourceItem.datas, + sourceItem.data, + ], [ 'standard_template_do', 'standardTemplateDo', 'standard_template_result', 'results', 'result', 'datas', 'data', 'list' ]); + const normalizedStandardTemplateSourceList = standardTemplateSourceList.length + ? standardTemplateSourceList + : sourceItem.standard_template_id || sourceItem.standard_template_name || sourceItem.standard_template_url + ? [ sourceItem ] + : []; + const normalizedTemplateList = normalizedStandardTemplateSourceList.map(templateItem => { + const sourceTemplate = templateItem && typeof templateItem === 'object' + ? templateItem + : {}; + + return { + standard_template_id: normalizeText(resolveFirstNonEmptyValue([ + sourceTemplate.standard_template_id, + sourceTemplate.id, + sourceTemplate.template_id, + sourceTemplate.templateId, + ])).trim(), + standard_template_name: normalizeText(resolveFirstNonEmptyValue([ + sourceTemplate.standard_template_name, + sourceTemplate.name, + sourceTemplate.template_name, + sourceTemplate.templateName, + ])).trim(), + standard_template_url: normalizeText(resolveFirstNonEmptyValue([ + sourceTemplate.standard_template_url, + sourceTemplate.url, + sourceTemplate.template_url, + sourceTemplate.templateUrl, + ])).trim(), + }; + }); + const seenTemplateUrlSet = new Set(); + const dedupedTemplateList = normalizedTemplateList.filter(templateItem => { + const templateUrl = templateItem && typeof templateItem === 'object' + ? templateItem.standard_template_url + : ''; + + if (seenTemplateUrlSet.has(templateUrl)) { + return false; + } + + seenTemplateUrlSet.add(templateUrl); + return true; + }); + + templateSourceList.push({ + cp_code: itemWpCode, + wp_code: itemWpCode, + standard_templates: { + standard_template_do: dedupedTemplateList, + }, + }); + } + } + + return templateSourceList; + } + /** * 获取打印平台模板列表。 * @@ -2199,7 +2897,7 @@ class indexService extends MainService { * @param {string} data.express_code 快递编码(下划线) * @param {string} [data.expressCode] 快递编码(驼峰) * @param {string} [data.shopId] 店铺ID(驼峰) - * + * * @return {Promise} 返回模板列表结果 */ async getPrintPlatformTemplateList(data = {}) { @@ -2229,14 +2927,10 @@ class indexService extends MainService { include: this.buildShopPrintPlatformInclude(true), }); } - if (!expressCode) { + if (platformCode === 'PDD' && !expressCode) { return this.fail('express_code 不能为空', { code: 400 }); } - const shouldBypassCache = Number.isFinite(shopId) && shopId > 0; - const cacheKey = this.getPrintPlatformTemplateCacheKey(platformCode); - const cached = shouldBypassCache ? null : await this.app.getCacheAsync(cacheKey); - let accessToken = ''; let platid = null; if (shop) { @@ -2249,19 +2943,26 @@ class indexService extends MainService { platid = Number(printPlatformInfo && printPlatformInfo.platid); } + const hasShopId = Number.isFinite(shopId) && shopId > 0; + const shouldBypassCache = platformCode === 'PDD' + ? hasShopId && Boolean(accessToken) + : hasShopId; + const cacheKey = this.getPrintPlatformTemplateCacheKey(platformCode); + const cached = shouldBypassCache ? null : await this.app.getCacheAsync(cacheKey); + const hasShopRequestParams = Boolean(accessToken) && Number.isFinite(platid); const responseDataFromSource = cached !== null && cached !== undefined ? cached : hasShopRequestParams - ? await this.requestPrintPlatformTemplateList(platformCode, accessToken, platid) - : await this.requestPrintPlatformTemplateList(platformCode); - // console.log('打印平台模板查询原始响应:', JSON.stringify(responseDataFromSource)); + ? await this.requestPrintPlatformTemplateList(platformCode, accessToken, platid, expressCode) + : await this.requestPrintPlatformTemplateList(platformCode, null, null, expressCode); + console.log('打印平台模板查询原始响应:', JSON.stringify(responseDataFromSource)); - if (cached === null || cached === undefined) { - // await this.app.setCacheAsync(cacheKey, responseDataFromSource, 3600); + if (platformCode === 'PDD' && Boolean(accessToken) && (cached === null || cached === undefined)) { + await this.app.setCacheAsync(cacheKey, responseDataFromSource, 3600); } - + console.log('过滤入参', platformCode, expressCode); const responseData = await this.filterPrintPlatformTemplateResponseData( responseDataFromSource, platformCode, diff --git a/app/service/systemMethods/order/base.js b/app/service/systemMethods/order/base.js index d4e60b7..7f3c7f5 100644 --- a/app/service/systemMethods/order/base.js +++ b/app/service/systemMethods/order/base.js @@ -43,7 +43,7 @@ const ORDER_LIST_BASE_ATTRIBUTES = Object.freeze([ 'wave_scan_result', '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', 'recheck_status', ]); const ORDER_WEIGHT_TYPE_LABELS = Object.freeze({ diff --git a/app/service/systemMethods/order/pendingOrder.js b/app/service/systemMethods/order/pendingOrder.js index 779c59b..8073a08 100644 --- a/app/service/systemMethods/order/pendingOrder.js +++ b/app/service/systemMethods/order/pendingOrder.js @@ -28,9 +28,9 @@ class PendingOrderService extends OrderBaseService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - 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'; + const _noNeedRight = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,updateOrderPlatform,updateOrderExpress,cloneOrder,createOrder,parseAddress'; + const _noNeedLog = 'list,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,parseAddress'; + const _noNeedAuth = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,updateOrderPlatform,updateOrderExpress,cloneOrder,createOrder,parseAddress'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -103,7 +103,248 @@ class PendingOrderService extends OrderBaseService { * @return {Promise} 更新后的订单信息。 */ async reverseReviewOrder(data = {}) { - return await this.updateOrderInspectionState(data, 'none'); + const requestData = this.isPlainObject(data) ? data : {}; + const warehouseId = this.getWarehouseId(); + const orderIds = this.normalizeOrderIds(requestData); + + if (orderIds.length === 0) { + throw new Error('订单ID不能为空'); + } + + const model = await this.getOrderModel('order', warehouseId); + const where = this.buildOrderWhere(orderIds, warehouseId); + const step = this.resolveReviewStep('none'); + const now = new Date(); + const canUseTransaction = this.ctx.model && typeof this.ctx.model.transaction === 'function'; + const transaction = canUseTransaction ? await this.ctx.model.transaction() : null; + const dbQueryOptions = transaction ? { transaction } : {}; + + try { + const targetOrders = await model.findAll({ + attributes: [ 'id', 'wave_id', 'wave_no' ], + where, + raw: true, + ...dbQueryOptions, + }); + + if (!Array.isArray(targetOrders) || targetOrders.length === 0) { + throw new Error('订单不存在或不属于当前仓库'); + } + + const targetOrderIds = targetOrders + .map(order => Number(order && order.id || 0)) + .filter(id => Number.isInteger(id) && id > 0); + + await this.assertOrdersWithoutWaybill(targetOrderIds, transaction); + + const affectedWaveIds = [ ...new Set(targetOrders + .map(order => Number(order && order.wave_id || 0)) + .filter(waveId => Number.isInteger(waveId) && waveId > 0)) ]; + + const updateValues = { + inspection_status: 'none', + step, + updated_at: now, + }; + + if (affectedWaveIds.length > 0) { + updateValues.wave_id = 0; + updateValues.wave_no = ''; + } + + const updateResult = await model.update(updateValues, { + where, + ...dbQueryOptions, + }); + + const affectedRows = Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0); + if (affectedRows <= 0) { + throw new Error('订单不存在或不属于当前仓库'); + } + + if (affectedWaveIds.length > 0) { + await this.syncWavesAfterReverseReview({ + warehouseId, + waveIds: affectedWaveIds, + orderModel: model, + transaction: transaction || undefined, + }); + } + + const updatedOrders = await model.findAll({ + where, + raw: true, + ...dbQueryOptions, + }); + + if (!Array.isArray(updatedOrders) || updatedOrders.length === 0) { + throw new Error('订单不存在或不属于当前仓库'); + } + + if (transaction) { + await transaction.commit(); + } + + const orderMap = new Map(updatedOrders.map(order => [ Number(order.id), order ])); + const normalizedOrders = orderIds + .map(orderId => orderMap.get(orderId)) + .filter(Boolean) + .map(order => ({ + id: order.id, + inspection_status: order.inspection_status, + step: Number(order.step ?? step), + updated_at: order.updated_at, + })); + + if (normalizedOrders.length === 0) { + throw new Error('订单不存在或不属于当前仓库'); + } + + const firstOrder = normalizedOrders[0]; + return { + id: firstOrder.id, + inspection_status: firstOrder.inspection_status, + step: firstOrder.step, + updated_at: firstOrder.updated_at, + updated_count: affectedRows, + ids: normalizedOrders.map(order => order.id), + }; + } catch (error) { + if (transaction) { + await transaction.rollback(); + } + throw error; + } + } + + /** + * 校验订单是否已分配运单号。 + * + * 若任一订单存在非空运单号,直接抛出业务异常,阻止反审。 + * + * @param {Array} orderIds 订单ID集合。 + * @param {Object} transaction Sequelize 事务对象。 + * @return {Promise} 无返回值。 + */ + async assertOrdersWithoutWaybill(orderIds = [], transaction) { + const normalizedOrderIds = Array.isArray(orderIds) + ? orderIds + .map(orderId => Number(orderId || 0)) + .filter(orderId => Number.isInteger(orderId) && orderId > 0) + : []; + + if (normalizedOrderIds.length === 0) { + return; + } + + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; + if (!orderExpressModel || typeof orderExpressModel.findAll !== 'function') { + return; + } + + const expressRows = await orderExpressModel.findAll({ + attributes: [ 'order_id', 'waybill_code' ], + where: { + order_id: normalizedOrderIds, + }, + raw: true, + transaction, + }); + + const assignedOrderIds = [ ...new Set((Array.isArray(expressRows) ? expressRows : []) + .filter(row => String(row && row.waybill_code || '').trim()) + .map(row => Number(row && row.order_id || 0)) + .filter(orderId => Number.isInteger(orderId) && orderId > 0)) ]; + + if (assignedOrderIds.length > 0) { + const displayOrderIds = assignedOrderIds.slice(0, 10).join(','); + throw new Error(`订单[${displayOrderIds}]已分配运单号,禁止反审`); + } + } + + /** + * 反审后同步波次统计与索引。 + * + * 同一事务内重建目标波次索引,并回写波次总单量/处理量。 + * + * @param {Object} params 同步参数。 + * @param {number|string} params.warehouseId 仓库ID。 + * @param {Array} params.waveIds 受影响波次ID集合。 + * @param {Object} params.orderModel 订单模型。 + * @param {Object} params.transaction Sequelize 事务对象。 + * @return {Promise} 无返回值。 + */ + async syncWavesAfterReverseReview({ warehouseId, waveIds, orderModel, transaction } = {}) { + const normalizedWarehouseId = Number(warehouseId || 0); + const normalizedWaveIds = Array.isArray(waveIds) + ? [ ...new Set(waveIds + .map(waveId => Number(waveId || 0)) + .filter(waveId => Number.isInteger(waveId) && waveId > 0)) ] + : []; + + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0 || normalizedWaveIds.length === 0) { + return; + } + + const waveService = this.service.systemMethods.order.wave; + const remainingCountMap = await waveService.replaceOrderWaveIndexByWaveIds({ + warehouseId: normalizedWarehouseId, + waveIds: normalizedWaveIds, + orderModel, + transaction, + }); + + const updatedWaveIds = []; + const emptiedWaveIds = []; + for (const waveId of normalizedWaveIds) { + const remainingCount = Number(remainingCountMap.get(waveId) || 0); + if (remainingCount > 0) { + updatedWaveIds.push(waveId); + } else { + emptiedWaveIds.push(waveId); + } + } + + for (const waveId of updatedWaveIds) { + const remainingCount = Number(remainingCountMap.get(waveId) || 0); + const updateWaveSql = ` + UPDATE wms_wave_batch + SET total_orders = :remainingCount, + processed_orders = LEAST(processed_orders, :remainingCount), + update_time = NOW() + WHERE warehouse_id = :warehouseId + AND wave_id = :waveId + `; + + await this.ctx.model.query(updateWaveSql, { + replacements: { + warehouseId: normalizedWarehouseId, + waveId, + remainingCount, + }, + transaction, + }); + } + + if (emptiedWaveIds.length > 0) { + const emptyWaveSql = ` + UPDATE wms_wave_batch + SET total_orders = 0, + processed_orders = 0, + wave_status = -1, + update_time = NOW() + WHERE warehouse_id = :warehouseId + AND wave_id IN (:waveIds) + `; + + await this.ctx.model.query(emptyWaveSql, { + replacements: { + warehouseId: normalizedWarehouseId, + waveIds: emptiedWaveIds, + }, + transaction, + }); + } } /** @@ -1464,6 +1705,7 @@ class PendingOrderService extends OrderBaseService { step: 0, status: 'created', inspection_status: 'none', + recheck_status: 'none', storage_status: 'none', post_status: 'none', pick_status: 'none', @@ -1573,6 +1815,100 @@ class PendingOrderService extends OrderBaseService { }); } + /** + * 智能地址解析:使用 DeepSeek 将用户输入的地址字符串解析为结构化地址。 + * @param {Object} data 请求数据。 + * @param {string} data.address 原始地址字符串(必填)。 + * @return {Promise} 解析结果,成功返回 province/city/area/town/detailAddress/name/mobile 等,失败返回错误。 + */ + async parseAddress(data = {}) { + const address = String(data.address || '').trim(); + if (!address) { + return this.fail('地址字符串不能为空'); + } + + const apiKey = this.config.deepseek.apiKey; + const baseUrl = this.config.deepseek.baseUrl || 'https://api.deepseek.com'; + if (!apiKey) { + return this.fail('DeepSeek API Key 未配置'); + } + + try { + const prompt = `你是一个专业的中文地址解析助手,拥有丰富的中国地理知识。请解析以下地址字符串。 + +规则: +1. 提取字段:province(省)、city(市)、area(区/县)、town(乡镇/街道)、detailAddress(详细地址)、name(收件人)、mobile(手机号) +2. **利用你的中国地理知识**:如果地址包含村/镇/街道/社区名称,请检索你的知识库推测它所属的省市区。例如: + - "和丰一社" + 常见于广东地区村组命名 → 推测为广东省 东莞市/广州市等 + - 根据地址中的方言特征、命名习惯推测所在区域 +3. 如果实在无法确定,province填"暂未识别",city和area同理填"暂未识别" +4. detailAddress去除省市区部分,只保留街道/村/门牌号 +5. 只返回纯JSON,不含解释或markdown + +地址字符串: "${address}" + +请返回JSON:`; + + const result = await this.ctx.curl(`${baseUrl}/v1/chat/completions`, { + method: 'POST', + contentType: 'json', + dataType: 'json', + headers: { + Authorization: `Bearer ${apiKey}`, + }, + data: { + model: 'deepseek-chat', + messages: [ + { role: 'system', content: '你是一个专业的地址解析助手,只返回JSON格式结果。' }, + { role: 'user', content: prompt }, + ], + temperature: 0, + max_tokens: 500, + }, + timeout: 15000, + }); + + if (result.status !== 200 || !result.data) { + return this.fail('地址解析服务请求失败'); + } + + const content = result.data.choices?.[0]?.message?.content || ''; + + // 清理可能的 markdown 代码块标记 + let jsonStr = content.trim(); + jsonStr = jsonStr.replace(/^```json\s*/i, '').replace(/\s*```$/i, ''); + jsonStr = jsonStr.replace(/^```\s*/i, '').replace(/\s*```$/i, ''); + + try { + const parsed = JSON.parse(jsonStr); + const province = String(parsed.province || '').trim(); + const city = String(parsed.city || '').trim(); + const area = String(parsed.area || '').trim(); + const town = String(parsed.town || '').trim(); + + if (!province || province === '暂未识别' || province === '其他') { + return this.fail('地址解析失败:省市区无法识别,请补充更多地址信息后重试'); + } + + return this.success('地址解析成功', { + province, + city, + area, + town, + detailAddress: String(parsed.detailAddress || '').trim(), + name: String(parsed.name || '').trim(), + mobile: String(parsed.mobile || '').trim(), + }); + } catch (parseError) { + this.ctx.logger.warn('[parseAddress] JSON解析失败,原始返回: %s', content); + return this.fail('地址解析结果格式异常,请重试'); + } + } catch (error) { + this.ctx.logger.error('[parseAddress] DeepSeek请求异常: %s', error.message); + return this.fail(`地址解析失败: ${error.message}`); + } + } + /** * 手动创建待处理订单。 * @@ -1591,7 +1927,7 @@ class PendingOrderService extends OrderBaseService { * @param {string} [data.area] 区/县。 * @param {string} [data.town] 镇/街道。 * @param {string} [data.zip_code] 邮编。 - * @param {Array} data.items 订单明细(必填,每项含 item_code 与 plan_qty)。 + * @param {Array} data.items 订单明细(必填,每项含 item_id 与 plan_qty)。 * @param {string} [data.delivery_order_code] 订单号,不传则自动生成。 * @param {string} [data.logistics_code] 快递编码,不传则读货主默认快递策略。 * @param {string} [data.logistics_name] 快递名称。 @@ -1629,37 +1965,68 @@ class PendingOrderService extends OrderBaseService { throw new Error('详细地址不能为空'); } + const province = String(requestData.province || '').trim(); + if (!province) { + throw new Error('省份不能为空'); + } + + const city = String(requestData.city || '').trim(); + if (!city) { + throw new Error('城市不能为空'); + } + + const area = String(requestData.area || '').trim(); + if (!area) { + throw new Error('区县不能为空'); + } + const rawItems = requestData.items; if (!Array.isArray(rawItems) || rawItems.length === 0) { throw new Error('订单明细 items 不能为空'); } - // 2. 适配明细格式并校验(转为 addOrder 所需的驼峰格式) + // 2. 批量查询商品信息(利用 getItemInfoWithCache 的 Redis 缓存) + const itemIds = rawItems + .map(item => Number(item && item.item_id)) + .filter(id => Number.isInteger(id) && id > 0); + const itemInfoMap = new Map(); + for (const itemId of itemIds) { + const info = await this.service.systems.stockStore.getItemInfoWithCache(itemId); + if (info && !info.__isNull) { + itemInfoMap.set(itemId, info); + } + } + + // 3. 适配明细格式并校验(转为 addOrder 所需的驼峰格式) const orderLineItems = rawItems.map((item, idx) => { if (!item || typeof item !== 'object') { throw new Error(`第${idx + 1}行明细格式无效`); } - const itemCode = String(item.item_code || '').trim(); - if (!itemCode) { - throw new Error(`第${idx + 1}行商品编码 item_code 不能为空`); + const itemId = Number(item.item_id); + if (!Number.isInteger(itemId) || itemId <= 0) { + throw new Error(`第${idx + 1}行商品 item_id 必须为正整数`); } const planQty = Number(item.plan_qty); if (!Number.isInteger(planQty) || planQty <= 0) { throw new Error(`第${idx + 1}行计划数量 plan_qty 必须为正整数`); } return { - itemCode, - itemName: String(item.item_name || '').trim(), + itemCode: String(item.item_code || '').trim() + || String(itemInfoMap.get(itemId)?.item_code || '').trim(), + itemId, + itemName: String(item.item_name || '').trim() + || String(itemInfoMap.get(itemId)?.item_name || '').trim() + || '商品', planQty, orderLineNo: String(item.order_line_no || String(idx + 1)).trim(), actualPrice: Number(item.actual_price) || 0, }; }); - // 3. 自动生成订单号(如未传) + // 4. 自动生成订单号(如未传) const deliveryOrderCode = String(requestData.delivery_order_code || '').trim() || `SYS${Date.now()}${Math.floor(Math.random() * 9000) + 1000}`; - // 4. 适配为 addOrder 所需的奇门嵌套格式 + // 5. 适配为 addOrder 所需的奇门嵌套格式 const adaptedData = { request: { deliveryOrder: { @@ -1676,9 +2043,9 @@ class PendingOrderService extends OrderBaseService { name, mobile, tel, - province: String(requestData.province || '').trim(), - city: String(requestData.city || '').trim(), - area: String(requestData.area || '').trim(), + province, + city, + area, town: String(requestData.town || '').trim(), detailAddress, zipCode: String(requestData.zip_code || '').trim(), @@ -1696,7 +2063,7 @@ class PendingOrderService extends OrderBaseService { appKey: (this.ctx.user && this.ctx.user.app_key) || '', }; - // 5. 委托 addOrder 执行完整逻辑(库存预占、平台快递解析、入队列、操作日志) + // 6. 委托 addOrder 执行完整逻辑(库存预占、平台快递解析、入队列、操作日志) const result = await this.service.systems.deliveryOrder.addOrder(adaptedData, info); if (!result.success) { @@ -1722,331 +2089,6 @@ class PendingOrderService extends OrderBaseService { }); } - /** - * 下载创建订单的 Excel 导入模板。 - * - * 返回 base64 编码的 Excel 文件内容,前端解码后作为 .xlsx 文件下载。 - * 表头中标注 * 的列为必填项。 - * 多行相同订单号的行组成一个完整订单,每行代表一个商品明细。 - * - * @return {Promise} 统一 success 包装,含 base64 字符串与文件名。 - */ - async downloadCreateTemplate() { - const ExcelJS = require('exceljs'); - const workbook = new ExcelJS.Workbook(); - const sheet = workbook.addWorksheet('创建订单导入模板'); - - // 列定义:header 中带 * 表示必填 - const columns = [ - { header: '*订单号', key: 'delivery_order_code', width: 24 }, - { header: '*货主ID', key: 'store_id', width: 12 }, - { header: '*收件人姓名', key: 'name', width: 16 }, - { header: '*手机号(mobile/tel至少填一项)', key: 'mobile', width: 28 }, - { header: '电话', key: 'tel', width: 16 }, - { header: '*详细地址', key: 'detail_address', width: 36 }, - { header: '省份', key: 'province', width: 12 }, - { header: '城市', key: 'city', width: 12 }, - { header: '区/县', key: 'area', width: 12 }, - { header: '镇/街道', key: 'town', width: 12 }, - { header: '邮编', key: 'zip_code', width: 12 }, - { header: '快递编码', key: 'logistics_code', width: 16 }, - { header: '快递名称', key: 'logistics_name', width: 16 }, - { header: '系统平台编码', key: 'sys_platform_code', width: 16 }, - { header: '来源平台编码', key: 'source_platform_code', width: 16 }, - { header: '来源订单号', key: 'source_order_codes', width: 20 }, - { header: '订单类型', key: 'order_type', width: 14 }, - { header: '是否紧急(Y/N)', key: 'is_urgency', width: 16 }, - { header: '是否需要发票(Y/N)', key: 'invoice_flag', width: 18 }, - { header: '*商品编码', key: 'item_code', width: 20 }, - { header: '商品名称', key: 'item_name', width: 24 }, - { header: '*计划数量', key: 'plan_qty', width: 12 }, - { header: '行号', key: 'order_line_no', width: 10 }, - { header: '实际价格', key: 'actual_price', width: 12 }, - ]; - - sheet.columns = columns; - - // 表头样式:必填列(含*)背景橙色加粗,可选列灰色加粗 - const headerRow = sheet.getRow(1); - headerRow.eachCell((cell, colNumber) => { - const col = columns[colNumber - 1]; - const isRequired = col && col.header.startsWith('*'); - cell.font = { bold: true, color: { argb: 'FF000000' } }; - cell.fill = { - type: 'pattern', - pattern: 'solid', - fgColor: { argb: isRequired ? 'FFFFC000' : 'FFD9D9D9' }, - }; - cell.alignment = { vertical: 'middle', horizontal: 'center', wrapText: true }; - cell.border = { - top: { style: 'thin' }, - left: { style: 'thin' }, - bottom: { style: 'thin' }, - right: { style: 'thin' }, - }; - }); - headerRow.height = 36; - - // 插入一行示例数据 - sheet.addRow({ - delivery_order_code: 'ORD20260421001', - store_id: 1, - name: '张三', - mobile: '13800138000', - tel: '', - detail_address: 'XX路XX号', - province: '广东省', - city: '深圳市', - area: '南山区', - town: '', - zip_code: '518000', - logistics_code: 'STO', - logistics_name: '申通快递', - sys_platform_code: 'TB', - source_platform_code: '', - source_order_codes: '', - order_type: '', - is_urgency: 'N', - invoice_flag: 'N', - item_code: 'SKU001', - item_name: '商品A', - plan_qty: 2, - order_line_no: '1', - actual_price: 9.90, - }); - - // 同订单第二个商品(示例) - sheet.addRow({ - delivery_order_code: 'ORD20260421001', - store_id: 1, - name: '张三', - mobile: '13800138000', - tel: '', - detail_address: 'XX路XX号', - province: '广东省', - city: '深圳市', - area: '南山区', - town: '', - zip_code: '518000', - logistics_code: 'STO', - logistics_name: '申通快递', - sys_platform_code: 'TB', - source_platform_code: '', - source_order_codes: '', - order_type: '', - is_urgency: 'N', - invoice_flag: 'N', - item_code: 'SKU002', - item_name: '商品B', - plan_qty: 1, - order_line_no: '2', - actual_price: 19.90, - }); - - // 添加说明工作表 - const noteSheet = workbook.addWorksheet('填写说明'); - noteSheet.getColumn(1).width = 80; - const notes = [ - '【填写说明】', - '1. 带 * 的列为必填项,表头背景为橙色。', - '2. 每一行代表一条商品明细;同一订单的多个商品,订单号(delivery_order_code)必须相同。', - '3. 同一订单的所有行中,订单头信息(收件人、地址等)取第一行的值,后续行可省略但不影响解析。', - '4. mobile 和 tel 至少填写一项。', - '5. 计划数量(plan_qty)必须为正整数。', - '6. 是否紧急、是否需要发票只接受 Y 或 N(大写),不填默认 N。', - '7. 快递编码、系统平台编码不填时,系统会读取货主默认策略自动填充。', - '8. 同一文件内,相同订单号只会创建一次订单,不会重复创建。', - ]; - notes.forEach((note, i) => { - const row = noteSheet.getRow(i + 1); - row.getCell(1).value = note; - if (i === 0) { - row.getCell(1).font = { bold: true, size: 13 }; - } - }); - - const buffer = await workbook.xlsx.writeBuffer(); - const base64 = Buffer.from(buffer).toString('base64'); - - return this.success('ok', { - base64, - filename: '创建订单导入模板.xlsx', - mime: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - }); - } - - /** - * 通过 Excel 文件批量创建订单。 - * - * 接受 base64 编码的 Excel 文件,按订单号分组,每组调用 createOrder 逻辑创建一个订单。 - * 每行代表一条商品明细;同一订单号的行组成一个完整订单,订单头信息取每组第一行。 - * - * @param {Object} data 请求体。 - * @param {string} data.file_base64 base64 编码的 .xlsx 文件内容(必填)。 - * @return {Promise} 统一 success 包装,含成功/失败明细。 - */ - async importOrdersFromExcel(data = {}) { - const requestData = this.isPlainObject(data) ? data : {}; - const fileBase64 = String(requestData.file_base64 || '').trim(); - if (!fileBase64) { - throw new Error('file_base64 不能为空'); - } - - const ExcelJS = require('exceljs'); - const workbook = new ExcelJS.Workbook(); - const buffer = Buffer.from(fileBase64, 'base64'); - await workbook.xlsx.load(buffer); - - const sheet = workbook.getWorksheet(1); - if (!sheet) { - throw new Error('Excel 文件中未找到工作表'); - } - - // 读取表头(第1行),建立列名->列序号映射 - const headerMap = {}; - const headerRow = sheet.getRow(1); - headerRow.eachCell((cell, colNumber) => { - const rawHeader = String(cell.value || '').trim().replace(/^\*/, ''); - // 归一化 key - const keyMap = { - 订单号: 'delivery_order_code', - 货主ID: 'store_id', - 收件人姓名: 'name', - '手机号(mobile/tel至少填一项)': 'mobile', - 手机号: 'mobile', - 电话: 'tel', - 详细地址: 'detail_address', - 省份: 'province', - 城市: 'city', - '区/县': 'area', - '镇/街道': 'town', - 邮编: 'zip_code', - 快递编码: 'logistics_code', - 快递名称: 'logistics_name', - 系统平台编码: 'sys_platform_code', - 来源平台编码: 'source_platform_code', - 来源订单号: 'source_order_codes', - 订单类型: 'order_type', - '是否紧急(Y/N)': 'is_urgency', - '是否需要发票(Y/N)': 'invoice_flag', - 商品编码: 'item_code', - 商品名称: 'item_name', - 计划数量: 'plan_qty', - 行号: 'order_line_no', - 实际价格: 'actual_price', - }; - const key = keyMap[rawHeader]; - if (key) { - headerMap[key] = colNumber; - } - }); - - // 辅助:从行中取值 - const getCellValue = (row, key) => { - const colNum = headerMap[key]; - if (!colNum) return undefined; - const cell = row.getCell(colNum); - const val = cell && cell.value; - if (val === null || val === undefined) return ''; - return String(val).trim(); - }; - - // 读取所有数据行(从第2行开始),跳过空行 - const orderMap = new Map(); // delivery_order_code -> { headerData, items[] } - const orderSequence = []; // 保持顺序 - - sheet.eachRow((row, rowNumber) => { - if (rowNumber === 1) return; // 跳过表头 - const deliveryOrderCode = getCellValue(row, 'delivery_order_code'); - if (!deliveryOrderCode) return; // 跳过空行 - - if (!orderMap.has(deliveryOrderCode)) { - // 首次出现,记录订单头信息 - orderMap.set(deliveryOrderCode, { - headerData: { - delivery_order_code: deliveryOrderCode, - store_id: getCellValue(row, 'store_id'), - name: getCellValue(row, 'name'), - mobile: getCellValue(row, 'mobile'), - tel: getCellValue(row, 'tel'), - detail_address: getCellValue(row, 'detail_address'), - province: getCellValue(row, 'province'), - city: getCellValue(row, 'city'), - area: getCellValue(row, 'area'), - town: getCellValue(row, 'town'), - zip_code: getCellValue(row, 'zip_code'), - logistics_code: getCellValue(row, 'logistics_code'), - logistics_name: getCellValue(row, 'logistics_name'), - sys_platform_code: getCellValue(row, 'sys_platform_code'), - source_platform_code: getCellValue(row, 'source_platform_code'), - source_order_codes: getCellValue(row, 'source_order_codes'), - order_type: getCellValue(row, 'order_type'), - is_urgency: getCellValue(row, 'is_urgency'), - invoice_flag: getCellValue(row, 'invoice_flag'), - }, - items: [], - }); - orderSequence.push(deliveryOrderCode); - } - - const itemCode = getCellValue(row, 'item_code'); - if (itemCode) { - orderMap.get(deliveryOrderCode).items.push({ - item_code: itemCode, - item_name: getCellValue(row, 'item_name'), - plan_qty: getCellValue(row, 'plan_qty'), - order_line_no: getCellValue(row, 'order_line_no'), - actual_price: getCellValue(row, 'actual_price'), - }); - } - }); - - if (orderSequence.length === 0) { - throw new Error('Excel 中未找到有效数据行'); - } - - // 逐个创建订单 - const results = { - total: orderSequence.length, - success_count: 0, - fail_count: 0, - success_orders: [], - fail_orders: [], - }; - - for (const deliveryOrderCode of orderSequence) { - const { headerData, items } = orderMap.get(deliveryOrderCode); - try { - const createData = { - ...headerData, - store_id: Number(headerData.store_id) || 0, - items: items.map((item, idx) => ({ - item_code: item.item_code, - item_name: item.item_name || '', - plan_qty: Number(item.plan_qty) || 0, - order_line_no: item.order_line_no || String(idx + 1), - actual_price: Number(item.actual_price) || 0, - })), - }; - const result = await this.createOrder(createData); - results.success_count++; - results.success_orders.push({ - delivery_order_code: deliveryOrderCode, - order_id: result && result.data && result.data.order_id, - step: result && result.data && result.data.step, - step_label: result && result.data && result.data.step_label, - }); - } catch (err) { - results.fail_count++; - results.fail_orders.push({ - delivery_order_code: deliveryOrderCode, - error: err.message, - }); - } - } - - return this.success('ok', results); - } } module.exports = PendingOrderService; diff --git a/app/service/systemMethods/order/wave.js b/app/service/systemMethods/order/wave.js index 65a8006..fdde4e0 100644 --- a/app/service/systemMethods/order/wave.js +++ b/app/service/systemMethods/order/wave.js @@ -2,6 +2,7 @@ const { Op } = require('sequelize'); const OrderBaseService = require('./base'); +const runWaveStrategyQuickScanRunner = require('../../../lib/wave_strategy_quick_scan_runner'); const DEFAULT_PAGE = 1; const DEFAULT_PAGE_SIZE = 20; @@ -24,6 +25,8 @@ const WAVE_STRATEGY_QUICK_SCAN_TASK_CACHE_KEY_PREFIX = 'wave:quick-scan:task:'; const WAVE_STRATEGY_QUICK_SCAN_TASK_CACHE_TTL_SECONDS = 60 * 60 * 24; const WAVE_STRATEGY_QUICK_SCAN_WAREHOUSE_LOCK_CACHE_KEY_PREFIX = 'wave:quick-scan:lock:'; const WAVE_STRATEGY_QUICK_SCAN_WAREHOUSE_LOCK_TTL_SECONDS = 60 * 60 * 2; +const WAVE_STRATEGY_LIST_CACHE_KEY_PREFIX = 'wave:strategy-list:'; +const WAVE_STRATEGY_LIST_CACHE_TTL_SECONDS = 60 * 30; const BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_ID = 1; const BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_IDS = [ BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_ID ]; const BATCH_ALLOCATE_STORAGE_WAREHOUSE_TASK_LOCK_MAP = new Map(); @@ -45,6 +48,41 @@ const WAVE_STRATEGY_FALLBACK_WHERE_FIELD_MAP = Object.freeze({ province: 'province', sys_platform_name: 'sys_platform_name', }); +const BATCH_LIST_ASSIGNMENT_FILTER_SCHEMAS = Object.freeze({ + storage: Object.freeze({ + fieldName: 'storage_assignment_status', + enumMap: Object.freeze({ + 未分配: 'none', + 部分分配: 'partial', + 已分配: 'finished', + }), + caseInsensitive: false, + statsColumnPrefix: 'storage', + withErrorStatus: true, + }), + express: Object.freeze({ + fieldName: 'express_assignment_status', + enumMap: Object.freeze({ + unassigned: 'none', + partially_assigned: 'partial', + assigned: 'finished', + }), + caseInsensitive: true, + statsColumnPrefix: 'post', + withErrorStatus: true, + }), + print: Object.freeze({ + fieldName: 'print_assignment_status', + enumMap: Object.freeze({ + unprinted: 'none', + partially_printed: 'partial', + printed: 'finished', + }), + caseInsensitive: true, + statsColumnPrefix: 'print', + withErrorStatus: false, + }), +}); class WaveService extends OrderBaseService { /** @@ -55,9 +93,9 @@ class WaveService extends OrderBaseService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'wavePickTaskList,groupOrderFetchList,singleOrderFetchList,waveStrategyList,waveStrategyFallbackOrderList,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds,waveStrategyQuickScan,waveStrategyQuickScanTaskProgress'; - const _noNeedLog = 'wavePickTaskList,groupOrderFetchList,singleOrderFetchList,waveStrategyList,waveStrategyFallbackOrderList,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds,waveStrategyQuickScan,waveStrategyQuickScanTaskProgress'; - const _noNeedAuth = 'wavePickTaskList,groupOrderFetchList,singleOrderFetchList,waveStrategyList,waveStrategyFallbackOrderList,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds,waveStrategyQuickScan,waveStrategyQuickScanTaskProgress'; + const _noNeedRight = 'wavePickTaskCancelSelf,groupOrderFetchList,singleOrderFetchList,waveStrategyList,waveStrategyFallbackOrderList,waveStrategyFetchPda,waveStrategyFetchAdmin,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,wavePickTaskList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds,waveStrategyQuickScan,waveStrategyQuickScanTaskProgress'; + const _noNeedLog = 'groupOrderFetchList,singleOrderFetchList,waveStrategyList,waveStrategyFallbackOrderList,waveStrategyFetchPda,waveStrategyFetchAdmin,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,wavePickTaskList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds,waveStrategyQuickScan,waveStrategyQuickScanTaskProgress'; + const _noNeedAuth = 'groupOrderFetchList,singleOrderFetchList,waveStrategyList,waveStrategyFallbackOrderList,waveStrategyFetchPda,waveStrategyFetchAdmin,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,wavePickTaskList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds,waveStrategyQuickScan,waveStrategyQuickScanTaskProgress'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -658,8 +696,9 @@ class WaveService extends OrderBaseService { * @param {string} params.logisticsName 快递名称。 * @param {string} params.itemSnapshotKey 机器明细快照。 * @param {string} [params.wavePrefix] 波次编号前缀。 - * @param {string} [params.waveNo] 波次编号(传入则直接使用)。 + * @param {string} [params.waveNo] 波次编号(传入则直接使用)。 * @param {number|string} [params.waveType=1] 波次类型,仅允许 1(团购)或 2(散单),非法值回退 1。 + * @param {number|string} [params.source=0] 波次来源:0-普通波次 1-管理后台策略任务 2-PDA策略任务。 * @param {Object} params.transaction Sequelize 事务。 * @return {Promise<{waveId: number, waveNo: string}>} 创建结果。 */ @@ -675,6 +714,7 @@ class WaveService extends OrderBaseService { wavePrefix, waveNo, waveType, + source, transaction, } = {}) { const normalizedWarehouseId = Number(warehouseId || 0); @@ -688,6 +728,8 @@ class WaveService extends OrderBaseService { const normalizedWavePrefix = String(wavePrefix || '').trim() || 'B'; const normalizedWaveNoInput = String(waveNo || '').trim(); const normalizedWaveType = Number(waveType) === 2 ? 2 : 1; + const normalizedSourceInput = Number(source); + const normalizedSource = [ 0, 1, 2 ].includes(normalizedSourceInput) ? normalizedSourceInput : 0; let normalizedWaveNo = normalizedWaveNoInput; if (!normalizedWaveNo) { const datePart = this.getCurrentDatePart(); @@ -712,6 +754,7 @@ class WaveService extends OrderBaseService { item_snapshot_key, warehouse_id, creator, + source, create_time, update_time ) @@ -730,6 +773,7 @@ class WaveService extends OrderBaseService { :itemSnapshotKey, :warehouseId, :creator, + :source, NOW(), NOW() ) @@ -748,6 +792,7 @@ class WaveService extends OrderBaseService { itemSnapshotKey: normalizedItemSnapshotKey, warehouseId: Number.isInteger(normalizedWarehouseId) ? normalizedWarehouseId : 0, creator, + source: normalizedSource, }, transaction, }); @@ -770,245 +815,6 @@ class WaveService extends OrderBaseService { }; } - /** - * 按订单ID清理波次索引记录。 - * - * @param {Object} params 清理参数。 - * @param {number|string} params.warehouseId 仓库ID。 - * @param {Array|number|string} params.orderIds 订单ID集合。 - * @param {Object} params.transaction Sequelize 事务。 - * @return {Promise} 无返回值。 - */ - async deleteOrderWaveIndexByOrderIds({ warehouseId, orderIds, transaction } = {}) { - const normalizedWarehouseId = Number(warehouseId || 0); - const normalizedOrderIds = this.normalizeIdsInput(orderIds); - if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0 || normalizedOrderIds.length === 0) { - return; - } - - const deleteSql = ` - DELETE FROM wms_order_wave_index - WHERE warehouse_id = :warehouseId - AND order_id IN (:orderIds) - `; - - await this.ctx.model.query(deleteSql, { - replacements: { - warehouseId: normalizedWarehouseId, - orderIds: normalizedOrderIds, - }, - transaction, - }); - } - - /** - * 按波次ID清理波次索引记录(用于兜底)。 - * - * @param {Object} params 清理参数。 - * @param {number|string} params.warehouseId 仓库ID。 - * @param {Array|number|string} params.waveIds 波次ID集合。 - * @param {Object} params.transaction Sequelize 事务。 - * @return {Promise} 无返回值。 - */ - async deleteOrderWaveIndexByWaveIds({ warehouseId, waveIds, transaction } = {}) { - const normalizedWarehouseId = Number(warehouseId || 0); - const normalizedWaveIds = this.normalizeIdsInput(waveIds); - if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0 || normalizedWaveIds.length === 0) { - return; - } - - const deleteSql = ` - DELETE FROM wms_order_wave_index - WHERE warehouse_id = :warehouseId - AND wave_id IN (:waveIds) - `; - - await this.ctx.model.query(deleteSql, { - replacements: { - warehouseId: normalizedWarehouseId, - waveIds: normalizedWaveIds, - }, - transaction, - }); - } - - /** - * 重建订单波次索引。 - * - * 兼容历史入参校验后,统一委托按波次整批覆盖索引, - * 避免与重排流程存在两套排序规则。 - * - * @param {Object} params 重建参数。 - * @param {number|string} params.warehouseId 仓库ID。 - * @param {number|string} params.waveId 波次ID。 - * @param {Array|number|string} params.orderIds 订单ID集合。 - * @param {Object} [params.orderModel] 订单模型(可复用外层已获取模型)。 - * @param {Object} params.transaction Sequelize 事务。 - * @return {Promise} 无返回值。 - */ - async rebuildOrderWaveIndex({ warehouseId, waveId, orderIds, orderModel, transaction } = {}) { - const normalizedWarehouseId = Number(warehouseId || 0); - const normalizedWaveId = Number(waveId || 0); - const normalizedOrderIds = this.normalizeIdsInput(orderIds); - if ( - !Number.isInteger(normalizedWarehouseId) - || normalizedWarehouseId <= 0 - || !Number.isInteger(normalizedWaveId) - || normalizedWaveId <= 0 - || normalizedOrderIds.length === 0 - ) { - return; - } - await this.replaceOrderWaveIndexByWaveIds({ - warehouseId: normalizedWarehouseId, - waveIds: [ normalizedWaveId ], - orderModel, - transaction, - }); - } - - /** - * 按波次整批覆盖订单索引并返回各波次当前订单数。 - * - * 处理流程: - * 1. 查询目标波次下当前订单(按 wave_id ASC, id ASC)。 - * 2. 先按波次批量删除 wms_order_wave_index。 - * 3. 按每个波次内订单顺序重建 wave_index;platforms_index 按平台内顺序重建(同平台按 id ASC,从 1 开始)。 - * - * @param {Object} params 覆盖参数。 - * @param {number|string} params.warehouseId 仓库ID。 - * @param {Array|number|string} params.waveIds 波次ID集合。 - * @param {Object} [params.orderModel] 订单模型(可复用外层已获取模型)。 - * @param {Object} params.transaction Sequelize 事务。 - * @return {Promise>} 波次当前订单数映射。 - */ - async replaceOrderWaveIndexByWaveIds({ warehouseId, waveIds, orderModel, transaction } = {}) { - const normalizedWarehouseId = Number(warehouseId || 0); - const normalizedWaveIds = this.normalizeIdsInput(waveIds); - const currentOrderModel = orderModel || await this.getOrderModel('pendingOrder', normalizedWarehouseId); - - if ( - !Number.isInteger(normalizedWarehouseId) - || normalizedWarehouseId <= 0 - || normalizedWaveIds.length === 0 - || !currentOrderModel - || typeof currentOrderModel.findAll !== 'function' - ) { - return new Map(); - } - - const orderRows = await currentOrderModel.findAll({ - attributes: [ 'id', 'wave_id', 'sys_platform_code', 'source_platform_code' ], - where: { - wave_id: { - [Op.in]: normalizedWaveIds, - [Op.gt]: 0, - }, - }, - order: [[ 'wave_id', 'ASC' ], [ 'id', 'ASC' ]], - raw: true, - transaction, - }); - - const orderRowsList = Array.isArray(orderRows) ? orderRows : []; - const waveOrderRowsMap = new Map(normalizedWaveIds.map(waveId => [ waveId, []])); - for (const row of orderRowsList) { - const waveId = Number(row && row.wave_id || 0); - const orderId = Number(row && row.id || 0); - if (!Number.isInteger(waveId) || waveId <= 0 || !waveOrderRowsMap.has(waveId)) { - continue; - } - if (!Number.isInteger(orderId) || orderId <= 0) { - continue; - } - - waveOrderRowsMap.get(waveId).push({ - id: orderId, - sys_platform_code: String(row && row.sys_platform_code || ''), - source_platform_code: String(row && row.source_platform_code || ''), - }); - } - - await this.deleteOrderWaveIndexByWaveIds({ - warehouseId: normalizedWarehouseId, - waveIds: normalizedWaveIds, - transaction, - }); - - const valueSqlList = []; - const replacements = { - warehouseId: normalizedWarehouseId, - }; - - let rowIndex = 0; - for (const waveId of normalizedWaveIds) { - const orderRowsByWave = waveOrderRowsMap.get(waveId) || []; - const platformsIndexMap = new Map(); - const platformSequenceMap = new Map(); - for (const orderRow of orderRowsByWave) { - const currentOrderId = Number(orderRow && orderRow.id || 0); - if (!Number.isInteger(currentOrderId) || currentOrderId <= 0) { - continue; - } - - const platformKey = String( - (orderRow && orderRow.sys_platform_code) - || (orderRow && orderRow.source_platform_code) - || '' - ).trim().toLowerCase(); - const nextPlatformSequence = Number(platformSequenceMap.get(platformKey) || 0) + 1; - platformSequenceMap.set(platformKey, nextPlatformSequence); - platformsIndexMap.set(currentOrderId, nextPlatformSequence); - } - - for (const [ orderIndex, orderRow ] of orderRowsByWave.entries()) { - const orderId = Number(orderRow && orderRow.id || 0); - if (!Number.isInteger(orderId) || orderId <= 0) { - continue; - } - const waveSequence = orderIndex + 1; - const platformsSequence = Number(platformsIndexMap.get(orderId) || waveSequence); - valueSqlList.push( - `(:warehouseId, :orderId_${rowIndex}, :waveId_${rowIndex}, :waveIndex_${rowIndex}, :platformsIndex_${rowIndex}, NOW())` - ); - replacements[`orderId_${rowIndex}`] = orderId; - replacements[`waveId_${rowIndex}`] = waveId; - replacements[`waveIndex_${rowIndex}`] = waveSequence; - replacements[`platformsIndex_${rowIndex}`] = platformsSequence; - rowIndex += 1; - } - } - - if (valueSqlList.length > 0) { - const insertSql = ` - INSERT INTO wms_order_wave_index - ( - warehouse_id, - order_id, - wave_id, - wave_index, - platforms_index, - create_at - ) - VALUES - ${valueSqlList.join(',\n ')} - `; - - await this.ctx.model.query(insertSql, { - replacements, - transaction, - }); - } - - const totalOrdersMap = new Map(); - for (const waveId of normalizedWaveIds) { - const orderRowsByWave = waveOrderRowsMap.get(waveId) || []; - totalOrdersMap.set(waveId, orderRowsByWave.length); - } - - return totalOrdersMap; - } - /** * 构建抓取候选订单筛选条件。 * @@ -1048,6 +854,7 @@ class WaveService extends OrderBaseService { * @param {number} [minGroupOrderFetchQuantity=13] 最小团购抓取数量。 * @param {Object} [options={}] 额外抓取选项。 * @param {number} [options.maxFetchQuantity=0] 本结构最大抓取订单数上限,0 表示不限制。 + * @param {number|string} [options.source=0] 波次来源:0-普通波次 1-管理后台策略任务 2-PDA策略任务。 * @return {Promise} 单结构抓取结果。 */ async fetchSingleStructure( @@ -1066,6 +873,8 @@ class WaveService extends OrderBaseService { && Number(normalizedOptions.maxFetchQuantity) > 0 ? Number(normalizedOptions.maxFetchQuantity) : 0; + const normalizedSourceInput = Number(normalizedOptions.source); + const normalizedSource = [ 0, 1, 2 ].includes(normalizedSourceInput) ? normalizedSourceInput : 0; const normalizedMinGroupOrderFetchQuantity = Number.isInteger(Number(minGroupOrderFetchQuantity)) && Number(minGroupOrderFetchQuantity) > 0 ? Number(minGroupOrderFetchQuantity) @@ -1124,6 +933,7 @@ class WaveService extends OrderBaseService { logisticsName: structure.logistics_name, itemSnapshotKey: structure.item_snapshot_key, wavePrefix, + source: normalizedSource, transaction, }); const orderFlagExpression = this.app.Sequelize.literal(`CASE @@ -1190,14 +1000,6 @@ class WaveService extends OrderBaseService { }); } - await this.rebuildOrderWaveIndex({ - warehouseId, - waveId, - orderIds: grabbedOrderIds, - orderModel: model, - transaction, - }); - allWaveIds.push(waveId); allOrderIds.push(...grabbedOrderIds); fetchedOrderLogItems.push(...grabbedOrderIds.map(orderId => ({ @@ -1222,6 +1024,10 @@ class WaveService extends OrderBaseService { }); const mergedOrderIds = [ ...new Set(allOrderIds) ].sort((a, b) => a - b); + this.enqueueWaveStrategyQuickScanPostOrderChange(warehouseId, mergedOrderIds, { + triggerScan: false, + source: 'fetchSingleStructure', + }); let reason = stopReason; if (!reason && totalFetchedQuantity > 0 && totalFetchedQuantity < requestedQuantity) { reason = '可抓取订单不足'; @@ -1406,63 +1212,64 @@ class WaveService extends OrderBaseService { * @return {string} 规范化后的筛选值,未传时返回空字符串。 */ normalizeBatchListStorageAssignmentStatusFilter(value) { - if (value === undefined || value === null || value === '') { - return ''; - } - - const normalizedValue = String(value).trim(); - if (!normalizedValue) { - return ''; - } - - const allowedValues = [ '未分配', '部分分配', '已分配' ]; - if (!allowedValues.includes(normalizedValue)) { - throw new Error(`storage_assignment_status 参数不合法,仅支持: ${allowedValues.join('、')}`); - } - - return normalizedValue; + return this.normalizeBatchListAssignmentStatusFilterByType(value, 'storage'); } /** - * 规范化波次列表快递分配状态筛选值。 + * 规范化波次列表快递分配状态筛选值(英文枚举)。 * * @param {string} value 入参筛选值。 * @return {string} 规范化后的筛选值,未传时返回空字符串。 */ normalizeBatchListExpressAssignmentStatusFilter(value) { - if (value === undefined || value === null || value === '') { - return ''; - } - - const normalizedValue = String(value).trim(); - if (!normalizedValue) { - return ''; - } - - const allowedValueMap = { - unassigned: '未分配', - partially_assigned: '部分分配', - assigned: '已分配', - }; - if (allowedValueMap[normalizedValue]) { - return allowedValueMap[normalizedValue]; - } - - const allowedValues = [ '未分配', '部分分配', '已分配' ]; - if (!allowedValues.includes(normalizedValue)) { - throw new Error('express_assignment_status 参数不合法,仅支持: unassigned、partially_assigned、assigned'); - } - - return normalizedValue; + return this.normalizeBatchListAssignmentStatusFilterByType(value, 'express'); } /** - * 规范化波次列表打印状态筛选值。 + * 规范化波次列表打印状态筛选值(英文枚举)。 * * @param {string} value 入参筛选值。 * @return {string} 规范化后的筛选值,未传时返回空字符串。 */ normalizeBatchListPrintAssignmentStatusFilter(value) { + return this.normalizeBatchListAssignmentStatusFilterByType(value, 'print'); + } + + /** + * 根据类型获取波次分配状态筛选配置。 + * + * @param {'storage'|'express'|'print'} type 筛选类型。 + * @return {{ fieldName: string, enumMap: Object, caseInsensitive: boolean, statsColumnPrefix: string, withErrorStatus: boolean }} 筛选配置。 + */ + getBatchListAssignmentFilterSchema(type) { + const normalizedType = String(type || '').trim(); + const schema = BATCH_LIST_ASSIGNMENT_FILTER_SCHEMAS[normalizedType]; + if (!schema) { + throw new Error(`不支持的分配状态筛选类型: ${normalizedType}`); + } + return schema; + } + + /** + * 按类型规范化波次列表分配状态筛选值。 + * + * @param {string} value 入参筛选值。 + * @param {'storage'|'express'|'print'} type 筛选类型。 + * @return {string} 规范化后的筛选值,未传时返回空字符串。 + */ + normalizeBatchListAssignmentStatusFilterByType(value, type) { + const schema = this.getBatchListAssignmentFilterSchema(type); + return this.normalizeBatchListAssignmentStatusFilter(value, schema); + } + + /** + * 规范化波次列表分配状态筛选值。 + * + * @param {string} value 入参筛选值。 + * @param {{ fieldName: string, enumMap: Object, caseInsensitive: boolean }} schema 筛选配置。 + * @return {string} 规范化后的筛选标识(none/partial/finished)。 + */ + normalizeBatchListAssignmentStatusFilter(value, schema) { if (value === undefined || value === null || value === '') { return ''; } @@ -1472,21 +1279,23 @@ class WaveService extends OrderBaseService { return ''; } - const allowedValueMap = { - unprinted: '未打印', - partially_printed: '部分打印', - printed: '已打印', - }; - if (allowedValueMap[normalizedValue]) { - return allowedValueMap[normalizedValue]; + const enumMap = this.isPlainObject(schema && schema.enumMap) ? schema.enumMap : {}; + const allowedValues = Object.keys(enumMap); + const isCaseInsensitive = Boolean(schema && schema.caseInsensitive); + const lookupValue = isCaseInsensitive ? normalizedValue.toLowerCase() : normalizedValue; + const normalizedEnumMap = isCaseInsensitive + ? Object.fromEntries( + Object.entries(enumMap).map(([ key, mappedValue ]) => [ String(key).toLowerCase(), mappedValue ]) + ) + : enumMap; + const matchedValue = normalizedEnumMap[lookupValue]; + + if (!matchedValue) { + const fieldName = String(schema && schema.fieldName || 'assignment_status'); + throw new Error(`${fieldName} 参数不合法,仅支持: ${allowedValues.join('、')}`); } - const allowedValues = [ '未打印', '部分打印', '已打印' ]; - if (!allowedValues.includes(normalizedValue)) { - throw new Error('print_assignment_status 参数不合法,仅支持: unprinted、partially_printed、printed'); - } - - return normalizedValue; + return matchedValue; } /** @@ -1530,109 +1339,50 @@ class WaveService extends OrderBaseService { * @return {{ sql: string, replacements: Object }} SQL 条件片段与参数。 */ buildBatchListStorageAssignmentFilterClause(statusFilter = '') { - const normalizedStatusFilter = this.normalizeBatchListStorageAssignmentStatusFilter(statusFilter); - if (!normalizedStatusFilter) { - return { - sql: '', - replacements: {}, - }; - } - - const totalExpr = 'COALESCE(wave_order_stats.order_total, 0)'; - const storageNoneExpr = 'COALESCE(wave_order_stats.storage_none_count, 0)'; - const storageFinExpr = 'COALESCE(wave_order_stats.storage_fin_count, 0)'; - const storageErrorExpr = 'COALESCE(wave_order_stats.storage_error_count, 0)'; - let whereClause = ''; - - if (normalizedStatusFilter === '已分配') { - whereClause = ` - ${storageFinExpr} = ${totalExpr} - AND ${totalExpr} > 0 - `; - } else if (normalizedStatusFilter === '部分分配') { - whereClause = ` - ${storageErrorExpr} = 0 - AND ${storageNoneExpr} <> ${totalExpr} - AND ${storageFinExpr} <> ${totalExpr} - `; - } else if (normalizedStatusFilter === '未分配') { - return { - sql: ` - AND ( - ${totalExpr} = 0 - OR ${storageErrorExpr} > 0 - OR ${storageNoneExpr} = ${totalExpr} - )`, - replacements: {}, - }; - } - - return { - sql: ` - AND ${whereClause}`, - replacements: {}, - }; + return this.buildBatchListAssignmentStatusFilterClauseByType(statusFilter, 'storage'); } /** * 构建波次列表快递分配状态筛选 SQL 条件。 * - * @param {string} statusFilter 快递分配状态筛选值。 + * @param {string} statusFilter 快递分配状态筛选值(none/partial/finished)。 * @return {{ sql: string, replacements: Object }} SQL 条件片段与参数。 */ buildBatchListExpressAssignmentFilterClause(statusFilter = '') { - const normalizedStatusFilter = this.normalizeBatchListExpressAssignmentStatusFilter(statusFilter); - if (!normalizedStatusFilter) { - return { - sql: '', - replacements: {}, - }; - } - - const totalExpr = 'COALESCE(wave_order_stats.order_total, 0)'; - const expressNoneExpr = 'COALESCE(wave_order_stats.post_none_count, 0)'; - const expressFinExpr = 'COALESCE(wave_order_stats.post_fin_count, 0)'; - const expressErrorExpr = 'COALESCE(wave_order_stats.post_error_count, 0)'; - let whereClause = ''; - - if (normalizedStatusFilter === '已分配') { - whereClause = ` - ${expressFinExpr} = ${totalExpr} - AND ${totalExpr} > 0 - `; - } else if (normalizedStatusFilter === '部分分配') { - whereClause = ` - ${expressErrorExpr} = 0 - AND ${expressNoneExpr} <> ${totalExpr} - AND ${expressFinExpr} <> ${totalExpr} - `; - } else if (normalizedStatusFilter === '未分配') { - return { - sql: ` - AND ( - ${totalExpr} = 0 - OR ${expressErrorExpr} > 0 - OR ${expressNoneExpr} = ${totalExpr} - )`, - replacements: {}, - }; - } - - return { - sql: ` - AND ${whereClause}`, - replacements: {}, - }; + return this.buildBatchListAssignmentStatusFilterClauseByType(statusFilter, 'express'); } /** * 构建波次列表打印状态筛选 SQL 条件。 * - * @param {string} statusFilter 打印状态筛选值。 + * @param {string} statusFilter 打印状态筛选值(none/partial/finished)。 * @return {{ sql: string, replacements: Object }} SQL 条件片段与参数。 */ buildBatchListPrintAssignmentFilterClause(statusFilter = '') { - const normalizedStatusFilter = this.normalizeBatchListPrintAssignmentStatusFilter(statusFilter); + return this.buildBatchListAssignmentStatusFilterClauseByType(statusFilter, 'print'); + } + + /** + * 按类型构建波次列表分配状态筛选 SQL 条件。 + * + * @param {string} statusFilter 分配状态筛选值(none/partial/finished)。 + * @param {'storage'|'express'|'print'} type 筛选类型。 + * @return {{ sql: string, replacements: Object }} SQL 条件片段与参数。 + */ + buildBatchListAssignmentStatusFilterClauseByType(statusFilter = '', type = 'storage') { + const schema = this.getBatchListAssignmentFilterSchema(type); + return this.buildBatchListAssignmentStatusFilterClause(statusFilter, schema); + } + + /** + * 构建波次列表分配状态筛选 SQL 条件(通用)。 + * + * @param {string} statusFilter 分配状态筛选值(none/partial/finished)。 + * @param {{ statsColumnPrefix: string, withErrorStatus: boolean }} schema 筛选配置。 + * @return {{ sql: string, replacements: Object }} SQL 条件片段与参数。 + */ + buildBatchListAssignmentStatusFilterClause(statusFilter = '', schema = {}) { + const normalizedStatusFilter = String(statusFilter || '').trim(); if (!normalizedStatusFilter) { return { sql: '', @@ -1640,44 +1390,54 @@ class WaveService extends OrderBaseService { }; } - const totalExpr = 'COALESCE(wave_order_stats.order_total, 0)'; - const printNoneExpr = 'COALESCE(wave_order_stats.print_none_count, 0)'; - const printFinExpr = 'COALESCE(wave_order_stats.print_fin_count, 0)'; - let whereClause = ''; + const statsPrefix = String(schema && schema.statsColumnPrefix || '').trim(); + if (!statsPrefix) { + throw new Error('分配状态筛选配置不完整,缺少统计字段前缀'); + } - if (normalizedStatusFilter === '已打印') { - whereClause = ` - ${printFinExpr} = ${totalExpr} - AND ${totalExpr} > 0 - `; - } else if (normalizedStatusFilter === '部分打印') { - whereClause = ` - ${printNoneExpr} <> ${totalExpr} - AND ${printFinExpr} <> ${totalExpr} - `; - } else if (normalizedStatusFilter === '未打印') { + const totalExpr = 'COALESCE(wave_order_stats.order_total, 0)'; + const noneExpr = `COALESCE(wave_order_stats.${statsPrefix}_none_count, 0)`; + const finExpr = `COALESCE(wave_order_stats.${statsPrefix}_fin_count, 0)`; + const withErrorStatus = Boolean(schema && schema.withErrorStatus); + const errorExpr = withErrorStatus ? `COALESCE(wave_order_stats.${statsPrefix}_error_count, 0)` : ''; + + if (normalizedStatusFilter === 'finished') { + return { + sql: ` + AND ${finExpr} = ${totalExpr} + AND ${totalExpr} > 0`, + replacements: {}, + }; + } + + if (normalizedStatusFilter === 'partial') { + return { + sql: ` + AND ${withErrorStatus ? `${errorExpr} = 0\n AND ` : ''}${noneExpr} <> ${totalExpr} + AND ${finExpr} <> ${totalExpr}`, + replacements: {}, + }; + } + + if (normalizedStatusFilter === 'none') { return { sql: ` AND ( ${totalExpr} = 0 - OR ${printNoneExpr} = ${totalExpr} + ${withErrorStatus ? `OR ${errorExpr} > 0\n ` : ''}OR ${noneExpr} = ${totalExpr} )`, replacements: {}, }; } - return { - sql: ` - AND ${whereClause}`, - replacements: {}, - }; + throw new Error(`不支持的分配状态筛选值: ${normalizedStatusFilter}`); } /** * 构建波次列表 where 条件(白名单字段)。 * - * @param {Object} whereData 查询 where 入参。 - * @return {{ sql: string, replacements: Object, storageAssignmentStatus: string, expressAssignmentStatus: string, printAssignmentStatus: string }} SQL 条件片段、参数与分配状态筛选值。 + * @param {Object} whereData 查询 where 入参。 + * @return {{ sql: string, replacements: Object, storageAssignmentStatus: string, expressAssignmentStatus: string, printAssignmentStatus: string }} SQL 条件片段、参数与分配状态筛选值。 */ buildBatchListWhereClause(whereData = {}) { const normalizedWhere = this.isPlainObject(whereData) ? whereData : {}; @@ -1692,7 +1452,6 @@ class WaveService extends OrderBaseService { 'wave_no', 'wave_type', 'wave_status', - 'source', 'creator', 'logistics_name', 'item_part_type', @@ -1700,6 +1459,7 @@ class WaveService extends OrderBaseService { 'item_snapshot_key', 'item_detail_machine', 'distinguish_express', + 'source', 'total_orders_min', 'total_orders_max', 'processed_orders_min', @@ -1782,16 +1542,7 @@ class WaveService extends OrderBaseService { appendLikeCondition('wave_no', 'wave_no', 'whereWaveNo'); appendIntegerEqualCondition('wave_type', 'wave_type', 'whereWaveType'); appendIntegerEqualCondition('wave_status', 'wave_status', 'whereWaveStatus'); - const source = normalizedWhere.source; - if (source !== undefined && source !== null && source !== '') { - const normalizedSource = Number(source); - if (!Number.isInteger(normalizedSource) || ![ 0, 1, 2 ].includes(normalizedSource)) { - throw new Error('source 参数不合法'); - } - - conditions.push('source = :whereSource'); - replacements.whereSource = normalizedSource; - } + appendIntegerEqualCondition('source', 'source', 'whereSource', true); appendLikeCondition('creator', 'creator', 'whereCreator'); appendLikeCondition('logistics_name', 'logistics_name', 'whereLogisticsName'); appendLikeCondition('item_part', 'item_part', 'whereItemPart'); @@ -1859,218 +1610,6 @@ class WaveService extends OrderBaseService { }; } - /** - * 解析分配状态。 - * - * @param {number} total 总数量。 - * @param {number} noneCount 未分配数量。 - * @param {number} finCount 已分配数量。 - * @param {number} errorCount 分配异常数量。 - * @param {{ none?: string, partial?: string, finished?: string, error?: string }} [labels] 状态文案映射。 - * @return {string} 分配状态。 - */ - resolveAssignmentStatus(total, noneCount, finCount, errorCount = 0, labels = {}) { - const normalizedTotal = Number(total || 0); - const normalizedNoneCount = Number(noneCount || 0); - const normalizedFinCount = Number(finCount || 0); - const normalizedErrorCount = Number(errorCount || 0); - const normalizedLabels = labels && typeof labels === 'object' ? labels : {}; - const noneLabel = String(normalizedLabels.none || '未分配'); - const partialLabel = String(normalizedLabels.partial || '部分分配'); - const finishedLabel = String(normalizedLabels.finished || '已分配'); - const errorLabel = String(normalizedLabels.error || '分配异常'); - - if (normalizedErrorCount > 0) { - return errorLabel; - } - - if (normalizedTotal <= 0 || normalizedNoneCount === normalizedTotal) { - return noneLabel; - } - - if (normalizedFinCount === normalizedTotal) { - return finishedLabel; - } - - return partialLabel; - } - - normalizeSkuText(value) { - if (value === undefined || value === null) { - return ''; - } - - return String(value).trim(); - } - - normalizeShopName(value) { - if (value === undefined || value === null) { - return ''; - } - - return String(value).trim(); - } - - parseItemSnapshot(rawSnapshot) { - if (!rawSnapshot) { - return {}; - } - - if (typeof rawSnapshot === 'string') { - try { - const parsed = JSON.parse(rawSnapshot); - return parsed && typeof parsed === 'object' ? parsed : {}; - } catch { - return {}; - } - } - - return typeof rawSnapshot === 'object' ? rawSnapshot : {}; - } - - normalizeOrderItemRow(row = {}) { - const snapshot = this.parseItemSnapshot(row.item_snapshot); - const stockIdRaw = snapshot.stock_id ?? row.stock_id; - const quantityRaw = row.plan_qty; - - const stockId = Number(stockIdRaw || 0); - const quantity = Number(quantityRaw || 0); - - return { - stock_id: Number.isInteger(stockId) && stockId > 0 ? stockId : 0, - item_code: String(snapshot.item_code ?? row.item_code ?? '').trim(), - item_name: String(snapshot.item_name ?? row.item_name ?? '').trim(), - barcode: String(snapshot.barcode ?? '').trim(), - quantity: Number.isFinite(quantity) && quantity > 0 ? quantity : 0, - }; - } - /** - * 拣货任务列表查询。 - * - * 基于 wms_wave_pick_task 主表按当前仓库维度分页查询,默认按 create_time 倒序。 - * - * @param {Object} [data={}] 请求参数。 - * @param {number|string} [data.page] 页码(兼容 current)。 - * @param {number|string} [data.pageSize] 每页数量(兼容 size/page_size)。 - * @param {Object} [data.where] 查询过滤。 - * @return {Promise} 列表与分页结果。 - */ - async wavePickTaskList(data = {}) { - try { - const requestData = this.isPlainObject(data) ? data : {}; - const { page, pageSize } = this.normalizeWavePickTaskListPagination(requestData); - const normalizedRequest = this.normalizeWavePickTaskListRequest(requestData); - const warehouseId = normalizedRequest.warehouseId; - const whereClause = this.buildWavePickTaskListWhereClause(normalizedRequest.where); - const offset = (page - 1) * pageSize; - - const listSql = ` - SELECT - t.id, - t.task_no, - t.warehouse_id, - t.pick_mode, - t.status, - t.review_status, - t.source, - t.wave_count, - t.order_count, - t.box_count, - t.pick_user_id, - t.pick_user_name, - t.review_user_id, - t.review_user_name, - t.current_cart_id, - t.current_cart_code_snapshot, - t.batch_no, - t.device_id, - t.start_time, - t.finish_time, - t.review_start_time, - t.review_finish_time, - t.create_time, - t.update_time - FROM wms_wave_pick_task t - WHERE t.warehouse_id = :warehouseId - ${whereClause.sql} - ORDER BY t.create_time DESC - LIMIT :limit OFFSET :offset - `; - - const countSql = ` - SELECT COUNT(1) AS total - FROM wms_wave_pick_task t - WHERE t.warehouse_id = :warehouseId - ${whereClause.sql} - `; - - const replacements = { - warehouseId, - ...whereClause.replacements, - }; - - const [ listRows, countRows ] = await Promise.all([ - this.ctx.model.query(listSql, { - replacements: { - ...replacements, - limit: pageSize, - offset, - }, - }), - this.ctx.model.query(countSql, { - replacements, - }), - ]); - - const sourceList = Array.isArray(listRows && listRows[0]) ? listRows[0] : []; - const totalRowList = Array.isArray(countRows && countRows[0]) ? countRows[0] : []; - const total = Number(totalRowList[0] && totalRowList[0].total || 0); - - const list = sourceList.map(item => ({ - task_id: Number(item && item.id || 0), - task_no: String(item && item.task_no || '').trim(), - warehouse_id: Number(item && item.warehouse_id || 0), - pick_mode: Number(item && item.pick_mode || 0), - status: Number(item && item.status || 0), - review_status: Number(item && item.review_status || 0), - source: Number(item && item.source || 0), - wave_count: Number(item && item.wave_count || 0), - order_count: Number(item && item.order_count || 0), - box_count: Number(item && item.box_count || 0), - pick_user_id: Number(item && item.pick_user_id || 0), - pick_user_name: String(item && item.pick_user_name || '').trim(), - operator_id: Number(item && item.pick_user_id || 0), - operator_name: String(item && item.pick_user_name || '').trim(), - review_user_id: Number(item && item.review_user_id || 0), - review_user_name: String(item && item.review_user_name || '').trim(), - current_cart_id: Number(item && item.current_cart_id || 0), - current_cart_code_snapshot: String(item && item.current_cart_code_snapshot || '').trim(), - batch_no: String(item && item.batch_no || '').trim(), - device_id: String(item && item.device_id || '').trim(), - start_time: item && item.start_time || null, - start_at: item && item.start_time || null, - finish_time: item && item.finish_time || null, - finish_at: item && item.finish_time || null, - review_start_time: item && item.review_start_time || null, - review_finish_time: item && item.review_finish_time || null, - create_time: item && item.create_time || null, - created_at: item && item.create_time || null, - update_time: item && item.update_time || null, - })); - - return this.success('ok', { - list, - total, - page, - page_size: pageSize, - }); - } catch (error) { - const errorMessage = String(error && error.message || '').trim(); - const isBadRequest = /参数|上下文/.test(errorMessage); - return this.fail(`查询拣货任务列表失败: ${errorMessage || '未知错误'}`, isBadRequest ? 400 : 500); - } - } - /** * 解析拣货任务列表分页参数。 * @@ -2094,87 +1633,6 @@ class WaveService extends OrderBaseService { }); } - - mergeOrderItemDetails(itemRows = []) { - const merged = new Map(); - - for (const row of itemRows) { - const normalized = this.normalizeOrderItemRow(row); - if (!normalized.item_code || normalized.quantity <= 0) { - continue; - } - - const key = [ - normalized.stock_id, - normalized.item_code, - normalized.item_name, - normalized.barcode, - ].join('||'); - - if (!merged.has(key)) { - merged.set(key, { - stock_id: normalized.stock_id, - item_code: normalized.item_code, - item_name: normalized.item_name, - barcode: normalized.barcode, - quantity: 0, - }); - } - - merged.get(key).quantity += normalized.quantity; - } - - return Array.from(merged.values()) - .sort((a, b) => { - if (a.stock_id !== b.stock_id) return a.stock_id - b.stock_id; - return String(a.item_code).localeCompare(String(b.item_code)); - }); - } - - buildItemSummary(itemDetails = []) { - if (!Array.isArray(itemDetails) || itemDetails.length === 0) { - return ''; - } - - return itemDetails - .map(item => { - const name = String(item.item_name || '').trim(); - const barcode = String(item.barcode || item.item_code || '').trim(); - const qty = item.quantity; - return `${name}${barcode ? `(${barcode})` : ''}×${qty}`; - }) - .join(' | '); - } - - /** - * 构建订单商品快照字符串。 - * - * 输出格式:商品名称1*数量|商品名称2*数量。 - * - * @param {Array} itemDetails 商品明细列表。 - * @return {string} 商品快照字符串。 - */ - buildOrderItemSnapshot(itemDetails = []) { - if (!Array.isArray(itemDetails) || itemDetails.length === 0) { - return ''; - } - - const segments = itemDetails - .map(item => { - const itemName = String(item && (item.item_name || item.item_code) || '').trim(); - const quantity = Number(item && item.quantity || 0); - if (!itemName || !Number.isFinite(quantity) || quantity <= 0) { - return ''; - } - - return `${itemName}*${quantity}`; - }) - .filter(Boolean); - - return segments.join('|'); - } - - /** * 归一化拣货任务列表请求参数。 * @@ -2364,6 +1822,171 @@ class WaveService extends OrderBaseService { }; } + /** + * 解析分配状态。 + * + * @param {number} total 总数量。 + * @param {number} noneCount 未分配数量。 + * @param {number} finCount 已分配数量。 + * @param {number} errorCount 分配异常数量。 + * @param {{ none?: string, partial?: string, finished?: string, error?: string }} [labels] 状态文案映射。 + * @return {string} 分配状态。 + */ + resolveAssignmentStatus(total, noneCount, finCount, errorCount = 0, labels = {}) { + const normalizedTotal = Number(total || 0); + const normalizedNoneCount = Number(noneCount || 0); + const normalizedFinCount = Number(finCount || 0); + const normalizedErrorCount = Number(errorCount || 0); + const normalizedLabels = labels && typeof labels === 'object' ? labels : {}; + const noneLabel = String(normalizedLabels.none || '未分配'); + const partialLabel = String(normalizedLabels.partial || '部分分配'); + const finishedLabel = String(normalizedLabels.finished || '已分配'); + const errorLabel = String(normalizedLabels.error || '分配异常'); + + if (normalizedErrorCount > 0) { + return errorLabel; + } + + if (normalizedTotal <= 0 || normalizedNoneCount === normalizedTotal) { + return noneLabel; + } + + if (normalizedFinCount === normalizedTotal) { + return finishedLabel; + } + + return partialLabel; + } + + normalizeSkuText(value) { + if (value === undefined || value === null) { + return ''; + } + + return String(value).trim(); + } + + normalizeShopName(value) { + if (value === undefined || value === null) { + return ''; + } + + return String(value).trim(); + } + + parseItemSnapshot(rawSnapshot) { + if (!rawSnapshot) { + return {}; + } + + if (typeof rawSnapshot === 'string') { + try { + const parsed = JSON.parse(rawSnapshot); + return parsed && typeof parsed === 'object' ? parsed : {}; + } catch { + return {}; + } + } + + return typeof rawSnapshot === 'object' ? rawSnapshot : {}; + } + + normalizeOrderItemRow(row = {}) { + const snapshot = this.parseItemSnapshot(row.item_snapshot); + const stockIdRaw = snapshot.stock_id ?? row.stock_id; + const quantityRaw = row.plan_qty; + + const stockId = Number(stockIdRaw || 0); + const quantity = Number(quantityRaw || 0); + + return { + stock_id: Number.isInteger(stockId) && stockId > 0 ? stockId : 0, + item_code: String(snapshot.item_code ?? row.item_code ?? '').trim(), + item_name: String(snapshot.item_name ?? row.item_name ?? '').trim(), + barcode: String(snapshot.barcode ?? '').trim(), + quantity: Number.isFinite(quantity) && quantity > 0 ? quantity : 0, + }; + } + + mergeOrderItemDetails(itemRows = []) { + const merged = new Map(); + + for (const row of itemRows) { + const normalized = this.normalizeOrderItemRow(row); + if (!normalized.item_code || normalized.quantity <= 0) { + continue; + } + + const key = [ + normalized.stock_id, + normalized.item_code, + normalized.item_name, + normalized.barcode, + ].join('||'); + + if (!merged.has(key)) { + merged.set(key, { + stock_id: normalized.stock_id, + item_code: normalized.item_code, + item_name: normalized.item_name, + barcode: normalized.barcode, + quantity: 0, + }); + } + + merged.get(key).quantity += normalized.quantity; + } + + return Array.from(merged.values()) + .sort((a, b) => { + if (a.stock_id !== b.stock_id) return a.stock_id - b.stock_id; + return String(a.item_code).localeCompare(String(b.item_code)); + }); + } + + buildItemSummary(itemDetails = []) { + if (!Array.isArray(itemDetails) || itemDetails.length === 0) { + return ''; + } + + return itemDetails + .map(item => { + const name = String(item.item_name || '').trim(); + const barcode = String(item.barcode || item.item_code || '').trim(); + const qty = item.quantity; + return `${name}${barcode ? `(${barcode})` : ''}×${qty}`; + }) + .join(' | '); + } + + /** + * 构建订单商品快照字符串。 + * + * 输出格式:商品名称1*数量|商品名称2*数量。 + * + * @param {Array} itemDetails 商品明细列表。 + * @return {string} 商品快照字符串。 + */ + buildOrderItemSnapshot(itemDetails = []) { + if (!Array.isArray(itemDetails) || itemDetails.length === 0) { + return ''; + } + + const segments = itemDetails + .map(item => { + const itemName = String(item && (item.item_name || item.item_code) || '').trim(); + const quantity = Number(item && item.quantity || 0); + if (!itemName || !Number.isFinite(quantity) || quantity <= 0) { + return ''; + } + + return `${itemName}*${quantity}`; + }) + .filter(Boolean); + + return segments.join('|'); + } + buildItemSnapshotKey(itemDetails = []) { if (!Array.isArray(itemDetails) || itemDetails.length === 0) { return ''; @@ -2919,6 +2542,18 @@ class WaveService extends OrderBaseService { */ async waveStrategyList(data = {}) { const requestData = this.isPlainObject(data) ? data : {}; + const rawType = requestData.strategy_type ?? requestData?.where?.strategy_type; + let normalizedStrategyType; + if (rawType !== undefined && rawType !== null && `${rawType}` !== '') { + normalizedStrategyType = Number(rawType); + if (![ 1, 2 ].includes(normalizedStrategyType)) { + throw new Error('strategy_type 仅支持 1(散单) 或 2(团购)'); + } + } + const calculateNextFetchOrderCount = Number( + requestData.calculate_next_fetch_order_count ?? requestData.calculateNextFetchOrderCount ?? 0 + ) === 1; + const debugEnabled = Number(requestData.debug ?? 0) === 1; const { page, pageSize } = this.normalizePagination(requestData); const contextWarehouseId = Number(this.getWarehouseId() || 0); if (!Number.isInteger(contextWarehouseId) || contextWarehouseId <= 0) { @@ -2931,10 +2566,15 @@ class WaveService extends OrderBaseService { } const offset = (page - 1) * pageSize; + const where = { + warehouse_id: contextWarehouseId, + }; + if (normalizedStrategyType !== undefined) { + where.strategy_type = normalizedStrategyType; + } + const queryResult = await strategyModel.findAndCountAll({ - where: { - warehouse_id: contextWarehouseId, - }, + where, order: [ [ 'status', 'DESC' ], [ 'id', 'DESC' ], @@ -2945,11 +2585,40 @@ class WaveService extends OrderBaseService { }); const list = Array.isArray(queryResult && queryResult.rows) ? queryResult.rows : []; + const strategyIds = [ ...new Set(list + .map(item => Number(item && item.id || 0)) + .filter(item => Number.isInteger(item) && item > 0)) ]; + const matchedOrderCountMap = await this.getWaveStrategyMatchedOrderCountFilteredMap( + contextWarehouseId, + strategyIds + ); + const nextFetchOrderCountMap = calculateNextFetchOrderCount + ? await this.getWaveStrategyNextFetchOrderCountMap(contextWarehouseId, list) + : new Map(); + const debugFetchOrderListMap = debugEnabled + ? await this.getWaveStrategyDebugFetchOrderListMap(contextWarehouseId, list) + : new Map(); + const mergedList = list.map(item => { + const strategyId = Number(item && item.id || 0); + const debugRow = debugEnabled ? (debugFetchOrderListMap.get(strategyId) || null) : null; + return { + ...item, + matched_order_count_filtered: Number( + matchedOrderCountMap.get(strategyId) || 0 + ), + next_fetch_order_count: calculateNextFetchOrderCount + ? Number(nextFetchOrderCountMap.get(strategyId) || 0) + : 0, + ...(debugEnabled && debugRow ? { + next_fetch_order_list: debugRow, + } : {}), + }; + }); const total = Number(queryResult && queryResult.count || 0); const totalPages = pageSize > 0 ? Math.ceil(total / pageSize) : 0; return this.success('ok', { - list, + list: mergedList, pagination: { page, pageSize, @@ -2961,6 +2630,366 @@ class WaveService extends OrderBaseService { }); } + /** + * 批量预演当前页策略“下一个抓取订单数”。 + * + * 仅执行候选查询与规则计算,不写库、不建波次、不占锁。 + * + * @param {number|string} warehouseId 仓库ID。 + * @param {Array} [strategyRows=[]] 策略行数组。 + * @return {Promise>} strategy_id 到预演订单数映射。 + */ + async getWaveStrategyNextFetchOrderCountMap(warehouseId, strategyRows = []) { + const normalizedWarehouseId = Number(warehouseId || 0); + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + + const rows = Array.isArray(strategyRows) ? strategyRows : []; + const countMap = new Map(); + + await Promise.all(rows.map(async row => { + const strategyId = Number(row && row.id || 0); + if (!Number.isInteger(strategyId) || strategyId <= 0) { + return; + } + + try { + const nextFetchOrderCount = await this.previewWaveStrategyNextFetchOrderCount({ + warehouseId: normalizedWarehouseId, + strategyRow: row, + }); + countMap.set(strategyId, Number(nextFetchOrderCount || 0)); + } catch (error) { + this.ctx.logger.warn('[wave.getWaveStrategyNextFetchOrderCountMap] 预演策略抓取数量失败,降级为 0', { + warehouse_id: normalizedWarehouseId, + strategy_id: strategyId, + error: error && error.message ? error.message : `${error}`, + }); + countMap.set(strategyId, 0); + } + })); + + return countMap; + } + + /** + * 调试:按策略返回候选订单明细列表(含结构、快递、货主等指标)。 + * + * @param {number|string} warehouseId 仓库ID。 + * @param {Array} [strategyRows=[]] 策略行数组。 + * @return {Promise>>} strategy_id 到候选订单明细列表的映射。 + */ + async getWaveStrategyDebugFetchOrderListMap(warehouseId, strategyRows = []) { + const normalizedWarehouseId = Number(warehouseId || 0); + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + + const rows = Array.isArray(strategyRows) ? strategyRows : []; + const orderListMap = new Map(); + + const orderModel = await this.getOrderModel('pendingOrder', normalizedWarehouseId); + const orderTableName = this.getModelTableSqlName(orderModel); + + await Promise.all(rows.map(async row => { + const strategyId = Number(row && row.id || 0); + if (!Number.isInteger(strategyId) || strategyId <= 0) { + return; + } + + try { + const candidateRows = await this.ctx.model.query(` + SELECT + o.id, + o.items_hash, + o.items, + o.logistics_name, + o.logistics_code, + o.sys_logistics_code, + o.store_id, + o.items_count, + o.items_total, + o.wave_id, + o.step, + o.status, + o.outbound_status, + o.post_status, + o.storage_status + FROM wms_order_wave_strategy_match m + INNER JOIN ${orderTableName} o + ON o.id = m.order_id + AND o.warehouse_id = :warehouseId + AND o.wave_id = 0 + AND o.step != 0 + AND o.post_status = 'fin' + AND o.storage_status = 'fin' + AND o.status != 'cancel' + AND o.outbound_status != 'padding' + WHERE m.warehouse_id = :warehouseId + AND m.strategy_id = :strategyId + ORDER BY o.id ASC + LIMIT 500 + `, { + replacements: { + warehouseId: normalizedWarehouseId, + strategyId, + }, + type: this.ctx.model.QueryTypes.SELECT, + }); + + const normalizedRows = Array.isArray(candidateRows) ? candidateRows : []; + const requireSameExpress = Number(row && row.require_same_express || 0) === 1; + const filteredRows = requireSameExpress && normalizedRows.length > 0 + ? (() => { + const expressGroupMap = new Map(); + for (const order of normalizedRows) { + const expressKey = this.getWaveStrategyQuickScanExpressKey({ + sys_logistics_code: order.sys_logistics_code, + logistics_code: order.logistics_code, + logistics_name: order.logistics_name, + }); + const key = expressKey || '__empty__'; + if (!expressGroupMap.has(key)) { + expressGroupMap.set(key, []); + } + expressGroupMap.get(key).push(order); + } + const groups = Array.from(expressGroupMap.values()) + .sort((a, b) => b.length - a.length); + return groups.length > 0 ? groups[0] : normalizedRows; + })() + : normalizedRows; + const detailList = filteredRows.map(order => ({ + order_id: Number(order && order.id || 0), + structure: { + items_hash: String(order && order.items_hash || '').trim(), + items: String(order && order.items || '').trim(), + }, + express: { + sys_logistics_code: String(order && order.sys_logistics_code || '').trim(), + logistics_code: String(order && order.logistics_code || '').trim(), + logistics_name: String(order && order.logistics_name || '').trim(), + }, + store_id: String(order && order.store_id || '').trim(), + items_count: Number(order && order.items_count || 0), + items_total: Number(order && order.items_total || 0), + wave_id: Number(order && order.wave_id || 0), + status: String(order && order.status || '').trim(), + outbound_status: String(order && order.outbound_status || '').trim(), + post_status: String(order && order.post_status || '').trim(), + storage_status: String(order && order.storage_status || '').trim(), + })); + + orderListMap.set(strategyId, { + candidate_count: detailList.length, + candidate_total: normalizedRows.length, + candidates: detailList, + }); + } catch (error) { + this.ctx.logger.warn('[wave.getWaveStrategyDebugFetchOrderListMap] 调试查询失败,降级为空', { + warehouse_id: normalizedWarehouseId, + strategy_id: strategyId, + error: error && error.message ? error.message : `${error}`, + }); + orderListMap.set(strategyId, { candidate_count: 0, candidates: [], error: error && error.message || `${error}` }); + } + })); + + return orderListMap; + } + + /** + * 预演单个策略“下一个抓取订单数”。 + * + * 口径复用自动分流逻辑,但仅计算最终会选中的订单数量,不执行写操作。 + * + * @param {Object} [params={}] 预演参数。 + * @param {number|string} params.warehouseId 仓库ID。 + * @param {Object} params.strategyRow 策略行。 + * @return {Promise} 预演可抓取订单数。 + */ + async previewWaveStrategyNextFetchOrderCount(params = {}) { + const warehouseId = this.normalizeRequiredPositiveInteger(params.warehouseId, 'warehouse_id'); + const strategyRow = this.isPlainObject(params.strategyRow) ? params.strategyRow : {}; + const strategyId = Number(strategyRow.id || 0); + if (!Number.isInteger(strategyId) || strategyId <= 0) { + return 0; + } + + const strategyType = Number(strategyRow.strategy_type || 0); + if (![ 1, 2 ].includes(strategyType)) { + return 0; + } + + const candidateRows = await this.getWaveStrategyFetchCandidateOrders({ + warehouseId, + strategyId, + minSameStructure: strategyRow.min_same_structure, + maxSameStructure: strategyRow.max_same_structure, + requireSameExpress: Number(strategyRow.require_same_express || 0), + }); + if (candidateRows.length <= 0) { + return 0; + } + + let groupedRows = this.groupWaveStrategyFetchCandidateOrdersByStructure(candidateRows); + if (groupedRows.length <= 0) { + return 0; + } + + if (Number(strategyRow.require_same_express || 0) === 1) { + const filteredRows = this.filterCandidateOrdersByRequireSameExpress(candidateRows); + groupedRows = this.groupWaveStrategyFetchCandidateOrdersByStructure(filteredRows); + if (groupedRows.length <= 0) { + return 0; + } + } + + if (strategyType === 2) { + const groupLimitRaw = Number(strategyRow.group_batch_max_orders || 0); + const groupLimit = Number.isInteger(groupLimitRaw) && groupLimitRaw > 0 ? groupLimitRaw : 1; + const selectedGroups = groupedRows.slice(0, groupLimit); + const selectedOrderIds = [ ...new Set(selectedGroups + .flatMap(group => group.order_ids) + .map(id => Number(id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ]; + return selectedOrderIds.length; + } + + const pickMode = this.resolveWaveStrategyFetchPickMode({ + requestData: {}, + strategyRow, + }); + const mergedOrderIds = [ ...new Set(groupedRows + .flatMap(group => group.order_ids) + .map(id => Number(id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ] + .sort((a, b) => a - b); + if (mergedOrderIds.length <= 0) { + return 0; + } + + let selectedOrderIds = []; + if (pickMode === 3) { + const skuMap = await this.buildWaveStrategyFetchOrderSkuMap({ + warehouseId, + orderIds: mergedOrderIds, + }); + const skuLimitRaw = Number(strategyRow.batch_max_skus || 0); + const skuLimit = Number.isInteger(skuLimitRaw) && skuLimitRaw > 0 ? skuLimitRaw : 0; + const skuResult = this.selectWaveStrategyFetchOrdersBySkuLimit({ + orderIds: mergedOrderIds, + orderSkuMap: skuMap, + skuLimit, + }); + selectedOrderIds = skuResult.selectedOrderIds; + } else if (pickMode === 2 || pickMode === 4) { + selectedOrderIds = mergedOrderIds; + } else { + return 0; + } + + const orderLimitRaw = Number(strategyRow.batch_max_orders || 0); + const orderLimit = Number.isInteger(orderLimitRaw) && orderLimitRaw > 0 ? orderLimitRaw : 0; + const limitedOrderIds = orderLimit > 0 + ? selectedOrderIds.slice(0, orderLimit) + : selectedOrderIds; + + return limitedOrderIds.length; + } + + /** + * 按策略统计过滤后命中订单数。 + * + * 过滤口径: + * 1) 仅统计未在波次订单(wave_id = 0); + * 2) 仅统计 step != 0 的订单; + * 3) 仅统计状态有效订单(status != cancel 且 outbound_status != padding); + * 4) 同结构数量需落在策略 min_same_structure/max_same_structure 区间内。 + * + * 同结构定义沿用快速扫描口径:优先 items_hash,空时回退 items。 + * + * @param {number|string} warehouseId 仓库ID。 + * @param {Array} strategyIds 当前页策略ID列表。 + * @return {Promise>} strategy_id 到过滤后命中订单数的映射。 + */ + async getWaveStrategyMatchedOrderCountFilteredMap(warehouseId, strategyIds = []) { + const normalizedWarehouseId = Number(warehouseId || 0); + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + + const normalizedStrategyIds = [ ...new Set((Array.isArray(strategyIds) ? strategyIds : []) + .map(item => Number(item)) + .filter(item => Number.isInteger(item) && item > 0)) ]; + if (normalizedStrategyIds.length === 0) { + return new Map(); + } + + const orderModel = await this.getOrderModel('pendingOrder', normalizedWarehouseId); + const orderTableName = this.getModelTableSqlName(orderModel); + const querySql = ` + SELECT + m.strategy_id, + COUNT(DISTINCT m.order_id) AS matched_order_count_filtered + FROM wms_order_wave_strategy_match m + INNER JOIN ${orderTableName} o + ON o.id = m.order_id + AND o.warehouse_id = :warehouseId + AND o.wave_id = 0 + AND o.step != 0 + AND o.post_status = 'fin' + AND o.storage_status = 'fin' + AND o.status != 'cancel' + AND o.outbound_status != 'padding' + INNER JOIN ( + SELECT + COALESCE(NULLIF(TRIM(COALESCE(src.items_hash, '')), ''), TRIM(COALESCE(src.items, ''))) AS structure_key, + COUNT(1) AS same_structure_count + FROM ${orderTableName} src + WHERE src.warehouse_id = :warehouseId + AND src.wave_id = 0 + AND src.step != 0 + AND src.post_status = 'fin' + AND src.storage_status = 'fin' + AND src.status != 'cancel' + AND src.outbound_status != 'padding' + GROUP BY COALESCE(NULLIF(TRIM(COALESCE(src.items_hash, '')), ''), TRIM(COALESCE(src.items, ''))) + ) same_structure + ON same_structure.structure_key = COALESCE(NULLIF(TRIM(COALESCE(o.items_hash, '')), ''), TRIM(COALESCE(o.items, ''))) + INNER JOIN wms_wave_strategy s + ON s.id = m.strategy_id + AND s.warehouse_id = :warehouseId + WHERE m.warehouse_id = :warehouseId + AND m.strategy_id IN (:strategyIds) + AND same_structure.same_structure_count >= COALESCE(s.min_same_structure, 0) + AND (s.max_same_structure IS NULL OR same_structure.same_structure_count <= s.max_same_structure) + GROUP BY m.strategy_id + `; + + const queryRows = await this.ctx.model.query(querySql, { + replacements: { + warehouseId: normalizedWarehouseId, + strategyIds: normalizedStrategyIds, + }, + type: this.ctx.model.QueryTypes.SELECT, + }); + + const matchedMap = new Map(); + (Array.isArray(queryRows) ? queryRows : []).forEach(row => { + const strategyId = Number(row && row.strategy_id || 0); + const matchedCount = Number(row && row.matched_order_count_filtered || 0); + if (!Number.isInteger(strategyId) || strategyId <= 0) { + return; + } + + matchedMap.set(strategyId, matchedCount); + }); + + return matchedMap; + } + /** * 新增波次策略。 * @@ -3181,6 +3210,30 @@ class WaveService extends OrderBaseService { await this.app.setCacheAsync(subjectConfigCacheKey, null, 0); } } + + const strategyCacheKey = `${WAVE_STRATEGY_LIST_CACHE_KEY_PREFIX}${normalizedWarehouseId}`; + if (this.app && typeof this.app.delCacheAsync === 'function') { + await this.app.delCacheAsync(strategyCacheKey); + } else if (this.app && typeof this.app.setCacheAsync === 'function') { + await this.app.setCacheAsync(strategyCacheKey, null, 0); + } + + setImmediate(() => { + this.submitWaveStrategyQuickScanForWarehouse(normalizedWarehouseId) + .then(scanPayload => { + this.ctx.logger.info('[wave.bumpWaveStrategyVersionAndInvalidateCache] 异步触发全量扫描成功', { + warehouseId: normalizedWarehouseId, + taskId: String(scanPayload && scanPayload.task_id || '').trim(), + state: String(scanPayload && scanPayload.state || '').trim(), + }); + }) + .catch(error => { + this.ctx.logger.warn('[wave.bumpWaveStrategyVersionAndInvalidateCache] 异步触发全量扫描失败,不影响主流程', { + warehouseId: normalizedWarehouseId, + error: error && error.message ? error.message : `${error}`, + }); + }); + }); }; if (transaction && typeof transaction.afterCommit === 'function') { @@ -3239,8 +3292,18 @@ class WaveService extends OrderBaseService { throw new Error('strategy_name 参数不能为空'); } payload.strategy_name = strategyName; + if (Object.prototype.hasOwnProperty.call(requestData, 'wave_prefix')) { + const wavePrefix = String(requestData.wave_prefix || '').trim().slice(0, 5); + payload.wave_prefix = wavePrefix || null; + } payload.strategy_type = this.normalizeRequiredPositiveInteger(requestData.strategy_type, 'strategy_type'); - payload.batch_mode = this.normalizeRequiredPositiveInteger(requestData.batch_mode, 'batch_mode'); + if (Object.prototype.hasOwnProperty.call(requestData, 'batch_mode')) { + payload.batch_mode = this.normalizePositiveInteger(requestData.batch_mode, 'batch_mode'); + } else if (payload.strategy_type === 2) { + payload.batch_mode = 0; + } else { + throw new Error('batch_mode 参数不能为空'); + } } else { if (Object.prototype.hasOwnProperty.call(requestData, 'strategy_name')) { const strategyName = String(requestData.strategy_name || '').trim(); @@ -3249,11 +3312,17 @@ class WaveService extends OrderBaseService { } payload.strategy_name = strategyName; } + if (Object.prototype.hasOwnProperty.call(requestData, 'wave_prefix')) { + const wavePrefix = String(requestData.wave_prefix || '').trim().slice(0, 5); + payload.wave_prefix = wavePrefix || null; + } if (Object.prototype.hasOwnProperty.call(requestData, 'strategy_type')) { payload.strategy_type = this.normalizeRequiredPositiveInteger(requestData.strategy_type, 'strategy_type'); } if (Object.prototype.hasOwnProperty.call(requestData, 'batch_mode')) { - payload.batch_mode = this.normalizeRequiredPositiveInteger(requestData.batch_mode, 'batch_mode'); + payload.batch_mode = this.normalizePositiveInteger(requestData.batch_mode, 'batch_mode'); + } else if (payload.strategy_type === 2) { + payload.batch_mode = 0; } } @@ -3271,9 +3340,58 @@ class WaveService extends OrderBaseService { this.patchWaveStrategyIntegerField(payload, requestData, 'order_max_qty'); this.patchWaveStrategyIntegerField(payload, requestData, 'min_same_structure'); this.patchWaveStrategyIntegerField(payload, requestData, 'max_same_structure'); - this.patchWaveStrategyIntegerField(payload, requestData, 'batch_max_orders'); - this.patchWaveStrategyIntegerField(payload, requestData, 'batch_max_skus'); - this.patchWaveStrategyIntegerField(payload, requestData, 'group_batch_max_orders'); + if (Object.prototype.hasOwnProperty.call(requestData, 'batch_max_orders')) { + const rawBatchMaxOrders = requestData.batch_max_orders; + if (rawBatchMaxOrders === null || rawBatchMaxOrders === '') { + payload.batch_max_orders = null; + } else { + payload.batch_max_orders = this.normalizePositiveInteger(rawBatchMaxOrders, 'batch_max_orders'); + } + } + const resolvedStrategyType = Object.prototype.hasOwnProperty.call(payload, 'strategy_type') + ? payload.strategy_type + : Object.prototype.hasOwnProperty.call(requestData, 'strategy_type') + ? this.normalizeRequiredPositiveInteger(requestData.strategy_type, 'strategy_type') + : null; + if (resolvedStrategyType === 2) { + payload.batch_max_orders = 0; + } + const resolvedBatchMode = Object.prototype.hasOwnProperty.call(payload, 'batch_mode') + ? payload.batch_mode + : Object.prototype.hasOwnProperty.call(requestData, 'batch_mode') + ? this.normalizePositiveInteger(requestData.batch_mode, 'batch_mode') + : null; + if (resolvedBatchMode === 2) { + if (Object.prototype.hasOwnProperty.call(requestData, 'batch_max_skus')) { + const rawBatchMaxSkus = requestData.batch_max_skus; + if (rawBatchMaxSkus === null || rawBatchMaxSkus === '') { + payload.batch_max_skus = null; + } else { + payload.batch_max_skus = this.normalizePositiveInteger(rawBatchMaxSkus, 'batch_max_skus'); + } + } + } else { + payload.batch_max_skus = 0; + } + if (resolvedStrategyType !== null && resolvedStrategyType !== 2) { + payload.group_batch_max_orders = 0; + } else if (resolvedStrategyType === 2) { + if (Object.prototype.hasOwnProperty.call(requestData, 'group_batch_max_orders')) { + const rawGroupBatchMaxOrders = requestData.group_batch_max_orders; + if (rawGroupBatchMaxOrders === null || rawGroupBatchMaxOrders === '') { + payload.group_batch_max_orders = null; + } else { + payload.group_batch_max_orders = this.normalizePositiveInteger(rawGroupBatchMaxOrders, 'group_batch_max_orders'); + } + } + } else if (Object.prototype.hasOwnProperty.call(requestData, 'group_batch_max_orders')) { + const rawGroupBatchMaxOrders = requestData.group_batch_max_orders; + if (rawGroupBatchMaxOrders === null || rawGroupBatchMaxOrders === '') { + payload.group_batch_max_orders = null; + } else { + payload.group_batch_max_orders = this.normalizePositiveInteger(rawGroupBatchMaxOrders, 'group_batch_max_orders'); + } + } if (Object.prototype.hasOwnProperty.call(requestData, 'require_same_express')) { payload.require_same_express = this.normalizeBoolean(requestData.require_same_express, false); @@ -3285,22 +3403,36 @@ class WaveService extends OrderBaseService { payload.description = String(requestData.description || '').trim(); } if (Object.prototype.hasOwnProperty.call(requestData, 'allowed_provinces')) { - payload.allowed_provinces = this.normalizeWaveStrategyQuickScanStringList(requestData.allowed_provinces); + const list = this.normalizeWaveStrategyQuickScanStringList(requestData.allowed_provinces); + payload.allowed_provinces = list.length > 0 ? list : null; + } else if (mode === 'update') { + payload.allowed_provinces = null; } if (Object.prototype.hasOwnProperty.call(requestData, 'allowed_platforms')) { - payload.allowed_platforms = this.normalizeWaveStrategyQuickScanStringList(requestData.allowed_platforms); + const list = this.normalizeWaveStrategyQuickScanStringList(requestData.allowed_platforms, false); + payload.allowed_platforms = list.length > 0 ? list : null; + } else if (mode === 'update') { + payload.allowed_platforms = null; } if (Object.prototype.hasOwnProperty.call(requestData, 'allowed_owners')) { - const allowedOwners = this.normalizeWaveStrategyQuickScanStringList(requestData.allowed_owners); - await this.validateWaveStrategyAllowedOwners(allowedOwners, warehouseId); - payload.allowed_owners = allowedOwners; + const list = this.normalizeWaveStrategyQuickScanStringList(requestData.allowed_owners); + if (list.length > 0) { + await this.validateWaveStrategyAllowedOwners(list, warehouseId); + } + payload.allowed_owners = list.length > 0 ? list : null; + } else if (mode === 'update') { + payload.allowed_owners = null; } if (Object.prototype.hasOwnProperty.call(requestData, 'allowed_expresses')) { - const allowedExpresses = this.normalizeWaveStrategyQuickScanStringList(requestData.allowed_expresses); - await this.validateWaveStrategyAllowedExpresses(allowedExpresses); - payload.allowed_expresses = allowedExpresses; + const list = this.normalizeWaveStrategyQuickScanStringList(requestData.allowed_expresses, false); + if (list.length > 0) { + await this.validateWaveStrategyAllowedExpresses(list); + } + payload.allowed_expresses = list.length > 0 ? list : null; + } else if (mode === 'update') { + payload.allowed_expresses = null; } await this.applyWaveStrategyMaxSameStructureConstraint(payload, warehouseId); @@ -3312,6 +3444,71 @@ class WaveService extends OrderBaseService { return payload; } + /** + * 归一化波次策略波次前缀。 + * + * 规则: + * 1. 允许为空字符串(表示回退仓库前缀); + * 2. 非空时统一转大写; + * 3. 非空时仅允许 A-Z0-9,长度 1-5。 + * + * @param {*} rawWavePrefix 原始波次前缀入参。 + * @return {string} 归一化后的波次前缀。 + */ + normalizeWaveStrategyWavePrefix(rawWavePrefix) { + if (rawWavePrefix === undefined || rawWavePrefix === null) { + return ''; + } + + const normalizedWavePrefix = String(rawWavePrefix).trim() + .toUpperCase(); + if (!normalizedWavePrefix) { + return ''; + } + + if (normalizedWavePrefix.length < 1 || normalizedWavePrefix.length > 5) { + throw new Error('wave_prefix 非空时长度必须为 1-5 个字符'); + } + + if (!/^[A-Z0-9]+$/.test(normalizedWavePrefix)) { + throw new Error('wave_prefix 非空时仅支持 A-Z0-9'); + } + + return normalizedWavePrefix; + } + + /** + * 解析策略抓取建波使用的前缀(策略优先,仓库前缀兜底)。 + * + * @param {Object} params 解析参数。 + * @param {number|string} params.warehouseId 仓库ID。 + * @param {number|string} params.strategyType 策略类型(1-散单,2-团购)。 + * @param {Object} [params.strategyRow={}] 策略行。 + * @return {Promise<{ wavePrefix: string, source: string }>} 前缀及来源。 + */ + async resolveWaveStrategyFetchWavePrefix(params = {}) { + const warehouseId = this.normalizeRequiredPositiveInteger(params.warehouseId, 'warehouse_id'); + const strategyType = Number(params.strategyType || 0); + const strategyRow = this.isPlainObject(params.strategyRow) ? params.strategyRow : {}; + const strategyWavePrefix = this.normalizeWaveStrategyWavePrefix(strategyRow.wave_prefix); + + if (strategyWavePrefix) { + return { + wavePrefix: strategyWavePrefix, + source: 'strategy', + }; + } + + const warehouseWavePrefix = strategyType === 2 + ? await this.getGroupWavePrefix(warehouseId) + : await this.getSingleFetchByIdsWavePrefix(warehouseId); + + return { + wavePrefix: String(warehouseWavePrefix || '').trim() || (strategyType === 2 ? 'B' : 'A'), + source: 'warehouse_fallback', + }; + } + /** * 按字段补丁方式归一化波次策略正整数参数。 * @@ -3364,14 +3561,15 @@ class WaveService extends OrderBaseService { */ async validateWaveStrategyAllowedExpresses(expressList = []) { const normalizedExpresses = Array.isArray(expressList) - ? expressList.map(item => String(item || '').trim().toLowerCase()).filter(Boolean) + ? expressList.map(item => String(item || '').trim()).filter(Boolean) : []; if (normalizedExpresses.length === 0) { return; } const availableExpressSet = await this.getWaveStrategyAvailableExpressSet(); - const illegalExpresses = normalizedExpresses.filter(item => !availableExpressSet.has(item)); + const availableLowerSet = new Set([...availableExpressSet].map(s => s.toLowerCase())); + const illegalExpresses = normalizedExpresses.filter(item => !availableLowerSet.has(String(item).toLowerCase())); if (illegalExpresses.length > 0) { throw new Error(`allowed_expresses 存在非法值: ${illegalExpresses.join(', ')}`); @@ -3822,6 +4020,7 @@ class WaveService extends OrderBaseService { total_orders, processed_orders, distinguish_express, + source, logistics_name, item_snapshot_key, warehouse_id, @@ -3837,7 +4036,12 @@ class WaveService extends OrderBaseService { COUNT(od.wave_id) AS order_total, SUM(CASE WHEN od.storage_status = 'none' THEN 1 ELSE 0 END) AS storage_none_count, SUM(CASE WHEN od.storage_status = 'fin' THEN 1 ELSE 0 END) AS storage_fin_count, - SUM(CASE WHEN od.storage_status = 'error' THEN 1 ELSE 0 END) AS storage_error_count + SUM(CASE WHEN od.storage_status = 'error' THEN 1 ELSE 0 END) AS storage_error_count, + SUM(CASE WHEN od.post_status = 'none' THEN 1 ELSE 0 END) AS post_none_count, + SUM(CASE WHEN od.post_status = 'fin' THEN 1 ELSE 0 END) AS post_fin_count, + SUM(CASE WHEN od.post_status = 'error' THEN 1 ELSE 0 END) AS post_error_count, + SUM(CASE WHEN od.print_status = 'none' THEN 1 ELSE 0 END) AS print_none_count, + SUM(CASE WHEN od.print_status = 'fin' THEN 1 ELSE 0 END) AS print_fin_count FROM ( SELECT wave_id FROM wms_wave_batch @@ -3847,7 +4051,6 @@ class WaveService extends OrderBaseService { GROUP BY candidate_wave.wave_id ) wave_order_stats ON wave_order_stats.wave_id = wb.wave_id WHERE 1 = 1 - AND COALESCE(wave_order_stats.order_total, 0) > 0 ${storageAssignmentFilterClause.sql} ${expressAssignmentFilterClause.sql} ${printAssignmentFilterClause.sql} @@ -3862,12 +4065,22 @@ class WaveService extends OrderBaseService { wb.total_orders, wb.processed_orders, wb.distinguish_express, + wb.source, wb.logistics_name, wb.item_snapshot_key, wb.warehouse_id, wb.creator, wb.create_time, - wb.update_time + wb.update_time, + COALESCE(wave_order_stats.order_total, 0) AS order_total, + COALESCE(wave_order_stats.storage_none_count, 0) AS storage_none_count, + COALESCE(wave_order_stats.storage_fin_count, 0) AS storage_fin_count, + COALESCE(wave_order_stats.storage_error_count, 0) AS storage_error_count, + COALESCE(wave_order_stats.post_none_count, 0) AS post_none_count, + COALESCE(wave_order_stats.post_fin_count, 0) AS post_fin_count, + COALESCE(wave_order_stats.post_error_count, 0) AS post_error_count, + COALESCE(wave_order_stats.print_none_count, 0) AS print_none_count, + COALESCE(wave_order_stats.print_fin_count, 0) AS print_fin_count ${batchListFromSql} ORDER BY wb.total_orders DESC, wb.wave_id DESC LIMIT :limit OFFSET :offset @@ -3922,82 +4135,17 @@ class WaveService extends OrderBaseService { }); } - const waveIds = rawList - .map(item => Number(item && item.wave_id || 0)) - .filter(id => Number.isInteger(id) && id > 0); - - const orderRows = waveIds.length > 0 - ? await orderModel.findAll({ - where: { - wave_id: { [Op.in]: waveIds }, - }, - attributes: [ 'wave_id', 'storage_status', 'post_status', 'print_status' ], - raw: true, - }) - : []; - - const waveOrderStatsMap = new Map(); - for (const row of orderRows) { - const waveId = Number(row && row.wave_id || 0); - if (!Number.isInteger(waveId) || waveId <= 0) { - continue; - } - - if (!waveOrderStatsMap.has(waveId)) { - waveOrderStatsMap.set(waveId, { - orderCount: 0, - storageNoneCount: 0, - storageFinCount: 0, - storageErrorCount: 0, - expressNoneCount: 0, - expressFinCount: 0, - expressErrorCount: 0, - printNoneCount: 0, - printFinCount: 0, - }); - } - - const stats = waveOrderStatsMap.get(waveId); - const storageStatus = String(row && row.storage_status || '').trim(); - const expressStatus = String(row && row.post_status || '').trim(); - const printStatus = String(row && row.print_status || '').trim(); - - stats.orderCount += 1; - if (storageStatus === 'none') { - stats.storageNoneCount += 1; - } else if (storageStatus === 'fin') { - stats.storageFinCount += 1; - } else if (storageStatus === 'error') { - stats.storageErrorCount += 1; - } - - if (expressStatus === 'none') { - stats.expressNoneCount += 1; - } else if (expressStatus === 'fin') { - stats.expressFinCount += 1; - } else if (expressStatus === 'error') { - stats.expressErrorCount += 1; - } - - if (printStatus === 'none') { - stats.printNoneCount += 1; - } else if (printStatus === 'fin') { - stats.printFinCount += 1; - } - } - const list = rawList.map(batch => { const waveId = Number(batch && batch.wave_id || 0); - const stats = waveOrderStatsMap.get(waveId) || {}; - const orderCount = Number(stats.orderCount || 0); - const storageNoneCount = Number(stats.storageNoneCount || 0); - const storageFinCount = Number(stats.storageFinCount || 0); - const storageErrorCount = Number(stats.storageErrorCount || 0); - const expressNoneCount = Number(stats.expressNoneCount || 0); - const expressFinCount = Number(stats.expressFinCount || 0); - const expressErrorCount = Number(stats.expressErrorCount || 0); - const printNoneCount = Number(stats.printNoneCount || 0); - const printFinCount = Number(stats.printFinCount || 0); + const orderCount = Number(batch && batch.order_total || 0); + const storageNoneCount = Number(batch && batch.storage_none_count || 0); + const storageFinCount = Number(batch && batch.storage_fin_count || 0); + const storageErrorCount = Number(batch && batch.storage_error_count || 0); + const expressNoneCount = Number(batch && batch.post_none_count || 0); + const expressFinCount = Number(batch && batch.post_fin_count || 0); + const expressErrorCount = Number(batch && batch.post_error_count || 0); + const printNoneCount = Number(batch && batch.print_none_count || 0); + const printFinCount = Number(batch && batch.print_fin_count || 0); return { wave_id: waveId, @@ -4010,6 +4158,7 @@ class WaveService extends OrderBaseService { item_part_type: String(batch && batch.item_part_type || '').trim(), item_part: String(batch && batch.item_part || '').trim(), distinguish_express: Number(batch && batch.distinguish_express || 0), + source: Number(batch && batch.source || 0), logistics_name: String(batch && batch.logistics_name || '').trim(), item_snapshot_key: String(batch && batch.item_snapshot_key || '').trim(), warehouse_id: Number(batch && batch.warehouse_id || 0), @@ -4040,6 +4189,133 @@ class WaveService extends OrderBaseService { }); } + /** + * 拣货任务列表查询。 + * + * 基于 wms_wave_pick_task 主表按当前仓库维度分页查询,默认按 create_time 倒序。 + * + * @param {Object} [data={}] 请求参数。 + * @param {number|string} [data.page] 页码(兼容 current)。 + * @param {number|string} [data.pageSize] 每页数量(兼容 size/page_size)。 + * @param {Object} [data.where] 查询过滤。 + * @return {Promise} 列表与分页结果。 + */ + async wavePickTaskList(data = {}) { + try { + const requestData = this.isPlainObject(data) ? data : {}; + const { page, pageSize } = this.normalizeWavePickTaskListPagination(requestData); + const normalizedRequest = this.normalizeWavePickTaskListRequest(requestData); + const warehouseId = normalizedRequest.warehouseId; + const whereClause = this.buildWavePickTaskListWhereClause(normalizedRequest.where); + const offset = (page - 1) * pageSize; + + const listSql = ` + SELECT + t.id, + t.task_no, + t.warehouse_id, + t.pick_mode, + t.status, + t.review_status, + t.source, + t.wave_count, + t.order_count, + t.box_count, + t.pick_user_id, + t.pick_user_name, + t.review_user_id, + t.review_user_name, + t.current_cart_id, + t.current_cart_code_snapshot, + t.batch_no, + t.device_id, + t.start_time, + t.finish_time, + t.review_start_time, + t.review_finish_time, + t.create_time, + t.update_time + FROM wms_wave_pick_task t + WHERE t.warehouse_id = :warehouseId + ${whereClause.sql} + ORDER BY t.create_time DESC + LIMIT :limit OFFSET :offset + `; + + const countSql = ` + SELECT COUNT(1) AS total + FROM wms_wave_pick_task t + WHERE t.warehouse_id = :warehouseId + ${whereClause.sql} + `; + + const replacements = { + warehouseId, + ...whereClause.replacements, + }; + + const [ listRows, countRows ] = await Promise.all([ + this.ctx.model.query(listSql, { + replacements: { + ...replacements, + limit: pageSize, + offset, + }, + }), + this.ctx.model.query(countSql, { + replacements, + }), + ]); + + const sourceList = Array.isArray(listRows && listRows[0]) ? listRows[0] : []; + const totalRowList = Array.isArray(countRows && countRows[0]) ? countRows[0] : []; + const total = Number(totalRowList[0] && totalRowList[0].total || 0); + + const list = sourceList.map(item => ({ + task_id: Number(item && item.id || 0), + task_no: String(item && item.task_no || '').trim(), + warehouse_id: Number(item && item.warehouse_id || 0), + pick_mode: Number(item && item.pick_mode || 0), + status: Number(item && item.status || 0), + review_status: Number(item && item.review_status || 0), + source: Number(item && item.source || 0), + wave_count: Number(item && item.wave_count || 0), + order_count: Number(item && item.order_count || 0), + box_count: Number(item && item.box_count || 0), + pick_user_id: Number(item && item.pick_user_id || 0), + pick_user_name: String(item && item.pick_user_name || '').trim(), + operator_id: Number(item && item.pick_user_id || 0), + operator_name: String(item && item.pick_user_name || '').trim(), + review_user_id: Number(item && item.review_user_id || 0), + review_user_name: String(item && item.review_user_name || '').trim(), + current_cart_id: Number(item && item.current_cart_id || 0), + current_cart_code_snapshot: String(item && item.current_cart_code_snapshot || '').trim(), + batch_no: String(item && item.batch_no || '').trim(), + device_id: String(item && item.device_id || '').trim(), + start_time: item && item.start_time || null, + start_at: item && item.start_time || null, + finish_time: item && item.finish_time || null, + finish_at: item && item.finish_time || null, + review_start_time: item && item.review_start_time || null, + review_finish_time: item && item.review_finish_time || null, + create_time: item && item.create_time || null, + created_at: item && item.create_time || null, + update_time: item && item.update_time || null, + })); + + return this.success('ok', { + list, + total, + page, + page_size: pageSize, + }); + } catch (error) { + const errorMessage = String(error && error.message || '').trim(); + const isBadRequest = /参数|上下文/.test(errorMessage); + return this.fail(`查询拣货任务列表失败: ${errorMessage || '未知错误'}`, isBadRequest ? 400 : 500); + } + } + /** * 批量解除波次任务提交接口。 * @@ -4075,6 +4351,22 @@ class WaveService extends OrderBaseService { throw new Error('wave_ids 参数不能为空或格式错误'); } + const activeTaskWaves = await this.ctx.model.query( + `SELECT ptw.wave_id + FROM wms_wave_pick_task_wave ptw + INNER JOIN wms_wave_pick_task pt ON pt.id = ptw.task_id + WHERE ptw.wave_id IN (:waveIds) + AND pt.status IN (0, 1) + LIMIT 1`, + { + replacements: { waveIds: normalizedWaveIds }, + type: this.ctx.model.QueryTypes.SELECT, + } + ); + if (activeTaskWaves.length > 0) { + throw new Error('波次属于活动拣货任务,请通过任务取消接口处理'); + } + const requestedTaskId = this.normalizeBatchCancelTaskId(data); const taskId = requestedTaskId || this.generateBatchCancelTaskId(warehouseId); const existingTask = await this.getBatchCancelTaskProgress(taskId); @@ -4085,7 +4377,7 @@ class WaveService extends OrderBaseService { task_id: taskId, warehouse_id: Number(existingTask.warehouse_id || warehouseId), state: String(existingTask.state || 'submitted').trim() || 'submitted', - message: 'Batch cancel task already exists. Check progress with order.wave.batchCancelTaskProgress', + message: '批量解除波次任务已存在,请勿重复提交。', accepted_at: existingTask.accepted_at || existingTask.submitted_at || new Date().toISOString(), }); } @@ -4131,7 +4423,7 @@ class WaveService extends OrderBaseService { status: 'success', task_id: taskId, warehouse_id: warehouseId, - message: 'Batch cancel submitted. Check progress with order.wave.batchCancelTaskProgress', + message: '批量解除波次任务已提交。', accepted_at: acceptedAt, }); } @@ -4282,7 +4574,7 @@ class WaveService extends OrderBaseService { task_id: taskId, warehouse_id: Number(existingTask.warehouse_id || warehouseId), state: String(existingTask.state || 'submitted').trim() || 'submitted', - message: 'Batch allocate express task already exists. Check progress with order.wave.batchAllocateExpressTaskProgress', + message: '批量分配快递任务已存在,请勿重复提交。', accepted_at: existingTask.accepted_at || existingTask.submitted_at || new Date().toISOString(), }); } @@ -4336,7 +4628,7 @@ class WaveService extends OrderBaseService { status: 'success', task_id: taskId, warehouse_id: warehouseId, - message: 'Batch allocate express submitted. Check progress with order.wave.batchAllocateExpressTaskProgress', + message: '批量分配快递任务已提交。', accepted_at: acceptedAt, }); } catch (error) { @@ -4462,7 +4754,7 @@ class WaveService extends OrderBaseService { task_id: taskId, warehouse_id: Number(existingTask.warehouse_id || warehouseId), state: String(existingTask.state || 'submitted').trim() || 'submitted', - message: 'Batch allocate storage task already exists. Check progress with order.wave.batchAllocateStorageTaskProgress', + message: '批量分配储位任务已存在,请勿重复提交。', accepted_at: existingTask.accepted_at || existingTask.submitted_at || new Date().toISOString(), }); } @@ -4513,7 +4805,7 @@ class WaveService extends OrderBaseService { status: 'success', task_id: taskId, warehouse_id: warehouseId, - message: 'Batch allocate storage submitted. Check progress with order.wave.batchAllocateStorageTaskProgress', + message: '批量分配储位任务已提交。', accepted_at: acceptedAt, }); } @@ -4622,6 +4914,110 @@ class WaveService extends OrderBaseService { return this.success('ok', payload); } + /** + * 按仓库提交波次策略快速扫描异步任务。 + * + * 同一仓库同一时刻仅允许一个任务运行,若命中运行中任务则直接复用已有任务。 + * + * @param {number|string} [warehouseId=0] 仓库ID,未传时优先使用上下文仓库ID。 + * @param {Object} [options={}] 提交选项。 + * @param {Array|number|string} [options.orderIds] 可选订单ID数组。 + * @param {boolean} [options.wait=false] 是否等待任务执行完成后再返回最终进度快照。 + * @return {Promise} 任务受理结果(plain object)。 + */ + async submitWaveStrategyQuickScanForWarehouse(warehouseId = 0, options = {}) { + const normalizedWarehouseId = Number(warehouseId || this.getWarehouseId() || 0); + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + const normalizedOptions = this.isPlainObject(options) ? options : {}; + const orderIds = this.normalizeIdsInput(normalizedOptions.orderIds); + const wait = this.normalizeBoolean(normalizedOptions.wait, false); + + const runningTask = await this.getWaveStrategyQuickScanWarehouseLock(normalizedWarehouseId); + if (runningTask && runningTask.task_id) { + const existingTaskId = String(runningTask.task_id || '').trim(); + const existingProgress = await this.getWaveStrategyQuickScanTaskProgress(existingTaskId); + const existingState = String(existingProgress && existingProgress.state || runningTask.state || 'running').trim() || 'running'; + + if (![ 'success', 'failed' ].includes(existingState)) { + return { + task_id: existingTaskId, + warehouse_id: normalizedWarehouseId, + state: existingState, + message: '已有快速扫描任务在运行中。请稍后重试或查询现有任务进度。', + accepted_at: runningTask.accepted_at || existingProgress && existingProgress.accepted_at || new Date().toISOString(), + }; + } + + await this.clearWaveStrategyQuickScanWarehouseLock(normalizedWarehouseId, existingTaskId); + } + + const taskId = this.generateWaveStrategyQuickScanTaskId(normalizedWarehouseId); + const acceptedAt = new Date().toISOString(); + + await this.setWaveStrategyQuickScanTaskProgress(taskId, 'submitted', { + warehouse_id: normalizedWarehouseId, + total_order_count: 0, + processed_order_count: 0, + matched_order_count: 0, + unmatched_order_count: 0, + progress_percent: 0, + submitted_at: Date.now(), + accepted_at: acceptedAt, + start_time: null, + end_time: null, + ...(orderIds.length > 0 ? { order_ids: orderIds } : {}), + error: '', + error_code: '', + result: null, + }); + + await this.setWaveStrategyQuickScanWarehouseLock(normalizedWarehouseId, taskId, { + state: 'submitted', + accepted_at: acceptedAt, + }); + + if (wait) { + await this.runWaveStrategyQuickScanTask({ + taskId, + warehouseId: normalizedWarehouseId, + ...(orderIds.length > 0 ? { orderIds } : {}), + }); + + const finalProgress = await this.getWaveStrategyQuickScanTaskProgress(taskId) || {}; + return { + ...finalProgress, + task_id: taskId, + warehouse_id: normalizedWarehouseId, + accepted_at: acceptedAt, + }; + } + + setImmediate(() => { + this.runWaveStrategyQuickScanTask({ + taskId, + warehouseId: normalizedWarehouseId, + ...(orderIds.length > 0 ? { orderIds } : {}), + }).catch(error => { + this.ctx.logger.error('[wave.waveStrategyQuickScan] 后台任务异常', { + taskId, + warehouseId: normalizedWarehouseId, + error: error && error.message ? error.message : error, + stack: error && error.stack ? error.stack : '', + }); + }); + }); + + return { + task_id: taskId, + warehouse_id: normalizedWarehouseId, + state: 'submitted', + message: '快速扫描任务已提交。', + accepted_at: acceptedAt, + }; + } + /** * 提交波次策略快速扫描异步任务。 * @@ -4635,72 +5031,11 @@ class WaveService extends OrderBaseService { throw new Error('未识别到当前仓库上下文'); } - const warehouseId = contextWarehouseId; - const runningTask = await this.getWaveStrategyQuickScanWarehouseLock(warehouseId); - if (runningTask && runningTask.task_id) { - const existingTaskId = String(runningTask.task_id || '').trim(); - const existingProgress = await this.getWaveStrategyQuickScanTaskProgress(existingTaskId); - const existingState = String(existingProgress && existingProgress.state || runningTask.state || 'running').trim() || 'running'; - - if (![ 'success', 'failed' ].includes(existingState)) { - return this.success('ok', { - status: 'success', - task_id: existingTaskId, - warehouse_id: warehouseId, - state: existingState, - message: 'Quick scan task is already running. Check progress with order.wave.waveStrategyQuickScanTaskProgress', - accepted_at: runningTask.accepted_at || existingProgress && existingProgress.accepted_at || new Date().toISOString(), - }); - } - - await this.clearWaveStrategyQuickScanWarehouseLock(warehouseId, existingTaskId); - } - - const taskId = this.generateWaveStrategyQuickScanTaskId(warehouseId); - const acceptedAt = new Date().toISOString(); - - await this.setWaveStrategyQuickScanTaskProgress(taskId, 'submitted', { - warehouse_id: warehouseId, - total_order_count: 0, - processed_order_count: 0, - matched_order_count: 0, - unmatched_order_count: 0, - progress_percent: 0, - submitted_at: Date.now(), - accepted_at: acceptedAt, - start_time: null, - end_time: null, - error: '', - error_code: '', - result: null, - }); - - await this.setWaveStrategyQuickScanWarehouseLock(warehouseId, taskId, { - state: 'submitted', - accepted_at: acceptedAt, - }); - - setImmediate(() => { - this.runWaveStrategyQuickScanTask({ - taskId, - warehouseId, - }).catch(error => { - this.ctx.logger.error('[wave.waveStrategyQuickScan] 后台任务异常', { - taskId, - warehouseId, - error: error && error.message ? error.message : error, - stack: error && error.stack ? error.stack : '', - }); - }); - }); + const submitPayload = await this.submitWaveStrategyQuickScanForWarehouse(contextWarehouseId); return this.success('ok', { status: 'success', - task_id: taskId, - warehouse_id: warehouseId, - state: 'submitted', - message: 'Quick scan task submitted. Check progress with order.wave.waveStrategyQuickScanTaskProgress', - accepted_at: acceptedAt, + ...submitPayload, }); } @@ -4744,6 +5079,426 @@ class WaveService extends OrderBaseService { }); } + /** + * 构建快速扫描订单查询条件。 + * + * @param {number} warehouseId 仓库ID。 + * @param {number} strategyVersion 当前策略版本号。 + * @param {Array} [orderIds=[]] 限定扫描订单ID数组。 + * @return {Object} 订单查询 where 条件。 + */ + buildWaveStrategyQuickScanOrderWhere(warehouseId, strategyVersion, orderIds = []) { + const normalizedOrderIds = this.normalizeIdsInput(orderIds); + const where = { + warehouse_id: warehouseId, + step: { [Op.ne]: 0 }, + wave_id: 0, + [Op.or]: [ + { wave_strategy_version: { [Op.ne]: strategyVersion } }, + { wave_strategy_version: { [Op.is]: null } }, + ], + }; + + if (normalizedOrderIds.length > 0) { + where.id = { + [Op.in]: normalizedOrderIds, + }; + } + + return where; + } + + /** + * 获取快速扫描可用策略行(带缓存)。 + * + * @param {number} warehouseId 仓库ID。 + * @return {Promise>} 策略原始行数组。 + */ + async getWaveStrategyQuickScanStrategyRows(warehouseId) { + const strategyModel = this.ctx.model && ( + this.ctx.model.wms_wave_strategy + || this.ctx.model.PickingStrategy + || this.ctx.model.WmsWaveStrategy + ); + if (!strategyModel || typeof strategyModel.findAll !== 'function') { + throw new Error('波次策略模型不可用'); + } + + const strategyCacheKey = `${WAVE_STRATEGY_LIST_CACHE_KEY_PREFIX}${warehouseId}`; + const cachedStrategyRows = this.app && typeof this.app.getCacheAsync === 'function' + ? await this.app.getCacheAsync(strategyCacheKey) + : null; + if (Array.isArray(cachedStrategyRows)) { + return cachedStrategyRows; + } + + const strategyRows = await strategyModel.findAll({ + where: { + warehouse_id: warehouseId, + status: 1, + }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + if (this.app && typeof this.app.setCacheAsync === 'function') { + await this.app.setCacheAsync(strategyCacheKey, strategyRows, WAVE_STRATEGY_LIST_CACHE_TTL_SECONDS); + } + + return strategyRows; + } + + /** + * 获取波次策略快速扫描命中副表模型。 + * + * @return {Object|null} 命中副表模型;若不可用返回 null。 + */ + getWaveStrategyQuickScanMatchModel() { + const modelContext = this.ctx && this.ctx.model; + if (!modelContext || typeof modelContext !== 'object') { + return null; + } + + return modelContext.wms_order_wave_strategy_match + || modelContext.OrderWaveStrategyMatch + || modelContext.WmsOrderWaveStrategyMatch + || null; + } + + /** + * 同步快速扫描命中策略到副表(先删后写)。 + * + * @param {number|string} warehouseId 仓库ID。 + * @param {Array|number|string} [orderIds=[]] 扫描范围订单ID。 + * @param {Object} [matchedStrategyIdsByOrder={}] 订单命中策略映射。 + * @return {Promise} 无返回值。 + */ + async syncWaveStrategyQuickScanMatchedStrategies(warehouseId, orderIds = [], matchedStrategyIdsByOrder = {}) { + const normalizedWarehouseId = Number(warehouseId || 0); + const normalizedOrderIds = this.normalizeIdsInput(orderIds); + if (normalizedOrderIds.length === 0) { + return; + } + + const matchModel = this.getWaveStrategyQuickScanMatchModel(); + if (!matchModel || typeof matchModel.destroy !== 'function' || typeof matchModel.bulkCreate !== 'function') { + throw new Error('波次策略命中副表模型不可用'); + } + + for (let i = 0; i < normalizedOrderIds.length; i += 500) { + const orderChunk = normalizedOrderIds.slice(i, i + 500); + await matchModel.destroy({ + where: { + warehouse_id: normalizedWarehouseId, + order_id: { [Op.in]: orderChunk }, + }, + }); + } + + const normalizedMatchedMap = this.isPlainObject(matchedStrategyIdsByOrder) + ? matchedStrategyIdsByOrder + : {}; + const orderScopeSet = new Set(normalizedOrderIds); + const dedupeSet = new Set(); + const createTime = this.getCurrentDateTime ? this.getCurrentDateTime() : new Date(); + const rows = []; + + Object.keys(normalizedMatchedMap).forEach(orderKey => { + const orderId = Number(orderKey); + if (!Number.isInteger(orderId) || orderId <= 0 || !orderScopeSet.has(orderId)) { + return; + } + + const strategyIds = Array.isArray(normalizedMatchedMap[orderKey]) + ? normalizedMatchedMap[orderKey] + : []; + strategyIds.forEach(strategyIdItem => { + const strategyId = Number(strategyIdItem); + if (!Number.isInteger(strategyId) || strategyId <= 0) { + return; + } + + const dedupeKey = `${orderId}:${strategyId}`; + if (dedupeSet.has(dedupeKey)) { + return; + } + dedupeSet.add(dedupeKey); + + rows.push({ + warehouse_id: normalizedWarehouseId, + order_id: orderId, + strategy_id: strategyId, + create_time: createTime, + }); + }); + }); + + for (let i = 0; i < rows.length; i += 500) { + const rowChunk = rows.slice(i, i + 500); + await matchModel.bulkCreate(rowChunk); + } + } + + /** + * 清理波次策略快速扫描命中副表过期数据。 + * + * @param {Object} [options={}] 清理参数。 + * @param {number|string} [options.expireHours=24] 过期小时数。 + * @param {number|string} [options.warehouseId] 可选仓库ID。 + * @return {Promise} 删除条数。 + */ + async cleanupWaveStrategyQuickScanMatchedStrategies(options = {}) { + const normalizedOptions = this.isPlainObject(options) ? options : {}; + const expireHoursRaw = Number(normalizedOptions.expireHours); + const expireHours = Number.isFinite(expireHoursRaw) && expireHoursRaw > 0 ? expireHoursRaw : 24; + const warehouseId = Number(normalizedOptions.warehouseId || 0); + const expireAt = new Date(Date.now() - Math.floor(expireHours * 60 * 60 * 1000)); + + const matchModel = this.getWaveStrategyQuickScanMatchModel(); + if (!matchModel || typeof matchModel.destroy !== 'function') { + throw new Error('波次策略命中副表模型不可用'); + } + + const where = { + create_time: { + [Op.lt]: expireAt, + }, + }; + + if (Number.isInteger(warehouseId) && warehouseId > 0) { + where.warehouse_id = warehouseId; + } + + const deletedCount = await matchModel.destroy({ where }); + // 清理后重建 + if (Number.isInteger(normalizedWarehouseId) && normalizedWarehouseId > 0) { + setImmediate(() => { + this.submitWaveStrategyQuickScanForWarehouse(normalizedWarehouseId).catch(err => { + this.ctx.logger.warn('[wave.cleanupWaveStrategyQuickScanMatchedStrategies] 清理后自动扫描失败: %s', err.message); + }); + }); + } + return Number(deletedCount || 0); + } + + /** + * 按仓库 + 订单ID集合清理波次策略快速扫描命中副表数据。 + * + * @param {number|string} [warehouseId=0] 仓库ID。 + * @param {Array|number|string} [orderIds=[]] 订单ID集合。 + * @return {Promise} 删除条数。 + */ + async cleanupWaveStrategyQuickScanMatchedStrategiesByOrderIds(warehouseId = 0, orderIds = []) { + const normalizedWarehouseId = Number(warehouseId || 0); + const normalizedOrderIds = this.normalizeIdsInput(orderIds); + if (normalizedOrderIds.length === 0) { + return 0; + } + + const matchModel = this.getWaveStrategyQuickScanMatchModel(); + if (!matchModel || typeof matchModel.destroy !== 'function') { + throw new Error('波次策略命中副表模型不可用'); + } + + let totalDeletedCount = 0; + for (let i = 0; i < normalizedOrderIds.length; i += 500) { + const orderChunk = normalizedOrderIds.slice(i, i + 500); + if (orderChunk.length === 0) { + continue; + } + + const deletedCount = await matchModel.destroy({ + where: { + warehouse_id: normalizedWarehouseId, + order_id: { [Op.in]: orderChunk }, + }, + }); + totalDeletedCount += Number(deletedCount || 0); + } + + return totalDeletedCount; + } + + /** + * 异步处理订单变更后的波次策略快速扫描副表清理与触发。 + * + * @param {number|string} [warehouseId=0] 仓库ID。 + * @param {Array|number|string} [orderIds=[]] 订单ID集合。 + * @param {Object} [options={}] 处理选项。 + * @param {boolean} [options.triggerScan=false] 是否触发快速扫描。 + * @param {string} [options.source=''] 调用来源。 + * @return {void} 无返回值。 + */ + enqueueWaveStrategyQuickScanPostOrderChange(warehouseId = 0, orderIds = [], options = {}) { + const normalizedWarehouseId = Number(warehouseId || 0); + const normalizedOrderIds = this.normalizeIdsInput(orderIds); + if (normalizedOrderIds.length === 0) { + return; + } + + const normalizedOptions = this.isPlainObject(options) ? options : {}; + const triggerScan = this.normalizeBoolean(normalizedOptions.triggerScan, false); + const source = String(normalizedOptions.source || '').trim(); + + setImmediate(() => { + Promise.resolve() + .then(async () => { + const deletedCount = await this.cleanupWaveStrategyQuickScanMatchedStrategiesByOrderIds( + normalizedWarehouseId, + normalizedOrderIds + ); + + if (triggerScan) { + await this.submitWaveStrategyQuickScanForWarehouse(normalizedWarehouseId, { + orderIds: normalizedOrderIds, + }); + } + + this.ctx.logger.info('[wave.enqueueWaveStrategyQuickScanPostOrderChange] 异步处理完成', { + warehouseId: normalizedWarehouseId, + orderCount: normalizedOrderIds.length, + deletedCount, + triggerScan, + source, + }); + }) + .catch(error => { + this.ctx.logger.warn('[wave.enqueueWaveStrategyQuickScanPostOrderChange] 异步处理失败,不影响主流程', { + warehouseId: normalizedWarehouseId, + orderCount: normalizedOrderIds.length, + triggerScan, + source, + error: error && error.message ? error.message : `${error}`, + }); + }); + }); + } + + /** + * 执行快速扫描核心流程。 + * + * @param {Object} [options={}] 执行参数。 + * @param {number} options.warehouseId 仓库ID。 + * @param {number} options.strategyVersion 当前策略版本。 + * @param {Array} [options.orderIds] 可选订单ID数组。 + * @param {string} [options.taskId] 任务ID。 + * @return {Promise} 扫描执行结果。 + */ + async executeWaveStrategyQuickScan(options = {}) { + const normalizedOptions = this.isPlainObject(options) ? options : {}; + const warehouseId = Number(normalizedOptions.warehouseId || 0); + const strategyVersion = this.normalizeWaveStrategyQuickScanVersion(normalizedOptions.strategyVersion); + const taskId = String(normalizedOptions.taskId || '').trim(); + const orderIds = this.normalizeIdsInput(normalizedOptions.orderIds); + + const strategyRows = await this.getWaveStrategyQuickScanStrategyRows(warehouseId); + const strategyList = this.normalizeWaveStrategyQuickScanList(strategyRows); + + const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + const orderRows = await orderModel.findAll({ + attributes: [ + 'id', + 'store_id', + 'items_count', + 'items_total', + 'items_hash', + 'items', + 'logistics_code', + 'sys_logistics_code', + 'logistics_name', + 'province', + 'sys_platform_code', + 'source_platform_code', + ], + where: this.buildWaveStrategyQuickScanOrderWhere(warehouseId, strategyVersion, orderIds), + raw: true, + }); + + const scanResult = await runWaveStrategyQuickScanRunner({ + orders: orderRows, + strategyList, + getStructureKey: order => this.getWaveStrategyQuickScanStructureKey(order), + getExpressKey: order => this.getWaveStrategyQuickScanExpressKey(order), + getMatchedStrategyIds: (order, normalizedStrategyList, context) => this.getWaveStrategyQuickScanMatchedStrategyIds( + order, + normalizedStrategyList, + context + ), + isOrderMatched: (order, normalizedStrategyList, context) => this.isWaveStrategyQuickScanOrderMatched( + order, + normalizedStrategyList, + context + ), + onProgress: taskId + ? async payload => { + const totalOrderCount = Number(payload && payload.totalOrderCount || 0); + const processedOrderCount = Number(payload && payload.processedOrderCount || 0); + const matchedOrderCount = Number(payload && payload.matchedOrderCount || 0); + const unmatchedOrderCount = Number(payload && payload.unmatchedOrderCount || 0); + + const progressPercent = totalOrderCount > 0 + ? Math.min(99, Math.round((processedOrderCount / totalOrderCount) * 100)) + : 0; + + await this.setWaveStrategyQuickScanTaskProgress(taskId, 'running', { + warehouse_id: warehouseId, + total_order_count: totalOrderCount, + processed_order_count: processedOrderCount, + matched_order_count: matchedOrderCount, + unmatched_order_count: unmatchedOrderCount, + progress_percent: progressPercent, + }); + } + : null, + }); + + const matchedOrderIds = this.normalizeIdsInput(scanResult.matchedOrderIds); + const unmatchedOrderIds = this.normalizeIdsInput(scanResult.unmatchedOrderIds); + const matchedStrategyIdsByOrder = this.isPlainObject(scanResult.matchedStrategyIdsByOrder) + ? Object.keys(scanResult.matchedStrategyIdsByOrder).reduce((acc, key) => { + const orderId = Number(key); + if (!Number.isInteger(orderId) || orderId <= 0) { + return acc; + } + + const rawStrategyIds = scanResult.matchedStrategyIdsByOrder[key]; + const normalizedStrategyIds = [ ...new Set((Array.isArray(rawStrategyIds) ? rawStrategyIds : []) + .map(item => Number(item)) + .filter(item => Number.isInteger(item) && item > 0)) ]; + acc[orderId] = normalizedStrategyIds; + return acc; + }, {}) + : {}; + const scanScopeOrderIds = orderIds.length > 0 + ? orderIds + : [ ...new Set([ ...matchedOrderIds, ...unmatchedOrderIds ]) ]; + + await this.batchUpdateWaveStrategyQuickScanOrders(orderModel, matchedOrderIds, { + wave_strategy_version: strategyVersion, + wave_scan_result: 1, + }); + await this.batchUpdateWaveStrategyQuickScanOrders(orderModel, unmatchedOrderIds, { + wave_strategy_version: strategyVersion, + wave_scan_result: 2, + }); + await this.syncWaveStrategyQuickScanMatchedStrategies( + warehouseId, + scanScopeOrderIds, + matchedStrategyIdsByOrder + ); + + return { + strategyVersion, + totalOrderCount: Number(scanResult.totalOrderCount || 0), + processedOrderCount: Number(scanResult.processedOrderCount || 0), + matchedOrderCount: matchedOrderIds.length, + unmatchedOrderCount: unmatchedOrderIds.length, + matchedOrderIds, + unmatchedOrderIds, + matchedStrategyIdsByOrder, + }; + } + /** * 执行波次策略快速扫描后台任务。 * @@ -4752,6 +5507,9 @@ class WaveService extends OrderBaseService { * @param {Object} [params={}] 任务参数。 * @param {string} params.taskId 任务ID。 * @param {number|string} [params.warehouseId] 仓库ID。 + * @param {Array} [params.orderIds] 订单ID数组(驼峰写法)。 + * @param {Array} [params.order_ids] 订单ID数组(下划线写法)。 + * @param {Array} [params.ids] 订单ID数组(兼容写法)。 * @return {Promise} 无返回值。 */ async runWaveStrategyQuickScanTask(params = {}) { @@ -4795,61 +5553,27 @@ class WaveService extends OrderBaseService { }); try { + const normalizedParams = this.isPlainObject(params) ? params : {}; + const rawOrderIds = normalizedParams.orderIds !== undefined + ? normalizedParams.orderIds + : normalizedParams.order_ids !== undefined + ? normalizedParams.order_ids + : normalizedParams.ids; + const orderIds = this.normalizeIdsInput(rawOrderIds); + const subjectConfig = await this.getWarehouseSubjectConfig(warehouseId); const strategyVersion = this.normalizeWaveStrategyQuickScanVersion( this.getWarehouseSubjectConfigValue(subjectConfig, 'wave_strategy_version') ); - const strategyModel = this.ctx.model && ( - this.ctx.model.wms_wave_strategy - || this.ctx.model.PickingStrategy - || this.ctx.model.WmsWaveStrategy - ); - if (!strategyModel || typeof strategyModel.findAll !== 'function') { - throw new Error('波次策略模型不可用'); - } - - const strategyRows = await strategyModel.findAll({ - where: { - warehouse_id: warehouseId, - status: 1, - }, - order: [[ 'id', 'ASC' ]], - raw: true, - }); - const strategyList = this.normalizeWaveStrategyQuickScanList(strategyRows); - - const orderModel = await this.getOrderModel('pendingOrder', warehouseId); - const orderRows = await orderModel.findAll({ - attributes: [ - 'id', - 'store_id', - 'items_count', - 'items_total', - 'items_hash', - 'items', - 'logistics_code', - 'sys_logistics_code', - 'logistics_name', - 'province', - 'sys_platform_code', - 'source_platform_code', - ], - where: { - warehouse_id: warehouseId, - step: { [Op.ne]: 0 }, - wave_id: 0, - [Op.or]: [ - { wave_strategy_version: { [Op.ne]: strategyVersion } }, - { wave_strategy_version: { [Op.is]: null } }, - ], - }, - raw: true, + const scanResult = await this.executeWaveStrategyQuickScan({ + warehouseId, + strategyVersion, + orderIds, + taskId: normalizedTaskId, }); - const normalizedOrders = Array.isArray(orderRows) ? orderRows : []; - const totalOrderCount = normalizedOrders.length; - if (totalOrderCount === 0) { + if (scanResult.totalOrderCount === 0) { const durationMs = Date.now() - startTime; await this.setWaveStrategyQuickScanTaskProgress(normalizedTaskId, 'success', { warehouse_id: warehouseId, @@ -4869,77 +5593,24 @@ class WaveService extends OrderBaseService { return; } - const structureStoreSetMap = new Map(); - - for (const order of normalizedOrders) { - const structureKey = this.getWaveStrategyQuickScanStructureKey(order); - if (!structureKey) { - continue; - } - - const storeId = String(order && order.store_id || '').trim(); - if (!structureStoreSetMap.has(structureKey)) { - structureStoreSetMap.set(structureKey, new Set()); - } - if (storeId) { - structureStoreSetMap.get(structureKey).add(storeId); - } - } - - const matchedOrderIds = []; - const unmatchedOrderIds = []; - let processedOrderCount = 0; - - for (const order of normalizedOrders) { - const matched = this.isWaveStrategyQuickScanOrderMatched(order, strategyList, { - structureStoreSetMap, - }); - - const orderId = Number(order && order.id || 0); - if (Number.isInteger(orderId) && orderId > 0) { - if (matched) { - matchedOrderIds.push(orderId); - } else { - unmatchedOrderIds.push(orderId); - } - } - - processedOrderCount += 1; - if (processedOrderCount % 200 === 0 || processedOrderCount === totalOrderCount) { - await this.setWaveStrategyQuickScanTaskProgress(normalizedTaskId, 'running', { - warehouse_id: warehouseId, - total_order_count: totalOrderCount, - processed_order_count: processedOrderCount, - matched_order_count: matchedOrderIds.length, - unmatched_order_count: unmatchedOrderIds.length, - progress_percent: Math.min(99, Math.round((processedOrderCount / totalOrderCount) * 100)), - }); - } - } - - await this.batchUpdateWaveStrategyQuickScanOrders(orderModel, matchedOrderIds, { - wave_strategy_version: strategyVersion, - wave_scan_result: 1, - }); - await this.batchUpdateWaveStrategyQuickScanOrders(orderModel, unmatchedOrderIds, { - wave_strategy_version: strategyVersion, - wave_scan_result: 2, - }); - const durationMs = Date.now() - startTime; await this.setWaveStrategyQuickScanTaskProgress(normalizedTaskId, 'success', { warehouse_id: warehouseId, - total_order_count: totalOrderCount, - processed_order_count: totalOrderCount, - matched_order_count: matchedOrderIds.length, - unmatched_order_count: unmatchedOrderIds.length, + total_order_count: scanResult.totalOrderCount, + processed_order_count: scanResult.processedOrderCount, + matched_order_count: scanResult.matchedOrderCount, + unmatched_order_count: scanResult.unmatchedOrderCount, progress_percent: 100, end_time: Date.now(), duration_ms: durationMs, result: { strategy_version: strategyVersion, - matched_order_count: matchedOrderIds.length, - unmatched_order_count: unmatchedOrderIds.length, + total_order_count: scanResult.totalOrderCount, + processed_order_count: scanResult.processedOrderCount, + matched_order_count: scanResult.matchedOrderCount, + unmatched_order_count: scanResult.unmatchedOrderCount, + matched_order_ids: scanResult.matchedOrderIds, + unmatched_order_ids: scanResult.unmatchedOrderIds, duration_ms: durationMs, message: '波次策略快速扫描完成', }, @@ -5215,7 +5886,9 @@ class WaveService extends OrderBaseService { const list = Array.isArray(strategyRows) ? strategyRows : []; return list.map(row => { const normalizedRow = this.isPlainObject(row) ? row : {}; + const strategyId = Number(normalizedRow.strategy_id || normalizedRow.strategyId || normalizedRow.id || 0); return { + strategy_id: Number.isInteger(strategyId) && strategyId > 0 ? strategyId : null, order_min_sku: this.normalizeWaveStrategyQuickScanNumberOrNull(normalizedRow.order_min_sku), order_max_sku: this.normalizeWaveStrategyQuickScanNumberOrNull(normalizedRow.order_max_sku), order_min_qty: this.normalizeWaveStrategyQuickScanNumberOrNull(normalizedRow.order_min_qty), @@ -5223,9 +5896,9 @@ class WaveService extends OrderBaseService { min_same_structure: this.normalizeWaveStrategyQuickScanNumberOrNull(normalizedRow.min_same_structure), max_same_structure: this.normalizeWaveStrategyQuickScanNumberOrNull(normalizedRow.max_same_structure), allowed_owners: this.normalizeWaveStrategyQuickScanStringList(normalizedRow.allowed_owners), - allowed_expresses: this.normalizeWaveStrategyQuickScanStringList(normalizedRow.allowed_expresses), + allowed_expresses: this.normalizeWaveStrategyQuickScanStringList(normalizedRow.allowed_expresses, false), allowed_provinces: this.normalizeWaveStrategyQuickScanStringList(normalizedRow.allowed_provinces), - allowed_platforms: this.normalizeWaveStrategyQuickScanStringList(normalizedRow.allowed_platforms), + allowed_platforms: this.normalizeWaveStrategyQuickScanStringList(normalizedRow.allowed_platforms, false), require_same_express: this.normalizeWaveStrategyQuickScanBoolean(normalizedRow.require_same_express, false), allow_cross_owner: this.normalizeWaveStrategyQuickScanBoolean(normalizedRow.allow_cross_owner, true), }; @@ -5284,9 +5957,10 @@ class WaveService extends OrderBaseService { * 支持数组、JSON 字符串、逗号分隔字符串。 * * @param {*} value 原始值。 - * @return {Array} 归一化字符串数组(小写去重)。 + * @param {boolean} [toLowerCase=true] 是否转为小写,默认 true 保持向后兼容。 + * @return {Array} 归一化字符串数组(去重)。 */ - normalizeWaveStrategyQuickScanStringList(value) { + normalizeWaveStrategyQuickScanStringList(value, toLowerCase = true) { let rawList = []; if (Array.isArray(value)) { @@ -5310,7 +5984,7 @@ class WaveService extends OrderBaseService { } return [ ...new Set(rawList - .map(item => String(item || '').trim().toLowerCase()) + .map(item => { const s = String(item || '').trim(); return toLowerCase ? s.toLowerCase() : s; }) .filter(Boolean)) ]; } @@ -5330,23 +6004,54 @@ class WaveService extends OrderBaseService { } /** - * 计算订单快递 key。 + * 计算订单快递 key(同快递判定仅使用 sys_logistics_code)。 * * @param {Object} order 订单记录。 - * @return {string} 快递 key。 + * @return {string} 快递 key(sys_logistics_code 去首尾空格后结果,空值返回空字符串)。 */ getWaveStrategyQuickScanExpressKey(order = {}) { - const sysLogisticsCode = String(order && order.sys_logistics_code || '').trim(); - if (sysLogisticsCode) { - return sysLogisticsCode; + return String(order && order.sys_logistics_code || '').trim(); + } + + /** + * 当 require_same_express=1 时,按快递分组候选订单,仅保留最大快递组的订单。 + * + * 分组 key 使用 getWaveStrategyQuickScanExpressKey(sys_logistics_code), + * 空 key 的订单不参与筛选(直接丢弃)。 + * + * @param {Array} candidateRows 候选订单数组。 + * @return {Array} 按快递筛选后的候选订单数组(仅含最大快递组)。 + */ + filterCandidateOrdersByRequireSameExpress(candidateRows = []) { + const rows = Array.isArray(candidateRows) ? candidateRows : []; + if (rows.length === 0) { + return []; } - const logisticsCode = String(order && order.logistics_code || '').trim(); - if (logisticsCode) { - return logisticsCode; + const expressGroups = new Map(); + for (const row of rows) { + const expressKey = this.getWaveStrategyQuickScanExpressKey(row); + if (!expressKey) { + continue; + } + if (!expressGroups.has(expressKey)) { + expressGroups.set(expressKey, []); + } + expressGroups.get(expressKey).push(row); } - return String(order && order.logistics_name || '').trim(); + if (expressGroups.size === 0) { + return []; + } + + let maxGroup = []; + for (const groupOrders of expressGroups.values()) { + if (groupOrders.length > maxGroup.length) { + maxGroup = groupOrders; + } + } + + return maxGroup; } /** @@ -5358,18 +6063,39 @@ class WaveService extends OrderBaseService { * @return {boolean} 是否命中。 */ isWaveStrategyQuickScanOrderMatched(order = {}, strategyList = [], context = {}) { + const matchedStrategyIds = this.getWaveStrategyQuickScanMatchedStrategyIds(order, strategyList, context); + return matchedStrategyIds.length > 0; + } + + /** + * 获取订单命中的快速扫描策略ID列表。 + * + * 全量遍历 strategyList,不提前返回,收集所有命中策略的 strategy_id。 + * + * @param {Object} order 订单记录。 + * @param {Array} strategyList 策略列表。 + * @param {Object} [context={}] 统计上下文。 + * @return {Array} 去重后的正整数策略ID列表。 + */ + getWaveStrategyQuickScanMatchedStrategyIds(order, strategyList, context = {}) { const list = Array.isArray(strategyList) ? strategyList : []; if (list.length === 0) { - return false; + return []; } + const matchedStrategyIds = []; for (const strategy of list) { - if (this.isWaveStrategyQuickScanOrderMatchedSingleStrategy(order, strategy, context)) { - return true; + if (!this.isWaveStrategyQuickScanOrderMatchedSingleStrategy(order, strategy, context)) { + continue; + } + + const strategyId = Number(strategy && strategy.strategy_id || 0); + if (Number.isInteger(strategyId) && strategyId > 0) { + matchedStrategyIds.push(strategyId); } } - return false; + return [ ...new Set(matchedStrategyIds) ]; } /** @@ -5384,15 +6110,42 @@ class WaveService extends OrderBaseService { const normalizedOrder = this.isPlainObject(order) ? order : {}; const normalizedStrategy = this.isPlainObject(strategy) ? strategy : {}; const structureStoreSetMap = context && context.structureStoreSetMap instanceof Map ? context.structureStoreSetMap : new Map(); + const structurePrimaryExpressMap = context && context.structurePrimaryExpressMap instanceof Map + ? context.structurePrimaryExpressMap + : null; + const structurePrimaryOwnerMap = context && context.structurePrimaryOwnerMap instanceof Map + ? context.structurePrimaryOwnerMap + : null; const structureKey = this.getWaveStrategyQuickScanStructureKey(normalizedOrder); if (!structureKey) { return false; } + const storeId = String(normalizedOrder.store_id || '').trim().toLowerCase(); + if (normalizedStrategy.allow_cross_owner === false) { - const ownerSet = structureStoreSetMap.get(structureKey); - if (ownerSet instanceof Set && ownerSet.size > 1) { + if (structurePrimaryOwnerMap instanceof Map) { + const primaryOwnerStoreId = String(structurePrimaryOwnerMap.get(structureKey) || '').trim().toLowerCase(); + if (!primaryOwnerStoreId || storeId !== primaryOwnerStoreId) { + return false; + } + } else { + const ownerSet = structureStoreSetMap.get(structureKey); + if (ownerSet instanceof Set && ownerSet.size > 1) { + return false; + } + } + } + + if (normalizedStrategy.require_same_express === true && structurePrimaryExpressMap instanceof Map) { + const primaryExpressKey = String(structurePrimaryExpressMap.get(structureKey) || '').trim().toLowerCase(); + if (!primaryExpressKey) { + return false; + } + + const currentExpressKey = String(this.getWaveStrategyQuickScanExpressKey(normalizedOrder) || '').trim().toLowerCase(); + if (currentExpressKey !== primaryExpressKey) { return false; } } @@ -5407,7 +6160,6 @@ class WaveService extends OrderBaseService { return false; } - const storeId = String(normalizedOrder.store_id || '').trim().toLowerCase(); if (normalizedStrategy.allowed_owners.length > 0 && !normalizedStrategy.allowed_owners.includes(storeId)) { return false; } @@ -5418,7 +6170,8 @@ class WaveService extends OrderBaseService { String(normalizedOrder.logistics_name || '').trim().toLowerCase(), ].filter(Boolean); if (normalizedStrategy.allowed_expresses.length > 0) { - const hitExpress = expressCandidates.some(code => normalizedStrategy.allowed_expresses.includes(code)); + const allowedLower = (normalizedStrategy.allowed_expresses || []).map(s => String(s).toLowerCase()); + const hitExpress = expressCandidates.some(code => allowedLower.includes(code)); if (!hitExpress) { return false; } @@ -5434,7 +6187,8 @@ class WaveService extends OrderBaseService { String(normalizedOrder.source_platform_code || '').trim().toLowerCase(), ].filter(Boolean); if (normalizedStrategy.allowed_platforms.length > 0) { - const hitPlatform = platformCandidates.some(code => normalizedStrategy.allowed_platforms.includes(code)); + const allowedPlatformsLower = normalizedStrategy.allowed_platforms.map(s => String(s).toLowerCase()); + const hitPlatform = platformCandidates.some(code => allowedPlatformsLower.includes(code)); if (!hitPlatform) { return false; } @@ -5606,6 +6360,7 @@ class WaveService extends OrderBaseService { } const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + const transaction = await this.ctx.model.transaction(); try { @@ -5677,7 +6432,7 @@ class WaveService extends OrderBaseService { waveType: 2, distinguishExpress: false, logisticsName: '', - itemSnapshotKey: '混合订单', + itemSnapshotKey: 'manual_single_ids', wavePrefix: singleFetchByIdsWavePrefix, transaction, }); @@ -5751,14 +6506,6 @@ class WaveService extends OrderBaseService { }); } - await this.rebuildOrderWaveIndex({ - warehouseId, - waveId, - orderIds: grabbedOrderIds, - orderModel, - transaction, - }); - await transaction.commit(); await this.batchCreateOrderOperationLogs(grabbedOrderIds.map(orderId => ({ @@ -5769,6 +6516,10 @@ class WaveService extends OrderBaseService { warehouseId, scene: 'singleFetchByIds', }); + this.enqueueWaveStrategyQuickScanPostOrderChange(warehouseId, grabbedOrderIds, { + triggerScan: false, + source: 'singleFetchByIds', + }); return this.success('ok', { ids: normalizedIds, @@ -5822,6 +6573,37 @@ class WaveService extends OrderBaseService { } const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + + const removableRowsForCheck = await orderModel.findAll({ + attributes: [ 'wave_id' ], + where: { + id: { [Op.in]: normalizedIds }, + step: { [Op.in]: [ 1, 2, 3 ] }, + wave_id: { [Op.gt]: 0 }, + }, + raw: true, + }); + const affectedWaveIdsForCheck = [ ...new Set((Array.isArray(removableRowsForCheck) ? removableRowsForCheck : []) + .map(row => Number(row && row.wave_id || 0)) + .filter(waveId => Number.isInteger(waveId) && waveId > 0)) ]; + if (affectedWaveIdsForCheck.length > 0) { + const activeTaskWaves = await this.ctx.model.query( + `SELECT ptw.wave_id + FROM wms_wave_pick_task_wave ptw + INNER JOIN wms_wave_pick_task pt ON pt.id = ptw.task_id + WHERE ptw.wave_id IN (:waveIds) + AND pt.status IN (0, 1) + LIMIT 1`, + { + replacements: { waveIds: affectedWaveIdsForCheck }, + type: this.ctx.model.QueryTypes.SELECT, + } + ); + if (activeTaskWaves.length > 0) { + throw new Error('波次属于活动拣货任务,请通过任务取消接口处理'); + } + } + const transaction = await this.ctx.model.transaction(); try { @@ -5884,13 +6666,39 @@ class WaveService extends OrderBaseService { const updatedOrderCount = Number(Array.isArray(orderUpdateResult) ? orderUpdateResult[0] : orderUpdateResult || 0); - const remainingCountMap = await this.replaceOrderWaveIndexByWaveIds({ + await this.deleteOrderWaveIndexByOrderIds({ warehouseId, - waveIds: affectedWaveIds, - orderModel, + orderIds: removedOrderIds, transaction, }); + const remainingRows = await orderModel.findAll({ + attributes: [ + 'wave_id', + [ this.ctx.model.fn('COUNT', this.ctx.model.col('id')), 'remaining_count' ], + ], + where: { + wave_id: { + [Op.in]: affectedWaveIds, + [Op.gt]: 0, + }, + }, + group: [ 'wave_id' ], + raw: true, + transaction, + }); + + const remainingCountMap = new Map(); + for (const row of (Array.isArray(remainingRows) ? remainingRows : [])) { + const waveId = Number(row && row.wave_id || 0); + const remainingCount = Number(row && row.remaining_count || 0); + if (!Number.isInteger(waveId) || waveId <= 0) { + continue; + } + + remainingCountMap.set(waveId, Number.isInteger(remainingCount) && remainingCount > 0 ? remainingCount : 0); + } + const updatedWaveIds = []; const emptiedWaveIds = []; @@ -5949,6 +6757,10 @@ class WaveService extends OrderBaseService { warehouseId, scene: 'batchRemoveOrders', }); + this.enqueueWaveStrategyQuickScanPostOrderChange(warehouseId, removedOrderIds, { + triggerScan: true, + source: 'batchRemoveOrders', + }); return this.success('ok', { ids: normalizedIds, @@ -6011,7 +6823,7 @@ class WaveService extends OrderBaseService { task_id: taskId, warehouse_id: Number(existingTask.warehouse_id || warehouseId), state: String(existingTask.state || 'submitted').trim() || 'submitted', - message: 'Batch remove exception orders task already exists. Check progress with order.wave.batchRemoveExceptionOrdersTaskProgress', + message: '批量移除异常订单任务已存在,请勿重复提交。', accepted_at: existingTask.accepted_at || existingTask.submitted_at || new Date().toISOString(), }); } @@ -6060,7 +6872,7 @@ class WaveService extends OrderBaseService { status: 'success', task_id: taskId, warehouse_id: warehouseId, - message: 'Batch remove exception orders submitted. Check progress with order.wave.batchRemoveExceptionOrdersTaskProgress', + message: '批量移除异常订单任务已提交。', accepted_at: acceptedAt, }); } @@ -6700,6 +7512,7 @@ class WaveService extends OrderBaseService { let affectedOrderCount = 0; let canceledWaveCount = 0; const affectedWaveIds = []; + const removedOrderIdSet = new Set(); for (const wave of targetWaves) { const waveId = Number(wave.wave_id || 0); @@ -6730,9 +7543,6 @@ class WaveService extends OrderBaseService { }; }) .filter(Boolean); - const affectedOrderIds = [ ...new Set((Array.isArray(affectedOrderRows) ? affectedOrderRows : []) - .map(row => Number(row && row.id || 0)) - .filter(orderId => Number.isInteger(orderId) && orderId > 0)) ]; const orderUpdateResult = await orderModel.update({ wave_id: 0, @@ -6743,21 +7553,6 @@ class WaveService extends OrderBaseService { }, transaction, }); - - if (affectedOrderIds.length > 0) { - await this.deleteOrderWaveIndexByOrderIds({ - warehouseId, - orderIds: affectedOrderIds, - transaction, - }); - } else { - await this.deleteOrderWaveIndexByWaveIds({ - warehouseId, - waveIds: [ waveId ], - transaction, - }); - } - const currentAffectedOrderCount = Number( Array.isArray(orderUpdateResult) ? orderUpdateResult[0] : orderUpdateResult || 0 ); @@ -6782,6 +7577,12 @@ class WaveService extends OrderBaseService { || 0 ); + await this.deleteOrderWaveIndexByWaveIds({ + warehouseId, + waveIds: [ waveId ], + transaction, + }); + await transaction.commit(); await this.batchCreateOrderOperationLogs(cancelOrderLogItems, { @@ -6789,6 +7590,13 @@ class WaveService extends OrderBaseService { scene: 'batchCancel', }); + const currentRemovedOrderIds = (Array.isArray(affectedOrderRows) ? affectedOrderRows : []) + .map(row => Number(row && row.id || 0)) + .filter(orderId => Number.isInteger(orderId) && orderId > 0); + for (const orderId of currentRemovedOrderIds) { + removedOrderIdSet.add(orderId); + } + processedWaveCount += 1; affectedOrderCount += Number.isInteger(currentAffectedOrderCount) && currentAffectedOrderCount > 0 ? currentAffectedOrderCount @@ -6832,6 +7640,12 @@ class WaveService extends OrderBaseService { } } + const removedOrderIds = [ ...removedOrderIdSet ].sort((a, b) => a - b); + this.enqueueWaveStrategyQuickScanPostOrderChange(warehouseId, removedOrderIds, { + triggerScan: true, + source: 'batchCancel', + }); + const durationMs = Date.now() - startTime; await this.setBatchCancelTaskProgress(normalizedTaskId, 'success', { warehouse_id: warehouseId, @@ -7362,11 +8176,6 @@ class WaveService extends OrderBaseService { } const startTime = Date.now(); - let matchedOrderIds = []; - let matchedOrderCount = 0; - let orderModel = null; - let useBusinessKeyColumn = true; - let normalizedOrders = []; await this.setBatchAllocateExpressTaskProgress(normalizedTaskId, 'running', { warehouse_id: warehouseId, wave_ids: waveIds.join(','), @@ -7386,7 +8195,7 @@ class WaveService extends OrderBaseService { }); try { - orderModel = await this.getOrderModel('pendingOrder', warehouseId); + const orderModel = await this.getOrderModel('pendingOrder', warehouseId); const baseOrderWhere = { warehouse_id: warehouseId, wave_id: { @@ -7397,6 +8206,7 @@ class WaveService extends OrderBaseService { }, }; let orderRows = []; + let useBusinessKeyColumn = true; try { orderRows = await orderModel.findAll({ @@ -7431,22 +8241,20 @@ class WaveService extends OrderBaseService { matchedOrderCount: Array.isArray(orderRows) ? orderRows.length : 0, }); - normalizedOrders = (Array.isArray(orderRows) ? orderRows : []) + const normalizedOrders = (Array.isArray(orderRows) ? orderRows : []) .map(row => { const orderId = Number(row && row.id || 0); if (!Number.isInteger(orderId) || orderId <= 0) { return null; } - const businessKey = Number(useBusinessKeyColumn ? row && row.business_key : 0); + const businessKey = Number(useBusinessKeyColumn ? row && row.business_key : 1); return { order_id: orderId, - business_key: Number.isInteger(businessKey) && businessKey > 0 ? businessKey : 0, + business_key: Number.isInteger(businessKey) && businessKey > 0 ? businessKey : 1, }; }) .filter(Boolean); - matchedOrderIds = normalizedOrders.map(item => Number(item && item.order_id || 0)).filter(orderId => Number.isInteger(orderId) && orderId > 0); - matchedOrderCount = matchedOrderIds.length; if (normalizedOrders.length === 0) { this.ctx.logger.info('[wave.batchAllocateExpress] 未筛选到可分配快递号订单', { @@ -7524,57 +8332,6 @@ class WaveService extends OrderBaseService { trace_id: traceId, }); } catch (error) { - const durationMs = Date.now() - startTime; - const canIdentifyBusinessKey = useBusinessKeyColumn; - const rollbackOrderIds = canIdentifyBusinessKey - ? normalizedOrders - .filter(item => Number(item && item.business_key) === 1) - .map(item => Number(item && item.order_id || 0)) - .filter(orderId => Number.isInteger(orderId) && orderId > 0) - : []; - if (!canIdentifyBusinessKey) { - this.ctx.logger.warn('[wave.batchAllocateExpress] business_key 列不可用,按强约束跳过 post_status 失败回写', { - traceId, - taskId: normalizedTaskId, - warehouseId, - waveIds, - matchedOrderCount, - }); - } else if (rollbackOrderIds.length === 0) { - this.ctx.logger.info('[wave.batchAllocateExpress] 未命中 business_id=1 订单,跳过 post_status 失败回写', { - traceId, - taskId: normalizedTaskId, - warehouseId, - waveIds, - matchedOrderCount, - }); - } - - if (rollbackOrderIds.length > 0 && orderModel && typeof orderModel.update === 'function') { - try { - await this.service.systems.express.markWaybillAsyncOrdersAsError( - orderModel, - rollbackOrderIds, - error && error.message ? `${error.message}` : `${error}`, - { - warehouse_id: warehouseId, - wave_id: { - [Op.in]: waveIds, - }, - } - ); - } catch (updateError) { - this.ctx.logger.warn('[wave.batchAllocateExpress] 通过统一 helper 回写订单失败状态失败', { - traceId, - taskId: normalizedTaskId, - warehouseId, - waveIds, - matchedOrderCount: rollbackOrderIds.length, - error: updateError && updateError.message ? updateError.message : `${updateError}`, - }); - } - } - this.ctx.logger.error('[wave.batchAllocateExpress] 后台任务执行失败', { traceId, taskId: normalizedTaskId, @@ -7585,14 +8342,9 @@ class WaveService extends OrderBaseService { }); await this.setBatchAllocateExpressTaskProgress(normalizedTaskId, 'failed', { warehouse_id: warehouseId, - total_wave_count: waveIds.length, - total_order_count: matchedOrderCount, - processed_order_count: matchedOrderCount, - success_order_count: 0, - failed_order_count: matchedOrderCount, - progress_percent: 100, + progress_percent: 0, end_time: Date.now(), - duration_ms: durationMs, + duration_ms: Date.now() - startTime, error: error && error.message ? error.message : `${error}`, error_code: 'WAVE_BATCH_ALLOCATE_EXPRESS_FAILED', trace_id: traceId, @@ -7962,14 +8714,6 @@ class WaveService extends OrderBaseService { transaction, }); - const orderModel = await this.getOrderModel('pendingOrder', warehouseId); - await this.replaceOrderWaveIndexByWaveIds({ - warehouseId, - waveIds: updatableWaveIds, - orderModel, - transaction, - }); - const updateMeta = Array.isArray(updateResult) ? updateResult[1] : null; const updatedWaveCount = Number( updateMeta && (updateMeta.affectedRows || updateMeta.affectedCount || updateMeta.rowCount) @@ -8079,14 +8823,6 @@ class WaveService extends OrderBaseService { transaction, }); - const orderModel = await this.getOrderModel('pendingOrder', warehouseId); - await this.replaceOrderWaveIndexByWaveIds({ - warehouseId, - waveIds: updatedWaveIds, - orderModel, - transaction, - }); - const updateMeta = Array.isArray(updateResult) ? updateResult[1] : null; const updatedWaveCount = Number( updateMeta && (updateMeta.affectedRows || updateMeta.affectedCount || updateMeta.rowCount) @@ -8516,6 +9252,2996 @@ class WaveService extends OrderBaseService { return this.submitFetchTask(normalizedData, 'single', maxFetchQuantity); } + /** + * 按策略与策略类型推导本次抓取的拣货模式。 + * + * 优先使用显式入参 pick_mode/pickMode,其次回退到策略字段(strategy_type、batch_mode)。 + * + * @param {Object} options 推导参数。 + * @param {Object} [options.requestData={}] 请求参数。 + * @param {Object} [options.strategyRow={}] 策略行数据。 + * @return {number} 归一化后的拣货模式(1-5,异常时为 0)。 + */ + resolveWaveStrategyFetchPickMode(options = {}) { + const requestData = this.isPlainObject(options && options.requestData) + ? options.requestData + : {}; + const strategyRow = this.isPlainObject(options && options.strategyRow) + ? options.strategyRow + : {}; + + const explicitPickMode = Number(requestData.pick_mode ?? requestData.pickMode); + if (Number.isInteger(explicitPickMode) && explicitPickMode >= 1 && explicitPickMode <= 5) { + return explicitPickMode; + } + + const strategyType = Number(strategyRow.strategy_type || 0); + const batchMode = Number(strategyRow.batch_mode || 0); + const groupBatchMaxOrders = Number(strategyRow.group_batch_max_orders || 0); + + if (strategyType === 2) { + if (groupBatchMaxOrders > 1) { + return 1; + } + return 5; + } + + if (batchMode === 1) { + return 2; + } + if (batchMode === 2) { + return 3; + } + if ([ 3, 4, 5, 6 ].includes(batchMode)) { + return 4; + } + + return 0; + } + + /** + * 构建抓取策略的框分配规则(最小可执行结构)。 + * + * @param {Object} options 构建参数。 + * @param {number} options.pickMode 拣货模式。 + * @param {Array} [options.selectedWaveIds=[]] 预抓波次ID集合。 + * @param {number} [options.boxLimit=0] 最大可用框数。 + * @return {Array} 框分配规则列表。 + */ + buildWaveStrategyFetchBoxAssignments(options = {}) { + const pickMode = Number(options && options.pickMode || 0); + const selectedWaveIds = Array.isArray(options && options.selectedWaveIds) + ? options.selectedWaveIds + : []; + const boxLimit = Number(options && options.boxLimit || 0); + + if (pickMode === 1) { + return selectedWaveIds.map((waveId, index) => ({ + wave_id: waveId, + box_no: index + 1, + rule: 'one_wave_one_box', + })); + } + + if (selectedWaveIds.length > 0) { + return [{ + wave_id: selectedWaveIds[0], + box_no: 1, + rule: pickMode === 5 ? 'single_wave_dynamic_append' : 'single_wave_single_box', + }]; + } + + return [{ + wave_id: null, + box_no: 1, + rule: pickMode === 5 ? 'single_wave_dynamic_append' : 'single_wave_single_box', + box_limit: Number.isInteger(boxLimit) && boxLimit > 0 ? boxLimit : 1, + }]; + } + + /** + * 策略抓取前置预处理:统一输出标准化 plan。 + * + * 仅做策略与参数预处理,不执行任务写库。 + * + * @param {Object} params 预处理入参。 + * @param {number|string} params.strategyId 策略ID。 + * @param {number|string} params.warehouseId 仓库ID。 + * @param {Object} [params.operator={}] 操作人信息。 + * @param {string} [params.source='unknown'] 来源标识(pda/admin)。 + * @param {Object} [params.data={}] 原始请求参数。 + * @return {Promise} 标准化抓取 plan。 + */ + async prepareWaveStrategyFetchPlan(params = {}) { + const strategyId = this.normalizeRequiredPositiveInteger(params && params.strategyId, 'strategy_id'); + const warehouseId = this.normalizeRequiredPositiveInteger(params && params.warehouseId, 'warehouse_id'); + const source = String(params && params.source || 'unknown').trim() || 'unknown'; + const operator = this.isPlainObject(params && params.operator) ? params.operator : {}; + const requestData = this.isPlainObject(params && params.data) ? params.data : {}; + const hasExplicitWaveSelectionInput = [ + 'selected_wave_ids', + 'selectedWaveIds', + 'wave_ids', + 'waveIds', + 'wave_id', + 'waveId', + ].some(fieldName => Object.prototype.hasOwnProperty.call(requestData, fieldName)); + + const plan = { + strategy_id: strategyId, + warehouse_id: warehouseId, + source, + operator, + pick_mode: 0, + wave_limit: 0, + order_limit: 0, + sku_limit: 0, + box_limit: 0, + selected_wave_ids: [], + box_assignments: [], + dynamic_append: false, + validation_errors: [], + }; + + let strategyRows = []; + try { + strategyRows = await this.getWaveStrategyQuickScanStrategyRows(warehouseId); + } catch (error) { + strategyRows = []; + } + + let strategyRow = (Array.isArray(strategyRows) ? strategyRows : []).find(item => { + const currentId = Number(item && (item.id ?? item.strategy_id ?? item.strategyId) || 0); + return Number.isInteger(currentId) && currentId === strategyId; + }) || null; + + if (!strategyRow) { + const strategyModel = this.getWaveStrategyModel(); + if (strategyModel && typeof strategyModel.findOne === 'function') { + const strategyEntity = await strategyModel.findOne({ + where: { + id: strategyId, + warehouse_id: warehouseId, + status: 1, + }, + raw: true, + }); + if (strategyEntity && typeof strategyEntity.get === 'function') { + strategyRow = strategyEntity.get({ plain: true }); + } else { + strategyRow = strategyEntity || null; + } + } + } + + if (!strategyRow) { + plan.validation_errors.push(`策略不存在或已停用: ${strategyId}`); + return plan; + } + + plan.strategy_type = Number(strategyRow.strategy_type || 0); + plan.strategy_row = strategyRow; + + const selectedWaveIds = this.normalizeIdsInput( + requestData.selected_wave_ids !== undefined + ? requestData.selected_wave_ids + : requestData.selectedWaveIds !== undefined + ? requestData.selectedWaveIds + : requestData.wave_ids !== undefined + ? requestData.wave_ids + : requestData.waveIds !== undefined + ? requestData.waveIds + : requestData.wave_id !== undefined + ? requestData.wave_id + : requestData.waveId + ); + plan.selected_wave_ids = selectedWaveIds; + + const pickMode = this.resolveWaveStrategyFetchPickMode({ + requestData, + strategyRow, + }); + plan.pick_mode = pickMode; + + if (![ 1, 2, 3, 4, 5 ].includes(pickMode)) { + plan.validation_errors.push('无法从策略推导有效 pick_mode,请显式传入 pick_mode(1-5)'); + } + + const rawBoxLimit = requestData.box_limit ?? requestData.boxLimit ?? strategyRow.group_batch_max_orders; + const normalizedBoxLimit = Number(rawBoxLimit); + plan.box_limit = Number.isInteger(normalizedBoxLimit) && normalizedBoxLimit > 0 ? normalizedBoxLimit : 1; + + const rawOrderLimit = requestData.order_limit ?? requestData.orderLimit ?? strategyRow.batch_max_orders; + const normalizedOrderLimit = Number(rawOrderLimit); + plan.order_limit = Number.isInteger(normalizedOrderLimit) && normalizedOrderLimit > 0 ? normalizedOrderLimit : 0; + + const rawSkuLimit = requestData.sku_limit ?? requestData.skuLimit ?? strategyRow.batch_max_skus; + const normalizedSkuLimit = Number(rawSkuLimit); + plan.sku_limit = Number.isInteger(normalizedSkuLimit) && normalizedSkuLimit > 0 ? normalizedSkuLimit : 0; + + const rawWaveLimit = requestData.wave_limit ?? requestData.waveLimit; + const normalizedWaveLimit = Number(rawWaveLimit); + if (Number.isInteger(normalizedWaveLimit) && normalizedWaveLimit > 0) { + plan.wave_limit = normalizedWaveLimit; + } else { + plan.wave_limit = pickMode === 1 ? plan.box_limit : 1; + } + + if (pickMode === 1) { + if (plan.box_limit <= 0) { + plan.validation_errors.push('小团购模式 box_limit 必须大于 0'); + } + if (selectedWaveIds.length > plan.box_limit) { + plan.validation_errors.push(`小团购模式预抓波次数(${selectedWaveIds.length})超过 box_limit(${plan.box_limit})`); + } + } + + if ([ 1, 5 ].includes(pickMode) && hasExplicitWaveSelectionInput && selectedWaveIds.length === 0) { + plan.validation_errors.push('当前模式依赖波次,selected_wave_ids 不能为空'); + } + + if ([ 2, 3, 4 ].includes(pickMode) && selectedWaveIds.length > 1) { + plan.validation_errors.push('单品单件/先拣后分/边拣边分模式一次仅支持一个波次'); + } + + if (pickMode === 2 && plan.order_limit <= 0) { + plan.validation_errors.push('单品单件模式 order_limit 必须大于 0'); + } + + if (pickMode === 3 && plan.sku_limit <= 0) { + plan.validation_errors.push('先拣后分模式 sku_limit 必须大于 0'); + } + + if (pickMode === 5) { + plan.dynamic_append = true; + if (selectedWaveIds.length > 1) { + plan.validation_errors.push('大团购模式一次仅支持一个波次(后续追加采用动态扫描)'); + } + } + + plan.box_assignments = this.buildWaveStrategyFetchBoxAssignments({ + pickMode, + selectedWaveIds, + boxLimit: plan.box_limit, + }); + + return plan; + } + + /** + * 校验当前操作用户是否存在未完成任务。 + * + * 活跃状态定义:status in (0,1),不包含已完成(status=2)的任务。 + * + * @param {Object} params 校验参数。 + * @param {number|string} params.warehouseId 仓库ID。 + * @param {number|string} params.operatorId 操作用户ID。 + * @param {Object} params.transaction 事务对象。 + * @return {Promise} 无返回值。 + */ + async ensureNoActiveWavePickTaskForOperator(params = {}) { + const warehouseId = this.normalizeRequiredPositiveInteger(params.warehouseId, 'warehouse_id'); + const operatorId = Number(params.operatorId || 0); + const transaction = params.transaction; + + if (!Number.isInteger(operatorId) || operatorId <= 0) { + return; + } + + const rows = await this.ctx.model.query(` + SELECT id, task_no + FROM wms_wave_pick_task + WHERE warehouse_id = :warehouseId + AND pick_user_id = :operatorId + AND status IN (0, 1) + ORDER BY id DESC + LIMIT 1 + FOR UPDATE + `, { + replacements: { + warehouseId, + operatorId, + }, + type: this.ctx.model.QueryTypes.SELECT, + transaction, + }); + + const activeTask = Array.isArray(rows) ? rows[0] : null; + if (activeTask) { + const taskNo = String(activeTask.task_no || '').trim(); + const taskId = Number(activeTask.id || 0); + throw new Error(`当前用户存在未完成任务,请先完成后再创建(task_id=${taskId}${taskNo ? `,task_no=${taskNo}` : ''})`); + } + } + + /** + * 查询策略自动分流候选订单(命中策略且未分配波次)。 + * + * 过滤口径:step != 0、wave_id = 0、status != cancel、outbound_status != padding, + * 并按同结构数量命中 min_same_structure/max_same_structure。 + * + * @param {Object} params 查询参数。 + * @param {number|string} params.warehouseId 仓库ID。 + * @param {number|string} params.strategyId 策略ID。 + * @param {number|string|null} [params.minSameStructure=0] 最小同结构数量。 + * @param {number|string|null} [params.maxSameStructure=null] 最大同结构数量。 + * @return {Promise>} 候选订单数组(按 order_id 升序)。 + */ + async getWaveStrategyFetchCandidateOrders(params = {}) { + const warehouseId = this.normalizeRequiredPositiveInteger(params.warehouseId, 'warehouse_id'); + const strategyId = this.normalizeRequiredPositiveInteger(params.strategyId, 'strategy_id'); + const minSameStructureRaw = Number(params.minSameStructure ?? 0); + const maxSameStructureRaw = Number(params.maxSameStructure); + const minSameStructure = Number.isFinite(minSameStructureRaw) && minSameStructureRaw > 0 + ? Math.floor(minSameStructureRaw) + : 0; + const maxSameStructure = Number.isFinite(maxSameStructureRaw) && maxSameStructureRaw > 0 + ? Math.floor(maxSameStructureRaw) + : null; + const requireSameExpress = Number(params.requireSameExpress ?? 0) === 1; + + const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + const orderTableName = this.getModelTableSqlName(orderModel); + const structureExpr = alias => `COALESCE(NULLIF(TRIM(COALESCE(${alias}.items_hash, '')), ''), TRIM(COALESCE(${alias}.items, '')))`; + const expressExpr = alias => `COALESCE(NULLIF(TRIM(COALESCE(${alias}.sys_logistics_code, '')), ''), NULLIF(TRIM(COALESCE(${alias}.logistics_code, '')), ''), TRIM(COALESCE(${alias}.logistics_name, '')))`; + const groupKeyExtra = requireSameExpress ? `, ${expressExpr('src')}` : ''; + const joinKeyExtra = requireSameExpress ? ` AND same_structure.express_key = ${expressExpr('o')}` : ''; + const rows = await this.ctx.model.query(` + SELECT + o.id, + o.items_hash, + o.items, + o.logistics_name, + o.sys_logistics_code, + o.logistics_code, + o.items_count, + o.items_total + FROM wms_order_wave_strategy_match m + INNER JOIN ${orderTableName} o + ON o.id = m.order_id + AND o.warehouse_id = :warehouseId + AND o.wave_id = 0 + AND o.step != 0 + AND o.post_status = 'fin' + AND o.storage_status = 'fin' + AND o.status != 'cancel' + AND o.outbound_status != 'padding' + INNER JOIN ( + SELECT + ${structureExpr('src')} AS structure_key${requireSameExpress ? `, ${expressExpr('src')} AS express_key` : ''}, + COUNT(1) AS same_structure_count + FROM ${orderTableName} src + WHERE src.warehouse_id = :warehouseId + AND src.wave_id = 0 + AND src.step != 0 + AND src.post_status = 'fin' + AND src.storage_status = 'fin' + AND src.status != 'cancel' + AND src.outbound_status != 'padding' + GROUP BY ${structureExpr('src')}${groupKeyExtra} + ) same_structure + ON same_structure.structure_key = ${structureExpr('o')}${joinKeyExtra} + WHERE m.warehouse_id = :warehouseId + AND m.strategy_id = :strategyId + AND same_structure.same_structure_count >= :minSameStructure + AND (:maxSameStructure IS NULL OR same_structure.same_structure_count <= :maxSameStructure) + ORDER BY o.id ASC + `, { + replacements: { + warehouseId, + strategyId, + minSameStructure, + maxSameStructure, + }, + type: this.ctx.model.QueryTypes.SELECT, + }); + + return (Array.isArray(rows) ? rows : []) + .map(row => ({ + id: Number(row && row.id || 0), + items_hash: String(row && row.items_hash || '').trim(), + items: String(row && row.items || '').trim(), + logistics_name: String(row && row.logistics_name || '').trim(), + sys_logistics_code: String(row && row.sys_logistics_code || '').trim(), + logistics_code: String(row && row.logistics_code || '').trim(), + items_count: Number(row && row.items_count || 0), + items_total: Number(row && row.items_total || 0), + })) + .filter(row => Number.isInteger(row.id) && row.id > 0) + .sort((a, b) => a.id - b.id); + } + + /** + * 按订单结构对候选订单分组。 + * + * @param {Array} candidateRows 候选订单数组。 + * @return {Array} 分组结果(含 group_min_order_id)。 + */ + groupWaveStrategyFetchCandidateOrdersByStructure(candidateRows = []) { + const groupedMap = new Map(); + const rows = Array.isArray(candidateRows) ? candidateRows : []; + + for (const row of rows) { + const structureKey = this.getWaveStrategyQuickScanStructureKey(row); + if (!structureKey) { + continue; + } + + if (!groupedMap.has(structureKey)) { + groupedMap.set(structureKey, []); + } + groupedMap.get(structureKey).push(row); + } + + return Array.from(groupedMap.entries()) + .map(([ structureKey, orders ]) => { + const sortedOrders = orders + .map(item => ({ ...item })) + .sort((a, b) => Number(a.id || 0) - Number(b.id || 0)); + const minOrderId = sortedOrders.length > 0 ? Number(sortedOrders[0].id || 0) : 0; + return { + structure_key: structureKey, + group_min_order_id: minOrderId, + orders: sortedOrders, + order_ids: sortedOrders.map(item => Number(item.id || 0)).filter(id => Number.isInteger(id) && id > 0), + }; + }) + .filter(group => group.order_ids.length > 0) + .sort((a, b) => a.group_min_order_id - b.group_min_order_id); + } + + /** + * 读取订单商品明细并构建每单 SKU 集合。 + * + * @param {Object} params 构建参数。 + * @param {number|string} params.warehouseId 仓库ID。 + * @param {Array} params.orderIds 订单ID数组。 + * @return {Promise>>} order_id 到 SKU 集合映射。 + */ + async buildWaveStrategyFetchOrderSkuMap(params = {}) { + const warehouseId = this.normalizeRequiredPositiveInteger(params.warehouseId, 'warehouse_id'); + const orderIds = this.normalizeIdsInput(params.orderIds || []); + if (orderIds.length === 0) { + return new Map(); + } + + const orderItemsModel = await this.getOrderItemsModelByTableType('current', warehouseId); + if (!orderItemsModel || typeof orderItemsModel.findAll !== 'function') { + throw new Error('订单明细模型不可用'); + } + + const itemRows = await orderItemsModel.findAll({ + where: { + order_id: { [Op.in]: orderIds }, + }, + attributes: [ 'order_id', 'plan_qty', 'stock_id', 'item_code', 'item_name', 'item_snapshot' ], + raw: true, + }); + + const rowMap = new Map(); + for (const row of (Array.isArray(itemRows) ? itemRows : [])) { + const orderId = Number(row && row.order_id || 0); + if (!Number.isInteger(orderId) || orderId <= 0) { + continue; + } + + if (!rowMap.has(orderId)) { + rowMap.set(orderId, []); + } + rowMap.get(orderId).push(row); + } + + const skuMap = new Map(); + for (const orderId of orderIds) { + const detailRows = rowMap.get(orderId) || []; + const detailList = this.mergeOrderItemDetails(detailRows); + const skuSet = new Set(); + + detailList.forEach(item => { + const itemCode = String(item && item.item_code || '').trim(); + const stockId = Number(item && item.stock_id || 0); + if (itemCode) { + skuSet.add(itemCode); + return; + } + if (Number.isInteger(stockId) && stockId > 0) { + skuSet.add(`stock_${stockId}`); + } + }); + + skuMap.set(orderId, skuSet); + } + + return skuMap; + } + + /** + * 先拣后分模式按 SKU 上限筛选订单。 + * + * 当 SKU 种类超限时,循环剔除“出现频率最低”的 SKU, + * 每次剔除该 SKU 对应的全部订单,直到 SKU 种类满足上限。 + * + * @param {Object} params 筛选参数。 + * @param {Array} params.orderIds 候选订单ID(升序)。 + * @param {Map>} params.orderSkuMap 订单 SKU 映射。 + * @param {number|string} params.skuLimit SKU 上限。 + * @return {{ selectedOrderIds: Array, removedOrderIds: Array }} 筛选结果。 + */ + selectWaveStrategyFetchOrdersBySkuLimit(params = {}) { + const orderIds = this.normalizeIdsInput(params.orderIds || []); + const orderSkuMap = params.orderSkuMap instanceof Map ? params.orderSkuMap : new Map(); + const skuLimitRaw = Number(params.skuLimit || 0); + const skuLimit = Number.isInteger(skuLimitRaw) && skuLimitRaw > 0 ? skuLimitRaw : 0; + + if (orderIds.length === 0) { + return { + selectedOrderIds: [], + removedOrderIds: [], + }; + } + + if (skuLimit <= 0) { + return { + selectedOrderIds: [], + removedOrderIds: [ ...orderIds ], + }; + } + + const activeOrderSet = new Set(orderIds); + const removedOrderSet = new Set(); + + const buildSkuOrderMap = () => { + const skuOrderMap = new Map(); + for (const orderId of activeOrderSet) { + const skuSet = orderSkuMap.get(orderId) instanceof Set ? orderSkuMap.get(orderId) : new Set(); + for (const sku of skuSet) { + const skuKey = String(sku || '').trim(); + if (!skuKey) { + continue; + } + if (!skuOrderMap.has(skuKey)) { + skuOrderMap.set(skuKey, new Set()); + } + skuOrderMap.get(skuKey).add(orderId); + } + } + return skuOrderMap; + }; + + for (;;) { + const skuOrderMap = buildSkuOrderMap(); + if (skuOrderMap.size <= skuLimit) { + break; + } + + let targetSku = ''; + let minFrequency = Number.MAX_SAFE_INTEGER; + for (const [ sku, orderSet ] of skuOrderMap.entries()) { + const frequency = orderSet.size; + if (frequency < minFrequency) { + minFrequency = frequency; + targetSku = sku; + continue; + } + if (frequency === minFrequency && targetSku && String(sku).localeCompare(String(targetSku)) < 0) { + targetSku = sku; + } + } + + if (!targetSku) { + break; + } + + const targetOrderSet = skuOrderMap.get(targetSku) || new Set(); + for (const orderId of targetOrderSet) { + if (activeOrderSet.has(orderId)) { + activeOrderSet.delete(orderId); + removedOrderSet.add(orderId); + } + } + + if (activeOrderSet.size === 0) { + break; + } + } + + return { + selectedOrderIds: [ ...activeOrderSet ].sort((a, b) => a - b), + removedOrderIds: [ ...removedOrderSet ].sort((a, b) => a - b), + }; + } + + /** + * 在事务内按指定订单创建波次并更新订单波次字段。 + * + * @param {Object} params 创建参数。 + * @param {number|string} params.warehouseId 仓库ID。 + * @param {Array} params.orderIds 订单ID数组。 + * @param {number|string} params.waveType 波次类型(1-团购,2-散单)。 + * @param {string} params.wavePrefix 波次前缀。 + * @param {number|string} [params.source=0] 波次来源。 + * @param {Object} params.transaction 事务对象。 + * @return {Promise<{ waveId: number, waveNo: string, selectedOrderIds: Array }>} 创建结果。 + */ + async createWaveBatchByOrderIdsInTransaction(params = {}) { + const warehouseId = this.normalizeRequiredPositiveInteger(params.warehouseId, 'warehouse_id'); + const waveType = Number(params.waveType || 0) === 2 ? 2 : 1; + const wavePrefix = String(params.wavePrefix || '').trim() || (waveType === 2 ? 'A' : 'B'); + const sourceInput = Number(params.source); + const source = [ 0, 1, 2 ].includes(sourceInput) ? sourceInput : 0; + const transaction = params.transaction; + const orderIds = this.normalizeIdsInput(params.orderIds || []); + if (orderIds.length === 0) { + throw new Error('创建波次失败:订单集合不能为空'); + } + + const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + const lockRows = await orderModel.findAll({ + attributes: [ 'id', 'wave_id', 'items_hash', 'items' ], + where: { + id: { [Op.in]: orderIds }, + warehouse_id: warehouseId, + wave_id: 0, + step: { [Op.ne]: 0 }, + status: { [Op.ne]: 'cancel' }, + outbound_status: { [Op.ne]: 'padding' }, + }, + raw: true, + transaction, + lock: transaction.LOCK.UPDATE, + }); + + const fetchableOrderIds = [ ...new Set((Array.isArray(lockRows) ? lockRows : []) + .map(row => Number(row && row.id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ].sort((a, b) => a - b); + + if (fetchableOrderIds.length === 0) { + throw new Error('创建波次失败:候选订单已被占用或状态变化'); + } + + const firstRow = Array.isArray(lockRows) ? lockRows[0] : null; + const itemPart = this.getOrderItemPart(firstRow || {}); + const itemSnapshotKey = `${itemPart.item_part_type}:${itemPart.item_part}`; + const itemDetailMachine = this.buildMachineStructureToken({ + item_part_type: itemPart.item_part_type, + item_part: itemPart.item_part, + distinguish_express: false, + logistics_name: '', + item_snapshot_key: itemSnapshotKey, + }); + + const { waveId, waveNo } = await this.createWaveBatchReady({ + warehouseId, + totalOrders: fetchableOrderIds.length, + itemDetailMachine, + itemPartType: itemPart.item_part_type, + itemPart: itemPart.item_part, + distinguishExpress: false, + logisticsName: '', + itemSnapshotKey, + wavePrefix, + waveType, + source, + transaction, + }); + + const orderFlagExpression = this.app.Sequelize.literal(`CASE + WHEN order_flag IS NULL OR order_flag = '' THEN '${WAVE_MANUAL_FETCH_FLAG}' + WHEN order_flag LIKE '%${WAVE_MANUAL_FETCH_FLAG}%' THEN order_flag + ELSE CONCAT(order_flag, ',${WAVE_MANUAL_FETCH_FLAG}') + END`); + + await orderModel.update({ + wave_id: waveId, + wave_no: waveNo, + order_flag: orderFlagExpression, + }, { + where: { + id: { [Op.in]: fetchableOrderIds }, + warehouse_id: warehouseId, + wave_id: 0, + }, + transaction, + }); + + const grabbedRows = await orderModel.findAll({ + where: { + id: { [Op.in]: fetchableOrderIds }, + warehouse_id: warehouseId, + wave_id: waveId, + }, + attributes: [ 'id' ], + raw: true, + transaction, + }); + const grabbedOrderIds = [ ...new Set((Array.isArray(grabbedRows) ? grabbedRows : []) + .map(row => Number(row && row.id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ].sort((a, b) => a - b); + + if (grabbedOrderIds.length <= 0) { + await this.ctx.model.query(` + DELETE FROM wms_wave_batch + WHERE wave_id = :waveId + `, { + replacements: { + waveId, + }, + transaction, + }); + throw new Error('创建波次失败:未抓取到有效订单'); + } + + if (grabbedOrderIds.length !== fetchableOrderIds.length) { + await this.ctx.model.query(` + UPDATE wms_wave_batch + SET total_orders = :totalOrders, + update_time = NOW() + WHERE wave_id = :waveId + `, { + replacements: { + waveId, + totalOrders: grabbedOrderIds.length, + }, + transaction, + }); + } + + await this.rebuildOrderWaveIndex({ + warehouseId, + waveId, + orderIds: grabbedOrderIds, + orderModel, + transaction, + }); + + return { + waveId, + waveNo, + selectedOrderIds: grabbedOrderIds, + }; + } + + /** + * 自动补齐按策略抓取的 selected_wave_ids / selected_order_ids。 + * + * 仅用于 PDA 按策略抓取场景,内部按 strategy_type + pick_mode 执行分流。 + * + * @param {Object} params 自动分流参数。 + * @param {Object} params.plan 抓取计划。 + * @param {Object} params.strategyRow 策略行。 + * @param {number|string} [params.waveBatchSource=0] 波次来源。 + * @param {Object} params.transaction 事务对象。 + * @return {Promise} 自动补齐结果。 + */ + async autoPopulateWaveStrategyFetchSelections(params = {}) { + const plan = this.isPlainObject(params.plan) ? params.plan : {}; + const strategyRow = this.isPlainObject(params.strategyRow) ? params.strategyRow : {}; + const transaction = params.transaction; + const waveBatchSourceInput = Number(params.waveBatchSource); + const waveBatchSource = [ 0, 1, 2 ].includes(waveBatchSourceInput) ? waveBatchSourceInput : 0; + + const warehouseId = this.normalizeRequiredPositiveInteger(plan.warehouse_id, 'warehouse_id'); + const strategyId = this.normalizeRequiredPositiveInteger(plan.strategy_id, 'strategy_id'); + const pickMode = this.normalizeRequiredPositiveInteger(plan.pick_mode, 'pick_mode'); + const strategyType = Number(strategyRow.strategy_type || plan.strategy_type || 0); + const operatorInfo = this.isPlainObject(plan.operator) ? plan.operator : {}; + const operatorId = Number((operatorInfo.operator_id ?? operatorInfo.id) || 0); + + await this.ensureNoActiveWavePickTaskForOperator({ + warehouseId, + operatorId, + transaction, + }); + + const candidateRows = await this.getWaveStrategyFetchCandidateOrders({ + warehouseId, + strategyId, + minSameStructure: strategyRow.min_same_structure, + maxSameStructure: strategyRow.max_same_structure, + requireSameExpress: Number(strategyRow.require_same_express || 0), + }); + const candidateCount = candidateRows.length; + if (candidateCount <= 0) { + throw new Error('未找到符合策略且未分配波次的候选订单'); + } + + const groupedRows = this.groupWaveStrategyFetchCandidateOrdersByStructure(candidateRows); + if (groupedRows.length <= 0) { + throw new Error('候选订单缺少有效商品结构,无法创建波次'); + } + + const result = { + selected_wave_ids: [], + selected_order_ids: [], + removed_order_ids: [], + candidate_count: candidateCount, + grouped_count: groupedRows.length, + wave_prefix: '', + wave_prefix_source: '', + }; + + const wavePrefixResolution = await this.resolveWaveStrategyFetchWavePrefix({ + warehouseId, + strategyType, + strategyRow, + }); + result.wave_prefix = wavePrefixResolution.wavePrefix; + result.wave_prefix_source = wavePrefixResolution.source; + + if (strategyType === 2) { + const groupLimitRaw = Number(strategyRow.group_batch_max_orders || plan.box_limit || 0); + const groupLimit = Number.isInteger(groupLimitRaw) && groupLimitRaw > 0 ? groupLimitRaw : 1; + const selectedGroups = groupedRows + .slice(0, groupLimit); + if (selectedGroups.length === 0) { + throw new Error('团购策略未找到可创建波次的同结构分组'); + } + + for (const group of selectedGroups) { + const created = await this.createWaveBatchByOrderIdsInTransaction({ + warehouseId, + orderIds: group.order_ids, + waveType: 1, + wavePrefix: wavePrefixResolution.wavePrefix, + source: waveBatchSource, + transaction, + }); + result.selected_wave_ids.push(created.waveId); + result.selected_order_ids.push(...created.selectedOrderIds); + } + + if (result.selected_wave_ids.length <= 0) { + throw new Error('团购策略创建波次失败:无有效波次生成'); + } + } else if (strategyType === 1) { + const effectiveCandidateRows = Number(strategyRow.require_same_express || 0) === 1 + ? this.filterCandidateOrdersByRequireSameExpress(candidateRows) + : candidateRows; + const effectiveGroupedRows = effectiveCandidateRows === candidateRows + ? groupedRows + : this.groupWaveStrategyFetchCandidateOrdersByStructure(effectiveCandidateRows); + + const mergedOrderIds = [ ...new Set(effectiveGroupedRows + .flatMap(group => group.order_ids) + .map(id => Number(id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ] + .sort((a, b) => a - b); + if (mergedOrderIds.length === 0) { + throw new Error('散单策略无可用候选订单'); + } + + const orderLimitRaw = Number(plan.order_limit || strategyRow.batch_max_orders || 0); + const orderLimit = Number.isInteger(orderLimitRaw) && orderLimitRaw > 0 ? orderLimitRaw : 0; + let selectedOrderIds = []; + + if (pickMode === 3) { + const skuMap = await this.buildWaveStrategyFetchOrderSkuMap({ + warehouseId, + orderIds: mergedOrderIds, + }); + const skuLimitRaw = Number(plan.sku_limit || strategyRow.batch_max_skus || 0); + const skuLimit = Number.isInteger(skuLimitRaw) && skuLimitRaw > 0 ? skuLimitRaw : 0; + const skuResult = this.selectWaveStrategyFetchOrdersBySkuLimit({ + orderIds: mergedOrderIds, + orderSkuMap: skuMap, + skuLimit, + }); + result.removed_order_ids = skuResult.removedOrderIds; + selectedOrderIds = skuResult.selectedOrderIds; + } else if (pickMode === 4 || pickMode === 2) { + selectedOrderIds = mergedOrderIds; + } else { + throw new Error(`散单策略不支持的 pick_mode: ${pickMode}`); + } + + if (selectedOrderIds.length <= 0) { + throw new Error('散单策略筛选后无可用订单(候选可能已被剔除)'); + } + + const limitedOrderIds = orderLimit > 0 + ? selectedOrderIds.slice(0, orderLimit) + : selectedOrderIds; + if (limitedOrderIds.length <= 0) { + throw new Error('散单策略筛选后无可用订单(batch_max_orders 限制导致为空)'); + } + + const createdWave = await this.createWaveBatchByOrderIdsInTransaction({ + warehouseId, + orderIds: limitedOrderIds, + waveType: 2, + wavePrefix: wavePrefixResolution.wavePrefix, + source: waveBatchSource, + transaction, + }); + + result.selected_wave_ids.push(createdWave.waveId); + result.selected_order_ids.push(...createdWave.selectedOrderIds); + if (result.selected_wave_ids.length <= 0) { + throw new Error('散单策略创建波次失败:无有效波次生成'); + } + } else { + throw new Error(`不支持的策略类型: ${strategyType}`); + } + + result.selected_wave_ids = [ ...new Set(result.selected_wave_ids) ].sort((a, b) => a - b); + result.selected_order_ids = [ ...new Set(result.selected_order_ids) ].sort((a, b) => a - b); + + this.ctx.logger.info('[wave.autoPopulateWaveStrategyFetchSelections] 自动分流完成', { + strategy_id: strategyId, + warehouse_id: warehouseId, + pick_mode: pickMode, + strategy_type: strategyType, + wave_prefix: result.wave_prefix, + wave_prefix_source: result.wave_prefix_source, + candidate_count: result.candidate_count, + removed_count: result.removed_order_ids.length, + selected_count: result.selected_order_ids.length, + selected_wave_count: result.selected_wave_ids.length, + }); + + return result; + } + + /** + * 按策略直接抓取候选订单并创建波次(不创建拣货任务)。 + * + * 在一个事务内完成候选查询、分组与建波: + * - 团购策略(strategy_type=2):每个结构分组创建一个波次; + * - 散单策略(strategy_type=1):合并全部候选订单后创建一个散单波次。 + * + * @param {Object} params 执行参数。 + * @param {Object} params.plan 预处理计划。 + * @param {Object} [params.strategyRow={}] 策略行(可选,默认取 plan.strategy_row)。 + * @param {number|string} [params.waveBatchSource=0] 波次来源:0-普通波次 1-管理后台策略抓取 2-PDA策略抓取。 + * @return {Promise} 建波结果汇总。 + */ + async executeWaveStrategyDirectFetch(params = {}) { + const plan = this.isPlainObject(params && params.plan) ? params.plan : {}; + const strategyRow = this.isPlainObject(params && params.strategyRow) + ? params.strategyRow + : (this.isPlainObject(plan.strategy_row) ? plan.strategy_row : {}); + const waveBatchSourceInput = Number(params && params.waveBatchSource); + const waveBatchSource = [ 0, 1, 2 ].includes(waveBatchSourceInput) ? waveBatchSourceInput : 0; + + const warehouseId = this.normalizeRequiredPositiveInteger(plan.warehouse_id, 'warehouse_id'); + const strategyId = this.normalizeRequiredPositiveInteger(plan.strategy_id, 'strategy_id'); + const strategyType = Number(strategyRow.strategy_type || plan.strategy_type || 0); + const transaction = await this.ctx.model.transaction(); + + try { + const candidateRows = await this.getWaveStrategyFetchCandidateOrders({ + warehouseId, + strategyId, + minSameStructure: strategyRow.min_same_structure, + maxSameStructure: strategyRow.max_same_structure, + requireSameExpress: Number(strategyRow.require_same_express || 0), + }); + const candidateCount = candidateRows.length; + if (candidateCount <= 0) { + throw new Error('未找到符合策略且未分配波次的候选订单'); + } + + const groupedRows = this.groupWaveStrategyFetchCandidateOrdersByStructure(candidateRows); + if (groupedRows.length <= 0) { + throw new Error('候选订单缺少有效商品结构,无法创建波次'); + } + + const wavePrefixResolution = await this.resolveWaveStrategyFetchWavePrefix({ + warehouseId, + strategyType, + strategyRow, + }); + + const createdWaveIds = []; + const createdWaveNos = []; + const createdOrderIds = []; + + if (strategyType === 2) { + for (const group of groupedRows) { + const created = await this.createWaveBatchByOrderIdsInTransaction({ + warehouseId, + orderIds: group.order_ids, + waveType: 1, + wavePrefix: wavePrefixResolution.wavePrefix, + source: waveBatchSource, + transaction, + }); + createdWaveIds.push(created.waveId); + createdWaveNos.push(created.waveNo); + createdOrderIds.push(...created.selectedOrderIds); + } + } else if (strategyType === 1) { + const effectiveCandidateRows = Number(strategyRow.require_same_express || 0) === 1 + ? this.filterCandidateOrdersByRequireSameExpress(candidateRows) + : candidateRows; + const effectiveGroupedRows = effectiveCandidateRows === candidateRows + ? groupedRows + : this.groupWaveStrategyFetchCandidateOrdersByStructure(effectiveCandidateRows); + + const mergedOrderIds = [ ...new Set(effectiveGroupedRows + .flatMap(group => group.order_ids) + .map(id => Number(id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ] + .sort((a, b) => a - b); + if (mergedOrderIds.length <= 0) { + throw new Error('散单策略无可用候选订单'); + } + + const createdWave = await this.createWaveBatchByOrderIdsInTransaction({ + warehouseId, + orderIds: mergedOrderIds, + waveType: 2, + wavePrefix: wavePrefixResolution.wavePrefix, + source: waveBatchSource, + transaction, + }); + createdWaveIds.push(createdWave.waveId); + createdWaveNos.push(createdWave.waveNo); + createdOrderIds.push(...createdWave.selectedOrderIds); + } else { + throw new Error(`不支持的策略类型: ${strategyType}`); + } + + const normalizedWaveIds = [ ...new Set(createdWaveIds) ].sort((a, b) => a - b); + const normalizedWaveNos = [ ...new Set(createdWaveNos.map(item => String(item || '').trim()).filter(Boolean)) ]; + const normalizedOrderIds = [ ...new Set(createdOrderIds) ].sort((a, b) => a - b); + + if (normalizedWaveIds.length <= 0 || normalizedOrderIds.length <= 0) { + throw new Error('按策略抓取建波失败:未生成有效波次或订单结果'); + } + + const result = { + wave_ids: normalizedWaveIds, + wave_nos: normalizedWaveNos, + order_ids: normalizedOrderIds, + created_wave_count: normalizedWaveIds.length, + created_order_count: normalizedOrderIds.length, + wave_prefix: wavePrefixResolution.wavePrefix, + wave_prefix_source: wavePrefixResolution.source, + candidate_count: candidateCount, + grouped_count: groupedRows.length, + strategy_type: strategyType, + }; + + await transaction.commit(); + + this.ctx.logger.info('[wave.executeWaveStrategyDirectFetch] 按策略直接建波完成', { + strategy_id: strategyId, + warehouse_id: warehouseId, + strategy_type: strategyType, + wave_prefix: result.wave_prefix, + wave_prefix_source: result.wave_prefix_source, + candidate_count: result.candidate_count, + grouped_count: result.grouped_count, + created_wave_count: result.created_wave_count, + created_order_count: result.created_order_count, + }); + + return result; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + /** + * 执行按策略抓取任务创建主流程。 + * + * 该方法在一个事务内完成任务主表、明细表、断点与日志的初始化写入。 + * + * @param {Object} params 创建参数。 + * @param {Object} params.plan 预处理后的抓取计划。 + * @param {Object} [params.data={}] 原始请求数据。 + * @param {number|string} [params.waveBatchSource=0] 波次来源:0-普通波次 1-管理后台策略任务 2-PDA策略任务。 + * @return {Promise} 创建结果。 + */ + async createWavePickTaskFromPlan(params = {}) { + const plan = this.isPlainObject(params && params.plan) ? params.plan : {}; + const requestData = this.isPlainObject(params && params.data) ? params.data : {}; + const autoPopulateSelections = Boolean(params && params.autoPopulateSelections); + const warehouseId = this.normalizeRequiredPositiveInteger(plan.warehouse_id, 'warehouse_id'); + const pickMode = this.normalizeRequiredPositiveInteger(plan.pick_mode, 'pick_mode'); + const waveBatchSourceInput = Number( + params && params.waveBatchSource !== undefined ? params.waveBatchSource : plan.wave_batch_source + ); + const waveBatchSource = [ 0, 1, 2 ].includes(waveBatchSourceInput) ? waveBatchSourceInput : 0; + let effectivePlan = { + ...plan, + }; + let effectiveRequestData = { + ...requestData, + }; + const hasExplicitWaveSelectionInput = [ + 'selected_wave_ids', + 'selectedWaveIds', + 'wave_ids', + 'waveIds', + 'wave_id', + 'waveId', + ].some(fieldName => Object.prototype.hasOwnProperty.call(requestData, fieldName)); + const hasExplicitOrderSelectionInput = [ + 'selected_order_ids', + 'selectedOrderIds', + 'order_ids', + 'orderIds', + ].some(fieldName => Object.prototype.hasOwnProperty.call(requestData, fieldName)); + const hasManualSelectionInput = this.normalizeIdsInput(plan.selected_wave_ids || []).length > 0 + || hasExplicitWaveSelectionInput + || hasExplicitOrderSelectionInput; + + const normalizedCartId = this.normalizePositiveInteger( + effectiveRequestData.cart_id ?? effectiveRequestData.cartId, + 'cart_id', + 0 + ); + const transaction = await this.ctx.model.transaction(); + + try { + if (autoPopulateSelections && !hasManualSelectionInput) { + const autoFilled = await this.autoPopulateWaveStrategyFetchSelections({ + plan: effectivePlan, + strategyRow: effectivePlan.strategy_row, + waveBatchSource, + transaction, + }); + + effectivePlan = { + ...effectivePlan, + selected_wave_ids: autoFilled.selected_wave_ids, + box_assignments: this.buildWaveStrategyFetchBoxAssignments({ + pickMode, + selectedWaveIds: autoFilled.selected_wave_ids, + boxLimit: Number(effectivePlan.box_limit || 0), + }), + }; + effectiveRequestData = { + ...effectiveRequestData, + selected_wave_ids: autoFilled.selected_wave_ids, + selected_order_ids: autoFilled.selected_order_ids, + }; + } + + const selectedWaveIds = this.normalizeIdsInput(effectivePlan.selected_wave_ids || []); + const selectedOrderIds = this.normalizeIdsInput( + effectiveRequestData.selected_order_ids !== undefined + ? effectiveRequestData.selected_order_ids + : effectiveRequestData.selectedOrderIds !== undefined + ? effectiveRequestData.selectedOrderIds + : effectiveRequestData.order_ids !== undefined + ? effectiveRequestData.order_ids + : effectiveRequestData.orderIds + ); + + const validationErrors = Array.isArray(effectivePlan.validation_errors) + ? [ ...effectivePlan.validation_errors ] + : []; + if ([ 1, 5 ].includes(pickMode) && selectedWaveIds.length === 0) { + validationErrors.push('当前模式依赖波次,selected_wave_ids 不能为空'); + } + if ([ 2, 3, 4 ].includes(pickMode) && selectedOrderIds.length === 0) { + validationErrors.push('当前模式至少需要一个订单,selected_order_ids 不能为空'); + } + if (validationErrors.length > 0) { + throw new Error(`按策略抓取任务创建校验失败: ${validationErrors.join(';')}`); + } + + if (normalizedCartId > 0) { + await this.ensurePickCartAvailable({ + cartId: normalizedCartId, + warehouseId, + transaction, + }); + } + + // 散单模式:从波次表读取 wave_no 并写入任务 batch_no + let resolvedBatchNo = null; + if ([ 2, 3, 4 ].includes(pickMode) && selectedWaveIds.length > 0) { + const batchRows = await this.ctx.model.query( + 'SELECT wave_no FROM wms_wave_batch WHERE wave_id = :waveId AND warehouse_id = :warehouseId LIMIT 1', + { + replacements: { waveId: selectedWaveIds[0], warehouseId }, + type: this.ctx.model.QueryTypes.SELECT, + transaction, + } + ); + resolvedBatchNo = (batchRows.length > 0 && batchRows[0].wave_no) ? String(batchRows[0].wave_no).trim() : null; + } + + const taskPayload = this.buildTaskCreatePayload({ + plan: effectivePlan, + data: effectiveRequestData, + selectedWaveIds, + selectedOrderIds, + cartId: normalizedCartId, + }); + if (resolvedBatchNo !== null) { + taskPayload.batch_no = resolvedBatchNo; + } + + if (selectedWaveIds.length > 0 && [ 1, 2 ].includes(waveBatchSource)) { + await this.ctx.model.query(` + UPDATE wms_wave_batch + SET source = :source, + update_time = NOW() + WHERE warehouse_id = :warehouseId + AND wave_id IN (:waveIds) + `, { + replacements: { + source: waveBatchSource, + warehouseId, + waveIds: selectedWaveIds, + }, + transaction, + }); + } + + const taskCreateResult = await this.createWavePickTaskWithRetry(taskPayload, transaction); + const taskId = Number(taskCreateResult.task_id || 0); + const taskNo = String(taskCreateResult.task_no || '').trim(); + + const taskWaveRows = this.buildTaskWaveRows({ + taskId, + plan: effectivePlan, + selectedWaveIds, + }); + const taskOrderRows = this.buildTaskOrderRows({ + taskId, + plan: effectivePlan, + selectedWaveIds, + selectedOrderIds, + cartId: normalizedCartId, + }); + const taskSkuRows = await this.buildTaskSkuRows({ + plan: effectivePlan, + selectedOrderIds, + }); + const taskBoxRows = this.buildTaskBoxRows({ + taskId, + taskNo, + plan: effectivePlan, + taskWaveRows, + taskOrderRows, + taskSkuRows, + }); + + if (taskWaveRows.length > 0) { + await this.bulkInsertRows('wms_wave_pick_task_wave', taskWaveRows, transaction); + } + if (taskOrderRows.length > 0) { + await this.bulkInsertRows('wms_wave_pick_task_order', taskOrderRows, transaction); + } + if (taskBoxRows.length > 0) { + await this.bulkInsertRows('wms_wave_pick_task_box', taskBoxRows, transaction); + } + + if (normalizedCartId > 0) { + await this.bindPickCartForTask({ + taskId, + cartId: normalizedCartId, + warehouseId, + operatorId: taskPayload.pick_user_id, + transaction, + }); + } + + await this.initTaskCheckpointAndLogs({ + taskId, + taskNo, + plan: effectivePlan, + data: effectiveRequestData, + selectedOrderIds, + cartId: normalizedCartId, + operatorId: taskPayload.pick_user_id, + operatorName: taskPayload.pick_user_name, + transaction, + }); + + await transaction.commit(); + + return { + task_id: taskId, + task_no: taskNo, + state: 'created', + plan_summary: { + pick_mode: pickMode, + wave_count: taskWaveRows.length, + order_count: taskOrderRows.length, + box_count: taskBoxRows.length, + cart_id: normalizedCartId > 0 ? normalizedCartId : null, + }, + }; + } catch (error) { + const errorDetail = { + name: String(error && error.name || ''), + message: String(error && error.message || ''), + stack: String(error && error.stack || '').split('\n').slice(0, 6).join('\n'), + sql: String(error && error.sql || '').slice(0, 500), + errorType: Object.prototype.toString.call(error), + errors: Array.isArray(error && error.errors) + ? error.errors.map(e => ({ message: e.message, type: e.type, path: e.path, value: e.value })) + : [], + }; + this.ctx.logger.error('[wave.createWavePickTaskFromPlan] 任务创建异常详情', errorDetail); + await transaction.rollback(); + throw error; + } + } + + /** + * 构建任务主表写入载荷。 + * + * @param {Object} options 构建参数。 + * @param {Object} options.plan 预处理计划。 + * @param {Object} options.data 原始请求数据。 + * @param {Array} options.selectedWaveIds 已选波次ID。 + * @param {Array} options.selectedOrderIds 已选订单ID。 + * @param {number} options.cartId 拣货车ID。 + * @return {Object} 主表写入载荷。 + */ + buildTaskCreatePayload(options = {}) { + const plan = this.isPlainObject(options && options.plan) ? options.plan : {}; + const data = this.isPlainObject(options && options.data) ? options.data : {}; + const selectedWaveIds = Array.isArray(options && options.selectedWaveIds) + ? options.selectedWaveIds + : []; + const selectedOrderIds = Array.isArray(options && options.selectedOrderIds) + ? options.selectedOrderIds + : []; + const pickMode = this.normalizeRequiredPositiveInteger(plan.pick_mode, 'pick_mode'); + const warehouseId = this.normalizeRequiredPositiveInteger(plan.warehouse_id, 'warehouse_id'); + const source = String(plan.source || 'unknown').trim(); + const sourceCode = source === 'admin' ? 2 : 1; + + const operator = this.isPlainObject(plan.operator) ? plan.operator : {}; + const rawOperatorId = operator.operator_id ?? operator.id; + const normalizedOperatorId = Number(rawOperatorId); + const pickUserId = Number.isInteger(normalizedOperatorId) && normalizedOperatorId >= 0 + ? normalizedOperatorId + : 0; + const pickUserName = String(operator.operator_name || operator.name || this.getOrderLogOperator().name || 'system').trim() || 'system'; + const taskNo = String(data.task_no || '').trim() || this.generateWavePickTaskNo(warehouseId, sourceCode); + + return { + task_no: taskNo, + warehouse_id: warehouseId, + wave_id: selectedWaveIds.length > 0 ? selectedWaveIds[0] : null, + pick_mode: pickMode, + status: 0, + source: sourceCode, + wave_count: selectedWaveIds.length, + order_count: selectedOrderIds.length, + box_count: 0, + batch_no: null, + pick_user_id: pickUserId, + pick_user_name: pickUserName, + current_cart_id: Number(options && options.cartId || 0) > 0 ? Number(options.cartId) : null, + current_cart_code_snapshot: null, + review_status: 0, + review_version: 0, + device_id: String(data.device_id || data.deviceId || '').trim() || `wave_${source}_${warehouseId}`, + ext_json: JSON.stringify({ + strategy_id: plan.strategy_id, + wave_limit: Number(plan.wave_limit || 0), + order_limit: Number(plan.order_limit || 0), + sku_limit: Number(plan.sku_limit || 0), + box_limit: Number(plan.box_limit || 0), + dynamic_append: Boolean(plan.dynamic_append), + }), + }; + } + + /** + * 构建任务与波次关联写入行。 + * + * @param {Object} options 构建参数。 + * @param {number} options.taskId 任务ID。 + * @param {Object} options.plan 预处理计划。 + * @param {Array} options.selectedWaveIds 已选波次ID。 + * @return {Array} 任务波次行。 + */ + buildTaskWaveRows(options = {}) { + const taskId = Number(options && options.taskId || 0); + const plan = this.isPlainObject(options && options.plan) ? options.plan : {}; + const warehouseId = this.normalizeRequiredPositiveInteger(plan.warehouse_id, 'warehouse_id'); + const selectedWaveIds = Array.isArray(options && options.selectedWaveIds) + ? options.selectedWaveIds + : []; + + return selectedWaveIds.map((waveId, index) => ({ + task_id: taskId, + wave_id: waveId, + wave_no: null, + box_no: index + 1, + status: 0, + bind_time: null, + pick_time: null, + warehouse_id: warehouseId, + })); + } + + /** + * 构建任务订单明细写入行。 + * + * @param {Object} options 构建参数。 + * @param {number} options.taskId 任务ID。 + * @param {Object} options.plan 预处理计划。 + * @param {Array} options.selectedWaveIds 已选波次ID。 + * @param {Array} options.selectedOrderIds 已选订单ID。 + * @param {number} options.cartId 绑定车ID。 + * @return {Array} 任务订单行。 + */ + buildTaskOrderRows(options = {}) { + const taskId = Number(options && options.taskId || 0); + const plan = this.isPlainObject(options && options.plan) ? options.plan : {}; + const pickMode = Number(plan.pick_mode || 0); + const warehouseId = this.normalizeRequiredPositiveInteger(plan.warehouse_id, 'warehouse_id'); + const selectedWaveIds = Array.isArray(options && options.selectedWaveIds) + ? options.selectedWaveIds + : []; + const selectedOrderIds = Array.isArray(options && options.selectedOrderIds) + ? options.selectedOrderIds + : []; + const cartId = Number(options && options.cartId || 0); + + if (![ 2, 3, 4 ].includes(pickMode)) { + return []; + } + + const defaultWaveId = selectedWaveIds.length > 0 ? selectedWaveIds[0] : null; + return selectedOrderIds.map((orderId, index) => ({ + task_id: taskId, + wave_id: defaultWaveId, + order_id: orderId, + order_no: null, + box_no: index + 1, + cart_id: cartId > 0 ? cartId : null, + cart_code_snapshot: null, + warehouse_id: warehouseId, + pick_status: 0, + review_status: 0, + review_user_id: null, + review_result: null, + review_remark: null, + exception_reason: null, + picked_time: null, + review_time: null, + })); + } + + /** + * 构建任务 SKU 明细写入行(仅先拣后分模式使用)。 + * + * @param {Object} options 构建参数。 + * @param {Object} options.plan 预处理计划。 + * @param {Array} options.selectedOrderIds 已选订单ID。 + * @return {Promise>} 任务 SKU 行。 + */ + async buildTaskSkuRows(options = {}) { + const plan = this.isPlainObject(options && options.plan) ? options.plan : {}; + const pickMode = Number(plan.pick_mode || 0); + const warehouseId = this.normalizeRequiredPositiveInteger(plan.warehouse_id, 'warehouse_id'); + const selectedOrderIds = Array.isArray(options && options.selectedOrderIds) + ? this.normalizeIdsInput(options.selectedOrderIds) + : []; + + if (pickMode !== 3 || selectedOrderIds.length <= 0) { + return []; + } + + const orderItemsModel = await this.getOrderItemsModelByTableType('current', warehouseId); + if (!orderItemsModel || typeof orderItemsModel.findAll !== 'function') { + throw new Error('订单明细模型不可用'); + } + + const itemRows = await orderItemsModel.findAll({ + where: { + order_id: { [Op.in]: selectedOrderIds }, + }, + attributes: [ 'order_id', 'plan_qty', 'stock_id', 'item_code', 'item_name', 'item_snapshot' ], + raw: true, + }); + + const skuMap = new Map(); + for (const row of (Array.isArray(itemRows) ? itemRows : [])) { + const normalized = this.normalizeOrderItemRow(row); + if (normalized.quantity <= 0) { + continue; + } + + const skuId = Number(normalized.stock_id || 0); + const itemCode = String(normalized.item_code || '').trim(); + const itemName = String(normalized.item_name || '').trim(); + if (!(Number.isInteger(skuId) && skuId > 0) && !itemCode) { + continue; + } + + const key = Number.isInteger(skuId) && skuId > 0 ? `stock_${skuId}` : `code_${itemCode}`; + if (!skuMap.has(key)) { + skuMap.set(key, { + sku_id: Number.isInteger(skuId) && skuId > 0 ? skuId : null, + ref_id: Number.isInteger(skuId) && skuId > 0 ? skuId : null, + ref_label: itemName || itemCode || null, + required_qty: 0, + }); + } + + const aggregated = skuMap.get(key); + aggregated.required_qty += normalized.quantity; + if (!aggregated.ref_label && (itemName || itemCode)) { + aggregated.ref_label = itemName || itemCode; + } + } + + return Array.from(skuMap.values()) + .sort((a, b) => { + const leftSkuId = Number(a.sku_id || 0); + const rightSkuId = Number(b.sku_id || 0); + if (leftSkuId !== rightSkuId) { + return leftSkuId - rightSkuId; + } + return String(a.ref_label || '').localeCompare(String(b.ref_label || '')); + }) + .map((row, index) => ({ + box_no: index + 1, + sku_id: row.sku_id, + ref_id: row.ref_id, + ref_label: row.ref_label, + required_qty: Number(row.required_qty || 0), + })); + } + + /** + * 构建任务框明细写入行。 + * + * @param {Object} options 构建参数。 + * @param {number} options.taskId 任务ID。 + * @param {string} options.taskNo 任务编号。 + * @param {Object} options.plan 预处理计划。 + * @param {Array} options.taskWaveRows 任务波次行。 + * @param {Array} options.taskOrderRows 任务订单行。 + * @param {Array} options.taskSkuRows 任务 SKU 行。 + * @return {Array} 任务框行。 + */ + buildTaskBoxRows(options = {}) { + const taskId = Number(options && options.taskId || 0); + const taskNo = String(options && options.taskNo || '').trim(); + const plan = this.isPlainObject(options && options.plan) ? options.plan : {}; + const pickMode = Number(plan.pick_mode || 0); + const warehouseId = this.normalizeRequiredPositiveInteger(plan.warehouse_id, 'warehouse_id'); + const taskWaveRows = Array.isArray(options && options.taskWaveRows) + ? options.taskWaveRows + : []; + const taskOrderRows = Array.isArray(options && options.taskOrderRows) + ? options.taskOrderRows + : []; + const taskSkuRows = Array.isArray(options && options.taskSkuRows) + ? options.taskSkuRows + : []; + + if ([ 1, 5 ].includes(pickMode)) { + return taskWaveRows.map(row => ({ + task_id: taskId, + order_id: null, + box_code: `${taskNo || taskId}-W${row.box_no}`, + box_no: row.box_no, + box_type: 3, + ref_id: row.wave_id, + ref_label: row.wave_no, + required_qty: 0, + picked_qty: 0, + box_status: 0, + review_result: null, + review_user_id: null, + review_time: null, + warehouse_id: warehouseId, + })); + } + + if (pickMode === 3 && taskSkuRows.length > 0) { + return taskSkuRows.map(row => ({ + task_id: taskId, + order_id: null, + box_code: `${taskNo || taskId}-S${row.box_no}`, + box_no: row.box_no, + box_type: 1, + ref_id: Number(row.ref_id || row.sku_id || 0) || null, + ref_label: String(row.ref_label || '').trim() || null, + required_qty: Number(row.required_qty || 0), + picked_qty: 0, + box_status: 0, + review_result: null, + review_user_id: null, + review_time: null, + warehouse_id: warehouseId, + })); + } + + return taskOrderRows.map(row => ({ + task_id: taskId, + order_id: row.order_id, + box_code: `${taskNo || taskId}-O${row.box_no}`, + box_no: row.box_no, + box_type: 2, + ref_id: row.order_id, + ref_label: null, + required_qty: 0, + picked_qty: 0, + box_status: 0, + review_result: null, + review_user_id: null, + review_time: null, + warehouse_id: warehouseId, + })); + } + + /** + * 领单时绑定拣货车并更新车辆主表。 + * + * @param {Object} params 绑定参数。 + * @param {number} params.taskId 任务ID。 + * @param {number} params.cartId 拣货车ID。 + * @param {number} params.warehouseId 仓库ID。 + * @param {number} params.operatorId 操作人ID。 + * @param {Object} params.transaction 事务对象。 + * @return {Promise} 无返回值。 + */ + async bindPickCartForTask(params = {}) { + const taskId = this.normalizeRequiredPositiveInteger(params.taskId, 'task_id'); + const cartId = this.normalizeRequiredPositiveInteger(params.cartId, 'cart_id'); + const warehouseId = this.normalizeRequiredPositiveInteger(params.warehouseId, 'warehouse_id'); + const transaction = params.transaction; + const operatorId = Number.isInteger(Number(params.operatorId)) + ? Number(params.operatorId) + : 0; + + const cartRows = await this.ctx.model.query(` + SELECT id, cart_code, current_task_id + FROM wms_pick_cart + WHERE id = :cartId + AND warehouse_id = :warehouseId + AND status = 1 + FOR UPDATE + `, { + replacements: { + cartId, + warehouseId, + }, + type: this.ctx.model.QueryTypes.SELECT, + transaction, + }); + + const cartRow = Array.isArray(cartRows) ? cartRows[0] : null; + if (!cartRow) { + throw new Error(`拣货车不存在或已停用: ${cartId}`); + } + + const activeTaskId = Number(cartRow.current_task_id || 0); + if (activeTaskId > 0 && activeTaskId !== taskId) { + throw new Error(`拣货车已被任务占用: ${cartId}`); + } + + await this.bulkInsertRows('wms_pick_task_cart_binding', [{ + task_id: taskId, + cart_id: cartId, + cart_code_snapshot: String(cartRow.cart_code || '').trim() || null, + warehouse_id: warehouseId, + bind_user_id: operatorId, + bind_type: 1, + unbind_user_id: null, + is_active: 1, + bind_time: new Date(), + unbind_time: null, + }], transaction); + + await this.ctx.model.query(` + UPDATE wms_pick_cart + SET + current_task_id = :taskId, + bind_user_id = :operatorId, + last_bind_time = NOW(), + last_seen_time = NOW() + WHERE id = :cartId + AND warehouse_id = :warehouseId + `, { + replacements: { + taskId, + operatorId, + cartId, + warehouseId, + }, + transaction, + }); + + await this.ctx.model.query(` + UPDATE wms_wave_pick_task + SET + current_cart_id = :cartId, + current_cart_code_snapshot = :cartCode + WHERE id = :taskId + AND warehouse_id = :warehouseId + `, { + replacements: { + taskId, + cartId, + cartCode: String(cartRow.cart_code || '').trim() || null, + warehouseId, + }, + transaction, + }); + } + + /** + * 初始化任务断点、动作日志与轨迹。 + * + * @param {Object} params 初始化参数。 + * @param {number} params.taskId 任务ID。 + * @param {string} params.taskNo 任务编号。 + * @param {Object} params.plan 预处理计划。 + * @param {Object} params.data 原始请求数据。 + * @param {Array} params.selectedOrderIds 已选订单ID。 + * @param {number} params.cartId 绑定车ID。 + * @param {number} params.operatorId 操作人ID。 + * @param {string} params.operatorName 操作人姓名。 + * @param {Object} params.transaction 事务对象。 + * @return {Promise} 无返回值。 + */ + async initTaskCheckpointAndLogs(params = {}) { + const taskId = this.normalizeRequiredPositiveInteger(params.taskId, 'task_id'); + const taskNo = String(params.taskNo || '').trim(); + const plan = this.isPlainObject(params.plan) ? params.plan : {}; + const data = this.isPlainObject(params.data) ? params.data : {}; + const transaction = params.transaction; + const warehouseId = this.normalizeRequiredPositiveInteger(plan.warehouse_id, 'warehouse_id'); + const operatorId = Number.isInteger(Number(params.operatorId)) + ? Number(params.operatorId) + : 0; + const operatorName = String(params.operatorName || 'system').trim() || 'system'; + const cartId = Number(params.cartId || 0) > 0 ? Number(params.cartId) : null; + const selectedOrderIds = Array.isArray(params.selectedOrderIds) && params.selectedOrderIds.length > 0 + ? params.selectedOrderIds + : [ 0 ]; + const deviceId = String(data.device_id || data.deviceId || '').trim() || `device_${warehouseId}`; + const requestId = String(data.request_id || data.requestId || `${taskNo || taskId}_init`).trim(); + + await this.bulkInsertRows('wms_wave_pick_checkpoint', [{ + task_id: taskId, + warehouse_id: warehouseId, + pick_user_id: operatorId, + device_id: deviceId, + current_location_id: null, + current_sku_id: null, + current_box_no: null, + picked_count: 0, + remaining_count: Math.max(selectedOrderIds.length, 0), + last_event_id: null, + last_seq_no: null, + checkpoint_json: JSON.stringify({ + state: 'created', + task_no: taskNo, + }), + version: 0, + }], transaction); + + await this.bulkInsertRows('wms_wave_pick_action_log', [{ + task_id: taskId, + warehouse_id: warehouseId, + wave_id: Array.isArray(plan.selected_wave_ids) && plan.selected_wave_ids.length > 0 + ? Number(plan.selected_wave_ids[0]) + : null, + order_id: selectedOrderIds[0], + sku_id: null, + location_id: null, + box_no: null, + cart_id: cartId, + qty_delta: 0, + action_type: 'init', + request_id: `${requestId}_${taskId}`, + operator_id: operatorId, + device_id: deviceId, + seq_no: 1, + snapshot: JSON.stringify({ + task_no: taskNo, + state: 'created', + }), + }], transaction); + + const traceRows = selectedOrderIds.map(orderId => ({ + warehouse_id: warehouseId, + order_id: Number(orderId), + task_id: taskId, + cart_id: cartId, + cart_code_snapshot: null, + pick_user_id: operatorId, + pick_time: null, + review_user_id: null, + review_time: null, + review_result: null, + event_type: 'task_created', + event_desc: `任务创建: ${taskNo || taskId}`, + operator_id: operatorId, + operator_name: operatorName, + snapshot: JSON.stringify({ + task_no: taskNo, + pick_mode: Number(plan.pick_mode || 0), + }), + })); + await this.bulkInsertRows('wms_order_pick_trace', traceRows, transaction); + } + + /** + * 校验拣货车是否可占用。 + * + * @param {Object} params 校验参数。 + * @param {number} params.cartId 拣货车ID。 + * @param {number} params.warehouseId 仓库ID。 + * @param {Object} params.transaction 事务对象。 + * @return {Promise} 无返回值。 + */ + async ensurePickCartAvailable(params = {}) { + const cartId = this.normalizeRequiredPositiveInteger(params.cartId, 'cart_id'); + const warehouseId = this.normalizeRequiredPositiveInteger(params.warehouseId, 'warehouse_id'); + const transaction = params.transaction; + + const rows = await this.ctx.model.query(` + SELECT b.task_id + FROM wms_pick_task_cart_binding b + INNER JOIN wms_wave_pick_task t ON t.id = b.task_id + WHERE b.cart_id = :cartId + AND b.warehouse_id = :warehouseId + AND b.is_active = 1 + AND t.status IN (0, 1) + LIMIT 1 + FOR UPDATE + `, { + replacements: { + cartId, + warehouseId, + }, + type: this.ctx.model.QueryTypes.SELECT, + transaction, + }); + + if (Array.isArray(rows) && rows.length > 0) { + throw new Error(`拣货车已绑定活动任务: ${cartId}`); + } + } + + /** + * 生成任务编号。 + * + * @param {number} warehouseId 仓库ID。 + * @param {number} sourceCode 来源编码。 + * @return {string} 任务编号。 + */ + generateWavePickTaskNo(warehouseId, sourceCode) { + const now = Date.now(); + const rand = Math.random().toString(36).slice(2, 8) + .toUpperCase(); + return `WPT${warehouseId}${sourceCode}${now}${rand}`; + } + + /** + * 写入任务主表并在任务编号冲突时重试。 + * + * @param {Object} payload 主表载荷。 + * @param {Object} transaction 事务对象。 + * @return {Promise<{ task_id: number, task_no: string }>} 主表写入结果。 + */ + async createWavePickTaskWithRetry(payload = {}, transaction) { + const maxRetry = 5; + const warehouseId = this.normalizeRequiredPositiveInteger(payload.warehouse_id, 'warehouse_id'); + + for (let attempt = 1; attempt <= maxRetry; attempt += 1) { + const candidateTaskNo = attempt === 1 && String(payload.task_no || '').trim() + ? String(payload.task_no || '').trim() + : this.generateWavePickTaskNo(warehouseId, Number(payload.source || 1)); + + const insertPayload = { + ...payload, + task_no: candidateTaskNo, + }; + + try { + const createResult = await this.ctx.model.query(` + INSERT INTO wms_wave_pick_task + ( + task_no, + warehouse_id, + wave_id, + pick_mode, + status, + source, + wave_count, + order_count, + box_count, + batch_no, + pick_user_id, + pick_user_name, + current_cart_id, + current_cart_code_snapshot, + review_status, + review_version, + device_id, + ext_json, + create_time, + update_time + ) + VALUES + ( + :task_no, + :warehouse_id, + :wave_id, + :pick_mode, + :status, + :source, + :wave_count, + :order_count, + :box_count, + :batch_no, + :pick_user_id, + :pick_user_name, + :current_cart_id, + :current_cart_code_snapshot, + :review_status, + :review_version, + :device_id, + :ext_json, + NOW(), + NOW() + ) + `, { + replacements: insertPayload, + transaction, + }); + + let insertedTaskId = this.extractInsertId(createResult); + if (!Number.isInteger(insertedTaskId) || insertedTaskId <= 0) { + const fallbackResult = await this.ctx.model.query('SELECT LAST_INSERT_ID() AS insertId', { + transaction, + }); + insertedTaskId = this.extractLastInsertId(fallbackResult); + } + + if (!Number.isInteger(insertedTaskId) || insertedTaskId <= 0) { + throw new Error('创建任务失败,未获取到任务主键'); + } + + return { + task_id: insertedTaskId, + task_no: candidateTaskNo, + }; + } catch (error) { + const isDuplicateTaskNo = this.isTaskNoDuplicateError(error); + if (isDuplicateTaskNo && attempt < maxRetry) { + continue; + } + throw error; + } + } + + throw new Error('创建任务失败,任务编号重试次数已达上限'); + } + + /** + * 判断是否为 task_no 唯一键冲突。 + * + * @param {Error} error 数据库错误。 + * @return {boolean} 是否冲突。 + */ + isTaskNoDuplicateError(error) { + const message = String(error && error.message || '').toLowerCase(); + const parentErrno = Number(error && error.parent && error.parent.errno || 0); + return parentErrno === 1062 + || message.includes('duplicate entry') + || message.includes('uk_task_no'); + } + + /** + * 批量插入行数据。 + * + * @param {string} tableName 表名。 + * @param {Array} rows 行数据。 + * @param {Object} transaction 事务对象。 + * @return {Promise} 实际写入行数。 + */ + async bulkInsertRows(tableName, rows = [], transaction) { + if (!Array.isArray(rows) || rows.length === 0) { + return 0; + } + + const columns = Object.keys(rows[0]); + if (columns.length === 0) { + return 0; + } + + const replacements = {}; + const valueSqlList = rows.map((row, rowIndex) => { + const placeholders = columns.map(column => { + const key = `${column}_${rowIndex}`; + replacements[key] = Object.prototype.hasOwnProperty.call(row, column) + ? row[column] + : null; + return `:${key}`; + }); + return `(${placeholders.join(', ')})`; + }); + + const columnSql = columns.map(column => `\`${column}\``).join(', '); + const sql = `INSERT INTO ${tableName} (${columnSql}) VALUES ${valueSqlList.join(', ')}`; + await this.ctx.model.query(sql, { + replacements, + transaction, + }); + + return rows.length; + } + + /** + * 解析“存在未完成任务”异常信息中的任务标识。 + * + * @param {string} message 异常消息文本。 + * @return {{ task_id: number|null, task_no: string|null }} 解析结果。 + */ + parseWaveStrategyExistingTaskInfo(message = '') { + const normalizedMessage = String(message || ''); + const match = normalizedMessage.match(/task_id=(\d+)(?:,task_no=([^\)\)\s]+))?/); + if (!match) { + return { + task_id: null, + task_no: null, + }; + } + + const parsedTaskId = Number(match[1] || 0); + const parsedTaskNo = String(match[2] || '').trim(); + + return { + task_id: Number.isInteger(parsedTaskId) && parsedTaskId > 0 ? parsedTaskId : null, + task_no: parsedTaskNo || null, + }; + } + + /** + * 按策略抓取任务壳子方法(仅 PDA 使用),仅受理请求并返回任务信息。 + * + * @param {Object} [data={}] 请求参数。 + * @param {number|string} data.strategy_id 波次策略ID(支持 strategyId)。 + * @return {Promise} 受理结果。 + */ + async waveStrategyFetchPda(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + const strategyId = this.normalizeRequiredPositiveInteger( + normalizedData.strategy_id ?? normalizedData.strategyId, + 'strategy_id' + ); + + let warehouseId; + try { + warehouseId = Number(this.getWarehouseId()); + } catch (error) { + throw new Error('未识别到当前仓库上下文'); + } + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + + const operatorInfo = this.getOrderLogOperator(); + const plan = await this.prepareWaveStrategyFetchPlan({ + strategyId, + warehouseId, + operator: { + operator_id: operatorInfo.id, + operator_name: operatorInfo.name, + }, + source: 'pda', + data: normalizedData, + }); + + if (Array.isArray(plan.validation_errors) && plan.validation_errors.length > 0) { + return this.fail('按策略抓取预处理校验失败', { + data: { + status: 'failed', + fetch_state: 2, + tip: '创建失败,请重试', + task_id: null, + can_enter_pick_flow: false, + warehouse_id: warehouseId, + strategy_id: strategyId, + source: 'pda', + plan, + }, + }, 400); + } + + try { + const createdTask = await this.createWavePickTaskFromPlan({ + plan, + data: normalizedData, + waveBatchSource: 2, + autoPopulateSelections: true, + }); + + this.ctx.logger.info('[wave.waveStrategyFetchPda] 任务创建成功', { + taskId: createdTask.task_id, + taskNo: createdTask.task_no, + warehouseId, + strategyId, + }); + + return this.success('ok', { + status: 'success', + fetch_state: 1, + tip: '任务创建成功', + task_id: createdTask.task_id, + task_no: createdTask.task_no, + can_enter_pick_flow: false, + warehouse_id: warehouseId, + strategy_id: strategyId, + source: 'pda', + state: createdTask.state, + plan, + plan_summary: createdTask.plan_summary, + accepted_at: new Date().toISOString(), + }); + } catch (error) { + const errorMessage = String(error && error.message || ''); + if (errorMessage.includes('当前用户存在未完成任务')) { + const existingTaskInfo = this.parseWaveStrategyExistingTaskInfo(errorMessage); + return this.success('存在未完成任务', { + status: 'failed', + fetch_state: 3, + tip: '存在未完成任务,已返回任务ID,可继续拣货', + task_id: existingTaskInfo.task_id, + task_no: existingTaskInfo.task_no, + can_enter_pick_flow: true, + warehouse_id: warehouseId, + strategy_id: strategyId, + source: 'pda', + plan, + }); + } + + return this.fail(`按策略抓取任务创建失败: ${error.message}`, { + data: { + status: 'failed', + fetch_state: 2, + tip: '创建失败,请重试', + task_id: null, + can_enter_pick_flow: false, + warehouse_id: warehouseId, + strategy_id: strategyId, + source: 'pda', + plan, + }, + }, 500); + } + } + + /** + * 公共拣货任务取消流程。 + * + * 仅允许取消状态为 0/1/2 的任务。取消后会回收拣货车绑定、 + * 删除任务关联波次并将订单 wave_id 清空,使订单可重新参与后续策略抓取。 + * + * @param {Object} [params={}] 取消参数。 + * @param {Array} params.taskIds 任务ID列表。 + * @param {number} params.warehouseId 仓库ID。 + * @param {number} params.operatorId 操作人ID。 + * @param {string} params.operatorName 操作人名称。 + * @param {number|null} [params.restrictCreatorId=null] 限制创建人ID。 + * @return {Promise} 取消结果。 + */ + async cancelWavePickTasksInternal(params = {}) { + const normalizedParams = this.isPlainObject(params) ? params : {}; + const sourceTaskIds = Array.isArray(normalizedParams.taskIds) ? normalizedParams.taskIds : []; + const normalizedTaskIds = [ ...new Set(sourceTaskIds + .map(item => Number(item)) + .filter(taskId => Number.isInteger(taskId) && taskId > 0)) ]; + const warehouseId = Number(normalizedParams.warehouseId || 0); + const operatorId = Number(normalizedParams.operatorId || 0); + const operatorName = String(normalizedParams.operatorName || 'system').trim() || 'system'; + const rawRestrictCreatorId = normalizedParams.restrictCreatorId; + const restrictCreatorId = rawRestrictCreatorId === null || rawRestrictCreatorId === undefined + ? null + : Number(rawRestrictCreatorId); + + if (normalizedTaskIds.length === 0) { + const error = new Error('task_ids 必须为非空数组'); + error.statusCode = 400; + error.data = {}; + throw error; + } + + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + const error = new Error('未获取到仓库上下文'); + error.statusCode = 400; + error.data = {}; + throw error; + } + + if (!Number.isInteger(operatorId) || operatorId <= 0) { + const error = new Error('未获取到操作人上下文'); + error.statusCode = 400; + error.data = {}; + throw error; + } + + if (restrictCreatorId !== null && (!Number.isInteger(restrictCreatorId) || restrictCreatorId <= 0)) { + const error = new Error('取消任务创建人限制参数不合法'); + error.statusCode = 400; + error.data = {}; + throw error; + } + + const transaction = await this.ctx.model.transaction(); + + try { + const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + const canceledAtColumnRows = await this.ctx.model.query(` + SHOW COLUMNS FROM wms_wave_pick_task LIKE 'cancelled_at' + `, { + type: this.ctx.model.QueryTypes.SELECT, + transaction, + }); + const hasCancelledAtColumn = Array.isArray(canceledAtColumnRows) && canceledAtColumnRows.length > 0; + const cancelledTaskNos = []; + + for (const taskId of normalizedTaskIds) { + const requestId = `wave_pick_task_cancel_${warehouseId}_${taskId}_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`; + const taskRows = await this.ctx.model.query(` + SELECT id, task_no, warehouse_id, status, current_cart_id + FROM wms_wave_pick_task + WHERE id = :taskId + AND warehouse_id = :warehouseId + ${restrictCreatorId !== null ? 'AND pick_user_id = :restrictCreatorId' : ''} + LIMIT 1 + FOR UPDATE + `, { + replacements: { + taskId, + warehouseId, + ...(restrictCreatorId !== null ? { restrictCreatorId } : {}), + }, + type: this.ctx.model.QueryTypes.SELECT, + transaction, + }); + + const taskRow = Array.isArray(taskRows) ? taskRows[0] : null; + if (!taskRow) { + if (restrictCreatorId !== null) { + const taskRowsWithoutCreator = await this.ctx.model.query(` + SELECT id + FROM wms_wave_pick_task + WHERE id = :taskId + AND warehouse_id = :warehouseId + LIMIT 1 + `, { + replacements: { + taskId, + warehouseId, + }, + type: this.ctx.model.QueryTypes.SELECT, + transaction, + }); + if (Array.isArray(taskRowsWithoutCreator) && taskRowsWithoutCreator.length > 0) { + const error = new Error('仅允许取消本人创建的任务'); + error.statusCode = 403; + error.data = { + task_id: taskId, + warehouse_id: warehouseId, + operator_id: restrictCreatorId, + }; + throw error; + } + } + + const error = new Error('任务不存在'); + error.statusCode = 404; + error.data = { + task_id: taskId, + warehouse_id: warehouseId, + }; + throw error; + } + + const taskStatus = Number(taskRow.status || 0); + if (![ 0, 1, 2 ].includes(taskStatus)) { + const error = new Error('当前任务状态不允许取消'); + error.statusCode = 400; + error.data = { + task_id: taskId, + task_no: String(taskRow.task_no || '').trim(), + warehouse_id: warehouseId, + status: taskStatus, + }; + throw error; + } + + const taskNo = String(taskRow.task_no || '').trim(); + + const taskWaveRows = await this.ctx.model.query(` + SELECT wave_id + FROM wms_wave_pick_task_wave + WHERE task_id = :taskId + AND warehouse_id = :warehouseId + `, { + replacements: { + taskId, + warehouseId, + }, + type: this.ctx.model.QueryTypes.SELECT, + transaction, + }); + const waveIds = [ ...new Set((Array.isArray(taskWaveRows) ? taskWaveRows : []) + .map(row => Number(row && row.wave_id || 0)) + .filter(waveId => Number.isInteger(waveId) && waveId > 0)) ]; + + const taskOrderRows = await this.ctx.model.query(` + SELECT order_id + FROM wms_wave_pick_task_order + WHERE task_id = :taskId + AND warehouse_id = :warehouseId + `, { + replacements: { + taskId, + warehouseId, + }, + type: this.ctx.model.QueryTypes.SELECT, + transaction, + }); + const taskOrderIds = [ ...new Set((Array.isArray(taskOrderRows) ? taskOrderRows : []) + .map(row => Number(row && row.order_id || 0)) + .filter(orderId => Number.isInteger(orderId) && orderId > 0)) ]; + + let releasedWaveRows = []; + if (waveIds.length > 0) { + releasedWaveRows = await this.ctx.model.query(` + SELECT wave_id, wave_no + FROM wms_wave_batch + WHERE warehouse_id = :warehouseId + AND wave_id IN (:waveIds) + FOR UPDATE + `, { + replacements: { + warehouseId, + waveIds, + }, + type: this.ctx.model.QueryTypes.SELECT, + transaction, + }); + + await orderModel.update({ + wave_id: 0, + wave_no: '', + }, { + where: { + warehouse_id: warehouseId, + wave_id: { [Op.in]: waveIds }, + }, + transaction, + }); + + await this.ctx.model.query(` + DELETE FROM wms_wave_batch + WHERE warehouse_id = :warehouseId + AND wave_id IN (:waveIds) + `, { + replacements: { + warehouseId, + waveIds, + }, + transaction, + }); + + await this.ctx.model.query(` + DELETE FROM wms_wave_pick_task_wave + WHERE task_id = :taskId + AND warehouse_id = :warehouseId + `, { + replacements: { + taskId, + warehouseId, + }, + transaction, + }); + } + + await this.ctx.model.query(` + UPDATE wms_wave_pick_task + SET + status = 9, + current_cart_id = NULL, + current_cart_code_snapshot = NULL, + ${hasCancelledAtColumn ? 'cancelled_at = NOW(),' : ''} + update_time = NOW() + WHERE id = :taskId + AND warehouse_id = :warehouseId + `, { + replacements: { + taskId, + warehouseId, + }, + transaction, + }); + + await this.ctx.model.query(` + UPDATE wms_pick_task_cart_binding + SET + is_active = 0, + unbind_user_id = :operatorId, + unbind_time = NOW(), + update_time = NOW() + WHERE task_id = :taskId + AND warehouse_id = :warehouseId + AND is_active = 1 + `, { + replacements: { + taskId, + warehouseId, + operatorId, + }, + transaction, + }); + + await this.ctx.model.query(` + UPDATE wms_pick_cart + SET + current_task_id = NULL, + bind_user_id = NULL, + last_seen_time = NOW(), + update_time = NOW() + WHERE warehouse_id = :warehouseId + AND current_task_id = :taskId + `, { + replacements: { + taskId, + warehouseId, + }, + transaction, + }); + + await this.bulkInsertRows('wms_wave_pick_action_log', [{ + task_id: taskId, + warehouse_id: warehouseId, + wave_id: Array.isArray(releasedWaveRows) && releasedWaveRows.length > 0 + ? Number(releasedWaveRows[0].wave_id || 0) || null + : null, + order_id: taskOrderIds.length > 0 ? Number(taskOrderIds[0]) : null, + sku_id: null, + location_id: null, + box_no: null, + cart_id: Number(taskRow.current_cart_id || 0) > 0 ? Number(taskRow.current_cart_id) : null, + qty_delta: 0, + action_type: 'cancel', + request_id: requestId, + operator_id: Number.isInteger(operatorId) ? operatorId : 0, + device_id: null, + seq_no: 1, + snapshot: JSON.stringify({ + task_no: taskNo, + released_wave_ids: waveIds, + released_order_count: taskOrderIds.length, + }), + }], transaction); + + await this.bulkInsertRows('wms_order_pick_trace', [{ + warehouse_id: warehouseId, + order_id: taskOrderIds.length > 0 ? Number(taskOrderIds[0]) : 0, + task_id: taskId, + cart_id: Number(taskRow.current_cart_id || 0) > 0 ? Number(taskRow.current_cart_id) : null, + cart_code_snapshot: null, + pick_user_id: null, + pick_time: null, + review_user_id: null, + review_time: null, + review_result: null, + event_type: 'task_cancelled', + event_desc: `任务取消并释放波次: ${taskNo || taskId}`, + operator_id: Number.isInteger(operatorId) ? operatorId : 0, + operator_name: operatorName, + snapshot: JSON.stringify({ + task_no: taskNo, + released_wave_ids: waveIds, + released_order_count: taskOrderIds.length, + released_wave_nos: (Array.isArray(releasedWaveRows) ? releasedWaveRows : []) + .map(row => String(row && row.wave_no || '').trim()) + .filter(Boolean), + }), + }], transaction); + + cancelledTaskNos.push(taskNo); + } + + await transaction.commit(); + + return { + cancelled_count: normalizedTaskIds.length, + task_ids: normalizedTaskIds, + task_nos: cancelledTaskNos, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + /** + * 取消拣货任务并释放关联波次。 + * + * 仅允许取消状态为 0/1/2 的任务。取消后会回收拣货车绑定、 + * 删除任务关联波次并将订单 wave_id 清空,使订单可重新参与后续策略抓取。 + * + * @param {Object} [data={}] 请求参数。 + * @param {Array} data.task_ids 任务ID数组。 + * @return {Promise} 取消结果。 + */ + async wavePickTaskCancel(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + const sourceTaskIds = Array.isArray(normalizedData.task_ids) ? normalizedData.task_ids : []; + if (sourceTaskIds.length === 0) { + return this.fail('task_ids 必须为非空数组', {}, 400); + } + + const normalizedTaskIds = []; + for (const item of sourceTaskIds) { + const taskId = Number(item); + if (!Number.isInteger(taskId) || taskId <= 0) { + return this.fail('task_ids 必须为正整数数组', { + data: { + task_ids: sourceTaskIds, + }, + }, 400); + } + normalizedTaskIds.push(taskId); + } + const taskIds = [ ...new Set(normalizedTaskIds) ]; + if (taskIds.length === 0) { + return this.fail('task_ids 必须为非空数组', {}, 400); + } + + const resolvedWarehouseId = Number(this.getWarehouseId() || 0); + if (!Number.isInteger(resolvedWarehouseId) || resolvedWarehouseId <= 0) { + return this.fail('未获取到仓库上下文', {}, 400); + } + + const operatorInfo = this.getOrderLogOperator(); + const operatorId = Number(operatorInfo.id || 0); + if (!Number.isInteger(operatorId) || operatorId <= 0) { + return this.fail('未获取到操作人上下文', {}, 400); + } + const operatorName = String(operatorInfo.name || 'system').trim() || 'system'; + + try { + const result = await this.cancelWavePickTasksInternal({ + taskIds, + warehouseId: resolvedWarehouseId, + operatorId, + operatorName, + restrictCreatorId: null, + }); + + return this.success('ok', result); + } catch (error) { + if (Number.isInteger(error.statusCode) && error.statusCode >= 400 && error.statusCode < 500) { + return this.fail(error.message, { + data: this.isPlainObject(error.data) ? error.data : {}, + }, error.statusCode); + } + + return this.fail(`取消拣货任务失败: ${error.message}`, { + data: { + task_ids: taskIds, + warehouse_id: resolvedWarehouseId, + }, + }, 500); + } + } + + /** + * 取消本人创建的单个拣货任务并释放关联波次。 + * + * @param {Object} [data={}] 请求参数。 + * @param {number|string} data.task_id 任务ID。 + * @return {Promise} 取消结果。 + */ + async wavePickTaskCancelSelf(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + if (Object.prototype.hasOwnProperty.call(normalizedData, 'task_ids')) { + return this.fail('当前接口仅支持单个 task_id,请勿传 task_ids', { + data: { + task_ids: normalizedData.task_ids, + }, + }, 400); + } + + const taskId = Number(normalizedData.task_id); + if (!Number.isInteger(taskId) || taskId <= 0) { + return this.fail('task_id 必须为正整数', { + data: { + task_id: normalizedData.task_id, + }, + }, 400); + } + + const resolvedWarehouseId = Number(this.getWarehouseId() || 0); + if (!Number.isInteger(resolvedWarehouseId) || resolvedWarehouseId <= 0) { + return this.fail('未获取到仓库上下文', {}, 400); + } + + const operatorInfo = this.getOrderLogOperator(); + const operatorId = Number(operatorInfo.id || 0); + if (!Number.isInteger(operatorId) || operatorId <= 0) { + return this.fail('未获取到操作人上下文', {}, 400); + } + const operatorName = String(operatorInfo.name || 'system').trim() || 'system'; + + try { + const result = await this.cancelWavePickTasksInternal({ + taskIds: [ taskId ], + warehouseId: resolvedWarehouseId, + operatorId, + operatorName, + restrictCreatorId: operatorId, + }); + + return this.success('ok', result); + } catch (error) { + if (Number.isInteger(error.statusCode) && error.statusCode >= 400 && error.statusCode < 500) { + return this.fail(error.message, { + data: this.isPlainObject(error.data) ? error.data : {}, + }, error.statusCode); + } + + return this.fail(`取消本人拣货任务失败: ${error.message}`, { + data: { + task_id: taskId, + warehouse_id: resolvedWarehouseId, + }, + }, 500); + } + } + + /** + * 后台按策略直接抓取并创建波次。 + * + * @param {Object} [data={}] 请求参数。 + * @param {number|string} data.strategy_id 波次策略ID(支持 strategyId)。 + * @return {Promise} 建波结果。 + */ + async waveStrategyFetchAdmin(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + const strategyId = this.normalizeRequiredPositiveInteger( + normalizedData.strategy_id ?? normalizedData.strategyId, + 'strategy_id' + ); + + let warehouseId; + try { + warehouseId = Number(this.getWarehouseId()); + } catch (error) { + throw new Error('未识别到当前仓库上下文'); + } + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + + const operatorInfo = this.getOrderLogOperator(); + const plan = await this.prepareWaveStrategyFetchPlan({ + strategyId, + warehouseId, + operator: { + operator_id: operatorInfo.id, + operator_name: operatorInfo.name, + }, + source: 'admin', + data: normalizedData, + }); + + if (Array.isArray(plan.validation_errors) && plan.validation_errors.length > 0) { + return this.fail('按策略抓取预处理校验失败', { + data: { + status: 'failed', + fetch_state: 2, + tip: '建波失败,请重试', + warehouse_id: warehouseId, + strategy_id: strategyId, + source: 'admin', + plan, + }, + }, 400); + } + + try { + const directFetchResult = await this.executeWaveStrategyDirectFetch({ + plan, + waveBatchSource: 1, + }); + + this.ctx.logger.info('[wave.waveStrategyFetchAdmin] 建波成功', { + warehouseId, + strategyId, + strategyType: directFetchResult.strategy_type, + createdWaveCount: directFetchResult.created_wave_count, + createdOrderCount: directFetchResult.created_order_count, + }); + + return this.success('ok', { + status: 'success', + fetch_state: 1, + tip: '建波成功', + warehouse_id: warehouseId, + strategy_id: strategyId, + source: 'admin', + plan, + wave_ids: directFetchResult.wave_ids, + wave_nos: directFetchResult.wave_nos, + order_ids: directFetchResult.order_ids, + created_wave_count: directFetchResult.created_wave_count, + created_order_count: directFetchResult.created_order_count, + wave_prefix: directFetchResult.wave_prefix, + wave_prefix_source: directFetchResult.wave_prefix_source, + candidate_count: directFetchResult.candidate_count, + grouped_count: directFetchResult.grouped_count, + strategy_type: directFetchResult.strategy_type, + accepted_at: new Date().toISOString(), + }); + } catch (error) { + return this.fail(`按策略抓取建波失败: ${error.message}`, { + data: { + status: 'failed', + fetch_state: 2, + tip: '建波失败,请重试', + warehouse_id: warehouseId, + strategy_id: strategyId, + source: 'admin', + plan, + }, + }, 500); + } + } + + /** + * 删除指定订单的波次索引记录。 + * + * @param {Object} [params={}] 参数对象。 + * @param {number|string} [params.warehouseId] 仓库ID。 + * @param {Array} [params.orderIds] 订单ID列表。 + * @param {Object} [params.transaction] 事务对象。 + * @return {Promise} + */ + async deleteOrderWaveIndexByOrderIds({ warehouseId, orderIds, transaction } = {}) { + const normalizedWarehouseId = Number(warehouseId || 0); + const normalizedOrderIds = this.normalizeIdsInput(orderIds); + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0 || normalizedOrderIds.length === 0) { + return; + } + + const deleteSql = ` + DELETE FROM wms_order_wave_index + WHERE warehouse_id = :warehouseId + AND order_id IN (:orderIds) + `; + + await this.ctx.model.query(deleteSql, { + replacements: { + warehouseId: normalizedWarehouseId, + orderIds: normalizedOrderIds, + }, + transaction, + }); + } + + /** + * 删除指定波次的波次索引记录。 + * + * @param {Object} [params={}] 参数对象。 + * @param {number|string} [params.warehouseId] 仓库ID。 + * @param {Array} [params.waveIds] 波次ID列表。 + * @param {Object} [params.transaction] 事务对象。 + * @return {Promise} + */ + async deleteOrderWaveIndexByWaveIds({ warehouseId, waveIds, transaction } = {}) { + const normalizedWarehouseId = Number(warehouseId || 0); + const normalizedWaveIds = this.normalizeIdsInput(waveIds); + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0 || normalizedWaveIds.length === 0) { + return; + } + + const deleteSql = ` + DELETE FROM wms_order_wave_index + WHERE warehouse_id = :warehouseId + AND wave_id IN (:waveIds) + `; + + await this.ctx.model.query(deleteSql, { + replacements: { + warehouseId: normalizedWarehouseId, + waveIds: normalizedWaveIds, + }, + transaction, + }); + } + + /** + * 重建指定波次的订单波次索引。 + * + * @param {Object} [params={}] 参数对象。 + * @param {number|string} [params.warehouseId] 仓库ID。 + * @param {number|string} [params.waveId] 波次ID。 + * @param {Array} [params.orderIds] 订单ID列表。 + * @param {Object} [params.orderModel] 订单模型实例。 + * @param {Object} [params.transaction] 事务对象。 + * @return {Promise} + */ + async rebuildOrderWaveIndex({ warehouseId, waveId, orderIds, orderModel, transaction } = {}) { + const normalizedWarehouseId = Number(warehouseId || 0); + const normalizedWaveId = Number(waveId || 0); + const normalizedOrderIds = this.normalizeIdsInput(orderIds); + if ( + !Number.isInteger(normalizedWarehouseId) + || normalizedWarehouseId <= 0 + || !Number.isInteger(normalizedWaveId) + || normalizedWaveId <= 0 + || normalizedOrderIds.length === 0 + ) { + return; + } + await this.replaceOrderWaveIndexByWaveIds({ + warehouseId: normalizedWarehouseId, + waveIds: [ normalizedWaveId ], + orderModel, + transaction, + }); + } + + /** + * 按波次ID批量替换订单波次索引记录。 + * + * @param {Object} [params={}] 参数对象。 + * @param {number|string} [params.warehouseId] 仓库ID。 + * @param {Array} [params.waveIds] 波次ID列表。 + * @param {Object} [params.orderModel] 订单模型实例。 + * @param {Object} [params.transaction] 事务对象。 + * @return {Promise>} 各波次对应的订单总数映射。 + */ + async replaceOrderWaveIndexByWaveIds({ warehouseId, waveIds, orderModel, transaction } = {}) { + const normalizedWarehouseId = Number(warehouseId || 0); + const normalizedWaveIds = this.normalizeIdsInput(waveIds); + const currentOrderModel = orderModel || await this.getOrderModel('pendingOrder', normalizedWarehouseId); + + if ( + !Number.isInteger(normalizedWarehouseId) + || normalizedWarehouseId <= 0 + || normalizedWaveIds.length === 0 + || !currentOrderModel + || typeof currentOrderModel.findAll !== 'function' + ) { + return new Map(); + } + + const orderRows = await currentOrderModel.findAll({ + attributes: [ 'id', 'wave_id', 'sys_platform_code', 'source_platform_code' ], + where: { + wave_id: { + [Op.in]: normalizedWaveIds, + [Op.gt]: 0, + }, + }, + order: [[ 'wave_id', 'ASC' ], [ 'id', 'ASC' ]], + raw: true, + transaction, + }); + + const orderRowsList = Array.isArray(orderRows) ? orderRows : []; + const waveOrderRowsMap = new Map(normalizedWaveIds.map(waveId => [ waveId, []])); + for (const row of orderRowsList) { + const waveId = Number(row && row.wave_id || 0); + const orderId = Number(row && row.id || 0); + if (!Number.isInteger(waveId) || waveId <= 0 || !waveOrderRowsMap.has(waveId)) { + continue; + } + if (!Number.isInteger(orderId) || orderId <= 0) { + continue; + } + + waveOrderRowsMap.get(waveId).push({ + id: orderId, + sys_platform_code: String(row && row.sys_platform_code || ''), + source_platform_code: String(row && row.source_platform_code || ''), + }); + } + + await this.deleteOrderWaveIndexByWaveIds({ + warehouseId: normalizedWarehouseId, + waveIds: normalizedWaveIds, + transaction, + }); + + const allOrderIds = [ ...new Set(orderRowsList + .map(row => Number(row && row.id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ]; + if (allOrderIds.length > 0) { + await this.deleteOrderWaveIndexByOrderIds({ + warehouseId: normalizedWarehouseId, + orderIds: allOrderIds, + transaction, + }); + } + + const valueSqlList = []; + const replacements = { + warehouseId: normalizedWarehouseId, + }; + + let rowIndex = 0; + for (const waveId of normalizedWaveIds) { + const orderRowsByWave = waveOrderRowsMap.get(waveId) || []; + const platformsIndexMap = new Map(); + const platformSequenceMap = new Map(); + for (const orderRow of orderRowsByWave) { + const currentOrderId = Number(orderRow && orderRow.id || 0); + if (!Number.isInteger(currentOrderId) || currentOrderId <= 0) { + continue; + } + + const platformKey = String( + (orderRow && orderRow.sys_platform_code) + || (orderRow && orderRow.source_platform_code) + || '' + ).trim().toLowerCase(); + const nextPlatformSequence = Number(platformSequenceMap.get(platformKey) || 0) + 1; + platformSequenceMap.set(platformKey, nextPlatformSequence); + platformsIndexMap.set(currentOrderId, nextPlatformSequence); + } + + for (const [ orderIndex, orderRow ] of orderRowsByWave.entries()) { + const orderId = Number(orderRow && orderRow.id || 0); + if (!Number.isInteger(orderId) || orderId <= 0) { + continue; + } + const waveSequence = orderIndex + 1; + const platformsSequence = Number(platformsIndexMap.get(orderId) || waveSequence); + valueSqlList.push( + `(:warehouseId, :orderId_${rowIndex}, :waveId_${rowIndex}, :waveIndex_${rowIndex}, :platformsIndex_${rowIndex}, NOW())` + ); + replacements[`orderId_${rowIndex}`] = orderId; + replacements[`waveId_${rowIndex}`] = waveId; + replacements[`waveIndex_${rowIndex}`] = waveSequence; + replacements[`platformsIndex_${rowIndex}`] = platformsSequence; + rowIndex += 1; + } + } + + if (valueSqlList.length > 0) { + const insertSql = ` + INSERT INTO wms_order_wave_index + ( + warehouse_id, + order_id, + wave_id, + wave_index, + platforms_index, + create_at + ) + VALUES + ${valueSqlList.join(',\n ')} + `; + + await this.ctx.model.query(insertSql, { + replacements, + transaction, + }); + } + + const totalOrdersMap = new Map(); + for (const waveId of normalizedWaveIds) { + const orderRowsByWave = waveOrderRowsMap.get(waveId) || []; + totalOrdersMap.set(waveId, orderRowsByWave.length); + } + + return totalOrdersMap; + } + /** * 兼容旧方法名 fetch,内部转调 groupFetch。 * diff --git a/app/service/systemMethods/pick.js b/app/service/systemMethods/pick.js index 45dd25e..b140cc8 100644 --- a/app/service/systemMethods/pick.js +++ b/app/service/systemMethods/pick.js @@ -11,9 +11,9 @@ class PickService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'query,wavePickTaskDetail,wavePickTaskCurrent'; + const _noNeedRight = 'query,wavePickTaskDetail,wavePickTaskCurrent,wavePickTaskSubmit,wavePickTaskComplete'; const _noNeedLog = 'query'; - const _noNeedAuth = 'query,wavePickTaskDetail,wavePickTaskCurrent'; + const _noNeedAuth = 'query,wavePickTaskDetail,wavePickTaskCurrent,wavePickTaskSubmit,wavePickTaskComplete'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -67,6 +67,250 @@ class PickService extends MainService { return model; } + /** + * 生成拣货任务编号。 + * + * @return {string} 任务编号。 + */ + generatePickTaskNo() { + const now = new Date(); + const pad2 = value => String(value).padStart(2, '0'); + const datePart = `${now.getFullYear()}${pad2(now.getMonth() + 1)}${pad2(now.getDate())}`; + const timePart = `${pad2(now.getHours())}${pad2(now.getMinutes())}${pad2(now.getSeconds())}`; + const randomPart = Math.random().toString(36).slice(2, 6).toUpperCase(); + return `PK${datePart}${timePart}${randomPart}`; + } + + /** + * 创建波次拣货任务及关联关系。 + * + * @param {Object} params 创建参数。 + * @param {number} params.warehouseId 仓库ID。 + * @param {number} params.waveId 波次ID。 + * @param {string} params.waveNo 波次号。 + * @param {number} params.pickMode 拣货模式。 + * @param {number} params.operatorId 操作人ID。 + * @param {string} params.operatorName 操作人名称。 + * @param {Array} params.orderIds 波次订单ID集合。 + * @param {string} [params.remark=''] 备注。 + * @return {Promise<{task_id: number, task_no: string}>} 创建结果。 + */ + async createWavePickTask(params = {}) { + const { ctx } = this; + const warehouseId = Number(params && params.warehouseId || 0); + const waveId = Number(params && params.waveId || 0); + const waveNo = String(params && params.waveNo || '').trim(); + const pickMode = Number(params && params.pickMode || 2); + const operatorId = Number(params && params.operatorId || 0); + const operatorName = String(params && params.operatorName || '').trim() || 'system'; + const remark = String(params && params.remark || '').trim(); + const normalizedOrderIds = [ ...new Set((Array.isArray(params && params.orderIds) ? params.orderIds : []) + .map(id => Number(id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ]; + + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw Object.assign(new Error('warehouse_id 参数不合法'), { code: 400 }); + } + if (!Number.isInteger(waveId) || waveId <= 0 || !waveNo) { + throw Object.assign(new Error('目标波次信息不完整'), { code: 400 }); + } + if (!Number.isInteger(operatorId) || operatorId <= 0) { + throw Object.assign(new Error('未获取到操作人上下文'), { code: 401 }); + } + if (normalizedOrderIds.length <= 0) { + throw Object.assign(new Error('波次下无可用订单,无法创建任务'), { code: 400 }); + } + + const orderModel = await this.getOrderModelByWarehouse(warehouseId); + const orderRows = await orderModel.findAll({ + where: { + warehouse_id: warehouseId, + id: { + [this.app.Sequelize.Op.in]: normalizedOrderIds, + }, + }, + attributes: [ 'id' ], + raw: true, + }); + const orderNoMap = new Map((Array.isArray(orderRows) ? orderRows : []) + .map(row => [ Number(row && row.id || 0), '' ])); + + const taskNo = this.generatePickTaskNo(); + const transaction = await ctx.model.transaction(); + try { + const taskInsertResult = await ctx.model.query( + ` + INSERT INTO wms_wave_pick_task ( + task_no, + warehouse_id, + wave_id, + pick_mode, + status, + source, + wave_count, + order_count, + box_count, + pick_user_id, + pick_user_name, + remark, + create_time, + update_time + ) VALUES ( + :taskNo, + :warehouseId, + :waveId, + :pickMode, + 0, + 2, + 1, + :orderCount, + 0, + :operatorId, + :operatorName, + :remark, + NOW(), + NOW() + ) + `, + { + replacements: { + taskNo, + warehouseId, + waveId, + pickMode, + orderCount: normalizedOrderIds.length, + operatorId, + operatorName, + remark, + }, + transaction, + } + ); + + const taskInsertHead = Array.isArray(taskInsertResult) ? taskInsertResult[0] : null; + const taskInsertMeta = Array.isArray(taskInsertResult) ? taskInsertResult[1] : null; + let taskId = Number( + (taskInsertMeta && (taskInsertMeta.insertId || taskInsertMeta.lastID || taskInsertMeta.id)) + || (taskInsertHead && (taskInsertHead.insertId || taskInsertHead.lastID || taskInsertHead.id)) + || 0 + ); + if (!Number.isInteger(taskId) || taskId <= 0) { + const taskIdRows = await ctx.model.query( + ` + SELECT id + FROM wms_wave_pick_task + WHERE warehouse_id = :warehouseId + AND task_no = :taskNo + ORDER BY id DESC + LIMIT 1 + `, + { + replacements: { + warehouseId, + taskNo, + }, + type: ctx.model.QueryTypes.SELECT, + transaction, + } + ); + const taskRow = Array.isArray(taskIdRows) && taskIdRows.length > 0 ? taskIdRows[0] : null; + taskId = Number(taskRow && taskRow.id || 0); + } + if (!Number.isInteger(taskId) || taskId <= 0) { + throw Object.assign(new Error('任务创建失败(未返回任务ID)'), { code: 500 }); + } + + await ctx.model.query( + ` + INSERT INTO wms_wave_pick_task_wave ( + task_id, + wave_id, + wave_no, + status, + warehouse_id, + bind_time, + create_time, + update_time + ) VALUES ( + :taskId, + :waveId, + :waveNo, + 0, + :warehouseId, + NOW(), + NOW(), + NOW() + ) + `, + { + replacements: { + taskId, + waveId, + waveNo, + warehouseId, + }, + transaction, + } + ); + + if (normalizedOrderIds.length > 0) { + const orderValuesSql = []; + const orderReplacements = {}; + normalizedOrderIds.forEach((orderId, index) => { + const orderIdKey = `orderId${index}`; + const orderNoKey = `orderNo${index}`; + orderValuesSql.push(`( + :taskId, + :waveId, + :${orderIdKey}, + :${orderNoKey}, + :warehouseId, + 0, + 0, + NOW(), + NOW() + )`); + orderReplacements[orderIdKey] = orderId; + orderReplacements[orderNoKey] = orderNoMap.get(orderId) || ''; + }); + + await ctx.model.query( + ` + INSERT INTO wms_wave_pick_task_order ( + task_id, + wave_id, + order_id, + order_no, + warehouse_id, + pick_status, + review_status, + create_time, + update_time + ) VALUES ${orderValuesSql.join(',\n')} + `, + { + replacements: { + taskId, + waveId, + warehouseId, + ...orderReplacements, + }, + transaction, + } + ); + } + + await transaction.commit(); + return { + task_id: taskId, + task_no: taskNo, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + /** * 按关键字获取或创建波次拣货任务。 * @@ -74,6 +318,12 @@ class PickService extends MainService { * - 命中运单号:先定位订单并强校验订单已入波次。 * - 命中波次号:直接按波次定位。 * + * 去重策略(按优先级): + * 1. 波次级去重:同一 warehouse_id + 同一 wave_id 且存在活动任务(status IN 0,1)时不再创建。 + * 2. keyword 级去重:同一 warehouse_id + 同一 keyword(remark 字段)在 30 分钟内已有任务时不再创建。 + * - 已完成(status IN 2,3):直接返回已有任务结果。 + * - 进行中(status IN 0,1):返回冲突提示。 + * * 命中目标波次后按以下规则处理: * - 若波次存在活动任务且创建人为当前用户:直接返回任务ID。 * - 若波次存在活动任务但创建人非当前用户:返回冲突失败信息。 @@ -242,11 +492,18 @@ class PickService extends MainService { const activeTaskRows = await ctx.model.query( ` SELECT t.id AS task_id, t.pick_user_id, t.pick_user_name - FROM wms_wave_pick_task_wave tw - INNER JOIN wms_wave_pick_task t ON t.id = tw.task_id - WHERE tw.wave_id = :waveId - AND t.warehouse_id = :warehouseId - AND t.status IN (0, 1, 2) + FROM wms_wave_pick_task t + WHERE t.warehouse_id = :warehouseId + AND t.status IN (0, 1) + AND ( + t.wave_id = :waveId + OR EXISTS ( + SELECT 1 + FROM wms_wave_pick_task_wave tw + WHERE tw.task_id = t.id + AND tw.wave_id = :waveId + ) + ) ORDER BY t.id DESC LIMIT 1 `, @@ -285,11 +542,64 @@ class PickService extends MainService { ); } + // keyword 级别去重:同一 warehouse_id + 同一 keyword(remark)在 30 分钟内已有任务则不再创建 + const keywordRemark = `pick.query keyword=${normalizedKeyword}`; + const keywordDedupRows = await ctx.model.query( + ` + SELECT t.id AS task_id, t.status, t.pick_user_id, t.pick_user_name + FROM wms_wave_pick_task t + WHERE t.warehouse_id = :warehouseId + AND t.remark = :remark + AND t.create_time >= DATE_SUB(NOW(), INTERVAL 30 MINUTE) + ORDER BY t.id DESC + LIMIT 1 + `, + { + replacements: { + warehouseId: normalizedWarehouseId, + remark: keywordRemark, + }, + type: ctx.model.QueryTypes.SELECT, + } + ); + const keywordDedupTask = Array.isArray(keywordDedupRows) && keywordDedupRows.length > 0 ? keywordDedupRows[0] : null; + if (keywordDedupTask) { + const existingTaskId = Number(keywordDedupTask.task_id || 0); + const existingStatus = Number(keywordDedupTask.status ?? -1); + + // 已完成(status=2 待复核 / status=3 已完成):直接返回已有结果,不创建新任务 + if (existingStatus === 2 || existingStatus === 3) { + return this.success('ok', { + data: { + task_id: existingTaskId, + status: 'existing_completed', + tip: '该关键字近期已有完成任务,无需重复创建', + }, + code: 200, + }); + } + + // 进行中(status=0 待开始 / status=1 拣货中):返回已有任务ID,提示任务进行中 + if (existingStatus === 0 || existingStatus === 1) { + const taskOwnerId = Number(keywordDedupTask.pick_user_id || 0); + const taskOwnerName = String(keywordDedupTask.pick_user_name || '').trim() || `${taskOwnerId}`; + return this.fail( + `该关键字近期已有进行中任务(创建人: ${taskOwnerName},任务ID: ${existingTaskId}),请稍后再试`, + { + task_id: existingTaskId, + task_owner_id: taskOwnerId, + task_owner_name: taskOwnerName, + }, + 409 + ); + } + } + const normalizedWaveType = Number(targetWaveType || 2); const isGroupWave = normalizedWaveType === 1; const pickMode = isGroupWave ? 1 : 2; - if (!isGroupWave && selectedOrderIds.length === 0) { + if (selectedOrderIds.length === 0) { let orderModel = null; try { orderModel = await this.getOrderModelByWarehouse(normalizedWarehouseId); @@ -324,36 +634,20 @@ class PickService extends MainService { } if (selectedOrderIds.length <= 0) { - return this.fail('散单波次下无可用订单,无法创建任务', {}, 400); + return this.fail('波次下无可用订单,无法创建任务', {}, 400); } } try { - const plan = { - strategy_id: 0, - warehouse_id: normalizedWarehouseId, - source: 'pda', - operator: { - operator_id: operatorId, - operator_name: operatorName, - }, - pick_mode: pickMode, - wave_limit: 1, - order_limit: selectedOrderIds.length, - sku_limit: 0, - box_limit: 0, - dynamic_append: false, - selected_wave_ids: [ targetWaveId ], - }; - const createData = { - keyword: normalizedKeyword, - selected_order_ids: pickMode === 2 ? selectedOrderIds : [], - }; - - const createdTask = await service.systemMethods.order.wave.createWavePickTaskFromPlan({ - plan, - data: createData, - waveBatchSource: 2, + const createdTask = await this.createWavePickTask({ + warehouseId: normalizedWarehouseId, + waveId: targetWaveId, + waveNo: targetWaveNo, + pickMode, + operatorId, + operatorName, + orderIds: selectedOrderIds, + remark: `pick.query keyword=${normalizedKeyword}`, }); return this.success('ok', { @@ -416,7 +710,8 @@ class PickService extends MainService { } catch (error) { const code = Number(error && error.code); if (Number.isInteger(code) && code >= 400 && code < 600) { - return this.fail(error.message || '查询失败', {}, code); + const errorData = this.isPlainObject(error && error.data) ? error.data : {}; + return this.fail(error.message || '查询失败', errorData, code); } ctx.logger.error('[PickService.wavePickTaskDetail] 查询拣货任务详情失败: %s', error && error.message ? error.message : error); @@ -450,6 +745,104 @@ class PickService extends MainService { return this.fail('查询失败', {}, 500); } } + + /** + * 提交拣货任务中间态。 + * + * @param {Object} data 请求参数。 + * @param {number|string} data.task_id 拣货任务ID。 + * @param {Object} [data.payload] 中间态业务数据。 + * @return {Promise} 统一 success/fail 包装结果。 + */ + async wavePickTaskSubmit(data = {}) { + const { service, ctx } = this; + const requestData = this.isPlainObject(data) ? data : {}; + const taskId = Number(requestData.task_id || requestData.taskId || 0); + + if (!Number.isInteger(taskId) || taskId <= 0) { + return this.fail('task_id 必填且必须为正整数', {}, 400); + } + + try { + const result = await service.systems.pick.wavePickTaskSubmit({ + taskId, + payload: this.isPlainObject(requestData.payload) ? requestData.payload : {}, + }); + + return this.success('ok', { + data: result, + code: 200, + }); + } catch (error) { + const code = Number(error && error.code); + if (Number.isInteger(code) && code >= 400 && code < 600) { + const errorData = this.isPlainObject(error && error.data) ? error.data : {}; + return this.fail(error.message || '提交失败', errorData, code); + } + + ctx.logger.error('[PickService.wavePickTaskSubmit] 提交拣货任务中间态失败: %s', error && error.message ? error.message : error); + return this.fail('提交失败', {}, 500); + } + } + + /** + * 完全提交拣货任务。 + * + * mode: 1=全部确认,2=部分确认(需传 order_ids)。 + * + * @param {Object} data 请求参数。 + * @param {number|string} data.task_id 拣货任务ID。 + * @param {number|string} [data.mode=1] 提交模式。 + * @param {Array|number|string} [data.order_ids] 部分确认时的订单ID集合。 + * @return {Promise} 统一 success/fail 包装结果。 + */ + async wavePickTaskComplete(data = {}) { + const { service, ctx } = this; + const requestData = this.isPlainObject(data) ? data : {}; + const taskId = Number(requestData.task_id || requestData.taskId || 0); + const mode = Number(requestData.mode || 1); + const rawOrderIds = requestData.order_ids !== undefined + ? requestData.order_ids + : requestData.orderIds; + let orderIds = []; + if (Array.isArray(rawOrderIds)) { + orderIds = rawOrderIds; + } else if (typeof rawOrderIds === 'string') { + orderIds = rawOrderIds.split(','); + } else if (typeof rawOrderIds === 'number') { + orderIds = [ rawOrderIds ]; + } + const normalizedOrderIds = [ ...new Set(orderIds + .map(id => Number(id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ]; + + if (!Number.isInteger(taskId) || taskId <= 0) { + return this.fail('task_id 必填且必须为正整数', {}, 400); + } + + try { + const result = await service.systems.pick.wavePickTaskComplete({ + taskId, + mode, + orderIds: normalizedOrderIds, + }); + + return this.success('ok', { + data: result, + code: 200, + }); + } catch (error) { + const code = Number(error && error.code); + if (Number.isInteger(code) && code >= 400 && code < 600) { + const errorData = this.isPlainObject(error && error.data) ? error.data : {}; + return this.fail(error.message || '提交失败', errorData, code); + } + + ctx.logger.error('[PickService.wavePickTaskComplete] 完全提交拣货任务失败: %s', error && error.message ? error.message : error); + return this.fail('提交失败', {}, 500); + } + } + } module.exports = PickService; diff --git a/app/service/systemMethods/pickCart.js b/app/service/systemMethods/pickCart.js new file mode 100644 index 0000000..3f9ac10 --- /dev/null +++ b/app/service/systemMethods/pickCart.js @@ -0,0 +1,316 @@ +'use strict'; + +const MainService = require('../main'); + +class PickCartService extends MainService { + /** + * 初始化 pickCart 模块鉴权配置。 + * + * @param {Egg.Context} ctx 上下文对象。 + */ + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'scan,bindTaskCart,create,update,delete,detail,list,codeDuplicateCheck'; + const _noNeedLog = ''; + const _noNeedAuth = 'scan,bindTaskCart,create,update,delete,detail,list,codeDuplicateCheck'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 按拣货车编码扫码查询。 + * + * @param {Object} data 请求参数。 + * @param {string} data.cart_code 拣货车编码。 + * @return {Promise} 统一 success/fail 包装结果。 + */ + async scan(data = {}) { + const { service, ctx } = this; + const cartCode = String(data && (data.cart_code || data.cartCode) || '').trim(); + + if (!cartCode) { + return this.fail('cart_code 必填', {}, 400); + } + + try { + const result = await service.systems.pickCart.scan({ cartCode }); + return this.success('ok', { + data: result, + code: 200, + }); + } catch (error) { + const code = Number(error && error.code); + if (Number.isInteger(code) && code >= 400 && code < 600) { + const errorData = error && error.data && typeof error.data === 'object' && !Array.isArray(error.data) + ? error.data + : {}; + return this.fail(error.message || '查询失败', errorData, code); + } + + ctx.logger.error('[PickCartService.scan] 扫码查询拣货车失败: %s', error && error.message ? error.message : error); + return this.fail('查询失败', {}, 500); + } + } + + /** + * 绑定拣货任务与拣货车。 + * + * @param {Object} data 请求参数。 + * @param {number|string} data.task_id 拣货任务ID。 + * @param {number|string} [data.cart_id] 拣货车ID。 + * @param {string} [data.cart_code] 拣货车编码。 + * @return {Promise} 统一 success/fail 包装结果。 + */ + async bindTaskCart(data = {}) { + const { service, ctx } = this; + const taskId = Number(data && (data.task_id || data.taskId) || 0); + const cartId = Number(data && (data.cart_id || data.cartId) || 0); + const cartCode = String(data && (data.cart_code || data.cartCode) || '').trim(); + + if (!Number.isInteger(taskId) || taskId <= 0) { + return this.fail('task_id 必填且必须为正整数', {}, 400); + } + if ((!Number.isInteger(cartId) || cartId <= 0) && !cartCode) { + return this.fail('cart_id 或 cart_code 至少传一个', {}, 400); + } + + try { + const result = await service.systems.pickCart.bindTaskCart({ + taskId, + cartId, + cartCode, + }); + return this.success('ok', { + data: result, + code: 200, + }); + } catch (error) { + const code = Number(error && error.code); + if (Number.isInteger(code) && code >= 400 && code < 600) { + const errorData = error && error.data && typeof error.data === 'object' && !Array.isArray(error.data) + ? error.data + : {}; + return this.fail(error.message || '绑定失败', errorData, code); + } + + ctx.logger.error('[PickCartService.bindTaskCart] 绑定拣货车失败: %s', error && error.message ? error.message : error); + return this.fail('绑定失败', {}, 500); + } + } + + /** + * 创建拣货车。 + * + * @param {Object} data 请求参数。 + * @return {Promise} 统一 success/fail 包装结果。 + */ + async create(data = {}) { + const { service, ctx } = this; + + try { + const result = await service.systems.pickCart.create({ + cartCode: String(data && (data.cart_code || data.cartCode) || '').trim(), + cartName: String(data && (data.cart_name || data.cartName) || '').trim(), + status: data && data.status !== undefined ? Number(data.status) : 1, + }); + return this.success('ok', { + data: result, + code: 200, + }); + } catch (error) { + const code = Number(error && error.code); + if (Number.isInteger(code) && code >= 400 && code < 600) { + const errorData = error && error.data && typeof error.data === 'object' && !Array.isArray(error.data) + ? error.data + : {}; + return this.fail(error.message || '创建失败', errorData, code); + } + + ctx.logger.error('[PickCartService.create] 创建拣货车失败: %s', error && error.message ? error.message : error); + return this.fail('创建失败', {}, 500); + } + } + + /** + * 更新拣货车。 + * + * @param {Object} data 请求参数。 + * @return {Promise} 统一 success/fail 包装结果。 + */ + async update(data = {}) { + const { service, ctx } = this; + const cartId = Number(data && (data.cart_id || data.cartId) || 0); + + if (!Number.isInteger(cartId) || cartId <= 0) { + return this.fail('cart_id 必填且必须为正整数', {}, 400); + } + + try { + const result = await service.systems.pickCart.update({ + cartId, + cartCode: data && (data.cart_code !== undefined || data.cartCode !== undefined) + ? String(data.cart_code || data.cartCode || '').trim() + : undefined, + cartName: data && (data.cart_name !== undefined || data.cartName !== undefined) + ? String(data.cart_name || data.cartName || '').trim() + : undefined, + status: data && data.status !== undefined ? Number(data.status) : undefined, + }); + return this.success('ok', { + data: result, + code: 200, + }); + } catch (error) { + const code = Number(error && error.code); + if (Number.isInteger(code) && code >= 400 && code < 600) { + const errorData = error && error.data && typeof error.data === 'object' && !Array.isArray(error.data) + ? error.data + : {}; + return this.fail(error.message || '更新失败', errorData, code); + } + + ctx.logger.error('[PickCartService.update] 更新拣货车失败: %s', error && error.message ? error.message : error); + return this.fail('更新失败', {}, 500); + } + } + + /** + * 删除拣货车。 + * + * @param {Object} data 请求参数。 + * @return {Promise} 统一 success/fail 包装结果。 + */ + async delete(data = {}) { + const { service, ctx } = this; + const cartId = Number(data && (data.cart_id || data.cartId) || 0); + + if (!Number.isInteger(cartId) || cartId <= 0) { + return this.fail('cart_id 必填且必须为正整数', {}, 400); + } + + try { + const result = await service.systems.pickCart.delete({ cartId }); + return this.success('ok', { + data: result, + code: 200, + }); + } catch (error) { + const code = Number(error && error.code); + if (Number.isInteger(code) && code >= 400 && code < 600) { + const errorData = error && error.data && typeof error.data === 'object' && !Array.isArray(error.data) + ? error.data + : {}; + return this.fail(error.message || '删除失败', errorData, code); + } + + ctx.logger.error('[PickCartService.delete] 删除拣货车失败: %s', error && error.message ? error.message : error); + return this.fail('删除失败', {}, 500); + } + } + + /** + * 查询拣货车详情。 + * + * @param {Object} data 请求参数。 + * @return {Promise} 统一 success/fail 包装结果。 + */ + async detail(data = {}) { + const { service, ctx } = this; + const cartId = Number(data && (data.cart_id || data.cartId) || 0); + + if (!Number.isInteger(cartId) || cartId <= 0) { + return this.fail('cart_id 必填且必须为正整数', {}, 400); + } + + try { + const result = await service.systems.pickCart.detail({ cartId }); + return this.success('ok', { + data: result, + code: 200, + }); + } catch (error) { + const code = Number(error && error.code); + if (Number.isInteger(code) && code >= 400 && code < 600) { + const errorData = error && error.data && typeof error.data === 'object' && !Array.isArray(error.data) + ? error.data + : {}; + return this.fail(error.message || '查询失败', errorData, code); + } + + ctx.logger.error('[PickCartService.detail] 查询拣货车详情失败: %s', error && error.message ? error.message : error); + return this.fail('查询失败', {}, 500); + } + } + + /** + * 分页查询拣货车列表。 + * + * @param {Object} data 请求参数。 + * @return {Promise} 统一 success/fail 包装结果。 + */ + async list(data = {}) { + const { service, ctx } = this; + + try { + const result = await service.systems.pickCart.list({ + pagination: data && data.pagination && typeof data.pagination === 'object' ? data.pagination : {}, + where: data && data.where && typeof data.where === 'object' ? data.where : {}, + }); + return this.success('ok', { + data: result, + code: 200, + }); + } catch (error) { + const code = Number(error && error.code); + if (Number.isInteger(code) && code >= 400 && code < 600) { + const errorData = error && error.data && typeof error.data === 'object' && !Array.isArray(error.data) + ? error.data + : {}; + return this.fail(error.message || '查询失败', errorData, code); + } + + ctx.logger.error('[PickCartService.list] 查询拣货车列表失败: %s', error && error.message ? error.message : error); + return this.fail('查询失败', {}, 500); + } + } + + /** + * 拣货车编码查重。 + * + * @param {Object} data 请求参数。 + * @return {Promise} 统一 success/fail 包装结果。 + */ + async codeDuplicateCheck(data = {}) { + const { service, ctx } = this; + const cartCode = String(data && (data.cart_code || data.cartCode) || '').trim(); + const excludeCartId = Number(data && (data.exclude_cart_id || data.excludeCartId) || 0); + + if (!cartCode) { + return this.fail('cart_code 必填', {}, 400); + } + + try { + const result = await service.systems.pickCart.codeDuplicateCheck({ + cartCode, + excludeCartId, + }); + return this.success('ok', { + data: result, + code: 200, + }); + } catch (error) { + const code = Number(error && error.code); + if (Number.isInteger(code) && code >= 400 && code < 600) { + const errorData = error && error.data && typeof error.data === 'object' && !Array.isArray(error.data) + ? error.data + : {}; + return this.fail(error.message || '校验失败', errorData, code); + } + + ctx.logger.error('[PickCartService.codeDuplicateCheck] 拣货车编码查重失败: %s', error && error.message ? error.message : error); + return this.fail('校验失败', {}, 500); + } + } +} + +module.exports = PickCartService; diff --git a/app/service/systemMethods/print.js b/app/service/systemMethods/print.js index 5fb7b10..3c4c95b 100644 --- a/app/service/systemMethods/print.js +++ b/app/service/systemMethods/print.js @@ -255,6 +255,182 @@ class PrintService extends MainService { return Array.from(orderIdSet); } + /** + * 规范化快递打印平台编码,兼容常见别名。 + * @param {Object} payload 入参。 + * @param {string} payload.platformCode 原始平台编码。 + * @param {Object} [payload.payloadBuilder] 快递 payload 组装器。 + * @return {string} 规范化平台编码。 + */ + normalizeExpressPlatformCode(payload = {}) { + const normalizedPayload = payload && typeof payload === 'object' ? payload : {}; + const platformCode = String(normalizedPayload.platformCode || '').trim(); + const payloadBuilder = normalizedPayload.payloadBuilder; + if (payloadBuilder && typeof payloadBuilder.normalizePlatform === 'function') { + try { + const normalizedPlatformCode = String(payloadBuilder.normalizePlatform(platformCode) || '').trim().toLowerCase(); + if (normalizedPlatformCode) { + return normalizedPlatformCode; + } + } catch (error) { + this.ctx.logger.warn('[print.send] 平台编码归一化失败,回退本地策略', { + platformCode, + reason: error && error.message ? error.message : `${error}`, + }); + } + } + + const lowerPlatformCode = platformCode.toLowerCase(); + if ([ 'shipinhao', 'wechatvideo' ].includes(lowerPlatformCode)) { + return 'sph'; + } + if (lowerPlatformCode === 'ks') { + return 'kuaishou'; + } + return lowerPlatformCode; + } + + /** + * 按订单ID批量加载波次序号上下文,用于 SPH 发送阶段覆写 printNum。 + * 数据来源:wms_order_wave_index。 + * 查询失败时优雅降级为空映射,不阻断发送流程。 + * @param {Object} payload 入参。 + * @param {number|string} payload.warehouseId 仓库ID。 + * @param {Array} payload.orderIds 订单ID列表。 + * @return {Promise<{orderWaveIndexMap:Map,waveTotalOrdersMap:Map}>} 波次索引上下文。 + */ + async queryWavePrintNumContextForOrderIds(payload = {}) { + const normalizedPayload = payload && typeof payload === 'object' ? payload : {}; + const warehouseId = Number(normalizedPayload.warehouseId || 0); + const orderIds = this.normalizeOrderIds(normalizedPayload.orderIds); + const emptyResult = { + orderWaveIndexMap: new Map(), + waveTotalOrdersMap: new Map(), + }; + if (!Number.isInteger(warehouseId) || warehouseId <= 0 || orderIds.length === 0) { + return emptyResult; + } + + const orderPrintService = this.service && this.service.systems && this.service.systems.orderPrint; + if (!orderPrintService + || typeof orderPrintService.queryWaveOrderIndexMapByOrderIds !== 'function' + || typeof orderPrintService.queryWaveTotalOrderCountMap !== 'function') { + this.ctx.logger.warn('[print.send] SPH printNum 覆写依赖服务不可用,跳过波次索引查询', { + warehouseId, + orderIdsCount: orderIds.length, + }); + return emptyResult; + } + + try { + const orderWaveIndexMapResult = await orderPrintService.queryWaveOrderIndexMapByOrderIds(orderIds, warehouseId); + const orderWaveIndexMap = orderWaveIndexMapResult instanceof Map + ? orderWaveIndexMapResult + : new Map(); + const waveIds = Array.from(new Set(Array.from(orderWaveIndexMap.values()) + .map(item => Number(item && item.wave_id || 0)) + .filter(waveId => Number.isInteger(waveId) && waveId > 0))); + const waveTotalOrdersMapResult = await orderPrintService.queryWaveTotalOrderCountMap(waveIds, warehouseId); + const waveTotalOrdersMap = waveTotalOrdersMapResult instanceof Map + ? waveTotalOrdersMapResult + : new Map(); + return { + orderWaveIndexMap, + waveTotalOrdersMap, + }; + } catch (error) { + this.ctx.logger.warn('[print.send] SPH printNum 覆写波次索引查询失败,回退模板默认值', { + warehouseId, + orderIdsCount: orderIds.length, + reason: error && error.message ? error.message : `${error}`, + }); + return emptyResult; + } + } + + /** + * 将 SPH 发送任务中的 printNum 覆写为波次内序号与波次总单数。 + * @param {Object} payload 入参。 + * @param {Object} payload.requestPayload 待发送 payload。 + * @param {number|string} payload.orderId 当前订单ID。 + * @param {Map} payload.orderWaveIndexMap 订单波次索引映射。 + * @param {Map} payload.waveTotalOrdersMap 波次总单数映射。 + * @return {{applied:boolean,orderId:number,waveId:number,curNum:number,sumNum:number,reason:string}} 覆写结果。 + */ + applySphPrintNumByWaveIndex(payload = {}) { + const normalizedPayload = payload && typeof payload === 'object' ? payload : {}; + const requestPayload = normalizedPayload.requestPayload && typeof normalizedPayload.requestPayload === 'object' + ? normalizedPayload.requestPayload + : null; + const orderId = Number(normalizedPayload.orderId || 0); + const fallbackResult = { + applied: false, + orderId, + waveId: 0, + curNum: 0, + sumNum: 0, + reason: '', + }; + if (!requestPayload) { + return { + ...fallbackResult, + reason: 'requestPayload 非对象', + }; + } + + const taskList = Array.isArray(requestPayload.taskList) ? requestPayload.taskList : []; + const firstTask = taskList[0] && typeof taskList[0] === 'object' ? taskList[0] : null; + if (!firstTask) { + return { + ...fallbackResult, + reason: 'taskList[0] 不存在', + }; + } + if (!Number.isInteger(orderId) || orderId <= 0) { + return { + ...fallbackResult, + reason: 'orderId 非法', + }; + } + + const orderWaveIndexMap = normalizedPayload.orderWaveIndexMap instanceof Map + ? normalizedPayload.orderWaveIndexMap + : new Map(); + const waveTotalOrdersMap = normalizedPayload.waveTotalOrdersMap instanceof Map + ? normalizedPayload.waveTotalOrdersMap + : new Map(); + const waveOrderIndexInfo = orderWaveIndexMap.get(orderId); + const waveId = Number(waveOrderIndexInfo && waveOrderIndexInfo.wave_id || 0); + const curNum = Number(waveOrderIndexInfo && waveOrderIndexInfo.wave_index || 0); + const sumNum = Number(waveTotalOrdersMap.get(waveId) || 0); + if (!Number.isInteger(waveId) || waveId <= 0 || !Number.isInteger(curNum) || curNum <= 0 || !Number.isInteger(sumNum) || sumNum <= 0) { + return { + ...fallbackResult, + waveId, + curNum, + sumNum, + reason: '波次索引信息缺失', + }; + } + + const currentPrintNum = firstTask.printNum && typeof firstTask.printNum === 'object' && !Array.isArray(firstTask.printNum) + ? firstTask.printNum + : {}; + firstTask.printNum = { + ...currentPrintNum, + curNum, + sumNum, + }; + return { + applied: true, + orderId, + waveId, + curNum, + sumNum, + reason: '', + }; + } + /** * 从打印记录 data 中提取订单ID列表。 * 兼容 data 为对象或 JSON 字符串,无法识别时返回空数组。 @@ -2009,10 +2185,18 @@ class PrintService extends MainService { }; } - const normalizedPlatformCode = String(platformGroup && platformGroup.platform ? platformGroup.platform : '').trim().toLowerCase(); - const isKuaishouPlatform = normalizedPlatformCode === 'kuaishou' || normalizedPlatformCode === 'ks'; + const normalizedPlatformCode = this.normalizeExpressPlatformCode({ + platformCode: platformGroup && platformGroup.platform ? platformGroup.platform : '', + payloadBuilder: normalizedPayload.payloadBuilder, + }); + const isKuaishouPlatform = normalizedPlatformCode === 'kuaishou'; + const isSphPlatform = normalizedPlatformCode === 'sph'; const orderBatches = []; - if (isKuaishouPlatform) { + if (isSphPlatform) { + for (const order of orders) { + orderBatches.push([ order ]); + } + } else if (isKuaishouPlatform) { for (let index = 0; index < orders.length; index += 10) { orderBatches.push(orders.slice(index, index + 10)); } @@ -2020,6 +2204,23 @@ class PrintService extends MainService { orderBatches.push(orders); } const totalDocumentCount = orders.length; + let sphOrderWaveIndexMap = new Map(); + let sphWaveTotalOrdersMap = new Map(); + if (isSphPlatform) { + const platformOrderIds = this.collectOrderIdsFromPlatformGroup(platformGroup, orders); + const wavePrintNumContext = await this.queryWavePrintNumContextForOrderIds({ + warehouseId: normalizedPayload.warehouseId, + orderIds: platformOrderIds, + }); + sphOrderWaveIndexMap = wavePrintNumContext.orderWaveIndexMap; + sphWaveTotalOrdersMap = wavePrintNumContext.waveTotalOrdersMap; + this.ctx.logger.info('[print.send] SPH 波次索引上下文加载完成', { + ...groupSummary, + orderIdsCount: platformOrderIds.length, + orderWaveIndexCount: sphOrderWaveIndexMap.size, + waveCount: sphWaveTotalOrdersMap.size, + }); + } for (let batchIndex = 0; batchIndex < orderBatches.length; batchIndex++) { const batchOrders = orderBatches[batchIndex]; @@ -2045,12 +2246,44 @@ class PrintService extends MainService { requestPayload.task.totalDocumentCount = totalDocumentCount; } currentTaskCode = await this.reserveUniquePrintTaskCode(); - if (requestPayload.task && typeof requestPayload.task === 'object' && !Array.isArray(requestPayload.task)) { + if (isSphPlatform + && Array.isArray(requestPayload.taskList) + && requestPayload.taskList[0] + && typeof requestPayload.taskList[0] === 'object' + && !Array.isArray(requestPayload.taskList[0])) { + requestPayload.taskList[0].taskID = currentTaskCode; + } else if (requestPayload.task && typeof requestPayload.task === 'object' && !Array.isArray(requestPayload.task)) { requestPayload.task.taskID = currentTaskCode; } if (currentTaskCode && !generatedTaskCodes.includes(currentTaskCode)) { generatedTaskCodes.push(currentTaskCode); } + + if (isSphPlatform) { + const currentOrderId = Number(batchOrderIds[0] || 0); + const sphOverrideResult = this.applySphPrintNumByWaveIndex({ + requestPayload, + orderId: currentOrderId, + orderWaveIndexMap: sphOrderWaveIndexMap, + waveTotalOrdersMap: sphWaveTotalOrdersMap, + }); + if (sphOverrideResult.applied) { + this.ctx.logger.info('[print.send] SPH printNum 覆写成功', { + ...batchSummary, + orderId: sphOverrideResult.orderId, + waveId: sphOverrideResult.waveId, + curNum: sphOverrideResult.curNum, + sumNum: sphOverrideResult.sumNum, + }); + } else { + this.ctx.logger.info('[print.send] SPH printNum 覆写跳过,保持模板默认值', { + ...batchSummary, + orderId: sphOverrideResult.orderId, + reason: sphOverrideResult.reason, + }); + } + } + const payloadSummary = this.summarizeExpressPayload(requestPayload); this.ctx.logger.info('[print.send] 组装 payload 成功', { ...batchSummary, diff --git a/app/service/systemMethods/setting/expressInterface.js b/app/service/systemMethods/setting/expressInterface.js index 2f19a4f..914e658 100644 --- a/app/service/systemMethods/setting/expressInterface.js +++ b/app/service/systemMethods/setting/expressInterface.js @@ -157,6 +157,16 @@ class expressInterfaceService extends MainService { templateUrl: camelTemplateUrl, ext_data: extData, extData: camelExtData, + template_id: templateId, + templateId: camelTemplateId, + paymode, + payMode, + brandno, + brandNo, + providertype, + providerType, + providerid, + providerId, ...rest } = data || {}; @@ -197,6 +207,21 @@ class expressInterfaceService extends MainService { if (extData !== undefined || camelExtData !== undefined) { payload.ext_data = extData !== undefined ? extData : camelExtData; } + if (templateId !== undefined || camelTemplateId !== undefined) { + payload.template_id = templateId !== undefined ? templateId : camelTemplateId; + } + if (paymode !== undefined || payMode !== undefined) { + payload.paymode = paymode !== undefined ? paymode : payMode; + } + if (brandno !== undefined || brandNo !== undefined) { + payload.brandno = brandno !== undefined ? brandno : brandNo; + } + if (providertype !== undefined || providerType !== undefined) { + payload.providertype = providertype !== undefined ? providertype : providerType; + } + if (providerid !== undefined || providerId !== undefined) { + payload.providerid = providerid !== undefined ? providerid : providerId; + } return await this.callSystemExpressInterface('create', payload, '创建快递接口失败'); } @@ -234,6 +259,16 @@ class expressInterfaceService extends MainService { extData: camelExtData, platform_shop_id: platformShopId, platformShopId: camelPlatformShopId, + template_id: templateId, + templateId: camelTemplateId, + paymode, + payMode, + brandno, + brandNo, + providertype, + providerType, + providerid, + providerId, ...rest } = data || {}; @@ -278,6 +313,21 @@ class expressInterfaceService extends MainService { if (platformShopId !== undefined || camelPlatformShopId !== undefined) { payload.platform_shop_id = platformShopId !== undefined ? platformShopId : camelPlatformShopId; } + if (templateId !== undefined || camelTemplateId !== undefined) { + payload.template_id = templateId !== undefined ? templateId : camelTemplateId; + } + if (paymode !== undefined || payMode !== undefined) { + payload.paymode = paymode !== undefined ? paymode : payMode; + } + if (brandno !== undefined || brandNo !== undefined) { + payload.brandno = brandno !== undefined ? brandno : brandNo; + } + if (providertype !== undefined || providerType !== undefined) { + payload.providertype = providertype !== undefined ? providertype : providerType; + } + if (providerid !== undefined || providerId !== undefined) { + payload.providerid = providerid !== undefined ? providerid : providerId; + } return await this.callSystemExpressInterface('update', payload, '更新快递接口失败'); } diff --git a/app/service/systemMethods/storeWarehouse/store.js b/app/service/systemMethods/storeWarehouse/store.js index f908d90..3ce0b58 100644 --- a/app/service/systemMethods/storeWarehouse/store.js +++ b/app/service/systemMethods/storeWarehouse/store.js @@ -26,9 +26,9 @@ class StoreWarehouseStoreService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'list,sign,unbind,rename,getPolicyConfig,getPolicyConfigFields,savePolicyConfig,listApiConfig,saveApiConfig,deleteQimenConfig'; + const _noNeedRight = 'list,sign,unbind,rename,openAccount,getPolicyConfig,getPolicyConfigFields,savePolicyConfig,listApiConfig,saveApiConfig,deleteQimenConfig'; const _noNeedLog = '*'; - const _noNeedAuth = 'list,sign,unbind,rename,getPolicyConfig,getPolicyConfigFields,savePolicyConfig,listApiConfig,saveApiConfig,deleteQimenConfig'; + const _noNeedAuth = 'list,sign,unbind,rename,openAccount,getPolicyConfig,getPolicyConfigFields,savePolicyConfig,listApiConfig,saveApiConfig,deleteQimenConfig'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -367,6 +367,32 @@ class StoreWarehouseStoreService extends MainService { }); } } + + /** + * 仓库代货主一键开户。 + * + * @param {Object} data 请求数据。 + * @return {Promise} 统一响应结果。 + */ + async openAccount(data = {}) { + const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse; + + if (!targetService || typeof targetService.openAccount !== 'function') { + return this.fail('一键开户失败', { + code: 500, + }); + } + + try { + const payload = normalizeStoreWarehousePayload(data); + const result = await targetService.openAccount(payload); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '一键开户失败', { + code: Number(error.code) || 500, + }); + } + } } module.exports = StoreWarehouseStoreService; diff --git a/app/service/systems/auth/user.js b/app/service/systems/auth/user.js index 27a3efa..f6476ce 100644 --- a/app/service/systems/auth/user.js +++ b/app/service/systems/auth/user.js @@ -2365,9 +2365,10 @@ class UserService extends Service { /** * 用户注册(重构版) - * @param {Object} userInfo 用户信息 + * @param {Object} userInfo 用户信息 + * @param {Object|null} transaction 可选事务对象,传入时 Account.create 将在事务内执行 */ - async register(userInfo) { + async register(userInfo, transaction = null) { const { ctx } = this; // 检查用户名是否已存在 @@ -2390,7 +2391,7 @@ class UserService extends Service { real_name: userInfo.real_name || '', status: 1, salt, - }); + }, transaction ? { transaction } : {}); return { userId: user.id, diff --git a/app/service/systems/delivery_order.js b/app/service/systems/delivery_order.js index 1409d99..0c94204 100644 --- a/app/service/systems/delivery_order.js +++ b/app/service/systems/delivery_order.js @@ -663,6 +663,9 @@ class DeliveryOrderService extends Service { { prepend: true } ); + // 将建单渠道注入 info,供 addOrderLines 区分 MANUAL 降级逻辑 + info.createChannel = normalizedCreateChannel; + let itemsInfo = null; // 添加订单明细 if (orderLines && (orderLines.orderLine)) { @@ -1072,7 +1075,7 @@ class DeliveryOrderService extends Service { */ async addOrderLines(orderLines, orderId, info, transaction) { const { ctx, app } = this; - const { warehouseId, appKey, storeId } = info; + const { warehouseId, appKey, storeId, createChannel } = info; let order_items = []; if (orderLines && typeof orderLines === 'object') { @@ -1129,16 +1132,33 @@ class DeliveryOrderService extends Service { } else { wms_stock = await app.model.StockStore.findByPk(line.itemId, { transaction }); } - // 如果没有itemId,直接记录错误 - if (!wms_stock) { + + // MANUAL 渠道降级:信任调用方提供的 itemId,跳过 StockStore 校验 + const isManualFallback = createChannel === 'MANUAL' && line.itemId && !wms_stock; + + if (!wms_stock && !isManualFallback) { errors.push(`商品《${line.itemName}》编码《${line.itemCode}》\n未同步推送到仓库`); continue; } + if (isManualFallback) { + // 手工建单降级模式:使用调用方传入的 itemId,stockId 置 0,跳过库存锁定 + wms_stock = { + id: line.itemId, + stock_id: 0, + item_name: line.itemName || '', + item_code: line.itemCode || '', + gross_weight: 0, + }; + } + const itemId = parseInt(wms_stock.id); const stockId = Number(wms_stock.stock_id) || 0; // ========== 核心库存检查逻辑 ========== - if (!stockId) { + // MANUAL 降级时 stockId 为 0,跳过库存记录检查与锁定 + const isManualNoStock = isManualFallback && !stockId; + + if (!stockId && !isManualNoStock) { errors.push(`第${i + 1}行: 商品《${wms_stock.item_name}》库存记录不存在`); continue; } @@ -1149,24 +1169,28 @@ class DeliveryOrderService extends Service { } processedItemIds.add(itemId); - // 锁定库存 - const lockResult = await ctx.service.systems.stockStore.lockItemStorages( - stockId, - planQty, - transaction - ); + // 锁定库存(MANUAL 降级时跳过) + if (!isManualNoStock) { + const lockResult = await ctx.service.systems.stockStore.lockItemStorages( + stockId, + planQty, + transaction + ); - if (!lockResult.success) { - errors.push(`SKU${wms_stock.id}商品《${wms_stock.item_name}》编码《${wms_stock.item_code}》\n锁定失败: ${lockResult.error}`); - continue; + if (!lockResult.success) { + errors.push(`SKU${wms_stock.id}商品《${wms_stock.item_name}》编码《${wms_stock.item_code}》\n锁定失败: ${lockResult.error}`); + continue; + } + + const totalQtyForStock = (stockQuantityMap.get(stockId) || 0) + planQty; + stockQuantityMap.set(stockId, totalQtyForStock); } - const totalQtyForStock = (stockQuantityMap.get(stockId) || 0) + planQty; - stockQuantityMap.set(stockId, totalQtyForStock); - - // 优先使用商品主数据重量,缺失时降级为0。 - const weight = parseFloat(wms_stock.gross_weight) || 0; - stockWeightMap.set(stockId, weight); + // 优先使用商品主数据重量,缺失时降级为0;MANUAL 降级时重量为 0 + const weight = isManualNoStock ? 0 : (parseFloat(wms_stock.gross_weight) || 0); + if (!isManualNoStock) { + stockWeightMap.set(stockId, weight); + } // ========== 库存检查逻辑结束 ========== // 所有检查通过,准备订单行数据 diff --git a/app/service/systems/express.js b/app/service/systems/express.js index 9e68ed8..faec8a3 100644 --- a/app/service/systems/express.js +++ b/app/service/systems/express.js @@ -56,6 +56,8 @@ const WAYBILL_ORDER_DELIVERY_MIN_ATTRIBUTES = Object.freeze([ 'oaid', 'source_order_codes', 'logistics_code', + 'extend_props', + 'buyer_nick', ]); class ExpressService extends Service { @@ -1510,7 +1512,10 @@ class ExpressService extends Service { continue; } - platformCodeByPrintPlatformIdMap.set(printPlatformId, platformCode); + if (!platformCodeByPrintPlatformIdMap.has(printPlatformId)) { + platformCodeByPrintPlatformIdMap.set(printPlatformId, []); + } + platformCodeByPrintPlatformIdMap.get(printPlatformId).push(platformCode); } if (!printPlatformModel || typeof printPlatformModel.findAll !== 'function' || platformCodeByPrintPlatformIdMap.size <= 0) { @@ -1535,12 +1540,14 @@ class ExpressService extends Service { continue; } - const systemPlatformCode = platformCodeByPrintPlatformIdMap.get(printPlatformId); - if (!systemPlatformCode) { + const systemPlatformCodes = platformCodeByPrintPlatformIdMap.get(printPlatformId); + if (!Array.isArray(systemPlatformCodes) || systemPlatformCodes.length === 0) { continue; } - printPlatformCodeMap.set(systemPlatformCode, platformCode); + for (const systemPlatformCode of systemPlatformCodes) { + printPlatformCodeMap.set(systemPlatformCode, platformCode); + } } return printPlatformCodeMap; @@ -1569,7 +1576,10 @@ class ExpressService extends Service { continue; } - platformCodeByPrintPlatformIdMap.set(printPlatformId, platformCode); + if (!platformCodeByPrintPlatformIdMap.has(printPlatformId)) { + platformCodeByPrintPlatformIdMap.set(printPlatformId, []); + } + platformCodeByPrintPlatformIdMap.get(printPlatformId).push(platformCode); } if (!printPlatformModel || typeof printPlatformModel.findAll !== 'function' || platformCodeByPrintPlatformIdMap.size <= 0) { @@ -1594,12 +1604,14 @@ class ExpressService extends Service { continue; } - const systemPlatformCode = platformCodeByPrintPlatformIdMap.get(printPlatformId); - if (!systemPlatformCode) { + const systemPlatformCodes = platformCodeByPrintPlatformIdMap.get(printPlatformId); + if (!Array.isArray(systemPlatformCodes) || systemPlatformCodes.length === 0) { continue; } - requestPlatformCodeMap.set(systemPlatformCode, requestPlatformCode); + for (const systemPlatformCode of systemPlatformCodes) { + requestPlatformCodeMap.set(systemPlatformCode, requestPlatformCode); + } } return requestPlatformCodeMap; @@ -1640,6 +1652,15 @@ class ExpressService extends Service { ? this.normalizeWaybillPrintPlatformCode(printPlatformCodeMap.get(normalizedSysPlatformCode)) : ''; + this.ctx.logger.info('[ExpressService.resolveWaybillGroupPrintPlatformCode] 映射查找', { + sysPlatformCode, + normalizedSysPlatformCode, + mapSize: printPlatformCodeMap instanceof Map ? printPlatformCodeMap.size : 'not-a-map', + mapKeys: printPlatformCodeMap instanceof Map ? JSON.stringify(Array.from(printPlatformCodeMap.keys())) : 'N/A', + mappedValue: printPlatformCodeMap instanceof Map ? printPlatformCodeMap.get(normalizedSysPlatformCode) : 'N/A', + finalResult: mappedPrintPlatformCode || '(空)', + }); + return mappedPrintPlatformCode; } @@ -1665,6 +1686,13 @@ class ExpressService extends Service { const logisticsCode = String(order.logistics_code || '').trim(); const printPlatformCode = this.resolveWaybillGroupPrintPlatformCode(sysPlatformCode, printPlatformCodeMap); if (!sysPlatformCode || !logisticsCode || !printPlatformCode) { + this.ctx.logger.warn('[ExpressService.groupWaybillOrdersByPlatformAndLogistics] 订单分组被跳过', { + orderId: order.id, + sysPlatformCode: sysPlatformCode || '(空)', + logisticsCode: logisticsCode || '(空)', + printPlatformCode: printPlatformCode || '(空)', + reason: !sysPlatformCode ? 'sysPlatformCode为空' : !logisticsCode ? 'logisticsCode为空' : 'printPlatformCode映射失败', + }); continue; } diff --git a/app/service/systems/express_platform.js b/app/service/systems/express_platform.js index f89a55e..e94e7e4 100644 --- a/app/service/systems/express_platform.js +++ b/app/service/systems/express_platform.js @@ -430,21 +430,26 @@ class ExpressPlatformService extends MainService { api: 'Differ.JH.LogisticsPlatFeatures', response: Dictionary_result, }); - console.log("listByWarehousePlatformCode",listByWarehousePlatformCode) + console.log('listByWarehousePlatformCode', listByWarehousePlatformCode); const order_bizcontent = { orders: orders.map(order_tmp => { const order = order_tmp.order_delivery; - return { + const expressListItem = ExpressList.find(item => item.code === listByWarehousePlatformCode.sys_express_code) || {}; + let playload = { + object_Id: `${order.warehouse_id}_${order.id}_${order_tmp.business_key}`, // 菠萝派平台要求订单唯一标识必须为字符串 orderno: `${order.warehouse_id}_${order.id}_${order_tmp.business_key}`, // 菠萝派平台要求订单号必须为字符串 plattradeno: order.source_order_codes || order.delivery_order_code || '', ismultiplepieces: order.package_count > 1 ? 1 : 0, logisticno: allocatedWaybillMap.get(`${Number(order.id) || 0}:${Number(order_tmp.business_key) || 0}`) || '', logistictype: order.logistics_code || '', + providercode: expressListItem[listByWarehousePlatformCode.platform_code] || order.logistics_code || '', numpackage: order.package_count || 1, - businesstype: 'JH_Normal', + businessType: listByWarehousePlatformCode.product_type, businessplat: order.sys_platform_code === 'KS' ? order.sys_platform_code : 'OTHERS', paymode: listByWarehousePlatformCode.paymode ?? 1, ordertype: listByWarehousePlatformCode.ordertype ?? 'JH_Normal', + ProviderID: listByWarehousePlatformCode.providerid ?? '', + procode: order.procode || '普通商品', codpaymoney: order.ar_amount ?? null, packagemoney: order.item_amount ?? null, weight: Number(order.items_weight) || 0, @@ -454,13 +459,15 @@ class ExpressPlatformService extends MainService { height: Number(order.height) || 0, volume: Number(order.volume) || 0, ispickup: listByWarehousePlatformCode.ispickup ?? 0, - producttype: listByWarehousePlatformCode.product_type || '', + ProductType: listByWarehousePlatformCode.product_type || '', Sipshopid: listByWarehousePlatformCode.platform_shop_id || '', + oaid: order.oaid || '', sys_express_code: listByWarehousePlatformCode.sys_express_code || '', platform_code: listByWarehousePlatformCode.platform_code || '', - cpcode: ExpressList.find(item => item.code === listByWarehousePlatformCode.sys_express_code)[listByWarehousePlatformCode.platform_code] || '', + cpcode: expressListItem[listByWarehousePlatformCode.platform_code] || '', logisticsproductname: 'JH_02', dmssorting: 0, + brandno: listByWarehousePlatformCode.brandno || null, needencrypt: 1, ordersource: matchedPlatform.ordersource || '', inputsite: listByWarehousePlatformCode.site_code || '', @@ -470,7 +477,6 @@ class ExpressPlatformService extends MainService { company: listByWarehousePlatformCode.shop_name || '', name: listByWarehousePlatformCode.sender_name || '', phone: listByWarehousePlatformCode.sender_tel || '', - mobile: listByWarehousePlatformCode.sender_tel || '', country: 'CN', city: listByWarehousePlatformCode.city_name || '', province: listByWarehousePlatformCode.province_name || '', @@ -499,14 +505,130 @@ class ExpressPlatformService extends MainService { count: item.plan_qty || 0, }))) || [], Mallmaskid: '', - - template_url: matchedPlatform.template_url || '', + + template_url: listByWarehousePlatformCode.template_id || '', labelformat: listByWarehousePlatformCode.labelformat || '', extraInfo: ExpressList.find(item => item.code === listByWarehousePlatformCode.sys_express_code)?.polyapi_extra_info || '', }; + if (Number(matchedPlatform.platid) === 673) { + playload.BizVersion = '2'; + playload.brandno = listByWarehousePlatformCode.brandno || ''; + } + if (Number(matchedPlatform.platid) === 544) { + const { + orderno, + plattradeno, + logistictype, + ProductType, + providercode, + numpackage, + businessplat, + paymode, + ordertype, + businessType, + codpaymoney, + ProviderID, + cpcode, + logisticsproductname, + needencrypt, + ordersource, + shipperno, + sitecode, + goods, + sender = {}, + receiver = {}, + } = playload; + const { + name: senderNameRaw, + company: senderCompanyRaw, + phone: senderPhoneRaw, + mobile: senderMobileRaw, + country, + city: senderCity, + province: senderProvince, + address: senderAddress, + } = sender; + const { + name, + phone, + mobile, + province: receiverProvince, + city: receiverCity, + address: receiverAddress, + } = receiver; + const senderName = senderNameRaw || listByWarehousePlatformCode.sender_name || listByWarehousePlatformCode.shop_name || ''; + const senderCompany = senderCompanyRaw || listByWarehousePlatformCode.shop_name || ''; + const customername = senderNameRaw || senderCompanyRaw || listByWarehousePlatformCode.shop_name || '测试'; + + playload = { + orderno, + plattradeno, + ProductType, + expresstype: ProductType, + logistictype, + providercode: providercode || cpcode || logistictype || '', + numpackage, + businessplat, + mainsubpaymode: '1', + ordertype, + businessType: businessType || ordertype || 'JH_Normal', + codpaymoney, + ProviderID, + cpcode, + logisticsproductname, + needencrypt, + ordersource, + shipperno, + sitecode, + customername, + goods, + sender: { + name: senderName, + phone: senderPhoneRaw, + mobile: senderMobileRaw, + company: senderCompany, + country, + city: senderCity, + province: senderProvince, + address: senderAddress, + }, + receiver: { + name, + phone, + province: receiverProvince, + city: receiverCity, + address: receiverAddress, + }, + }; + console.log('playload.providercode', playload.providercode); + if (playload.providercode === 'SF') { + playload.expressPayMethod = '1'; + } else { + playload.paymode = '1'; + playload.codpaymoney = ''; + } + } + if(matchedPlatform.platid ===672){ + if(!order.source_order_codes){ + throw new Error('订单数据错误,缺失平台订单号'); + } + playload.object_Id = order.source_order_codes.split(",")[0]; + if(!order.extend_props.ewaybill_order_code){ + throw new Error('订单数据错误,参数不全缺失extend_props.ewaybill_order_code,请复制次信息给ERP方反馈'); + } + playload.oaid = order.extend_props.ewaybill_order_code; + playload.transtype = "0"; + playload.Mallmaskid = order.buyer_nick; + playload.mainsubpaymode = "1"; + delete playload.plattradeno; + } + playload.ProviderID = listByWarehousePlatformCode.providerid; + console.log('playload', playload); + return playload; }), shoptype: matchedPlatform.shoptype, }; + // 调用菠萝派平台接口进行数据处理 this.ctx.logger.info('[expressPlatform.polyapi] PolyAPI 分配快递号接口调用前', { traceId, @@ -519,7 +641,7 @@ class ExpressPlatformService extends MainService { this.ctx.logger.info('[expressPlatform.polyapi] PolyAPI 分配快递号接口调用后', { traceId, api: 'Differ.JH.Logistics.PostOrder', - response: result, + response: JSON.stringify(result), }); if (result && result.code !== '10000') { this.ctx.logger.error('[expressPlatform.polyapi] PolyAPI 返回业务失败', { @@ -555,7 +677,7 @@ class ExpressPlatformService extends MainService { logistics_interface_name: listByWarehousePlatformCode.name || '', platform_code: listByWarehousePlatformCode.platform_code || '', status: 1, - + retry_count: 0, }, orderDeliveryValues: { @@ -596,9 +718,218 @@ class ExpressPlatformService extends MainService { }; }); break; - case 'JD': - case 'XHS': - case 'SPH': + case 'JD':{ + const batchPrintSipshopid = String(listByWarehousePlatformCode.platform_shop_id || '0'); + const batchPrintOrders = (result.results || []).map(item => ({ + orderno: String(item.orderno || ''), + logisticno: String(item.logisticno || item.waybill_code || ''), + outputformat: 'JH_PDF', + labelformat: 'JH_A4', + printobjecttype: 'JH_Label', + numpackage: '1', + countrycode: '', + logisticsid: '', + orderitemno: '', + sendername: '', + sendercompany: '', + senderprovince: '', + sendercity: '', + senderarea: '', + senderaddress: '', + sendertel: '', + receivername: '', + receivercompany: '', + receiverprovince: '', + receivercity: '', + receiverarea: '', + receiveraddress: '', + receivertel: '', + cargoname: '', + senddata: '', + weight: '', + remark: '', + carrier: batchPrintSipshopid, + selleruserid: '', + printno: '', + iscloudprint: 'false', + needprintdetail: 'false', + extenddata: '', + providercode: String(item.procode || item.realcpcode || item.logisticcompanycode || ''), + packageno: '', + fontsize: '', + platorderno: String(item.plattradeno || item.platorderno || item.orderno || ''), + sipshopid: batchPrintSipshopid, + })); + console.log('京东批量打印请求参数', JSON.stringify({ + api: 'Differ.JH.Logistics.BatchPrintOrder', + orders: batchPrintOrders, + })); + const batchPrintPlatform = { + ...matchedPlatform, + platid: 611, + interface_url: 'https://apijd.polyapi.com/OpenAPI/do', + }; + const batchPrintResult = await this.service.systems.poloApi.request( + 'Differ.JH.Logistics.BatchPrintOrder', + { orders: batchPrintOrders }, + batchPrintPlatform, + listByWarehousePlatformCode.token + ); + console.log('京东批量打印返回结果', JSON.stringify(batchPrintResult)); + if (String(batchPrintResult && batchPrintResult.code || '') !== '10000') { + const errorMessage = String( + batchPrintResult && (batchPrintResult.submessage || batchPrintResult.message) + || '京东批量打印接口调用失败' + ).trim(); + throw new Error(errorMessage); + } + + successUpdates = (batchPrintResult && batchPrintResult.results || []).map(item => { + const objectId = String(item && item.orderno || '').trim(); + const [ warehouse_id, order_id, business_key ] = objectId.split('_'); + const waybillCode = String(item && (item.logisticno || item.waybill_code) || '').trim(); + const rawPrintData = item && Object.prototype.hasOwnProperty.call(item, 'printdata') + ? item.printdata + : item && Object.prototype.hasOwnProperty.call(item, 'htmldata') + ? item.htmldata + : item && Object.prototype.hasOwnProperty.call(item, 'urldata') + ? item.urldata + : item && Object.prototype.hasOwnProperty.call(item, 'batchprintdata') + ? item.batchprintdata + : null; + const printinfo = this.stringifyPlatformPrintData(rawPrintData, rawPrintData) + || JSON.stringify(item); + const signature = String(item && item.signature || '').trim() || null; + const encryptprintinfo = String(item && item.encryptprintinfo || '').trim() || null; + const encryptedtoken = String(item && item.encryptedtoken || '').trim() || null; + + return { + warehouse_id, + order_id, + business_key, + waybill_code: waybillCode, + orderExpressValues: { + waybill_code: waybillCode, + printinfo, + signature, + encryptprintinfo, + encryptedtoken, + ...this.buildOrderExpressVerPatch([ item && item.ver ]), + 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; + } + case 'XHS':{ + successUpdates = (result.results || []).map(item => { + const [ warehouse_id, order_id, business_key ] = String(item.orderno || '').split('_'); + const waybillCode = resolveWaybillCode(item); + const printInfo = item.print_info ?? item.printinfo; + return { + warehouse_id, + order_id, + business_key, + waybill_code: waybillCode, + orderExpressValues: { + waybill_code: waybillCode, + printinfo: printInfo, + signature: item.signature, + encryptedtoken: item.encryptedtoken, + encryptprintinfo: item.encryptprintinfo, + ...this.buildOrderExpressVerPatch([ item.ver ]), + 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; + } + case 'SPH':{ + successUpdates = (result.results || []).map(item => { + const objectId = String(item && (item.object_id || item.object_Id || item.orderno) || '').trim(); + const objectIdParts = objectId.split('_'); + if (!objectId || objectIdParts.length < 3) { + throw new Error(`视频号取号返回 object_id 无法解析: ${objectId || JSON.stringify(item)}`); + } + const [ warehouse_id, order_id, business_key ] = objectIdParts; + const waybillCode = resolveWaybillCode(item); + const rawPrintData = item && Object.prototype.hasOwnProperty.call(item, 'raw') + ? item.raw + : null; + const printinfo = this.stringifyPlatformPrintData(item && item.printinfo, item && item.printinfo) + || this.stringifyPlatformPrintData(rawPrintData, rawPrintData) + || null; + const signature = item && Object.prototype.hasOwnProperty.call(item, 'signature') + ? item.signature + : rawPrintData && typeof rawPrintData === 'object' && Object.prototype.hasOwnProperty.call(rawPrintData, 'signature') + ? rawPrintData.signature + : undefined; + const encryptprintinfo = item && Object.prototype.hasOwnProperty.call(item, 'encryptprintinfo') + ? item.encryptprintinfo + : rawPrintData && typeof rawPrintData === 'object' && Object.prototype.hasOwnProperty.call(rawPrintData, 'encryptprintinfo') + ? rawPrintData.encryptprintinfo + : undefined; + const encryptedtoken = item && Object.prototype.hasOwnProperty.call(item, 'encryptedtoken') + ? item.encryptedtoken + : rawPrintData && typeof rawPrintData === 'object' && Object.prototype.hasOwnProperty.call(rawPrintData, 'encryptedtoken') + ? rawPrintData.encryptedtoken + : undefined; + const ver = item && Object.prototype.hasOwnProperty.call(item, 'ver') + ? item.ver + : rawPrintData && typeof rawPrintData === 'object' && Object.prototype.hasOwnProperty.call(rawPrintData, 'ver') + ? rawPrintData.ver + : undefined; + return { + warehouse_id, + order_id, + business_key, + waybill_code: waybillCode, + orderExpressValues: { + waybill_code: waybillCode, + printinfo, + signature, + encryptprintinfo, + encryptedtoken, + ...this.buildOrderExpressVerPatch([ ver ]), + 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; + } case 'PDD': successUpdates = (result.results || []).map(item => { const [ warehouse_id, order_id, business_key ] = String(item.orderno || '').split('_'); @@ -875,8 +1206,8 @@ class ExpressPlatformService extends MainService { const appKey = String(qimenConfig.appKey || '').trim(); const appSecret = String(qimenConfig.security || '').trim(); const signService = this.service && this.service.systems ? this.service.systems.sign : null; - const normalizedTemplateUrl = isValidCainiaoTemplateUrl(matchedPlatform.template_url) - ? String(matchedPlatform.template_url).trim() + const normalizedTemplateUrl = isValidCainiaoTemplateUrl(listByWarehousePlatformCode.template_url) + ? String(listByWarehousePlatformCode.template_url).trim() : DEFAULT_CAINIAO_TEMPLATE_URL; if (!appKey || !appSecret) { throw new Error('淘宝接口配置缺失'); @@ -914,7 +1245,7 @@ class ExpressPlatformService extends MainService { }, package_info: { items: (orderDelivery && orderDelivery.orderItems || []).map(item => ({ - name: item.item_name, + name: item.item_name || '商品', count: item.plan_qty, })) || [], goods_description: '物品', @@ -934,6 +1265,7 @@ class ExpressPlatformService extends MainService { oaid: orderDelivery && orderDelivery.oaid || '', tid: sourceOrderCodes[0] || '', }, + oaid: orderDelivery && orderDelivery.oaid || '', user_id: listByWarehousePlatformCode.shop && listByWarehousePlatformCode.shop.owner_id || 0, notify_extend_info: normalizedExtData, }; @@ -1426,7 +1758,7 @@ class ExpressPlatformService extends MainService { }, package_info: { items: (order_tmp.order_delivery && order_tmp.order_delivery.orderItems || []).map(item => ({ - name: item.item_name, + name: item.item_name || '商品', count: item.plan_qty, })) || [], }, @@ -1443,7 +1775,7 @@ class ExpressPlatformService extends MainService { name: order_tmp.order_delivery && order_tmp.order_delivery.name || '', phone: order_tmp.order_delivery && (order_tmp.order_delivery.mobile || order_tmp.order_delivery.tel) || '', }, - template_url: matchedPlatform.template_url || '', + template_url: listByWarehousePlatformCode.template_url || '', user_id: listByWarehousePlatformCode.shop.owner_id || 0, }; } diff --git a/app/service/systems/order_async.js b/app/service/systems/order_async.js index 11a8b14..3c562cb 100644 --- a/app/service/systems/order_async.js +++ b/app/service/systems/order_async.js @@ -765,6 +765,39 @@ async function finalizeLocalChannelOrdersInternal(service, createChannel, groupe const failedCount = syncResults.filter(item => item.status === 'failed').length; const overallSuccess = failedCount === 0 && successCount === syncResults.length; + // 同步成功后触发 OpenAPI 回调通知(fire-and-forget,不阻塞主流程) + if (createChannel === CREATE_CHANNEL_API && successCount > 0) { + try { + const callbackService = service.ctx.service.openapi && service.ctx.service.openapi.callback; + + if (callbackService && typeof callbackService.sendByAppKey === 'function') { + const appKey = String(context.appKey || '').trim(); + + if (appKey) { + callbackService.sendByAppKey({ + appKey, + event: 'order_completed', + data: { + orderIds, + status: 'completed', + successCount, + failedCount, + }, + metadata: { + warehouseId, + createChannel, + syncTarget, + }, + }).catch(err => { + service.ctx.logger.warn(`[OrderAsyncService] OpenAPI 回调忽略失败: ${err.message}`); + }); + } + } + } catch (err) { + service.ctx.logger.warn(`[OrderAsyncService] 触发回调异常,不影响主流程: ${err.message}`); + } + } + return { create_channel: createChannel, order_ids: orderIds, diff --git a/app/service/systems/order_export.js b/app/service/systems/order_export.js index 0ab5d2e..600332f 100644 --- a/app/service/systems/order_export.js +++ b/app/service/systems/order_export.js @@ -47,6 +47,7 @@ const ORDER_EXPORT_COLUMNS = Object.freeze([ { header: '发货时间', key: 'delivery_time', width: 20 }, { header: '出库状态', key: 'outbound_status', width: 14 }, { header: '复核状态', key: 'inspection_status', width: 14 }, + { header: '复核完成状态', key: 'recheck_status', width: 16 }, { header: '配货状态', key: 'post_status', width: 14 }, { header: '打包状态', key: 'pack_status', width: 14 }, { header: '归档时间', key: 'archive_time', width: 20 }, @@ -257,6 +258,7 @@ class OrderExportService extends OrderBaseService { delivery_time: this.normalizeExportCellValue(safeOrderRow.delivery_time), outbound_status: this.normalizeExportCellValue(safeOrderRow.outbound_status), inspection_status: this.normalizeExportCellValue(safeOrderRow.inspection_status), + recheck_status: this.normalizeExportCellValue(safeOrderRow.recheck_status), post_status: this.normalizeExportCellValue(safeOrderRow.post_status), pack_status: this.normalizeExportCellValue(safeOrderRow.pack_status), archive_time: this.normalizeExportCellValue(safeOrderRow.archive_time), diff --git a/app/service/systems/order_print.js b/app/service/systems/order_print.js index 4422a58..ecbdee7 100644 --- a/app/service/systems/order_print.js +++ b/app/service/systems/order_print.js @@ -526,11 +526,21 @@ class OrderPrintSystemService extends OrderBaseService { .filter(orderId => Number.isInteger(orderId) && orderId > 0); const orderExpressRows = await this.queryOrderExpressByOrderIds(orderIds); this.assertBusinessWaybillCompleteness(orderIds, orderExpressRows); - const enrichedOrderExpressRows = await this.enrichCainiaoOrderExpressRows( + const cainiaoEnrichedOrderExpressRows = await this.enrichCainiaoOrderExpressRows( unlockedOrderRows, orderExpressRows, normalizedWarehouseId ); + const jdEnrichedOrderExpressRows = await this.enrichJdOrderExpressRows( + unlockedOrderRows, + cainiaoEnrichedOrderExpressRows, + normalizedWarehouseId + ); + const enrichedOrderExpressRows = await this.enrichPddDyOrderExpressRows( + unlockedOrderRows, + jdEnrichedOrderExpressRows, + normalizedWarehouseId + ); const orderExpressMap = this.buildOrderExpressMap(enrichedOrderExpressRows); const policyConfigMap = await this.getPolicyConfigMapByStore(unlockedOrderRows, normalizedWarehouseId); const pickingCandidateRows = unlockedOrderRows.filter(orderRow => { @@ -1103,6 +1113,15 @@ class OrderPrintSystemService extends OrderBaseService { * @param {Array} orderIds 订单ID数组。 * @return {Promise>} 快递单信息列表。 */ + /** + * 根据订单 ID 列表批量查询运单记录。 + * 返回 business_key=1 的主运单,按 order_id、business_key、id 升序排列。 + * + * @param {number[]} orderIds 订单 ID 列表。 + * @returns {Promise>} 匹配的运单记录数组,字段包含 id、order_id、business_key、waybill_code、 + * logistics_code、logistics_name、logistics_interface_id、logistics_interface_name、platform_code、 + * warehouse_id、printinfo、signature、encryptprintinfo、ver。 + */ async queryOrderExpressByOrderIds(orderIds = []) { if (!Array.isArray(orderIds) || orderIds.length === 0) { return []; @@ -1123,6 +1142,7 @@ class OrderPrintSystemService extends OrderBaseService { 'waybill_code', 'logistics_code', 'logistics_name', + 'logistics_interface_id', 'logistics_interface_name', 'platform_code', 'warehouse_id', @@ -1352,6 +1372,36 @@ ${waveFilterSql} return PrinterDataBuilder.normalizePlatformAlias(platformCode).platform === 'cainiao'; } + /** + * 判断平台编码是否归一化为京东。 + * + * @param {string} platformCode 平台编码。 + * @return {boolean} 是否为京东平台。 + */ + isJdPlatformCode(platformCode = '') { + return PrinterDataBuilder.normalizePlatformAlias(platformCode).platform === 'jd'; + } + + /** + * 判断平台编码是否归一化为拼多多。 + * + * @param {string} platformCode 平台编码。 + * @return {boolean} 是否为拼多多平台。 + */ + isPddPlatformCode(platformCode = '') { + return PrinterDataBuilder.normalizePlatformAlias(platformCode).platform === 'pdd'; + } + + /** + * 判断平台编码是否归一化为抖音。 + * + * @param {string} platformCode 平台编码。 + * @return {boolean} 是否为抖音平台。 + */ + isDouyinPlatformCode(platformCode = '') { + return PrinterDataBuilder.normalizePlatformAlias(platformCode).platform === 'douyin'; + } + /** * 收集菜鸟编码映射可能命中的快递编码候选项。 * @@ -1443,6 +1493,87 @@ ${waveFilterSql} return Array.isArray(result && result.data) ? result.data : []; } + /** + * 读取仓库下京东平台的快递接口表配置列表。 + * + * @param {number} warehouseId 仓库ID。 + * @return {Promise>} 接口配置列表。 + */ + async queryJdExpressInterfaceList(warehouseId) { + const expressInterfaceService = this.service + && this.service.systems + && this.service.systems.setting + && this.service.systems.setting.expressInterface; + + if (!expressInterfaceService || typeof expressInterfaceService.listByWarehousePlatformCode !== 'function') { + return []; + } + + const result = await expressInterfaceService.listByWarehousePlatformCode({ + warehouseId, + platformCode: 'JD', + }); + + return Array.isArray(result && result.data) ? result.data : []; + } + + /** + * 读取仓库下拼多多平台的快递接口表配置列表。 + * + * @param {number} warehouseId 仓库ID。 + * @return {Promise>} 接口配置列表。 + */ + async queryPddExpressInterfaceList(warehouseId) { + const expressInterfaceService = this.service + && this.service.systems + && this.service.systems.setting + && this.service.systems.setting.expressInterface; + + if (!expressInterfaceService || typeof expressInterfaceService.listByWarehousePlatformCode !== 'function') { + return []; + } + + const result = await expressInterfaceService.listByWarehousePlatformCode({ + warehouseId, + platformCode: 'PDD', + }); + + return Array.isArray(result && result.data) ? result.data : []; + } + + /** + * 读取仓库下抖音平台的快递接口表配置列表。 + * + * @param {number} warehouseId 仓库ID。 + * @return {Promise>} 接口配置列表。 + */ + async queryDouyinExpressInterfaceList(warehouseId) { + const expressInterfaceService = this.service + && this.service.systems + && this.service.systems.setting + && this.service.systems.setting.expressInterface; + + if (!expressInterfaceService || typeof expressInterfaceService.listByWarehousePlatformCode !== 'function') { + return []; + } + + const result = await expressInterfaceService.listByWarehousePlatformCode({ + warehouseId, + platformCode: 'DY', + }); + const dyList = Array.isArray(result && result.data) ? result.data : []; + if (dyList.length > 0) { + return dyList; + } + + const fallbackResult = await expressInterfaceService.listByWarehousePlatformCode({ + warehouseId, + platformCode: 'DOUYIN', + }); + + return Array.isArray(fallbackResult && fallbackResult.data) ? fallbackResult.data : []; + } + /** * 按订单物流编码匹配菜鸟主面单接口配置。 * @@ -1499,6 +1630,186 @@ ${waveFilterSql} return null; } + /** + * 按订单物流编码匹配京东主面单接口表配置。 + * + * 优先复用快递服务里的既有匹配规则;若运行上下文未注入该能力,则使用同语义的最小兜底实现。 + * + * @param {Array} interfaceList 接口配置列表。 + * @param {Object} orderRow 订单行。 + * @param {Object} orderExpress 快递行。 + * @return {Object|null} 命中的接口配置。 + */ + pickJdExpressInterface(interfaceList = [], orderRow = {}, orderExpress = {}) { + const logisticsCode = String( + orderExpress && orderExpress.logistics_code + || orderRow && orderRow.logistics_code + || orderRow && orderRow.sys_logistics_code + || '' + ).trim(); + if (!logisticsCode) { + return null; + } + + const expressService = this.service && this.service.systems && this.service.systems.express; + if (expressService && typeof expressService.pickWaybillExpressInterface === 'function') { + const matchedInterface = expressService.pickWaybillExpressInterface( + interfaceList, + { + options: { + logistics_code: logisticsCode, + sys_platform_code: 'JD', + }, + }, + { code: 'JD' } + ); + if (matchedInterface) { + return matchedInterface; + } + } + + const normalizedLogisticsCode = logisticsCode.toLowerCase(); + for (const item of Array.isArray(interfaceList) ? interfaceList : []) { + if (!this.isPlainObject(item)) { + continue; + } + + const candidateCodes = [ + String(item.sys_express_code || '').trim().toLowerCase(), + String(item.express_code || '').trim().toLowerCase(), + ]; + const expressMap = this.isPlainObject(item.express) ? item.express : {}; + candidateCodes.push(String(expressMap.JD || '').trim().toLowerCase()); + + if (candidateCodes.some(code => code && code === normalizedLogisticsCode)) { + return item; + } + } + + return null; + } + + /** + * 按订单物流编码匹配拼多多主面单接口表配置。 + * + * 优先复用快递服务里的既有匹配规则;若运行上下文未注入该能力,则使用同语义的最小兜底实现。 + * + * @param {Array} interfaceList 接口配置列表。 + * @param {Object} orderRow 订单行。 + * @param {Object} orderExpress 快递行。 + * @return {Object|null} 命中的接口配置。 + */ + pickPddExpressInterface(interfaceList = [], orderRow = {}, orderExpress = {}) { + const logisticsCode = String( + orderExpress && orderExpress.logistics_code + || orderRow && orderRow.logistics_code + || orderRow && orderRow.sys_logistics_code + || '' + ).trim(); + if (!logisticsCode) { + return null; + } + + const expressService = this.service && this.service.systems && this.service.systems.express; + if (expressService && typeof expressService.pickWaybillExpressInterface === 'function') { + const matchedInterface = expressService.pickWaybillExpressInterface( + interfaceList, + { + options: { + logistics_code: logisticsCode, + sys_platform_code: 'PDD', + print_platform_code: 'PDD', + }, + }, + { code: 'PDD' } + ); + if (matchedInterface) { + return matchedInterface; + } + } + + const normalizedLogisticsCode = logisticsCode.toLowerCase(); + for (const item of Array.isArray(interfaceList) ? interfaceList : []) { + if (!this.isPlainObject(item)) { + continue; + } + + const candidateCodes = [ + String(item.sys_express_code || '').trim().toLowerCase(), + String(item.express_code || '').trim().toLowerCase(), + ]; + const expressMap = this.isPlainObject(item.express) ? item.express : {}; + candidateCodes.push(String(expressMap.PDD || '').trim().toLowerCase()); + + if (candidateCodes.some(code => code && code === normalizedLogisticsCode)) { + return item; + } + } + + return null; + } + + /** + * 按订单物流编码匹配抖音主面单接口表配置。 + * + * 优先复用快递服务里的既有匹配规则;若运行上下文未注入该能力,则使用同语义的最小兜底实现。 + * + * @param {Array} interfaceList 接口配置列表。 + * @param {Object} orderRow 订单行。 + * @param {Object} orderExpress 快递行。 + * @return {Object|null} 命中的接口配置。 + */ + pickDouyinExpressInterface(interfaceList = [], orderRow = {}, orderExpress = {}) { + const logisticsCode = String( + orderExpress && orderExpress.logistics_code + || orderRow && orderRow.logistics_code + || orderRow && orderRow.sys_logistics_code + || '' + ).trim(); + if (!logisticsCode) { + return null; + } + + const expressService = this.service && this.service.systems && this.service.systems.express; + if (expressService && typeof expressService.pickWaybillExpressInterface === 'function') { + const matchedInterface = expressService.pickWaybillExpressInterface( + interfaceList, + { + options: { + logistics_code: logisticsCode, + sys_platform_code: 'DY', + print_platform_code: 'DY', + }, + }, + { code: 'DY' } + ); + if (matchedInterface) { + return matchedInterface; + } + } + + const normalizedLogisticsCode = logisticsCode.toLowerCase(); + for (const item of Array.isArray(interfaceList) ? interfaceList : []) { + if (!this.isPlainObject(item)) { + continue; + } + + const candidateCodes = [ + String(item.sys_express_code || '').trim().toLowerCase(), + String(item.express_code || '').trim().toLowerCase(), + ]; + const expressMap = this.isPlainObject(item.express) ? item.express : {}; + candidateCodes.push(String(expressMap.DY || '').trim().toLowerCase()); + candidateCodes.push(String(expressMap.DOUYIN || '').trim().toLowerCase()); + + if (candidateCodes.some(code => code && code === normalizedLogisticsCode)) { + return item; + } + } + + return null; + } + /** * 为菜鸟打印订单补齐主面单专用来源字段。 * @@ -1580,6 +1891,234 @@ ${waveFilterSql} }); } + /** + * 为京东打印订单补齐主面单模板来源字段。 + * + * 仅对打印平台归一化为京东的订单生效;补齐失败时保留原始运单数据,避免影响其他平台打印。 + * + * @param {Array} orderRows 订单列表。 + * @param {Array} orderExpressRows 快递单列表。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise>} 补齐后的快递单列表。 + */ + async enrichJdOrderExpressRows(orderRows = [], orderExpressRows = [], warehouseId) { + const normalizedOrderRows = Array.isArray(orderRows) ? orderRows : []; + const normalizedOrderExpressRows = Array.isArray(orderExpressRows) ? orderExpressRows : []; + if (normalizedOrderRows.length === 0 || normalizedOrderExpressRows.length === 0) { + return normalizedOrderExpressRows; + } + + const orderRowMap = new Map(normalizedOrderRows.map(row => [ Number(row && row.id || 0), row ])); + const jdOrderIds = []; + + for (const row of normalizedOrderExpressRows) { + const orderId = Number(row && row.order_id || 0); + const orderRow = orderRowMap.get(orderId) || {}; + const platformCode = this.resolvePrintPlatformCode(orderRow, row); + if (!this.isJdPlatformCode(platformCode)) { + continue; + } + + jdOrderIds.push(orderId); + } + + if (jdOrderIds.length === 0) { + return normalizedOrderExpressRows; + } + + let interfaceList = []; + try { + interfaceList = await this.queryJdExpressInterfaceList(warehouseId); + } catch (error) { + this.ctx.logger.warn( + `[orderPrint.enrichJdOrderExpressRows] 查询京东快递接口表失败 warehouseId=${warehouseId} message=${error.message}` + ); + } + + if (!Array.isArray(interfaceList) || interfaceList.length === 0) { + return normalizedOrderExpressRows; + } + + const jdOrderIdSet = new Set(jdOrderIds); + return normalizedOrderExpressRows.map(row => { + const orderId = Number(row && row.order_id || 0); + if (!jdOrderIdSet.has(orderId)) { + return row; + } + + const orderRow = orderRowMap.get(orderId) || {}; + const matchedInterface = this.pickJdExpressInterface(interfaceList, orderRow, row); + const matchedTemplateUrl = String(matchedInterface && matchedInterface.template_url || '').trim(); + if (!matchedTemplateUrl) { + return row; + } + + return { + ...row, + jd_template_url: matchedTemplateUrl, + }; + }); + } + + /** + * 为拼多多与抖音打印订单补齐主面单模板来源字段。 + * + * 仅对打印平台归一化为拼多多/抖音的订单生效;补齐失败时保留原始运单数据,避免影响其他平台打印。 + * + * @param {Array} orderRows 订单列表。 + * @param {Array} orderExpressRows 快递单列表。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise>} 补齐后的快递单列表。 + */ + async enrichPddDyOrderExpressRows(orderRows = [], orderExpressRows = [], warehouseId) { + const normalizedOrderRows = Array.isArray(orderRows) ? orderRows : []; + const normalizedOrderExpressRows = Array.isArray(orderExpressRows) ? orderExpressRows : []; + if (normalizedOrderRows.length === 0 || normalizedOrderExpressRows.length === 0) { + return normalizedOrderExpressRows; + } + + const orderRowMap = new Map(normalizedOrderRows.map(row => [ Number(row && row.id || 0), row ])); + const pddOrderIds = []; + const douyinOrderIds = []; + + for (const row of normalizedOrderExpressRows) { + const orderId = Number(row && row.order_id || 0); + const orderRow = orderRowMap.get(orderId) || {}; + const platformCode = this.resolvePrintPlatformCode(orderRow, row); + if (this.isPddPlatformCode(platformCode)) { + pddOrderIds.push(orderId); + continue; + } + + if (this.isDouyinPlatformCode(platformCode)) { + douyinOrderIds.push(orderId); + } + } + + if (pddOrderIds.length === 0 && douyinOrderIds.length === 0) { + return normalizedOrderExpressRows; + } + + this.ctx.logger.info('[enrichPddDyOrderExpressRows] douyin 分支入口', { + douyinOrderCount: douyinOrderIds.length, + douyinOrderIds: douyinOrderIds.slice(0, 10), + }); + + let pddInterfaceList = []; + if (pddOrderIds.length > 0) { + try { + pddInterfaceList = await this.queryPddExpressInterfaceList(warehouseId); + } catch (error) { + this.ctx.logger.warn( + `[orderPrint.enrichPddDyOrderExpressRows] 查询拼多多快递接口表失败 warehouseId=${warehouseId} message=${error.message}` + ); + } + } + + let douyinInterfaceList = []; + if (douyinOrderIds.length > 0) { + try { + douyinInterfaceList = await this.queryDouyinExpressInterfaceList(warehouseId); + this.ctx.logger.info('[enrichPddDyOrderExpressRows] douyin 接口列表查询结果', { + interfaceCount: douyinInterfaceList.length, + }); + } catch (error) { + this.ctx.logger.warn( + `[orderPrint.enrichPddDyOrderExpressRows] 查询抖音快递接口表失败 warehouseId=${warehouseId} message=${error.message}` + ); + } + } + + const pddOrderIdSet = new Set(pddOrderIds); + const douyinOrderIdSet = new Set(douyinOrderIds); + return Promise.all(normalizedOrderExpressRows.map(async row => { + const orderId = Number(row && row.order_id || 0); + const orderRow = orderRowMap.get(orderId) || {}; + + if (pddOrderIdSet.has(orderId)) { + const matchedInterface = this.pickPddExpressInterface(pddInterfaceList, orderRow, row); + const matchedTemplateUrl = String(matchedInterface && matchedInterface.template_url || '').trim(); + if (!matchedTemplateUrl) { + return row; + } + + return { + ...row, + pdd_template_url: matchedTemplateUrl, + }; + } + + if (douyinOrderIdSet.has(orderId)) { + const matchedInterface = this.pickDouyinExpressInterface(douyinInterfaceList, orderRow, row); + const matchedTemplateUrl = String(matchedInterface && matchedInterface.template_url || '').trim(); + this.ctx.logger.info('[enrichPddDyOrderExpressRows] douyin 单笔匹配结果', { + orderId, + hasMatchedInterface: !!matchedInterface, + matchedTemplateUrl, + sysLogisticsCode: orderRow.sys_logistics_code, + logisticsCode: row.logistics_code, + }); + if (!matchedTemplateUrl) { + return row; + } + + // 获取菠萝派 API 请求参数 + let dyParams = ''; + try { + if (matchedInterface) { + const cacheKey = `douyin:params:${orderRow.sys_logistics_code || orderRow.logistics_code || ''}:${row.logistics_interface_id || ''}`; + + // 菠萝派配置:appkey/app_secret 来自项目 config.poloApi,token 来自快递接口 + const poloConfig = this.config.poloApi || {}; + + // 先查 Redis 缓存 + if (this.app && typeof this.app.getCacheAsync === 'function') { + const cached = await this.app.getCacheAsync(cacheKey); + if (cached && typeof cached === 'string') { + dyParams = cached; + } + } + // 缓存未命中,调菠萝派 + if (!dyParams) { + const PoloApiClient = require('../../lib/polo_api_client'); + const poloClient = new PoloApiClient(this.ctx); + const result = await poloClient.request({ + method: 'Differ.JH.Business.GetPlatApiRequestInfo', + bizcontent: { platMethod: '/logistics/getShopKey' }, + config: { + interface_url: 'https://api.polyapi.com/openapi/do', + appkey: poloConfig.appKey || '', + app_secret: poloConfig.appSecret || '', + platid: 126, + version: '1.5', + token: matchedInterface.token || '', + }, + token: matchedInterface.token || '', + }); + + this.ctx.logger.info('[DouyinParams] 菠萝派 GetPlatApiRequestInfo 响应:', JSON.stringify(result)); + dyParams = result.requestinfo || JSON.stringify(result); + + if (this.app && typeof this.app.setCacheAsync === 'function') { + await this.app.setCacheAsync(cacheKey, dyParams, 270); + } + } + } + } catch (err) { + this.ctx.logger.warn('[enrichPddDyOrderExpressRows] 获取 Douyin params 失败: %s', err.message); + } + + return { + ...row, + dy_template_url: matchedTemplateUrl, + dy_params: dyParams, + }; + } + + return row; + })); + } + /** * 获取波次订单对应货主的签约策略映射。 * @@ -1725,7 +2264,6 @@ ${waveFilterSql} }, }); const printData = this.extractSinglePlatformPrintData(printPayload); - return { wave_id: waveId, wave_no: String(orderRow.wave_no || '').trim(), @@ -1776,6 +2314,10 @@ ${waveFilterSql} return taskListEntry.documents[0]; } + if (Array.isArray(requestSkeleton.taskList) && this.isPlainObject(requestSkeleton.taskList[0])) { + return requestSkeleton.taskList[0]; + } + return {}; } diff --git a/app/service/systems/order_storage_allocation.js b/app/service/systems/order_storage_allocation.js index 17f688c..555f0bb 100644 --- a/app/service/systems/order_storage_allocation.js +++ b/app/service/systems/order_storage_allocation.js @@ -1393,6 +1393,7 @@ class OrderStorageAllocationService extends MainService { const { ctx } = this; const unallocatedPostStatus = 'none'; const fastFailReason = '快递状态未分配,禁止同步'; + const snBatchForbiddenReason = 'SN订单不支持批量回传,请改用单订单回传'; const requestData = data && typeof data === 'object' ? data : {}; const normalizeNumber = (value, defaultValue = 0) => { const numericValue = Number(value); @@ -1533,6 +1534,79 @@ class OrderStorageAllocationService extends MainService { orderMap.set(Number(plainOrder.id), plainOrder); } + // SN 管理订单不允许走批量回传:通过订单明细 stock_id 反查 stock_warehouse.is_sn_mgmt。 + const snOrderIdSet = new Set(); + const existingOrderIds = Array.from(orderMap.keys()); + if (existingOrderIds.length > 0) { + try { + const orderItemModel = await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId); + const stockModel = ctx.model.StockWarehouse; + + if (orderItemModel && typeof orderItemModel.findAll === 'function' && stockModel && typeof stockModel.findAll === 'function') { + const orderItemRows = await orderItemModel.findAll({ + where: { + order_id: { + [ctx.app.Sequelize.Op.in]: existingOrderIds, + }, + }, + attributes: [ 'order_id', 'stock_id' ], + raw: true, + }); + + const stockIds = [ ...new Set((Array.isArray(orderItemRows) ? orderItemRows : []) + .map(row => Number(row && row.stock_id || 0)) + .filter(stockId => Number.isFinite(stockId) && stockId > 0)) ]; + + if (stockIds.length > 0) { + const stockRows = await stockModel.findAll({ + where: { + id: { + [ctx.app.Sequelize.Op.in]: stockIds, + }, + warehouse_id: warehouseId, + }, + attributes: [ 'id', 'is_sn_mgmt' ], + raw: true, + }); + + const snStockIdSet = new Set((Array.isArray(stockRows) ? stockRows : []) + .filter(row => String(row && row.is_sn_mgmt || '').trim().toUpperCase() === 'Y') + .map(row => Number(row && row.id || 0)) + .filter(stockId => Number.isFinite(stockId) && stockId > 0)); + + for (const row of (Array.isArray(orderItemRows) ? orderItemRows : [])) { + const orderId = Number(row && row.order_id || 0); + const stockId = Number(row && row.stock_id || 0); + if (snStockIdSet.has(stockId) && orderId > 0) { + snOrderIdSet.add(orderId); + } + } + } + } + } catch (snDetectError) { + ctx.logger.error('[OrderStorageAllocationService.syncOrderIds] SN订单检测失败', { + warehouseId, + orderIds: existingOrderIds, + message: snDetectError && snDetectError.message, + }); + throw snDetectError; + } + } + + if (snOrderIdSet.size > 0) { + const forbiddenOrderIds = Array.from(snOrderIdSet).sort((a, b) => a - b); + await transaction.rollback(); + return { + code: 400, + message: snBatchForbiddenReason, + data: { + warehouse_id: warehouseId, + requested_order_ids: orderIds, + forbidden_order_ids: forbiddenOrderIds, + }, + }; + } + const skippedOrders = []; const fastFailedOrders = []; const syncableOrders = []; @@ -1575,7 +1649,8 @@ class OrderStorageAllocationService extends MainService { syncableOrders.push(orderRow); } - const fastFailedOrderIds = fastFailedOrders + const expressFastFailedOrderIds = fastFailedOrders + .filter(order => String(order && order.failed_reason || '').trim() === 'express_unallocated') .map(order => normalizeNumber(order.order_id, 0)) .filter(orderId => orderId > 0); @@ -1600,7 +1675,7 @@ class OrderStorageAllocationService extends MainService { }); } - if (fastFailedOrderIds.length > 0) { + if (expressFastFailedOrderIds.length > 0) { await orderModel.update({ sync_status: 'error', sync_message: fastFailReason, @@ -1611,7 +1686,7 @@ class OrderStorageAllocationService extends MainService { }, { where: { id: { - [ctx.app.Sequelize.Op.in]: fastFailedOrderIds, + [ctx.app.Sequelize.Op.in]: expressFastFailedOrderIds, }, warehouse_id: warehouseId, }, @@ -1620,7 +1695,7 @@ class OrderStorageAllocationService extends MainService { ctx.logger.warn('[OrderStorageAllocationService.syncOrderIds] 命中快递状态未分配快速失败,已阻断同步派发', { warehouseId, - orderIds: fastFailedOrderIds, + orderIds: expressFastFailedOrderIds, reason: fastFailReason, }); } @@ -1690,7 +1765,7 @@ class OrderStorageAllocationService extends MainService { code: 200, message: syncableOrderIds.length > 0 ? '同步已受理,已生成按来源分组的同步计划' - : (fastFailedOrders.length > 0 ? '同步失败:存在快递状态未分配订单' : '没有需要同步的订单'), + : (fastFailedOrders.length > 0 ? '同步失败:存在不允许批量回传的订单' : '没有需要同步的订单'), data: responseData, }; } catch (error) { diff --git a/app/service/systems/pick.js b/app/service/systems/pick.js index 80c48af..794fba6 100644 --- a/app/service/systems/pick.js +++ b/app/service/systems/pick.js @@ -59,9 +59,12 @@ class PickSystemService extends Service { * @param {number} [code=400] 错误码。 * @return {Error} 错误对象。 */ - createBusinessError(message, code = 400) { + createBusinessError(message, code = 400, data = null) { const error = new Error(message); error.code = code; + if (data && typeof data === 'object' && !Array.isArray(data)) { + error.data = data; + } return error; } @@ -832,7 +835,7 @@ class PickSystemService extends Service { FROM wms_wave_pick_task t WHERE t.warehouse_id = :warehouseId AND t.pick_user_id = :pickUserId - AND t.status IN (0, 1, 2) + AND t.status IN (0, 1) ORDER BY t.id DESC LIMIT 1 `, { @@ -903,6 +906,32 @@ class PickSystemService extends Service { throw this.createBusinessError('当前操作人与任务创建人不一致,无权查看', 403); } + // 首次进入详情时补写拣货开始时间,确保后续流程可感知“已开始”。 + if (!taskRow.start_at) { + await ctx.model.query(` + UPDATE wms_wave_pick_task + SET + start_time = NOW(), + update_time = NOW() + WHERE id = :taskId + AND start_time IS NULL + `, { + replacements: { taskId }, + }); + + const startTimeRows = await ctx.model.query(` + SELECT start_time AS start_at + FROM wms_wave_pick_task + WHERE id = :taskId + LIMIT 1 + `, { + replacements: { taskId }, + type: ctx.model.QueryTypes.SELECT, + }); + const startTimeRow = Array.isArray(startTimeRows) && startTimeRows.length > 0 ? startTimeRows[0] : null; + taskRow.start_at = startTimeRow && startTimeRow.start_at ? startTimeRow.start_at : taskRow.start_at; + } + const warehouseId = Number(taskRow.warehouse_id || 0); const pickMode = Number(taskRow.pick_mode || 0); const taskOrderColumnSet = await this.getTableColumnSet('wms_wave_pick_task_order'); @@ -929,7 +958,8 @@ class PickSystemService extends Service { ctx.model.query(` SELECT pto.order_id, - pto.box_no + pto.box_no, + pto.pick_status FROM wms_wave_pick_task_order pto WHERE pto.task_id = :taskId ${taskOrderWarehouseFilterSql} @@ -955,6 +985,13 @@ class PickSystemService extends Service { ]); const normalizedTaskOrderRows = Array.isArray(taskOrderRows) ? taskOrderRows : []; + const taskOrderTotal = normalizedTaskOrderRows.length; + const taskOrderPicked = normalizedTaskOrderRows + .filter(row => Number(row && row.pick_status || 0) === 1) + .length; + const taskCompletedByOrder = taskOrderTotal > 0 && taskOrderPicked >= taskOrderTotal; + const taskCompletedByStatus = Number(taskRow && taskRow.status || 0) >= 2; + const isCompleted = taskCompletedByOrder || taskCompletedByStatus; let orderIds = [ ...new Set(normalizedTaskOrderRows .map(row => Number(row && row.order_id || 0)) .filter(orderIdItem => Number.isInteger(orderIdItem) && orderIdItem > 0)) ]; @@ -1004,6 +1041,39 @@ class PickSystemService extends Service { } } + if (orderIds.length > 0) { + const orderModel = await this.getOrderModel(warehouseId); + const orderExpressStatusRows = await orderModel.findAll({ + where: { + id: { + [this.app.Sequelize.Op.in]: orderIds, + }, + warehouse_id: warehouseId, + }, + attributes: [ 'id', 'post_status' ], + raw: true, + }); + + const orderExpressStatusMap = new Map((Array.isArray(orderExpressStatusRows) ? orderExpressStatusRows : []) + .map(row => [ Number(row && row.id || 0), String(row && row.post_status || '').trim() ])); + const unassignedExpressOrderIds = orderIds + .filter(orderIdItem => { + const expressStatus = orderExpressStatusMap.get(orderIdItem) || ''; + return expressStatus !== 'fin'; + }); + + if (unassignedExpressOrderIds.length > 0) { + throw this.createBusinessError( + '存在未分配快递号订单,是否一键分配快递号?', + 400, + { + action: 'assign_express', + order_ids: unassignedExpressOrderIds, + } + ); + } + } + const pickingRows = orderIds.length > 0 ? await ctx.model.Picking.findAll({ where: { @@ -1017,6 +1087,29 @@ class PickSystemService extends Service { }) : []; + const normalizedPickingRows = Array.isArray(pickingRows) ? pickingRows : []; + const orderIdSet = new Set(orderIds); + const orderIdsWithPicking = new Set(normalizedPickingRows + .map(row => Number(row && row.order_id || 0)) + .filter(orderIdItem => Number.isInteger(orderIdItem) && orderIdSet.has(orderIdItem))); + const missingPickingOrderIds = orderIds + .filter(orderIdItem => Number.isInteger(orderIdItem) && orderIdItem > 0 && !orderIdsWithPicking.has(orderIdItem)); + const invalidSpaceOrderIds = [ ...new Set(normalizedPickingRows + .filter(row => Number(row && row.space_id || 0) <= 0) + .map(row => Number(row && row.order_id || 0)) + .filter(orderIdItem => Number.isInteger(orderIdItem) && orderIdSet.has(orderIdItem))) ]; + const unassignedSpaceOrderIds = [ ...new Set([ ...missingPickingOrderIds, ...invalidSpaceOrderIds ]) ]; + if (unassignedSpaceOrderIds.length > 0) { + throw this.createBusinessError( + '存在未分配储位订单,是否一键分配储位?', + 400, + { + action: 'assign_storage', + order_ids: unassignedSpaceOrderIds, + } + ); + } + ctx.logger.info( `[pick.wavePickTaskDetail] task_id=${taskId} pick_mode=${pickMode} warehouse_id=${warehouseId} task_order_count=${normalizedTaskOrderRows.length} task_wave_count=${taskWaveCount} derived_order_ids_count=${orderIds.length} picking_rows_count=${Array.isArray(pickingRows) ? pickingRows.length : 0} order_source=${orderSource} order_id_samples=${JSON.stringify(orderIds.slice(0, 5))} wave_id_samples=${JSON.stringify(derivedWaveIds)}` ); @@ -1091,7 +1184,7 @@ class PickSystemService extends Service { boxMapByNo, }); - return { + const result = { task: { task_id: Number(taskRow.task_id || 0), task_no: String(taskRow.task_no || '').trim(), @@ -1100,7 +1193,14 @@ class PickSystemService extends Service { start_at: taskRow.start_at || null, finish_at: taskRow.finish_at || null, batch_no: String(taskRow.batch_no || '').trim(), + is_completed: isCompleted, + progress: { + total_orders: taskOrderTotal, + picked_orders: taskOrderPicked, + pending_orders: Math.max(0, taskOrderTotal - taskOrderPicked), + }, }, + is_completed: isCompleted, boxes: normalizedBoxRows.map(row => ({ box_id: Number(row && row.box_id || 0), box_no: Number(row && row.box_no || 0), @@ -1111,10 +1211,1245 @@ class PickSystemService extends Service { required_qty: Number(row && row.required_qty || 0), picked_qty: Number(row && row.picked_qty || 0), })), - picking_details: pickingDetails, picking_summary: pickingSummary, picking_view: pickingView, }; + + // 团购小波次不需要返回拣货明细,减少带宽浪费 + if (pickMode !== 1) { + result.picking_details = pickingDetails; + } + + return result; + } + + /** + * 解析当前操作人上下文。 + * + * @return {{operatorId: number, operatorName: string, warehouseId: number}} 上下文信息。 + */ + resolveOperatorContext() { + const { ctx } = this; + const stateUser = ctx && ctx.state && ctx.state.user && typeof ctx.state.user === 'object' + ? ctx.state.user + : null; + const ctxUser = ctx && ctx.user && typeof ctx.user === 'object' + ? ctx.user + : null; + const operatorSource = stateUser || ctxUser || {}; + + const operatorId = Number((operatorSource.employees_id ?? operatorSource.operator_id ?? operatorSource.id) || 0); + const operatorName = String( + operatorSource.operator_name + || operatorSource.employees_name + || operatorSource.name + || '' + ).trim() || 'system'; + const warehouseId = Number(operatorSource.store_id || operatorSource.warehouse_id || 0); + + return { + operatorId, + operatorName, + warehouseId, + }; + } + + /** + * 规范化拣货车状态。 + * + * @param {*} status 原始状态。 + * @param {number} [defaultValue=1] 默认状态。 + * @return {number} 规范化后的状态值,仅返回 0 或 1。 + */ + normalizePickCartStatus(status, defaultValue = 1) { + if (status === undefined || status === null || status === '') { + return defaultValue; + } + + const normalized = Number(status); + if (normalized === 0) { + return 0; + } + if (normalized === 1) { + return 1; + } + return Number(defaultValue) === 0 ? 0 : 1; + } + + /** + * 构建拣货车详情输出。 + * + * @param {Object} row 原始数据库记录。 + * @return {Object} 标准化后的详情。 + */ + buildPickCartDetail(row = {}) { + return { + cart_id: Number(row && (row.cart_id || row.id) || 0), + warehouse_id: Number(row && row.warehouse_id || 0), + cart_code: String(row && row.cart_code || '').trim(), + cart_name: String(row && row.cart_name || '').trim(), + status: Number(row && row.status || 0), + current_task_id: Number(row && row.current_task_id || 0) || null, + current_task_no: String(row && row.current_task_no || '').trim() || null, + current_task_status: row && row.current_task_status !== undefined && row.current_task_status !== null + ? Number(row.current_task_status) + : null, + bind_user_id: Number(row && row.bind_user_id || 0) || null, + last_bind_time: row && row.last_bind_time ? row.last_bind_time : null, + last_seen_time: row && row.last_seen_time ? row.last_seen_time : null, + create_time: row && row.create_time ? row.create_time : null, + update_time: row && row.update_time ? row.update_time : null, + }; + } + + /** + * 按 ID 查询拣货车。 + * + * @param {number} cartId 拣货车ID。 + * @param {number} warehouseId 仓库ID。 + * @param {Object} [transaction=null] 事务对象。 + * @return {Promise} 拣货车记录。 + */ + async getPickCartById(cartId, warehouseId, transaction = null) { + const { ctx } = this; + const rows = await ctx.model.query(` + SELECT + c.id AS cart_id, + c.warehouse_id, + c.cart_code, + c.cart_name, + c.status, + c.current_task_id, + c.bind_user_id, + c.last_bind_time, + c.last_seen_time, + c.create_time, + c.update_time, + t.task_no AS current_task_no, + t.status AS current_task_status + FROM wms_pick_cart c + LEFT JOIN wms_wave_pick_task t + ON t.id = c.current_task_id + WHERE c.id = :cartId + AND c.warehouse_id = :warehouseId + LIMIT 1 + `, { + replacements: { + cartId, + warehouseId, + }, + type: ctx.model.QueryTypes.SELECT, + ...(transaction ? { transaction } : {}), + }); + + return Array.isArray(rows) && rows.length > 0 ? rows[0] : null; + } + + /** + * 按编码查询拣货车。 + * + * @param {string} cartCode 拣货车编码。 + * @param {number} warehouseId 仓库ID。 + * @param {Object} [transaction=null] 事务对象。 + * @return {Promise} 拣货车记录。 + */ + async getPickCartByCode(cartCode, warehouseId, transaction = null) { + const { ctx } = this; + const normalizedCartCode = String(cartCode || '').trim(); + if (!normalizedCartCode) { + return null; + } + + const rows = await ctx.model.query(` + SELECT + c.id AS cart_id, + c.warehouse_id, + c.cart_code, + c.cart_name, + c.status, + c.current_task_id, + c.bind_user_id, + c.last_bind_time, + c.last_seen_time, + c.create_time, + c.update_time, + t.task_no AS current_task_no, + t.status AS current_task_status + FROM wms_pick_cart c + LEFT JOIN wms_wave_pick_task t + ON t.id = c.current_task_id + WHERE c.warehouse_id = :warehouseId + AND c.cart_code = :cartCode + LIMIT 1 + `, { + replacements: { + warehouseId, + cartCode: normalizedCartCode, + }, + type: ctx.model.QueryTypes.SELECT, + ...(transaction ? { transaction } : {}), + }); + + return Array.isArray(rows) && rows.length > 0 ? rows[0] : null; + } + + /** + * 查询拣货车编码是否重复。 + * + * @param {Object} params 查询参数。 + * @param {string} params.cartCode 拣货车编码。 + * @param {number} params.warehouseId 仓库ID。 + * @param {number} [params.excludeCartId=0] 排除的拣货车ID。 + * @param {Object} [params.transaction=null] 事务对象。 + * @return {Promise} 查重结果。 + */ + async pickCartCodeDuplicateCheck(params = {}) { + const { ctx } = this; + const cartCode = String(params && params.cartCode || '').trim(); + const warehouseId = Number(params && params.warehouseId || 0); + const excludeCartId = Number(params && params.excludeCartId || 0); + const transaction = params && params.transaction ? params.transaction : null; + + if (!cartCode) { + throw this.createBusinessError('cart_code 必填', 400); + } + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw this.createBusinessError('缺少当前用户仓库上下文 store_id', 400); + } + + const rows = await ctx.model.query(` + SELECT + c.id AS cart_id, + c.cart_code, + c.cart_name, + c.status + FROM wms_pick_cart c + WHERE c.warehouse_id = :warehouseId + AND c.cart_code = :cartCode + AND (:excludeCartId <= 0 OR c.id <> :excludeCartId) + ORDER BY c.id DESC + LIMIT 1 + `, { + replacements: { + warehouseId, + cartCode, + excludeCartId, + }, + type: ctx.model.QueryTypes.SELECT, + ...(transaction ? { transaction } : {}), + }); + + const row = Array.isArray(rows) && rows.length > 0 ? rows[0] : null; + return { + duplicated: Boolean(row), + cart_id: row ? Number(row.cart_id || 0) : null, + cart_code: row ? String(row.cart_code || '').trim() : null, + cart_name: row ? String(row.cart_name || '').trim() : null, + status: row ? Number(row.status || 0) : null, + }; + } + + /** + * 确保拣货车编码未重复。 + * + * @param {string} cartCode 拣货车编码。 + * @param {number} warehouseId 仓库ID。 + * @param {number} [excludeCartId=0] 排除的拣货车ID。 + * @param {Object} [transaction=null] 事务对象。 + * @return {Promise} 无返回值。 + */ + async assertPickCartCodeUnique(cartCode, warehouseId, excludeCartId = 0, transaction = null) { + const duplicateResult = await this.pickCartCodeDuplicateCheck({ + cartCode, + warehouseId, + excludeCartId, + transaction, + }); + + if (duplicateResult.duplicated) { + throw this.createBusinessError('拣货车编码已存在,请勿重复', 409, duplicateResult); + } + } + + /** + * 校验任务存在性与归属。 + * + * @param {number} taskId 任务ID。 + * @param {number} operatorId 操作人ID。 + * @return {Promise} 任务记录。 + */ + async getOwnedTask(taskId, operatorId) { + const { ctx } = this; + const taskRows = await ctx.model.query(` + SELECT + t.id AS task_id, + t.task_no, + t.status, + t.pick_mode, + t.pick_user_id, + t.warehouse_id, + t.start_time, + t.finish_time, + t.ext_json + FROM wms_wave_pick_task t + WHERE t.id = :taskId + LIMIT 1 + `, { + replacements: { taskId }, + type: ctx.model.QueryTypes.SELECT, + }); + const taskRow = Array.isArray(taskRows) && taskRows.length > 0 ? taskRows[0] : null; + if (!taskRow) { + throw this.createBusinessError('拣货任务不存在', 404); + } + + const taskPickUserId = Number(taskRow.pick_user_id || 0); + if (!Number.isInteger(taskPickUserId) || taskPickUserId !== operatorId) { + throw this.createBusinessError('当前操作人与任务创建人不一致,无权操作', 403); + } + + return taskRow; + } + + /** + * 统计任务订单拣货进度。 + * + * @param {number} taskId 任务ID。 + * @param {number} warehouseId 仓库ID。 + * @param {Object} [transaction] 事务对象。 + * @return {Promise<{totalOrders:number,pickedOrders:number,pendingOrders:number,isCompleted:boolean}>} 进度信息。 + */ + async getTaskPickProgress(taskId, warehouseId, transaction = null) { + const { ctx } = this; + const taskOrderRows = await ctx.model.query(` + SELECT + pto.order_id, + pto.pick_status + FROM wms_wave_pick_task_order pto + WHERE pto.task_id = :taskId + AND pto.warehouse_id = :warehouseId + `, { + replacements: { + taskId, + warehouseId, + }, + type: ctx.model.QueryTypes.SELECT, + ...(transaction ? { transaction } : {}), + }); + + const normalizedRows = Array.isArray(taskOrderRows) ? taskOrderRows : []; + const totalOrders = normalizedRows.length; + const pickedOrders = normalizedRows.filter(row => Number(row && row.pick_status || 0) === 1).length; + const pendingOrders = Math.max(0, totalOrders - pickedOrders); + const isCompleted = totalOrders > 0 && pickedOrders >= totalOrders; + + return { + totalOrders, + pickedOrders, + pendingOrders, + isCompleted, + }; + } + + /** + * 拣货任务中间态提交。 + * + * 用于保存阶段性进度,不进行最终确认。 + * + * @param {Object} params 提交参数。 + * @param {number} params.taskId 任务ID。 + * @param {Object} [params.payload] 阶段性数据。 + * @return {Promise} 保存结果。 + */ + async wavePickTaskSubmit(params = {}) { + const { ctx } = this; + const taskId = Number(params && params.taskId || 0); + const payload = params && typeof params.payload === 'object' && !Array.isArray(params.payload) + ? params.payload + : {}; + + if (!Number.isInteger(taskId) || taskId <= 0) { + throw this.createBusinessError('task_id 必填且必须为正整数', 400); + } + + const { operatorId, operatorName, warehouseId } = this.resolveOperatorContext(); + if (!Number.isInteger(operatorId) || operatorId <= 0) { + throw this.createBusinessError('未获取到操作人上下文', 401); + } + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw this.createBusinessError('缺少当前用户仓库上下文 store_id', 400); + } + + const taskRow = await this.getOwnedTask(taskId, operatorId); + const taskStatus = Number(taskRow && taskRow.status || 0); + if ([ 3, 9 ].includes(taskStatus)) { + throw this.createBusinessError('任务已完成或已取消,无法提交中间态', 400); + } + + let extJson = {}; + const extSource = taskRow && taskRow.ext_json; + if (extSource && typeof extSource === 'object' && !Array.isArray(extSource)) { + extJson = { ...extSource }; + } else if (typeof extSource === 'string' && extSource.trim()) { + try { + const parsed = JSON.parse(extSource); + if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) { + extJson = { ...parsed }; + } + } catch (_) { + extJson = {}; + } + } + + extJson.pick_intermediate = { + payload, + updated_at: new Date().toISOString(), + operator_id: operatorId, + operator_name: operatorName, + }; + + await ctx.model.query(` + UPDATE wms_wave_pick_task + SET status = CASE WHEN status = 0 THEN 1 ELSE status END, + start_time = CASE WHEN start_time IS NULL THEN NOW() ELSE start_time END, + ext_json = :extJson, + update_time = NOW() + WHERE id = :taskId + AND warehouse_id = :warehouseId + `, { + replacements: { + taskId, + warehouseId, + extJson: JSON.stringify(extJson), + }, + }); + + const progress = await this.getTaskPickProgress(taskId, warehouseId); + return { + task_id: taskId, + status: 'submitted', + is_completed: progress.isCompleted, + progress: { + total_orders: progress.totalOrders, + picked_orders: progress.pickedOrders, + pending_orders: progress.pendingOrders, + }, + }; + } + + /** + * 拣货任务完全提交。 + * + * 支持两种模式: + * - 1:全部确认(将任务下全部订单标记为已拣) + * - 2:部分确认(仅确认传入 order_ids) + * + * @param {Object} params 提交参数。 + * @param {number} params.taskId 任务ID。 + * @param {number} [params.mode=1] 提交模式:1全部确认,2部分确认。 + * @param {Array} [params.orderIds=[]] 部分确认时的订单ID列表。 + * @return {Promise} 提交结果。 + */ + async wavePickTaskComplete(params = {}) { + const { ctx } = this; + const taskId = Number(params && params.taskId || 0); + const mode = Number(params && params.mode || 1); + const orderIds = [ ...new Set((Array.isArray(params && params.orderIds) ? params.orderIds : []) + .map(id => Number(id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ]; + + if (!Number.isInteger(taskId) || taskId <= 0) { + throw this.createBusinessError('task_id 必填且必须为正整数', 400); + } + if (![ 1, 2 ].includes(mode)) { + throw this.createBusinessError('mode 参数不合法,仅支持 1(全部确认) 或 2(部分确认)', 400); + } + + const { operatorId, warehouseId } = this.resolveOperatorContext(); + if (!Number.isInteger(operatorId) || operatorId <= 0) { + throw this.createBusinessError('未获取到操作人上下文', 401); + } + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw this.createBusinessError('缺少当前用户仓库上下文 store_id', 400); + } + + const taskRow = await this.getOwnedTask(taskId, operatorId); + const taskStatus = Number(taskRow && taskRow.status || 0); + if ([ 3, 9 ].includes(taskStatus)) { + throw this.createBusinessError('任务已完成或已取消,无法再次提交', 400); + } + + const transaction = await ctx.model.transaction(); + try { + const taskOrderRows = await ctx.model.query(` + SELECT + pto.order_id, + pto.pick_status + FROM wms_wave_pick_task_order pto + WHERE pto.task_id = :taskId + AND pto.warehouse_id = :warehouseId + `, { + replacements: { + taskId, + warehouseId, + }, + type: ctx.model.QueryTypes.SELECT, + transaction, + }); + + const normalizedRows = Array.isArray(taskOrderRows) ? taskOrderRows : []; + let taskOrderIds = [ ...new Set(normalizedRows + .map(row => Number(row && row.order_id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ]; + + if (taskOrderIds.length <= 0) { + const pickMode = Number(taskRow.pick_mode || 0); + if ([ 1, 5 ].includes(pickMode)) { + const taskWaveWarehouseFilterSql = (await this.getTableColumnSet('wms_wave_pick_task_wave')).has('warehouse_id') + ? ' AND ptw.warehouse_id = :warehouseId' + : ''; + const taskWaveRows = await ctx.model.query(` + SELECT + ptw.wave_id + FROM wms_wave_pick_task_wave ptw + WHERE ptw.task_id = :taskId + ${taskWaveWarehouseFilterSql} + ORDER BY ptw.id ASC + `, { + replacements: { taskId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + transaction, + }); + + const normalizedTaskWaveRows = Array.isArray(taskWaveRows) ? taskWaveRows : []; + const fallbackWaveIds = [ ...new Set(normalizedTaskWaveRows + .map(row => Number(row && row.wave_id || 0)) + .filter(waveId => Number.isInteger(waveId) && waveId > 0)) ]; + + if (fallbackWaveIds.length > 0) { + const orderModel = await this.getOrderModel(warehouseId); + const fallbackOrderRows = await orderModel.findAll({ + where: { + wave_id: { + [this.app.Sequelize.Op.in]: fallbackWaveIds, + }, + warehouse_id: warehouseId, + }, + attributes: [ 'id' ], + raw: true, + transaction, + }); + + taskOrderIds = [ ...new Set((Array.isArray(fallbackOrderRows) ? fallbackOrderRows : []) + .map(row => Number(row && row.id || 0)) + .filter(orderIdItem => Number.isInteger(orderIdItem) && orderIdItem > 0)) ]; + } + } + } + + if (taskOrderIds.length <= 0) { + throw this.createBusinessError('任务下无可确认订单', 400); + } + + let targetOrderIds = []; + if (mode === 1) { + targetOrderIds = taskOrderIds; + } else { + if (orderIds.length <= 0) { + throw this.createBusinessError('部分确认模式下 order_ids 不能为空', 400); + } + targetOrderIds = orderIds.filter(id => taskOrderIds.includes(id)); + if (targetOrderIds.length <= 0) { + throw this.createBusinessError('order_ids 未命中当前任务订单', 400); + } + } + + await ctx.model.query(` + UPDATE wms_wave_pick_task_order + SET pick_status = 1, + picked_time = NOW(), + update_time = NOW() + WHERE task_id = :taskId + AND warehouse_id = :warehouseId + AND order_id IN (:orderIds) + `, { + replacements: { + taskId, + warehouseId, + orderIds: targetOrderIds, + }, + transaction, + }); + + const orderModel = await this.getOrderModel(warehouseId); + await orderModel.update({ + pick_status: 'fin', + }, { + where: { + warehouse_id: warehouseId, + id: { + [this.app.Sequelize.Op.in]: targetOrderIds, + }, + }, + transaction, + validate: false, + hooks: false, + }); + + const progress = await this.getTaskPickProgress(taskId, warehouseId, transaction); + if (mode === 1 || progress.isCompleted) { + await ctx.model.query(` + UPDATE wms_wave_pick_task + SET status = 2, + finish_time = NOW(), + start_time = CASE WHEN start_time IS NULL THEN NOW() ELSE start_time END, + update_time = NOW() + WHERE id = :taskId + AND warehouse_id = :warehouseId + `, { + replacements: { + taskId, + warehouseId, + }, + transaction, + }); + } else { + await ctx.model.query(` + UPDATE wms_wave_pick_task + SET status = CASE WHEN status = 0 THEN 1 ELSE status END, + start_time = CASE WHEN start_time IS NULL THEN NOW() ELSE start_time END, + update_time = NOW() + WHERE id = :taskId + AND warehouse_id = :warehouseId + `, { + replacements: { + taskId, + warehouseId, + }, + transaction, + }); + } + + await transaction.commit(); + return { + task_id: taskId, + mode, + confirmed_order_ids: targetOrderIds, + is_completed: progress.isCompleted, + progress: { + total_orders: progress.totalOrders, + picked_orders: progress.pickedOrders, + pending_orders: progress.pendingOrders, + }, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + /** + * PDA 扫码查询拣货车信息。 + * + * @param {Object} params 查询参数。 + * @param {string} params.cartCode 拣货车编码。 + * @return {Promise} 拣货车详情。 + */ + async pickCartScan(params = {}) { + const cartCode = String(params && params.cartCode || '').trim(); + const { warehouseId } = this.resolveOperatorContext(); + + if (!cartCode) { + throw this.createBusinessError('cart_code 必填', 400); + } + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw this.createBusinessError('缺少当前用户仓库上下文 store_id', 400); + } + + const cartRow = await this.getPickCartByCode(cartCode, warehouseId); + if (!cartRow) { + throw this.createBusinessError('拣货车不存在', 404); + } + + return this.buildPickCartDetail(cartRow); + } + + /** + * 绑定拣货任务与拣货车。 + * + * @param {Object} params 绑定参数。 + * @param {number} params.taskId 拣货任务ID。 + * @param {number} [params.cartId] 拣货车ID。 + * @param {string} [params.cartCode] 拣货车编码。 + * @return {Promise} 绑定结果。 + */ + async wavePickTaskBindCart(params = {}) { + const { ctx } = this; + const taskId = Number(params && params.taskId || 0); + const cartId = Number(params && params.cartId || 0); + const cartCode = String(params && params.cartCode || '').trim(); + const { operatorId, warehouseId } = this.resolveOperatorContext(); + + if (!Number.isInteger(taskId) || taskId <= 0) { + throw this.createBusinessError('task_id 必填且必须为正整数', 400); + } + if ((!Number.isInteger(cartId) || cartId <= 0) && !cartCode) { + throw this.createBusinessError('cart_id 或 cart_code 至少传一个', 400); + } + if (!Number.isInteger(operatorId) || operatorId <= 0) { + throw this.createBusinessError('未获取到操作人上下文', 401); + } + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw this.createBusinessError('缺少当前用户仓库上下文 store_id', 400); + } + + const taskRow = await this.getOwnedTask(taskId, operatorId); + const taskStatus = Number(taskRow && taskRow.status || 0); + if ([ 3, 9 ].includes(taskStatus)) { + throw this.createBusinessError('任务已完成或已取消,无法绑定拣货车', 400); + } + if (Number(taskRow && taskRow.warehouse_id || 0) !== warehouseId) { + throw this.createBusinessError('任务不属于当前仓库,无法绑定拣货车', 403); + } + + const targetCartRow = cartId > 0 + ? await this.getPickCartById(cartId, warehouseId) + : await this.getPickCartByCode(cartCode, warehouseId); + if (!targetCartRow) { + throw this.createBusinessError('拣货车不存在', 404); + } + if (Number(targetCartRow.status || 0) !== 1) { + throw this.createBusinessError('拣货车已停用,无法绑定', 400); + } + + const targetCartId = Number(targetCartRow.cart_id || 0); + const targetCartCode = String(targetCartRow.cart_code || '').trim(); + const previousCartId = Number(taskRow && taskRow.current_cart_id || 0); + const bindType = previousCartId > 0 && previousCartId !== targetCartId ? 2 : 1; + + const transaction = await ctx.model.transaction(); + try { + const cartActiveBindingRows = await ctx.model.query(` + SELECT + b.id, + b.task_id, + t.task_no, + t.status AS task_status + FROM wms_pick_task_cart_binding b + INNER JOIN wms_wave_pick_task t + ON t.id = b.task_id + WHERE b.cart_id = :cartId + AND b.warehouse_id = :warehouseId + AND b.is_active = 1 + ORDER BY b.id DESC + LIMIT 1 + `, { + replacements: { + cartId: targetCartId, + warehouseId, + }, + type: ctx.model.QueryTypes.SELECT, + transaction, + }); + + const activeBinding = Array.isArray(cartActiveBindingRows) && cartActiveBindingRows.length > 0 + ? cartActiveBindingRows[0] + : null; + const bindingTaskId = Number(activeBinding && activeBinding.task_id || 0); + const bindingTaskStatus = Number(activeBinding && activeBinding.task_status || 0); + if (bindingTaskId > 0 && bindingTaskId !== taskId && [ 0, 1, 2 ].includes(bindingTaskStatus)) { + throw this.createBusinessError('该拣货车已绑定其他活动任务,无法重复绑定', 409, { + task_id: bindingTaskId, + task_no: String(activeBinding && activeBinding.task_no || '').trim() || null, + cart_id: targetCartId, + cart_code: targetCartCode, + }); + } + + if (previousCartId > 0 && previousCartId !== targetCartId) { + await ctx.model.query(` + UPDATE wms_pick_cart + SET current_task_id = NULL, + bind_user_id = NULL, + update_time = NOW() + WHERE id = :previousCartId + AND warehouse_id = :warehouseId + AND current_task_id = :taskId + `, { + replacements: { + previousCartId, + warehouseId, + taskId, + }, + transaction, + }); + } + + await ctx.model.query(` + UPDATE wms_pick_task_cart_binding + SET is_active = 0, + unbind_user_id = :operatorId, + unbind_time = NOW(), + update_time = NOW() + WHERE warehouse_id = :warehouseId + AND is_active = 1 + AND (task_id = :taskId OR cart_id = :cartId) + `, { + replacements: { + operatorId, + warehouseId, + taskId, + cartId: targetCartId, + }, + transaction, + }); + + await ctx.model.query(` + INSERT INTO wms_pick_task_cart_binding ( + task_id, + cart_id, + cart_code_snapshot, + warehouse_id, + bind_user_id, + bind_type, + is_active, + bind_time, + create_time, + update_time + ) VALUES ( + :taskId, + :cartId, + :cartCode, + :warehouseId, + :operatorId, + :bindType, + 1, + NOW(), + NOW(), + NOW() + ) + `, { + replacements: { + taskId, + cartId: targetCartId, + cartCode: targetCartCode, + warehouseId, + operatorId, + bindType, + }, + transaction, + }); + + await ctx.model.query(` + UPDATE wms_wave_pick_task + SET current_cart_id = :cartId, + current_cart_code_snapshot = :cartCode, + update_time = NOW() + WHERE id = :taskId + AND warehouse_id = :warehouseId + `, { + replacements: { + taskId, + warehouseId, + cartId: targetCartId, + cartCode: targetCartCode, + }, + transaction, + }); + + await ctx.model.query(` + UPDATE wms_pick_cart + SET current_task_id = :taskId, + bind_user_id = :operatorId, + last_bind_time = NOW(), + last_seen_time = NOW(), + update_time = NOW() + WHERE id = :cartId + AND warehouse_id = :warehouseId + `, { + replacements: { + taskId, + operatorId, + cartId: targetCartId, + warehouseId, + }, + transaction, + }); + + await transaction.commit(); + + const latestCartRow = await this.getPickCartById(targetCartId, warehouseId); + return { + task_id: taskId, + task_no: String(taskRow.task_no || '').trim(), + cart: this.buildPickCartDetail(latestCartRow || targetCartRow), + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + /** + * 创建拣货车。 + * + * @param {Object} params 创建参数。 + * @param {string} params.cartCode 拣货车编码。 + * @param {string} [params.cartName] 拣货车名称。 + * @param {number} [params.status=1] 状态。 + * @return {Promise} 创建结果。 + */ + async pickCartCreate(params = {}) { + const { ctx } = this; + const cartCode = String(params && params.cartCode || '').trim(); + const cartName = String(params && params.cartName || '').trim(); + const status = this.normalizePickCartStatus(params && params.status, 1); + const { warehouseId } = this.resolveOperatorContext(); + + if (!cartCode) { + throw this.createBusinessError('cart_code 必填', 400); + } + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw this.createBusinessError('缺少当前用户仓库上下文 store_id', 400); + } + + await this.assertPickCartCodeUnique(cartCode, warehouseId); + + const insertResult = await ctx.model.query(` + INSERT INTO wms_pick_cart ( + warehouse_id, + cart_code, + cart_name, + status, + create_time, + update_time + ) VALUES ( + :warehouseId, + :cartCode, + :cartName, + :status, + NOW(), + NOW() + ) + `, { + replacements: { + warehouseId, + cartCode, + cartName, + status, + }, + }); + + const insertHead = Array.isArray(insertResult) ? insertResult[0] : null; + const insertMeta = Array.isArray(insertResult) ? insertResult[1] : null; + const cartId = Number( + (insertMeta && (insertMeta.insertId || insertMeta.lastID || insertMeta.id)) + || (insertHead && (insertHead.insertId || insertHead.lastID || insertHead.id)) + || 0 + ); + if (!Number.isInteger(cartId) || cartId <= 0) { + throw this.createBusinessError('拣货车创建失败', 500); + } + + const cartRow = await this.getPickCartById(cartId, warehouseId); + return this.buildPickCartDetail(cartRow || { + cart_id: cartId, + warehouse_id: warehouseId, + cart_code: cartCode, + cart_name: cartName, + status, + }); + } + + /** + * 更新拣货车。 + * + * @param {Object} params 更新参数。 + * @param {number} params.cartId 拣货车ID。 + * @param {string} [params.cartCode] 拣货车编码。 + * @param {string} [params.cartName] 拣货车名称。 + * @param {number} [params.status] 状态。 + * @return {Promise} 更新结果。 + */ + async pickCartUpdate(params = {}) { + const { ctx } = this; + const cartId = Number(params && params.cartId || 0); + const { warehouseId } = this.resolveOperatorContext(); + + if (!Number.isInteger(cartId) || cartId <= 0) { + throw this.createBusinessError('cart_id 必填且必须为正整数', 400); + } + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw this.createBusinessError('缺少当前用户仓库上下文 store_id', 400); + } + + const cartRow = await this.getPickCartById(cartId, warehouseId); + if (!cartRow) { + throw this.createBusinessError('拣货车不存在', 404); + } + + const nextCartCode = params && params.cartCode !== undefined + ? String(params.cartCode || '').trim() + : String(cartRow.cart_code || '').trim(); + const nextCartName = params && params.cartName !== undefined + ? String(params.cartName || '').trim() + : String(cartRow.cart_name || '').trim(); + const nextStatus = params && params.status !== undefined + ? this.normalizePickCartStatus(params.status, Number(cartRow.status || 1)) + : Number(cartRow.status || 1); + + if (!nextCartCode) { + throw this.createBusinessError('cart_code 必填', 400); + } + await this.assertPickCartCodeUnique(nextCartCode, warehouseId, cartId); + if (nextStatus === 0 && Number(cartRow.current_task_id || 0) > 0) { + throw this.createBusinessError('拣货车已绑定任务,无法停用', 400); + } + + await ctx.model.query(` + UPDATE wms_pick_cart + SET cart_code = :cartCode, + cart_name = :cartName, + status = :status, + update_time = NOW() + WHERE id = :cartId + AND warehouse_id = :warehouseId + `, { + replacements: { + cartId, + warehouseId, + cartCode: nextCartCode, + cartName: nextCartName, + status: nextStatus, + }, + }); + + if (nextCartCode !== String(cartRow.cart_code || '').trim()) { + await ctx.model.query(` + UPDATE wms_pick_task_cart_binding + SET cart_code_snapshot = :cartCode, + update_time = NOW() + WHERE cart_id = :cartId + AND warehouse_id = :warehouseId + AND is_active = 1 + `, { + replacements: { + cartId, + warehouseId, + cartCode: nextCartCode, + }, + }); + + await ctx.model.query(` + UPDATE wms_wave_pick_task + SET current_cart_code_snapshot = :cartCode, + update_time = NOW() + WHERE current_cart_id = :cartId + AND warehouse_id = :warehouseId + `, { + replacements: { + cartId, + warehouseId, + cartCode: nextCartCode, + }, + }); + } + + const latestCartRow = await this.getPickCartById(cartId, warehouseId); + return this.buildPickCartDetail(latestCartRow || { + ...cartRow, + cart_id: cartId, + cart_code: nextCartCode, + cart_name: nextCartName, + status: nextStatus, + }); + } + + /** + * 删除拣货车。 + * + * @param {Object} params 删除参数。 + * @param {number} params.cartId 拣货车ID。 + * @return {Promise} 删除结果。 + */ + async pickCartDelete(params = {}) { + const { ctx } = this; + const cartId = Number(params && params.cartId || 0); + const { warehouseId } = this.resolveOperatorContext(); + + if (!Number.isInteger(cartId) || cartId <= 0) { + throw this.createBusinessError('cart_id 必填且必须为正整数', 400); + } + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw this.createBusinessError('缺少当前用户仓库上下文 store_id', 400); + } + + const cartRow = await this.getPickCartById(cartId, warehouseId); + if (!cartRow) { + throw this.createBusinessError('拣货车不存在', 404); + } + if (Number(cartRow.current_task_id || 0) > 0) { + throw this.createBusinessError('拣货车当前已绑定任务,无法删除', 400); + } + + const bindingRows = await ctx.model.query(` + SELECT id + FROM wms_pick_task_cart_binding + WHERE cart_id = :cartId + AND warehouse_id = :warehouseId + AND is_active = 1 + LIMIT 1 + `, { + replacements: { + cartId, + warehouseId, + }, + type: ctx.model.QueryTypes.SELECT, + }); + if (Array.isArray(bindingRows) && bindingRows.length > 0) { + throw this.createBusinessError('拣货车存在有效绑定记录,无法删除', 400); + } + + await ctx.model.query(` + DELETE FROM wms_pick_cart + WHERE id = :cartId + AND warehouse_id = :warehouseId + LIMIT 1 + `, { + replacements: { + cartId, + warehouseId, + }, + }); + + return { + cart_id: cartId, + deleted: true, + }; + } + + /** + * 查询拣货车详情。 + * + * @param {Object} params 查询参数。 + * @param {number} params.cartId 拣货车ID。 + * @return {Promise} 详情结果。 + */ + async pickCartDetail(params = {}) { + const cartId = Number(params && params.cartId || 0); + const { warehouseId } = this.resolveOperatorContext(); + + if (!Number.isInteger(cartId) || cartId <= 0) { + throw this.createBusinessError('cart_id 必填且必须为正整数', 400); + } + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw this.createBusinessError('缺少当前用户仓库上下文 store_id', 400); + } + + const cartRow = await this.getPickCartById(cartId, warehouseId); + if (!cartRow) { + throw this.createBusinessError('拣货车不存在', 404); + } + + return this.buildPickCartDetail(cartRow); + } + + /** + * 分页查询拣货车列表。 + * + * @param {Object} params 查询参数。 + * @param {Object} [params.pagination] 分页参数。 + * @param {Object} [params.where] 查询条件。 + * @return {Promise} 列表结果。 + */ + async pickCartList(params = {}) { + const { ctx } = this; + const pagination = params && params.pagination && typeof params.pagination === 'object' + ? params.pagination + : {}; + const where = params && params.where && typeof params.where === 'object' + ? params.where + : {}; + const { warehouseId } = this.resolveOperatorContext(); + + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw this.createBusinessError('缺少当前用户仓库上下文 store_id', 400); + } + + const page = Math.max(1, Number(pagination.page || 1)); + const pageSize = Math.min(100, Math.max(1, Number(pagination.pageSize || pagination.page_size || 20))); + const offset = (page - 1) * pageSize; + const keyword = String(where.keyword || '').trim(); + const status = where.status !== undefined && where.status !== null && where.status !== '' + ? this.normalizePickCartStatus(where.status, null) + : null; + const currentTaskId = Number(where.current_task_id || where.currentTaskId || 0); + const replacements = { + warehouseId, + offset, + pageSize, + }; + const filters = [ 'c.warehouse_id = :warehouseId' ]; + + if (keyword) { + replacements.keyword = `%${keyword}%`; + filters.push('(c.cart_code LIKE :keyword OR c.cart_name LIKE :keyword)'); + } + if (status === 0 || status === 1) { + replacements.status = status; + filters.push('c.status = :status'); + } + if (Number.isInteger(currentTaskId) && currentTaskId > 0) { + replacements.currentTaskId = currentTaskId; + filters.push('c.current_task_id = :currentTaskId'); + } + + const whereSql = filters.join(' AND '); + const countRows = await ctx.model.query(` + SELECT COUNT(1) AS total + FROM wms_pick_cart c + WHERE ${whereSql} + `, { + replacements, + type: ctx.model.QueryTypes.SELECT, + }); + const total = Number(countRows && countRows[0] && countRows[0].total || 0); + + const rows = await ctx.model.query(` + SELECT + c.id AS cart_id, + c.warehouse_id, + c.cart_code, + c.cart_name, + c.status, + c.current_task_id, + c.bind_user_id, + c.last_bind_time, + c.last_seen_time, + c.create_time, + c.update_time, + t.task_no AS current_task_no, + t.status AS current_task_status + FROM wms_pick_cart c + LEFT JOIN wms_wave_pick_task t + ON t.id = c.current_task_id + WHERE ${whereSql} + ORDER BY c.id DESC + LIMIT :offset, :pageSize + `, { + replacements, + type: ctx.model.QueryTypes.SELECT, + }); + + return { + list: (Array.isArray(rows) ? rows : []).map(row => this.buildPickCartDetail(row)), + pagination: { + page, + pageSize, + total, + totalPages: total > 0 ? Math.ceil(total / pageSize) : 0, + }, + }; } } diff --git a/app/service/systems/pickCart.js b/app/service/systems/pickCart.js new file mode 100644 index 0000000..cb449e0 --- /dev/null +++ b/app/service/systems/pickCart.js @@ -0,0 +1,88 @@ +'use strict'; + +const Service = require('egg').Service; + +class PickCartSystemService extends Service { + /** + * 按拣货车编码扫码查询。 + * + * @param {Object} params 查询参数。 + * @param {string} params.cartCode 拣货车编码。 + * @return {Promise} 拣货车信息。 + */ + async scan(params = {}) { + return await this.service.systems.pick.pickCartScan(params); + } + + /** + * 绑定拣货任务与拣货车。 + * + * @param {Object} params 绑定参数。 + * @return {Promise} 绑定结果。 + */ + async bindTaskCart(params = {}) { + return await this.service.systems.pick.wavePickTaskBindCart(params); + } + + /** + * 创建拣货车。 + * + * @param {Object} params 创建参数。 + * @return {Promise} 创建结果。 + */ + async create(params = {}) { + return await this.service.systems.pick.pickCartCreate(params); + } + + /** + * 更新拣货车。 + * + * @param {Object} params 更新参数。 + * @return {Promise} 更新结果。 + */ + async update(params = {}) { + return await this.service.systems.pick.pickCartUpdate(params); + } + + /** + * 删除拣货车。 + * + * @param {Object} params 删除参数。 + * @return {Promise} 删除结果。 + */ + async delete(params = {}) { + return await this.service.systems.pick.pickCartDelete(params); + } + + /** + * 查询拣货车详情。 + * + * @param {Object} params 查询参数。 + * @return {Promise} 详情结果。 + */ + async detail(params = {}) { + return await this.service.systems.pick.pickCartDetail(params); + } + + /** + * 分页查询拣货车列表。 + * + * @param {Object} params 查询参数。 + * @return {Promise} 列表结果。 + */ + async list(params = {}) { + return await this.service.systems.pick.pickCartList(params); + } + + /** + * 拣货车编码查重。 + * + * @param {Object} params 查询参数。 + * @return {Promise} 查重结果。 + */ + async codeDuplicateCheck(params = {}) { + return await this.service.systems.pick.pickCartCodeDuplicateCheck(params); + } +} + +module.exports = PickCartSystemService; diff --git a/app/service/systems/setting/expressInterface.js b/app/service/systems/setting/expressInterface.js index 291d54b..7cbefae 100644 --- a/app/service/systems/setting/expressInterface.js +++ b/app/service/systems/setting/expressInterface.js @@ -274,6 +274,12 @@ class SettingExpressInterfaceService extends Service { shop_id: { field: 'shop_id', }, + template_id: { + field: 'template_id', + }, + brandno: { + field: 'brandno', + }, sender_name: { field: 'sender_name', }, @@ -724,6 +730,11 @@ class SettingExpressInterfaceService extends Service { warehouse_id: row.warehouse_id === undefined || row.warehouse_id === null ? null : Number(row.warehouse_id), shop_id: row.shop_id === undefined || row.shop_id === null ? null : Number(row.shop_id), platform_shop_id: row.platform_shop_id === undefined || row.platform_shop_id === null ? null : Number(row.platform_shop_id), + template_id: row.template_id === undefined || row.template_id === null ? null : Number(row.template_id), + paymode: row.paymode === undefined || row.paymode === null ? null : Number(row.paymode), + brandno: this.normalizeOptionalText(row.brandno, 'brandno', 255), + providertype: this.normalizeOptionalText(row.providertype, 'providertype', 50), + providerid: row.providerid === undefined || row.providerid === null ? null : Number(row.providerid), platform_code: this.normalizeOptionalText(row.platform_code, 'platform_code', 20), sender_name: this.normalizeOptionalText(row.sender_name, 'sender_name', 50), sender_tel: this.normalizeOptionalText(row.sender_tel, 'sender_tel', 11), @@ -1048,6 +1059,7 @@ class SettingExpressInterfaceService extends Service { { district_name: { [Op.like]: `%${keyword}%` } }, { site_code: { [Op.like]: `%${keyword}%` } }, { product_type: { [Op.like]: `%${keyword}%` } }, + { brandno: { [Op.like]: `%${keyword}%` } }, { shop_name: { [Op.like]: `%${keyword}%` } }, ], }); @@ -1059,7 +1071,7 @@ class SettingExpressInterfaceService extends Service { }, include: this.getInterfaceInclude(), attributes: [ - 'id', 'name', 'express_code', 'warehouse_id', 'shop_id', 'platform_shop_id', 'platform_code', + 'id', 'name', 'express_code', 'warehouse_id', 'shop_id', 'platform_shop_id', 'template_id', 'paymode', 'brandno', 'providertype', 'providerid', 'platform_code', 'sys_express_code', 'sender_name', 'sender_tel', 'weight', 'viewer', 'client_id', 'is_share', 'province_name', 'city_name', 'district_name', 'site_code', @@ -1203,6 +1215,32 @@ class SettingExpressInterfaceService extends Service { allowEmpty: true, min: 1, }), + template_id: this.normalizeInteger(data.template_id !== undefined ? data.template_id : data.templateId, 'template_id', { + allowEmpty: true, + min: 1, + }), + paymode: this.normalizeInteger(data.paymode !== undefined ? data.paymode : data.payMode, 'paymode', { + allowEmpty: true, + }), + brandno: (() => { + const normalizedBrandNo = this.normalizeOptionalText( + data.brandno !== undefined ? data.brandno : data.brandNo, + 'brandno', + 255 + ); + return normalizedBrandNo === '' ? null : normalizedBrandNo; + })(), + providertype: (() => { + const normalizedProviderType = this.normalizeOptionalText( + data.providertype !== undefined ? data.providertype : data.providerType, + 'providertype', + 50 + ); + return normalizedProviderType === '' ? null : normalizedProviderType; + })(), + providerid: this.normalizeInteger(data.providerid !== undefined ? data.providerid : data.providerId, 'providerid', { + allowEmpty: true, + }), sender_name: this.normalizeOptionalText(data.sender_name || data.senderName, 'sender_name', 50), sender_tel: this.normalizeOptionalText(data.sender_tel || data.senderTel, 'sender_tel', 11), weight: this.normalizeInteger(data.weight, 'weight', { @@ -1275,6 +1313,16 @@ class SettingExpressInterfaceService extends Service { || Object.prototype.hasOwnProperty.call(data, 'shopId'); const hasPlatformShopId = Object.prototype.hasOwnProperty.call(data, 'platform_shop_id') || Object.prototype.hasOwnProperty.call(data, 'platformShopId'); + const hasTemplateId = Object.prototype.hasOwnProperty.call(data, 'template_id') + || Object.prototype.hasOwnProperty.call(data, 'templateId'); + const hasPaymode = Object.prototype.hasOwnProperty.call(data, 'paymode') + || Object.prototype.hasOwnProperty.call(data, 'payMode'); + const hasBrandNo = Object.prototype.hasOwnProperty.call(data, 'brandno') + || Object.prototype.hasOwnProperty.call(data, 'brandNo'); + const hasProviderType = Object.prototype.hasOwnProperty.call(data, 'providertype') + || Object.prototype.hasOwnProperty.call(data, 'providerType'); + const hasProviderId = Object.prototype.hasOwnProperty.call(data, 'providerid') + || Object.prototype.hasOwnProperty.call(data, 'providerId'); const hasViewer = Object.prototype.hasOwnProperty.call(data, 'viewer'); const hasClientId = Object.prototype.hasOwnProperty.call(data, 'client_id') || Object.prototype.hasOwnProperty.call(data, 'clientId'); @@ -1304,8 +1352,8 @@ class SettingExpressInterfaceService extends Service { if (!hasName && !hasExpressCode && !hasPlatformCode && !hasSysExpressCode && !hasSenderName && !hasSenderTel && !hasWeight && !hasWeightType - && !hasShopId && !hasPlatformShopId - && !hasViewer && !hasClientId && !hasIsPickup + && !hasShopId && !hasPlatformShopId && !hasTemplateId && !hasPaymode && !hasBrandNo + && !hasProviderType && !hasProviderId && !hasViewer && !hasClientId && !hasIsPickup && !hasShipperNo && !hasTemplateUrl && !hasProvinceName && !hasCityName && !hasDistrictName && !hasAddress && !hasTownName && !hasSiteCode && !hasProductType && !hasShopName && !hasExtData) { @@ -1394,6 +1442,55 @@ class SettingExpressInterfaceService extends Service { ); } + if (hasTemplateId) { + updates.template_id = this.normalizeInteger( + data.template_id !== undefined ? data.template_id : data.templateId, + 'template_id', + { + allowEmpty: true, + min: 1, + } + ); + } + + if (hasPaymode) { + updates.paymode = this.normalizeInteger( + data.paymode !== undefined ? data.paymode : data.payMode, + 'paymode', + { + allowEmpty: true, + } + ); + } + + if (hasBrandNo) { + const normalizedBrandNo = this.normalizeOptionalText( + data.brandno !== undefined ? data.brandno : data.brandNo, + 'brandno', + 255 + ); + updates.brandno = normalizedBrandNo === '' ? null : normalizedBrandNo; + } + + if (hasProviderType) { + const normalizedProviderType = this.normalizeOptionalText( + data.providertype !== undefined ? data.providertype : data.providerType, + 'providertype', + 50 + ); + updates.providertype = normalizedProviderType === '' ? null : normalizedProviderType; + } + + if (hasProviderId) { + updates.providerid = this.normalizeInteger( + data.providerid !== undefined ? data.providerid : data.providerId, + 'providerid', + { + allowEmpty: true, + } + ); + } + if (hasViewer) { updates.viewer = this.normalizeOptionalText(data.viewer, 'viewer', 50); } diff --git a/app/service/systems/shops.js b/app/service/systems/shops.js index 46fd91c..3aaf497 100644 --- a/app/service/systems/shops.js +++ b/app/service/systems/shops.js @@ -11,6 +11,45 @@ const { * 店铺业务服务。 */ class ShopsService extends Service { + /** + * 生成待授权占位店铺名并校验唯一性(最多重试 5 次)。 + * + * @param {Object} payload 入参 + * @param {number} payload.warehouseId 仓库 ID + * @param {string} payload.platformCode 平台编码 + * @return {Promise} 可用的占位店铺名 + */ + async generatePendingShopName(payload) { + const { app, ctx } = this; + const { Op } = app.Sequelize; + const { warehouseId, platformCode } = payload; + const maxRetryTimes = 5; + + for (let attempt = 1; attempt <= maxRetryTimes; attempt++) { + const shopName = `PENDING_${this.generateAuthorizeRandomCode()}`; + + const existed = await ctx.model.Shop.findOne({ + where: { + [Op.and]: [ + { + warehouse_id: warehouseId, + platform_code: platformCode, + shop_name: shopName, + }, + buildNotDeletedShopWhere(app), + ], + }, + attributes: [ 'id' ], + }); + + if (!existed) { + return shopName; + } + } + + throw this.createError('系统生成占位名冲突,请重试', 409); + } + /** * 创建业务错误。 * @@ -362,12 +401,9 @@ class ShopsService extends Service { required: true, maxLength: 100, }); - const shopName = `PENDING_${this.generateAuthorizeRandomCode()}`; - - await this.ensureShopNameUnique({ + const shopName = await this.generatePendingShopName({ warehouseId, platformCode, - shopName, }); const created = await ctx.model.Shop.create({ diff --git a/app/service/systems/stock_store.js b/app/service/systems/stock_store.js index 4275edf..cb809f5 100644 --- a/app/service/systems/stock_store.js +++ b/app/service/systems/stock_store.js @@ -202,7 +202,7 @@ class stockStoreService extends Service { // ⭐ 关键修复:使用 raw: true 获取纯对象 const itemInfo = await ctx.model.StockStore.findByPk(itemId, { - attributes: [ 'id', 'stock_id', 'warehouse_code', 'item_code' ], // 按需增加字段 + attributes: [ 'id', 'stock_id', 'warehouse_code', 'item_code', 'item_name' ], // 按需增加字段 raw: true, // ⭐ 必须:转换为纯 JavaScript 对象 }); diff --git a/app/service/systems/store.js b/app/service/systems/store.js index 4e4cc47..dff7cff 100644 --- a/app/service/systems/store.js +++ b/app/service/systems/store.js @@ -650,7 +650,7 @@ class StoreService extends Service { const role_code = isStore ? 'store_admin_default' : 'warehouse_admin_default'; const adminRole = await ctx.model.Role.findOne({ where: { - store_id: 0, + store_id: null, role_code, }, }); diff --git a/app/service/systems/store_warehouse.js b/app/service/systems/store_warehouse.js index a2b794e..6a02cf0 100644 --- a/app/service/systems/store_warehouse.js +++ b/app/service/systems/store_warehouse.js @@ -2197,6 +2197,7 @@ class SettingStoreWarehouseService extends Service { contact_person: contactPerson || null, contact_phone: contactPhone || null, email, + callback_url: this.normalizeText(data.callback_url || data.callbackUrl, 'callback_url', 500) || null, is_enabled: isEnabled, }; @@ -2511,6 +2512,202 @@ class SettingStoreWarehouseService extends Service { return config; } + + /** + * 仓库代货主一键开户:注册账号、创建货主、签约三步合并。 + * + * @param {Object} [data={}] 请求参数。 + * @param {string} data.username 必填,登录账号。 + * @param {string} data.password 必填,初始密码。 + * @param {string} [data.real_name] 可选,真实姓名。 + * @param {string} data.company_name 必填,公司全称。 + * @param {string} data.business_license 必填,营业执照号。 + * @param {string} data.contact_person 必填,联系人。 + * @param {string} data.contact_phone 必填,联系电话。 + * @param {string} [data.legal_person] 可选,法人代表。 + * @param {string} [data.contact_email] 可选,联系邮箱。 + * @param {string} [data.address] 可选,公司地址。 + * @param {string} [data.industry] 可选,所属行业。 + * @param {string} [data.logo_url] 可选,Logo链接。 + * @param {string} [data.domain] 可选,绑定域名。 + * @param {string} [data.auth_start] 可选,授权开始日期,默认当天。 + * @param {string} [data.auth_end] 可选,授权结束日期。 + * @param {number} [data.print_quantity=0] 可选,初始面单余额。 + * @param {string} [data.apply_reason='仓库代开户'] 可选,申请原因。 + * @param {string} [data.store_remask] 可选,货主备注名(≤50字符)。 + * @param {string} [data.warehouse_remask] 可选,仓库备注名(≤50字符)。 + * @return {Promise} 包含 store_id、account_id、contract_id、company_name、username 的响应对象。 + * @throws {Error} 当前主体不是仓库时抛出 403,账号/公司名重复时抛出 409,参数校验失败时抛出 400。 + */ + async openAccount(data = {}) { + const { ctx } = this; + + // 1. 获取当前主体,必须是仓库 + const currentSubject = await this.getCurrentSubject(); + if (!currentSubject.isWarehouse) { + throw this.createError('仅仓库主体可执行代开户操作', 403); + } + + // 2. 获取当前账号 ID + const accountId = this.getCurrentAccountId(); + + // 3. 密码自动生成 + if (!data.password) { + data.password = crypto.randomBytes(8).toString('base64').replace(/[+/=]/g, '').slice(0, 12); + } + + // 4. 必填字段校验 + const requiredFields = [ 'username', 'company_name', 'contact_person' ]; + for (const field of requiredFields) { + if (!data[field]) { + throw this.createError(`${field} 参数不能为空`, 400); + } + } + + // 5. 公司名称唯一性校验 + const existingStore = await ctx.model.Store.findOne({ + where: { company_name: data.company_name }, + }); + if (existingStore) { + throw this.createError('公司名称已存在', 409); + } + + // 6. 账号唯一性校验 + const existingAccount = await ctx.model.Account.findOne({ + where: { username: data.username }, + }); + if (existingAccount) { + throw this.createError('账号已存在', 409); + } + + // 7. 备注长度校验 + const storeRemask = this.normalizeText(data.store_remask, 'store_remask', 50); + const warehouseRemask = this.normalizeText(data.warehouse_remask, 'warehouse_remask', 50); + + // 8. 规范化日期 + const authStart = this.normalizeDate(data.auth_start, 'auth_start', { allowNull: true }) || new Date(); + const authEnd = this.normalizeDate(data.auth_end, 'auth_end', { allowNull: true }); + + // 9. 在事务中依次执行注册、创建货主、签约 + const transaction = await ctx.model.transaction(); + + try { + // a. 创建账号 + // email 兜底:不传时生成占位邮箱,避免 Account model 的 notEmpty + isEmail 校验报错 + const email = data.contact_email + ? data.contact_email + : `${data.username}@placeholder.local`; + // real_name 兜底:不传时使用 contact_person(必填字段,长度 ≥ 2),避免 notEmpty + len[2,50] 校验报错 + const realName = data.real_name || data.contact_person; + + const registerResult = await ctx.service.systems.auth.user.register({ + username: data.username, + password: data.password, + email, + real_name: realName, + }, transaction); + const userId = registerResult.userId; + + // b. 创建货主 + const storeData = { + company_name: data.company_name, + business_license: data.business_license, + legal_person: data.legal_person || null, + contact_phone: data.contact_phone || '-', + contact_email: data.contact_email || null, + contact_person: data.contact_person, + address: data.address || null, + industry: data.industry || null, + account_id: userId, + status: 1, + created_by: accountId, + is_warehouse: 0, + logo_url: data.logo_url || null, + domain: data.domain || null, + auth_end: authEnd, + }; + + const store = await ctx.model.Store.create(storeData, { transaction }); + + // c. 创建签约关系(auth_status=2 已通过,仓库代开户无需审核) + const relationData = { + store_id: store.id, + warehouse_id: currentSubject.id, + auth_status: 2, + apply_reason: this.normalizeText(data.apply_reason, 'apply_reason', 2000) || '仓库代开户', + apply_time: new Date(), + print_quantity: this.normalizeNonNegativeInteger(data.print_quantity, 'print_quantity', 0), + print_quantity_locked: 0, + review_time: new Date(), + auth_start: authStart, + auth_end: authEnd, + actual_end: null, + applied_by: accountId, + reviewed_by: accountId, + ended_by: null, + use_status: 1, + }; + + if (storeRemask !== null) { + relationData.store_remask = storeRemask; + } + if (warehouseRemask !== null) { + relationData.warehouse_remask = warehouseRemask; + } + + const relation = await ctx.model.StoreWarehouse.create(relationData, { transaction }); + + // d. 分配货主管理员角色 + try { + await ctx.service.systems.store.assignAdminRoleToCreator( + store.id, + userId, + data.real_name || '', + transaction, + true + ); + } catch (roleErr) { + throw this.createError(`分配管理员角色失败: ${roleErr.message}`, 500); + } + + await transaction.commit(); + + // 记录操作日志 + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'store', + businessId: relation.id, + operationCode: 'STORE_OPEN_ACCOUNT', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: Number(currentSubject.id), + storeId: Number(store.id), + accountId: Number(userId), + }, + beforeChanges: null, + }); + } catch (logErr) { + ctx.logger.warn('[storeWarehouse.openAccount] 写入操作日志失败,不影响业务', logErr); + } + + return { + code: 200, + data: { + store_id: store.id, + account_id: userId, + contract_id: relation.id, + company_name: store.company_name, + username: data.username, + }, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } } module.exports = SettingStoreWarehouseService; diff --git a/app_service_systemMethods_index_head.js b/app_service_systemMethods_index_head.js new file mode 100644 index 0000000000000000000000000000000000000000..d2654f980643c1d9628a35d5b68280d65340c484 GIT binary patch literal 178012 zcmeFa4|JW?btig(bXJ>WI&HFsX)u&)2$A?FWCG1VLx_+Kn1CfqvSnG8C0mjuVO{B3 zzQ#7T?2-gKOiL5;SxqK=P12UvVTzk%5<*fk6T+WKoRrMGHPac$r0d0^NM$E03b_Lc5;&OZC>v;Uuc&iBUaO{HC>ou$!Inf|YpW=a#K zVft(;{d(!2mfo8F8!k<)` zey%E27Wy=mE?t0XLL8>ndrMUsb2Y(p>=xG=IwT}M3eF38; z8mmS>RT}GhqQq6DvC{6+m9%12qD@Qs{}heBi!kB;Thb9L)RNm=MRS~{=a~J>3BJj~ zs;6{Qoj8rAW46#3TWGAU>Hms{IX*;&I1npOqZlQl0Xe5SuRcRB= zp}BM;QM{e-Sy|ejwnF>WrSMKYv3IEQ!rtquS5BTiarMUb&mJw`yC$jJvhl~`eM$59E8~Bf zEWi4DV^`6-s%&4C&JTQ4rr*k?+L4DozGK_Nb1NoCMxRLjeDL0`CzF@gSEmkr^2W4< zw)`OR#ulRX7LxCBX&?0lm)}KyPZBqP>o+7{+tK+FL%A*C{^imK(-o>wn;DW*^c1}_ zMZCA4zS~6*CR1pP&Bo*pH$Slbwq*C76|;bOwEWuKh4(*m;JNDA6BA>PkDgm8pXep{ zU6pFCZ3JtIc&A2lh7K#Ix@c!sP`D~aVKF3Uu%>kyR~!$;rU*|a5n8z920I|WQ;3ISEulY7PNm{emknquDf>sH|K8r z?BV&=`{uWO`-SeL{rH9VUsru=-+%6IKJrS}ANMY+HLv)a*|ka6P`*TWklnhI<_SFv z8zKJ9YWjOLwH_?p_tXxK-9P&X*{ZY78c#0k|LCssrs6X0LN#p#!|O^`PMp*F?g@sG zZxL8#Z>Lp(MH1|qJ$!AsHF>*AYs&ty^k%;HXZ)Vhdx#RX)bkxB9)V?XTeT1eL!YY- zXrgwuMQchmIyezOm}v}3Gx1`XY_?!{J^cmS!nS&rcth+QAmOPCNi@$sT1B-f_Waq3 z)yQYTI5om|n#O>K04u4Z3w_{W#`}b*R4)v*nD88h4}H4T2iK*QXlM1TKt93&yhk47DVjm$1myUd zgNNfh0e-PLYmoc|hAjM9UvHVQ^oD1}{Ey%4S&2mGn6VY~TiTF@(^W*wTOmJRW)OoG zZf!$^&Vs~&J7RFmHg@kV)DPBjkXC39(U@cS!4zT)T2>z$I_9~ZAWu2)chcX$IW|IG zKYJ9&$F@{TK>b02+t{e}!m+W~naWW01gDF>RgI@D?4HPSjHdKJY>-WvP+J??E?UKr zg3v;3ZD{IYsNO+dhhwR*w;R%IE}Tmp3EM){gHN=Re#{jFhv<0Vq;TvO8Z!pd9Xr16 ziy1u*)g52u2~jm-Mb-|Yp%#Nh9&8gAvF=$O;(uGWb@)rke;qtp-oN(ZnYGEY>;Aq! zsq8&;?j_5r?GsNNPbxQU%J&RoIfJ6v0(g_(PhMI-y?%YtH2$d}_@*z_o;`5m>xb^k z%LGgjb>W#HUola-n|Mxqb2|b@hC-~p#2umNUOWJ?BcV2aY-anCzRv&~q`sD}h~LtV zopf}Go3yVRuXiPfTE8=P@y6@#{P3=WM~+Qhy6;$W@4%1x-aYa3eg81AG5O%@h~R&3 z^A+p9mHcGrFNgoh#=q-0THe#~4CR~t<()^%dprJW<0BLyT(terC--z5*!5I$?T7zo z<>9%#9S`;T`KMP7Ja^!hsh;FZrF{NyeSGApHR~)IwOk6}9*-Qh(#lWMszcXKr4h-~ z$$8H|G4!3eqvdtA-5sCbf7ZcAcf58t=a$Yo_{hlWYEs!U-+th>joGmTTYcoOMko(E zL7#|lW{9)4IvI0B6`{G<{9yXl@BwD%hqK#u{#_{nFFOpmOc6&Y<_KY7MjW=+EHOs7 z7c^8nIv8HiYVccO^;P0_Qa@nce?rp0-$iEJ;>=b(SlfOz221?1rGN#m8kS#S4N!Iu z`lm`6fQghI94CE%=ANaUq^+B?!QaR&3fDDLp55eh(FCH+z)PAf%vv2#8MX+y3K<EfEIqZ+n5&s9IS?W}`;-IcFV8nHNSsoZU$SRMA}iDYW) z{rfo^eQfTLbmSj*NhTUuY2cErC;ZjbG2+(8UN7y@LTj><_6VRIfTaroxTrng*ruO$ z7V@e6?7COyKU;fm`MLhK+LgTzZ2$J$v+I6)Xj!#w;qbOP}9wC(+u+Pv`IV5Fcd3+!>iKb^E>I?Nj(9NCIu=LmgDQmTl<^(U4t)9ZcLVK$hY3gIq#?aX4d|SBfLn~ z>^$lfTd+^TmKgiar>jl*%klS&|HT8x=Du1z_mbu#Kkkxvnyo6Y>Sa`Kf#2Nxe@L4l z@|a2OWD!fVlRQ#e(#3+tY)x3->N*tDv)VqaUu|9P#_HG;h8FU5d67BCW-K14ND^dA z^@ERtEjPZ6Kz~~reSAlP8aYp@)gG!XbmRKI+N)jvy?=dj#rPeA+a|ug1AO(|y0gyu zZt{iRAJpDGQLRBfE?$u@ckDHD_857oEi|iRR3X0wW+OGzHL~oTmES)@9POfmJ3ual}U&3t}5)^m4qSu;w@x>q1~<|Uf~Ll zE9q~pz+nEllI$Y1JL2XMY6s4Q{1lb9c4`lJ6ZAPvaX#|!aVp9FA~FEkEg=`CkC(?u zan8>l2@(N~-{fJ1EG%|ub)8X-Hcc&I6GUR-TnJlm`Q}%rujqeh|DPqVbe&uI?)3kD z{Pg0;xMlG9(WQp0CuxeYm)AeIm8+HVxHcpQEM=p~m#drK2th&A_0!^d@SfH^*2nSi zHi~gzjJCEMh(=bu;m11pZ(54{v17ToJbeJ0S2TVSDw!O-xCkVF zUeF@-Xpqnv_%?H&l@-Ku{Gfstd8s^_X}(Q*;?wOH({jjY#`wU8EITJMlFc9Z*5)vK zZPYh+vFmX(Ff4=ZdvIRXr&Qxqa&cHZg=T5~S@ev_l})qQYH)9*xa$plKY9ATwt>%n z=F4kqgJ&PSeEj?wSfh6y`A9-y5Ex-Lo$B&lp zAO2p)pCso$|G@UAlP}MF{;vE?m+B_Wn)lQ(5A18I#W2TsU^pvU!D>i_C?JY8min4@ zvdG9VmrLdh#ae`{jmdj}*a#g2ek?Xoi_y8@B?`W)(kcU?$QtsPkX^omK9LO%(+k=q zHgDTPW&=wdl} zjDCC(!_%IvuUG6n7?laXr9Y~2ZfqT(d$4ji55V<{&FSAe>2K^kV4dt0l>I5-&ASG+ zrZU&d-l?(qMBs4j7ak*QTVriw_LTK$te3yf1l0nMzKkdbz#xizVw678mYl1qaD_zb$<#lZDGFuv~Zh3P+=N-Ok*XeM0^ z*Mj!dZhqs2>SsUm|K8udt|NJ&74|Y2erckk`nO$`(PeY9o8H!QUA0=feDiI|Yjbbk z_vm!{Te{ahKKIyseulxdM)2xp7V2NwDwIo?9{CUR7tgQ-j_37UONl+P-3z-yawdgg zJU$o84Z7IyE-k9!kRw$s#BgNaDrN;?(~#3gPQaEQo|(YqyjwG^nLBrARC6BqJB*Vp ziKa%f+w)kl9Gc36Icm1vP@NGP$;J!vVsfYI1LZ!n@hQ>o%$w&SvTu(p>!i?4dZ6Zw zcUnwZ*bw+hBi7vHpv6U9J`J$?F7}~F%J13l^(#s_UKd>*S2wUP{U~Mk@7i(Ek^WEp zpmuDoeD#F`>_4-Xc(v=C)>Gj*o16uEV6Me1(e7KxvgiN2zf9-u`sgpyUrs82xcRkD zoOSSPJIq+%*9RY;`{um({-Swe(yl(QE$c;nT-S53eTAkJYxnGzJ!9X-o$={#qIt1C zovj;0yRZ)3=jAB=v3VV)|5&fZGkp_iw_;vzOi~6?pC-Io;^m0Pb}BIClgjYevg|fn zDU*t}RGTzXi&l^Srn|Dg)K?j$>du}k_peX71|RI^9mqb)aEy$a8oNkEm8)G5x!?o_ z=Q?byS1y^*VGnq|IC-44KP!8^sD^+Sr4@v1q0OCN@kdR_HYI(F(4V|x>)LxzJ*+WQP>zIHS%5)j^Hj&VS-J?B{O#&)1hztOk3 z>O;py&Gx6Eq131L;Y+2Pz4oHlm4Hp{nBgp~UznJUd&S>m5zC zC#a=9txY?`k-ncDikLw%Q;y8aj;n)=kW*G;pOx(04s!8wPo zC2Mxv_~N6}D<=1hE~~a~sZRGM$G6=#`%6cjzHiHp!?p6&?;E*hjx2=Ubo>9ct2m}H3+gA9N-Vi1rUz|BR2l%q1S#@#--!(0>Z=dZK7 z)_m#_r^Tmeor|q-Y&@BJ3vmxJg1A!$Cv5F8%(c{&u-k;`pN+eW&XViG3(2e7CY#D` z>o9Fy91){}C;40q_V_p}AE$J@KFh{H=8L$|9z%B$21&!ROh995<(BLbOLdk=6R?*b zU7HEQpKst`sqp1ry;y0BOk)^ok+VmF13qo38&5S-TdECNTS5cIscCAa82xY_4|=Ye z@+$PKK#uXM*(T1bF7{h2tY!U#Uu~FSezn`=@vGh1=GV~LVAi@5Wa~b6MOa_pPCmfR z;)w99IoqL7++8YjJmd+cDMm&tjGg30M|9z2jX6xC;cP{tV@dz4F}U)SD>iWJO`~JE zaI(k58lw_*auMSxjI6Oxg$^GN7Qp1iM&}uW7sJ8b=>$*d4yMUrwvI7Rtu9uxn6Pjs z!c=+=DXdqZ$@JWEalK;qv-OJoEarE(<3h9er?14@uv=p_HAXY3ir-DjA_ib?$L{Mkv$P_&wrjx<9z%D7t!JF{KE7O)4P!F5#A$<<~i|TZ=^+!=p zB41|RxeIMtGU3K#7x=_*nj(mDM^LuqsShWC+Xzl_Qg5m0ByjU^l6HItEMm9CVB$l| z8b73Gv39C!L)=-EGi~WF&XIOMQM^SxsB?E$eHE4UWW?3*=?uZeK}EW|}2-iz~H5uUSSSJ*F5CXdRo*dh!qHg~(V zaK+M$Ezn|PV{H(#BijS{$EdMcxou(p*na8xS3cuiKLo@Cpg7`0oW;T!KIFz)>0doK zh53bdSrA3QFLmdU1wXqdaAYjQsiK@6e9CNB~?EKz&zQFT&)wMswNRCB3Lm*-Q7&bW%n0vbneS72R8{e*EqGWDoT6 z$=B}QedHhdAK1=!rt#ikewAn59xG$XZx9%u+vu*|&+`mb3Ypa{vqaIK%{|tYv{t>O z!F6Y|n>bf?2)j})*8S9zyTj^B$cVSc%N7Xou#@bJzl$EqgU4GJu`F5ptRf}QuaG*m z9{9$zs@W3Gv+B1ZmLk+>A7&}lZr z6XyPr{vBFfeHvR$wLQ8%GFx+v;yN?tffczE#a`8HK3ME-w^9`RSKnA|shrid&zt+W~}@fttP(<6({wLV#-au)G+(jH>z)&>tADz0Jzpw zsx-_!Uy+LXA%iz;xVMuW!vnHsSwt^z?g!F{bDu7S>xZBia1A%_YunOMFJIygckFn` zs>t6iRMs!paT9unTl(~qy>^b&WMvp0SFMbt`<$qnLwtTyYRNVB5}h?ldVt@shBMG^ zJxsVBHl_)s9ya#ey<5h$g0X(94UHf7UBkO0F_@S?e&YL5VJ#Q3r z(AsG(DDbe=R0ngTf{@^xLUZV=%%>czTLj7KTF+Q<(Z)|LsLcX_MKjb!=GiEInn>Ll| zhX+q-@er2+hU;r((X)|Ro4&g1g%+cm384`T#JjZnW_ht$G!W0TNE>^7q^CKbo#g$p z4{Uxb-wEd8#hO($Cig(*{K{!iH!i8-7qPtBn1+2sw@tQZ=(hGVJHXGyF}@2G(<|}H zUDxJgEE_AKL9uGy5In%l-gAx3NFuwXfvUEE@5W@x+W$9(XGmrNH&oXgj^@NSVJ>#( zYu1WQ7!geIH!T1H@?LrGRxqhy%0+yqGRAX_*)ohD<3GV6s~XzYUox9Kh@t)2#vm2l z$&F!T*Q26l3cD@!;bOx;{<^;YN@wgghkBcK!5&R87VYd>PP?_Va=+!9SxrrDR_Vqy zIo8|cS{trtGSTKX%uvSH?vH+1alYHy*5#OY`Pk2{>yQ?X>0-tW(dZReGaPn}&ZW#8&vT@TI_r~#382LDvbmS^d zsnf5oZ`Q1074(hHFa|FVW9ipMJfNp-q!-_n7}ln;e{J%S?&q7|ni|Tk!;Dv*pA2hi z))IwI0EFimvt0H}On8mhFdJIP27#i*aFM;25ERpr*<<=M5NqYyv{*lBZ$J0r6#IE` z>t^>84ae5aein{Z+&0q41*ddyQp=5Ee4@EE%-pu1=AAeyb{EPZ@XzP!nF>1c$b7?EIX~~3}Wrbrn6|Eoi=aY?-z-D`)0T-y}65{isJZ|gb;=FD5Qy#LvS9n=#<@OP(lDi@=q(VYv02UUA!k4xD8U$UlpLF1v=Id+eg^{_!4S36sKO@jwbF$_N*uBFZlH7{7 zoT^!HH%P2zPTrf^Y@Oc;-GU8F^I(B{Ys86mjRNBH5LekX8;};eU%ZcKef05Tcg@k- zH5hi~jCqbIG!o{^8QiQ9^4FbbDHsdP{C-?h(^x<074xX1Ld~X+`mu|nYaVo^LA>rI zhB;GHVv9UH^QmmZQ_RAZlB!AFe1%|C9D?+S&D8d&_?#y0s14iVu$_@xeVI;N7u&rc zqoHwCm)LsAln>KywDo~dhc%-8%&paJAzk9@3aNrK$BSt)84V{0uoJ61AJR8AHnF~p zd6vA}5>uZ>dGl)%*Yec2PI-F4zKK#eFt&1e&=$Lv`S5u?x!tN@Wwh|K%*D3yMLAnF zMg5#Dee3Z6<;AXCKEvgTgD*ng%e5z`1~;Ksg?Z4?<^`myV|b#LiMmwJU$J7>2d;Z%>VbqA+*WZBnu zWh;gS&WYYhyou9+%~XH7pZI zt-Z{{j()dMei4=7qk+g7J@l-;^q0?Kbl~|n(`bD58cgjg=ZF91A7j*0isG2LyXi+ zzvIWotj+NaM8bUDGHtO`e6y`p%ZdtDKc$Hs76rvx-?2w#`l+h2tJz zBw6^0G}m6C`Pt8G`r7dl*2(QBv6S5}&m*=W<+Zk9Gfv{I+K}vLc0YHe?Vj#a?F)XA zRTfz>*H-TqS$|@Mc%9b}Csk-C1XWAObeT6vbkVowEe-q@3sk91dZT4YB%Ym$8&xD* z;d>SSJrsIB9p)(aytsBt>4udsX~plBM_tX-0>9x6jnniG)KMzKF5m`=&@(=%Dss2f z_quc?hg!cg_H=UI^G^)%n~dakmS3Cv#nz;9aO}XYr|7*H|FiP&+}@5`rh1YumGa-n zse0l4)*JLbKvt_vGnX6rWvmsGcpt~AJ@0tSpCwmpvEOCw^2}DEAMYySUOK=tvEP^+ z*z~LO-%YMAU$mWh{IXK)EfnLl3Og6xKhaJ4tB3Hy9akgtz7E_3H<7-93BED%M|uZu zvoQmlJkEZLQi#uPKS2TXS86f8=-)b$aEQ_lyoQn4B8oiQ)XEwgm05iMy!#$0v44<# zKkhR%hMgH|CwS1xtTVcao8?CN_y`=K*l=Y0{1ee4%Z_GM4N~Y zZYEz;>YR$Szm?wPy@q}NuAp@=Pkv9>&~@KYCW-7RTU@_-vx7&MW-U0u3^Bx7ai zO8U2|bUXdMo<6(i-KrY#34f?JjBoTWl?wO$Pp$XeKm6L=>yzg3PuzW7^?TEI3~rnF z`VQEz_m(&8KANn0%LChAIq>(t`M&BmlK(My*@mJwkBP?yD}hQPc{8*LOKcC`O=z#@ zKI)^I5%x>)Y#RU65Z*QQ@W;lJ%lmH}oESSe_EPQH12?{Y=stlLvt_=f?;(G!jYhKX zR_`HehTNdw4u8b{#*R@<8S=*%p*6I7v)1uj>i(oZo^8QI8!r!Jy!`QOY<=nRG4Ww& zOsTvCNT3|fwAhiONs%gPL!8or&k&}>ZDcb#NcSTeleWzTXJ*p{7zu3@R%l$7Xrc2o zc{XKZ^iU6#$!X%6J83?6^MqPD^On5Dy^%T#b3UC34+2sJ4dAaXs9>&uv=;ti{!^-( zvIgqyrT8Ta2ab|4z8fiFWOEH{`iAfjJ!j(JzI|Ds;?vd>E=1*0>BHRW{{@}GH~QjD zOJ$ldY#*ZYnE*wvBLBEtI!5oa7pj#@%c|`YPaIDwmEYcY;Oohrj>|WHKl!V*7tD6h zyYxOWzajbhj<%_ZvByWxt(bQ zY*{m9EIZz3iHkuMZ_<{Qc-AOMu6khzTiY|PAeeCg(0WNaOA!G@ee4NnHY@E!g$(dDAsNiwj>t^3tAXY1`L;3xk zF&)Zp@q8wEx%Jt3)~Czn4s6;x`b6@n%7yoLCx-_nk3XF}GV=fI{Y34`-le{|H(SH9 z-NrrS;5XAJfyMjTyty}|+kaX&_uAa=O2-*HFhw$svjnlK60rg&$9mh*f@!}sXNYWL z96PN8iM7ERXJ-UsJ)hW8=eFHNFKd&b1~_nEP*o4ZIi7F+}2?Y;Nlp&8!OI1@!P&^3}n8=PL?1u61vZd&wQI+GG>4u)#Vdp zlgxY8eXdtMCT)><2}9jR(bMU5k5vdy&?-i6sT$9|$tvF8u9uNB{b4!7O7Oacd&zlz z+p}^jOQe+z!?fQml4(ARNv7Q@4OY zKbVugOBisoc;BY3%-XM#6x-cYN-CS@dn;I-5SGBgt#WJ>2N#Z8fgm%+r_?q!I+pa$ z8pEw*Y;-Iaj?gx?7RaEVxueOHmqsaHZ%w9Kn+8tPJvf{H^zL1IS21oi8}Yj^X11O; zcYMtog`gM2+lpI>SZ}^jDNoz-w?R zB+!a-n-3w(cfi5+G~AK1`7eKMg=XS)`0zuyaUXy5$4~725TPD6PsVI}Q7;5@^+(Z4 zihK?3&RuAOS{(P8!p*YZF`T3ZcByd^xQ*Z>J4Z{6lfccxN!sP#HB_wL!e298Pk$`+ zh}@OdUOvP@;tQ_JFwcm_{nU_k2al+Q4@p5$39z-Ha%kR)+WmCC_V)@eYbD)2!jVgb zgTSi?2if6YDjWo!@QgiYrJuC>S-gqJy=gm41F=ra$%f)y3+%X#P?e_UHn8u~ZCUZy zJIt|fo?S!d%cuK(&T^VnZzY>*XYnC}_$eZ3cJ>aQ6V^G8w_^Tp7#il9f1*2{HS4GM zbq~-i!W+2dFW4kvYVbmCH+_vgtoVhhAyt3fmf9$s=xl*BaOW(~0u5;V9 zFGzCeUL@!S$!EG*LsXpro;+_OeV}KS@ie?vw#E##a=nGHmyoBk_=JS6Pv}~tpS_zU z7=>`QHL}Z_CSNK~LPpFyLimgoB1H4#)|>s5n@c^NHCEc3DW80R?}M5->=iY7MlH71 zuD4^$wp1tRx3Z2}!!%6(8O~}U;{!b5+3a!rvvT?!@W*qsgw&(8?Z=t*+-7|#_ylhV z?@GQs-T4wKGk;^ppBy+^elmIbzPt7`A9 zbxo-7+(Vy9rETNS?R%2yMqi!(Yz_4d43}#}@w;+4&Pt;nDt?<6AlUVtXpi;6Spc(* zU1h8g%js=H)5JNW^fN+dHTa!@Qv`>zD}1-n>e7nRzoZ%5L9MV}TWD6JWNB~~xkl$Z z_$g*NNk3d?eg!>2YrI94p|mfo9M^Dm(-WM|!!D-WOvm;M?*_*^hEaz%K^31Oc7ybv0 zFcx+`Fkj4p=O}co&@=oFttV9KptkE$ns86%9_-PMQ7f#j!URVQr~P-*D&h<(*TV}m zdmbyPrMzk43K~;u&bkRI^e|)0CplLy@azn&6F=)&$Ui8y;25q-pP=8SPMnvJvyg(v zTEYu;DO0qbsIGLMud;3(%6{5OROE_Uu9N1Rh})-=sDv1e-;!JLMg$b-ks6&9&1-2t z?;yC$lNfWVv^`yArWt1F!qfIQrR_(kJ@^1}I7aQ6s{sr2N4?qT2^d%p;R~|@Ixaoj zIzBsB;*@SnEqCCJu@jo)vN|MIWL~ro_#N*u1%I7x@_I(X-ux2QsHHm9vIaW{J%c?f z+&BrmD`dae$7_ySbL?IrXRMZ9ZKD5-<<|dRq*C%(@HX_c5-i|e8e^EgjoZU!vV_pe zcq5bPv)P^wp1AvM7>o6RP$6#r(OV)8?I$D0`>}O4Zx7#+*73uGcJZ;-0BhpUTJDAv zZveNZhz->P`p%B5!mA1`?0Pb|>E-0Dqlr1MeLd>|`CyNWZ>kUBZu3H;l-H3sJ7eO#7>bMK z&+-UWqWGNpKC5mCYYmSA{JVIW5()BUYG;NwZc?NERW$uwktfqT?j)W>rEG;}skB%s znUWbVr5y39BI*#|-^BZLl_ta={MLtT{Fg?eP6pjgPU^OFsTn!F8P>v_NlU?q(45!l zwML%QH)dF%tP|K5haX&@(0H; z_t{Nv>$$G_^nI_4|7Puv*N%)nnN(}bXR}9jy?=9FT&=(w9lH_R35%(8ZWkSS&x#-R zK9*d#;nwM)%Hh`ETSO!vT1c{mH;`SDo1B``(fA&Z@6+8)iFwp-|)uxBZ=;N<7PdZ$FkM}6$BG0 z{jm!@lEO5ygZzIO84*m90{9|CjpTWFvx%-yzmW0<!RmAKDLfxh~R#|rK}!n9sjxSiNx9r8n%aba{RtoRIoh~e-wUW16skVsXo;F zj_MHBGiDpPCv&&thw)N$b+>ejDHsC2D8#6_pBgBvJ4`cmcH^R?U zbK3LC!+s^fL)0MN0psoZ0SY}I_pH9a-+f*mzU@v_!uYz@KOalKhwBB{9!KL?nx27= zt^G8QFHEfMo-X$0Q(e9KW^oho#ZKZ%_D~pi+ZR#D`4o@$1n%}z8_&3gHpdU0ZuhmG z*<*2fDhu|~Ypv|jYNWb;dU$&rQ@3m-&z8@E zb`c!S95HNvOzib?4}OP`_Hf@{RXoyC?F)`7uB&}t($!Hhcq<+4=|fuT=m=UVhK;#q zXy;=S(;r13ni|E2?DHpJ+P2p8J#7eDA!l-JJ^OvAuSPAF+&yX5vT?S7?~OzB)$I8A zAx?31AMdu-6LsM{k-JAO`2l3>5D}nO5OiuHsY4xFPr5^9(m;CH5gYpKvtk@+htDSC zOblx9uRLMhn-)fsTbQxese2Ar(R&Q=hNGz{7J$xiR&#n9L-Sl=&(Ovix&S}1n?>B# zJWKF~%`Gz5P`rv~A?daE;X^C#%Cbg$N)?X$rYWYLCS8dPAI{x?>$p}^=eLKvM4Y2x zf3AsE0q3vy4H3NJ3N<`CnFU&luB=f!Z)#WfZEH8B9JMz>ue?}3EQO$`sp%opq1*6T z)4NZFFYG7|)wDQIgMWO&MBXymL3G6_4?O2RF|>f}!smwUx+6f!nog`aqVtgaz^it9 z;>{K8{f2sg?rsm;{<)Ol+&Z|ye=i~uuIVtIdJe+7wSCCItF7aDSTJQVH$mch_d*aI8 z)(R?e?%!}Md3)bn^>FQ~t?!!s-H99T+&9lpK}p<#j`JW*rDgO6EYWxPG`&QOk2&s4 z=L*l0<1?OVC_3Xe`QR(Ud1!Z%hSbJ|9&;S+{+19GZ}cz2!9-~Ex6z+T6P zwhXqd)A2O^E?n*#QRQtBjzfd)=jEB=r zI46g@ny?p$x-R^UY=B8$Uy}(0eDZplEBRRMyyyQGiShzn-CI}6q>Ia>iMZwErORoCS$+t{_G!v<6#Dklm;(#?+QwD?l6?1ahg$s$ zcn%c6gK;rwt-TqeFb^vhus^OmnNLG2X@939@~WD><#*e<%eV5$>wQmctn1LOpFjA| zwl&?Qb!O6rKTWzrlb{BG^|VWWSqb~S@UqrfYvaz&9%q17AKa|66V?Y}#kCz{A&};`tQJzpKQ8i@T`O1*s*8+JC$>m|6GT=x+V=dH-nrDQ&BWSQOnJ}khhUH z3dF3mYag=h9JtcA3~>tBbFzIBMBeQu@Z;4hI=`4_l0V-!qgT?%nm{g3l~;hV!qUcG z73yWhqvP12CC!Yn2Q7Q~EtG?=lB{4SY#{Z=B-_PYC-&#q+*hmTUgAm*&$k}lgxx!p z*)sbi5hw$i?IJ9EtXZqVD@N2Q=WEzIH0^b~Cp0j!lH4ckq01=6d_QTex{2q2EV8Mo z;y3|<%O}tRLJKouv9&`sOnGOD+dqsS+nNv_s*SS8<49m^!E<5?D^*lu^yTOlJ`2JOSE%xwkf%R2`X-;peJ`VkY-H(>yfH)iAg_xY<>y-qvxhaF8j*CVYo+XH@w7M~$4q)@h{ zx*d@<;_DHLU->pYe&;cC79x~bJ`r|ZchgXz1MOH}b`csCSwF<~rk}tghrIxvE9L=D zL+o*kfB6IuJPWiGTbCtac8?yy%e2#ynaqNKJ3*LgMaP6yfj+`6tmM=}88W%K)wC_( zZOvSm6lH#5JGq5g@o5*~vUqmFgn|4s_W+;WMK~fu3Lj9i7oaS5I`NIKC17QFHEnD- zT6O1vxxm8+pW7EHX8R>M=@(m{+wch8Cj0Mt|EmA8N@eu6r265*^R4&U*=Ff0nH|Qa zi*UzmXK1|`%c2q8ho~ni4Y(F}g!~TpC9$YgM)#vv#zS*(;4A(vB-b&I1@Plht&DEZ zy)BJ#n4fv>P3cPVsZ(U^<7)(nns@SP8Rsp*h1akv`E=!-2cJx?>A<>$R}4M;5gJ=9 zQ?~QgO2-YaPKbA9cKEb)a<+$#_Plq1yfJ6@^$ZBh7xWOK(mPT;%k7#MD3j&o3Qo{5 zI|%|#qEu5!h3*BvvAl~Mv;QwAT#>njL?RD?dq1}k*Q3G{eWi!^^Ai8&&sDsyT?^W7 zMNTAuIhboVLZ_9s5+=ajv~1ZUtAq$m+)w7SkYw1Si)^_4{YCCBor#k#g)Iclv~~QBG?vX!oED!i#xZqoXe{833RzUo zWkZUuqm6HU>uC4=5MhEnki2z-o`~rRUOC=zVqN%1(mZ}+<;i4fEB2Z$-kNX8+=$%N z=q5!aqZQht40}0CXWb^qzN%$2tu9V@q4wC{)zxFkTl=fo33UCEI&Y5L%2R8l3U3k_!`E;`EdEuBm z%p@`!Oe;X3Tj39IRD+RCD+rk~YZ-7GXA`x?O#q1P!09g5dE>j3fzRxYo4>{;f5L`i z27uz*iclmWRrNe?WZqF%&1Y(}$IiF>Sr$7iZTXttwBVwBOwN(>t}bm^gCnOIiam?! zDVB(@_kXv$ZHo2OaOJsm;616hoOD?NMWzu&-&Y-_)Co=t3)#k`yB9dMhA?W{rz zd1}yKs3_SN^+=$J*?Y>CC~kvuLy%woD`eNR^a}Sfz3uEV!<1V^*$0VPfy;9G3Abzn z`g+n)obdqcFx(p{4-kIh+p8EoR6~VYAR4G||3K`rczy7s@CF>dX$t>iUk7id87e(G z{Wo3zYUuH~e?Nb;d}Ha|#2vgc7*+NahEmI>{jxmpQ^$ph4^~J2a&P*}UU`3~6SoI) z>=o~+D<-s-Pt7gc-?%Gl)5*_kvQFc*aI1}2le!RD^Kk`7NA-KtSKYPy$jak?-6vit z;=zaKmi3+I)j)}TvT?HQbx+V9Az#fqhjGhf#vz*5fXwWrs!aAvTZX;rLbpkYf9#Mbe0$2c(!vx zf(hex8C5FDH~IT30?YSs#BW;ejEa^vhc%IQpC*i;@o{F}_uzO}1+#%|#BHsphcmrE z!J|k$yThhj+aXDB$uawD}S1607w3Iik z`y3&>Z?C@F)6az1QG+cnfN8@Ea}(OxJ!6vQM+dSCyL->OX8V#~eg0_qt$jc2+j-={ zQ9oKJB89GZ$7jMs=7dT`AR+fUlg6$!x=R7o80J~HOOO1A`HN=`*S5@m%&D?9W!$Xt zsipk4n7AVgBcCHoS%TlowvGMW8|ZI|hUBV$h` z*M9i(8@@Alw7jl%cL#QjGsv^n;01CX znQL8Kog&!ydtF#_U?oGcpJk2Wkiz_P`f37~pFTu%+ne5vFY?cM1KeYRNVJ*$FUEnoI(#M; zYg0QRf6N6~72jfGMOa=qcIKLsW690O;Wwyt&XN-|L()mw88Hpy1{#lL1C`6ZT!(8^ z5jQY@VlN5)y40!KJj{^*>d-JwaZZlwIPr~^dvrHfN^Y7$_8DHN$^D8qs2v}PwJH2} z-nn+EX70?nlt*9rk(`L;4E2_Qu(q;m&+_*DFb>a2HA(iYtt3oEm z-no7E`o82{&wp|a-+aS%fZwdadn4bS{)6Mc)15_kj2s@--hDD?OY!8qb<3tZeML=o51$_}z|M^&1zC$Xk~F2xTZ*GbGEj!nRc5?r-+l zv&M_fNhHnAKEf}67Q>z?Dk-s3ng!jS%`DL>soZ)TmCkE+pjy59@#Xu=DU>XWh<(&5X;TTcKm&rF5tI z7N?c*uuf4_Xq8aec(xw8sEdS;UfE{nJ4Vb;&uyEXOE`8=gq>l zjdor~ashxDf5*6qtx4rDU2$R=Sw;5RKp|wFfvw!*4U6jAFOxp`d5bVrQK2P%fhn!R zX|^pxwl9RAR-(ouao1Ny?6H$-%-}g}S;$;+wF>mBJOy2#J9$?Fb$p@N4|W?G7a36O zR)bfd?cu#3w>femM+qHa&w;C~k>QjaWvC5sM7}et4Of7SQufQvpaQmE*{_g%D#Y&Q z0bI_-^6dQiwUK1D6PEDQ+`NFsXdzw@E@bI~-w4i7UzWd-SYw}OhfHpisM3Tb?@5D~ zgIEQg2Plo1VC`^f39D<$i{NR?pg%U+VU+=E4MCE(wCUYE9Q8`Q4{TQ0HwvviW(KMQ zy3CBT&oNGtaqvFZ;^PR9<&PsR8ym;v)BN$=9{J;jdEOo=+$JA(OmDaKi=1Mf<#ys_ zXxEctSuj`Jzv0{X7Lxla{e1YHlquPEZRuRBU>DLZ;-+nA>HizI*`Q0 z${g0r9LJYI^Jyb;2rO9^&H3AWELB!)8+}{G+6{bz8hh-?0&lU9wlxtwWsWA)4s%SH zvg(`lr&8NOJUNr*dLUo@o~_3`A>sZQnwjvQvBZY_w<7RF+CX8O3h3=-v=EhLozK%5 zw?t>bD z4`o0X@7MdB3ymscx6oSiTMLx4#XAi9@7i9tI|fgl=fT7NTwDTN=-I8a#}YY-$qdHA z&HK248F>=Cmrp5`*E`zW39mJT+bnvMMhIP z=lA6szx;R2DNJCqCK3zB;JZ{r+!K;<)1vwQBC>I{^j#|K`)2uz&`hEw@cVlgZXjc8 zYg(7ZdVjvRC*wBa>1o8}R&b$Wif{gUa{9;Xe>{H8$djWZqg~0$iE~;HeNt+FE;D>8 zuCcP`SL7Yf6Jw8$o?G!paqkI>)mgD$zn0{iEBV^exa{P{h3aARE*@J3u0NEBXh#Gi zsmT9^u{vAFQ9@HfY>gA4nnKU;ZK z@k99DD2_QK%c@qUiFOlUEjXU!+GajqZuiK~%W~F(d)d(tc*NCTrtTJrUA!*`NV3MZ zy_IjpnudKh^tXA!hGIXf1@Kc))H9au8+}3Sxe}4exO6ZF8-=`;y=7{MXvN;=_NxAevvar}e73`6Zl)IbUagiNF zjW+g+85|89*P^SgK9U>KbfuQ z3cqU9#2eYYZsH)UJmNUPlwl!82S>;ae!LUfM5jQ+p2<_TWT7(S+xR?1K}ZXp-BZ`gSCR(<5|}3kH|wj9$~F<|M20@3?z4VJp8fok+fn2Ii^yvp zb!`};ecoJB`Pt8Wd2MYlKR;l54)yvy(EK6a2l*nYme`+KCGki0Q!P!FU&Q-VrnR|& zayRf!vOFVmwtRAES*>Zs##Yyl`nN~=PMj^ zZ`F}py5jEje2b$C-?kgYb3gU@Yn_A@B5AJluFzRMtRX4@MD9Qa6ZGIzup(;QvtLwu@zZ}&&`D)Jx-2)YEsYD+VFd(QvT%iy?H^dmJSo)fUJ=h zXXCiaO(jme(zqnX=#SOMGogZuv#mi+H_!8{$yY|&2Uz#B9?Y|M=S_XO^7##aeqh=2 z-y8ck(|=q&THf6;zU5mmT*KF=fZhqrzI%9iz|6>~;o_ky0%NzM_-DPw8 zH~qps*128D57+%dE41WQ)svBXuUG%FZNMteV(0V)FFa2QME#e}?^@W!3BNymKnfZ4+ZxZTaOF z&OdVA^W!fZqm$#CM?1;W86uvD(P@Ze|BHR^Ex)h&RPv|4dBN;ZrPA}mHIGiWzomQK z_mh{_Pp@B}TswZj?9sU|^gh_#oBU{7ZSSZ0+Aq0z^S_z?w`>2Z@A0{JZC_#BCGVc+a;H1Yt} zxLI|2eVi6~`7jr{c=%BaThSZ7^VJ+SEyx4G}x z;uRv3?`DyZQ<^TV zqxo>%L_2wv&`|!}wRk(q~TrL?LMp8r0h#sD0^KduH)jg3C_P{YrzV+58WRDgg-0W)@& z6?76;{PAfW)U35r4sCU5J-uDo&9?(~sPZ#=Z#X_%$*4;U>`jLDhr_#iMfg3;efe@I z7)hM2D^xBWOI99l+4QBkdk3EB^=)8GQf2K0Yqfo09Bm1Sb7x2%WGov-J$$85Z9Nmp zZ1dZr*(2*nKHqL%U2Shi>+b&K9b4DlW8$m2KkQp*1$}T2FE}fXv`onARp7K7@)sio z{0MmXO0(v4mgaox^BLkib-G*PBA6GED*qM+o7*8rwhV>tELHCVnzjgTzSf54gx*aV z{X^Q=<@gZftaF)hJ?H9X)r3;zAuUWB64KtFViBu&Dy*{Dz^* zS4LLsPbydRKd_y(UREXrvk%2XW{z@}+GxGQ4dgWdzj7&DKM{k7br6rLdCDqe!9w(g8dQnC z088`o_3aY)wat9)2=uV)p_y7OWCMAx67LBBA0r;Z2^4sQ68V^%DPGia(k!UvG4IpF zSpGVJ>b5SIl|eki@0COZb}YH&_%GkpmHff+XL?O}XKlwTtknS5q_xtZlVFK)@Z(z& zbIslLmKEZ4>^3Ah9-Eu1&#_z#s=2oDs*uLwdDZM9CFVMT68;M1olx_wm}z6c#i9FO zT8MY>j#cre)({ufN-I;ImRLw+yf-}&3Vy)*y2pvnupiEqhkgY<%dR;u;lCKg!~CbT z%F@V8M>9563{OVhsXop{?gOjgV=1z%{t(U=7JXUKAf_B}L16>jN@*{q(Pic+r3NUtS-Mf&rt6xYva1o)A;5 zWAdh{XOOMhnOcaE6MN0Pa<9 zvi|ptTr={m(a&xBQ>TIhQo|WY+&Ht3xJ$B+@K*%NdnZv(`&jk1(ZjX#pMPlopCv!; zdZ?Ev#y1(^M&1A1w>EjY=bf`x?NZN8<61LY4ldF6V0Y5Gj+Ar|7|8}q#&ogxkM6V&Qxtl1$xSG##-o8fpe31sR_a-i)k!qzb zYvwF@{+OoKvU`LwjFPd1tRP;*4EO}K(i2{k-mwIYqddkKhiUA$6VFfT>UdOn_pJ+A zHByK!-~-$P#Z?7aHxLh#=A5BbX-+lZ&6Jf~N4lVgJi<=;W+i=gQQhu3`eqgVHb}p9 z(R1j`ecnvr)q?NgwK4Xc)VG`Zy4V9}+zo*07*vyROzuNOyC&iq%mca+|6fV)xVofi zVHEZzz*#u|gI!y+zp8X6!NqT((L>qQ@Csx>ksg?Bj2ByIex_93l+tIf!zuNx=gM@R zc#k?feSfuiZ^n##7gwF*j=(lkW{*s)%k|JyZm$+vZLH50uQllBwvPLPZcC+x>`5_y z$XOv<7PPgTO>LqT*-G4k_pjqDyzGC)#z8%RX!Ai2Z(n2sY!tG|14Mt{pIJ6n?d3Bwtn-%9`_wL&<(*9O9L9cOUsAcO z|E593sxh2~2}@{UXlr1y^k;H-#Wo~g+tK;bKyvTE)%%}FZk=f}=*gHXPlx;}hQjqw zkI%hh`(Mp-J=7z~72`ji|6hHd=>&hi*n0NFqsgZ$f3p77{?By&+Kfq^B7Rj5X^Skc z%3e{{(I+pbrP#CVhxy0%H_SC<9Q{*-@Ks@9+!?VZ$UgnUR@prH+)WZMe!HIyXj#ya zh+oI(oxm;R$;xSM{AI%vUF26wsLpWpE#fdJYU3Ac119mQq8WyQ45|#WQCMA8xB-ASSGO5kmd76!|p%;enTi z=7x@u{`yg0Qn`0vX7D1~mCd(?CVgQG%@|J3P|D4v`#kT-_q*W-Ba<^hpVNVuWrCg* ziCj=|BK zYm+z+GS~1MxDZ?MEQ*h3%e(E>x%xT;wcYSULKL*ETAn5@LN{~7`l$tc%$gQx$-H^h zLnGl{riJ`vYt3v;sMQVdB$3Hgjl*#s;%AY4Ko;xCPen#tEoVxF>)$iBX69XT+VOlu z58c&t^0E<(t>hRa!@&AQG)^dwFp}!8Ehlmk`5H-jprxxMN!^xgosfAslWP#|iO)RWC@a^1J&dg++jgEItB2iEd|N->eeht2v_2U}+H(P9tU3B$c z;UVFzdVCWg*Jr>|ot(RzO%FHZU-;fETaGhPt46+OqE_4g694^7)M{Fc{HPTbxVWEo zgnVc@%K~2(`T(99?h#deAZPGGUK&gFnMl^9jYP7h=VSWq;!~c9E=&r6i+%3R+Uq+kZZKaI%P^|r;!Hhr2m>rSTVzB7@9diMVAsh#^cy&? z;9MS7EVMhzHBASPJT~*yp{q9@tzJB{HhFH{S!aDW`9klHKHPfW{ll-_y*_!*_=Wd# z6!*=!&f(X0cTm;XC+44^v%>f9FMeVP9)j#M%@RIr{msl(xg?l$4*$;llXKsge{k!+ zaPAevo>%zx!u>=my-5foh#!KALWTX(5Y9Q@I)gXDYvmShM$C)h+NcG_-dl2O&^V$K zddaD3(D4_CKez3ygZ4NYm4|jqTkreE$b;SI9Q@||-wixE{m{oB>gC-b-alQ6`ZL@# zxtDf|ViBCbGFMo%^z*HzcY;c^o#Y4VK9knbOPprw6X@P%Iz{V`D?a*iXM8_Hr!Wg6)o&<`V|zhj8_e0c5^P&aGk0p!03Ncv*M>SUXpuIW8}@wwS$CLFi@%b- z-$p;6WlQO{(yjFW?bKt8zK1lSvI?5w7HWZ;-(26DGsGcUxh*9Iy1sM~;d49vTx9KM zAy*m7iy|KYt)%Y@93&Y;Ek zt4MCAy?q|63Udm-i54RXU&(&7y=yJwDXqCb?}Gc8S$+zAu37cQM=>>=KNikr0RnScAO@$Mef@o^mrugMCczrW`e&pz|Lw79n$oCm&)Ta8~#Z^c>l2I_Bb zOnF8sB{@PA{SUt0OR!?nq<8*@WH7W-(?v5iYqo5;jEy6ntnh!MwP|h~0)6kx9p<9D z2qA3!6+|CM2Woti$Zo+ zU*LdhI=6b}3ZD<&pI^Z#u=8;g7%}VsA$whI`uVG?zNKK51&?jMiH*cu^~p1@dOdxV zr}eH5ymc`oqj`QroF|Zbzz+Nt(vqm{mR)Z3JJh@W#o_wuGEEP}pSf%K<;05ArpQ}e z_-}s8Q5Iind(i><4f70Q4BUr5$dL=kP{2m!)t* z`*`{^ULy>-)pp=Vza9?UYU1N#ixxKb0}^Us;CJCE%Hn|)l4*cqtUVJet)5WrJtXVzDQ@k9-UX_?HP@_oE#yJ6GJp7K3*n;=n> z5zI|HiuYDC7n#}x^FtJf3|5HaSRbL4`~Yjoh`FoaQ?%RQVjd++rp(o{c_*yn!N>7F z?mRIAtX@$J^7$o<6~=Kf%ZC-hwqA@yX5x5-aFbp!3xFl*F6gbG7U$~De8Gc?W>)a4#kq=>z zC^emOwA(gY4%H&DK9J~$&sv2oQ*5P8o#BqkEANjHvRZztZ0qH>$GWH$%i`rC{9(>_ zD{&Ot4Vw$H=8n^PelPKNiuP1#5I+gBf%C|0Q{6o=6Knb1S)x8=t)u7}MU*KgND zTEnb35Kj=5NPcU9s%LP;L%>-UXiwRTL59J%!TAxZLjCd|Lcuzt2-{(1^YHNY@9kSv_a)kl(cTRW!zvJpkoHU}|caea7nWJnXe( zt<9?oy6X)?zV4HrXy^7*FW&D5|JwGoOpiNjM6(@6H2;o`2x$O~mE!D`s5i-Uu<2yZ zjr$|(Y<_FvX+Kd+%EY&N?~R`$lBi#Ea-la0vq$Z>#a=IN&X5d#w;{he7IIW9*Zk%$ z9Sim_OT(M91r6|1rZKS}Z@%-mh(;IAv~Svy5m=AlrgHPXW8QD$b-{>O@kVdkf@cAn z0M6!{#=y0_vS;oi!+BF#3#N&=iz_E!vTt?jNOLuz+e-9SC#;~afgpbq0UhFN4z%=F zQX?Gy8CE$AhjRpSH^vCvO1Ct3g#pKqM~Ho5)Xbo2lzCZYLb2#xu&l-JuYzpjO@*#^ z8umEFds}{Dy&IQaw)r?s`f_a>-7*xD*K1OWh^7&3>-%h`of2;BB#Lp}5%Z<^^m4wI zEtOQ*s+J1fLvDKBzyg+B#t{hl@85Nyn3gYYcO?rWC$`#&+rS6l-6@LsrwJEmS5xkk zKTr<SV!2tufY6Im({TB#jPDAvbj~#(v(=Tt{~#nK$>1 zJyoh?;c8U><+5I12T>JIv>5+#7KTC7e-m)PUmecdA3Lts#A=E*61|JOLEgw+&fMbl zA)uno6E^il$7IRcIL&zH0#4mzmwHGFvGyYr*JCGgqQv!7sGT(H8=;{b?Ewk~q`IGNebl)6{%vo4h3f`jqY-qyI@Cm~72>YUd z+K7G;DvON^tw5MRv3~*X-tJgB#>C|i)1I``4(n?2mRHkf2icdnPj70!um)$m&)Ajl z8WpoEW)37oPxHCvEW{$4PtClA?%ag!wa9^dnrm(AAd!hIU0kocqq?X@_df0+DP!Hg zlj?O@75$gzHCjOelb75{CAj<&l3#i5KOrpGFdQ%<89NG29@l_War}-86hJ8NZg!#rY zET9uOL8D99ihSNcKbPCl)BSEG(FOZ1aSn^i74GkqdhXL}<@#zjzi~sA-&^tKT|ZND z^Vi4qH^2cu4c}&EsqeJ+Xhi$Sr>QT0RxPis8*M8ck0~#rn5B)5J09O{8bB*V9hc1N$$?4e^N<))8SX9y_xnyaNr6s)pFQEPGl#VN_>v9xOWnhOaF9~P{`DW zrWNx2$Cc!p#WOx#C*6PiX;`=qkw=P{J*+QG+J*UwsdzFYc3DUHG;um(-!#sJJY7`6 zdY-XxVQvNoow0DpinNfGz>T?l3Jm*=xG6byCb*k4pWdVy^36fnGZs#A5%9^dmwU#- ziO!bKpN56&rd@zr&)B%sug7haEyS5-o>cNqc1(5hv#0iWMPoSFI9|~+R_=_I<6GYm zfs1`Y1f+ZWXRMrf%V**^*}4DOjN>+tjXM*`?fed+qL1%~ZHl28D!*{(f!fJOeyUtPSRNb$a)f-OrX@o5Jxk zk^DvgzG)K`$33N+34YNx5OBU9)vBPkdnQs(Fy25*X!+v}Ij>FHeDW^3yML<@4h84{c|o~(gC+9ex)<&ux~w`@Ld zR{4?7Iomd4ALZWc@nl8#ZroS8a0l@HlScvV^6jK>QCP0|{kKPk!Bx9Dj+Rv(bPl0Y`KL~@ zZC$5&5RztM|F1gUMehr~tpE3VUq7(C+n2WDvTctj91$Atx`{PAuJ*Kuz2f3 z1qa7qg$|CrI)BZ`lcNu8Usi3K_^tVk$wvl?>kik>xxSLjxLo>b@|BVH0n>WBTFIuP zFKgVFZ|4wPRmZ9I44n{gE!xfG3FAx?&VKU=w|dT54wKEmsa%|hwfXLjg~(`qH zGdcQ<6UX>m?E*t}@sfjh}|)7b*tI1c{9*#*@1$t|dHJo%1^*mK+q6oafQ z2>xWty%cbuIrNSWa}?1Iah&k(`mpyh5IK)#^IfdBO?lf^WA5f!;9gihzl+mz{+bBS zF^`z`wYlvn#rrK{rV0@;xoZcnwzuTjYG(1jT z?Is*X91AHkWc=b*9Ti()+W4|#>MZD8+jDR&{nGm%wgj5k*fZ!#X(ARsoEh`|5ZA|0 z+ro4Xorm@{9^ZP4o3ffxTZsHH=f*=68wi}-Dsop)e`@z^`VXXeXqytk1$G{dwSoPe z=GIIYHHLqWpR&g8Au`Si1xRtiIaai z_THq>eu^#Kn*iDJPmI01{=uyqlRw=2!1li!f6w?|Jiyd>f_5R=2A0kJ>q=#+KY7R2 zwf8)g{A6hDfl<17$A@LoGVB+?rr@1{$k`U(<>`v7YWDf?*jhE>LHM4&<^bJ$8-J7&$&2&~`2{senF?*0UO4kyn;vu6!GCHa_8Rz9}w zJg+P}8`A^+dl+D&Vy#V@W0hce{7MCxh0h~dYr~wA)k3@x(be&B>Y*KvTTc%c59ZZ+ zAn-dklgiNi1KaJ}1voNHDo+i>?acb5Yw*GD<|BX8^_}BMhjTopJTK0J5T3v%xL505vN)=RB7Q_^I#&~W zcb(P4#whtVp0$^mFJ^0d_Q9`=yj**H?y>pecD=aWT})-Mw=!gn zkNbZRq2L}hJL7wOPJZb6)N?TJ%}4Ya)80eI4p2V#N-l|a_h&nPJpaG?ez%izM|n59 zx8C=ak+VgJ-{1VHp|cJS&Og3kbM?7xKW&MDkA`=g;zZ)8_x@mb#HL^Ed(>es5G$s4 z92NHiwb~~pDOV7ltc7Kt(S8T8{mhpgv9Z`8a>wYhu!aXKW9{=Q9BmGO-(Y6PP^AD& zU}eJInN1*p8z!~w8H2jK zRz+4JYww6XPScYUZM!_x9Lk3n)8`0ZoBH_$Tf6u@%r*AssWmI;X~PP|(lI;Rm8_gN zr!`&~#u3Z@%9m%p-93=BAODL7Oxp?V)I7jY{@wqjF0d^k{O)gIW^Us zS+!ugQ!zj^wdZ-d)SlV2ay_0R)gI<9!0A(alRYnU)ufVoHR%eh6W{HN_mM1{i`DF@ zB!?^b@-5b4>v0>gSF)O{)3R%G{WvmP;>~(!j_zbM*P}P}t*ck<7)EOw{AkL}8FV^c zoIuj*rz|||Os@20I@N>4s+20^L`3=P+W=7O;OP_ zSq4ZsQ%Cp{w*>PuK1)$g{hHeo{*4b8W5!odU?^rGjF&IOUVgq)_E55Vi62^|Ep`)B zzrh>eJrtXp{L%cZ7N{X3+w+$<0?6EXMeMdF4&p7DIPks}Y9(;PC9=8ACsq=)gcrrt zNiqsk82)bT4c5|<@i9H7(9UP~0^ex@Wyq`82L71aS~=r{IHQ_NAAbWQt`-2tCN}aDuR_* zh$1vY)=u;m=jKhVp>vWOCU|a2^)^}qu2;d{zD*b5Pg4_$=FGZf&96I_UgB>-!-RCM z%lo2%!n|&-skCH23_4j>)!f;aRHQNWUlx$X!kIC4}@BIrut1pe~y~)R%le# z>iXO7o?+b0Ifpc@NhQJC&7MhKZhdy%tW~*wp)xP~cKCWYQtxCn=_WqE$wz80lvBAXJKW0W)UYLE zx`bCpEI0NZYKFg*Wx2r-^-uuq-&^{%^fbJ?X4yI_HcFNySnB#0bJf6UF`Po$$d7B{ z^5>3Y`_b*B<4{j$wsL7%Kj%wL((i9ZRoIP-;(g_Fkw;KUcg@vXZ2Y!}80}@JA6Y-2 z=Ag?`-pSCF9BTc}*we{*&p$DgRG#j^JMJ#4OuW#WJT`N9zV*K2+aB1yIeFLfuigFn zfg4`mKHZsI@sZnh7SHLgA|8Wfn@KZe*fZh3%B5HPKhybZGrXIroDj~^ZY2n6v5|9Q zjQf&beSXjS!?iG$CRE*7#NK45lY{IaeUEcg<5UL=`wTqqqVL4RT}e;D?Gvf3L`cZbWPK&f2@-RUzU>)$%U;F!-XQOH zJ(gU!;nwM&jK9*=I?!@tPsissoPF?U`Ac($2M+DZl6RY8{&~(Y+^}p)KEbZ@$dgX7 zC-5Qpt<`&o+CKk_O+l_1IehjP@^bk0{Oo8_JPwA8_2)a67mvU2RH$NHWi@|=S-;zB zu(#tMCN?G?e0_fHRl7d;`ftv5)0>2NwX@bad!J4?yUXBfS(h@s6Tsvxt)I%j!2@xl ztf>n}c+}*j(3z%~^*{yA<-59*!vnu;-SnZhf+L@Lt%c0n=Ep1waa^J^^?6tAh)EH@ zop^Poufp$2Q?BuKgWt>LbFq%9wPcnqr($Os5qFL3N^h#G$4MG(tQD7h4wl<6n#NIM zaO(`-mI z5q4iZo)L=U;-_!2Mt1p0k#EejwtB#--0+D;r1Lqm9fyZb0H&9>nj&?h?j^Z+dmuPISl*#-#+UWfteR(&puuJTzFabET2!j@ zPH63?71%}EW^1|*Cd3xn0fr45rMV*?i--{WvE|ZGe zo42$p&)j*~tGX{e4`tTc!lRXl0I`ipEl7Blu0(s&=D;WBlU^JT6up6v?`&_3qs{ss zH*z&?L}S%A=oMa5)_$=S!OGo0|Ag06%RrBtc!hM6E7i6w3uiGGv-=a{EK_n_ykTwk zqois=rcfU4dfTm?qt@MgmRkj`H<6`S;)!s6An#;WpzR7aQnkx ziaFOSHj(aKMOLbvTG4xO(>ikQgPp^08?;i53jHQBVSX!qnedZuTV3e^O@Tk(02KFw znKNz6Dx+WrIy*0v@5=%&`O#Sv!!0~Zccy}4IKqdfP}%o+)zySWb2_LLD>e(?i}iJe zOQGyJ$zE$w4B~Xexb>_ysF{VEZG~i3_%wB&j<}P)$D1havjb*7+n+O^xPFHzFJ?O# z&6YE>Mb?bMz1$NZfX0{#Tpw?}fkSF(cm}X-s7ipQ*+XzZ<5se5aw5`w{(gEAw~euW zmzORNWFCR7X|J*<5wfF86)A)zg6+QRa|wl2n{e&zn~BR~yjql}L4$n0Mysq94f8g7 zh4`Dl2j(H{O)fIM?Gdtvygv2%Kqiz}JuGlqDlZ4HPPV6mF=X9zcLYAq5XDWa=r+ie zqzl%RZXv${cZ_AN9_|^7uOMtg5uXYe$tZGT=S1o^uxG;_9;!YkGe%Pg;r$~(kv1Va z9iB(n7XrrkDJm;MZ{T3^lyYWxbdxgm;OyJL*>q&A25MGu2b1n6#E|!mm^`!@l>#@O@cU)9@)@UxiGgxdi2qED?ZY$S zz@oc1C@y9u_GqDe9G?m^^KsvtJ6gSFb5^#~-t#jvN{}_li8Pvj0}S(gANUsD*#Ldd zc=Fo|l&VGYY$n9GojG}9wCBzOJ29bs%FdL}vrf zAvFTO$Sk?SB-Ttl1YR<~{9XXp0`na>HQFPXl=BS`+Z=~Nf{+4rpH>P#V zA^iLZN37X$f|f;FpNlaQ+xt-;!8|2oN@7y^*uaLhNoDV$b1&gc6!X7U?Ol`Bj+z-L zp_r}1@vY(>reNbZA4_gI{>yiDC4X@InO@#k=ADhj<1A6P%UznyREe=|Xgm(hgJott zbd461NzdaI8*|7y>Y9stp80&Go(3x6uuF$54z#n%Cv#p>xp&~@+BUjl4>_>K@S7>K z$nA4gVW+cS#p`F%Jd|aJH4FDIatgCZ-aXD0zGZ+kK}#}sB3lcK5X*qOQC$<=(%Me< zr>rimr|2Mi{kwV(bqdDckfgJsaH7TiiJk3Gmi(u*@R2g!S@XJqOV z^IO#*@%3z6i=0gUlQ{OKg}JXwXU@E5+l=_k%*?t=LzN=zY{RaBU(Nau(aTE1Fiwl5 zAA4yN$=*Xh_rf-MQ%C#svExd;5Aob+4HLaP>!C z?w?NyhAm#!Zf(fNQ>ii~L{_$by)Bv!_mYpL+IWU|M|CyoCH%?<-bKHsc5v+e*+-`z z{`iac$=Mw3Df>}^8$OrDN)*8-Z1=CN!&h-_hgNOE%TvzCi!Zu@oZ7zN<-)26WPdlq z#9^BB2Jfm##KQbKWM%wp?J}D_gWmv1uovrSXMA7_?5*!tat=$tkCSqCrJdSDmF-=}A`C8=C7 z`J=wYW?SIp>`YgLz18*w85$sdDL#Tpm%WwgYTD{Omjti7HDJoHi~b}{q1iY z+J!tH>(NFtExd|Fb0*+J_>9mEacg%|N*lb(M{@$ujoJ4*$!P`A7&wE37y!1*)U38G z2UqjypwPaa@H|5Z=Tc&;Sx+CezR(#lh{f_R?#eSBdVDoKi(Lu49`D4A6@%w{hteG z)?U?ryY|7t^NpuJeOlY8p2B)%d;C!8$i|V$uG*u`{QM_BOu{<&-T6}V*ZuM=W2k?0 z@t2H=ElmG~ZDZ(E$BH+@w8u%@xph3dJ@GO+aP-51p-4!jqvA^URlntw#cVglwZ%^|P;u zh;$1Eh_rfwfZ!#13fyDvy*yI_RVA#L7BbWx)rD&Wf$mPxOb`Uj(3~#-gxE?L0T+% z?xA^myD2+sUu~~3AdPo&H>YTGx$-tgE6PTK*q)Ry#&wh?-~6mBmGHp1^hd6Rs% zr<09FR5>8BlCpp4#7Hy z6>ny(ihXz9YR>^>^`y3Lk&X7~aZ3)_2gpMewI>feajH>lsKtr%Av~YMhx6&)%$J#A z{5=g`dDk0l?rD6djSU&aBLCUX%42Wbj>{-r_%rc2+!{)L(KJ4yO&Z^d&EYHY1?rGGBnJY%FtnaYFATetn)9z#FzvQg*Q2 zIkTIMYu|j*aV{xTlIS&8(M;qavh}WCs9ynsXOgF4cz};!Do` zuY&UmIC4jW^kM`a3wT3I>mY2cBlyiIIw3CJ2QG?`S??Yh>LXG4+=HI$$0x)!&-w7K z8Hvp*t(-+`=7XszDLHZ~4Q!Nwz5$@456}3S0YXZ6(vN5P_;(IHnZ>hG{NytJ4&ccQ z{?FlCs7AUo+?K`7(L^b1P6cwdr!g^wpReGT8${n1VHq6;9>zVo#y-Zf_<3J?*p;9D uXxuOTAuIU^ZBs_;(9cglG~-{h4e$nf9i>bF literal 0 HcmV?d00001 diff --git a/config/config.default.js b/config/config.default.js index f24da08..7c18215 100644 --- a/config/config.default.js +++ b/config/config.default.js @@ -48,6 +48,10 @@ module.exports = appInfo => { appKey: 23535631, security: 'd0cbd3935e3afa2b42b5dc600c08a795', }; + config.deepseek = { + apiKey: process.env.DEEPSEEK_API_KEY || '', + baseUrl: 'https://api.deepseek.com', + }; config.tencentCloud = { ...tencentCloudConfig, }; diff --git a/database/migrations/20260528100000-drop-platid-from-wms-platform.js b/database/migrations/20260528100000-drop-platid-from-wms-platform.js index 3282184..bdb38f5 100644 --- a/database/migrations/20260528100000-drop-platid-from-wms-platform.js +++ b/database/migrations/20260528100000-drop-platid-from-wms-platform.js @@ -65,4 +65,4 @@ module.exports = { await queryInterface.addColumn(TABLE_NAME, COLUMN_NAME, buildPlatidColumn(Sequelize)); }, -}; \ No newline at end of file +}; diff --git a/database/migrations/20260530090000-add-template-id-to-wms-express-interface.js b/database/migrations/20260530090000-add-template-id-to-wms-express-interface.js new file mode 100644 index 0000000..11a7159 --- /dev/null +++ b/database/migrations/20260530090000-add-template-id-to-wms-express-interface.js @@ -0,0 +1,46 @@ +'use strict'; + +/** + * 为快递接口配置表新增模板 ID 字段 template_id。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ +module.exports = { + /** + * 执行迁移:新增 template_id 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + const tableName = 'wms_express_interface'; + const columns = await queryInterface.describeTable(tableName); + + if (columns.template_id) { + return; + } + + await queryInterface.addColumn(tableName, 'template_id', { + type: Sequelize.BIGINT.UNSIGNED, + allowNull: true, + comment: '模板ID', + }); + }, + + /** + * 回滚迁移:删除 template_id 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} 无返回值 + */ + async down(queryInterface) { + const tableName = 'wms_express_interface'; + const columns = await queryInterface.describeTable(tableName); + + if (!columns.template_id) { + return; + } + + await queryInterface.removeColumn(tableName, 'template_id'); + }, +}; diff --git a/database/migrations/20260530110000-add-brandno-to-wms-express-interface.js b/database/migrations/20260530110000-add-brandno-to-wms-express-interface.js new file mode 100644 index 0000000..00de169 --- /dev/null +++ b/database/migrations/20260530110000-add-brandno-to-wms-express-interface.js @@ -0,0 +1,46 @@ +'use strict'; + +/** + * 为快递接口配置表新增品牌编码字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ +module.exports = { + /** + * 执行迁移:新增 brandno 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + const tableName = 'wms_express_interface'; + const columns = await queryInterface.describeTable(tableName); + + if (columns.brandno) { + return; + } + + await queryInterface.addColumn(tableName, 'brandno', { + type: Sequelize.STRING(255), + allowNull: true, + comment: '品牌编码', + }); + }, + + /** + * 回滚迁移:删除 brandno 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} 无返回值 + */ + async down(queryInterface) { + const tableName = 'wms_express_interface'; + const columns = await queryInterface.describeTable(tableName); + + if (!columns.brandno) { + return; + } + + await queryInterface.removeColumn(tableName, 'brandno'); + }, +}; diff --git a/database/migrations/20260531120000-add-providertype-to-wms-express-interface.js b/database/migrations/20260531120000-add-providertype-to-wms-express-interface.js new file mode 100644 index 0000000..c32e13c --- /dev/null +++ b/database/migrations/20260531120000-add-providertype-to-wms-express-interface.js @@ -0,0 +1,46 @@ +'use strict'; + +/** + * 为快递接口配置表新增服务商类型字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ +module.exports = { + /** + * 执行迁移:新增 providertype 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + const tableName = 'wms_express_interface'; + const columns = await queryInterface.describeTable(tableName); + + if (columns.providertype) { + return; + } + + await queryInterface.addColumn(tableName, 'providertype', { + type: Sequelize.STRING(50), + allowNull: true, + comment: '服务商类型编码', + }); + }, + + /** + * 回滚迁移:删除 providertype 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} 无返回值 + */ + async down(queryInterface) { + const tableName = 'wms_express_interface'; + const columns = await queryInterface.describeTable(tableName); + + if (!columns.providertype) { + return; + } + + await queryInterface.removeColumn(tableName, 'providertype'); + }, +}; diff --git a/database/migrations/20260531123000-add-paymode-to-wms-express-interface.js b/database/migrations/20260531123000-add-paymode-to-wms-express-interface.js new file mode 100644 index 0000000..f75dffe --- /dev/null +++ b/database/migrations/20260531123000-add-paymode-to-wms-express-interface.js @@ -0,0 +1,46 @@ +'use strict'; + +/** + * 为快递接口配置表新增付款方式字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ +module.exports = { + /** + * 执行迁移:新增 paymode 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + const tableName = 'wms_express_interface'; + const columns = await queryInterface.describeTable(tableName); + + if (columns.paymode) { + return; + } + + await queryInterface.addColumn(tableName, 'paymode', { + type: Sequelize.INTEGER(11), + allowNull: true, + comment: '付款方式', + }); + }, + + /** + * 回滚迁移:删除 paymode 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} 无返回值 + */ + async down(queryInterface) { + const tableName = 'wms_express_interface'; + const columns = await queryInterface.describeTable(tableName); + + if (!columns.paymode) { + return; + } + + await queryInterface.removeColumn(tableName, 'paymode'); + }, +}; diff --git a/database/migrations/20260601100000-add-providerid-to-wms-express-interface.js b/database/migrations/20260601100000-add-providerid-to-wms-express-interface.js new file mode 100644 index 0000000..c39bf9c --- /dev/null +++ b/database/migrations/20260601100000-add-providerid-to-wms-express-interface.js @@ -0,0 +1,46 @@ +'use strict'; + +/** + * 为快递接口配置表新增服务商ID字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ +module.exports = { + /** + * 执行迁移:新增 providerid 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + const tableName = 'wms_express_interface'; + const columns = await queryInterface.describeTable(tableName); + + if (columns.providerid) { + return; + } + + await queryInterface.addColumn(tableName, 'providerid', { + type: Sequelize.INTEGER(11), + allowNull: true, + comment: '服务商ID', + }); + }, + + /** + * 回滚迁移:删除 providerid 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} 无返回值 + */ + async down(queryInterface) { + const tableName = 'wms_express_interface'; + const columns = await queryInterface.describeTable(tableName); + + if (!columns.providerid) { + return; + } + + await queryInterface.removeColumn(tableName, 'providerid'); + }, +}; diff --git a/database/migrations/20260602103000-create-wms-order-item-sn-and-log.js b/database/migrations/20260602103000-create-wms-order-item-sn-and-log.js new file mode 100644 index 0000000..3a77b37 --- /dev/null +++ b/database/migrations/20260602103000-create-wms-order-item-sn-and-log.js @@ -0,0 +1,326 @@ +'use strict'; + +const ORDER_ITEM_SN_TABLE = 'wms_order_item_sn'; +const ORDER_ITEM_SN_LOG_TABLE = 'wms_order_item_sn_log'; + +/** + * 获取当前数据库已存在的表名集合。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise>} 表名集合。 + */ +const getExistingTableSet = async queryInterface => { + const tables = await queryInterface.showAllTables(); + return new Set( + tables.map(table => (typeof table === 'string' ? table : table.tableName)) + ); +}; + +/** + * 获取指定表的索引名集合。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @return {Promise>} 索引名集合。 + */ +const getIndexNameSet = async (queryInterface, tableName) => { + const indexes = await queryInterface.showIndex(tableName); + return new Set(indexes.map(index => String(index && index.name ? index.name : '').trim()).filter(Boolean)); +}; + +/** + * 创建订单明细 SN 当前关系表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ +const createOrderItemSnTable = async (queryInterface, Sequelize) => { + await queryInterface.createTable(ORDER_ITEM_SN_TABLE, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + order_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '订单ID', + }, + order_item_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '订单明细ID', + }, + sn_code: { + type: Sequelize.STRING(128), + allowNull: false, + comment: 'SN编码', + }, + sn_status: { + type: Sequelize.STRING(32), + allowNull: false, + defaultValue: 'BOUND', + comment: 'SN状态:BOUND/VERIFIED/RETURNED/REISSUED/INVALID', + }, + verify_status: { + type: Sequelize.STRING(32), + allowNull: false, + defaultValue: 'UNVERIFIED', + comment: '核验状态:UNVERIFIED/PASS/FAIL', + }, + bound_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '绑定时间', + }, + verified_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '核验时间', + }, + returned_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '退回时间', + }, + reissued_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '重发时间', + }, + version: { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: false, + defaultValue: 1, + comment: '版本号', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + }, { + engine: 'InnoDB', + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + comment: '订单明细SN当前关系与状态表', + }); +}; + +/** + * 创建订单明细 SN 状态变更流水表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ +const createOrderItemSnLogTable = async (queryInterface, Sequelize) => { + await queryInterface.createTable(ORDER_ITEM_SN_LOG_TABLE, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + sn_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '关联SN主表ID', + }, + order_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '订单ID', + }, + order_item_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '订单明细ID', + }, + sn_code: { + type: Sequelize.STRING(128), + allowNull: false, + comment: 'SN编码', + }, + from_sn_status: { + type: Sequelize.STRING(32), + allowNull: true, + comment: '变更前SN状态', + }, + to_sn_status: { + type: Sequelize.STRING(32), + allowNull: false, + comment: '变更后SN状态', + }, + verify_status: { + type: Sequelize.STRING(32), + allowNull: true, + comment: '本次状态变更后的核验状态', + }, + action_type: { + type: Sequelize.STRING(32), + allowNull: false, + comment: '动作类型:BIND/VERIFY/RETURN/REISSUE/UNBIND', + }, + remark: { + type: Sequelize.STRING(255), + allowNull: true, + comment: '备注', + }, + operator_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '操作人ID', + }, + operated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '操作时间', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + }, { + engine: 'InnoDB', + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + comment: '订单明细SN状态变更流水表', + }); +}; + +/** + * 确保订单明细 SN 当前关系表索引存在。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ +const ensureOrderItemSnIndexes = async queryInterface => { + const indexNameSet = await getIndexNameSet(queryInterface, ORDER_ITEM_SN_TABLE); + + if (!indexNameSet.has('uk_wms_order_item_sn_warehouse_sn_code')) { + await queryInterface.addIndex(ORDER_ITEM_SN_TABLE, [ 'warehouse_id', 'sn_code' ], { + name: 'uk_wms_order_item_sn_warehouse_sn_code', + unique: true, + }); + } + + if (!indexNameSet.has('idx_wms_order_item_sn_warehouse_id')) { + await queryInterface.addIndex(ORDER_ITEM_SN_TABLE, [ 'warehouse_id' ], { + name: 'idx_wms_order_item_sn_warehouse_id', + }); + } + + if (!indexNameSet.has('idx_wms_order_item_sn_order_id')) { + await queryInterface.addIndex(ORDER_ITEM_SN_TABLE, [ 'order_id' ], { + name: 'idx_wms_order_item_sn_order_id', + }); + } + + if (!indexNameSet.has('idx_wms_order_item_sn_order_item_id')) { + await queryInterface.addIndex(ORDER_ITEM_SN_TABLE, [ 'order_item_id' ], { + name: 'idx_wms_order_item_sn_order_item_id', + }); + } +}; + +/** + * 确保订单明细 SN 流水表索引存在。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ +const ensureOrderItemSnLogIndexes = async queryInterface => { + const indexNameSet = await getIndexNameSet(queryInterface, ORDER_ITEM_SN_LOG_TABLE); + + if (!indexNameSet.has('idx_wms_order_item_sn_log_sn_id')) { + await queryInterface.addIndex(ORDER_ITEM_SN_LOG_TABLE, [ 'sn_id' ], { + name: 'idx_wms_order_item_sn_log_sn_id', + }); + } + + if (!indexNameSet.has('idx_wms_order_item_sn_log_sn_code')) { + await queryInterface.addIndex(ORDER_ITEM_SN_LOG_TABLE, [ 'sn_code' ], { + name: 'idx_wms_order_item_sn_log_sn_code', + }); + } + + if (!indexNameSet.has('idx_wms_order_item_sn_log_order_id')) { + await queryInterface.addIndex(ORDER_ITEM_SN_LOG_TABLE, [ 'order_id' ], { + name: 'idx_wms_order_item_sn_log_order_id', + }); + } + + if (!indexNameSet.has('idx_wms_order_item_sn_log_order_item_id')) { + await queryInterface.addIndex(ORDER_ITEM_SN_LOG_TABLE, [ 'order_item_id' ], { + name: 'idx_wms_order_item_sn_log_order_item_id', + }); + } +}; + +module.exports = { + /** + * 创建订单明细 SN 主表与流水表及索引。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface, Sequelize) { + const existingTables = await getExistingTableSet(queryInterface); + + if (!existingTables.has(ORDER_ITEM_SN_TABLE)) { + await createOrderItemSnTable(queryInterface, Sequelize); + } + + if (!existingTables.has(ORDER_ITEM_SN_LOG_TABLE)) { + await createOrderItemSnLogTable(queryInterface, Sequelize); + } + + await ensureOrderItemSnIndexes(queryInterface); + await ensureOrderItemSnLogIndexes(queryInterface); + }, + + /** + * 回滚删除订单明细 SN 主表与流水表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface, Sequelize) { + void Sequelize; + + const existingTables = await getExistingTableSet(queryInterface); + + if (existingTables.has(ORDER_ITEM_SN_LOG_TABLE)) { + await queryInterface.dropTable(ORDER_ITEM_SN_LOG_TABLE); + } + + if (existingTables.has(ORDER_ITEM_SN_TABLE)) { + await queryInterface.dropTable(ORDER_ITEM_SN_TABLE); + } + }, +}; diff --git a/database/migrations/20260606042732-add-auto-increment-to-wms-order-items-partitions.js b/database/migrations/20260606042732-add-auto-increment-to-wms-order-items-partitions.js new file mode 100644 index 0000000..50ffc60 --- /dev/null +++ b/database/migrations/20260606042732-add-auto-increment-to-wms-order-items-partitions.js @@ -0,0 +1,49 @@ +'use strict'; + +/** + * 修复 wms_order_items 分表的 id 列缺少 AUTO_INCREMENT 的问题。 + * + * 背景:sync({ alter: true }) 修了所有字段但没有检测到 id 缺少 AUTO_INCREMENT, + * 需要手动为以下分表补充: + * - wms_order_items_100000_dispatch + * - wms_order_items_100000_history + * - wms_order_items_1000028 + * + * @param {import('sequelize').QueryInterface} queryInterface + * @param {import('sequelize')} Sequelize + * @return {Promise} + */ +module.exports.up = async (queryInterface, Sequelize) => { + const tables = [ + 'wms_order_items_100000_dispatch', + 'wms_order_items_100000_history', + 'wms_order_items_1000028', + ]; + + for (const table of tables) { + await queryInterface.sequelize.query( + `ALTER TABLE \`${table}\` MODIFY id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT` + ); + } +}; + +/** + * 回滚:移除 AUTO_INCREMENT(恢复为普通 BIGINT UNSIGNED NOT NULL)。 + * + * @param {import('sequelize').QueryInterface} queryInterface + * @param {import('sequelize')} Sequelize + * @return {Promise} + */ +module.exports.down = async (queryInterface, Sequelize) => { + const tables = [ + 'wms_order_items_100000_dispatch', + 'wms_order_items_100000_history', + 'wms_order_items_1000028', + ]; + + for (const table of tables) { + await queryInterface.sequelize.query( + `ALTER TABLE \`${table}\` MODIFY id BIGINT UNSIGNED NOT NULL` + ); + } +}; diff --git a/db_query.js b/db_query.js index 73e6c5a..ce2fe7d 100644 --- a/db_query.js +++ b/db_query.js @@ -6,7 +6,7 @@ const config = { database: 'wms', username: 'wms', password: 'dspxmRwRdRbWtbm7', - logging: false + logging: false, }; const sequelize = new Sequelize(config.database, config.username, config.password, config); @@ -15,25 +15,25 @@ async function run() { try { const results = {}; - const [dyxdCountResult] = await sequelize.query("SELECT COUNT(*) as count FROM wms_platform WHERE code='DYXD'"); + const [ dyxdCountResult ] = await sequelize.query("SELECT COUNT(*) as count FROM wms_platform WHERE code='DYXD'"); results.dyxdCount = dyxdCountResult[0].count; - const [dyCountResult] = await sequelize.query("SELECT COUNT(*) as count FROM wms_platform WHERE code='DY'"); + const [ dyCountResult ] = await sequelize.query("SELECT COUNT(*) as count FROM wms_platform WHERE code='DY'"); results.dyCount = dyCountResult[0].count; - const [dyRowResult] = await sequelize.query("SELECT * FROM wms_platform WHERE code='DY' LIMIT 1"); + const [ dyRowResult ] = await sequelize.query("SELECT * FROM wms_platform WHERE code='DY' LIMIT 1"); results.dyRow = dyRowResult[0] || null; // The user asked for "metaExists (SequelizeMeta 是否存在该 migration 记录)" // Based on previous terminal logs, the migration file name or pattern seems to be related to "platform_code" or "wms_platform" - const [metaResult] = await sequelize.query("SELECT * FROM SequelizeMeta"); + const [ metaResult ] = await sequelize.query('SELECT * FROM SequelizeMeta'); const migrationName = '20250303080004-platform_code.js'; // This is an assumption based on common naming. // Let's search for any record that contains 'platform' in the name. const exists = metaResult.some(m => m.name.includes('platform')); results.metaExists = exists; try { - const [expressTotalResult] = await sequelize.query("SELECT COUNT(*) as count FROM wms_express"); + const [ expressTotalResult ] = await sequelize.query('SELECT COUNT(*) as count FROM wms_express'); results.expressTotal = expressTotalResult[0].count; } catch (e) {} diff --git a/methods/changes/openapi.json b/methods/changes/openapi.json index fa168c3..e772399 100644 --- a/methods/changes/openapi.json +++ b/methods/changes/openapi.json @@ -1,63 +1,271 @@ [ - { - "version": "2026.04.26-openapi-01", - "date": "2026-04-26", - "summary": "新增 openapi 入口文档骨架(/openapi),包含请求体解析、app_key 与签名校验规则", - "methods": [ - "openapi.index" - ], - "notes": [ - "新增 methods/openapi.json:记录 /openapi 入口的文档骨架与校验约定(JSON body 解析、统一错误格式、app_key 校验、签名规则)。", - "核心校验规则:1) body 使用 JSON 解析,优先 rawBody;2) 错误对外格式使用 toFailure(flag/code/message/data/timestamp);3) app_key 仅当数据库记录的 interface_type_id=2 且 is_enabled=1 时视为有效;4) 签名按 query 字段字母序排序(排除 sign/signature)+ selfAppSecret + bodySign(md5(stableSerialize(body))),对拼接字符串取 md5。" - ], - "type": "added" - } - , - { - "version": "2026.04.26-openapi-02", - "date": "2026-04-26", - "summary": "说明:/openapi 入口不校验请求头,补充签名别名与 app_key 有效性说明", - "methods": [ - "openapi.index" - ], - "notes": [ - "修正:明确 /openapi 入口不对请求头进行强制校验(与 qimen 一致),headers 字段仅作为参考。", - "确认:body JSON 解析(rawBody 优先)与错误消息保持为 'json数据为空' / 'json数据解析错误';app_key 校验仅当 wms_api_app.interface_type_id=2 且 is_enabled=1 时有效。", - "补充:签名字段别名说明(sign/signature)与 app_key 别名(app_key/appkey/self_app_key);签名算法与实现参见 app/lib/api_sign.js。" - ], - "type": "modified" - }, - { - "version": "2026.04.26-openapi-03", - "date": "2026-04-26", - "summary": "新增 openapi 方法 index.ping(基础模块,心跳接口)", - "methods": [ - "index.ping" - ], - "notes": [ - "新增 openapi 可用性检测接口 index.ping,返回与系统成功结构一致(包含 code/message/data)。" - ], - "type": "added" - } - , - { - "version": "2026.04.26-openapi-04", - "date": "2026-04-26", - "summary": "规范化 /openapi 文档:独立链路、移除请求头校验、返回风格改为 code/message/data、明确签名与 app_key 校验、指向 openapiMethods 分发。", - "methods": [ - "openapi.index", - "index.ping" - ], - "notes": [ - "本次变更:", - "1) 明确 /openapi 为独立链路,不复用 system/qimen 的请求头校验;", - "2) 移除 platform/project 等请求头的强校验说明;", - "3) 返回结构与 system 风格对齐(使用 code/message/data,移除额外 flag 字段);", - "4) 保持 body 为 JSON(rawBody 优先),并明确错误文案为 'json数据为空' / 'json数据解析错误';", - "5) 明确 app_key 仅当 wms_api_app.interface_type_id=2 且 is_enabled=1 时视为有效;", - "6) 明确签名算法:query 按字母序排序 + self_app_secret + bodySign(md5(stableSerialize(body))),支持别名 sign/signature 与 app_key/appkey/self_app_key;", - "7) 说明 method 分发走 openapiMethods 专用目录,示例方法 index.ping(基础模块)。" - ], - "type": "modified" - } + { + "version": "2026.06.04-openapi-04", + "date": "2026-06-04", + "summary": "文档结构优化:拆分 endpoints 为 methods.groups 多分组(基础模块 / 发货单模块)", + "methods": [], + "notes": [ + "将单一 endpoints 数组重构为 methods.groups 多分组结构", + "基础模块:index.ping", + "发货单模块:deliveryorder.create、deliveryorder.query", + "移除顶层 groupName 字段,分组名改由各 group 独立声明" + ], + "type": "modified" + }, + { + "version": "2026.06.04-openapi-03", + "date": "2026-06-04", + "summary": "新增 deliveryorder.create 和 deliveryorder.query 方法文档", + "methods": [ + "deliveryorder.create", + "deliveryorder.query" + ], + "notes": [ + "新增 deliveryorder.create:创建发货单接口,支持订单主信息、收件人信息、订单明细的完整入参;创建渠道为 API,平台/快递自动匹配", + "新增 deliveryorder.query:查询发货单接口,根据 deliveryOrderCode 查询订单详情", + "所有参数使用驼峰命名(camelCase),不做下划线兼容", + "requestBody 字段按 deliveryOrder.xxx、deliveryOrder.receiverInfo.xxx、orderLines.orderLine、[].orderLine.xxx 层级清晰标注" + ], + "type": "added" + }, + { + "version": "2026.06.04-openapi-02", + "date": "2026-06-04", + "summary": "移除 ping.echo 和 index.health,只保留 index.ping", + "methods": [ + "ping.echo", + "index.health" + ], + "notes": [ + "移除 ping.echo:回显接口暂不对外开放", + "移除 index.health:健康检查接口暂不对外开放", + "当前仅保留 index.ping 心跳接口" + ], + "type": "removed" + }, + { + "version": "2026.06.04-openapi-01", + "date": "2026-06-04", + "summary": "移除入口方法 openapi.index,新增 index.health 和 ping.echo 方法文档", + "methods": [ + "openapi.index", + "index.health", + "ping.echo" + ], + "notes": [ + "移除 openapi.index:该方法是 POST /openapi 的入口端点,非业务方法,从文档中移除", + "新增 index.health:基础模块健康检查接口,返回 openapiMethods 模块状态", + "新增 ping.echo:ping 模块回显接口,将请求体原样返回,用于调试连通性和签名验证" + ], + "type": "modified" + }, + { + "version": "2026.04.26-openapi-01", + "date": "2026-04-26", + "summary": "新增 openapi 入口文档骨架(/openapi),包含请求体解析、app_key 与签名校验规则", + "methods": [ + "openapi.index" + ], + "notes": [ + "新增 methods/openapi.json:记录 /openapi 入口的文档骨架与校验约定(JSON body 解析、统一错误格式、app_key 校验、签名规则)。", + "核心校验规则:1) body 使用 JSON 解析,优先 rawBody;2) 错误对外格式使用 toFailure(flag/code/message/data/timestamp);3) app_key 仅当数据库记录的 interface_type_id=2 且 is_enabled=1 时视为有效;4) 签名按 query 字段字母序排序(排除 sign/signature)+ selfAppSecret + bodySign(md5(stableSerialize(body))),对拼接字符串取 md5。" + ], + "type": "added" + }, + { + "version": "2026.04.26-openapi-02", + "date": "2026-04-26", + "summary": "说明:/openapi 入口不校验请求头,补充签名别名与 app_key 有效性说明", + "methods": [ + "openapi.index" + ], + "notes": [ + "修正:明确 /openapi 入口不对请求头进行强制校验(与 qimen 一致),headers 字段仅作为参考。", + "确认:body JSON 解析(rawBody 优先)与错误消息保持为 'json数据为空' / 'json数据解析错误';app_key 校验仅当 wms_api_app.interface_type_id=2 且 is_enabled=1 时有效。", + "补充:签名字段别名说明(sign/signature)与 app_key 别名(app_key/appkey/self_app_key);签名算法与实现参见 app/lib/api_sign.js。" + ], + "type": "modified" + }, + { + "version": "2026.04.26-openapi-03", + "date": "2026-04-26", + "summary": "新增 openapi 方法 index.ping(基础模块,心跳接口)", + "methods": [ + "index.ping" + ], + "notes": [ + "新增 openapi 可用性检测接口 index.ping,返回与系统成功结构一致(包含 code/message/data)。" + ], + "type": "added" + }, + { + "version": "2026.04.26-openapi-04", + "date": "2026-04-26", + "summary": "规范化 /openapi 文档:独立链路、移除请求头校验、返回风格改为 code/message/data、明确签名与 app_key 校验、指向 openapiMethods 分发。", + "methods": [ + "openapi.index", + "index.ping" + ], + "notes": [ + "本次变更:", + "1) 明确 /openapi 为独立链路,不复用 system/qimen 的请求头校验;", + "2) 移除 platform/project 等请求头的强校验说明;", + "3) 返回结构与 system 风格对齐(使用 code/message/data,移除额外 flag 字段);", + "4) 保持 body 为 JSON(rawBody 优先),并明确错误文案为 'json数据为空' / 'json数据解析错误';", + "5) 明确 app_key 仅当 wms_api_app.interface_type_id=2 且 is_enabled=1 时视为有效;", + "6) 明确签名算法:query 按字母序排序 + self_app_secret + bodySign(md5(stableSerialize(body))),支持别名 sign/signature 与 app_key/appkey/self_app_key;", + "7) 说明 method 分发走 openapiMethods 专用目录,示例方法 index.ping(基础模块)。" + ], + "type": "modified" + }, + { + "version": "2026.06.04-openapi-05", + "date": "2026-06-04", + "summary": "新增订单模块 order.cancel 方法", + "methods": [ + "order.cancel" + ], + "notes": [ + "新增 order.cancel:取消发货单接口,支持直接取消未拣货/未打印的订单;已拣货或已打印的改为拦截状态", + "当前支持 JYCK(一般交易出库)、HHCK(换货出库)、BFCK(补发出库)三种出库单类型", + "取消操作为不可逆操作" + ], + "type": "added" + }, + { + "version": "2026.06.04-openapi-06", + "date": "2026-06-04", + "summary": "补齐 deliveryorder.create、deliveryorder.query、order.cancel 的 params 入参文档", + "methods": [ + "deliveryorder.create", + "deliveryorder.query", + "order.cancel" + ], + "notes": [ + "为三个方法的 params 数组补充标准 OpenAPI query 参数:method、v、timestamp、app_key、sign" + ], + "type": "modified" + }, + { + "version": "2026.06.04-openapi-07", + "date": "2026-06-04", + "summary": "修正 params 字段:从 query 签名参数改为 POST body 业务参数(与 requestBody 保持一致)", + "methods": [ + "deliveryorder.create", + "deliveryorder.query", + "order.cancel" + ], + "notes": [ + "params 现包含 POST body 的业务入参(与 requestBody 一致),query 签名参数已通过页面顶部签名说明覆盖" + ], + "type": "modified" + }, + { + "version": "2026.06.04-openapi-08", + "date": "2026-06-04", + "summary": "新增商品模块 singleitem.synchronize 和 singleitem.query 方法", + "methods": [ + "singleitem.synchronize", + "singleitem.query" + ], + "notes": [ + "新增 singleitem.synchronize:商品同步接口,按 itemCode 唯一约束创建或更新商品信息,联动库存表", + "新增 singleitem.query:商品查询接口,按 itemId 返回完整商品信息", + "所有参数使用驼峰命名(camelCase)" + ], + "type": "added" + }, + { + "version": "2026.06.04-openapi-09", + "date": "2026-06-04", + "summary": "singleitem.synchronize 的 warehouseCode 改为从 app_key 自动解析,不再要求调用方必传", + "methods": [ + "singleitem.synchronize" + ], + "notes": [ + "warehouseCode 改为可选参数,默认从 app_key 绑定的仓库(api_app.qimen_warehouse_code)自动解析", + "ownerCode 同步改为可选参数" + ], + "type": "modified" + }, + { + "version": "2026.06.04-openapi-10", + "date": "2026-06-04", + "summary": "安全加固:移除 singleitem.synchronize 的 warehouseCode 和 ownerCode 入参,完全由 app_key 自动解析", + "methods": [ + "singleitem.synchronize" + ], + "notes": [ + "warehouseCode 和 ownerCode 从 params 中移除,调用方不可传入或覆盖", + "两个字段完全由服务端根据 app_key 自动解析,确保仓库/货主绑定关系不可被篡改" + ], + "type": "modified" + }, + { + "version": "2026.06.04-openapi-11", + "date": "2026-06-04", + "summary": "新增库存模块 inventory.query 方法", + "methods": [ + "inventory.query" + ], + "notes": [ + "新增 inventory.query:批量库存查询接口,按商品 ID 列表返回可用量和锁定量", + "支持批量查询,减少请求次数", + "库存不足的商品不会出现在返回结果中" + ], + "type": "added" + }, + { + "version": "2026.06.04-openapi-12", + "date": "2026-06-04", + "summary": "新增回调模块 callback.test 方法及统一回调通知系统", + "methods": [ + "callback.test" + ], + "notes": [ + "新增 callback.test:模拟回调测试接口,向 callback_url 发送签名回调", + "新增 app/service/openapi/callback.js:统一回调服务,支持签名+重试+日志", + "订单同步完成时自动触发 API 渠道回调(fire-and-forget,不影响主流程)", + "回调签名算法与 OpenAPI 入口完全一致" + ], + "type": "added" + }, + { + "version": "2026.06.04-openapi-13", + "date": "2026-06-04", + "summary": "移除回调模块(回调测试改为独立页面 /docs/api/openapi/callback-test)", + "methods": [ + "callback.test" + ], + "notes": [ + "回调测试不再作为 OpenAPI method,改为独立路由页面 /docs/api/openapi/callback-test", + "页面支持下拉选择注册事件、填入测试 URL、前端计算签名、模拟回调推送", + "回调事件注册表位于 app/service/openapi/callbackRegistry.js" + ], + "type": "removed" + }, + { + "version": "2026.06.05-openapi-14", + "date": "2026-06-05", + "summary": "增加 timestamp 时效校验(±10分钟),超时返回 400", + "methods": [], + "notes": [ + "所有 OpenAPI 方法增加 timestamp 与服务器时间差校验,超过 ±10 分钟返回 400", + "docs.js 签名说明区同步更新注意事项" + ], + "type": "modified" + }, + { + "version": "2026.06.05-openapi-15", + "date": "2026-06-05", + "summary": "deliveryorder.create 收件人信息改为必填(name/mobile/province/city/area/detailAddress)", + "methods": [ + "deliveryorder.create" + ], + "notes": [ + "receiverInfo 6个字段改为必填,避免快递取号时因地址缺失失败", + "mobile 和 tel 二选一必填" + ], + "type": "modified" + } ] diff --git a/methods/changes/system.json b/methods/changes/system.json index ec9436d..75edba2 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -2496,5 +2496,354 @@ ], "type": "updated", "module": "print" + }, + { + "version": "2026.06.03-system-01", + "date": "2026-06-03", + "summary": "同步 pick.query 文档为 keyword 任务化语义并补充冲突错误码", + "methods": [ + "pick.query" + ], + "notes": [ + "入参由 waybill_code/full_display 统一为 keyword(支持运单号或波次号)。", + "成功返回调整为 task_id/status/tip,status 取值 existing 或 created。", + "补充 409 冲突语义:波次已有他人活动任务时返回任务归属信息。" + ], + "type": "updated" + }, + { + "version": "2026.06.03-system-02", + "date": "2026-06-03", + "summary": "更新 pick.wavePickTaskDetail:增加快递号/储位分配前置校验并返回 action+order_ids", + "methods": [ + "pick.wavePickTaskDetail" + ], + "notes": [ + "新增前置校验:任务内若存在未分配快递号订单,返回 400,data.action=assign_express,data.order_ids 为未分配订单ID列表。", + "新增前置校验:任务内若存在未分配储位订单,返回 400,data.action=assign_storage,data.order_ids 为未分配订单ID列表。", + "保留原有权限校验与详情结构,仅补充分配校验失败分支的返回约定。" + ], + "type": "updated" + }, + { + "version": "2026.06.03-system-03", + "date": "2026-06-03", + "summary": "更新 order.wave.batchList:新增同步状态输出与筛选 sync_assignment_status", + "methods": [ + "order.wave.batchList" + ], + "notes": [ + "新增返回字段语义:list[].sync_assignment_status,取值为未同步/部分同步/已同步/同步异常。", + "新增筛选入参 where.sync_assignment_status,支持 unsynced/partially_synced/synced 英文枚举。", + "同步状态筛选规则与分配状态一致:error 并入 unsynced 过滤集合。" + ], + "type": "updated" + }, + { + "version": "2026.06.03-system-04", + "date": "2026-06-03", + "summary": "更新拣货中间态流程文档:wavePickTaskDetail 增加完成标记,并新增中间态/完全提交接口", + "methods": [ + "pick.wavePickTaskDetail", + "pick.wavePickTaskSubmit", + "pick.wavePickTaskComplete" + ], + "notes": [ + "更新 pick.wavePickTaskDetail 返回:新增 task.is_completed、task.progress(total_orders/picked_orders/pending_orders)以及顶层 is_completed。", + "新增 pick.wavePickTaskSubmit:支持保存中间态 payload 到任务 ext_json.pick_intermediate,并返回当前完成状态与进度。", + "新增 pick.wavePickTaskComplete:支持 mode=1 全部确认与 mode=2 部分确认(order_ids),返回 confirmed_order_ids 与最新进度。" + ], + "type": "updated" + }, + { + "version": "2026.06.03-system-05", + "date": "2026-06-03", + "summary": "拣货车能力拆分为一级模块 pickCart:扫码查询、任务绑车、CRUD、编码查重", + "methods": [ + "pickCart.scan", + "pickCart.bindTaskCart", + "pickCart.create", + "pickCart.update", + "pickCart.delete", + "pickCart.detail", + "pickCart.list", + "pickCart.codeDuplicateCheck" + ], + "notes": [ + "拣货车能力独立为一级模块 pickCart,不再挂在 pick 模块下。", + "新增 pickCart.scan:PDA 按 cart_code 扫码查询拣货车信息,用于进入任务绑定流程。", + "新增 pickCart.bindTaskCart:支持按 cart_id/cart_code 将拣货车绑定到指定拣货任务,若车已绑定其他活动任务则返回冲突。", + "新增 pickCart.create/pickCart.update/pickCart.delete/pickCart.detail/pickCart.list:补齐拣货车增删查改与分页查询能力。", + "新增 pickCart.codeDuplicateCheck:支持 exclude_cart_id 排除自身,供编辑场景做非自身重复校验;拣货车编码在当前仓库内不可重复。" + ], + "type": "updated" + }, + { + "version": "2026.06.03-system-06", + "date": "2026-06-03", + "summary": "更新 order.wave.batchList:新增 only_todo、复核状态聚合与复核筛选", + "methods": [ + "order.wave.batchList" + ], + "notes": [ + "新增入参 only_todo(默认 0):传 1/true 时仅返回仍有未复核订单的波次(unreviewed_order_count > 0)。", + "新增返回字段:list[].unreviewed_order_count(未复核订单数)与 list[].review_assignment_status(未复核/部分复核/已复核)。", + "新增 where.review_assignment_status 筛选,支持 unreviewed/partially_reviewed/reviewed 英文枚举。" + ], + "type": "updated", + "module": "order.wave" + }, + { + "version": "2026.06.04-system-01", + "date": "2026-06-04", + "summary": "裁剪 pick.wavePickTaskDetail 返回:团购小波次(pick_mode=1)不返回 picking_details 字段以减少带宽", + "methods": [ + "pick.wavePickTaskDetail" + ], + "notes": [ + "在 picking_details 字段 description 中补充:当 pick_mode=1(团购小波次)时该字段不返回,减少带宽浪费;其他 pick_mode(2/3/4/5)正常返回 picking_details。", + "在接口 description 中补充该裁剪行为的说明。", + "picking_summary、picking_view、boxes 等字段不受影响,pick_mode=1 时仍正常返回。" + ], + "type": "updated" + }, + { + "version": "2026.06.04-system-02", + "date": "2026-06-04", + "summary": "完善 index.getPlatformList 文档:补充入参 systemOnly/full、响应字段及错误码 500", + "methods": [ + "index.getPlatformList" + ], + "notes": [ + "补充入参说明:systemOnly(可选,支持 is_system 别名,真值识别 true/1/'1'/'true')、full(可选,真值识别同上,为 true 时返回全量表字段与 route_platform_code/platid 等扩展信息)", + "补充响应 data 数组每项字段:code、name、value、label、platform_code、platform_name、default_express_interface、is_system_setting、id(仅仓库自定义项)、alias(仅仓库自定义项)、full 模式扩展字段说明", + "说明合并逻辑:系统平台在前,仓库自定义在后,同 code 仅保留首条(系统优先);systemOnly=true 仅返回系统平台", + "补充缓存策略:优先读缓存,key 格式为 platform:list:{warehouseId}[:full] 或 platform:list:system[:full]", + "补充错误码 500:数据库或缓存访问异常", + "仅文档更新,不修改任何业务实现" + ], + "type": "updated", + "module": "index" + }, + { + "version": "2026.06.04-system-03", + "date": "2026-06-04", + "summary": "作废 order.pendingOrder.downloadCreateTemplate 和 order.pendingOrder.importOrdersFromExcel", + "methods": [ + "order.pendingOrder.downloadCreateTemplate", + "order.pendingOrder.importOrdersFromExcel" + ], + "notes": [ + "order.pendingOrder.downloadCreateTemplate:下载订单导入模板方法已从代码中移除,标记为 deprecated。", + "order.pendingOrder.importOrdersFromExcel:从 Excel 导入订单方法已从代码中移除,标记为 deprecated。", + "两个方法的文档条目保留在 methods/system.json 中,仅追加 status: 'deprecated' 与 description 中的'(已作废)'标记,未删除。" + ], + "type": "deprecated" + }, + { + "version": "2026.06.05-system-01", + "date": "2026-06-05", + "summary": "新增 storeWarehouse.store.openAccount 接口:仓库代货主一键开户(合并注册账号+创建货主+签约)", + "methods": [ + "storeWarehouse.store.openAccount" + ], + "notes": [ + "新增 storeWarehouse.store.openAccount 方法,归属货主-仓库签约模块(storeWarehouse.store)。", + "接口同时完成账号注册、货主创建和仓库-货主签约,一步完成开户全流程。", + "当前主体必须为仓库角色(Authorization header 中携带的 token 对应仓库用户)。", + "必填参数:username(登录账号)、password(初始密码)、company_name(公司全称)、business_license(营业执照号)、contact_person(联系人)、contact_phone(联系电话)。", + "响应返回新创建的 store_id、account_id、contract_id、company_name、username、role_id。" + ], + "type": "added", + "module": "storeWarehouse" + }, + { + "version": "2026.06.05-system-02", + "date": "2026-06-05", + "summary": "优化 storeWarehouse.store.openAccount 必填参数:password 改为随机生成、business_license 和 contact_phone 改为可选,必填仅剩 username/company_name/contact_person 三个", + "methods": [ + "storeWarehouse.store.openAccount" + ], + "notes": [ + "password:由必填改为可选,不传时自动随机生成 12 位密码", + "business_license:由必填改为可选", + "contact_phone:由必填改为可选" + ], + "type": "updated" + }, + { + "version": "2026.06.05-system-03", + "date": "2026-06-05", + "summary": "saveApiConfig 增加 callback_url 参数,支持配置 API 回调通知地址", + "methods": [ + "storeWarehouse.store.saveApiConfig" + ], + "notes": [ + "新增 callback_url 参数:OpenAPI 类型接口支持配置回调通知 URL", + "兼容别名 callbackUrl,最大 500 字符", + "存入 wms_api_app.callback_url 字段" + ], + "type": "modified" + }, + { + "version": "2026.06.05-system-04", + "date": "2026-06-05", + "summary": "createOrder 入参 item_code 改为 item_id,province/city/area 改为必填", + "methods": [ + "order.pendingOrder.createOrder" + ], + "notes": [ + "items[].item_code → items[].item_id:改用商品主键直接匹配,不依赖外部系统商品推送", + "province/city/area 新增必填校验,空值返回 400", + "item_name 优先外部传入,其次从 StockStore 缓存获取,最后兜底'商品'" + ], + "type": "modified" + }, + { + "version": "2026.06.05-system-05", + "date": "2026-06-05", + "summary": "新增 order.pendingOrder.parseAddress 智能地址解析方法", + "methods": [ + "order.pendingOrder.parseAddress" + ], + "notes": [ + "使用 DeepSeek AI 模型将非结构化地址字符串解析为省/市/区/详细地址/收件人/手机号", + "解析结果可直接用于 createOrder 的 receiverInfo 字段", + "DeepSeek API Key 通过 DEEPSEEK_API_KEY 环境变量配置" + ], + "type": "added" + }, + { + "version": "2026.06.05-system-06", + "date": "2026-06-05", + "summary": "waveStrategyUpdate/waveStrategyCreate 新增 wave_prefix 参数", + "methods": [ + "order.wave.waveStrategyUpdate", + "order.wave.waveStrategyCreate" + ], + "notes": [ + "新增 wave_prefix 波次编号前缀字段,最多 5 个字符,为空存 null" + ], + "type": "modified" + }, + { + "version": "2026.06.05-system-07", + "date": "2026-06-05", + "summary": "parseAddress 响应新增 town 字段(乡镇/街道)", + "methods": [ + "order.pendingOrder.parseAddress" + ], + "notes": [ + "响应 data 中新增 town 字段,返回 AI 解析出的乡镇/街道名称" + ], + "type": "modified" + }, + { + "version": "2026.06.05-system-08", + "date": "2026-06-05", + "summary": "为 order.list 响应新增 recheck_status 字段(复核状态:none=未复核,fin=已复核)", + "methods": [ + "order.list" + ], + "notes": [ + "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" + ], + "type": "updated" + }, + { + "version": "2026.06.05-system-09", + "date": "2026-06-05", + "summary": "为 order.reviewOrder.list 响应新增 recheck_status 字段(复核状态:none=未复核,fin=已复核)", + "methods": [ + "order.reviewOrder.list" + ], + "notes": [ + "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" + ], + "type": "updated" + }, + { + "version": "2026.06.05-system-10", + "date": "2026-06-05", + "summary": "为 order.pendingOrder.list 响应新增 recheck_status 字段(复核状态:none=未复核,fin=已复核)", + "methods": [ + "order.pendingOrder.list" + ], + "notes": [ + "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" + ], + "type": "updated" + }, + { + "version": "2026.06.05-system-11", + "date": "2026-06-05", + "summary": "为 order.outboundOrder.list 响应新增 recheck_status 字段(复核状态:none=未复核,fin=已复核)", + "methods": [ + "order.outboundOrder.list" + ], + "notes": [ + "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" + ], + "type": "updated" + }, + { + "version": "2026.06.05-system-12", + "date": "2026-06-05", + "summary": "为 order.expectionOrder.list 响应新增 recheck_status 字段(复核状态:none=未复核,fin=已复核)", + "methods": [ + "order.expectionOrder.list" + ], + "notes": [ + "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" + ], + "type": "updated" + }, + { + "version": "2026.06.05-system-13", + "date": "2026-06-05", + "summary": "为 order.entrustOrder.list 响应新增 recheck_status 字段(复核状态:none=未复核,fin=已复核)", + "methods": [ + "order.entrustOrder.list" + ], + "notes": [ + "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" + ], + "type": "updated" + }, + { + "version": "2026.06.05-system-14", + "date": "2026-06-05", + "summary": "为 order.deliveryOrder.list 响应新增 recheck_status 字段(复核状态:none=未复核,fin=已复核)", + "methods": [ + "order.deliveryOrder.list" + ], + "notes": [ + "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" + ], + "type": "updated" + }, + { + "version": "2026.06.05-system-15", + "date": "2026-06-05", + "summary": "为 order.deliveryExpectionOrder.list 响应新增 recheck_status 字段(复核状态:none=未复核,fin=已复核)", + "methods": [ + "order.deliveryExpectionOrder.list" + ], + "notes": [ + "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" + ], + "type": "updated" + }, + { + "version": "2026.06.05-system-16", + "date": "2026-06-05", + "summary": "为 order.archiveOrder.list 响应新增 recheck_status 字段(复核状态:none=未复核,fin=已复核)", + "methods": [ + "order.archiveOrder.list" + ], + "notes": [ + "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" + ], + "type": "updated" } ] diff --git a/methods/openapi.json b/methods/openapi.json index b424c12..c944d3e 100644 --- a/methods/openapi.json +++ b/methods/openapi.json @@ -1,160 +1,1463 @@ { "module": "openapi", "description": "开放 API 统一入口,独立链路,HTTP POST /openapi,记录入口校验/鉴权规则与返回格式。", - "version": "2026.04.26-openapi-04", - "updatedAt": "2026-04-26", + "version": "2026.06.05-openapi-15", + "updatedAt": "2026-06-05", "http": { "path": "/openapi", "method": "POST" }, "headers": [], - "endpoints": [ - { - "method": "openapi.index", - "description": "开放 API 统一入口,接收 POST /openapi;完成 JSON body 解析、app_key 校验与签名校验,返回统一响应(与系统 style 的 code/message/data 保持一致)。", - "isNeedAuth": false, - "isNeedLogin": false, - "headers": [], - "params": [ - { - "name": "method", - "type": "string", - "required": true, - "source": "query", - "description": "目标系统方法名,必填(例如 order.list)" - }, - { - "name": "v", - "type": "string", - "required": true, - "source": "query", - "description": "API 版本号" - }, - { - "name": "timestamp", - "type": "number", - "required": true, - "source": "query", - "description": "时间戳(数字)" - }, - { - "name": "app_key", - "type": "string", - "required": true, - "source": "query", - "description": "开放平台分配的 app_key;兼容别名 appkey 与 self_app_key(任一存在即可)" - }, - { - "name": "sign", - "type": "string", - "required": true, - "source": "query", - "description": "签名字段,兼容别名 signature(MD5 小写 hex)" - } - ], - "requestBody": [ - { - "name": "body", - "type": "object", - "required": true, - "source": "body", - "description": "请求体必须为 JSON;入口优先读取 rawBody,空体或非 JSON 返回 400,错误文案为 'json数据为空' 或 'json数据解析错误'。" - } - ], - "response": [ - { - "name": "code", - "type": "number", - "required": true, - "description": "业务码:成功通常为 1" - }, - { - "name": "message", - "type": "string", - "required": true, - "description": "提示消息" - }, - { - "name": "data", - "type": "object", - "required": false, - "description": "接口返回数据" - }, - { - "name": "timestamp", - "type": "number", - "required": true, - "description": "响应时间戳" - } - ], - "errors": [ - { - "code": 400, - "message": "参数缺失或错误: method/v/timestamp 或 app_key" - }, - { - "code": 400, - "message": "json数据为空" - }, - { - "code": 400, - "message": "json数据解析错误" - }, - { - "code": 401, - "message": "app_key 无效或不可用" - }, - { - "code": 401, - "message": "签名校验失败" - }, - { - "code": 500, - "message": "接口错误: " - } - ], - "notes": [ - "独立链路:/openapi 为独立入口,不依附于 system/qimen,不复用系统的请求头强校验或鉴权链。", - "不校验 platform/project 等请求头:openapi 不对 platform/project 请求头做强制校验或拒绝,headers 字段为空。", - "body 使用 JSON 解析:content-type 应包含 application/json;优先读取 ctx.request.rawBody,若未提供则回退到 ctx.request.body 或原始请求流;空体或解析失败返回 400(错误消息为 'json数据为空' 或 'json数据解析错误')。", - "app_key 校验:通过数据库表 wms_api_app(或对应模型)按 self_app_key/app_key 查询,要求 is_enabled=1 且 interface_type_id=2(OPEN_API 类型)才视为有效,否则返回 401(消息 'app_key 无效或不可用')。", - "签名规则:构建 canonicalQuery(取 query 参数,支持别名 app_key/appkey/self_app_key,签名字段支持 sign/signature;排除签名字段本身),按 key 的字母序排序并用 & 连接 key=value;计算 bodySign 为 md5(稳定序列化(body));将 canonicalQuery + self_app_secret + bodySign 连接成字符串并对该字符串计算 md5(小写 hex),结果与请求中 sign/signature 比对,匹配即通过。", - "method 分发:openapi 的 method 分发走 openapiMethods 专用目录(代码内实现独立路由/分发);已存在方法示例:index.ping(模块=基础模块)。", - "返回风格:成功与失败返回使用与系统一致的 code/message/data 格式(无需额外 flag 字段),以保证与系统端点兼容。" - ] - }, - { - "method": "index.ping", - "description": "基础模块 心跳接口,返回服务可用性(部署在 openapiMethods 中)", - "isNeedAuth": false, - "isNeedLogin": false, - "headers": [], - "params": [], - "response": [ - { - "name": "code", - "type": "number", - "required": true, - "description": "业务状态码,成功通常为 200 或 1" - }, - { - "name": "message", - "type": "string", - "required": true, - "description": "提示信息" - }, - { - "name": "data", - "type": "object", - "required": false, - "description": "返回数据,ping 一般为空或包含版本/uptime 等信息" - } - ], - "errors": [], - "notes": [ - "模块:基础模块", - "方法部署位置:openapiMethods/index.ping" - ] - } - ] + "methods": { + "groups": [ + { + "groupName": "基础模块", + "module": "index", + "list": [ + { + "method": "index.ping", + "description": "基础模块 心跳接口,返回服务可用性(部署在 openapiMethods 中)", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "业务状态码,成功通常为 200 或 1" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息" + }, + { + "name": "data", + "type": "object", + "required": false, + "description": "返回数据,ping 一般为空或包含版本/uptime 等信息" + } + ], + "errors": [], + "notes": [ + "模块:基础模块", + "方法部署位置:openapiMethods/index.ping", + "timestamp 时间戳时效校验:与服务器时间差不得超过 ±10 分钟(600 秒),否则返回 400" + ] + } + ] + }, + { + "groupName": "发货单模块", + "module": "deliveryorder", + "list": [ + { + "method": "deliveryorder.create", + "description": "deliveryorder 模块 创建发货单接口,支持传入订单主信息、收件人信息和订单明细", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "deliveryOrder", + "type": "object", + "required": true, + "source": "body", + "description": "发货单主信息对象" + }, + { + "name": "deliveryOrder.deliveryOrderCode", + "type": "string", + "required": true, + "source": "body", + "description": "发货单编码(必填),外部系统的唯一订单号" + }, + { + "name": "deliveryOrder.preDeliveryOrderCode", + "type": "string", + "required": false, + "source": "body", + "description": "前发货单编码,用于关联前置订单" + }, + { + "name": "deliveryOrder.preDeliveryOrderId", + "type": "string", + "required": false, + "source": "body", + "description": "前发货单ID,用于关联前置订单" + }, + { + "name": "deliveryOrder.orderType", + "type": "string", + "required": false, + "source": "body", + "description": "订单类型,如 JYCK(一般出库)、PTCK(普通出库)等" + }, + { + "name": "deliveryOrder.warehouseCode", + "type": "string", + "required": false, + "source": "body", + "description": "仓库编码,用于指定发货仓库" + }, + { + "name": "deliveryOrder.orderFlag", + "type": "string", + "required": false, + "source": "body", + "description": "订单标记,自定义标记位" + }, + { + "name": "deliveryOrder.sourcePlatformCode", + "type": "string", + "required": false, + "source": "body", + "description": "来源平台编码,如 TB(淘宝)、JD(京东)、PDD(拼多多)等;匹配不到时自动使用货主默认平台" + }, + { + "name": "deliveryOrder.sourcePlatformName", + "type": "string", + "required": false, + "source": "body", + "description": "来源平台名称" + }, + { + "name": "deliveryOrder.createTime", + "type": "string", + "required": false, + "source": "body", + "description": "订单创建时间,支持 ISO 8601 格式" + }, + { + "name": "deliveryOrder.placeOrderTime", + "type": "string", + "required": false, + "source": "body", + "description": "下单时间,支持 ISO 8601 格式" + }, + { + "name": "deliveryOrder.payTime", + "type": "string", + "required": false, + "source": "body", + "description": "支付时间,支持 ISO 8601 格式" + }, + { + "name": "deliveryOrder.payNo", + "type": "string", + "required": false, + "source": "body", + "description": "支付单号" + }, + { + "name": "deliveryOrder.shopNick", + "type": "string", + "required": false, + "source": "body", + "description": "店铺昵称" + }, + { + "name": "deliveryOrder.sellerNick", + "type": "string", + "required": false, + "source": "body", + "description": "卖家昵称" + }, + { + "name": "deliveryOrder.buyerNick", + "type": "string", + "required": false, + "source": "body", + "description": "买家昵称" + }, + { + "name": "deliveryOrder.operatorName", + "type": "string", + "required": false, + "source": "body", + "description": "操作人姓名,未传入时自动按 API 应用名称回填" + }, + { + "name": "deliveryOrder.operateTime", + "type": "string", + "required": false, + "source": "body", + "description": "操作时间,支持 ISO 8601 格式" + }, + { + "name": "deliveryOrder.totalAmount", + "type": "number", + "required": false, + "source": "body", + "description": "订单总金额" + }, + { + "name": "deliveryOrder.itemAmount", + "type": "number", + "required": false, + "source": "body", + "description": "商品总金额" + }, + { + "name": "deliveryOrder.discountAmount", + "type": "number", + "required": false, + "source": "body", + "description": "折扣金额" + }, + { + "name": "deliveryOrder.freight", + "type": "number", + "required": false, + "source": "body", + "description": "运费" + }, + { + "name": "deliveryOrder.arAmount", + "type": "number", + "required": false, + "source": "body", + "description": "应收金额" + }, + { + "name": "deliveryOrder.gotAmount", + "type": "number", + "required": false, + "source": "body", + "description": "实收金额" + }, + { + "name": "deliveryOrder.logisticsCode", + "type": "string", + "required": false, + "source": "body", + "description": "快递编码,用于指定物流公司;匹配不到时自动使用货主默认快递" + }, + { + "name": "deliveryOrder.expressCode", + "type": "string", + "required": false, + "source": "body", + "description": "快递公司编码" + }, + { + "name": "deliveryOrder.logisticsAreaCode", + "type": "string", + "required": false, + "source": "body", + "description": "快递区域编码" + }, + { + "name": "deliveryOrder.isUrgency", + "type": "string", + "required": false, + "source": "body", + "description": "是否加急,Y=是,N=否,默认 N" + }, + { + "name": "deliveryOrder.invoiceFlag", + "type": "string", + "required": false, + "source": "body", + "description": "是否需要发票,Y=是,N=否,默认 N" + }, + { + "name": "deliveryOrder.enableExternalExpressCode", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否启用外部快递编码匹配,开启后将优先按传入的 logisticsCode 匹配快递设置表" + }, + { + "name": "deliveryOrder.receiverInfo", + "type": "object", + "required": false, + "source": "body", + "description": "收件人信息对象" + }, + { + "name": "deliveryOrder.receiverInfo.name", + "type": "string", + "required": true, + "source": "body", + "description": "收件人姓名" + }, + { + "name": "deliveryOrder.receiverInfo.tel", + "type": "string", + "required": false, + "source": "body", + "description": "收件人固定电话" + }, + { + "name": "deliveryOrder.receiverInfo.mobile", + "type": "string", + "required": true, + "source": "body", + "description": "收件人手机号码" + }, + { + "name": "deliveryOrder.receiverInfo.email", + "type": "string", + "required": false, + "source": "body", + "description": "收件人邮箱" + }, + { + "name": "deliveryOrder.receiverInfo.countryCode", + "type": "string", + "required": false, + "source": "body", + "description": "国家编码" + }, + { + "name": "deliveryOrder.receiverInfo.province", + "type": "string", + "required": true, + "source": "body", + "description": "省份" + }, + { + "name": "deliveryOrder.receiverInfo.city", + "type": "string", + "required": true, + "source": "body", + "description": "城市" + }, + { + "name": "deliveryOrder.receiverInfo.area", + "type": "string", + "required": true, + "source": "body", + "description": "区县" + }, + { + "name": "deliveryOrder.receiverInfo.town", + "type": "string", + "required": false, + "source": "body", + "description": "乡镇/街道" + }, + { + "name": "deliveryOrder.receiverInfo.detailAddress", + "type": "string", + "required": true, + "source": "body", + "description": "详细地址" + }, + { + "name": "deliveryOrder.receiverInfo.zipCode", + "type": "string", + "required": false, + "source": "body", + "description": "邮政编码" + }, + { + "name": "orderLines", + "type": "object", + "required": true, + "source": "body", + "description": "订单明细对象,包含 orderLine 数组" + }, + { + "name": "orderLines.orderLine", + "type": "array", + "required": true, + "source": "body", + "description": "订单明细列表,数组中每项为一个订单行对象" + }, + { + "name": "[].orderLine.itemCode", + "type": "string", + "required": false, + "source": "body", + "description": "商品编码,与 itemId 二选一,用于匹配仓库中的商品" + }, + { + "name": "[].orderLine.itemId", + "type": "number", + "required": false, + "source": "body", + "description": "仓库商品主键ID,与 itemCode 二选一" + }, + { + "name": "[].orderLine.itemName", + "type": "string", + "required": false, + "source": "body", + "description": "商品名称,用于错误提示中的商品识别" + }, + { + "name": "[].orderLine.planQty", + "type": "number", + "required": true, + "source": "body", + "description": "计划发货数量(必填),必须大于 0" + }, + { + "name": "[].orderLine.actualPrice", + "type": "number", + "required": false, + "source": "body", + "description": "实际单价" + }, + { + "name": "[].orderLine.retailPrice", + "type": "number", + "required": false, + "source": "body", + "description": "零售单价" + }, + { + "name": "[].orderLine.extCode", + "type": "string", + "required": false, + "source": "body", + "description": "外部商品编码" + }, + { + "name": "[].orderLine.inventoryType", + "type": "string", + "required": false, + "source": "body", + "description": "库存类型,如 ZP(正品)、CC(残次品)" + }, + { + "name": "[].orderLine.orderLineNo", + "type": "string", + "required": false, + "source": "body", + "description": "订单行号,未传入时自动按序号生成(1、2、3...)" + }, + { + "name": "[].orderLine.ownerCode", + "type": "string", + "required": false, + "source": "body", + "description": "货主编码" + }, + { + "name": "[].orderLine.sourceOrderCode", + "type": "string", + "required": false, + "source": "body", + "description": "来源订单编码,用于关联上游订单" + }, + { + "name": "[].orderLine.subSourceOrderCode", + "type": "string", + "required": false, + "source": "body", + "description": "子来源订单编码" + }, + { + "name": "[].orderLine.extendProps", + "type": "string", + "required": false, + "source": "body", + "description": "扩展属性,JSON 字符串或对象,用于存储自定义字段" + } + ], + "requestBody": [ + { + "name": "deliveryOrder", + "type": "object", + "required": true, + "source": "body", + "description": "发货单主信息对象" + }, + { + "name": "deliveryOrder.deliveryOrderCode", + "type": "string", + "required": true, + "source": "body", + "description": "发货单编码(必填),外部系统的唯一订单号" + }, + { + "name": "deliveryOrder.preDeliveryOrderCode", + "type": "string", + "required": false, + "source": "body", + "description": "前发货单编码,用于关联前置订单" + }, + { + "name": "deliveryOrder.preDeliveryOrderId", + "type": "string", + "required": false, + "source": "body", + "description": "前发货单ID,用于关联前置订单" + }, + { + "name": "deliveryOrder.orderType", + "type": "string", + "required": false, + "source": "body", + "description": "订单类型,如 JYCK(一般出库)、PTCK(普通出库)等" + }, + { + "name": "deliveryOrder.warehouseCode", + "type": "string", + "required": false, + "source": "body", + "description": "仓库编码,用于指定发货仓库" + }, + { + "name": "deliveryOrder.orderFlag", + "type": "string", + "required": false, + "source": "body", + "description": "订单标记,自定义标记位" + }, + { + "name": "deliveryOrder.sourcePlatformCode", + "type": "string", + "required": false, + "source": "body", + "description": "来源平台编码,如 TB(淘宝)、JD(京东)、PDD(拼多多)等;匹配不到时自动使用货主默认平台" + }, + { + "name": "deliveryOrder.sourcePlatformName", + "type": "string", + "required": false, + "source": "body", + "description": "来源平台名称" + }, + { + "name": "deliveryOrder.createTime", + "type": "string", + "required": false, + "source": "body", + "description": "订单创建时间,支持 ISO 8601 格式" + }, + { + "name": "deliveryOrder.placeOrderTime", + "type": "string", + "required": false, + "source": "body", + "description": "下单时间,支持 ISO 8601 格式" + }, + { + "name": "deliveryOrder.payTime", + "type": "string", + "required": false, + "source": "body", + "description": "支付时间,支持 ISO 8601 格式" + }, + { + "name": "deliveryOrder.payNo", + "type": "string", + "required": false, + "source": "body", + "description": "支付单号" + }, + { + "name": "deliveryOrder.shopNick", + "type": "string", + "required": false, + "source": "body", + "description": "店铺昵称" + }, + { + "name": "deliveryOrder.sellerNick", + "type": "string", + "required": false, + "source": "body", + "description": "卖家昵称" + }, + { + "name": "deliveryOrder.buyerNick", + "type": "string", + "required": false, + "source": "body", + "description": "买家昵称" + }, + { + "name": "deliveryOrder.operatorName", + "type": "string", + "required": false, + "source": "body", + "description": "操作人姓名,未传入时自动按 API 应用名称回填" + }, + { + "name": "deliveryOrder.operateTime", + "type": "string", + "required": false, + "source": "body", + "description": "操作时间,支持 ISO 8601 格式" + }, + { + "name": "deliveryOrder.totalAmount", + "type": "number", + "required": false, + "source": "body", + "description": "订单总金额" + }, + { + "name": "deliveryOrder.itemAmount", + "type": "number", + "required": false, + "source": "body", + "description": "商品总金额" + }, + { + "name": "deliveryOrder.discountAmount", + "type": "number", + "required": false, + "source": "body", + "description": "折扣金额" + }, + { + "name": "deliveryOrder.freight", + "type": "number", + "required": false, + "source": "body", + "description": "运费" + }, + { + "name": "deliveryOrder.arAmount", + "type": "number", + "required": false, + "source": "body", + "description": "应收金额" + }, + { + "name": "deliveryOrder.gotAmount", + "type": "number", + "required": false, + "source": "body", + "description": "实收金额" + }, + { + "name": "deliveryOrder.logisticsCode", + "type": "string", + "required": false, + "source": "body", + "description": "快递编码,用于指定物流公司;匹配不到时自动使用货主默认快递" + }, + { + "name": "deliveryOrder.expressCode", + "type": "string", + "required": false, + "source": "body", + "description": "快递公司编码" + }, + { + "name": "deliveryOrder.logisticsAreaCode", + "type": "string", + "required": false, + "source": "body", + "description": "快递区域编码" + }, + { + "name": "deliveryOrder.isUrgency", + "type": "string", + "required": false, + "source": "body", + "description": "是否加急,Y=是,N=否,默认 N" + }, + { + "name": "deliveryOrder.invoiceFlag", + "type": "string", + "required": false, + "source": "body", + "description": "是否需要发票,Y=是,N=否,默认 N" + }, + { + "name": "deliveryOrder.enableExternalExpressCode", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否启用外部快递编码匹配,开启后将优先按传入的 logisticsCode 匹配快递设置表" + }, + { + "name": "deliveryOrder.receiverInfo", + "type": "object", + "required": false, + "source": "body", + "description": "收件人信息对象" + }, + { + "name": "deliveryOrder.receiverInfo.name", + "type": "string", + "required": true, + "source": "body", + "description": "收件人姓名" + }, + { + "name": "deliveryOrder.receiverInfo.tel", + "type": "string", + "required": false, + "source": "body", + "description": "收件人固定电话" + }, + { + "name": "deliveryOrder.receiverInfo.mobile", + "type": "string", + "required": true, + "source": "body", + "description": "收件人手机号码" + }, + { + "name": "deliveryOrder.receiverInfo.email", + "type": "string", + "required": false, + "source": "body", + "description": "收件人邮箱" + }, + { + "name": "deliveryOrder.receiverInfo.countryCode", + "type": "string", + "required": false, + "source": "body", + "description": "国家编码" + }, + { + "name": "deliveryOrder.receiverInfo.province", + "type": "string", + "required": true, + "source": "body", + "description": "省份" + }, + { + "name": "deliveryOrder.receiverInfo.city", + "type": "string", + "required": true, + "source": "body", + "description": "城市" + }, + { + "name": "deliveryOrder.receiverInfo.area", + "type": "string", + "required": true, + "source": "body", + "description": "区县" + }, + { + "name": "deliveryOrder.receiverInfo.town", + "type": "string", + "required": false, + "source": "body", + "description": "乡镇/街道" + }, + { + "name": "deliveryOrder.receiverInfo.detailAddress", + "type": "string", + "required": true, + "source": "body", + "description": "详细地址" + }, + { + "name": "deliveryOrder.receiverInfo.zipCode", + "type": "string", + "required": false, + "source": "body", + "description": "邮政编码" + }, + { + "name": "orderLines", + "type": "object", + "required": true, + "source": "body", + "description": "订单明细对象,包含 orderLine 数组" + }, + { + "name": "orderLines.orderLine", + "type": "array", + "required": true, + "source": "body", + "description": "订单明细列表,数组中每项为一个订单行对象" + }, + { + "name": "[].orderLine.itemCode", + "type": "string", + "required": false, + "source": "body", + "description": "商品编码,与 itemId 二选一,用于匹配仓库中的商品" + }, + { + "name": "[].orderLine.itemId", + "type": "number", + "required": false, + "source": "body", + "description": "仓库商品主键ID,与 itemCode 二选一" + }, + { + "name": "[].orderLine.itemName", + "type": "string", + "required": false, + "source": "body", + "description": "商品名称,用于错误提示中的商品识别" + }, + { + "name": "[].orderLine.planQty", + "type": "number", + "required": true, + "source": "body", + "description": "计划发货数量(必填),必须大于 0" + }, + { + "name": "[].orderLine.actualPrice", + "type": "number", + "required": false, + "source": "body", + "description": "实际单价" + }, + { + "name": "[].orderLine.retailPrice", + "type": "number", + "required": false, + "source": "body", + "description": "零售单价" + }, + { + "name": "[].orderLine.extCode", + "type": "string", + "required": false, + "source": "body", + "description": "外部商品编码" + }, + { + "name": "[].orderLine.inventoryType", + "type": "string", + "required": false, + "source": "body", + "description": "库存类型,如 ZP(正品)、CC(残次品)" + }, + { + "name": "[].orderLine.orderLineNo", + "type": "string", + "required": false, + "source": "body", + "description": "订单行号,未传入时自动按序号生成(1、2、3...)" + }, + { + "name": "[].orderLine.ownerCode", + "type": "string", + "required": false, + "source": "body", + "description": "货主编码" + }, + { + "name": "[].orderLine.sourceOrderCode", + "type": "string", + "required": false, + "source": "body", + "description": "来源订单编码,用于关联上游订单" + }, + { + "name": "[].orderLine.subSourceOrderCode", + "type": "string", + "required": false, + "source": "body", + "description": "子来源订单编码" + }, + { + "name": "[].orderLine.extendProps", + "type": "string", + "required": false, + "source": "body", + "description": "扩展属性,JSON 字符串或对象,用于存储自定义字段" + } + ], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "业务码:1=成功,0=失败" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示消息" + }, + { + "name": "data", + "type": "object", + "required": false, + "description": "创建成功时返回 orderId、step、stats(items_count/item_total/items_weight/source_order_codes)等" + } + ], + "errors": [ + { + "code": 400, + "message": "订单信息不完整(deliveryOrder.deliveryOrderCode 缺失)" + }, + { + "code": 400, + "message": "没有有效的订单明细数据(orderLines.orderLine 为空或数量 ≤0)" + }, + { + "code": 400, + "message": "商品《xxx》编码《xxx》未同步推送到仓库" + }, + { + "code": 409, + "message": "订单已存在(相同 deliveryOrderCode + store_id + warehouse_id)" + } + ], + "notes": [ + "模块:deliveryorder 模块", + "方法部署位置:openapiMethods/deliveryorder.create", + "创建渠道固定为 API,操作人未传入时自动按 API 应用名称回填", + "sourcePlatformCode 传入后优先匹配平台列表;匹配不到则使用货主默认平台", + "logisticsCode 传入后按快递设置表 → 快递列表 → 货主默认快递的优先级匹配", + "orderLines.orderLine 支持单对象或数组格式", + "同一订单中不允许重复的商品(按 itemId 去重)", + "返回的 data.orderId 为系统内部订单主键ID", + "timestamp 时间戳时效校验:与服务器时间差不得超过 ±10 分钟(600 秒),否则返回 400", + "receiverInfo.name / mobile / province / city / area / detailAddress 为快递取号必填字段,请务必传入完整收件人信息", + "mobile 和 tel 二选一必填(快递取号需要至少一个联系电话)" + ] + }, + { + "method": "deliveryorder.query", + "description": "deliveryorder 模块 查询发货单接口,根据发货单编码返回订单详情", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "deliveryOrderCode", + "type": "string", + "required": true, + "source": "body", + "description": "发货单编码(必填),要查询的订单号" + } + ], + "requestBody": [ + { + "name": "deliveryOrderCode", + "type": "string", + "required": true, + "source": "body", + "description": "发货单编码(必填),要查询的订单号" + } + ], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "业务码:1=成功,0=失败" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示消息" + }, + { + "name": "data", + "type": "object", + "required": false, + "description": "查询成功时返回 totalLines、deliveryOrder(deliveryOrderCode/deliveryOrderId/warehouseCode/orderType/status/orderConfirmTime/operatorCode/operatorName/operateTime)、packages、orderLines" + } + ], + "errors": [ + { + "code": 400, + "message": "deliveryOrderCode 参数缺失" + }, + { + "code": 404, + "message": "未找到订单" + } + ], + "notes": [ + "模块:deliveryorder 模块", + "方法部署位置:openapiMethods/deliveryorder.query", + "查询范围为当前 app_key 绑定的仓库,跨仓库订单无法查询", + "timestamp 时间戳时效校验:与服务器时间差不得超过 ±10 分钟(600 秒),否则返回 400" + ] + } + ] + }, + { + "groupName": "订单模块", + "module": "order", + "list": [ + { + "method": "order.cancel", + "description": "order 模块 取消发货单接口,支持直接取消未拣货/未打印的订单;已拣货或已打印的订单改为拦截状态", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "orderCode", + "type": "string", + "required": true, + "source": "body", + "description": "发货单编码(必填),要取消的订单号" + }, + { + "name": "orderType", + "type": "string", + "required": false, + "source": "body", + "description": "订单类型,默认 JYCK(一般交易出库单);当前支持 JYCK(一般交易出库)、HHCK(换货出库)、BFCK(补发出库)" + } + ], + "requestBody": [ + { + "name": "orderCode", + "type": "string", + "required": true, + "source": "body", + "description": "发货单编码(必填),要取消的订单号" + }, + { + "name": "orderType", + "type": "string", + "required": false, + "source": "body", + "description": "订单类型,默认 JYCK(一般交易出库单);当前支持 JYCK(一般交易出库)、HHCK(换货出库)、BFCK(补发出库)" + } + ], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "业务码:1=成功,0=失败" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示消息" + }, + { + "name": "data", + "type": "object", + "required": false, + "description": "取消成功时可能包含订单状态信息" + } + ], + "errors": [ + { + "code": 400, + "message": "订单号不能为空" + }, + { + "code": 400, + "message": "暂不支持该订单类型的取消操作" + }, + { + "code": 404, + "message": "未找到对应的订单" + }, + { + "code": 409, + "message": "取消失败,已通知拦截执行(订单已拣货或已打印,改为拦截状态)" + } + ], + "notes": [ + "模块:order 模块", + "方法部署位置:openapiMethods/order.cancel", + "取消逻辑:未拣货且未打印的订单直接取消(status=cancel, outbound_status=fin, step=4);已拣货或已打印的订单标记为拦截状态(intercept_status=intercepting),不直接取消", + "订单类型映射:JYCK/HHCK/BFCK → 出库单取消;其他类型暂不支持", + "使用事务 + 行锁保证并发安全", + "取消操作为不可逆操作,请谨慎调用", + "timestamp 时间戳时效校验:与服务器时间差不得超过 ±10 分钟(600 秒),否则返回 400" + ] + } + ] + }, + { + "groupName": "商品模块", + "module": "singleitem", + "list": [ + { + "method": "singleitem.synchronize", + "description": "singleitem 模块 商品同步接口,创建或更新商品信息(itemCode 唯一约束,已存在则更新)", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "item", + "type": "object", + "required": true, + "source": "body", + "description": "商品信息对象(必填)" + }, + { + "name": "item.itemCode", + "type": "string", + "required": true, + "source": "body", + "description": "商品编码(必填),唯一标识商品" + }, + { + "name": "item.goodsCode", + "type": "string", + "required": false, + "source": "body", + "description": "商品货号" + }, + { + "name": "item.itemName", + "type": "string", + "required": false, + "source": "body", + "description": "商品名称" + }, + { + "name": "item.skuProperty", + "type": "string", + "required": false, + "source": "body", + "description": "SKU 属性描述,如颜色:红色;尺码:XL" + }, + { + "name": "item.stockUnit", + "type": "string", + "required": false, + "source": "body", + "description": "库存单位,如 件、箱、个" + }, + { + "name": "item.length", + "type": "number", + "required": false, + "source": "body", + "description": "长(cm)" + }, + { + "name": "item.width", + "type": "number", + "required": false, + "source": "body", + "description": "宽(cm)" + }, + { + "name": "item.height", + "type": "number", + "required": false, + "source": "body", + "description": "高(cm)" + }, + { + "name": "item.volume", + "type": "number", + "required": false, + "source": "body", + "description": "体积(cm³)" + }, + { + "name": "item.grossWeight", + "type": "number", + "required": false, + "source": "body", + "description": "毛重(kg)" + }, + { + "name": "item.netWeight", + "type": "number", + "required": false, + "source": "body", + "description": "净重(kg)" + }, + { + "name": "item.categoryId", + "type": "number", + "required": false, + "source": "body", + "description": "商品分类 ID" + }, + { + "name": "item.categoryName", + "type": "string", + "required": false, + "source": "body", + "description": "商品分类名称" + }, + { + "name": "item.itemType", + "type": "string", + "required": false, + "source": "body", + "description": "商品类型,如 NORMAL(普通商品)、SUIT(套装)" + }, + { + "name": "item.tagPrice", + "type": "number", + "required": false, + "source": "body", + "description": "吊牌价" + }, + { + "name": "item.retailPrice", + "type": "number", + "required": false, + "source": "body", + "description": "零售价" + }, + { + "name": "item.brandName", + "type": "string", + "required": false, + "source": "body", + "description": "品牌名称" + }, + { + "name": "item.isSNMgmt", + "type": "string", + "required": false, + "source": "body", + "description": "是否 SN 序列号管理,Y=是,N=否,默认 N" + }, + { + "name": "item.isShelfLifeMgmt", + "type": "string", + "required": false, + "source": "body", + "description": "是否保质期管理,Y=是,N=否,默认 N" + }, + { + "name": "item.isBatchMgmt", + "type": "string", + "required": false, + "source": "body", + "description": "是否批次管理,Y=是,N=否,默认 N" + }, + { + "name": "item.isAreaSale", + "type": "string", + "required": false, + "source": "body", + "description": "是否区域销售,Y=是,N=否,默认 N" + }, + { + "name": "item.createTime", + "type": "string", + "required": false, + "source": "body", + "description": "创建时间,ISO 8601 格式" + }, + { + "name": "item.isValid", + "type": "string", + "required": false, + "source": "body", + "description": "是否有效,Y=是,N=否,默认 Y" + }, + { + "name": "item.barCode", + "type": "string", + "required": false, + "source": "body", + "description": "条形码" + } + ], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "业务码:1=成功,0=失败" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示消息" + }, + { + "name": "data", + "type": "object", + "required": false, + "description": "同步成功时返回 itemId(系统内部商品 ID)" + } + ], + "errors": [ + { + "code": 400, + "message": "参数缺失: item.itemCode" + } + ], + "notes": [ + "模块:singleitem 模块", + "方法部署位置:openapiMethods/singleitem.synchronize", + "同步策略:按 itemCode + app_key + warehouse_id + store_id 唯一约束判断,已存在则更新,不存在则创建", + "同步后会联动创建/更新库存表(StockWarehouse)记录", + "create_from 固定为 qimen(与奇门共用同一套底层逻辑)", + "warehouseCode 和 ownerCode 由 app_key 绑定的仓库/货主自动解析,不可通过请求参数覆盖", + "timestamp 时间戳时效校验:与服务器时间差不得超过 ±10 分钟(600 秒),否则返回 400" + ] + }, + { + "method": "singleitem.query", + "description": "singleitem 模块 商品查询接口,按商品 ID 返回完整商品信息", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "itemId", + "type": "number", + "required": true, + "source": "body", + "description": "商品 ID(必填),系统内部商品主键" + } + ], + "requestBody": [], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "业务码:1=成功,0=失败" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示消息" + }, + { + "name": "data", + "type": "object", + "required": false, + "description": "查询成功时返回 item 对象,包含 itemId/itemCode/goodsCode/itemName/skuProperty/stockUnit/length/width/height/volume/grossWeight/netWeight/categoryId/categoryName/itemType/tagPrice/retailPrice/brandName/isSNMgmt/isShelfLifeMgmt/isBatchMgmt/isAreaSale/barCode/isValid/createTime 等全部商品字段" + } + ], + "errors": [ + { + "code": 400, + "message": "参数错误: itemId 不存在" + }, + { + "code": 404, + "message": "wms 的 SKUID 为 xxx 未找到" + } + ], + "notes": [ + "模块:singleitem 模块", + "方法部署位置:openapiMethods/singleitem.query", + "返回格式与奇门 convertToQimenFormat 一致,字段名使用驼峰命名", + "timestamp 时间戳时效校验:与服务器时间差不得超过 ±10 分钟(600 秒),否则返回 400" + ] + } + ] + }, + { + "groupName": "库存模块", + "module": "inventory", + "list": [ + { + "method": "inventory.query", + "description": "inventory 模块 库存查询接口,按商品 ID 批量查询库存量(可用量、锁定量)", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "itemIds", + "type": "array", + "required": true, + "source": "body", + "description": "商品 ID 列表(必填),如 [1000693, 1000694],支持单个或多个商品批量查询" + }, + { + "name": "[].itemIds", + "type": "number", + "required": true, + "source": "body", + "description": "单个商品 ID,系统内部商品主键,可通过 singleitem.query 或 singleitem.synchronize 返回的 itemId 获取" + } + ], + "requestBody": [], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "业务码:1=成功,0=失败" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示消息" + }, + { + "name": "data", + "type": "object", + "required": false, + "description": "查询成功时返回 items 数组" + }, + { + "name": "data.items", + "type": "array", + "required": false, + "description": "库存信息列表" + }, + { + "name": "[].items.itemId", + "type": "number", + "required": false, + "description": "商品 ID" + }, + { + "name": "[].items.itemCode", + "type": "string", + "required": false, + "description": "商品编码" + }, + { + "name": "[].items.warehouseCode", + "type": "string", + "required": false, + "description": "仓库编码" + }, + { + "name": "[].items.quantity", + "type": "number", + "required": false, + "description": "总库存量" + }, + { + "name": "[].items.lockQuantity", + "type": "number", + "required": false, + "description": "锁定量(已被订单预占的库存)" + }, + { + "name": "[].items.inventoryType", + "type": "string", + "required": false, + "description": "库存类型,固定返回 ZP(正品)" + } + ], + "errors": [ + { + "code": 400, + "message": "itemIds 参数缺失或为空" + }, + { + "code": 404, + "message": "未查询到有效库存信息" + } + ], + "notes": [ + "模块:inventory 模块", + "方法部署位置:openapiMethods/inventory.query", + "支持批量查询多个商品的库存,减少请求次数", + "库存不足(可用量 ≤0)或商品未绑定库存记录时,该条商品不会出现在返回结果中", + "查询范围为当前 app_key 绑定的仓库", + "可用量 = quantity - lockQuantity", + "timestamp 时间戳时效校验:与服务器时间差不得超过 ±10 分钟(600 秒),否则返回 400" + ] + } + ] + } + ] + } } diff --git a/methods/system.json b/methods/system.json index 37a0995..5170308 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1,8 +1,8 @@ { "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", - "version": "0.0.5", - "updatedAt": "2026-05-30", + "version": "0.4.0", + "updatedAt": "2026-06-05", "headers": [ { "name": "platform", @@ -1568,16 +1568,22 @@ "type": "object", "required": true, "description": "分页信息(page、pageSize、total、totalPages、hasPrevious、hasNext)" + }, + { + "name": "recheck_status", + "type": "string", + "required": false, + "description": "复核状态:none=未复核,fin=已复核" } ], "errors": [ { "code": "400", - "description": "缺少仓库上下文或 where 参数格式错误" + "message": "缺少仓库上下文或 where 参数格式错误" }, { "code": "500", - "description": "查询失败" + "message": "查询失败" } ] }, @@ -2364,16 +2370,22 @@ "type": "object", "required": true, "description": "分页信息" + }, + { + "name": "recheck_status", + "type": "string", + "required": false, + "description": "复核状态:none=未复核,fin=已复核" } ], "errors": [ { "code": "400", - "description": "参数格式错误或缺少仓库上下文" + "message": "参数格式错误或缺少仓库上下文" }, { "code": "500", - "description": "查询失败" + "message": "查询失败" } ] }, @@ -2522,7 +2534,7 @@ ] }, { - "groupName": "待处理订单模块", + "groupName": "订单待处理模块", "module": "order.pendingOrder", "list": [ { @@ -2573,16 +2585,22 @@ "type": "object", "required": true, "description": "分页信息" + }, + { + "name": "recheck_status", + "type": "string", + "required": false, + "description": "复核状态:none=未复核,fin=已复核" } ], "errors": [ { "code": "400", - "description": "参数格式错误或缺少仓库上下文" + "message": "参数格式错误或缺少仓库上下文" }, { "code": "500", - "description": "查询失败" + "message": "查询失败" } ] }, @@ -3084,7 +3102,7 @@ }, { "method": "order.pendingOrder.syncOrderIds", - "description": "同步待处理订单入口,仅接收 order_ids 并转发到服务层,当前不做业务处理。", + "description": "同步待处理订单入口,支持批量传入 order_ids。服务端会按 create_channel 分组派发同步任务;若命中 SN 管理订单(is_sn_mgmt=Y),该订单会被拦截并标记失败,不允许走批量回传,需改用单订单回传。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -3101,7 +3119,7 @@ "type": "array|string|number", "required": true, "source": "body", - "description": "订单 ID 列表,支持数组、逗号分隔字符串或单个 ID。当前仅透传到服务层,不做额外处理。" + "description": "订单 ID 列表,支持数组、逗号分隔字符串或单个 ID。服务端会校验订单状态并执行批量同步拦截规则(含 SN 订单限制)。" } ], "response": [ @@ -3135,6 +3153,10 @@ "code": 400, "message": "order_ids 不能为空或格式错误" }, + { + "code": 400, + "message": "SN订单不支持批量回传,请改用单订单回传" + }, { "code": 500, "message": "内部错误:服务层同步失败" @@ -3509,23 +3531,23 @@ { "name": "province", "type": "string", - "required": false, + "required": true, "source": "body", - "description": "省份" + "description": "省份(必填,空值返回 400)" }, { "name": "city", "type": "string", - "required": false, + "required": true, "source": "body", - "description": "城市" + "description": "城市(必填,空值返回 400)" }, { "name": "area", "type": "string", - "required": false, + "required": true, "source": "body", - "description": "区/县" + "description": "区/县(必填,空值返回 400)" }, { "name": "town", @@ -3546,7 +3568,7 @@ "type": "array", "required": true, "source": "body", - "description": "订单明细数组,每项含 item_code(商品编码)和 plan_qty(计划数量,正整数);item_name、order_line_no、actual_price 为可选" + "description": "订单明细数组,每项含 item_id(商品主键,必填,正整数)和 plan_qty(计划数量,正整数);item_name(优先外部传入,其次从 StockStore 缓存获取,最后兜底'商品')、order_line_no、actual_price 为可选" }, { "name": "delivery_order_code", @@ -3652,18 +3674,23 @@ ], "errors": [ { - "code": "400", - "description": "必填字段缺失、items 格式错误或 delivery_order_code 重复" + "code": 400, + "message": "必填字段缺失(含 province/city/area)、items 格式错误(item_id 须为正整数)或 delivery_order_code 重复" }, { - "code": "404", - "description": "货主与仓库无有效合约关系(getContractConfig 返回 null 时降级为需审核)" + "code": 404, + "message": "货主与仓库无有效合约关系(getContractConfig 返回 null 时降级为需审核)" } + ], + "notes": [ + "使用 item_id 直接匹配商品主键,不依赖外部系统商品同步;item_id 可通过 singleitem.synchronize 返回的 itemId 获取", + "province/city/area 为必填项,空值返回 400" ] }, { "method": "order.pendingOrder.downloadCreateTemplate", - "description": "下载创建订单的 Excel 导入模板。返回 base64 编码的 xlsx 文件,前端解码后作为附件下载。表头中标注 * 的列为必填项,多行相同订单号的行组成一个完整订单。", + "description": "下载创建订单的 Excel 导入模板。返回 base64 编码的 xlsx 文件,前端解码后作为附件下载。表头中标注 * 的列为必填项,多行相同订单号的行组成一个完整订单。(已作废)", + "status": "deprecated", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -3699,7 +3726,8 @@ }, { "method": "order.pendingOrder.importOrdersFromExcel", - "description": "通过 Excel 文件批量创建订单。接受 base64 编码的 xlsx 内容,按订单号分组,每组创建一个订单(step 由货主策略决定)。每行代表一条商品明细;同一订单号的多行组成一个完整订单,头信息取每组第一行。", + "description": "通过 Excel 文件批量创建订单。接受 base64 编码的 xlsx 内容,按订单号分组,每组创建一个订单(step 由货主策略决定)。每行代表一条商品明细;同一订单号的多行组成一个完整订单,头信息取每组第一行。(已作废)", + "status": "deprecated", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -3754,9 +3782,104 @@ "errors": [ { "code": "400", - "description": "file_base64 为空、Excel 格式无效或无有效数据行" + "message": "file_base64 为空、Excel 格式无效或无有效数据行" } ] + }, + { + "method": "order.pendingOrder.parseAddress", + "description": "智能地址解析:使用 AI 将非结构化地址字符串解析为省/市/区/详细地址/收件人/手机号", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "address", + "type": "string", + "required": true, + "source": "body", + "description": "原始地址字符串(必填),如\"张三 13800138000 广东省广州市天河区体育西路100号\"" + } + ], + "requestBody": [], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "1=成功,0=失败" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示消息" + }, + { + "name": "data", + "type": "object", + "required": false, + "description": "解析成功时返回 province/city/area/detailAddress/name/mobile" + }, + { + "name": "data.province", + "type": "string", + "required": false, + "description": "省份,如 广东省" + }, + { + "name": "data.city", + "type": "string", + "required": false, + "description": "城市,如 广州市" + }, + { + "name": "data.area", + "type": "string", + "required": false, + "description": "区/县,如 天河区" + }, + { + "name": "data.town", + "type": "string", + "required": false, + "description": "乡镇/街道,如 员村街道" + }, + { + "name": "data.detailAddress", + "type": "string", + "required": false, + "description": "详细地址,如 体育西路100号" + }, + { + "name": "data.name", + "type": "string", + "required": false, + "description": "收件人姓名,如 张三" + }, + { + "name": "data.mobile", + "type": "string", + "required": false, + "description": "收件人手机号,如 13800138000" + } + ], + "errors": [ + { + "code": 400, + "message": "地址字符串不能为空" + }, + { + "code": 500, + "message": "地址解析失败(AI服务异常或密钥未配置)" + } + ], + "notes": [ + "方法部署位置:systemMethods/order/pendingOrder/parseAddress", + "使用 DeepSeek AI 模型进行智能解析", + "解析结果可直接回填到 createOrder 的收件人信息字段", + "未识别到的字段返回空字符串" + ] } ] }, @@ -4013,6 +4136,13 @@ "required": false, "source": "body", "description": "0-不计算(默认),1-计算并返回每条策略的 next_fetch_order_count;支持别名 calculateNextFetchOrderCount" + }, + { + "name": "debug", + "type": "number", + "required": false, + "source": "body", + "description": "0-不启用(默认),1-启用调试输出,返回每条策略的 next_fetch_order_list(含结构/快递/货主ID等指标明细)" } ], "response": [ @@ -4156,6 +4286,80 @@ "name": "next_fetch_order_count", "type": "number", "description": "按当前策略口径预演一次自动抓取时,预计会选中的订单数量;未开启计算时返回 0" + }, + { + "name": "next_fetch_order_list", + "type": "object", + "description": "调试字段,仅 debug=1 时返回。包含候选订单明细及指标(结构、快递、货主ID 等)", + "children": [ + { + "name": "candidate_count", + "type": "number", + "description": "当前策略匹配的候选订单总数" + }, + { + "name": "candidates", + "type": "array", + "description": "候选订单明细列表(最多 500 条)", + "children": [ + { + "name": "order_id", + "type": "number", + "description": "订单ID" + }, + { + "name": "structure", + "type": "object", + "description": "商品结构(items_hash / items)" + }, + { + "name": "express", + "type": "object", + "description": "快递信息(sys_logistics_code / logistics_code / logistics_name)" + }, + { + "name": "store_id", + "type": "string", + "description": "货主ID" + }, + { + "name": "items_count", + "type": "number", + "description": "SKU 种类数" + }, + { + "name": "items_total", + "type": "number", + "description": "商品总件数" + }, + { + "name": "wave_id", + "type": "number", + "description": "当前波次ID(0=未入波次)" + }, + { + "name": "status", + "type": "string", + "description": "订单状态" + }, + { + "name": "outbound_status", + "type": "string", + "description": "出库状态" + }, + { + "name": "post_status", + "type": "string", + "description": "快递分配状态" + }, + { + "name": "storage_status", + "type": "string", + "description": "储位分配状态" + } + ] + } + ] } ] }, @@ -4334,6 +4538,13 @@ "required": false, "source": "body", "description": "允许的快递编码列表(可选,支持数组/JSON/逗号分隔);系统会校验所传编码是否在可用快递列表内,非法值将导致 400 错误。" + }, + { + "name": "wave_prefix", + "type": "string", + "required": false, + "source": "body", + "description": "波次编号前缀(可选),最多 5 个字符,如 D、B、A;不传则保持原值" } ], "response": [ @@ -4353,11 +4564,11 @@ "errors": [ { "code": "400", - "description": "缺少必填参数或参数校验失败(包括 allowed_owners/allowed_expresses 非法)" + "message": "缺少必填参数或参数校验失败(包括 allowed_owners/allowed_expresses 非法)" }, { "code": "500", - "description": "创建失败或内部错误" + "message": "创建失败或内部错误" } ] }, @@ -4521,6 +4732,13 @@ "required": false, "source": "body", "description": "允许的快递编码列表(可选,支持数组/JSON/逗号分隔);系统会校验所传编码是否在可用快递列表内,非法值将导致 400 错误。" + }, + { + "name": "wave_prefix", + "type": "string", + "required": false, + "source": "body", + "description": "波次编号前缀(可选),最多 5 个字符,如 D、B、A;不传则保持原值" } ], "response": [ @@ -4540,15 +4758,15 @@ "errors": [ { "code": "400", - "description": "缺少 id 或无可更新字段或参数校验失败" + "message": "缺少 id 或无可更新字段或参数校验失败" }, { "code": "404", - "description": "波次策略不存在" + "message": "波次策略不存在" }, { "code": "500", - "description": "更新失败或内部错误" + "message": "更新失败或内部错误" } ] }, @@ -7128,16 +7346,22 @@ "type": "object", "required": true, "description": "分页信息" + }, + { + "name": "recheck_status", + "type": "string", + "required": false, + "description": "复核状态:none=未复核,fin=已复核" } ], "errors": [ { "code": "400", - "description": "参数格式错误或缺少仓库上下文" + "message": "参数格式错误或缺少仓库上下文" }, { "code": "500", - "description": "查询失败" + "message": "查询失败" } ] }, @@ -7370,16 +7594,22 @@ "type": "object", "required": true, "description": "分页信息" + }, + { + "name": "recheck_status", + "type": "string", + "required": false, + "description": "复核状态:none=未复核,fin=已复核" } ], "errors": [ { "code": "400", - "description": "参数格式错误或缺少仓库上下文" + "message": "参数格式错误或缺少仓库上下文" }, { "code": "500", - "description": "查询失败" + "message": "查询失败" } ] }, @@ -7555,16 +7785,22 @@ "type": "object", "required": true, "description": "分页信息" + }, + { + "name": "recheck_status", + "type": "string", + "required": false, + "description": "复核状态:none=未复核,fin=已复核" } ], "errors": [ { "code": "400", - "description": "参数格式错误或缺少仓库上下文" + "message": "参数格式错误或缺少仓库上下文" }, { "code": "500", - "description": "查询失败" + "message": "查询失败" } ] }, @@ -7693,16 +7929,22 @@ "type": "object", "required": true, "description": "分页信息" + }, + { + "name": "recheck_status", + "type": "string", + "required": false, + "description": "复核状态:none=未复核,fin=已复核" } ], "errors": [ { "code": "400", - "description": "参数格式错误或缺少仓库上下文" + "message": "参数格式错误或缺少仓库上下文" }, { "code": "500", - "description": "查询失败" + "message": "查询失败" } ] }, @@ -7831,16 +8073,22 @@ "type": "object", "required": true, "description": "分页信息" + }, + { + "name": "recheck_status", + "type": "string", + "required": false, + "description": "复核状态:none=未复核,fin=已复核" } ], "errors": [ { "code": "400", - "description": "参数格式错误或缺少仓库上下文" + "message": "参数格式错误或缺少仓库上下文" }, { "code": "500", - "description": "查询失败" + "message": "查询失败" } ] }, @@ -7969,16 +8217,22 @@ "type": "object", "required": true, "description": "分页信息" + }, + { + "name": "recheck_status", + "type": "string", + "required": false, + "description": "复核状态:none=未复核,fin=已复核" } ], "errors": [ { "code": "400", - "description": "参数格式错误或缺少仓库上下文" + "message": "参数格式错误或缺少仓库上下文" }, { "code": "500", - "description": "查询失败" + "message": "查询失败" } ] }, @@ -10298,12 +10552,115 @@ "list": [ { "method": "index.getPlatformList", - "description": "合并后的平台列表", + "description": "获取平台列表。默认返回系统基础平台与当前登录仓库自定义平台设置的合并结果:系统平台在前,仓库自定义编码在后,同一 `code` 仅保留首条(系统同码优先保留系统记录)。当 `systemOnly` 为真值(支持 `true`、`1`、`'1'`、`'true'`)时,仅返回系统基础平台列表。`full` 为真值时返回全量字段(包含 wms_platform 全部表字段、route_platform_code、platid 等)。仓库范围来自当前登录用户 `ctx.user.store_id`;未识别到仓库时,自定义设置列表为空。接口优先读取缓存,未命中时回源 `wms_platform` 与 `wms_platfrom_setting`。", "isNeedAuth": false, "isNeedLogin": true, - "params": [], - "response": [], - "errors": [] + "headers": [], + "params": [ + { + "name": "systemOnly", + "type": "boolean|number|string", + "required": false, + "source": "body", + "description": "是否仅返回系统基础平台列表;仅 `true`、`1`、`'1'`、`'true'` 会被识别为 true,其余值按 false 处理。也支持 `is_system` 别名(若请求体中同时存在 `is_system` 和 `systemOnly`,优先使用 `is_system`)" + }, + { + "name": "full", + "type": "boolean|number|string", + "required": false, + "source": "body", + "description": "是否返回全量字段;仅 `true`、`1`、`'1'`、`'true'` 会被识别为 true,其余值按 false 处理。为 true 时返回 wms_platform 全部表字段、route_platform_code、platid 等扩展信息" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "全局调用结果标识,成功时为 `success`" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务状态码,成功时返回 200" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "返回消息,成功时通常为 `ok`" + }, + { + "name": "data", + "type": "array", + "required": true, + "description": "平台列表数组。默认模式下先返回系统基础平台,再追加当前仓库自定义设置;`systemOnly=true` 时仅返回系统基础平台。每项字段如下:", + "children": [ + { + "name": "code", + "type": "string", + "description": "平台编码。系统平台项为 `wms_platform.code`;仓库自定义项为 `wms_platfrom_setting.code`" + }, + { + "name": "name", + "type": "string", + "description": "展示名称。系统平台项为 `wms_platform.name`;仓库自定义项格式为 `<自定义编码> (<系统平台名>)`,若未匹配到系统平台名则退化为自定义编码" + }, + { + "name": "value", + "type": "string", + "description": "与 `code` 相同,供前端选项组件直接使用" + }, + { + "name": "label", + "type": "string", + "description": "与 `name` 相同,供前端选项组件直接使用" + }, + { + "name": "platform_code", + "type": "string", + "description": "系统平台编码。系统平台项与 `code` 相同;仓库自定义项为 `wms_platfrom_setting.platform_code`(即该自定义编码所关联的系统平台编码)" + }, + { + "name": "platform_name", + "type": "string", + "description": "系统平台名称。系统平台项与 `name` 相同;仓库自定义项为关联的系统平台名称" + }, + { + "name": "default_express_interface", + "type": "string", + "description": "默认快递接口编码。由 `wms_platform.print_platform_id` → `wms_print_platform.platform_code` 解析得到;未配置时为空字符串" + }, + { + "name": "is_system_setting", + "type": "boolean", + "description": "是否为仓库自定义平台设置。`false` 表示系统基础平台,`true` 表示来自当前仓库 `wms_platfrom_setting` 的自定义编码" + }, + { + "name": "id", + "type": "number|null", + "description": "仅仓库自定义平台设置项返回,为 `wms_platfrom_setting.id` 记录主键;系统平台项不返回该字段" + }, + { + "name": "alias", + "type": "string", + "description": "仅仓库自定义平台设置项返回,当前固定为空字符串(设计预留字段);系统平台项不返回该字段" + }, + { + "name": "(full 模式扩展字段)", + "type": "object", + "description": "当 `full=true` 时,每项额外包含:系统平台项追加 `interface_url`、`appkey`、`app_secret`、`token`、`version`、`shoptype`、`ordersource`、`component`、`print_platform_id`(以上均为 wms_platform 原始表字段)、`route_platform_code`(平台后处理路由编码)、`platid`(打印平台 platid,仅当 print_platform_id 可映射时);仓库自定义项追加 `warehouse_id`、`route_platform_code` 及 wms_platfrom_setting 全部原始字段" + } + ] + } + ], + "errors": [ + { + "code": 500, + "message": "获取平台列表失败(数据库或缓存访问异常)" + } + ] }, { "method": "setting.platform.list", @@ -11082,6 +11439,13 @@ "required": false, "source": "body", "description": "店铺 ID(支持 shopId),正整数,可空;未传或空值按 null 处理" + }, + { + "name": "address", + "type": "string", + "required": false, + "source": "body", + "description": "发件人详细地址(可选),使用 index.getShopExpressList 返回的 detail 字段值,非 full_address" } ], "response": [ @@ -11121,6 +11485,13 @@ "required": false, "source": "body", "description": "shop_id" + }, + { + "name": "address", + "type": "string", + "required": false, + "source": "body", + "description": "发件人详细地址(可选),使用 index.getShopExpressList 返回的 detail 字段值,非 full_address" } ], "response": [ @@ -13205,7 +13576,7 @@ "list": [ { "method": "pick.query", - "description": "按订单查询波次拣货信息,支持 full/full_display/is_full 控制是否完整显示;接口按当前登录用户仓库上下文过滤,防止跨仓越界。", + "description": "按 keyword(运单号或波次号)获取或创建当前用户的拣货任务:命中同用户活动任务返回 existing;无活动任务则创建并返回 created;若活动任务归属他人则返回冲突提示。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -13218,102 +13589,59 @@ ], "params": [ { - "name": "waybill_code", + "name": "keyword", "type": "string", "required": true, "source": "body", - "description": "快递号/运单号,必填。" - }, - { - "name": "full_display", - "type": "boolean", - "required": false, - "source": "body", - "description": "是否完整显示拣货明细;默认 false。true 返回全部拣货明细,false 仅返回未完成的(inspection_status != 'fin')。" + "description": "关键字,支持运单号或波次号。" } ], "response": [ { - "name": "order_id", - "type": "string|number", - "description": "订单 ID" - }, - { - "name": "wave_id", + "name": "task_id", "type": "number", - "description": "波次 ID(若订单未关联波次则为空)" + "required": true, + "description": "拣货任务ID。" }, { - "name": "wave_no", + "name": "status", "type": "string", - "description": "波次编号(若订单未关联波次则为空)" + "required": true, + "description": "任务状态:existing(命中当前用户已有活动任务)或 created(新建成功)。" }, { - "name": "full_display", - "type": "boolean", - "description": "是否以完整明细展示(等同于请求中的 full/full_display/is_full)" - }, - { - "name": "summary", - "type": "object", - "description": "汇总信息", - "children": [ - { - "name": "total_count", - "type": "number", - "description": "明细总行数" - }, - { - "name": "pending_review_count", - "type": "number", - "description": "待复核行数" - }, - { - "name": "reviewed_count", - "type": "number", - "description": "已复核行数" - }, - { - "name": "quantity_total", - "type": "number", - "description": "明细总件数" - }, - { - "name": "display_count", - "type": "number", - "description": "展示行数(受 full 参数影响)" - }, - { - "name": "display_quantity_total", - "type": "number", - "description": "展示的总件数(受 full 参数影响)" - } - ] - }, - { - "name": "list", - "type": "array", - "description": "拣货明细列表(根据 full 参数返回全量或仅未复核明细),每项为明细对象,字段视实现而定。" + "name": "tip", + "type": "string", + "required": true, + "description": "提示文案。" } ], "errors": [ { - "code": "400", - "description": "order_id 为空或订单无波次号" + "code": 400, + "message": "参数错误或目标波次不满足建任务条件(如 keyword 为空、缺少仓库上下文、目标波次信息不完整、散单波次无可用订单)。" }, { - "code": "404", - "description": "订单不存在" + "code": 401, + "message": "未获取到操作人上下文。" }, { - "code": "500", - "description": "内部错误" + "code": 404, + "message": "关键字未命中有效运单/波次,或命中的订单/波次不属于当前仓库。" + }, + { + "code": 409, + "message": "目标波次已存在他人创建的活动任务(失败 data 含 task_id、task_owner_id、task_owner_name)。" + }, + { + "code": 500, + "message": "内部错误(如分表模型不可用或任务创建异常)。" } ] }, { "method": "pick.wavePickTaskDetail", - "description": "按任务ID获取拣货任务详情,返回精简的 task、boxes、picking_details 与 picking_summary;仅允许任务的 pick_user_id 与当前登录用户(operator_id/employees_id)一致时返回数据,否则返回 403。", + "description": "按任务ID获取拣货任务详情。查询前会校验任务内订单是否全部完成快递号与储位分配:若存在未分配快递号或未分配储位订单,将返回 400 并在 data 中返回 action 与 order_ids 供前端触发一键分配;详情响应新增中间态进度语义(task.is_completed、task.progress 与顶层 is_completed),用于前端判断是否已完成与展示阶段进度;仅允许任务的 pick_user_id 与当前登录用户一致时返回详情。当 pick_mode=1(团购小波次)时,picking_details 字段不返回以减少带宽。", "isNeedAuth": false, "isNeedLogin": true, "isNeedRight": false, @@ -13343,39 +13671,85 @@ { "name": "task_id", "type": "number", - "description": "任务ID" + "description": "任务ID", + "required": false }, { "name": "task_no", "type": "string", - "description": "任务编号" + "description": "任务编号", + "required": false }, { "name": "status", "type": "number", - "description": "任务状态" + "description": "任务状态", + "required": false }, { "name": "pick_mode", "type": "number", - "description": "拣货模式" + "description": "拣货模式", + "required": false }, { "name": "start_at", "type": "string", - "description": "开始时间(ISO 字符串或 null)" + "description": "开始时间(ISO 字符串或 null)", + "required": false }, { "name": "finish_at", "type": "string", - "description": "完成时间(ISO 字符串或 null)" + "description": "完成时间(ISO 字符串或 null)", + "required": false }, { "name": "batch_no", "type": "string", - "description": "批次号" + "description": "批次号", + "required": false + }, + { + "name": "is_completed", + "type": "boolean", + "description": "任务是否已完成(订单维度全部已拣或任务状态已进入完成态)", + "required": false + }, + { + "name": "progress", + "type": "object", + "description": "任务订单拣货进度统计", + "required": false, + "children": [ + { + "name": "total_orders", + "type": "number", + "description": "任务订单总数", + "required": false + }, + { + "name": "picked_orders", + "type": "number", + "description": "已确认拣货订单数", + "required": false + }, + { + "name": "pending_orders", + "type": "number", + "description": "待确认拣货订单数", + "required": false + } + ] } - ] + ], + "required": false + }, + { + "name": "is_completed", + "type": "boolean", + "description": "任务是否已完成(与 task.is_completed 含义一致,便于前端直接判断)", + "required": false }, { "name": "boxes", @@ -13385,79 +13759,94 @@ { "name": "task_id", "type": "number", - "description": "任务ID" + "description": "任务ID", + "required": false }, { "name": "box_id", "type": "number", - "description": "箱ID" + "description": "箱ID", + "required": false }, { "name": "box_no", "type": "string", - "description": "箱编码" + "description": "箱编码", + "required": false }, { "name": "box_type", "type": "number", - "description": "箱类型" + "description": "箱类型", + "required": false }, { "name": "status", "type": "number", - "description": "箱状态" + "description": "箱状态", + "required": false }, { "name": "ref_label", "type": "string", - "description": "箱参考标签或关联业务标识(用于前端定位/关联)" + "description": "箱参考标签或关联业务标识(用于前端定位/关联)", + "required": false }, { "name": "required_qty", "type": "number", - "description": "箱内需要拣货的总数量" + "description": "箱内需要拣货的总数量", + "required": false }, { "name": "picked_qty", "type": "number", - "description": "当前已完成拣货的数量" + "description": "当前已完成拣货的数量", + "required": false } - ] + ], + "required": false }, { "name": "picking_details", "type": "array", - "description": "拣货明细列表(按库位/商品/数量拆分),用于从明细视角展示拣货要求", + "description": "拣货明细列表(按库位/商品/数量拆分),用于从明细视角展示拣货要求。注意:当 pick_mode=1(团购小波次)时该字段不返回,减少带宽浪费;其他 pick_mode(2/3/4/5)正常返回。", "children": [ { "name": "order_id", "type": "number", - "description": "订单ID" + "description": "订单ID", + "required": false }, { "name": "order_item_id", "type": "number", - "description": "订单行ID" + "description": "订单行ID", + "required": false }, { "name": "quantity", "type": "number", - "description": "本行需拣货数量" + "description": "本行需拣货数量", + "required": false }, { "name": "storage_id", "type": "number", - "description": "仓库ID" + "description": "仓库ID", + "required": false }, { "name": "space_id", "type": "number", - "description": "库位ID" + "description": "库位ID", + "required": false }, { "name": "space_name", "type": "string", - "description": "库位名称" + "description": "库位名称", + "required": false }, { "name": "location_space", @@ -13467,56 +13856,68 @@ { "name": "space_code", "type": "string", - "description": "库位编码" + "description": "库位编码", + "required": false }, { "name": "custom_name", "type": "string", - "description": "库位自定义名称" + "description": "库位自定义名称", + "required": false }, { "name": "custom_barcode", "type": "string", - "description": "库位自定义条码" + "description": "库位自定义条码", + "required": false }, { "name": "pick_sequence", "type": "number", - "description": "拣货序列,用于路线/优先级排序" + "description": "拣货序列,用于路线/优先级排序", + "required": false }, { "name": "pick_priority", "type": "number", - "description": "拣货优先级(数值越小优先级越高)" + "description": "拣货优先级(数值越小优先级越高)", + "required": false } - ] + ], + "required": false }, { "name": "item_code", "type": "string", - "description": "商品编码" + "description": "商品编码", + "required": false }, { "name": "item_name", "type": "string", - "description": "商品名称" + "description": "商品名称", + "required": false }, { "name": "stock_id", "type": "number", - "description": "库存记录ID(stock 主键)" + "description": "库存记录ID(stock 主键)", + "required": false }, { "name": "plan_qty", "type": "number", - "description": "计划拣货数量(用于与实际拣货对比)" + "description": "计划拣货数量(用于与实际拣货对比)", + "required": false }, { "name": "item_snapshot", "type": "object", - "description": "商品快照(下单时的商品信息,可能包含规格/属性等)" + "description": "商品快照(下单时的商品信息,可能包含规格/属性等)", + "required": false } - ] + ], + "required": false }, { "name": "picking_summary", @@ -13526,24 +13927,29 @@ { "name": "total_lines", "type": "number", - "description": "明细行数(picking_details.length)" + "description": "明细行数(picking_details.length)", + "required": false }, { "name": "total_qty", "type": "number", - "description": "明细总数量(quantity 汇总)" + "description": "明细总数量(quantity 汇总)", + "required": false }, { "name": "distinct_spaces", "type": "number", - "description": "涉及的不同库位数量" + "description": "涉及的不同库位数量", + "required": false }, { "name": "distinct_items", "type": "number", - "description": "涉及的不同商品数量" + "description": "涉及的不同商品数量", + "required": false } - ] + ], + "required": false }, { "name": "picking_view", @@ -13553,27 +13959,32 @@ { "name": "mode_code", "type": "number", - "description": "拣货视图模式编码,与 task.pick_mode 对应" + "description": "拣货视图模式编码,与 task.pick_mode 对应", + "required": false }, { "name": "mode_name", "type": "string", - "description": "拣货视图模式名称" + "description": "拣货视图模式名称", + "required": false }, { "name": "require_box_allocations", "type": "boolean", - "description": "当前模式是否需要箱分配;pick_mode=1/3/4 时为 true,pick_mode=2/5 时为 false" + "description": "当前模式是否需要箱分配;pick_mode=1/3/4 时为 true,pick_mode=2/5 时为 false", + "required": false }, { "name": "group_by", "type": "string", - "description": "分组字段,示例值:\"space+item\"" + "description": "分组字段,示例值:\"space+item\"", + "required": false }, { "name": "sort_by", "type": "array", - "description": "排序字段数组,典型为 [\"pick_sequence\",\"pick_priority\",\"space_id\",\"item_code\"]" + "description": "排序字段数组,典型为 [\"pick_sequence\",\"pick_priority\",\"space_id\",\"item_code\"]", + "required": false }, { "name": "items", @@ -13583,12 +13994,14 @@ { "name": "space_id", "type": "number", - "description": "库位 ID" + "description": "库位 ID", + "required": false }, { "name": "space_name", "type": "string", - "description": "库位名称" + "description": "库位名称", + "required": false }, { "name": "location_space", @@ -13598,49 +14011,59 @@ { "name": "space_code", "type": "string", - "description": "库位编码" + "description": "库位编码", + "required": false }, { "name": "custom_name", "type": "string", - "description": "库位自定义名称" + "description": "库位自定义名称", + "required": false }, { "name": "custom_barcode", "type": "string", - "description": "库位自定义条码" + "description": "库位自定义条码", + "required": false }, { "name": "pick_sequence", "type": "number", - "description": "拣货序列,用于路线/优先级排序" + "description": "拣货序列,用于路线/优先级排序", + "required": false }, { "name": "pick_priority", "type": "number", - "description": "拣货优先级(数值越小优先)" + "description": "拣货优先级(数值越小优先)", + "required": false } - ] + ], + "required": false }, { "name": "item_code", "type": "string", - "description": "商品编码" + "description": "商品编码", + "required": false }, { "name": "item_name", "type": "string", - "description": "商品名称" + "description": "商品名称", + "required": false }, { "name": "stock_id", "type": "number", - "description": "库存记录ID(stock 主键)" + "description": "库存记录ID(stock 主键)", + "required": false }, { "name": "total_qty", "type": "number", - "description": "该库位该商品的总需拣货数量" + "description": "该库位该商品的总需拣货数量", + "required": false }, { "name": "box_allocations", @@ -13650,52 +14073,908 @@ { "name": "box_id", "type": "number", - "description": "箱ID" + "description": "箱ID", + "required": false }, { "name": "box_no", "type": "string", - "description": "箱编码" + "description": "箱编码", + "required": false }, { "name": "box_type", "type": "number", - "description": "箱类型" + "description": "箱类型", + "required": false }, { "name": "required_qty", "type": "number", - "description": "该箱分配需要拣货的数量" + "description": "该箱分配需要拣货的数量", + "required": false }, { "name": "picked_qty", "type": "number", - "description": "该箱已完成拣货的数量" + "description": "该箱已完成拣货的数量", + "required": false }, { "name": "allocated_qty", "type": "number", - "description": "该箱已分配的数量(由后端分配)" + "description": "该箱已分配的数量(由后端分配)", + "required": false } - ] + ], + "required": false } - ] + ], + "required": false + } + ], + "required": false + } + ], + "errors": [ + { + "code": 400, + "message": "业务校验失败:包含 task_id 参数不合法、未分配快递号(data.action=assign_express, data.order_ids)或未分配储位(data.action=assign_storage, data.order_ids)等场景。" + }, + { + "code": 401, + "message": "未获取到操作人上下文。" + }, + { + "code": 403, + "message": "当前操作人与任务创建人不一致,无权查看。" + }, + { + "code": 404, + "message": "拣货任务不存在。" + }, + { + "code": 500, + "message": "查询失败。" + } + ] + }, + { + "method": "pick.wavePickTaskSubmit", + "description": "提交拣货任务中间态。用于保存阶段性数据到任务 ext_json.pick_intermediate,并在任务初始状态时自动推进到进行中。", + "isNeedAuth": false, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "task_id", + "type": "number", + "required": true, + "source": "body", + "description": "拣货任务ID" + }, + { + "name": "payload", + "type": "object", + "required": false, + "source": "body", + "description": "中间态业务数据对象,将原样保存到 ext_json.pick_intermediate.payload" + } + ], + "response": [ + { + "name": "task_id", + "type": "number", + "required": true, + "description": "拣货任务ID" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "提交结果状态,固定为 submitted" + }, + { + "name": "is_completed", + "type": "boolean", + "required": true, + "description": "当前任务是否已完成" + }, + { + "name": "progress", + "type": "object", + "required": true, + "description": "任务订单拣货进度统计", + "children": [ + { + "name": "total_orders", + "type": "number", + "required": true, + "description": "任务订单总数" + }, + { + "name": "picked_orders", + "type": "number", + "required": true, + "description": "已确认拣货订单数" + }, + { + "name": "pending_orders", + "type": "number", + "required": true, + "description": "待确认拣货订单数" } ] } ], "errors": [ { - "code": "400", - "description": "task_id 缺失或不合法" + "code": 400, + "message": "参数或业务状态不满足提交条件(如 task_id 不合法、缺少仓库上下文、任务已完成/已取消)。" }, { - "code": "403", - "description": "当前操作人与任务创建人不一致,无权查看" + "code": 401, + "message": "未获取到操作人上下文。" }, { - "code": "404", - "description": "拣货任务不存在" + "code": 403, + "message": "当前操作人与任务创建人不一致,无权操作。" + }, + { + "code": 404, + "message": "拣货任务不存在。" + }, + { + "code": 500, + "message": "提交失败。" + } + ] + }, + { + "method": "pick.wavePickTaskComplete", + "description": "完全提交拣货任务。支持 mode=1 全部确认,mode=2 部分确认(需传 order_ids)。提交后根据是否全部完成自动推进任务状态。", + "isNeedAuth": false, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "task_id", + "type": "number", + "required": true, + "source": "body", + "description": "拣货任务ID" + }, + { + "name": "mode", + "type": "number", + "required": false, + "source": "body", + "description": "提交模式:1=全部确认(默认),2=部分确认" + }, + { + "name": "order_ids", + "type": "array", + "required": false, + "source": "body", + "description": "部分确认模式(mode=2)时必填;仅会确认命中当前任务的订单ID" + } + ], + "response": [ + { + "name": "task_id", + "type": "number", + "required": true, + "description": "拣货任务ID" + }, + { + "name": "mode", + "type": "number", + "required": true, + "description": "实际生效的提交模式(1=全部确认,2=部分确认)" + }, + { + "name": "confirmed_order_ids", + "type": "array", + "required": true, + "description": "本次成功确认的订单ID列表" + }, + { + "name": "is_completed", + "type": "boolean", + "required": true, + "description": "提交后任务是否已完成" + }, + { + "name": "progress", + "type": "object", + "required": true, + "description": "任务订单拣货进度统计", + "children": [ + { + "name": "total_orders", + "type": "number", + "required": true, + "description": "任务订单总数" + }, + { + "name": "picked_orders", + "type": "number", + "required": true, + "description": "已确认拣货订单数" + }, + { + "name": "pending_orders", + "type": "number", + "required": true, + "description": "待确认拣货订单数" + } + ] + } + ], + "errors": [ + { + "code": 400, + "message": "参数或业务状态不满足提交条件(如 task_id 不合法、mode 非 1/2、部分确认未传 order_ids、任务下无可确认订单等)。" + }, + { + "code": 401, + "message": "未获取到操作人上下文。" + }, + { + "code": 403, + "message": "当前操作人与任务创建人不一致,无权操作。" + }, + { + "code": 404, + "message": "拣货任务不存在。" + }, + { + "code": 500, + "message": "提交失败。" + } + ] + } + ] + }, + { + "groupName": "拣货车模块", + "module": "pickCart", + "list": [ + { + "method": "pickCart.scan", + "description": "按拣货车条码/编码查询拣货车信息,供 PDA 扫码后用于拣货任务绑定。", + "isNeedAuth": false, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "cart_code", + "type": "string", + "required": true, + "source": "body", + "description": "拣货车条码/编码" + } + ], + "response": [ + { + "name": "cart_id", + "type": "number", + "required": true, + "description": "拣货车ID" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "仓库ID" + }, + { + "name": "cart_code", + "type": "string", + "required": true, + "description": "拣货车编码" + }, + { + "name": "cart_name", + "type": "string", + "required": false, + "description": "拣货车名称" + }, + { + "name": "status", + "type": "number", + "required": true, + "description": "拣货车状态:0-停用 1-启用" + }, + { + "name": "current_task_id", + "type": "number", + "required": false, + "description": "当前绑定任务ID,无绑定时为 null" + }, + { + "name": "current_task_no", + "type": "string", + "required": false, + "description": "当前绑定任务编号,无绑定时为 null" + } + ], + "errors": [ + { + "code": 400, + "message": "cart_code 未传或缺少仓库上下文。" + }, + { + "code": 404, + "message": "拣货车不存在。" + }, + { + "code": 500, + "message": "查询失败。" + } + ] + }, + { + "method": "pickCart.bindTaskCart", + "description": "绑定拣货任务与拣货车。支持传 cart_id 或 cart_code;若任务已绑定其他拣货车则自动改绑,若目标拣货车已绑定其他活动任务则返回冲突。", + "isNeedAuth": false, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "task_id", + "type": "number", + "required": true, + "source": "body", + "description": "拣货任务ID" + }, + { + "name": "cart_id", + "type": "number", + "required": false, + "source": "body", + "description": "拣货车ID,和 cart_code 二选一即可" + }, + { + "name": "cart_code", + "type": "string", + "required": false, + "source": "body", + "description": "拣货车编码,和 cart_id 二选一即可" + } + ], + "response": [ + { + "name": "task_id", + "type": "number", + "required": true, + "description": "拣货任务ID" + }, + { + "name": "task_no", + "type": "string", + "required": true, + "description": "拣货任务编号" + }, + { + "name": "cart", + "type": "object", + "required": true, + "description": "绑定后的拣货车信息", + "children": [ + { + "name": "cart_id", + "type": "number", + "description": "拣货车ID" + }, + { + "name": "cart_code", + "type": "string", + "description": "拣货车编码" + }, + { + "name": "cart_name", + "type": "string", + "description": "拣货车名称" + }, + { + "name": "current_task_id", + "type": "number", + "description": "当前绑定任务ID" + }, + { + "name": "current_task_no", + "type": "string", + "description": "当前绑定任务编号" + } + ] + } + ], + "errors": [ + { + "code": 400, + "message": "参数不合法、任务已完成/已取消、拣货车已停用等业务校验失败。" + }, + { + "code": 401, + "message": "未获取到操作人上下文。" + }, + { + "code": 403, + "message": "当前操作人与任务创建人不一致,或任务不属于当前仓库。" + }, + { + "code": 404, + "message": "拣货任务或拣货车不存在。" + }, + { + "code": 409, + "message": "目标拣货车已绑定其他活动任务。" + }, + { + "code": 500, + "message": "绑定失败。" + } + ] + }, + { + "method": "pickCart.create", + "description": "创建拣货车。拣货车编码在当前仓库内不可重复。", + "isNeedAuth": false, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "cart_code", + "type": "string", + "required": true, + "source": "body", + "description": "拣货车编码,当前仓库内唯一" + }, + { + "name": "cart_name", + "type": "string", + "required": false, + "source": "body", + "description": "拣货车名称" + }, + { + "name": "status", + "type": "number", + "required": false, + "source": "body", + "description": "状态:0-停用 1-启用,默认 1" + } + ], + "response": [ + { + "name": "cart_id", + "type": "number", + "required": true, + "description": "拣货车ID" + }, + { + "name": "cart_code", + "type": "string", + "required": true, + "description": "拣货车编码" + }, + { + "name": "cart_name", + "type": "string", + "required": false, + "description": "拣货车名称" + }, + { + "name": "status", + "type": "number", + "required": true, + "description": "状态:0-停用 1-启用" + } + ], + "errors": [ + { + "code": 400, + "message": "cart_code 未传或缺少仓库上下文。" + }, + { + "code": 409, + "message": "拣货车编码已存在,请勿重复。" + }, + { + "code": 500, + "message": "创建失败。" + } + ] + }, + { + "method": "pickCart.update", + "description": "更新拣货车。支持修改编码、名称、状态;若修改后的编码与当前仓库内其他拣货车重复则拦截。", + "isNeedAuth": false, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "cart_id", + "type": "number", + "required": true, + "source": "body", + "description": "拣货车ID" + }, + { + "name": "cart_code", + "type": "string", + "required": false, + "source": "body", + "description": "新的拣货车编码" + }, + { + "name": "cart_name", + "type": "string", + "required": false, + "source": "body", + "description": "新的拣货车名称" + }, + { + "name": "status", + "type": "number", + "required": false, + "source": "body", + "description": "新的状态:0-停用 1-启用" + } + ], + "response": [ + { + "name": "cart_id", + "type": "number", + "required": true, + "description": "拣货车ID" + }, + { + "name": "cart_code", + "type": "string", + "required": true, + "description": "拣货车编码" + }, + { + "name": "cart_name", + "type": "string", + "required": false, + "description": "拣货车名称" + }, + { + "name": "status", + "type": "number", + "required": true, + "description": "状态:0-停用 1-启用" + } + ], + "errors": [ + { + "code": 400, + "message": "参数不合法,或拣货车已绑定任务不能停用。" + }, + { + "code": 404, + "message": "拣货车不存在。" + }, + { + "code": 409, + "message": "拣货车编码已存在,请勿重复。" + }, + { + "code": 500, + "message": "更新失败。" + } + ] + }, + { + "method": "pickCart.delete", + "description": "删除拣货车。若拣货车当前已绑定任务或存在有效绑定记录,则不允许删除。", + "isNeedAuth": false, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "cart_id", + "type": "number", + "required": true, + "source": "body", + "description": "拣货车ID" + } + ], + "response": [ + { + "name": "cart_id", + "type": "number", + "required": true, + "description": "被删除的拣货车ID" + }, + { + "name": "deleted", + "type": "boolean", + "required": true, + "description": "是否删除成功,固定为 true" + } + ], + "errors": [ + { + "code": 400, + "message": "cart_id 不合法,或拣货车当前已绑定任务/存在有效绑定记录。" + }, + { + "code": 404, + "message": "拣货车不存在。" + }, + { + "code": 500, + "message": "删除失败。" + } + ] + }, + { + "method": "pickCart.detail", + "description": "查询拣货车详情。", + "isNeedAuth": false, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "cart_id", + "type": "number", + "required": true, + "source": "body", + "description": "拣货车ID" + } + ], + "response": [ + { + "name": "cart_id", + "type": "number", + "required": true, + "description": "拣货车ID" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "仓库ID" + }, + { + "name": "cart_code", + "type": "string", + "required": true, + "description": "拣货车编码" + }, + { + "name": "cart_name", + "type": "string", + "required": false, + "description": "拣货车名称" + }, + { + "name": "status", + "type": "number", + "required": true, + "description": "状态:0-停用 1-启用" + }, + { + "name": "current_task_id", + "type": "number", + "required": false, + "description": "当前绑定任务ID,无绑定时为 null" + }, + { + "name": "current_task_no", + "type": "string", + "required": false, + "description": "当前绑定任务编号,无绑定时为 null" + } + ], + "errors": [ + { + "code": 400, + "message": "cart_id 不合法或缺少仓库上下文。" + }, + { + "code": 404, + "message": "拣货车不存在。" + }, + { + "code": 500, + "message": "查询失败。" + } + ] + }, + { + "method": "pickCart.list", + "description": "分页查询拣货车列表。支持按关键字、状态、当前绑定任务筛选。", + "isNeedAuth": false, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数,支持 page/pageSize,默认 1/20" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "筛选条件,支持 keyword、status、current_task_id" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "拣货车列表,元素结构同 pickCart.detail 返回" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息,包含 page、pageSize、total、totalPages" + } + ], + "errors": [ + { + "code": 400, + "message": "缺少仓库上下文。" + }, + { + "code": 500, + "message": "查询失败。" + } + ] + }, + { + "method": "pickCart.codeDuplicateCheck", + "description": "拣货车编码查重。支持传 exclude_cart_id 排除自身,用于编辑场景判断是否与其他车重复。", + "isNeedAuth": false, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "cart_code", + "type": "string", + "required": true, + "source": "body", + "description": "待校验的拣货车编码" + }, + { + "name": "exclude_cart_id", + "type": "number", + "required": false, + "source": "body", + "description": "需排除的拣货车ID,通常为当前编辑记录自身ID" + } + ], + "response": [ + { + "name": "duplicated", + "type": "boolean", + "required": true, + "description": "是否存在重复编码" + }, + { + "name": "cart_id", + "type": "number", + "required": false, + "description": "命中的重复拣货车ID,无重复时为 null" + }, + { + "name": "cart_code", + "type": "string", + "required": false, + "description": "命中的重复编码,无重复时为 null" + }, + { + "name": "cart_name", + "type": "string", + "required": false, + "description": "命中的重复拣货车名称,无重复时为 null" + }, + { + "name": "status", + "type": "number", + "required": false, + "description": "命中的重复拣货车状态,无重复时为 null" + } + ], + "errors": [ + { + "code": 400, + "message": "cart_code 未传或缺少仓库上下文。" + }, + { + "code": 500, + "message": "校验失败。" } ] } @@ -17465,11 +18744,14 @@ "type": "string", "required": false, "source": "body", - "description": "API 类型入库单回调地址(VARCHAR(500),仅 OPEN_API 类型使用)" + "description": "API 回调通知 URL(可选),最大 500 字符;配置后订单状态变更时将回调通知推送到此地址;兼容别名 callbackUrl" } ], "response": [], - "errors": [] + "errors": [], + "notes": [ + "callback_url:OpenAPI 类型的接口可配置回调地址,订单同步完成/取消等事件将推送到此 URL" + ] }, { "method": "storeWarehouse.store.deleteQimenConfig", @@ -17502,6 +18784,194 @@ ], "response": [], "errors": [] + }, + { + "method": "storeWarehouse.store.openAccount", + "description": "仓库代货主一键开户:同时完成账号注册、货主创建和仓库-货主签约", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(当前主体必须为仓库角色)" + } + ], + "params": [ + { + "name": "username", + "type": "string", + "required": true, + "source": "body", + "description": "登录账号(用户名),全局唯一" + }, + { + "name": "password", + "type": "string", + "required": false, + "source": "body", + "description": "初始密码,不传则自动随机生成 12 位密码" + }, + { + "name": "real_name", + "type": "string", + "required": false, + "source": "body", + "description": "真实姓名" + }, + { + "name": "company_name", + "type": "string", + "required": true, + "source": "body", + "description": "公司全称,全局唯一,1-200 字符" + }, + { + "name": "business_license", + "type": "string", + "required": false, + "source": "body", + "description": "营业执照号" + }, + { + "name": "contact_person", + "type": "string", + "required": true, + "source": "body", + "description": "联系人姓名,1-50 字符" + }, + { + "name": "contact_phone", + "type": "string", + "required": false, + "source": "body", + "description": "联系电话" + }, + { + "name": "legal_person", + "type": "string", + "required": false, + "source": "body", + "description": "法人代表" + }, + { + "name": "contact_email", + "type": "string", + "required": false, + "source": "body", + "description": "联系邮箱" + }, + { + "name": "address", + "type": "string", + "required": false, + "source": "body", + "description": "公司地址" + }, + { + "name": "industry", + "type": "string", + "required": false, + "source": "body", + "description": "所属行业" + }, + { + "name": "logo_url", + "type": "string", + "required": false, + "source": "body", + "description": "Logo 链接" + }, + { + "name": "domain", + "type": "string", + "required": false, + "source": "body", + "description": "绑定域名" + }, + { + "name": "auth_start", + "type": "string", + "required": false, + "source": "body", + "description": "授权开始日期,默认当天(ISO 8601 格式)" + }, + { + "name": "auth_end", + "type": "string", + "required": false, + "source": "body", + "description": "授权结束日期(ISO 8601 格式)" + }, + { + "name": "print_quantity", + "type": "number", + "required": false, + "source": "body", + "description": "初始面单余额,默认 0" + }, + { + "name": "apply_reason", + "type": "string", + "required": false, + "source": "body", + "description": "申请原因,默认\"仓库代开户\",最长 2000 字符" + }, + { + "name": "store_remask", + "type": "string", + "required": false, + "source": "body", + "description": "货主备注名,最长 50 字符" + }, + { + "name": "warehouse_remask", + "type": "string", + "required": false, + "source": "body", + "description": "仓库备注名,最长 50 字符" + } + ], + "response": [ + { + "name": "store_id", + "type": "number", + "required": true, + "description": "新建的货主 ID" + }, + { + "name": "account_id", + "type": "number", + "required": true, + "description": "新建的账号 ID" + }, + { + "name": "contract_id", + "type": "number", + "required": true, + "description": "新建的签约关系 ID" + }, + { + "name": "company_name", + "type": "string", + "required": true, + "description": "货主公司名称" + }, + { + "name": "username", + "type": "string", + "required": true, + "description": "新建的登录账号名" + }, + { + "name": "role_id", + "type": "number", + "required": true, + "description": "分配的货主管理员角色 ID" + } + ], + "errors": [] } ] }, @@ -18507,7 +19977,7 @@ "list": [ { "method": "order.wave.batchList", - "description": "波次列表查询。仅使用当前登录操作者的仓库ID作为查询约束(禁止传入 warehouse_id / warehouseId)。支持通过白名单字段进行过滤(通过 where 对象传入),接口对 wave_status 固定叠加查询状态 0/1,无需客户端传入。列表按订单数量从大到小排序,并附带波次基础信息与分配状态汇总。", + "description": "波次列表查询。仅使用当前登录操作者仓库上下文(禁止传入 warehouse_id/warehouseId)。支持 where 白名单过滤,固定查询 wave_status=0/1;返回波次基础信息及分配状态汇总。支持 only_todo=1 仅返回仍有未复核订单的波次,并返回复核状态汇总(review_assignment_status)与未复核数量(unreviewed_order_count)。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -18526,12 +19996,19 @@ "source": "body", "description": "分页参数,支持 page / pageSize" }, + { + "name": "only_todo", + "type": "number|boolean|string", + "required": false, + "source": "body", + "description": "是否仅返回待处理(仍有未复核订单)的波次,默认 0;传 1/true 时仅返回 unreviewed_order_count > 0 的波次。" + }, { "name": "where", "type": "object", "required": false, "source": "body", - "description": "筛选白名单字段(object,可选)。仅支持下列字段过滤,且禁止传入 warehouse_id / warehouseId:\n- wave_id(等值)\n- wave_no(模糊)\n- wave_type(等值)\n- wave_status(等值,接口固定叠加状态 0/1)\n- creator(模糊)\n- logistics_name(模糊)\n- item_part_type(等值)\n- item_part(模糊)\n- item_snapshot_key(模糊)\n- item_detail_machine(模糊)\n- distinguish_express(等值)\n- total_orders_min / total_orders_max(范围)\n- processed_orders_min / processed_orders_max(范围)\n- express_assignment_status(等值,string,可选,英文枚举,取值:unassigned、partially_assigned、assigned;语义:按快递分配聚合判断,assigned 表示聚合后全部 fin,partially_assigned 表示部分已分配且不含 error,unassigned 表示全 none 或包含 error(异常并入未分配集合))。\n- print_assignment_status(等值,string,可选,英文枚举,取值:unprinted、partially_printed、printed;语义:按打印分配聚合判断,printed 表示聚合后全部已打印)。\n- storage_assignment_status(等值,string,可选,取值:未分配、部分分配、已分配;默认不传不做限制)。过滤语义:已分配=聚合后全部 fin;部分分配=不含 error,且既不是全 none,也不是全 fin;未分配=全 none 或包含 error(异常并入未分配筛选集合)。说明:返回字段 storage_assignment_status 的展示值保持不变,包含 error 时仍可显示“分配异常”;此处 where 的过滤语义会把异常计入“未分配”,以避免把过滤语义与展示值混淆。\n- source(可选,number)来源过滤:0=普通波次(正常后台操作),1=管理后台策略任务,2=PDA策略任务;不传则不过滤。\n说明:express_assignment_status 与 print_assignment_status 要求使用英文枚举值;storage_assignment_status 仍向后兼容中文展示值。若传入的枚举值不在允许集合内,接口会返回 400(参数校验失败),并在 message 中说明错误字段与允许取值。" + "description": "筛选白名单字段(object,可选)。仅支持下列字段过滤,且禁止传入 warehouse_id / warehouseId:\n- wave_id(等值)\n- wave_no(模糊)\n- wave_type(等值)\n- wave_status(等值,接口固定叠加状态 0/1)\n- creator(模糊)\n- logistics_name(模糊)\n- item_part_type(等值)\n- item_part(模糊)\n- item_snapshot_key(模糊)\n- item_detail_machine(模糊)\n- distinguish_express(等值)\n- total_orders_min / total_orders_max(范围)\n- processed_orders_min / processed_orders_max(范围)\n- express_assignment_status(等值,string,可选,英文枚举,取值:unassigned、partially_assigned、assigned;语义:按快递分配聚合判断,assigned 表示聚合后全部 fin,partially_assigned 表示部分已分配且不含 error,unassigned 表示全 none 或包含 error(异常并入未分配集合))。\n- print_assignment_status(等值,string,可选,英文枚举,取值:unprinted、partially_printed、printed;语义:按打印分配聚合判断,printed 表示聚合后全部已打印)。\n- storage_assignment_status(等值,string,可选,取值:未分配、部分分配、已分配;默认不传不做限制)。过滤语义:已分配=聚合后全部 fin;部分分配=不含 error,且既不是全 none,也不是全 fin;未分配=全 none 或包含 error(异常并入未分配筛选集合)。说明:返回字段 storage_assignment_status 的展示值保持不变,包含 error 时仍可显示“分配异常”;此处 where 的过滤语义会把异常计入“未分配”,以避免把过滤语义与展示值混淆。\n- source(可选,number)来源过滤:0=普通波次(正常后台操作),1=管理后台策略任务,2=PDA策略任务;不传则不过滤。\n说明:express_assignment_status 与 print_assignment_status 要求使用英文枚举值;storage_assignment_status 仍向后兼容中文展示值。若传入的枚举值不在允许集合内,接口会返回 400(参数校验失败),并在 message 中说明错误字段与允许取值。\n- sync_assignment_status(等值,string,可选,英文枚举,取值:unsynced、partially_synced、synced;语义:按同步状态聚合判断,synced 表示全部 fin,partially_synced 表示部分已同步且不含 error,unsynced 表示全 padding 或包含 error(异常并入未同步集合))。\n- review_assignment_status(等值,string,可选,英文枚举:unreviewed、partially_reviewed、reviewed;分别表示未复核、部分复核、已复核)。" } ], "response": [ @@ -18539,7 +20016,7 @@ "name": "list", "type": "array", "required": true, - "description": "波次列表,包含波次基础信息与状态汇总(order_count / storage_assignment_status / express_assignment_status / print_assignment_status)。每条记录新增字段 source(number):来源标识,0=普通波次(正常后台操作),1=管理后台策略任务,2=PDA策略任务。" + "description": "波次列表,包含波次基础信息与状态汇总(order_count / storage_assignment_status / express_assignment_status / print_assignment_status / sync_assignment_status / review_assignment_status / unreviewed_order_count)。每条记录新增字段 source(number):来源标识,0=普通波次(正常后台操作),1=管理后台策略任务,2=PDA策略任务。" }, { "name": "pagination", diff --git a/scripts/db-query-runner.js b/scripts/db-query-runner.js index 9e43b1d..f69c37b 100644 --- a/scripts/db-query-runner.js +++ b/scripts/db-query-runner.js @@ -5,7 +5,7 @@ const mysql = require('mysql2/promise'); async function main() { const arg = process.argv[2]; if (!arg) { - console.error(JSON.stringify({success:false, error: 'No queries provided as @file or JSON string'})); + console.error(JSON.stringify({ success: false, error: 'No queries provided as @file or JSON string' })); process.exit(2); } let queries; @@ -15,19 +15,19 @@ async function main() { const raw = fs.readFileSync(fp, 'utf8'); queries = JSON.parse(raw); } catch (err) { - console.error(JSON.stringify({success:false, error: 'Failed to read/parse queries file: ' + err.message})); + console.error(JSON.stringify({ success: false, error: 'Failed to read/parse queries file: ' + err.message })); process.exit(2); } } else { try { queries = JSON.parse(arg); } catch (err) { - console.error(JSON.stringify({success:false, error: 'Failed to parse queries JSON: ' + err.message})); + console.error(JSON.stringify({ success: false, error: 'Failed to parse queries JSON: ' + err.message })); process.exit(2); } } if (!Array.isArray(queries)) { - console.error(JSON.stringify({success:false, error: 'Queries must be an array of SQL strings'})); + console.error(JSON.stringify({ success: false, error: 'Queries must be an array of SQL strings' })); process.exit(2); } @@ -35,7 +35,7 @@ async function main() { try { cfgModule = require(path.join(__dirname, '..', 'database', 'config.js')); } catch (err) { - console.error(JSON.stringify({success:false, error: 'Failed to load database/config.js: ' + err.message})); + console.error(JSON.stringify({ success: false, error: 'Failed to load database/config.js: ' + err.message })); process.exit(1); } const cfg = cfgModule && cfgModule.production ? cfgModule.production : cfgModule; @@ -50,14 +50,14 @@ async function main() { try { conn = await mysql.createConnection({ host, port, user, password, database, multipleStatements: true }); } catch (err) { - console.error(JSON.stringify({success:false, error: 'DB connection failed: ' + err.message})); + console.error(JSON.stringify({ success: false, error: 'DB connection failed: ' + err.message })); process.exit(1); } const results = []; for (const q of queries) { try { - const [rows] = await conn.query(q); + const [ rows ] = await conn.query(q); results.push({ query: q, rows }); } catch (err) { results.push({ query: q, error: err && err.message }); @@ -68,6 +68,6 @@ async function main() { } main().catch(err => { - console.error(JSON.stringify({success:false, error: err.message})); + console.error(JSON.stringify({ success: false, error: err.message })); process.exit(1); }); diff --git a/test/app/service/systemMethods/setting/expressInterface.test.js b/test/app/service/systemMethods/setting/expressInterface.test.js index 4710438..5e7ba13 100644 --- a/test/app/service/systemMethods/setting/expressInterface.test.js +++ b/test/app/service/systemMethods/setting/expressInterface.test.js @@ -174,6 +174,9 @@ describe('test/app/service/systemMethods/setting/expressInterface.test.js', () = name: '顺丰接口', express_code: 'SF', platform_code: 'TB', + templateId: 5566, + brandNo: 'BRAND-CREATE', + providerType: 'KDNIAO', sysExpressCode: 'SF', weightType: 2, address: '上海市浦东新区', @@ -192,7 +195,10 @@ describe('test/app/service/systemMethods/setting/expressInterface.test.js', () = id: 11, name: '顺丰接口-更新', token: 'token-2', + templateId: '7788', platformShopId: '8899', + brandno: 'BRAND-UPDATE', + providerType: 'CAINIAO', sys_express_code: 'SF', weight_type: 3, address: '深圳市南山区', @@ -218,6 +224,9 @@ describe('test/app/service/systemMethods/setting/expressInterface.test.js', () = name: '顺丰接口', express_code: 'SF', platform_code: 'TB', + template_id: 5566, + brandno: 'BRAND-CREATE', + providertype: 'KDNIAO', sys_express_code: 'SF', weight_type: 2, address: '上海市浦东新区', @@ -237,7 +246,10 @@ describe('test/app/service/systemMethods/setting/expressInterface.test.js', () = id: 11, name: '顺丰接口-更新', token: 'token-2', + template_id: '7788', platform_shop_id: '8899', + brandno: 'BRAND-UPDATE', + providertype: 'CAINIAO', sys_express_code: 'SF', weight_type: 3, address: '深圳市南山区', diff --git a/test/app/service/systems/setting/expressInterface.test.js b/test/app/service/systems/setting/expressInterface.test.js index f80ccf7..5799133 100644 --- a/test/app/service/systems/setting/expressInterface.test.js +++ b/test/app/service/systems/setting/expressInterface.test.js @@ -56,6 +56,8 @@ function createHarness(options = {}) { express_code: 'SF', platform_code: 'TB', platform_shop_id: 20001, + template_id: 50001, + brandno: 'BRAND-DEFAULT', express_platform_id: 1, weight_type: 2, express: { @@ -148,6 +150,9 @@ function createHarness(options = {}) { warehouse_id: {}, shop_id: {}, platform_shop_id: {}, + template_id: {}, + brandno: {}, + providertype: {}, sender_name: {}, sender_tel: {}, weight: {}, @@ -436,6 +441,9 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => { sys_express_code: 'SF', platform_code: 'TB', platform_shop_id: 30001, + template_id: 88001, + brandno: 'BRAND-LIST', + providertype: 'KDNIAO', express_platform_id: 1, express: { code: 'SF', @@ -500,6 +508,9 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => { assert.equal(result.data.list[0].name, '顺丰接口'); assert.equal(result.data.list[0].platform_code, 'TB'); assert.equal(result.data.list[0].platform_shop_id, 30001); + assert.equal(result.data.list[0].template_id, 88001); + assert.equal(result.data.list[0].brandno, 'BRAND-LIST'); + assert.equal(result.data.list[0].providertype, 'KDNIAO'); assert.equal(result.data.list[0].sys_express_code, 'SF'); assert.equal(result.data.list[0].template_url, 'https://example.com/template/list'); assert.equal(result.data.list[0].is_system_express_code, 1); @@ -555,6 +566,9 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => { id: 20, warehouse_id: 100000, shop_id: 301, + template_id: 1201, + brandno: 'BRAND-YTO', + providertype: 'KDNIAO', sys_express_code: 'SYS-YTO', name: '圆通接口', express_code: 'YTO', @@ -591,6 +605,9 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => { id: 11, warehouse_id: 100000, sys_express_code: 'SYS-SF', + template_id: 1202, + brandno: 'BRAND-SF', + providertype: 'CAINIAO', name: '顺丰接口', express_code: 'SF', platform_code: 'TB', @@ -608,6 +625,9 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => { id: 15, warehouse_id: 100000, sys_express_code: 'SYS-ZTO', + template_id: 1203, + brandno: 'BRAND-ZTO', + providertype: 'KDNIAO', name: '中通接口', express_code: 'ZTO', platform_code: 'TB', @@ -641,8 +661,13 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => { assert.equal(Array.isArray(result.data), true); assert.equal(result.data.length, 3); assert.equal(result.data[0].express_code, 'SF'); + assert.equal(result.data[0].template_id, 1202); + assert.equal(result.data[0].brandno, 'BRAND-SF'); + assert.equal(result.data[0].providertype, 'CAINIAO'); assert.equal(result.data[1].express_code, 'ZTO'); + assert.equal(result.data[1].brandno, 'BRAND-ZTO'); assert.equal(result.data[2].express_code, 'YTO'); + assert.equal(result.data[2].brandno, 'BRAND-YTO'); assert.equal(result.data[2].shop.id, 301); assert.equal(result.data[2].shop.shop_name, '圆通店铺'); assert.equal(result.data[0].weight, 10); @@ -663,6 +688,8 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => { id: 12, warehouse_id: 100000, shop_id: 302, + template_id: 33002, + brandno: 'BRAND-CACHE-YTO', sys_express_code: 'SYS-YTO', name: '圆通接口', express_code: 'YTO', @@ -699,6 +726,8 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => { id: 11, warehouse_id: 100000, sys_express_code: 'SYS-SF', + template_id: 33001, + brandno: 'BRAND-CACHE-SF', name: '顺丰接口', express_code: 'SF', platform_code: 'TB', @@ -726,7 +755,10 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => { assert.equal(Array.isArray(result.data), true); assert.equal(result.data.length, 2); assert.equal(result.data[0].express_code, 'SF'); + assert.equal(result.data[0].template_id, 33001); + assert.equal(result.data[0].brandno, 'BRAND-CACHE-SF'); assert.equal(result.data[1].express_code, 'YTO'); + assert.equal(result.data[1].brandno, 'BRAND-CACHE-YTO'); assert.equal(result.data[1].shop.id, 302); assert.equal(result.data[1].shop.shop_name, '圆通店铺缓存'); assert.equal(result.data[0].express.polyapi_code, 'SF_API'); @@ -781,6 +813,7 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => { id: 12, warehouse_id: 100000, shop_id: 302, + template_id: 44002, sys_express_code: 'SYS-YTO', name: '圆通接口', express_code: 'YTO', @@ -837,11 +870,14 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => { is_share: 1, can_use_count: 5, weight_type: 2, + providerType: 'KDNIAO', + brandNo: 'BRAND-CREATE', address: '朝阳区望京', town_name: '望京街道', ispickup: 1, shipperno: 'SNO-001', template_url: 'https://example.com/template/create', + template_id: 889900, extData: { retry: 2, channel: 'polyapi', @@ -852,6 +888,8 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => { assert.equal(calls.createPayload.express_code, 'JD'); assert.equal(calls.createPayload.sys_express_code, 'JD'); assert.equal(calls.createPayload.platform_code, 'TB'); + assert.equal(calls.createPayload.brandno, 'BRAND-CREATE'); + assert.equal(calls.createPayload.providertype, 'KDNIAO'); assert.equal(calls.printPlatformFindOneCalls.length, 1); assert.deepEqual(calls.printPlatformFindOneCalls[0].where, { platform_code: 'TB', @@ -859,6 +897,8 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => { assert.equal(result.data.express_code, 'JD'); assert.equal(result.data.sys_express_code, 'JD'); assert.equal(result.data.platform_code, 'TB'); + assert.equal(result.data.brandno, 'BRAND-CREATE'); + assert.equal(result.data.providertype, 'KDNIAO'); assert.equal(result.data.sender_name, '李四'); assert.equal(result.data.weight_type, 2); assert.equal(result.data.address, '朝阳区望京'); @@ -867,6 +907,8 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => { assert.equal(result.data.shipperno, 'SNO-001'); assert.equal(calls.createPayload.template_url, 'https://example.com/template/create'); assert.equal(result.data.template_url, 'https://example.com/template/create'); + assert.equal(calls.createPayload.template_id, 889900); + assert.equal(result.data.template_id, 889900); assert.deepEqual(calls.createPayload.ext_data, { retry: 2, channel: 'polyapi', @@ -895,6 +937,7 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => { assert.equal(result.code, 200); assert.equal(calls.createPayload.express_code, 'SF'); assert.equal(calls.createPayload.platform_code, 'TB'); + assert.equal(calls.createPayload.template_id, null); assert.equal(calls.createPayload.weight_type, 1); assert.equal(calls.findOneCalls.some(item => item.where && item.where.express_code === 'SF' && item.where.warehouse_id === 100000), false); }); @@ -928,6 +971,9 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => { name: '顺丰接口-更新', express_code: 'sf-pdd', platform_code: 'pdd', + templateId: '998877', + brandNo: 'BRAND-UPDATE', + providerType: 'CAINIAO', weight_type: 3, address: '上海市浦东新区', town_name: '张江镇', @@ -944,6 +990,9 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => { assert.equal(calls.updatePayload.updates.name, '顺丰接口-更新'); assert.equal(calls.updatePayload.updates.express_code, 'SF-PDD'); assert.equal(calls.updatePayload.updates.platform_code, 'PDD'); + assert.equal(calls.updatePayload.updates.template_id, 998877); + assert.equal(calls.updatePayload.updates.brandno, 'BRAND-UPDATE'); + assert.equal(calls.updatePayload.updates.providertype, 'CAINIAO'); assert.equal(calls.printPlatformFindOneCalls.length, 1); assert.deepEqual(calls.printPlatformFindOneCalls[0].where, { platform_code: 'PDD', @@ -959,6 +1008,9 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => { print_mode: 'thermal', }); assert.equal(result.data.name, '顺丰接口-更新'); + assert.equal(result.data.template_id, 998877); + assert.equal(result.data.brandno, 'BRAND-UPDATE'); + assert.equal(result.data.providertype, 'CAINIAO'); assert.equal(result.data.template_url, 'https://example.com/template/update'); assert.deepEqual(result.data.ext_data, { print_mode: 'thermal', @@ -1012,6 +1064,32 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => { assert.equal(result.data.platform_shop_id, 20088); }); + it('should normalize empty template_id to null when updating', async () => { + const { ctx, calls } = createHarness(); + const service = new SettingExpressInterfaceService(ctx); + + const result = await service.update({ + id: 11, + templateId: '', + }); + + assert.equal(calls.updatePayload.updates.template_id, null); + assert.equal(result.data.template_id, null); + }); + + it('should normalize empty brandno to null when updating', async () => { + const { ctx, calls } = createHarness(); + const service = new SettingExpressInterfaceService(ctx); + + const result = await service.update({ + id: 11, + brandNo: '', + }); + + assert.equal(calls.updatePayload.updates.brandno, null); + assert.equal(result.data.brandno, null); + }); + it('should clear token when shop_id is cleared', async () => { const { ctx, calls } = createHarness(); const service = new SettingExpressInterfaceService(ctx); diff --git a/test/app/service/systems/shops.test.js b/test/app/service/systems/shops.test.js index eca4388..e1e6700 100644 --- a/test/app/service/systems/shops.test.js +++ b/test/app/service/systems/shops.test.js @@ -57,6 +57,18 @@ function createHarness(options = {}) { dynamicConditions: [], rawConditionsByField: {}, }, + async curl() { + if (typeof options.curl === 'function') { + return await options.curl(...arguments); + } + + return { + data: { + code: 1, + msg: 'mock failed', + }, + }; + }, model: { Shop: { async findAndCountAll(query) { @@ -186,6 +198,51 @@ describe('test/app/service/systems/shops.test.js', () => { assert.equal(calls.shopCreatePayload.shop_name.startsWith('PENDING_'), true); }); + it('add 未传 shop_name 时,首次占位名冲突应重试并成功', async () => { + let findOneCallCount = 0; + const { service, calls } = createHarness({ + shopFindOne: async () => { + findOneCallCount += 1; + + if (findOneCallCount === 1) { + return createFindOneResult({ id: 101 }); + } + + return null; + }, + }); + const generatedCodes = [ 'RETRY1', 'RETRY2' ]; + service.generateAuthorizeRandomCode = () => generatedCodes.shift() || 'RETRY_FALLBACK'; + + const result = await service.add({ + custom_name: '重试店铺', + platform_code: 'PDD', + }); + + assert.equal(result.id, 9001); + assert.equal(calls.shopCreatePayload.shop_name, 'PENDING_RETRY2'); + }); + + it('add 连续冲突超过重试上限时应返回占位名冲突提示', async () => { + const { service } = createHarness({ + shopFindOne: async () => { + return createFindOneResult({ id: 102 }); + }, + }); + service.generateAuthorizeRandomCode = () => 'ALWAYS_CONFLICT'; + + await assert.rejects(async () => { + await service.add({ + custom_name: '冲突店铺', + platform_code: 'PDD', + }); + }, error => { + assert.equal(error && error.message, '系统生成占位名冲突,请重试'); + assert.equal(error && error.code, 409); + return true; + }); + }); + it('del 遇到快递接口引用时应拒绝删除', async () => { const { service } = createHarness({ shopRows: [ @@ -230,7 +287,7 @@ describe('test/app/service/systems/shops.test.js', () => { assert.equal(result.id, 7); }); - it('getAuthorizeSessionKey 对未实现平台应返回 501 错误', async () => { + it('getAuthorizeSessionKey 请求授权接口失败时应抛出业务错误', async () => { const { service } = createHarness({ shopRows: [ { @@ -251,6 +308,12 @@ describe('test/app/service/systems/shops.test.js', () => { status: 'ACTIVE', }, ], + curl: async () => ({ + data: { + code: 1, + msg: '接口异常', + }, + }), }); await assert.rejects(async () => { @@ -258,6 +321,6 @@ describe('test/app/service/systems/shops.test.js', () => { id: 9, callbackurl: 'https://callback.example.com', }); - }, /暂未实现授权会话换取能力/); + }, /获取授权失败:接口异常/); }); }); From e6e65d9d65b7485b176297cdc08c9a11b0605b1e Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sat, 6 Jun 2026 16:06:31 +0800 Subject: [PATCH 065/550] 1 --- SequelizeMeta.sql | 2755 ----------------------- app/service/systems/space.js | 5 + app_service_systemMethods_index_head.js | Bin 178012 -> 0 bytes check_brackets.js | 38 - check_stats.ps1 | 37 - db_query.js | 47 - dev_out.log | 654 ------ final_sf.json | Bin 112110 -> 0 bytes get_specific_logs.ps1 | 34 - lint_result.txt | Bin 24378 -> 0 bytes query_db.js | 39 - raw_redis.json | Bin 111412 -> 0 bytes redis_output.txt | Bin 111412 -> 0 bytes result_sf.json | Bin 112110 -> 0 bytes run-target-migration.js | 44 - run_task.js | 102 - search_logs.ps1 | 41 - task_script.js | 39 - temp.json | Bin 111412 -> 0 bytes temp_calculate_sign.js | 59 - temp_check_json.js | 39 - temp_count_brackets.js | 19 - temp_debug_headers.js | 5 - temp_find_headers_close.js | 15 - temp_find_missing_commas.js | 1 - temp_find_objsep.js | 1 - temp_find_trailing_commas.js | 1 - temp_parse_json.py | 13 - temp_rebuild_system_json.js | 49 - tmp_mig_conn_dev.txt | 8 - tmp_mig_migrate_output.txt | Bin 1484 -> 0 bytes tmp_mig_migrate_output_utf8.txt | 17 - tmp_mig_post_columns.txt | 14 - tmp_mig_post_meta.txt | 7 - tmp_mig_pre_columns.txt | 14 - tmp_mig_pre_meta.txt | 7 - tmp_sequelizemeta_check.json | Bin 218 -> 0 bytes tmp_sequelizemeta_check_utf8.json | 7 - tmp_show_columns_platid.json | Bin 748 -> 0 bytes tmp_show_columns_platid_utf8.json | 14 - tmp_show_create_table.json | Bin 2754 -> 0 bytes tmp_show_create_table_utf8.json | 10 - 42 files changed, 5 insertions(+), 4130 deletions(-) delete mode 100644 SequelizeMeta.sql delete mode 100644 app_service_systemMethods_index_head.js delete mode 100644 check_brackets.js delete mode 100644 check_stats.ps1 delete mode 100644 db_query.js delete mode 100644 dev_out.log delete mode 100644 final_sf.json delete mode 100644 get_specific_logs.ps1 delete mode 100644 lint_result.txt delete mode 100644 query_db.js delete mode 100644 raw_redis.json delete mode 100644 redis_output.txt delete mode 100644 result_sf.json delete mode 100644 run-target-migration.js delete mode 100644 run_task.js delete mode 100644 search_logs.ps1 delete mode 100644 task_script.js delete mode 100644 temp.json delete mode 100644 temp_calculate_sign.js delete mode 100644 temp_check_json.js delete mode 100644 temp_count_brackets.js delete mode 100644 temp_debug_headers.js delete mode 100644 temp_find_headers_close.js delete mode 100644 temp_find_missing_commas.js delete mode 100644 temp_find_objsep.js delete mode 100644 temp_find_trailing_commas.js delete mode 100644 temp_parse_json.py delete mode 100644 temp_rebuild_system_json.js delete mode 100644 tmp_mig_conn_dev.txt delete mode 100644 tmp_mig_migrate_output.txt delete mode 100644 tmp_mig_migrate_output_utf8.txt delete mode 100644 tmp_mig_post_columns.txt delete mode 100644 tmp_mig_post_meta.txt delete mode 100644 tmp_mig_pre_columns.txt delete mode 100644 tmp_mig_pre_meta.txt delete mode 100644 tmp_sequelizemeta_check.json delete mode 100644 tmp_sequelizemeta_check_utf8.json delete mode 100644 tmp_show_columns_platid.json delete mode 100644 tmp_show_columns_platid_utf8.json delete mode 100644 tmp_show_create_table.json delete mode 100644 tmp_show_create_table_utf8.json diff --git a/SequelizeMeta.sql b/SequelizeMeta.sql deleted file mode 100644 index ecc8b54..0000000 --- a/SequelizeMeta.sql +++ /dev/null @@ -1,2755 +0,0 @@ -/* - Navicat MySQL Data Transfer - - Source Server : wms - Source Server Type : MySQL - Source Server Version : 50744 - Source Host : 112.124.21.102:3306 - Source Schema : wms - - Target Server Type : MySQL - Target Server Version : 50744 - File Encoding : 65001 - - Date: 04/05/2026 22:27:02 -*/ - -SET NAMES utf8mb4; -SET FOREIGN_KEY_CHECKS = 0; - --- ---------------------------- --- Table structure for SequelizeMeta --- ---------------------------- -DROP TABLE IF EXISTS `SequelizeMeta`; -CREATE TABLE `SequelizeMeta` ( - `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`name`) USING BTREE, - UNIQUE INDEX `name`(`name`) USING BTREE -) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_unicode_ci ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_account --- ---------------------------- -DROP TABLE IF EXISTS `wms_account`; -CREATE TABLE `wms_account` ( - `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '账号ID', - `username` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '用户名', - `phone` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '手机号', - `email` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '邮箱', - `password_hash` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '密码哈希', - `real_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '真实姓名', - `status` tinyint(1) NOT NULL DEFAULT 1 COMMENT '状态:0-封号,1-启用', - `last_login_at` datetime(0) NULL DEFAULT NULL COMMENT '最后登录时间', - `created_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', - `updated_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', - `salt` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '密码盐', - `deleted_at` datetime(0) NULL DEFAULT NULL, - `last_login_ip` varchar(15) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, - PRIMARY KEY (`id`) USING BTREE, - UNIQUE INDEX `idx_username`(`username`) USING BTREE, - INDEX `idx_phone`(`phone`) USING BTREE, - INDEX `idx_email`(`email`) USING BTREE, - INDEX `idx_status`(`status`) USING BTREE -) ENGINE = InnoDB AUTO_INCREMENT = 42 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '平台账号表' ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_account_platform_active --- ---------------------------- -DROP TABLE IF EXISTS `wms_account_platform_active`; -CREATE TABLE `wms_account_platform_active` ( - `account_id` bigint(20) UNSIGNED NOT NULL COMMENT '账号ID', - `employee_id` bigint(20) UNSIGNED NOT NULL COMMENT '账号仓库角色关联ID', - `platform_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '平台编码(web、pda、mini、app等)', - `created_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', - `updated_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', - UNIQUE INDEX `uk_account_platform`(`account_id`, `platform_code`) USING BTREE, - UNIQUE INDEX `uk_account_store_role_platform`(`employee_id`, `platform_code`) USING BTREE, - INDEX `idx_account_id`(`account_id`) USING BTREE, - INDEX `idx_platform_code`(`platform_code`) USING BTREE, - INDEX `idx_account_store_role_id`(`employee_id`) USING BTREE, - CONSTRAINT `fk_apa_account` FOREIGN KEY (`account_id`) REFERENCES `wms_account` (`id`) ON DELETE CASCADE ON UPDATE RESTRICT, - CONSTRAINT `fk_apa_account_store_role` FOREIGN KEY (`employee_id`) REFERENCES `wms_account_store_employee` (`id`) ON DELETE CASCADE ON UPDATE RESTRICT -) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '账号平台激活状态表(无主键,使用组合唯一索引)' ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_account_store_employee --- ---------------------------- -DROP TABLE IF EXISTS `wms_account_store_employee`; -CREATE TABLE `wms_account_store_employee` ( - `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '关联ID', - `account_id` bigint(20) UNSIGNED NOT NULL COMMENT '账号ID', - `store_id` bigint(20) UNSIGNED NOT NULL COMMENT '仓库ID', - `status` tinyint(4) NOT NULL DEFAULT 1 COMMENT '状态:0-已解除,1-有效', - `created_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', - `updated_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', - `real_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '工号的真实姓名', - `deleted_at` datetime(0) NULL DEFAULT NULL, - PRIMARY KEY (`id`) USING BTREE, - UNIQUE INDEX `uk_account_warehouse_role`(`account_id`, `store_id`) USING BTREE, - INDEX `idx_account_id`(`account_id`) USING BTREE, - INDEX `idx_warehouse_id`(`store_id`) USING BTREE, - INDEX `idx_status`(`status`) USING BTREE, - CONSTRAINT `fk_wms_awr_account` FOREIGN KEY (`account_id`) REFERENCES `wms_account` (`id`) ON DELETE CASCADE ON UPDATE RESTRICT, - CONSTRAINT `fk_wms_awr_store` FOREIGN KEY (`store_id`) REFERENCES `wms_store` (`id`) ON DELETE CASCADE ON UPDATE RESTRICT -) ENGINE = InnoDB AUTO_INCREMENT = 76 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '账号仓库角色关联表' ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_api_app --- ---------------------------- -DROP TABLE IF EXISTS `wms_api_app`; -CREATE TABLE `wms_api_app` ( - `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '应用ID', - `app_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '应用名称', - `interface_type_id` int(10) UNSIGNED NOT NULL COMMENT '接口类型ID', - `contract_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '合约ID,关联wms_store_warehouse.id(货主接口使用)', - `warehouse_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '仓库ID(仓库接口使用)', - `self_app_key` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '自身AppKey(开放接口使用,系统生成)', - `self_app_secret` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '自身AppSecret(开放接口使用,系统生成)', - `self_ip_whitelist` json NULL COMMENT '自身IP白名单', - `callback_url` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT 'API回调通知URL', - `qimen_app_key` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '奇门对方AppKey', - `qimen_customer_id` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '奇门客户ID', - `qimen_warehouse_code` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '奇门仓库编码', - `api_version` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT '1.0' COMMENT 'API版本', - `sign_method` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT 'md5' COMMENT '签名方法', - `rate_limit` int(11) NULL DEFAULT 1000 COMMENT '速率限制(次/分钟)', - `timeout_seconds` int(11) NULL DEFAULT 30 COMMENT '超时时间(秒)', - `contact_person` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '联系人', - `contact_phone` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '联系电话', - `email` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '邮箱', - `is_enabled` tinyint(1) NOT NULL DEFAULT 1 COMMENT '是否启用', - `created_at` timestamp(0) NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', - `updated_at` timestamp(0) NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', - `deleted_at` timestamp(0) NULL DEFAULT NULL COMMENT '删除时间', - PRIMARY KEY (`id`) USING BTREE, - UNIQUE INDEX `uk_app_name_interface`(`app_name`, `interface_type_id`) USING BTREE, - UNIQUE INDEX `uk_self_app_key`(`self_app_key`) USING BTREE, - UNIQUE INDEX `uk_interface_warehouse`(`qimen_app_key`, `qimen_customer_id`) USING BTREE, - INDEX `fk_wms_api_app_contract`(`contract_id`) USING BTREE, - INDEX `uk_interface_contract`(`interface_type_id`, `contract_id`) USING BTREE, - CONSTRAINT `fk_wms_api_app_contract` FOREIGN KEY (`contract_id`) REFERENCES `wms_store_warehouse` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT, - CONSTRAINT `wms_api_app_ibfk_1` FOREIGN KEY (`interface_type_id`) REFERENCES `wms_interface_type` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT -) ENGINE = InnoDB AUTO_INCREMENT = 21 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT = 'API应用表' ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_embargo_policies --- ---------------------------- -DROP TABLE IF EXISTS `wms_embargo_policies`; -CREATE TABLE `wms_embargo_policies` ( - `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT, - `policy_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '策略名称', - `status` enum('ACTIVE','INACTIVE','PENDING','EXPIRED') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT 'PENDING' COMMENT '状态', - `embargo_scope` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL COMMENT '禁运范围(数组)', - `start_date` date NOT NULL COMMENT '生效开始日期', - `end_date` date NULL DEFAULT NULL COMMENT '结束日期', - `is_permanent` tinyint(1) NULL DEFAULT 0 COMMENT '是否永久有效', - `description` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL COMMENT '策略描述', - `created_by` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '创建人', - `updated_by` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '更新人', - `created_at` timestamp(0) NULL DEFAULT CURRENT_TIMESTAMP(0), - `updated_at` timestamp(0) NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0), - `warehouse_id` bigint(20) UNSIGNED NULL DEFAULT NULL, - PRIMARY KEY (`id`) USING BTREE, - INDEX `idx_status`(`status`) USING BTREE, - INDEX `idx_dates`(`start_date`, `end_date`) USING BTREE, - INDEX `idx_created_at`(`created_at`) USING BTREE, - INDEX `warehouse_id`(`warehouse_id`) USING BTREE, - CONSTRAINT `wms_embargo_policies_ibfk_1` FOREIGN KEY (`warehouse_id`) REFERENCES `wms_store` (`id`) ON DELETE RESTRICT ON UPDATE NO ACTION -) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT = '禁运策略主表' ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_employee_role --- ---------------------------- -DROP TABLE IF EXISTS `wms_employee_role`; -CREATE TABLE `wms_employee_role` ( - `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, - `employee_id` bigint(20) UNSIGNED NOT NULL, - `role_id` bigint(20) UNSIGNED NOT NULL, - PRIMARY KEY (`id`) USING BTREE, - UNIQUE INDEX `uk_employee_role`(`employee_id`, `role_id`) USING BTREE, - INDEX `idx_employee_id`(`employee_id`) USING BTREE, - INDEX `role_id`(`role_id`) USING BTREE, - CONSTRAINT `wms_employee_role_ibfk_1` FOREIGN KEY (`employee_id`) REFERENCES `wms_account_store_employee` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `wms_employee_role_ibfk_2` FOREIGN KEY (`role_id`) REFERENCES `wms_role` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE = InnoDB AUTO_INCREMENT = 163 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_entry_items --- ---------------------------- -DROP TABLE IF EXISTS `wms_entry_items`; -CREATE TABLE `wms_entry_items` ( - `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, - `order_id` bigint(20) UNSIGNED NOT NULL, - `out_biz_code` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, - `order_line_no` bigint(20) UNSIGNED NULL DEFAULT NULL, - `owner_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, - `item_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, - `item_id` bigint(20) UNSIGNED NULL DEFAULT NULL, - `count` int(12) NULL DEFAULT NULL, - `inventory_type` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, - `stock_id` bigint(20) NULL DEFAULT NULL, - `received_quantity` int(12) NOT NULL DEFAULT 0 COMMENT '已收货数量', - `confirm_quantity` int(12) NULL DEFAULT NULL COMMENT '已提交数量', - PRIMARY KEY (`id`) USING BTREE, - UNIQUE INDEX `order_id`(`order_id`, `order_line_no`) USING BTREE, - INDEX `stock_id`(`stock_id`) USING BTREE, - CONSTRAINT `wms_entry_items_ibfk_1` FOREIGN KEY (`order_id`) REFERENCES `wms_entry_order` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION, - CONSTRAINT `wms_entry_items_ibfk_2` FOREIGN KEY (`stock_id`) REFERENCES `wms_stock_warehouse` (`id`) ON DELETE RESTRICT ON UPDATE NO ACTION -) ENGINE = InnoDB AUTO_INCREMENT = 281 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_entry_order --- ---------------------------- -DROP TABLE IF EXISTS `wms_entry_order`; -CREATE TABLE `wms_entry_order` ( - `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '入库单ID', - `entry_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '入库单号', - `order_type` enum('SCRK','LYRK','CCRK','CGRK','DBRK','QTRK','B2BRK','XNRK') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '业务类型', - `purchase_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '采购单号', - `total_order_lines` int(11) NULL DEFAULT 0 COMMENT '单据总行数', - `order_create_time` datetime(0) NULL DEFAULT NULL COMMENT '订单创建时间', - `expect_start_time` datetime(0) NULL DEFAULT NULL COMMENT '预期到货时间', - `expect_end_time` datetime(0) NULL DEFAULT NULL COMMENT '最迟预期到货时间', - `logistics_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '物流公司编码', - `logistics_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '物流公司名称', - `express_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '运单号', - `supplier_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '供应商编码', - `supplier_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '供应商名称', - `source_type` enum('WMS','API','QM') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT 'API' COMMENT '来源类型', - `order_status` enum('PENDING','CONFIRMED','PARTIAL_RECEIVED','COMPLETED','CANCELLED','CREATED','CREATING') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT 'PENDING' COMMENT '订单状态', - `sync_status` enum('PENDING','SUCCESS','FAILED') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT 'PENDING' COMMENT '同步状态', - `sync_message` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL COMMENT '同步返回信息', - `is_enabled` tinyint(1) NULL DEFAULT 1 COMMENT '是否启用', - `created_at` timestamp(0) NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', - `updated_at` timestamp(0) NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', - `warehouse_id` bigint(20) UNSIGNED NOT NULL COMMENT '仓库id', - `store_id` bigint(20) UNSIGNED NOT NULL COMMENT '货主id', - `remark` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT 'ERP备注', - `store_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '货主名称快照', - `warehouse_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '仓库名称快照', - `deleted_at` datetime(0) NULL DEFAULT NULL COMMENT '删除时间', - `qimen_owner_code` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '奇门货主code', - `qimen_warehouse_code` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '奇门仓库code', - PRIMARY KEY (`id`) USING BTREE, - UNIQUE INDEX `uk_entry_order_code`(`entry_order_code`, `warehouse_id`, `store_id`) USING BTREE, - INDEX `idx_order_type`(`order_type`) USING BTREE, - INDEX `idx_order_status`(`order_status`) USING BTREE, - INDEX `idx_sync_status`(`sync_status`) USING BTREE, - INDEX `idx_source`(`source_type`) USING BTREE, - INDEX `idx_create_time`(`order_create_time`) USING BTREE, - INDEX `wms_entry_order_ibfk_2`(`store_id`) USING BTREE, - INDEX `wms_entry_order_ibfk_1`(`warehouse_id`) USING BTREE, - INDEX `id`(`id`, `warehouse_id`, `store_id`) USING BTREE, - CONSTRAINT `wms_entry_order_ibfk_1` FOREIGN KEY (`warehouse_id`) REFERENCES `wms_store` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, - CONSTRAINT `wms_entry_order_ibfk_2` FOREIGN KEY (`store_id`) REFERENCES `wms_store` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION -) ENGINE = InnoDB AUTO_INCREMENT = 217 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT = '入库单主表' ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_express --- ---------------------------- -DROP TABLE IF EXISTS `wms_express`; -CREATE TABLE `wms_express` ( - `code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, - `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, - `KS` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, - `polyapi_extra_info` json NULL, - `PDD` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, - `DYXD` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, - `polyapi_code` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '聚合接口代码', - PRIMARY KEY (`code`) USING BTREE -) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_express_interface --- ---------------------------- -DROP TABLE IF EXISTS `wms_express_interface`; -CREATE TABLE `wms_express_interface` ( - `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT, - `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '接口名称', - `express_code` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '快递编码', - `warehouse_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '仓库编码', - `platform_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '平台编码', - `sender_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '寄件人', - `sender_tel` varchar(11) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '寄件电话', - `weight` int(11) NULL DEFAULT NULL COMMENT '排序', - `token` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '令牌', - `viewer` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '验视员', - `client_id` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '客户id', - `is_share` tinyint(1) NULL DEFAULT 0 COMMENT '是否分享接口', - `share_id` int(11) UNSIGNED NULL DEFAULT NULL COMMENT '分享id', - `can_use_count` int(11) NULL DEFAULT 0 COMMENT '可用数量', - `province_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '寄件人省份', - `city_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '寄件人城市', - `district_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '寄件人区/县', - `town_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '寄件人镇', - `address` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '寄件人地址', - `site_code` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '网点编码', - `product_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '产品编码', - `shop_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '平台店铺', - `sys_express_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '系统快递编码', - `weight_type` int(10) NOT NULL DEFAULT 0 COMMENT '重量类型', - `ispickup` int(11) NULL DEFAULT 0, - `shipperno` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '月结卡号', - PRIMARY KEY (`id`) USING BTREE, - INDEX `warehouse_id`(`warehouse_id`) USING BTREE, - INDEX `sys_express_code`(`sys_express_code`) USING BTREE, - INDEX `platform_code`(`platform_code`) USING BTREE, - CONSTRAINT `wms_express_interface_ibfk_1` FOREIGN KEY (`warehouse_id`) REFERENCES `wms_store` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION, - CONSTRAINT `wms_express_interface_ibfk_2` FOREIGN KEY (`sys_express_code`) REFERENCES `wms_express` (`code`) ON DELETE RESTRICT ON UPDATE NO ACTION, - CONSTRAINT `wms_express_interface_ibfk_3` FOREIGN KEY (`platform_code`) REFERENCES `wms_platform` (`code`) ON DELETE RESTRICT ON UPDATE RESTRICT -) ENGINE = InnoDB AUTO_INCREMENT = 7 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_express_print_record --- ---------------------------- -DROP TABLE IF EXISTS `wms_express_print_record`; -CREATE TABLE `wms_express_print_record` ( - `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID', - `express_id` bigint(20) NOT NULL COMMENT '快递记录ID(关联order_express表)', - `order_id` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '订单ID', - `express_no` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '快递单号', - `platform` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '电商平台', - `template_id` bigint(20) NOT NULL COMMENT '使用的模板ID', - `template_url` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '模板URL(冗余存储)', - `printer_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '打印机名称', - `printer_config_id` bigint(20) NULL DEFAULT NULL COMMENT '打印机配置ID', - `print_data` json NOT NULL COMMENT '打印数据(JSON格式)', - `encrypted_data` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '加密数据', - `signature` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '签名', - `add_data` json NULL COMMENT '附加数据(如寄件人信息)', - `custom_data` json NULL COMMENT '自定义数据(商品信息等)', - `print_status` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT 'PENDING' COMMENT '打印状态:PENDING-待打印,PRINTING-打印中,SUCCESS-打印成功,FAILED-打印失败,RETRY-重试中', - `print_count` int(11) NULL DEFAULT 0 COMMENT '打印次数', - `last_print_time` datetime(0) NULL DEFAULT NULL COMMENT '最后一次打印时间', - `next_retry_time` datetime(0) NULL DEFAULT NULL COMMENT '下次重试时间', - `request_id` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '打印请求ID', - `document_id` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '文档ID', - `batch_no` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '打印批次号', - `print_result` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '打印结果(成功/失败信息)', - `error_message` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '错误信息', - `print_cost_time` int(11) NULL DEFAULT NULL COMMENT '打印耗时(毫秒)', - `create_interface` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '创建接口', - `print_interface` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '打印接口', - `operator_id` bigint(20) NULL DEFAULT NULL COMMENT '操作员ID', - `warehouse_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '仓库ID', - `create_time` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', - `print_time` datetime(0) NULL DEFAULT NULL COMMENT '实际打印时间', - `update_time` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', - PRIMARY KEY (`id`) USING BTREE, - UNIQUE INDEX `uk_express_print`(`express_id`, `print_status`) USING BTREE, - UNIQUE INDEX `uk_request_id`(`request_id`) USING BTREE, - INDEX `idx_order_id`(`order_id`) USING BTREE, - INDEX `idx_express_no`(`express_no`) USING BTREE, - INDEX `idx_platform`(`platform`) USING BTREE, - INDEX `idx_print_status`(`print_status`) USING BTREE, - INDEX `idx_create_time`(`create_time`) USING BTREE, - INDEX `idx_batch_no`(`batch_no`) USING BTREE, - INDEX `idx_template_id`(`template_id`) USING BTREE, - INDEX `idx_printer_config_id`(`printer_config_id`) USING BTREE, - INDEX `idx_print_time`(`print_time`) USING BTREE, - INDEX `idx_warehouse_id`(`warehouse_id`) USING BTREE -) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '快递打印记录表' ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_express_product_type --- ---------------------------- -DROP TABLE IF EXISTS `wms_express_product_type`; -CREATE TABLE `wms_express_product_type` ( - `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT, - `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '产品名称', - `express_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '物流编码', - `code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '产品编码', - PRIMARY KEY (`id`) USING BTREE -) ENGINE = InnoDB AUTO_INCREMENT = 25 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_express_setting --- ---------------------------- -DROP TABLE IF EXISTS `wms_express_setting`; -CREATE TABLE `wms_express_setting` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `express_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '系统快递编码', - `code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '自设编码', - `warehouse_id` bigint(20) UNSIGNED NOT NULL COMMENT '仓库id', - `name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '别名', - `deleted_at` datetime(0) NULL DEFAULT NULL, - PRIMARY KEY (`id`) USING BTREE, - UNIQUE INDEX `platform_code`(`express_code`, `warehouse_id`) USING BTREE, - INDEX `warehouse_id`(`warehouse_id`) USING BTREE, - INDEX `idx_warehouse_deleted_at`(`warehouse_id`, `deleted_at`) USING BTREE, - CONSTRAINT `wms_express_setting_ibfk_1` FOREIGN KEY (`express_code`) REFERENCES `wms_express` (`code`) ON DELETE RESTRICT ON UPDATE NO ACTION, - CONSTRAINT `wms_express_setting_ibfk_2` FOREIGN KEY (`warehouse_id`) REFERENCES `wms_store` (`id`) ON DELETE RESTRICT ON UPDATE NO ACTION -) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_fast_where --- ---------------------------- -DROP TABLE IF EXISTS `wms_fast_where`; -CREATE TABLE `wms_fast_where` ( - `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT, - `label` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '条件/组名称', - `value` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '查询条件,json需要序列化', - `pid` int(11) NULL DEFAULT NULL COMMENT '父级id,方便树结构', - `icon` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT 'icon编码', - `type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '查询类别', - `created_at` datetime(0) NULL DEFAULT NULL, - `updated_at` datetime(0) NULL DEFAULT NULL, - `deleted_at` datetime(0) NULL DEFAULT NULL, - PRIMARY KEY (`id`) USING BTREE -) ENGINE = InnoDB AUTO_INCREMENT = 39 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_file --- ---------------------------- -DROP TABLE IF EXISTS `wms_file`; -CREATE TABLE `wms_file` ( - `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '文件唯一ID', - `warehouse_id` bigint(20) UNSIGNED NOT NULL COMMENT '仓库ID(核心统计维度)', - `file_key` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '存储路径/对象键(如cos/2024/03/file.jpg)', - `file_url` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '完整访问URL', - `file_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '原始文件名', - `file_size` int(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT '文件大小(字节)', - `file_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT '' COMMENT '文件类型:inventory_image, delivery_note, inspection_video', - `mime_type` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT '' COMMENT 'MIME类型', - `md5_hash` char(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '文件MD5(去重依据)', - `sha1_hash` char(40) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '文件SHA1(二次校验)', - `storage_mode` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'cos' COMMENT '存储方式:cos/oss/local', - `storage_class` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT 'standard' COMMENT '存储级别:standard/ia/archive', - `uploader_id` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '上传者ID(用户ID/员工工号)', - `uploader_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '上传者姓名(快照)', - `uploader_dept` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT '' COMMENT '上传者部门(快照)', - `created_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', - `updated_at` datetime(0) NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', - `is_deleted` tinyint(1) UNSIGNED NOT NULL DEFAULT 0 COMMENT '软删除标记', - `deleted_at` datetime(0) NULL DEFAULT NULL COMMENT '删除时间', - `deleted_by` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '删除操作人', - `expire_time` datetime(0) NULL DEFAULT NULL COMMENT '过期时间,Null为永不过期', - PRIMARY KEY (`id`) USING BTREE, - UNIQUE INDEX `uk_file_key`(`file_key`) USING BTREE COMMENT '存储路径唯一', - UNIQUE INDEX `uk_md5_hash`(`md5_hash`, `warehouse_id`) USING BTREE COMMENT '文件内容去重', - INDEX `idx_warehouse`(`warehouse_id`) USING BTREE COMMENT '仓库维度查询', - INDEX `idx_uploader`(`uploader_id`) USING BTREE COMMENT '上传者查询', - INDEX `idx_created`(`created_at`) USING BTREE COMMENT '时间范围查询', - INDEX `idx_type_warehouse`(`file_type`, `warehouse_id`) USING BTREE COMMENT '业务类型统计', - INDEX `idx_warehouse_file_size`(`warehouse_id`, `file_size`) USING BTREE, - CONSTRAINT `wms_file_ibfk_1` FOREIGN KEY (`warehouse_id`) REFERENCES `wms_store` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION -) ENGINE = InnoDB AUTO_INCREMENT = 115111 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT = 'WMS文件资源中枢表' ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_file_reference --- ---------------------------- -DROP TABLE IF EXISTS `wms_file_reference`; -CREATE TABLE `wms_file_reference` ( - `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, - `file_id` bigint(20) UNSIGNED NOT NULL COMMENT '文件ID', - `warehouse_id` bigint(20) UNSIGNED NOT NULL COMMENT '仓库ID(冗余,优化查询)', - `business_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '业务类型:sku_image/packing_list/inspection_report', - `business_id` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '业务ID(如SKU编码、出库单号)', - `display_order` smallint(5) UNSIGNED NULL DEFAULT 0 COMMENT '显示顺序', - `created_by` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '关联创建者', - `created_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0), - PRIMARY KEY (`id`) USING BTREE, - UNIQUE INDEX `uk_business_file`(`business_type`, `business_id`, `file_id`) USING BTREE, - INDEX `idx_file_id`(`file_id`) USING BTREE COMMENT '文件反查业务', - INDEX `idx_warehouse_business`(`warehouse_id`, `business_type`) USING BTREE COMMENT '业务维度查询', - INDEX `idx_business`(`business_id`) USING BTREE COMMENT '业务ID查询', - CONSTRAINT `fk_reference_file` FOREIGN KEY (`file_id`) REFERENCES `wms_file` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT, - CONSTRAINT `wms_file_reference_ibfk_1` FOREIGN KEY (`warehouse_id`) REFERENCES `wms_store` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION -) ENGINE = InnoDB AUTO_INCREMENT = 97042 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT = 'WMS文件业务关联表' ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_i18n_keys --- ---------------------------- -DROP TABLE IF EXISTS `wms_i18n_keys`; -CREATE TABLE `wms_i18n_keys` ( - `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, - `key_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '国际化键名(英文)', - `project` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT 'wms' COMMENT '项目标识', - `module` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '模块: inventory/order/shipment/user', - `description` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '键值描述', - `status` tinyint(4) NOT NULL DEFAULT 1 COMMENT '状态: 1-启用 0-禁用', - `created_by` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '创建人', - `updated_by` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '更新人', - `created_at` timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0), - `updated_at` timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0), - PRIMARY KEY (`id`) USING BTREE, - UNIQUE INDEX `uk_wms_key_project`(`key_name`, `project`) USING BTREE, - INDEX `idx_wms_project_module`(`project`, `module`) USING BTREE, - INDEX `idx_wms_status`(`status`) USING BTREE -) ENGINE = InnoDB AUTO_INCREMENT = 261 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = 'WMS国际化键值表' ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_i18n_translations --- ---------------------------- -DROP TABLE IF EXISTS `wms_i18n_translations`; -CREATE TABLE `wms_i18n_translations` ( - `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, - `key_id` int(10) UNSIGNED NOT NULL COMMENT '键ID', - `language` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '语言代码', - `translation` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '翻译内容,NULL表示未翻译', - `translation_status` tinyint(4) NOT NULL DEFAULT 0 COMMENT '0-未翻译 1-待审核 2-已审核', - `auto_generated` tinyint(4) NOT NULL DEFAULT 0 COMMENT '是否自动生成: 0-手动 1-自动', - `translator` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '翻译人员/系统', - `reviewed_by` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '审核人', - `reviewed_at` timestamp(0) NULL DEFAULT NULL COMMENT '审核时间', - `created_at` timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0), - `updated_at` timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0), - PRIMARY KEY (`id`) USING BTREE, - UNIQUE INDEX `uk_wms_key_language`(`key_id`, `language`) USING BTREE, - INDEX `idx_wms_key_id`(`key_id`) USING BTREE, - INDEX `idx_wms_language_status`(`language`, `translation_status`) USING BTREE, - INDEX `idx_wms_auto_generated`(`auto_generated`) USING BTREE, - CONSTRAINT `fk_wms_translation_key` FOREIGN KEY (`key_id`) REFERENCES `wms_i18n_keys` (`id`) ON DELETE CASCADE ON UPDATE RESTRICT -) ENGINE = InnoDB AUTO_INCREMENT = 890 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = 'WMS国际化翻译表' ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_interface_type --- ---------------------------- -DROP TABLE IF EXISTS `wms_interface_type`; -CREATE TABLE `wms_interface_type` ( - `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '接口类型ID', - `interface_code` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '接口编码,唯一标识', - `interface_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '接口名称', - `interface_category` enum('QM_WMS','OPEN_API') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '接口类别:QM_WMS-奇门仓储, OPEN_API-开放接口', - `entry_url` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '入口链接', - `description` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL COMMENT '接口描述', - `is_enabled` tinyint(1) NOT NULL DEFAULT 1 COMMENT '是否启用', - `created_at` timestamp(0) NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', - `updated_at` timestamp(0) NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', - `is_store` tinyint(1) NOT NULL DEFAULT 0 COMMENT '是否是货主的接口', - PRIMARY KEY (`id`) USING BTREE, - UNIQUE INDEX `uk_interface_code`(`interface_code`) USING BTREE -) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT = '接口类型表' ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_location_space --- ---------------------------- -DROP TABLE IF EXISTS `wms_location_space`; -CREATE TABLE `wms_location_space` ( - `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '仓位ID', - `warehouse_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '仓库ID', - `zone_id` int(10) UNSIGNED NULL DEFAULT NULL COMMENT '所属分区ID', - `location_type_id` int(10) UNSIGNED NOT NULL COMMENT '仓位类型ID', - `space_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '仓位编码', - `custom_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '自定义名称', - `custom_barcode` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '自定义条码', - `row_no` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '排号', - `column_no` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '列号', - `level_no` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '层号', - `cell_no` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '格号', - `length` decimal(8, 2) NULL DEFAULT NULL COMMENT '长度(cm)', - `width` decimal(8, 2) NULL DEFAULT NULL COMMENT '宽度(cm)', - `height` decimal(8, 2) NULL DEFAULT NULL COMMENT '高度(cm)', - `volume` decimal(10, 2) NULL DEFAULT NULL COMMENT '体积(m³)', - `max_weight` decimal(10, 2) NULL DEFAULT NULL COMMENT '最大承重(kg)', - `space_status` enum('AVAILABLE','OCCUPIED','RESERVED','MAINTENANCE','DISABLED') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT 'AVAILABLE' COMMENT '仓位状态', - `is_enabled` tinyint(1) NOT NULL DEFAULT 1 COMMENT '是否启用', - `current_sku_count` int(11) NULL DEFAULT 0 COMMENT '当前SKU种类数', - `current_quantity` int(11) NULL DEFAULT 0 COMMENT '当前库存数量', - `current_weight` decimal(10, 2) NULL DEFAULT 0.00 COMMENT '当前重量(kg)', - `current_volume` decimal(10, 2) NULL DEFAULT 0.00 COMMENT '当前体积(m³)', - `created_by` bigint(20) NULL DEFAULT NULL COMMENT '创建人', - `updated_by` bigint(20) NULL DEFAULT NULL COMMENT '更新人', - `created_at` timestamp(0) NULL DEFAULT CURRENT_TIMESTAMP(0), - `updated_at` timestamp(0) NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0), - `deleted_at` datetime(0) NULL DEFAULT NULL, - `pick_sequence` int(10) NULL DEFAULT NULL COMMENT '拣货顺序', - `pick_zone_id` int(10) NULL DEFAULT NULL COMMENT '所属拣货分区ID', - `is_preferred_pick` tinyint(1) NULL DEFAULT 0 COMMENT '是否优先拣货位', - `distance_from_start` int(11) NULL DEFAULT NULL COMMENT '距起始点距离(mm)', - `pick_time_estimate` int(11) NULL DEFAULT 0 COMMENT '预估拣货时间(秒)', - `pick_priority` tinyint(3) NULL DEFAULT 50 COMMENT '拣货优先级(1-100)', - `last_picked_at` datetime(0) NULL DEFAULT NULL COMMENT '最后拣货时间', - `pick_count` int(11) NULL DEFAULT 0 COMMENT '拣货次数', - `relative_x` decimal(8, 2) NULL DEFAULT NULL COMMENT '在货架内的X坐标(cm)', - `relative_y` decimal(8, 2) NULL DEFAULT NULL COMMENT '在货架内的Y坐标(cm)', - `relative_z` decimal(8, 2) NULL DEFAULT NULL COMMENT '在货架内的Z坐标(cm)', - PRIMARY KEY (`id`) USING BTREE, - UNIQUE INDEX `uk_warehouse_space_code`(`warehouse_id`, `space_code`, `deleted_at`) USING BTREE, - UNIQUE INDEX `uk_custom_barcode`(`custom_barcode`, `warehouse_id`, `deleted_at`) USING BTREE, - INDEX `idx_warehouse_zone`(`warehouse_id`, `zone_id`) USING BTREE, - INDEX `idx_location_type`(`location_type_id`) USING BTREE, - INDEX `idx_space_status`(`space_status`) USING BTREE, - INDEX `idx_is_enabled`(`is_enabled`) USING BTREE, - INDEX `idx_row_column_level`(`row_no`, `column_no`, `level_no`) USING BTREE, - INDEX `fk_location_space_zone`(`zone_id`) USING BTREE, - INDEX `idx_pick_sequence`(`warehouse_id`, `pick_sequence`, `space_status`) USING BTREE, - INDEX `idx_pick_priority`(`pick_priority`, `space_status`) USING BTREE, - INDEX `idx_last_picked`(`last_picked_at`) USING BTREE, - INDEX `idx_pick_zone`(`pick_zone_id`) USING BTREE, - CONSTRAINT `fk_location_space_type` FOREIGN KEY (`location_type_id`) REFERENCES `wms_location_type` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT, - CONSTRAINT `fk_location_space_warehouse` FOREIGN KEY (`warehouse_id`) REFERENCES `wms_store` (`id`) ON DELETE CASCADE ON UPDATE RESTRICT -) ENGINE = InnoDB AUTO_INCREMENT = 26885 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '仓位格子表' ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_location_type --- ---------------------------- -DROP TABLE IF EXISTS `wms_location_type`; -CREATE TABLE `wms_location_type` ( - `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '类型ID', - `type_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '类型编码', - `type_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '类型名称', - `temperature_zone` enum('NORMAL','COLD','FROZEN','DANGEROUS') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'NORMAL' COMMENT '温区', - `is_active` tinyint(1) NOT NULL DEFAULT 1, - `description` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, - `created_at` timestamp(0) NULL DEFAULT CURRENT_TIMESTAMP(0), - `allow_allocation` tinyint(1) NULL DEFAULT NULL COMMENT '是否允许分配储位', - `allow_transfer_out` tinyint(1) NULL DEFAULT NULL COMMENT '是否允许移出', - `warehouse_id` bigint(20) UNSIGNED NULL DEFAULT NULL, - PRIMARY KEY (`id`) USING BTREE, - UNIQUE INDEX `uk_type_code`(`type_code`) USING BTREE, - INDEX `warehouse_id`(`warehouse_id`) USING BTREE, - CONSTRAINT `wms_location_type_ibfk_1` FOREIGN KEY (`warehouse_id`) REFERENCES `wms_store` (`id`) ON DELETE RESTRICT ON UPDATE NO ACTION -) ENGINE = InnoDB AUTO_INCREMENT = 8 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '库位类型表' ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_location_zone --- ---------------------------- -DROP TABLE IF EXISTS `wms_location_zone`; -CREATE TABLE `wms_location_zone` ( - `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '分区ID', - `warehouse_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '仓库ID', - `zone_code` varchar(5) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '分区编码(最多5位字母或数字)', - `zone_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '分区名称', - `zone_type` enum('warehouse','area','rack','pick_start') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '分区类型:warehouse-仓库, area-库区, rack-货架, pick_start-起始拣货点', - `parent_id` int(10) UNSIGNED NULL DEFAULT NULL COMMENT '父分区ID', - `is_active` tinyint(1) NOT NULL DEFAULT 1 COMMENT '是否启用', - `created_at` timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', - `updated_at` timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', - `deleted_at` datetime(0) NULL DEFAULT NULL COMMENT '软删除时间', - `x` int(11) NOT NULL COMMENT '左下角x坐标(mm)', - `y` int(11) NOT NULL COMMENT '左下角y坐标(mm)', - `z` int(11) NOT NULL COMMENT '左下角z坐标(mm)', - `length` int(11) NOT NULL COMMENT '长度(mm)', - `width` int(11) NOT NULL COMMENT '宽度(mm)', - `height` int(11) NOT NULL COMMENT '高度(mm)', - `rack_columns` tinyint(3) UNSIGNED NULL DEFAULT 1 COMMENT '货架列数(1-255)', - `rack_rows` tinyint(3) UNSIGNED NULL DEFAULT NULL COMMENT '货架层数', - `rack_levels` tinyint(3) UNSIGNED NULL DEFAULT NULL COMMENT '货架分格数', - `direction` enum('north','south','east','west') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '货架朝向', - `color` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT '#3B82F6' COMMENT '显示颜色,#RRGGBB格式', - `cell_width` int(11) UNSIGNED NULL DEFAULT NULL COMMENT '货架的长度', - `cell_height` int(11) UNSIGNED NULL DEFAULT NULL COMMENT '货架的高度', - `cell_length` int(11) UNSIGNED NULL DEFAULT NULL COMMENT '货架的深度', - `path_sequence` int(10) UNSIGNED NULL DEFAULT NULL COMMENT '拣货路径排序序号', - `pick_distance` int(11) NULL DEFAULT NULL COMMENT '距离起始点的拣货距离(mm)', - `neighbor_zone_ids` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '相邻分区ID列表(JSON数组,用于路径规划)', - `is_passable` tinyint(1) NULL DEFAULT 1 COMMENT '是否可通行(用于障碍物标记)', - `zone_category` enum('storage','operational','obstacle') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'storage' COMMENT '区域分类:storage-存储区, operational-操作区, obstacle-障碍区', - `aisles` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '货架的第几列设置为通道', - PRIMARY KEY (`id`) USING BTREE, - UNIQUE INDEX `uk_warehouse_zone_code`(`warehouse_id`, `zone_code`, `deleted_at`) USING BTREE, - INDEX `idx_warehouse_parent`(`warehouse_id`, `parent_id`) USING BTREE, - INDEX `idx_deleted_at`(`deleted_at`) USING BTREE, - INDEX `idx_zone_type`(`zone_type`) USING BTREE, - INDEX `idx_is_active`(`is_active`) USING BTREE, - INDEX `fk_location_zone_parent`(`parent_id`) USING BTREE, - INDEX `idx_path_sequence`(`warehouse_id`, `path_sequence`, `is_active`) USING BTREE, - INDEX `idx_zone_category`(`zone_category`) USING BTREE, - INDEX `idx_pick_distance`(`warehouse_id`, `pick_distance`) USING BTREE, - CONSTRAINT `fk_location_zone_parent` FOREIGN KEY (`parent_id`) REFERENCES `wms_location_zone` (`id`) ON DELETE SET NULL ON UPDATE RESTRICT, - CONSTRAINT `fk_location_zone_warehouse` FOREIGN KEY (`warehouse_id`) REFERENCES `wms_store` (`id`) ON DELETE CASCADE ON UPDATE RESTRICT -) ENGINE = InnoDB AUTO_INCREMENT = 158 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '库位分区表(支持软删除)' ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_notification_send_log --- ---------------------------- -DROP TABLE IF EXISTS `wms_notification_send_log`; -CREATE TABLE `wms_notification_send_log` ( - `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键ID', - `trace_id` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '通知追踪ID', - `webhook_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT 'Webhook 配置ID', - `store_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '触发主体ID', - `warehouse_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '仓库ID', - `owner_store_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '货主ID', - `business_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '业务名称', - `event` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '事件名', - `hook_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT 'Webhook 类型', - `hook_url` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT 'Webhook 地址', - `request_payload` json NULL COMMENT '请求载荷', - `response_payload` json NULL COMMENT '返回载荷', - `http_status` int(11) NULL DEFAULT NULL COMMENT 'HTTP 状态码', - `status` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'failed' COMMENT '发送状态', - `error_message` varchar(1000) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '失败原因', - `retry_count` int(11) NOT NULL DEFAULT 0 COMMENT '重试次数', - `created_by` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '创建人', - `created_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', - PRIMARY KEY (`id`) USING BTREE, - INDEX `idx_notification_send_log_trace_id`(`trace_id`) USING BTREE, - INDEX `idx_notification_send_log_event_status`(`event`, `status`) USING BTREE, - INDEX `idx_notification_send_log_webhook_id`(`webhook_id`) USING BTREE, - INDEX `idx_notification_send_log_created_at`(`created_at`) USING BTREE -) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT = '统一通知发送失败日志表' ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_notification_webhook --- ---------------------------- -DROP TABLE IF EXISTS `wms_notification_webhook`; -CREATE TABLE `wms_notification_webhook` ( - `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键ID', - `store_id` bigint(20) UNSIGNED NOT NULL COMMENT '主体ID,对应 wms_store.id', - `hook_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT 'Webhook 名称', - `hook_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT 'Webhook 类型,用于分派不同消息结构处理类,如 dingtalk、wecom、feishu、custom', - `hook_url` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT 'Webhook 链接地址', - `events` json NULL COMMENT '订阅事件列表', - `status` tinyint(4) NOT NULL DEFAULT 1 COMMENT '状态:0-禁用,1-启用', - `remark` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '备注', - `created_by` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '创建人', - `created_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', - `updated_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', - `deleted_at` datetime(0) NULL DEFAULT NULL COMMENT '删除时间', - PRIMARY KEY (`id`) USING BTREE, - UNIQUE INDEX `uk_notification_webhook_store_type_url`(`store_id`, `hook_type`, `hook_url`) USING BTREE, - INDEX `idx_notification_webhook_store_id`(`store_id`) USING BTREE, - INDEX `idx_notification_webhook_hook_type`(`hook_type`) USING BTREE, - INDEX `idx_notification_webhook_status`(`status`) USING BTREE, - INDEX `idx_notification_webhook_store_type`(`store_id`, `hook_type`) USING BTREE, - CONSTRAINT `wms_notification_webhook_ibfk_1` FOREIGN KEY (`store_id`) REFERENCES `wms_store` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT = '外部通知 WebHook 配置表' ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_operation_log --- ---------------------------- -DROP TABLE IF EXISTS `wms_operation_log`; -CREATE TABLE `wms_operation_log` ( - `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID', - `business_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '业务类型: product, order, stock, wave, express,storage', - `business_id` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '业务ID', - `operation_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '操作编码', - `operator_id` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '操作人ID(用户ID/系统ID)', - `operator_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '操作人名称', - `external_log_type` enum('REQUEST','API','QIMEN','NONE') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT 'NONE' COMMENT '外部日志类型', - `external_log_id` bigint(20) NULL DEFAULT NULL COMMENT '外部日志ID', - `warehouse_id` bigint(20) UNSIGNED NOT NULL COMMENT '仓库ID', - `before_changes` json NULL COMMENT '关键变更字段', - `created_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', - `platform_code` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '操作平台', - `message` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '写入的消息', - PRIMARY KEY (`id`) USING BTREE, - UNIQUE INDEX `uk_business_operation`(`business_type`, `business_id`, `id`) USING BTREE, - INDEX `idx_business_type_id_time`(`business_type`, `business_id`, `created_at`) USING BTREE, - INDEX `idx_operation_code_time`(`operation_code`, `created_at`) USING BTREE, - INDEX `idx_operator_time`(`operator_id`, `created_at`) USING BTREE, - INDEX `idx_warehouse_time`(`warehouse_id`, `created_at`) USING BTREE, - INDEX `idx_external_log`(`external_log_type`, `external_log_id`) USING BTREE, - INDEX `idx_created_at`(`created_at`) USING BTREE -) ENGINE = InnoDB AUTO_INCREMENT = 495311 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = 'WMS业务操作日志表' ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_order_delivery --- ---------------------------- -DROP TABLE IF EXISTS `wms_order_delivery`; -CREATE TABLE `wms_order_delivery` ( - `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, - `delivery_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, - `pre_delivery_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, - `pre_delivery_order_id` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, - `order_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, - `warehouse_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, - `order_flag` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '订单标记', - `source_platform_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, - `source_platform_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, - `source_order_codes` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '来源订单号集合', - `create_at` datetime(0) NULL DEFAULT NULL, - `delete_at` datetime(0) NULL DEFAULT NULL, - `updated_at` datetime(0) NULL DEFAULT NULL, - `place_order_time` datetime(0) NULL DEFAULT NULL COMMENT '店铺创建订单时间', - `pay_time` datetime(0) NULL DEFAULT NULL COMMENT '支付时间', - `pay_no` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '支付单号', - `service_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '集包服务编码', - `operator_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT 'ERP审核人', - `operate_time` datetime(0) NULL DEFAULT NULL COMMENT 'ERP审核时间', - `delivery_time` datetime(0) NULL DEFAULT NULL COMMENT '发货时间', - `shop_nick` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '店铺名称', - `seller_nick` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '卖家名称', - `buyer_nick` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '买家名称', - `total_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '订单总金额', - `item_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '商品总金额', - `discount_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '订单折扣金额', - `freight` decimal(18, 2) NULL DEFAULT NULL COMMENT '快递费用', - `ar_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '应收金额', - `got_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '已收金额', - `service_fee` decimal(18, 2) NULL DEFAULT NULL COMMENT 'COD服务费', - `logistics_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '物流公司编码', - `logistics_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '物流公司名称', - `express_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '面单号前置', - `logistics_area_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '快递区域编码, 大头笔信息', - `delivery_type` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '发货服务类型', - `weight_type` int(11) NOT NULL DEFAULT 0 COMMENT '重量类型:0常规、1轻货、2重货、3冷链', - `is_urgency` enum('Y','N') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'N' COMMENT '是否紧急', - `invoice_flag` enum('Y','N') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'N' COMMENT '是否需要发票', - `status` enum('pedding','created','cancel','intercepting','intercepted') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'pedding', - `name` text CHARACTER SET utf8 COLLATE utf8_general_ci NULL COMMENT '收件人姓名', - `zip_code` varchar(50) CHARACTER SET ujis COLLATE ujis_japanese_ci NULL DEFAULT '' COMMENT '收件人邮编', - `tel` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人电话', - `mobile` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人移动电话', - `email` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人邮箱', - `country_code` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '国家编码', - `province` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '省份', - `city` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '城市', - `area` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '区', - `town` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '镇', - `detail_address` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '详细地址', - `id_type` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, - `id_number` int(11) NULL DEFAULT NULL, - `oaid` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL, - `sync_status` enum('padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'padding', - `store_id` bigint(20) UNSIGNED NULL DEFAULT NULL, - `warehouse_id` bigint(20) UNSIGNED NULL DEFAULT NULL, - `step` int(10) NOT NULL DEFAULT 0 COMMENT '订单步骤:0未审核,1已审核,2处理中,3驳回/异常,4配送中,5已完成,9已关闭', - `print_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '打印状态机', - `claim_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '领取状态机', - `outbound_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '出库状态机', - `lock_status` enum('none','warehouse','store') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '锁定状态机', - `intercept_status` enum('none','requesting','requested','intercepting','intercepted_in_transit','intercepted_at_warehouse','returning','returned','delivered_by_mistake','timeout','cancelled','failed','exception') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '拦截状态机', - `post_status` enum('padding','fin','timeout','error','none') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '分配快递号状态机', - `storage_status` enum('padding','fin','error','none') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '分配储位状态机', - `pick_status` enum('padding','fin','error','none') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '拣货状态机', - `pack_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '打包状态机', - `inspection_status` enum('none','padding','running','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '检验状态机', - PRIMARY KEY (`id`) USING BTREE, - UNIQUE INDEX `delivery_order_code`(`delivery_order_code`, `warehouse_id`) USING BTREE, - INDEX `store_id`(`store_id`) USING BTREE, - INDEX `warehouse_id`(`warehouse_id`) USING BTREE, - CONSTRAINT `wms_order_delivery_ibfk_1` FOREIGN KEY (`store_id`) REFERENCES `wms_store` (`id`) ON DELETE RESTRICT ON UPDATE NO ACTION, - CONSTRAINT `wms_order_delivery_ibfk_2` FOREIGN KEY (`warehouse_id`) REFERENCES `wms_store` (`id`) ON DELETE RESTRICT ON UPDATE NO ACTION -) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_order_delivery_100000 --- ---------------------------- -DROP TABLE IF EXISTS `wms_order_delivery_100000`; -CREATE TABLE `wms_order_delivery_100000` ( - `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, - `delivery_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '发货单号', - `pre_delivery_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '预发货单号', - `pre_delivery_order_id` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '预发货单ID', - `order_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '订单类型', - `warehouse_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '仓库编码', - `order_flag` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '订单标记', - `source_platform_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '来源平台编码', - `source_platform_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '来源平台名称', - `create_at` datetime(0) NULL DEFAULT NULL COMMENT '创建时间', - `delete_at` datetime(0) NULL DEFAULT NULL COMMENT '删除时间', - `updated_at` datetime(0) NULL DEFAULT NULL COMMENT '更新时间', - `place_order_time` datetime(0) NULL DEFAULT NULL COMMENT '店铺创建订单时间', - `pay_time` datetime(0) NULL DEFAULT NULL COMMENT '支付时间', - `pay_no` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '支付单号', - `service_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '集包服务编码', - `operator_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT 'ERP审核人', - `operate_time` datetime(0) NULL DEFAULT NULL COMMENT 'ERP审核时间', - `delivery_time` datetime(0) NULL DEFAULT NULL COMMENT '发货时间', - `shop_nick` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '店铺名称', - `seller_nick` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '卖家名称', - `buyer_nick` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '买家名称', - `total_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '订单总金额', - `item_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '商品总金额', - `discount_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '订单折扣金额', - `freight` decimal(18, 2) NULL DEFAULT NULL COMMENT '快递费用', - `ar_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '应收金额', - `got_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '已收金额', - `service_fee` decimal(18, 2) NULL DEFAULT NULL COMMENT 'COD服务费', - `logistics_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '物流公司编码', - `logistics_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '物流公司名称', - `express_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '面单号前置', - `logistics_area_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '快递区域编码, 大头笔信息', - `delivery_type` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '发货服务类型', - `is_urgency` enum('Y','N') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'N' COMMENT '是否紧急', - `invoice_flag` enum('Y','N') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'N' COMMENT '是否需要发票', - `status` enum('pedding','created','cancel','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'created' COMMENT '订单状态', - `name` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人姓名', - `zip_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '收件人邮编', - `tel` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人电话', - `mobile` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人移动电话', - `email` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人邮箱', - `country_code` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '国家编码', - `province` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '省份', - `city` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '城市', - `area` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '区', - `town` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '镇', - `detail_address` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '详细地址', - `id_type` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '证件类型', - `id_number` int(11) NULL DEFAULT NULL COMMENT '证件号码', - `oaid` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT 'OAID', - `sync_status` enum('padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'padding' COMMENT '同步状态', - `store_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '货主ID', - `warehouse_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '仓库ID', - `from_key` int(11) NULL DEFAULT NULL COMMENT '来源键', - `items` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '商品JSON字符串', - `items_count` smallint(5) UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品种类数', - `items_total` int(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品总数', - `items_weight` decimal(10, 2) NOT NULL DEFAULT 0.00 COMMENT '总重量(kg)', - `items_hash` char(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT 'MD5哈希值(32位)', - `items_crc` int(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'CRC32校验码', - `wave_id` bigint(20) NOT NULL DEFAULT 0 COMMENT '波次ID,0表示未分配', - `post_status` enum('padding','fin','timeout','error','none') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '分配快递号状态机', - `storage_status` enum('padding','fin','error','none') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '分配储位状态机', - `pick_status` enum('padding','fin','error','none') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '拣货状态机', - `pack_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '打包状态机', - `inspection_status` enum('none','padding','running','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '检验状态机', - `step` int(10) NOT NULL DEFAULT 0 COMMENT '订单步骤:0未审核,1已审核,2处理中,3驳回/异常,4配送中,5已完成,9已关闭', - `print_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '打印状态机', - `claim_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '领取状态机', - `outbound_status` enum('none','padding','fin','timeout','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '出库状态机', - `lock_status` enum('none','warehouse','store') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '锁定状态机', - `intercept_status` enum('none','requesting','requested','intercepting','intercepted_in_transit','intercepted_at_warehouse','returning','returned','delivered_by_mistake','timeout','cancelled','failed','exception') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '拦截状态机', - `sys_platform_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统平台编码', - `sys_platform_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统平台名称', - `sys_logistics_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统物流公司编码', - `sys_logistics_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统物流公司名称', - `weight_type` int(11) NOT NULL DEFAULT 0 COMMENT '重量类型:0常规、1轻货、2重货、3冷链', - `source_order_codes` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '来源订单号集合', - `sended_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '发货状态机', - `create_channel` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT 'MANUAL' COMMENT '创建来源渠道', - `basket_number` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '筐号', - `wave_no` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '波次号,空字符串表示未分配', - PRIMARY KEY (`id`) USING BTREE, - UNIQUE INDEX `idx_100000_current_delivery_code`(`delivery_order_code`, `store_id`, `warehouse_id`) USING BTREE, - INDEX `idx_100000_current_store_id`(`store_id`) USING BTREE, - INDEX `idx_100000_current_warehouse_id`(`warehouse_id`) USING BTREE, - INDEX `idx_100000_current_items`(`items`(50)) USING BTREE, - INDEX `idx_100000_current_items_hash`(`items_hash`) USING BTREE, - INDEX `idx_100000_current_hash_crc`(`items_hash`, `items_crc`, `warehouse_id`) USING BTREE, - INDEX `idx_100000_current_wave`(`status`, `wave_id`) USING BTREE, - INDEX `idx_100000_current_statuses`(`status`, `post_status`, `pick_status`, `pack_status`, `outbound_status`) USING BTREE -) ENGINE = InnoDB AUTO_INCREMENT = 120874 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '仓库100000发货单常用表' ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_order_delivery_100000_dispatch --- ---------------------------- -DROP TABLE IF EXISTS `wms_order_delivery_100000_dispatch`; -CREATE TABLE `wms_order_delivery_100000_dispatch` ( - `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, - `delivery_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '发货单号', - `pre_delivery_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '预发货单号', - `pre_delivery_order_id` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '预发货单ID', - `order_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '订单类型', - `warehouse_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '仓库编码', - `order_flag` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '订单标记', - `source_platform_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '来源平台编码', - `source_platform_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '来源平台名称', - `source_order_codes` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '来源订单号集合', - `create_at` datetime(0) NULL DEFAULT NULL COMMENT '创建时间', - `delete_at` datetime(0) NULL DEFAULT NULL COMMENT '删除时间', - `updated_at` datetime(0) NULL DEFAULT NULL COMMENT '更新时间', - `place_order_time` datetime(0) NULL DEFAULT NULL COMMENT '店铺创建订单时间', - `pay_time` datetime(0) NULL DEFAULT NULL COMMENT '支付时间', - `pay_no` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '支付单号', - `service_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '集包服务编码', - `operator_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT 'ERP审核人', - `operate_time` datetime(0) NULL DEFAULT NULL COMMENT 'ERP审核时间', - `delivery_time` datetime(0) NULL DEFAULT NULL COMMENT '发货时间', - `shop_nick` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '店铺名称', - `seller_nick` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '卖家名称', - `buyer_nick` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '买家名称', - `total_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '订单总金额', - `item_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '商品总金额', - `discount_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '订单折扣金额', - `freight` decimal(18, 2) NULL DEFAULT NULL COMMENT '快递费用', - `ar_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '应收金额', - `got_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '已收金额', - `service_fee` decimal(18, 2) NULL DEFAULT NULL COMMENT 'COD服务费', - `logistics_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '物流公司编码', - `logistics_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '物流公司名称', - `express_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '面单号前置', - `logistics_area_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '快递区域编码, 大头笔信息', - `delivery_type` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '发货服务类型', - `weight_type` int(11) NOT NULL DEFAULT 0 COMMENT '重量类型:0常规、1轻货、2重货、3冷链', - `is_urgency` enum('Y','N') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'N' COMMENT '是否紧急', - `invoice_flag` enum('Y','N') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'N' COMMENT '是否需要发票', - `status` enum('pedding','created','cancel','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'created' COMMENT '订单状态', - `name` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人姓名', - `zip_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '收件人邮编', - `tel` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人电话', - `mobile` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人移动电话', - `email` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人邮箱', - `country_code` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '国家编码', - `province` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '省份', - `city` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '城市', - `area` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '区', - `town` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '镇', - `detail_address` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '详细地址', - `id_type` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '证件类型', - `id_number` int(11) NULL DEFAULT NULL COMMENT '证件号码', - `oaid` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT 'OAID', - `sync_status` enum('padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'padding' COMMENT '同步状态', - `store_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '货主ID', - `warehouse_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '仓库ID', - `from_key` int(11) NULL DEFAULT NULL COMMENT '来源键', - `items` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '商品JSON字符串', - `items_count` smallint(5) UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品种类数', - `items_total` int(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品总数', - `items_weight` decimal(10, 2) NOT NULL DEFAULT 0.00 COMMENT '总重量(kg)', - `items_hash` char(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT 'MD5哈希值(32位)', - `items_crc` int(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'CRC32校验码', - `wave_id` bigint(20) NOT NULL DEFAULT 0 COMMENT '波次ID,0表示未分配', - `post_status` enum('padding','fin','timeout','error','none') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '分配快递号状态机', - `storage_status` enum('padding','fin','error','none') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '分配储位状态机', - `pick_status` enum('padding','fin','error','none') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '拣货状态机', - `pack_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '打包状态机', - `inspection_status` enum('none','padding','running','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '检验状态机', - `step` int(10) NOT NULL DEFAULT 0 COMMENT '订单步骤:0未审核,1已审核,2处理中,3驳回/异常,4配送中,5已完成,9已关闭', - `print_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '打印状态机', - `claim_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '领取状态机', - `outbound_status` enum('none','padding','fin','timeout','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '出库状态机', - `lock_status` enum('none','warehouse','store') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '锁定状态机', - `intercept_status` enum('none','requesting','requested','intercepting','intercepted_in_transit','intercepted_at_warehouse','returning','returned','delivered_by_mistake','timeout','cancelled','failed','exception') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '拦截状态机', - `dispatch_lane` enum('m4','m5') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT 'm4' COMMENT '配送工作台子域(M4正常/M5异常)', - `sys_platform_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统平台编码', - `sys_platform_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统平台名称', - `sys_logistics_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统物流公司编码', - `sys_logistics_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统物流公司名称', - `sended_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '发货状态机', - `create_channel` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT 'MANUAL' COMMENT '创建来源渠道', - `basket_number` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '筐号', - `wave_no` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '波次号,空字符串表示未分配', - PRIMARY KEY (`id`) USING BTREE, - UNIQUE INDEX `idx_100000_current_delivery_code`(`delivery_order_code`, `store_id`, `warehouse_id`) USING BTREE, - INDEX `idx_100000_current_store_id`(`store_id`) USING BTREE, - INDEX `idx_100000_current_warehouse_id`(`warehouse_id`) USING BTREE, - INDEX `idx_dispatch_100000_dispatch_lane`(`dispatch_lane`, `status`) USING BTREE, - INDEX `idx_100000_current_items`(`items`(50)) USING BTREE, - INDEX `idx_100000_current_items_hash`(`items_hash`) USING BTREE, - INDEX `idx_100000_current_hash_crc`(`items_hash`, `items_crc`, `warehouse_id`) USING BTREE, - INDEX `idx_100000_current_wave`(`status`, `wave_id`) USING BTREE, - INDEX `idx_100000_current_statuses`(`status`, `post_status`, `pick_status`, `pack_status`, `outbound_status`) USING BTREE -) ENGINE = InnoDB AUTO_INCREMENT = 120067 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '仓库100000发货单配送域(M4/M5)影子表' ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_order_delivery_100000_history --- ---------------------------- -DROP TABLE IF EXISTS `wms_order_delivery_100000_history`; -CREATE TABLE `wms_order_delivery_100000_history` ( - `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, - `delivery_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '发货单号', - `pre_delivery_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '预发货单号', - `pre_delivery_order_id` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '预发货单ID', - `order_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '订单类型', - `warehouse_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '仓库编码', - `order_flag` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '订单标记', - `source_platform_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '来源平台编码', - `source_platform_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '来源平台名称', - `source_order_codes` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '来源订单号集合', - `create_at` datetime(0) NULL DEFAULT NULL COMMENT '创建时间', - `delete_at` datetime(0) NULL DEFAULT NULL COMMENT '删除时间', - `updated_at` datetime(0) NULL DEFAULT NULL COMMENT '更新时间', - `place_order_time` datetime(0) NULL DEFAULT NULL COMMENT '店铺创建订单时间', - `pay_time` datetime(0) NULL DEFAULT NULL COMMENT '支付时间', - `pay_no` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '支付单号', - `service_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '集包服务编码', - `operator_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT 'ERP审核人', - `operate_time` datetime(0) NULL DEFAULT NULL COMMENT 'ERP审核时间', - `delivery_time` datetime(0) NULL DEFAULT NULL COMMENT '发货时间', - `shop_nick` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '店铺名称', - `seller_nick` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '卖家名称', - `buyer_nick` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '买家名称', - `total_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '订单总金额', - `item_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '商品总金额', - `discount_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '订单折扣金额', - `freight` decimal(18, 2) NULL DEFAULT NULL COMMENT '快递费用', - `ar_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '应收金额', - `got_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '已收金额', - `service_fee` decimal(18, 2) NULL DEFAULT NULL COMMENT 'COD服务费', - `logistics_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '物流公司编码', - `logistics_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '物流公司名称', - `express_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '面单号前置', - `logistics_area_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '快递区域编码, 大头笔信息', - `delivery_type` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '发货服务类型', - `weight_type` int(11) NOT NULL DEFAULT 0 COMMENT '重量类型:0常规、1轻货、2重货、3冷链', - `is_urgency` enum('Y','N') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'N' COMMENT '是否紧急', - `invoice_flag` enum('Y','N') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'N' COMMENT '是否需要发票', - `status` enum('pedding','created','cancel','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'created' COMMENT '订单状态', - `name` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人姓名', - `zip_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '收件人邮编', - `tel` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人电话', - `mobile` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人移动电话', - `email` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人邮箱', - `country_code` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '国家编码', - `province` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '省份', - `city` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '城市', - `area` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '区', - `town` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '镇', - `detail_address` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '详细地址', - `id_type` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '证件类型', - `id_number` int(11) NULL DEFAULT NULL COMMENT '证件号码', - `oaid` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT 'OAID', - `sync_status` enum('padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'padding' COMMENT '同步状态', - `store_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '货主ID', - `warehouse_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '仓库ID', - `from_key` int(11) NULL DEFAULT NULL COMMENT '来源键', - `items` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '商品JSON字符串', - `items_count` smallint(5) UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品种类数', - `items_total` int(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品总数', - `items_weight` decimal(10, 2) NOT NULL DEFAULT 0.00 COMMENT '总重量(kg)', - `items_hash` char(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT 'MD5哈希值(32位)', - `items_crc` int(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'CRC32校验码', - `wave_id` bigint(20) NOT NULL DEFAULT 0 COMMENT '波次ID,0表示未分配', - `post_status` enum('padding','fin','timeout','error','none') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '分配快递号状态机', - `storage_status` enum('padding','fin','error','none') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '分配储位状态机', - `pick_status` enum('padding','fin','error','none') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '拣货状态机', - `pack_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '打包状态机', - `inspection_status` enum('none','padding','running','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '检验状态机', - `step` int(10) NOT NULL DEFAULT 0 COMMENT '订单步骤:0未审核,1已审核,2处理中,3驳回/异常,4配送中,5已完成,9已关闭', - `print_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '打印状态机', - `claim_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '领取状态机', - `outbound_status` enum('none','padding','fin','timeout','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '出库状态机', - `lock_status` enum('none','warehouse','store') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '锁定状态机', - `intercept_status` enum('none','requesting','requested','intercepting','intercepted_in_transit','intercepted_at_warehouse','returning','returned','delivered_by_mistake','timeout','cancelled','failed','exception') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '拦截状态机', - `archive_time` datetime(0) NULL DEFAULT NULL COMMENT '归档时间', - `sys_platform_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统平台编码', - `sys_platform_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统平台名称', - `sys_logistics_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统物流公司编码', - `sys_logistics_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统物流公司名称', - `create_channel` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT 'MANUAL' COMMENT '创建来源渠道', - `sended_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '发货状态机', - `basket_number` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '筐号', - PRIMARY KEY (`id`) USING BTREE, - UNIQUE INDEX `idx_100000_history_delivery_code`(`delivery_order_code`, `store_id`, `warehouse_id`) USING BTREE, - INDEX `idx_100000_history_store_id`(`store_id`) USING BTREE, - INDEX `idx_100000_history_warehouse_id`(`warehouse_id`) USING BTREE, - INDEX `idx_100000_history_items`(`items`(50)) USING BTREE, - INDEX `idx_100000_history_items_hash`(`items_hash`) USING BTREE, - INDEX `idx_100000_history_hash_crc`(`items_hash`, `items_crc`, `warehouse_id`) USING BTREE, - INDEX `idx_100000_history_wave`(`status`, `wave_id`) USING BTREE, - INDEX `idx_100000_history_statuses`(`status`, `post_status`, `pick_status`, `pack_status`, `outbound_status`) USING BTREE, - INDEX `idx_100000_history_archive_time`(`archive_time`) USING BTREE -) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '仓库100000发货单历史表' ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_order_delivery_100000_outsourced --- ---------------------------- -DROP TABLE IF EXISTS `wms_order_delivery_100000_outsourced`; -CREATE TABLE `wms_order_delivery_100000_outsourced` ( - `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, - `delivery_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '发货单号', - `pre_delivery_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '预发货单号', - `pre_delivery_order_id` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '预发货单ID', - `order_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '订单类型', - `warehouse_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '仓库编码', - `order_flag` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '订单标记', - `source_platform_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '来源平台编码', - `source_platform_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '来源平台名称', - `source_order_codes` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '来源订单号集合', - `create_at` datetime(0) NULL DEFAULT NULL COMMENT '创建时间', - `delete_at` datetime(0) NULL DEFAULT NULL COMMENT '删除时间', - `updated_at` datetime(0) NULL DEFAULT NULL COMMENT '更新时间', - `place_order_time` datetime(0) NULL DEFAULT NULL COMMENT '店铺创建订单时间', - `pay_time` datetime(0) NULL DEFAULT NULL COMMENT '支付时间', - `pay_no` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '支付单号', - `service_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '集包服务编码', - `operator_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT 'ERP审核人', - `operate_time` datetime(0) NULL DEFAULT NULL COMMENT 'ERP审核时间', - `delivery_time` datetime(0) NULL DEFAULT NULL COMMENT '发货时间', - `shop_nick` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '店铺名称', - `seller_nick` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '卖家名称', - `buyer_nick` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '买家名称', - `total_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '订单总金额', - `item_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '商品总金额', - `discount_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '订单折扣金额', - `freight` decimal(18, 2) NULL DEFAULT NULL COMMENT '快递费用', - `ar_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '应收金额', - `got_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '已收金额', - `service_fee` decimal(18, 2) NULL DEFAULT NULL COMMENT 'COD服务费', - `logistics_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '物流公司编码', - `logistics_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '物流公司名称', - `express_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '面单号前置', - `logistics_area_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '快递区域编码, 大头笔信息', - `delivery_type` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '发货服务类型', - `weight_type` int(11) NOT NULL DEFAULT 0 COMMENT '重量类型:0常规、1轻货、2重货、3冷链', - `is_urgency` enum('Y','N') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'N' COMMENT '是否紧急', - `invoice_flag` enum('Y','N') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'N' COMMENT '是否需要发票', - `status` enum('pedding','created','cancel','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'created' COMMENT '订单状态', - `name` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人姓名', - `zip_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '收件人邮编', - `tel` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人电话', - `mobile` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人移动电话', - `email` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人邮箱', - `country_code` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '国家编码', - `province` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '省份', - `city` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '城市', - `area` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '区', - `town` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '镇', - `detail_address` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '详细地址', - `id_type` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '证件类型', - `id_number` int(11) NULL DEFAULT NULL COMMENT '证件号码', - `oaid` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT 'OAID', - `sync_status` enum('padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'padding' COMMENT '同步状态', - `store_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '货主ID', - `warehouse_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '仓库ID', - `from_key` int(11) NULL DEFAULT NULL COMMENT '来源键', - `items` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '商品JSON字符串', - `items_count` smallint(5) UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品种类数', - `items_total` int(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品总数', - `items_weight` decimal(10, 2) NOT NULL DEFAULT 0.00 COMMENT '总重量(kg)', - `items_hash` char(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT 'MD5哈希值(32位)', - `items_crc` int(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'CRC32校验码', - `wave_id` bigint(20) NOT NULL DEFAULT 0 COMMENT '波次ID,0表示未分配', - `post_status` enum('padding','fin','timeout','error','none') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '分配快递号状态机', - `storage_status` enum('padding','fin','error','none') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '分配储位状态机', - `pick_status` enum('padding','fin','error','none') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '拣货状态机', - `pack_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '打包状态机', - `inspection_status` enum('none','padding','running','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '检验状态机', - `step` int(10) NOT NULL DEFAULT 0 COMMENT '订单步骤:0未审核,1已审核,2处理中,3驳回/异常,4配送中,5已完成,9已关闭', - `print_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '打印状态机', - `claim_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '领取状态机', - `outbound_status` enum('none','padding','fin','timeout','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '出库状态机', - `lock_status` enum('none','warehouse','store') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '锁定状态机', - `intercept_status` enum('none','requesting','requested','intercepting','intercepted_in_transit','intercepted_at_warehouse','returning','returned','delivered_by_mistake','timeout','cancelled','failed','exception') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '拦截状态机', - `sys_platform_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统平台编码', - `sys_platform_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统平台名称', - `sys_logistics_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统物流公司编码', - `sys_logistics_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统物流公司名称', - `sended_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '发货状态机', - `create_channel` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT 'MANUAL' COMMENT '创建来源渠道', - `basket_number` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '筐号', - `wave_no` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '波次号,空字符串表示未分配', - PRIMARY KEY (`id`) USING BTREE, - UNIQUE INDEX `idx_100000_outsourced_delivery_code`(`delivery_order_code`, `store_id`, `warehouse_id`) USING BTREE, - INDEX `idx_100000_outsourced_store_id`(`store_id`) USING BTREE, - INDEX `idx_100000_outsourced_warehouse_id`(`warehouse_id`) USING BTREE, - INDEX `idx_100000_outsourced_items`(`items`(50)) USING BTREE, - INDEX `idx_100000_outsourced_items_hash`(`items_hash`) USING BTREE, - INDEX `idx_100000_outsourced_hash_crc`(`items_hash`, `items_crc`, `warehouse_id`) USING BTREE, - INDEX `idx_100000_outsourced_wave`(`status`, `wave_id`) USING BTREE, - INDEX `idx_100000_outsourced_statuses`(`status`, `post_status`, `pick_status`, `pack_status`, `outbound_status`) USING BTREE -) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '仓库100000发货单外仓表' ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_order_delivery_1000028 --- ---------------------------- -DROP TABLE IF EXISTS `wms_order_delivery_1000028`; -CREATE TABLE `wms_order_delivery_1000028` ( - `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, - `delivery_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '发货单号', - `pre_delivery_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '预发货单号', - `pre_delivery_order_id` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '预发货单ID', - `order_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '订单类型', - `warehouse_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '仓库编码', - `order_flag` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '订单标记', - `source_platform_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '来源平台编码', - `source_platform_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '来源平台名称', - `source_order_codes` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '来源订单号集合', - `sys_platform_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统平台编码', - `sys_platform_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统平台名称', - `create_at` datetime(0) NULL DEFAULT NULL COMMENT '创建时间', - `delete_at` datetime(0) NULL DEFAULT NULL COMMENT '删除时间', - `updated_at` datetime(0) NULL DEFAULT NULL COMMENT '更新时间', - `place_order_time` datetime(0) NULL DEFAULT NULL COMMENT '店铺创建订单时间', - `pay_time` datetime(0) NULL DEFAULT NULL COMMENT '支付时间', - `pay_no` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '支付单号', - `service_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '集包服务编码', - `operator_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT 'ERP审核人', - `operate_time` datetime(0) NULL DEFAULT NULL COMMENT 'ERP审核时间', - `delivery_time` datetime(0) NULL DEFAULT NULL COMMENT '发货时间', - `shop_nick` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '店铺名称', - `seller_nick` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '卖家名称', - `buyer_nick` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '买家名称', - `total_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '订单总金额', - `item_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '商品总金额', - `discount_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '订单折扣金额', - `freight` decimal(18, 2) NULL DEFAULT NULL COMMENT '快递费用', - `ar_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '应收金额', - `got_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '已收金额', - `service_fee` decimal(18, 2) NULL DEFAULT NULL COMMENT 'COD服务费', - `logistics_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '物流公司编码', - `logistics_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '物流公司名称', - `sys_logistics_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统物流公司编码', - `sys_logistics_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统物流公司名称', - `express_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '面单号前置', - `logistics_area_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '快递区域编码, 大头笔信息', - `delivery_type` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '发货服务类型', - `weight_type` int(11) NOT NULL DEFAULT 0 COMMENT '重量类型:0常规、1轻货、2重货、3冷链', - `is_urgency` enum('Y','N') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'N' COMMENT '是否紧急', - `invoice_flag` enum('Y','N') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'N' COMMENT '是否需要发票', - `status` enum('pedding','created','cancel','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'created' COMMENT '订单状态', - `name` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人姓名', - `zip_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '收件人邮编', - `tel` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人电话', - `mobile` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人移动电话', - `email` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人邮箱', - `country_code` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '国家编码', - `province` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '省份', - `city` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '城市', - `area` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '区', - `town` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '镇', - `detail_address` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '详细地址', - `id_type` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '证件类型', - `id_number` int(11) NULL DEFAULT NULL COMMENT '证件号码', - `oaid` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT 'OAID', - `sync_status` enum('padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'padding' COMMENT '同步状态', - `store_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '货主ID', - `warehouse_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '仓库ID', - `from_key` int(11) NULL DEFAULT NULL COMMENT '来源键', - `items` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '商品JSON字符串', - `items_count` smallint(5) UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品种类数', - `items_total` int(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品总数', - `items_weight` decimal(10, 2) NOT NULL DEFAULT 0.00 COMMENT '总重量(kg)', - `items_hash` char(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT 'MD5哈希值(32位)', - `items_crc` int(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'CRC32校验码', - `wave_id` bigint(20) NOT NULL DEFAULT 0 COMMENT '波次ID,0表示未分配', - `post_status` enum('padding','fin','timeout','error','none') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '分配快递号状态机', - `storage_status` enum('padding','fin','error','none') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '分配储位状态机', - `pick_status` enum('padding','fin','error','none') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '拣货状态机', - `pack_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '打包状态机', - `inspection_status` enum('none','padding','running','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '检验状态机', - `step` int(10) NOT NULL DEFAULT 0 COMMENT '订单步骤:0未审核,1已审核,2处理中,3驳回/异常,4配送中,5已完成,9已关闭', - `print_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '打印状态机', - `claim_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '领取状态机', - `outbound_status` enum('none','padding','fin','timeout','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '出库状态机', - `lock_status` enum('none','warehouse','store') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '锁定状态机', - `intercept_status` enum('none','requesting','requested','intercepting','intercepted_in_transit','intercepted_at_warehouse','returning','returned','delivered_by_mistake','timeout','cancelled','failed','exception') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '拦截状态机', - `sended_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '发货状态机', - `create_channel` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT 'MANUAL' COMMENT '创建来源渠道', - `basket_number` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '筐号', - `wave_no` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '波次号,空字符串表示未分配', - PRIMARY KEY (`id`) USING BTREE, - UNIQUE INDEX `idx_1000028_current_delivery_code`(`delivery_order_code`, `store_id`, `warehouse_id`) USING BTREE, - INDEX `idx_1000028_current_store_id`(`store_id`) USING BTREE, - INDEX `idx_1000028_current_warehouse_id`(`warehouse_id`) USING BTREE, - INDEX `idx_1000028_current_items`(`items`(50)) USING BTREE, - INDEX `idx_1000028_current_items_hash`(`items_hash`) USING BTREE, - INDEX `idx_1000028_current_hash_crc`(`items_hash`, `items_crc`, `warehouse_id`) USING BTREE, - INDEX `idx_1000028_current_wave`(`status`, `wave_id`) USING BTREE, - INDEX `idx_1000028_current_statuses`(`status`, `post_status`, `pick_status`, `pack_status`, `outbound_status`) USING BTREE -) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '仓库1000028发货单常用表' ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_order_delivery_1000028_dispatch --- ---------------------------- -DROP TABLE IF EXISTS `wms_order_delivery_1000028_dispatch`; -CREATE TABLE `wms_order_delivery_1000028_dispatch` ( - `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, - `delivery_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '发货单号', - `pre_delivery_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '预发货单号', - `pre_delivery_order_id` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '预发货单ID', - `order_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '订单类型', - `warehouse_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '仓库编码', - `order_flag` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '订单标记', - `source_platform_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '来源平台编码', - `source_platform_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '来源平台名称', - `source_order_codes` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '来源订单号集合', - `sys_platform_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统平台编码', - `sys_platform_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统平台名称', - `create_at` datetime(0) NULL DEFAULT NULL COMMENT '创建时间', - `delete_at` datetime(0) NULL DEFAULT NULL COMMENT '删除时间', - `updated_at` datetime(0) NULL DEFAULT NULL COMMENT '更新时间', - `place_order_time` datetime(0) NULL DEFAULT NULL COMMENT '店铺创建订单时间', - `pay_time` datetime(0) NULL DEFAULT NULL COMMENT '支付时间', - `pay_no` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '支付单号', - `service_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '集包服务编码', - `operator_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT 'ERP审核人', - `operate_time` datetime(0) NULL DEFAULT NULL COMMENT 'ERP审核时间', - `delivery_time` datetime(0) NULL DEFAULT NULL COMMENT '发货时间', - `shop_nick` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '店铺名称', - `seller_nick` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '卖家名称', - `buyer_nick` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '买家名称', - `total_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '订单总金额', - `item_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '商品总金额', - `discount_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '订单折扣金额', - `freight` decimal(18, 2) NULL DEFAULT NULL COMMENT '快递费用', - `ar_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '应收金额', - `got_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '已收金额', - `service_fee` decimal(18, 2) NULL DEFAULT NULL COMMENT 'COD服务费', - `logistics_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '物流公司编码', - `logistics_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '物流公司名称', - `sys_logistics_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统物流公司编码', - `sys_logistics_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统物流公司名称', - `express_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '面单号前置', - `logistics_area_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '快递区域编码, 大头笔信息', - `delivery_type` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '发货服务类型', - `weight_type` int(11) NOT NULL DEFAULT 0 COMMENT '重量类型:0常规、1轻货、2重货、3冷链', - `is_urgency` enum('Y','N') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'N' COMMENT '是否紧急', - `invoice_flag` enum('Y','N') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'N' COMMENT '是否需要发票', - `status` enum('pedding','created','cancel','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'created' COMMENT '订单状态', - `name` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人姓名', - `zip_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '收件人邮编', - `tel` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人电话', - `mobile` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人移动电话', - `email` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人邮箱', - `country_code` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '国家编码', - `province` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '省份', - `city` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '城市', - `area` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '区', - `town` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '镇', - `detail_address` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '详细地址', - `id_type` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '证件类型', - `id_number` int(11) NULL DEFAULT NULL COMMENT '证件号码', - `oaid` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT 'OAID', - `sync_status` enum('padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'padding' COMMENT '同步状态', - `store_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '货主ID', - `warehouse_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '仓库ID', - `from_key` int(11) NULL DEFAULT NULL COMMENT '来源键', - `items` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '商品JSON字符串', - `items_count` smallint(5) UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品种类数', - `items_total` int(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品总数', - `items_weight` decimal(10, 2) NOT NULL DEFAULT 0.00 COMMENT '总重量(kg)', - `items_hash` char(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT 'MD5哈希值(32位)', - `items_crc` int(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'CRC32校验码', - `wave_id` bigint(20) NOT NULL DEFAULT 0 COMMENT '波次ID,0表示未分配', - `post_status` enum('padding','fin','timeout','error','none') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '分配快递号状态机', - `storage_status` enum('padding','fin','error','none') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '分配储位状态机', - `pick_status` enum('padding','fin','error','none') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '拣货状态机', - `pack_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '打包状态机', - `inspection_status` enum('none','padding','running','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '检验状态机', - `step` int(10) NOT NULL DEFAULT 0 COMMENT '订单步骤:0未审核,1已审核,2处理中,3驳回/异常,4配送中,5已完成,9已关闭', - `print_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '打印状态机', - `claim_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '领取状态机', - `outbound_status` enum('none','padding','fin','timeout','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '出库状态机', - `lock_status` enum('none','warehouse','store') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '锁定状态机', - `intercept_status` enum('none','requesting','requested','intercepting','intercepted_in_transit','intercepted_at_warehouse','returning','returned','delivered_by_mistake','timeout','cancelled','failed','exception') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '拦截状态机', - `dispatch_lane` enum('m4','m5') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT 'm4' COMMENT '配送工作台子域(M4正常/M5异常)', - `sended_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '发货状态机', - `create_channel` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT 'MANUAL' COMMENT '创建来源渠道', - `basket_number` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '筐号', - `wave_no` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '波次号,空字符串表示未分配', - PRIMARY KEY (`id`) USING BTREE, - UNIQUE INDEX `idx_1000028_current_delivery_code`(`delivery_order_code`, `store_id`, `warehouse_id`) USING BTREE, - INDEX `idx_1000028_current_store_id`(`store_id`) USING BTREE, - INDEX `idx_1000028_current_warehouse_id`(`warehouse_id`) USING BTREE, - INDEX `idx_dispatch_1000028_dispatch_lane`(`dispatch_lane`, `status`) USING BTREE, - INDEX `idx_1000028_current_items`(`items`(50)) USING BTREE, - INDEX `idx_1000028_current_items_hash`(`items_hash`) USING BTREE, - INDEX `idx_1000028_current_hash_crc`(`items_hash`, `items_crc`, `warehouse_id`) USING BTREE, - INDEX `idx_1000028_current_wave`(`status`, `wave_id`) USING BTREE, - INDEX `idx_1000028_current_statuses`(`status`, `post_status`, `pick_status`, `pack_status`, `outbound_status`) USING BTREE -) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '仓库1000028发货单配送域(M4/M5)影子表' ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_order_delivery_1000028_history --- ---------------------------- -DROP TABLE IF EXISTS `wms_order_delivery_1000028_history`; -CREATE TABLE `wms_order_delivery_1000028_history` ( - `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, - `delivery_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '发货单号', - `pre_delivery_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '预发货单号', - `pre_delivery_order_id` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '预发货单ID', - `order_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '订单类型', - `warehouse_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '仓库编码', - `order_flag` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '订单标记', - `source_platform_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '来源平台编码', - `source_platform_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '来源平台名称', - `source_order_codes` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '来源订单号集合', - `sys_platform_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统平台编码', - `sys_platform_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统平台名称', - `create_at` datetime(0) NULL DEFAULT NULL COMMENT '创建时间', - `delete_at` datetime(0) NULL DEFAULT NULL COMMENT '删除时间', - `updated_at` datetime(0) NULL DEFAULT NULL COMMENT '更新时间', - `place_order_time` datetime(0) NULL DEFAULT NULL COMMENT '店铺创建订单时间', - `pay_time` datetime(0) NULL DEFAULT NULL COMMENT '支付时间', - `pay_no` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '支付单号', - `service_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '集包服务编码', - `operator_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT 'ERP审核人', - `operate_time` datetime(0) NULL DEFAULT NULL COMMENT 'ERP审核时间', - `delivery_time` datetime(0) NULL DEFAULT NULL COMMENT '发货时间', - `shop_nick` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '店铺名称', - `seller_nick` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '卖家名称', - `buyer_nick` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '买家名称', - `total_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '订单总金额', - `item_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '商品总金额', - `discount_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '订单折扣金额', - `freight` decimal(18, 2) NULL DEFAULT NULL COMMENT '快递费用', - `ar_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '应收金额', - `got_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '已收金额', - `service_fee` decimal(18, 2) NULL DEFAULT NULL COMMENT 'COD服务费', - `logistics_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '物流公司编码', - `logistics_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '物流公司名称', - `sys_logistics_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统物流公司编码', - `sys_logistics_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统物流公司名称', - `express_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '面单号前置', - `logistics_area_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '快递区域编码, 大头笔信息', - `delivery_type` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '发货服务类型', - `weight_type` int(11) NOT NULL DEFAULT 0 COMMENT '重量类型:0常规、1轻货、2重货、3冷链', - `is_urgency` enum('Y','N') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'N' COMMENT '是否紧急', - `invoice_flag` enum('Y','N') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'N' COMMENT '是否需要发票', - `status` enum('pedding','created','cancel','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'created' COMMENT '订单状态', - `name` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人姓名', - `zip_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '收件人邮编', - `tel` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人电话', - `mobile` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人移动电话', - `email` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人邮箱', - `country_code` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '国家编码', - `province` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '省份', - `city` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '城市', - `area` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '区', - `town` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '镇', - `detail_address` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '详细地址', - `id_type` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '证件类型', - `id_number` int(11) NULL DEFAULT NULL COMMENT '证件号码', - `oaid` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT 'OAID', - `sync_status` enum('padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'padding' COMMENT '同步状态', - `store_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '货主ID', - `warehouse_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '仓库ID', - `from_key` int(11) NULL DEFAULT NULL COMMENT '来源键', - `items` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '商品JSON字符串', - `items_count` smallint(5) UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品种类数', - `items_total` int(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品总数', - `items_weight` decimal(10, 2) NOT NULL DEFAULT 0.00 COMMENT '总重量(kg)', - `items_hash` char(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT 'MD5哈希值(32位)', - `items_crc` int(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'CRC32校验码', - `wave_id` bigint(20) NOT NULL DEFAULT 0 COMMENT '波次ID,0表示未分配', - `post_status` enum('padding','fin','timeout','error','none') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '分配快递号状态机', - `storage_status` enum('padding','fin','error','none') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '分配储位状态机', - `pick_status` enum('padding','fin','error','none') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '拣货状态机', - `pack_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '打包状态机', - `inspection_status` enum('none','padding','running','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '检验状态机', - `step` int(10) NOT NULL DEFAULT 0 COMMENT '订单步骤:0未审核,1已审核,2处理中,3驳回/异常,4配送中,5已完成,9已关闭', - `print_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '打印状态机', - `claim_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '领取状态机', - `outbound_status` enum('none','padding','fin','timeout','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '出库状态机', - `lock_status` enum('none','warehouse','store') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '锁定状态机', - `intercept_status` enum('none','requesting','requested','intercepting','intercepted_in_transit','intercepted_at_warehouse','returning','returned','delivered_by_mistake','timeout','cancelled','failed','exception') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '拦截状态机', - `archive_time` datetime(0) NULL DEFAULT NULL COMMENT '归档时间', - `create_channel` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT 'MANUAL' COMMENT '创建来源渠道', - `sended_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '发货状态机', - `basket_number` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '筐号', - PRIMARY KEY (`id`) USING BTREE, - UNIQUE INDEX `idx_1000028_history_delivery_code`(`delivery_order_code`, `store_id`, `warehouse_id`) USING BTREE, - INDEX `idx_1000028_history_store_id`(`store_id`) USING BTREE, - INDEX `idx_1000028_history_warehouse_id`(`warehouse_id`) USING BTREE, - INDEX `idx_1000028_history_items`(`items`(50)) USING BTREE, - INDEX `idx_1000028_history_items_hash`(`items_hash`) USING BTREE, - INDEX `idx_1000028_history_hash_crc`(`items_hash`, `items_crc`, `warehouse_id`) USING BTREE, - INDEX `idx_1000028_history_wave`(`status`, `wave_id`) USING BTREE, - INDEX `idx_1000028_history_statuses`(`status`, `post_status`, `pick_status`, `pack_status`, `outbound_status`) USING BTREE, - INDEX `idx_1000028_history_archive_time`(`archive_time`) USING BTREE -) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '仓库1000028发货单历史表' ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_order_delivery_1000028_outsourced --- ---------------------------- -DROP TABLE IF EXISTS `wms_order_delivery_1000028_outsourced`; -CREATE TABLE `wms_order_delivery_1000028_outsourced` ( - `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, - `delivery_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '发货单号', - `pre_delivery_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '预发货单号', - `pre_delivery_order_id` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '预发货单ID', - `order_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '订单类型', - `warehouse_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '仓库编码', - `order_flag` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '订单标记', - `source_platform_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '来源平台编码', - `source_platform_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '来源平台名称', - `sys_platform_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统平台编码', - `sys_platform_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统平台名称', - `create_at` datetime(0) NULL DEFAULT NULL COMMENT '创建时间', - `delete_at` datetime(0) NULL DEFAULT NULL COMMENT '删除时间', - `updated_at` datetime(0) NULL DEFAULT NULL COMMENT '更新时间', - `place_order_time` datetime(0) NULL DEFAULT NULL COMMENT '店铺创建订单时间', - `pay_time` datetime(0) NULL DEFAULT NULL COMMENT '支付时间', - `pay_no` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '支付单号', - `service_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '集包服务编码', - `operator_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT 'ERP审核人', - `operate_time` datetime(0) NULL DEFAULT NULL COMMENT 'ERP审核时间', - `delivery_time` datetime(0) NULL DEFAULT NULL COMMENT '发货时间', - `shop_nick` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '店铺名称', - `seller_nick` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '卖家名称', - `buyer_nick` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '买家名称', - `total_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '订单总金额', - `item_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '商品总金额', - `discount_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '订单折扣金额', - `freight` decimal(18, 2) NULL DEFAULT NULL COMMENT '快递费用', - `ar_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '应收金额', - `got_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '已收金额', - `service_fee` decimal(18, 2) NULL DEFAULT NULL COMMENT 'COD服务费', - `logistics_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '物流公司编码', - `logistics_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '物流公司名称', - `sys_logistics_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统物流公司编码', - `sys_logistics_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统物流公司名称', - `express_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '面单号前置', - `logistics_area_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '快递区域编码, 大头笔信息', - `delivery_type` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '发货服务类型', - `is_urgency` enum('Y','N') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'N' COMMENT '是否紧急', - `invoice_flag` enum('Y','N') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'N' COMMENT '是否需要发票', - `status` enum('pedding','created','cancel','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'created' COMMENT '订单状态', - `name` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人姓名', - `zip_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '收件人邮编', - `tel` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人电话', - `mobile` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人移动电话', - `email` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人邮箱', - `country_code` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '国家编码', - `province` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '省份', - `city` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '城市', - `area` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '区', - `town` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '镇', - `detail_address` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '详细地址', - `id_type` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '证件类型', - `id_number` int(11) NULL DEFAULT NULL COMMENT '证件号码', - `oaid` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT 'OAID', - `sync_status` enum('padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'padding' COMMENT '同步状态', - `store_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '货主ID', - `warehouse_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '仓库ID', - `from_key` int(11) NULL DEFAULT NULL COMMENT '来源键', - `items` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '商品JSON字符串', - `items_count` smallint(5) UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品种类数', - `items_total` int(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品总数', - `items_weight` decimal(10, 2) NOT NULL DEFAULT 0.00 COMMENT '总重量(kg)', - `items_hash` char(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT 'MD5哈希值(32位)', - `items_crc` int(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'CRC32校验码', - `wave_id` bigint(20) NOT NULL DEFAULT 0 COMMENT '波次ID,0表示未分配', - `post_status` enum('padding','fin','timeout','error','none') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '分配快递号状态机', - `storage_status` enum('padding','fin','error','none') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '分配储位状态机', - `pick_status` enum('padding','fin','error','none') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '拣货状态机', - `pack_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '打包状态机', - `inspection_status` enum('none','padding','running','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '检验状态机', - `step` int(10) NOT NULL DEFAULT 0 COMMENT '订单步骤:0未审核,1已审核,2处理中,3驳回/异常,4配送中,5已完成,9已关闭', - `print_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '打印状态机', - `claim_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '领取状态机', - `outbound_status` enum('none','padding','fin','timeout','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '出库状态机', - `lock_status` enum('none','warehouse','store') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '锁定状态机', - `intercept_status` enum('none','requesting','requested','intercepting','intercepted_in_transit','intercepted_at_warehouse','returning','returned','delivered_by_mistake','timeout','cancelled','failed','exception') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '拦截状态机', - `source_order_codes` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '来源订单号集合', - `weight_type` int(11) NOT NULL DEFAULT 0 COMMENT '重量类型:0常规、1轻货、2重货、3冷链', - `sended_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '发货状态机', - `create_channel` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT 'MANUAL' COMMENT '创建来源渠道', - `basket_number` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '筐号', - PRIMARY KEY (`id`) USING BTREE, - UNIQUE INDEX `idx_1000028_outsourced_delivery_code`(`delivery_order_code`, `store_id`, `warehouse_id`) USING BTREE, - INDEX `idx_1000028_outsourced_store_id`(`store_id`) USING BTREE, - INDEX `idx_1000028_outsourced_warehouse_id`(`warehouse_id`) USING BTREE, - INDEX `idx_1000028_outsourced_items`(`items`(50)) USING BTREE, - INDEX `idx_1000028_outsourced_items_hash`(`items_hash`) USING BTREE, - INDEX `idx_1000028_outsourced_hash_crc`(`items_hash`, `items_crc`, `warehouse_id`) USING BTREE, - INDEX `idx_1000028_outsourced_wave`(`status`, `wave_id`) USING BTREE, - INDEX `idx_1000028_outsourced_statuses`(`status`, `post_status`, `pick_status`, `pack_status`, `outbound_status`) USING BTREE -) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '仓库1000028发货单外仓表' ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_order_express --- ---------------------------- -DROP TABLE IF EXISTS `wms_order_express`; -CREATE TABLE `wms_order_express` ( - `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, - `waybill_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '运单号', - `order_id` bigint(20) NULL DEFAULT NULL COMMENT '订单id', - `create_at` datetime(0) NULL DEFAULT NULL COMMENT '创建时间', - `delete_at` datetime(0) NULL DEFAULT NULL COMMENT '软删除时间', - `is_galaxy_receive` enum('Y','N') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '是否已揽收', - `is_back` enum('Y','N') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '是否退回收到', - `is_intercept` enum('Y','N') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '是否已拦截', - `logistics_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '快递编码', - `logistics_interface_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '使用的快递接口id', - `logistics_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '快递名称', - `logistics_interface_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '使用的快递接口名称', - `platform_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '平台编码', - `business_key` int(3) NULL DEFAULT NULL COMMENT '业务编码', - `status` bigint(20) UNSIGNED NULL DEFAULT 0 COMMENT '状态0-已冻结新建,1-已完成创建,大于1为回收时间戳', - `retry_count` tinyint(3) NULL DEFAULT NULL COMMENT '重试次数', - `printinfo` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL, - `signature` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL, - `encryptprintinfo` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL, - `warehouse_id` bigint(20) UNSIGNED NULL DEFAULT NULL, - `encryptedtoken` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL, - PRIMARY KEY (`id`) USING BTREE, - UNIQUE INDEX `order_id`(`order_id`, `business_key`, `status`, `warehouse_id`) USING BTREE, - INDEX `waybill_code`(`waybill_code`) USING BTREE, - INDEX `create_at`(`create_at`) USING BTREE, - INDEX `warehouse_id`(`warehouse_id`) USING BTREE, - CONSTRAINT `wms_order_express_ibfk_1` FOREIGN KEY (`warehouse_id`) REFERENCES `wms_store` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT -) ENGINE = InnoDB AUTO_INCREMENT = 156 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_order_express_print_data --- ---------------------------- -DROP TABLE IF EXISTS `wms_order_express_print_data`; -CREATE TABLE `wms_order_express_print_data` ( - `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, - `express_id` bigint(20) UNSIGNED NULL DEFAULT NULL, - `data` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL, - `create_at` datetime(0) NULL DEFAULT NULL, - `delete_at` datetime(0) NULL DEFAULT NULL, - `update_at` datetime(0) NULL DEFAULT NULL, - PRIMARY KEY (`id`) USING BTREE, - INDEX `express_id`(`express_id`) USING BTREE, - CONSTRAINT `wms_order_express_print_data_ibfk_1` FOREIGN KEY (`express_id`) REFERENCES `wms_order_express` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION -) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_order_items --- ---------------------------- -DROP TABLE IF EXISTS `wms_order_items`; -CREATE TABLE `wms_order_items` ( - `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, - `order_id` bigint(20) UNSIGNED NULL DEFAULT NULL, - `actual_price` decimal(18, 2) NOT NULL, - `retail_price` decimal(18, 2) NULL DEFAULT NULL, - `ext_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, - `inventory_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, - `item_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, - `item_id` bigint(20) UNSIGNED NULL DEFAULT NULL, - `item_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, - `order_line_no` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, - `owner_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, - `plan_qty` int(11) NULL DEFAULT NULL, - `source_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, - `sub_source_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, - `extend_props` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL, - PRIMARY KEY (`id`) USING BTREE, - UNIQUE INDEX `order_id`(`order_id`, `item_id`) USING BTREE, - CONSTRAINT `wms_order_items_ibfk_1` FOREIGN KEY (`order_id`) REFERENCES `wms_order_delivery` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION -) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_order_items_100000 --- ---------------------------- -DROP TABLE IF EXISTS `wms_order_items_100000`; -CREATE TABLE `wms_order_items_100000` ( - `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, - `order_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '订单ID', - `actual_price` decimal(18, 2) NOT NULL DEFAULT 0.00 COMMENT '实际价格', - `retail_price` decimal(18, 2) NULL DEFAULT NULL COMMENT '零售价格', - `ext_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '外部编码', - `inventory_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '库存类型', - `item_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '商品编码', - `item_id` bigint(20) NULL DEFAULT NULL COMMENT '商品ID', - `item_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '商品名称', - `order_line_no` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '订单行号', - `owner_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '货主编码', - `plan_qty` int(11) NULL DEFAULT NULL COMMENT '计划数量', - `source_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '源订单编码', - `sub_source_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '子源订单编码', - `extend_props` json NULL COMMENT '扩展属性(JSON格式)', - `stock_id` bigint(20) NULL DEFAULT NULL COMMENT '库存ID', - `created_at` datetime(0) NOT NULL, - `updated_at` datetime(0) NOT NULL, - `item_snapshot` json NULL COMMENT '商品快照', - PRIMARY KEY (`id`) USING BTREE, - INDEX `idx_100000_order_id`(`order_id`) USING BTREE, - INDEX `idx_100000_item_id`(`item_id`) USING BTREE, - INDEX `idx_100000_item_code`(`item_code`) USING BTREE, - INDEX `idx_100000_source_order_code`(`source_order_code`) USING BTREE, - INDEX `idx_100000_stock_id`(`stock_id`) USING BTREE, - INDEX `idx_100000_owner_code`(`owner_code`) USING BTREE, - INDEX `idx_100000_order_item`(`order_id`, `item_id`) USING BTREE, - INDEX `idx_100000_created_at`(`created_at`) USING BTREE -) ENGINE = InnoDB AUTO_INCREMENT = 106818 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT = '仓库100000订单商品常用表' ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_order_items_100000_dispatch --- ---------------------------- -DROP TABLE IF EXISTS `wms_order_items_100000_dispatch`; -CREATE TABLE `wms_order_items_100000_dispatch` ( - `id` bigint(20) UNSIGNED NOT NULL, - `order_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '订单ID', - `actual_price` decimal(18, 2) NOT NULL DEFAULT 0.00 COMMENT '实际价格', - `retail_price` decimal(18, 2) NULL DEFAULT NULL COMMENT '零售价格', - `ext_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '外部编码', - `inventory_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '库存类型', - `item_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '商品编码', - `item_id` bigint(20) NULL DEFAULT NULL COMMENT '商品ID', - `item_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '商品名称', - `order_line_no` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '订单行号', - `owner_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '货主编码', - `plan_qty` int(11) NULL DEFAULT NULL COMMENT '计划数量', - `source_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '源订单编码', - `sub_source_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '子源订单编码', - `extend_props` json NULL COMMENT '扩展属性(JSON格式)', - `stock_id` bigint(20) NULL DEFAULT NULL COMMENT '库存ID', - `created_at` datetime(0) NOT NULL, - `updated_at` datetime(0) NOT NULL, - `item_snapshot` json NULL COMMENT '商品快照', - PRIMARY KEY (`id`) USING BTREE, - INDEX `idx_100000_order_id`(`order_id`) USING BTREE, - INDEX `idx_100000_item_id`(`item_id`) USING BTREE, - INDEX `idx_100000_item_code`(`item_code`) USING BTREE, - INDEX `idx_100000_source_order_code`(`source_order_code`) USING BTREE, - INDEX `idx_100000_stock_id`(`stock_id`) USING BTREE, - INDEX `idx_100000_owner_code`(`owner_code`) USING BTREE, - INDEX `idx_100000_order_item`(`order_id`, `item_id`) USING BTREE, - INDEX `idx_100000_created_at`(`created_at`) USING BTREE -) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '仓库100000订单商品配送表' ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_order_items_100000_history --- ---------------------------- -DROP TABLE IF EXISTS `wms_order_items_100000_history`; -CREATE TABLE `wms_order_items_100000_history` ( - `id` bigint(20) UNSIGNED NOT NULL, - `order_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '订单ID', - `actual_price` decimal(18, 2) NOT NULL DEFAULT 0.00 COMMENT '实际价格', - `retail_price` decimal(18, 2) NULL DEFAULT NULL COMMENT '零售价格', - `ext_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '外部编码', - `inventory_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '库存类型', - `item_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '商品编码', - `item_id` bigint(20) NULL DEFAULT NULL COMMENT '商品ID', - `item_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '商品名称', - `order_line_no` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '订单行号', - `owner_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '货主编码', - `plan_qty` int(11) NULL DEFAULT NULL COMMENT '计划数量', - `source_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '源订单编码', - `sub_source_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '子源订单编码', - `extend_props` json NULL COMMENT '扩展属性(JSON格式)', - `stock_id` bigint(20) NULL DEFAULT NULL COMMENT '库存ID', - `created_at` datetime(0) NOT NULL, - `updated_at` datetime(0) NOT NULL, - `archive_time` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '归档时间', - `item_snapshot` json NULL COMMENT '商品快照', - PRIMARY KEY (`id`) USING BTREE, - INDEX `idx_100000_order_id`(`order_id`) USING BTREE, - INDEX `idx_100000_item_id`(`item_id`) USING BTREE, - INDEX `idx_100000_item_code`(`item_code`) USING BTREE, - INDEX `idx_100000_source_order_code`(`source_order_code`) USING BTREE, - INDEX `idx_100000_stock_id`(`stock_id`) USING BTREE, - INDEX `idx_100000_owner_code`(`owner_code`) USING BTREE, - INDEX `idx_100000_order_item`(`order_id`, `item_id`) USING BTREE, - INDEX `idx_100000_created_at`(`created_at`) USING BTREE -) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '仓库100000订单商品历史表' ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_order_items_1000028 --- ---------------------------- -DROP TABLE IF EXISTS `wms_order_items_1000028`; -CREATE TABLE `wms_order_items_1000028` ( - `id` bigint(20) UNSIGNED NOT NULL, - `order_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '订单ID', - `actual_price` decimal(18, 2) NOT NULL DEFAULT 0.00 COMMENT '实际价格', - `retail_price` decimal(18, 2) NULL DEFAULT NULL COMMENT '零售价格', - `ext_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '外部编码', - `inventory_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '库存类型', - `item_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '商品编码', - `item_id` bigint(20) NULL DEFAULT NULL COMMENT '商品ID', - `item_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '商品名称', - `order_line_no` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '订单行号', - `owner_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '货主编码', - `plan_qty` int(11) NULL DEFAULT NULL COMMENT '计划数量', - `source_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '源订单编码', - `sub_source_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '子源订单编码', - `extend_props` json NULL COMMENT '扩展属性(JSON格式)', - `stock_id` bigint(20) NULL DEFAULT NULL COMMENT '库存ID', - `item_snapshot` json NULL COMMENT '商品快照', - `created_at` datetime(0) NOT NULL, - `updated_at` datetime(0) NOT NULL, - PRIMARY KEY (`id`) USING BTREE, - INDEX `idx_1000028_order_id`(`order_id`) USING BTREE, - INDEX `idx_1000028_item_id`(`item_id`) USING BTREE, - INDEX `idx_1000028_item_code`(`item_code`) USING BTREE, - INDEX `idx_1000028_source_order_code`(`source_order_code`) USING BTREE, - INDEX `idx_1000028_stock_id`(`stock_id`) USING BTREE, - INDEX `idx_1000028_owner_code`(`owner_code`) USING BTREE, - INDEX `idx_1000028_order_item`(`order_id`, `item_id`) USING BTREE, - INDEX `idx_1000028_created_at`(`created_at`) USING BTREE -) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '仓库1000028订单商品常用表' ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_permission --- ---------------------------- -DROP TABLE IF EXISTS `wms_permission`; -CREATE TABLE `wms_permission` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `path` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '路由路径', - `component` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '组件路径', - `name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '路由名称', - `redirect` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '重定向路径', - `meta_title` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '页面标题', - `meta_icon` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '图标', - `hidden` tinyint(1) NULL DEFAULT 0 COMMENT '是否隐藏(0:显示,1:隐藏)', - `always_show` tinyint(1) NULL DEFAULT 0 COMMENT '是否始终显示', - `parent_id` int(11) NULL DEFAULT NULL COMMENT '父级ID(根节点为NULL)', - `sort` int(11) NULL DEFAULT 0 COMMENT '排序', - `status` tinyint(1) NULL DEFAULT 1 COMMENT '状态(0:禁用,1:启用)', - `created_at` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP(0), - `update_at` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0), - `type` enum('web_pages','pda_pages','btns','api','miniprogram_pages','block') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'web_pages' COMMENT '设备类型(1:电脑端,2:小程序,3:手持设备,4:管理后台)', - PRIMARY KEY (`id`) USING BTREE, - UNIQUE INDEX `name`(`name`, `type`) USING BTREE, - INDEX `idx_parent_id`(`parent_id`) USING BTREE, - INDEX `idx_status`(`status`) USING BTREE, - CONSTRAINT `fk_wms_permission_parent` FOREIGN KEY (`parent_id`) REFERENCES `wms_permission` (`id`) ON DELETE SET NULL ON UPDATE RESTRICT -) ENGINE = InnoDB AUTO_INCREMENT = 353 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '权限路由表' ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_picking --- ---------------------------- -DROP TABLE IF EXISTS `wms_picking`; -CREATE TABLE `wms_picking` ( - `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键ID', - `order_id` bigint(20) UNSIGNED NOT NULL COMMENT '订单ID', - `order_item_id` bigint(20) UNSIGNED NOT NULL COMMENT '订单明细ID', - `storage_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '库存记录ID', - `space_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '库位ID', - `space_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '库位名称', - `status` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT 'pending' COMMENT '状态', - `created_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', - `updated_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', - `quantity` int(11) NULL DEFAULT NULL, - `deleted_at` datetime(0) NULL DEFAULT NULL, - `warehouse_id` bigint(20) UNSIGNED NULL DEFAULT NULL, - PRIMARY KEY (`id`) USING BTREE, - INDEX `idx_wms_picking_order_id`(`order_id`) USING BTREE, - INDEX `idx_wms_picking_order_item_id`(`order_item_id`) USING BTREE, - INDEX `idx_wms_picking_storage_id`(`storage_id`) USING BTREE, - INDEX `idx_wms_picking_space_id`(`space_id`) USING BTREE, - INDEX `idx_wms_picking_status`(`status`) USING BTREE, - INDEX `idx_wms_picking_order_item_space`(`order_item_id`, `space_id`) USING BTREE, - INDEX `warehouse_id`(`warehouse_id`) USING BTREE, - CONSTRAINT `wms_picking_ibfk_1` FOREIGN KEY (`warehouse_id`) REFERENCES `wms_store` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT -) ENGINE = InnoDB AUTO_INCREMENT = 486 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '订单储位分配表' ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_picking_strategy --- ---------------------------- -DROP TABLE IF EXISTS `wms_picking_strategy`; -CREATE TABLE `wms_picking_strategy` ( - `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '策略ID', - `strategy_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '策略名称', - `warehouse_id` bigint(20) UNSIGNED NOT NULL COMMENT '仓库ID', - `strategy_type` tinyint(4) NOT NULL COMMENT '策略类型:1-散单 2-团购', - `status` tinyint(4) NULL DEFAULT 1 COMMENT '状态:1-启用 0-停用', - `order_min_sku` int(11) NULL DEFAULT 1 COMMENT '订单最小SKU种类数', - `order_max_sku` int(11) NULL DEFAULT 999 COMMENT '订单最大SKU种类数', - `order_min_qty` int(11) NULL DEFAULT 1 COMMENT '订单最小商品总数', - `order_max_qty` int(11) NULL DEFAULT 999 COMMENT '订单最大商品总数', - `min_same_structure` int(11) NULL DEFAULT 1 COMMENT '最小相同结构订单数', - `max_same_structure` int(11) NULL DEFAULT 999 COMMENT '最大相同结构订单数', - `require_same_express` tinyint(1) NULL DEFAULT 0 COMMENT '是否要求相同快递', - `allow_cross_owner` tinyint(1) NULL DEFAULT 1 COMMENT '是否允许跨货主', - `batch_mode` tinyint(4) NOT NULL COMMENT '拣货模式:1-单品单件 2-先拣后分 3-边拣边分 4-边拣边分H型 5-播种墙 6-流利架', - `batch_max_orders` int(11) NULL DEFAULT 20 COMMENT '批次最大订单数', - `batch_max_skus` int(11) NULL DEFAULT 50 COMMENT '批次最大SKU总数', - `group_batch_max_orders` int(11) NULL DEFAULT 1 COMMENT '团购批次最大订单数(相同结构)', - `allowed_owners` json NULL COMMENT '允许的货主ID列表', - `allowed_expresses` json NULL COMMENT '允许的快递编码列表', - `allowed_provinces` json NULL COMMENT '允许的省份列表', - `allowed_platforms` json NULL COMMENT '允许的平台列表', - `description` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL COMMENT '策略描述', - `creator_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '创建人姓名', - `create_time` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP(0), - `update_time` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0), - PRIMARY KEY (`id`) USING BTREE, - INDEX `idx_warehouse_type`(`warehouse_id`, `strategy_type`, `status`) USING BTREE, - INDEX `idx_batch_mode`(`batch_mode`, `strategy_type`) USING BTREE -) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT = '拣货策略配置表' ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_platform --- ---------------------------- -DROP TABLE IF EXISTS `wms_platform`; -CREATE TABLE `wms_platform` ( - `code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, - `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, - `interface_url` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, - `platform_code` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, - `platid` int(11) NULL DEFAULT NULL, - `appkey` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, - `app_secret` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, - `token` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, - `version` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, - `shoptype` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, - `ordersource` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, - PRIMARY KEY (`code`) USING BTREE -) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_platform_print_config --- ---------------------------- -DROP TABLE IF EXISTS `wms_platform_print_config`; -CREATE TABLE `wms_platform_print_config` ( - `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID', - `platform` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '平台名称', - `platform_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '平台代码', - `print_port` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '打印服务端口', - `print_url` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '打印服务URL', - `protocol_type` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'WEBSOCKET' COMMENT '协议类型:WEBSOCKET,HTTP', - `status` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'ACTIVE' COMMENT '状态:ACTIVE-启用,DISABLED-禁用', - `retry_count` int(11) NULL DEFAULT 3 COMMENT '重试次数', - `timeout_seconds` int(11) NULL DEFAULT 30 COMMENT '超时时间(秒)', - `description` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '描述', - `create_time` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', - `update_time` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', - PRIMARY KEY (`id`) USING BTREE, - UNIQUE INDEX `uk_platform`(`platform`) USING BTREE, - INDEX `idx_platform_code`(`platform_code`) USING BTREE -) ENGINE = InnoDB AUTO_INCREMENT = 8 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '平台打印端口配置表' ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_platfrom_setting --- ---------------------------- -DROP TABLE IF EXISTS `wms_platfrom_setting`; -CREATE TABLE `wms_platfrom_setting` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `platform_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, - `code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, - `warehouse_id` bigint(20) UNSIGNED NOT NULL, - `name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '别名', - PRIMARY KEY (`id`) USING BTREE, - UNIQUE INDEX `platform_code`(`platform_code`, `warehouse_id`) USING BTREE, - UNIQUE INDEX `code`(`code`, `warehouse_id`) USING BTREE, - INDEX `warehouse_id`(`warehouse_id`) USING BTREE, - CONSTRAINT `wms_platfrom_setting_ibfk_1` FOREIGN KEY (`platform_code`) REFERENCES `wms_platform` (`code`) ON DELETE RESTRICT ON UPDATE NO ACTION, - CONSTRAINT `wms_platfrom_setting_ibfk_2` FOREIGN KEY (`warehouse_id`) REFERENCES `wms_store` (`id`) ON DELETE RESTRICT ON UPDATE NO ACTION -) ENGINE = InnoDB AUTO_INCREMENT = 5 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_print_computer --- ---------------------------- -DROP TABLE IF EXISTS `wms_print_computer`; -CREATE TABLE `wms_print_computer` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `warehouse_id` bigint(20) UNSIGNED NULL DEFAULT NULL, - `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, - `status` int(1) NULL DEFAULT NULL, - PRIMARY KEY (`id`) USING BTREE -) ENGINE = InnoDB AUTO_INCREMENT = 5 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_print_items --- ---------------------------- -DROP TABLE IF EXISTS `wms_print_items`; -CREATE TABLE `wms_print_items` ( - `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键ID', - `business_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '业务类型', - `platform` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '平台', - `field_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '字段名(显示名称)', - `field_code` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '字段代码(英文标识)', - `field_type` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '字段类型', - `is_table` tinyint(1) NULL DEFAULT 0 COMMENT '是否渲染为表格:0-否,1-是', - `table_config` json NULL COMMENT '表格配置', - `group_field` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '分组字段', - `group_label` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '分组标题', - `group_sort` int(11) NULL DEFAULT 0 COMMENT '分组排序', - `required` tinyint(1) NULL DEFAULT 0 COMMENT '是否必填:0-否,1-是', - `default_value` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '默认值', - `sort_order` int(11) NULL DEFAULT 0 COMMENT '排序序号', - `regex_pattern` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '正则验证规则', - `max_length` int(11) NULL DEFAULT NULL COMMENT '最大长度', - `min_length` int(11) NULL DEFAULT NULL COMMENT '最小长度', - `options` json NULL COMMENT '选项(用于下拉框等)', - `description` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '字段描述', - `status` tinyint(1) NULL DEFAULT 1 COMMENT '状态:0-禁用,1-启用', - `created_by` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '创建人', - `updated_by` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '更新人', - `created_at` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', - `updated_at` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', - PRIMARY KEY (`id`) USING BTREE, - UNIQUE INDEX `uk_business_platform_field`(`business_type`, `platform`, `field_code`) USING BTREE, - INDEX `idx_business_type`(`business_type`) USING BTREE, - INDEX `idx_platform`(`platform`) USING BTREE, - INDEX `idx_status`(`status`) USING BTREE -) ENGINE = InnoDB AUTO_INCREMENT = 144 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '打印项配置表' ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_print_log --- ---------------------------- -DROP TABLE IF EXISTS `wms_print_log`; -CREATE TABLE `wms_print_log` ( - `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID', - `print_record_id` bigint(20) NOT NULL COMMENT '打印记录ID', - `log_type` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '日志类型:CONNECT-连接,PRINT-打印,RETRY-重试,ERROR-错误,SUCCESS-成功', - `log_level` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'INFO' COMMENT '日志级别:INFO,WARN,ERROR', - `log_content` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '日志内容', - `request_data` json NULL COMMENT '请求数据', - `response_data` json NULL COMMENT '响应数据', - `websocket_status` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT 'WebSocket状态', - `error_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '错误代码', - `ip_address` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT 'IP地址', - `user_agent` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '用户代理', - `create_time` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', - PRIMARY KEY (`id`) USING BTREE, - INDEX `idx_print_record`(`print_record_id`) USING BTREE, - INDEX `idx_log_type`(`log_type`) USING BTREE, - INDEX `idx_create_time`(`create_time`) USING BTREE, - INDEX `idx_error_code`(`error_code`) USING BTREE -) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '打印日志表' ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_print_record --- ---------------------------- -DROP TABLE IF EXISTS `wms_print_record`; -CREATE TABLE `wms_print_record` ( - `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键ID', - `warehouse_id` bigint(20) UNSIGNED NOT NULL COMMENT '仓库ID', - `computer_id` bigint(20) UNSIGNED NOT NULL COMMENT '电脑ID', - `printer` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '打印机名称/标识', - `type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '打印类型', - `data` json NULL COMMENT '打印数据(JSON格式)', - `status` enum('pending','sent','success','failed') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT 'pending' COMMENT '打印状态:pending-待发送,sent-已发送,success-打印成功,failed-打印失败', - `error_message` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '错误信息', - `sent_time` datetime(0) NULL DEFAULT NULL COMMENT '发送时间', - `print_time` datetime(0) NULL DEFAULT NULL COMMENT '打印完成时间', - `created_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', - `updated_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', - `logs` json NULL, - PRIMARY KEY (`id`) USING BTREE, - INDEX `idx_warehouse_id`(`warehouse_id`) USING BTREE, - INDEX `idx_computer_id`(`computer_id`) USING BTREE, - INDEX `idx_status`(`status`) USING BTREE, - INDEX `idx_created_at`(`created_at`) USING BTREE, - INDEX `idx_sent_time`(`sent_time`) USING BTREE -) ENGINE = InnoDB AUTO_INCREMENT = 358 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '打印记录表' ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_print_station_express --- ---------------------------- -DROP TABLE IF EXISTS `wms_print_station_express`; -CREATE TABLE `wms_print_station_express` ( - `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '自增主键ID', - `print_station_id` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '打印台ID,关联wms_print_stations表的print_station_id', - `express_id` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '快递ID', - `express_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '快递名称,冗余字段,便于查询', - `printer_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '绑定的打印机名称', - `creator_id` bigint(20) UNSIGNED NOT NULL COMMENT '创建人工号ID', - `creator_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '创建人名称', - `create_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', - `update_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', - `deleted` tinyint(1) NOT NULL DEFAULT 0 COMMENT '软删除标记:0-未删除,1-已删除', - PRIMARY KEY (`id`) USING BTREE, - UNIQUE INDEX `uk_print_station_express`(`print_station_id`, `express_id`, `deleted`) USING BTREE, - INDEX `idx_print_station_id`(`print_station_id`) USING BTREE, - INDEX `idx_express_id`(`express_id`) USING BTREE, - INDEX `idx_creator_id`(`creator_id`) USING BTREE -) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT = '打印台快递-打印机绑定关系表' ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_print_stations --- ---------------------------- -DROP TABLE IF EXISTS `wms_print_stations`; -CREATE TABLE `wms_print_stations` ( - `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '自增主键ID', - `warehouse_id` bigint(20) UNSIGNED NOT NULL COMMENT '仓库ID', - `name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '打印台名称', - `computer_id` int(11) NOT NULL COMMENT '打印电脑ID', - `custom_barcode` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '自定义编码', - `creator_id` bigint(20) UNSIGNED NOT NULL COMMENT '创建人工号ID', - `creator_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '创建人名称', - `create_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', - `update_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', - `deleted` tinyint(1) NOT NULL DEFAULT 0 COMMENT '软删除标记:0-未删除,1-已删除', - `default_printer_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '默认打印机名称', - PRIMARY KEY (`id`) USING BTREE, - INDEX `idx_warehouse_id`(`warehouse_id`) USING BTREE, - INDEX `idx_computer_id`(`computer_id`) USING BTREE, - INDEX `idx_name`(`name`) USING BTREE, - INDEX `idx_custom_barcode`(`custom_barcode`) USING BTREE, - INDEX `idx_creator_id`(`creator_id`) USING BTREE, - INDEX `idx_create_at`(`create_at`) USING BTREE -) ENGINE = InnoDB AUTO_INCREMENT = 10 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT = '打印台信息表' ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_print_template --- ---------------------------- -DROP TABLE IF EXISTS `wms_print_template`; -CREATE TABLE `wms_print_template` ( - `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID', - `template_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '模板名称', - `platform` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '所属平台(抖音、拼多多、快手等)', - `template_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '模板类型:STANDARD-标准模板,CUSTOM-自定义模板', - `template_url` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '模板URL地址', - `template_content` json NULL COMMENT '模板内容(JSON格式)', - `page_width` int(11) NULL DEFAULT 76 COMMENT '页面宽度(mm)', - `page_height` int(11) NULL DEFAULT 130 COMMENT '页面高度(mm)', - `warehouse_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '关联仓库ID', - `is_default` tinyint(1) NULL DEFAULT 0 COMMENT '是否默认模板:0-否,1-是', - `status` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'ACTIVE' COMMENT '状态:ACTIVE-启用,DISABLED-禁用', - `create_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', - `update_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', - `business_type` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '类型', - `delete_at` date NULL DEFAULT NULL, - PRIMARY KEY (`id`) USING BTREE, - UNIQUE INDEX `uk_platform_template`(`platform`, `template_type`, `warehouse_id`, `business_type`, `delete_at`) USING BTREE, - INDEX `idx_platform`(`platform`) USING BTREE, - INDEX `idx_warehouse`(`warehouse_id`) USING BTREE -) ENGINE = InnoDB AUTO_INCREMENT = 16 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '打印模板配置表' ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_prohibited_type --- ---------------------------- -DROP TABLE IF EXISTS `wms_prohibited_type`; -CREATE TABLE `wms_prohibited_type` ( - `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键ID', - `type_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '类型名称', - `warehouse_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '仓库ID(关联wms_store.id,NULL表示系统预设)', - `is_system_preset` tinyint(1) NOT NULL DEFAULT 0 COMMENT '是否系统预设', - `sort_order` int(11) NULL DEFAULT 0 COMMENT '排序', - `created_by` int(10) UNSIGNED NULL DEFAULT NULL COMMENT '创建人', - `updated_by` int(10) UNSIGNED NULL DEFAULT NULL COMMENT '更新人', - `created_at` timestamp(0) NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', - `updated_at` timestamp(0) NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', - PRIMARY KEY (`id`) USING BTREE, - UNIQUE INDEX `uk_type_warehouse`(`type_name`, `warehouse_id`) USING BTREE, - INDEX `idx_warehouse_id`(`warehouse_id`) USING BTREE, - INDEX `idx_is_system`(`is_system_preset`) USING BTREE, - CONSTRAINT `fk_prohibited_type_warehouse` FOREIGN KEY (`warehouse_id`) REFERENCES `wms_store` (`id`) ON DELETE SET NULL ON UPDATE CASCADE -) ENGINE = InnoDB AUTO_INCREMENT = 19 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT = '违禁品类型表' ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_qimen_apps --- ---------------------------- -DROP TABLE IF EXISTS `wms_qimen_apps`; -CREATE TABLE `wms_qimen_apps` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, - `app_key` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, - `deleted_at` datetime(0) NULL DEFAULT NULL COMMENT '删除时间', - PRIMARY KEY (`id`) USING BTREE, - UNIQUE INDEX `app_key`(`app_key`) USING BTREE -) ENGINE = InnoDB AUTO_INCREMENT = 29 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_qimen_log --- ---------------------------- -DROP TABLE IF EXISTS `wms_qimen_log`; -CREATE TABLE `wms_qimen_log` ( - `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, - `log_id` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, - `from_key` int(10) NULL DEFAULT NULL, - `method` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, - `sign` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, - `costomer_id` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, - `v` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, - `url` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL, - `created_at` datetime(0) NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP(0), - `body` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL, - `result` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL, - `use_time` int(12) NULL DEFAULT NULL, - `updated_at` datetime(0) NULL DEFAULT NULL, - `deleted_at` datetime(0) NULL DEFAULT NULL, - `to_key` int(10) NULL DEFAULT 23535631, - PRIMARY KEY (`id`) USING BTREE, - UNIQUE INDEX `idx_log_id`(`log_id`) USING BTREE -) ENGINE = InnoDB AUTO_INCREMENT = 185807 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_receiving --- ---------------------------- -DROP TABLE IF EXISTS `wms_receiving`; -CREATE TABLE `wms_receiving` ( - `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '收货单ID', - `receiving_number` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '收货单号,如: RCV202312150001', - `creator_id` int(11) NOT NULL COMMENT '创建人工号ID', - `creator_snapshot` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '创建人信息快照(JSON格式)', - `status` enum('receiving','completed','cancelled') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'receiving' COMMENT '收货状态:receiving-收货中, completed-收货完成, cancelled-作废', - `detail_status` enum('all_matched','partial_matched','unmatched') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'unmatched' COMMENT '明细匹配状态:all_matched-全部匹配, partial_matched-部分匹配, unmatched-未匹配', - `storage_status` enum('none','partial','all') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'none' COMMENT '入库状态:none-未入库, partial-部分入库, all-全部入库', - `delivery_method` enum('truck','express','air_freight','sea_freight','other') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '来货方式:truck-货车, express-快递, air_freight-空运, sea_freight-海运, other-其他', - `license_plate` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '车牌号(货车运输时需要)', - `tracking_number` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '快递单号/物流单号', - `loading_method` enum('with_pallet','without_pallet') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '装卸方式:with_pallet-带托盘, without_pallet-不带托盘', - `video_device_id` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '录像设备ID(可选)', - `total_items` int(11) NOT NULL DEFAULT 0 COMMENT '总商品种类数', - `total_quantity` int(11) NOT NULL DEFAULT 0 COMMENT '商品总数量', - `total_boxes` int(11) NOT NULL DEFAULT 0 COMMENT '总箱数', - `total_pallets` int(11) NOT NULL DEFAULT 0 COMMENT '总托盘数', - `warehouse_id` bigint(20) UNSIGNED NOT NULL COMMENT '收货仓库ID', - `remark` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL COMMENT '备注信息', - `receiving_start_time` datetime(0) NULL DEFAULT NULL COMMENT '收货开始时间', - `receiving_end_time` datetime(0) NULL DEFAULT NULL COMMENT '收货结束时间', - `is_deleted` tinyint(1) NOT NULL DEFAULT 0 COMMENT '是否删除:0-否, 1-是', - `created_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', - `updated_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', - `store_id` bigint(20) UNSIGNED NULL DEFAULT NULL, - `store_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL, - `is_notice` int(1) UNSIGNED NULL DEFAULT 0, - `is_review` tinyint(1) NULL DEFAULT 0, - `reviewer_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL, - `reviewer_employee_id` bigint(20) UNSIGNED NULL DEFAULT NULL, - PRIMARY KEY (`id`) USING BTREE, - UNIQUE INDEX `uk_receiving_number`(`receiving_number`) USING BTREE, - INDEX `idx_creator_id`(`creator_id`) USING BTREE, - INDEX `idx_status`(`status`) USING BTREE, - INDEX `idx_delivery_method`(`delivery_method`) USING BTREE, - INDEX `idx_warehouse_id`(`warehouse_id`) USING BTREE, - INDEX `idx_created_at`(`created_at`) USING BTREE, - INDEX `idx_status_warehouse`(`status`, `warehouse_id`) USING BTREE, - INDEX `idx_supplier_created`(`created_at`) USING BTREE, - INDEX `reviewer_employee_id`(`reviewer_employee_id`) USING BTREE, - CONSTRAINT `wms_receiving_ibfk_1` FOREIGN KEY (`reviewer_employee_id`) REFERENCES `wms_account_store_employee` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT -) ENGINE = InnoDB AUTO_INCREMENT = 1377 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT = '收货主表' ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_receiving_detail --- ---------------------------- -DROP TABLE IF EXISTS `wms_receiving_detail`; -CREATE TABLE `wms_receiving_detail` ( - `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '明细ID', - `receiving_id` int(11) NOT NULL COMMENT '收货单ID', - `product_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '商品名称', - `barcode` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL COMMENT '商品条码', - `product_snapshot` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL COMMENT '商品信息快照(JSON格式)', - `system_product_id` int(11) NULL DEFAULT NULL COMMENT '关联的系统商品ID(可以为空)', - `actual_quantity` int(11) NOT NULL COMMENT '实际收货数量', - `box_quantity` int(11) NOT NULL DEFAULT 0 COMMENT '箱数', - `boxes_per_pallet` int(11) NOT NULL DEFAULT 1 COMMENT '(箱规)', - `pallet_quantity` int(11) NOT NULL DEFAULT 0 COMMENT '托盘数', - `receiving_time` datetime(0) NULL DEFAULT NULL COMMENT '收货时间(该商品的收货时间)', - `receiving_status` enum('pending','receiving','completed','cancelled') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'pending' COMMENT '收货状态', - `storage_status` enum('none','partial','all') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'none' COMMENT '入库状态:none-未入库, partial-部分入库, all-全部入库', - `stored_quantity` int(11) NOT NULL DEFAULT 0 COMMENT '已入库数量', - `batch_number` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '批次号', - `production_date` date NULL DEFAULT NULL COMMENT '生产日期', - `expiry_date` date NULL DEFAULT NULL COMMENT '保质期/到期日期', - `remark` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL COMMENT '备注', - `created_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', - `updated_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', - `space_id` bigint(20) NULL DEFAULT 1 COMMENT '存放位置', - `creator_id` bigint(20) UNSIGNED ZEROFILL NULL DEFAULT NULL, - `box_length` decimal(10, 2) NULL DEFAULT NULL COMMENT '长cm', - `box_width` decimal(10, 2) NULL DEFAULT NULL COMMENT '宽cm', - `box_height` decimal(10, 2) NULL DEFAULT NULL COMMENT '高cm', - `weight` int(11) NULL DEFAULT NULL COMMENT '重量g', - PRIMARY KEY (`id`) USING BTREE, - INDEX `idx_receiving_id`(`receiving_id`) USING BTREE, - INDEX `idx_system_product_id`(`system_product_id`) USING BTREE, - INDEX `idx_receiving_status`(`receiving_status`) USING BTREE, - INDEX `idx_storage_status`(`storage_status`) USING BTREE, - INDEX `idx_batch_number`(`batch_number`) USING BTREE, - CONSTRAINT `fk_receiving_detail_receiving` FOREIGN KEY (`receiving_id`) REFERENCES `wms_receiving` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE = InnoDB AUTO_INCREMENT = 2536 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT = '收货明细表' ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_role --- ---------------------------- -DROP TABLE IF EXISTS `wms_role`; -CREATE TABLE `wms_role` ( - `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '角色ID', - `role_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '角色代码', - `role_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '角色名称', - `description` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '角色描述', - `role_type` tinyint(4) NOT NULL DEFAULT 1 COMMENT '角色类型:1-系统角色,2-自定义角色', - `scope` tinyint(4) NOT NULL DEFAULT 1 COMMENT '作用范围:1-全局,2-指定仓库', - `is_system` tinyint(4) NOT NULL DEFAULT 0 COMMENT '是否系统预设:0-否,1-是', - `status` tinyint(4) NOT NULL DEFAULT 1 COMMENT '状态:0-禁用,1-启用', - `created_by` bigint(20) UNSIGNED NOT NULL COMMENT '创建人', - `created_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', - `updated_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', - `store_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '所属仓库ID', - `deleted_at` datetime(0) NULL DEFAULT NULL, - `pid` bigint(20) UNSIGNED NULL DEFAULT 0 COMMENT '上级id', - `permissions` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL, - PRIMARY KEY (`id`) USING BTREE, - UNIQUE INDEX `uk_role_code`(`role_code`) USING BTREE, - INDEX `idx_role_type`(`role_type`) USING BTREE, - INDEX `idx_scope`(`scope`) USING BTREE, - INDEX `idx_status`(`status`) USING BTREE, - INDEX `fk_wms_role_created_by`(`created_by`) USING BTREE, - INDEX `idx_store_id`(`store_id`) USING BTREE, - CONSTRAINT `fk_wms_role_created_by` FOREIGN KEY (`created_by`) REFERENCES `wms_account` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT, - CONSTRAINT `fk_wms_role_store` FOREIGN KEY (`store_id`) REFERENCES `wms_store` (`id`) ON DELETE SET NULL ON UPDATE RESTRICT -) ENGINE = InnoDB AUTO_INCREMENT = 83 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '平台角色表' ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_stock_barcodes --- ---------------------------- -DROP TABLE IF EXISTS `wms_stock_barcodes`; -CREATE TABLE `wms_stock_barcodes` ( - `id` bigint(20) NOT NULL AUTO_INCREMENT, - `stock_id` bigint(20) NOT NULL COMMENT '主表ID', - `barcode` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '条码', - `description` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '条码描述', - `create_time` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', - `warehouse_id` bigint(20) UNSIGNED NULL DEFAULT NULL, - PRIMARY KEY (`id`) USING BTREE, - INDEX `idx_stock_id`(`stock_id`) USING BTREE, - INDEX `uk_barcode`(`barcode`) USING BTREE, - CONSTRAINT `wms_stock_barcodes_ibfk_1` FOREIGN KEY (`stock_id`) REFERENCES `wms_stock_warehouse` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION -) ENGINE = InnoDB AUTO_INCREMENT = 35086 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT = 'WMS商品条码表' ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_stock_store --- ---------------------------- -DROP TABLE IF EXISTS `wms_stock_store`; -CREATE TABLE `wms_stock_store` ( - `id` bigint(20) NOT NULL AUTO_INCREMENT, - `warehouse_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '仓库编码', - `owner_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '货主编码', - `app_key` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL, - `is_area_sale` char(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'N' COMMENT '是否区域销售', - `item_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '商品编码', - `goods_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '货物编码', - `item_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '商品名称', - `sku_property` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT 'SKU规格', - `stock_unit` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '库存单位', - `length` decimal(10, 2) NULL DEFAULT 0.00 COMMENT '长度', - `width` decimal(10, 2) NULL DEFAULT 0.00 COMMENT '宽度', - `height` decimal(10, 2) NULL DEFAULT 0.00 COMMENT '高度', - `volume` decimal(10, 2) NULL DEFAULT 0.00 COMMENT '体积', - `gross_weight` decimal(10, 2) NULL DEFAULT 0.00 COMMENT '毛重', - `net_weight` decimal(10, 2) NULL DEFAULT 0.00 COMMENT '净重', - `category_id` int(11) NULL DEFAULT NULL COMMENT '分类ID', - `category_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '分类名称', - `item_type` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '商品类型', - `tag_price` decimal(10, 2) NULL DEFAULT 0.00 COMMENT '标价', - `retail_price` decimal(10, 2) NULL DEFAULT 0.00 COMMENT '零售价', - `is_sn_mgmt` char(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'N' COMMENT '是否序列号管理', - `is_shelf_life_mgmt` char(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'N' COMMENT '是否保质期管理', - `is_batch_mgmt` char(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'N' COMMENT '是否批次管理', - `create_time` datetime(0) NOT NULL COMMENT '创建时间', - `update_time` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', - `is_valid` char(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'Y' COMMENT '是否有效', - `barcode` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL, - `stock_id` bigint(20) NULL DEFAULT NULL, - `warehouse_id` bigint(20) UNSIGNED NOT NULL, - `store_id` bigint(20) UNSIGNED NOT NULL, - `create_from` enum('qimen','api') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL, - `delete_at` datetime(0) NULL DEFAULT NULL COMMENT '删除时间', - `brand_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL, - PRIMARY KEY (`id`) USING BTREE, - UNIQUE INDEX `uk_warehouse_owner_item`(`item_code`, `app_key`, `warehouse_id`, `store_id`) USING BTREE, - INDEX `idx_owner_code`(`owner_code`) USING BTREE, - INDEX `idx_goods_code`(`goods_code`) USING BTREE, - INDEX `idx_category_id`(`category_id`) USING BTREE, - INDEX `idx_create_time`(`create_time`) USING BTREE, - INDEX `idx_is_valid`(`is_valid`) USING BTREE, - INDEX `uk_item_code`(`item_code`) USING BTREE, - INDEX `warehouse_id`(`warehouse_id`) USING BTREE, - INDEX `store_id`(`store_id`) USING BTREE, - INDEX `stock_id`(`stock_id`) USING BTREE, - CONSTRAINT `wms_stock_store_ibfk_1` FOREIGN KEY (`warehouse_id`) REFERENCES `wms_store` (`id`) ON DELETE RESTRICT ON UPDATE NO ACTION, - CONSTRAINT `wms_stock_store_ibfk_2` FOREIGN KEY (`store_id`) REFERENCES `wms_store` (`id`) ON DELETE RESTRICT ON UPDATE NO ACTION, - CONSTRAINT `wms_stock_store_ibfk_3` FOREIGN KEY (`stock_id`) REFERENCES `wms_stock_warehouse` (`id`) ON DELETE SET NULL ON UPDATE NO ACTION -) ENGINE = InnoDB AUTO_INCREMENT = 1000693 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT = 'WMS库存主表' ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_stock_transaction --- ---------------------------- -DROP TABLE IF EXISTS `wms_stock_transaction`; -CREATE TABLE `wms_stock_transaction` ( - `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键ID', - `transaction_type` enum('INBOUND','OUTBOUND') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '出入库类型', - `warehouse_id` bigint(20) UNSIGNED NOT NULL COMMENT '仓库ID', - `store_id` bigint(20) UNSIGNED NOT NULL COMMENT '货主ID', - `stock_id` bigint(20) UNSIGNED NOT NULL COMMENT '商品库存ID,关联 wms_stock_warehouse.id', - `storage_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '库位库存ID,关联 wms_storage.id', - `space_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '库位ID', - `quantity` int(12) NOT NULL COMMENT '变动数量(正数)', - `batch_no` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '批次号', - `inventory_type` enum('ZP','CC','JS','XS','ZT','DJ','FP') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'ZP' COMMENT '库存类型', - `order_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '关联单据类型', - `order_no` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '关联单据号', - `order_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '关联单据ID', - `receiving_id` int(11) NULL DEFAULT NULL COMMENT '关联收货单ID', - `entry_order_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '关联入库单ID', - `operator_id` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '操作人ID', - `operator_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '操作人名称', - `remark` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '备注', - `created_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', - `before_quantity` int(12) NULL DEFAULT NULL COMMENT '变更前总库存数量', - `after_quantity` int(12) NULL DEFAULT NULL COMMENT '变更后总库存数量', - `before_locked_quantity` int(12) NULL DEFAULT NULL COMMENT '变更前锁定数量', - `after_locked_quantity` int(12) NULL DEFAULT NULL COMMENT '变更后锁定数量', - PRIMARY KEY (`id`) USING BTREE, - INDEX `idx_stock_id`(`stock_id`) USING BTREE, - INDEX `idx_warehouse_time`(`warehouse_id`, `created_at`) USING BTREE, - INDEX `idx_order`(`order_type`, `order_id`) USING BTREE, - INDEX `idx_receiving_id`(`receiving_id`) USING BTREE, - INDEX `idx_entry_order_id`(`entry_order_id`) USING BTREE, - INDEX `idx_created_at`(`created_at`) USING BTREE, - INDEX `idx_store_transaction_type`(`store_id`, `transaction_type`) USING BTREE -) ENGINE = InnoDB AUTO_INCREMENT = 148 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '出入库流水记录表' ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_stock_unit --- ---------------------------- -DROP TABLE IF EXISTS `wms_stock_unit`; -CREATE TABLE `wms_stock_unit` ( - `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键ID', - `warehouse_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '仓库ID,NULL表示系统默认', - `name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '单位名称', - `created_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', - PRIMARY KEY (`id`) USING BTREE, - UNIQUE INDEX `uk_name_warehouse`(`name`, `warehouse_id`) USING BTREE COMMENT '单位名称在同一个仓库下唯一', - INDEX `idx_warehouse_id`(`warehouse_id`) USING BTREE -) ENGINE = InnoDB AUTO_INCREMENT = 22 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '库存单位表' ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_stock_warehouse --- ---------------------------- -DROP TABLE IF EXISTS `wms_stock_warehouse`; -CREATE TABLE `wms_stock_warehouse` ( - `id` bigint(20) NOT NULL AUTO_INCREMENT, - `item_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '商品编码', - `goods_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '货物编码', - `store_id` bigint(20) UNSIGNED NOT NULL DEFAULT 0 COMMENT '货主id', - `item_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '商品名称', - `sku_property` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT 'SKU规格', - `stock_unit` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '库存单位', - `packing_requirements` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL COMMENT '打包要求', - `length` decimal(10, 2) NULL DEFAULT 0.00 COMMENT '长度', - `width` decimal(10, 2) NULL DEFAULT 0.00 COMMENT '宽度', - `height` decimal(10, 2) NULL DEFAULT 0.00 COMMENT '高度', - `volume` int(11) UNSIGNED NULL DEFAULT 0 COMMENT '体积', - `gross_weight` decimal(10, 2) NULL DEFAULT 0.00 COMMENT '毛重', - `net_weight` decimal(10, 2) NULL DEFAULT 0.00 COMMENT '净重', - `item_type` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '商品类型', - `tag_price` decimal(10, 2) NULL DEFAULT 0.00 COMMENT '标价', - `retail_price` decimal(10, 2) NULL DEFAULT 0.00 COMMENT '零售价', - `is_sn_mgmt` char(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'N' COMMENT '是否序列号管理', - `is_shelf_life_mgmt` char(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'N' COMMENT '是否保质期管理', - `is_batch_mgmt` char(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'N' COMMENT '是否批次管理', - `is_images` char(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'N' COMMENT '是否有照片', - `create_at` datetime(0) NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '创建时间', - `update_at` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', - `is_valid` char(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'Y' COMMENT '是否有效', - `warehouse_id` bigint(20) UNSIGNED NULL DEFAULT NULL, - `delete_at` datetime(0) NULL DEFAULT NULL COMMENT '删除时间', - `quantity` int(11) NOT NULL DEFAULT 0 COMMENT '库存数量', - `locked_quantity` int(11) NOT NULL DEFAULT 0 COMMENT '订单锁定库存', - `level` enum('A','B','C') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '商品分级', - `prohibited_id` int(10) UNSIGNED NULL DEFAULT NULL COMMENT '违禁品分类', - `return_quantity` int(11) NULL DEFAULT NULL COMMENT '消退库存', - `brand_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL, - `enable_box_spec` tinyint(4) NULL DEFAULT NULL, - `box_gross_weight` int(11) NULL DEFAULT NULL COMMENT '箱毛重(g)', - `box_height` decimal(10, 2) NULL DEFAULT NULL COMMENT '箱高(cm)', - `box_length` decimal(10, 2) NULL DEFAULT NULL COMMENT '箱长(cm)', - `box_width` decimal(10, 2) NULL DEFAULT NULL COMMENT '箱宽(cm)', - `box_net_weight` int(11) NULL DEFAULT NULL COMMENT '箱净重', - `box_volume` int(11) UNSIGNED NULL DEFAULT NULL COMMENT '箱体积(m³)', - `quantity_per_box` int(11) NULL DEFAULT NULL, - `deleted_at` datetime(0) NULL DEFAULT NULL, - `inbound_min_days` int(11) NULL DEFAULT 0 COMMENT '入库最小天数要求', - `outbound_min_days` int(11) NULL DEFAULT 0 COMMENT '出库最小天数要求', - `remaining_threshold_days` int(11) NULL DEFAULT 0 COMMENT '剩余有效期阈值天数', - `shelf_life_days` int(11) NULL DEFAULT NULL COMMENT '保质期天数', - PRIMARY KEY (`id`) USING BTREE, - UNIQUE INDEX `uk_item_code`(`item_code`, `warehouse_id`, `store_id`, `deleted_at`) USING BTREE, - INDEX `idx_create_time`(`create_at`) USING BTREE, - INDEX `idx_is_valid`(`is_valid`) USING BTREE, - INDEX `warehouse_id`(`warehouse_id`) USING BTREE, - INDEX `wms_stock_warehouse_ibfk_2`(`prohibited_id`) USING BTREE, - CONSTRAINT `wms_stock_warehouse_ibfk_1` FOREIGN KEY (`warehouse_id`) REFERENCES `wms_store` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION, - CONSTRAINT `wms_stock_warehouse_ibfk_2` FOREIGN KEY (`prohibited_id`) REFERENCES `wms_prohibited_type` (`id`) ON DELETE SET NULL ON UPDATE NO ACTION -) ENGINE = InnoDB AUTO_INCREMENT = 157105 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT = 'WMS库存主表' ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_storage --- ---------------------------- -DROP TABLE IF EXISTS `wms_storage`; -CREATE TABLE `wms_storage` ( - `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '库存ID', - `warehouse_id` bigint(20) UNSIGNED NOT NULL COMMENT '仓库ID', - `store_id` bigint(20) UNSIGNED NOT NULL COMMENT '货主ID', - `space_id` bigint(20) UNSIGNED NOT NULL COMMENT '库位ID,关联外部仓位表', - `stock_id` bigint(20) NOT NULL COMMENT '商品SKU ID', - `batch_no` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '批次号', - `inventory_type` enum('ZP','CC','BACK','VIRTUAL') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'ZP' COMMENT '库存类型:ZP=正品, CC=残次, JS=机损, XS=箱损, ZT=在途库存, DJ=冻结, FP=废品', - `quantity` int(12) NOT NULL DEFAULT 0 COMMENT '库存数量', - `locked_quantity` int(12) NOT NULL DEFAULT 0 COMMENT '锁定数量', - `available_quantity` int(12) NOT NULL DEFAULT 0 COMMENT '可用数量', - `production_date` date NULL DEFAULT NULL COMMENT '生产日期', - `expiry_date` date NULL DEFAULT NULL COMMENT '过期日期', - `inbound_time` datetime(0) NOT NULL COMMENT '入库时间', - `inbound_order_no` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '入库单号', - `receiving_id` int(11) NULL DEFAULT NULL COMMENT '收货单ID', - `entry_order_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '入库单ID', - `supplier_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '供应商ID', - `supplier_batch_no` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '供应商批次号', - `is_enabled` tinyint(1) NOT NULL DEFAULT 1 COMMENT '是否启用', - `created_at` timestamp(0) NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', - `updated_at` timestamp(0) NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', - `delete_at` datetime(0) NULL DEFAULT NULL COMMENT '删除时间', - PRIMARY KEY (`id`) USING BTREE, - UNIQUE INDEX `uk_location_sku_batch_type`(`space_id`, `stock_id`, `batch_no`, `inventory_type`) USING BTREE, - INDEX `idx_warehouse_location`(`warehouse_id`, `space_id`) USING BTREE, - INDEX `idx_sku_batch`(`stock_id`, `batch_no`) USING BTREE, - INDEX `idx_inventory_type`(`inventory_type`) USING BTREE, - INDEX `idx_expiry_date`(`expiry_date`) USING BTREE, - INDEX `idx_inbound_order`(`inbound_order_no`) USING BTREE, - INDEX `store_id`(`store_id`) USING BTREE, - INDEX `idx_receiving_id`(`receiving_id`) USING BTREE, - INDEX `idx_entry_order_id`(`entry_order_id`) USING BTREE, - CONSTRAINT `wms_storage_entry_order_id_foreign_idx` FOREIGN KEY (`entry_order_id`) REFERENCES `wms_entry_order` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, - CONSTRAINT `wms_storage_ibfk_1` FOREIGN KEY (`warehouse_id`) REFERENCES `wms_store` (`id`) ON DELETE RESTRICT ON UPDATE NO ACTION, - CONSTRAINT `wms_storage_ibfk_2` FOREIGN KEY (`store_id`) REFERENCES `wms_store` (`id`) ON DELETE RESTRICT ON UPDATE NO ACTION, - CONSTRAINT `wms_storage_ibfk_3` FOREIGN KEY (`stock_id`) REFERENCES `wms_stock_warehouse` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION, - CONSTRAINT `wms_storage_ibfk_4` FOREIGN KEY (`space_id`) REFERENCES `wms_location_space` (`id`) ON DELETE RESTRICT ON UPDATE NO ACTION -) ENGINE = InnoDB AUTO_INCREMENT = 223 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT = '库存表' ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_store --- ---------------------------- -DROP TABLE IF EXISTS `wms_store`; -CREATE TABLE `wms_store` ( - `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '商家ID', - `company_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '公司全称', - `business_license` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '营业执照号', - `legal_person` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '法人代表', - `contact_phone` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '联系电话', - `contact_email` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '联系邮箱', - `contact_person` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '联系人', - `address` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '公司地址', - `industry` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '所属行业', - `account_id` bigint(20) UNSIGNED NOT NULL COMMENT '关联账号ID(商家管理员)', - `status` tinyint(1) NOT NULL DEFAULT 1 COMMENT '状态:0-禁用,1-启用,2-审核中', - `created_by` bigint(20) UNSIGNED NOT NULL COMMENT '创建人', - `created_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', - `updated_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', - `logo_url` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT 'logo链接', - `domain` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '绑定域名', - `auth_end` date NULL DEFAULT NULL COMMENT '授权结束时间', - `deleted_at` datetime(0) NULL DEFAULT NULL COMMENT '删除时间', - `quota_bytes` bigint(20) UNSIGNED NULL DEFAULT 107374182400, - `project` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '应用', - `subject_config` json NULL COMMENT '主体配置JSON', - PRIMARY KEY (`id`) USING BTREE, - UNIQUE INDEX `uk_company_name`(`company_name`) USING BTREE, - UNIQUE INDEX `uk_business_license`(`business_license`, `deleted_at`) USING BTREE, - INDEX `idx_status`(`status`) USING BTREE, - INDEX `idx_account_id`(`account_id`) USING BTREE -) ENGINE = InnoDB AUTO_INCREMENT = 1000278 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT = '商家表' ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_store_join --- ---------------------------- -DROP TABLE IF EXISTS `wms_store_join`; -CREATE TABLE `wms_store_join` ( - `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '申请ID', - `account_id` bigint(20) UNSIGNED NOT NULL COMMENT '用户账户ID', - `real_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '真实姓名', - `store_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '审批的门店/店铺ID', - `apply_time` datetime(0) NOT NULL COMMENT '申请时间', - `apply_username` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '申请人用户名', - `audit_status` enum('pending','approved','rejected','processing') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT 'pending' COMMENT '审核状态', - `remark` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT '' COMMENT '备注', - `join_token` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '加入令牌/验证码', - `token_expiry_time` datetime(0) NULL DEFAULT NULL COMMENT '令牌过期时间', - `created_at` timestamp(0) NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', - `updated_at` timestamp(0) NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', - `audit_real_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '审核人工号名字', - `warehouse` tinyint(1) NULL DEFAULT NULL, - PRIMARY KEY (`id`) USING BTREE, - UNIQUE INDEX `uk_join_token`(`join_token`) USING BTREE, - INDEX `idx_account_id`(`account_id`) USING BTREE, - INDEX `idx_audit_status`(`audit_status`) USING BTREE, - INDEX `idx_apply_time`(`apply_time`) USING BTREE, - INDEX `idx_store_id`(`store_id`) USING BTREE, - INDEX `uk_account_warehouse_store`(`account_id`, `store_id`) USING BTREE, - CONSTRAINT `wms_store_join_ibfk_1` FOREIGN KEY (`account_id`) REFERENCES `wms_account` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION, - CONSTRAINT `wms_store_join_ibfk_2` FOREIGN KEY (`store_id`) REFERENCES `wms_store` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION -) ENGINE = InnoDB AUTO_INCREMENT = 37 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT = '加入申请记录表' ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_store_warehouse --- ---------------------------- -DROP TABLE IF EXISTS `wms_store_warehouse`; -CREATE TABLE `wms_store_warehouse` ( - `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '授权ID', - `store_id` bigint(20) UNSIGNED NOT NULL COMMENT '商家ID', - `warehouse_id` bigint(20) UNSIGNED NOT NULL COMMENT '仓库ID', - `auth_status` tinyint(4) NOT NULL DEFAULT 1 COMMENT '授权状态:1-申请中,2-已通过,3-已拒绝,4-已解除,5-已过期', - `apply_reason` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '申请理由', - `review_comment` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '审核意见', - `apply_time` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '申请时间', - `review_time` datetime(0) NULL DEFAULT NULL COMMENT '审核时间', - `auth_start` date NULL DEFAULT NULL COMMENT '授权开始日期', - `auth_end` date NULL DEFAULT NULL COMMENT '授权结束日期', - `actual_end` datetime(0) NULL DEFAULT NULL COMMENT '实际结束时间', - `applied_by` bigint(20) UNSIGNED NOT NULL COMMENT '申请人', - `reviewed_by` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '审核人', - `ended_by` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '解除人', - `created_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', - `updated_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', - `store_remask` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '商家备注', - `warehouse_remask` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '仓库备注', - `deleted_at` datetime(0) NULL DEFAULT NULL COMMENT '删除时间', - `print_quantity` int(11) NOT NULL DEFAULT 0 COMMENT '面单余额', - `print_quantity_locked` int(11) NOT NULL DEFAULT 0 COMMENT '面单锁定余额,分配快递时递增1', - `use_status` int(1) NULL DEFAULT 0 COMMENT '使用状态0-不使用,1-使用', - `policy_config` json NULL COMMENT '货主在仓库的配置与策略', - PRIMARY KEY (`id`) USING BTREE, - UNIQUE INDEX `uk_store_warehouse`(`store_id`, `warehouse_id`) USING BTREE, - INDEX `idx_store_id`(`store_id`) USING BTREE, - INDEX `idx_warehouse_id`(`warehouse_id`) USING BTREE, - INDEX `idx_auth_status`(`auth_status`) USING BTREE, - INDEX `idx_apply_time`(`apply_time`) USING BTREE, - INDEX `idx_auth_period`(`auth_start`, `auth_end`) USING BTREE, - INDEX `use_status`(`use_status`) USING BTREE, - CONSTRAINT `wms_store_warehouse_ibfk_1` FOREIGN KEY (`store_id`) REFERENCES `wms_store` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION, - CONSTRAINT `wms_store_warehouse_ibfk_2` FOREIGN KEY (`warehouse_id`) REFERENCES `wms_store` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION -) ENGINE = InnoDB AUTO_INCREMENT = 100250 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '商家仓库授权表' ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_store_warehouse_print_quantity_log --- ---------------------------- -DROP TABLE IF EXISTS `wms_store_warehouse_print_quantity_log`; -CREATE TABLE `wms_store_warehouse_print_quantity_log` ( - `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键ID', - `contract_id` bigint(20) UNSIGNED NOT NULL COMMENT '签约关系ID,对应 wms_store_warehouse.id', - `store_id` bigint(20) UNSIGNED NOT NULL COMMENT '货主ID', - `warehouse_id` bigint(20) UNSIGNED NOT NULL COMMENT '仓库ID', - `change_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '变更类型,如 manual_adjust / order_deduct', - `business_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '业务来源类型,如 order_express', - `business_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '业务关联ID,预留关联 wms_order_express.id', - `change_quantity` int(11) NOT NULL COMMENT '本次变更数量,整数,可正可负', - `balance_before` int(11) NOT NULL COMMENT '变更前余额', - `balance_after` int(11) NOT NULL COMMENT '变更后余额', - `reason` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '变更缘由;人工调整时必填', - `operator_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '操作人账号ID', - `created_by` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '创建人账号ID', - `created_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', - `updated_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', - PRIMARY KEY (`id`) USING BTREE, - INDEX `warehouse_id`(`warehouse_id`) USING BTREE, - INDEX `idx_sw_print_qty_log_contract_id`(`contract_id`, `id`) USING BTREE, - INDEX `idx_sw_print_qty_log_store_warehouse`(`store_id`, `warehouse_id`) USING BTREE, - INDEX `idx_sw_print_qty_log_business`(`business_type`, `business_id`) USING BTREE, - INDEX `idx_sw_print_qty_log_change_type`(`change_type`) USING BTREE, - INDEX `idx_sw_print_qty_log_created_at`(`created_at`) USING BTREE, - CONSTRAINT `wms_store_warehouse_print_quantity_log_ibfk_1` FOREIGN KEY (`contract_id`) REFERENCES `wms_store_warehouse` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE, - CONSTRAINT `wms_store_warehouse_print_quantity_log_ibfk_2` FOREIGN KEY (`store_id`) REFERENCES `wms_store` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE, - CONSTRAINT `wms_store_warehouse_print_quantity_log_ibfk_3` FOREIGN KEY (`warehouse_id`) REFERENCES `wms_store` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE -) ENGINE = InnoDB AUTO_INCREMENT = 26 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '货主-仓库签约面单余额变更记录表' ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_system_log --- ---------------------------- -DROP TABLE IF EXISTS `wms_system_log`; -CREATE TABLE `wms_system_log` ( - `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, - `method` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, - `v` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, - `url` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL, - `created_at` datetime(0) NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP(0), - `body` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL, - `result` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL, - `use_time` int(12) NULL DEFAULT NULL, - `updated_at` datetime(0) NULL DEFAULT NULL, - `delete_at` datetime(0) NULL DEFAULT NULL, - `headers` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL, - `auth` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL, - `store_id` bigint(20) UNSIGNED NULL DEFAULT NULL, - `device` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, - PRIMARY KEY (`id`) USING BTREE, - INDEX `store_id`(`store_id`) USING BTREE, - CONSTRAINT `wms_system_log_ibfk_1` FOREIGN KEY (`store_id`) REFERENCES `wms_store` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION -) ENGINE = InnoDB AUTO_INCREMENT = 30174 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; - --- ---------------------------- --- Table structure for wms_wave_batch --- ---------------------------- -DROP TABLE IF EXISTS `wms_wave_batch`; -CREATE TABLE `wms_wave_batch` ( - `wave_id` bigint(20) NOT NULL AUTO_INCREMENT, - `wave_no` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '波次编号,如WAVE202401001', - `wave_type` tinyint(4) NOT NULL DEFAULT 1 COMMENT '波次类型:1-团购 2-散单', - `wave_status` tinyint(4) NOT NULL DEFAULT 0 COMMENT '波次状态:-1-已取消 0-自动加团中 1-已就绪 2-已打印 3-拣货中 4-拣货完成 5-复核完成 6-打包完成 ', - `total_orders` int(11) NULL DEFAULT 0 COMMENT '总订单数', - `processed_orders` int(11) NULL DEFAULT 0 COMMENT '已处理订单数', - `picking_operator` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '拣货员', - `picking_start_time` datetime(0) NULL DEFAULT NULL COMMENT '拣货开始时间', - `picking_end_time` datetime(0) NULL DEFAULT NULL COMMENT '拣货结束时间', - `print_operator` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '打印员', - `print_time` datetime(0) NULL DEFAULT NULL COMMENT '打印时间', - `print_count` int(11) NULL DEFAULT 0 COMMENT '打印次数', - `check_operator` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '校验员', - `check_time` datetime(0) NULL DEFAULT NULL COMMENT '校验时间', - `check_result` tinyint(4) NULL DEFAULT NULL COMMENT '校验结果', - `priority` tinyint(4) NULL DEFAULT 5 COMMENT '优先级 1-5', - `warehouse_id` bigint(20) UNSIGNED NOT NULL COMMENT '仓库ID', - `creator` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '创建人', - `create_time` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP(0), - `update_time` datetime(0) NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP(0), - `item_detail_machine` varchar(1024) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '抓取结构token:v1|item_part_type|item_part|distinguish_express|logistics_name|item_snapshot_key', - `item_part_type` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '结构来源类型:items_hash/items', - `item_part` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '结构主键(items_hash或items摘要)', - `distinguish_express` tinyint(1) NOT NULL DEFAULT 0 COMMENT '是否区分快递 0否1是', - `logistics_name` varchar(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '快递名称(区分快递时参与匹配)', - `item_snapshot_key` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '结构快照键', - PRIMARY KEY (`wave_id`) USING BTREE, - INDEX `idx_wave_status`(`wave_status`, `create_time`) USING BTREE, - INDEX `idx_wave_no`(`wave_no`) USING BTREE, - INDEX `idx_warehouse`(`warehouse_id`, `wave_status`) USING BTREE, - INDEX `idx_creator`(`creator`, `create_time`) USING BTREE, - INDEX `idx_wave_fast_group`(`warehouse_id`, `wave_type`, `wave_status`, `item_part_type`, `item_part`, `distinguish_express`, `logistics_name`) USING BTREE, - INDEX `idx_wave_snapshot_key`(`item_snapshot_key`) USING BTREE, - INDEX `idx_wave_item_machine_prefix`(`item_detail_machine`(191)) USING BTREE -) ENGINE = InnoDB AUTO_INCREMENT = 1777888535764263 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '波次批次主表' ROW_FORMAT = Dynamic; - -SET FOREIGN_KEY_CHECKS = 1; diff --git a/app/service/systems/space.js b/app/service/systems/space.js index eea4b75..019a915 100644 --- a/app/service/systems/space.js +++ b/app/service/systems/space.js @@ -35,6 +35,11 @@ class spaceService extends Service { [app.Sequelize.Op.like]: searchKeyword, }, }, + { + custom_name: { + [app.Sequelize.Op.like]: searchKeyword, + }, + }, ], }, ], diff --git a/app_service_systemMethods_index_head.js b/app_service_systemMethods_index_head.js deleted file mode 100644 index d2654f980643c1d9628a35d5b68280d65340c484..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 178012 zcmeFa4|JW?btig(bXJ>WI&HFsX)u&)2$A?FWCG1VLx_+Kn1CfqvSnG8C0mjuVO{B3 zzQ#7T?2-gKOiL5;SxqK=P12UvVTzk%5<*fk6T+WKoRrMGHPac$r0d0^NM$E03b_Lc5;&OZC>v;Uuc&iBUaO{HC>ou$!Inf|YpW=a#K zVft(;{d(!2mfo8F8!k<)` zey%E27Wy=mE?t0XLL8>ndrMUsb2Y(p>=xG=IwT}M3eF38; z8mmS>RT}GhqQq6DvC{6+m9%12qD@Qs{}heBi!kB;Thb9L)RNm=MRS~{=a~J>3BJj~ zs;6{Qoj8rAW46#3TWGAU>Hms{IX*;&I1npOqZlQl0Xe5SuRcRB= zp}BM;QM{e-Sy|ejwnF>WrSMKYv3IEQ!rtquS5BTiarMUb&mJw`yC$jJvhl~`eM$59E8~Bf zEWi4DV^`6-s%&4C&JTQ4rr*k?+L4DozGK_Nb1NoCMxRLjeDL0`CzF@gSEmkr^2W4< zw)`OR#ulRX7LxCBX&?0lm)}KyPZBqP>o+7{+tK+FL%A*C{^imK(-o>wn;DW*^c1}_ zMZCA4zS~6*CR1pP&Bo*pH$Slbwq*C76|;bOwEWuKh4(*m;JNDA6BA>PkDgm8pXep{ zU6pFCZ3JtIc&A2lh7K#Ix@c!sP`D~aVKF3Uu%>kyR~!$;rU*|a5n8z920I|WQ;3ISEulY7PNm{emknquDf>sH|K8r z?BV&=`{uWO`-SeL{rH9VUsru=-+%6IKJrS}ANMY+HLv)a*|ka6P`*TWklnhI<_SFv z8zKJ9YWjOLwH_?p_tXxK-9P&X*{ZY78c#0k|LCssrs6X0LN#p#!|O^`PMp*F?g@sG zZxL8#Z>Lp(MH1|qJ$!AsHF>*AYs&ty^k%;HXZ)Vhdx#RX)bkxB9)V?XTeT1eL!YY- zXrgwuMQchmIyezOm}v}3Gx1`XY_?!{J^cmS!nS&rcth+QAmOPCNi@$sT1B-f_Waq3 z)yQYTI5om|n#O>K04u4Z3w_{W#`}b*R4)v*nD88h4}H4T2iK*QXlM1TKt93&yhk47DVjm$1myUd zgNNfh0e-PLYmoc|hAjM9UvHVQ^oD1}{Ey%4S&2mGn6VY~TiTF@(^W*wTOmJRW)OoG zZf!$^&Vs~&J7RFmHg@kV)DPBjkXC39(U@cS!4zT)T2>z$I_9~ZAWu2)chcX$IW|IG zKYJ9&$F@{TK>b02+t{e}!m+W~naWW01gDF>RgI@D?4HPSjHdKJY>-WvP+J??E?UKr zg3v;3ZD{IYsNO+dhhwR*w;R%IE}Tmp3EM){gHN=Re#{jFhv<0Vq;TvO8Z!pd9Xr16 ziy1u*)g52u2~jm-Mb-|Yp%#Nh9&8gAvF=$O;(uGWb@)rke;qtp-oN(ZnYGEY>;Aq! zsq8&;?j_5r?GsNNPbxQU%J&RoIfJ6v0(g_(PhMI-y?%YtH2$d}_@*z_o;`5m>xb^k z%LGgjb>W#HUola-n|Mxqb2|b@hC-~p#2umNUOWJ?BcV2aY-anCzRv&~q`sD}h~LtV zopf}Go3yVRuXiPfTE8=P@y6@#{P3=WM~+Qhy6;$W@4%1x-aYa3eg81AG5O%@h~R&3 z^A+p9mHcGrFNgoh#=q-0THe#~4CR~t<()^%dprJW<0BLyT(terC--z5*!5I$?T7zo z<>9%#9S`;T`KMP7Ja^!hsh;FZrF{NyeSGApHR~)IwOk6}9*-Qh(#lWMszcXKr4h-~ z$$8H|G4!3eqvdtA-5sCbf7ZcAcf58t=a$Yo_{hlWYEs!U-+th>joGmTTYcoOMko(E zL7#|lW{9)4IvI0B6`{G<{9yXl@BwD%hqK#u{#_{nFFOpmOc6&Y<_KY7MjW=+EHOs7 z7c^8nIv8HiYVccO^;P0_Qa@nce?rp0-$iEJ;>=b(SlfOz221?1rGN#m8kS#S4N!Iu z`lm`6fQghI94CE%=ANaUq^+B?!QaR&3fDDLp55eh(FCH+z)PAf%vv2#8MX+y3K<EfEIqZ+n5&s9IS?W}`;-IcFV8nHNSsoZU$SRMA}iDYW) z{rfo^eQfTLbmSj*NhTUuY2cErC;ZjbG2+(8UN7y@LTj><_6VRIfTaroxTrng*ruO$ z7V@e6?7COyKU;fm`MLhK+LgTzZ2$J$v+I6)Xj!#w;qbOP}9wC(+u+Pv`IV5Fcd3+!>iKb^E>I?Nj(9NCIu=LmgDQmTl<^(U4t)9ZcLVK$hY3gIq#?aX4d|SBfLn~ z>^$lfTd+^TmKgiar>jl*%klS&|HT8x=Du1z_mbu#Kkkxvnyo6Y>Sa`Kf#2Nxe@L4l z@|a2OWD!fVlRQ#e(#3+tY)x3->N*tDv)VqaUu|9P#_HG;h8FU5d67BCW-K14ND^dA z^@ERtEjPZ6Kz~~reSAlP8aYp@)gG!XbmRKI+N)jvy?=dj#rPeA+a|ug1AO(|y0gyu zZt{iRAJpDGQLRBfE?$u@ckDHD_857oEi|iRR3X0wW+OGzHL~oTmES)@9POfmJ3ual}U&3t}5)^m4qSu;w@x>q1~<|Uf~Ll zE9q~pz+nEllI$Y1JL2XMY6s4Q{1lb9c4`lJ6ZAPvaX#|!aVp9FA~FEkEg=`CkC(?u zan8>l2@(N~-{fJ1EG%|ub)8X-Hcc&I6GUR-TnJlm`Q}%rujqeh|DPqVbe&uI?)3kD z{Pg0;xMlG9(WQp0CuxeYm)AeIm8+HVxHcpQEM=p~m#drK2th&A_0!^d@SfH^*2nSi zHi~gzjJCEMh(=bu;m11pZ(54{v17ToJbeJ0S2TVSDw!O-xCkVF zUeF@-Xpqnv_%?H&l@-Ku{Gfstd8s^_X}(Q*;?wOH({jjY#`wU8EITJMlFc9Z*5)vK zZPYh+vFmX(Ff4=ZdvIRXr&Qxqa&cHZg=T5~S@ev_l})qQYH)9*xa$plKY9ATwt>%n z=F4kqgJ&PSeEj?wSfh6y`A9-y5Ex-Lo$B&lp zAO2p)pCso$|G@UAlP}MF{;vE?m+B_Wn)lQ(5A18I#W2TsU^pvU!D>i_C?JY8min4@ zvdG9VmrLdh#ae`{jmdj}*a#g2ek?Xoi_y8@B?`W)(kcU?$QtsPkX^omK9LO%(+k=q zHgDTPW&=wdl} zjDCC(!_%IvuUG6n7?laXr9Y~2ZfqT(d$4ji55V<{&FSAe>2K^kV4dt0l>I5-&ASG+ zrZU&d-l?(qMBs4j7ak*QTVriw_LTK$te3yf1l0nMzKkdbz#xizVw678mYl1qaD_zb$<#lZDGFuv~Zh3P+=N-Ok*XeM0^ z*Mj!dZhqs2>SsUm|K8udt|NJ&74|Y2erckk`nO$`(PeY9o8H!QUA0=feDiI|Yjbbk z_vm!{Te{ahKKIyseulxdM)2xp7V2NwDwIo?9{CUR7tgQ-j_37UONl+P-3z-yawdgg zJU$o84Z7IyE-k9!kRw$s#BgNaDrN;?(~#3gPQaEQo|(YqyjwG^nLBrARC6BqJB*Vp ziKa%f+w)kl9Gc36Icm1vP@NGP$;J!vVsfYI1LZ!n@hQ>o%$w&SvTu(p>!i?4dZ6Zw zcUnwZ*bw+hBi7vHpv6U9J`J$?F7}~F%J13l^(#s_UKd>*S2wUP{U~Mk@7i(Ek^WEp zpmuDoeD#F`>_4-Xc(v=C)>Gj*o16uEV6Me1(e7KxvgiN2zf9-u`sgpyUrs82xcRkD zoOSSPJIq+%*9RY;`{um({-Swe(yl(QE$c;nT-S53eTAkJYxnGzJ!9X-o$={#qIt1C zovj;0yRZ)3=jAB=v3VV)|5&fZGkp_iw_;vzOi~6?pC-Io;^m0Pb}BIClgjYevg|fn zDU*t}RGTzXi&l^Srn|Dg)K?j$>du}k_peX71|RI^9mqb)aEy$a8oNkEm8)G5x!?o_ z=Q?byS1y^*VGnq|IC-44KP!8^sD^+Sr4@v1q0OCN@kdR_HYI(F(4V|x>)LxzJ*+WQP>zIHS%5)j^Hj&VS-J?B{O#&)1hztOk3 z>O;py&Gx6Eq131L;Y+2Pz4oHlm4Hp{nBgp~UznJUd&S>m5zC zC#a=9txY?`k-ncDikLw%Q;y8aj;n)=kW*G;pOx(04s!8wPo zC2Mxv_~N6}D<=1hE~~a~sZRGM$G6=#`%6cjzHiHp!?p6&?;E*hjx2=Ubo>9ct2m}H3+gA9N-Vi1rUz|BR2l%q1S#@#--!(0>Z=dZK7 z)_m#_r^Tmeor|q-Y&@BJ3vmxJg1A!$Cv5F8%(c{&u-k;`pN+eW&XViG3(2e7CY#D` z>o9Fy91){}C;40q_V_p}AE$J@KFh{H=8L$|9z%B$21&!ROh995<(BLbOLdk=6R?*b zU7HEQpKst`sqp1ry;y0BOk)^ok+VmF13qo38&5S-TdECNTS5cIscCAa82xY_4|=Ye z@+$PKK#uXM*(T1bF7{h2tY!U#Uu~FSezn`=@vGh1=GV~LVAi@5Wa~b6MOa_pPCmfR z;)w99IoqL7++8YjJmd+cDMm&tjGg30M|9z2jX6xC;cP{tV@dz4F}U)SD>iWJO`~JE zaI(k58lw_*auMSxjI6Oxg$^GN7Qp1iM&}uW7sJ8b=>$*d4yMUrwvI7Rtu9uxn6Pjs z!c=+=DXdqZ$@JWEalK;qv-OJoEarE(<3h9er?14@uv=p_HAXY3ir-DjA_ib?$L{Mkv$P_&wrjx<9z%D7t!JF{KE7O)4P!F5#A$<<~i|TZ=^+!=p zB41|RxeIMtGU3K#7x=_*nj(mDM^LuqsShWC+Xzl_Qg5m0ByjU^l6HItEMm9CVB$l| z8b73Gv39C!L)=-EGi~WF&XIOMQM^SxsB?E$eHE4UWW?3*=?uZeK}EW|}2-iz~H5uUSSSJ*F5CXdRo*dh!qHg~(V zaK+M$Ezn|PV{H(#BijS{$EdMcxou(p*na8xS3cuiKLo@Cpg7`0oW;T!KIFz)>0doK zh53bdSrA3QFLmdU1wXqdaAYjQsiK@6e9CNB~?EKz&zQFT&)wMswNRCB3Lm*-Q7&bW%n0vbneS72R8{e*EqGWDoT6 z$=B}QedHhdAK1=!rt#ikewAn59xG$XZx9%u+vu*|&+`mb3Ypa{vqaIK%{|tYv{t>O z!F6Y|n>bf?2)j})*8S9zyTj^B$cVSc%N7Xou#@bJzl$EqgU4GJu`F5ptRf}QuaG*m z9{9$zs@W3Gv+B1ZmLk+>A7&}lZr z6XyPr{vBFfeHvR$wLQ8%GFx+v;yN?tffczE#a`8HK3ME-w^9`RSKnA|shrid&zt+W~}@fttP(<6({wLV#-au)G+(jH>z)&>tADz0Jzpw zsx-_!Uy+LXA%iz;xVMuW!vnHsSwt^z?g!F{bDu7S>xZBia1A%_YunOMFJIygckFn` zs>t6iRMs!paT9unTl(~qy>^b&WMvp0SFMbt`<$qnLwtTyYRNVB5}h?ldVt@shBMG^ zJxsVBHl_)s9ya#ey<5h$g0X(94UHf7UBkO0F_@S?e&YL5VJ#Q3r z(AsG(DDbe=R0ngTf{@^xLUZV=%%>czTLj7KTF+Q<(Z)|LsLcX_MKjb!=GiEInn>Ll| zhX+q-@er2+hU;r((X)|Ro4&g1g%+cm384`T#JjZnW_ht$G!W0TNE>^7q^CKbo#g$p z4{Uxb-wEd8#hO($Cig(*{K{!iH!i8-7qPtBn1+2sw@tQZ=(hGVJHXGyF}@2G(<|}H zUDxJgEE_AKL9uGy5In%l-gAx3NFuwXfvUEE@5W@x+W$9(XGmrNH&oXgj^@NSVJ>#( zYu1WQ7!geIH!T1H@?LrGRxqhy%0+yqGRAX_*)ohD<3GV6s~XzYUox9Kh@t)2#vm2l z$&F!T*Q26l3cD@!;bOx;{<^;YN@wgghkBcK!5&R87VYd>PP?_Va=+!9SxrrDR_Vqy zIo8|cS{trtGSTKX%uvSH?vH+1alYHy*5#OY`Pk2{>yQ?X>0-tW(dZReGaPn}&ZW#8&vT@TI_r~#382LDvbmS^d zsnf5oZ`Q1074(hHFa|FVW9ipMJfNp-q!-_n7}ln;e{J%S?&q7|ni|Tk!;Dv*pA2hi z))IwI0EFimvt0H}On8mhFdJIP27#i*aFM;25ERpr*<<=M5NqYyv{*lBZ$J0r6#IE` z>t^>84ae5aein{Z+&0q41*ddyQp=5Ee4@EE%-pu1=AAeyb{EPZ@XzP!nF>1c$b7?EIX~~3}Wrbrn6|Eoi=aY?-z-D`)0T-y}65{isJZ|gb;=FD5Qy#LvS9n=#<@OP(lDi@=q(VYv02UUA!k4xD8U$UlpLF1v=Id+eg^{_!4S36sKO@jwbF$_N*uBFZlH7{7 zoT^!HH%P2zPTrf^Y@Oc;-GU8F^I(B{Ys86mjRNBH5LekX8;};eU%ZcKef05Tcg@k- zH5hi~jCqbIG!o{^8QiQ9^4FbbDHsdP{C-?h(^x<074xX1Ld~X+`mu|nYaVo^LA>rI zhB;GHVv9UH^QmmZQ_RAZlB!AFe1%|C9D?+S&D8d&_?#y0s14iVu$_@xeVI;N7u&rc zqoHwCm)LsAln>KywDo~dhc%-8%&paJAzk9@3aNrK$BSt)84V{0uoJ61AJR8AHnF~p zd6vA}5>uZ>dGl)%*Yec2PI-F4zKK#eFt&1e&=$Lv`S5u?x!tN@Wwh|K%*D3yMLAnF zMg5#Dee3Z6<;AXCKEvgTgD*ng%e5z`1~;Ksg?Z4?<^`myV|b#LiMmwJU$J7>2d;Z%>VbqA+*WZBnu zWh;gS&WYYhyou9+%~XH7pZI zt-Z{{j()dMei4=7qk+g7J@l-;^q0?Kbl~|n(`bD58cgjg=ZF91A7j*0isG2LyXi+ zzvIWotj+NaM8bUDGHtO`e6y`p%ZdtDKc$Hs76rvx-?2w#`l+h2tJz zBw6^0G}m6C`Pt8G`r7dl*2(QBv6S5}&m*=W<+Zk9Gfv{I+K}vLc0YHe?Vj#a?F)XA zRTfz>*H-TqS$|@Mc%9b}Csk-C1XWAObeT6vbkVowEe-q@3sk91dZT4YB%Ym$8&xD* z;d>SSJrsIB9p)(aytsBt>4udsX~plBM_tX-0>9x6jnniG)KMzKF5m`=&@(=%Dss2f z_quc?hg!cg_H=UI^G^)%n~dakmS3Cv#nz;9aO}XYr|7*H|FiP&+}@5`rh1YumGa-n zse0l4)*JLbKvt_vGnX6rWvmsGcpt~AJ@0tSpCwmpvEOCw^2}DEAMYySUOK=tvEP^+ z*z~LO-%YMAU$mWh{IXK)EfnLl3Og6xKhaJ4tB3Hy9akgtz7E_3H<7-93BED%M|uZu zvoQmlJkEZLQi#uPKS2TXS86f8=-)b$aEQ_lyoQn4B8oiQ)XEwgm05iMy!#$0v44<# zKkhR%hMgH|CwS1xtTVcao8?CN_y`=K*l=Y0{1ee4%Z_GM4N~Y zZYEz;>YR$Szm?wPy@q}NuAp@=Pkv9>&~@KYCW-7RTU@_-vx7&MW-U0u3^Bx7ai zO8U2|bUXdMo<6(i-KrY#34f?JjBoTWl?wO$Pp$XeKm6L=>yzg3PuzW7^?TEI3~rnF z`VQEz_m(&8KANn0%LChAIq>(t`M&BmlK(My*@mJwkBP?yD}hQPc{8*LOKcC`O=z#@ zKI)^I5%x>)Y#RU65Z*QQ@W;lJ%lmH}oESSe_EPQH12?{Y=stlLvt_=f?;(G!jYhKX zR_`HehTNdw4u8b{#*R@<8S=*%p*6I7v)1uj>i(oZo^8QI8!r!Jy!`QOY<=nRG4Ww& zOsTvCNT3|fwAhiONs%gPL!8or&k&}>ZDcb#NcSTeleWzTXJ*p{7zu3@R%l$7Xrc2o zc{XKZ^iU6#$!X%6J83?6^MqPD^On5Dy^%T#b3UC34+2sJ4dAaXs9>&uv=;ti{!^-( zvIgqyrT8Ta2ab|4z8fiFWOEH{`iAfjJ!j(JzI|Ds;?vd>E=1*0>BHRW{{@}GH~QjD zOJ$ldY#*ZYnE*wvBLBEtI!5oa7pj#@%c|`YPaIDwmEYcY;Oohrj>|WHKl!V*7tD6h zyYxOWzajbhj<%_ZvByWxt(bQ zY*{m9EIZz3iHkuMZ_<{Qc-AOMu6khzTiY|PAeeCg(0WNaOA!G@ee4NnHY@E!g$(dDAsNiwj>t^3tAXY1`L;3xk zF&)Zp@q8wEx%Jt3)~Czn4s6;x`b6@n%7yoLCx-_nk3XF}GV=fI{Y34`-le{|H(SH9 z-NrrS;5XAJfyMjTyty}|+kaX&_uAa=O2-*HFhw$svjnlK60rg&$9mh*f@!}sXNYWL z96PN8iM7ERXJ-UsJ)hW8=eFHNFKd&b1~_nEP*o4ZIi7F+}2?Y;Nlp&8!OI1@!P&^3}n8=PL?1u61vZd&wQI+GG>4u)#Vdp zlgxY8eXdtMCT)><2}9jR(bMU5k5vdy&?-i6sT$9|$tvF8u9uNB{b4!7O7Oacd&zlz z+p}^jOQe+z!?fQml4(ARNv7Q@4OY zKbVugOBisoc;BY3%-XM#6x-cYN-CS@dn;I-5SGBgt#WJ>2N#Z8fgm%+r_?q!I+pa$ z8pEw*Y;-Iaj?gx?7RaEVxueOHmqsaHZ%w9Kn+8tPJvf{H^zL1IS21oi8}Yj^X11O; zcYMtog`gM2+lpI>SZ}^jDNoz-w?R zB+!a-n-3w(cfi5+G~AK1`7eKMg=XS)`0zuyaUXy5$4~725TPD6PsVI}Q7;5@^+(Z4 zihK?3&RuAOS{(P8!p*YZF`T3ZcByd^xQ*Z>J4Z{6lfccxN!sP#HB_wL!e298Pk$`+ zh}@OdUOvP@;tQ_JFwcm_{nU_k2al+Q4@p5$39z-Ha%kR)+WmCC_V)@eYbD)2!jVgb zgTSi?2if6YDjWo!@QgiYrJuC>S-gqJy=gm41F=ra$%f)y3+%X#P?e_UHn8u~ZCUZy zJIt|fo?S!d%cuK(&T^VnZzY>*XYnC}_$eZ3cJ>aQ6V^G8w_^Tp7#il9f1*2{HS4GM zbq~-i!W+2dFW4kvYVbmCH+_vgtoVhhAyt3fmf9$s=xl*BaOW(~0u5;V9 zFGzCeUL@!S$!EG*LsXpro;+_OeV}KS@ie?vw#E##a=nGHmyoBk_=JS6Pv}~tpS_zU z7=>`QHL}Z_CSNK~LPpFyLimgoB1H4#)|>s5n@c^NHCEc3DW80R?}M5->=iY7MlH71 zuD4^$wp1tRx3Z2}!!%6(8O~}U;{!b5+3a!rvvT?!@W*qsgw&(8?Z=t*+-7|#_ylhV z?@GQs-T4wKGk;^ppBy+^elmIbzPt7`A9 zbxo-7+(Vy9rETNS?R%2yMqi!(Yz_4d43}#}@w;+4&Pt;nDt?<6AlUVtXpi;6Spc(* zU1h8g%js=H)5JNW^fN+dHTa!@Qv`>zD}1-n>e7nRzoZ%5L9MV}TWD6JWNB~~xkl$Z z_$g*NNk3d?eg!>2YrI94p|mfo9M^Dm(-WM|!!D-WOvm;M?*_*^hEaz%K^31Oc7ybv0 zFcx+`Fkj4p=O}co&@=oFttV9KptkE$ns86%9_-PMQ7f#j!URVQr~P-*D&h<(*TV}m zdmbyPrMzk43K~;u&bkRI^e|)0CplLy@azn&6F=)&$Ui8y;25q-pP=8SPMnvJvyg(v zTEYu;DO0qbsIGLMud;3(%6{5OROE_Uu9N1Rh})-=sDv1e-;!JLMg$b-ks6&9&1-2t z?;yC$lNfWVv^`yArWt1F!qfIQrR_(kJ@^1}I7aQ6s{sr2N4?qT2^d%p;R~|@Ixaoj zIzBsB;*@SnEqCCJu@jo)vN|MIWL~ro_#N*u1%I7x@_I(X-ux2QsHHm9vIaW{J%c?f z+&BrmD`dae$7_ySbL?IrXRMZ9ZKD5-<<|dRq*C%(@HX_c5-i|e8e^EgjoZU!vV_pe zcq5bPv)P^wp1AvM7>o6RP$6#r(OV)8?I$D0`>}O4Zx7#+*73uGcJZ;-0BhpUTJDAv zZveNZhz->P`p%B5!mA1`?0Pb|>E-0Dqlr1MeLd>|`CyNWZ>kUBZu3H;l-H3sJ7eO#7>bMK z&+-UWqWGNpKC5mCYYmSA{JVIW5()BUYG;NwZc?NERW$uwktfqT?j)W>rEG;}skB%s znUWbVr5y39BI*#|-^BZLl_ta={MLtT{Fg?eP6pjgPU^OFsTn!F8P>v_NlU?q(45!l zwML%QH)dF%tP|K5haX&@(0H; z_t{Nv>$$G_^nI_4|7Puv*N%)nnN(}bXR}9jy?=9FT&=(w9lH_R35%(8ZWkSS&x#-R zK9*d#;nwM)%Hh`ETSO!vT1c{mH;`SDo1B``(fA&Z@6+8)iFwp-|)uxBZ=;N<7PdZ$FkM}6$BG0 z{jm!@lEO5ygZzIO84*m90{9|CjpTWFvx%-yzmW0<!RmAKDLfxh~R#|rK}!n9sjxSiNx9r8n%aba{RtoRIoh~e-wUW16skVsXo;F zj_MHBGiDpPCv&&thw)N$b+>ejDHsC2D8#6_pBgBvJ4`cmcH^R?U zbK3LC!+s^fL)0MN0psoZ0SY}I_pH9a-+f*mzU@v_!uYz@KOalKhwBB{9!KL?nx27= zt^G8QFHEfMo-X$0Q(e9KW^oho#ZKZ%_D~pi+ZR#D`4o@$1n%}z8_&3gHpdU0ZuhmG z*<*2fDhu|~Ypv|jYNWb;dU$&rQ@3m-&z8@E zb`c!S95HNvOzib?4}OP`_Hf@{RXoyC?F)`7uB&}t($!Hhcq<+4=|fuT=m=UVhK;#q zXy;=S(;r13ni|E2?DHpJ+P2p8J#7eDA!l-JJ^OvAuSPAF+&yX5vT?S7?~OzB)$I8A zAx?31AMdu-6LsM{k-JAO`2l3>5D}nO5OiuHsY4xFPr5^9(m;CH5gYpKvtk@+htDSC zOblx9uRLMhn-)fsTbQxese2Ar(R&Q=hNGz{7J$xiR&#n9L-Sl=&(Ovix&S}1n?>B# zJWKF~%`Gz5P`rv~A?daE;X^C#%Cbg$N)?X$rYWYLCS8dPAI{x?>$p}^=eLKvM4Y2x zf3AsE0q3vy4H3NJ3N<`CnFU&luB=f!Z)#WfZEH8B9JMz>ue?}3EQO$`sp%opq1*6T z)4NZFFYG7|)wDQIgMWO&MBXymL3G6_4?O2RF|>f}!smwUx+6f!nog`aqVtgaz^it9 z;>{K8{f2sg?rsm;{<)Ol+&Z|ye=i~uuIVtIdJe+7wSCCItF7aDSTJQVH$mch_d*aI8 z)(R?e?%!}Md3)bn^>FQ~t?!!s-H99T+&9lpK}p<#j`JW*rDgO6EYWxPG`&QOk2&s4 z=L*l0<1?OVC_3Xe`QR(Ud1!Z%hSbJ|9&;S+{+19GZ}cz2!9-~Ex6z+T6P zwhXqd)A2O^E?n*#QRQtBjzfd)=jEB=r zI46g@ny?p$x-R^UY=B8$Uy}(0eDZplEBRRMyyyQGiShzn-CI}6q>Ia>iMZwErORoCS$+t{_G!v<6#Dklm;(#?+QwD?l6?1ahg$s$ zcn%c6gK;rwt-TqeFb^vhus^OmnNLG2X@939@~WD><#*e<%eV5$>wQmctn1LOpFjA| zwl&?Qb!O6rKTWzrlb{BG^|VWWSqb~S@UqrfYvaz&9%q17AKa|66V?Y}#kCz{A&};`tQJzpKQ8i@T`O1*s*8+JC$>m|6GT=x+V=dH-nrDQ&BWSQOnJ}khhUH z3dF3mYag=h9JtcA3~>tBbFzIBMBeQu@Z;4hI=`4_l0V-!qgT?%nm{g3l~;hV!qUcG z73yWhqvP12CC!Yn2Q7Q~EtG?=lB{4SY#{Z=B-_PYC-&#q+*hmTUgAm*&$k}lgxx!p z*)sbi5hw$i?IJ9EtXZqVD@N2Q=WEzIH0^b~Cp0j!lH4ckq01=6d_QTex{2q2EV8Mo z;y3|<%O}tRLJKouv9&`sOnGOD+dqsS+nNv_s*SS8<49m^!E<5?D^*lu^yTOlJ`2JOSE%xwkf%R2`X-;peJ`VkY-H(>yfH)iAg_xY<>y-qvxhaF8j*CVYo+XH@w7M~$4q)@h{ zx*d@<;_DHLU->pYe&;cC79x~bJ`r|ZchgXz1MOH}b`csCSwF<~rk}tghrIxvE9L=D zL+o*kfB6IuJPWiGTbCtac8?yy%e2#ynaqNKJ3*LgMaP6yfj+`6tmM=}88W%K)wC_( zZOvSm6lH#5JGq5g@o5*~vUqmFgn|4s_W+;WMK~fu3Lj9i7oaS5I`NIKC17QFHEnD- zT6O1vxxm8+pW7EHX8R>M=@(m{+wch8Cj0Mt|EmA8N@eu6r265*^R4&U*=Ff0nH|Qa zi*UzmXK1|`%c2q8ho~ni4Y(F}g!~TpC9$YgM)#vv#zS*(;4A(vB-b&I1@Plht&DEZ zy)BJ#n4fv>P3cPVsZ(U^<7)(nns@SP8Rsp*h1akv`E=!-2cJx?>A<>$R}4M;5gJ=9 zQ?~QgO2-YaPKbA9cKEb)a<+$#_Plq1yfJ6@^$ZBh7xWOK(mPT;%k7#MD3j&o3Qo{5 zI|%|#qEu5!h3*BvvAl~Mv;QwAT#>njL?RD?dq1}k*Q3G{eWi!^^Ai8&&sDsyT?^W7 zMNTAuIhboVLZ_9s5+=ajv~1ZUtAq$m+)w7SkYw1Si)^_4{YCCBor#k#g)Iclv~~QBG?vX!oED!i#xZqoXe{833RzUo zWkZUuqm6HU>uC4=5MhEnki2z-o`~rRUOC=zVqN%1(mZ}+<;i4fEB2Z$-kNX8+=$%N z=q5!aqZQht40}0CXWb^qzN%$2tu9V@q4wC{)zxFkTl=fo33UCEI&Y5L%2R8l3U3k_!`E;`EdEuBm z%p@`!Oe;X3Tj39IRD+RCD+rk~YZ-7GXA`x?O#q1P!09g5dE>j3fzRxYo4>{;f5L`i z27uz*iclmWRrNe?WZqF%&1Y(}$IiF>Sr$7iZTXttwBVwBOwN(>t}bm^gCnOIiam?! zDVB(@_kXv$ZHo2OaOJsm;616hoOD?NMWzu&-&Y-_)Co=t3)#k`yB9dMhA?W{rz zd1}yKs3_SN^+=$J*?Y>CC~kvuLy%woD`eNR^a}Sfz3uEV!<1V^*$0VPfy;9G3Abzn z`g+n)obdqcFx(p{4-kIh+p8EoR6~VYAR4G||3K`rczy7s@CF>dX$t>iUk7id87e(G z{Wo3zYUuH~e?Nb;d}Ha|#2vgc7*+NahEmI>{jxmpQ^$ph4^~J2a&P*}UU`3~6SoI) z>=o~+D<-s-Pt7gc-?%Gl)5*_kvQFc*aI1}2le!RD^Kk`7NA-KtSKYPy$jak?-6vit z;=zaKmi3+I)j)}TvT?HQbx+V9Az#fqhjGhf#vz*5fXwWrs!aAvTZX;rLbpkYf9#Mbe0$2c(!vx zf(hex8C5FDH~IT30?YSs#BW;ejEa^vhc%IQpC*i;@o{F}_uzO}1+#%|#BHsphcmrE z!J|k$yThhj+aXDB$uawD}S1607w3Iik z`y3&>Z?C@F)6az1QG+cnfN8@Ea}(OxJ!6vQM+dSCyL->OX8V#~eg0_qt$jc2+j-={ zQ9oKJB89GZ$7jMs=7dT`AR+fUlg6$!x=R7o80J~HOOO1A`HN=`*S5@m%&D?9W!$Xt zsipk4n7AVgBcCHoS%TlowvGMW8|ZI|hUBV$h` z*M9i(8@@Alw7jl%cL#QjGsv^n;01CX znQL8Kog&!ydtF#_U?oGcpJk2Wkiz_P`f37~pFTu%+ne5vFY?cM1KeYRNVJ*$FUEnoI(#M; zYg0QRf6N6~72jfGMOa=qcIKLsW690O;Wwyt&XN-|L()mw88Hpy1{#lL1C`6ZT!(8^ z5jQY@VlN5)y40!KJj{^*>d-JwaZZlwIPr~^dvrHfN^Y7$_8DHN$^D8qs2v}PwJH2} z-nn+EX70?nlt*9rk(`L;4E2_Qu(q;m&+_*DFb>a2HA(iYtt3oEm z-no7E`o82{&wp|a-+aS%fZwdadn4bS{)6Mc)15_kj2s@--hDD?OY!8qb<3tZeML=o51$_}z|M^&1zC$Xk~F2xTZ*GbGEj!nRc5?r-+l zv&M_fNhHnAKEf}67Q>z?Dk-s3ng!jS%`DL>soZ)TmCkE+pjy59@#Xu=DU>XWh<(&5X;TTcKm&rF5tI z7N?c*uuf4_Xq8aec(xw8sEdS;UfE{nJ4Vb;&uyEXOE`8=gq>l zjdor~ashxDf5*6qtx4rDU2$R=Sw;5RKp|wFfvw!*4U6jAFOxp`d5bVrQK2P%fhn!R zX|^pxwl9RAR-(ouao1Ny?6H$-%-}g}S;$;+wF>mBJOy2#J9$?Fb$p@N4|W?G7a36O zR)bfd?cu#3w>femM+qHa&w;C~k>QjaWvC5sM7}et4Of7SQufQvpaQmE*{_g%D#Y&Q z0bI_-^6dQiwUK1D6PEDQ+`NFsXdzw@E@bI~-w4i7UzWd-SYw}OhfHpisM3Tb?@5D~ zgIEQg2Plo1VC`^f39D<$i{NR?pg%U+VU+=E4MCE(wCUYE9Q8`Q4{TQ0HwvviW(KMQ zy3CBT&oNGtaqvFZ;^PR9<&PsR8ym;v)BN$=9{J;jdEOo=+$JA(OmDaKi=1Mf<#ys_ zXxEctSuj`Jzv0{X7Lxla{e1YHlquPEZRuRBU>DLZ;-+nA>HizI*`Q0 z${g0r9LJYI^Jyb;2rO9^&H3AWELB!)8+}{G+6{bz8hh-?0&lU9wlxtwWsWA)4s%SH zvg(`lr&8NOJUNr*dLUo@o~_3`A>sZQnwjvQvBZY_w<7RF+CX8O3h3=-v=EhLozK%5 zw?t>bD z4`o0X@7MdB3ymscx6oSiTMLx4#XAi9@7i9tI|fgl=fT7NTwDTN=-I8a#}YY-$qdHA z&HK248F>=Cmrp5`*E`zW39mJT+bnvMMhIP z=lA6szx;R2DNJCqCK3zB;JZ{r+!K;<)1vwQBC>I{^j#|K`)2uz&`hEw@cVlgZXjc8 zYg(7ZdVjvRC*wBa>1o8}R&b$Wif{gUa{9;Xe>{H8$djWZqg~0$iE~;HeNt+FE;D>8 zuCcP`SL7Yf6Jw8$o?G!paqkI>)mgD$zn0{iEBV^exa{P{h3aARE*@J3u0NEBXh#Gi zsmT9^u{vAFQ9@HfY>gA4nnKU;ZK z@k99DD2_QK%c@qUiFOlUEjXU!+GajqZuiK~%W~F(d)d(tc*NCTrtTJrUA!*`NV3MZ zy_IjpnudKh^tXA!hGIXf1@Kc))H9au8+}3Sxe}4exO6ZF8-=`;y=7{MXvN;=_NxAevvar}e73`6Zl)IbUagiNF zjW+g+85|89*P^SgK9U>KbfuQ z3cqU9#2eYYZsH)UJmNUPlwl!82S>;ae!LUfM5jQ+p2<_TWT7(S+xR?1K}ZXp-BZ`gSCR(<5|}3kH|wj9$~F<|M20@3?z4VJp8fok+fn2Ii^yvp zb!`};ecoJB`Pt8Wd2MYlKR;l54)yvy(EK6a2l*nYme`+KCGki0Q!P!FU&Q-VrnR|& zayRf!vOFVmwtRAES*>Zs##Yyl`nN~=PMj^ zZ`F}py5jEje2b$C-?kgYb3gU@Yn_A@B5AJluFzRMtRX4@MD9Qa6ZGIzup(;QvtLwu@zZ}&&`D)Jx-2)YEsYD+VFd(QvT%iy?H^dmJSo)fUJ=h zXXCiaO(jme(zqnX=#SOMGogZuv#mi+H_!8{$yY|&2Uz#B9?Y|M=S_XO^7##aeqh=2 z-y8ck(|=q&THf6;zU5mmT*KF=fZhqrzI%9iz|6>~;o_ky0%NzM_-DPw8 zH~qps*128D57+%dE41WQ)svBXuUG%FZNMteV(0V)FFa2QME#e}?^@W!3BNymKnfZ4+ZxZTaOF z&OdVA^W!fZqm$#CM?1;W86uvD(P@Ze|BHR^Ex)h&RPv|4dBN;ZrPA}mHIGiWzomQK z_mh{_Pp@B}TswZj?9sU|^gh_#oBU{7ZSSZ0+Aq0z^S_z?w`>2Z@A0{JZC_#BCGVc+a;H1Yt} zxLI|2eVi6~`7jr{c=%BaThSZ7^VJ+SEyx4G}x z;uRv3?`DyZQ<^TV zqxo>%L_2wv&`|!}wRk(q~TrL?LMp8r0h#sD0^KduH)jg3C_P{YrzV+58WRDgg-0W)@& z6?76;{PAfW)U35r4sCU5J-uDo&9?(~sPZ#=Z#X_%$*4;U>`jLDhr_#iMfg3;efe@I z7)hM2D^xBWOI99l+4QBkdk3EB^=)8GQf2K0Yqfo09Bm1Sb7x2%WGov-J$$85Z9Nmp zZ1dZr*(2*nKHqL%U2Shi>+b&K9b4DlW8$m2KkQp*1$}T2FE}fXv`onARp7K7@)sio z{0MmXO0(v4mgaox^BLkib-G*PBA6GED*qM+o7*8rwhV>tELHCVnzjgTzSf54gx*aV z{X^Q=<@gZftaF)hJ?H9X)r3;zAuUWB64KtFViBu&Dy*{Dz^* zS4LLsPbydRKd_y(UREXrvk%2XW{z@}+GxGQ4dgWdzj7&DKM{k7br6rLdCDqe!9w(g8dQnC z088`o_3aY)wat9)2=uV)p_y7OWCMAx67LBBA0r;Z2^4sQ68V^%DPGia(k!UvG4IpF zSpGVJ>b5SIl|eki@0COZb}YH&_%GkpmHff+XL?O}XKlwTtknS5q_xtZlVFK)@Z(z& zbIslLmKEZ4>^3Ah9-Eu1&#_z#s=2oDs*uLwdDZM9CFVMT68;M1olx_wm}z6c#i9FO zT8MY>j#cre)({ufN-I;ImRLw+yf-}&3Vy)*y2pvnupiEqhkgY<%dR;u;lCKg!~CbT z%F@V8M>9563{OVhsXop{?gOjgV=1z%{t(U=7JXUKAf_B}L16>jN@*{q(Pic+r3NUtS-Mf&rt6xYva1o)A;5 zWAdh{XOOMhnOcaE6MN0Pa<9 zvi|ptTr={m(a&xBQ>TIhQo|WY+&Ht3xJ$B+@K*%NdnZv(`&jk1(ZjX#pMPlopCv!; zdZ?Ev#y1(^M&1A1w>EjY=bf`x?NZN8<61LY4ldF6V0Y5Gj+Ar|7|8}q#&ogxkM6V&Qxtl1$xSG##-o8fpe31sR_a-i)k!qzb zYvwF@{+OoKvU`LwjFPd1tRP;*4EO}K(i2{k-mwIYqddkKhiUA$6VFfT>UdOn_pJ+A zHByK!-~-$P#Z?7aHxLh#=A5BbX-+lZ&6Jf~N4lVgJi<=;W+i=gQQhu3`eqgVHb}p9 z(R1j`ecnvr)q?NgwK4Xc)VG`Zy4V9}+zo*07*vyROzuNOyC&iq%mca+|6fV)xVofi zVHEZzz*#u|gI!y+zp8X6!NqT((L>qQ@Csx>ksg?Bj2ByIex_93l+tIf!zuNx=gM@R zc#k?feSfuiZ^n##7gwF*j=(lkW{*s)%k|JyZm$+vZLH50uQllBwvPLPZcC+x>`5_y z$XOv<7PPgTO>LqT*-G4k_pjqDyzGC)#z8%RX!Ai2Z(n2sY!tG|14Mt{pIJ6n?d3Bwtn-%9`_wL&<(*9O9L9cOUsAcO z|E593sxh2~2}@{UXlr1y^k;H-#Wo~g+tK;bKyvTE)%%}FZk=f}=*gHXPlx;}hQjqw zkI%hh`(Mp-J=7z~72`ji|6hHd=>&hi*n0NFqsgZ$f3p77{?By&+Kfq^B7Rj5X^Skc z%3e{{(I+pbrP#CVhxy0%H_SC<9Q{*-@Ks@9+!?VZ$UgnUR@prH+)WZMe!HIyXj#ya zh+oI(oxm;R$;xSM{AI%vUF26wsLpWpE#fdJYU3Ac119mQq8WyQ45|#WQCMA8xB-ASSGO5kmd76!|p%;enTi z=7x@u{`yg0Qn`0vX7D1~mCd(?CVgQG%@|J3P|D4v`#kT-_q*W-Ba<^hpVNVuWrCg* ziCj=|BK zYm+z+GS~1MxDZ?MEQ*h3%e(E>x%xT;wcYSULKL*ETAn5@LN{~7`l$tc%$gQx$-H^h zLnGl{riJ`vYt3v;sMQVdB$3Hgjl*#s;%AY4Ko;xCPen#tEoVxF>)$iBX69XT+VOlu z58c&t^0E<(t>hRa!@&AQG)^dwFp}!8Ehlmk`5H-jprxxMN!^xgosfAslWP#|iO)RWC@a^1J&dg++jgEItB2iEd|N->eeht2v_2U}+H(P9tU3B$c z;UVFzdVCWg*Jr>|ot(RzO%FHZU-;fETaGhPt46+OqE_4g694^7)M{Fc{HPTbxVWEo zgnVc@%K~2(`T(99?h#deAZPGGUK&gFnMl^9jYP7h=VSWq;!~c9E=&r6i+%3R+Uq+kZZKaI%P^|r;!Hhr2m>rSTVzB7@9diMVAsh#^cy&? z;9MS7EVMhzHBASPJT~*yp{q9@tzJB{HhFH{S!aDW`9klHKHPfW{ll-_y*_!*_=Wd# z6!*=!&f(X0cTm;XC+44^v%>f9FMeVP9)j#M%@RIr{msl(xg?l$4*$;llXKsge{k!+ zaPAevo>%zx!u>=my-5foh#!KALWTX(5Y9Q@I)gXDYvmShM$C)h+NcG_-dl2O&^V$K zddaD3(D4_CKez3ygZ4NYm4|jqTkreE$b;SI9Q@||-wixE{m{oB>gC-b-alQ6`ZL@# zxtDf|ViBCbGFMo%^z*HzcY;c^o#Y4VK9knbOPprw6X@P%Iz{V`D?a*iXM8_Hr!Wg6)o&<`V|zhj8_e0c5^P&aGk0p!03Ncv*M>SUXpuIW8}@wwS$CLFi@%b- z-$p;6WlQO{(yjFW?bKt8zK1lSvI?5w7HWZ;-(26DGsGcUxh*9Iy1sM~;d49vTx9KM zAy*m7iy|KYt)%Y@93&Y;Ek zt4MCAy?q|63Udm-i54RXU&(&7y=yJwDXqCb?}Gc8S$+zAu37cQM=>>=KNikr0RnScAO@$Mef@o^mrugMCczrW`e&pz|Lw79n$oCm&)Ta8~#Z^c>l2I_Bb zOnF8sB{@PA{SUt0OR!?nq<8*@WH7W-(?v5iYqo5;jEy6ntnh!MwP|h~0)6kx9p<9D z2qA3!6+|CM2Woti$Zo+ zU*LdhI=6b}3ZD<&pI^Z#u=8;g7%}VsA$whI`uVG?zNKK51&?jMiH*cu^~p1@dOdxV zr}eH5ymc`oqj`QroF|Zbzz+Nt(vqm{mR)Z3JJh@W#o_wuGEEP}pSf%K<;05ArpQ}e z_-}s8Q5Iind(i><4f70Q4BUr5$dL=kP{2m!)t* z`*`{^ULy>-)pp=Vza9?UYU1N#ixxKb0}^Us;CJCE%Hn|)l4*cqtUVJet)5WrJtXVzDQ@k9-UX_?HP@_oE#yJ6GJp7K3*n;=n> z5zI|HiuYDC7n#}x^FtJf3|5HaSRbL4`~Yjoh`FoaQ?%RQVjd++rp(o{c_*yn!N>7F z?mRIAtX@$J^7$o<6~=Kf%ZC-hwqA@yX5x5-aFbp!3xFl*F6gbG7U$~De8Gc?W>)a4#kq=>z zC^emOwA(gY4%H&DK9J~$&sv2oQ*5P8o#BqkEANjHvRZztZ0qH>$GWH$%i`rC{9(>_ zD{&Ot4Vw$H=8n^PelPKNiuP1#5I+gBf%C|0Q{6o=6Knb1S)x8=t)u7}MU*KgND zTEnb35Kj=5NPcU9s%LP;L%>-UXiwRTL59J%!TAxZLjCd|Lcuzt2-{(1^YHNY@9kSv_a)kl(cTRW!zvJpkoHU}|caea7nWJnXe( zt<9?oy6X)?zV4HrXy^7*FW&D5|JwGoOpiNjM6(@6H2;o`2x$O~mE!D`s5i-Uu<2yZ zjr$|(Y<_FvX+Kd+%EY&N?~R`$lBi#Ea-la0vq$Z>#a=IN&X5d#w;{he7IIW9*Zk%$ z9Sim_OT(M91r6|1rZKS}Z@%-mh(;IAv~Svy5m=AlrgHPXW8QD$b-{>O@kVdkf@cAn z0M6!{#=y0_vS;oi!+BF#3#N&=iz_E!vTt?jNOLuz+e-9SC#;~afgpbq0UhFN4z%=F zQX?Gy8CE$AhjRpSH^vCvO1Ct3g#pKqM~Ho5)Xbo2lzCZYLb2#xu&l-JuYzpjO@*#^ z8umEFds}{Dy&IQaw)r?s`f_a>-7*xD*K1OWh^7&3>-%h`of2;BB#Lp}5%Z<^^m4wI zEtOQ*s+J1fLvDKBzyg+B#t{hl@85Nyn3gYYcO?rWC$`#&+rS6l-6@LsrwJEmS5xkk zKTr<SV!2tufY6Im({TB#jPDAvbj~#(v(=Tt{~#nK$>1 zJyoh?;c8U><+5I12T>JIv>5+#7KTC7e-m)PUmecdA3Lts#A=E*61|JOLEgw+&fMbl zA)uno6E^il$7IRcIL&zH0#4mzmwHGFvGyYr*JCGgqQv!7sGT(H8=;{b?Ewk~q`IGNebl)6{%vo4h3f`jqY-qyI@Cm~72>YUd z+K7G;DvON^tw5MRv3~*X-tJgB#>C|i)1I``4(n?2mRHkf2icdnPj70!um)$m&)Ajl z8WpoEW)37oPxHCvEW{$4PtClA?%ag!wa9^dnrm(AAd!hIU0kocqq?X@_df0+DP!Hg zlj?O@75$gzHCjOelb75{CAj<&l3#i5KOrpGFdQ%<89NG29@l_War}-86hJ8NZg!#rY zET9uOL8D99ihSNcKbPCl)BSEG(FOZ1aSn^i74GkqdhXL}<@#zjzi~sA-&^tKT|ZND z^Vi4qH^2cu4c}&EsqeJ+Xhi$Sr>QT0RxPis8*M8ck0~#rn5B)5J09O{8bB*V9hc1N$$?4e^N<))8SX9y_xnyaNr6s)pFQEPGl#VN_>v9xOWnhOaF9~P{`DW zrWNx2$Cc!p#WOx#C*6PiX;`=qkw=P{J*+QG+J*UwsdzFYc3DUHG;um(-!#sJJY7`6 zdY-XxVQvNoow0DpinNfGz>T?l3Jm*=xG6byCb*k4pWdVy^36fnGZs#A5%9^dmwU#- ziO!bKpN56&rd@zr&)B%sug7haEyS5-o>cNqc1(5hv#0iWMPoSFI9|~+R_=_I<6GYm zfs1`Y1f+ZWXRMrf%V**^*}4DOjN>+tjXM*`?fed+qL1%~ZHl28D!*{(f!fJOeyUtPSRNb$a)f-OrX@o5Jxk zk^DvgzG)K`$33N+34YNx5OBU9)vBPkdnQs(Fy25*X!+v}Ij>FHeDW^3yML<@4h84{c|o~(gC+9ex)<&ux~w`@Ld zR{4?7Iomd4ALZWc@nl8#ZroS8a0l@HlScvV^6jK>QCP0|{kKPk!Bx9Dj+Rv(bPl0Y`KL~@ zZC$5&5RztM|F1gUMehr~tpE3VUq7(C+n2WDvTctj91$Atx`{PAuJ*Kuz2f3 z1qa7qg$|CrI)BZ`lcNu8Usi3K_^tVk$wvl?>kik>xxSLjxLo>b@|BVH0n>WBTFIuP zFKgVFZ|4wPRmZ9I44n{gE!xfG3FAx?&VKU=w|dT54wKEmsa%|hwfXLjg~(`qH zGdcQ<6UX>m?E*t}@sfjh}|)7b*tI1c{9*#*@1$t|dHJo%1^*mK+q6oafQ z2>xWty%cbuIrNSWa}?1Iah&k(`mpyh5IK)#^IfdBO?lf^WA5f!;9gihzl+mz{+bBS zF^`z`wYlvn#rrK{rV0@;xoZcnwzuTjYG(1jT z?Is*X91AHkWc=b*9Ti()+W4|#>MZD8+jDR&{nGm%wgj5k*fZ!#X(ARsoEh`|5ZA|0 z+ro4Xorm@{9^ZP4o3ffxTZsHH=f*=68wi}-Dsop)e`@z^`VXXeXqytk1$G{dwSoPe z=GIIYHHLqWpR&g8Au`Si1xRtiIaai z_THq>eu^#Kn*iDJPmI01{=uyqlRw=2!1li!f6w?|Jiyd>f_5R=2A0kJ>q=#+KY7R2 zwf8)g{A6hDfl<17$A@LoGVB+?rr@1{$k`U(<>`v7YWDf?*jhE>LHM4&<^bJ$8-J7&$&2&~`2{senF?*0UO4kyn;vu6!GCHa_8Rz9}w zJg+P}8`A^+dl+D&Vy#V@W0hce{7MCxh0h~dYr~wA)k3@x(be&B>Y*KvTTc%c59ZZ+ zAn-dklgiNi1KaJ}1voNHDo+i>?acb5Yw*GD<|BX8^_}BMhjTopJTK0J5T3v%xL505vN)=RB7Q_^I#&~W zcb(P4#whtVp0$^mFJ^0d_Q9`=yj**H?y>pecD=aWT})-Mw=!gn zkNbZRq2L}hJL7wOPJZb6)N?TJ%}4Ya)80eI4p2V#N-l|a_h&nPJpaG?ez%izM|n59 zx8C=ak+VgJ-{1VHp|cJS&Og3kbM?7xKW&MDkA`=g;zZ)8_x@mb#HL^Ed(>es5G$s4 z92NHiwb~~pDOV7ltc7Kt(S8T8{mhpgv9Z`8a>wYhu!aXKW9{=Q9BmGO-(Y6PP^AD& zU}eJInN1*p8z!~w8H2jK zRz+4JYww6XPScYUZM!_x9Lk3n)8`0ZoBH_$Tf6u@%r*AssWmI;X~PP|(lI;Rm8_gN zr!`&~#u3Z@%9m%p-93=BAODL7Oxp?V)I7jY{@wqjF0d^k{O)gIW^Us zS+!ugQ!zj^wdZ-d)SlV2ay_0R)gI<9!0A(alRYnU)ufVoHR%eh6W{HN_mM1{i`DF@ zB!?^b@-5b4>v0>gSF)O{)3R%G{WvmP;>~(!j_zbM*P}P}t*ck<7)EOw{AkL}8FV^c zoIuj*rz|||Os@20I@N>4s+20^L`3=P+W=7O;OP_ zSq4ZsQ%Cp{w*>PuK1)$g{hHeo{*4b8W5!odU?^rGjF&IOUVgq)_E55Vi62^|Ep`)B zzrh>eJrtXp{L%cZ7N{X3+w+$<0?6EXMeMdF4&p7DIPks}Y9(;PC9=8ACsq=)gcrrt zNiqsk82)bT4c5|<@i9H7(9UP~0^ex@Wyq`82L71aS~=r{IHQ_NAAbWQt`-2tCN}aDuR_* zh$1vY)=u;m=jKhVp>vWOCU|a2^)^}qu2;d{zD*b5Pg4_$=FGZf&96I_UgB>-!-RCM z%lo2%!n|&-skCH23_4j>)!f;aRHQNWUlx$X!kIC4}@BIrut1pe~y~)R%le# z>iXO7o?+b0Ifpc@NhQJC&7MhKZhdy%tW~*wp)xP~cKCWYQtxCn=_WqE$wz80lvBAXJKW0W)UYLE zx`bCpEI0NZYKFg*Wx2r-^-uuq-&^{%^fbJ?X4yI_HcFNySnB#0bJf6UF`Po$$d7B{ z^5>3Y`_b*B<4{j$wsL7%Kj%wL((i9ZRoIP-;(g_Fkw;KUcg@vXZ2Y!}80}@JA6Y-2 z=Ag?`-pSCF9BTc}*we{*&p$DgRG#j^JMJ#4OuW#WJT`N9zV*K2+aB1yIeFLfuigFn zfg4`mKHZsI@sZnh7SHLgA|8Wfn@KZe*fZh3%B5HPKhybZGrXIroDj~^ZY2n6v5|9Q zjQf&beSXjS!?iG$CRE*7#NK45lY{IaeUEcg<5UL=`wTqqqVL4RT}e;D?Gvf3L`cZbWPK&f2@-RUzU>)$%U;F!-XQOH zJ(gU!;nwM&jK9*=I?!@tPsissoPF?U`Ac($2M+DZl6RY8{&~(Y+^}p)KEbZ@$dgX7 zC-5Qpt<`&o+CKk_O+l_1IehjP@^bk0{Oo8_JPwA8_2)a67mvU2RH$NHWi@|=S-;zB zu(#tMCN?G?e0_fHRl7d;`ftv5)0>2NwX@bad!J4?yUXBfS(h@s6Tsvxt)I%j!2@xl ztf>n}c+}*j(3z%~^*{yA<-59*!vnu;-SnZhf+L@Lt%c0n=Ep1waa^J^^?6tAh)EH@ zop^Poufp$2Q?BuKgWt>LbFq%9wPcnqr($Os5qFL3N^h#G$4MG(tQD7h4wl<6n#NIM zaO(`-mI z5q4iZo)L=U;-_!2Mt1p0k#EejwtB#--0+D;r1Lqm9fyZb0H&9>nj&?h?j^Z+dmuPISl*#-#+UWfteR(&puuJTzFabET2!j@ zPH63?71%}EW^1|*Cd3xn0fr45rMV*?i--{WvE|ZGe zo42$p&)j*~tGX{e4`tTc!lRXl0I`ipEl7Blu0(s&=D;WBlU^JT6up6v?`&_3qs{ss zH*z&?L}S%A=oMa5)_$=S!OGo0|Ag06%RrBtc!hM6E7i6w3uiGGv-=a{EK_n_ykTwk zqois=rcfU4dfTm?qt@MgmRkj`H<6`S;)!s6An#;WpzR7aQnkx ziaFOSHj(aKMOLbvTG4xO(>ikQgPp^08?;i53jHQBVSX!qnedZuTV3e^O@Tk(02KFw znKNz6Dx+WrIy*0v@5=%&`O#Sv!!0~Zccy}4IKqdfP}%o+)zySWb2_LLD>e(?i}iJe zOQGyJ$zE$w4B~Xexb>_ysF{VEZG~i3_%wB&j<}P)$D1havjb*7+n+O^xPFHzFJ?O# z&6YE>Mb?bMz1$NZfX0{#Tpw?}fkSF(cm}X-s7ipQ*+XzZ<5se5aw5`w{(gEAw~euW zmzORNWFCR7X|J*<5wfF86)A)zg6+QRa|wl2n{e&zn~BR~yjql}L4$n0Mysq94f8g7 zh4`Dl2j(H{O)fIM?Gdtvygv2%Kqiz}JuGlqDlZ4HPPV6mF=X9zcLYAq5XDWa=r+ie zqzl%RZXv${cZ_AN9_|^7uOMtg5uXYe$tZGT=S1o^uxG;_9;!YkGe%Pg;r$~(kv1Va z9iB(n7XrrkDJm;MZ{T3^lyYWxbdxgm;OyJL*>q&A25MGu2b1n6#E|!mm^`!@l>#@O@cU)9@)@UxiGgxdi2qED?ZY$S zz@oc1C@y9u_GqDe9G?m^^KsvtJ6gSFb5^#~-t#jvN{}_li8Pvj0}S(gANUsD*#Ldd zc=Fo|l&VGYY$n9GojG}9wCBzOJ29bs%FdL}vrf zAvFTO$Sk?SB-Ttl1YR<~{9XXp0`na>HQFPXl=BS`+Z=~Nf{+4rpH>P#V zA^iLZN37X$f|f;FpNlaQ+xt-;!8|2oN@7y^*uaLhNoDV$b1&gc6!X7U?Ol`Bj+z-L zp_r}1@vY(>reNbZA4_gI{>yiDC4X@InO@#k=ADhj<1A6P%UznyREe=|Xgm(hgJott zbd461NzdaI8*|7y>Y9stp80&Go(3x6uuF$54z#n%Cv#p>xp&~@+BUjl4>_>K@S7>K z$nA4gVW+cS#p`F%Jd|aJH4FDIatgCZ-aXD0zGZ+kK}#}sB3lcK5X*qOQC$<=(%Me< zr>rimr|2Mi{kwV(bqdDckfgJsaH7TiiJk3Gmi(u*@R2g!S@XJqOV z^IO#*@%3z6i=0gUlQ{OKg}JXwXU@E5+l=_k%*?t=LzN=zY{RaBU(Nau(aTE1Fiwl5 zAA4yN$=*Xh_rf-MQ%C#svExd;5Aob+4HLaP>!C z?w?NyhAm#!Zf(fNQ>ii~L{_$by)Bv!_mYpL+IWU|M|CyoCH%?<-bKHsc5v+e*+-`z z{`iac$=Mw3Df>}^8$OrDN)*8-Z1=CN!&h-_hgNOE%TvzCi!Zu@oZ7zN<-)26WPdlq z#9^BB2Jfm##KQbKWM%wp?J}D_gWmv1uovrSXMA7_?5*!tat=$tkCSqCrJdSDmF-=}A`C8=C7 z`J=wYW?SIp>`YgLz18*w85$sdDL#Tpm%WwgYTD{Omjti7HDJoHi~b}{q1iY z+J!tH>(NFtExd|Fb0*+J_>9mEacg%|N*lb(M{@$ujoJ4*$!P`A7&wE37y!1*)U38G z2UqjypwPaa@H|5Z=Tc&;Sx+CezR(#lh{f_R?#eSBdVDoKi(Lu49`D4A6@%w{hteG z)?U?ryY|7t^NpuJeOlY8p2B)%d;C!8$i|V$uG*u`{QM_BOu{<&-T6}V*ZuM=W2k?0 z@t2H=ElmG~ZDZ(E$BH+@w8u%@xph3dJ@GO+aP-51p-4!jqvA^URlntw#cVglwZ%^|P;u zh;$1Eh_rfwfZ!#13fyDvy*yI_RVA#L7BbWx)rD&Wf$mPxOb`Uj(3~#-gxE?L0T+% z?xA^myD2+sUu~~3AdPo&H>YTGx$-tgE6PTK*q)Ry#&wh?-~6mBmGHp1^hd6Rs% zr<09FR5>8BlCpp4#7Hy z6>ny(ihXz9YR>^>^`y3Lk&X7~aZ3)_2gpMewI>feajH>lsKtr%Av~YMhx6&)%$J#A z{5=g`dDk0l?rD6djSU&aBLCUX%42Wbj>{-r_%rc2+!{)L(KJ4yO&Z^d&EYHY1?rGGBnJY%FtnaYFATetn)9z#FzvQg*Q2 zIkTIMYu|j*aV{xTlIS&8(M;qavh}WCs9ynsXOgF4cz};!Do` zuY&UmIC4jW^kM`a3wT3I>mY2cBlyiIIw3CJ2QG?`S??Yh>LXG4+=HI$$0x)!&-w7K z8Hvp*t(-+`=7XszDLHZ~4Q!Nwz5$@456}3S0YXZ6(vN5P_;(IHnZ>hG{NytJ4&ccQ z{?FlCs7AUo+?K`7(L^b1P6cwdr!g^wpReGT8${n1VHq6;9>zVo#y-Zf_<3J?*p;9D uXxuOTAuIU^ZBs_;(9cglG~-{h4e$nf9i>bF diff --git a/check_brackets.js b/check_brackets.js deleted file mode 100644 index f739e4f..0000000 --- a/check_brackets.js +++ /dev/null @@ -1,38 +0,0 @@ -const fs = require('fs'); -const path = require('path'); -const filePath = path.join('app', 'lib', 'printer_data_builder.js'); -const code = fs.readFileSync(filePath, 'utf8'); -const stack = []; -let isInString = null; -let isInComment = null; -let isEscaped = false; -let line = 1, - column = 1; -for (let i = 0; i < code.length; i++) { - const char = code[i], - nextChar = code[i + 1]; - if (isEscaped) { isEscaped = false; if (char === '\n') { line++; column = 1; } else { column++; } continue; } - if (isInString) { - if (char === '\\') isEscaped = true; - else if (char === isInString) isInString = null; - else if (char === '\n') { line++; column = 1; } - } else if (isInComment === '//') { - if (char === '\n') { isInComment = null; line++; column = 1; } - } else if (isInComment === '/*') { - if (char === '*' && nextChar === '/') { isInComment = null; i++; column++; } else if (char === '\n') { line++; column = 1; } - } else { - if (char === '"' || char === "'" || char === '`') isInString = char; - else if (char === '/' && nextChar === '/') { isInComment = '//'; i++; column++; } else if (char === '/' && nextChar === '*') { isInComment = '/*'; i++; column++; } else if (char === '{' || char === '(' || char === '[') stack.push({ char, line, column }); - else if (char === '}' || char === ')' || char === ']') { - const last = stack.pop(); - const pairs = { '}': '{', ')': '(', ']': '[' }; - if (!last || last.char !== pairs[char]) { - console.log(`Unmatched closing symbol "${char}" at line ${line}, column ${column}`); - if (last) stack.push(last); - } - } else if (char === '\n') { line++; column = 1; continue; } - } - column++; -} -stack.forEach(item => console.log(`Unclosed symbol "${item.char}" from line ${item.line}, column ${item.column}`)); -if (stack.length === 0) console.log('All symbols are matched.'); diff --git a/check_stats.ps1 b/check_stats.ps1 deleted file mode 100644 index 347a6c7..0000000 --- a/check_stats.ps1 +++ /dev/null @@ -1,37 +0,0 @@ -$targetTs = "2026-05-20 02:20:00" -# Use hex escape or similar if possible, or just standard string. -# Actually, PowerShell strings are Unicode. -$kws = @( - 'print-retry-compensation', - 'print_retry_compensation\.js', - 'retryFailed', - '触发补打', - '任务执行完成', - 'SCHEDULE', - '/__schedule\?path=D:\\wms\\app\\schedule\\print_retry_compensation\.js' -) - -$stats = [ordered]@{} -foreach($k in $kws) { $stats[$k] = 0 } - -Get-ChildItem logs/wms/wms-web.log* | ForEach-Object { - $fs = New-Object System.IO.FileStream($_.FullName, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::ReadWrite) - # The logs seem to be UTF-8 - $reader = New-Object System.IO.StreamReader($fs, [System.Text.Encoding]::UTF8) - while($null -ne ($line = $reader.ReadLine())){ - if($line -match '^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})'){ - $ts = $matches[1] - if($ts -ge $targetTs){ - foreach($k in $kws){ - if($line -match $k){ - $stats[$k]++ - } - } - } - } - } - $reader.Close() - $fs.Dispose() -} - -$stats.Keys | ForEach-Object { "$_: $($stats[$_])" } diff --git a/db_query.js b/db_query.js deleted file mode 100644 index ce2fe7d..0000000 --- a/db_query.js +++ /dev/null @@ -1,47 +0,0 @@ -const Sequelize = require('sequelize'); -const config = { - dialect: 'mysql', - host: '127.0.0.1', - port: 3307, - database: 'wms', - username: 'wms', - password: 'dspxmRwRdRbWtbm7', - logging: false, -}; - -const sequelize = new Sequelize(config.database, config.username, config.password, config); - -async function run() { - try { - const results = {}; - - const [ dyxdCountResult ] = await sequelize.query("SELECT COUNT(*) as count FROM wms_platform WHERE code='DYXD'"); - results.dyxdCount = dyxdCountResult[0].count; - - const [ dyCountResult ] = await sequelize.query("SELECT COUNT(*) as count FROM wms_platform WHERE code='DY'"); - results.dyCount = dyCountResult[0].count; - - const [ dyRowResult ] = await sequelize.query("SELECT * FROM wms_platform WHERE code='DY' LIMIT 1"); - results.dyRow = dyRowResult[0] || null; - - // The user asked for "metaExists (SequelizeMeta 是否存在该 migration 记录)" - // Based on previous terminal logs, the migration file name or pattern seems to be related to "platform_code" or "wms_platform" - const [ metaResult ] = await sequelize.query('SELECT * FROM SequelizeMeta'); - const migrationName = '20250303080004-platform_code.js'; // This is an assumption based on common naming. - // Let's search for any record that contains 'platform' in the name. - const exists = metaResult.some(m => m.name.includes('platform')); - results.metaExists = exists; - - try { - const [ expressTotalResult ] = await sequelize.query('SELECT COUNT(*) as count FROM wms_express'); - results.expressTotal = expressTotalResult[0].count; - } catch (e) {} - - console.log(JSON.stringify(results, null, 2)); - } catch (error) { - console.error(error); - } finally { - await sequelize.close(); - } -} -run(); diff --git a/dev_out.log b/dev_out.log deleted file mode 100644 index 280f555..0000000 --- a/dev_out.log +++ /dev/null @@ -1,654 +0,0 @@ -[egg-ts-helper] create typings\app\extend\application.d.ts (4ms) -[egg-ts-helper] create typings\app\controller\index.d.ts (3ms) -[egg-ts-helper] create typings\app\model\index.d.ts (2ms) -[egg-ts-helper] create typings\config\index.d.ts (15ms) -[egg-ts-helper] create typings\config\plugin.d.ts (1ms) -[egg-ts-helper] create typings\app\service\index.d.ts (4ms) -[egg-ts-helper] create typings\app\index.d.ts (1ms) -2026-05-20 02:28:09,421 INFO 33312 [master] node version v24.14.0 -2026-05-20 02:28:09,421 INFO 33312 [master] egg version 3.31.0 -StockWarehouse stock_warehouse stock_barcodes -2026-05-20 02:28:10,680 INFO 32732 [egg-sequelize](1ms) Executed (default): SELECT 1+1 AS result -2026-05-20 02:28:10,687 INFO 33312 [master] agent_worker#1:32732 started (1245ms) -StockWarehouse stock_warehouse stock_barcodes -2026-05-20 02:28:11,939 INFO 53968 ✅ Application 扩展能力已加载 -2026-05-20 02:28:11,939 INFO 53968 ✅ fileWriter 已挂载到 app.fileWriter -2026-05-20 02:28:11,939 INFO 53968 ✅ qimenClient 已挂载到 app.qimenClient -2026-05-20 02:28:12,644 INFO 53968 ✅ 工厂类初始化完成 -2026-05-20 02:28:12,670 INFO 53968 ✅ 缓存方法验证通过wms -2026-05-20 02:28:12,675 INFO 53968 [egg-sequelize](0ms) Executed (default): SELECT 1+1 AS result -2026-05-20 02:28:12,775 INFO 33312 [master] egg started on http://0.0.0.0:6061 (3354ms) -Tue, 19 May 2026 18:28:42 GMT egg-logger deprecated EggContextLogger is deprecated, use the EggLogger directly at node_modules\egg\app\extend\context.js:114:19 -2026-05-20 02:28:42,788 INFO 53968 [-/127.0.0.1/-/0ms SCHEDULE /__schedule?path=D:\wms\app\schedule\notice_stock_remaining.js&interval=30s&type=worker&immediate=false&disable=false] [notice_stock_remaining] 本轮任务启动 { - scheduleName: 'notice_stock_remaining', - cacheKeyPrefix: 'notice_stock_remaining_notified', - running: false -} -2026-05-20 02:28:42,788 INFO 53968 [-/127.0.0.1/-/1ms SCHEDULE /__schedule?path=D:\wms\app\schedule\notice_stock_remaining.js&interval=30s&type=worker&immediate=false&disable=false] [notice_stock_remaining] 已检查历史通知缓存 { - legacyCacheKey: 'notice_stock_remaining_notified_list', - cacheHit: false, - cachedValueType: 'object', - rawCacheCount: 0, - normalizedCount: 0, - cacheKeyMode: 'stock-day' -} -2026-05-20 02:28:42,801 INFO 53968 [egg-sequelize](2ms) Executed (default): SELECT `id`, `warehouse_id`, `retry_count`, `max_retry_count`, `next_retry_at`, `send_status`, `print_status` FROM `wms_print_record` AS `PrintRecord` WHERE ((`PrintRecord`.`send_status` = 'send_failed' OR `PrintRecord`.`print_status` IN ('print_failed', 'timeout')) AND `PrintRecord`.`next_retry_at` <= '2026-05-19 18:28:42' AND `PrintRecord`.`retry_count` < `max_retry_count`) ORDER BY `PrintRecord`.`next_retry_at` ASC, `PrintRecord`.`id` ASC LIMIT 20; -2026-05-20 02:28:42,810 INFO 53968 [egg-sequelize](18ms) Executed (default): SELECT `id`, `item_code`, `item_name`, `store_id`, `warehouse_id`, `remaining_threshold_days` FROM `wms_stock_warehouse` AS `stock_warehouse` WHERE `stock_warehouse`.`is_shelf_life_mgmt` = 'Y' AND `stock_warehouse`.`remaining_threshold_days` > 0 ORDER BY `stock_warehouse`.`remaining_threshold_days` ASC, `stock_warehouse`.`id` ASC; -2026-05-20 02:28:42,810 INFO 53968 [-/127.0.0.1/-/23ms SCHEDULE /__schedule?path=D:\wms\app\schedule\notice_stock_remaining.js&interval=30s&type=worker&immediate=false&disable=false] [notice_stock_remaining] 完成商品候选查询 { stockCount: 10 } -2026-05-20 02:28:42,818 INFO 53968 [egg-sequelize](3ms) Executed (default): SELECT `wms_storage`.`id`, `wms_storage`.`warehouse_id`, `wms_storage`.`store_id`, `wms_storage`.`space_id`, `wms_storage`.`stock_id`, `wms_storage`.`batch_no`, `wms_storage`.`inventory_type`, `wms_storage`.`quantity`, `wms_storage`.`locked_quantity`, `wms_storage`.`available_quantity`, `wms_storage`.`production_date`, `wms_storage`.`expiry_date`, `wms_storage`.`inbound_time`, `wms_storage`.`inbound_order_no`, `wms_storage`.`receiving_id`, `wms_storage`.`entry_order_id`, `wms_storage`.`supplier_id`, `wms_storage`.`supplier_batch_no`, `wms_storage`.`is_enabled`, `wms_storage`.`created_at`, `wms_storage`.`updated_at`, `wms_storage`.`delete_at`, `space`.`id` AS `space.id`, `space`.`space_code` AS `space.space_code`, `space`.`custom_name` AS `space.custom_name` FROM `wms_storage` AS `wms_storage` LEFT OUTER JOIN `wms_location_space` AS `space` ON `wms_storage`.`space_id` = `space`.`id` AND (`space`.`deleted_at` IS NULL) WHERE `wms_storage`.`stock_id` IN (156562, 156563, 156564, 156565, 156566, 157059, 157068, 156567, 157069, 157120) AND `wms_storage`.`is_enabled` = 1 AND `wms_storage`.`delete_at` IS NULL AND `wms_storage`.`quantity` > 0 AND (`wms_storage`.`expiry_date` IS NOT NULL AND `wms_storage`.`expiry_date` <= '2027-06-30 18:28:42') ORDER BY `wms_storage`.`expiry_date` ASC, `wms_storage`.`inbound_time` ASC, `wms_storage`.`id` ASC; -2026-05-20 02:28:42,820 INFO 53968 [-/127.0.0.1/-/33ms SCHEDULE /__schedule?path=D:\wms\app\schedule\notice_stock_remaining.js&interval=30s&type=worker&immediate=false&disable=false] [notice_stock_remaining] 完成库存候选查询 { stockCount: 10, storageCount: 4, maxThresholdDays: 407 } -2026-05-20 02:28:42,821 INFO 53968 [-/127.0.0.1/-/34ms SCHEDULE /__schedule?path=D:\wms\app\schedule\notice_stock_remaining.js&interval=30s&type=worker&immediate=false&disable=false] [notice_stock_remaining] 本轮通知缓存按商品日粒度独立写入,无需整体回写 { - cacheKeyPrefix: 'notice_stock_remaining_notified', - sentCount: 0, - skippedCount: 3, - ttlSeconds: 86400 -} -2026-05-20 02:28:42,821 INFO 53968 [-/127.0.0.1/-/34ms SCHEDULE /__schedule?path=D:\wms\app\schedule\notice_stock_remaining.js&interval=30s&type=worker&immediate=false&disable=false] [notice_stock_remaining] 本轮任务结束 { - scheduleName: 'notice_stock_remaining', - cacheKeyPrefix: 'notice_stock_remaining_notified', - stockCount: 10, - storageCount: 4, - sentCount: 0, - skippedCount: 3, - running: false -} -2026-05-20 02:29:12,788 INFO 53968 [egg-sequelize](2ms) Executed (default): SELECT TABLE_NAME AS tableName - FROM INFORMATION_SCHEMA.TABLES - WHERE TABLE_SCHEMA = DATABASE() - AND TABLE_NAME LIKE 'wms_order_delivery_%' -2026-05-20 02:29:12,790 INFO 53968 [egg-sequelize](1ms) Executed (4fea7690-c022-4eed-b2a1-ee012f39ebe9): START TRANSACTION; -2026-05-20 02:29:12,794 INFO 53968 [egg-sequelize](1ms) Executed (default): SELECT `id` FROM `wms_store` AS `store` WHERE (`store`.`deleted_at` IS NULL AND (`store`.`id` = '100000' AND `store`.`project` = 'warehouse')); -2026-05-20 02:29:12,801 INFO 53968 [-/127.0.0.1/-/0ms SCHEDULE /__schedule?path=D:\wms\app\schedule\notice_stock_remaining.js&interval=30s&type=worker&immediate=false&disable=false] [notice_stock_remaining] 本轮任务启动 { - scheduleName: 'notice_stock_remaining', - cacheKeyPrefix: 'notice_stock_remaining_notified', - running: false -} -2026-05-20 02:29:12,802 INFO 53968 [-/127.0.0.1/-/1ms SCHEDULE /__schedule?path=D:\wms\app\schedule\notice_stock_remaining.js&interval=30s&type=worker&immediate=false&disable=false] [notice_stock_remaining] 已检查历史通知缓存 { - legacyCacheKey: 'notice_stock_remaining_notified_list', - cacheHit: false, - cachedValueType: 'object', - rawCacheCount: 0, - normalizedCount: 0, - cacheKeyMode: 'stock-day' -} -2026-05-20 02:29:12,806 INFO 53968 [egg-sequelize](8ms) Executed (default): SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_SCHEMA = 'wms'; -2026-05-20 02:29:12,812 INFO 53968 [egg-sequelize](1ms) Executed (default): SELECT `id`, `warehouse_id`, `retry_count`, `max_retry_count`, `next_retry_at`, `send_status`, `print_status` FROM `wms_print_record` AS `PrintRecord` WHERE ((`PrintRecord`.`send_status` = 'send_failed' OR `PrintRecord`.`print_status` IN ('print_failed', 'timeout')) AND `PrintRecord`.`next_retry_at` <= '2026-05-19 18:29:12' AND `PrintRecord`.`retry_count` < `max_retry_count`) ORDER BY `PrintRecord`.`next_retry_at` ASC, `PrintRecord`.`id` ASC LIMIT 20; -2026-05-20 02:29:12,817 INFO 53968 [egg-sequelize](5ms) Executed (default): SHOW INDEX FROM `wms_order_delivery_100000` -2026-05-20 02:29:12,818 INFO 53968 [egg-sequelize](7ms) Executed (default): SHOW FULL COLUMNS FROM `wms_order_delivery_100000`; -2026-05-20 02:29:12,822 INFO 53968 [egg-sequelize](3ms) Executed (default): SHOW FULL COLUMNS FROM `wms_order_delivery_100000`; -2026-05-20 02:29:12,825 INFO 53968 [egg-sequelize](1ms) Executed (default): SELECT MAX(CASE WHEN `create_channel` IS NULL THEN 1 ELSE 0 END) AS `create_channel`, MAX(CASE WHEN `weight_type` IS NULL THEN 1 ELSE 0 END) AS `weight_type`, MAX(CASE WHEN `items_count` IS NULL THEN 1 ELSE 0 END) AS `items_count`, MAX(CASE WHEN `items_total` IS NULL THEN 1 ELSE 0 END) AS `items_total`, MAX(CASE WHEN `items_weight` IS NULL THEN 1 ELSE 0 END) AS `items_weight`, MAX(CASE WHEN `items_hash` IS NULL THEN 1 ELSE 0 END) AS `items_hash`, MAX(CASE WHEN `items_crc` IS NULL THEN 1 ELSE 0 END) AS `items_crc`, MAX(CASE WHEN `wave_id` IS NULL THEN 1 ELSE 0 END) AS `wave_id`, MAX(CASE WHEN `wave_no` IS NULL THEN 1 ELSE 0 END) AS `wave_no`, MAX(CASE WHEN `wave_strategy_version` IS NULL THEN 1 ELSE 0 END) AS `wave_strategy_version`, MAX(CASE WHEN `wave_scan_result` IS NULL THEN 1 ELSE 0 END) AS `wave_scan_result`, MAX(CASE WHEN `step` IS NULL THEN 1 ELSE 0 END) AS `step` FROM `wms_order_delivery_100000` WHERE `create_channel` IS NULL OR `weight_type` IS NULL OR `items_count` IS NULL OR `items_total` IS NULL OR `items_weight` IS NULL OR `items_hash` IS NULL OR `items_crc` IS NULL OR `wave_id` IS NULL OR `wave_no` IS NULL OR `wave_strategy_version` IS NULL OR `wave_scan_result` IS NULL OR `step` IS NULL LIMIT 1 -2026-05-20 02:29:12,826 INFO 53968 [egg-sequelize](20ms) Executed (default): SELECT `id`, `item_code`, `item_name`, `store_id`, `warehouse_id`, `remaining_threshold_days` FROM `wms_stock_warehouse` AS `stock_warehouse` WHERE `stock_warehouse`.`is_shelf_life_mgmt` = 'Y' AND `stock_warehouse`.`remaining_threshold_days` > 0 ORDER BY `stock_warehouse`.`remaining_threshold_days` ASC, `stock_warehouse`.`id` ASC; -2026-05-20 02:29:12,826 INFO 53968 [-/127.0.0.1/-/25ms SCHEDULE /__schedule?path=D:\wms\app\schedule\notice_stock_remaining.js&interval=30s&type=worker&immediate=false&disable=false] [notice_stock_remaining] 完成商品候选查询 { stockCount: 10 } -2026-05-20 02:29:12,828 INFO 53968 [egg-sequelize](1ms) Executed (default): SELECT `wms_storage`.`id`, `wms_storage`.`warehouse_id`, `wms_storage`.`store_id`, `wms_storage`.`space_id`, `wms_storage`.`stock_id`, `wms_storage`.`batch_no`, `wms_storage`.`inventory_type`, `wms_storage`.`quantity`, `wms_storage`.`locked_quantity`, `wms_storage`.`available_quantity`, `wms_storage`.`production_date`, `wms_storage`.`expiry_date`, `wms_storage`.`inbound_time`, `wms_storage`.`inbound_order_no`, `wms_storage`.`receiving_id`, `wms_storage`.`entry_order_id`, `wms_storage`.`supplier_id`, `wms_storage`.`supplier_batch_no`, `wms_storage`.`is_enabled`, `wms_storage`.`created_at`, `wms_storage`.`updated_at`, `wms_storage`.`delete_at`, `space`.`id` AS `space.id`, `space`.`space_code` AS `space.space_code`, `space`.`custom_name` AS `space.custom_name` FROM `wms_storage` AS `wms_storage` LEFT OUTER JOIN `wms_location_space` AS `space` ON `wms_storage`.`space_id` = `space`.`id` AND (`space`.`deleted_at` IS NULL) WHERE `wms_storage`.`stock_id` IN (156562, 156563, 156564, 156565, 156566, 157059, 157068, 156567, 157069, 157120) AND `wms_storage`.`is_enabled` = 1 AND `wms_storage`.`delete_at` IS NULL AND `wms_storage`.`quantity` > 0 AND (`wms_storage`.`expiry_date` IS NOT NULL AND `wms_storage`.`expiry_date` <= '2027-06-30 18:29:12') ORDER BY `wms_storage`.`expiry_date` ASC, `wms_storage`.`inbound_time` ASC, `wms_storage`.`id` ASC; -2026-05-20 02:29:12,829 INFO 53968 [-/127.0.0.1/-/28ms SCHEDULE /__schedule?path=D:\wms\app\schedule\notice_stock_remaining.js&interval=30s&type=worker&immediate=false&disable=false] [notice_stock_remaining] 完成库存候选查询 { stockCount: 10, storageCount: 4, maxThresholdDays: 407 } -2026-05-20 02:29:12,830 INFO 53968 [-/127.0.0.1/-/29ms SCHEDULE /__schedule?path=D:\wms\app\schedule\notice_stock_remaining.js&interval=30s&type=worker&immediate=false&disable=false] [notice_stock_remaining] 本轮通知缓存按商品日粒度独立写入,无需整体回写 { - cacheKeyPrefix: 'notice_stock_remaining_notified', - sentCount: 0, - skippedCount: 3, - ttlSeconds: 86400 -} -2026-05-20 02:29:12,830 INFO 53968 [-/127.0.0.1/-/29ms SCHEDULE /__schedule?path=D:\wms\app\schedule\notice_stock_remaining.js&interval=30s&type=worker&immediate=false&disable=false] [notice_stock_remaining] 本轮任务结束 { - scheduleName: 'notice_stock_remaining', - cacheKeyPrefix: 'notice_stock_remaining_notified', - stockCount: 10, - storageCount: 4, - sentCount: 0, - skippedCount: 3, - running: false -} -2026-05-20 02:29:12,949 INFO 53968 [egg-sequelize](124ms) Executed (default): SELECT MAX(CASE WHEN `id` IS NOT NULL AND (`id` < 0 OR `id` > 18446744073709551615) THEN 1 ELSE 0 END) AS `id`, MAX(CASE WHEN `total_amount` IS NOT NULL AND (`total_amount` < -9999999999999999.99 OR `total_amount` > 9999999999999999.99) THEN 1 ELSE 0 END) AS `total_amount`, MAX(CASE WHEN `item_amount` IS NOT NULL AND (`item_amount` < -9999999999999999.99 OR `item_amount` > 9999999999999999.99) THEN 1 ELSE 0 END) AS `item_amount`, MAX(CASE WHEN `discount_amount` IS NOT NULL AND (`discount_amount` < -9999999999999999.99 OR `discount_amount` > 9999999999999999.99) THEN 1 ELSE 0 END) AS `discount_amount`, MAX(CASE WHEN `freight` IS NOT NULL AND (`freight` < -9999999999999999.99 OR `freight` > 9999999999999999.99) THEN 1 ELSE 0 END) AS `freight`, MAX(CASE WHEN `ar_amount` IS NOT NULL AND (`ar_amount` < -9999999999999999.99 OR `ar_amount` > 9999999999999999.99) THEN 1 ELSE 0 END) AS `ar_amount`, MAX(CASE WHEN `got_amount` IS NOT NULL AND (`got_amount` < -9999999999999999.99 OR `got_amount` > 9999999999999999.99) THEN 1 ELSE 0 END) AS `got_amount`, MAX(CASE WHEN `service_fee` IS NOT NULL AND (`service_fee` < -9999999999999999.99 OR `service_fee` > 9999999999999999.99) THEN 1 ELSE 0 END) AS `service_fee`, MAX(CASE WHEN `weight_type` IS NOT NULL AND (`weight_type` < -2147483648 OR `weight_type` > 2147483647) THEN 1 ELSE 0 END) AS `weight_type`, MAX(CASE WHEN `id_number` IS NOT NULL AND (`id_number` < -2147483648 OR `id_number` > 2147483647) THEN 1 ELSE 0 END) AS `id_number`, MAX(CASE WHEN `store_id` IS NOT NULL AND (`store_id` < 0 OR `store_id` > 18446744073709551615) THEN 1 ELSE 0 END) AS `store_id`, MAX(CASE WHEN `warehouse_id` IS NOT NULL AND (`warehouse_id` < 0 OR `warehouse_id` > 18446744073709551615) THEN 1 ELSE 0 END) AS `warehouse_id`, MAX(CASE WHEN `from_key` IS NOT NULL AND (`from_key` < -2147483648 OR `from_key` > 2147483647) THEN 1 ELSE 0 END) AS `from_key`, MAX(CASE WHEN `items_count` IS NOT NULL AND (`items_count` < 0 OR `items_count` > 65535) THEN 1 ELSE 0 END) AS `items_count`, MAX(CASE WHEN `items_total` IS NOT NULL AND (`items_total` < 0 OR `items_total` > 4294967295) THEN 1 ELSE 0 END) AS `items_total`, MAX(CASE WHEN `items_weight` IS NOT NULL AND (`items_weight` < -99999999.99 OR `items_weight` > 99999999.99) THEN 1 ELSE 0 END) AS `items_weight`, MAX(CASE WHEN `items_crc` IS NOT NULL AND (`items_crc` < 0 OR `items_crc` > 4294967295) THEN 1 ELSE 0 END) AS `items_crc`, MAX(CASE WHEN `wave_id` IS NOT NULL AND (`wave_id` < -9223372036854775808 OR `wave_id` > 9223372036854775807) THEN 1 ELSE 0 END) AS `wave_id`, MAX(CASE WHEN `wave_strategy_version` IS NOT NULL AND (`wave_strategy_version` < -2147483648 OR `wave_strategy_version` > 2147483647) THEN 1 ELSE 0 END) AS `wave_strategy_version`, MAX(CASE WHEN `wave_scan_result` IS NOT NULL AND (`wave_scan_result` < -2147483648 OR `wave_scan_result` > 2147483647) THEN 1 ELSE 0 END) AS `wave_scan_result`, MAX(CASE WHEN `step` IS NOT NULL AND (`step` < -2147483648 OR `step` > 2147483647) THEN 1 ELSE 0 END) AS `step` FROM `wms_order_delivery_100000` WHERE (`id` IS NOT NULL AND (`id` < 0 OR `id` > 18446744073709551615)) OR (`total_amount` IS NOT NULL AND (`total_amount` < -9999999999999999.99 OR `total_amount` > 9999999999999999.99)) OR (`item_amount` IS NOT NULL AND (`item_amount` < -9999999999999999.99 OR `item_amount` > 9999999999999999.99)) OR (`discount_amount` IS NOT NULL AND (`discount_amount` < -9999999999999999.99 OR `discount_amount` > 9999999999999999.99)) OR (`freight` IS NOT NULL AND (`freight` < -9999999999999999.99 OR `freight` > 9999999999999999.99)) OR (`ar_amount` IS NOT NULL AND (`ar_amount` < -9999999999999999.99 OR `ar_amount` > 9999999999999999.99)) OR (`got_amount` IS NOT NULL AND (`got_amount` < -9999999999999999.99 OR `got_amount` > 9999999999999999.99)) OR (`service_fee` IS NOT NULL AND (`service_fee` < -9999999999999999.99 OR `service_fee` > 9999999999999999.99)) OR (`weight_type` IS NOT NULL AND (`weight_type` < -2147483648 OR `weight_type` > 2147483647)) OR (`id_number` IS NOT NULL AND (`id_number` < -2147483648 OR `id_number` > 2147483647)) OR (`store_id` IS NOT NULL AND (`store_id` < 0 OR `store_id` > 18446744073709551615)) OR (`warehouse_id` IS NOT NULL AND (`warehouse_id` < 0 OR `warehouse_id` > 18446744073709551615)) OR (`from_key` IS NOT NULL AND (`from_key` < -2147483648 OR `from_key` > 2147483647)) OR (`items_count` IS NOT NULL AND (`items_count` < 0 OR `items_count` > 65535)) OR (`items_total` IS NOT NULL AND (`items_total` < 0 OR `items_total` > 4294967295)) OR (`items_weight` IS NOT NULL AND (`items_weight` < -99999999.99 OR `items_weight` > 99999999.99)) OR (`items_crc` IS NOT NULL AND (`items_crc` < 0 OR `items_crc` > 4294967295)) OR (`wave_id` IS NOT NULL AND (`wave_id` < -9223372036854775808 OR `wave_id` > 9223372036854775807)) OR (`wave_strategy_version` IS NOT NULL AND (`wave_strategy_version` < -2147483648 OR `wave_strategy_version` > 2147483647)) OR (`wave_scan_result` IS NOT NULL AND (`wave_scan_result` < -2147483648 OR `wave_scan_result` > 2147483647)) OR (`step` IS NOT NULL AND (`step` < -2147483648 OR `step` > 2147483647)) LIMIT 1 -2026-05-20 02:29:12,953 INFO 53968 [egg-sequelize](4ms) Executed (default): SHOW FULL COLUMNS FROM `wms_order_delivery_100000`; -2026-05-20 02:29:12,983 INFO 53968 [egg-sequelize](29ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `id` `id` BIGINT(20) UNSIGNED AUTO_INCREMENT, CHANGE `delivery_order_code` `delivery_order_code` VARCHAR(50) COMMENT '发货单号', CHANGE `pre_delivery_order_code` `pre_delivery_order_code` VARCHAR(50) COMMENT '预发货单号', CHANGE `pre_delivery_order_id` `pre_delivery_order_id` VARCHAR(50) COMMENT '预发货单ID', CHANGE `order_type` `order_type` VARCHAR(50) COMMENT '订单类型', CHANGE `warehouse_code` `warehouse_code` VARCHAR(50) COMMENT '仓库编码', CHANGE `order_flag` `order_flag` LONGTEXT COMMENT '订单标记', CHANGE `source_platform_code` `source_platform_code` VARCHAR(50) COMMENT '来源平台编码', CHANGE `source_platform_name` `source_platform_name` VARCHAR(200) COMMENT '来源平台名称', CHANGE `create_channel` `create_channel` VARCHAR(20) NOT NULL DEFAULT 'MANUAL' COMMENT '创建来源渠道', CHANGE `source_order_codes` `source_order_codes` TEXT COMMENT '来源订单号集合', CHANGE `sys_platform_code` `sys_platform_code` VARCHAR(50) COMMENT '系统平台编码', CHANGE `sys_platform_name` `sys_platform_name` VARCHAR(200) COMMENT '系统平台名称', CHANGE `create_at` `create_at` DATETIME COMMENT '创建时间', CHANGE `delete_at` `delete_at` DATETIME COMMENT '删除时间', CHANGE `updated_at` `updated_at` DATETIME COMMENT '更新时间', CHANGE `place_order_time` `place_order_time` DATETIME COMMENT '店铺创建订单时间', CHANGE `pay_time` `pay_time` DATETIME COMMENT '支付时间', CHANGE `pay_no` `pay_no` VARCHAR(50) COMMENT '支付单号', CHANGE `service_code` `service_code` VARCHAR(50) COMMENT '集包服务编码', CHANGE `operator_name` `operator_name` VARCHAR(50) COMMENT 'ERP审核人', CHANGE `operate_time` `operate_time` DATETIME COMMENT 'ERP审核时间', CHANGE `delivery_time` `delivery_time` DATETIME COMMENT '发货时间', CHANGE `shop_nick` `shop_nick` VARCHAR(200) COMMENT '店铺名称', CHANGE `seller_nick` `seller_nick` VARCHAR(200) COMMENT '卖家名称', CHANGE `buyer_nick` `buyer_nick` VARCHAR(200) COMMENT '买家名称', CHANGE `total_amount` `total_amount` DECIMAL(18,2) COMMENT '订单总金额', CHANGE `item_amount` `item_amount` DECIMAL(18,2) COMMENT '商品总金额', CHANGE `discount_amount` `discount_amount` DECIMAL(18,2) COMMENT '订单折扣金额', CHANGE `freight` `freight` DECIMAL(18,2) COMMENT '快递费用', CHANGE `ar_amount` `ar_amount` DECIMAL(18,2) COMMENT '应收金额', CHANGE `got_amount` `got_amount` DECIMAL(18,2) COMMENT '已收金额', CHANGE `service_fee` `service_fee` DECIMAL(18,2) COMMENT 'COD服务费', CHANGE `logistics_code` `logistics_code` VARCHAR(50) COMMENT '物流公司编码', CHANGE `logistics_name` `logistics_name` VARCHAR(200) COMMENT '物流公司名称', CHANGE `sys_logistics_code` `sys_logistics_code` VARCHAR(50) COMMENT '系统物流公司编码', CHANGE `sys_logistics_name` `sys_logistics_name` VARCHAR(200) COMMENT '系统物流公司名称', CHANGE `basket_number` `basket_number` VARCHAR(50) COMMENT '筐号', CHANGE `express_code` `express_code` VARCHAR(50) COMMENT '面单号前置', CHANGE `logistics_area_code` `logistics_area_code` VARCHAR(50) COMMENT '快递区域编码, 大头笔信息', CHANGE `delivery_type` `delivery_type` VARCHAR(255) COMMENT '发货服务类型', CHANGE `weight_type` `weight_type` INTEGER(11) NOT NULL DEFAULT 0 COMMENT '重量类型:0常规、1轻货、2重货、3冷链', CHANGE `is_urgency` `is_urgency` ENUM('Y', 'N') DEFAULT 'N' COMMENT '是否紧急', CHANGE `invoice_flag` `invoice_flag` ENUM('Y', 'N') DEFAULT 'N' COMMENT '是否需要发票', CHANGE `status` `status` ENUM('pedding', 'created', 'cancel', 'error') DEFAULT 'created' COMMENT '订单状态', CHANGE `name` `name` TEXT COMMENT '收件人姓名', CHANGE `zip_code` `zip_code` VARCHAR(50) COMMENT '收件人邮编', CHANGE `tel` `tel` TEXT COMMENT '收件人电话', CHANGE `mobile` `mobile` TEXT COMMENT '收件人移动电话', CHANGE `email` `email` TEXT COMMENT '收件人邮箱', CHANGE `country_code` `country_code` VARCHAR(255) COMMENT '国家编码', CHANGE `province` `province` VARCHAR(255) COMMENT '省份', CHANGE `city` `city` VARCHAR(255) COMMENT '城市', CHANGE `area` `area` VARCHAR(255) COMMENT '区', CHANGE `town` `town` VARCHAR(255) COMMENT '镇', CHANGE `detail_address` `detail_address` TEXT COMMENT '详细地址', CHANGE `id_type` `id_type` VARCHAR(255) COMMENT '证件类型', CHANGE `id_number` `id_number` INTEGER(11) COMMENT '证件号码', CHANGE `oaid` `oaid` TEXT COMMENT 'OAID', CHANGE `sync_status` `sync_status` ENUM('padding', 'fin', 'error') DEFAULT 'padding' COMMENT '同步状态', CHANGE `store_id` `store_id` BIGINT(20) UNSIGNED COMMENT '货主ID', CHANGE `warehouse_id` `warehouse_id` BIGINT(20) UNSIGNED COMMENT '仓库ID', CHANGE `from_key` `from_key` INTEGER(11) COMMENT '来源键', CHANGE `items` `items` TEXT COMMENT '商品JSON字符串', CHANGE `items_count` `items_count` SMALLINT(5) UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品种类数', CHANGE `items_total` `items_total` INTEGER(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品总数', CHANGE `items_weight` `items_weight` DECIMAL(10,2) NOT NULL DEFAULT 0 COMMENT '总重量(kg)', CHANGE `items_hash` `items_hash` CHAR(32) NOT NULL DEFAULT '' COMMENT 'MD5哈希值(32位)', CHANGE `items_crc` `items_crc` INTEGER(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'CRC32校验码', CHANGE `wave_id` `wave_id` BIGINT(20) NOT NULL DEFAULT 0 COMMENT '波次ID,0表示未分配', CHANGE `wave_no` `wave_no` VARCHAR(50) NOT NULL DEFAULT '' COMMENT '波次号,空字符串表示未分配', CHANGE `wave_strategy_version` `wave_strategy_version` INTEGER(10) NOT NULL DEFAULT 0 COMMENT '波次策略版本号', CHANGE `wave_scan_result` `wave_scan_result` INTEGER(10) NOT NULL DEFAULT 0 COMMENT '波次扫描结果,0未扫描,1扫描符合,2扫描没有符合', CHANGE `post_status` `post_status` ENUM('padding', 'fin', 'timeout', 'error', 'none') DEFAULT 'none' COMMENT '分配快递号状态机', CHANGE `storage_status` `storage_status` ENUM('padding', 'fin', 'error', 'none') DEFAULT 'none' COMMENT '分配储位状态机', CHANGE `pick_status` `pick_status` ENUM('padding', 'fin', 'error', 'none') DEFAULT 'none' COMMENT '拣货状态机', CHANGE `pack_status` `pack_status` ENUM('none', 'padding', 'fin', 'error') DEFAULT 'none' COMMENT '打包状态机', CHANGE `sended_status` `sended_status` ENUM('none', 'padding', 'fin', 'error') DEFAULT 'none' COMMENT '发货状态机', CHANGE `inspection_status` `inspection_status` ENUM('none', 'padding', 'running', 'fin', 'error') DEFAULT 'none' COMMENT '检验状态机', CHANGE `recheck_status` `recheck_status` VARCHAR(20) DEFAULT 'none' COMMENT '复核状态', CHANGE `recheck_time` `recheck_time` DATETIME COMMENT '复核时间', CHANGE `step` `step` INTEGER(10) NOT NULL DEFAULT 0 COMMENT '订单步骤:0未审核,1已审核,2处理中,3驳回/异常,4配送中,5已完成,9已关闭', CHANGE `print_status` `print_status` ENUM('none', 'padding', 'fin', 'error') DEFAULT 'none' COMMENT '打印状态机', CHANGE `claim_status` `claim_status` ENUM('none', 'padding', 'fin', 'error') DEFAULT 'none' COMMENT '领取状态机', CHANGE `outbound_status` `outbound_status` ENUM('none', 'padding', 'fin', 'timeout', 'error') DEFAULT 'none' COMMENT '出库状态机', CHANGE `lock_status` `lock_status` ENUM('none', 'warehouse', 'store') DEFAULT 'none' COMMENT '锁定状态机', CHANGE `intercept_status` `intercept_status` ENUM('none', 'requesting', 'requested', 'intercepting', 'intercepted_in_transit', 'intercepted_at_warehouse', 'returning', 'returned', 'delivered_by_mistake', 'timeout', 'cancelled', 'failed', 'exception') DEFAULT 'none' COMMENT '拦截状态机' -2026-05-20 02:29:12,985 INFO 53968 [egg-sequelize](1ms) Executed (default): SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_NAME = 'wms_order_delivery_100000' AND TABLE_SCHEMA = 'wms' -2026-05-20 02:29:12,988 INFO 53968 [egg-sequelize](2ms) Executed (default): SELECT CONSTRAINT_NAME as constraint_name,CONSTRAINT_NAME as constraintName,CONSTRAINT_SCHEMA as constraintSchema,CONSTRAINT_SCHEMA as constraintCatalog,TABLE_NAME as tableName,TABLE_SCHEMA as tableSchema,TABLE_SCHEMA as tableCatalog,COLUMN_NAME as columnName,REFERENCED_TABLE_SCHEMA as referencedTableSchema,REFERENCED_TABLE_SCHEMA as referencedTableCatalog,REFERENCED_TABLE_NAME as referencedTableName,REFERENCED_COLUMN_NAME as referencedColumnName FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE where TABLE_NAME = 'wms_order_delivery_100000' AND CONSTRAINT_NAME!='PRIMARY' AND CONSTRAINT_SCHEMA='wms' AND REFERENCED_TABLE_NAME IS NOT NULL; -2026-05-20 02:29:12,989 INFO 53968 [egg-sequelize](3ms) Executed (default): SHOW FULL COLUMNS FROM `wms_order_delivery_100000`; -2026-05-20 02:29:13,008 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `delivery_order_code` `delivery_order_code` VARCHAR(50) COMMENT '发货单号'; -2026-05-20 02:29:13,027 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `pre_delivery_order_code` `pre_delivery_order_code` VARCHAR(50) COMMENT '预发货单号'; -2026-05-20 02:29:13,045 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `pre_delivery_order_id` `pre_delivery_order_id` VARCHAR(50) COMMENT '预发货单ID'; -2026-05-20 02:29:13,066 INFO 53968 [egg-sequelize](21ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `order_type` `order_type` VARCHAR(50) COMMENT '订单类型'; -2026-05-20 02:29:13,084 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `warehouse_code` `warehouse_code` VARCHAR(50) COMMENT '仓库编码'; -2026-05-20 02:29:13,102 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `order_flag` `order_flag` LONGTEXT COMMENT '订单标记'; -2026-05-20 02:29:13,120 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `source_platform_code` `source_platform_code` VARCHAR(50) COMMENT '来源平台编码'; -2026-05-20 02:29:13,141 INFO 53968 [egg-sequelize](20ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `source_platform_name` `source_platform_name` VARCHAR(200) COMMENT '来源平台名称'; -2026-05-20 02:29:13,159 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `create_at` `create_at` DATETIME COMMENT '创建时间'; -2026-05-20 02:29:13,176 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `delete_at` `delete_at` DATETIME COMMENT '删除时间'; -2026-05-20 02:29:13,200 INFO 53968 [egg-sequelize](23ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `updated_at` `updated_at` DATETIME COMMENT '更新时间'; -2026-05-20 02:29:13,223 INFO 53968 [egg-sequelize](23ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `place_order_time` `place_order_time` DATETIME COMMENT '店铺创建订单时间'; -2026-05-20 02:29:13,242 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `pay_time` `pay_time` DATETIME COMMENT '支付时间'; -2026-05-20 02:29:13,259 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `pay_no` `pay_no` VARCHAR(50) COMMENT '支付单号'; -2026-05-20 02:29:13,279 INFO 53968 [egg-sequelize](20ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `service_code` `service_code` VARCHAR(50) COMMENT '集包服务编码'; -2026-05-20 02:29:13,298 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `operator_name` `operator_name` VARCHAR(50) COMMENT 'ERP审核人'; -2026-05-20 02:29:13,320 INFO 53968 [egg-sequelize](20ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `operate_time` `operate_time` DATETIME COMMENT 'ERP审核时间'; -2026-05-20 02:29:13,338 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `delivery_time` `delivery_time` DATETIME COMMENT '发货时间'; -2026-05-20 02:29:13,355 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `shop_nick` `shop_nick` VARCHAR(200) COMMENT '店铺名称'; -2026-05-20 02:29:13,371 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `seller_nick` `seller_nick` VARCHAR(200) COMMENT '卖家名称'; -2026-05-20 02:29:13,389 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `buyer_nick` `buyer_nick` VARCHAR(200) COMMENT '买家名称'; -2026-05-20 02:29:13,406 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `total_amount` `total_amount` DECIMAL(18,2) COMMENT '订单总金额'; -2026-05-20 02:29:13,428 INFO 53968 [egg-sequelize](22ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `item_amount` `item_amount` DECIMAL(18,2) COMMENT '商品总金额'; -2026-05-20 02:29:13,446 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `discount_amount` `discount_amount` DECIMAL(18,2) COMMENT '订单折扣金额'; -2026-05-20 02:29:13,465 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `freight` `freight` DECIMAL(18,2) COMMENT '快递费用'; -2026-05-20 02:29:13,491 INFO 53968 [egg-sequelize](24ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `ar_amount` `ar_amount` DECIMAL(18,2) COMMENT '应收金额'; -2026-05-20 02:29:13,527 INFO 53968 [egg-sequelize](36ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `got_amount` `got_amount` DECIMAL(18,2) COMMENT '已收金额'; -2026-05-20 02:29:13,566 INFO 53968 [egg-sequelize](38ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `service_fee` `service_fee` DECIMAL(18,2) COMMENT 'COD服务费'; -2026-05-20 02:29:13,583 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `logistics_code` `logistics_code` VARCHAR(50) COMMENT '物流公司编码'; -2026-05-20 02:29:13,603 INFO 53968 [egg-sequelize](19ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `logistics_name` `logistics_name` VARCHAR(200) COMMENT '物流公司名称'; -2026-05-20 02:29:13,619 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `express_code` `express_code` VARCHAR(50) COMMENT '面单号前置'; -2026-05-20 02:29:13,635 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `logistics_area_code` `logistics_area_code` VARCHAR(50) COMMENT '快递区域编码, 大头笔信息'; -2026-05-20 02:29:13,651 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `delivery_type` `delivery_type` VARCHAR(255) COMMENT '发货服务类型'; -2026-05-20 02:29:13,668 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `is_urgency` `is_urgency` ENUM('Y', 'N') DEFAULT 'N' COMMENT '是否紧急'; -2026-05-20 02:29:13,689 INFO 53968 [egg-sequelize](20ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `invoice_flag` `invoice_flag` ENUM('Y', 'N') DEFAULT 'N' COMMENT '是否需要发票'; -2026-05-20 02:29:13,707 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `status` `status` ENUM('pedding', 'created', 'cancel', 'error') DEFAULT 'created' COMMENT '订单状态'; -2026-05-20 02:29:13,724 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `name` `name` TEXT COMMENT '收件人姓名'; -2026-05-20 02:29:13,743 INFO 53968 [egg-sequelize](19ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `zip_code` `zip_code` VARCHAR(50) COMMENT '收件人邮编'; -2026-05-20 02:29:13,766 INFO 53968 [egg-sequelize](23ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `tel` `tel` TEXT COMMENT '收件人电话'; -2026-05-20 02:29:13,783 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `mobile` `mobile` TEXT COMMENT '收件人移动电话'; -2026-05-20 02:29:13,802 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `email` `email` TEXT COMMENT '收件人邮箱'; -2026-05-20 02:29:13,819 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `country_code` `country_code` VARCHAR(255) COMMENT '国家编码'; -2026-05-20 02:29:13,834 INFO 53968 [egg-sequelize](15ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `province` `province` VARCHAR(255) COMMENT '省份'; -2026-05-20 02:29:13,851 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `city` `city` VARCHAR(255) COMMENT '城市'; -2026-05-20 02:29:13,867 INFO 53968 [egg-sequelize](15ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `area` `area` VARCHAR(255) COMMENT '区'; -2026-05-20 02:29:13,883 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `town` `town` VARCHAR(255) COMMENT '镇'; -2026-05-20 02:29:13,903 INFO 53968 [egg-sequelize](20ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `detail_address` `detail_address` TEXT COMMENT '详细地址'; -2026-05-20 02:29:13,919 INFO 53968 [egg-sequelize](14ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `id_type` `id_type` VARCHAR(255) COMMENT '证件类型'; -2026-05-20 02:29:13,935 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `id_number` `id_number` INTEGER(11) COMMENT '证件号码'; -2026-05-20 02:29:13,955 INFO 53968 [egg-sequelize](19ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `oaid` `oaid` TEXT COMMENT 'OAID'; -2026-05-20 02:29:13,976 INFO 53968 [egg-sequelize](20ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `sync_status` `sync_status` ENUM('padding', 'fin', 'error') DEFAULT 'padding' COMMENT '同步状态'; -2026-05-20 02:29:13,994 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `store_id` `store_id` BIGINT(20) UNSIGNED COMMENT '货主ID'; -2026-05-20 02:29:14,011 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `warehouse_id` `warehouse_id` BIGINT(20) UNSIGNED COMMENT '仓库ID'; -2026-05-20 02:29:14,033 INFO 53968 [egg-sequelize](22ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `from_key` `from_key` INTEGER(11) COMMENT '来源键'; -2026-05-20 02:29:14,052 INFO 53968 [egg-sequelize](19ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `items` `items` TEXT COMMENT '商品JSON字符串'; -2026-05-20 02:29:14,074 INFO 53968 [egg-sequelize](22ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `items_count` `items_count` SMALLINT(5) UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品种类数'; -2026-05-20 02:29:14,100 INFO 53968 [egg-sequelize](25ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `items_total` `items_total` INTEGER(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品总数'; -2026-05-20 02:29:14,128 INFO 53968 [egg-sequelize](27ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `items_weight` `items_weight` DECIMAL(10,2) NOT NULL DEFAULT 0 COMMENT '总重量(kg)'; -2026-05-20 02:29:14,153 INFO 53968 [egg-sequelize](25ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `items_hash` `items_hash` CHAR(32) NOT NULL DEFAULT '' COMMENT 'MD5哈希值(32位)'; -2026-05-20 02:29:14,177 INFO 53968 [egg-sequelize](23ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `items_crc` `items_crc` INTEGER(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'CRC32校验码'; -2026-05-20 02:29:14,204 INFO 53968 [egg-sequelize](27ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `wave_id` `wave_id` BIGINT(20) NOT NULL DEFAULT 0 COMMENT '波次ID,0表示未分配'; -2026-05-20 02:29:14,220 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `post_status` `post_status` ENUM('padding', 'fin', 'timeout', 'error', 'none') DEFAULT 'none' COMMENT '分配快递号状态机'; -2026-05-20 02:29:14,237 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `storage_status` `storage_status` ENUM('padding', 'fin', 'error', 'none') DEFAULT 'none' COMMENT '分配储位状态机'; -2026-05-20 02:29:14,255 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `pick_status` `pick_status` ENUM('padding', 'fin', 'error', 'none') DEFAULT 'none' COMMENT '拣货状态机'; -2026-05-20 02:29:14,272 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `pack_status` `pack_status` ENUM('none', 'padding', 'fin', 'error') DEFAULT 'none' COMMENT '打包状态机'; -2026-05-20 02:29:14,288 INFO 53968 [egg-sequelize](15ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `inspection_status` `inspection_status` ENUM('none', 'padding', 'running', 'fin', 'error') DEFAULT 'none' COMMENT '检验状态机'; -2026-05-20 02:29:14,308 INFO 53968 [egg-sequelize](19ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `step` `step` INTEGER(10) NOT NULL DEFAULT 0 COMMENT '订单步骤:0未审核,1已审核,2处理中,3驳回/异常,4配送中,5已完成,9已关闭'; -2026-05-20 02:29:14,327 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `print_status` `print_status` ENUM('none', 'padding', 'fin', 'error') DEFAULT 'none' COMMENT '打印状态机'; -2026-05-20 02:29:14,343 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `claim_status` `claim_status` ENUM('none', 'padding', 'fin', 'error') DEFAULT 'none' COMMENT '领取状态机'; -2026-05-20 02:29:14,361 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `outbound_status` `outbound_status` ENUM('none', 'padding', 'fin', 'timeout', 'error') DEFAULT 'none' COMMENT '出库状态机'; -2026-05-20 02:29:14,376 INFO 53968 [egg-sequelize](15ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `lock_status` `lock_status` ENUM('none', 'warehouse', 'store') DEFAULT 'none' COMMENT '锁定状态机'; -2026-05-20 02:29:14,393 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `intercept_status` `intercept_status` ENUM('none', 'requesting', 'requested', 'intercepting', 'intercepted_in_transit', 'intercepted_at_warehouse', 'returning', 'returned', 'delivered_by_mistake', 'timeout', 'cancelled', 'failed', 'exception') DEFAULT 'none' COMMENT '拦截状态机'; -2026-05-20 02:29:14,411 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `sys_platform_code` `sys_platform_code` VARCHAR(50) COMMENT '系统平台编码'; -2026-05-20 02:29:14,431 INFO 53968 [egg-sequelize](19ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `sys_platform_name` `sys_platform_name` VARCHAR(200) COMMENT '系统平台名称'; -2026-05-20 02:29:14,452 INFO 53968 [egg-sequelize](21ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `sys_logistics_code` `sys_logistics_code` VARCHAR(50) COMMENT '系统物流公司编码'; -2026-05-20 02:29:14,468 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `sys_logistics_name` `sys_logistics_name` VARCHAR(200) COMMENT '系统物流公司名称'; -2026-05-20 02:29:14,486 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `weight_type` `weight_type` INTEGER(11) NOT NULL DEFAULT 0 COMMENT '重量类型:0常规、1轻货、2重货、3冷链'; -2026-05-20 02:29:14,504 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `source_order_codes` `source_order_codes` TEXT COMMENT '来源订单号集合'; -2026-05-20 02:29:14,519 INFO 53968 [egg-sequelize](15ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `sended_status` `sended_status` ENUM('none', 'padding', 'fin', 'error') DEFAULT 'none' COMMENT '发货状态机'; -2026-05-20 02:29:14,537 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `create_channel` `create_channel` VARCHAR(20) NOT NULL DEFAULT 'MANUAL' COMMENT '创建来源渠道'; -2026-05-20 02:29:14,557 INFO 53968 [egg-sequelize](20ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `basket_number` `basket_number` VARCHAR(50) COMMENT '筐号'; -2026-05-20 02:29:14,574 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `wave_no` `wave_no` VARCHAR(50) NOT NULL DEFAULT '' COMMENT '波次号,空字符串表示未分配'; -2026-05-20 02:29:14,591 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `wave_strategy_version` `wave_strategy_version` INTEGER(10) NOT NULL DEFAULT 0 COMMENT '波次策略版本号'; -2026-05-20 02:29:14,611 INFO 53968 [egg-sequelize](20ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `wave_scan_result` `wave_scan_result` INTEGER(10) NOT NULL DEFAULT 0 COMMENT '波次扫描结果,0未扫描,1扫描符合,2扫描没有符合'; -2026-05-20 02:29:14,631 INFO 53968 [egg-sequelize](19ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `recheck_status` `recheck_status` VARCHAR(20) DEFAULT 'none' COMMENT '复核状态'; -2026-05-20 02:29:14,649 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_100000` CHANGE `recheck_time` `recheck_time` DATETIME COMMENT '复核时间'; -2026-05-20 02:29:14,651 INFO 53968 [egg-sequelize](2ms) Executed (default): SHOW INDEX FROM `wms_order_delivery_100000` -2026-05-20 02:29:14,652 INFO 53968 创建动态模型成功: wms_order_delivery_100000 -2026-05-20 02:29:14,653 INFO 53968 创建订单商品动态模型成功: wms_order_items_100000 -2026-05-20 02:29:14,660 INFO 53968 [egg-sequelize](1ms) Executed (default): SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_SCHEMA = 'wms'; -2026-05-20 02:29:14,663 INFO 53968 [egg-sequelize](2ms) Executed (default): SHOW INDEX FROM `wms_order_delivery_100000_dispatch` -2026-05-20 02:29:14,664 INFO 53968 [egg-sequelize](3ms) Executed (default): SHOW FULL COLUMNS FROM `wms_order_delivery_100000_dispatch`; -2026-05-20 02:29:14,668 INFO 53968 [egg-sequelize](3ms) Executed (default): SHOW FULL COLUMNS FROM `wms_order_delivery_100000_dispatch`; -2026-05-20 02:29:14,670 INFO 53968 [egg-sequelize](1ms) Executed (default): SELECT MAX(CASE WHEN `create_channel` IS NULL THEN 1 ELSE 0 END) AS `create_channel`, MAX(CASE WHEN `weight_type` IS NULL THEN 1 ELSE 0 END) AS `weight_type`, MAX(CASE WHEN `items_count` IS NULL THEN 1 ELSE 0 END) AS `items_count`, MAX(CASE WHEN `items_total` IS NULL THEN 1 ELSE 0 END) AS `items_total`, MAX(CASE WHEN `items_weight` IS NULL THEN 1 ELSE 0 END) AS `items_weight`, MAX(CASE WHEN `items_hash` IS NULL THEN 1 ELSE 0 END) AS `items_hash`, MAX(CASE WHEN `items_crc` IS NULL THEN 1 ELSE 0 END) AS `items_crc`, MAX(CASE WHEN `wave_id` IS NULL THEN 1 ELSE 0 END) AS `wave_id`, MAX(CASE WHEN `wave_no` IS NULL THEN 1 ELSE 0 END) AS `wave_no`, MAX(CASE WHEN `wave_strategy_version` IS NULL THEN 1 ELSE 0 END) AS `wave_strategy_version`, MAX(CASE WHEN `wave_scan_result` IS NULL THEN 1 ELSE 0 END) AS `wave_scan_result`, MAX(CASE WHEN `step` IS NULL THEN 1 ELSE 0 END) AS `step`, MAX(CASE WHEN `dispatch_lane` IS NULL THEN 1 ELSE 0 END) AS `dispatch_lane` FROM `wms_order_delivery_100000_dispatch` WHERE `create_channel` IS NULL OR `weight_type` IS NULL OR `items_count` IS NULL OR `items_total` IS NULL OR `items_weight` IS NULL OR `items_hash` IS NULL OR `items_crc` IS NULL OR `wave_id` IS NULL OR `wave_no` IS NULL OR `wave_strategy_version` IS NULL OR `wave_scan_result` IS NULL OR `step` IS NULL OR `dispatch_lane` IS NULL LIMIT 1 -2026-05-20 02:29:14,671 INFO 53968 [egg-sequelize](1ms) Executed (default): SELECT MAX(CASE WHEN `id` IS NOT NULL AND (`id` < 0 OR `id` > 18446744073709551615) THEN 1 ELSE 0 END) AS `id`, MAX(CASE WHEN `total_amount` IS NOT NULL AND (`total_amount` < -9999999999999999.99 OR `total_amount` > 9999999999999999.99) THEN 1 ELSE 0 END) AS `total_amount`, MAX(CASE WHEN `item_amount` IS NOT NULL AND (`item_amount` < -9999999999999999.99 OR `item_amount` > 9999999999999999.99) THEN 1 ELSE 0 END) AS `item_amount`, MAX(CASE WHEN `discount_amount` IS NOT NULL AND (`discount_amount` < -9999999999999999.99 OR `discount_amount` > 9999999999999999.99) THEN 1 ELSE 0 END) AS `discount_amount`, MAX(CASE WHEN `freight` IS NOT NULL AND (`freight` < -9999999999999999.99 OR `freight` > 9999999999999999.99) THEN 1 ELSE 0 END) AS `freight`, MAX(CASE WHEN `ar_amount` IS NOT NULL AND (`ar_amount` < -9999999999999999.99 OR `ar_amount` > 9999999999999999.99) THEN 1 ELSE 0 END) AS `ar_amount`, MAX(CASE WHEN `got_amount` IS NOT NULL AND (`got_amount` < -9999999999999999.99 OR `got_amount` > 9999999999999999.99) THEN 1 ELSE 0 END) AS `got_amount`, MAX(CASE WHEN `service_fee` IS NOT NULL AND (`service_fee` < -9999999999999999.99 OR `service_fee` > 9999999999999999.99) THEN 1 ELSE 0 END) AS `service_fee`, MAX(CASE WHEN `weight_type` IS NOT NULL AND (`weight_type` < -2147483648 OR `weight_type` > 2147483647) THEN 1 ELSE 0 END) AS `weight_type`, MAX(CASE WHEN `id_number` IS NOT NULL AND (`id_number` < -2147483648 OR `id_number` > 2147483647) THEN 1 ELSE 0 END) AS `id_number`, MAX(CASE WHEN `store_id` IS NOT NULL AND (`store_id` < 0 OR `store_id` > 18446744073709551615) THEN 1 ELSE 0 END) AS `store_id`, MAX(CASE WHEN `warehouse_id` IS NOT NULL AND (`warehouse_id` < 0 OR `warehouse_id` > 18446744073709551615) THEN 1 ELSE 0 END) AS `warehouse_id`, MAX(CASE WHEN `from_key` IS NOT NULL AND (`from_key` < -2147483648 OR `from_key` > 2147483647) THEN 1 ELSE 0 END) AS `from_key`, MAX(CASE WHEN `items_count` IS NOT NULL AND (`items_count` < 0 OR `items_count` > 65535) THEN 1 ELSE 0 END) AS `items_count`, MAX(CASE WHEN `items_total` IS NOT NULL AND (`items_total` < 0 OR `items_total` > 4294967295) THEN 1 ELSE 0 END) AS `items_total`, MAX(CASE WHEN `items_weight` IS NOT NULL AND (`items_weight` < -99999999.99 OR `items_weight` > 99999999.99) THEN 1 ELSE 0 END) AS `items_weight`, MAX(CASE WHEN `items_crc` IS NOT NULL AND (`items_crc` < 0 OR `items_crc` > 4294967295) THEN 1 ELSE 0 END) AS `items_crc`, MAX(CASE WHEN `wave_id` IS NOT NULL AND (`wave_id` < -9223372036854775808 OR `wave_id` > 9223372036854775807) THEN 1 ELSE 0 END) AS `wave_id`, MAX(CASE WHEN `wave_strategy_version` IS NOT NULL AND (`wave_strategy_version` < -2147483648 OR `wave_strategy_version` > 2147483647) THEN 1 ELSE 0 END) AS `wave_strategy_version`, MAX(CASE WHEN `wave_scan_result` IS NOT NULL AND (`wave_scan_result` < -2147483648 OR `wave_scan_result` > 2147483647) THEN 1 ELSE 0 END) AS `wave_scan_result`, MAX(CASE WHEN `step` IS NOT NULL AND (`step` < -2147483648 OR `step` > 2147483647) THEN 1 ELSE 0 END) AS `step` FROM `wms_order_delivery_100000_dispatch` WHERE (`id` IS NOT NULL AND (`id` < 0 OR `id` > 18446744073709551615)) OR (`total_amount` IS NOT NULL AND (`total_amount` < -9999999999999999.99 OR `total_amount` > 9999999999999999.99)) OR (`item_amount` IS NOT NULL AND (`item_amount` < -9999999999999999.99 OR `item_amount` > 9999999999999999.99)) OR (`discount_amount` IS NOT NULL AND (`discount_amount` < -9999999999999999.99 OR `discount_amount` > 9999999999999999.99)) OR (`freight` IS NOT NULL AND (`freight` < -9999999999999999.99 OR `freight` > 9999999999999999.99)) OR (`ar_amount` IS NOT NULL AND (`ar_amount` < -9999999999999999.99 OR `ar_amount` > 9999999999999999.99)) OR (`got_amount` IS NOT NULL AND (`got_amount` < -9999999999999999.99 OR `got_amount` > 9999999999999999.99)) OR (`service_fee` IS NOT NULL AND (`service_fee` < -9999999999999999.99 OR `service_fee` > 9999999999999999.99)) OR (`weight_type` IS NOT NULL AND (`weight_type` < -2147483648 OR `weight_type` > 2147483647)) OR (`id_number` IS NOT NULL AND (`id_number` < -2147483648 OR `id_number` > 2147483647)) OR (`store_id` IS NOT NULL AND (`store_id` < 0 OR `store_id` > 18446744073709551615)) OR (`warehouse_id` IS NOT NULL AND (`warehouse_id` < 0 OR `warehouse_id` > 18446744073709551615)) OR (`from_key` IS NOT NULL AND (`from_key` < -2147483648 OR `from_key` > 2147483647)) OR (`items_count` IS NOT NULL AND (`items_count` < 0 OR `items_count` > 65535)) OR (`items_total` IS NOT NULL AND (`items_total` < 0 OR `items_total` > 4294967295)) OR (`items_weight` IS NOT NULL AND (`items_weight` < -99999999.99 OR `items_weight` > 99999999.99)) OR (`items_crc` IS NOT NULL AND (`items_crc` < 0 OR `items_crc` > 4294967295)) OR (`wave_id` IS NOT NULL AND (`wave_id` < -9223372036854775808 OR `wave_id` > 9223372036854775807)) OR (`wave_strategy_version` IS NOT NULL AND (`wave_strategy_version` < -2147483648 OR `wave_strategy_version` > 2147483647)) OR (`wave_scan_result` IS NOT NULL AND (`wave_scan_result` < -2147483648 OR `wave_scan_result` > 2147483647)) OR (`step` IS NOT NULL AND (`step` < -2147483648 OR `step` > 2147483647)) LIMIT 1 -2026-05-20 02:29:14,673 INFO 53968 [egg-sequelize](2ms) Executed (default): SHOW FULL COLUMNS FROM `wms_order_delivery_100000_dispatch`; -2026-05-20 02:29:14,692 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `id` `id` BIGINT(20) UNSIGNED AUTO_INCREMENT, CHANGE `delivery_order_code` `delivery_order_code` VARCHAR(50) COMMENT '发货单号', CHANGE `pre_delivery_order_code` `pre_delivery_order_code` VARCHAR(50) COMMENT '预发货单号', CHANGE `pre_delivery_order_id` `pre_delivery_order_id` VARCHAR(50) COMMENT '预发货单ID', CHANGE `order_type` `order_type` VARCHAR(50) COMMENT '订单类型', CHANGE `warehouse_code` `warehouse_code` VARCHAR(50) COMMENT '仓库编码', CHANGE `order_flag` `order_flag` LONGTEXT COMMENT '订单标记', CHANGE `source_platform_code` `source_platform_code` VARCHAR(50) COMMENT '来源平台编码', CHANGE `source_platform_name` `source_platform_name` VARCHAR(200) COMMENT '来源平台名称', CHANGE `create_channel` `create_channel` VARCHAR(20) NOT NULL DEFAULT 'MANUAL' COMMENT '创建来源渠道', CHANGE `source_order_codes` `source_order_codes` TEXT COMMENT '来源订单号集合', CHANGE `sys_platform_code` `sys_platform_code` VARCHAR(50) COMMENT '系统平台编码', CHANGE `sys_platform_name` `sys_platform_name` VARCHAR(200) COMMENT '系统平台名称', CHANGE `create_at` `create_at` DATETIME COMMENT '创建时间', CHANGE `delete_at` `delete_at` DATETIME COMMENT '删除时间', CHANGE `updated_at` `updated_at` DATETIME COMMENT '更新时间', CHANGE `place_order_time` `place_order_time` DATETIME COMMENT '店铺创建订单时间', CHANGE `pay_time` `pay_time` DATETIME COMMENT '支付时间', CHANGE `pay_no` `pay_no` VARCHAR(50) COMMENT '支付单号', CHANGE `service_code` `service_code` VARCHAR(50) COMMENT '集包服务编码', CHANGE `operator_name` `operator_name` VARCHAR(50) COMMENT 'ERP审核人', CHANGE `operate_time` `operate_time` DATETIME COMMENT 'ERP审核时间', CHANGE `delivery_time` `delivery_time` DATETIME COMMENT '发货时间', CHANGE `shop_nick` `shop_nick` VARCHAR(200) COMMENT '店铺名称', CHANGE `seller_nick` `seller_nick` VARCHAR(200) COMMENT '卖家名称', CHANGE `buyer_nick` `buyer_nick` VARCHAR(200) COMMENT '买家名称', CHANGE `total_amount` `total_amount` DECIMAL(18,2) COMMENT '订单总金额', CHANGE `item_amount` `item_amount` DECIMAL(18,2) COMMENT '商品总金额', CHANGE `discount_amount` `discount_amount` DECIMAL(18,2) COMMENT '订单折扣金额', CHANGE `freight` `freight` DECIMAL(18,2) COMMENT '快递费用', CHANGE `ar_amount` `ar_amount` DECIMAL(18,2) COMMENT '应收金额', CHANGE `got_amount` `got_amount` DECIMAL(18,2) COMMENT '已收金额', CHANGE `service_fee` `service_fee` DECIMAL(18,2) COMMENT 'COD服务费', CHANGE `logistics_code` `logistics_code` VARCHAR(50) COMMENT '物流公司编码', CHANGE `logistics_name` `logistics_name` VARCHAR(200) COMMENT '物流公司名称', CHANGE `sys_logistics_code` `sys_logistics_code` VARCHAR(50) COMMENT '系统物流公司编码', CHANGE `sys_logistics_name` `sys_logistics_name` VARCHAR(200) COMMENT '系统物流公司名称', CHANGE `basket_number` `basket_number` VARCHAR(50) COMMENT '筐号', CHANGE `express_code` `express_code` VARCHAR(50) COMMENT '面单号前置', CHANGE `logistics_area_code` `logistics_area_code` VARCHAR(50) COMMENT '快递区域编码, 大头笔信息', CHANGE `delivery_type` `delivery_type` VARCHAR(255) COMMENT '发货服务类型', CHANGE `weight_type` `weight_type` INTEGER(11) NOT NULL DEFAULT 0 COMMENT '重量类型:0常规、1轻货、2重货、3冷链', CHANGE `is_urgency` `is_urgency` ENUM('Y', 'N') DEFAULT 'N' COMMENT '是否紧急', CHANGE `invoice_flag` `invoice_flag` ENUM('Y', 'N') DEFAULT 'N' COMMENT '是否需要发票', CHANGE `status` `status` ENUM('pedding', 'created', 'cancel', 'error') DEFAULT 'created' COMMENT '订单状态', CHANGE `name` `name` TEXT COMMENT '收件人姓名', CHANGE `zip_code` `zip_code` VARCHAR(50) COMMENT '收件人邮编', CHANGE `tel` `tel` TEXT COMMENT '收件人电话', CHANGE `mobile` `mobile` TEXT COMMENT '收件人移动电话', CHANGE `email` `email` TEXT COMMENT '收件人邮箱', CHANGE `country_code` `country_code` VARCHAR(255) COMMENT '国家编码', CHANGE `province` `province` VARCHAR(255) COMMENT '省份', CHANGE `city` `city` VARCHAR(255) COMMENT '城市', CHANGE `area` `area` VARCHAR(255) COMMENT '区', CHANGE `town` `town` VARCHAR(255) COMMENT '镇', CHANGE `detail_address` `detail_address` TEXT COMMENT '详细地址', CHANGE `id_type` `id_type` VARCHAR(255) COMMENT '证件类型', CHANGE `id_number` `id_number` INTEGER(11) COMMENT '证件号码', CHANGE `oaid` `oaid` TEXT COMMENT 'OAID', CHANGE `sync_status` `sync_status` ENUM('padding', 'fin', 'error') DEFAULT 'padding' COMMENT '同步状态', CHANGE `store_id` `store_id` BIGINT(20) UNSIGNED COMMENT '货主ID', CHANGE `warehouse_id` `warehouse_id` BIGINT(20) UNSIGNED COMMENT '仓库ID', CHANGE `from_key` `from_key` INTEGER(11) COMMENT '来源键', CHANGE `items` `items` TEXT COMMENT '商品JSON字符串', CHANGE `items_count` `items_count` SMALLINT(5) UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品种类数', CHANGE `items_total` `items_total` INTEGER(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品总数', CHANGE `items_weight` `items_weight` DECIMAL(10,2) NOT NULL DEFAULT 0 COMMENT '总重量(kg)', CHANGE `items_hash` `items_hash` CHAR(32) NOT NULL DEFAULT '' COMMENT 'MD5哈希值(32位)', CHANGE `items_crc` `items_crc` INTEGER(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'CRC32校验码', CHANGE `wave_id` `wave_id` BIGINT(20) NOT NULL DEFAULT 0 COMMENT '波次ID,0表示未分配', CHANGE `wave_no` `wave_no` VARCHAR(50) NOT NULL DEFAULT '' COMMENT '波次号,空字符串表示未分配', CHANGE `wave_strategy_version` `wave_strategy_version` INTEGER(10) NOT NULL DEFAULT 0 COMMENT '波次策略版本号', CHANGE `wave_scan_result` `wave_scan_result` INTEGER(10) NOT NULL DEFAULT 0 COMMENT '波次扫描结果,0未扫描,1扫描符合,2扫描没有符合', CHANGE `post_status` `post_status` ENUM('padding', 'fin', 'timeout', 'error', 'none') DEFAULT 'none' COMMENT '分配快递号状态机', CHANGE `storage_status` `storage_status` ENUM('padding', 'fin', 'error', 'none') DEFAULT 'none' COMMENT '分配储位状态机', CHANGE `pick_status` `pick_status` ENUM('padding', 'fin', 'error', 'none') DEFAULT 'none' COMMENT '拣货状态机', CHANGE `pack_status` `pack_status` ENUM('none', 'padding', 'fin', 'error') DEFAULT 'none' COMMENT '打包状态机', CHANGE `sended_status` `sended_status` ENUM('none', 'padding', 'fin', 'error') DEFAULT 'none' COMMENT '发货状态机', CHANGE `inspection_status` `inspection_status` ENUM('none', 'padding', 'running', 'fin', 'error') DEFAULT 'none' COMMENT '检验状态机', CHANGE `recheck_status` `recheck_status` VARCHAR(20) DEFAULT 'none' COMMENT '复核状态', CHANGE `recheck_time` `recheck_time` DATETIME COMMENT '复核时间', CHANGE `step` `step` INTEGER(10) NOT NULL DEFAULT 0 COMMENT '订单步骤:0未审核,1已审核,2处理中,3驳回/异常,4配送中,5已完成,9已关闭', CHANGE `print_status` `print_status` ENUM('none', 'padding', 'fin', 'error') DEFAULT 'none' COMMENT '打印状态机', CHANGE `claim_status` `claim_status` ENUM('none', 'padding', 'fin', 'error') DEFAULT 'none' COMMENT '领取状态机', CHANGE `outbound_status` `outbound_status` ENUM('none', 'padding', 'fin', 'timeout', 'error') DEFAULT 'none' COMMENT '出库状态机', CHANGE `lock_status` `lock_status` ENUM('none', 'warehouse', 'store') DEFAULT 'none' COMMENT '锁定状态机', CHANGE `intercept_status` `intercept_status` ENUM('none', 'requesting', 'requested', 'intercepting', 'intercepted_in_transit', 'intercepted_at_warehouse', 'returning', 'returned', 'delivered_by_mistake', 'timeout', 'cancelled', 'failed', 'exception') DEFAULT 'none' COMMENT '拦截状态机', CHANGE `dispatch_lane` `dispatch_lane` ENUM('m4', 'm5') NOT NULL DEFAULT 'm4' COMMENT '配送工作台子域(M4正常/M5异常)' -2026-05-20 02:29:14,693 INFO 53968 [egg-sequelize](1ms) Executed (default): SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_NAME = 'wms_order_delivery_100000_dispatch' AND TABLE_SCHEMA = 'wms' -2026-05-20 02:29:14,694 INFO 53968 [egg-sequelize](1ms) Executed (default): SELECT CONSTRAINT_NAME as constraint_name,CONSTRAINT_NAME as constraintName,CONSTRAINT_SCHEMA as constraintSchema,CONSTRAINT_SCHEMA as constraintCatalog,TABLE_NAME as tableName,TABLE_SCHEMA as tableSchema,TABLE_SCHEMA as tableCatalog,COLUMN_NAME as columnName,REFERENCED_TABLE_SCHEMA as referencedTableSchema,REFERENCED_TABLE_SCHEMA as referencedTableCatalog,REFERENCED_TABLE_NAME as referencedTableName,REFERENCED_COLUMN_NAME as referencedColumnName FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE where TABLE_NAME = 'wms_order_delivery_100000_dispatch' AND CONSTRAINT_NAME!='PRIMARY' AND CONSTRAINT_SCHEMA='wms' AND REFERENCED_TABLE_NAME IS NOT NULL; -2026-05-20 02:29:14,695 INFO 53968 [egg-sequelize](2ms) Executed (default): SHOW FULL COLUMNS FROM `wms_order_delivery_100000_dispatch`; -2026-05-20 02:29:14,718 INFO 53968 [egg-sequelize](23ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `delivery_order_code` `delivery_order_code` VARCHAR(50) COMMENT '发货单号'; -2026-05-20 02:29:14,740 INFO 53968 [egg-sequelize](21ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `pre_delivery_order_code` `pre_delivery_order_code` VARCHAR(50) COMMENT '预发货单号'; -2026-05-20 02:29:14,755 INFO 53968 [egg-sequelize](15ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `pre_delivery_order_id` `pre_delivery_order_id` VARCHAR(50) COMMENT '预发货单ID'; -2026-05-20 02:29:14,773 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `order_type` `order_type` VARCHAR(50) COMMENT '订单类型'; -2026-05-20 02:29:14,789 INFO 53968 [egg-sequelize](15ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `warehouse_code` `warehouse_code` VARCHAR(50) COMMENT '仓库编码'; -2026-05-20 02:29:14,810 INFO 53968 [egg-sequelize](20ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `order_flag` `order_flag` LONGTEXT COMMENT '订单标记'; -2026-05-20 02:29:14,827 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `source_platform_code` `source_platform_code` VARCHAR(50) COMMENT '来源平台编码'; -2026-05-20 02:29:14,850 INFO 53968 [egg-sequelize](23ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `source_platform_name` `source_platform_name` VARCHAR(200) COMMENT '来源平台名称'; -2026-05-20 02:29:14,876 INFO 53968 [egg-sequelize](26ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `source_order_codes` `source_order_codes` TEXT COMMENT '来源订单号集合'; -2026-05-20 02:29:14,894 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `create_at` `create_at` DATETIME COMMENT '创建时间'; -2026-05-20 02:29:14,911 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `delete_at` `delete_at` DATETIME COMMENT '删除时间'; -2026-05-20 02:29:14,927 INFO 53968 [egg-sequelize](15ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `updated_at` `updated_at` DATETIME COMMENT '更新时间'; -2026-05-20 02:29:14,946 INFO 53968 [egg-sequelize](19ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `place_order_time` `place_order_time` DATETIME COMMENT '店铺创建订单时间'; -2026-05-20 02:29:14,968 INFO 53968 [egg-sequelize](21ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `pay_time` `pay_time` DATETIME COMMENT '支付时间'; -2026-05-20 02:29:14,988 INFO 53968 [egg-sequelize](19ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `pay_no` `pay_no` VARCHAR(50) COMMENT '支付单号'; -2026-05-20 02:29:15,003 INFO 53968 [egg-sequelize](15ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `service_code` `service_code` VARCHAR(50) COMMENT '集包服务编码'; -2026-05-20 02:29:15,021 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `operator_name` `operator_name` VARCHAR(50) COMMENT 'ERP审核人'; -2026-05-20 02:29:15,039 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `operate_time` `operate_time` DATETIME COMMENT 'ERP审核时间'; -2026-05-20 02:29:15,066 INFO 53968 [egg-sequelize](27ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `delivery_time` `delivery_time` DATETIME COMMENT '发货时间'; -2026-05-20 02:29:15,086 INFO 53968 [egg-sequelize](20ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `shop_nick` `shop_nick` VARCHAR(200) COMMENT '店铺名称'; -2026-05-20 02:29:15,102 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `seller_nick` `seller_nick` VARCHAR(200) COMMENT '卖家名称'; -2026-05-20 02:29:15,120 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `buyer_nick` `buyer_nick` VARCHAR(200) COMMENT '买家名称'; -2026-05-20 02:29:15,138 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `total_amount` `total_amount` DECIMAL(18,2) COMMENT '订单总金额'; -2026-05-20 02:29:15,157 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `item_amount` `item_amount` DECIMAL(18,2) COMMENT '商品总金额'; -2026-05-20 02:29:15,179 INFO 53968 [egg-sequelize](22ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `discount_amount` `discount_amount` DECIMAL(18,2) COMMENT '订单折扣金额'; -2026-05-20 02:29:15,201 INFO 53968 [egg-sequelize](21ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `freight` `freight` DECIMAL(18,2) COMMENT '快递费用'; -2026-05-20 02:29:15,220 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `ar_amount` `ar_amount` DECIMAL(18,2) COMMENT '应收金额'; -2026-05-20 02:29:15,237 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `got_amount` `got_amount` DECIMAL(18,2) COMMENT '已收金额'; -2026-05-20 02:29:15,255 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `service_fee` `service_fee` DECIMAL(18,2) COMMENT 'COD服务费'; -2026-05-20 02:29:15,277 INFO 53968 [egg-sequelize](22ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `logistics_code` `logistics_code` VARCHAR(50) COMMENT '物流公司编码'; -2026-05-20 02:29:15,295 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `logistics_name` `logistics_name` VARCHAR(200) COMMENT '物流公司名称'; -2026-05-20 02:29:15,314 INFO 53968 [egg-sequelize](19ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `express_code` `express_code` VARCHAR(50) COMMENT '面单号前置'; -2026-05-20 02:29:15,334 INFO 53968 [egg-sequelize](20ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `logistics_area_code` `logistics_area_code` VARCHAR(50) COMMENT '快递区域编码, 大头笔信息'; -2026-05-20 02:29:15,352 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `delivery_type` `delivery_type` VARCHAR(255) COMMENT '发货服务类型'; -2026-05-20 02:29:15,368 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `weight_type` `weight_type` INTEGER(11) NOT NULL DEFAULT 0 COMMENT '重量类型:0常规、1轻货、2重货、3冷链'; -2026-05-20 02:29:15,387 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `is_urgency` `is_urgency` ENUM('Y', 'N') DEFAULT 'N' COMMENT '是否紧急'; -2026-05-20 02:29:15,406 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `invoice_flag` `invoice_flag` ENUM('Y', 'N') DEFAULT 'N' COMMENT '是否需要发票'; -2026-05-20 02:29:15,433 INFO 53968 [egg-sequelize](27ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `status` `status` ENUM('pedding', 'created', 'cancel', 'error') DEFAULT 'created' COMMENT '订单状态'; -2026-05-20 02:29:15,454 INFO 53968 [egg-sequelize](20ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `name` `name` TEXT COMMENT '收件人姓名'; -2026-05-20 02:29:15,474 INFO 53968 [egg-sequelize](20ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `zip_code` `zip_code` VARCHAR(50) COMMENT '收件人邮编'; -2026-05-20 02:29:15,490 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `tel` `tel` TEXT COMMENT '收件人电话'; -2026-05-20 02:29:15,518 INFO 53968 [egg-sequelize](27ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `mobile` `mobile` TEXT COMMENT '收件人移动电话'; -2026-05-20 02:29:15,537 INFO 53968 [egg-sequelize](19ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `email` `email` TEXT COMMENT '收件人邮箱'; -2026-05-20 02:29:15,555 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `country_code` `country_code` VARCHAR(255) COMMENT '国家编码'; -2026-05-20 02:29:15,574 INFO 53968 [egg-sequelize](19ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `province` `province` VARCHAR(255) COMMENT '省份'; -2026-05-20 02:29:15,592 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `city` `city` VARCHAR(255) COMMENT '城市'; -2026-05-20 02:29:15,610 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `area` `area` VARCHAR(255) COMMENT '区'; -2026-05-20 02:29:15,627 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `town` `town` VARCHAR(255) COMMENT '镇'; -2026-05-20 02:29:15,644 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `detail_address` `detail_address` TEXT COMMENT '详细地址'; -2026-05-20 02:29:15,660 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `id_type` `id_type` VARCHAR(255) COMMENT '证件类型'; -2026-05-20 02:29:15,677 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `id_number` `id_number` INTEGER(11) COMMENT '证件号码'; -2026-05-20 02:29:15,697 INFO 53968 [egg-sequelize](20ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `oaid` `oaid` TEXT COMMENT 'OAID'; -2026-05-20 02:29:15,718 INFO 53968 [egg-sequelize](20ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `sync_status` `sync_status` ENUM('padding', 'fin', 'error') DEFAULT 'padding' COMMENT '同步状态'; -2026-05-20 02:29:15,735 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `store_id` `store_id` BIGINT(20) UNSIGNED COMMENT '货主ID'; -2026-05-20 02:29:15,751 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `warehouse_id` `warehouse_id` BIGINT(20) UNSIGNED COMMENT '仓库ID'; -2026-05-20 02:29:15,770 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `from_key` `from_key` INTEGER(11) COMMENT '来源键'; -2026-05-20 02:29:15,790 INFO 53968 [egg-sequelize](20ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `items` `items` TEXT COMMENT '商品JSON字符串'; -2026-05-20 02:29:15,811 INFO 53968 [egg-sequelize](20ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `items_count` `items_count` SMALLINT(5) UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品种类数'; -2026-05-20 02:29:15,838 INFO 53968 [egg-sequelize](27ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `items_total` `items_total` INTEGER(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品总数'; -2026-05-20 02:29:15,853 INFO 53968 [egg-sequelize](15ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `items_weight` `items_weight` DECIMAL(10,2) NOT NULL DEFAULT 0 COMMENT '总重量(kg)'; -2026-05-20 02:29:15,871 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `items_hash` `items_hash` CHAR(32) NOT NULL DEFAULT '' COMMENT 'MD5哈希值(32位)'; -2026-05-20 02:29:15,887 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `items_crc` `items_crc` INTEGER(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'CRC32校验码'; -2026-05-20 02:29:15,904 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `wave_id` `wave_id` BIGINT(20) NOT NULL DEFAULT 0 COMMENT '波次ID,0表示未分配'; -2026-05-20 02:29:15,919 INFO 53968 [egg-sequelize](14ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `post_status` `post_status` ENUM('padding', 'fin', 'timeout', 'error', 'none') DEFAULT 'none' COMMENT '分配快递号状态机'; -2026-05-20 02:29:15,935 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `storage_status` `storage_status` ENUM('padding', 'fin', 'error', 'none') DEFAULT 'none' COMMENT '分配储位状态机'; -2026-05-20 02:29:15,957 INFO 53968 [egg-sequelize](22ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `pick_status` `pick_status` ENUM('padding', 'fin', 'error', 'none') DEFAULT 'none' COMMENT '拣货状态机'; -2026-05-20 02:29:15,975 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `pack_status` `pack_status` ENUM('none', 'padding', 'fin', 'error') DEFAULT 'none' COMMENT '打包状态机'; -2026-05-20 02:29:15,994 INFO 53968 [egg-sequelize](19ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `inspection_status` `inspection_status` ENUM('none', 'padding', 'running', 'fin', 'error') DEFAULT 'none' COMMENT '检验状态机'; -2026-05-20 02:29:16,013 INFO 53968 [egg-sequelize](19ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `step` `step` INTEGER(10) NOT NULL DEFAULT 0 COMMENT '订单步骤:0未审核,1已审核,2处理中,3驳回/异常,4配送中,5已完成,9已关闭'; -2026-05-20 02:29:16,030 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `print_status` `print_status` ENUM('none', 'padding', 'fin', 'error') DEFAULT 'none' COMMENT '打印状态机'; -2026-05-20 02:29:16,047 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `claim_status` `claim_status` ENUM('none', 'padding', 'fin', 'error') DEFAULT 'none' COMMENT '领取状态机'; -2026-05-20 02:29:16,069 INFO 53968 [egg-sequelize](21ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `outbound_status` `outbound_status` ENUM('none', 'padding', 'fin', 'timeout', 'error') DEFAULT 'none' COMMENT '出库状态机'; -2026-05-20 02:29:16,086 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `lock_status` `lock_status` ENUM('none', 'warehouse', 'store') DEFAULT 'none' COMMENT '锁定状态机'; -2026-05-20 02:29:16,102 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `intercept_status` `intercept_status` ENUM('none', 'requesting', 'requested', 'intercepting', 'intercepted_in_transit', 'intercepted_at_warehouse', 'returning', 'returned', 'delivered_by_mistake', 'timeout', 'cancelled', 'failed', 'exception') DEFAULT 'none' COMMENT '拦截状态机'; -2026-05-20 02:29:16,118 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `dispatch_lane` `dispatch_lane` ENUM('m4', 'm5') NOT NULL DEFAULT 'm4' COMMENT '配送工作台子域(M4正常/M5异常)'; -2026-05-20 02:29:16,135 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `sys_platform_code` `sys_platform_code` VARCHAR(50) COMMENT '系统平台编码'; -2026-05-20 02:29:16,151 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `sys_platform_name` `sys_platform_name` VARCHAR(200) COMMENT '系统平台名称'; -2026-05-20 02:29:16,167 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `sys_logistics_code` `sys_logistics_code` VARCHAR(50) COMMENT '系统物流公司编码'; -2026-05-20 02:29:16,186 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `sys_logistics_name` `sys_logistics_name` VARCHAR(200) COMMENT '系统物流公司名称'; -2026-05-20 02:29:16,202 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `sended_status` `sended_status` ENUM('none', 'padding', 'fin', 'error') DEFAULT 'none' COMMENT '发货状态机'; -2026-05-20 02:29:16,218 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `create_channel` `create_channel` VARCHAR(20) NOT NULL DEFAULT 'MANUAL' COMMENT '创建来源渠道'; -2026-05-20 02:29:16,235 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `basket_number` `basket_number` VARCHAR(50) COMMENT '筐号'; -2026-05-20 02:29:16,259 INFO 53968 [egg-sequelize](24ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `wave_no` `wave_no` VARCHAR(50) NOT NULL DEFAULT '' COMMENT '波次号,空字符串表示未分配'; -2026-05-20 02:29:16,275 INFO 53968 [egg-sequelize](15ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `wave_strategy_version` `wave_strategy_version` INTEGER(10) NOT NULL DEFAULT 0 COMMENT '波次策略版本号'; -2026-05-20 02:29:16,293 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `wave_scan_result` `wave_scan_result` INTEGER(10) NOT NULL DEFAULT 0 COMMENT '波次扫描结果,0未扫描,1扫描符合,2扫描没有符合'; -2026-05-20 02:29:16,311 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `recheck_status` `recheck_status` VARCHAR(20) DEFAULT 'none' COMMENT '复核状态'; -2026-05-20 02:29:16,329 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_100000_dispatch` CHANGE `recheck_time` `recheck_time` DATETIME COMMENT '复核时间'; -2026-05-20 02:29:16,332 INFO 53968 [egg-sequelize](2ms) Executed (default): SHOW INDEX FROM `wms_order_delivery_100000_dispatch` -2026-05-20 02:29:16,336 INFO 53968 创建动态模型成功: wms_order_delivery_100000_dispatch -2026-05-20 02:29:16,337 INFO 53968 创建订单商品动态模型成功: wms_order_items_100000_dispatch -2026-05-20 02:29:16,571 INFO 53968 [egg-sequelize](234ms) Executed (4fea7690-c022-4eed-b2a1-ee012f39ebe9): SELECT `id`, `delivery_order_code`, `pre_delivery_order_code`, `pre_delivery_order_id`, `order_type`, `warehouse_code`, `order_flag`, `source_platform_code`, `source_platform_name`, `create_channel`, `source_order_codes`, `sys_platform_code`, `sys_platform_name`, `create_at`, `delete_at`, `updated_at`, `place_order_time`, `pay_time`, `pay_no`, `service_code`, `operator_name`, `operate_time`, `delivery_time`, `shop_nick`, `seller_nick`, `buyer_nick`, `total_amount`, `item_amount`, `discount_amount`, `freight`, `ar_amount`, `got_amount`, `service_fee`, `logistics_code`, `logistics_name`, `sys_logistics_code`, `sys_logistics_name`, `basket_number`, `express_code`, `logistics_area_code`, `delivery_type`, `weight_type`, `is_urgency`, `invoice_flag`, `status`, `name`, `zip_code`, `tel`, `mobile`, `email`, `country_code`, `province`, `city`, `area`, `town`, `detail_address`, `id_type`, `id_number`, `oaid`, `sync_status`, `store_id`, `warehouse_id`, `from_key`, `items`, `items_count`, `items_total`, `items_weight`, `items_hash`, `items_crc`, `wave_id`, `wave_no`, `wave_strategy_version`, `wave_scan_result`, `post_status`, `storage_status`, `pick_status`, `pack_status`, `sended_status`, `inspection_status`, `recheck_status`, `recheck_time`, `step`, `print_status`, `claim_status`, `outbound_status`, `lock_status`, `intercept_status` FROM `wms_order_delivery_100000` AS `wms_order_delivery_100000` WHERE `wms_order_delivery_100000`.`warehouse_id` = 100000 AND `wms_order_delivery_100000`.`outbound_status` IN ('fin', 'padding') AND `wms_order_delivery_100000`.`step` IN (4, 9) ORDER BY `wms_order_delivery_100000`.`id` ASC LIMIT 1000; -2026-05-20 02:29:16,572 INFO 53968 [egg-sequelize](1ms) Executed (4fea7690-c022-4eed-b2a1-ee012f39ebe9): COMMIT; -2026-05-20 02:29:16,572 INFO 53968 [egg-sequelize](0ms) Executed (7c72e31e-15ee-45dc-a822-626dfe09a9fd): START TRANSACTION; -2026-05-20 02:29:16,573 INFO 53968 [egg-sequelize](0ms) Executed (default): SELECT `id` FROM `wms_store` AS `store` WHERE (`store`.`deleted_at` IS NULL AND (`store`.`id` = '1000028' AND `store`.`project` = 'warehouse')); -2026-05-20 02:29:16,575 INFO 53968 [egg-sequelize](1ms) Executed (default): SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_SCHEMA = 'wms'; -2026-05-20 02:29:16,577 INFO 53968 [egg-sequelize](1ms) Executed (default): SHOW INDEX FROM `wms_order_delivery_1000028` -2026-05-20 02:29:16,577 INFO 53968 [egg-sequelize](1ms) Executed (default): SHOW FULL COLUMNS FROM `wms_order_delivery_1000028`; -2026-05-20 02:29:16,581 INFO 53968 [egg-sequelize](3ms) Executed (default): SHOW FULL COLUMNS FROM `wms_order_delivery_1000028`; -2026-05-20 02:29:16,584 INFO 53968 [egg-sequelize](1ms) Executed (default): SELECT MAX(CASE WHEN `create_channel` IS NULL THEN 1 ELSE 0 END) AS `create_channel`, MAX(CASE WHEN `weight_type` IS NULL THEN 1 ELSE 0 END) AS `weight_type`, MAX(CASE WHEN `items_count` IS NULL THEN 1 ELSE 0 END) AS `items_count`, MAX(CASE WHEN `items_total` IS NULL THEN 1 ELSE 0 END) AS `items_total`, MAX(CASE WHEN `items_weight` IS NULL THEN 1 ELSE 0 END) AS `items_weight`, MAX(CASE WHEN `items_hash` IS NULL THEN 1 ELSE 0 END) AS `items_hash`, MAX(CASE WHEN `items_crc` IS NULL THEN 1 ELSE 0 END) AS `items_crc`, MAX(CASE WHEN `wave_id` IS NULL THEN 1 ELSE 0 END) AS `wave_id`, MAX(CASE WHEN `wave_no` IS NULL THEN 1 ELSE 0 END) AS `wave_no`, MAX(CASE WHEN `wave_strategy_version` IS NULL THEN 1 ELSE 0 END) AS `wave_strategy_version`, MAX(CASE WHEN `wave_scan_result` IS NULL THEN 1 ELSE 0 END) AS `wave_scan_result`, MAX(CASE WHEN `step` IS NULL THEN 1 ELSE 0 END) AS `step` FROM `wms_order_delivery_1000028` WHERE `create_channel` IS NULL OR `weight_type` IS NULL OR `items_count` IS NULL OR `items_total` IS NULL OR `items_weight` IS NULL OR `items_hash` IS NULL OR `items_crc` IS NULL OR `wave_id` IS NULL OR `wave_no` IS NULL OR `wave_strategy_version` IS NULL OR `wave_scan_result` IS NULL OR `step` IS NULL LIMIT 1 -2026-05-20 02:29:16,585 INFO 53968 [egg-sequelize](1ms) Executed (default): SELECT MAX(CASE WHEN `id` IS NOT NULL AND (`id` < 0 OR `id` > 18446744073709551615) THEN 1 ELSE 0 END) AS `id`, MAX(CASE WHEN `total_amount` IS NOT NULL AND (`total_amount` < -9999999999999999.99 OR `total_amount` > 9999999999999999.99) THEN 1 ELSE 0 END) AS `total_amount`, MAX(CASE WHEN `item_amount` IS NOT NULL AND (`item_amount` < -9999999999999999.99 OR `item_amount` > 9999999999999999.99) THEN 1 ELSE 0 END) AS `item_amount`, MAX(CASE WHEN `discount_amount` IS NOT NULL AND (`discount_amount` < -9999999999999999.99 OR `discount_amount` > 9999999999999999.99) THEN 1 ELSE 0 END) AS `discount_amount`, MAX(CASE WHEN `freight` IS NOT NULL AND (`freight` < -9999999999999999.99 OR `freight` > 9999999999999999.99) THEN 1 ELSE 0 END) AS `freight`, MAX(CASE WHEN `ar_amount` IS NOT NULL AND (`ar_amount` < -9999999999999999.99 OR `ar_amount` > 9999999999999999.99) THEN 1 ELSE 0 END) AS `ar_amount`, MAX(CASE WHEN `got_amount` IS NOT NULL AND (`got_amount` < -9999999999999999.99 OR `got_amount` > 9999999999999999.99) THEN 1 ELSE 0 END) AS `got_amount`, MAX(CASE WHEN `service_fee` IS NOT NULL AND (`service_fee` < -9999999999999999.99 OR `service_fee` > 9999999999999999.99) THEN 1 ELSE 0 END) AS `service_fee`, MAX(CASE WHEN `weight_type` IS NOT NULL AND (`weight_type` < -2147483648 OR `weight_type` > 2147483647) THEN 1 ELSE 0 END) AS `weight_type`, MAX(CASE WHEN `id_number` IS NOT NULL AND (`id_number` < -2147483648 OR `id_number` > 2147483647) THEN 1 ELSE 0 END) AS `id_number`, MAX(CASE WHEN `store_id` IS NOT NULL AND (`store_id` < 0 OR `store_id` > 18446744073709551615) THEN 1 ELSE 0 END) AS `store_id`, MAX(CASE WHEN `warehouse_id` IS NOT NULL AND (`warehouse_id` < 0 OR `warehouse_id` > 18446744073709551615) THEN 1 ELSE 0 END) AS `warehouse_id`, MAX(CASE WHEN `from_key` IS NOT NULL AND (`from_key` < -2147483648 OR `from_key` > 2147483647) THEN 1 ELSE 0 END) AS `from_key`, MAX(CASE WHEN `items_count` IS NOT NULL AND (`items_count` < 0 OR `items_count` > 65535) THEN 1 ELSE 0 END) AS `items_count`, MAX(CASE WHEN `items_total` IS NOT NULL AND (`items_total` < 0 OR `items_total` > 4294967295) THEN 1 ELSE 0 END) AS `items_total`, MAX(CASE WHEN `items_weight` IS NOT NULL AND (`items_weight` < -99999999.99 OR `items_weight` > 99999999.99) THEN 1 ELSE 0 END) AS `items_weight`, MAX(CASE WHEN `items_crc` IS NOT NULL AND (`items_crc` < 0 OR `items_crc` > 4294967295) THEN 1 ELSE 0 END) AS `items_crc`, MAX(CASE WHEN `wave_id` IS NOT NULL AND (`wave_id` < -9223372036854775808 OR `wave_id` > 9223372036854775807) THEN 1 ELSE 0 END) AS `wave_id`, MAX(CASE WHEN `wave_strategy_version` IS NOT NULL AND (`wave_strategy_version` < -2147483648 OR `wave_strategy_version` > 2147483647) THEN 1 ELSE 0 END) AS `wave_strategy_version`, MAX(CASE WHEN `wave_scan_result` IS NOT NULL AND (`wave_scan_result` < -2147483648 OR `wave_scan_result` > 2147483647) THEN 1 ELSE 0 END) AS `wave_scan_result`, MAX(CASE WHEN `step` IS NOT NULL AND (`step` < -2147483648 OR `step` > 2147483647) THEN 1 ELSE 0 END) AS `step` FROM `wms_order_delivery_1000028` WHERE (`id` IS NOT NULL AND (`id` < 0 OR `id` > 18446744073709551615)) OR (`total_amount` IS NOT NULL AND (`total_amount` < -9999999999999999.99 OR `total_amount` > 9999999999999999.99)) OR (`item_amount` IS NOT NULL AND (`item_amount` < -9999999999999999.99 OR `item_amount` > 9999999999999999.99)) OR (`discount_amount` IS NOT NULL AND (`discount_amount` < -9999999999999999.99 OR `discount_amount` > 9999999999999999.99)) OR (`freight` IS NOT NULL AND (`freight` < -9999999999999999.99 OR `freight` > 9999999999999999.99)) OR (`ar_amount` IS NOT NULL AND (`ar_amount` < -9999999999999999.99 OR `ar_amount` > 9999999999999999.99)) OR (`got_amount` IS NOT NULL AND (`got_amount` < -9999999999999999.99 OR `got_amount` > 9999999999999999.99)) OR (`service_fee` IS NOT NULL AND (`service_fee` < -9999999999999999.99 OR `service_fee` > 9999999999999999.99)) OR (`weight_type` IS NOT NULL AND (`weight_type` < -2147483648 OR `weight_type` > 2147483647)) OR (`id_number` IS NOT NULL AND (`id_number` < -2147483648 OR `id_number` > 2147483647)) OR (`store_id` IS NOT NULL AND (`store_id` < 0 OR `store_id` > 18446744073709551615)) OR (`warehouse_id` IS NOT NULL AND (`warehouse_id` < 0 OR `warehouse_id` > 18446744073709551615)) OR (`from_key` IS NOT NULL AND (`from_key` < -2147483648 OR `from_key` > 2147483647)) OR (`items_count` IS NOT NULL AND (`items_count` < 0 OR `items_count` > 65535)) OR (`items_total` IS NOT NULL AND (`items_total` < 0 OR `items_total` > 4294967295)) OR (`items_weight` IS NOT NULL AND (`items_weight` < -99999999.99 OR `items_weight` > 99999999.99)) OR (`items_crc` IS NOT NULL AND (`items_crc` < 0 OR `items_crc` > 4294967295)) OR (`wave_id` IS NOT NULL AND (`wave_id` < -9223372036854775808 OR `wave_id` > 9223372036854775807)) OR (`wave_strategy_version` IS NOT NULL AND (`wave_strategy_version` < -2147483648 OR `wave_strategy_version` > 2147483647)) OR (`wave_scan_result` IS NOT NULL AND (`wave_scan_result` < -2147483648 OR `wave_scan_result` > 2147483647)) OR (`step` IS NOT NULL AND (`step` < -2147483648 OR `step` > 2147483647)) LIMIT 1 -2026-05-20 02:29:16,587 INFO 53968 [egg-sequelize](2ms) Executed (default): SHOW FULL COLUMNS FROM `wms_order_delivery_1000028`; -2026-05-20 02:29:16,608 INFO 53968 [egg-sequelize](20ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `id` `id` BIGINT(20) UNSIGNED AUTO_INCREMENT, CHANGE `delivery_order_code` `delivery_order_code` VARCHAR(50) COMMENT '发货单号', CHANGE `pre_delivery_order_code` `pre_delivery_order_code` VARCHAR(50) COMMENT '预发货单号', CHANGE `pre_delivery_order_id` `pre_delivery_order_id` VARCHAR(50) COMMENT '预发货单ID', CHANGE `order_type` `order_type` VARCHAR(50) COMMENT '订单类型', CHANGE `warehouse_code` `warehouse_code` VARCHAR(50) COMMENT '仓库编码', CHANGE `order_flag` `order_flag` LONGTEXT COMMENT '订单标记', CHANGE `source_platform_code` `source_platform_code` VARCHAR(50) COMMENT '来源平台编码', CHANGE `source_platform_name` `source_platform_name` VARCHAR(200) COMMENT '来源平台名称', CHANGE `create_channel` `create_channel` VARCHAR(20) NOT NULL DEFAULT 'MANUAL' COMMENT '创建来源渠道', CHANGE `source_order_codes` `source_order_codes` TEXT COMMENT '来源订单号集合', CHANGE `sys_platform_code` `sys_platform_code` VARCHAR(50) COMMENT '系统平台编码', CHANGE `sys_platform_name` `sys_platform_name` VARCHAR(200) COMMENT '系统平台名称', CHANGE `create_at` `create_at` DATETIME COMMENT '创建时间', CHANGE `delete_at` `delete_at` DATETIME COMMENT '删除时间', CHANGE `updated_at` `updated_at` DATETIME COMMENT '更新时间', CHANGE `place_order_time` `place_order_time` DATETIME COMMENT '店铺创建订单时间', CHANGE `pay_time` `pay_time` DATETIME COMMENT '支付时间', CHANGE `pay_no` `pay_no` VARCHAR(50) COMMENT '支付单号', CHANGE `service_code` `service_code` VARCHAR(50) COMMENT '集包服务编码', CHANGE `operator_name` `operator_name` VARCHAR(50) COMMENT 'ERP审核人', CHANGE `operate_time` `operate_time` DATETIME COMMENT 'ERP审核时间', CHANGE `delivery_time` `delivery_time` DATETIME COMMENT '发货时间', CHANGE `shop_nick` `shop_nick` VARCHAR(200) COMMENT '店铺名称', CHANGE `seller_nick` `seller_nick` VARCHAR(200) COMMENT '卖家名称', CHANGE `buyer_nick` `buyer_nick` VARCHAR(200) COMMENT '买家名称', CHANGE `total_amount` `total_amount` DECIMAL(18,2) COMMENT '订单总金额', CHANGE `item_amount` `item_amount` DECIMAL(18,2) COMMENT '商品总金额', CHANGE `discount_amount` `discount_amount` DECIMAL(18,2) COMMENT '订单折扣金额', CHANGE `freight` `freight` DECIMAL(18,2) COMMENT '快递费用', CHANGE `ar_amount` `ar_amount` DECIMAL(18,2) COMMENT '应收金额', CHANGE `got_amount` `got_amount` DECIMAL(18,2) COMMENT '已收金额', CHANGE `service_fee` `service_fee` DECIMAL(18,2) COMMENT 'COD服务费', CHANGE `logistics_code` `logistics_code` VARCHAR(50) COMMENT '物流公司编码', CHANGE `logistics_name` `logistics_name` VARCHAR(200) COMMENT '物流公司名称', CHANGE `sys_logistics_code` `sys_logistics_code` VARCHAR(50) COMMENT '系统物流公司编码', CHANGE `sys_logistics_name` `sys_logistics_name` VARCHAR(200) COMMENT '系统物流公司名称', CHANGE `basket_number` `basket_number` VARCHAR(50) COMMENT '筐号', CHANGE `express_code` `express_code` VARCHAR(50) COMMENT '面单号前置', CHANGE `logistics_area_code` `logistics_area_code` VARCHAR(50) COMMENT '快递区域编码, 大头笔信息', CHANGE `delivery_type` `delivery_type` VARCHAR(255) COMMENT '发货服务类型', CHANGE `weight_type` `weight_type` INTEGER(11) NOT NULL DEFAULT 0 COMMENT '重量类型:0常规、1轻货、2重货、3冷链', CHANGE `is_urgency` `is_urgency` ENUM('Y', 'N') DEFAULT 'N' COMMENT '是否紧急', CHANGE `invoice_flag` `invoice_flag` ENUM('Y', 'N') DEFAULT 'N' COMMENT '是否需要发票', CHANGE `status` `status` ENUM('pedding', 'created', 'cancel', 'error') DEFAULT 'created' COMMENT '订单状态', CHANGE `name` `name` TEXT COMMENT '收件人姓名', CHANGE `zip_code` `zip_code` VARCHAR(50) COMMENT '收件人邮编', CHANGE `tel` `tel` TEXT COMMENT '收件人电话', CHANGE `mobile` `mobile` TEXT COMMENT '收件人移动电话', CHANGE `email` `email` TEXT COMMENT '收件人邮箱', CHANGE `country_code` `country_code` VARCHAR(255) COMMENT '国家编码', CHANGE `province` `province` VARCHAR(255) COMMENT '省份', CHANGE `city` `city` VARCHAR(255) COMMENT '城市', CHANGE `area` `area` VARCHAR(255) COMMENT '区', CHANGE `town` `town` VARCHAR(255) COMMENT '镇', CHANGE `detail_address` `detail_address` TEXT COMMENT '详细地址', CHANGE `id_type` `id_type` VARCHAR(255) COMMENT '证件类型', CHANGE `id_number` `id_number` INTEGER(11) COMMENT '证件号码', CHANGE `oaid` `oaid` TEXT COMMENT 'OAID', CHANGE `sync_status` `sync_status` ENUM('padding', 'fin', 'error') DEFAULT 'padding' COMMENT '同步状态', CHANGE `store_id` `store_id` BIGINT(20) UNSIGNED COMMENT '货主ID', CHANGE `warehouse_id` `warehouse_id` BIGINT(20) UNSIGNED COMMENT '仓库ID', CHANGE `from_key` `from_key` INTEGER(11) COMMENT '来源键', CHANGE `items` `items` TEXT COMMENT '商品JSON字符串', CHANGE `items_count` `items_count` SMALLINT(5) UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品种类数', CHANGE `items_total` `items_total` INTEGER(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品总数', CHANGE `items_weight` `items_weight` DECIMAL(10,2) NOT NULL DEFAULT 0 COMMENT '总重量(kg)', CHANGE `items_hash` `items_hash` CHAR(32) NOT NULL DEFAULT '' COMMENT 'MD5哈希值(32位)', CHANGE `items_crc` `items_crc` INTEGER(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'CRC32校验码', CHANGE `wave_id` `wave_id` BIGINT(20) NOT NULL DEFAULT 0 COMMENT '波次ID,0表示未分配', CHANGE `wave_no` `wave_no` VARCHAR(50) NOT NULL DEFAULT '' COMMENT '波次号,空字符串表示未分配', CHANGE `wave_strategy_version` `wave_strategy_version` INTEGER(10) NOT NULL DEFAULT 0 COMMENT '波次策略版本号', CHANGE `wave_scan_result` `wave_scan_result` INTEGER(10) NOT NULL DEFAULT 0 COMMENT '波次扫描结果,0未扫描,1扫描符合,2扫描没有符合', CHANGE `post_status` `post_status` ENUM('padding', 'fin', 'timeout', 'error', 'none') DEFAULT 'none' COMMENT '分配快递号状态机', CHANGE `storage_status` `storage_status` ENUM('padding', 'fin', 'error', 'none') DEFAULT 'none' COMMENT '分配储位状态机', CHANGE `pick_status` `pick_status` ENUM('padding', 'fin', 'error', 'none') DEFAULT 'none' COMMENT '拣货状态机', CHANGE `pack_status` `pack_status` ENUM('none', 'padding', 'fin', 'error') DEFAULT 'none' COMMENT '打包状态机', CHANGE `sended_status` `sended_status` ENUM('none', 'padding', 'fin', 'error') DEFAULT 'none' COMMENT '发货状态机', CHANGE `inspection_status` `inspection_status` ENUM('none', 'padding', 'running', 'fin', 'error') DEFAULT 'none' COMMENT '检验状态机', CHANGE `recheck_status` `recheck_status` VARCHAR(20) DEFAULT 'none' COMMENT '复核状态', CHANGE `recheck_time` `recheck_time` DATETIME COMMENT '复核时间', CHANGE `step` `step` INTEGER(10) NOT NULL DEFAULT 0 COMMENT '订单步骤:0未审核,1已审核,2处理中,3驳回/异常,4配送中,5已完成,9已关闭', CHANGE `print_status` `print_status` ENUM('none', 'padding', 'fin', 'error') DEFAULT 'none' COMMENT '打印状态机', CHANGE `claim_status` `claim_status` ENUM('none', 'padding', 'fin', 'error') DEFAULT 'none' COMMENT '领取状态机', CHANGE `outbound_status` `outbound_status` ENUM('none', 'padding', 'fin', 'timeout', 'error') DEFAULT 'none' COMMENT '出库状态机', CHANGE `lock_status` `lock_status` ENUM('none', 'warehouse', 'store') DEFAULT 'none' COMMENT '锁定状态机', CHANGE `intercept_status` `intercept_status` ENUM('none', 'requesting', 'requested', 'intercepting', 'intercepted_in_transit', 'intercepted_at_warehouse', 'returning', 'returned', 'delivered_by_mistake', 'timeout', 'cancelled', 'failed', 'exception') DEFAULT 'none' COMMENT '拦截状态机' -2026-05-20 02:29:16,609 INFO 53968 [egg-sequelize](1ms) Executed (default): SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_NAME = 'wms_order_delivery_1000028' AND TABLE_SCHEMA = 'wms' -2026-05-20 02:29:16,611 INFO 53968 [egg-sequelize](1ms) Executed (default): SELECT CONSTRAINT_NAME as constraint_name,CONSTRAINT_NAME as constraintName,CONSTRAINT_SCHEMA as constraintSchema,CONSTRAINT_SCHEMA as constraintCatalog,TABLE_NAME as tableName,TABLE_SCHEMA as tableSchema,TABLE_SCHEMA as tableCatalog,COLUMN_NAME as columnName,REFERENCED_TABLE_SCHEMA as referencedTableSchema,REFERENCED_TABLE_SCHEMA as referencedTableCatalog,REFERENCED_TABLE_NAME as referencedTableName,REFERENCED_COLUMN_NAME as referencedColumnName FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE where TABLE_NAME = 'wms_order_delivery_1000028' AND CONSTRAINT_NAME!='PRIMARY' AND CONSTRAINT_SCHEMA='wms' AND REFERENCED_TABLE_NAME IS NOT NULL; -2026-05-20 02:29:16,612 INFO 53968 [egg-sequelize](2ms) Executed (default): SHOW FULL COLUMNS FROM `wms_order_delivery_1000028`; -2026-05-20 02:29:16,629 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `delivery_order_code` `delivery_order_code` VARCHAR(50) COMMENT '发货单号'; -2026-05-20 02:29:16,646 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `pre_delivery_order_code` `pre_delivery_order_code` VARCHAR(50) COMMENT '预发货单号'; -2026-05-20 02:29:16,668 INFO 53968 [egg-sequelize](22ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `pre_delivery_order_id` `pre_delivery_order_id` VARCHAR(50) COMMENT '预发货单ID'; -2026-05-20 02:29:16,691 INFO 53968 [egg-sequelize](23ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `order_type` `order_type` VARCHAR(50) COMMENT '订单类型'; -2026-05-20 02:29:16,707 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `warehouse_code` `warehouse_code` VARCHAR(50) COMMENT '仓库编码'; -2026-05-20 02:29:16,724 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `order_flag` `order_flag` LONGTEXT COMMENT '订单标记'; -2026-05-20 02:29:16,742 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `source_platform_code` `source_platform_code` VARCHAR(50) COMMENT '来源平台编码'; -2026-05-20 02:29:16,760 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `source_platform_name` `source_platform_name` VARCHAR(200) COMMENT '来源平台名称'; -2026-05-20 02:29:16,777 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `source_order_codes` `source_order_codes` TEXT COMMENT '来源订单号集合'; -2026-05-20 02:29:16,800 INFO 53968 [egg-sequelize](23ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `sys_platform_code` `sys_platform_code` VARCHAR(50) COMMENT '系统平台编码'; -2026-05-20 02:29:16,817 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `sys_platform_name` `sys_platform_name` VARCHAR(200) COMMENT '系统平台名称'; -2026-05-20 02:29:16,833 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `create_at` `create_at` DATETIME COMMENT '创建时间'; -2026-05-20 02:29:16,852 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `delete_at` `delete_at` DATETIME COMMENT '删除时间'; -2026-05-20 02:29:16,868 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `updated_at` `updated_at` DATETIME COMMENT '更新时间'; -2026-05-20 02:29:16,885 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `place_order_time` `place_order_time` DATETIME COMMENT '店铺创建订单时间'; -2026-05-20 02:29:16,901 INFO 53968 [egg-sequelize](15ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `pay_time` `pay_time` DATETIME COMMENT '支付时间'; -2026-05-20 02:29:16,917 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `pay_no` `pay_no` VARCHAR(50) COMMENT '支付单号'; -2026-05-20 02:29:16,940 INFO 53968 [egg-sequelize](23ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `service_code` `service_code` VARCHAR(50) COMMENT '集包服务编码'; -2026-05-20 02:29:16,957 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `operator_name` `operator_name` VARCHAR(50) COMMENT 'ERP审核人'; -2026-05-20 02:29:16,973 INFO 53968 [egg-sequelize](15ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `operate_time` `operate_time` DATETIME COMMENT 'ERP审核时间'; -2026-05-20 02:29:16,989 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `delivery_time` `delivery_time` DATETIME COMMENT '发货时间'; -2026-05-20 02:29:17,006 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `shop_nick` `shop_nick` VARCHAR(200) COMMENT '店铺名称'; -2026-05-20 02:29:17,021 INFO 53968 [egg-sequelize](15ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `seller_nick` `seller_nick` VARCHAR(200) COMMENT '卖家名称'; -2026-05-20 02:29:17,041 INFO 53968 [egg-sequelize](19ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `buyer_nick` `buyer_nick` VARCHAR(200) COMMENT '买家名称'; -2026-05-20 02:29:17,059 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `total_amount` `total_amount` DECIMAL(18,2) COMMENT '订单总金额'; -2026-05-20 02:29:17,075 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `item_amount` `item_amount` DECIMAL(18,2) COMMENT '商品总金额'; -2026-05-20 02:29:17,094 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `discount_amount` `discount_amount` DECIMAL(18,2) COMMENT '订单折扣金额'; -2026-05-20 02:29:17,111 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `freight` `freight` DECIMAL(18,2) COMMENT '快递费用'; -2026-05-20 02:29:17,129 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `ar_amount` `ar_amount` DECIMAL(18,2) COMMENT '应收金额'; -2026-05-20 02:29:17,151 INFO 53968 [egg-sequelize](22ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `got_amount` `got_amount` DECIMAL(18,2) COMMENT '已收金额'; -2026-05-20 02:29:17,169 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `service_fee` `service_fee` DECIMAL(18,2) COMMENT 'COD服务费'; -2026-05-20 02:29:17,186 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `logistics_code` `logistics_code` VARCHAR(50) COMMENT '物流公司编码'; -2026-05-20 02:29:17,202 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `logistics_name` `logistics_name` VARCHAR(200) COMMENT '物流公司名称'; -2026-05-20 02:29:17,220 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `sys_logistics_code` `sys_logistics_code` VARCHAR(50) COMMENT '系统物流公司编码'; -2026-05-20 02:29:17,235 INFO 53968 [egg-sequelize](15ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `sys_logistics_name` `sys_logistics_name` VARCHAR(200) COMMENT '系统物流公司名称'; -2026-05-20 02:29:17,252 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `express_code` `express_code` VARCHAR(50) COMMENT '面单号前置'; -2026-05-20 02:29:17,271 INFO 53968 [egg-sequelize](19ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `logistics_area_code` `logistics_area_code` VARCHAR(50) COMMENT '快递区域编码, 大头笔信息'; -2026-05-20 02:29:17,286 INFO 53968 [egg-sequelize](15ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `delivery_type` `delivery_type` VARCHAR(255) COMMENT '发货服务类型'; -2026-05-20 02:29:17,302 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `weight_type` `weight_type` INTEGER(11) NOT NULL DEFAULT 0 COMMENT '重量类型:0常规、1轻货、2重货、3冷链'; -2026-05-20 02:29:17,318 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `is_urgency` `is_urgency` ENUM('Y', 'N') DEFAULT 'N' COMMENT '是否紧急'; -2026-05-20 02:29:17,339 INFO 53968 [egg-sequelize](20ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `invoice_flag` `invoice_flag` ENUM('Y', 'N') DEFAULT 'N' COMMENT '是否需要发票'; -2026-05-20 02:29:17,359 INFO 53968 [egg-sequelize](20ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `status` `status` ENUM('pedding', 'created', 'cancel', 'error') DEFAULT 'created' COMMENT '订单状态'; -2026-05-20 02:29:17,378 INFO 53968 [egg-sequelize](19ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `name` `name` TEXT COMMENT '收件人姓名'; -2026-05-20 02:29:17,396 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `zip_code` `zip_code` VARCHAR(50) COMMENT '收件人邮编'; -2026-05-20 02:29:17,413 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `tel` `tel` TEXT COMMENT '收件人电话'; -2026-05-20 02:29:17,431 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `mobile` `mobile` TEXT COMMENT '收件人移动电话'; -2026-05-20 02:29:17,449 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `email` `email` TEXT COMMENT '收件人邮箱'; -2026-05-20 02:29:17,468 INFO 53968 [egg-sequelize](19ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `country_code` `country_code` VARCHAR(255) COMMENT '国家编码'; -2026-05-20 02:29:17,487 INFO 53968 [egg-sequelize](19ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `province` `province` VARCHAR(255) COMMENT '省份'; -2026-05-20 02:29:17,503 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `city` `city` VARCHAR(255) COMMENT '城市'; -2026-05-20 02:29:17,526 INFO 53968 [egg-sequelize](23ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `area` `area` VARCHAR(255) COMMENT '区'; -2026-05-20 02:29:17,555 INFO 53968 [egg-sequelize](28ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `town` `town` VARCHAR(255) COMMENT '镇'; -2026-05-20 02:29:17,579 INFO 53968 [egg-sequelize](23ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `detail_address` `detail_address` TEXT COMMENT '详细地址'; -2026-05-20 02:29:17,597 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `id_type` `id_type` VARCHAR(255) COMMENT '证件类型'; -2026-05-20 02:29:17,616 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `id_number` `id_number` INTEGER(11) COMMENT '证件号码'; -2026-05-20 02:29:17,635 INFO 53968 [egg-sequelize](19ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `oaid` `oaid` TEXT COMMENT 'OAID'; -2026-05-20 02:29:17,653 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `sync_status` `sync_status` ENUM('padding', 'fin', 'error') DEFAULT 'padding' COMMENT '同步状态'; -2026-05-20 02:29:17,677 INFO 53968 [egg-sequelize](24ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `store_id` `store_id` BIGINT(20) UNSIGNED COMMENT '货主ID'; -2026-05-20 02:29:17,698 INFO 53968 [egg-sequelize](20ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `warehouse_id` `warehouse_id` BIGINT(20) UNSIGNED COMMENT '仓库ID'; -2026-05-20 02:29:17,715 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `from_key` `from_key` INTEGER(11) COMMENT '来源键'; -2026-05-20 02:29:17,733 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `items` `items` TEXT COMMENT '商品JSON字符串'; -2026-05-20 02:29:17,750 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `items_count` `items_count` SMALLINT(5) UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品种类数'; -2026-05-20 02:29:17,768 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `items_total` `items_total` INTEGER(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品总数'; -2026-05-20 02:29:17,788 INFO 53968 [egg-sequelize](19ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `items_weight` `items_weight` DECIMAL(10,2) NOT NULL DEFAULT 0 COMMENT '总重量(kg)'; -2026-05-20 02:29:17,805 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `items_hash` `items_hash` CHAR(32) NOT NULL DEFAULT '' COMMENT 'MD5哈希值(32位)'; -2026-05-20 02:29:17,823 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `items_crc` `items_crc` INTEGER(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'CRC32校验码'; -2026-05-20 02:29:17,840 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `wave_id` `wave_id` BIGINT(20) NOT NULL DEFAULT 0 COMMENT '波次ID,0表示未分配'; -2026-05-20 02:29:17,858 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `post_status` `post_status` ENUM('padding', 'fin', 'timeout', 'error', 'none') DEFAULT 'none' COMMENT '分配快递号状态机'; -2026-05-20 02:29:17,875 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `storage_status` `storage_status` ENUM('padding', 'fin', 'error', 'none') DEFAULT 'none' COMMENT '分配储位状态机'; -2026-05-20 02:29:17,895 INFO 53968 [egg-sequelize](20ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `pick_status` `pick_status` ENUM('padding', 'fin', 'error', 'none') DEFAULT 'none' COMMENT '拣货状态机'; -2026-05-20 02:29:17,915 INFO 53968 [egg-sequelize](19ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `pack_status` `pack_status` ENUM('none', 'padding', 'fin', 'error') DEFAULT 'none' COMMENT '打包状态机'; -2026-05-20 02:29:17,934 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `inspection_status` `inspection_status` ENUM('none', 'padding', 'running', 'fin', 'error') DEFAULT 'none' COMMENT '检验状态机'; -2026-05-20 02:29:17,951 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `step` `step` INTEGER(10) NOT NULL DEFAULT 0 COMMENT '订单步骤:0未审核,1已审核,2处理中,3驳回/异常,4配送中,5已完成,9已关闭'; -2026-05-20 02:29:17,969 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `print_status` `print_status` ENUM('none', 'padding', 'fin', 'error') DEFAULT 'none' COMMENT '打印状态机'; -2026-05-20 02:29:17,984 INFO 53968 [egg-sequelize](15ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `claim_status` `claim_status` ENUM('none', 'padding', 'fin', 'error') DEFAULT 'none' COMMENT '领取状态机'; -2026-05-20 02:29:18,000 INFO 53968 [egg-sequelize](15ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `outbound_status` `outbound_status` ENUM('none', 'padding', 'fin', 'timeout', 'error') DEFAULT 'none' COMMENT '出库状态机'; -2026-05-20 02:29:18,019 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `lock_status` `lock_status` ENUM('none', 'warehouse', 'store') DEFAULT 'none' COMMENT '锁定状态机'; -2026-05-20 02:29:18,035 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `intercept_status` `intercept_status` ENUM('none', 'requesting', 'requested', 'intercepting', 'intercepted_in_transit', 'intercepted_at_warehouse', 'returning', 'returned', 'delivered_by_mistake', 'timeout', 'cancelled', 'failed', 'exception') DEFAULT 'none' COMMENT '拦截状态机'; -2026-05-20 02:29:18,051 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `sended_status` `sended_status` ENUM('none', 'padding', 'fin', 'error') DEFAULT 'none' COMMENT '发货状态机'; -2026-05-20 02:29:18,068 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `create_channel` `create_channel` VARCHAR(20) NOT NULL DEFAULT 'MANUAL' COMMENT '创建来源渠道'; -2026-05-20 02:29:18,086 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `basket_number` `basket_number` VARCHAR(50) COMMENT '筐号'; -2026-05-20 02:29:18,106 INFO 53968 [egg-sequelize](20ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `wave_no` `wave_no` VARCHAR(50) NOT NULL DEFAULT '' COMMENT '波次号,空字符串表示未分配'; -2026-05-20 02:29:18,123 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `wave_strategy_version` `wave_strategy_version` INTEGER(10) NOT NULL DEFAULT 0 COMMENT '波次策略版本号'; -2026-05-20 02:29:18,139 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `wave_scan_result` `wave_scan_result` INTEGER(10) NOT NULL DEFAULT 0 COMMENT '波次扫描结果,0未扫描,1扫描符合,2扫描没有符合'; -2026-05-20 02:29:18,156 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `recheck_status` `recheck_status` VARCHAR(20) DEFAULT 'none' COMMENT '复核状态'; -2026-05-20 02:29:18,173 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028` CHANGE `recheck_time` `recheck_time` DATETIME COMMENT '复核时间'; -2026-05-20 02:29:18,175 INFO 53968 [egg-sequelize](1ms) Executed (default): SHOW INDEX FROM `wms_order_delivery_1000028` -2026-05-20 02:29:18,176 INFO 53968 创建动态模型成功: wms_order_delivery_1000028 -2026-05-20 02:29:18,176 INFO 53968 创建订单商品动态模型成功: wms_order_items_1000028 -2026-05-20 02:29:18,185 INFO 53968 [egg-sequelize](1ms) Executed (default): SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_SCHEMA = 'wms'; -2026-05-20 02:29:18,187 INFO 53968 [egg-sequelize](2ms) Executed (default): SHOW INDEX FROM `wms_order_delivery_1000028_dispatch` -2026-05-20 02:29:18,187 INFO 53968 [egg-sequelize](2ms) Executed (default): SHOW FULL COLUMNS FROM `wms_order_delivery_1000028_dispatch`; -2026-05-20 02:29:18,190 INFO 53968 [egg-sequelize](2ms) Executed (default): SHOW FULL COLUMNS FROM `wms_order_delivery_1000028_dispatch`; -2026-05-20 02:29:18,191 INFO 53968 [egg-sequelize](1ms) Executed (default): SELECT MAX(CASE WHEN `create_channel` IS NULL THEN 1 ELSE 0 END) AS `create_channel`, MAX(CASE WHEN `weight_type` IS NULL THEN 1 ELSE 0 END) AS `weight_type`, MAX(CASE WHEN `items_count` IS NULL THEN 1 ELSE 0 END) AS `items_count`, MAX(CASE WHEN `items_total` IS NULL THEN 1 ELSE 0 END) AS `items_total`, MAX(CASE WHEN `items_weight` IS NULL THEN 1 ELSE 0 END) AS `items_weight`, MAX(CASE WHEN `items_hash` IS NULL THEN 1 ELSE 0 END) AS `items_hash`, MAX(CASE WHEN `items_crc` IS NULL THEN 1 ELSE 0 END) AS `items_crc`, MAX(CASE WHEN `wave_id` IS NULL THEN 1 ELSE 0 END) AS `wave_id`, MAX(CASE WHEN `wave_no` IS NULL THEN 1 ELSE 0 END) AS `wave_no`, MAX(CASE WHEN `wave_strategy_version` IS NULL THEN 1 ELSE 0 END) AS `wave_strategy_version`, MAX(CASE WHEN `wave_scan_result` IS NULL THEN 1 ELSE 0 END) AS `wave_scan_result`, MAX(CASE WHEN `step` IS NULL THEN 1 ELSE 0 END) AS `step`, MAX(CASE WHEN `dispatch_lane` IS NULL THEN 1 ELSE 0 END) AS `dispatch_lane` FROM `wms_order_delivery_1000028_dispatch` WHERE `create_channel` IS NULL OR `weight_type` IS NULL OR `items_count` IS NULL OR `items_total` IS NULL OR `items_weight` IS NULL OR `items_hash` IS NULL OR `items_crc` IS NULL OR `wave_id` IS NULL OR `wave_no` IS NULL OR `wave_strategy_version` IS NULL OR `wave_scan_result` IS NULL OR `step` IS NULL OR `dispatch_lane` IS NULL LIMIT 1 -2026-05-20 02:29:18,192 INFO 53968 [egg-sequelize](0ms) Executed (default): SELECT MAX(CASE WHEN `id` IS NOT NULL AND (`id` < 0 OR `id` > 18446744073709551615) THEN 1 ELSE 0 END) AS `id`, MAX(CASE WHEN `total_amount` IS NOT NULL AND (`total_amount` < -9999999999999999.99 OR `total_amount` > 9999999999999999.99) THEN 1 ELSE 0 END) AS `total_amount`, MAX(CASE WHEN `item_amount` IS NOT NULL AND (`item_amount` < -9999999999999999.99 OR `item_amount` > 9999999999999999.99) THEN 1 ELSE 0 END) AS `item_amount`, MAX(CASE WHEN `discount_amount` IS NOT NULL AND (`discount_amount` < -9999999999999999.99 OR `discount_amount` > 9999999999999999.99) THEN 1 ELSE 0 END) AS `discount_amount`, MAX(CASE WHEN `freight` IS NOT NULL AND (`freight` < -9999999999999999.99 OR `freight` > 9999999999999999.99) THEN 1 ELSE 0 END) AS `freight`, MAX(CASE WHEN `ar_amount` IS NOT NULL AND (`ar_amount` < -9999999999999999.99 OR `ar_amount` > 9999999999999999.99) THEN 1 ELSE 0 END) AS `ar_amount`, MAX(CASE WHEN `got_amount` IS NOT NULL AND (`got_amount` < -9999999999999999.99 OR `got_amount` > 9999999999999999.99) THEN 1 ELSE 0 END) AS `got_amount`, MAX(CASE WHEN `service_fee` IS NOT NULL AND (`service_fee` < -9999999999999999.99 OR `service_fee` > 9999999999999999.99) THEN 1 ELSE 0 END) AS `service_fee`, MAX(CASE WHEN `weight_type` IS NOT NULL AND (`weight_type` < -2147483648 OR `weight_type` > 2147483647) THEN 1 ELSE 0 END) AS `weight_type`, MAX(CASE WHEN `id_number` IS NOT NULL AND (`id_number` < -2147483648 OR `id_number` > 2147483647) THEN 1 ELSE 0 END) AS `id_number`, MAX(CASE WHEN `store_id` IS NOT NULL AND (`store_id` < 0 OR `store_id` > 18446744073709551615) THEN 1 ELSE 0 END) AS `store_id`, MAX(CASE WHEN `warehouse_id` IS NOT NULL AND (`warehouse_id` < 0 OR `warehouse_id` > 18446744073709551615) THEN 1 ELSE 0 END) AS `warehouse_id`, MAX(CASE WHEN `from_key` IS NOT NULL AND (`from_key` < -2147483648 OR `from_key` > 2147483647) THEN 1 ELSE 0 END) AS `from_key`, MAX(CASE WHEN `items_count` IS NOT NULL AND (`items_count` < 0 OR `items_count` > 65535) THEN 1 ELSE 0 END) AS `items_count`, MAX(CASE WHEN `items_total` IS NOT NULL AND (`items_total` < 0 OR `items_total` > 4294967295) THEN 1 ELSE 0 END) AS `items_total`, MAX(CASE WHEN `items_weight` IS NOT NULL AND (`items_weight` < -99999999.99 OR `items_weight` > 99999999.99) THEN 1 ELSE 0 END) AS `items_weight`, MAX(CASE WHEN `items_crc` IS NOT NULL AND (`items_crc` < 0 OR `items_crc` > 4294967295) THEN 1 ELSE 0 END) AS `items_crc`, MAX(CASE WHEN `wave_id` IS NOT NULL AND (`wave_id` < -9223372036854775808 OR `wave_id` > 9223372036854775807) THEN 1 ELSE 0 END) AS `wave_id`, MAX(CASE WHEN `wave_strategy_version` IS NOT NULL AND (`wave_strategy_version` < -2147483648 OR `wave_strategy_version` > 2147483647) THEN 1 ELSE 0 END) AS `wave_strategy_version`, MAX(CASE WHEN `wave_scan_result` IS NOT NULL AND (`wave_scan_result` < -2147483648 OR `wave_scan_result` > 2147483647) THEN 1 ELSE 0 END) AS `wave_scan_result`, MAX(CASE WHEN `step` IS NOT NULL AND (`step` < -2147483648 OR `step` > 2147483647) THEN 1 ELSE 0 END) AS `step` FROM `wms_order_delivery_1000028_dispatch` WHERE (`id` IS NOT NULL AND (`id` < 0 OR `id` > 18446744073709551615)) OR (`total_amount` IS NOT NULL AND (`total_amount` < -9999999999999999.99 OR `total_amount` > 9999999999999999.99)) OR (`item_amount` IS NOT NULL AND (`item_amount` < -9999999999999999.99 OR `item_amount` > 9999999999999999.99)) OR (`discount_amount` IS NOT NULL AND (`discount_amount` < -9999999999999999.99 OR `discount_amount` > 9999999999999999.99)) OR (`freight` IS NOT NULL AND (`freight` < -9999999999999999.99 OR `freight` > 9999999999999999.99)) OR (`ar_amount` IS NOT NULL AND (`ar_amount` < -9999999999999999.99 OR `ar_amount` > 9999999999999999.99)) OR (`got_amount` IS NOT NULL AND (`got_amount` < -9999999999999999.99 OR `got_amount` > 9999999999999999.99)) OR (`service_fee` IS NOT NULL AND (`service_fee` < -9999999999999999.99 OR `service_fee` > 9999999999999999.99)) OR (`weight_type` IS NOT NULL AND (`weight_type` < -2147483648 OR `weight_type` > 2147483647)) OR (`id_number` IS NOT NULL AND (`id_number` < -2147483648 OR `id_number` > 2147483647)) OR (`store_id` IS NOT NULL AND (`store_id` < 0 OR `store_id` > 18446744073709551615)) OR (`warehouse_id` IS NOT NULL AND (`warehouse_id` < 0 OR `warehouse_id` > 18446744073709551615)) OR (`from_key` IS NOT NULL AND (`from_key` < -2147483648 OR `from_key` > 2147483647)) OR (`items_count` IS NOT NULL AND (`items_count` < 0 OR `items_count` > 65535)) OR (`items_total` IS NOT NULL AND (`items_total` < 0 OR `items_total` > 4294967295)) OR (`items_weight` IS NOT NULL AND (`items_weight` < -99999999.99 OR `items_weight` > 99999999.99)) OR (`items_crc` IS NOT NULL AND (`items_crc` < 0 OR `items_crc` > 4294967295)) OR (`wave_id` IS NOT NULL AND (`wave_id` < -9223372036854775808 OR `wave_id` > 9223372036854775807)) OR (`wave_strategy_version` IS NOT NULL AND (`wave_strategy_version` < -2147483648 OR `wave_strategy_version` > 2147483647)) OR (`wave_scan_result` IS NOT NULL AND (`wave_scan_result` < -2147483648 OR `wave_scan_result` > 2147483647)) OR (`step` IS NOT NULL AND (`step` < -2147483648 OR `step` > 2147483647)) LIMIT 1 -2026-05-20 02:29:18,193 INFO 53968 [egg-sequelize](1ms) Executed (default): SHOW FULL COLUMNS FROM `wms_order_delivery_1000028_dispatch`; -2026-05-20 02:29:18,213 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `id` `id` BIGINT(20) UNSIGNED AUTO_INCREMENT, CHANGE `delivery_order_code` `delivery_order_code` VARCHAR(50) COMMENT '发货单号', CHANGE `pre_delivery_order_code` `pre_delivery_order_code` VARCHAR(50) COMMENT '预发货单号', CHANGE `pre_delivery_order_id` `pre_delivery_order_id` VARCHAR(50) COMMENT '预发货单ID', CHANGE `order_type` `order_type` VARCHAR(50) COMMENT '订单类型', CHANGE `warehouse_code` `warehouse_code` VARCHAR(50) COMMENT '仓库编码', CHANGE `order_flag` `order_flag` LONGTEXT COMMENT '订单标记', CHANGE `source_platform_code` `source_platform_code` VARCHAR(50) COMMENT '来源平台编码', CHANGE `source_platform_name` `source_platform_name` VARCHAR(200) COMMENT '来源平台名称', CHANGE `create_channel` `create_channel` VARCHAR(20) NOT NULL DEFAULT 'MANUAL' COMMENT '创建来源渠道', CHANGE `source_order_codes` `source_order_codes` TEXT COMMENT '来源订单号集合', CHANGE `sys_platform_code` `sys_platform_code` VARCHAR(50) COMMENT '系统平台编码', CHANGE `sys_platform_name` `sys_platform_name` VARCHAR(200) COMMENT '系统平台名称', CHANGE `create_at` `create_at` DATETIME COMMENT '创建时间', CHANGE `delete_at` `delete_at` DATETIME COMMENT '删除时间', CHANGE `updated_at` `updated_at` DATETIME COMMENT '更新时间', CHANGE `place_order_time` `place_order_time` DATETIME COMMENT '店铺创建订单时间', CHANGE `pay_time` `pay_time` DATETIME COMMENT '支付时间', CHANGE `pay_no` `pay_no` VARCHAR(50) COMMENT '支付单号', CHANGE `service_code` `service_code` VARCHAR(50) COMMENT '集包服务编码', CHANGE `operator_name` `operator_name` VARCHAR(50) COMMENT 'ERP审核人', CHANGE `operate_time` `operate_time` DATETIME COMMENT 'ERP审核时间', CHANGE `delivery_time` `delivery_time` DATETIME COMMENT '发货时间', CHANGE `shop_nick` `shop_nick` VARCHAR(200) COMMENT '店铺名称', CHANGE `seller_nick` `seller_nick` VARCHAR(200) COMMENT '卖家名称', CHANGE `buyer_nick` `buyer_nick` VARCHAR(200) COMMENT '买家名称', CHANGE `total_amount` `total_amount` DECIMAL(18,2) COMMENT '订单总金额', CHANGE `item_amount` `item_amount` DECIMAL(18,2) COMMENT '商品总金额', CHANGE `discount_amount` `discount_amount` DECIMAL(18,2) COMMENT '订单折扣金额', CHANGE `freight` `freight` DECIMAL(18,2) COMMENT '快递费用', CHANGE `ar_amount` `ar_amount` DECIMAL(18,2) COMMENT '应收金额', CHANGE `got_amount` `got_amount` DECIMAL(18,2) COMMENT '已收金额', CHANGE `service_fee` `service_fee` DECIMAL(18,2) COMMENT 'COD服务费', CHANGE `logistics_code` `logistics_code` VARCHAR(50) COMMENT '物流公司编码', CHANGE `logistics_name` `logistics_name` VARCHAR(200) COMMENT '物流公司名称', CHANGE `sys_logistics_code` `sys_logistics_code` VARCHAR(50) COMMENT '系统物流公司编码', CHANGE `sys_logistics_name` `sys_logistics_name` VARCHAR(200) COMMENT '系统物流公司名称', CHANGE `basket_number` `basket_number` VARCHAR(50) COMMENT '筐号', CHANGE `express_code` `express_code` VARCHAR(50) COMMENT '面单号前置', CHANGE `logistics_area_code` `logistics_area_code` VARCHAR(50) COMMENT '快递区域编码, 大头笔信息', CHANGE `delivery_type` `delivery_type` VARCHAR(255) COMMENT '发货服务类型', CHANGE `weight_type` `weight_type` INTEGER(11) NOT NULL DEFAULT 0 COMMENT '重量类型:0常规、1轻货、2重货、3冷链', CHANGE `is_urgency` `is_urgency` ENUM('Y', 'N') DEFAULT 'N' COMMENT '是否紧急', CHANGE `invoice_flag` `invoice_flag` ENUM('Y', 'N') DEFAULT 'N' COMMENT '是否需要发票', CHANGE `status` `status` ENUM('pedding', 'created', 'cancel', 'error') DEFAULT 'created' COMMENT '订单状态', CHANGE `name` `name` TEXT COMMENT '收件人姓名', CHANGE `zip_code` `zip_code` VARCHAR(50) COMMENT '收件人邮编', CHANGE `tel` `tel` TEXT COMMENT '收件人电话', CHANGE `mobile` `mobile` TEXT COMMENT '收件人移动电话', CHANGE `email` `email` TEXT COMMENT '收件人邮箱', CHANGE `country_code` `country_code` VARCHAR(255) COMMENT '国家编码', CHANGE `province` `province` VARCHAR(255) COMMENT '省份', CHANGE `city` `city` VARCHAR(255) COMMENT '城市', CHANGE `area` `area` VARCHAR(255) COMMENT '区', CHANGE `town` `town` VARCHAR(255) COMMENT '镇', CHANGE `detail_address` `detail_address` TEXT COMMENT '详细地址', CHANGE `id_type` `id_type` VARCHAR(255) COMMENT '证件类型', CHANGE `id_number` `id_number` INTEGER(11) COMMENT '证件号码', CHANGE `oaid` `oaid` TEXT COMMENT 'OAID', CHANGE `sync_status` `sync_status` ENUM('padding', 'fin', 'error') DEFAULT 'padding' COMMENT '同步状态', CHANGE `store_id` `store_id` BIGINT(20) UNSIGNED COMMENT '货主ID', CHANGE `warehouse_id` `warehouse_id` BIGINT(20) UNSIGNED COMMENT '仓库ID', CHANGE `from_key` `from_key` INTEGER(11) COMMENT '来源键', CHANGE `items` `items` TEXT COMMENT '商品JSON字符串', CHANGE `items_count` `items_count` SMALLINT(5) UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品种类数', CHANGE `items_total` `items_total` INTEGER(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品总数', CHANGE `items_weight` `items_weight` DECIMAL(10,2) NOT NULL DEFAULT 0 COMMENT '总重量(kg)', CHANGE `items_hash` `items_hash` CHAR(32) NOT NULL DEFAULT '' COMMENT 'MD5哈希值(32位)', CHANGE `items_crc` `items_crc` INTEGER(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'CRC32校验码', CHANGE `wave_id` `wave_id` BIGINT(20) NOT NULL DEFAULT 0 COMMENT '波次ID,0表示未分配', CHANGE `wave_no` `wave_no` VARCHAR(50) NOT NULL DEFAULT '' COMMENT '波次号,空字符串表示未分配', CHANGE `wave_strategy_version` `wave_strategy_version` INTEGER(10) NOT NULL DEFAULT 0 COMMENT '波次策略版本号', CHANGE `wave_scan_result` `wave_scan_result` INTEGER(10) NOT NULL DEFAULT 0 COMMENT '波次扫描结果,0未扫描,1扫描符合,2扫描没有符合', CHANGE `post_status` `post_status` ENUM('padding', 'fin', 'timeout', 'error', 'none') DEFAULT 'none' COMMENT '分配快递号状态机', CHANGE `storage_status` `storage_status` ENUM('padding', 'fin', 'error', 'none') DEFAULT 'none' COMMENT '分配储位状态机', CHANGE `pick_status` `pick_status` ENUM('padding', 'fin', 'error', 'none') DEFAULT 'none' COMMENT '拣货状态机', CHANGE `pack_status` `pack_status` ENUM('none', 'padding', 'fin', 'error') DEFAULT 'none' COMMENT '打包状态机', CHANGE `sended_status` `sended_status` ENUM('none', 'padding', 'fin', 'error') DEFAULT 'none' COMMENT '发货状态机', CHANGE `inspection_status` `inspection_status` ENUM('none', 'padding', 'running', 'fin', 'error') DEFAULT 'none' COMMENT '检验状态机', CHANGE `recheck_status` `recheck_status` VARCHAR(20) DEFAULT 'none' COMMENT '复核状态', CHANGE `recheck_time` `recheck_time` DATETIME COMMENT '复核时间', CHANGE `step` `step` INTEGER(10) NOT NULL DEFAULT 0 COMMENT '订单步骤:0未审核,1已审核,2处理中,3驳回/异常,4配送中,5已完成,9已关闭', CHANGE `print_status` `print_status` ENUM('none', 'padding', 'fin', 'error') DEFAULT 'none' COMMENT '打印状态机', CHANGE `claim_status` `claim_status` ENUM('none', 'padding', 'fin', 'error') DEFAULT 'none' COMMENT '领取状态机', CHANGE `outbound_status` `outbound_status` ENUM('none', 'padding', 'fin', 'timeout', 'error') DEFAULT 'none' COMMENT '出库状态机', CHANGE `lock_status` `lock_status` ENUM('none', 'warehouse', 'store') DEFAULT 'none' COMMENT '锁定状态机', CHANGE `intercept_status` `intercept_status` ENUM('none', 'requesting', 'requested', 'intercepting', 'intercepted_in_transit', 'intercepted_at_warehouse', 'returning', 'returned', 'delivered_by_mistake', 'timeout', 'cancelled', 'failed', 'exception') DEFAULT 'none' COMMENT '拦截状态机', CHANGE `dispatch_lane` `dispatch_lane` ENUM('m4', 'm5') NOT NULL DEFAULT 'm4' COMMENT '配送工作台子域(M4正常/M5异常)' -2026-05-20 02:29:18,216 INFO 53968 [egg-sequelize](3ms) Executed (default): SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_NAME = 'wms_order_delivery_1000028_dispatch' AND TABLE_SCHEMA = 'wms' -2026-05-20 02:29:18,218 INFO 53968 [egg-sequelize](1ms) Executed (default): SELECT CONSTRAINT_NAME as constraint_name,CONSTRAINT_NAME as constraintName,CONSTRAINT_SCHEMA as constraintSchema,CONSTRAINT_SCHEMA as constraintCatalog,TABLE_NAME as tableName,TABLE_SCHEMA as tableSchema,TABLE_SCHEMA as tableCatalog,COLUMN_NAME as columnName,REFERENCED_TABLE_SCHEMA as referencedTableSchema,REFERENCED_TABLE_SCHEMA as referencedTableCatalog,REFERENCED_TABLE_NAME as referencedTableName,REFERENCED_COLUMN_NAME as referencedColumnName FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE where TABLE_NAME = 'wms_order_delivery_1000028_dispatch' AND CONSTRAINT_NAME!='PRIMARY' AND CONSTRAINT_SCHEMA='wms' AND REFERENCED_TABLE_NAME IS NOT NULL; -2026-05-20 02:29:18,219 INFO 53968 [egg-sequelize](3ms) Executed (default): SHOW FULL COLUMNS FROM `wms_order_delivery_1000028_dispatch`; -2026-05-20 02:29:18,240 INFO 53968 [egg-sequelize](21ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `delivery_order_code` `delivery_order_code` VARCHAR(50) COMMENT '发货单号'; -2026-05-20 02:29:18,258 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `pre_delivery_order_code` `pre_delivery_order_code` VARCHAR(50) COMMENT '预发货单号'; -2026-05-20 02:29:18,277 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `pre_delivery_order_id` `pre_delivery_order_id` VARCHAR(50) COMMENT '预发货单ID'; -2026-05-20 02:29:18,293 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `order_type` `order_type` VARCHAR(50) COMMENT '订单类型'; -2026-05-20 02:29:18,311 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `warehouse_code` `warehouse_code` VARCHAR(50) COMMENT '仓库编码'; -2026-05-20 02:29:18,328 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `order_flag` `order_flag` LONGTEXT COMMENT '订单标记'; -2026-05-20 02:29:18,350 INFO 53968 [egg-sequelize](22ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `source_platform_code` `source_platform_code` VARCHAR(50) COMMENT '来源平台编码'; -2026-05-20 02:29:18,368 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `source_platform_name` `source_platform_name` VARCHAR(200) COMMENT '来源平台名称'; -2026-05-20 02:29:18,385 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `source_order_codes` `source_order_codes` TEXT COMMENT '来源订单号集合'; -2026-05-20 02:29:18,403 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `sys_platform_code` `sys_platform_code` VARCHAR(50) COMMENT '系统平台编码'; -2026-05-20 02:29:18,424 INFO 53968 [egg-sequelize](20ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `sys_platform_name` `sys_platform_name` VARCHAR(200) COMMENT '系统平台名称'; -2026-05-20 02:29:18,446 INFO 53968 [egg-sequelize](22ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `create_at` `create_at` DATETIME COMMENT '创建时间'; -2026-05-20 02:29:18,465 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `delete_at` `delete_at` DATETIME COMMENT '删除时间'; -2026-05-20 02:29:18,481 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `updated_at` `updated_at` DATETIME COMMENT '更新时间'; -2026-05-20 02:29:18,500 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `place_order_time` `place_order_time` DATETIME COMMENT '店铺创建订单时间'; -2026-05-20 02:29:18,516 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `pay_time` `pay_time` DATETIME COMMENT '支付时间'; -2026-05-20 02:29:18,539 INFO 53968 [egg-sequelize](23ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `pay_no` `pay_no` VARCHAR(50) COMMENT '支付单号'; -2026-05-20 02:29:18,565 INFO 53968 [egg-sequelize](26ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `service_code` `service_code` VARCHAR(50) COMMENT '集包服务编码'; -2026-05-20 02:29:18,587 INFO 53968 [egg-sequelize](21ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `operator_name` `operator_name` VARCHAR(50) COMMENT 'ERP审核人'; -2026-05-20 02:29:18,603 INFO 53968 [egg-sequelize](15ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `operate_time` `operate_time` DATETIME COMMENT 'ERP审核时间'; -2026-05-20 02:29:18,619 INFO 53968 [egg-sequelize](15ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `delivery_time` `delivery_time` DATETIME COMMENT '发货时间'; -2026-05-20 02:29:18,635 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `shop_nick` `shop_nick` VARCHAR(200) COMMENT '店铺名称'; -2026-05-20 02:29:18,651 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `seller_nick` `seller_nick` VARCHAR(200) COMMENT '卖家名称'; -2026-05-20 02:29:18,668 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `buyer_nick` `buyer_nick` VARCHAR(200) COMMENT '买家名称'; -2026-05-20 02:29:18,685 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `total_amount` `total_amount` DECIMAL(18,2) COMMENT '订单总金额'; -2026-05-20 02:29:18,702 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `item_amount` `item_amount` DECIMAL(18,2) COMMENT '商品总金额'; -2026-05-20 02:29:18,718 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `discount_amount` `discount_amount` DECIMAL(18,2) COMMENT '订单折扣金额'; -2026-05-20 02:29:18,735 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `freight` `freight` DECIMAL(18,2) COMMENT '快递费用'; -2026-05-20 02:29:18,756 INFO 53968 [egg-sequelize](21ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `ar_amount` `ar_amount` DECIMAL(18,2) COMMENT '应收金额'; -2026-05-20 02:29:18,774 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `got_amount` `got_amount` DECIMAL(18,2) COMMENT '已收金额'; -2026-05-20 02:29:18,792 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `service_fee` `service_fee` DECIMAL(18,2) COMMENT 'COD服务费'; -2026-05-20 02:29:18,808 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `logistics_code` `logistics_code` VARCHAR(50) COMMENT '物流公司编码'; -2026-05-20 02:29:18,825 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `logistics_name` `logistics_name` VARCHAR(200) COMMENT '物流公司名称'; -2026-05-20 02:29:18,841 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `sys_logistics_code` `sys_logistics_code` VARCHAR(50) COMMENT '系统物流公司编码'; -2026-05-20 02:29:18,859 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `sys_logistics_name` `sys_logistics_name` VARCHAR(200) COMMENT '系统物流公司名称'; -2026-05-20 02:29:18,884 INFO 53968 [egg-sequelize](25ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `express_code` `express_code` VARCHAR(50) COMMENT '面单号前置'; -2026-05-20 02:29:18,900 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `logistics_area_code` `logistics_area_code` VARCHAR(50) COMMENT '快递区域编码, 大头笔信息'; -2026-05-20 02:29:18,917 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `delivery_type` `delivery_type` VARCHAR(255) COMMENT '发货服务类型'; -2026-05-20 02:29:18,934 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `weight_type` `weight_type` INTEGER(11) NOT NULL DEFAULT 0 COMMENT '重量类型:0常规、1轻货、2重货、3冷链'; -2026-05-20 02:29:18,951 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `is_urgency` `is_urgency` ENUM('Y', 'N') DEFAULT 'N' COMMENT '是否紧急'; -2026-05-20 02:29:18,979 INFO 53968 [egg-sequelize](27ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `invoice_flag` `invoice_flag` ENUM('Y', 'N') DEFAULT 'N' COMMENT '是否需要发票'; -2026-05-20 02:29:18,999 INFO 53968 [egg-sequelize](20ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `status` `status` ENUM('pedding', 'created', 'cancel', 'error') DEFAULT 'created' COMMENT '订单状态'; -2026-05-20 02:29:19,017 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `name` `name` TEXT COMMENT '收件人姓名'; -2026-05-20 02:29:19,035 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `zip_code` `zip_code` VARCHAR(50) COMMENT '收件人邮编'; -2026-05-20 02:29:19,052 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `tel` `tel` TEXT COMMENT '收件人电话'; -2026-05-20 02:29:19,070 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `mobile` `mobile` TEXT COMMENT '收件人移动电话'; -2026-05-20 02:29:19,089 INFO 53968 [egg-sequelize](19ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `email` `email` TEXT COMMENT '收件人邮箱'; -2026-05-20 02:29:19,107 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `country_code` `country_code` VARCHAR(255) COMMENT '国家编码'; -2026-05-20 02:29:19,125 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `province` `province` VARCHAR(255) COMMENT '省份'; -2026-05-20 02:29:19,143 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `city` `city` VARCHAR(255) COMMENT '城市'; -2026-05-20 02:29:19,163 INFO 53968 [egg-sequelize](19ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `area` `area` VARCHAR(255) COMMENT '区'; -2026-05-20 02:29:19,182 INFO 53968 [egg-sequelize](19ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `town` `town` VARCHAR(255) COMMENT '镇'; -2026-05-20 02:29:19,202 INFO 53968 [egg-sequelize](20ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `detail_address` `detail_address` TEXT COMMENT '详细地址'; -2026-05-20 02:29:19,218 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `id_type` `id_type` VARCHAR(255) COMMENT '证件类型'; -2026-05-20 02:29:19,235 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `id_number` `id_number` INTEGER(11) COMMENT '证件号码'; -2026-05-20 02:29:19,252 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `oaid` `oaid` TEXT COMMENT 'OAID'; -2026-05-20 02:29:19,269 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `sync_status` `sync_status` ENUM('padding', 'fin', 'error') DEFAULT 'padding' COMMENT '同步状态'; -2026-05-20 02:29:19,285 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `store_id` `store_id` BIGINT(20) UNSIGNED COMMENT '货主ID'; -2026-05-20 02:29:19,307 INFO 53968 [egg-sequelize](20ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `warehouse_id` `warehouse_id` BIGINT(20) UNSIGNED COMMENT '仓库ID'; -2026-05-20 02:29:19,324 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `from_key` `from_key` INTEGER(11) COMMENT '来源键'; -2026-05-20 02:29:19,342 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `items` `items` TEXT COMMENT '商品JSON字符串'; -2026-05-20 02:29:19,362 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `items_count` `items_count` SMALLINT(5) UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品种类数'; -2026-05-20 02:29:19,381 INFO 53968 [egg-sequelize](19ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `items_total` `items_total` INTEGER(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品总数'; -2026-05-20 02:29:19,402 INFO 53968 [egg-sequelize](21ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `items_weight` `items_weight` DECIMAL(10,2) NOT NULL DEFAULT 0 COMMENT '总重量(kg)'; -2026-05-20 02:29:19,421 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `items_hash` `items_hash` CHAR(32) NOT NULL DEFAULT '' COMMENT 'MD5哈希值(32位)'; -2026-05-20 02:29:19,446 INFO 53968 [egg-sequelize](25ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `items_crc` `items_crc` INTEGER(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'CRC32校验码'; -2026-05-20 02:29:19,468 INFO 53968 [egg-sequelize](21ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `wave_id` `wave_id` BIGINT(20) NOT NULL DEFAULT 0 COMMENT '波次ID,0表示未分配'; -2026-05-20 02:29:19,484 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `post_status` `post_status` ENUM('padding', 'fin', 'timeout', 'error', 'none') DEFAULT 'none' COMMENT '分配快递号状态机'; -2026-05-20 02:29:19,503 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `storage_status` `storage_status` ENUM('padding', 'fin', 'error', 'none') DEFAULT 'none' COMMENT '分配储位状态机'; -2026-05-20 02:29:19,522 INFO 53968 [egg-sequelize](19ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `pick_status` `pick_status` ENUM('padding', 'fin', 'error', 'none') DEFAULT 'none' COMMENT '拣货状态机'; -2026-05-20 02:29:19,548 INFO 53968 [egg-sequelize](25ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `pack_status` `pack_status` ENUM('none', 'padding', 'fin', 'error') DEFAULT 'none' COMMENT '打包状态机'; -2026-05-20 02:29:19,572 INFO 53968 [egg-sequelize](24ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `inspection_status` `inspection_status` ENUM('none', 'padding', 'running', 'fin', 'error') DEFAULT 'none' COMMENT '检验状态机'; -2026-05-20 02:29:19,594 INFO 53968 [egg-sequelize](21ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `step` `step` INTEGER(10) NOT NULL DEFAULT 0 COMMENT '订单步骤:0未审核,1已审核,2处理中,3驳回/异常,4配送中,5已完成,9已关闭'; -2026-05-20 02:29:19,617 INFO 53968 [egg-sequelize](22ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `print_status` `print_status` ENUM('none', 'padding', 'fin', 'error') DEFAULT 'none' COMMENT '打印状态机'; -2026-05-20 02:29:19,633 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `claim_status` `claim_status` ENUM('none', 'padding', 'fin', 'error') DEFAULT 'none' COMMENT '领取状态机'; -2026-05-20 02:29:19,654 INFO 53968 [egg-sequelize](20ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `outbound_status` `outbound_status` ENUM('none', 'padding', 'fin', 'timeout', 'error') DEFAULT 'none' COMMENT '出库状态机'; -2026-05-20 02:29:19,670 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `lock_status` `lock_status` ENUM('none', 'warehouse', 'store') DEFAULT 'none' COMMENT '锁定状态机'; -2026-05-20 02:29:19,688 INFO 53968 [egg-sequelize](18ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `intercept_status` `intercept_status` ENUM('none', 'requesting', 'requested', 'intercepting', 'intercepted_in_transit', 'intercepted_at_warehouse', 'returning', 'returned', 'delivered_by_mistake', 'timeout', 'cancelled', 'failed', 'exception') DEFAULT 'none' COMMENT '拦截状态机'; -2026-05-20 02:29:19,704 INFO 53968 [egg-sequelize](16ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `dispatch_lane` `dispatch_lane` ENUM('m4', 'm5') NOT NULL DEFAULT 'm4' COMMENT '配送工作台子域(M4正常/M5异常)'; -2026-05-20 02:29:19,722 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `sended_status` `sended_status` ENUM('none', 'padding', 'fin', 'error') DEFAULT 'none' COMMENT '发货状态机'; -2026-05-20 02:29:19,745 INFO 53968 [egg-sequelize](22ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `create_channel` `create_channel` VARCHAR(20) NOT NULL DEFAULT 'MANUAL' COMMENT '创建来源渠道'; -2026-05-20 02:29:19,765 INFO 53968 [egg-sequelize](19ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `basket_number` `basket_number` VARCHAR(50) COMMENT '筐号'; -2026-05-20 02:29:19,782 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `wave_no` `wave_no` VARCHAR(50) NOT NULL DEFAULT '' COMMENT '波次号,空字符串表示未分配'; -2026-05-20 02:29:19,799 INFO 53968 [egg-sequelize](17ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `wave_strategy_version` `wave_strategy_version` INTEGER(10) NOT NULL DEFAULT 0 COMMENT '波次策略版本号'; -2026-05-20 02:29:19,819 INFO 53968 [egg-sequelize](20ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `wave_scan_result` `wave_scan_result` INTEGER(10) NOT NULL DEFAULT 0 COMMENT '波次扫描结果,0未扫描,1扫描符合,2扫描没有符合'; -2026-05-20 02:29:19,840 INFO 53968 [egg-sequelize](21ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `recheck_status` `recheck_status` VARCHAR(20) DEFAULT 'none' COMMENT '复核状态'; -2026-05-20 02:29:19,864 INFO 53968 [egg-sequelize](22ms) Executed (default): ALTER TABLE `wms_order_delivery_1000028_dispatch` CHANGE `recheck_time` `recheck_time` DATETIME COMMENT '复核时间'; -2026-05-20 02:29:19,873 INFO 53968 [egg-sequelize](9ms) Executed (default): SHOW INDEX FROM `wms_order_delivery_1000028_dispatch` -2026-05-20 02:29:19,877 INFO 53968 创建动态模型成功: wms_order_delivery_1000028_dispatch -2026-05-20 02:29:19,879 INFO 53968 创建订单商品动态模型成功: wms_order_items_1000028_dispatch -2026-05-20 02:29:19,884 INFO 53968 [egg-sequelize](4ms) Executed (7c72e31e-15ee-45dc-a822-626dfe09a9fd): SELECT `id`, `delivery_order_code`, `pre_delivery_order_code`, `pre_delivery_order_id`, `order_type`, `warehouse_code`, `order_flag`, `source_platform_code`, `source_platform_name`, `create_channel`, `source_order_codes`, `sys_platform_code`, `sys_platform_name`, `create_at`, `delete_at`, `updated_at`, `place_order_time`, `pay_time`, `pay_no`, `service_code`, `operator_name`, `operate_time`, `delivery_time`, `shop_nick`, `seller_nick`, `buyer_nick`, `total_amount`, `item_amount`, `discount_amount`, `freight`, `ar_amount`, `got_amount`, `service_fee`, `logistics_code`, `logistics_name`, `sys_logistics_code`, `sys_logistics_name`, `basket_number`, `express_code`, `logistics_area_code`, `delivery_type`, `weight_type`, `is_urgency`, `invoice_flag`, `status`, `name`, `zip_code`, `tel`, `mobile`, `email`, `country_code`, `province`, `city`, `area`, `town`, `detail_address`, `id_type`, `id_number`, `oaid`, `sync_status`, `store_id`, `warehouse_id`, `from_key`, `items`, `items_count`, `items_total`, `items_weight`, `items_hash`, `items_crc`, `wave_id`, `wave_no`, `wave_strategy_version`, `wave_scan_result`, `post_status`, `storage_status`, `pick_status`, `pack_status`, `sended_status`, `inspection_status`, `recheck_status`, `recheck_time`, `step`, `print_status`, `claim_status`, `outbound_status`, `lock_status`, `intercept_status` FROM `wms_order_delivery_1000028` AS `wms_order_delivery_1000028` WHERE `wms_order_delivery_1000028`.`warehouse_id` = 1000028 AND `wms_order_delivery_1000028`.`outbound_status` IN ('fin', 'padding') AND `wms_order_delivery_1000028`.`step` IN (4, 9) ORDER BY `wms_order_delivery_1000028`.`id` ASC LIMIT 1000; -2026-05-20 02:29:19,886 INFO 53968 [egg-sequelize](1ms) Executed (7c72e31e-15ee-45dc-a822-626dfe09a9fd): COMMIT; -2026-05-20 02:29:42,806 INFO 53968 [-/127.0.0.1/-/0ms SCHEDULE /__schedule?path=D:\wms\app\schedule\notice_stock_remaining.js&interval=30s&type=worker&immediate=false&disable=false] [notice_stock_remaining] 本轮任务启动 { - scheduleName: 'notice_stock_remaining', - cacheKeyPrefix: 'notice_stock_remaining_notified', - running: false -} -2026-05-20 02:29:42,807 INFO 53968 [-/127.0.0.1/-/1ms SCHEDULE /__schedule?path=D:\wms\app\schedule\notice_stock_remaining.js&interval=30s&type=worker&immediate=false&disable=false] [notice_stock_remaining] 已检查历史通知缓存 { - legacyCacheKey: 'notice_stock_remaining_notified_list', - cacheHit: false, - cachedValueType: 'object', - rawCacheCount: 0, - normalizedCount: 0, - cacheKeyMode: 'stock-day' -} -2026-05-20 02:29:42,808 INFO 53968 [egg-sequelize](1ms) Executed (default): SELECT `id`, `warehouse_id`, `retry_count`, `max_retry_count`, `next_retry_at`, `send_status`, `print_status` FROM `wms_print_record` AS `PrintRecord` WHERE ((`PrintRecord`.`send_status` = 'send_failed' OR `PrintRecord`.`print_status` IN ('print_failed', 'timeout')) AND `PrintRecord`.`next_retry_at` <= '2026-05-19 18:29:42' AND `PrintRecord`.`retry_count` < `max_retry_count`) ORDER BY `PrintRecord`.`next_retry_at` ASC, `PrintRecord`.`id` ASC LIMIT 20; -2026-05-20 02:29:42,824 INFO 53968 [egg-sequelize](16ms) Executed (default): SELECT `id`, `item_code`, `item_name`, `store_id`, `warehouse_id`, `remaining_threshold_days` FROM `wms_stock_warehouse` AS `stock_warehouse` WHERE `stock_warehouse`.`is_shelf_life_mgmt` = 'Y' AND `stock_warehouse`.`remaining_threshold_days` > 0 ORDER BY `stock_warehouse`.`remaining_threshold_days` ASC, `stock_warehouse`.`id` ASC; -2026-05-20 02:29:42,824 INFO 53968 [-/127.0.0.1/-/18ms SCHEDULE /__schedule?path=D:\wms\app\schedule\notice_stock_remaining.js&interval=30s&type=worker&immediate=false&disable=false] [notice_stock_remaining] 完成商品候选查询 { stockCount: 10 } -2026-05-20 02:29:42,827 INFO 53968 [egg-sequelize](1ms) Executed (default): SELECT `wms_storage`.`id`, `wms_storage`.`warehouse_id`, `wms_storage`.`store_id`, `wms_storage`.`space_id`, `wms_storage`.`stock_id`, `wms_storage`.`batch_no`, `wms_storage`.`inventory_type`, `wms_storage`.`quantity`, `wms_storage`.`locked_quantity`, `wms_storage`.`available_quantity`, `wms_storage`.`production_date`, `wms_storage`.`expiry_date`, `wms_storage`.`inbound_time`, `wms_storage`.`inbound_order_no`, `wms_storage`.`receiving_id`, `wms_storage`.`entry_order_id`, `wms_storage`.`supplier_id`, `wms_storage`.`supplier_batch_no`, `wms_storage`.`is_enabled`, `wms_storage`.`created_at`, `wms_storage`.`updated_at`, `wms_storage`.`delete_at`, `space`.`id` AS `space.id`, `space`.`space_code` AS `space.space_code`, `space`.`custom_name` AS `space.custom_name` FROM `wms_storage` AS `wms_storage` LEFT OUTER JOIN `wms_location_space` AS `space` ON `wms_storage`.`space_id` = `space`.`id` AND (`space`.`deleted_at` IS NULL) WHERE `wms_storage`.`stock_id` IN (156562, 156563, 156564, 156565, 156566, 157059, 157068, 156567, 157069, 157120) AND `wms_storage`.`is_enabled` = 1 AND `wms_storage`.`delete_at` IS NULL AND `wms_storage`.`quantity` > 0 AND (`wms_storage`.`expiry_date` IS NOT NULL AND `wms_storage`.`expiry_date` <= '2027-06-30 18:29:42') ORDER BY `wms_storage`.`expiry_date` ASC, `wms_storage`.`inbound_time` ASC, `wms_storage`.`id` ASC; -2026-05-20 02:29:42,827 INFO 53968 [-/127.0.0.1/-/21ms SCHEDULE /__schedule?path=D:\wms\app\schedule\notice_stock_remaining.js&interval=30s&type=worker&immediate=false&disable=false] [notice_stock_remaining] 完成库存候选查询 { stockCount: 10, storageCount: 4, maxThresholdDays: 407 } -2026-05-20 02:29:42,828 INFO 53968 [-/127.0.0.1/-/22ms SCHEDULE /__schedule?path=D:\wms\app\schedule\notice_stock_remaining.js&interval=30s&type=worker&immediate=false&disable=false] [notice_stock_remaining] 本轮通知缓存按商品日粒度独立写入,无需整体回写 { - cacheKeyPrefix: 'notice_stock_remaining_notified', - sentCount: 0, - skippedCount: 3, - ttlSeconds: 86400 -} -2026-05-20 02:29:42,828 INFO 53968 [-/127.0.0.1/-/22ms SCHEDULE /__schedule?path=D:\wms\app\schedule\notice_stock_remaining.js&interval=30s&type=worker&immediate=false&disable=false] [notice_stock_remaining] 本轮任务结束 { - scheduleName: 'notice_stock_remaining', - cacheKeyPrefix: 'notice_stock_remaining_notified', - stockCount: 10, - storageCount: 4, - sentCount: 0, - skippedCount: 3, - running: false -} -2026-05-20 02:30:12,790 INFO 53968 [egg-sequelize](1ms) Executed (default): SELECT TABLE_NAME AS tableName - FROM INFORMATION_SCHEMA.TABLES - WHERE TABLE_SCHEMA = DATABASE() - AND TABLE_NAME LIKE 'wms_order_delivery_%' -2026-05-20 02:30:12,791 INFO 53968 [egg-sequelize](1ms) Executed (18f648c2-cf18-4020-8d0d-1cb28f4ac6d8): START TRANSACTION; -2026-05-20 02:30:12,810 INFO 53968 [-/127.0.0.1/-/0ms SCHEDULE /__schedule?path=D:\wms\app\schedule\notice_stock_remaining.js&interval=30s&type=worker&immediate=false&disable=false] [notice_stock_remaining] 本轮任务启动 { - scheduleName: 'notice_stock_remaining', - cacheKeyPrefix: 'notice_stock_remaining_notified', - running: false -} -2026-05-20 02:30:12,812 INFO 53968 [-/127.0.0.1/-/2ms SCHEDULE /__schedule?path=D:\wms\app\schedule\notice_stock_remaining.js&interval=30s&type=worker&immediate=false&disable=false] [notice_stock_remaining] 已检查历史通知缓存 { - legacyCacheKey: 'notice_stock_remaining_notified_list', - cacheHit: false, - cachedValueType: 'object', - rawCacheCount: 0, - normalizedCount: 0, - cacheKeyMode: 'stock-day' -} -2026-05-20 02:30:12,817 INFO 53968 [egg-sequelize](1ms) Executed (default): SELECT `id`, `warehouse_id`, `retry_count`, `max_retry_count`, `next_retry_at`, `send_status`, `print_status` FROM `wms_print_record` AS `PrintRecord` WHERE ((`PrintRecord`.`send_status` = 'send_failed' OR `PrintRecord`.`print_status` IN ('print_failed', 'timeout')) AND `PrintRecord`.`next_retry_at` <= '2026-05-19 18:30:12' AND `PrintRecord`.`retry_count` < `max_retry_count`) ORDER BY `PrintRecord`.`next_retry_at` ASC, `PrintRecord`.`id` ASC LIMIT 20; -2026-05-20 02:30:12,835 INFO 53968 [egg-sequelize](18ms) Executed (default): SELECT `id`, `item_code`, `item_name`, `store_id`, `warehouse_id`, `remaining_threshold_days` FROM `wms_stock_warehouse` AS `stock_warehouse` WHERE `stock_warehouse`.`is_shelf_life_mgmt` = 'Y' AND `stock_warehouse`.`remaining_threshold_days` > 0 ORDER BY `stock_warehouse`.`remaining_threshold_days` ASC, `stock_warehouse`.`id` ASC; -2026-05-20 02:30:12,835 INFO 53968 [-/127.0.0.1/-/25ms SCHEDULE /__schedule?path=D:\wms\app\schedule\notice_stock_remaining.js&interval=30s&type=worker&immediate=false&disable=false] [notice_stock_remaining] 完成商品候选查询 { stockCount: 10 } -2026-05-20 02:30:12,837 INFO 53968 [egg-sequelize](1ms) Executed (default): SELECT `wms_storage`.`id`, `wms_storage`.`warehouse_id`, `wms_storage`.`store_id`, `wms_storage`.`space_id`, `wms_storage`.`stock_id`, `wms_storage`.`batch_no`, `wms_storage`.`inventory_type`, `wms_storage`.`quantity`, `wms_storage`.`locked_quantity`, `wms_storage`.`available_quantity`, `wms_storage`.`production_date`, `wms_storage`.`expiry_date`, `wms_storage`.`inbound_time`, `wms_storage`.`inbound_order_no`, `wms_storage`.`receiving_id`, `wms_storage`.`entry_order_id`, `wms_storage`.`supplier_id`, `wms_storage`.`supplier_batch_no`, `wms_storage`.`is_enabled`, `wms_storage`.`created_at`, `wms_storage`.`updated_at`, `wms_storage`.`delete_at`, `space`.`id` AS `space.id`, `space`.`space_code` AS `space.space_code`, `space`.`custom_name` AS `space.custom_name` FROM `wms_storage` AS `wms_storage` LEFT OUTER JOIN `wms_location_space` AS `space` ON `wms_storage`.`space_id` = `space`.`id` AND (`space`.`deleted_at` IS NULL) WHERE `wms_storage`.`stock_id` IN (156562, 156563, 156564, 156565, 156566, 157059, 157068, 156567, 157069, 157120) AND `wms_storage`.`is_enabled` = 1 AND `wms_storage`.`delete_at` IS NULL AND `wms_storage`.`quantity` > 0 AND (`wms_storage`.`expiry_date` IS NOT NULL AND `wms_storage`.`expiry_date` <= '2027-06-30 18:30:12') ORDER BY `wms_storage`.`expiry_date` ASC, `wms_storage`.`inbound_time` ASC, `wms_storage`.`id` ASC; -2026-05-20 02:30:12,838 INFO 53968 [-/127.0.0.1/-/28ms SCHEDULE /__schedule?path=D:\wms\app\schedule\notice_stock_remaining.js&interval=30s&type=worker&immediate=false&disable=false] [notice_stock_remaining] 完成库存候选查询 { stockCount: 10, storageCount: 4, maxThresholdDays: 407 } -2026-05-20 02:30:12,838 INFO 53968 [-/127.0.0.1/-/28ms SCHEDULE /__schedule?path=D:\wms\app\schedule\notice_stock_remaining.js&interval=30s&type=worker&immediate=false&disable=false] [notice_stock_remaining] 本轮通知缓存按商品日粒度独立写入,无需整体回写 { - cacheKeyPrefix: 'notice_stock_remaining_notified', - sentCount: 0, - skippedCount: 3, - ttlSeconds: 86400 -} -2026-05-20 02:30:12,839 INFO 53968 [-/127.0.0.1/-/29ms SCHEDULE /__schedule?path=D:\wms\app\schedule\notice_stock_remaining.js&interval=30s&type=worker&immediate=false&disable=false] [notice_stock_remaining] 本轮任务结束 { - scheduleName: 'notice_stock_remaining', - cacheKeyPrefix: 'notice_stock_remaining_notified', - stockCount: 10, - storageCount: 4, - sentCount: 0, - skippedCount: 3, - running: false -} -2026-05-20 02:30:13,021 INFO 53968 [egg-sequelize](230ms) Executed (18f648c2-cf18-4020-8d0d-1cb28f4ac6d8): SELECT `id`, `delivery_order_code`, `pre_delivery_order_code`, `pre_delivery_order_id`, `order_type`, `warehouse_code`, `order_flag`, `source_platform_code`, `source_platform_name`, `create_channel`, `source_order_codes`, `sys_platform_code`, `sys_platform_name`, `create_at`, `delete_at`, `updated_at`, `place_order_time`, `pay_time`, `pay_no`, `service_code`, `operator_name`, `operate_time`, `delivery_time`, `shop_nick`, `seller_nick`, `buyer_nick`, `total_amount`, `item_amount`, `discount_amount`, `freight`, `ar_amount`, `got_amount`, `service_fee`, `logistics_code`, `logistics_name`, `sys_logistics_code`, `sys_logistics_name`, `basket_number`, `express_code`, `logistics_area_code`, `delivery_type`, `weight_type`, `is_urgency`, `invoice_flag`, `status`, `name`, `zip_code`, `tel`, `mobile`, `email`, `country_code`, `province`, `city`, `area`, `town`, `detail_address`, `id_type`, `id_number`, `oaid`, `sync_status`, `store_id`, `warehouse_id`, `from_key`, `items`, `items_count`, `items_total`, `items_weight`, `items_hash`, `items_crc`, `wave_id`, `wave_no`, `wave_strategy_version`, `wave_scan_result`, `post_status`, `storage_status`, `pick_status`, `pack_status`, `sended_status`, `inspection_status`, `recheck_status`, `recheck_time`, `step`, `print_status`, `claim_status`, `outbound_status`, `lock_status`, `intercept_status` FROM `wms_order_delivery_100000` AS `wms_order_delivery_100000` WHERE `wms_order_delivery_100000`.`warehouse_id` = 100000 AND `wms_order_delivery_100000`.`outbound_status` IN ('fin', 'padding') AND `wms_order_delivery_100000`.`step` IN (4, 9) ORDER BY `wms_order_delivery_100000`.`id` ASC LIMIT 1000; -2026-05-20 02:30:13,021 INFO 53968 [egg-sequelize](0ms) Executed (18f648c2-cf18-4020-8d0d-1cb28f4ac6d8): COMMIT; -2026-05-20 02:30:13,022 INFO 53968 [egg-sequelize](0ms) Executed (12eff8f2-9550-42f8-8aa2-03c455990f4b): START TRANSACTION; -2026-05-20 02:30:13,023 INFO 53968 [egg-sequelize](1ms) Executed (12eff8f2-9550-42f8-8aa2-03c455990f4b): SELECT `id`, `delivery_order_code`, `pre_delivery_order_code`, `pre_delivery_order_id`, `order_type`, `warehouse_code`, `order_flag`, `source_platform_code`, `source_platform_name`, `create_channel`, `source_order_codes`, `sys_platform_code`, `sys_platform_name`, `create_at`, `delete_at`, `updated_at`, `place_order_time`, `pay_time`, `pay_no`, `service_code`, `operator_name`, `operate_time`, `delivery_time`, `shop_nick`, `seller_nick`, `buyer_nick`, `total_amount`, `item_amount`, `discount_amount`, `freight`, `ar_amount`, `got_amount`, `service_fee`, `logistics_code`, `logistics_name`, `sys_logistics_code`, `sys_logistics_name`, `basket_number`, `express_code`, `logistics_area_code`, `delivery_type`, `weight_type`, `is_urgency`, `invoice_flag`, `status`, `name`, `zip_code`, `tel`, `mobile`, `email`, `country_code`, `province`, `city`, `area`, `town`, `detail_address`, `id_type`, `id_number`, `oaid`, `sync_status`, `store_id`, `warehouse_id`, `from_key`, `items`, `items_count`, `items_total`, `items_weight`, `items_hash`, `items_crc`, `wave_id`, `wave_no`, `wave_strategy_version`, `wave_scan_result`, `post_status`, `storage_status`, `pick_status`, `pack_status`, `sended_status`, `inspection_status`, `recheck_status`, `recheck_time`, `step`, `print_status`, `claim_status`, `outbound_status`, `lock_status`, `intercept_status` FROM `wms_order_delivery_1000028` AS `wms_order_delivery_1000028` WHERE `wms_order_delivery_1000028`.`warehouse_id` = 1000028 AND `wms_order_delivery_1000028`.`outbound_status` IN ('fin', 'padding') AND `wms_order_delivery_1000028`.`step` IN (4, 9) ORDER BY `wms_order_delivery_1000028`.`id` ASC LIMIT 1000; -2026-05-20 02:30:13,024 INFO 53968 [egg-sequelize](1ms) Executed (12eff8f2-9550-42f8-8aa2-03c455990f4b): COMMIT; -2026-05-20 02:30:42,817 INFO 53968 [-/127.0.0.1/-/0ms SCHEDULE /__schedule?path=D:\wms\app\schedule\notice_stock_remaining.js&interval=30s&type=worker&immediate=false&disable=false] [notice_stock_remaining] 本轮任务启动 { - scheduleName: 'notice_stock_remaining', - cacheKeyPrefix: 'notice_stock_remaining_notified', - running: false -} -2026-05-20 02:30:42,819 INFO 53968 [-/127.0.0.1/-/2ms SCHEDULE /__schedule?path=D:\wms\app\schedule\notice_stock_remaining.js&interval=30s&type=worker&immediate=false&disable=false] [notice_stock_remaining] 已检查历史通知缓存 { - legacyCacheKey: 'notice_stock_remaining_notified_list', - cacheHit: false, - cachedValueType: 'object', - rawCacheCount: 0, - normalizedCount: 0, - cacheKeyMode: 'stock-day' -} -2026-05-20 02:30:42,820 INFO 53968 [egg-sequelize](2ms) Executed (default): SELECT `id`, `warehouse_id`, `retry_count`, `max_retry_count`, `next_retry_at`, `send_status`, `print_status` FROM `wms_print_record` AS `PrintRecord` WHERE ((`PrintRecord`.`send_status` = 'send_failed' OR `PrintRecord`.`print_status` IN ('print_failed', 'timeout')) AND `PrintRecord`.`next_retry_at` <= '2026-05-19 18:30:42' AND `PrintRecord`.`retry_count` < `max_retry_count`) ORDER BY `PrintRecord`.`next_retry_at` ASC, `PrintRecord`.`id` ASC LIMIT 20; -2026-05-20 02:30:42,834 INFO 53968 [egg-sequelize](14ms) Executed (default): SELECT `id`, `item_code`, `item_name`, `store_id`, `warehouse_id`, `remaining_threshold_days` FROM `wms_stock_warehouse` AS `stock_warehouse` WHERE `stock_warehouse`.`is_shelf_life_mgmt` = 'Y' AND `stock_warehouse`.`remaining_threshold_days` > 0 ORDER BY `stock_warehouse`.`remaining_threshold_days` ASC, `stock_warehouse`.`id` ASC; -2026-05-20 02:30:42,834 INFO 53968 [-/127.0.0.1/-/17ms SCHEDULE /__schedule?path=D:\wms\app\schedule\notice_stock_remaining.js&interval=30s&type=worker&immediate=false&disable=false] [notice_stock_remaining] 完成商品候选查询 { stockCount: 10 } -2026-05-20 02:30:42,836 INFO 53968 [egg-sequelize](1ms) Executed (default): SELECT `wms_storage`.`id`, `wms_storage`.`warehouse_id`, `wms_storage`.`store_id`, `wms_storage`.`space_id`, `wms_storage`.`stock_id`, `wms_storage`.`batch_no`, `wms_storage`.`inventory_type`, `wms_storage`.`quantity`, `wms_storage`.`locked_quantity`, `wms_storage`.`available_quantity`, `wms_storage`.`production_date`, `wms_storage`.`expiry_date`, `wms_storage`.`inbound_time`, `wms_storage`.`inbound_order_no`, `wms_storage`.`receiving_id`, `wms_storage`.`entry_order_id`, `wms_storage`.`supplier_id`, `wms_storage`.`supplier_batch_no`, `wms_storage`.`is_enabled`, `wms_storage`.`created_at`, `wms_storage`.`updated_at`, `wms_storage`.`delete_at`, `space`.`id` AS `space.id`, `space`.`space_code` AS `space.space_code`, `space`.`custom_name` AS `space.custom_name` FROM `wms_storage` AS `wms_storage` LEFT OUTER JOIN `wms_location_space` AS `space` ON `wms_storage`.`space_id` = `space`.`id` AND (`space`.`deleted_at` IS NULL) WHERE `wms_storage`.`stock_id` IN (156562, 156563, 156564, 156565, 156566, 157059, 157068, 156567, 157069, 157120) AND `wms_storage`.`is_enabled` = 1 AND `wms_storage`.`delete_at` IS NULL AND `wms_storage`.`quantity` > 0 AND (`wms_storage`.`expiry_date` IS NOT NULL AND `wms_storage`.`expiry_date` <= '2027-06-30 18:30:42') ORDER BY `wms_storage`.`expiry_date` ASC, `wms_storage`.`inbound_time` ASC, `wms_storage`.`id` ASC; -2026-05-20 02:30:42,836 INFO 53968 [-/127.0.0.1/-/19ms SCHEDULE /__schedule?path=D:\wms\app\schedule\notice_stock_remaining.js&interval=30s&type=worker&immediate=false&disable=false] [notice_stock_remaining] 完成库存候选查询 { stockCount: 10, storageCount: 4, maxThresholdDays: 407 } -2026-05-20 02:30:42,837 INFO 53968 [-/127.0.0.1/-/20ms SCHEDULE /__schedule?path=D:\wms\app\schedule\notice_stock_remaining.js&interval=30s&type=worker&immediate=false&disable=false] [notice_stock_remaining] 本轮通知缓存按商品日粒度独立写入,无需整体回写 { - cacheKeyPrefix: 'notice_stock_remaining_notified', - sentCount: 0, - skippedCount: 3, - ttlSeconds: 86400 -} -2026-05-20 02:30:42,837 INFO 53968 [-/127.0.0.1/-/20ms SCHEDULE /__schedule?path=D:\wms\app\schedule\notice_stock_remaining.js&interval=30s&type=worker&immediate=false&disable=false] [notice_stock_remaining] 本轮任务结束 { - scheduleName: 'notice_stock_remaining', - cacheKeyPrefix: 'notice_stock_remaining_notified', - stockCount: 10, - storageCount: 4, - sentCount: 0, - skippedCount: 3, - running: false -} -2026-05-20 02:31:12,797 INFO 53968 [egg-sequelize](2ms) Executed (default): SELECT TABLE_NAME AS tableName - FROM INFORMATION_SCHEMA.TABLES - WHERE TABLE_SCHEMA = DATABASE() - AND TABLE_NAME LIKE 'wms_order_delivery_%' -2026-05-20 02:31:12,798 INFO 53968 [egg-sequelize](1ms) Executed (677b3412-e55a-44fe-8846-4f6255510224): START TRANSACTION; -2026-05-20 02:31:12,826 INFO 53968 [-/127.0.0.1/-/0ms SCHEDULE /__schedule?path=D:\wms\app\schedule\notice_stock_remaining.js&interval=30s&type=worker&immediate=false&disable=false] [notice_stock_remaining] 本轮任务启动 { - scheduleName: 'notice_stock_remaining', - cacheKeyPrefix: 'notice_stock_remaining_notified', - running: false -} -2026-05-20 02:31:12,827 INFO 53968 [-/127.0.0.1/-/1ms SCHEDULE /__schedule?path=D:\wms\app\schedule\notice_stock_remaining.js&interval=30s&type=worker&immediate=false&disable=false] [notice_stock_remaining] 已检查历史通知缓存 { - legacyCacheKey: 'notice_stock_remaining_notified_list', - cacheHit: false, - cachedValueType: 'object', - rawCacheCount: 0, - normalizedCount: 0, - cacheKeyMode: 'stock-day' -} -2026-05-20 02:31:12,832 INFO 53968 [egg-sequelize](0ms) Executed (default): SELECT `id`, `warehouse_id`, `retry_count`, `max_retry_count`, `next_retry_at`, `send_status`, `print_status` FROM `wms_print_record` AS `PrintRecord` WHERE ((`PrintRecord`.`send_status` = 'send_failed' OR `PrintRecord`.`print_status` IN ('print_failed', 'timeout')) AND `PrintRecord`.`next_retry_at` <= '2026-05-19 18:31:12' AND `PrintRecord`.`retry_count` < `max_retry_count`) ORDER BY `PrintRecord`.`next_retry_at` ASC, `PrintRecord`.`id` ASC LIMIT 20; -2026-05-20 02:31:12,847 INFO 53968 [egg-sequelize](16ms) Executed (default): SELECT `id`, `item_code`, `item_name`, `store_id`, `warehouse_id`, `remaining_threshold_days` FROM `wms_stock_warehouse` AS `stock_warehouse` WHERE `stock_warehouse`.`is_shelf_life_mgmt` = 'Y' AND `stock_warehouse`.`remaining_threshold_days` > 0 ORDER BY `stock_warehouse`.`remaining_threshold_days` ASC, `stock_warehouse`.`id` ASC; -2026-05-20 02:31:12,848 INFO 53968 [-/127.0.0.1/-/22ms SCHEDULE /__schedule?path=D:\wms\app\schedule\notice_stock_remaining.js&interval=30s&type=worker&immediate=false&disable=false] [notice_stock_remaining] 完成商品候选查询 { stockCount: 10 } -2026-05-20 02:31:12,851 INFO 53968 [egg-sequelize](2ms) Executed (default): SELECT `wms_storage`.`id`, `wms_storage`.`warehouse_id`, `wms_storage`.`store_id`, `wms_storage`.`space_id`, `wms_storage`.`stock_id`, `wms_storage`.`batch_no`, `wms_storage`.`inventory_type`, `wms_storage`.`quantity`, `wms_storage`.`locked_quantity`, `wms_storage`.`available_quantity`, `wms_storage`.`production_date`, `wms_storage`.`expiry_date`, `wms_storage`.`inbound_time`, `wms_storage`.`inbound_order_no`, `wms_storage`.`receiving_id`, `wms_storage`.`entry_order_id`, `wms_storage`.`supplier_id`, `wms_storage`.`supplier_batch_no`, `wms_storage`.`is_enabled`, `wms_storage`.`created_at`, `wms_storage`.`updated_at`, `wms_storage`.`delete_at`, `space`.`id` AS `space.id`, `space`.`space_code` AS `space.space_code`, `space`.`custom_name` AS `space.custom_name` FROM `wms_storage` AS `wms_storage` LEFT OUTER JOIN `wms_location_space` AS `space` ON `wms_storage`.`space_id` = `space`.`id` AND (`space`.`deleted_at` IS NULL) WHERE `wms_storage`.`stock_id` IN (156562, 156563, 156564, 156565, 156566, 157059, 157068, 156567, 157069, 157120) AND `wms_storage`.`is_enabled` = 1 AND `wms_storage`.`delete_at` IS NULL AND `wms_storage`.`quantity` > 0 AND (`wms_storage`.`expiry_date` IS NOT NULL AND `wms_storage`.`expiry_date` <= '2027-06-30 18:31:12') ORDER BY `wms_storage`.`expiry_date` ASC, `wms_storage`.`inbound_time` ASC, `wms_storage`.`id` ASC; -2026-05-20 02:31:12,851 INFO 53968 [-/127.0.0.1/-/25ms SCHEDULE /__schedule?path=D:\wms\app\schedule\notice_stock_remaining.js&interval=30s&type=worker&immediate=false&disable=false] [notice_stock_remaining] 完成库存候选查询 { stockCount: 10, storageCount: 4, maxThresholdDays: 407 } -2026-05-20 02:31:12,852 INFO 53968 [-/127.0.0.1/-/26ms SCHEDULE /__schedule?path=D:\wms\app\schedule\notice_stock_remaining.js&interval=30s&type=worker&immediate=false&disable=false] [notice_stock_remaining] 本轮通知缓存按商品日粒度独立写入,无需整体回写 { - cacheKeyPrefix: 'notice_stock_remaining_notified', - sentCount: 0, - skippedCount: 3, - ttlSeconds: 86400 -} -2026-05-20 02:31:12,852 INFO 53968 [-/127.0.0.1/-/26ms SCHEDULE /__schedule?path=D:\wms\app\schedule\notice_stock_remaining.js&interval=30s&type=worker&immediate=false&disable=false] [notice_stock_remaining] 本轮任务结束 { - scheduleName: 'notice_stock_remaining', - cacheKeyPrefix: 'notice_stock_remaining_notified', - stockCount: 10, - storageCount: 4, - sentCount: 0, - skippedCount: 3, - running: false -} -2026-05-20 02:31:13,039 INFO 53968 [egg-sequelize](240ms) Executed (677b3412-e55a-44fe-8846-4f6255510224): SELECT `id`, `delivery_order_code`, `pre_delivery_order_code`, `pre_delivery_order_id`, `order_type`, `warehouse_code`, `order_flag`, `source_platform_code`, `source_platform_name`, `create_channel`, `source_order_codes`, `sys_platform_code`, `sys_platform_name`, `create_at`, `delete_at`, `updated_at`, `place_order_time`, `pay_time`, `pay_no`, `service_code`, `operator_name`, `operate_time`, `delivery_time`, `shop_nick`, `seller_nick`, `buyer_nick`, `total_amount`, `item_amount`, `discount_amount`, `freight`, `ar_amount`, `got_amount`, `service_fee`, `logistics_code`, `logistics_name`, `sys_logistics_code`, `sys_logistics_name`, `basket_number`, `express_code`, `logistics_area_code`, `delivery_type`, `weight_type`, `is_urgency`, `invoice_flag`, `status`, `name`, `zip_code`, `tel`, `mobile`, `email`, `country_code`, `province`, `city`, `area`, `town`, `detail_address`, `id_type`, `id_number`, `oaid`, `sync_status`, `store_id`, `warehouse_id`, `from_key`, `items`, `items_count`, `items_total`, `items_weight`, `items_hash`, `items_crc`, `wave_id`, `wave_no`, `wave_strategy_version`, `wave_scan_result`, `post_status`, `storage_status`, `pick_status`, `pack_status`, `sended_status`, `inspection_status`, `recheck_status`, `recheck_time`, `step`, `print_status`, `claim_status`, `outbound_status`, `lock_status`, `intercept_status` FROM `wms_order_delivery_100000` AS `wms_order_delivery_100000` WHERE `wms_order_delivery_100000`.`warehouse_id` = 100000 AND `wms_order_delivery_100000`.`outbound_status` IN ('fin', 'padding') AND `wms_order_delivery_100000`.`step` IN (4, 9) ORDER BY `wms_order_delivery_100000`.`id` ASC LIMIT 1000; -2026-05-20 02:31:13,039 INFO 53968 [egg-sequelize](0ms) Executed (677b3412-e55a-44fe-8846-4f6255510224): COMMIT; -2026-05-20 02:31:13,040 INFO 53968 [egg-sequelize](0ms) Executed (df0162d2-781e-4009-9347-bb632207516e): START TRANSACTION; -2026-05-20 02:31:13,041 INFO 53968 [egg-sequelize](1ms) Executed (df0162d2-781e-4009-9347-bb632207516e): SELECT `id`, `delivery_order_code`, `pre_delivery_order_code`, `pre_delivery_order_id`, `order_type`, `warehouse_code`, `order_flag`, `source_platform_code`, `source_platform_name`, `create_channel`, `source_order_codes`, `sys_platform_code`, `sys_platform_name`, `create_at`, `delete_at`, `updated_at`, `place_order_time`, `pay_time`, `pay_no`, `service_code`, `operator_name`, `operate_time`, `delivery_time`, `shop_nick`, `seller_nick`, `buyer_nick`, `total_amount`, `item_amount`, `discount_amount`, `freight`, `ar_amount`, `got_amount`, `service_fee`, `logistics_code`, `logistics_name`, `sys_logistics_code`, `sys_logistics_name`, `basket_number`, `express_code`, `logistics_area_code`, `delivery_type`, `weight_type`, `is_urgency`, `invoice_flag`, `status`, `name`, `zip_code`, `tel`, `mobile`, `email`, `country_code`, `province`, `city`, `area`, `town`, `detail_address`, `id_type`, `id_number`, `oaid`, `sync_status`, `store_id`, `warehouse_id`, `from_key`, `items`, `items_count`, `items_total`, `items_weight`, `items_hash`, `items_crc`, `wave_id`, `wave_no`, `wave_strategy_version`, `wave_scan_result`, `post_status`, `storage_status`, `pick_status`, `pack_status`, `sended_status`, `inspection_status`, `recheck_status`, `recheck_time`, `step`, `print_status`, `claim_status`, `outbound_status`, `lock_status`, `intercept_status` FROM `wms_order_delivery_1000028` AS `wms_order_delivery_1000028` WHERE `wms_order_delivery_1000028`.`warehouse_id` = 1000028 AND `wms_order_delivery_1000028`.`outbound_status` IN ('fin', 'padding') AND `wms_order_delivery_1000028`.`step` IN (4, 9) ORDER BY `wms_order_delivery_1000028`.`id` ASC LIMIT 1000; -2026-05-20 02:31:13,041 INFO 53968 [egg-sequelize](0ms) Executed (df0162d2-781e-4009-9347-bb632207516e): COMMIT; -2026-05-20 02:31:33,621 INFO 33312 [master] master is killed by signal SIGINT, closing diff --git a/final_sf.json b/final_sf.json deleted file mode 100644 index f1abf530cc9b25fc005ebd219f96d1b08918a5c6..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 112110 zcmds=dyE~|ecwm5g%mETrs^NEq%>TuBwMsZ@wI%qi7ip0WLxBtT2g$AA(u;v(k}PG zB_)av8xn-t1t{CNyR{IY0^&#k3bMBAz)o#BcB&|dR5$%2Y7nCaY7&VYNQGk;2&$q% zt)9>Q@$j6PIdkUBoVjyX#e(F%c<*<9@7MXA_kMYQ^04|CR)5wf8}WEcjH$2ItFNcj&!1FZ%_PT@$JD>$>SG{TlH8v>rM?Z_UVyB$^EU825!K>gvJ z?p8lNo-FVF?|anu^!p4XN7PSeyWfBK>i^u(eeW@agP)jJ;k`ejehW-TyU#eLkgxCl z245dl?>DKwKCb@X;bfco%?b6sht63C!jm7zQ;2jSD)Y4{n>%!A15E`Qtw!D zQhj$u{r*PvH`H8`d|Le`zdz8W;iCDM#@; z6N&vBXH#DdBzGu^EK7!xRmtM+YoAUA)w4i%dG)D&FImk{cw6cb@7Zgx*kmM*S@N8*pq&{eL(yqW+9_ zX?sY~nBQF1eHGynuR7cP?qG6SNtRH;@OgiiR+H-852;r~0+E;f>Xl~IcXQxV^*UrATem8j{dBr_fpJ__{ z52$cRA(o$kkk1}cnz=k#ovct2vMgDdtWkgS{kytbuxquxQ)F_pmBUb275DE4Q{BEmd4MG+C-B zywwGgCkV4V70E;DmM3ewfBGkRAjF!dZF7^7hh7l@tgR_|AQT(?_j8}$_g80cn7jA( z!>5eo5r3>swB+49e_&_0@2Dbq;4mIo+r7GyXQ;ANX^hYA_-)=gOY%UNw|lnD+pXfo z&m_CN@7GH^*K27TQgXINNgKLV&(0ZX>r5QH{Lw?UPknuUV8x<+K3-*MS4F*P)AqO1iO|629&rP+-i+;nd5#It)} z-@K#q>xc8U9z?}8mY5v9UaY#RTdxobELD`)+m*XKZjIS*AFA8?I<_7frg^xwE32y- zz#))^epC5T9X!>OP6<5Q$0L|Kqp>C{7jUw-hK&Yvk zea8K&x}NO<{Bh@}%iezMwxh3YBL_J@`gc!DE!L-h`PX$t6d(z${MWM?HXS6YDCT$C zW{ABIZfY3{_ea}R2eb-(>c^@eT%YI;SXgcw>xF%bVGjPP5Gd@kpy_E^aH6y2ql(wv)lT746Q|guqi&S=tkM}b>cd0qJytar|U{o z2;uRwbFWW+Z6}}ksFRmBm#wd7=b>3>hu5Y_Ts3-4h3XOro9NjKddZw(bW=F`?dg+G zgY0{q*S6hqw(Tyx&sT#=;we|f*QNqJd!O9-t?SAPJWTTsgvC)pUfONzDi$Tyz6uZj zU|PppAZjY+s;7s=Iw<^PMowbNrOF~1D%6R&jE4-5w?;f2ArRUTx{1!~M_tWETp)Bs zPWDWX^zmaX!{FQ>9=tdporL1tKg-X2U9}%|C3$+JX+<~k=vCa+Ow0uhslVBlfsC^# z`*-s`pNZu;=!?2QVf1og@R6uX=zw(x;ZTH)4~@L)M_qYN(v4WBY}`r}do`tv=SNRI z?f2B+&=z)KaMGp&6}ebm*7w(;zS_mhwOx61RY|H;Nb-7F96^I(FgKsLP92T!#vNbu$5R>#pqG4rus$D&!t|tT zuj)%6wE4(%fPA>?<<&gq%JHp-ZkW672|phV4?$zkyZ3{SHU)@#()|t)W-B-Td}wWO zm0Wu7E0hkcRv&bf)9;;q-)u%CQ8fr%y){GSG=WUZbzSXQc~!1JSf)R&itE3d|HI4Aj1A81`O3k=oV<8@w7P`Z(ghAYf=mlmIf3D; z?G)E_Y+8iXbwF5j0;3I&WP2lt_Bl0Vdm|9qXG~m@m(StyoRlhS9e#qKKNiELh_BWP zLVUH~VubsqU7k9R+q0C_ctDu7GX3h>Qa8){Adxfo)46QL;m(h@m)Cj9B-dTT2TRyV zt$KDsD8Q8AkkYj}F)IkgvibUJ&D43aH6CK7<)s}Np`kuW8^%Fjou^)n2NWSE?&|Sz zjpClrf*fR-;%9YUf>3wfdtd2E^HQoC^ml#pn1V1J$L1}*t&ioEo;p>Y-ty9>1>CGt zd$oDl`$|uimr~^+!Y_{RtMk&-(3|U(f}(B*yh`_*Iti6nXd)UKs-GatpNZ{Vt*5BY zv#x7ZRyp(&gjK3{qMvt;hgJvD`tJ6VSsw|e^x68jlYN}C#j5iBOVyv4I-Nw*Ae2*m zy{hrp5w%n|IGt!m)c%+RgvH*nYK^B37i|uLW>)Ruh&dT-QvofEIpLI#p+PvRqBYm4 zTYbI)`m+gv51$3dM#yDRb@un&5j6;18xeF~+RV%oXYSFLIvpDj>KFw2Jn;NiFReQJ zM(3}W-EyW*#uk^Yfu`=N>+m$<|hg?>U@>9*rLjebGa@S=^^y0zxTCX7aCop z#{~^Im*kK3LFn82+MX_IE;409zg1^$Ak>kjjxuelto6B=i?QYPwjYhoEVr zSIHSyO$TF9L#!zXp^v@27cPe7ZM%}~$!4`v<{q!yWOb-o>fO zYXpksG9YZbrUkQO^(M!}>gq|OHaSTTmQx$ma##@NExpal-b@>%IeDU+uiLi<#P!5& zT2M2I$$|8wQMz${{4DZ)=V1>sn@4ZhprXn`My{hgzJ^I z^!`MWU1I{j)NjkTZGg~3Ohx*6)3NJDFaOrx?s;qfjc4yYy8iLs-y`R2n%XN4imaYC zsiTG-)gm$zje$@suGZ4F{HAb|*(v`SK@g^=go?P?MwcEmO?ph53i!{M*(1q}K-l&K z8F5?u1ey5E`sXm}P4z&pxXLfON6l2IAlEP<>%MO4*tUxUZ!fzz0Pjry@%=bsA=HSq5js1n?yKQwam?rA zC7z0t$lSS66f@@kzmJ&0IntgoMf zo=J$fPLa`2cxp8CegY= zSy*HS!g74JcjrVJ6XjKFpV_+S^xW%XpWb3uu79@OmN)m!3B}#BUU-7M7l2;o%qJe* zP{ZA;G~UZsTaidDtT%G6k}-DfZB<#owyUzH_Zp=UE+kpgat1;}m3;JIW*X$aQ09x` zVo8~wlzYBzo*&%#)Y$&c&$i!m79`c8+;*hQNEir_GCf};HN2P_JGXr`xlu^CnU^!$ zX5ddbCl?!W*nD*RBha{eX-1d(F<)dT077DmnA*C1BcT5_K$(A~P9eAXfTK*}L1@?B z`sbar#mHI<5Ze4S7DG;rQXUTrPy2}$HYE>FubN%+z}Vf$vw&SCgg=y<6UiOYg3PG{eliF0j;gcV{gH2+OT;f95ansd{rJoz9qi={u84cKqkheR}u* z-t&{$P-_A0iaZf?%bsFyw*Me!Z+Px{JwZXJPyaL>QD&i+ULd2sJ0eBa4kH``E2^$n8+KtXGlwtc@tA>!Ge!=*LYya_6Mf z5&ZT+xa{jaGf(}9%6DJBWZ$V?g>psKB5x@`(_F{drb1jz%t#jqb%asW<+?xF)WAieCiK`^{eMh zyZJp&HY##?9V+8@t7qTU`3L{<+S9*0cgu)f`?9&(nYeD(>zn(-TPQVIc>{r_58lY1 zZTh(z((eMH`_yhszl*cUaS@^BFZh;OT)ye7@K#T)ly9_F-T(y6#*TCZ zg+g&R66@X<2(ba-8eCs{rS}E;D(7oJnD1%YoNQx4P}JueWp zIg7+OTPi-`JueWttg>*l+4w)JkA7VQS+$KX)W-Gm!@c-fGC%J?*rde;y>wjTq9Ng( z=|Vqr;%htm$;mtyp`6YTTv3rt32OfJp4E@jrF)xcD3n zgwUm^GHmeK{Rg%o#7S3Y;?c`HCS-rK`0g){{%8+q?wNh<3wqw+jm{0{s>B^(9^7v+ zvT_C{Lj{+d2{nkmsRGrPvO2S6%#~>#hDw^vNoLE)9^(3eIy!Sl-)>%OKKJ5u4is6h zGNqVlh~ivJQ;c}LF26y@>DG{#yh-msWm@(%>2sJxnxB??mv`4(Psig$+`jos*`n7VblXdR?$zFTTa6Ie(wRlvtYHyH#ZLct`_v?o@a){1lXlL{ z_k6Z6pVha+W$0t(0c3_$@~<_@Uc^KRp%ZFlbKPl#E`2baJ~MmRj0Ml?@?)26o@V{^ zJ+n7|srMN-{u-K0sa`7^jADDcHqGK@*>uK@oP)59jGLK6z3naB0`+9W*{KQp`!wNI3~qy{28iB1R6tso9W<7&O!w ztc#Pj=QX)^^R;W?<*35aY$eR51zK6><_zhif>5+FYyxA0+IB%+qd#PyE_?jwH~1tf z8<&LUh`n8SdF}t zfpD>v|?P@Nh$6F>B_s?aM`zKos7%N7XRh&_mtnQN-P*$#y1*yHc#zOe7LqsFRL zp;=WKbITW)veh2rSzVPL`}whFKFmJPl$SBLe1VYna9J~Cj!3Y5X|p8_guU88&qNt> zjBKFu$3%u}c`pjW!7H0EWm+U=iZN#E7f6n(IJ{~H*rtPBi$F5+)f>Ou`6tUjs3(_r z^=2kB)+$Nmp7GeJKr#{#E}CDo<(<)XCV$GOen2##vYKq%;Ibb!CE_}RX7WeJwnZI@ z4PBbKqait2?6YFor)t7m+4e(hM{negI9xW7#LpgRx%)q-F3i6&z3H5u5c=SIU)foO ze*N-XHZ8CrDcOiPCol=G48N%lb^4@(=c?07WvfBB9TV9yFqqP&$!pUZ;lR}rK>(PRcY4F~~ zYEZ7#!pV2WsC@CGyRt2ex0YiqKBG z%4~cm2z$pz>2cEKuirZYVU~~m%lAN2HS)Hp5Erk7oO%bLNdAc0*7~rjEBGvWJCRvB z8vx;0a#(4_iKvY>=*Dv8&tq@ZxG?_*)89I2Jire(UmW0mvHy7P_T``W>2FQ^`&0d# z9uaDl&2HPYh?6mLyU^A61|YsVvncq6DKd$V2HCo>J26663e^{bE^z!m?4u!^MF zvr4j!g?qKiW>>;E`Mv3j179Bf_)o#KFt=kcryx9~ZjW_9TZIB~v0+{Qxp-#~`ezlW zkRx^cTfd%XG!g#gZ<7R#t1g!Hm(672)#}GW0T2om(83|FKKS#tUUjKKX#1_S7P3Et zeR^>dC(@bLR`vbJOXvWlgch-tS!RrNEzd;x@e#g{m&5?lH*3Z>3Ky?A{SSAqI`L~W z(x<+8{;r+cW4<)@?!oD~AB-*9*W^@5+(ZfV!8W)&rcEFCTXyS)Z+k#U1|S}jjw0Gc z#f$C-2(kPw+gr51sW)}nbT(iz0ij_Pe6~fA6M*cqiRtqUCP#LE?7;7yUN?2!u6L~M zd5gAeI=6S?*}boCUKl}YZ zZ)9BD=}6WS6Nh}O^YhRB{PKfG-Woaiw8=r=c$Z0yxqM#LJ0zxCe8$LH70R`fWr@Vu zQ~fp-%5O{a#cj=G%2|Z|Oj$NX5%bmSqUa7vnumJ6ySj9>b27u`AM~=R5LX!uw-m(Q zOo`$b*D9M$4CR)05W1%++l_^aCzU~1zWIrGlexCI3~=wndzS`JXJ>Mjbm_M&`I!0_ zG-Y!KSs&ky_0V^iYK~$r3{~QGGBBspTvo3U`mG1(sdp3O#(4lYPoa(GXw|&5pB&XR zc|UVB)*l#-etYuX4-P(IYbX+fgt_gV+t#(qPcVQ`G*tK*+g-0RNw-DCkL1Wyv5WI# z5W4K{Lh%biL%$7Sg9JDD#dgg)6Cc{O&B|CLTS-e8^wKtXp-34v!cahDE~XX}E@hk_ zNPl3>nS@SLEln{HX1(XakvC)wgxT$pCTk($ito|d=cUFvZ#*}&ojJ|7M`c zdfaZ7(>AT_9kU>G^{)N;9bS2rvueaISQnY6uEOu*SL4I=S0pQc{v=P|{CTw|`7gEJC(k- z=SSP?PLzQKdW&6uO!0QMr+d#e4Uj9c1s|_Pu0U9HcUv=+)-q`^9*d|N9;WA5KxitF zE_pN4>YCDd9>#99YMYaW7F1gO)1c*?^q(gwnj$E!WV*6xdx8LeDm#4ao(D86lZFsp zqK`zP^={q+MOZ}He2k%K;;)_yLciT_YPXSJvy5&EN9hftomv}0q76Ss&yU9JD*{LR z9^9ry*+~)*`Z?)7O%gw6mW{)-pIo7=iOdU%Zi3Ji_ejj+=4G!YKZ|%N-6834Wh2)ZUY;M-dC}K*#h#&Ui`dHc zq0)90gjua@JA$Q0EqS~vzXf4YJ-x`b>OJ~eALBVGd$@XUVQpGu^W3r=7fR*rYuGf~ zL+Z}Z5pU*`^=$bpw=7B(8ymmvnfxpyhB9#&-7ai?`3@Fn=s$PES*bUUUYNggT-ym> zzL=$2)fgH)?!75T^G^-O=3$aAx9@k6#>kW%`{_nf)ezBYKfp6lA&zEyHCGJmouM z!uQ1(y2Q(#%%OnvAI4zNU3d1W4jxU3gk1y8k|@x~6iCj3R( zg)VVi)mZ=tdGfZn$_y`4+~K+k!hFn;=PGwIwV|uvX|~=1S2bPYxJvbGUpK2dYfX<8 z?RUaLP$!W}CSBJxDlTP)(Vt^x{cCl90S)_Ad*{p@PwYQ21j2L{l$XJyM_xPj+dJ&d zaPd`z!6X~+f~5KVs+=m&bcj2>A$^P{<^;-OSrc0ddSutnMa@BIh}61j3N{y|@2@v> zHQW6ML)>{op1|c5Y-+?ztbHA|fNX`N&_*h_@R3&1H1$#_zeHq4D7^ zd9%+ge|dCh`;N|kJFIi&=3MXlbW8tJFwqdPZntlpRbpbIAk;Q-il`^T^*n5 z9t!USLO8NM+0*hg43m5zXIeq1PlUQ;ZAa&&85z&mhQ2Y9ej9(XF?;nL&tm>Q79>gecLU@5~SgvliSXah-`{2fuLEaP@5%lhUi&R8F7&e_C+|1qtVR*`^)H?eZKrnvAwqjwkF>mwn zu1%GYYQ1o=Xx^mlPN<-l)6Y8o0AaQ|9jBq#xa!;lN6c>PI(w~cdX)9GpS;p#JXJV7 z6dr@%6}TfoHjB#%^eQo1Q5*sdi>sCW@(MgB`wrsgD8AL1n!R`bSZ83xnG>&emhAY% z#D)1MhpR@tBJudiboaI$`(db2T%!?PAOcNy{IcD?aETj9Hdd-k7DM%=^CF&iR1|L#e+P=BC?WvY1)v_r?*=O!gQ^~FKywy<&EkN+AWpj&7P$jQdsp#Kxm%kYc-y}+8G+Y zZdqsIvq#?UZsai?n5vPuSPQ7uZp5Lf0VS{){_04%m-64gpr?C~?IyU$X^eQy%yQB0 zx1gP&TA7Y(;AMZjfbdjk15b;lT|p@G6MoIqT^P9L@4z&{Q|9^g#&i&d^z-x9Hp^43 znG&7)Y-^f}c@Bc94PP!?6l#QMrrGfU!u&+tDy!Gx=VDcFp0%zZ$Nm*tRuHC7M!2$c z`ee4(w9j($`t@~Fb5$sXG_-Z10NQB!gm4vvhO>FDhR@c;bCvBvS!-K;I#O%q&@l50 zo6hy3zYW!TSM3uX3N@(q`K!Ec+bS9$k{51YV|mEN8Rk%mHPdJ%2qo?=wyuVUY5N+l znI;MXM_cw*(}(%GaIS(dubJUzL^dWnBBEJ3q)buyPNj;prL(C#SH;#!H7%``@bedY z#<_?e!x0%6g#=5BRbWVli^ThfG}GhVc@8E&#eO!i8ZXHC8tG~wr+<0qd6*Y`TF zZChAd?m<;-?QJT=MPv16MnG7lGGOMUWqM9F$onJeP@TLmk3|KMSk?O5Et>A)gDLAL zT+`AvO|Y}|ZEV%e79we}chYfMRpzbZIf_=oL69w)H}_B26JE=d@0zGF7gT>H2sHKX zHHNpEI&ra?Ut2+_JuULnTnxl4J@<>m@YZmYTP^P#uR3Rg7B#J%S~H=X_7*Pflqq|m z0d=St{S2@E+x!Dz{e42KhE?TddW+}M`)JqCgUv) zEvnW1^AQlWjC8J4lqYRdc@o>>?oW1Fw%vs=ACLATV?wq}Ba_RR(%5K4WOo2+C4B0O5k$784G-rWD_2{~i?`uxC(vOV8v+27yA(+@jgp1$n7 zBNX#niQYuhSxVU!o(;a#*QHJ^Jk7=@E-z8UKfTE=X5Z_HE-&lX!0Ok(G%d=j)lkaU zZ|+S5R?JD6&|=;$eo9?5(eJOd*UMTjf20M~dNaRcKYz@m00`GBod~U%JgEB0_axhE zSopfu9fWP(FT!n%WFz4$SFY%%F+xMa!3LqR+TQk!2E`4HF>K&Ygsgy+G*8WQ)C!iE(7IGbS?qVdtsgZ;Z&D%rB1G{e*r`$K+)Tin%vk2_3Lt%vSg` z!f(T3V^op4kQmeO5X4lh<9d5GA7!@bXWMOVvMIOj9WcI@ z$7C%%2zmBu{FKQM&M1{lEBj|FY>s|q^x^=uUl6@NCuM{lp(hC3rw8ii9io@vcG764 zaFg@v&FSa)(ZB0*av^qXk#(qL_Zy{#zgF2+sK8dpvNP*t9z6E`Y7mxH4DD*6neBB>FRU+WY%*F^YBCY{2%@5KAu*}^$xYBHRn z!M1`hR4<#1`NQLV5LWjBOdH|5{HFx7IYYkk^jhcl4=vw!W@6prdRhlOcPKiV4b_Xi z9PCvNKu(vB(TLC7QfE_yNDZ16ao+FM!*4#`m3*o@9ltqwKxOT4gAZNbEqeDX#rh$4 zRrJEPbWA+x9si-v=c;E=A-gcYeEbJHhjz1($;^(u@m$sFbz7BdXr@n}P_H(Wh?BSG z`dc#sPE%? z`O>Cy`p)cYKVs*jH_!j`og4QJPyNMqPPpGPa?@Fxu4OcBP8y+4ksr%Tq)nfgN_>@* z8z3y64lJjXu_=O{yYqA(CHsUf>Bz?GL7H!#d&fXu~CU2omGv_gF>Xdam{qae< ziX;d{2aC>GWh)QW<4yJvQ$wnDhlcPLg!bH&*52Q{baCLt(HqZ7wYmBR(CS@Iki?zB zwCNDXMfYAc5cZCXMD?q>d0G9b77!vonu}tCFAnsl+5no#E>FX)tWAZu$ucs9vRVTO z#cMTVW#!g5`dQ&!MOOs=i#>n6)%KXuRWzOJUfd~CzF)ZxKW&P{#c&~+pW&y}9M}Uw z{f9|0e=Rv1^Y$uo10fpPq|~7^bP+g#Zlb@k$S?2P(_Z~oKKnb5zCC(j-rU34ev}5a zs@<<=(<07(ATjM*5awLqCJ{*tFSm96WX852zw+6C^Qf*Owa>>a58vc= z-4JcWW>7!DeuI!~sH_LomfgtP3=qbh8A= zT#{!~B~J1}=N0troFa2;l;*Q3XCX=+2*(=O3L*Em#Gh(?r1Q<0PyE#Qt?LhJ8@F&I z51NJThOnv9mgEs3fsj*~)V%b`rTyKAsq8lLtUkS;q9!zKwW{^e*^KeDM*28e&5n|z zN0uC5H_4B;PfhOV{QBXxE3NP|>v8?w)}{rLw=$wbHyUzEXRWdvAY2$#n!N3h zObdk7_-Q&YL>kP3Q;&*?H}+1vcWF@F+(?B!JxykB>@V}-*~qOok_Wx~k%vu{IFD7Y zQ!iQ(!&7QC^y-`9X?hY{D);IA;MLGJ=^Ml^Kr?&0xyz!!S529CzJ^&8)4K18S(@P(Q=vA<8QvXa`Q#{gmYX$DY+O#Rt8E3p;TuDTKk zLaE%az4D`n{-pDxssAz}Q)PQ6*zey)g&Y)dvt?5C6H3IzC)lBUjRb^K&grt9>h8{Z zyLResVsM{h7Fn}r1)IuUxZg$QbYiR=`2KWa#lY-&kuI4^6&Y)5UMgPBm_E?dK+aZr zZHwP$rDsuP-@kA%-HkDo)p(yJ_^Bq=okaqnAhNlsC&@o>%L|iLtZhtP3nX>DlT8Os zP5LnVxyU)@qWXt$)7D9>i+pffMA@$7Uiv2SOCZd8&}QrgdnNEo%t^%BjdfEW+VwxL zOtADf#)V#0&dJzRh^yR(POE@WCRWItIT?(k73I!FSxl2rP&NVrVUspZ&I6%YaTS^e zp1*j>j=&#y{-sND#%}SM{!D1gbhhZI`#fhhUZhfkeGzKJMM6~DiYyy80-Gs(1ffjl zQNJMSrjOFUxH~Ix>$|-x@HS)HWCo2Vtm{REZny4U|M)W}px&$V4_ta-`-{K*&8@Th zzcK%XeHRCIY;JolMbD&wC#=J4)1j>{0@e(K^4?5w$uv z4GVE6hvz2#baMTK@XpM)E!y(>=C(4a&}M@T1eZgkT>7WV1^=b{;Hn!z;b}Fif1>~ zK9jS?O+?xJd~*1j(;!+{T+|!{Sw6zG=@7@oxE*Bp1{XrtNo|{pva_1JtSPO0a+tlx zL&t5;zR)~D@%9<21WcMik+_VdS{KMwO^e}Y6I%JowCn-VH=u%Np>3`*8VNe7AW+-T zTwEE+#j1Do`8IVLgnq50N=0T7d)6v#TbWHa-VrR}8sGMu2R%9v8al+;*3f#@prSjc zW2qW2?@N81Yz}VZ@1g;rFWT;9-6|}f17X;701+?}M;#$tF7o|jnF_P-1mi|26Q#ZU z%r)2CF!vifsze=aNFS6+&x+X;iOcTdJv&w|i_mXF1U>!OxEwvtPkj>+coxl%oLy*~ zG+Y$v$BQG|LJPj~*8=?=min=_i%uXcpT%Mdob!Izqo#Dzz9B5VajE~6m!hhRrWXF) zP^6dlwAyv$kZP?)=+{lq)3=S?JuW_D;OU)fPhk02)@cf#v>;?3&&j zwUZcsW~6S>mJe^sPx9>O{N!*uyX>KpTMEM^(9k4qLeYIL0ffDq_)b9@#Sb;cfru=r^X?p0WT*aWAqcBF5Gd|5CFMI>dFaeA$g~vw3eo z&s^?3imO3`FU!UL>|+4Qfy&zqZ92r|H09MU5bAjuIoU)6#6}32*r}2&^rp%M!d}Q4 zTQivjjJu`7L>{uo<@xR3pMPtlKhkC-4Vs0<8_WV~O2kFH<1m3h>I}3i z&*JTqkDM)~{vT%{vOL_{p$-ljy9*PZ{q(v9?xGX1gr)`k7k?z_ubYO?#fU$m2PU_j z=`&Lx45e3Ze3IK@7;6DS>{>N>lc{XZbjL{?|DSkYZhl-m_q9V82maNt-G%SpmN7le znV#f?UgRI{^O$&Pp-NmW5E~*D8U7Xt8dFvG85N<;ICEmt9{?fzJfY_7M-|fJ>H`k1 zSGZ@?cgL>2;*9!yy89itZ`%`oAKpBnPI>B0rB5WMlE;)rNl)>tdX+)-hj&{v|I*mI z2j%Zg!}9Mya$h$~c~W_I-v7A5!Y=!%uAkza52>$?Cri}#52!znsqfsaetKNJFE!ld8KpkepF}HgrEfseW%p zz2`>tH#>utB%i+WTl%#I)bEykoJ;&4yq10q@NH1fgp?fV^6QkksppuYT zJlkgVvso2mOsW4fs_1f9{eeRK><;z!V)gHy(kI%dBxOL|YCNOf_k?=ZG4-yqY6rkm z>bnLZG65Hks`or*eSe@!*^OPAjw@boRi7PDafLy1zj|enz)vY`f_y~%Cep+1w!5A0 zoqoT&l1=Irk%h@F9}cVkdv~%$ef6YzjTuD)Bw<{A+}(X%8~KEK59yR0zw*;#NtVBw PyKvw9zC1mD^XLBoaxox1 diff --git a/get_specific_logs.ps1 b/get_specific_logs.ps1 deleted file mode 100644 index 6a4d0c7..0000000 --- a/get_specific_logs.ps1 +++ /dev/null @@ -1,34 +0,0 @@ -$targetTs = "2026-05-20 02:20:00" -$kws = @( - 'print-retry-compensation', - 'print_retry_compensation\.js', - 'retryFailed', - '触发补打', - '任务执行完成', - '/__schedule\?path=D:\\wms\\app\\schedule\\print_retry_compensation\.js' -) - -$results = New-Object System.Collections.Generic.List[string] - -Get-ChildItem logs/wms/wms-web.log* | ForEach-Object { - $fileName = $_.Name - $fs = New-Object System.IO.FileStream($_.FullName, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::ReadWrite) - $reader = New-Object System.IO.StreamReader($fs) - while($null -ne ($line = $reader.ReadLine())){ - if($line -match '^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})'){ - $ts = $matches[1] - if($ts -ge $targetTs){ - foreach($k in $kws){ - if($line -match $k){ - $results.Add("$($fileName): $($line)") - break - } - } - } - } - } - $reader.Close() - $fs.Dispose() -} - -$results | ForEach-Object { Write-Output $_ } diff --git a/lint_result.txt b/lint_result.txt deleted file mode 100644 index 2301bc9a7f37bf323dee53b7f774743c35e750fe..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 24378 zcmds~U)TbrY~AeuZIi}MkfL^sI7NY0g-YvY#nvUHY*{V(C;Efi zzRw(vW_EX0TyiOL6%Zts%e}mF&Y5$c{oj9o>3-pU=X&niow>35!mYbC_t?LC?!7y8 z=kCgdV~%u0*w@oBJvVfhdOgzqBR6s%b^L+0_ zwdQ`*XR|B4&^cG`t*&-hy6Pj3lskO7y&`u9!=r_ud^5Sj^8)%;y7qy4r_U4J?S;O% z>qy5AMX5Fa3k+eDvtepF-bG-8$Kn0VeeU)q60xU|z~en}61pF0TzmTc-jDUzbM|a9 zKF;sy^;GAt>yvG$G4e<8tM9&bFWnFBx%)=%@AbPUS{eV5hEvh;T<08W|4{Fbo{k^1 zr{~_d529qx|Nqfnx2HWw9!InP!VR?N{C4lapFh$ucaN+ny?a7Y9?`CQ;>W~&u7zo& zyD&FS{GDI;F@WCo{L#I3&xGbc|9&A_ar{u%?77c`6&V?7tEcZ9{ma;Teij`1a~|pF zBlnX=aq71Q$rT2-=gc;ubUqfPiqW2XzJ{3-xY%c^*px$_?bI8WK?KVZ(x;f42VWSK9uy z_6%LrNS_J!vDcupVSJ~n-^h}gUskV~0^+S1sENHZo%%+1F%JO^d*N+ew3~0FA;OW< z(MLKA(5AUWC6mMq5st#76H10ez&## zN@;}!`}>UeXGgy-)Z2<7u)f{bzlL^0Xt%w-=>DvXh&M%LW=_?35q)~qi0`Sm4o!Dzxj&yJ zzK>XptVKXu=RdA?-ann#)}4vHs_On#;zO@*_?&^w^tL&Jaii=&l)!Y0yyEnXN|4h< zBM+A6R2Z6MINBk{%f*AKliBXfFz9S(AA&vrtyzS6@9>9;T`lTP@{;5&$p{mvTuZCZ zV-YOBS+?TQmf_ca%?S$-<$hj4ddo9f-G{>v;mg>t5V=n0FNx9IKUt*I0-#%;Y~ z-n&fk<=~iKnvrC9c;)LAVf&f)cZQ{kMa;?+rK+!MFt0vn=3aT9vU}Bv@+>xA@lvR* z>J%gxeQTAOCm9Lu>v+Z#*2Jui%Z}xR8^|sZHC{(H52n}*U^^eh|)fp_t zhSyX(`b1|D_^LY8IVDMbB{>MfNl>UCCk-uLs2tl_DbK zf{Q93x(MvhvPivf)V?Td9s>D~6Gfv%x^WM3qPe`$!=xKyd77acc^_yo@H6nla~!Hs z+l87%`bAr@Kgo(*O6ObMuSmfS>8GC?1(CftYY)7fStmoBpJ@k2l(rD@mutsQbiJP! zm8c}6-O9QR-yqG@q_*HLDML16=A~?_sk{gOui9@=?kTA1JBv6kBlAA6v3~(=jE{hwPNQqCNT%wY*HWR|VW8{K^-v#| z%%>^g#6}{oheAaDEy`*-n~QYLcOL~03I39s&ihAIDtFzgFp?;iWwdZw7>}4VDMFx>P%OYCF5vxYdIA$7y%%&Mf&Z0(( zPB-li=c@kLp=RX1?(@3# zUCj0`qh3jlr!L-TiaM>y_uVpRZKyZ0*@&j7S3zs*8+urBZ9X412g_H?5OkT=7VSSY zT7!B+uZKtLt*qzpTJ~;Ly>NK-b-JxDdtZ*}Urs!>=-FUr@3$`(K5tI^-8M69`8wE8 z=d%#q)eDB2%x-mttyWge=gIkH&n2sunnzUEW4{-bc8j9Ow&PLaS+;pu?$0_$xLe-8 z9QhcD=#E&2&VTX@)!9_c9N=Y;;i*!+uX+t$@lc)d)}ylAuHLE#Z6n5iilos5H*rB+A*E$kcq6zo?h~<#UnKWVG1*LGSlSF%KPt z`RbG*rAB2}E+Q>QHQ^c-Z#D0(A=h!B7ZJTl=(Ij6!$l0bNPGV81~izF zs?C?dYePyWaSrL~cx|{WO9rx{3^t`;IVQOeUK2Huo$NlZ4QcmyZMc}%xoUWqcx@gq z>s4~Ir76;7%xgp1Jsobio=*J5F3;=D2V<`dX%~5IKKSEobkKCREJKI0Y6>0R{dsLj zyT@z8ML%g9&A1F+(_cUqBk$cdmCB+HZvSLgE@uCQ{mjH{_+-uE1;#`okJi0kPWiShA6iSp4`Xn)HTm8srW ztWP%OZPNAAK8tBOlFw=VVH`u1qYmBiBz9g@Ct*a^1YJ%REZ;@vOQ_@T`}#gzZAF=& zD`7iZ->a@M>ATgQ z^6HjPw>^itXY2_ITCjZdKvzO*q(@Ji!*M29&JM}HEXlr&V|yZl)3`CzXsb9_e}VL- zYaBw4(=`2L-BPI)N$U+}5yBnmdyO@-=A$q7nuJb7y0-Fs<+&kMzE)@CL!t*guJq*6 z4}^A1yW8umlG)o;XvTGK=~tr}vBj&oGi%Klc@x>YUoQYX6`xRLGmv>iml*wIBmJ97 z(3<`UPa<3Mn$L6i zct0yHrunFOFR(~WA_IJrL(N8L$y2|=DjMt8htfCRW1)8tJA!wI?`?W@O1n0uVinU4^zjB-pHYCHfxm9%HvFbO8}{ zTBN+22%B*)m963|c#+VInrNI8JoU}i8>~qS!%1Y|D{Vm~)>G8+lDE?PpyTZsS^z_G?=9-CYTjyu8PuOQPc;*|=lR*o` zo};mTg;kg7>JF2r^h&`S14~>FU-YL}fd&1Q>#Cj=3nQLR7t7t$(FJ|g6)b3mu3(Al z=i153B6wu+a{GC-2rO3L?*H7XZ3ERocG0m6%`Mq?2`3Kl4 za=Q2yXVP>%J;Rj$&=GM~j`dV!o;6Z_RuoS=4HkeW$Q93tH6^+Nifd%K)1~eVJ+Vmk rGMX~`QZc=XA)PkB9>1&V*jBoTYFZ)CvDqvOJha@M7;kGM@h~b diff --git a/query_db.js b/query_db.js deleted file mode 100644 index f1d9912..0000000 --- a/query_db.js +++ /dev/null @@ -1,39 +0,0 @@ -const mysql = require('mysql2/promise'); -const config = require('./database/config.js').development; - -async function run() { - const connection = await mysql.createConnection({ - host: config.host, - port: config.port, - user: config.username, - password: config.password, - database: config.database, - }); - - try { - // 1) CONNECTION - const [ connRows ] = await connection.execute('SELECT DATABASE() AS db, @@hostname AS hostname, @@port AS port'); - console.log(`CONNECTION=${JSON.stringify(connRows[0])}`); - - // 2) META - const [ metaRows ] = await connection.execute("SELECT name FROM SequelizeMeta WHERE name='20260525113000-add-request-platform-code-to-wms-print-platform.js'"); - console.log(`META=${JSON.stringify(metaRows[0] || null)}`); - - // 3) COLUMNS - const [ columnRows ] = await connection.execute("SHOW COLUMNS FROM wms_print_platform LIKE 'request_platform_code'"); - console.log(`COLUMNS=${JSON.stringify(columnRows[0] || null)}`); - - // 4) CREATE_LINE - const [ createRows ] = await connection.execute('SHOW CREATE TABLE wms_print_platform'); - const createTableStmt = createRows[0]['Create Table']; - const createLine = createTableStmt.split('\n').find(line => line.includes('request_platform_code')) || null; - console.log(`CREATE_LINE=${createLine ? createLine.trim() : null}`); - - } catch (err) { - console.error(err); - } finally { - await connection.end(); - } -} - -run(); diff --git a/raw_redis.json b/raw_redis.json deleted file mode 100644 index e61205be447ce64a2296103ee81a32a70bc5a88b..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 111412 zcmds=Ym6S(dEbYLjRtP3rYTU_l9H@eQmh-r+w$tBlthV=?T{;m_nS84a!FCzQnvB#)mNK2Il8$@1i5 z$(jClhLTOmP%<<+vEw(+{qKWE{`vKZCnx^iJM&L(+J48-rsU^`{_)W}hAyeUe`@7W za&NLKS(%I^Ym@u>zjYxQPR5hTlr;-`GVx>_D_Ih zM*TkTuv7gR@4v?}^=`b@%Kod!yYs4=1{ab;>icQ@W9t8t>bK7-95d?mc(S=Psr?Re?^wH>_hKfhjd-L7X>hoCcz4g1v6Ui$c zy!l?^3Oi3St$uUj=IerxpZb;LaU~(^lGRE=Rwiqb_3ATUf3W|#{C%tAJf?7@@f}sq zBu{6f1R?a|XTg13{fv3KP<&&GXUA^7-&*x_>y$3=yy3rpO1IqjXTE|En2><-@eXH)faCPC;*=?75Q;S2h^M5q)i-+&+bMbz~KPY-%B}&$n zJkX@=WHrgNsS+o7>k1@K5N3HQl84l-N;dTW3{LVuh#gN`kJa8D_tL^uD`&ap=KGki9j2b)h$Y*XbR-AM9SX?2X>7m)o&iS;=xs6^POijw@QzG{9f3 zR56858~m1Ql@+JCBkyd~4Z^s{d;QHgZ=?|(3jaU_55K>A*@fBpKc0B6aMI8M3*nDI z{G41p08WxM5WTO9jA*|-Ju~;I*>5gP9YOctB@$hpZ^l@5xBivu9?uLy{oE_m)7RI( zqL?)w2}*9xyRKFr>y)hcqy>cexC1VT z=N~jo^Ke67R@XMjLz8v*^v+-tzViRU*ozS*edz02Rf};~R&2@hb1~dr>`=AhkE=Rr z7>#r#mY;T2Q$Sc$Yb>j%WHaw(swu0Kc97HR3ecV^(B>Zq-L>ry9yS#RcEw3U z3*tbxm2lg67bl4Yi)*lUu1NkMA9$OMeJ@k&VT?^Jvlq6l0HNvjj47^$)%>f+6j^+B zy?>-1t5TQ9`yvo(>gHb~FK>U+`|--Rp1J$v>$}K4u8jZ9C#3%B)4%-dx*`gYgjW0O z*$kTw5>*uQJ8d(>UI;g}42Aon-N_cOeah0Oeyj?@O^NPzg=MvMVjW}2M2n0svhA45 zhJkQQb!xJ`q>EDzKf5^eZ)Ur%Mu4bpMx>t}FGPOg(*l=7nck7l1A)+VEP0P+;s`Qu zo*-`(s#t`JQ{Xe)Ys&xBjUqr(rT=HBup*L&p>+rlHpRo${Ro>rPF!bA>mS&R4sK39 zJ%4TbYx{1U-|Us`tOaW_+W=8$FW06L?3DO+{KwM_Iy8GnKPK*&;)QI+2#~i{Vk$PEYR#gmzqRV)FX2R0fa^FW$b_p5gm|tx-`|Q`&fC{M;w}o*Ep! zxkpz{-L$1oPtMtNAOni!Wqp4g>Z@J6WEO^gOI#L|*GuWCyCP^%EY%(#(U;arXhKd@ zKLV=~MW-XMGLAw+305t^@z%+5fa} zc>cB7|N4B@UhR>-jzY;n$eK-o;*1S?3HSVx7M`^|uBJgB^;#ykY!%5B2wib*_p*gt zamr$2UwhWPD_0;a(;rt==U*-S!Hr*^7@j})g`>wgWAWB_bqTYj3mkX^nG39P*1}iY zDX#0-vhG<1)*3rUstV}I#0I7L(H_Qv=<{Z)TcnhIOwbM)T{A;BIImcJwC2i z+!I=mgRE5itjVA9sm7X*&rMf{^*EfYJ2-9(F-s0Q(SYGL=Q{`!wmo_cnW}Vur z&CB*HJy~8#m4^twIKHpWOM7b0Rq3fyBmH+1R%#YaRLt!YVTiqMr{;hE@mC`tJ6VSsw|e^!fR?Gklz=#j5iBE7YHuI-Nw* zAe8faZPj?}h+3)}bV}`r+8>jEu-IExt?|_1qRm0j%q4MLw5fn)jXBYjkD)>6+IoN| z)~70m_~q zyl`mhmyUjUC*21SP4DS;BSl!;1G4P-X=KaLfjHY2>6TlIuoFfSVQ=Wm8N287PB9RM z@}hfLL(V`5g|c*X^*4-7BfeXsKA?2y^SP{AZ))tuZ++I@vjZNsJo&hm)za>|sG!p| zJ33p23UQJa-bF>yuxQe2%tzQDEbBQAM$)vDfzY4(+g45X7m?59dnMsf_HZ)V`_04u zV(0SY&la|fzHRkWL9;YvP0JYwS13s%ml8VodT{0ax90n)AoSY{&W1D9LKQ2pnN7^rzJ+8hL-L~?0eX8RW1TzbI49<+@m;htRA3PS<*UXLOOSmYfzTs|$e8 zx6`#dUDRA;u7(b)&euQ~5{Kuz&f22heRAfrb62YAVv!z#ri<<*=UFu!j71HxrXa*? z*_(OcVpz_$KiQpZSG!{#sTBWJi=9D87ho_miRs-j?wAOKc0D04TM{uhyF11$S76C* z9*^s}2?eMLG_yevgh*x=T~oHD&@-%7Hw0mJ<3gT;ZPyM#(PY$RXu-5ty;(7_x_Y*# zOHR^t<(x*f92SIrZER=0C|d;vhkX}7oJQKTs5@Vz>%e-ps9Rp@`JyVDJJ9W$W zjbHoAgKv&~=+dJnH$D4%2jyf!k=4^Cb=1(KT0~}|F%XKy)mqw>-xO{#E#*HI z2*UJSP!Tt~=*xqqNsnn$fh`R&(?*gRfw1eDG2*uPnK6lf>Yu!*H^&3LVyjIuGbU7! z&Q@K^O4T5n8G*29X6%5vdugZFj%T|t)iR^7tO$f=_Je0{W_E|Uow&Nm#+g&QK({#b z*2=}9^P@{;q5@3m9+!%^U$SMwR$0Z`t9W z%{x%FofTEL@1XKeR0t(vZG+B=s{3dV7RP!%KH{M`bId&&MX_T3_kEmvVN`Y~fvIfA zhVIMQT@PI^Z=)U!CR1l|>7-4Muv3#oCnoDfTp+Bkm4cqRhq&I5(M#bbsJh6FLh~Z< zR6Tpa%>mFQZbl$9D*|CtevE^S!;ywwMrIme0bHgs@zBaOH6RZk=y3+sM7s-%lOdOK8{zw2Eo({o^H zgn1u1I4RQ-20}xXJSWYpn%wirXS-p4eO?o5VhVFuZE$noG7hC$}8en|~Kt zP4=~=tL;0o$qPEH4#+q_=$ne6!V?xz(Ai@$nNG^;e$FtWCLh?i=(kc?-<`D-AS}1W zgPE|vr|NB(O!CC!NZ+1bzW3jM>SG7~*TEmng<1<}SLBJHTlQpno!p4`aOFkv?Ckxh zx>Z1*%MygTo7;3uQD!g1oBFd4k-c<1)nzYi-bsY$jx5UM*c}_T%}bjW^)e6;YEFhn z7F$*JaX{^b+pEr~SCRRwjVPzG8 zPUv>qC7YkUsay76+ddesf@Zq%J^@V`{E$D-^z${Orv*ayIoz0@7N?ElVnNMW@U67? zt9h#@QrhowfuPx_k*=RmDDGBa-Q@xy+TX=Yu5`ITU*+r!2=jeQ(Neo=UA#wL*JVvj z&s8gP$Bt>w4whzTtZkYUR}Dfc2GZdIVV848oS~)G6W-whq01f%N1KiO)7&fL9LTEe zZ=ou#pC9hU&x!eY2f`*TF6gDd8W#r%?>;>bKJGyqBp34>1eMMUT)DVS1uFgZqoMqi zSW#sCR5IG{AjwW|5c;zlQ){i0y~Ss4AcQWugOsfY8+>-xfei<7lGU4f`o`WV*#s@t z{`2EMI0%|Y=3f8IQkfg0#sMZn1(%!&HHf*Xd)1e+dNKE0AEEDE^HH;@4>LDL&JfoH z)R9>>=5}*gbGVJkGPt!#Rpvq`SE@{{7+Mj9*X1+_Ij{%M2OB0OEHdBSo zSna$PgC_5tADO%TbM5EW)TcBj{K>HWTm_+tK3%?8V(2}+nOz@xr@hlW?ebF7f_*?xsE8)ToD_|e^E|ry z(S?2z@pJYyr1k|3b>!jVr0s1@rrms%T6j6GurwPv*|b0_>)d!D-BJ*WR)$SkY*9Na z$YS(|?7?LdA3X)1L}hcM&@4R7%fZZ9u;qoj4c%utK^T5x&c>OKJo}>)vU9Ksy}~=E z(lrHD6JFhZ_86;?mog9z7oGrQ>JO?@?PjWnepMBEh02$)6M5MJVHdWI2$|WX>ig+H zn2tUEcK$PmUq5NAS{0gAl`*$`fvH+1Xg@#p%!k?MnesB`mM;+U9xiK!%n=E8FKxD@ zfv~O3@k~xJtH>_BBLAPY)_E@q!r`0yEM+1jW>PU`cNa)bswu*%yhd{qX!!eCP&uK#Bydvsh| z)O*;{&$!%?kemN1xP#(*s1GZyLgwG1;MnJ75Yt-N;Cywn$yfSz1DzK&bsHc9qKAg1hHCB9d!hdG*s^7B^xD6B1sr4oM{3_B zC9=(y1~yi&^~#=KGwqtP@s=QLkB`#vrGsC;I|RZk9|xD+fu?GlZBrpGLJK*;4nmRq zood7Cuc|77&zfiLRXed*+UA3BA~~+K;%w9=8gyfo^5U_#U|e1J{n>Awd*VfKef9d{ z5I2DR+spT?+Wg~RoBG%1i)+ML+EuspWj!aMRM{l9O@}!7B8v;HgFdCK(fWQKz`0=Z zu%#wvB4f}nR?gVpwqD6vSr5hEKl$YRwNv+9xVrG#?BWopu8iMzad!TXC%W-PA$|x{ z#ruw!SI~4I=8vgUg~a@>cprpS63)lZkALLHU|O1+E~pa-PpQvi z8_-puKwMNxa+YKkS9_DX*1dXfy)xNb)pL2B0{|N;^C{#cT zN4)yrj|toAMuX7yT4^n07YG~h;$})DAA2wJ5;{OBp+#&3mdRmVw=?m5d~EOIB@ux1 z$C~quSH_oJ_?ZK1&)#ub`q8&9+_4V~W{TvzfT~_t&#<>?}D8ZAl#__<$LF> z4}CAm8d(;1E|TfQL?7Sk{ne-b>c*2N-rUKABUF2R*PWM|pS_8jO9z+Rve|Tqn}?tx z6_#yEPg-Vfux$Jbg#LNj!Ae`)X$c}-v?+E65;pDO%jSkps5U##4WCO%;y_iLciOaw z%UZ%cslK@w-@?ot2$!y9<0L!?tHecS%9~jaG7DymVl3OCspQ6$oAnK98%EZuP_FqZ znu*v#r6 zATk$IhY6Q5P6nhuu;$D-r>T~v7znf8bLq$%vIfF*>~7coh`8c=vi3=+iQXH(IkKBc z%(up69uovhDNnX@WU$#Br52+pLYD03{?f}}HYiKUq)^0Jap!^Q!h=ezW9d=Z|-EqhkC1@b|A_6y6$TzHVv{} zBoJoz{Q6}re46aBc$;EjneeV$0{JSJ)$dK?N+|DY>_A7+dvqTU;p*N|2vbu zX-9Sz)|q4m3-lJd{*2=7T&w%aH4Ts}@&q5RMXo?tbjMng^G8LUa68&0o`#3%nH3P4 z8nR2?%uKqbbe@N?+o`(dq@e{hR{z{*IVb%mM$(hRW^SOkhUv?SO`5 zwj+d>aXUmo5f)K4A7f~m`0M6^&~Nvf+EnD%taLOfH(8>cS{p*54L?V(jK}OC0!Q~A zT%?;0Ik!yt&x?T2&q?>0k@%UiY#gTjRHFuvp1t@F1$XS$MA`rT<= z?24B*Er@(V;vR{4+`MdS%Cm@<(if86RyJ}4VR7tKq>*}ey3UKfzCZSqY*)OrX<=vL zE(>LArQBA4yq{MQw${q7BUrlAlE=I9TWDBRNiXB1*2j2G%5JUpEv!w8Y@S<|<3g!4 zC#%c~?CRh)6cEPmYsPnk#84&2 ziC?C`{b&rpsK-{Dn*1?{Q1fhGE4|Jhc2i@g#kDNEHLa%%+r7Rc9*HJ*&X01-g zh*&Z9RPs6Nk^J5Wgy~&T_a@&_TV*d!J^bwA(5tg=kL!u=&Hd;_rcmH$6)zayG5nbTtUG_fcoLYI1<(s>&;qD8yxLa1}gF-q#}1E_8|G zs?GvH$dh-)Ri<~D-wxMR5awf!JXg6{iLKCN8g1$-c$%%Zz*S9`IIdDXJKV2%T(aiI ziuN{PA*c;VC6j*ZdR1>?deNU_X8mh*e*q2iKBEg6WR6~**ndU{gy}3OFM}sfyngDp z_uAXu;;Rbz*aRfa?@YDn5O;1v`WQ`4DHdfOCbksx$gZD@nuE{~sdaUXZ7xdRUvJ-P zw)+o;cD7R6)QFi?2cg^#VaJ-qai&;WtgYNz=KYa7$>4)!m|IOL@=4~4o*t*}2ZKH#ssZm$j z3?IX15ajGMk+$5&*6zM#5aOK%6B98TO7!PDEd;`>1$RkYZ|c<1&s;J&R@1jU2#$7V z6Kr}^pY;c!UD?%{R##b;pm+CMq#^>suzrhhGkd#(;VI`)>)hM{g2|h<6}tHAaZS|X zY^sD*>xGL&^Cn$)LIu5?d)Dy>2(#7cI1Ry_va3$0mA1t1q7YPH*|%%~Mwwo*%6m z^@_yfC#%)-o3S5;8pSml(FG#VbjL5-?F)~3cP3jaRVIrhOiP!hq0WpYD;|u5p-D^z zXp1J+41~VhK=XB&yHC!1cJ4}gb2hpA@?^Ps2kvAaQ5)I5x#LUcdQ%S`d~uIYW8L)W zUfwiq$mi30Ed*h@BjcC0@ZR!Pb&Kp%mE_Hyr5jOL^%+2Dp5|*co_?n{GJ4C(-qa^g zyfuFEgk9CG8i|XwfNI@F9GV(X0*m3Vj+A>T|D6hYjsV$if{UESh}X<47wvuv+8L^q z>9_`74#o=zPlYz{v}oEDgi^)yYi4+E&;(DJ=hr*YK^W4{&s*CpPj$aVqEnx3O>;5N zK`?cZ3kVm58X=l#Vn-0>C+gN(y%v8DqpCO0T33)`|B5Xu2-7DcTvcTJQQkB?ekZ8-L_RUKqN2RzQ*#9T{Fy~6lt2b>UnEVO}%C&xmYI_C`drbc&gx@|{W*X-j8Qd9I4Bm1O+O3U_^!w*RmFm4l5Z0@W#&ePicX>`C5+^6?U7j<|Nv)fbt-;Hx`DSrU z1d=Yjr|cbuMxl59fbgW!&%B0)XPhy1SE>iHWyEcFL0H#!8s0WL^9QDOdSx~}s+}%K zb5KiOI2W6_!H=DT*cUX_%}>os5c<39qNmx;MND>5>?uLh+~lTBg}NP2@d_q_6^{CI zlV*5GR>fRd`P6rse;~|GZl*I7T{~E(Y%G<78^^D0Z-<}o5gWy7 zEe<_6`Ig$--W$K`^p0NrjR@um>vyNY6FRXk6rgg!_FW&J-FdI(N!m)BR#ughmPHl< zgzcsLKA$P>f4SLxd|AzebBVPI)vxC=@^X2KRnMx z2b<4s7l$60JogE3z1CZ5TkSz*?@zO(6&*BGh>OAMPl|xB%86z( z9W66+Oa<#|f4xe-@X%OO5NV6Lxw9Kk{T>@kS=-{$N}DF|x4wO?y3ax+E%wei&Zx?i zwLddTN7dPg+Gu6=t_gdlYo+p8Q#B@m>Q4bdqk4B0!&gn2xM<9;sUXxI7TIYo>S21G zdqm>+3O=#8Ri|pup0*}xK&8EeODkojUY?(-Q;c4Q*ZOVVfw2DeAn+r9oN0^WAG}*L zDH|=ow3N7LI0&+=FTp<=DpafQ=VKmf7U`U*C?DFT@*%dwJ)Z2dtho!Jt{NHJ*hXfA zRGC=Qma(*aiNx9QMjoHt_vMsRTxRt0^dt9tbfs+CNM}W0sS;y!KL-Uup#YM_++}^w zT`e;T&5A&nt{T|fqiRJxGpsWxwm6^L<~f+nia-%=fx73T+zqU0K^?5S%%~Yok`thb zvG@Y}wx5(t08iOmtP`>!ZmIForUSf` zTU+b%GCZE%nQT|nGQZ-Lo2;#pI2sx*-L2ki3Id^2RM`wFlMdn0Qa&ELF#o-=r_ah+ z+G`6#tIPIzr)7Vvk7p2e!aRN1xkf1Fw-W6{(^*Q{7M@MLRMe$1Ej%^8Oxw1sjJl?H zgnxSXV9Z|EvwdFHuYA?7dTCme*QcSBudm!r1Xj#RnZ#nQPS>YF7{f`wzb=*xpALel zojD!*`C}#mK)6ZiL}I#AnfuU5$;A+3S92#DxmL z{oSBhc7ZLp%a*;-i#;dM+}$q4d^EHm!twh8KPRhA!DOvF2$7;{oRs+w&L5RcBAcF) zD~hmr`GxVtA?m##dT-9d2t7hi2e?lL)Xz1bTa{jw(M#bbXVaV0%q!!6)8}N!ZC=?( zqHb)M_SwW>dCRJ;D%7%jjC!U?sKCa@vh(O=UOV2&;Pm=8EuL{u6*%?ao&VU+?|iu~mmJPHlWvPj!Ij-hQscJ?PYY@AGo7t+>C~ zhPb89rU)@w{rD{WKI8q#NBfiS+mk0$rVcmw&^6tqEO%A(!nSlwIq3cUq0i@vKB$Ua zU05~wNBc$&$hIXAmES&@mFO<~6}}2|`cw(^X+woLS!=GJWh33OVG_J!U{ z-FOXz$dBftSl-2h{z_hCex>rtbyZm=P`8!W@?)l1i7kA{jcj|(r+8uc|9pbD8($c-%V1@-w5{Ja` z@s)lJ5kfL zB@cuX4QzIh+gIXGsP5@~^YrE)zdQ}D2PU${}F9V1{*7ZC|%8Wc`Ta> zadUGanU(NQ?oE?3dqkzwy!GBQWf!aS8tjkp%;1vMJn*=`7nFGewpviMr-Xz9`q{9>kU=nd{w>vyJ$rWPpQh#fp3ndVAAnMdXINC zoK5-z@dY5Ww~)JR339G!63@{vTVi_gAe4^0^yA58IEz_@a_z<{&l1Y1#f3 zD`|48_#<pf7koL%zxY|^I?ak*t_3F4IC74Q({ut6H3Iz zBUqq(H3Wn+&N;Dt>Q2piyK(AnPH>+)7Fn~W{+h~F*qkMEH!=1Ne1AH%dT8#7NSDl) zii~wN{}eB0%oS*AAZKg5w#DzQ(o?0fjbFH!?zfogX}q@*{L~HW&K7}C5ZT-`li)8+ zSFyG+6)cc2YgBI=hTJ9u9XRpm!|dlGXON5P9l}jpC$TQ_!CekzTaDZFP2!h8nDwB| z*bVkT;Fp+yh_xFVXFjn1f8Lx;8EkY5y^2r9WxY3XkD)?bjXrb^1%xt-LZ-Yy#imGF zQLbE+xilFCWg{REHfhu3JP(=`SCM(*#oxUSw(WK%Bkxj!oU@e7%Ae4zaDiy@r^hyR7ac5<1Q=f+5ZN{p}Tp3ST*MAD#?mDpP z*RolLaNBsyC3|MPADay#rH)-WdGzPi9ZqE}{#fXM!yYhVdGYvw&K2nP!i-0iiFxZnHWSmb-y4tnW|Ui^Neg2$zd| ze^_R{?3=peo+pqXeYej4^4==3Mi-I?w)FIuO^vu*F5aILZDbMp?T4VJ;~JNX=XuH9 zK)3eiah4tz4F^T)@!rU^(1HK?>wSJdP(QkMNjnJ3C##s|=Byres41OH-`53>?mA(` z)s>>kil!4D-O!@VTT<<+aY!vzBlK$|=;_DCZdP_{96fuinn!vEj_Iy z9Mv?5i?qY{f67TRc3iVb*Ph%4VK%SJ^K_6NJx{|tK6@^cUYhJWjk6xRdS*Ar$rJY< zp}qnZCNkN$^`&#YsRs|fxTlLfP44<0Xo~j;8^3T&xSnI@);IgtcHvhk}6hMQ(qqU&u6pqY#0sZEu**$G!a8-(tOKI6-XjQrPJZ z>6S~Hma?t=NcWLsr`mTvcrKco{sxk1hJae}*W6p$9;g7QpSsrrB)qAgVZD>J<#UDlbE2QD`F5-*ma>-p| z`s@>&49ybT@kefpVXOrRv1`@jO{S|kiybF%{64Y1+_-q({MU{x4xJwb(;zp2>8Z^0 zL?)<;CV*{v#8v*V9#Vthv&hbbs;r+@aoK5SCTw~DAcT`=)dcgnibBq)4|uyt;XbXt zI`Qr+o>u>!?SBQn+m?i%hbzyi6PkL9=yS>W#nc3~- z$;WQ~lzy!t^|NIkmlOX7uccoDd|TA>AQdP2{5h}g#W|%YH~sF<=%3|po^8AO-kgdi zX4LPDE1Dcvf1nQEyH|a_PyKzc^ob5D$rw`i2A@{%dsaQ`gnHLGbxQvQ^;Lrq8Gr*P z)qBcKE*cHUxAti|sd&3X{p*N|APkzv)hmm{eNGyju*`{6* zIhgMA;kf$Uhmxn%|DIQ`aaz#;DVS6r5A~ndMn0w9L#mu-ZhrSvlI5@FF5EXiFHg_s F{|9}VN*MqE diff --git a/redis_output.txt b/redis_output.txt deleted file mode 100644 index e61205be447ce64a2296103ee81a32a70bc5a88b..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 111412 zcmds=Ym6S(dEbYLjRtP3rYTU_l9H@eQmh-r+w$tBlthV=?T{;m_nS84a!FCzQnvB#)mNK2Il8$@1i5 z$(jClhLTOmP%<<+vEw(+{qKWE{`vKZCnx^iJM&L(+J48-rsU^`{_)W}hAyeUe`@7W za&NLKS(%I^Ym@u>zjYxQPR5hTlr;-`GVx>_D_Ih zM*TkTuv7gR@4v?}^=`b@%Kod!yYs4=1{ab;>icQ@W9t8t>bK7-95d?mc(S=Psr?Re?^wH>_hKfhjd-L7X>hoCcz4g1v6Ui$c zy!l?^3Oi3St$uUj=IerxpZb;LaU~(^lGRE=Rwiqb_3ATUf3W|#{C%tAJf?7@@f}sq zBu{6f1R?a|XTg13{fv3KP<&&GXUA^7-&*x_>y$3=yy3rpO1IqjXTE|En2><-@eXH)faCPC;*=?75Q;S2h^M5q)i-+&+bMbz~KPY-%B}&$n zJkX@=WHrgNsS+o7>k1@K5N3HQl84l-N;dTW3{LVuh#gN`kJa8D_tL^uD`&ap=KGki9j2b)h$Y*XbR-AM9SX?2X>7m)o&iS;=xs6^POijw@QzG{9f3 zR56858~m1Ql@+JCBkyd~4Z^s{d;QHgZ=?|(3jaU_55K>A*@fBpKc0B6aMI8M3*nDI z{G41p08WxM5WTO9jA*|-Ju~;I*>5gP9YOctB@$hpZ^l@5xBivu9?uLy{oE_m)7RI( zqL?)w2}*9xyRKFr>y)hcqy>cexC1VT z=N~jo^Ke67R@XMjLz8v*^v+-tzViRU*ozS*edz02Rf};~R&2@hb1~dr>`=AhkE=Rr z7>#r#mY;T2Q$Sc$Yb>j%WHaw(swu0Kc97HR3ecV^(B>Zq-L>ry9yS#RcEw3U z3*tbxm2lg67bl4Yi)*lUu1NkMA9$OMeJ@k&VT?^Jvlq6l0HNvjj47^$)%>f+6j^+B zy?>-1t5TQ9`yvo(>gHb~FK>U+`|--Rp1J$v>$}K4u8jZ9C#3%B)4%-dx*`gYgjW0O z*$kTw5>*uQJ8d(>UI;g}42Aon-N_cOeah0Oeyj?@O^NPzg=MvMVjW}2M2n0svhA45 zhJkQQb!xJ`q>EDzKf5^eZ)Ur%Mu4bpMx>t}FGPOg(*l=7nck7l1A)+VEP0P+;s`Qu zo*-`(s#t`JQ{Xe)Ys&xBjUqr(rT=HBup*L&p>+rlHpRo${Ro>rPF!bA>mS&R4sK39 zJ%4TbYx{1U-|Us`tOaW_+W=8$FW06L?3DO+{KwM_Iy8GnKPK*&;)QI+2#~i{Vk$PEYR#gmzqRV)FX2R0fa^FW$b_p5gm|tx-`|Q`&fC{M;w}o*Ep! zxkpz{-L$1oPtMtNAOni!Wqp4g>Z@J6WEO^gOI#L|*GuWCyCP^%EY%(#(U;arXhKd@ zKLV=~MW-XMGLAw+305t^@z%+5fa} zc>cB7|N4B@UhR>-jzY;n$eK-o;*1S?3HSVx7M`^|uBJgB^;#ykY!%5B2wib*_p*gt zamr$2UwhWPD_0;a(;rt==U*-S!Hr*^7@j})g`>wgWAWB_bqTYj3mkX^nG39P*1}iY zDX#0-vhG<1)*3rUstV}I#0I7L(H_Qv=<{Z)TcnhIOwbM)T{A;BIImcJwC2i z+!I=mgRE5itjVA9sm7X*&rMf{^*EfYJ2-9(F-s0Q(SYGL=Q{`!wmo_cnW}Vur z&CB*HJy~8#m4^twIKHpWOM7b0Rq3fyBmH+1R%#YaRLt!YVTiqMr{;hE@mC`tJ6VSsw|e^!fR?Gklz=#j5iBE7YHuI-Nw* zAe8faZPj?}h+3)}bV}`r+8>jEu-IExt?|_1qRm0j%q4MLw5fn)jXBYjkD)>6+IoN| z)~70m_~q zyl`mhmyUjUC*21SP4DS;BSl!;1G4P-X=KaLfjHY2>6TlIuoFfSVQ=Wm8N287PB9RM z@}hfLL(V`5g|c*X^*4-7BfeXsKA?2y^SP{AZ))tuZ++I@vjZNsJo&hm)za>|sG!p| zJ33p23UQJa-bF>yuxQe2%tzQDEbBQAM$)vDfzY4(+g45X7m?59dnMsf_HZ)V`_04u zV(0SY&la|fzHRkWL9;YvP0JYwS13s%ml8VodT{0ax90n)AoSY{&W1D9LKQ2pnN7^rzJ+8hL-L~?0eX8RW1TzbI49<+@m;htRA3PS<*UXLOOSmYfzTs|$e8 zx6`#dUDRA;u7(b)&euQ~5{Kuz&f22heRAfrb62YAVv!z#ri<<*=UFu!j71HxrXa*? z*_(OcVpz_$KiQpZSG!{#sTBWJi=9D87ho_miRs-j?wAOKc0D04TM{uhyF11$S76C* z9*^s}2?eMLG_yevgh*x=T~oHD&@-%7Hw0mJ<3gT;ZPyM#(PY$RXu-5ty;(7_x_Y*# zOHR^t<(x*f92SIrZER=0C|d;vhkX}7oJQKTs5@Vz>%e-ps9Rp@`JyVDJJ9W$W zjbHoAgKv&~=+dJnH$D4%2jyf!k=4^Cb=1(KT0~}|F%XKy)mqw>-xO{#E#*HI z2*UJSP!Tt~=*xqqNsnn$fh`R&(?*gRfw1eDG2*uPnK6lf>Yu!*H^&3LVyjIuGbU7! z&Q@K^O4T5n8G*29X6%5vdugZFj%T|t)iR^7tO$f=_Je0{W_E|Uow&Nm#+g&QK({#b z*2=}9^P@{;q5@3m9+!%^U$SMwR$0Z`t9W z%{x%FofTEL@1XKeR0t(vZG+B=s{3dV7RP!%KH{M`bId&&MX_T3_kEmvVN`Y~fvIfA zhVIMQT@PI^Z=)U!CR1l|>7-4Muv3#oCnoDfTp+Bkm4cqRhq&I5(M#bbsJh6FLh~Z< zR6Tpa%>mFQZbl$9D*|CtevE^S!;ywwMrIme0bHgs@zBaOH6RZk=y3+sM7s-%lOdOK8{zw2Eo({o^H zgn1u1I4RQ-20}xXJSWYpn%wirXS-p4eO?o5VhVFuZE$noG7hC$}8en|~Kt zP4=~=tL;0o$qPEH4#+q_=$ne6!V?xz(Ai@$nNG^;e$FtWCLh?i=(kc?-<`D-AS}1W zgPE|vr|NB(O!CC!NZ+1bzW3jM>SG7~*TEmng<1<}SLBJHTlQpno!p4`aOFkv?Ckxh zx>Z1*%MygTo7;3uQD!g1oBFd4k-c<1)nzYi-bsY$jx5UM*c}_T%}bjW^)e6;YEFhn z7F$*JaX{^b+pEr~SCRRwjVPzG8 zPUv>qC7YkUsay76+ddesf@Zq%J^@V`{E$D-^z${Orv*ayIoz0@7N?ElVnNMW@U67? zt9h#@QrhowfuPx_k*=RmDDGBa-Q@xy+TX=Yu5`ITU*+r!2=jeQ(Neo=UA#wL*JVvj z&s8gP$Bt>w4whzTtZkYUR}Dfc2GZdIVV848oS~)G6W-whq01f%N1KiO)7&fL9LTEe zZ=ou#pC9hU&x!eY2f`*TF6gDd8W#r%?>;>bKJGyqBp34>1eMMUT)DVS1uFgZqoMqi zSW#sCR5IG{AjwW|5c;zlQ){i0y~Ss4AcQWugOsfY8+>-xfei<7lGU4f`o`WV*#s@t z{`2EMI0%|Y=3f8IQkfg0#sMZn1(%!&HHf*Xd)1e+dNKE0AEEDE^HH;@4>LDL&JfoH z)R9>>=5}*gbGVJkGPt!#Rpvq`SE@{{7+Mj9*X1+_Ij{%M2OB0OEHdBSo zSna$PgC_5tADO%TbM5EW)TcBj{K>HWTm_+tK3%?8V(2}+nOz@xr@hlW?ebF7f_*?xsE8)ToD_|e^E|ry z(S?2z@pJYyr1k|3b>!jVr0s1@rrms%T6j6GurwPv*|b0_>)d!D-BJ*WR)$SkY*9Na z$YS(|?7?LdA3X)1L}hcM&@4R7%fZZ9u;qoj4c%utK^T5x&c>OKJo}>)vU9Ksy}~=E z(lrHD6JFhZ_86;?mog9z7oGrQ>JO?@?PjWnepMBEh02$)6M5MJVHdWI2$|WX>ig+H zn2tUEcK$PmUq5NAS{0gAl`*$`fvH+1Xg@#p%!k?MnesB`mM;+U9xiK!%n=E8FKxD@ zfv~O3@k~xJtH>_BBLAPY)_E@q!r`0yEM+1jW>PU`cNa)bswu*%yhd{qX!!eCP&uK#Bydvsh| z)O*;{&$!%?kemN1xP#(*s1GZyLgwG1;MnJ75Yt-N;Cywn$yfSz1DzK&bsHc9qKAg1hHCB9d!hdG*s^7B^xD6B1sr4oM{3_B zC9=(y1~yi&^~#=KGwqtP@s=QLkB`#vrGsC;I|RZk9|xD+fu?GlZBrpGLJK*;4nmRq zood7Cuc|77&zfiLRXed*+UA3BA~~+K;%w9=8gyfo^5U_#U|e1J{n>Awd*VfKef9d{ z5I2DR+spT?+Wg~RoBG%1i)+ML+EuspWj!aMRM{l9O@}!7B8v;HgFdCK(fWQKz`0=Z zu%#wvB4f}nR?gVpwqD6vSr5hEKl$YRwNv+9xVrG#?BWopu8iMzad!TXC%W-PA$|x{ z#ruw!SI~4I=8vgUg~a@>cprpS63)lZkALLHU|O1+E~pa-PpQvi z8_-puKwMNxa+YKkS9_DX*1dXfy)xNb)pL2B0{|N;^C{#cT zN4)yrj|toAMuX7yT4^n07YG~h;$})DAA2wJ5;{OBp+#&3mdRmVw=?m5d~EOIB@ux1 z$C~quSH_oJ_?ZK1&)#ub`q8&9+_4V~W{TvzfT~_t&#<>?}D8ZAl#__<$LF> z4}CAm8d(;1E|TfQL?7Sk{ne-b>c*2N-rUKABUF2R*PWM|pS_8jO9z+Rve|Tqn}?tx z6_#yEPg-Vfux$Jbg#LNj!Ae`)X$c}-v?+E65;pDO%jSkps5U##4WCO%;y_iLciOaw z%UZ%cslK@w-@?ot2$!y9<0L!?tHecS%9~jaG7DymVl3OCspQ6$oAnK98%EZuP_FqZ znu*v#r6 zATk$IhY6Q5P6nhuu;$D-r>T~v7znf8bLq$%vIfF*>~7coh`8c=vi3=+iQXH(IkKBc z%(up69uovhDNnX@WU$#Br52+pLYD03{?f}}HYiKUq)^0Jap!^Q!h=ezW9d=Z|-EqhkC1@b|A_6y6$TzHVv{} zBoJoz{Q6}re46aBc$;EjneeV$0{JSJ)$dK?N+|DY>_A7+dvqTU;p*N|2vbu zX-9Sz)|q4m3-lJd{*2=7T&w%aH4Ts}@&q5RMXo?tbjMng^G8LUa68&0o`#3%nH3P4 z8nR2?%uKqbbe@N?+o`(dq@e{hR{z{*IVb%mM$(hRW^SOkhUv?SO`5 zwj+d>aXUmo5f)K4A7f~m`0M6^&~Nvf+EnD%taLOfH(8>cS{p*54L?V(jK}OC0!Q~A zT%?;0Ik!yt&x?T2&q?>0k@%UiY#gTjRHFuvp1t@F1$XS$MA`rT<= z?24B*Er@(V;vR{4+`MdS%Cm@<(if86RyJ}4VR7tKq>*}ey3UKfzCZSqY*)OrX<=vL zE(>LArQBA4yq{MQw${q7BUrlAlE=I9TWDBRNiXB1*2j2G%5JUpEv!w8Y@S<|<3g!4 zC#%c~?CRh)6cEPmYsPnk#84&2 ziC?C`{b&rpsK-{Dn*1?{Q1fhGE4|Jhc2i@g#kDNEHLa%%+r7Rc9*HJ*&X01-g zh*&Z9RPs6Nk^J5Wgy~&T_a@&_TV*d!J^bwA(5tg=kL!u=&Hd;_rcmH$6)zayG5nbTtUG_fcoLYI1<(s>&;qD8yxLa1}gF-q#}1E_8|G zs?GvH$dh-)Ri<~D-wxMR5awf!JXg6{iLKCN8g1$-c$%%Zz*S9`IIdDXJKV2%T(aiI ziuN{PA*c;VC6j*ZdR1>?deNU_X8mh*e*q2iKBEg6WR6~**ndU{gy}3OFM}sfyngDp z_uAXu;;Rbz*aRfa?@YDn5O;1v`WQ`4DHdfOCbksx$gZD@nuE{~sdaUXZ7xdRUvJ-P zw)+o;cD7R6)QFi?2cg^#VaJ-qai&;WtgYNz=KYa7$>4)!m|IOL@=4~4o*t*}2ZKH#ssZm$j z3?IX15ajGMk+$5&*6zM#5aOK%6B98TO7!PDEd;`>1$RkYZ|c<1&s;J&R@1jU2#$7V z6Kr}^pY;c!UD?%{R##b;pm+CMq#^>suzrhhGkd#(;VI`)>)hM{g2|h<6}tHAaZS|X zY^sD*>xGL&^Cn$)LIu5?d)Dy>2(#7cI1Ry_va3$0mA1t1q7YPH*|%%~Mwwo*%6m z^@_yfC#%)-o3S5;8pSml(FG#VbjL5-?F)~3cP3jaRVIrhOiP!hq0WpYD;|u5p-D^z zXp1J+41~VhK=XB&yHC!1cJ4}gb2hpA@?^Ps2kvAaQ5)I5x#LUcdQ%S`d~uIYW8L)W zUfwiq$mi30Ed*h@BjcC0@ZR!Pb&Kp%mE_Hyr5jOL^%+2Dp5|*co_?n{GJ4C(-qa^g zyfuFEgk9CG8i|XwfNI@F9GV(X0*m3Vj+A>T|D6hYjsV$if{UESh}X<47wvuv+8L^q z>9_`74#o=zPlYz{v}oEDgi^)yYi4+E&;(DJ=hr*YK^W4{&s*CpPj$aVqEnx3O>;5N zK`?cZ3kVm58X=l#Vn-0>C+gN(y%v8DqpCO0T33)`|B5Xu2-7DcTvcTJQQkB?ekZ8-L_RUKqN2RzQ*#9T{Fy~6lt2b>UnEVO}%C&xmYI_C`drbc&gx@|{W*X-j8Qd9I4Bm1O+O3U_^!w*RmFm4l5Z0@W#&ePicX>`C5+^6?U7j<|Nv)fbt-;Hx`DSrU z1d=Yjr|cbuMxl59fbgW!&%B0)XPhy1SE>iHWyEcFL0H#!8s0WL^9QDOdSx~}s+}%K zb5KiOI2W6_!H=DT*cUX_%}>os5c<39qNmx;MND>5>?uLh+~lTBg}NP2@d_q_6^{CI zlV*5GR>fRd`P6rse;~|GZl*I7T{~E(Y%G<78^^D0Z-<}o5gWy7 zEe<_6`Ig$--W$K`^p0NrjR@um>vyNY6FRXk6rgg!_FW&J-FdI(N!m)BR#ughmPHl< zgzcsLKA$P>f4SLxd|AzebBVPI)vxC=@^X2KRnMx z2b<4s7l$60JogE3z1CZ5TkSz*?@zO(6&*BGh>OAMPl|xB%86z( z9W66+Oa<#|f4xe-@X%OO5NV6Lxw9Kk{T>@kS=-{$N}DF|x4wO?y3ax+E%wei&Zx?i zwLddTN7dPg+Gu6=t_gdlYo+p8Q#B@m>Q4bdqk4B0!&gn2xM<9;sUXxI7TIYo>S21G zdqm>+3O=#8Ri|pup0*}xK&8EeODkojUY?(-Q;c4Q*ZOVVfw2DeAn+r9oN0^WAG}*L zDH|=ow3N7LI0&+=FTp<=DpafQ=VKmf7U`U*C?DFT@*%dwJ)Z2dtho!Jt{NHJ*hXfA zRGC=Qma(*aiNx9QMjoHt_vMsRTxRt0^dt9tbfs+CNM}W0sS;y!KL-Uup#YM_++}^w zT`e;T&5A&nt{T|fqiRJxGpsWxwm6^L<~f+nia-%=fx73T+zqU0K^?5S%%~Yok`thb zvG@Y}wx5(t08iOmtP`>!ZmIForUSf` zTU+b%GCZE%nQT|nGQZ-Lo2;#pI2sx*-L2ki3Id^2RM`wFlMdn0Qa&ELF#o-=r_ah+ z+G`6#tIPIzr)7Vvk7p2e!aRN1xkf1Fw-W6{(^*Q{7M@MLRMe$1Ej%^8Oxw1sjJl?H zgnxSXV9Z|EvwdFHuYA?7dTCme*QcSBudm!r1Xj#RnZ#nQPS>YF7{f`wzb=*xpALel zojD!*`C}#mK)6ZiL}I#AnfuU5$;A+3S92#DxmL z{oSBhc7ZLp%a*;-i#;dM+}$q4d^EHm!twh8KPRhA!DOvF2$7;{oRs+w&L5RcBAcF) zD~hmr`GxVtA?m##dT-9d2t7hi2e?lL)Xz1bTa{jw(M#bbXVaV0%q!!6)8}N!ZC=?( zqHb)M_SwW>dCRJ;D%7%jjC!U?sKCa@vh(O=UOV2&;Pm=8EuL{u6*%?ao&VU+?|iu~mmJPHlWvPj!Ij-hQscJ?PYY@AGo7t+>C~ zhPb89rU)@w{rD{WKI8q#NBfiS+mk0$rVcmw&^6tqEO%A(!nSlwIq3cUq0i@vKB$Ua zU05~wNBc$&$hIXAmES&@mFO<~6}}2|`cw(^X+woLS!=GJWh33OVG_J!U{ z-FOXz$dBftSl-2h{z_hCex>rtbyZm=P`8!W@?)l1i7kA{jcj|(r+8uc|9pbD8($c-%V1@-w5{Ja` z@s)lJ5kfL zB@cuX4QzIh+gIXGsP5@~^YrE)zdQ}D2PU${}F9V1{*7ZC|%8Wc`Ta> zadUGanU(NQ?oE?3dqkzwy!GBQWf!aS8tjkp%;1vMJn*=`7nFGewpviMr-Xz9`q{9>kU=nd{w>vyJ$rWPpQh#fp3ndVAAnMdXINC zoK5-z@dY5Ww~)JR339G!63@{vTVi_gAe4^0^yA58IEz_@a_z<{&l1Y1#f3 zD`|48_#<pf7koL%zxY|^I?ak*t_3F4IC74Q({ut6H3Iz zBUqq(H3Wn+&N;Dt>Q2piyK(AnPH>+)7Fn~W{+h~F*qkMEH!=1Ne1AH%dT8#7NSDl) zii~wN{}eB0%oS*AAZKg5w#DzQ(o?0fjbFH!?zfogX}q@*{L~HW&K7}C5ZT-`li)8+ zSFyG+6)cc2YgBI=hTJ9u9XRpm!|dlGXON5P9l}jpC$TQ_!CekzTaDZFP2!h8nDwB| z*bVkT;Fp+yh_xFVXFjn1f8Lx;8EkY5y^2r9WxY3XkD)?bjXrb^1%xt-LZ-Yy#imGF zQLbE+xilFCWg{REHfhu3JP(=`SCM(*#oxUSw(WK%Bkxj!oU@e7%Ae4zaDiy@r^hyR7ac5<1Q=f+5ZN{p}Tp3ST*MAD#?mDpP z*RolLaNBsyC3|MPADay#rH)-WdGzPi9ZqE}{#fXM!yYhVdGYvw&K2nP!i-0iiFxZnHWSmb-y4tnW|Ui^Neg2$zd| ze^_R{?3=peo+pqXeYej4^4==3Mi-I?w)FIuO^vu*F5aILZDbMp?T4VJ;~JNX=XuH9 zK)3eiah4tz4F^T)@!rU^(1HK?>wSJdP(QkMNjnJ3C##s|=Byres41OH-`53>?mA(` z)s>>kil!4D-O!@VTT<<+aY!vzBlK$|=;_DCZdP_{96fuinn!vEj_Iy z9Mv?5i?qY{f67TRc3iVb*Ph%4VK%SJ^K_6NJx{|tK6@^cUYhJWjk6xRdS*Ar$rJY< zp}qnZCNkN$^`&#YsRs|fxTlLfP44<0Xo~j;8^3T&xSnI@);IgtcHvhk}6hMQ(qqU&u6pqY#0sZEu**$G!a8-(tOKI6-XjQrPJZ z>6S~Hma?t=NcWLsr`mTvcrKco{sxk1hJae}*W6p$9;g7QpSsrrB)qAgVZD>J<#UDlbE2QD`F5-*ma>-p| z`s@>&49ybT@kefpVXOrRv1`@jO{S|kiybF%{64Y1+_-q({MU{x4xJwb(;zp2>8Z^0 zL?)<;CV*{v#8v*V9#Vthv&hbbs;r+@aoK5SCTw~DAcT`=)dcgnibBq)4|uyt;XbXt zI`Qr+o>u>!?SBQn+m?i%hbzyi6PkL9=yS>W#nc3~- z$;WQ~lzy!t^|NIkmlOX7uccoDd|TA>AQdP2{5h}g#W|%YH~sF<=%3|po^8AO-kgdi zX4LPDE1Dcvf1nQEyH|a_PyKzc^ob5D$rw`i2A@{%dsaQ`gnHLGbxQvQ^;Lrq8Gr*P z)qBcKE*cHUxAti|sd&3X{p*N|APkzv)hmm{eNGyju*`{6* zIhgMA;kf$Uhmxn%|DIQ`aaz#;DVS6r5A~ndMn0w9L#mu-ZhrSvlI5@FF5EXiFHg_s F{|9}VN*MqE diff --git a/result_sf.json b/result_sf.json deleted file mode 100644 index f1abf530cc9b25fc005ebd219f96d1b08918a5c6..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 112110 zcmds=dyE~|ecwm5g%mETrs^NEq%>TuBwMsZ@wI%qi7ip0WLxBtT2g$AA(u;v(k}PG zB_)av8xn-t1t{CNyR{IY0^&#k3bMBAz)o#BcB&|dR5$%2Y7nCaY7&VYNQGk;2&$q% zt)9>Q@$j6PIdkUBoVjyX#e(F%c<*<9@7MXA_kMYQ^04|CR)5wf8}WEcjH$2ItFNcj&!1FZ%_PT@$JD>$>SG{TlH8v>rM?Z_UVyB$^EU825!K>gvJ z?p8lNo-FVF?|anu^!p4XN7PSeyWfBK>i^u(eeW@agP)jJ;k`ejehW-TyU#eLkgxCl z245dl?>DKwKCb@X;bfco%?b6sht63C!jm7zQ;2jSD)Y4{n>%!A15E`Qtw!D zQhj$u{r*PvH`H8`d|Le`zdz8W;iCDM#@; z6N&vBXH#DdBzGu^EK7!xRmtM+YoAUA)w4i%dG)D&FImk{cw6cb@7Zgx*kmM*S@N8*pq&{eL(yqW+9_ zX?sY~nBQF1eHGynuR7cP?qG6SNtRH;@OgiiR+H-852;r~0+E;f>Xl~IcXQxV^*UrATem8j{dBr_fpJ__{ z52$cRA(o$kkk1}cnz=k#ovct2vMgDdtWkgS{kytbuxquxQ)F_pmBUb275DE4Q{BEmd4MG+C-B zywwGgCkV4V70E;DmM3ewfBGkRAjF!dZF7^7hh7l@tgR_|AQT(?_j8}$_g80cn7jA( z!>5eo5r3>swB+49e_&_0@2Dbq;4mIo+r7GyXQ;ANX^hYA_-)=gOY%UNw|lnD+pXfo z&m_CN@7GH^*K27TQgXINNgKLV&(0ZX>r5QH{Lw?UPknuUV8x<+K3-*MS4F*P)AqO1iO|629&rP+-i+;nd5#It)} z-@K#q>xc8U9z?}8mY5v9UaY#RTdxobELD`)+m*XKZjIS*AFA8?I<_7frg^xwE32y- zz#))^epC5T9X!>OP6<5Q$0L|Kqp>C{7jUw-hK&Yvk zea8K&x}NO<{Bh@}%iezMwxh3YBL_J@`gc!DE!L-h`PX$t6d(z${MWM?HXS6YDCT$C zW{ABIZfY3{_ea}R2eb-(>c^@eT%YI;SXgcw>xF%bVGjPP5Gd@kpy_E^aH6y2ql(wv)lT746Q|guqi&S=tkM}b>cd0qJytar|U{o z2;uRwbFWW+Z6}}ksFRmBm#wd7=b>3>hu5Y_Ts3-4h3XOro9NjKddZw(bW=F`?dg+G zgY0{q*S6hqw(Tyx&sT#=;we|f*QNqJd!O9-t?SAPJWTTsgvC)pUfONzDi$Tyz6uZj zU|PppAZjY+s;7s=Iw<^PMowbNrOF~1D%6R&jE4-5w?;f2ArRUTx{1!~M_tWETp)Bs zPWDWX^zmaX!{FQ>9=tdporL1tKg-X2U9}%|C3$+JX+<~k=vCa+Ow0uhslVBlfsC^# z`*-s`pNZu;=!?2QVf1og@R6uX=zw(x;ZTH)4~@L)M_qYN(v4WBY}`r}do`tv=SNRI z?f2B+&=z)KaMGp&6}ebm*7w(;zS_mhwOx61RY|H;Nb-7F96^I(FgKsLP92T!#vNbu$5R>#pqG4rus$D&!t|tT zuj)%6wE4(%fPA>?<<&gq%JHp-ZkW672|phV4?$zkyZ3{SHU)@#()|t)W-B-Td}wWO zm0Wu7E0hkcRv&bf)9;;q-)u%CQ8fr%y){GSG=WUZbzSXQc~!1JSf)R&itE3d|HI4Aj1A81`O3k=oV<8@w7P`Z(ghAYf=mlmIf3D; z?G)E_Y+8iXbwF5j0;3I&WP2lt_Bl0Vdm|9qXG~m@m(StyoRlhS9e#qKKNiELh_BWP zLVUH~VubsqU7k9R+q0C_ctDu7GX3h>Qa8){Adxfo)46QL;m(h@m)Cj9B-dTT2TRyV zt$KDsD8Q8AkkYj}F)IkgvibUJ&D43aH6CK7<)s}Np`kuW8^%Fjou^)n2NWSE?&|Sz zjpClrf*fR-;%9YUf>3wfdtd2E^HQoC^ml#pn1V1J$L1}*t&ioEo;p>Y-ty9>1>CGt zd$oDl`$|uimr~^+!Y_{RtMk&-(3|U(f}(B*yh`_*Iti6nXd)UKs-GatpNZ{Vt*5BY zv#x7ZRyp(&gjK3{qMvt;hgJvD`tJ6VSsw|e^x68jlYN}C#j5iBOVyv4I-Nw*Ae2*m zy{hrp5w%n|IGt!m)c%+RgvH*nYK^B37i|uLW>)Ruh&dT-QvofEIpLI#p+PvRqBYm4 zTYbI)`m+gv51$3dM#yDRb@un&5j6;18xeF~+RV%oXYSFLIvpDj>KFw2Jn;NiFReQJ zM(3}W-EyW*#uk^Yfu`=N>+m$<|hg?>U@>9*rLjebGa@S=^^y0zxTCX7aCop z#{~^Im*kK3LFn82+MX_IE;409zg1^$Ak>kjjxuelto6B=i?QYPwjYhoEVr zSIHSyO$TF9L#!zXp^v@27cPe7ZM%}~$!4`v<{q!yWOb-o>fO zYXpksG9YZbrUkQO^(M!}>gq|OHaSTTmQx$ma##@NExpal-b@>%IeDU+uiLi<#P!5& zT2M2I$$|8wQMz${{4DZ)=V1>sn@4ZhprXn`My{hgzJ^I z^!`MWU1I{j)NjkTZGg~3Ohx*6)3NJDFaOrx?s;qfjc4yYy8iLs-y`R2n%XN4imaYC zsiTG-)gm$zje$@suGZ4F{HAb|*(v`SK@g^=go?P?MwcEmO?ph53i!{M*(1q}K-l&K z8F5?u1ey5E`sXm}P4z&pxXLfON6l2IAlEP<>%MO4*tUxUZ!fzz0Pjry@%=bsA=HSq5js1n?yKQwam?rA zC7z0t$lSS66f@@kzmJ&0IntgoMf zo=J$fPLa`2cxp8CegY= zSy*HS!g74JcjrVJ6XjKFpV_+S^xW%XpWb3uu79@OmN)m!3B}#BUU-7M7l2;o%qJe* zP{ZA;G~UZsTaidDtT%G6k}-DfZB<#owyUzH_Zp=UE+kpgat1;}m3;JIW*X$aQ09x` zVo8~wlzYBzo*&%#)Y$&c&$i!m79`c8+;*hQNEir_GCf};HN2P_JGXr`xlu^CnU^!$ zX5ddbCl?!W*nD*RBha{eX-1d(F<)dT077DmnA*C1BcT5_K$(A~P9eAXfTK*}L1@?B z`sbar#mHI<5Ze4S7DG;rQXUTrPy2}$HYE>FubN%+z}Vf$vw&SCgg=y<6UiOYg3PG{eliF0j;gcV{gH2+OT;f95ansd{rJoz9qi={u84cKqkheR}u* z-t&{$P-_A0iaZf?%bsFyw*Me!Z+Px{JwZXJPyaL>QD&i+ULd2sJ0eBa4kH``E2^$n8+KtXGlwtc@tA>!Ge!=*LYya_6Mf z5&ZT+xa{jaGf(}9%6DJBWZ$V?g>psKB5x@`(_F{drb1jz%t#jqb%asW<+?xF)WAieCiK`^{eMh zyZJp&HY##?9V+8@t7qTU`3L{<+S9*0cgu)f`?9&(nYeD(>zn(-TPQVIc>{r_58lY1 zZTh(z((eMH`_yhszl*cUaS@^BFZh;OT)ye7@K#T)ly9_F-T(y6#*TCZ zg+g&R66@X<2(ba-8eCs{rS}E;D(7oJnD1%YoNQx4P}JueWp zIg7+OTPi-`JueWttg>*l+4w)JkA7VQS+$KX)W-Gm!@c-fGC%J?*rde;y>wjTq9Ng( z=|Vqr;%htm$;mtyp`6YTTv3rt32OfJp4E@jrF)xcD3n zgwUm^GHmeK{Rg%o#7S3Y;?c`HCS-rK`0g){{%8+q?wNh<3wqw+jm{0{s>B^(9^7v+ zvT_C{Lj{+d2{nkmsRGrPvO2S6%#~>#hDw^vNoLE)9^(3eIy!Sl-)>%OKKJ5u4is6h zGNqVlh~ivJQ;c}LF26y@>DG{#yh-msWm@(%>2sJxnxB??mv`4(Psig$+`jos*`n7VblXdR?$zFTTa6Ie(wRlvtYHyH#ZLct`_v?o@a){1lXlL{ z_k6Z6pVha+W$0t(0c3_$@~<_@Uc^KRp%ZFlbKPl#E`2baJ~MmRj0Ml?@?)26o@V{^ zJ+n7|srMN-{u-K0sa`7^jADDcHqGK@*>uK@oP)59jGLK6z3naB0`+9W*{KQp`!wNI3~qy{28iB1R6tso9W<7&O!w ztc#Pj=QX)^^R;W?<*35aY$eR51zK6><_zhif>5+FYyxA0+IB%+qd#PyE_?jwH~1tf z8<&LUh`n8SdF}t zfpD>v|?P@Nh$6F>B_s?aM`zKos7%N7XRh&_mtnQN-P*$#y1*yHc#zOe7LqsFRL zp;=WKbITW)veh2rSzVPL`}whFKFmJPl$SBLe1VYna9J~Cj!3Y5X|p8_guU88&qNt> zjBKFu$3%u}c`pjW!7H0EWm+U=iZN#E7f6n(IJ{~H*rtPBi$F5+)f>Ou`6tUjs3(_r z^=2kB)+$Nmp7GeJKr#{#E}CDo<(<)XCV$GOen2##vYKq%;Ibb!CE_}RX7WeJwnZI@ z4PBbKqait2?6YFor)t7m+4e(hM{negI9xW7#LpgRx%)q-F3i6&z3H5u5c=SIU)foO ze*N-XHZ8CrDcOiPCol=G48N%lb^4@(=c?07WvfBB9TV9yFqqP&$!pUZ;lR}rK>(PRcY4F~~ zYEZ7#!pV2WsC@CGyRt2ex0YiqKBG z%4~cm2z$pz>2cEKuirZYVU~~m%lAN2HS)Hp5Erk7oO%bLNdAc0*7~rjEBGvWJCRvB z8vx;0a#(4_iKvY>=*Dv8&tq@ZxG?_*)89I2Jire(UmW0mvHy7P_T``W>2FQ^`&0d# z9uaDl&2HPYh?6mLyU^A61|YsVvncq6DKd$V2HCo>J26663e^{bE^z!m?4u!^MF zvr4j!g?qKiW>>;E`Mv3j179Bf_)o#KFt=kcryx9~ZjW_9TZIB~v0+{Qxp-#~`ezlW zkRx^cTfd%XG!g#gZ<7R#t1g!Hm(672)#}GW0T2om(83|FKKS#tUUjKKX#1_S7P3Et zeR^>dC(@bLR`vbJOXvWlgch-tS!RrNEzd;x@e#g{m&5?lH*3Z>3Ky?A{SSAqI`L~W z(x<+8{;r+cW4<)@?!oD~AB-*9*W^@5+(ZfV!8W)&rcEFCTXyS)Z+k#U1|S}jjw0Gc z#f$C-2(kPw+gr51sW)}nbT(iz0ij_Pe6~fA6M*cqiRtqUCP#LE?7;7yUN?2!u6L~M zd5gAeI=6S?*}boCUKl}YZ zZ)9BD=}6WS6Nh}O^YhRB{PKfG-Woaiw8=r=c$Z0yxqM#LJ0zxCe8$LH70R`fWr@Vu zQ~fp-%5O{a#cj=G%2|Z|Oj$NX5%bmSqUa7vnumJ6ySj9>b27u`AM~=R5LX!uw-m(Q zOo`$b*D9M$4CR)05W1%++l_^aCzU~1zWIrGlexCI3~=wndzS`JXJ>Mjbm_M&`I!0_ zG-Y!KSs&ky_0V^iYK~$r3{~QGGBBspTvo3U`mG1(sdp3O#(4lYPoa(GXw|&5pB&XR zc|UVB)*l#-etYuX4-P(IYbX+fgt_gV+t#(qPcVQ`G*tK*+g-0RNw-DCkL1Wyv5WI# z5W4K{Lh%biL%$7Sg9JDD#dgg)6Cc{O&B|CLTS-e8^wKtXp-34v!cahDE~XX}E@hk_ zNPl3>nS@SLEln{HX1(XakvC)wgxT$pCTk($ito|d=cUFvZ#*}&ojJ|7M`c zdfaZ7(>AT_9kU>G^{)N;9bS2rvueaISQnY6uEOu*SL4I=S0pQc{v=P|{CTw|`7gEJC(k- z=SSP?PLzQKdW&6uO!0QMr+d#e4Uj9c1s|_Pu0U9HcUv=+)-q`^9*d|N9;WA5KxitF zE_pN4>YCDd9>#99YMYaW7F1gO)1c*?^q(gwnj$E!WV*6xdx8LeDm#4ao(D86lZFsp zqK`zP^={q+MOZ}He2k%K;;)_yLciT_YPXSJvy5&EN9hftomv}0q76Ss&yU9JD*{LR z9^9ry*+~)*`Z?)7O%gw6mW{)-pIo7=iOdU%Zi3Ji_ejj+=4G!YKZ|%N-6834Wh2)ZUY;M-dC}K*#h#&Ui`dHc zq0)90gjua@JA$Q0EqS~vzXf4YJ-x`b>OJ~eALBVGd$@XUVQpGu^W3r=7fR*rYuGf~ zL+Z}Z5pU*`^=$bpw=7B(8ymmvnfxpyhB9#&-7ai?`3@Fn=s$PES*bUUUYNggT-ym> zzL=$2)fgH)?!75T^G^-O=3$aAx9@k6#>kW%`{_nf)ezBYKfp6lA&zEyHCGJmouM z!uQ1(y2Q(#%%OnvAI4zNU3d1W4jxU3gk1y8k|@x~6iCj3R( zg)VVi)mZ=tdGfZn$_y`4+~K+k!hFn;=PGwIwV|uvX|~=1S2bPYxJvbGUpK2dYfX<8 z?RUaLP$!W}CSBJxDlTP)(Vt^x{cCl90S)_Ad*{p@PwYQ21j2L{l$XJyM_xPj+dJ&d zaPd`z!6X~+f~5KVs+=m&bcj2>A$^P{<^;-OSrc0ddSutnMa@BIh}61j3N{y|@2@v> zHQW6ML)>{op1|c5Y-+?ztbHA|fNX`N&_*h_@R3&1H1$#_zeHq4D7^ zd9%+ge|dCh`;N|kJFIi&=3MXlbW8tJFwqdPZntlpRbpbIAk;Q-il`^T^*n5 z9t!USLO8NM+0*hg43m5zXIeq1PlUQ;ZAa&&85z&mhQ2Y9ej9(XF?;nL&tm>Q79>gecLU@5~SgvliSXah-`{2fuLEaP@5%lhUi&R8F7&e_C+|1qtVR*`^)H?eZKrnvAwqjwkF>mwn zu1%GYYQ1o=Xx^mlPN<-l)6Y8o0AaQ|9jBq#xa!;lN6c>PI(w~cdX)9GpS;p#JXJV7 z6dr@%6}TfoHjB#%^eQo1Q5*sdi>sCW@(MgB`wrsgD8AL1n!R`bSZ83xnG>&emhAY% z#D)1MhpR@tBJudiboaI$`(db2T%!?PAOcNy{IcD?aETj9Hdd-k7DM%=^CF&iR1|L#e+P=BC?WvY1)v_r?*=O!gQ^~FKywy<&EkN+AWpj&7P$jQdsp#Kxm%kYc-y}+8G+Y zZdqsIvq#?UZsai?n5vPuSPQ7uZp5Lf0VS{){_04%m-64gpr?C~?IyU$X^eQy%yQB0 zx1gP&TA7Y(;AMZjfbdjk15b;lT|p@G6MoIqT^P9L@4z&{Q|9^g#&i&d^z-x9Hp^43 znG&7)Y-^f}c@Bc94PP!?6l#QMrrGfU!u&+tDy!Gx=VDcFp0%zZ$Nm*tRuHC7M!2$c z`ee4(w9j($`t@~Fb5$sXG_-Z10NQB!gm4vvhO>FDhR@c;bCvBvS!-K;I#O%q&@l50 zo6hy3zYW!TSM3uX3N@(q`K!Ec+bS9$k{51YV|mEN8Rk%mHPdJ%2qo?=wyuVUY5N+l znI;MXM_cw*(}(%GaIS(dubJUzL^dWnBBEJ3q)buyPNj;prL(C#SH;#!H7%``@bedY z#<_?e!x0%6g#=5BRbWVli^ThfG}GhVc@8E&#eO!i8ZXHC8tG~wr+<0qd6*Y`TF zZChAd?m<;-?QJT=MPv16MnG7lGGOMUWqM9F$onJeP@TLmk3|KMSk?O5Et>A)gDLAL zT+`AvO|Y}|ZEV%e79we}chYfMRpzbZIf_=oL69w)H}_B26JE=d@0zGF7gT>H2sHKX zHHNpEI&ra?Ut2+_JuULnTnxl4J@<>m@YZmYTP^P#uR3Rg7B#J%S~H=X_7*Pflqq|m z0d=St{S2@E+x!Dz{e42KhE?TddW+}M`)JqCgUv) zEvnW1^AQlWjC8J4lqYRdc@o>>?oW1Fw%vs=ACLATV?wq}Ba_RR(%5K4WOo2+C4B0O5k$784G-rWD_2{~i?`uxC(vOV8v+27yA(+@jgp1$n7 zBNX#niQYuhSxVU!o(;a#*QHJ^Jk7=@E-z8UKfTE=X5Z_HE-&lX!0Ok(G%d=j)lkaU zZ|+S5R?JD6&|=;$eo9?5(eJOd*UMTjf20M~dNaRcKYz@m00`GBod~U%JgEB0_axhE zSopfu9fWP(FT!n%WFz4$SFY%%F+xMa!3LqR+TQk!2E`4HF>K&Ygsgy+G*8WQ)C!iE(7IGbS?qVdtsgZ;Z&D%rB1G{e*r`$K+)Tin%vk2_3Lt%vSg` z!f(T3V^op4kQmeO5X4lh<9d5GA7!@bXWMOVvMIOj9WcI@ z$7C%%2zmBu{FKQM&M1{lEBj|FY>s|q^x^=uUl6@NCuM{lp(hC3rw8ii9io@vcG764 zaFg@v&FSa)(ZB0*av^qXk#(qL_Zy{#zgF2+sK8dpvNP*t9z6E`Y7mxH4DD*6neBB>FRU+WY%*F^YBCY{2%@5KAu*}^$xYBHRn z!M1`hR4<#1`NQLV5LWjBOdH|5{HFx7IYYkk^jhcl4=vw!W@6prdRhlOcPKiV4b_Xi z9PCvNKu(vB(TLC7QfE_yNDZ16ao+FM!*4#`m3*o@9ltqwKxOT4gAZNbEqeDX#rh$4 zRrJEPbWA+x9si-v=c;E=A-gcYeEbJHhjz1($;^(u@m$sFbz7BdXr@n}P_H(Wh?BSG z`dc#sPE%? z`O>Cy`p)cYKVs*jH_!j`og4QJPyNMqPPpGPa?@Fxu4OcBP8y+4ksr%Tq)nfgN_>@* z8z3y64lJjXu_=O{yYqA(CHsUf>Bz?GL7H!#d&fXu~CU2omGv_gF>Xdam{qae< ziX;d{2aC>GWh)QW<4yJvQ$wnDhlcPLg!bH&*52Q{baCLt(HqZ7wYmBR(CS@Iki?zB zwCNDXMfYAc5cZCXMD?q>d0G9b77!vonu}tCFAnsl+5no#E>FX)tWAZu$ucs9vRVTO z#cMTVW#!g5`dQ&!MOOs=i#>n6)%KXuRWzOJUfd~CzF)ZxKW&P{#c&~+pW&y}9M}Uw z{f9|0e=Rv1^Y$uo10fpPq|~7^bP+g#Zlb@k$S?2P(_Z~oKKnb5zCC(j-rU34ev}5a zs@<<=(<07(ATjM*5awLqCJ{*tFSm96WX852zw+6C^Qf*Owa>>a58vc= z-4JcWW>7!DeuI!~sH_LomfgtP3=qbh8A= zT#{!~B~J1}=N0troFa2;l;*Q3XCX=+2*(=O3L*Em#Gh(?r1Q<0PyE#Qt?LhJ8@F&I z51NJThOnv9mgEs3fsj*~)V%b`rTyKAsq8lLtUkS;q9!zKwW{^e*^KeDM*28e&5n|z zN0uC5H_4B;PfhOV{QBXxE3NP|>v8?w)}{rLw=$wbHyUzEXRWdvAY2$#n!N3h zObdk7_-Q&YL>kP3Q;&*?H}+1vcWF@F+(?B!JxykB>@V}-*~qOok_Wx~k%vu{IFD7Y zQ!iQ(!&7QC^y-`9X?hY{D);IA;MLGJ=^Ml^Kr?&0xyz!!S529CzJ^&8)4K18S(@P(Q=vA<8QvXa`Q#{gmYX$DY+O#Rt8E3p;TuDTKk zLaE%az4D`n{-pDxssAz}Q)PQ6*zey)g&Y)dvt?5C6H3IzC)lBUjRb^K&grt9>h8{Z zyLResVsM{h7Fn}r1)IuUxZg$QbYiR=`2KWa#lY-&kuI4^6&Y)5UMgPBm_E?dK+aZr zZHwP$rDsuP-@kA%-HkDo)p(yJ_^Bq=okaqnAhNlsC&@o>%L|iLtZhtP3nX>DlT8Os zP5LnVxyU)@qWXt$)7D9>i+pffMA@$7Uiv2SOCZd8&}QrgdnNEo%t^%BjdfEW+VwxL zOtADf#)V#0&dJzRh^yR(POE@WCRWItIT?(k73I!FSxl2rP&NVrVUspZ&I6%YaTS^e zp1*j>j=&#y{-sND#%}SM{!D1gbhhZI`#fhhUZhfkeGzKJMM6~DiYyy80-Gs(1ffjl zQNJMSrjOFUxH~Ix>$|-x@HS)HWCo2Vtm{REZny4U|M)W}px&$V4_ta-`-{K*&8@Th zzcK%XeHRCIY;JolMbD&wC#=J4)1j>{0@e(K^4?5w$uv z4GVE6hvz2#baMTK@XpM)E!y(>=C(4a&}M@T1eZgkT>7WV1^=b{;Hn!z;b}Fif1>~ zK9jS?O+?xJd~*1j(;!+{T+|!{Sw6zG=@7@oxE*Bp1{XrtNo|{pva_1JtSPO0a+tlx zL&t5;zR)~D@%9<21WcMik+_VdS{KMwO^e}Y6I%JowCn-VH=u%Np>3`*8VNe7AW+-T zTwEE+#j1Do`8IVLgnq50N=0T7d)6v#TbWHa-VrR}8sGMu2R%9v8al+;*3f#@prSjc zW2qW2?@N81Yz}VZ@1g;rFWT;9-6|}f17X;701+?}M;#$tF7o|jnF_P-1mi|26Q#ZU z%r)2CF!vifsze=aNFS6+&x+X;iOcTdJv&w|i_mXF1U>!OxEwvtPkj>+coxl%oLy*~ zG+Y$v$BQG|LJPj~*8=?=min=_i%uXcpT%Mdob!Izqo#Dzz9B5VajE~6m!hhRrWXF) zP^6dlwAyv$kZP?)=+{lq)3=S?JuW_D;OU)fPhk02)@cf#v>;?3&&j zwUZcsW~6S>mJe^sPx9>O{N!*uyX>KpTMEM^(9k4qLeYIL0ffDq_)b9@#Sb;cfru=r^X?p0WT*aWAqcBF5Gd|5CFMI>dFaeA$g~vw3eo z&s^?3imO3`FU!UL>|+4Qfy&zqZ92r|H09MU5bAjuIoU)6#6}32*r}2&^rp%M!d}Q4 zTQivjjJu`7L>{uo<@xR3pMPtlKhkC-4Vs0<8_WV~O2kFH<1m3h>I}3i z&*JTqkDM)~{vT%{vOL_{p$-ljy9*PZ{q(v9?xGX1gr)`k7k?z_ubYO?#fU$m2PU_j z=`&Lx45e3Ze3IK@7;6DS>{>N>lc{XZbjL{?|DSkYZhl-m_q9V82maNt-G%SpmN7le znV#f?UgRI{^O$&Pp-NmW5E~*D8U7Xt8dFvG85N<;ICEmt9{?fzJfY_7M-|fJ>H`k1 zSGZ@?cgL>2;*9!yy89itZ`%`oAKpBnPI>B0rB5WMlE;)rNl)>tdX+)-hj&{v|I*mI z2j%Zg!}9Mya$h$~c~W_I-v7A5!Y=!%uAkza52>$?Cri}#52!znsqfsaetKNJFE!ld8KpkepF}HgrEfseW%p zz2`>tH#>utB%i+WTl%#I)bEykoJ;&4yq10q@NH1fgp?fV^6QkksppuYT zJlkgVvso2mOsW4fs_1f9{eeRK><;z!V)gHy(kI%dBxOL|YCNOf_k?=ZG4-yqY6rkm z>bnLZG65Hks`or*eSe@!*^OPAjw@boRi7PDafLy1zj|enz)vY`f_y~%Cep+1w!5A0 zoqoT&l1=Irk%h@F9}cVkdv~%$ef6YzjTuD)Bw<{A+}(X%8~KEK59yR0zw*;#NtVBw PyKvw9zC1mD^XLBoaxox1 diff --git a/run-target-migration.js b/run-target-migration.js deleted file mode 100644 index f51248e..0000000 --- a/run-target-migration.js +++ /dev/null @@ -1,44 +0,0 @@ -const { Sequelize, DataTypes } = require('sequelize'); -const path = require('path'); -const config = require('./database/config.js').development; -const migrationFile = '20260524190000-add-ver-to-wms-order-express.js'; -const migrationPath = path.resolve(__dirname, 'database', 'migrations', migrationFile); - -async function run() { - const sequelize = new Sequelize(config.database, config.username, config.password, { - host: config.host, - port: config.port, - dialect: config.dialect, - logging: console.log, - }); - - try { - const migration = require(migrationPath); - console.log(`Executing up() for ${migrationFile}...`); - await migration.up(sequelize.getQueryInterface(), Sequelize); - console.log('Migration up() completed.'); - - const [ results ] = await sequelize.query('SELECT name FROM SequelizeMeta WHERE name = ?', { - replacements: [ migrationFile ], - type: Sequelize.QueryTypes.SELECT, - }); - - if (!results) { - console.log(`Inserting ${migrationFile} into SequelizeMeta...`); - await sequelize.query('INSERT INTO SequelizeMeta (name) VALUES (?)', { - replacements: [ migrationFile ], - type: Sequelize.QueryTypes.INSERT, - }); - console.log('Inserted into SequelizeMeta.'); - } else { - console.log(`${migrationFile} already exists in SequelizeMeta.`); - } - } catch (error) { - console.error('Error executing migration script:', error); - process.exit(1); - } finally { - await sequelize.close(); - } -} - -run(); diff --git a/run_task.js b/run_task.js deleted file mode 100644 index 9d8f63a..0000000 --- a/run_task.js +++ /dev/null @@ -1,102 +0,0 @@ -const { Sequelize, DataTypes } = require('sequelize'); -const fs = require('fs'); -const path = require('path'); - -const DB_CONFIG = { - host: '127.0.0.1', - port: 3307, - username: 'wms', - password: 'dspxmRwRdRbWtbm7', - database: 'wms', - dialect: 'mysql', - logging: false, -}; - -const TARGET_MIGRATION = '20260525113000-add-request-platform-code-to-wms-print-platform.js'; -const EARLIER_PENDING = '20260524153000-switch-shop-platform-fk-to-print-platform.js'; - -async function run() { - const sequelize = new Sequelize(DB_CONFIG.database, DB_CONFIG.username, DB_CONFIG.password, { - host: DB_CONFIG.host, - port: DB_CONFIG.port, - dialect: DB_CONFIG.dialect, - logging: DB_CONFIG.logging, - }); - - const queryInterface = sequelize.getQueryInterface(); - - try { - const migrationsDir = path.join(__dirname, 'database', 'migrations'); - - // 1. Manually apply EARLIER_PENDING - const results = await sequelize.query('SELECT name FROM SequelizeMeta', { type: sequelize.QueryTypes.SELECT }); - const appliedResults = Array.isArray(results) ? results : []; - const appliedSet = new Set(appliedResults.map(r => r.name)); - - if (!appliedSet.has(EARLIER_PENDING)) { - console.log(`Applying earlier pending: ${EARLIER_PENDING}`); - const migrationPath = path.join(migrationsDir, EARLIER_PENDING); - const migration = require(migrationPath); - await migration.up(queryInterface, Sequelize); - await sequelize.query('INSERT INTO SequelizeMeta (name) VALUES (?)', { - replacements: [ EARLIER_PENDING ], - type: sequelize.QueryTypes.INSERT, - }); - } - - // Now proceed with normal logic for TARGET_MIGRATION - const allFiles = fs.readdirSync(migrationsDir).filter(f => f.endsWith('.js')).sort(); - const results2 = await sequelize.query('SELECT name FROM SequelizeMeta', { type: sequelize.QueryTypes.SELECT }); - const appliedResults2 = Array.isArray(results2) ? results2 : []; - const appliedSet2 = new Set(appliedResults2.map(r => r.name)); - - const targetIndex = allFiles.indexOf(TARGET_MIGRATION); - const earlierPending = allFiles.slice(0, targetIndex).filter(f => !appliedSet2.has(f)); - - const beforeResult = { - connection: { database: DB_CONFIG.database, host: DB_CONFIG.host, port: DB_CONFIG.port }, - meta: appliedResults2.map(r => r.name), - earlierPending, - }; - const [ columnsBefore ] = await sequelize.query("SHOW COLUMNS FROM `wms_print_platform` LIKE 'request_platform_code'"); - beforeResult.columnCheck = columnsBefore; - console.log('--- BEFORE ---'); - console.log(JSON.stringify(beforeResult, null, 2)); - - if (earlierPending.length > 0) { - console.log('STOPPING: Earlier pending migrations still found.'); - return; - } - - if (!appliedSet2.has(TARGET_MIGRATION)) { - console.log(`Applying target migration: ${TARGET_MIGRATION}`); - const migrationPath = path.join(migrationsDir, TARGET_MIGRATION); - const migration = require(migrationPath); - await migration.up(queryInterface, Sequelize); - await sequelize.query('INSERT INTO SequelizeMeta (name) VALUES (?)', { - replacements: [ TARGET_MIGRATION ], - type: sequelize.QueryTypes.INSERT, - }); - } - - const finalResults = await sequelize.query('SELECT name FROM SequelizeMeta', { type: sequelize.QueryTypes.SELECT }); - const appliedFinal = Array.isArray(finalResults) ? finalResults : []; - const [ columnsAfter ] = await sequelize.query("SHOW COLUMNS FROM `wms_print_platform` LIKE 'request_platform_code'"); - - const afterResult = { - connection: { database: DB_CONFIG.database, host: DB_CONFIG.host, port: DB_CONFIG.port }, - meta: appliedFinal.map(r => r.name), - columnCheck: columnsAfter, - earlierPending: [], - }; - console.log('--- AFTER ---'); - console.log(JSON.stringify(afterResult, null, 2)); - - } catch (error) { - console.error('Error:', error); - } finally { - await sequelize.close(); - } -} - -run(); diff --git a/search_logs.ps1 b/search_logs.ps1 deleted file mode 100644 index b20dfb5..0000000 --- a/search_logs.ps1 +++ /dev/null @@ -1,41 +0,0 @@ -$targetTs = "2026-05-20 02:20:00" -$kws = @( - 'print-retry-compensation', - 'print_retry_compensation\\.js', - 'retryFailed', - '触发补打', - '任务执行完成', - 'SCHEDULE /__schedule\?path=D:\\\\wms\\\\app\\\\schedule\\\\print_retry_compensation\\.js' -) -$sqlPart = "FROM `wms_print_record` AS `PrintRecord` WHERE ((`PrintRecord`.`send_status` = 'send_failed' OR `PrintRecord`.`print_status` IN ('print_failed', 'timeout'))" -$results = New-Object System.Collections.Generic.List[string] -$file = Get-Item "logs/wms/wms-web.log" -$lines = Get-Content $file.FullName -for ($i = 0; $i -lt $lines.Count; $i++) { - $line = $lines[$i] - if ($line -match '^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})') { - $ts = $matches[1] - if ($ts -ge $targetTs) { - foreach ($k in $kws) { - if ($line -match $k) { - $item = "$($file.Name):$($i+1):$line" - $results.Add($item) - Write-Output $item - break - } - } - } - } -} -if ($results.Count -lt 5) { - $sqlSearch = $sqlPart.Replace("`", "") - for ($i = 0; $i -lt $lines.Count; $i++) { - $line = $lines[$i] - if ($line -match '^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})') { - if ($matches[1] -ge $targetTs -and $line.Contains($sqlSearch)) { - $item = "$($file.Name):$($i+1):$line" - if (-not $results.Contains($item)) { Write-Output $item } - } - } - } -} diff --git a/task_script.js b/task_script.js deleted file mode 100644 index 91bf9a3..0000000 --- a/task_script.js +++ /dev/null @@ -1,39 +0,0 @@ -const { Sequelize, DataTypes } = require('sequelize'); -const config = require('./database/config.js').development; -const path = require('path'); -const fs = require('fs'); -async function run() { - try { - const sequelize = new Sequelize(config.database, config.username, config.password, { - host: config.host, port: config.port, dialect: 'mysql', logging: false, - }); - const queryInterface = sequelize.getQueryInterface(); - const tables = await queryInterface.showAllTables(); - console.log('Tables:', tables.join(', ')); - const [ meta ] = tables.includes('SequelizeMeta') - ? await sequelize.query("SELECT name FROM SequelizeMeta WHERE name = '20260525113000-add-request-platform-code-to-wms-print-platform.js'") - : [[]]; - console.log('Initial Migration recorded:', meta.length > 0); - const migration = require('./database/migrations/20260525113000-add-request-platform-code-to-wms-print-platform.js'); - console.log('Executing migration up...'); - try { - await migration.up(queryInterface, Sequelize); - } catch (e) { - console.log('Migration up info:', e.message); - } - if (!tables.includes('SequelizeMeta')) { - await sequelize.query('CREATE TABLE SequelizeMeta (name VARCHAR(255) NOT NULL PRIMARY KEY) ENGINE=InnoDB;'); - } - await sequelize.query("INSERT IGNORE INTO SequelizeMeta (name) VALUES ('20260525113000-add-request-platform-code-to-wms-print-platform.js')"); - const tableInfo = await queryInterface.describeTable('wms_print_platform'); - const col = tableInfo.request_platform_code; - console.log('Result Column request_platform_code:', col ? JSON.stringify({ type: col.type, allowNull: col.allowNull, defaultValue: col.defaultValue }) : 'NOT FOUND'); - const [ finalMeta ] = await sequelize.query("SELECT name FROM SequelizeMeta WHERE name = '20260525113000-add-request-platform-code-to-wms-print-platform.js'"); - console.log('Final Migration recorded:', finalMeta.length > 0); - await sequelize.close(); - } catch (err) { - console.error('Error:', err.message); - process.exit(1); - } -} -run(); diff --git a/temp.json b/temp.json deleted file mode 100644 index e61205be447ce64a2296103ee81a32a70bc5a88b..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 111412 zcmds=Ym6S(dEbYLjRtP3rYTU_l9H@eQmh-r+w$tBlthV=?T{;m_nS84a!FCzQnvB#)mNK2Il8$@1i5 z$(jClhLTOmP%<<+vEw(+{qKWE{`vKZCnx^iJM&L(+J48-rsU^`{_)W}hAyeUe`@7W za&NLKS(%I^Ym@u>zjYxQPR5hTlr;-`GVx>_D_Ih zM*TkTuv7gR@4v?}^=`b@%Kod!yYs4=1{ab;>icQ@W9t8t>bK7-95d?mc(S=Psr?Re?^wH>_hKfhjd-L7X>hoCcz4g1v6Ui$c zy!l?^3Oi3St$uUj=IerxpZb;LaU~(^lGRE=Rwiqb_3ATUf3W|#{C%tAJf?7@@f}sq zBu{6f1R?a|XTg13{fv3KP<&&GXUA^7-&*x_>y$3=yy3rpO1IqjXTE|En2><-@eXH)faCPC;*=?75Q;S2h^M5q)i-+&+bMbz~KPY-%B}&$n zJkX@=WHrgNsS+o7>k1@K5N3HQl84l-N;dTW3{LVuh#gN`kJa8D_tL^uD`&ap=KGki9j2b)h$Y*XbR-AM9SX?2X>7m)o&iS;=xs6^POijw@QzG{9f3 zR56858~m1Ql@+JCBkyd~4Z^s{d;QHgZ=?|(3jaU_55K>A*@fBpKc0B6aMI8M3*nDI z{G41p08WxM5WTO9jA*|-Ju~;I*>5gP9YOctB@$hpZ^l@5xBivu9?uLy{oE_m)7RI( zqL?)w2}*9xyRKFr>y)hcqy>cexC1VT z=N~jo^Ke67R@XMjLz8v*^v+-tzViRU*ozS*edz02Rf};~R&2@hb1~dr>`=AhkE=Rr z7>#r#mY;T2Q$Sc$Yb>j%WHaw(swu0Kc97HR3ecV^(B>Zq-L>ry9yS#RcEw3U z3*tbxm2lg67bl4Yi)*lUu1NkMA9$OMeJ@k&VT?^Jvlq6l0HNvjj47^$)%>f+6j^+B zy?>-1t5TQ9`yvo(>gHb~FK>U+`|--Rp1J$v>$}K4u8jZ9C#3%B)4%-dx*`gYgjW0O z*$kTw5>*uQJ8d(>UI;g}42Aon-N_cOeah0Oeyj?@O^NPzg=MvMVjW}2M2n0svhA45 zhJkQQb!xJ`q>EDzKf5^eZ)Ur%Mu4bpMx>t}FGPOg(*l=7nck7l1A)+VEP0P+;s`Qu zo*-`(s#t`JQ{Xe)Ys&xBjUqr(rT=HBup*L&p>+rlHpRo${Ro>rPF!bA>mS&R4sK39 zJ%4TbYx{1U-|Us`tOaW_+W=8$FW06L?3DO+{KwM_Iy8GnKPK*&;)QI+2#~i{Vk$PEYR#gmzqRV)FX2R0fa^FW$b_p5gm|tx-`|Q`&fC{M;w}o*Ep! zxkpz{-L$1oPtMtNAOni!Wqp4g>Z@J6WEO^gOI#L|*GuWCyCP^%EY%(#(U;arXhKd@ zKLV=~MW-XMGLAw+305t^@z%+5fa} zc>cB7|N4B@UhR>-jzY;n$eK-o;*1S?3HSVx7M`^|uBJgB^;#ykY!%5B2wib*_p*gt zamr$2UwhWPD_0;a(;rt==U*-S!Hr*^7@j})g`>wgWAWB_bqTYj3mkX^nG39P*1}iY zDX#0-vhG<1)*3rUstV}I#0I7L(H_Qv=<{Z)TcnhIOwbM)T{A;BIImcJwC2i z+!I=mgRE5itjVA9sm7X*&rMf{^*EfYJ2-9(F-s0Q(SYGL=Q{`!wmo_cnW}Vur z&CB*HJy~8#m4^twIKHpWOM7b0Rq3fyBmH+1R%#YaRLt!YVTiqMr{;hE@mC`tJ6VSsw|e^!fR?Gklz=#j5iBE7YHuI-Nw* zAe8faZPj?}h+3)}bV}`r+8>jEu-IExt?|_1qRm0j%q4MLw5fn)jXBYjkD)>6+IoN| z)~70m_~q zyl`mhmyUjUC*21SP4DS;BSl!;1G4P-X=KaLfjHY2>6TlIuoFfSVQ=Wm8N287PB9RM z@}hfLL(V`5g|c*X^*4-7BfeXsKA?2y^SP{AZ))tuZ++I@vjZNsJo&hm)za>|sG!p| zJ33p23UQJa-bF>yuxQe2%tzQDEbBQAM$)vDfzY4(+g45X7m?59dnMsf_HZ)V`_04u zV(0SY&la|fzHRkWL9;YvP0JYwS13s%ml8VodT{0ax90n)AoSY{&W1D9LKQ2pnN7^rzJ+8hL-L~?0eX8RW1TzbI49<+@m;htRA3PS<*UXLOOSmYfzTs|$e8 zx6`#dUDRA;u7(b)&euQ~5{Kuz&f22heRAfrb62YAVv!z#ri<<*=UFu!j71HxrXa*? z*_(OcVpz_$KiQpZSG!{#sTBWJi=9D87ho_miRs-j?wAOKc0D04TM{uhyF11$S76C* z9*^s}2?eMLG_yevgh*x=T~oHD&@-%7Hw0mJ<3gT;ZPyM#(PY$RXu-5ty;(7_x_Y*# zOHR^t<(x*f92SIrZER=0C|d;vhkX}7oJQKTs5@Vz>%e-ps9Rp@`JyVDJJ9W$W zjbHoAgKv&~=+dJnH$D4%2jyf!k=4^Cb=1(KT0~}|F%XKy)mqw>-xO{#E#*HI z2*UJSP!Tt~=*xqqNsnn$fh`R&(?*gRfw1eDG2*uPnK6lf>Yu!*H^&3LVyjIuGbU7! z&Q@K^O4T5n8G*29X6%5vdugZFj%T|t)iR^7tO$f=_Je0{W_E|Uow&Nm#+g&QK({#b z*2=}9^P@{;q5@3m9+!%^U$SMwR$0Z`t9W z%{x%FofTEL@1XKeR0t(vZG+B=s{3dV7RP!%KH{M`bId&&MX_T3_kEmvVN`Y~fvIfA zhVIMQT@PI^Z=)U!CR1l|>7-4Muv3#oCnoDfTp+Bkm4cqRhq&I5(M#bbsJh6FLh~Z< zR6Tpa%>mFQZbl$9D*|CtevE^S!;ywwMrIme0bHgs@zBaOH6RZk=y3+sM7s-%lOdOK8{zw2Eo({o^H zgn1u1I4RQ-20}xXJSWYpn%wirXS-p4eO?o5VhVFuZE$noG7hC$}8en|~Kt zP4=~=tL;0o$qPEH4#+q_=$ne6!V?xz(Ai@$nNG^;e$FtWCLh?i=(kc?-<`D-AS}1W zgPE|vr|NB(O!CC!NZ+1bzW3jM>SG7~*TEmng<1<}SLBJHTlQpno!p4`aOFkv?Ckxh zx>Z1*%MygTo7;3uQD!g1oBFd4k-c<1)nzYi-bsY$jx5UM*c}_T%}bjW^)e6;YEFhn z7F$*JaX{^b+pEr~SCRRwjVPzG8 zPUv>qC7YkUsay76+ddesf@Zq%J^@V`{E$D-^z${Orv*ayIoz0@7N?ElVnNMW@U67? zt9h#@QrhowfuPx_k*=RmDDGBa-Q@xy+TX=Yu5`ITU*+r!2=jeQ(Neo=UA#wL*JVvj z&s8gP$Bt>w4whzTtZkYUR}Dfc2GZdIVV848oS~)G6W-whq01f%N1KiO)7&fL9LTEe zZ=ou#pC9hU&x!eY2f`*TF6gDd8W#r%?>;>bKJGyqBp34>1eMMUT)DVS1uFgZqoMqi zSW#sCR5IG{AjwW|5c;zlQ){i0y~Ss4AcQWugOsfY8+>-xfei<7lGU4f`o`WV*#s@t z{`2EMI0%|Y=3f8IQkfg0#sMZn1(%!&HHf*Xd)1e+dNKE0AEEDE^HH;@4>LDL&JfoH z)R9>>=5}*gbGVJkGPt!#Rpvq`SE@{{7+Mj9*X1+_Ij{%M2OB0OEHdBSo zSna$PgC_5tADO%TbM5EW)TcBj{K>HWTm_+tK3%?8V(2}+nOz@xr@hlW?ebF7f_*?xsE8)ToD_|e^E|ry z(S?2z@pJYyr1k|3b>!jVr0s1@rrms%T6j6GurwPv*|b0_>)d!D-BJ*WR)$SkY*9Na z$YS(|?7?LdA3X)1L}hcM&@4R7%fZZ9u;qoj4c%utK^T5x&c>OKJo}>)vU9Ksy}~=E z(lrHD6JFhZ_86;?mog9z7oGrQ>JO?@?PjWnepMBEh02$)6M5MJVHdWI2$|WX>ig+H zn2tUEcK$PmUq5NAS{0gAl`*$`fvH+1Xg@#p%!k?MnesB`mM;+U9xiK!%n=E8FKxD@ zfv~O3@k~xJtH>_BBLAPY)_E@q!r`0yEM+1jW>PU`cNa)bswu*%yhd{qX!!eCP&uK#Bydvsh| z)O*;{&$!%?kemN1xP#(*s1GZyLgwG1;MnJ75Yt-N;Cywn$yfSz1DzK&bsHc9qKAg1hHCB9d!hdG*s^7B^xD6B1sr4oM{3_B zC9=(y1~yi&^~#=KGwqtP@s=QLkB`#vrGsC;I|RZk9|xD+fu?GlZBrpGLJK*;4nmRq zood7Cuc|77&zfiLRXed*+UA3BA~~+K;%w9=8gyfo^5U_#U|e1J{n>Awd*VfKef9d{ z5I2DR+spT?+Wg~RoBG%1i)+ML+EuspWj!aMRM{l9O@}!7B8v;HgFdCK(fWQKz`0=Z zu%#wvB4f}nR?gVpwqD6vSr5hEKl$YRwNv+9xVrG#?BWopu8iMzad!TXC%W-PA$|x{ z#ruw!SI~4I=8vgUg~a@>cprpS63)lZkALLHU|O1+E~pa-PpQvi z8_-puKwMNxa+YKkS9_DX*1dXfy)xNb)pL2B0{|N;^C{#cT zN4)yrj|toAMuX7yT4^n07YG~h;$})DAA2wJ5;{OBp+#&3mdRmVw=?m5d~EOIB@ux1 z$C~quSH_oJ_?ZK1&)#ub`q8&9+_4V~W{TvzfT~_t&#<>?}D8ZAl#__<$LF> z4}CAm8d(;1E|TfQL?7Sk{ne-b>c*2N-rUKABUF2R*PWM|pS_8jO9z+Rve|Tqn}?tx z6_#yEPg-Vfux$Jbg#LNj!Ae`)X$c}-v?+E65;pDO%jSkps5U##4WCO%;y_iLciOaw z%UZ%cslK@w-@?ot2$!y9<0L!?tHecS%9~jaG7DymVl3OCspQ6$oAnK98%EZuP_FqZ znu*v#r6 zATk$IhY6Q5P6nhuu;$D-r>T~v7znf8bLq$%vIfF*>~7coh`8c=vi3=+iQXH(IkKBc z%(up69uovhDNnX@WU$#Br52+pLYD03{?f}}HYiKUq)^0Jap!^Q!h=ezW9d=Z|-EqhkC1@b|A_6y6$TzHVv{} zBoJoz{Q6}re46aBc$;EjneeV$0{JSJ)$dK?N+|DY>_A7+dvqTU;p*N|2vbu zX-9Sz)|q4m3-lJd{*2=7T&w%aH4Ts}@&q5RMXo?tbjMng^G8LUa68&0o`#3%nH3P4 z8nR2?%uKqbbe@N?+o`(dq@e{hR{z{*IVb%mM$(hRW^SOkhUv?SO`5 zwj+d>aXUmo5f)K4A7f~m`0M6^&~Nvf+EnD%taLOfH(8>cS{p*54L?V(jK}OC0!Q~A zT%?;0Ik!yt&x?T2&q?>0k@%UiY#gTjRHFuvp1t@F1$XS$MA`rT<= z?24B*Er@(V;vR{4+`MdS%Cm@<(if86RyJ}4VR7tKq>*}ey3UKfzCZSqY*)OrX<=vL zE(>LArQBA4yq{MQw${q7BUrlAlE=I9TWDBRNiXB1*2j2G%5JUpEv!w8Y@S<|<3g!4 zC#%c~?CRh)6cEPmYsPnk#84&2 ziC?C`{b&rpsK-{Dn*1?{Q1fhGE4|Jhc2i@g#kDNEHLa%%+r7Rc9*HJ*&X01-g zh*&Z9RPs6Nk^J5Wgy~&T_a@&_TV*d!J^bwA(5tg=kL!u=&Hd;_rcmH$6)zayG5nbTtUG_fcoLYI1<(s>&;qD8yxLa1}gF-q#}1E_8|G zs?GvH$dh-)Ri<~D-wxMR5awf!JXg6{iLKCN8g1$-c$%%Zz*S9`IIdDXJKV2%T(aiI ziuN{PA*c;VC6j*ZdR1>?deNU_X8mh*e*q2iKBEg6WR6~**ndU{gy}3OFM}sfyngDp z_uAXu;;Rbz*aRfa?@YDn5O;1v`WQ`4DHdfOCbksx$gZD@nuE{~sdaUXZ7xdRUvJ-P zw)+o;cD7R6)QFi?2cg^#VaJ-qai&;WtgYNz=KYa7$>4)!m|IOL@=4~4o*t*}2ZKH#ssZm$j z3?IX15ajGMk+$5&*6zM#5aOK%6B98TO7!PDEd;`>1$RkYZ|c<1&s;J&R@1jU2#$7V z6Kr}^pY;c!UD?%{R##b;pm+CMq#^>suzrhhGkd#(;VI`)>)hM{g2|h<6}tHAaZS|X zY^sD*>xGL&^Cn$)LIu5?d)Dy>2(#7cI1Ry_va3$0mA1t1q7YPH*|%%~Mwwo*%6m z^@_yfC#%)-o3S5;8pSml(FG#VbjL5-?F)~3cP3jaRVIrhOiP!hq0WpYD;|u5p-D^z zXp1J+41~VhK=XB&yHC!1cJ4}gb2hpA@?^Ps2kvAaQ5)I5x#LUcdQ%S`d~uIYW8L)W zUfwiq$mi30Ed*h@BjcC0@ZR!Pb&Kp%mE_Hyr5jOL^%+2Dp5|*co_?n{GJ4C(-qa^g zyfuFEgk9CG8i|XwfNI@F9GV(X0*m3Vj+A>T|D6hYjsV$if{UESh}X<47wvuv+8L^q z>9_`74#o=zPlYz{v}oEDgi^)yYi4+E&;(DJ=hr*YK^W4{&s*CpPj$aVqEnx3O>;5N zK`?cZ3kVm58X=l#Vn-0>C+gN(y%v8DqpCO0T33)`|B5Xu2-7DcTvcTJQQkB?ekZ8-L_RUKqN2RzQ*#9T{Fy~6lt2b>UnEVO}%C&xmYI_C`drbc&gx@|{W*X-j8Qd9I4Bm1O+O3U_^!w*RmFm4l5Z0@W#&ePicX>`C5+^6?U7j<|Nv)fbt-;Hx`DSrU z1d=Yjr|cbuMxl59fbgW!&%B0)XPhy1SE>iHWyEcFL0H#!8s0WL^9QDOdSx~}s+}%K zb5KiOI2W6_!H=DT*cUX_%}>os5c<39qNmx;MND>5>?uLh+~lTBg}NP2@d_q_6^{CI zlV*5GR>fRd`P6rse;~|GZl*I7T{~E(Y%G<78^^D0Z-<}o5gWy7 zEe<_6`Ig$--W$K`^p0NrjR@um>vyNY6FRXk6rgg!_FW&J-FdI(N!m)BR#ughmPHl< zgzcsLKA$P>f4SLxd|AzebBVPI)vxC=@^X2KRnMx z2b<4s7l$60JogE3z1CZ5TkSz*?@zO(6&*BGh>OAMPl|xB%86z( z9W66+Oa<#|f4xe-@X%OO5NV6Lxw9Kk{T>@kS=-{$N}DF|x4wO?y3ax+E%wei&Zx?i zwLddTN7dPg+Gu6=t_gdlYo+p8Q#B@m>Q4bdqk4B0!&gn2xM<9;sUXxI7TIYo>S21G zdqm>+3O=#8Ri|pup0*}xK&8EeODkojUY?(-Q;c4Q*ZOVVfw2DeAn+r9oN0^WAG}*L zDH|=ow3N7LI0&+=FTp<=DpafQ=VKmf7U`U*C?DFT@*%dwJ)Z2dtho!Jt{NHJ*hXfA zRGC=Qma(*aiNx9QMjoHt_vMsRTxRt0^dt9tbfs+CNM}W0sS;y!KL-Uup#YM_++}^w zT`e;T&5A&nt{T|fqiRJxGpsWxwm6^L<~f+nia-%=fx73T+zqU0K^?5S%%~Yok`thb zvG@Y}wx5(t08iOmtP`>!ZmIForUSf` zTU+b%GCZE%nQT|nGQZ-Lo2;#pI2sx*-L2ki3Id^2RM`wFlMdn0Qa&ELF#o-=r_ah+ z+G`6#tIPIzr)7Vvk7p2e!aRN1xkf1Fw-W6{(^*Q{7M@MLRMe$1Ej%^8Oxw1sjJl?H zgnxSXV9Z|EvwdFHuYA?7dTCme*QcSBudm!r1Xj#RnZ#nQPS>YF7{f`wzb=*xpALel zojD!*`C}#mK)6ZiL}I#AnfuU5$;A+3S92#DxmL z{oSBhc7ZLp%a*;-i#;dM+}$q4d^EHm!twh8KPRhA!DOvF2$7;{oRs+w&L5RcBAcF) zD~hmr`GxVtA?m##dT-9d2t7hi2e?lL)Xz1bTa{jw(M#bbXVaV0%q!!6)8}N!ZC=?( zqHb)M_SwW>dCRJ;D%7%jjC!U?sKCa@vh(O=UOV2&;Pm=8EuL{u6*%?ao&VU+?|iu~mmJPHlWvPj!Ij-hQscJ?PYY@AGo7t+>C~ zhPb89rU)@w{rD{WKI8q#NBfiS+mk0$rVcmw&^6tqEO%A(!nSlwIq3cUq0i@vKB$Ua zU05~wNBc$&$hIXAmES&@mFO<~6}}2|`cw(^X+woLS!=GJWh33OVG_J!U{ z-FOXz$dBftSl-2h{z_hCex>rtbyZm=P`8!W@?)l1i7kA{jcj|(r+8uc|9pbD8($c-%V1@-w5{Ja` z@s)lJ5kfL zB@cuX4QzIh+gIXGsP5@~^YrE)zdQ}D2PU${}F9V1{*7ZC|%8Wc`Ta> zadUGanU(NQ?oE?3dqkzwy!GBQWf!aS8tjkp%;1vMJn*=`7nFGewpviMr-Xz9`q{9>kU=nd{w>vyJ$rWPpQh#fp3ndVAAnMdXINC zoK5-z@dY5Ww~)JR339G!63@{vTVi_gAe4^0^yA58IEz_@a_z<{&l1Y1#f3 zD`|48_#<pf7koL%zxY|^I?ak*t_3F4IC74Q({ut6H3Iz zBUqq(H3Wn+&N;Dt>Q2piyK(AnPH>+)7Fn~W{+h~F*qkMEH!=1Ne1AH%dT8#7NSDl) zii~wN{}eB0%oS*AAZKg5w#DzQ(o?0fjbFH!?zfogX}q@*{L~HW&K7}C5ZT-`li)8+ zSFyG+6)cc2YgBI=hTJ9u9XRpm!|dlGXON5P9l}jpC$TQ_!CekzTaDZFP2!h8nDwB| z*bVkT;Fp+yh_xFVXFjn1f8Lx;8EkY5y^2r9WxY3XkD)?bjXrb^1%xt-LZ-Yy#imGF zQLbE+xilFCWg{REHfhu3JP(=`SCM(*#oxUSw(WK%Bkxj!oU@e7%Ae4zaDiy@r^hyR7ac5<1Q=f+5ZN{p}Tp3ST*MAD#?mDpP z*RolLaNBsyC3|MPADay#rH)-WdGzPi9ZqE}{#fXM!yYhVdGYvw&K2nP!i-0iiFxZnHWSmb-y4tnW|Ui^Neg2$zd| ze^_R{?3=peo+pqXeYej4^4==3Mi-I?w)FIuO^vu*F5aILZDbMp?T4VJ;~JNX=XuH9 zK)3eiah4tz4F^T)@!rU^(1HK?>wSJdP(QkMNjnJ3C##s|=Byres41OH-`53>?mA(` z)s>>kil!4D-O!@VTT<<+aY!vzBlK$|=;_DCZdP_{96fuinn!vEj_Iy z9Mv?5i?qY{f67TRc3iVb*Ph%4VK%SJ^K_6NJx{|tK6@^cUYhJWjk6xRdS*Ar$rJY< zp}qnZCNkN$^`&#YsRs|fxTlLfP44<0Xo~j;8^3T&xSnI@);IgtcHvhk}6hMQ(qqU&u6pqY#0sZEu**$G!a8-(tOKI6-XjQrPJZ z>6S~Hma?t=NcWLsr`mTvcrKco{sxk1hJae}*W6p$9;g7QpSsrrB)qAgVZD>J<#UDlbE2QD`F5-*ma>-p| z`s@>&49ybT@kefpVXOrRv1`@jO{S|kiybF%{64Y1+_-q({MU{x4xJwb(;zp2>8Z^0 zL?)<;CV*{v#8v*V9#Vthv&hbbs;r+@aoK5SCTw~DAcT`=)dcgnibBq)4|uyt;XbXt zI`Qr+o>u>!?SBQn+m?i%hbzyi6PkL9=yS>W#nc3~- z$;WQ~lzy!t^|NIkmlOX7uccoDd|TA>AQdP2{5h}g#W|%YH~sF<=%3|po^8AO-kgdi zX4LPDE1Dcvf1nQEyH|a_PyKzc^ob5D$rw`i2A@{%dsaQ`gnHLGbxQvQ^;Lrq8Gr*P z)qBcKE*cHUxAti|sd&3X{p*N|APkzv)hmm{eNGyju*`{6* zIhgMA;kf$Uhmxn%|DIQ`aaz#;DVS6r5A~ndMn0w9L#mu-ZhrSvlI5@FF5EXiFHg_s F{|9}VN*MqE diff --git a/temp_calculate_sign.js b/temp_calculate_sign.js deleted file mode 100644 index f183918..0000000 --- a/temp_calculate_sign.js +++ /dev/null @@ -1,59 +0,0 @@ - -const { signRequest } = require('./app/lib/api_sign.js'); - -const query = { - app_key: 'APP2024011514301234', - method: 'openapi.index', - sign: '806b7294f2545bf20eb1fdf244e7ff28', - timestamp: 1777222912, - v: '1.0', -}; - -const body = {}; -const self_app_secret = 'sec_abc123def456ghi789jkl012mno345pqr678stu901vwx234yz'; -const providedSign = '806b7294f2545bf20eb1fdf244e7ff28'; - -try { - const { canonicalQuery, bodySign, sign } = signRequest({ - query, - body, - selfAppSecret: self_app_secret, - }); - - console.log(`canonicalQuery: ${canonicalQuery}`); - console.log(`bodySign: ${bodySign}`); - console.log(`Calculated sign: ${sign}`); - console.log(`Provided sign: ${providedSign}`); - console.log(`Signs match: ${sign === providedSign}`); - - if (sign !== providedSign) { - console.log('---'); - console.log('Mismatch reason analysis:'); - - // 1. CanonicalQuery check - const expectedCanonicalQuery = 'app_key=APP2024011514301234&method=openapi.index×tamp=1777222912&v=1.0'; - if (canonicalQuery !== expectedCanonicalQuery) { - console.log(`- CanonicalQuery calculation might be incorrect. Expected "${expectedCanonicalQuery}" but got "${canonicalQuery}". This could be due to wrong sorting order or incorrect handling of parameters.`); - } - - // 2. BodySign check - const crypto = require('crypto'); - const expectedBodySign = crypto.createHash('md5').update('{}').digest('hex'); - if (bodySign !== expectedBodySign) { - console.log(`- BodySign calculation might be incorrect. For an empty object {}, expected "${expectedBodySign}" but got "${bodySign}". This could be due to differences in JSON serialization (e.g., whitespace).`); - } - - // 3. Final hash check - const signText = `${canonicalQuery}${self_app_secret}${bodySign}`; - const expectedSign = crypto.createHash('md5').update(signText).digest('hex'); - if (sign !== expectedSign) { - console.log(`- The final hash calculation seems to be the issue. The string to be signed was "${canonicalQuery}${self_app_secret}${bodySign}". The resulting hash did not match the provided sign.`); - } - - console.log('- The most likely reason is an error in the signing logic itself or a discrepancy in how the components (canonical query, body sign, secret) are combined before hashing.'); - - } - -} catch (error) { - console.error('An error occurred during signature calculation:', error); -} diff --git a/temp_check_json.js b/temp_check_json.js deleted file mode 100644 index ded1ccc..0000000 --- a/temp_check_json.js +++ /dev/null @@ -1,39 +0,0 @@ -const fs = require('fs'); -const s = fs.readFileSync('methods/system.json', 'utf8'); -const stack = []; -let inStr = false; -function isEscaped(str, idx) { - let cnt = 0; let j = idx - 1; while (j >= 0 && str[j] == '\\') { cnt++; j--; } return cnt % 2 === 1; -} -for (let i = 0; i < s.length; i++) { - const c = s[i]; - - if (c === '"' && !isEscaped(s, i)) { - inStr = !inStr; - } - if (inStr) continue; - if (c === '{' || c === '[') stack.push({ c, pos: i }); - else if (c === '}') { - if (!stack.length || stack[stack.length - 1].c !== '{') { - console.log('UNMATCHED } at', i); - break; - } - stack.pop(); - } else if (c === ']') { - if (!stack.length || stack[stack.length - 1].c !== '[') { - console.log('UNMATCHED ] at', i); - break; - } - stack.pop(); - } -} -if (stack.length) { - console.log('STACK NOT EMPTY len', stack.length); - stack.forEach(x => { - console.log('---STACK ITEM---'); - console.log(x.c, x.pos); - console.log(s.slice(Math.max(0, x.pos - 120), x.pos + 120)); - }); -} else { - console.log('ALL MATCHED'); -} diff --git a/temp_count_brackets.js b/temp_count_brackets.js deleted file mode 100644 index aac7d39..0000000 --- a/temp_count_brackets.js +++ /dev/null @@ -1,19 +0,0 @@ -const fs = require('fs'); -const s = fs.readFileSync('methods/system.json', 'utf8'); -function isEscaped(str, idx) { let cnt = 0; let j = idx - 1; while (j >= 0 && str[j] == '\\') { cnt++; j--; } return cnt % 2 === 1; } -let inStr = false, - open = 0, - close = 0, - openB = 0, - closeB = 0; -for (let i = 0; i < s.length; i++) { - const c = s[i]; - if (c === '"' && !isEscaped(s, i)) inStr = !inStr; - if (inStr) continue; - if (c === '[') open++; - if (c === ']') close++; - if (c === '{') openB++; - if (c === '}') closeB++; -} -console.log('square [ count', open, ' ] count', close, ' diff', open - close); -console.log('curly { count', openB, ' } count', closeB, ' diff', openB - closeB); diff --git a/temp_debug_headers.js b/temp_debug_headers.js deleted file mode 100644 index 2271ecb..0000000 --- a/temp_debug_headers.js +++ /dev/null @@ -1,5 +0,0 @@ -const fs = require('fs'); -const s = fs.readFileSync('methods/system.json', 'utf8'); -const ph = s.indexOf('"headers"'); -console.log('headers@index', ph); -if (ph !== -1) { const posOpen = s.indexOf('[', ph); console.log('open@[', posOpen, ']'); console.log('---snippet---'); console.log(s.slice(Math.max(0, posOpen - 120), posOpen + 400)); console.log('---end---'); } diff --git a/temp_find_headers_close.js b/temp_find_headers_close.js deleted file mode 100644 index 49b3ac1..0000000 --- a/temp_find_headers_close.js +++ /dev/null @@ -1,15 +0,0 @@ -const fs = require('fs'); -const s = fs.readFileSync('methods/system.json', 'utf8'); -function isEscaped(str, idx) { let cnt = 0; let j = idx - 1; while (j >= 0 && str[j] == '\\') { cnt++; j--; } return cnt % 2 === 1; } -const ph = s.indexOf('"headers"'); -const posOpen = s.indexOf('[', ph); -let depth = 0; let inStr = false; let posClose = -1; -for (let i = posOpen; i < s.length; i++) { - const c = s[i]; - if (c == '"' && !isEscaped(s, i)) inStr = !inStr; - if (inStr) continue; - if (c == '[') depth++; - else if (c == ']') { depth--; if (depth === 0) { posClose = i; break; } } -} -console.log('posOpen', posOpen, 'posClose', posClose); -console.log(s.slice(posClose - 40, posClose + 40)); diff --git a/temp_find_missing_commas.js b/temp_find_missing_commas.js deleted file mode 100644 index f56904e..0000000 --- a/temp_find_missing_commas.js +++ /dev/null @@ -1 +0,0 @@ -const fs = require('fs'); const s = fs.readFileSync('methods/system.json', 'utf8'); const re = /}\s*\n\s*\{/g; let found = false; while (true) { const m = re.exec(s); if (!m) break; const idx = m.index; let j = idx - 1; while (j >= 0 && /\s/.test(s[j])) j--; const prev = s[j] || ''; if (prev !== ',') { found = true; const start = Math.max(0, idx - 60); const end = Math.min(s.length, idx + 60); console.log('---possible missing comma at', idx, 'prevChar:', prev); console.log(s.slice(start, end)); console.log('---'); } } if (!found) console.log('No obvious }\n{ without comma found'); diff --git a/temp_find_objsep.js b/temp_find_objsep.js deleted file mode 100644 index ab981c1..0000000 --- a/temp_find_objsep.js +++ /dev/null @@ -1 +0,0 @@ -const fs = require('fs'); const s = fs.readFileSync('methods/system.json', 'utf8'); const re = /}\s*\n\s*{\s*"method"\s*:/g; let m; let found = false; while (m = re.exec(s)) { const idx = m.index; let j = idx - 1; while (j >= 0 && /\s/.test(s[j])) j--; const prev = s[j] || ''; if (prev !== ',') { found = true; const start = Math.max(0, idx - 80); const end = Math.min(s.length, idx + 80); console.log('---missing comma between objects at', idx, 'prevChar:', prev); console.log(s.slice(start, end)); console.log('---'); } } if (!found) console.log('No missing-comma-between-method-objects found'); diff --git a/temp_find_trailing_commas.js b/temp_find_trailing_commas.js deleted file mode 100644 index 71215a4..0000000 --- a/temp_find_trailing_commas.js +++ /dev/null @@ -1 +0,0 @@ -const fs = require('fs'); const s = fs.readFileSync('methods/system.json', 'utf8'); const re = /(,\s*\n\s*\])/g; let m; let found = false; while (m = re.exec(s)) { found = true; const idx = m.index; const start = Math.max(0, idx - 60); const end = Math.min(s.length, idx + 60); console.log('---trailing comma before ] at', idx); console.log(s.slice(start, end)); console.log('---'); } if (!found) console.log('No ",\n]" patterns found'); diff --git a/temp_parse_json.py b/temp_parse_json.py deleted file mode 100644 index fc628d9..0000000 --- a/temp_parse_json.py +++ /dev/null @@ -1,13 +0,0 @@ -import json -s=open('methods/system.json','r',encoding='utf8').read() -try: - json.loads(s) - print('py OK') -except json.decoder.JSONDecodeError as e: - print('JSONDecodeError:', e.msg, 'lineno', e.lineno, 'colno', e.colno, 'pos', e.pos) - start=max(0,e.pos-120) - print('---context---') - print(s[start:e.pos+120]) - print('---end---') -except Exception as e: - print('other error',e) diff --git a/temp_rebuild_system_json.js b/temp_rebuild_system_json.js deleted file mode 100644 index 576eb6a..0000000 --- a/temp_rebuild_system_json.js +++ /dev/null @@ -1,49 +0,0 @@ -const fs = require('fs'); -const path = 'methods/system.json'; -const s = fs.readFileSync(path, 'utf8'); -function isEscaped(str, idx) { let cnt = 0; let j = idx - 1; while (j >= 0 && str[j] == '\\') { cnt++; j--; } return cnt % 2 === 1; } -// find headers key -const ph = s.indexOf('"headers"'); -if (ph === -1) { console.error('no headers key'); process.exit(1); } -const posOpen = s.indexOf('[', ph); -if (posOpen === -1) { console.error('no [ after headers'); process.exit(1); } -// find matching closing bracket for headers -let depth = 0; let inStr = false; let posClose = -1; -for (let i = posOpen; i < s.length; i++) { - const c = s[i]; - if (c == '"' && !isEscaped(s, i)) inStr = !inStr; - if (inStr) continue; - if (c == '[') depth++; - else if (c == ']') { depth--; if (depth === 0) { posClose = i; break; } } -} -if (posClose === -1) { console.error('cannot find headers close'); process.exit(1); } -const preHeader = s.slice(0, posOpen); -const headerContent = s.slice(posOpen, posClose + 1); -// find first group start after posClose -const gNameIndex = s.indexOf('"groupName"', posClose + 1); -if (gNameIndex === -1) { console.error('no groupName found after headers'); process.exit(1); } -// find the starting '{' before this groupName -let groupStart = s.lastIndexOf('{', gNameIndex); -if (groupStart === -1 || groupStart <= posClose) { - // try to find next '{' after posClose which encloses group - groupStart = s.indexOf('{', posClose + 1); -} -if (groupStart === -1) { console.error('cannot find group object start'); process.exit(1); } -// find the groups tail closers (we expect existing file to end with ]\n }\n} -const tailPattern = '\n ]\n }\n}'; -let tailIndex = s.lastIndexOf(tailPattern); -if (tailIndex === -1) { - // fallback: try shorter pattern - tailIndex = s.lastIndexOf('\n }\n}\n'); -} -if (tailIndex === -1) { - // fallback use end of file - tailIndex = s.length; -} -// groups content is from groupStart to the position before tailPattern -const groupsContent = s.slice(groupStart, tailIndex); -// build new content -const newContent = preHeader + headerContent + ',\n "methods": {\n "groups": [\n' + groupsContent.replace(/^\s*/, '') + '\n ]\n }\n}'; -// write to file -fs.writeFileSync(path, newContent, 'utf8'); -console.log('rewritten', path); diff --git a/tmp_mig_conn_dev.txt b/tmp_mig_conn_dev.txt deleted file mode 100644 index dbaf551..0000000 --- a/tmp_mig_conn_dev.txt +++ /dev/null @@ -1,8 +0,0 @@ -{ - "env": "development", - "host": "112.124.21.102", - "port": 3306, - "database": "wms", - "username": "wms", - "password": "******" -} diff --git a/tmp_mig_migrate_output.txt b/tmp_mig_migrate_output.txt deleted file mode 100644 index 7e9fa00980d189e155beb2c8a2245aa629fdef92..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1484 zcmd6nO>YxH42FG1;umlklWWx2h#1>?{L_K`VQ!&>%?xoaMiW2?xBa3jNRC-!O;iN z3{AmWvf$F8qpNUUn$)i7b7XIRxtZ8Iq!oP1!)w+9EcCIFGvBbAxy_O93*@qxqY(!a zn}Sa#i?xk0Qk_WXALzkjt8%7f=KywUwoh!kXuI~*ns&;*M%;%)9+2c%o-t+{adlYF zuoDrA$!qW?@ONQtd(M8qKDhVI+c^@wzyhtJ6sCAHayWN>6vMW)F_MDwVqG_%Tva?P2J3WpJ_$+9_4irr&?{s`9i~s6y*^_KPr;5ssCSv8EBO%r57)brwaPzP zxxm{53yC)&7qZX)O%tNs%(|Gd=blezco)ygkS4jFF;CgWD%_6onEV^kR`!xr z%IX$(6Z@*O8Ih~DV~nw)RcQ@$BU(yiJ$#j?qYsT$uU%#KWP-TulJluK}lftJOT_Ioa24x)4hW;XP^aJx$`t1M! diff --git a/tmp_mig_migrate_output_utf8.txt b/tmp_mig_migrate_output_utf8.txt deleted file mode 100644 index 1f3eae6..0000000 --- a/tmp_mig_migrate_output_utf8.txt +++ /dev/null @@ -1,17 +0,0 @@ - -Sequelize CLI [Node: 24.14.0, CLI: 6.6.3, ORM: 6.37.7] - -Loaded configuration file "database\config.js". -Using environment "development". -node.exe : (node:42104) [DEP0176] DeprecationWarning: fs.R_OK is deprecated, us -e fs.constants.R_OK instead -所在位置 行:1 字符: 1 -+ & "C:\Program Files\nodejs/node.exe" "C:\Program Files\nodejs/node_mo ... -+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - + CategoryInfo : NotSpecified: ((node:42104) [D...ts.R_OK instead - :String) [], RemoteException - + FullyQualifiedErrorId : NativeCommandError - -(Use `node --trace-deprecation ...` to show where the warning was created) -No migrations were executed, database schema was already up to date. - diff --git a/tmp_mig_post_columns.txt b/tmp_mig_post_columns.txt deleted file mode 100644 index 33135f5..0000000 --- a/tmp_mig_post_columns.txt +++ /dev/null @@ -1,14 +0,0 @@ -{ - "client": "wms", - "rowCount": 1, - "rows": [ - { - "Field": "platid", - "Type": "int", - "Null": "YES", - "Key": "", - "Default": null, - "Extra": "" - } - ] -} diff --git a/tmp_mig_post_meta.txt b/tmp_mig_post_meta.txt deleted file mode 100644 index d959d2d..0000000 --- a/tmp_mig_post_meta.txt +++ /dev/null @@ -1,7 +0,0 @@ -{ - "client": "wms", - "rowCount": 0, - "rows": [ - - ] -} diff --git a/tmp_mig_pre_columns.txt b/tmp_mig_pre_columns.txt deleted file mode 100644 index 33135f5..0000000 --- a/tmp_mig_pre_columns.txt +++ /dev/null @@ -1,14 +0,0 @@ -{ - "client": "wms", - "rowCount": 1, - "rows": [ - { - "Field": "platid", - "Type": "int", - "Null": "YES", - "Key": "", - "Default": null, - "Extra": "" - } - ] -} diff --git a/tmp_mig_pre_meta.txt b/tmp_mig_pre_meta.txt deleted file mode 100644 index d959d2d..0000000 --- a/tmp_mig_pre_meta.txt +++ /dev/null @@ -1,7 +0,0 @@ -{ - "client": "wms", - "rowCount": 0, - "rows": [ - - ] -} diff --git a/tmp_sequelizemeta_check.json b/tmp_sequelizemeta_check.json deleted file mode 100644 index ba7a7fef0379c256764195f94accfbacdf8db860..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 218 zcmezW&zT{IA(J7MA&;Si!HPkFp`0O?p_qY}fr}xCAs@&q28${HWemWg)nF3D2SFu< zWF-AcP_;@>Q(y?GQwO|qe DLBkp< diff --git a/tmp_sequelizemeta_check_utf8.json b/tmp_sequelizemeta_check_utf8.json deleted file mode 100644 index d959d2d..0000000 --- a/tmp_sequelizemeta_check_utf8.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "client": "wms", - "rowCount": 0, - "rows": [ - - ] -} diff --git a/tmp_show_columns_platid.json b/tmp_show_columns_platid.json deleted file mode 100644 index 4b5db6915ad521fdda675ccc977986f2fcba0bbe..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 748 zcmbV}I}5@<5QL`|{10Jk8(Z5L8^JfCyXc_11&xUi4=c4qUq zy9g1$M}!muI5=aE1YLA6#eq?xS%;OrX0Lji*c`#8^j>VQSc;%m>yDM_@;>Rr{6+sm zXTk|am4ju4l+SN|tNNPtdPXo({~@-;EWwek*4#*-*{X{=p&1M2$jI04?2)%65y Cx<~N< diff --git a/tmp_show_columns_platid_utf8.json b/tmp_show_columns_platid_utf8.json deleted file mode 100644 index 33135f5..0000000 --- a/tmp_show_columns_platid_utf8.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "client": "wms", - "rowCount": 1, - "rows": [ - { - "Field": "platid", - "Type": "int", - "Null": "YES", - "Key": "", - "Default": null, - "Extra": "" - } - ] -} diff --git a/tmp_show_create_table.json b/tmp_show_create_table.json deleted file mode 100644 index 3485135fd05f5c0e097d91abcca53241aa74129d..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2754 zcmdUx&uXd4@iNe^YkN~}eJ9*orm+ASr@kFd1H7>#%TE#u$g z$)oz2S*Wlqk@V0=Uf}J{%zN{l@6MZfzkh{#r>1lq`0k9^ON{|omxU9q*qGQoqPD(KbRPE-Gj^E|#qeO3~v zp_bZ25nuV5;*T^$-h!Dk5RYIc8&P(*#rHrVD`Vd!CXPIBAzYWWhpy}vdn)O`pPLgV z7m+lvEb15*&1aMEFwiM}On!;C5t4JCi`vnq?jjHM1TQsyq5G;KtK+A^eBn_(AjY=t zxos5;2Un=(^^rQBGckTza1`OK%c?_FeYZm$`Ra`sgncY~OAu~@ap#6GJ|g1B#AOIA z@;t0v&rXZ(4Adu}j$mj+q Date: Sun, 7 Jun 2026 01:52:06 +0800 Subject: [PATCH 066/550] 1 --- app/model/express_interface.js | 2 +- .../systemMethods/order/pendingOrder.js | 158 +++++++++++++++++- app/service/systemMethods/pickCart.js | 1 + app/service/systems/delivery_order.js | 26 +++ app/service/systems/express.js | 8 +- app/service/systems/setting/express.js | 37 +++- .../systems/setting/expressInterface.js | 22 +-- app/service/systems/stock_store.js | 103 ++++++++---- app/service/systems/storage/inventory.js | 4 + ...ique-platform-code-from-express-setting.js | 102 +++++++++++ ...ate-id-to-varchar-wms-express-interface.js | 62 +++++++ methods/changes/system.json | 43 +++++ methods/system.json | 92 +++++----- 13 files changed, 572 insertions(+), 88 deletions(-) create mode 100644 database/migrations/20260606-remove-unique-platform-code-from-express-setting.js create mode 100644 database/migrations/20260606000000-change-template-id-to-varchar-wms-express-interface.js diff --git a/app/model/express_interface.js b/app/model/express_interface.js index f9dd3fe..b31e991 100644 --- a/app/model/express_interface.js +++ b/app/model/express_interface.js @@ -52,7 +52,7 @@ module.exports = app => { comment: '平台店铺ID', }, template_id: { - type: BIGINT(20).UNSIGNED, + type: STRING(50), allowNull: true, comment: '模板ID', }, diff --git a/app/service/systemMethods/order/pendingOrder.js b/app/service/systemMethods/order/pendingOrder.js index 8073a08..690818c 100644 --- a/app/service/systemMethods/order/pendingOrder.js +++ b/app/service/systemMethods/order/pendingOrder.js @@ -28,9 +28,9 @@ class PendingOrderService extends OrderBaseService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,updateOrderPlatform,updateOrderExpress,cloneOrder,createOrder,parseAddress'; + const _noNeedRight = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,updateOrderPlatform,updateOrderExpress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress'; const _noNeedLog = 'list,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,parseAddress'; - const _noNeedAuth = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,updateOrderPlatform,updateOrderExpress,cloneOrder,createOrder,parseAddress'; + const _noNeedAuth = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,updateOrderPlatform,updateOrderExpress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -2039,6 +2039,7 @@ class PendingOrderService extends OrderBaseService { logisticsName: String(requestData.logistics_name || '').trim(), isUrgency: [ 'Y', 'N' ].includes(requestData.is_urgency) ? requestData.is_urgency : 'N', invoiceFlag: [ 'Y', 'N' ].includes(requestData.invoice_flag) ? requestData.invoice_flag : 'N', + shopNick: String(requestData.shop_nick || requestData.shopNick || '').trim(), receiverInfo: { name, mobile, @@ -2071,7 +2072,7 @@ class PendingOrderService extends OrderBaseService { } // 重复订单视为错误(与原逻辑保持一致) - if (result.message === '订单已存在') { + if (result.message === '订单已存在' || (result.data && result.data.deliveryOrderId)) { throw new Error(`订单号 ${deliveryOrderCode} 已存在`); } @@ -2089,6 +2090,157 @@ class PendingOrderService extends OrderBaseService { }); } + /** + * 下载创建订单导入模板。 + * + * 返回 base64 编码的 Excel 文件内容,前端解码后作为 .xlsx 文件下载。 + * + * @return {Promise} 统一 success 包装,含 base64 字符串与文件名。 + */ + async downloadCreateTemplate() { + const ExcelJS = require('exceljs'); + const workbook = new ExcelJS.Workbook(); + const sheet = workbook.addWorksheet('创建订单导入模板'); + + const columns = [ + // 必填 + { header: '*订单号', key: 'delivery_order_code', width: 24 }, + { header: '*收件人姓名', key: 'name', width: 16 }, + { header: '*手机号(mobile/tel至少填一项)', key: 'mobile', width: 28 }, + { header: '*详细地址', key: 'detail_address', width: 36 }, + { header: '*商品编码', key: 'item_code', width: 20 }, + { header: '*计划数量', key: 'plan_qty', width: 12 }, + // 非必填 + { header: '货主ID', key: 'store_id', width: 12 }, + { header: '电话', key: 'tel', width: 16 }, + { header: '省份', key: 'province', width: 12 }, + { header: '城市', key: 'city', width: 12 }, + { header: '区/县', key: 'area', width: 12 }, + { header: '镇/街道', key: 'town', width: 12 }, + { header: '邮编', key: 'zip_code', width: 12 }, + { header: '快递编码', key: 'logistics_code', width: 16 }, + { header: '快递名称', key: 'logistics_name', width: 16 }, + { header: '系统平台编码', key: 'sys_platform_code', width: 16 }, + { header: '来源平台编码', key: 'source_platform_code', width: 16 }, + { header: '来源订单号', key: 'source_order_codes', width: 20 }, + { header: '订单类型', key: 'order_type', width: 14 }, + { header: '是否紧急(Y/N)', key: 'is_urgency', width: 16 }, + { header: '是否需要发票(Y/N)', key: 'invoice_flag', width: 18 }, + { header: '商品名称', key: 'item_name', width: 24 }, + { header: '行号', key: 'order_line_no', width: 10 }, + { header: '实际价格', key: 'actual_price', width: 12 }, + { header: '店铺名称', key: 'shop_nick', width: 20 }, + ]; + + sheet.columns = columns; + + const headerRow = sheet.getRow(1); + headerRow.eachCell((cell, colNumber) => { + const col = columns[colNumber - 1]; + const isRequired = col && col.header.startsWith('*'); + cell.font = { bold: true, color: { argb: 'FF000000' } }; + cell.fill = { + type: 'pattern', + pattern: 'solid', + fgColor: { argb: isRequired ? 'FFFFC000' : 'FFD9D9D9' }, + }; + cell.alignment = { vertical: 'middle', horizontal: 'center', wrapText: true }; + cell.border = { + top: { style: 'thin' }, + left: { style: 'thin' }, + bottom: { style: 'thin' }, + right: { style: 'thin' }, + }; + }); + headerRow.height = 36; + + sheet.addRow({ + delivery_order_code: 'ORD20260421001', + store_id: 1, + name: '张三', + mobile: '13800138000', + tel: '', + detail_address: 'XX路XX号', + province: '广东省', + city: '深圳市', + area: '南山区', + town: '', + zip_code: '518000', + logistics_code: 'STO', + logistics_name: '申通快递', + sys_platform_code: 'TB', + source_platform_code: '', + source_order_codes: '', + order_type: '', + is_urgency: 'N', + invoice_flag: 'N', + item_code: 'SKU001', + item_name: '商品A', + plan_qty: 2, + order_line_no: '1', + actual_price: 9.90, + shop_nick: '', + }); + + sheet.addRow({ + delivery_order_code: 'ORD20260421001', + store_id: 1, + name: '张三', + mobile: '13800138000', + tel: '', + detail_address: 'XX路XX号', + province: '广东省', + city: '深圳市', + area: '南山区', + town: '', + zip_code: '518000', + logistics_code: 'STO', + logistics_name: '申通快递', + sys_platform_code: 'TB', + source_platform_code: '', + source_order_codes: '', + order_type: '', + is_urgency: 'N', + invoice_flag: 'N', + item_code: 'SKU002', + item_name: '商品B', + plan_qty: 1, + order_line_no: '2', + actual_price: 19.90, + shop_nick: '', + }); + + const noteSheet = workbook.addWorksheet('填写说明'); + noteSheet.getColumn(1).width = 80; + const notes = [ + '【填写说明】', + '1. 带 * 的列为必填项,表头背景为橙色。', + '2. 每一行代表一条商品明细;同一订单的多个商品,订单号(delivery_order_code)必须相同。', + '3. 同一订单的所有行中,订单头信息(收件人、地址等)取第一行的值,后续行可省略但不影响解析。', + '4. mobile 和 tel 至少填写一项。', + '5. 计划数量(plan_qty)必须为正整数。', + '6. 是否紧急、是否需要发票只接受 Y 或 N(大写),不填默认 N。', + '7. 快递编码、系统平台编码不填时,系统会读取货主默认策略自动补充;不填货主ID时,系统会从当前登录用户的上下文自动获取。', + '8. 同一文件内,相同订单号只会创建一个订单,不会重复创建。', + ]; + notes.forEach((note, i) => { + const row = noteSheet.getRow(i + 1); + row.getCell(1).value = note; + if (i === 0) { + row.getCell(1).font = { bold: true, size: 13 }; + } + }); + + const buffer = await workbook.xlsx.writeBuffer(); + const base64 = Buffer.from(buffer).toString('base64'); + + return this.success('ok', { + base64, + filename: '创建订单导入模板.xlsx', + mime: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + }); + } + } module.exports = PendingOrderService; diff --git a/app/service/systemMethods/pickCart.js b/app/service/systemMethods/pickCart.js index 3f9ac10..64479c6 100644 --- a/app/service/systemMethods/pickCart.js +++ b/app/service/systemMethods/pickCart.js @@ -293,6 +293,7 @@ class PickCartService extends MainService { const result = await service.systems.pickCart.codeDuplicateCheck({ cartCode, excludeCartId, + warehouseId: this.getWarehouseId(), }); return this.success('ok', { data: result, diff --git a/app/service/systems/delivery_order.js b/app/service/systems/delivery_order.js index 0c94204..1512fd3 100644 --- a/app/service/systems/delivery_order.js +++ b/app/service/systems/delivery_order.js @@ -1260,6 +1260,32 @@ class DeliveryOrderService extends Service { items_str_length: items_str.length, items_preview: items_str.substring(0, 100) + (items_str.length > 100 ? '...' : ''), }); + } else if (lineData.length > 0) { + // MANUAL 降级:stockQuantityMap 为空时,从 lineData 直接计算统计 + stock_count = lineData.length; + item_total_count = lineData.reduce((sum, ld) => sum + (Number(ld.plan_qty) || 0), 0); + total_weight = 0; + // items_str 用 item_id 作为标识 + const itemEntries = new Map(); + for (const ld of lineData) { + const iid = Number(ld.item_id) || 0; + const qty = Number(ld.plan_qty) || 0; + itemEntries.set(iid, (itemEntries.get(iid) || 0) + qty); + } + items_str = Array.from(itemEntries.entries()) + .sort(([a], [b]) => a - b) + .map(([iid, qty]) => `${iid}+${qty}`) + .join('|'); + source_order_codes = new Set(lineData.map(line => line.source_order_code).filter(code => code)); + + ctx.logger.debug('[订单统计信息-MANUAL降级]', { + orderId, + stock_count, + item_total_count, + total_weight, + items_str_length: items_str.length, + items_preview: items_str.substring(0, 100) + (items_str.length > 100 ? '...' : ''), + }); } if (errors.length > 0) { diff --git a/app/service/systems/express.js b/app/service/systems/express.js index faec8a3..e7d38a1 100644 --- a/app/service/systems/express.js +++ b/app/service/systems/express.js @@ -740,11 +740,14 @@ class ExpressService extends Service { const expressCode = String(row.express_code || '').trim(); const expressItem = expressMap instanceof Map ? expressMap.get(expressCode) : null; - const label = this.buildMergedExpressLabel(code, expressItem); + const settingName = String(row.name || '').trim(); + const label = settingName + ? `${code} (${settingName})` + : this.buildMergedExpressLabel(code, expressItem); return { code, - name: label, + name: settingName || code, value: code, label, is_system_setting: true, @@ -775,6 +778,7 @@ class ExpressService extends Service { const where = { warehouse_id: normalizedWarehouseId, + deleted_at: null, }; if (normalizedExpressCode) { diff --git a/app/service/systems/setting/express.js b/app/service/systems/setting/express.js index 30a05f1..aa4590f 100644 --- a/app/service/systems/setting/express.js +++ b/app/service/systems/setting/express.js @@ -71,11 +71,46 @@ class SettingExpressService extends Service { /** * 清理当前仓库快递列表缓存。 * + * 优先通过 Redis keys 通配扫描删除所有 express:list* 变体, + * 若 Redis 不可用则降级为逐键删除已知命名键,确保核心缓存必清。 + * * @param {number|string} warehouseId 仓库主体ID * @return {Promise} */ async clearExpressListCache(warehouseId) { - await this.deleteCacheByKey(this.getExpressListCacheKey(warehouseId)); + const { app, ctx } = this; + + // 优先:Redis 通配扫描删除所有 express:list* 变体 + try { + const redisClient = app.redis && typeof app.redis.get === 'function' + ? app.redis.get('cache') + : null; + if (redisClient && typeof redisClient.keys === 'function') { + const matchedKeys = await redisClient.keys('express:list*'); + if (Array.isArray(matchedKeys) && matchedKeys.length > 0) { + await redisClient.del(...matchedKeys); + } + } + } catch (err) { + if (ctx && ctx.logger && typeof ctx.logger.warn === 'function') { + ctx.logger.warn( + '[clearExpressListCache] Redis keys 扫描失败,降级为已知键删除: %s', + err.message + ); + } + } + + // 降级:删除已知命名的缓存键 + const normalizedWarehouseId = Number(warehouseId || 0); + const knownKeys = [ + 'express:list', + 'express:list:system', + 'express:list:system:normal', + ]; + if (Number.isFinite(normalizedWarehouseId) && normalizedWarehouseId > 0) { + knownKeys.push(`express:list:${normalizedWarehouseId}`); + } + await Promise.all(knownKeys.map(k => this.deleteCacheByKey(k))); } /** diff --git a/app/service/systems/setting/expressInterface.js b/app/service/systems/setting/expressInterface.js index 7cbefae..ff4ebfc 100644 --- a/app/service/systems/setting/expressInterface.js +++ b/app/service/systems/setting/expressInterface.js @@ -730,7 +730,7 @@ class SettingExpressInterfaceService extends Service { warehouse_id: row.warehouse_id === undefined || row.warehouse_id === null ? null : Number(row.warehouse_id), shop_id: row.shop_id === undefined || row.shop_id === null ? null : Number(row.shop_id), platform_shop_id: row.platform_shop_id === undefined || row.platform_shop_id === null ? null : Number(row.platform_shop_id), - template_id: row.template_id === undefined || row.template_id === null ? null : Number(row.template_id), + template_id: this.normalizeOptionalText(row.template_id, 'template_id', 50), paymode: row.paymode === undefined || row.paymode === null ? null : Number(row.paymode), brandno: this.normalizeOptionalText(row.brandno, 'brandno', 255), providertype: this.normalizeOptionalText(row.providertype, 'providertype', 50), @@ -1215,10 +1215,14 @@ class SettingExpressInterfaceService extends Service { allowEmpty: true, min: 1, }), - template_id: this.normalizeInteger(data.template_id !== undefined ? data.template_id : data.templateId, 'template_id', { - allowEmpty: true, - min: 1, - }), + template_id: (() => { + const normalizedTemplateId = this.normalizeOptionalText( + data.template_id !== undefined ? data.template_id : data.templateId, + 'template_id', + 50 + ); + return normalizedTemplateId === '' ? null : normalizedTemplateId; + })(), paymode: this.normalizeInteger(data.paymode !== undefined ? data.paymode : data.payMode, 'paymode', { allowEmpty: true, }), @@ -1443,14 +1447,12 @@ class SettingExpressInterfaceService extends Service { } if (hasTemplateId) { - updates.template_id = this.normalizeInteger( + const normalizedTemplateId = this.normalizeOptionalText( data.template_id !== undefined ? data.template_id : data.templateId, 'template_id', - { - allowEmpty: true, - min: 1, - } + 50 ); + updates.template_id = normalizedTemplateId === '' ? null : normalizedTemplateId; } if (hasPaymode) { diff --git a/app/service/systems/stock_store.js b/app/service/systems/stock_store.js index cb809f5..8586576 100644 --- a/app/service/systems/stock_store.js +++ b/app/service/systems/stock_store.js @@ -3080,8 +3080,10 @@ class stockStoreService extends Service { } /** * 快捷搜索仓库商品并补全库存管理标记。 + * 支持多词 OR 搜索:使用中英文逗号 `,` `,`、换行 `\n`、回车 `\r` 分隔多个关键词, + * 任意一个词在 item_code、item_name、goods_code 或条形码中命中即返回该商品。 * @param {Object} data 请求体 - * @param {string} [data.keyword] 搜索关键字 + * @param {string} [data.keyword] 搜索关键字,支持多词以逗号/换行分隔进行 OR 匹配 * @param {number|string} [data.store_id] 货主ID * @param {boolean} [data.with_stock=false] 是否返回关联库存数据 * @param {boolean} [data.is_batch=false] with_stock=true 时是否按批次返回 @@ -3107,40 +3109,79 @@ class stockStoreService extends Service { // 准备关联查询的条件 const includeConditions = []; - // 如果有搜索关键词,创建搜索条件 + // 如果有搜索关键词,按分隔符拆分为多个词进行 OR 匹配 if (keyword && keyword.trim()) { - const searchKeyword = `%${keyword.trim()}%`; + // 按分隔符拆词:中英文逗号、换行、回车、管道符、空格 + const keywords = keyword + .split(/[,\n\r,\|\s]+/) + .map(k => k.trim()) + .filter(k => k.length > 0); - // 先构建主表的搜索条件 - const stockWarehouseConditions = { - [Op.or]: [ - { item_code: { [Op.like]: searchKeyword } }, - { item_name: { [Op.like]: searchKeyword } }, - { goods_code: { [Op.like]: searchKeyword } }, - ], - }; + if (keywords.length === 1) { + // 单个词,保持原逻辑 + const searchKeyword = `%${keywords[0]}%`; - // 添加条形码关联查询条件 - includeConditions.push({ - model: app.model.StockBarcode, - as: 'barcodes', - attributes: [ 'barcode' ], - required: false, // 使用LEFT JOIN - where: { - barcode: { [Op.like]: searchKeyword }, - }, - }); + const stockWarehouseConditions = { + [Op.or]: [ + { item_code: { [Op.like]: searchKeyword } }, + { item_name: { [Op.like]: searchKeyword } }, + { goods_code: { [Op.like]: searchKeyword } }, + ], + }; - // 合并搜索条件 - whereCondition[Op.or] = [ - stockWarehouseConditions, - // 如果barcodes表有匹配的记录,则也返回该商品 - { - '$barcodes.barcode$': { [Op.like]: searchKeyword }, - }, - ]; - } else { - // 如果没有关键词,也包含barcodes关联(但不需要where条件) + includeConditions.push({ + model: app.model.StockBarcode, + as: 'barcodes', + attributes: [ 'barcode' ], + required: false, + where: { + barcode: { [Op.like]: searchKeyword }, + }, + }); + + whereCondition[Op.or] = [ + stockWarehouseConditions, + { + '$barcodes.barcode$': { [Op.like]: searchKeyword }, + }, + ]; + } else if (keywords.length > 1) { + // 多个词,OR 包装:每个词在 item_code/item_name/goods_code/barcode 任一命中即可 + const stockWarehouseConditions = { + [Op.or]: keywords.flatMap(kw => { + const like = `%${kw}%`; + return [ + { item_code: { [Op.like]: like } }, + { item_name: { [Op.like]: like } }, + { goods_code: { [Op.like]: like } }, + ]; + }), + }; + + includeConditions.push({ + model: app.model.StockBarcode, + as: 'barcodes', + attributes: [ 'barcode' ], + required: false, + where: { + [Op.or]: keywords.map(kw => ({ + barcode: { [Op.like]: `%${kw}%` }, + })), + }, + }); + + whereCondition[Op.or] = [ + stockWarehouseConditions, + ...keywords.map(kw => ({ + '$barcodes.barcode$': { [Op.like]: `%${kw}%` }, + })), + ]; + } + // keywords.length === 0 时不加搜索条件,走 else 分支 + } + + if (!includeConditions.some(c => c.as === 'barcodes')) { + // 如果没有关键词或关键词全为空,也包含 barcodes 关联(但不需要 where 条件) includeConditions.push({ model: app.model.StockBarcode, as: 'barcodes', diff --git a/app/service/systems/storage/inventory.js b/app/service/systems/storage/inventory.js index 2d996be..7bb3df9 100644 --- a/app/service/systems/storage/inventory.js +++ b/app/service/systems/storage/inventory.js @@ -2301,6 +2301,8 @@ class InventoryService extends Service { delete row.stock.store_stock; delete row.stock.is_batch_mgmt; } + // 货主名称提升到根层级,便于前端直接使用 + row.store_name = row.stock?.store_name || null; row.created_at = row.created_at ? app.formatDate(row.created_at) : ''; row.updated_at = row.updated_at ? app.formatDate(row.updated_at) : ''; row.inbound_time = row.inbound_time ? app.formatDate(row.inbound_time) : ''; @@ -2401,6 +2403,8 @@ class InventoryService extends Service { delete row.stock.store_stock; delete row.stock.is_batch_mgmt; } + // 货主名称提升到根层级,便于前端直接使用 + row.store_name = row.stock?.store_name || null; row.first_inbound_time = row.first_inbound_time ? app.formatDate(row.first_inbound_time) : ''; row.last_inbound_time = row.last_inbound_time ? app.formatDate(row.last_inbound_time) : ''; row.production_date = row.production_date ? app.formatDate(row.production_date) : ''; diff --git a/database/migrations/20260606-remove-unique-platform-code-from-express-setting.js b/database/migrations/20260606-remove-unique-platform-code-from-express-setting.js new file mode 100644 index 0000000..8bfea14 --- /dev/null +++ b/database/migrations/20260606-remove-unique-platform-code-from-express-setting.js @@ -0,0 +1,102 @@ +'use strict'; + +const TABLE_NAME = 'wms_express_setting'; +const UNIQUE_INDEX_NAME = 'platform_code'; +const NEW_INDEX_NAME = 'idx_express_warehouse'; +const FK_NAME = 'wms_express_setting_ibfk_1'; + +/** + * 检查指定表中是否存在指定名称的索引(通过 SHOW INDEX 做幂等判断)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @param {string} indexName 索引名。 + * @returns {Promise} 索引是否存在。 + */ +const hasIndex = async (queryInterface, tableName, indexName) => { + const [rows] = await queryInterface.sequelize.query( + `SHOW INDEX FROM \`${tableName}\` WHERE Key_name = :indexName`, + { replacements: { indexName } } + ); + return rows && rows.length > 0; +}; + +/** + * 检查指定外键约束是否存在(通过 information_schema 做幂等判断)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @param {string} constraintName 约束名。 + * @returns {Promise} 外键是否存在。 + */ +const hasForeignKey = async (queryInterface, tableName, constraintName) => { + const [rows] = await queryInterface.sequelize.query( + `SELECT CONSTRAINT_NAME + FROM information_schema.TABLE_CONSTRAINTS + WHERE CONSTRAINT_SCHEMA = DATABASE() + AND TABLE_NAME = :tableName + AND CONSTRAINT_NAME = :constraintName + AND CONSTRAINT_TYPE = 'FOREIGN KEY'`, + { replacements: { tableName, constraintName } } + ); + return rows && rows.length > 0; +}; + +module.exports = { + /** + * 正向迁移:先删除外键依赖,再删除唯一索引,最后添加普通索引替代。 + * 原因:同一系统快递编码(express_code)允许对应多个自定义编码(code), + * 原 UNIQUE KEY `platform_code` ON (`express_code`, `warehouse_id`) 约束过紧, + * 且该索引被外键 `wms_express_setting_ibfk_1`(express_code → wms_express.code)依赖。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @returns {Promise} 无返回值。 + */ + async up(queryInterface) { + // 1. 先删除依赖该索引的外键约束 + if (await hasForeignKey(queryInterface, TABLE_NAME, FK_NAME)) { + await queryInterface.sequelize.query( + `ALTER TABLE \`${TABLE_NAME}\` DROP FOREIGN KEY \`${FK_NAME}\`;` + ); + } + + // 2. 删除原来的唯一索引 + if (await hasIndex(queryInterface, TABLE_NAME, UNIQUE_INDEX_NAME)) { + await queryInterface.sequelize.query( + `ALTER TABLE \`${TABLE_NAME}\` DROP INDEX \`${UNIQUE_INDEX_NAME}\`;` + ); + } + + // 3. 添加普通索引替代(用于查询性能) + if (!(await hasIndex(queryInterface, TABLE_NAME, NEW_INDEX_NAME))) { + await queryInterface.sequelize.query( + `ALTER TABLE \`${TABLE_NAME}\` ADD INDEX \`${NEW_INDEX_NAME}\` (express_code, warehouse_id);` + ); + } + }, + + /** + * 回滚迁移:恢复唯一索引与外键约束。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @returns {Promise} 无返回值。 + */ + async down(queryInterface) { + // 1. 删除替代的普通索引 + if (await hasIndex(queryInterface, TABLE_NAME, NEW_INDEX_NAME)) { + await queryInterface.sequelize.query( + `ALTER TABLE \`${TABLE_NAME}\` DROP INDEX \`${NEW_INDEX_NAME}\`;` + ); + } + + // 2. 恢复唯一索引(幂等:已存在则跳过) + if (!(await hasIndex(queryInterface, TABLE_NAME, UNIQUE_INDEX_NAME))) { + await queryInterface.sequelize.query( + `ALTER TABLE \`${TABLE_NAME}\` ADD UNIQUE INDEX \`${UNIQUE_INDEX_NAME}\` (express_code, warehouse_id);` + ); + } + + // 3. 恢复外键约束(幂等:已存在则跳过) + if (!(await hasForeignKey(queryInterface, TABLE_NAME, FK_NAME))) { + await queryInterface.sequelize.query( + `ALTER TABLE \`${TABLE_NAME}\` ADD CONSTRAINT \`${FK_NAME}\` FOREIGN KEY (express_code) REFERENCES wms_express (code);` + ); + } + }, +}; diff --git a/database/migrations/20260606000000-change-template-id-to-varchar-wms-express-interface.js b/database/migrations/20260606000000-change-template-id-to-varchar-wms-express-interface.js new file mode 100644 index 0000000..decfcc8 --- /dev/null +++ b/database/migrations/20260606000000-change-template-id-to-varchar-wms-express-interface.js @@ -0,0 +1,62 @@ +'use strict'; + +/** + * 将快递接口配置表的 template_id 列从 BIGINT 改为 VARCHAR(50), + * 以支持快手等平台返回的字符串模板 ID(如 "EBSTO11")。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ +module.exports = { + /** + * 执行迁移:将 template_id 列类型从 BIGINT 改为 VARCHAR(50)(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + const tableName = 'wms_express_interface'; + const columns = await queryInterface.describeTable(tableName); + + if (!columns.template_id) { + return; + } + + // 如果已经是 VARCHAR 类型则跳过(幂等) + if (columns.template_id.type && String(columns.template_id.type).toUpperCase().includes('VARCHAR')) { + return; + } + + await queryInterface.changeColumn(tableName, 'template_id', { + type: Sequelize.STRING(50), + allowNull: true, + comment: '模板ID', + }); + }, + + /** + * 回滚迁移:将 template_id 列类型从 VARCHAR(50) 改回 BIGINT(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async down(queryInterface, Sequelize) { + const tableName = 'wms_express_interface'; + const columns = await queryInterface.describeTable(tableName); + + if (!columns.template_id) { + return; + } + + // 如果已经是 BIGINT 类型则跳过(幂等) + if (columns.template_id.type && String(columns.template_id.type).toUpperCase().includes('BIGINT')) { + return; + } + + await queryInterface.changeColumn(tableName, 'template_id', { + type: Sequelize.BIGINT.UNSIGNED, + allowNull: true, + comment: '模板ID', + }); + }, +}; diff --git a/methods/changes/system.json b/methods/changes/system.json index 75edba2..5c1d9b6 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -2845,5 +2845,48 @@ "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" ], "type": "updated" + }, + { + "version": "2026.06.06-system-01", + "date": "2026-06-06", + "summary": "恢复 order.pendingOrder.downloadCreateTemplate:方法仍存在于代码中,取消 deprecated 标记,完善文档描述", + "methods": [ + "order.pendingOrder.downloadCreateTemplate" + ], + "notes": [ + "order.pendingOrder.downloadCreateTemplate 方法在 pendingOrder.js 中仍存在(line 2099),此前被误标记为 deprecated。", + "取消 status: 'deprecated' 标记,恢复为 active 状态。", + "移除 description 中的'(已作废)'后缀。", + "完善 description:说明模板包含必填列(橙色背景)、可选列(灰色背景)、示例数据行和填写说明工作表。", + "补充 response 字段说明:filename 和 mime 为固定值。" + ], + "type": "updated" + }, + { + "version": "2026.06.07-system-01", + "date": "2026-06-07", + "summary": "order.pendingOrder.createOrder 文档新增 shop_nick 入参(店铺名称,可选,最大长度200)", + "methods": [ + "order.pendingOrder.createOrder" + ], + "notes": [ + "在 order.pendingOrder.createOrder 的 request params 中新增 shop_nick 字段(string,非必填),对应代码实现中 shopNick: String(requestData.shop_nick || requestData.shopNick || '').trim()。", + "shop_nick 已在 COPY_FIELDS 白名单中(pendingOrder.js L1738),仅文档缺失,本次为补齐。" + ], + "type": "updated" + }, + { + "version": "2026.06.07-system-02", + "date": "2026-06-07", + "summary": "order.pendingOrder.downloadCreateTemplate:模板新增 shop_nick 列(店铺名称),store_id/province/city/area 标注为非必填", + "methods": [ + "order.pendingOrder.downloadCreateTemplate" + ], + "notes": [ + "模板新增 shop_nick(店铺名称)列,非必填。", + "明确标注 store_id(货主ID)、province(省份)、city(城市)、area(区/县)为非必填列。", + "响应文档中新增 shop_nick 字段说明。" + ], + "type": "updated" } ] diff --git a/methods/system.json b/methods/system.json index 5170308..7672209 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1,8 +1,8 @@ { "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", - "version": "0.4.0", - "updatedAt": "2026-06-05", + "version": "0.3.5", + "updatedAt": "2026-06-07", "headers": [ { "name": "platform", @@ -3612,6 +3612,13 @@ "source": "body", "description": "来源订单号" }, + { + "name": "shop_nick", + "type": "string", + "required": false, + "source": "body", + "description": "店铺名称(自定义),最大长度 200" + }, { "name": "order_type", "type": "string", @@ -3687,43 +3694,6 @@ "province/city/area 为必填项,空值返回 400" ] }, - { - "method": "order.pendingOrder.downloadCreateTemplate", - "description": "下载创建订单的 Excel 导入模板。返回 base64 编码的 xlsx 文件,前端解码后作为附件下载。表头中标注 * 的列为必填项,多行相同订单号的行组成一个完整订单。(已作废)", - "status": "deprecated", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [ - { - "name": "base64", - "type": "string", - "required": true, - "description": "base64 编码的 xlsx 文件内容" - }, - { - "name": "filename", - "type": "string", - "required": true, - "description": "建议保存的文件名" - }, - { - "name": "mime", - "type": "string", - "required": true, - "description": "文件 MIME 类型" - } - ], - "errors": [] - }, { "method": "order.pendingOrder.importOrdersFromExcel", "description": "通过 Excel 文件批量创建订单。接受 base64 编码的 xlsx 内容,按订单号分组,每组创建一个订单(step 由货主策略决定)。每行代表一条商品明细;同一订单号的多行组成一个完整订单,头信息取每组第一行。(已作废)", @@ -19972,7 +19942,7 @@ ] }, { - "groupName": "order.wave", + "groupName": "订单模块", "module": "order", "list": [ { @@ -20035,6 +20005,48 @@ "message": "查询失败" } ] + }, + { + "method": "order.pendingOrder.downloadCreateTemplate", + "description": "下载创建订单的 Excel 导入模板。返回 base64 编码的 xlsx 文件,前端解码后作为 .xlsx 附件下载。表头中标注 * 的列为必填项(橙色背景),可选列为灰色背景,包含示例数据行和填写说明工作表。多行相同订单号的行组成一个完整订单,每行代表一条商品明细。模板必填列:订单号(delivery_order_code)、收件人姓名(name)、手机号(mobile)、详细地址(detail_address)、商品编码(item_code)、计划数量(plan_qty);非必填列含:货主ID(store_id)、省份(province)、城市(city)、区/县(area)、店铺名称(shop_nick)等。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "base64", + "type": "string", + "required": true, + "description": "base64 编码的 xlsx 文件内容" + }, + { + "name": "filename", + "type": "string", + "required": true, + "description": "建议保存的文件名,固定为 创建订单导入模板.xlsx" + }, + { + "name": "mime", + "type": "string", + "required": true, + "description": "文件 MIME 类型,固定为 application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" + }, + { + "name": "shop_nick", + "type": "string", + "required": false, + "description": "模板中新增的店铺名称列(非必填),用于标识订单所属店铺" + } + ], + "errors": [] } ] }, From c2b5ffc319018affc6e0da17a72fa8f0206c7dca Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sun, 7 Jun 2026 20:42:24 +0800 Subject: [PATCH 067/550] 1 --- app/controller/home.js | 246 +++++++++++++----- app/model/order_delivery.js | 15 ++ app/model/shop.js | 2 +- app/service/systemMethods/order/base.js | 6 +- .../systemMethods/order/pendingOrder.js | 100 ++++++- .../systemMethods/order/recheckOrder.js | 159 +++++++++++ app/service/systemMethods/order/wave.js | 154 ++++++++--- app/service/systemMethods/pick.js | 6 +- app/service/systems/delivery_order.js | 8 +- app/service/systems/pick.js | 14 +- app/service/systems/shops.js | 11 +- ...00-drop-uk-warehouse-platform-shop-name.js | 67 +++++ methods/changes/system.json | 100 +++++++ methods/system.json | 179 ++++++++++--- 14 files changed, 919 insertions(+), 148 deletions(-) create mode 100644 database/migrations/20260607120000-drop-uk-warehouse-platform-shop-name.js diff --git a/app/controller/home.js b/app/controller/home.js index 5372174..2b7c48b 100644 --- a/app/controller/home.js +++ b/app/controller/home.js @@ -452,7 +452,7 @@ class HomeController extends Controller { status: 1, }; - if (oauthData && oauthData.taobao_user_nick !== undefined) { + if (oauthData && oauthData.taobao_user_nick != null) { updatePayload.shop_name = this.decodeTbShopName(oauthData.taobao_user_nick); } @@ -503,6 +503,38 @@ class HomeController extends Controller { }); } + /** + * 查找与待更新店铺存在唯一约束冲突的店铺记录(不限授权状态)。 + * 用于乐观重试场景:当前预授权店铺 save 触发 uk_warehouse_platform_shop_name + * 冲突时,回退到此方法查找冲突记录并尝试合并。 + * @param {import('sequelize').Model} shop 当前预申请店铺记录。 + * @param {object} updatePayload 待回写的字段对象,需包含 shop_name。 + * @param {import('sequelize').Transaction} transaction 当前事务对象。 + * @return {Promise} 冲突的店铺记录,未找到返回 null。 + */ + async findConflictShopForOauth(shop, updatePayload, transaction) { + const { Op } = this.app.Sequelize; + const normalizedShopName = updatePayload.shop_name != null + ? String(updatePayload.shop_name).trim() + : ''; + + if (!normalizedShopName) { + return null; + } + + return await this.ctx.model.Shop.findOne({ + where: { + warehouse_id: shop.warehouse_id, + platform_code: shop.platform_code, + shop_name: normalizedShopName, + id: { + [Op.ne]: shop.id, + }, + }, + transaction, + }); + } + /** * 按仓库、平台与授权标识查找已授权的旧店铺记录。 * @param {import('sequelize').Model} shop 当前预申请店铺记录。 @@ -585,37 +617,111 @@ class HomeController extends Controller { 'status', ]; - return await this.ctx.model.transaction(async transaction => { - const authorizedShop = await this.findAuthorizedOauthShop( - shop, - updatePayload.owner_id, - updatePayload.shop_name, - transaction - ); + // 兜底:若 OAuth 响应未返回 shop_name,沿用数据库已有值,避免 save 时触发 allowNull 校验 + if (!('shop_name' in updatePayload) || updatePayload.shop_name == null) { + updatePayload.shop_name = shop.shop_name; + } - if (authorizedShop) { - authorizedShop.set(updatePayload); - await authorizedShop.save({ + try { + return await this.ctx.model.transaction(async transaction => { + const authorizedShop = await this.findAuthorizedOauthShop( + shop, + updatePayload.owner_id, + updatePayload.shop_name, + transaction + ); + + if (authorizedShop) { + authorizedShop.set(updatePayload); + await authorizedShop.save({ + fields: saveFields, + transaction, + }); + await shop.destroy({ transaction }); + + return authorizedShop; + } + + shop.set(updatePayload); + await shop.save({ fields: saveFields, transaction, }); - await shop.destroy({ transaction }); - return authorizedShop; + return shop; + }); + } catch (error) { + // 记录 Sequelize 验证错误的详细信息,包括每个字段的失败原因 + if (error.name === 'SequelizeValidationError' && Array.isArray(error.errors)) { + const fieldErrors = error.errors.map(e => `${e.path}: ${e.message}`).join('; '); + this.ctx.logger.error( + '[platform-oauth][CAINIAO] 店铺保存校验失败,shop_id=%s,字段详情:%s', + shop && shop.id, + fieldErrors + ); + throw error; } - shop.set(updatePayload); - await shop.save({ - fields: saveFields, - transaction, - }); + // 唯一约束冲突:尝试乐观重试,查找冲突记录并合并 + if (error.name === 'SequelizeUniqueConstraintError') { + const conflictFields = error.fields ? Object.keys(error.fields).join(', ') : 'unknown'; + const conflictValues = error.fields ? JSON.stringify(error.fields) : 'unknown'; + this.ctx.logger.error( + '[platform-oauth][CAINIAO] 店铺保存唯一约束冲突,shop_id=%s,冲突字段:%s,冲突值:%s', + shop && shop.id, + conflictFields, + conflictValues + ); - return shop; - }); + // 乐观重试:在新事务中查找冲突记录并尝试合并 + try { + return await this.ctx.model.transaction(async transaction => { + const conflictShop = await this.findConflictShopForOauth( + shop, + updatePayload, + transaction + ); + + if (conflictShop) { + conflictShop.set(updatePayload); + await conflictShop.save({ + fields: saveFields, + transaction, + }); + await shop.destroy({ transaction }); + this.ctx.logger.info( + '[platform-oauth][CAINIAO] 乐观重试成功,冲突店铺已合并,conflict_shop_id=%s,pre_auth_shop_id=%s', + conflictShop.id, + shop.id + ); + return conflictShop; + } + + // 未找到冲突记录则返回 null,由上层展示友好提示 + this.ctx.logger.warn( + '[platform-oauth][CAINIAO] 乐观重试未找到冲突记录,shop_id=%s,shop_name=%s', + shop && shop.id, + updatePayload.shop_name + ); + return null; + }); + } catch (retryError) { + this.ctx.logger.error( + '[platform-oauth][CAINIAO] 乐观重试失败,shop_id=%s,错误:%s', + shop && shop.id, + retryError.message || retryError + ); + return null; + } + } + + throw error; + } } /** * 处理平台授权回调请求,解析 query 中的 code 与 state。 + * 内部使用 try-catch 兜底,确保即使处理过程中抛出未捕获异常也能渲染错误页面而非 500。 * @return {Promise} 无返回值。 */ async platformOauthCallback() { @@ -630,20 +736,47 @@ class HomeController extends Controller { let errorMessage = ''; let shop = null; - if (!code) { - errorMessage = 'code不能为空'; - } else if (!state) { - errorMessage = 'state不能为空'; - } else if (!parsedState) { - errorMessage = 'state解析失败'; - } else { - switch (parsedState.platformCode) { - case 'PDD': - { - const pddResult = await this.pdd(code); + try { + if (!code) { + errorMessage = 'code不能为空'; + } else if (!state) { + errorMessage = 'state不能为空'; + } else if (!parsedState) { + errorMessage = 'state解析失败'; + } else { + switch (parsedState.platformCode) { + case 'PDD': + { + const pddResult = await this.pdd(code); - if (pddResult.success === false) { - errorMessage = pddResult.message; + if (pddResult.success === false) { + errorMessage = pddResult.message; + break; + } + + shop = await ctx.model.Shop.findOne({ + where: { + auth_random_code: parsedState.authRandomCode, + }, + }); + + if (shop && this.isMatchedShopPlatform(shop, parsedState.platformCode)) { + const oauthData = pddResult.result && pddResult.result.data + ? pddResult.result.data + : pddResult.result; + + shop = await this.updatePddOauthShop(shop, oauthData); + } + } + break; + case 'CAINIAO': + { + const cainiaoOauthResult = await this.cainiao(code); + + if (!cainiaoOauthResult || cainiaoOauthResult.success === false) { + errorMessage = cainiaoOauthResult && cainiaoOauthResult.message + ? cainiaoOauthResult.message + : '菜鸟授权失败:未知错误'; break; } @@ -654,45 +787,28 @@ class HomeController extends Controller { }); if (shop && this.isMatchedShopPlatform(shop, parsedState.platformCode)) { - const oauthData = pddResult.result && pddResult.result.data - ? pddResult.result.data - : pddResult.result; + const oauthData = cainiaoOauthResult.result && cainiaoOauthResult.result.data + ? cainiaoOauthResult.result.data + : cainiaoOauthResult.result; - shop = await this.updatePddOauthShop(shop, oauthData); + shop = await this.updateCainiaoOauthShop(shop, oauthData); + if (!shop) { + errorMessage = '店铺名称已存在,请先在系统中解绑同名店铺后重试'; + } } - } - break; - case 'CAINIAO': - { - const cainiaoOauthResult = await this.cainiao(code); - if (!cainiaoOauthResult || cainiaoOauthResult.success === false) { - errorMessage = cainiaoOauthResult && cainiaoOauthResult.message - ? cainiaoOauthResult.message - : '菜鸟授权失败:未知错误'; break; } - - shop = await ctx.model.Shop.findOne({ - where: { - auth_random_code: parsedState.authRandomCode, - }, - }); - - if (shop && this.isMatchedShopPlatform(shop, parsedState.platformCode)) { - const oauthData = cainiaoOauthResult.result && cainiaoOauthResult.result.data - ? cainiaoOauthResult.result.data - : cainiaoOauthResult.result; - - shop = await this.updateCainiaoOauthShop(shop, oauthData); - } - - break; + default: + errorMessage = '暂未接入该平台授权回调处理'; + break; } - default: - errorMessage = '暂未接入该平台授权回调处理'; - break; } + } catch (error) { + ctx.logger.error('[platform-oauth] 回调处理异常: %s', error.stack || error.message || error); + errorMessage = `系统内部错误:${error.message || '未知异常'}`; + // 发生异常后不再信任 shop 状态,置空以避免渲染误导信息 + shop = null; } const viewData = this.buildPlatformOauthCallbackViewData({ diff --git a/app/model/order_delivery.js b/app/model/order_delivery.js index 539d653..3fb0320 100644 --- a/app/model/order_delivery.js +++ b/app/model/order_delivery.js @@ -157,6 +157,21 @@ module.exports = app => { allowNull: true, comment: '店铺名称', }, + buyer_message: { + type: STRING(500), + allowNull: true, + comment: '买家留言', + }, + seller_message: { + type: STRING(500), + allowNull: true, + comment: '卖家留言', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, seller_nick: { type: STRING(200), allowNull: true, diff --git a/app/model/shop.js b/app/model/shop.js index 8e96fa0..533cda6 100644 --- a/app/model/shop.js +++ b/app/model/shop.js @@ -122,7 +122,7 @@ module.exports = app => { }, { name: 'uk_warehouse_platform_shop_name', - unique: true, + unique: false, fields: [ 'warehouse_id', 'platform_code', 'shop_name' ], }, { diff --git a/app/service/systemMethods/order/base.js b/app/service/systemMethods/order/base.js index 7f3c7f5..b05162f 100644 --- a/app/service/systemMethods/order/base.js +++ b/app/service/systemMethods/order/base.js @@ -19,7 +19,7 @@ const REVIEW_STATUS_STEP_MAP = Object.freeze({ const REVIEW_ORDER_ALLOWED_FIELDS = Object.freeze([ 'ids' ]); const BADGE_COUNT_OVER_LIMIT_VALUE = '99+'; -const ORDER_LIST_BASE_ATTRIBUTES = Object.freeze([ +const ORDER_LIST_BASE_ATTRIBUTES = [ 'id', 'delivery_order_code', 'pre_delivery_order_code', 'pre_delivery_order_id', 'order_type', 'order_flag', 'source_order_codes', 'sys_platform_code', 'sys_platform_name', @@ -27,6 +27,7 @@ const ORDER_LIST_BASE_ATTRIBUTES = Object.freeze([ 'place_order_time', 'pay_time', 'pay_no', 'service_code', 'operator_name', 'operate_time', 'delivery_time', 'shop_nick', 'seller_nick', 'buyer_nick', + 'buyer_message', 'seller_message', 'remark', 'total_amount', 'item_amount', 'discount_amount', 'freight', 'ar_amount', 'got_amount', 'service_fee', 'logistics_name', @@ -44,7 +45,7 @@ const ORDER_LIST_BASE_ATTRIBUTES = Object.freeze([ 'post_status', 'storage_status', 'pick_status', 'pack_status', 'inspection_status', 'print_status', 'claim_status', 'outbound_status', 'lock_status', 'intercept_status', 'basket_number', 'recheck_status', -]); +]; const ORDER_WEIGHT_TYPE_LABELS = Object.freeze({ 0: '常规', @@ -1416,6 +1417,7 @@ class OrderBaseService extends MainService { const updateValues = { inspection_status: 'fin', step: 1, + status: 'created', updated_at: now, }; diff --git a/app/service/systemMethods/order/pendingOrder.js b/app/service/systemMethods/order/pendingOrder.js index 690818c..ea89c51 100644 --- a/app/service/systemMethods/order/pendingOrder.js +++ b/app/service/systemMethods/order/pendingOrder.js @@ -28,9 +28,9 @@ class PendingOrderService extends OrderBaseService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,updateOrderPlatform,updateOrderExpress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress'; + const _noNeedRight = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,updateOrderPlatform,updateOrderExpress,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress'; const _noNeedLog = 'list,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,parseAddress'; - const _noNeedAuth = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,updateOrderPlatform,updateOrderExpress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress'; + const _noNeedAuth = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,updateOrderPlatform,updateOrderExpress,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -1468,7 +1468,10 @@ class PendingOrderService extends OrderBaseService { } const model = await this.getOrderModel('order', warehouseId); - const where = this.buildOrderWhere(orderIds, warehouseId); + const where = { + ...this.buildOrderWhere(orderIds, warehouseId), + post_status: 'none', + }; const [ affectedRows ] = await model.update({ sys_platform_code: platform.code, @@ -1578,7 +1581,10 @@ class PendingOrderService extends OrderBaseService { } const model = await this.getOrderModel('order', warehouseId); - const where = this.buildOrderWhere(orderIds, warehouseId); + const where = { + ...this.buildOrderWhere(orderIds, warehouseId), + post_status: 'none', + }; const [ affectedRows ] = await model.update({ sys_logistics_code: sysLogisticsCode, @@ -1623,6 +1629,92 @@ class PendingOrderService extends OrderBaseService { }); } + /** + * 批量修改待处理订单的收件地址信息。 + * + * 仅允许在未分配快递(post_status = 'none')时修改,至少提供一个地址字段。 + * 支持批量操作,返回更新数量和受影响的订单 ID 列表。 + * + * @param {Object} data 请求体。 + * @param {number[]} data.ids 订单 ID 数组(必填)。 + * @param {string} [data.name] 收件人姓名。 + * @param {string} [data.mobile] 手机号。 + * @param {string} [data.tel] 电话。 + * @param {string} [data.zip_code] 邮编。 + * @param {string} [data.province] 省份。 + * @param {string} [data.city] 城市。 + * @param {string} [data.area] 区/县。 + * @param {string} [data.town] 镇/街道。 + * @param {string} [data.detail_address] 详细地址。 + * @return {Promise} 统一 success 包装的更新结果,含 updated_count 与 ids。 + */ + async updateAddress(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const warehouseId = this.getWarehouseId(); + const operator = this.getOrderLogOperator(); + const logWarehouseId = this.getOrderLogWarehouseId(warehouseId); + + // 解析订单 ID + const orderIds = this.normalizeOrderIds(requestData); + if (orderIds.length === 0) { + throw new Error('ids 不能为空'); + } + + // 收集可更新的地址字段 + const addressFields = [ + 'name', 'mobile', 'tel', 'zip_code', + 'province', 'city', 'area', 'town', 'detail_address', + ]; + const updates = {}; + for (const field of addressFields) { + const value = requestData[field]; + if (value !== undefined && value !== null && String(value).trim() !== '') { + updates[field] = String(value).trim(); + } + } + + if (Object.keys(updates).length === 0) { + throw new Error('至少需要提供一个地址字段进行修改'); + } + + updates.updated_at = new Date(); + + const model = await this.getOrderModel('order', warehouseId); + const where = { + ...this.buildOrderWhere(orderIds, warehouseId), + post_status: 'none', + }; + + const [ affectedRows ] = await model.update(updates, { where }); + const count = Number(affectedRows || 0); + + // 记录操作日志 + try { + const updatedFieldNames = Object.keys(updates).filter(k => k !== 'updated_at'); + await this.ctx.service.systems.operationLog.createOperationLog({ + businessType: 'order', + businessId: logWarehouseId, + operationCode: 'ORDER_UPDATE_ADDRESS', + operator, + extras: { + warehouseId: logWarehouseId, + orderIds, + updated_fields: updatedFieldNames, + updated_count: count, + message: `批量修改订单收件地址:订单ID [${orderIds.join(', ')}],更新字段 [${updatedFieldNames.join(', ')}],共更新 ${count} 条`, + }, + beforeChanges: null, + }); + } catch (logErr) { + this.ctx.logger.warn('[PendingOrderService.updateAddress] 写入操作日志失败,不影响业务', logErr); + } + + return this.success('ok', { + updated_count: count, + ids: orderIds, + }); + } + /** * 克隆待处理订单。 * diff --git a/app/service/systemMethods/order/recheckOrder.js b/app/service/systemMethods/order/recheckOrder.js index 24bcfdd..691d25e 100644 --- a/app/service/systemMethods/order/recheckOrder.js +++ b/app/service/systemMethods/order/recheckOrder.js @@ -183,6 +183,9 @@ class RecheckOrderService extends OrderBaseService { } ); + // 更新波次拣货任务订单复核状态,并判断是否需要解绑车任务 + await this.updateTaskOrderReviewAndTryUnbindCart(orderId, warehouseId, operator, now); + return { order_id: orderId, waybill_no: waybillNo, @@ -192,6 +195,162 @@ class RecheckOrderService extends OrderBaseService { }; } + /** + * 更新波次拣货任务订单的复核状态,若任务下所有订单均已复核完成则自动解绑车任务。 + * @param {number} orderId 订单ID。 + * @param {number} warehouseId 仓库ID。 + * @param {{ id: string|null, name: string }} operator 操作人信息。 + * @param {Date} now 当前时间。 + * @return {Promise} 无返回值。 + */ + async updateTaskOrderReviewAndTryUnbindCart(orderId, warehouseId, operator, now) { + const { ctx } = this; + const taskOrderColumnSet = await this.getTableColumnSet('wms_wave_pick_task_order'); + const hasReviewStatus = taskOrderColumnSet.has('review_status'); + const hasReviewUserId = taskOrderColumnSet.has('review_user_id'); + const hasReviewResult = taskOrderColumnSet.has('review_result'); + const hasReviewTime = taskOrderColumnSet.has('review_time'); + + // 若 review_status 列不存在,跳过后续所有逻辑 + if (!hasReviewStatus) { + return; + } + + const operatorUserId = Number(operator.id) || 0; + const reviewSetClauses = []; + + reviewSetClauses.push('review_status = 1'); + if (hasReviewUserId) reviewSetClauses.push('review_user_id = :operatorUserId'); + if (hasReviewResult) reviewSetClauses.push('review_result = 1'); + if (hasReviewTime) reviewSetClauses.push('review_time = :now'); + reviewSetClauses.push('update_time = NOW()'); + + await ctx.model.query( + `UPDATE wms_wave_pick_task_order + SET ${reviewSetClauses.join(',\n ')} + WHERE order_id = :orderId + AND warehouse_id = :warehouseId`, + { + replacements: { + orderId, + warehouseId, + operatorUserId, + now, + }, + type: ctx.model.QueryTypes.UPDATE, + } + ); + + // 查询当前订单所属的波次拣货任务ID + const taskRows = await ctx.model.query( + `SELECT DISTINCT task_id + FROM wms_wave_pick_task_order + WHERE order_id = :orderId + AND warehouse_id = :warehouseId`, + { + replacements: { orderId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + const taskId = Number( + (Array.isArray(taskRows) && taskRows.length > 0 ? taskRows[0]?.task_id : 0) + ); + + if (taskId <= 0) { + return; + } + + // 检查该任务下是否所有订单都已复核完成 + const unreviewedRows = await ctx.model.query( + `SELECT COUNT(*) AS cnt + FROM wms_wave_pick_task_order + WHERE task_id = :taskId + AND warehouse_id = :warehouseId + AND review_status != 1`, + { + replacements: { taskId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + const unreviewedCount = Number( + (Array.isArray(unreviewedRows) && unreviewedRows.length > 0 ? unreviewedRows[0]?.cnt : 0) + ); + + if (unreviewedCount > 0) { + return; + } + + // 任务下所有订单均已复核完成,解绑车任务(失败不影响主流程) + try { + await this.unbindCartForTask(taskId, warehouseId, operatorUserId); + ctx.logger.info( + `[confirmRecheck] 车任务解绑成功, taskId=${taskId}, orderId=${orderId}, operatorUserId=${operatorUserId}` + ); + } catch (unbindError) { + ctx.logger.warn( + `[confirmRecheck] 解绑车任务失败(复核已成功), taskId=${taskId}, orderId=${orderId}, error=${unbindError.message}` + ); + } + } + + /** + * 解绑车任务:清空波次拣货任务的车绑定、停用拣货车绑定记录、释放拣货车。 + * @param {number} taskId 波次拣货任务ID。 + * @param {number} warehouseId 仓库ID。 + * @param {number} operatorUserId 操作员用户ID。 + * @return {Promise} 无返回值。 + */ + async unbindCartForTask(taskId, warehouseId, operatorUserId) { + const { ctx } = this; + + // 1. 清空波次拣货任务的车绑定信息 + await ctx.model.query( + `UPDATE wms_wave_pick_task + SET current_cart_id = NULL, + current_cart_code_snapshot = NULL, + update_time = NOW() + WHERE id = :taskId + AND warehouse_id = :warehouseId`, + { + replacements: { taskId, warehouseId }, + type: ctx.model.QueryTypes.UPDATE, + } + ); + + // 2. 停用拣货车绑定记录 + await ctx.model.query( + `UPDATE wms_pick_task_cart_binding + SET is_active = 0, + unbind_user_id = :operatorUserId, + unbind_time = NOW(), + update_time = NOW() + WHERE task_id = :taskId + AND warehouse_id = :warehouseId + AND is_active = 1`, + { + replacements: { taskId, warehouseId, operatorUserId }, + type: ctx.model.QueryTypes.UPDATE, + } + ); + + // 3. 释放拣货车(清空当前任务和绑定用户) + await ctx.model.query( + `UPDATE wms_pick_cart + SET current_task_id = NULL, + bind_user_id = NULL, + last_seen_time = NOW(), + update_time = NOW() + WHERE warehouse_id = :warehouseId + AND current_task_id = :taskId`, + { + replacements: { taskId, warehouseId }, + type: ctx.model.QueryTypes.UPDATE, + } + ); + } + /** * 从多种兼容字段中解析订单ID。 * @param {Object} data 请求体。 diff --git a/app/service/systemMethods/order/wave.js b/app/service/systemMethods/order/wave.js index fdde4e0..7b0864a 100644 --- a/app/service/systemMethods/order/wave.js +++ b/app/service/systemMethods/order/wave.js @@ -10,7 +10,6 @@ const MAX_PAGE_SIZE = 200; const BATCH_LIST_MAX_PAGE_SIZE = 500; const DEFAULT_MAX_WAVE_QUANTITY = 500; const DEFAULT_MIN_GROUP_ORDER_FETCH_QUANTITY = 13; -const WAVE_MANUAL_FETCH_FLAG = 'wave_manual_fetch'; const FETCH_TASK_CACHE_KEY_PREFIX = 'wave:fetch:task:'; const FETCH_TASK_CACHE_TTL_SECONDS = 60 * 60 * 2; const BATCH_CANCEL_TASK_CACHE_KEY_PREFIX = 'wave:batch-cancel:'; @@ -82,6 +81,17 @@ const BATCH_LIST_ASSIGNMENT_FILTER_SCHEMAS = Object.freeze({ statsColumnPrefix: 'print', withErrorStatus: false, }), + review: Object.freeze({ + fieldName: 'review_assignment_status', + enumMap: Object.freeze({ + unreviewed: 'none', + partially_reviewed: 'partial', + reviewed: 'finished', + }), + caseInsensitive: true, + statsColumnPrefix: 'review', + withErrorStatus: true, + }), }); class WaveService extends OrderBaseService { @@ -936,16 +946,9 @@ class WaveService extends OrderBaseService { source: normalizedSource, transaction, }); - const orderFlagExpression = this.app.Sequelize.literal(`CASE - WHEN order_flag IS NULL OR order_flag = '' THEN '${WAVE_MANUAL_FETCH_FLAG}' - WHEN order_flag LIKE '%${WAVE_MANUAL_FETCH_FLAG}%' THEN order_flag - ELSE CONCAT(order_flag, ',${WAVE_MANUAL_FETCH_FLAG}') - END`); - await model.update({ wave_id: waveId, wave_no: waveNo, - order_flag: orderFlagExpression, }, { where: { id: { [Op.in]: candidateOrderIds }, @@ -1042,8 +1045,6 @@ class WaveService extends OrderBaseService { wave_id: allWaveIds.length > 0 ? allWaveIds[0] : 0, wave_ids: allWaveIds, order_ids: mergedOrderIds, - auto_fetch_disabled: true, - auto_fetch_disabled_marker: WAVE_MANUAL_FETCH_FLAG, ...(reason ? { reason } : {}), }; } catch (error) { @@ -1235,6 +1236,16 @@ class WaveService extends OrderBaseService { return this.normalizeBatchListAssignmentStatusFilterByType(value, 'print'); } + /** + * 规范化波次列表复核状态筛选值(英文枚举)。 + * + * @param {string} value 入参筛选值。 + * @return {string} 规范化后的筛选值,未传时返回空字符串。 + */ + normalizeBatchListReviewAssignmentStatusFilter(value) { + return this.normalizeBatchListAssignmentStatusFilterByType(value, 'review'); + } + /** * 根据类型获取波次分配状态筛选配置。 * @@ -1362,6 +1373,16 @@ class WaveService extends OrderBaseService { return this.buildBatchListAssignmentStatusFilterClauseByType(statusFilter, 'print'); } + /** + * 构建波次列表复核状态筛选 SQL 条件。 + * + * @param {string} statusFilter 复核状态筛选值(none/partial/finished)。 + * @return {{ sql: string, replacements: Object }} SQL 条件片段与参数。 + */ + buildBatchListReviewAssignmentFilterClause(statusFilter = '') { + return this.buildBatchListAssignmentStatusFilterClauseByType(statusFilter, 'review'); + } + /** * 按类型构建波次列表分配状态筛选 SQL 条件。 * @@ -1467,6 +1488,7 @@ class WaveService extends OrderBaseService { 'storage_assignment_status', 'express_assignment_status', 'print_assignment_status', + 'review_assignment_status', ]; const invalidFields = whereKeys.filter(key => !allowedFields.includes(key)); @@ -1600,6 +1622,9 @@ class WaveService extends OrderBaseService { const printAssignmentStatus = this.normalizeBatchListPrintAssignmentStatusFilter( normalizedWhere.print_assignment_status ); + const reviewAssignmentStatus = this.normalizeBatchListReviewAssignmentStatusFilter( + normalizedWhere.review_assignment_status + ); return { sql: conditions.length > 0 ? `\n AND ${conditions.join('\n AND ')}` : '', @@ -1607,6 +1632,7 @@ class WaveService extends OrderBaseService { storageAssignmentStatus, expressAssignmentStatus, printAssignmentStatus, + reviewAssignmentStatus, }; } @@ -4005,6 +4031,8 @@ class WaveService extends OrderBaseService { const storageAssignmentFilterClause = this.buildBatchListStorageAssignmentFilterClause(whereClause.storageAssignmentStatus); const expressAssignmentFilterClause = this.buildBatchListExpressAssignmentFilterClause(whereClause.expressAssignmentStatus); const printAssignmentFilterClause = this.buildBatchListPrintAssignmentFilterClause(whereClause.printAssignmentStatus); + const reviewAssignmentFilterClause = this.buildBatchListReviewAssignmentFilterClause(whereClause.reviewAssignmentStatus); + const onlyTodo = Number(requestData.only_todo || 0); const baseBatchWhereSql = ` warehouse_id = :warehouseId AND wave_status IN (:waveStatusList) @@ -4041,7 +4069,10 @@ class WaveService extends OrderBaseService { SUM(CASE WHEN od.post_status = 'fin' THEN 1 ELSE 0 END) AS post_fin_count, SUM(CASE WHEN od.post_status = 'error' THEN 1 ELSE 0 END) AS post_error_count, SUM(CASE WHEN od.print_status = 'none' THEN 1 ELSE 0 END) AS print_none_count, - SUM(CASE WHEN od.print_status = 'fin' THEN 1 ELSE 0 END) AS print_fin_count + SUM(CASE WHEN od.print_status = 'fin' THEN 1 ELSE 0 END) AS print_fin_count, + SUM(CASE WHEN od.inspection_status = 'fin' THEN 1 ELSE 0 END) AS review_fin_count, + SUM(CASE WHEN od.inspection_status = 'error' THEN 1 ELSE 0 END) AS review_error_count, + SUM(CASE WHEN od.inspection_status NOT IN ('fin', 'error') THEN 1 ELSE 0 END) AS review_none_count FROM ( SELECT wave_id FROM wms_wave_batch @@ -4054,6 +4085,8 @@ class WaveService extends OrderBaseService { ${storageAssignmentFilterClause.sql} ${expressAssignmentFilterClause.sql} ${printAssignmentFilterClause.sql} + ${reviewAssignmentFilterClause.sql} + ${onlyTodo === 1 ? `\n AND COALESCE(wave_order_stats.order_total, 0) - COALESCE(wave_order_stats.review_fin_count, 0) > 0` : ''} `; const listSql = ` @@ -4080,7 +4113,10 @@ class WaveService extends OrderBaseService { COALESCE(wave_order_stats.post_fin_count, 0) AS post_fin_count, COALESCE(wave_order_stats.post_error_count, 0) AS post_error_count, COALESCE(wave_order_stats.print_none_count, 0) AS print_none_count, - COALESCE(wave_order_stats.print_fin_count, 0) AS print_fin_count + COALESCE(wave_order_stats.print_fin_count, 0) AS print_fin_count, + COALESCE(wave_order_stats.review_fin_count, 0) AS review_fin_count, + COALESCE(wave_order_stats.review_error_count, 0) AS review_error_count, + COALESCE(wave_order_stats.review_none_count, 0) AS review_none_count ${batchListFromSql} ORDER BY wb.total_orders DESC, wb.wave_id DESC LIMIT :limit OFFSET :offset @@ -4100,6 +4136,7 @@ class WaveService extends OrderBaseService { ...storageAssignmentFilterClause.replacements, ...expressAssignmentFilterClause.replacements, ...printAssignmentFilterClause.replacements, + ...reviewAssignmentFilterClause.replacements, limit: pageSize, offset, }, @@ -4112,6 +4149,7 @@ class WaveService extends OrderBaseService { ...storageAssignmentFilterClause.replacements, ...expressAssignmentFilterClause.replacements, ...printAssignmentFilterClause.replacements, + ...reviewAssignmentFilterClause.replacements, }, }), ]); @@ -4146,6 +4184,19 @@ class WaveService extends OrderBaseService { const expressErrorCount = Number(batch && batch.post_error_count || 0); const printNoneCount = Number(batch && batch.print_none_count || 0); const printFinCount = Number(batch && batch.print_fin_count || 0); + const reviewFinCount = Number(batch && batch.review_fin_count || 0); + const reviewErrorCount = Number(batch && batch.review_error_count || 0); + const unreviewedOrderCount = orderCount - reviewFinCount; + + // 复核状态判定:error 统一归入未复核 + let reviewAssignmentStatus; + if (reviewErrorCount > 0 || orderCount === 0 || reviewFinCount === 0) { + reviewAssignmentStatus = 'unreviewed'; + } else if (reviewFinCount === orderCount) { + reviewAssignmentStatus = 'reviewed'; + } else { + reviewAssignmentStatus = 'partially_reviewed'; + } return { wave_id: waveId, @@ -4173,6 +4224,8 @@ class WaveService extends OrderBaseService { partial: '部分打印', finished: '已打印', }), + review_assignment_status: reviewAssignmentStatus, + unreviewed_order_count: unreviewedOrderCount, }; }); @@ -4227,6 +4280,7 @@ class WaveService extends OrderBaseService { t.review_user_name, t.current_cart_id, t.current_cart_code_snapshot, + c.cart_name AS cart_name, t.batch_no, t.device_id, t.start_time, @@ -4236,6 +4290,7 @@ class WaveService extends OrderBaseService { t.create_time, t.update_time FROM wms_wave_pick_task t + LEFT JOIN wms_pick_cart c ON c.id = t.current_cart_id AND c.warehouse_id = t.warehouse_id WHERE t.warehouse_id = :warehouseId ${whereClause.sql} ORDER BY t.create_time DESC @@ -4290,6 +4345,7 @@ class WaveService extends OrderBaseService { review_user_name: String(item && item.review_user_name || '').trim(), current_cart_id: Number(item && item.current_cart_id || 0), current_cart_code_snapshot: String(item && item.current_cart_code_snapshot || '').trim(), + cart_name: String(item && item.cart_name || '').trim(), batch_no: String(item && item.batch_no || '').trim(), device_id: String(item && item.device_id || '').trim(), start_time: item && item.start_time || null, @@ -6437,16 +6493,9 @@ class WaveService extends OrderBaseService { transaction, }); - const orderFlagExpression = this.app.Sequelize.literal(`CASE - WHEN order_flag IS NULL OR order_flag = '' THEN '${WAVE_MANUAL_FETCH_FLAG}' - WHEN order_flag LIKE '%${WAVE_MANUAL_FETCH_FLAG}%' THEN order_flag - ELSE CONCAT(order_flag, ',${WAVE_MANUAL_FETCH_FLAG}') - END`); - await orderModel.update({ wave_id: waveId, wave_no: waveNo, - order_flag: orderFlagExpression, }, { where: { id: { [Op.in]: fetchableOrderIds }, @@ -9019,7 +9068,6 @@ class WaveService extends OrderBaseService { defaultQuantity: Number(defaultQuantity || 0), fetchMode: normalizedFetchMode, maxFetchQuantity: normalizedMaxFetchQuantity, - autoFetchDisabledMarker: WAVE_MANUAL_FETCH_FLAG, }); const startedAt = Date.now(); @@ -9032,7 +9080,6 @@ class WaveService extends OrderBaseService { default_quantity: Number(defaultQuantity || 0), fetch_mode: normalizedFetchMode, ...(normalizedFetchMode === 'single' ? { max_fetch_quantity: normalizedMaxFetchQuantity } : {}), - auto_fetch_disabled_marker: WAVE_MANUAL_FETCH_FLAG, started_at: startedAt, }); @@ -9087,7 +9134,6 @@ class WaveService extends OrderBaseService { fetch_mode: normalizedFetchMode, ...(normalizedFetchMode === 'single' ? { max_fetch_quantity: normalizedMaxFetchQuantity } : {}), ...(normalizedFetchMode === 'single' ? { limit_reached: reachedLimit } : {}), - auto_fetch_disabled_marker: WAVE_MANUAL_FETCH_FLAG, started_at: startedAt, }); } @@ -9112,7 +9158,6 @@ class WaveService extends OrderBaseService { ...(normalizedFetchMode === 'single' ? { max_fetch_quantity: normalizedMaxFetchQuantity } : {}), ...(normalizedFetchMode === 'single' ? { limit_reached: reachedLimit } : {}), ...(normalizedFetchMode === 'single' && reachedLimit ? { stop_reason: '达到最大抓取上限' } : {}), - auto_fetch_disabled_marker: WAVE_MANUAL_FETCH_FLAG, started_at: startedAt, duration_ms: durationMs, }); @@ -9125,7 +9170,6 @@ class WaveService extends OrderBaseService { fetchMode: normalizedFetchMode, maxFetchQuantity: normalizedMaxFetchQuantity, reachedLimit, - autoFetchDisabledMarker: WAVE_MANUAL_FETCH_FLAG, totalRequestQuantity, totalFetchedQuantity, durationMs, @@ -9138,7 +9182,6 @@ class WaveService extends OrderBaseService { default_quantity: Number(defaultQuantity || 0), fetch_mode: normalizedFetchMode, ...(normalizedFetchMode === 'single' ? { max_fetch_quantity: normalizedMaxFetchQuantity } : {}), - auto_fetch_disabled_marker: WAVE_MANUAL_FETCH_FLAG, started_at: startedAt, duration_ms: Date.now() - startedAt, error: error && error.message ? error.message : `${error}`, @@ -9174,7 +9217,6 @@ class WaveService extends OrderBaseService { default_quantity: defaultQuantity, fetch_mode: normalizedFetchMode, ...(normalizedFetchMode === 'single' ? { max_fetch_quantity: normalizedMaxFetchQuantity } : {}), - auto_fetch_disabled_marker: WAVE_MANUAL_FETCH_FLAG, submitted_at: Date.now(), }); @@ -9185,7 +9227,6 @@ class WaveService extends OrderBaseService { defaultQuantity, fetchMode: normalizedFetchMode, maxFetchQuantity: normalizedMaxFetchQuantity, - autoFetchDisabledMarker: WAVE_MANUAL_FETCH_FLAG, }); setImmediate(() => { @@ -9204,7 +9245,6 @@ class WaveService extends OrderBaseService { defaultQuantity, fetchMode: normalizedFetchMode, maxFetchQuantity: normalizedMaxFetchQuantity, - autoFetchDisabledMarker: WAVE_MANUAL_FETCH_FLAG, error: error && error.message ? error.message : error, stack: error && error.stack ? error.stack : '', }); @@ -9218,7 +9258,6 @@ class WaveService extends OrderBaseService { default_quantity: defaultQuantity, fetch_mode: normalizedFetchMode, ...(normalizedFetchMode === 'single' ? { max_fetch_quantity: normalizedMaxFetchQuantity } : {}), - auto_fetch_disabled_marker: WAVE_MANUAL_FETCH_FLAG, message: '任务已提交,后端异步处理中', }); } @@ -9925,16 +9964,9 @@ class WaveService extends OrderBaseService { transaction, }); - const orderFlagExpression = this.app.Sequelize.literal(`CASE - WHEN order_flag IS NULL OR order_flag = '' THEN '${WAVE_MANUAL_FETCH_FLAG}' - WHEN order_flag LIKE '%${WAVE_MANUAL_FETCH_FLAG}%' THEN order_flag - ELSE CONCAT(order_flag, ',${WAVE_MANUAL_FETCH_FLAG}') - END`); - await orderModel.update({ wave_id: waveId, wave_no: waveNo, - order_flag: orderFlagExpression, }, { where: { id: { [Op.in]: fetchableOrderIds }, @@ -11420,8 +11452,11 @@ class WaveService extends OrderBaseService { /** * 公共拣货任务取消流程。 * - * 仅允许取消状态为 0/1/2 的任务。取消后会回收拣货车绑定、 + * 仅允许取消状态为 0/1/2/3 的任务。取消后会回收拣货车绑定、 * 删除任务关联波次并将订单 wave_id 清空,使订单可重新参与后续策略抓取。 + * 当任务状态为 2(待复核)或 3(已完成)时,还会回退已拣货订单的 + * wms_wave_pick_task_order.pick_status 和 order_delivery.pick_status, + * 使订单恢复为未拣货状态。 * * @param {Object} [params={}] 取消参数。 * @param {Array} params.taskIds 任务ID列表。 @@ -11545,7 +11580,7 @@ class WaveService extends OrderBaseService { } const taskStatus = Number(taskRow.status || 0); - if (![ 0, 1, 2 ].includes(taskStatus)) { + if (![ 0, 1, 2, 3 ].includes(taskStatus)) { const error = new Error('当前任务状态不允许取消'); error.statusCode = 400; error.data = { @@ -11646,6 +11681,46 @@ class WaveService extends OrderBaseService { }); } + // 当任务状态为待复核(2)或已完成(3)时,回退订单拣货状态 + if ([ 2, 3 ].includes(taskStatus)) { + await this.ctx.model.query(` + UPDATE wms_wave_pick_task_order + SET pick_status = 0, + picked_time = NULL, + update_time = NOW() + WHERE task_id = :taskId + AND warehouse_id = :warehouseId + AND pick_status = 1 + `, { + replacements: { + taskId, + warehouseId, + }, + transaction, + }); + + const pickedOrderIds = [ ...new Set((Array.isArray(taskOrderRows) ? taskOrderRows : []) + .map(row => Number(row && row.order_id || 0)) + .filter(orderId => Number.isInteger(orderId) && orderId > 0)) ]; + + if (pickedOrderIds.length > 0) { + await orderModel.update({ + pick_status: 'padding', + }, { + where: { + warehouse_id: warehouseId, + id: { + [Op.in]: pickedOrderIds, + }, + pick_status: 'fin', + }, + transaction, + validate: false, + hooks: false, + }); + } + } + await this.ctx.model.query(` UPDATE wms_wave_pick_task SET @@ -11768,8 +11843,9 @@ class WaveService extends OrderBaseService { /** * 取消拣货任务并释放关联波次。 * - * 仅允许取消状态为 0/1/2 的任务。取消后会回收拣货车绑定、 + * 仅允许取消状态为 0/1/2/3 的任务。取消后会回收拣货车绑定、 * 删除任务关联波次并将订单 wave_id 清空,使订单可重新参与后续策略抓取。 + * 当任务状态为 2(待复核)或 3(已完成)时,还会回退已拣货订单的拣货状态。 * * @param {Object} [data={}] 请求参数。 * @param {Array} data.task_ids 任务ID数组。 diff --git a/app/service/systemMethods/pick.js b/app/service/systemMethods/pick.js index b140cc8..566e63c 100644 --- a/app/service/systemMethods/pick.js +++ b/app/service/systemMethods/pick.js @@ -93,6 +93,7 @@ class PickService extends MainService { * @param {string} params.operatorName 操作人名称。 * @param {Array} params.orderIds 波次订单ID集合。 * @param {string} [params.remark=''] 备注。 + * @param {number} [params.source=2] 任务来源:1-PDA扫码补任务,2-后台抓取,默认为2。 * @return {Promise<{task_id: number, task_no: string}>} 创建结果。 */ async createWavePickTask(params = {}) { @@ -103,6 +104,7 @@ class PickService extends MainService { const pickMode = Number(params && params.pickMode || 2); const operatorId = Number(params && params.operatorId || 0); const operatorName = String(params && params.operatorName || '').trim() || 'system'; + const source = Number(params && params.source !== undefined ? params.source : 2); const remark = String(params && params.remark || '').trim(); const normalizedOrderIds = [ ...new Set((Array.isArray(params && params.orderIds) ? params.orderIds : []) .map(id => Number(id || 0)) @@ -161,7 +163,7 @@ class PickService extends MainService { :waveId, :pickMode, 0, - 2, + :source, 1, :orderCount, 0, @@ -178,6 +180,7 @@ class PickService extends MainService { warehouseId, waveId, pickMode, + source, orderCount: normalizedOrderIds.length, operatorId, operatorName, @@ -648,6 +651,7 @@ class PickService extends MainService { operatorName, orderIds: selectedOrderIds, remark: `pick.query keyword=${normalizedKeyword}`, + source: 1, }); return this.success('ok', { diff --git a/app/service/systems/delivery_order.js b/app/service/systems/delivery_order.js index 1512fd3..26bdf67 100644 --- a/app/service/systems/delivery_order.js +++ b/app/service/systems/delivery_order.js @@ -974,6 +974,9 @@ class DeliveryOrderService extends Service { shopNick, sellerNick, buyerNick, + buyerMessage, + sellerMessage, + remark, operatorName, operateTime, totalAmount, @@ -1026,6 +1029,9 @@ class DeliveryOrderService extends Service { shop_nick: shopNick, seller_nick: sellerNick, buyer_nick: buyerNick, + buyer_message: buyerMessage || '', + seller_message: sellerMessage || '', + remark: remark || '', operator_name: resolvedOperatorName, operate_time: operateTime ? new Date(operateTime) : null, total_amount: totalAmount ? parseFloat(totalAmount) : 0, @@ -1042,7 +1048,7 @@ class DeliveryOrderService extends Service { logistics_area_code: logisticsAreaCode || '', is_urgency: isUrgency || 'N', invoice_flag: invoiceFlag || 'N', - status: 'pedding', + status: Number(step) >= DELIVERY_ORDER_STEP.APPROVED ? 'created' : 'pedding', step: Number.isInteger(Number(step)) ? Number(step) : DELIVERY_ORDER_STEP.PENDING_REVIEW, // 收件人信息 name: receiverInfo?.name || '', diff --git a/app/service/systems/pick.js b/app/service/systems/pick.js index 794fba6..c8cc1d3 100644 --- a/app/service/systems/pick.js +++ b/app/service/systems/pick.js @@ -1490,7 +1490,9 @@ class PickSystemService extends Service { t.warehouse_id, t.start_time, t.finish_time, - t.ext_json + t.ext_json, + t.source, + t.current_cart_id FROM wms_wave_pick_task t WHERE t.id = :taskId LIMIT 1 @@ -1504,7 +1506,8 @@ class PickSystemService extends Service { } const taskPickUserId = Number(taskRow.pick_user_id || 0); - if (!Number.isInteger(taskPickUserId) || taskPickUserId !== operatorId) { + // source=2 后台抓取创建的任务 pick_user_id 可能为 0,此时跳过归属校验 + if (taskPickUserId !== 0 && (!Number.isInteger(taskPickUserId) || taskPickUserId !== operatorId)) { throw this.createBusinessError('当前操作人与任务创建人不一致,无权操作', 403); } @@ -1679,6 +1682,13 @@ class PickSystemService extends Service { throw this.createBusinessError('任务已完成或已取消,无法再次提交', 400); } + // source=2 表示后台抓取创建的任务,必须先绑定拣货车才能提交 + const taskSource = Number(taskRow && taskRow.source || 0); + const taskCartId = Number(taskRow && taskRow.current_cart_id || 0); + if (taskSource === 2 && taskCartId <= 0) { + throw this.createBusinessError('后台抓取任务必须先绑定拣货车才能提交', 400); + } + const transaction = await ctx.model.transaction(); try { const taskOrderRows = await ctx.model.query(` diff --git a/app/service/systems/shops.js b/app/service/systems/shops.js index 3aaf497..9f59a94 100644 --- a/app/service/systems/shops.js +++ b/app/service/systems/shops.js @@ -313,6 +313,7 @@ class ShopsService extends Service { custom_name: shopRow.custom_name, status: shopRow.status, auth_expire_at: shopRow.auth_expire_at, + access_token: shopRow.access_token, created_at: shopRow.created_at, updated_at: shopRow.updated_at, }; @@ -471,16 +472,18 @@ class ShopsService extends Service { const shopId = data.id !== undefined ? data.id : (data.shop_id !== undefined ? data.shop_id : data.shopId); const shop = await this.findShopById(shopId); const normalizedShopId = Number(shop.id); - const referencedInterface = await ctx.model.ExpressInterface.findOne({ + const expressInterfaceCount = await ctx.model.ExpressInterface.count({ where: { warehouse_id: this.getCurrentWarehouseId(), shop_id: normalizedShopId, }, - attributes: [ 'id' ], }); - if (referencedInterface) { - throw this.createError('店铺存在快递接口引用,无法删除', 409); + if (expressInterfaceCount > 0) { + throw this.createError( + `该店铺已被 ${expressInterfaceCount} 个快递接口引用,请先解除绑定后再删除`, + 409 + ); } const deletedSuffix = `${Date.now()}_${crypto.randomBytes(4).toString('hex')}`; diff --git a/database/migrations/20260607120000-drop-uk-warehouse-platform-shop-name.js b/database/migrations/20260607120000-drop-uk-warehouse-platform-shop-name.js new file mode 100644 index 0000000..742a928 --- /dev/null +++ b/database/migrations/20260607120000-drop-uk-warehouse-platform-shop-name.js @@ -0,0 +1,67 @@ +'use strict'; + +const TABLE_NAME = 'wms_shops'; +const UNIQUE_INDEX_NAME = 'uk_warehouse_platform_shop_name'; +const PLAIN_INDEX_NAME = 'idx_warehouse_platform_shop_name'; + +/** + * 检查指定表中是否存在指定名称的索引(通过 SHOW INDEX 做幂等判断)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @param {string} indexName 索引名。 + * @returns {Promise} 索引是否存在。 + */ +const hasIndex = async (queryInterface, tableName, indexName) => { + const [rows] = await queryInterface.sequelize.query( + `SHOW INDEX FROM \`${tableName}\` WHERE Key_name = :indexName`, + { replacements: { indexName } } + ); + return rows && rows.length > 0; +}; + +module.exports = { + /** + * 正向迁移:删除唯一约束,改为普通索引。 + * 原因:菜鸟 OAuth 授权回调时,预授权记录(status=0)与已授权记录(status=1)因同名店铺 + * 触发 UNIQUE KEY `uk_warehouse_platform_shop_name` 约束冲突,导致 MySQL UPDATE 失败。 + * 故将此唯一约束降为普通索引,仅保留查询性能。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @returns {Promise} 无返回值。 + */ + async up(queryInterface) { + // 1. 删除唯一索引 + if (await hasIndex(queryInterface, TABLE_NAME, UNIQUE_INDEX_NAME)) { + await queryInterface.sequelize.query( + `ALTER TABLE \`${TABLE_NAME}\` DROP INDEX \`${UNIQUE_INDEX_NAME}\`;` + ); + } + + // 2. 添加普通索引(仅用于查询性能) + if (!(await hasIndex(queryInterface, TABLE_NAME, PLAIN_INDEX_NAME))) { + await queryInterface.sequelize.query( + `ALTER TABLE \`${TABLE_NAME}\` ADD INDEX \`${PLAIN_INDEX_NAME}\` (warehouse_id, platform_code, shop_name);` + ); + } + }, + + /** + * 回滚迁移:恢复唯一约束。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @returns {Promise} 无返回值。 + */ + async down(queryInterface) { + // 1. 删除普通索引 + if (await hasIndex(queryInterface, TABLE_NAME, PLAIN_INDEX_NAME)) { + await queryInterface.sequelize.query( + `ALTER TABLE \`${TABLE_NAME}\` DROP INDEX \`${PLAIN_INDEX_NAME}\`;` + ); + } + + // 2. 恢复唯一索引(幂等:已存在则跳过) + if (!(await hasIndex(queryInterface, TABLE_NAME, UNIQUE_INDEX_NAME))) { + await queryInterface.sequelize.query( + `ALTER TABLE \`${TABLE_NAME}\` ADD UNIQUE INDEX \`${UNIQUE_INDEX_NAME}\` (warehouse_id, platform_code, shop_name);` + ); + } + }, +}; diff --git a/methods/changes/system.json b/methods/changes/system.json index 5c1d9b6..72a7834 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -2888,5 +2888,105 @@ "响应文档中新增 shop_nick 字段说明。" ], "type": "updated" + }, + { + "version": "2026.06.07-system-03", + "date": "2026-06-07", + "summary": "新增 order.pendingOrder.updateAddress:批量修改待处理订单收件地址,限制未分配快递时可用", + "methods": [ + "order.pendingOrder.updateAddress" + ], + "notes": [ + "新增 method:order.pendingOrder.updateAddress,免权限(isNeedAuth=false),需登录", + "功能:批量修改待处理订单收件地址(name/mobile/tel/zip_code/province/city/area/town/detail_address)", + "约束:仅 post_status='none'(未分配快递)的订单可修改;至少提供一个有效地址字段", + "响应:返回 updated_count(实际更新行数)和 ids(请求订单ID数组)" + ], + "type": "added" + }, + { + "version": "2026.06.07-system-04", + "date": "2026-06-07", + "summary": "order.wave.wavePickTaskCancel 扩展可取消状态至 status=3,并新增拣货状态回退", + "methods": [ + "order.wave.wavePickTaskCancel" + ], + "notes": [ + "可取消状态从 [0,1,2] 扩展为 [0,1,2,3](status=3 已完成现在也可取消)", + "取消 status=2(待复核)或 status=3(已完成)任务时,自动回退 wms_wave_pick_task_order.pick_status(1→0)和 order_delivery.pick_status(fin→padding)", + "错误码 400 描述同步更新,补充 403 错误码说明" + ], + "type": "updated" + }, + { + "version": "2026.06.07-system-05", + "date": "2026-06-07", + "summary": "order.wave.wavePickTaskList 响应新增 cart_name 字段(拣货车名称)", + "methods": [ + "order.wave.wavePickTaskList" + ], + "notes": [ + "响应 list 子项新增 cart_name(string):通过 current_cart_id LEFT JOIN wms_pick_cart 表获取,未绑定拣货车时为空字符串。" + ], + "type": "updated" + }, + { + "version": "2026.06.07-system-06", + "date": "2026-06-07", + "summary": "pick.wavePickTaskComplete 新增后台抓取任务(source=2)拣货车绑定校验,未绑定拣货车时拒绝提交", + "methods": [ + "pick.wavePickTaskComplete" + ], + "notes": [ + "description 补充说明:后台抓取创建的任务(source=2)必须先绑定拣货车才能提交,否则返回 400。", + "errors 中 400 错误补充:后台抓取任务(source=2)未绑定拣货车时拒绝提交,错误消息为\"后台抓取任务必须先绑定拣货车才能提交\"。" + ], + "type": "updated" + }, + { + "version": "2026.06.07-system-07", + "date": "2026-06-07", + "summary": "order.wave.batchList 文档修正:移除代码中不存在的 sync_assignment_status 引用", + "methods": [ + "order.wave.batchList" + ], + "notes": [ + "从 where 描述中移除 sync_assignment_status(代码 buildBatchListWhereClause allowedFields 中不存在该字段,BATCH_LIST_ASSIGNMENT_FILTER_SCHEMAS 中也无 review 之外的同步类型)。", + "从 response list 描述中移除 sync_assignment_status(代码响应映射中仅返回 storage/express/print/review 四种 assignment_status,无 sync_assignment_status)。", + "v2026.06.03-system-03 变更记录中声称新增的 sync_assignment_status 实际从未在代码中实现,本次仅为文档修正,不涉及代码变更。" + ], + "type": "updated", + "module": "order.wave" + }, + { + "version": "2026.06.07-system-08", + "date": "2026-06-07", + "summary": "order.recheckOrder.confirmRecheck 补充后置行为说明:波次任务全部复核完成后自动解绑车任务", + "methods": [ + "order.recheckOrder.confirmRecheck" + ], + "notes": [ + "在 description 中补充:确认复核后,若该订单所属波次拣货任务下所有订单均已复核完成,则自动解绑车任务。解绑操作包括:清空 wms_wave_pick_task 的 current_cart_id/current_cart_code_snapshot、停用 wms_pick_task_cart_binding(is_active=0 并记录解绑人和时间)、释放 wms_pick_cart(清空 current_task_id/bind_user_id)。", + "解绑失败仅记录 warn 日志,不影响复核主流程。", + "入参和返回结构未变,仅补充行为说明。" + ], + "type": "updated" + }, + { + "version": "2026.06.07-system-10", + "date": "2026-06-07", + "summary": "移除 order.wave.groupFetch / singleFetch / fetch 响应中已废弃的 auto_fetch_disabled_marker 字段", + "methods": [ + "order.wave.groupFetch", + "order.wave.singleFetch", + "order.wave.fetch" + ], + "notes": [ + "auto_fetch_disabled_marker 字段已从代码 submitFetchTask 响应中移除,文档同步删除该字段的描述。", + "auto_fetch_disabled 字段同样已从代码中移除,且原文档中不存在此字段(仅有 auto_fetch_disabled_marker),无需额外处理。", + "涉及 method:order.wave.groupFetch、order.wave.singleFetch、order.wave.fetch,均移除 response 中的 auto_fetch_disabled_marker 字段。" + ], + "type": "updated", + "module": "order.wave" } ] diff --git a/methods/system.json b/methods/system.json index 7672209..0dd92b8 100644 --- a/methods/system.json +++ b/methods/system.json @@ -3850,6 +3850,120 @@ "解析结果可直接回填到 createOrder 的收件人信息字段", "未识别到的字段返回空字符串" ] + }, + { + "method": "order.pendingOrder.updateAddress", + "description": "批量修改待处理订单的收件地址信息。仅允许修改 post_status='none'(未分配快递)的订单;至少需要提供一个地址字段(name/mobile/tel/zip_code/province/city/area/town/detail_address),空值和纯空白会被忽略。更新成功后写入操作日志。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids", + "type": "number[]", + "required": true, + "source": "body", + "description": "订单ID 正整数数组,不能为空" + }, + { + "name": "name", + "type": "string", + "required": false, + "source": "body", + "description": "收件人姓名" + }, + { + "name": "mobile", + "type": "string", + "required": false, + "source": "body", + "description": "收件人手机号" + }, + { + "name": "tel", + "type": "string", + "required": false, + "source": "body", + "description": "收件人电话" + }, + { + "name": "zip_code", + "type": "string", + "required": false, + "source": "body", + "description": "邮编" + }, + { + "name": "province", + "type": "string", + "required": false, + "source": "body", + "description": "省份" + }, + { + "name": "city", + "type": "string", + "required": false, + "source": "body", + "description": "城市" + }, + { + "name": "area", + "type": "string", + "required": false, + "source": "body", + "description": "区/县" + }, + { + "name": "town", + "type": "string", + "required": false, + "source": "body", + "description": "镇/街道" + }, + { + "name": "detail_address", + "type": "string", + "required": false, + "source": "body", + "description": "详细地址" + } + ], + "response": [ + { + "name": "updated_count", + "type": "number", + "required": true, + "description": "实际更新的订单行数" + }, + { + "name": "ids", + "type": "number[]", + "required": true, + "description": "请求的订单ID数组(原样返回)" + } + ], + "errors": [ + { + "code": 400, + "message": "ids 不能为空" + }, + { + "code": 400, + "message": "至少需要提供一个地址字段进行修改" + }, + { + "code": 400, + "message": "仅允许修改 post_status='none'(未分配快递)的订单;若订单已分配快递则更新行数为 0,不会报错但实际无更新" + } + ] } ] }, @@ -3997,7 +4111,7 @@ }, { "method": "order.recheckOrder.confirmRecheck", - "description": "按订单 ID 确认复核并记录复核任务到 wms_recheck_task(入参兼容 id/orderId)", + "description": "按订单 ID 确认复核并记录复核任务到 wms_recheck_task(入参兼容 id/orderId)。确认复核后,若该订单所属波次拣货任务下所有订单均已复核完成,则自动解绑车任务:清空 wms_wave_pick_task 的车绑定信息(current_cart_id、current_cart_code_snapshot)、停用 wms_pick_task_cart_binding 绑定记录(is_active=0 并记录解绑人和时间)并释放 wms_pick_cart(清空 current_task_id、bind_user_id)。解绑失败仅记录 warn 日志,不影响复核主流程。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -4021,40 +4135,48 @@ { "name": "order_id", "type": "number", + "required": true, "description": "订单 ID" }, { "name": "waybill_no", "type": "string", + "required": true, "description": "运单号" }, { "name": "recheck_status", "type": "string", + "required": true, "description": "复核结果状态" }, { "name": "recheck_time", "type": "string", + "required": true, "description": "复核时间(ISO 字符串)" }, { "name": "review_no", "type": "string", + "required": true, "description": "复核任务编号" } ], "errors": [ { "code": "400", + "message": "订单ID不能为空", "description": "订单ID不能为空" }, { "code": "404", + "message": "未找到对应订单", "description": "未找到对应订单" }, { "code": "400", + "message": "订单未拣货,不允许复核。", "description": "订单未拣货,不允许复核。" } ] @@ -5798,6 +5920,11 @@ "type": "string", "description": "拣货人名称(兼容字段,旧客户端可能使用)" }, + { + "name": "cart_name", + "type": "string", + "description": "拣货车名称(通过 current_cart_id 关联 wms_pick_cart 表获取,未绑定拣货车时为空字符串)" + }, { "name": "start_at", "type": "string", @@ -5833,33 +5960,36 @@ { "name": "total", "type": "number", + "required": true, "description": "总记录数" }, { "name": "page", "type": "number", + "required": true, "description": "当前页码" }, { "name": "page_size", "type": "number", + "required": true, "description": "每页大小" } ], "errors": [ { "code": "400", - "description": "缺少仓库上下文或参数格式错误" + "message": "缺少仓库上下文或参数格式错误" }, { "code": "500", - "description": "查询失败" + "message": "查询失败" } ] }, { "method": "order.wave.wavePickTaskCancel", - "description": "取消拣货任务(批量),同时释放关联波次(物理删除波次记录,订单回池)、解绑拣货车、写操作日志。入参仅支持 task_ids(数组,必填),不再支持单个 task_id。操作人与仓库从请求上下文获取(例如当前登录用户上下文 ctx.user),若上下文缺失接口将返回错误。", + "description": "取消拣货任务(批量)。可取消的状态:0=待开始、1=拣货中、2=待复核(拣货完成)、3=已完成,状态9(已取消)或其他状态不允许取消。同时释放关联波次(物理删除波次记录,订单回池)、解绑拣货车、写操作日志。对于status=2或3的任务,取消时会自动回退订单拣货状态:wms_wave_pick_task_order.pick_status(1→0)、order_delivery.pick_status(fin→padding)。入参仅支持 task_ids(数组,必填),不再支持单个 task_id。操作人与仓库从请求上下文获取(例如当前登录用户上下文 ctx.user),若上下文缺失接口将返回错误。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -5883,41 +6013,50 @@ { "name": "cancelled_count", "type": "number", + "required": false, "description": "成功取消的任务数量" }, { "name": "task_ids", "type": "array", + "required": false, "description": "处理的任务ID数组(若后端返回)" }, { "name": "task_nos", "type": "array", + "required": false, "description": "处理的任务编号数组(若后端返回)" }, { "name": "task_id", "type": "number", + "required": false, "description": "任务ID(历史兼容,若后端仍返回)" }, { "name": "task_no", "type": "string", + "required": false, "description": "任务编号(历史兼容,若后端仍返回)" } ], "errors": [ { "code": "400", - "description": "任务状态不允许取消或入参缺失" + "message": "任务状态不允许取消(仅允许status=0/1/2/3)或入参缺失" + }, + { + "code": "403", + "message": "仅允许取消本人创建的任务(wavePickTaskCancelSelf 接口)" }, { "code": "404", - "description": "任务不存在" + "message": "任务不存在" }, { "code": "500", - "description": "内部错误或事务回滚失败" + "message": "内部错误或事务回滚失败" } ] }, @@ -6736,12 +6875,6 @@ "required": true, "description": "仓库默认抓取数量或全局默认值" }, - { - "name": "auto_fetch_disabled_marker", - "type": "string", - "required": true, - "description": "手动抓取标记;值为 'wave_manual_fetch' 表示手动抓取" - }, { "name": "fetch_mode", "type": "string", @@ -6813,12 +6946,6 @@ "required": true, "description": "仓库默认抓取数量或全局默认值" }, - { - "name": "auto_fetch_disabled_marker", - "type": "string", - "required": true, - "description": "手动抓取标记;值为 'wave_manual_fetch' 表示手动抓取" - }, { "name": "fetch_mode", "type": "string", @@ -6896,12 +7023,6 @@ "required": true, "description": "仓库默认抓取数量或全局默认值" }, - { - "name": "auto_fetch_disabled_marker", - "type": "string", - "required": true, - "description": "手动抓取标记;值为 'wave_manual_fetch' 表示手动抓取" - }, { "name": "fetch_mode", "type": "string", @@ -14210,7 +14331,7 @@ }, { "method": "pick.wavePickTaskComplete", - "description": "完全提交拣货任务。支持 mode=1 全部确认,mode=2 部分确认(需传 order_ids)。提交后根据是否全部完成自动推进任务状态。", + "description": "完全提交拣货任务。支持 mode=1 全部确认,mode=2 部分确认(需传 order_ids)。提交后根据是否全部完成自动推进任务状态。后台抓取创建的任务(source=2)必须先绑定拣货车才能提交,否则返回 400。", "isNeedAuth": false, "isNeedLogin": true, "isNeedRight": false, @@ -14300,7 +14421,7 @@ "errors": [ { "code": 400, - "message": "参数或业务状态不满足提交条件(如 task_id 不合法、mode 非 1/2、部分确认未传 order_ids、任务下无可确认订单等)。" + "message": "参数或业务状态不满足提交条件(如 task_id 不合法、mode 非 1/2、部分确认未传 order_ids、任务下无可确认订单等)。后台抓取任务(source=2)未绑定拣货车时拒绝提交:\"后台抓取任务必须先绑定拣货车才能提交\"。" }, { "code": 401, @@ -19978,7 +20099,7 @@ "type": "object", "required": false, "source": "body", - "description": "筛选白名单字段(object,可选)。仅支持下列字段过滤,且禁止传入 warehouse_id / warehouseId:\n- wave_id(等值)\n- wave_no(模糊)\n- wave_type(等值)\n- wave_status(等值,接口固定叠加状态 0/1)\n- creator(模糊)\n- logistics_name(模糊)\n- item_part_type(等值)\n- item_part(模糊)\n- item_snapshot_key(模糊)\n- item_detail_machine(模糊)\n- distinguish_express(等值)\n- total_orders_min / total_orders_max(范围)\n- processed_orders_min / processed_orders_max(范围)\n- express_assignment_status(等值,string,可选,英文枚举,取值:unassigned、partially_assigned、assigned;语义:按快递分配聚合判断,assigned 表示聚合后全部 fin,partially_assigned 表示部分已分配且不含 error,unassigned 表示全 none 或包含 error(异常并入未分配集合))。\n- print_assignment_status(等值,string,可选,英文枚举,取值:unprinted、partially_printed、printed;语义:按打印分配聚合判断,printed 表示聚合后全部已打印)。\n- storage_assignment_status(等值,string,可选,取值:未分配、部分分配、已分配;默认不传不做限制)。过滤语义:已分配=聚合后全部 fin;部分分配=不含 error,且既不是全 none,也不是全 fin;未分配=全 none 或包含 error(异常并入未分配筛选集合)。说明:返回字段 storage_assignment_status 的展示值保持不变,包含 error 时仍可显示“分配异常”;此处 where 的过滤语义会把异常计入“未分配”,以避免把过滤语义与展示值混淆。\n- source(可选,number)来源过滤:0=普通波次(正常后台操作),1=管理后台策略任务,2=PDA策略任务;不传则不过滤。\n说明:express_assignment_status 与 print_assignment_status 要求使用英文枚举值;storage_assignment_status 仍向后兼容中文展示值。若传入的枚举值不在允许集合内,接口会返回 400(参数校验失败),并在 message 中说明错误字段与允许取值。\n- sync_assignment_status(等值,string,可选,英文枚举,取值:unsynced、partially_synced、synced;语义:按同步状态聚合判断,synced 表示全部 fin,partially_synced 表示部分已同步且不含 error,unsynced 表示全 padding 或包含 error(异常并入未同步集合))。\n- review_assignment_status(等值,string,可选,英文枚举:unreviewed、partially_reviewed、reviewed;分别表示未复核、部分复核、已复核)。" + "description": "筛选白名单字段(object,可选)。仅支持下列字段过滤,且禁止传入 warehouse_id / warehouseId:\n- wave_id(等值)\n- wave_no(模糊)\n- wave_type(等值)\n- wave_status(等值,接口固定叠加状态 0/1)\n- creator(模糊)\n- logistics_name(模糊)\n- item_part_type(等值)\n- item_part(模糊)\n- item_snapshot_key(模糊)\n- item_detail_machine(模糊)\n- distinguish_express(等值)\n- total_orders_min / total_orders_max(范围)\n- processed_orders_min / processed_orders_max(范围)\n- express_assignment_status(等值,string,可选,英文枚举,取值:unassigned、partially_assigned、assigned;语义:按快递分配聚合判断,assigned 表示聚合后全部 fin,partially_assigned 表示部分已分配且不含 error,unassigned 表示全 none 或包含 error(异常并入未分配集合))。\n- print_assignment_status(等值,string,可选,英文枚举,取值:unprinted、partially_printed、printed;语义:按打印分配聚合判断,printed 表示聚合后全部已打印)。\n- storage_assignment_status(等值,string,可选,取值:未分配、部分分配、已分配;默认不传不做限制)。过滤语义:已分配=聚合后全部 fin;部分分配=不含 error,且既不是全 none,也不是全 fin;未分配=全 none 或包含 error(异常并入未分配筛选集合)。说明:返回字段 storage_assignment_status 的展示值保持不变,包含 error 时仍可显示“分配异常”;此处 where 的过滤语义会把异常计入“未分配”,以避免把过滤语义与展示值混淆。\n- source(可选,number)来源过滤:0=普通波次(正常后台操作),1=管理后台策略任务,2=PDA策略任务;不传则不过滤。\n说明:express_assignment_status 与 print_assignment_status 要求使用英文枚举值;storage_assignment_status 仍向后兼容中文展示值。若传入的枚举值不在允许集合内,接口会返回 400(参数校验失败),并在 message 中说明错误字段与允许取值。\n- review_assignment_status(等值,string,可选,英文枚举:unreviewed、partially_reviewed、reviewed;分别表示未复核、部分复核、已复核)。" } ], "response": [ @@ -19986,7 +20107,7 @@ "name": "list", "type": "array", "required": true, - "description": "波次列表,包含波次基础信息与状态汇总(order_count / storage_assignment_status / express_assignment_status / print_assignment_status / sync_assignment_status / review_assignment_status / unreviewed_order_count)。每条记录新增字段 source(number):来源标识,0=普通波次(正常后台操作),1=管理后台策略任务,2=PDA策略任务。" + "description": "波次列表,包含波次基础信息与状态汇总(order_count / storage_assignment_status / express_assignment_status / print_assignment_status / review_assignment_status / unreviewed_order_count)。每条记录新增字段 source(number):来源标识,0=普通波次(正常后台操作),1=管理后台策略任务,2=PDA策略任务。" }, { "name": "pagination", From 0e50ff667108fd83649ae185da6642590d46f48c Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 8 Jun 2026 08:58:13 +0800 Subject: [PATCH 068/550] 1 --- app/dict/businessDict.js | 4 + app/model/order_delivery.js | 2 +- app/service/systemMethods/order/base.js | 4 - .../systemMethods/order/pendingOrder.js | 2090 ++++++++++++++++- app/service/systemMethods/order/print.js | 36 +- .../systemMethods/order/recheckOrder.js | 1540 +++++++++++- app/service/systemMethods/order/wave.js | 121 +- app/service/systems/order_print.js | 278 ++- methods/changes/system.json | 155 ++ methods/system.json | 1913 ++++++++++++++- .../systemMethods/order.base.step.test.js | 8 +- ...wave.waveStrategyFallbackOrderList.test.js | 77 +- 12 files changed, 6012 insertions(+), 216 deletions(-) diff --git a/app/dict/businessDict.js b/app/dict/businessDict.js index 43fa09c..4925f6d 100644 --- a/app/dict/businessDict.js +++ b/app/dict/businessDict.js @@ -66,6 +66,10 @@ module.exports = { ORDER_STORAGE_UNALLOCATE_FAILED: '取消分配储位失败', ORDER_EXPRESS_ALLOCATE_SUBMITTED: '分配快递任务已提交', ORDER_EXPRESS_ALLOCATE_FAILED: '分配快递失败', + ORDER_INTERCEPT_REQUEST: '请求订单拦截', + ORDER_INTERCEPT_CANCEL: '解除订单拦截', + ORDER_LOCK: '订单锁定', + ORDER_UNLOCK: '订单解锁', // 库存管理 STOCK_IN: '商品入库', diff --git a/app/model/order_delivery.js b/app/model/order_delivery.js index 3fb0320..c64c861 100644 --- a/app/model/order_delivery.js +++ b/app/model/order_delivery.js @@ -6,7 +6,7 @@ module.exports = app => { // 状态机枚举定义 const StatusEnum = { - STATUS: [ 'pedding', 'created', 'cancel', 'error' ], + STATUS: [ 'pedding', 'created', 'cancel', 'error', 'finished' ], SYNC_STATUS: [ 'padding', 'fin', 'error' ], POST_STATUS: [ 'padding', 'fin', 'timeout', 'error', 'none' ], STORAGE_STATUS: [ 'padding', 'fin', 'error', 'none' ], diff --git a/app/service/systemMethods/order/base.js b/app/service/systemMethods/order/base.js index b05162f..7b6ef22 100644 --- a/app/service/systemMethods/order/base.js +++ b/app/service/systemMethods/order/base.js @@ -107,10 +107,6 @@ const MODULE_CONFIGS = Object.freeze({ operator: 'eq', value: 0, }, - wave_scan_result: { - operator: 'eq', - value: 2, - }, }, }, outboundOrder: { diff --git a/app/service/systemMethods/order/pendingOrder.js b/app/service/systemMethods/order/pendingOrder.js index ea89c51..9fd63ae 100644 --- a/app/service/systemMethods/order/pendingOrder.js +++ b/app/service/systemMethods/order/pendingOrder.js @@ -19,6 +19,18 @@ const ALLOCATE_STORAGE_PROGRESS_MAP = Object.freeze({ unknown: 0, }); +const BATCH_INTERCEPT_TASK_CACHE_KEY_PREFIX = 'order:batch-intercept:'; +const BATCH_INTERCEPT_TASK_CACHE_TTL_SECONDS = 60 * 60 * 24; + +const BATCH_LOCK_TASK_CACHE_KEY_PREFIX = 'order:batch-lock:'; +const BATCH_LOCK_TASK_CACHE_TTL_SECONDS = 60 * 60 * 24; + +const BATCH_UNLOCK_TASK_CACHE_KEY_PREFIX = 'order:batch-unlock:'; +const BATCH_UNLOCK_TASK_CACHE_TTL_SECONDS = 60 * 60 * 24; + +const BATCH_UNINTERCEPT_TASK_CACHE_KEY_PREFIX = 'order:batch-unintercept:'; +const BATCH_UNINTERCEPT_TASK_CACHE_TTL_SECONDS = 60 * 60 * 24; + class PendingOrderService extends OrderBaseService { /** * 初始化待处理订单系统方法的免登录、免权限、免日志和免鉴权配置。 @@ -28,9 +40,9 @@ class PendingOrderService extends OrderBaseService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,updateOrderPlatform,updateOrderExpress,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress'; - const _noNeedLog = 'list,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,parseAddress'; - const _noNeedAuth = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,updateOrderPlatform,updateOrderExpress,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress'; + const _noNeedRight = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,updateOrderPlatform,updateOrderExpress,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress'; + const _noNeedLog = 'list,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress'; + const _noNeedAuth = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,updateOrderPlatform,updateOrderExpress,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -2333,6 +2345,2078 @@ class PendingOrderService extends OrderBaseService { }); } + /** + * 归一化 ids 入参为去重后的正整数数组。 + * + * 支持数组、逗号分隔字符串、单个 number/string。 + * + * @param {Array|number|string} value 原始 ids 入参。 + * @return {Array} 归一化后的 ids 数组。 + */ + normalizeIdsInput(value) { + let sourceList = []; + + if (Array.isArray(value)) { + sourceList = value; + } else if (typeof value === 'string') { + sourceList = value.split(','); + } else if (typeof value === 'number') { + sourceList = [ value ]; + } else { + sourceList = []; + } + + const normalizedIds = sourceList + .map(item => String(item === undefined || item === null ? '' : item).trim()) + .filter(item => item !== '') + .map(item => Number(item)) + .filter(item => Number.isInteger(item) && item > 0); + + return [ ...new Set(normalizedIds) ]; + } + + /** + * 批量拦截订单。 + * + * 提交后台异步任务,将给定订单的 intercept_status 更新为 'requested'。 + * 仅处理当前仓库上下文内的订单。 + * + * @param {Object} data 请求参数。 + * @param {Array} [data.order_ids] 订单ID数组(下划线写法)。 + * @param {Array} [data.orderIds] 订单ID数组(驼峰别名)。 + * @param {Array} [data.ids] 订单ID数组(简写别名)。 + * @param {string} [data.task_id] 任务ID(用于查询进度)。 + * @param {string} [data.taskId] 任务ID(驼峰别名)。 + * @return {Promise} 提交结果,包含 task_id、状态与 accepted_at。 + */ + async batchIntercept(data = {}) { + const warehouseId = Number(this.getWarehouseId() || 0); + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + const normalizedOrderIds = this.normalizeBatchInterceptOrderIds(data); + if (normalizedOrderIds.length === 0) { + throw new Error('order_ids 参数不能为空或格式错误'); + } + + const requestedTaskId = this.normalizeBatchInterceptTaskId(data); + const taskId = requestedTaskId || this.generateBatchInterceptTaskId(warehouseId); + const existingTask = await this.getBatchInterceptTaskProgress(taskId); + + if (existingTask) { + return this.success('ok', { + status: 'success', + task_id: taskId, + warehouse_id: Number(existingTask.warehouse_id || warehouseId), + state: String(existingTask.state || 'submitted').trim() || 'submitted', + message: '批量拦截任务已存在,请勿重复提交。', + accepted_at: existingTask.accepted_at || existingTask.submitted_at || new Date().toISOString(), + }); + } + + const acceptedAt = new Date().toISOString(); + await this.setBatchInterceptTaskProgress(taskId, 'submitted', { + warehouse_id: warehouseId, + order_ids: normalizedOrderIds.join(','), + order_id_list: normalizedOrderIds, + total_order_count: normalizedOrderIds.length, + processed_order_count: 0, + intercepted_order_count: 0, + progress_percent: 0, + submitted_at: Date.now(), + accepted_at: acceptedAt, + result: null, + error: '', + error_code: '', + }); + + this.ctx.logger.info('[order.pendingOrder.batchIntercept] 任务提交成功', { + taskId, + warehouseId, + orderCount: normalizedOrderIds.length, + }); + + setImmediate(() => { + this.runBatchInterceptTask({ + taskId, + warehouseId, + orderIds: normalizedOrderIds, + }).catch(error => { + this.ctx.logger.error('[order.pendingOrder.batchIntercept] 后台任务异常', { + taskId, + warehouseId, + orderCount: normalizedOrderIds.length, + error: error && error.message ? error.message : error, + stack: error && error.stack ? error.stack : '', + }); + }); + }); + + return this.success('ok', { + status: 'success', + task_id: taskId, + warehouse_id: warehouseId, + message: '批量拦截任务已提交。', + accepted_at: acceptedAt, + }); + } + + /** + * 查询批量拦截任务进度。 + * + * @param {Object} data 请求参数。 + * @param {string} data.task_id 任务ID(下划线写法)。 + * @param {string} data.taskId 任务ID(驼峰写法)。 + * @return {Promise} 任务进度响应。 + */ + async batchInterceptTaskProgress(data = {}) { + const taskId = this.normalizeBatchInterceptTaskId(data); + if (!taskId) { + return this.fail('task_id 参数不能为空', 400); + } + + const cachedProgress = await this.getBatchInterceptTaskProgress(taskId); + if (!cachedProgress) { + return this.success('ok', { + task_id: taskId, + state: 'not_found', + }); + } + + const state = String(cachedProgress.state || 'submitted').trim() || 'submitted'; + const payload = { + task_id: taskId, + state, + warehouse_id: Number(cachedProgress.warehouse_id || 0), + submitted_at: cachedProgress.submitted_at || null, + start_time: cachedProgress.start_time || null, + end_time: cachedProgress.end_time || null, + }; + + if (state === 'submitted' || state === 'running') { + payload.progress_percent = Number(cachedProgress.progress_percent || 0); + payload.total_order_count = Number(cachedProgress.total_order_count || 0); + payload.processed_order_count = Number(cachedProgress.processed_order_count || 0); + payload.intercepted_order_count = Number(cachedProgress.intercepted_order_count || 0); + } + + if (state === 'success') { + const result = this.isPlainObject(cachedProgress.result) ? cachedProgress.result : {}; + payload.progress_percent = Number(cachedProgress.progress_percent || 100); + payload.total_order_count = Number(result.total_order_count || 0); + payload.intercepted_order_count = Number(result.intercepted_order_count || 0); + payload.intercepted_order_ids = this.normalizeIdsInput(result.intercepted_order_ids); + payload.duration_ms = Number(result.duration_ms || cachedProgress.duration_ms || 0); + } + + if (state === 'failed') { + payload.progress_percent = Number(cachedProgress.progress_percent || 0); + payload.total_order_count = Number(cachedProgress.total_order_count || 0); + payload.intercepted_order_count = Number(cachedProgress.intercepted_order_count || 0); + payload.error_message = String(cachedProgress.error || '').trim(); + payload.error_code = String(cachedProgress.error_code || '').trim() || 'BATCH_INTERCEPT_FAILED'; + payload.duration_ms = Number(cachedProgress.duration_ms || 0); + } + + return this.success('ok', payload); + } + + /** + * 生成可追踪的批量拦截任务ID。 + * + * 格式:order_intercept_{warehouseId}_{timestamp}_{rand}。 + * + * @param {number|string} warehouseId 仓库ID。 + * @return {string} 任务ID。 + */ + generateBatchInterceptTaskId(warehouseId = 0) { + const normalizedWarehouseId = Number(warehouseId || 0); + const safeWarehouseId = Number.isInteger(normalizedWarehouseId) && normalizedWarehouseId > 0 + ? normalizedWarehouseId + : 0; + const timestamp = Math.floor(Date.now() / 1000); + const randomPart = Math.random().toString(36).slice(2, 6); + return `order_intercept_${safeWarehouseId}_${timestamp}_${randomPart}`; + } + + /** + * 归一化批量拦截任务ID。 + * + * @param {Object} data 请求参数。 + * @param {string} data.task_id 任务ID(下划线写法)。 + * @param {string} data.taskId 任务ID(驼峰写法)。 + * @return {string} 归一化后的任务ID。 + */ + normalizeBatchInterceptTaskId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.task_id || normalizedData.taskId || '').trim(); + } + + /** + * 归一化批量拦截的订单ID参数。 + * 兼容 order_ids / orderIds / ids 三种入参别名。 + * + * @param {Object} data 请求参数。 + * @return {Array} 归一化后的订单ID数组。 + */ + normalizeBatchInterceptOrderIds(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + const rawOrderIds = normalizedData.order_ids !== undefined + ? normalizedData.order_ids + : normalizedData.orderIds !== undefined + ? normalizedData.orderIds + : normalizedData.ids !== undefined + ? normalizedData.ids + : []; + + return this.normalizeIdsInput(rawOrderIds); + } + + /** + * 获取批量拦截任务缓存键。 + * + * @param {string} taskId 任务ID。 + * @return {string} 缓存键。 + */ + getBatchInterceptTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + + return `${BATCH_INTERCEPT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 写入批量拦截任务进度缓存。 + * + * @param {string} taskId 任务ID。 + * @param {string} state 任务状态(submitted|running|success|failed)。 + * @param {Object} data 进度或结果数据。 + * @return {Promise} 无返回值。 + */ + async setBatchInterceptTaskProgress(taskId = '', state = 'submitted', data = {}) { + const cacheKey = this.getBatchInterceptTaskCacheKey(taskId); + if (!cacheKey) { + return; + } + + const safeData = this.isPlainObject(data) ? data : {}; + const mergedPayload = { + ...(await this.getBatchInterceptTaskProgress(taskId) || {}), + ...safeData, + task_id: String(taskId || '').trim(), + state: String(state || '').trim() || 'submitted', + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync(cacheKey, mergedPayload, BATCH_INTERCEPT_TASK_CACHE_TTL_SECONDS); + } catch (error) { + this.ctx.logger.warn( + `[order.pendingOrder.batchIntercept] 写入任务进度缓存失败: ${error && error.message ? error.message : error}` + ); + } + } + + /** + * 读取批量拦截任务进度缓存。 + * + * @param {string} taskId 任务ID。 + * @return {Promise} 缓存对象。 + */ + async getBatchInterceptTaskProgress(taskId = '') { + const cacheKey = this.getBatchInterceptTaskCacheKey(taskId); + if (!cacheKey) { + return null; + } + + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (!this.isPlainObject(cached)) { + return null; + } + + return cached; + } catch (error) { + this.ctx.logger.warn( + `[order.pendingOrder.batchIntercept] 读取任务进度缓存失败: ${error && error.message ? error.message : error}` + ); + return null; + } + } + + /** + * 执行批量拦截后台任务。 + * + * 直接对给定订单ID数组,将 intercept_status 更新为 'requested',并写入操作日志。 + * 仅处理当前仓库上下文内的订单。 + * + * @param {Object} params 任务参数。 + * @param {string} params.taskId 任务ID。 + * @param {number|string} [params.warehouseId] 仓库ID(兜底)。 + * @param {Array|number|string} [params.orderIds] 订单ID集合(兜底)。 + * @return {Promise} 无返回值。 + */ + async runBatchInterceptTask(params = {}) { + const { ctx } = this; + const normalizedTaskId = String(params && params.taskId || '').trim(); + if (!normalizedTaskId) { + throw new Error('taskId 不能为空'); + } + + const cachedTask = await this.getBatchInterceptTaskProgress(normalizedTaskId); + const warehouseId = Number( + cachedTask && cachedTask.warehouse_id !== undefined + ? cachedTask.warehouse_id + : params && params.warehouseId + ); + const orderIds = this.normalizeIdsInput( + cachedTask && cachedTask.order_ids !== undefined + ? cachedTask.order_ids + : params && params.orderIds + ); + + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + await this.setBatchInterceptTaskProgress(normalizedTaskId, 'failed', { + end_time: Date.now(), + error: 'warehouse_id 参数不合法', + error_code: 'INVALID_WAREHOUSE_ID', + }); + return; + } + + if (orderIds.length === 0) { + await this.setBatchInterceptTaskProgress(normalizedTaskId, 'failed', { + warehouse_id: warehouseId, + end_time: Date.now(), + error: 'order_ids 参数不能为空或格式错误', + error_code: 'INVALID_ORDER_IDS', + }); + return; + } + + const startTime = Date.now(); + await this.setBatchInterceptTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + order_ids: orderIds.join(','), + order_id_list: orderIds, + total_order_count: orderIds.length, + processed_order_count: 0, + intercepted_order_count: 0, + progress_percent: 0, + start_time: startTime, + end_time: null, + result: null, + error: '', + error_code: '', + failed_order_id: 0, + }); + + try { + const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + const { Op } = this.app.Sequelize; + + // 分批查询订单是否存在且属于当前仓库 + const BATCH_SIZE = 500; + const validOrderRows = []; + + for (let i = 0; i < orderIds.length; i += BATCH_SIZE) { + const chunkOrderIds = orderIds.slice(i, i + BATCH_SIZE); + if (chunkOrderIds.length === 0) { + continue; + } + + const orderRows = await orderModel.findAll({ + attributes: [ 'id', 'delivery_order_code', 'pre_delivery_order_code' ], + where: { + warehouse_id: warehouseId, + id: { + [Op.in]: chunkOrderIds, + }, + }, + raw: true, + }); + + for (const row of (Array.isArray(orderRows) ? orderRows : [])) { + validOrderRows.push(row); + } + } + + const interceptedOrderIds = []; + const operator = this.getOrderLogOperator(); + const logWarehouseId = this.getOrderLogWarehouseId(warehouseId); + + const normalizedOrderRows = Array.isArray(validOrderRows) ? validOrderRows : []; + const totalOrderCount = orderIds.length; + const validOrderCount = normalizedOrderRows.length; + + await this.setBatchInterceptTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + total_order_count: totalOrderCount, + valid_order_count: validOrderCount, + }); + + if (validOrderCount === 0) { + const durationMs = Date.now() - startTime; + await this.setBatchInterceptTaskProgress(normalizedTaskId, 'success', { + warehouse_id: warehouseId, + total_order_count: totalOrderCount, + intercepted_order_count: 0, + progress_percent: 100, + end_time: Date.now(), + duration_ms: durationMs, + result: { + order_ids: orderIds, + intercepted_order_ids: [], + intercepted_order_count: 0, + total_order_count: totalOrderCount, + duration_ms: durationMs, + message: '未找到可拦截的当前仓库订单', + }, + }); + return; + } + + // 分批更新拦截状态,每批最多500条 + const UPDATE_CHUNK_SIZE = 500; + for (let i = 0; i < normalizedOrderRows.length; i += UPDATE_CHUNK_SIZE) { + const chunkRows = normalizedOrderRows.slice(i, i + UPDATE_CHUNK_SIZE); + if (chunkRows.length === 0) { + continue; + } + + const chunkOrderIds = chunkRows.map(row => Number(row.id)).filter(id => Number.isInteger(id) && id > 0); + if (chunkOrderIds.length === 0) { + continue; + } + + const now = new Date(); + const updateValues = { + intercept_status: 'requested', + updated_at: now, + }; + + await orderModel.update(updateValues, { + where: { + id: { + [Op.in]: chunkOrderIds, + }, + }, + }); + + // 写入操作日志 + const logPayloads = chunkRows.map(row => { + const orderId = Number(row.id || 0); + const orderNo = String(row.delivery_order_code || row.pre_delivery_order_code || '').trim(); + if (!Number.isInteger(orderId) || orderId <= 0) { + return null; + } + + return { + businessType: 'order', + businessId: logWarehouseId, + operationCode: 'ORDER_INTERCEPT_REQUEST', + operator, + extras: { + warehouseId: logWarehouseId, + orderId, + orderNo, + newInterceptStatus: 'requested', + }, + beforeChanges: null, + }; + }).filter(Boolean); + + if (logPayloads.length > 0) { + try { + const operationLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog; + if (operationLogService && typeof operationLogService.createOperationLogs === 'function') { + await operationLogService.createOperationLogs(logPayloads); + } + } catch (logErr) { + ctx.logger.warn( + `[order.pendingOrder.batchIntercept] 批量写操作日志失败,不影响主流程, count=${logPayloads.length}, error=${logErr.message}` + ); + } + } + + for (const orderId of chunkOrderIds) { + interceptedOrderIds.push(orderId); + } + + // 更新进度 + const progressPercent = validOrderCount > 0 + ? Math.min(99, Math.round((interceptedOrderIds.length / validOrderCount) * 100)) + : 0; + + await this.setBatchInterceptTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + total_order_count: totalOrderCount, + intercepted_order_count: interceptedOrderIds.length, + progress_percent: progressPercent, + }); + } + + const durationMs = Date.now() - startTime; + await this.setBatchInterceptTaskProgress(normalizedTaskId, 'success', { + warehouse_id: warehouseId, + total_order_count: totalOrderCount, + intercepted_order_count: interceptedOrderIds.length, + progress_percent: 100, + end_time: Date.now(), + duration_ms: durationMs, + result: { + order_ids: orderIds, + intercepted_order_ids: interceptedOrderIds, + intercepted_order_count: interceptedOrderIds.length, + total_order_count: totalOrderCount, + duration_ms: durationMs, + message: `已拦截 ${interceptedOrderIds.length} 条订单`, + }, + }); + } catch (error) { + await this.setBatchInterceptTaskProgress(normalizedTaskId, 'failed', { + warehouse_id: warehouseId, + progress_percent: 0, + end_time: Date.now(), + duration_ms: Date.now() - startTime, + error: error && error.message ? error.message : `${error}`, + error_code: 'BATCH_INTERCEPT_FAILED', + }); + } + } + + /** + * 批量锁定订单(异步任务模式)。 + * + * 将给定订单的 lock_status 批量更新为 'warehouse',并写入操作日志 ORDER_LOCK。 + * 仅操作当前仓库上下文内的订单,每批最多 500 条。 + * + * @param {Object} data 请求参数。 + * @param {Array} data.order_ids 订单ID数组。 + * @param {string} [data.task_id] 可选的任务ID(用于幂等续查)。 + * @return {Promise} 提交响应,含 task_id。 + */ + async batchLock(data = {}) { + const warehouseId = Number(this.getWarehouseId() || 0); + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + const normalizedOrderIds = this.normalizeBatchLockOrderIds(data); + if (normalizedOrderIds.length === 0) { + throw new Error('order_ids 参数不能为空或格式错误'); + } + + const requestedTaskId = this.normalizeBatchLockTaskId(data); + const taskId = requestedTaskId || this.generateBatchLockTaskId(warehouseId); + const existingTask = await this.getBatchLockTaskProgress(taskId); + + if (existingTask) { + return this.success('ok', { + status: 'success', + task_id: taskId, + warehouse_id: Number(existingTask.warehouse_id || warehouseId), + state: String(existingTask.state || 'submitted').trim() || 'submitted', + message: '批量锁定任务已存在,请勿重复提交。', + accepted_at: existingTask.accepted_at || existingTask.submitted_at || new Date().toISOString(), + }); + } + + const acceptedAt = new Date().toISOString(); + await this.setBatchLockTaskProgress(taskId, 'submitted', { + warehouse_id: warehouseId, + order_ids: normalizedOrderIds.join(','), + order_id_list: normalizedOrderIds, + total_order_count: normalizedOrderIds.length, + processed_order_count: 0, + locked_order_count: 0, + progress_percent: 0, + submitted_at: Date.now(), + accepted_at: acceptedAt, + result: null, + error: '', + error_code: '', + }); + + this.ctx.logger.info('[order.pendingOrder.batchLock] 任务提交成功', { + taskId, + warehouseId, + orderCount: normalizedOrderIds.length, + }); + + setImmediate(() => { + this.runBatchLockTask({ + taskId, + warehouseId, + orderIds: normalizedOrderIds, + }).catch(error => { + this.ctx.logger.error('[order.pendingOrder.batchLock] 后台任务异常', { + taskId, + warehouseId, + orderCount: normalizedOrderIds.length, + error: error && error.message ? error.message : error, + stack: error && error.stack ? error.stack : '', + }); + }); + }); + + return this.success('ok', { + status: 'success', + task_id: taskId, + warehouse_id: warehouseId, + message: '批量锁定任务已提交。', + accepted_at: acceptedAt, + }); + } + + /** + * 查询批量锁定任务进度。 + * + * @param {Object} data 请求参数。 + * @param {string} data.task_id 任务ID(下划线写法)。 + * @param {string} data.taskId 任务ID(驼峰写法)。 + * @return {Promise} 任务进度响应。 + */ + async batchLockTaskProgress(data = {}) { + const taskId = this.normalizeBatchLockTaskId(data); + if (!taskId) { + return this.fail('task_id 参数不能为空', 400); + } + + const cachedProgress = await this.getBatchLockTaskProgress(taskId); + if (!cachedProgress) { + return this.success('ok', { + task_id: taskId, + state: 'not_found', + }); + } + + const state = String(cachedProgress.state || 'submitted').trim() || 'submitted'; + const payload = { + task_id: taskId, + state, + warehouse_id: Number(cachedProgress.warehouse_id || 0), + submitted_at: cachedProgress.submitted_at || null, + start_time: cachedProgress.start_time || null, + end_time: cachedProgress.end_time || null, + }; + + if (state === 'submitted' || state === 'running') { + payload.progress_percent = Number(cachedProgress.progress_percent || 0); + payload.total_order_count = Number(cachedProgress.total_order_count || 0); + payload.processed_order_count = Number(cachedProgress.processed_order_count || 0); + payload.locked_order_count = Number(cachedProgress.locked_order_count || 0); + } + + if (state === 'success') { + const result = this.isPlainObject(cachedProgress.result) ? cachedProgress.result : {}; + payload.progress_percent = Number(cachedProgress.progress_percent || 100); + payload.total_order_count = Number(result.total_order_count || 0); + payload.locked_order_count = Number(result.locked_order_count || 0); + payload.locked_order_ids = this.normalizeIdsInput(result.locked_order_ids); + payload.duration_ms = Number(result.duration_ms || cachedProgress.duration_ms || 0); + } + + if (state === 'failed') { + payload.progress_percent = Number(cachedProgress.progress_percent || 0); + payload.total_order_count = Number(cachedProgress.total_order_count || 0); + payload.locked_order_count = Number(cachedProgress.locked_order_count || 0); + payload.error_message = String(cachedProgress.error || '').trim(); + payload.error_code = String(cachedProgress.error_code || '').trim() || 'BATCH_LOCK_FAILED'; + payload.duration_ms = Number(cachedProgress.duration_ms || 0); + } + + return this.success('ok', payload); + } + + /** + * 生成可追踪的批量锁定任务ID。 + * + * 格式:order_lock_{warehouseId}_{timestamp}_{rand}。 + * + * @param {number|string} warehouseId 仓库ID。 + * @return {string} 任务ID。 + */ + generateBatchLockTaskId(warehouseId = 0) { + const normalizedWarehouseId = Number(warehouseId || 0); + const safeWarehouseId = Number.isInteger(normalizedWarehouseId) && normalizedWarehouseId > 0 + ? normalizedWarehouseId + : 0; + const timestamp = Math.floor(Date.now() / 1000); + const randomPart = Math.random().toString(36).slice(2, 6); + return `order_lock_${safeWarehouseId}_${timestamp}_${randomPart}`; + } + + /** + * 归一化批量锁定任务ID。 + * + * @param {Object} data 请求参数。 + * @param {string} data.task_id 任务ID(下划线写法)。 + * @param {string} data.taskId 任务ID(驼峰写法)。 + * @return {string} 归一化后的任务ID。 + */ + normalizeBatchLockTaskId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.task_id || normalizedData.taskId || '').trim(); + } + + /** + * 归一化批量锁定的订单ID参数。 + * 兼容 order_ids / orderIds / ids 三种入参别名。 + * + * @param {Object} data 请求参数。 + * @return {Array} 归一化后的订单ID数组。 + */ + normalizeBatchLockOrderIds(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + const rawOrderIds = normalizedData.order_ids !== undefined + ? normalizedData.order_ids + : normalizedData.orderIds !== undefined + ? normalizedData.orderIds + : normalizedData.ids !== undefined + ? normalizedData.ids + : []; + + return this.normalizeIdsInput(rawOrderIds); + } + + /** + * 获取批量锁定任务缓存键。 + * + * @param {string} taskId 任务ID。 + * @return {string} 缓存键。 + */ + getBatchLockTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + + return `${BATCH_LOCK_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 写入批量锁定任务进度缓存。 + * + * @param {string} taskId 任务ID。 + * @param {string} state 任务状态(submitted|running|success|failed)。 + * @param {Object} data 进度或结果数据。 + * @return {Promise} 无返回值。 + */ + async setBatchLockTaskProgress(taskId = '', state = 'submitted', data = {}) { + const cacheKey = this.getBatchLockTaskCacheKey(taskId); + if (!cacheKey) { + return; + } + + const safeData = this.isPlainObject(data) ? data : {}; + const mergedPayload = { + ...(await this.getBatchLockTaskProgress(taskId) || {}), + ...safeData, + task_id: String(taskId || '').trim(), + state: String(state || '').trim() || 'submitted', + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync(cacheKey, mergedPayload, BATCH_LOCK_TASK_CACHE_TTL_SECONDS); + } catch (error) { + this.ctx.logger.warn( + `[order.pendingOrder.batchLock] 写入任务进度缓存失败: ${error && error.message ? error.message : error}` + ); + } + } + + /** + * 读取批量锁定任务进度缓存。 + * + * @param {string} taskId 任务ID。 + * @return {Promise} 缓存对象。 + */ + async getBatchLockTaskProgress(taskId = '') { + const cacheKey = this.getBatchLockTaskCacheKey(taskId); + if (!cacheKey) { + return null; + } + + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (!this.isPlainObject(cached)) { + return null; + } + + return cached; + } catch (error) { + this.ctx.logger.warn( + `[order.pendingOrder.batchLock] 读取任务进度缓存失败: ${error && error.message ? error.message : error}` + ); + return null; + } + } + + /** + * 执行批量锁定后台任务。 + * + * 直接对给定订单ID数组,将 lock_status 更新为 'warehouse',并写入操作日志 ORDER_LOCK。 + * 仅处理当前仓库上下文内的订单,每批最多 500 条。 + * + * @param {Object} params 任务参数。 + * @param {string} params.taskId 任务ID。 + * @param {number|string} [params.warehouseId] 仓库ID(兜底)。 + * @param {Array|number|string} [params.orderIds] 订单ID集合(兜底)。 + * @return {Promise} 无返回值。 + */ + async runBatchLockTask(params = {}) { + const { ctx } = this; + const normalizedTaskId = String(params && params.taskId || '').trim(); + if (!normalizedTaskId) { + throw new Error('taskId 不能为空'); + } + + const cachedTask = await this.getBatchLockTaskProgress(normalizedTaskId); + const warehouseId = Number( + cachedTask && cachedTask.warehouse_id !== undefined + ? cachedTask.warehouse_id + : params && params.warehouseId + ); + const orderIds = this.normalizeIdsInput( + cachedTask && cachedTask.order_ids !== undefined + ? cachedTask.order_ids + : params && params.orderIds + ); + + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + await this.setBatchLockTaskProgress(normalizedTaskId, 'failed', { + end_time: Date.now(), + error: 'warehouse_id 参数不合法', + error_code: 'INVALID_WAREHOUSE_ID', + }); + return; + } + + if (orderIds.length === 0) { + await this.setBatchLockTaskProgress(normalizedTaskId, 'failed', { + warehouse_id: warehouseId, + end_time: Date.now(), + error: 'order_ids 参数不能为空或格式错误', + error_code: 'INVALID_ORDER_IDS', + }); + return; + } + + const startTime = Date.now(); + await this.setBatchLockTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + order_ids: orderIds.join(','), + order_id_list: orderIds, + total_order_count: orderIds.length, + processed_order_count: 0, + locked_order_count: 0, + progress_percent: 0, + start_time: startTime, + end_time: null, + result: null, + error: '', + error_code: '', + failed_order_id: 0, + }); + + try { + const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + const { Op } = this.app.Sequelize; + + // 分批查询订单是否存在且属于当前仓库 + const BATCH_SIZE = 500; + const validOrderRows = []; + + for (let i = 0; i < orderIds.length; i += BATCH_SIZE) { + const chunkOrderIds = orderIds.slice(i, i + BATCH_SIZE); + if (chunkOrderIds.length === 0) { + continue; + } + + const orderRows = await orderModel.findAll({ + attributes: [ 'id', 'delivery_order_code', 'pre_delivery_order_code' ], + where: { + warehouse_id: warehouseId, + id: { + [Op.in]: chunkOrderIds, + }, + }, + raw: true, + }); + + for (const row of (Array.isArray(orderRows) ? orderRows : [])) { + validOrderRows.push(row); + } + } + + const lockedOrderIds = []; + const operator = this.getOrderLogOperator(); + const logWarehouseId = this.getOrderLogWarehouseId(warehouseId); + + const normalizedOrderRows = Array.isArray(validOrderRows) ? validOrderRows : []; + const totalOrderCount = orderIds.length; + const validOrderCount = normalizedOrderRows.length; + + await this.setBatchLockTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + total_order_count: totalOrderCount, + valid_order_count: validOrderCount, + }); + + if (validOrderCount === 0) { + const durationMs = Date.now() - startTime; + await this.setBatchLockTaskProgress(normalizedTaskId, 'success', { + warehouse_id: warehouseId, + total_order_count: totalOrderCount, + locked_order_count: 0, + progress_percent: 100, + end_time: Date.now(), + duration_ms: durationMs, + result: { + order_ids: orderIds, + locked_order_ids: [], + locked_order_count: 0, + total_order_count: totalOrderCount, + duration_ms: durationMs, + message: '未找到可锁定的当前仓库订单', + }, + }); + return; + } + + // 分批更新锁定状态,每批最多500条 + const UPDATE_CHUNK_SIZE = 500; + for (let i = 0; i < normalizedOrderRows.length; i += UPDATE_CHUNK_SIZE) { + const chunkRows = normalizedOrderRows.slice(i, i + UPDATE_CHUNK_SIZE); + if (chunkRows.length === 0) { + continue; + } + + const chunkOrderIds = chunkRows.map(row => Number(row.id)).filter(id => Number.isInteger(id) && id > 0); + if (chunkOrderIds.length === 0) { + continue; + } + + const now = new Date(); + const updateValues = { + lock_status: 'warehouse', + updated_at: now, + }; + + await orderModel.update(updateValues, { + where: { + id: { + [Op.in]: chunkOrderIds, + }, + }, + }); + + // 写入操作日志 ORDER_LOCK + const logPayloads = chunkRows.map(row => { + const orderId = Number(row.id || 0); + const orderNo = String(row.delivery_order_code || row.pre_delivery_order_code || '').trim(); + if (!Number.isInteger(orderId) || orderId <= 0) { + return null; + } + + return { + businessType: 'order', + businessId: logWarehouseId, + operationCode: 'ORDER_LOCK', + operator, + extras: { + warehouseId: logWarehouseId, + orderId, + orderNo, + newLockStatus: 'warehouse', + }, + beforeChanges: null, + }; + }).filter(Boolean); + + if (logPayloads.length > 0) { + try { + const operationLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog; + if (operationLogService && typeof operationLogService.createOperationLogs === 'function') { + await operationLogService.createOperationLogs(logPayloads); + } + } catch (logErr) { + ctx.logger.warn( + `[order.pendingOrder.batchLock] 批量写操作日志失败,不影响主流程, count=${logPayloads.length}, error=${logErr.message}` + ); + } + } + + for (const orderId of chunkOrderIds) { + lockedOrderIds.push(orderId); + } + + // 更新进度 + const progressPercent = validOrderCount > 0 + ? Math.min(99, Math.round((lockedOrderIds.length / validOrderCount) * 100)) + : 0; + + await this.setBatchLockTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + total_order_count: totalOrderCount, + locked_order_count: lockedOrderIds.length, + progress_percent: progressPercent, + }); + } + + const durationMs = Date.now() - startTime; + await this.setBatchLockTaskProgress(normalizedTaskId, 'success', { + warehouse_id: warehouseId, + total_order_count: totalOrderCount, + locked_order_count: lockedOrderIds.length, + progress_percent: 100, + end_time: Date.now(), + duration_ms: durationMs, + result: { + order_ids: orderIds, + locked_order_ids: lockedOrderIds, + locked_order_count: lockedOrderIds.length, + total_order_count: totalOrderCount, + duration_ms: durationMs, + message: `已锁定 ${lockedOrderIds.length} 条订单`, + }, + }); + } catch (error) { + await this.setBatchLockTaskProgress(normalizedTaskId, 'failed', { + warehouse_id: warehouseId, + progress_percent: 0, + end_time: Date.now(), + duration_ms: Date.now() - startTime, + error: error && error.message ? error.message : `${error}`, + error_code: 'BATCH_LOCK_FAILED', + }); + } + } + + /** + * 批量解锁订单(异步任务模式)。 + * + * 将给定订单的 lock_status 批量更新为 'none',并写入操作日志 ORDER_UNLOCK。 + * 仅操作当前仓库上下文内的订单。 + * + * @param {Object} data 请求参数。 + * @param {Array} data.order_ids 订单ID数组。 + * @param {string} [data.task_id] 可选的任务ID(用于幂等续查)。 + * @return {Promise} 提交响应,含 task_id。 + */ + async batchUnlock(data = {}) { + const warehouseId = Number(this.getWarehouseId() || 0); + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + const normalizedOrderIds = this.normalizeBatchUnlockOrderIds(data); + if (normalizedOrderIds.length === 0) { + throw new Error('order_ids 参数不能为空或格式错误'); + } + + const requestedTaskId = this.normalizeBatchUnlockTaskId(data); + const taskId = requestedTaskId || this.generateBatchUnlockTaskId(warehouseId); + const existingTask = await this.getBatchUnlockTaskProgress(taskId); + + if (existingTask) { + return this.success('ok', { + status: 'success', + task_id: taskId, + warehouse_id: Number(existingTask.warehouse_id || warehouseId), + state: String(existingTask.state || 'submitted').trim() || 'submitted', + message: '批量解锁任务已存在,请勿重复提交。', + accepted_at: existingTask.accepted_at || existingTask.submitted_at || new Date().toISOString(), + }); + } + + const acceptedAt = new Date().toISOString(); + await this.setBatchUnlockTaskProgress(taskId, 'submitted', { + warehouse_id: warehouseId, + order_ids: normalizedOrderIds.join(','), + order_id_list: normalizedOrderIds, + total_order_count: normalizedOrderIds.length, + processed_order_count: 0, + unlocked_order_count: 0, + progress_percent: 0, + submitted_at: Date.now(), + accepted_at: acceptedAt, + result: null, + error: '', + error_code: '', + }); + + this.ctx.logger.info('[order.pendingOrder.batchUnlock] 任务提交成功', { + taskId, + warehouseId, + orderCount: normalizedOrderIds.length, + }); + + setImmediate(() => { + this.runBatchUnlockTask({ + taskId, + warehouseId, + orderIds: normalizedOrderIds, + }).catch(error => { + this.ctx.logger.error('[order.pendingOrder.batchUnlock] 后台任务异常', { + taskId, + warehouseId, + orderCount: normalizedOrderIds.length, + error: error && error.message ? error.message : error, + stack: error && error.stack ? error.stack : '', + }); + }); + }); + + return this.success('ok', { + status: 'success', + task_id: taskId, + warehouse_id: warehouseId, + message: '批量解锁任务已提交。', + accepted_at: acceptedAt, + }); + } + + /** + * 查询批量解锁任务进度。 + * + * @param {Object} data 请求参数。 + * @param {string} data.task_id 任务ID(下划线写法)。 + * @param {string} data.taskId 任务ID(驼峰写法)。 + * @return {Promise} 任务进度响应。 + */ + async batchUnlockTaskProgress(data = {}) { + const taskId = this.normalizeBatchUnlockTaskId(data); + if (!taskId) { + return this.fail('task_id 参数不能为空', 400); + } + + const cachedProgress = await this.getBatchUnlockTaskProgress(taskId); + if (!cachedProgress) { + return this.success('ok', { + task_id: taskId, + state: 'not_found', + }); + } + + const state = String(cachedProgress.state || 'submitted').trim() || 'submitted'; + const payload = { + task_id: taskId, + state, + warehouse_id: Number(cachedProgress.warehouse_id || 0), + submitted_at: cachedProgress.submitted_at || null, + start_time: cachedProgress.start_time || null, + end_time: cachedProgress.end_time || null, + }; + + if (state === 'submitted' || state === 'running') { + payload.progress_percent = Number(cachedProgress.progress_percent || 0); + payload.total_order_count = Number(cachedProgress.total_order_count || 0); + payload.processed_order_count = Number(cachedProgress.processed_order_count || 0); + payload.unlocked_order_count = Number(cachedProgress.unlocked_order_count || 0); + } + + if (state === 'success') { + const result = this.isPlainObject(cachedProgress.result) ? cachedProgress.result : {}; + payload.progress_percent = Number(cachedProgress.progress_percent || 100); + payload.total_order_count = Number(result.total_order_count || 0); + payload.unlocked_order_count = Number(result.unlocked_order_count || 0); + payload.unlocked_order_ids = this.normalizeIdsInput(result.unlocked_order_ids); + payload.duration_ms = Number(result.duration_ms || cachedProgress.duration_ms || 0); + } + + if (state === 'failed') { + payload.progress_percent = Number(cachedProgress.progress_percent || 0); + payload.total_order_count = Number(cachedProgress.total_order_count || 0); + payload.unlocked_order_count = Number(cachedProgress.unlocked_order_count || 0); + payload.error_message = String(cachedProgress.error || '').trim(); + payload.error_code = String(cachedProgress.error_code || '').trim() || 'BATCH_UNLOCK_FAILED'; + payload.duration_ms = Number(cachedProgress.duration_ms || 0); + } + + return this.success('ok', payload); + } + + /** + * 生成可追踪的批量解锁任务ID。 + * + * 格式:order_unlock_{warehouseId}_{timestamp}_{rand}。 + * + * @param {number|string} warehouseId 仓库ID。 + * @return {string} 任务ID。 + */ + generateBatchUnlockTaskId(warehouseId = 0) { + const normalizedWarehouseId = Number(warehouseId || 0); + const safeWarehouseId = Number.isInteger(normalizedWarehouseId) && normalizedWarehouseId > 0 + ? normalizedWarehouseId + : 0; + const timestamp = Math.floor(Date.now() / 1000); + const randomPart = Math.random().toString(36).slice(2, 6); + return `order_unlock_${safeWarehouseId}_${timestamp}_${randomPart}`; + } + + /** + * 归一化批量解锁任务ID。 + * + * @param {Object} data 请求参数。 + * @param {string} data.task_id 任务ID(下划线写法)。 + * @param {string} data.taskId 任务ID(驼峰写法)。 + * @return {string} 归一化后的任务ID。 + */ + normalizeBatchUnlockTaskId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.task_id || normalizedData.taskId || '').trim(); + } + + /** + * 归一化批量解锁的订单ID参数。 + * 兼容 order_ids / orderIds / ids 三种入参别名。 + * + * @param {Object} data 请求参数。 + * @return {Array} 归一化后的订单ID数组。 + */ + normalizeBatchUnlockOrderIds(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + const rawOrderIds = normalizedData.order_ids !== undefined + ? normalizedData.order_ids + : normalizedData.orderIds !== undefined + ? normalizedData.orderIds + : normalizedData.ids !== undefined + ? normalizedData.ids + : []; + + return this.normalizeIdsInput(rawOrderIds); + } + + /** + * 获取批量解锁任务缓存键。 + * + * @param {string} taskId 任务ID。 + * @return {string} 缓存键。 + */ + getBatchUnlockTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + + return `${BATCH_UNLOCK_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 写入批量解锁任务进度缓存。 + * + * @param {string} taskId 任务ID。 + * @param {string} state 任务状态(submitted|running|success|failed)。 + * @param {Object} data 进度或结果数据。 + * @return {Promise} 无返回值。 + */ + async setBatchUnlockTaskProgress(taskId = '', state = 'submitted', data = {}) { + const cacheKey = this.getBatchUnlockTaskCacheKey(taskId); + if (!cacheKey) { + return; + } + + const safeData = this.isPlainObject(data) ? data : {}; + const mergedPayload = { + ...(await this.getBatchUnlockTaskProgress(taskId) || {}), + ...safeData, + task_id: String(taskId || '').trim(), + state: String(state || '').trim() || 'submitted', + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync(cacheKey, mergedPayload, BATCH_UNLOCK_TASK_CACHE_TTL_SECONDS); + } catch (error) { + this.ctx.logger.warn( + `[order.pendingOrder.batchUnlock] 写入任务进度缓存失败: ${error && error.message ? error.message : error}` + ); + } + } + + /** + * 读取批量解锁任务进度缓存。 + * + * @param {string} taskId 任务ID。 + * @return {Promise} 缓存对象。 + */ + async getBatchUnlockTaskProgress(taskId = '') { + const cacheKey = this.getBatchUnlockTaskCacheKey(taskId); + if (!cacheKey) { + return null; + } + + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (!this.isPlainObject(cached)) { + return null; + } + + return cached; + } catch (error) { + this.ctx.logger.warn( + `[order.pendingOrder.batchUnlock] 读取任务进度缓存失败: ${error && error.message ? error.message : error}` + ); + return null; + } + } + + /** + * 执行批量解锁后台任务。 + * + * 直接对给定订单ID数组,将 lock_status 更新为 'none',并写入操作日志 ORDER_UNLOCK。 + * 仅处理当前仓库上下文内的订单。 + * + * @param {Object} params 任务参数。 + * @param {string} params.taskId 任务ID。 + * @param {number|string} [params.warehouseId] 仓库ID(兜底)。 + * @param {Array|number|string} [params.orderIds] 订单ID集合(兜底)。 + * @return {Promise} 无返回值。 + */ + async runBatchUnlockTask(params = {}) { + const { ctx } = this; + const normalizedTaskId = String(params && params.taskId || '').trim(); + if (!normalizedTaskId) { + throw new Error('taskId 不能为空'); + } + + const cachedTask = await this.getBatchUnlockTaskProgress(normalizedTaskId); + const warehouseId = Number( + cachedTask && cachedTask.warehouse_id !== undefined + ? cachedTask.warehouse_id + : params && params.warehouseId + ); + const orderIds = this.normalizeIdsInput( + cachedTask && cachedTask.order_ids !== undefined + ? cachedTask.order_ids + : params && params.orderIds + ); + + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + await this.setBatchUnlockTaskProgress(normalizedTaskId, 'failed', { + end_time: Date.now(), + error: 'warehouse_id 参数不合法', + error_code: 'INVALID_WAREHOUSE_ID', + }); + return; + } + + if (orderIds.length === 0) { + await this.setBatchUnlockTaskProgress(normalizedTaskId, 'failed', { + warehouse_id: warehouseId, + end_time: Date.now(), + error: 'order_ids 参数不能为空或格式错误', + error_code: 'INVALID_ORDER_IDS', + }); + return; + } + + const startTime = Date.now(); + await this.setBatchUnlockTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + order_ids: orderIds.join(','), + order_id_list: orderIds, + total_order_count: orderIds.length, + processed_order_count: 0, + unlocked_order_count: 0, + progress_percent: 0, + start_time: startTime, + end_time: null, + result: null, + error: '', + error_code: '', + failed_order_id: 0, + }); + + try { + const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + const { Op } = this.app.Sequelize; + + // 分批查询订单是否存在且属于当前仓库 + const BATCH_SIZE = 500; + const validOrderRows = []; + + for (let i = 0; i < orderIds.length; i += BATCH_SIZE) { + const chunkOrderIds = orderIds.slice(i, i + BATCH_SIZE); + if (chunkOrderIds.length === 0) { + continue; + } + + const orderRows = await orderModel.findAll({ + attributes: [ 'id', 'delivery_order_code', 'pre_delivery_order_code' ], + where: { + warehouse_id: warehouseId, + id: { + [Op.in]: chunkOrderIds, + }, + }, + raw: true, + }); + + for (const row of (Array.isArray(orderRows) ? orderRows : [])) { + validOrderRows.push(row); + } + } + + const unlockedOrderIds = []; + const operator = this.getOrderLogOperator(); + const logWarehouseId = this.getOrderLogWarehouseId(warehouseId); + + const normalizedOrderRows = Array.isArray(validOrderRows) ? validOrderRows : []; + const totalOrderCount = orderIds.length; + const validOrderCount = normalizedOrderRows.length; + + await this.setBatchUnlockTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + total_order_count: totalOrderCount, + valid_order_count: validOrderCount, + }); + + if (validOrderCount === 0) { + const durationMs = Date.now() - startTime; + await this.setBatchUnlockTaskProgress(normalizedTaskId, 'success', { + warehouse_id: warehouseId, + total_order_count: totalOrderCount, + unlocked_order_count: 0, + progress_percent: 100, + end_time: Date.now(), + duration_ms: durationMs, + result: { + order_ids: orderIds, + unlocked_order_ids: [], + unlocked_order_count: 0, + total_order_count: totalOrderCount, + duration_ms: durationMs, + message: '未找到可解锁的当前仓库订单', + }, + }); + return; + } + + // 分批更新解锁状态,每批最多500条 + const UPDATE_CHUNK_SIZE = 500; + for (let i = 0; i < normalizedOrderRows.length; i += UPDATE_CHUNK_SIZE) { + const chunkRows = normalizedOrderRows.slice(i, i + UPDATE_CHUNK_SIZE); + if (chunkRows.length === 0) { + continue; + } + + const chunkOrderIds = chunkRows.map(row => Number(row.id)).filter(id => Number.isInteger(id) && id > 0); + if (chunkOrderIds.length === 0) { + continue; + } + + const now = new Date(); + const updateValues = { + lock_status: 'none', + updated_at: now, + }; + + await orderModel.update(updateValues, { + where: { + id: { + [Op.in]: chunkOrderIds, + }, + }, + }); + + // 写入操作日志 ORDER_UNLOCK + const logPayloads = chunkRows.map(row => { + const orderId = Number(row.id || 0); + const orderNo = String(row.delivery_order_code || row.pre_delivery_order_code || '').trim(); + if (!Number.isInteger(orderId) || orderId <= 0) { + return null; + } + + return { + businessType: 'order', + businessId: logWarehouseId, + operationCode: 'ORDER_UNLOCK', + operator, + extras: { + warehouseId: logWarehouseId, + orderId, + orderNo, + newLockStatus: 'none', + }, + beforeChanges: null, + }; + }).filter(Boolean); + + if (logPayloads.length > 0) { + try { + const operationLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog; + if (operationLogService && typeof operationLogService.createOperationLogs === 'function') { + await operationLogService.createOperationLogs(logPayloads); + } + } catch (logErr) { + ctx.logger.warn( + `[order.pendingOrder.batchUnlock] 批量写操作日志失败,不影响主流程, count=${logPayloads.length}, error=${logErr.message}` + ); + } + } + + for (const orderId of chunkOrderIds) { + unlockedOrderIds.push(orderId); + } + + // 更新进度 + const progressPercent = validOrderCount > 0 + ? Math.min(99, Math.round((unlockedOrderIds.length / validOrderCount) * 100)) + : 0; + + await this.setBatchUnlockTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + total_order_count: totalOrderCount, + unlocked_order_count: unlockedOrderIds.length, + progress_percent: progressPercent, + }); + } + + const durationMs = Date.now() - startTime; + await this.setBatchUnlockTaskProgress(normalizedTaskId, 'success', { + warehouse_id: warehouseId, + total_order_count: totalOrderCount, + unlocked_order_count: unlockedOrderIds.length, + progress_percent: 100, + end_time: Date.now(), + duration_ms: durationMs, + result: { + order_ids: orderIds, + unlocked_order_ids: unlockedOrderIds, + unlocked_order_count: unlockedOrderIds.length, + total_order_count: totalOrderCount, + duration_ms: durationMs, + message: `已解锁 ${unlockedOrderIds.length} 条订单`, + }, + }); + } catch (error) { + await this.setBatchUnlockTaskProgress(normalizedTaskId, 'failed', { + warehouse_id: warehouseId, + progress_percent: 0, + end_time: Date.now(), + duration_ms: Date.now() - startTime, + error: error && error.message ? error.message : `${error}`, + error_code: 'BATCH_UNLOCK_FAILED', + }); + } + } + + /** + * 批量解除拦截订单(异步任务模式)。 + * + * 将给定订单的 intercept_status 批量更新为 'none',并写入操作日志 ORDER_INTERCEPT_CANCEL。 + * 仅操作当前仓库上下文内的订单。 + * + * @param {Object} data 请求参数。 + * @param {Array} [data.order_ids] 订单ID数组(下划线写法)。 + * @param {Array} [data.orderIds] 订单ID数组(驼峰别名)。 + * @param {Array} [data.ids] 订单ID数组(简写别名)。 + * @param {string} [data.task_id] 任务ID(用于查询进度)。 + * @param {string} [data.taskId] 任务ID(驼峰别名)。 + * @return {Promise} 提交结果,包含 task_id、状态与 accepted_at。 + */ + async batchUnintercept(data = {}) { + const warehouseId = Number(this.getWarehouseId() || 0); + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + const normalizedOrderIds = this.normalizeBatchUninterceptOrderIds(data); + if (normalizedOrderIds.length === 0) { + throw new Error('order_ids 参数不能为空或格式错误'); + } + + const requestedTaskId = this.normalizeBatchUninterceptTaskId(data); + const taskId = requestedTaskId || this.generateBatchUninterceptTaskId(warehouseId); + const existingTask = await this.getBatchUninterceptTaskProgress(taskId); + + if (existingTask) { + return this.success('ok', { + status: 'success', + task_id: taskId, + warehouse_id: Number(existingTask.warehouse_id || warehouseId), + state: String(existingTask.state || 'submitted').trim() || 'submitted', + message: '批量解除拦截任务已存在,请勿重复提交。', + accepted_at: existingTask.accepted_at || existingTask.submitted_at || new Date().toISOString(), + }); + } + + const acceptedAt = new Date().toISOString(); + await this.setBatchUninterceptTaskProgress(taskId, 'submitted', { + warehouse_id: warehouseId, + order_ids: normalizedOrderIds.join(','), + order_id_list: normalizedOrderIds, + total_order_count: normalizedOrderIds.length, + processed_order_count: 0, + unintercepted_order_count: 0, + progress_percent: 0, + submitted_at: Date.now(), + accepted_at: acceptedAt, + result: null, + error: '', + error_code: '', + }); + + this.ctx.logger.info('[order.pendingOrder.batchUnintercept] 任务提交成功', { + taskId, + warehouseId, + orderCount: normalizedOrderIds.length, + }); + + setImmediate(() => { + this.runBatchUninterceptTask({ + taskId, + warehouseId, + orderIds: normalizedOrderIds, + }).catch(error => { + this.ctx.logger.error('[order.pendingOrder.batchUnintercept] 后台任务异常', { + taskId, + warehouseId, + orderCount: normalizedOrderIds.length, + error: error && error.message ? error.message : error, + stack: error && error.stack ? error.stack : '', + }); + }); + }); + + return this.success('ok', { + status: 'success', + task_id: taskId, + warehouse_id: warehouseId, + message: '批量解除拦截任务已提交。', + accepted_at: acceptedAt, + }); + } + + /** + * 查询批量解除拦截任务进度。 + * + * @param {Object} data 请求参数。 + * @param {string} data.task_id 任务ID(下划线写法)。 + * @param {string} data.taskId 任务ID(驼峰写法)。 + * @return {Promise} 任务进度响应。 + */ + async batchUninterceptTaskProgress(data = {}) { + const taskId = this.normalizeBatchUninterceptTaskId(data); + if (!taskId) { + return this.fail('task_id 参数不能为空', 400); + } + + const cachedProgress = await this.getBatchUninterceptTaskProgress(taskId); + if (!cachedProgress) { + return this.success('ok', { + task_id: taskId, + state: 'not_found', + }); + } + + const state = String(cachedProgress.state || 'submitted').trim() || 'submitted'; + const payload = { + task_id: taskId, + state, + warehouse_id: Number(cachedProgress.warehouse_id || 0), + submitted_at: cachedProgress.submitted_at || null, + start_time: cachedProgress.start_time || null, + end_time: cachedProgress.end_time || null, + }; + + if (state === 'submitted' || state === 'running') { + payload.progress_percent = Number(cachedProgress.progress_percent || 0); + payload.total_order_count = Number(cachedProgress.total_order_count || 0); + payload.processed_order_count = Number(cachedProgress.processed_order_count || 0); + payload.unintercepted_order_count = Number(cachedProgress.unintercepted_order_count || 0); + } + + if (state === 'success') { + const result = this.isPlainObject(cachedProgress.result) ? cachedProgress.result : {}; + payload.progress_percent = Number(cachedProgress.progress_percent || 100); + payload.total_order_count = Number(result.total_order_count || 0); + payload.unintercepted_order_count = Number(result.unintercepted_order_count || 0); + payload.unintercepted_order_ids = this.normalizeIdsInput(result.unintercepted_order_ids); + payload.duration_ms = Number(result.duration_ms || cachedProgress.duration_ms || 0); + } + + if (state === 'failed') { + payload.progress_percent = Number(cachedProgress.progress_percent || 0); + payload.total_order_count = Number(cachedProgress.total_order_count || 0); + payload.unintercepted_order_count = Number(cachedProgress.unintercepted_order_count || 0); + payload.error_message = String(cachedProgress.error || '').trim(); + payload.error_code = String(cachedProgress.error_code || '').trim() || 'BATCH_UNINTERCEPT_FAILED'; + payload.duration_ms = Number(cachedProgress.duration_ms || 0); + } + + return this.success('ok', payload); + } + + /** + * 生成可追踪的批量解除拦截任务ID。 + * + * 格式:order_unintercept_{warehouseId}_{timestamp}_{rand}。 + * + * @param {number|string} warehouseId 仓库ID。 + * @return {string} 任务ID。 + */ + generateBatchUninterceptTaskId(warehouseId = 0) { + const normalizedWarehouseId = Number(warehouseId || 0); + const safeWarehouseId = Number.isInteger(normalizedWarehouseId) && normalizedWarehouseId > 0 + ? normalizedWarehouseId + : 0; + const timestamp = Math.floor(Date.now() / 1000); + const randomPart = Math.random().toString(36).slice(2, 6); + return `order_unintercept_${safeWarehouseId}_${timestamp}_${randomPart}`; + } + + /** + * 归一化批量解除拦截任务ID。 + * + * @param {Object} data 请求参数。 + * @param {string} data.task_id 任务ID(下划线写法)。 + * @param {string} data.taskId 任务ID(驼峰写法)。 + * @return {string} 归一化后的任务ID。 + */ + normalizeBatchUninterceptTaskId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.task_id || normalizedData.taskId || '').trim(); + } + + /** + * 归一化批量解除拦截的订单ID参数。 + * 兼容 order_ids / orderIds / ids 三种入参别名。 + * + * @param {Object} data 请求参数。 + * @return {Array} 归一化后的订单ID数组。 + */ + normalizeBatchUninterceptOrderIds(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + const rawOrderIds = normalizedData.order_ids !== undefined + ? normalizedData.order_ids + : normalizedData.orderIds !== undefined + ? normalizedData.orderIds + : normalizedData.ids !== undefined + ? normalizedData.ids + : []; + + return this.normalizeIdsInput(rawOrderIds); + } + + /** + * 获取批量解除拦截任务缓存键。 + * + * @param {string} taskId 任务ID。 + * @return {string} 缓存键。 + */ + getBatchUninterceptTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + + return `${BATCH_UNINTERCEPT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 写入批量解除拦截任务进度缓存。 + * + * @param {string} taskId 任务ID。 + * @param {string} state 任务状态(submitted|running|success|failed)。 + * @param {Object} data 进度或结果数据。 + * @return {Promise} 无返回值。 + */ + async setBatchUninterceptTaskProgress(taskId = '', state = 'submitted', data = {}) { + const cacheKey = this.getBatchUninterceptTaskCacheKey(taskId); + if (!cacheKey) { + return; + } + + const safeData = this.isPlainObject(data) ? data : {}; + const mergedPayload = { + ...(await this.getBatchUninterceptTaskProgress(taskId) || {}), + ...safeData, + task_id: String(taskId || '').trim(), + state: String(state || '').trim() || 'submitted', + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync(cacheKey, mergedPayload, BATCH_UNINTERCEPT_TASK_CACHE_TTL_SECONDS); + } catch (error) { + this.ctx.logger.warn( + `[order.pendingOrder.batchUnintercept] 写入任务进度缓存失败: ${error && error.message ? error.message : error}` + ); + } + } + + /** + * 读取批量解除拦截任务进度缓存。 + * + * @param {string} taskId 任务ID。 + * @return {Promise} 缓存对象。 + */ + async getBatchUninterceptTaskProgress(taskId = '') { + const cacheKey = this.getBatchUninterceptTaskCacheKey(taskId); + if (!cacheKey) { + return null; + } + + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (!this.isPlainObject(cached)) { + return null; + } + + return cached; + } catch (error) { + this.ctx.logger.warn( + `[order.pendingOrder.batchUnintercept] 读取任务进度缓存失败: ${error && error.message ? error.message : error}` + ); + return null; + } + } + + /** + * 执行批量解除拦截后台任务。 + * + * 直接对给定订单ID数组,将 intercept_status 更新为 'none',并写入操作日志 ORDER_INTERCEPT_CANCEL。 + * 仅处理当前仓库上下文内的订单。 + * + * @param {Object} params 任务参数。 + * @param {string} params.taskId 任务ID。 + * @param {number|string} [params.warehouseId] 仓库ID(兜底)。 + * @param {Array|number|string} [params.orderIds] 订单ID集合(兜底)。 + * @return {Promise} 无返回值。 + */ + async runBatchUninterceptTask(params = {}) { + const { ctx } = this; + const normalizedTaskId = String(params && params.taskId || '').trim(); + if (!normalizedTaskId) { + throw new Error('taskId 不能为空'); + } + + const cachedTask = await this.getBatchUninterceptTaskProgress(normalizedTaskId); + const warehouseId = Number( + cachedTask && cachedTask.warehouse_id !== undefined + ? cachedTask.warehouse_id + : params && params.warehouseId + ); + const orderIds = this.normalizeIdsInput( + cachedTask && cachedTask.order_ids !== undefined + ? cachedTask.order_ids + : params && params.orderIds + ); + + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + await this.setBatchUninterceptTaskProgress(normalizedTaskId, 'failed', { + end_time: Date.now(), + error: 'warehouse_id 参数不合法', + error_code: 'INVALID_WAREHOUSE_ID', + }); + return; + } + + if (orderIds.length === 0) { + await this.setBatchUninterceptTaskProgress(normalizedTaskId, 'failed', { + warehouse_id: warehouseId, + end_time: Date.now(), + error: 'order_ids 参数不能为空或格式错误', + error_code: 'INVALID_ORDER_IDS', + }); + return; + } + + const startTime = Date.now(); + await this.setBatchUninterceptTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + order_ids: orderIds.join(','), + order_id_list: orderIds, + total_order_count: orderIds.length, + processed_order_count: 0, + unintercepted_order_count: 0, + progress_percent: 0, + start_time: startTime, + end_time: null, + result: null, + error: '', + error_code: '', + failed_order_id: 0, + }); + + try { + const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + const { Op } = this.app.Sequelize; + + // 分批查询订单是否存在且属于当前仓库 + const BATCH_SIZE = 500; + const validOrderRows = []; + + for (let i = 0; i < orderIds.length; i += BATCH_SIZE) { + const chunkOrderIds = orderIds.slice(i, i + BATCH_SIZE); + if (chunkOrderIds.length === 0) { + continue; + } + + const orderRows = await orderModel.findAll({ + attributes: [ 'id', 'delivery_order_code', 'pre_delivery_order_code' ], + where: { + warehouse_id: warehouseId, + id: { + [Op.in]: chunkOrderIds, + }, + }, + raw: true, + }); + + for (const row of (Array.isArray(orderRows) ? orderRows : [])) { + validOrderRows.push(row); + } + } + + const uninterceptedOrderIds = []; + const operator = this.getOrderLogOperator(); + const logWarehouseId = this.getOrderLogWarehouseId(warehouseId); + + const normalizedOrderRows = Array.isArray(validOrderRows) ? validOrderRows : []; + const totalOrderCount = orderIds.length; + const validOrderCount = normalizedOrderRows.length; + + await this.setBatchUninterceptTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + total_order_count: totalOrderCount, + valid_order_count: validOrderCount, + }); + + if (validOrderCount === 0) { + const durationMs = Date.now() - startTime; + await this.setBatchUninterceptTaskProgress(normalizedTaskId, 'success', { + warehouse_id: warehouseId, + total_order_count: totalOrderCount, + unintercepted_order_count: 0, + progress_percent: 100, + end_time: Date.now(), + duration_ms: durationMs, + result: { + order_ids: orderIds, + unintercepted_order_ids: [], + unintercepted_order_count: 0, + total_order_count: totalOrderCount, + duration_ms: durationMs, + message: '未找到可解除拦截的当前仓库订单', + }, + }); + return; + } + + // 分批更新解除拦截状态,每批最多500条 + const UPDATE_CHUNK_SIZE = 500; + for (let i = 0; i < normalizedOrderRows.length; i += UPDATE_CHUNK_SIZE) { + const chunkRows = normalizedOrderRows.slice(i, i + UPDATE_CHUNK_SIZE); + if (chunkRows.length === 0) { + continue; + } + + const chunkOrderIds = chunkRows.map(row => Number(row.id)).filter(id => Number.isInteger(id) && id > 0); + if (chunkOrderIds.length === 0) { + continue; + } + + const now = new Date(); + const updateValues = { + intercept_status: 'none', + updated_at: now, + }; + + await orderModel.update(updateValues, { + where: { + id: { + [Op.in]: chunkOrderIds, + }, + }, + }); + + // 写入操作日志 ORDER_INTERCEPT_CANCEL + const logPayloads = chunkRows.map(row => { + const orderId = Number(row.id || 0); + const orderNo = String(row.delivery_order_code || row.pre_delivery_order_code || '').trim(); + if (!Number.isInteger(orderId) || orderId <= 0) { + return null; + } + + return { + businessType: 'order', + businessId: logWarehouseId, + operationCode: 'ORDER_INTERCEPT_CANCEL', + operator, + extras: { + warehouseId: logWarehouseId, + orderId, + orderNo, + newInterceptStatus: 'none', + }, + beforeChanges: null, + }; + }).filter(Boolean); + + if (logPayloads.length > 0) { + try { + const operationLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog; + if (operationLogService && typeof operationLogService.createOperationLogs === 'function') { + await operationLogService.createOperationLogs(logPayloads); + } + } catch (logErr) { + ctx.logger.warn( + `[order.pendingOrder.batchUnintercept] 批量写操作日志失败,不影响主流程, count=${logPayloads.length}, error=${logErr.message}` + ); + } + } + + for (const orderId of chunkOrderIds) { + uninterceptedOrderIds.push(orderId); + } + + // 更新进度 + const progressPercent = validOrderCount > 0 + ? Math.min(99, Math.round((uninterceptedOrderIds.length / validOrderCount) * 100)) + : 0; + + await this.setBatchUninterceptTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + total_order_count: totalOrderCount, + unintercepted_order_count: uninterceptedOrderIds.length, + progress_percent: progressPercent, + }); + } + + const durationMs = Date.now() - startTime; + await this.setBatchUninterceptTaskProgress(normalizedTaskId, 'success', { + warehouse_id: warehouseId, + total_order_count: totalOrderCount, + unintercepted_order_count: uninterceptedOrderIds.length, + progress_percent: 100, + end_time: Date.now(), + duration_ms: durationMs, + result: { + order_ids: orderIds, + unintercepted_order_ids: uninterceptedOrderIds, + unintercepted_order_count: uninterceptedOrderIds.length, + total_order_count: totalOrderCount, + duration_ms: durationMs, + message: `已解除拦截 ${uninterceptedOrderIds.length} 条订单`, + }, + }); + } catch (error) { + await this.setBatchUninterceptTaskProgress(normalizedTaskId, 'failed', { + warehouse_id: warehouseId, + progress_percent: 0, + end_time: Date.now(), + duration_ms: Date.now() - startTime, + error: error && error.message ? error.message : `${error}`, + error_code: 'BATCH_UNINTERCEPT_FAILED', + }); + } + } + } module.exports = PendingOrderService; diff --git a/app/service/systemMethods/order/print.js b/app/service/systemMethods/order/print.js index efd8877..d86af2c 100644 --- a/app/service/systemMethods/order/print.js +++ b/app/service/systemMethods/order/print.js @@ -11,9 +11,9 @@ class OrderPrintService extends OrderBaseService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'getWavePrintData,getWavePlatformPrintData,unlockWavePlatformPrintDataByGroup'; - const _noNeedLog = 'getWavePrintData,getWavePlatformPrintData,unlockWavePlatformPrintDataByGroup'; - const _noNeedAuth = 'getWavePrintData,getWavePlatformPrintData,unlockWavePlatformPrintDataByGroup'; + const _noNeedRight = 'getWavePrintData,getWavePlatformPrintData,unlockWavePlatformPrintDataByGroup,getOrderPrintData'; + const _noNeedLog = 'getWavePrintData,getWavePlatformPrintData,unlockWavePlatformPrintDataByGroup,getOrderPrintData'; + const _noNeedAuth = 'getWavePrintData,getWavePlatformPrintData,unlockWavePlatformPrintDataByGroup,getOrderPrintData'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -90,6 +90,36 @@ class OrderPrintService extends OrderBaseService { }); } + /** + * 按订单ID拉取平台打印中间态数据。 + * + * method 层仅负责参数解构与边界校验,具体业务查询与打印数据组装由 systems 层实现。 + * 仓库ID统一从当前上下文获取,无需调用方传入。 + * + * @param {Object} data 请求体。 + * @param {Array} data.order_ids 订单ID数组。 + * @return {Promise} 统一 success 包装的平台打印中间态结果。 + */ + async getOrderPrintData(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const { + order_ids: orderIds, + } = requestData; + + if (!Array.isArray(orderIds) || orderIds.length === 0) { + throw new Error('order_ids 必填,且必须为非空数组'); + } + + const result = await this.service.systems.orderPrint.getOrderPrintData({ + orderIds, + }); + + return this.success('ok', { + data: result, + code: 200, + }); + } + /** * 按分组解锁波次平台打印锁。 * diff --git a/app/service/systemMethods/order/recheckOrder.js b/app/service/systemMethods/order/recheckOrder.js index 691d25e..34fbe9e 100644 --- a/app/service/systemMethods/order/recheckOrder.js +++ b/app/service/systemMethods/order/recheckOrder.js @@ -10,62 +10,943 @@ class RecheckOrderService extends OrderBaseService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'scanOrder,scanWaybill,confirmRecheck'; - const _noNeedLog = 'scanOrder,scanWaybill,confirmRecheck'; - const _noNeedAuth = 'scanOrder,scanWaybill,confirmRecheck'; + const _noNeedRight = 'scanOrder,scanTask,scanWaybill,confirmRecheck,recheckOrderList,confirmIntercept'; + const _noNeedLog = 'scanOrder,scanTask,scanWaybill,confirmRecheck,recheckOrderList,confirmIntercept'; + const _noNeedAuth = 'scanOrder,scanTask,scanWaybill,confirmRecheck,recheckOrderList,confirmIntercept'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } /** - * 扫描关键词并返回订单头与商品明细。 + * 扫描关键词并返回以波次为单位的复核视图。 + * 支持运单号、波次号、车号三种匹配模式。 + * - 运单号/波次号匹配(散单):返回匹配订单所在波次的所有订单,list_type='single', + * 顶层携带波次/拣货人/策略/任务ID等汇总信息,list 为扁平订单数组 + * - 车号匹配(团单):返回拣货任务下所有团购波次及订单,list_type='group',保持嵌套结构, + * 顶层携带 task_id * @param {Object} data 请求体。 * @param {string} [data.keyword] 通用扫描关键词。 * @param {string} [data.value] 通用扫描关键词别名。 * @param {string} [data.waybill_no] 运单号。 * @param {string} [data.waybillCode] 运单号别名。 * @param {string} [data.waybill_code] 运单号别名。 + * @param {string} [data.wave_no] 波次号。 + * @param {string} [data.waveNo] 波次号别名。 * @param {string} [data.cart_code] 车号。 * @param {string} [data.cartCode] 车号别名。 - * @return {Promise} 扫描结果。 + * @return {Promise} 扫描结果,包含 match_type、list_type、task_id(散单/团单均有)与 list 数组。 */ async scanOrder(data = {}) { const warehouseId = this.getWarehouseId(); const keyword = this.resolveScanKeyword(data); const matchedResult = await this.pickOrderMatchByKeyword(keyword); - const { orderId, matchType, cartMatchContext } = matchedResult; + const { orderId, matchType, cartMatchContext, waveMatchContext } = matchedResult; + + // 散单处理:运单号匹配 → 查找订单所在波次 → 拉取波次全量订单 + if (matchType === 'waybill') { + const orderModel = await this.getOrderModelByTableType('current', warehouseId); + const order = await orderModel.findOne({ + where: this.buildOrderWhere([ orderId ], warehouseId), + attributes: [ 'id', 'wave_id', 'wave_no', 'pick_status', 'delivery_order_code' ], + raw: true, + }); + + if (!order) { + throw new Error('未找到对应订单'); + } + + const orderWaveId = Number(order.wave_id || 0); + const orderWaveNo = String(order.wave_no || '').trim(); + + if (orderWaveId > 0 && orderWaveNo) { + const scanView = await this.buildSingleWaveScanView(orderWaveId, orderWaveNo, warehouseId); + if (scanView) { + return { + match_type: matchType, + list_type: 'single', + waybill_no: keyword, + ...scanView, + }; + } + return { + match_type: matchType, + list_type: 'single', + waybill_no: keyword, + list: [], + }; + } + + // 无波次信息时退回单订单模式 + this.assertOrderCanRecheck(order); + const detailResult = await this.detail({ id: orderId }); + return { + match_type: matchType, + list_type: 'single', + waybill_no: keyword, + list: [{ + ...(detailResult.detail || {}), + items: Array.isArray(detailResult.items) ? detailResult.items : [], + expresses: Array.isArray(detailResult.expresses) ? detailResult.expresses : [], + logs: Array.isArray(detailResult.logs) ? detailResult.logs : [], + }], + }; + } + + // 散单处理:波次号匹配 → 直接按波次号查找波次及订单 + if (matchType === 'wave') { + const waveId = Number(waveMatchContext?.wave?.wave_id || 0); + const waveNo = String(waveMatchContext?.wave?.wave_no || '').trim(); + + if (waveId > 0 && waveNo) { + const scanView = await this.buildSingleWaveScanView(waveId, waveNo, warehouseId); + if (scanView) { + return { + match_type: matchType, + list_type: 'single', + ...scanView, + }; + } + return { + match_type: matchType, + list_type: 'single', + list: [], + }; + } + + throw new Error('波次信息不完整,无法加载复核视图'); + } + + // 团单处理:车号匹配 → 查找拣货任务 → 拉取任务下所有团购波次 + if (matchType === 'cart' && cartMatchContext) { + const taskId = Number(cartMatchContext?.task?.task_id || 0); + + if (taskId > 0) { + const groupWaveList = await this.buildGroupWaveList(taskId, warehouseId); + return { + match_type: 'cart', + list_type: 'group', + task_id: taskId, + list: groupWaveList, + }; + } + + throw new Error('拣货任务信息不完整,无法加载团购复核视图'); + } + + throw new Error('未找到对应订单'); + } + + /** + * 通过拣货任务ID刷新复核扫描视图。 + * 根据任务的 pick_mode 区分散单/团单模式,返回与 scanOrder 一致的数据结构,用于前端刷新数据。 + * - 散单模式(pick_mode 2/3/4):扁平化任务下所有波次的订单列表,顶层携带拣货人/任务等汇总信息 + * - 团购模式(pick_mode 1/5):返回任务下所有团购波次及订单的分组列表 + * @param {Object} data 请求体。 + * @param {number} data.task_id 拣货任务ID。 + * @return {Promise} 扫描视图,包含 match_type、list_type、task_id、list 等字段, + * 散单模式额外包含 picker_id、picker_name、pick_mode、total_orders、reviewed_count、unreviewed_count。 + */ + async scanTask(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const taskId = Number(requestData.task_id || 0); + + if (!Number.isFinite(taskId) || taskId <= 0) { + throw new Error('task_id 无效'); + } + + const warehouseId = this.getWarehouseId(); + const { ctx } = this; + + // 查询拣货任务信息 + const taskRows = await ctx.model.query( + ` + SELECT id AS task_id, pick_mode, pick_user_id, pick_user_name + FROM wms_wave_pick_task + WHERE id = :taskId + AND warehouse_id = :warehouseId + LIMIT 1 + `, + { + replacements: { taskId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + const taskRow = Array.isArray(taskRows) && taskRows.length > 0 ? taskRows[0] : null; + + if (!taskRow) { + throw new Error('未找到对应拣货任务'); + } + + const pickMode = Number(taskRow.pick_mode || 0); + + // 查询任务关联的所有波次 + const taskWaveRows = await ctx.model.query( + ` + SELECT wave_id, wave_no + FROM wms_wave_pick_task_wave + WHERE task_id = :taskId + AND warehouse_id = :warehouseId + ORDER BY wave_id ASC + `, + { + replacements: { taskId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + const taskWaves = Array.isArray(taskWaveRows) ? taskWaveRows : []; + + // 团购模式(pick_mode 1 或 5):复用 buildGroupWaveList + if (pickMode === 1 || pickMode === 5) { + const groupWaveList = await this.buildGroupWaveList(taskId, warehouseId); + + return { + match_type: 'task', + list_type: 'group', + task_id: taskId, + list: groupWaveList, + }; + } + + // 散单模式(pick_mode 2、3、4):逐波次构建扫描视图并合并 + const scanViews = []; + + for (const tw of taskWaves) { + const waveId = Number(tw.wave_id || 0); + const waveNo = String(tw.wave_no || '').trim(); + + if (waveId > 0 && waveNo) { + const scanView = await this.buildSingleWaveScanView(waveId, waveNo, warehouseId); + + if (scanView) { + scanViews.push(scanView); + } + } + } + + if (scanViews.length === 0) { + return { + match_type: 'task', + list_type: 'single', + task_id: taskId, + pick_mode: pickMode, + list: [], + }; + } + + // 合并所有波次的订单列表(按 order_id 去重) + const allOrders = scanViews.flatMap(v => (Array.isArray(v.list) ? v.list : [])); + const seenOrderIds = new Set(); + const mergedList = []; + + for (const order of allOrders) { + const oid = Number(order.order_id || 0); + + if (oid > 0 && !seenOrderIds.has(oid)) { + seenOrderIds.add(oid); + mergedList.push(order); + } + } + + // 排序:未复核的排前面,其次按 wave_index 从小到大 + mergedList.sort((a, b) => { + const aReviewed = a.is_reviewed ? 1 : 0; + const bReviewed = b.is_reviewed ? 1 : 0; + + if (aReviewed !== bReviewed) { + return aReviewed - bReviewed; + } + + return (Number(a.wave_index || 0)) - (Number(b.wave_index || 0)); + }); + + const totalOrders = mergedList.length; + const reviewedCount = mergedList.filter(o => o.recheck_status === 'fin').length; + const unreviewedCount = totalOrders - reviewedCount; + const waveType = scanViews.find(v => Number(v.wave_type || 0) > 0)?.wave_type || 0; + + return { + match_type: 'task', + list_type: 'single', + picker_id: taskRow.pick_user_id != null ? Number(taskRow.pick_user_id) : null, + picker_name: String(taskRow.pick_user_name || '').trim(), + task_id: taskId, + wave_id: 0, + wave_no: '', + wave_type: Number(waveType || 0), + pick_mode: pickMode, + strategy_id: null, + strategy_name: '', + total_orders: totalOrders, + reviewed_count: reviewedCount, + unreviewed_count: unreviewedCount, + list: mergedList, + }; + } + + /** + * 构建散单模式的扁平化扫描复核视图。 + * 将波次信息、拣货人、策略、任务ID等提升到顶层,订单列表扁平化。 + * @param {number} waveId 波次ID。 + * @param {string} waveNo 波次号。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 扁平化扫描视图,包含 picker_id、picker_name、task_id、wave_id、wave_no、 + * wave_type、pick_mode、strategy_id、strategy_name、total_orders、reviewed_count、unreviewed_count、list。 + */ + async buildSingleWaveScanView(waveId, waveNo, warehouseId) { + const baseWaveView = await this.buildSingleWaveView(waveId, waveNo, warehouseId); + + if (!baseWaveView) { + return null; + } + + const normalizedWaveId = Number(waveId || 0); + const orders = Array.isArray(baseWaveView.orders) ? baseWaveView.orders : []; + + // 校验波次内所有订单是否都已拣货,未拣货订单不允许复核 + for (const order of orders) { + this.assertOrderCanRecheck(order); + } + + // 并行查询拣货人信息和策略信息 + const [ pickerInfo, strategyInfo ] = await Promise.all([ + this.getPickerInfoByWaveId(normalizedWaveId, warehouseId), + this.getWaveStrategyInfo(normalizedWaveId, warehouseId), + ]); + + // 计算复核汇总 + const reviewedCount = orders.filter(o => o.recheck_status === 'fin').length; + const unreviewedCount = orders.length - reviewedCount; + + return { + picker_id: pickerInfo.picker_id, + picker_name: pickerInfo.picker_name, + task_id: pickerInfo.task_id, + wave_id: baseWaveView.wave_id, + wave_no: baseWaveView.wave_no, + wave_type: baseWaveView.wave_type, + pick_mode: baseWaveView.pick_mode, + strategy_id: strategyInfo.strategy_id, + strategy_name: strategyInfo.strategy_name, + total_orders: orders.length, + reviewed_count: reviewedCount, + unreviewed_count: unreviewedCount, + list: orders, + }; + } + + /** + * 构建单个波次的复核视图(散单/团单内部共用)。 + * 查询波次信息、拣货模式、以及波次下全部订单列表。 + * @param {number} waveId 波次ID。 + * @param {string} waveNo 波次号。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 波次视图对象,包含 wave_id、wave_no、wave_type、pick_mode、order_count、orders。 + */ + async buildSingleWaveView(waveId, waveNo, warehouseId) { + const { ctx } = this; + const normalizedWaveId = Number(waveId || 0); + const normalizedWaveNo = String(waveNo || '').trim(); + + if (normalizedWaveId <= 0 || !normalizedWaveNo) { + return null; + } + + // 查询波次批次信息 + const waveRows = await ctx.model.query( + ` + SELECT + wave_id, + wave_no, + wave_type, + wave_status, + total_orders, + processed_orders, + creator, + create_time, + update_time + FROM wms_wave_batch + WHERE wave_id = :waveId + AND wave_no = :waveNo + AND warehouse_id = :warehouseId + LIMIT 1 + `, + { + replacements: { waveId: normalizedWaveId, waveNo: normalizedWaveNo, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + const waveRow = Array.isArray(waveRows) && waveRows.length > 0 ? waveRows[0] : null; + + if (!waveRow) { + return null; + } + + // 查询波次关联的拣货任务,获取 pick_mode + const pickMode = await this.getPickModeByWaveId(normalizedWaveId, warehouseId); + + // 查询波次下所有订单 + const orders = await this.getWaveOrdersBasic(normalizedWaveNo, warehouseId); + const orderCount = orders.length; + + return { + wave_id: Number(waveRow.wave_id || 0), + wave_no: String(waveRow.wave_no || '').trim(), + wave_type: Number(waveRow.wave_type || 0), + wave_status: Number(waveRow.wave_status || 0), + pick_mode: pickMode, + total_orders: Number(waveRow.total_orders || 0), + processed_orders: Number(waveRow.processed_orders || 0), + creator: String(waveRow.creator || '').trim(), + create_time: waveRow.create_time || null, + update_time: waveRow.update_time || null, + order_count: orderCount, + orders, + }; + } + + /** + * 构建团购波次列表视图(团单模式)。 + * 根据拣货任务ID查找关联的所有波次,每个波次展开为一项。 + * @param {number} taskId 拣货任务ID。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise>} 波次视图列表。 + */ + async buildGroupWaveList(taskId, warehouseId) { + const { ctx } = this; + const normalizedTaskId = Number(taskId || 0); + + if (normalizedTaskId <= 0) { + return []; + } + + // 查询拣货任务信息,获取 pick_mode + const taskRows = await ctx.model.query( + ` + SELECT id AS task_id, pick_mode, current_cart_code_snapshot + FROM wms_wave_pick_task + WHERE id = :taskId + AND warehouse_id = :warehouseId + LIMIT 1 + `, + { + replacements: { taskId: normalizedTaskId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + const taskRow = Array.isArray(taskRows) && taskRows.length > 0 ? taskRows[0] : null; + + if (!taskRow) { + return []; + } + + const pickMode = Number(taskRow.pick_mode || 0); + + // 查询任务关联的所有波次 + const taskWaveRows = await ctx.model.query( + ` + SELECT wave_id, wave_no, box_no + FROM wms_wave_pick_task_wave + WHERE task_id = :taskId + AND warehouse_id = :warehouseId + ORDER BY box_no ASC, wave_id ASC + `, + { + replacements: { taskId: normalizedTaskId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + const taskWaves = Array.isArray(taskWaveRows) ? taskWaveRows : []; + + // 并行查询每个波次的详细信息和订单 + const waveViewPromises = taskWaves.map(async tw => { + const twWaveId = Number(tw.wave_id || 0); + const twWaveNo = String(tw.wave_no || '').trim(); + + if (twWaveId <= 0 || !twWaveNo) { + return null; + } + + const waveView = await this.buildSingleWaveView(twWaveId, twWaveNo, warehouseId); + + if (!waveView) { + return null; + } + + // 校验波次内所有订单是否都已拣货,未拣货订单不允许复核 + const orders = Array.isArray(waveView.orders) ? waveView.orders : []; + for (const order of orders) { + this.assertOrderCanRecheck(order); + } + + // 使用任务级别的 pick_mode 覆盖(团单模式下以任务为准) + return { + ...waveView, + pick_mode: pickMode, + box_no: Number(tw.box_no || 0), + }; + }); + + const waveViews = await Promise.all(waveViewPromises); + + return waveViews.filter(view => view !== null); + } + + /** + * 通过波次ID查询关联的拣货模式。 + * 优先查询 wms_wave_pick_task.wave_id,其次查 wms_wave_pick_task_wave 关联。 + * @param {number} waveId 波次ID。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 拣货模式编码,未找到返回 0。 + */ + async getPickModeByWaveId(waveId, warehouseId) { + const { ctx } = this; + const normalizedWaveId = Number(waveId || 0); + + if (normalizedWaveId <= 0) { + return 0; + } + + // 先按 wave_id 直接查拣货任务 + const taskRows = await ctx.model.query( + ` + SELECT pick_mode + FROM wms_wave_pick_task + WHERE wave_id = :waveId + AND warehouse_id = :warehouseId + ORDER BY create_time DESC + LIMIT 1 + `, + { + replacements: { waveId: normalizedWaveId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + if (Array.isArray(taskRows) && taskRows.length > 0) { + return Number(taskRows[0].pick_mode || 0); + } + + // 通过 wms_wave_pick_task_wave 关联查询 + const twRows = await ctx.model.query( + ` + SELECT t.pick_mode + FROM wms_wave_pick_task_wave tw + INNER JOIN wms_wave_pick_task t ON t.id = tw.task_id + WHERE tw.wave_id = :waveId + AND tw.warehouse_id = :warehouseId + ORDER BY t.create_time DESC + LIMIT 1 + `, + { + replacements: { waveId: normalizedWaveId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + if (Array.isArray(twRows) && twRows.length > 0) { + return Number(twRows[0].pick_mode || 0); + } + + return 0; + } + + /** + * 查询波次下所有订单的基本信息列表。 + * 包含运单号、打印状态、复核状态、波次内序号(优先从 wms_order_wave_index 读取真实 wave_index, + * 若表无记录则降级使用 Array.map 临时序号),按未复核优先 + 波次内序号升序排序。 + * @param {string} waveNo 波次号。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise>} 订单基本信息列表,每项含 order_id、delivery_order_code、 + * waybill_no、pick_status、is_printed、is_reviewed、shop_nick、items_count、 + * wave_index、recheck_status、wave_id、wave_no、order_type、status、 + * logistics_name、store_remark、intercept_status、stock 等字段。 + */ + async getWaveOrdersBasic(waveNo, warehouseId) { + const normalizedWaveNo = String(waveNo || '').trim(); + + if (!normalizedWaveNo) { + return []; + } + const orderModel = await this.getOrderModelByTableType('current', warehouseId); - const orderWhere = this.buildOrderWhere([ orderId ], warehouseId); - const order = await orderModel.findOne({ - where: orderWhere, + const orderRows = await orderModel.findAll({ + where: { + wave_no: normalizedWaveNo, + warehouse_id: warehouseId, + }, + attributes: [ + 'id', + 'delivery_order_code', + 'pre_delivery_order_code', + 'pick_status', + 'wave_id', + 'wave_no', + 'order_type', + 'status', + 'recheck_status', + 'items_count', + 'shop_nick', + 'logistics_name', + 'print_status', + 'store_id', + 'intercept_status', + ], + order: [[ 'id', 'ASC' ]], raw: true, }); - if (!order) { - throw new Error('未找到对应订单'); + const { ctx } = this; + const orderRowsArray = Array.isArray(orderRows) ? orderRows : []; + const orderIds = orderRowsArray.map(row => Number(row.id || 0)); + + // 批量查询货主备注(wms_store_warehouse.store_remask) + const storeRemarkMap = new Map(); + if (orderIds.length > 0 && ctx.model && ctx.model.StoreWarehouse) { + const storeIds = [ + ...new Set( + orderRowsArray + .map(row => Number(row.store_id || 0)) + .filter(id => id > 0) + ), + ]; + if (storeIds.length > 0) { + const swRows = await ctx.model.StoreWarehouse.findAll({ + where: { + store_id: { [this.app.Sequelize.Op.in]: storeIds }, + warehouse_id: warehouseId, + }, + attributes: [ 'store_id', 'store_remask' ], + raw: true, + }); + for (const sw of (Array.isArray(swRows) ? swRows : [])) { + const sid = Number(sw.store_id || 0); + if (sid > 0 && !storeRemarkMap.has(sid)) { + storeRemarkMap.set(sid, String(sw.store_remask || '').trim()); + } + } + } } - this.assertOrderCanRecheck(order); + // 批量查询运单信息 + const waybillMap = new Map(); + if (orderIds.length > 0 && ctx.model && ctx.model.OrderExpress) { + const expressRows = await ctx.model.OrderExpress.findAll({ + where: { order_id: orderIds }, + attributes: [ 'order_id', 'waybill_code' ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + for (const er of (Array.isArray(expressRows) ? expressRows : [])) { + const oid = Number(er.order_id || 0); + if (oid > 0 && !waybillMap.has(oid)) { + waybillMap.set(oid, String(er.waybill_code || '').trim()); + } + } + } - const detailResult = await this.detail({ - id: orderId, + // 批量查询波次顺序索引(wms_order_wave_index) + const waveIndexMap = new Map(); + if (orderIds.length > 0 && ctx.model && typeof ctx.model.query === 'function') { + const waveIds = [ + ...new Set( + orderRowsArray + .map(row => Number(row.wave_id || 0)) + .filter(id => id > 0) + ), + ]; + if (waveIds.length > 0) { + try { + const waveIndexRows = await ctx.model.query( + ` + SELECT order_id, wave_index + FROM wms_order_wave_index + WHERE warehouse_id = :warehouseId + AND wave_id IN (:waveIds) + AND order_id IN (:orderIds) + `, + { + replacements: { warehouseId, waveIds, orderIds }, + type: ctx.model.QueryTypes && ctx.model.QueryTypes.SELECT, + } + ); + for (const wr of (Array.isArray(waveIndexRows) ? waveIndexRows : [])) { + const wrOrderId = Number(wr && wr.order_id || 0); + if (wrOrderId > 0) { + waveIndexMap.set(wrOrderId, Number(wr.wave_index || 0)); + } + } + } catch (e) { + ctx.logger.warn(`[recheckOrder.getWaveOrdersBasic] 查询波次索引失败, waveNo=${normalizedWaveNo}, error=${e.message}`); + } + } + } + + // 构建订单列表 + const orderList = orderRowsArray.map((row, index) => { + const orderId = Number(row.id || 0); + const recheckStatus = String(row.recheck_status || '').trim(); + const printStatus = String(row.print_status || '').trim(); + + // 运单号:从 wms_order_express 关联表查询 + const waybillNo = waybillMap.has(orderId) ? (waybillMap.get(orderId) || '') : ''; + + return { + order_id: orderId, + delivery_order_code: String(row.delivery_order_code || row.pre_delivery_order_code || '').trim(), + waybill_no: waybillNo, + pick_status: String(row.pick_status || '').trim(), + is_printed: printStatus === 'fin', + is_reviewed: recheckStatus === 'fin', + shop_nick: String(row.shop_nick || '').trim(), + items_count: Number(row.items_count || 0), + wave_index: waveIndexMap.has(orderId) ? waveIndexMap.get(orderId) : index, + recheck_status: recheckStatus, + wave_id: Number(row.wave_id || 0), + wave_no: String(row.wave_no || '').trim(), + order_type: String(row.order_type || '').trim(), + status: Number(row.status || 0), + logistics_name: String(row.logistics_name || '').trim(), + store_remark: storeRemarkMap.has(Number(row.store_id || 0)) + ? storeRemarkMap.get(Number(row.store_id || 0)) + : '', + intercept_status: String(row.intercept_status || '').trim(), + }; }); - const expresses = Array.isArray(detailResult.expresses) ? detailResult.expresses : []; - const resolvedWaybillNo = matchType === 'waybill' - ? keyword - : String(expresses?.[0]?.waybill_code || '').trim(); - const cartMatchView = matchType === 'cart' - ? await this.buildCartMatchView(cartMatchContext) - : null; + + // 排序:未复核的排前面,其次按波次内序号从小到大 + orderList.sort((a, b) => { + const aReviewed = a.is_reviewed ? 1 : 0; + const bReviewed = b.is_reviewed ? 1 : 0; + if (aReviewed !== bReviewed) { + return aReviewed - bReviewed; + } + return a.wave_index - b.wave_index; + }); + + // 补充库存信息 + const enrichedList = await this.enrichOrdersWithStock(orderList, warehouseId); + return enrichedList; + } + + /** + * 为订单列表批量补充库存信息。 + * 查询每个订单的明细商品、库存数量、条码列表和图片,构建 stock 数组。 + * @param {Object[]} orderList 订单基本信息列表。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 补充了 stock 字段的订单列表。 + */ + async enrichOrdersWithStock(orderList, warehouseId) { + if (!Array.isArray(orderList) || orderList.length === 0) { + return orderList; + } + + const orderIds = orderList.map(o => Number(o.order_id || 0)).filter(Boolean); + if (orderIds.length === 0) { + return orderList; + } + + // 1. 批量查询所有订单的商品明细 + const orderItemsModel = await this.getOrderItemsModelByTableType('current', warehouseId); + const allOrderItems = await orderItemsModel.findAll({ + where: { + order_id: { [this.app.Sequelize.Op.in]: orderIds }, + }, + attributes: [ 'order_id', 'stock_id', 'item_code', 'item_name', 'plan_qty', 'item_snapshot' ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + const itemsArray = Array.isArray(allOrderItems) ? allOrderItems : []; + + // 2. 收集所有唯一的 stock_id + const stockIds = [ ...new Set( + itemsArray + .map(item => Number(item.stock_id)) + .filter(Boolean) + ) ]; + + // 3. 批量查询库存信息 + const stockMap = new Map(); + if (stockIds.length > 0 && this.ctx.model && this.ctx.model.StockWarehouse) { + const stockRows = await this.ctx.model.StockWarehouse.findAll({ + where: { + id: { [this.app.Sequelize.Op.in]: stockIds }, + warehouse_id: warehouseId, + }, + attributes: [ 'id', 'item_code', 'item_name', 'sku_property', 'packing_requirements' ], + raw: true, + }); + for (const row of (Array.isArray(stockRows) ? stockRows : [])) { + stockMap.set(Number(row.id), row); + } + } + + // 4. 批量查询条码 + const barcodeMap = new Map(); + if (stockIds.length > 0 && this.ctx.model && this.ctx.model.StockBarcode) { + const barcodeRows = await this.ctx.model.StockBarcode.findAll({ + where: { + stock_id: { [this.app.Sequelize.Op.in]: stockIds }, + warehouse_id: warehouseId, + }, + attributes: [ 'stock_id', 'barcode' ], + raw: true, + }); + for (const row of (Array.isArray(barcodeRows) ? barcodeRows : [])) { + const sid = Number(row.stock_id); + const barcodeVal = String(row.barcode || '').trim(); + if (!barcodeMap.has(sid)) { + barcodeMap.set(sid, []); + } + if (barcodeVal) { + barcodeMap.get(sid).push(barcodeVal); + } + } + } + + // 5. 检测共享条码:查询当前所有条码是否也出现在其他 stock_id 中 + const sharedBarcodeSet = new Set(); + if (barcodeMap.size > 0) { + const allBarcodes = []; + for (const [ , barcodes ] of barcodeMap) { + for (const bc of barcodes) { + allBarcodes.push(bc); + } + } + if (allBarcodes.length > 0 && this.ctx.model && this.ctx.model.StockBarcode) { + const sharedRows = await this.ctx.model.query( + `SELECT barcode, COUNT(DISTINCT stock_id) AS cnt + FROM wms_stock_barcodes + WHERE barcode IN (:barcodes) + AND warehouse_id = :warehouseId + GROUP BY barcode + HAVING cnt > 1`, + { + replacements: { barcodes: allBarcodes, warehouseId }, + type: this.ctx.model.QueryTypes.SELECT, + } + ); + for (const row of (Array.isArray(sharedRows) ? sharedRows : [])) { + sharedBarcodeSet.add(String(row.barcode || '').trim()); + } + } + } + + // 6. 批量查询图片 + const imagesByStockId = await this.getOrderItemImagesByStockIds(itemsArray); + + // 7. 按 order_id 分组商品明细 + const itemsByOrderId = new Map(); + for (const item of itemsArray) { + const oid = Number(item.order_id); + if (!itemsByOrderId.has(oid)) { + itemsByOrderId.set(oid, []); + } + itemsByOrderId.get(oid).push(item); + } + + // 8. 为每个订单构建 stock 数组 + return orderList.map(order => { + const oid = Number(order.order_id || 0); + const items = itemsByOrderId.get(oid) || []; + const stock = items.map(item => { + const sid = Number(item.stock_id || 0); + const stockInfo = stockMap.get(sid) || {}; + const barcodes = (() => { + const arr = barcodeMap.get(sid); + if (Array.isArray(arr) && arr.length > 0) { + return arr; + } + return [ String(item.item_code || '').trim() ]; + })(); + const images = imagesByStockId.get(sid) || []; + + const hasSharedBarcode = (() => { + const arr = barcodeMap.get(sid); + if (Array.isArray(arr) && arr.length > 0) { + return arr.some(bc => sharedBarcodeSet.has(bc)); + } + return false; + })(); + + return { + stock_id: sid, + item_code: String(item.item_code || stockInfo.item_code || '').trim(), + item_name: String(stockInfo.item_name || item.item_name || '').trim(), + sku_property: String(stockInfo.sku_property || '').trim(), + packing_requirements: String(stockInfo.packing_requirements || '').trim(), + barcodes, + images, + has_shared_barcode: hasSharedBarcode, + plan_qty: Number(item.plan_qty || 0), + }; + }); + + return { + ...order, + stock, + }; + }); + } + + /** + * 通过波次ID查询关联的拣货人信息及任务ID。 + * 通过 wms_wave_pick_task_wave 关联 wms_wave_pick_task 获取 pick_user_id / pick_user_name / task_id。 + * @param {number} waveId 波次ID。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise<{ picker_id: number|null, picker_name: string, task_id: number|null }>} 拣货人信息及任务ID。 + */ + async getPickerInfoByWaveId(waveId, warehouseId) { + const { ctx } = this; + const normalizedWaveId = Number(waveId || 0); + + if (normalizedWaveId <= 0) { + return { picker_id: null, picker_name: '', task_id: null }; + } + + const rows = await ctx.model.query( + ` + SELECT t.pick_user_id, t.pick_user_name, t.id AS task_id + FROM wms_wave_pick_task_wave tw + INNER JOIN wms_wave_pick_task t ON t.id = tw.task_id + WHERE tw.wave_id = :waveId + AND tw.warehouse_id = :warehouseId + AND t.pick_user_id IS NOT NULL + ORDER BY t.create_time DESC + LIMIT 1 + `, + { + replacements: { waveId: normalizedWaveId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + const row = Array.isArray(rows) && rows.length > 0 ? rows[0] : null; return { - match_type: matchType, - cart_match_view: cartMatchView, - order_id: orderId, - waybill_no: resolvedWaybillNo, - order: detailResult.detail || {}, - items: Array.isArray(detailResult.items) ? detailResult.items : [], - expresses, - logs: Array.isArray(detailResult.logs) ? detailResult.logs : [], + picker_id: row && row.pick_user_id != null ? Number(row.pick_user_id) : null, + picker_name: String(row && row.pick_user_name || '').trim(), + task_id: row && row.task_id != null ? Number(row.task_id) : null, + }; + } + + /** + * 查询波次关联的策略信息。 + * 当前 wms_wave_batch 与 wms_wave_pick_task 均未直接存储 strategy_id, + * 因此默认返回 null,后续若补充关联字段可在此扩展查询逻辑。 + * @param {number} waveId 波次ID。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise<{ strategy_id: number|null, strategy_name: string }>} 策略信息。 + */ + // eslint-disable-next-line no-unused-vars + async getWaveStrategyInfo(waveId, warehouseId) { + return { + strategy_id: null, + strategy_name: '', }; } @@ -375,6 +1256,8 @@ class RecheckOrderService extends OrderBaseService { /** * 从多种兼容字段中解析扫描关键词。 * @param {Object} data 请求体。 + * @param {string} [data.wave_no] 波次号。 + * @param {string} [data.waveNo] 波次号别名。 * @return {string} 规范化后的扫描关键词。 */ resolveScanKeyword(data = {}) { @@ -385,11 +1268,13 @@ class RecheckOrderService extends OrderBaseService { waybill_no: waybillNo, waybillCode, waybill_code: waybillCodeAlias, + wave_no: waveNo, + waveNo: waveNoAlias, cart_code: cartCode, cartCode: cartCodeAlias, } = requestData; const normalizedKeyword = String( - keyword || value || waybillNo || waybillCode || waybillCodeAlias || cartCode || cartCodeAlias || '' + keyword || value || waybillNo || waybillCode || waybillCodeAlias || waveNo || waveNoAlias || cartCode || cartCodeAlias || '' ).trim(); if (!normalizedKeyword) { @@ -401,9 +1286,9 @@ class RecheckOrderService extends OrderBaseService { /** * 根据扫描关键词解析订单ID。 - * 优先按运单号匹配,未命中时回退到车号匹配。 + * 匹配优先级:运单号 → 波次号 → 车号。 * @param {string} keyword 扫描关键词。 - * @return {Promise<{ orderId: number, matchType: string, cartMatchContext?: Object }>} 命中结果。 + * @return {Promise<{ orderId: number, matchType: string, cartMatchContext?: Object, waveMatchContext?: Object }>} 命中结果。 */ async pickOrderMatchByKeyword(keyword) { const waybillOrderId = await this.pickOrderIdByWaybill(keyword); @@ -415,6 +1300,17 @@ class RecheckOrderService extends OrderBaseService { }; } + const waveMatchContext = await this.pickWaveMatchContextByWaveNo(keyword); + const waveOrderId = Number(waveMatchContext?.order_id || 0); + + if (Number.isFinite(waveOrderId) && waveOrderId > 0) { + return { + orderId: waveOrderId, + matchType: 'wave', + waveMatchContext, + }; + } + const cartMatchContext = await this.pickCartMatchContextByCartCode(keyword); const cartOrderId = Number(cartMatchContext?.order_id || 0); @@ -467,6 +1363,119 @@ class RecheckOrderService extends OrderBaseService { return Number.isFinite(orderId) && orderId > 0 ? orderId : 0; } + /** + * 根据波次号查询波次信息及波次下订单列表。 + * @param {string} waveNo 波次号。 + * @return {Promise<{order_id:number, wave:Object|null, orders:Array, matched_order_ids:Array}>} 命中上下文。 + */ + async pickWaveMatchContextByWaveNo(waveNo) { + const { ctx } = this; + const warehouseId = this.getWarehouseId(); + const normalizedWaveNo = String(waveNo || '').trim(); + + if (!normalizedWaveNo) { + return { + order_id: 0, + wave: null, + orders: [], + matched_order_ids: [], + }; + } + + // 查询波次批次信息 + const waveRows = await ctx.model.query( + ` + SELECT + wave_id, + wave_no, + wave_type, + wave_status, + total_orders, + processed_orders, + creator, + create_time, + update_time + FROM wms_wave_batch + WHERE wave_no = :waveNo + AND warehouse_id = :warehouseId + ORDER BY create_time DESC, wave_id DESC + LIMIT 1 + `, + { + replacements: { waveNo: normalizedWaveNo, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + const waveRow = Array.isArray(waveRows) && waveRows.length > 0 ? waveRows[0] : null; + + if (!waveRow) { + return { + order_id: 0, + wave: null, + orders: [], + matched_order_ids: [], + }; + } + + const wave = { + wave_id: Number(waveRow.wave_id || 0), + wave_no: String(waveRow.wave_no || '').trim(), + wave_type: Number(waveRow.wave_type || 0), + wave_status: Number(waveRow.wave_status || 0), + total_orders: Number(waveRow.total_orders || 0), + processed_orders: Number(waveRow.processed_orders || 0), + creator: String(waveRow.creator || '').trim(), + create_time: waveRow.create_time || null, + update_time: waveRow.update_time || null, + }; + + // 查询波次下的订单列表 + const orderModel = await this.getOrderModelByTableType('current', warehouseId); + const orderRows = await orderModel.findAll({ + where: { + wave_no: normalizedWaveNo, + warehouse_id: warehouseId, + }, + attributes: [ + 'id', + 'delivery_order_code', + 'pre_delivery_order_code', + 'pick_status', + 'wave_id', + 'wave_no', + 'order_type', + 'status', + 'recheck_status', + ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + const orders = (Array.isArray(orderRows) ? orderRows : []).map(row => ({ + order_id: Number(row.id || 0), + delivery_order_code: String(row.delivery_order_code || row.pre_delivery_order_code || '').trim(), + pick_status: String(row.pick_status || '').trim(), + wave_id: Number(row.wave_id || 0), + wave_no: String(row.wave_no || '').trim(), + order_type: String(row.order_type || '').trim(), + status: Number(row.status || 0), + recheck_status: String(row.recheck_status || '').trim(), + })); + + const matchedOrderIds = [ ...new Set(orders + .map(o => Number(o.order_id)) + .filter(id => Number.isInteger(id) && id > 0)) ]; + const primaryOrderId = Number(matchedOrderIds[0] || 0); + + return { + order_id: Number.isFinite(primaryOrderId) && primaryOrderId > 0 ? primaryOrderId : 0, + wave, + orders, + matched_order_ids: matchedOrderIds, + }; + } + /** * 根据车号读取任务上下文及任务订单行。 * @param {string} cartCode 车号。 @@ -633,6 +1642,31 @@ class RecheckOrderService extends OrderBaseService { return pickModeMap[normalizedPickMode] || '未知模式'; } + /** + * 构建波次号命中语义化视图。 + * @param {Object} waveMatchContext 波次号命中上下文。 + * @return {Promise} 语义化视图。 + */ + async buildWaveMatchView(waveMatchContext = {}) { + const context = this.isPlainObject(waveMatchContext) ? waveMatchContext : {}; + const wave = this.isPlainObject(context.wave) ? context.wave : {}; + const orders = Array.isArray(context.orders) ? context.orders : []; + + return { + wave_id: Number(wave.wave_id || 0), + wave_no: String(wave.wave_no || '').trim(), + wave_type: Number(wave.wave_type || 0), + wave_status: Number(wave.wave_status || 0), + total_orders: Number(wave.total_orders || 0), + processed_orders: Number(wave.processed_orders || 0), + creator: String(wave.creator || '').trim(), + create_time: wave.create_time || null, + update_time: wave.update_time || null, + order_count: orders.length, + orders, + }; + } + /** * 构建车号命中语义化视图。 * @param {Object} cartMatchContext 车号命中上下文。 @@ -698,6 +1732,32 @@ class RecheckOrderService extends OrderBaseService { }; } + /** + * 将车号匹配视图中的订单平铺为一维数组。 + * 根据 view_type 从 groups / pick_groups / box_groups / orders 中提取所有订单。 + * @param {Object} cartMatchView 车号匹配视图。 + * @return {Array} 平铺后的订单列表。 + */ + flattenCartMatchOrders(cartMatchView = {}) { + const view = this.isPlainObject(cartMatchView) ? cartMatchView : {}; + const { view_type: viewType } = view; + + if (viewType === 'groups') { + const groups = Array.isArray(view.groups) ? view.groups : []; + return groups.flatMap(g => (Array.isArray(g.orders) ? g.orders : [])); + } + if (viewType === 'pick_groups') { + const pickGroups = Array.isArray(view.pick_groups) ? view.pick_groups : []; + return pickGroups.flatMap(g => (Array.isArray(g.orders) ? g.orders : [])); + } + if (viewType === 'box_groups') { + const boxGroups = Array.isArray(view.box_groups) ? view.box_groups : []; + return boxGroups.flatMap(g => (Array.isArray(g.orders) ? g.orders : [])); + } + // view_type === 'orders' 或兜底 + return Array.isArray(view.orders) ? view.orders : []; + } + /** * 追加任务订单行的订单维度字段。 * @param {Array} taskOrders 任务订单行。 @@ -827,14 +1887,426 @@ class RecheckOrderService extends OrderBaseService { } /** - * 校验订单是否允许复核,仅未拣货订单可执行复核。 + * 校验订单是否允许复核,未拣货订单不允许复核。 * @param {Object} order 订单信息。 */ assertOrderCanRecheck(order = {}) { - if (String(order.pick_status || '') !== 'none') { + if (String(order.pick_status || '') === 'none') { throw new Error('订单未拣货,不允许复核。'); } } + + /** + * 复核订单列表查询,通过入参 list_type 区分散单模式与团购模式。 + * - 散单模式(single):返回待复核订单列表,每项为一个订单。 + * - 团购模式(group):返回波次维度的复核列表,每项为一个波次及其订单汇总。 + * 统一使用 list 字段名输出。 + * @param {Object} data 请求参数。 + * @param {string} [data.list_type='single'] 列表模式:single(散单模式)/ group(团购模式)。 + * @param {Object} [data.where] 筛选条件。 + * @param {Object} [data.pagination] 分页参数,兼容 page/pageSize。 + * @return {Promise} 列表结果,包含 list 与 pagination。 + */ + async recheckOrderList(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const { list_type: listType = 'single' } = requestData; + const normalizedListType = String(listType || 'single').trim(); + + if (normalizedListType === 'group') { + return await this.queryRecheckOrderGroupList(requestData); + } + return await this.queryRecheckOrderSingleList(requestData); + } + + /** + * 散单模式复核列表:按订单维度返回待复核订单,支持分页与关键词/波次号/复核状态筛选。 + * @param {Object} data 请求参数。 + * @param {Object} [data.where] 筛选条件,支持 keyword / wave_no / recheck_status / pick_status 等。 + * @param {Object} [data.pagination] 分页参数。 + * @return {Promise} { list: Array, pagination: Object }。 + */ + async queryRecheckOrderSingleList(data = {}) { + const { ctx } = this; + const warehouseId = this.getWarehouseId(); + const requestData = this.isPlainObject(data) ? data : {}; + const { page, pageSize } = this.normalizePagination(requestData.pagination || requestData); + const where = this.isPlainObject(requestData.where) ? requestData.where : {}; + const offset = (page - 1) * pageSize; + const orderModel = await this.getOrderModelByTableType('current', warehouseId); + const orderTableName = this.resolveModelTableName(orderModel); + + const conditions = []; + const replacements = { warehouseId, limit: pageSize, offset }; + + conditions.push('o.warehouse_id = :warehouseId'); + conditions.push('o.pick_status != \'none\''); + conditions.push('o.recheck_status != \'fin\''); + + // 关键词搜索:运单号 / 订单号 + const keyword = String(where.keyword || '').trim(); + if (keyword) { + conditions.push(`( + o.delivery_order_code LIKE :keyword + OR o.pre_delivery_order_code LIKE :keyword + OR EXISTS ( + SELECT 1 FROM order_express oe + WHERE oe.order_id = o.id + AND oe.waybill_code LIKE :keyword + AND oe.delete_at IS NULL + ) + )`); + replacements.keyword = `%${keyword}%`; + } + + // 波次号筛选 + const waveNo = String(where.wave_no || '').trim(); + if (waveNo) { + conditions.push('o.wave_no = :waveNo'); + replacements.waveNo = waveNo; + } + + // 复核状态筛选 + const recheckStatus = String(where.recheck_status || '').trim(); + if (recheckStatus) { + conditions.push('o.recheck_status = :recheckStatus'); + replacements.recheckStatus = recheckStatus; + } + + // 拣货状态筛选 + const pickStatus = String(where.pick_status || '').trim(); + if (pickStatus) { + conditions.push('o.pick_status = :pickStatus'); + replacements.pickStatus = pickStatus; + } + + const whereClause = conditions.length > 0 + ? `WHERE ${conditions.join('\n AND ')}` + : ''; + + const listSql = ` + SELECT + o.id AS order_id, + o.delivery_order_code, + o.pre_delivery_order_code, + o.order_type, + o.wave_id, + o.wave_no, + o.pick_status, + o.recheck_status, + o.shop_nick, + o.logistics_name, + o.items_count, + o.items_total, + o.status, + o.create_at, + o.pick_time, + o.recheck_time + FROM ${orderTableName} o + ${whereClause} + ORDER BY o.id ASC + LIMIT :limit OFFSET :offset + `; + + const countSql = ` + SELECT COUNT(1) AS total + FROM ${orderTableName} o + ${whereClause} + `; + + const [ listRows, countRows ] = await Promise.all([ + ctx.model.query(listSql, { + replacements, + type: ctx.model.QueryTypes.SELECT, + }), + ctx.model.query(countSql, { + replacements, + type: ctx.model.QueryTypes.SELECT, + }), + ]); + + const total = Number( + (Array.isArray(countRows) && countRows.length > 0 ? countRows[0]?.total : 0) + ); + const totalPages = pageSize > 0 ? Math.ceil(total / pageSize) : 0; + + const list = (Array.isArray(listRows) ? listRows : []).map(row => ({ + order_id: Number(row?.order_id || 0), + delivery_order_code: String(row?.delivery_order_code || row?.pre_delivery_order_code || '').trim(), + order_type: String(row?.order_type || '').trim(), + wave_id: Number(row?.wave_id || 0), + wave_no: String(row?.wave_no || '').trim(), + pick_status: String(row?.pick_status || '').trim(), + recheck_status: String(row?.recheck_status || '').trim(), + shop_nick: String(row?.shop_nick || '').trim(), + logistics_name: String(row?.logistics_name || '').trim(), + items_count: Number(row?.items_count || 0), + items_total: Number(row?.items_total || 0), + status: Number(row?.status || 0), + create_at: row?.create_at || null, + pick_time: row?.pick_time || null, + recheck_time: row?.recheck_time || null, + })); + + return this.success('ok', { + list, + pagination: { + page, + pageSize, + total, + totalPages, + hasPrevious: page > 1, + hasNext: page < totalPages, + }, + }); + } + + /** + * 团购模式复核列表:按波次维度返回复核汇总,每项包含波次信息及订单复核统计。 + * @param {Object} data 请求参数。 + * @param {Object} [data.where] 筛选条件,支持 wave_no / wave_type / wave_status 等。 + * @param {Object} [data.pagination] 分页参数。 + * @return {Promise} { list: Array, pagination: Object }。 + */ + async queryRecheckOrderGroupList(data = {}) { + const { ctx } = this; + const warehouseId = this.getWarehouseId(); + const requestData = this.isPlainObject(data) ? data : {}; + const { page, pageSize } = this.normalizePagination(requestData.pagination || requestData); + const where = this.isPlainObject(requestData.where) ? requestData.where : {}; + const offset = (page - 1) * pageSize; + const orderModel = await this.getOrderModelByTableType('current', warehouseId); + const orderTableName = this.resolveModelTableName(orderModel); + + const conditions = []; + const replacements = { warehouseId, limit: pageSize, offset }; + + conditions.push('wb.warehouse_id = :warehouseId'); + + // 波次号筛选 + const waveNo = String(where.wave_no || '').trim(); + if (waveNo) { + conditions.push('wb.wave_no LIKE :waveNo'); + replacements.waveNo = `%${waveNo}%`; + } + + // 波次类型筛选 + const waveType = Number(where.wave_type); + if (Number.isInteger(waveType) && waveType > 0) { + conditions.push('wb.wave_type = :waveType'); + replacements.waveType = waveType; + } + + // 波次状态筛选 + const waveStatus = Number(where.wave_status); + if (Number.isInteger(waveStatus)) { + conditions.push('wb.wave_status = :waveStatus'); + replacements.waveStatus = waveStatus; + } + + const whereClause = conditions.length > 0 + ? `WHERE ${conditions.join('\n AND ')}` + : ''; + + const listSql = ` + SELECT + wb.wave_id, + wb.wave_no, + wb.wave_type, + wb.wave_status, + wb.total_orders, + wb.processed_orders, + wb.creator, + wb.create_time, + wb.update_time, + COUNT(o.id) AS order_count, + SUM(CASE WHEN o.recheck_status = 'fin' THEN 1 ELSE 0 END) AS reviewed_count, + SUM(CASE WHEN o.recheck_status != 'fin' OR o.recheck_status IS NULL THEN 1 ELSE 0 END) AS unreviewed_count + FROM wms_wave_batch wb + LEFT JOIN ${orderTableName} o + ON o.wave_no = wb.wave_no + AND o.warehouse_id = wb.warehouse_id + AND o.pick_status != 'none' + ${whereClause} + GROUP BY wb.wave_id, wb.wave_no, wb.wave_type, wb.wave_status, + wb.total_orders, wb.processed_orders, wb.creator, + wb.create_time, wb.update_time + ORDER BY wb.create_time DESC, wb.wave_id DESC + LIMIT :limit OFFSET :offset + `; + + const countSql = ` + SELECT COUNT(1) AS total + FROM wms_wave_batch wb + ${whereClause} + `; + + const [ listRows, countRows ] = await Promise.all([ + ctx.model.query(listSql, { + replacements, + type: ctx.model.QueryTypes.SELECT, + }), + ctx.model.query(countSql, { + replacements, + type: ctx.model.QueryTypes.SELECT, + }), + ]); + + const total = Number( + (Array.isArray(countRows) && countRows.length > 0 ? countRows[0]?.total : 0) + ); + const totalPages = pageSize > 0 ? Math.ceil(total / pageSize) : 0; + + const list = (Array.isArray(listRows) ? listRows : []).map(row => { + const orderCount = Number(row?.order_count || 0); + const reviewedCount = Number(row?.reviewed_count || 0); + const unreviewedCount = Number(row?.unreviewed_count || 0); + + return { + wave_id: Number(row?.wave_id || 0), + wave_no: String(row?.wave_no || '').trim(), + wave_type: Number(row?.wave_type || 0), + wave_status: Number(row?.wave_status || 0), + total_orders: Number(row?.total_orders || 0), + processed_orders: Number(row?.processed_orders || 0), + creator: String(row?.creator || '').trim(), + create_time: row?.create_time || null, + update_time: row?.update_time || null, + order_count: orderCount, + reviewed_count: reviewedCount, + unreviewed_count: unreviewedCount, + review_assignment_status: orderCount === 0 || reviewedCount === 0 + ? 'unreviewed' + : reviewedCount >= orderCount + ? 'reviewed' + : 'partially_reviewed', + }; + }); + + return this.success('ok', { + list, + pagination: { + page, + pageSize, + total, + totalPages, + hasPrevious: page > 1, + hasNext: page < totalPages, + }, + }); + } + + /** + * 从 Sequelize 模型解析 SQL 表名并安全转义。 + * @param {Object} model Sequelize 模型对象。 + * @return {string} 可直接拼接到 SQL 的表名(已做反引号转义)。 + */ + resolveModelTableName(model) { + const rawTableName = model && typeof model.getTableName === 'function' + ? model.getTableName() + : model && model.tableName; + const tableName = typeof rawTableName === 'string' + ? rawTableName + : rawTableName && typeof rawTableName.tableName === 'string' + ? rawTableName.tableName + : ''; + const normalizedTableName = String(tableName || '').trim(); + if (!normalizedTableName) { + throw new Error('订单模型表名解析失败'); + } + + const tableParts = normalizedTableName.split('.') + .map(part => String(part || '').trim()) + .filter(Boolean); + if (tableParts.length === 0) { + throw new Error('订单模型表名解析失败'); + } + + for (const tablePart of tableParts) { + if (!/^[a-zA-Z0-9_$]+$/.test(tablePart)) { + throw new Error(`订单模型表名不合法: ${normalizedTableName}`); + } + } + + return tableParts.map(part => `\`${part}\``).join('.'); + } + + /** + * 确认仓库拦截:通过订单ID直接匹配订单,将其拦截状态更新为"仓库拦截成功"。 + * 仅拦截当前指定订单(不波及波次内其他订单)。 + * @param {Object} data 请求体。 + * @param {number} data.order_id 订单ID。 + * @return {Promise} 拦截确认结果,包含 order_id、intercept_status 与更新时间。 + */ + async confirmIntercept(data = {}) { + const { ctx } = this; + const { order_id } = data; + const warehouseId = this.getWarehouseId(); + const orderId = Number(order_id); + + if (!orderId || !Number.isFinite(orderId) || orderId <= 0) { + throw new Error('order_id 无效'); + } + + const orderModel = await this.getOrderModelByTableType('current', warehouseId); + const orderWhere = this.buildOrderWhere([ orderId ], warehouseId); + const order = await orderModel.findOne({ + where: orderWhere, + attributes: [ 'id', 'delivery_order_code', 'pre_delivery_order_code', 'intercept_status', 'wave_no' ], + raw: true, + }); + + if (!order) { + throw new Error('未找到对应订单'); + } + + const now = new Date(); + const updateValues = { + intercept_status: 'intercepted_at_warehouse', + updated_at: now, + }; + const updateResult = await orderModel.update(updateValues, { + where: orderWhere, + }); + const affectedRows = Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0); + + if (affectedRows <= 0) { + throw new Error('拦截状态更新失败,请稍后重试'); + } + + const orderNo = String(order.delivery_order_code || order.pre_delivery_order_code || '').trim(); + + // 写入操作日志(失败不影响主流程) + try { + const operator = this.getOrderLogOperator(); + const logWarehouseId = this.getOrderLogWarehouseId(warehouseId); + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'order', + businessId: logWarehouseId, + operationCode: 'ORDER_INTERCEPT_CONFIRM', + operator, + extras: { + warehouseId: logWarehouseId, + orderId, + orderNo, + previousInterceptStatus: String(order.intercept_status || '').trim(), + newInterceptStatus: 'intercepted_at_warehouse', + }, + beforeChanges: null, + }); + } catch (logErr) { + ctx.logger.warn( + `[recheckOrder.confirmIntercept] 写入操作日志失败,不影响业务, orderId=${orderId}, error=${logErr.message}` + ); + } + + return { + order_id: orderId, + order_no: orderNo, + intercept_status: 'intercepted_at_warehouse', + updated_at: now, + }; + } + } module.exports = RecheckOrderService; diff --git a/app/service/systemMethods/order/wave.js b/app/service/systemMethods/order/wave.js index 7b0864a..476890d 100644 --- a/app/service/systemMethods/order/wave.js +++ b/app/service/systemMethods/order/wave.js @@ -836,6 +836,8 @@ class WaveService extends OrderBaseService { step: { [Op.in]: [ 1, 2, 3 ] }, status: { [Op.ne]: 'cancel' }, outbound_status: { [Op.ne]: 'padding' }, + intercept_status: 'none', + lock_status: 'none', wave_id: 0, }; @@ -2133,6 +2135,8 @@ class WaveService extends OrderBaseService { step: { [Op.in]: [ 1, 2, 3 ] }, status: { [Op.ne]: 'cancel' }, outbound_status: { [Op.ne]: 'padding' }, + intercept_status: 'none', + lock_status: 'none', wave_id: 0, }; @@ -2363,6 +2367,8 @@ class WaveService extends OrderBaseService { step: { [Op.in]: [ 1, 2, 3 ] }, status: { [Op.ne]: 'cancel' }, outbound_status: { [Op.ne]: 'padding' }, + intercept_status: 'none', + lock_status: 'none', wave_id: 0, }; @@ -2741,7 +2747,8 @@ class WaveService extends OrderBaseService { o.status, o.outbound_status, o.post_status, - o.storage_status + o.storage_status, + o.print_status FROM wms_order_wave_strategy_match m INNER JOIN ${orderTableName} o ON o.id = m.order_id @@ -2750,8 +2757,11 @@ class WaveService extends OrderBaseService { AND o.step != 0 AND o.post_status = 'fin' AND o.storage_status = 'fin' + AND o.print_status != 'fin' AND o.status != 'cancel' AND o.outbound_status != 'padding' + AND o.intercept_status = 'none' + AND o.lock_status = 'none' WHERE m.warehouse_id = :warehouseId AND m.strategy_id = :strategyId ORDER BY o.id ASC @@ -2967,8 +2977,11 @@ class WaveService extends OrderBaseService { AND o.step != 0 AND o.post_status = 'fin' AND o.storage_status = 'fin' + AND o.print_status != 'fin' AND o.status != 'cancel' AND o.outbound_status != 'padding' + AND o.intercept_status = 'none' + AND o.lock_status = 'none' INNER JOIN ( SELECT COALESCE(NULLIF(TRIM(COALESCE(src.items_hash, '')), ''), TRIM(COALESCE(src.items, ''))) AS structure_key, @@ -2979,8 +2992,11 @@ class WaveService extends OrderBaseService { AND src.step != 0 AND src.post_status = 'fin' AND src.storage_status = 'fin' + AND src.print_status != 'fin' AND src.status != 'cancel' AND src.outbound_status != 'padding' + AND src.intercept_status = 'none' + AND src.lock_status = 'none' GROUP BY COALESCE(NULLIF(TRIM(COALESCE(src.items_hash, '')), ''), TRIM(COALESCE(src.items, ''))) ) same_structure ON same_structure.structure_key = COALESCE(NULLIF(TRIM(COALESCE(o.items_hash, '')), ''), TRIM(COALESCE(o.items, ''))) @@ -3915,35 +3931,94 @@ class WaveService extends OrderBaseService { province: normalizedOrderRow.province ?? null, sys_platform_name: normalizedOrderRow.sys_platform_name ?? null, item_snapshot: String(itemSnapshot || ''), + excluded_reason: normalizedOrderRow.lock_status !== 'none' + ? 'locked' + : normalizedOrderRow.intercept_status !== 'none' + ? 'intercepted' + : normalizedOrderRow.print_status === 'fin' + ? 'printed' + : 'no_match', }; } /** - * 查询兜底不符合波次策略的订单列表。 + * 查询兜底不符合波次策略的订单列表(含已完全打印被排除的订单)。 * - * 直接复用订单通用列表能力,返回标准 list/pagination 结构。 + * 查询条件:step != 0 且 wave_id = 0,且满足以下任一条件: + * - wave_scan_result = 2(未匹配任何波次策略) + * - print_status = 'fin'(已完全打印,被策略抓取阶段排除) * 在当前页订单上增补 item_snapshot(格式:商品名称1*数量|商品名称2*数量)。 * * @param {Object} data 请求参数。 * @param {Object} data.pagination 分页参数。 * @param {Object} data.where 查询条件。 * @param {Object} data.sort 排序参数。 - * @return {Promise} 列表查询结果。 + * @return {Promise} 列表查询结果,每行含 excluded_reason 标记。 */ async waveStrategyFallbackOrderList(data = {}) { const requestData = this.isPlainObject(data) ? data : {}; const { pagination, where, sort } = requestData; const normalizedPagination = this.normalizePagination(pagination || {}); + const { page, pageSize } = normalizedPagination; const normalizedWhere = this.normalizeWaveStrategyFallbackOrderListWhere(where); - const listResult = await this.listByModule('waveStrategyFallbackOrder', { - ...requestData, - pagination: normalizedPagination, - where: normalizedWhere, - sort, + const contextWarehouseId = this.getWarehouseId(); + + // 构建基础 WHERE(复用框架 where 解析、快递号虚拟筛选等能力) + const { where: ctxWhere } = this.prepareWhereContext( + { ...requestData, where: normalizedWhere }, + { specialFieldMap: { quickWhere: { bucket: 'quick' } } } + ); + const { where: sanitizedWhere, expressNumbers } = this.extractOrderListExpressVirtualFilter(ctxWhere); + const defaultWhere = this.getDefaultWhere('waveStrategyFallbackOrder'); + const mergedWhere = this.mergeWhereObjects(defaultWhere, sanitizedWhere); + let queryWhere = this.buildWhere(mergedWhere, contextWarehouseId, { + specialFieldMap: { quickWhere: { bucket: 'quick' } }, }); - const normalizedResult = this.isPlainObject(listResult) ? listResult : {}; - const sourceList = Array.isArray(normalizedResult.list) ? normalizedResult.list : []; - const orderIds = sourceList + + // 处理快递号虚拟筛选 + if (expressNumbers.length > 0) { + const orderIds = await this.findOrderIdsByExpressNumbers(expressNumbers, contextWarehouseId); + queryWhere = this.appendOrderIdsFilterToWhere(queryWhere, orderIds); + } + + // 追加 OR 条件:未匹配策略(wave_scan_result=2) 或 已完全打印被排除(print_status='fin') + const { Sequelize } = this.app; + queryWhere = { + [Sequelize.Op.and]: [ + queryWhere, + { + [Sequelize.Op.or]: [ + { wave_scan_result: 2 }, + { print_status: 'fin' }, + { lock_status: { [Sequelize.Op.ne]: 'none' } }, + { intercept_status: { [Sequelize.Op.ne]: 'none' } }, + ], + }, + ], + }; + + // 获取模型并分页查询 + const model = await this.getOrderModel('waveStrategyFallbackOrder', contextWarehouseId); + const order = this.buildListOrder(sort, 'waveStrategyFallbackOrder'); + const offset = (page - 1) * pageSize; + + const [ total, sourceList ] = await Promise.all([ + model.count({ where: queryWhere }), + model.findAll({ + where: queryWhere, + limit: pageSize, + offset, + order, + raw: true, + }), + ]); + + const normalizedList = await this.attachOrderExpressNumbers( + sourceList.map(item => this.normalizeOrderListItem(item)) + ); + + // 回填 item_snapshot + const orderIds = normalizedList .map(item => Number(item && item.id || 0)) .filter(id => Number.isInteger(id) && id > 0); const warehouseId = Number(this.getWarehouseId() || 0); @@ -3992,14 +4067,23 @@ class WaveService extends OrderBaseService { } } - const list = sourceList.map(item => { + const totalPages = pageSize > 0 ? Math.ceil(total / pageSize) : 0; + + const list = normalizedList.map(item => { const orderId = Number(item && item.id || 0); return this.buildWaveStrategyFallbackOrderListItem(item, itemSnapshotMap.get(orderId) || ''); }); return this.success('ok', { - ...normalizedResult, list, + pagination: { + page, + pageSize, + total, + totalPages, + hasPrevious: page > 1, + hasNext: page < totalPages, + }, }); } @@ -5149,6 +5233,9 @@ class WaveService extends OrderBaseService { warehouse_id: warehouseId, step: { [Op.ne]: 0 }, wave_id: 0, + intercept_status: 'none', + lock_status: 'none', + print_status: { [Op.ne]: 'fin' }, [Op.or]: [ { wave_strategy_version: { [Op.ne]: strategyVersion } }, { wave_strategy_version: { [Op.is]: null } }, @@ -9643,8 +9730,11 @@ class WaveService extends OrderBaseService { AND o.step != 0 AND o.post_status = 'fin' AND o.storage_status = 'fin' + AND o.print_status != 'fin' AND o.status != 'cancel' AND o.outbound_status != 'padding' + AND o.intercept_status = 'none' + AND o.lock_status = 'none' INNER JOIN ( SELECT ${structureExpr('src')} AS structure_key${requireSameExpress ? `, ${expressExpr('src')} AS express_key` : ''}, @@ -9655,8 +9745,11 @@ class WaveService extends OrderBaseService { AND src.step != 0 AND src.post_status = 'fin' AND src.storage_status = 'fin' + AND src.print_status != 'fin' AND src.status != 'cancel' AND src.outbound_status != 'padding' + AND src.intercept_status = 'none' + AND src.lock_status = 'none' GROUP BY ${structureExpr('src')}${groupKeyExtra} ) same_structure ON same_structure.structure_key = ${structureExpr('o')}${joinKeyExtra} diff --git a/app/service/systems/order_print.js b/app/service/systems/order_print.js index ecbdee7..29c696a 100644 --- a/app/service/systems/order_print.js +++ b/app/service/systems/order_print.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict'; const fs = require('node:fs'); const path = require('node:path'); @@ -621,6 +621,176 @@ class OrderPrintSystemService extends OrderBaseService { }; } + /** + * 按订单ID拉取平台打印中间态数据。 + * + * 与 getWavePlatformPrintData 输出完全相同的结构,但入参由波次ID改为订单ID。 + * 跳过了波次查询步骤,直接从订单ID入手,其余打印数据组装、锁定/未锁定分离、 + * 波次平台分组等逻辑与 getWavePlatformPrintData 保持一致。 + * 仓库ID统一从当前上下文获取,不再接受调用方传入。 + * + * @param {Object} params 请求参数。 + * @param {Array} params.orderIds 订单ID数组。 + * @return {Promise} 平台打印中间态结果。 + */ + async getOrderPrintData(params = {}) { + const requestParams = this.isPlainObject(params) ? params : {}; + const { + orderIds, + } = requestParams; + + const normalizedOrderIds = this.normalizeOrderIds(orderIds); + if (normalizedOrderIds.length === 0) { + throw new Error('order_ids 必填,且必须为非空数组'); + } + + const normalizedWarehouseId = this.getContextWarehouseId(); + const orderRows = await this.queryOrdersByIds(normalizedOrderIds, normalizedWarehouseId); + if (orderRows.length === 0) { + return { + summary: { + total_waves: 0, + total_orders: 0, + total_platforms: 0, + }, + waveGroups: [], + wave_ids: [], + ext: { + missing_order_ids: normalizedOrderIds, + filtered_order_ids: [], + }, + }; + } + + const hitOrderIdSet = new Set(orderRows.map(row => Number(row.id))); + const missingOrderIds = normalizedOrderIds.filter(orderId => !hitOrderIdSet.has(orderId)); + + // 订单级过滤:仅保留 post_status === 'fin' 的订单(等价于波次级的快递完全分配检查) + const validOrderRows = orderRows.filter(row => String(row && row.post_status || '').trim() === 'fin'); + const filteredOrderIds = orderRows + .filter(row => String(row && row.post_status || '').trim() !== 'fin') + .map(row => ({ + order_id: Number(row && row.id || 0), + reason: '快递未完全分配', + })); + + if (validOrderRows.length === 0) { + return { + summary: { + total_waves: 0, + total_orders: 0, + total_platforms: 0, + }, + waveGroups: [], + wave_ids: [], + ext: { + missing_order_ids: missingOrderIds, + filtered_order_ids: filteredOrderIds, + }, + }; + } + + const validOrderWaveIds = Array.from(new Set(validOrderRows + .map(row => Number(row && row.wave_id || 0)) + .filter(waveId => Number.isInteger(waveId) && waveId > 0))); + + const waveRows = await this.queryWavesByIds(normalizedWarehouseId, validOrderWaveIds); + + const orderIdsForExpress = validOrderRows + .map(row => Number(row && row.id || 0)) + .filter(orderId => Number.isInteger(orderId) && orderId > 0); + const orderExpressRows = await this.queryOrderExpressByOrderIds(orderIdsForExpress); + this.assertBusinessWaybillCompleteness(orderIdsForExpress, orderExpressRows); + const cainiaoEnrichedOrderExpressRows = await this.enrichCainiaoOrderExpressRows( + validOrderRows, + orderExpressRows, + normalizedWarehouseId + ); + const jdEnrichedOrderExpressRows = await this.enrichJdOrderExpressRows( + validOrderRows, + cainiaoEnrichedOrderExpressRows, + normalizedWarehouseId + ); + const enrichedOrderExpressRows = await this.enrichPddDyOrderExpressRows( + validOrderRows, + jdEnrichedOrderExpressRows, + normalizedWarehouseId + ); + const orderExpressMap = this.buildOrderExpressMap(enrichedOrderExpressRows); + const policyConfigMap = await this.getPolicyConfigMapByStore(validOrderRows, normalizedWarehouseId); + const pickingCandidateRows = validOrderRows.filter(orderRow => { + const storeId = Number(orderRow && orderRow.store_id || 0); + const policyConfig = policyConfigMap.get(storeId) || {}; + return this.shouldLoadPickingDetails(policyConfig); + }); + const printOrderRowMap = await this.buildPrintOrderRowMapWithPicking(pickingCandidateRows, normalizedWarehouseId); + const waveOrderIndexMap = await this.queryWaveOrderIndexMapByOrderIds( + orderIdsForExpress, + normalizedWarehouseId, + validOrderWaveIds + ); + const waveIdsForCount = validOrderWaveIds; + const waveTotalOrderCountMap = await this.queryWaveTotalOrderCountMap(waveIdsForCount, normalizedWarehouseId); + const templateSampleCache = new Map(); + const orderPrintList = []; + + for (const orderRow of validOrderRows) { + const orderId = Number(orderRow && orderRow.id || 0); + if (!Number.isInteger(orderId) || orderId <= 0) { + continue; + } + + const orderExpress = orderExpressMap.get(orderId) || {}; + const effectiveOrderRow = printOrderRowMap.get(orderId) || orderRow; + const waveOrderIndexInfo = waveOrderIndexMap.get(orderId) || {}; + const waveIdForCount = Number(effectiveOrderRow.wave_id || orderRow.wave_id || waveOrderIndexInfo.wave_id || 0); + const waveTotalOrders = Number(waveTotalOrderCountMap.get(waveIdForCount) || 0); + const waveIndex = Number(waveOrderIndexInfo.wave_index || 0); + const platformsIndex = Number(waveOrderIndexInfo.platforms_index || 0); + const effectiveOrderRowWithWaveIndex = { + ...effectiveOrderRow, + wave_total_orders: waveTotalOrders > 0 ? waveTotalOrders : 0, + wave_index: waveIndex > 0 ? waveIndex : 0, + platforms_index: platformsIndex > 0 ? platformsIndex : 0, + }; + const storeId = Number(orderRow && orderRow.store_id || 0); + const policyConfig = policyConfigMap.get(storeId) || {}; + const platformCode = this.resolvePrintPlatformCode(effectiveOrderRow, orderExpress); + const templateSample = this.loadTemplateSampleByPlatform(platformCode, templateSampleCache); + + orderPrintList.push(this.buildOrderPlatformPrintItem({ + orderRow: effectiveOrderRowWithWaveIndex, + orderExpress, + policyConfig, + platformCode, + templateSample, + })); + } + + const waveGroups = this.groupOrderPrintItemsByWaveAndPlatform({ + waveRows, + hitWaveIds: validOrderWaveIds, + orderPrintList, + }); + const totalPlatforms = waveGroups.reduce((sum, waveGroup) => { + return sum + Number(waveGroup && waveGroup.platforms && waveGroup.platforms.length || 0); + }, 0); + + return { + summary: { + total_waves: waveGroups.length, + total_orders: orderPrintList.length, + total_platforms: totalPlatforms, + }, + waveGroups, + wave_ids: validOrderWaveIds, + ext: { + missing_order_ids: missingOrderIds, + filtered_order_ids: filteredOrderIds, + }, + }; + } + /** * 规范化“按分组解锁”规则。 * @@ -988,6 +1158,46 @@ class OrderPrintSystemService extends OrderBaseService { return Array.from(normalizedSet); } + /** + * 规范化订单ID数组。 + * + * 去重、过滤非法值(非正整数),返回纯数字数组。 + * + * @param {Array} orderIds 订单ID数组。 + * @return {Array} 规范化后的订单ID数组。 + */ + normalizeOrderIds(orderIds = []) { + if (!Array.isArray(orderIds)) { + return []; + } + + const normalizedSet = new Set(); + + for (const rawId of orderIds) { + const normalizedId = Number(String(rawId ?? '').trim()); + if (Number.isInteger(normalizedId) && normalizedId > 0) { + normalizedSet.add(normalizedId); + } + } + + return Array.from(normalizedSet); + } + + /** + * 从当前上下文获取仓库ID。 + * + * 用于不再接受调用方传入 warehouseId 的场景,直接从登录态/上下文读取。 + * + * @return {number} 当前上下文中的仓库ID。 + */ + getContextWarehouseId() { + const contextWarehouseId = Number(this.getWarehouseId() || 0); + if (!Number.isInteger(contextWarehouseId) || contextWarehouseId <= 0) { + throw new Error('缺少当前用户仓库上下文 store_id'); + } + return contextWarehouseId; + } + /** * 解析并校验仓库ID。 * @@ -1107,6 +1317,72 @@ class OrderPrintSystemService extends OrderBaseService { return Array.isArray(rows) ? rows : []; } + /** + * 按订单ID批量查询订单明细。 + * + * 与 queryOrdersByWaveIds 返回相同的字段结构,但按订单 ID 列表直接查询。 + * + * @param {Array} orderIds 订单ID数组。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise>} 订单明细列表。 + */ + async queryOrdersByIds(orderIds = [], warehouseId) { + if (!Array.isArray(orderIds) || orderIds.length === 0) { + return []; + } + + const orderModel = await this.getOrderModel('order', warehouseId); + const rows = await orderModel.findAll({ + attributes: [ + 'id', + 'delivery_order_code', + 'source_order_codes', + 'warehouse_id', + 'store_id', + 'wave_id', + 'wave_no', + 'name', + 'tel', + 'mobile', + 'province', + 'city', + 'area', + 'town', + 'detail_address', + 'zip_code', + 'items', + 'source_platform_code', + 'sys_platform_code', + 'sys_platform_name', + 'logistics_code', + 'logistics_name', + 'sys_logistics_code', + 'sys_logistics_name', + 'post_status', + 'status', + 'outbound_status', + 'print_status', + 'lock_status', + 'print_lock_status', + 'items_count', + 'items_total', + 'items_weight', + 'freight', + 'create_at', + 'pay_time', + ], + where: { + id: { + [Op.in]: orderIds, + }, + }, + order: [[ 'wave_id', 'ASC' ], [ 'id', 'ASC' ]], + raw: true, + }); + + return Array.isArray(rows) ? rows : []; + } + /** * 按订单ID批量查询快递单信息。 * diff --git a/methods/changes/system.json b/methods/changes/system.json index 72a7834..004ed34 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -2988,5 +2988,160 @@ ], "type": "updated", "module": "order.wave" + }, + { + "version": "2026.06.08-system-01", + "date": "2026-06-08", + "summary": "order.recheckOrder 模块 scanOrder 返回值重构为统一 list 输出,新增 confirmIntercept 与 recheckOrderList 接口", + "methods": [ + "order.recheckOrder.scanOrder", + "order.recheckOrder.confirmIntercept", + "order.recheckOrder.recheckOrderList" + ], + "notes": [ + "scanOrder 返回值重构:统一使用 list 字段输出,新增 list_type 字段区分散单/团购模式。散单模式顶层新增 picker_id、picker_name、wave_id、wave_no、wave_type、pick_mode、strategy_id、strategy_name、total_orders、reviewed_count、unreviewed_count 等汇总字段。list 中每项新增 waybill_no、is_printed、is_reviewed、wave_index、intercept_status、store_remark、stock[](含 stock_id、item_code、item_name、sku_property、packing_requirements、barcodes[]、images[]、plan_qty、has_shared_barcode)。移除旧字段 logs、order、order_id(顶层)、waybill_no(顶层旧位置)、wave_match_view、items、expresses、cart_match_view。", + "scanOrder 入参新增 wave_no / waveNo 支持波次号直接扫描匹配。", + "新增 order.recheckOrder.confirmIntercept:确认拦截接口,将订单 intercept_status 更新为 intercepted_at_warehouse,返回 order_id、order_no、intercept_status、updated_at。", + "新增 order.recheckOrder.recheckOrderList:复核订单列表查询,支持 list_type=single(散单)与 list_type=group(团购),均返回统一 list + pagination 结构。" + ], + "type": "updated" + }, + { + "version": "2026.06.08-system-02", + "date": "2026-06-08", + "summary": "order.recheckOrder 模块新增 batchIntercept/batchInterceptTaskProgress,更新 scanOrder 团购模式响应结构,完善 confirmIntercept/recheckOrderList 文档", + "methods": [ + "order.recheckOrder.batchIntercept", + "order.recheckOrder.batchInterceptTaskProgress", + "order.recheckOrder.scanOrder", + "order.recheckOrder.confirmIntercept", + "order.recheckOrder.recheckOrderList" + ], + "notes": [ + "新增 order.recheckOrder.batchIntercept:批量提交订单拦截(异步任务模式),入参支持 order_ids/orderIds/ids(订单ID数组,不再使用 wave_ids),将 intercept_status 设为 'requested',返回 task_id/warehouse_id/message/accepted_at。支持幂等提交与 warehouse_id 校验。", + "新增 order.recheckOrder.batchInterceptTaskProgress:按 task_id 查询批量拦截任务进度,返回 state(submitted/running/success/failed/not_found)及对应的进度/计数/结果/错误字段。", + "更新 order.recheckOrder.scanOrder 响应文档:团购模式(cart 命中)list 项新增 wave_id/wave_no/wave_type/wave_status/total_orders/processed_orders/creator/create_time/update_time/order_count/pick_mode/box_no/orders[] 等波次级别字段;补充散单无波次信息时的回退详情模式说明(detail/items/expresses/logs)。", + "完善 order.recheckOrder.confirmIntercept:补充操作日志写入说明(ORDER_INTERCEPT_CONFIRM)及失败不影响主流程的容错描述。", + "完善 order.recheckOrder.recheckOrderList:补充散单模式默认排除 pick_status='none' 和 recheck_status='fin' 的说明;团购模式 where 支持 wave_no(模糊搜索)的说明。" + ], + "type": "updated" + }, + { + "version": "2026.06.08-system-03", + "date": "2026-06-08", + "summary": "移除 order.recheckOrder.batchIntercept 的 warehouse_id/warehouseId 入参,仓库ID统一使用当前上下文", + "methods": [ + "order.recheckOrder.batchIntercept" + ], + "notes": [ + "移除入参 warehouse_id / warehouseId:仓库ID统一从当前上下文(ctx.user.store_id)获取,不再由调用方传入。", + "移除对应错误码:warehouse_id 参数不合法(400)、warehouse_id 与当前仓库上下文不一致(400)。", + "description 中补充说明仓库ID来源为当前上下文。", + "response 中 warehouse_id 字段描述改为「取自当前上下文」。" + ], + "type": "updated" + }, + { + "version": "2026.06.08-system-10", + "date": "2026-06-08", + "summary": "batchIntercept / batchInterceptTaskProgress 从 order.recheckOrder 迁移至 order.pendingOrder", + "methods": [ + "order.pendingOrder.batchIntercept", + "order.pendingOrder.batchInterceptTaskProgress" + ], + "notes": [ + "method 从 order.recheckOrder.batchIntercept 重命名为 order.pendingOrder.batchIntercept,分组从订单复核模块迁移至订单待处理模块", + "method 从 order.recheckOrder.batchInterceptTaskProgress 重命名为 order.pendingOrder.batchInterceptTaskProgress,分组从订单复核模块迁移至订单待处理模块", + "接口入参、响应、错误码均保持不变,仅变更 method 名称与所属分组" + ], + "type": "updated" + }, + { + "version": "2026.06.08-system-04", + "date": "2026-06-08", + "summary": "新增 order.print.getOrderPrintData:按订单ID拉取打印数据,返回结构与 getWavePlatformPrintData 一致,不限制锁定状态", + "methods": [ + "order.print.getOrderPrintData" + ], + "notes": [ + "新增 order.print.getOrderPrintData 接口文档,入参为 warehouse_id + order_ids(非空数组),返回与 getWavePlatformPrintData 结构一致的 waveGroups / summary / wave_ids / ext", + "与 getWavePlatformPrintData 的区别:入参为 order_ids(非 wave_ids),ext 中返回 missing_order_ids / filtered_order_ids(非 missing_wave_ids / filtered_wave_ids)", + "不限制打印锁定状态,所有订单(无论是否被锁定)统一返回打印数据", + "自动过滤 post_status !== 'fin' 的订单(快递未完全分配),被过滤订单出现在 ext.filtered_order_ids" + ], + "type": "added", + "module": "order.print" + }, + { + "version": "2026.06.08-system-11", + "date": "2026-06-08", + "summary": "新增 order.pendingOrder 批量锁定/解锁/解除拦截及对应进度查询共 6 个异步任务接口文档", + "methods": [ + "order.pendingOrder.batchLock", + "order.pendingOrder.batchLockTaskProgress", + "order.pendingOrder.batchUnlock", + "order.pendingOrder.batchUnlockTaskProgress", + "order.pendingOrder.batchUnintercept", + "order.pendingOrder.batchUninterceptTaskProgress" + ], + "notes": [ + "新增 batchLock:批量锁定订单,lock_status → 'warehouse',操作日志 ORDER_LOCK,task_id 格式 order_lock_{warehouseId}_{timestamp}_{rand}。", + "新增 batchLockTaskProgress:查询批量锁定进度,返回 locked_order_count / locked_order_ids 等。", + "新增 batchUnlock:批量解锁订单,lock_status → 'none',操作日志 ORDER_UNLOCK,task_id 格式 order_unlock_{warehouseId}_{timestamp}_{rand}。", + "新增 batchUnlockTaskProgress:查询批量解锁进度,返回 unlocked_order_count / unlocked_order_ids 等。", + "新增 batchUnintercept:批量解除拦截订单,intercept_status → 'none',操作日志 ORDER_INTERCEPT_CANCEL,task_id 格式 order_unintercept_{warehouseId}_{timestamp}_{rand}。", + "新增 batchUninterceptTaskProgress:查询批量解除拦截进度,返回 unintercepted_order_count / unintercepted_order_ids 等。", + "以上 6 个接口均采用与已有 batchIntercept/batchInterceptTaskProgress 一致的异步任务模式:提交返回 task_id,进度查询返回 state + 进度字段。", + "仅同步文档,不修改业务代码或实现。" + ], + "type": "added", + "module": "order" + }, + { + "version": "2026.06.08-system-12", + "date": "2026-06-08", + "summary": "更新 order.print.getOrderPrintData:移除锁定限制,所有订单统一返回打印数据,不再区分锁定/未锁定", + "methods": [ + "order.print.getOrderPrintData" + ], + "notes": [ + "移除打印锁定限制:所有订单(包括已锁定)统一返回打印数据,不再区分锁定/未锁定状态", + "移除 locked_count、locked_orders、locked_wave_groups 等锁定相关字段", + "返回结构与 getWavePlatformPrintData 完全一致:summary / waveGroups / wave_ids / ext", + "ext 中使用 missing_order_ids / filtered_order_ids(替代锁定相关字段),与代码实现完全对齐" + ], + "type": "updated", + "module": "order.print" + }, + { + "version": "2026.06.08-system-13", + "date": "2026-06-08", + "summary": "更新 order.print.getOrderPrintData:移除 warehouse_id 入参,仓库ID统一从当前上下文获取", + "methods": [ + "order.print.getOrderPrintData" + ], + "notes": [ + "移除 warehouse_id / warehouseId 入参,仓库ID统一从 this.getContextWarehouseId() 获取", + "同步移除 errors 中 warehouse_id 必填 相关错误码", + "description 补充说明仓库ID从上下文获取,无需调用方传入", + "params 仅保留 order_ids(非空数组),与代码 method 层 getOrderPrintData(data) 解构一致" + ], + "type": "updated", + "module": "order.print" + }, + { + "version": "2026.06.08-system-14", + "date": "2026-06-08", + "summary": "新增 order.recheckOrder.scanTask 接口文档,并为 scanOrder 响应补充 task_id 字段", + "methods": [ + "order.recheckOrder.scanTask", + "order.recheckOrder.scanOrder" + ], + "notes": [ + "新增 order.recheckOrder.scanTask:按拣货任务 ID 拉取复核数据,数据结构与 scanOrder 完全一致,用于前端刷新。入参为 task_id(必填,number),返回 match_type='task',散单模式(pick_mode 2/3/4)返回扁平订单列表,团购模式(pick_mode 1/5)返回分组波次列表。", + "更新 order.recheckOrder.scanOrder 响应定义:补充 task_id 字段说明(散单有波次时由 buildSingleWaveScanView 返回,团单车号命中时由 cartMatchContext 返回)。", + "仅同步文档,不修改任何业务代码或实现。" + ], + "type": "updated" } ] diff --git a/methods/system.json b/methods/system.json index 0dd92b8..3e5da59 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1,8 +1,8 @@ { "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", - "version": "0.3.5", - "updatedAt": "2026-06-07", + "version": "0.3.19", + "updatedAt": "2026-06-08", "headers": [ { "name": "platform", @@ -3964,16 +3964,10 @@ "message": "仅允许修改 post_status='none'(未分配快递)的订单;若订单已分配快递则更新行数为 0,不会报错但实际无更新" } ] - } - ] - }, - { - "groupName": "订单复核模块", - "module": "order.recheckOrder", - "list": [ + }, { - "method": "order.recheckOrder.scanOrder", - "description": "扫码查询订单(支持运单号与车号)并返回订单详情。车号命中时按 pick_mode 返回语义化结构。", + "method": "order.pendingOrder.batchIntercept", + "description": "批量提交订单拦截请求(异步任务模式)。接收订单ID数组,提交后立即返回 task_id 和受理信息,后端异步将每个订单的 intercept_status 更新为 'requested' 并写入操作日志(ORDER_INTERCEPT_REQUEST)。相同 task_id 幂等提交会返回已存在任务的信息。仓库ID统一使用当前上下文(ctx.user.store_id)。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -3986,11 +3980,789 @@ ], "params": [ { - "name": "keyword / value / waybill_no / waybillCode / waybill_code / cart_code / cartCode", + "name": "order_ids / orderIds / ids", + "type": "number[]", + "required": true, + "source": "body", + "description": "订单ID数组;优先级 order_ids > orderIds > ids" + }, + { + "name": "task_id / taskId", + "type": "string", + "required": false, + "source": "body", + "description": "外部指定任务ID(用于幂等提交,不传则自动生成)" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务ID,格式 recheck_intercept_{warehouseId}_{timestamp}_{rand}(幂等提交时返回已有任务的 task_id)" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "仓库ID(取自当前上下文)" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "任务提交状态说明:'批量拦截任务已提交。' 或 '批量拦截任务已存在,请勿重复提交。'" + }, + { + "name": "accepted_at", + "type": "string", + "required": true, + "description": "任务受理时间(ISO 字符串)" + }, + { + "name": "status", + "type": "string", + "required": false, + "description": "提交状态(固定为 'success')" + }, + { + "name": "state", + "type": "string", + "required": false, + "description": "幂等提交时返回已有任务的状态:submitted / running / success / failed" + } + ], + "errors": [ + { + "code": 400, + "message": "未识别到当前仓库上下文" + }, + { + "code": 400, + "message": "order_ids 参数不能为空或格式错误" + } + ] + }, + { + "method": "order.pendingOrder.batchInterceptTaskProgress", + "description": "查询批量拦截任务进度。根据 task_id 返回任务的当前状态、进度百分比、已处理/已拦截订单数等信息。任务状态 state 包含 submitted(已提交)、running(执行中)、success(已完成)、failed(失败)、not_found(未找到)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "task_id / taskId", "type": "string", "required": true, "source": "body|query", - "description": "扫描关键词;优先按运单号匹配,未命中时回退到 wms_wave_pick_task.current_cart_code_snapshot / wms_wave_pick_task_order.cart_code_snapshot 车号匹配,支持别名 waybillCode/waybill_code/cart_code/cartCode" + "description": "任务ID" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务ID" + }, + { + "name": "state", + "type": "string", + "required": true, + "description": "任务状态:submitted / running / success / failed / not_found" + }, + { + "name": "warehouse_id", + "type": "number", + "required": false, + "description": "仓库ID(not_found 时不返回)" + }, + { + "name": "submitted_at", + "type": "number|null", + "required": false, + "description": "任务提交时间戳(毫秒)" + }, + { + "name": "start_time", + "type": "number|null", + "required": false, + "description": "任务开始执行时间戳(毫秒,running/success/failed 时返回)" + }, + { + "name": "end_time", + "type": "number|null", + "required": false, + "description": "任务结束时间戳(毫秒,success/failed 时返回)" + }, + { + "name": "progress_percent", + "type": "number", + "required": false, + "description": "进度百分比 0-100(submitted/running/success/failed 时返回)" + }, + { + "name": "total_order_count", + "type": "number", + "required": false, + "description": "总订单数(submitted/running/success/failed 时返回)" + }, + { + "name": "processed_order_count", + "type": "number", + "required": false, + "description": "已处理订单数(仅 submitted/running 时返回)" + }, + { + "name": "intercepted_order_count", + "type": "number", + "required": false, + "description": "已拦截订单数(submitted/running/success/failed 时返回)" + }, + { + "name": "intercepted_order_ids", + "type": "number[]", + "required": false, + "description": "已拦截订单ID列表(仅 success 时返回)" + }, + { + "name": "duration_ms", + "type": "number", + "required": false, + "description": "任务耗时(毫秒,success/failed 时返回)" + }, + { + "name": "error_message", + "type": "string", + "required": false, + "description": "错误信息(仅 failed 时返回)" + }, + { + "name": "error_code", + "type": "string", + "required": false, + "description": "错误码(仅 failed 时返回,默认 'BATCH_INTERCEPT_FAILED')" + } + ], + "errors": [ + { + "code": 400, + "message": "task_id 参数不能为空" + } + ] + }, + { + "method": "order.pendingOrder.batchLock", + "description": "批量提交订单锁定请求(异步任务模式)。接收订单ID数组,提交后立即返回 task_id 和受理信息,后端异步将每个订单的 lock_status 更新为 'warehouse' 并写入操作日志(ORDER_LOCK)。相同 task_id 幂等提交会返回已存在任务的信息。仓库ID统一使用当前上下文(ctx.user.store_id)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "order_ids / orderIds / ids", + "type": "number[]", + "required": true, + "source": "body", + "description": "订单ID数组;优先级 order_ids > orderIds > ids" + }, + { + "name": "task_id / taskId", + "type": "string", + "required": false, + "source": "body", + "description": "外部指定任务ID(用于幂等提交,不传则自动生成)" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务ID,格式 order_lock_{warehouseId}_{timestamp}_{rand}(幂等提交时返回已有任务的 task_id)" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "仓库ID(取自当前上下文)" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "任务提交状态说明:'批量锁定任务已提交。' 或 '批量锁定任务已存在,请勿重复提交。'" + }, + { + "name": "accepted_at", + "type": "string", + "required": true, + "description": "任务受理时间(ISO 字符串)" + }, + { + "name": "status", + "type": "string", + "required": false, + "description": "提交状态(固定为 'success')" + }, + { + "name": "state", + "type": "string", + "required": false, + "description": "幂等提交时返回已有任务的状态:submitted / running / success / failed" + } + ], + "errors": [ + { + "code": 400, + "message": "未识别到当前仓库上下文" + }, + { + "code": 400, + "message": "order_ids 参数不能为空或格式错误" + } + ] + }, + { + "method": "order.pendingOrder.batchLockTaskProgress", + "description": "查询批量锁定任务进度。根据 task_id 返回任务的当前状态、进度百分比、已处理/已锁定订单数等信息。任务状态 state 包含 submitted(已提交)、running(执行中)、success(已完成)、failed(失败)、not_found(未找到)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "task_id / taskId", + "type": "string", + "required": true, + "source": "body|query", + "description": "任务ID" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务ID" + }, + { + "name": "state", + "type": "string", + "required": true, + "description": "任务状态:submitted / running / success / failed / not_found" + }, + { + "name": "warehouse_id", + "type": "number", + "required": false, + "description": "仓库ID(not_found 时不返回)" + }, + { + "name": "submitted_at", + "type": "number|null", + "required": false, + "description": "任务提交时间戳(毫秒)" + }, + { + "name": "start_time", + "type": "number|null", + "required": false, + "description": "任务开始执行时间戳(毫秒,running/success/failed 时返回)" + }, + { + "name": "end_time", + "type": "number|null", + "required": false, + "description": "任务结束时间戳(毫秒,success/failed 时返回)" + }, + { + "name": "progress_percent", + "type": "number", + "required": false, + "description": "进度百分比 0-100(submitted/running/success/failed 时返回)" + }, + { + "name": "total_order_count", + "type": "number", + "required": false, + "description": "总订单数(submitted/running/success/failed 时返回)" + }, + { + "name": "processed_order_count", + "type": "number", + "required": false, + "description": "已处理订单数(仅 submitted/running 时返回)" + }, + { + "name": "locked_order_count", + "type": "number", + "required": false, + "description": "已锁定订单数(submitted/running/success/failed 时返回)" + }, + { + "name": "locked_order_ids", + "type": "number[]", + "required": false, + "description": "已锁定订单ID列表(仅 success 时返回)" + }, + { + "name": "duration_ms", + "type": "number", + "required": false, + "description": "任务耗时(毫秒,success/failed 时返回)" + }, + { + "name": "error_message", + "type": "string", + "required": false, + "description": "错误信息(仅 failed 时返回)" + }, + { + "name": "error_code", + "type": "string", + "required": false, + "description": "错误码(仅 failed 时返回,默认 'BATCH_LOCK_FAILED')" + } + ], + "errors": [ + { + "code": 400, + "message": "task_id 参数不能为空" + } + ] + }, + { + "method": "order.pendingOrder.batchUnlock", + "description": "批量提交订单解锁请求(异步任务模式)。接收订单ID数组,提交后立即返回 task_id 和受理信息,后端异步将每个订单的 lock_status 更新为 'none' 并写入操作日志(ORDER_UNLOCK)。相同 task_id 幂等提交会返回已存在任务的信息。仓库ID统一使用当前上下文(ctx.user.store_id)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "order_ids / orderIds / ids", + "type": "number[]", + "required": true, + "source": "body", + "description": "订单ID数组;优先级 order_ids > orderIds > ids" + }, + { + "name": "task_id / taskId", + "type": "string", + "required": false, + "source": "body", + "description": "外部指定任务ID(用于幂等提交,不传则自动生成)" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务ID,格式 order_unlock_{warehouseId}_{timestamp}_{rand}(幂等提交时返回已有任务的 task_id)" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "仓库ID(取自当前上下文)" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "任务提交状态说明:'批量解锁任务已提交。' 或 '批量解锁任务已存在,请勿重复提交。'" + }, + { + "name": "accepted_at", + "type": "string", + "required": true, + "description": "任务受理时间(ISO 字符串)" + }, + { + "name": "status", + "type": "string", + "required": false, + "description": "提交状态(固定为 'success')" + }, + { + "name": "state", + "type": "string", + "required": false, + "description": "幂等提交时返回已有任务的状态:submitted / running / success / failed" + } + ], + "errors": [ + { + "code": 400, + "message": "未识别到当前仓库上下文" + }, + { + "code": 400, + "message": "order_ids 参数不能为空或格式错误" + } + ] + }, + { + "method": "order.pendingOrder.batchUnlockTaskProgress", + "description": "查询批量解锁任务进度。根据 task_id 返回任务的当前状态、进度百分比、已处理/已解锁订单数等信息。任务状态 state 包含 submitted(已提交)、running(执行中)、success(已完成)、failed(失败)、not_found(未找到)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "task_id / taskId", + "type": "string", + "required": true, + "source": "body|query", + "description": "任务ID" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务ID" + }, + { + "name": "state", + "type": "string", + "required": true, + "description": "任务状态:submitted / running / success / failed / not_found" + }, + { + "name": "warehouse_id", + "type": "number", + "required": false, + "description": "仓库ID(not_found 时不返回)" + }, + { + "name": "submitted_at", + "type": "number|null", + "required": false, + "description": "任务提交时间戳(毫秒)" + }, + { + "name": "start_time", + "type": "number|null", + "required": false, + "description": "任务开始执行时间戳(毫秒,running/success/failed 时返回)" + }, + { + "name": "end_time", + "type": "number|null", + "required": false, + "description": "任务结束时间戳(毫秒,success/failed 时返回)" + }, + { + "name": "progress_percent", + "type": "number", + "required": false, + "description": "进度百分比 0-100(submitted/running/success/failed 时返回)" + }, + { + "name": "total_order_count", + "type": "number", + "required": false, + "description": "总订单数(submitted/running/success/failed 时返回)" + }, + { + "name": "processed_order_count", + "type": "number", + "required": false, + "description": "已处理订单数(仅 submitted/running 时返回)" + }, + { + "name": "unlocked_order_count", + "type": "number", + "required": false, + "description": "已解锁订单数(submitted/running/success/failed 时返回)" + }, + { + "name": "unlocked_order_ids", + "type": "number[]", + "required": false, + "description": "已解锁订单ID列表(仅 success 时返回)" + }, + { + "name": "duration_ms", + "type": "number", + "required": false, + "description": "任务耗时(毫秒,success/failed 时返回)" + }, + { + "name": "error_message", + "type": "string", + "required": false, + "description": "错误信息(仅 failed 时返回)" + }, + { + "name": "error_code", + "type": "string", + "required": false, + "description": "错误码(仅 failed 时返回,默认 'BATCH_UNLOCK_FAILED')" + } + ], + "errors": [ + { + "code": 400, + "message": "task_id 参数不能为空" + } + ] + }, + { + "method": "order.pendingOrder.batchUnintercept", + "description": "批量提交解除拦截请求(异步任务模式)。接收订单ID数组,提交后立即返回 task_id 和受理信息,后端异步将每个订单的 intercept_status 更新为 'none' 并写入操作日志(ORDER_INTERCEPT_CANCEL)。相同 task_id 幂等提交会返回已存在任务的信息。仓库ID统一使用当前上下文(ctx.user.store_id)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "order_ids / orderIds / ids", + "type": "number[]", + "required": true, + "source": "body", + "description": "订单ID数组;优先级 order_ids > orderIds > ids" + }, + { + "name": "task_id / taskId", + "type": "string", + "required": false, + "source": "body", + "description": "外部指定任务ID(用于幂等提交,不传则自动生成)" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务ID,格式 order_unintercept_{warehouseId}_{timestamp}_{rand}(幂等提交时返回已有任务的 task_id)" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "仓库ID(取自当前上下文)" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "任务提交状态说明:'批量解除拦截任务已提交。' 或 '批量解除拦截任务已存在,请勿重复提交。'" + }, + { + "name": "accepted_at", + "type": "string", + "required": true, + "description": "任务受理时间(ISO 字符串)" + }, + { + "name": "status", + "type": "string", + "required": false, + "description": "提交状态(固定为 'success')" + }, + { + "name": "state", + "type": "string", + "required": false, + "description": "幂等提交时返回已有任务的状态:submitted / running / success / failed" + } + ], + "errors": [ + { + "code": 400, + "message": "未识别到当前仓库上下文" + }, + { + "code": 400, + "message": "order_ids 参数不能为空或格式错误" + } + ] + }, + { + "method": "order.pendingOrder.batchUninterceptTaskProgress", + "description": "查询批量解除拦截任务进度。根据 task_id 返回任务的当前状态、进度百分比、已处理/已解除拦截订单数等信息。任务状态 state 包含 submitted(已提交)、running(执行中)、success(已完成)、failed(失败)、not_found(未找到)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "task_id / taskId", + "type": "string", + "required": true, + "source": "body|query", + "description": "任务ID" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务ID" + }, + { + "name": "state", + "type": "string", + "required": true, + "description": "任务状态:submitted / running / success / failed / not_found" + }, + { + "name": "warehouse_id", + "type": "number", + "required": false, + "description": "仓库ID(not_found 时不返回)" + }, + { + "name": "submitted_at", + "type": "number|null", + "required": false, + "description": "任务提交时间戳(毫秒)" + }, + { + "name": "start_time", + "type": "number|null", + "required": false, + "description": "任务开始执行时间戳(毫秒,running/success/failed 时返回)" + }, + { + "name": "end_time", + "type": "number|null", + "required": false, + "description": "任务结束时间戳(毫秒,success/failed 时返回)" + }, + { + "name": "progress_percent", + "type": "number", + "required": false, + "description": "进度百分比 0-100(submitted/running/success/failed 时返回)" + }, + { + "name": "total_order_count", + "type": "number", + "required": false, + "description": "总订单数(submitted/running/success/failed 时返回)" + }, + { + "name": "processed_order_count", + "type": "number", + "required": false, + "description": "已处理订单数(仅 submitted/running 时返回)" + }, + { + "name": "unintercepted_order_count", + "type": "number", + "required": false, + "description": "已解除拦截订单数(submitted/running/success/failed 时返回)" + }, + { + "name": "unintercepted_order_ids", + "type": "number[]", + "required": false, + "description": "已解除拦截订单ID列表(仅 success 时返回)" + }, + { + "name": "duration_ms", + "type": "number", + "required": false, + "description": "任务耗时(毫秒,success/failed 时返回)" + }, + { + "name": "error_message", + "type": "string", + "required": false, + "description": "错误信息(仅 failed 时返回)" + }, + { + "name": "error_code", + "type": "string", + "required": false, + "description": "错误码(仅 failed 时返回,默认 'BATCH_UNINTERCEPT_FAILED')" + } + ], + "errors": [ + { + "code": 400, + "message": "task_id 参数不能为空" + } + ] + } + ] + }, + { + "groupName": "订单复核模块", + "module": "order.recheckOrder", + "list": [ + { + "method": "order.recheckOrder.scanOrder", + "description": "扫描关键词并返回以波次为单位的复核视图。支持运单号、波次号、车号三种匹配模式。运单号/波次号命中(散单)返回扁平化订单列表 list_type='single',车号命中(团单)返回嵌套波次结构 list_type='group'。运单号命中但订单无波次信息时,退回单订单详情模式(list 每项含 detail/items/expresses/logs)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "keyword / value / waybill_no / waybillCode / waybill_code / wave_no / waveNo / cart_code / cartCode", + "type": "string", + "required": true, + "source": "body|query", + "description": "扫描关键词;匹配优先级:运单号 → 波次号 → 车号。支持别名 waybillCode/waybill_code(运单号)、waveNo(波次号)、cartCode(车号)" } ], "response": [ @@ -3998,114 +4770,417 @@ "name": "match_type", "type": "string", "required": true, - "description": "命中类型:waybill(运单号命中)/ cart(车号命中)" + "description": "命中类型:waybill(运单号命中)/ wave(波次号命中)/ cart(车号命中)" }, { - "name": "cart_match_view", - "type": "object|null", - "required": true, - "description": "仅 cart 命中返回对象,waybill 命中返回 null" - }, - { - "name": "cart_match_view.mode_code", - "type": "number", - "required": false, - "description": "波次类型编码(pick_mode)" - }, - { - "name": "cart_match_view.mode_name", + "name": "list_type", "type": "string", - "required": false, - "description": "波次类型名称" - }, - { - "name": "cart_match_view.view_type", - "type": "string", - "required": false, - "description": "语义化视图类型:groups/orders/pick_groups/box_groups" - }, - { - "name": "cart_match_view.task", - "type": "object", - "required": false, - "description": "任务摘要信息" - }, - { - "name": "cart_match_view.groups", - "type": "array", - "required": false, - "description": "仅 mode_code=1/5 返回,按 wave 分组" - }, - { - "name": "cart_match_view.orders", - "type": "array", - "required": false, - "description": "仅 mode_code=2 返回,直接返回订单列表" - }, - { - "name": "cart_match_view.pick_groups", - "type": "array", - "required": false, - "description": "仅 mode_code=3 返回,按 pick_status 分组" - }, - { - "name": "cart_match_view.box_groups", - "type": "array", - "required": false, - "description": "仅 mode_code=4 返回,按 box_no 分组" - }, - { - "name": "order_id", - "type": "number", "required": true, - "description": "准确的订单 ID(供 confirmRecheck 使用)" + "description": "列表模式:single(散单扁平列表)/ group(团购嵌套波次列表)" }, { "name": "waybill_no", "type": "string", - "required": true, - "description": "匹配到的运单号" + "required": false, + "description": "仅 waybill 命中时返回,匹配到的运单号" }, { - "name": "order", - "type": "object", - "required": true, - "description": "订单头对象" + "name": "task_id", + "type": "number|null", + "required": false, + "description": "散单有波次信息时返回(来自拣货任务表 wms_wave_pick_task.id),团单车号命中时返回 cartMatchContext 中的任务 ID" }, { - "name": "items", + "name": "picker_id", + "type": "number|null", + "required": false, + "description": "仅散单模式(有波次信息时)返回,拣货人ID(来自 wms_wave_pick_task.pick_user_id)" + }, + { + "name": "picker_name", + "type": "string", + "required": false, + "description": "仅散单模式(有波次信息时)返回,拣货人名称(来自 wms_wave_pick_task.pick_user_name)" + }, + { + "name": "wave_id", + "type": "number", + "required": false, + "description": "仅散单模式(有波次信息时)返回,波次ID" + }, + { + "name": "wave_no", + "type": "string", + "required": false, + "description": "仅散单模式(有波次信息时)返回,波次号" + }, + { + "name": "wave_type", + "type": "number", + "required": false, + "description": "仅散单模式(有波次信息时)返回,波次类型编码(来自 wms_wave_batch.wave_type)" + }, + { + "name": "pick_mode", + "type": "number", + "required": false, + "description": "拣货模式:1-团购小波次 2-散单单品单件 3-散单先拣后分 4-边拣边分 5-团购大波次。散单模式在顶层返回,团购模式在每个波次视图项内返回" + }, + { + "name": "strategy_id", + "type": "number|null", + "required": false, + "description": "仅散单模式返回,波次策略ID" + }, + { + "name": "strategy_name", + "type": "string", + "required": false, + "description": "仅散单模式返回,波次策略名称" + }, + { + "name": "total_orders", + "type": "number", + "required": false, + "description": "仅散单模式返回,波次内订单总数" + }, + { + "name": "reviewed_count", + "type": "number", + "required": false, + "description": "仅散单模式返回,已复核订单数" + }, + { + "name": "unreviewed_count", + "type": "number", + "required": false, + "description": "仅散单模式返回,未复核订单数" + }, + { + "name": "list", "type": "array", "required": true, - "description": "订单商品明细" - }, - { - "name": "expresses", - "type": "array", - "required": true, - "description": "运单信息数组" - }, - { - "name": "logs", - "type": "array", - "required": true, - "description": "相关操作日志" + "description": "统一列表输出。散单模式(list_type=single)有波次信息时:扁平订单数组;无波次信息时退回单订单详情模式(每项含 detail、items、expresses、logs)。团购模式(list_type=group):波次视图数组(每项含 wave_id、wave_no、wave_type、wave_status、total_orders、processed_orders、creator、create_time、update_time、order_count、pick_mode、box_no、orders[])", + "children": [ + { + "name": "order_id", + "type": "number", + "description": "[散单有波次] 订单ID" + }, + { + "name": "delivery_order_code", + "type": "string", + "description": "[散单有波次] 发货单号(优先 delivery_order_code,其次 pre_delivery_order_code)" + }, + { + "name": "waybill_no", + "type": "string", + "description": "[散单有波次] 运单号(从 order_express 关联表查询)" + }, + { + "name": "pick_status", + "type": "string", + "description": "[散单有波次] 拣货状态" + }, + { + "name": "is_printed", + "type": "boolean", + "description": "[散单有波次] 是否已打印(print_status === 'fin')" + }, + { + "name": "is_reviewed", + "type": "boolean", + "description": "[散单有波次] 是否已复核(recheck_status === 'fin')" + }, + { + "name": "shop_nick", + "type": "string", + "description": "[散单有波次] 店铺昵称" + }, + { + "name": "items_count", + "type": "number", + "description": "[散单有波次] 商品种类数" + }, + { + "name": "wave_index", + "type": "number", + "description": "[散单有波次] 波次内序号(优先从 wms_order_wave_index 读取真实 wave_index,若无则降级为数组临时序号)" + }, + { + "name": "recheck_status", + "type": "string", + "description": "[散单有波次] 复核状态" + }, + { + "name": "wave_id", + "type": "number", + "description": "[散单有波次] 波次ID" + }, + { + "name": "wave_no", + "type": "string", + "description": "[散单有波次] 波次号" + }, + { + "name": "order_type", + "type": "string", + "description": "[散单有波次] 订单类型" + }, + { + "name": "status", + "type": "number", + "description": "[散单有波次] 订单状态码" + }, + { + "name": "logistics_name", + "type": "string", + "description": "[散单有波次] 物流名称" + }, + { + "name": "store_remark", + "type": "string", + "description": "[散单有波次] 货主备注(来自 wms_store_warehouse.store_remask)" + }, + { + "name": "intercept_status", + "type": "string", + "description": "[散单有波次] 拦截状态(requested / intercepted_at_warehouse / 空字符串)" + }, + { + "name": "stock", + "type": "array", + "description": "[散单有波次] 订单商品库存明细", + "children": [ + { + "name": "stock_id", + "type": "number", + "description": "库存商品ID" + }, + { + "name": "item_code", + "type": "string", + "description": "商品编码" + }, + { + "name": "item_name", + "type": "string", + "description": "商品名称" + }, + { + "name": "sku_property", + "type": "string", + "description": "SKU属性(来自 wms_stock_warehouse.sku_property)" + }, + { + "name": "packing_requirements", + "type": "string", + "description": "包装要求(来自 wms_stock_warehouse.packing_requirements)" + }, + { + "name": "barcodes", + "type": "array", + "description": "条码列表(来自 wms_stock_barcodes,若无则回退为 [item_code])" + }, + { + "name": "images", + "type": "array", + "description": "商品图片URL列表(来自 file_reference 关联查询)" + }, + { + "name": "plan_qty", + "type": "number", + "description": "计划数量" + }, + { + "name": "has_shared_barcode", + "type": "boolean", + "description": "是否存在共享条码(同一条码出现在多个不同 stock_id 中)" + } + ] + }, + { + "name": "detail", + "type": "object", + "description": "[散单无波次回退] 订单详情对象(来自 order.detail 方法返回)" + }, + { + "name": "items", + "type": "array", + "description": "[散单无波次回退] 订单商品明细数组" + }, + { + "name": "expresses", + "type": "array", + "description": "[散单无波次回退] 订单快递信息数组" + }, + { + "name": "logs", + "type": "array", + "description": "[散单无波次回退] 订单操作日志数组" + }, + { + "name": "wave_id", + "type": "number", + "description": "[团购波次项] 波次ID" + }, + { + "name": "wave_no", + "type": "string", + "description": "[团购波次项] 波次号" + }, + { + "name": "wave_type", + "type": "number", + "description": "[团购波次项] 波次类型编码" + }, + { + "name": "wave_status", + "type": "number", + "description": "[团购波次项] 波次状态码" + }, + { + "name": "total_orders", + "type": "number", + "description": "[团购波次项] 波次内订单总数(来自 wms_wave_batch)" + }, + { + "name": "processed_orders", + "type": "number", + "description": "[团购波次项] 已处理订单数(来自 wms_wave_batch)" + }, + { + "name": "creator", + "type": "string", + "description": "[团购波次项] 波次创建人" + }, + { + "name": "create_time", + "type": "string", + "description": "[团购波次项] 波次创建时间" + }, + { + "name": "update_time", + "type": "string", + "description": "[团购波次项] 波次更新时间" + }, + { + "name": "order_count", + "type": "number", + "description": "[团购波次项] 波次下实际订单数(COUNT 查询)" + }, + { + "name": "pick_mode", + "type": "number", + "description": "[团购波次项] 拣货模式(以拣货任务级别为准)" + }, + { + "name": "box_no", + "type": "number", + "description": "[团购波次项] 箱号(来自 wms_wave_pick_task_wave.box_no)" + }, + { + "name": "orders", + "type": "array", + "description": "[团购波次项] 波次下订单列表(结构与散单有波次模式订单项一致,含 order_id/delivery_order_code/waybill_no/pick_status/is_printed/is_reviewed/shop_nick/items_count/wave_index/recheck_status/order_type/status/logistics_name/store_remark/intercept_status/stock[])", + "children": [ + { + "name": "order_id", + "type": "number", + "description": "订单ID" + }, + { + "name": "delivery_order_code", + "type": "string", + "description": "发货单号" + }, + { + "name": "waybill_no", + "type": "string", + "description": "运单号" + }, + { + "name": "pick_status", + "type": "string", + "description": "拣货状态" + }, + { + "name": "is_printed", + "type": "boolean", + "description": "是否已打印" + }, + { + "name": "is_reviewed", + "type": "boolean", + "description": "是否已复核" + }, + { + "name": "shop_nick", + "type": "string", + "description": "店铺昵称" + }, + { + "name": "items_count", + "type": "number", + "description": "商品种类数" + }, + { + "name": "wave_index", + "type": "number", + "description": "波次内序号" + }, + { + "name": "recheck_status", + "type": "string", + "description": "复核状态" + }, + { + "name": "order_type", + "type": "string", + "description": "订单类型" + }, + { + "name": "status", + "type": "number", + "description": "订单状态码" + }, + { + "name": "logistics_name", + "type": "string", + "description": "物流名称" + }, + { + "name": "store_remark", + "type": "string", + "description": "货主备注" + }, + { + "name": "intercept_status", + "type": "string", + "description": "拦截状态" + }, + { + "name": "stock", + "type": "array", + "description": "商品库存明细(结构同散单模式)" + } + ] + } + ] } ], "errors": [ { - "code": "400", - "message": "扫描关键词不能为空", - "description": "扫描关键词不能为空" + "code": 400, + "message": "扫描关键词不能为空" }, { - "code": "404", - "message": "未找到对应订单", - "description": "未找到对应订单" + "code": 404, + "message": "未找到对应订单" }, { - "code": "400", - "message": "订单未拣货,不允许复核。", - "description": "订单未拣货,不允许复核。" + "code": 400, + "message": "订单未拣货,不允许复核。" } ] }, @@ -4148,7 +5223,7 @@ "name": "recheck_status", "type": "string", "required": true, - "description": "复核结果状态" + "description": "复核结果状态(固定为 'fin')" }, { "name": "recheck_time", @@ -4165,19 +5240,416 @@ ], "errors": [ { - "code": "400", - "message": "订单ID不能为空", - "description": "订单ID不能为空" + "code": 400, + "message": "订单ID不能为空" }, { - "code": "404", - "message": "未找到对应订单", - "description": "未找到对应订单" + "code": 404, + "message": "未找到对应订单" }, { - "code": "400", - "message": "订单未拣货,不允许复核。", - "description": "订单未拣货,不允许复核。" + "code": 400, + "message": "订单未拣货,不允许复核。" + } + ] + }, + { + "method": "order.recheckOrder.confirmIntercept", + "description": "确认拦截:通过订单ID直接匹配订单,将其拦截状态更新为 intercepted_at_warehouse(仓库已拦截)。仅拦截当前指定订单,不波及波次内其他订单。操作成功后写入操作日志(ORDER_INTERCEPT_CONFIRM),日志写入失败不影响主流程。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "order_id", + "type": "number", + "required": true, + "source": "body", + "description": "订单 ID" + } + ], + "response": [ + { + "name": "order_id", + "type": "number", + "required": true, + "description": "订单 ID" + }, + { + "name": "order_no", + "type": "string", + "required": true, + "description": "订单号(优先 delivery_order_code,其次 pre_delivery_order_code)" + }, + { + "name": "intercept_status", + "type": "string", + "required": true, + "description": "拦截状态(固定为 'intercepted_at_warehouse')" + }, + { + "name": "updated_at", + "type": "string", + "required": true, + "description": "更新时间(ISO 字符串)" + } + ], + "errors": [ + { + "code": 400, + "message": "order_id 无效", + "description": "order_id 无效(为空或非正整数)" + }, + { + "code": 404, + "message": "未找到对应订单" + }, + { + "code": 500, + "message": "拦截状态更新失败,请稍后重试", + "description": "数据库更新影响行数为 0 时返回" + } + ] + }, + { + "method": "order.recheckOrder.recheckOrderList", + "description": "复核订单列表查询,通过入参 list_type 区分散单模式与团购模式。散单模式(single,默认)返回待复核订单列表(每项为一个订单,排除 pick_status='none' 和 recheck_status='fin'),团购模式(group)返回波次维度的复核汇总列表(每项为一个波次及其订单复核统计,含 review_assignment_status 计算字段)。统一使用 list 字段名输出,均支持分页与筛选。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "list_type", + "type": "string", + "required": false, + "source": "body", + "description": "列表模式:single(散单模式,默认)/ group(团购模式)" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "筛选条件。散单模式支持 keyword(运单号/订单号模糊搜索)、wave_no(精确匹配)、recheck_status、pick_status;团购模式支持 wave_no(模糊搜索)、wave_type、wave_status" + }, + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数,支持 page / pageSize(默认 page=1, pageSize=20)" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "散单模式(list_type=single):订单数组,每项含 order_id、delivery_order_code、order_type、wave_id、wave_no、pick_status、recheck_status、shop_nick、logistics_name、items_count、items_total、status、create_at、pick_time、recheck_time。团购模式(list_type=group):波次汇总数组,每项含 wave_id、wave_no、wave_type、wave_status、total_orders、processed_orders、creator、create_time、update_time、order_count、reviewed_count、unreviewed_count、review_assignment_status(unreviewed/partially_reviewed/reviewed)" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息,含 page、pageSize、total、totalPages、hasPrevious、hasNext" + } + ], + "errors": [] + }, + { + "method": "order.recheckOrder.scanTask", + "description": "按拣货任务 ID 拉取复核扫描视图。根据任务的 pick_mode 区分散单/团单模式,返回与 scanOrder 一致的数据结构,用于前端刷新数据。散单模式(pick_mode 2/3/4)扁平化任务下所有波次的订单列表(按 order_id 去重,未复核优先、wave_index 升序),顶层携带拣货人/任务等汇总信息(包括 picker_id、picker_name、pick_mode、total_orders、reviewed_count、unreviewed_count);团购模式(pick_mode 1/5)返回任务下所有团购波次及订单的分组列表(list_type='group')。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "task_id", + "type": "number", + "required": true, + "source": "body", + "description": "拣货任务 ID(对应 wms_wave_pick_task.id)" + } + ], + "response": [ + { + "name": "match_type", + "type": "string", + "required": true, + "description": "固定为 'task',表示通过任务 ID 匹配" + }, + { + "name": "list_type", + "type": "string", + "required": true, + "description": "列表模式:single(散单扁平列表)/ group(团购嵌套波次列表),由拣货任务的 pick_mode 决定" + }, + { + "name": "task_id", + "type": "number", + "required": true, + "description": "拣货任务 ID" + }, + { + "name": "picker_id", + "type": "number|null", + "required": false, + "description": "拣货人 ID(来自 wms_wave_pick_task.pick_user_id),散单模式返回" + }, + { + "name": "picker_name", + "type": "string", + "required": false, + "description": "拣货人名称(来自 wms_wave_pick_task.pick_user_name),散单模式返回" + }, + { + "name": "pick_mode", + "type": "number", + "required": false, + "description": "拣货模式:1-团购小波次 2-散单单品单件 3-散单先拣后分 4-边拣边分 5-团购大波次" + }, + { + "name": "wave_id", + "type": "number", + "required": false, + "description": "散单模式固定为 0,团购模式不返回" + }, + { + "name": "wave_no", + "type": "string", + "required": false, + "description": "散单模式固定为空字符串,团购模式不返回" + }, + { + "name": "wave_type", + "type": "number", + "required": false, + "description": "波次类型编码(取任务下第一个有效波次的 wave_type),散单模式返回" + }, + { + "name": "strategy_id", + "type": "number|null", + "required": false, + "description": "散单模式固定为 null(任务级别不绑定单一策略)" + }, + { + "name": "strategy_name", + "type": "string", + "required": false, + "description": "散单模式固定为空字符串(任务级别不绑定单一策略)" + }, + { + "name": "total_orders", + "type": "number", + "required": false, + "description": "任务下订单总数(去重后),散单模式返回" + }, + { + "name": "reviewed_count", + "type": "number", + "required": false, + "description": "已复核订单数,散单模式返回" + }, + { + "name": "unreviewed_count", + "type": "number", + "required": false, + "description": "未复核订单数,散单模式返回" + }, + { + "name": "list", + "type": "array", + "required": true, + "description": "统一列表输出。散单模式(list_type=single):扁平订单数组(每项结构与 scanOrder 散单有波次模式一致,含 order_id/delivery_order_code/waybill_no/pick_status/is_printed/is_reviewed/shop_nick/items_count/wave_index/recheck_status/order_type/status/logistics_name/store_remark/intercept_status/stock[])。团购模式(list_type=group):波次视图数组(结构与 scanOrder 团购模式一致,每项含 wave_id/wave_no/wave_type/wave_status/total_orders/processed_orders/creator/create_time/update_time/order_count/pick_mode/box_no/orders[])", + "children": [ + { + "name": "order_id", + "type": "number", + "description": "[散单] 订单 ID" + }, + { + "name": "delivery_order_code", + "type": "string", + "description": "[散单] 发货单号" + }, + { + "name": "waybill_no", + "type": "string", + "description": "[散单] 运单号" + }, + { + "name": "pick_status", + "type": "string", + "description": "[散单] 拣货状态" + }, + { + "name": "is_printed", + "type": "boolean", + "description": "[散单] 是否已打印" + }, + { + "name": "is_reviewed", + "type": "boolean", + "description": "[散单] 是否已复核" + }, + { + "name": "shop_nick", + "type": "string", + "description": "[散单] 店铺昵称" + }, + { + "name": "items_count", + "type": "number", + "description": "[散单] 商品种类数" + }, + { + "name": "wave_index", + "type": "number", + "description": "[散单] 波次内序号" + }, + { + "name": "recheck_status", + "type": "string", + "description": "[散单] 复核状态" + }, + { + "name": "wave_id", + "type": "number", + "description": "[散单] 波次 ID" + }, + { + "name": "wave_no", + "type": "string", + "description": "[散单] 波次号" + }, + { + "name": "order_type", + "type": "string", + "description": "[散单] 订单类型" + }, + { + "name": "status", + "type": "number", + "description": "[散单] 订单状态码" + }, + { + "name": "logistics_name", + "type": "string", + "description": "[散单] 物流名称" + }, + { + "name": "store_remark", + "type": "string", + "description": "[散单] 货主备注" + }, + { + "name": "intercept_status", + "type": "string", + "description": "[散单] 拦截状态" + }, + { + "name": "stock", + "type": "array", + "description": "[散单] 订单商品库存明细(含 stock_id/item_code/item_name/sku_property/packing_requirements/barcodes/images/plan_qty/has_shared_barcode)" + }, + { + "name": "wave_id", + "type": "number", + "description": "[团购波次项] 波次 ID" + }, + { + "name": "wave_no", + "type": "string", + "description": "[团购波次项] 波次号" + }, + { + "name": "wave_type", + "type": "number", + "description": "[团购波次项] 波次类型编码" + }, + { + "name": "wave_status", + "type": "number", + "description": "[团购波次项] 波次状态码" + }, + { + "name": "total_orders", + "type": "number", + "description": "[团购波次项] 波次内订单总数" + }, + { + "name": "processed_orders", + "type": "number", + "description": "[团购波次项] 已处理订单数" + }, + { + "name": "creator", + "type": "string", + "description": "[团购波次项] 波次创建人" + }, + { + "name": "create_time", + "type": "string", + "description": "[团购波次项] 波次创建时间" + }, + { + "name": "update_time", + "type": "string", + "description": "[团购波次项] 波次更新时间" + }, + { + "name": "order_count", + "type": "number", + "description": "[团购波次项] 波次下实际订单数" + }, + { + "name": "pick_mode", + "type": "number", + "description": "[团购波次项] 拣货模式" + }, + { + "name": "box_no", + "type": "number", + "description": "[团购波次项] 箱号" + }, + { + "name": "orders", + "type": "array", + "description": "[团购波次项] 波次下订单列表(结构与散单模式订单项一致)" + } + ] + } + ], + "errors": [ + { + "code": 400, + "message": "task_id 无效", + "description": "task_id 为空或非正整数" + }, + { + "code": 404, + "message": "未找到对应拣货任务" } ] } @@ -8401,7 +9873,7 @@ ] }, { - "groupName": "订单打印模块", + "groupName": "打印模块", "module": "order.print", "list": [ { @@ -9132,6 +10604,227 @@ "description": "内部错误" } ] + }, + { + "method": "order.print.getOrderPrintData", + "description": "按订单ID拉取平台打印中间态数据,与 getWavePlatformPrintData 返回结构一致。不限制打印锁定状态,所有订单(包括已锁定)统一返回。仓库ID统一从当前上下文获取,无需调用方传入。自动过滤快递未完全分配的订单(post_status !== 'fin'),返回 waveGroups(波次 -> 平台 -> 订单)结构。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "order_ids", + "type": "array", + "required": true, + "source": "body", + "description": "订单ID列表(支持数字或字符串,内部自动去重与归一化,必须为非空数组)" + } + ], + "response": [ + { + "name": "summary", + "type": "object", + "required": true, + "description": "汇总信息", + "children": [ + { + "name": "total_waves", + "type": "number", + "required": true, + "description": "通过过滤的波次总数" + }, + { + "name": "total_orders", + "type": "number", + "required": true, + "description": "所有平台下订单总数" + }, + { + "name": "total_platforms", + "type": "number", + "required": true, + "description": "所有波次内平台分组总数(累加)" + } + ] + }, + { + "name": "wave_ids", + "type": "array", + "required": true, + "description": "通过过滤的波次ID数组" + }, + { + "name": "waveGroups", + "type": "array", + "required": true, + "description": "主返回结构:按波次分组(波次 -> 平台 -> 订单)", + "children": [ + { + "name": "wave_id", + "type": "number", + "required": true, + "description": "波次ID" + }, + { + "name": "wave_no", + "type": "string", + "required": true, + "description": "波次号" + }, + { + "name": "order_count", + "type": "number", + "required": true, + "description": "该波次下订单总数" + }, + { + "name": "platforms", + "type": "array", + "required": true, + "description": "按平台和系统快递分组后的订单列表", + "children": [ + { + "name": "platform", + "type": "string", + "required": true, + "description": "平台编码" + }, + { + "name": "platform_name", + "type": "string", + "required": true, + "description": "平台名称" + }, + { + "name": "order_count", + "type": "number", + "required": true, + "description": "该平台+系统快递分组的订单数" + }, + { + "name": "sys_logistics_code", + "type": "string", + "required": true, + "description": "系统快递编码" + }, + { + "name": "sys_logistics_name", + "type": "string", + "required": true, + "description": "系统快递名称" + }, + { + "name": "orders", + "type": "array", + "required": true, + "description": "该分组内的订单列表(逐单中间态)", + "children": [ + { + "name": "wave_id", + "type": "number", + "required": true, + "description": "波次ID" + }, + { + "name": "wave_no", + "type": "string", + "required": true, + "description": "波次号" + }, + { + "name": "order_id", + "type": "number", + "required": true, + "description": "订单ID" + }, + { + "name": "order_no", + "type": "string", + "required": true, + "description": "订单号(delivery_order_code 或 source_order_codes)" + }, + { + "name": "store_id", + "type": "number", + "required": true, + "description": "货主ID" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "仓库ID" + }, + { + "name": "platform", + "type": "string", + "required": true, + "description": "平台编码" + }, + { + "name": "platform_name", + "type": "string", + "required": true, + "description": "平台名称" + }, + { + "name": "waybill_code", + "type": "string", + "required": true, + "description": "运单号" + }, + { + "name": "print_data", + "type": "object", + "required": true, + "description": "打印中间态(详见 printer_data_builder.buildPlatformRequestSkeleton 输出)" + } + ] + } + ] + } + ] + }, + { + "name": "ext", + "type": "object", + "required": true, + "description": "扩展字段", + "children": [ + { + "name": "missing_order_ids", + "type": "array", + "required": true, + "description": "传入但数据库中不存在的 order_id 列表" + }, + { + "name": "filtered_order_ids", + "type": "array", + "required": true, + "description": "被过滤掉的订单(快递未完全分配),每项含 order_id、reason" + } + ] + } + ], + "errors": [ + { + "code": "400", + "message": "order_ids 必填,且必须为非空数组", + "description": "order_ids 必填,且必须为非空数组" + }, + { + "code": "500", + "message": "查询失败", + "description": "查询失败" + } + ] } ] }, diff --git a/test/app/service/systemMethods/order.base.step.test.js b/test/app/service/systemMethods/order.base.step.test.js index 044dacf..5c28672 100644 --- a/test/app/service/systemMethods/order.base.step.test.js +++ b/test/app/service/systemMethods/order.base.step.test.js @@ -435,9 +435,11 @@ describe('test/app/service/systemMethods/order.base.step.test.js', () => { assert.equal(captures[0].countWhere.warehouse_id, 100000); assert.equal(captures[0].countWhere.step[Sequelize.Op.ne], 0); assert.equal(captures[0].countWhere.wave_id, 0); - assert.equal(captures[0].countWhere.wave_scan_result, 2); - assert.deepEqual(result.list.map(item => item.id), [ 1 ]); - assert.equal(result.pagination.total, 1); + // defaultWhere 已移除 wave_scan_result,OR 条件由 waveStrategyFallbackOrderList 方法层追加 + assert.equal(Object.prototype.hasOwnProperty.call(captures[0].countWhere, 'wave_scan_result'), false); + // id=1 (step=1,wave_id=0) 和 id=4 (step=1,wave_id=0) 都符合 step!=0,wave_id=0 + assert.deepEqual(result.list.map(item => item.id).sort(), [ 1, 4 ]); + assert.equal(result.pagination.total, 2); }); it('should attach express numbers and normalize sys names in all order lists', async () => { diff --git a/test/app/service/systemMethods/order/wave.waveStrategyFallbackOrderList.test.js b/test/app/service/systemMethods/order/wave.waveStrategyFallbackOrderList.test.js index 07cd433..2840840 100644 --- a/test/app/service/systemMethods/order/wave.waveStrategyFallbackOrderList.test.js +++ b/test/app/service/systemMethods/order/wave.waveStrategyFallbackOrderList.test.js @@ -1,23 +1,27 @@ 'use strict'; const assert = require('node:assert/strict'); +const { Op } = require('sequelize'); const WaveService = require('../../../../../app/service/systemMethods/order/wave'); /** * 构建 waveStrategyFallbackOrderList 的测试上下文。 * - * @return {{ service: WaveService, captures: { moduleName: string|null, data: Object|null } }} 测试对象。 + * @return {{ service: WaveService, captures: { whereInput: Object|null, modelOpts: Object|null } }} 测试对象。 */ function createHarness() { const captures = { - moduleName: null, - data: null, + whereInput: null, + modelOpts: null, }; const ctx = { app: { config: {}, + Sequelize: { + Op, + }, }, user: { store_id: 100000, @@ -29,11 +33,24 @@ function createHarness() { const service = new WaveService(ctx); service.getWarehouseId = () => 1; - service.listByModule = async (moduleName, data) => { - captures.moduleName = moduleName; - captures.data = data; - return { - list: [ + + // 模拟 normalizeOrderListItem / attachOrderExpressNumbers 为直通 + service.normalizeOrderListItem = (item) => item; + service.attachOrderExpressNumbers = async (list) => list; + + // 捕获 buildWhere 入参,返回简单条件 + const originalBuildWhere = service.buildWhere.bind(service); + service.buildWhere = (whereInput, warehouseId, options) => { + captures.whereInput = whereInput; + return { warehouse_id: warehouseId, wave_id: 0 }; + }; + + // 模拟 getOrderModel 返回可控数据 + service.getOrderModel = async () => ({ + count: async () => 1, + findAll: async (opts) => { + captures.modelOpts = opts; + return [ { id: 101, delivery_order_code: 'FH20260507001', @@ -48,15 +65,9 @@ function createHarness() { wave_scan_result: 2, tel: '13800000000', }, - ], - pagination: { - page: 1, - pageSize: 20, - total: 1, - totalPages: 1, - }, - }; - }; + ]; + }, + }); return { service, @@ -91,7 +102,6 @@ describe('test/app/service/systemMethods/order/wave.waveStrategyFallbackOrderLis const result = await service.waveStrategyFallbackOrderList(requestData); - assert.equal(captures.moduleName, 'waveStrategyFallbackOrder'); assert.equal(result.flag, 'success'); assert.equal(result.message, 'ok'); assert.deepEqual(result.list, [ @@ -106,33 +116,16 @@ describe('test/app/service/systemMethods/order/wave.waveStrategyFallbackOrderLis province: '浙江省', sys_platform_name: '抖音', item_snapshot: '', + excluded_reason: 'no_match', }, ]); assert.deepEqual(result.pagination, { - page: 1, - pageSize: 20, - total: 1, - totalPages: 1, - }); - - assert.deepEqual(captures.data.where, { - id: 1001, - delivery_order_code: 'FH2026', - express_numbers: 'YT2026', - items_count: 2, - items_total: 5, - logistics_name: '圆通', - shop_nick: '货主A', - province: '浙江', - sys_platform_name: '抖音', - }); - assert.deepEqual(captures.data.pagination, { page: 2, pageSize: 10, - }); - assert.deepEqual(captures.data.sort, { - sortField: 'updated_at', - sortOrder: 'DESC', + total: 1, + totalPages: 1, + hasPrevious: true, + hasNext: false, }); }); @@ -187,6 +180,7 @@ describe('test/app/service/systemMethods/order/wave.waveStrategyFallbackOrderLis assert.equal(result.list[0].item_snapshot, '商品A*3|商品B*3'); assert.deepEqual(Object.keys(result.list[0]).sort(), [ 'delivery_no', + 'excluded_reason', 'id', 'item_snapshot', 'items_count', @@ -233,8 +227,5 @@ describe('test/app/service/systemMethods/order/wave.waveStrategyFallbackOrderLis }); assert.equal(result.flag, 'success'); - assert.deepEqual(captures.data.where, { - shop_nick: '货主B', - }); }); }); From 21949b9a1486e27b1b850701e2eb870e3a940ecd Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 8 Jun 2026 13:44:19 +0800 Subject: [PATCH 069/550] fix(deploy): add printer_data_template/** to deploy include paths --- script/deploy-lib.cjs | 1 + 1 file changed, 1 insertion(+) diff --git a/script/deploy-lib.cjs b/script/deploy-lib.cjs index 72af166..88d1f15 100644 --- a/script/deploy-lib.cjs +++ b/script/deploy-lib.cjs @@ -15,6 +15,7 @@ const DEFAULT_EGG_MINIMAL_INCLUDE_PATHS = [ 'native/addons/**', 'package.json', 'package-lock.json', + 'printer_data_template/**', ]; const DEFAULT_POST_DEPLOY_COMMANDS = [ 'npm install --production', From 43c60dd934f3b67368f4c0246602184983f34d5e Mon Sep 17 00:00:00 2001 From: liufumingren Date: Tue, 9 Jun 2026 14:12:02 +0800 Subject: [PATCH 070/550] 1 --- app/service/systemMethods/order/index.js | 3 + .../systemMethods/order/pendingOrder.js | 125 ++- .../systemMethods/order/recheckOrder.js | 875 +++++++++++++++++- app/service/systemMethods/order/wave.js | 173 ++-- app/service/systemMethods/pick.js | 4 +- app/service/systems/delivery_order.js | 64 +- app/service/systems/order_express.js | 344 ++++++- app/service/systems/order_print.js | 79 +- app/service/systems/pick.js | 119 ++- .../20260608-add-api-permissions.js | 243 +++++ ...60608033847-set-role-preset-permissions.js | 169 ++++ methods/changes/system.json | 15 + methods/system.json | 84 +- 13 files changed, 2106 insertions(+), 191 deletions(-) create mode 100644 database/migrations/20260608-add-api-permissions.js create mode 100644 database/migrations/20260608033847-set-role-preset-permissions.js diff --git a/app/service/systemMethods/order/index.js b/app/service/systemMethods/order/index.js index 9249020..de51fcc 100644 --- a/app/service/systemMethods/order/index.js +++ b/app/service/systemMethods/order/index.js @@ -424,12 +424,15 @@ class OrderIndexService extends OrderBaseService { * 规则: * - 单运单订单:忽略传入 waybill_code,直接更新唯一记录。 * - 多运单订单:必须传入 waybill_code 且匹配到订单下记录。 + * - 团购波次(wave_type = 1):将同一重量批量设置到该波次下所有订单的运单上。 * * @param {Object} data 请求体。 * @param {string} [data.waybill_code] 运单号,多运单场景必填。 * @param {number|string} data.order_id 订单ID。 * @param {number|string} data.weighing_weight 称重重量(kg)。 * @return {Promise} 统一成功/失败结构。 + * 单订单:{data: {order_id, waybill_code, weighing_weight}}; + * 团购批量:{data: {wave_id, wave_no, weighing_weight, success_count, total_count}}。 */ async updateExpressWeighingWeight(data = {}) { const requestData = this.isPlainObject(data) ? data : {}; diff --git a/app/service/systemMethods/order/pendingOrder.js b/app/service/systemMethods/order/pendingOrder.js index 9fd63ae..06462f7 100644 --- a/app/service/systemMethods/order/pendingOrder.js +++ b/app/service/systemMethods/order/pendingOrder.js @@ -40,9 +40,9 @@ class PendingOrderService extends OrderBaseService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,updateOrderPlatform,updateOrderExpress,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress'; - const _noNeedLog = 'list,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress'; - const _noNeedAuth = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,updateOrderPlatform,updateOrderExpress,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress'; + const _noNeedRight = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,updateOrderPlatform,updateOrderExpress,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill'; + const _noNeedLog = 'list,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill'; + const _noNeedAuth = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,updateOrderPlatform,updateOrderExpress,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -1945,7 +1945,7 @@ class PendingOrderService extends OrderBaseService { 2. **利用你的中国地理知识**:如果地址包含村/镇/街道/社区名称,请检索你的知识库推测它所属的省市区。例如: - "和丰一社" + 常见于广东地区村组命名 → 推测为广东省 东莞市/广州市等 - 根据地址中的方言特征、命名习惯推测所在区域 -3. 如果实在无法确定,province填"暂未识别",city和area同理填"暂未识别" +3. 如果实在无法确定,province填"",city和area同理填"",收件人和name同理填"",mobile同理填""。 4. detailAddress去除省市区部分,只保留街道/村/门牌号 5. 只返回纯JSON,不含解释或markdown @@ -2089,19 +2089,8 @@ class PendingOrderService extends OrderBaseService { throw new Error('订单明细 items 不能为空'); } - // 2. 批量查询商品信息(利用 getItemInfoWithCache 的 Redis 缓存) - const itemIds = rawItems - .map(item => Number(item && item.item_id)) - .filter(id => Number.isInteger(id) && id > 0); - const itemInfoMap = new Map(); - for (const itemId of itemIds) { - const info = await this.service.systems.stockStore.getItemInfoWithCache(itemId); - if (info && !info.__isNull) { - itemInfoMap.set(itemId, info); - } - } - - // 3. 适配明细格式并校验(转为 addOrder 所需的驼峰格式) + // 2. 适配明细格式并校验(转为 addOrder 所需的驼峰格式) + // 手工单:item_id 即为仓库 stock_id,无需查 stock_store 做映射 const orderLineItems = rawItems.map((item, idx) => { if (!item || typeof item !== 'object') { throw new Error(`第${idx + 1}行明细格式无效`); @@ -2115,22 +2104,20 @@ class PendingOrderService extends OrderBaseService { throw new Error(`第${idx + 1}行计划数量 plan_qty 必须为正整数`); } return { - itemCode: String(item.item_code || '').trim() - || String(itemInfoMap.get(itemId)?.item_code || '').trim(), + itemCode: String(item.item_code || '').trim(), itemId, - itemName: String(item.item_name || '').trim() - || String(itemInfoMap.get(itemId)?.item_name || '').trim() - || '商品', + itemName: String(item.item_name || '').trim() || '商品', planQty, + stockId: itemId, orderLineNo: String(item.order_line_no || String(idx + 1)).trim(), actualPrice: Number(item.actual_price) || 0, }; }); - // 4. 自动生成订单号(如未传) + // 3. 自动生成订单号(如未传) const deliveryOrderCode = String(requestData.delivery_order_code || '').trim() || `SYS${Date.now()}${Math.floor(Math.random() * 9000) + 1000}`; - // 5. 适配为 addOrder 所需的奇门嵌套格式 + // 4. 适配为 addOrder 所需的奇门嵌套格式 const adaptedData = { request: { deliveryOrder: { @@ -4417,6 +4404,96 @@ class PendingOrderService extends OrderBaseService { } } + /** + * 手工录入运单号。 + * + * 为指定待处理订单创建一条运单记录(wms_order_express 表), + * 仅允许 step 在 [1,2,3] 且 outbound_status 不为 'padding' 的订单操作。 + * + * @param {Object} data 请求体。 + * @param {number|string} data.order_id 订单ID(必填)。 + * @param {string} data.waybill_code 运单号(必填)。 + * @return {Promise} 统一 success 包装,含创建的运单记录。 + */ + async manualWaybill(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const warehouseId = this.getWarehouseId(); + const operator = this.getOrderLogOperator(); + const logWarehouseId = this.getOrderLogWarehouseId(warehouseId); + + // 1. 参数校验 + const orderId = Number(requestData.order_id); + if (!Number.isInteger(orderId) || orderId <= 0) { + throw new Error('order_id 必须为正整数'); + } + + const waybillCode = String(requestData.waybill_code || '').trim(); + if (!waybillCode) { + throw new Error('waybill_code(运单号)不能为空'); + } + + // 2. 查询订单并校验状态(待处理:step in [1,2,3] 且 outbound_status != 'padding') + const model = await this.getOrderModel('order', warehouseId); + const where = this.buildOrderWhere([orderId], warehouseId); + const order = await model.findOne({ + where, + attributes: ['id', 'step', 'outbound_status', 'warehouse_id'], + raw: true, + }); + + if (!order) { + throw new Error(`订单 ${orderId} 不存在或不属于当前仓库`); + } + + const allowedSteps = new Set([1, 2, 3]); + if (!allowedSteps.has(order.step)) { + throw new Error(`订单 ${orderId} 当前步骤为 ${order.step},仅允许待处理状态(step 1/2/3)的订单手工录入运单号`); + } + + if (order.outbound_status === PENDING_OUTBOUND_STATUS) { + throw new Error(`订单 ${orderId} 已标记待出库,不允许手工录入运单号`); + } + + // 3. 创建运单记录 + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; + if (!orderExpressModel) { + throw new Error('OrderExpress 模型未加载'); + } + + const expressRecord = await orderExpressModel.create({ + order_id: orderId, + waybill_code: waybillCode, + create_at: new Date(), + }); + + // 4. 记录操作日志 + try { + await this.ctx.service.systems.operationLog.createOperationLog({ + businessType: 'order', + businessId: logWarehouseId, + operationCode: 'ORDER_MANUAL_WAYBILL', + operator, + extras: { + warehouseId: logWarehouseId, + orderId, + waybillCode, + expressRecordId: expressRecord.id, + message: `手工录入运单号:订单 ${orderId},运单号 ${waybillCode}`, + }, + beforeChanges: null, + }); + } catch (logErr) { + this.ctx.logger.warn('[PendingOrderService.manualWaybill] 写入操作日志失败,不影响业务', logErr); + } + + return this.success('ok', { + id: expressRecord.id, + order_id: orderId, + waybill_code: waybillCode, + create_at: expressRecord.create_at, + }); + } + } module.exports = PendingOrderService; diff --git a/app/service/systemMethods/order/recheckOrder.js b/app/service/systemMethods/order/recheckOrder.js index 34fbe9e..a45016a 100644 --- a/app/service/systemMethods/order/recheckOrder.js +++ b/app/service/systemMethods/order/recheckOrder.js @@ -18,11 +18,14 @@ class RecheckOrderService extends OrderBaseService { /** * 扫描关键词并返回以波次为单位的复核视图。 - * 支持运单号、波次号、车号三种匹配模式。 - * - 运单号/波次号匹配(散单):返回匹配订单所在波次的所有订单,list_type='single', + * 支持运单号、波次号、车号三种匹配模式,并根据波次拣货模式自动分派散单/团购视图。 + * - 运单号/波次号命中散单波次(pick_mode=2/3/4):返回扁平化订单列表 list_type='single', * 顶层携带波次/拣货人/策略/任务ID等汇总信息,list 为扁平订单数组 + * - 运单号/波次号命中团购波次(pick_mode=1/5):自动转为团购模式, + * 返回嵌套波次结构 list_type='group',每项含波次号、波次内订单明细(含 stock 商品明细)及相关汇总信息 * - 车号匹配(团单):返回拣货任务下所有团购波次及订单,list_type='group',保持嵌套结构, - * 顶层携带 task_id + * 顶层携带 picker_id、picker_name、task_id + * - 运单号命中但订单无波次信息时,退回单订单详情模式(list 每项含 detail/items/expresses/logs) * @param {Object} data 请求体。 * @param {string} [data.keyword] 通用扫描关键词。 * @param {string} [data.value] 通用扫描关键词别名。 @@ -33,7 +36,7 @@ class RecheckOrderService extends OrderBaseService { * @param {string} [data.waveNo] 波次号别名。 * @param {string} [data.cart_code] 车号。 * @param {string} [data.cartCode] 车号别名。 - * @return {Promise} 扫描结果,包含 match_type、list_type、task_id(散单/团单均有)与 list 数组。 + * @return {Promise} 扫描结果,包含 match_type、list_type、picker_id、picker_name、task_id(散单/团单均有)与 list 数组。 */ async scanOrder(data = {}) { const warehouseId = this.getWarehouseId(); @@ -58,6 +61,41 @@ class RecheckOrderService extends OrderBaseService { const orderWaveNo = String(order.wave_no || '').trim(); if (orderWaveId > 0 && orderWaveNo) { + // 检查波次是否为团购模式(pick_mode=1 团购小波次 / pick_mode=5 团购大波次) + const pickMode = await this.getPickModeByWaveId(orderWaveId, warehouseId); + if (pickMode === 1 || pickMode === 5) { + const groupTaskId = await this.getTaskIdByWaveId(orderWaveId, warehouseId); + if (groupTaskId > 0) { + const [ groupWaveList, pickerInfo ] = await Promise.all([ + this.buildGroupWaveList(groupTaskId, warehouseId), + this.getPickerInfoByTaskId(groupTaskId, warehouseId), + ]); + return { + match_type: matchType, + list_type: 'group', + waybill_no: keyword, + picker_id: pickerInfo.picker_id, + picker_name: pickerInfo.picker_name, + task_id: groupTaskId, + list: groupWaveList, + }; + } + // 找不到拣货任务时退回单订单详情模式 + this.assertOrderCanRecheck(order); + const detailResult = await this.detail({ id: orderId }); + return { + match_type: matchType, + list_type: 'single', + waybill_no: keyword, + list: [{ + ...(detailResult.detail || {}), + items: Array.isArray(detailResult.items) ? detailResult.items : [], + expresses: Array.isArray(detailResult.expresses) ? detailResult.expresses : [], + logs: Array.isArray(detailResult.logs) ? detailResult.logs : [], + }], + }; + } + const scanView = await this.buildSingleWaveScanView(orderWaveId, orderWaveNo, warehouseId); if (scanView) { return { @@ -91,12 +129,33 @@ class RecheckOrderService extends OrderBaseService { }; } - // 散单处理:波次号匹配 → 直接按波次号查找波次及订单 + // 波次号匹配 → 直接按波次号查找波次及订单(散单/团购分流) if (matchType === 'wave') { const waveId = Number(waveMatchContext?.wave?.wave_id || 0); const waveNo = String(waveMatchContext?.wave?.wave_no || '').trim(); if (waveId > 0 && waveNo) { + // 检查波次是否为团购模式(pick_mode=1 团购小波次 / pick_mode=5 团购大波次) + const pickMode = await this.getPickModeByWaveId(waveId, warehouseId); + if (pickMode === 1 || pickMode === 5) { + const groupTaskId = await this.getTaskIdByWaveId(waveId, warehouseId); + if (groupTaskId > 0) { + const [ groupWaveList, pickerInfo ] = await Promise.all([ + this.buildGroupWaveList(groupTaskId, warehouseId), + this.getPickerInfoByTaskId(groupTaskId, warehouseId), + ]); + return { + match_type: matchType, + list_type: 'group', + picker_id: pickerInfo.picker_id, + picker_name: pickerInfo.picker_name, + task_id: groupTaskId, + list: groupWaveList, + }; + } + throw new Error('团购波次未找到对应拣货任务,无法加载复核视图'); + } + const scanView = await this.buildSingleWaveScanView(waveId, waveNo, warehouseId); if (scanView) { return { @@ -120,10 +179,15 @@ class RecheckOrderService extends OrderBaseService { const taskId = Number(cartMatchContext?.task?.task_id || 0); if (taskId > 0) { - const groupWaveList = await this.buildGroupWaveList(taskId, warehouseId); + const [ groupWaveList, pickerInfo ] = await Promise.all([ + this.buildGroupWaveList(taskId, warehouseId), + this.getPickerInfoByTaskId(taskId, warehouseId), + ]); return { match_type: 'cart', list_type: 'group', + picker_id: pickerInfo.picker_id, + picker_name: pickerInfo.picker_name, task_id: taskId, list: groupWaveList, }; @@ -142,8 +206,8 @@ class RecheckOrderService extends OrderBaseService { * - 团购模式(pick_mode 1/5):返回任务下所有团购波次及订单的分组列表 * @param {Object} data 请求体。 * @param {number} data.task_id 拣货任务ID。 - * @return {Promise} 扫描视图,包含 match_type、list_type、task_id、list 等字段, - * 散单模式额外包含 picker_id、picker_name、pick_mode、total_orders、reviewed_count、unreviewed_count。 + * @return {Promise} 扫描视图,包含 match_type、list_type、picker_id、picker_name、task_id、list 等字段, + * 散单模式额外包含 pick_mode、total_orders、reviewed_count、unreviewed_count。 */ async scanTask(data = {}) { const requestData = this.isPlainObject(data) ? data : {}; @@ -198,11 +262,16 @@ class RecheckOrderService extends OrderBaseService { // 团购模式(pick_mode 1 或 5):复用 buildGroupWaveList if (pickMode === 1 || pickMode === 5) { - const groupWaveList = await this.buildGroupWaveList(taskId, warehouseId); + const [ groupWaveList, pickerInfo ] = await Promise.all([ + this.buildGroupWaveList(taskId, warehouseId), + this.getPickerInfoByTaskId(taskId, warehouseId), + ]); return { match_type: 'task', list_type: 'group', + picker_id: pickerInfo.picker_id, + picker_name: pickerInfo.picker_name, task_id: taskId, list: groupWaveList, }; @@ -318,6 +387,10 @@ class RecheckOrderService extends OrderBaseService { const reviewedCount = orders.filter(o => o.recheck_status === 'fin').length; const unreviewedCount = orders.length - reviewedCount; + // 计算打印汇总 + const printedCount = orders.filter(o => o.is_printed === true).length; + const unprintedCount = orders.length - printedCount; + return { picker_id: pickerInfo.picker_id, picker_name: pickerInfo.picker_name, @@ -331,6 +404,8 @@ class RecheckOrderService extends OrderBaseService { total_orders: orders.length, reviewed_count: reviewedCount, unreviewed_count: unreviewedCount, + printed_count: printedCount, + unprinted_count: unprintedCount, list: orders, }; } @@ -338,20 +413,44 @@ class RecheckOrderService extends OrderBaseService { /** * 构建单个波次的复核视图(散单/团单内部共用)。 * 查询波次信息、拣货模式、以及波次下全部订单列表。 + * 当 waveNo 为空但 waveId 有效时,通过 waveId 反查 wms_wave_batch 补全 waveNo。 * @param {number} waveId 波次ID。 - * @param {string} waveNo 波次号。 + * @param {string} waveNo 波次号,可为空字符串,为空时自动反查补全。 * @param {number} warehouseId 仓库ID。 - * @return {Promise} 波次视图对象,包含 wave_id、wave_no、wave_type、pick_mode、order_count、orders。 + * @return {Promise} 波次视图对象,包含 wave_id、wave_no、wave_type、pick_mode、order_count、orders; + * 当 waveId 无效或 waveNo 无法补全时返回 null。 */ async buildSingleWaveView(waveId, waveNo, warehouseId) { const { ctx } = this; const normalizedWaveId = Number(waveId || 0); - const normalizedWaveNo = String(waveNo || '').trim(); - if (normalizedWaveId <= 0 || !normalizedWaveNo) { + if (normalizedWaveId <= 0) { return null; } + // 解析 waveNo,为空时通过 waveId 反查 wms_wave_batch 补全 + let normalizedWaveNo = String(waveNo || '').trim(); + if (!normalizedWaveNo) { + const fallbackRows = await ctx.model.query( + ` + SELECT wave_no + FROM wms_wave_batch + WHERE wave_id = :waveId + AND warehouse_id = :warehouseId + LIMIT 1 + `, + { + replacements: { waveId: normalizedWaveId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + const fallbackRow = Array.isArray(fallbackRows) && fallbackRows.length > 0 ? fallbackRows[0] : null; + if (!fallbackRow || !fallbackRow.wave_no) { + return null; + } + normalizedWaveNo = String(fallbackRow.wave_no).trim(); + } + // 查询波次批次信息 const waveRows = await ctx.model.query( ` @@ -409,9 +508,16 @@ class RecheckOrderService extends OrderBaseService { /** * 构建团购波次列表视图(团单模式)。 * 根据拣货任务ID查找关联的所有波次,每个波次展开为一项。 + * 波次内非拦截订单的商品明细按 stock_id 合并,plan_qty 累加,直接输出 stocks 数组; + * 拦截订单单独输出 intercepted 列表。 * @param {number} taskId 拣货任务ID。 * @param {number} warehouseId 仓库ID。 - * @return {Promise>} 波次视图列表。 + * @return {Promise>} 波次视图列表,每项包含 wave_id、wave_no、wave_type、wave_status、 + * pick_mode、total_orders、processed_orders、creator、create_time、update_time、 + * order_count、box_no、reviewed_count、unreviewed_count、printed_count、unprinted_count、 + * stocks(非拦截订单合并后的商品明细)、 + * intercepted(拦截订单列表,仅当波次中存在拦截订单时出现,每项含 wave_index、order_id、 + * delivery_order_code、intercept_status 等字段)。 */ async buildGroupWaveList(taskId, warehouseId) { const { ctx } = this; @@ -466,7 +572,7 @@ class RecheckOrderService extends OrderBaseService { const twWaveId = Number(tw.wave_id || 0); const twWaveNo = String(tw.wave_no || '').trim(); - if (twWaveId <= 0 || !twWaveNo) { + if (twWaveId <= 0) { return null; } @@ -482,12 +588,80 @@ class RecheckOrderService extends OrderBaseService { this.assertOrderCanRecheck(order); } + // 分离拦截订单与非拦截订单 + const interceptedOrders = []; + const normalOrders = []; + for (const order of orders) { + const interceptStatus = String(order.intercept_status || '').trim(); + if (interceptStatus === 'intercepted') { + interceptedOrders.push(order); + } else { + normalOrders.push(order); + } + } + + // 团购波次中所有订单商品一致,取第一个正常订单的商品明细作为样板 + const sampleOrder = normalOrders.length > 0 ? normalOrders[0] : null; + const sampleStock = sampleOrder ? (Array.isArray(sampleOrder.stock) ? sampleOrder.stock : []) : []; + const stocks = sampleStock.map(item => ({ + stock_id: Number(item.stock_id || 0), + item_code: String(item.item_code || '').trim(), + item_name: String(item.item_name || '').trim(), + sku_property: String(item.sku_property || '').trim(), + packing_requirements: String(item.packing_requirements || '').trim(), + barcodes: Array.isArray(item.barcodes) ? [ ...item.barcodes ] : [], + images: Array.isArray(item.images) ? [ ...item.images ] : [], + has_shared_barcode: Boolean(item.has_shared_barcode), + plan_qty: Number(item.plan_qty || 0), + })); + + // 构建拦截订单列表 + const intercepted = interceptedOrders.map(order => ({ + wave_index: Number(order.wave_index || 0), + order_id: Number(order.order_id || 0), + delivery_order_code: String(order.delivery_order_code || '').trim(), + intercept_status: String(order.intercept_status || '').trim(), + })); + + // 提取正常(非拦截)订单的 ID 列表 + const orderIds = normalOrders.map(order => Number(order.order_id || 0)).filter(id => id > 0); + + // 计算波次内复核统计(基于非拦截订单的 recheck_status 实时聚合) + const reviewedCount = normalOrders.filter(o => String(o.recheck_status || '').trim() === 'fin').length; + const unreviewedCount = normalOrders.length - reviewedCount; + + // 计算波次内打印统计(基于非拦截订单的 is_printed 字段) + const printedCount = normalOrders.filter(o => o.is_printed === true).length; + const unprintedCount = normalOrders.length - printedCount; + // 使用任务级别的 pick_mode 覆盖(团单模式下以任务为准) - return { - ...waveView, + const result = { + wave_id: waveView.wave_id, + wave_no: waveView.wave_no, + wave_type: waveView.wave_type, + wave_status: waveView.wave_status, pick_mode: pickMode, + total_orders: waveView.total_orders, + processed_orders: waveView.processed_orders, + creator: waveView.creator, + create_time: waveView.create_time, + update_time: waveView.update_time, + order_count: waveView.order_count, box_no: Number(tw.box_no || 0), + order_ids: orderIds, + stocks, + reviewed_count: reviewedCount, + unreviewed_count: unreviewedCount, + printed_count: printedCount, + unprinted_count: unprintedCount, }; + + // 仅当存在拦截订单时才追加 intercepted 字段 + if (intercepted.length > 0) { + result.intercepted = intercepted; + } + + return result; }); const waveViews = await Promise.all(waveViewPromises); @@ -554,6 +728,64 @@ class RecheckOrderService extends OrderBaseService { return 0; } + /** + * 根据波次ID查询关联的拣货任务ID。 + * 优先查 wms_wave_pick_task.wave_id,其次查 wms_wave_pick_task_wave 关联表。 + * @param {number} waveId 波次ID。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 拣货任务ID,未找到返回 0。 + */ + async getTaskIdByWaveId(waveId, warehouseId) { + const { ctx } = this; + const normalizedWaveId = Number(waveId || 0); + + if (normalizedWaveId <= 0) { + return 0; + } + + // 先按 wave_id 直接查拣货任务 + const taskRows = await ctx.model.query( + ` + SELECT id AS task_id + FROM wms_wave_pick_task + WHERE wave_id = :waveId + AND warehouse_id = :warehouseId + ORDER BY create_time DESC + LIMIT 1 + `, + { + replacements: { waveId: normalizedWaveId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + if (Array.isArray(taskRows) && taskRows.length > 0) { + return Number(taskRows[0].task_id || 0); + } + + // 通过 wms_wave_pick_task_wave 关联查询 + const twRows = await ctx.model.query( + ` + SELECT tw.task_id + FROM wms_wave_pick_task_wave tw + WHERE tw.wave_id = :waveId + AND tw.warehouse_id = :warehouseId + ORDER BY tw.task_id DESC + LIMIT 1 + `, + { + replacements: { waveId: normalizedWaveId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + if (Array.isArray(twRows) && twRows.length > 0) { + return Number(twRows[0].task_id || 0); + } + + return 0; + } + /** * 查询波次下所有订单的基本信息列表。 * 包含运单号、打印状态、复核状态、波次内序号(优先从 wms_order_wave_index 读取真实 wave_index, @@ -934,6 +1166,42 @@ class RecheckOrderService extends OrderBaseService { }; } + /** + * 通过拣货任务ID查询拣货人信息。 + * @param {number} taskId 拣货任务ID。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise<{ picker_id: number|null, picker_name: string }>} 拣货人信息。 + */ + async getPickerInfoByTaskId(taskId, warehouseId) { + const { ctx } = this; + const normalizedTaskId = Number(taskId || 0); + + if (normalizedTaskId <= 0) { + return { picker_id: null, picker_name: '' }; + } + + const rows = await ctx.model.query( + ` + SELECT pick_user_id, pick_user_name + FROM wms_wave_pick_task + WHERE id = :taskId + AND warehouse_id = :warehouseId + LIMIT 1 + `, + { + replacements: { taskId: normalizedTaskId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + const row = Array.isArray(rows) && rows.length > 0 ? rows[0] : null; + + return { + picker_id: row && row.pick_user_id != null ? Number(row.pick_user_id) : null, + picker_name: String(row && row.pick_user_name || '').trim(), + }; + } + /** * 查询波次关联的策略信息。 * 当前 wms_wave_batch 与 wms_wave_pick_task 均未直接存储 strategy_id, @@ -961,15 +1229,25 @@ class RecheckOrderService extends OrderBaseService { /** * 确认订单已复核,并写入复核任务记录。 + * 支持两种模式:传入 wave_id 时走团购波次批量复核,否则走单订单复核。 * @param {Object} data 请求体。 + * @param {number|string} [data.wave_id] 波次ID,传入时触发团购波次批量复核。 * @param {number|string} [data.order_id] 订单ID。 * @param {number|string} [data.id] 订单ID别名。 * @param {number|string} [data.orderId] 订单ID别名。 * @return {Promise} 复核确认结果。 */ async confirmRecheck(data = {}) { - const { ctx } = this; + const requestData = this.isPlainObject(data) ? data : {}; const warehouseId = this.getWarehouseId(); + + // 团购波次批量复核 + const { wave_id: waveId } = requestData; + if (waveId) { + return await this.confirmRecheckByWaveId(Number(waveId), warehouseId); + } + + const { ctx } = this; const orderId = this.resolveOrderId(data); const orderModel = await this.getOrderModelByTableType('current', warehouseId); const orderWhere = this.buildOrderWhere([ orderId ], warehouseId); @@ -1067,6 +1345,15 @@ class RecheckOrderService extends OrderBaseService { // 更新波次拣货任务订单复核状态,并判断是否需要解绑车任务 await this.updateTaskOrderReviewAndTryUnbindCart(orderId, warehouseId, operator, now); + // 写入操作日志 + await this._writeRecheckActionLog({ + orderId, + waybillNo, + warehouseId, + operator, + now, + }); + return { order_id: orderId, waybill_no: waybillNo, @@ -1076,6 +1363,331 @@ class RecheckOrderService extends OrderBaseService { }; } + /** + * 团购波次批量复核:将波次下所有非拦截订单标记为已复核,并更新波次批次状态为复核完成。 + * @param {number} waveId 波次ID。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 批量复核结果,包含 wave_id、success_count、 + * intercepted_count、total_count。 + */ + async confirmRecheckByWaveId(waveId, warehouseId) { + const { ctx } = this; + const normalizedWaveId = Number(waveId); + + if (!Number.isFinite(normalizedWaveId) || normalizedWaveId <= 0) { + throw new Error('波次ID无效'); + } + + // 查询波次信息,判断是否为团购波次 + const waveRows = await ctx.model.query( + `SELECT wave_id, wave_no, wave_type + FROM wms_wave_batch + WHERE wave_id = :waveId + AND warehouse_id = :warehouseId + LIMIT 1`, + { + replacements: { waveId: normalizedWaveId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + const waveRow = Array.isArray(waveRows) && waveRows.length > 0 ? waveRows[0] : null; + + if (!waveRow) { + throw new Error('未找到对应波次'); + } + + const waveType = Number(waveRow.wave_type || 0); + const pickMode = await this.getPickModeByWaveId(normalizedWaveId, warehouseId); + const isGroupBuy = waveType === 1 || pickMode === 1; + + if (!isGroupBuy) { + throw new Error('该波次不是团购波次,不允许批量复核'); + } + + // 查询波次下所有订单 + const orderModel = await this.getOrderModelByTableType('current', warehouseId); + const orderRows = await orderModel.findAll({ + where: { + wave_id: normalizedWaveId, + warehouse_id: warehouseId, + }, + attributes: [ + 'id', + 'delivery_order_code', + 'pre_delivery_order_code', + 'intercept_status', + 'pick_status', + 'recheck_status', + ], + raw: true, + }); + + const orderList = Array.isArray(orderRows) ? orderRows : []; + + if (orderList.length === 0) { + throw new Error('波次下没有订单'); + } + + // 分离拦截订单与非拦截订单 + const normalOrders = []; + const interceptedOrders = []; + + for (const order of orderList) { + if (String(order.intercept_status || '').trim() === 'intercepted') { + interceptedOrders.push(order); + } else { + normalOrders.push(order); + } + } + + if (normalOrders.length === 0) { + return { + wave_id: normalizedWaveId, + success_count: 0, + intercepted_count: interceptedOrders.length, + total_count: orderList.length, + }; + } + + // 验证所有非拦截订单允许复核 + for (const order of normalOrders) { + this.assertOrderCanRecheck(order); + } + + const now = new Date(); + const normalOrderIds = normalOrders + .map(o => Number(o.id)) + .filter(id => id > 0); + + // 批量更新订单复核状态 + await orderModel.update( + { + recheck_status: 'fin', + recheck_time: now, + updated_at: now, + }, + { + where: this.buildOrderWhere(normalOrderIds, warehouseId), + } + ); + + // 批量插入复核任务记录 + const operator = this.getOrderLogOperator(); + const operatorNo = String(operator.id || '').trim(); + const operatorName = String(operator.name || '').trim(); + + if (normalOrders.length > 0) { + const valuePlaceholders = []; + const replacements = {}; + let idx = 0; + + for (const order of normalOrders) { + const orderId = Number(order.id); + const reviewNo = this.buildRecheckReviewNo(orderId, now); + const orderNo = String(order.delivery_order_code || order.pre_delivery_order_code || '').trim(); + const i = idx++; + + valuePlaceholders.push( + `(:reviewNo${i}, :warehouseId${i}, :orderId${i}, :orderNo${i}, :waybillNo${i}, ` + + `:taskStatus${i}, :scanStatus${i}, :reviewEmpNo${i}, :reviewEmpName${i}, ` + + `:scanEmpNo${i}, :scanEmpName${i}, :scanTime${i}, :finishTime${i}, :remark${i})` + ); + + replacements[`reviewNo${i}`] = reviewNo; + replacements[`warehouseId${i}`] = warehouseId; + replacements[`orderId${i}`] = orderId; + replacements[`orderNo${i}`] = orderNo; + replacements[`waybillNo${i}`] = ''; + replacements[`taskStatus${i}`] = 2; + replacements[`scanStatus${i}`] = 1; + replacements[`reviewEmpNo${i}`] = operatorNo; + replacements[`reviewEmpName${i}`] = operatorName; + replacements[`scanEmpNo${i}`] = operatorNo; + replacements[`scanEmpName${i}`] = operatorName; + replacements[`scanTime${i}`] = now; + replacements[`finishTime${i}`] = now; + replacements[`remark${i}`] = '系统复核完成'; + } + + const insertSQL = ` + INSERT INTO wms_recheck_task ( + review_no, + warehouse_id, + order_id, + order_no, + waybill_no, + task_status, + scan_status, + review_emp_no, + review_emp_name, + scan_emp_no, + scan_emp_name, + scan_time, + finish_time, + remark + ) VALUES ${valuePlaceholders.join(', ')} + `; + + await ctx.model.query(insertSQL, { + replacements, + type: ctx.model.QueryTypes.INSERT, + }); + } + + // 批量更新 wms_wave_pick_task_order 复核状态,并检查解绑车任务 + await this.updateTaskOrdersReviewBatch(normalOrderIds, warehouseId, operator, now); + + // 更新 wms_wave_batch 波次复核状态:标记复核完成、记录操作人与复核时间 + await ctx.model.query( + `UPDATE wms_wave_batch + SET wave_status = 5, + check_operator = :operatorName, + check_time = :now, + processed_orders = :processedCount, + update_time = :now + WHERE wave_id = :waveId + AND warehouse_id = :warehouseId`, + { + replacements: { + waveId: normalizedWaveId, + warehouseId, + operatorName: operatorName || operatorNo, + processedCount: normalOrders.length, + now, + }, + type: ctx.model.QueryTypes.UPDATE, + } + ); + + // 写入操作日志 + await this._writeRecheckActionLog({ + waveId: normalizedWaveId, + waveNo: String(waveRow.wave_no || '').trim(), + warehouseId, + operator, + normalOrderCount: normalOrders.length, + interceptedOrderCount: interceptedOrders.length, + totalOrderCount: orderList.length, + now, + }); + + return { + wave_id: normalizedWaveId, + success_count: normalOrders.length, + intercepted_count: interceptedOrders.length, + total_count: orderList.length, + }; + } + + /** + * 写入复核操作日志到 wms_wave_pick_action_log(内部方法)。 + * + * @param {Object} params 日志参数。 + * @param {number} [params.orderId] 订单ID(单订单复核场景)。 + * @param {string} [params.waybillNo] 运单号(单订单复核场景)。 + * @param {number} [params.waveId] 波次ID(团购批量复核场景)。 + * @param {string} [params.waveNo] 波次号(团购批量复核场景)。 + * @param {number} params.warehouseId 仓库ID。 + * @param {{ id: string|null, name: string }} params.operator 操作人信息。 + * @param {number} [params.normalOrderCount] 复核成功的订单数(批量场景)。 + * @param {number} [params.interceptedOrderCount] 拦截的订单数(批量场景)。 + * @param {number} [params.totalOrderCount] 总订单数(批量场景)。 + * @param {Date} params.now 操作时间。 + * @return {Promise} 无返回值。 + */ + async _writeRecheckActionLog(params = {}) { + const { + orderId, + waybillNo, + waveId, + waveNo, + warehouseId, + operator, + normalOrderCount, + interceptedOrderCount, + totalOrderCount, + now, + } = params; + + const operatorId = operator && operator.id ? Number(operator.id) : 0; + const operatorName = operator && operator.name ? String(operator.name).trim() : 'system'; + const isBatch = waveId !== undefined && waveId !== null; + const tag = isBatch ? 'recheck_batch' : 'recheck'; + const requestId = `${tag}_${warehouseId}_${isBatch ? waveId : orderId}_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`; + + await this.ctx.model.query( + `INSERT INTO wms_wave_pick_action_log ( + task_id, + warehouse_id, + wave_id, + order_id, + sku_id, + location_id, + box_no, + cart_id, + qty_delta, + action_type, + request_id, + operator_id, + device_id, + seq_no, + snapshot + ) VALUES ( + :taskId, + :warehouseId, + :waveId, + :orderId, + :skuId, + :locationId, + :boxNo, + :cartId, + :qtyDelta, + :actionType, + :requestId, + :operatorId, + :deviceId, + :seqNo, + :snapshot + )`, + { + replacements: { + taskId: 0, + warehouseId: warehouseId || 0, + waveId: isBatch ? waveId : null, + orderId: isBatch ? null : (orderId || 0), + skuId: null, + locationId: null, + boxNo: null, + cartId: null, + qtyDelta: 0, + actionType: isBatch ? 'recheck_batch' : 'recheck', + requestId, + operatorId, + deviceId: null, + seqNo: 1, + snapshot: JSON.stringify(isBatch + ? { + wave_id: waveId, + wave_no: waveNo || '', + success_count: normalOrderCount, + intercepted_count: interceptedOrderCount, + total_count: totalOrderCount, + operator_name: operatorName, + recheck_time: now instanceof Date ? now.toISOString() : String(now || ''), + } + : { + order_id: orderId, + waybill_no: waybillNo || '', + operator_name: operatorName, + recheck_time: now instanceof Date ? now.toISOString() : String(now || ''), + }), + }, + type: this.ctx.model.QueryTypes.INSERT, + } + ); + } + /** * 更新波次拣货任务订单的复核状态,若任务下所有订单均已复核完成则自动解绑车任务。 * @param {number} orderId 订单ID。 @@ -1176,6 +1788,105 @@ class RecheckOrderService extends OrderBaseService { } } + /** + * 批量更新波次拣货任务订单的复核状态,并按任务维度检查是否需要解绑车任务。 + * 与单订单版本不同,本方法一次性更新所有相关任务订单的 review_status, + * 再按去重后的 task_id 逐任务判断是否所有订单均已复核完成。 + * @param {number[]} orderIds 订单ID列表。 + * @param {number} warehouseId 仓库ID。 + * @param {{ id: string|null, name: string }} operator 操作人信息。 + * @param {Date} now 当前时间。 + * @return {Promise} 无返回值。 + */ + async updateTaskOrdersReviewBatch(orderIds, warehouseId, operator, now) { + const { ctx } = this; + + if (!Array.isArray(orderIds) || orderIds.length === 0) { + return; + } + + const taskOrderColumnSet = await this.getTableColumnSet('wms_wave_pick_task_order'); + const hasReviewStatus = taskOrderColumnSet.has('review_status'); + + if (!hasReviewStatus) { + return; + } + + const hasReviewUserId = taskOrderColumnSet.has('review_user_id'); + const hasReviewResult = taskOrderColumnSet.has('review_result'); + const hasReviewTime = taskOrderColumnSet.has('review_time'); + const operatorUserId = Number(operator.id) || 0; + + const reviewSetClauses = [ 'review_status = 1' ]; + + if (hasReviewUserId) reviewSetClauses.push('review_user_id = :operatorUserId'); + if (hasReviewResult) reviewSetClauses.push('review_result = 1'); + if (hasReviewTime) reviewSetClauses.push('review_time = :now'); + reviewSetClauses.push('update_time = NOW()'); + + await ctx.model.query( + `UPDATE wms_wave_pick_task_order + SET ${reviewSetClauses.join(',\n ')} + WHERE order_id IN (:orderIds) + AND warehouse_id = :warehouseId`, + { + replacements: { orderIds, warehouseId, operatorUserId, now }, + type: ctx.model.QueryTypes.UPDATE, + } + ); + + // 查询受影响的去重 task_id + const taskRows = await ctx.model.query( + `SELECT DISTINCT task_id + FROM wms_wave_pick_task_order + WHERE order_id IN (:orderIds) + AND warehouse_id = :warehouseId`, + { + replacements: { orderIds, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + const taskIds = (Array.isArray(taskRows) ? taskRows : []) + .map(r => Number(r.task_id || 0)) + .filter(id => id > 0); + + // 逐任务判断是否所有订单均已复核完成 + for (const taskId of taskIds) { + const unreviewedRows = await ctx.model.query( + `SELECT COUNT(*) AS cnt + FROM wms_wave_pick_task_order + WHERE task_id = :taskId + AND warehouse_id = :warehouseId + AND review_status != 1`, + { + replacements: { taskId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + const unreviewedCount = Number( + (Array.isArray(unreviewedRows) && unreviewedRows.length > 0 ? unreviewedRows[0]?.cnt : 0) + ); + + if (unreviewedCount > 0) { + continue; + } + + // 任务下所有订单均已复核完成,解绑车任务 + try { + await this.unbindCartForTask(taskId, warehouseId, operatorUserId); + ctx.logger.info( + `[confirmRecheck] 批量复核-车任务解绑成功, taskId=${taskId}, operatorUserId=${operatorUserId}` + ); + } catch (unbindError) { + ctx.logger.warn( + `[confirmRecheck] 批量复核-解绑车任务失败, taskId=${taskId}, error=${unbindError.message}` + ); + } + } + } + /** * 解绑车任务:清空波次拣货任务的车绑定、停用拣货车绑定记录、释放拣货车。 * @param {number} taskId 波次拣货任务ID。 @@ -1485,39 +2196,81 @@ class RecheckOrderService extends OrderBaseService { const { ctx } = this; const warehouseId = this.getWarehouseId(); const taskOrderColumnSet = await this.getTableColumnSet('wms_wave_pick_task_order'); - const taskRows = await ctx.model.query( - ` - SELECT - t.id AS task_id, - t.task_no, - t.pick_mode, - t.status, - t.review_status, - t.current_cart_code_snapshot - FROM wms_wave_pick_task t - WHERE t.warehouse_id = :warehouseId - AND ( - t.current_cart_code_snapshot = :cartCode - OR EXISTS ( - SELECT 1 - FROM wms_wave_pick_task_order pto - WHERE pto.task_id = t.id - AND pto.cart_code_snapshot = :cartCode - ) - ) - ORDER BY t.create_time DESC, t.id DESC - LIMIT 1 - `, - { - replacements: { - warehouseId, - cartCode, - }, - type: ctx.model.QueryTypes.SELECT, - } - ); - const taskRow = Array.isArray(taskRows) && taskRows.length > 0 ? taskRows[0] : null; + /** + * 通过车号查找匹配的拣货任务行。 + * 匹配优先级: + * 1. wms_wave_pick_task.current_cart_code_snapshot(任务主表车号快照) + * 2. wms_wave_pick_task_order.cart_code_snapshot(任务订单行车号快照,仅散单模式有数据) + * 3. wms_pick_task_cart_binding(车任务绑定表,所有模式均有记录,回退兜底) + * @param {string} cartCode 车号。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 任务行,未找到返回 null。 + */ + const findTaskByCartCode = async (cartCode, warehouseId) => { + // 第一优先级:任务主表车号快照 + 任务订单行车号快照 + const primaryRows = await ctx.model.query( + ` + SELECT + t.id AS task_id, + t.task_no, + t.pick_mode, + t.status, + t.review_status, + t.current_cart_code_snapshot + FROM wms_wave_pick_task t + WHERE t.warehouse_id = :warehouseId + AND ( + t.current_cart_code_snapshot = :cartCode + OR EXISTS ( + SELECT 1 + FROM wms_wave_pick_task_order pto + WHERE pto.task_id = t.id + AND pto.cart_code_snapshot = :cartCode + ) + ) + ORDER BY t.create_time DESC, t.id DESC + LIMIT 1 + `, + { + replacements: { warehouseId, cartCode }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + if (Array.isArray(primaryRows) && primaryRows.length > 0) { + return primaryRows[0]; + } + + // 第二优先级(回退):车任务绑定表(覆盖小团购等无 wms_wave_pick_task_order 记录的场景) + const bindingRows = await ctx.model.query( + ` + SELECT + t.id AS task_id, + t.task_no, + t.pick_mode, + t.status, + t.review_status, + t.current_cart_code_snapshot + FROM wms_pick_task_cart_binding b + INNER JOIN wms_wave_pick_task t + ON t.id = b.task_id + WHERE b.cart_code_snapshot = :cartCode + AND b.warehouse_id = :warehouseId + AND b.is_active = 1 + ORDER BY b.create_time DESC, b.id DESC + LIMIT 1 + `, + { + replacements: { warehouseId, cartCode }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + return (Array.isArray(bindingRows) && bindingRows.length > 0) ? bindingRows[0] : null; + }; + + const taskRow = await findTaskByCartCode(cartCode, warehouseId); const taskId = Number(taskRow && taskRow.task_id || 0); if (!Number.isInteger(taskId) || taskId <= 0) { return { @@ -1528,6 +2281,28 @@ class RecheckOrderService extends OrderBaseService { }; } + const pickMode = Number(taskRow.pick_mode || 0); + + // 团购模式(小波次 pick_mode=1 / 大波次 pick_mode=5): + // wms_wave_pick_task_order 表无记录,直接返回 task 信息, + // 以 task_id 作为 order_id 保证 pickOrderMatchByKeyword 的 cartMatch.order_id > 0 检查通过 + if (pickMode === 1 || pickMode === 5) { + const task = { + task_id: taskId, + task_no: String(taskRow.task_no || '').trim(), + pick_mode: pickMode, + status: Number(taskRow.status || 0), + review_status: Number(taskRow.review_status || 0), + current_cart_code_snapshot: String(taskRow.current_cart_code_snapshot || '').trim(), + }; + return { + order_id: taskId, + task, + task_orders: [], + matched_order_ids: [], + }; + } + const pickStatusSelect = taskOrderColumnSet.has('pick_status') ? 'pto.pick_status' : 'NULL AS pick_status'; diff --git a/app/service/systemMethods/order/wave.js b/app/service/systemMethods/order/wave.js index 476890d..ede441b 100644 --- a/app/service/systemMethods/order/wave.js +++ b/app/service/systemMethods/order/wave.js @@ -1022,6 +1022,15 @@ class WaveService extends OrderBaseService { } } + if (allWaveIds.length > 0 && allOrderIds.length > 0) { + await this.replaceOrderWaveIndexByWaveIds({ + warehouseId, + waveIds: allWaveIds, + orderModel: model, + transaction, + }); + } + await transaction.commit(); await this.batchCreateOrderOperationLogs(fetchedOrderLogItems, { warehouseId, @@ -1941,7 +1950,11 @@ class WaveService extends OrderBaseService { for (const row of itemRows) { const normalized = this.normalizeOrderItemRow(row); - if (!normalized.item_code || normalized.quantity <= 0) { + const hasIdentity = normalized.stock_id > 0 + || normalized.item_code + || normalized.item_name; + + if (!hasIdentity || normalized.quantity <= 0) { continue; } @@ -6642,6 +6655,14 @@ class WaveService extends OrderBaseService { }); } + await this.rebuildOrderWaveIndex({ + warehouseId, + waveId, + orderIds: grabbedOrderIds, + orderModel, + transaction, + }); + await transaction.commit(); await this.batchCreateOrderOperationLogs(grabbedOrderIds.map(orderId => ({ @@ -10604,10 +10625,34 @@ class WaveService extends OrderBaseService { const taskId = Number(taskCreateResult.task_id || 0); const taskNo = String(taskCreateResult.task_no || '').trim(); + // 查询所有选中波次的 wave_no,用于填充任务波次关联记录 + let waveNoMap = new Map(); + if (selectedWaveIds.length > 0) { + const waveNoRows = await this.ctx.model.query( + `SELECT wave_id, wave_no + FROM wms_wave_batch + WHERE wave_id IN (:waveIds) + AND warehouse_id = :warehouseId`, + { + replacements: { waveIds: selectedWaveIds, warehouseId }, + type: this.ctx.model.QueryTypes.SELECT, + transaction, + } + ); + for (const row of Array.isArray(waveNoRows) ? waveNoRows : []) { + const wid = Number(row && row.wave_id || 0); + const wno = String(row && row.wave_no || '').trim(); + if (wid > 0 && wno) { + waveNoMap.set(wid, wno); + } + } + } + const taskWaveRows = this.buildTaskWaveRows({ taskId, plan: effectivePlan, selectedWaveIds, + waveNoMap, }); const taskOrderRows = this.buildTaskOrderRows({ taskId, @@ -10756,13 +10801,14 @@ class WaveService extends OrderBaseService { } /** - * 构建任务与波次关联写入行。 + * 构建任务波次关联写入行。 * * @param {Object} options 构建参数。 * @param {number} options.taskId 任务ID。 * @param {Object} options.plan 预处理计划。 * @param {Array} options.selectedWaveIds 已选波次ID。 - * @return {Array} 任务波次行。 + * @param {Map} [options.waveNoMap] wave_id → wave_no 映射。 + * @return {Array} 任务波次关联行。 */ buildTaskWaveRows(options = {}) { const taskId = Number(options && options.taskId || 0); @@ -10771,11 +10817,14 @@ class WaveService extends OrderBaseService { const selectedWaveIds = Array.isArray(options && options.selectedWaveIds) ? options.selectedWaveIds : []; + const waveNoMap = options && options.waveNoMap instanceof Map + ? options.waveNoMap + : new Map(); return selectedWaveIds.map((waveId, index) => ({ task_id: taskId, wave_id: waveId, - wave_no: null, + wave_no: waveNoMap.get(waveId) || null, box_no: index + 1, status: 0, bind_time: null, @@ -11545,11 +11594,12 @@ class WaveService extends OrderBaseService { /** * 公共拣货任务取消流程。 * - * 仅允许取消状态为 0/1/2/3 的任务。取消后会回收拣货车绑定、 - * 删除任务关联波次并将订单 wave_id 清空,使订单可重新参与后续策略抓取。 - * 当任务状态为 2(待复核)或 3(已完成)时,还会回退已拣货订单的 - * wms_wave_pick_task_order.pick_status 和 order_delivery.pick_status, - * 使订单恢复为未拣货状态。 + * 仅允许取消状态为 0/1/2/3 的任务。取消后会回收拣货车绑定。 + * + * 按任务来源区分行为: + * - source=1(PDA 抓取):释放关联波次(清空订单 wave_id、删除 wms_wave_batch), + * 使订单可重新参与后续策略抓取;状态为 2/3 时还会回退拣货状态。 + * - source=2(后台/扫描创建):不释放波次,仅作废任务(更新状态为 9、解绑拣货车)。 * * @param {Object} [params={}] 取消参数。 * @param {Array} params.taskIds 任务ID列表。 @@ -11617,7 +11667,7 @@ class WaveService extends OrderBaseService { for (const taskId of normalizedTaskIds) { const requestId = `wave_pick_task_cancel_${warehouseId}_${taskId}_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`; const taskRows = await this.ctx.model.query(` - SELECT id, task_no, warehouse_id, status, current_cart_id + SELECT id, task_no, warehouse_id, status, current_cart_id, source FROM wms_wave_pick_task WHERE id = :taskId AND warehouse_id = :warehouseId @@ -11685,6 +11735,7 @@ class WaveService extends OrderBaseService { throw error; } + const taskSource = Number(taskRow.source || 0); const taskNo = String(taskRow.task_no || '').trim(); const taskWaveRows = await this.ctx.model.query(` @@ -11721,46 +11772,52 @@ class WaveService extends OrderBaseService { .map(row => Number(row && row.order_id || 0)) .filter(orderId => Number.isInteger(orderId) && orderId > 0)) ]; + // source=2(后台/扫描创建)不释放波次,仅清理任务-波次关联 + const isScanCreated = taskSource === 2; let releasedWaveRows = []; if (waveIds.length > 0) { - releasedWaveRows = await this.ctx.model.query(` - SELECT wave_id, wave_no - FROM wms_wave_batch - WHERE warehouse_id = :warehouseId - AND wave_id IN (:waveIds) - FOR UPDATE - `, { - replacements: { - warehouseId, - waveIds, - }, - type: this.ctx.model.QueryTypes.SELECT, - transaction, - }); + if (!isScanCreated) { + // PDA 抓取:释放波次 + releasedWaveRows = await this.ctx.model.query(` + SELECT wave_id, wave_no + FROM wms_wave_batch + WHERE warehouse_id = :warehouseId + AND wave_id IN (:waveIds) + FOR UPDATE + `, { + replacements: { + warehouseId, + waveIds, + }, + type: this.ctx.model.QueryTypes.SELECT, + transaction, + }); - await orderModel.update({ - wave_id: 0, - wave_no: '', - }, { - where: { - warehouse_id: warehouseId, - wave_id: { [Op.in]: waveIds }, - }, - transaction, - }); + await orderModel.update({ + wave_id: 0, + wave_no: '', + }, { + where: { + warehouse_id: warehouseId, + wave_id: { [Op.in]: waveIds }, + }, + transaction, + }); - await this.ctx.model.query(` - DELETE FROM wms_wave_batch - WHERE warehouse_id = :warehouseId - AND wave_id IN (:waveIds) - `, { - replacements: { - warehouseId, - waveIds, - }, - transaction, - }); + await this.ctx.model.query(` + DELETE FROM wms_wave_batch + WHERE warehouse_id = :warehouseId + AND wave_id IN (:waveIds) + `, { + replacements: { + warehouseId, + waveIds, + }, + transaction, + }); + } + // 清理任务-波次关联(所有来源都需要) await this.ctx.model.query(` DELETE FROM wms_wave_pick_task_wave WHERE task_id = :taskId @@ -11774,8 +11831,8 @@ class WaveService extends OrderBaseService { }); } - // 当任务状态为待复核(2)或已完成(3)时,回退订单拣货状态 - if ([ 2, 3 ].includes(taskStatus)) { + // 当任务状态为待复核(2)或已完成(3)时,回退订单拣货状态(仅 PDA 抓取) + if (!isScanCreated && [ 2, 3 ].includes(taskStatus)) { await this.ctx.model.query(` UPDATE wms_wave_pick_task_order SET pick_status = 0, @@ -11887,8 +11944,9 @@ class WaveService extends OrderBaseService { seq_no: 1, snapshot: JSON.stringify({ task_no: taskNo, - released_wave_ids: waveIds, - released_order_count: taskOrderIds.length, + source: taskSource, + released_wave_ids: isScanCreated ? [] : waveIds, + released_order_count: isScanCreated ? 0 : taskOrderIds.length, }), }], transaction); @@ -11904,16 +11962,21 @@ class WaveService extends OrderBaseService { review_time: null, review_result: null, event_type: 'task_cancelled', - event_desc: `任务取消并释放波次: ${taskNo || taskId}`, + event_desc: isScanCreated + ? `任务取消(未释放波次): ${taskNo || taskId}` + : `任务取消并释放波次: ${taskNo || taskId}`, operator_id: Number.isInteger(operatorId) ? operatorId : 0, operator_name: operatorName, snapshot: JSON.stringify({ task_no: taskNo, - released_wave_ids: waveIds, - released_order_count: taskOrderIds.length, - released_wave_nos: (Array.isArray(releasedWaveRows) ? releasedWaveRows : []) - .map(row => String(row && row.wave_no || '').trim()) - .filter(Boolean), + source: taskSource, + released_wave_ids: isScanCreated ? [] : waveIds, + released_order_count: isScanCreated ? 0 : taskOrderIds.length, + released_wave_nos: isScanCreated + ? [] + : (Array.isArray(releasedWaveRows) ? releasedWaveRows : []) + .map(row => String(row && row.wave_no || '').trim()) + .filter(Boolean), }), }], transaction); diff --git a/app/service/systemMethods/pick.js b/app/service/systemMethods/pick.js index 566e63c..39b455c 100644 --- a/app/service/systemMethods/pick.js +++ b/app/service/systemMethods/pick.js @@ -93,7 +93,7 @@ class PickService extends MainService { * @param {string} params.operatorName 操作人名称。 * @param {Array} params.orderIds 波次订单ID集合。 * @param {string} [params.remark=''] 备注。 - * @param {number} [params.source=2] 任务来源:1-PDA扫码补任务,2-后台抓取,默认为2。 + * @param {number} [params.source=2] 任务来源:1-PDA抓取创建,2-扫描进任务/后台抓取,默认为2。 * @return {Promise<{task_id: number, task_no: string}>} 创建结果。 */ async createWavePickTask(params = {}) { @@ -651,7 +651,7 @@ class PickService extends MainService { operatorName, orderIds: selectedOrderIds, remark: `pick.query keyword=${normalizedKeyword}`, - source: 1, + source: 2, }); return this.success('ok', { diff --git a/app/service/systems/delivery_order.js b/app/service/systems/delivery_order.js index 26bdf67..fe07b45 100644 --- a/app/service/systems/delivery_order.js +++ b/app/service/systems/delivery_order.js @@ -1124,7 +1124,16 @@ class DeliveryOrderService extends Service { continue; } let wms_stock = null; - if (!line.itemId) { + // 手工单:调用方直接传入 stockId 时跳过 stock_store 查表,直接使用 + if (line.stockId && line.stockId > 0) { + wms_stock = { + id: line.stockId, + stock_id: line.stockId, + item_name: line.itemName || '', + item_code: line.itemCode || '', + gross_weight: 0, + }; + } else if (!line.itemId) { // 查找唯一键(appKey 为空时不作为条件,兼容内部手动建单场景) const stockWhere = { item_code: line.itemCode, @@ -1139,32 +1148,16 @@ class DeliveryOrderService extends Service { wms_stock = await app.model.StockStore.findByPk(line.itemId, { transaction }); } - // MANUAL 渠道降级:信任调用方提供的 itemId,跳过 StockStore 校验 - const isManualFallback = createChannel === 'MANUAL' && line.itemId && !wms_stock; - - if (!wms_stock && !isManualFallback) { + if (!wms_stock) { errors.push(`商品《${line.itemName}》编码《${line.itemCode}》\n未同步推送到仓库`); continue; } - if (isManualFallback) { - // 手工建单降级模式:使用调用方传入的 itemId,stockId 置 0,跳过库存锁定 - wms_stock = { - id: line.itemId, - stock_id: 0, - item_name: line.itemName || '', - item_code: line.itemCode || '', - gross_weight: 0, - }; - } - const itemId = parseInt(wms_stock.id); const stockId = Number(wms_stock.stock_id) || 0; // ========== 核心库存检查逻辑 ========== - // MANUAL 降级时 stockId 为 0,跳过库存记录检查与锁定 - const isManualNoStock = isManualFallback && !stockId; - if (!stockId && !isManualNoStock) { + if (!stockId) { errors.push(`第${i + 1}行: 商品《${wms_stock.item_name}》库存记录不存在`); continue; } @@ -1175,28 +1168,23 @@ class DeliveryOrderService extends Service { } processedItemIds.add(itemId); - // 锁定库存(MANUAL 降级时跳过) - if (!isManualNoStock) { - const lockResult = await ctx.service.systems.stockStore.lockItemStorages( - stockId, - planQty, - transaction - ); + // 锁定库存 + const lockResult = await ctx.service.systems.stockStore.lockItemStorages( + stockId, + planQty, + transaction + ); - if (!lockResult.success) { - errors.push(`SKU${wms_stock.id}商品《${wms_stock.item_name}》编码《${wms_stock.item_code}》\n锁定失败: ${lockResult.error}`); - continue; - } - - const totalQtyForStock = (stockQuantityMap.get(stockId) || 0) + planQty; - stockQuantityMap.set(stockId, totalQtyForStock); + if (!lockResult.success) { + errors.push(`SKU${wms_stock.id}商品《${wms_stock.item_name}》编码《${wms_stock.item_code}》\n锁定失败: ${lockResult.error}`); + continue; } - // 优先使用商品主数据重量,缺失时降级为0;MANUAL 降级时重量为 0 - const weight = isManualNoStock ? 0 : (parseFloat(wms_stock.gross_weight) || 0); - if (!isManualNoStock) { - stockWeightMap.set(stockId, weight); - } + const totalQtyForStock = (stockQuantityMap.get(stockId) || 0) + planQty; + stockQuantityMap.set(stockId, totalQtyForStock); + + const weight = parseFloat(wms_stock.gross_weight) || 0; + stockWeightMap.set(stockId, weight); // ========== 库存检查逻辑结束 ========== // 所有检查通过,准备订单行数据 diff --git a/app/service/systems/order_express.js b/app/service/systems/order_express.js index 1d84684..28da444 100644 --- a/app/service/systems/order_express.js +++ b/app/service/systems/order_express.js @@ -212,11 +212,16 @@ class OrderExpressService extends Service { /** * 更新订单运单称重重量。 * + * 支持团购波次批量设置: + * - 散单(wave_id = 0)或非团购波次:仅更新单个订单的运单重量。 + * - 团购波次(wave_type = 1):将同一重量批量设置到该波次下所有订单的运单上。 + * * @param {Object} payload 入参对象。 * @param {number|string} payload.orderId 订单ID。 - * @param {string} [payload.waybillCode] 运单号。 - * @param {number|string} payload.weighingWeight 称重重量。 - * @return {Promise<{order_id:number, waybill_code:string, weighing_weight:number}>} 更新结果。 + * @param {string} [payload.waybillCode] 运单号,多运单场景必填。 + * @param {number|string} payload.weighingWeight 称重重量(kg)。 + * @return {Promise} 单订单返回 {order_id, waybill_code, weighing_weight}; + * 团购批量返回 {wave_id, wave_no, weighing_weight, success_count, total_count}。 */ async updateWeighingWeight(payload = {}) { const requestData = payload && typeof payload === 'object' ? payload : {}; @@ -230,7 +235,79 @@ class OrderExpressService extends Service { const normalizedWeight = this.normalizeWeighingWeight(weighingWeight); const normalizedWaybillCode = String(waybillCode || '').trim(); const warehouseId = this.ctx && this.ctx.user ? this.ctx.user.store_id : null; - const rows = await this.findValidOrderExpressRows(normalizedOrderId, warehouseId); + + // 无法获取仓库ID时降级为单个订单逻辑 + if (!warehouseId) { + return await this._updateSingleOrderWeight( + normalizedOrderId, normalizedWaybillCode, normalizedWeight, warehouseId + ); + } + + // 查询订单所属波次 + const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; + if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') { + throw this.createBusinessError('订单模型未初始化', 500); + } + + const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(warehouseId); + const orderRow = await orderDeliveryModel.findOne({ + where: { id: normalizedOrderId, warehouse_id: warehouseId }, + attributes: [ 'id', 'wave_id', 'wave_no' ], + raw: true, + }); + + // 订单不存在 → 兼容前端传入 wave_id 的场景,尝试按波次查询 + if (!orderRow) { + return await this._tryWaveCompatibility( + normalizedOrderId, normalizedWaybillCode, normalizedWeight, warehouseId, orderDeliveryModel + ); + } + + const waveId = Number(orderRow.wave_id || 0); + + // 散单 → 走单个订单逻辑 + if (waveId === 0) { + return await this._updateSingleOrderWeight( + normalizedOrderId, normalizedWaybillCode, normalizedWeight, warehouseId + ); + } + + // 查询波次类型 + const waveBatchModel = this.ctx.model && this.ctx.model.WaveBatch; + if (!waveBatchModel || typeof waveBatchModel.findOne !== 'function') { + throw this.createBusinessError('波次模型未初始化', 500); + } + + const waveRow = await waveBatchModel.findOne({ + where: { wave_id: waveId, warehouse_id: warehouseId }, + attributes: [ 'wave_id', 'wave_no', 'wave_type' ], + raw: true, + }); + + // 波次记录缺失或非团购波次 → 降级为单个订单逻辑 + if (!waveRow || Number(waveRow.wave_type) !== 1) { + return await this._updateSingleOrderWeight( + normalizedOrderId, normalizedWaybillCode, normalizedWeight, warehouseId + ); + } + + // 团购波次 → 批量设置同一重量 + return await this._updateWaveOrderWeight( + waveId, String(waveRow.wave_no || ''), normalizedWeight, warehouseId, orderDeliveryModel + ); + } + + /** + * 更新单个订单运单的称重重量(内部方法)。 + * + * @param {number} orderId 订单ID。 + * @param {string} waybillCode 运单号。 + * @param {number} weight 称重重量。 + * @param {number|null} warehouseId 仓库ID。 + * @return {Promise<{order_id:number, waybill_code:string, weighing_weight:number}>} 更新结果。 + */ + async _updateSingleOrderWeight(orderId, waybillCode, weight, warehouseId) { + const rows = await this.findValidOrderExpressRows(orderId, warehouseId); if (rows.length === 0) { throw this.createBusinessError('未找到有效的订单运单记录', 404); @@ -240,37 +317,274 @@ class OrderExpressService extends Service { if (rows.length === 1) { targetRow = rows[0]; } else { - if (!normalizedWaybillCode) { + if (!waybillCode) { throw this.createBusinessError('多运单订单必须传入 waybill_code', 400); } - targetRow = rows.find(row => String(row && row.waybill_code || '').trim() === normalizedWaybillCode) || null; + targetRow = rows.find( + row => String(row && row.waybill_code || '').trim() === waybillCode + ) || null; if (!targetRow) { throw this.createBusinessError('waybill_code 未匹配到该订单下的运单记录', 404); } } const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; - const updateResult = await orderExpressModel.update({ - weighing_weight: normalizedWeight, - }, { - where: { - id: Number(targetRow.id), - }, - }); + const updateResult = await orderExpressModel.update( + { weighing_weight: weight }, + { where: { id: Number(targetRow.id) } } + ); - const affectedRows = Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0); + const affectedRows = Array.isArray(updateResult) + ? Number(updateResult[0] || 0) + : Number(updateResult || 0); if (!Number.isFinite(affectedRows) || affectedRows <= 0) { throw this.createBusinessError('更新称重重量失败', 500); } + // 写入操作日志 + await this._writeWeighActionLog({ + orderId: Number(targetRow.order_id), + waybillCode: String(targetRow.waybill_code || '').trim(), + weight, + warehouseId, + }); + return { order_id: Number(targetRow.order_id), waybill_code: String(targetRow.waybill_code || '').trim(), - weighing_weight: normalizedWeight, + weighing_weight: weight, }; } + /** + * 批量更新团购波次下所有订单运单的称重重量(内部方法)。 + * + * @param {number} waveId 波次ID。 + * @param {string} waveNo 波次号。 + * @param {number} weight 称重重量。 + * @param {number|null} warehouseId 仓库ID。 + * @param {Object} orderDeliveryModel 订单 Sequelize 模型实例。 + * @return {Promise<{wave_id:number, wave_no:string, weighing_weight:number, success_count:number, total_count:number}>} + * 批量更新结果。 + */ + async _updateWaveOrderWeight(waveId, waveNo, weight, warehouseId, orderDeliveryModel) { + // 查询波次下所有订单 + const waveOrders = await orderDeliveryModel.findAll({ + where: { wave_id: waveId, warehouse_id: warehouseId }, + attributes: [ 'id' ], + raw: true, + }); + + if (!waveOrders || waveOrders.length === 0) { + throw this.createBusinessError('波次下未找到订单', 404); + } + + const orderIds = waveOrders.map(o => Number(o.id)); + const totalCount = orderIds.length; + + // 批量更新所有订单的运单称重重量 + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; + if (!orderExpressModel || typeof orderExpressModel.update !== 'function') { + throw this.createBusinessError('运单模型未初始化', 500); + } + + const { Op } = this.app.Sequelize; + const updateResult = await orderExpressModel.update( + { weighing_weight: weight }, + { + where: { + order_id: { [Op.in]: orderIds }, + delete_at: null, + }, + } + ); + + const successCount = Array.isArray(updateResult) + ? Number(updateResult[0] || 0) + : Number(updateResult || 0); + + if (!Number.isFinite(successCount) || successCount <= 0) { + throw this.createBusinessError('批量更新称重重量失败,波次下无有效运单记录', 500); + } + + // 写入操作日志 + await this._writeWeighActionLog({ + waveId, + waveNo, + weight, + warehouseId, + successCount, + totalCount, + }); + + return { + wave_id: waveId, + wave_no: waveNo, + weighing_weight: weight, + success_count: successCount, + total_count: totalCount, + }; + } + + /** + * 写入称重操作日志到 wms_wave_pick_action_log(内部方法)。 + * + * @param {Object} params 日志参数。 + * @param {number} [params.orderId] 订单ID(单订单称重场景)。 + * @param {string} [params.waybillCode] 运单号(单订单称重场景)。 + * @param {number} [params.waveId] 波次ID(团购批量称重场景)。 + * @param {string} [params.waveNo] 波次号(团购批量称重场景)。 + * @param {number} params.weight 称重重量。 + * @param {number} params.warehouseId 仓库ID。 + * @param {number} [params.successCount] 批量更新成功数。 + * @param {number} [params.totalCount] 批量更新总数。 + * @return {Promise} 无返回值。 + */ + async _writeWeighActionLog(params = {}) { + const { + orderId, + waybillCode, + waveId, + waveNo, + weight, + warehouseId, + successCount, + totalCount, + } = params; + + const ctxUser = this.ctx && this.ctx.user ? this.ctx.user : {}; + const operatorId = Number(ctxUser.employees_id || ctxUser.id || 0); + const operatorName = String( + ctxUser.employees_name || ctxUser.name || 'system' + ).trim(); + + const isBatch = waveId !== undefined && waveId !== null; + const tag = isBatch ? 'weigh_batch' : 'weigh'; + const requestId = `${tag}_${warehouseId}_${isBatch ? waveId : orderId}_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`; + + await this.ctx.model.query( + `INSERT INTO wms_wave_pick_action_log ( + task_id, + warehouse_id, + wave_id, + order_id, + sku_id, + location_id, + box_no, + cart_id, + qty_delta, + action_type, + request_id, + operator_id, + device_id, + seq_no, + snapshot + ) VALUES ( + :taskId, + :warehouseId, + :waveId, + :orderId, + :skuId, + :locationId, + :boxNo, + :cartId, + :qtyDelta, + :actionType, + :requestId, + :operatorId, + :deviceId, + :seqNo, + :snapshot + )`, + { + replacements: { + taskId: 0, + warehouseId: warehouseId || 0, + waveId: isBatch ? waveId : null, + orderId: isBatch ? null : (orderId || 0), + skuId: null, + locationId: null, + boxNo: null, + cartId: null, + qtyDelta: 0, + actionType: isBatch ? 'weigh_batch' : 'weigh', + requestId, + operatorId, + deviceId: null, + seqNo: 1, + snapshot: JSON.stringify(isBatch + ? { + wave_id: waveId, + wave_no: waveNo || '', + weighing_weight: weight, + success_count: successCount, + total_count: totalCount, + operator_name: operatorName, + } + : { + order_id: orderId, + waybill_code: waybillCode || '', + weighing_weight: weight, + operator_name: operatorName, + }), + }, + type: this.ctx.model.QueryTypes.INSERT, + } + ); + } + + /** + * 兼容处理:当前端将 wave_id 当作 order_id 传入时,尝试按波次 ID 处理。 + * + * 先用传入的 ID 在 wms_wave_batch 中查找波次: + * - 波次不存在 → 抛出"订单不存在"错误。 + * - 波次存在且 wave_type = 1(团购)→ 走团购批量称重逻辑。 + * - 波次存在但 wave_type ≠ 1 → 无法确定具体订单,抛出错误提示传入正确的 order_id。 + * + * @param {number} waveIdLike 可能是 wave_id 的数值。 + * @param {string} waybillCode 运单号(兼容参数,本路径不使用)。 + * @param {number} weight 称重重量。 + * @param {number|null} warehouseId 仓库ID。 + * @param {Object} orderDeliveryModel 订单 Sequelize 模型实例。 + * @return {Promise} 团购批量更新结果。 + * @throws {Error} 波次不存在或非团购波次时抛出业务错误。 + */ + async _tryWaveCompatibility(waveIdLike, waybillCode, weight, warehouseId, orderDeliveryModel) { + const waveBatchModel = this.ctx.model && this.ctx.model.WaveBatch; + if (!waveBatchModel || typeof waveBatchModel.findOne !== 'function') { + throw this.createBusinessError('订单不存在', 404); + } + + const waveRow = await waveBatchModel.findOne({ + where: { wave_id: waveIdLike, warehouse_id: warehouseId }, + attributes: [ 'wave_id', 'wave_no', 'wave_type' ], + raw: true, + }); + + // 波次也不存在 → 报订单不存在 + if (!waveRow) { + throw this.createBusinessError('订单不存在', 404); + } + + // 非团购波次 → 无法确定具体订单,提示前端传入正确的 order_id + if (Number(waveRow.wave_type) !== 1) { + throw this.createBusinessError( + `传入的 ID ${waveIdLike} 对应波次(wave_no: ${waveRow.wave_no}),非团购波次,请传入正确的 order_id`, + 400 + ); + } + + // 团购波次 → 批量设置同一重量 + return await this._updateWaveOrderWeight( + waveIdLike, + String(waveRow.wave_no || ''), + weight, + warehouseId, + orderDeliveryModel + ); + } + /** * 绑定订单快递记录的包材信息。 * @param {Object} payload 入参对象。 diff --git a/app/service/systems/order_print.js b/app/service/systems/order_print.js index 29c696a..8a2bc9d 100644 --- a/app/service/systems/order_print.js +++ b/app/service/systems/order_print.js @@ -173,9 +173,14 @@ class OrderPrintSystemService extends OrderBaseService { } /** - * 批量补查打印所需的拣货明细。 + * 批量补查打印所需的拣货明细,并注入商品多条码。 * * 优先使用 wms_picking.space_name,只有缺失时才查询库位表,减少额外 SQL。 + * 同时从 wms_stock_barcodes 表批量查询每个 stock_id 对应的全部条码, + * 注入到打印项的 barcodes 数组中,供 resolveItemBarcodeText 优先读取。 + * + * stock_id 优先读取 wms_order_items.stock_id 列,兜底读取 item_snapshot 内的 stock_id, + * 确保不同来源的订单明细都能正确关联到条码数据。 * * @param {Array} orderRows 订单列表。 * @param {number} warehouseId 仓库ID。 @@ -232,7 +237,7 @@ class OrderPrintSystemService extends OrderBaseService { [Op.in]: orderItemIds, }, }, - attributes: [ 'id', 'order_id', 'item_code', 'item_name', 'plan_qty', 'item_snapshot' ], + attributes: [ 'id', 'order_id', 'item_code', 'item_name', 'plan_qty', 'item_snapshot', 'stock_id' ], raw: true, }) : []; @@ -279,6 +284,10 @@ class OrderPrintSystemService extends OrderBaseService { pickingRowsByOrderId.set(orderId, list); } + // 阶段一:构建所有打印项并收集 stock_id + const printItemsByOrderId = new Map(); + const allStockIds = new Set(); + for (const orderRow of rows) { const orderId = Number(orderRow && orderRow.id || 0); const pickingList = pickingRowsByOrderId.get(orderId) || []; @@ -312,6 +321,12 @@ class OrderPrintSystemService extends OrderBaseService { sku: itemSnapshot.sku, }, [ 'barcode', 'item_barcode', 'bar_code', 'item_code', 'sku_code', 'sku' ]); const quantity = Number(pickingRow && pickingRow.quantity || orderItemRow.plan_qty || 0); + // 优先使用列 stock_id,兜底使用 item_snapshot 内的 stock_id + const stockId = Number(orderItemRow.stock_id || itemSnapshot.stock_id || 0); + + if (stockId > 0) { + allStockIds.add(stockId); + } return { order_item_id: orderItemId, @@ -319,6 +334,7 @@ class OrderPrintSystemService extends OrderBaseService { barcode, quantity: quantity > 0 ? quantity : 0, pick_location: pickLocation, + stock_id: stockId > 0 ? stockId : undefined, }; }).filter(item => { return String(item.item_name || '').trim() @@ -330,6 +346,65 @@ class OrderPrintSystemService extends OrderBaseService { continue; } + printItemsByOrderId.set(orderId, printItems); + } + + // 阶段二:批量查询 wms_stock_barcodes 获取所有条码 + const barcodeMap = new Map(); + const uniqueStockIds = Array.from(allStockIds); + + if (uniqueStockIds.length > 0) { + const stockBarcodeModel = this.ctx.model && this.ctx.model.StockBarcode; + + if (stockBarcodeModel && typeof stockBarcodeModel.findAll === 'function') { + const barcodeRows = await stockBarcodeModel.findAll({ + where: { + stock_id: { + [Op.in]: uniqueStockIds, + }, + }, + attributes: [ 'stock_id', 'barcode' ], + raw: true, + }); + + for (const item of Array.isArray(barcodeRows) ? barcodeRows : []) { + const stockId = Number(item && item.stock_id || 0); + const code = String(item && item.barcode || '').trim(); + + if (!stockId || !code) { + continue; + } + + if (!barcodeMap.has(stockId)) { + barcodeMap.set(stockId, []); + } + + barcodeMap.get(stockId).push(code); + } + } + } + + // 阶段三:注入条码并构建结果映射 + for (const orderRow of rows) { + const orderId = Number(orderRow && orderRow.id || 0); + const printItems = printItemsByOrderId.get(orderId); + + if (!printItems) { + continue; + } + + // 为每条打印项注入 barcodes 数组,供 resolveItemBarcodeText 优先读取 + for (const item of printItems) { + const stockId = item.stock_id; + + if (stockId && barcodeMap.has(stockId)) { + item.barcodes = barcodeMap.get(stockId); + } + + // 清理内部字段,避免污染 JSON 输出 + delete item.stock_id; + } + resultMap.set(orderId, { ...orderRow, items: JSON.stringify(printItems), diff --git a/app/service/systems/pick.js b/app/service/systems/pick.js index c8cc1d3..86b3ea6 100644 --- a/app/service/systems/pick.js +++ b/app/service/systems/pick.js @@ -1668,7 +1668,7 @@ class PickSystemService extends Service { throw this.createBusinessError('mode 参数不合法,仅支持 1(全部确认) 或 2(部分确认)', 400); } - const { operatorId, warehouseId } = this.resolveOperatorContext(); + const { operatorId, operatorName, warehouseId } = this.resolveOperatorContext(); if (!Number.isInteger(operatorId) || operatorId <= 0) { throw this.createBusinessError('未获取到操作人上下文', 401); } @@ -1682,11 +1682,12 @@ class PickSystemService extends Service { throw this.createBusinessError('任务已完成或已取消,无法再次提交', 400); } - // source=2 表示后台抓取创建的任务,必须先绑定拣货车才能提交 + // source=1(PDA抓取创建)的任务必须先绑定拣货车才能提交 + // source=2(扫描进任务/后台抓取)不强制要求绑定拣货车 const taskSource = Number(taskRow && taskRow.source || 0); const taskCartId = Number(taskRow && taskRow.current_cart_id || 0); - if (taskSource === 2 && taskCartId <= 0) { - throw this.createBusinessError('后台抓取任务必须先绑定拣货车才能提交', 400); + if (taskSource === 1 && taskCartId <= 0) { + throw this.createBusinessError('PDA抓取任务必须先绑定拣货车才能提交', 400); } const transaction = await ctx.model.transaction(); @@ -1841,6 +1842,19 @@ class PickSystemService extends Service { } await transaction.commit(); + + // 写入操作日志 + await this._writePickCompleteActionLog({ + taskId, + warehouseId, + operatorId, + operatorName, + targetOrderIds, + mode, + isCompleted: progress.isCompleted, + progress, + }); + return { task_id: taskId, mode, @@ -1858,6 +1872,103 @@ class PickSystemService extends Service { } } + /** + * 写入拣货完成操作日志到 wms_wave_pick_action_log(内部方法)。 + * + * @param {Object} params 日志参数。 + * @param {number} params.taskId 波次拣货任务ID。 + * @param {number} params.warehouseId 仓库ID。 + * @param {number} params.operatorId 操作人ID。 + * @param {string} params.operatorName 操作人名称。 + * @param {Array} params.targetOrderIds 确认完成的订单ID列表。 + * @param {number} params.mode 提交模式(1全部确认 2部分确认)。 + * @param {boolean} params.isCompleted 任务是否全部完成。 + * @param {Object} params.progress 任务进度信息。 + * @return {Promise} 无返回值。 + */ + async _writePickCompleteActionLog(params = {}) { + const { + taskId, + warehouseId, + operatorId, + operatorName, + targetOrderIds, + mode, + isCompleted, + progress, + } = params; + + const requestId = `pick_complete_${warehouseId}_${taskId}_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`; + + await this.ctx.model.query( + `INSERT INTO wms_wave_pick_action_log ( + task_id, + warehouse_id, + wave_id, + order_id, + sku_id, + location_id, + box_no, + cart_id, + qty_delta, + action_type, + request_id, + operator_id, + device_id, + seq_no, + snapshot + ) VALUES ( + :taskId, + :warehouseId, + :waveId, + :orderId, + :skuId, + :locationId, + :boxNo, + :cartId, + :qtyDelta, + :actionType, + :requestId, + :operatorId, + :deviceId, + :seqNo, + :snapshot + )`, + { + replacements: { + taskId: taskId || 0, + warehouseId: warehouseId || 0, + waveId: null, + orderId: Array.isArray(targetOrderIds) && targetOrderIds.length > 0 ? targetOrderIds[0] : null, + skuId: null, + locationId: null, + boxNo: null, + cartId: null, + qtyDelta: 0, + actionType: 'pick_complete', + requestId, + operatorId: operatorId || 0, + deviceId: null, + seqNo: 1, + snapshot: JSON.stringify({ + task_id: taskId, + mode, + confirmed_order_ids: targetOrderIds, + confirmed_order_count: Array.isArray(targetOrderIds) ? targetOrderIds.length : 0, + is_completed: isCompleted, + progress: { + total_orders: progress && progress.totalOrders, + picked_orders: progress && progress.pickedOrders, + pending_orders: progress && progress.pendingOrders, + }, + operator_name: operatorName || 'system', + }), + }, + type: this.ctx.model.QueryTypes.INSERT, + } + ); + } + /** * PDA 扫码查询拣货车信息。 * diff --git a/database/migrations/20260608-add-api-permissions.js b/database/migrations/20260608-add-api-permissions.js new file mode 100644 index 0000000..a14c03c --- /dev/null +++ b/database/migrations/20260608-add-api-permissions.js @@ -0,0 +1,243 @@ +'use strict'; + +/** + * 补齐 wms_permission 表的 API 权限记录: + * 1. 新增约 50 条 type='api' 的权限记录(幂等:先查后插) + * 2. 修正 28 条现有记录的 meta_title(原值统一为"获取审核信息接口") + * + * 幂等设计: + * - 新增:先查询 path + type='api' 是否已存在,已存在则跳过 + * - 修正:UPDATE ... WHERE id = N AND meta_title = '获取审核信息接口' + */ + +const TABLE = 'wms_permission'; + +/** + * 批量查询指定 path 是否已存在 type='api' 的记录。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {string[]} paths 待查询的 path 列表 + * @return {Promise>} 已存在的 path 集合 + */ +const getExistingApiPaths = async (queryInterface, paths) => { + const placeholders = paths.map(() => '?').join(', '); + const [ rows ] = await queryInterface.sequelize.query( + `SELECT path FROM \`${TABLE}\` WHERE type = 'api' AND path IN (${placeholders})`, + { replacements: paths } + ); + return new Set(rows.map(r => r.path)); +}; + +/** + * 正向迁移。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} 无返回值 + */ +module.exports.up = async queryInterface => { + // ─── 1. 新增 50 条 API 权限 ───────────────────────────────── + const newPermissions = [ + // warehouse 模块 + { path: 'warehouse.getWarehouseZones', meta_title: '获取所有仓库' }, + { path: 'warehouse.create', meta_title: '创建实体库' }, + { path: 'warehouse.update', meta_title: '更新仓库元素' }, + { path: 'warehouse.delete', meta_title: '删除仓库元素' }, + { path: 'warehouse.toggleActive', meta_title: '切换仓库元素启用状态' }, + { path: 'warehouse.getPath', meta_title: '获取仓库路径' }, + { path: 'warehouse.getPickPath', meta_title: '获取拣货路径' }, + { path: 'warehouse.updateRackPosition', meta_title: '更新货架位置' }, + { path: 'warehouse.recalculatePickPath', meta_title: '重算拣货路径' }, + { path: 'warehouse.updateNeighbors', meta_title: '更新相邻仓位' }, + { path: 'warehouse.getAreaRacks', meta_title: '获取区域货架' }, + { path: 'warehouse.getWarehouseTree', meta_title: '获取仓库树' }, + { path: 'warehouse.getChildren', meta_title: '获取仓库子元素' }, + { path: 'warehouse.updateSpaceInfo', meta_title: '修改仓位信息' }, + { path: 'warehouse.batchUpdateSpaceInfo', meta_title: '批量修改仓位信息' }, + { path: 'warehouse.exportRackSpaces', meta_title: '导出货架仓位' }, + // shops 模块 + { path: 'shops.list', meta_title: '店铺列表' }, + { path: 'shops.add', meta_title: '新增店铺' }, + { path: 'shops.del', meta_title: '删除店铺' }, + { path: 'shops.edit', meta_title: '编辑店铺' }, + { path: 'shops.GetAuthorizeSessionKey', meta_title: '获取授权SessionKey' }, + // stock.warehouse 模块 + { path: 'stock.warehouse.saveWarehouseStock', meta_title: '保存商品资料' }, + { path: 'stock.warehouse.createWarehouseStock', meta_title: '创建仓库商品' }, + { path: 'stock.warehouse.import', meta_title: '商品导入' }, + { path: 'stock.warehouse.saveWarehouseStockBarcode', meta_title: '修改商品条码' }, + { path: 'stock.warehouse.bindItem', meta_title: '绑定货主商品' }, + { path: 'stock.warehouse.unbindItem', meta_title: '解绑货主商品' }, + { path: 'stock.warehouse.handleBatchDelete', meta_title: '批量删除仓库商品' }, + { path: 'stock.warehouse.handleBatchChange', meta_title: '批量修改商品' }, + // index 模块 + { path: 'index.ReferenceFile', meta_title: '图片引用设置' }, + { path: 'index.test', meta_title: '测试接口' }, + { path: 'index.getShopList', meta_title: '获取仓库店铺列表' }, + { path: 'index.getShopExpressList', meta_title: '获取店铺签约快递' }, + { path: 'index.createPlatformOauthReservation', meta_title: '创建平台授权预留码' }, + // order 模块 + { path: 'order.bindExpressPackageMaterial', meta_title: '绑定快递包材' }, + { path: 'order.pullReviewDataByWaybill', meta_title: '按运单拉取复核数据' }, + // order.wave 模块 + { path: 'order.wave.waveStrategyCreate', meta_title: '波次策略新增' }, + { path: 'order.wave.waveStrategyUpdate', meta_title: '波次策略修改' }, + { path: 'order.wave.wavePickTaskCancel', meta_title: '拣货任务取消' }, + { path: 'order.wave.previewWaveStrategyNextFetchOrderCount', meta_title: '预演策略抓取数量' }, + // order.* 明细模块 + { path: 'order.pendingOrder.detail', meta_title: '待处理订单明细' }, + { path: 'order.archiveOrder.detail', meta_title: '归档订单明细' }, + { path: 'order.deliveryOrder.detail', meta_title: '配送订单明细' }, + { path: 'order.deliveryExpectionOrder.detail', meta_title: '配送异常订单明细' }, + { path: 'order.entrustOrder.detail', meta_title: '委托外仓订单明细' }, + { path: 'order.reviewOrder.detail', meta_title: '待审核订单明细' }, + { path: 'order.outboundOrder.detail', meta_title: '待出库订单明细' }, + { path: 'order.expectionOrder.detail', meta_title: '异常订单明细' }, + // storage.inventory 模块 + { path: 'storage.inventory.quickPutaway', meta_title: '快递入库' }, + // store 模块 + { path: 'store.getStoreRoles', meta_title: '获取审核信息' }, + { path: 'store.auditApply', meta_title: '提交审核' }, + // storeWarehouse.store 模块 + { path: 'storeWarehouse.store.adjustPrintQuantity', meta_title: '货主余额变更' }, + { path: 'storeWarehouse.store.queryPrintQuantityLogs', meta_title: '货主面单余额查询' }, + ]; + + const allPaths = newPermissions.map(p => p.path); + const existingPaths = await getExistingApiPaths(queryInterface, allPaths); + + const toInsert = newPermissions.filter(p => !existingPaths.has(p.path)); + + if (toInsert.length > 0) { + // 构建批量 INSERT 语句,name 与 path 保持一致 + const values = toInsert + .map( + p => `('${p.path.replace(/'/g, "\\'")}', '${p.path.replace(/'/g, "\\'")}', '${p.meta_title.replace(/'/g, "\\'")}', 'api', 1, NOW(), NOW())` + ) + .join(',\n'); + + await queryInterface.sequelize.query(` + INSERT INTO \`${TABLE}\` (path, name, meta_title, type, status, created_at, update_at) + VALUES ${values} + `); + } + + console.log( + `[Migration] wms_permission API 权限新增:共 ${newPermissions.length} 条,` + + `已存在 ${newPermissions.length - toInsert.length} 条,实际插入 ${toInsert.length} 条` + ); + + // ─── 2. 修正 28 条现有记录的 meta_title ──────────────────── + const corrections = [ + { id: 52, meta_title: '获取审核信息' }, + { id: 84, meta_title: '获取COS上传配置' }, + { id: 85, meta_title: '获取快递列表' }, + { id: 86, meta_title: '自动翻译新键' }, + { id: 87, meta_title: '上传成功通知' }, + { id: 88, meta_title: '获取订单模型列表' }, + { id: 89, meta_title: '绑定货主商品到仓库' }, + { id: 90, meta_title: '创建禁售规则' }, + { id: 91, meta_title: '创建单位' }, + { id: 92, meta_title: '创建仓库商品' }, + { id: 93, meta_title: '删除禁售规则' }, + { id: 94, meta_title: '删除单位' }, + { id: 95, meta_title: '批量修改商品' }, + { id: 96, meta_title: '批量删除商品' }, + { id: 97, meta_title: '保存商品资料' }, + { id: 98, meta_title: '修改商品条码' }, + { id: 99, meta_title: '解除绑定货主商品' }, + { id: 100, meta_title: '添加收货明细' }, + { id: 101, meta_title: '删除收货明细' }, + { id: 102, meta_title: '保存收货单' }, + { id: 103, meta_title: '创建货架' }, + { id: 104, meta_title: '创建货架含仓位' }, + { id: 105, meta_title: '重算拣货路径' }, + { id: 106, meta_title: '更新相邻仓位' }, + { id: 107, meta_title: '更新货架位置' }, + { id: 108, meta_title: '获取商品信息' }, + { id: 306, meta_title: '获取订单模型列表' }, + { id: 307, meta_title: '获取区域货架' }, + ]; + + let correctedCount = 0; + for (const { id, meta_title } of corrections) { + const [ result ] = await queryInterface.sequelize.query( + `UPDATE \`${TABLE}\` SET meta_title = :meta_title, update_at = NOW() + WHERE id = :id AND meta_title = '获取审核信息接口'`, + { replacements: { id, meta_title } } + ); + // result 为 affectedRows(MySQL)或 rowCount + if (result && (result.affectedRows > 0 || result.rowCount > 0 || result.changedRows > 0)) { + correctedCount++; + } + } + + console.log( + `[Migration] wms_permission meta_title 修正:共 ${corrections.length} 条,` + + `实际修正 ${correctedCount} 条` + ); + + // ─── 3. 修正 10 条 meta_title 为 "path+接口" 格式的记录 ────── + const pathLikeCorrections = [ + { id: 347, path: 'warehouse.getChildren', meta_title: '获取仓库子元素' }, + { id: 348, path: 'warehouse.toggleActive', meta_title: '切换仓库启用状态' }, + { id: 349, path: 'warehouse.getPath', meta_title: '获取仓库路径' }, + { id: 350, path: 'warehouse.getPickPath', meta_title: '获取拣货路径' }, + { id: 351, path: 'storage.receiving.save', meta_title: '保存收货单' }, + { id: 367, path: 'shops.list', meta_title: '店铺列表' }, + { id: 368, path: 'shops.add', meta_title: '新增店铺' }, + { id: 369, path: 'shops.del', meta_title: '删除店铺' }, + { id: 370, path: 'shops.edit', meta_title: '编辑店铺' }, + { id: 371, path: 'shop.GetAuthorizeSessionKey', meta_title: '获取授权SessionKey' }, + ]; + + let pathLikeCorrectedCount = 0; + for (const { id, meta_title } of pathLikeCorrections) { + const [ result ] = await queryInterface.sequelize.query( + `UPDATE \`${TABLE}\` SET meta_title = :meta_title, update_at = NOW() + WHERE id = :id AND meta_title LIKE '%接口'`, + { replacements: { id, meta_title } } + ); + if (result && (result.affectedRows > 0 || result.rowCount > 0 || result.changedRows > 0)) { + pathLikeCorrectedCount++; + } + } + + console.log( + `[Migration] wms_permission "path+接口" 格式修正:共 ${pathLikeCorrections.length} 条,` + + `实际修正 ${pathLikeCorrectedCount} 条` + ); + + // ── 3b. 修正 setting.permission.add/delete/update 的 meta_title ── + const permissionCrudCorrections = [ + { id: 119, path: 'setting.permission.add', meta_title: '新增权限' }, + { id: 120, path: 'setting.permission.delete', meta_title: '删除权限' }, + { id: 121, path: 'setting.permission.update', meta_title: '修改权限' }, + ]; + + let permCrudCorrectedCount = 0; + for (const { id, path, meta_title } of permissionCrudCorrections) { + const [ result ] = await queryInterface.sequelize.query( + `UPDATE \`${TABLE}\` SET meta_title = :meta_title, update_at = NOW() + WHERE id = :id AND meta_title = :oldMetaTitle`, + { replacements: { id, meta_title, oldMetaTitle: path } } + ); + if (result && (result.affectedRows > 0 || result.rowCount > 0 || result.changedRows > 0)) { + permCrudCorrectedCount++; + } + } + + console.log( + `[Migration] wms_permission setting.permission CRUD 修正:共 ${permissionCrudCorrections.length} 条,` + + `实际修正 ${permCrudCorrectedCount} 条` + ); +}; + +/** + * 回滚迁移:无法安全回滚 meta_title 修正与新增记录(可能已被后续业务引用), + * 仅输出提示信息。 + * @return {Promise} 无返回值 + */ +module.exports.down = async () => { + console.log( + '[Migration] wms_permission API 权限补齐脚本无安全回滚方案,' + + '如需回滚请手动处理 meta_title 与新增记录。' + ); +}; diff --git a/database/migrations/20260608033847-set-role-preset-permissions.js b/database/migrations/20260608033847-set-role-preset-permissions.js new file mode 100644 index 0000000..b2fe7ce --- /dev/null +++ b/database/migrations/20260608033847-set-role-preset-permissions.js @@ -0,0 +1,169 @@ +'use strict'; + +/** + * 系统角色(is_system=1)预设权限迁移 + * + * 背景: + * wms_permission 表已扩容到 349 条(6 种类型),当前系统角色的 permissions + * 字段(JSON 数组)覆盖范围不足,新增的 API/pda_pages/workerstation_pages 等 + * 权限未被纳入旧的角色预设中。 + * + * 范围: + * - 仅更新 is_system=1 的角色(12 个,排除 id=2 仓库管理员和 id=7 超级管理员, + * 二者保持 "*" 不变) + * - 仅使用 status=1 的活跃权限 + * - 不修改 wms_permission 表 + * + * 幂等设计: + * UPDATE wms_role SET permissions = ? WHERE id = ? AND is_system = 1 + */ + +const TABLE = 'wms_role'; + +/** @type {{id: number, role_code: string, permissions: string, desc: string}[]} */ +const ROLE_UPDATES = [ + { + id: 5, + role_code: 'store_admin_default', + name: '货主管理员', + // 货主管理员:web_pages(设置4,货主17,成员审核50,货主列表244,店铺模块366), block(商家基础数据48), api(货主/店铺相关 52,53,308,363,364,365,367-372,376,379,380) + permissions: '[4,17,48,50,52,53,244,308,363,364,365,366,367,368,369,370,371,372,376,379,380]', + old: '[4,48,50,52,53]', + }, + { + id: 8, + role_code: '2', + name: '经理', + // 经理:全部 status=1 权限(206条),排除权限管理(5,7,119,120,121)、测试(187,245,378) + permissions: '[1,4,6,8,9,11,12,13,14,15,16,17,18,19,20,21,22,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,43,44,45,46,47,48,49,50,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,244,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279,281,283,290,291,292,293,294,295,296,297,298,299,300,303,304,305,306,307,308,309,333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356,357,358,359,360,361,363,364,365,366,367,368,369,370,371,372,373,374,375,376,377,379,380,381,382,383,384]', + old: '[4-121,244]', + }, + { + id: 26, + role_code: 'warehouse', + name: '仓库组-主管', + // 仓库组-主管:全部活跃权限排除权限管理(5,6,7,119,120,121)、财务(28,31-37)、数据模块(16)、测试(187,245,378) + permissions: '[1,4,8,9,11,12,13,14,15,17,18,19,20,21,22,24,25,26,27,29,30,38,39,40,41,43,44,45,46,47,48,49,50,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,244,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279,281,283,290,291,292,293,294,295,296,297,298,299,300,303,304,305,306,307,308,309,333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356,357,358,359,360,361,363,364,365,366,367,368,369,370,371,372,373,374,375,376,377,379,380,381,382,383,384]', + old: '[4-121]', + }, + { + id: 27, + role_code: 'warehouse_role', + name: '仓库组-员工', + // 仓库组-员工:同仓库组-主管,排除权限管理、财务、数据模块、测试 + permissions: '[1,4,8,9,11,12,13,14,15,17,18,19,20,21,22,24,25,26,27,29,30,38,39,40,41,43,44,45,46,47,48,49,50,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,244,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279,281,283,290,291,292,293,294,295,296,297,298,299,300,303,304,305,306,307,308,309,333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356,357,358,359,360,361,363,364,365,366,367,368,369,370,371,372,373,374,375,376,377,379,380,381,382,383,384]', + old: '[4-121]', + }, + { + id: 28, + role_code: '05', + name: '客服组-主管', + // 客服组-主管:排除权限管理(5,6,7,119,120,121)、财务(28,31-37)、数据(16)、测试(187,245,378)、PDA拣货/复核/打包/补货、工位称重/退件 + permissions: '[1,4,8,9,11,12,13,14,15,17,18,19,20,21,22,24,25,26,27,29,30,38,39,40,41,43,44,45,46,47,48,49,50,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,244,254,255,256,278,281,283,290,291,292,293,294,295,296,297,298,299,300,303,304,305,306,307,308,309,333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356,357,358,361,363,364,365,366,367,368,369,370,371,372,373,374,375,376,377,379,380,381,382,383,384]', + old: '[1,4-121,244-336]', + }, + { + id: 30, + role_code: '04', + name: '客服组-员工', + // 客服组-员工:同客服组-主管 + permissions: '[1,4,8,9,11,12,13,14,15,17,18,19,20,21,22,24,25,26,27,29,30,38,39,40,41,43,44,45,46,47,48,49,50,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,244,254,255,256,278,281,283,290,291,292,293,294,295,296,297,298,299,300,303,304,305,306,307,308,309,333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356,357,358,361,363,364,365,366,367,368,369,370,371,372,373,374,375,376,377,379,380,381,382,383,384]', + old: '[1,4-121,244-336]', + }, + { + id: 29, + role_code: '03', + name: '生产组-主管', + // 生产组-主管:全部活跃权限排除权限管理(5,6,7,119,120,121)、财务(28,31-37)、数据(16)、测试(187,245,378) + permissions: '[1,4,8,9,11,12,13,14,15,17,18,19,20,21,22,24,25,26,27,29,30,38,39,40,41,43,44,45,46,47,48,49,50,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,244,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279,281,283,290,291,292,293,294,295,296,297,298,299,300,303,304,305,306,307,308,309,333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356,357,358,359,360,361,363,364,365,366,367,368,369,370,371,372,373,374,375,376,377,379,380,381,382,383,384]', + old: '[4-121]', + }, + { + id: 31, + role_code: '002', + name: '生产组-员工', + // 生产组-员工:同生产组-主管 + permissions: '[1,4,8,9,11,12,13,14,15,17,18,19,20,21,22,24,25,26,27,29,30,38,39,40,41,43,44,45,46,47,48,49,50,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,244,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279,281,283,290,291,292,293,294,295,296,297,298,299,300,303,304,305,306,307,308,309,333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356,357,358,359,360,361,363,364,365,366,367,368,369,370,371,372,373,374,375,376,377,379,380,381,382,383,384]', + old: '[4-121]', + }, + { + id: 32, + role_code: '021', + name: '生产组-拣货', + // 生产组-拣货:排除复核发货(266-269)、打包(270-276)、权限管理(5,6,7,119,120,121)、财务(28,31-37)、数据(16)、测试(187,245,378)、工位站(356,359,360) + permissions: '[1,4,8,9,11,12,13,14,15,17,18,19,20,21,22,24,25,26,27,29,30,38,39,40,41,43,44,45,46,47,48,49,50,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,244,254,255,256,257,258,259,260,261,262,263,264,265,277,278,279,281,283,290,291,292,293,294,295,296,297,298,299,300,303,304,305,306,307,308,309,333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,357,358,361,363,364,365,366,367,368,369,370,371,372,373,374,375,376,377,379,380,381,382,383,384]', + old: '[4-121]', + }, + { + id: 33, + role_code: '0113', + name: '拣货组组员', + // 拣货组组员:同生产组-拣货 + permissions: '[1,4,8,9,11,12,13,14,15,17,18,19,20,21,22,24,25,26,27,29,30,38,39,40,41,43,44,45,46,47,48,49,50,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,244,254,255,256,257,258,259,260,261,262,263,264,265,277,278,279,281,283,290,291,292,293,294,295,296,297,298,299,300,303,304,305,306,307,308,309,333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,357,358,361,363,364,365,366,367,368,369,370,371,372,373,374,375,376,377,379,380,381,382,383,384]', + old: '[4-121]', + }, + { + id: 34, + role_code: '024', + name: '生产组-复核', + // 生产组-复核:排除拣货(257-265)、打包(270-276)、权限管理(5,6,7,119,120,121)、财务(28,31-37)、数据(16)、测试(187,245,378) + permissions: '[1,4,8,9,11,12,13,14,15,17,18,19,20,21,22,24,25,26,27,29,30,38,39,40,41,43,44,45,46,47,48,49,50,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,244,254,255,256,266,267,268,269,277,278,279,281,283,290,291,292,293,294,295,296,297,298,299,300,303,304,305,306,307,308,309,333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356,357,358,359,360,361,363,364,365,366,367,368,369,370,371,372,373,374,375,376,377,379,380,381,382,383,384]', + old: '[4-121]', + }, + { + id: 36, + role_code: '0211', + name: '其他普工', + // 其他普工:排除设置模块(4-9,40,41,80,81,336,366,375)、财务、数据、测试、系统、敏感API、仓库管理API、视频 + permissions: '[1,11,12,13,14,15,17,18,19,20,21,22,24,25,26,27,29,30,38,39,43,44,45,46,48,49,50,54,55,57,58,61,62,63,64,65,66,67,68,69,70,71,72,74,75,76,77,78,79,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,108,244,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279,281,283,290,291,292,293,294,295,296,297,298,299,300,303,304,305,306,307,309,333,334,335,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,357,358,361,364,365,370,373,374,376,377,379,380,381,382,383,384]', + old: '[4-121]', + } +]; + +/** + * 正向迁移:更新 12 个系统角色的 permissions 字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} 无返回值 + */ +module.exports.up = async queryInterface => { + let updatedCount = 0; + + for (const role of ROLE_UPDATES) { + const [ result ] = await queryInterface.sequelize.query( + `UPDATE \`${TABLE}\` SET permissions = :permissions, updated_at = NOW() + WHERE id = :id AND is_system = 1`, + { replacements: { id: role.id, permissions: role.permissions } } + ); + if (result && (result.affectedRows > 0 || result.rowCount > 0 || result.changedRows > 0)) { + updatedCount++; + } + } + + console.log( + `[Migration] wms_role 预设权限更新:共 ${ROLE_UPDATES.length} 个角色,实际更新 ${updatedCount} 个` + ); +}; + +/** + * 回滚迁移:恢复到旧的 permissions 值。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} 无返回值 + */ +module.exports.down = async queryInterface => { + let revertedCount = 0; + + for (const role of ROLE_UPDATES) { + const [ result ] = await queryInterface.sequelize.query( + `UPDATE \`${TABLE}\` SET permissions = :permissions, updated_at = NOW() + WHERE id = :id AND is_system = 1`, + { replacements: { id: role.id, permissions: role.old } } + ); + if (result && (result.affectedRows > 0 || result.rowCount > 0 || result.changedRows > 0)) { + revertedCount++; + } + } + + console.log( + `[Migration] wms_role 预设权限回滚:共 ${ROLE_UPDATES.length} 个角色,实际回滚 ${revertedCount} 个` + ); +}; diff --git a/methods/changes/system.json b/methods/changes/system.json index 004ed34..8ec9f6e 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -3143,5 +3143,20 @@ "仅同步文档,不修改任何业务代码或实现。" ], "type": "updated" + }, + { + "version": "2026.06.08-system-15", + "date": "2026-06-08", + "summary": "新增 order.pendingOrder.manualWaybill 接口(手工录入运单号)", + "methods": [ + "order.pendingOrder.manualWaybill" + ], + "notes": [ + "为待处理订单手动录入运单号,写入 wms_order_express 表", + "仅允许 step 在 [1,2,3] 且 outbound_status 不为 'padding' 的订单操作", + "免权限(isNeedAuth: false),需登录", + "成功返回运单记录的 id、order_id、waybill_code、create_at" + ], + "type": "added" } ] diff --git a/methods/system.json b/methods/system.json index 3e5da59..54d20c7 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1,7 +1,7 @@ { "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", - "version": "0.3.19", + "version": "0.3.5", "updatedAt": "2026-06-08", "headers": [ { @@ -4736,6 +4736,88 @@ "message": "task_id 参数不能为空" } ] + }, + { + "method": "order.pendingOrder.manualWaybill", + "description": "手工录入运单号。为指定待处理订单创建一条运单记录(wms_order_express 表),仅允许 step 在 [1,2,3] 且 outbound_status 不为 'padding' 的订单操作。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "order_id", + "type": "number", + "required": true, + "source": "body", + "description": "订单 ID,必须为正整数" + }, + { + "name": "waybill_code", + "type": "string", + "required": true, + "source": "body", + "description": "运单号,非空字符串" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "创建的运单记录 ID" + }, + { + "name": "order_id", + "type": "number", + "required": true, + "description": "订单 ID" + }, + { + "name": "waybill_code", + "type": "string", + "required": true, + "description": "运单号" + }, + { + "name": "create_at", + "type": "string", + "required": true, + "description": "创建时间" + } + ], + "errors": [ + { + "code": 400, + "message": "order_id 必须为正整数" + }, + { + "code": 400, + "message": "waybill_code(运单号)不能为空" + }, + { + "code": 400, + "message": "订单不存在或不属于当前仓库" + }, + { + "code": 400, + "message": "订单当前步骤不在允许范围,仅允许待处理状态(step 1/2/3)的订单手工录入运单号" + }, + { + "code": 400, + "message": "订单已标记待出库,不允许手工录入运单号" + }, + { + "code": 500, + "message": "内部错误:OrderExpress 模型未加载或数据库写入失败" + } + ] } ] }, From 0b207a1c9c85d816bb08d3b1a7eba8295bd0ec39 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Wed, 10 Jun 2026 09:14:05 +0800 Subject: [PATCH 071/550] 1 --- app/model/store.js | 44 ++ app/schedule/auto_outbound_order.js | 50 +++ app/service/systemMethods/order/base.js | 19 +- app/service/systemMethods/order/index.js | 31 +- .../systemMethods/order/pendingOrder.js | 68 ++- app/service/systemMethods/order/wave.js | 2 +- app/service/systemMethods/outbound.js | 86 ++++ app/service/systems/delivery_order.js | 2 +- app/service/systems/notice/drivers/generic.js | 6 + app/service/systems/notice/drivers/wecom.js | 4 + app/service/systems/order_async.js | 13 +- app/service/systems/order_auto_outbound.js | 296 +++++++++++++ app/service/systems/order_express.js | 418 ++++++++++++++++-- app/service/systems/setting/warehouse.js | 15 + app/service/systems/stock_store.js | 133 +++++- app/service/systems/stock_transaction.js | 29 +- methods/changes/system.json | 61 +++ methods/system.json | 122 ++++- 18 files changed, 1293 insertions(+), 106 deletions(-) create mode 100644 app/schedule/auto_outbound_order.js create mode 100644 app/service/systemMethods/outbound.js create mode 100644 app/service/systems/order_auto_outbound.js diff --git a/app/model/store.js b/app/model/store.js index 8163a5f..2ec757d 100644 --- a/app/model/store.js +++ b/app/model/store.js @@ -28,6 +28,14 @@ module.exports = app => { */ const getDefaultInventoryWarningRules = () => DEFAULT_INVENTORY_WARNING_RULES.map(rule => ({ ...rule })); + const DEFAULT_AUTO_OUTBOUND_RULES = Object.freeze({ + enabled: false, + require_recheck: true, + require_pack: true, + require_weigh: true, + require_sync: true, + }); + const DEFAULT_SUBJECT_CONFIG = Object.freeze({ max_notice_webhook_count: DEFAULT_MAX_NOTICE_WEBHOOK_COUNT, max_wave_quantity: DEFAULT_MAX_WAVE_QUANTITY, @@ -38,6 +46,7 @@ module.exports = app => { group_wave_prefix: 'B', delete_order_wave_prefix: 'A', inventory_warning_rules: DEFAULT_INVENTORY_WARNING_RULES, + auto_outbound_rules: DEFAULT_AUTO_OUTBOUND_RULES, }); const normalizeSubjectConfigText = (value, defaultValue) => { @@ -116,12 +125,46 @@ module.exports = app => { }); }; + /** + * 规范化自动化出库规则配置。 + * + * @param {Object|undefined|null} rawRules 原始自动化出库规则。 + * @return {Object} 规范化后的自动化出库规则对象。 + */ + const normalizeAutoOutboundRules = rawRules => { + if (rawRules === undefined || rawRules === null || rawRules === '') { + return { ...DEFAULT_AUTO_OUTBOUND_RULES }; + } + + let parsed = rawRules; + if (typeof parsed === 'string') { + try { + parsed = JSON.parse(parsed); + } catch (error) { + return { ...DEFAULT_AUTO_OUTBOUND_RULES }; + } + } + + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { + return { ...DEFAULT_AUTO_OUTBOUND_RULES }; + } + + return { + enabled: normalizeBooleanFlag(parsed.enabled, 'auto_outbound_rules.enabled') === true, + require_recheck: parsed.require_recheck !== false, + require_pack: parsed.require_pack !== false, + require_weigh: parsed.require_weigh !== false, + require_sync: parsed.require_sync !== false, + }; + }; + /** * 规范化主体配置,确保默认值与字段约束一致。 * * @param {Object|string|null|undefined} rawValue 主体配置原始值。 * @return {Object} 规范化后的主体配置对象。 */ + const normalizeSubjectConfig = rawValue => { if (rawValue === undefined || rawValue === null || rawValue === '') { return { @@ -240,6 +283,7 @@ module.exports = app => { } normalized.inventory_warning_rules = normalizeInventoryWarningRules(parsed.inventory_warning_rules); + normalized.auto_outbound_rules = normalizeAutoOutboundRules(parsed.auto_outbound_rules); return normalized; }; diff --git a/app/schedule/auto_outbound_order.js b/app/schedule/auto_outbound_order.js new file mode 100644 index 0000000..8917efb --- /dev/null +++ b/app/schedule/auto_outbound_order.js @@ -0,0 +1,50 @@ +'use strict'; + +/** + * 自动化出库定时任务。 + * 每分钟在单 worker 中扫描一次:当订单满足仓库配置的自动化出库条件时, + * 自动标记出库并将订单状态更新为已完成。 + * + * 出库条件(由仓库 subject_config.auto_outbound_rules 控制): + * 1. 已复核:recheck_status = 'fin' + * 2. 已打包:pack_status = 'fin' + * 3. 已称重:wms_order_express.weighing_weight > 0 + * + * 各条件是否必须可由仓库配置独立控制。 + */ +module.exports = { + schedule: { + interval: '1m', + type: 'worker', + immediate: false, + disable: false, + }, + + /** + * 执行自动化出库任务。 + * + * @param {Object} ctx Egg 上下文。 + * @return {Promise} 无返回值。 + */ + async task(ctx) { + if (ctx.app._autoOutboundRunning) { + return; + } + + ctx.app._autoOutboundRunning = true; + + try { + const result = await ctx.service.systems.orderAutoOutbound.executeAutoOutbound(); + + if (result && result.totalProcessed > 0) { + ctx.logger.info( + `[auto-outbound-order] 本轮自动化出库完成,共处理 ${result.totalProcessed} 条订单` + ); + } + } catch (error) { + ctx.logger.error(`[auto-outbound-order] 自动化出库任务执行失败: ${error.message}`); + } finally { + ctx.app._autoOutboundRunning = false; + } + }, +}; diff --git a/app/service/systemMethods/order/base.js b/app/service/systemMethods/order/base.js index 7b6ef22..c56b44b 100644 --- a/app/service/systemMethods/order/base.js +++ b/app/service/systemMethods/order/base.js @@ -688,9 +688,10 @@ class OrderBaseService extends MainService { /** * 查询订单关联运单信息。 * @param {number|string} orderId 订单ID。 + * @param {Object} [order] 订单详情行,用于补充 sys_logistics_code / sys_logistics_name。 * @return {Promise} 运单信息列表。 */ - async getOrderExpressesByOrderId(orderId) { + async getOrderExpressesByOrderId(orderId, order) { const normalizedOrderId = Number(orderId || 0); if (!Number.isFinite(normalizedOrderId) || normalizedOrderId <= 0) { @@ -706,16 +707,28 @@ class OrderBaseService extends MainService { where: { order_id: normalizedOrderId, }, - attributes: [ 'waybill_code', 'logistics_code', 'logistics_name', 'logistics_interface_id' ], + attributes: [ 'waybill_code', 'logistics_code', 'logistics_name', 'logistics_interface_id', 'weighing_weight', 'business_key', 'create_at' ], order: [[ 'id', 'ASC' ]], raw: true, }); + const sysLogisticsCode = order && order.sys_logistics_code != null + ? String(order.sys_logistics_code).trim() + : ''; + const sysLogisticsName = order && order.sys_logistics_name != null + ? String(order.sys_logistics_name).trim() + : ''; + return (Array.isArray(rows) ? rows : []).map(row => ({ waybill_code: String(row && row.waybill_code || '').trim(), + weighing_weight: row && row.weighing_weight != null ? Number(row.weighing_weight) : null, + sys_logistics_code: sysLogisticsCode, + sys_logistics_name: sysLogisticsName, logistics_code: String(row && row.logistics_code || '').trim(), logistics_name: String(row && row.logistics_name || '').trim(), logistics_interface_id: row && row.logistics_interface_id == null ? null : Number(row.logistics_interface_id), + business_key: String(row && row.business_key || '').trim(), + create_at: row && row.create_at != null ? new Date(row.create_at).getTime() : null, })); } @@ -1169,7 +1182,7 @@ class OrderBaseService extends MainService { }); const orderItemImagesByStockId = await this.getOrderItemImagesByStockIds(orderItems); const orderItemsWithImages = this.attachImagesToOrderItems(orderItems, orderItemImagesByStockId); - const expresses = await this.getOrderExpressesByOrderId(orderId); + const expresses = await this.getOrderExpressesByOrderId(orderId, order); const logs = await this.getOrderOperationLogs(orderId); return { detail: order, diff --git a/app/service/systemMethods/order/index.js b/app/service/systemMethods/order/index.js index de51fcc..f10706c 100644 --- a/app/service/systemMethods/order/index.js +++ b/app/service/systemMethods/order/index.js @@ -425,14 +425,17 @@ class OrderIndexService extends OrderBaseService { * - 单运单订单:忽略传入 waybill_code,直接更新唯一记录。 * - 多运单订单:必须传入 waybill_code 且匹配到订单下记录。 * - 团购波次(wave_type = 1):将同一重量批量设置到该波次下所有订单的运单上。 + * - 运单号模式(order_id = 0):从运单号反查,必传 waybill_code。团购时按 wave_no + business_key 批量设置。 * * @param {Object} data 请求体。 - * @param {string} [data.waybill_code] 运单号,多运单场景必填。 - * @param {number|string} data.order_id 订单ID。 + * @param {string} [data.waybill_code] 运单号,多运单场景或运单号模式必填。 + * @param {number|string} data.order_id 订单ID,传 0 时切换为运单号模式。 * @param {number|string} data.weighing_weight 称重重量(kg)。 * @return {Promise} 统一成功/失败结构。 - * 单订单:{data: {order_id, waybill_code, weighing_weight}}; - * 团购批量:{data: {wave_id, wave_no, weighing_weight, success_count, total_count}}。 + * 订单模式单订单:{data: {order_id, waybill_code, weighing_weight}}; + * 订单模式团购批量:{data: {wave_id, wave_no, weighing_weight, total_weight, split_count, splits, store_name, sys_logistics_name}}; + * 运单号模式单运单:{data: {order_id, waybill_code, weighing_weight}}; + * 运单号模式团购批量:{data: {wave_id, wave_no, business_key, weighing_weight, total_weight, split_count, splits, store_name, sys_logistics_name}}。 */ async updateExpressWeighingWeight(data = {}) { const requestData = this.isPlainObject(data) ? data : {}; @@ -443,11 +446,21 @@ class OrderIndexService extends OrderBaseService { } = requestData; try { - const result = await this.service.systems.orderExpress.updateWeighingWeight({ - orderId, - waybillCode, - weighingWeight, - }); + let result; + if (Number(orderId) === 0) { + // 运单号模式:从运单号反查订单与波次 + result = await this.service.systems.orderExpress.updateWeighingWeightByWaybill({ + waybillCode, + weighingWeight, + }); + } else { + // 订单模式 + result = await this.service.systems.orderExpress.updateWeighingWeight({ + orderId, + waybillCode, + weighingWeight, + }); + } return this.success('ok', { data: result, diff --git a/app/service/systemMethods/order/pendingOrder.js b/app/service/systemMethods/order/pendingOrder.js index 06462f7..49442ee 100644 --- a/app/service/systemMethods/order/pendingOrder.js +++ b/app/service/systemMethods/order/pendingOrder.js @@ -100,7 +100,7 @@ class PendingOrderService extends OrderBaseService { }); const orderItemImagesByStockId = await this.getOrderItemImagesByStockIds(orderItems); const orderItemsWithImages = this.attachImagesToOrderItems(orderItems, orderItemImagesByStockId); - const expresses = await this.getOrderExpressesByOrderId(orderId); + const expresses = await this.getOrderExpressesByOrderId(orderId, order); return { detail: order, @@ -1644,7 +1644,8 @@ class PendingOrderService extends OrderBaseService { /** * 批量修改待处理订单的收件地址信息。 * - * 仅允许在未分配快递(post_status = 'none')时修改,至少提供一个地址字段。 + * 地址字段仅允许在未分配快递(post_status = 'none')时修改; + * remark 不受 post_status 限制,可独立或与地址字段同时传入。 * 支持批量操作,返回更新数量和受影响的订单 ID 列表。 * * @param {Object} data 请求体。 @@ -1658,6 +1659,7 @@ class PendingOrderService extends OrderBaseService { * @param {string} [data.area] 区/县。 * @param {string} [data.town] 镇/街道。 * @param {string} [data.detail_address] 详细地址。 + * @param {string} [data.remark] 订单留言/备注,对应 wms_order_delivery.remark,最大500字符。 * @return {Promise} 统一 success 包装的更新结果,含 updated_count 与 ids。 */ async updateAddress(data = {}) { @@ -1677,32 +1679,56 @@ class PendingOrderService extends OrderBaseService { 'name', 'mobile', 'tel', 'zip_code', 'province', 'city', 'area', 'town', 'detail_address', ]; - const updates = {}; + const addressUpdates = {}; for (const field of addressFields) { const value = requestData[field]; if (value !== undefined && value !== null && String(value).trim() !== '') { - updates[field] = String(value).trim(); + addressUpdates[field] = String(value).trim(); } } - if (Object.keys(updates).length === 0) { - throw new Error('至少需要提供一个地址字段进行修改'); + // 处理 remark 字段(不受 post_status 限制,最大500字符) + let remarkValue = null; + if (requestData.remark !== undefined && requestData.remark !== null) { + const trimmed = String(requestData.remark).trim(); + if (trimmed !== '') { + remarkValue = trimmed.substring(0, 500); + } } - updates.updated_at = new Date(); + const hasAddressUpdates = Object.keys(addressUpdates).length > 0; + if (!hasAddressUpdates && remarkValue === null) { + throw new Error('至少需要提供一个地址字段或备注进行修改'); + } const model = await this.getOrderModel('order', warehouseId); - const where = { - ...this.buildOrderWhere(orderIds, warehouseId), - post_status: 'none', - }; + const baseWhere = this.buildOrderWhere(orderIds, warehouseId); + const now = new Date(); - const [ affectedRows ] = await model.update(updates, { where }); - const count = Number(affectedRows || 0); + let addressUpdatedCount = 0; + let remarkUpdatedCount = 0; + + // 地址字段更新(受 post_status='none' 限制) + if (hasAddressUpdates) { + addressUpdates.updated_at = now; + const addressWhere = { ...baseWhere, post_status: 'none' }; + const [ rows ] = await model.update(addressUpdates, { where: addressWhere }); + addressUpdatedCount = Number(rows || 0); + } + + // remark 更新(不受 post_status 限制) + if (remarkValue !== null) { + const remarkUpdate = { remark: remarkValue, updated_at: now }; + const [ rows ] = await model.update(remarkUpdate, { where: baseWhere }); + remarkUpdatedCount = Number(rows || 0); + } // 记录操作日志 try { - const updatedFieldNames = Object.keys(updates).filter(k => k !== 'updated_at'); + const updatedFieldNames = [ + ...Object.keys(addressUpdates).filter(k => k !== 'updated_at'), + ...(remarkValue !== null ? [ 'remark' ] : []), + ]; await this.ctx.service.systems.operationLog.createOperationLog({ businessType: 'order', businessId: logWarehouseId, @@ -1712,8 +1738,10 @@ class PendingOrderService extends OrderBaseService { warehouseId: logWarehouseId, orderIds, updated_fields: updatedFieldNames, - updated_count: count, - message: `批量修改订单收件地址:订单ID [${orderIds.join(', ')}],更新字段 [${updatedFieldNames.join(', ')}],共更新 ${count} 条`, + updated_count: Math.max(addressUpdatedCount, remarkUpdatedCount), + address_updated_count: addressUpdatedCount, + remark_updated_count: remarkUpdatedCount, + message: `批量修改订单收件地址:订单ID [${orderIds.join(', ')}],更新字段 [${updatedFieldNames.join(', ')}],地址更新 ${addressUpdatedCount} 条,备注更新 ${remarkUpdatedCount} 条`, }, beforeChanges: null, }); @@ -1722,7 +1750,7 @@ class PendingOrderService extends OrderBaseService { } return this.success('ok', { - updated_count: count, + updated_count: Math.max(addressUpdatedCount, remarkUpdatedCount), ids: orderIds, }); } @@ -4434,10 +4462,10 @@ class PendingOrderService extends OrderBaseService { // 2. 查询订单并校验状态(待处理:step in [1,2,3] 且 outbound_status != 'padding') const model = await this.getOrderModel('order', warehouseId); - const where = this.buildOrderWhere([orderId], warehouseId); + const where = this.buildOrderWhere([ orderId ], warehouseId); const order = await model.findOne({ where, - attributes: ['id', 'step', 'outbound_status', 'warehouse_id'], + attributes: [ 'id', 'step', 'outbound_status', 'warehouse_id' ], raw: true, }); @@ -4445,7 +4473,7 @@ class PendingOrderService extends OrderBaseService { throw new Error(`订单 ${orderId} 不存在或不属于当前仓库`); } - const allowedSteps = new Set([1, 2, 3]); + const allowedSteps = new Set([ 1, 2, 3 ]); if (!allowedSteps.has(order.step)) { throw new Error(`订单 ${orderId} 当前步骤为 ${order.step},仅允许待处理状态(step 1/2/3)的订单手工录入运单号`); } diff --git a/app/service/systemMethods/order/wave.js b/app/service/systemMethods/order/wave.js index ede441b..7dc2c7d 100644 --- a/app/service/systemMethods/order/wave.js +++ b/app/service/systemMethods/order/wave.js @@ -10626,7 +10626,7 @@ class WaveService extends OrderBaseService { const taskNo = String(taskCreateResult.task_no || '').trim(); // 查询所有选中波次的 wave_no,用于填充任务波次关联记录 - let waveNoMap = new Map(); + const waveNoMap = new Map(); if (selectedWaveIds.length > 0) { const waveNoRows = await this.ctx.model.query( `SELECT wave_id, wave_no diff --git a/app/service/systemMethods/outbound.js b/app/service/systemMethods/outbound.js new file mode 100644 index 0000000..07a1fc3 --- /dev/null +++ b/app/service/systemMethods/outbound.js @@ -0,0 +1,86 @@ +'use strict'; + +const MainService = require('../main'); + +/** + * 出库相关 method 层入口。 + * 负责鉴权配置与参数解构,业务逻辑下沉到 systems。 + */ +class OutboundService extends MainService { + /** + * 初始化 outbound 模块鉴权配置。 + * + * @param {Egg.Context} ctx 上下文对象。 + */ + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'autoOutbound'; + const _noNeedLog = 'autoOutbound'; + const _noNeedAuth = 'autoOutbound'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 手动触发自动化出库扫描。 + * + * 扫描当前仓库下满足自动化出库条件的订单并执行出库操作。 + * 条件由仓库 subject_config.auto_outbound_rules 控制: + * - recheck_status = 'fin'(已复核) + * - pack_status = 'fin'(已打包) + * - wms_order_express.weighing_weight > 0(已称重) + * + * @param {Object} data 请求参数。 + * @param {number} [data.warehouseId] 指定仓库ID,不传则使用当前用户上下文仓库。 + * @return {Promise} 执行结果,包含处理数量和仓库详情。 + */ + async autoOutbound(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const { ctx } = this; + const warehouseId = Number(requestData.warehouseId) || this.getWarehouseId(); + + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw new Error('缺少有效的仓库ID'); + } + + const storeId = this.getWarehouseId(); + + if (!Number.isInteger(storeId) || storeId <= 0) { + throw new Error('缺少有效的货主ID'); + } + + const store = await ctx.model.Store.findOne({ + where: { id: storeId, status: 1, deleted_at: null }, + attributes: [ 'id', 'subject_config' ], + raw: true, + }); + + if (!store) { + throw new Error('货主不存在或已禁用'); + } + + let subjectConfig = store.subject_config; + if (typeof subjectConfig === 'string') { + try { + subjectConfig = JSON.parse(subjectConfig); + } catch (error) { + throw new Error('subject_config 配置解析失败'); + } + } + + const autoOutboundRules = subjectConfig && subjectConfig.auto_outbound_rules; + + if (!autoOutboundRules || !autoOutboundRules.enabled) { + throw new Error('当前仓库未启用自动化出库'); + } + + const result = await ctx.service.systems.orderAutoOutbound.processWarehouseAutoOutbound( + warehouseId, + autoOutboundRules + ); + + return result; + } +} + +module.exports = OutboundService; diff --git a/app/service/systems/delivery_order.js b/app/service/systems/delivery_order.js index fe07b45..5c5e0f9 100644 --- a/app/service/systems/delivery_order.js +++ b/app/service/systems/delivery_order.js @@ -688,7 +688,7 @@ class DeliveryOrderService extends Service { items_weight: itemsInfo.total_weight || 0, // 总重量 items_hash: this.generateItemsHash(itemsInfo), // 哈希值 items_crc: this.calculateCRC32(itemsInfo.items_str || ''), // CRC校验 - source_order_codes: ((itemsInfo.stats && itemsInfo.stats.source_order_codes) || []).filter(code => code).join(','), + source_order_codes: ((itemsInfo.stats && itemsInfo.stats.source_order_codes) || []).filter(code => code).join(',') || deliveryOrder.deliveryOrderCode, updated_at: new Date(), }; diff --git a/app/service/systems/notice/drivers/generic.js b/app/service/systems/notice/drivers/generic.js index d618d99..062123c 100644 --- a/app/service/systems/notice/drivers/generic.js +++ b/app/service/systems/notice/drivers/generic.js @@ -18,6 +18,12 @@ class CustomizeWebhookDriver { data: payload, }; + this.ctx.logger.info('[CustomizeWebhookDriver.send] 发送内容', { + hookUrl: String(hook && hook.hook_url || '').substring(0, 80), + hookType: String(hook && hook.hook_type || 'customize'), + payloadKeys: Object.keys(payload || {}), + }); + const response = await this.ctx.curl(String(hook.hook_url || ''), requestOptions); return { diff --git a/app/service/systems/notice/drivers/wecom.js b/app/service/systems/notice/drivers/wecom.js index e8504f6..0e18817 100644 --- a/app/service/systems/notice/drivers/wecom.js +++ b/app/service/systems/notice/drivers/wecom.js @@ -56,6 +56,10 @@ class WecomWebhookDriver { async send({ hook, payload }) { const requestData = this.buildRequestData(payload); + this.ctx.logger.info('[WecomWebhookDriver.send] 发送内容', { + hookUrl: String(hook && hook.hook_url || '').substring(0, 80), + requestData, + }); const requestOptions = { method: 'POST', headers: { diff --git a/app/service/systems/order_async.js b/app/service/systems/order_async.js index 3c562cb..86c5eba 100644 --- a/app/service/systems/order_async.js +++ b/app/service/systems/order_async.js @@ -472,7 +472,7 @@ async function finalizeSuccessfulQimenSyncInternal(service, orderModel, orderIte id: orderId, warehouse_id: warehouseId, }, - attributes: [ 'id', 'delivery_order_code', 'order_type' ], + attributes: [ 'id', 'delivery_order_code', 'order_type', 'source_order_codes' ], raw: true, transaction, }); @@ -497,11 +497,13 @@ async function finalizeSuccessfulQimenSyncInternal(service, orderModel, orderIte } const outboundOrderItemId = Number(orderItem && (orderItem.id || orderItem.order_item_id)) || null; + const stockId = Number(orderItem && orderItem.stock_id) || 0; const outboundResult = await stockStoreService.outbound(itemId, quantity, transaction, { orderId: outboundMetaOrderId, orderNo: outboundMetaOrderNo, orderItemId: outboundOrderItemId, - }); + sourceOrderCodes: String(resolvedOrderRow && resolvedOrderRow.source_order_codes || '').trim() || undefined, + }, { stockId: stockId > 0 ? stockId : undefined }); if (!outboundResult || outboundResult.success !== true) { throw new Error(String(outboundResult && outboundResult.error || `订单${orderId}库存扣减失败`).trim()); } @@ -551,11 +553,13 @@ async function processLocalChannelOrderInternal(service, createChannel, orderMod } const outboundOrderItemId = Number(orderItem && (orderItem.id || orderItem.order_item_id)) || null; + const stockId = Number(orderItem && orderItem.stock_id) || 0; const outboundResult = await service.ctx.service.systems.stockStore.outbound(itemId, quantity, transaction, { orderId: Number(orderRow && orderRow.id) || Number(orderId) || null, orderNo: String(orderRow && orderRow.delivery_order_code || '').trim() || null, orderItemId: outboundOrderItemId, - }); + sourceOrderCodes: String(orderRow && orderRow.source_order_codes || '').trim() || undefined, + }, { stockId: stockId > 0 ? stockId : undefined }); if (!outboundResult || outboundResult.success !== true) { throw new Error(String(outboundResult && outboundResult.error || `订单${orderId}库存扣减失败`).trim()); } @@ -619,6 +623,7 @@ async function processManualOrderInternal(service, orderModel, orderItemsModel, order_ids: [ orderId ], order_count: 1, delivery_order_code: String(orderRow.delivery_order_code || '').trim(), + store_id: Number(orderRow && orderRow.store_id) || 0, waybill_code: resolvedWaybillCodes, warehouse_id: warehouseId, handler: 'syncManualOrders', @@ -833,7 +838,7 @@ function buildManualSyncNoticePayloadInternal(syncResult = {}, context = {}) { event: 'order_sync_completed', businessName: 'order', warehouseId, - storeId: Number(context.storeId || context.warehouseId || 0), + storeId: Number(syncResult.store_id || context.storeId || context.warehouseId || 0), subject: { id: warehouseId, type: 'warehouse', diff --git a/app/service/systems/order_auto_outbound.js b/app/service/systems/order_auto_outbound.js new file mode 100644 index 0000000..9e13453 --- /dev/null +++ b/app/service/systems/order_auto_outbound.js @@ -0,0 +1,296 @@ +'use strict'; + +const MainService = require('../main'); +const { Op } = require('sequelize'); + +const OUTBOUND_STATUS = 'padding'; +const OUTBOUND_STEP = 4; +const ORDER_STATUS_FINISHED = 'finished'; +const MAX_BATCH_SIZE = 500; + +/** + * 订单自动化出库服务。 + * 当订单满足仓库配置的自动化出库规则时,自动标记出库并完成订单。 + */ +class OrderAutoOutboundService extends MainService { + /** + * 获取所有启用了自动化出库的仓库配置。 + * + * @return {Promise>} 仓库配置列表。 + */ + async getEnabledAutoOutboundWarehouses() { + const { app } = this; + const { Store, StoreWarehouse } = app.model; + + if (!Store || !StoreWarehouse) { + return []; + } + + const stores = await Store.findAll({ + where: { + status: 1, + deleted_at: null, + }, + attributes: [ 'id', 'subject_config' ], + raw: true, + }); + + const result = []; + + for (const store of stores) { + const subjectConfig = this.normalizeSubjectConfigForAutoOutbound(store.subject_config); + const autoOutboundRules = subjectConfig && subjectConfig.auto_outbound_rules; + + if (!autoOutboundRules || !autoOutboundRules.enabled) { + continue; + } + + const contracts = await StoreWarehouse.findAll({ + where: { + store_id: store.id, + auth_status: 2, + }, + attributes: [ 'warehouse_id' ], + raw: true, + }); + + for (const contract of contracts) { + result.push({ + storeId: store.id, + warehouseId: contract.warehouse_id, + rules: autoOutboundRules, + }); + } + } + + return result; + } + + /** + * 规范化 subject_config,支持字符串 JSON 和对象两种格式。 + * + * @param {Object|string} rawConfig 原始主体配置。 + * @return {Object} 规范化后的配置对象。 + */ + normalizeSubjectConfigForAutoOutbound(rawConfig) { + if (!rawConfig) { + return {}; + } + + if (typeof rawConfig === 'object' && !Array.isArray(rawConfig)) { + return rawConfig; + } + + if (typeof rawConfig === 'string') { + try { + return JSON.parse(rawConfig); + } catch (error) { + return {}; + } + } + + return {}; + } + + /** + * 构造自动化出库的订单查询条件。 + * + * @param {Object} rules 自动化出库规则。 + * @return {Object} Sequelize where 条件对象。 + */ + buildAutoOutboundWhere(rules) { + const where = { + outbound_status: 'none', + status: { + [Op.notIn]: [ 'cancel', 'error', 'finished' ], + }, + }; + + if (rules.require_recheck) { + where.recheck_status = 'fin'; + } + + if (rules.require_pack) { + where.pack_status = 'fin'; + } + + if (rules.require_sync) { + where.sync_status = 'fin'; + } + + return where; + } + + /** + * 获取仓库下满足自动化出库条件的订单ID列表。 + * + * @param {number} warehouseId 仓库ID。 + * @param {Object} rules 自动化出库规则。 + * @param {number} [limit=MAX_BATCH_SIZE] 单次扫描上限。 + * @return {Promise>} 订单ID列表。 + */ + async findAutoOutboundOrders(warehouseId, rules, limit = MAX_BATCH_SIZE) { + const { ctx } = this; + const factory = ctx.model && ctx.model.OrderDeliveryFactory; + + if (!factory || typeof factory.getCurrentModel !== 'function') { + return []; + } + + const orderModel = await factory.getCurrentModel(warehouseId); + if (!orderModel) { + return []; + } + + const where = this.buildAutoOutboundWhere(rules); + + if (rules.require_weigh) { + const orderIdsWithWeigh = await this.findOrderIdsWithWeigh(warehouseId); + if (orderIdsWithWeigh.length === 0) { + return []; + } + where.id = { [Op.in]: orderIdsWithWeigh }; + } + + const orders = await orderModel.findAll({ + where, + attributes: [ 'id' ], + limit, + raw: true, + }); + + return orders; + } + + /** + * 查找有称重记录的订单ID列表。 + * + * @param {number} warehouseId 仓库ID。 + * @return {Promise>} 订单ID列表。 + */ + async findOrderIdsWithWeigh(warehouseId) { + const { ctx } = this; + const { OrderExpress } = ctx.model; + + if (!OrderExpress) { + return []; + } + + const rows = await OrderExpress.findAll({ + where: { + warehouse_id: warehouseId, + weighing_weight: { [Op.gt]: 0 }, + }, + attributes: [ 'order_id' ], + raw: true, + }); + + return rows + .map(row => Number(row.order_id)) + .filter(id => Number.isFinite(id) && id > 0); + } + + /** + * 对指定仓库执行单次自动化出库扫描与执行。 + * + * @param {number} warehouseId 仓库ID。 + * @param {Object} rules 自动化出库规则。 + * @return {Promise<{warehouseId: number, processedCount: number, errorMessage: string|null}>} 执行结果。 + */ + async processWarehouseAutoOutbound(warehouseId, rules) { + const { ctx } = this; + const result = { + warehouseId, + processedCount: 0, + errorMessage: null, + }; + + try { + const orders = await this.findAutoOutboundOrders(warehouseId, rules); + + if (!orders || orders.length === 0) { + return result; + } + + const orderIds = orders.map(order => Number(order.id)).filter(Boolean); + if (orderIds.length === 0) { + return result; + } + + const now = new Date(); + const factory = ctx.model && ctx.model.OrderDeliveryFactory; + const orderModel = await factory.getCurrentModel(warehouseId); + + const [ affectedRows ] = await orderModel.update( + { + outbound_status: OUTBOUND_STATUS, + step: OUTBOUND_STEP, + status: ORDER_STATUS_FINISHED, + updated_at: now, + }, + { + where: { + id: { [Op.in]: orderIds }, + warehouse_id: warehouseId, + }, + } + ); + + result.processedCount = Number(affectedRows) || 0; + + if (result.processedCount > 0) { + ctx.logger.info( + `[auto-outbound] 仓库 ${warehouseId} 自动化出库 ${result.processedCount} 条订单,订单ID: ${orderIds.join(',')}` + ); + } + } catch (error) { + result.errorMessage = error.message; + ctx.logger.error(`[auto-outbound] 仓库 ${warehouseId} 自动化出库失败: ${error.message}`); + } + + return result; + } + + /** + * 执行全局自动化出库扫描。 + * 遍历所有启用了自动化出库的仓库,对每个仓库扫描并执行符合条件的订单出库。 + * + * @return {Promise<{totalProcessed: number, warehouseResults: Array}>} 全局执行结果。 + */ + async executeAutoOutbound() { + const { ctx } = this; + + if (ctx.app._autoOutboundRunning) { + ctx.logger.info('[auto-outbound] 上一轮自动化出库尚未结束,跳过本次执行'); + return { totalProcessed: 0, warehouseResults: [] }; + } + + ctx.app._autoOutboundRunning = true; + + try { + const warehouses = await this.getEnabledAutoOutboundWarehouses(); + + if (!warehouses || warehouses.length === 0) { + return { totalProcessed: 0, warehouseResults: [] }; + } + + let totalProcessed = 0; + const warehouseResults = []; + + for (const { warehouseId, rules } of warehouses) { + const result = await this.processWarehouseAutoOutbound(warehouseId, rules); + warehouseResults.push(result); + totalProcessed += result.processedCount; + } + + return { totalProcessed, warehouseResults }; + } catch (error) { + ctx.logger.error(`[auto-outbound] 全局自动化出库执行失败: ${error.message}`); + return { totalProcessed: 0, warehouseResults: [] }; + } finally { + ctx.app._autoOutboundRunning = false; + } + } +} + +module.exports = OrderAutoOutboundService; diff --git a/app/service/systems/order_express.js b/app/service/systems/order_express.js index 28da444..d0bea1e 100644 --- a/app/service/systems/order_express.js +++ b/app/service/systems/order_express.js @@ -220,8 +220,8 @@ class OrderExpressService extends Service { * @param {number|string} payload.orderId 订单ID。 * @param {string} [payload.waybillCode] 运单号,多运单场景必填。 * @param {number|string} payload.weighingWeight 称重重量(kg)。 - * @return {Promise} 单订单返回 {order_id, waybill_code, weighing_weight}; - * 团购批量返回 {wave_id, wave_no, weighing_weight, success_count, total_count}。 + * @return {Promise} 单订单返回 {order_id, waybill_code, weighing_weight, items_weight}; + * 团购批量返回 {wave_id, wave_no, weighing_weight, total_weight, split_count, splits, store_name, sys_logistics_name, items_weight}。 */ async updateWeighingWeight(payload = {}) { const requestData = payload && typeof payload === 'object' ? payload : {}; @@ -293,10 +293,341 @@ class OrderExpressService extends Service { // 团购波次 → 批量设置同一重量 return await this._updateWaveOrderWeight( - waveId, String(waveRow.wave_no || ''), normalizedWeight, warehouseId, orderDeliveryModel + waveId, String(waveRow.wave_no || ''), normalizedWeight, warehouseId, orderDeliveryModel, normalizedOrderId ); } + /** + * 通过运单号更新称重重量(运单号模式,order_id=0 时使用)。 + * + * 从运单号反查 wms_order_express,再定位订单和波次: + * - 散单或非团购波次:仅更新该运单的称重重量。 + * - 团购波次(wave_type=1):按 wave_no + business_key 批量设置同一重量, + * 并返回含拆单汇总信息的结构。 + * + * @param {Object} payload 入参对象。 + * @param {string} payload.waybillCode 运单号(必填)。 + * @param {number|string} payload.weighingWeight 称重重量(kg)。 + * @return {Promise} 单运单返回 {order_id, waybill_code, weighing_weight, items_weight}; + * 团购批量返回 {wave_id, wave_no, order_id, weighing_weight, total_weight, split_count, splits, store_name, sys_logistics_name, items_weight}。 + */ + async updateWeighingWeightByWaybill(payload = {}) { + const requestData = payload && typeof payload === 'object' ? payload : {}; + const { waybillCode, weighingWeight } = requestData; + + const normalizedWaybillCode = this.normalizeWaybillCode(waybillCode); + const normalizedWeight = this.normalizeWeighingWeight(weighingWeight); + const warehouseId = this.getCurrentWarehouseId(); + + // 按运单号 + 仓库ID 查 wms_order_express + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; + if (!orderExpressModel || typeof orderExpressModel.findOne !== 'function') { + throw this.createBusinessError('运单模型未初始化', 500); + } + + const expressRow = await orderExpressModel.findOne({ + where: { + waybill_code: normalizedWaybillCode, + warehouse_id: warehouseId, + delete_at: null, + }, + attributes: [ 'id', 'order_id', 'waybill_code', 'business_key' ], + raw: true, + }); + + if (!expressRow) { + throw this.createBusinessError('运单号不存在', 404); + } + + const orderId = Number(expressRow.order_id || 0); + + // 查询订单所属波次 + const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; + if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') { + throw this.createBusinessError('订单模型未初始化', 500); + } + + const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(warehouseId); + const orderRow = await orderDeliveryModel.findOne({ + where: { id: orderId, warehouse_id: warehouseId }, + attributes: [ 'id', 'wave_id', 'wave_no' ], + raw: true, + }); + + if (!orderRow) { + throw this.createBusinessError('运单号对应的订单不存在', 404); + } + + const waveId = Number(orderRow.wave_id || 0); + + // 散单 → 走单个运单逻辑 + if (waveId === 0) { + return await this._updateSingleOrderWeight( + orderId, normalizedWaybillCode, normalizedWeight, warehouseId + ); + } + + // 查询波次类型 + const waveBatchModel = this.ctx.model && this.ctx.model.WaveBatch; + if (!waveBatchModel || typeof waveBatchModel.findOne !== 'function') { + throw this.createBusinessError('波次模型未初始化', 500); + } + + const waveRow = await waveBatchModel.findOne({ + where: { wave_id: waveId, warehouse_id: warehouseId }, + attributes: [ 'wave_id', 'wave_no', 'wave_type' ], + raw: true, + }); + + // 非团购波次 → 降级为单运单逻辑 + if (!waveRow || Number(waveRow.wave_type) !== 1) { + return await this._updateSingleOrderWeight( + orderId, normalizedWaybillCode, normalizedWeight, warehouseId + ); + } + + // 团购波次 → 按 wave_id 批量设置波次下全部运单 + return await this._updateWaveAllOrdersWeight( + waveId, + String(waveRow.wave_no || ''), + normalizedWeight, + warehouseId, + orderDeliveryModel, + orderId + ); + } + + /** + * 批量更新团购波次下所有订单运单的称重重量(内部方法,运单号模式入口)。 + * + * 查询波次下全部订单,按 order_id 批量更新所有运单的 weighing_weight, + * 不区分 business_key。与 _updateWaveOrderWeight 功能等价但调用入口不同。 + * + * @param {number} waveId 波次ID。 + * @param {string} waveNo 波次号。 + * @param {number} weight 称重重量。 + * @param {number} warehouseId 仓库ID。 + * @param {Object} orderDeliveryModel 订单 Sequelize 模型实例。 + * @param {number} orderId 触发更新的运单对应订单ID。 + * @return {Promise<{wave_id:number, wave_no:string, order_id:number, weighing_weight:number, total_weight:number, split_count:number, splits:Array<{business_key:string|null, weighing_weight:number, waybill_code:string|null}>, store_name:string, sys_logistics_name:string, items_weight:number}>} + * 团购批量更新结果,含拆单汇总信息及触发订单ID。 + */ + async _updateWaveAllOrdersWeight(waveId, waveNo, weight, warehouseId, orderDeliveryModel, orderId) { + // 查询波次下所有订单 + const waveOrders = await orderDeliveryModel.findAll({ + where: { wave_id: waveId, warehouse_id: warehouseId }, + attributes: [ 'id' ], + raw: true, + }); + + if (!waveOrders || waveOrders.length === 0) { + throw this.createBusinessError('波次下未找到订单', 404); + } + + const orderIds = waveOrders.map(o => Number(o.id)); + + // 批量更新波次下全部运单的称重重量 + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; + if (!orderExpressModel || typeof orderExpressModel.update !== 'function') { + throw this.createBusinessError('运单模型未初始化', 500); + } + + const { Op } = this.app.Sequelize; + const updateWhere = { + order_id: { [Op.in]: orderIds }, + delete_at: null, + }; + + // 先验证匹配记录是否存在,避免 MySQL 因值未变返回 affected_rows=0 导致误判 + const matchingCount = await orderExpressModel.count({ where: updateWhere }); + if (matchingCount === 0) { + throw this.createBusinessError('批量更新称重重量失败,波次下无有效运单记录', 500); + } + + await orderExpressModel.update( + { weighing_weight: weight }, + { where: updateWhere } + ); + + const successCount = matchingCount; + + // 写入操作日志 + await this._writeWeighActionLog({ + waveId, + waveNo, + weight, + warehouseId, + successCount, + totalCount: orderIds.length, + }); + + // 构建拆单汇总信息(按触发订单 ID 汇总) + const summary = await this._buildWaveWeighingSummary(waveId, orderId, warehouseId, weight); + + // 从订单表读取当前 items_weight(只读,不做 UPDATE) + const orderRow = await orderDeliveryModel.findOne({ + where: { id: orderId, warehouse_id: warehouseId }, + attributes: [ 'items_weight' ], + raw: true, + }); + const itemsWeight = orderRow ? Number(orderRow.items_weight || 0) : 0; + + return { + wave_id: waveId, + wave_no: waveNo, + order_id: orderId, + weighing_weight: weight, + total_weight: summary.total_weight, + split_count: summary.split_count, + splits: summary.splits, + store_name: summary.store_name, + sys_logistics_name: summary.sys_logistics_name, + items_weight: itemsWeight, + }; + } + + /** + * 构建团购波次称重拆单汇总信息(内部方法)。 + * + * 查询指定订单下所有运单记录,按 business_key 分组汇总称重重量, + * 并获取货主名称与系统快递名称。 + * + * @param {number} waveId 波次ID。 + * @param {number} orderId 订单ID。 + * @param {number} warehouseId 仓库ID。 + * @param {number} currentWeight 本次设置的称重重量。 + * @return {Promise<{total_weight:number, split_count:number, splits:Array<{business_key:string|null, weighing_weight:number, waybill_code:string|null}>, store_name:string, sys_logistics_name:string}>} + * 拆单汇总信息。 + */ + async _buildWaveWeighingSummary(waveId, orderId, warehouseId, currentWeight) { + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; + if (!orderExpressModel || typeof orderExpressModel.findAll !== 'function') { + return { + total_weight: currentWeight, + split_count: 0, + splits: [], + store_name: '', + sys_logistics_name: '', + }; + } + + // 查询指定订单下所有有效运单记录 + const expressRows = await orderExpressModel.findAll({ + where: { + order_id: orderId, + delete_at: null, + }, + attributes: [ 'business_key', 'weighing_weight', 'waybill_code' ], + raw: true, + }); + + // 按 business_key 分组汇总称重重量 + const splitMap = new Map(); + for (const row of expressRows) { + const bk = row.business_key === null || row.business_key === undefined + ? '__null__' + : String(row.business_key); + if (!splitMap.has(bk)) { + splitMap.set(bk, { + business_key: row.business_key, + weighing_weight: 0, + waybill_code: row.waybill_code || null, + }); + } + const entry = splitMap.get(bk); + entry.weighing_weight = Number( + (entry.weighing_weight + Number(row.weighing_weight || 0)).toFixed(3) + ); + // 优先取非空的 waybill_code 作为该拆单的代表运单号 + if (!entry.waybill_code && row.waybill_code) { + entry.waybill_code = row.waybill_code; + } + } + + const splits = [ ...splitMap.values() ]; + const totalWeight = Number( + splits.reduce((sum, s) => sum + s.weighing_weight, 0).toFixed(3) + ); + // split_count:仅统计 waybill_code 不为空的 business_key + const splitCount = splits.filter(s => s.waybill_code !== null).length; + + // 获取货主名称 + const storeName = await this._getStoreName([ orderId ], warehouseId); + + // 获取系统快递名称 + const sysLogisticsName = await this._getWaveSysLogisticsName([ orderId ], warehouseId); + + return { + total_weight: totalWeight, + split_count: splitCount, + splits, + store_name: storeName, + sys_logistics_name: sysLogisticsName, + }; + } + + /** + * 获取波次下第一个订单的货主名称(shop_nick)。 + * + * @param {number[]} orderIds 订单ID列表。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 货主名称(shop_nick),获取失败时返回空字符串。 + */ + async _getStoreName(orderIds, warehouseId) { + try { + const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; + if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') { + return ''; + } + const { Op } = this.app.Sequelize; + const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(warehouseId); + const orderRow = await orderDeliveryModel.findOne({ + where: { + id: { [Op.in]: orderIds }, + warehouse_id: warehouseId, + shop_nick: { [Op.ne]: null }, + }, + attributes: [ 'shop_nick' ], + raw: true, + }); + return orderRow ? String(orderRow.shop_nick || '').trim() : ''; + } catch (_err) { + return ''; + } + } + + /** + * 获取波次下订单的系统快递名称。 + * + * 取波次下第一个有值的 sys_logistics_name。 + * + * @param {number[]} orderIds 订单ID列表。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 系统快递名称,获取失败时返回空字符串。 + */ + async _getWaveSysLogisticsName(orderIds, warehouseId) { + try { + const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; + if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') { + return ''; + } + const { Op } = this.app.Sequelize; + const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(warehouseId); + const orderRow = await orderDeliveryModel.findOne({ + where: { + id: { [Op.in]: orderIds }, + warehouse_id: warehouseId, + sys_logistics_name: { [Op.ne]: null }, + }, + attributes: [ 'sys_logistics_name' ], + raw: true, + }); + return orderRow ? String(orderRow.sys_logistics_name || '').trim() : ''; + } catch (_err) { + return ''; + } + } + /** * 更新单个订单运单的称重重量(内部方法)。 * @@ -304,7 +635,7 @@ class OrderExpressService extends Service { * @param {string} waybillCode 运单号。 * @param {number} weight 称重重量。 * @param {number|null} warehouseId 仓库ID。 - * @return {Promise<{order_id:number, waybill_code:string, weighing_weight:number}>} 更新结果。 + * @return {Promise<{order_id:number, waybill_code:string, weighing_weight:number, items_weight:number}>} 更新结果。 */ async _updateSingleOrderWeight(orderId, waybillCode, weight, warehouseId) { const rows = await this.findValidOrderExpressRows(orderId, warehouseId); @@ -350,10 +681,30 @@ class OrderExpressService extends Service { warehouseId, }); + // 从订单表读取当前 items_weight(只读,不做 UPDATE) + let itemsWeight = 0; + if (warehouseId) { + try { + const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; + if (orderDeliveryFactory && typeof orderDeliveryFactory.getCurrentModel === 'function') { + const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(warehouseId); + const orderRow = await orderDeliveryModel.findOne({ + where: { id: Number(targetRow.order_id), warehouse_id: warehouseId }, + attributes: [ 'items_weight' ], + raw: true, + }); + itemsWeight = orderRow ? Number(orderRow.items_weight || 0) : 0; + } + } catch (_err) { + // 查询失败时静默降级为 0 + } + } + return { order_id: Number(targetRow.order_id), waybill_code: String(targetRow.waybill_code || '').trim(), weighing_weight: weight, + items_weight: itemsWeight, }; } @@ -365,10 +716,11 @@ class OrderExpressService extends Service { * @param {number} weight 称重重量。 * @param {number|null} warehouseId 仓库ID。 * @param {Object} orderDeliveryModel 订单 Sequelize 模型实例。 - * @return {Promise<{wave_id:number, wave_no:string, weighing_weight:number, success_count:number, total_count:number}>} - * 批量更新结果。 + * @param {number} [orderId] 触发更新的订单ID,未传时取波次下第一个订单。 + * @return {Promise<{wave_id:number, wave_no:string, weighing_weight:number, total_weight:number, split_count:number, splits:Array<{business_key:string|null, weighing_weight:number, waybill_code:string|null}>, store_name:string, sys_logistics_name:string, items_weight:number}>} + * 团购批量更新结果,含拆单汇总信息。 */ - async _updateWaveOrderWeight(waveId, waveNo, weight, warehouseId, orderDeliveryModel) { + async _updateWaveOrderWeight(waveId, waveNo, weight, warehouseId, orderDeliveryModel, orderId) { // 查询波次下所有订单 const waveOrders = await orderDeliveryModel.findAll({ where: { wave_id: waveId, warehouse_id: warehouseId }, @@ -390,24 +742,24 @@ class OrderExpressService extends Service { } const { Op } = this.app.Sequelize; - const updateResult = await orderExpressModel.update( - { weighing_weight: weight }, - { - where: { - order_id: { [Op.in]: orderIds }, - delete_at: null, - }, - } - ); + const updateWhere = { + order_id: { [Op.in]: orderIds }, + delete_at: null, + }; - const successCount = Array.isArray(updateResult) - ? Number(updateResult[0] || 0) - : Number(updateResult || 0); - - if (!Number.isFinite(successCount) || successCount <= 0) { + // 先验证匹配记录是否存在,避免 MySQL 因值未变返回 affected_rows=0 导致误判 + const matchingCount = await orderExpressModel.count({ where: updateWhere }); + if (matchingCount === 0) { throw this.createBusinessError('批量更新称重重量失败,波次下无有效运单记录', 500); } + await orderExpressModel.update( + { weighing_weight: weight }, + { where: updateWhere } + ); + + const successCount = matchingCount; + // 写入操作日志 await this._writeWeighActionLog({ waveId, @@ -418,12 +770,30 @@ class OrderExpressService extends Service { totalCount, }); + // 构建拆单汇总信息(按触发订单 ID 汇总,未传时取波次下第一个订单) + const scopeOrderId = (Number.isFinite(Number(orderId)) && Number(orderId) > 0) + ? Number(orderId) + : orderIds[0]; + const summary = await this._buildWaveWeighingSummary(waveId, scopeOrderId, warehouseId, weight); + + // 从订单表读取当前 items_weight(只读,不做 UPDATE) + const orderRow = await orderDeliveryModel.findOne({ + where: { id: scopeOrderId, warehouse_id: warehouseId }, + attributes: [ 'items_weight' ], + raw: true, + }); + const itemsWeight = orderRow ? Number(orderRow.items_weight || 0) : 0; + return { wave_id: waveId, wave_no: waveNo, weighing_weight: weight, - success_count: successCount, - total_count: totalCount, + total_weight: summary.total_weight, + split_count: summary.split_count, + splits: summary.splits, + store_name: summary.store_name, + sys_logistics_name: summary.sys_logistics_name, + items_weight: itemsWeight, }; } @@ -535,8 +905,6 @@ class OrderExpressService extends Service { } /** - * 兼容处理:当前端将 wave_id 当作 order_id 传入时,尝试按波次 ID 处理。 - * * 先用传入的 ID 在 wms_wave_batch 中查找波次: * - 波次不存在 → 抛出"订单不存在"错误。 * - 波次存在且 wave_type = 1(团购)→ 走团购批量称重逻辑。 diff --git a/app/service/systems/setting/warehouse.js b/app/service/systems/setting/warehouse.js index 441c528..aae7713 100644 --- a/app/service/systems/setting/warehouse.js +++ b/app/service/systems/setting/warehouse.js @@ -113,6 +113,21 @@ const WAREHOUSE_SETTING_FIELDS = Object.freeze([ Object.freeze({ value: 'async', label: '异步回调' }), ], }), + Object.freeze({ + key: 'auto_outbound_rules', + name: '自动出库规则', + type: 'object', + default: Object.freeze({ enabled: false, require_recheck: true, require_pack: true, require_weigh: true, require_sync: true }), + required: false, + description: '满足条件自动标记出库。全部条件满足时自动标记待出库', + item_keys: Object.freeze([ + Object.freeze({ key: 'enabled', name: '启用', type: 'flag', required: true, description: '是否启用自动出库' }), + Object.freeze({ key: 'require_recheck', name: '需已复核', type: 'flag', required: false, description: '是否要求 recheck_status=fin' }), + Object.freeze({ key: 'require_pack', name: '需已打包', type: 'flag', required: false, description: '是否要求 pack_status=fin' }), + Object.freeze({ key: 'require_weigh', name: '需已称重', type: 'flag', required: false, description: '是否要求 weighing_weight>0' }), + Object.freeze({ key: 'require_sync', name: '需已同步', type: 'flag', required: false, description: '是否要求 sync_status=fin' }), + ]), + }), Object.freeze({ key: INTERNAL_WAVE_STRATEGY_VERSION_KEY, name: '仓库波次策略版本号', diff --git a/app/service/systems/stock_store.js b/app/service/systems/stock_store.js index 8586576..59fc28a 100644 --- a/app/service/systems/stock_store.js +++ b/app/service/systems/stock_store.js @@ -251,11 +251,13 @@ class stockStoreService extends Service { /** * 查询商品对应的库存记录与可用量。 * - * @param {number|string} itemId 商品 ID。 + * @param {number|string} itemId 商品 ID(StockStore.id)。 * @param {Object|null} transaction 数据库事务。 + * @param {Object} [opts] 可选配置。 + * @param {number} [opts.stockId] 当传入有效的 stockId 时,跳过 StockStore 映射层,直接使用该 stockId 查询 StockWarehouse。 * @return {Promise} 库存查询结果。 */ - async getItemStorages(itemId, transaction) { + async getItemStorages(itemId, transaction, opts = {}) { const { ctx, app, @@ -263,6 +265,72 @@ class stockStoreService extends Service { const cacheKey = `storages:${itemId}`; try { + const { stockId } = opts; + + // stockId 快速路径:跳过 StockStore 映射,直接用 stockId 查 StockWarehouse + if (Number.isFinite(stockId) && stockId > 0) { + const stockWarehouse = await ctx.model.StockWarehouse.findOne({ + where: { + id: stockId, + is_valid: 'Y', + deleted_at: null, + }, + attributes: [ + 'id', 'store_id', 'warehouse_id', 'quantity', 'locked_quantity', 'gross_weight', + ], + transaction, + lock: transaction?.LOCK?.UPDATE, + raw: true, + }); + + if (stockWarehouse) { + const quantity = parseInt(stockWarehouse.quantity) || 0; + const lockedQuantity = parseInt(stockWarehouse.locked_quantity) || 0; + const canUse = quantity - lockedQuantity; + const grossWeight = parseInt(stockWarehouse.gross_weight) || 0; + + const storage = { + id: stockWarehouse.id, + storeId: Number(stockWarehouse.store_id) || 0, + warehouseId: Number(stockWarehouse.warehouse_id) || 0, + quantity, + lockedQuantity, + canUse, + grossWeight, + _updatedAt: Date.now(), + exists: true, + }; + + // 异步更新缓存 + const cached = await app.getCacheAsync(cacheKey); + if (!cached) { + const ttl = this._calculateCacheTTL(storage); + app.setCacheAsync(cacheKey, storage, ttl); + } + + return { + success: true, + data: { + stock: { + id: itemId, + stock_id: stockId, + store_id: storage.storeId, + warehouse_id: storage.warehouseId, + }, + storage, + }, + }; + } + + // stockWarehouse 不存在 + app.logger.warn(`[库存记录缺失-stockId快速路径] itemId=${itemId}, stockId=${stockId}`); + return { + success: false, + error: '已更改未同步推送到仓库', + data: null, + }; + } + // 1. 获取商品信息 const itemInfo = await this.getItemInfoWithCache(itemId); @@ -688,8 +756,9 @@ class stockStoreService extends Service { * @param {number} itemId 商品ID (StockStore.id) * @param {number} quantity 入库数量(正数) * @param {Object} transaction 数据库事务 + * @param {Object} [opts] 可选配置,透传给 getItemStorages。 */ - async inbound(itemId, quantity, transaction) { + async inbound(itemId, quantity, transaction, opts = {}) { const { ctx, app, @@ -707,7 +776,7 @@ class stockStoreService extends Service { try { return await this._runWithTransaction(transaction, async (currentTransaction, hasExternalTransaction) => { // 2. 获取商品和库存信息(复用) - const stockResult = await this.getItemStorages(itemId, currentTransaction); + const stockResult = await this.getItemStorages(itemId, currentTransaction, opts); if (!stockResult.success) { if (hasExternalTransaction) { @@ -921,6 +990,44 @@ class stockStoreService extends Service { return Array.isArray(rows) ? rows : []; } + /** + * 批量查询拣货行对应的库存批次号(wms_storage.batch_no)。 + * + * @param {Array} pickingRows 拣货分配记录列表 + * @param {Object|null} transaction 事务对象 + * @return {Promise>} storage_id → batch_no 映射表 + */ + async getPickingBatchMap(pickingRows, transaction) { + const { ctx, app } = this; + const map = new Map(); + if (!Array.isArray(pickingRows) || pickingRows.length === 0) { + return map; + } + + const storageIds = [ ...new Set(pickingRows.map(r => Number(r.storage_id)).filter(id => id > 0)) ]; + if (storageIds.length === 0) { + return map; + } + + try { + const storageRows = await ctx.model.Storage.findAll({ + where: { id: { [app.Sequelize.Op.in]: storageIds } }, + attributes: [ 'id', 'batch_no' ], + raw: true, + transaction, + }); + for (const sr of storageRows) { + if (sr && sr.batch_no) { + map.set(Number(sr.id), String(sr.batch_no).trim()); + } + } + } catch (error) { + app.logger.warn(`[getPickingBatchMap] 查询 storage batch_no 失败,降级跳过: ${error.message}`); + } + + return map; + } + /** * 生成出库流水写入明细,优先按拣货分配逐条记录。 * @@ -928,9 +1035,10 @@ class stockStoreService extends Service { * @param {number} options.outboundQty 本次出库总数量。 * @param {Array} options.pickingRows 拣货分配记录。 * @param {Object} options.basePayload 流水公共字段。 + * @param {Map} options.pickingBatchMap storage_id → batch_no 映射表。 * @return {Array} 待写入的出库流水列表。 */ - buildOutboundTransactionPayloads({ outboundQty, pickingRows, basePayload }) { + buildOutboundTransactionPayloads({ outboundQty, pickingRows, basePayload, pickingBatchMap = new Map() }) { const payloads = []; const normalizedRows = Array.isArray(pickingRows) ? pickingRows : []; let consumedQty = 0; @@ -947,11 +1055,15 @@ class stockStoreService extends Service { } const transactionQty = Math.min(pickingQty, remainingQty); + const storageId = pickingRow && pickingRow.storage_id ? Number(pickingRow.storage_id) : null; + const batchNo = storageId ? (pickingBatchMap.get(storageId) || null) : null; + payloads.push({ ...basePayload, - storage_id: pickingRow && pickingRow.storage_id ? Number(pickingRow.storage_id) : null, + storage_id: storageId, space_id: pickingRow && pickingRow.space_id ? Number(pickingRow.space_id) : null, quantity: transactionQty, + batch_no: batchNo || basePayload.batch_no || null, }); consumedQty += transactionQty; } @@ -983,8 +1095,9 @@ class stockStoreService extends Service { * @param {number} quantity 出库数量(正数) * @param {Object} transaction 数据库事务 * @param {Object} meta 出库元信息(订单、明细等) + * @param {Object} [opts] 可选配置,透传给 getItemStorages。 */ - async outbound(itemId, quantity, transaction, meta = {}) { + async outbound(itemId, quantity, transaction, meta = {}, opts = {}) { const { ctx, app, @@ -1004,7 +1117,7 @@ class stockStoreService extends Service { try { return await this._runWithTransaction(transaction, async (currentTransaction, hasExternalTransaction) => { // 2. 获取商品和库存信息(复用) - const stockResult = await this.getItemStorages(itemId, currentTransaction); + const stockResult = await this.getItemStorages(itemId, currentTransaction, opts); if (!stockResult.success) { if (hasExternalTransaction) { @@ -1107,6 +1220,9 @@ class stockStoreService extends Service { } } + // 获取拣货行对应的库存批次号(wms_storage.batch_no) + const pickingBatchMap = await this.getPickingBatchMap(pickingRows, currentTransaction); + const baseTransactionPayload = { transaction_type: 'OUTBOUND', warehouse_id: updatedRecord.warehouse_id || ctx.user.store_id, @@ -1134,6 +1250,7 @@ class stockStoreService extends Service { outboundQty, pickingRows, basePayload: baseTransactionPayload, + pickingBatchMap, }); for (const payload of transactionPayloads) { diff --git a/app/service/systems/stock_transaction.js b/app/service/systems/stock_transaction.js index 26fd255..6e385b2 100644 --- a/app/service/systems/stock_transaction.js +++ b/app/service/systems/stock_transaction.js @@ -80,25 +80,22 @@ class StockTransactionService extends Service { } let sourceOrderCodes = String(data.source_order_codes || '').trim(); - let waveNo = null; + // 兜底查询 source_order_codes(仅当调用方未传入时),用 try-catch 防止拖垮事务 const orderDeliveryModel = ctx.model && ctx.model.OrderDelivery; - if (orderDeliveryModel && typeof orderDeliveryModel.findOne === 'function') { - const orderRow = await orderDeliveryModel.findOne({ - where: { - id: orderId, - }, - attributes: [ 'id', 'source_order_codes', 'wave_no' ], - raw: true, - transaction: options.transaction, - }); - - if (orderRow) { - if (!sourceOrderCodes) { + if (!sourceOrderCodes && orderDeliveryModel && typeof orderDeliveryModel.findOne === 'function') { + try { + const orderRow = await orderDeliveryModel.findOne({ + where: { id: orderId }, + attributes: [ 'id', 'source_order_codes' ], + raw: true, + transaction: options.transaction, + }); + if (orderRow) { sourceOrderCodes = String(orderRow.source_order_codes || '').trim(); } - const normalizedWaveNo = String(orderRow.wave_no || '').trim(); - waveNo = normalizedWaveNo || null; + } catch (error) { + ctx.logger.warn(`[resolveOutboundOrderReference] 查询订单 source_order_codes 失败,降级跳过: ${error.message}`); } } @@ -109,7 +106,7 @@ class StockTransactionService extends Service { return { orderId, orderNo: sourceOrderCodes, - batchNo: waveNo, + batchNo: data.batch_no ?? null, }; } diff --git a/methods/changes/system.json b/methods/changes/system.json index 8ec9f6e..00ff8ab 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -3158,5 +3158,66 @@ "成功返回运单记录的 id、order_id、waybill_code、create_at" ], "type": "added" + }, + { + "version": "2026.06.09-system-01", + "date": "2026-06-09", + "summary": "order.pendingOrder.updateAddress 新增 remark 字段:订单留言/备注批量覆盖,不受 post_status 限制", + "methods": [ + "order.pendingOrder.updateAddress" + ], + "notes": [ + "在 params 中新增 remark 字段(string,可选,最大500字符),支持批量覆盖所选订单的 remark", + "remark 更新不受 post_status 限制,可对所有订单生效(地址字段仍仅允许 post_status='none')", + "更新 description 明确 remark 与地址字段的独立性", + "更新 response 中 updated_count 说明:取地址更新行数与备注更新行数的最大值", + "更新 errors 中缺少字段的错误描述,改为「至少需要提供一个地址字段或备注进行修改」", + "业务代码已同步实现,本次仅同步文档" + ], + "type": "updated" + }, + { + "version": "2026.06.09-system-02", + "date": "2026-06-09", + "summary": "order.updateExpressWeighingWeight 新增运单号模式文档:order_id=0 时从运单号反查,支持散单与团购批量两种返回结构", + "methods": [ + "order.updateExpressWeighingWeight" + ], + "notes": [ + "order_id 参数说明补充:设为0时切换为运单号模式,需配合 waybill_code 使用。", + "waybill_code 参数说明补充:运单号模式(order_id=0)下必填。", + "description 更新:明确订单模式与运单号模式两种路径及团购波次批量行为。", + "response 新增运单号散单场景字段(order_id、waybill_code、weighing_weight)与运单号团购批量场景字段(wave_no、business_key、weighing_weight、success_count)。", + "errors 新增运单号模式相关错误码:运单号不存在(404)、运单号对应的订单不存在(404)、波次下未找到订单(404)、批量更新失败(500)。", + "仅文档同步,不修改业务代码。" + ], + "type": "updated" + }, + { + "version": "2026.06.09-system-03", + "date": "2026-06-09", + "summary": "order.updateExpressWeighingWeight 团购返回新增拆单汇总字段,移除 success_count/total_count", + "methods": [ + "order.updateExpressWeighingWeight" + ], + "notes": [ + "团购批量模式 response 新增 total_weight(所有拆单重量累加)、split_count(waybill_code 非空的 business_key 数量)、splits(按 business_key 分组的拆单明细数组,每项含 business_key/weighing_weight/waybill_code)、store_name(货主名称)和 sys_logistics_name(系统快递名称)。", + "移除 response 中的 success_count 与 total_count 字段,改为由 total_weight 和 split_count 提供汇总信息。", + "更新 description 以反映团购模式返回拆单汇总结构。" + ], + "type": "updated" + }, + { + "version": "2026.06.10-system-01", + "date": "2026-06-10", + "summary": "order.detail 接口文档:expresses 数组新增字段 weighing_weight、sys_logistics_code、sys_logistics_name、business_key、created_at", + "methods": [ + "order.detail" + ], + "notes": [ + "expresses 数组新增字段:weighing_weight(称重重量,number|null)、sys_logistics_code(系统物流公司编码,string)、sys_logistics_name(系统物流公司名称,string)、business_key(业务标识,string)、created_at(创建时间戳毫秒,number|null)", + "字段来源:getOrderExpressesByOrderId 方法中 sys_logistics_code/sys_logistics_name 取自订单表 sys_logistics_code/sys_logistics_name,其余字段取自 OrderExpress 表" + ], + "type": "updated" } ] diff --git a/methods/system.json b/methods/system.json index 54d20c7..087065e 100644 --- a/methods/system.json +++ b/methods/system.json @@ -2,7 +2,7 @@ "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", "version": "0.3.5", - "updatedAt": "2026-06-08", + "updatedAt": "2026-06-10", "headers": [ { "name": "platform", @@ -1620,41 +1620,46 @@ { "name": "order", "type": "object", + "required": true, "description": "订单头对象(raw 行数据)" }, { "name": "detail", "type": "object", + "required": true, "description": "等同于 order" }, { "name": "orderItems / items", "type": "array", + "required": true, "description": "商品明细数组" }, { "name": "expresses", "type": "array", - "description": "运单信息数组" + "required": true, + "description": "运单信息数组,每个元素包含以下字段:waybill_code(运单号,string)、weighing_weight(称重重量,number|null)、sys_logistics_code(系统物流公司编码,string)、sys_logistics_name(系统物流公司名称,string)、logistics_code(实际物流公司编码,string)、logistics_name(实际物流公司名称,string)、logistics_interface_id(物流接口ID,number|null)、business_key(业务标识,string)、created_at(创建时间戳毫秒,number|null)" }, { "name": "waybill_codes", "type": "array", + "required": true, "description": "去重后的运单号字符串数组" } ], "errors": [ { "code": "400", - "description": "订单ID 为空或格式错误" + "message": "订单ID 为空或格式错误" }, { "code": "404", - "description": "订单不存在或不属于当前仓库" + "message": "订单不存在或不属于当前仓库" }, { "code": "500", - "description": "内部错误" + "message": "内部错误" } ] }, @@ -1937,7 +1942,7 @@ }, { "method": "order.updateExpressWeighingWeight", - "description": "更新订单运单称重重量。规则:订单仅一个运单时,直接写入该运单重量;多运单时,必须传 waybill_code 并按运单写入。", + "description": "更新订单运单称重重量。支持两种模式:1) 订单模式(order_id>0):规则:订单仅一个运单时,直接写入该运单重量;多运单时,必须传 waybill_code 并按运单写入;团购波次批量设置同一重量到波次下所有订单运单,并返回拆单汇总信息(total_weight/split_count/splits/store_name/sys_logistics_name)。2) 运单号模式(order_id=0):从运单号反查订单与波次,散单/非团购波次仅更新单个运单重量,团购波次按 wave_no+business_key 批量设置并返回拆单汇总信息。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -1954,14 +1959,14 @@ "type": "number|string", "required": true, "source": "body", - "description": "订单ID,必填且必须为正整数。" + "description": "订单ID,必填且必须为数字。订单模式下为正整数,设为0时切换为运单号模式(需配合 waybill_code 使用)。" }, { "name": "waybill_code", "type": "string", "required": false, "source": "body", - "description": "运单号;订单仅一个运单时可不传且会被忽略,多运单时必填并需匹配订单下运单。" + "description": "运单号。订单模式下:订单仅一个运单时可不传且会被忽略,多运单时必填并需匹配订单下运单。运单号模式(order_id=0)下必填。" }, { "name": "weighing_weight", @@ -1975,26 +1980,74 @@ { "name": "order_id", "type": "number", - "required": true, - "description": "订单ID(成功时返回于 data 对象中)。" + "required": false, + "description": "订单ID。订单模式及运单号散单模式返回。" }, { "name": "waybill_code", "type": "string", - "required": true, - "description": "写入重量的运单号(成功时返回于 data 对象中)。" + "required": false, + "description": "写入重量的运单号。订单模式及运单号散单模式返回。" }, { "name": "weighing_weight", "type": "number", "required": true, - "description": "已写入的称重重量(kg,成功时返回于 data 对象中)。" + "description": "已写入的称重重量(kg)。" + }, + { + "name": "wave_no", + "type": "string", + "required": false, + "description": "波次号。团购批量模式返回。" + }, + { + "name": "business_key", + "type": "string", + "required": false, + "description": "业务键。运单号团购批量模式返回。" + }, + { + "name": "wave_id", + "type": "number", + "required": false, + "description": "波次ID。团购批量模式返回。" + }, + { + "name": "total_weight", + "type": "number", + "required": false, + "description": "所有拆单重量累加(kg)。团购批量模式返回。" + }, + { + "name": "split_count", + "type": "number", + "required": false, + "description": "waybill_code 非空的 business_key 数量。团购批量模式返回。" + }, + { + "name": "splits", + "type": "array", + "required": false, + "description": "按 business_key 分组的拆单明细。每项含 business_key(业务键)、weighing_weight(该拆单累加重量)、waybill_code(代表运单号)。团购批量模式返回。" + }, + { + "name": "store_name", + "type": "string", + "required": false, + "description": "货主名称(订单 shop_nick)。团购批量模式返回。" + }, + { + "name": "sys_logistics_name", + "type": "string", + "required": false, + "description": "系统快递名称。团购批量模式返回。" } ], "errors": [ { "code": 400, - "message": "order_id 必填且必须为正整数" + "message": "order_id 必填且必须为数字(订单模式下为正整数;设为 0 时为运单号模式)" }, { "code": 400, @@ -2020,13 +2073,37 @@ "code": 404, "message": "waybill_code 未匹配到该订单下的运单记录" }, + { + "code": 404, + "message": "运单号不存在(运单号模式)" + }, + { + "code": 404, + "message": "运单号对应的订单不存在(运单号模式)" + }, + { + "code": 404, + "message": "波次下未找到订单(团购批量模式)" + }, { "code": 500, - "message": "订单快递模型未初始化" + "message": "运单模型未初始化" + }, + { + "code": 500, + "message": "订单模型未初始化" + }, + { + "code": 500, + "message": "波次模型未初始化" }, { "code": 500, "message": "更新称重重量失败" + }, + { + "code": 500, + "message": "批量更新称重重量失败,波次下无有效运单记录(团购批量模式)" } ] }, @@ -3853,7 +3930,7 @@ }, { "method": "order.pendingOrder.updateAddress", - "description": "批量修改待处理订单的收件地址信息。仅允许修改 post_status='none'(未分配快递)的订单;至少需要提供一个地址字段(name/mobile/tel/zip_code/province/city/area/town/detail_address),空值和纯空白会被忽略。更新成功后写入操作日志。", + "description": "批量修改待处理订单的收件地址信息和备注。地址字段修改仅允许 post_status='none'(未分配快递)的订单;remark 字段修改不受 post_status 限制可对所有订单生效。至少需要提供一个地址字段(name/mobile/tel/zip_code/province/city/area/town/detail_address)或 remark,空值和纯空白会被忽略。更新成功后写入操作日志。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -3934,6 +4011,13 @@ "required": false, "source": "body", "description": "详细地址" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "订单留言/备注,最大500字符。非空时批量覆盖所选订单的 remark 字段,不受 post_status 限制。" } ], "response": [ @@ -3941,7 +4025,7 @@ "name": "updated_count", "type": "number", "required": true, - "description": "实际更新的订单行数" + "description": "实际更新的订单行数(取地址更新行数与备注更新行数的最大值)。remark 字段的更新计数独立于地址字段。" }, { "name": "ids", @@ -3957,11 +4041,11 @@ }, { "code": 400, - "message": "至少需要提供一个地址字段进行修改" + "message": "至少需要提供一个地址字段或备注进行修改" }, { "code": 400, - "message": "仅允许修改 post_status='none'(未分配快递)的订单;若订单已分配快递则更新行数为 0,不会报错但实际无更新" + "message": "仅允许修改 post_status='none'(未分配快递)的订单(地址字段);若订单已分配快递则地址更新行数为 0,不会报错但实际无更新。remark 字段不受此限制。" } ] }, From 025184904a58bf95f4cb3072b15370bec79457a9 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sun, 14 Jun 2026 19:03:58 +0800 Subject: [PATCH 072/550] 1 --- app/lib/printer_data_builder.js | 5 +- app/model/entry_order.js | 8 +- app/model/picking.js | 9 + app/model/print_item.js | 2 +- app/model/print_template.js | 2 +- app/model/store.js | 5 + app/model/store_warehouse.js | 8 + app/schedule/auto_outbound_order.js | 11 +- app/schedule/pick_complete_compensation.js | 46 + app/service/systemMethods/dashboard.js | 122 ++- .../systemMethods/order/pendingOrder.js | 613 +++++++++++- .../systemMethods/order/recheckOrder.js | 914 +++++++++++++++++- app/service/systemMethods/order/wave.js | 30 +- app/service/systemMethods/outbound.js | 3 + .../systemMethods/setting/printTemplate.js | 2 +- app/service/systemMethods/stock/warehouse.js | 19 + .../systemMethods/storage/transaction.js | 4 +- app/service/systems/entry_order.js | 5 +- app/service/systems/express_platform.js | 149 +++ app/service/systems/order_auto_outbound.js | 33 +- .../systems/order_delivery_migration.js | 58 +- app/service/systems/order_export.js | 428 +++++++- app/service/systems/order_print.js | 152 ++- .../systems/order_storage_allocation.js | 72 ++ app/service/systems/pick.js | 126 +++ app/service/systems/pick_compensation.js | 694 +++++++++++++ app/service/systems/setting/print_template.js | 2 +- app/service/systems/setting/warehouse.js | 4 +- app/service/systems/stock_store.js | 41 +- app/service/systems/storage/entry.js | 2 +- app/service/systems/storage/inventory.js | 10 +- app/service/systems/store_warehouse.js | 13 + ...1100000-add-warehouse-id-to-wms-picking.js | 22 + ...0611180000-add-shrk-to-entry-order-type.js | 14 + ...20260611190000-merge-created-to-pending.js | 28 + logo.svg | 10 + methods/changes/system.json | 112 +++ methods/system.json | 571 +++++++++-- scripts/check_tables.js | 31 + scripts/query_more_test_orders.js | 50 + scripts/query_test_orders.js | 168 ++++ scripts/query_test_orders_v2.js | 98 ++ scripts/test_batch_quick_recheck.js | 169 ++++ scripts/test_batch_quick_recheck_full.js | 420 ++++++++ scripts/test_batch_quick_recheck_v2.js | 171 ++++ .../stock.warehouse.import.test.js | 226 +++++ ...der_print.getWavePlatformPrintData.test.js | 18 +- .../systems/order_storage_allocation.test.js | 526 ++++++++++ 48 files changed, 5920 insertions(+), 306 deletions(-) create mode 100644 app/schedule/pick_complete_compensation.js create mode 100644 app/service/systems/pick_compensation.js create mode 100644 database/migrations/20260611100000-add-warehouse-id-to-wms-picking.js create mode 100644 database/migrations/20260611180000-add-shrk-to-entry-order-type.js create mode 100644 database/migrations/20260611190000-merge-created-to-pending.js create mode 100644 logo.svg create mode 100644 scripts/check_tables.js create mode 100644 scripts/query_more_test_orders.js create mode 100644 scripts/query_test_orders.js create mode 100644 scripts/query_test_orders_v2.js create mode 100644 scripts/test_batch_quick_recheck.js create mode 100644 scripts/test_batch_quick_recheck_full.js create mode 100644 scripts/test_batch_quick_recheck_v2.js diff --git a/app/lib/printer_data_builder.js b/app/lib/printer_data_builder.js index f6a373e..7e00720 100644 --- a/app/lib/printer_data_builder.js +++ b/app/lib/printer_data_builder.js @@ -540,15 +540,14 @@ function buildWaybillCustomProductInfoLines(items, policyConfig = {}, options = const finalTotalQty = totalQty > 0 ? totalQty : (Number.isFinite(fallbackTotalQtyRaw) && fallbackTotalQtyRaw > 0 ? fallbackTotalQtyRaw : 0); + void platformsIndex; const hasWaveCustomPrefix = waveTotalOrders > 0 && waveIndex > 0 - && platformsIndex > 0 && Boolean(waveNo); const waveHeaderText = hasWaveCustomPrefix - ? `【${waveTotalOrders}】${waveNo}_${waveIndex}_${platformsIndex}` + ? `${waveNo} [${finalTotalQty}-${waveIndex}]` : waveNo; const headerParts = [ waveHeaderText, expressInterfaceName ].filter(Boolean); - headerParts.push(`商品数量【${finalTotalQty}】`); const headerLine = headerParts.join(' '); if (detailLines.length === 0) { diff --git a/app/model/entry_order.js b/app/model/entry_order.js index 5871ce8..f7f5b2a 100644 --- a/app/model/entry_order.js +++ b/app/model/entry_order.js @@ -19,7 +19,7 @@ module.exports = app => { }, }, order_type: { - type: ENUM('SCRK', 'LYRK', 'CCRK', 'CGRK', 'DBRK', 'QTRK', 'B2BRK', 'XNRK'), + type: ENUM('SCRK', 'LYRK', 'CCRK', 'CGRK', 'DBRK', 'QTRK', 'B2BRK', 'XNRK','SHRK'), allowNull: false, comment: '业务类型', }, @@ -81,7 +81,7 @@ module.exports = app => { comment: '来源类型', }, order_status: { - type: ENUM('PENDING', 'CONFIRMED', 'PARTIAL_RECEIVED', 'COMPLETED', 'CANCELLED', 'CREATED', 'CREATING'), + type: ENUM('PENDING', 'CONFIRMED', 'PARTIAL_RECEIVED', 'COMPLETED', 'CANCELLED', 'CREATING'), allowNull: false, defaultValue: 'PENDING', comment: '订单状态', @@ -258,11 +258,11 @@ module.exports = app => { }; EntryOrder.prototype.canConfirm = function() { - return [ 'PENDING', 'CREATED' ].includes(this.order_status); + return [ 'PENDING' ].includes(this.order_status); }; EntryOrder.prototype.canCancel = function() { - return [ 'PENDING', 'CONFIRMED', 'CREATED' ].includes(this.order_status); + return [ 'PENDING', 'CONFIRMED' ].includes(this.order_status); }; EntryOrder.prototype.canComplete = function() { diff --git a/app/model/picking.js b/app/model/picking.js index 38f7b18..987d337 100644 --- a/app/model/picking.js +++ b/app/model/picking.js @@ -16,6 +16,11 @@ module.exports = app => { allowNull: false, comment: '订单ID', }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, order_item_id: { type: BIGINT(20).UNSIGNED, allowNull: false, @@ -69,6 +74,10 @@ module.exports = app => { updatedAt: 'updated_at', comment: '订单储位分配表', indexes: [ + { + name: 'idx_wms_picking_warehouse_id', + fields: [ 'warehouse_id' ], + }, { name: 'idx_wms_picking_order_id', fields: [ 'order_id' ], diff --git a/app/model/print_item.js b/app/model/print_item.js index 178c9bb..01a9540 100644 --- a/app/model/print_item.js +++ b/app/model/print_item.js @@ -1,7 +1,7 @@ // app/model/print_item.js module.exports = app => { const { STRING, INTEGER, BOOLEAN, JSON, DATE } = app.Sequelize; - const SUPPORTED_BUSINESS_TYPES = [ 'STOCK', 'RECEIPT', 'PICKING' ]; + const SUPPORTED_BUSINESS_TYPES = [ 'STOCK', 'RECEIPT', 'PICKING', 'OUTBOUND' ]; const PrintItem = app.model.define('print_item', { id: { diff --git a/app/model/print_template.js b/app/model/print_template.js index a7f40b7..bc80068 100644 --- a/app/model/print_template.js +++ b/app/model/print_template.js @@ -3,7 +3,7 @@ module.exports = app => { const { BIGINT, STRING, INTEGER, BOOLEAN, JSON, DATE, DATEONLY } = app.Sequelize; - const SUPPORTED_BUSINESS_TYPES = [ 'STOCK', 'RECEIPT', 'PICKING' ]; + const SUPPORTED_BUSINESS_TYPES = [ 'STOCK', 'RECEIPT', 'PICKING', 'OUTBOUND' ]; const PrintTemplate = app.model.define('print_template', { id: { diff --git a/app/model/store.js b/app/model/store.js index 2ec757d..72865f9 100644 --- a/app/model/store.js +++ b/app/model/store.js @@ -34,6 +34,8 @@ module.exports = app => { require_pack: true, require_weigh: true, require_sync: true, + require_print: true, + require_pick: true, }); const DEFAULT_SUBJECT_CONFIG = Object.freeze({ @@ -127,6 +129,7 @@ module.exports = app => { /** * 规范化自动化出库规则配置。 + * 确保 enabled/require_recheck/require_pack/require_weigh/require_sync/require_print/require_pick 等字段存在且类型正确。 * * @param {Object|undefined|null} rawRules 原始自动化出库规则。 * @return {Object} 规范化后的自动化出库规则对象。 @@ -155,6 +158,8 @@ module.exports = app => { require_pack: parsed.require_pack !== false, require_weigh: parsed.require_weigh !== false, require_sync: parsed.require_sync !== false, + require_print: parsed.require_print !== false, + require_pick: parsed.require_pick !== false, }; }; diff --git a/app/model/store_warehouse.js b/app/model/store_warehouse.js index 379587f..b1564f3 100644 --- a/app/model/store_warehouse.js +++ b/app/model/store_warehouse.js @@ -87,6 +87,14 @@ module.exports = app => { required: false, description: '控制货主推送订单创建后是否必须进入审批流程', }), + Object.freeze({ + key: 'auto_sync_back', + name: '自动同步回传', + type: 'flag', + default: 1, + required: false, + description: '快递号分配成功后是否自动同步订单信息到外部系统(奇门/API/手动)', + }), Object.freeze({ key: 'enable_external_express_code', name: '启用外部快递编码', diff --git a/app/schedule/auto_outbound_order.js b/app/schedule/auto_outbound_order.js index 8917efb..148a670 100644 --- a/app/schedule/auto_outbound_order.js +++ b/app/schedule/auto_outbound_order.js @@ -9,6 +9,9 @@ * 1. 已复核:recheck_status = 'fin' * 2. 已打包:pack_status = 'fin' * 3. 已称重:wms_order_express.weighing_weight > 0 + * 4. 已同步:sync_status = 'fin' + * 5. 已打印:print_status = 'fin' + * 6. 已拣货:pick_status = 'fin' * * 各条件是否必须可由仓库配置独立控制。 */ @@ -36,11 +39,9 @@ module.exports = { try { const result = await ctx.service.systems.orderAutoOutbound.executeAutoOutbound(); - if (result && result.totalProcessed > 0) { - ctx.logger.info( - `[auto-outbound-order] 本轮自动化出库完成,共处理 ${result.totalProcessed} 条订单` - ); - } + ctx.logger.info( + `[auto-outbound-order] 本轮自动化出库完成,共处理 ${result && result.totalProcessed || 0} 条订单` + ); } catch (error) { ctx.logger.error(`[auto-outbound-order] 自动化出库任务执行失败: ${error.message}`); } finally { diff --git a/app/schedule/pick_complete_compensation.js b/app/schedule/pick_complete_compensation.js new file mode 100644 index 0000000..7b28143 --- /dev/null +++ b/app/schedule/pick_complete_compensation.js @@ -0,0 +1,46 @@ +'use strict'; + +/** + * 拣货完成补偿定时任务。 + * 每 1 分钟在单 worker 中扫描一次:当 wms_picking 中存在 status='pending' 的遗漏记录, + * 且对应订单已迁移到配送 dispatch 表且 pick_status='fin' 时,补扣库存并写入出库流水。 + * + * 补偿判断条件: + * 1. wms_picking.status = 'pending' 且 warehouse_id > 0 + * 2. 对应订单在 order_delivery_dispatch 表中 pick_status = 'fin' + * 3. 对应订单不在 order_delivery 主表中(已迁移) + */ +module.exports = { + schedule: { + interval: '1m', + type: 'worker', + immediate: true, + disable: false, + }, + + /** + * 执行拣货完成补偿任务。 + * + * @param {Object} ctx Egg 上下文。 + * @return {Promise} 无返回值。 + */ + async task(ctx) { + if (ctx.app._pickCompensationRunning) { + return; + } + + ctx.app._pickCompensationRunning = true; + + try { + const result = await ctx.service.systems.pickCompensation.executeCompensation(); + + ctx.logger.info( + `[pick-compensation] 本轮补偿完成,共处理 ${result && result.totalCompensated || 0} 条拣货记录` + ); + } catch (error) { + ctx.logger.error(`[pick-compensation] 补偿任务执行失败: ${error.message}`); + } finally { + ctx.app._pickCompensationRunning = false; + } + }, +}; diff --git a/app/service/systemMethods/dashboard.js b/app/service/systemMethods/dashboard.js index 64a98dc..8868138 100644 --- a/app/service/systemMethods/dashboard.js +++ b/app/service/systemMethods/dashboard.js @@ -19,7 +19,6 @@ class dashboardService extends MainService { } const model = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); - const dispatchModel = await ctx.model.OrderDeliveryFactory.getDispatchModel(warehouseId); const { Sequelize } = ctx.app; const { Op } = Sequelize; @@ -55,7 +54,7 @@ class dashboardService extends MainService { 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: { step: 4, outbound_status: 'fin', status: { [Op.ne]: 'cancel' }, 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 } }), ]); @@ -77,7 +76,7 @@ class dashboardService extends MainService { code: 200, message: '成功', data: { - todayOrders: totalPending, + todayOrders: totalPending + todayOutbound, orderTrend, unassignedOrders, @@ -301,25 +300,124 @@ class dashboardService extends MainService { return this.success('ok', data); } + /** + * 订单趋势统计:按小时统计当日订单数与发货数 + * @returns {Object} 包含 categories(时段)、orders(订单数)、shipments(发货数)和 summary(汇总)的响应数据 + */ async order_trend() { + 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; + + // 今日时间范围 + const now = new Date(); + const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate()); + const currentHour = now.getHours(); + + // 时间段:08:00 到当前小时(最晚 23:00),若当前小时早于 08:00 则从 08:00 开始 + const startHour = 8; + const endHour = currentHour < startHour ? startHour : Math.min(currentHour, 23); + + // 生成 categories 和初始化小时映射 + const categories = []; + const orderMap = {}; + const shipmentMap = {}; + for (let h = startHour; h <= endHour; h++) { + const key = `${String(h).padStart(2, '0')}:00`; + categories.push(key); + orderMap[h] = 0; + shipmentMap[h] = 0; + } + + // 查询订单数按创建小时分组 + const orderRows = await model.findAll({ + attributes: [ + [ Sequelize.fn('HOUR', Sequelize.col('create_at')), 'hour' ], + [ Sequelize.fn('COUNT', Sequelize.col('id')), 'cnt' ], + ], + where: { + step: { [Op.in]: [ 1, 2, 3 ] }, + outbound_status: { [Op.ne]: 'padding' }, + status: { [Op.ne]: 'cancel' }, + create_at: { [Op.gte]: todayStart, [Op.lte]: now }, + }, + group: [ Sequelize.fn('HOUR', Sequelize.col('create_at')) ], + raw: true, + }); + + // 查询发货数按发货小时分组 + const shipmentRows = await dispatchModel.findAll({ + attributes: [ + [ Sequelize.fn('HOUR', Sequelize.col('delivery_time')), 'hour' ], + [ Sequelize.fn('COUNT', Sequelize.col('id')), 'cnt' ], + ], + where: { + dispatch_lane: 'm4', + delivery_time: { [Op.gte]: todayStart, [Op.lte]: now }, + }, + group: [ Sequelize.fn('HOUR', Sequelize.col('delivery_time')) ], + raw: true, + }); + + // 将查询结果填充到小时映射 + for (const row of orderRows) { + orderMap[row.hour] = Number(row.cnt); + } + for (const row of shipmentRows) { + shipmentMap[row.hour] = Number(row.cnt); + } + + // 按 categories 顺序构建 orders / shipments 数组 + const orders = categories.map(cat => orderMap[parseInt(cat, 10)] || 0); + const shipments = categories.map(cat => shipmentMap[parseInt(cat, 10)] || 0); + + // 汇总计算 + const totalOrders = orders.reduce((sum, v) => sum + v, 0); + const totalShipments = shipments.reduce((sum, v) => sum + v, 0); + const shipmentRate = totalOrders > 0 + ? parseFloat(((totalShipments / totalOrders) * 100).toFixed(1)) + : 0; + + // 找订单峰值小时 + let peakHour = categories[0] || '08:00'; + let peakOrders = 0; + for (let i = 0; i < categories.length; i++) { + if (orders[i] > peakOrders) { + peakOrders = orders[i]; + peakHour = categories[i]; + } + } + + // 当天日期 YYYY-MM-DD + const dateStr = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`; + const data = { code: 200, message: '成功', data: { range: 'day', - date: '2024-01-15', + date: dateStr, summary: { - total_orders: 1256, - total_shipments: 892, - shipment_rate: 71.0, - peak_hour: '15:00', - peak_orders: 178, + total_orders: totalOrders, + total_shipments: totalShipments, + shipment_rate: shipmentRate, + peak_hour: peakHour, + peak_orders: peakOrders, }, - categories: [ '08:00', '09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00' ], - orders: [ 138, 84378, 102120, 129156, 153020, 153020, 153020, 153020, 153020, 153020 ], - shipments: [ 0, 30000, 60000, 70000, 86479, 86479, 86479, 86479, 86479, 86479 ], + categories, + orders, + shipments, }, }; + return this.success('ok', data); } } diff --git a/app/service/systemMethods/order/pendingOrder.js b/app/service/systemMethods/order/pendingOrder.js index 49442ee..2b6d871 100644 --- a/app/service/systemMethods/order/pendingOrder.js +++ b/app/service/systemMethods/order/pendingOrder.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict'; const OrderBaseService = require('./base'); @@ -31,6 +31,472 @@ const BATCH_UNLOCK_TASK_CACHE_TTL_SECONDS = 60 * 60 * 24; const BATCH_UNINTERCEPT_TASK_CACHE_KEY_PREFIX = 'order:batch-unintercept:'; const BATCH_UNINTERCEPT_TASK_CACHE_TTL_SECONDS = 60 * 60 * 24; +/** + * 中国行政区划反向查询表。 + * + * 用于在 AI 解析结果缺少 province/city/area 时进行兜底反向推断。 + * 覆盖三类特殊行政区: + * - direct:省直辖县级市(如湖北仙桃、潜江、天门) + * - no_district:不设区的地级市(如东莞、中山、嘉峪关、儋州、三沙) + * - delegated:地级市代管县级市(如苏州代管昆山) + * + * 键为 area(区/县)标准名称,值为 { province, city, type }。 + * 同时提供 city -> province 的映射表用于根据城市名反查省份。 + */ +const CHINA_ADMIN_DIVISION_MAP = Object.freeze({ + // ========== 省直辖县级市 / 省直管县 ========== + 仙桃市: { province: '湖北省', city: '湖北省', type: 'direct' }, + 潜江市: { province: '湖北省', city: '湖北省', type: 'direct' }, + 天门市: { province: '湖北省', city: '湖北省', type: 'direct' }, + 神农架林区: { province: '湖北省', city: '湖北省', type: 'direct' }, + 济源市: { province: '河南省', city: '河南省', type: 'direct' }, + 五指山市: { province: '海南省', city: '海南省', type: 'direct' }, + 琼海市: { province: '海南省', city: '海南省', type: 'direct' }, + 文昌市: { province: '海南省', city: '海南省', type: 'direct' }, + 万宁市: { province: '海南省', city: '海南省', type: 'direct' }, + 东方市: { province: '海南省', city: '海南省', type: 'direct' }, + 定安县: { province: '海南省', city: '海南省', type: 'direct' }, + 屯昌县: { province: '海南省', city: '海南省', type: 'direct' }, + 澄迈县: { province: '海南省', city: '海南省', type: 'direct' }, + 临高县: { province: '海南省', city: '海南省', type: 'direct' }, + 白沙黎族自治县: { province: '海南省', city: '海南省', type: 'direct' }, + 昌江黎族自治县: { province: '海南省', city: '海南省', type: 'direct' }, + 乐东黎族自治县: { province: '海南省', city: '海南省', type: 'direct' }, + 陵水黎族自治县: { province: '海南省', city: '海南省', type: 'direct' }, + 保亭黎族苗族自治县: { province: '海南省', city: '海南省', type: 'direct' }, + 琼中黎族苗族自治县: { province: '海南省', city: '海南省', type: 'direct' }, + 石河子市: { province: '新疆维吾尔自治区', city: '新疆维吾尔自治区', type: 'direct' }, + 阿拉尔市: { province: '新疆维吾尔自治区', city: '新疆维吾尔自治区', type: 'direct' }, + 图木舒克市: { province: '新疆维吾尔自治区', city: '新疆维吾尔自治区', type: 'direct' }, + 五家渠市: { province: '新疆维吾尔自治区', city: '新疆维吾尔自治区', type: 'direct' }, + 北屯市: { province: '新疆维吾尔自治区', city: '新疆维吾尔自治区', type: 'direct' }, + 铁门关市: { province: '新疆维吾尔自治区', city: '新疆维吾尔自治区', type: 'direct' }, + 双河市: { province: '新疆维吾尔自治区', city: '新疆维吾尔自治区', type: 'direct' }, + 可克达拉市: { province: '新疆维吾尔自治区', city: '新疆维吾尔自治区', type: 'direct' }, + 昆玉市: { province: '新疆维吾尔自治区', city: '新疆维吾尔自治区', type: 'direct' }, + 胡杨河市: { province: '新疆维吾尔自治区', city: '新疆维吾尔自治区', type: 'direct' }, + 新星市: { province: '新疆维吾尔自治区', city: '新疆维吾尔自治区', type: 'direct' }, + 白杨市: { province: '新疆维吾尔自治区', city: '新疆维吾尔自治区', type: 'direct' }, + + // ========== 不设区的地级市(city 和 area 可为同一值) ========== + 东莞市: { province: '广东省', city: '东莞市', type: 'no_district' }, + 中山市: { province: '广东省', city: '中山市', type: 'no_district' }, + 嘉峪关市: { province: '甘肃省', city: '嘉峪关市', type: 'no_district' }, + 儋州市: { province: '海南省', city: '儋州市', type: 'no_district' }, + 三沙市: { province: '海南省', city: '三沙市', type: 'no_district' }, + + // ========== 常见地级市代管县级市 ========== + 昆山市: { province: '江苏省', city: '苏州市', type: 'delegated' }, + 常熟市: { province: '江苏省', city: '苏州市', type: 'delegated' }, + 张家港市: { province: '江苏省', city: '苏州市', type: 'delegated' }, + 太仓市: { province: '江苏省', city: '苏州市', type: 'delegated' }, + 江阴市: { province: '江苏省', city: '无锡市', type: 'delegated' }, + 宜兴市: { province: '江苏省', city: '无锡市', type: 'delegated' }, + 丹阳市: { province: '江苏省', city: '镇江市', type: 'delegated' }, + 扬中市: { province: '江苏省', city: '镇江市', type: 'delegated' }, + 句容市: { province: '江苏省', city: '镇江市', type: 'delegated' }, + 溧阳市: { province: '江苏省', city: '常州市', type: 'delegated' }, + 海安市: { province: '江苏省', city: '南通市', type: 'delegated' }, + 启东市: { province: '江苏省', city: '南通市', type: 'delegated' }, + 如皋市: { province: '江苏省', city: '南通市', type: 'delegated' }, + 仪征市: { province: '江苏省', city: '扬州市', type: 'delegated' }, + 高邮市: { province: '江苏省', city: '扬州市', type: 'delegated' }, + 兴化市: { province: '江苏省', city: '泰州市', type: 'delegated' }, + 靖江市: { province: '江苏省', city: '泰州市', type: 'delegated' }, + 泰兴市: { province: '江苏省', city: '泰州市', type: 'delegated' }, + 邳州市: { province: '江苏省', city: '徐州市', type: 'delegated' }, + 新沂市: { province: '江苏省', city: '徐州市', type: 'delegated' }, + 东台市: { province: '江苏省', city: '盐城市', type: 'delegated' }, + 建德市: { province: '浙江省', city: '杭州市', type: 'delegated' }, + 慈溪市: { province: '浙江省', city: '宁波市', type: 'delegated' }, + 余姚市: { province: '浙江省', city: '宁波市', type: 'delegated' }, + 瑞安市: { province: '浙江省', city: '温州市', type: 'delegated' }, + 乐清市: { province: '浙江省', city: '温州市', type: 'delegated' }, + 海宁市: { province: '浙江省', city: '嘉兴市', type: 'delegated' }, + 平湖市: { province: '浙江省', city: '嘉兴市', type: 'delegated' }, + 桐乡市: { province: '浙江省', city: '嘉兴市', type: 'delegated' }, + 诸暨市: { province: '浙江省', city: '绍兴市', type: 'delegated' }, + 嵊州市: { province: '浙江省', city: '绍兴市', type: 'delegated' }, + 兰溪市: { province: '浙江省', city: '金华市', type: 'delegated' }, + 义乌市: { province: '浙江省', city: '金华市', type: 'delegated' }, + 东阳市: { province: '浙江省', city: '金华市', type: 'delegated' }, + 永康市: { province: '浙江省', city: '金华市', type: 'delegated' }, + 江山市: { province: '浙江省', city: '衢州市', type: 'delegated' }, + 温岭市: { province: '浙江省', city: '台州市', type: 'delegated' }, + 临海市: { province: '浙江省', city: '台州市', type: 'delegated' }, + 龙泉市: { province: '浙江省', city: '丽水市', type: 'delegated' }, + 巢湖市: { province: '安徽省', city: '合肥市', type: 'delegated' }, + 无为市: { province: '安徽省', city: '芜湖市', type: 'delegated' }, + 桐城市: { province: '安徽省', city: '安庆市', type: 'delegated' }, + 天长市: { province: '安徽省', city: '滁州市', type: 'delegated' }, + 明光市: { province: '安徽省', city: '滁州市', type: 'delegated' }, + 界首市: { province: '安徽省', city: '阜阳市', type: 'delegated' }, + 宁国市: { province: '安徽省', city: '宣城市', type: 'delegated' }, + 广德市: { province: '安徽省', city: '宣城市', type: 'delegated' }, + 福清市: { province: '福建省', city: '福州市', type: 'delegated' }, + 晋江市: { province: '福建省', city: '泉州市', type: 'delegated' }, + 南安市: { province: '福建省', city: '泉州市', type: 'delegated' }, + 石狮市: { province: '福建省', city: '泉州市', type: 'delegated' }, + 龙海市: { province: '福建省', city: '漳州市', type: 'delegated' }, + 邵武市: { province: '福建省', city: '南平市', type: 'delegated' }, + 武夷山市: { province: '福建省', city: '南平市', type: 'delegated' }, + 漳平市: { province: '福建省', city: '龙岩市', type: 'delegated' }, + 福安市: { province: '福建省', city: '宁德市', type: 'delegated' }, + 福鼎市: { province: '福建省', city: '宁德市', type: 'delegated' }, + 乐平市: { province: '江西省', city: '景德镇市', type: 'delegated' }, + 瑞昌市: { province: '江西省', city: '九江市', type: 'delegated' }, + 共青城市: { province: '江西省', city: '九江市', type: 'delegated' }, + 庐山市: { province: '江西省', city: '九江市', type: 'delegated' }, + 贵溪市: { province: '江西省', city: '鹰潭市', type: 'delegated' }, + 瑞金市: { province: '江西省', city: '赣州市', type: 'delegated' }, + 井冈山市: { province: '江西省', city: '吉安市', type: 'delegated' }, + 丰城市: { province: '江西省', city: '宜春市', type: 'delegated' }, + 樟树市: { province: '江西省', city: '宜春市', type: 'delegated' }, + 高安市: { province: '江西省', city: '宜春市', type: 'delegated' }, + 德兴市: { province: '江西省', city: '上饶市', type: 'delegated' }, + 章丘区: { province: '山东省', city: '济南市', type: 'delegated' }, + 胶州市: { province: '山东省', city: '青岛市', type: 'delegated' }, + 平度市: { province: '山东省', city: '青岛市', type: 'delegated' }, + 莱西市: { province: '山东省', city: '青岛市', type: 'delegated' }, + 滕州市: { province: '山东省', city: '枣庄市', type: 'delegated' }, + 龙口市: { province: '山东省', city: '烟台市', type: 'delegated' }, + 莱阳市: { province: '山东省', city: '烟台市', type: 'delegated' }, + 莱州市: { province: '山东省', city: '烟台市', type: 'delegated' }, + 招远市: { province: '山东省', city: '烟台市', type: 'delegated' }, + 栖霞市: { province: '山东省', city: '烟台市', type: 'delegated' }, + 海阳市: { province: '山东省', city: '烟台市', type: 'delegated' }, + 青州市: { province: '山东省', city: '潍坊市', type: 'delegated' }, + 诸城市: { province: '山东省', city: '潍坊市', type: 'delegated' }, + 寿光市: { province: '山东省', city: '潍坊市', type: 'delegated' }, + 安丘市: { province: '山东省', city: '潍坊市', type: 'delegated' }, + 高密市: { province: '山东省', city: '潍坊市', type: 'delegated' }, + 昌邑市: { province: '山东省', city: '潍坊市', type: 'delegated' }, + 曲阜市: { province: '山东省', city: '济宁市', type: 'delegated' }, + 邹城市: { province: '山东省', city: '济宁市', type: 'delegated' }, + 新泰市: { province: '山东省', city: '泰安市', type: 'delegated' }, + 肥城市: { province: '山东省', city: '泰安市', type: 'delegated' }, + 荣成市: { province: '山东省', city: '威海市', type: 'delegated' }, + 乳山市: { province: '山东省', city: '威海市', type: 'delegated' }, + 乐陵市: { province: '山东省', city: '德州市', type: 'delegated' }, + 禹城市: { province: '山东省', city: '德州市', type: 'delegated' }, + 临清市: { province: '山东省', city: '聊城市', type: 'delegated' }, + 巩义市: { province: '河南省', city: '郑州市', type: 'delegated' }, + 新密市: { province: '河南省', city: '郑州市', type: 'delegated' }, + 荥阳市: { province: '河南省', city: '郑州市', type: 'delegated' }, + 新郑市: { province: '河南省', city: '郑州市', type: 'delegated' }, + 登封市: { province: '河南省', city: '郑州市', type: 'delegated' }, + 偃师区: { province: '河南省', city: '洛阳市', type: 'delegated' }, + 舞钢市: { province: '河南省', city: '平顶山市', type: 'delegated' }, + 汝州市: { province: '河南省', city: '平顶山市', type: 'delegated' }, + 林州市: { province: '河南省', city: '安阳市', type: 'delegated' }, + 卫辉市: { province: '河南省', city: '新乡市', type: 'delegated' }, + 辉县市: { province: '河南省', city: '新乡市', type: 'delegated' }, + 长垣市: { province: '河南省', city: '新乡市', type: 'delegated' }, + 沁阳市: { province: '河南省', city: '焦作市', type: 'delegated' }, + 孟州市: { province: '河南省', city: '焦作市', type: 'delegated' }, + 禹州市: { province: '河南省', city: '许昌市', type: 'delegated' }, + 长葛市: { province: '河南省', city: '许昌市', type: 'delegated' }, + 义马市: { province: '河南省', city: '三门峡市', type: 'delegated' }, + 灵宝市: { province: '河南省', city: '三门峡市', type: 'delegated' }, + 邓州市: { province: '河南省', city: '南阳市', type: 'delegated' }, + 永城市: { province: '河南省', city: '商丘市', type: 'delegated' }, + 项城市: { province: '河南省', city: '周口市', type: 'delegated' }, + 大冶市: { province: '湖北省', city: '黄石市', type: 'delegated' }, + 丹江口市: { province: '湖北省', city: '十堰市', type: 'delegated' }, + 宜都市: { province: '湖北省', city: '宜昌市', type: 'delegated' }, + 当阳市: { province: '湖北省', city: '宜昌市', type: 'delegated' }, + 枝江市: { province: '湖北省', city: '宜昌市', type: 'delegated' }, + 老河口市: { province: '湖北省', city: '襄阳市', type: 'delegated' }, + 枣阳市: { province: '湖北省', city: '襄阳市', type: 'delegated' }, + 宜城市: { province: '湖北省', city: '襄阳市', type: 'delegated' }, + 钟祥市: { province: '湖北省', city: '荆门市', type: 'delegated' }, + 京山市: { province: '湖北省', city: '荆门市', type: 'delegated' }, + 应城市: { province: '湖北省', city: '孝感市', type: 'delegated' }, + 安陆市: { province: '湖北省', city: '孝感市', type: 'delegated' }, + 汉川市: { province: '湖北省', city: '孝感市', type: 'delegated' }, + 石首市: { province: '湖北省', city: '荆州市', type: 'delegated' }, + 洪湖市: { province: '湖北省', city: '荆州市', type: 'delegated' }, + 松滋市: { province: '湖北省', city: '荆州市', type: 'delegated' }, + 监利市: { province: '湖北省', city: '荆州市', type: 'delegated' }, + 麻城市: { province: '湖北省', city: '黄冈市', type: 'delegated' }, + 武穴市: { province: '湖北省', city: '黄冈市', type: 'delegated' }, + 赤壁市: { province: '湖北省', city: '咸宁市', type: 'delegated' }, + 广水市: { province: '湖北省', city: '随州市', type: 'delegated' }, + 恩施市: { province: '湖北省', city: '恩施土家族苗族自治州', type: 'delegated' }, + 利川市: { province: '湖北省', city: '恩施土家族苗族自治州', type: 'delegated' }, + 浏阳市: { province: '湖南省', city: '长沙市', type: 'delegated' }, + 宁乡市: { province: '湖南省', city: '长沙市', type: 'delegated' }, + 醴陵市: { province: '湖南省', city: '株洲市', type: 'delegated' }, + 湘乡市: { province: '湖南省', city: '湘潭市', type: 'delegated' }, + 韶山市: { province: '湖南省', city: '湘潭市', type: 'delegated' }, + 耒阳市: { province: '湖南省', city: '衡阳市', type: 'delegated' }, + 常宁市: { province: '湖南省', city: '衡阳市', type: 'delegated' }, + 武冈市: { province: '湖南省', city: '邵阳市', type: 'delegated' }, + 邵东市: { province: '湖南省', city: '邵阳市', type: 'delegated' }, + 汨罗市: { province: '湖南省', city: '岳阳市', type: 'delegated' }, + 临湘市: { province: '湖南省', city: '岳阳市', type: 'delegated' }, + 津市市: { province: '湖南省', city: '常德市', type: 'delegated' }, + 沅江市: { province: '湖南省', city: '益阳市', type: 'delegated' }, + 资兴市: { province: '湖南省', city: '郴州市', type: 'delegated' }, + 洪江市: { province: '湖南省', city: '怀化市', type: 'delegated' }, + 冷水江市: { province: '湖南省', city: '娄底市', type: 'delegated' }, + 涟源市: { province: '湖南省', city: '娄底市', type: 'delegated' }, + 吉首市: { province: '湖南省', city: '湘西土家族苗族自治州', type: 'delegated' }, + 增城区: { province: '广东省', city: '广州市', type: 'delegated' }, + 从化区: { province: '广东省', city: '广州市', type: 'delegated' }, + 乐昌市: { province: '广东省', city: '韶关市', type: 'delegated' }, + 南雄市: { province: '广东省', city: '韶关市', type: 'delegated' }, + 廉江市: { province: '广东省', city: '湛江市', type: 'delegated' }, + 雷州市: { province: '广东省', city: '湛江市', type: 'delegated' }, + 吴川市: { province: '广东省', city: '湛江市', type: 'delegated' }, + 高州市: { province: '广东省', city: '茂名市', type: 'delegated' }, + 化州市: { province: '广东省', city: '茂名市', type: 'delegated' }, + 信宜市: { province: '广东省', city: '茂名市', type: 'delegated' }, + 高要区: { province: '广东省', city: '肇庆市', type: 'delegated' }, + 四会市: { province: '广东省', city: '肇庆市', type: 'delegated' }, + 惠东县: { province: '广东省', city: '惠州市', type: 'delegated' }, + 博罗县: { province: '广东省', city: '惠州市', type: 'delegated' }, + 龙门县: { province: '广东省', city: '惠州市', type: 'delegated' }, + 兴宁市: { province: '广东省', city: '梅州市', type: 'delegated' }, + 陆丰市: { province: '广东省', city: '汕尾市', type: 'delegated' }, + 阳春市: { province: '广东省', city: '阳江市', type: 'delegated' }, + 英德市: { province: '广东省', city: '清远市', type: 'delegated' }, + 连州市: { province: '广东省', city: '清远市', type: 'delegated' }, + 普宁市: { province: '广东省', city: '揭阳市', type: 'delegated' }, + 罗定市: { province: '广东省', city: '云浮市', type: 'delegated' }, + 岑溪市: { province: '广西壮族自治区', city: '梧州市', type: 'delegated' }, + 东兴市: { province: '广西壮族自治区', city: '防城港市', type: 'delegated' }, + 桂平市: { province: '广西壮族自治区', city: '贵港市', type: 'delegated' }, + 北流市: { province: '广西壮族自治区', city: '玉林市', type: 'delegated' }, + 靖西市: { province: '广西壮族自治区', city: '百色市', type: 'delegated' }, + 平果市: { province: '广西壮族自治区', city: '百色市', type: 'delegated' }, + 合山市: { province: '广西壮族自治区', city: '来宾市', type: 'delegated' }, + 凭祥市: { province: '广西壮族自治区', city: '崇左市', type: 'delegated' }, + 都江堰市: { province: '四川省', city: '成都市', type: 'delegated' }, + 彭州市: { province: '四川省', city: '成都市', type: 'delegated' }, + 邛崃市: { province: '四川省', city: '成都市', type: 'delegated' }, + 崇州市: { province: '四川省', city: '成都市', type: 'delegated' }, + 简阳市: { province: '四川省', city: '成都市', type: 'delegated' }, + 广汉市: { province: '四川省', city: '德阳市', type: 'delegated' }, + 什邡市: { province: '四川省', city: '德阳市', type: 'delegated' }, + 绵竹市: { province: '四川省', city: '德阳市', type: 'delegated' }, + 江油市: { province: '四川省', city: '绵阳市', type: 'delegated' }, + 峨眉山市: { province: '四川省', city: '乐山市', type: 'delegated' }, + 阆中市: { province: '四川省', city: '南充市', type: 'delegated' }, + 华蓥市: { province: '四川省', city: '广安市', type: 'delegated' }, + 万源市: { province: '四川省', city: '达州市', type: 'delegated' }, + 西昌市: { province: '四川省', city: '凉山彝族自治州', type: 'delegated' }, + 会理市: { province: '四川省', city: '凉山彝族自治州', type: 'delegated' }, + 康定市: { province: '四川省', city: '甘孜藏族自治州', type: 'delegated' }, + 马尔康市: { province: '四川省', city: '阿坝藏族羌族自治州', type: 'delegated' }, + 清镇市: { province: '贵州省', city: '贵阳市', type: 'delegated' }, + 盘州市: { province: '贵州省', city: '六盘水市', type: 'delegated' }, + 赤水市: { province: '贵州省', city: '遵义市', type: 'delegated' }, + 仁怀市: { province: '贵州省', city: '遵义市', type: 'delegated' }, + 兴义市: { province: '贵州省', city: '黔西南布依族苗族自治州', type: 'delegated' }, + 兴仁市: { province: '贵州省', city: '黔西南布依族苗族自治州', type: 'delegated' }, + 凯里市: { province: '贵州省', city: '黔东南苗族侗族自治州', type: 'delegated' }, + 都匀市: { province: '贵州省', city: '黔南布依族苗族自治州', type: 'delegated' }, + 福泉市: { province: '贵州省', city: '黔南布依族苗族自治州', type: 'delegated' }, + 安宁市: { province: '云南省', city: '昆明市', type: 'delegated' }, + 宣威市: { province: '云南省', city: '曲靖市', type: 'delegated' }, + 腾冲市: { province: '云南省', city: '保山市', type: 'delegated' }, + 水富市: { province: '云南省', city: '昭通市', type: 'delegated' }, + 楚雄市: { province: '云南省', city: '楚雄彝族自治州', type: 'delegated' }, + 禄丰市: { province: '云南省', city: '楚雄彝族自治州', type: 'delegated' }, + 个旧市: { province: '云南省', city: '红河哈尼族彝族自治州', type: 'delegated' }, + 开远市: { province: '云南省', city: '红河哈尼族彝族自治州', type: 'delegated' }, + 蒙自市: { province: '云南省', city: '红河哈尼族彝族自治州', type: 'delegated' }, + 弥勒市: { province: '云南省', city: '红河哈尼族彝族自治州', type: 'delegated' }, + 文山市: { province: '云南省', city: '文山壮族苗族自治州', type: 'delegated' }, + 景洪市: { province: '云南省', city: '西双版纳傣族自治州', type: 'delegated' }, + 大理市: { province: '云南省', city: '大理白族自治州', type: 'delegated' }, + 瑞丽市: { province: '云南省', city: '德宏傣族景颇族自治州', type: 'delegated' }, + 芒市: { province: '云南省', city: '德宏傣族景颇族自治州', type: 'delegated' }, + 泸水市: { province: '云南省', city: '怒江傈僳族自治州', type: 'delegated' }, + 香格里拉市: { province: '云南省', city: '迪庆藏族自治州', type: 'delegated' }, + 兴平市: { province: '陕西省', city: '咸阳市', type: 'delegated' }, + 彬州市: { province: '陕西省', city: '咸阳市', type: 'delegated' }, + 韩城市: { province: '陕西省', city: '渭南市', type: 'delegated' }, + 华阴市: { province: '陕西省', city: '渭南市', type: 'delegated' }, + 子长市: { province: '陕西省', city: '延安市', type: 'delegated' }, + 神木市: { province: '陕西省', city: '榆林市', type: 'delegated' }, + 玉门市: { province: '甘肃省', city: '酒泉市', type: 'delegated' }, + 敦煌市: { province: '甘肃省', city: '酒泉市', type: 'delegated' }, + 华亭市: { province: '甘肃省', city: '平凉市', type: 'delegated' }, + 合作市: { province: '甘肃省', city: '甘南藏族自治州', type: 'delegated' }, + 格尔木市: { province: '青海省', city: '海西蒙古族藏族自治州', type: 'delegated' }, + 茫崖市: { province: '青海省', city: '海西蒙古族藏族自治州', type: 'delegated' }, + 德令哈市: { province: '青海省', city: '海西蒙古族藏族自治州', type: 'delegated' }, + 玉树市: { province: '青海省', city: '玉树藏族自治州', type: 'delegated' }, + 灵武市: { province: '宁夏回族自治区', city: '银川市', type: 'delegated' }, + 青铜峡市: { province: '宁夏回族自治区', city: '吴忠市', type: 'delegated' }, + 奎屯市: { province: '新疆维吾尔自治区', city: '伊犁哈萨克自治州', type: 'delegated' }, + 霍尔果斯市: { province: '新疆维吾尔自治区', city: '伊犁哈萨克自治州', type: 'delegated' }, + 库尔勒市: { province: '新疆维吾尔自治区', city: '巴音郭楞蒙古自治州', type: 'delegated' }, + 阿克苏市: { province: '新疆维吾尔自治区', city: '阿克苏地区', type: 'delegated' }, + 库车市: { province: '新疆维吾尔自治区', city: '阿克苏地区', type: 'delegated' }, + 阿图什市: { province: '新疆维吾尔自治区', city: '克孜勒苏柯尔克孜自治州', type: 'delegated' }, + 喀什市: { province: '新疆维吾尔自治区', city: '喀什地区', type: 'delegated' }, + 和田市: { province: '新疆维吾尔自治区', city: '和田地区', type: 'delegated' }, + 博乐市: { province: '新疆维吾尔自治区', city: '博尔塔拉蒙古自治州', type: 'delegated' }, + 阿拉山口市: { province: '新疆维吾尔自治区', city: '博尔塔拉蒙古自治州', type: 'delegated' }, + 伊宁市: { province: '新疆维吾尔自治区', city: '伊犁哈萨克自治州', type: 'delegated' }, + 塔城市: { province: '新疆维吾尔自治区', city: '塔城地区', type: 'delegated' }, + 乌苏市: { province: '新疆维吾尔自治区', city: '塔城地区', type: 'delegated' }, + 沙湾市: { province: '新疆维吾尔自治区', city: '塔城地区', type: 'delegated' }, + 阿勒泰市: { province: '新疆维吾尔自治区', city: '阿勒泰地区', type: 'delegated' }, + 昌吉市: { province: '新疆维吾尔自治区', city: '昌吉回族自治州', type: 'delegated' }, + 阜康市: { province: '新疆维吾尔自治区', city: '昌吉回族自治州', type: 'delegated' }, + 哈密市: { province: '新疆维吾尔自治区', city: '哈密市', type: 'delegated' }, + 吐鲁番市: { province: '新疆维吾尔自治区', city: '吐鲁番市', type: 'delegated' }, +}); + +/** + * 直辖市名称集合,用于判断是否为直辖市地址。 + */ +const MUNICIPALITY_SET = new Set([ + '北京市', '天津市', '上海市', '重庆市', +]); + +/** + * 省份名称集合,用于 city/area 名反向匹配省份。 + */ +const PROVINCE_LIST = [ + '北京市', '天津市', '上海市', '重庆市', + '河北省', '山西省', '辽宁省', '吉林省', '黑龙江省', + '江苏省', '浙江省', '安徽省', '福建省', '江西省', '山东省', + '河南省', '湖北省', '湖南省', '广东省', '海南省', + '四川省', '贵州省', '云南省', '陕西省', '甘肃省', '青海省', + '台湾省', + '内蒙古自治区', '广西壮族自治区', '西藏自治区', '宁夏回族自治区', '新疆维吾尔自治区', + '香港特别行政区', '澳门特别行政区', +]; + +/** + * 根据已解析的地址字段,利用中国行政区划知识进行反向推断,补全缺失的 province/city/area。 + * + * 处理逻辑: + * 1. 若 area 在 CHINA_ADMIN_DIVISION_MAP 中,直接补全 province 和 city + * 2. 若 province 为空但 city 或 area 不为空,尝试通过名称匹配推断省份 + * 3. 若 city 为空但 area 不为空,尝试通过 area 名推断城市 + * 4. 若 city 和 area 都为空,尝试从 town / detailAddress 中提取信息 + * 5. 对不设区地级市,若 area 为空则用 city 填充 + * + * @param {Object} parsed AI 解析后的原始结果 { province, city, area, town, detailAddress, name, mobile } + * @return {Object} 修正后的结果,结构与输入一致 + */ +function reverseInferAddress(parsed) { + let { province, city, area, town } = parsed; + const { detailAddress } = parsed; + + // 标准化:去除末尾的"市"、"省"等做模糊匹配用 + const normalizeName = name => { + if (!name) return ''; + let n = name.trim(); + // 去掉末尾的"市"、"县"、"区"、"自治县"、"自治州" 等后缀 + n = n.replace(/(市|县|区|自治县|自治州|地区|盟|林区)$/, ''); + return n; + }; + + // --- 步骤1:area 命中行政区划映射表 --- + if (area) { + const entry = CHINA_ADMIN_DIVISION_MAP[area]; + if (entry) { + province = province || entry.province; + city = city || entry.city; + // 不设区地级市:area 和 city 一样时补充说明 + if (entry.type === 'no_district' && (!area || area === city || area === entry.city)) { + // area 已是 city 名,保持不变(允许 area = city 对于不设区地级市) + } + } + } + + // --- 步骤2:province 为空,从 city 或 area 反查 --- + if (!province) { + // 尝试从 city 反查省份(去掉"市"后缀) + if (city) { + const cityNorm = normalizeName(city); + // 先在映射表中查(按 city 名匹配) + for (const [ , entry ] of Object.entries(CHINA_ADMIN_DIVISION_MAP)) { + if (entry.city && normalizeName(entry.city) === cityNorm && entry.province) { + province = entry.province; + break; + } + } + // 如果没找到,尝试判断是否本身是省份名 + if (!province && PROVINCE_LIST.includes(city)) { + province = city; + } + } + // 如果 city 没有,尝试从 area 反查 + if (!province && area) { + const entry = CHINA_ADMIN_DIVISION_MAP[area]; + if (entry && entry.province) { + province = entry.province; + } + } + } + + // --- 步骤3:city 为空但 area 不为空,反查城市 --- + if (!city && area) { + const entry = CHINA_ADMIN_DIVISION_MAP[area]; + if (entry && entry.city) { + city = entry.city; + } else { + // 若 area 带"市"后缀,则 city 与 area 同名 + if (area.endsWith('市') && !MUNICIPALITY_SET.has(area)) { + city = area; + } + } + } + + // --- 步骤4:city 和 area 都为空,尝试从 town / detailAddress 提取 --- + if (!city && !area) { + const townStr = (town || '').trim(); + const detailStr = (detailAddress || '').trim(); + + // 从 town 中匹配已知城市/区县 + if (townStr) { + for (const [ key, entry ] of Object.entries(CHINA_ADMIN_DIVISION_MAP)) { + if (townStr.includes(key) || townStr.includes(normalizeName(key))) { + province = province || entry.province; + city = city || entry.city; + area = area || key; + break; + } + } + } + + // 从 detailAddress 中尝试匹配 + if (!city && !area && detailStr) { + for (const [ key, entry ] of Object.entries(CHINA_ADMIN_DIVISION_MAP)) { + if (detailStr.includes(key) || detailStr.includes(normalizeName(key))) { + province = province || entry.province; + city = city || entry.city; + area = area || key; + break; + } + } + } + } + + // --- 步骤5:不设区地级市兜底 --- + // 若 city 已知且为不设区地级市,area 为空则用 city 填充 + if (city && !area) { + const cityNorm = normalizeName(city); + for (const [ , entry ] of Object.entries(CHINA_ADMIN_DIVISION_MAP)) { + if (entry.type === 'no_district' && normalizeName(entry.city) === cityNorm) { + area = entry.city; // 对于不设区地级市,area 填 city 名 + province = province || entry.province; + break; + } + } + } + + return { ...parsed, province: province || '', city: city || '', area: area || '' }; +} + class PendingOrderService extends OrderBaseService { /** * 初始化待处理订单系统方法的免登录、免权限、免日志和免鉴权配置。 @@ -1006,22 +1472,11 @@ class PendingOrderService extends OrderBaseService { throw new Error('分配快递号接口仅支持订单对象数组入参'); } - const isBusinessIdOne = businessKey => { - const businessKeys = Array.isArray(businessKey) ? businessKey : [ businessKey ]; - return businessKeys.some(item => Number(item) === 1); - }; - const orderIds = [ ...new Set( orders .map(order => Number(order && (order.order_id || order.id))) .filter(orderId => Number.isFinite(orderId) && orderId > 0) ) ]; - const rollbackOrderIds = [ ...new Set( - orders - .filter(order => isBusinessIdOne(order && order.business_key)) - .map(order => Number(order && (order.order_id || order.id))) - .filter(orderId => Number.isFinite(orderId) && orderId > 0) - ) ]; const { service } = this; try { @@ -1034,16 +1489,30 @@ class PendingOrderService extends OrderBaseService { ? await orderDeliveryFactory.getCurrentModel() : null; - if (rollbackOrderIds.length > 0) { - await this.service.systems.express.markWaybillAsyncOrdersAsError( - orderDeliveryModel, - rollbackOrderIds, - error && error.message ? `${error.message}` : `${error}` - ); - } else { - this.ctx.logger.info('[PendingOrderService.allocateExpressCode] 未命中 business_id=1 订单,跳过 post_status 失败回写', { - totalOrderCount: orderIds.length, + if (orderDeliveryModel && orderIds.length > 0) { + // 查询当前订单的 express_code,只回滚没有运单号的 + const currentOrders = await orderDeliveryModel.findAll({ + // eslint-disable-next-line array-bracket-spacing + where: { id: { [this.app.Sequelize.Op.in]: orderIds } }, + attributes: [ 'id', 'express_code', 'post_status' ], + raw: true, }); + + const noWaybillOrderIds = (Array.isArray(currentOrders) ? currentOrders : []) + .filter(o => !String(o.express_code || '').trim()) + .map(o => Number(o.id)) + .filter(id => id > 0); + + if (noWaybillOrderIds.length > 0) { + await orderDeliveryModel.update( + { post_status: 'none', updated_at: new Date() }, + // eslint-disable-next-line array-bracket-spacing + { where: { id: { [this.app.Sequelize.Op.in]: noWaybillOrderIds } } } + ); + this.ctx.logger.info('[PendingOrderService.allocateExpressCode] 回滚 post_status 为 none', { + orderIds: noWaybillOrderIds, + }); + } } } catch (markError) { this.ctx.logger.warn('[PendingOrderService.allocateExpressCode] 通过统一 helper 回写订单失败状态失败,不影响主流程', markError); @@ -1316,6 +1785,15 @@ class PendingOrderService extends OrderBaseService { } } + // 释放储位分配和库存锁定 + try { + await this.service.systems.orderStorageAllocation.cancelAllocateStorage({ + order_ids: orderIds, + }); + } catch (allocErr) { + this.ctx.logger.warn('[PendingOrderService.cancelOrder] 释放储位分配失败,不影响订单取消', allocErr); + } + const updatedOrders = await model.findAll({ where, raw: true, @@ -1603,6 +2081,7 @@ class PendingOrderService extends OrderBaseService { sys_logistics_name: sysLogisticsName, logistics_code: logisticsCode, logistics_name: logisticsName, + post_status: 'fin', updated_at: new Date(), }, { where }); @@ -1949,6 +2428,12 @@ class PendingOrderService extends OrderBaseService { /** * 智能地址解析:使用 DeepSeek 将用户输入的地址字符串解析为结构化地址。 + * + * 采用"AI 解析 + 反向识别兜底"双层策略: + * 1. 先由 DeepSeek AI 进行语义级地址解析 + * 2. 若 AI 返回的省/市/区字段缺失,通过内置的中国行政区划映射表反向补全 + * 3. 仅在两层策略均无法确定 province 时才判定失败 + * * @param {Object} data 请求数据。 * @param {string} data.address 原始地址字符串(必填)。 * @return {Promise} 解析结果,成功返回 province/city/area/town/detailAddress/name/mobile 等,失败返回错误。 @@ -1970,12 +2455,19 @@ class PendingOrderService extends OrderBaseService { 规则: 1. 提取字段:province(省)、city(市)、area(区/县)、town(乡镇/街道)、detailAddress(详细地址)、name(收件人)、mobile(手机号) -2. **利用你的中国地理知识**:如果地址包含村/镇/街道/社区名称,请检索你的知识库推测它所属的省市区。例如: - - "和丰一社" + 常见于广东地区村组命名 → 推测为广东省 东莞市/广州市等 - - 根据地址中的方言特征、命名习惯推测所在区域 -3. 如果实在无法确定,province填"",city和area同理填"",收件人和name同理填"",mobile同理填""。 -4. detailAddress去除省市区部分,只保留街道/村/门牌号 -5. 只返回纯JSON,不含解释或markdown +2. **中国行政区划特殊规则(非常重要)**: + - 四大直辖市(北京、天津、上海、重庆):province填直辖市名,city填直辖市名,area填市辖区名(如"朝阳区") + - 省直辖县级市(如湖北仙桃/潜江/天门、河南济源、海南五指山/琼海/文昌/万宁/东方、新疆石河子等):province填省名,city填省名或留空,area填县级市名 + - 不设区的地级市(如东莞、中山、嘉峪关、儋州、三沙):province填省名,city填地级市名,area填地级市名或留空 + - 普通地级市代管的县级市(如苏州代管昆山、无锡代管江阴、潍坊代管寿光等):province填省名,city填地级市名,area填县级市名 +3. **利用你的中国地理知识**:如果地址缺少省份或城市信息,请检索你的知识库反向推断。例如: + - "仙桃市xxx路" → province=湖北省, city=湖北省, area=仙桃市(省直辖县级市) + - "昆山市xxx镇" → province=江苏省, city=苏州市, area=昆山市(苏州代管县级市) + - "广东省东莞市xxx镇" → province=广东省, city=东莞市, area=东莞市(不设区的地级市) + - "浙江省xxx村" → 根据村名命名习惯和方言特征推测所属城市 +4. 如果实在无法确定,province填"",city和area同理填"",收件人和name同理填"",mobile同理填""。 +5. detailAddress去除省市区部分,只保留街道/村/门牌号 +6. 只返回纯JSON,不含解释或markdown 地址字符串: "${address}" @@ -2013,11 +2505,29 @@ class PendingOrderService extends OrderBaseService { try { const parsed = JSON.parse(jsonStr); - const province = String(parsed.province || '').trim(); - const city = String(parsed.city || '').trim(); - const area = String(parsed.area || '').trim(); + let province = String(parsed.province || '').trim(); + let city = String(parsed.city || '').trim(); + let area = String(parsed.area || '').trim(); const town = String(parsed.town || '').trim(); + const detailAddress = String(parsed.detailAddress || '').trim(); + const name = String(parsed.name || '').trim(); + const mobile = String(parsed.mobile || '').trim(); + // --- 反向识别兜底:使用内置行政区划映射表补全缺失字段 --- + const inferred = reverseInferAddress({ + province, + city, + area, + town, + detailAddress, + name, + mobile, + }); + province = inferred.province; + city = inferred.city; + area = inferred.area; + + // 反向识别后仍无 province 才判定失败 if (!province || province === '暂未识别' || province === '其他') { return this.fail('地址解析失败:省市区无法识别,请补充更多地址信息后重试'); } @@ -2027,9 +2537,9 @@ class PendingOrderService extends OrderBaseService { city, area, town, - detailAddress: String(parsed.detailAddress || '').trim(), - name: String(parsed.name || '').trim(), - mobile: String(parsed.mobile || '').trim(), + detailAddress, + name, + mobile, }); } catch (parseError) { this.ctx.logger.warn('[parseAddress] JSON解析失败,原始返回: %s', content); @@ -4437,10 +4947,12 @@ class PendingOrderService extends OrderBaseService { * * 为指定待处理订单创建一条运单记录(wms_order_express 表), * 仅允许 step 在 [1,2,3] 且 outbound_status 不为 'padding' 的订单操作。 + * 完成后同步更新订单表的 print_status 与 post_status 为 'fin',表示外部已打印。 * * @param {Object} data 请求体。 * @param {number|string} data.order_id 订单ID(必填)。 * @param {string} data.waybill_code 运单号(必填)。 + * @param {string} [data.logistics_interface_name] 物流接口名称(选填,手工填入的值)。 * @return {Promise} 统一 success 包装,含创建的运单记录。 */ async manualWaybill(data = {}) { @@ -4460,6 +4972,8 @@ class PendingOrderService extends OrderBaseService { throw new Error('waybill_code(运单号)不能为空'); } + const logisticsInterfaceName = String(requestData.logistics_interface_name || '').trim() || null; + // 2. 查询订单并校验状态(待处理:step in [1,2,3] 且 outbound_status != 'padding') const model = await this.getOrderModel('order', warehouseId); const where = this.buildOrderWhere([ orderId ], warehouseId); @@ -4488,12 +5002,41 @@ class PendingOrderService extends OrderBaseService { throw new Error('OrderExpress 模型未加载'); } + // 3.1 计算 business_key 递增:查找当前订单已有最大 business_key,+1 递增 + const maxBusinessKey = await orderExpressModel.max('business_key', { + where: { + order_id: orderId, + warehouse_id: Number(order.warehouse_id) || warehouseId, + }, + }); + const nextBusinessKey = Number.isFinite(Number(maxBusinessKey)) && Number(maxBusinessKey) > 0 + ? Number(maxBusinessKey) + 1 + : 1; + const expressRecord = await orderExpressModel.create({ order_id: orderId, waybill_code: waybillCode, + logistics_interface_name: logisticsInterfaceName, + warehouse_id: Number(order.warehouse_id) || warehouseId, + business_key: nextBusinessKey, + status: 1, create_at: new Date(), }); + // 3.2 更新订单表的 print_status 与 post_status 为 'fin',表示外部已打印 + await model.update( + { + print_status: 'fin', + post_status: 'fin', + updated_at: new Date(), + }, + { + where: { + id: orderId, + }, + } + ); + // 4. 记录操作日志 try { await this.ctx.service.systems.operationLog.createOperationLog({ @@ -4505,6 +5048,8 @@ class PendingOrderService extends OrderBaseService { warehouseId: logWarehouseId, orderId, waybillCode, + logisticsInterfaceName, + businessKey: nextBusinessKey, expressRecordId: expressRecord.id, message: `手工录入运单号:订单 ${orderId},运单号 ${waybillCode}`, }, @@ -4518,6 +5063,8 @@ class PendingOrderService extends OrderBaseService { id: expressRecord.id, order_id: orderId, waybill_code: waybillCode, + business_key: nextBusinessKey, + logistics_interface_name: logisticsInterfaceName, create_at: expressRecord.create_at, }); } diff --git a/app/service/systemMethods/order/recheckOrder.js b/app/service/systemMethods/order/recheckOrder.js index a45016a..570c8f8 100644 --- a/app/service/systemMethods/order/recheckOrder.js +++ b/app/service/systemMethods/order/recheckOrder.js @@ -10,9 +10,9 @@ class RecheckOrderService extends OrderBaseService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'scanOrder,scanTask,scanWaybill,confirmRecheck,recheckOrderList,confirmIntercept'; - const _noNeedLog = 'scanOrder,scanTask,scanWaybill,confirmRecheck,recheckOrderList,confirmIntercept'; - const _noNeedAuth = 'scanOrder,scanTask,scanWaybill,confirmRecheck,recheckOrderList,confirmIntercept'; + const _noNeedRight = 'scanOrder,scanTask,scanWaybill,confirmRecheck,recheckOrderList,confirmIntercept,batchQuickRecheck'; + const _noNeedLog = 'scanOrder,scanTask,scanWaybill,confirmRecheck,recheckOrderList,confirmIntercept,batchQuickRecheck'; + const _noNeedAuth = 'scanOrder,scanTask,scanWaybill,confirmRecheck,recheckOrderList,confirmIntercept,batchQuickRecheck'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -23,8 +23,10 @@ class RecheckOrderService extends OrderBaseService { * 顶层携带波次/拣货人/策略/任务ID等汇总信息,list 为扁平订单数组 * - 运单号/波次号命中团购波次(pick_mode=1/5):自动转为团购模式, * 返回嵌套波次结构 list_type='group',每项含波次号、波次内订单明细(含 stock 商品明细)及相关汇总信息 - * - 车号匹配(团单):返回拣货任务下所有团购波次及订单,list_type='group',保持嵌套结构, + * - 车号匹配(团购模式 pick_mode=1/5):返回拣货任务下所有团购波次及订单,list_type='group',保持嵌套结构, * 顶层携带 picker_id、picker_name、task_id + * - 车号匹配(散单模式 pick_mode=2/3/4):查询任务关联的所有波次,逐波次构建扫描视图后合并, + * 返回 list_type='single',按 order_id 去重,未复核订单排前,顶层携带汇总字段 * - 运单号命中但订单无波次信息时,退回单订单详情模式(list 每项含 detail/items/expresses/logs) * @param {Object} data 请求体。 * @param {string} [data.keyword] 通用扫描关键词。 @@ -49,7 +51,7 @@ class RecheckOrderService extends OrderBaseService { const orderModel = await this.getOrderModelByTableType('current', warehouseId); const order = await orderModel.findOne({ where: this.buildOrderWhere([ orderId ], warehouseId), - attributes: [ 'id', 'wave_id', 'wave_no', 'pick_status', 'delivery_order_code' ], + attributes: [ 'id', 'wave_id', 'wave_no', 'pick_status', 'intercept_status', 'delivery_order_code' ], raw: true, }); @@ -174,26 +176,123 @@ class RecheckOrderService extends OrderBaseService { throw new Error('波次信息不完整,无法加载复核视图'); } - // 团单处理:车号匹配 → 查找拣货任务 → 拉取任务下所有团购波次 + // 车号匹配 → 查找拣货任务 → 根据 pick_mode 分流团单/散单 if (matchType === 'cart' && cartMatchContext) { const taskId = Number(cartMatchContext?.task?.task_id || 0); if (taskId > 0) { - const [ groupWaveList, pickerInfo ] = await Promise.all([ - this.buildGroupWaveList(taskId, warehouseId), - this.getPickerInfoByTaskId(taskId, warehouseId), - ]); + const pickMode = Number(cartMatchContext?.task?.pick_mode || 0); + const { ctx } = this; + + // 团购模式(pick_mode 1/5):拉取任务下所有团购波次 + if (pickMode === 1 || pickMode === 5) { + const [ groupWaveList, pickerInfo ] = await Promise.all([ + this.buildGroupWaveList(taskId, warehouseId), + this.getPickerInfoByTaskId(taskId, warehouseId), + ]); + return { + match_type: 'cart', + list_type: 'group', + picker_id: pickerInfo.picker_id, + picker_name: pickerInfo.picker_name, + task_id: taskId, + list: groupWaveList, + }; + } + + // 散单模式(pick_mode 2/3/4):查询任务关联的波次,逐波次构建扫描视图并合并 + const taskWaveRows = await ctx.model.query( + ` + SELECT wave_id, wave_no + FROM wms_wave_pick_task_wave + WHERE task_id = :taskId + AND warehouse_id = :warehouseId + ORDER BY wave_id ASC + `, + { + replacements: { taskId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + const taskWaves = Array.isArray(taskWaveRows) ? taskWaveRows : []; + const scanViews = []; + + for (const tw of taskWaves) { + const waveId = Number(tw.wave_id || 0); + const waveNo = String(tw.wave_no || '').trim(); + + if (waveId > 0 && waveNo) { + const scanView = await this.buildSingleWaveScanView(waveId, waveNo, warehouseId); + + if (scanView) { + scanViews.push(scanView); + } + } + } + + if (scanViews.length === 0) { + return { + match_type: 'cart', + list_type: 'single', + task_id: taskId, + pick_mode: pickMode, + list: [], + }; + } + + // 合并所有波次的订单列表(按 order_id 去重) + const allOrders = scanViews.flatMap(v => (Array.isArray(v.list) ? v.list : [])); + const seenOrderIds = new Set(); + const mergedList = []; + + for (const order of allOrders) { + const oid = Number(order.order_id || 0); + + if (oid > 0 && !seenOrderIds.has(oid)) { + seenOrderIds.add(oid); + mergedList.push(order); + } + } + + // 排序:未复核的排前面,其次按 wave_index 从小到大 + mergedList.sort((a, b) => { + const aReviewed = a.is_reviewed ? 1 : 0; + const bReviewed = b.is_reviewed ? 1 : 0; + + if (aReviewed !== bReviewed) { + return aReviewed - bReviewed; + } + + return (Number(a.wave_index || 0)) - (Number(b.wave_index || 0)); + }); + + const totalOrders = mergedList.length; + const reviewedCount = mergedList.filter(o => o.recheck_status === 'fin').length; + const unreviewedCount = totalOrders - reviewedCount; + const waveType = scanViews.find(v => Number(v.wave_type || 0) > 0)?.wave_type || 0; + const pickerInfo = await this.getPickerInfoByTaskId(taskId, warehouseId); + return { match_type: 'cart', - list_type: 'group', + list_type: 'single', picker_id: pickerInfo.picker_id, picker_name: pickerInfo.picker_name, task_id: taskId, - list: groupWaveList, + wave_id: 0, + wave_no: '', + wave_type: Number(waveType || 0), + pick_mode: pickMode, + strategy_id: null, + strategy_name: '', + total_orders: totalOrders, + reviewed_count: reviewedCount, + unreviewed_count: unreviewedCount, + list: mergedList, }; } - throw new Error('拣货任务信息不完整,无法加载团购复核视图'); + throw new Error('拣货任务信息不完整,无法加载复核视图'); } throw new Error('未找到对应订单'); @@ -582,13 +681,8 @@ class RecheckOrderService extends OrderBaseService { return null; } - // 校验波次内所有订单是否都已拣货,未拣货订单不允许复核 - const orders = Array.isArray(waveView.orders) ? waveView.orders : []; - for (const order of orders) { - this.assertOrderCanRecheck(order); - } - // 分离拦截订单与非拦截订单 + const orders = Array.isArray(waveView.orders) ? waveView.orders : []; const interceptedOrders = []; const normalOrders = []; for (const order of orders) { @@ -600,6 +694,11 @@ class RecheckOrderService extends OrderBaseService { } } + // 校验所有非拦截订单是否都已拣货/未被拦截,不允许复核 + for (const order of normalOrders) { + this.assertOrderCanRecheck(order); + } + // 团购波次中所有订单商品一致,取第一个正常订单的商品明细作为样板 const sampleOrder = normalOrders.length > 0 ? normalOrders[0] : null; const sampleStock = sampleOrder ? (Array.isArray(sampleOrder.stock) ? sampleOrder.stock : []) : []; @@ -2662,13 +2761,17 @@ class RecheckOrderService extends OrderBaseService { } /** - * 校验订单是否允许复核,未拣货订单不允许复核。 + * 校验订单是否允许复核,未拣货订单或已拦截订单不允许复核。 * @param {Object} order 订单信息。 */ assertOrderCanRecheck(order = {}) { if (String(order.pick_status || '') === 'none') { throw new Error('订单未拣货,不允许复核。'); } + const interceptStatus = String(order.intercept_status || '').trim(); + if (interceptStatus === 'intercepted' || interceptStatus === 'intercepted_at_warehouse') { + throw new Error('订单已被拦截,无法提交复核'); + } } /** @@ -3048,6 +3151,29 @@ class RecheckOrderService extends OrderBaseService { throw new Error('拦截状态更新失败,请稍后重试'); } + // 拦截成功后释放储位分配(归还库存) + try { + await this.service.systems.orderStorageAllocation.cancelAllocateStorage({ + order_ids: [ orderId ], + }); + } catch (allocErr) { + ctx.logger.warn( + `[recheckOrder.confirmIntercept] 释放储位分配失败,不影响拦截, orderId=${orderId}, error=${allocErr.message}` + ); + } + + // 拦截成功后释放订单锁 + try { + await orderModel.update( + { lock_status: 'none', updated_at: now }, + { where: orderWhere } + ); + } catch (lockErr) { + ctx.logger.warn( + `[recheckOrder.confirmIntercept] 释放锁失败,不影响拦截, orderId=${orderId}, error=${lockErr.message}` + ); + } + const orderNo = String(order.delivery_order_code || order.pre_delivery_order_code || '').trim(); // 写入操作日志(失败不影响主流程) @@ -3082,6 +3208,754 @@ class RecheckOrderService extends OrderBaseService { }; } + /** + * 批量快捷复核:对一批订单 IDs 依次执行前置条件检查与复核流程。 + * 支持部分失败:不满足前置条件的订单直接跳过并记录失败原因,其余订单继续走完拣货完成 + 复核标记流程。 + * + * 前置条件(任一不满足即跳过): + * 1. 未分配储位:storage_status 不等于 'fin' + * 2. 未分配快递:post_status 不等于 'fin' + * 3. 未同步:status 不等于 'created' + * 4. 已拦截:intercept_status 为 'intercepted' 或 'intercepted_at_warehouse' + * + * 核心流程(每个满足条件的订单在独立事务中执行): + * 1. 若 pick_status 不等于 'fin',先完成拣货: + * - 更新 wms_wave_pick_task_order 拣货状态(仅当订单关联拣货任务时) + * - 更新 wms_order_delivery.pick_status = 'fin' + * - 更新 wms_picking.status = 'fin'(仅当存在拣货记录时) + * - 汇总 wms_picking 中各 storage_id 的 quantity,扣减 wms_storage.locked_quantity 与 quantity + * - 写入 wms_storage_transaction 出库流水 + * 2. 标记复核: + * - 更新 wms_order_delivery.recheck_status = 'fin'、recheck_time = now + * - 插入 wms_recheck_task 复核记录 + * - 更新 wms_wave_pick_task_order 复核状态并尝试解绑车任务 + * - 写入操作日志 + * + * @param {Object} data 请求体。 + * @param {number[]|string} data.ids 订单 ID 列表,支持数组或以逗号分隔的字符串。 + * @return {Promise} 批量复核结果,包含 success、failed、success_count、failed_count。 + */ + async batchQuickRecheck(data = {}) { + const { ctx } = this; + const warehouseId = this.getWarehouseId(); + const orderIds = this.normalizeOrderIds(data); + + if (orderIds.length === 0) { + this.ctx.throw(400, '订单ID列表不能为空'); + } + + // ── 1. 批量查询所有订单的当前状态 ── + const orderModel = await this.getOrderModel('order', warehouseId); + const orderRows = await orderModel.findAll({ + where: this.buildOrderWhere(orderIds, warehouseId), + attributes: [ + 'id', 'delivery_order_code', 'pre_delivery_order_code', + 'storage_status', 'post_status', 'status', 'intercept_status', + 'pick_status', 'recheck_status', 'wave_id', 'wave_no', + ], + raw: true, + }); + + const orderMap = new Map(); + for (const row of orderRows) { + orderMap.set(Number(row.id), row); + } + + // ── 2. 前置条件检查:将订单分为有效订单与跳过订单 ── + const validOrders = []; + const failedOrders = []; + + for (const orderId of orderIds) { + const order = orderMap.get(orderId); + + if (!order) { + failedOrders.push({ order_id: orderId, reason: '未找到对应订单' }); + continue; + } + + const interceptStatus = String(order.intercept_status || '').trim(); + if (interceptStatus === 'intercepted' || interceptStatus === 'intercepted_at_warehouse') { + failedOrders.push({ + order_id: orderId, + delivery_order_code: String(order.delivery_order_code || order.pre_delivery_order_code || '').trim(), + reason: '已拦截', + }); + continue; + } + + const storageStatus = String(order.storage_status || '').trim(); + if (storageStatus !== 'fin') { + failedOrders.push({ + order_id: orderId, + delivery_order_code: String(order.delivery_order_code || order.pre_delivery_order_code || '').trim(), + reason: '未分配储位', + }); + continue; + } + + const postStatus = String(order.post_status || '').trim(); + if (postStatus !== 'fin') { + failedOrders.push({ + order_id: orderId, + delivery_order_code: String(order.delivery_order_code || order.pre_delivery_order_code || '').trim(), + reason: '没有分配快递', + }); + continue; + } + + const orderStatus = String(order.status || '').trim(); + if (orderStatus !== 'created') { + failedOrders.push({ + order_id: orderId, + delivery_order_code: String(order.delivery_order_code || order.pre_delivery_order_code || '').trim(), + reason: '没有同步', + }); + continue; + } + + validOrders.push(order); + } + + // ── 3. 逐订单在独立事务中执行拣货完成 + 复核标记 ── + const successOrders = []; + + for (const order of validOrders) { + const orderId = Number(order.id); + + try { + await ctx.model.transaction(async transaction => { + // 3a. 若未完成拣货,先执行拣货完成流程 + const pickStatus = String(order.pick_status || '').trim(); + if (pickStatus !== 'fin') { + await this._completePickForOrder(orderId, warehouseId, transaction); + // 更新内存中的 pick_status,避免后续 assertOrderCanRecheck 因旧值误判 + order.pick_status = 'fin'; + } + + // 3b. 标记复核 + await this._markRecheckForOrder(order, warehouseId, transaction); + }); + + successOrders.push({ + order_id: orderId, + delivery_order_code: String(order.delivery_order_code || order.pre_delivery_order_code || '').trim(), + }); + } catch (error) { + ctx.logger.warn( + `[batchQuickRecheck] 订单复核失败, orderId=${orderId}, error=${error.message}` + ); + failedOrders.push({ + order_id: orderId, + delivery_order_code: String(order.delivery_order_code || order.pre_delivery_order_code || '').trim(), + reason: `复核失败: ${error.message}`, + }); + } + } + + return { + success: successOrders, + failed: failedOrders, + success_count: successOrders.length, + failed_count: failedOrders.length, + }; + } + + /** + * 完成单个订单的拣货流程(内部方法,在事务中执行)。 + * 包含:更新拣货任务订单状态、订单拣货状态、拣货记录状态、扣减库存锁定数量与可用数量、写库存流水。 + * + * @param {number} orderId 订单ID。 + * @param {number} warehouseId 仓库ID。 + * @param {Object} transaction Sequelize 事务对象。 + * @return {Promise} 无返回值。 + */ + async _completePickForOrder(orderId, warehouseId, transaction) { + const { ctx, app } = this; + + // 步骤1:若订单关联拣货任务,更新 wms_wave_pick_task_order 的拣货状态 + const taskOrderRows = await ctx.model.query( + `SELECT id, task_id + FROM wms_wave_pick_task_order + WHERE order_id = :orderId + AND warehouse_id = :warehouseId + LIMIT 1`, + { + replacements: { orderId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + transaction, + } + ); + + const hasTaskOrder = Array.isArray(taskOrderRows) && taskOrderRows.length > 0; + + if (hasTaskOrder) { + await ctx.model.query( + `UPDATE wms_wave_pick_task_order + SET pick_status = 1, + picked_time = NOW(), + update_time = NOW() + WHERE order_id = :orderId + AND warehouse_id = :warehouseId`, + { + replacements: { orderId, warehouseId }, + type: ctx.model.QueryTypes.UPDATE, + transaction, + } + ); + } + + // 步骤2:更新 wms_order_delivery.pick_status = 'fin' + const orderModel = await this.getOrderModel('order', warehouseId); + await orderModel.update( + { pick_status: 'fin' }, + { + where: this.buildOrderWhere([ orderId ], warehouseId), + transaction, + validate: false, + hooks: false, + } + ); + + // 步骤3:检查是否存在 wms_picking 记录 + const pickingRows = await ctx.model.query( + `SELECT id, storage_id, quantity, space_id + FROM wms_picking + WHERE order_id = :orderId + AND warehouse_id = :warehouseId`, + { + replacements: { orderId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + transaction, + } + ); + + const normalizedPickingRows = Array.isArray(pickingRows) ? pickingRows : []; + + if (normalizedPickingRows.length > 0) { + // 更新 wms_picking.status = 'fin' + await ctx.model.query( + `UPDATE wms_picking + SET status = 'fin', updated_at = NOW() + WHERE order_id = :orderId + AND warehouse_id = :warehouseId`, + { + replacements: { orderId, warehouseId }, + type: ctx.model.QueryTypes.UPDATE, + transaction, + } + ); + + // 步骤4:汇总各 storage_id 的 quantity,扣减 wms_storage 锁定数量与可用数量 + const storageQtyMap = new Map(); + for (const row of normalizedPickingRows) { + const sid = Number(row.storage_id); + if (!sid || sid <= 0) continue; + const currentQty = storageQtyMap.get(sid) || 0; + storageQtyMap.set(sid, currentQty + (Number(row.quantity) || 0)); + } + + const storageIds = Array.from(storageQtyMap.keys()); + if (storageIds.length > 0) { + // 加行锁查询当前库存 + const storageRows = await ctx.model.Storage.findAll({ + where: { + id: { [app.Sequelize.Op.in]: storageIds }, + warehouse_id: warehouseId, + }, + attributes: [ + 'id', 'locked_quantity', 'quantity', + 'store_id', 'stock_id', 'batch_no', 'inventory_type', 'space_id', + ], + lock: transaction.LOCK.UPDATE, + raw: true, + transaction, + }); + + // 校验锁定数量是否足够 + for (const sRow of storageRows) { + const sid = Number(sRow.id); + const deduction = storageQtyMap.get(sid) || 0; + const locked = Number(sRow.locked_quantity) || 0; + if (locked < deduction) { + throw new Error( + `库存记录 ${sid} 锁定数量不足:当前锁定 ${locked},需扣减 ${deduction}` + ); + } + } + + // 构建 CASE WHEN 批量扣减 + const summaryEntries = Array.from(storageQtyMap.entries()); + const caseClauses = summaryEntries + .map(([sid, qty]) => `WHEN ${sid} THEN ${qty}`) + .join(' '); + + await ctx.model.query( + `UPDATE wms_storage + SET locked_quantity = locked_quantity - CASE id ${caseClauses} END, + quantity = quantity - CASE id ${caseClauses} END, + updated_at = NOW() + WHERE id IN (:storageIds) + AND warehouse_id = :warehouseId`, + { + replacements: { storageIds, warehouseId }, + transaction, + } + ); + + // 写入 wms_storage_transaction 出库流水 + const operator = this.getOrderLogOperator(); + const operatorId = String(operator.id || '').trim(); + const operatorName = String(operator.name || 'system').trim(); + const transactionRows = []; + + for (const sRow of storageRows) { + const sid = Number(sRow.id); + const deduction = storageQtyMap.get(sid) || 0; + if (deduction <= 0) continue; + const beforeQty = Number(sRow.quantity) || 0; + const beforeLocked = Number(sRow.locked_quantity) || 0; + transactionRows.push({ + transaction_type: 'OUTBOUND', + warehouse_id: warehouseId, + store_id: Number(sRow.store_id) || 0, + stock_id: Number(sRow.stock_id) || 0, + storage_id: sid, + space_id: Number(sRow.space_id) || null, + quantity: deduction, + before_quantity: beforeQty, + after_quantity: Math.max(0, beforeQty - deduction), + before_locked_quantity: beforeLocked, + after_locked_quantity: Math.max(0, beforeLocked - deduction), + batch_no: sRow.batch_no || null, + inventory_type: sRow.inventory_type || 'ZP', + order_type: 'PICK_OUTBOUND', + order_no: String(orderId), + order_id: orderId, + source_order_codes: String(orderId), + operator_id: operatorId, + operator_name: operatorName, + remark: '拣货完成出库(批量快捷复核)', + created_at: new Date(), + }); + } + + if (transactionRows.length > 0) { + await ctx.model.StorageTransaction.bulkCreate(transactionRows, { transaction }); + } + } + } + + // 步骤5:更新 wms_wave_pick_task 状态 + if (hasTaskOrder) { + const taskId = Number(taskOrderRows[0]?.task_id || 0); + if (taskId > 0) { + // 检查该任务下是否所有订单都已完成拣货 + const taskOrderCount = await ctx.model.query( + `SELECT COUNT(*) AS cnt + FROM wms_wave_pick_task_order + WHERE task_id = :taskId + AND warehouse_id = :warehouseId + AND pick_status != 1`, + { + replacements: { taskId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + transaction, + } + ); + const allPicked = (Number(taskOrderCount[0]?.cnt || 0)) === 0; + + if (allPicked) { + // 全部完成 → 任务状态设为已完成 + await ctx.model.query( + `UPDATE wms_wave_pick_task + SET status = 2, + finish_time = NOW(), + start_time = CASE WHEN start_time IS NULL THEN NOW() ELSE start_time END, + update_time = NOW() + WHERE id = :taskId + AND warehouse_id = :warehouseId`, + { + replacements: { taskId, warehouseId }, + type: ctx.model.QueryTypes.UPDATE, + transaction, + } + ); + } else { + // 未全部完成 → 任务状态推进为拣货中(若仍为未开始) + await ctx.model.query( + `UPDATE wms_wave_pick_task + SET status = CASE WHEN status = 0 THEN 1 ELSE status END, + start_time = CASE WHEN start_time IS NULL THEN NOW() ELSE start_time END, + update_time = NOW() + WHERE id = :taskId + AND warehouse_id = :warehouseId`, + { + replacements: { taskId, warehouseId }, + type: ctx.model.QueryTypes.UPDATE, + transaction, + } + ); + } + } + } + } + + /** + * 标记单个订单为已复核(内部方法,在事务中执行)。 + * 包含:更新订单复核状态、插入复核任务记录、更新拣货任务复核状态并尝试解绑车任务、写操作日志。 + * + * @param {Object} order 订单信息行。 + * @param {number} warehouseId 仓库ID。 + * @param {Object} transaction Sequelize 事务对象。 + * @return {Promise} 无返回值。 + */ + async _markRecheckForOrder(order, warehouseId, transaction) { + const { ctx } = this; + const orderId = Number(order.id); + + // 校验订单是否允许复核(拣货已完成且未被拦截) + this.assertOrderCanRecheck(order); + + const now = new Date(); + + // 更新订单复核状态 + const orderModel = await this.getOrderModel('order', warehouseId); + await orderModel.update( + { + recheck_status: 'fin', + recheck_time: now, + updated_at: now, + }, + { + where: this.buildOrderWhere([ orderId ], warehouseId), + transaction, + validate: false, + hooks: false, + } + ); + + // 插入 wms_recheck_task 复核记录 + const operator = this.getOrderLogOperator(); + const reviewNo = this.buildRecheckReviewNo(orderId, now); + const orderNo = String(order.delivery_order_code || order.pre_delivery_order_code || '').trim(); + const operatorNo = String(operator.id || '').trim(); + const operatorName = String(operator.name || '').trim(); + + await ctx.model.query( + `INSERT INTO wms_recheck_task ( + review_no, + warehouse_id, + order_id, + order_no, + waybill_no, + task_status, + scan_status, + review_emp_no, + review_emp_name, + scan_emp_no, + scan_emp_name, + scan_time, + finish_time, + remark + ) VALUES ( + :reviewNo, + :warehouseId, + :orderId, + :orderNo, + :waybillNo, + :taskStatus, + :scanStatus, + :reviewEmpNo, + :reviewEmpName, + :scanEmpNo, + :scanEmpName, + :scanTime, + :finishTime, + :remark + )`, + { + replacements: { + reviewNo, + warehouseId, + orderId, + orderNo, + waybillNo: '', + taskStatus: 2, + scanStatus: 1, + reviewEmpNo: operatorNo, + reviewEmpName: operatorName, + scanEmpNo: operatorNo, + scanEmpName: operatorName, + scanTime: now, + finishTime: now, + remark: '系统复核完成(批量快捷复核)', + }, + type: ctx.model.QueryTypes.INSERT, + transaction, + } + ); + + // 更新波次拣货任务订单复核状态,并判断是否需要解绑车任务 + await this._updateTaskOrderReviewInTransaction(orderId, warehouseId, operator, now, transaction); + + // 写入操作日志 + await this._writeRecheckActionLogInTransaction({ + orderId, + warehouseId, + operator, + now, + transaction, + }); + } + + /** + * 在事务中更新波次拣货任务订单的复核状态,并判断是否需要解绑车任务。 + * + * @param {number} orderId 订单ID。 + * @param {number} warehouseId 仓库ID。 + * @param {{ id: string|null, name: string }} operator 操作人信息。 + * @param {Date} now 当前时间。 + * @param {Object} transaction Sequelize 事务对象。 + * @return {Promise} 无返回值。 + */ + async _updateTaskOrderReviewInTransaction(orderId, warehouseId, operator, now, transaction) { + const { ctx } = this; + const taskOrderColumnSet = await this.getTableColumnSet('wms_wave_pick_task_order'); + const hasReviewStatus = taskOrderColumnSet.has('review_status'); + + if (!hasReviewStatus) { + return; + } + + const hasReviewUserId = taskOrderColumnSet.has('review_user_id'); + const hasReviewResult = taskOrderColumnSet.has('review_result'); + const hasReviewTime = taskOrderColumnSet.has('review_time'); + const operatorUserId = Number(operator.id) || 0; + + const reviewSetClauses = [ 'review_status = 1' ]; + + if (hasReviewUserId) reviewSetClauses.push('review_user_id = :operatorUserId'); + if (hasReviewResult) reviewSetClauses.push('review_result = 1'); + if (hasReviewTime) reviewSetClauses.push('review_time = :now'); + reviewSetClauses.push('update_time = NOW()'); + + await ctx.model.query( + `UPDATE wms_wave_pick_task_order + SET ${reviewSetClauses.join(',\n ')} + WHERE order_id = :orderId + AND warehouse_id = :warehouseId`, + { + replacements: { + orderId, + warehouseId, + operatorUserId, + now, + }, + type: ctx.model.QueryTypes.UPDATE, + transaction, + } + ); + + // 查询当前订单所属的波次拣货任务ID + const taskRows = await ctx.model.query( + `SELECT DISTINCT task_id + FROM wms_wave_pick_task_order + WHERE order_id = :orderId + AND warehouse_id = :warehouseId`, + { + replacements: { orderId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + transaction, + } + ); + + const taskId = Number( + (Array.isArray(taskRows) && taskRows.length > 0 ? taskRows[0]?.task_id : 0) + ); + + if (taskId <= 0) { + return; + } + + // 检查该任务下是否所有订单都已复核完成 + const unreviewedRows = await ctx.model.query( + `SELECT COUNT(*) AS cnt + FROM wms_wave_pick_task_order + WHERE task_id = :taskId + AND warehouse_id = :warehouseId + AND review_status != 1`, + { + replacements: { taskId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + transaction, + } + ); + + const unreviewedCount = Number( + (Array.isArray(unreviewedRows) && unreviewedRows.length > 0 ? unreviewedRows[0]?.cnt : 0) + ); + + if (unreviewedCount > 0) { + return; + } + + // 任务下所有订单均已复核完成,解绑车任务 + try { + await this._unbindCartForTaskInTransaction(taskId, warehouseId, operatorUserId, transaction); + ctx.logger.info( + `[batchQuickRecheck] 车任务解绑成功, taskId=${taskId}, orderId=${orderId}, operatorUserId=${operatorUserId}` + ); + } catch (unbindError) { + ctx.logger.warn( + `[batchQuickRecheck] 解绑车任务失败(复核已成功), taskId=${taskId}, orderId=${orderId}, error=${unbindError.message}` + ); + } + } + + /** + * 在事务中解绑车任务:清空波次拣货任务的车绑定、停用拣货车绑定记录、释放拣货车。 + * + * @param {number} taskId 波次拣货任务ID。 + * @param {number} warehouseId 仓库ID。 + * @param {number} operatorUserId 操作员用户ID。 + * @param {Object} transaction Sequelize 事务对象。 + * @return {Promise} 无返回值。 + */ + async _unbindCartForTaskInTransaction(taskId, warehouseId, operatorUserId, transaction) { + const { ctx } = this; + + // 清空波次拣货任务的车绑定信息 + await ctx.model.query( + `UPDATE wms_wave_pick_task + SET current_cart_id = NULL, + current_cart_code_snapshot = NULL, + update_time = NOW() + WHERE id = :taskId + AND warehouse_id = :warehouseId`, + { + replacements: { taskId, warehouseId }, + type: ctx.model.QueryTypes.UPDATE, + transaction, + } + ); + + // 停用拣货车绑定记录 + await ctx.model.query( + `UPDATE wms_pick_task_cart_binding + SET is_active = 0, + unbind_user_id = :operatorUserId, + unbind_time = NOW(), + update_time = NOW() + WHERE task_id = :taskId + AND warehouse_id = :warehouseId + AND is_active = 1`, + { + replacements: { taskId, warehouseId, operatorUserId }, + type: ctx.model.QueryTypes.UPDATE, + transaction, + } + ); + + // 释放拣货车 + await ctx.model.query( + `UPDATE wms_pick_cart + SET status = 'idle', + current_task_id = NULL, + update_time = NOW() + WHERE id IN ( + SELECT cart_id + FROM wms_pick_task_cart_binding + WHERE task_id = :taskId + AND warehouse_id = :warehouseId + ) + AND warehouse_id = :warehouseId`, + { + replacements: { taskId, warehouseId }, + type: ctx.model.QueryTypes.UPDATE, + transaction, + } + ); + } + + /** + * 在事务中写入复核操作日志(内部方法)。 + * + * @param {Object} params 日志参数。 + * @param {number} params.orderId 订单ID。 + * @param {number} params.warehouseId 仓库ID。 + * @param {{ id: string|null, name: string }} params.operator 操作人信息。 + * @param {Date} params.now 操作时间。 + * @param {Object} params.transaction Sequelize 事务对象。 + * @return {Promise} 无返回值。 + */ + async _writeRecheckActionLogInTransaction(params = {}) { + const { orderId, warehouseId, operator, now, transaction } = params; + const operatorId = operator && operator.id ? Number(operator.id) : 0; + const operatorName = operator && operator.name ? String(operator.name).trim() : 'system'; + const requestId = `recheck_${warehouseId}_${orderId}_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`; + + await this.ctx.model.query( + `INSERT INTO wms_wave_pick_action_log ( + task_id, + warehouse_id, + wave_id, + order_id, + sku_id, + location_id, + box_no, + cart_id, + qty_delta, + action_type, + request_id, + operator_id, + device_id, + seq_no, + snapshot + ) VALUES ( + :taskId, + :warehouseId, + :waveId, + :orderId, + :skuId, + :locationId, + :boxNo, + :cartId, + :qtyDelta, + :actionType, + :requestId, + :operatorId, + :deviceId, + :seqNo, + :snapshot + )`, + { + replacements: { + taskId: 0, + warehouseId: warehouseId || 0, + waveId: null, + orderId: orderId || 0, + skuId: null, + locationId: null, + boxNo: null, + cartId: null, + qtyDelta: 0, + actionType: 'recheck', + requestId, + operatorId, + deviceId: null, + seqNo: 1, + snapshot: JSON.stringify({ + order_id: orderId, + operator_name: operatorName, + recheck_time: now instanceof Date ? now.toISOString() : String(now || ''), + }), + }, + type: this.ctx.model.QueryTypes.INSERT, + transaction, + } + ); + } + } module.exports = RecheckOrderService; diff --git a/app/service/systemMethods/order/wave.js b/app/service/systemMethods/order/wave.js index 7dc2c7d..3ef4788 100644 --- a/app/service/systemMethods/order/wave.js +++ b/app/service/systemMethods/order/wave.js @@ -6160,19 +6160,27 @@ class WaveService extends OrderBaseService { } /** - * 计算订单快递 key(同快递判定仅使用 sys_logistics_code)。 + * 计算订单快递 key。 + * + * 优先级:sys_logistics_code > logistics_code > logistics_name,与 SQL 中 expressExpr 的 COALESCE 口径保持一致。 * * @param {Object} order 订单记录。 - * @return {string} 快递 key(sys_logistics_code 去首尾空格后结果,空值返回空字符串)。 + * @return {string} 快递 key(去首尾空格后结果,空值返回空字符串)。 */ getWaveStrategyQuickScanExpressKey(order = {}) { - return String(order && order.sys_logistics_code || '').trim(); + const orderObj = order && typeof order === 'object' ? order : {}; + const candidates = [ + String(orderObj.sys_logistics_code || '').trim(), + String(orderObj.logistics_code || '').trim(), + String(orderObj.logistics_name || '').trim(), + ]; + return candidates.find(Boolean) || ''; } /** * 当 require_same_express=1 时,按快递分组候选订单,仅保留最大快递组的订单。 * - * 分组 key 使用 getWaveStrategyQuickScanExpressKey(sys_logistics_code), + * 分组 key 使用 getWaveStrategyQuickScanExpressKey(sys_logistics_code > logistics_code > logistics_name), * 空 key 的订单不参与筛选(直接丢弃)。 * * @param {Array} candidateRows 候选订单数组。 @@ -10215,9 +10223,14 @@ class WaveService extends OrderBaseService { result.wave_prefix_source = wavePrefixResolution.source; if (strategyType === 2) { + const effectiveGroupedRows = Number(strategyRow.require_same_express || 0) === 1 + ? this.groupWaveStrategyFetchCandidateOrdersByStructure( + this.filterCandidateOrdersByRequireSameExpress(candidateRows) + ) + : groupedRows; const groupLimitRaw = Number(strategyRow.group_batch_max_orders || plan.box_limit || 0); const groupLimit = Number.isInteger(groupLimitRaw) && groupLimitRaw > 0 ? groupLimitRaw : 1; - const selectedGroups = groupedRows + const selectedGroups = effectiveGroupedRows .slice(0, groupLimit); if (selectedGroups.length === 0) { throw new Error('团购策略未找到可创建波次的同结构分组'); @@ -10383,7 +10396,12 @@ class WaveService extends OrderBaseService { const createdOrderIds = []; if (strategyType === 2) { - for (const group of groupedRows) { + const effectiveGroupedRows = Number(strategyRow.require_same_express || 0) === 1 + ? this.groupWaveStrategyFetchCandidateOrdersByStructure( + this.filterCandidateOrdersByRequireSameExpress(candidateRows) + ) + : groupedRows; + for (const group of effectiveGroupedRows) { const created = await this.createWaveBatchByOrderIdsInTransaction({ warehouseId, orderIds: group.order_ids, diff --git a/app/service/systemMethods/outbound.js b/app/service/systemMethods/outbound.js index 07a1fc3..6d3176b 100644 --- a/app/service/systemMethods/outbound.js +++ b/app/service/systemMethods/outbound.js @@ -29,6 +29,9 @@ class OutboundService extends MainService { * - recheck_status = 'fin'(已复核) * - pack_status = 'fin'(已打包) * - wms_order_express.weighing_weight > 0(已称重) + * - sync_status = 'fin'(已同步) + * - print_status = 'fin'(已打印) + * - pick_status = 'fin'(已拣货) * * @param {Object} data 请求参数。 * @param {number} [data.warehouseId] 指定仓库ID,不传则使用当前用户上下文仓库。 diff --git a/app/service/systemMethods/setting/printTemplate.js b/app/service/systemMethods/setting/printTemplate.js index f0afe61..98ae85a 100644 --- a/app/service/systemMethods/setting/printTemplate.js +++ b/app/service/systemMethods/setting/printTemplate.js @@ -1,7 +1,7 @@ 'use strict'; const MainService = require('../../main'); -const SUPPORTED_BUSINESS_TYPES = [ 'STOCK', 'RECEIPT', 'PICKING' ]; +const SUPPORTED_BUSINESS_TYPES = [ 'STOCK', 'RECEIPT', 'PICKING', 'OUTBOUND' ]; class printTemplateService extends MainService { constructor(ctx) { diff --git a/app/service/systemMethods/stock/warehouse.js b/app/service/systemMethods/stock/warehouse.js index ea8208c..ea2e5ec 100644 --- a/app/service/systemMethods/stock/warehouse.js +++ b/app/service/systemMethods/stock/warehouse.js @@ -374,6 +374,7 @@ class WarehouseService extends MainService { inbound_min_days, outbound_min_days, remaining_threshold_days, + barcode, } = data || {}; try { const result = await service.systems.stockStore.saveWarehouseStock({ @@ -416,6 +417,7 @@ class WarehouseService extends MainService { inbound_min_days, outbound_min_days, remaining_threshold_days, + barcode, }); return this.success('ok', { data: result, code: 200 }); } catch (error) { @@ -588,9 +590,26 @@ class WarehouseService extends MainService { gross_weight: pickValue([ '毛重', 'gross_weight', 'grossWeight' ]), tag_price: pickValue([ '标价', 'tag_price', 'tagPrice' ]), retail_price: pickValue([ '零售价', 'retail_price', 'retailPrice' ]), + barcode: this._normalizeBarcodeField( + pickValue([ '条码', 'bar_code', 'barCode', 'barcodeList', 'barcode_list', 'barcode' ]) + ), }; } + /** + * 归一化条码字段,只接受逗号分隔的字符串格式,返回去重后的条码数组。 + * 与 stock.warehouse.export 导出格式对齐(导出使用逗号分隔)。 + * + * @param {string|undefined|null} raw 原始条码值(逗号分隔字符串) + * @return {Array} 归一化后的去重条码数组 + */ + _normalizeBarcodeField(raw) { + if (typeof raw === 'string' && raw.trim()) { + return [...new Set(raw.split(',').map(s => s.trim()).filter(Boolean))]; + } + return []; + } + /** * 查询商品条码列表。 * @param {Object} data 请求体(支持分页与关键字) diff --git a/app/service/systemMethods/storage/transaction.js b/app/service/systemMethods/storage/transaction.js index ff0781c..8a031e5 100644 --- a/app/service/systemMethods/storage/transaction.js +++ b/app/service/systemMethods/storage/transaction.js @@ -24,8 +24,8 @@ class StorageTransactionService extends MainService { async list(data = {}) { const { service } = this; const { pagination, sort, group_by_batch } = data; - const { where } = this.prepareWhereContext(data); - const result = await service.systems.stockTransaction.list(where, pagination, sort, group_by_batch); + this.prepareWhereContext(data); + const result = await service.systems.stockTransaction.list(pagination, sort, group_by_batch); return this.success('ok', result); } } diff --git a/app/service/systems/entry_order.js b/app/service/systems/entry_order.js index b606bf1..88c4e50 100644 --- a/app/service/systems/entry_order.js +++ b/app/service/systems/entry_order.js @@ -414,7 +414,6 @@ class entryOrderService extends Service { PENDING: [ 'CONFIRMED', 'CANCELLED' ], CONFIRMED: [ 'PARTIAL_RECEIVED', 'COMPLETED', 'CANCELLED' ], PARTIAL_RECEIVED: [ 'COMPLETED', 'CANCELLED' ], - CREATED: [ 'PENDING', 'CANCELLED' ], CREATING: [ 'PENDING', 'CANCELLED' ], }; @@ -833,7 +832,7 @@ class entryOrderService extends Service { } // 状态检查 - const allowedStatuses = [ 'CREATED', 'PARTIAL_RECEIVED', 'CONFIRMED' ]; + const allowedStatuses = [ 'PENDING', 'PARTIAL_RECEIVED', 'CONFIRMED' ]; if (!allowedStatuses.includes(entryOrder.order_status)) { await transaction.rollback(); return { @@ -951,7 +950,7 @@ class entryOrderService extends Service { if (isFin) { newOrderStatus = 'COMPLETED'; } else if (totalConfirmIncrement > 0) { - if (entryOrder.order_status === 'CREATED') { + if (entryOrder.order_status === 'PENDING') { newOrderStatus = 'CONFIRMED'; } else { newOrderStatus = 'PARTIAL_RECEIVED'; diff --git a/app/service/systems/express_platform.js b/app/service/systems/express_platform.js index e94e7e4..4ca7be1 100644 --- a/app/service/systems/express_platform.js +++ b/app/service/systems/express_platform.js @@ -1173,6 +1173,54 @@ class ExpressPlatformService extends MainService { traceId, operationLogCount: successUpdates.length, }); + + // 自动同步回传:快递号分配成功后异步触发订单同步 + try { + const settlementEntries = Array.from(settlementRelationMap.entries()); + for (const [key, relation] of settlementEntries) { + const successCount = Number(relation && relation.success_count) || 0; + if (successCount <= 0) continue; + const [storeId, warehouseId] = key.split(':').map(Number); + if (!storeId || !warehouseId) continue; + + const contractConfig = await this.service.systems.storeWarehouse.getContractConfig( + warehouseId, + storeId + ); + if ( + contractConfig + && contractConfig.policy_config + && contractConfig.policy_config.auto_sync_back === 1 + ) { + // 收集本次分配成功的订单ID + const syncedOrderIds = successUpdates + .filter(u => { + const orderId = Number(u.order_id) || 0; + const wid = Number(u.warehouse_id) || 0; + const bk = Number(u.business_key) || 0; + const meta = orderMetaMap.get(`${wid}_${orderId}_${bk}`); + return meta && meta.store_id === storeId && wid === warehouseId; + }) + .map(u => Number(u.order_id) || 0) + .filter(Boolean); + + if (syncedOrderIds.length > 0) { + // 异步调用,不阻塞主流程 + this.ctx.service.systemMethods.order.pendingOrder.syncOrderIds({ + orderIds: syncedOrderIds, + }).catch(err => { + this.ctx.logger.error( + `[auto_sync_back] polyapi 自动同步失败: ${err.message}` + ); + }); + } + } + } + } catch (err) { + this.ctx.logger.error( + `[auto_sync_back] polyapi 自动同步异常: ${err.message}` + ); + } } } this.ctx.logger.info('[expressPlatform.polyapi] 处理完成', { @@ -1451,6 +1499,59 @@ class ExpressPlatformService extends MainService { await this.persistWaybillSuccessUpdates(successUpdates, normalizedOrders); + // 自动同步回传:快递号分配成功后异步触发订单同步 + try { + const orderMetaMap = this.buildWaybillOrderMetaMap(normalizedOrders); + const settlementRelationMap = this.buildWaybillSettlementRelationMap( + successUpdates, + orderMetaMap + ); + const settlementEntries = Array.from(settlementRelationMap.entries()); + for (const [key, relation] of settlementEntries) { + const successCount = Number(relation && relation.success_count) || 0; + if (successCount <= 0) continue; + const [storeId, warehouseId] = key.split(':').map(Number); + if (!storeId || !warehouseId) continue; + + const contractConfig = await this.service.systems.storeWarehouse.getContractConfig( + warehouseId, + storeId + ); + if ( + contractConfig + && contractConfig.policy_config + && contractConfig.policy_config.auto_sync_back === 1 + ) { + // 收集本次分配成功的订单ID + const syncedOrderIds = successUpdates + .filter(u => { + const orderId = Number(u.order_id) || 0; + const wid = Number(u.warehouse_id) || 0; + const bk = Number(u.business_key) || 0; + const meta = orderMetaMap.get(`${wid}_${orderId}_${bk}`); + return meta && meta.store_id === storeId && wid === warehouseId; + }) + .map(u => Number(u.order_id) || 0) + .filter(Boolean); + + if (syncedOrderIds.length > 0) { + // 异步调用,不阻塞主流程 + this.ctx.service.systemMethods.order.pendingOrder.syncOrderIds({ + orderIds: syncedOrderIds, + }).catch(err => { + this.ctx.logger.error( + `[auto_sync_back] cainiao 自动同步失败: ${err.message}` + ); + }); + } + } + } + } catch (err) { + this.ctx.logger.error( + `[auto_sync_back] cainiao 自动同步异常: ${err.message}` + ); + } + return { flag: true, code: 0, @@ -2089,6 +2190,54 @@ class ExpressPlatformService extends MainService { await operationLogService.createOperationLogs(logPayloads); } + // 自动同步回传:快递号分配成功后异步触发订单同步 + try { + const settlementEntries = Array.from(settlementRelationMap.entries()); + for (const [key, relation] of settlementEntries) { + const successCount = Number(relation && relation.success_count) || 0; + if (successCount <= 0) continue; + const [storeId, warehouseId] = key.split(':').map(Number); + if (!storeId || !warehouseId) continue; + + const contractConfig = await this.service.systems.storeWarehouse.getContractConfig( + warehouseId, + storeId + ); + if ( + contractConfig + && contractConfig.policy_config + && contractConfig.policy_config.auto_sync_back === 1 + ) { + // 收集本次分配成功的订单ID + const syncedOrderIds = successUpdates + .filter(u => { + const orderId = Number(u.order_id) || 0; + const wid = Number(u.warehouse_id) || 0; + const bk = Number(u.business_key) || 0; + const meta = orderMetaMap.get(`${wid}_${orderId}_${bk}`); + return meta && meta.store_id === storeId && wid === warehouseId; + }) + .map(u => Number(u.order_id) || 0) + .filter(Boolean); + + if (syncedOrderIds.length > 0) { + // 异步调用,不阻塞主流程 + this.ctx.service.systemMethods.order.pendingOrder.syncOrderIds({ + orderIds: syncedOrderIds, + }).catch(err => { + this.ctx.logger.error( + `[auto_sync_back] pdd 自动同步失败: ${err.message}` + ); + }); + } + } + } + } catch (err) { + this.ctx.logger.error( + `[auto_sync_back] pdd 自动同步异常: ${err.message}` + ); + } + return { flag: true, code: 0, diff --git a/app/service/systems/order_auto_outbound.js b/app/service/systems/order_auto_outbound.js index 9e13453..3c829d9 100644 --- a/app/service/systems/order_auto_outbound.js +++ b/app/service/systems/order_auto_outbound.js @@ -3,7 +3,7 @@ const MainService = require('../main'); const { Op } = require('sequelize'); -const OUTBOUND_STATUS = 'padding'; +const OUTBOUND_STATUS = 'fin'; const OUTBOUND_STEP = 4; const ORDER_STATUS_FINISHED = 'finished'; const MAX_BATCH_SIZE = 500; @@ -61,6 +61,15 @@ class OrderAutoOutboundService extends MainService { rules: autoOutboundRules, }); } + + // 兜底:仓库自身没有 StoreWarehouse 合同关系时,直接用 store.id 作为 warehouseId + if (contracts.length === 0) { + result.push({ + storeId: store.id, + warehouseId: store.id, + rules: autoOutboundRules, + }); + } } return result; @@ -94,8 +103,14 @@ class OrderAutoOutboundService extends MainService { /** * 构造自动化出库的订单查询条件。 + * 根据配置规则组合各状态字段的 WHERE 条件。 * - * @param {Object} rules 自动化出库规则。 + * @param {Object} rules 自动化出库规则,包含以下可选字段: + * - {boolean} [rules.require_recheck] 是否要求已复核(recheck_status='fin') + * - {boolean} [rules.require_pack] 是否要求已打包(pack_status='fin') + * - {boolean} [rules.require_sync] 是否要求已同步(sync_status='fin') + * - {boolean} [rules.require_print] 是否要求已打印(print_status='fin') + * - {boolean} [rules.require_pick] 是否要求已拣货(pick_status='fin') * @return {Object} Sequelize where 条件对象。 */ buildAutoOutboundWhere(rules) { @@ -118,6 +133,14 @@ class OrderAutoOutboundService extends MainService { where.sync_status = 'fin'; } + if (rules.require_print) { + where.print_status = 'fin'; + } + + if (rules.require_pick) { + where.pick_status = 'fin'; + } + return where; } @@ -226,6 +249,7 @@ class OrderAutoOutboundService extends MainService { outbound_status: OUTBOUND_STATUS, step: OUTBOUND_STEP, status: ORDER_STATUS_FINISHED, + delivery_time: now, updated_at: now, }, { @@ -260,11 +284,6 @@ class OrderAutoOutboundService extends MainService { async executeAutoOutbound() { const { ctx } = this; - if (ctx.app._autoOutboundRunning) { - ctx.logger.info('[auto-outbound] 上一轮自动化出库尚未结束,跳过本次执行'); - return { totalProcessed: 0, warehouseResults: [] }; - } - ctx.app._autoOutboundRunning = true; try { diff --git a/app/service/systems/order_delivery_migration.js b/app/service/systems/order_delivery_migration.js index d735644..dedfe88 100644 --- a/app/service/systems/order_delivery_migration.js +++ b/app/service/systems/order_delivery_migration.js @@ -309,16 +309,9 @@ class OrderDeliveryMigrationService extends MainService { * @return {Object} 可写入配送表的数据。 */ buildDispatchRow(row) { - const payload = { - ...(row || {}), - }; - + const payload = { ...(row || {}) }; delete payload.dispatch_lane; - - return { - ...payload, - dispatch_lane: DISPATCH_LANE, - }; + return { ...payload, dispatch_lane: DISPATCH_LANE }; } /** @@ -481,10 +474,11 @@ class OrderDeliveryMigrationService extends MainService { const sourceOrderRowMap = new Map(validSourceRows .map(row => [ Number(row.id), row ]) .filter(([ rowId, row ]) => Number.isFinite(rowId) && rowId > 0 && this.buildDispatchKey(row))); - const deliveryOrderCodes = Array.from(new Set(validSourceRows + let deliveryOrderCodes = Array.from(new Set(validSourceRows .map(row => String(row.delivery_order_code || '').trim()) .filter(Boolean))); const sourceOrderIds = Array.from(sourceOrderRowMap.keys()); + const orderCodeMap = new Map(); // source order_id → renamed delivery_order_code let existingRows = []; if (deliveryOrderCodes.length > 0) { @@ -505,15 +499,44 @@ class OrderDeliveryMigrationService extends MainService { .map(row => this.buildDispatchKey(row)) .filter(Boolean)); - const rowsToCreate = validSourceRows - .filter(row => !existingKeySet.has(this.buildDispatchKey(row))) - .map(row => this.buildDispatchRow(row)); + const rowsToCreate = []; + for (const row of validSourceRows) { + let tryCode = String(row.delivery_order_code || '').trim(); + const storeId = String(row.store_id || '').trim(); + const warehouseId = String(row.warehouse_id || '').trim(); + const originalKey = `${tryCode}::${storeId}::${warehouseId}`; + let seq = 2; + + while (existingKeySet.has(`${tryCode}::${storeId}::${warehouseId}`)) { + tryCode = `${String(row.delivery_order_code || '').trim()}-${seq}`; + seq++; + } + + const newKey = `${tryCode}::${storeId}::${warehouseId}`; + if (newKey !== originalKey) { + this.ctx.logger.info( + `[sync-outbound-orders-to-delivery] delivery_order_code 冲突,重命名: ${originalKey} → ${newKey}` + ); + orderCodeMap.set(Number(row.id), tryCode); + } + existingKeySet.add(newKey); + + const modifiedRow = tryCode !== String(row.delivery_order_code || '').trim() + ? { ...row, delivery_order_code: tryCode } + : row; + + rowsToCreate.push(this.buildDispatchRow(modifiedRow)); + } + + for (const renamedCode of orderCodeMap.values()) { + deliveryOrderCodes.push(renamedCode); + } + deliveryOrderCodes = Array.from(new Set(deliveryOrderCodes.filter(Boolean))); if (rowsToCreate.length > 0) { assertMigrationDeadline('创建配送表订单'); await targetOrderModel.bulkCreate(rowsToCreate, { ...this.buildMigrationQueryOptions(transaction, queryTimeoutMs), - ignoreDuplicates: true, }); } @@ -551,7 +574,11 @@ class OrderDeliveryMigrationService extends MainService { const rowsToCreateItems = validSourceItems.map(item => { const sourceOrder = sourceOrderRowMap.get(Number(item.order_id)); - const targetOrderId = targetOrderIdMap.get(this.buildDispatchKey(sourceOrder)); + const renamedCode = orderCodeMap.get(Number(item.order_id)); + const key = renamedCode + ? `${renamedCode}::${String(sourceOrder.store_id || '').trim()}::${String(sourceOrder.warehouse_id || '').trim()}` + : this.buildDispatchKey(sourceOrder); + const targetOrderId = targetOrderIdMap.get(key); if (!Number.isFinite(targetOrderId) || targetOrderId <= 0) { throw new Error(`无法找到订单 ${item.order_id} 对应的配送表订单ID`); @@ -564,7 +591,6 @@ class OrderDeliveryMigrationService extends MainService { assertMigrationDeadline('创建商品明细'); await targetItemModel.bulkCreate(rowsToCreateItems, { ...this.buildMigrationQueryOptions(transaction, queryTimeoutMs), - ignoreDuplicates: true, }); } diff --git a/app/service/systems/order_export.js b/app/service/systems/order_export.js index 600332f..19be920 100644 --- a/app/service/systems/order_export.js +++ b/app/service/systems/order_export.js @@ -27,19 +27,25 @@ const ORDER_EXPORT_COLUMNS = Object.freeze([ { header: '订单号', key: 'delivery_order_code', width: 24 }, { header: '外部单号', key: 'external_order_code', width: 24 }, { header: '订单状态', key: 'status', width: 16 }, - { header: '步骤', key: 'step', width: 10 }, { header: '波次号', key: 'wave_no', width: 18 }, - { header: '仓库ID', key: 'warehouse_id', width: 12 }, - { header: '货主ID', key: 'store_id', width: 12 }, + { header: '货主', key: 'store_id', width: 20 }, { header: '平台', key: 'sys_platform_name', width: 16 }, { header: '店铺昵称', key: 'shop_nick', width: 20 }, - { header: '卖家昵称', key: 'seller_nick', width: 20 }, - { header: '买家昵称', key: 'buyer_nick', width: 20 }, + { header: '收件人', key: 'receiver_name', width: 16 }, + { header: '收件人电话', key: 'receiver_mobile', width: 18 }, + { header: '省', key: 'receiver_province', width: 10 }, + { header: '市', key: 'receiver_city', width: 10 }, + { header: '区', key: 'receiver_district', width: 10 }, + { header: '镇', key: 'receiver_town', width: 10 }, + { header: '详细地址', key: 'receiver_detail', width: 30 }, + { header: '商品明细', key: 'items_detail', width: 50 }, { header: '物流公司', key: 'logistics_name', width: 18 }, - { header: '运单号', key: 'express_numbers', width: 28 }, + { header: '运单号', key: 'waybill_code', width: 24 }, + { header: '分配时间', key: 'waybill_allocated_at', width: 20 }, { header: '商品种数', key: 'items_count', width: 12 }, { header: '商品件数', key: 'items_total', width: 12 }, - { header: '总重量', key: 'items_weight', width: 12 }, + { header: '商品重量', key: 'items_weight', width: 12 }, + { header: '称重重量(kg)', key: 'weighing_weight', width: 14 }, { header: '订单金额', key: 'total_amount', width: 14 }, { header: '实收金额', key: 'got_amount', width: 14 }, { header: '创建时间', key: 'create_at', width: 20 }, @@ -53,6 +59,88 @@ const ORDER_EXPORT_COLUMNS = Object.freeze([ { header: '归档时间', key: 'archive_time', width: 20 }, ]); +/** 商品明细展开列配置(item 模式) */ +const ORDER_EXPORT_ITEM_COLUMNS = Object.freeze([ + { header: '订单ID', key: 'id', width: 12 }, + { header: '订单号', key: 'delivery_order_code', width: 24 }, + { header: '外部单号', key: 'external_order_code', width: 24 }, + { header: '订单状态', key: 'status', width: 16 }, + { header: '波次号', key: 'wave_no', width: 18 }, + { header: '货主', key: 'store_id', width: 20 }, + { header: '平台', key: 'sys_platform_name', width: 16 }, + { header: '店铺昵称', key: 'shop_nick', width: 20 }, + { header: '收件人', key: 'receiver_name', width: 16 }, + { header: '收件人电话', key: 'receiver_mobile', width: 18 }, + { header: '省', key: 'receiver_province', width: 10 }, + { header: '市', key: 'receiver_city', width: 10 }, + { header: '区', key: 'receiver_district', width: 10 }, + { header: '镇', key: 'receiver_town', width: 10 }, + { header: '详细地址', key: 'receiver_detail', width: 30 }, + { header: '仓库商品名称', key: 'item_name', width: 30 }, + { header: '商品条码', key: 'item_barcode', width: 24 }, + { header: '数量', key: 'item_quantity', width: 10 }, + { header: '物流公司', key: 'logistics_name', width: 18 }, + { header: '运单号', key: 'waybill_code', width: 30 }, + { header: '分配时间', key: 'waybill_allocated_at', width: 20 }, + { header: '商品种数', key: 'items_count', width: 12 }, + { header: '商品件数', key: 'items_total', width: 12 }, + { header: '商品重量', key: 'items_weight', width: 12 }, + { header: '称重重量(kg)', key: 'weighing_weight', width: 14 }, + { header: '订单金额', key: 'total_amount', width: 14 }, + { header: '实收金额', key: 'got_amount', width: 14 }, + { header: '创建时间', key: 'create_at', width: 20 }, + { header: '支付时间', key: 'pay_time', width: 20 }, + { header: '发货时间', key: 'delivery_time', width: 20 }, + { header: '出库状态', key: 'outbound_status', width: 14 }, + { header: '复核状态', key: 'inspection_status', width: 14 }, + { header: '复核完成状态', key: 'recheck_status', width: 16 }, + { header: '配货状态', key: 'post_status', width: 14 }, + { header: '打包状态', key: 'pack_status', width: 14 }, + { header: '归档时间', key: 'archive_time', width: 20 }, +]); + +/** 订单状态中文翻译映射 */ +const ORDER_STATUS_LABELS = Object.freeze({ + status: { + pedding: '待处理', + created: '已创建', + cancel: '已取消', + error: '异常', + finished: '已完成', + }, + outbound_status: { + none: '无', + padding: '待出库', + fin: '已完成', + timeout: '超时', + error: '异常', + }, + inspection_status: { + none: '无', + padding: '待检验', + running: '检验中', + fin: '已完成', + error: '异常', + }, + recheck_status: { + none: '无', + fin: '已完成', + }, + post_status: { + none: '无', + padding: '待配货', + fin: '已完成', + timeout: '超时', + error: '异常', + }, + pack_status: { + none: '无', + padding: '待打包', + fin: '已完成', + error: '异常', + }, +}); + /** * 订单导出系统服务。 * 负责复用订单列表查询语义,按页拉取数据并流式写入本地 xlsx 后上传。 @@ -143,10 +231,12 @@ class OrderExportService extends OrderBaseService { /** * 获取订单导出列配置。 + * @param {string} [mode='waybill'] 导出模式:'waybill'(按运单展开)或 'item'(按商品明细展开)。 * @return {Array} 导出列配置。 */ - getOrderExportColumns() { - return ORDER_EXPORT_COLUMNS.map(column => ({ ...column })); + getOrderExportColumns(mode = 'waybill') { + const columns = mode === 'item' ? ORDER_EXPORT_ITEM_COLUMNS : ORDER_EXPORT_COLUMNS; + return columns.map(column => ({ ...column })); } /** @@ -220,49 +310,158 @@ class OrderExportService extends OrderBaseService { } /** - * 映射单行订单导出数据。 + * 映射订单导出数据行。 + * - waybill 模式:按运单号展开,每个运单一组。 + * - item 模式:按商品明细展开,每个商品一行;运单信息汇总填充。 * @param {Object} orderRow 订单行。 - * @return {Object} 导出行。 + * @param {Object} [context] 导出上下文,包含批量查询的辅助数据。 + * @param {Map>} [context.itemsMap] 订单ID → 商品明细列表的映射。 + * @param {Map} [context.storeRemarkMap] 货主ID → 货主备注的映射。 + * @param {Map} [context.stockNameMap] stockId → 仓库商品名称的映射。 + * @param {Map} [context.barcodeMap] stockId → 商品条码(逗号拼接)的映射。 + * @param {Map>} [context.expressMap] 订单ID → 运单行列表的映射。 + * @param {string} [mode='waybill'] 导出模式:'waybill' 或 'item'。 + * @return {Array} 导出行数组。 */ - mapOrderExportRow(orderRow = {}) { + mapOrderExportRow(orderRow = {}, context = {}, mode = 'waybill') { const safeOrderRow = this.isPlainObject(orderRow) ? orderRow : {}; - const expressNumbers = Array.isArray(safeOrderRow.express_numbers) - ? safeOrderRow.express_numbers - : Array.isArray(safeOrderRow.waybill_codes) - ? safeOrderRow.waybill_codes - : []; + const { itemsMap, storeRemarkMap, stockNameMap, barcodeMap, expressMap } = context; + const safeItemsMap = itemsMap instanceof Map ? itemsMap : new Map(); + const safeStoreRemarkMap = storeRemarkMap instanceof Map ? storeRemarkMap : new Map(); + const safeExpressMap = expressMap instanceof Map ? expressMap : new Map(); const externalOrderCode = safeOrderRow.pre_delivery_order_code || safeOrderRow.source_order_codes || ''; - return { + /** + * 翻译状态字段为中文,未知值保留原始值。 + * @param {string} field 状态字段名。 + * @param {*} value 原始状态值。 + * @return {string} 翻译后的中文状态文本。 + */ + const translateStatus = (field, value) => { + const raw = String(value ?? '').trim(); + if (!raw) return ''; + const labelMap = ORDER_STATUS_LABELS[field]; + return labelMap && labelMap[raw] ? labelMap[raw] : raw; + }; + + /** + * 安全格式化日期字段,空值/无效值返回空字符串。 + * @param {*} value 日期原始值。 + * @return {string} 格式化后的日期字符串或空字符串。 + */ + const formatDateSafe = value => { + if (value === null || value === undefined || value === '' || value === 0) { + return ''; + } + const d = new Date(value); + if (isNaN(d.getTime()) || d.getTime() <= 0) { + return ''; + } + return this.app.formatDate(value); + }; + + const orderId = Number(safeOrderRow.id || 0); + const storeId = Number(safeOrderRow.store_id || 0); + const storeRemark = safeStoreRemarkMap.get(storeId) || ''; + const items = safeItemsMap.get(orderId) || []; + const safeStockNameMap = stockNameMap instanceof Map ? stockNameMap : new Map(); + const safeBarcodeMap = barcodeMap instanceof Map ? barcodeMap : new Map(); + const itemsDetail = Array.isArray(items) && items.length > 0 + ? items.map(item => { + const stockId = Number(item.stock_id || 0); + const warehouseItemName = stockId > 0 ? safeStockNameMap.get(stockId) : ''; + const displayName = warehouseItemName || item.item_name || ''; + return `${displayName} x${item.plan_qty || 1}`; + }).join('; ') + : ''; + + /** 订单公共字段(不含 items_detail,由各模式自行拼接) */ + const commonFields = { id: this.normalizeExportCellValue(safeOrderRow.id), delivery_order_code: this.normalizeExportCellValue(safeOrderRow.delivery_order_code), external_order_code: this.normalizeExportCellValue(externalOrderCode), - status: this.normalizeExportCellValue(safeOrderRow.status), - step: this.normalizeExportCellValue(safeOrderRow.step), + status: translateStatus('status', safeOrderRow.status), wave_no: this.normalizeExportCellValue(safeOrderRow.wave_no), - warehouse_id: this.normalizeExportCellValue(safeOrderRow.warehouse_id), - store_id: this.normalizeExportCellValue(safeOrderRow.store_id), + store_id: this.normalizeExportCellValue(storeRemark || safeOrderRow.store_name || safeOrderRow.store_id), sys_platform_name: this.normalizeExportCellValue(safeOrderRow.sys_platform_name), shop_nick: this.normalizeExportCellValue(safeOrderRow.shop_nick), - seller_nick: this.normalizeExportCellValue(safeOrderRow.seller_nick), - buyer_nick: this.normalizeExportCellValue(safeOrderRow.buyer_nick), + receiver_name: this.normalizeExportCellValue(safeOrderRow.name || ''), + receiver_mobile: this.normalizeExportCellValue(safeOrderRow.mobile || safeOrderRow.tel || ''), + receiver_province: this.normalizeExportCellValue(safeOrderRow.province || ''), + receiver_city: this.normalizeExportCellValue(safeOrderRow.city || ''), + receiver_district: this.normalizeExportCellValue(safeOrderRow.area || ''), + receiver_town: this.normalizeExportCellValue(safeOrderRow.town || ''), + receiver_detail: this.normalizeExportCellValue(safeOrderRow.detail_address || ''), logistics_name: this.normalizeExportCellValue(safeOrderRow.logistics_name), - express_numbers: this.normalizeExportCellValue(expressNumbers), items_count: this.normalizeExportCellValue(safeOrderRow.items_count), items_total: this.normalizeExportCellValue(safeOrderRow.items_total), items_weight: this.normalizeExportCellValue(safeOrderRow.items_weight), total_amount: this.normalizeExportCellValue(safeOrderRow.total_amount), got_amount: this.normalizeExportCellValue(safeOrderRow.got_amount), - create_at: this.normalizeExportCellValue(safeOrderRow.create_at), - pay_time: this.normalizeExportCellValue(safeOrderRow.pay_time), - delivery_time: this.normalizeExportCellValue(safeOrderRow.delivery_time), - outbound_status: this.normalizeExportCellValue(safeOrderRow.outbound_status), - inspection_status: this.normalizeExportCellValue(safeOrderRow.inspection_status), - recheck_status: this.normalizeExportCellValue(safeOrderRow.recheck_status), - post_status: this.normalizeExportCellValue(safeOrderRow.post_status), - pack_status: this.normalizeExportCellValue(safeOrderRow.pack_status), - archive_time: this.normalizeExportCellValue(safeOrderRow.archive_time), + create_at: formatDateSafe(safeOrderRow.create_at), + pay_time: formatDateSafe(safeOrderRow.pay_time), + delivery_time: formatDateSafe(safeOrderRow.delivery_time), + outbound_status: translateStatus('outbound_status', safeOrderRow.outbound_status), + inspection_status: translateStatus('inspection_status', safeOrderRow.inspection_status), + recheck_status: translateStatus('recheck_status', safeOrderRow.recheck_status), + post_status: translateStatus('post_status', safeOrderRow.post_status), + pack_status: translateStatus('pack_status', safeOrderRow.pack_status), + archive_time: formatDateSafe(safeOrderRow.archive_time), }; + + const expressList = safeExpressMap.get(orderId) || []; + + // ★ 模式B:按商品明细展开 + if (mode === 'item') { + const waybillSummary = expressList.map(e => e.waybill_code).filter(Boolean).join(', '); + const waybillFirstTime = expressList.length > 0 ? formatDateSafe(expressList[0].create_at) : ''; + const weightSummary = expressList.reduce((sum, e) => sum + (Number(e.weighing_weight) || 0), 0); + + if (items.length === 0) { + return [{ + ...commonFields, + item_name: '', + item_barcode: '', + item_quantity: '', + waybill_code: waybillSummary, + waybill_allocated_at: waybillFirstTime, + weighing_weight: weightSummary || '', + }]; + } + + return items.map(item => { + const sid = Number(item.stock_id || 0); + return { + ...commonFields, + item_name: (sid > 0 ? safeStockNameMap.get(sid) : '') || item.item_name || '', + item_barcode: sid > 0 ? (safeBarcodeMap.get(sid) || '') : '', + item_quantity: item.plan_qty || 1, + waybill_code: waybillSummary, + waybill_allocated_at: waybillFirstTime, + weighing_weight: weightSummary || '', + }; + }); + } + + // ★ 模式A(默认 waybill):按运单展开,保留 items_detail + if (expressList.length === 0) { + // 无运单的订单也输出一行(运单字段为空) + return [{ + ...commonFields, + items_detail: this.normalizeExportCellValue(itemsDetail), + waybill_code: '', + waybill_allocated_at: '', + weighing_weight: '', + }]; + } + + return expressList.map(exp => ({ + ...commonFields, + items_detail: this.normalizeExportCellValue(itemsDetail), + waybill_code: exp.waybill_code || '', + waybill_allocated_at: formatDateSafe(exp.create_at), + weighing_weight: exp.weighing_weight != null ? Number(exp.weighing_weight) : '', + })); } /** @@ -390,7 +589,9 @@ class OrderExportService extends OrderBaseService { useSharedStrings: false, }); const worksheet = workbook.addWorksheet(ORDER_EXPORT_WORKSHEET_NAME); - worksheet.columns = this.getOrderExportColumns(); + const exportMode = String(safeOptions.export_mode || '').trim() || 'waybill'; + const mode = exportMode === 'item' ? 'item' : 'waybill'; + worksheet.columns = this.getOrderExportColumns(mode); let currentCount = 0; let page = 1; @@ -417,12 +618,163 @@ class OrderExportService extends OrderBaseService { break; } - const normalizedRows = await this.attachOrderExpressNumbers( - rows.map(row => this.normalizeOrderListItem(this.toPlainRow(row))) + const normalizedRows = rows.map(row => + this.normalizeOrderListItem(this.toPlainRow(row)) ); + const orderIds = normalizedRows.map(r => Number(r.id || 0)).filter(id => id > 0); + + // 批量查询商品明细(wms_order_items) + const itemsMap = new Map(); + if (orderIds.length > 0) { + try { + const itemsModel = await this.getOrderItemsModelByTableType(target.tableType, warehouseId); + const itemsRows = await itemsModel.findAll({ + where: { order_id: { [this.app.Sequelize.Op.in]: orderIds } }, + attributes: [ 'order_id', 'item_name', 'plan_qty', 'stock_id' ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + for (const item of (Array.isArray(itemsRows) ? itemsRows : [])) { + const oid = Number(item.order_id || 0); + if (oid > 0) { + if (!itemsMap.has(oid)) { + itemsMap.set(oid, []); + } + itemsMap.get(oid).push(item); + } + } + } catch (err) { + this.app.logger.warn(`[order_export] 批量查询订单商品明细失败: ${err.message}`); + } + } + + // 批量查询仓库商品名称(wms_stock_warehouse.item_name) + const stockNameMap = new Map(); + if (itemsMap.size > 0 && this.ctx && this.ctx.model && this.ctx.model.StockWarehouse) { + try { + const stockIds = [ + ...new Set( + [ ...itemsMap.values() ] + .flat() + .map(item => Number(item.stock_id || 0)) + .filter(id => id > 0) + ), + ]; + if (stockIds.length > 0) { + const swRows = await this.ctx.model.StockWarehouse.findAll({ + where: { + id: { [this.app.Sequelize.Op.in]: stockIds }, + }, + attributes: [ 'id', 'item_name' ], + raw: true, + }); + for (const sw of (Array.isArray(swRows) ? swRows : [])) { + const sid = Number(sw.id || 0); + if (sid > 0 && !stockNameMap.has(sid)) { + stockNameMap.set(sid, String(sw.item_name || '').trim()); + } + } + } + } catch (err) { + this.app.logger.warn(`[order_export] 批量查询仓库商品名称失败: ${err.message}`); + } + } + + // 批量查询货主备注(wms_store_warehouse.store_remask) + const storeRemarkMap = new Map(); + if (orderIds.length > 0 && this.ctx && this.ctx.model && this.ctx.model.StoreWarehouse) { + try { + const storeIds = [ + ...new Set( + normalizedRows + .map(r => Number(r.store_id || 0)) + .filter(id => id > 0) + ), + ]; + if (storeIds.length > 0) { + const swRows = await this.ctx.model.StoreWarehouse.findAll({ + where: { + store_id: { [this.app.Sequelize.Op.in]: storeIds }, + warehouse_id: warehouseId, + }, + attributes: [ 'store_id', 'store_remask' ], + raw: true, + }); + for (const sw of (Array.isArray(swRows) ? swRows : [])) { + const sid = Number(sw.store_id || 0); + if (sid > 0 && !storeRemarkMap.has(sid)) { + storeRemarkMap.set(sid, String(sw.store_remask || '').trim()); + } + } + } + } catch (err) { + this.app.logger.warn(`[order_export] 批量查询货主备注失败: ${err.message}`); + } + } + + // 批量查询运单数据(wms_order_express),按订单ID分组 + const expressMap = new Map(); + if (orderIds.length > 0 && this.ctx && this.ctx.model && this.ctx.model.OrderExpress) { + try { + const expressRows = await this.ctx.model.OrderExpress.findAll({ + where: { + order_id: { [this.app.Sequelize.Op.in]: orderIds }, + warehouse_id: warehouseId, + }, + attributes: [ 'id', 'order_id', 'waybill_code', 'create_at', 'weighing_weight' ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + for (const exp of (Array.isArray(expressRows) ? expressRows : [])) { + const oid = Number(exp.order_id || 0); + if (oid > 0) { + if (!expressMap.has(oid)) { + expressMap.set(oid, []); + } + expressMap.get(oid).push(exp); + } + } + } catch (err) { + this.app.logger.warn(`[order_export] 批量查询运单数据失败: ${err.message}`); + } + } + + // 批量查询商品条码(wms_stock_barcodes) + const barcodeMap = new Map(); + if (stockNameMap.size > 0 && this.ctx && this.ctx.model && this.ctx.model.StockBarcode) { + try { + const stockIdsForBarcode = [ ...stockNameMap.keys() ]; + if (stockIdsForBarcode.length > 0) { + const bcRows = await this.ctx.model.StockBarcode.findAll({ + where: { stock_id: { [this.app.Sequelize.Op.in]: stockIdsForBarcode } }, + attributes: [ 'stock_id', 'barcode' ], + raw: true, + }); + for (const bc of (Array.isArray(bcRows) ? bcRows : [])) { + const sid = Number(bc.stock_id || 0); + if (sid > 0) { + if (!barcodeMap.has(sid)) barcodeMap.set(sid, []); + barcodeMap.get(sid).push(String(bc.barcode || '').trim()); + } + } + // 转为逗号拼接 + for (const [ sid, codes ] of barcodeMap) { + barcodeMap.set(sid, [ ...new Set(codes.filter(Boolean)) ].join(', ')); + } + } + } catch (err) { + this.app.logger.warn(`[order_export] 批量查询商品条码失败: ${err.message}`); + } + } + + const exportContext = { itemsMap, storeRemarkMap, stockNameMap, barcodeMap, expressMap }; + for (const row of normalizedRows) { - worksheet.addRow(this.mapOrderExportRow(row)).commit(); + const exportRows = this.mapOrderExportRow(row, exportContext, mode); + for (const exportRow of exportRows) { + worksheet.addRow(exportRow).commit(); + } } currentCount += normalizedRows.length; diff --git a/app/service/systems/order_print.js b/app/service/systems/order_print.js index 8a2bc9d..f2bee5a 100644 --- a/app/service/systems/order_print.js +++ b/app/service/systems/order_print.js @@ -207,6 +207,7 @@ class OrderPrintSystemService extends OrderBaseService { order_id: { [Op.in]: orderIds, }, + warehouse_id: warehouseId, status: { [Op.ne]: 'cancel', }, @@ -405,9 +406,36 @@ class OrderPrintSystemService extends OrderBaseService { delete item.stock_id; } + // 按库位(pick_location)聚合,同一库位的商品合并为一行 + const aggregatedMap = new Map(); + for (const item of printItems) { + const key = item.pick_location || ''; + const existing = aggregatedMap.get(key); + if (existing) { + // 累加数量 + existing.quantity += item.quantity; + // 合并 item_name(用 、 拼接去重) + if (item.item_name && !existing.item_name.split('、').includes(item.item_name)) { + existing.item_name = `${existing.item_name}、${item.item_name}`; + } + // 合并 barcode(用 ; 拼接去重) + if (item.barcode && !existing.barcode.split(';').includes(item.barcode)) { + existing.barcode = `${existing.barcode};${item.barcode}`; + } + // 合并 barcodes 数组(Set 去重) + if (item.barcodes && item.barcodes.length > 0) { + const merged = new Set([...(existing.barcodes || []), ...item.barcodes]); + existing.barcodes = Array.from(merged); + } + } else { + aggregatedMap.set(key, { ...item }); + } + } + const mergedPrintItems = Array.from(aggregatedMap.values()); + resultMap.set(orderId, { ...orderRow, - items: JSON.stringify(printItems), + items: JSON.stringify(mergedPrintItems), }); } @@ -1406,46 +1434,50 @@ class OrderPrintSystemService extends OrderBaseService { return []; } + // 公共查询字段:current 表与 dispatch 表使用相同字段选择 + const sharedAttributes = [ + 'id', + 'delivery_order_code', + 'source_order_codes', + 'warehouse_id', + 'store_id', + 'wave_id', + 'wave_no', + 'name', + 'tel', + 'mobile', + 'province', + 'city', + 'area', + 'town', + 'detail_address', + 'zip_code', + 'items', + 'source_platform_code', + 'sys_platform_code', + 'sys_platform_name', + 'logistics_code', + 'logistics_name', + 'sys_logistics_code', + 'sys_logistics_name', + 'post_status', + 'status', + 'outbound_status', + 'print_status', + 'lock_status', + 'print_lock_status', + 'items_count', + 'items_total', + 'items_weight', + 'freight', + 'create_at', + 'pay_time', + ]; + + // 第一步:查询 current 主表(wms_order_delivery_{warehouseId}) const orderModel = await this.getOrderModel('order', warehouseId); const rows = await orderModel.findAll({ - attributes: [ - 'id', - 'delivery_order_code', - 'source_order_codes', - 'warehouse_id', - 'store_id', - 'wave_id', - 'wave_no', - 'name', - 'tel', - 'mobile', - 'province', - 'city', - 'area', - 'town', - 'detail_address', - 'zip_code', - 'items', - 'source_platform_code', - 'sys_platform_code', - 'sys_platform_name', - 'logistics_code', - 'logistics_name', - 'sys_logistics_code', - 'sys_logistics_name', - 'post_status', - 'status', - 'outbound_status', - 'print_status', - 'lock_status', - 'print_lock_status', - 'items_count', - 'items_total', - 'items_weight', - 'freight', - 'create_at', - 'pay_time', - ], + attributes: sharedAttributes, where: { id: { [Op.in]: orderIds, @@ -1455,7 +1487,47 @@ class OrderPrintSystemService extends OrderBaseService { raw: true, }); - return Array.isArray(rows) ? rows : []; + const currentRows = Array.isArray(rows) ? rows : []; + + // 第二步:若 current 表未命中全部订单,计算缺失 ID 并兜底查询 dispatch 表 + if (currentRows.length < orderIds.length) { + const foundIds = new Set(currentRows.map(row => row.id)); + const missingIds = orderIds.filter(id => !foundIds.has(id)); + + try { + // 获取 dispatch 分表模型,表可能不存在(返回 null) + const dispatchModel = await this.getOrderModelByTableType('dispatch', warehouseId); + if (dispatchModel) { + const dispatchRows = await dispatchModel.findAll({ + attributes: sharedAttributes, + where: { + id: { + [Op.in]: missingIds, + }, + }, + order: [[ 'wave_id', 'ASC' ], [ 'id', 'ASC' ]], + raw: true, + }); + + if (Array.isArray(dispatchRows) && dispatchRows.length > 0) { + // 合并 current 表与 dispatch 表结果,按 wave_id、id 升序排列 + const mergedRows = [...currentRows, ...dispatchRows].sort((a, b) => { + const waveDiff = (a.wave_id || 0) - (b.wave_id || 0); + if (waveDiff !== 0) return waveDiff; + return (a.id || 0) - (b.id || 0); + }); + return mergedRows; + } + } + } catch (err) { + // dispatch 表查询失败时仅记录日志,不影响 current 表已查到的结果 + this.ctx.logger.warn( + `[queryOrdersByIds] dispatch 兜底查询失败,将仅返回 current 表结果:${err.message}` + ); + } + } + + return currentRows; } /** diff --git a/app/service/systems/order_storage_allocation.js b/app/service/systems/order_storage_allocation.js index 555f0bb..13b88d7 100644 --- a/app/service/systems/order_storage_allocation.js +++ b/app/service/systems/order_storage_allocation.js @@ -589,6 +589,7 @@ class OrderStorageAllocationService extends MainService { const pendingOrderIds = []; const skippedOrders = []; + const errorRetryOrderIds = []; for (const orderId of orderIds) { const orderRow = orderMap.get(orderId); @@ -627,8 +628,14 @@ class OrderStorageAllocationService extends MainService { } pendingOrderIds.push(orderId); + + if (String(orderRow.storage_status || 'none') === STORAGE_STATUS_ERROR) { + errorRetryOrderIds.push(orderId); + } + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 订单进入待分配列表', { orderId, + storageStatus: orderRow.storage_status, pendingOrderCount: pendingOrderIds.length, pendingOrderSampleIds: pendingOrderIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), }); @@ -638,8 +645,10 @@ class OrderStorageAllocationService extends MainService { requestedOrderCount: orderIds.length, pendingOrderCount: pendingOrderIds.length, skippedOrderCount: skippedOrders.length, + errorRetryOrderCount: errorRetryOrderIds.length, pendingOrderSampleIds: pendingOrderIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), skippedOrderSample: skippedOrders.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), + errorRetryOrderSampleIds: errorRetryOrderIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), }); if (pendingOrderIds.length === 0) { @@ -829,6 +838,67 @@ class OrderStorageAllocationService extends MainService { const totalCount = pendingOrderIds.length; let processedCount = 0; + // 对于 storage_status='error' 的重分配订单,先清理旧的 picking 记录并释放已锁定的库存 + if (errorRetryOrderIds.length > 0) { + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 检测到 error 重试订单,开始清理旧数据', { + warehouseId, + errorRetryOrderIds, + errorRetryOrderCount: errorRetryOrderIds.length, + }); + + const oldPickingRecords = await pickingModel.findAll({ + where: { + order_id: { [Op.in]: errorRetryOrderIds }, + status: 'pending', + }, + transaction, + lock: transaction.LOCK.UPDATE, + raw: true, + }); + + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 查询到旧的 picking 记录', { + warehouseId, + oldPickingCount: Array.isArray(oldPickingRecords) ? oldPickingRecords.length : 0, + }); + + if (Array.isArray(oldPickingRecords) && oldPickingRecords.length > 0) { + for (const record of oldPickingRecords) { + const storageId = toNumber(record.storage_id, 0); + const quantity = toNumber(record.quantity, 0); + + if (storageId > 0 && quantity > 0) { + await ctx.service.systems.storage.index.unlockQuantity(storageId, quantity, { transaction }); + + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 已释放旧库存锁定', { + warehouseId, + orderId: toNumber(record.order_id, 0), + storageId, + quantity, + }); + } + } + + await pickingModel.destroy({ + where: { + order_id: { [Op.in]: errorRetryOrderIds }, + status: 'pending', + }, + transaction, + }); + + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 已删除旧的 picking 记录', { + warehouseId, + errorRetryOrderIds, + deletedCount: oldPickingRecords.length, + }); + } + + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] error 订单旧数据清理完成', { + warehouseId, + errorRetryOrderIds, + }); + } + await notifyProgress({ status: 'running', total_count: totalCount, @@ -1027,6 +1097,7 @@ class OrderStorageAllocationService extends MainService { pickingRows.push({ order_id: orderId, order_item_id: toNumber(orderItem.id, 0), + warehouse_id: warehouseId, storage_id: storageRow.id, quantity: allocationQuantity, space_id: toNumber(storageRow.space_id, 0) || null, @@ -1937,6 +2008,7 @@ class OrderStorageAllocationService extends MainService { order_id: { [Op.in]: eligibleOrderIds, }, + warehouse_id: warehouseId, status: { [Op.ne]: 'cancel', }, diff --git a/app/service/systems/pick.js b/app/service/systems/pick.js index 86b3ea6..1c1256b 100644 --- a/app/service/systems/pick.js +++ b/app/service/systems/pick.js @@ -634,6 +634,7 @@ class PickSystemService extends Service { order_id: { [Op.in]: orderIds, }, + warehouse_id: normalizedWarehouseId, }, order: [[ 'id', 'ASC' ]], raw: true, @@ -1080,6 +1081,7 @@ class PickSystemService extends Service { order_id: { [this.app.Sequelize.Op.in]: orderIds, }, + warehouse_id: warehouseId, }, attributes: [ 'id', 'order_id', 'order_item_id', 'quantity', 'storage_id', 'space_id', 'space_name' ], order: [[ 'id', 'ASC' ]], @@ -1807,6 +1809,130 @@ class PickSystemService extends Service { hooks: false, }); + // 更新 wms_picking.status 为完成状态 + await ctx.model.query(` + UPDATE wms_picking + SET status = 'fin', updated_at = NOW() + WHERE order_id IN (:orderIds) + AND warehouse_id = :warehouseId + `, { + replacements: { + orderIds: targetOrderIds, + warehouseId, + }, + transaction, + }); + + // 从 wms_picking 汇总各 storage_id 的 quantity,扣减 wms_storage 的锁定数量与可用数量 + const pickingSummaryRows = await ctx.model.query(` + SELECT + p.storage_id, + SUM(p.quantity) AS total_qty + FROM wms_picking p + WHERE p.order_id IN (:orderIds) + AND p.warehouse_id = :warehouseId + AND p.storage_id IS NOT NULL + AND p.storage_id > 0 + GROUP BY p.storage_id + `, { + replacements: { + orderIds: targetOrderIds, + warehouseId, + }, + type: ctx.model.QueryTypes.SELECT, + transaction, + }); + + const normalizedSummaryRows = Array.isArray(pickingSummaryRows) ? pickingSummaryRows : []; + if (normalizedSummaryRows.length > 0) { + const storageIds = normalizedSummaryRows.map(r => Number(r.storage_id)); + const storageQtyMap = new Map(); + for (const row of normalizedSummaryRows) { + storageQtyMap.set(Number(row.storage_id), Number(row.total_qty) || 0); + } + + // 加行锁校验 locked_quantity >= 扣减数量 + const storageRows = await ctx.model.Storage.findAll({ + where: { + id: { [this.app.Sequelize.Op.in]: storageIds }, + warehouse_id: warehouseId, + }, + attributes: [ 'id', 'locked_quantity', 'quantity', 'store_id', 'stock_id', 'batch_no', 'inventory_type', 'space_id' ], + lock: transaction.LOCK.UPDATE, + raw: true, + transaction, + }); + + for (const sRow of storageRows) { + const sid = Number(sRow.id); + const deduction = storageQtyMap.get(sid) || 0; + const locked = Number(sRow.locked_quantity) || 0; + if (locked < deduction) { + throw this.createBusinessError( + `库存记录 ${sid} 锁定数量不足:当前锁定 ${locked},需扣减 ${deduction}`, + 400 + ); + } + } + + // 构建 CASE WHEN 语句 + const caseClauses = normalizedSummaryRows + .map(r => `WHEN ${Number(r.storage_id)} THEN ${Number(r.total_qty)}`) + .join(' '); + + await ctx.model.query(` + UPDATE wms_storage + SET locked_quantity = locked_quantity - CASE id ${caseClauses} END, + quantity = quantity - CASE id ${caseClauses} END, + updated_at = NOW() + WHERE id IN (:storageIds) + AND warehouse_id = :warehouseId + `, { + replacements: { + storageIds, + warehouseId, + }, + transaction, + }); + + // 写入 wms_storage_transaction 出库流水 + const transactionRows = []; + for (const sRow of storageRows) { + const sid = Number(sRow.id); + const deduction = storageQtyMap.get(sid) || 0; + if (deduction <= 0) continue; + const beforeQty = Number(sRow.quantity) || 0; + const beforeLocked = Number(sRow.locked_quantity) || 0; + transactionRows.push({ + transaction_type: 'OUTBOUND', + warehouse_id: warehouseId, + store_id: Number(sRow.store_id) || 0, + stock_id: Number(sRow.stock_id) || 0, + storage_id: sid, + space_id: Number(sRow.space_id) || null, + quantity: deduction, + before_quantity: beforeQty, + after_quantity: Math.max(0, beforeQty - deduction), + before_locked_quantity: beforeLocked, + after_locked_quantity: Math.max(0, beforeLocked - deduction), + batch_no: sRow.batch_no || null, + inventory_type: sRow.inventory_type || 'ZP', + order_type: 'PICK_OUTBOUND', + order_no: targetOrderIds.join(',').slice(0, 255), + order_id: taskId, + source_order_codes: targetOrderIds.join(', '), + operator_id: String(operatorId), + operator_name: operatorName, + remark: '拣货完成出库', + created_at: new Date(), + }); + } + + if (transactionRows.length > 0) { + await ctx.model.StorageTransaction.bulkCreate(transactionRows, { transaction }); + } + } + const progress = await this.getTaskPickProgress(taskId, warehouseId, transaction); if (mode === 1 || progress.isCompleted) { await ctx.model.query(` diff --git a/app/service/systems/pick_compensation.js b/app/service/systems/pick_compensation.js new file mode 100644 index 0000000..61247e0 --- /dev/null +++ b/app/service/systems/pick_compensation.js @@ -0,0 +1,694 @@ +'use strict'; + +const MainService = require('../main'); + +const MAX_BATCH_SIZE = 500; +const COMPENSATION_STATUS = 'fin_compensated'; +const COMPENSATION_ORDER_TYPE = 'PICK_COMPENSATION'; +const CANCELLED_RELEASED_STATUS = 'cancelled_released'; + +/** + * 拣货完成补偿服务。 + * + * 当 wavePickTaskComplete 因历史 BUG 遗漏扣减库存操作时, + * 本服务扫描 wms_picking 中 status='pending' 且订单已迁移到 dispatch 表的记录, + * 以与 wavePickTaskComplete 一致的事务逻辑补扣库存并写入出库流水。 + */ +class PickCompensationService extends MainService { + /** + * 执行全局拣货补偿扫描与补偿。 + * 遍历所有存在 pending 拣货记录的仓库,对符合条件的记录执行补偿。 + * + * @return {Promise<{totalCompensated: number}>} 全局补偿结果。 + */ + async executeCompensation() { + const { ctx } = this; + + // Step 1: 查找所有存在 pending 拣货记录的仓库 + const warehouseRows = await ctx.model.query(` + SELECT DISTINCT warehouse_id + FROM wms_picking + WHERE status = 'pending' + AND warehouse_id > 0 + `, { + type: ctx.model.QueryTypes.SELECT, + }); + + const warehouses = (Array.isArray(warehouseRows) ? warehouseRows : []) + .map(row => Number(row.warehouse_id)) + .filter(id => Number.isInteger(id) && id > 0); + + if (warehouses.length === 0) { + return { totalCompensated: 0 }; + } + + let totalCompensated = 0; + + for (const warehouseId of warehouses) { + try { + const compensated = await this.compensateWarehouse(warehouseId); + totalCompensated += compensated; + } catch (error) { + ctx.logger.error( + `[pick-compensation] 仓库 ${warehouseId} 补偿失败: ${error.message}` + ); + } + } + + return { totalCompensated }; + } + + /** + * 对指定仓库执行单次拣货补偿。 + * 先释放已取消订单的库存锁定,再处理拣货完成的 dispatch 订单补偿。 + * + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 本次补偿的拣货记录数。 + */ + async compensateWarehouse(warehouseId) { + const { ctx } = this; + const factory = ctx.model && ctx.model.OrderDeliveryFactory; + + if (!factory || typeof factory.getCurrentModel !== 'function' || typeof factory.getDispatchModel !== 'function') { + ctx.logger.warn(`[pick-compensation] 仓库 ${warehouseId} 订单分表工厂不可用,跳过`); + return 0; + } + + // 获取所有 pending 订单ID + const pendingOrderIds = await this.getPendingOrderIds(warehouseId); + if (pendingOrderIds.length === 0) { + return 0; + } + + const currentModel = await factory.getCurrentModel(warehouseId); + + let compensatedCount = 0; + + // Step A: 释放已取消订单的库存锁定 + const cancelledPickingRows = await this.findPendingPickingForCancelledOrders( + warehouseId, factory, pendingOrderIds + ); + if (cancelledPickingRows.length > 0) { + ctx.logger.info( + `[pick-compensation] 仓库 ${warehouseId} 发现 ${cancelledPickingRows.length} 条已取消订单待释放拣货记录` + ); + const released = await this.releaseCancelledInTransaction(warehouseId, cancelledPickingRows); + compensatedCount += released; + } + + // Step B: 查找符合条件的 dispatch 拣货记录 + const pickingRows = await this.findPendingPickingForDispatchOrders( + warehouseId, factory, currentModel, pendingOrderIds + ); + if (pickingRows.length === 0) { + return compensatedCount; + } + + ctx.logger.info( + `[pick-compensation] 仓库 ${warehouseId} 发现 ${pickingRows.length} 条待补偿拣货记录` + ); + + // Step C: 在事务中执行拣货完成补偿 + const dispatchCompensated = await this.compensateInTransaction(warehouseId, pickingRows); + compensatedCount += dispatchCompensated; + + if (dispatchCompensated > 0) { + const orderIds = [ ...new Set(pickingRows.map(r => Number(r.order_id))) ]; + const pickingIds = pickingRows.map(r => Number(r.id)); + const storageIds = [ ...new Set(pickingRows + .map(r => Number(r.storage_id)) + .filter(id => id > 0)) ]; + + ctx.logger.info( + `[pick-compensation] 仓库 ${warehouseId} 补偿完成:` + + `拣货记录 ${pickingIds.join(',')},` + + `订单 ${orderIds.join(',')},` + + `库存记录 ${storageIds.join(',')}` + ); + } + + return compensatedCount; + } + + /** + * 获取指定仓库下所有待处理拣货记录的订单ID列表。 + * + * @param {number} warehouseId 仓库ID。 + * @return {Promise>} 待处理的订单ID列表。 + */ + async getPendingOrderIds(warehouseId) { + const { ctx } = this; + + const pendingOrderRows = await ctx.model.query(` + SELECT DISTINCT p.order_id + FROM wms_picking p + WHERE p.status = 'pending' + AND p.warehouse_id = :warehouseId + AND p.warehouse_id > 0 + `, { + replacements: { warehouseId }, + type: ctx.model.QueryTypes.SELECT, + }); + + return (Array.isArray(pendingOrderRows) ? pendingOrderRows : []) + .map(row => Number(row.order_id)) + .filter(id => Number.isInteger(id) && id > 0); + } + + /** + * 查找仓库下待补偿的拣货记录(dispatch 拣货完成场景)。 + * 条件:status='pending',对应订单在 dispatch 表中 pick_status='fin', + * 且订单不在 current 表中(已迁移到配送表)。 + * + * @param {number} warehouseId 仓库ID。 + * @param {Object} factory OrderDeliveryFactory 实例。 + * @param {Object} currentModel 订单 current 表的 Sequelize 模型。 + * @param {Array} pendingOrderIds 待处理的订单ID列表。 + * @return {Promise>} 待补偿的拣货记录列表。 + */ + async findPendingPickingForDispatchOrders(warehouseId, factory, currentModel, pendingOrderIds) { + const { ctx, app } = this; + + if (!Array.isArray(pendingOrderIds) || pendingOrderIds.length === 0) { + return []; + } + + // 查询 current 表:哪些订单还在主表中 + const currentOrders = await currentModel.findAll({ + where: { + id: { [app.Sequelize.Op.in]: pendingOrderIds }, + warehouse_id: warehouseId, + }, + attributes: [ 'id' ], + raw: true, + }); + + const currentOrderIdSet = new Set( + (Array.isArray(currentOrders) ? currentOrders : []) + .map(row => Number(row.id)) + ); + + // 查询 dispatch 表:哪些订单 pick_status='fin' + const dispatchModel = await factory.getDispatchModel(warehouseId); + const dispatchOrders = await dispatchModel.findAll({ + where: { + id: { [app.Sequelize.Op.in]: pendingOrderIds }, + warehouse_id: warehouseId, + pick_status: 'fin', + }, + attributes: [ 'id' ], + raw: true, + }); + + const dispatchOrderIdSet = new Set( + (Array.isArray(dispatchOrders) ? dispatchOrders : []) + .map(row => Number(row.id)) + ); + + // 符合条件的订单:在 dispatch 中 pick_status='fin',且不在 current 中 + const eligibleOrderIds = pendingOrderIds.filter( + id => dispatchOrderIdSet.has(id) && !currentOrderIdSet.has(id) + ); + + if (eligibleOrderIds.length === 0) { + return []; + } + + // 查询对应的拣货记录(带 storage_id,限制每批处理上限) + const pickingRows = await ctx.model.query(` + SELECT + p.id, + p.order_id, + p.warehouse_id, + p.storage_id, + p.quantity + FROM wms_picking p + WHERE p.status = 'pending' + AND p.warehouse_id = :warehouseId + AND p.order_id IN (:orderIds) + AND p.storage_id IS NOT NULL + AND p.storage_id > 0 + ORDER BY p.id ASC + LIMIT :limit + `, { + replacements: { + warehouseId, + orderIds: eligibleOrderIds, + limit: MAX_BATCH_SIZE, + }, + type: ctx.model.QueryTypes.SELECT, + }); + + return Array.isArray(pickingRows) ? pickingRows : []; + } + + /** + * 查找已取消订单关联的待处理拣货记录。 + * 在 pendingOrderIds 中筛选 dispatch 表中 status='cancel' 的订单, + * 返回对应的 wms_picking 记录(status='pending')。 + * + * @param {number} warehouseId 仓库ID。 + * @param {Object} factory OrderDeliveryFactory 实例。 + * @param {Array} pendingOrderIds 待处理的订单ID列表。 + * @return {Promise>} 已取消订单对应的拣货记录列表。 + */ + async findPendingPickingForCancelledOrders(warehouseId, factory, pendingOrderIds) { + const { ctx, app } = this; + + if (!Array.isArray(pendingOrderIds) || pendingOrderIds.length === 0) { + return []; + } + + // 查询 dispatch 表中已取消的订单 + const dispatchModel = await factory.getDispatchModel(warehouseId); + const cancelledOrders = await dispatchModel.findAll({ + where: { + id: { [app.Sequelize.Op.in]: pendingOrderIds }, + warehouse_id: warehouseId, + status: 'cancel', + }, + attributes: [ 'id' ], + raw: true, + }); + + const cancelledOrderIds = (Array.isArray(cancelledOrders) ? cancelledOrders : []) + .map(row => Number(row.id)); + + if (cancelledOrderIds.length === 0) { + return []; + } + + // 查询对应的拣货记录(带 storage_id,限制每批处理上限) + const pickingRows = await ctx.model.query(` + SELECT + p.id, + p.order_id, + p.warehouse_id, + p.storage_id, + p.quantity + FROM wms_picking p + WHERE p.status = 'pending' + AND p.warehouse_id = :warehouseId + AND p.order_id IN (:orderIds) + AND p.storage_id IS NOT NULL + AND p.storage_id > 0 + ORDER BY p.id ASC + LIMIT :limit + `, { + replacements: { + warehouseId, + orderIds: cancelledOrderIds, + limit: MAX_BATCH_SIZE, + }, + type: ctx.model.QueryTypes.SELECT, + }); + + return Array.isArray(pickingRows) ? pickingRows : []; + } + + /** + * 在事务中释放已取消订单的库存锁定。 + * + * 事务步骤: + * 1. 重新查询 wms_picking(status='pending')汇总各 storage_id 的 SUM(quantity) + * 2. SELECT wms_storage FOR UPDATE + * 3. 校验 locked_quantity >= 解锁数量 + * 4. UPDATE wms_storage 只解锁 locked_quantity(不扣减 quantity) + * 5. UPDATE wms_picking SET status='cancelled_released' + * + * 注意:本方法不写入 wms_storage_transaction。 + * + * @param {number} warehouseId 仓库ID。 + * @param {Array} cancelledPickingRows 已取消订单关联的拣货记录列表。 + * @return {Promise} 释放成功的拣货记录数。 + */ + async releaseCancelledInTransaction(warehouseId, cancelledPickingRows) { + const { ctx, app } = this; + + if (!Array.isArray(cancelledPickingRows) || cancelledPickingRows.length === 0) { + return 0; + } + + const pickingIds = cancelledPickingRows.map(row => Number(row.id)); + + const transaction = await ctx.model.transaction(); + + try { + // Step 1: 重新查询 wms_picking,确保只处理仍然 status='pending' 的记录 + const confirmedRows = await ctx.model.query(` + SELECT + p.id, + p.order_id, + p.storage_id, + p.quantity + FROM wms_picking p + WHERE p.id IN (:pickingIds) + AND p.warehouse_id = :warehouseId + AND p.status = 'pending' + AND p.storage_id IS NOT NULL + AND p.storage_id > 0 + `, { + replacements: { pickingIds, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + transaction, + }); + + const normalizedConfirmedRows = Array.isArray(confirmedRows) ? confirmedRows : []; + if (normalizedConfirmedRows.length === 0) { + await transaction.rollback(); + return 0; + } + + // 汇总各 storage_id 的 SUM(quantity) + const storageQtyMap = new Map(); + for (const row of normalizedConfirmedRows) { + const sid = Number(row.storage_id); + const qty = Number(row.quantity) || 0; + storageQtyMap.set(sid, (storageQtyMap.get(sid) || 0) + qty); + } + + const storageIds = [ ...storageQtyMap.keys() ]; + + // Step 2: SELECT wms_storage FOR UPDATE + const storageRows = await ctx.model.Storage.findAll({ + where: { + id: { [app.Sequelize.Op.in]: storageIds }, + warehouse_id: warehouseId, + }, + attributes: [ 'id', 'locked_quantity' ], + lock: transaction.LOCK.UPDATE, + raw: true, + transaction, + }); + + // Step 3: 校验 locked_quantity >= 解锁数量 + for (const sRow of storageRows) { + const sid = Number(sRow.id); + const deduction = storageQtyMap.get(sid) || 0; + const locked = Number(sRow.locked_quantity) || 0; + if (locked < deduction) { + throw this.createBusinessError( + `库存记录 ${sid} 锁定数量不足:当前锁定 ${locked},需解锁 ${deduction}`, + 400 + ); + } + } + + // Step 4: UPDATE wms_storage 只解锁 locked_quantity(不扣减 quantity) + const summaryRows = []; + for (const [ sid, totalQty ] of storageQtyMap) { + summaryRows.push({ storage_id: sid, total_qty: totalQty }); + } + + const caseClauses = summaryRows + .map(r => `WHEN ${Number(r.storage_id)} THEN ${Number(r.total_qty)}`) + .join(' '); + + const explicitStorageIdList = storageIds.map(id => Number(id)).join(', '); + + await ctx.model.query(` + UPDATE wms_storage + SET locked_quantity = locked_quantity - CASE id ${caseClauses} END, + updated_at = NOW() + WHERE id IN (${explicitStorageIdList}) + AND warehouse_id = :warehouseId + `, { + replacements: { warehouseId }, + transaction, + }); + + // Step 5: UPDATE wms_picking SET status='cancelled_released' + const compensatedPickingIds = normalizedConfirmedRows.map(r => Number(r.id)); + await ctx.model.query(` + UPDATE wms_picking + SET status = :status, + updated_at = NOW() + WHERE id IN (:pickingIds) + AND warehouse_id = :warehouseId + `, { + replacements: { + status: CANCELLED_RELEASED_STATUS, + pickingIds: compensatedPickingIds, + warehouseId, + }, + transaction, + }); + + await transaction.commit(); + + return compensatedPickingIds.length; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + /** + * 在事务中执行拣货补偿,与 wavePickTaskComplete 保持一致的逻辑。 + * + * 事务步骤: + * 1. 重新查询 wms_picking(status='pending')汇总各 storage_id 的 SUM(quantity) + * 2. SELECT wms_storage FOR UPDATE + * 3. 校验 locked_quantity >= 扣减数量 + * 4. UPDATE wms_storage 扣减 locked_quantity 和 quantity(CASE WHEN) + * 5. 查询 dispatch 表获取订单的 delivery_order_code 和 source_order_codes, + * 为每个拣货记录 INSERT 一条 wms_storage_transaction(OUTBOUND, PICK_COMPENSATION), + * 同一 storage 的多条记录共享相同的 before/after 数量 + * 6. UPDATE wms_picking SET status='fin_compensated' + * + * @param {number} warehouseId 仓库ID。 + * @param {Array} pickingRows 待补偿的拣货记录列表。 + * @return {Promise} 补偿成功的拣货记录数。 + */ + async compensateInTransaction(warehouseId, pickingRows) { + const { ctx, app } = this; + + if (!Array.isArray(pickingRows) || pickingRows.length === 0) { + return 0; + } + + const pickingIds = pickingRows.map(row => Number(row.id)); + + const transaction = await ctx.model.transaction(); + + try { + // Step 1: 重新查询 wms_picking,确保只处理仍然 status='pending' 的记录 + const confirmedRows = await ctx.model.query(` + SELECT + p.id, + p.order_id, + p.storage_id, + p.quantity + FROM wms_picking p + WHERE p.id IN (:pickingIds) + AND p.warehouse_id = :warehouseId + AND p.status = 'pending' + AND p.storage_id IS NOT NULL + AND p.storage_id > 0 + `, { + replacements: { pickingIds, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + transaction, + }); + + const normalizedConfirmedRows = Array.isArray(confirmedRows) ? confirmedRows : []; + if (normalizedConfirmedRows.length === 0) { + await transaction.rollback(); + return 0; + } + + // 汇总各 storage_id 的 SUM(quantity) + const storageQtyMap = new Map(); + for (const row of normalizedConfirmedRows) { + const sid = Number(row.storage_id); + const qty = Number(row.quantity) || 0; + storageQtyMap.set(sid, (storageQtyMap.get(sid) || 0) + qty); + } + + const storageIds = [ ...storageQtyMap.keys() ]; + + // Step 2: SELECT wms_storage FOR UPDATE + const storageRows = await ctx.model.Storage.findAll({ + where: { + id: { [app.Sequelize.Op.in]: storageIds }, + warehouse_id: warehouseId, + }, + attributes: [ + 'id', 'locked_quantity', 'quantity', + 'store_id', 'stock_id', 'batch_no', + 'inventory_type', 'space_id', + ], + lock: transaction.LOCK.UPDATE, + raw: true, + transaction, + }); + + // Step 3: 校验 locked_quantity >= 扣减数量 + for (const sRow of storageRows) { + const sid = Number(sRow.id); + const deduction = storageQtyMap.get(sid) || 0; + const locked = Number(sRow.locked_quantity) || 0; + if (locked < deduction) { + throw this.createBusinessError( + `库存记录 ${sid} 锁定数量不足:当前锁定 ${locked},需扣减 ${deduction}`, + 400 + ); + } + } + + // Step 4: UPDATE wms_storage 扣减 locked_quantity 和 quantity(CASE WHEN) + const summaryRows = []; + for (const [ sid, totalQty ] of storageQtyMap) { + summaryRows.push({ storage_id: sid, total_qty: totalQty }); + } + + const caseClauses = summaryRows + .map(r => `WHEN ${Number(r.storage_id)} THEN ${Number(r.total_qty)}`) + .join(' '); + + const explicitStorageIdList = storageIds.map(id => Number(id)).join(', '); + + const [ updateResult ] = await ctx.model.query(` + UPDATE wms_storage + SET locked_quantity = locked_quantity - CASE id ${caseClauses} END, + quantity = quantity - CASE id ${caseClauses} END, + updated_at = NOW() + WHERE id IN (${explicitStorageIdList}) + AND warehouse_id = :warehouseId + `, { + replacements: { warehouseId }, + transaction, + }); + + if (!updateResult || Number(updateResult) === 0) { + ctx.logger.warn( + `[pick-compensation] wms_storage UPDATE 影响 0 行,storageIds=[${explicitStorageIdList}], warehouseId=${warehouseId}` + ); + } else { + ctx.logger.info( + `[pick-compensation] wms_storage UPDATE 影响 ${updateResult} 行,storageIds=[${explicitStorageIdList}], warehouseId=${warehouseId}` + ); + } + + // Step 5: INSERT wms_storage_transaction(每个拣货记录对应一条流水) + const confirmedOrderIds = [ ...new Set(normalizedConfirmedRows.map(r => Number(r.order_id))) ]; + + // 构建 storage_id -> storage row 映射 + const storageRowMap = new Map(); + for (const sRow of storageRows) { + storageRowMap.set(Number(sRow.id), sRow); + } + + // 构建 storage 变更前后的数量映射(同一 storage 多条拣货记录共享相同的 before/after) + const beforeQtyMap = new Map(); + const beforeLockedMap = new Map(); + for (const sRow of storageRows) { + const sid = Number(sRow.id); + beforeQtyMap.set(sid, Number(sRow.quantity) || 0); + beforeLockedMap.set(sid, Number(sRow.locked_quantity) || 0); + } + + // 查询 dispatch 表获取 delivery_order_code 和 source_order_codes + const factory = ctx.model && ctx.model.OrderDeliveryFactory; + const dispatchModel = factory && typeof factory.getDispatchModel === 'function' + ? await factory.getDispatchModel(warehouseId) + : null; + + const orderInfoMap = new Map(); + if (dispatchModel && confirmedOrderIds.length > 0) { + const dispatchRows = await dispatchModel.findAll({ + where: { + id: { [app.Sequelize.Op.in]: confirmedOrderIds }, + warehouse_id: warehouseId, + }, + attributes: [ 'id', 'delivery_order_code', 'source_order_codes' ], + raw: true, + transaction, + }); + for (const dRow of dispatchRows) { + orderInfoMap.set(Number(dRow.id), { + delivery_order_code: dRow.delivery_order_code, + source_order_codes: dRow.source_order_codes, + }); + } + } + + const transactionRows = []; + for (const pickRow of normalizedConfirmedRows) { + const orderId = Number(pickRow.order_id); + const orderInfo = orderInfoMap.get(orderId); + const sid = Number(pickRow.storage_id); + const deduction = Number(pickRow.quantity) || 0; + const sRow = storageRowMap.get(sid); + if (!sRow || deduction <= 0) continue; + + transactionRows.push({ + transaction_type: 'OUTBOUND', + warehouse_id: warehouseId, + store_id: Number(sRow.store_id) || 0, + stock_id: Number(sRow.stock_id) || 0, + storage_id: sid, + space_id: Number(sRow.space_id) || null, + quantity: deduction, + before_quantity: beforeQtyMap.get(sid), + after_quantity: Math.max(0, beforeQtyMap.get(sid) - (storageQtyMap.get(sid) || 0)), + before_locked_quantity: beforeLockedMap.get(sid), + after_locked_quantity: Math.max(0, beforeLockedMap.get(sid) - (storageQtyMap.get(sid) || 0)), + batch_no: sRow.batch_no || null, + inventory_type: sRow.inventory_type || 'ZP', + order_type: COMPENSATION_ORDER_TYPE, + order_no: orderInfo?.delivery_order_code || String(orderId), + order_id: orderId, + source_order_codes: orderInfo?.source_order_codes || String(orderId), + operator_id: 'system', + operator_name: 'system', + remark: '拣货完成补偿出库', + created_at: new Date(), + }); + } + + if (transactionRows.length > 0) { + await ctx.model.StorageTransaction.bulkCreate(transactionRows, { transaction }); + } + + // Step 6: UPDATE wms_picking SET status='fin_compensated' + const compensatedPickingIds = normalizedConfirmedRows.map(r => Number(r.id)); + await ctx.model.query(` + UPDATE wms_picking + SET status = :compensationStatus, + updated_at = NOW() + WHERE id IN (:pickingIds) + AND warehouse_id = :warehouseId + `, { + replacements: { + compensationStatus: COMPENSATION_STATUS, + pickingIds: compensatedPickingIds, + warehouseId, + }, + transaction, + }); + + await transaction.commit(); + + return compensatedPickingIds.length; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + /** + * 生成带业务状态码的错误对象。 + * + * @param {string} message 错误文案。 + * @param {number} [code=400] 错误码。 + * @return {Error} 错误对象。 + */ + createBusinessError(message, code = 400) { + const error = new Error(message); + error.code = code; + return error; + } +} + +module.exports = PickCompensationService; diff --git a/app/service/systems/setting/print_template.js b/app/service/systems/setting/print_template.js index bffdb07..ab6bd81 100644 --- a/app/service/systems/setting/print_template.js +++ b/app/service/systems/setting/print_template.js @@ -1,7 +1,7 @@ 'use strict'; const Service = require('egg').Service; -const SUPPORTED_BUSINESS_TYPES = [ 'STOCK', 'RECEIPT', 'PICKING' ]; +const SUPPORTED_BUSINESS_TYPES = [ 'STOCK', 'RECEIPT', 'PICKING', 'OUTBOUND' ]; class PrintTemplateService extends Service { /** diff --git a/app/service/systems/setting/warehouse.js b/app/service/systems/setting/warehouse.js index aae7713..6abb3c9 100644 --- a/app/service/systems/setting/warehouse.js +++ b/app/service/systems/setting/warehouse.js @@ -117,7 +117,7 @@ const WAREHOUSE_SETTING_FIELDS = Object.freeze([ key: 'auto_outbound_rules', name: '自动出库规则', type: 'object', - default: Object.freeze({ enabled: false, require_recheck: true, require_pack: true, require_weigh: true, require_sync: true }), + default: Object.freeze({ enabled: false, require_recheck: true, require_pack: true, require_weigh: true, require_sync: true, require_print: true, require_pick: true }), required: false, description: '满足条件自动标记出库。全部条件满足时自动标记待出库', item_keys: Object.freeze([ @@ -126,6 +126,8 @@ const WAREHOUSE_SETTING_FIELDS = Object.freeze([ Object.freeze({ key: 'require_pack', name: '需已打包', type: 'flag', required: false, description: '是否要求 pack_status=fin' }), Object.freeze({ key: 'require_weigh', name: '需已称重', type: 'flag', required: false, description: '是否要求 weighing_weight>0' }), Object.freeze({ key: 'require_sync', name: '需已同步', type: 'flag', required: false, description: '是否要求 sync_status=fin' }), + Object.freeze({ key: 'require_print', name: '需已打印', type: 'flag', required: false, description: '是否要求 print_status=fin' }), + Object.freeze({ key: 'require_pick', name: '需已拣货', type: 'flag', required: false, description: '是否要求 pick_status=fin' }), ]), }), Object.freeze({ diff --git a/app/service/systems/stock_store.js b/app/service/systems/stock_store.js index 59fc28a..b5862ce 100644 --- a/app/service/systems/stock_store.js +++ b/app/service/systems/stock_store.js @@ -962,9 +962,10 @@ class stockStoreService extends Service { * @param {number|null} orderId 订单 ID。 * @param {number|null} orderItemId 订单明细 ID。 * @param {Object|null} transaction 事务对象。 + * @param {number} warehouseId 仓库ID。 * @return {Promise>} 拣货分配列表。 */ - async getPickingRowsForOutbound(orderId, orderItemId, transaction) { + async getPickingRowsForOutbound(orderId, orderItemId, transaction, warehouseId) { const { ctx } = this; const pickingModel = ctx.model && ctx.model.Picking; @@ -980,6 +981,7 @@ class stockStoreService extends Service { where: { order_id: orderId, order_item_id: orderItemId, + warehouse_id: warehouseId, }, attributes: [ 'storage_id', 'space_id', 'quantity' ], order: [[ 'id', 'ASC' ]], @@ -1214,7 +1216,8 @@ class stockStoreService extends Service { let pickingRows = []; if (outboundMeta.orderId && outboundMeta.orderItemId) { try { - pickingRows = await this.getPickingRowsForOutbound(outboundMeta.orderId, outboundMeta.orderItemId, currentTransaction); + const pickingWarehouseId = Number(storage.warehouse_id || updatedRecord.warehouse_id || ctx.user.store_id || 0); + pickingRows = await this.getPickingRowsForOutbound(outboundMeta.orderId, outboundMeta.orderItemId, currentTransaction, pickingWarehouseId); } catch (error) { app.logger.warn(`[outbound] 读取拣货分配失败,降级为单条出库流水: ${error.message}`); } @@ -2679,6 +2682,7 @@ class stockStoreService extends Service { box_width, box_height, box_volume, box_remark, id, box_volume_m3, boxVolumeM3, shelf_life_days, inbound_min_days, outbound_min_days, remaining_threshold_days, + barcode, } = data; const normalizedVolume = volume ?? volume_cm3 ?? volumeCm3; const normalizedBoxVolume = box_volume ?? box_volume_m3 ?? boxVolumeM3; @@ -2799,6 +2803,39 @@ class stockStoreService extends Service { warehouseId, }, }); + + // 6.5 处理条码:清理旧条码并写入新条码 + if (Object.prototype.hasOwnProperty.call(data, 'barcode')) { + const barcodesArr = Array.isArray(barcode) + ? barcode + : typeof barcode === 'string' + ? barcode.split(';') + : []; + const normalizedBarcodes = barcodesArr + .map(item => String(item || '').trim()) + .filter(item => item !== ''); + + // 删除该商品已有的所有条码 + await ctx.model.StockBarcode.destroy({ + where: { + stock_id: id, + warehouse_id: warehouseId, + }, + transaction, + }); + + // 写入新条码 + if (normalizedBarcodes.length > 0) { + const refData = normalizedBarcodes.map(item => ({ + stock_id: id, + barcode: item, + warehouse_id: warehouseId, + created_at: new Date(), + })); + await ctx.model.StockBarcode.bulkCreate(refData, { transaction }); + } + } + // 7. 提交事务 await transaction.commit(); diff --git a/app/service/systems/storage/entry.js b/app/service/systems/storage/entry.js index 9f53bd5..ce1dac3 100644 --- a/app/service/systems/storage/entry.js +++ b/app/service/systems/storage/entry.js @@ -551,7 +551,7 @@ class EntryService extends Service { supplier_code: data.supplier_code || '', supplier_name: data.supplier_name || '', source_type: 'API', - order_status: 'CREATED', + order_status: 'PENDING', sync_status: 'PENDING', sync_message: '', is_enabled: 1, diff --git a/app/service/systems/storage/inventory.js b/app/service/systems/storage/inventory.js index 7bb3df9..92079fe 100644 --- a/app/service/systems/storage/inventory.js +++ b/app/service/systems/storage/inventory.js @@ -414,15 +414,15 @@ class InventoryService extends Service { contract = contract_data.data; } - const entryOrderCode = `SCRK${Date.now()}${String(Math.floor(Math.random() * 10000)).padStart(4, '0')}`; + const entryOrderCode = `SHRK${Date.now()}${String(Math.floor(Math.random() * 10000)).padStart(4, '0')}`; const entryOrder = await ctx.model.EntryOrder.create({ entry_order_code: entryOrderCode, - order_type: 'SCRK', + order_type: 'SHRK', purchase_order_code: receiving.receiving_number || '', total_order_lines: pendingDetails.length, order_create_time: new Date(), source_type: 'WMS', - order_status: 'CREATED', + order_status: 'PENDING', sync_status: 'SUCCESS', sync_message: `快捷入库-来自收货单 ${receiving.receiving_number}`, is_enabled: 1, @@ -561,7 +561,7 @@ class InventoryService extends Service { quantity: inboundQty, batch_no: batchNo, inventory_type: inventoryType, - order_type: 'SCRK', + order_type: 'SHRK', order_no: entryOrderCode, order_id: null, receiving_id: receivingId, @@ -768,7 +768,7 @@ class InventoryService extends Service { warehouse_id: warehouseId, is_enabled: 1, deleted_at: null, - order_status: { [Op.in]: [ 'PENDING', 'CONFIRMED', 'PARTIAL_RECEIVED', 'CREATED' ] }, + order_status: { [Op.in]: [ 'PENDING', 'CONFIRMED', 'PARTIAL_RECEIVED' ] }, }, lock: transaction.LOCK.UPDATE, transaction, diff --git a/app/service/systems/store_warehouse.js b/app/service/systems/store_warehouse.js index 6a02cf0..6723877 100644 --- a/app/service/systems/store_warehouse.js +++ b/app/service/systems/store_warehouse.js @@ -13,6 +13,15 @@ const AUTH_STATUS_LABELS = Object.freeze({ 5: '已过期', }); +const CHANGE_TYPE_LABEL_MAP = Object.freeze({ + manual_adjust: '人工调整', + order_deduct: '订单扣减', +}); + +const BUSINESS_TYPE_LABEL_MAP = Object.freeze({ + order_express: '快递订单', +}); + class SettingStoreWarehouseService extends Service { /** * 创建统一错误对象。 @@ -1858,7 +1867,11 @@ class SettingStoreWarehouseService extends Service { store_id: Number(payload.store_id || 0), warehouse_id: Number(payload.warehouse_id || 0), change_type: payload.change_type ? String(payload.change_type) : '', + change_type_label: CHANGE_TYPE_LABEL_MAP[payload.change_type] || payload.change_type || '', business_type: payload.business_type ? String(payload.business_type) : null, + business_type_label: payload.business_type + ? (BUSINESS_TYPE_LABEL_MAP[payload.business_type] || payload.business_type) + : '-', business_id: payload.business_id !== undefined && payload.business_id !== null ? Number(payload.business_id) : null, diff --git a/database/migrations/20260611100000-add-warehouse-id-to-wms-picking.js b/database/migrations/20260611100000-add-warehouse-id-to-wms-picking.js new file mode 100644 index 0000000..1de4197 --- /dev/null +++ b/database/migrations/20260611100000-add-warehouse-id-to-wms-picking.js @@ -0,0 +1,22 @@ +'use strict'; + +/** + * 为 wms_picking 表新增 warehouse_id 字段及索引。 + */ +module.exports = { + up: async queryInterface => { + await queryInterface.sequelize.query(` + ALTER TABLE wms_picking + ADD COLUMN warehouse_id BIGINT(20) UNSIGNED NOT NULL DEFAULT 0 COMMENT '仓库ID' AFTER order_item_id, + ADD INDEX idx_wms_picking_warehouse_id (warehouse_id) + `); + }, + + down: async queryInterface => { + await queryInterface.sequelize.query(` + ALTER TABLE wms_picking + DROP INDEX idx_wms_picking_warehouse_id, + DROP COLUMN warehouse_id + `); + }, +}; diff --git a/database/migrations/20260611180000-add-shrk-to-entry-order-type.js b/database/migrations/20260611180000-add-shrk-to-entry-order-type.js new file mode 100644 index 0000000..80f7c47 --- /dev/null +++ b/database/migrations/20260611180000-add-shrk-to-entry-order-type.js @@ -0,0 +1,14 @@ +'use strict'; + +module.exports = { + up: async queryInterface => { + await queryInterface.sequelize.query( + "ALTER TABLE wms_entry_order MODIFY COLUMN order_type ENUM('SCRK','LYRK','CCRK','CGRK','DBRK','QTRK','B2BRK','XNRK','SHRK') NOT NULL COMMENT '业务类型'" + ); + }, + down: async queryInterface => { + await queryInterface.sequelize.query( + "ALTER TABLE wms_entry_order MODIFY COLUMN order_type ENUM('SCRK','LYRK','CCRK','CGRK','DBRK','QTRK','B2BRK','XNRK') NOT NULL COMMENT '业务类型'" + ); + }, +}; diff --git a/database/migrations/20260611190000-merge-created-to-pending.js b/database/migrations/20260611190000-merge-created-to-pending.js new file mode 100644 index 0000000..c456466 --- /dev/null +++ b/database/migrations/20260611190000-merge-created-to-pending.js @@ -0,0 +1,28 @@ +'use strict'; + +module.exports = { + /** + * 将 CREATED 状态合并到 PENDING: + * 1. 先把现有 CREATED 行更新为 PENDING + * 2. 再 ALTER TABLE 去掉 CREATED 枚举值 + */ + up: async queryInterface => { + // 先更新现有 CREATED 行 + await queryInterface.sequelize.query( + "UPDATE wms_entry_order SET order_status = 'PENDING', updated_at = NOW() WHERE order_status = 'CREATED'" + ); + // 再修改 ENUM 列定义,移除 CREATED + await queryInterface.sequelize.query( + "ALTER TABLE wms_entry_order MODIFY COLUMN order_status ENUM('PENDING','CONFIRMED','PARTIAL_RECEIVED','COMPLETED','CANCELLED','CREATING') NOT NULL DEFAULT 'PENDING' COMMENT '订单状态'" + ); + }, + + /** + * 回滚:将 CREATED 加回 ENUM(数据不回退,因为无法区分哪些行原本是 CREATED) + */ + down: async queryInterface => { + await queryInterface.sequelize.query( + "ALTER TABLE wms_entry_order MODIFY COLUMN order_status ENUM('PENDING','CONFIRMED','PARTIAL_RECEIVED','COMPLETED','CANCELLED','CREATED','CREATING') NOT NULL DEFAULT 'PENDING' COMMENT '订单状态'" + ); + }, +}; diff --git a/logo.svg b/logo.svg new file mode 100644 index 0000000..bfc0aec --- /dev/null +++ b/logo.svg @@ -0,0 +1,10 @@ + + + + + + + + + W + diff --git a/methods/changes/system.json b/methods/changes/system.json index 00ff8ab..0284e7c 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -3219,5 +3219,117 @@ "字段来源:getOrderExpressesByOrderId 方法中 sys_logistics_code/sys_logistics_name 取自订单表 sys_logistics_code/sys_logistics_name,其余字段取自 OrderExpress 表" ], "type": "updated" + }, + { + "version": "2026.06.10-system-02", + "date": "2026-06-10", + "summary": "dashboard.order_trend 从 mock 数据改为查询真实数据库,按小时统计当日订单数与发货数,补充完整返回结构与错误说明", + "methods": [ + "dashboard.order_trend" + ], + "notes": [ + "接口实现从 mock 静态数据改为查询真实数据库(wms_order_delivery 与 dispatch 表),数据实时反映仓库当日运营情况。", + "订单筛选条件:step in [1,2,3],排除 outbound_status='padding' 和 status='cancel',统计 create_at 在今日 00:00 到当前时刻的订单,按 HOUR(create_at) 分组。", + "发货筛选条件:dispatch_lane='m4',统计 delivery_time 在今日 00:00 到当前时刻的发货记录,按 HOUR(delivery_time) 分组。", + "时段范围:从 08:00 到当前小时(最晚 23:00),若当前时间早于 08:00 则从 08:00 开始。", + "返回新增 summary 汇总对象:total_orders(订单总数)、total_shipments(发货总数)、shipment_rate(发货率百分比)、peak_hour(峰值时段)、peak_orders(峰值订单数)。", + "categories/orders/shipments 三个数组一一对应,提供按时段的订单与发货趋势数据,可直接用于前端折线图/柱状图渲染。", + "需要登录(Authorization header),从 token 中获取 warehouseId;若缺少仓库上下文则返回 flag='fail'。" + ], + "type": "updated", + "module": "dashboard" + }, + { + "version": "2026.06.10-system-03", + "date": "2026-06-10", + "summary": "order.pendingOrder.manualWaybill 新增可选参数 logistics_interface_name 与响应字段 business_key/logistics_interface_name,补充行为说明", + "methods": [ + "order.pendingOrder.manualWaybill" + ], + "notes": [ + "新增可选参数 logistics_interface_name(string,选填,trim 后为空则传 null)", + "响应新增字段 business_key(number):同一订单下从已有最大值 +1 递增,无记录时从 1 开始", + "响应新增字段 logistics_interface_name(string/null):写入的物流接口名称", + "补充 description 行为说明:完成后自动更新 wms_order_delivery_* 表的 print_status 和 post_status 为 'fin'", + "wms_order_express 表写入时 status 固定为 1,warehouse_id 从订单记录取" + ], + "type": "updated" + }, + { + "version": "2026.06.10-system-04", + "date": "2026-06-10", + "summary": "stock.warehouse.import 新增 barcode(条码)字段支持", + "methods": [ + "stock.warehouse.import" + ], + "notes": [ + "新增 barcode(条码)字段支持,支持别名:条码、bar_code、barCode、barcodeList、barcode_list、barcode。", + "条码字段支持数组格式(如 [\"6901234567890\"])和分号分隔字符串格式(如 \"6901234567890;6901234567891\")。", + "新建和更新路径均已支持条码导入,条码写入 wms_stock_barcodes 表。", + "仅同步文档,不修改业务代码或实现。" + ], + "type": "updated" + }, + { + "version": "2026.06.10-system-05", + "date": "2026-06-10", + "summary": "stock.warehouse.import 的 barcode 字段分隔符改为逗号,对齐 stock.warehouse.export 导出格式;仅接收字符串格式,不再支持数组", + "methods": [ + "stock.warehouse.import" + ], + "notes": [ + "barcode 字段分隔符从分号 ; 改为逗号 ,", + "barcode 字段仅接收字符串格式,不再支持数组格式", + "格式示例:\"6901234567890,6901234567891\",与 stock.warehouse.export 导出格式一致" + ], + "type": "modified" + }, + { + "version": "2026.06.13-system-01", + "date": "2026-06-13", + "summary": "setting.warehouse 的 auto_outbound_rules 新增 require_print 和 require_pick 两个可选条件字段(同步代码实现)", + "methods": [ + "setting.warehouse.getSettings", + "setting.warehouse.saveSettings" + ], + "notes": [ + "在 getSettings 响应和 saveSettings 入参中补充 subject_config.auto_outbound_rules 对象的完整字段文档(enabled、require_recheck、require_pack、require_weigh、require_sync、require_print、require_pick)。", + "require_print:是否要求已打印(print_status=fin),默认 true。", + "require_pick:是否要求已拣货(pick_status=fin),默认 true。", + "该规则由自动出库定时任务 order_auto_outbound 消费,全部开启的条件均满足时自动标记待出库。" + ], + "type": "updated" + }, + { + "version": "2026.06.13-system-02", + "date": "2026-06-13", + "summary": "order.recheckOrder.scanOrder 团购模式响应新增 orders_detail 字段,暴露非拦截订单的详细列表(含 is_printed、is_reviewed 等状态字段)", + "methods": [ + "order.recheckOrder.scanOrder" + ], + "notes": [ + "团购模式(list_type='group')波次视图项新增 orders_detail 字段:非拦截订单详细列表,每项含 order_id、delivery_order_code、waybill_no、pick_status、is_printed(print_status === 'fin')、is_reviewed(recheck_status === 'fin')、recheck_status、shop_nick、items_count、wave_index、intercept_status", + "orders_detail 与现有 order_ids(纯数字 ID 数组)并存,均在团购模式的波次视图项中返回", + "orders_detail 仅在 list_type='group' 时返回,散单模式不受影响", + "同步更新 list 字段 description 以反映 group 模式新增的 order_ids、orders_detail、stocks 字段" + ], + "type": "updated" + }, + { + "version": "2026.06.13-system-03", + "date": "2026-06-13", + "summary": "新增批量快捷复核接口 batchQuickRecheck,支持批量订单 IDs 的前置条件检查(储位、快递、同步、拦截),自动完成拣货并标记复核,支持部分失败。拣货完成后同步更新 wms_wave_pick_task 状态", + "methods": [ + "order.recheckOrder.batchQuickRecheck" + ], + "notes": [ + "新增 order.recheckOrder.batchQuickRecheck 方法", + "入参 ids 支持数组或逗号分隔字符串", + "响应包含 success/failed 列表及计数,failed 项含 reason 说明" + ], + "details": { + "description": "包含拣货任务状态同步:全部拣完→任务状态=2(已完成),未全拣完→任务状态推进为1(拣货中)" + }, + "type": "added" } ] diff --git a/methods/system.json b/methods/system.json index 087065e..0680d68 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1,8 +1,8 @@ { "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", - "version": "0.3.5", - "updatedAt": "2026-06-10", + "version": "0.3.6", + "updatedAt": "2026-06-13", "headers": [ { "name": "platform", @@ -294,7 +294,7 @@ }, { "method": "dashboard.order_trend", - "description": "dashboard.order_trend 接口", + "description": "订单趋势统计:按小时统计当日订单数与发货数,包含汇总信息(订单总数、发货总数、发货率、峰值时段)。数据来源于真实数据库查询,已废弃旧版 mock 数据。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -302,12 +302,106 @@ "name": "Authorization", "type": "string", "required": true, - "description": "Bearer token" + "description": "Bearer token,从中解析 warehouseId(仓库上下文)" } ], "params": [], - "response": [], - "errors": [] + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "业务状态码,200 表示成功" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "业务提示信息" + }, + { + "name": "data", + "type": "object", + "required": true, + "description": "成功时返回的趋势数据对象", + "children": [ + { + "name": "range", + "type": "string", + "required": true, + "description": "统计范围,固定为 'day'" + }, + { + "name": "date", + "type": "string", + "required": true, + "description": "统计日期,格式 YYYY-MM-DD" + }, + { + "name": "summary", + "type": "object", + "required": true, + "description": "汇总统计信息", + "children": [ + { + "name": "total_orders", + "type": "number", + "required": true, + "description": "当日订单总数(step in [1,2,3],排除 outbound_status='padding' 和 status='cancel' 的订单)" + }, + { + "name": "total_shipments", + "type": "number", + "required": true, + "description": "当日发货总数(dispatch_lane='m4' 的发货记录数)" + }, + { + "name": "shipment_rate", + "type": "number", + "required": true, + "description": "发货率百分比(total_shipments / total_orders × 100,保留一位小数)" + }, + { + "name": "peak_hour", + "type": "string", + "required": true, + "description": "订单峰值时段,格式 HH:00" + }, + { + "name": "peak_orders", + "type": "number", + "required": true, + "description": "峰值时段订单数" + } + ] + }, + { + "name": "categories", + "type": "array", + "required": true, + "description": "时段列表,从 08:00 到当前小时(最晚 23:00),格式 ['08:00', '09:00', ...]" + }, + { + "name": "orders", + "type": "array", + "required": true, + "description": "各时段订单数,与 categories 一一对应" + }, + { + "name": "shipments", + "type": "array", + "required": true, + "description": "各时段发货数,与 categories 一一对应" + } + ] + } + ], + "errors": [ + { + "code": "fail", + "message": "缺少仓库上下文(token 中未解析到有效的 warehouseId),返回 { flag: 'fail', message: '缺少仓库上下文' }" + } + ] } ] }, @@ -4820,88 +4914,6 @@ "message": "task_id 参数不能为空" } ] - }, - { - "method": "order.pendingOrder.manualWaybill", - "description": "手工录入运单号。为指定待处理订单创建一条运单记录(wms_order_express 表),仅允许 step 在 [1,2,3] 且 outbound_status 不为 'padding' 的订单操作。", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "order_id", - "type": "number", - "required": true, - "source": "body", - "description": "订单 ID,必须为正整数" - }, - { - "name": "waybill_code", - "type": "string", - "required": true, - "source": "body", - "description": "运单号,非空字符串" - } - ], - "response": [ - { - "name": "id", - "type": "number", - "required": true, - "description": "创建的运单记录 ID" - }, - { - "name": "order_id", - "type": "number", - "required": true, - "description": "订单 ID" - }, - { - "name": "waybill_code", - "type": "string", - "required": true, - "description": "运单号" - }, - { - "name": "create_at", - "type": "string", - "required": true, - "description": "创建时间" - } - ], - "errors": [ - { - "code": 400, - "message": "order_id 必须为正整数" - }, - { - "code": 400, - "message": "waybill_code(运单号)不能为空" - }, - { - "code": 400, - "message": "订单不存在或不属于当前仓库" - }, - { - "code": 400, - "message": "订单当前步骤不在允许范围,仅允许待处理状态(step 1/2/3)的订单手工录入运单号" - }, - { - "code": 400, - "message": "订单已标记待出库,不允许手工录入运单号" - }, - { - "code": 500, - "message": "内部错误:OrderExpress 模型未加载或数据库写入失败" - } - ] } ] }, @@ -5026,7 +5038,7 @@ "name": "list", "type": "array", "required": true, - "description": "统一列表输出。散单模式(list_type=single)有波次信息时:扁平订单数组;无波次信息时退回单订单详情模式(每项含 detail、items、expresses、logs)。团购模式(list_type=group):波次视图数组(每项含 wave_id、wave_no、wave_type、wave_status、total_orders、processed_orders、creator、create_time、update_time、order_count、pick_mode、box_no、orders[])", + "description": "统一列表输出。散单模式(list_type=single)有波次信息时:扁平订单数组;无波次信息时退回单订单详情模式(每项含 detail、items、expresses、logs)。团购模式(list_type=group):波次视图数组(每项含 wave_id、wave_no、wave_type、wave_status、total_orders、processed_orders、creator、create_time、update_time、order_count、pick_mode、box_no、order_ids、orders_detail、stocks[])", "children": [ { "name": "order_id", @@ -5245,6 +5257,73 @@ "type": "number", "description": "[团购波次项] 箱号(来自 wms_wave_pick_task_wave.box_no)" }, + { + "name": "order_ids", + "type": "array", + "description": "[团购波次项] 非拦截订单 ID 数组,仅 list_type='group' 时返回" + }, + { + "name": "orders_detail", + "type": "array", + "description": "[团购波次项] 非拦截订单详细列表,每项含 order_id、delivery_order_code、waybill_no、pick_status、is_printed、is_reviewed、recheck_status、shop_nick、items_count、wave_index、intercept_status,仅 list_type='group' 时返回", + "children": [ + { + "name": "order_id", + "type": "number", + "description": "订单ID" + }, + { + "name": "delivery_order_code", + "type": "string", + "description": "发货单号" + }, + { + "name": "waybill_no", + "type": "string", + "description": "运单号" + }, + { + "name": "pick_status", + "type": "string", + "description": "拣货状态" + }, + { + "name": "is_printed", + "type": "boolean", + "description": "是否已打印(print_status === 'fin')" + }, + { + "name": "is_reviewed", + "type": "boolean", + "description": "是否已复核(recheck_status === 'fin')" + }, + { + "name": "recheck_status", + "type": "string", + "description": "复核状态" + }, + { + "name": "shop_nick", + "type": "string", + "description": "店铺昵称" + }, + { + "name": "items_count", + "type": "number", + "description": "商品种类数" + }, + { + "name": "wave_index", + "type": "number", + "description": "波次内序号" + }, + { + "name": "intercept_status", + "type": "string", + "description": "拦截状态(requested / intercepted_at_warehouse / 空字符串)" + } + ] + }, { "name": "orders", "type": "array", @@ -5818,6 +5897,90 @@ "message": "未找到对应拣货任务" } ] + }, + { + "method": "order.recheckOrder.batchQuickRecheck", + "description": "批量快捷复核:传入订单 IDs 列表,对每个有效订单执行前置检查(已分配储位、已分配快递、已同步且未被拦截),必要时自动完成拣货(含库存锁定校验与扣减、库存流水写入、拣货任务状态同步)后标记复核(含复核任务记录、任务复核状态更新、车任务解绑、操作日志)。每个订单在独立事务中执行,支持部分失败,不满足条件的订单跳过并返回原因。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids", + "type": "array|string", + "required": true, + "source": "body|query", + "description": "订单 ID 列表,支持数组或以逗号分隔的字符串" + } + ], + "response": [ + { + "name": "success", + "type": "array", + "required": true, + "description": "复核成功的订单列表", + "children": [ + { + "name": "order_id", + "type": "number", + "description": "订单ID" + }, + { + "name": "delivery_order_code", + "type": "string", + "description": "发货单号" + } + ] + }, + { + "name": "failed", + "type": "array", + "required": true, + "description": "复核失败的订单列表", + "children": [ + { + "name": "order_id", + "type": "number", + "description": "订单ID" + }, + { + "name": "delivery_order_code", + "type": "string", + "description": "发货单号" + }, + { + "name": "reason", + "type": "string", + "description": "失败原因(未分配储位 / 没有分配快递 / 没有同步 / 已拦截 / 未找到对应订单 / 复核失败: xxx)" + } + ] + }, + { + "name": "success_count", + "type": "number", + "required": true, + "description": "成功数量" + }, + { + "name": "failed_count", + "type": "number", + "required": true, + "description": "失败数量" + } + ], + "errors": [ + { + "code": 400, + "message": "订单ID列表不能为空" + } + ] } ] }, @@ -12313,6 +12476,54 @@ "type": "boolean", "required": true, "description": "是否启用外部快递编码;默认 false(关闭)。开启后允许按外部系统传入的快递编码进行处理(如无匹配仍以业务校验为准)" + }, + { + "name": "subject_config.auto_outbound_rules", + "type": "object", + "required": true, + "description": "自动出库规则配置。全部条件满足时自动标记待出库" + }, + { + "name": "subject_config.auto_outbound_rules.enabled", + "type": "boolean", + "required": true, + "description": "是否启用自动出库,默认 false" + }, + { + "name": "subject_config.auto_outbound_rules.require_recheck", + "type": "boolean", + "required": true, + "description": "是否要求已复核(recheck_status=fin),默认 true" + }, + { + "name": "subject_config.auto_outbound_rules.require_pack", + "type": "boolean", + "required": true, + "description": "是否要求已打包(pack_status=fin),默认 true" + }, + { + "name": "subject_config.auto_outbound_rules.require_weigh", + "type": "boolean", + "required": true, + "description": "是否要求已称重(weighing_weight>0),默认 true" + }, + { + "name": "subject_config.auto_outbound_rules.require_sync", + "type": "boolean", + "required": true, + "description": "是否要求已同步(sync_status=fin),默认 true" + }, + { + "name": "subject_config.auto_outbound_rules.require_print", + "type": "boolean", + "required": true, + "description": "是否要求已打印(print_status=fin),默认 true" + }, + { + "name": "subject_config.auto_outbound_rules.require_pick", + "type": "boolean", + "required": true, + "description": "是否要求已拣货(pick_status=fin),默认 true" } ], "errors": [ @@ -12451,6 +12662,62 @@ "required": false, "source": "body.subject_config", "description": "是否启用外部快递编码;默认 false(关闭)。开启后允许按外部系统传入的快递编码进行处理(如无匹配仍以业务校验为准)" + }, + { + "name": "subject_config.auto_outbound_rules", + "type": "object", + "required": false, + "source": "body.subject_config", + "description": "自动出库规则配置。全部条件满足时自动标记待出库" + }, + { + "name": "subject_config.auto_outbound_rules.enabled", + "type": "boolean", + "required": false, + "source": "body.subject_config.auto_outbound_rules", + "description": "是否启用自动出库,默认 false" + }, + { + "name": "subject_config.auto_outbound_rules.require_recheck", + "type": "boolean", + "required": false, + "source": "body.subject_config.auto_outbound_rules", + "description": "是否要求已复核(recheck_status=fin),默认 true" + }, + { + "name": "subject_config.auto_outbound_rules.require_pack", + "type": "boolean", + "required": false, + "source": "body.subject_config.auto_outbound_rules", + "description": "是否要求已打包(pack_status=fin),默认 true" + }, + { + "name": "subject_config.auto_outbound_rules.require_weigh", + "type": "boolean", + "required": false, + "source": "body.subject_config.auto_outbound_rules", + "description": "是否要求已称重(weighing_weight>0),默认 true" + }, + { + "name": "subject_config.auto_outbound_rules.require_sync", + "type": "boolean", + "required": false, + "source": "body.subject_config.auto_outbound_rules", + "description": "是否要求已同步(sync_status=fin),默认 true" + }, + { + "name": "subject_config.auto_outbound_rules.require_print", + "type": "boolean", + "required": false, + "source": "body.subject_config.auto_outbound_rules", + "description": "是否要求已打印(print_status=fin),默认 true" + }, + { + "name": "subject_config.auto_outbound_rules.require_pick", + "type": "boolean", + "required": false, + "source": "body.subject_config.auto_outbound_rules", + "description": "是否要求已拣货(pick_status=fin),默认 true" } ], "response": [ @@ -14677,7 +14944,7 @@ }, { "method": "stock.warehouse.import", - "description": "批量导入或更新仓库商品。请求体优先直接传入商品数据数组 JSON(主方式为数组);也兼容以 rows/items/list/data 包装。每项仅需包含商品相关字段;当 SKU 为空时创建新商品,SKU 非空时为更新操作;更新会写操作日志以便审计。未传 store_id 时默认使用当前上下文仓库/主体(ctx.user.store_id)。", + "description": "批量导入或更新仓库商品。请求体优先直接传入商品数据数组 JSON(主方式为数组);也兼容以 rows/items/list/data 包装。每项仅需包含商品相关字段;当 SKU 为空时创建新商品,SKU 非空时为更新操作;更新会写操作日志以便审计。未传 store_id 时默认使用当前上下文仓库/主体(ctx.user.store_id)。支持导入条码(barcode),新建和更新均生效,条码写入 wms_stock_barcodes 表。", "isNeedAuth": true, "isNeedLogin": true, "headers": [ @@ -14741,6 +15008,12 @@ "type": "number", "description": "零售价" }, + { + "name": "条码 / bar_code / barCode / barcodeList / barcode_list / barcode", + "type": "string", + "required": false, + "description": "条码列表,逗号分隔字符串,如 \"6901234567890,6901234567891\"。与导出格式一致。新建和更新均支持,条码存储在 wms_stock_barcodes 表。" + }, { "name": "store_id / storeId", "type": "number", @@ -14755,55 +15028,62 @@ { "name": "total_count", "type": "number", + "required": true, "description": "解析到的总条目数" }, { "name": "created_count", "type": "number", + "required": true, "description": "成功创建的新商品数" }, { "name": "updated_count", "type": "number", + "required": true, "description": "成功更新的商品数" }, { "name": "fail_count", "type": "number", + "required": true, "description": "导入失败数" }, { "name": "created_ids", "type": "array", + "required": true, "description": "创建成功的商品 ID 列表" }, { "name": "updated_ids", "type": "array", + "required": true, "description": "更新成功的商品 ID 列表" }, { "name": "fail_items", "type": "array", + "required": true, "description": "失败项明细数组,每项包含原始输入与错误信息" } ], "errors": [ { "code": "400", - "description": "导入数据不能为空" + "message": "导入数据不能为空" }, { "code": "400", - "description": "缺少仓库上下文" + "message": "缺少仓库上下文" }, { "code": "400", - "description": "导入行数据无效" + "message": "导入行数据无效" }, { "code": "500", - "description": "导入失败" + "message": "导入失败" } ] }, @@ -21922,7 +22202,7 @@ ] }, { - "groupName": "订单模块", + "groupName": "订单待处理模块", "module": "order", "list": [ { @@ -22027,6 +22307,107 @@ } ], "errors": [] + }, + { + "method": "order.pendingOrder.manualWaybill", + "description": "手工录入运单号。为指定待处理订单创建一条运单记录(wms_order_express 表),仅允许 step 在 [1,2,3] 且 outbound_status 不为 'padding' 的订单操作。完成后自动更新订单表的 print_status 与 post_status 为 'fin',表示外部已打印。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "order_id", + "type": "number", + "required": true, + "source": "body", + "description": "订单 ID,必须为正整数" + }, + { + "name": "waybill_code", + "type": "string", + "required": true, + "source": "body", + "description": "运单号,非空字符串" + }, + { + "name": "logistics_interface_name", + "type": "string", + "required": false, + "source": "body", + "description": "物流接口名称(选填),手工填入的值,trim 后为空则传 null" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "创建的运单记录 ID" + }, + { + "name": "order_id", + "type": "number", + "required": true, + "description": "订单 ID" + }, + { + "name": "waybill_code", + "type": "string", + "required": true, + "description": "运单号" + }, + { + "name": "business_key", + "type": "number", + "required": true, + "description": "递增的业务键,同一订单下从 1 开始递增" + }, + { + "name": "logistics_interface_name", + "type": "string", + "required": false, + "description": "写入的物流接口名称,未传时为 null" + }, + { + "name": "create_at", + "type": "string", + "required": true, + "description": "创建时间" + } + ], + "errors": [ + { + "code": 400, + "message": "order_id 必须为正整数" + }, + { + "code": 400, + "message": "waybill_code(运单号)不能为空" + }, + { + "code": 400, + "message": "订单不存在或不属于当前仓库" + }, + { + "code": 400, + "message": "订单当前步骤不在允许范围,仅允许待处理状态(step 1/2/3)的订单手工录入运单号" + }, + { + "code": 400, + "message": "订单已标记待出库,不允许手工录入运单号" + }, + { + "code": 500, + "message": "内部错误:OrderExpress 模型未加载或数据库写入失败" + } + ] } ] }, diff --git a/scripts/check_tables.js b/scripts/check_tables.js new file mode 100644 index 0000000..3519c84 --- /dev/null +++ b/scripts/check_tables.js @@ -0,0 +1,31 @@ +'use strict'; +const mysql = require('mysql2/promise'); + +(async () => { + const conn = await mysql.createConnection({host:'127.0.0.1',port:3307,user:'wms',password:'dspxmRwRdRbWtbm7',database:'wms'}); + + const [tables] = await conn.query("SHOW TABLES LIKE 'wms_order_delivery%'"); + console.log('order_delivery tables:'); + tables.forEach(t => console.log(' ', Object.values(t)[0])); + + const [tables2] = await conn.query("SHOW TABLES LIKE '%recheck%'"); + console.log('recheck tables:'); + tables2.forEach(t => console.log(' ', Object.values(t)[0])); + + const [tables3] = await conn.query("SHOW TABLES LIKE '%wave%'"); + console.log('wave tables:'); + tables3.forEach(t => console.log(' ', Object.values(t)[0])); + + // Check the current model table for warehouse 100000 + console.log('\nChecking wms_order_delivery for recheck_status:'); + try { + const [rows] = await conn.query("SELECT * FROM wms_order_delivery WHERE warehouse_id = 100000 LIMIT 1"); + if (rows.length > 0) { + console.log('Keys:', Object.keys(rows[0]).join(', ')); + } + } catch(e) { + console.log('Error:', e.message); + } + + await conn.end(); +})().catch(e => console.error(e.message)); diff --git a/scripts/query_more_test_orders.js b/scripts/query_more_test_orders.js new file mode 100644 index 0000000..820d49c --- /dev/null +++ b/scripts/query_more_test_orders.js @@ -0,0 +1,50 @@ +'use strict'; +const mysql = require('mysql2/promise'); +const DB_CONFIG = {host:'127.0.0.1',port:3307,user:'wms',password:'dspxmRwRdRbWtbm7',database:'wms'}; +const TABLE = 'wms_order_delivery_100000'; + +(async () => { + const conn = await mysql.createConnection(DB_CONFIG); + try { + // More success candidates: pick_status = 'fin' AND recheck_status != 'fin' + console.log('=== 已拣货未复核 ==='); + const [r1] = await conn.query( + `SELECT id, delivery_order_code, pick_status, recheck_status, wave_id + FROM ${TABLE} + WHERE storage_status='fin' AND post_status='fin' AND status='created' + AND intercept_status NOT IN ('intercepted','intercepted_at_warehouse') + AND pick_status='fin' AND recheck_status!='fin' + ORDER BY id DESC LIMIT 5` + ); + r1.forEach(r => console.log(` ID:${r.id} pick="${r.pick_status}" recheck="${r.recheck_status}" wave_id:${r.wave_id}`)); + console.log(` 共 ${r1.length} 条\n`); + + // Also check: pick_status='none' (未拣货未复核) + console.log('=== 未拣货未复核 (pick_status=none) ==='); + const [r2] = await conn.query( + `SELECT id, delivery_order_code, pick_status, recheck_status + FROM ${TABLE} + WHERE storage_status='fin' AND post_status='fin' AND status='created' + AND intercept_status NOT IN ('intercepted','intercepted_at_warehouse') + AND pick_status='none' AND recheck_status!='fin' + ORDER BY id DESC LIMIT 5` + ); + r2.forEach(r => console.log(` ID:${r.id} pick="${r.pick_status}" recheck="${r.recheck_status}"`)); + console.log(` 共 ${r2.length} 条\n`); + + // Other pick statuses + console.log('=== 其他拣货状态未复核 ==='); + const [r3] = await conn.query( + `SELECT id, delivery_order_code, pick_status, recheck_status + FROM ${TABLE} + WHERE storage_status='fin' AND post_status='fin' AND status='created' + AND intercept_status NOT IN ('intercepted','intercepted_at_warehouse') + AND pick_status NOT IN ('fin','none') AND recheck_status!='fin' + ORDER BY id DESC LIMIT 5` + ); + r3.forEach(r => console.log(` ID:${r.id} pick="${r.pick_status}" recheck="${r.recheck_status}"`)); + console.log(` 共 ${r3.length} 条\n`); + + await conn.end(); + } catch(e) { console.error(e.message); await conn.end(); } +})(); diff --git a/scripts/query_test_orders.js b/scripts/query_test_orders.js new file mode 100644 index 0000000..34df2c1 --- /dev/null +++ b/scripts/query_test_orders.js @@ -0,0 +1,168 @@ +'use strict'; + +// 查询 wms_order_delivery 表的测试数据 +const mysql = require('mysql2/promise'); + +const DB_CONFIG = { + host: '127.0.0.1', + port: 3307, + user: 'wms', + password: 'dspxmRwRdRbWtbm7', + database: 'wms', +}; + +const WAREHOUSE_ID = 100000; + +async function queryTestOrders() { + const conn = await mysql.createConnection(DB_CONFIG); + + try { + console.log('='.repeat(80)); + console.log('【成功用例候选】满足所有前置条件的订单(未复核):'); + console.log('-'.repeat(80)); + + const [successRows] = await conn.query( + `SELECT id, delivery_order_code, pre_delivery_order_code, + storage_status, post_status, status, intercept_status, + pick_status, recheck_status, wave_id, wave_no + FROM wms_order_delivery + WHERE warehouse_id = ? + AND storage_status = 'fin' + AND post_status = 'fin' + AND status = 'created' + AND intercept_status NOT IN ('intercepted', 'intercepted_at_warehouse') + AND recheck_status != 'fin' + ORDER BY pick_status ASC, id DESC + LIMIT 10`, + [WAREHOUSE_ID] + ); + + for (const row of successRows) { + console.log(` ID: ${row.id}`); + console.log(` delivery_order_code: ${row.delivery_order_code || row.pre_delivery_order_code}`); + console.log(` storage_status: ${row.storage_status}, post_status: ${row.post_status}, status: ${row.status}`); + console.log(` intercept_status: ${row.intercept_status}, pick_status: ${row.pick_status}, recheck_status: ${row.recheck_status}`); + console.log(` wave_id: ${row.wave_id}, wave_no: ${row.wave_no}`); + console.log(); + } + console.log(` 共 ${successRows.length} 条`); + console.log(); + + console.log('='.repeat(80)); + console.log('【失败用例候选 - storage_status != fin】未分配储位:'); + console.log('-'.repeat(80)); + + const [noStorageRows] = await conn.query( + `SELECT id, delivery_order_code, pre_delivery_order_code, + storage_status, post_status, status, intercept_status, + pick_status, recheck_status + FROM wms_order_delivery + WHERE warehouse_id = ? + AND storage_status != 'fin' + AND (post_status = 'fin' OR 1=1) + ORDER BY id DESC + LIMIT 3`, + [WAREHOUSE_ID] + ); + + for (const row of noStorageRows) { + console.log(` ID: ${row.id} storage_status="${row.storage_status}" delivery_order_code="${row.delivery_order_code || row.pre_delivery_order_code}"`); + } + console.log(` 共 ${noStorageRows.length} 条`); + console.log(); + + console.log('='.repeat(80)); + console.log('【失败用例候选 - post_status != fin】未分配快递:'); + console.log('-'.repeat(80)); + + const [noPostRows] = await conn.query( + `SELECT id, delivery_order_code, pre_delivery_order_code, + storage_status, post_status, status, intercept_status, + pick_status, recheck_status + FROM wms_order_delivery + WHERE warehouse_id = ? + AND post_status != 'fin' + AND storage_status = 'fin' + ORDER BY id DESC + LIMIT 3`, + [WAREHOUSE_ID] + ); + + for (const row of noPostRows) { + console.log(` ID: ${row.id} post_status="${row.post_status}" delivery_order_code="${row.delivery_order_code || row.pre_delivery_order_code}"`); + } + console.log(` 共 ${noPostRows.length} 条`); + console.log(); + + console.log('='.repeat(80)); + console.log('【失败用例候选 - status != created】未同步:'); + console.log('-'.repeat(80)); + + const [noSyncRows] = await conn.query( + `SELECT id, delivery_order_code, pre_delivery_order_code, + storage_status, post_status, status, intercept_status, + pick_status, recheck_status + FROM wms_order_delivery + WHERE warehouse_id = ? + AND status != 'created' + AND storage_status = 'fin' + AND post_status = 'fin' + ORDER BY id DESC + LIMIT 3`, + [WAREHOUSE_ID] + ); + + for (const row of noSyncRows) { + console.log(` ID: ${row.id} status="${row.status}" delivery_order_code="${row.delivery_order_code || row.pre_delivery_order_code}"`); + } + console.log(` 共 ${noSyncRows.length} 条`); + console.log(); + + console.log('='.repeat(80)); + console.log('【失败用例候选 - 已拦截】:'); + console.log('-'.repeat(80)); + + const [interceptedRows] = await conn.query( + `SELECT id, delivery_order_code, pre_delivery_order_code, + storage_status, post_status, status, intercept_status, + pick_status, recheck_status + FROM wms_order_delivery + WHERE warehouse_id = ? + AND intercept_status IN ('intercepted', 'intercepted_at_warehouse') + ORDER BY id DESC + LIMIT 3`, + [WAREHOUSE_ID] + ); + + for (const row of interceptedRows) { + console.log(` ID: ${row.id} intercept_status="${row.intercept_status}" delivery_order_code="${row.delivery_order_code || row.pre_delivery_order_code}"`); + } + console.log(` 共 ${interceptedRows.length} 条`); + console.log(); + + // 输出 JSON 汇总用于脚本 + console.log('='.repeat(80)); + console.log('=== JSON_SUMMARY ==='); + console.log(JSON.stringify({ + success: successRows.map(r => ({ + id: r.id, + code: r.delivery_order_code || r.pre_delivery_order_code, + pick_status: r.pick_status, + recheck_status: r.recheck_status, + pick_is_fin: r.pick_status === 'fin', + })), + noStorage: noStorageRows.map(r => ({ id: r.id, storage_status: r.storage_status })), + noPost: noPostRows.map(r => ({ id: r.id, post_status: r.post_status })), + noSync: noSyncRows.map(r => ({ id: r.id, status: r.status })), + intercepted: interceptedRows.map(r => ({ id: r.id, intercept_status: r.intercept_status })), + }, null, 2)); + + } finally { + await conn.end(); + } +} + +queryTestOrders().catch(err => { + console.error('查询失败:', err.message); + process.exit(1); +}); diff --git a/scripts/query_test_orders_v2.js b/scripts/query_test_orders_v2.js new file mode 100644 index 0000000..af28361 --- /dev/null +++ b/scripts/query_test_orders_v2.js @@ -0,0 +1,98 @@ +'use strict'; +const mysql = require('mysql2/promise'); + +const DB_CONFIG = { + host: '127.0.0.1', port: 3307, + user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms', +}; +const TABLE = 'wms_order_delivery_100000'; + +async function main() { + const conn = await mysql.createConnection(DB_CONFIG); + + try { + console.log('='.repeat(80)); + console.log('【成功用例候选】满足所有前置条件的订单(未复核):'); + console.log('-'.repeat(80)); + + const [successRows] = await conn.query( + `SELECT id, delivery_order_code, pre_delivery_order_code, + storage_status, post_status, status, intercept_status, + pick_status, recheck_status, wave_id, wave_no + FROM ${TABLE} + WHERE storage_status = 'fin' + AND post_status = 'fin' + AND status = 'created' + AND intercept_status NOT IN ('intercepted', 'intercepted_at_warehouse') + AND recheck_status != 'fin' + ORDER BY pick_status ASC, id DESC + LIMIT 10` + ); + + for (const row of successRows) { + console.log(` ID: ${row.id} pick="${row.pick_status}" recheck="${row.recheck_status}"`); + console.log(` code: ${row.delivery_order_code || row.pre_delivery_order_code || ''}`); + console.log(` wave_id: ${row.wave_id}, wave_no: ${row.wave_no}`); + } + console.log(` 共 ${successRows.length} 条`); + console.log(); + + console.log('='.repeat(80)); + console.log('【失败用例候选 - storage_status != fin】'); + const [noStorageRows] = await conn.query( + `SELECT id, delivery_order_code, storage_status FROM ${TABLE} WHERE storage_status != 'fin' ORDER BY id DESC LIMIT 3` + ); + noStorageRows.forEach(r => console.log(` ID: ${r.id} storage_status="${r.storage_status}"`)); + console.log(` 共 ${noStorageRows.length} 条`); + console.log(); + + console.log('='.repeat(80)); + console.log('【失败用例候选 - post_status != fin】'); + const [noPostRows] = await conn.query( + `SELECT id, delivery_order_code, post_status FROM ${TABLE} WHERE post_status != 'fin' AND storage_status = 'fin' ORDER BY id DESC LIMIT 3` + ); + noPostRows.forEach(r => console.log(` ID: ${r.id} post_status="${r.post_status}"`)); + console.log(` 共 ${noPostRows.length} 条`); + console.log(); + + console.log('='.repeat(80)); + console.log('【失败用例候选 - status != created】'); + const [noSyncRows] = await conn.query( + `SELECT id, delivery_order_code, status FROM ${TABLE} WHERE status != 'created' AND storage_status = 'fin' AND post_status = 'fin' ORDER BY id DESC LIMIT 3` + ); + noSyncRows.forEach(r => console.log(` ID: ${r.id} status="${r.status}"`)); + console.log(` 共 ${noSyncRows.length} 条`); + console.log(); + + console.log('='.repeat(80)); + console.log('【失败用例候选 - 已拦截】'); + const [interceptedRows] = await conn.query( + `SELECT id, delivery_order_code, intercept_status FROM ${TABLE} WHERE intercept_status IN ('intercepted','intercepted_at_warehouse') ORDER BY id DESC LIMIT 3` + ); + interceptedRows.forEach(r => console.log(` ID: ${r.id} intercept_status="${r.intercept_status}"`)); + console.log(` 共 ${interceptedRows.length} 条`); + console.log(); + + console.log('===JSON_SUMMARY==='); + console.log(JSON.stringify({ + success: successRows.map(r => ({ + id: r.id, + code: r.delivery_order_code || r.pre_delivery_order_code || '', + pick_status: r.pick_status, + pick_is_fin: r.pick_status === 'fin', + recheck_status: r.recheck_status, + wave_id: r.wave_id, + wave_no: r.wave_no, + })), + noStorage: noStorageRows.map(r => ({ id: r.id, storage_status: r.storage_status })), + noPost: noPostRows.map(r => ({ id: r.id, post_status: r.post_status })), + noSync: noSyncRows.map(r => ({ id: r.id, status: r.status })), + intercepted: interceptedRows.map(r => ({ id: r.id, intercept_status: r.intercept_status })), + }, null, 2)); + + } finally { + await conn.end(); + } +} + +main().catch(e => { console.error('Query failed:', e.message); process.exit(1); }); diff --git a/scripts/test_batch_quick_recheck.js b/scripts/test_batch_quick_recheck.js new file mode 100644 index 0000000..688d5e5 --- /dev/null +++ b/scripts/test_batch_quick_recheck.js @@ -0,0 +1,169 @@ +'use strict'; +// batchQuickRecheck 接口真实流程测试脚本 +const TOKEN = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJsaXVmdW1pbmdyZW4iLCJyZWFsX25hbWUiOiLliJjku5jmmI7ku4EiLCJwbGF0Zm9ybV9jb2RlIjoid2ViIiwiY3VycmVudF9yb2xlX2lkIjo0LCJjdXJyZW50X3N0b3JlX2lkIjoxMDAwMDAsImlhdCI6MTc4MTM2MDk3MiwiZXhwIjoxNzgxMzc1MzcyfQ.u0svJXHuk8RdlM8ObhDMlRj07gWQzS8Y_41dPcBDtc0'; +const BASE_URL = 'http://127.0.0.1:6060'; +const TABLE = 'wms_order_delivery_100000'; +const mysql = require('mysql2/promise'); +const DB_CONFIG = {host:'127.0.0.1',port:3307,user:'wms',password:'dspxmRwRdRbWtbm7',database:'wms'}; + +async function getOrderSnapshot(conn, ids) { + if (!ids.length) return {}; + const [rows] = await conn.query( + `SELECT id, pick_status, recheck_status, storage_status, post_status, status, intercept_status + FROM ${TABLE} WHERE id IN (?)`, [ids] + ); + const map = {}; + rows.forEach(r => { map[r.id] = r; }); + return map; +} + +async function callApi(ids) { + const ts = Math.floor(Date.now() / 1000); + const url = `${BASE_URL}/system?method=order.recheckOrder.batchQuickRecheck&v=1.0×tamp=${ts}`; + const headers = { + 'platform': 'web', + 'project': 'wms', + 'Content-Type': 'application/json; charset=utf-8', + 'Authorization': `Bearer ${TOKEN}`, + }; + const body = JSON.stringify({ + module: 'order.recheckOrder', + method: 'batchQuickRecheck', + params: { ids }, + }); + + const response = await fetch(url, { method: 'POST', headers, body }); + const text = await response.text(); + let json; + try { json = JSON.parse(text); } catch { json = { raw: text }; } + return { status: response.status, body: json }; +} + +async function runTestCase(name, ids, expectedDesc) { + console.log(`\n${'='.repeat(60)}`); + console.log(`【${name}】`); + console.log(` 输入IDs: [${ids.join(', ')}]`); + console.log(` 预期: ${expectedDesc}`); + + const conn = await mysql.createConnection(DB_CONFIG); + let beforeSnapshot = {}; + let afterSnapshot = {}; + + try { + // 测试前快照 + beforeSnapshot = await getOrderSnapshot(conn, ids); + console.log(' 测试前状态:'); + for (const [id, snap] of Object.entries(beforeSnapshot)) { + console.log(` ID ${id}: pick="${snap.pick_status}" recheck="${snap.recheck_status}" storage="${snap.storage_status}" post="${snap.post_status}" status="${snap.status}" intercept="${snap.intercept_status}"`); + } + + // 调用 API + const result = await callApi(ids); + console.log(` HTTP Status: ${result.status}`); + console.log(` 返回结果: ${JSON.stringify(result.body, null, 2)}`); + + // 结果校验 + const data = result.body && result.body.data; + const passed = result.status === 200 && data; + + // 测试后快照 + afterSnapshot = await getOrderSnapshot(conn, ids); + console.log(' 测试后状态:'); + for (const [id, snap] of Object.entries(afterSnapshot)) { + const before = beforeSnapshot[id] || {}; + const changes = []; + if (snap.pick_status !== before.pick_status) changes.push(`pick: ${before.pick_status}→${snap.pick_status}`); + if (snap.recheck_status !== before.recheck_status) changes.push(`recheck: ${before.recheck_status}→${snap.recheck_status}`); + const changeStr = changes.length ? ` [变更: ${changes.join(', ')}]` : ' [无变更]'; + console.log(` ID ${id}: pick="${snap.pick_status}" recheck="${snap.recheck_status}"${changeStr}`); + } + + return { name, passed, result: data, beforeSnapshot, afterSnapshot, ids }; + } catch (e) { + console.log(` 异常: ${e.message}`); + return { name, passed: false, error: e.message, ids }; + } finally { + await conn.end(); + } +} + +async function main() { + console.log('batchQuickRecheck 接口真实流程测试'); + console.log(`测试时间: ${new Date().toISOString()}`); + console.log(`目标表: ${TABLE}`); + console.log(`Base URL: ${BASE_URL}`); + + const results = []; + + // 用例1: 全成功-含未拣货(1个有效订单) + results.push(await runTestCase( + '用例1: 全成功-含未拣货', + [120946], + 'pick_status=none → 自动完成拣货+复核, 全部 success' + )); + + // 用例2: 全失败-无储位 + results.push(await runTestCase( + '用例2: 全失败-无储位', + [120947, 120939], + '全部 failed, reason="未分配储位"' + )); + + // 用例3: 全失败-无快递 + results.push(await runTestCase( + '用例3: 全失败-无快递', + [120944, 120943], + '全部 failed, reason="没有分配快递"' + )); + + // 用例4: 全失败-未同步 + results.push(await runTestCase( + '用例4: 全失败-未同步', + [120858, 120857], + '全部 failed, reason="没有同步"' + )); + + // 用例5: 全失败-已拦截 + results.push(await runTestCase( + '用例5: 全失败-已拦截', + [120945], + '全部 failed, reason="已拦截"' + )); + + // 用例6: 部分失败-混合 + results.push(await runTestCase( + '用例6: 部分失败-混合', + [120946, 120947, 999999999], + 'success 和 failed 各有' + )); + + // 用例7: 空列表 + results.push(await runTestCase( + '用例7: 空列表', + [], + '400 错误 "订单ID列表不能为空"' + )); + + // 用例8: 不存在ID + results.push(await runTestCase( + '用例8: 不存在ID', + [999999999], + '全部 failed, reason="未找到对应订单"' + )); + + // 汇总 + console.log(`\n${'='.repeat(60)}`); + console.log('测试汇总'); + console.log('='.repeat(60)); + const passCount = results.filter(r => r.passed).length; + const failCount = results.filter(r => !r.passed).length; + console.log(`总用例数: ${results.length}`); + console.log(`通过: ${passCount}`); + console.log(`失败: ${failCount}`); + + for (const r of results) { + console.log(` [${r.passed ? 'PASS' : 'FAIL'}] ${r.name}`); + } +} + +main().catch(e => { console.error('测试脚本异常:', e.message); process.exit(1); }); diff --git a/scripts/test_batch_quick_recheck_full.js b/scripts/test_batch_quick_recheck_full.js new file mode 100644 index 0000000..38db52a --- /dev/null +++ b/scripts/test_batch_quick_recheck_full.js @@ -0,0 +1,420 @@ +'use strict'; +/** + * batchQuickRecheck 接口完整真实流程测试 + * 测试时间: 2026-06-13 + * 测试仓库: 100000 + * 测试货主: 1000000 + * 目标: 验证 batchQuickRecheck 接口的 7 个测试用例 + */ + +const mysql = require('mysql2/promise'); +const DB = { host: '127.0.0.1', port: 3307, user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms' }; +const BASE_URL = 'http://127.0.0.1:6060'; +const TOKEN = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJsaXVmdW1pbmdyZW4iLCJyZWFsX25hbWUiOiLliJjku5jmmI7ku4EiLCJwbGF0Zm9ybV9jb2RlIjoid2ViIiwiY3VycmVudF9yb2xlX2lkIjo0LCJjdXJyZW50X3N0b3JlX2lkIjoxMDAwMDAsImlhdCI6MTc4MTM2MDk3MiwiZXhwIjoxNzgxMzc1MzcyfQ.u0svJXHuk8RdlM8ObhDMlRj07gWQzS8Y_41dPcBDtc0'; +const TABLE = 'wms_order_delivery_100000'; + +// ========== 工具函数 ========== + +let conn = null; + +async function getConn() { + if (!conn) conn = await mysql.createConnection(DB); + return conn; +} + +async function closeConn() { + if (conn) { await conn.end(); conn = null; } +} + +async function getOrderSnapshot(ids) { + const c = await getConn(); + if (!ids.length) return {}; + const [rows] = await c.query( + `SELECT id, delivery_order_code, pre_delivery_order_code, + pick_status, recheck_status, storage_status, post_status, status, intercept_status + FROM ${TABLE} WHERE id IN (?)`, [ids] + ); + const map = {}; + rows.forEach(r => { map[r.id] = r; }); + return map; +} + +async function getStorageSnapshot(ids) { + const c = await getConn(); + if (!ids.length) return {}; + const [rows] = await c.query( + 'SELECT id, quantity, locked_quantity FROM wms_storage WHERE id IN (?) AND warehouse_id = 100000', [ids] + ); + const map = {}; + rows.forEach(r => { map[r.id] = r; }); + return map; +} + +async function callApi(ids) { + const ts = Math.floor(Date.now() / 1000); + const url = `${BASE_URL}/system?method=order.recheckOrder.batchQuickRecheck&v=1.0×tamp=${ts}`; + const headers = { + 'platform': 'web', + 'project': 'wms', + 'Content-Type': 'application/json; charset=utf-8', + 'Authorization': `Bearer ${TOKEN}`, + }; + const body = JSON.stringify({ ids }); + + const response = await fetch(url, { method: 'POST', headers, body }); + const text = await response.text(); + let json; + try { json = JSON.parse(text); } catch { json = { raw: text }; } + return { status: response.status, body: json }; +} + +// ========== 测试用例 ========== + +async function runTestCase(name, ids, expectedDesc, preSetup, postVerify, postCleanup) { + console.log(`\n${'='.repeat(60)}`); + console.log(`【${name}】`); + console.log(` 输入IDs: [${ids.join(', ')}]`); + console.log(` 预期: ${expectedDesc}`); + + let beforeOrder = {}, beforeStorage = {}, afterOrder = {}, afterStorage = {}; + let passed = false; + let failReason = ''; + + try { + // 前置准备 + if (preSetup) { + console.log(' [前置准备] 执行中...'); + await preSetup(); + console.log(' [前置准备] 完成'); + } + + // 测试前快照 + beforeOrder = await getOrderSnapshot(ids); + console.log(' 测试前订单状态:'); + for (const [id, snap] of Object.entries(beforeOrder)) { + console.log(` ID ${id}: storage="${snap.storage_status}" post="${snap.post_status}" status="${snap.status}" intercept="${snap.intercept_status}" pick="${snap.pick_status}" recheck="${snap.recheck_status}" code="${snap.delivery_order_code || snap.pre_delivery_order_code || ''}"`); + } + + // 调用 API + const result = await callApi(ids); + console.log(` HTTP Status: ${result.status}`); + const data = result.body && (result.body.data !== undefined ? result.body.data : result.body); + console.log(` 返回结果: ${JSON.stringify(data, null, 2)}`); + + // 测试后快照 + afterOrder = await getOrderSnapshot(ids); + console.log(' 测试后订单状态:'); + for (const [id, snap] of Object.entries(afterOrder)) { + const before = beforeOrder[id] || {}; + const changes = []; + if (snap.pick_status !== before.pick_status) changes.push(`pick: ${before.pick_status}→${snap.pick_status}`); + if (snap.recheck_status !== before.recheck_status) changes.push(`recheck: ${before.recheck_status}→${snap.recheck_status}`); + if (snap.storage_status !== before.storage_status) changes.push(`storage: ${before.storage_status}→${snap.storage_status}`); + const changeStr = changes.length ? ` [变更: ${changes.join(', ')}]` : ' [无变更]'; + console.log(` ID ${id}: pick="${snap.pick_status}" recheck="${snap.recheck_status}" storage="${snap.storage_status}"${changeStr}`); + } + + // 自定义验证 + if (postVerify) { + const verifyResult = await postVerify(result, beforeOrder, afterOrder); + if (verifyResult === true) { + passed = true; + } else { + passed = false; + failReason = typeof verifyResult === 'string' ? verifyResult : '自定义验证失败'; + } + } else { + // 默认验证:HTTP 200 + passed = result.status === 200; + if (!passed) failReason = `HTTP ${result.status}`; + } + + return { name, passed, failReason, result: data, beforeOrder, afterOrder, ids }; + } catch (e) { + console.log(` 异常: ${e.message}`); + return { name, passed: false, failReason: e.message, ids }; + } finally { + // 后置清理 + if (postCleanup) { + try { + console.log(' [后置清理] 执行中...'); + await postCleanup(); + console.log(' [后置清理] 完成'); + } catch (cleanupErr) { + console.log(` [后置清理] 失败: ${cleanupErr.message}`); + } + } + } +} + +// ========== 主测试流程 ========== + +async function main() { + console.log('='.repeat(60)); + console.log('batchQuickRecheck 接口完整真实流程测试'); + console.log(`测试时间: ${new Date().toISOString()}`); + console.log(`目标表: ${TABLE}`); + console.log(`Base URL: ${BASE_URL}`); + console.log(`测试仓库ID: 100000 | 测试货主ID: 1000000`); + console.log('='.repeat(60)); + + const results = []; + + // ── 全局前置准备:恢复 120946 的库存锁定数量 ── + console.log('\n── 全局前置:恢复 120946 关联库存 locked_quantity ──'); + const c = await getConn(); + // 记录 storage 184 原始状态 + const [origStorage] = await c.query('SELECT id, quantity, locked_quantity FROM wms_storage WHERE id = 184 AND warehouse_id = 100000'); + console.log(` storage 184 原始: quantity=${origStorage[0].quantity}, locked=${origStorage[0].locked_quantity}`); + // 恢复 locked_quantity 以便测试成功扣减 + if (origStorage[0].locked_quantity < 1) { + await c.query('UPDATE wms_storage SET locked_quantity = locked_quantity + 1, updated_at = NOW() WHERE id = 184 AND warehouse_id = 100000'); + console.log(' storage 184 locked_quantity 已 +1(恢复用于测试)'); + } + // 恢复 wms_picking 状态 + await c.query("UPDATE wms_picking SET status = 'pending', updated_at = NOW() WHERE id = 87425 AND warehouse_id = 100000"); + console.log(' wms_picking 87425 status 恢复为 pending'); + // 恢复 wave_pick_task_order + await c.query('UPDATE wms_wave_pick_task_order SET pick_status = 0, picked_time = NULL, update_time = NOW() WHERE id = 6057 AND warehouse_id = 100000'); + console.log(' wave_pick_task_order 6057 pick_status 恢复为 0'); + // 恢复 120946 的 pick_status 和 recheck_status + await c.query("UPDATE wms_order_delivery_100000 SET pick_status = 'none', recheck_status = 'none', updated_at = NOW() WHERE id = 120946 AND warehouse_id = 100000"); + console.log(' 订单 120946 pick_status/recheck_status 已恢复'); + + // ── 用例 7: 空列表(不修改数据,最先测) ── + results.push(await runTestCase( + '用例7: 空列表-应返回错误', + [], + '返回错误 "订单ID列表不能为空"', + null, + async (result) => { + // batchQuickRecheck 返回 500 而非 400(内部 throw(400) 被框架包装为 500) + // 检查是否包含错误消息 + const msg = result.body && (result.body.message || ''); + const dataMsg = result.body && result.body.data && result.body.data.message || ''; + if (msg.includes('订单ID列表不能为空') || dataMsg.includes('订单ID列表不能为空')) return true; + return `期望包含"订单ID列表不能为空",实际: ${JSON.stringify(result.body)}`; + } + )); + + // ── 用例 8: 不存在的订单ID ── + results.push(await runTestCase( + '用例8: 不存在的订单ID', + [999999999], + '全部 failed, reason="未找到对应订单"', + null, + async (result) => { + const data = result.body && (result.body.data !== undefined ? result.body.data : result.body); + if (!data || typeof data !== 'object') return `返回数据格式异常: ${JSON.stringify(result.body)}`; + if (data.success_count === 0 && data.failed_count >= 1) { + const firstFail = data.failed && data.failed[0]; + if (firstFail && firstFail.reason === '未找到对应订单') return true; + return `期望 reason="未找到对应订单",实际: ${JSON.stringify(firstFail)}`; + } + return `期望 success_count=0, failed_count>=1,实际: ${JSON.stringify(data)}`; + } + )); + + // ── 用例 5: 失败-未同步(120858: status='pedding') ── + results.push(await runTestCase( + '用例5: 失败-未同步', + [120858, 120857], + '全部 failed, reason="没有同步"', + null, + async (result) => { + const data = result.body && (result.body.data !== undefined ? result.body.data : result.body); + if (!data || data.success_count !== 0) return `期望 success_count=0,实际: ${JSON.stringify(data)}`; + const allNoSync = (data.failed || []).every(f => f.reason === '没有同步'); + if (allNoSync) return true; + return `期望所有 failed reason="没有同步",实际: ${JSON.stringify(data.failed)}`; + } + )); + + // ── 用例 4: 失败-无快递(120944: post_status='none') ── + results.push(await runTestCase( + '用例4: 失败-无快递', + [120944, 120943], + '全部 failed, reason="没有分配快递"', + null, + async (result) => { + const data = result.body && (result.body.data !== undefined ? result.body.data : result.body); + if (!data || data.success_count !== 0) return `期望 success_count=0,实际: ${JSON.stringify(data)}`; + const allNoPost = (data.failed || []).every(f => f.reason === '没有分配快递'); + if (allNoPost) return true; + return `期望所有 failed reason="没有分配快递",实际: ${JSON.stringify(data.failed)}`; + } + )); + + // ── 用例 3: 失败-未分配储位(120947: storage_status='none') ── + results.push(await runTestCase( + '用例3: 失败-未分配储位', + [120947, 120939], + '全部 failed, reason="未分配储位"', + null, + async (result) => { + const data = result.body && (result.body.data !== undefined ? result.body.data : result.body); + if (!data || data.success_count !== 0) return `期望 success_count=0,实际: ${JSON.stringify(data)}`; + const allNoStorage = (data.failed || []).every(f => f.reason === '未分配储位'); + if (allNoStorage) return true; + return `期望所有 failed reason="未分配储位",实际: ${JSON.stringify(data.failed)}`; + } + )); + + // ── 用例 2: 失败-已拦截(120945: intercept_status='intercepted_at_warehouse') ── + results.push(await runTestCase( + '用例2: 失败-已拦截', + [120945], + '全部 failed, reason="已拦截"', + null, + async (result) => { + const data = result.body && (result.body.data !== undefined ? result.body.data : result.body); + if (!data || data.success_count !== 0) return `期望 success_count=0,实际: ${JSON.stringify(data)}`; + const allIntercepted = (data.failed || []).every(f => f.reason === '已拦截'); + if (allIntercepted) return true; + return `期望所有 failed reason="已拦截",实际: ${JSON.stringify(data.failed)}`; + } + )); + + // ── 用例 1: 成功-含未拣货(120946: storage='fin', post='fin', status='created', pick='none') ── + // 前置: 确保 120946 的 picking 记录和库存已恢复 + let case1Cleanup = null; + results.push(await runTestCase( + '用例1: 成功-含未拣货', + [120946], + 'success_count >= 1, 订单 recheck_status=fin, pick_status=fin', + async () => { + // 再次确认前置条件 + const c2 = await getConn(); + const [st] = await c2.query('SELECT locked_quantity FROM wms_storage WHERE id = 184 AND warehouse_id = 100000'); + console.log(` [前置确认] storage 184 locked_quantity=${st[0].locked_quantity}`); + const [pk] = await c2.query('SELECT status FROM wms_picking WHERE id = 87425 AND warehouse_id = 100000'); + console.log(` [前置确认] picking 87425 status=${pk[0].status}`); + }, + async (result) => { + const data = result.body && (result.body.data !== undefined ? result.body.data : result.body); + if (!data || data.success_count < 1) return `期望 success_count >= 1,实际: ${JSON.stringify(data)}`; + + // 验证 120946 的状态 + const c3 = await getConn(); + const [order] = await c3.query( + 'SELECT pick_status, recheck_status FROM wms_order_delivery_100000 WHERE id = 120946 AND warehouse_id = 100000' + ); + console.log(` [验证] 120946 pick_status="${order[0].pick_status}" recheck_status="${order[0].recheck_status}"`); + if (order[0].pick_status !== 'fin') return `期望 pick_status='fin',实际="${order[0].pick_status}"`; + if (order[0].recheck_status !== 'fin') return `期望 recheck_status='fin',实际="${order[0].recheck_status}"`; + + // 验证库存已扣减 + const [stAfter] = await c3.query('SELECT locked_quantity, quantity FROM wms_storage WHERE id = 184 AND warehouse_id = 100000'); + console.log(` [验证] storage 184 扣减后: locked=${stAfter[0].locked_quantity}, quantity=${stAfter[0].quantity}`); + + // 记录清理函数 + case1Cleanup = async () => { + const cc = await getConn(); + // 恢复库存 + await cc.query('UPDATE wms_storage SET locked_quantity = locked_quantity + 1, quantity = quantity + 1, updated_at = NOW() WHERE id = 184 AND warehouse_id = 100000'); + // 恢复 picking + await cc.query("UPDATE wms_picking SET status = 'pending', updated_at = NOW() WHERE id = 87425 AND warehouse_id = 100000"); + // 恢复 wave_pick_task_order + await cc.query('UPDATE wms_wave_pick_task_order SET pick_status = 0, picked_time = NULL, update_time = NOW() WHERE id = 6057 AND warehouse_id = 100000'); + // 恢复订单状态 + await cc.query("UPDATE wms_order_delivery_100000 SET pick_status = 'none', recheck_status = 'none', updated_at = NOW() WHERE id = 120946 AND warehouse_id = 100000"); + console.log(' [用例1恢复] 120946 相关数据已恢复'); + }; + return true; + }, + case1Cleanup ? async () => { await case1Cleanup(); } : null + )); + + // ── 用例 6: 部分失败-混合(有效+无效) ── + // 需要先确保 120946 恢复到可测试状态 + results.push(await runTestCase( + '用例6: 部分失败-混合', + [120946, 120947, 999999999], + 'success_count >= 1 且 failed_count >= 2', + async () => { + // 恢复 120946 的前置条件 + const c4 = await getConn(); + const [st] = await c4.query('SELECT locked_quantity FROM wms_storage WHERE id = 184 AND warehouse_id = 100000'); + if (st[0].locked_quantity < 1) { + await c4.query('UPDATE wms_storage SET locked_quantity = locked_quantity + 1, quantity = quantity + 1, updated_at = NOW() WHERE id = 184 AND warehouse_id = 100000'); + console.log(' [前置] storage 184 locked_quantity 已恢复 +1'); + } + await c4.query("UPDATE wms_picking SET status = 'pending', updated_at = NOW() WHERE id = 87425 AND warehouse_id = 100000"); + await c4.query('UPDATE wms_wave_pick_task_order SET pick_status = 0, picked_time = NULL, update_time = NOW() WHERE id = 6057 AND warehouse_id = 100000'); + await c4.query("UPDATE wms_order_delivery_100000 SET pick_status = 'none', recheck_status = 'none', updated_at = NOW() WHERE id = 120946 AND warehouse_id = 100000"); + console.log(' [前置] 120946 数据已恢复'); + }, + async (result) => { + const data = result.body && (result.body.data !== undefined ? result.body.data : result.body); + if (!data) return `返回数据为空: ${JSON.stringify(result.body)}`; + if (data.success_count >= 1 && data.failed_count >= 2) { + const hasUnfound = (data.failed || []).some(f => f.reason === '未找到对应订单'); + const hasNoStorage = (data.failed || []).some(f => f.reason === '未分配储位'); + console.log(` [验证] 包含未找到: ${hasUnfound}, 包含未分配储位: ${hasNoStorage}`); + return true; + } + return `期望 success_count>=1 且 failed_count>=2,实际 success_count=${data.success_count}, failed_count=${data.failed_count}`; + }, + async () => { + // 恢复 120946 + const c5 = await getConn(); + const [st] = await c5.query('SELECT locked_quantity, quantity FROM wms_storage WHERE id = 184 AND warehouse_id = 100000'); + // 如果 locked_quantity 减少了(测试成功扣减了),恢复 + await c5.query("UPDATE wms_picking SET status = 'pending', updated_at = NOW() WHERE id = 87425 AND warehouse_id = 100000"); + await c5.query('UPDATE wms_wave_pick_task_order SET pick_status = 0, picked_time = NULL, update_time = NOW() WHERE id = 6057 AND warehouse_id = 100000'); + await c5.query("UPDATE wms_order_delivery_100000 SET pick_status = 'none', recheck_status = 'none', updated_at = NOW() WHERE id = 120946 AND warehouse_id = 100000"); + // 检查库存是否需要恢复 + const [st2] = await c5.query('SELECT locked_quantity FROM wms_storage WHERE id = 184 AND warehouse_id = 100000'); + console.log(` [用例6恢复] 120946 数据已恢复,storage 184 locked=${st2[0].locked_quantity}`); + } + )); + + // ── 全局恢复:将 storage 184 恢复到测试前状态 ── + console.log('\n── 全局恢复:storage 184 ──'); + // 检查当前状态,恢复到原始值 + const [finalSt] = await c.query('SELECT quantity, locked_quantity FROM wms_storage WHERE id = 184 AND warehouse_id = 100000'); + console.log(` storage 184 最终: quantity=${finalSt[0].quantity}, locked=${finalSt[0].locked_quantity}`); + console.log(` storage 184 原始: quantity=${origStorage[0].quantity}, locked=${origStorage[0].locked_quantity}`); + + // 恢复 picking 87425 到 pending + await c.query("UPDATE wms_picking SET status = 'pending', updated_at = NOW() WHERE id = 87425 AND warehouse_id = 100000"); + // 恢复 wave_pick_task_order 6057 到 pick_status=0 + await c.query('UPDATE wms_wave_pick_task_order SET pick_status = 0, picked_time = NULL, update_time = NOW() WHERE id = 6057 AND warehouse_id = 100000'); + // 恢复订单 120946 + await c.query("UPDATE wms_order_delivery_100000 SET pick_status = 'none', recheck_status = 'none', updated_at = NOW() WHERE id = 120946 AND warehouse_id = 100000"); + console.log(' 全局恢复完成'); + + // ── 汇总 ── + console.log(`\n${'='.repeat(60)}`); + console.log('测试汇总'); + console.log('='.repeat(60)); + const passCount = results.filter(r => r.passed).length; + const failCount = results.filter(r => !r.passed).length; + console.log(`总用例数: ${results.length}`); + console.log(`通过: ${passCount}`); + console.log(`失败: ${failCount}`); + console.log(''); + + for (const r of results) { + const status = r.passed ? 'PASS' : 'FAIL'; + console.log(` [${status}] ${r.name}`); + if (r.result && r.result.success_count !== undefined) { + console.log(` success_count=${r.result.success_count}, failed_count=${r.result.failed_count}`); + } + if (!r.passed && r.failReason) { + console.log(` 失败原因: ${r.failReason}`); + } + } + + await closeConn(); + return { results, passCount, failCount }; +} + +main().then(({ results, passCount, failCount }) => { + console.log('\n测试完成。'); + // 返回给调用者 + process.exit(failCount > 0 ? 1 : 0); +}).catch(e => { + console.error('测试脚本异常:', e.message); + process.exit(1); +}); diff --git a/scripts/test_batch_quick_recheck_v2.js b/scripts/test_batch_quick_recheck_v2.js new file mode 100644 index 0000000..5829f84 --- /dev/null +++ b/scripts/test_batch_quick_recheck_v2.js @@ -0,0 +1,171 @@ +'use strict'; +// batchQuickRecheck 接口真实流程测试脚本 v2 - 修复 body 格式 +const TOKEN = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJsaXVmdW1pbmdyZW4iLCJyZWFsX25hbWUiOiLliJjku5jmmI7ku4EiLCJwbGF0Zm9ybV9jb2RlIjoid2ViIiwiY3VycmVudF9yb2xlX2lkIjo0LCJjdXJyZW50X3N0b3JlX2lkIjoxMDAwMDAsImlhdCI6MTc4MTM2MDk3MiwiZXhwIjoxNzgxMzc1MzcyfQ.u0svJXHuk8RdlM8ObhDMlRj07gWQzS8Y_41dPcBDtc0'; +const BASE_URL = 'http://127.0.0.1:6060'; +const TABLE = 'wms_order_delivery_100000'; +const mysql = require('mysql2/promise'); +const DB_CONFIG = {host:'127.0.0.1',port:3307,user:'wms',password:'dspxmRwRdRbWtbm7',database:'wms'}; + +async function getOrderSnapshot(conn, ids) { + if (!ids.length) return {}; + const [rows] = await conn.query( + `SELECT id, delivery_order_code, pre_delivery_order_code, + pick_status, recheck_status, storage_status, post_status, status, intercept_status + FROM ${TABLE} WHERE id IN (?)`, [ids] + ); + const map = {}; + rows.forEach(r => { map[r.id] = r; }); + return map; +} + +async function callApi(ids) { + const ts = Math.floor(Date.now() / 1000); + const url = `${BASE_URL}/system?method=order.recheckOrder.batchQuickRecheck&v=1.0×tamp=${ts}`; + const headers = { + 'platform': 'web', + 'project': 'wms', + 'Content-Type': 'application/json; charset=utf-8', + 'Authorization': `Bearer ${TOKEN}`, + }; + // IMPORTANT: body 必须扁平化,ids 直接在顶层。callMethod 将整个 body 传给业务方法 + const body = JSON.stringify({ ids }); + + const response = await fetch(url, { method: 'POST', headers, body }); + const text = await response.text(); + let json; + try { json = JSON.parse(text); } catch { json = { raw: text }; } + return { status: response.status, body: json }; +} + +async function runTestCase(name, ids, expectedDesc) { + console.log(`\n${'='.repeat(60)}`); + console.log(`【${name}】`); + console.log(` 输入IDs: [${ids.join(', ')}]`); + console.log(` 预期: ${expectedDesc}`); + + const conn = await mysql.createConnection(DB_CONFIG); + let beforeSnapshot = {}; + let afterSnapshot = {}; + let passed = false; + + try { + beforeSnapshot = await getOrderSnapshot(conn, ids); + console.log(' 测试前状态:'); + for (const [id, snap] of Object.entries(beforeSnapshot)) { + console.log(` ID ${id}: pick="${snap.pick_status}" recheck="${snap.recheck_status}" storage="${snap.storage_status}" post="${snap.post_status}" status="${snap.status}" intercept="${snap.intercept_status}" code="${snap.delivery_order_code || snap.pre_delivery_order_code || ''}"`); + } + + const result = await callApi(ids); + console.log(` HTTP Status: ${result.status}`); + const data = result.body && result.body.data; + console.log(` 返回结果: ${JSON.stringify(data || result.body, null, 2)}`); + + passed = result.status === 200; + + afterSnapshot = await getOrderSnapshot(conn, ids); + console.log(' 测试后状态:'); + for (const [id, snap] of Object.entries(afterSnapshot)) { + const before = beforeSnapshot[id] || {}; + const changes = []; + if (snap.pick_status !== before.pick_status) changes.push(`pick: ${before.pick_status}→${snap.pick_status}`); + if (snap.recheck_status !== before.recheck_status) changes.push(`recheck: ${before.recheck_status}→${snap.recheck_status}`); + const changeStr = changes.length ? ` [变更: ${changes.join(', ')}]` : ' [无变更]'; + console.log(` ID ${id}: pick="${snap.pick_status}" recheck="${snap.recheck_status}"${changeStr}`); + } + + return { name, passed, result: data || result.body, beforeSnapshot, afterSnapshot, ids }; + } catch (e) { + console.log(` 异常: ${e.message}`); + return { name, passed: false, error: e.message, ids }; + } finally { + await conn.end(); + } +} + +async function main() { + console.log('='.repeat(60)); + console.log('batchQuickRecheck 接口真实流程测试'); + console.log(`测试时间: ${new Date().toISOString()}`); + console.log(`目标表: ${TABLE}`); + console.log(`Base URL: ${BASE_URL}`); + console.log('='.repeat(60)); + + const results = []; + + // 用例7: 空列表 (先测,不修改数据) + results.push(await runTestCase( + '用例7: 空列表', + [], + '400 错误 "订单ID列表不能为空"' + )); + + // 用例8: 不存在ID + results.push(await runTestCase( + '用例8: 不存在ID', + [999999999], + '全部 failed, reason="未找到对应订单"' + )); + + // 用例4: 全失败-未同步 + results.push(await runTestCase( + '用例4: 全失败-未同步', + [120858, 120857], + '全部 failed, reason="没有同步"' + )); + + // 用例3: 全失败-无快递 + results.push(await runTestCase( + '用例3: 全失败-无快递', + [120944, 120943], + '全部 failed, reason="没有分配快递"' + )); + + // 用例2: 全失败-无储位 + results.push(await runTestCase( + '用例2: 全失败-无储位', + [120947, 120939], + '全部 failed, reason="未分配储位"' + )); + + // 用例5: 全失败-已拦截 + results.push(await runTestCase( + '用例5: 全失败-已拦截', + [120945], + '全部 failed, reason="已拦截"' + )); + + // 用例6: 部分失败-混合(valid + invalid) + results.push(await runTestCase( + '用例6: 部分失败-混合', + [120946, 120947, 999999999], + 'success 和 failed 各有' + )); + + // 用例1: 全成功-含未拣货 (最后测,会修改数据) + results.push(await runTestCase( + '用例1: 全成功-含未拣货', + [120946], + 'pick_status=none → 自动完成拣货+复核, recheck_status=fin' + )); + + // 汇总 + console.log(`\n${'='.repeat(60)}`); + console.log('测试汇总'); + console.log('='.repeat(60)); + const passCount = results.filter(r => r.passed).length; + const failCount = results.filter(r => !r.passed).length; + console.log(`总用例数: ${results.length}`); + console.log(`通过: ${passCount}`); + console.log(`失败: ${failCount}`); + console.log(''); + + for (const r of results) { + const status = r.passed ? 'PASS' : 'FAIL'; + console.log(` [${status}] ${r.name}`); + if (r.result && r.result.success_count !== undefined) { + console.log(` success_count=${r.result.success_count}, failed_count=${r.result.failed_count}`); + } + } +} + +main().catch(e => { console.error('测试脚本异常:', e.message); process.exit(1); }); diff --git a/test/app/service/systemMethods/stock.warehouse.import.test.js b/test/app/service/systemMethods/stock.warehouse.import.test.js index ca1da91..b13fda4 100644 --- a/test/app/service/systemMethods/stock.warehouse.import.test.js +++ b/test/app/service/systemMethods/stock.warehouse.import.test.js @@ -137,4 +137,230 @@ describe('test/app/service/systemMethods/stock.warehouse.import.test.js', () => assert.equal(calls.saveArgs[0].goods_code, 'CARGO-321'); assert.equal(calls.saveArgs[0].item_code, 'ITEM-321'); }); + + // ======================= _normalizeBarcodeField 单元测试 ======================= + describe('_normalizeBarcodeField()', () => { + let service; + before(() => { + const h = createHarness(); + service = h.service; + }); + + it('should return empty array for null', () => { + assert.deepEqual(service._normalizeBarcodeField(null), []); + }); + + it('should return empty array for undefined', () => { + assert.deepEqual(service._normalizeBarcodeField(undefined), []); + }); + + it('should return empty array for array input (arrays no longer supported)', () => { + const result = service._normalizeBarcodeField([ 'A', 'B', 'A', '', 'C ' ]); + assert.deepEqual(result, []); + }); + + it('should return empty array for array input with whitespace items', () => { + const result = service._normalizeBarcodeField([ ' 69123456 ', '69123456', ' 7890 ' ]); + assert.deepEqual(result, []); + }); + + it('should split comma-separated string', () => { + const result = service._normalizeBarcodeField('A,B,C'); + assert.deepEqual(result, [ 'A', 'B', 'C' ]); + }); + + it('should trim and filter empty parts from comma string', () => { + const result = service._normalizeBarcodeField(' A ,, B , ,C '); + assert.deepEqual(result, [ 'A', 'B', 'C' ]); + }); + + it('should return empty array for empty string', () => { + assert.deepEqual(service._normalizeBarcodeField(''), []); + }); + + it('should return empty array for whitespace-only string', () => { + assert.deepEqual(service._normalizeBarcodeField(' '), []); + }); + + it('should return empty array for all-empty array', () => { + assert.deepEqual(service._normalizeBarcodeField([ '', '', '' ]), []); + }); + + it('should return single item for single-value string', () => { + assert.deepEqual(service._normalizeBarcodeField('6901234567890'), [ '6901234567890' ]); + }); + + it('should deduplicate comma-separated values', () => { + const result = service._normalizeBarcodeField('A,A,B'); + assert.deepEqual(result, [ 'A', 'B' ]); + }); + }); + + // ======================= _normalizeWarehouseImportRow 条码别名映射测试 ======================= + describe('_normalizeWarehouseImportRow barcode alias mapping', () => { + let service; + before(() => { + const h = createHarness(); + service = h.service; + }); + + it('should map 条码 to barcode', () => { + const row = { '条码': 'A,B' }; + const normalized = service._normalizeWarehouseImportRow(row); + assert.deepEqual(normalized.barcode, [ 'A', 'B' ]); + }); + + it('should map bar_code to barcode', () => { + const row = { bar_code: 'X,Y' }; + const normalized = service._normalizeWarehouseImportRow(row); + assert.deepEqual(normalized.barcode, [ 'X', 'Y' ]); + }); + + it('should map barCode to barcode', () => { + const row = { barCode: 'P,Q' }; + const normalized = service._normalizeWarehouseImportRow(row); + assert.deepEqual(normalized.barcode, [ 'P', 'Q' ]); + }); + + it('should return empty array for barcodeList (array no longer supported)', () => { + const row = { barcodeList: [ 'M', 'N' ] }; + const normalized = service._normalizeWarehouseImportRow(row); + assert.deepEqual(normalized.barcode, []); + }); + + it('should map barcode_list to barcode', () => { + const row = { barcode_list: 'R,S,T' }; + const normalized = service._normalizeWarehouseImportRow(row); + assert.deepEqual(normalized.barcode, [ 'R', 'S', 'T' ]); + }); + + it('should return empty array for barcode pass-through (array no longer supported)', () => { + const row = { barcode: [ 'U', 'V' ] }; + const normalized = service._normalizeWarehouseImportRow(row); + assert.deepEqual(normalized.barcode, []); + }); + }); + + // ======================= 新建商品时传入 barcode ======================= + describe('create with barcode', () => { + it('should pass barcode as array to createWarehouseStock (comma string input)', async () => { + const { service, calls, ctx } = createHarness(); + + await service.import([ + { + item_code: 'NEW-SKU-1', + goods_code: 'G-NEW-1', + 条码: '6901234567890,6901234567891', + }, + ]); + + assert.equal(calls.createArgs.length, 1); + assert.equal(calls.saveArgs.length, 0); + assert.equal(calls.createArgs[0].item_code, 'NEW-SKU-1'); + assert.equal(calls.createArgs[0].store_id, ctx.user.store_id); + assert.deepEqual(calls.createArgs[0].barcode, [ '6901234567890', '6901234567891' ]); + }); + + it('should pass barcode as array to createWarehouseStock (comma string input via bar_code)', async () => { + const { service, calls, ctx } = createHarness(); + + await service.import([ + { + item_code: 'NEW-SKU-2', + goods_code: 'G-NEW-2', + bar_code: '6901234567892,6901234567893', + }, + ]); + + assert.equal(calls.createArgs.length, 1); + assert.equal(calls.saveArgs.length, 0); + assert.equal(calls.createArgs[0].item_code, 'NEW-SKU-2'); + assert.deepEqual(calls.createArgs[0].barcode, [ '6901234567892', '6901234567893' ]); + }); + + it('should pass empty barcode array to createWarehouseStock when no barcode provided', async () => { + const { service, calls } = createHarness(); + + await service.import([ + { + item_code: 'NEW-SKU-3', + goods_code: 'G-NEW-3', + }, + ]); + + assert.equal(calls.createArgs.length, 1); + assert.deepEqual(calls.createArgs[0].barcode, []); + }); + }); + + // ======================= 更新商品时传入 barcode ======================= + describe('update with barcode', () => { + it('should pass barcode to saveWarehouseStock when updating (comma string format)', async () => { + const { service, calls } = createHarness(); + + await service.import([ + { + SKU: '500', + item_code: 'SKU-500', + barcode_list: 'BAR-1,BAR-2,BAR-3', + }, + ]); + + assert.equal(calls.saveArgs.length, 1); + assert.equal(calls.createArgs.length, 0); + assert.equal(calls.saveArgs[0].id, '500'); + assert.deepEqual(calls.saveArgs[0].barcode, [ 'BAR-1', 'BAR-2', 'BAR-3' ]); + }); + + it('should return empty barcode array when updating (array no longer supported)', async () => { + const { service, calls } = createHarness(); + + await service.import([ + { + id: '501', + item_code: 'SKU-501', + barcodeList: [ 'BAR-A', 'BAR-B' ], + }, + ]); + + assert.equal(calls.saveArgs.length, 1); + assert.equal(calls.saveArgs[0].id, '501'); + assert.deepEqual(calls.saveArgs[0].barcode, []); + }); + + it('should pass empty barcode array to saveWarehouseStock when barcode is explicitly empty', async () => { + const { service, calls } = createHarness(); + + await service.import([ + { + SKU: '502', + item_code: 'SKU-502', + barcode: [], + }, + ]); + + assert.equal(calls.saveArgs.length, 1); + assert.equal(calls.saveArgs[0].id, '502'); + assert.deepEqual(calls.saveArgs[0].barcode, []); + }); + + it('should pass empty barcode array to saveWarehouseStock when barcode is not provided at all', async () => { + const { service, calls } = createHarness(); + + await service.import([ + { + SKU: '503', + item_code: 'SKU-503', + goods_code: 'G-503', + }, + ]); + + assert.equal(calls.saveArgs.length, 1); + assert.equal(calls.saveArgs[0].id, '503'); + // barcode 属性由 _normalizeWarehouseImportRow 始终设置,未传入时为空数组 [] + // saveWarehouseStock 中通过 hasOwnProperty('barcode') 判定为 true,会清空旧条码 + assert.equal(Object.prototype.hasOwnProperty.call(calls.saveArgs[0], 'barcode'), true); + assert.deepEqual(calls.saveArgs[0].barcode, []); + }); + }); }); diff --git a/test/app/service/systems/order_print.getWavePlatformPrintData.test.js b/test/app/service/systems/order_print.getWavePlatformPrintData.test.js index cd2ea06..d1fb6af 100644 --- a/test/app/service/systems/order_print.getWavePlatformPrintData.test.js +++ b/test/app/service/systems/order_print.getWavePlatformPrintData.test.js @@ -146,7 +146,7 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js' const customDataContent = result.print_data.contents.find(content => content && content.customData); assert.ok(customDataContent); assert.equal(customDataContent.templateURL, 'http://www.ye4s.com/mb/kuaishou.xml'); - assert.ok(customDataContent.customData.productInfo.includes('W010 申通快递 商品数量【2】')); + assert.ok(customDataContent.customData.productInfo.includes('W010 申通快递')); assert.ok(customDataContent.customData.productInfo.includes('E2区02-04-02 化妆品 6973348850399 【2】')); }); @@ -242,7 +242,7 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js' assert.ok(customContent); assert.equal(customContent.templateURL, 'http://www.ye4s.com/mb/pdd.xml'); assert.ok(customContent.data.list[0].text.includes('\r')); - assert.ok(customContent.data.list[0].text.includes('W020 顺丰空运 商品数量【1】')); + assert.ok(customContent.data.list[0].text.includes('W020 顺丰空运')); assert.ok(customContent.data.list[0].text.includes('A1-01-01 90123 【1】')); }); @@ -339,7 +339,7 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js' const customContent = result.print_data.contents.find(content => content && content.data && Array.isArray(content.data.list)); assert.ok(customContent); - assert.ok(customContent.data.list[0].text.includes('W021 圆通 商品数量【3】')); + assert.ok(customContent.data.list[0].text.includes('W021 圆通')); assert.ok(customContent.data.list[0].text.includes('C1-01-01 9988776655443 【3】')); }); @@ -424,7 +424,7 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js' const customContent = result.print_data.contents[1]; assert.ok(customContent); assert.equal(customContent.templateURL, 'http://cloudprint.cainiao.com/cloudprint/customArea/queryCustomAreaList4Top.json?custom_area_id=6474956'); - assert.ok(customContent.data.CustomControl.includes('商品数量【2】')); + assert.ok(customContent.data.CustomControl.includes('W026 申通快递')); assert.ok(customContent.data.CustomControl.includes('E1区01-19-01 运动短袖 988948487 【2】')); }); @@ -564,7 +564,7 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js' const customContent = result.print_data.contents[1]; assert.ok(customContent); - assert.ok(customContent.data.CustomControl.includes('商品数量【1】')); + assert.ok(customContent.data.CustomControl.includes('W027 申通快递')); assert.ok(customContent.data.CustomControl.includes('A1-01-01 fallback 运动短袖 111111111 【1】')); }); @@ -808,7 +808,7 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js' const customContent = result.print_data.contents.find(content => content && content.data && Array.isArray(content.data.list)); assert.ok(customContent); - assert.ok(customContent.data.list[0].text.includes('W022 韵达 商品数量【1】')); + assert.ok(customContent.data.list[0].text.includes('W022 韵达')); assert.ok(customContent.data.list[0].text.includes('E2区08-05-02 皮带黑色 665835404213 【1】')); }); @@ -898,7 +898,7 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js' const customContent = result.print_data.contents.find(content => content && content.data && Array.isArray(content.data.list)); assert.ok(customContent); - assert.equal(customContent.data.list[0].text, 'W023 中通 商品数量【2】\r'); + assert.equal(customContent.data.list[0].text, 'W023 中通\r'); }); it('should render detail lines from non-json string items', () => { @@ -960,7 +960,7 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js' const customDataContent = result.print_data.contents.find(content => content && content.customData); assert.ok(customDataContent); - assert.ok(customDataContent.customData.productInfo.includes('W024 申通快递 商品数量【3】')); + assert.ok(customDataContent.customData.productInfo.includes('W024 申通快递')); assert.ok(customDataContent.customData.productInfo.includes('皮带黑色 【1】')); assert.ok(customDataContent.customData.productInfo.includes('皮带金色 【2】')); }); @@ -1052,7 +1052,7 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js' const customContent = result.print_data.contents.find(content => content && content.data && Array.isArray(content.data.list)); assert.ok(customContent); const text = customContent.data.list[0].text; - assert.ok(text.includes('W025 顺丰空运 商品数量【2】')); + assert.ok(text.includes('W025 顺丰空运')); assert.ok(text.includes('E2区08-05-02 04213 【1】')); assert.ok(text.includes('E2区08-04-02 00507 【1】')); assert.ok(!text.includes('\r【1】\r')); diff --git a/test/app/service/systems/order_storage_allocation.test.js b/test/app/service/systems/order_storage_allocation.test.js index 6445c08..8d23e2d 100644 --- a/test/app/service/systems/order_storage_allocation.test.js +++ b/test/app/service/systems/order_storage_allocation.test.js @@ -252,6 +252,11 @@ function createHarness(options = {}) { }, async bulkCreate(rows) { captures.pickingRows = rows.map(row => ({ ...row })); + // 推入 pickingRows 以支持 find/destroy(多轮分配场景需要) + let nextId = pickingRows.reduce((max, r) => Math.max(max, Number(r.id) || 0), 0) + 1; + for (const row of rows) { + pickingRows.push({ ...row, id: nextId++ }); + } return rows; }, }, @@ -261,6 +266,11 @@ function createHarness(options = {}) { storage: { index: { async lockQuantity(storageId, quantity) { + // 支持测试场景:模拟锁定失败以验证事务回退 + if (options.throwOnLockStorageId && Number(storageId) === Number(options.throwOnLockStorageId)) { + throw new Error(`模拟事务回退: lockQuantity 对 storageId=${storageId} 抛异常`); + } + const matchedRow = storageRows.find(row => Number(row.id) === Number(storageId)); if (!matchedRow) { throw new Error(`库存记录不存在: ${storageId}`); @@ -838,4 +848,520 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => { assert.equal(orders[0].order_flag, ''); assert.equal(captures.reversePendingExceptionRequest, undefined); }); + + // ============================================================ + // 场景 1:error 订单重分配 — 旧 picking 清理 + 库存锁定释放 + 新分配正确 + // ============================================================ + it('should clean old picking, unlock old storage locks, and create correct new picking when retrying an error order', async () => { + const { service, captures, orders, storageRows } = createHarness({ + orders: [ + { id: 100, warehouse_id: 100000, storage_status: 'error', order_flag: '库存不足:sku(501),数量:3,库位数量:0', step: 3 }, + ], + orderItems: [ + { id: 1001, order_id: 100, stock_id: 501, plan_qty: 3, order_line_no: '1' }, + { id: 1002, order_id: 100, stock_id: 502, plan_qty: 2, order_line_no: '2' }, + ], + pickingRows: [ + { + id: 101, + order_id: 100, + order_item_id: 1001, + warehouse_id: 100000, + storage_id: 3001, + quantity: 3, + space_id: 1, + space_name: '旧库位A', + status: 'pending', + created_at: '2026-06-01 10:00:00', + updated_at: '2026-06-01 10:00:00', + }, + { + id: 102, + order_id: 100, + order_item_id: 1002, + warehouse_id: 100000, + storage_id: 3002, + quantity: 2, + space_id: 2, + space_name: '旧库位B', + status: 'pending', + created_at: '2026-06-01 10:00:00', + updated_at: '2026-06-01 10:00:00', + }, + ], + stockRows: [ + { id: 501, item_code: 'SKU-501', item_name: '商品501', warehouse_id: 100000, deleted_at: null, is_valid: 'Y', locked_quantity: 0 }, + { id: 502, item_code: 'SKU-502', item_name: '商品502', warehouse_id: 100000, deleted_at: null, is_valid: 'Y', locked_quantity: 0 }, + ], + storageRows: [ + // 旧库存(首次分配时已被锁定,available=0) + { + id: 3001, + warehouse_id: 100000, + stock_id: 501, + is_enabled: 1, + delete_at: null, + available_quantity: 0, + quantity: 3, + locked_quantity: 3, + production_date: null, + inbound_time: '2026-06-01 08:00:00', + space_id: 1, + space: { id: 1, space_code: 'OLD-A', custom_name: '旧库位A', is_preferred_pick: false, locationType: { id: 1, allow_allocation: 1, is_active: 1 } }, + }, + { + id: 3002, + warehouse_id: 100000, + stock_id: 502, + is_enabled: 1, + delete_at: null, + available_quantity: 0, + quantity: 2, + locked_quantity: 2, + production_date: null, + inbound_time: '2026-06-01 08:00:00', + space_id: 2, + space: { id: 2, space_code: 'OLD-B', custom_name: '旧库位B', is_preferred_pick: false, locationType: { id: 1, allow_allocation: 1, is_active: 1 } }, + }, + // 新库存(补货后可用) + { + id: 4001, + warehouse_id: 100000, + stock_id: 501, + is_enabled: 1, + delete_at: null, + available_quantity: 5, + quantity: 5, + locked_quantity: 0, + production_date: null, + inbound_time: '2026-06-10 08:00:00', + space_id: 3, + space: { id: 3, space_code: 'NEW-A', custom_name: '新库位A', is_preferred_pick: false, locationType: { id: 1, allow_allocation: 1, is_active: 1 } }, + }, + { + id: 4002, + warehouse_id: 100000, + stock_id: 502, + is_enabled: 1, + delete_at: null, + available_quantity: 4, + quantity: 4, + locked_quantity: 0, + production_date: null, + inbound_time: '2026-06-10 08:00:00', + space_id: 4, + space: { id: 4, space_code: 'NEW-B', custom_name: '新库位B', is_preferred_pick: false, locationType: { id: 1, allow_allocation: 1, is_active: 1 } }, + }, + ], + policies: { + 501: { policyConfig: { storage_separation: 1 } }, + 502: { policyConfig: { storage_separation: 1 } }, + }, + }); + + const result = await service.allocateStorage({ + allow_storage_location: true, + order_ids: [ 100 ], + }); + + // 1) 旧库存锁定已释放 + assert.equal(captures.storageUnlocks.length, 2); + assert.deepEqual(captures.storageUnlocks[0], { storageId: 3001, quantity: 3 }); + assert.deepEqual(captures.storageUnlocks[1], { storageId: 3002, quantity: 2 }); + + // 2) 旧 picking 已删除 + assert.deepEqual(captures.pickingDestroyIds, [ 101, 102 ]); + + // 3) 新库存已锁定(只锁定新的,不锁旧的) + assert.equal(captures.storageLocks.length, 2); + const lockedIds = captures.storageLocks.map(l => l.storageId); + assert.ok(!lockedIds.includes(3001), '旧库存3001不应被重新锁定'); + assert.ok(!lockedIds.includes(3002), '旧库存3002不应被重新锁定'); + assert.ok(lockedIds.includes(4001), '新库存4001应被锁定'); + assert.ok(lockedIds.includes(4002), '新库存4002应被锁定'); + + // 4) 新 picking 数量正确(只有2条,无重复) + assert.equal(captures.pickingRows.length, 2); + + // 5) 同一 (order_item_id, space_name) 组合只有 1 条 + const itemSpacePairs = captures.pickingRows.map(r => `${r.order_item_id}_${r.space_name}`); + assert.equal(new Set(itemSpacePairs).size, 2, `存在重复的 (order_item_id, space_name) 组合: ${JSON.stringify(itemSpacePairs)}`); + + // 6) 新 picking 指向新库位 + const picking1001 = captures.pickingRows.find(r => r.order_item_id === 1001); + const picking1002 = captures.pickingRows.find(r => r.order_item_id === 1002); + assert.ok(picking1001, '应存在 order_item_id=1001 的 picking 记录'); + assert.equal(picking1001.storage_id, 4001); + assert.equal(picking1001.space_name, '新库位A'); + assert.equal(picking1001.quantity, 3); + assert.ok(picking1002, '应存在 order_item_id=1002 的 picking 记录'); + assert.equal(picking1002.storage_id, 4002); + assert.equal(picking1002.space_name, '新库位B'); + assert.equal(picking1002.quantity, 2); + + // 7) storageRows 状态正确:旧库存已解锁,新库存已锁定 + const oldStorageA = storageRows.find(r => r.id === 3001); + assert.equal(oldStorageA.available_quantity, 3, '旧库存3001解锁后available应为3'); + assert.equal(oldStorageA.locked_quantity, 0, '旧库存3001 locked应为0'); + + const oldStorageB = storageRows.find(r => r.id === 3002); + assert.equal(oldStorageB.available_quantity, 2, '旧库存3002解锁后available应为2'); + assert.equal(oldStorageB.locked_quantity, 0, '旧库存3002 locked应为0'); + + const newStorageA = storageRows.find(r => r.id === 4001); + assert.equal(newStorageA.available_quantity, 2, '新库存4001锁定后available应为2(5-3)'); + assert.equal(newStorageA.locked_quantity, 3, '新库存4001 locked应为3'); + + const newStorageB = storageRows.find(r => r.id === 4002); + assert.equal(newStorageB.available_quantity, 2, '新库存4002锁定后available应为2(4-2)'); + assert.equal(newStorageB.locked_quantity, 2, '新库存4002 locked应为2'); + + // 8) 订单状态变为 fin,无缺货信息 + assert.equal(result.code, 200); + const orderResult = result.data.orders.find(item => item.order_id === 100); + assert.ok(orderResult, '返回结果应包含订单100'); + assert.equal(orderResult.storage_status, 'fin'); + assert.equal(orderResult.status, 'success'); + assert.equal(orders[0].storage_status, 'fin'); + assert.equal(orders[0].order_flag, ''); + }); + + // ============================================================ + // 场景 2:连续两次 error 重试 — picking 始终无重复,库存锁定不泄漏 + // ============================================================ + it('should not leave duplicate picking or leaked locks after consecutive error retries', async () => { + const harness = createHarness({ + orders: [ + { id: 200, warehouse_id: 100000, storage_status: 'none', order_flag: '', step: 2 }, + ], + orderItems: [ + { id: 2001, order_id: 200, stock_id: 601, plan_qty: 5, order_line_no: '1' }, + ], + pickingRows: [], + stockRows: [ + { id: 601, item_code: 'SKU-601', item_name: '商品601', warehouse_id: 100000, deleted_at: null, is_valid: 'Y', locked_quantity: 0 }, + ], + storageRows: [ + { + id: 6001, + warehouse_id: 100000, + stock_id: 601, + is_enabled: 1, + delete_at: null, + available_quantity: 2, + quantity: 2, + locked_quantity: 0, + production_date: null, + inbound_time: '2026-06-01 08:00:00', + space_id: 10, + space: { id: 10, space_code: 'LOC-10', custom_name: '库位10', is_preferred_pick: false, locationType: { id: 1, allow_allocation: 1, is_active: 1 } }, + }, + ], + policies: { + 601: { policyConfig: { storage_separation: 1 } }, + }, + }); + + const { service, captures, orders, storageRows, pickingRows } = harness; + + // === 第 1 次分配:部分成功 → error === + const result1 = await service.allocateStorage({ allow_storage_location: true, order_ids: [ 200 ] }); + assert.equal(result1.code, 200); + assert.equal(orders[0].storage_status, 'error'); + assert.equal(captures.storageLocks.length, 1); + assert.deepEqual(captures.storageLocks[0], { storageId: 6001, quantity: 2 }); + assert.equal(captures.pickingRows.length, 1); + assert.equal(pickingRows.length, 1); + assert.equal(pickingRows[0].order_id, 200); + assert.equal(pickingRows[0].storage_id, 6001); + assert.equal(pickingRows[0].quantity, 2); + assert.equal(pickingRows[0].status, 'pending'); + assert.equal(storageRows[0].available_quantity, 0); + assert.equal(storageRows[0].locked_quantity, 2); + + const unlockCountAfterCall1 = captures.storageUnlocks.length; + + // 补货 — 追加新库存(仍不够:1 < 3) + storageRows.push({ + id: 6002, + warehouse_id: 100000, + stock_id: 601, + is_enabled: 1, + delete_at: null, + available_quantity: 1, + quantity: 1, + locked_quantity: 0, + production_date: null, + inbound_time: '2026-06-02 08:00:00', + space_id: 11, + space: { id: 11, space_code: 'LOC-11', custom_name: '库位11', is_preferred_pick: false, locationType: { id: 1, allow_allocation: 1, is_active: 1 } }, + }); + + // === 第 2 次分配:仍然缺货 → error === + const result2 = await service.allocateStorage({ allow_storage_location: true, order_ids: [ 200 ] }); + assert.equal(result2.code, 200); + assert.equal(orders[0].storage_status, 'error'); + + // 验证第 2 次调用清理了第 1 次的旧数据 + const newUnlocks = captures.storageUnlocks.slice(unlockCountAfterCall1); + assert.equal(newUnlocks.length, 1, '第2次调用应释放第1次的1条锁定'); + assert.deepEqual(newUnlocks[0], { storageId: 6001, quantity: 2 }); + + // picking 表只有新记录(旧的已被 destroy),无重复 + assert.equal(pickingRows.length, 1, 'picking表应只有1条记录(旧的已删除)'); + assert.equal(pickingRows[0].storage_id, 6002); + assert.equal(pickingRows[0].quantity, 1); + + const unlockCountAfterCall2 = captures.storageUnlocks.length; + + // 再次补货 — 这次够了 + storageRows.push({ + id: 6003, + warehouse_id: 100000, + stock_id: 601, + is_enabled: 1, + delete_at: null, + available_quantity: 10, + quantity: 10, + locked_quantity: 0, + production_date: null, + inbound_time: '2026-06-03 08:00:00', + space_id: 12, + space: { id: 12, space_code: 'LOC-12', custom_name: '库位12', is_preferred_pick: false, locationType: { id: 1, allow_allocation: 1, is_active: 1 } }, + }); + + // === 第 3 次分配:成功 === + const result3 = await service.allocateStorage({ allow_storage_location: true, order_ids: [ 200 ] }); + assert.equal(result3.code, 200); + assert.equal(orders[0].storage_status, 'fin'); + + // 验证第 3 次调用清理了第 2 次的旧数据 + const finalUnlocks = captures.storageUnlocks.slice(unlockCountAfterCall2); + assert.equal(finalUnlocks.length, 1, '第3次调用应释放第2次的1条锁定'); + assert.deepEqual(finalUnlocks[0], { storageId: 6002, quantity: 1 }); + + // 注意:第3次分配的 Storage.findAll 查询时,6001 已被第2次清理释放(available=2), + // 6003 是新增的(available=10),6002 在查询时 available=0 被过滤。 + // 所以分配结果:6001(qty=2) + 6003(qty=3) = 5 → 2 条 picking + assert.equal(pickingRows.length, 2, 'picking应有2条(6001和6003各一条)'); + + // 验证每条 picking 的分配数量 + const picking6001 = pickingRows.find(r => r.storage_id === 6001); + const picking6003 = pickingRows.find(r => r.storage_id === 6003); + assert.ok(picking6001, '应存在 storage_id=6001 的 picking'); + assert.equal(picking6001.quantity, 2); + assert.ok(picking6003, '应存在 storage_id=6003 的 picking'); + assert.equal(picking6003.quantity, 3); + + // 总分配数量 = 5 + const totalAllocated = pickingRows.reduce((sum, r) => sum + Number(r.quantity), 0); + assert.equal(totalAllocated, 5, '总分配数量应为5'); + + // 所有 picking 的 (order_item_id, space_name) 无重复 + const itemSpacePairs = pickingRows.map(r => `${r.order_item_id}_${r.space_name}`); + assert.equal(new Set(itemSpacePairs).size, pickingRows.length, '不应存在重复的 (order_item_id, space_name)'); + + // 库存锁定没有泄漏:6002 在清理后被释放锁定,且本轮未被重新分配(因为 findAll 查询时其 available=0) + // 6001 被重新锁定 2,6003 被锁定 3 + assert.equal(storageRows.find(r => r.id === 6002).locked_quantity, 0, '6002锁定应已清零'); + }); + + // ============================================================ + // 场景 3:fin 订单在混合批次中不被影响 + // ============================================================ + it('should skip fin orders and only clean up error order data in a mixed batch', async () => { + const { service, captures, orders } = createHarness({ + orders: [ + { id: 300, warehouse_id: 100000, storage_status: 'fin', order_flag: '', step: 2 }, + { id: 301, warehouse_id: 100000, storage_status: 'error', order_flag: '库存不足:sku(701),数量:5,库位数量:2', step: 3 }, + ], + orderItems: [ + { id: 3001, order_id: 300, stock_id: 701, plan_qty: 1, order_line_no: '1' }, + { id: 3011, order_id: 301, stock_id: 701, plan_qty: 5, order_line_no: '1' }, + ], + pickingRows: [ + { + id: 301, + order_id: 301, + order_item_id: 3011, + warehouse_id: 100000, + storage_id: 7001, + quantity: 2, + space_id: 20, + space_name: '旧库位X', + status: 'pending', + created_at: '2026-06-01 10:00:00', + updated_at: '2026-06-01 10:00:00', + }, + ], + stockRows: [ + { id: 701, item_code: 'SKU-701', item_name: '商品701', warehouse_id: 100000, deleted_at: null, is_valid: 'Y', locked_quantity: 0 }, + ], + storageRows: [ + // 旧库存(error 订单首次分配锁定的) + { + id: 7001, + warehouse_id: 100000, + stock_id: 701, + is_enabled: 1, + delete_at: null, + available_quantity: 0, + quantity: 2, + locked_quantity: 2, + production_date: null, + inbound_time: '2026-06-01 08:00:00', + space_id: 20, + space: { id: 20, space_code: 'OLD-X', custom_name: '旧库位X', is_preferred_pick: false, locationType: { id: 1, allow_allocation: 1, is_active: 1 } }, + }, + // 新库存(补货后可用,同时供 fin 和 error 订单使用) + { + id: 7002, + warehouse_id: 100000, + stock_id: 701, + is_enabled: 1, + delete_at: null, + available_quantity: 10, + quantity: 10, + locked_quantity: 0, + production_date: null, + inbound_time: '2026-06-10 08:00:00', + space_id: 21, + space: { id: 21, space_code: 'NEW-X', custom_name: '新库位X', is_preferred_pick: false, locationType: { id: 1, allow_allocation: 1, is_active: 1 } }, + }, + ], + policies: { + 701: { policyConfig: { storage_separation: 1 } }, + }, + }); + + const result = await service.allocateStorage({ + allow_storage_location: true, + order_ids: [ 300, 301 ], + }); + + // 1) fin 订单被跳过 + const skippedOrder300 = result.data.skipped_orders.find(item => item.order_id === 300); + assert.ok(skippedOrder300, '订单300应在skipped中'); + assert.equal(skippedOrder300.skipped_reason, 'already_allocated'); + assert.equal(orders[0].storage_status, 'fin'); + + // 2) error 订单的旧 picking 被清理 + assert.deepEqual(captures.pickingDestroyIds, [ 301 ]); + + // 3) 旧库存锁定被释放 + assert.equal(captures.storageUnlocks.length, 1); + assert.deepEqual(captures.storageUnlocks[0], { storageId: 7001, quantity: 2 }); + + // 4) fin 订单的 picking 没有被删除(它不在 pending 状态或不在 errorRetryOrderIds 中) + // 注意:fin 订单没有 pending picking,所以 destroy 的 where 只匹配 error 订单的 picking + + // 5) error 订单被分配并变为 fin + const orderResult301 = result.data.orders.find(item => item.order_id === 301); + assert.ok(orderResult301, '返回结果应包含订单301'); + assert.equal(orderResult301.storage_status, 'fin'); + assert.equal(orderResult301.status, 'success'); + assert.equal(orders[1].storage_status, 'fin'); + assert.equal(orders[1].order_flag, ''); + + // 6) 新 picking 只有 error 订单的记录 + assert.equal(captures.pickingRows.length, 1); + assert.equal(captures.pickingRows[0].order_id, 301); + assert.equal(captures.pickingRows[0].order_item_id, 3011); + assert.equal(captures.pickingRows[0].storage_id, 7002); + assert.equal(captures.pickingRows[0].quantity, 5); + }); + + // ============================================================ + // 场景 4:事务回退验证 — 清理后的分配异常触发回滚 + // ============================================================ + it('should rollback transaction and preserve old data when allocation fails after cleanup', async () => { + const { service, captures, pickingRows } = createHarness({ + orders: [ + { id: 400, warehouse_id: 100000, storage_status: 'error', order_flag: '库存不足', step: 3 }, + ], + orderItems: [ + { id: 4001, order_id: 400, stock_id: 801, plan_qty: 3, order_line_no: '1' }, + ], + pickingRows: [ + { + id: 401, + order_id: 400, + order_item_id: 4001, + warehouse_id: 100000, + storage_id: 8001, + quantity: 1, + space_id: 30, + space_name: '旧库位Z', + status: 'pending', + created_at: '2026-06-01 10:00:00', + updated_at: '2026-06-01 10:00:00', + }, + ], + stockRows: [ + { id: 801, item_code: 'SKU-801', item_name: '商品801', warehouse_id: 100000, deleted_at: null, is_valid: 'Y', locked_quantity: 0 }, + ], + storageRows: [ + { + id: 8001, + warehouse_id: 100000, + stock_id: 801, + is_enabled: 1, + delete_at: null, + available_quantity: 0, + quantity: 1, + locked_quantity: 1, + production_date: null, + inbound_time: '2026-06-01 08:00:00', + space_id: 30, + space: { id: 30, space_code: 'OLD-Z', custom_name: '旧库位Z', is_preferred_pick: false, locationType: { id: 1, allow_allocation: 1, is_active: 1 } }, + }, + // 新库存,但可用量不足以满足需求(导致分配时抛异常) + { + id: 8002, + warehouse_id: 100000, + stock_id: 801, + is_enabled: 1, + delete_at: null, + available_quantity: 1, // 需要3,只有1 → lockQuantity 不会抛异常(分配1个),但最终标记 error,不会触发 rollback + quantity: 1, + locked_quantity: 0, + production_date: null, + inbound_time: '2026-06-10 08:00:00', + space_id: 31, + space: { id: 31, space_code: 'NEW-Z', custom_name: '新库位Z', is_preferred_pick: false, locationType: { id: 1, allow_allocation: 1, is_active: 1 } }, + }, + ], + policies: { + 801: { policyConfig: { storage_separation: 1 } }, + }, + // 触发事务回退:在 lockQuantity 中对特定 storage_id 抛异常 + throwOnLockStorageId: 8002, + }); + + // 记录事务回退前的状态快照 + const unlockBefore = captures.storageUnlocks.length; + + // 验证清理前存在旧 picking 记录 + assert.equal(pickingRows.length, 1, '清理前应有1条旧picking'); + + // 预期:分配过程中 lockQuantity 对 8002 抛出异常,事务回退 + await assert.rejects( + () => service.allocateStorage({ allow_storage_location: true, order_ids: [ 400 ] }), + /模拟事务回退/, + '应抛出模拟异常' + ); + + // 验证事务已回退 + assert.equal(captures.rolledBack, true, '事务应已回退'); + + // 注意:mock 层的事务回退不会真实恢复 pickingRows/storageRows 状态, + // 但 unlockQuantity 和 destroy 在执行时仍然会修改数据(因为它们在 rollback 之前执行)。 + // 在实际 MySQL 中,这些修改会被 rollback 撤销;在 mock 中无法模拟此行为。 + // 因此这里只验证 rollback 被调用,状态恢复需由集成测试验证。 + + // 但我们可以验证:unlockQuantity 确实在 rollback 之前被调用了 + const unlocksAfterCleanup = captures.storageUnlocks.slice(unlockBefore); + assert.equal(unlocksAfterCleanup.length, 1, '清理阶段应调用 unlockQuantity'); + assert.deepEqual(unlocksAfterCleanup[0], { storageId: 8001, quantity: 1 }); + }); }); From d743e67b9da68e75685e21a7ef4a95a4619dcad1 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Wed, 17 Jun 2026 01:18:55 +0800 Subject: [PATCH 073/550] 1 --- app/lib/printer_data_builder.js | 19 +- app/model/api_app.js | 2 +- app/model/package_material_item_relation.js | 130 +++++ app/model/platform_setting.js | 6 +- app/model/store.js | 9 - app/service/qimenMethods/entryorder.js | 7 +- app/service/systemMethods/order/base.js | 13 +- app/service/systemMethods/order/index.js | 50 +- .../systemMethods/order/pendingOrder.js | 29 +- .../systemMethods/order/recheckOrder.js | 93 ++- app/service/systemMethods/order/wave.js | 70 ++- app/service/systemMethods/print.js | 65 ++- .../systemMethods/setting/packageMaterial.js | 16 +- app/service/systemMethods/stock/warehouse.js | 10 +- app/service/systems/delivery_order.js | 19 +- app/service/systems/entry_order.js | 15 +- app/service/systems/express_platform.js | 33 ++ app/service/systems/order_express.js | 544 +++++++++++++++++- app/service/systems/order_print.js | 34 +- .../systems/order_storage_allocation.js | 34 +- app/service/systems/pick.js | 85 +++ app/service/systems/pick_compensation.js | 186 +++++- app/service/systems/platform.js | 64 ++- .../systems/setting/packageMaterial.js | 40 ++ app/service/systems/setting/warehouse.js | 8 + app/service/systems/stock_store.js | 151 +++-- app/service/systems/store_warehouse.js | 17 +- ...eate-wms-package-material-item-relation.js | 150 +++++ ...0615160000-alter-uk-interface-warehouse.js | 32 ++ ...use-id-nullable-in-wms-platfrom-setting.js | 20 + docs/stock-stockWarehouse-query-rules.md | 11 + methods/changes/2026.06.16-system-01.json | 17 + methods/changes/2026.06.16-system-02.json | 16 + methods/changes/2026.06.16-system-03.json | 16 + methods/changes/2026.06.16-system-04.json | 16 + methods/changes/system.json | 85 +++ methods/system.json | 207 ++++++- scripts/integration_test_stock_warehouse.js | 114 ++++ 38 files changed, 2252 insertions(+), 181 deletions(-) create mode 100644 app/model/package_material_item_relation.js create mode 100644 database/migrations/20260615143000-create-wms-package-material-item-relation.js create mode 100644 database/migrations/20260615160000-alter-uk-interface-warehouse.js create mode 100644 database/migrations/20260617150000-make-warehouse-id-nullable-in-wms-platfrom-setting.js create mode 100644 methods/changes/2026.06.16-system-01.json create mode 100644 methods/changes/2026.06.16-system-02.json create mode 100644 methods/changes/2026.06.16-system-03.json create mode 100644 methods/changes/2026.06.16-system-04.json create mode 100644 scripts/integration_test_stock_warehouse.js diff --git a/app/lib/printer_data_builder.js b/app/lib/printer_data_builder.js index 7e00720..f7dde6f 100644 --- a/app/lib/printer_data_builder.js +++ b/app/lib/printer_data_builder.js @@ -465,6 +465,7 @@ function resolveItemQuantity(item) { * @param {number} [options.platforms_index] 平台内序号。 * @param {string} [options.expressInterfaceName] 快递渠道显示名。 * @param {number} [options.fallbackTotalQty] 兜底商品总数。 + * @param {string} [options.packageMaterialName] 推荐包材名称,非空时追加到波次号前。 * @return {Array} 自定义区文本行数组。 */ function buildWaybillCustomProductInfoLines(items, policyConfig = {}, options = {}) { @@ -544,9 +545,12 @@ function buildWaybillCustomProductInfoLines(items, policyConfig = {}, options = const hasWaveCustomPrefix = waveTotalOrders > 0 && waveIndex > 0 && Boolean(waveNo); - const waveHeaderText = hasWaveCustomPrefix - ? `${waveNo} [${finalTotalQty}-${waveIndex}]` + const packageMaterialName = String(safeOptions.packageMaterialName || '').trim(); + const packageMaterialLabel = packageMaterialName ? `【${packageMaterialName}】` : ''; + const waveBodyText = hasWaveCustomPrefix + ? `${waveNo} [${waveTotalOrders}-${waveIndex}]` : waveNo; + const waveHeaderText = packageMaterialLabel + waveBodyText; const headerParts = [ waveHeaderText, expressInterfaceName ].filter(Boolean); const headerLine = headerParts.join(' '); @@ -1243,6 +1247,7 @@ function applyKuaishouExpressFieldMapping(platform, skeleton, orderExpress, orde wave_total_orders: Number(safeOrderDelivery.wave_total_orders || 0), wave_index: Number(safeOrderDelivery.wave_index || 0), platforms_index: Number(safeOrderDelivery.platforms_index || 0), + packageMaterialName: toTrimmedString(safeOrderDelivery.package_material_name), expressInterfaceName: toTrimmedString( safeOrderExpress.logistics_interface_name || safeOrderExpress.logistics_name @@ -1387,6 +1392,7 @@ function applyPddExpressFieldMapping(platform, skeleton, orderExpress, orderDeli wave_total_orders: Number(safeOrderDelivery.wave_total_orders || 0), wave_index: Number(safeOrderDelivery.wave_index || 0), platforms_index: Number(safeOrderDelivery.platforms_index || 0), + packageMaterialName: toTrimmedString(safeOrderDelivery.package_material_name), expressInterfaceName: toTrimmedString( safeOrderExpress.logistics_interface_name || safeOrderExpress.logistics_name @@ -1573,6 +1579,7 @@ function applyDouyinExpressFieldMapping(platform, skeleton, orderExpress, orderD wave_total_orders: Number(safeOrderDelivery.wave_total_orders || 0), wave_index: Number(safeOrderDelivery.wave_index || 0), platforms_index: Number(safeOrderDelivery.platforms_index || 0), + packageMaterialName: toTrimmedString(safeOrderDelivery.package_material_name), expressInterfaceName: toTrimmedString( safeOrderExpress.logistics_interface_name || safeOrderExpress.logistics_name @@ -1705,6 +1712,7 @@ function applyCainiaoExpressFieldMapping( wave_total_orders: Number(safeOrderDelivery.wave_total_orders || 0), wave_index: Number(safeOrderDelivery.wave_index || 0), platforms_index: Number(safeOrderDelivery.platforms_index || 0), + packageMaterialName: toTrimmedString(safeOrderDelivery.package_material_name), expressInterfaceName: toTrimmedString( safeOrderExpress.logistics_interface_name || safeOrderExpress.logistics_name @@ -1905,6 +1913,7 @@ function applyXhsExpressFieldMapping( wave_total_orders: Number(safeOrderDelivery.wave_total_orders || 0), wave_index: Number(safeOrderDelivery.wave_index || 0), platforms_index: Number(safeOrderDelivery.platforms_index || 0), + packageMaterialName: toTrimmedString(safeOrderDelivery.package_material_name), expressInterfaceName: toTrimmedString( safeOrderExpress.logistics_interface_name || safeOrderExpress.logistics_name @@ -2008,6 +2017,7 @@ function applySphExpressFieldMapping( wave_total_orders: Number(safeOrderDelivery.wave_total_orders || 0), wave_index: Number(safeOrderDelivery.wave_index || 0), platforms_index: Number(safeOrderDelivery.platforms_index || 0), + packageMaterialName: toTrimmedString(safeOrderDelivery.package_material_name), expressInterfaceName: toTrimmedString( safeOrderExpress.logistics_interface_name || safeOrderExpress.logistics_name @@ -2173,6 +2183,7 @@ function applyJdExpressFieldMapping( wave_total_orders: Number(safeOrderDelivery.wave_total_orders || 0), wave_index: Number(safeOrderDelivery.wave_index || 0), platforms_index: Number(safeOrderDelivery.platforms_index || 0), + packageMaterialName: toTrimmedString(safeOrderDelivery.package_material_name), expressInterfaceName: toTrimmedString( safeOrderExpress.logistics_interface_name || safeOrderExpress.logistics_name @@ -2209,7 +2220,9 @@ function buildPlatformRequestSkeleton(input = {}) { const orderExpressForCompose = isPlainObject(input.order_express) ? { ...input.order_express } : {}; - const orderDeliveryForCompose = isPlainObject(input.order_delivery) ? input.order_delivery : {}; + const orderDeliveryForCompose = isPlainObject(input.order_delivery) + ? { ...input.order_delivery, package_material_name: String(options.packageMaterialName || '').trim() } + : {}; if (!orderExpressForCompose.items && orderDeliveryForCompose.items) { orderExpressForCompose.items = orderDeliveryForCompose.items; } diff --git a/app/model/api_app.js b/app/model/api_app.js index 7ecbacd..b81db1b 100644 --- a/app/model/api_app.js +++ b/app/model/api_app.js @@ -200,7 +200,7 @@ module.exports = app => { { name: 'uk_interface_warehouse', unique: true, - fields: [ 'qimen_app_key', 'qimen_customer_id' ], + fields: [ 'qimen_app_key', 'qimen_warehouse_code' ], }, { name: 'uk_interface_contract', diff --git a/app/model/package_material_item_relation.js b/app/model/package_material_item_relation.js new file mode 100644 index 0000000..8eb8e03 --- /dev/null +++ b/app/model/package_material_item_relation.js @@ -0,0 +1,130 @@ +'use strict'; + +/** + * 商品结构-包材绑定关系模型。 + * 记录订单商品结构指纹与包材的绑定历史,支持智能推荐。 + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} Sequelize 模型。 + */ +module.exports = app => { + const { STRING, CHAR, INTEGER, BIGINT, DECIMAL, TINYINT, DATE } = app.Sequelize; + + const PackageMaterialItemRelation = app.model.define('package_material_item_relation', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键ID', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + items_hash: { + type: CHAR(32), + allowNull: false, + comment: '订单商品结构MD5指纹', + }, + items_crc: { + type: INTEGER.UNSIGNED, + allowNull: false, + comment: '订单商品结构CRC32校验', + }, + package_material_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '包材ID', + }, + package_material_code: { + type: STRING(64), + allowNull: false, + comment: '包材编码(快照)', + }, + package_material_name: { + type: STRING(128), + allowNull: false, + comment: '包材名称(快照)', + }, + package_material_spec: { + type: STRING(128), + defaultValue: '', + comment: '规格(快照)', + }, + package_material_type: { + type: STRING(32), + defaultValue: '', + comment: '类型(快照)', + }, + length: { + type: DECIMAL(10, 2), + defaultValue: 0, + comment: '长(cm)快照', + }, + width: { + type: DECIMAL(10, 2), + defaultValue: 0, + comment: '宽(cm)快照', + }, + height: { + type: DECIMAL(10, 2), + defaultValue: 0, + comment: '高(cm)快照', + }, + weight: { + type: DECIMAL(10, 2), + defaultValue: 0, + comment: '重量(kg)快照', + }, + bind_count: { + type: INTEGER.UNSIGNED, + defaultValue: 1, + comment: '累计绑定次数', + }, + last_order_id: { + type: BIGINT(20).UNSIGNED, + comment: '最近订单ID', + }, + last_waybill_code: { + type: STRING(50), + defaultValue: '', + comment: '最近运单号', + }, + last_bind_user_id: { + type: BIGINT(20).UNSIGNED, + comment: '最近操作用户ID', + }, + last_bind_at: { + type: DATE, + comment: '最近绑定时间', + }, + is_active: { + type: TINYINT, + defaultValue: 1, + comment: '包材当前是否启用', + }, + created_at: { + type: DATE, + allowNull: false, + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + comment: '更新时间', + }, + delete_at: { + type: DATE, + comment: '软删除时间', + }, + }, { + tableName: 'wms_package_material_item_relation', + underscored: true, + paranoid: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + deletedAt: 'delete_at', + }); + + return PackageMaterialItemRelation; +}; diff --git a/app/model/platform_setting.js b/app/model/platform_setting.js index 268748e..1cb52dd 100644 --- a/app/model/platform_setting.js +++ b/app/model/platform_setting.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict'; /** * 平台设置模型定义。 @@ -34,8 +34,8 @@ module.exports = app => { }, warehouse_id: { type: BIGINT(20), - allowNull: false, - comment: '仓库ID', + allowNull: true, + comment: '仓库ID,NULL表示系统级设置', }, }, { tableName: 'wms_platfrom_setting', diff --git a/app/model/store.js b/app/model/store.js index 72865f9..105b028 100644 --- a/app/model/store.js +++ b/app/model/store.js @@ -42,7 +42,6 @@ module.exports = app => { max_notice_webhook_count: DEFAULT_MAX_NOTICE_WEBHOOK_COUNT, max_wave_quantity: DEFAULT_MAX_WAVE_QUANTITY, min_group_order_fetch_quantity: 13, - auto_grouping_enabled: false, default_express_code: 'STO', default_platform_code: 'TB', group_wave_prefix: 'B', @@ -228,14 +227,6 @@ module.exports = app => { normalized.min_group_order_fetch_quantity = minGroupOrderFetchQuantity; } - const autoGroupingEnabled = normalizeBooleanFlag( - parsed.auto_grouping_enabled, - 'subject_config.auto_grouping_enabled' - ); - normalized.auto_grouping_enabled = autoGroupingEnabled === undefined - ? DEFAULT_SUBJECT_CONFIG.auto_grouping_enabled - : autoGroupingEnabled; - normalized.default_express_code = normalizeSubjectConfigText( parsed.default_express_code, DEFAULT_SUBJECT_CONFIG.default_express_code diff --git a/app/service/qimenMethods/entryorder.js b/app/service/qimenMethods/entryorder.js index 48efe60..8be0b41 100644 --- a/app/service/qimenMethods/entryorder.js +++ b/app/service/qimenMethods/entryorder.js @@ -7,7 +7,12 @@ class entryorderServer extends MainService { const res = await this.ctx.service.systems.entryOrder.addOrder(data, this.getInfo(), 'QM'); if (res.success) { - return this.success(res.message, { createTime: this.app.formatDate(new Date()), entryOrderId: res.data.entryOrderId }); + return this.success(res.message, { + createTime: this.app.formatDate(new Date()), + entryOrderId: res.data.entryOrderId, + entryOrderCode: res.data.entryOrderCode, + status: res.data.status, + }); } return this.fail(res.message, { createTime: this.app.formatDate(new Date()) }); diff --git a/app/service/systemMethods/order/base.js b/app/service/systemMethods/order/base.js index c56b44b..ad6010c 100644 --- a/app/service/systemMethods/order/base.js +++ b/app/service/systemMethods/order/base.js @@ -707,7 +707,7 @@ class OrderBaseService extends MainService { where: { order_id: normalizedOrderId, }, - attributes: [ 'waybill_code', 'logistics_code', 'logistics_name', 'logistics_interface_id', 'weighing_weight', 'business_key', 'create_at' ], + attributes: [ 'waybill_code', 'logistics_code', 'logistics_name', 'logistics_interface_id', 'logistics_interface_name', 'weighing_weight', 'business_key', 'create_at', 'package_material_id', 'package_material_name_snapshot' ], order: [[ 'id', 'ASC' ]], raw: true, }); @@ -727,8 +727,11 @@ class OrderBaseService extends MainService { logistics_code: String(row && row.logistics_code || '').trim(), logistics_name: String(row && row.logistics_name || '').trim(), logistics_interface_id: row && row.logistics_interface_id == null ? null : Number(row.logistics_interface_id), + logistics_interface_name: String(row && row.logistics_interface_name || '').trim(), business_key: String(row && row.business_key || '').trim(), create_at: row && row.create_at != null ? new Date(row.create_at).getTime() : null, + package_material_id: row && row.package_material_id != null ? Number(row.package_material_id) : null, + package_material_name_snapshot: row && row.package_material_name_snapshot != null ? String(row.package_material_name_snapshot).trim() : null, })); } @@ -1184,10 +1187,18 @@ class OrderBaseService extends MainService { const orderItemsWithImages = this.attachImagesToOrderItems(orderItems, orderItemImagesByStockId); const expresses = await this.getOrderExpressesByOrderId(orderId, order); const logs = await this.getOrderOperationLogs(orderId); + + // 从运单列表中提取去重后的运单号数组 + const waybillCodes = Array.isArray(expresses) + ? [ ...new Set(expresses.map(expr => String(expr && expr.waybill_code || '').trim()).filter(Boolean)) ] + : []; + return { + order, detail: order, items: orderItemsWithImages, expresses, + waybill_codes: waybillCodes, logs, }; } diff --git a/app/service/systemMethods/order/index.js b/app/service/systemMethods/order/index.js index f10706c..e7a15d3 100644 --- a/app/service/systemMethods/order/index.js +++ b/app/service/systemMethods/order/index.js @@ -13,9 +13,9 @@ class OrderIndexService extends OrderBaseService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'list,badgeCount,manualOutboundOrder,queryOrderLogs,queryOrderLogList,detail,updateExpressWeighingWeight,export,exportTaskProgress'; - const _noNeedLog = 'list,badgeCount,manualOutboundOrder,queryOrderLogs,queryOrderLogList,detail,updateExpressWeighingWeight,export,exportTaskProgress'; - const _noNeedAuth = 'list,badgeCount,manualOutboundOrder,queryOrderLogs,queryOrderLogList,detail,updateExpressWeighingWeight,export,exportTaskProgress'; + const _noNeedRight = 'list,badgeCount,manualOutboundOrder,queryOrderLogs,queryOrderLogList,detail,updateExpressWeighingWeight,export,exportTaskProgress,bindExpressPackageMaterialByWaybill'; + const _noNeedLog = 'list,badgeCount,manualOutboundOrder,queryOrderLogs,queryOrderLogList,detail,updateExpressWeighingWeight,export,exportTaskProgress,bindExpressPackageMaterialByWaybill'; + const _noNeedAuth = 'list,badgeCount,manualOutboundOrder,queryOrderLogs,queryOrderLogList,detail,updateExpressWeighingWeight,export,exportTaskProgress,bindExpressPackageMaterialByWaybill'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -512,6 +512,50 @@ class OrderIndexService extends OrderBaseService { } } + /** + * 根据运单号绑定包材。 + * + * method 层仅负责参数解构、systems 转发与统一返回结构。 + * 无需传入订单ID,仅凭运单号即可完成包材绑定。 + * + * 支持团购波次自动感知: + * - 非团购订单:仅绑定当前运单的包材。 + * - 团购波次(wave_type=1):自动将同一波次下、相同快递业务键(business_key)的 + * 所有运单批量绑定相同的包材,实现一键补齐。 + * + * @param {Object} data 请求体。 + * @param {string} data.waybill_code 运单号。 + * @param {string} data.package_material_code 包材编码。 + * @return {Promise} 统一成功/失败结构。 + * 单条绑定:data 含 {order_id, waybill_code, package_material_id, package_material_name_snapshot, package_material_code}; + * 团购批量绑定:data 含 {wave_id, wave_no, business_key, order_id, waybill_code, package_material_id, package_material_code, package_material_name_snapshot, bind_count, bound_waybills, store_name, sys_logistics_name}。 + */ + async bindExpressPackageMaterialByWaybill(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const { + waybill_code: waybillCode = '', + package_material_code: packageMaterialCode = '', + } = requestData; + + try { + const result = await this.service.systems.orderExpress.bindExpressPackageMaterialByWaybill({ + waybillCode, + packageMaterialCode, + }); + + return this.success('ok', { + data: result, + code: 200, + }); + } catch (error) { + const errorCode = Number(error && error.code); + const statusCode = Number.isFinite(errorCode) && errorCode > 0 ? errorCode : 500; + return this.fail(error && error.message ? error.message : '绑定包材失败', { + data: null, + }, statusCode); + } + } + /** * 根据运单号拉取复核数据。 * diff --git a/app/service/systemMethods/order/pendingOrder.js b/app/service/systemMethods/order/pendingOrder.js index 2b6d871..97ff7a7 100644 --- a/app/service/systemMethods/order/pendingOrder.js +++ b/app/service/systemMethods/order/pendingOrder.js @@ -2081,7 +2081,6 @@ class PendingOrderService extends OrderBaseService { sys_logistics_name: sysLogisticsName, logistics_code: logisticsCode, logistics_name: logisticsName, - post_status: 'fin', updated_at: new Date(), }, { where }); @@ -4979,7 +4978,7 @@ class PendingOrderService extends OrderBaseService { const where = this.buildOrderWhere([ orderId ], warehouseId); const order = await model.findOne({ where, - attributes: [ 'id', 'step', 'outbound_status', 'warehouse_id' ], + attributes: [ 'id', 'step', 'outbound_status', 'warehouse_id', 'store_id' ], raw: true, }); @@ -5059,6 +5058,32 @@ class PendingOrderService extends OrderBaseService { this.ctx.logger.warn('[PendingOrderService.manualWaybill] 写入操作日志失败,不影响业务', logErr); } + // 5. 自动同步回传(受合约策略 auto_sync_back 控制) + try { + const storeId = Number(order.store_id) || 0; + if (storeId > 0) { + const contractConfig = await this.service.systems.storeWarehouse.getContractConfig( + Number(order.warehouse_id) || warehouseId, + storeId + ); + if ( + contractConfig + && contractConfig.policy_config + && contractConfig.policy_config.auto_sync_back === 1 + ) { + this.syncOrderIds({ orderIds: [orderId] }).catch(err => { + this.ctx.logger.error( + `[auto_sync_back] manualWaybill 自动同步失败: ${err.message}` + ); + }); + } + } + } catch (err) { + this.ctx.logger.error( + `[auto_sync_back] manualWaybill 自动同步异常: ${err.message}` + ); + } + return this.success('ok', { id: expressRecord.id, order_id: orderId, diff --git a/app/service/systemMethods/order/recheckOrder.js b/app/service/systemMethods/order/recheckOrder.js index 570c8f8..320a635 100644 --- a/app/service/systemMethods/order/recheckOrder.js +++ b/app/service/systemMethods/order/recheckOrder.js @@ -2875,6 +2875,8 @@ class RecheckOrderService extends OrderBaseService { o.logistics_name, o.items_count, o.items_total, + o.items_weight, + o.weight_type, o.status, o.create_at, o.pick_time, @@ -2919,6 +2921,8 @@ class RecheckOrderService extends OrderBaseService { logistics_name: String(row?.logistics_name || '').trim(), items_count: Number(row?.items_count || 0), items_total: Number(row?.items_total || 0), + items_weight: row?.items_weight != null ? Number(row.items_weight) : null, + weight_type: this.formatWeightTypeLabel(row?.weight_type), status: Number(row?.status || 0), create_at: row?.create_at || null, pick_time: row?.pick_time || null, @@ -3486,7 +3490,7 @@ class RecheckOrderService extends OrderBaseService { // 构建 CASE WHEN 批量扣减 const summaryEntries = Array.from(storageQtyMap.entries()); const caseClauses = summaryEntries - .map(([sid, qty]) => `WHEN ${sid} THEN ${qty}`) + .map(([ sid, qty ]) => `WHEN ${sid} THEN ${qty}`) .join(' '); await ctx.model.query( @@ -3542,6 +3546,93 @@ class RecheckOrderService extends OrderBaseService { if (transactionRows.length > 0) { await ctx.model.StorageTransaction.bulkCreate(transactionRows, { transaction }); } + + // 释放 wms_stock_warehouse 锁定数量并写入 wms_stock_transaction 出库流水 + const stockQtyMap = new Map(); + for (const sRow of storageRows) { + const sid = Number(sRow.stock_id); + if (!sid || sid <= 0) continue; + const deduction = storageQtyMap.get(Number(sRow.id)) || 0; + if (deduction <= 0) continue; + stockQtyMap.set(sid, (stockQtyMap.get(sid) || 0) + deduction); + } + + if (stockQtyMap.size > 0) { + const stockIds = Array.from(stockQtyMap.keys()); + const stockWarehouseRows = await ctx.model.StockWarehouse.findAll({ + where: { + id: { [app.Sequelize.Op.in]: stockIds }, + warehouse_id: warehouseId, + }, + attributes: [ 'id', 'quantity', 'locked_quantity' ], + lock: transaction.LOCK.UPDATE, + raw: true, + transaction, + }); + + const stockWarehouseMap = new Map(); + for (const swRow of stockWarehouseRows) { + stockWarehouseMap.set(Number(swRow.id), swRow); + } + + for (const [ stockId, qty ] of stockQtyMap) { + const swRow = stockWarehouseMap.get(stockId); + if (!swRow) { + ctx.logger.warn(`[recheckOrder] stock_warehouse 记录不存在: ${stockId}`); + continue; + } + const currentLocked = Number(swRow.locked_quantity) || 0; + if (currentLocked < qty) { + throw new Error( + `货主库存 ${stockId} 锁定数量不足:当前锁定 ${currentLocked},需释放 ${qty}` + ); + } + await ctx.model.StockWarehouse.update({ + locked_quantity: app.Sequelize.literal(`locked_quantity - ${qty}`), + update_at: app.Sequelize.literal('CURRENT_TIMESTAMP'), + }, { + where: { + id: stockId, + locked_quantity: { [app.Sequelize.Op.gte]: qty }, + }, + transaction, + }); + } + + const operator = this.getOrderLogOperator(); + const opId = String(operator.id || '').trim(); + const opName = String(operator.name || 'system').trim(); + const stockTransactionRows = []; + for (const [ stockId, qty ] of stockQtyMap) { + const swRow = stockWarehouseMap.get(stockId); + if (!swRow) continue; + const sRow = storageRows.find(r => Number(r.stock_id) === stockId); + const beforeQty = Number(swRow.quantity) || 0; + const beforeLocked = Number(swRow.locked_quantity) || 0; + stockTransactionRows.push({ + transaction_type: 'OUTBOUND', + warehouse_id: warehouseId, + store_id: sRow ? Number(sRow.store_id) || 0 : 0, + stock_id: stockId, + quantity: qty, + before_quantity: beforeQty, + after_quantity: Math.max(0, beforeQty - qty), + before_locked_quantity: beforeLocked, + after_locked_quantity: Math.max(0, beforeLocked - qty), + order_type: 'PICK_OUTBOUND', + order_no: String(orderId), + order_id: orderId, + operator_id: opId, + operator_name: opName, + remark: '拣货完成出库-货主库存释放(批量快捷复核)', + created_at: new Date(), + }); + } + + if (stockTransactionRows.length > 0) { + await ctx.model.StockTransaction.bulkCreate(stockTransactionRows, { transaction }); + } + } } } diff --git a/app/service/systemMethods/order/wave.js b/app/service/systemMethods/order/wave.js index 3ef4788..2f94475 100644 --- a/app/service/systemMethods/order/wave.js +++ b/app/service/systemMethods/order/wave.js @@ -2166,7 +2166,7 @@ class WaveService extends OrderBaseService { where, attributes: [ 'id', 'store_id', 'logistics_name', - 'items_hash', 'items', 'items_total', + 'items_hash', 'items', 'items_total', 'items_weight', 'post_status', 'pick_status', 'outbound_status', 'create_at', ], raw: true, @@ -2289,6 +2289,9 @@ class WaveService extends OrderBaseService { if (!last_order_time || o.create_at > last_order_time) last_order_time = o.create_at; } + // 同组订单 items_hash 相同,重量一致,取首单即可 + const firstOrder = g.orders[0] || {}; + list.push({ item_detail: itemSummary, item_detail_machine: itemDetailMachine, @@ -2297,6 +2300,7 @@ class WaveService extends OrderBaseService { group: g.orders.length, group_count: g.orders.length, items_total, + items_weight: firstOrder.items_weight != null ? Number(firstOrder.items_weight) : null, store_id: store_ids.length === 1 ? store_ids[0] : 0, store_ids, logistics_name: logisticsName, @@ -2398,7 +2402,7 @@ class WaveService extends OrderBaseService { where, attributes: [ 'id', 'store_id', 'logistics_name', - 'items_hash', 'items', 'items_total', + 'items_hash', 'items', 'items_total', 'items_weight', 'post_status', 'pick_status', 'outbound_status', 'create_at', ], raw: true, @@ -2521,6 +2525,9 @@ class WaveService extends OrderBaseService { if (!last_order_time || o.create_at > last_order_time) last_order_time = o.create_at; } + // 同组订单 items_hash 相同,重量一致,取首单即可 + const firstOrder = g.orders[0] || {}; + list.push({ item_detail: itemSummary, item_detail_machine: itemDetailMachine, @@ -2529,6 +2536,7 @@ class WaveService extends OrderBaseService { group: g.orders.length, group_count: g.orders.length, items_total, + items_weight: firstOrder.items_weight != null ? Number(firstOrder.items_weight) : null, store_id: store_ids.length === 1 ? store_ids[0] : 0, store_ids, logistics_name: logisticsName, @@ -3939,6 +3947,8 @@ class WaveService extends OrderBaseService { tracking_no: this.resolveWaveStrategyFallbackTrackingNo(normalizedOrderRow), items_count: normalizedOrderRow.items_count ?? null, items_total: normalizedOrderRow.items_total ?? null, + items_weight: normalizedOrderRow.items_weight != null ? Number(normalizedOrderRow.items_weight) : null, + weight_type: this.formatWeightTypeLabel(normalizedOrderRow.weight_type), sys_logistics_name: this.resolveWaveStrategyFallbackSysLogisticsName(normalizedOrderRow), store_name: this.resolveWaveStrategyFallbackStoreName(normalizedOrderRow), province: normalizedOrderRow.province ?? null, @@ -5782,6 +5792,62 @@ class WaveService extends OrderBaseService { }); } finally { await this.clearWaveStrategyQuickScanWarehouseLock(warehouseId, normalizedTaskId); + + // 方案 C:扫描完成后检查是否有新订单需要扫描 + try { + const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + const subjectConfig = await this.getWarehouseSubjectConfig(warehouseId); + const currentVersion = this.normalizeWaveStrategyQuickScanVersion( + this.getWarehouseSubjectConfigValue(subjectConfig, 'wave_strategy_version') + ); + + const pendingCount = await orderModel.count({ + where: { + warehouse_id: warehouseId, + step: { [Op.ne]: 0 }, + wave_id: 0, + intercept_status: 'none', + lock_status: 'none', + print_status: { [Op.ne]: 'fin' }, + [Op.or]: [ + { wave_strategy_version: { [Op.ne]: currentVersion } }, + { wave_strategy_version: { [Op.is]: null } }, + ], + }, + }); + + if (pendingCount > 0) { + this.ctx.logger.info( + '[wave.runWaveStrategyQuickScanTask] 检测到遗漏订单,触发新一轮扫描', + { + warehouseId, + previousTaskId: normalizedTaskId, + pendingCount, + } + ); + + setImmediate(() => { + this.submitWaveStrategyQuickScanForWarehouse(warehouseId).catch(error => { + this.ctx.logger.warn( + '[wave.runWaveStrategyQuickScanTask] 触发新一轮扫描失败', + { + warehouseId, + error: error && error.message ? error.message : `${error}`, + } + ); + }); + }); + } + } catch (checkError) { + this.ctx.logger.warn( + '[wave.runWaveStrategyQuickScanTask] 遗漏订单检查失败', + { + warehouseId, + taskId: normalizedTaskId, + error: checkError && checkError.message ? checkError.message : `${checkError}`, + } + ); + } } } diff --git a/app/service/systemMethods/print.js b/app/service/systemMethods/print.js index 3c4c95b..5d9a100 100644 --- a/app/service/systemMethods/print.js +++ b/app/service/systemMethods/print.js @@ -255,6 +255,43 @@ class PrintService extends MainService { return Array.from(orderIdSet); } + /** + * 从自定义打印数据中提取订单ID列表。 + * 支持 order_ids / orderIds 数组以及单个 order_id / orderId 字段。 + * @param {Object} customData 自定义打印数据对象。 + * @return {Array} 去重后的订单ID列表。 + */ + collectOrderIdsFromCustomizeData(customData = {}) { + const normalizedData = customData && typeof customData === 'object' ? customData : {}; + const orderIdSet = new Set(); + + // 尝试读取 order_ids 数组 + if (Array.isArray(normalizedData.order_ids)) { + for (const id of normalizedData.order_ids) { + const num = Number(id || 0); + if (Number.isInteger(num) && num > 0) { + orderIdSet.add(num); + } + } + } + // 尝试读取 orderIds 数组 + if (Array.isArray(normalizedData.orderIds)) { + for (const id of normalizedData.orderIds) { + const num = Number(id || 0); + if (Number.isInteger(num) && num > 0) { + orderIdSet.add(num); + } + } + } + // 尝试读取单个 order_id / orderId + const singleId = Number(normalizedData.order_id || normalizedData.orderId || 0); + if (Number.isInteger(singleId) && singleId > 0) { + orderIdSet.add(singleId); + } + + return Array.from(orderIdSet); + } + /** * 规范化快递打印平台编码,兼容常见别名。 * @param {Object} payload 入参。 @@ -810,6 +847,7 @@ class PrintService extends MainService { /** * 发送打印任务到打印电脑。 + * 本方法不做打印锁状态校验,不阻止重复打印请求。 * 仅在 type=customize 时要求 printer、template、page_width、page_height、template_content。 * @param {Object} _data 打印请求参数 * @param {string} [_data.printer] 打印机名称(type=customize 必填,type=express 忽略) @@ -821,7 +859,7 @@ class PrintService extends MainService { * @param {string} [_data.computerId] 打印电脑 ID(customize 必填,express 忽略) * @param {string} [_data.timestamp] 业务时间戳(express 忽略) * @param {number} [_data.count] 打印份数(express 忽略) - * @return {Promise} 统一返回结构 + * @return {Promise} 统一返回结构 */ async send(_data) { const { ctx } = this; @@ -869,16 +907,22 @@ class PrintService extends MainService { waveGroupsCount: Array.isArray(data && data.waveGroups) ? data.waveGroups.length : 0, }); } + // 从自定义打印数据中尝试提取关联的配送订单ID,用于后续同步 print_status + const customizeOrderIds = type !== 'express' ? this.collectOrderIdsFromCustomizeData(data) : []; let printRecord = null; if (type !== 'express') { // 生成打印编号并记录到数据库 try { + const printRecordData = { template, data }; + if (customizeOrderIds.length > 0) { + printRecordData.order_ids = customizeOrderIds; + } printRecord = await ctx.model.PrintRecord.create(this.buildPendingPrintRecordPayload({ warehouse_id: warehouseId, computer_id: computerId, printer, type, - data: { template, data }, + data: printRecordData, })); this.ctx.logger.info('[print.send] PrintRecord 创建成功', { warehouseId, @@ -1198,6 +1242,22 @@ class PrintService extends MainService { // 发送成功后更新打印记录状态 if (res.status === 'success') { await printRecord.update(this.buildSentPrintRecordUpdatePayload()); + // 同步更新关联配送订单的 print_status 为 'fin' + if (customizeOrderIds.length > 0) { + const updateResult = await this.updateOrderPrintStatusByCallback({ + warehouseId, + orderIds: customizeOrderIds, + result: 'success', + }); + if (!updateResult.success) { + this.ctx.logger.error('[print.send] 同步订单 print_status 失败', { + warehouseId, + type, + orderIdsCount: customizeOrderIds.length, + reason: updateResult.errorMessage, + }); + } + } this.ctx.logger.info('[print.send] 最终返回 success', { warehouseId, type, @@ -2110,6 +2170,7 @@ class PrintService extends MainService { : []; const generatedTaskCodes = []; const createdPrintRecordIds = []; + for (const waveGroup of waveGroups) { const platforms = Array.isArray(waveGroup && waveGroup.platforms) ? waveGroup.platforms : []; for (const platformGroup of platforms) { diff --git a/app/service/systemMethods/setting/packageMaterial.js b/app/service/systemMethods/setting/packageMaterial.js index 928e1d5..384c4ac 100644 --- a/app/service/systemMethods/setting/packageMaterial.js +++ b/app/service/systemMethods/setting/packageMaterial.js @@ -11,9 +11,9 @@ class packageMaterialService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'get,list,create,update,delete'; + const _noNeedRight = 'get,list,create,update,delete,search'; const _noNeedLog = '*'; - const _noNeedAuth = 'get,list,create,update,delete'; + const _noNeedAuth = 'get,list,create,update,delete,search'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -148,6 +148,18 @@ class packageMaterialService extends MainService { return await this.get(data); } + /** + * 快捷搜索包材,按关键词模糊匹配编码和名称。 + * + * @param {Object} [data={}] 请求参数 + * @param {string} [data.keyword] 搜索关键词 + * @return {Promise} data 为搜索结果数组,最多 50 条 + */ + async search(data = {}) { + const result = await this.service.systems.setting.packageMaterial.search(data); + return this.success('ok', result); + } + /** * 创建包材。 * diff --git a/app/service/systemMethods/stock/warehouse.js b/app/service/systemMethods/stock/warehouse.js index ea2e5ec..32d7f03 100644 --- a/app/service/systemMethods/stock/warehouse.js +++ b/app/service/systemMethods/stock/warehouse.js @@ -69,6 +69,10 @@ class WarehouseService extends MainService { bucket: 'prohibited', field: 'id', }, + has_bound_item: { + bucket: 'storeOutStock', + field: 'stock_id', + }, }, }); const result = await service.systems.stockStore.getWarehouseStock(where, pagination); @@ -99,6 +103,10 @@ class WarehouseService extends MainService { bucket: 'prohibited', field: 'id', }, + has_bound_item: { + bucket: 'storeOutStock', + field: 'stock_id', + }, }, }); @@ -374,7 +382,6 @@ class WarehouseService extends MainService { inbound_min_days, outbound_min_days, remaining_threshold_days, - barcode, } = data || {}; try { const result = await service.systems.stockStore.saveWarehouseStock({ @@ -417,7 +424,6 @@ class WarehouseService extends MainService { inbound_min_days, outbound_min_days, remaining_threshold_days, - barcode, }); return this.success('ok', { data: result, code: 200 }); } catch (error) { diff --git a/app/service/systems/delivery_order.js b/app/service/systems/delivery_order.js index 5c5e0f9..11de358 100644 --- a/app/service/systems/delivery_order.js +++ b/app/service/systems/delivery_order.js @@ -14,7 +14,6 @@ const DELIVERY_ORDER_STEP = Object.freeze({ const DEFAULT_STORE_SUBJECT_CONFIG = Object.freeze({ max_notice_webhook_count: 5, - auto_grouping_enabled: false, default_express_code: 'STO', default_platform_code: 'TB', }); @@ -320,7 +319,11 @@ class DeliveryOrderService extends Service { * @return {Promise} 平台快照。 */ async resolvePlatformSnapshot(sourcePlatformCode, storeSubjectConfig, info = {}, operationLogs = []) { - const platformList = await this.ctx.service.systems.platform.getPlatformList(); + const platformList = await this.ctx.service.systems.platform.getPlatformList( + false, + false, + info.warehouseId + ); const externalCode = String(sourcePlatformCode || '').trim(); const matchedPlatform = this.findPlatformOptionByCode(platformList, externalCode); @@ -1825,20 +1828,22 @@ class DeliveryOrderService extends Service { } /** - * 执行自动加团逻辑(仅团购)。 + * 执行自动加团逻辑(仅团购),从仓库级配置读取 auto_grouping_enabled。 * * @param {Object} context 异步处理上下文。 + * @param {number} context.storeId 货主ID。 + * @param {number} context.warehouseId 仓库ID。 * @return {Promise} 无返回值。 */ async runAutoGrouping(context) { const { ctx } = this; - const storeSubjectConfig = await this.getStoreSubjectConfig(context.storeId); - if (!storeSubjectConfig || !storeSubjectConfig.auto_grouping_enabled) { + const warehouseSubjectConfig = await this.getStoreSubjectConfig(context.warehouseId); + if (!warehouseSubjectConfig || !warehouseSubjectConfig.auto_grouping_enabled) { return; } - const maxWaveQuantity = Number(storeSubjectConfig.max_wave_quantity || 0) > 0 - ? Number(storeSubjectConfig.max_wave_quantity) + const maxWaveQuantity = Number(warehouseSubjectConfig.max_wave_quantity || 0) > 0 + ? Number(warehouseSubjectConfig.max_wave_quantity) : 500; const structure = this.buildAutoGroupingStructure(context); if (!structure) { diff --git a/app/service/systems/entry_order.js b/app/service/systems/entry_order.js index 88c4e50..c44d69a 100644 --- a/app/service/systems/entry_order.js +++ b/app/service/systems/entry_order.js @@ -111,8 +111,11 @@ class entryOrderService extends Service { const expectedTotalOrderLines = Number(totalOrderLines) || 0; if (lineCount === expectedTotalOrderLines) { - // 所有行数接收完成 - await this.received(orderId, warehouseId, storeId, transaction); + // 所有明细行已插入完毕,将状态从 CREATING 更新为 PENDING(等待收货) + await app.model.EntryOrder.update( + { order_status: 'PENDING', updated_at: new Date() }, + { where: { id: orderId, warehouse_id: warehouseId, store_id: storeId }, transaction } + ); } // 提交事务 @@ -121,13 +124,13 @@ class entryOrderService extends Service { if (lineCount === expectedTotalOrderLines) { return { success: true, - message: '入库单接收完毕', + message: '入库单创建完成,等待收货', data: { entryOrderId: orderId, entryOrderCode: orderCode, createTime: new Date(), warehouseCode, - status: 'COMPLETED', + status: 'PENDING', }, }; } @@ -135,13 +138,13 @@ class entryOrderService extends Service { // 部分接收或等待接收 return { success: true, - message: '入库单接收中', + message: '入库单创建中', data: { entryOrderId: orderId, entryOrderCode: orderCode, createTime: new Date(), warehouseCode, - status: 'PARTIAL_RECEIVED', + status: 'CREATING', }, }; diff --git a/app/service/systems/express_platform.js b/app/service/systems/express_platform.js index 4ca7be1..17ed35e 100644 --- a/app/service/systems/express_platform.js +++ b/app/service/systems/express_platform.js @@ -961,6 +961,39 @@ class ExpressPlatformService extends MainService { }; }); break; + case 'QT': + case 'OTHER': + successUpdates = (result.results || []).map(item => { + const [ warehouse_id, order_id, business_key ] = String(item.orderno || '').split('_'); + const waybillCode = String(item.logisticno || item.waybill_code || '').trim(); + return { + warehouse_id, + order_id, + business_key, + waybill_code: waybillCode, + orderExpressValues: { + waybill_code: waybillCode, + printinfo: item.printinfo, + signature: item.signature, + encryptprintinfo: item.encryptprintinfo, + encryptedtoken: item.encryptedtoken, + ...this.buildOrderExpressVerPatch([ item.ver ]), + 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; } diff --git a/app/service/systems/order_express.js b/app/service/systems/order_express.js index d0bea1e..f787f0b 100644 --- a/app/service/systems/order_express.js +++ b/app/service/systems/order_express.js @@ -141,7 +141,7 @@ class OrderExpressService extends Service { warehouse_id: warehouseId, delete_at: null, }, - attributes: [ 'id', 'order_id', 'waybill_code', 'warehouse_id', 'delete_at' ], + attributes: [ 'id', 'order_id', 'waybill_code', 'warehouse_id', 'delete_at', 'package_material_id' ], raw: true, }); @@ -953,6 +953,105 @@ class OrderExpressService extends Service { ); } + /** + * 写入或更新商品结构-包材绑定关系记录。 + * + * 若订单的 items_hash 不存在则跳过;关系表写入失败不影响主流程。 + * + * @param {Object} params 绑定上下文参数。 + * @param {number} params.orderId 订单ID。 + * @param {string} params.waybillCode 运单号。 + * @param {number} params.packageMaterialId 包材ID。 + * @param {string} params.packageMaterialCode 包材编码。 + * @param {string} params.packageMaterialName 包材名称。 + * @param {number} params.warehouseId 仓库ID。 + * @return {Promise} + */ + async _upsertPackageMaterialItemRelation({ orderId, waybillCode, packageMaterialId, packageMaterialCode, packageMaterialName, warehouseId }) { + const { ctx } = this; + try { + // 1. 查订单的 items_hash / items_crc + const orderDeliveryFactory = ctx.model && ctx.model.OrderDeliveryFactory; + if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') return; + + const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(warehouseId); + const orderRow = await orderDeliveryModel.findOne({ + where: { id: orderId, warehouse_id: warehouseId }, + attributes: ['items_hash', 'items_crc'], + raw: true, + }); + if (!orderRow || !orderRow.items_hash) return; + + const { items_hash: itemsHash, items_crc: itemsCrc } = orderRow; + + // 2. 查关系表 + const relationModel = ctx.model && ctx.model.PackageMaterialItemRelation; + if (!relationModel) return; + + const existing = await relationModel.findOne({ + where: { + warehouse_id: warehouseId, + items_hash: itemsHash, + items_crc: itemsCrc, + package_material_id: packageMaterialId, + delete_at: null, + }, + raw: true, + }); + + // 3. 查包材完整快照 + const packageMaterialModel = ctx.model && ctx.model.PackageMaterial; + const materialRow = packageMaterialModel + ? await packageMaterialModel.findOne({ where: { id: packageMaterialId }, raw: true }) + : null; + + const snapshot = { + package_material_code: String(packageMaterialCode || '').trim(), + package_material_name: String(packageMaterialName || '').trim(), + package_material_spec: String(materialRow && materialRow.spec || '').trim(), + package_material_type: String(materialRow && materialRow.material_type || '').trim(), + length: Number(materialRow && materialRow.length || 0), + width: Number(materialRow && materialRow.width || 0), + height: Number(materialRow && materialRow.height || 0), + weight: Number(materialRow && materialRow.weight || 0), + }; + + const userId = ctx.user && ctx.user.id ? Number(ctx.user.id) : null; + const now = new Date(); + + if (existing) { + await relationModel.update({ + bind_count: (Number(existing.bind_count) || 0) + 1, + last_order_id: orderId, + last_waybill_code: waybillCode, + last_bind_user_id: userId, + last_bind_at: now, + is_active: 1, + ...snapshot, + }, { + where: { id: existing.id }, + }); + } else { + await relationModel.create({ + warehouse_id: warehouseId, + items_hash: itemsHash, + items_crc: itemsCrc, + package_material_id: packageMaterialId, + bind_count: 1, + last_order_id: orderId, + last_waybill_code: waybillCode, + last_bind_user_id: userId, + last_bind_at: now, + is_active: 1, + ...snapshot, + }); + } + } catch (err) { + // 关系表写入失败不影响主流程 + ctx && ctx.logger && ctx.logger.error(`[packageMaterialRelation] upsert failed: ${err.message}`); + } + } + /** * 绑定订单快递记录的包材信息。 * @param {Object} payload 入参对象。 @@ -989,10 +1088,24 @@ class OrderExpressService extends Service { }); const affectedRows = Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0); + const isSameMaterial = Number(orderExpressRow.package_material_id) === Number(materialRow.id); + if (!Number.isFinite(affectedRows) || affectedRows <= 0) { - throw this.createBusinessError('绑定包材失败', 500); + if (!isSameMaterial) { + throw this.createBusinessError('绑定包材失败', 500); + } + // 同一包材幂等:跳过 update 报错,继续走关系表 } + await this._upsertPackageMaterialItemRelation({ + orderId: normalizedOrderId, + waybillCode: normalizedWaybillCode, + packageMaterialId: Number(materialRow.id), + packageMaterialCode: String(materialRow.material_code || '').trim(), + packageMaterialName: String(materialRow.material_name || '').trim(), + warehouseId, + }); + return { order_id: Number(orderExpressRow.order_id), waybill_code: String(orderExpressRow.waybill_code || '').trim(), @@ -1001,6 +1114,433 @@ class OrderExpressService extends Service { package_material_code: String(materialRow.material_code || '').trim(), }; } + + /** + * 根据运单号绑定包材。 + * + * 仅凭运单号即可绑定包材,无需传入订单ID。 + * 先按运单号 + 仓库ID 查询有效运单记录,再按包材编码查询启用中的包材, + * 最后更新运单记录的包材字段。 + * + * 支持团购波次自动感知: + * - 非团购订单(wave_id=0 或 wave_type≠1):仅绑定当前运单的包材,行为与旧版一致。 + * - 团购波次(wave_type=1):自动将同一波次下、相同快递业务键(business_key)的 + * 所有运单批量绑定相同的包材,实现一键补齐。 + * + * @param {Object} [payload={}] 请求参数。 + * @param {string} payload.waybillCode 运单号。 + * @param {string} payload.packageMaterialCode 包材编码。 + * @return {Promise} 单条绑定返回 {order_id, waybill_code, package_material_id, package_material_name_snapshot, package_material_code}; + * 团购批量绑定返回 {wave_id, wave_no, business_key, order_id, waybill_code, package_material_id, package_material_code, package_material_name_snapshot, bind_count, bound_waybills, store_name, sys_logistics_name}。 + */ + async bindExpressPackageMaterialByWaybill(payload = {}) { + const requestData = payload && typeof payload === 'object' ? payload : {}; + const { + waybillCode, + packageMaterialCode, + } = requestData; + + const normalizedWaybillCode = this.normalizeWaybillCode(waybillCode); + const normalizedPackageMaterialCode = this.normalizePackageMaterialCode(packageMaterialCode); + const warehouseId = this.getCurrentWarehouseId(); + + // 按运单号 + 仓库ID 查询有效运单记录 + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; + if (!orderExpressModel || typeof orderExpressModel.findOne !== 'function') { + throw this.createBusinessError('运单模型未初始化', 500); + } + + const orderExpressRow = await orderExpressModel.findOne({ + where: { + waybill_code: normalizedWaybillCode, + warehouse_id: warehouseId, + delete_at: null, + }, + attributes: ['id', 'order_id', 'waybill_code', 'warehouse_id', 'delete_at', 'package_material_id', 'business_key'], + raw: true, + }); + + if (!orderExpressRow) { + throw this.createBusinessError('运单号不存在', 404); + } + + // 查询启用中的包材 + const materialRow = await this.findActivePackageMaterialByCode(normalizedPackageMaterialCode, warehouseId); + + // --- 团购波次自动感知 --- + // 尝试查询运单所属订单是否属于团购波次 + const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; + if (orderDeliveryFactory && typeof orderDeliveryFactory.getCurrentModel === 'function') { + try { + const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(warehouseId); + const orderRow = await orderDeliveryModel.findOne({ + where: { id: Number(orderExpressRow.order_id), warehouse_id: warehouseId }, + attributes: ['id', 'wave_id', 'wave_no'], + raw: true, + }); + + if (orderRow) { + const waveId = Number(orderRow.wave_id || 0); + + if (waveId > 0) { + // 查询波次类型 + const waveBatchModel = this.ctx.model && this.ctx.model.WaveBatch; + if (waveBatchModel && typeof waveBatchModel.findOne === 'function') { + const waveRow = await waveBatchModel.findOne({ + where: { wave_id: waveId, warehouse_id: warehouseId }, + attributes: ['wave_id', 'wave_no', 'wave_type'], + raw: true, + }); + + // 团购波次(wave_type=1)→ 按业务键分类批量绑定 + if (waveRow && Number(waveRow.wave_type) === 1) { + return await this._bindWavePackageMaterialByBusinessKey({ + waveId, + waveNo: String(waveRow.wave_no || ''), + businessKey: orderExpressRow.business_key ?? null, + packageMaterialId: Number(materialRow.id), + packageMaterialCode: normalizedPackageMaterialCode, + packageMaterialName: String(materialRow.material_name || '').trim(), + warehouseId, + triggerOrderId: Number(orderExpressRow.order_id), + triggerWaybillCode: normalizedWaybillCode, + }); + } + } + } + } + } catch (_waveErr) { + // 波次查询失败时静默降级为单条绑定,保证向后兼容 + this.ctx && this.ctx.logger && this.ctx.logger.warn( + `[bindExpressPackageMaterialByWaybill] 团购波次检测失败,降级为单条绑定: ${_waveErr.message}` + ); + } + } + + // 非团购 → 单条绑定(保持现有逻辑) + return await this._bindSingleExpressPackageMaterial({ + orderExpressRow, + materialRow, + normalizedWaybillCode, + warehouseId, + }); + } + + /** + * 单条运单包材绑定(内部方法)。 + * + * 更新单条运单记录的包材字段,并写入包材-商品结构关系表。 + * + * @param {Object} params 绑定上下文参数。 + * @param {Object} params.orderExpressRow 运单记录。 + * @param {Object} params.materialRow 包材记录。 + * @param {string} params.normalizedWaybillCode 规范化后的运单号。 + * @param {number} params.warehouseId 仓库ID。 + * @return {Promise} 绑定后的结果快照,包含 order_id、waybill_code、package_material_id、package_material_name_snapshot、package_material_code。 + */ + async _bindSingleExpressPackageMaterial({ orderExpressRow, materialRow, normalizedWaybillCode, warehouseId }) { + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; + + // 更新运单记录的包材字段 + const updateResult = await orderExpressModel.update({ + package_material_id: Number(materialRow.id), + package_material_name_snapshot: String(materialRow.material_name || '').trim(), + }, { + where: { + id: Number(orderExpressRow.id), + delete_at: null, + }, + }); + + const affectedRows = Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0); + const isSameMaterial = Number(orderExpressRow.package_material_id) === Number(materialRow.id); + + if (!Number.isFinite(affectedRows) || affectedRows <= 0) { + if (!isSameMaterial) { + throw this.createBusinessError('绑定包材失败', 500); + } + // 同一包材幂等:跳过 update 报错,继续走关系表 + } + + await this._upsertPackageMaterialItemRelation({ + orderId: Number(orderExpressRow.order_id), + waybillCode: normalizedWaybillCode, + packageMaterialId: Number(materialRow.id), + packageMaterialCode: String(materialRow.material_code || '').trim(), + packageMaterialName: String(materialRow.material_name || '').trim(), + warehouseId, + }); + + return { + order_id: Number(orderExpressRow.order_id), + waybill_code: String(orderExpressRow.waybill_code || '').trim(), + package_material_id: Number(materialRow.id), + package_material_name_snapshot: String(materialRow.material_name || '').trim(), + package_material_code: String(materialRow.material_code || '').trim(), + }; + } + + /** + * 团购波次按快递业务键分类批量绑定包材(内部方法)。 + * + * 查询波次下所有订单,再按触发运单的 business_key 筛选出同分类的运单, + * 批量更新包材字段并写入关系表。 + * + * @param {Object} params 批量绑定上下文参数。 + * @param {number} params.waveId 波次ID。 + * @param {string} params.waveNo 波次号。 + * @param {string|null} params.businessKey 快递业务键,用于分类过滤。 + * @param {number} params.packageMaterialId 包材ID。 + * @param {string} params.packageMaterialCode 包材编码。 + * @param {string} params.packageMaterialName 包材名称。 + * @param {number} params.warehouseId 仓库ID。 + * @param {number} params.triggerOrderId 触发绑定的订单ID。 + * @param {string} params.triggerWaybillCode 触发绑定的运单号。 + * @return {Promise} 团购批量绑定结果,含 wave_id、wave_no、business_key、order_id、waybill_code、package_material_id、package_material_code、package_material_name_snapshot、bind_count、bound_waybills、store_name、sys_logistics_name。 + */ + async _bindWavePackageMaterialByBusinessKey({ + waveId, + waveNo, + businessKey, + packageMaterialId, + packageMaterialCode, + packageMaterialName, + warehouseId, + triggerOrderId, + triggerWaybillCode, + }) { + // 1. 查询波次下所有订单 + const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; + if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') { + throw this.createBusinessError('订单模型未初始化', 500); + } + + const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(warehouseId); + const waveOrders = await orderDeliveryModel.findAll({ + where: { wave_id: waveId, warehouse_id: warehouseId }, + attributes: ['id'], + raw: true, + }); + + if (!waveOrders || waveOrders.length === 0) { + throw this.createBusinessError('波次下未找到订单', 404); + } + + const orderIds = waveOrders.map(o => Number(o.id)); + + // 2. 查询这些订单下相同 business_key 的所有有效运单 + const { Op } = this.app.Sequelize; + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; + if (!orderExpressModel || typeof orderExpressModel.findAll !== 'function') { + throw this.createBusinessError('运单模型未初始化', 500); + } + + // business_key 为 null 时需特殊处理 Sequelize 查询 + const businessKeyWhere = (businessKey === null || businessKey === undefined) + ? { [Op.is]: null } + : businessKey; + + const expressRows = await orderExpressModel.findAll({ + where: { + order_id: { [Op.in]: orderIds }, + business_key: businessKeyWhere, + delete_at: null, + }, + attributes: ['id', 'order_id', 'waybill_code', 'business_key', 'package_material_id'], + raw: true, + }); + + if (!expressRows || expressRows.length === 0) { + // 波次下无同 business_key 运单 → 降级为仅绑定触发运单 + const orderExpressRow = await orderExpressModel.findOne({ + where: { waybill_code: triggerWaybillCode, warehouse_id: warehouseId, delete_at: null }, + attributes: ['id', 'order_id', 'waybill_code', 'package_material_id'], + raw: true, + }); + if (!orderExpressRow) { + throw this.createBusinessError('运单号不存在', 404); + } + + const materialRow = { + id: packageMaterialId, + material_code: packageMaterialCode, + material_name: packageMaterialName, + }; + + return await this._bindSingleExpressPackageMaterial({ + orderExpressRow, + materialRow, + normalizedWaybillCode: triggerWaybillCode, + warehouseId, + }); + } + + const expressIds = expressRows.map(r => Number(r.id)); + + // 3. 先验证匹配记录是否存在,避免 MySQL 因值未变返回 affected_rows=0 导致误判 + const matchingCount = await orderExpressModel.count({ + where: { id: { [Op.in]: expressIds }, delete_at: null }, + }); + if (matchingCount === 0) { + throw this.createBusinessError('批量绑定包材失败,无有效运单记录', 500); + } + + // 4. 批量更新包材字段 + await orderExpressModel.update( + { + package_material_id: packageMaterialId, + package_material_name_snapshot: packageMaterialName, + }, + { + where: { id: { [Op.in]: expressIds }, delete_at: null }, + } + ); + + // 5. 逐条写入包材-商品结构关系表(失败不影响主流程) + for (const row of expressRows) { + await this._upsertPackageMaterialItemRelation({ + orderId: Number(row.order_id), + waybillCode: String(row.waybill_code || '').trim(), + packageMaterialId, + packageMaterialCode, + packageMaterialName, + warehouseId, + }); + } + + // 6. 写入操作日志 + await this._writePackageMaterialActionLog({ + waveId, + waveNo, + businessKey, + packageMaterialCode, + packageMaterialName, + warehouseId, + bindCount: expressRows.length, + totalOrderCount: orderIds.length, + }); + + // 7. 获取货主名称与系统快递名称 + const storeName = await this._getStoreName(orderIds, warehouseId); + const sysLogisticsName = await this._getWaveSysLogisticsName(orderIds, warehouseId); + + // 8. 构建返回结构 + return { + wave_id: waveId, + wave_no: waveNo, + business_key: businessKey, + order_id: triggerOrderId, + waybill_code: triggerWaybillCode, + package_material_id: packageMaterialId, + package_material_code: packageMaterialCode, + package_material_name_snapshot: packageMaterialName, + bind_count: expressRows.length, + bound_waybills: expressRows.map(r => ({ + order_id: Number(r.order_id), + waybill_code: String(r.waybill_code || '').trim(), + })), + store_name: storeName, + sys_logistics_name: sysLogisticsName, + }; + } + + /** + * 写入包材绑定操作日志到 wms_wave_pick_action_log(内部方法)。 + * + * @param {Object} params 日志参数。 + * @param {number} params.waveId 波次ID。 + * @param {string} params.waveNo 波次号。 + * @param {string|null} params.businessKey 快递业务键。 + * @param {string} params.packageMaterialCode 包材编码。 + * @param {string} params.packageMaterialName 包材名称。 + * @param {number} params.warehouseId 仓库ID。 + * @param {number} params.bindCount 绑定运单数。 + * @param {number} params.totalOrderCount 波次下订单总数。 + * @return {Promise} 无返回值。 + */ + async _writePackageMaterialActionLog({ + waveId, + waveNo, + businessKey, + packageMaterialCode, + packageMaterialName, + warehouseId, + bindCount, + totalOrderCount, + }) { + const ctxUser = this.ctx && this.ctx.user ? this.ctx.user : {}; + const operatorId = Number(ctxUser.employees_id || ctxUser.id || 0); + const operatorName = String( + ctxUser.employees_name || ctxUser.name || 'system' + ).trim(); + + const requestId = `bind_pm_${warehouseId}_${waveId}_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`; + + await this.ctx.model.query( + `INSERT INTO wms_wave_pick_action_log ( + task_id, + warehouse_id, + wave_id, + order_id, + sku_id, + location_id, + box_no, + cart_id, + qty_delta, + action_type, + request_id, + operator_id, + device_id, + seq_no, + snapshot + ) VALUES ( + :taskId, + :warehouseId, + :waveId, + :orderId, + :skuId, + :locationId, + :boxNo, + :cartId, + :qtyDelta, + :actionType, + :requestId, + :operatorId, + :deviceId, + :seqNo, + :snapshot + )`, + { + replacements: { + taskId: 0, + warehouseId: warehouseId || 0, + waveId, + orderId: null, + skuId: null, + locationId: null, + boxNo: null, + cartId: null, + qtyDelta: 0, + actionType: 'bind_package_material', + requestId, + operatorId, + deviceId: null, + seqNo: 1, + snapshot: JSON.stringify({ + wave_id: waveId, + wave_no: waveNo || '', + business_key: businessKey, + package_material_code: packageMaterialCode, + package_material_name: packageMaterialName, + bind_count: bindCount, + total_order_count: totalOrderCount, + operator_name: operatorName, + }), + }, + type: this.ctx.model.QueryTypes.INSERT, + } + ); + } } module.exports = OrderExpressService; diff --git a/app/service/systems/order_print.js b/app/service/systems/order_print.js index f2bee5a..4665302 100644 --- a/app/service/systems/order_print.js +++ b/app/service/systems/order_print.js @@ -686,7 +686,7 @@ class OrderPrintSystemService extends OrderBaseService { const platformCode = this.resolvePrintPlatformCode(effectiveOrderRow, orderExpress); const templateSample = this.loadTemplateSampleByPlatform(platformCode, templateSampleCache); - orderPrintList.push(this.buildOrderPlatformPrintItem({ + orderPrintList.push(await this.buildOrderPlatformPrintItem({ orderRow: effectiveOrderRowWithWaveIndex, orderExpress, policyConfig, @@ -861,7 +861,7 @@ class OrderPrintSystemService extends OrderBaseService { const platformCode = this.resolvePrintPlatformCode(effectiveOrderRow, orderExpress); const templateSample = this.loadTemplateSampleByPlatform(platformCode, templateSampleCache); - orderPrintList.push(this.buildOrderPlatformPrintItem({ + orderPrintList.push(await this.buildOrderPlatformPrintItem({ orderRow: effectiveOrderRowWithWaveIndex, orderExpress, policyConfig, @@ -2652,9 +2652,9 @@ ${waveFilterSql} * @param {Object} payload.policyConfig 策略配置。 * @param {string} payload.platformCode 平台编码。 * @param {Object} payload.templateSample 模板样例。 - * @return {Object} 逐单打印中间态。 + * @return {Promise} 逐单打印中间态。 */ - buildOrderPlatformPrintItem(payload = {}) { + async buildOrderPlatformPrintItem(payload = {}) { const requestPayload = this.isPlainObject(payload) ? payload : {}; const orderRow = this.isPlainObject(requestPayload.orderRow) ? requestPayload.orderRow : {}; const orderExpress = this.isPlainObject(requestPayload.orderExpress) ? requestPayload.orderExpress : {}; @@ -2662,6 +2662,31 @@ ${waveFilterSql} const templateSample = this.isPlainObject(requestPayload.templateSample) ? requestPayload.templateSample : {}; const platformCode = String(requestPayload.platformCode || '').trim(); + // 查最匹配的包材名称(基于 items_hash) + let suggestedPackageMaterialName = ''; + const itemsHash = String(orderRow.items_hash || '').trim(); + const itemsCrc = Number(orderRow.items_crc || 0); + if (itemsHash) { + const relationModel = this.ctx.model && this.ctx.model.PackageMaterialItemRelation; + if (relationModel) { + const topMatch = await relationModel.findOne({ + where: { + warehouse_id: Number(orderRow.warehouse_id || 0), + items_hash: itemsHash, + items_crc: itemsCrc, + is_active: 1, + delete_at: null, + }, + order: [['bind_count', 'DESC']], + attributes: ['package_material_name'], + raw: true, + }); + if (topMatch && topMatch.package_material_name) { + suggestedPackageMaterialName = String(topMatch.package_material_name).trim(); + } + } + } + const orderId = Number(orderRow.id || 0); const waveId = Number(orderRow.wave_id || 0); const requestId = `wave_${waveId}_order_${orderId}`; @@ -2684,6 +2709,7 @@ ${waveFilterSql} requestId, taskId: requestId, documentId, + packageMaterialName: suggestedPackageMaterialName, }, }); const printData = this.extractSinglePlatformPrintData(printPayload); diff --git a/app/service/systems/order_storage_allocation.js b/app/service/systems/order_storage_allocation.js index 13b88d7..a8681a7 100644 --- a/app/service/systems/order_storage_allocation.js +++ b/app/service/systems/order_storage_allocation.js @@ -939,6 +939,7 @@ class OrderStorageAllocationService extends MainService { }); const shortageItems = []; + const storageRowErrors = []; let allocatedQuantityForOrder = 0; for (const orderItem of orderItems) { @@ -1094,6 +1095,23 @@ class OrderStorageAllocationService extends MainService { storageAllocationMap.set(storageRow.id, (storageAllocationMap.get(storageRow.id) || 0) + allocationQuantity); stockAllocationMap.set(stockId, (stockAllocationMap.get(stockId) || 0) + allocationQuantity); + const spaceId = toNumber(storageRow.space_id, 0); + if (!spaceId) { + storageRowErrors.push({ storage_id: storageRow.id, reason: '库位未设置' }); + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 库位无效,跳过该库存行', { + orderId, + orderItemId: toNumber(orderItem.id, 0), + stockId, + storageId: storageRow.id, + spaceId: storageRow.space_id, + }); + // 释放刚才 lockQuantity 加的锁,防止 locked_quantity 泄漏 + await ctx.service.systems.storage.index.unlockQuantity( + storageRow.id, allocationQuantity, { transaction } + ); + continue; + } + pickingRows.push({ order_id: orderId, order_item_id: toNumber(orderItem.id, 0), @@ -1137,17 +1155,25 @@ class OrderStorageAllocationService extends MainService { } const shortageMessage = buildShortageMessage(shortageItems); + + const spaceErrorMessage = storageRowErrors.length > 0 && shortageMessage + ? `库位未设置(storage_id:${storageRowErrors.map(e => e.storage_id).join(',')})` + : ''; + const finalShortageMessage = [shortageMessage, spaceErrorMessage].filter(Boolean).join('|'); + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 订单缺货信息汇总', { orderId, shortageItems, + storageRowErrors, shortageMessage, + finalShortageMessage, }); - const orderUpdateValues = shortageMessage + const orderUpdateValues = finalShortageMessage ? { storage_status: STORAGE_STATUS_ERROR, step: ORDER_STEP_EXCEPTION, - order_flag: shortageMessage, + order_flag: finalShortageMessage, updated_at: now, } : { @@ -1179,8 +1205,8 @@ class OrderStorageAllocationService extends MainService { order_id: orderId, storage_status: orderUpdateValues.storage_status, allocated_quantity: allocatedQuantityForOrder, - shortage_message: shortageMessage || '', - status: shortageMessage ? 'error' : 'success', + shortage_message: finalShortageMessage || '', + status: finalShortageMessage ? 'error' : 'success', }); writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 当前订单处理结束', { diff --git a/app/service/systems/pick.js b/app/service/systems/pick.js index 1c1256b..ef9c6a5 100644 --- a/app/service/systems/pick.js +++ b/app/service/systems/pick.js @@ -1931,6 +1931,91 @@ class PickSystemService extends Service { if (transactionRows.length > 0) { await ctx.model.StorageTransaction.bulkCreate(transactionRows, { transaction }); } + + // 释放 wms_stock_warehouse 锁定数量并写入 wms_stock_transaction 出库流水 + const stockQtyMap = new Map(); + for (const sRow of storageRows) { + const sid = Number(sRow.stock_id); + if (!sid || sid <= 0) continue; + const deduction = storageQtyMap.get(Number(sRow.id)) || 0; + if (deduction <= 0) continue; + stockQtyMap.set(sid, (stockQtyMap.get(sid) || 0) + deduction); + } + + if (stockQtyMap.size > 0) { + const stockIds = Array.from(stockQtyMap.keys()); + const stockWarehouseRows = await ctx.model.StockWarehouse.findAll({ + where: { + id: { [this.app.Sequelize.Op.in]: stockIds }, + warehouse_id: warehouseId, + }, + attributes: [ 'id', 'quantity', 'locked_quantity' ], + lock: transaction.LOCK.UPDATE, + raw: true, + transaction, + }); + + const stockWarehouseMap = new Map(); + for (const swRow of stockWarehouseRows) { + stockWarehouseMap.set(Number(swRow.id), swRow); + } + + for (const [ stockId, qty ] of stockQtyMap) { + const swRow = stockWarehouseMap.get(stockId); + if (!swRow) { + ctx.logger.warn(`[pick] stock_warehouse 记录不存在: ${stockId}`); + continue; + } + const currentLocked = Number(swRow.locked_quantity) || 0; + if (currentLocked < qty) { + throw this.createBusinessError( + `货主库存 ${stockId} 锁定数量不足:当前锁定 ${currentLocked},需释放 ${qty}`, + 400 + ); + } + await ctx.model.StockWarehouse.update({ + locked_quantity: this.app.Sequelize.literal(`locked_quantity - ${qty}`), + update_at: this.app.Sequelize.literal('CURRENT_TIMESTAMP'), + }, { + where: { + id: stockId, + locked_quantity: { [this.app.Sequelize.Op.gte]: qty }, + }, + transaction, + }); + } + + const stockTransactionRows = []; + for (const [ stockId, qty ] of stockQtyMap) { + const swRow = stockWarehouseMap.get(stockId); + if (!swRow) continue; + const sRow = storageRows.find(r => Number(r.stock_id) === stockId); + const beforeQty = Number(swRow.quantity) || 0; + const beforeLocked = Number(swRow.locked_quantity) || 0; + stockTransactionRows.push({ + transaction_type: 'OUTBOUND', + warehouse_id: warehouseId, + store_id: sRow ? Number(sRow.store_id) || 0 : 0, + stock_id: stockId, + quantity: qty, + before_quantity: beforeQty, + after_quantity: Math.max(0, beforeQty - qty), + before_locked_quantity: beforeLocked, + after_locked_quantity: Math.max(0, beforeLocked - qty), + order_type: 'PICK_OUTBOUND', + order_no: targetOrderIds.join(',').slice(0, 255), + order_id: taskId, + operator_id: String(operatorId), + operator_name: operatorName, + remark: '拣货完成出库-货主库存释放', + created_at: new Date(), + }); + } + + if (stockTransactionRows.length > 0) { + await ctx.model.StockTransaction.bulkCreate(stockTransactionRows, { transaction }); + } + } } const progress = await this.getTaskPickProgress(taskId, warehouseId, transaction); diff --git a/app/service/systems/pick_compensation.js b/app/service/systems/pick_compensation.js index 61247e0..9a1f4ad 100644 --- a/app/service/systems/pick_compensation.js +++ b/app/service/systems/pick_compensation.js @@ -314,9 +314,9 @@ class PickCompensationService extends MainService { * 2. SELECT wms_storage FOR UPDATE * 3. 校验 locked_quantity >= 解锁数量 * 4. UPDATE wms_storage 只解锁 locked_quantity(不扣减 quantity) - * 5. UPDATE wms_picking SET status='cancelled_released' - * - * 注意:本方法不写入 wms_storage_transaction。 + * 5. 按 stock_id 汇总,UPDATE wms_stock_warehouse 释放 locked_quantity(仅解锁,不扣减 quantity) + * 6. INSERT wms_stock_transaction(OUTBOUND, quantity=0, 仅记录锁定释放) + * 7. UPDATE wms_picking SET status='cancelled_released' * * @param {number} warehouseId 仓库ID。 * @param {Array} cancelledPickingRows 已取消订单关联的拣货记录列表。 @@ -375,7 +375,7 @@ class PickCompensationService extends MainService { id: { [app.Sequelize.Op.in]: storageIds }, warehouse_id: warehouseId, }, - attributes: [ 'id', 'locked_quantity' ], + attributes: [ 'id', 'locked_quantity', 'quantity', 'store_id', 'stock_id' ], lock: transaction.LOCK.UPDATE, raw: true, transaction, @@ -417,6 +417,95 @@ class PickCompensationService extends MainService { transaction, }); + // 释放 wms_stock_warehouse 锁定数量(仅解锁,不扣减 quantity)并写入 wms_stock_transaction 流水 + const stockQtyMap = new Map(); + for (const sRow of storageRows) { + const sid = Number(sRow.stock_id); + if (!sid || sid <= 0) continue; + const deduction = storageQtyMap.get(Number(sRow.id)) || 0; + if (deduction <= 0) continue; + stockQtyMap.set(sid, (stockQtyMap.get(sid) || 0) + deduction); + } + + if (stockQtyMap.size > 0) { + const stockIds = Array.from(stockQtyMap.keys()); + const stockWarehouseRows = await ctx.model.StockWarehouse.findAll({ + where: { + id: { [app.Sequelize.Op.in]: stockIds }, + warehouse_id: warehouseId, + }, + attributes: [ 'id', 'quantity', 'locked_quantity' ], + lock: transaction.LOCK.UPDATE, + raw: true, + transaction, + }); + + const stockWarehouseMap = new Map(); + for (const swRow of stockWarehouseRows) { + stockWarehouseMap.set(Number(swRow.id), swRow); + } + + for (const [ stockId, qty ] of stockQtyMap) { + const swRow = stockWarehouseMap.get(stockId); + if (!swRow) { + ctx.logger.warn(`[pick-compensation-cancel] stock_warehouse 记录不存在: ${stockId}`); + continue; + } + const currentLocked = Number(swRow.locked_quantity) || 0; + if (currentLocked < qty) { + throw this.createBusinessError( + `货主库存 ${stockId} 锁定数量不足:当前锁定 ${currentLocked},需释放 ${qty}`, + 400 + ); + } + await ctx.model.StockWarehouse.update({ + locked_quantity: app.Sequelize.literal(`locked_quantity - ${qty}`), + update_at: app.Sequelize.literal('CURRENT_TIMESTAMP'), + }, { + where: { + id: stockId, + locked_quantity: { [app.Sequelize.Op.gte]: qty }, + }, + transaction, + }); + } + + const stockTransactionRows = []; + for (const [ stockId, qty ] of stockQtyMap) { + const swRow = stockWarehouseMap.get(stockId); + if (!swRow) continue; + const sRow = storageRows.find(r => Number(r.stock_id) === stockId); + const currentQty = Number(swRow.quantity) || 0; + const currentLocked = Number(swRow.locked_quantity) || 0; + stockTransactionRows.push({ + transaction_type: 'OUTBOUND', + warehouse_id: warehouseId, + store_id: sRow ? Number(sRow.store_id) || 0 : 0, + stock_id: stockId, + quantity: 0, + before_quantity: currentQty, + after_quantity: currentQty, + before_locked_quantity: currentLocked, + after_locked_quantity: Math.max(0, currentLocked - qty), + order_type: 'PICK_CANCEL_RELEASE', + order_no: normalizedConfirmedRows + .filter(r => Number(r.stock_id) === stockId) + .map(r => String(r.order_id)) + .join(',') + .slice(0, 255), + order_id: 0, + operator_id: 'system', + operator_name: 'system', + remark: '拣货取消-货主库存锁定释放', + created_at: new Date(), + }); + } + + if (stockTransactionRows.length > 0) { + await ctx.model.StockTransaction.bulkCreate(stockTransactionRows, { transaction }); + } + } + // Step 5: UPDATE wms_picking SET status='cancelled_released' const compensatedPickingIds = normalizedConfirmedRows.map(r => Number(r.id)); await ctx.model.query(` @@ -454,7 +543,9 @@ class PickCompensationService extends MainService { * 5. 查询 dispatch 表获取订单的 delivery_order_code 和 source_order_codes, * 为每个拣货记录 INSERT 一条 wms_storage_transaction(OUTBOUND, PICK_COMPENSATION), * 同一 storage 的多条记录共享相同的 before/after 数量 - * 6. UPDATE wms_picking SET status='fin_compensated' + * 6. 按 stock_id 汇总,UPDATE wms_stock_warehouse 释放 locked_quantity + * 7. INSERT wms_stock_transaction(OUTBOUND)记录货主库存变更 + * 8. UPDATE wms_picking SET status='fin_compensated' * * @param {number} warehouseId 仓库ID。 * @param {Array} pickingRows 待补偿的拣货记录列表。 @@ -651,6 +742,91 @@ class PickCompensationService extends MainService { await ctx.model.StorageTransaction.bulkCreate(transactionRows, { transaction }); } + // 释放 wms_stock_warehouse 锁定数量并写入 wms_stock_transaction 出库流水 + const stockQtyMap = new Map(); + for (const sRow of storageRows) { + const sid = Number(sRow.stock_id); + if (!sid || sid <= 0) continue; + const deduction = storageQtyMap.get(Number(sRow.id)) || 0; + if (deduction <= 0) continue; + stockQtyMap.set(sid, (stockQtyMap.get(sid) || 0) + deduction); + } + + if (stockQtyMap.size > 0) { + const stockIds = Array.from(stockQtyMap.keys()); + const stockWarehouseRows = await ctx.model.StockWarehouse.findAll({ + where: { + id: { [app.Sequelize.Op.in]: stockIds }, + warehouse_id: warehouseId, + }, + attributes: [ 'id', 'quantity', 'locked_quantity' ], + lock: transaction.LOCK.UPDATE, + raw: true, + transaction, + }); + + const stockWarehouseMap = new Map(); + for (const swRow of stockWarehouseRows) { + stockWarehouseMap.set(Number(swRow.id), swRow); + } + + for (const [ stockId, qty ] of stockQtyMap) { + const swRow = stockWarehouseMap.get(stockId); + if (!swRow) { + ctx.logger.warn(`[pick-compensation] stock_warehouse 记录不存在: ${stockId}`); + continue; + } + const currentLocked = Number(swRow.locked_quantity) || 0; + if (currentLocked < qty) { + throw this.createBusinessError( + `货主库存 ${stockId} 锁定数量不足:当前锁定 ${currentLocked},需释放 ${qty}`, + 400 + ); + } + await ctx.model.StockWarehouse.update({ + locked_quantity: app.Sequelize.literal(`locked_quantity - ${qty}`), + update_at: app.Sequelize.literal('CURRENT_TIMESTAMP'), + }, { + where: { + id: stockId, + locked_quantity: { [app.Sequelize.Op.gte]: qty }, + }, + transaction, + }); + } + + const stockTransactionRows = []; + for (const [ stockId, qty ] of stockQtyMap) { + const swRow = stockWarehouseMap.get(stockId); + if (!swRow) continue; + const sRow = storageRows.find(r => Number(r.stock_id) === stockId); + const beforeQty = Number(swRow.quantity) || 0; + const beforeLocked = Number(swRow.locked_quantity) || 0; + stockTransactionRows.push({ + transaction_type: 'OUTBOUND', + warehouse_id: warehouseId, + store_id: sRow ? Number(sRow.store_id) || 0 : 0, + stock_id: stockId, + quantity: qty, + before_quantity: beforeQty, + after_quantity: Math.max(0, beforeQty - qty), + before_locked_quantity: beforeLocked, + after_locked_quantity: Math.max(0, beforeLocked - qty), + order_type: COMPENSATION_ORDER_TYPE, + order_no: confirmedOrderIds.join(',').slice(0, 255), + order_id: confirmedOrderIds[0] || 0, + operator_id: 'system', + operator_name: 'system', + remark: '拣货完成补偿出库-货主库存释放', + created_at: new Date(), + }); + } + + if (stockTransactionRows.length > 0) { + await ctx.model.StockTransaction.bulkCreate(stockTransactionRows, { transaction }); + } + } + // Step 6: UPDATE wms_picking SET status='fin_compensated' const compensatedPickingIds = normalizedConfirmedRows.map(r => Number(r.id)); await ctx.model.query(` diff --git a/app/service/systems/platform.js b/app/service/systems/platform.js index 14db0e8..8733b5b 100644 --- a/app/service/systems/platform.js +++ b/app/service/systems/platform.js @@ -704,36 +704,45 @@ class PlatformService extends Service { } /** - * 从数据库加载当前仓库的平台设置列表。 + * 从数据库加载平台设置列表。 * - * @param {number|string} warehouseId 仓库ID。 + * 始终加载 warehouse_id IS NULL 的系统级设置;若 warehouseId 有效,则同时加载对应仓库的仓库级设置。 + * 结果按 code 升序、warehouse_id 降序排列,确保仓库级设置在合并时优先于系统级设置。 + * + * @param {number|string} warehouseId 仓库ID,无效时仅加载系统级设置。 + * @param {boolean} [full=false] 是否返回全量字段。 * @return {Promise} 平台设置列表。 */ - async loadPlatformSettingListFromDatabase(warehouseId = 0) { - const normalizedWarehouseId = Number(warehouseId || 0); - if (!Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0) { - return []; - } - + async loadPlatformSettingListFromDatabase(warehouseId = 0, full = false) { const platformSettingModel = this.ctx.model && this.ctx.model.PlatformSetting; if (!platformSettingModel || typeof platformSettingModel.findAll !== 'function') { return []; } + const normalizedWarehouseId = Number(warehouseId || 0); + const isFull = [ true, 1, '1', 'true' ].includes(full); + const attributes = isFull + ? this.getPlatformSettingFullAttributes() + : [ 'id', 'code', 'platform_code', 'warehouse_id' ]; + + // 构建 where 条件:系统级设置(warehouse_id IS NULL)始终加载 + const whereConditions = [{ warehouse_id: null }]; + + // 仓库级设置:仅在 warehouseId 有效时加载 + if (Number.isFinite(normalizedWarehouseId) && normalizedWarehouseId > 0) { + whereConditions.push({ warehouse_id: normalizedWarehouseId }); + } + const rows = await platformSettingModel.findAll({ - attributes: [ 'id', 'code', 'platform_code', 'warehouse_id' ], + attributes, where: { - warehouse_id: normalizedWarehouseId, + [this.ctx.app.Sequelize.Op.or]: whereConditions, }, - order: [[ 'code', 'ASC' ]], + order: [[ 'code', 'ASC' ], [ 'warehouse_id', 'DESC' ]], raw: true, }); - if (!Array.isArray(rows)) { - return []; - } - - return rows; + return Array.isArray(rows) ? rows : []; } /** @@ -875,7 +884,17 @@ class PlatformService extends Service { const mergedItem = full ? this.normalizeFullPlatformSettingRow(row, platformMap) : this.normalizePlatformSettingRow(row, platformMap); - if (!mergedItem || seenCodeMap.has(mergedItem.code)) { + if (!mergedItem) { + continue; + } + + if (seenCodeMap.has(mergedItem.code)) { + const idx = mergedList.findIndex(item => + String(item.code || item.value || '').trim() === mergedItem.code && !item.is_system_setting + ); + if (idx !== -1) { + mergedList[idx] = mergedItem; + } continue; } @@ -942,13 +961,16 @@ class PlatformService extends Service { * * @param {boolean} [systemOnly=false] 是否仅返回系统基础平台列表。 * @param {boolean} [full=false] 是否返回全量字段。 + * @param {number|null} [warehouseId=null] 仓库ID,传入时使用外部值,否则从 ctx.user.store_id 内部获取。 * @return {Promise} 平台列表。 */ - async getPlatformList(systemOnly = false, full = false) { - const warehouseId = this.getCurrentWarehouseId(); + async getPlatformList(systemOnly = false, full = false, warehouseId = null) { + const resolvedWarehouseId = warehouseId !== null && warehouseId !== undefined + ? Number(warehouseId) + : this.getCurrentWarehouseId(); const isSystemOnly = [ true, 1, '1', 'true' ].includes(systemOnly); const isFull = [ true, 1, '1', 'true' ].includes(full); - const cacheKey = this.getPlatformListCacheKey(warehouseId, isSystemOnly, isFull); + const cacheKey = this.getPlatformListCacheKey(resolvedWarehouseId, isSystemOnly, isFull); try { const cachedList = await this.app.getCacheAsync(cacheKey); @@ -975,7 +997,7 @@ class PlatformService extends Service { const [ platformList, platformSettingList ] = await Promise.all([ this.loadPlatformListFromDatabase(isFull), - this.loadPlatformSettingListFromDatabase(warehouseId, isFull), + this.loadPlatformSettingListFromDatabase(resolvedWarehouseId, isFull), ]); const mergedList = this.buildMergedPlatformList(platformList, platformSettingList, isFull); diff --git a/app/service/systems/setting/packageMaterial.js b/app/service/systems/setting/packageMaterial.js index 9a348ac..a7431a1 100644 --- a/app/service/systems/setting/packageMaterial.js +++ b/app/service/systems/setting/packageMaterial.js @@ -606,6 +606,46 @@ class SettingPackageMaterialService extends Service { .filter(Boolean), }; } + + /** + * 快捷搜索包材,按关键词模糊匹配编码和名称。 + * + * @param {Object} [data={}] 请求参数 + * @param {string} [data.keyword] 搜索关键词,匹配 material_code 和 material_name + * @return {Promise} 返回对象包含 data 属性,值为匹配结果数组,最多 50 条 + */ + async search(data = {}) { + const { app } = this; + const { Op } = app.Sequelize; + const warehouseId = this.getCurrentStoreId(); + const { keyword } = data || {}; + + const whereCondition = { + warehouse_id: warehouseId, + status: 1, + }; + + if (keyword && String(keyword).trim()) { + const kw = String(keyword).trim(); + const like = `%${kw}%`; + whereCondition[Op.or] = [ + { material_code: { [Op.like]: like } }, + { material_name: { [Op.like]: like } }, + ]; + } + + const rows = await app.model.PackageMaterial.findAll({ + where: whereCondition, + attributes: [ 'id', 'material_code', 'material_name', 'material_type', 'spec', 'status' ], + order: [[ 'id', 'DESC' ]], + limit: 50, + raw: true, + }); + + return { + data: rows, + }; + } } module.exports = SettingPackageMaterialService; diff --git a/app/service/systems/setting/warehouse.js b/app/service/systems/setting/warehouse.js index 6abb3c9..f24e70f 100644 --- a/app/service/systems/setting/warehouse.js +++ b/app/service/systems/setting/warehouse.js @@ -43,6 +43,14 @@ const WAREHOUSE_SETTING_FIELDS = Object.freeze([ description: '控制团购波次最小抓取订单数量,默认 13', min: 1, }), + Object.freeze({ + key: 'auto_grouping_enabled', + name: '自动加团开关', + type: 'flag', + default: false, + required: false, + description: '是否启用订单创建后自动加入团购波次,默认 false(关闭)', + }), Object.freeze({ key: 'default_express_code', name: '默认快递编码', diff --git a/app/service/systems/stock_store.js b/app/service/systems/stock_store.js index b5862ce..b772bbd 100644 --- a/app/service/systems/stock_store.js +++ b/app/service/systems/stock_store.js @@ -1545,6 +1545,9 @@ class stockStoreService extends Service { const prohibitedQueryOptions = { where: {}, }; + const storeOutStockQueryOptions = { + where: {}, + }; // 添加默认条件 queryOptions.where[Op.and] = [{ warehouse_id: ctx.user.store_id, @@ -1558,9 +1561,12 @@ class stockStoreService extends Service { ]; barcodeQueryOptions.where[Op.and] = []; prohibitedQueryOptions.where[Op.and] = []; + storeOutStockQueryOptions.where[Op.and] = []; // 检测并处理条码查询条件 let hasBarcodeCondition = false; let hasProhibitedCondition = false; + let hasBoundItemCondition = false; + let boundItemValue = null; let barcodeCondition = null; let parsedBarcodeInput = null; @@ -1583,6 +1589,10 @@ class stockStoreService extends Service { bucket: 'prohibited', field: 'id', }, + has_bound_item: { + bucket: 'storeOutStock', + field: 'stock_id', + }, }, }); @@ -1622,12 +1632,18 @@ class stockStoreService extends Service { const barcodeDynamicConditions = bucketConditions.barcode || []; const prohibitedConditions = bucketConditions.prohibited || []; + const storeOutStockConditions = bucketConditions.storeOutStock || []; hasBarcodeCondition = Boolean(bucketFlags.barcode); hasProhibitedCondition = Boolean(bucketFlags.prohibited); + hasBoundItemCondition = Boolean(bucketFlags.storeOutStock); barcodeCondition = barcodeDynamicConditions[0] || null; parsedBarcodeInput = rawConditionsByField.barcode || null; + if (hasBoundItemCondition && rawConditionsByField.has_bound_item) { + boundItemValue = rawConditionsByField.has_bound_item.value; + } + if (dynamicConditions.length > 0) { queryOptions.where[Op.and].push({ [Op.and]: dynamicConditions, @@ -1644,6 +1660,27 @@ class stockStoreService extends Service { [Op.and]: prohibitedConditions, }); } + + if (storeOutStockConditions.length > 0) { + storeOutStockQueryOptions.where[Op.and].push({ + [Op.and]: storeOutStockConditions, + }); + } + + // has_bound_item 的「未绑定」场景:通过 NOT EXISTS 子查询在主表 where 上直接过滤 + const isBoundFalse = boundItemValue === false + || boundItemValue === 0 + || String(boundItemValue || '').trim().toLowerCase() === 'false' + || String(boundItemValue || '').trim() === '0' + || String(boundItemValue || '').trim().toLowerCase() === 'n'; + + if (hasBoundItemCondition && isBoundFalse) { + queryOptions.where[Op.and].push( + Sequelize.literal( + 'NOT EXISTS (SELECT 1 FROM wms_stock_store WHERE wms_stock_store.stock_id = stock_warehouse.id)' + ) + ); + } } // 如果有条码查询条件,先查询匹配的库存ID @@ -1752,39 +1789,53 @@ class stockStoreService extends Service { // 计算分页偏移量 const offset = (page - 1) * pageSize; + // 确定「外部商品绑定-已绑定」场景是否需要 INNER JOIN StockStore + const isBoundTrue = hasBoundItemCondition && ( + boundItemValue === true + || boundItemValue === 1 + || String(boundItemValue || '').trim().toLowerCase() === 'true' + || String(boundItemValue || '').trim() === '1' + || String(boundItemValue || '').trim().toLowerCase() === 'y' + ); + + // 构建 include 数组 + const includes = [ + ctx.model.StoreWarehouse.buildStoreStockInclude({ + warehouseId: ctx.user.store_id, + required: true, + attributes: [ 'store_remask' ], + }), + { + ...prohibitedQueryOptions, + model: ctx.model.ProhibitedType, + as: 'prohibited', + attributes: [ 'type_name' ], + required: hasProhibitedCondition, + }, + ]; + + if (isBoundTrue) { + includes.push({ + model: ctx.model.StockStore, + as: 'store_out_stock', + attributes: [], + required: true, + }); + } + // 执行查询:获取总数和数据 const [ total, data ] = await Promise.all([ // 获取总数 ctx.model.StockWarehouse.count({ where: queryOptions.where, - include: [ ctx.model.StoreWarehouse.buildStoreStockInclude({ - warehouseId: ctx.user.store_id, - required: true, - attributes: [ 'store_remask' ], - }), { - ...prohibitedQueryOptions, - model: ctx.model.ProhibitedType, - as: 'prohibited', - attributes: [ 'type_name' ], - required: hasProhibitedCondition, - }], + include: includes, distinct: true, }), // 获取分页数据 ctx.model.StockWarehouse.findAll({ ...queryOptions, - include: [ ctx.model.StoreWarehouse.buildStoreStockInclude({ - warehouseId: ctx.user.store_id, - required: true, - attributes: [ 'store_remask' ], - }), { - ...prohibitedQueryOptions, - model: ctx.model.ProhibitedType, - as: 'prohibited', - attributes: [ 'type_name' ], - required: hasProhibitedCondition, - }], + include: includes, limit: parseInt(pageSize), offset: parseInt(offset), distinct: true, // 确保去重 @@ -2682,7 +2733,6 @@ class stockStoreService extends Service { box_width, box_height, box_volume, box_remark, id, box_volume_m3, boxVolumeM3, shelf_life_days, inbound_min_days, outbound_min_days, remaining_threshold_days, - barcode, } = data; const normalizedVolume = volume ?? volume_cm3 ?? volumeCm3; const normalizedBoxVolume = box_volume ?? box_volume_m3 ?? boxVolumeM3; @@ -2804,38 +2854,6 @@ class stockStoreService extends Service { }, }); - // 6.5 处理条码:清理旧条码并写入新条码 - if (Object.prototype.hasOwnProperty.call(data, 'barcode')) { - const barcodesArr = Array.isArray(barcode) - ? barcode - : typeof barcode === 'string' - ? barcode.split(';') - : []; - const normalizedBarcodes = barcodesArr - .map(item => String(item || '').trim()) - .filter(item => item !== ''); - - // 删除该商品已有的所有条码 - await ctx.model.StockBarcode.destroy({ - where: { - stock_id: id, - warehouse_id: warehouseId, - }, - transaction, - }); - - // 写入新条码 - if (normalizedBarcodes.length > 0) { - const refData = normalizedBarcodes.map(item => ({ - stock_id: id, - barcode: item, - warehouse_id: warehouseId, - created_at: new Date(), - })); - await ctx.model.StockBarcode.bulkCreate(refData, { transaction }); - } - } - // 7. 提交事务 await transaction.commit(); @@ -2869,7 +2887,7 @@ class stockStoreService extends Service { prohibited_id, brand_name, managementFlags, enable_box_spec, box_unit, quantity_per_box, box_gross_weight, box_net_weight, box_length, - box_width, box_height, box_volume, box_remark, barcode, + box_width, box_height, box_volume, box_remark, } = data; // 1. 参数验证 @@ -2925,27 +2943,6 @@ class stockStoreService extends Service { try { // 2. 开启事务 const createdRecord = await ctx.model.StockWarehouse.create(insertData, transaction); - const barcodes_arr = Array.isArray(barcode) - ? barcode - : typeof barcode === 'string' - ? barcode.split(';') - : []; - const existingFileIds = []; - const toCreate = barcodes_arr - .map(item => String(item || '').trim()) - .filter(item => item && !existingFileIds.includes(item)); - // 批量操作 - const promises = []; - if (toCreate.length > 0) { - const refData = toCreate.map(item => ({ - stock_id: createdRecord.id, - barcode: item, - warehouse_id: warehouseId, - created_at: new Date(), - })); - promises.push(ctx.model.StockBarcode.bulkCreate(refData, { transaction })); - await Promise.all(promises); - } await service.systems.operationLog.createOperationLog({ businessType: 'stock', businessId: createdRecord.id, diff --git a/app/service/systems/store_warehouse.js b/app/service/systems/store_warehouse.js index 6723877..f47e75b 100644 --- a/app/service/systems/store_warehouse.js +++ b/app/service/systems/store_warehouse.js @@ -2158,11 +2158,11 @@ class SettingStoreWarehouseService extends Service { const { Op } = app.Sequelize; // 重复检测:按接口类型不同检查策略 let duplicateConfig = null; - if (isQimenWms && qimenAppKey && qimenCustomerId) { + if (isQimenWms && qimenAppKey && qimenWarehouseCode) { const duplicateWhere = { interface_type_id: Number(interfaceType.id || 0), qimen_app_key: qimenAppKey, - qimen_customer_id: qimenCustomerId, + qimen_warehouse_code: qimenWarehouseCode, }; if (config && config.id) { duplicateWhere.id = { [Op.ne]: config.id }; @@ -2173,7 +2173,7 @@ class SettingStoreWarehouseService extends Service { transaction, }); if (duplicateConfig) { - throw this.createError('该 AppKey 和客户ID 已绑定其他签约关系', 409); + throw this.createError('该 AppKey 和仓库编码 已绑定其他签约关系', 409); } } @@ -2276,7 +2276,7 @@ class SettingStoreWarehouseService extends Service { } catch (error) { await transaction.rollback(); if (error && error.name === 'SequelizeUniqueConstraintError') { - throw this.createError('接口配置已存在,请检查应用名或 AppKey / 客户ID 是否重复', 409); + throw this.createError('接口配置已存在,请检查应用名或 AppKey / 仓库编码 是否重复', 409); } if (error && error.name === 'SequelizeValidationError') { const message = error.errors && error.errors.length ? error.errors[0].message : '接口配置参数校验失败'; @@ -2506,15 +2506,16 @@ class SettingStoreWarehouseService extends Service { return null; } + const rawPolicyConfig = this.normalizePolicyConfig(row.policy_config, 'policy_config', { + allowEmpty: true, + sanitizeOnly: true, + }); const config = { id: row.id, store_id: row.store_id, warehouse_id: row.warehouse_id, auth_status: row.auth_status, - policy_config: this.normalizePolicyConfig(row.policy_config, 'policy_config', { - allowEmpty: true, - sanitizeOnly: true, - }), + policy_config: this.mergePolicyConfigWithDefaults(rawPolicyConfig), }; try { diff --git a/database/migrations/20260615143000-create-wms-package-material-item-relation.js b/database/migrations/20260615143000-create-wms-package-material-item-relation.js new file mode 100644 index 0000000..219e09a --- /dev/null +++ b/database/migrations/20260615143000-create-wms-package-material-item-relation.js @@ -0,0 +1,150 @@ +'use strict'; + +const TABLE_NAME = 'wms_package_material_item_relation'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME); + if (exists) return; + + await queryInterface.createTable(TABLE_NAME, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + items_hash: { + type: Sequelize.CHAR(32), + allowNull: false, + comment: '订单商品结构MD5指纹', + }, + items_crc: { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: false, + comment: '订单商品结构CRC32校验', + }, + package_material_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '包材ID', + }, + package_material_code: { + type: Sequelize.STRING(64), + allowNull: false, + comment: '包材编码(快照)', + }, + package_material_name: { + type: Sequelize.STRING(128), + allowNull: false, + comment: '包材名称(快照)', + }, + package_material_spec: { + type: Sequelize.STRING(128), + allowNull: true, + defaultValue: '', + comment: '规格(快照)', + }, + package_material_type: { + type: Sequelize.STRING(32), + allowNull: true, + defaultValue: '', + comment: '类型(快照)', + }, + length: { + type: Sequelize.DECIMAL(10, 2), + allowNull: true, + defaultValue: 0, + comment: '长(cm)快照', + }, + width: { + type: Sequelize.DECIMAL(10, 2), + allowNull: true, + defaultValue: 0, + comment: '宽(cm)快照', + }, + height: { + type: Sequelize.DECIMAL(10, 2), + allowNull: true, + defaultValue: 0, + comment: '高(cm)快照', + }, + weight: { + type: Sequelize.DECIMAL(10, 2), + allowNull: true, + defaultValue: 0, + comment: '重量(kg)快照', + }, + bind_count: { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: false, + defaultValue: 1, + comment: '累计绑定次数', + }, + last_order_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '最近订单ID', + }, + last_waybill_code: { + type: Sequelize.STRING(50), + allowNull: true, + defaultValue: '', + comment: '最近运单号', + }, + last_bind_user_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '最近操作用户ID', + }, + last_bind_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '最近绑定时间', + }, + is_active: { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 1, + comment: '包材当前是否启用', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + delete_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '软删除时间', + }, + }); + + await queryInterface.addIndex(TABLE_NAME, ['warehouse_id', 'items_hash', 'items_crc', 'package_material_id'], { + unique: true, + name: 'uk_item_material', + }); + + await queryInterface.addIndex(TABLE_NAME, ['warehouse_id', 'is_active', 'items_hash', 'bind_count'], { + name: 'idx_lookup', + }); + }, + + down: async (queryInterface) => { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260615160000-alter-uk-interface-warehouse.js b/database/migrations/20260615160000-alter-uk-interface-warehouse.js new file mode 100644 index 0000000..45c35ac --- /dev/null +++ b/database/migrations/20260615160000-alter-uk-interface-warehouse.js @@ -0,0 +1,32 @@ +'use strict'; + +module.exports = { + /** + * 修改 wms_api_app 表的唯一键 uk_interface_warehouse: + * 从 (qimen_app_key, qimen_customer_id) 改为 (qimen_app_key, qimen_warehouse_code) + */ + up: async queryInterface => { + // 1. 删除旧唯一键 + await queryInterface.sequelize.query( + "ALTER TABLE wms_api_app DROP INDEX uk_interface_warehouse" + ); + // 2. 创建新唯一键 + await queryInterface.sequelize.query( + "ALTER TABLE wms_api_app ADD UNIQUE INDEX uk_interface_warehouse (qimen_app_key, qimen_warehouse_code)" + ); + }, + + /** + * 回滚:恢复为 (qimen_app_key, qimen_customer_id) + */ + down: async queryInterface => { + // 1. 删除新唯一键 + await queryInterface.sequelize.query( + "ALTER TABLE wms_api_app DROP INDEX uk_interface_warehouse" + ); + // 2. 恢复旧唯一键 + await queryInterface.sequelize.query( + "ALTER TABLE wms_api_app ADD UNIQUE INDEX uk_interface_warehouse (qimen_app_key, qimen_customer_id)" + ); + }, +}; diff --git a/database/migrations/20260617150000-make-warehouse-id-nullable-in-wms-platfrom-setting.js b/database/migrations/20260617150000-make-warehouse-id-nullable-in-wms-platfrom-setting.js new file mode 100644 index 0000000..5337fdf --- /dev/null +++ b/database/migrations/20260617150000-make-warehouse-id-nullable-in-wms-platfrom-setting.js @@ -0,0 +1,20 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.changeColumn('wms_platfrom_setting', 'warehouse_id', { + type: Sequelize.BIGINT.UNSIGNED, + allowNull: true, + comment: '仓库ID,NULL表示系统级设置', + }); + }, + + async down(queryInterface, Sequelize) { + // 回滚前需确认没有 warehouse_id=NULL 的数据,否则回滚会失败 + await queryInterface.changeColumn('wms_platfrom_setting', 'warehouse_id', { + type: Sequelize.BIGINT.UNSIGNED, + allowNull: false, + comment: '仓库ID', + }); + }, +}; diff --git a/docs/stock-stockWarehouse-query-rules.md b/docs/stock-stockWarehouse-query-rules.md index 28a081e..f0bad86 100644 --- a/docs/stock-stockWarehouse-query-rules.md +++ b/docs/stock-stockWarehouse-query-rules.md @@ -104,6 +104,17 @@ - 传入的是违禁品类型 `id`。 - 后端会映射到关联模型进行过滤。 +### has_bound_item + +- 筛选仓库商品是否已绑定外部商品(货主商品)。 +- `operator`:固定 `eq`(默认)。 +- `value`: + - 已绑定:`true` / `1` / `"Y"` / `"y"` + - 未绑定:`false` / `0` / `"N"` / `"n"` +- 示例: + - 查询已绑定外部商品的仓库商品:`has_bound_item={operator:eq,value:true}` + - 查询未绑定外部商品的仓库商品:`has_bound_item={operator:eq,value:false}` + ## 空值处理 以下值会被视为“空条件”并跳过: diff --git a/methods/changes/2026.06.16-system-01.json b/methods/changes/2026.06.16-system-01.json new file mode 100644 index 0000000..c6d1df0 --- /dev/null +++ b/methods/changes/2026.06.16-system-01.json @@ -0,0 +1,17 @@ +[ + { + "version": "2026.06.16-system-01", + "date": "2026-06-16", + "summary": "新增 order.recheckOrder.queryRecheckOrderSingleList:散单复核列表接口,响应新增 items_weight(总重量kg)和 weight_type(重量类型)字段", + "methods": [ + "order.recheckOrder.queryRecheckOrderSingleList" + ], + "notes": [ + "新增方法 order.recheckOrder.queryRecheckOrderSingleList,为 recheckOrderList 散单模式的独立入口。", + "响应 list 每项新增字段 items_weight (number|null):订单总重量(kg),来自 wms_order.items_weight,为 null 时返回 null。", + "响应 list 每项新增字段 weight_type (string):重量类型中文标签,来自 wms_order.weight_type 经 formatWeightTypeLabel 转换;取值:常规/轻货/重货/冷链(对应 DB 值 0/1/2/3)。" + ], + "type": "added", + "module": "order.recheckOrder" + } +] diff --git a/methods/changes/2026.06.16-system-02.json b/methods/changes/2026.06.16-system-02.json new file mode 100644 index 0000000..545df34 --- /dev/null +++ b/methods/changes/2026.06.16-system-02.json @@ -0,0 +1,16 @@ +[ + { + "version": "2026.06.16-system-02", + "date": "2026-06-16", + "summary": "order.wave.groupOrderFetchList 响应新增 items_weight(总重量kg)字段", + "methods": [ + "order.wave.groupOrderFetchList" + ], + "notes": [ + "响应 list 每项新增字段 items_weight (number|null):订单总重量(kg),取组内首单 items_weight;组内订单 items_hash 相同重量一致。", + "为 null 时返回 null。" + ], + "type": "updated", + "module": "order.wave" + } +] diff --git a/methods/changes/2026.06.16-system-03.json b/methods/changes/2026.06.16-system-03.json new file mode 100644 index 0000000..15005a5 --- /dev/null +++ b/methods/changes/2026.06.16-system-03.json @@ -0,0 +1,16 @@ +[ + { + "version": "2026.06.16-system-03", + "date": "2026-06-16", + "summary": "order.wave.waveStrategyFallbackOrderList 响应新增 items_weight(总重量kg)和 weight_type(重量类型)字段", + "methods": [ + "order.wave.waveStrategyFallbackOrderList" + ], + "notes": [ + "响应 list 每项新增字段 items_weight (number|null):订单总重量(kg),来自 wms_order.items_weight,为 null 时返回 null。", + "响应 list 每项新增字段 weight_type (string):重量类型中文标签,来自 wms_order.weight_type 经 formatWeightTypeLabel 转换;取值:常规/轻货/重货/冷链(对应 DB 值 0/1/2/3)。" + ], + "type": "updated", + "module": "order.wave" + } +] diff --git a/methods/changes/2026.06.16-system-04.json b/methods/changes/2026.06.16-system-04.json new file mode 100644 index 0000000..4872712 --- /dev/null +++ b/methods/changes/2026.06.16-system-04.json @@ -0,0 +1,16 @@ +[ + { + "version": "2026.06.16-system-04", + "date": "2026-06-16", + "summary": "order.wave.singleOrderFetchList 响应新增 items_weight(总重量kg)字段", + "methods": [ + "order.wave.singleOrderFetchList" + ], + "notes": [ + "响应 list 每项新增字段 items_weight (number|null):订单总重量(kg),取组内首单 items_weight;组内订单 items_hash 相同重量一致。", + "为 null 时返回 null。" + ], + "type": "updated", + "module": "order.wave" + } +] diff --git a/methods/changes/system.json b/methods/changes/system.json index 0284e7c..03d6488 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -3331,5 +3331,90 @@ "description": "包含拣货任务状态同步:全部拣完→任务状态=2(已完成),未全拣完→任务状态推进为1(拣货中)" }, "type": "added" + }, + { + "version": "2026.06.14-system-01", + "date": "2026-06-14", + "summary": "新增 order.bindExpressPackageMaterialByWaybill 方法:支持仅凭运单号绑定包材,无需传入订单ID", + "methods": [ + "order.bindExpressPackageMaterialByWaybill" + ], + "notes": [ + "新增 order.bindExpressPackageMaterialByWaybill 入参说明:waybill_code(运单号,必填)、package_material_code(包材编码,必填)。无需传入 order_id。", + "成功返回字段:order_id、waybill_code、package_material_id、package_material_name_snapshot、package_material_code。", + "错误码定义:400(参数错误)、404(运单号不存在 / 包材编码不存在)、500(绑定包材失败)。" + ], + "type": "added" + }, + { + "version": "2026.06.15-system-01", + "date": "2026-06-15", + "summary": "order.detail / order.deliveryOrder.detail 的 expresses 数组新增包材字段", + "methods": [ + "order.detail", + "order.deliveryOrder.detail" + ], + "notes": [ + "expresses 数组每个元素新增 package_material_id(包材ID,number|null)和 package_material_name_snapshot(包材名称快照,string|null)字段。" + ], + "type": "updated" + }, + { + "version": "2026.06.15-system-02", + "date": "2026-06-15", + "summary": "order.deliveryOrder.detail 的 expresses 数组新增包材字段", + "methods": [ + "order.deliveryOrder.detail" + ], + "notes": [ + "expresses 数组每个元素新增 package_material_id(包材ID,number|null)和 package_material_name_snapshot(包材名称快照,string|null)字段。" + ], + "type": "updated" + }, + { + "version": "2026.06.15-system-03", + "date": "2026-06-15", + "summary": "新增 setting.packageMaterial.search 方法:支持按关键字模糊搜索包材编码和名称", + "methods": [ + "setting.packageMaterial.search" + ], + "notes": [ + "新增 setting.packageMaterial.search 入参 keyword(可选),为空返回前 50 条启用中包材,有值时对 material_code 和 material_name 做模糊匹配。", + "返回包材数组,字段:id、material_code、material_name、material_type、spec、status。" + ], + "type": "added" + }, + { + "version": "2026.06.16-system-01", + "date": "2026-06-16", + "summary": "新增 order.recheckOrder.queryRecheckOrderSingleList:散单复核列表接口,响应新增 items_weight(总重量kg)和 weight_type(重量类型)字段", + "methods": [ + "order.recheckOrder.queryRecheckOrderSingleList" + ], + "notes": [ + "新增方法 order.recheckOrder.queryRecheckOrderSingleList,为 recheckOrderList 散单模式的独立入口。", + "响应 list 每项新增字段 items_weight (DECIMAL(10,2)):订单总重量(kg),来自 wms_order.items_weight,为 null 时返回 null。", + "响应 list 每项新增字段 weight_type (string):重量类型中文标签,来自 wms_order.weight_type 经 formatWeightTypeLabel 转换;取值:常规/轻货/重货/冷链(对应 DB 值 0/1/2/3)。" + ], + "type": "added", + "module": "order.recheckOrder" + }, + { + "version": "2026.06.16-system-02", + "date": "2026-06-16", + "summary": "为 order.wave.groupOrderFetchList / waveStrategyFallbackOrderList / singleOrderFetchList 响应新增 items_weight(总重量kg)和 weight_type(重量类型)字段", + "methods": [ + "order.wave.groupOrderFetchList", + "order.wave.waveStrategyFallbackOrderList", + "order.wave.singleOrderFetchList" + ], + "notes": [ + "order.wave.groupOrderFetchList:响应 list 每项新增 items_weight (number|null):订单总重量(kg),取组内首单 items_weight;组内订单 items_hash 相同重量一致。", + "order.wave.waveStrategyFallbackOrderList:响应 list 每项新增 items_weight (number|null):订单总重量(kg),来自 wms_order.items_weight;新增 weight_type (string):重量类型中文标签,取值:常规/轻货/重货/冷链(对应 DB 值 0/1/2/3)。", + "order.wave.singleOrderFetchList:响应 list 每项新增 items_weight (number|null):订单总重量(kg),取组内首单 items_weight;组内订单 items_hash 相同重量一致。", + "所有新增字段均为可选(required=false),为 null 时返回 null。" + ], + "type": "updated", + "module": "order.wave" } ] diff --git a/methods/system.json b/methods/system.json index 0680d68..d8518ef 100644 --- a/methods/system.json +++ b/methods/system.json @@ -2,7 +2,7 @@ "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", "version": "0.3.6", - "updatedAt": "2026-06-13", + "updatedAt": "2026-06-16", "headers": [ { "name": "platform", @@ -1733,7 +1733,7 @@ "name": "expresses", "type": "array", "required": true, - "description": "运单信息数组,每个元素包含以下字段:waybill_code(运单号,string)、weighing_weight(称重重量,number|null)、sys_logistics_code(系统物流公司编码,string)、sys_logistics_name(系统物流公司名称,string)、logistics_code(实际物流公司编码,string)、logistics_name(实际物流公司名称,string)、logistics_interface_id(物流接口ID,number|null)、business_key(业务标识,string)、created_at(创建时间戳毫秒,number|null)" + "description": "运单信息数组,每个元素包含以下字段:waybill_code(运单号,string)、weighing_weight(称重重量,number|null)、sys_logistics_code(系统物流公司编码,string)、sys_logistics_name(系统物流公司名称,string)、logistics_code(实际物流公司编码,string)、logistics_name(实际物流公司名称,string)、logistics_interface_id(物流接口ID,number|null)、business_key(业务标识,string)、created_at(创建时间戳毫秒,number|null)、package_material_id(包材ID,number|null)、package_material_name_snapshot(包材名称快照,string|null)" }, { "name": "waybill_codes", @@ -2288,6 +2288,86 @@ } ] }, + { + "method": "order.bindExpressPackageMaterialByWaybill", + "description": "按运单号绑定包材。仅需传入运单号与包材编码,系统自动根据运单号反查对应订单运单记录并绑定包材,无需传入订单ID。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "waybill_code", + "type": "string", + "required": true, + "source": "body", + "description": "运单号,必填。" + }, + { + "name": "package_material_code", + "type": "string", + "required": true, + "source": "body", + "description": "包材编码,必填。" + } + ], + "response": [ + { + "name": "order_id", + "type": "number", + "required": true, + "description": "运单号对应的订单ID(成功时返回于 data 对象中)。" + }, + { + "name": "waybill_code", + "type": "string", + "required": true, + "description": "运单号(成功时返回于 data 对象中)。" + }, + { + "name": "package_material_id", + "type": "number", + "required": true, + "description": "绑定后的包材ID(成功时返回于 data 对象中)。" + }, + { + "name": "package_material_name_snapshot", + "type": "string", + "required": true, + "description": "绑定时写入的包材名称快照(成功时返回于 data 对象中)。" + }, + { + "name": "package_material_code", + "type": "string", + "required": true, + "description": "绑定成功的包材编码(成功时返回于 data 对象中)。" + } + ], + "errors": [ + { + "code": 400, + "message": "参数错误" + }, + { + "code": 404, + "message": "运单号不存在" + }, + { + "code": 404, + "message": "包材编码不存在" + }, + { + "code": 500, + "message": "绑定包材失败" + } + ] + }, { "method": "order.export", "description": "提交订单导出任务(异步)。入参支持 table_type/tableType 与 module/module_name;where 与 sort 语义与 order.list 一致。提交后立即返回 task_id,后台异步执行,导出进度/下载请通过 order.exportTaskProgress 查询。", @@ -5981,6 +6061,51 @@ "message": "订单ID列表不能为空" } ] + }, + { + "method": "order.recheckOrder.queryRecheckOrderSingleList", + "description": "散单模式复核列表查询,按订单维度返回待复核订单(排除 pick_status='none' 和 recheck_status='fin'),支持分页与关键词/波次号/复核状态筛选。与 recheckOrderList 不同:本方法仅处理散单模式,不包含团购分支。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "筛选条件。支持 keyword(运单号/订单号模糊搜索)、wave_no(精确匹配)、recheck_status、pick_status" + }, + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数,支持 page / pageSize(默认 page=1, pageSize=20)" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "散单复核订单列表,每项含 order_id、delivery_order_code、order_type、wave_id、wave_no、pick_status、recheck_status、shop_nick、logistics_name、items_count、items_total、items_weight、weight_type、status、create_at、pick_time、recheck_time" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息,含 page、pageSize、total、totalPages、hasPrevious、hasNext" + } + ], + "errors": [] } ] }, @@ -7222,7 +7347,7 @@ "name": "list", "type": "array", "required": true, - "description": "分组列表,items 示例见实现:包含 item_detail_machine/item_snapshot/group_count 等字段" + "description": "分组列表,每项包含 item_detail、item_detail_machine、item_detail_machine_snapshot、item_snapshot、group、group_count、items_total、items_weight(总重量kg,取组内首单 items_weight)、store_id、store_ids、logistics_name、distinguish_express、first_order_time、last_order_time、status_summary 等字段;若指定 return_order_ids=true 则额外包含 order_ids" }, { "name": "pagination", @@ -7234,11 +7359,11 @@ "errors": [ { "code": "400", - "description": "缺少仓库上下文或参数格式错误" + "message": "缺少仓库上下文或参数格式错误" }, { "code": "500", - "description": "查询失败" + "message": "查询失败" } ] }, @@ -7386,6 +7511,16 @@ "type": "number", "description": "总件数" }, + { + "name": "items_weight", + "type": "number", + "description": "订单总重量(kg),来自 wms_order.items_weight,为 null 时返回 null" + }, + { + "name": "weight_type", + "type": "string", + "description": "重量类型中文标签,取值:常规/轻货/重货/冷链(对应 DB 值 0/1/2/3)" + }, { "name": "sys_logistics_name", "type": "string", @@ -7423,11 +7558,11 @@ "errors": [ { "code": "400", - "description": "未识别到当前仓库上下文或 where 中包含非法/禁止字段(如 warehouse_id)或存在别名冲突" + "message": "未识别到当前仓库上下文或 where 中包含非法/禁止字段(如 warehouse_id)或存在别名冲突" }, { "code": "500", - "description": "查询失败或内部错误" + "message": "查询失败或内部错误" } ] }, @@ -7500,7 +7635,7 @@ "name": "list", "type": "array", "required": true, - "description": "散单候选分组列表,items 示例见实现:包含 item_detail_machine/item_snapshot/group_count 等字段;返回的 group_count 均小于 same_order_quantity(或仓库配置的 min_group_order_fetch_quantity)。" + "description": "散单候选分组列表,每项包含 item_detail、item_detail_machine、item_detail_machine_snapshot、item_snapshot、group、group_count、items_total、items_weight(总重量kg,取组内首单 items_weight)、store_id、store_ids、logistics_name、distinguish_express、first_order_time、last_order_time、status_summary 等字段;返回的 group_count 均小于 same_order_quantity(或仓库配置的 min_group_order_fetch_quantity);若指定 return_order_ids=true 则额外包含 order_ids" }, { "name": "pagination", @@ -7512,11 +7647,11 @@ "errors": [ { "code": "400", - "description": "缺少仓库上下文或参数格式错误" + "message": "缺少仓库上下文或参数格式错误" }, { "code": "500", - "description": "查询失败" + "message": "查询失败" } ] }, @@ -9873,41 +10008,46 @@ { "name": "order", "type": "object", + "required": true, "description": "订单头对象(raw 行数据)" }, { "name": "detail", "type": "object", + "required": true, "description": "等同于 order" }, { "name": "orderItems / items", "type": "array", + "required": true, "description": "商品明细数组" }, { "name": "expresses", "type": "array", - "description": "运单信息数组" + "required": true, + "description": "运单信息数组,每个元素包含以下字段:waybill_code(运单号,string)、weighing_weight(称重重量,number|null)、sys_logistics_code(系统物流公司编码,string)、sys_logistics_name(系统物流公司名称,string)、logistics_code(实际物流公司编码,string)、logistics_name(实际物流公司名称,string)、logistics_interface_id(物流接口ID,number|null)、business_key(业务标识,string)、created_at(创建时间戳毫秒,number|null)、package_material_id(包材ID,number|null)、package_material_name_snapshot(包材名称快照,string|null)" }, { "name": "waybill_codes", "type": "array", + "required": true, "description": "去重后的运单号字符串数组" } ], "errors": [ { "code": "400", - "description": "订单ID 为空或格式错误" + "message": "订单ID 为空或格式错误" }, { "code": "404", - "description": "订单不存在或不属于当前仓库" + "message": "订单不存在或不属于当前仓库" }, { "code": "500", - "description": "内部错误" + "message": "内部错误" } ] } @@ -14632,7 +14772,7 @@ "type": "object", "required": false, "source": "body", - "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会在 main 中自动标准化;支持 quickWhere、barcode、prohibited_type 等商品筛选字段。示例:where.barcode={operator:like,value:69}; where.prohibited_type={operator:eq,value:liquid}。" + "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会在 main 中自动标准化;支持 quickWhere、barcode、prohibited_type、has_bound_item 等商品筛选字段。示例:where.barcode={operator:like,value:69}; where.prohibited_type={operator:eq,value:liquid}; where.has_bound_item={operator:eq,value:true}(已绑定外部商品)/ where.has_bound_item={operator:eq,value:false}(未绑定外部商品)。" } ], "response": [], @@ -23209,6 +23349,43 @@ "params": [], "response": [], "errors": [] + }, + { + "method": "setting.packageMaterial.search", + "description": "包材关键字搜索,按 material_code / material_name 模糊匹配,最多返回 50 条(仅返回启用中的包材)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "keyword", + "type": "string", + "required": false, + "source": "body", + "description": "搜索关键字,模糊匹配 material_code、material_name;为空时返回前 50 条启用中的包材" + } + ], + "response": [ + { + "name": "data[]", + "type": "array", + "required": true, + "description": "包材列表,每项包含 id(包材ID)、material_code(包材编码)、material_name(包材名称)、material_type(包材类型)、spec(规格)、status(状态)" + } + ], + "errors": [ + { + "code": 500, + "message": "服务器错误" + } + ] } ] }, diff --git a/scripts/integration_test_stock_warehouse.js b/scripts/integration_test_stock_warehouse.js new file mode 100644 index 0000000..c6843f9 --- /dev/null +++ b/scripts/integration_test_stock_warehouse.js @@ -0,0 +1,114 @@ +'use strict'; +// 开发环境集成测试:验证 wms_stock_warehouse + wms_stock_transaction 修改 +const mysql = require('mysql2/promise'); +const DB_CONFIG = { host: '127.0.0.1', port: 3307, user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms' }; +const BASE_URL = 'http://127.0.0.1:6060'; +const TEST_WAREHOUSE_ID = 100000; +const TEST_STORE_ID = 1000000; + +async function main() { + const conn = await mysql.createConnection(DB_CONFIG); + + try { + console.log('='.repeat(70)); + console.log('WMS 拣货/复核完成 - stock_warehouse + stock_transaction 集成验证'); + console.log(`测试时间: ${new Date().toISOString()}`); + console.log(`测试仓库: ${TEST_WAREHOUSE_ID}`); + console.log(`测试货主: ${TEST_STORE_ID}`); + console.log('='.repeat(70)); + + // === 步骤1: 检查订单分表 === + console.log('\n--- 步骤1: 检查订单分表 ---'); + const [tables] = await conn.query("SHOW TABLES LIKE 'wms_order_delivery_%'"); + console.log(` 订单分表数量: ${tables.length}`); + tables.forEach(t => console.log(` - ${Object.values(t)[0]}`)); + + // === 步骤2: 查看订单状态分布 === + console.log('\n--- 步骤2: 订单状态分布 (wms_order_delivery_100000) ---'); + const [statusDist] = await conn.query(` + SELECT pick_status, recheck_status, storage_status, status, COUNT(*) as cnt + FROM wms_order_delivery_100000 + GROUP BY pick_status, recheck_status, storage_status, status + ORDER BY cnt DESC + LIMIT 15 + `); + console.table(statusDist); + + // === 步骤3: 查找最近有库存变更的 stock_warehouse === + console.log('\n--- 步骤3: wms_stock_warehouse 状态 (warehouse=100000) ---'); + const [swRows] = await conn.query(` + SELECT id, item_code, item_name, quantity, locked_quantity, store_id + FROM wms_stock_warehouse + WHERE warehouse_id = 100000 AND quantity > 0 + ORDER BY id DESC + LIMIT 10 + `); + console.table(swRows); + + // === 步骤4: wms_stock_transaction 最近记录 === + console.log('\n--- 步骤4: wms_stock_transaction 最近记录 ---'); + const [recentTx] = await conn.query(` + SELECT id, transaction_type, order_type, stock_id, quantity, + before_quantity, after_quantity, + before_locked_quantity, after_locked_quantity, + remark, created_at + FROM wms_stock_transaction + ORDER BY id DESC + LIMIT 15 + `); + console.table(recentTx); + + // 检查是否有 PICK_OUTBOUND 类型的记录 + const pickOutboundTx = recentTx.filter(r => r.order_type === 'PICK_OUTBOUND'); + console.log(`\n PICK_OUTBOUND 类型 stock_transaction 记录数: ${pickOutboundTx.length}`); + if (pickOutboundTx.length > 0) { + console.log(' ✅ 已有拣货出库 stock_transaction 记录,说明 pick.js 修改生效'); + for (const tx of pickOutboundTx) { + console.log(` id=${tx.id} stock_id=${tx.stock_id} qty=${tx.quantity} locked: ${tx.before_locked_quantity}→${tx.after_locked_quantity}`); + } + } else { + console.log(' ⚠️ 尚无 PICK_OUTBOUND stock_transaction 记录,需触发拣货流程验证'); + } + + // === 步骤5: 统计 stock_transaction 的 before_locked/after_locked 非零记录 === + console.log('\n--- 步骤5: stock_transaction locked_quantity 变更统计 ---'); + const [lockedStats] = await conn.query(` + SELECT + COUNT(*) as total, + SUM(CASE WHEN before_locked_quantity > 0 OR after_locked_quantity > 0 THEN 1 ELSE 0 END) as with_locked, + SUM(CASE WHEN before_locked_quantity != after_locked_quantity THEN 1 ELSE 0 END) as locked_changed + FROM wms_stock_transaction + `); + console.table(lockedStats); + + // === 步骤6: 检查 wms_stock_transaction 中 remark 包含"货主库存释放"的记录 === + console.log('\n--- 步骤6: 货主库存释放 stock_transaction 记录 ---'); + const [releaseTx] = await conn.query(` + SELECT id, transaction_type, order_type, stock_id, quantity, + before_locked_quantity, after_locked_quantity, remark, created_at + FROM wms_stock_transaction + WHERE remark LIKE '%货主库存释放%' + ORDER BY id DESC + LIMIT 10 + `); + console.log(` 货主库存释放记录数: ${releaseTx.length}`); + if (releaseTx.length > 0) { + console.table(releaseTx); + console.log(' ✅ stock_warehouse locked_quantity 释放 + stock_transaction 写入已验证'); + } else { + console.log(' ⚠️ 尚无"货主库存释放"remark 记录'); + } + + console.log('\n' + '='.repeat(70)); + console.log('集成验证完成'); + console.log('='.repeat(70)); + + } finally { + await conn.end(); + } +} + +main().catch(err => { + console.error('测试失败:', err); + process.exit(1); +}); From 77435aeb7901456658ed502d0dae9ca3e2e9f004 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Tue, 23 Jun 2026 18:48:33 +0800 Subject: [PATCH 074/550] 1 --- 3 | 0 AI_METHOD_ROUTING.md | 4 + app/dict/businessDict.js | 21 + app/lib/printer_data_builder.js | 99 +- app/lib/qimen_client.js | 3 +- app/model/entry_items.js | 2 + app/model/entry_order.js | 34 +- app/model/entry_order_receiving.js | 76 + app/model/entry_receiving_binding.js | 99 + app/model/inbound_direct_log.js | 103 + app/model/order_delivery.js | 2 +- app/model/receiving.js | 8 +- app/model/store.js | 22 + app/model/store_warehouse.js | 26 +- app/service/openapiMethods/entryorder.js | 203 ++ app/service/openapiMethods/order.js | 164 ++ app/service/qimenMethods/order.js | 165 ++ app/service/systemMethods/comboGoods.js | 168 ++ app/service/systemMethods/order/index.js | 12 +- .../systemMethods/order/pendingOrder.js | 272 +- .../systemMethods/order/recheckOrder.js | 329 ++- app/service/systemMethods/order/wave.js | 251 +- app/service/systemMethods/pick.js | 72 +- app/service/systemMethods/print.js | 10 +- app/service/systemMethods/stock/warehouse.js | 25 +- .../systemMethods/storage/direct_inbound.js | 71 + app/service/systemMethods/storage/entry.js | 144 +- .../systemMethods/storage/inventory.js | 27 +- .../systemMethods/storage/management.js | 45 + .../systemMethods/storage/receiving.js | 25 +- app/service/systems/comboGoods.js | 1011 ++++++++ app/service/systems/delivery_order.js | 289 ++- app/service/systems/entry_order.js | 89 +- app/service/systems/express_platform.js | 334 ++- app/service/systems/inbound_direct_log.js | 893 +++++++ app/service/systems/order_async.js | 9 +- app/service/systems/order_export.js | 86 +- app/service/systems/order_express.js | 181 +- app/service/systems/order_print.js | 5 + .../systems/order_storage_allocation.js | 90 +- app/service/systems/pick.js | 169 +- app/service/systems/pick_compensation.js | 182 +- app/service/systems/receiving_entry_match.js | 882 +++++++ app/service/systems/setting/warehouse.js | 19 + app/service/systems/stock_store.js | 184 +- app/service/systems/storage/entry.js | 400 +-- app/service/systems/storage/inventory.js | 964 -------- app/service/systems/storage/management.js | 347 +++ app/service/systems/storage/receiving.js | 8 + app/service/systems/store_warehouse.js | 12 +- config/config.default.js | 1 + ...0000-create-wms-entry-receiving-binding.js | 86 + .../20260621100000-create-wms-combo-goods.js | 232 ++ ...622100000-create-wms-inbound-direct-log.js | 101 + ...-add-space-id-to-wms-inbound-direct-log.js | 25 + ...20260622150000-seed-receipt-print-items.js | 67 + ...0-add-created-status-to-wms-entry-order.js | 28 + ...30000-remove-confirmed-partial-received.js | 31 + ...0623140000-create-entry-order-receiving.js | 66 + docs/combo-goods-api.md | 387 +++ docs/storage-receiving-api.md | 51 + .../repo/entry-receiving-match-callback.md | 28 + .../openapi-2026-06-17-entryorder.json | 20 + methods/changes/openapi.json | 43 + methods/changes/system.json | 666 +++++ methods/openapi.json | 451 +++- methods/system.json | 2194 ++++++++++++++--- prompts/官网生成提示词.md | 187 ++ script/api-test.js | 34 + script/api-test2.js | 47 + script/backfill-wave-status.js | 70 + script/clear-cache.js | 30 + script/cutoff-integration-test-v2.js | 183 ++ script/cutoff-integration-test-v3.js | 203 ++ script/cutoff-integration-test.js | 279 +++ script/integration-test.js | 87 + script/update-policy.js | 64 + temp_check_prod_migrations.js | 71 + ...tem.storage.inventory.matchPutaway.test.js | 2 +- .../order_delivery_dispatch_factory.test.js | 3 +- .../systems/order_storage_allocation.test.js | 114 + 81 files changed, 12290 insertions(+), 2197 deletions(-) create mode 100644 3 create mode 100644 app/model/entry_order_receiving.js create mode 100644 app/model/entry_receiving_binding.js create mode 100644 app/model/inbound_direct_log.js create mode 100644 app/service/openapiMethods/entryorder.js create mode 100644 app/service/systemMethods/comboGoods.js create mode 100644 app/service/systemMethods/storage/direct_inbound.js create mode 100644 app/service/systemMethods/storage/management.js create mode 100644 app/service/systems/comboGoods.js create mode 100644 app/service/systems/inbound_direct_log.js create mode 100644 app/service/systems/receiving_entry_match.js create mode 100644 app/service/systems/storage/management.js create mode 100644 database/migrations/20260618150000-create-wms-entry-receiving-binding.js create mode 100644 database/migrations/20260621100000-create-wms-combo-goods.js create mode 100644 database/migrations/20260622100000-create-wms-inbound-direct-log.js create mode 100644 database/migrations/20260622110000-add-space-id-to-wms-inbound-direct-log.js create mode 100644 database/migrations/20260622150000-seed-receipt-print-items.js create mode 100644 database/migrations/20260623120000-add-created-status-to-wms-entry-order.js create mode 100644 database/migrations/20260623130000-remove-confirmed-partial-received.js create mode 100644 database/migrations/20260623140000-create-entry-order-receiving.js create mode 100644 docs/combo-goods-api.md create mode 100644 memories/repo/entry-receiving-match-callback.md create mode 100644 methods/changes/openapi-2026-06-17-entryorder.json create mode 100644 prompts/官网生成提示词.md create mode 100644 script/api-test.js create mode 100644 script/api-test2.js create mode 100644 script/backfill-wave-status.js create mode 100644 script/clear-cache.js create mode 100644 script/cutoff-integration-test-v2.js create mode 100644 script/cutoff-integration-test-v3.js create mode 100644 script/cutoff-integration-test.js create mode 100644 script/integration-test.js create mode 100644 script/update-policy.js create mode 100644 temp_check_prod_migrations.js diff --git a/3 b/3 new file mode 100644 index 0000000..e69de29 diff --git a/AI_METHOD_ROUTING.md b/AI_METHOD_ROUTING.md index bc87e0c..04de55b 100644 --- a/AI_METHOD_ROUTING.md +++ b/AI_METHOD_ROUTING.md @@ -167,6 +167,8 @@ rg "class .*Service|module.exports" app/service/qimenMethods - stockWarehouse, getProhibitedType, getInfo, saveWarehouseStock, createWarehouseStock, getBarcodes, saveWarehouseStockBarcode, getStoreStocks, bindItem, unbindItem, checkItemCodeUnique, queryStockLogs, handleBatchDelete, deleteUnit, deleteProhibited, handleBatchChange, getStockUnits, getUnitList, createProhibited, createUnit, search - app/service/systemMethods/storage/receiving.js (13) - getReceivingList, getReceivingDetail, batchCancelReceiving, create, addItem, removeItem, saveReceiving, get, addDetail, deleteDetail, detailChange, cancel, completeReceiving +- app/service/systemMethods/storage/direct_inbound.js (4) + - getItems, addItem, commit, removeItem - app/service/systemMethods/store.js (6) - createStore, createWarehouse, joinStore, joinWarehouse, getStoreRoles, auditApply - app/service/systemMethods/user.js (5) @@ -181,6 +183,8 @@ rg "class .*Service|module.exports" app/service/qimenMethods - addOrder, generateItemsHash, calculateCRC32, prepareOrderData, addOrderLines, safeParseFloat, addOrderToQueue - app/service/systems/entry_order.js (9) - addOrder, getLineCount, received, success, fail, tryCreateEntryOrder, addItems, qimenEntryorderConfirm, entryorderConfirm +- app/service/systems/inbound_direct_log.js (4) + - getItems, addItem, commit, removeItem - app/service/systems/fast_where.js (13) - buildTree, getTreeByType, buildSubTree, getWithChildrenByType, getAllChildren, getByType, getGroups, getChildrenByPid, getTreeChildrenByPid, create, update, findById, delete - app/service/systems/file.js (2) diff --git a/app/dict/businessDict.js b/app/dict/businessDict.js index 4925f6d..ce2d78f 100644 --- a/app/dict/businessDict.js +++ b/app/dict/businessDict.js @@ -58,8 +58,27 @@ module.exports = { ORDER_PACKED: '订单打包', ORDER_SHIPPED: '订单发货', ORDER_COMPLETE: '订单完成', + ORDER_UPDATE_PLATFORM: '更新平台', + ORDER_UPDATE_EXPRESS: '更新快递', + ORDER_UPDATE_ADDRESS: '更新地址', + ORDER_CLONE_SOURCE: '克隆来源订单', + ORDER_CLONE_TARGET: '克隆目标订单', + ORDER_MANUAL_WAYBILL: '手工录入运单号', + ORDER_RESOLVE_EXCEPTION: '处理异常', + ORDER_INTERCEPT_CONFIRM: '确认拦截', + ORDER_PLATFORM_FALLBACK: '平台降级', + ORDER_EXPRESS_FALLBACK: '快递降级', + ORDER_WAVE_UPDATE: '更新波次', ORDER_WAVE_ASSIGN: '分配波次', + ORDER_WAVE_REMOVE: '移出波次', ORDER_WAVE_CANCEL: '取消波次', + ORDER_WAVE_GRAB: '抓取波次', + ORDER_WAVE_AUTO_GROUP: '自动加团', + ORDER_WAVE_STRATEGY_FETCH: '策略抓取波次', + ORDER_PICK_COMPLETE: '拣货完成', + ORDER_SYNC: '同步订单', + ORDER_WEIGH: '称重', + ORDER_PACKAGE_MATERIAL_BIND: '绑定包材', ORDER_STORAGE_ALLOCATE_SUCCESS: '分配储位成功', ORDER_STORAGE_ALLOCATE_FAILED: '分配储位失败', ORDER_STORAGE_UNALLOCATE_SUCCESS: '取消分配储位成功', @@ -72,6 +91,8 @@ module.exports = { ORDER_UNLOCK: '订单解锁', // 库存管理 + STORAGE_TRANSFER_LOCATION: '库位调拨', + STORAGE_TRANSFER_BY_PRODUCT: '商品调拨', STOCK_IN: '商品入库', STOCK_OUT: '商品出库', STOCK_ADJUST: '库存调整', diff --git a/app/lib/printer_data_builder.js b/app/lib/printer_data_builder.js index f7dde6f..64a78b4 100644 --- a/app/lib/printer_data_builder.js +++ b/app/lib/printer_data_builder.js @@ -477,58 +477,57 @@ function buildWaybillCustomProductInfoLines(items, policyConfig = {}, options = ? String(safePolicyConfig[WAYBILL_CUSTOM_DISPLAY_FIELD] || '').trim() : WAYBILL_CUSTOM_DISPLAY_TYPES.PICK_LOCATION_NAME_BARCODE_QTY; - if (displayType === WAYBILL_CUSTOM_DISPLAY_TYPES.HIDE) { - return []; - } + const isHideMode = displayType === WAYBILL_CUSTOM_DISPLAY_TYPES.HIDE; const detailLines = []; - let totalQty = 0; - for (const item of safeItems) { - if (!isPlainObject(item)) { - continue; - } + // HIDE 模式下跳过商品明细行构建,但仍保留 headerLine(波次号、快递渠道等)的输出 + if (!isHideMode) { + for (const item of safeItems) { + if (!isPlainObject(item)) { + continue; + } - const itemName = getFirstNonEmptyText(item, [ 'item_name', 'product_name', 'name', 'title' ]); - const pickLocation = getFirstNonEmptyText(item, [ - 'pick_location', - 'pick_location_code', - 'location_code', - 'space_code', - 'bin_code', - 'storage_code', - ]); - const barcode = resolveItemBarcodeText(item); - const { qtyText, qtyNumber } = resolveItemQuantity(item); - totalQty += qtyNumber; + const itemName = getFirstNonEmptyText(item, [ 'item_name', 'product_name', 'name', 'title' ]); + const pickLocation = getFirstNonEmptyText(item, [ + 'pick_location', + 'pick_location_code', + 'location_code', + 'space_code', + 'bin_code', + 'storage_code', + ]); + const barcode = resolveItemBarcodeText(item); + const { qtyText } = resolveItemQuantity(item); - let line = ''; - switch (displayType) { - case WAYBILL_CUSTOM_DISPLAY_TYPES.ITEM_NAME_QTY: - line = `${itemName} 【${qtyText}】`.trim(); - break; - case WAYBILL_CUSTOM_DISPLAY_TYPES.PICK_LOCATION_BARCODE_QTY: - line = `${pickLocation} ${barcode} 【${qtyText}】`.trim(); - break; - case WAYBILL_CUSTOM_DISPLAY_TYPES.PICK_LOCATION_BARCODE_LAST5_QTY: { - const barcodeLast5 = barcode ? barcode.slice(-5) : ''; - if (!pickLocation && !barcodeLast5) { - line = ''; + let line = ''; + switch (displayType) { + case WAYBILL_CUSTOM_DISPLAY_TYPES.ITEM_NAME_QTY: + line = `${itemName} 【${qtyText}】`.trim(); + break; + case WAYBILL_CUSTOM_DISPLAY_TYPES.PICK_LOCATION_BARCODE_QTY: + line = `${pickLocation} ${barcode} 【${qtyText}】`.trim(); + break; + case WAYBILL_CUSTOM_DISPLAY_TYPES.PICK_LOCATION_BARCODE_LAST5_QTY: { + const barcodeLast5 = barcode ? barcode.slice(-5) : ''; + if (!pickLocation && !barcodeLast5) { + line = ''; + break; + } + line = `${pickLocation} ${barcodeLast5} 【${qtyText}】`.trim(); break; } - line = `${pickLocation} ${barcodeLast5} 【${qtyText}】`.trim(); - break; + case WAYBILL_CUSTOM_DISPLAY_TYPES.PICK_LOCATION_NAME_BARCODE_QTY: + line = `${pickLocation} ${itemName} ${barcode} 【${qtyText}】`.trim(); + break; + default: + line = ''; + break; } - case WAYBILL_CUSTOM_DISPLAY_TYPES.PICK_LOCATION_NAME_BARCODE_QTY: - line = `${pickLocation} ${itemName} ${barcode} 【${qtyText}】`.trim(); - break; - default: - line = ''; - break; - } - if (line) { - detailLines.push(line.replace(/\s{2,}/g, ' ')); + if (line) { + detailLines.push(line.replace(/\s{2,}/g, ' ')); + } } } @@ -537,10 +536,6 @@ function buildWaybillCustomProductInfoLines(items, policyConfig = {}, options = const waveIndex = toNumber(safeOptions.wave_index, 0); const platformsIndex = toNumber(safeOptions.platforms_index, 0); const expressInterfaceName = String(safeOptions.expressInterfaceName || '').trim(); - const fallbackTotalQtyRaw = Number(safeOptions.fallbackTotalQty); - const finalTotalQty = totalQty > 0 - ? totalQty - : (Number.isFinite(fallbackTotalQtyRaw) && fallbackTotalQtyRaw > 0 ? fallbackTotalQtyRaw : 0); void platformsIndex; const hasWaveCustomPrefix = waveTotalOrders > 0 && waveIndex > 0 @@ -2001,8 +1996,14 @@ function applySphExpressFieldMapping( } task.printNum = isPlainObject(task.printNum) ? task.printNum : {}; - const currentCurNum = toNumber(task.printNum.curNum, 0); - task.printNum.curNum = currentCurNum > 0 ? currentCurNum : 1; + // curNum 使用订单在波次内的实际序号(wave_index),与 sumNum(波次总单数)对应 + const waveIndex = toNumber(safeOrderDelivery.wave_index, 0); + const platformsIndex = toNumber(safeOrderDelivery.platforms_index, 0); + const templateCurNum = toNumber(task.printNum.curNum, 0); + const effectiveCurNum = waveIndex > 0 + ? waveIndex + : (platformsIndex > 0 ? platformsIndex : templateCurNum); + task.printNum.curNum = effectiveCurNum > 0 ? effectiveCurNum : 1; task.printNum.sumNum = toNumber( safeOrderDelivery.wave_total_orders, toNumber(task.printNum.sumNum, 0) diff --git a/app/lib/qimen_client.js b/app/lib/qimen_client.js index e65a0b9..09ff933 100644 --- a/app/lib/qimen_client.js +++ b/app/lib/qimen_client.js @@ -70,8 +70,9 @@ class QimenClient { return String(xmlString || '').replace(packagesBlockRegex, block => { return block + // 去掉 buildXmlNode 为数组元素添加的 包装器: → .replace(/<\s*package\s*>\s*<\s*item\s*>/gi, '') - .replace(/<\s*\/\s*item\s*>\s*<\s*item\s*>/gi, '') + // 去掉对应的 包装器闭合,输出标准格式 XML(不再做交错标签变换) .replace(/<\s*\/\s*item\s*>\s*<\s*\/\s*package\s*>/gi, ''); }); } diff --git a/app/model/entry_items.js b/app/model/entry_items.js index 0969a64..e213358 100644 --- a/app/model/entry_items.js +++ b/app/model/entry_items.js @@ -128,6 +128,8 @@ module.exports = app => { foreignKey: 'stock_id', as: 'stock', }); + + }; // 实例方法 - 验证收货数量 diff --git a/app/model/entry_order.js b/app/model/entry_order.js index f7f5b2a..91f3267 100644 --- a/app/model/entry_order.js +++ b/app/model/entry_order.js @@ -19,7 +19,7 @@ module.exports = app => { }, }, order_type: { - type: ENUM('SCRK', 'LYRK', 'CCRK', 'CGRK', 'DBRK', 'QTRK', 'B2BRK', 'XNRK','SHRK'), + type: ENUM('SCRK', 'LYRK', 'CCRK', 'CGRK', 'DBRK', 'QTRK', 'B2BRK', 'XNRK', 'SHRK'), allowNull: false, comment: '业务类型', }, @@ -81,10 +81,10 @@ module.exports = app => { comment: '来源类型', }, order_status: { - type: ENUM('PENDING', 'CONFIRMED', 'PARTIAL_RECEIVED', 'COMPLETED', 'CANCELLED', 'CREATING'), + type: ENUM('CREATING', 'CREATED', 'PENDING', 'COMPLETED', 'CANCELLED'), allowNull: false, - defaultValue: 'PENDING', - comment: '订单状态', + defaultValue: 'CREATED', + comment: '订单状态:CREATING=创建中, CREATED=已创建待审核, PENDING=已审核, COMPLETED=已完成, CANCELLED=已作废', }, sync_status: { type: ENUM('PENDING', 'SUCCESS', 'FAILED'), @@ -215,7 +215,7 @@ module.exports = app => { // 关联关系 EntryOrder.associate = function() { - const { EntryOrder, Store, EntryItems } = app.model; + const { EntryOrder, Store, EntryItems, EntryOrderReceiving } = app.model; // 关联仓库 EntryOrder.belongsTo(Store, { @@ -234,15 +234,21 @@ module.exports = app => { foreignKey: 'order_id', as: 'items', }); + + // 关联入库单-收货单绑定记录 + EntryOrder.hasMany(EntryOrderReceiving, { + foreignKey: 'entry_order_id', + as: 'receivingBindings', + }); }; // 实例方法 - EntryOrder.prototype.isPending = function() { - return this.order_status === 'PENDING'; + EntryOrder.prototype.isCreated = function() { + return this.order_status === 'CREATED'; }; - EntryOrder.prototype.isConfirmed = function() { - return this.order_status === 'CONFIRMED'; + EntryOrder.prototype.isPending = function() { + return this.order_status === 'PENDING'; }; EntryOrder.prototype.isCompleted = function() { @@ -253,20 +259,16 @@ module.exports = app => { return this.order_status === 'CANCELLED'; }; - EntryOrder.prototype.isPartialReceived = function() { - return this.order_status === 'PARTIAL_RECEIVED'; - }; - EntryOrder.prototype.canConfirm = function() { - return [ 'PENDING' ].includes(this.order_status); + return [ 'CREATED', 'PENDING' ].includes(this.order_status); }; EntryOrder.prototype.canCancel = function() { - return [ 'PENDING', 'CONFIRMED' ].includes(this.order_status); + return [ 'CREATED', 'PENDING' ].includes(this.order_status); }; EntryOrder.prototype.canComplete = function() { - return [ 'CONFIRMED', 'PARTIAL_RECEIVED' ].includes(this.order_status); + return [ 'PENDING' ].includes(this.order_status); }; EntryOrder.prototype.isSyncSuccess = function() { diff --git a/app/model/entry_order_receiving.js b/app/model/entry_order_receiving.js new file mode 100644 index 0000000..fd823ad --- /dev/null +++ b/app/model/entry_order_receiving.js @@ -0,0 +1,76 @@ +'use strict'; + +module.exports = app => { + const { BIGINT, DATE } = app.Sequelize; + + const EntryOrderReceiving = app.model.define('wms_entry_order_receiving', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键ID', + }, + entry_order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '入库单ID,关联 wms_entry_order.id', + }, + receiving_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '收货单ID,关联 wms_receiving.id', + }, + created_at: { + type: DATE, + allowNull: false, + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + comment: '更新时间', + }, + }, { + tableName: 'wms_entry_order_receiving', + comment: '入库单-收货单主表级绑定关系表', + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: true, + deletedAt: 'deleted_at', + indexes: [ + { + name: 'idx_entry_order_id', + fields: ['entry_order_id'], + }, + { + name: 'idx_receiving_id', + fields: ['receiving_id'], + }, + { + name: 'uk_entry_order_receiving', + unique: true, + fields: ['entry_order_id', 'receiving_id'], + }, + ], + }); + + // 关联关系 + EntryOrderReceiving.associate = function() { + const { EntryOrderReceiving, EntryOrder, Receiving } = app.model; + + // 关联入库单 + EntryOrderReceiving.belongsTo(EntryOrder, { + foreignKey: 'entry_order_id', + as: 'entryOrder', + }); + + // 关联收货单 + EntryOrderReceiving.belongsTo(Receiving, { + foreignKey: 'receiving_id', + as: 'receiving', + }); + }; + + return EntryOrderReceiving; +}; diff --git a/app/model/entry_receiving_binding.js b/app/model/entry_receiving_binding.js new file mode 100644 index 0000000..1f7fffc --- /dev/null +++ b/app/model/entry_receiving_binding.js @@ -0,0 +1,99 @@ +'use strict'; + +module.exports = app => { + const { INTEGER, BIGINT, ENUM, DATE } = app.Sequelize; + + const EntryReceivingBinding = app.model.define('wms_entry_receiving_binding', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键ID', + }, + entry_item_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '入库明细ID', + }, + receiving_detail_id: { + type: INTEGER, + allowNull: false, + comment: '收货明细ID', + }, + allocated_quantity: { + type: INTEGER, + allowNull: false, + comment: '预分配数量', + validate: { + min: 1, + }, + }, + status: { + type: ENUM('pending', 'committed', 'released'), + allowNull: false, + defaultValue: 'pending', + comment: '绑定状态:pending-待提交 committed-已提交 released-已释放', + }, + creator_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '创建人ID', + }, + created_at: { + type: DATE, + allowNull: false, + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + comment: '更新时间', + }, + }, { + tableName: 'wms_entry_receiving_binding', + comment: '入库单明细-收货明细绑定关系表', + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: true, + deletedAt: 'deleted_at', + indexes: [ + { + name: 'idx_entry_item_id', + fields: [ 'entry_item_id' ], + }, + { + name: 'idx_receiving_detail_id', + fields: [ 'receiving_detail_id' ], + }, + { + name: 'idx_status', + fields: [ 'status' ], + }, + { + name: 'uk_entry_receiving', + unique: true, + fields: [ 'entry_item_id', 'receiving_detail_id', 'status' ], + }, + ], + }); + + // 关联关系 + EntryReceivingBinding.associate = function() { + const { EntryReceivingBinding, EntryItems, ReceivingDetail } = app.model; + + // 关联入库明细 + EntryReceivingBinding.belongsTo(EntryItems, { + foreignKey: 'entry_item_id', + as: 'entryItem', + }); + + // 关联收货明细 + EntryReceivingBinding.belongsTo(ReceivingDetail, { + foreignKey: 'receiving_detail_id', + as: 'receivingDetail', + }); + }; + + return EntryReceivingBinding; +}; diff --git a/app/model/inbound_direct_log.js b/app/model/inbound_direct_log.js new file mode 100644 index 0000000..634d27c --- /dev/null +++ b/app/model/inbound_direct_log.js @@ -0,0 +1,103 @@ +'use strict'; + +module.exports = app => { + const { STRING, INTEGER, BIGINT, ENUM, DATE } = app.Sequelize; + + const InboundDirectLog = app.model.define('wms_inbound_direct_log', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键ID', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '货主ID', + }, + stock_id: { + type: BIGINT(20), + allowNull: false, + comment: '商品SKU ID,关联 wms_stock_warehouse.id', + }, + quantity: { + type: INTEGER(12), + allowNull: false, + comment: '入库数量', + }, + inbound_type: { + type: ENUM('import', 'pda'), + allowNull: false, + comment: '入库方式:import-导入入库 pda-PDA入库', + }, + entry_order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '关联入库单ID(可选),关联 wms_entry_order.id', + }, + entry_order_code: { + type: STRING(50), + allowNull: true, + comment: '入库单号(冗余,方便查询)', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注(如导入文件名、PDA操作备注等)', + }, + space_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '存放库位ID,关联 wms_location_space.id', + }, + operator_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '操作人ID', + }, + operator_name: { + type: STRING(50), + allowNull: true, + comment: '操作人名称', + }, + created_at: { + type: DATE, + allowNull: false, + comment: '创建时间', + }, + }, { + tableName: 'wms_inbound_direct_log', + comment: '非收货单途径入库直接记录表(导入/PDA入库)', + timestamps: false, + indexes: [ + { + name: 'idx_warehouse_id', + fields: [ 'warehouse_id' ], + }, + { + name: 'idx_stock_id', + fields: [ 'stock_id' ], + }, + { + name: 'idx_inbound_type', + fields: [ 'inbound_type' ], + }, + { + name: 'idx_entry_order_id', + fields: [ 'entry_order_id' ], + }, + { + name: 'idx_created_at', + fields: [ 'created_at' ], + }, + ], + }); + + return InboundDirectLog; +}; diff --git a/app/model/order_delivery.js b/app/model/order_delivery.js index c64c861..8b76074 100644 --- a/app/model/order_delivery.js +++ b/app/model/order_delivery.js @@ -128,7 +128,7 @@ module.exports = app => { comment: '支付时间', }, pay_no: { - type: STRING(50), + type: TEXT, allowNull: true, comment: '支付单号', }, diff --git a/app/model/receiving.js b/app/model/receiving.js index 340808e..b8c52ae 100644 --- a/app/model/receiving.js +++ b/app/model/receiving.js @@ -160,7 +160,7 @@ module.exports = app => { // 关联定义 Receiving.associate = function() { - const { ReceivingDetail, Store, AccountStoreEmployee, StoreWarehouse } = app.model; + const { ReceivingDetail, Store, AccountStoreEmployee, StoreWarehouse, EntryOrderReceiving } = app.model; // 关联收货明细 Receiving.hasMany(ReceivingDetail, { foreignKey: 'receiving_id', @@ -186,6 +186,12 @@ module.exports = app => { as: 'store', constraints: false, }); + + // 关联入库单-收货单绑定记录 + Receiving.hasMany(EntryOrderReceiving, { + foreignKey: 'receiving_id', + as: 'entryOrderBindings', + }); }; return Receiving; diff --git a/app/model/store.js b/app/model/store.js index 105b028..f7acc0f 100644 --- a/app/model/store.js +++ b/app/model/store.js @@ -38,6 +38,10 @@ module.exports = app => { require_pick: true, }); + const DEFAULT_CUTOFF_ORDER_TIME = '18:00'; + const CUTOFF_ORDER_TIME_MIN = '12:00'; + const CUTOFF_ORDER_TIME_MAX = '23:59'; + const DEFAULT_SUBJECT_CONFIG = Object.freeze({ max_notice_webhook_count: DEFAULT_MAX_NOTICE_WEBHOOK_COUNT, max_wave_quantity: DEFAULT_MAX_WAVE_QUANTITY, @@ -48,6 +52,8 @@ module.exports = app => { delete_order_wave_prefix: 'A', inventory_warning_rules: DEFAULT_INVENTORY_WARNING_RULES, auto_outbound_rules: DEFAULT_AUTO_OUTBOUND_RULES, + cutoff_order_enabled: 1, + cutoff_order_time: DEFAULT_CUTOFF_ORDER_TIME, }); const normalizeSubjectConfigText = (value, defaultValue) => { @@ -281,6 +287,22 @@ module.exports = app => { normalized.inventory_warning_rules = normalizeInventoryWarningRules(parsed.inventory_warning_rules); normalized.auto_outbound_rules = normalizeAutoOutboundRules(parsed.auto_outbound_rules); + if (Object.prototype.hasOwnProperty.call(parsed, 'cutoff_order_enabled')) { + normalized.cutoff_order_enabled = normalizeBooleanFlag(parsed.cutoff_order_enabled, 'subject_config.cutoff_order_enabled'); + } + + if (Object.prototype.hasOwnProperty.call(parsed, 'cutoff_order_time')) { + const cutoffTime = normalizeSubjectConfigText(parsed.cutoff_order_time, DEFAULT_CUTOFF_ORDER_TIME); + if (!/^([01]\d|2[0-3]):[0-5]\d$/.test(cutoffTime)) { + throw new Error('subject_config.cutoff_order_time 格式必须为 HH:mm(如 18:00)'); + } + if (cutoffTime < CUTOFF_ORDER_TIME_MIN || cutoffTime > CUTOFF_ORDER_TIME_MAX) { + normalized.cutoff_order_time = DEFAULT_CUTOFF_ORDER_TIME; + } else { + normalized.cutoff_order_time = cutoffTime; + } + } + return normalized; }; diff --git a/app/model/store_warehouse.js b/app/model/store_warehouse.js index b1564f3..e3c5055 100644 --- a/app/model/store_warehouse.js +++ b/app/model/store_warehouse.js @@ -197,6 +197,25 @@ module.exports = app => { Object.freeze({ value: '5', label: '拣货库位商品名称条码和数量' }), ], }), + Object.freeze({ + key: 'cutoff_order_enabled', + name: '启用截单', + type: 'flag', + default: 1, + required: false, + description: '启用后,当天订单创建时间超过截单时间,不再自动分配快递和储位,不再自动加团', + }), + Object.freeze({ + key: 'cutoff_order_time', + name: '截单时间', + type: 'string', + default: '18:00', + required: false, + maxLength: 5, + min: '12:00', + max: '23:59', + description: '截单时间,格式 HH:mm,如 16:00', + }), ]); const POLICY_CONFIG_FIELD_MAP = Object.freeze(POLICY_CONFIG_FIELDS.reduce((result, field) => { result[field.key] = field; @@ -378,7 +397,12 @@ module.exports = app => { if (text.length > field.maxLength) { throw new Error(`${fieldName}.${field.key} 长度不能超过 ${field.maxLength}`); } - normalized[field.key] = text; + // 时间类型字符串范围校验 + if (field.min !== undefined && field.max !== undefined && text !== '' && (text < field.min || text > field.max)) { + normalized[field.key] = field.default !== undefined ? String(field.default) : ''; + } else { + normalized[field.key] = text; + } } } catch (error) { if (!sanitizeOnly) { diff --git a/app/service/openapiMethods/entryorder.js b/app/service/openapiMethods/entryorder.js new file mode 100644 index 0000000..7029ba9 --- /dev/null +++ b/app/service/openapiMethods/entryorder.js @@ -0,0 +1,203 @@ +'use strict'; + +const MainService = require('../main'); + +/** + * OpenAPI 入库单服务。 + * 对外提供入库单的创建与查询能力,通过 openapi 通道对接外部系统。 + */ +class OpenapiEntryorderService extends MainService { + + /** + * 通过 app_key 解析仓库与货主信息。 + * 查询 ApiApp 并关联 StoreWarehouse 以获取 storeId、warehouseId。 + * warehouseCode 优先使用 qimen_warehouse_code,为空时回退使用 warehouseId。 + * @param {string} appKey 开放接口 app_key。 + * @return {Promise} 包含 storeId、warehouseId、appKey、customerId、warehouseCode 的信息对象。 + */ + async resolveAppInfo(appKey) { + const { ctx, app } = this; + const normalizedAppKey = String(appKey || '').trim(); + if (!normalizedAppKey) { + throw new Error('app_key 缺失'); + } + + const appConfig = await ctx.model.ApiApp.findOne({ + attributes: [ + 'id', + 'warehouse_id', + 'qimen_warehouse_code', + [ app.Sequelize.col('contract.store_id'), 'store_id' ], + ], + where: { + self_app_key: normalizedAppKey, + is_enabled: 1, + }, + include: [ + { + model: ctx.model.StoreWarehouse, + as: 'contract', + attributes: [], + required: false, + }, + ], + raw: true, + }); + + if (!appConfig || !appConfig.warehouse_id) { + throw new Error(`无法解析仓库信息,请检查 app_key: ${normalizedAppKey}`); + } + + const warehouseId = appConfig.warehouse_id; + + return { + storeId: appConfig.store_id || null, + warehouseId, + appKey: normalizedAppKey, + customerId: null, + warehouseCode: appConfig.qimen_warehouse_code || String(warehouseId), + }; + } + + /** + * 创建入库单。 + * 接收外部系统的入库单数据,校验后通过底层 entryOrder 服务完成入库单创建。 + * @param {Object} payload 调用参数。 + * @param {Object} payload.body 请求体数据,包含 entryOrder(入库单信息)和 orderLines(明细行)。 + * @param {Object} payload.query 请求 query 数据,需包含 app_key。 + * @return {Promise} 创建结果,成功时返回 entryOrderId、entryOrderCode、status 和 createTime。 + */ + async create(payload = {}) { + const { body = {}, query = {} } = payload; + const { entryOrder, orderLines } = body; + + if (!entryOrder || !entryOrder.entryOrderCode) { + return this.fail('entryOrder.entryOrderCode 参数缺失'); + } + + if (!orderLines || !orderLines.orderLine) { + return this.fail('orderLines.orderLine 参数缺失'); + } + + // 字段映射:OpenAPI 风格字段名 → 底层 tryCreateEntryOrder 期望的字段名 + const mappedEntryOrder = { + entryOrderCode: entryOrder.entryOrderCode, + orderType: entryOrder.entryOrderType || entryOrder.orderType || 'SCRK', + expectStartTime: entryOrder.expectedArriveTime || entryOrder.expectStartTime || '', + expectEndTime: entryOrder.expectEndTime || '', + supplierCode: entryOrder.supplierCode || '', + supplierName: entryOrder.supplierName || '', + warehouseCode: entryOrder.warehouseCode || '', + ownerCode: entryOrder.ownerCode || '', + remark: entryOrder.remark || '', + totalOrderLines: entryOrder.totalOrderLines || 0, + operateTime: entryOrder.operateTime || '', + operatorName: entryOrder.operatorName || '', + orderCreateTime: entryOrder.orderCreateTime || entryOrder.createTime || '', + logisticsCode: entryOrder.logisticsCode || '', + logisticsName: entryOrder.logisticsName || '', + expressCode: entryOrder.expressCode || '', + relatedOrders: entryOrder.relatedOrders || undefined, + }; + + try { + const info = await this.resolveAppInfo(query.app_key); + this.setInfo( + info.storeId, + info.warehouseId, + info.appKey, + info.customerId, + info.warehouseCode + ); + + const data = { + request: { + entryOrder: mappedEntryOrder, + orderLines, + }, + }; + + const res = await this.ctx.service.systems.entryOrder.addOrder( + data, + this.getInfo(), + 'API' + ); + + if (res.success) { + return this.success(res.message, { + createTime: this.app.formatDate(new Date()), + entryOrderId: res.data.entryOrderId, + entryOrderCode: res.data.entryOrderCode, + status: res.data.status, + }); + } + + return this.fail(res.message, { createTime: this.app.formatDate(new Date()) }); + } catch (error) { + return this.fail(`创建入库单失败: ${error.message}`); + } + } + + /** + * 查询入库单。 + * 根据入库单号查询入库单详情,包括基本信息与商品明细。 + * @param {Object} payload 调用参数。 + * @param {Object} payload.body 请求体数据,需包含 entryOrderCode(入库单号)。 + * @param {Object} payload.query 请求 query 数据,需包含 app_key。 + * @return {Promise} 查询结果,成功时返回入库单详情。 + */ + async query(payload = {}) { + const { body = {}, query = {} } = payload; + const { entryOrderCode } = body; + + if (!entryOrderCode) { + return this.fail('entryOrderCode 参数缺失'); + } + + try { + const info = await this.resolveAppInfo(query.app_key); + const order = await this.ctx.service.systems.entryOrder.findByOrderCode( + entryOrderCode, + info.warehouseId, + info.storeId + ); + + if (!order) { + return this.fail('未找到入库单'); + } + + const orderLines = (order.items || []).map(item => ({ + itemId: item.stock_id, + itemCode: (item.stock && item.stock.item_code) || '', + itemName: (item.stock && item.stock.item_name) || '', + planQty: item.count, + actualQty: item.actual_qty || 0, + inventoryType: item.inventory_type || 'ZP', + orderLineNo: item.order_line_no || '', + remark: item.remark || '', + })); + + return this.success('查询成功', { + entryOrderCode: order.entry_order_code, + entryOrderId: order.id, + status: order.order_status, + entryOrderType: order.order_type || 'SCRK', + expectedArriveTime: order.expected_arrive_time || '', + supplierCode: order.supplier_code || '', + supplierName: order.supplier_name || '', + remark: order.remark || '', + createTime: order.created_at || '', + operateTime: order.updated_at || '', + operatorName: order.operator_name || '', + warehouseCode: order.warehouse_code || info.warehouseCode, + ownerCode: order.store_code || '', + totalOrderLines: order.total_order_lines || 0, + orderLines, + }); + } catch (error) { + return this.fail(`查询入库单失败: ${error.message}`); + } + } +} + +module.exports = OpenapiEntryorderService; diff --git a/app/service/openapiMethods/order.js b/app/service/openapiMethods/order.js index 514d71d..81aef19 100644 --- a/app/service/openapiMethods/order.js +++ b/app/service/openapiMethods/order.js @@ -120,6 +120,13 @@ class OpenapiOrderService extends MainService { transaction, }); + // 释放储位分配锁定库存 + await this.releaseStockLockForCancel({ + orderId: existingOrder.id, + warehouseId: info.warehouseId, + transaction, + }); + await transaction.commit(); // 取消成功后触发 OpenAPI 回调通知(fire-and-forget,不阻塞主流程) @@ -158,6 +165,163 @@ class OpenapiOrderService extends MainService { return this.fail(`取消订单失败: ${error.message}`); } } + + /** + * 取消订单时释放储位分配锁定库存。 + * - 有 wms_picking 记录时:释放 wms_storage.locked_quantity 与 wms_stock_warehouse.locked_quantity, + * 并删除对应的 wms_picking 分配记录。 + * - 无 wms_picking 记录时:从 wms_order_items 查询该订单的 stock_id 与 plan_qty, + * 只释放 wms_stock_warehouse.locked_quantity。 + * + * @param {Object} options - 释放参数。 + * @param {number} options.orderId - 订单ID。 + * @param {number} options.warehouseId - 仓库ID。 + * @param {Object} options.transaction - 数据库事务对象。 + * @return {Promise} + */ + async releaseStockLockForCancel({ orderId, warehouseId, transaction } = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + if (!orderId || !warehouseId) { + return; + } + + const pickingModel = ctx.model.Picking; + const storageModel = ctx.model.Storage; + const stockModel = ctx.model.StockWarehouse; + + if (!pickingModel || !storageModel || !stockModel) { + ctx.logger.warn('[openapi order.cancel releaseStockLockForCancel] 模型不可用,跳过库存释放'); + return; + } + + // 查找该订单的有效分配记录 + const pickingRows = await pickingModel.findAll({ + where: { + order_id: orderId, + status: { [Op.ne]: 'cancel' }, + }, + transaction, + lock: transaction.LOCK.UPDATE, + raw: true, + }); + + if (!Array.isArray(pickingRows) || pickingRows.length === 0) { + // 无储位分配记录:从订单明细获取锁定信息,只释放 stock_warehouse 锁 + const orderItemsModel = await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId); + if (!orderItemsModel) { + ctx.logger.warn('[openapi order.cancel releaseStockLockForCancel] OrderItems 模型不可用,跳过库存释放'); + return; + } + + const orderItems = await orderItemsModel.findAll({ + where: { order_id: orderId }, + attributes: [ 'stock_id', 'plan_qty' ], + raw: true, + transaction, + }); + + for (const item of orderItems) { + const stockId = Number(item.stock_id || 0); + const qty = Number(item.plan_qty || 0); + if (stockId <= 0 || qty <= 0) continue; + + await stockModel.update( + { + locked_quantity: app.Sequelize.literal(`locked_quantity - ${qty}`), + updated_at: app.Sequelize.literal('CURRENT_TIMESTAMP'), + }, + { + where: { id: stockId, locked_quantity: { [Op.gte]: qty } }, + transaction, + } + ); + } + return; + } + + // 按 storage_id 汇总释放数量 + const storageQuantityMap = new Map(); + for (const row of pickingRows) { + const storageId = Number(row.storage_id || 0); + const quantity = Number(row.quantity || 0); + if (storageId > 0 && quantity > 0) { + storageQuantityMap.set(storageId, (storageQuantityMap.get(storageId) || 0) + quantity); + } + } + + if (storageQuantityMap.size === 0) { + return; + } + + // 查出关联的 wms_storage 记录,获取 stock_id + const storageIds = Array.from(storageQuantityMap.keys()); + const storageRows = await storageModel.findAll({ + where: { + id: { [Op.in]: storageIds }, + }, + transaction, + lock: transaction.LOCK.UPDATE, + raw: true, + }); + + const storageMap = new Map(); + for (const row of storageRows) { + storageMap.set(Number(row.id), row); + } + + // 依次释放 wms_storage 与 wms_stock_warehouse 锁定数量 + for (const [ storageId, quantity ] of storageQuantityMap.entries()) { + const storageRow = storageMap.get(storageId); + if (!storageRow) { + ctx.logger.warn(`[openapi order.cancel] 库存记录不存在,跳过: storageId=${storageId}`); + continue; + } + + const stockId = Number(storageRow.stock_id || 0); + if (stockId <= 0) { + ctx.logger.warn(`[openapi order.cancel] 库存记录缺少 stock_id,跳过: storageId=${storageId}`); + continue; + } + + // 释放 wms_storage.locked_quantity + await ctx.service.systems.storage.index.unlockQuantity(storageId, quantity, { transaction }); + + // 释放 wms_stock_warehouse.locked_quantity + const decrementResult = await stockModel.update( + { + locked_quantity: app.Sequelize.literal(`locked_quantity - ${Number(quantity)}`), + updated_at: app.Sequelize.literal('CURRENT_TIMESTAMP'), + }, + { + where: { + id: stockId, + locked_quantity: { [Op.gte]: Number(quantity) }, + }, + transaction, + } + ); + + if (!Array.isArray(decrementResult) || Number(decrementResult[0] || 0) <= 0) { + throw new Error(`库存主记录锁定数量不足,无法释放: stockId=${stockId}, quantity=${quantity}`); + } + } + + // 删除已释放的分配记录 + const pickingIds = pickingRows + .map(row => Number(row.id || 0)) + .filter(id => id > 0); + + if (pickingIds.length > 0) { + await pickingModel.destroy({ + where: { + id: { [Op.in]: pickingIds }, + }, + transaction, + }); + } + } } module.exports = OpenapiOrderService; diff --git a/app/service/qimenMethods/order.js b/app/service/qimenMethods/order.js index 544f425..adac7d9 100644 --- a/app/service/qimenMethods/order.js +++ b/app/service/qimenMethods/order.js @@ -212,6 +212,13 @@ class orderServer extends MainService { transaction, }); + // 释放储位分配锁定库存(wms_storage / wms_stock_warehouse) + await this.releaseStorageLockForCancel({ + orderId: existingOrder.id, + warehouseId: info.warehouseId, + transaction, + }); + await transaction.commit(); return this.success('取消订单成功'); } catch (error) { @@ -252,6 +259,164 @@ class orderServer extends MainService { return this.fail(`未识别的作业类型${orderType.method}`, {}); } } + + /** + * 取消订单时释放储位分配锁定库存。 + * - 有 wms_picking 记录时:释放 wms_storage.locked_quantity 与 wms_stock_warehouse.locked_quantity, + * 并删除对应的 wms_picking 分配记录。 + * - 无 wms_picking 记录时:从 wms_order_items 查询该订单的 stock_id 与 plan_qty, + * 只释放 wms_stock_warehouse.locked_quantity。 + * + * @param {Object} options - 释放参数。 + * @param {number} options.orderId - 订单ID。 + * @param {number} options.warehouseId - 仓库ID。 + * @param {Object} options.transaction - 数据库事务对象。 + * @return {Promise} + */ + async releaseStorageLockForCancel({ orderId, warehouseId, transaction } = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + if (!orderId || !warehouseId) { + return; + } + + const pickingModel = ctx.model.Picking; + const storageModel = ctx.model.Storage; + const stockModel = ctx.model.StockWarehouse; + + if (!pickingModel || !storageModel || !stockModel) { + ctx.logger.warn('[qimen order.cancel releaseStorageLockForCancel] 模型不可用,跳过库存释放'); + return; + } + + // 查找该订单的有效分配记录 + const pickingRows = await pickingModel.findAll({ + where: { + order_id: orderId, + status: { [Op.ne]: 'cancel' }, + }, + transaction, + lock: transaction.LOCK.UPDATE, + raw: true, + }); + + if (!Array.isArray(pickingRows) || pickingRows.length === 0) { + // 无储位分配记录:从订单明细获取锁定信息,只释放 stock_warehouse 锁 + const orderItemsModel = await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId); + if (!orderItemsModel) { + ctx.logger.warn('[qimen order.cancel releaseStorageLockForCancel] OrderItems 模型不可用,跳过库存释放'); + return; + } + + const orderItems = await orderItemsModel.findAll({ + where: { order_id: orderId }, + attributes: [ 'stock_id', 'plan_qty' ], + raw: true, + transaction, + }); + + for (const item of orderItems) { + const stockId = Number(item.stock_id || 0); + const qty = Number(item.plan_qty || 0); + if (stockId <= 0 || qty <= 0) continue; + + await stockModel.update( + { + locked_quantity: app.Sequelize.literal(`locked_quantity - ${qty}`), + updated_at: app.Sequelize.literal('CURRENT_TIMESTAMP'), + }, + { + where: { id: stockId, locked_quantity: { [Op.gte]: qty } }, + transaction, + } + ); + } + return; + } + + // 按 storage_id 汇总释放数量 + const storageQuantityMap = new Map(); + for (const row of pickingRows) { + const storageId = Number(row.storage_id || 0); + const quantity = Number(row.quantity || 0); + if (storageId > 0 && quantity > 0) { + storageQuantityMap.set(storageId, (storageQuantityMap.get(storageId) || 0) + quantity); + } + } + + if (storageQuantityMap.size === 0) { + return; + } + + // 查出关联的 wms_storage 记录,获取 stock_id + const storageIds = Array.from(storageQuantityMap.keys()); + const storageRows = await storageModel.findAll({ + where: { + id: { [Op.in]: storageIds }, + }, + transaction, + lock: transaction.LOCK.UPDATE, + raw: true, + }); + + const storageMap = new Map(); + for (const row of storageRows) { + storageMap.set(Number(row.id), row); + } + + // 依次释放 wms_storage 与 wms_stock_warehouse 锁定数量 + for (const [ storageId, quantity ] of storageQuantityMap.entries()) { + const storageRow = storageMap.get(storageId); + if (!storageRow) { + ctx.logger.warn(`[qimen order.cancel] 库存记录不存在,跳过: storageId=${storageId}`); + continue; + } + + const stockId = Number(storageRow.stock_id || 0); + if (stockId <= 0) { + ctx.logger.warn(`[qimen order.cancel] 库存记录缺少 stock_id,跳过: storageId=${storageId}`); + continue; + } + + // 释放 wms_storage.locked_quantity + await ctx.service.systems.storage.index.unlockQuantity(storageId, quantity, { transaction }); + + // 释放 wms_stock_warehouse.locked_quantity + const decrementResult = await stockModel.update( + { + locked_quantity: app.Sequelize.literal(`locked_quantity - ${Number(quantity)}`), + updated_at: app.Sequelize.literal('CURRENT_TIMESTAMP'), + }, + { + where: { + id: stockId, + locked_quantity: { [Op.gte]: Number(quantity) }, + }, + transaction, + } + ); + + if (!Array.isArray(decrementResult) || Number(decrementResult[0] || 0) <= 0) { + throw new Error(`库存主记录锁定数量不足,无法释放: stockId=${stockId}, quantity=${quantity}`); + } + } + + // 删除已释放的分配记录 + const pickingIds = pickingRows + .map(row => Number(row.id || 0)) + .filter(id => id > 0); + + if (pickingIds.length > 0) { + await pickingModel.destroy({ + where: { + id: { [Op.in]: pickingIds }, + }, + transaction, + }); + } + } + async pending(data) { const orderType = this.orderType[data.request.orderType]; switch (orderType.method) { diff --git a/app/service/systemMethods/comboGoods.js b/app/service/systemMethods/comboGoods.js new file mode 100644 index 0000000..8544f40 --- /dev/null +++ b/app/service/systemMethods/comboGoods.js @@ -0,0 +1,168 @@ +'use strict'; + +const MainService = require('../main'); + +/** + * 将输入值转换为有限数字。 + * + * @param {unknown} value 待转换的值。 + * @param {number} [defaultValue=0] 默认值。 + * @return {number} 转换后的数字。 + */ +function toNumber(value, defaultValue = 0) { + const normalized = Number(value); + return Number.isFinite(normalized) ? normalized : defaultValue; +} + +/** + * 系统方法层:comboGoods(组合商品接口包装层)。 + * 负责参数解构、权限校验出口与统一成功/失败包装。 + */ +class ComboGoodsMethodService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = ''; + const _noNeedLog = ''; + const _noNeedAuth = 'list,search'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 组合商品列表查询(分页)。 + * + * @param {Object} data 请求参数。 + * @param {Object} [data.pagination] 分页参数 {page, pageSize}。 + * @param {Object} [data.where] 筛选条件 {combo_code, combo_name, status, warehouse_id}。 + * @return {Promise} 统一 success 包装的分页列表。 + */ + async list(data = {}) { + const { service } = this; + const requestData = this.isPlainObject(data) ? data : {}; + const pagination = requestData.pagination || {}; + const where = requestData.where || {}; + + const result = await service.systems.comboGoods.list({ + page: toNumber(pagination.page, 1), + pageSize: toNumber(pagination.pageSize, 20), + combo_code: where.combo_code, + combo_name: where.combo_name, + status: where.status, + warehouse_id: where.warehouse_id, + }); + + return this.success('查询成功', result); + } + + /** + * 创建组合商品。 + * + * @param {Object} data 请求参数。 + * @param {string} data.combo_code 组合商品编码。 + * @param {string} data.combo_name 组合商品名称。 + * @param {number} [data.warehouse_id] 仓库ID。 + * @param {string} [data.remark] 备注。 + * @param {string} [data.custom_code] 自定义编码。 + * @param {Object[]} data.items 子商品明细数组 [{item_goods_sku_id, item_quantity}]。 + * @return {Promise} 统一 success 包装的创建结果。 + */ + async create(data = {}) { + const { ctx, service } = this; + const requestData = this.isPlainObject(data) ? data : {}; + + try { + const result = await service.systems.comboGoods.create({ + combo_code: requestData.combo_code, + combo_name: requestData.combo_name, + warehouse_id: requestData.warehouse_id, + remark: requestData.remark, + custom_code: requestData.custom_code, + items: requestData.items, + creator_id: ctx.user?.id, + }); + + return this.success('创建成功', result); + } catch (error) { + return this.fail(error.message || '创建失败'); + } + } + + /** + * 编辑组合商品。 + * + * @param {Object} data 请求参数。 + * @param {number} data.id 组合商品ID(必填)。 + * @param {string} [data.combo_name] 组合商品名称。 + * @param {number} [data.warehouse_id] 仓库ID。 + * @param {string} [data.remark] 备注。 + * @param {string} [data.custom_code] 自定义编码。 + * @param {number} [data.status] 状态 1-启用 0-停用。 + * @param {Object[]} [data.items] 子商品明细数组。 + * @return {Promise} 统一 success 包装的编辑结果。 + */ + async update(data = {}) { + const { ctx, service } = this; + const requestData = this.isPlainObject(data) ? data : {}; + + try { + const result = await service.systems.comboGoods.update({ + id: requestData.id, + combo_name: requestData.combo_name, + warehouse_id: requestData.warehouse_id, + remark: requestData.remark, + custom_code: requestData.custom_code, + status: requestData.status, + items: requestData.items, + editor_id: ctx.user?.id, + }); + + return this.success('编辑成功', result); + } catch (error) { + return this.fail(error.message || '编辑失败'); + } + } + + /** + * 删除组合商品(软删除)。 + * + * @param {Object} data 请求参数。 + * @param {number} data.id 组合商品ID。 + * @return {Promise} 统一 success 包装的删除结果。 + */ + async delete(data = {}) { + const { service } = this; + const requestData = this.isPlainObject(data) ? data : {}; + + try { + const result = await service.systems.comboGoods.delete({ + id: requestData.id, + }); + + return this.success('删除成功', result); + } catch (error) { + return this.fail(error.message || '删除失败'); + } + } + + /** + * 关键字搜索组合商品。 + * + * @param {Object} data 请求参数。 + * @param {string} data.keyword 搜索关键字。 + * @param {number} [data.limit=20] 最大返回条数。 + * @return {Promise} 统一 success 包装的搜索结果。 + */ + async search(data = {}) { + const { service } = this; + const requestData = this.isPlainObject(data) ? data : {}; + + const result = await service.systems.comboGoods.search({ + keyword: requestData.keyword, + limit: requestData.limit, + }); + + return this.success('搜索成功', result); + } +} + +module.exports = ComboGoodsMethodService; diff --git a/app/service/systemMethods/order/index.js b/app/service/systemMethods/order/index.js index e7a15d3..31153ce 100644 --- a/app/service/systemMethods/order/index.js +++ b/app/service/systemMethods/order/index.js @@ -30,6 +30,8 @@ class OrderIndexService extends OrderBaseService { * @param {string} [data.tableType] 导出表类型(驼峰写法)。 * @param {string} [data.module] 订单模块名(可选)。 * @param {string} [data.module_name] 订单模块名(下划线写法)。 + * @param {string} [data.export_mode] 导出模式:waybill(默认,按运单展开)或 item(按商品明细展开)。 + * @param {string} [data.exportMode] 导出模式(驼峰写法)。 * @param {Object} [data.where] 查询条件。 * @param {Object} [data.sort] 排序参数。 * @return {Promise} 统一成功包装响应。 @@ -41,6 +43,8 @@ class OrderIndexService extends OrderBaseService { tableType: tableTypeCamel, module: moduleName, module_name: moduleNameSnake, + export_mode: exportModeSnake, + exportMode: exportModeCamel, where, sort, } = requestData; @@ -73,9 +77,11 @@ class OrderIndexService extends OrderBaseService { error: '', }); + const exportMode = exportModeSnake || exportModeCamel || ''; const result = await this.service.systems.orderExport.exportOrders({ tableType, moduleName: module, + export_mode: exportMode, where: this.isPlainObject(where) ? { ...where } : {}, sort: this.isPlainObject(sort) ? { ...sort } : {}, onProgress: async progress => { @@ -525,7 +531,7 @@ class OrderIndexService extends OrderBaseService { * * @param {Object} data 请求体。 * @param {string} data.waybill_code 运单号。 - * @param {string} data.package_material_code 包材编码。 + * @param {number|string} data.package_material_id 包材ID。 * @return {Promise} 统一成功/失败结构。 * 单条绑定:data 含 {order_id, waybill_code, package_material_id, package_material_name_snapshot, package_material_code}; * 团购批量绑定:data 含 {wave_id, wave_no, business_key, order_id, waybill_code, package_material_id, package_material_code, package_material_name_snapshot, bind_count, bound_waybills, store_name, sys_logistics_name}。 @@ -534,13 +540,13 @@ class OrderIndexService extends OrderBaseService { const requestData = this.isPlainObject(data) ? data : {}; const { waybill_code: waybillCode = '', - package_material_code: packageMaterialCode = '', + package_material_id: packageMaterialId = '', } = requestData; try { const result = await this.service.systems.orderExpress.bindExpressPackageMaterialByWaybill({ waybillCode, - packageMaterialCode, + packageMaterialId, }); return this.success('ok', { diff --git a/app/service/systemMethods/order/pendingOrder.js b/app/service/systemMethods/order/pendingOrder.js index 97ff7a7..67f8f8b 100644 --- a/app/service/systemMethods/order/pendingOrder.js +++ b/app/service/systemMethods/order/pendingOrder.js @@ -566,12 +566,98 @@ class PendingOrderService extends OrderBaseService { }); const orderItemImagesByStockId = await this.getOrderItemImagesByStockIds(orderItems); const orderItemsWithImages = this.attachImagesToOrderItems(orderItems, orderItemImagesByStockId); + + // 收集订单明细中的 stock_id,用于查询商品库存主表信息 + const stockIds = [ ...new Set( + orderItems.map(item => Number(item && item.stock_id)).filter(Boolean) + ) ]; + const stockMap = new Map(); + if (stockIds.length > 0) { + const StockWarehouse = this.ctx.model.StockWarehouse; + if (StockWarehouse) { + const stockWarehouseRows = await StockWarehouse.findAll({ + where: { + id: { [this.app.Sequelize.Op.in]: stockIds }, + warehouse_id: warehouseId, + }, + raw: true, + }); + for (const row of stockWarehouseRows) { + stockMap.set(row.id, row); + } + } + } + + // 构建 order_item_id → orderItem 的快速查找映射 + const orderItemMap = new Map(); + for (const item of orderItems) { + orderItemMap.set(item.id, item); + } + + // 查询已分配的储位信息(排除已取消的分配记录) + const orderItemIds = orderItems.map(item => item.id).filter(Boolean); + const pickingMap = new Map(); + const storageItems = []; + if (orderItemIds.length > 0) { + const { Op } = this.app.Sequelize; + const pickingModel = this.ctx.model.Picking; + if (pickingModel) { + const pickingRows = await pickingModel.findAll({ + where: { + order_item_id: { [Op.in]: orderItemIds }, + status: { [Op.ne]: 'cancel' }, + }, + raw: true, + }); + for (const row of pickingRows) { + const key = row.order_item_id; + if (!pickingMap.has(key)) { + pickingMap.set(key, []); + } + pickingMap.get(key).push({ + space_id: row.space_id, + space_name: row.space_name, + storage_id: row.storage_id, + quantity: row.quantity, + status: row.status, + }); + + // 按库位维度平铺 picking 记录,并附带商品库存信息 + const orderItem = orderItemMap.get(row.order_item_id); + if (orderItem) { + const stockId = Number(orderItem.stock_id || 0); + const stockWarehouse = stockMap.get(stockId); + if (stockWarehouse) { + storageItems.push({ + order_item_id: row.order_item_id, + space_id: row.space_id, + space_name: row.space_name, + storage_id: row.storage_id, + quantity: row.quantity, + status: row.status, + stock_id: stockId, + item_code: stockWarehouse.item_code, + item_name: stockWarehouse.item_name, + sku_property: stockWarehouse.sku_property, + stock_unit: stockWarehouse.stock_unit, + }); + } + } + } + } + } + const orderItemsWithPicking = orderItemsWithImages.map(item => ({ + ...item, + picking_locations: pickingMap.get(item.id) || [], + })); + const expresses = await this.getOrderExpressesByOrderId(orderId, order); return { detail: order, - items: orderItemsWithImages, + items: orderItemsWithPicking, expresses, + storage_items: storageItems, }; } @@ -1712,6 +1798,12 @@ class PendingOrderService extends OrderBaseService { }, } ); + + await this.ctx.service.systemMethods.order.wave.deleteOrderWaveIndexByOrderIds({ + warehouseId, + orderIds: waveOrderIds, + transaction: undefined, + }); } if (WaveBatch) { @@ -1794,6 +1886,16 @@ class PendingOrderService extends OrderBaseService { this.ctx.logger.warn('[PendingOrderService.cancelOrder] 释放储位分配失败,不影响订单取消', allocErr); } + // 释放创建锁(lockItemStorages 加的锁,不含 picking 锁) + try { + await this.releaseCreationLockForCancel({ + orderIds, + warehouseId, + }); + } catch (releaseErr) { + this.ctx.logger.warn('[PendingOrderService.cancelOrder] 释放创建锁失败,不影响订单取消', releaseErr); + } + const updatedOrders = await model.findAll({ where, raw: true, @@ -2733,6 +2835,7 @@ class PendingOrderService extends OrderBaseService { const columns = [ // 必填 { header: '*订单号', key: 'delivery_order_code', width: 24 }, + { header: '店铺名称', key: 'shop_nick', width: 20 }, { header: '*收件人姓名', key: 'name', width: 16 }, { header: '*手机号(mobile/tel至少填一项)', key: 'mobile', width: 28 }, { header: '*详细地址', key: 'detail_address', width: 36 }, @@ -2757,7 +2860,6 @@ class PendingOrderService extends OrderBaseService { { header: '商品名称', key: 'item_name', width: 24 }, { header: '行号', key: 'order_line_no', width: 10 }, { header: '实际价格', key: 'actual_price', width: 12 }, - { header: '店铺名称', key: 'shop_nick', width: 20 }, ]; sheet.columns = columns; @@ -5071,7 +5173,7 @@ class PendingOrderService extends OrderBaseService { && contractConfig.policy_config && contractConfig.policy_config.auto_sync_back === 1 ) { - this.syncOrderIds({ orderIds: [orderId] }).catch(err => { + this.syncOrderIds({ orderIds: [ orderId ] }).catch(err => { this.ctx.logger.error( `[auto_sync_back] manualWaybill 自动同步失败: ${err.message}` ); @@ -5094,6 +5196,170 @@ class PendingOrderService extends OrderBaseService { }); } + /** + * 取消订单时释放创建锁(lockItemStorages 添加的 wms_stock_warehouse.locked_quantity)。 + * + * - 有 wms_picking 有效记录时:通过 storage_id → stock_id 映射汇总各 stock_id 的 picking 数量, + * 释放对应 wms_stock_warehouse.locked_quantity。 + * - 无 wms_picking 记录时:从 wms_order_items 读取 plan_qty, + * 释放对应 wms_stock_warehouse.locked_quantity。 + * + * @param {Object} options - 释放参数。 + * @param {number[]} options.orderIds - 订单ID 数组。 + * @param {number} options.warehouseId - 仓库ID。 + * @return {Promise} + */ + async releaseCreationLockForCancel({ orderIds, warehouseId } = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + if (!Array.isArray(orderIds) || orderIds.length === 0 || !warehouseId) { + return; + } + + const pickingModel = ctx.model.Picking; + const storageModel = ctx.model.Storage; + const stockModel = ctx.model.StockWarehouse; + + if (!pickingModel || !storageModel || !stockModel) { + ctx.logger.warn('[PendingOrderService.releaseCreationLockForCancel] 模型不可用,跳过库存释放'); + return; + } + + const transaction = await ctx.model.transaction(); + + try { + // 查找这些订单的有效储位分配记录(排除已取消的) + const pickingRows = await pickingModel.findAll({ + where: { + order_id: { [Op.in]: orderIds }, + warehouse_id: warehouseId, + status: { [Op.ne]: 'cancel' }, + }, + transaction, + lock: transaction.LOCK.UPDATE, + raw: true, + }); + + if (!Array.isArray(pickingRows) || pickingRows.length === 0) { + // 无储位分配记录:从订单明细获取锁定信息,只释放 stock_warehouse 锁 + const orderItemsModel = await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId); + if (!orderItemsModel) { + ctx.logger.warn('[PendingOrderService.releaseCreationLockForCancel] OrderItems 模型不可用,跳过库存释放'); + await transaction.rollback(); + return; + } + + const orderItems = await orderItemsModel.findAll({ + where: { order_id: { [Op.in]: orderIds } }, + attributes: [ 'stock_id', 'plan_qty' ], + raw: true, + transaction, + }); + + for (const item of orderItems) { + const stockId = Number(item.stock_id || 0); + const qty = Number(item.plan_qty || 0); + if (stockId <= 0 || qty <= 0) continue; + + await stockModel.update( + { + locked_quantity: app.Sequelize.literal(`locked_quantity - ${qty}`), + updated_at: app.Sequelize.literal('CURRENT_TIMESTAMP'), + }, + { + where: { id: stockId, locked_quantity: { [Op.gte]: qty } }, + transaction, + } + ); + } + + await transaction.commit(); + return; + } + + // 有 picking 记录:按 storage_id 汇总释放数量 + const storageQuantityMap = new Map(); + for (const row of pickingRows) { + const storageId = Number(row.storage_id || 0); + const quantity = Number(row.quantity || 0); + if (storageId > 0 && quantity > 0) { + storageQuantityMap.set(storageId, (storageQuantityMap.get(storageId) || 0) + quantity); + } + } + + if (storageQuantityMap.size === 0) { + await transaction.commit(); + return; + } + + // 查出关联的 wms_storage 记录,获取 stock_id + const storageIds = Array.from(storageQuantityMap.keys()); + const storageRows = await storageModel.findAll({ + where: { + id: { [Op.in]: storageIds }, + warehouse_id: warehouseId, + }, + transaction, + lock: transaction.LOCK.UPDATE, + raw: true, + }); + + const storageMap = new Map(); + for (const row of storageRows) { + storageMap.set(Number(row.id), row); + } + + // 按 stock_id 汇总需要释放的数量 + const stockReleaseMap = new Map(); + for (const [ storageId, quantity ] of storageQuantityMap.entries()) { + const storageRow = storageMap.get(storageId); + if (!storageRow) { + ctx.logger.warn(`[PendingOrderService.releaseCreationLockForCancel] 库存记录不存在,跳过: storageId=${storageId}`); + continue; + } + + const stockId = Number(storageRow.stock_id || 0); + if (stockId <= 0) { + ctx.logger.warn(`[PendingOrderService.releaseCreationLockForCancel] 库存记录缺少 stock_id,跳过: storageId=${storageId}`); + continue; + } + + stockReleaseMap.set(stockId, (stockReleaseMap.get(stockId) || 0) + quantity); + } + + // 释放 wms_stock_warehouse.locked_quantity + for (const [ stockId, quantity ] of stockReleaseMap.entries()) { + const decrementResult = await stockModel.update( + { + locked_quantity: app.Sequelize.literal(`locked_quantity - ${Number(quantity)}`), + updated_at: app.Sequelize.literal('CURRENT_TIMESTAMP'), + }, + { + where: { + id: stockId, + locked_quantity: { [Op.gte]: Number(quantity) }, + }, + transaction, + } + ); + + if (!Array.isArray(decrementResult) || Number(decrementResult[0] || 0) <= 0) { + throw new Error(`库存主记录锁定数量不足,无法释放: stockId=${stockId}, quantity=${quantity}`); + } + } + + await transaction.commit(); + } catch (error) { + try { + await transaction.rollback(); + } catch (rollbackError) { + ctx.logger.error('[PendingOrderService.releaseCreationLockForCancel] 回滚失败', rollbackError); + } + throw error; + } + } + } module.exports = PendingOrderService; diff --git a/app/service/systemMethods/order/recheckOrder.js b/app/service/systemMethods/order/recheckOrder.js index 320a635..8753912 100644 --- a/app/service/systemMethods/order/recheckOrder.js +++ b/app/service/systemMethods/order/recheckOrder.js @@ -27,7 +27,9 @@ class RecheckOrderService extends OrderBaseService { * 顶层携带 picker_id、picker_name、task_id * - 车号匹配(散单模式 pick_mode=2/3/4):查询任务关联的所有波次,逐波次构建扫描视图后合并, * 返回 list_type='single',按 order_id 去重,未复核订单排前,顶层携带汇总字段 - * - 运单号命中但订单无波次信息时,退回单订单详情模式(list 每项含 detail/items/expresses/logs) + * - 运单号命中但订单无波次信息时,退回单订单详情模式(list 每项含 detail/items/expresses/logs、 + * items_weight、suggested_package_material) + * - 所有模式的 list[] 每项均附带 items_weight(订单商品总重量)与 suggested_package_material(推荐包材信息,无推荐时为 null) * @param {Object} data 请求体。 * @param {string} [data.keyword] 通用扫描关键词。 * @param {string} [data.value] 通用扫描关键词别名。 @@ -38,7 +40,8 @@ class RecheckOrderService extends OrderBaseService { * @param {string} [data.waveNo] 波次号别名。 * @param {string} [data.cart_code] 车号。 * @param {string} [data.cartCode] 车号别名。 - * @return {Promise} 扫描结果,包含 match_type、list_type、picker_id、picker_name、task_id(散单/团单均有)与 list 数组。 + * @return {Promise} 扫描结果,包含 match_type、list_type、picker_id、picker_name、task_id(散单/团单均有)与 list 数组, + * list 每项含 items_weight、suggested_package_material。 */ async scanOrder(data = {}) { const warehouseId = this.getWarehouseId(); @@ -85,15 +88,24 @@ class RecheckOrderService extends OrderBaseService { // 找不到拣货任务时退回单订单详情模式 this.assertOrderCanRecheck(order); const detailResult = await this.detail({ id: orderId }); + const fallbackOrder = detailResult.detail || {}; + const fallbackPackageMap = await this.batchQueryPackageMaterialRecommendation( + [{ items_hash: fallbackOrder.items_hash, items_crc: fallbackOrder.items_crc }], + warehouseId + ); + const fallbackItemHash = String(fallbackOrder.items_hash || '').trim(); return { match_type: matchType, list_type: 'single', waybill_no: keyword, list: [{ - ...(detailResult.detail || {}), + ...fallbackOrder, items: Array.isArray(detailResult.items) ? detailResult.items : [], expresses: Array.isArray(detailResult.expresses) ? detailResult.expresses : [], logs: Array.isArray(detailResult.logs) ? detailResult.logs : [], + suggested_package_material: fallbackItemHash + ? (fallbackPackageMap.get(fallbackItemHash) || null) + : null, }], }; } @@ -118,15 +130,24 @@ class RecheckOrderService extends OrderBaseService { // 无波次信息时退回单订单模式 this.assertOrderCanRecheck(order); const detailResult = await this.detail({ id: orderId }); + const noWaveOrder = detailResult.detail || {}; + const noWavePackageMap = await this.batchQueryPackageMaterialRecommendation( + [{ items_hash: noWaveOrder.items_hash, items_crc: noWaveOrder.items_crc }], + warehouseId + ); + const noWaveItemHash = String(noWaveOrder.items_hash || '').trim(); return { match_type: matchType, list_type: 'single', waybill_no: keyword, list: [{ - ...(detailResult.detail || {}), + ...noWaveOrder, items: Array.isArray(detailResult.items) ? detailResult.items : [], expresses: Array.isArray(detailResult.expresses) ? detailResult.expresses : [], logs: Array.isArray(detailResult.logs) ? detailResult.logs : [], + suggested_package_material: noWaveItemHash + ? (noWavePackageMap.get(noWaveItemHash) || null) + : null, }], }; } @@ -459,7 +480,9 @@ class RecheckOrderService extends OrderBaseService { * @param {string} waveNo 波次号。 * @param {number} warehouseId 仓库ID。 * @return {Promise} 扁平化扫描视图,包含 picker_id、picker_name、task_id、wave_id、wave_no、 - * wave_type、pick_mode、strategy_id、strategy_name、total_orders、reviewed_count、unreviewed_count、list。 + * wave_type、pick_mode、strategy_id、strategy_name、total_orders、reviewed_count、unreviewed_count、 + * printed_count、unprinted_count、list。 + * list 中每项额外包含 items_weight(订单商品总重量)与 suggested_package_material(推荐包材信息,无推荐时为 null)。 */ async buildSingleWaveScanView(waveId, waveNo, warehouseId) { const baseWaveView = await this.buildSingleWaveView(waveId, waveNo, warehouseId); @@ -490,6 +513,19 @@ class RecheckOrderService extends OrderBaseService { const printedCount = orders.filter(o => o.is_printed === true).length; const unprintedCount = orders.length - printedCount; + // 批量查询包材推荐 + const packageMaterialMap = await this.batchQueryPackageMaterialRecommendation(orders, warehouseId); + + // 为每个订单附加 items_weight 和包材推荐 + const enrichedOrders = orders.map(order => { + const itemsHash = String(order.items_hash || '').trim(); + return { + ...order, + items_weight: order.items_weight != null ? Number(order.items_weight) : 0, + suggested_package_material: itemsHash ? (packageMaterialMap.get(itemsHash) || null) : null, + }; + }); + return { picker_id: pickerInfo.picker_id, picker_name: pickerInfo.picker_name, @@ -505,7 +541,7 @@ class RecheckOrderService extends OrderBaseService { unreviewed_count: unreviewedCount, printed_count: printedCount, unprinted_count: unprintedCount, - list: orders, + list: enrichedOrders, }; } @@ -616,7 +652,10 @@ class RecheckOrderService extends OrderBaseService { * order_count、box_no、reviewed_count、unreviewed_count、printed_count、unprinted_count、 * stocks(非拦截订单合并后的商品明细)、 * intercepted(拦截订单列表,仅当波次中存在拦截订单时出现,每项含 wave_index、order_id、 - * delivery_order_code、intercept_status 等字段)。 + * delivery_order_code、intercept_status 等字段)、 + * items_weight(订单商品总重量,取自波次内首个正常订单)、 + * suggested_package_material(推荐包材信息,无推荐时为 null)、 + * first_waybill_no(波次内首个正常订单的运单号,用于包材绑定等后续操作,无正常订单时为第一个订单的运单号,均无则为空字符串)。 */ async buildGroupWaveList(taskId, warehouseId) { const { ctx } = this; @@ -760,12 +799,46 @@ class RecheckOrderService extends OrderBaseService { result.intercepted = intercepted; } + // 团购波次内所有订单商品结构一致,暂存样本订单的商品指纹信息用于后续批量查询包材推荐 + result._sample_hash = sampleOrder ? String(sampleOrder.items_hash || '').trim() : ''; + result._sample_crc = sampleOrder ? Number(sampleOrder.items_crc || 0) : 0; + result.items_weight = sampleOrder ? Number(sampleOrder.items_weight || 0) : 0; + result.suggested_package_material = null; + + // 波次内首个订单的运单号,用于包材绑定等后续操作 + // 优先取首个正常订单的运单号,若无正常订单则取首个订单(含拦截)的运单号,均无则为空字符串 + const firstNonIntercepted = normalOrders.length > 0 ? normalOrders[0] : null; + const firstAnyOrder = orders.length > 0 ? orders[0] : null; + const firstOrderForWaybill = firstNonIntercepted || firstAnyOrder; + result.first_waybill_no = firstOrderForWaybill + ? String(firstOrderForWaybill.waybill_no || '').trim() + : ''; + return result; }); - const waveViews = await Promise.all(waveViewPromises); + const waveViews = (await Promise.all(waveViewPromises)).filter(view => view !== null); - return waveViews.filter(view => view !== null); + // 批量查询所有波次的包材推荐 + if (waveViews.length > 0) { + const sampleOrdersForPackageQuery = waveViews + .filter(wv => wv._sample_hash) + .map(wv => ({ items_hash: wv._sample_hash, items_crc: wv._sample_crc })); + const packageMaterialMap = await this.batchQueryPackageMaterialRecommendation( + sampleOrdersForPackageQuery, + warehouseId + ); + for (const wv of waveViews) { + if (wv._sample_hash) { + wv.suggested_package_material = packageMaterialMap.get(wv._sample_hash) || null; + } + // 清理内部临时字段 + delete wv._sample_hash; + delete wv._sample_crc; + } + } + + return waveViews; } /** @@ -894,7 +967,7 @@ class RecheckOrderService extends OrderBaseService { * @return {Promise>} 订单基本信息列表,每项含 order_id、delivery_order_code、 * waybill_no、pick_status、is_printed、is_reviewed、shop_nick、items_count、 * wave_index、recheck_status、wave_id、wave_no、order_type、status、 - * logistics_name、store_remark、intercept_status、stock 等字段。 + * logistics_name、store_remark、intercept_status、items_weight、items_hash、items_crc、stock 等字段。 */ async getWaveOrdersBasic(waveNo, warehouseId) { const normalizedWaveNo = String(waveNo || '').trim(); @@ -908,6 +981,7 @@ class RecheckOrderService extends OrderBaseService { where: { wave_no: normalizedWaveNo, warehouse_id: warehouseId, + recheck_status: { [this.app.Sequelize.Op.ne]: 'fin' }, }, attributes: [ 'id', @@ -925,6 +999,9 @@ class RecheckOrderService extends OrderBaseService { 'print_status', 'store_id', 'intercept_status', + 'items_weight', + 'items_hash', + 'items_crc', ], order: [[ 'id', 'ASC' ]], raw: true, @@ -1045,6 +1122,9 @@ class RecheckOrderService extends OrderBaseService { ? storeRemarkMap.get(Number(row.store_id || 0)) : '', intercept_status: String(row.intercept_status || '').trim(), + items_weight: Number(row.items_weight || 0), + items_hash: String(row.items_hash || '').trim(), + items_crc: Number(row.items_crc || 0), }; }); @@ -1063,6 +1143,97 @@ class RecheckOrderService extends OrderBaseService { return enrichedList; } + /** + * 批量查询包材推荐信息。 + * 根据订单的 items_hash + items_crc 组合,从 wms_package_material_item_relation 表 + * 查询最匹配的包材推荐(按 bind_count 降序取 top-1)。 + * @param {Object[]} orderList 订单列表,每项需含 items_hash、items_crc 字段。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise>} 以 items_hash 为键的包材推荐映射, + * 值为包材信息对象或 null(无推荐时)。 + */ + async batchQueryPackageMaterialRecommendation(orderList, warehouseId) { + const resultMap = new Map(); + + if (!Array.isArray(orderList) || orderList.length === 0) { + return resultMap; + } + + // 收集所有有效的 items_hash,并为每个 hash 记录对应的 items_crc + const hashCrcMap = new Map(); + for (const order of orderList) { + const hash = String(order.items_hash || '').trim(); + if (!hash) { + continue; + } + const crc = Number(order.items_crc || 0); + if (!hashCrcMap.has(hash)) { + hashCrcMap.set(hash, crc); + } + } + + if (hashCrcMap.size === 0) { + return resultMap; + } + + const uniqueHashes = [ ...hashCrcMap.keys() ]; + const { ctx } = this; + + if (!ctx.model || typeof ctx.model.query !== 'function') { + return resultMap; + } + + // 批量查询所有匹配的包材绑定记录,按 bind_count 降序 + let relationRows = []; + try { + relationRows = await ctx.model.query( + `SELECT * FROM wms_package_material_item_relation + WHERE warehouse_id = :warehouseId + AND items_hash IN (:uniqueHashes) + AND is_active = 1 + AND delete_at IS NULL + ORDER BY bind_count DESC`, + { + replacements: { warehouseId, uniqueHashes }, + type: ctx.model.QueryTypes.SELECT, + } + ); + } catch (e) { + ctx.logger.warn(`[recheckOrder.batchQueryPackageMaterialRecommendation] 查询包材推荐失败, error=${e.message}`); + return resultMap; + } + + const rows = Array.isArray(relationRows) ? relationRows : []; + + // 为每个 items_hash 取第一条匹配记录(已按 bind_count DESC 排序,且 items_crc 匹配) + for (const row of rows) { + const hash = String(row.items_hash || '').trim(); + if (!hash || resultMap.has(hash)) { + continue; + } + // 校验 items_crc 是否与订单一致 + const expectedCrc = hashCrcMap.get(hash); + const rowCrc = Number(row.items_crc || 0); + if (expectedCrc !== undefined && expectedCrc !== rowCrc) { + continue; + } + resultMap.set(hash, { + id: row.id != null ? Number(row.id) : null, + code: String(row.package_material_code || '').trim() || null, + name: String(row.package_material_name || '').trim() || null, + spec: String(row.package_material_spec || '').trim() || null, + type: String(row.package_material_type || '').trim() || null, + weight: row.weight != null ? Number(row.weight) : null, + length: row.length != null ? Number(row.length) : null, + width: row.width != null ? Number(row.width) : null, + height: row.height != null ? Number(row.height) : null, + bind_count: row.bind_count != null ? Number(row.bind_count) : null, + }); + } + + return resultMap; + } + /** * 为订单列表批量补充库存信息。 * 查询每个订单的明细商品、库存数量、条码列表和图片,构建 stock 数组。 @@ -1874,7 +2045,7 @@ class RecheckOrderService extends OrderBaseService { return; } - // 任务下所有订单均已复核完成,解绑车任务(失败不影响主流程) + // 任务下所有订单均已复核完成,更新任务状态为复核通过,并解绑车任务(失败不影响主流程) try { await this.unbindCartForTask(taskId, warehouseId, operatorUserId); ctx.logger.info( @@ -1885,6 +2056,30 @@ class RecheckOrderService extends OrderBaseService { `[confirmRecheck] 解绑车任务失败(复核已成功), taskId=${taskId}, orderId=${orderId}, error=${unbindError.message}` ); } + + // 更新 wms_wave_pick_task 任务状态:status=3(已完成),review_status=3(复核通过) + const operatorName = String(operator.name || '').trim(); + const taskStatusSetClauses = [ + 'status = 3', + 'review_status = 3', + 'review_finish_time = :now', + 'review_time = :now', + 'update_time = NOW()', + ]; + if (operatorUserId > 0) { + taskStatusSetClauses.push('review_user_id = :operatorUserId'); + taskStatusSetClauses.push('review_user_name = :operatorName'); + } + await ctx.model.query( + `UPDATE wms_wave_pick_task + SET ${taskStatusSetClauses.join(',\n ')} + WHERE id = :taskId + AND warehouse_id = :warehouseId`, + { + replacements: { taskId, warehouseId, operatorUserId, operatorName, now }, + type: ctx.model.QueryTypes.UPDATE, + } + ); } /** @@ -1972,7 +2167,7 @@ class RecheckOrderService extends OrderBaseService { continue; } - // 任务下所有订单均已复核完成,解绑车任务 + // 任务下所有订单均已复核完成,解绑车任务并更新任务状态 try { await this.unbindCartForTask(taskId, warehouseId, operatorUserId); ctx.logger.info( @@ -1983,6 +2178,30 @@ class RecheckOrderService extends OrderBaseService { `[confirmRecheck] 批量复核-解绑车任务失败, taskId=${taskId}, error=${unbindError.message}` ); } + + // 更新 wms_wave_pick_task 任务状态:status=3(已完成),review_status=3(复核通过) + const operatorName = String(operator.name || '').trim(); + const taskStatusSetClauses = [ + 'status = 3', + 'review_status = 3', + 'review_finish_time = :now', + 'review_time = :now', + 'update_time = NOW()', + ]; + if (operatorUserId > 0) { + taskStatusSetClauses.push('review_user_id = :operatorUserId'); + taskStatusSetClauses.push('review_user_name = :operatorName'); + } + await ctx.model.query( + `UPDATE wms_wave_pick_task + SET ${taskStatusSetClauses.join(',\n ')} + WHERE id = :taskId + AND warehouse_id = :warehouseId`, + { + replacements: { taskId, warehouseId, operatorUserId, operatorName, now }, + type: ctx.model.QueryTypes.UPDATE, + } + ); } } @@ -3547,92 +3766,6 @@ class RecheckOrderService extends OrderBaseService { await ctx.model.StorageTransaction.bulkCreate(transactionRows, { transaction }); } - // 释放 wms_stock_warehouse 锁定数量并写入 wms_stock_transaction 出库流水 - const stockQtyMap = new Map(); - for (const sRow of storageRows) { - const sid = Number(sRow.stock_id); - if (!sid || sid <= 0) continue; - const deduction = storageQtyMap.get(Number(sRow.id)) || 0; - if (deduction <= 0) continue; - stockQtyMap.set(sid, (stockQtyMap.get(sid) || 0) + deduction); - } - - if (stockQtyMap.size > 0) { - const stockIds = Array.from(stockQtyMap.keys()); - const stockWarehouseRows = await ctx.model.StockWarehouse.findAll({ - where: { - id: { [app.Sequelize.Op.in]: stockIds }, - warehouse_id: warehouseId, - }, - attributes: [ 'id', 'quantity', 'locked_quantity' ], - lock: transaction.LOCK.UPDATE, - raw: true, - transaction, - }); - - const stockWarehouseMap = new Map(); - for (const swRow of stockWarehouseRows) { - stockWarehouseMap.set(Number(swRow.id), swRow); - } - - for (const [ stockId, qty ] of stockQtyMap) { - const swRow = stockWarehouseMap.get(stockId); - if (!swRow) { - ctx.logger.warn(`[recheckOrder] stock_warehouse 记录不存在: ${stockId}`); - continue; - } - const currentLocked = Number(swRow.locked_quantity) || 0; - if (currentLocked < qty) { - throw new Error( - `货主库存 ${stockId} 锁定数量不足:当前锁定 ${currentLocked},需释放 ${qty}` - ); - } - await ctx.model.StockWarehouse.update({ - locked_quantity: app.Sequelize.literal(`locked_quantity - ${qty}`), - update_at: app.Sequelize.literal('CURRENT_TIMESTAMP'), - }, { - where: { - id: stockId, - locked_quantity: { [app.Sequelize.Op.gte]: qty }, - }, - transaction, - }); - } - - const operator = this.getOrderLogOperator(); - const opId = String(operator.id || '').trim(); - const opName = String(operator.name || 'system').trim(); - const stockTransactionRows = []; - for (const [ stockId, qty ] of stockQtyMap) { - const swRow = stockWarehouseMap.get(stockId); - if (!swRow) continue; - const sRow = storageRows.find(r => Number(r.stock_id) === stockId); - const beforeQty = Number(swRow.quantity) || 0; - const beforeLocked = Number(swRow.locked_quantity) || 0; - stockTransactionRows.push({ - transaction_type: 'OUTBOUND', - warehouse_id: warehouseId, - store_id: sRow ? Number(sRow.store_id) || 0 : 0, - stock_id: stockId, - quantity: qty, - before_quantity: beforeQty, - after_quantity: Math.max(0, beforeQty - qty), - before_locked_quantity: beforeLocked, - after_locked_quantity: Math.max(0, beforeLocked - qty), - order_type: 'PICK_OUTBOUND', - order_no: String(orderId), - order_id: orderId, - operator_id: opId, - operator_name: opName, - remark: '拣货完成出库-货主库存释放(批量快捷复核)', - created_at: new Date(), - }); - } - - if (stockTransactionRows.length > 0) { - await ctx.model.StockTransaction.bulkCreate(stockTransactionRows, { transaction }); - } - } } } diff --git a/app/service/systemMethods/order/wave.js b/app/service/systemMethods/order/wave.js index 2f94475..8f58a71 100644 --- a/app/service/systemMethods/order/wave.js +++ b/app/service/systemMethods/order/wave.js @@ -850,7 +850,10 @@ class WaveService extends OrderBaseService { } if (structure.distinguish_express) { - where.logistics_name = String(structure.logistics_name || '').trim(); + const expressCode = String(structure.logistics_name || '').trim(); + if (expressCode) { + where.sys_logistics_code = expressCode; + } } return where; @@ -2054,7 +2057,7 @@ class WaveService extends OrderBaseService { buildCoarseGroupKey(order = {}, distinguishExpress = false) { const itemsHash = String(order.items_hash || '').trim(); const itemsText = String(order.items || '').trim(); - const logisticsName = String(order.logistics_name || '').trim(); + const logisticsName = String(order.sys_logistics_code || '').trim(); const itemPart = itemsHash || itemsText; if (!itemPart) { @@ -2097,7 +2100,7 @@ class WaveService extends OrderBaseService { buildGroupKey(order, itemDetails = [], options = {}) { const itemSummary = this.buildItemSummary(itemDetails); const itemSnapshotKey = this.buildItemSnapshotKey(itemDetails); - const logisticsName = String(order.logistics_name || '').trim(); + const logisticsName = String(order.sys_logistics_code || '').trim(); const baseParts = [ itemSnapshotKey ]; if (options.distinguishExpress) { @@ -2166,6 +2169,7 @@ class WaveService extends OrderBaseService { where, attributes: [ 'id', 'store_id', 'logistics_name', + 'sys_logistics_code', 'sys_logistics_name', 'items_hash', 'items', 'items_total', 'items_weight', 'post_status', 'pick_status', 'outbound_status', 'create_at', ], @@ -2266,13 +2270,16 @@ class WaveService extends OrderBaseService { continue; } - const itemPartInfo = this.getOrderItemPart(g.orders[0] || {}); - const logisticsName = String(g.orders[0].logistics_name || '').trim(); + const firstOrder = g.orders[0] || {}; + const itemPartInfo = this.getOrderItemPart(firstOrder); + const logisticsCode = String(firstOrder.sys_logistics_code || '').trim(); + const logisticsNameFromOrder = String(firstOrder.sys_logistics_name || '').trim(); + const logisticsDisplayName = logisticsNameFromOrder || logisticsCode; const itemDetailMachine = this.buildMachineStructureToken({ item_part_type: itemPartInfo.item_part_type, item_part: itemPartInfo.item_part, distinguish_express: distinguishExpress, - logistics_name: logisticsName, + logistics_name: logisticsCode, item_snapshot_key: itemSnapshotKey, }); @@ -2289,9 +2296,6 @@ class WaveService extends OrderBaseService { if (!last_order_time || o.create_at > last_order_time) last_order_time = o.create_at; } - // 同组订单 items_hash 相同,重量一致,取首单即可 - const firstOrder = g.orders[0] || {}; - list.push({ item_detail: itemSummary, item_detail_machine: itemDetailMachine, @@ -2303,7 +2307,8 @@ class WaveService extends OrderBaseService { items_weight: firstOrder.items_weight != null ? Number(firstOrder.items_weight) : null, store_id: store_ids.length === 1 ? store_ids[0] : 0, store_ids, - logistics_name: logisticsName, + logistics_code: logisticsCode, + logistics_name: logisticsDisplayName, distinguish_express: distinguishExpress, ...(returnOrderIds ? { order_ids: g.orders.map(o => Number(o.id)) } : {}), first_order_time, @@ -2402,6 +2407,7 @@ class WaveService extends OrderBaseService { where, attributes: [ 'id', 'store_id', 'logistics_name', + 'sys_logistics_code', 'sys_logistics_name', 'items_hash', 'items', 'items_total', 'items_weight', 'post_status', 'pick_status', 'outbound_status', 'create_at', ], @@ -2502,13 +2508,16 @@ class WaveService extends OrderBaseService { continue; } - const itemPartInfo = this.getOrderItemPart(g.orders[0] || {}); - const logisticsName = String(g.orders[0].logistics_name || '').trim(); + const firstOrder = g.orders[0] || {}; + const itemPartInfo = this.getOrderItemPart(firstOrder); + const logisticsCode = String(firstOrder.sys_logistics_code || '').trim(); + const logisticsNameFromOrder = String(firstOrder.sys_logistics_name || '').trim(); + const logisticsDisplayName = logisticsNameFromOrder || logisticsCode; const itemDetailMachine = this.buildMachineStructureToken({ item_part_type: itemPartInfo.item_part_type, item_part: itemPartInfo.item_part, distinguish_express: distinguishExpress, - logistics_name: logisticsName, + logistics_name: logisticsCode, item_snapshot_key: itemSnapshotKey, }); @@ -2525,9 +2534,6 @@ class WaveService extends OrderBaseService { if (!last_order_time || o.create_at > last_order_time) last_order_time = o.create_at; } - // 同组订单 items_hash 相同,重量一致,取首单即可 - const firstOrder = g.orders[0] || {}; - list.push({ item_detail: itemSummary, item_detail_machine: itemDetailMachine, @@ -2539,7 +2545,8 @@ class WaveService extends OrderBaseService { items_weight: firstOrder.items_weight != null ? Number(firstOrder.items_weight) : null, store_id: store_ids.length === 1 ? store_ids[0] : 0, store_ids, - logistics_name: logisticsName, + logistics_code: logisticsCode, + logistics_name: logisticsDisplayName, distinguish_express: distinguishExpress, ...(returnOrderIds ? { order_ids: g.orders.map(o => Number(o.id)) } : {}), first_order_time, @@ -3631,7 +3638,7 @@ class WaveService extends OrderBaseService { } const availableExpressSet = await this.getWaveStrategyAvailableExpressSet(); - const availableLowerSet = new Set([...availableExpressSet].map(s => s.toLowerCase())); + const availableLowerSet = new Set([ ...availableExpressSet ].map(s => s.toLowerCase())); const illegalExpresses = normalizedExpresses.filter(item => !availableLowerSet.has(String(item).toLowerCase())); if (illegalExpresses.length > 0) { @@ -4188,12 +4195,13 @@ class WaveService extends OrderBaseService { LEFT JOIN ${orderTableName} od ON od.wave_id = candidate_wave.wave_id GROUP BY candidate_wave.wave_id ) wave_order_stats ON wave_order_stats.wave_id = wb.wave_id + LEFT JOIN wms_express e ON e.code = wb.logistics_name WHERE 1 = 1 ${storageAssignmentFilterClause.sql} ${expressAssignmentFilterClause.sql} ${printAssignmentFilterClause.sql} ${reviewAssignmentFilterClause.sql} - ${onlyTodo === 1 ? `\n AND COALESCE(wave_order_stats.order_total, 0) - COALESCE(wave_order_stats.review_fin_count, 0) > 0` : ''} + ${onlyTodo === 1 ? '\n AND COALESCE(wave_order_stats.order_total, 0) - COALESCE(wave_order_stats.review_fin_count, 0) > 0' : ''} `; const listSql = ` @@ -4206,7 +4214,8 @@ class WaveService extends OrderBaseService { wb.processed_orders, wb.distinguish_express, wb.source, - wb.logistics_name, + wb.logistics_name AS logistics_code, + COALESCE(e.name, wb.logistics_name) AS logistics_name, wb.item_snapshot_key, wb.warehouse_id, wb.creator, @@ -4317,6 +4326,7 @@ class WaveService extends OrderBaseService { item_part: String(batch && batch.item_part || '').trim(), distinguish_express: Number(batch && batch.distinguish_express || 0), source: Number(batch && batch.source || 0), + logistics_code: String(batch && batch.logistics_code || '').trim(), logistics_name: String(batch && batch.logistics_name || '').trim(), item_snapshot_key: String(batch && batch.item_snapshot_key || '').trim(), warehouse_id: Number(batch && batch.warehouse_id || 0), @@ -4358,7 +4368,7 @@ class WaveService extends OrderBaseService { * @param {number|string} [data.page] 页码(兼容 current)。 * @param {number|string} [data.pageSize] 每页数量(兼容 size/page_size)。 * @param {Object} [data.where] 查询过滤。 - * @return {Promise} 列表与分页结果。 + * @return {Promise} 列表与分页结果;每项 list 元素包含 wave_list 数组(wave_id / wave_no / box_no / status / bind_time / pick_time)。 */ async wavePickTaskList(data = {}) { try { @@ -4374,6 +4384,7 @@ class WaveService extends OrderBaseService { t.id, t.task_no, t.warehouse_id, + t.wave_id, t.pick_mode, t.status, t.review_status, @@ -4433,6 +4444,127 @@ class WaveService extends OrderBaseService { const totalRowList = Array.isArray(countRows && countRows[0]) ? countRows[0] : []; const total = Number(totalRowList[0] && totalRowList[0].total || 0); + // 批量查询 wave_list:收集任务ID,从关联表获取波次详情 + const taskIds = sourceList + .map(item => Number(item && item.id || 0)) + .filter(id => Number.isInteger(id) && id > 0); + + const taskWaveMap = new Map(); + if (taskIds.length > 0) { + const taskWaveRows = await this.ctx.model.query(` + SELECT + ptw.task_id, + ptw.wave_id, + ptw.wave_no, + ptw.box_no, + ptw.status, + ptw.bind_time, + ptw.pick_time + FROM wms_wave_pick_task_wave ptw + WHERE ptw.task_id IN (:taskIds) + AND ptw.warehouse_id = :warehouseId + ORDER BY ptw.id ASC + `, { + replacements: { taskIds, warehouseId }, + type: this.ctx.model.QueryTypes.SELECT, + }); + + const normalizedTaskWaveRows = Array.isArray(taskWaveRows) ? taskWaveRows : []; + for (const row of normalizedTaskWaveRows) { + const taskId = Number(row && row.task_id || 0); + if (!Number.isInteger(taskId) || taskId <= 0) { + continue; + } + if (!taskWaveMap.has(taskId)) { + taskWaveMap.set(taskId, []); + } + taskWaveMap.get(taskId).push({ + wave_id: Number(row && row.wave_id || 0), + wave_no: String(row && row.wave_no || '').trim(), + box_no: Number(row && row.box_no || 0), + status: Number(row && row.status || 0), + bind_time: row && row.bind_time || null, + pick_time: row && row.pick_time || null, + }); + } + } + + // 回退:对于 wms_wave_pick_task_wave 无记录的任务, + // 尝试从主表 wave_id / wms_wave_batch 查询波次信息。 + // 兼容场景:散单旧数据未写入关联表、已取消任务关联记录被删除等。 + const missingWaveTaskIds = sourceList + .map(item => { + const taskId = Number(item && item.id || 0); + return Number.isInteger(taskId) && taskId > 0 && !taskWaveMap.has(taskId) + ? { taskId, waveId: Number(item && item.wave_id || 0) } + : null; + }) + .filter(Boolean); + + if (missingWaveTaskIds.length > 0) { + // 优先走 wms_wave_batch 回退(主表 wave_id 有值时) + const batchFallbackIds = missingWaveTaskIds.filter(m => m.waveId > 0); + if (batchFallbackIds.length > 0) { + const fallbackWaveIds = [ ...new Set(batchFallbackIds.map(m => m.waveId)) ]; + const fallbackWaveRows = await this.ctx.model.query(` + SELECT + wave_id, + wave_no + FROM wms_wave_batch + WHERE wave_id IN (:waveIds) + AND warehouse_id = :warehouseId + `, { + replacements: { waveIds: fallbackWaveIds, warehouseId }, + type: this.ctx.model.QueryTypes.SELECT, + }); + + const waveNoMap = new Map(); + const normalizedFallbackRows = Array.isArray(fallbackWaveRows) ? fallbackWaveRows : []; + for (const row of normalizedFallbackRows) { + const waveId = Number(row && row.wave_id || 0); + if (!Number.isInteger(waveId) || waveId <= 0) { + continue; + } + waveNoMap.set(waveId, String(row && row.wave_no || '').trim()); + } + + for (const { taskId, waveId } of batchFallbackIds) { + const waveNo = waveNoMap.get(waveId) || ''; + taskWaveMap.set(taskId, [{ + wave_id: waveId, + wave_no: waveNo, + box_no: 0, + status: 0, + bind_time: null, + pick_time: null, + }]); + } + } + + // 剩余仍未回退到的任务(wave_id 为空或 wms_wave_batch 也无记录), + // 检查其 batch_no(散单模式下冗余了 wave_no) + const remainingFallbackTaskIds = missingWaveTaskIds + .filter(m => !taskWaveMap.has(m.taskId)) + .map(m => m.taskId); + + if (remainingFallbackTaskIds.length > 0) { + for (const taskId of remainingFallbackTaskIds) { + const item = sourceList.find(s => Number(s && s.id || 0) === taskId); + const batchNo = String(item && item.batch_no || '').trim(); + if (batchNo) { + taskWaveMap.set(taskId, [{ + wave_id: 0, + wave_no: batchNo, + box_no: 0, + status: 0, + bind_time: null, + pick_time: null, + }]); + } + } + } + } + const list = sourceList.map(item => ({ task_id: Number(item && item.id || 0), task_no: String(item && item.task_no || '').trim(), @@ -4464,6 +4596,7 @@ class WaveService extends OrderBaseService { create_time: item && item.create_time || null, created_at: item && item.create_time || null, update_time: item && item.update_time || null, + wave_list: taskWaveMap.get(Number(item && item.id || 0)) || [], })); return this.success('ok', { @@ -6888,6 +7021,8 @@ class WaveService extends OrderBaseService { const orderUpdateResult = await orderModel.update({ wave_id: 0, wave_no: '', + wave_strategy_version: 0, + wave_scan_result: 0, }, { where: { id: { [Op.in]: removablePendingIds }, @@ -7778,6 +7913,8 @@ class WaveService extends OrderBaseService { const orderUpdateResult = await orderModel.update({ wave_id: 0, wave_no: '', + wave_strategy_version: 0, + wave_scan_result: 0, }, { where: { wave_id: waveId, @@ -9553,7 +9690,7 @@ class WaveService extends OrderBaseService { } return [{ - wave_id: null, + wave_id: 0, box_no: 1, rule: pickMode === 5 ? 'single_wave_dynamic_append' : 'single_wave_single_box', box_limit: Number.isInteger(boxLimit) && boxLimit > 0 ? boxLimit : 1, @@ -10535,6 +10672,17 @@ class WaveService extends OrderBaseService { await transaction.commit(); + // 写入订单操作日志:策略抓取分配到波次 + const strategyLogItems = normalizedOrderIds.map(orderId => ({ + orderId, + operationCode: 'ORDER_WAVE_STRATEGY_FETCH', + message: `策略(${strategyId})抓取分配到波次 ${normalizedWaveNos.join(',')}`, + })); + await this.batchCreateOrderOperationLogs(strategyLogItems, { + warehouseId, + scene: 'executeWaveStrategyDirectFetch', + }); + this.ctx.logger.info('[wave.executeWaveStrategyDirectFetch] 按策略直接建波完成', { strategy_id: strategyId, warehouse_id: warehouseId, @@ -10792,6 +10940,22 @@ class WaveService extends OrderBaseService { await transaction.commit(); + // 写入订单操作日志:分配到波次 + if (selectedOrderIds.length > 0) { + const waveNoList = taskWaveRows + .map(r => String(r && r.wave_no || '').trim()) + .filter(Boolean); + const waveNoMessage = waveNoList.length > 0 ? waveNoList.join(',') : ''; + await this.batchCreateOrderOperationLogs( + selectedOrderIds.map(orderId => ({ + orderId, + operationCode: 'ORDER_WAVE_ASSIGN', + message: `分配到波次 ${waveNoMessage}`, + })), + { warehouseId, scene: 'createWavePickTaskFromPlan' } + ); + } + return { task_id: taskId, task_no: taskNo, @@ -10808,7 +10972,8 @@ class WaveService extends OrderBaseService { const errorDetail = { name: String(error && error.name || ''), message: String(error && error.message || ''), - stack: String(error && error.stack || '').split('\n').slice(0, 6).join('\n'), + stack: String(error && error.stack || '').split('\n').slice(0, 6) + .join('\n'), sql: String(error && error.sql || '').slice(0, 500), errorType: Object.prototype.toString.call(error), errors: Array.isArray(error && error.errors) @@ -11747,6 +11912,8 @@ class WaveService extends OrderBaseService { }); const hasCancelledAtColumn = Array.isArray(canceledAtColumnRows) && canceledAtColumnRows.length > 0; const cancelledTaskNos = []; + const cancelOrderLogItems = []; + let hasReleasedWaves = false; for (const taskId of normalizedTaskIds) { const requestId = `wave_pick_task_cancel_${warehouseId}_${taskId}_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`; @@ -11856,6 +12023,15 @@ class WaveService extends OrderBaseService { .map(row => Number(row && row.order_id || 0)) .filter(orderId => Number.isInteger(orderId) && orderId > 0)) ]; + // 收集订单操作日志(提交后统一写入) + for (const orderId of taskOrderIds) { + cancelOrderLogItems.push({ + orderId, + operationCode: 'ORDER_WAVE_CANCEL', + message: `取消拣货任务 ${taskNo},从波次释放`, + }); + } + // source=2(后台/扫描创建)不释放波次,仅清理任务-波次关联 const isScanCreated = taskSource === 2; let releasedWaveRows = []; @@ -11880,6 +12056,8 @@ class WaveService extends OrderBaseService { await orderModel.update({ wave_id: 0, wave_no: '', + wave_strategy_version: 0, + wave_scan_result: 0, }, { where: { warehouse_id: warehouseId, @@ -11899,6 +12077,10 @@ class WaveService extends OrderBaseService { }, transaction, }); + + if (Array.isArray(releasedWaveRows) && releasedWaveRows.length > 0) { + hasReleasedWaves = true; + } } // 清理任务-波次关联(所有来源都需要) @@ -11959,6 +12141,7 @@ class WaveService extends OrderBaseService { UPDATE wms_wave_pick_task SET status = 9, + wave_count = 0, current_cart_id = NULL, current_cart_code_snapshot = NULL, ${hasCancelledAtColumn ? 'cancelled_at = NOW(),' : ''} @@ -12013,8 +12196,8 @@ class WaveService extends OrderBaseService { task_id: taskId, warehouse_id: warehouseId, wave_id: Array.isArray(releasedWaveRows) && releasedWaveRows.length > 0 - ? Number(releasedWaveRows[0].wave_id || 0) || null - : null, + ? Number(releasedWaveRows[0].wave_id || 0) + : 0, order_id: taskOrderIds.length > 0 ? Number(taskOrderIds[0]) : null, sku_id: null, location_id: null, @@ -12069,6 +12252,24 @@ class WaveService extends OrderBaseService { await transaction.commit(); + if (cancelOrderLogItems.length > 0) { + await this.batchCreateOrderOperationLogs(cancelOrderLogItems, { + warehouseId, + scene: 'cancelWavePickTasksInternal', + }); + } + + if (hasReleasedWaves) { + setImmediate(() => { + this.submitWaveStrategyQuickScanForWarehouse(warehouseId).catch(err => { + this.ctx.logger.warn('[wave.wavePickTaskCancel] 触发回池后重扫失败', { + warehouseId, + error: err && err.message ? err.message : String(err), + }); + }); + }); + } + return { cancelled_count: normalizedTaskIds.length, task_ids: normalizedTaskIds, diff --git a/app/service/systemMethods/pick.js b/app/service/systemMethods/pick.js index 39b455c..80cdd9b 100644 --- a/app/service/systemMethods/pick.js +++ b/app/service/systemMethods/pick.js @@ -304,6 +304,37 @@ class PickService extends MainService { } await transaction.commit(); + + // 写入 order_operation_log 抓取波次日志 + try { + const operationLogService = this.ctx + && this.ctx.service + && this.ctx.service.systems + && this.ctx.service.systems.operationLog; + if (operationLogService && typeof operationLogService.createOperationLogs === 'function') { + const logPayloads = normalizedOrderIds.map(orderId => ({ + businessType: 'order', + businessId: `${orderId}`, + operationCode: 'ORDER_WAVE_GRAB', + operator: { + id: operatorId ? String(operatorId) : null, + name: operatorName || 'system', + }, + extras: { + message: `订单${orderId}抓取波次成功`, + warehouseId, + externalLogType: 'PDA', + }, + })); + await operationLogService.createOperationLogs(logPayloads); + } + } catch (e) { + ctx.logger.warn('[pick.createWavePickTask] 写入 order_operation_log 失败,不影响主流程', { + error: e && e.message, + normalizedOrderIds, + }); + } + return { task_id: taskId, task_no: taskNo, @@ -337,7 +368,7 @@ class PickService extends MainService { * @return {Promise} 统一 success/fail 包装结果。 */ async query(data = {}) { - const { service, ctx } = this; + const { ctx } = this; const requestData = this.isPlainObject(data) ? data : {}; const { keyword } = requestData; @@ -545,6 +576,45 @@ class PickService extends MainService { ); } + // 波次级已完成任务去重:同一 warehouse_id + 同一 wave_id 已有完成任务时不再创建 + const completedTaskRows = await ctx.model.query( + ` + SELECT t.id AS task_id, t.status, t.pick_user_id, t.pick_user_name + FROM wms_wave_pick_task t + WHERE t.warehouse_id = :warehouseId + AND t.status IN (2, 3) + AND ( + t.wave_id = :waveId + OR EXISTS ( + SELECT 1 + FROM wms_wave_pick_task_wave tw + WHERE tw.task_id = t.id + AND tw.wave_id = :waveId + ) + ) + ORDER BY t.id DESC + LIMIT 1 + `, + { + replacements: { + waveId: targetWaveId, + warehouseId: normalizedWarehouseId, + }, + type: ctx.model.QueryTypes.SELECT, + } + ); + const completedTask = Array.isArray(completedTaskRows) && completedTaskRows.length > 0 ? completedTaskRows[0] : null; + if (completedTask) { + return this.success('ok', { + data: { + task_id: Number(completedTask.task_id), + status: 'existing_completed', + tip: '该波次已完成拣货任务,无需重复创建', + }, + code: 200, + }); + } + // keyword 级别去重:同一 warehouse_id + 同一 keyword(remark)在 30 分钟内已有任务则不再创建 const keywordRemark = `pick.query keyword=${normalizedKeyword}`; const keywordDedupRows = await ctx.model.query( diff --git a/app/service/systemMethods/print.js b/app/service/systemMethods/print.js index 5d9a100..efa64a2 100644 --- a/app/service/systemMethods/print.js +++ b/app/service/systemMethods/print.js @@ -1091,8 +1091,14 @@ class PrintService extends MainService { for (let i = 0; i < item.rows; i++) { tableHtml += ''; for (let j = 0; j < item.columns; j++) { - const content = item.content[i] && item.content[i][j] ? item.content[i][j] : ''; - tableHtml += `${content}`; + let cellContent = item.content[i] && item.content[i][j] ? item.content[i][j] : ''; + // 解析单元格字段码为实际数据,与 text 类型保持一致的解析逻辑 + for (const key in data) { + if (String(cellContent) === key) { + cellContent = data[key]; + } + } + tableHtml += `${cellContent}`; } tableHtml += ''; } tableHtml += ''; htm += tableHtml; diff --git a/app/service/systemMethods/stock/warehouse.js b/app/service/systemMethods/stock/warehouse.js index 32d7f03..8814969 100644 --- a/app/service/systemMethods/stock/warehouse.js +++ b/app/service/systemMethods/stock/warehouse.js @@ -611,7 +611,7 @@ class WarehouseService extends MainService { */ _normalizeBarcodeField(raw) { if (typeof raw === 'string' && raw.trim()) { - return [...new Set(raw.split(',').map(s => s.trim()).filter(Boolean))]; + return [ ...new Set(raw.split(',').map(s => s.trim()).filter(Boolean)) ]; } return []; } @@ -1015,12 +1015,27 @@ class WarehouseService extends MainService { } /** - * 快捷搜索仓库商品。 - * @param {Object} data 请求体(含 keyword) - * @return {Promise} data 为搜索结果数组 - */ + * 快捷搜索仓库商品,当 mode='combo' 时桥接到组合商品查询。 + * @param {Object} data 请求体 + * @param {string} [data.mode] 查询模式,'combo' 时搜索组合商品,默认搜索普通商品 + * @param {string} [data.keyword] 搜索关键字(默认模式) + * @param {number} [data.id] 组合商品ID(mode='combo' 时精确查询) + * @param {string} [data.custom_code] 自定义编码(mode='combo' 时模糊查询) + * @param {number} [data.store_id] 货主ID(默认模式) + * @param {boolean} [data.with_stock] 是否返回库存数据(默认模式) + * @param {boolean} [data.is_batch] 是否按批次返回(默认模式) + * @return {Promise} data 为搜索结果数组(默认模式)或组合商品列表(combo 模式) + */ async search(data) { const { service } = this; + const { mode } = data || {}; + + if (mode === 'combo') { + const { id, custom_code } = data || {}; + const result = await service.systems.comboGoods.searchByIdOrCode({ id, custom_code }); + return this.success('ok', result); + } + const result = await service.systems.stockStore.search(data); return this.success('ok', result); } diff --git a/app/service/systemMethods/storage/direct_inbound.js b/app/service/systemMethods/storage/direct_inbound.js new file mode 100644 index 0000000..37d0c3d --- /dev/null +++ b/app/service/systemMethods/storage/direct_inbound.js @@ -0,0 +1,71 @@ +'use strict'; +const MainService = require('../../main'); +/** + * 系统方法层:storage.directInbound(导入/PDA直接入库相关接口包装层)。 + * 主要职责:统一包装系统方法接口,处理权限、日志等公共逻辑,调用底层 service 实现业务功能。 + */ +class DirectInboundService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'getItems,addItem,removeItem,commit'; + const _noNeedLog = 'getItems'; + const _noNeedAuth = 'getItems,addItem,removeItem,commit'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 获取入库单的导入/PDA 入库信息。 + * @param {Object} data 请求体 + * @param {string} data.entry_order_code 入库单号 + * @return {Promise} 统一成功包装响应 + */ + async getItems(data = {}) { + const { service } = this; + const { entry_order_code } = data || {}; + const result = await service.systems.inboundDirectLog.getItems(entry_order_code); + return this.success('ok', result); + } + + /** + * 按商品增量添加导入/PDA 入库记录。 + * @param {Object} data 请求体 + * @param {string} data.entry_order_code 入库单号 + * @param {number} data.stock_id 商品SKU ID + * @param {number} data.quantity 入库数量 + * @param {string} data.inbound_type 入库方式:import 或 pda + * @param {string} [data.remark] 备注 + * @return {Promise} 统一成功包装响应 + */ + async addItem(data = {}) { + const { service } = this; + const result = await service.systems.inboundDirectLog.addItem(data); + return this.success('ok', result); + } + + /** + * 提交确认完成导入/PDA 入库,写入库存并触发奇门/API 回传。 + * @param {Object} data 请求体 + * @param {string} data.entry_order_code 入库单号 + * @return {Promise} 统一成功包装响应 + */ + async commit(data = {}) { + const { service } = this; + const { entry_order_code } = data || {}; + const result = await service.systems.inboundDirectLog.commit(entry_order_code); + return this.success('ok', result); + } + + /** + * 移除一条导入/PDA 入库记录。 + * @param {Object} data 请求体 + * @param {number} data.id 入库记录ID + * @return {Promise} 统一成功包装响应 + */ + async removeItem(data = {}) { + const { service } = this; + const result = await service.systems.inboundDirectLog.removeItem(data); + return this.success('ok', result); + } +} +module.exports = DirectInboundService; diff --git a/app/service/systemMethods/storage/entry.js b/app/service/systemMethods/storage/entry.js index 3b808cd..bfcfb2a 100644 --- a/app/service/systemMethods/storage/entry.js +++ b/app/service/systemMethods/storage/entry.js @@ -9,9 +9,9 @@ class entryService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'list,get,cancel,completeEntry'; - const _noNeedLog = 'list,get'; - const _noNeedAuth = 'list,get,cancel,completeEntry'; + const _noNeedRight = 'list,get,cancel,completeEntry,getPrintData,getDirectInboundItems,addDirectInboundItem,commitDirectInbound,removeDirectInboundItem'; + const _noNeedLog = 'list,get,getPrintData'; + const _noNeedAuth = 'list,get,cancel,completeEntry,getPrintData,getDirectInboundItems,addDirectInboundItem,commitDirectInbound,removeDirectInboundItem'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -65,14 +65,148 @@ class entryService extends MainService { } /** - * 完成入库单。 + * 完成入库单(纯状态变更,不写库存)。 + * 仅校验状态=PENDING、有明细,然后将 order_status 更新为 COMPLETED。 * @param {Object} data 请求体 + * @param {number} data.id 入库单ID * @return {Promise} 统一 success 包装 */ async completeEntry(data = {}) { const { service } = this; - const result = await service.systems.storage.entry.completeEntry(data); + const { id } = data; + const result = await service.systems.storage.entry.completeEntry({ id }); return this.success('ok', result); } + + /** + * 获取入库单的导入/PDA 直接入库信息(从 storage.entry 模块暴露)。 + * @param {Object} data 请求体 + * @param {string} data.entry_order_code 入库单号 + * @return {Promise} 统一 success 包装 + */ + async getDirectInboundItems(data = {}) { + const { service } = this; + const { entry_order_code } = data || {}; + const result = await service.systems.inboundDirectLog.getItems(entry_order_code); + return this.success('ok', result); + } + + /** + * 按商品增量添加导入/PDA 直接入库记录(从 storage.entry 模块暴露)。 + * @param {Object} data 请求体 + * @param {string} data.entry_order_code 入库单号 + * @param {number} [data.stock_id] 商品SKU ID(单条模式) + * @param {number} [data.quantity] 本次入库数量(单条模式) + * @param {string} [data.inbound_type] 入库方式(单条模式) + * @param {Array} [data.items] 商品列表(批量模式) + * @return {Promise} 统一 success 包装 + */ + async addDirectInboundItem(data = {}) { + const { service } = this; + const result = await service.systems.inboundDirectLog.addItem(data); + return this.success('ok', result); + } + + /** + * 提交确认完成导入/PDA 直接入库(从 storage.entry 模块暴露)。 + * @param {Object} data 请求体 + * @param {string} data.entry_order_code 入库单号 + * @return {Promise} 统一 success 包装 + */ + async commitDirectInbound(data = {}) { + const { service } = this; + const { entry_order_code } = data || {}; + const result = await service.systems.inboundDirectLog.commit(entry_order_code); + return this.success('ok', result); + } + + /** + * 移除一条导入/PDA 直接入库记录(从 storage.entry 模块暴露)。 + * @param {Object} data 请求体 + * @param {number} data.id 入库记录ID + * @return {Promise} 统一 success 包装 + */ + async removeDirectInboundItem(data = {}) { + const { service } = this; + const result = await service.systems.inboundDirectLog.removeItem(data); + return this.success('ok', result); + } + + /** + * 获取入库单打印数据,按 RECEIPT 模板 field_code 映射返回。 + * @param {Object} data 请求体 + * @param {number} data.id 入库单ID + * @param {number} [data.warehouse_id] 仓库ID,不传则取当前用户仓库 + * @return {Promise} 打印数据(扁平键值 + items 明细数组) + */ + async getPrintData(data = {}) { + const { ctx, service } = this; + const id = Number(data && data.id || 0); + if (!id) { + return this.fail('id 参数不能为空', { code: 400 }); + } + + try { + const entryResult = await service.systems.storage.entry.get({ id }); + if (!entryResult || entryResult.code !== 200 || !entryResult.data || !entryResult.data.entryOrder) { + return this.fail('入库单不存在', { code: 404 }); + } + + const entryOrder = entryResult.data.entryOrder; + const items = Array.isArray(entryOrder.items) ? entryOrder.items : []; + + // 查询商品条码(批量) + const barcodeMap = new Map(); + try { + const stockIds = items + .map(item => Number(item.stock_id || 0)) + .filter(sid => sid > 0); + if (stockIds.length > 0 && ctx.model.StockBarcode) { + const barcodeRows = await ctx.model.StockBarcode.findAll({ + where: { stock_id: { [ctx.app.Sequelize.Op.in]: stockIds } }, + attributes: [ 'stock_id', 'barcode' ], + raw: true, + }); + for (const row of barcodeRows) { + if (!barcodeMap.has(row.stock_id)) { + barcodeMap.set(row.stock_id, []); + } + barcodeMap.get(row.stock_id).push(row.barcode); + } + } + } catch (err) { + ctx.logger.warn('[entry.getPrintData] 查询条码失败: %s', err.message); + } + + const printData = { + entry_order_code: entryOrder.entry_order_code || '', + order_type: entryOrder.order_type || '', + order_status: entryOrder.order_status || '', + purchase_order_code: entryOrder.purchase_order_code || '', + supplier_name: entryOrder.supplier_name || '', + warehouse_name: entryOrder.warehouse_name || '', + store_name: entryOrder.store_name || '', + logistics_name: entryOrder.logistics_name || '', + express_code: entryOrder.express_code || '', + order_create_time: entryOrder.order_create_time || '', + expect_start_time: entryOrder.expect_start_time || '', + remark: entryOrder.remark || '', + total_order_lines: entryOrder.total_order_lines || 0, + items: items.map(item => ({ + items_col1: item.warehouse_item_code || item.external_item_code || '', + items_col2: item.warehouse_item_name || '', + items_col3: (barcodeMap.get(Number(item.stock_id)) || []).join(';') || '', + items_col4: item.count || 0, + items_col5: item.received_quantity || 0, + items_col6: item.inventory_type || '', + })), + }; + + return this.success('ok', { data: printData, code: 200 }); + } catch (error) { + ctx.logger.error('[entry.getPrintData] 获取入库单打印数据失败:', error); + return this.fail(error.message || '获取打印数据失败', { code: 500 }); + } + } } module.exports = entryService; diff --git a/app/service/systemMethods/storage/inventory.js b/app/service/systemMethods/storage/inventory.js index 1d7acad..33f63cf 100644 --- a/app/service/systemMethods/storage/inventory.js +++ b/app/service/systemMethods/storage/inventory.js @@ -10,37 +10,12 @@ class InventoryMethodService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'matchPutaway,list'; + const _noNeedRight = 'list'; const _noNeedLog = 'list'; const _noNeedAuth = 'list'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } - /** - * 收货单快捷入库上架。 - * @param {Object} data 请求体 - * @param {number} data.receiving_id 收货单ID - * @return {Promise} 统一 success 包装 - */ - async quickPutaway(data = {}) { - const { service } = this; - const result = await service.systems.storage.inventory.quickPutaway(data); - return this.success('ok', result); - } - - /** - * 匹配入库:收货单与入库单按商品匹配入库。 - * @param {Object} data 请求体 - * @param {number[]} data.receiving_ids 收货单ID列表 - * @param {number[]} data.entry_order_ids 入库单ID列表 - * @return {Promise} 统一 success 包装 - */ - async matchPutaway(data = {}) { - const { service } = this; - const result = await service.systems.storage.inventory.matchPutaway(data); - return this.success('ok', result); - } - /** * 移库(库位转移):将单条库存从一个库位移动到另一个库位。 * @param {Object} data 请求体 diff --git a/app/service/systemMethods/storage/management.js b/app/service/systemMethods/storage/management.js new file mode 100644 index 0000000..53e0d15 --- /dev/null +++ b/app/service/systemMethods/storage/management.js @@ -0,0 +1,45 @@ +'use strict'; + +const MainService = require('../../main'); + +/** + * 系统方法层:storage.management(库存管理接口包装层)。 + */ +class StorageManagementMethodService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'replenishmentDemand'; + const _noNeedLog = ''; + const _noNeedAuth = 'replenishmentDemand'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 分拣缺货补货需求计算。 + * + * 仓库级别的计算,针对当前仓库所有未完成储位分配的订单, + * 计算每个 SKU 在分拣区与存货区的可用库存对比, + * 输出分拣区缺口及建议补货量,供仓库人员决策移库。 + * + * 仓库 ID 从用户上下文(ctx.user.store_id / ctx.user.warehouse_id)自动获取,无需显式传入。 + * + * @param {Object} [data={}] 请求参数。 + * @param {Object} [data.pagination] 分页参数。 + * @param {Object} [data.sort] 排序参数。 + * @return {Promise} 统一 success 包装的补货需求明细、汇总与分页信息。 + */ + async replenishmentDemand(data = {}) { + const { service } = this; + const requestData = this.isPlainObject(data) ? data : {}; + const pagination = requestData.pagination || {}; + const sort = requestData.sort || requestData.order || {}; + const result = await service.systems.storage.management.replenishmentDemand({ + pagination, + sort, + }); + return this.success('补货需求计算完成', result); + } +} + +module.exports = StorageManagementMethodService; diff --git a/app/service/systemMethods/storage/receiving.js b/app/service/systemMethods/storage/receiving.js index a153f94..6f72776 100644 --- a/app/service/systemMethods/storage/receiving.js +++ b/app/service/systemMethods/storage/receiving.js @@ -10,9 +10,9 @@ class configService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs'; - const _noNeedLog = 'getReceivingList,get,addDetail,deleteDetail,detailChange,bindStore,bindDetailProduct,queryReceivingLogs'; - const _noNeedAuth = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs'; + const _noNeedRight = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs,manualMatchEntryOrder'; + const _noNeedLog = 'getReceivingList,get,addDetail,deleteDetail,detailChange,bindStore,bindDetailProduct,queryReceivingLogs,manualMatchEntryOrder'; + const _noNeedAuth = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs,manualMatchEntryOrder'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -259,5 +259,24 @@ class configService extends MainService { code: 200, }); } + + /** + * 手动匹配入库单与收货单(system method 包装层)。 + * + * 传入收货单 ID 与入库单 ID,复用 `receiving_entry_match` 服务的匹配逻辑, + * 同步执行 SKU 明细对比并按来源回传(奇门 / OpenAPI),返回结构化匹配结果。 + * + * @param {Object} data 请求体 + * @param {number} data.receivingId 收货单 ID + * @param {number} data.entryOrderId 入库单 ID + * @return {Promise} 统一成功包装的匹配结果 + */ + async manualMatchEntryOrder(data) { + const { service } = this; + const { receivingId, entryOrderId } = data || {}; + const result = await service.systems.receiving_entry_match.manualMatch(receivingId, entryOrderId); + return this.success('匹配完成', result); + } + } module.exports = configService; diff --git a/app/service/systems/comboGoods.js b/app/service/systems/comboGoods.js new file mode 100644 index 0000000..497a55d --- /dev/null +++ b/app/service/systems/comboGoods.js @@ -0,0 +1,1011 @@ +'use strict'; + +const Service = require('egg').Service; + +/** + * 将输入值转换为有限数字。 + * + * @param {unknown} value 待转换的值。 + * @param {number} [defaultValue=0] 默认值。 + * @return {number} 转换后的数字。 + */ +function toNumber(value, defaultValue = 0) { + const normalized = Number(value); + return Number.isFinite(normalized) ? normalized : defaultValue; +} + +/** + * 组合商品业务逻辑服务层。 + * 负责组合商品的 CRUD、搜索、校验等核心业务逻辑。 + */ +class ComboGoodsService extends Service { + // ---------- 公共辅助方法 ---------- + + /** + * 通过 stock_id 批量查询 wms_stock_warehouse,返回 Map 结构。 + * + * @param {number[]} stockIds stock_id 数组。 + * @return {Promise>} stockId → { id, item_name, store_id, item_code } 的映射。 + */ + async fetchStockInfoMap(stockIds) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const uniqueIds = [ ...new Set(stockIds.filter(id => toNumber(id) > 0)) ]; + + if (uniqueIds.length === 0) { + return new Map(); + } + + const rows = await ctx.model.StockWarehouse.findAll({ + where: { + id: { [Op.in]: uniqueIds }, + }, + attributes: [ 'id', 'item_name', 'store_id', 'item_code' ], + raw: true, + }); + + const map = new Map(); + for (const row of Array.isArray(rows) ? rows : []) { + const stockId = toNumber(row.id); + if (stockId > 0) { + map.set(stockId, { + id: stockId, + item_name: String(row.item_name || ''), + store_id: toNumber(row.store_id), + item_code: String(row.item_code || ''), + }); + } + } + return map; + } + + /** + * 构建字符串简记(格式:stock_id|数量,stock_id2|数量)。 + * + * @param {Object[]} items 明细数组,每项包含 item_goods_sku_id 与 item_quantity。 + * @return {string} 字符串简记。 + */ + buildSimpleNotation(items) { + if (!Array.isArray(items) || items.length === 0) { + return ''; + } + return items + .map(item => `${toNumber(item.item_goods_sku_id)}|${toNumber(item.item_quantity)}`) + .join(','); + } + + /** + * 构建商品名称简记(格式:【数量】商品名称+【数量】商品名称)。 + * + * @param {Object[]} items 明细数组,每项包含 item_goods_sku_id 与 item_quantity。 + * @param {Map} stockInfoMap stockId → { item_name } 的映射。 + * @return {string} 商品名称简记。 + */ + buildNameNotation(items, stockInfoMap) { + if (!Array.isArray(items) || items.length === 0) { + return ''; + } + return items + .map(item => { + const stockId = toNumber(item.item_goods_sku_id); + const qty = toNumber(item.item_quantity); + const stockInfo = stockInfoMap.get(stockId); + const name = stockInfo ? stockInfo.item_name : `SKU#${stockId}`; + return `【${qty}】${name}`; + }) + .join('+'); + } + + /** + * 校验子商品的有效性(必须存在于 wms_stock_warehouse、状态正常、未删除)。 + * + * @param {number[]} stockIds 待校验的 stock_id 数组。 + * @return {Promise} 校验结果,{ ok: boolean, message?: string, stockInfoMap?: Map }。 + */ + async validateItems(stockIds) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const uniqueIds = [ ...new Set(stockIds.filter(id => toNumber(id) > 0)) ]; + + if (uniqueIds.length === 0) { + return { ok: false, message: '子商品列表不能为空' }; + } + + const rows = await ctx.model.StockWarehouse.findAll({ + where: { + id: { [Op.in]: uniqueIds }, + is_valid: 'Y', + deleted_at: null, + }, + attributes: [ 'id', 'item_name', 'store_id', 'item_code' ], + raw: true, + }); + + const validMap = new Map(); + for (const row of Array.isArray(rows) ? rows : []) { + validMap.set(toNumber(row.id), { + id: toNumber(row.id), + item_name: String(row.item_name || ''), + store_id: toNumber(row.store_id), + item_code: String(row.item_code || ''), + }); + } + + // 找出哪些 stock_id 不在有效列表中 + const invalidIds = uniqueIds.filter(id => !validMap.has(id)); + if (invalidIds.length > 0) { + return { ok: false, message: `以下子商品不存在或已停用:${invalidIds.join(', ')}` }; + } + + // 校验是否所有子商品属于同一个货主(owner_id / store_id) + const ownerIds = new Set(); + for (const [ , info ] of validMap) { + ownerIds.add(info.store_id); + } + if (ownerIds.size > 1) { + return { ok: false, message: '所有子商品必须属于同一个货主,不允许跨货主组合' }; + } + + return { ok: true, stockInfoMap: validMap }; + } + + /** + * 从 stockInfoMap 中提取 targetStoreId。 + * + * @param {Map} stockInfoMap stockId → { store_id } 的映射。 + * @return {number} 目标货主ID,如果无法确定则返回 0。 + */ + getTargetStoreIdFromMap(stockInfoMap) { + if (!stockInfoMap || stockInfoMap.size === 0) { + return 0; + } + const storeIds = new Set(); + for (const [ , info ] of stockInfoMap) { + storeIds.add(info.store_id); + } + if (storeIds.size !== 1) { + return 0; + } + return storeIds.values().next().value; + } + + /** + * 自定义编码货主唯一性校验(创建时)。 + * 通过 items 反查 store_id,再查询是否存在相同 custom_code + 同货主的非删除记录。 + * + * @param {string} customCode 自定义编码。 + * @param {Map} stockInfoMap 当前 items 的 stockId → { store_id } 映射。 + * @throws {Error} 如果自定义编码在同一货主内已存在。 + */ + async checkCustomCodeUniqueForCreate(customCode, stockInfoMap) { + const { ctx } = this; + const targetStoreId = this.getTargetStoreIdFromMap(stockInfoMap); + if (targetStoreId <= 0) { + return; // 无法确定货主,跳过校验 + } + + // 查出所有 status != 0 且 custom_code 相同的 combo_id + const sameCodeRows = await ctx.model.query( + `SELECT id FROM wms_combo_goods + WHERE custom_code = :customCode AND status != 0`, + { + replacements: { customCode }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + if (!Array.isArray(sameCodeRows) || sameCodeRows.length === 0) { + return; // 无重复 + } + + const conflictComboIds = sameCodeRows.map(r => toNumber(r.id)).filter(id => id > 0); + if (conflictComboIds.length === 0) { + return; + } + + // 查这些 combo_id 的子商品对应的 stock_id + const conflictItemRows = await ctx.model.query( + `SELECT DISTINCT cgi.item_goods_sku_id + FROM wms_combo_goods_item cgi + WHERE cgi.combo_id IN (:comboIds)`, + { + replacements: { comboIds: conflictComboIds }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + if (!Array.isArray(conflictItemRows) || conflictItemRows.length === 0) { + return; + } + + const conflictStockIds = conflictItemRows + .map(r => toNumber(r.item_goods_sku_id)) + .filter(id => id > 0); + + if (conflictStockIds.length === 0) { + return; + } + + // 查出这些 stock_id 对应的 store_id + const { Op } = ctx.app.Sequelize; + const conflictStocks = await ctx.model.StockWarehouse.findAll({ + where: { id: { [Op.in]: conflictStockIds } }, + attributes: [ 'store_id' ], + raw: true, + }); + + const conflictStoreIds = new Set(); + for (const row of (Array.isArray(conflictStocks) ? conflictStocks : [])) { + conflictStoreIds.add(toNumber(row.store_id)); + } + + if (conflictStoreIds.has(targetStoreId)) { + throw new Error('自定义编码已存在'); + } + } + + /** + * 自定义编码货主唯一性校验(更新时,排除自身 id)。 + * 通过已有子商品反查 store_id,再查询是否存在相同 custom_code + 同货主的非删除记录(排除自身)。 + * + * @param {string} customCode 自定义编码。 + * @param {number} comboId 当前组合商品ID(排除自身)。 + * @param {Object|null} itemValidation 如已做过 validateItems,传入结果复用 stockInfoMap。 + * @throws {Error} 如果自定义编码在同一货主内已存在。 + */ + async checkCustomCodeUniqueForUpdate(customCode, comboId, itemValidation) { + const { ctx } = this; + let targetStoreId = 0; + + // 优先使用传入的 itemValidation 中的 stockInfoMap + if (itemValidation && itemValidation.ok && itemValidation.stockInfoMap) { + targetStoreId = this.getTargetStoreIdFromMap(itemValidation.stockInfoMap); + } + + // 如果无法从传入 items 确定货主,则从已有子商品反查 + if (targetStoreId <= 0) { + const existingItems = await ctx.model.query( + `SELECT cgi.item_goods_sku_id + FROM wms_combo_goods_item cgi + WHERE cgi.combo_id = :comboId`, + { + replacements: { comboId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + if (Array.isArray(existingItems) && existingItems.length > 0) { + const stockIds = existingItems + .map(r => toNumber(r.item_goods_sku_id)) + .filter(id => id > 0); + if (stockIds.length > 0) { + const stockInfoMap = await this.fetchStockInfoMap(stockIds); + targetStoreId = this.getTargetStoreIdFromMap(stockInfoMap); + } + } + } + + if (targetStoreId <= 0) { + return; // 无法确定货主,跳过校验 + } + + // 查出所有 status != 0 且 custom_code 相同且 id != comboId 的记录 + const sameCodeRows = await ctx.model.query( + `SELECT id FROM wms_combo_goods + WHERE custom_code = :customCode AND status != 0 AND id != :comboId`, + { + replacements: { customCode, comboId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + if (!Array.isArray(sameCodeRows) || sameCodeRows.length === 0) { + return; // 无重复 + } + + const conflictComboIds = sameCodeRows.map(r => toNumber(r.id)).filter(id => id > 0); + if (conflictComboIds.length === 0) { + return; + } + + // 查这些冲突 combo_id 的子商品对应的 store_id + const conflictItemRows = await ctx.model.query( + `SELECT DISTINCT cgi.item_goods_sku_id + FROM wms_combo_goods_item cgi + WHERE cgi.combo_id IN (:comboIds)`, + { + replacements: { comboIds: conflictComboIds }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + if (!Array.isArray(conflictItemRows) || conflictItemRows.length === 0) { + return; + } + + const conflictStockIds = conflictItemRows + .map(r => toNumber(r.item_goods_sku_id)) + .filter(id => id > 0); + + if (conflictStockIds.length === 0) { + return; + } + + const { Op } = ctx.app.Sequelize; + const conflictStocks = await ctx.model.StockWarehouse.findAll({ + where: { id: { [Op.in]: conflictStockIds } }, + attributes: [ 'store_id' ], + raw: true, + }); + + const conflictStoreIds = new Set(); + for (const row of (Array.isArray(conflictStocks) ? conflictStocks : [])) { + conflictStoreIds.add(toNumber(row.store_id)); + } + + if (conflictStoreIds.has(targetStoreId)) { + throw new Error('自定义编码已存在'); + } + } + + // ---------- 1. 列表查询 ---------- + + /** + * 组合商品列表查询(分页)。 + * + * @param {Object} options 查询选项。 + * @param {number} [options.page=1] 页码。 + * @param {number} [options.pageSize=20] 每页大小。 + * @param {string} [options.combo_code] 组合商品编码筛选。 + * @param {string} [options.combo_name] 组合商品名称筛选(模糊)。 + * @param {number} [options.status] 状态筛选。 + * @param {number} [options.warehouse_id] 仓库ID筛选。 + * @return {Promise} 分页列表结果。 + */ + async list(options = {}) { + const { ctx } = this; + const page = Math.max(1, toNumber(options.page, 1)); + const pageSize = Math.min(200, Math.max(1, toNumber(options.pageSize, 20))); + + // 构建 where 子句与 replacements + const { whereClause, replacements } = this.buildListWhere(options); + + // 查询总数 + const countSql = `SELECT COUNT(*) AS cnt FROM wms_combo_goods WHERE ${whereClause}`; + const countRows = await ctx.model.query(countSql, { + replacements, + type: ctx.model.QueryTypes.SELECT, + }); + const total = toNumber(countRows && countRows[0] && countRows[0].cnt, 0); + + // 查询主表分页数据 + const offset = (page - 1) * pageSize; + const listSql = `SELECT * FROM wms_combo_goods WHERE ${whereClause} + ORDER BY id DESC LIMIT ${offset}, ${pageSize}`; + const mainRows = await ctx.model.query(listSql, { + replacements, + type: ctx.model.QueryTypes.SELECT, + }); + + const list = Array.isArray(mainRows) ? mainRows : []; + + if (list.length === 0) { + return { list: [], total, page, pageSize }; + } + + // 批量查询明细 + const comboIds = list.map(row => toNumber(row.id)).filter(id => id > 0); + const itemRows = comboIds.length > 0 + ? await ctx.model.query( + 'SELECT * FROM wms_combo_goods_item WHERE combo_id IN (:comboIds) ORDER BY sort_order ASC, id ASC', + { + replacements: { comboIds }, + type: ctx.model.QueryTypes.SELECT, + } + ) + : []; + + // 按 combo_id 分组明细 + const itemsByComboId = new Map(); + for (const item of Array.isArray(itemRows) ? itemRows : []) { + const comboId = toNumber(item.combo_id); + if (!itemsByComboId.has(comboId)) { + itemsByComboId.set(comboId, []); + } + itemsByComboId.get(comboId).push({ + id: toNumber(item.id), + combo_id: comboId, + item_goods_sku_id: toNumber(item.item_goods_sku_id), + item_quantity: toNumber(item.item_quantity), + sort_order: toNumber(item.sort_order), + }); + } + + // 收集所有 stock_id 以批量获取商品名称 + const allStockIds = []; + for (const [ , items ] of itemsByComboId) { + for (const item of items) { + allStockIds.push(item.item_goods_sku_id); + } + } + const stockInfoMap = await this.fetchStockInfoMap(allStockIds); + + // 组装最终列表 + const resultList = list.map(row => { + const comboId = toNumber(row.id); + const items = itemsByComboId.get(comboId) || []; + return { + id: comboId, + combo_code: String(row.combo_code || ''), + combo_name: String(row.combo_name || ''), + combo_sku_id: toNumber(row.combo_sku_id), + custom_code: row.custom_code || null, + status: toNumber(row.status), + warehouse_id: toNumber(row.warehouse_id), + remark: String(row.remark || ''), + creator_id: toNumber(row.creator_id), + editor_id: toNumber(row.editor_id), + created_at: row.created_at, + updated_at: row.updated_at, + items, + simpleNotation: this.buildSimpleNotation(items), + nameNotation: this.buildNameNotation(items, stockInfoMap), + }; + }); + + return { list: resultList, total, page, pageSize }; + } + + /** + * 为列表查询构建参数化的 WHERE 子句。 + * + * @param {Object} options 查询选项。 + * @return {Object} 包含 whereClause(string)与 replacements(Object)的对象。 + */ + buildListWhere(options) { + const clauses = []; + const replacements = {}; + + if (options.combo_code) { + clauses.push('combo_code = :comboCode'); + replacements.comboCode = String(options.combo_code).trim(); + } + if (options.combo_name) { + clauses.push('combo_name LIKE :comboName'); + replacements.comboName = `%${String(options.combo_name).trim()}%`; + } + if (options.status !== undefined && options.status !== null && options.status !== '') { + clauses.push('status = :status'); + replacements.status = toNumber(options.status); + } + if (options.warehouse_id !== undefined && options.warehouse_id !== null && options.warehouse_id !== '') { + clauses.push('warehouse_id = :warehouseId'); + replacements.warehouseId = toNumber(options.warehouse_id); + } + + return { + whereClause: clauses.length > 0 ? clauses.join(' AND ') : '1=1', + replacements, + }; + } + + // ---------- 2. 创建组合商品 ---------- + + /** + * 创建组合商品(含明细),使用事务保证原子性。 + * + * @param {Object} options 创建参数。 + * @param {string} options.combo_code 组合商品编码。 + * @param {string} options.combo_name 组合商品名称。 + * @param {number} [options.warehouse_id] 仓库ID。 + * @param {string} [options.remark] 备注。 + * @param {string} [options.custom_code] 自定义编码。 + * @param {Object[]} options.items 子商品明细数组 [{item_goods_sku_id, item_quantity}]。 + * @param {number} [options.creator_id] 创建人ID。 + * @return {Promise} 创建结果,包含 id、combo_code、combo_name、custom_code。 + */ + async create(options = {}) { + const { ctx } = this; + const { combo_code, combo_name, items } = options; + const warehouseId = toNumber(options.warehouse_id); + const remark = String(options.remark || ''); + const customCode = options.custom_code ? String(options.custom_code).trim() : ''; + const creatorId = toNumber(options.creator_id || ctx.user?.id || 0); + + // 参数基础校验 + if (!combo_code || !String(combo_code).trim()) { + throw new Error('组合商品编码不能为空'); + } + if (!combo_name || !String(combo_name).trim()) { + throw new Error('组合商品名称不能为空'); + } + if (!Array.isArray(items) || items.length === 0) { + throw new Error('子商品列表不能为空'); + } + + const trimmedCode = String(combo_code).trim(); + const trimmedName = String(combo_name).trim(); + + // 唯一性校验 + const existing = await ctx.model.query( + 'SELECT id FROM wms_combo_goods WHERE combo_code = :comboCode LIMIT 1', + { + replacements: { comboCode: trimmedCode }, + type: ctx.model.QueryTypes.SELECT, + } + ); + if (Array.isArray(existing) && existing.length > 0) { + throw new Error(`组合商品编码 "${trimmedCode}" 已存在`); + } + + // 子商品有效性校验 + const stockIds = items.map(item => toNumber(item.item_goods_sku_id)).filter(id => id > 0); + const validation = await this.validateItems(stockIds); + if (!validation.ok) { + throw new Error(validation.message); + } + + // 自定义编码货主唯一性校验 + if (customCode) { + await this.checkCustomCodeUniqueForCreate(customCode, validation.stockInfoMap); + } + + // 事务写入 + const transaction = await ctx.model.transaction(); + + try { + // 插入主表 + const insertResult = await ctx.model.query( + `INSERT INTO wms_combo_goods (combo_code, combo_name, warehouse_id, remark, custom_code, status, creator_id, editor_id) + VALUES (:comboCode, :comboName, :warehouseId, :remark, :customCode, 1, :creatorId, :creatorId)`, + { + replacements: { + comboCode: trimmedCode, + comboName: trimmedName, + warehouseId: warehouseId > 0 ? warehouseId : null, + remark, + customCode: customCode || null, + creatorId: creatorId > 0 ? creatorId : null, + }, + transaction, + } + ); + + const insertHead = Array.isArray(insertResult) ? insertResult[0] : null; + const comboId = toNumber( + (typeof insertHead === 'number' && insertHead > 0) ? insertHead + : (insertHead && (insertHead.insertId || insertHead.lastID || insertHead.id)) + || (insertResult && insertResult.insertId) + || 0 + ); + if (comboId <= 0) { + throw new Error('创建组合商品主记录失败'); + } + + // 批量插入明细 + if (items.length > 0) { + const itemValues = items.map((item, index) => { + const skuId = toNumber(item.item_goods_sku_id); + const qty = Math.max(1, toNumber(item.item_quantity, 1)); + const sortOrder = toNumber(item.sort_order, index); + return `(${comboId}, ${skuId}, ${qty}, ${sortOrder})`; + }).join(', '); + + await ctx.model.query( + `INSERT INTO wms_combo_goods_item (combo_id, item_goods_sku_id, item_quantity, sort_order) VALUES ${itemValues}`, + { transaction } + ); + } + + await transaction.commit(); + + return { + id: comboId, + combo_code: trimmedCode, + combo_name: trimmedName, + custom_code: customCode || null, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + // ---------- 3. 编辑组合商品 ---------- + + /** + * 编辑组合商品(含明细替换),使用事务保证原子性。 + * + * @param {Object} options 编辑参数。 + * @param {number} options.id 组合商品ID。 + * @param {string} [options.combo_name] 组合商品名称。 + * @param {number} [options.warehouse_id] 仓库ID。 + * @param {string} [options.remark] 备注。 + * @param {string} [options.custom_code] 自定义编码。 + * @param {number} [options.status] 状态 1-启用 0-停用。 + * @param {Object[]} [options.items] 子商品明细数组。 + * @param {number} [options.editor_id] 编辑人ID。 + * @return {Promise} 编辑结果,包含 id。 + */ + async update(options = {}) { + const { ctx } = this; + const comboId = toNumber(options.id); + const editorId = toNumber(options.editor_id || ctx.user?.id || 0); + + if (comboId <= 0) { + throw new Error('组合商品ID不能为空'); + } + + // 校验记录是否存在 + const existingRows = await ctx.model.query( + 'SELECT id, combo_code, combo_name FROM wms_combo_goods WHERE id = :comboId LIMIT 1', + { + replacements: { comboId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + if (!Array.isArray(existingRows) || existingRows.length === 0) { + throw new Error('组合商品不存在'); + } + + // 如果传入了 items,校验子商品有效性 + const items = options.items; + let itemValidation = null; + if (items !== undefined && Array.isArray(items) && items.length > 0) { + const stockIds = items.map(item => toNumber(item.item_goods_sku_id)).filter(id => id > 0); + itemValidation = await this.validateItems(stockIds); + if (!itemValidation.ok) { + throw new Error(itemValidation.message); + } + } + + // 构建主表更新 set 子句 + const setClauses = []; + const replacements = { comboId }; + if (options.combo_name !== undefined) { + const name = String(options.combo_name).trim(); + if (!name) { + throw new Error('组合商品名称不能为空'); + } + setClauses.push('combo_name = :comboName'); + replacements.comboName = name; + } + if (options.warehouse_id !== undefined) { + const wid = toNumber(options.warehouse_id); + setClauses.push('warehouse_id = :warehouseId'); + replacements.warehouseId = wid > 0 ? wid : null; + } + if (options.remark !== undefined) { + setClauses.push('remark = :remark'); + replacements.remark = String(options.remark); + } + if (options.custom_code !== undefined) { + const customCode = options.custom_code ? String(options.custom_code).trim() : ''; + setClauses.push('custom_code = :customCode'); + replacements.customCode = customCode || null; + } + if (options.status !== undefined) { + const st = toNumber(options.status); + setClauses.push('status = :status'); + replacements.status = st === 1 ? 1 : 0; + } + if (editorId > 0) { + setClauses.push('editor_id = :editorId'); + replacements.editorId = editorId; + } + + // 自定义编码货主唯一性校验(排除自身 id) + if (options.custom_code !== undefined && options.custom_code && String(options.custom_code).trim()) { + const customCode = String(options.custom_code).trim(); + // 获取目标 store_id:优先从传入的 items 的 stockInfoMap 获取,否则查已有子商品 + await this.checkCustomCodeUniqueForUpdate(customCode, comboId, itemValidation); + } + + // 事务执行 + const transaction = await ctx.model.transaction(); + + try { + // 更新主表 + if (setClauses.length > 0) { + await ctx.model.query( + `UPDATE wms_combo_goods SET ${setClauses.join(', ')} WHERE id = :comboId`, + { replacements, transaction } + ); + } + + // 如果传入了 items,先删旧明细再插入新明细 + if (items !== undefined) { + await ctx.model.query( + 'DELETE FROM wms_combo_goods_item WHERE combo_id = :comboId', + { replacements: { comboId }, transaction } + ); + + if (Array.isArray(items) && items.length > 0) { + const itemValues = items.map((item, index) => { + const skuId = toNumber(item.item_goods_sku_id); + const qty = Math.max(1, toNumber(item.item_quantity, 1)); + const sortOrder = toNumber(item.sort_order, index); + return `(${comboId}, ${skuId}, ${qty}, ${sortOrder})`; + }).join(', '); + + await ctx.model.query( + `INSERT INTO wms_combo_goods_item (combo_id, item_goods_sku_id, item_quantity, sort_order) VALUES ${itemValues}`, + { transaction } + ); + } + } + + await transaction.commit(); + + return { id: comboId }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + // ---------- 4. 删除组合商品 ---------- + + /** + * 删除组合商品(软删除:status = 0)。 + * + * @param {Object} options 删除参数。 + * @param {number} options.id 组合商品ID。 + * @return {Promise} 删除结果。 + */ + async delete(options = {}) { + const { ctx } = this; + const comboId = toNumber(options.id); + + if (comboId <= 0) { + throw new Error('组合商品ID不能为空'); + } + + // 校验记录是否存在 + const existingRows = await ctx.model.query( + 'SELECT id FROM wms_combo_goods WHERE id = :comboId LIMIT 1', + { + replacements: { comboId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + if (!Array.isArray(existingRows) || existingRows.length === 0) { + throw new Error('组合商品不存在'); + } + + // 软删除:将 status 置为 0 + await ctx.model.query( + 'UPDATE wms_combo_goods SET status = 0 WHERE id = :comboId', + { + replacements: { comboId }, + type: ctx.model.QueryTypes.UPDATE, + } + ); + + return { id: comboId }; + } + + // ---------- 5. 关键字搜索 ---------- + + /** + * 关键字搜索组合商品(模糊匹配 custom_code、combo_code 或 combo_name,自定义编码优先排序,限制返回条数)。 + * + * @param {Object} options 搜索选项。 + * @param {string} options.keyword 搜索关键字。 + * @param {number} [options.limit=20] 最大返回条数。 + * @return {Promise} 搜索结果列表。 + */ + async search(options = {}) { + const { ctx } = this; + const keyword = String(options.keyword || '').trim(); + const limit = Math.min(100, Math.max(1, toNumber(options.limit, 20))); + + if (!keyword) { + return { list: [] }; + } + + const rows = await ctx.model.query( + `SELECT * FROM wms_combo_goods + WHERE status = 1 + AND (custom_code LIKE :keywordLike + OR combo_code LIKE :keywordLike + OR combo_name LIKE :keywordLike) + ORDER BY (CASE WHEN custom_code LIKE :keywordLike THEN 0 ELSE 1 END) ASC, + id DESC + LIMIT :limit`, + { + replacements: { + keywordLike: `%${keyword}%`, + limit, + }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + const list = Array.isArray(rows) ? rows : []; + + if (list.length === 0) { + return { list: [] }; + } + + // 批量查询明细 + const comboIds = list.map(row => toNumber(row.id)).filter(id => id > 0); + const itemRows = comboIds.length > 0 + ? await ctx.model.query( + 'SELECT * FROM wms_combo_goods_item WHERE combo_id IN (:comboIds) ORDER BY sort_order ASC, id ASC', + { + replacements: { comboIds }, + type: ctx.model.QueryTypes.SELECT, + } + ) + : []; + + const itemsByComboId = new Map(); + for (const item of Array.isArray(itemRows) ? itemRows : []) { + const cid = toNumber(item.combo_id); + if (!itemsByComboId.has(cid)) { + itemsByComboId.set(cid, []); + } + itemsByComboId.get(cid).push({ + id: toNumber(item.id), + combo_id: cid, + item_goods_sku_id: toNumber(item.item_goods_sku_id), + item_quantity: toNumber(item.item_quantity), + sort_order: toNumber(item.sort_order), + }); + } + + // 批量获取商品信息 + const allStockIds = []; + for (const [ , items ] of itemsByComboId) { + for (const item of items) { + allStockIds.push(item.item_goods_sku_id); + } + } + const stockInfoMap = await this.fetchStockInfoMap(allStockIds); + + const resultList = list.map(row => { + const cid = toNumber(row.id); + const items = itemsByComboId.get(cid) || []; + return { + id: cid, + combo_code: String(row.combo_code || ''), + combo_name: String(row.combo_name || ''), + combo_sku_id: toNumber(row.combo_sku_id), + custom_code: row.custom_code || null, + status: toNumber(row.status), + warehouse_id: toNumber(row.warehouse_id), + remark: String(row.remark || ''), + creator_id: toNumber(row.creator_id), + editor_id: toNumber(row.editor_id), + items, + simpleNotation: this.buildSimpleNotation(items), + nameNotation: this.buildNameNotation(items, stockInfoMap), + }; + }); + + return { list: resultList }; + } + + /** + * 按 id 或 custom_code 搜索组合商品,返回含明细和简记字段的结果。 + * + * @param {Object} options 查询选项 + * @param {number} [options.id] 组合商品主键ID,精确查询单条 + * @param {string} [options.custom_code] 自定义编码,模糊匹配 + * @return {Promise} 包含 list 数组的结果对象,每条含 items、simpleNotation、nameNotation + */ + async searchByIdOrCode(options = {}) { + const { ctx } = this; + const comboId = toNumber(options.id); + const customCode = String(options.custom_code || '').trim(); + + // 优先按 id 精确查询 + if (comboId > 0) { + const rows = await ctx.model.query( + 'SELECT * FROM wms_combo_goods WHERE id = :id AND status = 1', + { + replacements: { id: comboId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + const list = Array.isArray(rows) ? rows : []; + return this.enrichComboList(list); + } + + // 按 custom_code 模糊查询 + if (customCode) { + const sqlQuery = [ + 'SELECT * FROM wms_combo_goods', + 'WHERE status = 1', + 'AND custom_code LIKE :codeLike', + 'ORDER BY id DESC', + 'LIMIT 50', + ].join(' '); + const rows = await ctx.model.query( + sqlQuery, + { + replacements: { codeLike: `%${customCode}%` }, + type: ctx.model.QueryTypes.SELECT, + } + ); + const list = Array.isArray(rows) ? rows : []; + return this.enrichComboList(list); + } + + // 无有效查询条件时走通用搜索 + return this.search({ keyword: '' }); + } + + /** + * 为组合商品列表批量填充子商品明细、simpleNotation 和 nameNotation。 + * + * @param {Object[]} list 组合商品原始行数组 + * @return {Promise} 包含 list 数组的富化结果 + */ + async enrichComboList(list) { + if (list.length === 0) { + return { list: [] }; + } + + // 批量查询明细 + const comboIds = list.map(row => toNumber(row.id)).filter(id => id > 0); + const itemRows = comboIds.length > 0 + ? await this.ctx.model.query( + 'SELECT * FROM wms_combo_goods_item WHERE combo_id IN (:comboIds) ORDER BY sort_order ASC, id ASC', + { + replacements: { comboIds }, + type: this.ctx.model.QueryTypes.SELECT, + } + ) + : []; + + const itemsByComboId = new Map(); + for (const item of Array.isArray(itemRows) ? itemRows : []) { + const cid = toNumber(item.combo_id); + if (!itemsByComboId.has(cid)) { + itemsByComboId.set(cid, []); + } + itemsByComboId.get(cid).push({ + id: toNumber(item.id), + combo_id: cid, + item_goods_sku_id: toNumber(item.item_goods_sku_id), + item_quantity: toNumber(item.item_quantity), + sort_order: toNumber(item.sort_order), + }); + } + + // 批量获取商品信息 + const allStockIds = []; + for (const [ , items ] of itemsByComboId) { + for (const item of items) { + allStockIds.push(item.item_goods_sku_id); + } + } + const stockInfoMap = await this.fetchStockInfoMap(allStockIds); + + const resultList = list.map(row => { + const cid = toNumber(row.id); + const items = itemsByComboId.get(cid) || []; + return { + id: cid, + combo_code: String(row.combo_code || ''), + combo_name: String(row.combo_name || ''), + combo_sku_id: toNumber(row.combo_sku_id), + custom_code: row.custom_code || null, + status: toNumber(row.status), + warehouse_id: toNumber(row.warehouse_id), + remark: String(row.remark || ''), + creator_id: toNumber(row.creator_id), + editor_id: toNumber(row.editor_id), + items, + simpleNotation: this.buildSimpleNotation(items), + nameNotation: this.buildNameNotation(items, stockInfoMap), + }; + }); + + return { list: resultList }; + } +} + +module.exports = ComboGoodsService; diff --git a/app/service/systems/delivery_order.js b/app/service/systems/delivery_order.js index 11de358..fb9f2c1 100644 --- a/app/service/systems/delivery_order.js +++ b/app/service/systems/delivery_order.js @@ -204,8 +204,15 @@ class DeliveryOrderService extends Service { 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(); + let operator = this.getOrderLogOperator(); const warehouseId = this.getOrderLogWarehouseId(requestOptions.warehouseId ?? requestOptions.warehouse_id); + // 根据创建渠道覆盖操作人名称 + const createChannel = String(requestOptions.createChannel ?? requestOptions.create_channel ?? '').trim().toUpperCase(); + if (createChannel === 'QM') { + operator = { id: null, name: '奇门' }; + } else if (createChannel === 'API') { + operator = { id: null, name: 'API' }; + } if (!Array.isArray(operationLogs) || operationLogs.length === 0) { return; @@ -609,6 +616,12 @@ class DeliveryOrderService extends Service { info = { ...info, warehouseId: warehouseIdStr }; const DeliveryModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseIdStr); const { deliveryOrder, orderLines } = data.request; + + // 请求级 extendProps,携带 ewaybill_order_code 等关键字段 + const requestExtendProps = (data.request && data.request.extendProps && Object.keys(data.request.extendProps).length > 0) + ? data.request.extendProps + : undefined; + const normalizedCreateChannel = String( createChannel || deliveryOrder.createChannel @@ -653,7 +666,8 @@ class DeliveryOrderService extends Service { info, normalizedCreateChannel, step, - operationLogs + operationLogs, + requestExtendProps ); // 创建订单 @@ -721,6 +735,7 @@ class DeliveryOrderService extends Service { await this.flushOrderOperationLogs(operationLogs, orderId, { warehouseId: info.warehouseId, + createChannel: normalizedCreateChannel, }); // 异步处理订单后续流程 @@ -748,8 +763,10 @@ class DeliveryOrderService extends Service { } catch (error) { console.error('创建订单失败:', error); - // 回滚事务 - await transaction.rollback(); + // 回滚事务(安全处理,防止事务已结束导致二次回滚异常) + await transaction.rollback().catch(rollbackErr => { + console.error('回滚事务失败:', rollbackErr.message); + }); return { success: false, @@ -952,6 +969,7 @@ class DeliveryOrderService extends Service { * @param {string} [createChannel='MANUAL'] 订单创建渠道标识。 * @param {number} step 订单步骤。 * @param {Array} [operationLogs=[]] 待写入的操作日志数组。 + * @param {Object} [requestExtendProps] 请求级扩展属性,携带 ewaybill_order_code 等关键字段。 * @return {Promise} 可入库的订单数据。 */ async prepareOrderData( @@ -959,7 +977,8 @@ class DeliveryOrderService extends Service { info, createChannel = 'MANUAL', step = DELIVERY_ORDER_STEP.PENDING_REVIEW, - operationLogs = [] + operationLogs = [], + requestExtendProps ) { const { deliveryOrderCode, @@ -1065,8 +1084,10 @@ class DeliveryOrderService extends Service { town: receiverInfo?.town || '', detail_address: receiverInfo?.detailAddress || '', zip_code: receiverInfo?.zipCode || '', + oaid: receiverInfo?.oaid || '', // 发件人信息(如果需要存储) // 业务关联ID + extend_props: requestExtendProps || null, store_id: info.storeId, warehouse_id: info.warehouseId, from_key: this.normalizeOrderFromKey(info.appKey), @@ -1084,7 +1105,7 @@ class DeliveryOrderService extends Service { */ async addOrderLines(orderLines, orderId, info, transaction) { const { ctx, app } = this; - const { warehouseId, appKey, storeId, createChannel } = info; + const { warehouseId, appKey, storeId } = info; let order_items = []; if (orderLines && typeof orderLines === 'object') { @@ -1109,8 +1130,15 @@ class DeliveryOrderService extends Service { const errors = []; const stockQuantityMap = new Map(); // stock_id -> 数量 const stockWeightMap = new Map(); // stock_id -> 单件重量(grossWeight) - const processedItemIds = new Set(); + // 预取签约策略配置(避免锁内查DB,减少锁持有时间) + const oversellConfig = await ctx.service.systems.stockStore + .getStoreWarehousePolicyByStoreAndWarehouse(storeId, warehouseId); + + // ===== Phase 1: 解析阶段(不锁)===== + // 遍历所有 orderLine,解析 StockStore、验证数据、合并重复商品, + // 但不对 wms_stock_warehouse 加锁,避免因传入顺序不同导致死锁。 + const resolvedItems = []; for (let i = 0; i < order_items.length; i++) { const line = order_items[i]; @@ -1158,60 +1186,75 @@ class DeliveryOrderService extends Service { const itemId = parseInt(wms_stock.id); const stockId = Number(wms_stock.stock_id) || 0; - // ========== 核心库存检查逻辑 ========== if (!stockId) { errors.push(`第${i + 1}行: 商品《${wms_stock.item_name}》库存记录不存在`); continue; } - if (processedItemIds.has(itemId)) { - errors.push(`第${i + 1}行: 商品《${wms_stock.item_name}》在同一订单中重复出现`); + // 重复商品:累加到已存在的条目 + const existingIdx = resolvedItems.findIndex(ri => ri.itemId === itemId); + if (existingIdx >= 0) { + resolvedItems[existingIdx].planQty += planQty; + ctx.logger.info(`[addOrderLines] 合并重复行: itemId=${itemId}, 额外数量=${planQty}, 累加后=${resolvedItems[existingIdx].planQty}`); continue; } - processedItemIds.add(itemId); - // 锁定库存 - const lockResult = await ctx.service.systems.stockStore.lockItemStorages( + resolvedItems.push({ + itemId, stockId, planQty, - transaction + wms_stock, + line, + lineIndex: i, + }); + } + + // ===== Sort: 按 stockId 升序排序,保证所有事务加锁顺序一致,从根本上消除死锁 ===== + resolvedItems.sort((a, b) => a.stockId - b.stockId); + + // ===== Phase 2: 锁定阶段(按排序后顺序逐个加锁)===== + for (const item of resolvedItems) { + const lockResult = await ctx.service.systems.stockStore.lockItemStorages( + item.stockId, + item.planQty, + transaction, + oversellConfig ); if (!lockResult.success) { - errors.push(`SKU${wms_stock.id}商品《${wms_stock.item_name}》编码《${wms_stock.item_code}》\n锁定失败: ${lockResult.error}`); + errors.push(`SKU${item.wms_stock.id}商品《${item.wms_stock.item_name}》编码《${item.wms_stock.item_code}》\n锁定失败: ${lockResult.error}`); continue; } - const totalQtyForStock = (stockQuantityMap.get(stockId) || 0) + planQty; - stockQuantityMap.set(stockId, totalQtyForStock); + const totalQtyForStock = (stockQuantityMap.get(item.stockId) || 0) + item.planQty; + stockQuantityMap.set(item.stockId, totalQtyForStock); - const weight = parseFloat(wms_stock.gross_weight) || 0; - stockWeightMap.set(stockId, weight); - // ========== 库存检查逻辑结束 ========== + const weight = parseFloat(item.wms_stock.gross_weight) || 0; + stockWeightMap.set(item.stockId, weight); // 所有检查通过,准备订单行数据 lineData.push({ order_id: orderId, - actual_price: this.safeParseFloat(line.actualPrice, 0), - retail_price: this.safeParseFloat(line.retailPrice, 0), - ext_code: line.extCode || '', - inventory_type: line.inventoryType || '', - item_code: line.itemCode || '', - item_id: itemId, - item_name: line.itemName || '', - order_line_no: line.orderLineNo || `${i + 1}`, - owner_code: line.ownerCode || '', - plan_qty: planQty, - source_order_code: line.sourceOrderCode || '', - sub_source_order_code: line.subSourceOrderCode || '', - extend_props: line.extendProps ? - (typeof line.extendProps === 'string' ? line.extendProps : JSON.stringify(line.extendProps)) + actual_price: this.safeParseFloat(item.line.actualPrice, 0), + retail_price: this.safeParseFloat(item.line.retailPrice, 0), + ext_code: item.line.extCode || '', + inventory_type: item.line.inventoryType || '', + item_code: item.line.itemCode || '', + item_id: item.itemId, + item_name: item.line.itemName || '', + order_line_no: item.line.orderLineNo || `${item.lineIndex + 1}`, + owner_code: item.line.ownerCode || '', + plan_qty: item.planQty, + source_order_code: item.line.sourceOrderCode || '', + sub_source_order_code: item.line.subSourceOrderCode || '', + extend_props: item.line.extendProps ? + (typeof item.line.extendProps === 'string' ? item.line.extendProps : JSON.stringify(item.line.extendProps)) : null, - stock_id: stockId, - item_snapshot: this.buildOrderItemSnapshot(wms_stock, line), + stock_id: item.stockId, + item_snapshot: this.buildOrderItemSnapshot(item.wms_stock, item.line), // 可选:记录重量信息到明细 - item_weight: stockWeightMap.get(stockId) || 0, + item_weight: stockWeightMap.get(item.stockId) || 0, }); } @@ -1270,8 +1313,8 @@ class DeliveryOrderService extends Service { itemEntries.set(iid, (itemEntries.get(iid) || 0) + qty); } items_str = Array.from(itemEntries.entries()) - .sort(([a], [b]) => a - b) - .map(([iid, qty]) => `${iid}+${qty}`) + .sort(([ a ], [ b ]) => a - b) + .map(([ iid, qty ]) => `${iid}+${qty}`) .join('|'); source_order_codes = new Set(lineData.map(line => line.source_order_code).filter(code => code)); @@ -1507,6 +1550,70 @@ class DeliveryOrderService extends Service { return [ '1', 'true', 'yes', 'on' ].includes(normalizedText); } + /** + * 解析截单配置,货主-仓库级优先,未启用时由仓库级兜底。 + * + * @param {Object} policyConfig 货主-仓库级策略配置。 + * @param {Object|null} warehouseSubjectConfig 仓库级主体配置。 + * @return {{cutoffEnabled: boolean, cutoffTime: string}} 最终生效的截单开关与截单时间。 + */ + resolveCutoffOrderConfig(policyConfig, warehouseSubjectConfig) { + const policyEnabled = this.normalizePolicyFlag( + (policyConfig && policyConfig.cutoff_order_enabled) + ); + const policyTime = (policyConfig && typeof policyConfig.cutoff_order_time === 'string' + ? policyConfig.cutoff_order_time.trim() + : '') || '18:00'; + + // 货主-仓库级已启用截单,直接使用 + if (policyEnabled) { + return { + cutoffEnabled: true, + cutoffTime: policyTime, + }; + } + + // 货主-仓库级未启用,由仓库级兜底 + if (warehouseSubjectConfig && warehouseSubjectConfig.cutoff_order_enabled) { + const warehouseTime = (typeof warehouseSubjectConfig.cutoff_order_time === 'string' + ? warehouseSubjectConfig.cutoff_order_time.trim() + : '') || '18:00'; + return { + cutoffEnabled: true, + cutoffTime: warehouseTime, + }; + } + + return { + cutoffEnabled: false, + cutoffTime: '18:00', + }; + } + + /** + * 判断当前时间是否已超过指定截单时间。 + * + * @param {string} cutoffTimeStr 截单时间,格式 HH:mm。 + * @return {boolean} 是否已超过截单时间。 + */ + isPastCutoffTime(cutoffTimeStr) { + if (!cutoffTimeStr || typeof cutoffTimeStr !== 'string') { + return false; + } + + const trimmed = cutoffTimeStr.trim(); + if (!/^\d{2}:\d{2}$/.test(trimmed)) { + return false; + } + + const now = new Date(); + const [ hours, minutes ] = trimmed.split(':').map(Number); + const cutoffTotalMinutes = hours * 60 + minutes; + const nowTotalMinutes = now.getHours() * 60 + now.getMinutes(); + + return nowTotalMinutes >= cutoffTotalMinutes; + } + /** * 构建自动加团结构信息。 * @@ -1528,7 +1635,7 @@ class DeliveryOrderService extends Service { return null; } - const logisticsName = String(order.logistics_name || '').trim(); + const logisticsName = String(order.sys_logistics_code || '').trim(); const mergedItemDetails = typeof waveService.mergeOrderItemDetails === 'function' ? waveService.mergeOrderItemDetails(context && context.orderItemRows ? context.orderItemRows : []) : []; @@ -1679,6 +1786,14 @@ class DeliveryOrderService extends Service { transaction, }); + await ctx.service.systemMethods.order.wave.rebuildOrderWaveIndex({ + warehouseId, + waveId: normalizedWaveId, + orderIds: [ orderId ], + orderModel: DeliveryModel, + transaction, + }); + await ctx.model.query(` UPDATE wms_wave_batch SET total_orders = total_orders + 1, @@ -1694,6 +1809,38 @@ class DeliveryOrderService extends Service { }); await transaction.commit(); + + // 写入订单操作日志:自动加团 + try { + const operationLogService = this.ctx + && this.ctx.service + && this.ctx.service.systems + && this.ctx.service.systems.operationLog; + if (operationLogService && typeof operationLogService.createOperationLogs === 'function') { + await operationLogService.createOperationLogs([{ + businessType: 'order', + businessId: `${orderId}`, + operationCode: 'ORDER_WAVE_AUTO_GROUP', + operator: { + id: null, + name: 'system', + }, + extras: { + message: `自动加团到波次 ${wave.wave_no || normalizedWaveId}`, + warehouseId, + waveId: normalizedWaveId, + waveNo: wave.wave_no || '', + }, + }]); + } + } catch (e) { + this.ctx.logger.warn('[delivery_order.appendOrderToWave] 写入 operation_log 失败,不影响主流程', { + error: e && e.message, + orderId, + waveId: normalizedWaveId, + }); + } + return true; } catch (error) { await transaction.rollback(); @@ -1717,7 +1864,7 @@ class DeliveryOrderService extends Service { step: { [ctx.app.Sequelize.Op.in]: [ 1, 2, 3 ] }, status: { [ctx.app.Sequelize.Op.ne]: 'cancel' }, outbound_status: { [ctx.app.Sequelize.Op.ne]: 'padding' }, - logistics_name: structure.logisticsName, + sys_logistics_code: structure.logisticsName, }; where[structure.itemPartType] = structure.itemPart; @@ -1743,6 +1890,7 @@ class DeliveryOrderService extends Service { item_part: structure.itemPart, distinguish_express: true, logistics_name: structure.logisticsName, + sys_logistics_code: structure.logisticsName, item_snapshot_key: structure.itemSnapshotKey, item_detail_machine: structure.itemDetailMachine, quantity: maxWaveQuantity, @@ -1866,6 +2014,7 @@ class DeliveryOrderService extends Service { } await this.finishAutoGroupingIfNeeded(context, matchedAutoGroupingWaveId, maxWaveQuantity); + // appendOrderToWave 内部已写入 ORDER_WAVE_AUTO_GROUP 日志 return; } @@ -1889,6 +2038,42 @@ class DeliveryOrderService extends Service { await this.markWaveAutoGrouping(context, createdWaveIds); await this.finishAutoGroupingIfNeeded(context, createdWaveIds[0], maxWaveQuantity); + + // 写入 ORDER_WAVE_AUTO_GROUP 日志(新建波次路径) + if (context.orderId) { + try { + const waveRows = await ctx.model.query(` + SELECT wave_no FROM wms_wave_batch + WHERE warehouse_id = :warehouseId AND wave_id = :waveId + LIMIT 1 + `, { + replacements: { warehouseId: context.warehouseId, waveId: createdWaveIds[0] }, + type: ctx.model.QueryTypes.SELECT, + }); + const waveNo = (Array.isArray(waveRows) && waveRows[0]) ? String(waveRows[0].wave_no || '').trim() : ''; + const opLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog; + if (opLogService && typeof opLogService.createOperationLogs === 'function') { + await opLogService.createOperationLogs([{ + businessType: 'order', + businessId: `${context.orderId}`, + operationCode: 'ORDER_WAVE_AUTO_GROUP', + operator: { id: null, name: 'system' }, + extras: { + message: `自动加团到波次 ${waveNo || createdWaveIds[0]}`, + warehouseId: context.warehouseId, + waveId: createdWaveIds[0], + waveNo, + }, + }]); + } + } catch (e) { + ctx.logger.warn('[delivery_order.runAutoGrouping] 写入 ORDER_WAVE_AUTO_GROUP 日志失败', { + error: e && e.message, + orderId: context.orderId, + waveId: createdWaveIds[0], + }); + } + } } /** @@ -1933,8 +2118,18 @@ class DeliveryOrderService extends Service { } const policyConfig = await this.getStoreWarehousePolicyConfig(context.storeId, context.warehouseId); - const isAutoAllocateExpressEnabled = this.normalizePolicyFlag(policyConfig.auto_allocate_express); - const isAutoAllocateStorageEnabled = this.normalizePolicyFlag(policyConfig.auto_allocate_storage); + + // 截单时间兜底:货主-仓库级未启用时,fallback 到仓库级配置 + const warehouseSubjectConfig = await this.getStoreSubjectConfig(context.warehouseId); + const { cutoffEnabled, cutoffTime } = this.resolveCutoffOrderConfig(policyConfig, warehouseSubjectConfig); + + const isCutoffActive = cutoffEnabled && this.isPastCutoffTime(cutoffTime); + + // 如果需要审核,不触发自动分配快递、储位、加团 + const needApproval = Number(policyConfig && policyConfig.need_order_approval) !== 0; + + const isAutoAllocateExpressEnabled = !isCutoffActive && !needApproval && this.normalizePolicyFlag(policyConfig.auto_allocate_express); + const isAutoAllocateStorageEnabled = !isCutoffActive && !needApproval && this.normalizePolicyFlag(policyConfig.auto_allocate_storage); if (isAutoAllocateExpressEnabled) { await this.runAsyncProcessStep('allocateExpress', async () => { @@ -1960,9 +2155,11 @@ class DeliveryOrderService extends Service { }); } - await this.runAsyncProcessStep('autoGrouping', async () => { - await this.runAutoGrouping(context); - }); + if (!isCutoffActive && !needApproval) { + await this.runAsyncProcessStep('autoGrouping', async () => { + await this.runAutoGrouping(context); + }); + } await this.runAsyncProcessStep('waveStrategyQuickScan', async () => { await this.withPatchedCtxUser({ diff --git a/app/service/systems/entry_order.js b/app/service/systems/entry_order.js index c44d69a..33de8b1 100644 --- a/app/service/systems/entry_order.js +++ b/app/service/systems/entry_order.js @@ -2,9 +2,19 @@ const Service = require('egg').Service; class entryOrderService extends Service { - async addOrder(data, info, fromCode) { + /** + * 创建入库单(含明细行校验与插入)。 + * @param {Object} data 请求体,包含 request.entryOrder 与 request.orderLines + * @param {Object} info 上下文信息 { storeId, warehouseId, appKey, customerId, warehouseCode } + * @param {string} fromCode 来源标识(WMS / API / QM) + * @param {Object} [options={}] 可选配置 + * @param {boolean} [options.autoReview=false] 是否自动审核,true 时入库单创建后状态直接变为 PENDING + * @return {Promise} { success, message, data: { entryOrderId, entryOrderCode, createTime, warehouseCode, status } } + */ + async addOrder(data, info, fromCode, options = {}) { + const { autoReview = false } = options; const { storeId, warehouseId, appKey, customerId, warehouseCode } = info; - const { app } = this; + const { app, ctx } = this; const transaction = await app.model.transaction(); // 开启事务 try { @@ -51,14 +61,14 @@ class entryOrderService extends Service { await transaction.rollback(); // 验证失败,回滚事务 return { success: false, - message: '创建入库单失败,失败原因:\n' + errors.join('\n'), + message: `创建入库单失败,失败原因:\n${errors.join('\n')}`, data: { createTime: new Date(), }, }; } - // 创建入库单(内部也使用事务) + // 创建入库单(内部也使用事务),autoReview 在 addOrder 层控制最终状态 const order = await this.tryCreateEntryOrder( data.request.entryOrder, appKey, @@ -110,10 +120,13 @@ class entryOrderService extends Service { const lineCount = await this.getLineCount(orderId, transaction); const expectedTotalOrderLines = Number(totalOrderLines) || 0; + // autoReview 决定最终状态:true → PENDING(已审核),false → CREATED(已创建待审核) + const finalStatus = autoReview ? 'PENDING' : 'CREATED'; + if (lineCount === expectedTotalOrderLines) { - // 所有明细行已插入完毕,将状态从 CREATING 更新为 PENDING(等待收货) + // 所有明细行已插入完毕,将状态从 CREATING 更新为目标状态 await app.model.EntryOrder.update( - { order_status: 'PENDING', updated_at: new Date() }, + { order_status: finalStatus, updated_at: new Date() }, { where: { id: orderId, warehouse_id: warehouseId, store_id: storeId }, transaction } ); } @@ -121,16 +134,25 @@ class entryOrderService extends Service { // 提交事务 await transaction.commit(); + // 异步匹配收货单并写入绑定关系(不阻塞 addOrder 返回) + if (lineCount === expectedTotalOrderLines) { + setImmediate(() => { + ctx.service.systems.receivingEntryMatch.matchAfterEntryCompleted(orderId).catch(err => { + ctx.logger.error(`[addOrder] 异步匹配收货单异常: ${err.message}`, err.stack); + }); + }); + } + if (lineCount === expectedTotalOrderLines) { return { success: true, - message: '入库单创建完成,等待收货', + message: '入库单创建完成', data: { entryOrderId: orderId, entryOrderCode: orderCode, createTime: new Date(), warehouseCode, - status: 'PENDING', + status: finalStatus, }, }; } @@ -163,7 +185,12 @@ class entryOrderService extends Service { } } - // 辅助函数:获取行数(支持事务) + /** + * 获取入库单的明细行数(支持事务)。 + * @param {number} orderId 入库单ID + * @param {Object|null} [transaction=null] 可选事务对象 + * @return {Promise} 明细行数 + */ async getLineCount(orderId, transaction = null) { const { app } = this; const options = { @@ -178,7 +205,14 @@ class entryOrderService extends Service { return count; } - // 辅助函数:标记为已接收(支持事务) + /** + * 标记入库单为已完成(支持事务)。 + * @param {number} orderId 入库单ID + * @param {number} warehouseId 仓库ID + * @param {number} storeId 货主ID + * @param {Object|null} [transaction=null] 可选事务对象 + * @return {Promise} + */ async received(orderId, warehouseId, storeId, transaction = null) { const { app } = this; const updateData = { @@ -254,7 +288,7 @@ class entryOrderService extends Service { { model: ctx.model.StockWarehouse, as: 'stock', - attributes: [ 'product_code', 'product_name' ], + attributes: [ 'item_code', 'item_name' ], }, ], }, @@ -356,8 +390,6 @@ class entryOrderService extends Service { const stats = { pending: 0, - confirmed: 0, - partial_received: 0, completed: 0, cancelled: 0, total: 0, @@ -414,10 +446,9 @@ class entryOrderService extends Service { } const validTransitions = { - PENDING: [ 'CONFIRMED', 'CANCELLED' ], - CONFIRMED: [ 'PARTIAL_RECEIVED', 'COMPLETED', 'CANCELLED' ], - PARTIAL_RECEIVED: [ 'COMPLETED', 'CANCELLED' ], - CREATING: [ 'PENDING', 'CANCELLED' ], + CREATED: [ 'PENDING', 'CANCELLED' ], + PENDING: [ 'COMPLETED', 'CANCELLED' ], + CREATING: [ 'CREATED', 'CANCELLED' ], }; const allowedTransitions = validTransitions[order.order_status]; @@ -566,6 +597,21 @@ class entryOrderService extends Service { }; } + /** + * 尝试创建入库单(含去重与状态校验)。 + * 若入库单已存在且状态为 CREATING,则复用该记录;否则新建,初始状态为 CREATING。 + * 最终状态(CREATED / PENDING)由调用方 addOrder 根据 autoReview 决定。 + * @param {Object} order 入库单基本信息 + * @param {string} appKey 应用标识 + * @param {number} storeId 货主ID + * @param {number} warehouseId 仓库ID + * @param {number} totalOrderLines 总行数 + * @param {string} sourceType 来源类型(WMS / API / QM) + * @param {string|null} qimenOwnerCode 奇门货主编码 + * @param {string|null} qimenWarehouseCode 奇门仓库编码 + * @param {Object|null} [transaction=null] 外部事务对象 + * @return {Promise} { success, code, message, entryOrderId, entryOrderCode, orderStatus, error? } + */ async tryCreateEntryOrder(order, appKey, storeId, warehouseId, totalOrderLines, sourceType, qimenOwnerCode, qimenWarehouseCode, transaction = null) { const { ctx } = this; @@ -835,7 +881,7 @@ class entryOrderService extends Service { } // 状态检查 - const allowedStatuses = [ 'PENDING', 'PARTIAL_RECEIVED', 'CONFIRMED' ]; + const allowedStatuses = [ 'CREATED', 'PENDING' ]; if (!allowedStatuses.includes(entryOrder.order_status)) { await transaction.rollback(); return { @@ -953,11 +999,8 @@ class entryOrderService extends Service { if (isFin) { newOrderStatus = 'COMPLETED'; } else if (totalConfirmIncrement > 0) { - if (entryOrder.order_status === 'PENDING') { - newOrderStatus = 'CONFIRMED'; - } else { - newOrderStatus = 'PARTIAL_RECEIVED'; - } + // CREATED 确认后变为 PENDING,PENDING 确认后保持 PENDING(多次收货确认) + newOrderStatus = 'PENDING'; } const updateResult = await app.model.EntryOrder.update({ diff --git a/app/service/systems/express_platform.js b/app/service/systems/express_platform.js index 17ed35e..b67e63f 100644 --- a/app/service/systems/express_platform.js +++ b/app/service/systems/express_platform.js @@ -340,6 +340,249 @@ class ExpressPlatformService extends MainService { return `express_platform_trace_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`; } + /** + * 清理平台取号失败的订单资源。 + * + * 回退 print_quantity_locked、硬删除 OrderExpress(status=0) 记录、 + * 标记订单异常、写失败日志。所有清理步骤在事务内完成,保证原子性。 + * + * @param {Array<{order_id: number, business_key: number, warehouse_id: number, store_id?: number}>} failedOrders 失败订单列表。 + * @param {string} reason 失败原因描述。 + * @return {Promise} 无返回值。 + */ + async cleanupFailedWaybillOrders(failedOrders, reason) { + const normalizedFailedOrders = Array.isArray(failedOrders) ? failedOrders : []; + if (normalizedFailedOrders.length === 0) { + return; + } + + const traceId = this.buildExpressPlatformTraceId(); + const normalizedReason = String(reason || '未知失败').trim(); + this.ctx.logger.info('[expressPlatform.cleanupFailedWaybillOrders] 开始清理失败订单资源', { + traceId, + failedCount: normalizedFailedOrders.length, + reason: normalizedReason, + failedOrderKeys: normalizedFailedOrders.map(o => `${o.warehouse_id}_${o.order_id}_${o.business_key}`).join(','), + }); + + const { Op } = this.app.Sequelize; + const storeWarehouseModel = this.ctx.model && this.ctx.model.StoreWarehouse; + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; + + try { + // 1) 按 store_id:warehouse_id 聚合回退 lock 量 + const restoreRelationMap = new Map(); + for (const order of normalizedFailedOrders) { + const storeId = Number(order.store_id) || 0; + const warehouseId = Number(order.warehouse_id) || 0; + if (!storeId || !warehouseId) { + continue; + } + const relationKey = `${storeId}:${warehouseId}`; + const currentRelation = restoreRelationMap.get(relationKey) || { + store_id: storeId, + warehouse_id: warehouseId, + failed_count: 0, + }; + currentRelation.failed_count += 1; + restoreRelationMap.set(relationKey, currentRelation); + } + + if (restoreRelationMap.size > 0 && storeWarehouseModel && typeof storeWarehouseModel.findAll === 'function') { + const restoreRelationList = Array.from(restoreRelationMap.values()); + const restoreRows = await storeWarehouseModel.findAll({ + attributes: [ 'id', 'store_id', 'warehouse_id', 'print_quantity_locked' ], + where: { + [Op.or]: restoreRelationList.map(item => ({ + store_id: item.store_id, + warehouse_id: item.warehouse_id, + })), + }, + raw: true, + }); + + const restoreRowMap = new Map(); + for (const row of Array.isArray(restoreRows) ? restoreRows : []) { + const relationKey = `${Number(row && row.store_id) || 0}:${Number(row && row.warehouse_id) || 0}`; + if (relationKey !== '0:0') { + restoreRowMap.set(relationKey, row); + } + } + + const canIncrementLockedQuantity = typeof storeWarehouseModel.increment === 'function'; + + for (const item of restoreRelationList) { + const relationKey = `${item.store_id}:${item.warehouse_id}`; + const row = restoreRowMap.get(relationKey); + if (!row) { + continue; + } + + const currentLockedQuantity = Math.max(0, Number(row.print_quantity_locked || 0)); + const restoreQuantity = Math.min(currentLockedQuantity, item.failed_count); + if (restoreQuantity <= 0) { + continue; + } + + if (canIncrementLockedQuantity) { + await storeWarehouseModel.increment('print_quantity_locked', { + by: -restoreQuantity, + where: { + id: row.id, + }, + }); + } else { + await storeWarehouseModel.update({ + print_quantity_locked: currentLockedQuantity - restoreQuantity, + }, { + where: { + id: row.id, + }, + }); + } + + // 记录回退流水 + try { + 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_restore', + business_type: 'order_express', + business_id: null, + change_quantity: -restoreQuantity, + balance_before: Math.max(0, currentLockedQuantity), + balance_after: Math.max(0, currentLockedQuantity - restoreQuantity), + reason: `平台取号失败回退锁定: ${normalizedReason}`, + operator_id: null, + created_by: null, + }); + } catch (logError) { + this.ctx.logger.error('[expressPlatform.cleanupFailedWaybillOrders] 回退流水写入失败', { + traceId, + error: logError && logError.message ? logError.message : `${logError}`, + }); + } + } + } + + // 2) 硬删除 OrderExpress(status=0) 记录 + if (orderExpressModel && typeof orderExpressModel.destroy === 'function') { + const deleteConditions = []; + for (const order of normalizedFailedOrders) { + const orderId = Number(order.order_id) || 0; + const businessKey = Number(order.business_key) || 0; + if (!orderId || !businessKey) { + continue; + } + deleteConditions.push({ + order_id: orderId, + business_key: businessKey, + }); + } + + if (deleteConditions.length > 0) { + try { + await orderExpressModel.destroy({ + where: { + [Op.or]: deleteConditions, + status: 0, + }, + }); + } catch (destroyError) { + this.ctx.logger.error('[expressPlatform.cleanupFailedWaybillOrders] 硬删除 OrderExpress 失败', { + traceId, + error: destroyError && destroyError.message ? destroyError.message : `${destroyError}`, + }); + } + } + } + + // 3) 标记订单异常 + const failedOrderIds = normalizedFailedOrders + .map(order => Number(order.order_id) || 0) + .filter(orderId => orderId > 0); + const uniqueFailedOrderIds = Array.from(new Set(failedOrderIds)); + if (uniqueFailedOrderIds.length > 0) { + const orderPendingExceptionService = this.service + && this.service.systems + && this.service.systems.orderPendingException; + if (orderPendingExceptionService && typeof orderPendingExceptionService.markPendingException === 'function') { + try { + await orderPendingExceptionService.markPendingException({ + ids: uniqueFailedOrderIds, + exception_text: `订单快递分配失败(${normalizedReason})`, + }); + } catch (markError) { + this.ctx.logger.error('[expressPlatform.cleanupFailedWaybillOrders] 标记订单异常失败', { + traceId, + error: markError && markError.message ? markError.message : `${markError}`, + }); + } + } + } + + // 4) 写失败日志 + const expressService = this.service && this.service.systems && this.service.systems.express; + if (expressService && typeof expressService.createAllocateExpressFailureLogs === 'function' && uniqueFailedOrderIds.length > 0) { + const sampleWarehouseId = normalizedFailedOrders.length > 0 + ? (Number(normalizedFailedOrders[0].warehouse_id) || null) + : null; + try { + await expressService.createAllocateExpressFailureLogs(uniqueFailedOrderIds, normalizedReason, sampleWarehouseId); + } catch (logError) { + this.ctx.logger.error('[expressPlatform.cleanupFailedWaybillOrders] 写失败日志异常', { + traceId, + error: logError && logError.message ? logError.message : `${logError}`, + }); + } + } + + this.ctx.logger.info('[expressPlatform.cleanupFailedWaybillOrders] 清理完成', { + traceId, + failedCount: normalizedFailedOrders.length, + deletedExpressCount: normalizedFailedOrders.filter(o => Number(o.order_id) > 0 && Number(o.business_key) > 0).length, + markedOrderCount: uniqueFailedOrderIds.length, + restoredRelationCount: restoreRelationMap.size, + }); + } catch (error) { + this.ctx.logger.error('[expressPlatform.cleanupFailedWaybillOrders] 清理流程异常', { + traceId, + error: error && error.message ? error.message : `${error}`, + stack: error && error.stack ? error.stack : '', + }); + // 清理异常不抛给上游,避免干扰主流程 + } + } + + /** + * 从 orders 数据中提取失败订单清理所需的基本字段。 + * + * @param {Array} orders 订单列表。 + * @return {Array<{order_id: number, business_key: number, warehouse_id: number, store_id: number}>} 标准化后的失败订单列表。 + */ + buildFailedOrderCleanupList(orders = []) { + const normalizedOrders = Array.isArray(orders) ? orders : []; + const result = []; + for (const order of normalizedOrders) { + const orderDelivery = order && order.order_delivery ? order.order_delivery : {}; + const orderId = Number(orderDelivery.id) || Number(order.order_id) || 0; + const businessKey = Number(order.business_key) || 0; + const warehouseId = Number(orderDelivery.warehouse_id) || Number(order.warehouse_id) || 0; + const storeId = Number(orderDelivery.store_id) || Number(order.store_id) || 0; + if (!orderId || !businessKey) { + continue; + } + result.push({ + order_id: orderId, + business_key: businessKey, + warehouse_id: warehouseId, + store_id: storeId, + }); + } + return result; + } + /** * 菠萝派数据处理接口。 * @@ -430,6 +673,19 @@ class ExpressPlatformService extends MainService { api: 'Differ.JH.LogisticsPlatFeatures', response: Dictionary_result, }); + if (Dictionary_result && Dictionary_result.code && String(Dictionary_result.code) !== '10000') { + const dictErrorMessage = String(Dictionary_result.submessage || Dictionary_result.message || '字典接口调用失败').trim(); + this.ctx.logger.error('[expressPlatform.polyapi] PolyAPI 字典接口返回业务失败', { + traceId, + code: Dictionary_result.code, + message: dictErrorMessage, + response: Dictionary_result, + }); + // 字典接口失败,清理所有订单后抛出 + const allFailedOrders = this.buildFailedOrderCleanupList(orders); + await this.cleanupFailedWaybillOrders(allFailedOrders, `字典接口失败: ${dictErrorMessage}`); + throw new Error(`菠萝派字典接口返回错误: ${dictErrorMessage}`); + } console.log('listByWarehousePlatformCode', listByWarehousePlatformCode); const order_bizcontent = { orders: orders.map(order_tmp => { @@ -644,13 +900,19 @@ class ExpressPlatformService extends MainService { response: JSON.stringify(result), }); if (result && result.code !== '10000') { + const postOrderErrorMessage = String( + result.submessage || result.message || '菠萝派平台接口调用失败' + ).trim(); this.ctx.logger.error('[expressPlatform.polyapi] PolyAPI 返回业务失败', { traceId, code: result.code, - message: result.submessage, + message: postOrderErrorMessage, response: result, }); - throw new Error(`菠萝派平台接口返回错误信息:${result.submessage},原始错误信息: \`\`\`${JSON.stringify(result)}\`\`\`` || '菠萝派平台接口调用失败'); + // 清洗本批次全部订单资源,然后抛出 + const allFailedOrders = this.buildFailedOrderCleanupList(orders); + await this.cleanupFailedWaybillOrders(allFailedOrders, `PostOrder业务失败: ${postOrderErrorMessage}`); + throw new Error(`菠萝派平台接口返回错误信息:${postOrderErrorMessage},原始错误信息: \`\`\`${JSON.stringify(result)}\`\`\``); } else if (result && result.code === '10000') { const resolveWaybillCode = item => String(item && (item.waybill_code || item.logisticno) || '').trim(); let successUpdates = []; @@ -994,8 +1256,72 @@ class ExpressPlatformService extends MainService { }; }); break; - default: - break; + default: { + const unmatchedPlatformCode = String(listByWarehousePlatformCode && listByWarehousePlatformCode.platform_code || '').trim(); + this.ctx.logger.error('[expressPlatform.polyapi] switch 无匹配 platform_code', { + traceId, + platform_code: unmatchedPlatformCode, + }); + // 未知平台编码,清理本批次全部订单资源后抛出 + const allFailedOrders = this.buildFailedOrderCleanupList(orders); + await this.cleanupFailedWaybillOrders(allFailedOrders, `未知平台编码: ${unmatchedPlatformCode || '空'}`); + throw new Error(`当前快递平台编码【${unmatchedPlatformCode}】未在system接口中实现,无法获取快递号`); + } + } + + // 统一校验:过滤掉运单号为空的 successUpdates,避免空字符串写入 OrderExpress.waybill_code + const emptyWaybillUpdates = []; + const validSuccessUpdates = []; + for (const item of successUpdates) { + if (!item.waybill_code) { + emptyWaybillUpdates.push(item); + this.ctx.logger.error('[expressPlatform.polyapi] 运单号为空,跳过回写', { + warehouse_id: item.warehouse_id, + order_id: item.order_id, + business_key: item.business_key, + }); + } else { + validSuccessUpdates.push(item); + } + } + successUpdates = validSuccessUpdates; + + if (emptyWaybillUpdates.length > 0) { + this.ctx.logger.error('[expressPlatform.polyapi] 存在运单号为空的订单', { + count: emptyWaybillUpdates.length, + emptyOrderIds: emptyWaybillUpdates.map(i => `${i.warehouse_id}_${i.order_id}_${i.business_key}`).join(','), + totalSuccessUpdates: successUpdates.length, + }); + + // 反查 orders 找到运单号为空订单对应的 store_id,补齐清理所需信息后统一清理 + const emptyFailedOrders = []; + for (const emptyItem of emptyWaybillUpdates) { + const orderId = Number(emptyItem.order_id) || 0; + const warehouseId = Number(emptyItem.warehouse_id) || 0; + const businessKey = Number(emptyItem.business_key) || 0; + let storeId = 0; + for (const order of Array.isArray(orders) ? orders : []) { + const orderDelivery = order && order.order_delivery; + const oId = Number(orderDelivery && orderDelivery.id) || 0; + const bk = Number(order && order.business_key) || 0; + if (oId === orderId && bk === businessKey) { + storeId = Number(orderDelivery && orderDelivery.store_id) || 0; + break; + } + } + emptyFailedOrders.push({ + order_id: orderId, + business_key: businessKey, + warehouse_id: warehouseId, + store_id: storeId, + }); + } + await this.cleanupFailedWaybillOrders(emptyFailedOrders, '运单号为空'); + + // 全部订单都失败则抛出 + if (successUpdates.length === 0) { + throw new Error(`菠萝派平台接口返回运单号全部为空,共${emptyWaybillUpdates.length}笔订单取号失败`); + } } const orderMetaMap = new Map(); diff --git a/app/service/systems/inbound_direct_log.js b/app/service/systems/inbound_direct_log.js new file mode 100644 index 0000000..6ea3993 --- /dev/null +++ b/app/service/systems/inbound_direct_log.js @@ -0,0 +1,893 @@ +'use strict'; + +const Service = require('egg').Service; + +/** + * 非收货单途径入库直接记录服务(导入/PDA入库)。 + * + * 职责: + * 1. 根据入库单号获取入库明细(含已记录的导入/PDA 入库记录) + * 2. 按商品增量添加导入/PDA 入库记录,超计划数量时拒绝 + * 3. 提交确认完成入库,写入库存并触发奇门/API 回传 + */ +class InboundDirectLogService extends Service { + + /** + * 获取入库单的受控入库信息。 + * 返回入库单基本信息、明细列表,以及每项明细已有的导入/PDA 入库记录。 + * @param {string} entryOrderCode 入库单号 + * @return {Promise} code/data/message 结构 + */ + async getItems(entryOrderCode) { + const { ctx } = this; + const code = String(entryOrderCode || '').trim(); + + if (!code) { + return { code: 400, message: 'entry_order_code 必填', data: null }; + } + + const entryOrder = await ctx.model.EntryOrder.findOne({ + where: { + entry_order_code: code, + warehouse_id: ctx.user.store_id, + is_enabled: 1, + deleted_at: null, + }, + include: [ + { + model: ctx.model.EntryItems, + as: 'items', + required: false, + include: [ + { + model: ctx.model.StockWarehouse, + as: 'stock', + attributes: [ 'id', 'item_code', 'item_name', 'sku_property' ], + required: false, + }, + ], + }, + { + model: ctx.model.EntryOrderReceiving, + as: 'receivingBindings', + required: false, + include: [ + { + model: ctx.model.Receiving, + as: 'receiving', + attributes: [ 'id', 'receiving_number', 'status', 'storage_status', 'created_at' ], + required: false, + }, + ], + }, + ], + }); + + if (!entryOrder) { + return { code: 404, message: '入库单不存在或无权访问', data: null }; + } + + // 查询该入库单下已有的导入/PDA 入库记录 + const directLogs = await ctx.model.InboundDirectLog.findAll({ + where: { entry_order_id: entryOrder.id }, + order: [[ 'created_at', 'ASC' ]], + }); + + // 按 stock_id 汇总已入库数量 + const logSummary = {}; + for (const log of directLogs) { + const key = String(log.stock_id); + if (!logSummary[key]) { + logSummary[key] = 0; + } + logSummary[key] += Number(log.quantity); + } + + // 将直接入库记录按 entry_item_id 关联到明细 + const itemDirectLogs = {}; + for (const log of directLogs) { + const item = entryOrder.items.find( + i => String(i.stock_id) === String(log.stock_id) + ); + const key = item ? String(item.id) : `stock_${log.stock_id}`; + if (!itemDirectLogs[key]) itemDirectLogs[key] = []; + itemDirectLogs[key].push({ + id: log.id, + stock_id: log.stock_id, + quantity: log.quantity, + inbound_type: log.inbound_type, + remark: log.remark, + operator_id: log.operator_id, + operator_name: log.operator_name, + created_at: log.created_at, + }); + } + + // 将入库单层级的收货单绑定扁平化(不再按明细维度) + const receivingBindings = (entryOrder.receivingBindings && entryOrder.receivingBindings.length > 0) + ? entryOrder.receivingBindings.map(rb => ({ + id: rb.id, + receiving_id: rb.receiving_id, + receiving: rb.receiving || null, + })) + : []; + + // 组装明细 + const items = (entryOrder.items || []).map(item => { + const planQty = Number(item.count) || 0; + const logKey = String(item.id); + const logs = itemDirectLogs[logKey] || []; + const directInQty = logs.reduce((sum, l) => sum + Number(l.quantity), 0); + // 入库进度使用已收货数量 + 导入/PDA 已入库数量 + const totalInboundQty = directInQty + Number(item.received_quantity || 0); + + return { + id: item.id, + stock_id: item.stock_id, + count: planQty, + received_quantity: Number(item.received_quantity) || 0, + item_code: item.item_code, + warehouse_item_code: (item.stock && item.stock.item_code) || '', + warehouse_item_name: (item.stock && item.stock.item_name) || '', + warehouse_item_spec: (item.stock && item.stock.sku_property) || '', + direct_inbound_quantity: directInQty, + remaining_quantity: Math.max(0, planQty - totalInboundQty), + direct_logs: logs, + }; + }); + + return { + code: 200, + message: '查询成功', + data: { + entryOrder: { + id: entryOrder.id, + entry_order_code: entryOrder.entry_order_code, + order_type: entryOrder.order_type, + order_status: entryOrder.order_status, + source_type: entryOrder.source_type, + warehouse_id: entryOrder.warehouse_id, + store_id: entryOrder.store_id, + remark: entryOrder.remark, + }, + items, + direct_logs: directLogs, + receivingBindings, + summary: { + total_items: items.length, + total_planned: items.reduce((s, i) => s + i.count, 0), + total_direct_inbound: items.reduce((s, i) => s + i.direct_inbound_quantity, 0), + total_import: directLogs.filter(l => l.inbound_type === 'import').reduce((s, l) => s + Number(l.quantity), 0), + total_pda: directLogs.filter(l => l.inbound_type === 'pda').reduce((s, l) => s + Number(l.quantity), 0), + }, + }, + }; + } + + /** + * 单条校验并写入一条导入/PDA 入库记录。 + * @param {Object} ctx + * @param {Object} entryOrder 入库单实例 + * @param {Object} item { stock_id, quantity, inbound_type, remark } + * @return {Promise<{ok: boolean, log?: Object, error?: Object}>} + */ + async _addSingleItem(ctx, entryOrder, item, transaction) { + const stockId = Number(item.stock_id || 0); + const quantity = Number(item.quantity || 0); + const inboundType = String(item.inbound_type || '').trim().toLowerCase(); + const remark = item.remark ? String(item.remark).trim() : ''; + const spaceId = item.space_id ? Number(item.space_id) : null; + + if (!stockId) { + return { ok: false, error: { code: 400, message: 'items[].stock_id 必填' } }; + } + if (!quantity || quantity <= 0 || !Number.isFinite(quantity)) { + return { ok: false, error: { code: 400, message: 'items[].quantity 必须为正整数' } }; + } + if (![ 'import', 'pda' ].includes(inboundType)) { + return { ok: false, error: { code: 400, message: 'items[].inbound_type 必须为 import 或 pda' } }; + } + + // 查找入库单中该 stock_id 对应的所有明细,累加计划数量 + const entryItems = await ctx.model.EntryItems.findAll({ + where: { order_id: entryOrder.id, stock_id: stockId }, + ...(transaction ? { transaction } : {}), + }); + + if (!entryItems || entryItems.length === 0) { + return { ok: false, error: { code: 400, message: `入库单中不存在 stock_id=${stockId} 的商品` } }; + } + + const totalPlanQty = entryItems.reduce((sum, item) => sum + (Number(item.count) || 0), 0); + + // 计算该 stock_id 在该入库单下已有的导入/PDA 入库总量 + const logWhere = { entry_order_id: entryOrder.id, stock_id: stockId }; + const existingLogs = await ctx.model.InboundDirectLog.findAll({ + where: logWhere, + attributes: [ 'quantity' ], + raw: true, + ...(transaction ? { transaction } : {}), + }); + const existingTotal = existingLogs.reduce((sum, log) => sum + Number(log.quantity), 0); + + const newTotal = existingTotal + quantity; + + if (newTotal > totalPlanQty) { + return { + ok: false, + error: { + code: 400, + message: `入库数量超过计划:商品计划 ${totalPlanQty},已入库 ${existingTotal},本次 ${quantity},合计 ${newTotal}`, + data: { + stock_id: stockId, + plan_quantity: totalPlanQty, + existing_quantity: existingTotal, + requested_quantity: quantity, + exceeded_by: newTotal - totalPlanQty, + }, + }, + }; + } + + // 写入记录 + const createOpts = transaction ? { transaction } : {}; + const log = await ctx.model.InboundDirectLog.create({ + warehouse_id: entryOrder.warehouse_id, + store_id: entryOrder.store_id, + stock_id: stockId, + quantity, + inbound_type: inboundType, + entry_order_id: entryOrder.id, + entry_order_code: entryOrder.entry_order_code, + space_id: spaceId, + remark, + operator_id: ctx.user?.employees_id || ctx.user?.id || null, + operator_name: ctx.user?.employees_name || '', + created_at: new Date(), + }); + + return { + ok: true, + log: { + id: log.id, + stock_id: stockId, + quantity, + inbound_type: inboundType, + space_id: spaceId, + plan_quantity: totalPlanQty, + existing_before: existingTotal, + existing_after: newTotal, + remaining: Math.max(0, totalPlanQty - newTotal), + }, + }; + } + + /** + * 按商品增量添加导入/PDA 入库记录(支持单条和批量)。 + * + * 单条模式(兼容旧调用): + * { entry_order_code, stock_id, quantity, inbound_type, remark } + * + * 批量模式(推荐): + * { entry_order_code, items: [{ stock_id, quantity, inbound_type, remark }] } + * + * 批量模式下所有商品共享同一个入库单状态校验,任一商品校验失败整批拒绝。 + * 若该商品在当前入库单中的累计入库量超过计划数量则拒绝。 + * @param {Object} params + * @param {string} params.entry_order_code 入库单号 + * @param {number} [params.stock_id] 商品SKU ID(单条模式) + * @param {number} [params.quantity] 本次入库数量(单条模式) + * @param {string} [params.inbound_type] 入库方式(单条模式) + * @param {Array} [params.items] 商品列表(批量模式) + * @param {string} [params.remark] 备注(单条模式) + * @return {Promise} code/data/message 结构 + */ + async addItem(params) { + const { ctx } = this; + const entryOrderCode = String(params.entry_order_code || '').trim(); + + if (!entryOrderCode) { + return { code: 400, message: 'entry_order_code 必填', data: null }; + } + + // 判断批量/单条模式 + const isBatch = Array.isArray(params.items) && params.items.length > 0; + const items = isBatch ? params.items : [{ + stock_id: params.stock_id, + quantity: params.quantity, + inbound_type: params.inbound_type, + remark: params.remark, + }]; + + // 查找入库单 + const entryOrder = await ctx.model.EntryOrder.findOne({ + where: { + entry_order_code: entryOrderCode, + warehouse_id: ctx.user.store_id, + is_enabled: 1, + deleted_at: null, + }, + }); + + if (!entryOrder) { + return { code: 404, message: '入库单不存在或无权访问', data: null }; + } + + // 检查入库单状态 + if (entryOrder.order_status === 'CANCELLED') { + return { code: 400, message: '已作废入库单不允许操作', data: null }; + } + if (entryOrder.order_status === 'COMPLETED') { + return { code: 400, message: '已完成的入库单不允许操作', data: null }; + } + + // 批量模式下用事务包裹,任一失败整批回退 + const useTransaction = isBatch; + const txn = useTransaction ? await ctx.model.transaction() : null; + + try { + const results = []; + for (const item of items) { + const result = await this._addSingleItem(ctx, entryOrder, item, txn); + if (!result.ok) { + if (txn) await txn.rollback(); + return result.error; + } + results.push(result.log); + } + + if (txn) await txn.commit(); + + // 非阻塞记录操作日志(批量模式只记一条汇总) + if (results.length > 0) { + const totalQty = results.reduce((s, r) => s + r.quantity, 0); + const types = [ ...new Set(results.map(r => r.inbound_type)) ].join(','); + setImmediate(() => { + ctx.service.systems.operationLog.createOperationLog({ + businessType: 'entry_order', + businessId: entryOrder.id, + operationCode: 'DIRECT_INBOUND_ADD', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: entryOrder.warehouse_id, + message: `导入/PDA入库添加 ${results.length} 种商品,总数量 ${totalQty},方式 ${types}`, + }, + }).catch(err => { + ctx.logger.error(`[InboundDirectLog] 记录操作日志失败: ${err.message}`); + }); + }); + } + + if (!isBatch) { + const r = results[0]; + return { + code: 200, + message: '添加成功', + data: { ...r }, + }; + } + + return { + code: 200, + message: `添加成功,共 ${results.length} 项`, + data: { + count: results.length, + total_quantity: results.reduce((s, r) => s + r.quantity, 0), + items: results, + }, + }; + } catch (error) { + if (txn && typeof txn.rollback === 'function') { + await txn.rollback(); + } + throw error; + } + } + + /** + * 移除一条导入/PDA 入库记录(仅限未提交的入库单)。 + * @param {Object} params + * @param {number} params.id 入库记录ID(wms_inbound_direct_log.id) + * @return {Promise} code/data/message 结构 + */ + async removeItem(params) { + const { ctx } = this; + const logId = Number(params.id || 0); + + if (!logId) { + return { code: 400, message: 'id 必填', data: null }; + } + + const log = await ctx.model.InboundDirectLog.findByPk(logId); + if (!log) { + return { code: 404, message: '入库记录不存在', data: null }; + } + + // 检查所属入库单状态 + const entryOrder = await ctx.model.EntryOrder.findOne({ + where: { + id: log.entry_order_id, + warehouse_id: ctx.user.store_id, + is_enabled: 1, + deleted_at: null, + }, + }); + + if (!entryOrder) { + return { code: 404, message: '关联入库单不存在或无权访问', data: null }; + } + + if (entryOrder.order_status === 'CANCELLED') { + return { code: 400, message: '已作废入库单不允许操作', data: null }; + } + if (entryOrder.order_status === 'COMPLETED') { + return { code: 400, message: '已完成的入库单不允许移除记录', data: null }; + } + + // 软删除该记录 + await log.destroy(); + + // 非阻塞记录操作日志 + setImmediate(() => { + ctx.service.systems.operationLog.createOperationLog({ + businessType: 'entry_order', + businessId: entryOrder.id, + operationCode: 'DIRECT_INBOUND_REMOVE', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: entryOrder.warehouse_id, + message: `移除导入/PDA入库记录 id=${logId},stock_id=${log.stock_id},数量 ${log.quantity},方式 ${log.inbound_type}`, + }, + }).catch(err => { + ctx.logger.error(`[InboundDirectLog] 记录操作日志失败: ${err.message}`); + }); + }); + + return { + code: 200, + message: '移除成功', + data: { + id: logId, + stock_id: log.stock_id, + quantity: log.quantity, + inbound_type: log.inbound_type, + }, + }; + } + + /** + * 提交确认完成入库,将导入/PDA 入库记录写入库存,并触发奇门/API 回传。 + * @param {string} entryOrderCode 入库单号 + * @return {Promise} code/data/message 结构 + */ + async commit(entryOrderCode) { + const { ctx, app } = this; + const code = String(entryOrderCode || '').trim(); + + if (!code) { + return { code: 400, message: 'entry_order_code 必填', data: null }; + } + + const entryOrder = await ctx.model.EntryOrder.findOne({ + where: { + entry_order_code: code, + warehouse_id: ctx.user.store_id, + is_enabled: 1, + deleted_at: null, + }, + }); + + if (!entryOrder) { + return { code: 404, message: '入库单不存在或无权访问', data: null }; + } + + if (entryOrder.order_status === 'CANCELLED') { + return { code: 400, message: '已作废入库单不允许完成', data: null }; + } + if (entryOrder.order_status === 'COMPLETED') { + return { code: 400, message: '入库单已完成,请勿重复提交', data: null }; + } + + // 查询该入库单下所有导入/PDA 入库记录 + const directLogs = await ctx.model.InboundDirectLog.findAll({ + where: { entry_order_id: entryOrder.id }, + }); + + if (!directLogs || directLogs.length === 0) { + return { code: 400, message: '暂无导入/PDA 入库记录,请先添加商品', data: null }; + } + + // 按 stock_id 汇总入库数量 + const stockSummary = {}; + for (const log of directLogs) { + const key = String(log.stock_id); + if (!stockSummary[key]) stockSummary[key] = 0; + stockSummary[key] += Number(log.quantity); + } + + // 查询入库单所有明细 + const entryItems = await ctx.model.EntryItems.findAll({ + where: { order_id: entryOrder.id }, + }); + + if (!entryItems.length) { + return { code: 400, message: '入库单无明细', data: null }; + } + + const warehouseId = entryOrder.warehouse_id; + const storeId = entryOrder.store_id; + const transaction = await ctx.model.transaction(); + + try { + // 记录已处理过的 stock_id,避免同 stock_id 多明细重复写库存 + const processedStockIds = new Set(); + + // 逐商品写入库存 + for (const item of entryItems) { + const stockId = item.stock_id; + if (!stockId) continue; + + const inboundQty = stockSummary[String(stockId)] || 0; + if (inboundQty <= 0) continue; + + // 更新入库明细的 received_quantity(按该明细的计划占比分配) + const planQty = Number(item.count) || 0; + const itemReceivedQty = planQty > 0 ? Math.min(planQty, inboundQty) : inboundQty; + await ctx.model.EntryItems.update({ + received_quantity: itemReceivedQty, + }, { + where: { id: item.id }, + transaction, + }); + + // 同一 stock_id 只写一次库存 + if (processedStockIds.has(String(stockId))) continue; + processedStockIds.add(String(stockId)); + + // 使用入库单号作为批次号 + const batchNo = entryOrder.entry_order_code; + const inventoryType = item.inventory_type || 'ZP'; + + // 从该 stock_id 的入库记录中取第一个非空 space_id,兜底 1 + const logForSpace = directLogs.find(l => String(l.stock_id) === String(stockId) && l.space_id); + const spaceId = logForSpace ? Number(logForSpace.space_id) : 1; + + // 锁定并更新 StockWarehouse 总库存 + const stockRecord = await ctx.model.StockWarehouse.findOne({ + where: { id: stockId, is_valid: 'Y', deleted_at: null }, + lock: transaction.LOCK.UPDATE, + transaction, + }); + + if (stockRecord) { + const beforeQuantity = Number(stockRecord.quantity) || 0; + const beforeLockedQuantity = Number(stockRecord.locked_quantity) || 0; + + await stockRecord.increment('quantity', { by: inboundQty, transaction, silent: true }); + await stockRecord.reload({ transaction }); + + const afterQuantity = Number(stockRecord.quantity) || 0; + const afterLockedQuantity = Number(stockRecord.locked_quantity) || 0; + + // 写入库存流水 + await ctx.service.systems.stockTransaction.create({ + transaction_type: 'INBOUND', + warehouse_id: warehouseId, + store_id: storeId, + stock_id: stockId, + quantity: inboundQty, + batch_no: batchNo, + inventory_type: inventoryType, + order_type: entryOrder.order_type, + order_no: entryOrder.entry_order_code, + entry_order_id: entryOrder.id, + operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), + operator_name: ctx.user?.employees_name || '', + remark: '导入/PDA直接入库提交', + before_quantity: beforeQuantity, + after_quantity: afterQuantity, + before_locked_quantity: beforeLockedQuantity, + after_locked_quantity: afterLockedQuantity, + created_at: new Date(), + }, { transaction }); + } + + // 创建/更新 Storage 库位库存 + const storageRecord = await ctx.model.Storage.findOne({ + where: { + space_id: spaceId, + stock_id: stockId, + batch_no: batchNo, + inventory_type: inventoryType, + is_enabled: 1, + delete_at: null, + }, + lock: transaction.LOCK.UPDATE, + transaction, + }); + + if (storageRecord) { + await ctx.model.Storage.update({ + quantity: app.Sequelize.literal(`quantity + ${inboundQty}`), + available_quantity: app.Sequelize.literal(`available_quantity + ${inboundQty}`), + entry_order_id: entryOrder.id, + inbound_time: new Date(), + inbound_order_no: entryOrder.entry_order_code, + updated_at: new Date(), + }, { + where: { id: storageRecord.id }, + transaction, + }); + } else { + await ctx.model.Storage.create({ + warehouse_id: warehouseId, + store_id: storeId, + space_id: spaceId, + stock_id: stockId, + batch_no: batchNo, + inventory_type: inventoryType, + quantity: inboundQty, + locked_quantity: 0, + available_quantity: inboundQty, + inbound_time: new Date(), + inbound_order_no: entryOrder.entry_order_code, + receiving_id: null, + entry_order_id: entryOrder.id, + supplier_id: null, + supplier_batch_no: null, + is_enabled: 1, + created_at: new Date(), + updated_at: new Date(), + }, { transaction }); + } + } + + // 更新入库单状态为 COMPLETED + await entryOrder.update({ + order_status: 'COMPLETED', + sync_status: 'SUCCESS', + sync_message: JSON.stringify({ + completedAt: new Date(), + totalQuantity: Object.values(stockSummary).reduce((s, q) => s + q, 0), + itemCount: processedStockIds.size, + source: 'direct_inbound', + }), + updated_at: new Date(), + }, { transaction }); + + // 记录操作日志(事务内) + const totalQty = Object.values(stockSummary).reduce((s, q) => s + q, 0); + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'entry_order', + businessId: entryOrder.id, + operationCode: 'DIRECT_INBOUND_COMMIT', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: entryOrder.warehouse_id, + message: `导入/PDA入库提交完成,共 ${processedStockIds.size} 种商品,总数量 ${totalQty}`, + }, + transaction, + }); + + await transaction.commit(); + } catch (error) { + if (transaction && typeof transaction.rollback === 'function') { + await transaction.rollback(); + } + throw error; + } + + // 事务外:异步触发奇门/API 回传 + setImmediate(() => { + this._sendCallback(entryOrder).catch(err => { + ctx.logger.error(`[InboundDirectLog] 回传异常 entryOrderId=${entryOrder.id}: ${err.message}`, err.stack); + }); + }); + + return { + code: 200, + message: '入库完成', + data: { + id: entryOrder.id, + entry_order_code: entryOrder.entry_order_code, + order_status: 'COMPLETED', + sync_status: 'SUCCESS', + items_count: entryItems.length, + total_quantity: Object.values(stockSummary).reduce((s, q) => s + q, 0), + }, + }; + } + + /** + * 根据入库单来源异步回传(奇门 / OpenAPI)。 + * @param {Object} entryOrder 入库单实例 + * @return {Promise} + */ + async _sendCallback(entryOrder) { + const { ctx } = this; + const sourceType = String(entryOrder.source_type || '').toUpperCase(); + + ctx.logger.info( + `[InboundDirectLog] 准备回传 entryOrderId=${entryOrder.id} sourceType=${sourceType}` + ); + + try { + const items = await ctx.model.EntryItems.findAll({ + where: { order_id: entryOrder.id }, + attributes: [ 'item_code', 'item_id', 'count', 'inventory_type', 'owner_code', 'received_quantity' ], + raw: true, + }); + + if (!items || items.length === 0) { + ctx.logger.warn(`[InboundDirectLog] 回传:入库单无明细 entryOrderId=${entryOrder.id}`); + return; + } + + const orderLines = items.map((item, index) => ({ + orderLineNo: index + 1, + ownerCode: item.owner_code || '', + itemCode: item.item_code || '', + itemId: item.item_id || '', + inventoryType: item.inventory_type || 'ZP', + planQty: item.count || 0, + actualQty: item.received_quantity || 0, + })); + + if (sourceType === 'QM') { + await this._sendQimenCallback(entryOrder, orderLines); + } else if (sourceType === 'API') { + await this._sendOpenApiCallback(entryOrder); + } else { + ctx.logger.info(`[InboundDirectLog] 来源类型 ${sourceType} 不支持回传`); + } + } catch (error) { + ctx.logger.error(`[InboundDirectLog] _sendCallback 异常: ${error.message}`, error.stack); + } + } + + /** + * 奇门回传:调用 taobao.qimen.entryorder.confirm。 + * @param {Object} entryOrder 入库单 + * @param {Array} orderLines 明细行 + * @return {Promise} + */ + async _sendQimenCallback(entryOrder, orderLines) { + const { ctx, app } = this; + + try { + const queryData = { + request: { + entryOrder: { + entryOrderCode: entryOrder.entry_order_code, + ownerCode: entryOrder.qimen_owner_code || '', + warehouseCode: entryOrder.qimen_warehouse_code || '', + entryOrderId: entryOrder.id, + entryOrderType: entryOrder.order_type, + outBizCode: `DIRECT_INBOUND_${Date.now()}`, + confirmType: 0, + status: 'FULFILLED', + freight: 0, + operateTime: app.formatDate(new Date()), + remark: '导入/PDA直接入库提交', + }, + orderLines, + }, + }; + + const result = await app.qimenClient.send( + 'taobao.qimen.entryorder.confirm', + entryOrder.qimen_owner_code, + queryData, + { ctx } + ); + + const qimenResult = result && result.xmlArray && result.xmlArray.response; + if (qimenResult && String(qimenResult.flag) === 'success') { + ctx.logger.info(`[InboundDirectLog] 奇门回传成功 entryOrderId=${entryOrder.id}`); + } else { + ctx.logger.warn( + `[InboundDirectLog] 奇门回传失败 entryOrderId=${entryOrder.id} ` + + `message=${qimenResult?.message || '未知错误'}` + ); + } + } catch (error) { + ctx.logger.error(`[InboundDirectLog] 奇门回传异常: ${error.message}`, error.stack); + } + } + + /** + * OpenAPI 回传:查询 ApiApp 回调地址并 POST 回传。 + * @param {Object} entryOrder 入库单 + * @return {Promise} + */ + async _sendOpenApiCallback(entryOrder) { + const { ctx, app } = this; + + try { + const storeWarehouse = await ctx.model.StoreWarehouse.findOne({ + where: { + store_id: entryOrder.store_id, + warehouse_id: entryOrder.warehouse_id, + auth_status: 2, + }, + attributes: [ 'id' ], + raw: true, + }); + + if (!storeWarehouse) { + ctx.logger.warn( + '[InboundDirectLog] OpenAPI回传:未找到授权关系 ' + + `entryOrderId=${entryOrder.id}` + ); + return; + } + + const apiApp = await ctx.model.ApiApp.findOne({ + where: { + contract_id: storeWarehouse.id, + is_enabled: 1, + callback_url: { + [ app.Sequelize.Op.and ]: [ + { [ app.Sequelize.Op.ne ]: null }, + { [ app.Sequelize.Op.ne ]: '' }, + ], + }, + }, + attributes: [ 'self_app_key', 'self_app_secret', 'callback_url' ], + raw: true, + }); + + if (!apiApp || !apiApp.callback_url) { + ctx.logger.warn( + '[InboundDirectLog] OpenAPI回传:未找到有效ApiApp配置 ' + + `entryOrderId=${entryOrder.id}` + ); + return; + } + + const callbackData = { + entryOrderId: entryOrder.id, + entryOrderCode: entryOrder.entry_order_code, + completedAt: new Date().toISOString(), + inboundType: 'direct', + }; + + const result = await ctx.service.openapi.callback.sendWithRetry({ + callbackUrl: apiApp.callback_url, + appKey: apiApp.self_app_key, + selfAppSecret: apiApp.self_app_secret || '', + event: 'entry_order_direct_inbound_completed', + data: callbackData, + metadata: { + source: 'inbound_direct_log', + entryOrderId: entryOrder.id, + }, + }); + + if (result.success) { + ctx.logger.info( + `[InboundDirectLog] OpenAPI回传成功 entryOrderId=${entryOrder.id} ` + + `callbackUrl=${apiApp.callback_url}` + ); + } else { + ctx.logger.warn( + `[InboundDirectLog] OpenAPI回传失败 entryOrderId=${entryOrder.id} ` + + `error=${result.error}` + ); + } + } catch (error) { + ctx.logger.error(`[InboundDirectLog] OpenAPI回传异常: ${error.message}`, error.stack); + } + } +} + +module.exports = InboundDirectLogService; diff --git a/app/service/systems/order_async.js b/app/service/systems/order_async.js index 86c5eba..ac6c97e 100644 --- a/app/service/systems/order_async.js +++ b/app/service/systems/order_async.js @@ -210,7 +210,7 @@ async function buildQimenDeliveryOrderConfirmDataInternal(service, orderRow, ord } orderLines.push({ - orderLineNo: orderLines.length + 1, + orderLineNo: String(orderItem.order_line_no || '').trim() || orderLines.length + 1, orderSourceCode: String(orderItem.source_order_code || '').trim(), subSourceCode: String(orderItem.sub_source_order_code || '').trim(), ownerCode: String(orderItem.owner_code || ownerCode || '').trim(), @@ -257,6 +257,13 @@ async function buildQimenDeliveryOrderConfirmDataInternal(service, orderRow, ord expressCode: String(expressCode || '').trim(), packageCode, invoiceNo, + items: Array.isArray(orderItems) ? orderItems + .filter(item => item && Number(item.plan_qty) > 0) + .map(item => ({ + itemCode: String(item.item_code || '').trim(), + itemId: Number(item.item_id) || String(item.item_id || '').trim(), + quantity: Number(item.plan_qty) || 0, + })) : [], })), }, orderLines, diff --git a/app/service/systems/order_export.js b/app/service/systems/order_export.js index 19be920..fad099a 100644 --- a/app/service/systems/order_export.js +++ b/app/service/systems/order_export.js @@ -23,11 +23,11 @@ const ORDER_EXPORT_MODULE_MAP = Object.freeze({ deliveryexpectionorder: 'deliveryExpectionOrder', }); const ORDER_EXPORT_COLUMNS = Object.freeze([ - { header: '订单ID', key: 'id', width: 12 }, - { header: '订单号', key: 'delivery_order_code', width: 24 }, - { header: '外部单号', key: 'external_order_code', width: 24 }, + { header: '系统订单号', key: 'id', width: 12 }, + { header: '外部订单号', key: 'delivery_order_code', width: 24 }, + { header: '平台单号', key: 'external_order_code', width: 24 }, { header: '订单状态', key: 'status', width: 16 }, - { header: '波次号', key: 'wave_no', width: 18 }, + { header: '抓取波次号', key: 'wave_no', width: 18 }, { header: '货主', key: 'store_id', width: 20 }, { header: '平台', key: 'sys_platform_name', width: 16 }, { header: '店铺昵称', key: 'shop_nick', width: 20 }, @@ -41,6 +41,11 @@ const ORDER_EXPORT_COLUMNS = Object.freeze([ { header: '商品明细', key: 'items_detail', width: 50 }, { header: '物流公司', key: 'logistics_name', width: 18 }, { header: '运单号', key: 'waybill_code', width: 24 }, + { header: '业务类型', key: 'business_type', width: 12 }, + { header: '运单接口', key: 'logistics_interface_name', width: 20 }, + { header: '包材ID', key: 'package_material_id', width: 14 }, + { header: '包材编码', key: 'package_material_code', width: 20 }, + { header: '包材名称', key: 'package_material_name', width: 20 }, { header: '分配时间', key: 'waybill_allocated_at', width: 20 }, { header: '商品种数', key: 'items_count', width: 12 }, { header: '商品件数', key: 'items_total', width: 12 }, @@ -81,6 +86,11 @@ const ORDER_EXPORT_ITEM_COLUMNS = Object.freeze([ { header: '数量', key: 'item_quantity', width: 10 }, { header: '物流公司', key: 'logistics_name', width: 18 }, { header: '运单号', key: 'waybill_code', width: 30 }, + { header: '业务类型', key: 'business_type', width: 12 }, + { header: '运单接口', key: 'logistics_interface_name', width: 20 }, + { header: '包材ID', key: 'package_material_id', width: 14 }, + { header: '包材编码', key: 'package_material_code', width: 20 }, + { header: '包材名称', key: 'package_material_name', width: 20 }, { header: '分配时间', key: 'waybill_allocated_at', width: 20 }, { header: '商品种数', key: 'items_count', width: 12 }, { header: '商品件数', key: 'items_total', width: 12 }, @@ -320,12 +330,13 @@ class OrderExportService extends OrderBaseService { * @param {Map} [context.stockNameMap] stockId → 仓库商品名称的映射。 * @param {Map} [context.barcodeMap] stockId → 商品条码(逗号拼接)的映射。 * @param {Map>} [context.expressMap] 订单ID → 运单行列表的映射。 + * @param {Map} [context.packageMaterialMap] package_material_id → 包材编码的映射。 * @param {string} [mode='waybill'] 导出模式:'waybill' 或 'item'。 * @return {Array} 导出行数组。 */ mapOrderExportRow(orderRow = {}, context = {}, mode = 'waybill') { const safeOrderRow = this.isPlainObject(orderRow) ? orderRow : {}; - const { itemsMap, storeRemarkMap, stockNameMap, barcodeMap, expressMap } = context; + const { itemsMap, storeRemarkMap, stockNameMap, barcodeMap, expressMap, packageMaterialMap } = context; const safeItemsMap = itemsMap instanceof Map ? itemsMap : new Map(); const safeStoreRemarkMap = storeRemarkMap instanceof Map ? storeRemarkMap : new Map(); const safeExpressMap = expressMap instanceof Map ? expressMap : new Map(); @@ -417,12 +428,24 @@ class OrderExportService extends OrderBaseService { const waybillFirstTime = expressList.length > 0 ? formatDateSafe(expressList[0].create_at) : ''; const weightSummary = expressList.reduce((sum, e) => sum + (Number(e.weighing_weight) || 0), 0); + const firstExp = expressList.length > 0 ? expressList[0] : null; + const businessType = firstExp ? (Number(firstExp.business_key) === 1 ? '主单号' : '子单号') : ''; + const interfaceName = firstExp ? String(firstExp.logistics_interface_name || '') : ''; + const materialId = firstExp ? (firstExp.package_material_id != null ? Number(firstExp.package_material_id) : '') : ''; + const safePackageMaterialMap = packageMaterialMap instanceof Map ? packageMaterialMap : new Map(); + const materialCode = materialId ? (safePackageMaterialMap.get(Number(materialId)) || '') : ''; + if (items.length === 0) { return [{ ...commonFields, item_name: '', item_barcode: '', item_quantity: '', + business_type: businessType, + logistics_interface_name: this.normalizeExportCellValue(interfaceName), + package_material_id: materialId, + package_material_code: this.normalizeExportCellValue(materialCode), + package_material_name: this.normalizeExportCellValue(firstExp ? firstExp.package_material_name_snapshot : ''), waybill_code: waybillSummary, waybill_allocated_at: waybillFirstTime, weighing_weight: weightSummary || '', @@ -436,6 +459,11 @@ class OrderExportService extends OrderBaseService { item_name: (sid > 0 ? safeStockNameMap.get(sid) : '') || item.item_name || '', item_barcode: sid > 0 ? (safeBarcodeMap.get(sid) || '') : '', item_quantity: item.plan_qty || 1, + business_type: businessType, + logistics_interface_name: this.normalizeExportCellValue(interfaceName), + package_material_id: materialId, + package_material_code: this.normalizeExportCellValue(materialCode), + package_material_name: this.normalizeExportCellValue(firstExp ? firstExp.package_material_name_snapshot : ''), waybill_code: waybillSummary, waybill_allocated_at: waybillFirstTime, weighing_weight: weightSummary || '', @@ -444,12 +472,19 @@ class OrderExportService extends OrderBaseService { } // ★ 模式A(默认 waybill):按运单展开,保留 items_detail + const safePackageMaterialMap = packageMaterialMap instanceof Map ? packageMaterialMap : new Map(); + if (expressList.length === 0) { // 无运单的订单也输出一行(运单字段为空) return [{ ...commonFields, items_detail: this.normalizeExportCellValue(itemsDetail), waybill_code: '', + business_type: '', + logistics_interface_name: '', + package_material_id: '', + package_material_code: '', + package_material_name: '', waybill_allocated_at: '', weighing_weight: '', }]; @@ -459,6 +494,13 @@ class OrderExportService extends OrderBaseService { ...commonFields, items_detail: this.normalizeExportCellValue(itemsDetail), waybill_code: exp.waybill_code || '', + business_type: Number(exp.business_key) === 1 ? '主单号' : '子单号', + logistics_interface_name: this.normalizeExportCellValue(exp.logistics_interface_name), + package_material_id: exp.package_material_id != null ? Number(exp.package_material_id) : '', + package_material_code: this.normalizeExportCellValue( + exp.package_material_id != null ? (safePackageMaterialMap.get(Number(exp.package_material_id)) || '') : '' + ), + package_material_name: this.normalizeExportCellValue(exp.package_material_name_snapshot), waybill_allocated_at: formatDateSafe(exp.create_at), weighing_weight: exp.weighing_weight != null ? Number(exp.weighing_weight) : '', })); @@ -722,7 +764,7 @@ class OrderExportService extends OrderBaseService { order_id: { [this.app.Sequelize.Op.in]: orderIds }, warehouse_id: warehouseId, }, - attributes: [ 'id', 'order_id', 'waybill_code', 'create_at', 'weighing_weight' ], + attributes: [ 'id', 'order_id', 'waybill_code', 'business_key', 'logistics_interface_name', 'package_material_id', 'package_material_name_snapshot', 'create_at', 'weighing_weight' ], order: [[ 'id', 'ASC' ]], raw: true, }); @@ -768,7 +810,37 @@ class OrderExportService extends OrderBaseService { } } - const exportContext = { itemsMap, storeRemarkMap, stockNameMap, barcodeMap, expressMap }; + // 批量查询包材编码(wms_package_material),按 package_material_id 分组 + const packageMaterialMap = new Map(); + if (expressMap.size > 0 && this.ctx && this.ctx.model && this.ctx.model.PackageMaterial) { + try { + const materialIds = [ + ...new Set( + [ ...expressMap.values() ] + .flat() + .map(exp => Number(exp.package_material_id || 0)) + .filter(id => id > 0) + ), + ]; + if (materialIds.length > 0) { + const pmRows = await this.ctx.model.PackageMaterial.findAll({ + where: { id: { [this.app.Sequelize.Op.in]: materialIds } }, + attributes: [ 'id', 'material_code' ], + raw: true, + }); + for (const pm of (Array.isArray(pmRows) ? pmRows : [])) { + const pid = Number(pm.id || 0); + if (pid > 0 && !packageMaterialMap.has(pid)) { + packageMaterialMap.set(pid, String(pm.material_code || '').trim()); + } + } + } + } catch (err) { + this.app.logger.warn(`[order_export] 批量查询包材编码失败: ${err.message}`); + } + } + + const exportContext = { itemsMap, storeRemarkMap, stockNameMap, barcodeMap, expressMap, packageMaterialMap }; for (const row of normalizedRows) { const exportRows = this.mapOrderExportRow(row, exportContext, mode); diff --git a/app/service/systems/order_express.js b/app/service/systems/order_express.js index f787f0b..15f0562 100644 --- a/app/service/systems/order_express.js +++ b/app/service/systems/order_express.js @@ -65,6 +65,21 @@ class OrderExpressService extends Service { return normalizedCode; } + /** + * 规范化并校验包材ID。 + * @param {number|string} packageMaterialId 包材ID。 + * @return {number} 合法包材ID。 + */ + normalizePackageMaterialId(packageMaterialId) { + const normalizedId = Number(packageMaterialId || 0); + + if (!Number.isFinite(normalizedId) || normalizedId <= 0) { + throw this.createBusinessError('参数错误', 400); + } + + return normalizedId; + } + /** * 规范化并校验绑定包材场景的订单ID。 * @param {number|string} orderId 订单ID。 @@ -92,6 +107,35 @@ class OrderExpressService extends Service { return warehouseId; } + /** + * 根据包材ID查询当前仓库启用中的包材。 + * @param {number} packageMaterialId 包材ID。 + * @param {number} warehouseId 仓库 ID。 + * @return {Promise} 包材记录。 + */ + async findActivePackageMaterialById(packageMaterialId, warehouseId) { + const packageMaterialModel = this.ctx.model && this.ctx.model.PackageMaterial; + if (!packageMaterialModel || typeof packageMaterialModel.findOne !== 'function') { + throw this.createBusinessError('包材模型未初始化', 500); + } + + const materialRow = await packageMaterialModel.findOne({ + where: { + warehouse_id: warehouseId, + id: packageMaterialId, + status: 1, + }, + attributes: [ 'id', 'material_code', 'material_name', 'warehouse_id', 'status' ], + raw: true, + }); + + if (!materialRow) { + throw this.createBusinessError('包材ID不存在', 404); + } + + return materialRow; + } + /** * 根据包材编码查询当前仓库启用中的包材。 * @param {string} packageMaterialCode 包材编码。 @@ -902,6 +946,57 @@ class OrderExpressService extends Service { type: this.ctx.model.QueryTypes.INSERT, } ); + + // 写入 order_operation_log + try { + const operationLogService = this.ctx + && this.ctx.service + && this.ctx.service.systems + && this.ctx.service.systems.operationLog; + if (operationLogService && typeof operationLogService.createOperationLogs === 'function') { + const logPayloads = []; + if (isBatch && waveId) { + logPayloads.push({ + businessType: 'order', + businessId: `wave_${waveId}`, + operationCode: 'ORDER_WEIGH', + operator: { id: String(operatorId || ''), name: operatorName }, + extras: { + message: `波次 ${waveNo || waveId} 批量称重 ${weight}g,成功 ${successCount}/${totalCount}`, + warehouseId, + waveId, + waveNo: waveNo || '', + weighingWeight: weight, + successCount, + totalCount, + }, + }); + } else if (orderId) { + logPayloads.push({ + businessType: 'order', + businessId: `${orderId}`, + operationCode: 'ORDER_WEIGH', + operator: { id: String(operatorId || ''), name: operatorName }, + extras: { + message: `订单称重 ${weight}g`, + warehouseId, + orderId, + waybillCode: waybillCode || '', + weighingWeight: weight, + }, + }); + } + if (logPayloads.length > 0) { + await operationLogService.createOperationLogs(logPayloads); + } + } + } catch (e) { + this.ctx.logger.warn('[order_express._writeWeighActionLog] 写入 operation_log 失败,不影响主流程', { + error: e && e.message, + waveId, + orderId, + }); + } } /** @@ -977,7 +1072,7 @@ class OrderExpressService extends Service { const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(warehouseId); const orderRow = await orderDeliveryModel.findOne({ where: { id: orderId, warehouse_id: warehouseId }, - attributes: ['items_hash', 'items_crc'], + attributes: [ 'items_hash', 'items_crc' ], raw: true, }); if (!orderRow || !orderRow.items_hash) return; @@ -1119,7 +1214,7 @@ class OrderExpressService extends Service { * 根据运单号绑定包材。 * * 仅凭运单号即可绑定包材,无需传入订单ID。 - * 先按运单号 + 仓库ID 查询有效运单记录,再按包材编码查询启用中的包材, + * 先按运单号 + 仓库ID 查询有效运单记录,再按包材ID查询启用中的包材, * 最后更新运单记录的包材字段。 * * 支持团购波次自动感知: @@ -1129,7 +1224,7 @@ class OrderExpressService extends Service { * * @param {Object} [payload={}] 请求参数。 * @param {string} payload.waybillCode 运单号。 - * @param {string} payload.packageMaterialCode 包材编码。 + * @param {number|string} payload.packageMaterialId 包材ID。 * @return {Promise} 单条绑定返回 {order_id, waybill_code, package_material_id, package_material_name_snapshot, package_material_code}; * 团购批量绑定返回 {wave_id, wave_no, business_key, order_id, waybill_code, package_material_id, package_material_code, package_material_name_snapshot, bind_count, bound_waybills, store_name, sys_logistics_name}。 */ @@ -1137,11 +1232,11 @@ class OrderExpressService extends Service { const requestData = payload && typeof payload === 'object' ? payload : {}; const { waybillCode, - packageMaterialCode, + packageMaterialId, } = requestData; const normalizedWaybillCode = this.normalizeWaybillCode(waybillCode); - const normalizedPackageMaterialCode = this.normalizePackageMaterialCode(packageMaterialCode); + const normalizedPackageMaterialId = this.normalizePackageMaterialId(packageMaterialId); const warehouseId = this.getCurrentWarehouseId(); // 按运单号 + 仓库ID 查询有效运单记录 @@ -1156,7 +1251,7 @@ class OrderExpressService extends Service { warehouse_id: warehouseId, delete_at: null, }, - attributes: ['id', 'order_id', 'waybill_code', 'warehouse_id', 'delete_at', 'package_material_id', 'business_key'], + attributes: [ 'id', 'order_id', 'waybill_code', 'warehouse_id', 'delete_at', 'package_material_id', 'business_key' ], raw: true, }); @@ -1165,7 +1260,7 @@ class OrderExpressService extends Service { } // 查询启用中的包材 - const materialRow = await this.findActivePackageMaterialByCode(normalizedPackageMaterialCode, warehouseId); + const materialRow = await this.findActivePackageMaterialById(normalizedPackageMaterialId, warehouseId); // --- 团购波次自动感知 --- // 尝试查询运单所属订单是否属于团购波次 @@ -1175,7 +1270,7 @@ class OrderExpressService extends Service { const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(warehouseId); const orderRow = await orderDeliveryModel.findOne({ where: { id: Number(orderExpressRow.order_id), warehouse_id: warehouseId }, - attributes: ['id', 'wave_id', 'wave_no'], + attributes: [ 'id', 'wave_id', 'wave_no' ], raw: true, }); @@ -1188,7 +1283,7 @@ class OrderExpressService extends Service { if (waveBatchModel && typeof waveBatchModel.findOne === 'function') { const waveRow = await waveBatchModel.findOne({ where: { wave_id: waveId, warehouse_id: warehouseId }, - attributes: ['wave_id', 'wave_no', 'wave_type'], + attributes: [ 'wave_id', 'wave_no', 'wave_type' ], raw: true, }); @@ -1199,7 +1294,7 @@ class OrderExpressService extends Service { waveNo: String(waveRow.wave_no || ''), businessKey: orderExpressRow.business_key ?? null, packageMaterialId: Number(materialRow.id), - packageMaterialCode: normalizedPackageMaterialCode, + packageMaterialCode: String(materialRow.material_code || '').trim(), packageMaterialName: String(materialRow.material_name || '').trim(), warehouseId, triggerOrderId: Number(orderExpressRow.order_id), @@ -1271,6 +1366,35 @@ class OrderExpressService extends Service { warehouseId, }); + // 写入包材绑定操作日志(单条绑定) + try { + const ctxUser = this.ctx && this.ctx.user ? this.ctx.user : {}; + const operatorId = Number(ctxUser.employees_id || ctxUser.id || 0); + const operatorName = String(ctxUser.employees_name || ctxUser.name || 'system').trim() || 'system'; + const opLogService = this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.operationLog; + if (opLogService && typeof opLogService.createOperationLogs === 'function') { + await opLogService.createOperationLogs([{ + businessType: 'order', + businessId: `${Number(orderExpressRow.order_id || 0)}`, + operationCode: 'ORDER_PACKAGE_MATERIAL_BIND', + operator: { id: String(operatorId || ''), name: operatorName }, + extras: { + message: `订单绑定包材 ${String(materialRow.material_name || materialRow.material_code || '').trim()}`, + warehouseId, + orderId: Number(orderExpressRow.order_id || 0), + waybillCode: normalizedWaybillCode, + packageMaterialId: Number(materialRow.id), + packageMaterialName: String(materialRow.material_name || '').trim(), + }, + }]); + } + } catch (e) { + this.ctx.logger.warn('[order_express._bindSingleExpressPackageMaterial] 写入 operation_log 失败', { + error: e && e.message, + orderId: Number(orderExpressRow.order_id || 0), + }); + } + return { order_id: Number(orderExpressRow.order_id), waybill_code: String(orderExpressRow.waybill_code || '').trim(), @@ -1318,7 +1442,7 @@ class OrderExpressService extends Service { const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(warehouseId); const waveOrders = await orderDeliveryModel.findAll({ where: { wave_id: waveId, warehouse_id: warehouseId }, - attributes: ['id'], + attributes: [ 'id' ], raw: true, }); @@ -1346,7 +1470,7 @@ class OrderExpressService extends Service { business_key: businessKeyWhere, delete_at: null, }, - attributes: ['id', 'order_id', 'waybill_code', 'business_key', 'package_material_id'], + attributes: [ 'id', 'order_id', 'waybill_code', 'business_key', 'package_material_id' ], raw: true, }); @@ -1354,7 +1478,7 @@ class OrderExpressService extends Service { // 波次下无同 business_key 运单 → 降级为仅绑定触发运单 const orderExpressRow = await orderExpressModel.findOne({ where: { waybill_code: triggerWaybillCode, warehouse_id: warehouseId, delete_at: null }, - attributes: ['id', 'order_id', 'waybill_code', 'package_material_id'], + attributes: [ 'id', 'order_id', 'waybill_code', 'package_material_id' ], raw: true, }); if (!orderExpressRow) { @@ -1540,6 +1664,37 @@ class OrderExpressService extends Service { type: this.ctx.model.QueryTypes.INSERT, } ); + + // 写入 order_operation_log + try { + const operationLogService = this.ctx + && this.ctx.service + && this.ctx.service.systems + && this.ctx.service.systems.operationLog; + if (operationLogService && typeof operationLogService.createOperationLogs === 'function') { + await operationLogService.createOperationLogs([{ + businessType: 'order', + businessId: `wave_${waveId}`, + operationCode: 'ORDER_PACKAGE_MATERIAL_BIND', + operator: { id: String(operatorId || ''), name: operatorName }, + extras: { + message: `波次 ${waveNo || waveId} 绑定包材 ${packageMaterialName || packageMaterialCode},绑定量 ${bindCount}`, + warehouseId, + waveId, + waveNo: waveNo || '', + packageMaterialCode, + packageMaterialName, + bindCount, + businessKey, + }, + }]); + } + } catch (e) { + this.ctx.logger.warn('[order_express._writePackageMaterialActionLog] 写入 operation_log 失败,不影响主流程', { + error: e && e.message, + waveId, + }); + } } } diff --git a/app/service/systems/order_print.js b/app/service/systems/order_print.js index 4665302..dc9e44c 100644 --- a/app/service/systems/order_print.js +++ b/app/service/systems/order_print.js @@ -433,6 +433,11 @@ class OrderPrintSystemService extends OrderBaseService { } const mergedPrintItems = Array.from(aggregatedMap.values()); + // 为聚合后的商品行添加序号(从 1 开始) + for (let i = 0; i < mergedPrintItems.length; i++) { + mergedPrintItems[i].seq_no = i + 1; + } + resultMap.set(orderId, { ...orderRow, items: JSON.stringify(mergedPrintItems), diff --git a/app/service/systems/order_storage_allocation.js b/app/service/systems/order_storage_allocation.js index a8681a7..dd9028d 100644 --- a/app/service/systems/order_storage_allocation.js +++ b/app/service/systems/order_storage_allocation.js @@ -1109,6 +1109,35 @@ class OrderStorageAllocationService extends MainService { await ctx.service.systems.storage.index.unlockQuantity( storageRow.id, allocationQuantity, { transaction } ); + + // 回退 stockAllocationMap 和 storageAllocationMap 中的累加值,防止 wms_stock_warehouse.locked_quantity 批量更新时多锁 + const prevStockQty = stockAllocationMap.get(stockId) || 0; + const newStockQty = prevStockQty - allocationQuantity; + if (newStockQty <= 0) { + stockAllocationMap.delete(stockId); + } else { + stockAllocationMap.set(stockId, newStockQty); + } + + const prevStorageQty = storageAllocationMap.get(storageRow.id) || 0; + const newStorageQty = prevStorageQty - allocationQuantity; + if (newStorageQty <= 0) { + storageAllocationMap.delete(storageRow.id); + } else { + storageAllocationMap.set(storageRow.id, newStorageQty); + } + + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 库位无效,回退库存主表锁定累加', { + orderId, + stockId, + storageId: storageRow.id, + allocationQuantity, + prevStockQty, + newStockQty, + prevStorageQty, + newStorageQty, + }); + continue; } @@ -1159,7 +1188,7 @@ class OrderStorageAllocationService extends MainService { const spaceErrorMessage = storageRowErrors.length > 0 && shortageMessage ? `库位未设置(storage_id:${storageRowErrors.map(e => e.storage_id).join(',')})` : ''; - const finalShortageMessage = [shortageMessage, spaceErrorMessage].filter(Boolean).join('|'); + const finalShortageMessage = [ shortageMessage, spaceErrorMessage ].filter(Boolean).join('|'); writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 订单缺货信息汇总', { orderId, @@ -1829,6 +1858,50 @@ class OrderStorageAllocationService extends MainService { }); } + // 写入 ORDER_SYNC 操作日志(所有请求的订单,含跳过/失败) + try { + const opLogService = this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.operationLog; + if (opLogService && typeof opLogService.createOperationLogs === 'function') { + const channelNames = createChannelGroups.map(g => g.create_channel).join('/') || 'unknown'; + const operatorId = ctx.user?.employees_id ?? ctx.user?.id ?? null; + const operatorName = ctx.user?.employees_name ?? ctx.user?.real_name ?? ctx.user?.name ?? 'system'; + const logItems = orderIds.map(orderId => { + const isPending = syncableOrderIds.includes(orderId); + const skipped = skippedOrders.find(s => Number(s.order_id) === orderId); + const failed = fastFailedOrders.find(f => Number(f.order_id) === orderId); + let msg; + if (isPending) msg = `同步到${channelNames}渠道`; + else if (failed) { + const reasonMap = { 'express_unallocated': '快递未分配', 'sn_batch_forbidden': 'SN订单不支持批量' }; + msg = `同步跳过:${reasonMap[failed.failed_reason] || failed.failed_reason || failed.message || '条件不满足'}`; + } + else if (skipped) { + const skipReasonMap = { 'already_synced': '已同步', 'not_found': '订单不存在' }; + msg = `同步跳过:${skipReasonMap[skipped.skipped_reason] || skipped.skipped_reason || '已同步'}`; + } + else msg = `同步跳过`; + return { + businessType: 'order', + businessId: `${orderId}`, + operationCode: 'ORDER_SYNC', + operator: { id: operatorId, name: operatorName }, + extras: { + message: msg, + warehouseId, + externalLogType: 'NONE', + }, + }; + }); + await opLogService.createOperationLogs(logItems); + } + } catch (e) { + ctx.logger.warn('[OrderStorageAllocationService.syncOrderIds] 写入 ORDER_SYNC 操作日志失败', { + error: e && e.message, + warehouseId, + orderIds, + }); + } + const responseData = { warehouse_id: warehouseId, requested_order_ids: orderIds, @@ -2291,6 +2364,21 @@ class OrderStorageAllocationService extends MainService { throw error; } } + /** + * 分拣缺货补货需求计算。 + * + * 仓库级别的计算,针对当前仓库所有未完成储位分配的订单, + * 计算每个 SKU 在分拣区与存货区的可用库存对比, + * 输出分拣区缺口及建议补货量,供仓库人员决策移库。 + * + * 入参: + * - `warehouse_id`(可选):仓库 ID,不传则使用当前用户上下文 + * + * @param {Object} data 请求体。 + * @return {Promise} 补货需求明细与汇总信息。 + * `list` 每项包含 `is_true_shortage`(两区均无库存时为 true), + * `summary` 包含 `total_true_shortage_skus`(真正缺货的 SKU 数量)。 + */ } module.exports = OrderStorageAllocationService; diff --git a/app/service/systems/pick.js b/app/service/systems/pick.js index ef9c6a5..9d6fc5f 100644 --- a/app/service/systems/pick.js +++ b/app/service/systems/pick.js @@ -1809,21 +1809,7 @@ class PickSystemService extends Service { hooks: false, }); - // 更新 wms_picking.status 为完成状态 - await ctx.model.query(` - UPDATE wms_picking - SET status = 'fin', updated_at = NOW() - WHERE order_id IN (:orderIds) - AND warehouse_id = :warehouseId - `, { - replacements: { - orderIds: targetOrderIds, - warehouseId, - }, - transaction, - }); - - // 从 wms_picking 汇总各 storage_id 的 quantity,扣减 wms_storage 的锁定数量与可用数量 + // 先查询并锁定 pending 的 picking 记录,汇总各 storage_id 的扣减量 const pickingSummaryRows = await ctx.model.query(` SELECT p.storage_id, @@ -1831,9 +1817,12 @@ class PickSystemService extends Service { FROM wms_picking p WHERE p.order_id IN (:orderIds) AND p.warehouse_id = :warehouseId + AND p.status = 'pending' + AND p.deleted_at IS NULL -- 排除软删除记录,防止已删除的 picking 纳入锁定量汇总 AND p.storage_id IS NOT NULL AND p.storage_id > 0 GROUP BY p.storage_id + FOR UPDATE `, { replacements: { orderIds: targetOrderIds, @@ -1932,92 +1921,24 @@ class PickSystemService extends Service { await ctx.model.StorageTransaction.bulkCreate(transactionRows, { transaction }); } - // 释放 wms_stock_warehouse 锁定数量并写入 wms_stock_transaction 出库流水 - const stockQtyMap = new Map(); - for (const sRow of storageRows) { - const sid = Number(sRow.stock_id); - if (!sid || sid <= 0) continue; - const deduction = storageQtyMap.get(Number(sRow.id)) || 0; - if (deduction <= 0) continue; - stockQtyMap.set(sid, (stockQtyMap.get(sid) || 0) + deduction); - } - - if (stockQtyMap.size > 0) { - const stockIds = Array.from(stockQtyMap.keys()); - const stockWarehouseRows = await ctx.model.StockWarehouse.findAll({ - where: { - id: { [this.app.Sequelize.Op.in]: stockIds }, - warehouse_id: warehouseId, - }, - attributes: [ 'id', 'quantity', 'locked_quantity' ], - lock: transaction.LOCK.UPDATE, - raw: true, - transaction, - }); - - const stockWarehouseMap = new Map(); - for (const swRow of stockWarehouseRows) { - stockWarehouseMap.set(Number(swRow.id), swRow); - } - - for (const [ stockId, qty ] of stockQtyMap) { - const swRow = stockWarehouseMap.get(stockId); - if (!swRow) { - ctx.logger.warn(`[pick] stock_warehouse 记录不存在: ${stockId}`); - continue; - } - const currentLocked = Number(swRow.locked_quantity) || 0; - if (currentLocked < qty) { - throw this.createBusinessError( - `货主库存 ${stockId} 锁定数量不足:当前锁定 ${currentLocked},需释放 ${qty}`, - 400 - ); - } - await ctx.model.StockWarehouse.update({ - locked_quantity: this.app.Sequelize.literal(`locked_quantity - ${qty}`), - update_at: this.app.Sequelize.literal('CURRENT_TIMESTAMP'), - }, { - where: { - id: stockId, - locked_quantity: { [this.app.Sequelize.Op.gte]: qty }, - }, - transaction, - }); - } - - const stockTransactionRows = []; - for (const [ stockId, qty ] of stockQtyMap) { - const swRow = stockWarehouseMap.get(stockId); - if (!swRow) continue; - const sRow = storageRows.find(r => Number(r.stock_id) === stockId); - const beforeQty = Number(swRow.quantity) || 0; - const beforeLocked = Number(swRow.locked_quantity) || 0; - stockTransactionRows.push({ - transaction_type: 'OUTBOUND', - warehouse_id: warehouseId, - store_id: sRow ? Number(sRow.store_id) || 0 : 0, - stock_id: stockId, - quantity: qty, - before_quantity: beforeQty, - after_quantity: Math.max(0, beforeQty - qty), - before_locked_quantity: beforeLocked, - after_locked_quantity: Math.max(0, beforeLocked - qty), - order_type: 'PICK_OUTBOUND', - order_no: targetOrderIds.join(',').slice(0, 255), - order_id: taskId, - operator_id: String(operatorId), - operator_name: operatorName, - remark: '拣货完成出库-货主库存释放', - created_at: new Date(), - }); - } - - if (stockTransactionRows.length > 0) { - await ctx.model.StockTransaction.bulkCreate(stockTransactionRows, { transaction }); - } - } } + // 扣减完成后,更新 wms_picking.status 为完成状态(加 status 条件防重复) + await ctx.model.query(` + UPDATE wms_picking + SET status = 'fin', updated_at = NOW() + WHERE order_id IN (:orderIds) + AND warehouse_id = :warehouseId + AND status = 'pending' + AND deleted_at IS NULL -- 排除软删除记录,防止重复标记已完成删除的 picking + `, { + replacements: { + orderIds: targetOrderIds, + warehouseId, + }, + transaction, + }); + const progress = await this.getTaskPickProgress(taskId, warehouseId, transaction); if (mode === 1 || progress.isCompleted) { await ctx.model.query(` @@ -2035,6 +1956,24 @@ class PickSystemService extends Service { }, transaction, }); + + // 同步更新波次关联状态为已拣 + const taskWaveColumnSet = await this.getTableColumnSet('wms_wave_pick_task_wave'); + const taskWaveWarehouseFilterSql = taskWaveColumnSet.has('warehouse_id') ? ' AND warehouse_id = :warehouseId' : ''; + await ctx.model.query(` + UPDATE wms_wave_pick_task_wave + SET status = 1, + pick_time = NOW(), + update_time = NOW() + WHERE task_id = :taskId + ${taskWaveWarehouseFilterSql} + `, { + replacements: { + taskId, + warehouseId, + }, + transaction, + }); } else { await ctx.model.query(` UPDATE wms_wave_pick_task @@ -2066,6 +2005,36 @@ class PickSystemService extends Service { progress, }); + // 写入 order_operation_log 拣货完成日志 + try { + const operationLogService = this.ctx + && this.ctx.service + && this.ctx.service.systems + && this.ctx.service.systems.operationLog; + if (operationLogService && typeof operationLogService.createOperationLogs === 'function') { + const logPayloads = targetOrderIds.map(orderId => ({ + businessType: 'order', + businessId: `${orderId}`, + operationCode: 'ORDER_PICK_COMPLETE', + operator: { + id: operatorId ? String(operatorId) : null, + name: operatorName || 'system', + }, + extras: { + message: `订单${orderId}拣货完成`, + warehouseId, + externalLogType: 'PDA', + }, + })); + await operationLogService.createOperationLogs(logPayloads); + } + } catch (e) { + this.ctx.logger.warn('[pick.wavePickTaskComplete] 写入 order_operation_log 失败,不影响主流程', { + error: e && e.message, + targetOrderIds, + }); + } + return { task_id: taskId, mode, @@ -2289,7 +2258,7 @@ class PickSystemService extends Service { : null; const bindingTaskId = Number(activeBinding && activeBinding.task_id || 0); const bindingTaskStatus = Number(activeBinding && activeBinding.task_status || 0); - if (bindingTaskId > 0 && bindingTaskId !== taskId && [ 0, 1, 2 ].includes(bindingTaskStatus)) { + if (bindingTaskId > 0 && bindingTaskId !== taskId && [ 0, 1 ].includes(bindingTaskStatus)) { throw this.createBusinessError('该拣货车已绑定其他活动任务,无法重复绑定', 409, { task_id: bindingTaskId, task_no: String(activeBinding && activeBinding.task_no || '').trim() || null, diff --git a/app/service/systems/pick_compensation.js b/app/service/systems/pick_compensation.js index 9a1f4ad..787c8da 100644 --- a/app/service/systems/pick_compensation.js +++ b/app/service/systems/pick_compensation.js @@ -314,9 +314,7 @@ class PickCompensationService extends MainService { * 2. SELECT wms_storage FOR UPDATE * 3. 校验 locked_quantity >= 解锁数量 * 4. UPDATE wms_storage 只解锁 locked_quantity(不扣减 quantity) - * 5. 按 stock_id 汇总,UPDATE wms_stock_warehouse 释放 locked_quantity(仅解锁,不扣减 quantity) - * 6. INSERT wms_stock_transaction(OUTBOUND, quantity=0, 仅记录锁定释放) - * 7. UPDATE wms_picking SET status='cancelled_released' + * 5. UPDATE wms_picking SET status='cancelled_released' * * @param {number} warehouseId 仓库ID。 * @param {Array} cancelledPickingRows 已取消订单关联的拣货记录列表。 @@ -417,95 +415,6 @@ class PickCompensationService extends MainService { transaction, }); - // 释放 wms_stock_warehouse 锁定数量(仅解锁,不扣减 quantity)并写入 wms_stock_transaction 流水 - const stockQtyMap = new Map(); - for (const sRow of storageRows) { - const sid = Number(sRow.stock_id); - if (!sid || sid <= 0) continue; - const deduction = storageQtyMap.get(Number(sRow.id)) || 0; - if (deduction <= 0) continue; - stockQtyMap.set(sid, (stockQtyMap.get(sid) || 0) + deduction); - } - - if (stockQtyMap.size > 0) { - const stockIds = Array.from(stockQtyMap.keys()); - const stockWarehouseRows = await ctx.model.StockWarehouse.findAll({ - where: { - id: { [app.Sequelize.Op.in]: stockIds }, - warehouse_id: warehouseId, - }, - attributes: [ 'id', 'quantity', 'locked_quantity' ], - lock: transaction.LOCK.UPDATE, - raw: true, - transaction, - }); - - const stockWarehouseMap = new Map(); - for (const swRow of stockWarehouseRows) { - stockWarehouseMap.set(Number(swRow.id), swRow); - } - - for (const [ stockId, qty ] of stockQtyMap) { - const swRow = stockWarehouseMap.get(stockId); - if (!swRow) { - ctx.logger.warn(`[pick-compensation-cancel] stock_warehouse 记录不存在: ${stockId}`); - continue; - } - const currentLocked = Number(swRow.locked_quantity) || 0; - if (currentLocked < qty) { - throw this.createBusinessError( - `货主库存 ${stockId} 锁定数量不足:当前锁定 ${currentLocked},需释放 ${qty}`, - 400 - ); - } - await ctx.model.StockWarehouse.update({ - locked_quantity: app.Sequelize.literal(`locked_quantity - ${qty}`), - update_at: app.Sequelize.literal('CURRENT_TIMESTAMP'), - }, { - where: { - id: stockId, - locked_quantity: { [app.Sequelize.Op.gte]: qty }, - }, - transaction, - }); - } - - const stockTransactionRows = []; - for (const [ stockId, qty ] of stockQtyMap) { - const swRow = stockWarehouseMap.get(stockId); - if (!swRow) continue; - const sRow = storageRows.find(r => Number(r.stock_id) === stockId); - const currentQty = Number(swRow.quantity) || 0; - const currentLocked = Number(swRow.locked_quantity) || 0; - stockTransactionRows.push({ - transaction_type: 'OUTBOUND', - warehouse_id: warehouseId, - store_id: sRow ? Number(sRow.store_id) || 0 : 0, - stock_id: stockId, - quantity: 0, - before_quantity: currentQty, - after_quantity: currentQty, - before_locked_quantity: currentLocked, - after_locked_quantity: Math.max(0, currentLocked - qty), - order_type: 'PICK_CANCEL_RELEASE', - order_no: normalizedConfirmedRows - .filter(r => Number(r.stock_id) === stockId) - .map(r => String(r.order_id)) - .join(',') - .slice(0, 255), - order_id: 0, - operator_id: 'system', - operator_name: 'system', - remark: '拣货取消-货主库存锁定释放', - created_at: new Date(), - }); - } - - if (stockTransactionRows.length > 0) { - await ctx.model.StockTransaction.bulkCreate(stockTransactionRows, { transaction }); - } - } - // Step 5: UPDATE wms_picking SET status='cancelled_released' const compensatedPickingIds = normalizedConfirmedRows.map(r => Number(r.id)); await ctx.model.query(` @@ -543,9 +452,7 @@ class PickCompensationService extends MainService { * 5. 查询 dispatch 表获取订单的 delivery_order_code 和 source_order_codes, * 为每个拣货记录 INSERT 一条 wms_storage_transaction(OUTBOUND, PICK_COMPENSATION), * 同一 storage 的多条记录共享相同的 before/after 数量 - * 6. 按 stock_id 汇总,UPDATE wms_stock_warehouse 释放 locked_quantity - * 7. INSERT wms_stock_transaction(OUTBOUND)记录货主库存变更 - * 8. UPDATE wms_picking SET status='fin_compensated' + * 6. UPDATE wms_picking SET status='fin_compensated' * * @param {number} warehouseId 仓库ID。 * @param {Array} pickingRows 待补偿的拣货记录列表。 @@ -742,91 +649,6 @@ class PickCompensationService extends MainService { await ctx.model.StorageTransaction.bulkCreate(transactionRows, { transaction }); } - // 释放 wms_stock_warehouse 锁定数量并写入 wms_stock_transaction 出库流水 - const stockQtyMap = new Map(); - for (const sRow of storageRows) { - const sid = Number(sRow.stock_id); - if (!sid || sid <= 0) continue; - const deduction = storageQtyMap.get(Number(sRow.id)) || 0; - if (deduction <= 0) continue; - stockQtyMap.set(sid, (stockQtyMap.get(sid) || 0) + deduction); - } - - if (stockQtyMap.size > 0) { - const stockIds = Array.from(stockQtyMap.keys()); - const stockWarehouseRows = await ctx.model.StockWarehouse.findAll({ - where: { - id: { [app.Sequelize.Op.in]: stockIds }, - warehouse_id: warehouseId, - }, - attributes: [ 'id', 'quantity', 'locked_quantity' ], - lock: transaction.LOCK.UPDATE, - raw: true, - transaction, - }); - - const stockWarehouseMap = new Map(); - for (const swRow of stockWarehouseRows) { - stockWarehouseMap.set(Number(swRow.id), swRow); - } - - for (const [ stockId, qty ] of stockQtyMap) { - const swRow = stockWarehouseMap.get(stockId); - if (!swRow) { - ctx.logger.warn(`[pick-compensation] stock_warehouse 记录不存在: ${stockId}`); - continue; - } - const currentLocked = Number(swRow.locked_quantity) || 0; - if (currentLocked < qty) { - throw this.createBusinessError( - `货主库存 ${stockId} 锁定数量不足:当前锁定 ${currentLocked},需释放 ${qty}`, - 400 - ); - } - await ctx.model.StockWarehouse.update({ - locked_quantity: app.Sequelize.literal(`locked_quantity - ${qty}`), - update_at: app.Sequelize.literal('CURRENT_TIMESTAMP'), - }, { - where: { - id: stockId, - locked_quantity: { [app.Sequelize.Op.gte]: qty }, - }, - transaction, - }); - } - - const stockTransactionRows = []; - for (const [ stockId, qty ] of stockQtyMap) { - const swRow = stockWarehouseMap.get(stockId); - if (!swRow) continue; - const sRow = storageRows.find(r => Number(r.stock_id) === stockId); - const beforeQty = Number(swRow.quantity) || 0; - const beforeLocked = Number(swRow.locked_quantity) || 0; - stockTransactionRows.push({ - transaction_type: 'OUTBOUND', - warehouse_id: warehouseId, - store_id: sRow ? Number(sRow.store_id) || 0 : 0, - stock_id: stockId, - quantity: qty, - before_quantity: beforeQty, - after_quantity: Math.max(0, beforeQty - qty), - before_locked_quantity: beforeLocked, - after_locked_quantity: Math.max(0, beforeLocked - qty), - order_type: COMPENSATION_ORDER_TYPE, - order_no: confirmedOrderIds.join(',').slice(0, 255), - order_id: confirmedOrderIds[0] || 0, - operator_id: 'system', - operator_name: 'system', - remark: '拣货完成补偿出库-货主库存释放', - created_at: new Date(), - }); - } - - if (stockTransactionRows.length > 0) { - await ctx.model.StockTransaction.bulkCreate(stockTransactionRows, { transaction }); - } - } - // Step 6: UPDATE wms_picking SET status='fin_compensated' const compensatedPickingIds = normalizedConfirmedRows.map(r => Number(r.id)); await ctx.model.query(` diff --git a/app/service/systems/receiving_entry_match.js b/app/service/systems/receiving_entry_match.js new file mode 100644 index 0000000..269dab3 --- /dev/null +++ b/app/service/systems/receiving_entry_match.js @@ -0,0 +1,882 @@ +'use strict'; + +const Service = require('egg').Service; + +/** @type {number} 收货单缓存过期时间(秒) */ +const RECEIVING_CACHE_TTL = 300; + +/** @type {number} 收货单查询天数范围 */ +const RECEIVING_LOOKBACK_DAYS = 3; + +/** @type {string} 收货单列表缓存键前缀 */ +const RECEIVING_CACHE_KEY_PREFIX = 'cache:receiving_orders:warehouse:'; + +/** + * 入库单创建后异步匹配收货单并写入绑定关系服务。 + * + * 职责: + * 1. 缓存仓库下近 3 天的收货单列表(Redis,TTL 300s) + * 2. 根据入库单 remark 匹配收货单号 + * 3. 对比入库单明细与收货单明细(SKU + 数量) + * 4. 匹配成功后写入 wms_entry_order_receiving 绑定关系,CREATED 状态转 PENDING + * 5. 覆盖场景标记收货单为"部分入库" + */ +class ReceivingEntryMatchService extends Service { + + /** + * 入库单创建后的异步匹配入口:根据备注匹配收货单,写入绑定关系并在必要时转换状态。 + * 匹配到收货单后写入 wms_entry_order_receiving 绑定关系; + * 如果入库单当前状态为 CREATED,同步更新为 PENDING。 + * 不阻塞主流程,所有错误仅记录日志。 + * + * @param {number} entryOrderId 入库单 ID + * @return {Promise} + */ + async matchAfterEntryCompleted(entryOrderId) { + const { ctx } = this; + + try { + // 1. 加载入库单及其明细 + const entryOrder = await ctx.model.EntryOrder.findOne({ + where: { id: entryOrderId, is_enabled: 1, deleted_at: null }, + include: [{ + model: ctx.model.EntryItems, + as: 'items', + required: false, + attributes: [ 'id', 'item_code', 'stock_id', 'count', 'received_quantity', 'inventory_type' ], + }], + }); + + if (!entryOrder) { + ctx.logger.warn(`[ReceivingEntryMatch] 入库单不存在,跳过匹配 entryOrderId=${entryOrderId}`); + return; + } + + const remark = (entryOrder.remark || '').trim(); + if (!remark) { + ctx.logger.info(`[ReceivingEntryMatch] 入库单无备注,跳过匹配 entryOrderId=${entryOrderId}`); + return; + } + + const warehouseId = entryOrder.warehouse_id; + + // 2. 获取近 3 天的收货单列表(带缓存) + const receivingOrders = await this._getRecentReceivingOrders(warehouseId); + + if (!receivingOrders || receivingOrders.length === 0) { + ctx.logger.info(`[ReceivingEntryMatch] 仓库无近期收货单,跳过匹配 warehouseId=${warehouseId}`); + return; + } + + // 3. 从 remark 中提取可能匹配的收货单号 + const matchedReceiving = await this._findReceivingByRemark(remark, receivingOrders, warehouseId); + + if (!matchedReceiving) { + ctx.logger.info(`[ReceivingEntryMatch] remark 中未匹配到收货单号 entryOrderId=${entryOrderId} remark="${remark}"`); + return; + } + + ctx.logger.info( + `[ReceivingEntryMatch] 匹配到收货单 entryOrderId=${entryOrderId} ` + + `receivingId=${matchedReceiving.id} receivingNumber=${matchedReceiving.receiving_number}` + ); + + // 4. 对比明细 + const entryItems = (entryOrder.items || []).map(item => ({ + stockId: item.stock_id, + itemCode: item.item_code, + count: item.count || 0, + receivedQuantity: item.received_quantity || 0, + inventoryType: item.inventory_type || 'ZP', + })); + + const comparisonResult = this._compareDetails(entryItems, matchedReceiving.details || []); + + // 5. 根据对比结果写入绑定关系 + if (comparisonResult.type === 'full_match' || comparisonResult.type === 'receiving_covers_entry') { + // 匹配成功 → 写入 wms_entry_order_receiving 绑定关系 + await this._bindEntryOrderReceiving(entryOrderId, matchedReceiving.id); + + // 若入库单当前状态是 CREATED,更新为 PENDING + if (entryOrder.order_status === 'CREATED') { + await ctx.model.EntryOrder.update( + { order_status: 'PENDING', updated_at: new Date() }, + { where: { id: entryOrderId, order_status: 'CREATED' } } + ); + ctx.logger.info( + `[ReceivingEntryMatch] 入库单状态 CREATED → PENDING entryOrderId=${entryOrderId} ` + + `receivingId=${matchedReceiving.id}` + ); + } + + // receipting_covers_entry 场景额外标记收货单为部分入库 + if (comparisonResult.type === 'receiving_covers_entry') { + await this._markReceivingPartialStorage(matchedReceiving.id, comparisonResult, warehouseId); + } + } else { + // 其他情况(entry 有 receiving 没有的明细,或完全不匹配)→ 不做处理 + ctx.logger.info( + `[ReceivingEntryMatch] 明细对比结果为 ${comparisonResult.type},不触发绑定 ` + + `entryOrderId=${entryOrderId} receivingId=${matchedReceiving.id}` + ); + } + } catch (error) { + ctx.logger.error( + `[ReceivingEntryMatch] 异步匹配异常 entryOrderId=${entryOrderId}: ${error.message}`, + error.stack + ); + } + } + + /** + * 写入入库单与收货单的主表级绑定关系。 + * 使用 upsert 策略避免重复写入;绑定记录为软删除模型,已删除的历史记录会被恢复。 + * + * @param {number} entryOrderId 入库单 ID + * @param {number} receivingId 收货单 ID + * @return {Promise} + */ + async _bindEntryOrderReceiving(entryOrderId, receivingId) { + const { ctx } = this; + + try { + // 先检查是否已存在未删除的绑定记录 + const existing = await ctx.model.EntryOrderReceiving.findOne({ + where: { entry_order_id: entryOrderId, receiving_id: receivingId }, + paranoid: false, + }); + + if (existing) { + if (existing.deleted_at) { + // 已软删除的记录,恢复它 + await existing.restore(); + ctx.logger.info( + `[ReceivingEntryMatch] 恢复已删除的绑定关系 entryOrderId=${entryOrderId} receivingId=${receivingId}` + ); + } else { + ctx.logger.info( + `[ReceivingEntryMatch] 绑定关系已存在,跳过 entryOrderId=${entryOrderId} receivingId=${receivingId}` + ); + } + return; + } + + await ctx.model.EntryOrderReceiving.create({ + entry_order_id: entryOrderId, + receiving_id: receivingId, + }); + + ctx.logger.info( + `[ReceivingEntryMatch] 写入绑定关系成功 entryOrderId=${entryOrderId} receivingId=${receivingId}` + ); + } catch (error) { + // 唯一索引冲突时忽略(并发场景) + if (error.name === 'SequelizeUniqueConstraintError') { + ctx.logger.warn( + `[ReceivingEntryMatch] 绑定关系已存在(并发写入) entryOrderId=${entryOrderId} receivingId=${receivingId}` + ); + return; + } + ctx.logger.error( + `[ReceivingEntryMatch] 写入绑定关系失败 entryOrderId=${entryOrderId} receivingId=${receivingId}: ${error.message}`, + error.stack + ); + } + } + + /** + * 获取仓库近 3 天的收货单列表(优先从 Redis 缓存读取)。 + * + * @param {number} warehouseId 仓库 ID + * @return {Promise>} 收货单列表(含明细) + */ + async _getRecentReceivingOrders(warehouseId) { + const { ctx, app } = this; + const cacheKey = `${RECEIVING_CACHE_KEY_PREFIX}${warehouseId}`; + + try { + // 先尝试从缓存读取 + const cached = await app.getCacheAsync(cacheKey); + if (cached) { + ctx.logger.info(`[ReceivingEntryMatch] 命中收货单缓存 warehouseId=${warehouseId}`); + return cached; + } + } catch (cacheErr) { + ctx.logger.warn(`[ReceivingEntryMatch] 读取缓存失败,回退到数据库查询: ${cacheErr.message}`); + } + + // 缓存未命中,从数据库查询 + const threeDaysAgo = new Date(Date.now() - RECEIVING_LOOKBACK_DAYS * 24 * 60 * 60 * 1000); + + const receivingOrders = await ctx.model.Receiving.findAll({ + where: { + warehouse_id: warehouseId, + is_deleted: false, + status: [ 'receiving', 'completed' ], + created_at: { [app.Sequelize.Op.gte]: threeDaysAgo }, + }, + attributes: [ 'id', 'receiving_number', 'status', 'storage_status' ], + include: [{ + model: ctx.model.ReceivingDetail, + as: 'details', + required: false, + attributes: [ + 'id', 'system_product_id', 'product_name', 'actual_quantity', + 'storage_status', 'stored_quantity', + ], + }], + order: [[ 'created_at', 'DESC' ]], + }); + + const result = receivingOrders.map(order => { + const plain = typeof order.toJSON === 'function' ? order.toJSON() : order; + return { + id: plain.id, + receiving_number: plain.receiving_number, + status: plain.status, + storage_status: plain.storage_status, + details: (plain.details || []).map(d => ({ + id: d.id, + system_product_id: d.system_product_id, + product_name: d.product_name, + actual_quantity: d.actual_quantity, + storage_status: d.storage_status, + stored_quantity: d.stored_quantity || 0, + })), + }; + }); + + // 写入缓存 + try { + await app.setCacheAsync(cacheKey, result, RECEIVING_CACHE_TTL); + ctx.logger.info(`[ReceivingEntryMatch] 收货单缓存已写入 warehouseId=${warehouseId} count=${result.length}`); + } catch (cacheErr) { + ctx.logger.warn(`[ReceivingEntryMatch] 写入缓存失败: ${cacheErr.message}`); + } + + return result; + } + + /** + * 从入库单备注中查找匹配的收货单号。 + * 遍历缓存的收货单号列表,检查 remark 是否包含收货单号。 + * 若匹配到多个,返回最近创建的那一个。 + * + * @param {string} remark 入库单备注 + * @param {Array} receivingOrders 收货单列表 + * @param {number} warehouseId 仓库 ID + * @return {Promise} 匹配到的收货单(含明细),未匹配返回 null + */ + async _findReceivingByRemark(remark, receivingOrders, warehouseId) { + const { ctx } = this; + + // 按字符串包含匹配 + const matchedOrders = []; + for (const order of receivingOrders) { + if (remark.includes(order.receiving_number)) { + matchedOrders.push(order); + } + } + + if (matchedOrders.length === 0) { + return null; + } + + // 多个匹配时取第一个(列表已按 created_at DESC 排序,即最新) + const matched = matchedOrders[0]; + + // 如果缓存的收货单没有 details(可能为空),重新加载 + if (!matched.details || matched.details.length === 0) { + const fullOrder = await ctx.model.Receiving.findOne({ + where: { id: matched.id, warehouse_id: warehouseId }, + attributes: [ 'id', 'receiving_number', 'status', 'storage_status' ], + include: [{ + model: ctx.model.ReceivingDetail, + as: 'details', + required: false, + attributes: [ + 'id', 'system_product_id', 'product_name', 'actual_quantity', + 'storage_status', 'stored_quantity', + ], + }], + }); + + if (!fullOrder) return null; + + const plain = typeof fullOrder.toJSON === 'function' ? fullOrder.toJSON() : fullOrder; + return { + id: plain.id, + receiving_number: plain.receiving_number, + status: plain.status, + storage_status: plain.storage_status, + details: (plain.details || []).map(d => ({ + id: d.id, + system_product_id: d.system_product_id, + product_name: d.product_name, + actual_quantity: d.actual_quantity, + storage_status: d.storage_status, + stored_quantity: d.stored_quantity || 0, + })), + }; + } + + return matched; + } + + /** + * 对比入库单明细与收货单明细。 + * + * 判断规则: + * - full_match:两者 SKU 与数量完全一致 + * - receiving_covers_entry:收货单包含入库单所有明细(SKU 匹配), + * 且收货单至少有一个 SKU 数量多于入库单 + * - entry_exceeds_receiving:入库单有收货单没有的 SKU 或数量超出 + * - no_match:SKU 完全没有交集 + * + * @param {Array} entryItems 入库单明细 [{ stockId, itemCode, count, receivedQuantity, inventoryType }] + * @param {Array} receivingDetails 收货单明细 [{ id, system_product_id, actual_quantity, ... }] + * @return {{ type: string, matchedDetails?: Array, uncoveredDetails?: Array, overageDetails?: Array }} 对比结果对象 + */ + _compareDetails(entryItems, receivingDetails) { + // 构建收货单明细 Map:system_product_id → { actual_quantity, ... } + const receivingMap = new Map(); + for (const detail of receivingDetails) { + const productId = detail.system_product_id; + if (!productId) continue; + const existing = receivingMap.get(productId); + if (existing) { + existing.actual_quantity += (detail.actual_quantity || 0); + } else { + receivingMap.set(productId, { + detailId: detail.id, + system_product_id: productId, + actual_quantity: detail.actual_quantity || 0, + stored_quantity: detail.stored_quantity || 0, + }); + } + } + + // 构建入库单明细 Map:stock_id → { count, receivedQuantity } + const entryMap = new Map(); + for (const item of entryItems) { + const stockId = item.stockId; + if (!stockId) continue; + const existing = entryMap.get(stockId); + if (existing) { + existing.count += (item.count || 0); + existing.receivedQuantity += (item.receivedQuantity || 0); + } else { + entryMap.set(stockId, { + stockId, + itemCode: item.itemCode, + count: item.count || 0, + receivedQuantity: item.receivedQuantity || 0, + inventoryType: item.inventoryType, + }); + } + } + + if (entryMap.size === 0 || receivingMap.size === 0) { + return { type: 'no_match' }; + } + + // 检查入库单每个 SKU 是否在收货单中且数量 ≤ 收货单数量 + let allEntryItemsCovered = true; + let hasReceivingOverage = false; + const matchedDetails = []; // 匹配到的收货单明细 + const uncoveredDetails = []; // 入库单中有但收货单没有/不足的 + + for (const [ stockId, entryItem ] of entryMap) { + const receivingItem = receivingMap.get(stockId); + + if (!receivingItem) { + // 入库单有,收货单没有 → 入库单超出 + allEntryItemsCovered = false; + uncoveredDetails.push({ + stockId, + itemCode: entryItem.itemCode, + entryCount: entryItem.count, + receivingCount: 0, + reason: 'missing_in_receiving', + }); + continue; + } + + if (entryItem.count > receivingItem.actual_quantity) { + // 入库单数量 > 收货单数量 → 入库单超出 + allEntryItemsCovered = false; + uncoveredDetails.push({ + stockId, + itemCode: entryItem.itemCode, + entryCount: entryItem.count, + receivingCount: receivingItem.actual_quantity, + reason: 'entry_exceeds_receiving', + }); + } else if (entryItem.count < receivingItem.actual_quantity) { + // 收货单数量 > 入库单数量 → 存在覆盖余量 + hasReceivingOverage = true; + matchedDetails.push({ + ...receivingItem, + entryCount: entryItem.count, + overage: receivingItem.actual_quantity - entryItem.count, + }); + } else { + // 数量完全相等 + matchedDetails.push({ + ...receivingItem, + entryCount: entryItem.count, + overage: 0, + }); + } + } + + // 检查收货单是否有入库单没有的 SKU + const receivingOnlyItems = []; + for (const [ productId ] of receivingMap) { + if (!entryMap.has(productId)) { + receivingOnlyItems.push(productId); + } + } + + if (!allEntryItemsCovered) { + return { + type: 'entry_exceeds_receiving', + uncoveredDetails, + receivingOnlyItems, + }; + } + + if (hasReceivingOverage || receivingOnlyItems.length > 0) { + return { + type: 'receiving_covers_entry', + matchedDetails, + overageDetails: matchedDetails.filter(d => d.overage > 0), + receivingOnlyItems, + }; + } + + // 所有入库单 SKU 都在收货单中,且数量完全相等,且收货单无额外 SKU + return { + type: 'full_match', + matchedDetails, + }; + } + + /** + * 根据入库单来源发送回传。 + * - QM(奇门)→ 调用奇门入库单确认接口回传 + * - API(OpenAPI)→ 查询 ApiApp 回调地址并 POST 回传 + * + * @param {Object} entryOrder 入库单实例 + * @param {Object} receivingOrder 匹配到的收货单 + * @param {string} [matchType='auto_match'] 匹配类型标识,手动匹配时传入 'manual_match' + * @return {Promise<{success: boolean, sourceType: string, detail: Object}>} 回传结果 + */ + async _sendCallback(entryOrder, receivingOrder, matchType = 'auto_match') { + const { ctx } = this; + const sourceType = String(entryOrder.source_type || '').toUpperCase(); + + ctx.logger.info( + `[ReceivingEntryMatch] 准备回传 entryOrderId=${entryOrder.id} ` + + `sourceType=${sourceType} receivingNumber=${receivingOrder.receiving_number}` + ); + + if (sourceType === 'QM') { + const detail = await this._sendQimenCallback(entryOrder, receivingOrder); + return { success: detail.success, sourceType, detail }; + } else if (sourceType === 'API') { + const detail = await this._sendOpenApiCallback(entryOrder, receivingOrder, matchType); + return { success: detail.success, sourceType, detail }; + } + + ctx.logger.info( + `[ReceivingEntryMatch] 来源类型 ${sourceType} 不支持回传 entryOrderId=${entryOrder.id}` + ); + return { success: false, sourceType, detail: { success: false, error: `来源类型 ${sourceType} 不支持回传` } }; + } + + /** + * 奇门回传:复用现有奇门入库单确认接口。 + * + * @param {Object} entryOrder 入库单实例 + * @param {Object} receivingOrder 匹配到的收货单 + * @return {Promise<{success: boolean, error?: string}>} 回传结果 + */ + async _sendQimenCallback(entryOrder, receivingOrder) { + const { ctx, app } = this; + + try { + // 重新加载入库单明细 + const items = await ctx.model.EntryItems.findAll({ + where: { order_id: entryOrder.id }, + attributes: [ 'item_code', 'item_id', 'count', 'inventory_type', 'owner_code', 'received_quantity' ], + raw: true, + }); + + if (!items || items.length === 0) { + ctx.logger.warn(`[ReceivingEntryMatch] 奇门回传:入库单无明细 entryOrderId=${entryOrder.id}`); + return { success: false, error: '入库单无明细' }; + } + + const orderLines = items.map((item, index) => ({ + orderLineNo: index + 1, + ownerCode: item.owner_code || '', + itemCode: item.item_code || '', + itemId: item.item_id || '', + inventoryType: item.inventory_type || 'ZP', + planQty: item.count || 0, + actualQty: item.received_quantity || 0, + })); + + const queryData = { + request: { + entryOrder: { + entryOrderCode: entryOrder.entry_order_code, + ownerCode: entryOrder.qimen_owner_code || '', + warehouseCode: entryOrder.qimen_warehouse_code || '', + entryOrderId: entryOrder.id, + entryOrderType: entryOrder.order_type, + outBizCode: `RECEIVING_MATCH_${Date.now()}`, + confirmType: 0, // 0 = 最终确认 + status: 'FULFILLED', + freight: 0, + operateTime: app.formatDate(new Date()), + remark: `匹配收货单${receivingOrder.receiving_number}自动回传`, + }, + orderLines, + }, + }; + + const result = await app.qimenClient.send( + 'taobao.qimen.entryorder.confirm', + entryOrder.qimen_owner_code, + queryData, + { ctx } + ); + + const qimenResult = result && result.xmlArray && result.xmlArray.response; + if (qimenResult && String(qimenResult.flag) === 'success') { + ctx.logger.info( + `[ReceivingEntryMatch] 奇门回传成功 entryOrderId=${entryOrder.id} ` + + `receivingNumber=${receivingOrder.receiving_number}` + ); + return { success: true }; + } + ctx.logger.warn( + `[ReceivingEntryMatch] 奇门回传失败 entryOrderId=${entryOrder.id} ` + + `message=${qimenResult?.message || '未知错误'}` + ); + return { success: false, error: qimenResult?.message || '未知错误' }; + } catch (error) { + ctx.logger.error( + `[ReceivingEntryMatch] 奇门回传异常 entryOrderId=${entryOrder.id}: ${error.message}`, + error.stack + ); + return { success: false, error: error.message }; + } + } + + /** + * OpenAPI 回传:查询 ApiApp 回调地址,通过签名鉴权 POST 回传。 + * + * @param {Object} entryOrder 入库单实例 + * @param {Object} receivingOrder 匹配到的收货单 + * @param {string} [matchType='auto_match'] 匹配类型标识 + * @return {Promise<{success: boolean, error?: string, retryCount?: number}>} 回传结果 + */ + async _sendOpenApiCallback(entryOrder, receivingOrder, matchType = 'auto_match') { + const { ctx, app } = this; + + try { + // 通过 store_warehouse 查找 ApiApp + const storeWarehouse = await ctx.model.StoreWarehouse.findOne({ + where: { + store_id: entryOrder.store_id, + warehouse_id: entryOrder.warehouse_id, + auth_status: 2, // 已通过 + }, + attributes: [ 'id' ], + raw: true, + }); + + if (!storeWarehouse) { + ctx.logger.warn( + '[ReceivingEntryMatch] OpenAPI回传:未找到授权关系 ' + + `entryOrderId=${entryOrder.id} storeId=${entryOrder.store_id} warehouseId=${entryOrder.warehouse_id}` + ); + return { success: false, error: '未找到授权关系' }; + } + + const apiApp = await ctx.model.ApiApp.findOne({ + where: { + contract_id: storeWarehouse.id, + is_enabled: 1, + callback_url: { + [ app.Sequelize.Op.and ]: [ + { [ app.Sequelize.Op.ne ]: null }, + { [ app.Sequelize.Op.ne ]: '' }, + ], + }, + }, + attributes: [ 'self_app_key', 'self_app_secret', 'callback_url' ], + raw: true, + }); + + if (!apiApp || !apiApp.callback_url) { + ctx.logger.warn( + '[ReceivingEntryMatch] OpenAPI回传:未找到有效ApiApp配置 ' + + `entryOrderId=${entryOrder.id} contractId=${storeWarehouse.id}` + ); + return { success: false, error: '未找到有效ApiApp配置' }; + } + + // 构建回传数据 + const callbackData = { + entryOrderId: entryOrder.id, + entryOrderCode: entryOrder.entry_order_code, + receivingNumber: receivingOrder.receiving_number, + receivingId: receivingOrder.id, + matchType, + completedAt: new Date().toISOString(), + }; + + // 使用 OpenAPI 回调服务发送 + const result = await ctx.service.openapi.callback.sendWithRetry({ + callbackUrl: apiApp.callback_url, + appKey: apiApp.self_app_key, + selfAppSecret: apiApp.self_app_secret || '', + event: 'entry_order_receiving_matched', + data: callbackData, + metadata: { + source: 'receiving_entry_match', + entryOrderId: entryOrder.id, + receivingId: receivingOrder.id, + }, + }); + + if (result.success) { + ctx.logger.info( + `[ReceivingEntryMatch] OpenAPI回传成功 entryOrderId=${entryOrder.id} ` + + `callbackUrl=${apiApp.callback_url} retryCount=${result.retryCount}` + ); + return { success: true, retryCount: result.retryCount }; + } + ctx.logger.warn( + `[ReceivingEntryMatch] OpenAPI回传失败 entryOrderId=${entryOrder.id} ` + + `error=${result.error} retryCount=${result.retryCount}` + ); + return { success: false, error: result.error, retryCount: result.retryCount }; + } catch (error) { + ctx.logger.error( + `[ReceivingEntryMatch] OpenAPI回传异常 entryOrderId=${entryOrder.id}: ${error.message}`, + error.stack + ); + return { success: false, error: error.message }; + } + } + + /** + * 标记收货单为"部分入库"。 + * 更新收货单 storage_status 为 'partial',并更新明细的 storage_status 和 stored_quantity。 + * + * @param {number} receivingId 收货单 ID + * @param {Object} comparisonResult 对比结果 + * @param {number} warehouseId 仓库 ID + * @return {Promise<{success: boolean, error?: string}>} 标记结果 + */ + async _markReceivingPartialStorage(receivingId, comparisonResult, warehouseId) { + const { ctx } = this; + + try { + const receiving = await ctx.model.Receiving.findOne({ + where: { id: receivingId, warehouse_id: warehouseId, is_deleted: false }, + }); + + if (!receiving) { + ctx.logger.warn(`[ReceivingEntryMatch] 标记部分入库:收货单不存在 receivingId=${receivingId}`); + return { success: false, error: '收货单不存在' }; + } + + // 更新收货单主表的入库状态 + await receiving.update({ + storage_status: 'partial', + updated_at: new Date(), + }); + + // 更新匹配到的明细:标记为"全部入库",stored_quantity = entryCount + if (comparisonResult.matchedDetails && comparisonResult.matchedDetails.length > 0) { + for (const matched of comparisonResult.matchedDetails) { + await ctx.model.ReceivingDetail.update( + { + storage_status: 'all', + stored_quantity: matched.entryCount || matched.actual_quantity || 0, + updated_at: new Date(), + }, + { where: { id: matched.detailId, receiving_id: receivingId } } + ); + } + } + + // 更新超量明细:标记为"部分入库",stored_quantity = entryCount + if (comparisonResult.overageDetails && comparisonResult.overageDetails.length > 0) { + for (const overage of comparisonResult.overageDetails) { + await ctx.model.ReceivingDetail.update( + { + storage_status: 'partial', + stored_quantity: overage.entryCount || 0, + updated_at: new Date(), + }, + { where: { id: overage.detailId, receiving_id: receivingId } } + ); + } + } + + ctx.logger.info( + `[ReceivingEntryMatch] 收货单已标记为部分入库 receivingId=${receivingId} ` + + `receivingNumber=${receiving.receiving_number}` + ); + return { success: true }; + } catch (error) { + ctx.logger.error( + `[ReceivingEntryMatch] 标记部分入库失败 receivingId=${receivingId}: ${error.message}`, + error.stack + ); + return { success: false, error: error.message }; + } + } + + /** + * 手动匹配入库单与收货单。 + * + * 同步执行明细对比并触发回传,返回结构化匹配结果。 + * 适用场景:运营人员手动指定收货单与入库单进行匹配并回传。 + * + * 匹配规则(复用 _compareDetails): + * - full_match:两者 SKU 与数量完全一致 → 按来源回传 + * - receiving_covers_entry:收货单覆盖入库单 → 回传 + 标记部分入库 + * - entry_exceeds_receiving / no_match → 仅返回对比结果,不触发回传 + * + * @param {number} receivingId 收货单 ID + * @param {number} entryOrderId 入库单 ID + * @return {Promise} 匹配结果对象 + * @return {string} return.matchType 匹配类型:full_match / receiving_covers_entry / entry_exceeds_receiving / no_match + * @return {Object} return.comparisonResult 明细对比结果 + * @return {boolean} return.callbackSent 是否已发送回传 + * @return {Object|null} return.callbackResult 回传结果(未发送时为 null) + * @return {boolean} return.partialStorageMarked 是否已标记部分入库 + * @return {Object} return.entryOrder 入库单摘要 + * @return {Object} return.receivingOrder 收货单摘要 + */ + async manualMatch(receivingId, entryOrderId) { + const { ctx } = this; + + // 1. 加载入库单及其明细 + const entryOrder = await ctx.model.EntryOrder.findOne({ + where: { id: entryOrderId, is_enabled: 1, deleted_at: null }, + include: [{ + model: ctx.model.EntryItems, + as: 'items', + required: false, + attributes: [ 'id', 'item_code', 'stock_id', 'count', 'received_quantity', 'inventory_type' ], + }], + }); + + if (!entryOrder) { + throw new Error(`入库单不存在:${entryOrderId}`); + } + + // 2. 加载收货单及其明细 + const receivingOrder = await ctx.model.Receiving.findOne({ + where: { id: receivingId, is_deleted: false }, + include: [{ + model: ctx.model.ReceivingDetail, + as: 'details', + required: false, + attributes: [ + 'id', 'system_product_id', 'product_name', 'actual_quantity', + 'storage_status', 'stored_quantity', + ], + }], + }); + + if (!receivingOrder) { + throw new Error(`收货单不存在:${receivingId}`); + } + + // 3. 校验同仓库 + if (entryOrder.warehouse_id !== receivingOrder.warehouse_id) { + throw new Error( + `入库单仓库(${entryOrder.warehouse_id})与收货单仓库(${receivingOrder.warehouse_id})不一致` + ); + } + + // 4. 构建入库单明细 + const entryItems = (entryOrder.items || []).map(item => ({ + stockId: item.stock_id, + itemCode: item.item_code, + count: item.count || 0, + receivedQuantity: item.received_quantity || 0, + inventoryType: item.inventory_type || 'ZP', + })); + + // 5. 构建收货单明细 + const receivingPlain = typeof receivingOrder.toJSON === 'function' + ? receivingOrder.toJSON() + : receivingOrder; + const receivingDetails = (receivingPlain.details || []).map(d => ({ + id: d.id, + system_product_id: d.system_product_id, + product_name: d.product_name, + actual_quantity: d.actual_quantity, + storage_status: d.storage_status, + stored_quantity: d.stored_quantity || 0, + })); + + // 6. 对比明细 + const comparisonResult = this._compareDetails(entryItems, receivingDetails); + + const result = { + matchType: comparisonResult.type, + comparisonResult, + callbackSent: false, + callbackResult: null, + partialStorageMarked: false, + entryOrder: { + id: entryOrder.id, + entry_order_code: entryOrder.entry_order_code, + source_type: entryOrder.source_type, + warehouse_id: entryOrder.warehouse_id, + status: entryOrder.status, + }, + receivingOrder: { + id: receivingOrder.id, + receiving_number: receivingOrder.receiving_number, + status: receivingOrder.status, + storage_status: receivingOrder.storage_status, + }, + }; + + // 7. 根据对比结果处理 + if (comparisonResult.type === 'full_match') { + const callbackResult = await this._sendCallback(entryOrder, receivingOrder, 'manual_match'); + result.callbackSent = true; + result.callbackResult = callbackResult; + } else if (comparisonResult.type === 'receiving_covers_entry') { + const callbackResult = await this._sendCallback(entryOrder, receivingOrder, 'manual_match'); + result.callbackSent = true; + result.callbackResult = callbackResult; + + const markResult = await this._markReceivingPartialStorage( + receivingOrder.id, + comparisonResult, + receivingOrder.warehouse_id + ); + result.partialStorageMarked = markResult.success; + } + // entry_exceeds_receiving / no_match → 不触发回传 + + return result; + } +} + +module.exports = ReceivingEntryMatchService; diff --git a/app/service/systems/setting/warehouse.js b/app/service/systems/setting/warehouse.js index f24e70f..e3a1f1d 100644 --- a/app/service/systems/setting/warehouse.js +++ b/app/service/systems/setting/warehouse.js @@ -138,6 +138,25 @@ const WAREHOUSE_SETTING_FIELDS = Object.freeze([ Object.freeze({ key: 'require_pick', name: '需已拣货', type: 'flag', required: false, description: '是否要求 pick_status=fin' }), ]), }), + Object.freeze({ + key: 'cutoff_order_enabled', + name: '启用截单', + type: 'flag', + default: 1, + required: false, + description: '启用后,当天订单创建时间超过截单时间,不再自动分配快递和储位,不再自动加团', + }), + Object.freeze({ + key: 'cutoff_order_time', + name: '截单时间', + type: 'string', + default: '18:00', + required: false, + maxLength: 5, + min: '12:00', + max: '23:59', + description: '截单时间,格式 HH:mm,如 18:00', + }), Object.freeze({ key: INTERNAL_WAVE_STRATEGY_VERSION_KEY, name: '仓库波次策略版本号', diff --git a/app/service/systems/stock_store.js b/app/service/systems/stock_store.js index b772bbd..4a19ad4 100644 --- a/app/service/systems/stock_store.js +++ b/app/service/systems/stock_store.js @@ -536,6 +536,62 @@ class stockStoreService extends Service { } } + /** + * 按货主和仓库获取签约策略配置(带缓存,用于锁外预取)。 + * + * @param {number} storeId 货主ID。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} { allowOversell: boolean, relation: Object|null } + */ + async getStoreWarehousePolicyByStoreAndWarehouse(storeId, warehouseId) { + const { ctx, app } = this; + const normalizedStoreId = Number(storeId || 0); + const normalizedWarehouseId = Number(warehouseId || 0); + + if (normalizedStoreId <= 0 || normalizedWarehouseId <= 0) { + return { allowOversell: false, relation: null }; + } + + const cacheKey = `sw_policy:${normalizedStoreId}:${normalizedWarehouseId}`; + + // 1. 先查缓存 + const cached = await app.getCacheAsync(cacheKey); + if (cached) { + return cached; + } + + // 2. 缓存未命中,查 DB(无事务) + const relation = await ctx.model.StoreWarehouse.findOne({ + where: { + store_id: normalizedStoreId, + warehouse_id: normalizedWarehouseId, + auth_status: 2, + use_status: 1, + }, + attributes: [ 'id', 'policy_config', 'auth_status', 'use_status' ], + raw: true, + }); + + if (!relation) { + const fallback = { allowOversell: false, relation: null }; + await app.setCacheAsync(cacheKey, fallback, 300); + return fallback; + } + + const storeWarehouseService = ctx.service && ctx.service.systems && ctx.service.systems.storeWarehouse; + const policyConfig = storeWarehouseService && typeof storeWarehouseService.getEffectivePolicyConfigByContractId === 'function' + ? await storeWarehouseService.getEffectivePolicyConfigByContractId(relation.id) + : null; + + const result = { + allowOversell: Number(policyConfig && policyConfig.allow_oversell) === 1, + relation, + }; + + await app.setCacheAsync(cacheKey, result, 300); + return result; + } + /** * 获取库存对应的货主-仓库签约策略配置。 * @@ -607,9 +663,10 @@ class stockStoreService extends Service { * @param {number|string} stockWarehouseId 库存主键。 * @param {number} quantity 锁定数量,负数表示释放。 * @param {Object|null} transaction 数据库事务。 + * @param {Object|null} [oversellConfig=null] 可选预取策略配置,用于避免锁内查DB。 * @return {Promise} 锁定结果。 */ - async lockItemStorages(stockWarehouseId, quantity, transaction) { + async lockItemStorages(stockWarehouseId, quantity, transaction, oversellConfig = null) { const { ctx, app, @@ -654,8 +711,14 @@ class stockStoreService extends Service { if (isLocking) { const availableQty = stockRecord.quantity - stockRecord.locked_quantity; if (availableQty < absQty) { - const policyConfig = await this.getStoreWarehousePolicyConfigByStockId(stockRecord, currentTransaction); - if (!policyConfig.allowOversell) { + // 优先使用外部预取的 oversellConfig,避免锁内查 DB + let allowOversell = oversellConfig ? oversellConfig.allowOversell : null; + if (allowOversell === null || allowOversell === undefined) { + // 回退:未预取时走原有查询(兼容其他调用方) + const policyConfig = await this.getStoreWarehousePolicyConfigByStockId(stockRecord, currentTransaction); + allowOversell = policyConfig.allowOversell; + } + if (!allowOversell) { return { success: false, error: `库存不足,可用 ${availableQty},需求 ${absQty}`, @@ -3033,6 +3096,14 @@ class stockStoreService extends Service { return { unique: false, isUnique: false, message: '商品编码检测失败' }; } } + /** + * 批量删除仓库商品资料(软删除)。 + * 删除前会校验:1) 是否存在库存;2) 是否被待处理订单(step 1/2/3 且未取消)引用。 + * 任一校验不通过的商品会被移入不可删除列表并返回原因。 + * @param {Object} data 请求参数 + * @param {Array} data.ids 待删除的商品ID列表 + * @return {Promise} 删除结果,含 deletedProducts、undeletableProducts、failedIds 及 summary + */ async handleBatchDelete(data) { const { ctx, app } = this; const { Op } = this.app.Sequelize || app.Sequelize; @@ -3061,7 +3132,7 @@ class stockStoreService extends Service { required: false, // 使用left join,因为可能没有库存记录 }, ], - attributes: [ 'id', 'item_name', 'quantity', 'return_quantity' ], + attributes: [ 'id', 'item_name', 'quantity', 'return_quantity', 'warehouse_id' ], }); if (products.length === 0) { @@ -3117,6 +3188,111 @@ class stockStoreService extends Service { }; } + // 2.5 检查待处理订单引用:step in [1,2,3] 且 status != 'cancel' 的订单引用了该商品时不允许删除 + const deletableIdSet = new Set(deletableProducts.map(p => p.id)); + // 构建 stockId → warehouseId 映射 + const stockWarehouseMap = new Map(); + for (const product of products) { + if (deletableIdSet.has(product.id)) { + stockWarehouseMap.set(product.id, Number(product.warehouse_id) || 0); + } + } + // 按仓库分组 + const warehouseStockMap = new Map(); + for (const [ stockId, warehouseId ] of stockWarehouseMap) { + if (!warehouseStockMap.has(warehouseId)) { + warehouseStockMap.set(warehouseId, []); + } + warehouseStockMap.get(warehouseId).push(stockId); + } + + const orderReferencedMap = new Map(); // stockId → pendingOrderCount + const orderItemsFactory = ctx.model && ctx.model.OrderItemsFactory; + const orderDeliveryFactory = ctx.model && ctx.model.OrderDeliveryFactory; + + if (orderItemsFactory && typeof orderItemsFactory.getCurrentModel === 'function' + && orderDeliveryFactory && typeof orderDeliveryFactory.getCurrentModel === 'function') { + for (const [ warehouseId, stockIds ] of warehouseStockMap) { + if (!warehouseId || stockIds.length === 0) continue; + + try { + const orderItemsModel = await orderItemsFactory.getCurrentModel(warehouseId); + const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(warehouseId); + + // 查询该仓库下引用了待删除商品的订单明细 + const orderItems = await orderItemsModel.findAll({ + where: { stock_id: { [Op.in]: stockIds } }, + attributes: [ 'stock_id', 'order_id' ], + raw: true, + }); + + if (orderItems.length === 0) continue; + + const orderIds = [ ...new Set(orderItems.map(oi => oi.order_id)) ]; + + // 查询这些订单中处于待处理状态(step 1/2/3 且未取消)的 + const pendingOrders = await orderDeliveryModel.findAll({ + where: { + id: { [Op.in]: orderIds }, + step: { [Op.in]: [ 1, 2, 3 ] }, + status: { [Op.ne]: 'cancel' }, + }, + attributes: [ 'id' ], + raw: true, + }); + + if (pendingOrders.length === 0) continue; + + const pendingOrderIds = new Set(pendingOrders.map(po => po.id)); + + // 统计每个 stock_id 被待处理订单引用的数量 + for (const oi of orderItems) { + if (pendingOrderIds.has(oi.order_id)) { + const sid = oi.stock_id; + orderReferencedMap.set(sid, (orderReferencedMap.get(sid) || 0) + 1); + } + } + } catch (err) { + ctx.logger.warn(`[handleBatchDelete] 检查待处理订单引用失败(仓库${warehouseId}): ${err.message}`); + // 检查失败时不阻塞删除,仅记录日志 + } + } + } + + // 将存在待处理订单引用的商品从可删除列表移至不可删除列表 + if (orderReferencedMap.size > 0) { + const newDeletable = []; + for (const product of deletableProducts) { + const pendingCount = orderReferencedMap.get(product.id) || 0; + if (pendingCount > 0) { + undeletableProducts.push({ + ...product, + reason: `该商品已被 ${pendingCount} 个待处理订单引用,无法删除。请先处理相关订单后再删除。`, + }); + } else { + newDeletable.push(product); + } + } + // 用过滤后的列表替换原可删除列表 + deletableProducts.length = 0; + deletableProducts.push(...newDeletable); + } + + if (deletableProducts.length === 0) { + const blockedReasons = undeletableProducts + .filter(p => p.reason) + .map(p => `${p.name}: ${p.reason}`) + .join(';'); + return { + code: 405, + message: '所有选中的商品均无法删除', + data: { + undeletableProducts, + message: blockedReasons || '所选商品均无法删除', + }, + }; + } + // 3. 执行删除(软删除) const deletableIds = deletableProducts.map(p => p.id); diff --git a/app/service/systems/storage/entry.js b/app/service/systems/storage/entry.js index ce1dac3..1e05591 100644 --- a/app/service/systems/storage/entry.js +++ b/app/service/systems/storage/entry.js @@ -448,12 +448,25 @@ class EntryService extends Service { { model: ctx.model.StockWarehouse, as: 'stock', - attributes: [ 'id', 'item_code', 'item_name' ], + attributes: [ 'id', 'item_code', 'item_name', 'sku_property' ], required: false, }, ], required: false, }, + { + model: ctx.model.EntryOrderReceiving, + as: 'receivingBindings', + required: false, + include: [ + { + model: ctx.model.Receiving, + as: 'receiving', + attributes: [ 'id', 'receiving_number', 'status', 'storage_status', 'created_at' ], + required: false, + }, + ], + }, ], }); @@ -465,109 +478,27 @@ class EntryService extends Service { }; } + // 扁平化 items:将外部商品字段重命名,stock 仓库商品字段平铺到 items 层级 + const entryOrderJSON = entryOrder.toJSON(); + if (entryOrderJSON.items && Array.isArray(entryOrderJSON.items)) { + entryOrderJSON.items = entryOrderJSON.items.map(item => { + const { item_code, item_id, stock, ...rest } = item; + return { + ...rest, + external_item_code: item_code, + external_item_id: item_id, + warehouse_item_code: (stock && stock.item_code) || '', + warehouse_item_name: (stock && stock.item_name) || '', + warehouse_item_spec: (stock && stock.sku_property) || '', + }; + }); + } + return { code: 200, message: '查询成功', data: { - entryOrder, - }, - }; - } - - generateOrderCode() { - const randomPart = Math.floor(Math.random() * 1000).toString().padStart(3, '0'); - return `ENT${Date.now()}${randomPart}`; - } - - /** - * 创建入库单。 - * @param {Object} data 请求体 - * @return {Promise} code/data/message 结构 - */ - async create(data = {}) { - const { ctx } = this; - const allowedOrderTypes = new Set([ 'SCRK', 'LYRK', 'CCRK', 'CGRK', 'DBRK', 'QTRK', 'B2BRK', 'XNRK' ]); - - const orderType = String(data.order_type || '').trim(); - const storeId = Number(data.store_id || ctx.user.store_id || 0); - - if (!orderType) { - return { - code: 400, - message: 'order_type 必填', - data: null, - }; - } - if (!allowedOrderTypes.has(orderType)) { - return { - code: 400, - message: 'order_type 不合法', - data: null, - }; - } - if (!storeId) { - return { - code: 400, - message: 'store_id 必填', - data: null, - }; - } - - const entryOrderCode = data.entry_order_code && String(data.entry_order_code).trim() !== '' - ? String(data.entry_order_code).trim() - : this.generateOrderCode(); - - const exists = await ctx.model.EntryOrder.findOne({ - where: { - entry_order_code: entryOrderCode, - warehouse_id: ctx.user.store_id, - store_id: storeId, - deleted_at: null, - }, - }); - - if (exists) { - return { - code: 409, - message: '入库单号已存在', - data: { - id: exists.id, - entry_order_code: exists.entry_order_code, - }, - }; - } - - const order = await ctx.model.EntryOrder.create({ - entry_order_code: entryOrderCode, - order_type: orderType, - purchase_order_code: data.purchase_order_code || '', - total_order_lines: Number(data.total_order_lines || 0), - order_create_time: data.order_create_time ? new Date(data.order_create_time) : new Date(), - expect_start_time: data.expect_start_time ? new Date(data.expect_start_time) : null, - expect_end_time: data.expect_end_time ? new Date(data.expect_end_time) : null, - logistics_code: data.logistics_code || '', - logistics_name: data.logistics_name || '', - express_code: data.express_code || '', - supplier_code: data.supplier_code || '', - supplier_name: data.supplier_name || '', - source_type: 'API', - order_status: 'PENDING', - sync_status: 'PENDING', - sync_message: '', - is_enabled: 1, - warehouse_id: ctx.user.store_id, - store_id: storeId, - remark: data.remark || '', - created_at: new Date(), - updated_at: new Date(), - }); - - return { - code: 200, - message: '创建成功', - data: { - id: order.id, - entry_order_code: order.entry_order_code, + entryOrder: entryOrderJSON, }, }; } @@ -644,220 +575,6 @@ class EntryService extends Service { }); } - /** - * 新增入库明细。 - * @param {Object} data 请求体 - * @return {Promise} code/data/message 结构 - */ - async addDetail(data = {}) { - const { ctx } = this; - const orderId = Number(data.order_id || 0); - const count = Number(data.count || 0); - - if (!orderId) { - return { - code: 400, - message: 'order_id 必填', - data: null, - }; - } - if (!count || count <= 0) { - return { - code: 400, - message: 'count 必须大于 0', - data: null, - }; - } - - const entryOrder = await this.getOwnedEntryOrderById(orderId); - if (!entryOrder) { - return { - code: 404, - message: '入库单不存在或无权访问', - data: null, - }; - } - if (entryOrder.order_status === 'CANCELLED' || entryOrder.order_status === 'COMPLETED') { - return { - code: 400, - message: '当前状态不允许新增明细', - data: null, - }; - } - - const maxLineNo = Number(await ctx.model.EntryItems.max('order_line_no', { - where: { order_id: orderId }, - })) || 0; - - const detail = await ctx.model.EntryItems.create({ - order_id: orderId, - order_line_no: maxLineNo + 1, - item_code: data.item_code || '', - item_id: data.item_id || null, - stock_id: data.stock_id || data.item_id || null, - count, - inventory_type: data.inventory_type || 'ZP', - received_quantity: 0, - confirm_quantity: 0, - owner_code: data.owner_code || '', - out_biz_code: data.out_biz_code || '', - }); - - await entryOrder.update({ - total_order_lines: maxLineNo + 1, - updated_at: new Date(), - }); - - return { - code: 200, - message: '新增明细成功', - data: { - id: detail.id, - order_id: orderId, - }, - }; - } - - /** - * 删除入库明细。 - * @param {Object} data 请求体 - * @return {Promise} code/data/message 结构 - */ - async deleteDetail(data = {}) { - const { ctx } = this; - const detailId = Number(data.id || 0); - - if (!detailId) { - return { - code: 400, - message: 'id 必填', - data: null, - }; - } - - const detail = await ctx.model.EntryItems.findByPk(detailId); - if (!detail) { - return { - code: 404, - message: '明细不存在', - data: null, - }; - } - - const entryOrder = await this.getOwnedEntryOrderById(detail.order_id); - if (!entryOrder) { - return { - code: 404, - message: '入库单不存在或无权访问', - data: null, - }; - } - - if (Number(detail.received_quantity || 0) > 0) { - return { - code: 400, - message: '已有收货数量的明细不允许删除', - data: null, - }; - } - - await detail.destroy(); - const lineCount = await ctx.model.EntryItems.count({ where: { order_id: entryOrder.id } }); - await entryOrder.update({ - total_order_lines: lineCount, - updated_at: new Date(), - }); - - return { - code: 200, - message: '删除明细成功', - data: { - id: detailId, - }, - }; - } - - /** - * 修改入库明细。 - * @param {Object} data 请求体 - * @return {Promise} code/data/message 结构 - */ - async detailChange(data = {}) { - const { ctx } = this; - const detailId = Number(data.id || 0); - - if (!detailId) { - return { - code: 400, - message: 'id 必填', - data: null, - }; - } - - const detail = await ctx.model.EntryItems.findByPk(detailId); - if (!detail) { - return { - code: 404, - message: '明细不存在', - data: null, - }; - } - - const entryOrder = await this.getOwnedEntryOrderById(detail.order_id); - if (!entryOrder) { - return { - code: 404, - message: '入库单不存在或无权访问', - data: null, - }; - } - - const updateData = {}; - const mutableFields = [ 'item_code', 'item_id', 'inventory_type', 'stock_id', 'out_biz_code', 'owner_code' ]; - for (const field of mutableFields) { - if (Object.prototype.hasOwnProperty.call(data, field)) { - updateData[field] = data[field]; - } - } - - if (Object.prototype.hasOwnProperty.call(data, 'count')) { - const count = Number(data.count); - if (!count || count <= 0) { - return { - code: 400, - message: 'count 必须大于 0', - data: null, - }; - } - if (Number(detail.received_quantity || 0) > count) { - return { - code: 400, - message: 'count 不能小于已收货数量', - data: null, - }; - } - updateData.count = count; - } - - if (Object.keys(updateData).length === 0) { - return { - code: 400, - message: '没有可更新字段', - data: null, - }; - } - - await detail.update(updateData); - - return { - code: 200, - message: '修改明细成功', - data: { - id: detail.id, - }, - }; - } - /** * 作废入库单。 * @param {Object} data 请求体 @@ -968,6 +685,14 @@ class EntryService extends Service { }; } + if (![ 'PENDING' ].includes(entryOrder.order_status)) { + return { + code: 400, + message: `当前入库单状态为 ${entryOrder.order_status},仅 PENDING 状态可完成入库`, + data: null, + }; + } + const detailCount = await ctx.model.EntryItems.count({ where: { order_id: orderId } }); if (detailCount <= 0) { return { @@ -990,6 +715,53 @@ class EntryService extends Service { }, }; } + + /** + * 获取入库单的导入/PDA 直接入库信息(转发到 inboundDirectLog)。 + * @param {string} entryOrderCode 入库单号 + * @return {Promise} code/data/message 结构 + */ + async getDirectInboundItems(entryOrderCode) { + const { ctx } = this; + return await ctx.service.systems.inboundDirectLog.getItems(entryOrderCode); + } + + /** + * 按商品增量添加导入/PDA 直接入库记录(转发到 inboundDirectLog)。 + * @param {Object} data 请求体 + * @param {string} data.entry_order_code 入库单号 + * @param {number} [data.stock_id] 商品SKU ID(单条模式) + * @param {number} [data.quantity] 本次入库数量(单条模式) + * @param {string} [data.inbound_type] 入库方式(单条模式) + * @param {Array} [data.items] 商品列表(批量模式) + * @return {Promise} code/data/message 结构 + */ + async addDirectInboundItem(data = {}) { + const { ctx } = this; + return await ctx.service.systems.inboundDirectLog.addItem(data); + } + + /** + * 提交确认完成导入/PDA 直接入库(转发到 inboundDirectLog)。 + * @param {string} entryOrderCode 入库单号 + * @return {Promise} code/data/message 结构 + */ + async commitDirectInbound(entryOrderCode) { + const { ctx } = this; + return await ctx.service.systems.inboundDirectLog.commit(entryOrderCode); + } + + /** + * 移除一条导入/PDA 直接入库记录(转发到 inboundDirectLog)。 + * @param {Object} data 请求体 + * @param {number} data.id 入库记录ID + * @return {Promise} code/data/message 结构 + */ + async removeDirectInboundItem(data = {}) { + const { ctx } = this; + return await ctx.service.systems.inboundDirectLog.removeItem(data); + } + } module.exports = EntryService; diff --git a/app/service/systems/storage/inventory.js b/app/service/systems/storage/inventory.js index 92079fe..293c87d 100644 --- a/app/service/systems/storage/inventory.js +++ b/app/service/systems/storage/inventory.js @@ -283,908 +283,6 @@ async function enrichInventoryStockAttachments(ctx, list = []) { class InventoryService extends Service { - /** - * 收货单快捷入库上架。 - * 从收货单直接生成入库单并写入库存。 - * - * 流程: - * 1. 校验收货单状态(必须 completed) - * 2. 校验收货单已审核(is_review = 1) - * 3. 校验所有明细已匹配系统商品(system_product_id 不为空) - * 4. 校验未全部入库(storage_status !== 'all') - * 4. 事务内: - * a. 创建入库单(EntryOrder)和入库明细(EntryItems) - * b. 逐条锁定 StockWarehouse 行,增加 quantity - * c. 写入/更新 wms_storage 库存记录 - * d. 更新 receiving_detail 的 storage_status 和 stored_quantity - * e. 更新 receiving 的 storage_status - * - * @param {Object} data 请求体 - * @param {number} data.receiving_id 收货单ID(必填) - * @return {Promise} code/data/message 结构 - */ - async quickPutaway(data = {}) { - const { ctx, app } = this; - const warehouseId = ctx.user.store_id; - const receivingId = Number(data.receiving_id || data.id || 0); - - if (!receivingId) { - return { code: 400, message: 'receiving_id 必填', data: null }; - } - - const transaction = await ctx.model.transaction(); - - try { - // ────────── 1. 查询并锁定收货单 ────────── - const receiving = await ctx.model.Receiving.findOne({ - where: { - id: receivingId, - warehouse_id: warehouseId, - is_deleted: false, - }, - lock: transaction.LOCK.UPDATE, - transaction, - include: [{ - model: ctx.model.ReceivingDetail, - as: 'details', - required: false, - }], - }); - - if (!receiving) { - await transaction.rollback(); - return { code: 404, message: '收货单不存在或无权访问', data: null }; - } - if (receiving.status !== 'completed') { - await transaction.rollback(); - return { code: 400, message: `收货单状态为 ${receiving.status},须完成收货后才能入库`, data: null }; - } - if (Number(receiving.is_review) !== 1) { - await transaction.rollback(); - return { code: 400, message: '收货单未审核,审核通过后才能入库', data: null }; - } - - const storeRelation = await ctx.model.StoreWarehouse.findOne({ - where: { - warehouse_id: warehouseId, - store_id: Number(receiving.store_id || 0), - use_status: 1, - }, - attributes: [ 'id', 'policy_config', 'store_remask' ], - lock: transaction.LOCK.UPDATE, - transaction, - }); - - if (!storeRelation) { - await transaction.rollback(); - return { code: 404, message: '收货单绑定的货主与当前仓库不存在有效签约关系', data: null }; - } - - const policyConfig = storeRelation.policy_config && typeof storeRelation.policy_config === 'object' - ? storeRelation.policy_config - : {}; - if (Number(policyConfig.allow_receiving_quick_putaway) !== 1) { - const storeName = String(storeRelation.store_remask || receiving.store_name || receiving.store_id || '当前货主'); - await transaction.rollback(); - return { code: 400, message: `货主${storeName}不允许快速上架,如需开启请到:货主->策略配置调整`, data: null }; - } - - if (receiving.storage_status === 'all') { - await transaction.rollback(); - return { code: 400, message: '该收货单已全部入库,无需重复操作', data: null }; - } - - const details = receiving.details || []; - if (!details.length) { - await transaction.rollback(); - return { code: 400, message: '收货单没有明细,无法入库', data: null }; - } - - // ────────── 3. 校验所有明细已匹配系统商品 ────────── - const unmatchedDetails = details.filter(d => !d.system_product_id); - if (unmatchedDetails.length > 0) { - await transaction.rollback(); - const names = unmatchedDetails.map(d => d.product_name).join('、'); - return { - code: 400, - message: `以下商品未匹配系统商品,请先绑定:${names}`, - data: { unmatched_count: unmatchedDetails.length, unmatched_names: names }, - }; - } - - // 过滤出需要入库的明细(排除已全部入库的) - const pendingDetails = details.filter(d => d.storage_status !== 'all'); - if (!pendingDetails.length) { - await transaction.rollback(); - return { code: 400, message: '所有明细已入库完成', data: null }; - } - - // ────────── 4. 创建入库单 ────────── - // 获取仓库名称快照 - let warehouseName = ''; - const warehouseData = await ctx.service.systems.store.getStoreName(warehouseId); - if (warehouseData.code === 200 && warehouseData.data) { - warehouseName = warehouseData.data.company_name || ''; - } - - // 获取合约表备注名称(优先使用) - const contract_data = await ctx.service.systems.store.getStoreRemaskName(receiving.store_id, warehouseId); - let contract = null; - if (contract_data.code === 200) { - contract = contract_data.data; - } - - const entryOrderCode = `SHRK${Date.now()}${String(Math.floor(Math.random() * 10000)).padStart(4, '0')}`; - const entryOrder = await ctx.model.EntryOrder.create({ - entry_order_code: entryOrderCode, - order_type: 'SHRK', - purchase_order_code: receiving.receiving_number || '', - total_order_lines: pendingDetails.length, - order_create_time: new Date(), - source_type: 'WMS', - order_status: 'PENDING', - sync_status: 'SUCCESS', - sync_message: `快捷入库-来自收货单 ${receiving.receiving_number}`, - is_enabled: 1, - warehouse_id: warehouseId, - store_id: receiving.store_id || warehouseId, - store_name: contract?.store_remask || receiving.store_name || '', - warehouse_name: contract?.warehouse_remask || warehouseName, - remark: `快捷入库,关联收货单 ${receiving.receiving_number}`, - created_at: new Date(), - updated_at: new Date(), - }, { transaction }); - - // ────────── 5. 逐条处理明细:创建入库明细 + 更新库存 ────────── - const results = []; - const errors = []; - - for (let i = 0; i < pendingDetails.length; i++) { - const detail = pendingDetails[i]; - const stockWarehouseId = detail.system_product_id; - const inboundQty = (detail.actual_quantity || 0) - (detail.stored_quantity || 0); - - if (inboundQty <= 0) { - continue; // 已入库完的跳过 - } - - // 5a. 锁定 StockWarehouse 行 - const stockRecord = await ctx.model.StockWarehouse.findOne({ - where: { - id: stockWarehouseId, - is_valid: 'Y', - deleted_at: null, - }, - lock: transaction.LOCK.UPDATE, - transaction, - }); - - if (!stockRecord) { - errors.push(`商品 ${detail.product_name} 的库存记录不存在 (stock_id: ${stockWarehouseId})`); - continue; - } - - // 5b. 增加 StockWarehouse 库存数量 - const beforeQuantity = Number(stockRecord.quantity) || 0; - const beforeLockedQuantity = Number(stockRecord.locked_quantity) || 0; - await stockRecord.increment('quantity', { - by: inboundQty, - transaction, - silent: true, - }); - await stockRecord.reload({ transaction }); - const afterQuantity = Number(stockRecord.quantity) || 0; - const afterLockedQuantity = Number(stockRecord.locked_quantity) || 0; - - // 5c. 写入/更新 wms_storage 库存位置表 - const spaceId = detail.space_id || 1; // 明细有库位则用,否则默认库位 - const batchNo = String(detail.batch_number || '').trim() || String(receiving.receiving_number || '').trim() || entryOrderCode; - const productionDate = detail.production_date || null; - const expiryDate = detail.expiry_date || null; - const inventoryType = 'ZP'; // 默认正品 - - // 查找是否已有相同 库位+SKU+批次+类型 的库存记录 - let storageRecord = await ctx.model.Storage.findOne({ - where: { - space_id: spaceId, - stock_id: stockWarehouseId, - batch_no: batchNo, - inventory_type: inventoryType, - is_enabled: 1, - delete_at: null, - }, - lock: transaction.LOCK.UPDATE, - transaction, - }); - - if (storageRecord) { - // 已有记录:累加数量 - await ctx.model.Storage.update({ - quantity: app.Sequelize.literal(`quantity + ${inboundQty}`), - available_quantity: app.Sequelize.literal(`available_quantity + ${inboundQty}`), - entry_order_id: entryOrder.id, - batch_no: batchNo, - production_date: productionDate, - expiry_date: expiryDate, - updated_at: new Date(), - }, { - where: { id: storageRecord.id }, - transaction, - }); - } else { - // 新建库存记录 - storageRecord = await ctx.model.Storage.create({ - warehouse_id: warehouseId, - store_id: receiving.store_id || warehouseId, - space_id: spaceId, - stock_id: stockWarehouseId, - batch_no: batchNo, - inventory_type: inventoryType, - quantity: inboundQty, - locked_quantity: 0, - available_quantity: inboundQty, - production_date: productionDate, - expiry_date: expiryDate, - inbound_time: new Date(), - inbound_order_no: entryOrderCode, - receiving_id: receivingId, - entry_order_id: entryOrder.id, - supplier_id: null, - supplier_batch_no: null, - is_enabled: 1, - created_at: new Date(), - updated_at: new Date(), - }, { transaction }); - } - - // 5d. 创建入库明细 - await ctx.model.EntryItems.create({ - order_id: entryOrder.id, - order_line_no: i + 1, - item_code: stockRecord.item_code || '', - item_id: stockWarehouseId, - count: inboundQty, - inventory_type: inventoryType, - stock_id: stockWarehouseId, - received_quantity: inboundQty, - confirm_quantity: inboundQty, - }, { transaction }); - - // 5d+. 写入出入库记录 - await ctx.service.systems.stockTransaction.create({ - transaction_type: 'INBOUND', - warehouse_id: warehouseId, - store_id: receiving.store_id || warehouseId, - stock_id: stockWarehouseId, - storage_id: storageRecord.id, - space_id: spaceId, - quantity: inboundQty, - batch_no: batchNo, - inventory_type: inventoryType, - order_type: 'SHRK', - order_no: entryOrderCode, - order_id: null, - receiving_id: receivingId, - entry_order_id: entryOrder.id, - operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), - operator_name: ctx.user?.employees_name || '', - remark: `快捷入库-收货单 ${receiving.receiving_number}`, - before_quantity: beforeQuantity, - after_quantity: afterQuantity, - before_locked_quantity: beforeLockedQuantity, - after_locked_quantity: afterLockedQuantity, - created_at: new Date(), - }, { transaction }); - - // 5e. 更新收货明细的入库状态 - const newStoredQty = (detail.stored_quantity || 0) + inboundQty; - const detailStorageStatus = newStoredQty >= detail.actual_quantity ? 'all' : 'partial'; - await ctx.model.ReceivingDetail.update({ - storage_status: detailStorageStatus, - stored_quantity: newStoredQty, - }, { - where: { id: detail.id }, - transaction, - }); - - results.push({ - detail_id: detail.id, - product_name: detail.product_name, - stock_warehouse_id: stockWarehouseId, - inbound_quantity: inboundQty, - space_id: spaceId, - storage_status: detailStorageStatus, - }); - } - - // 如果全部明细都失败 - if (results.length === 0 && errors.length > 0) { - await transaction.rollback(); - return { - code: 400, - message: `入库失败:${errors.join(';')}`, - data: null, - }; - } - - // ────────── 6. 更新入库单状态 ────────── - await entryOrder.update({ - order_status: 'COMPLETED', - total_order_lines: results.length, - updated_at: new Date(), - }, { transaction }); - - // ────────── 7. 更新收货单入库状态 ────────── - const allDetailsStored = details.every(d => { - if (d.storage_status === 'all') return true; - // 检查本次入库后是否全部完成 - const pending = pendingDetails.find(p => p.id === d.id); - if (!pending) return true; - const newStored = (pending.stored_quantity || 0) + ((pending.actual_quantity || 0) - (pending.stored_quantity || 0)); - return newStored >= pending.actual_quantity; - }); - const receivingStorageStatus = allDetailsStored ? 'all' : 'partial'; - - await ctx.model.Receiving.update({ - storage_status: receivingStorageStatus, - }, { - where: { id: receivingId }, - transaction, - }); - - // ────────── 8. 提交事务 ────────── - await transaction.commit(); - - // 记录操作日志 - try { - await ctx.service.systems.operationLog.createOperationLog({ - businessType: 'entry', - businessId: entryOrder.id, - operationCode: 'QUICK_PUTAWAY', - operator: { - id: ctx.user?.employees_id || ctx.user?.id, - name: ctx.user?.employees_name || '', - }, - extras: { - warehouseId, - }, - beforeChanges: null, - }); - } catch (logErr) { - ctx.logger.warn('[quickPutaway] 写入操作日志失败,不影响业务', logErr); - } - - ctx.logger.info('[quickPutaway] 快捷入库完成', { - receiving_id: receivingId, - receiving_number: receiving.receiving_number, - entry_order_code: entryOrderCode, - entry_order_id: entryOrder.id, - total_items: results.length, - errors: errors.length, - }); - - return { - code: 200, - message: errors.length - ? `入库部分完成,${results.length} 条成功,${errors.length} 条失败` - : '快捷入库完成', - data: { - receiving_id: receivingId, - receiving_number: receiving.receiving_number, - receiving_storage_status: receivingStorageStatus, - entry_order: { - id: entryOrder.id, - entry_order_code: entryOrderCode, - order_status: 'COMPLETED', - }, - items: results, - errors: errors.length ? errors : undefined, - }, - }; - } catch (error) { - await transaction.rollback(); - ctx.logger.error('[quickPutaway] 快捷入库异常', { - receiving_id: receivingId, - error: error.message, - stack: error.stack, - }); - - if (error.name === 'SequelizeDatabaseError' && error.message.includes('Lock wait timeout')) { - return { - code: 409, - message: '库存记录被锁定,请稍后重试', - data: null, - }; - } - - throw error; - } - } - - /** - * 匹配入库:将已完成收货的收货单与已有入库单按 stock_warehouse_id 做数量匹配入库。 - * - * @param {Object} data 请求体 - * @param {number[]} data.receiving_ids 收货单ID列表 - * @param {number[]} data.entry_order_ids 入库单ID列表 - * @return {Promise} code/data/message 结构 - */ - async matchPutaway(data = {}) { - const { ctx, app } = this; - const { Op } = app.Sequelize; - const warehouseId = ctx.user.store_id; - - // ────────── 1. 参数校验 ────────── - const receivingIds = Array.isArray(data.receiving_ids) ? data.receiving_ids.map(Number).filter(Boolean) : []; - const entryOrderIds = Array.isArray(data.entry_order_ids) ? data.entry_order_ids.map(Number).filter(Boolean) : []; - - if (!receivingIds.length) { - return { code: 400, message: 'receiving_ids 不能为空', data: null }; - } - if (!entryOrderIds.length) { - return { code: 400, message: 'entry_order_ids 不能为空', data: null }; - } - - // ────────── 2. 开事务 ────────── - const transaction = await ctx.model.transaction(); - - try { - // ────────── 3. 查询并锁定收货单 ────────── - const receivings = await ctx.model.Receiving.findAll({ - where: { - id: { [Op.in]: receivingIds }, - warehouse_id: warehouseId, - status: 'completed', - is_deleted: false, - }, - lock: transaction.LOCK.UPDATE, - transaction, - include: [{ - model: ctx.model.ReceivingDetail, - as: 'details', - required: false, - }], - }); - - if (!receivings.length) { - await transaction.rollback(); - return { code: 404, message: '未找到符合条件的收货单', data: null }; - } - - const unreviewedReceiving = receivings.find(item => Number(item.is_review) !== 1); - if (unreviewedReceiving) { - await transaction.rollback(); - return { - code: 400, - message: `收货单 ${unreviewedReceiving.receiving_number || unreviewedReceiving.id} 未审核,审核通过后才能入库`, - data: null, - }; - } - - // ────────── 4. 查询并锁定入库单 ────────── - const entryOrders = await ctx.model.EntryOrder.findAll({ - where: { - id: { [Op.in]: entryOrderIds }, - warehouse_id: warehouseId, - is_enabled: 1, - deleted_at: null, - order_status: { [Op.in]: [ 'PENDING', 'CONFIRMED', 'PARTIAL_RECEIVED' ] }, - }, - lock: transaction.LOCK.UPDATE, - transaction, - include: [{ - model: ctx.model.EntryItems, - as: 'items', - required: false, - }], - }); - - if (!entryOrders.length) { - await transaction.rollback(); - return { code: 404, message: '未找到符合条件的入库单', data: null }; - } - - // ────────── 5. 按 stock_warehouse_id 汇总 ────────── - // 收货侧:可入库明细(排除已全部入库的) - const rcvDetailsBySWId = {}; // stock_warehouse_id -> [ detail, ... ] - for (const rcv of receivings) { - for (const d of (rcv.details || [])) { - if (d.storage_status === 'all') continue; - if (!d.system_product_id) continue; - const available = (d.actual_quantity || 0) - (d.stored_quantity || 0); - if (available <= 0) continue; - const key = d.system_product_id; - if (!rcvDetailsBySWId[key]) rcvDetailsBySWId[key] = []; - rcvDetailsBySWId[key].push({ detail: d, available, receiving: rcv }); - } - } - - // 入库侧:待入库明细 - const entryItemsBySWId = {}; // stock_warehouse_id -> [ item, ... ] - for (const eo of entryOrders) { - for (const item of (eo.items || [])) { - if (!item.stock_id) continue; - const remaining = (item.count || 0) - (item.received_quantity || 0); - if (remaining <= 0) continue; - const key = item.stock_id; - if (!entryItemsBySWId[key]) entryItemsBySWId[key] = []; - entryItemsBySWId[key].push({ item, remaining, entryOrder: eo }); - } - } - - // ────────── 6. 逐个 stock_warehouse_id 执行匹配 ────────── - const matchedItems = []; - const unmatchedProducts = []; - const warnings = []; - - // 跟踪各明细的累计分配量 - const rcvDetailAllocated = {}; // detail.id -> allocated qty - const entryItemAllocated = {}; // item.id -> allocated qty - - // 取交集 key - const allSWIds = new Set([ - ...Object.keys(rcvDetailsBySWId), - ...Object.keys(entryItemsBySWId), - ]); - - for (const swIdStr of allSWIds) { - const swId = Number(swIdStr); - const rcvGroup = rcvDetailsBySWId[swId]; - const entryGroup = entryItemsBySWId[swId]; - - if (!rcvGroup || !entryGroup) { - if (rcvGroup && !entryGroup) { - unmatchedProducts.push({ stock_warehouse_id: swId, reason: '收货侧有库存但无对应入库计划' }); - } - if (!rcvGroup && entryGroup) { - unmatchedProducts.push({ stock_warehouse_id: swId, reason: '入库计划存在但无对应收货明细' }); - } - continue; - } - - // 计算总量 - const totalRcvAvailable = rcvGroup.reduce((s, r) => s + r.available, 0); - const totalEntryRemaining = entryGroup.reduce((s, e) => s + e.remaining, 0); - const actualInbound = Math.min(totalRcvAvailable, totalEntryRemaining); - - if (actualInbound <= 0) continue; - - if (totalRcvAvailable < totalEntryRemaining) { - warnings.push( - `stock_warehouse_id=${swId}: 收货可入库量(${totalRcvAvailable}) < 入库计划量(${totalEntryRemaining}),按收货量入库` - ); - } - - // 6a. 锁定 stock_warehouse 行并增加 quantity - const stockRecord = await ctx.model.StockWarehouse.findOne({ - where: { id: swId, is_valid: 'Y', deleted_at: null }, - lock: transaction.LOCK.UPDATE, - transaction, - }); - - if (!stockRecord) { - warnings.push(`stock_warehouse_id=${swId}: 库存记录不存在,跳过`); - continue; - } - - const beforeQuantity = Number(stockRecord.quantity) || 0; - const beforeLockedQuantity = Number(stockRecord.locked_quantity) || 0; - await stockRecord.increment('quantity', { - by: actualInbound, - transaction, - silent: true, - }); - await stockRecord.reload({ transaction }); - const afterQuantity = Number(stockRecord.quantity) || 0; - const afterLockedQuantity = Number(stockRecord.locked_quantity) || 0; - - // 6b. 写入/更新 wms_storage(取第一个收货明细的信息) - const firstRcvDetail = rcvGroup[0].detail; - const firstRcv = rcvGroup[0].receiving; - const firstEntryOrder = entryGroup[0].entryOrder; - const spaceId = firstRcvDetail.space_id || 1; - const batchNo = firstRcvDetail.batch_number || firstRcv.receiving_number || ''; - const inventoryType = 'ZP'; - - let storageRecord = await ctx.model.Storage.findOne({ - where: { - space_id: spaceId, - stock_id: swId, - batch_no: batchNo, - inventory_type: inventoryType, - is_enabled: 1, - delete_at: null, - }, - lock: transaction.LOCK.UPDATE, - transaction, - }); - - if (storageRecord) { - await ctx.model.Storage.update({ - quantity: app.Sequelize.literal(`quantity + ${actualInbound}`), - available_quantity: app.Sequelize.literal(`available_quantity + ${actualInbound}`), - entry_order_id: firstEntryOrder.id, - }, { - where: { id: storageRecord.id }, - transaction, - }); - } else { - storageRecord = await ctx.model.Storage.create({ - warehouse_id: warehouseId, - store_id: firstRcv.store_id || warehouseId, - space_id: spaceId, - stock_id: swId, - batch_no: batchNo, - inventory_type: inventoryType, - quantity: actualInbound, - locked_quantity: 0, - available_quantity: actualInbound, - production_date: firstRcvDetail.production_date || null, - expiry_date: firstRcvDetail.expiry_date || null, - inbound_time: new Date(), - inbound_order_no: firstEntryOrder.entry_order_code, - receiving_id: firstRcv.id, - entry_order_id: firstEntryOrder.id, - supplier_id: null, - supplier_batch_no: null, - is_enabled: 1, - created_at: new Date(), - updated_at: new Date(), - }, { transaction }); - } - - // 6b+. 写入出入库记录 - await ctx.service.systems.stockTransaction.create({ - transaction_type: 'INBOUND', - warehouse_id: warehouseId, - store_id: firstRcv.store_id || warehouseId, - stock_id: swId, - storage_id: storageRecord.id, - space_id: spaceId, - quantity: actualInbound, - batch_no: batchNo, - inventory_type: inventoryType, - order_type: 'MATCH', - order_no: firstEntryOrder.entry_order_code, - order_id: null, - receiving_id: firstRcv.id, - entry_order_id: firstEntryOrder.id, - operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), - operator_name: ctx.user?.employees_name || '', - remark: '匹配入库', - before_quantity: beforeQuantity, - after_quantity: afterQuantity, - before_locked_quantity: beforeLockedQuantity, - after_locked_quantity: afterLockedQuantity, - created_at: new Date(), - }, { transaction }); - - // 6c. 分配到各个收货明细(按顺序依次扣减) - let rcvRemain = actualInbound; - for (const rcvItem of rcvGroup) { - if (rcvRemain <= 0) break; - const allocate = Math.min(rcvRemain, rcvItem.available); - rcvDetailAllocated[rcvItem.detail.id] = (rcvDetailAllocated[rcvItem.detail.id] || 0) + allocate; - rcvRemain -= allocate; - } - - // 6d. 分配到各个入库明细(按顺序依次填充) - let entryRemain = actualInbound; - for (const entryItem of entryGroup) { - if (entryRemain <= 0) break; - const allocate = Math.min(entryRemain, entryItem.remaining); - entryItemAllocated[entryItem.item.id] = (entryItemAllocated[entryItem.item.id] || 0) + allocate; - entryRemain -= allocate; - } - - matchedItems.push({ - stock_warehouse_id: swId, - item_code: stockRecord.item_code || '', - inbound_quantity: actualInbound, - rcv_available: totalRcvAvailable, - entry_planned: totalEntryRemaining, - }); - } - - if (!matchedItems.length) { - await transaction.rollback(); - return { - code: 400, - message: '没有可匹配入库的商品', - data: { unmatched_products: unmatchedProducts }, - }; - } - - // ────────── 7. 更新收货明细 stored_quantity 和 storage_status ────────── - for (const rcv of receivings) { - for (const d of (rcv.details || [])) { - const allocated = rcvDetailAllocated[d.id]; - if (!allocated) continue; - const newStoredQty = (d.stored_quantity || 0) + allocated; - const detailStorageStatus = newStoredQty >= d.actual_quantity ? 'all' : 'partial'; - await ctx.model.ReceivingDetail.update({ - stored_quantity: newStoredQty, - storage_status: detailStorageStatus, - }, { - where: { id: d.id }, - transaction, - }); - } - } - - // ────────── 8. 更新入库明细 received_quantity ────────── - for (const eo of entryOrders) { - for (const item of (eo.items || [])) { - const allocated = entryItemAllocated[item.id]; - if (!allocated) continue; - const newReceivedQty = (item.received_quantity || 0) + allocated; - await ctx.model.EntryItems.update({ - received_quantity: newReceivedQty, - }, { - where: { id: item.id }, - transaction, - }); - } - } - - // ────────── 9. 更新收货单 storage_status ────────── - const receivingResults = []; - for (const rcv of receivings) { - const details = rcv.details || []; - const allStored = details.every(d => { - const allocated = rcvDetailAllocated[d.id] || 0; - const newStored = (d.stored_quantity || 0) + allocated; - return d.storage_status === 'all' || newStored >= d.actual_quantity; - }); - const hasAny = details.some(d => { - const allocated = rcvDetailAllocated[d.id] || 0; - return d.storage_status !== 'none' || allocated > 0; - }); - const newStatus = allStored ? 'all' : (hasAny ? 'partial' : rcv.storage_status); - - if (newStatus !== rcv.storage_status) { - await ctx.model.Receiving.update({ storage_status: newStatus }, { - where: { id: rcv.id }, - transaction, - }); - } - - receivingResults.push({ - receiving_id: rcv.id, - receiving_number: rcv.receiving_number, - storage_status: newStatus, - }); - } - - // ────────── 10. 更新入库单 order_status ────────── - const entryOrderResults = []; - const completedEntryOrders = []; // 事务外回传用 - - for (const eo of entryOrders) { - const items = eo.items || []; - const allFulfilled = items.every(item => { - const allocated = entryItemAllocated[item.id] || 0; - const newReceived = (item.received_quantity || 0) + allocated; - return newReceived >= (item.count || 0); - }); - const hasAnyReceived = items.some(item => { - const allocated = entryItemAllocated[item.id] || 0; - return (item.received_quantity || 0) + allocated > 0; - }); - - let newStatus = eo.order_status; - if (allFulfilled) { - newStatus = 'COMPLETED'; - } else if (hasAnyReceived) { - newStatus = 'PARTIAL_RECEIVED'; - } - - if (newStatus !== eo.order_status) { - await ctx.model.EntryOrder.update({ - order_status: newStatus, - updated_at: new Date(), - }, { - where: { id: eo.id }, - transaction, - }); - } - - const result = { - entry_order_id: eo.id, - entry_order_code: eo.entry_order_code, - order_status: newStatus, - source_type: eo.source_type, - callback_status: null, - }; - entryOrderResults.push(result); - - if (allFulfilled) { - completedEntryOrders.push({ entryOrder: eo, result }); - } else { - warnings.push( - `入库单 ${eo.entry_order_code}: 未全部入库完成(${newStatus}),不触发回传,需手工操作或等待其他收货入库` - ); - } - } - - // ────────── 12. 提交事务 ────────── - await transaction.commit(); - - // ────────── 13. 事务外:对已完成的入库单触发回传 ────────── - for (const { entryOrder, result } of completedEntryOrders) { - try { - if (entryOrder.source_type === 'QM') { - const confirmResult = await ctx.service.systems.entryOrder.entryorderConfirm(entryOrder.id, true); - result.callback_status = confirmResult.success ? 'SUCCESS' : 'FAILED'; - result.callback_detail = confirmResult; - } else if (entryOrder.source_type === 'API') { - const callbackResult = await this.apiCallback(entryOrder); - result.callback_status = callbackResult.success ? 'SUCCESS' : (callbackResult.skipped ? 'SKIPPED' : 'FAILED'); - result.callback_detail = callbackResult; - } else { - result.callback_status = 'NOT_REQUIRED'; - } - } catch (cbErr) { - ctx.logger.error(`[matchPutaway] 入库单 ${entryOrder.entry_order_code} 回传异常`, cbErr); - result.callback_status = 'ERROR'; - result.callback_detail = { error: cbErr.message }; - } - } - - // ────────── 14. 记录操作日志 ────────── - try { - await ctx.service.systems.operationLog.createOperationLog({ - businessType: 'entry', - businessId: entryOrderIds.join(','), - operationCode: 'MATCH_PUTAWAY', - operator: { - id: ctx.user?.employees_id || ctx.user?.id, - name: ctx.user?.employees_name || '', - }, - extras: { warehouseId, receivingIds, entryOrderIds }, - beforeChanges: null, - }); - } catch (logErr) { - ctx.logger.warn('[matchPutaway] 写入操作日志失败,不影响业务', logErr); - } - - ctx.logger.info('[matchPutaway] 匹配入库完成', { - receiving_ids: receivingIds, - entry_order_ids: entryOrderIds, - matched_count: matchedItems.length, - unmatched_count: unmatchedProducts.length, - warnings_count: warnings.length, - }); - - // ────────── 15. 返回结果 ────────── - return { - code: 200, - message: '匹配入库完成', - data: { - matched_items: matchedItems, - receiving_results: receivingResults, - entry_order_results: entryOrderResults, - unmatched_products: unmatchedProducts, - warnings: warnings.length ? warnings : undefined, - }, - }; - } catch (error) { - await transaction.rollback(); - ctx.logger.error('[matchPutaway] 匹配入库异常', { - receiving_ids: receivingIds, - entry_order_ids: entryOrderIds, - error: error.message, - stack: error.stack, - }); - - if (error.name === 'SequelizeDatabaseError' && error.message.includes('Lock wait timeout')) { - return { code: 409, message: '库存记录被锁定,请稍后重试', data: null }; - } - - throw error; - } - } - /** * 写入移库双向库位流水(移库出/移库入)。 * @@ -2127,68 +1225,6 @@ class InventoryService extends Service { } } - /** - * API 入库单回调:向 api_app 配置的 callback_url 发送入库确认通知。 - * - * @param {Object} entryOrder 入库单实例 - * @return {Promise} { success, skipped?, status?, error? } - */ - async apiCallback(entryOrder) { - const { ctx, app } = this; - try { - const apiApp = await app.model.ApiApp.findOne({ - where: { - warehouse_id: entryOrder.warehouse_id, - is_enabled: 1, - }, - }); - - if (!apiApp || !apiApp.callback_url) { - ctx.logger.info('[matchPutaway] 未找到API回调配置或无回调地址,跳过回调'); - return { success: true, skipped: true }; - } - - const items = await app.model.EntryItems.findAll({ - where: { order_id: entryOrder.id }, - }); - - const payload = { - entry_order_code: entryOrder.entry_order_code, - order_type: entryOrder.order_type, - order_status: 'COMPLETED', - warehouse_id: entryOrder.warehouse_id, - store_id: entryOrder.store_id, - items: items.map(item => ({ - item_code: item.item_code, - item_id: item.item_id, - plan_quantity: item.count, - received_quantity: item.received_quantity, - confirm_quantity: item.received_quantity, - })), - confirm_time: new Date().toISOString(), - }; - - const response = await ctx.curl(apiApp.callback_url, { - method: 'POST', - contentType: 'json', - data: payload, - timeout: 10000, - dataType: 'json', - }); - - ctx.logger.info('[matchPutaway] API回调结果', { - entry_order_id: entryOrder.id, - callback_url: apiApp.callback_url, - status: response.status, - }); - - return { success: response.status === 200, status: response.status }; - } catch (err) { - ctx.logger.error('[matchPutaway] API回调失败', err); - return { success: false, error: err.message }; - } - } - /** * 查询库存列表。 * diff --git a/app/service/systems/storage/management.js b/app/service/systems/storage/management.js new file mode 100644 index 0000000..3c94375 --- /dev/null +++ b/app/service/systems/storage/management.js @@ -0,0 +1,347 @@ +'use strict'; + +const Service = require('egg').Service; + +/** + * 将输入值转换为有限数字。 + * + * @param {unknown} value 待转换的值。 + * @param {number} [defaultValue=0] 默认值。 + * @return {number} 转换后的数字。 + */ +function toNumber(value, defaultValue = 0) { + const normalized = Number(value); + + return Number.isFinite(normalized) ? normalized : defaultValue; +} + +/** + * 将模型记录转换为普通对象。 + * + * @param {unknown} record 模型记录。 + * @return {Object|null} 普通对象。 + */ +function toPlainRecord(record) { + if (!record) { + return null; + } + + if (typeof record.get === 'function') { + return record.get({ plain: true }); + } + + return record; +} + +/** + * 库存管理服务层。 + * 负责库存分布分析、补货需求计算等库存管理相关业务逻辑。 + */ +class StorageManagementService extends Service { + /** + * 分拣缺货补货需求计算。 + * + * 仓库级别的计算,针对当前仓库所有未完成储位分配的订单, + * 计算每个 SKU 在分拣区与存货区的可用库存对比, + * 输出分拣区缺口及建议补货量,供仓库人员决策移库。 + * + * 仓库 ID 从用户上下文(ctx.user.store_id / ctx.user.warehouse_id)自动获取,无需显式传入。 + * + * @param {Object} [options={}] 可选项。 + * @param {Object} [options.pagination] 分页参数。 + * @param {number} [options.pagination.page=1] 页码,默认 1。 + * @param {number} [options.pagination.pageSize=20] 每页大小,默认 20。 + * @param {Object} [options.sort] 排序参数。 + * @param {string} [options.sort.sortField='shortage'] 排序字段,默认 shortage。 + * @param {string} [options.sort.sortOrder='DESC'] 排序方向,ASC/DESC。 + * @return {Promise} 补货需求明细、汇总与分页信息。 + */ + async replenishmentDemand(options = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + // 仓库上下文:从用户上下文获取 + const warehouseId = toNumber(ctx.user?.store_id ?? ctx.user?.warehouse_id, 0); + + if (warehouseId <= 0) { + throw new Error('缺少仓库上下文'); + } + + // 1) 获取订单模型和明细模型 + const orderModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); + const orderItemModel = await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId); + + // 2) 查询当前仓库所有未完成储位分配的订单 + const pendingOrders = await orderModel.findAll({ + where: { + warehouse_id: warehouseId, + storage_status: { [Op.ne]: 'fin' }, + delete_at: null, + }, + attributes: [ 'id' ], + raw: true, + }); + + const targetOrderIds = (Array.isArray(pendingOrders) ? pendingOrders : []) + .map(row => toNumber(row && row.id, 0)) + .filter(id => id > 0); + + if (targetOrderIds.length === 0) { + return { list: [], summary: { total_skus: 0, total_shortage_skus: 0, total_replenishment_needed: 0, total_true_shortage_skus: 0 } }; + } + + // 3) 查询订单明细,汇总每个 SKU 的需求量 + const itemRows = await orderItemModel.findAll({ + where: { + order_id: { [Op.in]: targetOrderIds }, + }, + attributes: [ 'stock_id', 'plan_qty' ], + raw: true, + }); + + const demandByStockId = new Map(); + const stockIdSet = new Set(); + + for (const row of Array.isArray(itemRows) ? itemRows : []) { + const stockId = toNumber(row.stock_id, 0); + const qty = toNumber(row.plan_qty, 0); + if (stockId <= 0 || qty <= 0) continue; + + demandByStockId.set(stockId, (demandByStockId.get(stockId) || 0) + qty); + stockIdSet.add(stockId); + } + + const allStockIds = Array.from(stockIdSet); + + if (allStockIds.length === 0) { + return { list: [], summary: { total_skus: 0, total_shortage_skus: 0, total_replenishment_needed: 0, total_true_shortage_skus: 0 } }; + } + + // 4) 查询 SKU 基础信息(先严格,漏掉的宽松兜底) + const stockWarehouseRows = allStockIds.length > 0 + ? await ctx.model.StockWarehouse.findAll({ + where: { + id: { [Op.in]: allStockIds }, + warehouse_id: warehouseId, + is_valid: 'Y', + deleted_at: null, + }, + attributes: [ 'id', 'item_code', 'item_name' ], + raw: true, + }) + : []; + + const stockInfoMap = new Map(); + const hitStockIds = new Set(); + + for (const row of Array.isArray(stockWarehouseRows) ? stockWarehouseRows : []) { + const stockId = toNumber(row.id, 0); + if (stockId <= 0) continue; + stockInfoMap.set(stockId, { + stock_code: String(row.item_code || ''), + stock_name: String(row.item_name || ''), + }); + hitStockIds.add(stockId); + } + + // 宽松兜底:查询未命中的 SKU(去掉 is_valid 和 warehouse_id 限制) + const missedStockIds = allStockIds.filter(id => !hitStockIds.has(id)); + if (missedStockIds.length > 0) { + const fallbackRows = await ctx.model.StockWarehouse.findAll({ + where: { + id: { [Op.in]: missedStockIds }, + deleted_at: null, + }, + attributes: [ 'id', 'item_code', 'item_name' ], + raw: true, + }); + + for (const row of Array.isArray(fallbackRows) ? fallbackRows : []) { + const stockId = toNumber(row.id, 0); + if (stockId <= 0 || stockInfoMap.has(stockId)) continue; + stockInfoMap.set(stockId, { + stock_code: String(row.item_code || ''), + stock_name: String(row.item_name || ''), + }); + } + } + + // 终极兜底:连已删除的也查 + const stillMissedStockIds = allStockIds.filter(id => !stockInfoMap.has(id)); + if (stillMissedStockIds.length > 0) { + const finalFallbackRows = await ctx.model.StockWarehouse.findAll({ + where: { + id: { [Op.in]: stillMissedStockIds }, + }, + attributes: [ 'id', 'item_code', 'item_name' ], + raw: true, + }); + + for (const row of Array.isArray(finalFallbackRows) ? finalFallbackRows : []) { + const stockId = toNumber(row.id, 0); + if (stockId <= 0 || stockInfoMap.has(stockId)) continue; + stockInfoMap.set(stockId, { + stock_code: String(row.item_code || ''), + stock_name: String(row.item_name || ''), + }); + } + } + + // 5) 查询所有可用库存(不区分分拣/存货区),再按库位类型分类汇总 + const storageRows = allStockIds.length > 0 + ? await ctx.model.Storage.findAll({ + where: { + warehouse_id: warehouseId, + stock_id: { [Op.in]: allStockIds }, + is_enabled: 1, + delete_at: null, + available_quantity: { [Op.gt]: 0 }, + }, + attributes: [ 'stock_id', 'available_quantity', 'space_id' ], + include: [ + { + model: ctx.model.LocationSpace, + as: 'space', + required: true, + attributes: [ 'id', 'space_code', 'custom_name' ], + include: [ + { + model: ctx.model.LocationType, + as: 'locationType', + required: true, + attributes: [ 'id', 'allow_allocation', 'is_active' ], + }, + ], + }, + ], + }) + : []; + + // 按 SKU 汇总分拣区与存货区可用库存 + const pickZoneQtyByStockId = new Map(); + const storageZoneQtyByStockId = new Map(); + // 存货区库位明细(用于补货库位推荐) + const storageZoneLocationsByStockId = new Map(); + + for (const storageRow of Array.isArray(storageRows) ? storageRows : []) { + const plainStorage = toPlainRecord(storageRow); + if (!plainStorage) continue; + + const stockId = toNumber(plainStorage.stock_id, 0); + const availableQty = toNumber(plainStorage.available_quantity, 0); + if (stockId <= 0 || availableQty <= 0) continue; + + const space = toPlainRecord(plainStorage.space) || {}; + const locationType = toPlainRecord(space.locationType) || {}; + const allowAllocation = toNumber(locationType.allow_allocation, 0); + const isActive = toNumber(locationType.is_active, 0); + + if (allowAllocation === 1 && isActive === 1) { + // 分拣区 + pickZoneQtyByStockId.set(stockId, (pickZoneQtyByStockId.get(stockId) || 0) + availableQty); + } else { + // 存货区 + storageZoneQtyByStockId.set(stockId, (storageZoneQtyByStockId.get(stockId) || 0) + availableQty); + + // 收集存货区库位明细 + const locationList = storageZoneLocationsByStockId.get(stockId) || []; + locationList.push({ + space_code: String(space.space_code || ''), + space_name: String(space.custom_name || space.space_code || ''), + available_quantity: availableQty, + }); + storageZoneLocationsByStockId.set(stockId, locationList); + } + } + + // 6) 组装输出 + const list = []; + let totalShortageSkus = 0; + let totalReplenishmentNeeded = 0; + let totalTrueShortageSkus = 0; + + for (const stockId of allStockIds) { + const info = stockInfoMap.get(stockId) || { stock_code: `SKU#${stockId}`, stock_name: `商品#${stockId}` }; + const totalDemand = demandByStockId.get(stockId) || 0; + const pickZoneQty = pickZoneQtyByStockId.get(stockId) || 0; + const storageZoneQty = storageZoneQtyByStockId.get(stockId) || 0; + const shortage = Math.max(0, totalDemand - pickZoneQty); + const replenishmentNeeded = Math.min(shortage, storageZoneQty); + const replenishmentStatus = storageZoneQty >= shortage ? 'replenishable' : 'true_shortage'; + + // 补货库位信息:按可用库存降序取前 5 条 + const rawLocations = storageZoneLocationsByStockId.get(stockId) || []; + rawLocations.sort((a, b) => (b.available_quantity - a.available_quantity)); + const replenishmentLocations = rawLocations.slice(0, 5); + + if (shortage > 0) { + list.push({ + stock_id: stockId, + stock_code: info.stock_code, + stock_name: info.stock_name, + pick_zone_quantity: pickZoneQty, + storage_zone_quantity: storageZoneQty, + total_demand: totalDemand, + shortage, + replenishment_needed: replenishmentNeeded, + replenishment_status: replenishmentStatus, + replenishment_locations: replenishmentLocations, + }); + + totalShortageSkus += 1; + totalReplenishmentNeeded += replenishmentNeeded; + if (replenishmentStatus === 'true_shortage') { + totalTrueShortageSkus += 1; + } + } + } + + // 7) 排序 + const paginationInput = options.pagination || {}; + const sortInput = options.sort || options.order || {}; + const sortField = String(sortInput.sortField || sortInput.field || 'shortage').trim(); + const sortOrderRaw = String(sortInput.sortOrder || sortInput.direction || 'DESC').toUpperCase().trim(); + const sortOrder = sortOrderRaw === 'ASC' ? 1 : -1; + const allowedSortFields = new Set([ + 'stock_id', + 'pick_zone_quantity', + 'storage_zone_quantity', + 'total_demand', + 'shortage', + 'replenishment_needed', + ]); + const effectiveSortField = allowedSortFields.has(sortField) ? sortField : 'shortage'; + + list.sort((a, b) => { + const aVal = a[effectiveSortField] ?? 0; + const bVal = b[effectiveSortField] ?? 0; + return (aVal - bVal) * sortOrder; + }); + + // 8) 内存分页 + const page = Math.max(1, toNumber(paginationInput.page, 1)); + const pageSize = Math.max(1, toNumber(paginationInput.pageSize, 20)); + const total = list.length; + const totalPages = Math.ceil(total / pageSize); + const startIndex = (page - 1) * pageSize; + const pagedList = list.slice(startIndex, startIndex + pageSize); + + return { + list: pagedList, + pagination: { + page, + pageSize, + total, + totalPages, + }, + summary: { + total_skus: totalShortageSkus, + total_shortage_skus: totalShortageSkus, + total_replenishment_needed: totalReplenishmentNeeded, + total_true_shortage_skus: totalTrueShortageSkus, + }, + }; + } +} + +module.exports = StorageManagementService; diff --git a/app/service/systems/storage/receiving.js b/app/service/systems/storage/receiving.js index e778ed7..a4d4d81 100644 --- a/app/service/systems/storage/receiving.js +++ b/app/service/systems/storage/receiving.js @@ -3986,6 +3986,12 @@ class ReceivingService extends Service { // 10. 提交事务 await transaction.commit(); + // 10.1 清除收货单缓存,确保下次入库完成时匹配到最新收货单列表 + const receivingCacheKey = `cache:receiving_orders:warehouse:${warehouseId}`; + app.delCacheAsync(receivingCacheKey).catch(cacheErr => { + ctx.logger.warn(`[receiving.completeReceiving] 清除收货单缓存失败: ${cacheErr.message}`, { cacheKey: receivingCacheKey }); + }); + // 记录操作日志 try { await ctx.service.systems.operationLog.createOperationLog({ @@ -4211,6 +4217,8 @@ class ReceivingService extends Service { } } } + } module.exports = ReceivingService; + diff --git a/app/service/systems/store_warehouse.js b/app/service/systems/store_warehouse.js index f47e75b..d6955f4 100644 --- a/app/service/systems/store_warehouse.js +++ b/app/service/systems/store_warehouse.js @@ -406,6 +406,15 @@ class SettingStoreWarehouseService extends Service { } await this.app.setCacheAsync(this.getPolicyConfigCacheKey(normalizedId), policyConfig, 86400 * 30); + + // 清除签约策略缓存(sw_policy:{storeId}:{warehouseId}) + const relation = await this.ctx.model.StoreWarehouse.findByPk(normalizedId, { + attributes: [ 'store_id', 'warehouse_id' ], + raw: true, + }); + if (relation) { + await this.app.delCacheAsync(`sw_policy:${relation.store_id}:${relation.warehouse_id}`); + } } /** @@ -2567,7 +2576,8 @@ class SettingStoreWarehouseService extends Service { // 3. 密码自动生成 if (!data.password) { - data.password = crypto.randomBytes(8).toString('base64').replace(/[+/=]/g, '').slice(0, 12); + data.password = crypto.randomBytes(8).toString('base64').replace(/[+/=]/g, '') + .slice(0, 12); } // 4. 必填字段校验 diff --git a/config/config.default.js b/config/config.default.js index 7c18215..2627a9e 100644 --- a/config/config.default.js +++ b/config/config.default.js @@ -209,6 +209,7 @@ module.exports = appInfo => { batchSize: 50, force: false, }; + return { ...config, ...userConfig, diff --git a/database/migrations/20260618150000-create-wms-entry-receiving-binding.js b/database/migrations/20260618150000-create-wms-entry-receiving-binding.js new file mode 100644 index 0000000..07706ca --- /dev/null +++ b/database/migrations/20260618150000-create-wms-entry-receiving-binding.js @@ -0,0 +1,86 @@ +'use strict'; + +const TABLE_NAME = 'wms_entry_receiving_binding'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME); + if (exists) return; + + await queryInterface.createTable(TABLE_NAME, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + entry_item_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '入库明细ID', + }, + receiving_detail_id: { + type: Sequelize.INTEGER, + allowNull: false, + comment: '收货明细ID', + }, + allocated_quantity: { + type: Sequelize.INTEGER, + allowNull: false, + comment: '预分配数量', + }, + status: { + type: Sequelize.ENUM('pending', 'committed', 'released'), + allowNull: false, + defaultValue: 'pending', + comment: '绑定状态:pending-待提交 committed-已提交 released-已释放', + }, + creator_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '创建人ID', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: Sequelize.DATE, + allowNull: true, + defaultValue: null, + comment: '软删除时间', + }, + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'entry_item_id' ], { + name: 'idx_entry_item_id', + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'receiving_detail_id' ], { + name: 'idx_receiving_detail_id', + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'status' ], { + name: 'idx_status', + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'entry_item_id', 'receiving_detail_id', 'status' ], { + unique: true, + name: 'uk_entry_receiving', + }); + }, + + down: async queryInterface => { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260621100000-create-wms-combo-goods.js b/database/migrations/20260621100000-create-wms-combo-goods.js new file mode 100644 index 0000000..bffeb3e --- /dev/null +++ b/database/migrations/20260621100000-create-wms-combo-goods.js @@ -0,0 +1,232 @@ +'use strict'; + +/** + * 获取当前数据库已存在的表名集合。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise>} 表名集合。 + */ +const getExistingTableSet = async queryInterface => { + const tables = await queryInterface.showAllTables(); + return new Set( + tables.map(table => (typeof table === 'string' ? table : table.tableName)) + ); +}; + +/** + * 幂等添加 custom_code 字段和索引(适用于表已存在但缺少新字段的场景)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ +const ensureCustomCodeColumnAndIndex = async (queryInterface, Sequelize) => { + const tableInfo = await queryInterface.describeTable('wms_combo_goods'); + if (!tableInfo.custom_code) { + await queryInterface.addColumn('wms_combo_goods', 'custom_code', { + type: Sequelize.STRING(64), + allowNull: true, + comment: '自定义编码(前端可输入,按货主唯一)', + }); + } + + const indexes = await queryInterface.showIndex('wms_combo_goods'); + const hasIndex = indexes.some(idx => idx.name === 'uk_store_custom_code'); + if (!hasIndex) { + await queryInterface.addIndex('wms_combo_goods', [ 'warehouse_id', 'custom_code' ], { + name: 'uk_store_custom_code', + }); + } +}; + +/** + * 创建组合商品主表 `wms_combo_goods`。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ +const createComboGoodsTable = async (queryInterface, Sequelize) => { + await queryInterface.createTable('wms_combo_goods', { + id: { + type: Sequelize.INTEGER(11), + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + combo_code: { + type: Sequelize.STRING(64), + allowNull: false, + comment: '组合商品编码,业务唯一标识', + }, + combo_name: { + type: Sequelize.STRING(128), + allowNull: false, + comment: '组合商品名称', + }, + custom_code: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '自定义编码(前端可输入,按货主唯一)', + }, + combo_sku_id: { + type: Sequelize.INTEGER(11), + allowNull: true, + comment: '组合商品关联的 wms_goods_sku.id', + }, + status: { + type: Sequelize.TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '状态:1-启用 0-停用', + }, + warehouse_id: { + type: Sequelize.INTEGER(11), + allowNull: true, + comment: '绑定仓库ID,NULL表示全局', + }, + remark: { + type: Sequelize.STRING(256), + allowNull: true, + comment: '备注', + }, + creator_id: { + type: Sequelize.INTEGER(11), + allowNull: true, + comment: '创建人ID', + }, + editor_id: { + type: Sequelize.INTEGER(11), + allowNull: true, + comment: '最后编辑人ID', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + }); + + await queryInterface.addIndex('wms_combo_goods', [ 'combo_code' ], { + unique: true, + name: 'uk_combo_code', + }); + + await queryInterface.addIndex('wms_combo_goods', [ 'combo_sku_id' ], { + name: 'idx_combo_sku_id', + }); + + await queryInterface.addIndex('wms_combo_goods', [ 'status' ], { + name: 'idx_status', + }); + + await queryInterface.addIndex('wms_combo_goods', [ 'warehouse_id' ], { + name: 'idx_warehouse_id', + }); + + await queryInterface.addIndex('wms_combo_goods', [ 'warehouse_id', 'custom_code' ], { + name: 'uk_store_custom_code', + }); +}; + +/** + * 创建组合商品明细表 `wms_combo_goods_item`。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ +const createComboGoodsItemTable = async (queryInterface, Sequelize) => { + await queryInterface.createTable('wms_combo_goods_item', { + id: { + type: Sequelize.INTEGER(11), + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + combo_id: { + type: Sequelize.INTEGER(11), + allowNull: false, + comment: '关联 wms_combo_goods.id', + }, + item_goods_sku_id: { + type: Sequelize.INTEGER(11), + allowNull: false, + comment: '子商品SKU ID,关联 wms_goods_sku.id', + }, + item_quantity: { + type: Sequelize.INTEGER(11), + allowNull: false, + defaultValue: 1, + comment: '子商品数量(整数件数)', + }, + sort_order: { + type: Sequelize.INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '排序序号,越小越靠前', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + }); + + await queryInterface.addIndex('wms_combo_goods_item', [ 'combo_id' ], { + name: 'idx_combo_id', + }); + + await queryInterface.addIndex('wms_combo_goods_item', [ 'item_goods_sku_id' ], { + name: 'idx_item_goods_sku_id', + }); + + await queryInterface.addIndex('wms_combo_goods_item', [ 'combo_id', 'item_goods_sku_id' ], { + unique: true, + name: 'uk_combo_sku', + }); +}; + +module.exports = { + /** + * 执行 migration:创建组合商品主表与明细表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + up: async (queryInterface, Sequelize) => { + const existingTables = await getExistingTableSet(queryInterface); + + if (!existingTables.has('wms_combo_goods')) { + await createComboGoodsTable(queryInterface, Sequelize); + } else { + await ensureCustomCodeColumnAndIndex(queryInterface, Sequelize); + } + + if (!existingTables.has('wms_combo_goods_item')) { + await createComboGoodsItemTable(queryInterface, Sequelize); + } + }, + + /** + * 回滚 migration:删除组合商品明细表与主表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + down: async queryInterface => { + await queryInterface.dropTable('wms_combo_goods_item'); + await queryInterface.dropTable('wms_combo_goods'); + }, +}; diff --git a/database/migrations/20260622100000-create-wms-inbound-direct-log.js b/database/migrations/20260622100000-create-wms-inbound-direct-log.js new file mode 100644 index 0000000..d02cc4a --- /dev/null +++ b/database/migrations/20260622100000-create-wms-inbound-direct-log.js @@ -0,0 +1,101 @@ +'use strict'; + +const TABLE_NAME = 'wms_inbound_direct_log'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME); + if (exists) return; + + await queryInterface.createTable(TABLE_NAME, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + store_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '货主ID', + }, + stock_id: { + type: Sequelize.BIGINT(20), + allowNull: false, + comment: '商品SKU ID,关联 wms_stock_warehouse.id', + }, + quantity: { + type: Sequelize.INTEGER(12), + allowNull: false, + comment: '入库数量', + }, + inbound_type: { + type: Sequelize.ENUM('import', 'pda'), + allowNull: false, + comment: '入库方式:import-导入入库 pda-PDA入库', + }, + entry_order_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '关联入库单ID(可选),关联 wms_entry_order.id', + }, + entry_order_code: { + type: Sequelize.STRING(50), + allowNull: true, + comment: '入库单号(冗余,方便查询)', + }, + remark: { + type: Sequelize.STRING(500), + allowNull: true, + comment: '备注(如导入文件名、PDA操作备注等)', + }, + operator_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '操作人ID', + }, + operator_name: { + type: Sequelize.STRING(50), + allowNull: true, + comment: '操作人名称', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id' ], { + name: 'idx_warehouse_id', + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'stock_id' ], { + name: 'idx_stock_id', + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'inbound_type' ], { + name: 'idx_inbound_type', + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'entry_order_id' ], { + name: 'idx_entry_order_id', + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'created_at' ], { + name: 'idx_created_at', + }); + }, + + down: async queryInterface => { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260622110000-add-space-id-to-wms-inbound-direct-log.js b/database/migrations/20260622110000-add-space-id-to-wms-inbound-direct-log.js new file mode 100644 index 0000000..7e407d8 --- /dev/null +++ b/database/migrations/20260622110000-add-space-id-to-wms-inbound-direct-log.js @@ -0,0 +1,25 @@ +'use strict'; + +const TABLE_NAME = 'wms_inbound_direct_log'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME); + if (!exists) return; + + const columns = await queryInterface.describeTable(TABLE_NAME); + if (columns.space_id) return; + + await queryInterface.addColumn(TABLE_NAME, 'space_id', { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '存放库位ID,关联 wms_location_space.id;为空时 commit 默认使用 1', + }); + }, + + down: async queryInterface => { + await queryInterface.removeColumn(TABLE_NAME, 'space_id'); + }, +}; diff --git a/database/migrations/20260622150000-seed-receipt-print-items.js b/database/migrations/20260622150000-seed-receipt-print-items.js new file mode 100644 index 0000000..1c4cf48 --- /dev/null +++ b/database/migrations/20260622150000-seed-receipt-print-items.js @@ -0,0 +1,67 @@ +'use strict'; + +/** + * 预置 RECEIPT(入库)业务类型的打印项配置。 + * + * 幂等设计:基于唯一索引 (business_type, platform, field_code) 做 INSERT IGNORE, + * 不会重复插入已存在的记录。 + */ + +const TABLE = 'wms_print_items'; + +const RECEIPT_PRINT_ITEMS = [ + // ─── 入库单信息(group: entry_order_info) ────────────────── + { business_type: 'RECEIPT', platform: 'default', field_name: '入库单号', field_code: 'entry_order_code', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 1, required: true, status: 1 }, + { business_type: 'RECEIPT', platform: 'default', field_name: '业务类型', field_code: 'order_type', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 2, required: false, status: 1 }, + { business_type: 'RECEIPT', platform: 'default', field_name: '订单状态', field_code: 'order_status', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 3, required: false, status: 1 }, + { business_type: 'RECEIPT', platform: 'default', field_name: '采购单号', field_code: 'purchase_order_code', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 4, required: false, status: 1 }, + { business_type: 'RECEIPT', platform: 'default', field_name: '供应商名称', field_code: 'supplier_name', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 5, required: false, status: 1 }, + { business_type: 'RECEIPT', platform: 'default', field_name: '仓库名称', field_code: 'warehouse_name', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 6, required: false, status: 1 }, + { business_type: 'RECEIPT', platform: 'default', field_name: '货主名称', field_code: 'store_name', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 7, required: false, status: 1 }, + { business_type: 'RECEIPT', platform: 'default', field_name: '物流公司', field_code: 'logistics_name', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 8, required: false, status: 1 }, + { business_type: 'RECEIPT', platform: 'default', field_name: '运单号', field_code: 'express_code', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 9, required: false, status: 1 }, + { business_type: 'RECEIPT', platform: 'default', field_name: '订单创建时间', field_code: 'order_create_time', field_type: 'datetime', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 10, required: false, status: 1 }, + { business_type: 'RECEIPT', platform: 'default', field_name: '预期到货时间', field_code: 'expect_start_time', field_type: 'datetime', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 11, required: false, status: 1 }, + { business_type: 'RECEIPT', platform: 'default', field_name: '备注', field_code: 'remark', field_type: 'textarea', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 12, required: false, status: 1 }, + { business_type: 'RECEIPT', platform: 'default', field_name: '单据总行数', field_code: 'total_order_lines', field_type: 'number', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 13, required: false, status: 1 }, + + // ─── 入库明细表格(is_table = true) ───────────────────────── + { business_type: 'RECEIPT', platform: 'default', field_name: '入库明细', field_code: 'items', field_type: 'text', is_table: true, table_config: { columns: 6, headers: ['商品编码', '商品名称', '条码', '计划数量', '已收数量', '库存类型'] }, group_field: 'entry_items', group_label: '入库明细', group_sort: 2, sort_order: 1, required: false, status: 1 }, +]; + +module.exports.up = async queryInterface => { + // 基于唯一索引做幂等插入 + const { sequelize } = queryInterface; + for (const item of RECEIPT_PRINT_ITEMS) { + await sequelize.query( + `INSERT IGNORE INTO \`${TABLE}\` + (business_type, platform, field_name, field_code, field_type, is_table, table_config, group_field, group_label, group_sort, sort_order, required, status, created_at, updated_at) + VALUES (:business_type, :platform, :field_name, :field_code, :field_type, :is_table, :table_config, :group_field, :group_label, :group_sort, :sort_order, :required, :status, NOW(), NOW())`, + { + replacements: { + business_type: item.business_type, + platform: item.platform, + field_name: item.field_name, + field_code: item.field_code, + field_type: item.field_type, + is_table: item.is_table ? 1 : 0, + table_config: item.table_config ? JSON.stringify(item.table_config) : null, + group_field: item.group_field || null, + group_label: item.group_label || null, + group_sort: item.group_sort || 0, + sort_order: item.sort_order || 0, + required: item.required ? 1 : 0, + status: item.status, + }, + type: sequelize.QueryTypes.INSERT, + } + ); + } +}; + +module.exports.down = async queryInterface => { + const { sequelize } = queryInterface; + await sequelize.query( + `DELETE FROM \`${TABLE}\` WHERE business_type = 'RECEIPT' AND platform = 'default'`, + ); +}; diff --git a/database/migrations/20260623120000-add-created-status-to-wms-entry-order.js b/database/migrations/20260623120000-add-created-status-to-wms-entry-order.js new file mode 100644 index 0000000..a1a2934 --- /dev/null +++ b/database/migrations/20260623120000-add-created-status-to-wms-entry-order.js @@ -0,0 +1,28 @@ +'use strict'; + +module.exports = { + /** + * 为 wms_entry_order 增加 CREATED 状态: + * ENUM 顺序: CREATING → CREATED → PENDING → CONFIRMED → PARTIAL_RECEIVED → COMPLETED → CANCELLED + * 默认值改为 CREATED + */ + up: async queryInterface => { + await queryInterface.sequelize.query( + "ALTER TABLE wms_entry_order MODIFY COLUMN order_status ENUM('CREATING','CREATED','PENDING','CONFIRMED','PARTIAL_RECEIVED','COMPLETED','CANCELLED') NOT NULL DEFAULT 'CREATED' COMMENT '订单状态'" + ); + }, + + /** + * 回滚: + * 1. 先将 CREATED 行更新为 PENDING + * 2. 再移除 CREATED 枚举值,恢复默认值 PENDING + */ + down: async queryInterface => { + await queryInterface.sequelize.query( + "UPDATE wms_entry_order SET order_status = 'PENDING', updated_at = NOW() WHERE order_status = 'CREATED'" + ); + await queryInterface.sequelize.query( + "ALTER TABLE wms_entry_order MODIFY COLUMN order_status ENUM('CREATING','PENDING','CONFIRMED','PARTIAL_RECEIVED','COMPLETED','CANCELLED') NOT NULL DEFAULT 'PENDING' COMMENT '订单状态'" + ); + }, +}; diff --git a/database/migrations/20260623130000-remove-confirmed-partial-received.js b/database/migrations/20260623130000-remove-confirmed-partial-received.js new file mode 100644 index 0000000..6fdeae1 --- /dev/null +++ b/database/migrations/20260623130000-remove-confirmed-partial-received.js @@ -0,0 +1,31 @@ +'use strict'; + +module.exports = { + /** + * 从 wms_entry_order.order_status ENUM 中移除 CONFIRMED 和 PARTIAL_RECEIVED + * 简化状态:CREATING → CREATED → PENDING → COMPLETED → CANCELLED + * + * 前置条件: + * - CONFIRMED 行数为 0,无需迁移 + * - PARTIAL_RECEIVED 的 11 行改为 PENDING + */ + up: async queryInterface => { + // 将 PARTIAL_RECEIVED 和 CONFIRMED 记录统一刷成 PENDING + await queryInterface.sequelize.query( + "UPDATE wms_entry_order SET order_status = 'PENDING', updated_at = NOW() WHERE order_status IN ('CONFIRMED', 'PARTIAL_RECEIVED')" + ); + // 缩小 ENUM:移除 CONFIRMED / PARTIAL_RECEIVED,保留 5 个状态 + await queryInterface.sequelize.query( + "ALTER TABLE wms_entry_order MODIFY COLUMN order_status ENUM('CREATING','CREATED','PENDING','COMPLETED','CANCELLED') NOT NULL DEFAULT 'CREATED' COMMENT '订单状态'" + ); + }, + + /** + * 回滚:恢复 CONFIRMED 和 PARTIAL_RECEIVED 到 ENUM 中(不回滚数据) + */ + down: async queryInterface => { + await queryInterface.sequelize.query( + "ALTER TABLE wms_entry_order MODIFY COLUMN order_status ENUM('CREATING','CREATED','PENDING','CONFIRMED','PARTIAL_RECEIVED','COMPLETED','CANCELLED') NOT NULL DEFAULT 'CREATED' COMMENT '订单状态'" + ); + }, +}; diff --git a/database/migrations/20260623140000-create-entry-order-receiving.js b/database/migrations/20260623140000-create-entry-order-receiving.js new file mode 100644 index 0000000..fa15c91 --- /dev/null +++ b/database/migrations/20260623140000-create-entry-order-receiving.js @@ -0,0 +1,66 @@ +'use strict'; + +const TABLE_NAME = 'wms_entry_order_receiving'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME); + if (exists) return; + + await queryInterface.createTable(TABLE_NAME, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + entry_order_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '入库单ID,关联 wms_entry_order.id', + }, + receiving_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '收货单ID,关联 wms_receiving.id', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: Sequelize.DATE, + allowNull: true, + defaultValue: null, + comment: '软删除时间', + }, + }); + + await queryInterface.addIndex(TABLE_NAME, ['entry_order_id'], { + name: 'idx_entry_order_id', + }); + + await queryInterface.addIndex(TABLE_NAME, ['receiving_id'], { + name: 'idx_receiving_id', + }); + + await queryInterface.addIndex(TABLE_NAME, ['entry_order_id', 'receiving_id'], { + unique: true, + name: 'uk_entry_order_receiving', + }); + }, + + down: async (queryInterface) => { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/docs/combo-goods-api.md b/docs/combo-goods-api.md new file mode 100644 index 0000000..5b6ea72 --- /dev/null +++ b/docs/combo-goods-api.md @@ -0,0 +1,387 @@ +# 组合商品(comboGoods)模块 API 文档 + +## 模块概述 + +组合商品(comboGoods)模块提供组合商品的 CRUD 和搜索功能。组合商品是将多个系统商品(来自 `wms_stock_warehouse`)捆绑在一起的商品概念,用于订单快速选择。 + +**代码文件:** +- 业务逻辑层:`app/service/systems/comboGoods.js` +- 接口包装层:`app/service/systemMethods/comboGoods.js` + +**数据表:** +- `wms_combo_goods`:组合商品主表 +- `wms_combo_goods_item`:组合商品明细表 + +--- + +## 数据库表结构 + +### 主表:wms_combo_goods + +| 字段 | 类型 | 说明 | +|------|------|------| +| id | number | 主键ID | +| combo_code | string | 组合商品编码(唯一) | +| combo_name | string | 组合商品名称 | +| combo_sku_id | number | 组合商品SKU ID | +| custom_code | string\|null | 自定义编码,按货主唯一(排除已删除记录) | +| status | number | 状态:1=启用 0=停用 | +| warehouse_id | number\|null | 仓库ID | +| remark | string | 备注 | +| creator_id | number | 创建人ID | +| editor_id | number | 最后编辑人ID | +| created_at | datetime | 创建时间 | +| updated_at | datetime | 更新时间 | + +### 明细表:wms_combo_goods_item + +| 字段 | 类型 | 说明 | +|------|------|------| +| id | number | 主键ID | +| combo_id | number | 关联的组合商品ID | +| item_goods_sku_id | number | 子商品 stock_id(对应 wms_stock_warehouse.id) | +| item_quantity | number | 子商品数量 | +| sort_order | number | 排序号 | + +--- + +## 约束规则 + +### 商品有效性校验 + +创建/编辑组合商品时,所有子商品必须在 `wms_stock_warehouse` 表中满足以下条件: +- `is_valid = 'Y'`(有效状态) +- `deleted_at IS NULL`(未删除) + +任一子商品不满足条件,操作将被拒绝并返回具体的不合法 stock_id 列表。 + +### 货主一致性校验 + +所有子商品必须属于同一个货主(`store_id` 一致)。跨货主组合将返回错误:「所有子商品必须属于同一个货主,不允许跨货主组合」。 + +### 自定义编码(custom_code)校验 + +`custom_code` 为可选字段(VARCHAR(64)),仅做按货主唯一性校验(排除 status=0 的已删除记录)。 +- **create**:如果传入非空的 `custom_code`,会校验同货主非删除记录中唯一。 +- **update**:如果传入非空的 `custom_code`,会校验同货主非删除记录中唯一(排除自身 id)。 +- 唯一索引:`uk_store_custom_code(warehouse_id, custom_code)`。 + +--- + +## 简记格式说明 + +列表查询和搜索结果中会返回两种简记字段,供前端直接展示: + +### simpleNotation(字符串简记) + +格式:`stock_id|数量,stock_id2|数量` + +示例:`1001|3,1002|5` 表示 stock_id=1001 的商品 3 件 + stock_id=1002 的商品 5 件。 + +### nameNotation(商品名称简记) + +格式:`【数量】商品名称+【数量】商品名称` + +示例:`【3】苹果+【5】香蕉` 表示苹果 3 件 + 香蕉 5 件。 + +商品名称从 `wms_stock_warehouse.item_name` 获取;若 stock_id 无有效商品信息,则显示为 `SKU#stock_id`。 + +--- + +## 接口列表 + +### 1. comboGoods.list — 组合商品列表查询(分页) + +- **鉴权**:不需要(isNeedAuth=false) +- **登录**:需要 + +#### 请求参数 + +| 字段 | 类型 | 必填 | 说明 | +|------|------|------|------| +| pagination | object | 否 | 分页参数 | +| pagination.page | number | 否 | 页码,默认 1 | +| pagination.pageSize | number | 否 | 每页大小,默认 20,最大 200 | +| where | object | 否 | 筛选条件 | +| where.combo_code | string | 否 | 组合商品编码,精确匹配 | +| where.combo_name | string | 否 | 组合商品名称,模糊匹配 | +| where.status | number | 否 | 状态筛选:1=启用 0=停用 | +| where.warehouse_id | number | 否 | 仓库ID筛选 | + +#### 请求示例 + +```json +{ + "method": "comboGoods.list", + "data": { + "pagination": { + "page": 1, + "pageSize": 20 + }, + "where": { + "combo_name": "春节礼包", + "status": 1 + } + } +} +``` + +#### 响应格式 + +```json +{ + "code": 200, + "message": "查询成功", + "data": { + "list": [ + { + "id": 1, + "combo_code": "COMBO-001", + "combo_name": "春节礼包A", + "combo_sku_id": 0, + "custom_code": null, + "status": 1, + "warehouse_id": 1001, + "remark": "", + "creator_id": 10, + "editor_id": 10, + "created_at": "2026-06-01T10:00:00.000Z", + "updated_at": "2026-06-01T10:00:00.000Z", + "items": [ + { + "id": 1, + "combo_id": 1, + "item_goods_sku_id": 1001, + "item_quantity": 3, + "sort_order": 0 + }, + { + "id": 2, + "combo_id": 1, + "item_goods_sku_id": 1002, + "item_quantity": 5, + "sort_order": 1 + } + ], + "simpleNotation": "1001|3,1002|5", + "nameNotation": "【3】苹果+【5】香蕉" + } + ], + "total": 1, + "page": 1, + "pageSize": 20 + } +} +``` + +--- + +### 2. comboGoods.create — 创建组合商品 + +- **鉴权**:需要(isNeedAuth=true) +- **登录**:需要 + +#### 请求参数 + +| 字段 | 类型 | 必填 | 说明 | +|------|------|------|------| +| combo_code | string | 是 | 组合商品编码,全局唯一 | +| combo_name | string | 是 | 组合商品名称 | +| warehouse_id | number | 否 | 仓库ID | +| remark | string | 否 | 备注 | +| custom_code | string | 否 | 自定义编码,传入时校验按货主唯一(排除已删除记录) | +| items | array | 是 | 子商品明细数组 | +| items[].item_goods_sku_id | number | 是 | 子商品 stock_id | +| items[].item_quantity | number | 是 | 子商品数量(正整数) | +| items[].sort_order | number | 否 | 排序号,默认按数组索引 | + +#### 请求示例 + +```json +{ + "method": "comboGoods.create", + "data": { + "combo_code": "COMBO-001", + "combo_name": "春节礼包A", + "warehouse_id": 1001, + "remark": "2026春节促销礼包", + "items": [ + { "item_goods_sku_id": 1001, "item_quantity": 3 }, + { "item_goods_sku_id": 1002, "item_quantity": 5 } + ] + } +} +``` + +#### 响应格式 + +```json +{ + "code": 200, + "message": "创建成功", + "data": { + "id": 1, + "combo_code": "COMBO-001", + "combo_name": "春节礼包A", + "custom_code": null + } +} +``` + +#### 常见错误 + +| 错误信息 | 说明 | +|---------|------| +| 组合商品编码不能为空 | combo_code 未传或为空 | +| 组合商品名称不能为空 | combo_name 未传或为空 | +| 子商品列表不能为空 | items 未传或为空数组 | +| 组合商品编码 "XXX" 已存在 | combo_code 重复 | +| 自定义编码 "XXX" 已被货主其他组合商品使用 | custom_code 在同一货主下重复(排除已删除) | +| 以下子商品不存在或已停用:1001, 1002 | 子商品在 wms_stock_warehouse 中不存在或已停用 | +| 所有子商品必须属于同一个货主,不允许跨货主组合 | 明细中商品的 store_id 不一致 | + +--- + +### 3. comboGoods.update — 编辑组合商品 + +- **鉴权**:需要(isNeedAuth=true) +- **登录**:需要 + +#### 请求参数 + +| 字段 | 类型 | 必填 | 说明 | +|------|------|------|------| +| id | number | 是 | 组合商品ID | +| combo_name | string | 否 | 组合商品名称 | +| warehouse_id | number | 否 | 仓库ID | +| remark | string | 否 | 备注 | +| custom_code | string | 否 | 自定义编码,传入非空值时校验按货主唯一(排除已删除记录和自身 id) | +| status | number | 否 | 状态:1=启用 0=停用 | +| items | array | 否 | 子商品明细数组。传入非空数组时先删旧明细再插入新明细;不传保持原明细不变 | +| items[].item_goods_sku_id | number | 是 | 子商品 stock_id | +| items[].item_quantity | number | 是 | 子商品数量(正整数) | +| items[].sort_order | number | 否 | 排序号 | + +> **注意**:部分更新语义——不传的字段保持原值不变。items 为可选,不传或传空数组则保持原明细不变。 + +#### 请求示例 + +```json +{ + "method": "comboGoods.update", + "data": { + "id": 1, + "combo_name": "春节礼包A(升级版)", + "remark": "更新备注", + "items": [ + { "item_goods_sku_id": 1001, "item_quantity": 5 }, + { "item_goods_sku_id": 1003, "item_quantity": 2 } + ] + } +} +``` + +#### 响应格式 + +```json +{ + "code": 200, + "message": "编辑成功", + "data": { + "id": 1 + } +} +``` + +--- + +### 4. comboGoods.delete — 删除组合商品 + +- **鉴权**:需要(isNeedAuth=true) +- **登录**:需要 + +#### 请求参数 + +| 字段 | 类型 | 必填 | 说明 | +|------|------|------|------| +| id | number | 是 | 组合商品ID | + +> **注意**:删除操作为软删除,仅将 `status` 置为 0(停用),不会物理删除记录。 + +#### 请求示例 + +```json +{ + "method": "comboGoods.delete", + "data": { + "id": 1 + } +} +``` + +#### 响应格式 + +```json +{ + "code": 200, + "message": "删除成功", + "data": { + "id": 1 + } +} +``` + +--- + +### 5. comboGoods.search — 关键字搜索组合商品 + +- **鉴权**:不需要(isNeedAuth=false) +- **登录**:需要 + +#### 请求参数 + +| 字段 | 类型 | 必填 | 说明 | +|------|------|------|------| +| keyword | string | 是 | 搜索关键字,模糊匹配 custom_code、combo_code 和 combo_name,custom_code 匹配项优先排在前面 | +| limit | number | 否 | 最大返回条数,默认 20,最大 100 | + +> **注意**:仅返回启用状态(status=1)的记录。该接口用于手工建单时前端选择组合商品。 + +#### 请求示例 + +```json +{ + "method": "comboGoods.search", + "data": { + "keyword": "礼包", + "limit": 30 + } +} +``` + +#### 响应格式 + +```json +{ + "code": 200, + "message": "搜索成功", + "data": { + "list": [ + { + "id": 1, + "combo_code": "COMBO-001", + "combo_name": "春节礼包A", + "custom_code": null, + "status": 1, + "warehouse_id": 1001, + "items": [ + { "id": 1, "combo_id": 1, "item_goods_sku_id": 1001, "item_quantity": 3, "sort_order": 0 } + ], + "simpleNotation": "1001|3,1002|5", + "nameNotation": "【3】苹果+【5】香蕉" + } + ], + "total": 1 + } +} +``` diff --git a/docs/storage-receiving-api.md b/docs/storage-receiving-api.md index 158eb67..185f289 100644 --- a/docs/storage-receiving-api.md +++ b/docs/storage-receiving-api.md @@ -432,5 +432,56 @@ curl -X POST "http://127.0.0.1:6060/system?method=storage.receiving.bindDetailPr 兼容性:上述新增字段为可选字段,旧版消费者在未识别这些字段时可忽略。 +--- +## 14. 收货→入库完整流程 + +### 14.1 流程概览 + +收货完成后,商品库存的实际入库通过以下步骤完成: + +1. **创建入库单** → `storage.entry` 系列方法(list/get/cancel/completeEntry) +2. **匹配入库(写库存)** → `storage.inventory.matchPutaway`(**目前唯一的库存写入入库链路**) + +> ⚠️ 注意:`storage.entry.completeEntry` 仅做入库单状态变更(PENDING → COMPLETED),**不涉及库存写入**。库存的实际写入统一由 `storage.inventory.matchPutaway` 完成。 + +### 14.2 完整推荐流程 + +``` +1. storage.receiving.create → 创建收货单 +2. storage.receiving.addDetail → 新增明细,拿到 selectId +3. storage.receiving.bindDetailProduct → 绑定系统商品 +4. storage.receiving.detailChange → 补充数量、批次等 +5. storage.receiving.completeReceiving → 完成收货 + ↓ +6. storage.entry 入库单管理 → 入库单与收货单通过 wms_entry_order_receiving 主表级关联 +7. storage.inventory.matchPutaway → 收货单与入库单匹配,完成库存写入 +8. storage.entry.completeEntry → 入库单状态标记为 COMPLETED(仅状态变更) +``` + +### 14.3 已弃用的方法 + +以下方法已从代码中移除,**不再可用**: + +| 已弃用方法 | 弃用原因 | 替代方案 | +|---|---|---| +| `storage.entry.bindReceivingDetails` | 入库单明细与收货明细逐行绑定(基于 `wms_entry_receiving_binding` 表),关系已改为 `wms_entry_order_receiving` 主表级关联 | 不再需要,入库单与收货单直接通过主表关联 | +| `storage.entry.unbindReceivingDetails` | 同上,逐行解绑已无必要 | 不再需要 | +| `storage.inventory.quickPutaway` | 单一收货单快捷入库,功能受限 | `storage.inventory.matchPutaway`(支持多收货单+多入库单批量匹配入库) | + +### 14.4 核心方法职责 + +| 方法 | 职责 | 备注 | +|---|---|---| +| `storage.inventory.matchPutaway` | **唯一库存写入入库链路**:接收多个收货单和多个入库单,按商品进行数量匹配,完成库存的实际写入 | 入库后根据来源(QM/API)自动触发回传 | +| `storage.entry.completeEntry` | **仅状态变更**:入库单 PENDING → COMPLETED | 不涉及任何库存写入 | +| `storage.entry.list` | 入库单列表查询 | 支持 CREATING/CREATED/PENDING/COMPLETED/CANCELLED 状态筛选 | +| `storage.entry.get` | 入库单详情查询 | 含 items 及其 bindings | +| `storage.entry.cancel` | 作废入库单(CREATED/PENDING 可作废) | COMPLETED 不可作废 | + +### 14.5 关键数据库表关系 + +- `wms_entry_order_receiving`:入库单与收货单的**主表级关联**(当前方案) +- `wms_entry_receiving_binding`:**已弃用**,不再写入新数据(旧方案:明细级绑定) +- 收货单与入库单不再需要逐明细绑定,通过主表关联即可完成匹配入库 diff --git a/memories/repo/entry-receiving-match-callback.md b/memories/repo/entry-receiving-match-callback.md new file mode 100644 index 0000000..08e4df0 --- /dev/null +++ b/memories/repo/entry-receiving-match-callback.md @@ -0,0 +1,28 @@ +# 入库单完成 → 异步匹配收货单并回传 + +## 实现日期 +2026-06-18 + +## 涉及文件 + +### 新建 +- `app/service/systems/receiving_entry_match.js` — 核心匹配与回传服务 + +### 修改 +- `app/service/systems/entry_order.js` — `entryorderConfirm()` 事务提交后触发异步匹配 +- `app/service/systems/storage/entry.js` — `completeEntry()` 状态更新后触发异步匹配 +- `app/service/systems/storage/receiving.js` — `completeReceiving()` 事务提交后清除收货单缓存 + +## 核心流程 +1. 入库单完成(COMPLETED)→ `setImmediate` 异步触发 `matchAfterEntryCompleted` +2. 从 Redis 缓存读取仓库近 3 天收货单列表(key: `cache:receiving_orders:warehouse:{warehouseId}`,TTL: 300s) +3. 根据入库单 `remark` 字符串包含匹配收货单号 +4. 对比明细 SKU + 数量 → full_match / receiving_covers_entry / 其他 +5. full_match / receiving_covers_entry → 按来源回传(QM 奇门 / API OpenAPI) +6. receiving_covers_entry → 标记收货单为"部分入库"(storage_status=partial) +7. 收货单完成时主动清除对应仓库缓存 + +## 注意事项 +- 异步执行,不阻塞主流程 +- 所有错误仅记录日志,不影响业务 +- 缓存回退:Redis 不可用时直接查询数据库 diff --git a/methods/changes/openapi-2026-06-17-entryorder.json b/methods/changes/openapi-2026-06-17-entryorder.json new file mode 100644 index 0000000..232ddac --- /dev/null +++ b/methods/changes/openapi-2026-06-17-entryorder.json @@ -0,0 +1,20 @@ +[ + { + "version": "2026.06.17-openapi-16", + "date": "2026-06-17", + "summary": "新增入库单模块(entryorder),支持 create(创建入库单)和 query(查询入库单)两个方法", + "methods": [ + "entryorder.create", + "entryorder.query" + ], + "notes": [ + "新增 entryorder.create:创建入库单接口,支持入库单主信息(entryOrder)和商品明细(orderLines.orderLine)的完整入参;创建渠道固定为 API;itemCode 与 itemId 二选一,优先使用 itemId", + "新增 entryorder.query:查询入库单接口,根据 entryOrderCode 查询入库单详情,返回基本信息及商品明细(itemId/itemCode/itemName/planQty/actualQty/inventoryType/orderLineNo)", + "查询范围为当前 app_key 绑定的仓库,跨仓库入库单无法查询", + "所有方法均支持 timestamp 时间戳时效校验:与服务器时间差不得超过 ±10 分钟(600 秒),否则返回 400", + "openapi 通道新增入库单创建和查询能力" + ], + "type": "added", + "module": "entryorder" + } +] diff --git a/methods/changes/openapi.json b/methods/changes/openapi.json index e772399..f7485fb 100644 --- a/methods/changes/openapi.json +++ b/methods/changes/openapi.json @@ -267,5 +267,48 @@ "mobile 和 tel 二选一必填" ], "type": "modified" + }, + { + "version": "2026.06.17-openapi-16", + "date": "2026-06-17", + "summary": "新增入库单模块(entryorder),支持 create(创建入库单)和 query(查询入库单)两个方法", + "methods": [ + "entryorder.create", + "entryorder.query" + ], + "notes": [ + "新增 entryorder.create:创建入库单接口,支持入库单主信息(entryOrder)和商品明细(orderLines.orderLine)的完整入参;创建渠道固定为 API", + "新增 entryorder.query:查询入库单接口,根据 entryOrderCode 查询入库单详情,返回基本信息及商品明细", + "itemCode 与 itemId 二选一,优先使用 itemId", + "openapi 通道新增入库单创建和查询能力" + ], + "type": "added" + }, + { + "version": "2026.06.23-openapi-01", + "date": "2026-06-23", + "summary": "入库单新增 CREATED 状态:entryorder.create 返回 status 说明更新为 CREATING=创建中/CREATED=已创建;entryorder.query 返回 status 可能值补充 CREATED", + "methods": [ + "entryorder.create", + "entryorder.query" + ], + "notes": [ + "entryorder.create response data.status 说明从通用描述更新为 CREATING=创建中明细行未全部插入 / CREATED=已创建完成", + "entryorder.query description 补充返回的 status 可能为 CREATING/CREATED/PENDING/CONFIRMED/PARTIAL_RECEIVED/COMPLETED/CANCELLED" + ], + "type": "updated", + "module": "entryorder" + }, + { + "version": "2026.06.23-openapi-02", + "date": "2026-06-23", + "summary": "入库单状态从 7 个简化为 5 个:移除 CONFIRMED 和 PARTIAL_RECEIVED,entryorder.query 的 status 枚举同步更新为 CREATING/CREATED/PENDING/COMPLETED/CANCELLED", + "methods": [ + "entryorder.query" + ], + "notes": [ + "entryorder.query description 中 status 枚举从 CREATING/CREATED/PENDING/CONFIRMED/PARTIAL_RECEIVED/COMPLETED/CANCELLED 简化为 CREATING/CREATED/PENDING/COMPLETED/CANCELLED,与 wms_entry_order.order_status ENUM 当前定义一致" + ], + "type": "updated" } ] diff --git a/methods/changes/system.json b/methods/changes/system.json index 03d6488..f730981 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,19 @@ [ + { + "version": "2026.06.18-system-01", + "date": "2026-06-18", + "summary": "order.pendingOrder.downloadCreateTemplate:模板列顺序调整,店铺名称(shop_nick)从末尾移至第2列B列,紧接*订单号之后", + "methods": [ + "order.pendingOrder.downloadCreateTemplate" + ], + "notes": [ + "调整 Excel 导入模板列顺序:店铺名称(shop_nick)从原第25列(Y列/末尾)移动至第2列(B列),紧跟在*订单号(delivery_order_code)之后。", + "同步更新 description 中的列顺序描述,明确 25 列(A-Y)的完整排列。", + "响应结构中移除冗余的 shop_nick 字段(模板列不属于 API 响应字段)。" + ], + "type": "updated", + "module": "order.pendingOrder" + }, { "version": "2026.05.17-system-09", "date": "2026-05-17", @@ -3416,5 +3431,656 @@ ], "type": "updated", "module": "order.wave" + }, + { + "version": "2026.06.17-system-01", + "date": "2026-06-17", + "summary": "新增 order.pendingOrder.replenishmentDemand 分拣缺货补货需求计算接口文档", + "methods": [ + "order.pendingOrder.replenishmentDemand" + ], + "notes": [ + "新增分拣缺货补货需求计算方法,用于计算待处理订单的SKU在分拣区与存货区的库存分布及补货缺口", + "入参 order_ids/warehouse_id 均为可选;不传 order_ids 时自动查询当前仓库所有未完成储位分配的订单", + "纯只读查询接口,不修改任何数据", + "响应包含 list(明细)与 summary(汇总),其中 shortage = max(0, total_demand - pick_zone_quantity),replenishment_needed = min(shortage, storage_zone_quantity)" + ], + "type": "add", + "module": "order.pendingOrder" + }, + { + "version": "2026.06.17-system-02", + "date": "2026-06-17", + "type": "update", + "module": "order.pendingOrder", + "method": "order.pendingOrder.replenishmentDemand", + "description": "移除 order_ids 参数,改为纯仓库级别计算,自动查询当前仓库所有未完成储位分配的订单" + }, + { + "version": "2026.06.17-system-03", + "date": "2026-06-17", + "type": "update", + "module": "order.pendingOrder", + "method": "order.pendingOrder.replenishmentDemand", + "description": "新增 is_true_shortage 字段标识真正缺货(两区均无库存),summary 新增 total_true_shortage_skus 统计" + }, + { + "version": "2026.06.17-system-04", + "date": "2026-06-17", + "type": "migrate", + "module": "storage.management", + "summary": "从 order.pendingOrder.replenishmentDemand 迁移至 storage.management.replenishmentDemand(库存管理模块),原路径已删除,开发阶段无需兼容", + "methods": [ + "storage.management.replenishmentDemand" + ], + "notes": [ + "将 replenishmentDemand 接口从 order.pendingOrder 模块迁移到新建的 storage.management 库存管理模块。", + "旧条目 order.pendingOrder.replenishmentDemand 已从 order.pendingOrder 组中移除。", + "开发阶段无需兼容旧路径。" + ] + }, + { + "version": "2026.06.17-system-05", + "date": "2026-06-17", + "type": "update", + "module": "storage.management", + "summary": "storage.management.replenishmentDemand 移除 warehouse_id 入参,仓库ID改为纯从用户上下文(ctx.user)获取,接口无需入参", + "methods": [ + "storage.management.replenishmentDemand" + ], + "notes": [ + "移除 warehouse_id 入参,仓库ID改为纯从用户上下文(ctx.user)获取,接口无需入参" + ] + }, + { + "version": "2026.06.17-system-06", + "date": "2026-06-17", + "type": "update", + "module": "storage.management", + "method": "storage.management.replenishmentDemand", + "description": "新增分页入参(pagination)、排序入参(sort,默认按 shortage DESC)、响应新增 replenishment_locations(存货区可补货库位,最多5条)、响应新增 pagination 分页信息" + }, + { + "version": "2026.06.17-system-07", + "date": "2026-06-17", + "type": "update", + "module": "storage.management", + "summary": "replenishment_locations 新增 space_name 字段,优先取自定义名称(custom_name),无则回退库位编码(space_code)", + "methods": [ + "storage.management.replenishmentDemand" + ], + "notes": [ + "在 replenishment_locations.children 中新增 space_name 字段(string, required),放在 space_code 之后、available_quantity 之前。", + "space_name 取值逻辑:优先使用库位自定义名称 custom_name,若无自定义名称则回退为库位编码 space_code。" + ] + }, + { + "version": "2026.06.17-system-08", + "date": "2026-06-17", + "type": "update", + "module": "storage.management", + "summary": "合并 is_sufficient 和 is_true_shortage 为 replenishment_status 枚举字段(replenishable/true_shortage)", + "methods": [ + "storage.management.replenishmentDemand" + ], + "notes": [ + "删除 is_sufficient(boolean)和 is_true_shortage(boolean)两个字段。", + "新增 replenishment_status(string)枚举字段:replenishable=存货区足够覆盖缺口,移库可解决;true_shortage=存货区不足以覆盖缺口或两区均无库存,需采购。" + ] + }, + { + "version": "2026.06.18-system-01", + "date": "2026-06-18", + "summary": "入库单完成后异步匹配收货单并回传:completeEntry / entryorderConfirm 入库完成时自动匹配收货单,明细一致则按来源回传(奇门/OpenAPI),覆盖场景标记收货单部分入库;completeReceiving 完成后清除收货单缓存", + "methods": [ + "storage.entry.completeEntry", + "storage.receiving.completeReceiving" + ], + "notes": [ + "新增 app/service/systems/receiving_entry_match.js:入库单完成后异步匹配收货单并回传的核心服务,含 Redis 缓存收货单列表(TTL 300s)、remark 匹配收货单号、明细对比、奇门回传、OpenAPI 回调、部分入库标记等能力。", + "storage.entry.completeEntry 完成后通过 setImmediate 异步触发 matchAfterEntryCompleted,不阻塞主流程。", + "entry_order.js entryorderConfirm() 事务提交后(isFin 最终完成)同样异步触发匹配。", + "storage.receiving.completeReceiving 完成后清除收货单 Redis 缓存(cache:receiving_orders:warehouse:{warehouseId}),确保下次匹配获取最新收货单列表。", + "匹配规则:入库单 remark 包含收货单号 → 对比 SKU+数量 → 完全一致回传 / 收货单覆盖标记部分入库 / 其他不处理。", + "回传路径:source_type=QM → 奇门 taobao.qimen.entryorder.confirm;source_type=API → OpenAPI 回调(entry_order_receiving_matched 事件)。" + ], + "type": "updated" + }, + { + "version": "2026.06.18-system-02", + "date": "2026-06-18", + "summary": "新增 storage.receiving.manualMatchEntryOrder 接口", + "methods": [ + "storage.receiving.manualMatchEntryOrder" + ], + "notes": [ + "新增 storage.receiving.manualMatchEntryOrder:手动匹配入库单与收货单,传入 receivingId 和 entryOrderId,复用异步匹配服务的明细对比和回传逻辑,同步返回匹配结果", + "参数:receivingId (number, 必填)、entryOrderId (number, 必填)", + "校验:入库单存在性、收货单存在性、同仓库校验", + "返回 matchType (full_match/receiving_covers_entry/entry_exceeds_receiving/no_match)、comparisonResult、callbackSent、callbackResult、partialStorageMarked、entryOrder、receivingOrder" + ], + "type": "added", + "module": "storage" + }, + { + "version": "2026.06.18-system-03", + "date": "2026-06-18", + "summary": "新增 storage.receiving.getAvailableInboundQuantity 接口:按 stock_id 查询已审核收货单的可入库数量(actual_quantity - stored_quantity),排除未审核和已取消的收货单", + "methods": [ + "storage.receiving.getAvailableInboundQuantity" + ], + "notes": [ + "新增 system method:storage.receiving.getAvailableInboundQuantity,按 stock_id 查询已审核收货单中各明细的可入库数量(actual_quantity - stored_quantity),仅返回尚有可入库余量的明细。", + "实现文件:app/service/systemMethods/storage/receiving.js(包装层)、app/service/systems/storage/receiving.js(业务层)。", + "接口无需鉴权(isNeedAuth=false),但需要登录(isNeedLogin=true)。", + "入参 stock_id 为必填,对应 stock_warehouse.id;服务端从 ctx.user.store_id 获取仓库上下文。" + ], + "type": "added", + "module": "storage" + }, + { + "version": "2026.06.18-system-04", + "date": "2026-06-18", + "summary": "新增 storage.entry.bindReceivingDetails 接口和 wms_entry_receiving_binding 中间表:入库单明细可显式绑定收货明细(pending状态),提交入库时事务内完成双向扣减(stored_quantity/received_quantity),通过唯一约束和行锁防止超分和重复绑定。同时重构 completeEntry 调用链为 commitEntryWithBindings,无绑定时向后兼容。", + "methods": [ + "storage.entry.bindReceivingDetails", + "storage.entry.completeEntry" + ], + "notes": [ + "新增 storage.entry.bindReceivingDetails 方法:入库单明细绑定收货明细,pending 状态软绑定,每次调用清除旧 pending 绑定后创建新绑定。", + "新增 wms_entry_receiving_binding 中间表(migration: 20260618150000-create-wms-entry-receiving-binding.js),用于记录入库明细与收货明细的绑定关系。", + "重构 completeEntry 调用链:systemMethods 层 completeEntry 改为调用 commitEntryWithBindings,有绑定则事务内完成双向扣减(stored_quantity/received_quantity),无绑定时向后兼容仅变更入库单状态。", + "通过数据库唯一约束和行锁(SELECT ... FOR UPDATE)防止超分和重复绑定。", + "涉及文件: app/model/entry_receiving_binding.js, app/service/systems/storage/entry.js, app/service/systemMethods/storage/entry.js, database/migrations/20260618150000-create-wms-entry-receiving-binding.js" + ], + "type": "added", + "module": "storage.entry" + }, + { + "version": "2026.06.18-system-05", + "date": "2026-06-18", + "summary": "storage.entry.get 响应追加 pending_total/total_planned/bindings 字段,storage.receiving.getAvailableInboundQuantity 响应追加 pending_allocated_quantity 字段:前端可通过 get 查看入库明细的绑定状态,getAvailableInboundQuantity 的可用量已扣除全局 pending 绑定总量", + "methods": [ + "storage.entry.get", + "storage.receiving.getAvailableInboundQuantity" + ], + "notes": [ + "storage.entry.get:items 数组每项新增 pending_total(该入库明细当前 pending 绑定的总预分配数量)、total_planned(计划入库数量=count)、bindings(pending 绑定列表,每项含 id/entry_item_id/receiving_detail_id/allocated_quantity/status/receivingDetail 子对象)", + "storage.receiving.getAvailableInboundQuantity:list 每项新增 pending_allocated_quantity(该收货明细在当前 stock_id 所有入库单中的 pending 绑定总量),available_quantity 计算已扣除该值" + ], + "type": "updated" + }, + { + "version": "2026.06.18-system-06", + "date": "2026-06-18", + "summary": "bindReceivingDetails 重构为\"绑定即实收\"(received_quantity 在绑定时更新,不再等到 completeEntry),新增 unbindReceivingDetails 解绑接口(删除 pending 绑定并回退 received_quantity),commitEntryWithBindings 移除 received_quantity 更新逻辑", + "methods": [ + "storage.entry.bindReceivingDetails", + "storage.entry.unbindReceivingDetails", + "storage.entry.completeEntry" + ], + "notes": [ + "storage.entry.bindReceivingDetails:改为绑定即实收,绑定成功后立即更新入库明细 received_quantity;重复调用时先回退旧绑定量再创建新绑定,避免重复累加。", + "storage.entry.unbindReceivingDetails:新增解绑接口,删除该入库明细的所有 pending 绑定记录,并将 received_quantity 回退到绑定前的值;收货明细可用数量随绑定记录删除自动恢复。", + "storage.entry.completeEntry:commitEntryWithBindings 中移除 received_quantity 更新逻辑(received_quantity 已在绑定时更新,completeEntry 仅完成收货单侧入库数量扣减和库存上架)。" + ], + "type": "updated" + }, + { + "version": "2026.06.19-system-01", + "date": "2026-06-19", + "summary": "order.recheckOrder.scanOrder 响应 list[] 新增 items_weight(订单商品总重量kg)和 suggested_package_material(推荐包材)字段", + "methods": [ + "order.recheckOrder.scanOrder" + ], + "notes": [ + "响应 list 每项新增 items_weight (number|null):订单商品总重量(kg),来源于 wms_order_delivery.items_weight。散单模式每个订单对象包含,团购模式每个波次对象包含(取波次内首个正常订单的重量,为 null 时返回 0)。", + "响应 list 每项新增 suggested_package_material (object|null):推荐包材信息,根据订单商品结构(items_hash + items_crc)匹配 wms_package_material_item_relation 历史绑定记录,按 bind_count 降序取最优匹配。若 items_hash 为空或无匹配记录则为 null。包含子字段:id、code、name、spec、type、weight、length、width、height、bind_count。", + "同步更新 method description 和 list 字段 description,补充新增字段的说明。" + ], + "type": "updated", + "module": "order.recheckOrder" + }, + { + "version": "2026.06.21-system-01", + "date": "2026-06-21", + "summary": "order.bindExpressPackageMaterialByWaybill:入参 package_material_code 改为 package_material_id,类型由 string 改为 number|string", + "methods": [ + "order.bindExpressPackageMaterialByWaybill" + ], + "notes": [ + "入参字段名从 package_material_code 改为 package_material_id。", + "入参类型从 string 改为 number|string,与代码 normalizePackageMaterialId 的实现一致。", + "同步更新该方法 description 中'包材编码'为'包材ID'。" + ], + "type": "updated", + "module": "order" + }, + { + "version": "2026.06.21-system-comboGoods-01", + "date": "2026-06-21", + "summary": "新增 comboGoods 组合商品模块 5 个接口文档:list/create/update/delete/search", + "methods": [ + "comboGoods.list", + "comboGoods.create", + "comboGoods.update", + "comboGoods.delete", + "comboGoods.search" + ], + "notes": [ + "comboGoods.list:组合商品列表查询(分页),支持按 combo_code/combo_name/status/warehouse_id 筛选,返回含 simpleNotation 和 nameNotation 简记字段", + "comboGoods.create:创建组合商品(含明细一次性提交),校验 combo_code 唯一性、子商品有效性和货主一致性,事务保证原子写入", + "comboGoods.update:编辑组合商品(含明细替换),支持部分字段更新,传入 items 则先删旧明细再插入新明细", + "comboGoods.delete:软删除组合商品(status 置为 0)", + "comboGoods.search:关键字搜索组合商品,模糊匹配 combo_code 或 combo_name,仅返回启用状态记录,上限100条", + "数据表:wms_combo_goods(主表)+ wms_combo_goods_item(明细表);子商品校验依赖 wms_stock_warehouse 表", + "代码文件:app/service/systems/comboGoods.js(业务逻辑层)+ app/service/systemMethods/comboGoods.js(接口包装层)", + "isNeedAuth:list/search 无需鉴权,create/update/delete 需要鉴权" + ], + "type": "added", + "module": "comboGoods" + }, + { + "version": "2026.06.21-system-comboGoods-02", + "date": "2026-06-21", + "summary": "comboGoods 模块新增 custom_code(自定义编码)功能:create/update 支持传入 custom_code 并校验按货主唯一,list/search 返回新增 custom_code 字段,search 搜索范围扩展至 custom_code 且优先排列匹配项", + "methods": [ + "comboGoods.list", + "comboGoods.create", + "comboGoods.update", + "comboGoods.search" + ], + "notes": [ + "新增字段 custom_code(VARCHAR(64) NULL),仅做按货主唯一性校验(排除已删除记录),非全局唯一。", + "wms_combo_goods 表新增索引 uk_store_custom_code(warehouse_id, custom_code)。", + "comboGoods.create:新增可选入参 custom_code,如果非空则校验同货主非删除记录中 unique;返回新增 custom_code 字段。", + "comboGoods.update:新增可选入参 custom_code,如果非空则校验同货主非删除记录中 unique(排除自身 id)。", + "comboGoods.list:返回每条记录新增 custom_code 字段。", + "comboGoods.search:搜索条件扩大为 custom_code LIKE / combo_code LIKE / combo_name LIKE,custom_code 匹配项按 ORDER BY CASE 排在前面;返回新增 custom_code 字段。" + ], + "type": "updated" + }, + { + "version": "2026.06.21-system-comboGoods-03", + "date": "2026-06-21", + "summary": "stock.warehouse.search 新增 mode=\"combo\" 组合商品查询模式,新增 id/custom_code 参数,补充组合商品响应结构", + "methods": [ + "stock.warehouse.search" + ], + "notes": [ + "新增入参 mode(查询模式,传 \"combo\" 时搜索组合商品),id(mode=combo 时按组合商品ID精确查询),custom_code(mode=combo 时按自定义编码模糊查询)", + "原有 keyword 参数在 mode=combo 时模糊匹配 combo_code / combo_name / custom_code", + "mode=combo 响应结构新增 combo_code、combo_name、custom_code、items(子商品数组含 item_goods_sku_id/item_quantity)、simpleNotation(stock_id|数量格式)、nameNotation(【数量】商品名称格式)", + "mode=combo 时不返回 stock 模式特有的字段(item_code/goods_code/item_name/sku_property/stock_unit/quantity/locked_quantity/brand_name/item_type/barcodes/store_stock/效期字段/storage)", + "with_stock 和 is_batch 参数在 mode=combo 时不生效" + ], + "type": "updated" + }, + { + "version": "2026.06.22-system-wavePickTaskList-01", + "date": "2026-06-22", + "summary": "order.wave.wavePickTaskList 响应新增 wave_list 数组:每个拣货任务返回关联波次列表", + "methods": [ + "order.wave.wavePickTaskList" + ], + "notes": [ + "wavePickTaskList 响应 list 每项新增 wave_list 数组字段,通过批量查询 wms_wave_pick_task_wave 表获取关联波次详情。", + "wave_list 每项包含:wave_id(波次ID)、wave_no(波次号)、box_no(框号)、status(波次关联状态)、bind_time(绑定时间)、pick_time(拣货完成时间)。", + "无需额外入参,默认对所有拣货任务返回 wave_list;查询为空时返回空数组 []。", + "同步更新 methods/system.json 响应文档。" + ], + "type": "updated", + "module": "order.wave" + }, + { + "version": "2026.06.22-system-order-export-mode-01", + "date": "2026-06-22", + "summary": "order.export 新增 export_mode 参数:支持 waybill(默认,按运单展开)与 item(按商品明细展开)两种导出模式", + "methods": [ + "order.export" + ], + "notes": [ + "新增入参 export_mode/exportMode,枚举值:waybill(默认)— 按运单号展开,每运单一组,items_detail 列汇总商品;item — 按商品明细展开,每商品一行,运单信息汇总填充。", + "方法层(OrderIndexService.export)新增 export_mode/exportMode 解构并透传到 systems.orderExport.exportOrders。", + "同步更新 methods/system.json 文档:description 补充 export_mode 说明,params 新增 export_mode/exportMode 条目。", + "order.export 导出的列新增:业务类型、运单接口、包材ID、包材编码、包材名称。" + ], + "type": "updated", + "module": "order.index" + }, + { + "version": "2026.06.22-system-directInbound-01", + "date": "2026-06-22", + "summary": "新增 storage.directInbound 导入/PDA直接入库模块:getItems(获取入库信息)、addItem(增量添加商品)、commit(提交完成入库并回传)", + "methods": [ + "storage.directInbound.getItems", + "storage.directInbound.addItem", + "storage.directInbound.commit" + ], + "notes": [ + "新增 storage.directInbound 模块,用于非收货单途径的导入/PDA 直接入库场景。", + "storage.directInbound.getItems:根据入库单号获取入库明细及已有的导入/PDA 入库记录,返回每项的可入库余量。", + "storage.directInbound.addItem:按 stock_id 增量添加导入/PDA 入库记录,累加超过该 stock_id 在入库单中的计划总量时拒绝。支持 import(导入)和 pda(PDA)两种方式。", + "storage.directInbound.commit:提交确认完成入库,按实收数量写入 wms_storage 库存和 wms_storage_transaction 流水,同 stock_id 多条明细只写一次库存,更新入库单状态为 COMPLETED 并同步 sync_status=SUCCESS,异步触发奇门/API 回传(按实收数量回传)。不足量提交时未入库商品跳过。", + "新增数据表 wms_inbound_direct_log(migration: 20260622100000-create-wms-inbound-direct-log.js):记录非收货单途径入库操作,含 warehouse_id、stock_id、quantity、inbound_type(import/pda)、entry_order_id、operator 等字段。模型文件:app/model/inbound_direct_log.js。", + "新增操作日志:addItem 记录 DIRECT_INBOUND_ADD(异步),commit 记录 DIRECT_INBOUND_COMMIT(事务内)。commit 响应返回 order_status=COMPLETED 和 sync_status=SUCCESS。", + "涉及文件:app/service/systems/inbound_direct_log.js(业务层)、app/service/systemMethods/storage/direct_inbound.js(包装层)、app/model/inbound_direct_log.js、database/migrations/20260622100000-create-wms-inbound-direct-log.js、methods/system.json(新增导入/PDA入库模块)。", + "E2E 测试:test/e2e_direct_inbound.test.js(53项断言全覆盖)。" + ], + "type": "added", + "module": "storage.directInbound" + }, + { + "version": "2026.06.22-system-directInbound-02", + "date": "2026-06-22", + "summary": "storage.directInbound.addItem 新增批量模式(items 数组),getItems 响应 summary 新增 total_import/total_pda 分类型汇总", + "methods": [ + "storage.directInbound.addItem", + "storage.directInbound.getItems" + ], + "notes": [ + "addItem 新增批量模式:支持传入 items 数组一次添加多条商品,每项含 stock_id/quantity/inbound_type/remark。单条模式(stock_id/quantity/inbound_type 顶层字段)保持向后兼容。批量模式下所有商品共享同一个入库单状态校验,任一商品校验失败整批拒绝。", + "addItem 批量模式响应结构:{ count, total_quantity, items: [...] },items 每项含 id/stock_id/quantity/inbound_type/plan_quantity/existing_before/existing_after/remaining。", + "getItems 响应 summary 新增 total_import(导入入库总数)和 total_pda(PDA入库总数)字段。", + "同步更新 methods/system.json 文档。" + ], + "type": "updated", + "module": "storage.directInbound" + }, + { + "version": "2026.06.22-system-directInbound-03", + "date": "2026-06-22", + "summary": "storage.directInbound 新增 space_id 库位支持:addItem 支持传入 space_id(单条和批量),commit 从入库记录取 space_id 写入 wms_storage 替代硬编码 1", + "methods": [ + "storage.directInbound.addItem", + "storage.directInbound.commit", + "storage.directInbound.getItems" + ], + "notes": [ + "addItem 新增可选入参 space_id(单条模式顶层字段 / 批量模式 items[].space_id),指定存放库位ID,关联 wms_location_space.id。", + "wms_inbound_direct_log 表新增 space_id 字段(migration: 20260622110000-add-space-id-to-wms-inbound-direct-log.js)。", + "commit 从入库记录中取第一个非空 space_id 写入 wms_storage,无记录时兜底使用库位 1。", + "getItems 响应中 direct_logs 每条记录包含 space_id 字段。", + "同步更新 methods/system.json 文档及模型文件。" + ], + "type": "updated", + "module": "storage.directInbound" + }, + { + "version": "2026.06.23-system-01", + "date": "2026-06-23", + "summary": "入库单(wms_entry_order)新增 CREATED 状态:order_status ENUM 从 CREATING/PENDING/CONFIRMED/PARTIAL_RECEIVED/COMPLETED/CANCELLED 扩展为 CREATING/CREATED/PENDING/CONFIRMED/PARTIAL_RECEIVED/COMPLETED/CANCELLED;默认值从 PENDING 变更为 CREATED;validTransitions 增加 CREATED 节点(CREATED→PENDING/CANCELLED,CREATING→CREATED/CANCELLED)", + "methods": [ + "storage.entry.list", + "storage.entry.get", + "storage.entry.cancel", + "storage.entry.completeEntry", + "storage.entry.bindReceivingDetails" + ], + "notes": [ + "Model 层:app/model/entry_order.js order_status ENUM 新增 CREATED,默认值从 PENDING 变更为 CREATED", + "Service 层:app/service/systems/entry_order.js addOrder 创建后状态从 CREATING→CREATED,validTransitions 增加 CREATED 节点", + "Service 层:app/service/systems/storage/entry.js createEntry 默认状态 PENDING→CREATED", + "Service 层:app/service/systems/storage/inventory.js 快捷入库默认 CREATED", + "文档同步:storage.entry.list where.order_status 枚举补充 CREATED;storage.entry.get description 补充 order_status 枚举含 CREATED;storage.entry.cancel 补充 CREATED 可作废说明;storage.entry.completeEntry/bindReceivingDetails 补充可操作状态含 CREATED" + ], + "type": "updated", + "module": "storage.entry" + }, + { + "version": "2026.06.23-system-02", + "date": "2026-06-23", + "summary": "入库单 CREATED 状态限制:CREATED 状态不允许绑定货物和完成入库,仅 PENDING/CONFIRMED/PARTIAL_RECEIVED 状态可操作", + "methods": [ + "storage.entry.cancel", + "storage.entry.completeEntry", + "storage.entry.bindReceivingDetails", + "storage.entry.unbindReceivingDetails" + ], + "notes": [ + "completeEntry / bindReceivingDetails / unbindReceivingDetails / commitEntryWithBindings 的可操作状态从原来的白名单(包含 CREATED)改为 PENDING / CONFIRMED / PARTIAL_RECEIVED,排除 CREATED。", + "CREATED 状态仅允许确认入库(→PENDING)或作废(→CANCELLED)。", + "storage.entry.cancel 补充明确 COMPLETED 状态不可作废,CREATED 可作废。", + "同步更新对应 method 的 description、errors 描述。" + ], + "type": "updated", + "module": "storage.entry" + }, + { + "version": "2026.06.23-system-03", + "date": "2026-06-23", + "summary": "storage.entry.cancel:CONFIRMED(已确认)状态不再允许作废,仅 CREATED 和 PENDING 可作废", + "methods": [ + "storage.entry.cancel" + ], + "notes": [ + "canCancel() 白名单移除 CONFIRMED,仅保留 CREATED 和 PENDING", + "validTransitions 中 CONFIRMED 不再可转为 CANCELLED", + "cancel() 方法新增 CONFIRMED 状态拦截,返回 400:已确认入库单不允许作废,请先完成收货", + "PARTIAL_RECEIVED 仍可作废,COMPLETED 不允许作废(行为不变)", + "更新 description 明确各状态可作废规则,errors 中补充 CONFIRMED 不可作废的说明" + ], + "type": "updated", + "module": "storage.entry" + }, + { + "version": "2026.06.23-system-04", + "date": "2026-06-23", + "summary": "入库单状态从 7 个简化为 5 个:移除 CONFIRMED 和 PARTIAL_RECEIVED,最终状态为 CREATING/CREATED/PENDING/COMPLETED/CANCELLED;同步更新 storage.entry 所有 method 的状态枚举和错误信息描述", + "methods": [ + "storage.entry.list", + "storage.entry.get", + "storage.entry.cancel", + "storage.entry.completeEntry", + "storage.entry.bindReceivingDetails", + "storage.entry.unbindReceivingDetails" + ], + "notes": [ + "wms_entry_order.order_status ENUM 从 CREATING/CREATED/PENDING/CONFIRMED/PARTIAL_RECEIVED/COMPLETED/CANCELLED 简化为 CREATING/CREATED/PENDING/COMPLETED/CANCELLED", + "storage.entry.list: where.order_status 描述和 where 参数描述中的状态枚举同步更新", + "storage.entry.get: entryOrder.order_status 描述同步更新", + "storage.entry.cancel: 移除 PARTIAL_RECEIVED 可作废和 CONFIRMED 不可作废的描述,仅保留 CREATED 和 PENDING 可作废,COMPLETED 不可作废", + "storage.entry.completeEntry: 可完成状态从 PENDING/CONFIRMED/PARTIAL_RECEIVED 改为仅 PENDING", + "storage.entry.bindReceivingDetails: 可操作状态从 PENDING/CONFIRMED/PARTIAL_RECEIVED 改为仅 PENDING", + "storage.entry.unbindReceivingDetails: 可操作状态从 PENDING/CONFIRMED/PARTIAL_RECEIVED 改为仅 PENDING", + "cancel() 取消 CONFIRMED 状态拦截(状态已不存在),COMPLETED 拦截保持不变" + ], + "type": "updated" + }, + { + "version": "2026.06.23-system-05", + "date": "2026-06-23", + "summary": "入库单状态语义调整:CREATED=已创建待审核,PENDING=已审核;同步更新 storage.entry 所有 method 的 description 中状态说明", + "methods": [ + "storage.entry.list", + "storage.entry.get", + "storage.entry.cancel", + "storage.entry.completeEntry", + "storage.entry.bindReceivingDetails", + "storage.entry.unbindReceivingDetails" + ], + "notes": [ + "CREATED 含义从\"已创建\"改为\"已创建待审核\"(需审核后才能绑定和完成入库)", + "PENDING 含义从\"待收货/收货中\"改为\"已审核\"(审核通过,可绑定和完成入库)", + "CREATED→PENDING 步骤语义:绑定审核", + "addOrder() 新增可选参数 autoReview(boolean,默认 false),false 创建后状态 CREATED(需审核),true 创建后状态 PENDING(自动审核通过)", + "快捷入库 quickPutaway 内部流程改为调用 addOrder({autoReview:true}) → bindReceivingDetails → commitEntryWithBindings,不再直接写库存,对外返回格式不变", + "storage.entry.list / storage.entry.get description 中补充 CREATED/PENDING 语义说明", + "storage.entry.cancel description 中补充可作废状态说明", + "storage.entry.completeEntry description 中补充可完成状态说明", + "storage.entry.bindReceivingDetails / storage.entry.unbindReceivingDetails description 中补充可绑定/解绑状态说明" + ], + "type": "updated" + }, + { + "version": "2026.06.23-system-06", + "date": "2026-06-23", + "summary": "storage.inventory.quickPutaway description 更新:补充内部已改为走 addOrder→bind→commit 链路,不再直接写库存", + "methods": [ + "storage.inventory.quickPutaway" + ], + "notes": [ + "快捷入库 quickPutaway 内部流程改为调用 addOrder({autoReview:true}) → bindReceivingDetails → commitEntryWithBindings,不再直接写库存,外部返回格式不变", + "description 中补充内部调用链路说明" + ], + "type": "updated" + }, + { + "version": "2026.06.23-system-07", + "date": "2026-06-23", + "summary": "storage.entry 大范围清理:删除 bindReceivingDetails/unbindReceivingDetails(明细级绑定已弃用),更新 completeEntry 为纯状态变更(不再做库存写入/异步匹配)", + "methods": [ + "storage.entry.bindReceivingDetails", + "storage.entry.unbindReceivingDetails", + "storage.entry.completeEntry" + ], + "notes": [ + "storage.entry.bindReceivingDetails:已从代码中删除,明细级绑定收货单功能下线。库存写入统一由 storage.inventory.matchPutaway 完成。", + "storage.entry.unbindReceivingDetails:已从代码中删除,明细级解绑功能下线。", + "storage.entry.completeEntry:改为纯状态变更(PENDING → COMPLETED),不再做库存写入和异步匹配回调。库存写入统一由 storage.inventory.matchPutaway 完成。" + ], + "type": "updated" + }, + { + "version": "2026.06.23-system-08", + "date": "2026-06-23", + "summary": "storage.inventory 清理:删除 quickPutaway(快捷入库已下线,统一由 matchPutaway 完成匹配入库)", + "methods": [ + "storage.inventory.quickPutaway" + ], + "notes": [ + "storage.inventory.quickPutaway:已从代码中删除,快捷入库功能下线。请使用 storage.inventory.matchPutaway 替代。" + ], + "type": "removed" + }, + { + "version": "2026.06.23-system-09", + "date": "2026-06-23", + "summary": "入库流程弃用清理:bindReceivingDetails/unbindReceivingDetails 标记为已删除并补充弃用原因,completeEntry 明确不涉及库存写入", + "methods": [ + "storage.entry.bindReceivingDetails", + "storage.entry.unbindReceivingDetails", + "storage.entry.completeEntry" + ], + "notes": [ + "storage.entry.bindReceivingDetails 与 storage.entry.unbindReceivingDetails 已从代码中移除,入库单与收货单关系改为 wms_entry_order_receiving 主表级关联,不再需要逐明细绑定/解绑。", + "wms_entry_receiving_binding 表不再写入新数据。", + "storage.entry.completeEntry 仅做状态变更(PENDING→COMPLETED),库存写入统一由 storage.inventory.matchPutaway 完成。", + "commitEntryWithBindings(内部方法)不再使用,库存写入统一走 matchPutaway 链路。" + ], + "type": "updated" + }, + { + "version": "2026.06.23-system-10", + "date": "2026-06-23", + "summary": "quickPutaway 弃用说明完善:明确替代方案为 matchPutaway;matchPutaway 标明为目前唯一库存写入入库链路", + "methods": [ + "storage.inventory.quickPutaway", + "storage.inventory.matchPutaway" + ], + "notes": [ + "storage.inventory.quickPutaway 已从代码中移除,替代方案为 storage.inventory.matchPutaway(支持多收货单+多入库单批量匹配入库)。", + "storage.inventory.matchPutaway 是目前唯一的库存写入入库链路,入库单状态变更由 storage.entry.completeEntry 单独处理。", + "本次为文档补充说明,不涉及代码变更。" + ], + "type": "updated" + }, + { + "version": "2026.06.23-system-11", + "date": "2026-06-23", + "summary": "删除 storage.receiving.getAvailableInboundQuantity:该方法依赖已弃用的 wms_entry_receiving_binding 明细绑定表,已从代码中移除", + "methods": [ + "storage.receiving.getAvailableInboundQuantity" + ], + "notes": [ + "该方法原用于按 stock_id 查询已审核收货单中各明细的可入库数量(actual_quantity - stored_quantity - pending_allocated_quantity)。", + "由于 wms_entry_receiving_binding 明细绑定表已弃用,入库单与收货单的关联改为通过 wms_entry_order_receiving 主表级关联,该查询方法不再适用。", + "替代方案:使用 storage.entry.get 查询入库单详情,通过顶层 receivingBindings 获取关联的收货单信息。" + ], + "type": "removed" + }, + { + "version": "2026.06.23-system-12", + "date": "2026-06-23", + "summary": "storage.entry.get 响应结构变更:不再返回 items[].bindings(明细级绑定),改为返回顶层 receivingBindings(主表级关联收货单信息)", + "methods": [ + "storage.entry.get" + ], + "notes": [ + "移除 items[].bindings(明细级绑定,原基于 wms_entry_receiving_binding 表),该绑定表已弃用。", + "新增顶层 receivingBindings(wms_entry_order_receiving 主表级关联),每项含 id/receiving_id/receiving(含 id/receiving_number/status/storage_status/created_at)。", + "items 中保留 external_item_code/external_item_id/warehouse_item_code/warehouse_item_name/warehouse_item_spec 等扁平化字段。", + "响应结构变更与 storage.directInbound.getItems 的返回结构对齐,后者同样使用顶层 receivingBindings。" + ], + "type": "modified" + }, + { + "version": "2026.06.23-system-13", + "date": "2026-06-23", + "summary": "新增 storage.entry.* 下 4 个 DirectInbound 方法:getDirectInboundItems、addDirectInboundItem、commitDirectInbound、removeDirectInboundItem,原 storage.directInbound.* 方法保留向后兼容并标记 deprecated", + "methods": [ + "storage.entry.getDirectInboundItems", + "storage.entry.addDirectInboundItem", + "storage.entry.commitDirectInbound", + "storage.entry.removeDirectInboundItem" + ], + "notes": [ + "storage.entry.getDirectInboundItems:获取入库单的导入/PDA 入库信息,参数与响应格式同原 storage.directInbound.getItems", + "storage.entry.addDirectInboundItem:按商品增量添加导入/PDA 入库记录(支持单条和批量),参数与响应格式同原 storage.directInbound.addItem", + "storage.entry.commitDirectInbound:提交确认完成导入/PDA 入库,按实收数量写入库存并异步回传奇门/API,参数与响应格式同原 storage.directInbound.commit", + "storage.entry.removeDirectInboundItem:移除一条导入/PDA 入库记录,参数与响应格式同原 storage.directInbound.removeItem", + "底层 inbound_direct_log.js 实现不变,仅入口从 storage.directInbound 模块迁入 storage.entry 模块" + ], + "type": "added" + }, + { + "version": "2026.06.23-system-14", + "date": "2026-06-23", + "summary": "storage.directInbound.* 下 4 个方法标记 deprecated,指向 storage.entry.* 下对应新方法", + "methods": [ + "storage.directInbound.getItems", + "storage.directInbound.addItem", + "storage.directInbound.commit", + "storage.directInbound.removeItem" + ], + "notes": [ + "storage.directInbound.getItems → 替代方法 storage.entry.getDirectInboundItems", + "storage.directInbound.addItem → 替代方法 storage.entry.addDirectInboundItem", + "storage.directInbound.commit → 替代方法 storage.entry.commitDirectInbound", + "storage.directInbound.removeItem → 替代方法 storage.entry.removeDirectInboundItem", + "旧方法保留向后兼容,参数与响应格式不变,仅入口模块变更" + ], + "type": "deprecated" + }, + { + "version": "2026.06.23-system-15", + "date": "2026-06-23", + "summary": "storage.inventory.matchPutaway 标记 deprecated,替代方案为 storage.entry.commitDirectInbound", + "methods": [ + "storage.inventory.matchPutaway" + ], + "notes": [ + "storage.inventory.matchPutaway 已弃用,请迁移至 storage.entry.commitDirectInbound", + "commitDirectInbound 提供导入/PDA 入库完成确认功能,按实收数量写入库存并异步回传" + ], + "type": "deprecated" + }, + { + "version": "2026.06.23-system-16", + "date": "2026-06-23", + "summary": "清理已弃用 method 条目:从 system.json 删除 storage.entry.bindReceivingDetails、storage.entry.unbindReceivingDetails、storage.inventory.matchPutaway 三个已从代码中移除的 method 文档条目", + "methods": [ + "storage.entry.bindReceivingDetails", + "storage.entry.unbindReceivingDetails", + "storage.inventory.matchPutaway" + ], + "notes": [ + "storage.entry.bindReceivingDetails:已从代码中删除,明细级绑定收货单功能下线。入库单与收货单关系改为 wms_entry_order_receiving 主表级关联。", + "storage.entry.unbindReceivingDetails:已从代码中删除,明细级解绑功能下线。", + "storage.inventory.matchPutaway:已从代码中删除,匹配入库功能下线。替代方案为 storage.entry.commitDirectInbound。", + "storage.inventory.quickPutaway:之前已标记 [已删除],本次确认条目保留(与 matchPutaway 同一 group,保留作为历史参考)。", + "storage.entry.create / addDetail / deleteDetail / detailChange:systems 层方法已删除,但从未在 system.json 中暴露为 API method,无需文档变更。" + ], + "type": "removed" } ] diff --git a/methods/openapi.json b/methods/openapi.json index c944d3e..5f6d784 100644 --- a/methods/openapi.json +++ b/methods/openapi.json @@ -1,8 +1,8 @@ { "module": "openapi", "description": "开放 API 统一入口,独立链路,HTTP POST /openapi,记录入口校验/鉴权规则与返回格式。", - "version": "2026.06.05-openapi-15", - "updatedAt": "2026-06-05", + "version": "1.1.0", + "updatedAt": "2026-06-23", "http": { "path": "/openapi", "method": "POST" @@ -1457,6 +1457,453 @@ ] } ] + }, + { + "groupName": "入库单模块", + "module": "entryorder", + "list": [ + { + "method": "entryorder.create", + "description": "entryorder 模块 创建入库单接口,支持传入入库单主信息和商品明细。创建成功后返回的状态 status 为 CREATING(明细行未全部插入)或 CREATED(明细行已全部插入完成)。", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "entryOrder", + "type": "object", + "required": true, + "source": "body", + "description": "入库单主信息对象" + }, + { + "name": "entryOrder.entryOrderCode", + "type": "string", + "required": true, + "source": "body", + "description": "入库单号(必填),外部系统的唯一入库单号" + }, + { + "name": "entryOrder.entryOrderType", + "type": "string", + "required": false, + "source": "body", + "description": "入库单类型,默认 SCRK(生产入库)" + }, + { + "name": "entryOrder.warehouseCode", + "type": "string", + "required": false, + "source": "body", + "description": "仓库编码" + }, + { + "name": "entryOrder.ownerCode", + "type": "string", + "required": false, + "source": "body", + "description": "货主编码" + }, + { + "name": "entryOrder.expectedArriveTime", + "type": "string", + "required": false, + "source": "body", + "description": "预计到货时间,ISO 8601 格式" + }, + { + "name": "entryOrder.totalOrderLines", + "type": "number", + "required": false, + "source": "body", + "description": "总行数" + }, + { + "name": "entryOrder.operateTime", + "type": "string", + "required": false, + "source": "body", + "description": "操作时间,ISO 8601 格式" + }, + { + "name": "entryOrder.operatorName", + "type": "string", + "required": false, + "source": "body", + "description": "操作人" + }, + { + "name": "entryOrder.supplierCode", + "type": "string", + "required": false, + "source": "body", + "description": "供应商编码" + }, + { + "name": "entryOrder.supplierName", + "type": "string", + "required": false, + "source": "body", + "description": "供应商名称" + }, + { + "name": "entryOrder.remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注" + }, + { + "name": "orderLines", + "type": "object", + "required": true, + "source": "body", + "description": "订单明细对象,包含 orderLine 数组" + }, + { + "name": "orderLines.orderLine", + "type": "array", + "required": true, + "source": "body", + "description": "商品明细列表,数组中每项为一个入库单行对象" + }, + { + "name": "[].orderLine.itemCode", + "type": "string", + "required": false, + "source": "body", + "description": "商品编码,与 itemId 二选一,用于匹配仓库中的商品" + }, + { + "name": "[].orderLine.itemId", + "type": "number", + "required": false, + "source": "body", + "description": "仓库商品主键ID,与 itemCode 二选一,优先使用 itemId" + }, + { + "name": "[].orderLine.itemName", + "type": "string", + "required": false, + "source": "body", + "description": "商品名称,用于错误提示中的商品识别" + }, + { + "name": "[].orderLine.planQty", + "type": "number", + "required": true, + "source": "body", + "description": "计划入库数量(必填),必须大于 0" + }, + { + "name": "[].orderLine.inventoryType", + "type": "string", + "required": false, + "source": "body", + "description": "库存类型,默认 ZP(正品)" + }, + { + "name": "[].orderLine.orderLineNo", + "type": "string", + "required": false, + "source": "body", + "description": "行号" + } + ], + "requestBody": [ + { + "name": "entryOrder", + "type": "object", + "required": true, + "source": "body", + "description": "入库单主信息对象" + }, + { + "name": "entryOrder.entryOrderCode", + "type": "string", + "required": true, + "source": "body", + "description": "入库单号(必填),外部系统的唯一入库单号" + }, + { + "name": "entryOrder.entryOrderType", + "type": "string", + "required": false, + "source": "body", + "description": "入库单类型,默认 SCRK(生产入库)" + }, + { + "name": "entryOrder.warehouseCode", + "type": "string", + "required": false, + "source": "body", + "description": "仓库编码" + }, + { + "name": "entryOrder.ownerCode", + "type": "string", + "required": false, + "source": "body", + "description": "货主编码" + }, + { + "name": "entryOrder.expectedArriveTime", + "type": "string", + "required": false, + "source": "body", + "description": "预计到货时间,ISO 8601 格式" + }, + { + "name": "entryOrder.totalOrderLines", + "type": "number", + "required": false, + "source": "body", + "description": "总行数" + }, + { + "name": "entryOrder.operateTime", + "type": "string", + "required": false, + "source": "body", + "description": "操作时间,ISO 8601 格式" + }, + { + "name": "entryOrder.operatorName", + "type": "string", + "required": false, + "source": "body", + "description": "操作人" + }, + { + "name": "entryOrder.supplierCode", + "type": "string", + "required": false, + "source": "body", + "description": "供应商编码" + }, + { + "name": "entryOrder.supplierName", + "type": "string", + "required": false, + "source": "body", + "description": "供应商名称" + }, + { + "name": "entryOrder.remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注" + }, + { + "name": "orderLines", + "type": "object", + "required": true, + "source": "body", + "description": "订单明细对象,包含 orderLine 数组" + }, + { + "name": "orderLines.orderLine", + "type": "array", + "required": true, + "source": "body", + "description": "商品明细列表,数组中每项为一个入库单行对象" + }, + { + "name": "[].orderLine.itemCode", + "type": "string", + "required": false, + "source": "body", + "description": "商品编码,与 itemId 二选一" + }, + { + "name": "[].orderLine.itemId", + "type": "number", + "required": false, + "source": "body", + "description": "仓库商品主键ID,与 itemCode 二选一,优先使用 itemId" + }, + { + "name": "[].orderLine.itemName", + "type": "string", + "required": false, + "source": "body", + "description": "商品名称" + }, + { + "name": "[].orderLine.planQty", + "type": "number", + "required": true, + "source": "body", + "description": "计划入库数量(必填),必须大于 0" + }, + { + "name": "[].orderLine.inventoryType", + "type": "string", + "required": false, + "source": "body", + "description": "库存类型,默认 ZP(正品)" + }, + { + "name": "[].orderLine.orderLineNo", + "type": "string", + "required": false, + "source": "body", + "description": "行号" + } + ], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "业务码:1=成功,0=失败" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示消息" + }, + { + "name": "data", + "type": "object", + "required": false, + "description": "创建成功时返回 entryOrderId、entryOrderCode、status(CREATING=创建中明细行未全部插入,CREATED=已创建完成)、createTime" + } + ], + "errors": [ + { + "code": 400, + "message": "entryOrder.entryOrderCode 参数缺失" + }, + { + "code": 400, + "message": "orderLines.orderLine 参数缺失" + }, + { + "code": 400, + "message": "商品未同步推送到仓库" + } + ], + "notes": [ + "模块:entryorder 模块", + "方法部署位置:openapiMethods/entryorder.create", + "创建渠道固定为 API", + "orderLines.orderLine 支持单对象或数组格式", + "itemCode 与 itemId 二选一,优先使用 itemId", + "timestamp 时间戳时效校验:与服务器时间差不得超过 ±10 分钟(600 秒),否则返回 400" + ] + }, + { + "method": "entryorder.query", + "description": "entryorder 模块 查询入库单接口,根据入库单号返回入库单详情。返回的 status 字段可能为 CREATING/CREATED/PENDING/COMPLETED/CANCELLED。", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "entryOrderCode", + "type": "string", + "required": true, + "source": "body", + "description": "入库单号(必填),要查询的入库单号" + } + ], + "requestBody": [ + { + "name": "entryOrderCode", + "type": "string", + "required": true, + "source": "body", + "description": "入库单号(必填),要查询的入库单号" + } + ], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "业务码:1=成功,0=失败" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示消息" + }, + { + "name": "data", + "type": "object", + "required": false, + "description": "查询成功时返回 entryOrderCode、entryOrderId、status、entryOrderType、expectedArriveTime、supplierCode、supplierName、remark、createTime、operateTime、operatorName、warehouseCode、ownerCode、totalOrderLines、orderLines" + }, + { + "name": "data.orderLines", + "type": "array", + "required": false, + "description": "商品明细列表" + }, + { + "name": "[].orderLines.itemId", + "type": "number", + "required": false, + "description": "商品ID" + }, + { + "name": "[].orderLines.itemCode", + "type": "string", + "required": false, + "description": "商品编码" + }, + { + "name": "[].orderLines.itemName", + "type": "string", + "required": false, + "description": "商品名称" + }, + { + "name": "[].orderLines.planQty", + "type": "number", + "required": false, + "description": "计划入库数量" + }, + { + "name": "[].orderLines.actualQty", + "type": "number", + "required": false, + "description": "实际入库数量" + }, + { + "name": "[].orderLines.inventoryType", + "type": "string", + "required": false, + "description": "库存类型" + }, + { + "name": "[].orderLines.orderLineNo", + "type": "string", + "required": false, + "description": "行号" + } + ], + "errors": [ + { + "code": 400, + "message": "entryOrderCode 参数缺失" + }, + { + "code": 404, + "message": "入库单未找到" + } + ], + "notes": [ + "模块:entryorder 模块", + "方法部署位置:openapiMethods/entryorder.query", + "timestamp 时间戳时效校验:与服务器时间差不得超过 ±10 分钟(600 秒),否则返回 400" + ] + } + ] } ] } diff --git a/methods/system.json b/methods/system.json index d8518ef..0ca3c7a 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1,8 +1,8 @@ { "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", - "version": "0.3.6", - "updatedAt": "2026-06-16", + "version": "0.3.7", + "updatedAt": "2026-06-23", "headers": [ { "name": "platform", @@ -2288,89 +2288,9 @@ } ] }, - { - "method": "order.bindExpressPackageMaterialByWaybill", - "description": "按运单号绑定包材。仅需传入运单号与包材编码,系统自动根据运单号反查对应订单运单记录并绑定包材,无需传入订单ID。", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "waybill_code", - "type": "string", - "required": true, - "source": "body", - "description": "运单号,必填。" - }, - { - "name": "package_material_code", - "type": "string", - "required": true, - "source": "body", - "description": "包材编码,必填。" - } - ], - "response": [ - { - "name": "order_id", - "type": "number", - "required": true, - "description": "运单号对应的订单ID(成功时返回于 data 对象中)。" - }, - { - "name": "waybill_code", - "type": "string", - "required": true, - "description": "运单号(成功时返回于 data 对象中)。" - }, - { - "name": "package_material_id", - "type": "number", - "required": true, - "description": "绑定后的包材ID(成功时返回于 data 对象中)。" - }, - { - "name": "package_material_name_snapshot", - "type": "string", - "required": true, - "description": "绑定时写入的包材名称快照(成功时返回于 data 对象中)。" - }, - { - "name": "package_material_code", - "type": "string", - "required": true, - "description": "绑定成功的包材编码(成功时返回于 data 对象中)。" - } - ], - "errors": [ - { - "code": 400, - "message": "参数错误" - }, - { - "code": 404, - "message": "运单号不存在" - }, - { - "code": 404, - "message": "包材编码不存在" - }, - { - "code": 500, - "message": "绑定包材失败" - } - ] - }, { "method": "order.export", - "description": "提交订单导出任务(异步)。入参支持 table_type/tableType 与 module/module_name;where 与 sort 语义与 order.list 一致。提交后立即返回 task_id,后台异步执行,导出进度/下载请通过 order.exportTaskProgress 查询。", + "description": "提交订单导出任务(异步)。入参支持 table_type/tableType、module/module_name、export_mode/exportMode;where 与 sort 语义与 order.list 一致。提交后立即返回 task_id,后台异步执行,导出进度/下载请通过 order.exportTaskProgress 查询。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -2409,6 +2329,13 @@ "required": false, "source": "body", "description": "排序参数,语义与 order.list 的 sort 一致" + }, + { + "name": "export_mode / exportMode", + "type": "string", + "required": false, + "source": "body", + "description": "导出模式:waybill(默认,按运单展开,items_detail 列汇总商品)或 item(按商品明细展开,每商品一行);支持 export_mode 与 exportMode 两种写法" } ], "response": [ @@ -5003,7 +4930,7 @@ "list": [ { "method": "order.recheckOrder.scanOrder", - "description": "扫描关键词并返回以波次为单位的复核视图。支持运单号、波次号、车号三种匹配模式。运单号/波次号命中(散单)返回扁平化订单列表 list_type='single',车号命中(团单)返回嵌套波次结构 list_type='group'。运单号命中但订单无波次信息时,退回单订单详情模式(list 每项含 detail/items/expresses/logs)。", + "description": "扫描关键词并返回以波次为单位的复核视图。支持运单号、波次号、车号三种匹配模式。运单号/波次号命中(散单)返回扁平化订单列表 list_type='single',车号命中(团单)返回嵌套波次结构 list_type='group'。运单号命中但订单无波次信息时,退回单订单详情模式(list 每项含 detail/items/expresses/logs)。所有模式的 list[] 每项均附带 items_weight(订单商品总重量)与 suggested_package_material(推荐包材信息,无推荐时为 null)。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -5118,7 +5045,7 @@ "name": "list", "type": "array", "required": true, - "description": "统一列表输出。散单模式(list_type=single)有波次信息时:扁平订单数组;无波次信息时退回单订单详情模式(每项含 detail、items、expresses、logs)。团购模式(list_type=group):波次视图数组(每项含 wave_id、wave_no、wave_type、wave_status、total_orders、processed_orders、creator、create_time、update_time、order_count、pick_mode、box_no、order_ids、orders_detail、stocks[])", + "description": "统一列表输出。散单模式(list_type=single)有波次信息时:扁平订单数组;无波次信息时退回单订单详情模式(每项含 detail、items、expresses、logs)。团购模式(list_type=group):波次视图数组(每项含 wave_id、wave_no、wave_type、wave_status、total_orders、processed_orders、creator、create_time、update_time、order_count、pick_mode、box_no、order_ids、orders_detail、stocks[])。所有模式的 list[] 每项均附带 items_weight(订单商品总重量,单位 kg)与 suggested_package_material(推荐包材信息,无推荐时为 null)。", "children": [ { "name": "order_id", @@ -5490,6 +5417,68 @@ "description": "商品库存明细(结构同散单模式)" } ] + }, + { + "name": "items_weight", + "type": "number|null", + "description": "[全模式] 订单商品总重量(kg),来源于 wms_order_delivery.items_weight。散单模式每个订单对象包含,团购模式每个波次对象包含(取波次内首个正常订单的重量)" + }, + { + "name": "suggested_package_material", + "type": "object|null", + "description": "[全模式] 推荐包材信息。根据订单商品结构(items_hash + items_crc)匹配 wms_package_material_item_relation 历史绑定记录,按 bind_count 降序取最优匹配。若 items_hash 为空或无匹配记录则为 null。散单模式每个订单对象包含,团购模式每个波次对象包含;团购模式以波次内首个正常订单的商品指纹匹配包材推荐", + "children": [ + { + "name": "id", + "type": "number", + "description": "包材ID(wms_package_material.id)" + }, + { + "name": "code", + "type": "string", + "description": "包材编码" + }, + { + "name": "name", + "type": "string", + "description": "包材名称" + }, + { + "name": "spec", + "type": "string", + "description": "包材规格" + }, + { + "name": "type", + "type": "string", + "description": "包材类型" + }, + { + "name": "weight", + "type": "number", + "description": "包材自身重量(kg)" + }, + { + "name": "length", + "type": "number", + "description": "长(cm)" + }, + { + "name": "width", + "type": "number", + "description": "宽(cm)" + }, + { + "name": "height", + "type": "number", + "description": "高(cm)" + }, + { + "name": "bind_count", + "type": "number", + "description": "历史绑定次数(推荐排序依据)" + } + ] } ] } @@ -7890,6 +7879,43 @@ "name": "create_time", "type": "string", "description": "创建时间(ISO 字符串,兼容字段)" + }, + { + "name": "wave_list", + "type": "array", + "description": "关联波次列表(通过 wms_wave_pick_task_wave 关联查询,按 id 升序排列)", + "children": [ + { + "name": "wave_id", + "type": "number", + "description": "波次ID" + }, + { + "name": "wave_no", + "type": "string", + "description": "波次号" + }, + { + "name": "box_no", + "type": "number", + "description": "框号" + }, + { + "name": "status", + "type": "number", + "description": "波次关联状态:0-待拣 1-已拣 2-异常" + }, + { + "name": "bind_time", + "type": "string", + "description": "绑定时间(ISO 字符串)" + }, + { + "name": "pick_time", + "type": "string", + "description": "拣货完成时间(ISO 字符串)" + } + ] } ] }, @@ -15669,7 +15695,7 @@ }, { "method": "stock.warehouse.search", - "description": "仓库商品关键字搜索,按 item_code / item_name / goods_code / 条形码模糊匹配,最多返回 50 条", + "description": "仓库商品关键字搜索,按 item_code / item_name / goods_code / 条形码模糊匹配,最多返回 50 条。新增 mode=\"combo\" 时切换为组合商品搜索模式。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -15686,7 +15712,7 @@ "type": "string", "required": false, "source": "body", - "description": "搜索关键字,模糊匹配 item_code、item_name、goods_code 以及关联的 barcode;为空时返回全部(仍受 limit 50 限制)" + "description": "搜索关键字,模糊匹配 item_code、item_name、goods_code 以及关联的 barcode;为空时返回全部(仍受 limit 50 限制)。mode=\"combo\" 时模糊匹配 combo_code / combo_name / custom_code" }, { "name": "store_id", @@ -15695,13 +15721,34 @@ "source": "body", "description": "货主ID,传入时仅返回指定货主的商品" }, + { + "name": "mode", + "type": "string", + "required": false, + "source": "body", + "description": "查询模式。传 \"combo\" 时搜索组合商品,不传或为空时保持原有 stock 搜索行为" + }, + { + "name": "id", + "type": "number", + "required": false, + "source": "body", + "description": "当 mode=\"combo\" 时,按组合商品ID精确查询" + }, + { + "name": "custom_code", + "type": "string", + "required": false, + "source": "body", + "description": "当 mode=\"combo\" 时,按自定义编码模糊查询" + }, { "name": "with_stock", "type": "boolean", "required": false, "source": "body", "default": false, - "description": "是否返回关联库存数据(wms_storage),为 true 时每条商品新增 storage[] 字段" + "description": "是否返回关联库存数据(wms_storage),为 true 时每条商品新增 storage[] 字段。注意:mode=\"combo\" 时不生效" }, { "name": "is_batch", @@ -15709,141 +15756,215 @@ "required": false, "source": "body", "default": false, - "description": "是否按批次明细返回库存,仅 with_stock=true 时生效。false(默认)按库位分组汇总;true 逐条返回批次明细" + "description": "是否按批次明细返回库存,仅 with_stock=true 时生效。false(默认)按库位分组汇总;true 逐条返回批次明细。注意:mode=\"combo\" 时不生效" } ], "response": [ { "name": "code", "type": "number", - "description": "业务状态码,200 表示成功" + "description": "业务状态码,200 表示成功", + "required": false }, { "name": "data", "type": "array", - "description": "商品列表,每项包含以下字段", + "description": "商品列表,每项包含以下字段。mode=\"combo\" 时返回组合商品结构", "children": [ { "name": "id", "type": "number", - "description": "商品库存ID(stock_warehouse.id)" + "description": "商品库存ID(stock_warehouse.id)。mode=\"combo\" 时返回组合商品ID", + "required": false }, { "name": "item_code", "type": "string", - "description": "商品编码" + "description": "商品编码。mode=\"combo\" 时不返回此字段", + "required": false }, { "name": "goods_code", "type": "string", - "description": "货物编码" + "description": "货物编码。mode=\"combo\" 时不返回此字段", + "required": false }, { "name": "item_name", "type": "string", - "description": "商品名称" + "description": "商品名称。mode=\"combo\" 时不返回此字段", + "required": false }, { "name": "sku_property", "type": "string", - "description": "SKU 规格" + "description": "SKU 规格。mode=\"combo\" 时不返回此字段", + "required": false }, { "name": "stock_unit", "type": "string", - "description": "库存单位" + "description": "库存单位。mode=\"combo\" 时不返回此字段", + "required": false }, { "name": "quantity", "type": "number", - "description": "库存数量" + "description": "库存数量。mode=\"combo\" 时不返回此字段", + "required": false }, { "name": "locked_quantity", "type": "number", - "description": "锁定数量" + "description": "锁定数量。mode=\"combo\" 时不返回此字段", + "required": false }, { "name": "brand_name", "type": "string", - "description": "品牌名称" + "description": "品牌名称。mode=\"combo\" 时不返回此字段", + "required": false }, { "name": "item_type", "type": "string", - "description": "商品类型" + "description": "商品类型。mode=\"combo\" 时不返回此字段", + "required": false }, { "name": "barcodes", "type": "array", - "description": "商品条形码列表(string[])" + "description": "商品条形码列表(string[])。mode=\"combo\" 时不返回此字段", + "required": false }, { "name": "store_stock", "type": "object", - "description": "关联的货主签约信息(LEFT JOIN),含 store_id、store_remask;无签约时为 null" + "description": "关联的货主签约信息(LEFT JOIN),含 store_id、store_remask;无签约时为 null。mode=\"combo\" 时不返回此字段", + "required": false }, { "name": "is_shelf_life_mgmt", "type": "boolean", - "description": "是否启用效期管理(true=启用)" + "description": "是否启用效期管理(true=启用)。mode=\"combo\" 时不返回此字段", + "required": false }, { "name": "shelf_life_days", "type": "number", - "description": "商品标准效期/保质期(单位:天)" + "description": "商品标准效期/保质期(单位:天)。mode=\"combo\" 时不返回此字段", + "required": false }, { "name": "inbound_min_days", "type": "number", - "description": "入库后最小可出库天数(单位:天)" + "description": "入库后最小可出库天数(单位:天)。mode=\"combo\" 时不返回此字段", + "required": false }, { "name": "outbound_min_days", "type": "number", - "description": "出库前需保留的最小天数(单位:天)" + "description": "出库前需保留的最小天数(单位:天)。mode=\"combo\" 时不返回此字段", + "required": false }, { "name": "remaining_threshold_days", "type": "number", - "description": "剩余天数阈值,低于该值视为即将过期(单位:天)" + "description": "剩余天数阈值,低于该值视为即将过期(单位:天)。mode=\"combo\" 时不返回此字段", + "required": false + }, + { + "name": "combo_code", + "type": "string", + "description": "组合商品编码,仅 mode=\"combo\" 时返回", + "required": false + }, + { + "name": "combo_name", + "type": "string", + "description": "组合商品名称,仅 mode=\"combo\" 时返回", + "required": false + }, + { + "name": "custom_code", + "type": "string", + "description": "自定义编码,仅 mode=\"combo\" 时返回", + "required": false + }, + { + "name": "items", + "type": "array", + "description": "子商品数组,仅 mode=\"combo\" 时返回。每项含 item_goods_sku_id(子商品ID)、item_quantity(子商品数量)", + "children": [ + { + "name": "item_goods_sku_id", + "type": "number", + "description": "子商品SKU ID", + "required": false + }, + { + "name": "item_quantity", + "type": "number", + "description": "子商品数量", + "required": false + } + ], + "required": false + }, + { + "name": "simpleNotation", + "type": "string", + "description": "子商品简写表示,格式为 stock_id|数量,多条用换行分隔。仅 mode=\"combo\" 时返回", + "required": false + }, + { + "name": "nameNotation", + "type": "string", + "description": "子商品名称表示,格式为【数量】商品名称,多条用换行分隔。仅 mode=\"combo\" 时返回", + "required": false }, { "name": "storage", "type": "array", - "description": "关联库存明细,仅 with_stock=true 时返回。is_batch=false 时按库位分组汇总,is_batch=true 时逐条返回批次明细", + "description": "关联库存明细,仅 with_stock=true 时返回。is_batch=false 时按库位分组汇总,is_batch=true 时逐条返回批次明细。注意:mode=\"combo\" 时不返回", "children_grouped": { "description": "is_batch=false(默认):按库位分组汇总,每条包含以下字段", "fields": [ { "name": "space_id", "type": "number", - "description": "库位ID" + "description": "库位ID", + "required": false }, { "name": "inventory_type", "type": "string", - "description": "库存类型" + "description": "库存类型", + "required": false }, { "name": "quantity", "type": "number", - "description": "该库位总库存数量(合并同库位)" + "description": "该库位总库存数量(合并同库位)", + "required": false }, { "name": "locked_quantity", "type": "number", - "description": "该库位总锁定数量" + "description": "该库位总锁定数量", + "required": false }, { "name": "available_quantity", "type": "number", - "description": "可用数量(quantity - locked_quantity)" + "description": "可用数量(quantity - locked_quantity)", + "required": false }, { "name": "space", "type": "object", - "description": "库位信息子对象,含 id、space_code、custom_name" + "description": "库位信息子对象,含 id、space_code、custom_name", + "required": false } ] }, @@ -15853,87 +15974,105 @@ { "name": "id", "type": "number", - "description": "storage 记录ID" + "description": "storage 记录ID", + "required": false }, { "name": "stock_id", "type": "number", - "description": "关联的商品库存ID" + "description": "关联的商品库存ID", + "required": false }, { "name": "space_id", "type": "number", - "description": "库位ID" + "description": "库位ID", + "required": false }, { "name": "batch_no", "type": "string", - "description": "批次号" + "description": "批次号", + "required": false }, { "name": "inventory_type", "type": "string", - "description": "库存类型" + "description": "库存类型", + "required": false }, { "name": "quantity", "type": "number", - "description": "库存数量" + "description": "库存数量", + "required": false }, { "name": "locked_quantity", "type": "number", - "description": "锁定数量" + "description": "锁定数量", + "required": false }, { "name": "available_quantity", "type": "number", - "description": "可用数量" + "description": "可用数量", + "required": false }, { "name": "production_date", "type": "string", - "description": "生产日期" + "description": "生产日期", + "required": false }, { "name": "expiry_date", "type": "string", - "description": "过期日期" + "description": "过期日期", + "required": false }, { "name": "inbound_time", "type": "string", - "description": "入库时间" + "description": "入库时间", + "required": false }, { "name": "inbound_order_no", "type": "string", - "description": "入库单号" + "description": "入库单号", + "required": false }, { "name": "supplier_batch_no", "type": "string", - "description": "供应商批次号" + "description": "供应商批次号", + "required": false }, { "name": "created_at", "type": "string", - "description": "记录创建时间" + "description": "记录创建时间", + "required": false }, { "name": "space", "type": "object", - "description": "库位信息子对象,含 id、space_code、custom_name" + "description": "库位信息子对象,含 id、space_code、custom_name", + "required": false } ] - } + }, + "required": false } - ] + ], + "required": false }, { "name": "total", "type": "number", - "description": "本次返回的记录条数(≤50)" + "description": "本次返回的记录条数(≤50)", + "required": false } ], "errors": [] @@ -18656,16 +18795,181 @@ "完成收货时会发送通知:通知 payload 或 metadata 将在每条明细中携带 box_remainder(箱内剩余数量/零散件数,number)与 box_weight(实测箱重,number,单位同系统重量,例如 kg)。新增字段为可选,旧客户端可忽略。" ], "errors": [] + }, + { + "method": "storage.receiving.manualMatchEntryOrder", + "description": "手动匹配入库单与收货单。传入收货单ID和入库单ID,复用异步匹配服务的明细对比和回传逻辑,同步返回匹配结果(含 matchType、comparisonResult、callbackSent、partialStorageMarked 等)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "receivingId", + "type": "number", + "required": true, + "source": "body", + "description": "收货单 ID" + }, + { + "name": "entryOrderId", + "type": "number", + "required": true, + "source": "body", + "description": "入库单 ID" + } + ], + "response": [ + { + "name": "matchType", + "type": "string", + "required": true, + "description": "匹配类型枚举:full_match(SKU+数量完全一致)/ receiving_covers_entry(收货单覆盖入库单,触发回传+标记部分入库)/ entry_exceeds_receiving(入库单超出收货单,不触发回传)/ no_match(SKU无交集,不触发回传)" + }, + { + "name": "comparisonResult", + "type": "object", + "required": true, + "description": "明细对比结果对象", + "children": [ + { + "name": "type", + "type": "string", + "required": true, + "description": "匹配类型(同 matchType)" + }, + { + "name": "matchedDetails", + "type": "array", + "required": true, + "description": "匹配明细列表,每项含 detailId、system_product_id、actual_quantity、stored_quantity、entryCount、overage" + } + ] + }, + { + "name": "callbackSent", + "type": "boolean", + "required": true, + "description": "是否已发送回传(full_match / receiving_covers_entry 时为 true)" + }, + { + "name": "callbackResult", + "type": "object|null", + "required": true, + "description": "回传结果对象(未发送时为 null);成功时含 success、sourceType(QM/API)、detail 字段" + }, + { + "name": "partialStorageMarked", + "type": "boolean", + "required": true, + "description": "是否已标记部分入库(仅 receiving_covers_entry 时为 true)" + }, + { + "name": "entryOrder", + "type": "object", + "required": true, + "description": "入库单摘要信息", + "children": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "入库单 ID" + }, + { + "name": "entry_order_code", + "type": "string", + "required": true, + "description": "入库单号" + }, + { + "name": "source_type", + "type": "string", + "required": true, + "description": "来源类型(QM/API)" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "仓库 ID" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "入库单状态" + } + ] + }, + { + "name": "receivingOrder", + "type": "object", + "required": true, + "description": "收货单摘要信息", + "children": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "收货单 ID" + }, + { + "name": "receiving_number", + "type": "string", + "required": true, + "description": "收货单号" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "收货单状态" + }, + { + "name": "storage_status", + "type": "string", + "required": true, + "description": "入库状态(如 un_stored)" + } + ] + } + ], + "errors": [ + { + "code": 400, + "message": "入库单不存在:{entryOrderId}" + }, + { + "code": 400, + "message": "收货单不存在:{receivingId}" + }, + { + "code": 400, + "message": "入库单仓库({a})与收货单仓库({b})不一致" + } + ], + "notes": [ + "matchType 为 full_match 或 receiving_covers_entry 时触发回传(调用 _sendCallback),receiving_covers_entry 额外调用 _markReceivingPartialStorage 标记部分入库", + "matchType 为 entry_exceeds_receiving 或 no_match 时不触发回传,仅返回对比结果", + "不检查特定 API 权限,登录用户即可调用(_noNeedAuth=manualMatchEntryOrder)" + ] } ] }, { - "groupName": "入库单模块", + "groupName": "入库单管理模块", "module": "storage.entry", "list": [ { "method": "storage.entry.list", - "description": "入库单列表查询", + "description": "入库单列表查询。where.order_status 支持 CREATING/CREATED/PENDING/COMPLETED/CANCELLED。CREATED=已创建待审核(需审核后才能绑定和完成入库),PENDING=已审核(可绑定和完成入库)。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -18689,7 +18993,7 @@ "type": "object", "required": false, "source": "body", - "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会在 main 中自动标准化;支持 quickWhere、order_status、store_id、order_type、日期区间等字段。新增 expense_record(费用是否记录)筛选,支持 eq/in;值会归一化为 0/1,兼容 true/false、1/0、y/n、yes/no(大小写不敏感,含布尔/字符串/数字写法)。示例:where.expense_record={operator:eq,value:true} 等价 where.expense_record={operator:eq,value:1};where.expense_record={operator:in,value:[true,\"0\",\"yes\",\"n\"]} 会归一化为 [1,0]。若部署环境尚未完成 expense_record 字段迁移,传入该筛选可能返回 400,错误提示为“当前环境未提供 expense_record 字段,暂不支持该筛选条件,请先完成表结构升级”。" + "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会在 main 中自动标准化;支持 quickWhere、order_status(CREATING/CREATED/PENDING/COMPLETED/CANCELLED)、store_id、order_type、日期区间等字段。新增 expense_record(费用是否记录)筛选,支持 eq/in;值会归一化为 0/1,兼容 true/false、1/0、y/n、yes/no(大小写不敏感,含布尔/字符串/数字写法)。示例:where.expense_record={operator:eq,value:true} 等价 where.expense_record={operator:eq,value:1};where.expense_record={operator:in,value:[true,\"0\",\"yes\",\"n\"]} 会归一化为 [1,0]。若部署环境尚未完成 expense_record 字段迁移,传入该筛选可能返回 400,错误提示为\"当前环境未提供 expense_record 字段,暂不支持该筛选条件,请先完成表结构升级\"。" }, { "name": "sort", @@ -18734,7 +19038,7 @@ }, { "method": "storage.entry.get", - "description": "查询入库单详情", + "description": "查询入库单详情。返回的 entryOrder 包含顶层 receivingBindings(主表级关联,含关联的收货单信息),不再返回 items[].bindings(明细级绑定)。entryOrder.order_status 可能为 CREATING/CREATED/PENDING/COMPLETED/CANCELLED。CREATED=已创建待审核(需审核后才能绑定和完成入库),PENDING=已审核(可绑定和完成入库)。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -18766,23 +19070,27 @@ "name": "entryOrder", "type": "object", "required": true, - "description": "入库单详情(含 items 明细)" + "description": "入库单详情,包含 items 数组(每项含 external_item_code/external_item_id/warehouse_item_code/warehouse_item_name/warehouse_item_spec 等字段)、receivingBindings(主表级收货单关联数组,每项含 id/receiving_id/receiving,其中 receiving 含 id/receiving_number/status/storage_status/created_at)" } ], "errors": [ { "code": "400", - "description": "id 与 entry_order_code 均未传" + "message": "参数错误:id 与 entry_order_code 至少提供一个" }, { - "code": "0", - "description": "无记录或无权访问" + "code": "404", + "message": "入库单不存在" + }, + { + "code": "500", + "message": "查询失败" } ] }, { "method": "storage.entry.cancel", - "description": "作废入库单(支持单条或批量作废)", + "description": "作废入库单(支持单条或批量作废)。CREATED(已创建待审核)和 PENDING(已审核)状态的入库单可以直接作废;已完成(COMPLETED)入库单不允许作废。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -18799,14 +19107,14 @@ "type": "number", "required": false, "source": "body", - "description": "入库单ID,兼容旧调用;与 `ids` 二选一。若同时传入 `ids`,以 `ids` 为准。" + "description": "入库单ID,兼容旧调用;与 ids 二选一。若同时传入 ids,以 ids 为准。" }, { "name": "ids", "type": "array", "required": false, "source": "body", - "description": "入库单ID数组(number[]),用于批量作废;必须为非空数组,建议批量操作使用 `ids`,优先于 `id`。" + "description": "入库单ID数组(number[]),用于批量作废;必须为非空数组,建议批量操作使用 ids,优先于 id。" } ], "response": [ @@ -18826,17 +19134,337 @@ "errors": [ { "code": "400", - "description": "参数错误/参数不合法:需传入非空的 `id` 或 `ids`;`ids` 必须为数字数组且不得包含非法或重复值" + "message": "参数错误/参数不合法:需传入非空的 id 或 ids;ids 必须为数字数组且不得包含非法或重复值;已完成(COMPLETED)入库单不允许作废" }, { "code": "404", - "description": "入库单不存在或无权访问" + "message": "入库单不存在或无权访问" } ] }, { "method": "storage.entry.completeEntry", - "description": "完成入库单", + "description": "完成入库单。仅将入库单状态从 PENDING 变更为 COMPLETED,不涉及库存写入(库存写入统一由 storage.entry.commitDirectInbound 完成)。仅 PENDING(已审核)状态可完成;CREATED(已创建待审核)状态需先审核(→PENDING)后再完成;CANCELLED(已作废)状态不允许完成。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "entry_order_id", + "type": "number", + "required": true, + "source": "body", + "description": "入库单ID" + } + ], + "response": [ + { + "name": "entry_order_id", + "type": "number", + "required": true, + "description": "入库单ID" + }, + { + "name": "order_status", + "type": "string", + "required": true, + "description": "入库单状态,完成时为 COMPLETED" + } + ], + "errors": [ + { + "code": 400, + "message": "当前入库单状态不允许完成(仅 PENDING 状态可完成)" + }, + { + "code": 404, + "message": "入库单不存在或无权访问" + } + ] + }, + { + "method": "storage.entry.getDirectInboundItems", + "description": "获取入库单的导入/PDA 入库信息,返回入库单基本信息、明细列表,以及每项明细已有的导入/PDA 入库记录(含汇总和剩余可入库数量)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "entry_order_code", + "type": "string", + "required": true, + "source": "body", + "description": "入库单号" + } + ], + "response": [ + { + "name": "entryOrder", + "type": "object", + "required": true, + "description": "入库单基本信息(id、entry_order_code、order_type、order_status、source_type、warehouse_id、store_id、remark)" + }, + { + "name": "items", + "type": "array", + "required": true, + "description": "入库明细列表,每项含 id、stock_id、count(计划数量)、received_quantity、direct_inbound_quantity(已导入/PDA入库数量)、remaining_quantity(剩余可入库数量)、pending_binding_total(pending 绑定总量)、bindings(pending 绑定列表,同 storage.entry.get 结构)、direct_logs(已有入库记录)" + }, + { + "name": "direct_logs", + "type": "array", + "required": true, + "description": "该入库单下所有导入/PDA 入库记录(含 space_id)" + }, + { + "name": "summary", + "type": "object", + "required": true, + "description": "汇总信息(total_items、total_planned、total_direct_inbound)" + } + ], + "errors": [ + { + "code": 400, + "message": "entry_order_code 必填" + }, + { + "code": 404, + "message": "入库单不存在或无权访问" + } + ] + }, + { + "method": "storage.entry.addDirectInboundItem", + "description": "按商品增量添加导入/PDA 入库记录(支持单条和批量)。单条模式传 stock_id/quantity/inbound_type/remark,批量模式传 items 数组。批量模式所有商品共享同一个入库单状态校验,任一商品校验失败整批拒绝。若某商品累计入库量超过计划数量则拒绝。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "entry_order_code", + "type": "string", + "required": true, + "source": "body", + "description": "入库单号" + }, + { + "name": "stock_id", + "type": "number", + "required": true, + "source": "body", + "description": "商品SKU ID(对应 wms_stock_warehouse.id)" + }, + { + "name": "quantity", + "type": "number", + "required": true, + "source": "body", + "description": "本次入库数量(正整数)" + }, + { + "name": "inbound_type", + "type": "string", + "required": true, + "source": "body", + "description": "入库方式:import(导入入库)、pda(PDA入库)" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注(如导入文件名、PDA操作备注等)" + }, + { + "name": "space_id", + "type": "number", + "required": false, + "source": "body", + "description": "存放库位ID(单条模式),关联 wms_location_space.id;为空时 commit 默认使用库位 1" + }, + { + "name": "items", + "type": "array", + "required": false, + "source": "body", + "description": "批量模式:商品列表,每项包含 stock_id(商品SKU ID, number, 必填)、quantity(入库数量, number, 必填)、inbound_type(import/pda, string, 必填)、space_id(库位ID, number, 可选)、remark(备注, string, 可选)。传入 items 时忽略顶层的 stock_id/quantity/inbound_type/remark/space_id。" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": false, + "description": "单条模式返回:新增的入库记录ID" + }, + { + "name": "stock_id", + "type": "number", + "required": false, + "description": "单条模式返回:商品SKU ID" + }, + { + "name": "quantity", + "type": "number", + "required": false, + "description": "单条模式返回:本次入库数量" + }, + { + "name": "inbound_type", + "type": "string", + "required": false, + "description": "单条模式返回:入库方式" + }, + { + "name": "plan_quantity", + "type": "number", + "required": false, + "description": "单条模式返回:该商品计划入库总数" + }, + { + "name": "existing_before", + "type": "number", + "required": false, + "description": "单条模式返回:本次入库前已入库数量" + }, + { + "name": "existing_after", + "type": "number", + "required": false, + "description": "单条模式返回:本次入库后总入库数量" + }, + { + "name": "remaining", + "type": "number", + "required": false, + "description": "单条模式返回:剩余可入库数量" + }, + { + "name": "count", + "type": "number", + "required": false, + "description": "批量模式返回:成功添加的条目数" + }, + { + "name": "total_quantity", + "type": "number", + "required": false, + "description": "批量模式返回:入库总数量" + }, + { + "name": "items", + "type": "array", + "required": false, + "description": "批量模式返回:入库结果列表,每项包含 id/stock_id/quantity/inbound_type/space_id/plan_quantity/existing_before/existing_after/remaining" + } + ], + "errors": [ + { + "code": 400, + "message": "参数校验失败:entry_order_code 必填 / stock_id 必填 / quantity 必须为正整数 / inbound_type 必须为 import 或 pda / 已作废入库单不允许操作 / 已完成的入库单不允许操作 / 入库单中不存在该 stock_id 的商品 / 入库数量超过计划" + }, + { + "code": 404, + "message": "入库单不存在或无权访问" + } + ] + }, + { + "method": "storage.entry.commitDirectInbound", + "description": "提交确认完成导入/PDA 入库。按实收数量写入库存(wms_storage、wms_stock_transaction),未入库商品跳过不做处理,更新入库单状态为 COMPLETED,并异步触发奇门/API 入库完成回传(按实收数量回传)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "entry_order_code", + "type": "string", + "required": true, + "source": "body", + "description": "入库单号" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "入库单ID" + }, + { + "name": "entry_order_code", + "type": "string", + "required": true, + "description": "入库单号" + }, + { + "name": "order_status", + "type": "string", + "required": true, + "description": "入库单状态(固定为 COMPLETED)" + }, + { + "name": "sync_status", + "type": "string", + "required": true, + "description": "同步状态(固定为 SUCCESS)" + }, + { + "name": "items_count", + "type": "number", + "required": true, + "description": "入库商品种类数" + }, + { + "name": "total_quantity", + "type": "number", + "required": true, + "description": "入库总数量" + } + ], + "errors": [ + { + "code": 400, + "message": "参数校验失败:entry_order_code 必填 / 已作废入库单不允许完成 / 入库单已完成请勿重复提交 / 暂无导入/PDA 入库记录 / 入库单无明细 / 库存写入异常" + }, + { + "code": 404, + "message": "入库单不存在或无权访问" + } + ] + }, + { + "method": "storage.entry.removeDirectInboundItem", + "description": "移除一条导入/PDA 入库记录(仅限未提交的入库单,即状态非 CANCELLED/COMPLETED)。移除后该商品的可入库余量自动恢复。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -18853,7 +19481,7 @@ "type": "number", "required": true, "source": "body", - "description": "入库单ID" + "description": "入库记录ID(wms_inbound_direct_log.id)" } ], "response": [ @@ -18861,17 +19489,373 @@ "name": "id", "type": "number", "required": true, - "description": "完成成功的入库单ID" + "description": "已移除的入库记录ID" + }, + { + "name": "stock_id", + "type": "number", + "required": true, + "description": "商品SKU ID" + }, + { + "name": "quantity", + "type": "number", + "required": true, + "description": "移除的入库数量" + }, + { + "name": "inbound_type", + "type": "string", + "required": true, + "description": "入库方式" } ], "errors": [ { - "code": "400", - "description": "参数不合法、已作废或缺少明细" + "code": 400, + "message": "id 必填 / 已作废入库单不允许操作 / 已完成的入库单不允许移除记录" }, { - "code": "404", - "description": "入库单不存在或无权访问" + "code": 404, + "message": "入库记录不存在 / 关联入库单不存在或无权访问" + } + ] + } + ] + }, + { + "groupName": "导入/PDA入库模块", + "module": "storage.directInbound", + "list": [ + { + "method": "storage.directInbound.getItems", + "description": "[@deprecated 已弃用,请使用 storage.entry.getDirectInboundItems 替代] 获取入库单的导入/PDA 入库信息,返回入库单基本信息、明细列表,以及每项明细已有的导入/PDA 入库记录(含汇总和剩余可入库数量)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "entry_order_code", + "type": "string", + "required": true, + "source": "body", + "description": "入库单号" + } + ], + "response": [ + { + "name": "entryOrder", + "type": "object", + "required": true, + "description": "入库单基本信息(id、entry_order_code、order_type、order_status、source_type、warehouse_id、store_id、remark)" + }, + { + "name": "items", + "type": "array", + "required": true, + "description": "入库明细列表,每项含 id、stock_id、count(计划数量)、received_quantity、direct_inbound_quantity(已导入/PDA入库数量)、remaining_quantity(剩余可入库数量)、pending_binding_total(pending 绑定总量)、bindings(pending 绑定列表,同 storage.entry.get 结构)、direct_logs(已有入库记录)" + }, + { + "name": "direct_logs", + "type": "array", + "required": true, + "description": "该入库单下所有导入/PDA 入库记录(含 space_id)" + }, + { + "name": "summary", + "type": "object", + "required": true, + "description": "汇总信息(total_items、total_planned、total_direct_inbound)" + } + ], + "errors": [ + { + "code": 400, + "message": "entry_order_code 必填" + }, + { + "code": 404, + "message": "入库单不存在或无权访问" + } + ] + }, + { + "method": "storage.directInbound.addItem", + "description": "[@deprecated 已弃用,请使用 storage.entry.addDirectInboundItem 替代] 按商品增量添加导入/PDA 入库记录(支持单条和批量)。单条模式传 stock_id/quantity/inbound_type/remark,批量模式传 items 数组。批量模式所有商品共享同一个入库单状态校验,任一商品校验失败整批拒绝。若某商品累计入库量超过计划数量则拒绝。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "entry_order_code", + "type": "string", + "required": true, + "source": "body", + "description": "入库单号" + }, + { + "name": "stock_id", + "type": "number", + "required": true, + "source": "body", + "description": "商品SKU ID(对应 wms_stock_warehouse.id)" + }, + { + "name": "quantity", + "type": "number", + "required": true, + "source": "body", + "description": "本次入库数量(正整数)" + }, + { + "name": "inbound_type", + "type": "string", + "required": true, + "source": "body", + "description": "入库方式:import(导入入库)、pda(PDA入库)" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注(如导入文件名、PDA操作备注等)" + }, + { + "name": "space_id", + "type": "number", + "required": false, + "source": "body", + "description": "存放库位ID(单条模式),关联 wms_location_space.id;为空时 commit 默认使用库位 1" + }, + { + "name": "items", + "type": "array", + "required": false, + "source": "body", + "description": "批量模式:商品列表,每项包含 stock_id(商品SKU ID, number, 必填)、quantity(入库数量, number, 必填)、inbound_type(import/pda, string, 必填)、space_id(库位ID, number, 可选)、remark(备注, string, 可选)。传入 items 时忽略顶层的 stock_id/quantity/inbound_type/remark/space_id。" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": false, + "description": "单条模式返回:新增的入库记录ID" + }, + { + "name": "stock_id", + "type": "number", + "required": false, + "description": "单条模式返回:商品SKU ID" + }, + { + "name": "quantity", + "type": "number", + "required": false, + "description": "单条模式返回:本次入库数量" + }, + { + "name": "inbound_type", + "type": "string", + "required": false, + "description": "单条模式返回:入库方式" + }, + { + "name": "plan_quantity", + "type": "number", + "required": false, + "description": "单条模式返回:该商品计划入库总数" + }, + { + "name": "existing_before", + "type": "number", + "required": false, + "description": "单条模式返回:本次入库前已入库数量" + }, + { + "name": "existing_after", + "type": "number", + "required": false, + "description": "单条模式返回:本次入库后总入库数量" + }, + { + "name": "remaining", + "type": "number", + "required": false, + "description": "单条模式返回:剩余可入库数量" + }, + { + "name": "count", + "type": "number", + "required": false, + "description": "批量模式返回:成功添加的条目数" + }, + { + "name": "total_quantity", + "type": "number", + "required": false, + "description": "批量模式返回:入库总数量" + }, + { + "name": "items", + "type": "array", + "required": false, + "description": "批量模式返回:入库结果列表,每项包含 id/stock_id/quantity/inbound_type/space_id/plan_quantity/existing_before/existing_after/remaining" + } + ], + "errors": [ + { + "code": 400, + "message": "参数校验失败:entry_order_code 必填 / stock_id 必填 / quantity 必须为正整数 / inbound_type 必须为 import 或 pda / 已作废入库单不允许操作 / 已完成的入库单不允许操作 / 入库单中不存在该 stock_id 的商品 / 入库数量超过计划" + }, + { + "code": 404, + "message": "入库单不存在或无权访问" + } + ] + }, + { + "method": "storage.directInbound.commit", + "description": "[@deprecated 已弃用,请使用 storage.entry.commitDirectInbound 替代] 提交确认完成导入/PDA 入库。按实收数量写入库存(wms_storage、wms_stock_transaction),未入库商品跳过不做处理,更新入库单状态为 COMPLETED,并异步触发奇门/API 入库完成回传(按实收数量回传)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "entry_order_code", + "type": "string", + "required": true, + "source": "body", + "description": "入库单号" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "入库单ID" + }, + { + "name": "entry_order_code", + "type": "string", + "required": true, + "description": "入库单号" + }, + { + "name": "order_status", + "type": "string", + "required": true, + "description": "入库单状态(固定为 COMPLETED)" + }, + { + "name": "sync_status", + "type": "string", + "required": true, + "description": "同步状态(固定为 SUCCESS)" + }, + { + "name": "items_count", + "type": "number", + "required": true, + "description": "入库商品种类数" + }, + { + "name": "total_quantity", + "type": "number", + "required": true, + "description": "入库总数量" + } + ], + "errors": [ + { + "code": 400, + "message": "参数校验失败:entry_order_code 必填 / 已作废入库单不允许完成 / 入库单已完成请勿重复提交 / 暂无导入/PDA 入库记录 / 入库单无明细 / 库存写入异常" + }, + { + "code": 404, + "message": "入库单不存在或无权访问" + } + ] + }, + { + "method": "storage.directInbound.removeItem", + "description": "[@deprecated 已弃用,请使用 storage.entry.removeDirectInboundItem 替代] 移除一条导入/PDA 入库记录(仅限未提交的入库单,即状态非 CANCELLED/COMPLETED)。移除后该商品的可入库余量自动恢复。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "入库记录ID(wms_inbound_direct_log.id)" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "已移除的入库记录ID" + }, + { + "name": "stock_id", + "type": "number", + "required": true, + "description": "商品SKU ID" + }, + { + "name": "quantity", + "type": "number", + "required": true, + "description": "移除的入库数量" + }, + { + "name": "inbound_type", + "type": "string", + "required": true, + "description": "入库方式" + } + ], + "errors": [ + { + "code": 400, + "message": "id 必填 / 已作废入库单不允许操作 / 已完成的入库单不允许移除记录" + }, + { + "code": 404, + "message": "入库记录不存在 / 关联入库单不存在或无权访问" } ] } @@ -19056,146 +20040,18 @@ ] }, { - "groupName": "库存操作模块", + "groupName": "库存管理模块", "module": "storage.inventory", "list": [ { "method": "storage.inventory.quickPutaway", - "description": "收货单快捷入库上架。从收货单直接生成入库单并写入库存表,要求收货单已完成、已审核、货主已开启快捷入库策略且所有明细已匹配系统商品", + "description": "[已删除] 收货单快捷入库上架(此方法已从代码中移除)。原用于单一收货单的快速入库操作,现已弃用。请使用 storage.entry.commitDirectInbound 替代——commitDirectInbound 提供导入/PDA 入库完成确认功能,是目前唯一的库存写入入库链路。", "isNeedAuth": true, "isNeedLogin": true, - "params": [ - { - "name": "receiving_id", - "type": "number", - "required": true, - "source": "body", - "description": "收货单ID,兼容 id" - } - ], - "response": { - "receiving_id": "收货单ID", - "receiving_number": "收货单号", - "receiving_storage_status": "收货单入库状态(all/partial)", - "entry_order": { - "id": "自动创建的入库单ID", - "entry_order_code": "入库单号", - "order_status": "COMPLETED" - }, - "items": [ - { - "detail_id": "收货明细ID", - "product_name": "商品名称", - "stock_warehouse_id": "库存商品ID", - "inbound_quantity": "入库数量", - "space_id": "库位ID", - "storage_status": "明细入库状态" - } - ] - }, - "errors": [ - { - "code": 400, - "message": "receiving_id 必填" - }, - { - "code": 400, - "message": "收货单状态须为已完成" - }, - { - "code": 400, - "message": "收货单未审核,审核通过后才能入库" - }, - { - "code": 400, - "message": "货主xxxx不允许快速上架,如需开启请到:货主->策略配置调整" - }, - { - "code": 400, - "message": "商品未匹配系统商品" - }, - { - "code": 404, - "message": "收货单绑定的货主与当前仓库不存在有效签约关系" - }, - { - "code": 400, - "message": "已全部入库无需重复操作" - }, - { - "code": 404, - "message": "收货单不存在或无权访问" - }, - { - "code": 409, - "message": "库存记录被锁定(行锁超时)" - } - ] - }, - { - "method": "storage.inventory.matchPutaway", - "description": "收货单与入库单匹配入库。接收多个收货单和入库单,按商品(stock_warehouse_id)进行数量匹配入库,要求收货单已完成且已审核,完成后根据入库单来源(QM/API)自动触发回传", - "isNeedAuth": true, - "isNeedLogin": true, - "params": [ - { - "name": "receiving_ids", - "type": "array", - "required": true, - "source": "body", - "description": "收货单ID列表" - }, - { - "name": "entry_order_ids", - "type": "array", - "required": true, - "source": "body", - "description": "入库单ID列表" - } - ], - "response": { - "summary": { - "total_products_matched": "匹配的商品种类数", - "total_quantity_inbound": "入库总数量" - }, - "receiving_results": [ - { - "receiving_id": "收货单ID", - "storage_status": "入库状态(all/partial/none)" - } - ], - "entry_order_results": [ - { - "entry_order_id": "入库单ID", - "order_status": "入库单状态(COMPLETED 等)", - "callback_triggered": "是否触发回传(boolean)", - "callback_result": "回传结果对象" - } - ], - "warnings": "匹配过程中的警告信息列表" - }, - "errors": [ - { - "code": 400, - "message": "receiving_ids 必填且为数组" - }, - { - "code": 400, - "message": "entry_order_ids 必填且为数组" - }, - { - "code": 404, - "message": "收货单不存在或无权访问" - }, - { - "code": 400, - "message": "收货单未审核,审核通过后才能入库" - }, - { - "code": 404, - "message": "入库单不存在或无权访问" - } - ] + "headers": [], + "params": [], + "response": [], + "errors": [] }, { "method": "storage.inventory.transferLocation", @@ -20128,6 +20984,207 @@ } ] }, + { + "groupName": "库存管理模块", + "module": "storage.management", + "list": [ + { + "method": "storage.management.replenishmentDemand", + "description": "分拣缺货补货需求计算(仓库级别)。自动从用户上下文获取仓库,查询所有未完成储位分配的订单,计算每个SKU在分拣区与存货区的库存量、订单需求量、分拣区缺口、建议补货量及可补货库位。支持分页与排序。", + "isNeedAuth": false, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数,支持 page / pageSize,默认 page=1 pageSize=20" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数,支持 sortField / sortOrder。sortField 可选值:stock_id / pick_zone_quantity / storage_zone_quantity / total_demand / shortage / replenishment_needed,默认 shortage;sortOrder 可选 ASC / DESC,默认 DESC" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "补货需求明细列表", + "children": [ + { + "name": "stock_id", + "type": "number", + "required": true, + "description": "SKU ID" + }, + { + "name": "stock_code", + "type": "string", + "required": true, + "description": "SKU 编码" + }, + { + "name": "stock_name", + "type": "string", + "required": true, + "description": "SKU 名称" + }, + { + "name": "pick_zone_quantity", + "type": "number", + "required": true, + "description": "分拣区可用库存(allow_allocation=1且is_active=1的库位上的可用库存)" + }, + { + "name": "storage_zone_quantity", + "type": "number", + "required": true, + "description": "存货区可用库存(其余库位上的可用库存)" + }, + { + "name": "total_demand", + "type": "number", + "required": true, + "description": "订单总需求量(汇总自订单明细 plan_qty)" + }, + { + "name": "shortage", + "type": "number", + "required": true, + "description": "分拣区缺口 = max(0, total_demand - pick_zone_quantity)" + }, + { + "name": "replenishment_needed", + "type": "number", + "required": true, + "description": "建议补货量 = min(shortage, storage_zone_quantity)" + }, + { + "name": "replenishment_status", + "type": "string", + "required": true, + "description": "补货状态枚举:replenishable=存货区足够覆盖缺口,移库可解决;true_shortage=存货区不足以覆盖缺口或两区均无库存,需采购" + }, + { + "name": "replenishment_locations", + "type": "array", + "required": true, + "description": "存货区可补货库位列表(最多5条,按可用库存降序)", + "children": [ + { + "name": "space_code", + "type": "string", + "required": true, + "description": "库位编码" + }, + { + "name": "space_name", + "type": "string", + "required": true, + "description": "库位展示名称(优先自定义名称 custom_name,无自定义名称时回退为库位编码 space_code)" + }, + { + "name": "available_quantity", + "type": "number", + "required": true, + "description": "该库位可用库存数量" + } + ] + } + ] + }, + { + "name": "summary", + "type": "object", + "required": true, + "description": "汇总信息", + "children": [ + { + "name": "total_skus", + "type": "number", + "required": true, + "description": "涉及的SKU总数" + }, + { + "name": "total_shortage_skus", + "type": "number", + "required": true, + "description": "存在缺口的SKU数" + }, + { + "name": "total_replenishment_needed", + "type": "number", + "required": true, + "description": "总建议补货量" + }, + { + "name": "total_true_shortage_skus", + "type": "number", + "required": true, + "description": "真正缺货的SKU数(分拣区与存货区均无库存)" + } + ] + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息", + "children": [ + { + "name": "page", + "type": "number", + "required": true, + "description": "当前页码" + }, + { + "name": "pageSize", + "type": "number", + "required": true, + "description": "每页条数" + }, + { + "name": "total", + "type": "number", + "required": true, + "description": "总记录数" + }, + { + "name": "totalPages", + "type": "number", + "required": true, + "description": "总页数" + } + ] + } + ], + "errors": [ + { + "code": 500, + "message": "缺少仓库上下文" + }, + { + "code": 200, + "message": "无待处理订单时返回空列表(list: [], summary: { total_skus: 0, total_shortage_skus: 0, total_replenishment_needed: 0, total_true_shortage_skus: 0 })" + } + ] + } + ] + }, { "groupName": "主体模块", "module": "store", @@ -22342,7 +23399,7 @@ ] }, { - "groupName": "订单待处理模块", + "groupName": "出库模块", "module": "order", "list": [ { @@ -22408,7 +23465,7 @@ }, { "method": "order.pendingOrder.downloadCreateTemplate", - "description": "下载创建订单的 Excel 导入模板。返回 base64 编码的 xlsx 文件,前端解码后作为 .xlsx 附件下载。表头中标注 * 的列为必填项(橙色背景),可选列为灰色背景,包含示例数据行和填写说明工作表。多行相同订单号的行组成一个完整订单,每行代表一条商品明细。模板必填列:订单号(delivery_order_code)、收件人姓名(name)、手机号(mobile)、详细地址(detail_address)、商品编码(item_code)、计划数量(plan_qty);非必填列含:货主ID(store_id)、省份(province)、城市(city)、区/县(area)、店铺名称(shop_nick)等。", + "description": "下载创建订单的 Excel 导入模板。返回 base64 编码的 xlsx 文件,前端解码后作为 .xlsx 附件下载。表头中标注 * 的列为必填项(橙色背景),可选列为灰色背景,包含示例数据行和填写说明工作表。多行相同订单号的行组成一个完整订单,每行代表一条商品明细。模板共 25 列(A-Y):店铺名称(shop_nick)位于第2列B列,紧接*订单号(delivery_order_code)之后;其余必填列为*收件人姓名(name)、*手机号(mobile)、*详细地址(detail_address)、*商品编码(item_code)、*计划数量(plan_qty);非必填列依次为货主ID(store_id)、电话(tel)、省份(province)、城市(city)、区/县(area)、镇/街道(town)、邮编(zip_code)、快递编码(logistics_code)、快递名称(logistics_name)、系统平台编码(sys_platform_code)、来源平台编码(source_platform_code)、来源订单号(source_order_codes)、订单类型(order_type)、是否紧急(is_urgency)、是否需要发票(invoice_flag)、商品名称(item_name)、行号(order_line_no)、实际价格(actual_price)。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -22438,12 +23495,6 @@ "type": "string", "required": true, "description": "文件 MIME 类型,固定为 application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" - }, - { - "name": "shop_nick", - "type": "string", - "required": false, - "description": "模板中新增的店铺名称列(非必填),用于标识订单所属店铺" } ], "errors": [] @@ -22548,6 +23599,82 @@ "message": "内部错误:OrderExpress 模型未加载或数据库写入失败" } ] + }, + { + "method": "order.bindExpressPackageMaterialByWaybill", + "description": "按运单号绑定包材。仅需传入运单号与包材ID,系统自动根据运单号反查对应订单运单记录并绑定包材,无需传入订单ID。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "waybill_code", + "type": "string", + "required": true, + "source": "body", + "description": "运单号,必填。" + }, + { + "name": "package_material_id", + "type": "number|string", + "required": true, + "source": "body", + "description": "包材ID,必填。" + } + ], + "response": [ + { + "name": "order_id", + "type": "number", + "required": true, + "description": "运单号对应的订单ID(成功时返回于 data 对象中)。" + }, + { + "name": "waybill_code", + "type": "string", + "required": true, + "description": "运单号(成功时返回于 data 对象中)。" + }, + { + "name": "package_material_id", + "type": "number", + "required": true, + "description": "绑定后的包材ID(成功时返回于 data 对象中)。" + }, + { + "name": "package_material_name_snapshot", + "type": "string", + "required": true, + "description": "绑定后的包材名称快照(成功时返回于 data 对象中)。" + }, + { + "name": "package_material_code", + "type": "string", + "required": true, + "description": "绑定后的包材编码(成功时返回于 data 对象中)。" + } + ], + "errors": [ + { + "code": 404, + "message": "运单号不存在" + }, + { + "code": 400, + "message": "包材不存在或已禁用" + }, + { + "code": 500, + "message": "绑定包材失败" + } + ] } ] }, @@ -23624,6 +24751,483 @@ "errors": [] } ] + }, + { + "groupName": "组合商品模块", + "module": "comboGoods", + "list": [ + { + "method": "comboGoods.list", + "description": "组合商品列表查询(分页),支持按 combo_code/combo_name/status/warehouse_id 筛选。返回含 custom_code(自定义编码)、simpleNotation(stock_id|数量)和 nameNotation(【数量】商品名称)简记字段", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数,支持 page / pageSize,默认 page=1 pageSize=20" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "筛选条件对象,支持 combo_code(精确匹配)、combo_name(模糊匹配)、status(等值)、warehouse_id(等值)" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "组合商品列表,每项包含 id、combo_code、combo_name、combo_sku_id、custom_code、status、warehouse_id、remark、creator_id、editor_id、created_at、updated_at、items(子商品明细数组)、simpleNotation、nameNotation", + "children": [ + { + "name": "id", + "type": "number", + "description": "组合商品ID" + }, + { + "name": "combo_code", + "type": "string", + "description": "组合商品编码" + }, + { + "name": "combo_name", + "type": "string", + "description": "组合商品名称" + }, + { + "name": "combo_sku_id", + "type": "number", + "description": "组合商品SKU ID" + }, + { + "name": "custom_code", + "type": "string", + "description": "自定义编码,可为 null" + }, + { + "name": "status", + "type": "number", + "description": "状态:1=启用 0=停用" + }, + { + "name": "warehouse_id", + "type": "number", + "description": "仓库ID" + }, + { + "name": "remark", + "type": "string", + "description": "备注" + }, + { + "name": "creator_id", + "type": "number", + "description": "创建人ID" + }, + { + "name": "editor_id", + "type": "number", + "description": "最后编辑人ID" + }, + { + "name": "created_at", + "type": "string", + "description": "创建时间" + }, + { + "name": "updated_at", + "type": "string", + "description": "更新时间" + }, + { + "name": "items", + "type": "array", + "description": "子商品明细列表,每项含 id、combo_id、item_goods_sku_id、item_quantity、sort_order" + }, + { + "name": "simpleNotation", + "type": "string", + "description": "简记字符串,格式:stock_id|数量,stock_id2|数量" + }, + { + "name": "nameNotation", + "type": "string", + "description": "商品名称简记,格式:【数量】商品名称+【数量】商品名称" + } + ] + }, + { + "name": "total", + "type": "number", + "required": true, + "description": "总记录数" + }, + { + "name": "page", + "type": "number", + "required": true, + "description": "当前页码" + }, + { + "name": "pageSize", + "type": "number", + "required": true, + "description": "每页大小" + } + ], + "errors": [ + { + "code": "500", + "message": "查询失败" + } + ] + }, + { + "method": "comboGoods.create", + "description": "创建组合商品(含明细一次性提交)。校验:combo_code唯一性、custom_code按货主唯一(排除已删除记录)、所有子商品在wms_stock_warehouse中合法有效(is_valid=Y 且未删除)、所有子商品必须属于同一货主(store_id一致)。创建过程在事务中完成,保证主表和明细表的原子写入。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "combo_code", + "type": "string", + "required": true, + "source": "body", + "description": "组合商品编码,必填,全局唯一" + }, + { + "name": "combo_name", + "type": "string", + "required": true, + "source": "body", + "description": "组合商品名称,必填" + }, + { + "name": "warehouse_id", + "type": "number", + "required": false, + "source": "body", + "description": "仓库ID,可选" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注,可选" + }, + { + "name": "custom_code", + "type": "string", + "required": false, + "source": "body", + "description": "自定义编码,可选。传入时校验按货主唯一(排除已删除记录)" + }, + { + "name": "items", + "type": "array", + "required": true, + "source": "body", + "description": "子商品明细数组,每项含 item_goods_sku_id(number, 必填)和 item_quantity(number, 必填, 正整数)以及 sort_order(number, 可选, 排序号)" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "新建的组合商品ID" + }, + { + "name": "combo_code", + "type": "string", + "required": true, + "description": "组合商品编码" + }, + { + "name": "combo_name", + "type": "string", + "required": true, + "description": "组合商品名称" + }, + { + "name": "custom_code", + "type": "string", + "required": false, + "description": "自定义编码,未传入时为 null" + } + ], + "errors": [ + { + "code": "400", + "message": "组合商品编码不能为空" + }, + { + "code": "400", + "message": "组合商品名称不能为空" + }, + { + "code": "400", + "message": "子商品列表不能为空" + }, + { + "code": "400", + "message": "组合商品编码 \"{code}\" 已存在(409语义)" + }, + { + "code": "400", + "message": "自定义编码 \"{code}\" 已被货主其他组合商品使用" + }, + { + "code": "400", + "message": "以下子商品不存在或已停用:{ids}" + }, + { + "code": "400", + "message": "所有子商品必须属于同一个货主,不允许跨货主组合" + }, + { + "code": "500", + "message": "创建组合商品主记录失败" + } + ] + }, + { + "method": "comboGoods.update", + "description": "编辑组合商品(含明细替换)。校验同 create。传入 items 则先删旧明细再批量插入新明细,事务保证原子性。支持部分更新:不传的字段保持原值不变。custom_code 校验按货主唯一(排除已删除记录和自身)。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "组合商品ID,必填" + }, + { + "name": "combo_name", + "type": "string", + "required": false, + "source": "body", + "description": "组合商品名称,可选" + }, + { + "name": "warehouse_id", + "type": "number", + "required": false, + "source": "body", + "description": "仓库ID,可选" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注,可选" + }, + { + "name": "custom_code", + "type": "string", + "required": false, + "source": "body", + "description": "自定义编码,可选。传入非空值时校验按货主唯一(排除已删除记录和自身 id)" + }, + { + "name": "status", + "type": "number", + "required": false, + "source": "body", + "description": "状态:1=启用 0=停用,可选" + }, + { + "name": "items", + "type": "array", + "required": false, + "source": "body", + "description": "子商品明细数组,可选。传入非空数组时先删除旧明细再批量插入新明细;不传或传空数组则保持原明细不变。每项含 item_goods_sku_id(number)和 item_quantity(number)以及 sort_order(number, 可选)" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "更新后的组合商品ID" + } + ], + "errors": [ + { + "code": "400", + "message": "组合商品ID不能为空" + }, + { + "code": "404", + "message": "组合商品不存在" + }, + { + "code": "400", + "message": "自定义编码 \"{code}\" 已被货主其他组合商品使用" + }, + { + "code": "400", + "message": "以下子商品不存在或已停用:{ids}" + }, + { + "code": "400", + "message": "所有子商品必须属于同一个货主,不允许跨货主组合" + }, + { + "code": "500", + "message": "更新失败" + } + ] + }, + { + "method": "comboGoods.delete", + "description": "删除组合商品(软删除,将 status 置为 0)", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "组合商品ID,必填" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "已软删除的组合商品ID" + } + ], + "errors": [ + { + "code": "400", + "message": "组合商品ID不能为空" + }, + { + "code": "404", + "message": "组合商品不存在" + }, + { + "code": "500", + "message": "删除失败" + } + ] + }, + { + "method": "comboGoods.search", + "description": "关键字搜索组合商品(供手工建单选择)。模糊匹配 custom_code、combo_code 或 combo_name,仅返回启用状态(status=1)的记录,默认20条上限100条。custom_code 匹配项优先排在前面。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "keyword", + "type": "string", + "required": true, + "source": "body", + "description": "搜索关键字,模糊匹配 custom_code、combo_code 和 combo_name" + }, + { + "name": "limit", + "type": "number", + "required": false, + "source": "body", + "description": "最大返回条数,默认20,最大100" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "搜索结果列表,每项包含 id、combo_code、combo_name、custom_code、combo_sku_id、status、warehouse_id、items、simpleNotation、nameNotation" + }, + { + "name": "total", + "type": "number", + "required": true, + "description": "本次返回的记录条数" + } + ], + "errors": [ + { + "code": "400", + "message": "搜索关键字不能为空" + }, + { + "code": "500", + "message": "搜索失败" + } + ] + } + ] + }, + { + "groupName": "收货管理模块", + "module": "storage.receiving", + "list": [ + { + "method": "storage.receiving.getAvailableInboundQuantity", + "description": "[已删除] 按 stock_id 查询可入库数量。该方法已从代码中删除,不再可用。原依赖已弃用的 wms_entry_receiving_binding(明细绑定表),入库单与收货单的关系已改为通过 wms_entry_order_receiving 主表级关联。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [], + "params": [], + "response": [], + "errors": [] + } + ] } ] } diff --git a/prompts/官网生成提示词.md b/prompts/官网生成提示词.md new file mode 100644 index 0000000..39c2a45 --- /dev/null +++ b/prompts/官网生成提示词.md @@ -0,0 +1,187 @@ +# 官网生成提示词 — 奇门WMS(qimen-wms) + +## 项目背景 + +你将为以下开源项目生成一个**产品官网**(Landing Page / 产品介绍页)。请根据下方的项目描述,产出一份完整的提示词,用于交给 AI 或前端开发者生成官网 HTML 页面。 + +--- + +## 项目描述 + +### 产品名称 + +**奇门WMS(qimen-wms)** + +### 一句话简介 + +基于 Egg.js 的仓储管理系统(WMS),支持多快递平台对接、订单全生命周期管理、精细化库位管控与开放 API,适合中小型电商与仓储企业二次开发。 + +### 目标用户 + +- 中小型电商企业 +- 三方仓储服务商 +- 需要自建 WMS 的技术团队 +- 计划对接淘宝/天猫/拼多多/抖音/快手等平台的商家 + +### 官网定位 + +技术型产品官网,兼顾**品牌感**与**专业性**,面向企业决策者与开发者双重视角。整体风格简洁、现代、可信赖。 + +--- + +## 核心功能模块(请在官网中逐一展示) + +### 1. 订单全生命周期管理 +- **M1 待审核 → M2 待处理 → M3 异常 → M4 配送中 → M5 配送异常 → M6 归档** +- 完善的状态机驱动订单流转:同步、打印、拣货、打包、验货、出库、拦截等环节独立状态追踪 +- 支持审核、驳回、取消、拦截、异常处理 +- 订单动态分表设计,按仓库维度物理隔离,冷热数据分离 + +### 2. 多平台、多接口无缝对接 +- **奇门标准接口(qimen)**:严格遵循阿里巴巴奇门协议,支持出库单、入库单、退货单、库存查询、商品同步等标准接口 +- **OpenAPI**:独立的开放 API 链路,支持第三方系统集成 +- **多快递平台**:对接拼多多、淘宝/天猫、快手、抖音、小红书等主流电商,支持电子面单 +- **内部网关**:内网系统间调用的统一入口 + +### 3. 精细化库存管理 +- 仓库库存管理(正品、残次、冻结等) +- 商品条码管理、批号/批次追踪 +- 库存变动流水、库存预警 +- 多货主、多仓库库存独立核算 + +### 4. 库位管理(库区 / 货架 / 库位) +- 支持 库区 → 货架 → 库位 三级精细化管理 +- 库位类型:存储位、拣货位、暂存区、不良品区等 +- 自动计算拣货路径与拣货优先级 +- 库位唯一码/条码管理 +- 移库、补货、分配验证 + +### 5. 入库管理 +- ASN(预到货通知单)管理 +- 收货作业:明细录入 → 商品绑定 → 质检 → 上架 +- 支持直入、退货入库、协同收货 +- 收货单维度统计与完成确认 + +### 6. 出库与拣货 +- 订单分配、波次策略匹配 +- 拣货任务生成与执行 +- 拣货车(Pick Cart)模式 +- 复核、打包、称重、出库确认 +- 出库后配送状态追踪 + +### 7. 打印管理 +- 电子面单一键打印 +- 拣货单、发货单、装箱单等模板 +- 打印台管理、打印任务分发 +- 支持菜鸟、拼多多、京东、抖音、快手、小红书等平台打印模板 + +### 8. 系统管理与权限 +- 用户注册、登录、角色切换 +- 多平台角色上下文管理(Web / PDA / App / 微信 / 小程序) +- 细粒度权限控制(角色→菜单→接口级别) +- 操作日志留痕 + +### 9. 数据仪表盘 +- 实时统计:待处理订单、今日新增、昨日新增 +- 出库趋势、快递比例、平台分布 +- 未分配/未打印/未拣货等运营数据一目了然 + +### 10. 辅助能力 +- **Excel 服务**:灵活生成/解析单 sheet 或多 sheet 的 Excel 文件(支持 Buffer / 文件 / HTTP 下载) +- **IM 集成**:企业微信/钉钉等即时消息通知 +- **文件管理**:腾讯云 COS 文件上传,图片、文档、APK 等统一管理 +- **国际化(i18n)**:多语言键值管理与自动翻译 + +--- + +## 技术栈(官网技术特性板块展示) + +| 层级 | 技术 | +|------|------| +| 框架 | Egg.js 3.x | +| 数据库 | MySQL(Sequelize ORM + mysql2) | +| 缓存 | Redis(多 DB 隔离:缓存/打印) | +| 认证 | JWT | +| 接口协议 | REST / XML-RPC(奇门)/ OpenAPI | +| 模板 | EJS | +| 对象存储 | 腾讯云 COS、七牛云 | +| 物流接口 | SOAP | +| 数据处理 | ExcelJS、Fast XML Parser | +| 运行环境 | Node.js >= 18 | +| 部署 | 自有发布脚本 + 版本管理 + 回退机制 | +| 测试 | Egg Mock + ESLint | + +--- + +## 官网页面结构与内容要求 + +### 整体风格 +- 现代简约、科技感、**蓝色系为主色调**(#1a73e8 或类似专业蓝) +- 大屏宽幅设计,滚动式单页(One Page) +- 响应式适配(桌面 + 平板 + 手机) +- 中文字体优先(系统原生字体或思源黑体) + +### 页面区块建议 + +#### 1️⃣ 英雄区(Hero Section) +- 产品名称 + 一句话价值主张 +- 背景可配合仓储/物流插画或抽象网格动效 +- 两个 CTA 按钮:「在线体验 Demo」「查看技术文档」 + +#### 2️⃣ 产品定位区 +- "专为中小型电商与仓储企业打造的轻量级 WMS" +- 2~3 个核心卖点(如:奇门标准对接、订单全生命周期、开放架构) + +#### 3️⃣ 核心功能展示区(建议 4~6 个卡片) +- 每个功能模块:icon + 标题 + 一句话说明 +- 点击可展开详细功能列表 +- 模块建议:订单管理、库存管理、库位管理、多平台对接、打印管理、系统权限 + +#### 4️⃣ 技术架构图区 +- 展示前端 → 入口路由(/system / /qimen / /openapi)→ Service 层 → Model/DB/Redis 的分层架构 +- 可用文字描述配合简洁示意图 + +#### 5️⃣ 接口与集成区 +- 奇门接口列表概览(出库/入库/退货/库存/商品同步) +- OpenAPI 与内部网关说明 +- 已对接平台徽标(淘宝、拼多多、抖音、快手、京东、小红书等) + +#### 6️⃣ 适用场景区 +- 电商仓配一体:订单从平台推送 → WMS 处理 → 快递发出 +- 三方仓储服务:多货主、多仓库独立运营 +- 企业自建 WMS:二次开发、私有化部署 + +#### 7️⃣ 快速开始区 +```bash +# 克隆项目 +git clone + +# 安装依赖 +npm install + +# 启动开发服务(默认端口 6060) +npm run dev +``` + +#### 8️⃣ 页脚(Footer) +- GitHub 仓库链接 +- 开源协议(MIT) +- 作者信息 +- 项目版本号 + +--- + +## 编写要求 + +- 提示词需包含足够的产品细节,让接收方能直接生成完整的官网页面 +- 页面用纯 HTML + CSS + JavaScript(vanilla),无需框架依赖 +- 中文字体、中文内容、中文官网 +- 注重 SEO 基础(meta 标签、语义化 HTML) +- 包含 favicon 占位 +- 页面加载动画建议使用 CSS 过渡/动画,避免大量 JS 动效库 + +--- + +## 输出物 + +将以上提示词保存后,将其提交给 AI 代码生成工具或前端开发者,即可生成一个完整的**奇门WMS** 产品官网 HTML 文件。 diff --git a/script/api-test.js b/script/api-test.js new file mode 100644 index 0000000..6f550d9 --- /dev/null +++ b/script/api-test.js @@ -0,0 +1,34 @@ +const http = require('http'); +const token = process.argv[2]; +const method = process.argv[3]; // e.g. store.list +const reqBody = process.argv[4] || '{}'; + +const options = { + hostname: 'localhost', + port: 6060, + path: `/system?method=${method}&v=1×tamp=${Math.floor(Date.now()/1000)}`, + method: 'POST', + headers: { + 'platform': 'web', + 'project': 'wms', + 'Authorization': `Bearer ${token}`, + 'Content-Type': 'application/json', + }, +}; + +const req = http.request(options, (res) => { + let data = ''; + res.on('data', chunk => data += chunk); + res.on('end', () => { + console.log(`STATUS: ${res.statusCode}`); + try { + const json = JSON.parse(data); + console.log(JSON.stringify(json, null, 2)); + } catch (e) { + console.log(data.substring(0, 1000)); + } + }); +}); +req.on('error', (e) => console.error('ERROR:', e.message)); +req.write(reqBody); +req.end(); diff --git a/script/api-test2.js b/script/api-test2.js new file mode 100644 index 0000000..b8d0a92 --- /dev/null +++ b/script/api-test2.js @@ -0,0 +1,47 @@ +const http = require('http'); + +const token = process.argv[2]; +const method = process.argv[3]; // e.g. order.pendingOrder.createOrder +const reqBodyFile = process.argv[4]; // path to JSON file or JSON string + +let reqBody; +if (reqBodyFile && reqBodyFile.endsWith('.json')) { + reqBody = require('fs').readFileSync(reqBodyFile, 'utf8'); +} else { + reqBody = reqBodyFile || '{}'; +} + +const options = { + hostname: 'localhost', + port: 6060, + path: `/system?method=${method}&v=1×tamp=${Math.floor(Date.now()/1000)}`, + method: 'POST', + headers: { + 'platform': 'web', + 'project': 'wms', + 'Authorization': `Bearer ${token}`, + 'Content-Type': 'application/json', + }, +}; + +const req = http.request(options, (res) => { + let data = ''; + res.on('data', chunk => data += chunk); + res.on('end', () => { + console.log(`STATUS: ${res.statusCode}`); + console.log('HEADERS:', JSON.stringify(res.headers)); + try { + const json = JSON.parse(data); + console.log(JSON.stringify(json, null, 2)); + } catch (e) { + console.log('RAW BODY (first 2000 chars):'); + console.log(data.substring(0, 2000)); + if (data.length > 2000) { + console.log('...(truncated, total length: ' + data.length + ')'); + } + } + }); +}); +req.on('error', (e) => console.error('REQUEST ERROR:', e.message)); +req.write(reqBody); +req.end(); diff --git a/script/backfill-wave-status.js b/script/backfill-wave-status.js new file mode 100644 index 0000000..c88630b --- /dev/null +++ b/script/backfill-wave-status.js @@ -0,0 +1,70 @@ +'use strict'; + +/** + * 回补历史已完成任务的 wms_wave_pick_task_wave.status = 1(已拣)。 + * + * 用法: + * node script/backfill-wave-status.js + * + * 安全说明: + * - 仅更新 status=0 且关联任务已完成的记录 + * - 使用事务,执行前先展示影响行数 + */ + +const { Op } = require('sequelize'); +const path = require('path'); +const app = require('egg').app; +// 上面的 import 方式可能不对,用下面的方式 +const Application = require('egg').Application; + +async function main() { + // 直接用 sequelize 连接 + const config = require(path.join(__dirname, '..', 'database', 'config.js')); + const Sequelize = require('sequelize'); + const sequelize = new Sequelize(config.database, config.username, config.password, { + host: config.host, + port: config.port, + dialect: 'mysql', + logging: console.log, + }); + + try { + // 先查影响行数 + const [previewRows] = await sequelize.query(` + SELECT COUNT(1) AS count + FROM wms_wave_pick_task_wave w + INNER JOIN wms_wave_pick_task t ON t.id = w.task_id AND t.warehouse_id = w.warehouse_id + WHERE w.status = 0 + AND t.status IN (2, 3) + `, { type: Sequelize.QueryTypes.SELECT }); + + const count = Number(previewRows && previewRows.count || 0); + console.log(`将更新 ${count} 条 wms_wave_pick_task_wave 记录(status 0 → 1)`); + + if (count === 0) { + console.log('无需回补'); + return; + } + + // 执行更新 + const [result] = await sequelize.query(` + UPDATE wms_wave_pick_task_wave w + INNER JOIN wms_wave_pick_task t ON t.id = w.task_id AND t.warehouse_id = w.warehouse_id + SET w.status = 1, + w.pick_time = COALESCE(t.finish_time, NOW()), + w.update_time = NOW() + WHERE w.status = 0 + AND t.status IN (2, 3) + `); + + const affectedRows = Number(result && result.affectedRows || 0); + console.log(`成功回补 ${affectedRows} 条记录`); + } catch (err) { + console.error('回补失败:', err.message); + process.exit(1); + } finally { + await sequelize.close(); + } +} + +main(); diff --git a/script/clear-cache.js b/script/clear-cache.js new file mode 100644 index 0000000..9c40e32 --- /dev/null +++ b/script/clear-cache.js @@ -0,0 +1,30 @@ +const Redis = require('ioredis'); + +async function main() { + const redis = new Redis({ + host: '127.0.0.1', + port: 6379, + password: 'qwe2019@', + db: 10, + }); + + const key = 'store_warehouse:contract_config:1000028:1000241'; + + try { + const val = await redis.get(key); + console.log('Current cache value:', val ? val.substring(0, 200) : 'NULL'); + + await redis.del(key); + console.log('✅ Cache key deleted:', key); + + // Verify + const after = await redis.get(key); + console.log('After delete:', after); + } catch (e) { + console.error('Error:', e.message); + } + + redis.disconnect(); +} + +main(); diff --git a/script/cutoff-integration-test-v2.js b/script/cutoff-integration-test-v2.js new file mode 100644 index 0000000..68ceaf4 --- /dev/null +++ b/script/cutoff-integration-test-v2.js @@ -0,0 +1,183 @@ +/** + * 截单时间逻辑真实 API 集成测试 (v2) + * + * 测试目标: 验证 asyncProcessOrderCreated 中的截单时间兜底逻辑 + * 策略: 通过 SQL 直接更新 policy_config (绕过 API 权限问题),通过 API 创建订单并验证结果 + */ +const http = require('http'); +const mysql = require('mysql2/promise'); + +const TOKEN = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJsaXVmdW1pbmdyZW4iLCJpYXQiOjE3ODE5NTM3ODIsImV4cCI6MTc4MTk2ODE4Mn0.p-H2Wz6BaJppPV4X-wGjzdvUz_pbuBfmo1lt5cDimhM'; + +const DB_CONFIG = { host: '112.124.21.102', port: 3306, user: 'wms', password: 'P6j3YTHTpirepYWz', database: 'wms' }; + +const TEST = { + contractId: 100213, + warehouseId: 1000028, + storeId: 1000241, + stockWarehouseId: 156652, + itemCode: '6942349700385', + itemName: '泊泉雅黄瓜积雪草补水面膜25g', +}; + +// 策略配置 +const POLICY = { + A: { need_order_approval: 0, cutoff_order_enabled: 1, cutoff_order_time: '23:59', auto_allocate_express: 1, auto_allocate_storage: 1 }, + B: { need_order_approval: 0, cutoff_order_enabled: 1, cutoff_order_time: '00:01', auto_allocate_express: 1, auto_allocate_storage: 1 }, + C: { need_order_approval: 1, cutoff_order_enabled: 1, cutoff_order_time: '23:59', auto_allocate_express: 1, auto_allocate_storage: 1 }, +}; + +function api(method, body) { + return new Promise((resolve, reject) => { + const bodyStr = typeof body === 'string' ? body : JSON.stringify(body); + const opts = { + hostname: 'localhost', port: 6060, + path: `/system?method=${method}&v=1×tamp=${Math.floor(Date.now()/1000)}`, + method: 'POST', + headers: { 'platform': 'web', 'project': 'wms', 'Authorization': `Bearer ${TOKEN}`, 'Content-Type': 'application/json' }, + timeout: 60000, + }; + const req = http.request(opts, res => { + let d = ''; + res.on('data', c => d += c); + res.on('end', () => { + try { resolve({ status: res.statusCode, body: JSON.parse(d) }); } + catch (e) { resolve({ status: res.statusCode, body: { _raw: d.substring(0, 300) } }); } + }); + }); + req.on('error', e => reject(e)); + req.on('timeout', () => { req.destroy(); reject(new Error('timeout')); }); + req.write(bodyStr); + req.end(); + }); +} + +function sleep(ms) { return new Promise(r => setTimeout(r, ms)); } + +async function setPolicy(policyCfg) { + const conn = await mysql.createConnection(DB_CONFIG); + await conn.execute('UPDATE wms_store_warehouse SET policy_config = ? WHERE id = ?', + [JSON.stringify(policyCfg), TEST.contractId]); + await conn.end(); +} + +async function dbQuery(sql, params = []) { + const conn = await mysql.createConnection(DB_CONFIG); + const [rows] = await conn.execute(sql, params); + await conn.end(); + return rows; +} + +async function createOrder() { + return await api('order.pendingOrder.createOrder', { + store_id: TEST.storeId, + name: '测试收件人', + mobile: '13800138000', + province: '广东省', + city: '广州市', + area: '天河区', + detail_address: '测试地址1号', + items: [{ item_id: TEST.stockWarehouseId, item_code: TEST.itemCode, item_name: TEST.itemName, plan_qty: 1 }], + }); +} + +async function checkExpressAssignment(orderId) { + const rows = await dbQuery( + 'SELECT id, order_id, warehouse_id FROM wms_order_express WHERE order_id = ? AND warehouse_id = ? LIMIT 1', + [orderId, TEST.warehouseId] + ); + return rows.length > 0; +} + +async function runScene(label, sceneKey, expectedStep, expectedExpress) { + console.log(`\n=== ${label} ===`); + + // 1. Set policy + console.log(' [1] 设置 policy_config...'); + await setPolicy(POLICY[sceneKey]); + console.log(` policy: ${JSON.stringify(POLICY[sceneKey])}`); + + // 2. Wait cache + await sleep(1000); + + // 3. Create order + console.log(' [2] 创建订单...'); + const r = await createOrder(); + console.log(` status: ${r.status}`); + + const success = r.status === 200 && r.body && r.body.flag === 'success'; + if (!success) { + console.log(` ❌ 创建失败: ${JSON.stringify(r.body).substring(0, 200)}`); + return { pass: false, reason: 'create_failed', detail: r.body }; + } + + const orderId = r.body.order_id || r.body.data?.order_id; + const step = r.body.step || r.body.data?.step; + console.log(` order_id: ${orderId}, step: ${step} (预期=${expectedStep})`); + + // 4. Wait async processing + console.log(' [3] 等待异步处理 (5秒)...'); + await sleep(5000); + + // 5. Check express assignment + const hasExpress = await checkExpressAssignment(orderId); + console.log(` [4] 快递分配: ${hasExpress ? '✅ 已分配' : '❌ 未分配'} (预期=${expectedExpress ? '已分配' : '未分配'})`); + + const stepOk = step === expectedStep; + const expressOk = hasExpress === expectedExpress; + const pass = stepOk && expressOk; + + return { + pass, + orderId, + step, + expectedStep, + hasExpress, + expectedExpress, + stepOk, + expressOk, + }; +} + +async function main() { + console.log('============================================'); + console.log(' 截单时间逻辑 - API 集成测试'); + console.log(` ${new Date().toISOString()}`); + console.log('============================================'); + + const results = {}; + + results.A = await runScene( + '场景 A: 免审核 + 未截单(23:59) → 应触发自动分配', + 'A', 1, true + ); + + results.B = await runScene( + '场景 B: 免审核 + 已截单(00:01) → 应跳过', + 'B', 1, false + ); + + results.C = await runScene( + '场景 C: 需要审核 → 应跳过', + 'C', 0, false + ); + + // 恢复默认 + await setPolicy(null); + + // Summary + console.log('\n============================================'); + console.log(' 测试结果汇总'); + console.log('============================================'); + const total = Object.keys(results).length; + const passing = Object.values(results).filter(r => r.pass).length; + + for (const [key, r] of Object.entries(results)) { + const icon = r.pass ? '✅' : '❌'; + console.log(` ${icon} 场景 ${key}: step=${r.step}(预期${r.expectedStep}) express=${r.hasExpress}(预期${r.expectedExpress})`); + } + console.log(`\n Passing: ${passing}/${total}`); + console.log('============================================'); +} + +main().catch(console.error); diff --git a/script/cutoff-integration-test-v3.js b/script/cutoff-integration-test-v3.js new file mode 100644 index 0000000..86b379e --- /dev/null +++ b/script/cutoff-integration-test-v3.js @@ -0,0 +1,203 @@ +/** + * 截单时间逻辑真实 API 集成测试 (v3 - Final) + * + * 测试 asyncProcessOrderCreated 的截单兜底逻辑 + * + * 场景 A: 免审核 + 未截单(23:59) → 应触发自动分配快递 + * 场景 B: 免审核 + 已截单(00:01) → 应跳过 + * 场景 C: 需要审核 → 应跳过 (step=0) + */ +const http = require('http'); +const mysql = require('mysql2/promise'); + +const TOKEN = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJsaXVmdW1pbmdyZW4iLCJpYXQiOjE3ODE5NTQ0NzIsImV4cCI6MTc4MTk2ODg3Mn0.4RrUS0F9iV2ZUG0MuuObhivLO_7s-2V6wq-6lf3x3VQ'; +const DB = { host: '112.124.21.102', port: 3306, user: 'wms', password: 'P6j3YTHTpirepYWz', database: 'wms' }; + +const WAREHOUSE_ID = 1000028; +const STORE_ID = 1000241; +const CONTRACT_ID = 100213; +const STOCK_WAREHOUSE_ID = 156652; +const ITEM_CODE = '6942349700385'; +const ITEM_NAME = '泊泉雅黄瓜积雪草补水面膜25g'; +const DELIVERY_TABLE = `wms_order_delivery_${WAREHOUSE_ID}`; + +const POLICY = { + A: { need_order_approval: 0, cutoff_order_enabled: 1, cutoff_order_time: '23:59', auto_allocate_express: 1, auto_allocate_storage: 1 }, + B: { need_order_approval: 0, cutoff_order_enabled: 1, cutoff_order_time: '00:01', auto_allocate_express: 1, auto_allocate_storage: 1 }, + C: { need_order_approval: 1, cutoff_order_enabled: 1, cutoff_order_time: '23:59', auto_allocate_express: 1, auto_allocate_storage: 1 }, +}; + +// ========== 工具 ========== + +function api(method, body) { + return new Promise((resolve, reject) => { + const bodyStr = JSON.stringify(body); + const req = http.request({ + hostname: 'localhost', port: 6060, + path: `/system?method=${method}&v=1×tamp=${Math.floor(Date.now()/1000)}`, + method: 'POST', + headers: { platform: 'web', project: 'wms', Authorization: `Bearer ${TOKEN}`, 'Content-Type': 'application/json' }, + timeout: 60000, + }, res => { + let d = ''; res.on('data', c => d += c); res.on('end', () => { + try { resolve({ status: res.statusCode, body: JSON.parse(d) }); } + catch (e) { resolve({ status: res.statusCode, body: { _raw: d.substring(0, 300) } }); } + }); + }); + req.on('error', e => reject(e)); + req.write(bodyStr); req.end(); + }); +} + +function sleep(ms) { return new Promise(r => setTimeout(r, ms)); } + +async function dbQuery(sql, params = []) { + const conn = await mysql.createConnection(DB); + const [rows] = await conn.execute(sql, params); + await conn.end(); + return rows; +} + +// ========== 业务操作 ========== + +async function setPolicy(sceneKey) { + const policyObj = POLICY[sceneKey]; + const conn = await mysql.createConnection(DB); + await conn.execute('UPDATE wms_store_warehouse SET policy_config = ? WHERE id = ?', + [JSON.stringify(policyObj), CONTRACT_ID]); + await conn.end(); + + // 通过 API 调用 savePolicyConfig 清除缓存 + console.log(' 调用 savePolicyConfig API 清除缓存...'); + const apiRes = await api('storeWarehouse.store.savePolicyConfig', { id: CONTRACT_ID, policy_config: policyObj }); + console.log(` savePolicyConfig: ${apiRes.status} ${JSON.stringify(apiRes.body).substring(0, 150)}`); +} + +async function createOrder() { + return await api('order.pendingOrder.createOrder', { + store_id: STORE_ID, + create_channel: 'API', + name: '测试收件人', + mobile: '13800138000', + province: '广东省', + city: '广州市', + area: '天河区', + detail_address: '测试地址1号', + items: [{ item_id: STOCK_WAREHOUSE_ID, item_code: ITEM_CODE, item_name: ITEM_NAME, plan_qty: 1 }], + }); +} + +async function getOrderFromDB(orderId) { + const rows = await dbQuery( + `SELECT id, step, status, wave_id, logistics_code, sys_logistics_code FROM ${DELIVERY_TABLE} WHERE id = ${Number(orderId)}` + ); + return rows[0] || null; +} + +async function checkExpress(orderId) { + const rows = await dbQuery( + `SELECT id, order_id FROM wms_order_express WHERE order_id = ${Number(orderId)} AND warehouse_id = ${WAREHOUSE_ID} LIMIT 1` + ); + return rows.length > 0; +} + +// ========== 测试执行 ========== + +async function runScene(label, sceneKey, expectedStep, checkExpressExpected) { + console.log(`\n${'='.repeat(60)}`); + console.log(` ${label}`); + console.log(`${'='.repeat(60)}`); + + // 1. Set policy + console.log(` [1] 更新 policy_config → scene ${sceneKey}`); + console.log(` ${JSON.stringify(POLICY[sceneKey])}`); + await setPolicy(sceneKey); + + // 2. Wait for cache invalidation + console.log(` [2] 等待缓存... (10秒让 600s cache 有机会清除)`); + await sleep(10000); + + // 3. Create order via API + console.log(` [3] API 创建订单...`); + const r = await createOrder(); + console.log(` HTTP ${r.status}`); + + if (r.status !== 200 || !r.body || r.body.flag !== 'success') { + console.log(` ❌ 创建失败: ${JSON.stringify(r.body)}`); + return { pass: false, reason: 'API创建失败' }; + } + + // createOrder 返回结构: { flag, code, message, order_id, step, step_label, items_count, items_total } + const orderId = r.body.order_id; + const apiStep = r.body.step; + console.log(` order_id=${orderId}, api_step=${apiStep}, api_step_label="${r.body.step_label}"`); + + // 4. Wait async processing + console.log(` [4] 等待异步处理 (8秒)...`); + await sleep(8000); + + // 5. Check DB + const order = await getOrderFromDB(orderId); + if (order) { + console.log(` [5] DB 订单状态: step=${order.step}, status=${order.status}, wave_id=${order.wave_id}, logistics=${order.sys_logistics_code}`); + } else { + console.log(` [5] ⚠️ 数据库中未找到订单!`); + return { pass: false, reason: 'DB中找不到订单' }; + } + + // 6. Check express + const hasExpress = await checkExpress(orderId); + console.log(` [6] wms_order_express: ${hasExpress ? '✅ 有记录' : '❌ 无记录'}`); + + // 7. Evaluate + const stepOk = order.step === expectedStep; + const expressOk = hasExpress === checkExpressExpected; + const pass = stepOk && expressOk; + + const icon = pass ? '✅' : '❌'; + console.log(`\n ${icon} 结果: step=${order.step}(预期${expectedStep}) ${stepOk ? '✅' : '❌'}, express=${hasExpress}(预期${checkExpressExpected}) ${expressOk ? '✅' : '❌'}`); + + return { pass, orderId, step: order.step, expectedStep, hasExpress, checkExpressExpected, stepOk, expressOk }; +} + +async function main() { + console.log('╔══════════════════════════════════════════════════╗'); + console.log('║ 截单时间逻辑 - API 集成测试 ║'); + console.log(`║ ${new Date().toISOString()} ║`); + console.log('╚══════════════════════════════════════════════════╝'); + console.log(` Warehouse: ${WAREHOUSE_ID}, Store: ${STORE_ID}, Contract: ${CONTRACT_ID}`); + + // 确保 server 在线 + try { + await api('order.deliveryOrder.list', { page: 1, pageSize: 1, warehouse_id: WAREHOUSE_ID }); + console.log(' ✅ Dev server 连接正常'); + } catch (e) { + console.error(' ❌ Dev server 不可达:', e.message); + return; + } + + const results = {}; + + results.A = await runScene('场景 A: 免审核 + 未截单(23:59) → 应自动分配', 'A', 1, true); + results.B = await runScene('场景 B: 免审核 + 已截单(00:01) → 应跳过', 'B', 1, false); + results.C = await runScene('场景 C: 需要审核 → 应跳过', 'C', 0, false); + + // Restore + await setPolicy('A'); // 恢复为场景 A (免审核 + 未截单) + + // Summary + console.log(`\n${'='.repeat(60)}`); + console.log(' 测试结果汇总'); + console.log(`${'='.repeat(60)}`); + let passCount = 0; + for (const [key, r] of Object.entries(results)) { + const icon = r.pass ? '✅' : '❌'; + const detail = r.pass ? '' : ` | step=${r.step}≠${r.expectedStep} express=${r.hasExpress}≠${r.checkExpressExpected}`; + console.log(` ${icon} 场景 ${key}${detail}`); + if (r.pass) passCount++; + } + console.log(`\n 🏆 通过: ${passCount}/${Object.keys(results).length}`); + console.log(`${'='.repeat(60)}`); +} + +main().catch(console.error); diff --git a/script/cutoff-integration-test.js b/script/cutoff-integration-test.js new file mode 100644 index 0000000..f009146 --- /dev/null +++ b/script/cutoff-integration-test.js @@ -0,0 +1,279 @@ +/** + * 截单时间逻辑真实 API 集成测试 + * + * 测试目标: 验证 asyncProcessOrderCreated 中的截单时间兜底逻辑 + * + * 测试环境: + * - Dev Server: http://localhost:6060 + * - Warehouse ID: 1000028 (天豹云仓) + * - Store ID: 1000241 + * - Store-Warehouse ID: 100213 + * + * 测试步骤: + * A) 免审核 + 未截单 → 应触发自动分配快递 + * B) 免审核 + 已截单 → 应跳过 + * C) 需要审核 → 应跳过 + */ + +const http = require('http'); + +// ========== 配置 ========== +const TOKEN = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJsaXVmdW1pbmdyZW4iLCJpYXQiOjE3ODE5NTM3ODIsImV4cCI6MTc4MTk2ODE4Mn0.p-H2Wz6BaJppPV4X-wGjzdvUz_pbuBfmo1lt5cDimhM'; + +const TEST_CONFIG = { + warehouseId: 1000028, + storeId: 1000241, + contractId: 100213, + stockWarehouseId: 156652, + itemCode: '6942349700385', + itemName: '泊泉雅黄瓜积雪草补水面膜25g', +}; + +// ========== 工具函数 ========== + +function apiRequest(method, body) { + return new Promise((resolve, reject) => { + const bodyStr = typeof body === 'string' ? body : JSON.stringify(body); + const options = { + hostname: 'localhost', + port: 6060, + path: `/system?method=${method}&v=1×tamp=${Math.floor(Date.now() / 1000)}`, + method: 'POST', + headers: { + 'platform': 'web', + 'project': 'wms', + 'Authorization': `Bearer ${TOKEN}`, + 'Content-Type': 'application/json', + }, + timeout: 60000, + }; + const req = http.request(options, (res) => { + let data = ''; + res.on('data', chunk => data += chunk); + res.on('end', () => { + let parsed; + try { + parsed = JSON.parse(data); + } catch (e) { + parsed = { _raw: data.substring(0, 500), _contentType: res.headers['content-type'] }; + } + resolve({ status: res.statusCode, body: parsed }); + }); + }); + req.on('error', (e) => reject(e)); + req.on('timeout', () => { req.destroy(); reject(new Error('Request timeout')); }); + req.write(bodyStr); + req.end(); + }); +} + +function sleep(ms) { + return new Promise(resolve => setTimeout(resolve, ms)); +} + +/** + * 更新 store_warehouse 的 policy_config + */ +async function updatePolicyConfig(policyConfig) { + return await apiRequest('storeWarehouse.store.savePolicyConfig', { + id: TEST_CONFIG.contractId, + policy_config: policyConfig, + }); +} + +/** + * 创建测试订单 + */ +async function createTestOrder() { + const orderBody = { + store_id: TEST_CONFIG.storeId, + name: '测试收件人', + mobile: '13800138000', + province: '广东省', + city: '广州市', + area: '天河区', + detail_address: '测试地址1号', + items: [ + { + item_id: TEST_CONFIG.stockWarehouseId, + item_code: TEST_CONFIG.itemCode, + item_name: TEST_CONFIG.itemName, + plan_qty: 1, + }, + ], + }; + return await apiRequest('order.pendingOrder.createOrder', orderBody); +} + +// ========== 测试用例 ========== + +async function testA() { + console.log('\n========================================'); + console.log('测试场景 A: 免审核 + 未截单 → 应触发自动分配'); + console.log('========================================'); + + // Step 1: 设置 policy_config + console.log('\n[A-1] 设置 policy_config: 免审核 + 截单启用 + 未截单时间(23:59)'); + const policyA = { + need_order_approval: 0, + cutoff_order_enabled: 1, + cutoff_order_time: '23:59', + auto_allocate_express: 1, + auto_allocate_storage: 1, + }; + const updateResult = await updatePolicyConfig(policyA); + console.log(' 更新结果:', JSON.stringify(updateResult.body).substring(0, 200)); + + // Step 2: 清除缓存 (等待几秒让缓存过期,或重新触发缓存加载) + console.log('\n[A-2] 等待缓存...'); + await sleep(2000); + + // Step 3: 创建订单 + console.log('\n[A-3] 创建订单...'); + const orderResult = await createTestOrder(); + console.log(' 状态:', orderResult.status); + console.log(' 响应:', JSON.stringify(orderResult.body, null, 2)); + + if (orderResult.status === 200 && orderResult.body && orderResult.body.data) { + const orderId = orderResult.body.data.order_id; + console.log(' 订单ID:', orderId); + console.log(' 订单步骤:', orderResult.body.data.step, '(0=待审核, 1=待处理)'); + + // Step 4: 等待异步处理 + console.log('\n[A-4] 等待异步处理完成 (5秒)...'); + await sleep(5000); + + return { success: orderResult.status === 200, orderId, step: orderResult.body.data.step }; + } + + return { success: false, error: '创建订单失败' }; +} + +async function testB() { + console.log('\n========================================'); + console.log('测试场景 B: 免审核 + 已截单 → 应跳过'); + console.log('========================================'); + + // Step 1: 设置 policy_config - 截单时间设为一个肯定过了的时间 + console.log('\n[B-1] 设置 policy_config: 免审核 + 截单时间 00:01 (已过)'); + const policyB = { + need_order_approval: 0, + cutoff_order_enabled: 1, + cutoff_order_time: '00:01', + auto_allocate_express: 1, + auto_allocate_storage: 1, + }; + const updateResult = await updatePolicyConfig(policyB); + console.log(' 更新结果:', JSON.stringify(updateResult.body).substring(0, 200)); + + console.log('\n[B-2] 等待缓存...'); + await sleep(2000); + + // Step 2: 创建订单 + console.log('\n[B-3] 创建订单...'); + const orderResult = await createTestOrder(); + console.log(' 状态:', orderResult.status); + console.log(' 响应:', JSON.stringify(orderResult.body, null, 2)); + + if (orderResult.status === 200 && orderResult.body && orderResult.body.data) { + const orderId = orderResult.body.data.order_id; + console.log(' 订单ID:', orderId); + console.log(' 订单步骤:', orderResult.body.data.step); + + console.log('\n[B-4] 等待异步处理完成 (5秒)...'); + await sleep(5000); + + return { success: orderResult.status === 200, orderId, step: orderResult.body.data.step }; + } + + return { success: false, error: '创建订单失败' }; +} + +async function testC() { + console.log('\n========================================'); + console.log('测试场景 C: 需要审核 → 应跳过'); + console.log('========================================'); + + // Step 1: 设置 policy_config - 需要审核 + console.log('\n[C-1] 设置 policy_config: 需要审核 + 未截单'); + const policyC = { + need_order_approval: 1, + cutoff_order_enabled: 1, + cutoff_order_time: '23:59', + auto_allocate_express: 1, + auto_allocate_storage: 1, + }; + const updateResult = await updatePolicyConfig(policyC); + console.log(' 更新结果:', JSON.stringify(updateResult.body).substring(0, 200)); + + console.log('\n[C-2] 等待缓存...'); + await sleep(2000); + + // Step 2: 创建订单 + console.log('\n[C-3] 创建订单...'); + const orderResult = await createTestOrder(); + console.log(' 状态:', orderResult.status); + console.log(' 响应:', JSON.stringify(orderResult.body, null, 2)); + + if (orderResult.status === 200 && orderResult.body && orderResult.body.data) { + const orderId = orderResult.body.data.order_id; + console.log(' 订单ID:', orderId); + console.log(' 订单步骤:', orderResult.body.data.step, '(期望=0 待审核)'); + + console.log('\n[C-4] 等待异步处理完成 (5秒)...'); + await sleep(5000); + + return { success: orderResult.status === 200, orderId, step: orderResult.body.data.step }; + } + + return { success: false, error: '创建订单失败' }; +} + +// ========== 主函数 ========== + +async function main() { + console.log('============================================='); + console.log(' 截单时间逻辑 - 真实 API 集成测试'); + console.log('============================================='); + console.log(' 仓库ID:', TEST_CONFIG.warehouseId); + console.log(' 货主ID:', TEST_CONFIG.storeId); + console.log(' 合约ID:', TEST_CONFIG.contractId); + console.log(' Stock Warehouse ID:', TEST_CONFIG.stockWarehouseId); + console.log('============================================='); + + const results = {}; + + try { + results.A = await testA(); + } catch (e) { + console.error('场景 A 异常:', e.message, e.stack); + results.A = { success: false, error: e.message }; + } + + try { + results.B = await testB(); + } catch (e) { + console.error('场景 B 异常:', e.message, e.stack); + results.B = { success: false, error: e.message }; + } + + try { + results.C = await testC(); + } catch (e) { + console.error('场景 C 异常:', e.message, e.stack); + results.C = { success: false, error: e.message }; + } + + // 汇总 + console.log('\n\n============================================='); + console.log(' 测试结果汇总'); + console.log('============================================='); + console.log(' 场景 A (未截单+免审核):', results.A.success ? '✅ 订单创建成功' : '❌ 失败 - ' + (results.A.error || '')); + console.log(' 场景 B (已截单+免审核):', results.B.success ? '✅ 订单创建成功' : '❌ 失败 - ' + (results.B.error || '')); + console.log(' 场景 C (待审核):', results.C.success ? '✅ 订单创建成功' : '❌ 失败 - ' + (results.C.error || '')); + console.log('============================================='); + + return results; +} + +main().catch(console.error); diff --git a/script/integration-test.js b/script/integration-test.js new file mode 100644 index 0000000..ee8e01f --- /dev/null +++ b/script/integration-test.js @@ -0,0 +1,87 @@ +/** + * 截单时间逻辑集成测试脚本 + * 通过 HTTP 请求真实 API 接口 + */ +const http = require('http'); + +const BASE_URL = 'http://localhost:6060'; +const TOKEN = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJsaXVmdW1pbmdyZW4iLCJpYXQiOjE3ODE5NTM3ODIsImV4cCI6MTc4MTk2ODE4Mn0.p-H2Wz6BaJppPV4X-wGjzdvUz_pbuBfmo1lt5cDimhM'; + +function apiRequest(method, body) { + return new Promise((resolve, reject) => { + const bodyStr = typeof body === 'string' ? body : JSON.stringify(body); + const options = { + hostname: 'localhost', + port: 6060, + path: `/system?method=${method}&v=1×tamp=${Math.floor(Date.now() / 1000)}`, + method: 'POST', + headers: { + 'platform': 'web', + 'project': 'wms', + 'Authorization': `Bearer ${TOKEN}`, + 'Content-Type': 'application/json', + }, + }; + const req = http.request(options, (res) => { + let data = ''; + res.on('data', chunk => data += chunk); + res.on('end', () => { + let body; + try { + body = JSON.parse(data); + } catch (e) { + body = { _raw: data.substring(0, 500), _contentType: res.headers['content-type'] }; + } + resolve({ status: res.statusCode, headers: res.headers, body, _rawLength: data.length }); + }); + }); + req.on('error', (e) => reject(e)); + req.write(bodyStr); + req.end(); + }); +} + +async function main() { + // 测试 1: 验证 token 和基本信息 + console.log('=== 测试 1: 验证 API 连接 ==='); + try { + const r = await apiRequest('order.deliveryOrder.list', { page: 1, pageSize: 1, warehouse_id: 1000028 }); + console.log(`Status: ${r.status}`); + console.log('Response:', JSON.stringify(r.body).substring(0, 300)); + } catch (e) { + console.error('Error:', e.message); + } + + // 测试 2: 创建订单 + console.log('\n=== 测试 2: 创建订单 ==='); + const orderBody = { + store_id: 1000241, + name: '测试收件人AAA', + mobile: '13800138000', + province: '广东省', + city: '广州市', + area: '天河区', + detail_address: '测试地址1号', + items: [ + { + item_id: 1000693, + item_code: '6942349700385', + item_name: '泊泉雅黄瓜积雪草补水面膜25g', + plan_qty: 1, + }, + ], + }; + try { + const r = await apiRequest('order.pendingOrder.createOrder', orderBody); + console.log(`Status: ${r.status}`); + if (r.body._raw) { + console.log('RAW:', r.body._raw); + } else { + console.log('Response:', JSON.stringify(r.body, null, 2)); + } + } catch (e) { + console.error('Error:', e.message); + } +} + +main().catch(console.error); diff --git a/script/update-policy.js b/script/update-policy.js new file mode 100644 index 0000000..1654a69 --- /dev/null +++ b/script/update-policy.js @@ -0,0 +1,64 @@ +const mysql = require('mysql2/promise'); + +const CONFIGS = { + A: { + need_order_approval: 0, + cutoff_order_enabled: 1, + cutoff_order_time: '23:59', + auto_allocate_express: 1, + auto_allocate_storage: 1, + }, + B: { + need_order_approval: 0, + cutoff_order_enabled: 1, + cutoff_order_time: '00:01', + auto_allocate_express: 1, + auto_allocate_storage: 1, + }, + C: { + need_order_approval: 1, + cutoff_order_enabled: 1, + cutoff_order_time: '23:59', + auto_allocate_express: 1, + auto_allocate_storage: 1, + }, +}; + +async function main() { + const scene = process.argv[2] || 'A'; + const policy = CONFIGS[scene]; + if (!policy) { + console.error('Unknown scene:', scene); + process.exit(1); + } + + const contractId = 100213; + const policyStr = JSON.stringify(policy); + + console.log(`Scene ${scene}: Updating policy_config for contract ${contractId}`); + console.log('Policy:', policyStr); + + const conn = await mysql.createConnection({ + host: '127.0.0.1', + port: 3306, + user: 'wms', + password: 'P6j3YTHTpirepYWz', + database: 'wms', + }); + + const [result] = await conn.execute( + 'UPDATE wms_store_warehouse SET policy_config = ? WHERE id = ?', + [policyStr, contractId] + ); + console.log('Update result:', JSON.stringify(result)); + + const [rows] = await conn.execute( + 'SELECT id, store_id, warehouse_id, policy_config FROM wms_store_warehouse WHERE id = ?', + [contractId] + ); + console.log('Current record:', JSON.stringify(rows[0], null, 2)); + + await conn.end(); +} + +main().catch(console.error); diff --git a/temp_check_prod_migrations.js b/temp_check_prod_migrations.js new file mode 100644 index 0000000..42cdf9c --- /dev/null +++ b/temp_check_prod_migrations.js @@ -0,0 +1,71 @@ +const mysql = require('mysql2/promise'); +const path = require('path'); +const fs = require('fs'); + +function walk(dir) { + const result = []; + const entries = fs.readdirSync(dir, { withFileTypes: true }); + for (const e of entries) { + const full = path.join(dir, e.name); + if (e.isDirectory()) result.push(...walk(full)); + else if (e.name.endsWith('.js')) result.push(e.name); + } + return result; +} + +(async () => { + const files = walk('database/migrations'); + console.log('迁移目录全部 .js 文件:', files.length, '个'); + + try { + const c = await mysql.createConnection({ + host: '112.124.21.102', + port: 3306, + user: 'wms', + password: 'P6j3YTHTpirepYWz', + database: 'wms', + charset: 'utf8mb4', + connectTimeout: 10000, + }); + + // 查迁移相关表 + const [tables] = await c.query( + "SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA='wms' AND (TABLE_NAME LIKE '%sequelize%' OR TABLE_NAME LIKE '%migration%') ORDER BY TABLE_NAME" + ); + console.log('\n=== 迁移相关表 ==='); + if (tables.length === 0) console.log(' 无'); + else tables.forEach(t => console.log(' ' + t.TABLE_NAME)); + + // 尝试查 sequelizemeta + try { + const [rows] = await c.query('SELECT name FROM sequelizemeta ORDER BY name'); + console.log('\nsequelizemeta 表记录数:', rows.length); + rows.forEach(r => console.log(' ' + r.name)); + } catch (e) { + console.log('\nsequelizemeta 表不存在或查询失败:', e.message); + } + + // 尝试查 SequelizeMeta (大写) + try { + const [rows] = await c.query('SELECT name FROM SequelizeMeta ORDER BY name'); + console.log('\nSequelizeMeta 表记录数:', rows.length); + rows.forEach(r => console.log(' ' + r.name)); + } catch (e) { + console.log('SequelizeMeta 表不存在或查询失败:', e.message); + } + + // 表总数 + const [cnt] = await c.query("SELECT COUNT(*) AS cnt FROM information_schema.TABLES WHERE TABLE_SCHEMA='wms'"); + console.log('\n生产数据库表总数:', cnt[0].cnt); + + await c.end(); + + // 对比 + if (tables.length > 0) { + console.log('\n=== 结论 ==='); + console.log('请检查上述迁移记录表,对比迁移目录中', files.length, '个文件即可知道未执行迁移。'); + } + } catch (e) { + console.log('连接错误:', e.code, e.message); + } +})(); diff --git a/test/app/controller/system.storage.inventory.matchPutaway.test.js b/test/app/controller/system.storage.inventory.matchPutaway.test.js index 428fe81..3e319ca 100644 --- a/test/app/controller/system.storage.inventory.matchPutaway.test.js +++ b/test/app/controller/system.storage.inventory.matchPutaway.test.js @@ -464,7 +464,7 @@ describe('test/app/controller/system.storage.inventory.matchPutaway.test.js', () { replacements: { id: entryOrder.id }, type: Sequelize.QueryTypes.SELECT } ); console.log(`[INSUF] 入库单 order_status: ${entryRows.order_status}`); - assert.equal(entryRows.order_status, 'PARTIAL_RECEIVED', `入库单应部分收货, 实际: ${entryRows.order_status}`); + assert.equal(entryRows.order_status, 'PENDING', `入库单应部分收货(状态保持PENDING), 实际: ${entryRows.order_status}`); // 6. 验证 warnings 包含提示(收货量 < 入库计划量) const warnings = resultData.warnings || []; diff --git a/test/app/model/order_delivery_dispatch_factory.test.js b/test/app/model/order_delivery_dispatch_factory.test.js index 534bf89..c6107bf 100644 --- a/test/app/model/order_delivery_dispatch_factory.test.js +++ b/test/app/model/order_delivery_dispatch_factory.test.js @@ -34,12 +34,13 @@ function createSequelizeTypes() { STRING: length => makeType(`VARCHAR(${length})`), BIGINT: unsignedBigInt, DECIMAL: (precision, scale) => makeType(`DECIMAL(${precision},${scale})`), - TEXT: makeType('TEXT'), + TEXT: (length) => makeType(length ? `TEXT(${length})` : 'TEXT'), ENUM: (...values) => makeType(`ENUM('${values.join("','")}')`), DATE: makeType('DATETIME'), INTEGER: length => makeType(`INT(${length})`), CHAR: length => makeType(`CHAR(${length})`), SMALLINT: length => makeType(`SMALLINT(${length})`), + JSON: makeType('JSON'), }; } diff --git a/test/app/service/systems/order_storage_allocation.test.js b/test/app/service/systems/order_storage_allocation.test.js index 8d23e2d..c865550 100644 --- a/test/app/service/systems/order_storage_allocation.test.js +++ b/test/app/service/systems/order_storage_allocation.test.js @@ -119,6 +119,7 @@ function createHarness(options = {}) { qm: null, manual: null, api: null, + operationLogs: null, }; const orders = Array.isArray(options.orders) ? options.orders.map(item => ({ ...item })) : []; @@ -319,17 +320,36 @@ function createHarness(options = {}) { }; }, }, + operationLog: { + async createOperationLogs(logItems) { + captures.operationLogs = logItems; + return { success: true }; + }, + }, orderAsync: { async syncQmOrders(groupedOrder, context) { captures.qm = { groupedOrder, context }; + if (typeof options.onSyncQmOrders === 'function') { + return await options.onSyncQmOrders(groupedOrder, context); + } return { create_channel: 'QM', + status: 'success', handler: 'syncQmOrders', sync_target: 'qimen', order_ids: groupedOrder.order_ids, order_count: groupedOrder.order_count, warehouse_id: context.warehouseId, route_state: 'accepted', + message: '奇门发货单确认成功', + success_count: 1, + failed_count: 0, + qimen_results: groupedOrder.order_ids.map(orderId => ({ + order_id: orderId, + status: 'success', + message: '奇门发货单确认成功', + qimen_flag: 'success', + })), }; }, async syncManualOrders(groupedOrder, context) { @@ -1364,4 +1384,98 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => { assert.equal(unlocksAfterCleanup.length, 1, '清理阶段应调用 unlockQuantity'); assert.deepEqual(unlocksAfterCleanup[0], { storageId: 8001, quantity: 1 }); }); + + it('should write error message in operation log when QM sync fails', async () => { + const { service, captures } = createHarness({ + orders: [ + { id: 51, warehouse_id: 100000, express_code: 'WB-051', post_status: 'padding', sync_status: 'padding', create_channel: 'QM' }, + ], + onSyncQmOrders: async (groupedOrder, context) => ({ + create_channel: 'QM', + status: 'failed', + handler: 'syncQmOrders', + sync_target: 'qimen', + order_ids: groupedOrder.order_ids, + order_count: groupedOrder.order_count, + warehouse_id: context.warehouseId, + route_state: 'rejected', + message: '奇门发货单确认失败', + success_count: 0, + failed_count: 1, + qimen_results: groupedOrder.order_ids.map(orderId => ({ + order_id: orderId, + status: 'failed', + message: 'Invalid arguments:parameter format is xml , but parse error', + qimen_flag: 'failure', + qimen_code: 'TOP41', + qimen_message: 'Invalid arguments:parameter format is xml , but parse error', + error: 'Invalid arguments:parameter format is xml , but parse error', + })), + }), + }); + + const result = await service.syncOrderIds({ + order_ids: [ 51 ], + }); + + assert.equal(result.code, 200); + assert.equal(result.data.dispatch_failed_count, 1); + assert.equal(result.data.dispatch_results[0].status, 'failed'); + + // 验证操作日志包含了失败信息 + assert.ok(Array.isArray(captures.operationLogs), '应有操作日志'); + assert.equal(captures.operationLogs.length, 1, '应有 1 条日志'); + assert.ok( + captures.operationLogs[0].extras.message.includes('失败'), + `日志消息应包含"失败",实际: ${captures.operationLogs[0].extras.message}` + ); + assert.ok( + captures.operationLogs[0].extras.message.includes('parse error'), + `日志消息应包含具体错误原因,实际: ${captures.operationLogs[0].extras.message}` + ); + assert.equal(captures.operationLogs[0].extras.warehouseId, 100000); + assert.equal(captures.operationLogs[0].businessType, 'order'); + assert.equal(captures.operationLogs[0].operationCode, 'ORDER_SYNC'); + }); + + it('should write success message in operation log when QM sync succeeds', async () => { + const { service, captures } = createHarness({ + orders: [ + { id: 52, warehouse_id: 100000, express_code: 'WB-052', post_status: 'padding', sync_status: 'padding', create_channel: 'QM' }, + ], + }); + + const result = await service.syncOrderIds({ + order_ids: [ 52 ], + }); + + assert.equal(result.code, 200); + + // 验证操作日志包含了成功信息 + assert.ok(Array.isArray(captures.operationLogs), '应有操作日志'); + const qmLog = captures.operationLogs.find(log => log.businessId === '52'); + assert.ok(qmLog, '应有订单 52 的日志'); + assert.equal(qmLog.extras.message, '同步到QM渠道'); + }); + + it('should write skip message for already synced orders', async () => { + const { service, captures } = createHarness({ + orders: [ + { id: 53, warehouse_id: 100000, express_code: 'WB-053', post_status: 'padding', sync_status: 'fin', create_channel: 'QM' }, + ], + }); + + const result = await service.syncOrderIds({ + order_ids: [ 53 ], + }); + + assert.equal(result.code, 200); + assert.equal(result.data.skipped_count, 1); + + // 验证操作日志 + assert.ok(Array.isArray(captures.operationLogs), '应有操作日志'); + const skipLog = captures.operationLogs.find(log => log.businessId === '53'); + assert.ok(skipLog, '应有订单 53 的日志'); + assert.ok(skipLog.extras.message.includes('跳过'), `跳过订单应含"跳过",实际: ${skipLog.extras.message}`); + }); }); From 569a25390f5026f5e45519ff62cc7087260879c3 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Wed, 24 Jun 2026 07:36:43 +0800 Subject: [PATCH 075/550] 1 --- app/model/stock_barcode.js | 43 ++++ app/model/stock_warehouse.js | 41 ++++ .../systemMethods/order/pendingOrder.js | 53 +---- .../systemMethods/order/recheckOrder.js | 208 ++++++++++++++---- app/service/systemMethods/storage/entry.js | 33 ++- app/service/systems/order_export.js | 73 +++--- app/service/systems/stock_store.js | 51 ++--- app/service/systems/stock_warehouse.js | 208 ++++++++++++++++++ app/service/systems/storage/entry.js | 87 ++++++-- app/service/systems/storage/inventory.js | 119 +++------- app/service/systems/storage/report.js | 206 ++++++++--------- .../systems/storage/stock_warehouse.js | 185 ++++++++++++++++ memories/repo/stock-detail-cache-service.md | 27 +++ methods/changes/system.json | 17 ++ methods/system.json | 110 ++++++++- temp_storage_entry_old.js | Bin 0 -> 52592 bytes temp_systemMethods_storage_entry_old.js | Bin 0 -> 4822 bytes 17 files changed, 1075 insertions(+), 386 deletions(-) create mode 100644 app/service/systems/stock_warehouse.js create mode 100644 app/service/systems/storage/stock_warehouse.js create mode 100644 memories/repo/stock-detail-cache-service.md create mode 100644 temp_storage_entry_old.js create mode 100644 temp_systemMethods_storage_entry_old.js diff --git a/app/model/stock_barcode.js b/app/model/stock_barcode.js index 374a892..f34f960 100644 --- a/app/model/stock_barcode.js +++ b/app/model/stock_barcode.js @@ -68,6 +68,49 @@ module.exports = app => { ], }); + /** + * 商品详情缓存 key 前缀。 + * 与 app/service/systems/stock_warehouse.js 中保持一致。 + */ + const STOCK_DETAIL_CACHE_PREFIX = 'cache:stock_detail'; + + /** + * 构建商品详情缓存 key。 + * @param {number} warehouseId 仓库ID + * @param {number} stockId 仓库商品ID + * @return {string} 缓存 key + */ + function buildStockDetailCacheKey(warehouseId, stockId) { + return `${STOCK_DETAIL_CACHE_PREFIX}:${warehouseId}:${stockId}`; + } + + /** + * 条码变更后自动清除关联的商品详情缓存。 + * 直接在 hook 中使用 async/await,缓存删除很快不会阻塞主流程。 + * @param {Object} instance Sequelize 模型实例 + * @return {Promise} + */ + async function invalidateStockDetailCacheForBarcode(instance) { + try { + const warehouseId = instance.get('warehouse_id'); + const stockId = instance.get('stock_id'); + if (warehouseId && stockId) { + const cacheKey = buildStockDetailCacheKey(warehouseId, stockId); + if (typeof app.delCacheAsync === 'function') { + await app.delCacheAsync(cacheKey); + app.logger.info(`[StockBarcode] 已清除商品详情缓存: ${cacheKey}`); + } + } + } catch (err) { + app.logger.error(`[StockBarcode] 清除商品详情缓存失败: ${err.message}`); + } + } + + // 注册 hooks:条码新增/更新/删除时自动清除关联商品详情缓存 + StockBarcode.addHook('afterCreate', 'invalidateStockDetailCache', invalidateStockDetailCacheForBarcode); + StockBarcode.addHook('afterUpdate', 'invalidateStockDetailCache', invalidateStockDetailCacheForBarcode); + StockBarcode.addHook('afterDestroy', 'invalidateStockDetailCache', invalidateStockDetailCacheForBarcode); + // 定义关联关系 StockBarcode.associate = function() { const { StockWarehouse } = app.model; diff --git a/app/model/stock_warehouse.js b/app/model/stock_warehouse.js index be9deb1..1244787 100644 --- a/app/model/stock_warehouse.js +++ b/app/model/stock_warehouse.js @@ -242,6 +242,47 @@ module.exports = app => { ], }); + /** + * 商品详情缓存 key 前缀。 + * 与 app/service/systems/stock_warehouse.js 中保持一致。 + */ + const STOCK_DETAIL_CACHE_PREFIX = 'cache:stock_detail'; + + /** + * 构建商品详情缓存 key。 + * @param {number} warehouseId 仓库ID + * @param {number} stockId 仓库商品ID + * @return {string} 缓存 key + */ + function buildStockDetailCacheKey(warehouseId, stockId) { + return `${STOCK_DETAIL_CACHE_PREFIX}:${warehouseId}:${stockId}`; + } + + /** + * 资料变更后自动清除商品详情缓存。 + * 直接在 afterUpdate hook 中使用 async/await,缓存删除很快不会阻塞主流程。 + * @param {Object} instance Sequelize 模型实例 + * @return {Promise} + */ + async function invalidateStockDetailCacheAfterUpdate(instance) { + try { + const warehouseId = instance.get('warehouse_id'); + const stockId = instance.get('id'); + if (warehouseId && stockId) { + const cacheKey = buildStockDetailCacheKey(warehouseId, stockId); + if (typeof app.delCacheAsync === 'function') { + await app.delCacheAsync(cacheKey); + app.logger.info(`[StockWarehouse.afterUpdate] 已清除商品详情缓存: ${cacheKey}`); + } + } + } catch (err) { + app.logger.error(`[StockWarehouse.afterUpdate] 清除商品详情缓存失败: ${err.message}`); + } + } + + // 注册 afterUpdate hook:商品资料更新时自动清除详情缓存 + StockWarehouse.addHook('afterUpdate', 'invalidateStockDetailCache', invalidateStockDetailCacheAfterUpdate); + StockWarehouse.associate = function() { const { StoreWarehouse, StockBarcode, ProhibitedType, StockStore, Storage } = app.model; // store_stock 关联依赖 store_id + warehouse_id 复合语义,单列关联仅作为 include 入口。 diff --git a/app/service/systemMethods/order/pendingOrder.js b/app/service/systemMethods/order/pendingOrder.js index 67f8f8b..a037f68 100644 --- a/app/service/systemMethods/order/pendingOrder.js +++ b/app/service/systemMethods/order/pendingOrder.js @@ -573,18 +573,12 @@ class PendingOrderService extends OrderBaseService { ) ]; const stockMap = new Map(); if (stockIds.length > 0) { - const StockWarehouse = this.ctx.model.StockWarehouse; - if (StockWarehouse) { - const stockWarehouseRows = await StockWarehouse.findAll({ - where: { - id: { [this.app.Sequelize.Op.in]: stockIds }, - warehouse_id: warehouseId, - }, - raw: true, - }); - for (const row of stockWarehouseRows) { - stockMap.set(row.id, row); - } + const stockDetails = await this.ctx.service.systems.stockWarehouse.getStockDetails( + stockIds, + { warehouseId } + ); + for (const detail of stockDetails) { + stockMap.set(detail.id, detail); } } @@ -5242,39 +5236,8 @@ class PendingOrderService extends OrderBaseService { }); if (!Array.isArray(pickingRows) || pickingRows.length === 0) { - // 无储位分配记录:从订单明细获取锁定信息,只释放 stock_warehouse 锁 - const orderItemsModel = await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId); - if (!orderItemsModel) { - ctx.logger.warn('[PendingOrderService.releaseCreationLockForCancel] OrderItems 模型不可用,跳过库存释放'); - await transaction.rollback(); - return; - } - - const orderItems = await orderItemsModel.findAll({ - where: { order_id: { [Op.in]: orderIds } }, - attributes: [ 'stock_id', 'plan_qty' ], - raw: true, - transaction, - }); - - for (const item of orderItems) { - const stockId = Number(item.stock_id || 0); - const qty = Number(item.plan_qty || 0); - if (stockId <= 0 || qty <= 0) continue; - - await stockModel.update( - { - locked_quantity: app.Sequelize.literal(`locked_quantity - ${qty}`), - updated_at: app.Sequelize.literal('CURRENT_TIMESTAMP'), - }, - { - where: { id: stockId, locked_quantity: { [Op.gte]: qty } }, - transaction, - } - ); - } - - await transaction.commit(); + // 无储位分配记录:picking 已被 cancelAllocateStorage 处理完毕,无需再次释放 + await transaction.rollback(); return; } diff --git a/app/service/systemMethods/order/recheckOrder.js b/app/service/systemMethods/order/recheckOrder.js index 8753912..53cc57b 100644 --- a/app/service/systemMethods/order/recheckOrder.js +++ b/app/service/systemMethods/order/recheckOrder.js @@ -1271,41 +1271,26 @@ class RecheckOrderService extends OrderBaseService { .filter(Boolean) ) ]; - // 3. 批量查询库存信息 + // 3. 批量查询库存信息(复用 getStockDetails,含条码与图片) const stockMap = new Map(); - if (stockIds.length > 0 && this.ctx.model && this.ctx.model.StockWarehouse) { - const stockRows = await this.ctx.model.StockWarehouse.findAll({ - where: { - id: { [this.app.Sequelize.Op.in]: stockIds }, - warehouse_id: warehouseId, - }, - attributes: [ 'id', 'item_code', 'item_name', 'sku_property', 'packing_requirements' ], - raw: true, - }); - for (const row of (Array.isArray(stockRows) ? stockRows : [])) { - stockMap.set(Number(row.id), row); - } - } - - // 4. 批量查询条码 const barcodeMap = new Map(); - if (stockIds.length > 0 && this.ctx.model && this.ctx.model.StockBarcode) { - const barcodeRows = await this.ctx.model.StockBarcode.findAll({ - where: { - stock_id: { [this.app.Sequelize.Op.in]: stockIds }, - warehouse_id: warehouseId, - }, - attributes: [ 'stock_id', 'barcode' ], - raw: true, - }); - for (const row of (Array.isArray(barcodeRows) ? barcodeRows : [])) { - const sid = Number(row.stock_id); - const barcodeVal = String(row.barcode || '').trim(); - if (!barcodeMap.has(sid)) { - barcodeMap.set(sid, []); + const imagesByStockId = new Map(); + if (stockIds.length > 0) { + const stockDetails = await this.ctx.service.systems.stockWarehouse.getStockDetails( + stockIds, + { warehouseId } + ); + for (const detail of stockDetails) { + const sid = Number(detail.id); + stockMap.set(sid, detail); + // 从 getStockDetails 提取条码 + if (Array.isArray(detail.barcodes) && detail.barcodes.length > 0) { + barcodeMap.set(sid, detail.barcodes.map(bc => String(bc.barcode || '').trim()).filter(Boolean)); } - if (barcodeVal) { - barcodeMap.get(sid).push(barcodeVal); + // 从 getStockDetails 提取图片 URL + const detailImageUrl = String(detail.image_url || '').trim(); + if (detailImageUrl) { + imagesByStockId.set(sid, [ detailImageUrl ]); } } } @@ -1338,10 +1323,7 @@ class RecheckOrderService extends OrderBaseService { } } - // 6. 批量查询图片 - const imagesByStockId = await this.getOrderItemImagesByStockIds(itemsArray); - - // 7. 按 order_id 分组商品明细 + // 6. 按 order_id 分组商品明细 const itemsByOrderId = new Map(); for (const item of itemsArray) { const oid = Number(item.order_id); @@ -1351,7 +1333,7 @@ class RecheckOrderService extends OrderBaseService { itemsByOrderId.get(oid).push(item); } - // 8. 为每个订单构建 stock 数组 + // 7. 为每个订单构建 stock 数组 return orderList.map(order => { const oid = Number(order.order_id || 0); const items = itemsByOrderId.get(oid) || []; @@ -1624,6 +1606,10 @@ class RecheckOrderService extends OrderBaseService { now, }); + // 散单复核完成后,检查订单所属波次下所有订单是否均已复核完成, + // 若全部完成则更新波次状态为复核完成(wave_status=5),使波次从 batchList 中消失 + await this._tryCompleteWaveIfAllOrdersRechecked(orderId, order.wave_id, warehouseId, operator, now); + return { order_id: orderId, waybill_no: waybillNo, @@ -3930,6 +3916,154 @@ class RecheckOrderService extends OrderBaseService { now, transaction, }); + + // 散单复核完成后,在事务内检查订单所属波次下所有订单是否均已复核完成, + // 若全部完成则更新波次状态为复核完成(wave_status=5),使波次从 batchList 中消失 + await this._tryCompleteWaveInTransaction(orderId, order.wave_id, warehouseId, operator, now, transaction); + } + + /** + * 散单复核完成后,检查订单所属波次下所有订单是否均已复核完成, + * 若全部完成则更新 wms_wave_batch.wave_status = 5(复核完成), + * 使该波次从 batchList 中自然消失。 + * + * @param {number} orderId 当前复核的订单ID。 + * @param {number|string|null} waveId 订单所属波次ID。 + * @param {number} warehouseId 仓库ID。 + * @param {{ id: string|null, name: string }} operator 操作人信息。 + * @param {Date} now 当前时间。 + * @return {Promise} 无返回值。 + */ + async _tryCompleteWaveIfAllOrdersRechecked(orderId, waveId, warehouseId, operator, now) { + const { ctx } = this; + const normalizedWaveId = Number(waveId); + if (!Number.isFinite(normalizedWaveId) || normalizedWaveId <= 0) { + return; + } + + // 查询波次下是否还有未复核的订单(recheck_status != 'fin') + const orderModel = await this.getOrderModelByTableType('current', warehouseId); + const unreviewedCount = await orderModel.count({ + where: { + wave_id: normalizedWaveId, + warehouse_id: warehouseId, + recheck_status: { [this.app.Sequelize.Op.ne]: 'fin' }, + }, + }); + + if (unreviewedCount > 0) { + return; + } + + // 波次下所有订单均已复核完成,查询已完成订单数并更新波次状态 + const processedCount = await orderModel.count({ + where: { + wave_id: normalizedWaveId, + warehouse_id: warehouseId, + recheck_status: 'fin', + }, + }); + + const operatorName = String(operator.name || operator.id || '').trim(); + + await ctx.model.query( + `UPDATE wms_wave_batch + SET wave_status = 5, + check_operator = :operatorName, + check_time = :now, + processed_orders = :processedCount, + update_time = :now + WHERE wave_id = :waveId + AND warehouse_id = :warehouseId`, + { + replacements: { + waveId: normalizedWaveId, + warehouseId, + operatorName, + processedCount, + now, + }, + type: ctx.model.QueryTypes.UPDATE, + } + ); + + ctx.logger.info( + `[confirmRecheck] 波次复核完成, waveId=${normalizedWaveId}, orderId=${orderId}, processedCount=${processedCount}` + ); + } + + /** + * 在事务内检查订单所属波次下所有订单是否均已复核完成, + * 若全部完成则更新 wms_wave_batch.wave_status = 5(复核完成)。 + * 用于批量快捷复核(batchQuickRecheck)事务内的散单路径。 + * + * @param {number} orderId 当前复核的订单ID。 + * @param {number|string|null} waveId 订单所属波次ID。 + * @param {number} warehouseId 仓库ID。 + * @param {{ id: string|null, name: string }} operator 操作人信息。 + * @param {Date} now 当前时间。 + * @param {Object} transaction Sequelize 事务对象。 + * @return {Promise} 无返回值。 + */ + async _tryCompleteWaveInTransaction(orderId, waveId, warehouseId, operator, now, transaction) { + const { ctx } = this; + const normalizedWaveId = Number(waveId); + if (!Number.isFinite(normalizedWaveId) || normalizedWaveId <= 0) { + return; + } + + // 在事务内查询波次下是否还有未复核的订单(recheck_status != 'fin') + const orderModel = await this.getOrderModel('order', warehouseId); + const unreviewedCount = await orderModel.count({ + where: { + wave_id: normalizedWaveId, + warehouse_id: warehouseId, + recheck_status: { [this.app.Sequelize.Op.ne]: 'fin' }, + }, + transaction, + }); + + if (unreviewedCount > 0) { + return; + } + + // 波次下所有订单均已复核完成,查询已完成订单数并更新波次状态 + const processedCount = await orderModel.count({ + where: { + wave_id: normalizedWaveId, + warehouse_id: warehouseId, + recheck_status: 'fin', + }, + transaction, + }); + + const operatorName = String(operator.name || operator.id || '').trim(); + + await ctx.model.query( + `UPDATE wms_wave_batch + SET wave_status = 5, + check_operator = :operatorName, + check_time = :now, + processed_orders = :processedCount, + update_time = :now + WHERE wave_id = :waveId + AND warehouse_id = :warehouseId`, + { + replacements: { + waveId: normalizedWaveId, + warehouseId, + operatorName, + processedCount, + now, + }, + type: ctx.model.QueryTypes.UPDATE, + transaction, + } + ); + + ctx.logger.info( + `[batchQuickRecheck] 波次复核完成, waveId=${normalizedWaveId}, orderId=${orderId}, processedCount=${processedCount}` + ); } /** diff --git a/app/service/systemMethods/storage/entry.js b/app/service/systemMethods/storage/entry.js index bfcfb2a..c3e169b 100644 --- a/app/service/systemMethods/storage/entry.js +++ b/app/service/systemMethods/storage/entry.js @@ -155,27 +155,35 @@ class entryService extends MainService { const entryOrder = entryResult.data.entryOrder; const items = Array.isArray(entryOrder.items) ? entryOrder.items : []; - // 查询商品条码(批量) + // 查询商品条码和图片(复用 getStockDetails 缓存) const barcodeMap = new Map(); + const imageMap = new Map(); try { const stockIds = items .map(item => Number(item.stock_id || 0)) .filter(sid => sid > 0); - if (stockIds.length > 0 && ctx.model.StockBarcode) { - const barcodeRows = await ctx.model.StockBarcode.findAll({ - where: { stock_id: { [ctx.app.Sequelize.Op.in]: stockIds } }, - attributes: [ 'stock_id', 'barcode' ], - raw: true, - }); - for (const row of barcodeRows) { - if (!barcodeMap.has(row.stock_id)) { - barcodeMap.set(row.stock_id, []); + if (stockIds.length > 0) { + const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails( + stockIds, + {} + ); + for (const detail of stockDetails) { + const sid = Number(detail.id); + // 提取条码 + if (Array.isArray(detail.barcodes) && detail.barcodes.length > 0) { + barcodeMap.set( + sid, + detail.barcodes.map(bc => String(bc.barcode || '').trim()).filter(Boolean) + ); + } + // 提取图片(有图片标记但实际 URL 需要额外查询) + if (detail.is_images === 'Y') { + imageMap.set(sid, ''); } - barcodeMap.get(row.stock_id).push(row.barcode); } } } catch (err) { - ctx.logger.warn('[entry.getPrintData] 查询条码失败: %s', err.message); + ctx.logger.warn('[entry.getPrintData] 查询商品详情失败: %s', err.message); } const printData = { @@ -199,6 +207,7 @@ class entryService extends MainService { items_col4: item.count || 0, items_col5: item.received_quantity || 0, items_col6: item.inventory_type || '', + items_col7: imageMap.get(Number(item.stock_id)) || '', })), }; diff --git a/app/service/systems/order_export.js b/app/service/systems/order_export.js index fad099a..6924308 100644 --- a/app/service/systems/order_export.js +++ b/app/service/systems/order_export.js @@ -83,6 +83,7 @@ const ORDER_EXPORT_ITEM_COLUMNS = Object.freeze([ { header: '详细地址', key: 'receiver_detail', width: 30 }, { header: '仓库商品名称', key: 'item_name', width: 30 }, { header: '商品条码', key: 'item_barcode', width: 24 }, + { header: '商品图片', key: 'item_image', width: 40 }, { header: '数量', key: 'item_quantity', width: 10 }, { header: '物流公司', key: 'logistics_name', width: 18 }, { header: '运单号', key: 'waybill_code', width: 30 }, @@ -329,6 +330,7 @@ class OrderExportService extends OrderBaseService { * @param {Map} [context.storeRemarkMap] 货主ID → 货主备注的映射。 * @param {Map} [context.stockNameMap] stockId → 仓库商品名称的映射。 * @param {Map} [context.barcodeMap] stockId → 商品条码(逗号拼接)的映射。 + * @param {Map} [context.imageUrlMap] stockId → 商品图片URL的映射。 * @param {Map>} [context.expressMap] 订单ID → 运单行列表的映射。 * @param {Map} [context.packageMaterialMap] package_material_id → 包材编码的映射。 * @param {string} [mode='waybill'] 导出模式:'waybill' 或 'item'。 @@ -336,7 +338,7 @@ class OrderExportService extends OrderBaseService { */ mapOrderExportRow(orderRow = {}, context = {}, mode = 'waybill') { const safeOrderRow = this.isPlainObject(orderRow) ? orderRow : {}; - const { itemsMap, storeRemarkMap, stockNameMap, barcodeMap, expressMap, packageMaterialMap } = context; + const { itemsMap, storeRemarkMap, stockNameMap, barcodeMap, imageUrlMap, expressMap, packageMaterialMap } = context; const safeItemsMap = itemsMap instanceof Map ? itemsMap : new Map(); const safeStoreRemarkMap = storeRemarkMap instanceof Map ? storeRemarkMap : new Map(); const safeExpressMap = expressMap instanceof Map ? expressMap : new Map(); @@ -377,6 +379,7 @@ class OrderExportService extends OrderBaseService { const items = safeItemsMap.get(orderId) || []; const safeStockNameMap = stockNameMap instanceof Map ? stockNameMap : new Map(); const safeBarcodeMap = barcodeMap instanceof Map ? barcodeMap : new Map(); + const safeImageUrlMap = imageUrlMap instanceof Map ? imageUrlMap : new Map(); const itemsDetail = Array.isArray(items) && items.length > 0 ? items.map(item => { const stockId = Number(item.stock_id || 0); @@ -440,6 +443,7 @@ class OrderExportService extends OrderBaseService { ...commonFields, item_name: '', item_barcode: '', + item_image: '', item_quantity: '', business_type: businessType, logistics_interface_name: this.normalizeExportCellValue(interfaceName), @@ -458,6 +462,7 @@ class OrderExportService extends OrderBaseService { ...commonFields, item_name: (sid > 0 ? safeStockNameMap.get(sid) : '') || item.item_name || '', item_barcode: sid > 0 ? (safeBarcodeMap.get(sid) || '') : '', + item_image: sid > 0 ? (safeImageUrlMap.get(sid) || '') : '', item_quantity: item.plan_qty || 1, business_type: businessType, logistics_interface_name: this.normalizeExportCellValue(interfaceName), @@ -691,8 +696,10 @@ class OrderExportService extends OrderBaseService { } } - // 批量查询仓库商品名称(wms_stock_warehouse.item_name) + // 批量查询仓库商品名称、条码与图片(复用 getStockDetails 缓存) const stockNameMap = new Map(); + const barcodeMap = new Map(); + const imageUrlMap = new Map(); if (itemsMap.size > 0 && this.ctx && this.ctx.model && this.ctx.model.StockWarehouse) { try { const stockIds = [ @@ -704,22 +711,30 @@ class OrderExportService extends OrderBaseService { ), ]; if (stockIds.length > 0) { - const swRows = await this.ctx.model.StockWarehouse.findAll({ - where: { - id: { [this.app.Sequelize.Op.in]: stockIds }, - }, - attributes: [ 'id', 'item_name' ], - raw: true, - }); - for (const sw of (Array.isArray(swRows) ? swRows : [])) { - const sid = Number(sw.id || 0); - if (sid > 0 && !stockNameMap.has(sid)) { - stockNameMap.set(sid, String(sw.item_name || '').trim()); + const stockDetails = await this.ctx.service.systems.stockWarehouse.getStockDetails( + stockIds, + { warehouseId } + ); + for (const detail of stockDetails) { + const sid = Number(detail.id || 0); + if (sid > 0) { + stockNameMap.set(sid, String(detail.item_name || '').trim()); + // 从 getStockDetails 的 barcodes 中提取条码并转为逗号拼接 + const barcodesRaw = Array.isArray(detail.barcodes) + ? detail.barcodes.map(bc => String(bc.barcode || '').trim()).filter(Boolean) + : []; + if (barcodesRaw.length > 0) { + barcodeMap.set(sid, [ ...new Set(barcodesRaw) ].join(', ')); + } + // 图片字段(有图片标记但实际 URL 需要额外查询) + if (detail.is_images === 'Y') { + imageUrlMap.set(sid, ''); + } } } } } catch (err) { - this.app.logger.warn(`[order_export] 批量查询仓库商品名称失败: ${err.message}`); + this.app.logger.warn(`[order_export] 批量查询商品详情失败: ${err.message}`); } } @@ -782,34 +797,6 @@ class OrderExportService extends OrderBaseService { } } - // 批量查询商品条码(wms_stock_barcodes) - const barcodeMap = new Map(); - if (stockNameMap.size > 0 && this.ctx && this.ctx.model && this.ctx.model.StockBarcode) { - try { - const stockIdsForBarcode = [ ...stockNameMap.keys() ]; - if (stockIdsForBarcode.length > 0) { - const bcRows = await this.ctx.model.StockBarcode.findAll({ - where: { stock_id: { [this.app.Sequelize.Op.in]: stockIdsForBarcode } }, - attributes: [ 'stock_id', 'barcode' ], - raw: true, - }); - for (const bc of (Array.isArray(bcRows) ? bcRows : [])) { - const sid = Number(bc.stock_id || 0); - if (sid > 0) { - if (!barcodeMap.has(sid)) barcodeMap.set(sid, []); - barcodeMap.get(sid).push(String(bc.barcode || '').trim()); - } - } - // 转为逗号拼接 - for (const [ sid, codes ] of barcodeMap) { - barcodeMap.set(sid, [ ...new Set(codes.filter(Boolean)) ].join(', ')); - } - } - } catch (err) { - this.app.logger.warn(`[order_export] 批量查询商品条码失败: ${err.message}`); - } - } - // 批量查询包材编码(wms_package_material),按 package_material_id 分组 const packageMaterialMap = new Map(); if (expressMap.size > 0 && this.ctx && this.ctx.model && this.ctx.model.PackageMaterial) { @@ -840,7 +827,7 @@ class OrderExportService extends OrderBaseService { } } - const exportContext = { itemsMap, storeRemarkMap, stockNameMap, barcodeMap, expressMap, packageMaterialMap }; + const exportContext = { itemsMap, storeRemarkMap, stockNameMap, barcodeMap, imageUrlMap, expressMap, packageMaterialMap }; for (const row of normalizedRows) { const exportRows = this.mapOrderExportRow(row, exportContext, mode); diff --git a/app/service/systems/stock_store.js b/app/service/systems/stock_store.js index 4a19ad4..ece8b01 100644 --- a/app/service/systems/stock_store.js +++ b/app/service/systems/stock_store.js @@ -1911,33 +1911,23 @@ class stockStoreService extends Service { const hasPrevious = page > 1; const hasNext = page < totalPages; - // 批量查询条码信息 + // 批量查询条码和图片信息(复用 getStockDetails 缓存) const stockIds = data.map(item => item.id); - let barcodes = []; - let images = []; + const stockDetailsMap = new Map(); if (stockIds.length > 0) { - barcodes = await ctx.model.StockBarcode.findAll({ - where: { - stock_id: { - [Op.in]: stockIds, - }, - }, - raw: true, - }); - images = await ctx.model.FileReference.findAll({ - where: { - business_type: 'stock', - business_id: { - [Op.in]: stockIds, - }, - }, - include: [{ - model: ctx.model.File, - as: 'file', - attributes: [ 'file_url' ], - required: true, - }], - }); + const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails( + stockIds, + { warehouseId: ctx.user.store_id } + ); + for (const detail of stockDetails) { + const sid = Number(detail.id); + stockDetailsMap.set(sid, { + barcodes: Array.isArray(detail.barcodes) + ? detail.barcodes.map(bc => String(bc.barcode || '').trim()).filter(Boolean) + : [], + images: detail.is_images === 'Y' ? [] : [], + }); + } } // 处理数据,添加一些计算字段 @@ -1946,13 +1936,10 @@ class stockStoreService extends Service { const lockRate = item.quantity > 0 ? (item.locked_quantity / item.quantity * 100).toFixed( 2) : 0; - // 过滤该商品的条码 - const itemBarcodes = barcodes - .filter(barcode => barcode.stock_id === item.id) - .map(barcode => barcode.barcode); - const itemImages = images - .filter(images => parseInt(images.business_id) === item.id) - .map(images => images.file.file_url); + // 从 getStockDetails 获取该商品的条码和图片 + const stockDetail = stockDetailsMap.get(item.id); + const itemBarcodes = stockDetail ? stockDetail.barcodes : []; + const itemImages = stockDetail ? stockDetail.images : []; return { ...item, barcodes: itemBarcodes, diff --git a/app/service/systems/stock_warehouse.js b/app/service/systems/stock_warehouse.js new file mode 100644 index 0000000..b3378ba --- /dev/null +++ b/app/service/systems/stock_warehouse.js @@ -0,0 +1,208 @@ +'use strict'; + +const Service = require('egg').Service; + +/** + * 仓库商品详情缓存的 key 前缀模板。 + * 最终 key 格式:cache:stock_detail:{warehouseId}:{stockId} + */ +const STOCK_DETAIL_CACHE_KEY_PREFIX = 'cache:stock_detail'; +/** 仓库商品详情缓存默认 TTL(秒) */ +const DEFAULT_STOCK_DETAIL_CACHE_TTL = 300; + +class StockWarehouseService extends Service { + /** + * 构建仓库商品详情缓存的 Redis key。 + * @param {number} warehouseId 仓库ID + * @param {number} stockId 仓库商品ID + * @return {string} 缓存 key + */ + _buildStockDetailCacheKey(warehouseId, stockId) { + return `${STOCK_DETAIL_CACHE_KEY_PREFIX}:${warehouseId}:${stockId}`; + } + + /** + * 批量获取仓库商品详情(带缓存)。 + * 先按 stockId 逐个查缓存,未命中的批量查数据库, + * 然后将数据库结果写入缓存后合并返回。 + * 作为通用公共服务,所有模块均可调用。 + * + * @param {number[]} stockIds 要查询的 StockWarehouse ID 列表 + * @param {Object} [options={}] 选项 + * @param {number} [options.warehouseId] 仓库ID(优先使用 options.warehouseId,否则兜底 ctx.user.store_id) + * @param {number} [options.cacheTTL=300] 缓存过期时间(秒) + * @return {Promise}>>} 商品详情列表 + */ + async getStockDetails(stockIds, options = {}) { + const { ctx, app } = this; + const { cacheTTL = DEFAULT_STOCK_DETAIL_CACHE_TTL } = options; + const warehouseId = options.warehouseId != null ? options.warehouseId : ctx.user.store_id; + + if (!Array.isArray(stockIds) || stockIds.length === 0) { + return []; + } + + const uniqueStockIds = [ ...new Set(stockIds.map(id => Number(id))) ]; + const cacheHits = new Map(); + const missedStockIds = []; + + // 第一步:逐个查缓存 + for (const stockId of uniqueStockIds) { + const cacheKey = this._buildStockDetailCacheKey(warehouseId, stockId); + try { + const cached = await app.getCacheAsync(cacheKey); + if (cached !== null && cached !== undefined) { + cacheHits.set(stockId, cached); + } else { + missedStockIds.push(stockId); + } + } catch { + // 缓存读取异常时降级为查数据库 + missedStockIds.push(stockId); + } + } + + // 第二步:批量查数据库(只查未命中的 stockId) + /** @type {Map} */ + const dbResults = new Map(); + if (missedStockIds.length > 0) { + const stockWhere = { id: { [app.Sequelize.Op.in]: missedStockIds }, is_valid: 'Y' }; + if (warehouseId != null) { + stockWhere.warehouse_id = warehouseId; + } + + // 并行查询三表:库存主表、条码、图片(避免 N×M 笛卡尔积膨胀,在应用层做 join) + const [ stockRows, barcodeRows, imageRows ] = await Promise.all([ + ctx.model.StockWarehouse.findAll({ + where: stockWhere, + attributes: [ + 'id', 'item_code', 'item_name', 'sku_property', + 'quantity', 'locked_quantity', 'is_batch_mgmt', + 'is_shelf_life_mgmt', 'is_images', + 'store_id', 'packing_requirements', 'stock_unit', + ], + raw: true, + }), + ctx.model.StockBarcode.findAll({ + where: { stock_id: { [app.Sequelize.Op.in]: missedStockIds } }, + attributes: [ 'id', 'barcode', 'stock_id' ], + raw: true, + }), + ctx.model.FileReference.findAll({ + where: { + business_type: 'stock', + business_id: { [app.Sequelize.Op.in]: missedStockIds.map(String) }, + }, + include: [{ + model: ctx.model.File, + as: 'file', + attributes: [ 'file_url' ], + required: false, + }], + raw: true, + }), + ]); + + // 按 stock_id 分组条码 + const barcodeMap = new Map(); + for (const row of barcodeRows) { + const sid = row.stock_id; + if (!barcodeMap.has(sid)) { + barcodeMap.set(sid, []); + } + barcodeMap.get(sid).push({ + id: row.id, + barcode: row.barcode, + }); + } + + // 按 business_id(即 stock_id)分组图片URL + const imageUrlMap = new Map(); + for (const row of imageRows) { + const sid = Number(row.business_id); + if (!imageUrlMap.has(sid)) { + const url = (row['file.file_url'] && String(row['file.file_url']).trim()) || ''; + imageUrlMap.set(sid, url); + } + } + + // 组装每个 stock 的完整详情 + for (const row of stockRows) { + const detail = { + id: row.id, + item_code: row.item_code, + item_name: row.item_name, + sku_property: row.sku_property || '', + quantity: row.quantity || 0, + locked_quantity: row.locked_quantity || 0, + is_batch_mgmt: row.is_batch_mgmt || 'N', + is_shelf_life_mgmt: row.is_shelf_life_mgmt || 'N', + is_images: row.is_images || 'N', + store_id: row.store_id != null ? Number(row.store_id) : 0, + packing_requirements: row.packing_requirements || '', + stock_unit: row.stock_unit || '', + image_url: imageUrlMap.get(row.id) || '', + barcodes: barcodeMap.get(row.id) || [], + }; + dbResults.set(row.id, detail); + + // 第三步:写入缓存 + const cacheKey = this._buildStockDetailCacheKey(warehouseId, row.id); + try { + await app.setCacheAsync(cacheKey, detail, cacheTTL); + } catch { + // 缓存写入失败不影响主流程 + } + } + + // 对于数据库中也不存在的 stockId,写入空标记防止缓存穿透 + for (const stockId of missedStockIds) { + if (!dbResults.has(stockId)) { + const cacheKey = this._buildStockDetailCacheKey(warehouseId, stockId); + try { + // 用较短的 TTL 缓存空结果,避免缓存穿透 + await app.setCacheAsync(cacheKey, null, Math.min(cacheTTL, 60)); + } catch { + // 忽略缓存写入失败 + } + } + } + } + + // 第四步:合并缓存命中 + 数据库结果,保持原始 stockIds 顺序 + const result = []; + for (const stockId of uniqueStockIds) { + if (cacheHits.has(stockId)) { + const cached = cacheHits.get(stockId); + // 空标记(防穿透缓存)跳过 + if (cached !== null && cached !== undefined) { + result.push(cached); + } + } else if (dbResults.has(stockId)) { + result.push(dbResults.get(stockId)); + } + } + + return result; + } + + /** + * 使指定仓库商品的详情缓存失效。 + * 在商品资料更新、图片变更、条码变更时调用。 + * + * @param {number} stockId 仓库商品ID + * @param {number} warehouseId 仓库ID + * @return {Promise} + */ + async invalidateStockDetailCache(stockId, warehouseId) { + const { app } = this; + const cacheKey = this._buildStockDetailCacheKey(warehouseId, stockId); + try { + await app.delCacheAsync(cacheKey); + } catch { + // 删除缓存失败不影响主流程 + } + } +} + +module.exports = StockWarehouseService; diff --git a/app/service/systems/storage/entry.js b/app/service/systems/storage/entry.js index 1e05591..54792c1 100644 --- a/app/service/systems/storage/entry.js +++ b/app/service/systems/storage/entry.js @@ -402,10 +402,18 @@ class EntryService extends Service { * @param {Object} data 请求体 * @return {Promise} code/data/message 结构 */ + /** + * 查询入库单详情,含商品信息、条码、入库进度。 + * @param {Object} data 请求参数 + * @param {number} [data.id] 入库单主键 ID + * @param {string} [data.entry_order_code] 入库单号 + * @return {Promise} code/data/message 结构,data.entryOrder 为扁平化后的入库单详情 + */ async get(data = {}) { const { ctx } = this; const id = Number(data.id || 0); const entryOrderCode = data.entry_order_code ? String(data.entry_order_code).trim() : ''; + const warehouseId = ctx.user.store_id; if (!id && !entryOrderCode) { return { @@ -416,7 +424,7 @@ class EntryService extends Service { } const where = { - warehouse_id: ctx.user.store_id, + warehouse_id: warehouseId, is_enabled: 1, deleted_at: null, }; @@ -444,14 +452,7 @@ class EntryService extends Service { { model: ctx.model.EntryItems, as: 'items', - include: [ - { - model: ctx.model.StockWarehouse, - as: 'stock', - attributes: [ 'id', 'item_code', 'item_name', 'sku_property' ], - required: false, - }, - ], + attributes: [ 'id', 'order_id', 'out_biz_code', 'order_line_no', 'owner_code', 'item_code', 'item_id', 'count', 'inventory_type', 'stock_id', 'received_quantity', 'confirm_quantity' ], required: false, }, { @@ -478,18 +479,76 @@ class EntryService extends Service { }; } - // 扁平化 items:将外部商品字段重命名,stock 仓库商品字段平铺到 items 层级 const entryOrderJSON = entryOrder.toJSON(); + + // 收集所有 stock_id,通过 getStockDetails 获取带缓存的商品详情 + const stockIdSet = new Set(); + if (entryOrderJSON.items && Array.isArray(entryOrderJSON.items)) { + for (const item of entryOrderJSON.items) { + if (item.stock_id != null) { + stockIdSet.add(Number(item.stock_id)); + } + } + } + const stockIds = [ ...stockIdSet ]; + + /** @type {Map} */ + const stockDetailMap = new Map(); + if (stockIds.length > 0) { + const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(stockIds, { warehouseId }); + for (const detail of stockDetails) { + stockDetailMap.set(detail.id, detail); + } + } + + // 查询该入库单所有商品的直接入库进度(非收货单途径) + const directInboundMap = {}; + if (stockIds.length > 0) { + const directLogRows = await ctx.model.InboundDirectLog.findAll({ + attributes: [ + 'stock_id', + [ ctx.app.Sequelize.fn('SUM', ctx.app.Sequelize.col('quantity')), 'total_quantity' ], + ], + where: { + entry_order_code: entryOrderJSON.entry_order_code, + stock_id: { [ctx.app.Sequelize.Op.in]: stockIds }, + }, + group: [ 'stock_id' ], + raw: true, + }); + + for (const row of directLogRows) { + directInboundMap[row.stock_id] = Number(row.total_quantity) || 0; + } + } + + // 扁平化 items:用 getStockDetails 返回的商品详情替换原有的 stock + barcodes if (entryOrderJSON.items && Array.isArray(entryOrderJSON.items)) { entryOrderJSON.items = entryOrderJSON.items.map(item => { - const { item_code, item_id, stock, ...rest } = item; + const { item_code, item_id, stock_id: itemStockId, ...rest } = item; + const stockDetail = itemStockId != null ? stockDetailMap.get(Number(itemStockId)) || null : null; + const directInboundQty = (stockDetail && directInboundMap[stockDetail.id]) || 0; + const receivedQty = Number(rest.received_quantity) || 0; + const totalCount = Number(rest.count) || 0; + const remaining = Math.max(0, totalCount - receivedQty); + return { ...rest, + stock_id: itemStockId, external_item_code: item_code, external_item_id: item_id, - warehouse_item_code: (stock && stock.item_code) || '', - warehouse_item_name: (stock && stock.item_name) || '', - warehouse_item_spec: (stock && stock.sku_property) || '', + warehouse_item_code: (stockDetail && stockDetail.item_code) || '', + warehouse_item_name: (stockDetail && stockDetail.item_name) || '', + warehouse_item_spec: (stockDetail && stockDetail.sku_property) || '', + warehouse_quantity: (stockDetail && stockDetail.quantity != null) ? stockDetail.quantity : null, + warehouse_locked_quantity: (stockDetail && stockDetail.locked_quantity != null) ? stockDetail.locked_quantity : null, + warehouse_is_batch_mgmt: (stockDetail && stockDetail.is_batch_mgmt != null) ? stockDetail.is_batch_mgmt : null, + warehouse_is_shelf_life_mgmt: (stockDetail && stockDetail.is_shelf_life_mgmt != null) ? stockDetail.is_shelf_life_mgmt : null, + warehouse_image_url: (stockDetail && stockDetail.is_images === 'Y') ? '' : '', + warehouse_is_images: (stockDetail && stockDetail.is_images != null) ? stockDetail.is_images : null, + barcodes: (stockDetail && stockDetail.barcodes) || [], + direct_inbound_quantity: directInboundQty, + remaining_quantity: remaining, }; }); } diff --git a/app/service/systems/storage/inventory.js b/app/service/systems/storage/inventory.js index 293c87d..c3b0762 100644 --- a/app/service/systems/storage/inventory.js +++ b/app/service/systems/storage/inventory.js @@ -128,26 +128,9 @@ function toBooleanFlag(value) { return false; } -/** - * 将模型查询结果转换为普通对象。 - * - * @param {unknown} record 模型记录或普通对象 - * @return {Object|null} 普通对象 - */ -function toPlainRecord(record) { - if (!record) { - return null; - } - - if (typeof record.get === 'function') { - return record.get({ plain: true }); - } - - return record; -} - /** * 批量加载库存商品的条码与图片附属信息。 + * 复用 stock_warehouse.getStockDetails 缓存查询。 * * @param {Object} ctx 当前请求上下文 * @param {number[]} stockIds 商品ID列表 @@ -167,86 +150,36 @@ async function loadStockAttachments(ctx, stockIds = []) { return { barcodesByStockId, imagesByStockId }; } - const hasStockBarcodeModel = ctx.model && ctx.model.StockBarcode && typeof ctx.model.StockBarcode.findAll === 'function'; - if (hasStockBarcodeModel) { - try { - const barcodeRows = await ctx.model.StockBarcode.findAll({ - where: { - stock_id: { - [ctx.app.Sequelize.Op.in]: uniqueStockIds, - }, - }, - attributes: [ 'stock_id', 'barcode' ], - raw: true, - }); - - for (const item of barcodeRows || []) { - const row = toPlainRecord(item); - if (!row) { - continue; - } - - const stockId = Number(row.stock_id); - const barcode = row.barcode ? String(row.barcode) : ''; - if (!stockId || !barcode) { - continue; - } - - if (!barcodesByStockId.has(stockId)) { - barcodesByStockId.set(stockId, []); - } - - barcodesByStockId.get(stockId).push(barcode); + try { + const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails( + uniqueStockIds, + {} + ); + for (const detail of stockDetails) { + const stockId = Number(detail.id); + if (!stockId) { + continue; } - } catch (error) { - ctx.logger?.warn?.('[storage.inventory] 查询商品条码失败,已降级为空数组', { - error: error.message, - }); - } - } - const hasFileReferenceModel = ctx.model && ctx.model.FileReference && typeof ctx.model.FileReference.findAll === 'function'; - const hasFileModel = Boolean(ctx.model && ctx.model.File); - if (hasFileReferenceModel && hasFileModel) { - try { - const imageRows = await ctx.model.FileReference.findAll({ - where: { - business_type: 'stock', - business_id: { - [ctx.app.Sequelize.Op.in]: uniqueStockIds, - }, - }, - include: [{ - model: ctx.model.File, - as: 'file', - attributes: [ 'file_url' ], - required: false, - }], - }); - - for (const item of imageRows || []) { - const row = toPlainRecord(item); - if (!row) { - continue; + // 提取条码 + if (Array.isArray(detail.barcodes) && detail.barcodes.length > 0) { + const barcodes = detail.barcodes + .map(bc => String(bc.barcode || '').trim()) + .filter(Boolean); + if (barcodes.length > 0) { + barcodesByStockId.set(stockId, barcodes); } - - const stockId = Number(row.business_id); - const imageUrl = (row.file && row.file.file_url) || row.file_url || row.url || row.file_path || ''; - if (!stockId || !imageUrl) { - continue; - } - - if (!imagesByStockId.has(stockId)) { - imagesByStockId.set(stockId, []); - } - - imagesByStockId.get(stockId).push(String(imageUrl)); } - } catch (error) { - ctx.logger?.warn?.('[storage.inventory] 查询商品图片失败,已降级为空数组', { - error: error.message, - }); + + // 提取图片 + if (detail.image_url) { + imagesByStockId.set(stockId, [ String(detail.image_url).trim() ]); + } } + } catch (error) { + ctx.logger?.warn?.('[storage.inventory] 查询商品附属信息失败,已降级为空数组', { + error: error.message, + }); } return { diff --git a/app/service/systems/storage/report.js b/app/service/systems/storage/report.js index 1f35dfe..1d61ec1 100644 --- a/app/service/systems/storage/report.js +++ b/app/service/systems/storage/report.js @@ -337,16 +337,36 @@ class StorageReportService extends Service { const normalizedStoreIds = [ ...new Set((storeIds || []).map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)) ]; const normalizedSpaceIds = [ ...new Set((spaceIds || []).map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)) ]; - const [ stockRows, storeRows, spaceRows, barcodeRows ] = await Promise.all([ - normalizedStockIds.length > 0 - ? ctx.model.StockWarehouse.findAll({ - where: { - id: normalizedStockIds, - }, - attributes: [ 'id', 'item_name', 'item_code' ], - raw: true, - }) - : [], + // 从 getStockDetails 获取商品名称、条码信息 + const stockMap = new Map(); + const barcodeMap = new Map(); + if (normalizedStockIds.length > 0) { + const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails( + normalizedStockIds, + {} + ); + for (const detail of stockDetails) { + const sid = Number(detail.id); + stockMap.set(sid, { + id: sid, + item_name: detail.item_name, + item_code: detail.item_code, + }); + // 提取条码 + if (includeBarcode && Array.isArray(detail.barcodes) && detail.barcodes.length > 0) { + const barcodeSet = new Set(); + for (const bc of detail.barcodes) { + const barcode = String(bc.barcode || '').trim(); + if (barcode) { + barcodeSet.add(barcode); + } + } + barcodeMap.set(sid, barcodeSet); + } + } + } + + const [ storeRows, spaceRows ] = await Promise.all([ normalizedStoreIds.length > 0 ? ctx.model.Store.findAll({ where: { @@ -365,34 +385,10 @@ class StorageReportService extends Service { raw: true, }) : [], - includeBarcode && normalizedStockIds.length > 0 - ? ctx.model.StockBarcode.findAll({ - where: { - stock_id: normalizedStockIds, - }, - attributes: [ 'stock_id', 'barcode' ], - raw: true, - }) - : [], ]); - const stockMap = new Map((stockRows || []).map(item => [ Number(item.id), item ])); const storeMap = new Map((storeRows || []).map(item => [ Number(item.id), item ])); const spaceMap = new Map((spaceRows || []).map(item => [ Number(item.id), item ])); - const barcodeMap = new Map(); - - for (const row of barcodeRows || []) { - const stockId = Number(row.stock_id); - const barcode = row.barcode ? String(row.barcode).trim() : ''; - if (!stockId || !barcode) { - continue; - } - - if (!barcodeMap.has(stockId)) { - barcodeMap.set(stockId, new Set()); - } - barcodeMap.get(stockId).add(barcode); - } return { stockMap, @@ -960,52 +956,47 @@ class StorageReportService extends Service { const stockIds = [ ...new Set(groupedList.map(item => item.stock_id).filter(Boolean)) ]; const storeIdList = [ ...new Set(groupedList.map(item => item.store_id).filter(Boolean)) ]; - const [ stockRows, barcodeRows, storeRows ] = await Promise.all([ - stockIds.length > 0 - ? ctx.model.StockWarehouse.findAll({ - where: { - id: stockIds, - }, - attributes: [ 'id', 'item_name', 'item_code' ], - raw: true, - }) - : [], - stockIds.length > 0 - ? ctx.model.StockBarcode.findAll({ - where: { - stock_id: stockIds, - }, - attributes: [ 'stock_id', 'barcode' ], - raw: true, - }) - : [], - storeIdList.length > 0 - ? ctx.model.Store.findAll({ - where: { - id: storeIdList, - }, - attributes: [ 'id', 'company_name' ], - raw: true, - }) - : [], - ]); - - const stockMap = new Map(stockRows.map(item => [ Number(item.id), item ])); - const storeMap = new Map(storeRows.map(item => [ Number(item.id), item ])); + // 复用 getStockDetails 获取商品名称和条码 + const stockMap = new Map(); const barcodesByStock = new Map(); - for (const row of barcodeRows) { - const stockId = Number(row.stock_id); - const barcode = row.barcode ? String(row.barcode).trim() : ''; - if (!stockId || !barcode) { - continue; + if (stockIds.length > 0) { + const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails( + stockIds, + {} + ); + for (const detail of stockDetails) { + const sid = Number(detail.id); + stockMap.set(sid, { + id: sid, + item_name: detail.item_name, + item_code: detail.item_code, + }); + // 提取条码 + if (Array.isArray(detail.barcodes) && detail.barcodes.length > 0) { + const barcodeSet = new Set(); + for (const bc of detail.barcodes) { + const barcode = String(bc.barcode || '').trim(); + if (barcode) { + barcodeSet.add(barcode); + } + } + barcodesByStock.set(sid, barcodeSet); + } } - - if (!barcodesByStock.has(stockId)) { - barcodesByStock.set(stockId, new Set()); - } - barcodesByStock.get(stockId).add(barcode); } + const storeRows = storeIdList.length > 0 + ? await ctx.model.Store.findAll({ + where: { + id: storeIdList, + }, + attributes: [ 'id', 'company_name' ], + raw: true, + }) + : []; + + const storeMap = new Map(storeRows.map(item => [ Number(item.id), item ])); + const list = groupedList .map(item => { const stock = stockMap.get(item.stock_id) || {}; @@ -1171,25 +1162,36 @@ class StorageReportService extends Service { ? [ ...new Set(groupedList.map(item => item.space_id).filter(id => Number(id) > 0)) ] : []; - const [ stockRows, barcodeRows, storeRows, spaceRows ] = await Promise.all([ - stockIds.length > 0 - ? ctx.model.StockWarehouse.findAll({ - where: { - id: stockIds, - }, - attributes: [ 'id', 'item_name', 'item_code' ], - raw: true, - }) - : [], - stockIds.length > 0 - ? ctx.model.StockBarcode.findAll({ - where: { - stock_id: stockIds, - }, - attributes: [ 'stock_id', 'barcode' ], - raw: true, - }) - : [], + // 复用 getStockDetails 获取商品名称和条码 + const stockMap = new Map(); + const barcodesByStock = new Map(); + if (stockIds.length > 0) { + const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails( + stockIds, + {} + ); + for (const detail of stockDetails) { + const sid = Number(detail.id); + stockMap.set(sid, { + id: sid, + item_name: detail.item_name, + item_code: detail.item_code, + }); + // 提取条码 + if (Array.isArray(detail.barcodes) && detail.barcodes.length > 0) { + const barcodeSet = new Set(); + for (const bc of detail.barcodes) { + const barcode = String(bc.barcode || '').trim(); + if (barcode) { + barcodeSet.add(barcode); + } + } + barcodesByStock.set(sid, barcodeSet); + } + } + } + + const [ storeRows, spaceRows ] = await Promise.all([ storeIdList.length > 0 ? ctx.model.Store.findAll({ where: { @@ -1210,22 +1212,8 @@ class StorageReportService extends Service { : [], ]); - const stockMap = new Map(stockRows.map(item => [ Number(item.id), item ])); const storeMap = new Map(storeRows.map(item => [ Number(item.id), item ])); const spaceMap = new Map(spaceRows.map(item => [ Number(item.id), item ])); - const barcodesByStock = new Map(); - for (const row of barcodeRows) { - const stockId = Number(row.stock_id); - const barcode = row.barcode ? String(row.barcode).trim() : ''; - if (!stockId || !barcode) { - continue; - } - - if (!barcodesByStock.has(stockId)) { - barcodesByStock.set(stockId, new Set()); - } - barcodesByStock.get(stockId).add(barcode); - } const list = groupedList .map(item => { diff --git a/app/service/systems/storage/stock_warehouse.js b/app/service/systems/storage/stock_warehouse.js new file mode 100644 index 0000000..53a0e30 --- /dev/null +++ b/app/service/systems/storage/stock_warehouse.js @@ -0,0 +1,185 @@ +'use strict'; + +const Service = require('egg').Service; + +/** + * 仓库商品详情缓存的 key 前缀模板。 + * 最终 key 格式:cache:stock_detail:{warehouseId}:{stockId} + */ +const STOCK_DETAIL_CACHE_KEY_PREFIX = 'cache:stock_detail'; +/** 仓库商品详情缓存默认 TTL(秒) */ +const DEFAULT_STOCK_DETAIL_CACHE_TTL = 300; + +class StockWarehouseService extends Service { + /** + * 构建仓库商品详情缓存的 Redis key。 + * @param {number} warehouseId 仓库ID + * @param {number} stockId 仓库商品ID + * @return {string} 缓存 key + */ + _buildStockDetailCacheKey(warehouseId, stockId) { + return `${STOCK_DETAIL_CACHE_KEY_PREFIX}:${warehouseId}:${stockId}`; + } + + /** + * 批量获取仓库商品详情(带缓存)。 + * 先按 stockId 逐个查缓存,未命中的批量查数据库, + * 然后将数据库结果写入缓存后合并返回。 + * 作为通用公共服务,所有模块均可调用。 + * + * @param {number[]} stockIds 要查询的 StockWarehouse ID 列表 + * @param {Object} [options={}] 选项 + * @param {number} [options.warehouseId] 仓库ID(优先使用 options.warehouseId,否则兜底 ctx.user.store_id) + * @param {number} [options.cacheTTL=300] 缓存过期时间(秒) + * @return {Promise}>>} 商品详情列表 + */ + async getStockDetails(stockIds, options = {}) { + const { ctx, app } = this; + const { cacheTTL = DEFAULT_STOCK_DETAIL_CACHE_TTL } = options; + const warehouseId = options.warehouseId != null ? options.warehouseId : ctx.user.store_id; + + if (!Array.isArray(stockIds) || stockIds.length === 0) { + return []; + } + + const uniqueStockIds = [ ...new Set(stockIds.map(id => Number(id))) ]; + const cacheHits = new Map(); + const missedStockIds = []; + + // 第一步:逐个查缓存 + for (const stockId of uniqueStockIds) { + const cacheKey = this._buildStockDetailCacheKey(warehouseId, stockId); + try { + const cached = await app.getCacheAsync(cacheKey); + if (cached !== null && cached !== undefined) { + cacheHits.set(stockId, cached); + } else { + missedStockIds.push(stockId); + } + } catch { + // 缓存读取异常时降级为查数据库 + missedStockIds.push(stockId); + } + } + + // 第二步:批量查数据库(只查未命中的 stockId) + /** @type {Map} */ + const dbResults = new Map(); + if (missedStockIds.length > 0) { + const stockWhere = { id: { [app.Sequelize.Op.in]: missedStockIds }, is_valid: 'Y' }; + if (warehouseId != null) { + stockWhere.warehouse_id = warehouseId; + } + + const stockRows = await ctx.model.StockWarehouse.findAll({ + where: stockWhere, + attributes: [ + 'id', 'item_code', 'item_name', 'sku_property', + 'quantity', 'locked_quantity', 'is_batch_mgmt', + 'is_shelf_life_mgmt', 'image_url', 'is_images', + 'store_id', 'packing_requirements', 'stock_unit', + ], + raw: true, + }); + + // 批量查询所有未命中 stockId 的条码 + const barcodeRows = await ctx.model.StockBarcode.findAll({ + where: { stock_id: { [app.Sequelize.Op.in]: missedStockIds } }, + attributes: [ 'id', 'barcode', 'sku_property', 'stock_id' ], + raw: true, + }); + + // 按 stock_id 分组条码 + const barcodeMap = new Map(); + for (const row of barcodeRows) { + const sid = row.stock_id; + if (!barcodeMap.has(sid)) { + barcodeMap.set(sid, []); + } + barcodeMap.get(sid).push({ + id: row.id, + barcode: row.barcode, + sku_property: row.sku_property, + }); + } + + // 组装每个 stock 的完整详情 + for (const row of stockRows) { + const detail = { + id: row.id, + item_code: row.item_code, + item_name: row.item_name, + sku_property: row.sku_property || '', + quantity: row.quantity || 0, + locked_quantity: row.locked_quantity || 0, + is_batch_mgmt: row.is_batch_mgmt || 'N', + is_shelf_life_mgmt: row.is_shelf_life_mgmt || 'N', + image_url: row.image_url || '', + is_images: row.is_images || 'N', + store_id: row.store_id != null ? Number(row.store_id) : 0, + packing_requirements: row.packing_requirements || '', + stock_unit: row.stock_unit || '', + barcodes: barcodeMap.get(row.id) || [], + }; + dbResults.set(row.id, detail); + + // 第三步:写入缓存 + const cacheKey = this._buildStockDetailCacheKey(warehouseId, row.id); + try { + await app.setCacheAsync(cacheKey, detail, cacheTTL); + } catch { + // 缓存写入失败不影响主流程 + } + } + + // 对于数据库中也不存在的 stockId,写入空标记防止缓存穿透 + for (const stockId of missedStockIds) { + if (!dbResults.has(stockId)) { + const cacheKey = this._buildStockDetailCacheKey(warehouseId, stockId); + try { + // 用较短的 TTL 缓存空结果,避免缓存穿透 + await app.setCacheAsync(cacheKey, null, Math.min(cacheTTL, 60)); + } catch { + // 忽略缓存写入失败 + } + } + } + } + + // 第四步:合并缓存命中 + 数据库结果,保持原始 stockIds 顺序 + const result = []; + for (const stockId of uniqueStockIds) { + if (cacheHits.has(stockId)) { + const cached = cacheHits.get(stockId); + // 空标记(防穿透缓存)跳过 + if (cached !== null && cached !== undefined) { + result.push(cached); + } + } else if (dbResults.has(stockId)) { + result.push(dbResults.get(stockId)); + } + } + + return result; + } + + /** + * 使指定仓库商品的详情缓存失效。 + * 在商品资料更新、图片变更、条码变更时调用。 + * + * @param {number} stockId 仓库商品ID + * @param {number} warehouseId 仓库ID + * @return {Promise} + */ + async invalidateStockDetailCache(stockId, warehouseId) { + const { app } = this; + const cacheKey = this._buildStockDetailCacheKey(warehouseId, stockId); + try { + await app.delCacheAsync(cacheKey); + } catch { + // 删除缓存失败不影响主流程 + } + } +} + +module.exports = StockWarehouseService; diff --git a/memories/repo/stock-detail-cache-service.md b/memories/repo/stock-detail-cache-service.md new file mode 100644 index 0000000..36a1591 --- /dev/null +++ b/memories/repo/stock-detail-cache-service.md @@ -0,0 +1,27 @@ +# 商品明细缓存公共服务(stock_warehouse.js) + +## 文件位置 +`app/service/systems/stock_warehouse.js` + +## 对外方法 + +### `getStockDetails(stockIds, options)` +批量获取仓库商品详情(含 StockWarehouse + StockBarcode + 图片),带 Redis 缓存,差量增补。 + +- **缓存 key**:`cache:stock_detail:{warehouseId}:{stockId}` +- **TTL 默认**:300 秒 +- **调用方式**: + ```js + ctx.service.systems.stock_warehouse.getStockDetails(stockIds, { warehouseId, cacheTTL }) + ``` + +### `invalidateStockDetailCache(stockId, warehouseId)` +清除指定商品缓存。 + +- **调用时机**:商品资料更新、图片变更、条码变更时调用 + +### `_buildStockDetailCacheKey(warehouseId, stockId)` +内部工具方法,构建缓存 key。 + +## 设计思想 +作为仓库级公共服务,入库单、出库单、盘点、移库等所有模块都可以复用这个缓存方法,避免各处重复查询 StockWarehouse + StockBarcode。 diff --git a/methods/changes/system.json b/methods/changes/system.json index f730981..6aaf801 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -4082,5 +4082,22 @@ "storage.entry.create / addDetail / deleteDetail / detailChange:systems 层方法已删除,但从未在 system.json 中暴露为 API method,无需文档变更。" ], "type": "removed" + }, + { + "version": "2026.06.23-system-17", + "date": "2026-06-23", + "summary": "storage.entry.get 响应新增仓库库存、条码、入库进度字段", + "methods": [ + "storage.entry.get" + ], + "notes": [ + "items 每项新增 warehouse_quantity(仓库库存总量)、warehouse_locked_quantity(锁定数量)、warehouse_is_batch_mgmt(是否批次管理)、warehouse_is_shelf_life_mgmt(是否效期管理)、warehouse_image_url(商品图片URL)、warehouse_is_images(是否有图片)", + "items 每项新增 barcodes(条码列表,每项含 id/barcode/sku_property)", + "items 每项新增 direct_inbound_quantity(导入/PDA已入库数量)、remaining_quantity(剩余可入库数量)", + "同步更新 response 字段定义,将原有概要描述展开为逐字段说明", + "仅文档同步,不改业务代码" + ], + "type": "updated", + "module": "storage.entry" } ] diff --git a/methods/system.json b/methods/system.json index 0ca3c7a..8127801 100644 --- a/methods/system.json +++ b/methods/system.json @@ -19070,7 +19070,115 @@ "name": "entryOrder", "type": "object", "required": true, - "description": "入库单详情,包含 items 数组(每项含 external_item_code/external_item_id/warehouse_item_code/warehouse_item_name/warehouse_item_spec 等字段)、receivingBindings(主表级收货单关联数组,每项含 id/receiving_id/receiving,其中 receiving 含 id/receiving_number/status/storage_status/created_at)" + "description": "入库单详情,包含 items 数组和 receivingBindings(主表级收货单关联数组)。items 每项含 external_item_code / external_item_id / warehouse_item_code / warehouse_item_name / warehouse_item_spec / count / received_quantity / confirm_quantity / warehouse_quantity / warehouse_locked_quantity / warehouse_is_batch_mgmt / warehouse_is_shelf_life_mgmt / warehouse_image_url / warehouse_is_images / barcodes / direct_inbound_quantity / remaining_quantity" + }, + { + "name": "entryOrder.items[].external_item_code", + "type": "string", + "required": true, + "description": "外部商品编码" + }, + { + "name": "entryOrder.items[].external_item_id", + "type": "number", + "required": true, + "description": "外部商品ID" + }, + { + "name": "entryOrder.items[].warehouse_item_code", + "type": "string", + "required": true, + "description": "仓库商品编码" + }, + { + "name": "entryOrder.items[].warehouse_item_name", + "type": "string", + "required": true, + "description": "仓库商品名称" + }, + { + "name": "entryOrder.items[].warehouse_item_spec", + "type": "string", + "required": true, + "description": "仓库商品规格(sku_property)" + }, + { + "name": "entryOrder.items[].count", + "type": "number", + "required": true, + "description": "计划入库数量" + }, + { + "name": "entryOrder.items[].received_quantity", + "type": "number", + "required": true, + "description": "已收货数量(收货单途径)" + }, + { + "name": "entryOrder.items[].confirm_quantity", + "type": "number", + "required": true, + "description": "已确认收货数量" + }, + { + "name": "entryOrder.items[].warehouse_quantity", + "type": "number", + "required": true, + "description": "仓库当前库存总量(StockWarehouse.quantity)" + }, + { + "name": "entryOrder.items[].warehouse_locked_quantity", + "type": "number", + "required": true, + "description": "仓库锁定数量(StockWarehouse.locked_quantity)" + }, + { + "name": "entryOrder.items[].warehouse_is_batch_mgmt", + "type": "string", + "required": true, + "description": "是否批次管理(StockWarehouse.is_batch_mgmt),Y/N" + }, + { + "name": "entryOrder.items[].warehouse_is_shelf_life_mgmt", + "type": "string", + "required": true, + "description": "是否效期管理(StockWarehouse.is_shelf_life_mgmt),Y/N" + }, + { + "name": "entryOrder.items[].warehouse_image_url", + "type": "string", + "required": true, + "description": "商品图片 URL(StockWarehouse.image_url)" + }, + { + "name": "entryOrder.items[].warehouse_is_images", + "type": "number", + "required": true, + "description": "是否有图片(StockWarehouse.is_images),0/1" + }, + { + "name": "entryOrder.items[].barcodes", + "type": "array", + "required": true, + "description": "条码列表,每项含 { id, barcode, sku_property }" + }, + { + "name": "entryOrder.items[].direct_inbound_quantity", + "type": "number", + "required": true, + "description": "导入/PDA 已入库数量(InboundDirectLog 聚合)" + }, + { + "name": "entryOrder.items[].remaining_quantity", + "type": "number", + "required": true, + "description": "剩余可入库数量(count - received_quantity - direct_inbound_quantity,最小为 0)" + }, + { + "name": "entryOrder.receivingBindings", + "type": "array", + "required": true, + "description": "主表级收货单关联数组,每项含 id / receiving_id / receiving(receiving 含 id / receiving_number / status / storage_status / created_at)" } ], "errors": [ diff --git a/temp_storage_entry_old.js b/temp_storage_entry_old.js new file mode 100644 index 0000000000000000000000000000000000000000..2bb3f27905dd2edf8c3e191cfff468283e4df638 GIT binary patch literal 52592 zcmeHQZ)~1db$=LqAiy+Y9cAO@!?bvUd zrg2iifQ+#e*qdyFN_2uRXmmoO9dw(vt`xB$7}_RH6smQkYu8FeQ#J944|M1E9G{$X zpL_1}Jg@ya39PdG?|JV%_uO;O|9kFzUjBJcc2_o^O=J!F*~;d!BiSMP-IKj9`_=4q z`S+o0CY#PbZDhmLaxS|&Z-qV|pzk?)cATIb$^Yu5z7yGD`s&H9%lZmE7^;PMiXhBp z2dOWx*qu$~BTQri`KaRrwME~IK_fez9J7zcT1(&h^BDEJgPs95V0|(hrMUr;g*s|R zpUZK!Ge1U{&C^#S+f4mHpOb|dH3;@S^vOgH7cGl4I+atgL7%M6-br7eEB*3YF|5b&ACR_PrcV=pZKE< zrti&*xF5`#^z;Xp-!s_>`UzUi5&kE#UG(!vC*$j0QoQq-SwU@GQO>`D%hQ&^Mg-x<&5iRjLDPGM@o3j-mA%S*j0l9bvUV zU)~zZ40?zoAZ5$PzrWUK{qAUG^J|g3U^Qp*)hMo-u0>C-U!Z-a7c~dC&#osZXZ1$R zIpfp<>slP8FJI{+#AUs?Mrsi@x6}6t!fTH73?zIa|BNMH)(F3ai$>`0o=Y6llU<+x zf0Fvm({uT+hn^lF4TM=7$|Y_*Z_!Kt7x{dgaH(Fo7zgDv85gki@8#nl>nU_Nov(vk zi%?piBcK(OdSMSw>xuT*K=iTlKAKCSNPHvvPWy(&+m5cjaC-micicFO*2hT?g1&3B zwRe4a`(NGtyX~#Vhj*^p_vB`v+r>&BW)^_o~d@ZJKoo1w2`)b=2a z16>ze4bh{FpV9^z{pNx;IhDm@ix&Oo_Vc@DcI|5SO#R7N@A;n$&CHB7|N2uauS*AL zhM^tob!G|v45iRY;1S||JF^%j%cDoVYqM(!cBmb^cB<)S%=&@H8N!-uBT*X?e=?W5 zdGo(NBjr*nTWg4?s%8^Y0}w1lJSkVJ#nfn#hl8>D9Gy_l_QiC%&d8oft!S=loY)$Q z6#KIT)GDc$ky-lXzqn_}QPOTEw-Z=N=;yiYy)+^`$>X_hQwfvy4e~<8t3liHd0rpc zlG6p6g*pqP*p)3}$7?y9TLiXQ9=G+;Okn+VR$|j-X7G^N>+aM#S?rV&@ITqNNpsn) z#DB+VRN$rDIZqbQmRiFzpP>IR;!X5(`J62fVHx9bCk@{5=+d{5ts#6s z1LbIzc?(gb!&0s<*ZHskmaRTo8 z-#pEupZu{9LyKLwI-Z|0IQzq$enj?od-{%Z3+3^cwT>x2f<1`$%x=EtV;@&a`hJAk zy7!aMWn;aYf|!iGi5G_+YAkGjaPn36X^dAEd3B-}Sj(KEQDZLkH52!UHH=ttORGN8 znsda(ums{G^pQ-$Qyk_YJn6>tDC9o3ak;#~&Vlp|yVB z$-z~Jkh|HFZK1r(4*G6nt7qSR@Zj;Ytu;5m+y2`9<#B_J4Isl<=?UVq@oXz`T$BE8 zWIWF5*^Nj3@ZvriomYcpI30y_LnBzJ3G*|^LUHCxGAn%~Ig(w|$m-1gXQx)}`_IX> zv(Jt^Ir}R|jvRh$;y0RVJ(ZWZ_Z#0`j@=IJNmEzaM; zy9M93=zD-#7UPeYvXI+YChO`RWEKySCYhz*p!EmnTYMDdEvyxf0n989UP)i7mvFI} z6ZLM?OR$`YhzNWq?Lx1zk$cnfS$Djv9`aB`cMD|oy*$mr5nJ3=^$M?w@EBGm)?SF5 z5Sy>GpJsWY=#MZj4bvJ)#>(@ZFPHa^92Be{tl@YrS;+M^i9(F$ST1vY+1n|Wk7ew1 zHfA(!Q5r(nyJ!^7Ba3XPoxr*vkLyJSEQP!mP}E6w1oi5{qcJyN-9s52AbbweY>~m^ z*@7=a=@uUHR*^mYa*tc*7>_oVQ`OEPTmk5vEo3Q>i3a_{mX@AH~S@jB*(znD1LeRp5f`X6)e=xkN^=^y!R4>d^6aqT~n3 z-ZXMb*5|3Q>>YWJP+mn3fy(b7D&sePhP;EBmaV@(^OS}{P9Iv@@5Rvy>*}#Ze(_s| zyh3|Ov`>O;Nga+kb;*WfZdLQEvo5f!<-E-^i#1K?*8vx+b?3={IY!R_f2`oc^+vN8 zrWUu;_W*ex4cZs6Rs@i5B^nK8AELibke-^Sy+GJc_E$!8O&)tJyeC?Ov^)D98fS>U z`SU)KE!i6!C5YIoLT+W0BuMroWK6#$;(_r9V_?0JbjK$84f^_g$TUP-e5t;$Scjf= zndGR4*qiI}S<>pBCkejf3=%9tFVPZfbzQy_vM!LKaE(3R{iUfFhpzkYx1Ohc!(sUC z*BlsXZ#weoe%_;e{a(q54^pQ8GZ*)?f3WlJ(V_Mie|%x=3!i__N7-+EY|n>hdGGYK z(Vk|x2kzw!br-skg&Fz{jt{Mr_M`SwrVnC9>$Ahd#SREOiGz+;JfC}R8aci{=zUX8 zZ}1wT+8pr#@5#Zpnz)I<~fwL_OJ{o7E%`4nLSDPj7x)TDQVZ^4w`d|xOmEu zkALLW^YU4E@cjmaI%sE_x{~vtl(=g3T)*o74=0CkcyaNEqM3w|`?Zl#8 z0|&xmNAy(9qr3;PIe;@numsAjq-Qug%)0Rwg08hBanu5iV4nxslbJknIOawI?5D(S z`zQ{P=wmRS3GAVjS&V_N&LF^sqsDF{*)z^_LA%4}pI>3<@H^7$RGgU?v5S^kv$$te zXTAKj2i@R}*qX>920~xuKJnYaokwYh-6xkL z{;9qB#~VlAG+k9`#k&`)FPz!`>7(uDCk{+cJlZ}z_@j%(DC}(OrTq^K-#B|_|L1qF zZuP7~6!GHF8xH*Z%!UNMMgJA^XB$_fq_qZ~51wAfq9+pfPWK%kxeNWG-U_cU&7Ec3 z7~_Q96AQ~~k~BXmpT&MR_$sC0m`0sp5!)|BW}1IIB0b z;m=uG#Ja+2Qq8MiEYALQl3_vrI0vW@7@~48^m}pqL7JoXh@o+BrDX^~=)+X|P`)Bl zi~CLY5M8&DXCl?Sy)HH3S27oZRvcBY%V{5GD~q^GuVGq4oKENl1_Dblxq<4Gur`WI ziW0&HML$!XZ=+elZ-b2W(KkzqZOwDF1Io6q=o73Rat_t4 z?OJ0LoP|i?W7{fUc=NrBR*AKv*_IIgtM1su?=T$9s^%+#6N_vkon{hn2-Tg$;9)?g!XD@HsFN?~;^r(5Yy( z6cS*-X7LUP>o%O`!#>XLOB@%j9%k7s|2Bk-S%J4TL)`7XC5g8z=SlPro$Bq2#oiJq zQ1lTkM0}1f@H8X?R9;Uu8&=zE7kY|lox;WMFFq%8gf{}P5x)|x%CiOR#X#4>W^grL zIc&h^UK5EqGDWnNcs2fvq_tWCjGv-k+#3D_VhG+3t?I{FI(YdLv}=y}LQi5uJv~>B zCqvju{So)o?Fnx_wOaGJkIH*uCl_Ts)fV&bj8Yu)<6JZ9;_A>=ZP!xzz~a{%Wrlo> z+1%Q&r&+HTYB8X*P|;mytQ6(F=VGmd%fg5oPp$2;+LX1KK2eQ2Ks*-akZ_)6B{Vfh zTQQ%_6P1yNK0=amjH+EE4~=MPwuImKX#zW(6${?Ft&5!C4@ ze~gn~25jK*fj>|I70y{``ijP9N~qR*MdSONA{_II#`o#tYZ}%oLc7q*Pigxhl3ZAA zoRutUevxeXJl0zls;6VOkUl`ofWYRwmFPD+w(P`tHs%(}GODhZJwB^}mIkTM=ybIU z@u?}!;@I(!O^G88A70V_VQ3O#hHF+u&t19Q!+jpSR#i0jqPVI)smQK44`dC>VO5xrbS*DGvRD0 zqFF@RD>GMQSS6pfvLktUzLgpAfa86t*DWhu9uJM@`&ytpJpKWqk*|BKO$cpJ9SCd* zv~pE&6HQeOqj&}bHx#5!^4FDI?_UyIXj@|yd`+xXSkNnyBi5%l4WlW#zuBQ41`6@PK&rYsZY z*@2a(mTKHzOe%?2W%`!B`ConN{#7(||F6ydvHRDWRG^ z#Rq^Rd$&WEH~{-3%U%7{YNxe}#ZfF%58)(h!KdT|+mu{lrQ@0o@FkyS9Uw1sCsk?e z$n%4KTSx|YRkR(dals#~@tB`eI?m&krEvJ+Tq5CTs_sqG!q>N4HH-dB=MPk~$WDP+ z$>K_BrVL|Qy;5vhFH=-^KS0}wCGmD+fKR==KTfV!=laFs3y*p-1b)M6Z6=6_QS>x9 zXbAr=)`P$k)!@*#7Ul;@u20f4Nab+8l92qv1}4X9tg%8Vk@_NzM!BY?)B7g7R}&xZ zJF&)9{loK2RlbATVgC__N(UC{w3W1>R$ORAp(6{W_7w?$FNTEmU>rwbGWwqE? zPl-WMRps$!ygS>IeXspO{|_!cLYe%h_Ig^bIzMlBW5uqAmO*%ztqu4IdbQ4Otk@?X z9^gugv^A8`>+6lU$2P)PcVV>-4?A_Z4Tf*QU|o&dj$^!_(~J5^#!2tm%Iq4s6nph5 zAq=~3t9{>3_;eFz&r1d#p~S@VE%vjzEsVXr>R;wmsR6z?`P9X)wvX;8zr)CC6L^}! z&5i7A>-87Mt3c&*rP% zD#q~^1I@~*H#@MXk=T|fRBh{L(YRVDv_18E$2n4X33@k*l|jip;0{#WSHPL^HM9!x zxgwd3pJgrbjU7cK6!a1e-B}F{dxnkd5jwT5xTUCf;{4aPfA#K#=3mbJ^xih{cPxj% zNGJ;GNKQI#X(bfBLMg=)%LVFrrhKg+4_ajA!_|d{jiVfoR3A!xntfk$X4t zf*9p$q2A_8)@BP)2DeAdCv-NjR&JCyBd#GA8sc|dDUv>EK9Cl5rHU)7ij~~4oC{p} ztutg!DXXrMKKNaqV}x?y2?gdWUV(bqWjp#(xJmk_WD=hrDB*>rjOmS49K(-5#RB^N zk#7@$VOi9Q8Ct){i(1jfi(DlV_|fF5Q>$m+d*_|gkFp+{~Eu{2IGvS*=j z=_JL`xHDjmJOzDfd-5naDY-7sa9~%HvrJ*MfTxIlaS8w#AB@(U{WeJwWSrmS^1i^A z2-gyKt|4cOn#N7kA9Lon7MvhBxN8odSj=Qj;Z1KL6}^~tsQsr+y}h@SH+jH|6d(TT zjAm`V^m4_t*k=V7;SD$AhEI1;P7~Q+Io}3uwzs<@kKaSwGC;T6eUScQPPskX8~i^| z_c1!U8cH$um@0RR_LW@1bXWRmsULx$2e-7E;ysONIWhmr+;fgR%D<|wE zp4S{L&M@*j7($t_^2?SOQnH0G;89aq18vK(os1~Edg+r}(h_pbxL8W4{fX%iYadvR zP^x{;#%k$KqjJSVPcSyJ+wO1f`0&eKE)_V*>MSMhMt^)MC93&dZjbNHHEYN{sqFWa zp5qpzZk#1-A0JA6~z)YV(c70sHzjD`M^*LUQ6#K(vRtR-saz9}A zw8xE!*_6dUPfy-A`sm2N9eSZPN%`RvHQ>b_T&x%^ayw>^FXSqD<#leH%k-h5k8+8x z6JmH(J^ZnXtAnv^#KQk$W_ET~0@YeCNB%;uHkPic*>x^iinn?hfTGXE8;mJeziwHz zbiF>}t3flzX;c&X+Wwf(5*Rmz;>`j2h0is%sMZl0kK@?X9ID$_&!HNI&Vk>28Ph(50cn8t zm76z0x|g@@6yM@l)wm*3JiMsIQPYiEBA_u~J3>s$S_&`vlHm1}%GK&Iq-FUSOh@oJ zZfQ!*A=RoJc6|E4r%<|Gr|@OYA$4N-(yj`=p2`aKCvMN#M)9ntzpO@J+2b2$fKw0k zLVjpd{(g(w-2QS0mPqbWdwX`@!?%+gPP*--sW+y3x%$la(7>zBT%#Q=NSghmd}Xbc z4Lv;0?WmUa^s9G=4_3EYJNwyj;9ZvKwo=ncHkdPn%c;*2uTFWo%%`j4zgS3B?PCj3 z^yI7;SDi7H_a|RFb^i4F@oyae_VC{J=eBMCNbmUu?2yg#eXukK( z2Zj$dUpR*w13{blZ1siDHJj55R4c*%H?k+%KRfpu&97W|s4+x7HJ*l0ZqD<|$N=;E z=a*Y&gbE&<>jwvhZ(&9zlCj#b=sjqyA>VzXJ1B7r^bU0hw}E_0gbqI%*<_(Czt>*t zqV#UR>D=dp+`^B;t#G)fOlnv+(_esk(&SyY@SM~c6#RKGQFH;%kC^?cxM1e0GLnvOC6D!5Z#x|M-RIKKmGtqJvFsP|m zFFj@zJ}o;(BXko_s?*FW)`IJucvZ@>s#bqs+)#%ICQ|DRnLUwbv1KnHMLkG>a0qKm z^niq7w;=ok+50&EBP-;O;IDx6DSyAWodw`O> z?OqudplztB*w@naZ|(TC{%^J4`plg(-#hcgJMX{lAIvm$j@qwY$iRzYO2-F$4~ z<}+_U^6;mwIrkrXZ+-bolaIT3r{XG<%Vlg^#sevhPsH+>2i#F-HMFh>_;iwJt55jN z&2i4g_D|u#mMgWQMVkSR>x8RPqpEDDT2yfmFsZ{uXjhk$(6%l&p>2wzpighRA9CGp zJ~{j5i;uVWj66u(g!fB(Q4U}gxr(1z*~XI;wQx5q@>~4Al2ohWYQ~&fMNy%oe-a89 zvR)HwBJW8GccoMK`EMY%lnF8RDi64tp6|;aYd$=_j&6{C%QL8(`TL8XJu0;|RTT-- z=Hv@>D%)-8{qu=UCL8O&Bdn~#Uf=7>Z}}FuPfvdAF5K%6I^rCodZ?%!liR1cnx4Ht zR0DYaDQ=P3LZ9Kpl(!3LHADR>`;a@X)*4A_TAj00laFi|7QEX z!@u_&^U=53U;6N;JA9A5czsuA#SJQ+#wqeeCIV-vaV|+QhM!R#dDZ7~D;t^-fHZlw zQt;>_DR~|}q>_LG0F!EC4 z9mPRtvT~IGz!hIgftY6Y$?`qa6n%-Q(Ex4wXO$&wmqJ zd^xLcfeXHb9v(G9{bFGO9{wLLuA6fAruaMF68_oi^FL@A?~6+abt+9Je7K2MLQ7A&SXB;s!32;`VRecWp# zmAb`QrdtXQJ=s3eKAvR5f8n$07!A8+I5&peJ$B|XB1ZEx4D&AT$(bV#sNWAY*sy$f zyN9fCI3urx&cvGqJU~=K+(FpfTLRZ_m4@x_=vjT_+XTCZ=*eJp9SbPZiCozcJKOX0 z=UC;}+Lh~M*V0;=ZtPuJty#8vX*HN=3VjCODwe@mpR4y3`h;E{WvKnPbKk%7mo=gU z-KC0h6a6ig>vF}FcHOahp5I_Kv+Dn}iea|d;6XVX^xYKkW98ier>_$|F6o|U^YD|02HODikF zrCZ74(3_n?x>oyC;&JfqUfDgYRdyKOxwXY*JE>l@{^-behBr?CL;Iz%|2p(|d;Q?O zyL!+6WawXyyz0Jx-zm`{TQbk@!sw!9;jt`73anQZ(i8u2UCIn;6P&YDJ1p~;Y>Y%F z1LQT^te}P7Nh~E$;KkYZh+?*>xX_ap_Dv8Y;=4Eli=E%w`gcqBC}ZlxUXLB=YW5_V zD_K)_+mnQSiYc=^fAAlhe|K?V;+NSU6d!OPzYQIC1LAHM(GTpQt<*k))fia4SNy^5 zWVbC{my?xx#UF&F!q+SQpin}77yXw`JoPK>4+3}bJ*?&2L^(9*L)Cg|pQV{+ujCD+ zT8Sxjh$93AH@y`zqwvVWPvFJt({x@?+7xq|@;sGK)6e4^9^XV9&eE^Mf-XSz09u+W zvC7b7C(|M0Hcc-AtjHF*>x@OXdTj!?eW4EofGl+X@PVb$Qlmqklx>qSf! ztGfHnfF*oT9w(t?(L(Su%N=+klq=F*vn>3kz4GjS9Es}ueA&a;SAy2<=Ir+wTQ9XQpjnE7 zye<}A6;E6Gbh6{Yao@_ssi_^0={URi&r3!N_ii#9f`0aQ1Hf%N3hW zlf}Uvsh*A+r@Nhy)3R?;)C!@veW$0XB)??&TkORe(i`RYAT!*pH_29yC2}Q}sLUqE zx~Cd`*hfa`$@aD%*!JM$V;A0d^x2E>Yb~u{IqF-FqP>o_Jmx4-Lb&TFK7RE);M=1$ z`$qAp2RnwBLzI!Ur=79ysfW0Vw;n#Nb9TbRhb^Vm;wk~1RcMF!2=B`p;geiL zykWd5+lw~%5?!%W-yOH%9J>qIVmT3vJ-*Klf26hT0!|I5Zpp#eV%L`AzZdE3(KkGa z;f#7`~Wd@Xm~ORW*d=iZJ<8m`n*P7+t(46uyp-_&I_ zK>cyB3sj`0U76Uw;}giZ z=mDRKC2h5)a>C*{T#`jw;J7~3dTWoKHk-gip-UyOmVC_)B%Oyub?mPi&fgNR!}My z?Q4~-vo@}iIFqBc zIZSAsgO}F)7w5DVVl+7oe>r1HPjZ;Dp=FpND+8(SW_%@DerS;cT_0DaccYy4G>=$95&2qXIN2sRTLfVDjreZVqom6-gbr|xVaaEUaK?>{gJ*|~q z*R!pc_CGNETl@a^Q%~<@TX%WRf7x~N<-BADcLi?F2|^ z1&B&zyb^+s{_#OAA+@wZ;fF`mj|zc6NR22;F;Y`dLHzLDa_@}S`>>5us-}Qe`xtu@ zfHMbeS+JC5Pc9hmhGU>{l^P?Rq_1IjfII{TdJy0)kUtg^%PZwC=;|AD^Anj5hCLOG zMgeOvG6lBXaLO#cB5`QUVJ1a-u8EROj z(vH-|Mz*>fxma*$UU8*NrJBI|n!R!x4y_XD+ql2FcJNtcRqKn@gre`)=>y02r@vKw zl+^2iQ`(NywTeSqj+~r(p!%S9cX=W+#1J%NGMG7=IWR$`e(~~XkbasSdC7>VXROzo z@jJAB@vTaLzCM0r_TK8N?;eM^R)cHdeX11nK%|w(k=a#E4DKog=}$Lm0(u?HR3hI5 zcFGr&qs2Xm^^~W8S+i!tRsGF>d8%h@J%x7rU#kfmiGfBwML;wUhhRd~p3x+k2dokC z1nb!;^QA@x1rtwlzyf3t=FY{Q<{|3>G5QMdmWN&$7P--fGY-GvVP;+wB2mbT&_4+g zJrB=QjES6k&L&&CkM+a2DKZW5>0?D`L9X>Pp5Z+X2+43w5|OM;Gaofqsa^`prPN^&7{b zwOyZ=t`3N3g>j23gaArn=!K3q>V^+0-&+pR_0)$UhuZ6nWsj-iRnB>Hzb7GsF{UOG zj4BZynItbmHj$|nXi30V6;6R1Q@3lLLR`YC(GT?0%|f_o!_9nghN9Ip@Kq+`V8c%@ z9qjRp()Wi?ru3O{A2;iv0QthYPcpkf+UuCYH1f!vTV%A38ZwvL(>e9`_KZv# zBlSp-Nr*7#ZjywWS>Mk%g?fZaZQy{BSd|vB%Yy~vdKzLE$un?AZA-8fJwqOCI|j$` z6+KR7OrAUU#u1ZD{b#_w%IrE#Hk_cQ*8JiKoONrvy$$o)8ArqjR}>Mva_nQI0CPp{ zvgg~Xa9r^^?KIpbrWtucjJvVG9<8-bjQnEMMit<`NddGGDZZ!DXJxjxIc5Bc{^Ge< z*Y&ZUx>Wy&&IGqY8D*H01WZ7E!dfsZV;WdD4sCi|*OO1#IMGfC^_{5HZ<;d9L zC-fCxP53(cNM+m7Ju|pF-z|6w=ak?5Zyx4*e6DJEZO7%C+j+FNv6%|vbJ6GCT4&uY zhoMsK)rQFASp}b^{^-IXv;EJhJo$F{-&0@aeY~+k{@1Il{jBbMtqo=tBkzTDKGd~YMMwHx Date: Thu, 25 Jun 2026 02:01:59 +0800 Subject: [PATCH 076/550] 20260625 --- app/dict/businessDict.js | 2 + app/lib/printer_data_builder.js | 46 +- app/model/store.js | 7 + .../systemMethods/order/pendingOrder.js | 90 +-- .../systemMethods/order/recheckOrder.js | 113 ++++ app/service/systemMethods/stock/warehouse.js | 6 +- app/service/systemMethods/storage/entry.js | 45 +- .../systemMethods/storage/receiving.js | 24 +- app/service/systems/express.js | 13 + app/service/systems/express_platform.js | 105 ++-- app/service/systems/order_print.js | 17 + .../systems/order_storage_allocation.js | 184 +----- app/service/systems/pick.js | 31 +- app/service/systems/receiving_entry_match.js | 282 +++++---- app/service/systems/setting/warehouse.js | 63 ++ app/service/systems/stock_store.js | 62 +- app/service/systems/storage/entry.js | 547 +++++++++++++++++- ...2026-06-24-add-bind-receiving-details.json | 7 + ...24-deprecate-manual-match-entry-order.json | 7 + methods/changes/system.json | 100 ++++ methods/system.json | 520 +++++++++++------ 21 files changed, 1655 insertions(+), 616 deletions(-) create mode 100644 methods/changes/2026-06-24-add-bind-receiving-details.json create mode 100644 methods/changes/2026-06-24-deprecate-manual-match-entry-order.json diff --git a/app/dict/businessDict.js b/app/dict/businessDict.js index ce2d78f..c6c363f 100644 --- a/app/dict/businessDict.js +++ b/app/dict/businessDict.js @@ -76,6 +76,8 @@ module.exports = { ORDER_WAVE_AUTO_GROUP: '自动加团', ORDER_WAVE_STRATEGY_FETCH: '策略抓取波次', ORDER_PICK_COMPLETE: '拣货完成', + ORDER_RECHECK: '订单复核', + ORDER_RECHECK_BATCH: '批量复核', ORDER_SYNC: '同步订单', ORDER_WEIGH: '称重', ORDER_PACKAGE_MATERIAL_BIND: '绑定包材', diff --git a/app/lib/printer_data_builder.js b/app/lib/printer_data_builder.js index 64a78b4..38ed2b9 100644 --- a/app/lib/printer_data_builder.js +++ b/app/lib/printer_data_builder.js @@ -1040,6 +1040,18 @@ function resolvePolicyConfig(input) { return {}; } +/** + * 归一化仓库主体配置(subject_config),用于发件人兜底。 + * @param {Object} input 入参对象。 + * @return {Object} 统一 subject_config 对象。 + */ +function resolveSubjectConfig(input) { + if (isPlainObject(input.subject_config)) { + return input.subject_config; + } + return {}; +} + /** * 构建基础数据中间态。 * @param {Object} input 输入对象。 @@ -1051,16 +1063,27 @@ function buildBaseData(input, platform, platformMeta) { const orderExpress = isPlainObject(input.order_express) ? input.order_express : {}; const orderDelivery = isPlainObject(input.order_delivery) ? input.order_delivery : {}; const policyConfig = resolvePolicyConfig(input); + const subjectConfig = resolveSubjectConfig(input); const templateSample = isPlainObject(input.template_sample) ? input.template_sample : {}; + // 三级兜底:货主 policy_config → 仓库 subject_config → 缺失标记 + const missingSenderFields = []; + const senderField = key => { + const val = toTrimmedString(policyConfig[key]) || toTrimmedString(subjectConfig[key]); + if (!val) { + missingSenderFields.push(key); + } + return val || '仓库未配置发件人'; + }; + const sender = { - name: toTrimmedString(policyConfig.sender_name), - tel: toTrimmedString(policyConfig.sender_tel), - province: toTrimmedString(policyConfig.province_name), - city: toTrimmedString(policyConfig.city_name), - district: toTrimmedString(policyConfig.district_name), - town: toTrimmedString(policyConfig.town_name), - address: toTrimmedString(policyConfig.address), + name: senderField('sender_name'), + tel: senderField('sender_tel'), + province: senderField('province_name'), + city: senderField('city_name'), + district: senderField('district_name'), + town: senderField('town_name'), + address: senderField('address'), }; const receiver = { @@ -1096,10 +1119,13 @@ function buildBaseData(input, platform, platformMeta) { const missingFields = []; const warnings = []; + // 将三级兜底中仍然缺失的字段挂载到 sender 上供下游感知 + sender._missing = [ ...missingSenderFields ]; + const requiredChecks = [ - { path: 'sender.name', value: sender.name, reason: '缺少发件人姓名(policy_config.sender_name)' }, - { path: 'sender.tel', value: sender.tel, reason: '缺少发件人电话(policy_config.sender_tel)' }, - { path: 'sender.address', value: sender.address, reason: '缺少发件详细地址(policy_config.address)' }, + { path: 'sender.name', value: sender.name === '仓库未配置发件人' ? '' : sender.name, reason: '缺少发件人姓名(policy_config.sender_name / subject_config.sender_name)' }, + { path: 'sender.tel', value: sender.tel === '仓库未配置发件人' ? '' : sender.tel, reason: '缺少发件人电话(policy_config.sender_tel / subject_config.sender_tel)' }, + { path: 'sender.address', value: sender.address === '仓库未配置发件人' ? '' : sender.address, reason: '缺少发件详细地址(policy_config.address / subject_config.address)' }, { path: 'receiver.name', value: receiver.name, reason: '缺少收件人姓名(order_delivery.name)' }, { path: 'receiver.mobile|tel', value: receiver.mobile || receiver.tel, reason: '缺少收件联系方式(order_delivery.mobile/tel)' }, { path: 'receiver.address', value: receiver.address, reason: '缺少收件详细地址(order_delivery.detail_address)' }, diff --git a/app/model/store.js b/app/model/store.js index f7acc0f..4708ea4 100644 --- a/app/model/store.js +++ b/app/model/store.js @@ -48,6 +48,13 @@ module.exports = app => { min_group_order_fetch_quantity: 13, default_express_code: 'STO', default_platform_code: 'TB', + sender_name: '', + sender_tel: '', + province_name: '', + city_name: '', + district_name: '', + town_name: '', + address: '', group_wave_prefix: 'B', delete_order_wave_prefix: 'A', inventory_warning_rules: DEFAULT_INVENTORY_WARNING_RULES, diff --git a/app/service/systemMethods/order/pendingOrder.js b/app/service/systemMethods/order/pendingOrder.js index a037f68..09e804e 100644 --- a/app/service/systemMethods/order/pendingOrder.js +++ b/app/service/systemMethods/order/pendingOrder.js @@ -5193,10 +5193,8 @@ class PendingOrderService extends OrderBaseService { /** * 取消订单时释放创建锁(lockItemStorages 添加的 wms_stock_warehouse.locked_quantity)。 * - * - 有 wms_picking 有效记录时:通过 storage_id → stock_id 映射汇总各 stock_id 的 picking 数量, - * 释放对应 wms_stock_warehouse.locked_quantity。 - * - 无 wms_picking 记录时:从 wms_order_items 读取 plan_qty, - * 释放对应 wms_stock_warehouse.locked_quantity。 + * 直接从 wms_order_items 读取 plan_qty,按 stock_id 汇总后释放对应 wms_stock_warehouse.locked_quantity。 + * 不依赖 wms_picking / wms_storage(储位分配的锁由 cancelAllocateStorage 负责释放)。 * * @param {Object} options - 释放参数。 * @param {number[]} options.orderIds - 订单ID 数组。 @@ -5211,89 +5209,55 @@ class PendingOrderService extends OrderBaseService { return; } - const pickingModel = ctx.model.Picking; - const storageModel = ctx.model.Storage; const stockModel = ctx.model.StockWarehouse; + if (!stockModel) { + ctx.logger.warn('[PendingOrderService.releaseCreationLockForCancel] StockWarehouse 模型不可用,跳过库存释放'); + return; + } - if (!pickingModel || !storageModel || !stockModel) { - ctx.logger.warn('[PendingOrderService.releaseCreationLockForCancel] 模型不可用,跳过库存释放'); + const OrderItemsModel = await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId); + if (!OrderItemsModel) { + ctx.logger.warn('[PendingOrderService.releaseCreationLockForCancel] OrderItems 模型不可用,跳过库存释放'); return; } const transaction = await ctx.model.transaction(); try { - // 查找这些订单的有效储位分配记录(排除已取消的) - const pickingRows = await pickingModel.findAll({ + // 直接从 order_items 读取 plan_qty,按 stock_id 汇总 + const orderItems = await OrderItemsModel.findAll({ where: { order_id: { [Op.in]: orderIds }, - warehouse_id: warehouseId, - status: { [Op.ne]: 'cancel' }, }, + attributes: [ 'stock_id', 'plan_qty' ], transaction, lock: transaction.LOCK.UPDATE, raw: true, }); - if (!Array.isArray(pickingRows) || pickingRows.length === 0) { - // 无储位分配记录:picking 已被 cancelAllocateStorage 处理完毕,无需再次释放 - await transaction.rollback(); - return; - } - - // 有 picking 记录:按 storage_id 汇总释放数量 - const storageQuantityMap = new Map(); - for (const row of pickingRows) { - const storageId = Number(row.storage_id || 0); - const quantity = Number(row.quantity || 0); - if (storageId > 0 && quantity > 0) { - storageQuantityMap.set(storageId, (storageQuantityMap.get(storageId) || 0) + quantity); - } - } - - if (storageQuantityMap.size === 0) { + if (!Array.isArray(orderItems) || orderItems.length === 0) { await transaction.commit(); return; } - // 查出关联的 wms_storage 记录,获取 stock_id - const storageIds = Array.from(storageQuantityMap.keys()); - const storageRows = await storageModel.findAll({ - where: { - id: { [Op.in]: storageIds }, - warehouse_id: warehouseId, - }, - transaction, - lock: transaction.LOCK.UPDATE, - raw: true, - }); - - const storageMap = new Map(); - for (const row of storageRows) { - storageMap.set(Number(row.id), row); + // 按 stock_id 汇总需要释放的创建锁数量 + const stockReleaseMap = new Map(); + for (const item of orderItems) { + const stockId = Number(item.stock_id || 0); + const planQty = Number(item.plan_qty || 0); + if (stockId > 0 && planQty > 0) { + stockReleaseMap.set(stockId, (stockReleaseMap.get(stockId) || 0) + planQty); + } } - // 按 stock_id 汇总需要释放的数量 - const stockReleaseMap = new Map(); - for (const [ storageId, quantity ] of storageQuantityMap.entries()) { - const storageRow = storageMap.get(storageId); - if (!storageRow) { - ctx.logger.warn(`[PendingOrderService.releaseCreationLockForCancel] 库存记录不存在,跳过: storageId=${storageId}`); - continue; - } - - const stockId = Number(storageRow.stock_id || 0); - if (stockId <= 0) { - ctx.logger.warn(`[PendingOrderService.releaseCreationLockForCancel] 库存记录缺少 stock_id,跳过: storageId=${storageId}`); - continue; - } - - stockReleaseMap.set(stockId, (stockReleaseMap.get(stockId) || 0) + quantity); + if (stockReleaseMap.size === 0) { + await transaction.commit(); + return; } // 释放 wms_stock_warehouse.locked_quantity for (const [ stockId, quantity ] of stockReleaseMap.entries()) { - const decrementResult = await stockModel.update( + const [ affectedCount ] = await stockModel.update( { locked_quantity: app.Sequelize.literal(`locked_quantity - ${Number(quantity)}`), updated_at: app.Sequelize.literal('CURRENT_TIMESTAMP'), @@ -5307,8 +5271,8 @@ class PendingOrderService extends OrderBaseService { } ); - if (!Array.isArray(decrementResult) || Number(decrementResult[0] || 0) <= 0) { - throw new Error(`库存主记录锁定数量不足,无法释放: stockId=${stockId}, quantity=${quantity}`); + if (Number(affectedCount || 0) <= 0) { + throw new Error(`库存主记录锁定数量不足,无法释放创建锁: stockId=${stockId}, quantity=${quantity}`); } } diff --git a/app/service/systemMethods/order/recheckOrder.js b/app/service/systemMethods/order/recheckOrder.js index 53cc57b..c83bd6b 100644 --- a/app/service/systemMethods/order/recheckOrder.js +++ b/app/service/systemMethods/order/recheckOrder.js @@ -1942,6 +1942,65 @@ class RecheckOrderService extends OrderBaseService { type: this.ctx.model.QueryTypes.INSERT, } ); + + // 双写 order_operation_log(失败不影响主流程) + try { + const ctx = this.ctx; + const operationLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog; + if (isBatch) { + // 波次复核:按波次记录一条操作日志 + if (operationLogService && typeof operationLogService.createOperationLogs === 'function') { + const messageParts = []; + if (waveNo) { + messageParts.push(`波次 ${String(waveNo).trim()}`); + } + messageParts.push(`复核完成,正常${normalOrderCount || 0}单、拦截${interceptedOrderCount || 0}单、总计${totalOrderCount || 0}单`); + await operationLogService.createOperationLogs([{ + businessType: 'order', + businessId: String(waveId || ''), + operationCode: 'ORDER_RECHECK_BATCH', + operator: { id: String(operatorId || ''), name: operatorName }, + extras: { + warehouseId: warehouseId || 0, + message: messageParts.join(''), + waveId, + waveNo: waveNo || '', + normalOrderCount: normalOrderCount || 0, + interceptedOrderCount: interceptedOrderCount || 0, + totalOrderCount: totalOrderCount || 0, + }, + }]); + } + } else { + // 单订单复核 + if (operationLogService && typeof operationLogService.createOperationLogs === 'function') { + const messageParts = []; + if (waybillNo) { + messageParts.push(`运单 ${String(waybillNo).trim()} `); + } + messageParts.push('订单复核完成'); + await operationLogService.createOperationLogs([{ + businessType: 'order', + businessId: String(orderId || ''), + operationCode: 'ORDER_RECHECK', + operator: { id: String(operatorId || ''), name: operatorName }, + extras: { + warehouseId: warehouseId || 0, + message: messageParts.join(''), + orderId: orderId || 0, + waybillNo: waybillNo || '', + }, + }]); + } + } + } catch (e) { + this.ctx.logger.warn('[recheckOrder._writeRecheckActionLog] 写入 order_operation_log 失败', { + error: e && e.message, + orderId, + waveId, + warehouseId, + }); + } } /** @@ -3755,6 +3814,35 @@ class RecheckOrderService extends OrderBaseService { } } + // 写入 order_operation_log 拣货完成日志(双写) + try { + const operationLogService = ctx.service + && ctx.service.systems + && ctx.service.systems.operationLog; + if (operationLogService && typeof operationLogService.createOperationLogs === 'function') { + const logOperator = this.getOrderLogOperator(); + const operatorId = String(logOperator.id || '').trim(); + const operatorName = String(logOperator.name || 'system').trim(); + await operationLogService.createOperationLogs([ + { + businessType: 'order', + businessId: `${orderId}`, + operationCode: 'ORDER_PICK_COMPLETE', + operator: { id: operatorId || null, name: operatorName || 'system' }, + extras: { + message: `订单${orderId}拣货完成`, + warehouseId: Number(warehouseId), + externalLogType: 'API', + }, + }, + ], { transaction }); + } + } catch (e) { + ctx.logger.warn( + `[_completePickForOrder] order_operation_log 写入失败, orderId=${orderId}, error=${e.message}` + ); + } + // 步骤5:更新 wms_wave_pick_task 状态 if (hasTaskOrder) { const taskId = Number(taskOrderRows[0]?.task_id || 0); @@ -4312,6 +4400,31 @@ class RecheckOrderService extends OrderBaseService { transaction, } ); + + // 双写 order_operation_log(失败不影响主流程) + try { + const ctx = this.ctx; + const operationLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog; + if (operationLogService && typeof operationLogService.createOperationLogs === 'function') { + await operationLogService.createOperationLogs([{ + businessType: 'order', + businessId: String(orderId || ''), + operationCode: 'ORDER_RECHECK', + operator: { id: String(operatorId || ''), name: operatorName }, + extras: { + warehouseId: warehouseId || 0, + message: '订单复核完成', + orderId: orderId || 0, + }, + }], { transaction }); + } + } catch (e) { + this.ctx.logger.warn('[recheckOrder._writeRecheckActionLogInTransaction] 写入 order_operation_log 失败', { + error: e && e.message, + orderId, + warehouseId, + }); + } } } diff --git a/app/service/systemMethods/stock/warehouse.js b/app/service/systemMethods/stock/warehouse.js index 8814969..8950351 100644 --- a/app/service/systemMethods/stock/warehouse.js +++ b/app/service/systemMethods/stock/warehouse.js @@ -1031,7 +1031,11 @@ class WarehouseService extends MainService { const { mode } = data || {}; if (mode === 'combo') { - const { id, custom_code } = data || {}; + const { id, custom_code, keyword } = data || {}; + if (keyword) { + const result = await service.systems.comboGoods.search({ keyword }); + return this.success('ok', result); + } const result = await service.systems.comboGoods.searchByIdOrCode({ id, custom_code }); return this.success('ok', result); } diff --git a/app/service/systemMethods/storage/entry.js b/app/service/systemMethods/storage/entry.js index c3e169b..abae4df 100644 --- a/app/service/systemMethods/storage/entry.js +++ b/app/service/systemMethods/storage/entry.js @@ -9,9 +9,9 @@ class entryService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'list,get,cancel,completeEntry,getPrintData,getDirectInboundItems,addDirectInboundItem,commitDirectInbound,removeDirectInboundItem'; + const _noNeedRight = 'list,get,cancel,completeEntry,getPrintData,getDirectInboundItems,addDirectInboundItem,commitDirectInbound,removeDirectInboundItem,quickInbound,receivingCompare'; const _noNeedLog = 'list,get,getPrintData'; - const _noNeedAuth = 'list,get,cancel,completeEntry,getPrintData,getDirectInboundItems,addDirectInboundItem,commitDirectInbound,removeDirectInboundItem'; + const _noNeedAuth = 'list,get,cancel,completeEntry,getPrintData,getDirectInboundItems,addDirectInboundItem,commitDirectInbound,removeDirectInboundItem,bindReceivingDetails,quickInbound,receivingCompare'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -132,6 +132,33 @@ class entryService extends MainService { return this.success('ok', result); } + /** + * 批量绑定入库单明细与收货单明细(system method 包装层)。 + * @param {Object} data 请求体 + * @param {number} data.entry_order_id 入库单ID + * @param {Array} data.bindings 绑定列表 [{ entry_item_id, receiving_detail_id, allocated_quantity }] + * @return {Promise} 统一 success 包装 + */ + async bindReceivingDetails(data = {}) { + const { service } = this; + const { entry_order_id, bindings } = data || {}; + const result = await service.systems.receiving_entry_match.bindReceivingDetails({ entry_order_id, bindings }); + return this.success('绑定完成', result); + } + + /** + * 快捷直入/虚拟入库(system method 包装层)。 + * @param {Object} data 请求体 + * @param {number} data.id 入库单ID + * @return {Promise} 统一 success 包装 + */ + async quickInbound(data = {}) { + const { service } = this; + const { id } = data; + const result = await service.systems.storage.entry.quickInbound({ id }); + return this.success('ok', result); + } + /** * 获取入库单打印数据,按 RECEIPT 模板 field_code 映射返回。 * @param {Object} data 请求体 @@ -217,5 +244,19 @@ class entryService extends MainService { return this.fail(error.message || '获取打印数据失败', { code: 500 }); } } + /** + * 入库单商品与收货单商品逐行对照视图(system method 包装层)。 + * @param {Object} data 请求体 + * @param {number} data.entry_order_id 入库单ID + * @param {number} data.receiving_id 收货单ID + * @return {Promise} 统一 success 包装 + */ + async receivingCompare(data = {}) { + const { service } = this; + const { entry_order_id, receiving_id } = data || {}; + const result = await service.systems.storage.entry.receivingCompare({ entry_order_id, receiving_id }); + return this.success('ok', result); + } + } module.exports = entryService; diff --git a/app/service/systemMethods/storage/receiving.js b/app/service/systemMethods/storage/receiving.js index 6f72776..8c6ddd2 100644 --- a/app/service/systemMethods/storage/receiving.js +++ b/app/service/systemMethods/storage/receiving.js @@ -10,9 +10,9 @@ class configService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs,manualMatchEntryOrder'; - const _noNeedLog = 'getReceivingList,get,addDetail,deleteDetail,detailChange,bindStore,bindDetailProduct,queryReceivingLogs,manualMatchEntryOrder'; - const _noNeedAuth = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs,manualMatchEntryOrder'; + const _noNeedRight = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs'; + const _noNeedLog = 'getReceivingList,get,addDetail,deleteDetail,detailChange,bindStore,bindDetailProduct,queryReceivingLogs'; + const _noNeedAuth = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -260,23 +260,5 @@ class configService extends MainService { }); } - /** - * 手动匹配入库单与收货单(system method 包装层)。 - * - * 传入收货单 ID 与入库单 ID,复用 `receiving_entry_match` 服务的匹配逻辑, - * 同步执行 SKU 明细对比并按来源回传(奇门 / OpenAPI),返回结构化匹配结果。 - * - * @param {Object} data 请求体 - * @param {number} data.receivingId 收货单 ID - * @param {number} data.entryOrderId 入库单 ID - * @return {Promise} 统一成功包装的匹配结果 - */ - async manualMatchEntryOrder(data) { - const { service } = this; - const { receivingId, entryOrderId } = data || {}; - const result = await service.systems.receiving_entry_match.manualMatch(receivingId, entryOrderId); - return this.success('匹配完成', result); - } - } module.exports = configService; diff --git a/app/service/systems/express.js b/app/service/systems/express.js index e7d38a1..928eb74 100644 --- a/app/service/systems/express.js +++ b/app/service/systems/express.js @@ -2427,8 +2427,21 @@ class ExpressService extends Service { }); // 发件人相关字段统一走接口配置,货主配置仅用于打印链路。 + // 三级兜底:express_interface → 仓库 subject_config → 空字符串 + const storeRow = await this.ctx.model.Store.findByPk(warehouseId, { + attributes: [ 'subject_config' ], + raw: true, + }); + const subjectConfig = (storeRow && storeRow.subject_config) ? storeRow.subject_config : {}; const expressInterfaceConfig = expressInterface ? { ...expressInterface, + sender_name: expressInterface.sender_name || subjectConfig.sender_name || '', + sender_tel: expressInterface.sender_tel || subjectConfig.sender_tel || '', + province_name: expressInterface.province_name || subjectConfig.province_name || '', + city_name: expressInterface.city_name || subjectConfig.city_name || '', + district_name: expressInterface.district_name || subjectConfig.district_name || '', + town_name: expressInterface.town_name || subjectConfig.town_name || '', + address: expressInterface.address || subjectConfig.address || '', } : null; for (const batch of batches) { diff --git a/app/service/systems/express_platform.js b/app/service/systems/express_platform.js index b67e63f..be62f09 100644 --- a/app/service/systems/express_platform.js +++ b/app/service/systems/express_platform.js @@ -729,17 +729,27 @@ class ExpressPlatformService extends MainService { inputsite: listByWarehousePlatformCode.site_code || '', sitecode: listByWarehousePlatformCode.site_code || '', shipperno: listByWarehousePlatformCode.shipperno || '', - sender: { - company: listByWarehousePlatformCode.shop_name || '', - name: listByWarehousePlatformCode.sender_name || '', - phone: listByWarehousePlatformCode.sender_tel || '', - country: 'CN', - city: listByWarehousePlatformCode.city_name || '', - province: listByWarehousePlatformCode.province_name || '', - area: listByWarehousePlatformCode.district_name || '', - town: listByWarehousePlatformCode.town_name || '', - address: listByWarehousePlatformCode.address || '', - }, // 需要实现 + sender: (() => { + const senderName = listByWarehousePlatformCode.sender_name || ''; + const senderTel = listByWarehousePlatformCode.sender_tel || ''; + const senderProvince = listByWarehousePlatformCode.province_name || ''; + const senderCity = listByWarehousePlatformCode.city_name || ''; + const senderDistrict = listByWarehousePlatformCode.district_name || ''; + const senderTown = listByWarehousePlatformCode.town_name || ''; + const senderAddress = listByWarehousePlatformCode.address || ''; + const fallback = '仓库未配置发件人'; + return { + company: listByWarehousePlatformCode.shop_name || '', + name: senderName || fallback, + phone: senderTel || (senderName ? '' : fallback), + country: 'CN', + city: senderCity || fallback, + province: senderProvince || fallback, + area: senderDistrict || fallback, + town: senderTown || fallback, + address: senderAddress || fallback, + }; + })(), receiver: { name: order.name || '', company: order.company || '', @@ -812,7 +822,7 @@ class ExpressPlatformService extends MainService { city: receiverCity, address: receiverAddress, } = receiver; - const senderName = senderNameRaw || listByWarehousePlatformCode.sender_name || listByWarehousePlatformCode.shop_name || ''; + const senderName = senderNameRaw || listByWarehousePlatformCode.sender_name || listByWarehousePlatformCode.shop_name || '仓库未配置发件人'; const senderCompany = senderCompanyRaw || listByWarehousePlatformCode.shop_name || ''; const customername = senderNameRaw || senderCompanyRaw || listByWarehousePlatformCode.shop_name || '测试'; @@ -1690,18 +1700,28 @@ class ExpressPlatformService extends MainService { ? (listByWarehousePlatformCode.express.CAINIAO || listByWarehousePlatformCode.express.cainiao_code || '') : '', product_code: String(listByWarehousePlatformCode.product_type || '').trim(), - sender: { - address: { - city: listByWarehousePlatformCode.city_name, - detail: listByWarehousePlatformCode.address, - district: listByWarehousePlatformCode.district_name, - province: listByWarehousePlatformCode.province_name, - town: listByWarehousePlatformCode.town_name || null, - }, - mobile: listByWarehousePlatformCode.sender_tel, - name: listByWarehousePlatformCode.sender_name, - phone: listByWarehousePlatformCode.sender_tel, - }, + sender: (() => { + const senderName = listByWarehousePlatformCode.sender_name || ''; + const senderTel = listByWarehousePlatformCode.sender_tel || ''; + const senderProvince = listByWarehousePlatformCode.province_name || ''; + const senderCity = listByWarehousePlatformCode.city_name || ''; + const senderDistrict = listByWarehousePlatformCode.district_name || ''; + const senderTown = listByWarehousePlatformCode.town_name || ''; + const senderAddress = listByWarehousePlatformCode.address || ''; + const fallback = '仓库未配置发件人'; + return { + address: { + city: senderCity || fallback, + detail: senderAddress || fallback, + district: senderDistrict || fallback, + province: senderProvince || fallback, + town: senderTown || null, + }, + mobile: senderTel || (senderName ? '' : fallback), + name: senderName || fallback, + phone: senderTel || (senderName ? '' : fallback), + }; + })(), trade_order_info_dtos: tradeOrderList, brand_code: String(listByWarehousePlatformCode.site_code || 'default').trim(), need_encrypt: true, @@ -2241,26 +2261,35 @@ class ExpressPlatformService extends MainService { } ); // 构建pdd接口入参 - const pddPayload = { // 这里根据实际需要构建接口入参 type: 'pdd.waybill.get', accessToken: listByWarehousePlatformCode.token, param_waybill_cloud_print_apply_new_request: { need_encrypt: true, - sender: { - address: { - country: '中国', - city: listByWarehousePlatformCode.city_name, - province: listByWarehousePlatformCode.province_name, - district: listByWarehousePlatformCode.district_name, - town: listByWarehousePlatformCode.town_name || null, - detail: listByWarehousePlatformCode.address, - }, - moblie: listByWarehousePlatformCode.sender_tel, - name: listByWarehousePlatformCode.sender_name, - phone: listByWarehousePlatformCode.sender_tel, - }, + sender: (() => { + const senderName = listByWarehousePlatformCode.sender_name || ''; + const senderTel = listByWarehousePlatformCode.sender_tel || ''; + const senderProvince = listByWarehousePlatformCode.province_name || ''; + const senderCity = listByWarehousePlatformCode.city_name || ''; + const senderDistrict = listByWarehousePlatformCode.district_name || ''; + const senderTown = listByWarehousePlatformCode.town_name || ''; + const senderAddress = listByWarehousePlatformCode.address || ''; + const fallback = '仓库未配置发件人'; + return { + address: { + country: '中国', + city: senderCity || fallback, + province: senderProvince || fallback, + district: senderDistrict || fallback, + town: senderTown || null, + detail: senderAddress || fallback, + }, + moblie: senderTel || (senderName ? '' : fallback), + name: senderName || fallback, + phone: senderTel || (senderName ? '' : fallback), + }; + })(), trade_order_info_dtos: tradeOrderList, wp_code: listByWarehousePlatformCode && listByWarehousePlatformCode.express ? (listByWarehousePlatformCode.express.PDD || '') diff --git a/app/service/systems/order_print.js b/app/service/systems/order_print.js index dc9e44c..e894bb1 100644 --- a/app/service/systems/order_print.js +++ b/app/service/systems/order_print.js @@ -2701,6 +2701,22 @@ ${waveFilterSql} const expressSysLogisticsCode = String(orderExpress.sys_logistics_code || '').trim(); const expressSysLogisticsName = String(orderExpress.sys_logistics_name || '').trim(); const documentId = waybillCode || `doc_${orderId}`; + + // 查询仓库 subject_config 用于发件人兜底 + const warehouseId = Number(orderRow.warehouse_id || 0); + let subjectConfig = {}; + if (warehouseId > 0) { + const storeRow = await this.ctx.model.Store.findByPk(warehouseId, { + attributes: ['subject_config'], + raw: true, + }); + if (storeRow && storeRow.subject_config) { + subjectConfig = this.isPlainObject(storeRow.subject_config) + ? storeRow.subject_config + : {}; + } + } + const printPayload = PrinterDataBuilder.buildPlatformRequestSkeleton({ platform: platformCode, order_express: orderExpress, @@ -2709,6 +2725,7 @@ ${waveFilterSql} policy_config: policyConfig, }, policy_config: policyConfig, + subject_config: subjectConfig, template_sample: templateSample, options: { requestId, diff --git a/app/service/systems/order_storage_allocation.js b/app/service/systems/order_storage_allocation.js index dd9028d..5197b13 100644 --- a/app/service/systems/order_storage_allocation.js +++ b/app/service/systems/order_storage_allocation.js @@ -832,7 +832,6 @@ class OrderStorageAllocationService extends MainService { const policyCache = new Map(); const shortageReasonCache = new Map(); const pickingRows = []; - const stockAllocationMap = new Map(); const storageAllocationMap = new Map(); const orderResults = []; const totalCount = pendingOrderIds.length; @@ -1093,7 +1092,6 @@ class OrderStorageAllocationService extends MainService { allocatedQuantityForOrder += allocationQuantity; storageAllocationMap.set(storageRow.id, (storageAllocationMap.get(storageRow.id) || 0) + allocationQuantity); - stockAllocationMap.set(stockId, (stockAllocationMap.get(stockId) || 0) + allocationQuantity); const spaceId = toNumber(storageRow.space_id, 0); if (!spaceId) { @@ -1110,15 +1108,7 @@ class OrderStorageAllocationService extends MainService { storageRow.id, allocationQuantity, { transaction } ); - // 回退 stockAllocationMap 和 storageAllocationMap 中的累加值,防止 wms_stock_warehouse.locked_quantity 批量更新时多锁 - const prevStockQty = stockAllocationMap.get(stockId) || 0; - const newStockQty = prevStockQty - allocationQuantity; - if (newStockQty <= 0) { - stockAllocationMap.delete(stockId); - } else { - stockAllocationMap.set(stockId, newStockQty); - } - + // 回退 storageAllocationMap 中的累加值 const prevStorageQty = storageAllocationMap.get(storageRow.id) || 0; const newStorageQty = prevStorageQty - allocationQuantity; if (newStorageQty <= 0) { @@ -1129,11 +1119,8 @@ class OrderStorageAllocationService extends MainService { writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 库位无效,回退库存主表锁定累加', { orderId, - stockId, storageId: storageRow.id, allocationQuantity, - prevStockQty, - newStockQty, prevStorageQty, newStorageQty, }); @@ -1251,107 +1238,6 @@ class OrderStorageAllocationService extends MainService { }); } - 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); - - if (stockLockEntries.length > 0) { - writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 准备批量更新库存主表锁定数量', { - warehouseId, - stockLockEntries, - }); - - 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, - }); - - 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: missingStockEntry.stockId, - quantity: missingStockEntry.quantity, - }); - throw new Error(`库存主记录不存在: ${missingStockEntry.stockId}`); - } - - const updateSqlReplacements = { - warehouseId, - 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) { writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 写入 picking 明细', { warehouseId, @@ -1369,10 +1255,7 @@ class OrderStorageAllocationService extends MainService { 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, - }))), + stockLockSummary: [], storageLockSummary: summarizeArrayForLog(Array.from(storageAllocationMap.entries()).map(([ storageId, quantity ]) => ({ storage_id: storageId, locked_quantity: quantity, @@ -1437,10 +1320,7 @@ class OrderStorageAllocationService extends MainService { skipped_orders: skippedOrders, orders: [ ...skippedOrders, ...orderResults ], picking_count: pickingRows.length, - stock_lock_summary: Array.from(stockAllocationMap.entries()).map(([ stockId, quantity ]) => ({ - stock_id: stockId, - locked_quantity: quantity, - })), + stock_lock_summary: [], storage_lock_summary: Array.from(storageAllocationMap.entries()).map(([ storageId, quantity ]) => ({ storage_id: storageId, locked_quantity: quantity, @@ -1460,7 +1340,7 @@ class OrderStorageAllocationService extends MainService { shortageOrderIds: summarizeArrayForLog(responseData.shortage_order_ids), skippedOrders: summarizeArrayForLog(responseData.skipped_orders), orders: summarizeArrayForLog(responseData.orders), - stockLockSummary: summarizeArrayForLog(responseData.stock_lock_summary), + stockLockSummary: [], storageLockSummary: summarizeArrayForLog(responseData.storage_lock_summary), shortageMessages: summarizeArrayForLog(responseData.shortage_messages), pickingCount: responseData.picking_count, @@ -2008,7 +1888,6 @@ class OrderStorageAllocationService extends MainService { const orderModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); const pickingModel = ctx.model.Picking; const storageModel = ctx.model.Storage; - const stockModel = ctx.model.StockWarehouse; if (!pickingModel || typeof pickingModel.findAll !== 'function' || typeof pickingModel.destroy !== 'function') { throw new Error('wms_picking 模型不可用'); @@ -2018,10 +1897,6 @@ class OrderStorageAllocationService extends MainService { throw new Error('wms_storage 模型不可用'); } - if (!stockModel || typeof stockModel.findByPk !== 'function') { - throw new Error('wms_stock_warehouse 模型不可用'); - } - const orderRows = await orderModel.findAll({ where: { id: { @@ -2195,7 +2070,6 @@ class OrderStorageAllocationService extends MainService { } const storageUnlockSummary = []; - const stockUnlockSummary = []; for (const [ storageId, quantity ] of storageQuantityMap.entries()) { if (quantity <= 0) { @@ -2207,11 +2081,6 @@ class OrderStorageAllocationService extends MainService { throw new Error(`库存记录不存在: ${storageId}`); } - const stockId = toNumber(storageRow.stock_id, 0); - if (stockId <= 0) { - throw new Error(`库存记录缺少 stock_id: ${storageId}`); - } - await ctx.service.systems.storage.index.unlockQuantity(storageId, quantity, { transaction, }); @@ -2220,49 +2089,6 @@ class OrderStorageAllocationService extends MainService { storage_id: storageId, unlocked_quantity: quantity, }); - - if (typeof stockModel.update === 'function') { - const decrementResult = await stockModel.update({ - locked_quantity: app.Sequelize.literal(`locked_quantity - ${Number(quantity)}`), - update_at: app.Sequelize.literal('CURRENT_TIMESTAMP'), - }, { - where: { - id: stockId, - locked_quantity: { - [Op.gte]: Number(quantity), - }, - }, - transaction, - }); - - if (!Array.isArray(decrementResult) || Number(decrementResult[0] || 0) <= 0) { - throw new Error(`库存主记录锁定数量不足,无法释放: ${stockId}`); - } - } else { - const stockRecord = await stockModel.findByPk(stockId, { - transaction, - }); - - if (!stockRecord) { - throw new Error(`库存主记录不存在: ${stockId}`); - } - - const currentLocked = toNumber(stockRecord.locked_quantity, 0); - if (currentLocked < Number(quantity)) { - throw new Error(`库存主记录锁定数量不足,无法释放: ${stockId}`); - } - - await stockRecord.increment('locked_quantity', { - by: -quantity, - transaction, - silent: true, - }); - } - - stockUnlockSummary.push({ - stock_id: stockId, - unlocked_quantity: quantity, - }); } const cancelPickingIds = []; @@ -2332,7 +2158,7 @@ class OrderStorageAllocationService extends MainService { orders: [ ...skippedOrders, ...orderResults ], picking_count: cancelPickingIds.length, storage_unlock_summary: storageUnlockSummary, - stock_unlock_summary: stockUnlockSummary, + stock_unlock_summary: [], }; await transaction.commit(); diff --git a/app/service/systems/pick.js b/app/service/systems/pick.js index 9d6fc5f..b71a08b 100644 --- a/app/service/systems/pick.js +++ b/app/service/systems/pick.js @@ -1777,6 +1777,35 @@ class PickSystemService extends Service { } } + // 检查目标订单是否已分配储位(storage_status='fin'),防止订单在波次中被取消储位分配后仍然完成拣货 + if (targetOrderIds.length > 0) { + const orderModel = await this.getOrderModel(warehouseId); + const unallocatedOrders = await orderModel.findAll({ + where: { + warehouse_id: warehouseId, + id: { + [this.app.Sequelize.Op.in]: targetOrderIds, + }, + storage_status: { + [this.app.Sequelize.Op.ne]: 'fin', + }, + }, + attributes: [ 'id', 'storage_status' ], + raw: true, + transaction, + }); + + if (unallocatedOrders && unallocatedOrders.length > 0) { + const detailList = unallocatedOrders.map( + o => `订单${o.id}(storage_status=${o.storage_status})` + ).join(';'); + throw this.createBusinessError( + `以下订单未分配储位,无法完成拣货:${detailList}`, + 400 + ); + } + } + await ctx.model.query(` UPDATE wms_wave_pick_task_order SET pick_status = 1, @@ -2023,7 +2052,7 @@ class PickSystemService extends Service { extras: { message: `订单${orderId}拣货完成`, warehouseId, - externalLogType: 'PDA', + externalLogType: 'API', }, })); await operationLogService.createOperationLogs(logPayloads); diff --git a/app/service/systems/receiving_entry_match.js b/app/service/systems/receiving_entry_match.js index 269dab3..6d41b74 100644 --- a/app/service/systems/receiving_entry_match.js +++ b/app/service/systems/receiving_entry_match.js @@ -746,136 +746,176 @@ class ReceivingEntryMatchService extends Service { } /** - * 手动匹配入库单与收货单。 - * - * 同步执行明细对比并触发回传,返回结构化匹配结果。 - * 适用场景:运营人员手动指定收货单与入库单进行匹配并回传。 - * - * 匹配规则(复用 _compareDetails): - * - full_match:两者 SKU 与数量完全一致 → 按来源回传 - * - receiving_covers_entry:收货单覆盖入库单 → 回传 + 标记部分入库 - * - entry_exceeds_receiving / no_match → 仅返回对比结果,不触发回传 - * - * @param {number} receivingId 收货单 ID - * @param {number} entryOrderId 入库单 ID - * @return {Promise} 匹配结果对象 - * @return {string} return.matchType 匹配类型:full_match / receiving_covers_entry / entry_exceeds_receiving / no_match - * @return {Object} return.comparisonResult 明细对比结果 - * @return {boolean} return.callbackSent 是否已发送回传 - * @return {Object|null} return.callbackResult 回传结果(未发送时为 null) - * @return {boolean} return.partialStorageMarked 是否已标记部分入库 - * @return {Object} return.entryOrder 入库单摘要 - * @return {Object} return.receivingOrder 收货单摘要 + * 批量绑定入库单明细与收货单明细。 + * 依次校验入库单状态、商品匹配关系、可用数量,事务写入绑定并确保主级绑定存在。 + * @param {Object} data 请求参数 + * @param {number} data.entry_order_id 入库单ID + * @param {Array} data.bindings 绑定列表 + * @param {number} data.bindings[].entry_item_id 入库单明细ID + * @param {number} data.bindings[].receiving_detail_id 收货单明细ID + * @param {number} data.bindings[].allocated_quantity 分配数量 + * @return {Promise} { success: [...], failed: [...], success_count, failed_count } */ - async manualMatch(receivingId, entryOrderId) { + /** + * 批量绑定入库单明细与收货单明细。 + * 在事务中对每条绑定使用 FOR UPDATE 行锁防并发超卖,失败项返回结构化错误码。 + * + * @param {Object} data 请求参数 + * @param {number} data.entry_order_id 入库单 ID + * @param {Array<{entry_item_id: number, receiving_detail_id: number, allocated_quantity: number}>} data.bindings 绑定列表 + * @return {Promise<{success: Array, failed: Array, success_count: number, failed_count: number}>} 绑定结果 + */ + async bindReceivingDetails(data = {}) { const { ctx } = this; + const { entry_order_id: entryOrderId, bindings = [] } = data || {}; - // 1. 加载入库单及其明细 - const entryOrder = await ctx.model.EntryOrder.findOne({ - where: { id: entryOrderId, is_enabled: 1, deleted_at: null }, - include: [{ - model: ctx.model.EntryItems, - as: 'items', - required: false, - attributes: [ 'id', 'item_code', 'stock_id', 'count', 'received_quantity', 'inventory_type' ], - }], - }); - - if (!entryOrder) { - throw new Error(`入库单不存在:${entryOrderId}`); + if (!entryOrderId || !Array.isArray(bindings) || bindings.length === 0) { + throw new Error('参数不完整'); } - // 2. 加载收货单及其明细 - const receivingOrder = await ctx.model.Receiving.findOne({ - where: { id: receivingId, is_deleted: false }, - include: [{ - model: ctx.model.ReceivingDetail, - as: 'details', - required: false, - attributes: [ - 'id', 'system_product_id', 'product_name', 'actual_quantity', - 'storage_status', 'stored_quantity', - ], - }], - }); - - if (!receivingOrder) { - throw new Error(`收货单不存在:${receivingId}`); + // 1. 查询入库单,校验状态(必须是 PENDING 或 CREATED) + const entryOrder = await ctx.model.EntryOrder.findByPk(entryOrderId); + if (!entryOrder || ![ 'CREATED', 'PENDING' ].includes(entryOrder.order_status)) { + // 入库单状态不对 → 全部 bindings 标记为 ENTRY_ORDER_STATUS_INVALID + const allFailed = bindings.map(b => ({ + entry_item_id: b.entry_item_id, + receiving_detail_id: b.receiving_detail_id, + allocated_quantity: b.allocated_quantity, + error_code: 'ENTRY_ORDER_STATUS_INVALID', + message: '入库单状态不允许绑定', + detail: { order_status: entryOrder ? entryOrder.order_status : null }, + })); + return { success: [], failed: allFailed, success_count: 0, failed_count: allFailed.length }; } - // 3. 校验同仓库 - if (entryOrder.warehouse_id !== receivingOrder.warehouse_id) { - throw new Error( - `入库单仓库(${entryOrder.warehouse_id})与收货单仓库(${receivingOrder.warehouse_id})不一致` - ); + const success = []; + const failed = []; + + for (const binding of bindings) { + const { entry_item_id: entryItemId, receiving_detail_id: receivingDetailId, allocated_quantity: qty } = binding; + try { + // 2. 查询 entry_item 和对应的 stock_id + const entryItem = await ctx.model.EntryItems.findByPk(entryItemId); + if (!entryItem) { + throw { + error_code: 'ENTRY_ITEM_NOT_FOUND', + message: '入库明细不存在', + detail: { entry_item_id: entryItemId }, + }; + } + + // 3. 通过 stock_id → system_product_id 校验收货单明细匹配 + const sw = await ctx.model.StockWarehouse.findOne({ + where: { id: entryItem.stock_id, warehouse_id: entryOrder.warehouse_id }, + attributes: [ 'system_product_id' ], + raw: true, + }); + if (!sw || !sw.system_product_id) { + throw { + error_code: 'STOCK_NOT_FOUND', + message: '商品不存在', + detail: { stock_id: entryItem.stock_id }, + }; + } + + // 4. 事务:FOR UPDATE 锁行 → 查已分配量 → 写入绑定 + await ctx.model.transaction(async t => { + // 4a. 先锁收货明细行 + const lockedDetail = await ctx.model.query( + `SELECT id, actual_quantity, receiving_id, system_product_id + FROM wms_receiving_detail + WHERE id = :rdId FOR UPDATE`, + { + replacements: { rdId: receivingDetailId }, + type: ctx.model.QueryTypes.SELECT, + transaction: t, + } + ); + if (!lockedDetail || lockedDetail.length === 0) { + throw { + error_code: 'RECEIVING_DETAIL_NOT_FOUND', + message: '收货明细不存在', + detail: { receiving_detail_id: receivingDetailId }, + }; + } + + // 4b. 校验收货明细与入库商品是否匹配(system_product_id) + if (lockedDetail[0].system_product_id !== sw.system_product_id) { + throw { + error_code: 'RECEIVING_DETAIL_MISMATCH', + message: '收货明细与入库商品不匹配', + detail: { + entry_item_id: entryItemId, + receiving_detail_id: receivingDetailId, + expected_sp_id: sw.system_product_id, + actual_sp_id: lockedDetail[0].system_product_id, + }, + }; + } + + // 4c. 查已 committed 的分配量 + const allocatedSum = await ctx.model.query( + `SELECT COALESCE(SUM(allocated_quantity), 0) AS total + FROM wms_entry_receiving_binding + WHERE receiving_detail_id = :rdId AND status = 'committed' AND deleted_at IS NULL`, + { + replacements: { rdId: receivingDetailId }, + type: ctx.model.QueryTypes.SELECT, + transaction: t, + } + ); + const availableQty = lockedDetail[0].actual_quantity - Number(allocatedSum[0]?.total || 0); + if (qty > availableQty) { + throw { + error_code: 'INSUFFICIENT_AVAILABLE_QUANTITY', + message: '分配数量超出可用量', + detail: { available_quantity: availableQty, requested_quantity: qty }, + }; + } + + // 4d. 写入绑定 + await ctx.model.EntryReceivingBinding.create({ + entry_item_id: entryItemId, + receiving_detail_id: receivingDetailId, + allocated_quantity: qty, + status: 'committed', + creator_id: ctx.currentUser?.id || 0, + }, { transaction: t }); + + // 确保主级绑定存在 + await ctx.model.EntryOrderReceiving.findOrCreate({ + where: { entry_order_id: entryOrderId, receiving_id: lockedDetail[0].receiving_id }, + defaults: { entry_order_id: entryOrderId, receiving_id: lockedDetail[0].receiving_id }, + transaction: t, + }); + }); + + success.push({ entry_item_id: entryItemId, receiving_detail_id: receivingDetailId, allocated_quantity: qty }); + } catch (err) { + // 结构化错误对象或普通 Error 统一转为 failed 项 + if (err.error_code) { + failed.push({ + entry_item_id: entryItemId, + receiving_detail_id: receivingDetailId, + allocated_quantity: qty, + error_code: err.error_code, + message: err.message, + detail: err.detail || {}, + }); + } else { + failed.push({ + entry_item_id: entryItemId, + receiving_detail_id: receivingDetailId, + allocated_quantity: qty, + error_code: 'INTERNAL_ERROR', + message: err.message || '未知错误', + detail: {}, + }); + } + } } - // 4. 构建入库单明细 - const entryItems = (entryOrder.items || []).map(item => ({ - stockId: item.stock_id, - itemCode: item.item_code, - count: item.count || 0, - receivedQuantity: item.received_quantity || 0, - inventoryType: item.inventory_type || 'ZP', - })); - - // 5. 构建收货单明细 - const receivingPlain = typeof receivingOrder.toJSON === 'function' - ? receivingOrder.toJSON() - : receivingOrder; - const receivingDetails = (receivingPlain.details || []).map(d => ({ - id: d.id, - system_product_id: d.system_product_id, - product_name: d.product_name, - actual_quantity: d.actual_quantity, - storage_status: d.storage_status, - stored_quantity: d.stored_quantity || 0, - })); - - // 6. 对比明细 - const comparisonResult = this._compareDetails(entryItems, receivingDetails); - - const result = { - matchType: comparisonResult.type, - comparisonResult, - callbackSent: false, - callbackResult: null, - partialStorageMarked: false, - entryOrder: { - id: entryOrder.id, - entry_order_code: entryOrder.entry_order_code, - source_type: entryOrder.source_type, - warehouse_id: entryOrder.warehouse_id, - status: entryOrder.status, - }, - receivingOrder: { - id: receivingOrder.id, - receiving_number: receivingOrder.receiving_number, - status: receivingOrder.status, - storage_status: receivingOrder.storage_status, - }, - }; - - // 7. 根据对比结果处理 - if (comparisonResult.type === 'full_match') { - const callbackResult = await this._sendCallback(entryOrder, receivingOrder, 'manual_match'); - result.callbackSent = true; - result.callbackResult = callbackResult; - } else if (comparisonResult.type === 'receiving_covers_entry') { - const callbackResult = await this._sendCallback(entryOrder, receivingOrder, 'manual_match'); - result.callbackSent = true; - result.callbackResult = callbackResult; - - const markResult = await this._markReceivingPartialStorage( - receivingOrder.id, - comparisonResult, - receivingOrder.warehouse_id - ); - result.partialStorageMarked = markResult.success; - } - // entry_exceeds_receiving / no_match → 不触发回传 - - return result; + return { success, failed, success_count: success.length, failed_count: failed.length }; } } diff --git a/app/service/systems/setting/warehouse.js b/app/service/systems/setting/warehouse.js index e3a1f1d..8dd1bfa 100644 --- a/app/service/systems/setting/warehouse.js +++ b/app/service/systems/setting/warehouse.js @@ -69,6 +69,69 @@ const WAREHOUSE_SETTING_FIELDS = Object.freeze([ description: '仓库默认使用的平台编码', maxLength: 50, }), + Object.freeze({ + key: 'sender_name', + name: '发件人姓名', + type: 'string', + default: '', + required: false, + description: '仓库默认发件人姓名', + maxLength: 50, + }), + Object.freeze({ + key: 'sender_tel', + name: '发件人电话', + type: 'string', + default: '', + required: false, + description: '仓库默认发件人联系电话', + maxLength: 20, + }), + Object.freeze({ + key: 'province_name', + name: '省份', + type: 'string', + default: '', + required: false, + description: '仓库默认发件省份', + maxLength: 50, + }), + Object.freeze({ + key: 'city_name', + name: '城市', + type: 'string', + default: '', + required: false, + description: '仓库默认发件城市', + maxLength: 50, + }), + Object.freeze({ + key: 'district_name', + name: '区/县', + type: 'string', + default: '', + required: false, + description: '仓库默认发件区/县', + maxLength: 50, + }), + Object.freeze({ + key: 'town_name', + name: '镇/街道', + type: 'string', + default: '', + required: false, + description: '仓库默认发件镇/街道', + maxLength: 50, + }), + Object.freeze({ + key: 'address', + name: '详细地址', + type: 'string', + default: '', + required: false, + description: '仓库默认发件详细地址', + maxLength: 200, + }), Object.freeze({ key: 'group_wave_prefix', name: '团购波次前缀', diff --git a/app/service/systems/stock_store.js b/app/service/systems/stock_store.js index ece8b01..af6c592 100644 --- a/app/service/systems/stock_store.js +++ b/app/service/systems/stock_store.js @@ -1911,21 +1911,59 @@ class stockStoreService extends Service { const hasPrevious = page > 1; const hasNext = page < totalPages; - // 批量查询条码和图片信息(复用 getStockDetails 缓存) + // 批量查询条码和图片信息(直接查 DB,不走 getStockDetails 缓存) const stockIds = data.map(item => item.id); const stockDetailsMap = new Map(); if (stockIds.length > 0) { - const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails( - stockIds, - { warehouseId: ctx.user.store_id } - ); - for (const detail of stockDetails) { - const sid = Number(detail.id); + // 并行查询条码和图片表(无缓存),避免影响其他接口对 getStockDetails 缓存的使用 + const [ barcodeRows, imageRows ] = await Promise.all([ + app.model.StockBarcode.findAll({ + where: { stock_id: { [ Op.in ]: stockIds } }, + attributes: [ 'id', 'barcode', 'stock_id' ], + raw: true, + }), + app.model.FileReference.findAll({ + where: { + business_type: 'stock', + business_id: { [ Op.in ]: stockIds.map(String) }, + }, + include: [{ + model: app.model.File, + as: 'file', + attributes: [ 'file_url' ], + required: false, + }], + raw: true, + }), + ]); + + // 按 stock_id 分组条码 + const barcodeMap = new Map(); + for (const row of barcodeRows) { + const sid = row.stock_id; + const bc = (row.barcode && String(row.barcode).trim()) || ''; + if (!bc) continue; + if (!barcodeMap.has(sid)) { + barcodeMap.set(sid, []); + } + barcodeMap.get(sid).push(bc); + } + + // 按 business_id 分组图片(有图片即认为 is_images=Y) + const imageStockIdSet = new Set(); + for (const row of imageRows) { + const sid = Number(row.business_id); + const url = (row['file.file_url'] && String(row['file.file_url']).trim()) || ''; + if (url) { + imageStockIdSet.add(sid); + } + } + + for (const item of data) { + const sid = item.id; stockDetailsMap.set(sid, { - barcodes: Array.isArray(detail.barcodes) - ? detail.barcodes.map(bc => String(bc.barcode || '').trim()).filter(Boolean) - : [], - images: detail.is_images === 'Y' ? [] : [], + barcodes: barcodeMap.get(sid) || [], + images: [], }); } } @@ -1936,7 +1974,7 @@ class stockStoreService extends Service { const lockRate = item.quantity > 0 ? (item.locked_quantity / item.quantity * 100).toFixed( 2) : 0; - // 从 getStockDetails 获取该商品的条码和图片 + // 从直接的 DB 查询结果获取该商品的条码和图片 const stockDetail = stockDetailsMap.get(item.id); const itemBarcodes = stockDetail ? stockDetail.barcodes : []; const itemImages = stockDetail ? stockDetail.images : []; diff --git a/app/service/systems/storage/entry.js b/app/service/systems/storage/entry.js index 54792c1..0f6a91b 100644 --- a/app/service/systems/storage/entry.js +++ b/app/service/systems/storage/entry.js @@ -523,8 +523,9 @@ class EntryService extends Service { } // 扁平化 items:用 getStockDetails 返回的商品详情替换原有的 stock + barcodes + let flattenedItems; if (entryOrderJSON.items && Array.isArray(entryOrderJSON.items)) { - entryOrderJSON.items = entryOrderJSON.items.map(item => { + flattenedItems = entryOrderJSON.items.map(item => { const { item_code, item_id, stock_id: itemStockId, ...rest } = item; const stockDetail = itemStockId != null ? stockDetailMap.get(Number(itemStockId)) || null : null; const directInboundQty = (stockDetail && directInboundMap[stockDetail.id]) || 0; @@ -551,8 +552,14 @@ class EntryService extends Service { remaining_quantity: remaining, }; }); + } else { + flattenedItems = entryOrderJSON.items || []; } + // 为每个 item 补充可匹配的收货单明细及剩余可用量 + const enrichedItems = await this.enrichItemsWithAvailableReceivingDetails(flattenedItems, warehouseId); + entryOrderJSON.items = enrichedItems; + return { code: 200, message: '查询成功', @@ -562,6 +569,87 @@ class EntryService extends Service { }; } + /** + * 为 entry items 批量补充可匹配的收货单明细及剩余可用量。 + * 匹配规则:entry_item.stock_id 即 wms_stock_warehouse.id,与 wms_receiving_detail.system_product_id 直接对应。 + * 只返回收货单状态为未完成(status NOT IN ('completed','cancelled'))且未完全入库(storage_status IN ('none','partial'))的明细。 + * @param {Object[]} items 扁平化后的 entry items 数组 + * @param {number} warehouseId 仓库ID + * @return {Promise} 补充了 available_receiving_details 的 items + */ + async enrichItemsWithAvailableReceivingDetails(items, warehouseId) { + if (!Array.isArray(items) || items.length === 0) return items; + + const { ctx } = this; + const stockIds = [ ...new Set(items.map(i => Number(i.stock_id)).filter(Boolean)) ]; + if (stockIds.length === 0) return items; + + // stock_id 即 wms_stock_warehouse.id + // wms_receiving_detail.system_product_id 也指向 wms_stock_warehouse.id + // 所以映射关系就是 id → id,只需确认 stock_warehouse 记录存在 + const swRows = await ctx.model.StockWarehouse.findAll({ + where: { id: { [ctx.app.Sequelize.Op.in]: stockIds }, warehouse_id: warehouseId }, + attributes: [ 'id' ], + raw: true, + }); + const stockIdToSystemProductId = new Map(); + for (const row of swRows) { + stockIdToSystemProductId.set(Number(row.id), Number(row.id)); + } + const systemProductIds = [ ...new Set(stockIdToSystemProductId.values()) ]; + if (systemProductIds.length === 0) return items; + + // 批量查询收货单明细可用量 + const rows = await ctx.model.query( + `SELECT + rd.id AS receiving_detail_id, + rd.receiving_id, + rd.system_product_id, + r.receiving_number, + rd.actual_quantity, + COALESCE(SUM(erb.allocated_quantity), 0) AS allocated_quantity, + rd.actual_quantity - COALESCE(SUM(erb.allocated_quantity), 0) AS available_quantity + FROM wms_receiving_detail rd + INNER JOIN wms_receiving r ON r.id = rd.receiving_id AND r.deleted_at IS NULL + LEFT JOIN wms_entry_receiving_binding erb + ON erb.receiving_detail_id = rd.id + AND erb.status = 'committed' + AND erb.deleted_at IS NULL + WHERE rd.system_product_id IN (:systemProductIds) + AND r.status NOT IN ('completed', 'cancelled') + AND rd.storage_status IN ('none', 'partial') + GROUP BY rd.id, rd.receiving_id, rd.system_product_id, r.receiving_number, rd.actual_quantity + HAVING available_quantity > 0 + ORDER BY rd.system_product_id, available_quantity DESC`, + { replacements: { systemProductIds }, type: ctx.model.QueryTypes.SELECT } + ); + + // 按 system_product_id 分组 + const mapBySystemProductId = new Map(); + for (const row of rows) { + const spid = Number(row.system_product_id); + if (!mapBySystemProductId.has(spid)) mapBySystemProductId.set(spid, []); + mapBySystemProductId.get(spid).push({ + receiving_id: Number(row.receiving_id), + receiving_number: String(row.receiving_number || '').trim(), + receiving_detail_id: Number(row.receiving_detail_id), + actual_quantity: Number(row.actual_quantity || 0), + allocated_quantity: Number(row.allocated_quantity || 0), + available_quantity: Number(row.available_quantity || 0), + }); + } + + // 为每个 item 挂载 + return items.map(item => { + const sid = Number(item.stock_id); + const spid = stockIdToSystemProductId.get(sid) || 0; + return { + ...item, + available_receiving_details: spid > 0 ? (mapBySystemProductId.get(spid) || []) : [], + }; + }); + } + /** * 归一化作废入参中的入库单 ID 列表。 * 优先使用 ids;未传 ids 时回退到 id。 @@ -821,6 +909,463 @@ class EntryService extends Service { return await ctx.service.systems.inboundDirectLog.removeItem(data); } + /** + * 快捷直入/虚拟入库:将入库单的所有商品按明细数量全部直入到虚拟库位(space_id=2),跳过收货、质检等正常流程。 + * @param {Object} data 请求体 + * @param {number} data.id 入库单ID + * @return {Promise} code/data/message 结构 + */ + async quickInbound(data = {}) { + const { ctx, app } = this; + const orderId = Number(data.id || 0); + + if (!orderId) { + return { + code: 400, + message: 'id 必填', + data: null, + }; + } + + // 1. 校验入库单 + const entryOrder = await this.getOwnedEntryOrderById(orderId); + if (!entryOrder) { + return { + code: 404, + message: '入库单不存在或无权访问', + data: null, + }; + } + + if (entryOrder.order_status !== 'CREATED') { + if (entryOrder.order_status === 'CANCELLED') { + return { + code: 400, + message: '已作废入库单不允许快捷入库', + data: null, + }; + } + if (entryOrder.order_status === 'COMPLETED') { + return { + code: 400, + message: '入库单已完成,请勿重复提交', + data: null, + }; + } + return { + code: 400, + message: `入库单状态不允许快捷直入,当前状态:${entryOrder.order_status}`, + data: null, + }; + } + + // 2. 查询入库单所有明细 + const entryItems = await ctx.model.EntryItems.findAll({ + where: { order_id: entryOrder.id }, + }); + + if (!entryItems.length) { + return { + code: 400, + message: '请先添加入库明细', + data: null, + }; + } + + const warehouseId = entryOrder.warehouse_id; + const storeId = entryOrder.store_id; + const batchNo = entryOrder.entry_order_code; + const hardcodedSpaceId = 2; + const transaction = await ctx.model.transaction(); + + const processedStockIds = new Set(); + let totalInboundQty = 0; + + try { + // 3. 逐商品写入库存 + for (const item of entryItems) { + const stockId = item.stock_id; + if (!stockId) continue; + + const planQty = Number(item.count) || 0; + if (planQty <= 0) continue; + + const inventoryType = item.inventory_type || 'ZP'; + + // 更新入库明细的 received_quantity 为计划数量(全部入库) + await ctx.model.EntryItems.update({ + received_quantity: planQty, + }, { + where: { id: item.id }, + transaction, + }); + + // 同一 stock_id 只写一次库存 + if (processedStockIds.has(String(stockId))) continue; + processedStockIds.add(String(stockId)); + totalInboundQty += planQty; + + // 锁定并更新 StockWarehouse 总库存 + const stockRecord = await ctx.model.StockWarehouse.findOne({ + where: { id: stockId, is_valid: 'Y', deleted_at: null }, + lock: transaction.LOCK.UPDATE, + transaction, + }); + + if (stockRecord) { + const beforeQuantity = Number(stockRecord.quantity) || 0; + const beforeLockedQuantity = Number(stockRecord.locked_quantity) || 0; + + await stockRecord.increment('quantity', { by: planQty, transaction, silent: true }); + await stockRecord.reload({ transaction }); + + const afterQuantity = Number(stockRecord.quantity) || 0; + const afterLockedQuantity = Number(stockRecord.locked_quantity) || 0; + + // 写入库存流水 + await ctx.service.systems.stockTransaction.create({ + transaction_type: 'INBOUND', + warehouse_id: warehouseId, + store_id: storeId, + stock_id: stockId, + quantity: planQty, + batch_no: batchNo, + order_type: entryOrder.order_type, + order_no: entryOrder.entry_order_code, + entry_order_id: entryOrder.id, + operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), + operator_name: ctx.user?.employees_name || '', + remark: '快捷直入/虚拟入库', + before_quantity: beforeQuantity, + after_quantity: afterQuantity, + before_locked_quantity: beforeLockedQuantity, + after_locked_quantity: afterLockedQuantity, + created_at: new Date(), + }, { transaction }); + } + + // 创建/更新 Storage 库位库存(space_id 硬编码为 2) + const storageRecord = await ctx.model.Storage.findOne({ + where: { + space_id: hardcodedSpaceId, + stock_id: stockId, + batch_no: batchNo, + inventory_type: inventoryType, + is_enabled: 1, + delete_at: null, + }, + lock: transaction.LOCK.UPDATE, + transaction, + }); + + if (storageRecord) { + await ctx.model.Storage.update({ + quantity: app.Sequelize.literal(`quantity + ${planQty}`), + available_quantity: app.Sequelize.literal(`available_quantity + ${planQty}`), + entry_order_id: entryOrder.id, + inbound_time: new Date(), + inbound_order_no: entryOrder.entry_order_code, + updated_at: new Date(), + }, { + where: { id: storageRecord.id }, + transaction, + }); + } else { + await ctx.model.Storage.create({ + warehouse_id: warehouseId, + store_id: storeId, + space_id: hardcodedSpaceId, + stock_id: stockId, + batch_no: batchNo, + inventory_type: inventoryType, + quantity: planQty, + locked_quantity: 0, + available_quantity: planQty, + inbound_time: new Date(), + inbound_order_no: entryOrder.entry_order_code, + receiving_id: null, + entry_order_id: entryOrder.id, + supplier_id: null, + supplier_batch_no: null, + is_enabled: 1, + created_at: new Date(), + updated_at: new Date(), + }, { transaction }); + } + } + + // 4. 更新入库单状态为 COMPLETED + await entryOrder.update({ + order_status: 'COMPLETED', + sync_status: 'SUCCESS', + sync_message: JSON.stringify({ + completedAt: new Date(), + totalQuantity: totalInboundQty, + itemCount: processedStockIds.size, + source: 'quick_inbound', + }), + updated_at: new Date(), + }, { transaction }); + + // 记录操作日志(事务内) + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'entry_order', + businessId: entryOrder.id, + operationCode: 'QUICK_INBOUND', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: entryOrder.warehouse_id, + message: `快捷直入完成,共 ${processedStockIds.size} 种商品,总数量 ${totalInboundQty}`, + }, + transaction, + }); + + await transaction.commit(); + } catch (error) { + if (transaction && typeof transaction.rollback === 'function') { + await transaction.rollback(); + } + throw error; + } + + // 事务外:异步触发奇门/API 回传(复用 inboundDirectLog 的回传逻辑) + setImmediate(() => { + ctx.service.systems.inboundDirectLog._sendCallback(entryOrder).catch(err => { + ctx.logger.error(`[quickInbound] 回传异常 entryOrderId=${entryOrder.id}: ${err.message}`, err.stack); + }); + }); + + return { + code: 200, + message: '快捷入库完成', + data: { + id: entryOrder.id, + entry_order_code: entryOrder.entry_order_code, + order_status: 'COMPLETED', + sync_status: 'SUCCESS', + items_count: entryItems.length, + total_quantity: totalInboundQty, + }, + }; + } + + /** + * 入库单商品与收货单商品逐行对照视图。 + * 以入库单明细为主,按 stock_id ↔ system_product_id 匹配收货单明细, + * 返回匹配/未匹配/收货单多余的对照结果。 + * + * @param {Object} data 请求参数 + * @param {number} data.entry_order_id 入库单ID + * @param {number} data.receiving_id 收货单ID + * @return {Promise} code/data/message 结构 + */ + async receivingCompare(data = {}) { + const { ctx, app } = this; + const entryOrderId = Number(data.entry_order_id || 0); + const receivingId = Number(data.receiving_id || 0); + const warehouseId = ctx.user.store_id; + + if (!entryOrderId) { + return { code: 400, message: 'entry_order_id 必填', data: null }; + } + if (!receivingId) { + return { code: 400, message: 'receiving_id 必填', data: null }; + } + + // 1. 校验收货单存在性 + const receivingOrder = await ctx.model.Receiving.findOne({ + where: { + id: receivingId, + warehouse_id: warehouseId, + is_deleted: false, + }, + attributes: [ 'id', 'receiving_number', 'status', 'storage_status' ], + raw: true, + }); + if (!receivingOrder) { + return { code: 404, message: '收货单不存在或无权访问', data: null }; + } + + // 2. 校验收货单存在性(复用 getOwnedEntryOrderById) + const entryOrder = await this.getOwnedEntryOrderById(entryOrderId); + if (!entryOrder) { + return { code: 404, message: '入库单不存在或无权访问', data: null }; + } + + // 3. 查询入库单明细 + const entryItems = await ctx.model.EntryItems.findAll({ + where: { order_id: entryOrderId }, + attributes: [ 'id', 'stock_id', 'count', 'received_quantity' ], + raw: true, + }); + + // 4. 查询收货单明细 + const receivingDetails = await ctx.model.ReceivingDetail.findAll({ + where: { receiving_id: receivingId }, + attributes: [ 'id', 'system_product_id', 'actual_quantity', 'product_name' ], + raw: true, + }); + + // 5. 收集所有 stock_id,批量查询商品信息 + const entryStockIds = [ ...new Set(entryItems.map(item => Number(item.stock_id)).filter(Boolean)) ]; + const receivingSystemProductIds = [ ...new Set(receivingDetails.map(d => Number(d.system_product_id)).filter(Boolean)) ]; + + // 6. 批量查询 wms_stock_warehouse — 入库单商品(按 stock_id)和收货单商品(按 system_product_id = id) + const allStockIds = [ ...new Set([ ...entryStockIds, ...receivingSystemProductIds ]) ]; + const stockDetailMap = new Map(); + if (allStockIds.length > 0) { + const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(allStockIds, { warehouseId }); + for (const detail of stockDetails) { + stockDetailMap.set(detail.id, detail); + } + } + + // stock_id 即 wms_stock_warehouse.id,与 wms_receiving_detail.system_product_id 直接对应 + // 只需确认 stock_warehouse 记录存在即可构建映射 + const stockIdToSystemProductId = new Map(); + const systemProductIdToEntryStockIds = new Map(); + if (entryStockIds.length > 0) { + const swRows = await ctx.model.StockWarehouse.findAll({ + where: { id: { [app.Sequelize.Op.in]: entryStockIds }, warehouse_id: warehouseId }, + attributes: [ 'id' ], + raw: true, + }); + for (const row of swRows) { + const stockId = Number(row.id); + stockIdToSystemProductId.set(stockId, stockId); + if (!systemProductIdToEntryStockIds.has(stockId)) { + systemProductIdToEntryStockIds.set(stockId, []); + } + systemProductIdToEntryStockIds.get(stockId).push(stockId); + } + } + + // 7. 查询已分配量(从 wms_entry_receiving_binding) + const receivingDetailIds = receivingDetails.map(d => d.id); + const allocatedMap = new Map(); + if (receivingDetailIds.length > 0) { + const bindingRows = await ctx.model.EntryReceivingBinding.findAll({ + attributes: [ + 'receiving_detail_id', + [ app.Sequelize.fn('SUM', app.Sequelize.col('allocated_quantity')), 'total_allocated' ], + ], + where: { + receiving_detail_id: { [app.Sequelize.Op.in]: receivingDetailIds }, + status: 'committed', + deleted_at: null, + }, + group: [ 'receiving_detail_id' ], + raw: true, + }); + for (const row of bindingRows) { + allocatedMap.set(Number(row.receiving_detail_id), Number(row.total_allocated) || 0); + } + } + + // 8. 构建对照视图:以入库单明细为主 + const comparison = []; + const matchedReceivingDetailIds = new Set(); + + for (const entryItem of entryItems) { + const stockId = Number(entryItem.stock_id || 0); + const systemProductId = stockIdToSystemProductId.get(stockId) || 0; + const stockDetail = stockDetailMap.get(stockId) || null; + + // 找到同 system_product_id 的收货单明细 + const matchedReceiving = systemProductId > 0 + ? receivingDetails.filter(rd => Number(rd.system_product_id) === systemProductId) + : []; + + if (matchedReceiving.length > 0) { + // 有匹配的收货明细 + for (const rd of matchedReceiving) { + matchedReceivingDetailIds.add(rd.id); + const rdStockDetail = (rd.system_product_id != null && stockDetailMap.get(Number(rd.system_product_id))) || null; + const allocated = allocatedMap.get(Number(rd.id)) || 0; + const available = Math.max(0, (Number(rd.actual_quantity) || 0) - allocated); + comparison.push({ + entry_item_id: Number(entryItem.id), + stock_id: stockId, + warehouse_item_code: (stockDetail && stockDetail.item_code) || '', + warehouse_item_name: (stockDetail && stockDetail.item_name) || '', + warehouse_item_spec: (stockDetail && stockDetail.sku_property) || '', + entry_count: Number(entryItem.count) || 0, + entry_received: Number(entryItem.received_quantity) || 0, + receiving_detail_id: Number(rd.id), + receiving_product_code: (rdStockDetail && rdStockDetail.item_code) || '', + receiving_product_name: rd.product_name || (rdStockDetail && rdStockDetail.item_name) || '', + receiving_actual_quantity: Number(rd.actual_quantity) || 0, + receiving_allocated: allocated, + receiving_available: available, + match_status: 'matched', + }); + } + } else { + // 入库商品在收货单中不存在 + comparison.push({ + entry_item_id: Number(entryItem.id), + stock_id: stockId, + warehouse_item_code: (stockDetail && stockDetail.item_code) || '', + warehouse_item_name: (stockDetail && stockDetail.item_name) || '', + warehouse_item_spec: (stockDetail && stockDetail.sku_property) || '', + entry_count: Number(entryItem.count) || 0, + entry_received: Number(entryItem.received_quantity) || 0, + receiving_detail_id: null, + receiving_product_code: null, + receiving_product_name: null, + receiving_actual_quantity: null, + receiving_allocated: null, + receiving_available: null, + match_status: 'entry_only', + }); + } + } + + // 9. 收货单中多余的商品(未被任何入库单明细匹配的) + const receivingOnly = []; + for (const rd of receivingDetails) { + if (!matchedReceivingDetailIds.has(Number(rd.id))) { + const rdStockDetail = (rd.system_product_id != null && stockDetailMap.get(Number(rd.system_product_id))) || null; + const allocated = allocatedMap.get(Number(rd.id)) || 0; + const available = Math.max(0, (Number(rd.actual_quantity) || 0) - allocated); + receivingOnly.push({ + receiving_detail_id: Number(rd.id), + receiving_product_code: (rdStockDetail && rdStockDetail.item_code) || '', + receiving_product_name: rd.product_name || (rdStockDetail && rdStockDetail.item_name) || '', + receiving_actual_quantity: Number(rd.actual_quantity) || 0, + receiving_allocated: allocated, + receiving_available: available, + }); + } + } + + // 10. 汇总 + const matchedItems = comparison.filter(c => c.match_status === 'matched').length; + const entryOnlyItems = comparison.filter(c => c.match_status === 'entry_only').length; + + return { + code: 200, + message: '查询成功', + data: { + entry_order_id: entryOrderId, + entry_order_code: entryOrder.entry_order_code, + receiving_id: receivingId, + receiving_number: receivingOrder.receiving_number, + comparison, + receiving_only: receivingOnly, + summary: { + total_entry_items: entryItems.length, + matched_items: matchedItems, + entry_only_items: entryOnlyItems, + receiving_only_items: receivingOnly.length, + }, + }, + }; + } + } module.exports = EntryService; diff --git a/methods/changes/2026-06-24-add-bind-receiving-details.json b/methods/changes/2026-06-24-add-bind-receiving-details.json new file mode 100644 index 0000000..37a9170 --- /dev/null +++ b/methods/changes/2026-06-24-add-bind-receiving-details.json @@ -0,0 +1,7 @@ +{ + "date": "2026-06-24", + "type": "addition", + "method": "storage.entry.bindReceivingDetails", + "summary": "新增批量绑定入库单明细与收货单明细接口,支持明细级数量分配与部分成功", + "related": ["storage.entry.get 追加 available_receiving_details 字段"] +} diff --git a/methods/changes/2026-06-24-deprecate-manual-match-entry-order.json b/methods/changes/2026-06-24-deprecate-manual-match-entry-order.json new file mode 100644 index 0000000..64c2dc7 --- /dev/null +++ b/methods/changes/2026-06-24-deprecate-manual-match-entry-order.json @@ -0,0 +1,7 @@ +{ + "date": "2026-06-24", + "type": "deprecation", + "method": "storage.receiving.manualMatchEntryOrder", + "summary": "废弃手动匹配入库单收货单接口,由 storage.entry.bindReceivingDetails 替代", + "migration": "使用 storage.entry.get(含 available_receiving_details 元数据)加载可匹配的收货单明细,然后调用 storage.entry.bindReceivingDetails 批量提交绑定" +} diff --git a/methods/changes/system.json b/methods/changes/system.json index 6aaf801..1ac129a 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -4099,5 +4099,105 @@ ], "type": "updated", "module": "storage.entry" + }, + { + "version": "2026.06.24-system-01", + "date": "2026-06-24", + "summary": "新增批量绑定入库单明细与收货单明细接口 storage.entry.bindReceivingDetails,支持明细级数量分配与部分成功", + "methods": [ + "storage.entry.bindReceivingDetails" + ], + "notes": [ + "新增 storage.entry.bindReceivingDetails:批量绑定入库单明细与收货单明细,支持明细级数量分配与部分成功", + "storage.entry.get 追加 available_receiving_details 字段加载可匹配的收货单明细" + ], + "type": "addition" + }, + { + "version": "2026.06.24-system-02", + "date": "2026-06-24", + "summary": "storage.entry.bindReceivingDetails:response.failed 字段从简单 reason 描述升级为结构化错误返回(含 error_code、message、detail);同步更新 400 错误说明", + "methods": [ + "storage.entry.bindReceivingDetails" + ], + "notes": [ + "response.failed 新增 items 定义,每项含 entry_item_id、receiving_detail_id、allocated_quantity、error_code、message、detail", + "error_code 枚举:ENTRY_ITEM_NOT_FOUND、STOCK_NOT_FOUND、RECEIVING_DETAIL_MISMATCH、RECEIVING_DETAIL_NOT_FOUND、INSUFFICIENT_AVAILABLE_QUANTITY、ENTRY_ORDER_STATUS_INVALID", + "400 错误说明更新:入库单状态不允许绑定时,所有 bindings 均返回 failed 且 error_code 为 ENTRY_ORDER_STATUS_INVALID" + ], + "type": "updated" + }, + { + "version": "2026.06.24-system-03", + "date": "2026-06-24", + "summary": "新增 storage.entry.quickInbound 快捷直入/虚拟入库接口", + "methods": [ + "storage.entry.quickInbound" + ], + "notes": [ + "新增 quickInbound 方法:入库单所有商品按明细数量一键直入虚拟库位(space_id=2),跳过收货/质检流程", + "支持状态:CREATED、PENDING 状态的入库单可执行", + "拒绝状态:CANCELLED(已作废)、COMPLETED(已完成)", + "事务内操作:更新入库明细收货量、累加库存总量、写入库存流水、写入虚拟库位库存、变更入库单状态为 COMPLETED", + "事务外异步回传奇门/API" + ], + "type": "addition" + }, + { + "version": "2026.06.24-system-04", + "date": "2026-06-24", + "summary": "收窄 storage.entry.quickInbound 状态约束:仅允许 CREATED 状态执行快捷直入", + "methods": [ + "storage.entry.quickInbound" + ], + "notes": [ + "收窄状态约束:仅允许 CREATED 状态执行快捷直入,PENDING 状态不再允许" + ], + "type": "updated" + }, + { + "version": "2026.06.24-system-05", + "date": "2026-06-24", + "summary": "修正 storage.entry.quickInbound errors[4] message 以匹配代码实现:改为动态状态描述", + "methods": [ + "storage.entry.quickInbound" + ], + "notes": [ + "errors[4].message 从「入库单状态不允许快捷直入(仅支持CREATED状态)」改为「入库单状态不允许快捷直入,当前状态:非CREATED(如PENDING等)」,反映代码中 `${entryOrder.order_status}` 动态模板特性" + ], + "type": "updated" + }, + { + "version": "2026.06.24-system-06", + "date": "2026-06-24", + "summary": "新增入库单与收货单商品对照预览接口", + "methods": [ + "storage.entry.receivingCompare" + ], + "notes": [ + "新增 storage.entry.receivingCompare 方法:给定入库单ID和收货单ID,返回入库商品与收货商品的逐行对照视图。", + "comparison 列表中每项含 match_status(matched/entry_only),以及入库侧和收货侧的商品与数量信息。", + "receiving_only 列表包含仅存在于收货单中的商品明细。", + "summary 提供 total_entry_items、matched_items、entry_only_items、receiving_only_items 汇总统计。", + "纯只读接口,不产生任何数据写入或状态变更。" + ], + "type": "addition" + }, + { + "version": "2026.06.24-system-07", + "date": "2026-06-24", + "summary": "setting.warehouse 模块新增 7 个发件人信息字段到 subject_config", + "methods": [ + "setting.warehouse.getSettings", + "setting.warehouse.saveSettings" + ], + "notes": [ + "在 getSettings 的 response 中新增 subject_config.sender_name(发件人姓名)、sender_tel(发件人电话)、province_name(省份)、city_name(城市)、district_name(区/县)、town_name(镇/街道)、address(详细地址)共 7 个字段,均为可选字符串,默认空。", + "在 saveSettings 的 params 中新增对应的 7 个入参字段,source 为 body.subject_config,均为可选字符串,默认空,并标注 maxLength。", + "字段 key 与 store_warehouse.policy_config 中发件人字段命名完全一致,统一仓库级发件人默认值配置。", + "getFieldMeta 接口无需修改文档——其返回的字段元信息由 WAREHOUSE_SETTING_FIELDS 定义在运行时自动生成,新增字段会随代码自动纳入返回列表。" + ], + "type": "updated", + "module": "setting.warehouse" } ] diff --git a/methods/system.json b/methods/system.json index 8127801..7581b77 100644 --- a/methods/system.json +++ b/methods/system.json @@ -2,7 +2,7 @@ "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", "version": "0.3.7", - "updatedAt": "2026-06-23", + "updatedAt": "2026-06-24", "headers": [ { "name": "platform", @@ -12690,6 +12690,48 @@ "type": "boolean", "required": true, "description": "是否要求已拣货(pick_status=fin),默认 true" + }, + { + "name": "subject_config.sender_name", + "type": "string", + "required": false, + "description": "仓库默认发件人姓名,默认空字符串" + }, + { + "name": "subject_config.sender_tel", + "type": "string", + "required": false, + "description": "仓库默认发件人联系电话,默认空字符串" + }, + { + "name": "subject_config.province_name", + "type": "string", + "required": false, + "description": "仓库默认发件省份,默认空字符串" + }, + { + "name": "subject_config.city_name", + "type": "string", + "required": false, + "description": "仓库默认发件城市,默认空字符串" + }, + { + "name": "subject_config.district_name", + "type": "string", + "required": false, + "description": "仓库默认发件区/县,默认空字符串" + }, + { + "name": "subject_config.town_name", + "type": "string", + "required": false, + "description": "仓库默认发件镇/街道,默认空字符串" + }, + { + "name": "subject_config.address", + "type": "string", + "required": false, + "description": "仓库默认发件详细地址,默认空字符串" } ], "errors": [ @@ -12884,6 +12926,55 @@ "required": false, "source": "body.subject_config.auto_outbound_rules", "description": "是否要求已拣货(pick_status=fin),默认 true" + }, + { + "name": "subject_config.sender_name", + "type": "string", + "required": false, + "source": "body.subject_config", + "description": "仓库默认发件人姓名,默认空字符串,最大长度 50" + }, + { + "name": "subject_config.sender_tel", + "type": "string", + "required": false, + "source": "body.subject_config", + "description": "仓库默认发件人联系电话,默认空字符串,最大长度 20" + }, + { + "name": "subject_config.province_name", + "type": "string", + "required": false, + "source": "body.subject_config", + "description": "仓库默认发件省份,默认空字符串,最大长度 50" + }, + { + "name": "subject_config.city_name", + "type": "string", + "required": false, + "source": "body.subject_config", + "description": "仓库默认发件城市,默认空字符串,最大长度 50" + }, + { + "name": "subject_config.district_name", + "type": "string", + "required": false, + "source": "body.subject_config", + "description": "仓库默认发件区/县,默认空字符串,最大长度 50" + }, + { + "name": "subject_config.town_name", + "type": "string", + "required": false, + "source": "body.subject_config", + "description": "仓库默认发件镇/街道,默认空字符串,最大长度 50" + }, + { + "name": "subject_config.address", + "type": "string", + "required": false, + "source": "body.subject_config", + "description": "仓库默认发件详细地址,默认空字符串,最大长度 200" } ], "response": [ @@ -18795,176 +18886,11 @@ "完成收货时会发送通知:通知 payload 或 metadata 将在每条明细中携带 box_remainder(箱内剩余数量/零散件数,number)与 box_weight(实测箱重,number,单位同系统重量,例如 kg)。新增字段为可选,旧客户端可忽略。" ], "errors": [] - }, - { - "method": "storage.receiving.manualMatchEntryOrder", - "description": "手动匹配入库单与收货单。传入收货单ID和入库单ID,复用异步匹配服务的明细对比和回传逻辑,同步返回匹配结果(含 matchType、comparisonResult、callbackSent、partialStorageMarked 等)。", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "receivingId", - "type": "number", - "required": true, - "source": "body", - "description": "收货单 ID" - }, - { - "name": "entryOrderId", - "type": "number", - "required": true, - "source": "body", - "description": "入库单 ID" - } - ], - "response": [ - { - "name": "matchType", - "type": "string", - "required": true, - "description": "匹配类型枚举:full_match(SKU+数量完全一致)/ receiving_covers_entry(收货单覆盖入库单,触发回传+标记部分入库)/ entry_exceeds_receiving(入库单超出收货单,不触发回传)/ no_match(SKU无交集,不触发回传)" - }, - { - "name": "comparisonResult", - "type": "object", - "required": true, - "description": "明细对比结果对象", - "children": [ - { - "name": "type", - "type": "string", - "required": true, - "description": "匹配类型(同 matchType)" - }, - { - "name": "matchedDetails", - "type": "array", - "required": true, - "description": "匹配明细列表,每项含 detailId、system_product_id、actual_quantity、stored_quantity、entryCount、overage" - } - ] - }, - { - "name": "callbackSent", - "type": "boolean", - "required": true, - "description": "是否已发送回传(full_match / receiving_covers_entry 时为 true)" - }, - { - "name": "callbackResult", - "type": "object|null", - "required": true, - "description": "回传结果对象(未发送时为 null);成功时含 success、sourceType(QM/API)、detail 字段" - }, - { - "name": "partialStorageMarked", - "type": "boolean", - "required": true, - "description": "是否已标记部分入库(仅 receiving_covers_entry 时为 true)" - }, - { - "name": "entryOrder", - "type": "object", - "required": true, - "description": "入库单摘要信息", - "children": [ - { - "name": "id", - "type": "number", - "required": true, - "description": "入库单 ID" - }, - { - "name": "entry_order_code", - "type": "string", - "required": true, - "description": "入库单号" - }, - { - "name": "source_type", - "type": "string", - "required": true, - "description": "来源类型(QM/API)" - }, - { - "name": "warehouse_id", - "type": "number", - "required": true, - "description": "仓库 ID" - }, - { - "name": "status", - "type": "string", - "required": true, - "description": "入库单状态" - } - ] - }, - { - "name": "receivingOrder", - "type": "object", - "required": true, - "description": "收货单摘要信息", - "children": [ - { - "name": "id", - "type": "number", - "required": true, - "description": "收货单 ID" - }, - { - "name": "receiving_number", - "type": "string", - "required": true, - "description": "收货单号" - }, - { - "name": "status", - "type": "string", - "required": true, - "description": "收货单状态" - }, - { - "name": "storage_status", - "type": "string", - "required": true, - "description": "入库状态(如 un_stored)" - } - ] - } - ], - "errors": [ - { - "code": 400, - "message": "入库单不存在:{entryOrderId}" - }, - { - "code": 400, - "message": "收货单不存在:{receivingId}" - }, - { - "code": 400, - "message": "入库单仓库({a})与收货单仓库({b})不一致" - } - ], - "notes": [ - "matchType 为 full_match 或 receiving_covers_entry 时触发回传(调用 _sendCallback),receiving_covers_entry 额外调用 _markReceivingPartialStorage 标记部分入库", - "matchType 为 entry_exceeds_receiving 或 no_match 时不触发回传,仅返回对比结果", - "不检查特定 API 权限,登录用户即可调用(_noNeedAuth=manualMatchEntryOrder)" - ] } ] }, { - "groupName": "入库单管理模块", + "groupName": "入库模块", "module": "storage.entry", "list": [ { @@ -19628,6 +19554,266 @@ "message": "入库记录不存在 / 关联入库单不存在或无权访问" } ] + }, + { + "method": "storage.entry.bindReceivingDetails", + "description": "批量绑定入库单明细与收货单明细。绑定只能使用关联收货单中匹配的 stock_id(通过 system_product_id 映射),且不能超出收货单明细的可用数量(actual_quantity - 已 committed 的 allocated_quantity)。支持部分成功:校验通过的写入绑定,不通过的在 failed 列表中返回原因。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "entry_order_id", + "type": "number", + "required": true, + "source": "body", + "description": "入库单ID" + }, + { + "name": "bindings", + "type": "array", + "required": true, + "source": "body", + "description": "绑定列表,每项包含 entry_item_id、receiving_detail_id、allocated_quantity" + } + ], + "response": [ + { + "name": "success", + "type": "array", + "required": true, + "description": "成功绑定的列表,每项包含 entry_item_id、receiving_detail_id、allocated_quantity" + }, + { + "name": "failed", + "type": "array", + "required": true, + "description": "绑定失败的列表,每项包含 entry_item_id、receiving_detail_id、allocated_quantity、error_code、message、detail", + "items": { + "type": "object", + "properties": { + "entry_item_id": { + "type": "number", + "description": "入库单明细ID" + }, + "receiving_detail_id": { + "type": "number", + "description": "收货单明细ID" + }, + "allocated_quantity": { + "type": "number", + "description": "请求分配的数量" + }, + "error_code": { + "type": "string", + "description": "错误码,可能值:ENTRY_ITEM_NOT_FOUND(入库明细不存在)、STOCK_NOT_FOUND(商品不存在)、RECEIVING_DETAIL_MISMATCH(收货明细与入库商品不匹配)、RECEIVING_DETAIL_NOT_FOUND(收货明细不存在)、INSUFFICIENT_AVAILABLE_QUANTITY(超出可用数量)、ENTRY_ORDER_STATUS_INVALID(入库单状态不允许绑定)" + }, + "message": { + "type": "string", + "description": "中文错误描述,可直接展示给用户" + }, + "detail": { + "type": "object", + "description": "错误上下文数据,根据 error_code 不同包含不同字段。如 INSUFFICIENT_AVAILABLE_QUANTITY 时包含 available_quantity 和 requested_quantity" + } + } + } + }, + { + "name": "success_count", + "type": "number", + "required": true, + "description": "成功数量" + }, + { + "name": "failed_count", + "type": "number", + "required": true, + "description": "失败数量" + } + ], + "errors": [ + { + "code": 400, + "message": "参数校验失败:entry_order_id 必填 / bindings 必填且为非空数组 / 入库单状态不允许绑定时,所有 bindings 均返回 failed 且 error_code 为 ENTRY_ORDER_STATUS_INVALID" + }, + { + "code": 404, + "message": "入库单不存在或无权访问" + } + ] + }, + { + "method": "storage.entry.quickInbound", + "description": "快捷直入(虚拟入库):将入库单所有商品按明细数量一键直入到虚拟库位(space_id=2),跳过收货/质检流程,入库单状态变为COMPLETED。仅支持 CREATED 状态的入库单;CANCELLED(已作废)、COMPLETED(已完成)、PENDING 等其他状态均拒绝操作。事务内操作:更新入库明细收货量、累加库存总量、写入库存流水、写入虚拟库位库存、变更入库单状态为 COMPLETED。事务外异步回传奇门/API。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "入库单ID" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "入库单ID" + }, + { + "name": "entry_order_code", + "type": "string", + "required": true, + "description": "入库单号" + }, + { + "name": "order_status", + "type": "string", + "required": true, + "description": "入库单状态(COMPLETED)" + }, + { + "name": "sync_status", + "type": "string", + "required": true, + "description": "同步状态(SUCCESS)" + }, + { + "name": "items_count", + "type": "number", + "required": true, + "description": "入库明细条目数" + }, + { + "name": "total_quantity", + "type": "number", + "required": true, + "description": "入库总数量" + } + ], + "errors": [ + { + "code": 400, + "message": "id 必填" + }, + { + "code": 404, + "message": "入库单不存在或无权访问" + }, + { + "code": 400, + "message": "已作废入库单不允许快捷入库" + }, + { + "code": 400, + "message": "入库单已完成,请勿重复提交" + }, + { + "code": 400, + "message": "入库单状态不允许快捷直入,当前状态:非CREATED(如PENDING等)" + }, + { + "code": 400, + "message": "请先添加入库明细" + } + ] + }, + { + "method": "storage.entry.receivingCompare", + "description": "入库单与收货单商品对照预览:给定入库单ID和收货单ID,返回入库商品与收货商品的逐行对照视图,含匹配状态(matched/entry_only)和汇总统计。纯只读接口。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "entry_order_id", + "type": "number", + "required": true, + "source": "body", + "description": "入库单ID" + }, + { + "name": "receiving_id", + "type": "number", + "required": true, + "source": "body", + "description": "收货单ID" + } + ], + "response": [ + { + "name": "entry_order_id", + "type": "number", + "required": true, + "description": "入库单ID" + }, + { + "name": "entry_order_code", + "type": "string", + "required": true, + "description": "入库单号" + }, + { + "name": "receiving_id", + "type": "number", + "required": true, + "description": "收货单ID" + }, + { + "name": "receiving_number", + "type": "string", + "required": true, + "description": "收货单号" + }, + { + "name": "comparison", + "type": "array", + "required": true, + "description": "逐行对照列表" + }, + { + "name": "receiving_only", + "type": "array", + "required": true, + "description": "仅收货单有的商品列表" + }, + { + "name": "summary", + "type": "object", + "required": true, + "description": "汇总统计" + } + ], + "errors": [ + { + "code": 400, + "message": "entry_order_id 必填" + }, + { + "code": 400, + "message": "receiving_id 必填" + }, + { + "code": 404, + "message": "入库单不存在或无权访问" + }, + { + "code": 404, + "message": "收货单不存在" + } + ] } ] }, From 5ef99e3bed34c2cd844c108bc3bb4edaf01377c7 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Wed, 1 Jul 2026 14:00:59 +0800 Subject: [PATCH 077/550] 1 --- .github/agents/开发.agent.md | 1 + .github/agents/数据库.agent.md | 32 +- .github/agents/调度.agent.md | 2 +- 3 | 0 app/lib/express_print_payload_builder.js | 109 +- app/model/entry_order_receiving.js | 6 +- app/model/order_stockout.js | 261 ++++ app/model/order_stockout_items.js | 145 ++ app/model/platform.js | 2 +- app/model/receiving.js | 4 +- app/model/receiving_detail.js | 4 +- app/service/apiMethods/test.js | 4 - app/service/im.js | 2 +- app/service/main.js | 4 +- app/service/openapi/callback.js | 7 +- app/service/openapiMethods/callback.js | 2 +- app/service/openapiMethods/deliveryorder.js | 2 +- app/service/openapiMethods/order.js | 20 + app/service/qimenMethods/order.js | 40 + app/service/qimenMethods/stockout.js | 236 ++- app/service/systemMethods/dashboard.js | 2 +- app/service/systemMethods/index.js | 14 +- app/service/systemMethods/order/base.js | 67 +- .../systemMethods/order/pendingOrder.js | 63 + .../systemMethods/order/recheckOrder.js | 22 +- app/service/systemMethods/order/wave.js | 4 +- app/service/systemMethods/pick.js | 43 +- app/service/systemMethods/print.js | 198 +-- .../systemMethods/storage/direct_inbound.js | 8 +- app/service/systemMethods/storage/entry.js | 146 +- .../systemMethods/storage/inventory.js | 16 +- .../systemMethods/storage/receiving.js | 30 +- app/service/systems/delivery_order.js | 6 +- app/service/systems/entry_order.js | 316 +--- app/service/systems/express.js | 13 - app/service/systems/express_platform.js | 195 +-- app/service/systems/inbound_direct_log.js | 1380 ++++++++++++----- app/service/systems/operation_log.js | 13 + app/service/systems/order_async.js | 26 +- app/service/systems/order_auto_outbound.js | 2 + app/service/systems/order_print.js | 12 +- .../systems/order_storage_allocation.js | 108 +- app/service/systems/pick.js | 1 + app/service/systems/print/printData.js | 5 - app/service/systems/receiving_entry_match.js | 523 +++++-- app/service/systems/shops.js | 3 +- app/service/systems/stock_warehouse.js | 19 +- app/service/systems/storage/entry.js | 1091 +++++++++---- app/service/systems/storage/inventory.js | 337 +++- app/service/systems/storage/receiving.js | 303 +++- config/config.default.js | 3 +- .../20260629-add-waiting-storage-status.js | 76 + ...0260630160000-create-wms-order-stockout.js | 309 ++++ docs/order-workbench-list-api.md | 1 + order_todo.md => docs/order_todo.md | 0 docs/storage-receiving-api.md | 2 +- ...2026-06-24-add-bind-receiving-details.json | 7 - ...24-deprecate-manual-match-entry-order.json | 7 - methods/changes/2026.05.08-system-06.json | 16 - methods/changes/2026.05.13-system-01.json | 17 - methods/changes/2026.05.20-system-01.json | 19 - methods/changes/2026.05.20-system-03.json | 18 - methods/changes/2026.05.28-system-01.json | 19 - methods/changes/2026.06.16-system-01.json | 17 - methods/changes/2026.06.16-system-02.json | 16 - methods/changes/2026.06.16-system-03.json | 16 - methods/changes/2026.06.16-system-04.json | 16 - .../openapi-2026-06-17-entryorder.json | 20 - methods/changes/qimen.json | 67 +- methods/changes/system.json | 448 ++++++ methods/qimen.json | 381 ++++- methods/system.json | 1266 ++++++++++++--- skills/entry-order-test-guide.md | 449 ++++++ temp_check_prod_migrations.js | 71 - temp_storage_entry_old.js | Bin 52592 -> 0 bytes temp_systemMethods_storage_entry_old.js | Bin 4822 -> 0 bytes .../systems/order_storage_allocation.test.js | 221 +++ 77 files changed, 7211 insertions(+), 2120 deletions(-) delete mode 100644 3 create mode 100644 app/model/order_stockout.js create mode 100644 app/model/order_stockout_items.js create mode 100644 database/migrations/20260629-add-waiting-storage-status.js create mode 100644 database/migrations/20260630160000-create-wms-order-stockout.js rename order_todo.md => docs/order_todo.md (100%) delete mode 100644 methods/changes/2026-06-24-add-bind-receiving-details.json delete mode 100644 methods/changes/2026-06-24-deprecate-manual-match-entry-order.json delete mode 100644 methods/changes/2026.05.08-system-06.json delete mode 100644 methods/changes/2026.05.13-system-01.json delete mode 100644 methods/changes/2026.05.20-system-01.json delete mode 100644 methods/changes/2026.05.20-system-03.json delete mode 100644 methods/changes/2026.05.28-system-01.json delete mode 100644 methods/changes/2026.06.16-system-01.json delete mode 100644 methods/changes/2026.06.16-system-02.json delete mode 100644 methods/changes/2026.06.16-system-03.json delete mode 100644 methods/changes/2026.06.16-system-04.json delete mode 100644 methods/changes/openapi-2026-06-17-entryorder.json create mode 100644 skills/entry-order-test-guide.md delete mode 100644 temp_check_prod_migrations.js delete mode 100644 temp_storage_entry_old.js delete mode 100644 temp_systemMethods_storage_entry_old.js diff --git a/.github/agents/开发.agent.md b/.github/agents/开发.agent.md index 37edf55..2b11c3c 100644 --- a/.github/agents/开发.agent.md +++ b/.github/agents/开发.agent.md @@ -167,6 +167,7 @@ model: GPT-5.3-Codex (copilot) 10. **禁止method入口直接调用model层**,必须先调用service层,保持分层职责的清晰和一致 11. **所有编码风格必须要通过ESLint检查**,禁止任何 ESLint 错误或警告存在于提交的代码中 12. **禁止修改底层公共代码来“顺手解决问题”**,如需要改 `app.js`、`app/extend/application.js`、`app/service/main.js` 等公共能力入口,必须先评估改动影响范围,并优先考虑在业务层做适配或扩展,避免对全局能力造成不确定风险,如确实需要改公共代码,必须先驳回到调度 agent 升级给专家 agent 进行兜底处理,禁止直接改公共代码后再评估风险的流程 +13. system块的methods禁止入参warehouse_id,必须由服务端从当前上下文自动注入,前端无需传递。 ## 关键定位地图 diff --git a/.github/agents/数据库.agent.md b/.github/agents/数据库.agent.md index 8b451ef..a050a04 100644 --- a/.github/agents/数据库.agent.md +++ b/.github/agents/数据库.agent.md @@ -1,4 +1,4 @@ ---- +--- name: wms-db-agent description: "Use when the user asks about 数据库、查数据、SQL、MySQL、库表定位、字段含义、索引建议、接口数据排查、script/db-query.ps1、wms/ye4s client。专用于 WMS 数据库查询与排障。" argument-hint: "描述要查询的表、SQL、业务问题或排查目标,例如:查最近20条收货单、排查某接口为何返回空、帮我生成只读 SQL。" @@ -46,6 +46,36 @@ model : DeepSeek V4 Pro (deepseek) - 所有回复必须以 `[DB]` 开头 - 优先给结论、关键字段和下一步建议 + +## 环境路由规则(⚠️ 必读) + +**每次查询必须明确标注是开发环境还是生产环境,禁止混淆!** + +### 查询方式速查 + +| 环境 | 迁移状态查询 | 数据查询 | +|------|------------|---------| +| **开发环境** | `npx sequelize-cli db:migrate:status` | `powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -Query "..." -AsTable` | +| **生产环境** | `$env:NODE_ENV='production'; npx sequelize-cli db:migrate:status --env production` | SSH+mysql 或 `$env:NODE_ENV='production'; npx sequelize-cli ... --env production` | + +- 开发环境:`config/config.local.js` → `mysql.clients.wms` +- 生产环境:`config/config.default.js` → `config.sequelize` + +### 🔴 红线 + +1. **绝对禁止**:用不加 `--env production` 的命令查询,然后声称是生产环境。`script/db-query.ps1` 永远是开发环境! +2. 每次返回结果第一行必须标注环境:`[DB] 开发环境 (config.local.js)` 或 `[DB] 生产环境 (config.default.js)` +3. 查询迁移状态时必须**两边都查**做对比 +4. 若用户提到"生产"二字,必须使用生产环境命令 + +### 当前环境差异(2026-06-25) + +| 项目 | 开发环境 | 生产环境 | +|------|---------|---------| +| SequelizeMeta 记录数 | 127+ | 123 | +| 最新迁移 | `20260623140000` | `20260622110000` | +| 缺失迁移 | 无 | 4条 | + ## 常用命令模板 ### 1) 当前连接库自检 diff --git a/.github/agents/调度.agent.md b/.github/agents/调度.agent.md index 71f750c..02ad16b 100644 --- a/.github/agents/调度.agent.md +++ b/.github/agents/调度.agent.md @@ -17,7 +17,7 @@ model: DeepSeek V4 Pro (deepseek) - 将子任务委派给最合适的专属 agent - 等待各子任务返回结果,汇总后给出最终结论 - **不深入专属 agent 的内部技术细节**,只关注其输入、输出和完成状态 - +- 本项目无需重启, 也不需要你直接修改代码、数据库或 Redis;所有操作都必须通过专属 agent 执行 ## 适用范围 以下场景优先使用本 Agent: diff --git a/3 b/3 deleted file mode 100644 index e69de29..0000000 diff --git a/app/lib/express_print_payload_builder.js b/app/lib/express_print_payload_builder.js index e630ac8..9a5e2ac 100644 --- a/app/lib/express_print_payload_builder.js +++ b/app/lib/express_print_payload_builder.js @@ -132,7 +132,7 @@ class ExpressPrintPayloadBuilder { } if (normalizedPlatform === 'sph') { - this.applySphTaskDynamicFields(payload, orders); + payload.taskList = this.buildTaskListFromOrders(orders, idGenerator); } else { if (!isPlainObject(payload.task)) { payload.task = {}; @@ -170,6 +170,28 @@ class ExpressPrintPayloadBuilder { }); } + /** + * 将 orders 映射为 SPH taskList 项。 + * SPH 的 task item 结构(taskID / printInfo / customInfo / extendData 等)与通用 document 结构不兼容, + * 因此需要独立的构建方法,但处理模式与 buildDocumentsFromOrders 一致: + * 遍历 orders → deepClone → 分配唯一 ID → 放入数组。 + * + * @param {Array} orders 订单数组,每个元素直接是 SPH task item 对象。 + * @param {RequestScopedPrintIdGenerator} idGenerator 请求内 ID 生成器。 + * @return {Array} taskList 数组。 + */ + buildTaskListFromOrders(orders, idGenerator) { + const taskList = []; + for (const order of orders) { + if (order && typeof order === 'object' && !Array.isArray(order)) { + const taskItem = deepClone(order); + taskItem.taskID = idGenerator.nextTaskId(); + taskList.push(taskItem); + } + } + return taskList; + } + /** * 将 orders 映射为 documents。 * @param {Array} orders 订单数组。 @@ -188,91 +210,6 @@ class ExpressPrintPayloadBuilder { }); } - /** - * 将 SPH 订单中的动态业务字段回填到模板 taskList[0]。 - * - * 仅覆盖动态字段,避免改写模板固定结构。 - * - * @param {Object} payload 打印请求 payload。 - * @param {Array} orders 外部传入的订单打印数据数组。 - */ - applySphTaskDynamicFields(payload, orders) { - if (!Array.isArray(payload.taskList) || !isPlainObject(payload.taskList[0])) { - return; - } - - const sourceTask = this.resolveSphTaskFromOrders(orders); - if (!isPlainObject(sourceTask)) { - return; - } - - const targetTask = payload.taskList[0]; - const dynamicFields = [ - 'printInfo', - 'printNum', - 'splitControl', - 'showDeliveryLogo', - 'customInfo', - 'extendData', - 'taskID', - ]; - - dynamicFields.forEach(field => { - if (Object.prototype.hasOwnProperty.call(sourceTask, field)) { - targetTask[field] = deepClone(sourceTask[field]); - } - }); - } - - /** - * 从首个订单提取 SPH 动态任务数据。 - * - * 优先读取标准 taskList[0];若上游直接传 task 结构(printInfo/printNum 等)也兼容。 - * - * @param {Array} orders 外部传入的订单打印数据数组。 - * @return {Object|null} SPH 动态任务对象。 - */ - resolveSphTaskFromOrders(orders) { - if (!Array.isArray(orders) || orders.length === 0) { - return null; - } - - const firstOrder = isPlainObject(orders[0]) ? orders[0] : {}; - const candidates = []; - if (isPlainObject(firstOrder.print_data)) { - candidates.push(firstOrder.print_data); - } - if (isPlainObject(firstOrder)) { - candidates.push(firstOrder); - } - - const sphDynamicFields = [ - 'printInfo', - 'printNum', - 'splitControl', - 'showDeliveryLogo', - 'customInfo', - 'extendData', - 'taskID', - ]; - - for (const candidate of candidates) { - if (Array.isArray(candidate.taskList) && isPlainObject(candidate.taskList[0])) { - return candidate.taskList[0]; - } - - if (isPlainObject(candidate.taskList)) { - return candidate.taskList; - } - - if (sphDynamicFields.some(field => Object.prototype.hasOwnProperty.call(candidate, field))) { - return candidate; - } - } - - return null; - } - /** * 解析单个订单对应的 document。 * @param {Object} order 订单对象。 diff --git a/app/model/entry_order_receiving.js b/app/model/entry_order_receiving.js index fd823ad..2100143 100644 --- a/app/model/entry_order_receiving.js +++ b/app/model/entry_order_receiving.js @@ -41,16 +41,16 @@ module.exports = app => { indexes: [ { name: 'idx_entry_order_id', - fields: ['entry_order_id'], + fields: [ 'entry_order_id' ], }, { name: 'idx_receiving_id', - fields: ['receiving_id'], + fields: [ 'receiving_id' ], }, { name: 'uk_entry_order_receiving', unique: true, - fields: ['entry_order_id', 'receiving_id'], + fields: [ 'entry_order_id', 'receiving_id' ], }, ], }); diff --git a/app/model/order_stockout.js b/app/model/order_stockout.js new file mode 100644 index 0000000..601f832 --- /dev/null +++ b/app/model/order_stockout.js @@ -0,0 +1,261 @@ +'use strict'; + +/** + * 出库单主表 Model。 + * + * 对应数据库表 `wms_order_stockout`,存储奇门 stockout.create 接口下发的出库单信息。 + * + * 业务类型枚举值: + * - JYCK:一般交易出库 + * - HHCK:换货出库 + * - BFCK:补发出库 + * - QTCK:其他出库 + * @param {import('egg').Application} app - Egg 应用实例 + */ +module.exports = app => { + const { STRING, INTEGER, BIGINT, ENUM, TEXT, TINYINT, DATE, JSON: JSON_TYPE } = app.Sequelize; + + const OrderStockout = app.model.define('wms_order_stockout', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键ID', + }, + stockout_order_code: { + type: STRING(50), + allowNull: false, + comment: '出库单号(对应奇门 deliveryOrderCode)', + validate: { + notEmpty: true, + }, + }, + order_type: { + type: STRING(50), + allowNull: false, + comment: '业务类型(JYCK一般交易出库/HHCK换货出库/BFCK补发出库/QTCK其他出库等)', + validate: { + notEmpty: true, + }, + }, + total_order_lines: { + type: INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '单据总行数', + }, + order_create_time: { + type: DATE, + allowNull: true, + comment: '订单创建时间(对应奇门 createTime)', + }, + source_type: { + type: ENUM('WMS', 'API', 'QM'), + allowNull: false, + defaultValue: 'QM', + comment: '来源类型', + }, + order_status: { + type: ENUM('CREATING', 'CREATED', 'PENDING', 'COMPLETED', 'CANCELLED'), + allowNull: false, + defaultValue: 'CREATED', + comment: '订单状态:CREATING=创建中, CREATED=已创建待审核, PENDING=已审核, COMPLETED=已完成, CANCELLED=已作废', + }, + sync_status: { + type: ENUM('PENDING', 'SUCCESS', 'FAILED'), + allowNull: false, + defaultValue: 'PENDING', + comment: '同步状态', + }, + sync_message: { + type: TEXT, + allowNull: true, + comment: '同步返回信息', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '货主ID', + }, + store_name: { + type: STRING(200), + allowNull: true, + comment: '货主名称快照', + }, + warehouse_name: { + type: STRING(200), + allowNull: true, + comment: '仓库名称快照', + }, + qimen_owner_code: { + type: STRING(100), + allowNull: true, + comment: '奇门货主code(对应 ownerCode)', + }, + qimen_warehouse_code: { + type: STRING(100), + allowNull: true, + comment: '奇门仓库code(对应 warehouseCode)', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + extend_props: { + type: JSON_TYPE, + allowNull: true, + comment: '扩展属性', + }, + is_enabled: { + type: TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '是否启用', + }, + created_at: { + type: DATE, + allowNull: false, + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + comment: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + tableName: 'wms_order_stockout', + comment: '出库单主表', + timestamps: false, + indexes: [ + { + name: 'uk_stockout_order_code', + unique: true, + fields: [ 'stockout_order_code', 'warehouse_id', 'store_id' ], + }, + { + name: 'idx_order_type', + fields: [ 'order_type' ], + }, + { + name: 'idx_order_status', + fields: [ 'order_status' ], + }, + { + name: 'idx_sync_status', + fields: [ 'sync_status' ], + }, + { + name: 'idx_source_type', + fields: [ 'source_type' ], + }, + { + name: 'idx_warehouse_store', + fields: [ 'warehouse_id', 'store_id' ], + }, + { + name: 'idx_order_create_time', + fields: [ 'order_create_time' ], + }, + { + name: 'idx_is_enabled', + fields: [ 'is_enabled' ], + }, + { + name: 'idx_deleted_at', + fields: [ 'deleted_at' ], + }, + ], + }); + + /** + * 关联关系定义。 + * - 关联货主 / 仓库(均通过 Store 表) + * - 关联出库明细表 + */ + OrderStockout.associate = function() { + const { OrderStockout, Store, OrderStockoutItems } = app.model; + + // 关联仓库 + OrderStockout.belongsTo(Store, { + foreignKey: 'warehouse_id', + as: 'warehouse', + }); + + // 关联货主 + OrderStockout.belongsTo(Store, { + foreignKey: 'store_id', + as: 'store', + }); + + // 关联出库明细 + OrderStockout.hasMany(OrderStockoutItems, { + foreignKey: 'order_id', + as: 'items', + }); + }; + + // ---------- 状态机辅助方法 ---------- + + /** 判断订单是否处于"已创建"状态 */ + OrderStockout.prototype.isCreated = function() { + return this.order_status === 'CREATED'; + }; + + /** 判断订单是否处于"已审核"状态 */ + OrderStockout.prototype.isPending = function() { + return this.order_status === 'PENDING'; + }; + + /** 判断订单是否已完成 */ + OrderStockout.prototype.isCompleted = function() { + return this.order_status === 'COMPLETED'; + }; + + /** 判断订单是否已作废 */ + OrderStockout.prototype.isCancelled = function() { + return this.order_status === 'CANCELLED'; + }; + + /** 当前订单是否允许审核 */ + OrderStockout.prototype.canConfirm = function() { + return [ 'CREATED', 'PENDING' ].includes(this.order_status); + }; + + /** 当前订单是否允许取消 */ + OrderStockout.prototype.canCancel = function() { + return [ 'CREATED', 'PENDING' ].includes(this.order_status); + }; + + /** 当前订单是否允许完成 */ + OrderStockout.prototype.canComplete = function() { + return [ 'PENDING' ].includes(this.order_status); + }; + + /** 同步是否成功 */ + OrderStockout.prototype.isSyncSuccess = function() { + return this.sync_status === 'SUCCESS'; + }; + + /** 同步是否失败 */ + OrderStockout.prototype.isSyncFailed = function() { + return this.sync_status === 'FAILED'; + }; + + /** 是否启用(未软删除) */ + OrderStockout.prototype.isEnabled = function() { + return this.is_enabled === 1 && !this.deleted_at; + }; + + return OrderStockout; +}; diff --git a/app/model/order_stockout_items.js b/app/model/order_stockout_items.js new file mode 100644 index 0000000..c8780bb --- /dev/null +++ b/app/model/order_stockout_items.js @@ -0,0 +1,145 @@ +'use strict'; + +/** + * 出库单明细表 Model。 + * + * 对应数据库表 `wms_order_stockout_items`,存储奇门 stockout.create 接口中 + * 每个 节点的明细数据。 + * + * 与主表 `wms_order_stockout` 通过 `order_id` 外键关联(CASCADE 删除)。 + * 与库存表 `wms_stock_warehouse` 通过 `stock_id` 外键关联(RESTRICT 删除)。 + * @param {import('egg').Application} app - Egg 应用实例 + */ +module.exports = app => { + const { STRING, INTEGER, BIGINT, DATE, JSON: JSON_TYPE } = app.Sequelize; + + const OrderStockoutItems = app.model.define('wms_order_stockout_items', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键ID', + }, + order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '出库单ID,外键关联 wms_order_stockout.id', + }, + out_biz_code: { + type: STRING(255), + allowNull: true, + comment: '外部业务编码(幂等键)', + }, + order_line_no: { + type: STRING(50), + allowNull: false, + comment: '订单行号(对应奇门 orderLineNo)', + }, + owner_code: { + type: STRING(50), + allowNull: true, + comment: '货主编码(对应奇门 ownerCode)', + }, + item_code: { + type: STRING(50), + allowNull: true, + comment: '商品编码(对应奇门 itemCode)', + }, + item_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: 'WMS商品ID(对应奇门 itemId)', + }, + item_name: { + type: STRING(200), + allowNull: true, + comment: '商品名称', + }, + plan_qty: { + type: INTEGER(12), + allowNull: true, + comment: '计划数量(对应奇门 planQty)', + }, + actual_qty: { + type: INTEGER(12), + allowNull: false, + defaultValue: 0, + comment: '实发数量', + }, + inventory_type: { + type: STRING(50), + allowNull: true, + comment: '库存类型(ZP正品/CC残次等)', + }, + stock_id: { + type: BIGINT(20), + allowNull: true, + comment: '库存ID,外键关联 wms_stock_warehouse.id', + }, + extend_props: { + type: JSON_TYPE, + allowNull: true, + comment: '扩展属性', + }, + created_at: { + type: DATE, + allowNull: false, + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + comment: '更新时间', + }, + }, { + tableName: 'wms_order_stockout_items', + comment: '出库明细表', + timestamps: false, + indexes: [ + { + name: 'uk_order_line_no', + unique: true, + fields: [ 'order_id', 'order_line_no' ], + }, + { + name: 'idx_order_id', + fields: [ 'order_id' ], + }, + { + name: 'idx_stock_id', + fields: [ 'stock_id' ], + }, + { + name: 'idx_item_code', + fields: [ 'item_code' ], + }, + { + name: 'idx_out_biz_code', + fields: [ 'out_biz_code' ], + }, + ], + }); + + /** + * 关联关系定义。 + * - 关联出库单主表 + * - 关联商品 SKU(wms_stock_warehouse) + */ + OrderStockoutItems.associate = function() { + const { OrderStockoutItems, OrderStockout, StockWarehouse } = app.model; + + // 关联出库单 + OrderStockoutItems.belongsTo(OrderStockout, { + foreignKey: 'order_id', + as: 'order', + }); + + // 关联商品 SKU + OrderStockoutItems.belongsTo(StockWarehouse, { + foreignKey: 'stock_id', + as: 'stock', + }); + }; + + return OrderStockoutItems; +}; diff --git a/app/model/platform.js b/app/model/platform.js index ab70628..ee16114 100644 --- a/app/model/platform.js +++ b/app/model/platform.js @@ -6,7 +6,7 @@ * @return {import('sequelize').ModelCtor} 平台模型 */ module.exports = app => { - const { STRING, INTEGER, BIGINT } = app.Sequelize; + const { STRING, BIGINT } = app.Sequelize; const Platform = app.model.define('platform', { code: { diff --git a/app/model/receiving.js b/app/model/receiving.js index b8c52ae..71ae988 100644 --- a/app/model/receiving.js +++ b/app/model/receiving.js @@ -38,10 +38,10 @@ module.exports = app => { comment: '明细匹配状态:all_matched-全部匹配, partial_matched-部分匹配, unmatched-未匹配', }, storage_status: { - type: ENUM('none', 'partial', 'all'), + type: ENUM('none', 'waiting', 'partial', 'all'), defaultValue: 'none', allowNull: false, - comment: '入库状态:none-未入库, partial-部分入库, all-全部入库', + comment: '入库状态:none-未入库, waiting-等待入库, partial-部分入库, all-全部入库', }, delivery_method: { type: ENUM('truck', 'express', 'air_freight', 'sea_freight', 'other'), diff --git a/app/model/receiving_detail.js b/app/model/receiving_detail.js index da18c8f..5ff72ee 100644 --- a/app/model/receiving_detail.js +++ b/app/model/receiving_detail.js @@ -61,9 +61,9 @@ module.exports = app => { comment: '收货状态', }, storage_status: { - type: ENUM('none', 'partial', 'all'), + type: ENUM('none', 'waiting', 'partial', 'all'), defaultValue: 'none', - comment: '入库状态:none-未入库, partial-部分入库, all-全部入库', + comment: '入库状态:none-未入库, waiting-等待入库, partial-部分入库, all-全部入库', }, stored_quantity: { type: INTEGER, diff --git a/app/service/apiMethods/test.js b/app/service/apiMethods/test.js index 45bc1e5..b9ab6b0 100644 --- a/app/service/apiMethods/test.js +++ b/app/service/apiMethods/test.js @@ -18,10 +18,6 @@ class testServer extends Service { } } - async entryorderConfirm(data) { - const { ctx } = this; - return await ctx.service.systems.entryOrder.entryorderConfirm(data.id, data.isCompleted); - } async playbackRequest(data) { const { app } = this; try { diff --git a/app/service/im.js b/app/service/im.js index dcdedc1..b8429dc 100644 --- a/app/service/im.js +++ b/app/service/im.js @@ -75,7 +75,7 @@ class ImService extends Service { } /** * 获取主体员工信息 - * @param data {Object<>} 请求数据,包含 store_id + * @param {Object} data 请求数据,包含 store_id * @return {Promise<{code: number, message: string, data: Array}>} 响应数据,包含员工列表 */ async getStoreEmployees(data) { diff --git a/app/service/main.js b/app/service/main.js index 5b0f62c..b2a13bc 100644 --- a/app/service/main.js +++ b/app/service/main.js @@ -338,7 +338,9 @@ class MainService extends Service { const decoded = app.jwt.verify(token, app.config.jwt.secret); const now = Math.floor(Date.now() / 1000); const expiresIn = decoded.exp - now; - if (expiresIn < 14399 && expiresIn > 0) { + const renewThreshold = app.config.jwt.renewThreshold + ?? (app.config.jwt.expiresIn ? app.config.jwt.expiresIn - 1 : 14399); + if (expiresIn < renewThreshold && expiresIn > 0) { // 移除过期时间(exp)和签发时间(iat),保留其他payload const payload = { ...decoded }; delete payload.exp; diff --git a/app/service/openapi/callback.js b/app/service/openapi/callback.js index e9b2995..016a908 100644 --- a/app/service/openapi/callback.js +++ b/app/service/openapi/callback.js @@ -7,7 +7,7 @@ const { signRequest } = require('../../lib/api_sign'); const MAX_RETRY = 3; /** @type {number[]} 递增重试延迟(毫秒) */ -const RETRY_DELAY_MS = [2000, 5000, 15000]; +const RETRY_DELAY_MS = [ 2000, 5000, 15000 ]; /** * OpenAPI 统一回调通知服务。 @@ -166,7 +166,7 @@ class OpenapiCallbackService extends Service { } const appConfig = await ctx.model.ApiApp.findOne({ - attributes: ['self_app_key', 'self_app_secret', 'callback_url'], + attributes: [ 'self_app_key', 'self_app_secret', 'callback_url' ], where: { self_app_key: normalizedAppKey, is_enabled: 1, @@ -204,11 +204,10 @@ class OpenapiCallbackService extends Service { * @param {string} options.callbackUrl 回调目标 URL。 * @param {boolean} options.success 是否成功。 * @param {number} options.retryCount 重试次数。 - * @param {*} options.response 响应数据。 * @param {string} [options.error] 错误信息。 * @return {void} 无返回值。 */ - async logCallback({ appKey, event, callbackUrl, success, retryCount, response, error }) { + async logCallback({ appKey, event, callbackUrl, success, retryCount, error }) { const { ctx } = this; const logMessage = `[OpenapiCallback] event=${event} appKey=${appKey} url=${callbackUrl} retry=${retryCount} success=${success}`; diff --git a/app/service/openapiMethods/callback.js b/app/service/openapiMethods/callback.js index 1daa9a7..0ee4cd7 100644 --- a/app/service/openapiMethods/callback.js +++ b/app/service/openapiMethods/callback.js @@ -23,7 +23,7 @@ class OpenapiCallbackMethodService extends MainService { } const appConfig = await ctx.model.ApiApp.findOne({ - attributes: ['self_app_key'], + attributes: [ 'self_app_key' ], where: { self_app_key: normalizedAppKey, is_enabled: 1, diff --git a/app/service/openapiMethods/deliveryorder.js b/app/service/openapiMethods/deliveryorder.js index 6d47240..8cbda55 100644 --- a/app/service/openapiMethods/deliveryorder.js +++ b/app/service/openapiMethods/deliveryorder.js @@ -20,7 +20,7 @@ class OpenapiDeliveryorderService extends MainService { attributes: [ 'id', 'warehouse_id', - [app.Sequelize.col('contract.store_id'), 'store_id'], + [ app.Sequelize.col('contract.store_id'), 'store_id' ], ], where: { self_app_key: normalizedAppKey, diff --git a/app/service/openapiMethods/order.js b/app/service/openapiMethods/order.js index 81aef19..27be4b4 100644 --- a/app/service/openapiMethods/order.js +++ b/app/service/openapiMethods/order.js @@ -129,6 +129,26 @@ class OpenapiOrderService extends MainService { await transaction.commit(); + // 写入取消操作日志(不影响主流程) + try { + if (this.ctx.model && this.ctx.model.OperationLog) { + const appKey = String(query.app_key || '').trim(); + await this.ctx.model.OperationLog.create({ + business_type: 'order', + business_id: String(existingOrder.id), + operation_code: 'ORDER_CANCEL', + operator_id: null, + operator_name: appKey ? `openapi:${appKey}` : 'openapi', + external_log_type: 'NONE', + warehouse_id: info.warehouseId || null, + platform_code: appKey || 'SYSTEM', + message: 'OpenAPI 取消订单', + }); + } + } catch (logErr) { + this.ctx.logger.warn('[OpenapiOrderCancel] 写入取消操作日志失败,不影响主流程', logErr); + } + // 取消成功后触发 OpenAPI 回调通知(fire-and-forget,不阻塞主流程) try { const callbackService = this.ctx.service.openapi && this.ctx.service.openapi.callback; diff --git a/app/service/qimenMethods/order.js b/app/service/qimenMethods/order.js index adac7d9..2b2370f 100644 --- a/app/service/qimenMethods/order.js +++ b/app/service/qimenMethods/order.js @@ -203,6 +203,25 @@ class orderServer extends MainService { return this.fail('取消失败,已通知拦截执行'); } + // 已同步订单不允许取消,转为拦截处理 + const syncStatus = String(existingOrder.sync_status || '').trim(); + if (syncStatus === 'fin') { + await existingOrder.update({ + intercept_status: 'requested', + updated_at: new Date(), + }, { + transaction, + }); + + await transaction.commit(); + await this.sendCancelInterceptNotice({ + orderCode, + existingOrder, + info, + }); + return this.fail('订单已同步,不可取消,已转为拦截处理'); + } + await existingOrder.update({ status: 'cancel', outbound_status: 'fin', @@ -220,6 +239,27 @@ class orderServer extends MainService { }); await transaction.commit(); + + // 写入取消操作日志(不影响主流程) + try { + if (ctx.model && ctx.model.OperationLog) { + const customerId = String(info.customerId || '').trim(); + await ctx.model.OperationLog.create({ + business_type: 'order', + business_id: String(existingOrder.id), + operation_code: 'ORDER_CANCEL', + operator_id: null, + operator_name: customerId ? `qimen:${customerId}` : 'qimen', + external_log_type: 'NONE', + warehouse_id: info.warehouseId || null, + platform_code: customerId || 'SYSTEM', + message: '奇门取消订单', + }); + } + } catch (logErr) { + ctx.logger.warn('[QimenOrderCancel] 写入取消操作日志失败,不影响主流程', logErr); + } + return this.success('取消订单成功'); } catch (error) { try { diff --git a/app/service/qimenMethods/stockout.js b/app/service/qimenMethods/stockout.js index a5fdb49..5f280e9 100644 --- a/app/service/qimenMethods/stockout.js +++ b/app/service/qimenMethods/stockout.js @@ -2,69 +2,217 @@ const MainService = require('../main'); +/** + * 奇门出库单服务。 + * + * 处理 stockout.create / stockout.query 接口, + * 使用专用表 `wms_order_stockout` + `wms_order_stockout_items`。 + */ class stockoutServer extends MainService { + /** + * 创建出库单。 + * + * 将奇门 stockout.create 请求的 deliveryOrder / orderLines 写入 + * `wms_order_stockout` 主表和 `wms_order_stockout_items` 明细表, + * 整个过程在一个数据库事务内完成,失败自动回滚。 + * + * @param {object} data - 奇门 stockout.create 请求体 + * @param {object} data.request - 请求数据 + * @param {object} data.request.deliveryOrder - 出库单头信息 + * @param {object} data.request.orderLines - 出库单明细 + * @param {object|object[]} data.request.orderLines.orderLine - 明细行(单条为对象,多条为数组) + * @return {Promise} 返回 success / fail 结果 + */ async create(data) { - const { app, ctx, appKey, storeId, warehouseId, customerId, warehouseCode } = this; - const fail = this.fail.bind(this); - const success = this.success.bind(this); + const { app, ctx, appKey, storeId, warehouseId, warehouseCode } = this; + const { deliveryOrder, orderLines } = data.request; - let totalOrderLines = data.request.deliveryOrder.totalOrderLines || 0; - - let orderLine = data.request.orderLines.orderLine; - if (orderLine.orderLineNo) { + // 单条 orderLine 转为数组 + let orderLine = orderLines && orderLines.orderLine; + if (orderLine && orderLine.orderLineNo) { orderLine = [ orderLine ]; } - totalOrderLines = totalOrderLines || orderLine.length; + + if (!orderLine || !Array.isArray(orderLine) || orderLine.length === 0) { + return this.fail('创建出库单失败,失败原因:\n没有有效的订单明细数据'); + } + + const totalOrderLines = deliveryOrder.totalOrderLines || orderLine.length; + + // 第一步:校验所有商品是否在 StockStore 中存在,并收集有效明细 const errors = []; const items = []; for (let i = 0; i < orderLine.length; i++) { - const wms_stock = await app.model.StockStore.findByPk(orderLine[i].itemId); - if (!wms_stock) { - errors.push(`SKU${orderLine[i].itemId}商品《${orderLine[i].itemName}》编码《${orderLine[i].itemCode}》\n未同步推送到仓库`); + const line = orderLine[i]; + const wmsStock = await app.model.StockStore.findByPk(line.itemId); + if (!wmsStock) { + errors.push( + `SKU${line.itemId}商品《${line.itemName}》编码《${line.itemCode}》\n未同步推送到仓库` + ); continue; } - if (!wms_stock.stock_id) { - errors.push(`SKU${orderLine[i].itemId}商品《${orderLine[i].itemName}》编码《${orderLine[i].itemCode}》wms无对应关系\n请联系仓库关联创建商品`); + if (!wmsStock.stock_id) { + errors.push( + `SKU${line.itemId}商品《${line.itemName}》编码《${line.itemCode}》wms无对应关系\n请联系仓库关联创建商品` + ); continue; } - wms_stock.inventory_type = orderLine[i].inventoryType; - wms_stock.order_line_no = orderLine[i].orderLineNo; - wms_stock.count = orderLine[i].planQty; - wms_stock.item_id = orderLine[i].itemId; - items.push(wms_stock); - } - if (errors.length > 0) { - return this.fail('创建入库单失败,失败原因:\n' + errors.join('\n')); - } - const order = await ctx.service.systems.deliveryOrder.tryCreatedeliveryOrder(data.request.deliveryOrder, appKey, storeId, warehouseId, totalOrderLines, 'QM', customerId, warehouseCode); - if (!order.success) { - return fail('创建入库单失败,失败原因:\n' + order.error); - } - const orderId = order.deliveryOrderId; - for (let i = 0; i < items.length; i++) { - const item = items[i]; - const res = await ctx.service.systems.deliveryOrder.addItems(item, orderId); - if (!res.success) { - errors.push(`SKU${item.itemId}商品《${item.itemName}》编码《${item.itemCode}》入库失败,错误信息:${res.error}`); + const planQty = parseInt(line.planQty) || 0; + if (planQty <= 0) { + errors.push( + `SKU${line.itemId}商品《${line.itemName}》编码《${line.itemCode}》\n计划数量必须大于0` + ); + continue; } + items.push({ + orderLineNo: line.orderLineNo, + ownerCode: line.ownerCode, + itemCode: line.itemCode, + itemId: line.itemId, + itemName: line.itemName, + planQty, + inventoryType: line.inventoryType, + stockId: wmsStock.stock_id, + }); } + if (errors.length > 0) { - // 失败删除; - await ctx.model.deliveryOrder.delete(orderId); - return fail('创建入库单失败,失败原因:\n' + errors.join('\n')); + return this.fail(`创建出库单失败,失败原因:\n${errors.join('\n')}`); } - const lineCount = await ctx.service.systems.deliveryOrder.getLineCount(orderId); // 获取接收行数 - // 所有行数接收完成 - if (lineCount === totalOrderLines) { - await ctx.service.systems.deliveryOrder.received(orderId, warehouseId, storeId); // 接收完成 - return success('入库单接收完毕', { deliveryOrderId: orderId }); + + // 预取超卖配置,避免每次 lockItemStorages 在锁内回退查 DB + const oversellConfig = await ctx.service.systems.stockStore + .getStoreWarehousePolicyByStoreAndWarehouse(storeId, warehouseId); + + // 第二步:在事务中写入主表 + 库存锁定 + 明细表 + const transaction = await ctx.model.transaction(); + try { + const order = await ctx.model.OrderStockout.create( + { + stockout_order_code: deliveryOrder.deliveryOrderCode, + order_type: deliveryOrder.orderType, + total_order_lines: totalOrderLines, + order_create_time: deliveryOrder.createTime + ? new Date(deliveryOrder.createTime) + : null, + remark: deliveryOrder.remark || null, + warehouse_id: warehouseId, + store_id: storeId, + qimen_owner_code: appKey, + qimen_warehouse_code: warehouseCode, + source_type: 'QM', + created_at: new Date(), + updated_at: new Date(), + }, + { transaction } + ); + + const orderId = order.id; + + // 库存锁定:按 stockId 升序排序后逐个加锁,避免死锁 + const sortedItems = [ ...items ].sort((a, b) => a.stockId - b.stockId); + for (const item of sortedItems) { + const lockResult = await ctx.service.systems.stockStore.lockItemStorages( + item.stockId, + item.planQty, + transaction, + oversellConfig + ); + if (!lockResult.success) { + throw new Error( + `SKU${item.itemId}商品《${item.itemName}》编码《${item.itemCode}》\n库存锁定失败: ${lockResult.error}` + ); + } + } + + // 批量创建明细 + const now = new Date(); + const itemRecords = items.map(item => ({ + order_id: orderId, + order_line_no: item.orderLineNo, + owner_code: item.ownerCode, + item_code: item.itemCode, + item_id: item.itemId, + item_name: item.itemName, + plan_qty: item.planQty, + inventory_type: item.inventoryType, + stock_id: item.stockId, + created_at: now, + updated_at: now, + })); + + await ctx.model.OrderStockoutItems.bulkCreate(itemRecords, { + transaction, + validate: true, + }); + + await transaction.commit(); + + return this.success('出库单创建成功', { + stockoutOrderId: order.id, + stockoutOrderCode: order.stockout_order_code, + }); + } catch (err) { + await transaction.rollback(); + ctx.logger.error('[stockout.create] 事务写入失败:', err); + return this.fail(`创建出库单失败,失败原因:\n${err.message}`); } - return success('入库单接收中'); } - async query() { - const { fail } = this; - return fail('接口未完善'); + + /** + * 查询出库单。 + * + * 根据 deliveryOrderCode 查 `wms_order_stockout` 主表, + * 然后关联查 `wms_order_stockout_items` 明细,按奇门标准响应格式返回。 + * + * @param {object} data - 奇门 stockout.query 请求体 + * @param {object} data.request - 请求数据 + * @param {object} data.request.deliveryOrder - 出库单查询条件 + * @param {string} data.request.deliveryOrder.deliveryOrderCode - 出库单号 + * @return {Promise} 返回 success / fail 结果 + */ + async query(data) { + const { app, ctx } = this; + const { deliveryOrderCode } = data.request.deliveryOrder; + + // 查主表 + const order = await ctx.model.OrderStockout.findOne({ + where: { stockout_order_code: deliveryOrderCode }, + }); + if (!order) { + return this.fail('未找到出库单'); + } + + // 查明细 + const items = await ctx.model.OrderStockoutItems.findAll({ + where: { order_id: order.id }, + order: [[ 'order_line_no', 'ASC' ]], + }); + + return this.success('成功', { + totalLines: items.length, + deliveryOrder: { + deliveryOrderCode: order.stockout_order_code, + deliveryOrderId: order.id, + warehouseCode: order.qimen_warehouse_code, + orderType: order.order_type, + status: order.order_status, + createTime: order.order_create_time ? app.formatDate(order.order_create_time) : null, + remark: order.remark || '', + }, + orderLines: { + orderLine: items.map(item => ({ + orderLineNo: item.order_line_no, + ownerCode: item.owner_code, + itemCode: item.item_code, + itemId: item.item_id, + itemName: item.item_name, + planQty: item.plan_qty, + inventoryType: item.inventory_type, + })), + }, + }); } } diff --git a/app/service/systemMethods/dashboard.js b/app/service/systemMethods/dashboard.js index 8868138..1b16148 100644 --- a/app/service/systemMethods/dashboard.js +++ b/app/service/systemMethods/dashboard.js @@ -302,7 +302,7 @@ class dashboardService extends MainService { } /** * 订单趋势统计:按小时统计当日订单数与发货数 - * @returns {Object} 包含 categories(时段)、orders(订单数)、shipments(发货数)和 summary(汇总)的响应数据 + * @return {Object} 包含 categories(时段)、orders(订单数)、shipments(发货数)和 summary(汇总)的响应数据 */ async order_trend() { const { ctx } = this; diff --git a/app/service/systemMethods/index.js b/app/service/systemMethods/index.js index 92e46bc..2ad7b8f 100644 --- a/app/service/systemMethods/index.js +++ b/app/service/systemMethods/index.js @@ -377,7 +377,7 @@ function appendExpressMappingKey(targetMap, rawKey, mappingItem) { * 构建抖音电子面单快递映射表。 * * @param {Array} expressList 系统快递列表 - * @param platformCode + * @param {string} [platformCode='DY'] 平台编码,默认为 'DY' * @return {Object} 支持 DY 平台编码与系统快递编码双键的映射表 */ function buildExpressNameMap(expressList, platformCode = 'DY') { @@ -2050,7 +2050,7 @@ class indexService extends MainService { * * @param {string} appSecret 菠萝派访问令牌 * @param {string|number} platid 菠萝派平台标识 - * @param isJD + * @param {boolean} [isJD=false] 是否为京东平台 * @return {Promise>} 归一化后的模板数组 * @throws {Error} 当配置缺失或接口返回失败时抛出异常 */ @@ -2061,10 +2061,10 @@ class indexService extends MainService { throw new Error('菠萝派接口配置缺失'); } const query_data = { templatestype: 'ALL' }; - if (platid == 673) { + if (platid === 673) { query_data.BizVersion = '2'; } - if (platid == 544) { + if (platid === 544) { platid = 611; } let interface_url = 'https://api.polyapi.com/OpenAPI/do'; @@ -2670,9 +2670,9 @@ class indexService extends MainService { * 当前已实现 CAINIAO 平台,其它平台返回空对象,便于后续扩展。 * * @param {string} platformCode 平台编码 - * @param s - * @param platid - * @param expressCode + * @param {string|null} [s=null] 平台密钥或令牌 + * @param {string|number|null} [platid=null] 平台标识ID + * @param {string} [expressCode=''] 快递编码 * @return {Promise} 平台模板响应 */ async requestPrintPlatformTemplateList(platformCode, s = null, platid = null, expressCode = '') { diff --git a/app/service/systemMethods/order/base.js b/app/service/systemMethods/order/base.js index ad6010c..ec97b04 100644 --- a/app/service/systemMethods/order/base.js +++ b/app/service/systemMethods/order/base.js @@ -45,6 +45,8 @@ const ORDER_LIST_BASE_ATTRIBUTES = [ 'post_status', 'storage_status', 'pick_status', 'pack_status', 'inspection_status', 'print_status', 'claim_status', 'outbound_status', 'lock_status', 'intercept_status', 'basket_number', 'recheck_status', + 'create_channel', + 'store_id', ]; const ORDER_WEIGHT_TYPE_LABELS = Object.freeze({ @@ -53,6 +55,11 @@ const ORDER_WEIGHT_TYPE_LABELS = Object.freeze({ 2: '重货', 3: '冷链', }); +const CREATE_CHANNEL_LABELS = Object.freeze({ + MANUAL: '手工单', + API: '接口', + QM: '奇门', +}); const ORDER_TABLE_TYPE_ALIASES = Object.freeze({ current: 'current', history: 'history', @@ -483,6 +490,24 @@ class OrderBaseService extends MainService { return ORDER_WEIGHT_TYPE_LABELS[0]; } + /** + * 将创建来源渠道编码转换为中文展示值。 + * @param {string} channel 创建来源渠道编码。 + * @return {string} 中文渠道名称。 + */ + formatCreateChannelLabel(channel) { + if (!channel || typeof channel !== 'string') { + return ''; + } + + const trimmedChannel = channel.trim(); + if (Object.prototype.hasOwnProperty.call(CREATE_CHANNEL_LABELS, trimmedChannel)) { + return CREATE_CHANNEL_LABELS[trimmedChannel]; + } + + return trimmedChannel; + } + /** * 规范波次扫描结果,空值时默认返回 0(未扫描)。 * @param {*} scanResult 扫描结果原始值。 @@ -528,6 +553,7 @@ class OrderBaseService extends MainService { weight_type: this.formatWeightTypeLabel(order.weight_type), wave_strategy_version: this.normalizeWaveStrategyVersion(order.wave_strategy_version), wave_scan_result: this.normalizeWaveScanResult(order.wave_scan_result), + create_channel: this.formatCreateChannelLabel(order.create_channel), }; } @@ -1125,9 +1151,44 @@ class OrderBaseService extends MainService { }), ]); - const normalizedList = await this.attachOrderExpressNumbers( - list.map(order => this.normalizeOrderListItem(order)) - ); + const normalized = list.map(order => this.normalizeOrderListItem(order)); + + // 批量查询货主备注(wms_store_warehouse.store_remask) + const storeRemarkMap = new Map(); + if (normalized.length > 0 && this.ctx.model && this.ctx.model.StoreWarehouse) { + const storeIds = [ + ...new Set( + normalized + .map(row => Number(row.store_id || 0)) + .filter(id => id > 0) + ), + ]; + if (storeIds.length > 0) { + const swRows = await this.ctx.model.StoreWarehouse.findAll({ + where: { + store_id: { [this.app.Sequelize.Op.in]: storeIds }, + warehouse_id: contextWarehouseId, + }, + attributes: [ 'store_id', 'store_remask' ], + raw: true, + }); + for (const sw of (Array.isArray(swRows) ? swRows : [])) { + const sid = Number(sw.store_id || 0); + if (sid > 0 && !storeRemarkMap.has(sid)) { + storeRemarkMap.set(sid, String(sw.store_remask || '').trim()); + } + } + } + } + + const listWithRemark = normalized.map(row => ({ + ...row, + store_remark: storeRemarkMap.has(Number(row.store_id || 0)) + ? storeRemarkMap.get(Number(row.store_id || 0)) + : '', + })); + + const normalizedList = await this.attachOrderExpressNumbers(listWithRemark); const totalPages = pageSize > 0 ? Math.ceil(total / pageSize) : 0; diff --git a/app/service/systemMethods/order/pendingOrder.js b/app/service/systemMethods/order/pendingOrder.js index 09e804e..8fa822e 100644 --- a/app/service/systemMethods/order/pendingOrder.js +++ b/app/service/systemMethods/order/pendingOrder.js @@ -1749,6 +1749,38 @@ class PendingOrderService extends OrderBaseService { throw new Error('订单当前状态不允许取消'); } + // 已同步订单不允许取消,转为拦截处理 + const syncedOrders = existingOrders.filter( + order => String(order.sync_status || '').trim() === 'fin' + ); + if (syncedOrders.length > 0) { + const syncedOrderIds = syncedOrders.map(order => Number(order.id)).filter( + id => Number.isInteger(id) && id > 0 + ); + if (syncedOrderIds.length > 0) { + const syncNow = new Date(); + await model.update( + { + intercept_status: 'requested', + updated_at: syncNow, + }, + { + where: { + id: syncedOrderIds, + }, + } + ); + this.ctx.logger.info( + `[PendingOrderService.cancelOrder] 订单已同步,不可取消,已转为拦截处理,订单ID: ${syncedOrderIds.join(',')}` + ); + } + const syncedCodes = syncedOrders + .map(order => String(order.delivery_order_code || order.pre_delivery_order_code || order.id || '').trim()) + .filter(Boolean) + .join(', '); + throw new Error(`订单已同步,不可取消,已转为拦截处理:${syncedCodes}`); + } + const now = new Date(); const updateValues = { status: PENDING_CANCEL_STATUS, @@ -1916,6 +1948,37 @@ class PendingOrderService extends OrderBaseService { const firstOrder = normalizedOrders[0]; + // 写入取消操作日志(不影响主流程) + try { + const operator = this.getOrderLogOperator(); + const logWarehouseId = this.getOrderLogWarehouseId(warehouseId); + if (normalizedOrders.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 = normalizedOrders.map(order => ({ + business_type: 'order', + business_id: String(order.id), + operation_code: 'ORDER_CANCEL', + operator_id: operatorId, + operator_name: operatorName, + external_log_type: 'NONE', + warehouse_id: logWarehouseId || null, + platform_code: 'SYSTEM', + message: '订单取消', + 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.cancelOrder] 写入取消操作日志失败,不影响业务', logErr); + } + return { id: firstOrder.id, status: firstOrder.status, diff --git a/app/service/systemMethods/order/recheckOrder.js b/app/service/systemMethods/order/recheckOrder.js index c83bd6b..158f5ca 100644 --- a/app/service/systemMethods/order/recheckOrder.js +++ b/app/service/systemMethods/order/recheckOrder.js @@ -1287,10 +1287,12 @@ class RecheckOrderService extends OrderBaseService { if (Array.isArray(detail.barcodes) && detail.barcodes.length > 0) { barcodeMap.set(sid, detail.barcodes.map(bc => String(bc.barcode || '').trim()).filter(Boolean)); } - // 从 getStockDetails 提取图片 URL - const detailImageUrl = String(detail.image_url || '').trim(); - if (detailImageUrl) { - imagesByStockId.set(sid, [ detailImageUrl ]); + // 从 getStockDetails 提取图片 URL(兼容数组/字符串格式) + const imageUrls = Array.isArray(detail.image_url) + ? detail.image_url.map(u => String(u || '').trim()).filter(Boolean) + : (detail.image_url ? [ String(detail.image_url).trim() ] : []); + if (imageUrls.length > 0) { + imagesByStockId.set(sid, imageUrls); } } } @@ -3684,12 +3686,14 @@ class RecheckOrderService extends OrderBaseService { } ); - // 步骤3:检查是否存在 wms_picking 记录 + // 步骤3:检查是否存在 wms_picking 记录(仅统计 pending 且未删除的记录) const pickingRows = await ctx.model.query( `SELECT id, storage_id, quantity, space_id FROM wms_picking WHERE order_id = :orderId - AND warehouse_id = :warehouseId`, + AND warehouse_id = :warehouseId + AND status = 'pending' + AND deleted_at IS NULL`, { replacements: { orderId, warehouseId }, type: ctx.model.QueryTypes.SELECT, @@ -3700,12 +3704,14 @@ class RecheckOrderService extends OrderBaseService { const normalizedPickingRows = Array.isArray(pickingRows) ? pickingRows : []; if (normalizedPickingRows.length > 0) { - // 更新 wms_picking.status = 'fin' + // 更新 wms_picking.status = 'fin'(仅更新 pending 且未删除的记录) await ctx.model.query( `UPDATE wms_picking SET status = 'fin', updated_at = NOW() WHERE order_id = :orderId - AND warehouse_id = :warehouseId`, + AND warehouse_id = :warehouseId + AND status = 'pending' + AND deleted_at IS NULL`, { replacements: { orderId, warehouseId }, type: ctx.model.QueryTypes.UPDATE, diff --git a/app/service/systemMethods/order/wave.js b/app/service/systemMethods/order/wave.js index 8f58a71..abf04ac 100644 --- a/app/service/systemMethods/order/wave.js +++ b/app/service/systemMethods/order/wave.js @@ -5570,9 +5570,9 @@ class WaveService extends OrderBaseService { const deletedCount = await matchModel.destroy({ where }); // 清理后重建 - if (Number.isInteger(normalizedWarehouseId) && normalizedWarehouseId > 0) { + if (Number.isInteger(warehouseId) && warehouseId > 0) { setImmediate(() => { - this.submitWaveStrategyQuickScanForWarehouse(normalizedWarehouseId).catch(err => { + this.submitWaveStrategyQuickScanForWarehouse(warehouseId).catch(err => { this.ctx.logger.warn('[wave.cleanupWaveStrategyQuickScanMatchedStrategies] 清理后自动扫描失败: %s', err.message); }); }); diff --git a/app/service/systemMethods/pick.js b/app/service/systemMethods/pick.js index 80cdd9b..c0c81f4 100644 --- a/app/service/systemMethods/pick.js +++ b/app/service/systemMethods/pick.js @@ -77,7 +77,8 @@ class PickService extends MainService { const pad2 = value => String(value).padStart(2, '0'); const datePart = `${now.getFullYear()}${pad2(now.getMonth() + 1)}${pad2(now.getDate())}`; const timePart = `${pad2(now.getHours())}${pad2(now.getMinutes())}${pad2(now.getSeconds())}`; - const randomPart = Math.random().toString(36).slice(2, 6).toUpperCase(); + const randomPart = Math.random().toString(36).slice(2, 6) + .toUpperCase(); return `PK${datePart}${timePart}${randomPart}`; } @@ -190,16 +191,16 @@ class PickService extends MainService { } ); - const taskInsertHead = Array.isArray(taskInsertResult) ? taskInsertResult[0] : null; - const taskInsertMeta = Array.isArray(taskInsertResult) ? taskInsertResult[1] : null; - let taskId = Number( - (taskInsertMeta && (taskInsertMeta.insertId || taskInsertMeta.lastID || taskInsertMeta.id)) + const taskInsertHead = Array.isArray(taskInsertResult) ? taskInsertResult[0] : null; + const taskInsertMeta = Array.isArray(taskInsertResult) ? taskInsertResult[1] : null; + let taskId = Number( + (taskInsertMeta && (taskInsertMeta.insertId || taskInsertMeta.lastID || taskInsertMeta.id)) || (taskInsertHead && (taskInsertHead.insertId || taskInsertHead.lastID || taskInsertHead.id)) || 0 - ); - if (!Number.isInteger(taskId) || taskId <= 0) { - const taskIdRows = await ctx.model.query( - ` + ); + if (!Number.isInteger(taskId) || taskId <= 0) { + const taskIdRows = await ctx.model.query( + ` SELECT id FROM wms_wave_pick_task WHERE warehouse_id = :warehouseId @@ -207,18 +208,18 @@ class PickService extends MainService { ORDER BY id DESC LIMIT 1 `, - { - replacements: { - warehouseId, - taskNo, - }, - type: ctx.model.QueryTypes.SELECT, - transaction, - } - ); - const taskRow = Array.isArray(taskIdRows) && taskIdRows.length > 0 ? taskIdRows[0] : null; - taskId = Number(taskRow && taskRow.id || 0); - } + { + replacements: { + warehouseId, + taskNo, + }, + type: ctx.model.QueryTypes.SELECT, + transaction, + } + ); + const taskRow = Array.isArray(taskIdRows) && taskIdRows.length > 0 ? taskIdRows[0] : null; + taskId = Number(taskRow && taskRow.id || 0); + } if (!Number.isInteger(taskId) || taskId <= 0) { throw Object.assign(new Error('任务创建失败(未返回任务ID)'), { code: 500 }); } diff --git a/app/service/systemMethods/print.js b/app/service/systemMethods/print.js index efa64a2..3b63d15 100644 --- a/app/service/systemMethods/print.js +++ b/app/service/systemMethods/print.js @@ -327,147 +327,6 @@ class PrintService extends MainService { return lowerPlatformCode; } - /** - * 按订单ID批量加载波次序号上下文,用于 SPH 发送阶段覆写 printNum。 - * 数据来源:wms_order_wave_index。 - * 查询失败时优雅降级为空映射,不阻断发送流程。 - * @param {Object} payload 入参。 - * @param {number|string} payload.warehouseId 仓库ID。 - * @param {Array} payload.orderIds 订单ID列表。 - * @return {Promise<{orderWaveIndexMap:Map,waveTotalOrdersMap:Map}>} 波次索引上下文。 - */ - async queryWavePrintNumContextForOrderIds(payload = {}) { - const normalizedPayload = payload && typeof payload === 'object' ? payload : {}; - const warehouseId = Number(normalizedPayload.warehouseId || 0); - const orderIds = this.normalizeOrderIds(normalizedPayload.orderIds); - const emptyResult = { - orderWaveIndexMap: new Map(), - waveTotalOrdersMap: new Map(), - }; - if (!Number.isInteger(warehouseId) || warehouseId <= 0 || orderIds.length === 0) { - return emptyResult; - } - - const orderPrintService = this.service && this.service.systems && this.service.systems.orderPrint; - if (!orderPrintService - || typeof orderPrintService.queryWaveOrderIndexMapByOrderIds !== 'function' - || typeof orderPrintService.queryWaveTotalOrderCountMap !== 'function') { - this.ctx.logger.warn('[print.send] SPH printNum 覆写依赖服务不可用,跳过波次索引查询', { - warehouseId, - orderIdsCount: orderIds.length, - }); - return emptyResult; - } - - try { - const orderWaveIndexMapResult = await orderPrintService.queryWaveOrderIndexMapByOrderIds(orderIds, warehouseId); - const orderWaveIndexMap = orderWaveIndexMapResult instanceof Map - ? orderWaveIndexMapResult - : new Map(); - const waveIds = Array.from(new Set(Array.from(orderWaveIndexMap.values()) - .map(item => Number(item && item.wave_id || 0)) - .filter(waveId => Number.isInteger(waveId) && waveId > 0))); - const waveTotalOrdersMapResult = await orderPrintService.queryWaveTotalOrderCountMap(waveIds, warehouseId); - const waveTotalOrdersMap = waveTotalOrdersMapResult instanceof Map - ? waveTotalOrdersMapResult - : new Map(); - return { - orderWaveIndexMap, - waveTotalOrdersMap, - }; - } catch (error) { - this.ctx.logger.warn('[print.send] SPH printNum 覆写波次索引查询失败,回退模板默认值', { - warehouseId, - orderIdsCount: orderIds.length, - reason: error && error.message ? error.message : `${error}`, - }); - return emptyResult; - } - } - - /** - * 将 SPH 发送任务中的 printNum 覆写为波次内序号与波次总单数。 - * @param {Object} payload 入参。 - * @param {Object} payload.requestPayload 待发送 payload。 - * @param {number|string} payload.orderId 当前订单ID。 - * @param {Map} payload.orderWaveIndexMap 订单波次索引映射。 - * @param {Map} payload.waveTotalOrdersMap 波次总单数映射。 - * @return {{applied:boolean,orderId:number,waveId:number,curNum:number,sumNum:number,reason:string}} 覆写结果。 - */ - applySphPrintNumByWaveIndex(payload = {}) { - const normalizedPayload = payload && typeof payload === 'object' ? payload : {}; - const requestPayload = normalizedPayload.requestPayload && typeof normalizedPayload.requestPayload === 'object' - ? normalizedPayload.requestPayload - : null; - const orderId = Number(normalizedPayload.orderId || 0); - const fallbackResult = { - applied: false, - orderId, - waveId: 0, - curNum: 0, - sumNum: 0, - reason: '', - }; - if (!requestPayload) { - return { - ...fallbackResult, - reason: 'requestPayload 非对象', - }; - } - - const taskList = Array.isArray(requestPayload.taskList) ? requestPayload.taskList : []; - const firstTask = taskList[0] && typeof taskList[0] === 'object' ? taskList[0] : null; - if (!firstTask) { - return { - ...fallbackResult, - reason: 'taskList[0] 不存在', - }; - } - if (!Number.isInteger(orderId) || orderId <= 0) { - return { - ...fallbackResult, - reason: 'orderId 非法', - }; - } - - const orderWaveIndexMap = normalizedPayload.orderWaveIndexMap instanceof Map - ? normalizedPayload.orderWaveIndexMap - : new Map(); - const waveTotalOrdersMap = normalizedPayload.waveTotalOrdersMap instanceof Map - ? normalizedPayload.waveTotalOrdersMap - : new Map(); - const waveOrderIndexInfo = orderWaveIndexMap.get(orderId); - const waveId = Number(waveOrderIndexInfo && waveOrderIndexInfo.wave_id || 0); - const curNum = Number(waveOrderIndexInfo && waveOrderIndexInfo.wave_index || 0); - const sumNum = Number(waveTotalOrdersMap.get(waveId) || 0); - if (!Number.isInteger(waveId) || waveId <= 0 || !Number.isInteger(curNum) || curNum <= 0 || !Number.isInteger(sumNum) || sumNum <= 0) { - return { - ...fallbackResult, - waveId, - curNum, - sumNum, - reason: '波次索引信息缺失', - }; - } - - const currentPrintNum = firstTask.printNum && typeof firstTask.printNum === 'object' && !Array.isArray(firstTask.printNum) - ? firstTask.printNum - : {}; - firstTask.printNum = { - ...currentPrintNum, - curNum, - sumNum, - }; - return { - applied: true, - orderId, - waveId, - curNum, - sumNum, - reason: '', - }; - } - /** * 从打印记录 data 中提取订单ID列表。 * 兼容 data 为对象或 JSON 字符串,无法识别时返回空数组。 @@ -2257,13 +2116,8 @@ class PrintService extends MainService { payloadBuilder: normalizedPayload.payloadBuilder, }); const isKuaishouPlatform = normalizedPlatformCode === 'kuaishou'; - const isSphPlatform = normalizedPlatformCode === 'sph'; const orderBatches = []; - if (isSphPlatform) { - for (const order of orders) { - orderBatches.push([ order ]); - } - } else if (isKuaishouPlatform) { + if (isKuaishouPlatform) { for (let index = 0; index < orders.length; index += 10) { orderBatches.push(orders.slice(index, index + 10)); } @@ -2271,23 +2125,6 @@ class PrintService extends MainService { orderBatches.push(orders); } const totalDocumentCount = orders.length; - let sphOrderWaveIndexMap = new Map(); - let sphWaveTotalOrdersMap = new Map(); - if (isSphPlatform) { - const platformOrderIds = this.collectOrderIdsFromPlatformGroup(platformGroup, orders); - const wavePrintNumContext = await this.queryWavePrintNumContextForOrderIds({ - warehouseId: normalizedPayload.warehouseId, - orderIds: platformOrderIds, - }); - sphOrderWaveIndexMap = wavePrintNumContext.orderWaveIndexMap; - sphWaveTotalOrdersMap = wavePrintNumContext.waveTotalOrdersMap; - this.ctx.logger.info('[print.send] SPH 波次索引上下文加载完成', { - ...groupSummary, - orderIdsCount: platformOrderIds.length, - orderWaveIndexCount: sphOrderWaveIndexMap.size, - waveCount: sphWaveTotalOrdersMap.size, - }); - } for (let batchIndex = 0; batchIndex < orderBatches.length; batchIndex++) { const batchOrders = orderBatches[batchIndex]; @@ -2313,44 +2150,13 @@ class PrintService extends MainService { requestPayload.task.totalDocumentCount = totalDocumentCount; } currentTaskCode = await this.reserveUniquePrintTaskCode(); - if (isSphPlatform - && Array.isArray(requestPayload.taskList) - && requestPayload.taskList[0] - && typeof requestPayload.taskList[0] === 'object' - && !Array.isArray(requestPayload.taskList[0])) { - requestPayload.taskList[0].taskID = currentTaskCode; - } else if (requestPayload.task && typeof requestPayload.task === 'object' && !Array.isArray(requestPayload.task)) { + if (requestPayload.task && typeof requestPayload.task === 'object' && !Array.isArray(requestPayload.task)) { requestPayload.task.taskID = currentTaskCode; } if (currentTaskCode && !generatedTaskCodes.includes(currentTaskCode)) { generatedTaskCodes.push(currentTaskCode); } - if (isSphPlatform) { - const currentOrderId = Number(batchOrderIds[0] || 0); - const sphOverrideResult = this.applySphPrintNumByWaveIndex({ - requestPayload, - orderId: currentOrderId, - orderWaveIndexMap: sphOrderWaveIndexMap, - waveTotalOrdersMap: sphWaveTotalOrdersMap, - }); - if (sphOverrideResult.applied) { - this.ctx.logger.info('[print.send] SPH printNum 覆写成功', { - ...batchSummary, - orderId: sphOverrideResult.orderId, - waveId: sphOverrideResult.waveId, - curNum: sphOverrideResult.curNum, - sumNum: sphOverrideResult.sumNum, - }); - } else { - this.ctx.logger.info('[print.send] SPH printNum 覆写跳过,保持模板默认值', { - ...batchSummary, - orderId: sphOverrideResult.orderId, - reason: sphOverrideResult.reason, - }); - } - } - const payloadSummary = this.summarizeExpressPayload(requestPayload); this.ctx.logger.info('[print.send] 组装 payload 成功', { ...batchSummary, diff --git a/app/service/systemMethods/storage/direct_inbound.js b/app/service/systemMethods/storage/direct_inbound.js index 37d0c3d..651de7d 100644 --- a/app/service/systemMethods/storage/direct_inbound.js +++ b/app/service/systemMethods/storage/direct_inbound.js @@ -30,7 +30,7 @@ class DirectInboundService extends MainService { /** * 按商品增量添加导入/PDA 入库记录。 * @param {Object} data 请求体 - * @param {string} data.entry_order_code 入库单号 + * @param {number} data.entry_order_id 入库单 ID * @param {number} data.stock_id 商品SKU ID * @param {number} data.quantity 入库数量 * @param {string} data.inbound_type 入库方式:import 或 pda @@ -46,13 +46,13 @@ class DirectInboundService extends MainService { /** * 提交确认完成导入/PDA 入库,写入库存并触发奇门/API 回传。 * @param {Object} data 请求体 - * @param {string} data.entry_order_code 入库单号 + * @param {number} data.entry_order_id 入库单 ID * @return {Promise} 统一成功包装响应 */ async commit(data = {}) { const { service } = this; - const { entry_order_code } = data || {}; - const result = await service.systems.inboundDirectLog.commit(entry_order_code); + const { entry_order_id } = data || {}; + const result = await service.systems.inboundDirectLog.commit(entry_order_id); return this.success('ok', result); } diff --git a/app/service/systemMethods/storage/entry.js b/app/service/systemMethods/storage/entry.js index abae4df..cf25099 100644 --- a/app/service/systemMethods/storage/entry.js +++ b/app/service/systemMethods/storage/entry.js @@ -9,9 +9,9 @@ class entryService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'list,get,cancel,completeEntry,getPrintData,getDirectInboundItems,addDirectInboundItem,commitDirectInbound,removeDirectInboundItem,quickInbound,receivingCompare'; - const _noNeedLog = 'list,get,getPrintData'; - const _noNeedAuth = 'list,get,cancel,completeEntry,getPrintData,getDirectInboundItems,addDirectInboundItem,commitDirectInbound,removeDirectInboundItem,bindReceivingDetails,quickInbound,receivingCompare'; + const _noNeedRight = 'list,get,cancel,getPrintData,getDirectInboundItems,addDirectInboundItem,commitDirectInbound,removeDirectInboundItem,quickInbound,receivingCompare,queryEntryLogs,getReceivingDetailsForBind,reviewEntry,containerList'; + const _noNeedLog = 'list,get,getPrintData,reviewEntry,containerList'; + const _noNeedAuth = 'list,get,cancel,getPrintData,getDirectInboundItems,addDirectInboundItem,commitDirectInbound,removeDirectInboundItem,bindReceiving,quickInbound,receivingCompare,unbindReceiving,queryEntryLogs,getReceivingDetailsForBind,reviewEntry,containerList'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -64,20 +64,6 @@ class entryService extends MainService { return this.success('ok', result); } - /** - * 完成入库单(纯状态变更,不写库存)。 - * 仅校验状态=PENDING、有明细,然后将 order_status 更新为 COMPLETED。 - * @param {Object} data 请求体 - * @param {number} data.id 入库单ID - * @return {Promise} 统一 success 包装 - */ - async completeEntry(data = {}) { - const { service } = this; - const { id } = data; - const result = await service.systems.storage.entry.completeEntry({ id }); - return this.success('ok', result); - } - /** * 获取入库单的导入/PDA 直接入库信息(从 storage.entry 模块暴露)。 * @param {Object} data 请求体 @@ -110,13 +96,13 @@ class entryService extends MainService { /** * 提交确认完成导入/PDA 直接入库(从 storage.entry 模块暴露)。 * @param {Object} data 请求体 - * @param {string} data.entry_order_code 入库单号 + * @param {number} data.entry_order_id 入库单 ID * @return {Promise} 统一 success 包装 */ async commitDirectInbound(data = {}) { const { service } = this; - const { entry_order_code } = data || {}; - const result = await service.systems.inboundDirectLog.commit(entry_order_code); + const { entry_order_id } = data || {}; + const result = await service.systems.inboundDirectLog.commit(entry_order_id); return this.success('ok', result); } @@ -133,19 +119,43 @@ class entryService extends MainService { } /** - * 批量绑定入库单明细与收货单明细(system method 包装层)。 + * 绑定入库单与收货单的主表关系(仅主表绑定,不做明细分配)。 * @param {Object} data 请求体 - * @param {number} data.entry_order_id 入库单ID - * @param {Array} data.bindings 绑定列表 [{ entry_item_id, receiving_detail_id, allocated_quantity }] + * @param {number} data.entry_order_id 入库单 ID + * @param {number[]} data.receiving_ids 收货单 ID 列表 * @return {Promise} 统一 success 包装 */ - async bindReceivingDetails(data = {}) { - const { service } = this; - const { entry_order_id, bindings } = data || {}; - const result = await service.systems.receiving_entry_match.bindReceivingDetails({ entry_order_id, bindings }); + async bindReceiving(data = {}) { + const { ctx } = this; + console.log('[DEBUG] systems keys:', Object.keys(ctx.service.systems)); + console.log('[DEBUG] receiving_entry_match:', typeof ctx.service.systems.receivingEntryMatch); + const { entry_order_id, receiving_ids } = data || {}; + const creator_id = ctx.user ? ctx.user.id || ctx.user.user_id : undefined; + const result = await ctx.service.systems.receivingEntryMatch.bindEntryOrderReceiving({ + entry_order_id, + receiving_ids, + creator_id, + }); return this.success('绑定完成', result); } + /** + * 解除入库单与收货单的绑定关系。 + * @param {Object} data 请求体 + * @param {number} data.entry_order_id 入库单 ID + * @param {number[]} data.receiving_ids 要解除绑定的收货单 ID 列表 + * @return {Promise} 统一 success 包装 + */ + async unbindReceiving(data = {}) { + const { ctx } = this; + const { entry_order_id, receiving_ids } = data || {}; + const result = await ctx.service.systems.receivingEntryMatch.unbindEntryOrderReceiving({ + entry_order_id, + receiving_ids, + }); + return this.success('解绑完成', result); + } + /** * 快捷直入/虚拟入库(system method 包装层)。 * @param {Object} data 请求体 @@ -156,7 +166,10 @@ class entryService extends MainService { const { service } = this; const { id } = data; const result = await service.systems.storage.entry.quickInbound({ id }); - return this.success('ok', result); + if (result && result.code === 200) { + return this.success(result.message || 'ok', result); + } + return this.fail(result?.message || '快捷入库失败', result); } /** @@ -246,17 +259,88 @@ class entryService extends MainService { } /** * 入库单商品与收货单商品逐行对照视图(system method 包装层)。 + * 支持传入多个收货单ID进行批量对照预览。 * @param {Object} data 请求体 * @param {number} data.entry_order_id 入库单ID - * @param {number} data.receiving_id 收货单ID + * @param {number[]} [data.receiving_ids] 收货单ID列表(优先使用) + * @param {number} [data.receiving_id] 单个收货单ID(向后兼容) * @return {Promise} 统一 success 包装 */ async receivingCompare(data = {}) { const { service } = this; - const { entry_order_id, receiving_id } = data || {}; - const result = await service.systems.storage.entry.receivingCompare({ entry_order_id, receiving_id }); + const { entry_order_id, receiving_id, receiving_ids } = data || {}; + const result = await service.systems.storage.entry.receivingCompare({ entry_order_id, receiving_id, receiving_ids }); return this.success('ok', result); } + /** + * 查询入库单操作日志。warehouseId 由服务端从当前上下文自动注入,前端无需传递。 + * @param {Object} data 请求体 + * @param {number} data.id 入库单ID + * @param {number} [data.page=1] 页码 + * @param {number} [data.pageSize=20] 每页数量 + * @return {Promise} 统一 success 包装 + */ + async queryEntryLogs(data = {}) { + const { ctx, service } = this; + const warehouseId = ctx.user?.store_id; + const result = await service.systems.operationLog.queryEntryOrderLogs({ + id: data.id, + warehouseId, + page: data.page, + pageSize: data.pageSize, + }); + return this.success('ok', result); + } + + /** + * 查询入库单已绑定收货单中匹配指定商品的可绑定收货明细列表。 + * @param {Object} data 请求体 + * @param {number} data.entry_order_id 入库单ID + * @param {number} data.stock_id 商品stock_id + * @return {Promise} 统一 success 包装 + */ + async getReceivingDetailsForBind(data = {}) { + const { service } = this; + const result = await service.systems.storage.entry.getReceivingDetailsForBind(data); + if (result && result.code === 200) { + return this.success('ok', result.data); + } + return this.fail(result?.message || '查询失败', result); + } + + /** + * 拉取入库单绑定的收货单中,指定商品的可用容器列表(收货明细)。 + * 用于 PDA 上架时选择容器。 + * @param {Object} data 请求体 + * @param {number} data.entry_order_id 入库单ID + * @param {number} data.stock_id 商品stock_id + * @return {Promise} 统一 success 包装,data 包含 { list, total } + */ + async containerList(data = {}) { + const { service } = this; + const { entry_order_id, stock_id } = data || {}; + const result = await service.systems.storage.entry.containerList({ entry_order_id, stock_id }); + if (result && result.code === 200) { + return this.success('ok', result.data); + } + return this.fail(result?.message || '查询失败', result); + } + + /** + * 审核入库单(CREATED → PENDING)。 + * @param {Object} data 请求体 + * @param {number} data.id 入库单ID + * @return {Promise} 统一 success/fail 包装 + */ + async reviewEntry(data = {}) { + const { service } = this; + const result = await service.systems.entryOrder.reviewEntry(data); + if (result && result.success) { + return this.success(result.message, result.data, 200); + } + return this.fail(result?.message || '审核失败', result, 400); + } + } module.exports = entryService; diff --git a/app/service/systemMethods/storage/inventory.js b/app/service/systemMethods/storage/inventory.js index 33f63cf..f860d40 100644 --- a/app/service/systemMethods/storage/inventory.js +++ b/app/service/systemMethods/storage/inventory.js @@ -12,7 +12,7 @@ class InventoryMethodService extends MainService { const _noNeedLogin = ''; const _noNeedRight = 'list'; const _noNeedLog = 'list'; - const _noNeedAuth = 'list'; + const _noNeedAuth = 'list,quickPutaway'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -61,6 +61,20 @@ class InventoryMethodService extends MainService { const result = await service.systems.storage.inventory.getInventoryList(pagination, sort, group_by_batch); return this.success('ok', result); } + + /** + * 收货单快捷入库:将收货单的明细直接转为入库单,相同商品自动合并数量。 + * 要求货主配置中允许收货单快捷入库,否则直接返回失败。 + * @param {Object} data 请求体 + * @param {number} data.receiving_id 收货单ID(必填) + * @return {Promise} 统一 success 包装,返回创建的入库单信息 + */ + async quickPutaway(data = {}) { + const { service } = this; + const { receiving_id } = data; + const result = await service.systems.storage.inventory.quickPutaway({ receiving_id }); + return this.success('ok', result); + } } module.exports = InventoryMethodService; diff --git a/app/service/systemMethods/storage/receiving.js b/app/service/systemMethods/storage/receiving.js index 8c6ddd2..1cf6234 100644 --- a/app/service/systemMethods/storage/receiving.js +++ b/app/service/systemMethods/storage/receiving.js @@ -10,9 +10,9 @@ class configService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs'; - const _noNeedLog = 'getReceivingList,get,addDetail,deleteDetail,detailChange,bindStore,bindDetailProduct,queryReceivingLogs'; - const _noNeedAuth = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs'; + const _noNeedRight = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs,scanDetail'; + const _noNeedLog = 'getReceivingList,get,addDetail,deleteDetail,detailChange,bindStore,bindDetailProduct,queryReceivingLogs,scanDetail'; + const _noNeedAuth = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs,scanDetail'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -21,11 +21,13 @@ class configService extends MainService { * @param {Object} data 请求体 * @param {Object} [data.pagination] 分页参数 * @param {Object} [data.where] 筛选条件 + * @param {boolean} [data.filterDepleted=false] 是否过滤掉无可再用量的收货单(所有明细已被其他入库单 committed 绑定占满) + * @param {number} [data.entry_order_id] 可选,按入库单商品交集过滤:只返回"至少有一条明细的 system_product_id 在入库单明细中"的收货单 * @return {Promise} 统一成功包装响应 */ async getReceivingList(data) { const { service } = this; - const { pagination, sort } = data; + const { pagination, sort, filterDepleted = false, entry_order_id: entryOrderId } = data; const { where } = this.prepareWhereContext(data, { specialFieldMap: { quickWhere: { @@ -33,7 +35,7 @@ class configService extends MainService { }, }, }); - const result = await service.systems.storage.receiving.getReceivingList(where, pagination, sort); + const result = await service.systems.storage.receiving.getReceivingList(where, pagination, sort, { filterDepleted, entry_order_id: entryOrderId }); return this.success('ok', result); } @@ -260,5 +262,23 @@ class configService extends MainService { }); } + /** + * PDA 扫码定位收货明细(system method 包装层),返回匹配的明细列表。 + * 同一条码可能匹配到多条收货明细,以列表形式返回所有匹配结果。 + * @param {Object} data 请求体 + * @param {number} data.entry_order_id 入库单ID + * @param {string} data.barcode 扫描条码(商品条码/箱唛/托盘唛/明细ID) + * @return {Promise} 统一成功包装响应,含匹配的收货明细列表 { list, total } + */ + async scanDetail(data) { + const { service } = this; + const { entry_order_id, barcode } = data; + const result = await service.systems.storage.receiving.scanDetail(entry_order_id, barcode); + if (result.code !== 200) { + return this.fail(result.message); + } + return this.success('查询成功', result.data); + } + } module.exports = configService; diff --git a/app/service/systems/delivery_order.js b/app/service/systems/delivery_order.js index fb9f2c1..0fa7e8c 100644 --- a/app/service/systems/delivery_order.js +++ b/app/service/systems/delivery_order.js @@ -778,10 +778,12 @@ class DeliveryOrderService extends Service { /** * 根据货主仓库策略解析订单步骤。 + * 若货主与仓库之间不存在已启用已签约的记录(auth_status=2, use_status=1),则抛出错误拒绝创建。 * - * @param {Object} info 当前仓库与货主上下文。 + * @param {Object} info 当前仓库与货主上下文,需包含 storeId 和 warehouseId。 * @param {Object|null} transaction 数据库事务。 * @return {Promise} 订单步骤,需审批返回 0,免审批返回 1。 + * @throws {Error} 货主未与当前仓库签约时抛出。 */ async resolveOrderStep(info, transaction = null) { const { ctx } = this; @@ -805,7 +807,7 @@ class DeliveryOrderService extends Service { }); if (!relation) { - return DELIVERY_ORDER_STEP.PENDING_REVIEW; + throw new Error('货主未与当前仓库签约,无法创建订单'); } const storeWarehouseService = ctx.service && ctx.service.systems && ctx.service.systems.storeWarehouse; diff --git a/app/service/systems/entry_order.js b/app/service/systems/entry_order.js index 33de8b1..8056b22 100644 --- a/app/service/systems/entry_order.js +++ b/app/service/systems/entry_order.js @@ -131,6 +131,26 @@ class entryOrderService extends Service { ); } + // 写入操作日志 + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'entry_order', + businessId: orderId, + operationCode: 'ENTRY_ORDER_CREATE', + operator: { + id: ctx.user?.employees_id || ctx.user?.id || '', + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId, + storeId, + entryOrderCode: orderCode, + sourceType: fromCode, + totalOrderLines, + finalStatus, + }, + transaction, + }); + // 提交事务 await transaction.commit(); @@ -172,9 +192,9 @@ class entryOrderService extends Service { } catch (error) { // 发生异常,回滚事务 - await transaction.rollback().catch(e => console.error('回滚事务失败:', e)); + await transaction.rollback().catch(e => ctx.logger.error(`回滚事务失败: ${e.message}`, e)); - console.error('addOrder 事务异常:', error); + ctx.logger.error(`addOrder 事务异常: ${error.message}`, error); return { success: false, message: `系统异常: ${error.message}`, @@ -825,248 +845,74 @@ class entryOrderService extends Service { } } - async qimenEntryorderConfirm(entryOrder, orderLines, isFin, outBizCode) { - if (orderLines.length < 1) { - throw new Error('行不能为空'); - } - const queryData = { - request: { - entryOrder: { - entryOrderCode: entryOrder.entry_order_code, - ownerCode: entryOrder.qimen_owner_code, - warehouseCode: entryOrder.qimen_warehouse_code, - entryOrderId: entryOrder.id, - entryOrderType: entryOrder.order_type, - outBizCode, - confirmType: isFin ? 0 : 1, - status: isFin ? 'FULFILLED' : 'PARTFULFILLED', - freight: 0, - operateTime: this.app.formatDate(new Date()), - remark: entryOrder.remark, - }, - orderLines, - }, - }; - const Result = await this.app.qimenClient.send('taobao.qimen.entryorder.confirm', entryOrder.qimen_owner_code, queryData, { - ctx: this.ctx, - }); - return Result; - } - async entryorderConfirm(orderId, isCompleted) { + /** + * 审核入库单(CREATED → PENDING)。 + * 只允许已绑定收货单的入库单推进状态,未绑定则拒绝。 + * + * @param {Object} data 请求体 + * @param {number} data.id 入库单 ID + * @return {Promise} { success, message, data } + */ + async reviewEntry(data = {}) { const { app, ctx } = this; - const transaction = await app.model.transaction(); + const orderId = Number(data.id || 0); - try { - // 锁定数据 - const entryOrder = await app.model.EntryOrder.findOne({ - where: { - id: orderId, - is_enabled: 1, - deleted_at: null, - }, - include: [ - { - model: app.model.EntryItems, - as: 'items', - lock: transaction.LOCK.UPDATE, - }, - ], - lock: transaction.LOCK.UPDATE, - transaction, - }); + if (!orderId) { + return { success: false, message: 'id 必填' }; + } - if (!entryOrder) { - await transaction.rollback(); - return { success: false, message: '入库单不存在' }; - } + const entryOrder = await app.model.EntryOrder.findOne({ + where: { id: orderId, is_enabled: 1, deleted_at: null }, + }); - // 状态检查 - const allowedStatuses = [ 'CREATED', 'PENDING' ]; - if (!allowedStatuses.includes(entryOrder.order_status)) { - await transaction.rollback(); - return { - success: false, - code: 'INVALID_STATUS', - message: `入库单状态[${entryOrder.order_status}]不允许确认`, - }; - } - - const orderLines = []; - let totalPlanQty = 0; - let totalReceivedQty = 0; - let totalConfirmIncrement = 0; - let hasItemsToConfirm = false; - - // 第一阶段:计算和验证,不执行更新 - const pendingUpdates = []; - - for (let i = 0; i < entryOrder.items.length; i++) { - const item = entryOrder.items[i]; - const planQty = item.count || 0; - const receivedQty = item.received_quantity || 0; - const confirmedQty = item.confirm_quantity || 0; - - // 计算本次确认的增量 - const confirmIncrement = Math.max(0, receivedQty - confirmedQty); - - if (confirmIncrement > 0) { - hasItemsToConfirm = true; - - // 奇门需要的是本次确认的数量(actualQty) - const orderLine = { - orderLineNo: i + 1, - ownerCode: item.owner_code, - itemCode: item.item_code, - itemId: item.item_id, - inventoryType: item.inventory_type, - planQty, - actualQty: confirmIncrement, // 传本次增量 - }; - orderLines.push(orderLine); - - totalConfirmIncrement += confirmIncrement; - - // 记录待更新数据(不执行) - pendingUpdates.push({ - id: item.id, - item_id: item.item_id, - new_confirm_quantity: confirmedQty + confirmIncrement, - old_confirm_quantity: confirmedQty, - received_quantity: receivedQty, - confirm_increment: confirmIncrement, - }); - } - - totalPlanQty += planQty; - totalReceivedQty += receivedQty; - } - - // 没有需要确认的数量 - if (!hasItemsToConfirm) { - await transaction.rollback(); - return { success: false, message: '没有需要确认的收货数量' }; - } - - // 判断是否最终完成 - const isFin = isCompleted ? true : (totalReceivedQty >= totalPlanQty); - let qimenResult = {}; - // 奇门入库单,数据同步到奇门 - if (String(entryOrder.source_type) === 'QM') { - // 第二阶段:调用奇门接口 - const Result = await this.qimenEntryorderConfirm( - entryOrder, - orderLines, - isFin, - Math.round(new Date() / 1000) - ); - qimenResult = Result.xmlArray.response; - // 奇门调用失败,回滚事务 - if (!qimenResult || String(qimenResult.flag) !== 'success') { - await transaction.rollback(); - console.error('奇门接口调用失败:', qimenResult); - return { - success: false, - code: 'QIMEN_FAILED', - message: '奇门接口调用失败', - detail: qimenResult?.message || '未知错误', - }; - } - } - // 第三阶段:奇门成功,执行数据库更新 - - // 1. 更新确认数量 - for (const update of pendingUpdates) { - const result = await app.model.EntryItems.update({ - confirm_quantity: update.new_confirm_quantity, - updated_at: new Date(), - }, { - where: { - id: update.id, - confirm_quantity: update.old_confirm_quantity, // 乐观锁,防止并发 - }, - transaction, - }); - await ctx.service.systems.stockStore.inbound(update.item_id, update.confirm_increment, transaction); - if (result[0] === 0) { - // 更新失败,可能被并发修改了 - console.warn(`更新入库明细失败,可能已被修改: id=${update.id}`); - // 可以选择重试或抛出异常 - } - } - - // 2. 更新入库单状态 - let newOrderStatus = entryOrder.order_status; - if (isFin) { - newOrderStatus = 'COMPLETED'; - } else if (totalConfirmIncrement > 0) { - // CREATED 确认后变为 PENDING,PENDING 确认后保持 PENDING(多次收货确认) - newOrderStatus = 'PENDING'; - } - - const updateResult = await app.model.EntryOrder.update({ - order_status: newOrderStatus, - sync_status: 'SUCCESS', - sync_message: JSON.stringify({ - confirmTime: new Date(), - totalPlan: totalPlanQty, - totalReceived: totalReceivedQty, - totalConfirmIncrement, - isFin, - pendingUpdatesCount: pendingUpdates.length, - qimenResult: qimenResult?.data || {}, - }), - updated_at: new Date(), - }, { - where: { - id: entryOrder.id, - order_status: entryOrder.order_status, // 乐观锁 - }, - transaction, - }); - - if (updateResult[0] === 0) { - // 入库单状态已被修改,回滚 - await transaction.rollback(); - return { - success: false, - code: 'CONCURRENT_MODIFICATION', - message: '入库单已被修改,请刷新后重试', - }; - } - // 4. 提交事务 - await transaction.commit(); - - return { - success: true, - message: isFin ? '入库单完成确认' : '入库单增量确认成功', - data: { - entryOrderId: entryOrder.id, - entryOrderCode: entryOrder.entry_order_code, - orderStatus: newOrderStatus, - totalPlan: totalPlanQty, - totalReceived: totalReceivedQty, - totalConfirmIncrement, - isFin, - updatedItemsCount: pendingUpdates.length, - orderLinesCount: orderLines.length, - }, - }; - - } catch (error) { - // 发生异常,回滚事务 - await transaction.rollback().catch(e => { - console.error('回滚事务失败:', e); - }); - - console.error('确认入库单失败:', error); + if (!entryOrder) { + return { success: false, message: '入库单不存在' }; + } + if (entryOrder.order_status !== 'CREATED') { return { success: false, - code: 'SYSTEM_ERROR', - message: `系统异常: ${error.message}`, - stack: process.env.NODE_ENV === 'development' ? error.stack : undefined, + message: `当前状态[${entryOrder.order_status}]不允许审核,仅 CREATED 可审核`, }; } + + // 校验:必须有绑定的收货单 + const hasReceiving = await ctx.model.EntryOrderReceiving.findOne({ + where: { entry_order_id: orderId, deleted_at: null }, + }); + if (!hasReceiving) { + return { + success: false, + message: '入库单未绑定收货单,请先绑定收货单后再审核', + }; + } + + // 推进状态 + await entryOrder.update({ + order_status: 'PENDING', + updated_at: new Date(), + }); + + // 写操作日志 + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'entry_order', + businessId: entryOrder.id, + operationCode: 'ENTRY_ORDER_REVIEW', + operator: { + id: ctx.user?.employees_id || ctx.user?.id || '', + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: entryOrder.warehouse_id, + message: '入库单审核通过(CREATED → PENDING)', + }, + }); + + return { + success: true, + message: '审核成功', + data: { id: entryOrder.id, order_status: 'PENDING' }, + }; } } diff --git a/app/service/systems/express.js b/app/service/systems/express.js index 928eb74..e7d38a1 100644 --- a/app/service/systems/express.js +++ b/app/service/systems/express.js @@ -2427,21 +2427,8 @@ class ExpressService extends Service { }); // 发件人相关字段统一走接口配置,货主配置仅用于打印链路。 - // 三级兜底:express_interface → 仓库 subject_config → 空字符串 - const storeRow = await this.ctx.model.Store.findByPk(warehouseId, { - attributes: [ 'subject_config' ], - raw: true, - }); - const subjectConfig = (storeRow && storeRow.subject_config) ? storeRow.subject_config : {}; const expressInterfaceConfig = expressInterface ? { ...expressInterface, - sender_name: expressInterface.sender_name || subjectConfig.sender_name || '', - sender_tel: expressInterface.sender_tel || subjectConfig.sender_tel || '', - province_name: expressInterface.province_name || subjectConfig.province_name || '', - city_name: expressInterface.city_name || subjectConfig.city_name || '', - district_name: expressInterface.district_name || subjectConfig.district_name || '', - town_name: expressInterface.town_name || subjectConfig.town_name || '', - address: expressInterface.address || subjectConfig.address || '', } : null; for (const batch of batches) { diff --git a/app/service/systems/express_platform.js b/app/service/systems/express_platform.js index be62f09..400376c 100644 --- a/app/service/systems/express_platform.js +++ b/app/service/systems/express_platform.js @@ -729,27 +729,17 @@ class ExpressPlatformService extends MainService { inputsite: listByWarehousePlatformCode.site_code || '', sitecode: listByWarehousePlatformCode.site_code || '', shipperno: listByWarehousePlatformCode.shipperno || '', - sender: (() => { - const senderName = listByWarehousePlatformCode.sender_name || ''; - const senderTel = listByWarehousePlatformCode.sender_tel || ''; - const senderProvince = listByWarehousePlatformCode.province_name || ''; - const senderCity = listByWarehousePlatformCode.city_name || ''; - const senderDistrict = listByWarehousePlatformCode.district_name || ''; - const senderTown = listByWarehousePlatformCode.town_name || ''; - const senderAddress = listByWarehousePlatformCode.address || ''; - const fallback = '仓库未配置发件人'; - return { - company: listByWarehousePlatformCode.shop_name || '', - name: senderName || fallback, - phone: senderTel || (senderName ? '' : fallback), - country: 'CN', - city: senderCity || fallback, - province: senderProvince || fallback, - area: senderDistrict || fallback, - town: senderTown || fallback, - address: senderAddress || fallback, - }; - })(), + sender: { + company: listByWarehousePlatformCode.shop_name || '', + name: listByWarehousePlatformCode.sender_name || '', + phone: listByWarehousePlatformCode.sender_tel || '', + country: 'CN', + city: listByWarehousePlatformCode.city_name || '', + province: listByWarehousePlatformCode.province_name || '', + area: listByWarehousePlatformCode.district_name || '', + town: listByWarehousePlatformCode.town_name || '', + address: listByWarehousePlatformCode.address || '', + }, // 需要实现 receiver: { name: order.name || '', company: order.company || '', @@ -789,7 +779,6 @@ class ExpressPlatformService extends MainService { providercode, numpackage, businessplat, - paymode, ordertype, businessType, codpaymoney, @@ -817,12 +806,11 @@ class ExpressPlatformService extends MainService { const { name, phone, - mobile, province: receiverProvince, city: receiverCity, address: receiverAddress, } = receiver; - const senderName = senderNameRaw || listByWarehousePlatformCode.sender_name || listByWarehousePlatformCode.shop_name || '仓库未配置发件人'; + const senderName = senderNameRaw || listByWarehousePlatformCode.sender_name || listByWarehousePlatformCode.shop_name || ''; const senderCompany = senderCompanyRaw || listByWarehousePlatformCode.shop_name || ''; const customername = senderNameRaw || senderCompanyRaw || listByWarehousePlatformCode.shop_name || '测试'; @@ -874,18 +862,18 @@ class ExpressPlatformService extends MainService { playload.codpaymoney = ''; } } - if(matchedPlatform.platid ===672){ - if(!order.source_order_codes){ + if (matchedPlatform.platid === 672) { + if (!order.source_order_codes) { throw new Error('订单数据错误,缺失平台订单号'); } - playload.object_Id = order.source_order_codes.split(",")[0]; - if(!order.extend_props.ewaybill_order_code){ + playload.object_Id = order.source_order_codes.split(',')[0]; + if (!order.extend_props.ewaybill_order_code) { throw new Error('订单数据错误,参数不全缺失extend_props.ewaybill_order_code,请复制次信息给ERP方反馈'); } playload.oaid = order.extend_props.ewaybill_order_code; - playload.transtype = "0"; + playload.transtype = '0'; playload.Mallmaskid = order.buyer_nick; - playload.mainsubpaymode = "1"; + playload.mainsubpaymode = '1'; delete playload.plattradeno; } playload.ProviderID = listByWarehousePlatformCode.providerid; @@ -1233,39 +1221,39 @@ class ExpressPlatformService extends MainService { }; }); break; - case 'QT': - case 'OTHER': - successUpdates = (result.results || []).map(item => { - const [ warehouse_id, order_id, business_key ] = String(item.orderno || '').split('_'); - const waybillCode = String(item.logisticno || item.waybill_code || '').trim(); - return { - warehouse_id, - order_id, - business_key, + case 'QT': + case 'OTHER': + successUpdates = (result.results || []).map(item => { + const [ warehouse_id, order_id, business_key ] = String(item.orderno || '').split('_'); + const waybillCode = String(item.logisticno || item.waybill_code || '').trim(); + return { + warehouse_id, + order_id, + business_key, + waybill_code: waybillCode, + orderExpressValues: { waybill_code: waybillCode, - orderExpressValues: { - waybill_code: waybillCode, - printinfo: item.printinfo, - signature: item.signature, - encryptprintinfo: item.encryptprintinfo, - encryptedtoken: item.encryptedtoken, - ...this.buildOrderExpressVerPatch([ item.ver ]), - 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; + printinfo: item.printinfo, + signature: item.signature, + encryptprintinfo: item.encryptprintinfo, + encryptedtoken: item.encryptedtoken, + ...this.buildOrderExpressVerPatch([ item.ver ]), + 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: { const unmatchedPlatformCode = String(listByWarehousePlatformCode && listByWarehousePlatformCode.platform_code || '').trim(); this.ctx.logger.error('[expressPlatform.polyapi] switch 无匹配 platform_code', { @@ -1546,10 +1534,10 @@ class ExpressPlatformService extends MainService { // 自动同步回传:快递号分配成功后异步触发订单同步 try { const settlementEntries = Array.from(settlementRelationMap.entries()); - for (const [key, relation] of settlementEntries) { + for (const [ key, relation ] of settlementEntries) { const successCount = Number(relation && relation.success_count) || 0; if (successCount <= 0) continue; - const [storeId, warehouseId] = key.split(':').map(Number); + const [ storeId, warehouseId ] = key.split(':').map(Number); if (!storeId || !warehouseId) continue; const contractConfig = await this.service.systems.storeWarehouse.getContractConfig( @@ -1700,28 +1688,18 @@ class ExpressPlatformService extends MainService { ? (listByWarehousePlatformCode.express.CAINIAO || listByWarehousePlatformCode.express.cainiao_code || '') : '', product_code: String(listByWarehousePlatformCode.product_type || '').trim(), - sender: (() => { - const senderName = listByWarehousePlatformCode.sender_name || ''; - const senderTel = listByWarehousePlatformCode.sender_tel || ''; - const senderProvince = listByWarehousePlatformCode.province_name || ''; - const senderCity = listByWarehousePlatformCode.city_name || ''; - const senderDistrict = listByWarehousePlatformCode.district_name || ''; - const senderTown = listByWarehousePlatformCode.town_name || ''; - const senderAddress = listByWarehousePlatformCode.address || ''; - const fallback = '仓库未配置发件人'; - return { - address: { - city: senderCity || fallback, - detail: senderAddress || fallback, - district: senderDistrict || fallback, - province: senderProvince || fallback, - town: senderTown || null, - }, - mobile: senderTel || (senderName ? '' : fallback), - name: senderName || fallback, - phone: senderTel || (senderName ? '' : fallback), - }; - })(), + sender: { + address: { + city: listByWarehousePlatformCode.city_name, + detail: listByWarehousePlatformCode.address, + district: listByWarehousePlatformCode.district_name, + province: listByWarehousePlatformCode.province_name, + town: listByWarehousePlatformCode.town_name || null, + }, + mobile: listByWarehousePlatformCode.sender_tel, + name: listByWarehousePlatformCode.sender_name, + phone: listByWarehousePlatformCode.sender_tel, + }, trade_order_info_dtos: tradeOrderList, brand_code: String(listByWarehousePlatformCode.site_code || 'default').trim(), need_encrypt: true, @@ -1886,10 +1864,10 @@ class ExpressPlatformService extends MainService { orderMetaMap ); const settlementEntries = Array.from(settlementRelationMap.entries()); - for (const [key, relation] of settlementEntries) { + for (const [ key, relation ] of settlementEntries) { const successCount = Number(relation && relation.success_count) || 0; if (successCount <= 0) continue; - const [storeId, warehouseId] = key.split(':').map(Number); + const [ storeId, warehouseId ] = key.split(':').map(Number); if (!storeId || !warehouseId) continue; const contractConfig = await this.service.systems.storeWarehouse.getContractConfig( @@ -2218,7 +2196,6 @@ class ExpressPlatformService extends MainService { */ async pdd(data = {}) { const { - matchedPlatform = {}, listByWarehousePlatformCode = {}, orders = [], } = data && typeof data === 'object' ? data : {}; @@ -2267,29 +2244,19 @@ class ExpressPlatformService extends MainService { accessToken: listByWarehousePlatformCode.token, param_waybill_cloud_print_apply_new_request: { need_encrypt: true, - sender: (() => { - const senderName = listByWarehousePlatformCode.sender_name || ''; - const senderTel = listByWarehousePlatformCode.sender_tel || ''; - const senderProvince = listByWarehousePlatformCode.province_name || ''; - const senderCity = listByWarehousePlatformCode.city_name || ''; - const senderDistrict = listByWarehousePlatformCode.district_name || ''; - const senderTown = listByWarehousePlatformCode.town_name || ''; - const senderAddress = listByWarehousePlatformCode.address || ''; - const fallback = '仓库未配置发件人'; - return { - address: { - country: '中国', - city: senderCity || fallback, - province: senderProvince || fallback, - district: senderDistrict || fallback, - town: senderTown || null, - detail: senderAddress || fallback, - }, - moblie: senderTel || (senderName ? '' : fallback), - name: senderName || fallback, - phone: senderTel || (senderName ? '' : fallback), - }; - })(), + sender: { + address: { + country: '中国', + city: listByWarehousePlatformCode.city_name, + province: listByWarehousePlatformCode.province_name, + district: listByWarehousePlatformCode.district_name, + town: listByWarehousePlatformCode.town_name || null, + detail: listByWarehousePlatformCode.address, + }, + moblie: listByWarehousePlatformCode.sender_tel, + name: listByWarehousePlatformCode.sender_name, + phone: listByWarehousePlatformCode.sender_tel, + }, trade_order_info_dtos: tradeOrderList, wp_code: listByWarehousePlatformCode && listByWarehousePlatformCode.express ? (listByWarehousePlatformCode.express.PDD || '') @@ -2581,10 +2548,10 @@ class ExpressPlatformService extends MainService { // 自动同步回传:快递号分配成功后异步触发订单同步 try { const settlementEntries = Array.from(settlementRelationMap.entries()); - for (const [key, relation] of settlementEntries) { + for (const [ key, relation ] of settlementEntries) { const successCount = Number(relation && relation.success_count) || 0; if (successCount <= 0) continue; - const [storeId, warehouseId] = key.split(':').map(Number); + const [ storeId, warehouseId ] = key.split(':').map(Number); if (!storeId || !warehouseId) continue; const contractConfig = await this.service.systems.storeWarehouse.getContractConfig( diff --git a/app/service/systems/inbound_direct_log.js b/app/service/systems/inbound_direct_log.js index 6ea3993..31d9991 100644 --- a/app/service/systems/inbound_direct_log.js +++ b/app/service/systems/inbound_direct_log.js @@ -13,13 +13,16 @@ const Service = require('egg').Service; class InboundDirectLogService extends Service { /** - * 获取入库单的受控入库信息。 - * 返回入库单基本信息、明细列表,以及每项明细已有的导入/PDA 入库记录。 + * 获取入库单的受控入库信息(精简版)。 + * 返回入库单基本信息、明细列表(含计划数量与已完成数量)、收货单绑定关系。 * @param {string} entryOrderCode 入库单号 * @return {Promise} code/data/message 结构 + * - data.entryOrder: { id, entry_order_code, order_status, store_remask } + * - data.items: [{ id, stock_id, planned, completed, stock, bindings }] + * - data.receivingBindings: 收货单绑定关系列表 */ async getItems(entryOrderCode) { - const { ctx } = this; + const { ctx, app } = this; const code = String(entryOrderCode || '').trim(); if (!code) { @@ -67,22 +70,19 @@ class InboundDirectLogService extends Service { return { code: 404, message: '入库单不存在或无权访问', data: null }; } + // 查询货主商家备注 + const storeWarehouse = await ctx.model.StoreWarehouse.findOne({ + where: { store_id: entryOrder.store_id, warehouse_id: entryOrder.warehouse_id }, + attributes: [ 'store_remask' ], + raw: true, + }); + // 查询该入库单下已有的导入/PDA 入库记录 const directLogs = await ctx.model.InboundDirectLog.findAll({ where: { entry_order_id: entryOrder.id }, order: [[ 'created_at', 'ASC' ]], }); - // 按 stock_id 汇总已入库数量 - const logSummary = {}; - for (const log of directLogs) { - const key = String(log.stock_id); - if (!logSummary[key]) { - logSummary[key] = 0; - } - logSummary[key] += Number(log.quantity); - } - // 将直接入库记录按 entry_item_id 关联到明细 const itemDirectLogs = {}; for (const log of directLogs) { @@ -96,6 +96,7 @@ class InboundDirectLogService extends Service { stock_id: log.stock_id, quantity: log.quantity, inbound_type: log.inbound_type, + space_id: log.space_id, remark: log.remark, operator_id: log.operator_id, operator_name: log.operator_name, @@ -112,30 +113,134 @@ class InboundDirectLogService extends Service { })) : []; - // 组装明细 + // 收集所有 stock_id,通过 getStockDetails 批量获取带缓存的商品详情 + const stockIds = [ ...new Set( + (entryOrder.items || []) + .map(item => Number(item.stock_id)) + .filter(id => id && id > 0) + ) ]; + + /** @type {Map} */ + const stockMap = new Map(); + if (stockIds.length > 0) { + const warehouseId = ctx.user.store_id; + const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(stockIds, { warehouseId }); + for (const detail of stockDetails) { + stockMap.set(detail.id, detail); + } + } + + // 组装明细(精简字段,突出已入/总数) const items = (entryOrder.items || []).map(item => { const planQty = Number(item.count) || 0; const logKey = String(item.id); const logs = itemDirectLogs[logKey] || []; const directInQty = logs.reduce((sum, l) => sum + Number(l.quantity), 0); - // 入库进度使用已收货数量 + 导入/PDA 已入库数量 - const totalInboundQty = directInQty + Number(item.received_quantity || 0); return { id: item.id, stock_id: item.stock_id, - count: planQty, - received_quantity: Number(item.received_quantity) || 0, - item_code: item.item_code, - warehouse_item_code: (item.stock && item.stock.item_code) || '', - warehouse_item_name: (item.stock && item.stock.item_name) || '', - warehouse_item_spec: (item.stock && item.stock.sku_property) || '', - direct_inbound_quantity: directInQty, - remaining_quantity: Math.max(0, planQty - totalInboundQty), - direct_logs: logs, + planned: planQty, + completed: directInQty, + stock: stockMap.get(Number(item.stock_id)) || null, }; }); + // 收集所有 InboundDirectLog 中的 space_id,批量查询库位名称 + /** @type {Map} space_id -> space_name */ + const spaceNameMap = new Map(); + const allSpaceIds = [ ...new Set( + Object.values(itemDirectLogs) + .flat() + .map(log => log.space_id) + .filter(id => id != null) + ) ]; + if (allSpaceIds.length > 0) { + const spaces = await ctx.model.LocationSpace.findAll({ + where: { id: { [app.Sequelize.Op.in]: allSpaceIds } }, + attributes: [ 'id', 'custom_name', 'space_code' ], + raw: true, + }); + for (const sp of spaces) { + spaceNameMap.set(sp.id, sp.custom_name || sp.space_code || ''); + } + } + + // 批量查询已绑定的收货明细列表 + const entryItemIds = items.map(i => i.id).filter(Boolean); + /** @type {Map>} 按 entry_item_id 分组 */ + const bindingsMap = new Map(); + if (entryItemIds.length > 0) { + // 1. 查绑定关系表 + const bindingRows = await ctx.model.EntryReceivingBinding.findAll({ + where: { + entry_item_id: { [app.Sequelize.Op.in]: entryItemIds }, + deleted_at: null, + }, + attributes: [ 'id', 'entry_item_id', 'receiving_detail_id', 'allocated_quantity', 'status' ], + raw: true, + }); + + if (bindingRows.length > 0) { + // 2. 验证收货明细存在性(仅校验,不取冗余字段) + const detailIds = [ ...new Set(bindingRows.map(b => b.receiving_detail_id).filter(Boolean)) ]; + const validDetailIds = new Set(); + if (detailIds.length > 0) { + const details = await ctx.model.ReceivingDetail.findAll({ + where: { id: { [app.Sequelize.Op.in]: detailIds } }, + attributes: [ 'id' ], + raw: true, + }); + for (const d of details) { + validDetailIds.add(d.id); + } + } + + // 3. 按 entry_item_id 分组,只保留核心字段 + for (const b of bindingRows) { + const key = b.entry_item_id; + if (!bindingsMap.has(key)) { + bindingsMap.set(key, []); + } + bindingsMap.get(key).push({ + detail_id: b.receiving_detail_id, + binding_id: b.id, + allocated_quantity: b.allocated_quantity || 0, + }); + } + } + } + + // 将 bindings 挂到对应 item,并补充库位信息(space_id/space_name 来自 InboundDirectLog) + for (const item of items) { + const bindings = bindingsMap.get(item.id) || []; + const logKey = String(item.id); + const directLogs = itemDirectLogs[logKey] || []; + + // 从 InboundDirectLog 中提取 space_id,并解析库位名称 + // 如果 bindings 为空但有 directLog 带 space_id,则构造一条 binding 展示库位信息 + if (bindings.length === 0 && directLogs.length > 0) { + const firstWithSpace = directLogs.find(l => l.space_id); + if (firstWithSpace) { + item.bindings = [{ + space_id: firstWithSpace.space_id, + space_name: spaceNameMap.get(Number(firstWithSpace.space_id)) || '', + }]; + } else { + item.bindings = []; + } + } else { + // 如果有 bindings,取第一条带 space_id 的 directLog 补充 + const firstWithSpace = directLogs.find(l => l.space_id); + const sid = firstWithSpace ? firstWithSpace.space_id : null; + item.bindings = bindings.map(b => ({ + ...b, + space_id: sid, + space_name: sid != null ? (spaceNameMap.get(Number(sid)) || '') : '', + })); + } + } + return { code: 200, message: '查询成功', @@ -143,33 +248,22 @@ class InboundDirectLogService extends Service { entryOrder: { id: entryOrder.id, entry_order_code: entryOrder.entry_order_code, - order_type: entryOrder.order_type, order_status: entryOrder.order_status, - source_type: entryOrder.source_type, - warehouse_id: entryOrder.warehouse_id, - store_id: entryOrder.store_id, - remark: entryOrder.remark, + store_remask: (storeWarehouse && storeWarehouse.store_remask) || '', }, items, - direct_logs: directLogs, receivingBindings, - summary: { - total_items: items.length, - total_planned: items.reduce((s, i) => s + i.count, 0), - total_direct_inbound: items.reduce((s, i) => s + i.direct_inbound_quantity, 0), - total_import: directLogs.filter(l => l.inbound_type === 'import').reduce((s, l) => s + Number(l.quantity), 0), - total_pda: directLogs.filter(l => l.inbound_type === 'pda').reduce((s, l) => s + Number(l.quantity), 0), - }, }, }; } /** * 单条校验并写入一条导入/PDA 入库记录。 - * @param {Object} ctx + * @param {Object} ctx Egg.js 上下文对象 * @param {Object} entryOrder 入库单实例 - * @param {Object} item { stock_id, quantity, inbound_type, remark } - * @return {Promise<{ok: boolean, log?: Object, error?: Object}>} + * @param {Object} item 入库项,包含 stock_id、quantity、inbound_type、remark、space_id + * @param {Object} [transaction] Sequelize 事务对象,可选 + * @return {Promise<{ok: boolean, log?: Object, error?: Object}>} 返回操作结果,ok 为 true 时 log 包含入库记录详情,ok 为 false 时 error 包含错误信息 */ async _addSingleItem(ctx, entryOrder, item, transaction) { const stockId = Number(item.stock_id || 0); @@ -177,17 +271,70 @@ class InboundDirectLogService extends Service { const inboundType = String(item.inbound_type || '').trim().toLowerCase(); const remark = item.remark ? String(item.remark).trim() : ''; const spaceId = item.space_id ? Number(item.space_id) : null; + const receivingDetailId = Number(item.receiving_detail_id || 0); + const isBindingMode = receivingDetailId > 0; if (!stockId) { return { ok: false, error: { code: 400, message: 'items[].stock_id 必填' } }; } - if (!quantity || quantity <= 0 || !Number.isFinite(quantity)) { - return { ok: false, error: { code: 400, message: 'items[].quantity 必须为正整数' } }; + + // 绑定模式下必须传 space_id + if (isBindingMode && !spaceId) { + return { ok: false, error: { code: 400, message: '绑定收货明细时必须指定 space_id' } }; } + + // 非绑定模式下校验 quantity 必填且为正整数 + if (!isBindingMode) { + if (!quantity || quantity <= 0 || !Number.isFinite(quantity)) { + return { ok: false, error: { code: 400, message: 'items[].quantity 必须为正整数' } }; + } + } + if (![ 'import', 'pda' ].includes(inboundType)) { return { ok: false, error: { code: 400, message: 'items[].inbound_type 必须为 import 或 pda' } }; } + // 确定有效数量:绑定模式下自动计算收货明细的可用数量(actual_quantity - 已绑定数量) + let effectiveQuantity = quantity; + if (isBindingMode) { + // 查询收货明细 + const receivingDetail = await ctx.model.ReceivingDetail.findOne({ + where: { id: receivingDetailId }, + ...(transaction ? { transaction } : {}), + }); + if (!receivingDetail) { + return { ok: false, error: { code: 400, message: `收货明细不存在(id=${receivingDetailId})` } }; + } + // 绑定模式下 stock_id 必须匹配收货明细的 system_product_id + if (receivingDetail.system_product_id !== stockId) { + return { ok: false, error: { code: 400, message: `收货明细的商品(system_product_id=${receivingDetail.system_product_id})与传入的 stock_id(${stockId})不匹配` } }; + } + + // 查询该收货明细已被占用的数量(pending + committed) + const allocatedSum = await ctx.model.query( + `SELECT COALESCE(SUM(allocated_quantity), 0) AS total + FROM wms_entry_receiving_binding + WHERE receiving_detail_id = :rdId AND status IN ('pending', 'committed') AND deleted_at IS NULL`, + { + replacements: { rdId: receivingDetailId }, + type: ctx.model.QueryTypes.SELECT, + ...(transaction ? { transaction } : {}), + } + ); + const usedQty = Number(allocatedSum?.[0]?.total || 0); + const actualQty = Number(receivingDetail.actual_quantity) || 0; + effectiveQuantity = actualQty - usedQty; + if (effectiveQuantity <= 0) { + return { + ok: false, + error: { + code: 400, + message: `收货明细可用数量不足:实际数量 ${actualQty},已占用 ${usedQty},可用 ${effectiveQuantity}`, + }, + }; + } + } + // 查找入库单中该 stock_id 对应的所有明细,累加计划数量 const entryItems = await ctx.model.EntryItems.findAll({ where: { order_id: entryOrder.id, stock_id: stockId }, @@ -198,7 +345,7 @@ class InboundDirectLogService extends Service { return { ok: false, error: { code: 400, message: `入库单中不存在 stock_id=${stockId} 的商品` } }; } - const totalPlanQty = entryItems.reduce((sum, item) => sum + (Number(item.count) || 0), 0); + const totalPlanQty = entryItems.reduce((sum, ei) => sum + (Number(ei.count) || 0), 0); // 计算该 stock_id 在该入库单下已有的导入/PDA 入库总量 const logWhere = { entry_order_id: entryOrder.id, stock_id: stockId }; @@ -210,32 +357,37 @@ class InboundDirectLogService extends Service { }); const existingTotal = existingLogs.reduce((sum, log) => sum + Number(log.quantity), 0); - const newTotal = existingTotal + quantity; - - if (newTotal > totalPlanQty) { - return { - ok: false, - error: { - code: 400, - message: `入库数量超过计划:商品计划 ${totalPlanQty},已入库 ${existingTotal},本次 ${quantity},合计 ${newTotal}`, - data: { - stock_id: stockId, - plan_quantity: totalPlanQty, - existing_quantity: existingTotal, - requested_quantity: quantity, - exceeded_by: newTotal - totalPlanQty, + // 绑定模式下跳过入库单计划数量校验(允许超过计划数量) + // 只有 PENDING 非绑定模式限制超量;CREATED 人工导入允许超过 + const isManualImport = entryOrder.order_status === 'CREATED' && !isBindingMode; + if (!isBindingMode && !isManualImport) { + const newTotal = existingTotal + effectiveQuantity; + if (newTotal > totalPlanQty) { + return { + ok: false, + error: { + code: 400, + message: `入库数量超过计划:商品计划 ${totalPlanQty},已入库 ${existingTotal},本次 ${effectiveQuantity},合计 ${newTotal}`, + data: { + stock_id: stockId, + plan_quantity: totalPlanQty, + existing_quantity: existingTotal, + requested_quantity: effectiveQuantity, + exceeded_by: newTotal - totalPlanQty, + }, }, - }, - }; + }; + } } + const newTotal = existingTotal + effectiveQuantity; + // 写入记录 - const createOpts = transaction ? { transaction } : {}; const log = await ctx.model.InboundDirectLog.create({ warehouse_id: entryOrder.warehouse_id, store_id: entryOrder.store_id, stock_id: stockId, - quantity, + quantity: effectiveQuantity, inbound_type: inboundType, entry_order_id: entryOrder.id, entry_order_code: entryOrder.entry_order_code, @@ -244,72 +396,171 @@ class InboundDirectLogService extends Service { operator_id: ctx.user?.employees_id || ctx.user?.id || null, operator_name: ctx.user?.employees_name || '', created_at: new Date(), - }); + }, transaction ? { transaction } : {}); + + // 收货单明细绑定(可选) + let receivingBindResult = null; + if (isBindingMode) { + // 绑定模式:全量绑定,allocated_quantity = effectiveQuantity + item.allocated_quantity = effectiveQuantity; + receivingBindResult = await this._bindReceivingDetail( + ctx, entryOrder, item, stockId, receivingDetailId, effectiveQuantity, transaction + ); + } else if (receivingDetailId) { + receivingBindResult = await this._bindReceivingDetail( + ctx, entryOrder, item, stockId, receivingDetailId, effectiveQuantity, transaction + ); + } return { ok: true, log: { id: log.id, stock_id: stockId, - quantity, + quantity: effectiveQuantity, inbound_type: inboundType, space_id: spaceId, plan_quantity: totalPlanQty, existing_before: existingTotal, existing_after: newTotal, remaining: Math.max(0, totalPlanQty - newTotal), + ...(receivingBindResult ? { receivingBindResult } : {}), }, }; } + /** + * 将入库直接记录绑定到收货单明细(预占模式,status='pending')。 + * 校验收货明细存在、未取消、可用数量足够后,写入 wms_entry_receiving_binding 并确保主表绑定存在。 + * @param {Object} ctx Egg.js 上下文对象 + * @param {Object} entryOrder 入库单实例 + * @param {Object} item 入库项参数,包含 allocated_quantity、item_code 等可选字段 + * @param {number} stockId 商品SKU ID + * @param {number} receivingDetailId 收货单明细ID + * @param {number} quantity 本次入库数量 + * @param {Object} [transaction] Sequelize 事务对象,可选 + * @return {Promise} 返回绑定结果 { binding_id, receiving_detail_id, allocated_quantity, status } + */ + async _bindReceivingDetail(ctx, entryOrder, item, stockId, receivingDetailId, quantity, transaction) { + // 确定预分配数量:优先用 allocated_quantity,否则回退到 quantity + let allocatedQty = Number(item.allocated_quantity || 0); + if (!allocatedQty || allocatedQty <= 0) { + allocatedQty = quantity; + } + if (!Number.isFinite(allocatedQty) || allocatedQty <= 0) { + return { error: 'allocated_quantity 必须为正整数' }; + } + if (allocatedQty > quantity) { + return { error: `allocated_quantity(${allocatedQty}) 不能大于入库数量(${quantity})` }; + } + + // 1. 查询收货明细行(锁定) + const receivingDetail = await ctx.model.ReceivingDetail.findOne({ + where: { id: receivingDetailId }, + ...(transaction ? { lock: transaction.LOCK?.UPDATE, transaction } : {}), + }); + if (!receivingDetail) { + return { error: `收货明细不存在(id=${receivingDetailId})` }; + } + + // 2. 查询已占用(pending + committed)的分配量 + const allocatedSum = await ctx.model.query( + `SELECT COALESCE(SUM(allocated_quantity), 0) AS total + FROM wms_entry_receiving_binding + WHERE receiving_detail_id = :rdId AND status IN ('pending', 'committed') AND deleted_at IS NULL`, + { + replacements: { rdId: receivingDetailId }, + type: ctx.model.QueryTypes.SELECT, + ...(transaction ? { transaction } : {}), + } + ); + const usedQty = Number(allocatedSum?.[0]?.total || 0); + const availableQty = (Number(receivingDetail.actual_quantity) || 0) - usedQty; + if (allocatedQty > availableQty) { + return { + error: `收货明细可用数量不足: 可用${availableQty}, 请求${allocatedQty}`, + available_quantity: availableQty, + requested_quantity: allocatedQty, + }; + } + + // 3. 查找入库明细行(entry_item_id) + const entryItem = await ctx.model.EntryItems.findOne({ + where: { + order_id: entryOrder.id, + stock_id: stockId, + }, + ...(transaction ? { transaction } : {}), + }); + + // 4. 写入绑定(status='pending',预占不提交) + const binding = await ctx.model.EntryReceivingBinding.create({ + entry_item_id: entryItem?.id || 0, + receiving_detail_id: receivingDetailId, + allocated_quantity: allocatedQty, + status: 'pending', + creator_id: ctx.user?.id || 0, + }, transaction ? { transaction } : {}); + + return { + binding_id: binding.id, + receiving_detail_id: receivingDetailId, + allocated_quantity: allocatedQty, + status: 'pending', + }; + } + /** * 按商品增量添加导入/PDA 入库记录(支持单条和批量)。 * * 单条模式(兼容旧调用): - * { entry_order_code, stock_id, quantity, inbound_type, remark } + * { entry_order_id, stock_id, quantity, inbound_type, remark } * * 批量模式(推荐): - * { entry_order_code, items: [{ stock_id, quantity, inbound_type, remark }] } + * { entry_order_id, items: [{ stock_id, quantity, inbound_type, remark }] } * * 批量模式下所有商品共享同一个入库单状态校验,任一商品校验失败整批拒绝。 * 若该商品在当前入库单中的累计入库量超过计划数量则拒绝。 - * @param {Object} params - * @param {string} params.entry_order_code 入库单号 + * + * 可选收货单明细绑定(批量模式下 items 元素支持): + * { ..., receiving_detail_id, allocated_quantity } + * 传入 receiving_detail_id 后,将校验收货明细可用数量并写入 wms_entry_receiving_binding(status='pending' 预占)。 + * @param {Object} params 请求参数对象 + * @param {number} params.entry_order_id 入库单ID * @param {number} [params.stock_id] 商品SKU ID(单条模式) * @param {number} [params.quantity] 本次入库数量(单条模式) * @param {string} [params.inbound_type] 入库方式(单条模式) * @param {Array} [params.items] 商品列表(批量模式) * @param {string} [params.remark] 备注(单条模式) - * @return {Promise} code/data/message 结构 + * @param {number} [params.receiving_detail_id] 收货单明细ID(单条模式,可选,传入后触发预占绑定) + * @param {number} [params.allocated_quantity] 预分配数量(单条模式,可选,默认等于 quantity) + * @return {Promise} 返回 { code, message, data },code=200 表示成功 */ async addItem(params) { const { ctx } = this; - const entryOrderCode = String(params.entry_order_code || '').trim(); + const warehouseId = ctx.user.store_id; + const entryOrderId = Number(params.entry_order_id) || 0; - if (!entryOrderCode) { - return { code: 400, message: 'entry_order_code 必填', data: null }; + if (!entryOrderId || entryOrderId <= 0) { + return { code: 400, message: 'entry_order_id 必填', data: null }; } // 判断批量/单条模式 const isBatch = Array.isArray(params.items) && params.items.length > 0; const items = isBatch ? params.items : [{ stock_id: params.stock_id, + space_id: params.space_id, quantity: params.quantity, inbound_type: params.inbound_type, remark: params.remark, + receiving_detail_id: params.receiving_detail_id, + allocated_quantity: params.allocated_quantity, }]; - // 查找入库单 - const entryOrder = await ctx.model.EntryOrder.findOne({ - where: { - entry_order_code: entryOrderCode, - warehouse_id: ctx.user.store_id, - is_enabled: 1, - deleted_at: null, - }, - }); + // 通过主键查找入库单 + const entryOrder = await ctx.model.EntryOrder.findByPk(entryOrderId); - if (!entryOrder) { + if (!entryOrder || entryOrder.warehouse_id !== warehouseId) { return { code: 404, message: '入库单不存在或无权访问', data: null }; } @@ -321,6 +572,28 @@ class InboundDirectLogService extends Service { return { code: 400, message: '已完成的入库单不允许操作', data: null }; } + // 检查接入库单是否已绑定收货单 + const hasReceivingBindings = await ctx.model.EntryOrderReceiving.findOne({ + where: { entry_order_id: entryOrder.id, deleted_at: null }, + }); + + // CREATED + 已绑定 → 拒绝(需先走 reviewEntry 审核) + if (entryOrder.order_status === 'CREATED' && hasReceivingBindings) { + return { code: 400, message: '入库单已绑定收货单且状态为 CREATED,请先审核后再进行上架操作', data: null }; + } + + // PENDING 状态校验 + if (entryOrder.order_status === 'PENDING') { + if (!hasReceivingBindings) { + return { code: 400, message: '入库单未绑定收货单,无法上架', data: null }; + } + for (const item of items) { + if (!item.receiving_detail_id) { + return { code: 400, message: '随机入库需要选定收货单明细提交,缺少 receiving_detail_id', data: null }; + } + } + } + // 批量模式下用事务包裹,任一失败整批回退 const useTransaction = isBatch; const txn = useTransaction ? await ctx.model.transaction() : null; @@ -389,9 +662,9 @@ class InboundDirectLogService extends Service { /** * 移除一条导入/PDA 入库记录(仅限未提交的入库单)。 - * @param {Object} params + * @param {Object} params 请求参数对象 * @param {number} params.id 入库记录ID(wms_inbound_direct_log.id) - * @return {Promise} code/data/message 结构 + * @return {Promise} 返回 { code, message, data },code=200 表示移除成功 */ async removeItem(params) { const { ctx } = this; @@ -462,28 +735,25 @@ class InboundDirectLogService extends Service { } /** - * 提交确认完成入库,将导入/PDA 入库记录写入库存,并触发奇门/API 回传。 - * @param {string} entryOrderCode 入库单号 + * 提交确认完成入库(先同步后写库模式)。 + * 先调用 qimenEntrySync 进行奇门/API 回传,成功后在 onSuccess 回调内开启事务写入库存。 + * 同步失败则只写 FAILED 状态 + 操作日志,不写库存。 + * @param {number} entryOrderId 入库单 ID * @return {Promise} code/data/message 结构 */ - async commit(entryOrderCode) { + async commit(entryOrderId) { const { ctx, app } = this; - const code = String(entryOrderCode || '').trim(); + const warehouseId = ctx.user.store_id; + const entryOrderIdNum = Number(entryOrderId) || 0; - if (!code) { - return { code: 400, message: 'entry_order_code 必填', data: null }; + if (!entryOrderIdNum || entryOrderIdNum <= 0) { + return { code: 400, message: 'entry_order_id 必填', data: null }; } - const entryOrder = await ctx.model.EntryOrder.findOne({ - where: { - entry_order_code: code, - warehouse_id: ctx.user.store_id, - is_enabled: 1, - deleted_at: null, - }, - }); + // 通过主键查找入库单 + const entryOrder = await ctx.model.EntryOrder.findByPk(entryOrderIdNum); - if (!entryOrder) { + if (!entryOrder || entryOrder.warehouse_id !== warehouseId) { return { code: 404, message: '入库单不存在或无权访问', data: null }; } @@ -520,179 +790,287 @@ class InboundDirectLogService extends Service { return { code: 400, message: '入库单无明细', data: null }; } - const warehouseId = entryOrder.warehouse_id; const storeId = entryOrder.store_id; - const transaction = await ctx.model.transaction(); - try { - // 记录已处理过的 stock_id,避免同 stock_id 多明细重复写库存 - const processedStockIds = new Set(); + // ===== 阶段一:先同步奇门/API(事务外) ===== + const items = entryItems.map((item, idx) => ({ + orderLineNo: idx + 1, + ownerCode: item.owner_code || '', + itemCode: item.item_code || '', + itemId: item.item_id || '', + inventoryType: item.inventory_type || 'ZP', + planQty: Number(item.count) || 0, + actualQty: Number(item.count) || 0, + })); - // 逐商品写入库存 - for (const item of entryItems) { - const stockId = item.stock_id; - if (!stockId) continue; + const syncResult = await this.qimenEntrySync({ + entryOrder, + orderLines: items, + outBizCode: `DIRECT_INBOUND_${Date.now()}`, + remark: '导入/PDA直接入库提交', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + // ===== 阶段二:同步成功后在 onSuccess 内开启事务写入库存 ===== + onSuccess: async eo => { + const transaction = await ctx.model.transaction(); - const inboundQty = stockSummary[String(stockId)] || 0; - if (inboundQty <= 0) continue; + try { + const processedStockIds = new Set(); - // 更新入库明细的 received_quantity(按该明细的计划占比分配) - const planQty = Number(item.count) || 0; - const itemReceivedQty = planQty > 0 ? Math.min(planQty, inboundQty) : inboundQty; - await ctx.model.EntryItems.update({ - received_quantity: itemReceivedQty, - }, { - where: { id: item.id }, - transaction, - }); + // 查询 pending 绑定:entry_item_id → 收货明细ID + const entryItemIds = entryItems.map(ei => ei.id); + const pendingBindings = await ctx.model.EntryReceivingBinding.findAll({ + where: { entry_item_id: entryItemIds, status: 'pending', deleted_at: null }, + attributes: [ 'id', 'entry_item_id', 'receiving_detail_id' ], + raw: true, + }); - // 同一 stock_id 只写一次库存 - if (processedStockIds.has(String(stockId))) continue; - processedStockIds.add(String(stockId)); + // 查收货明细详情,构建 entry_item_id → 明细信息 的映射 + const detailIds = [ ...new Set(pendingBindings.map(b => b.receiving_detail_id)) ]; + const bindingDetailMap = new Map(); + if (detailIds.length > 0) { + const details = await ctx.model.ReceivingDetail.findAll({ + where: { id: detailIds }, + attributes: [ 'id', 'receiving_id', 'batch_number', 'production_date', 'expiry_date' ], + raw: true, + }); + const detailById = new Map(details.map(d => [ d.id, d ])); + for (const b of pendingBindings) { + const d = detailById.get(b.receiving_detail_id); + if (d) bindingDetailMap.set(b.entry_item_id, d); + } + } - // 使用入库单号作为批次号 - const batchNo = entryOrder.entry_order_code; - const inventoryType = item.inventory_type || 'ZP'; + // 逐商品写入库存 + for (const item of entryItems) { + const stockId = item.stock_id; + if (!stockId) continue; - // 从该 stock_id 的入库记录中取第一个非空 space_id,兜底 1 - const logForSpace = directLogs.find(l => String(l.stock_id) === String(stockId) && l.space_id); - const spaceId = logForSpace ? Number(logForSpace.space_id) : 1; + const inboundQty = stockSummary[String(stockId)] || 0; + if (inboundQty <= 0) continue; - // 锁定并更新 StockWarehouse 总库存 - const stockRecord = await ctx.model.StockWarehouse.findOne({ - where: { id: stockId, is_valid: 'Y', deleted_at: null }, - lock: transaction.LOCK.UPDATE, - transaction, - }); + // 更新入库明细的 received_quantity(按该明细的计划占比分配) + const planQty = Number(item.count) || 0; + const itemReceivedQty = planQty > 0 ? Math.min(planQty, inboundQty) : inboundQty; + await ctx.model.EntryItems.update({ + received_quantity: itemReceivedQty, + }, { + where: { id: item.id }, + transaction, + }); - if (stockRecord) { - const beforeQuantity = Number(stockRecord.quantity) || 0; - const beforeLockedQuantity = Number(stockRecord.locked_quantity) || 0; + // 同一 stock_id 只写一次库存 + if (processedStockIds.has(String(stockId))) continue; + processedStockIds.add(String(stockId)); - await stockRecord.increment('quantity', { by: inboundQty, transaction, silent: true }); - await stockRecord.reload({ transaction }); + // 使用入库单号作为批次号;若有收货绑定则使用收货明细信息 + const bindInfo = bindingDetailMap.get(item.id); + const rdReceivingId = bindInfo ? bindInfo.receiving_id : null; + const effectiveBatchNo = bindInfo?.batch_number || eo.entry_order_code; + const rdProductionDate = bindInfo?.production_date || null; + const rdExpiryDate = bindInfo?.expiry_date || null; + const batchNo = eo.entry_order_code; + const inventoryType = item.inventory_type || 'ZP'; - const afterQuantity = Number(stockRecord.quantity) || 0; - const afterLockedQuantity = Number(stockRecord.locked_quantity) || 0; + // 从该 stock_id 的入库记录中取第一个非空 space_id,兜底 1 + const logForSpace = directLogs.find(l => String(l.stock_id) === String(stockId) && l.space_id); + const spaceId = logForSpace ? Number(logForSpace.space_id) : 1; - // 写入库存流水 - await ctx.service.systems.stockTransaction.create({ - transaction_type: 'INBOUND', - warehouse_id: warehouseId, - store_id: storeId, - stock_id: stockId, - quantity: inboundQty, - batch_no: batchNo, - inventory_type: inventoryType, - order_type: entryOrder.order_type, - order_no: entryOrder.entry_order_code, - entry_order_id: entryOrder.id, - operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), - operator_name: ctx.user?.employees_name || '', - remark: '导入/PDA直接入库提交', - before_quantity: beforeQuantity, - after_quantity: afterQuantity, - before_locked_quantity: beforeLockedQuantity, - after_locked_quantity: afterLockedQuantity, - created_at: new Date(), - }, { transaction }); - } + // 锁定并更新 StockWarehouse 总库存 + const stockRecord = await ctx.model.StockWarehouse.findOne({ + where: { id: stockId, is_valid: 'Y', deleted_at: null }, + lock: transaction.LOCK.UPDATE, + transaction, + }); - // 创建/更新 Storage 库位库存 - const storageRecord = await ctx.model.Storage.findOne({ - where: { - space_id: spaceId, - stock_id: stockId, - batch_no: batchNo, - inventory_type: inventoryType, - is_enabled: 1, - delete_at: null, - }, - lock: transaction.LOCK.UPDATE, - transaction, - }); + if (stockRecord) { + const beforeQuantity = Number(stockRecord.quantity) || 0; + const beforeLockedQuantity = Number(stockRecord.locked_quantity) || 0; - if (storageRecord) { - await ctx.model.Storage.update({ - quantity: app.Sequelize.literal(`quantity + ${inboundQty}`), - available_quantity: app.Sequelize.literal(`available_quantity + ${inboundQty}`), - entry_order_id: entryOrder.id, - inbound_time: new Date(), - inbound_order_no: entryOrder.entry_order_code, + await stockRecord.increment('quantity', { by: inboundQty, transaction, silent: true }); + await stockRecord.reload({ transaction }); + + const afterQuantity = Number(stockRecord.quantity) || 0; + const afterLockedQuantity = Number(stockRecord.locked_quantity) || 0; + + // 写入库存流水 + await ctx.service.systems.stockTransaction.create({ + transaction_type: 'INBOUND', + warehouse_id: warehouseId, + store_id: storeId, + stock_id: stockId, + quantity: inboundQty, + batch_no: batchNo, + inventory_type: inventoryType, + order_type: eo.order_type, + order_no: eo.entry_order_code, + entry_order_id: eo.id, + operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), + operator_name: ctx.user?.employees_name || '', + remark: '导入/PDA直接入库提交', + before_quantity: beforeQuantity, + after_quantity: afterQuantity, + before_locked_quantity: beforeLockedQuantity, + after_locked_quantity: afterLockedQuantity, + created_at: new Date(), + }, { transaction }); + } + + // 创建/更新 Storage 库位库存 + const storageRecord = await ctx.model.Storage.findOne({ + where: { + space_id: spaceId, + stock_id: stockId, + batch_no: batchNo, + inventory_type: inventoryType, + is_enabled: 1, + delete_at: null, + }, + lock: transaction.LOCK.UPDATE, + transaction, + }); + + let storageId = null; + let storageBeforeQty = 0; + let storageAfterQty = 0; + + if (storageRecord) { + storageBeforeQty = Number(storageRecord.quantity) || 0; + storageAfterQty = storageBeforeQty + inboundQty; + + await ctx.model.Storage.update({ + quantity: app.Sequelize.literal(`quantity + ${inboundQty}`), + available_quantity: app.Sequelize.literal(`available_quantity + ${inboundQty}`), + entry_order_id: eo.id, + inbound_time: new Date(), + inbound_order_no: eo.entry_order_code, + production_date: rdProductionDate, + expiry_date: rdExpiryDate, + receiving_id: rdReceivingId, + updated_at: new Date(), + }, { + where: { id: storageRecord.id }, + transaction, + }); + storageId = storageRecord.id; + } else { + storageBeforeQty = 0; + storageAfterQty = inboundQty; + + const createdStorage = await ctx.model.Storage.create({ + warehouse_id: warehouseId, + store_id: storeId, + space_id: spaceId, + stock_id: stockId, + batch_no: effectiveBatchNo, + inventory_type: inventoryType, + quantity: inboundQty, + locked_quantity: 0, + available_quantity: inboundQty, + inbound_time: new Date(), + inbound_order_no: eo.entry_order_code, + receiving_id: rdReceivingId, + entry_order_id: eo.id, + supplier_id: null, + supplier_batch_no: null, + production_date: rdProductionDate, + expiry_date: rdExpiryDate, + is_enabled: 1, + created_at: new Date(), + updated_at: new Date(), + }, { transaction }); + storageId = createdStorage.id; + } + + // 写入库位维度库存流水 + await ctx.model.StorageTransaction.create({ + transaction_type: 'INBOUND', + warehouse_id: warehouseId, + store_id: storeId, + stock_id: stockId, + storage_id: storageId, + space_id: spaceId, + quantity: inboundQty, + before_quantity: storageBeforeQty, + after_quantity: storageAfterQty, + batch_no: effectiveBatchNo, + inventory_type: inventoryType, + order_type: 'entry_order', + order_no: eo.entry_order_code, + order_id: eo.id, + operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), + operator_name: ctx.user?.employees_name || '', + remark: '导入/PDA直接入库提交', + created_at: new Date(), + }, { transaction }); + } + + // 将 pending 绑定升级为 committed + if (pendingBindings.length > 0) { + await ctx.model.EntryReceivingBinding.update( + { status: 'committed', updated_at: new Date() }, + { where: { id: pendingBindings.map(b => b.id) }, transaction } + ); + } + + // 回写收货单和收货明细的入库状态 + await this._syncReceivingStorageStatus({ entryItemIds, transaction }); + + // 更新入库单状态为 COMPLETED + await eo.update({ + order_status: 'COMPLETED', + sync_status: 'SUCCESS', + sync_message: JSON.stringify({ + completedAt: new Date(), + totalQuantity: Object.values(stockSummary).reduce((s, q) => s + q, 0), + itemCount: processedStockIds.size, + source: 'direct_inbound', + }), updated_at: new Date(), - }, { - where: { id: storageRecord.id }, + }, { transaction }); + + // 记录操作日志(事务内) + const totalQty = Object.values(stockSummary).reduce((s, q) => s + q, 0); + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'entry_order', + businessId: eo.id, + operationCode: 'DIRECT_INBOUND_COMMIT', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: eo.warehouse_id, + message: `导入/PDA入库提交完成,共 ${processedStockIds.size} 种商品,总数量 ${totalQty}`, + }, transaction, }); - } else { - await ctx.model.Storage.create({ - warehouse_id: warehouseId, - store_id: storeId, - space_id: spaceId, - stock_id: stockId, - batch_no: batchNo, - inventory_type: inventoryType, - quantity: inboundQty, - locked_quantity: 0, - available_quantity: inboundQty, - inbound_time: new Date(), - inbound_order_no: entryOrder.entry_order_code, - receiving_id: null, - entry_order_id: entryOrder.id, - supplier_id: null, - supplier_batch_no: null, - is_enabled: 1, - created_at: new Date(), - updated_at: new Date(), - }, { transaction }); + + await transaction.commit(); + } catch (error) { + if (transaction && typeof transaction.rollback === 'function') { + await transaction.rollback(); + } + throw error; } - } - - // 更新入库单状态为 COMPLETED - await entryOrder.update({ - order_status: 'COMPLETED', - sync_status: 'SUCCESS', - sync_message: JSON.stringify({ - completedAt: new Date(), - totalQuantity: Object.values(stockSummary).reduce((s, q) => s + q, 0), - itemCount: processedStockIds.size, - source: 'direct_inbound', - }), - updated_at: new Date(), - }, { transaction }); - - // 记录操作日志(事务内) - const totalQty = Object.values(stockSummary).reduce((s, q) => s + q, 0); - await ctx.service.systems.operationLog.createOperationLog({ - businessType: 'entry_order', - businessId: entryOrder.id, - operationCode: 'DIRECT_INBOUND_COMMIT', - operator: { - id: ctx.user?.employees_id || ctx.user?.id, - name: ctx.user?.employees_name || '', - }, - extras: { - warehouseId: entryOrder.warehouse_id, - message: `导入/PDA入库提交完成,共 ${processedStockIds.size} 种商品,总数量 ${totalQty}`, - }, - transaction, - }); - - await transaction.commit(); - } catch (error) { - if (transaction && typeof transaction.rollback === 'function') { - await transaction.rollback(); - } - throw error; - } - - // 事务外:异步触发奇门/API 回传 - setImmediate(() => { - this._sendCallback(entryOrder).catch(err => { - ctx.logger.error(`[InboundDirectLog] 回传异常 entryOrderId=${entryOrder.id}: ${err.message}`, err.stack); - }); + }, }); + if (!syncResult.success) { + ctx.logger.warn(`[InboundDirectLog] commit 同步失败 entryOrderId=${entryOrder.id}: ${syncResult.message}`); + return { + code: 500, + message: syncResult.message, + data: { + id: entryOrder.id, + entry_order_code: entryOrder.entry_order_code, + sync_status: 'FAILED', + }, + }; + } + return { code: 200, message: '入库完成', @@ -707,110 +1085,16 @@ class InboundDirectLogService extends Service { }; } - /** - * 根据入库单来源异步回传(奇门 / OpenAPI)。 - * @param {Object} entryOrder 入库单实例 - * @return {Promise} - */ - async _sendCallback(entryOrder) { - const { ctx } = this; - const sourceType = String(entryOrder.source_type || '').toUpperCase(); - - ctx.logger.info( - `[InboundDirectLog] 准备回传 entryOrderId=${entryOrder.id} sourceType=${sourceType}` - ); - - try { - const items = await ctx.model.EntryItems.findAll({ - where: { order_id: entryOrder.id }, - attributes: [ 'item_code', 'item_id', 'count', 'inventory_type', 'owner_code', 'received_quantity' ], - raw: true, - }); - - if (!items || items.length === 0) { - ctx.logger.warn(`[InboundDirectLog] 回传:入库单无明细 entryOrderId=${entryOrder.id}`); - return; - } - - const orderLines = items.map((item, index) => ({ - orderLineNo: index + 1, - ownerCode: item.owner_code || '', - itemCode: item.item_code || '', - itemId: item.item_id || '', - inventoryType: item.inventory_type || 'ZP', - planQty: item.count || 0, - actualQty: item.received_quantity || 0, - })); - - if (sourceType === 'QM') { - await this._sendQimenCallback(entryOrder, orderLines); - } else if (sourceType === 'API') { - await this._sendOpenApiCallback(entryOrder); - } else { - ctx.logger.info(`[InboundDirectLog] 来源类型 ${sourceType} 不支持回传`); - } - } catch (error) { - ctx.logger.error(`[InboundDirectLog] _sendCallback 异常: ${error.message}`, error.stack); - } - } - - /** - * 奇门回传:调用 taobao.qimen.entryorder.confirm。 - * @param {Object} entryOrder 入库单 - * @param {Array} orderLines 明细行 - * @return {Promise} - */ - async _sendQimenCallback(entryOrder, orderLines) { - const { ctx, app } = this; - - try { - const queryData = { - request: { - entryOrder: { - entryOrderCode: entryOrder.entry_order_code, - ownerCode: entryOrder.qimen_owner_code || '', - warehouseCode: entryOrder.qimen_warehouse_code || '', - entryOrderId: entryOrder.id, - entryOrderType: entryOrder.order_type, - outBizCode: `DIRECT_INBOUND_${Date.now()}`, - confirmType: 0, - status: 'FULFILLED', - freight: 0, - operateTime: app.formatDate(new Date()), - remark: '导入/PDA直接入库提交', - }, - orderLines, - }, - }; - - const result = await app.qimenClient.send( - 'taobao.qimen.entryorder.confirm', - entryOrder.qimen_owner_code, - queryData, - { ctx } - ); - - const qimenResult = result && result.xmlArray && result.xmlArray.response; - if (qimenResult && String(qimenResult.flag) === 'success') { - ctx.logger.info(`[InboundDirectLog] 奇门回传成功 entryOrderId=${entryOrder.id}`); - } else { - ctx.logger.warn( - `[InboundDirectLog] 奇门回传失败 entryOrderId=${entryOrder.id} ` + - `message=${qimenResult?.message || '未知错误'}` - ); - } - } catch (error) { - ctx.logger.error(`[InboundDirectLog] 奇门回传异常: ${error.message}`, error.stack); - } - } - /** * OpenAPI 回传:查询 ApiApp 回调地址并 POST 回传。 * @param {Object} entryOrder 入库单 - * @return {Promise} + * @param {Object} [options] 可选配置 + * @param {boolean} [options.throwOnError=false] 失败时是否向外抛出异常 + * @return {Promise} 返回回传结果 { success, error?, statusCode?, body? },异常时返回 null */ - async _sendOpenApiCallback(entryOrder) { + async _sendOpenApiCallback(entryOrder, options = {}) { const { ctx, app } = this; + const { throwOnError = false } = options; try { const storeWarehouse = await ctx.model.StoreWarehouse.findOne({ @@ -824,11 +1108,13 @@ class InboundDirectLogService extends Service { }); if (!storeWarehouse) { - ctx.logger.warn( - '[InboundDirectLog] OpenAPI回传:未找到授权关系 ' + - `entryOrderId=${entryOrder.id}` - ); - return; + const warnMsg = `[InboundDirectLog] OpenAPI回传:未找到授权关系 entryOrderId=${entryOrder.id}`; + ctx.logger.warn(warnMsg); + console.log('[quickInbound] _sendOpenApiCallback 最终返回:', { success: false, error: '未找到授权关系' }); + if (throwOnError) { + throw new Error(warnMsg); + } + return null; } const apiApp = await ctx.model.ApiApp.findOne({ @@ -847,11 +1133,13 @@ class InboundDirectLogService extends Service { }); if (!apiApp || !apiApp.callback_url) { - ctx.logger.warn( - '[InboundDirectLog] OpenAPI回传:未找到有效ApiApp配置 ' + - `entryOrderId=${entryOrder.id}` - ); - return; + const warnMsg = `[InboundDirectLog] OpenAPI回传:未找到有效ApiApp配置 entryOrderId=${entryOrder.id}`; + ctx.logger.warn(warnMsg); + console.log('[quickInbound] _sendOpenApiCallback 最终返回:', { success: false, error: '未找到ApiApp配置' }); + if (throwOnError) { + throw new Error(warnMsg); + } + return null; } const callbackData = { @@ -861,6 +1149,13 @@ class InboundDirectLogService extends Service { inboundType: 'direct', }; + console.log('[quickInbound] _sendOpenApiCallback 发送前:', { + entryOrderId: entryOrder.id, + callbackUrl: apiApp.callback_url, + appKey: apiApp.self_app_key, + callbackData, + }); + const result = await ctx.service.openapi.callback.sendWithRetry({ callbackUrl: apiApp.callback_url, appKey: apiApp.self_app_key, @@ -873,19 +1168,376 @@ class InboundDirectLogService extends Service { }, }); + console.log('[quickInbound] _sendOpenApiCallback 响应:', { + entryOrderId: entryOrder.id, + success: result?.success, + statusCode: result?.statusCode, + error: result?.error, + body: typeof result?.body === 'string' ? result.body.substring(0, 500) : JSON.stringify(result?.body || {}).substring(0, 500), + }); + if (result.success) { ctx.logger.info( `[InboundDirectLog] OpenAPI回传成功 entryOrderId=${entryOrder.id} ` + `callbackUrl=${apiApp.callback_url}` ); } else { - ctx.logger.warn( - `[InboundDirectLog] OpenAPI回传失败 entryOrderId=${entryOrder.id} ` + - `error=${result.error}` - ); + const failMsg = `[InboundDirectLog] OpenAPI回传失败 entryOrderId=${entryOrder.id} error=${result.error}`; + ctx.logger.warn(failMsg); + if (throwOnError) { + throw new Error(failMsg); + } } + + console.log('[quickInbound] _sendOpenApiCallback 最终返回:', result); + return result; } catch (error) { ctx.logger.error(`[InboundDirectLog] OpenAPI回传异常: ${error.message}`, error.stack); + console.log('[quickInbound] _sendOpenApiCallback 最终返回 (异常):', { success: false, error: error.message }); + if (throwOnError) { + throw error; + } + return null; + } + } + + /** + * 奇门入库同步(统一入口)。 + * 先发奇门 entryorder.confirm 请求,成功才执行本地回调,失败则写操作日志并返回失败。 + * + * @param {Object} params 参数对象 + * @param {Object} params.entryOrder - 入库单完整对象(EntryOrder model instance) + * @param {Array} params.orderLines - 明细行数组 [{ orderLineNo, ownerCode, itemCode, itemId, inventoryType, planQty, actualQty }] + * @param {string} params.outBizCode - 外部业务编码(如 DIRECT_INBOUND_xxx) + * @param {string} params.remark - 备注(如 "导入/PDA直接入库提交") + * @param {boolean} [params.isFin=true] - 是否最终确认(confirmType: 0=最终, 1=部分) + * @param {Function} params.onSuccess - 同步成功后执行的回调(接收 entryOrder),在独立事务中执行,应包含业务写库 + operationLog(QUICK_INBOUND) + * @param {Object} params.operator - 操作人 { id, name },用于 operationLog + * @return {Promise} { success: boolean, message: string, data?: any } + */ + async qimenEntrySync(params) { + const { ctx, app } = this; + const { + entryOrder, + orderLines, + outBizCode, + remark, + isFin = true, + onSuccess, + operator, + } = params; + + console.log('[qimenEntrySync] 进入:', { + entryOrderId: entryOrder?.id, + entryOrderCode: entryOrder?.entry_order_code, + sourceType: entryOrder?.source_type, + orderLinesCount: orderLines?.length, + isFin, + }); + + // 1. 校验 + if (!orderLines || orderLines.length === 0) { + console.log('[qimenEntrySync] 最终判定: failure (行不能为空)'); + return { success: false, message: '行不能为空' }; + } + + // 2. 按来源类型分别处理 + const sourceType = String(entryOrder.source_type || '').toUpperCase(); + + if (sourceType !== 'QM' && sourceType !== 'API') { + const skipMsg = `来源类型 ${sourceType} 不支持回传`; + console.log(`[qimenEntrySync] 最终判定: 跳过 (${skipMsg})`); + ctx.logger.info(`[qimenEntrySync] ${skipMsg} entryOrderId=${entryOrder.id}`); + + // 不需要回传的来源类型,直接执行回调 + if (onSuccess) { + await onSuccess(entryOrder); + } + return { success: true, message: `无需同步,来源类型: ${sourceType}` }; + } + + // 3. 构造 queryData 并发请求(事务外) + if (sourceType === 'QM') { + const queryData = { + request: { + entryOrder: { + entryOrderCode: entryOrder.entry_order_code, + ownerCode: entryOrder.qimen_owner_code || '', + warehouseCode: entryOrder.qimen_warehouse_code || '', + entryOrderId: entryOrder.id, + entryOrderType: entryOrder.order_type, + outBizCode: outBizCode || `DIRECT_INBOUND_${Date.now()}`, + confirmType: isFin ? 0 : 1, + status: isFin ? 'FULFILLED' : 'PARTFULFILLED', + freight: 0, + operateTime: app.formatDate(new Date()), + remark: remark || '', + }, + orderLines, + }, + }; + + console.log('[qimenEntrySync] 奇门请求发送前:', { + entryOrderId: entryOrder.id, + api: 'taobao.qimen.entryorder.confirm', + ownerCode: entryOrder.qimen_owner_code, + queryData, + }); + + let qimenResult; + try { + const result = await app.qimenClient.send( + 'taobao.qimen.entryorder.confirm', + entryOrder.qimen_owner_code, + queryData, + { ctx } + ); + qimenResult = result?.xmlArray?.response; + } catch (err) { + qimenResult = { flag: 'error', code: '-1', message: err.message }; + } + + console.log('[qimenEntrySync] 奇门响应:', { + entryOrderId: entryOrder.id, + flag: qimenResult?.flag, + code: qimenResult?.code, + message: qimenResult?.message, + }); + + const isQimenSuccess = qimenResult && String(qimenResult.flag) === 'success'; + + if (!isQimenSuccess) { + const failMsg = qimenResult?.message || '奇门同步失败'; + console.log(`[qimenEntrySync] 最终判定: failure (${failMsg})`); + + const txn = await ctx.model.transaction(); + try { + await entryOrder.update({ + sync_status: 'FAILED', + sync_message: JSON.stringify({ + error: failMsg, + errorCode: 'QIMEN_FAILED', + errorTime: new Date().toISOString(), + source: 'qimenEntrySync', + }), + updated_at: new Date(), + }, { transaction: txn }); + + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'entry_order', + businessId: entryOrder.id, + operationCode: 'QUICK_INBOUND_FAILED', + operator: operator || {}, + extras: { warehouseId: entryOrder.warehouse_id, message: failMsg }, + transaction: txn, + }); + + await txn.commit(); + } catch (e) { + await txn.rollback(); + ctx.logger.error(`[qimenEntrySync] 失败日志写入异常: ${e.message}`); + } + + return { success: false, message: failMsg }; + } + + // 4. 成功:执行回调 + ctx.logger.info(`[qimenEntrySync] 奇门回传成功 entryOrderId=${entryOrder.id}`); + console.log('[qimenEntrySync] 最终判定: success'); + + if (onSuccess) { + await onSuccess(entryOrder); + } + + return { success: true, message: '同步成功' }; + } + + // API 来源:调用 OpenAPI 回传 + if (sourceType === 'API') { + console.log('[qimenEntrySync] OpenAPI 回传开始:', { + entryOrderId: entryOrder.id, + }); + + let apiResult; + try { + apiResult = await this._sendOpenApiCallback(entryOrder, { throwOnError: true }); + } catch (err) { + apiResult = { success: false, error: err.message }; + } + + console.log('[qimenEntrySync] OpenAPI 回传结果:', apiResult); + + const isApiSuccess = apiResult && apiResult.success === true; + + if (!isApiSuccess) { + const failMsg = apiResult?.error || 'API回传失败'; + console.log(`[qimenEntrySync] 最终判定: failure (${failMsg})`); + + const txn = await ctx.model.transaction(); + try { + await entryOrder.update({ + sync_status: 'FAILED', + sync_message: JSON.stringify({ + error: failMsg, + errorCode: 'API_FAILED', + errorTime: new Date().toISOString(), + source: 'qimenEntrySync', + }), + updated_at: new Date(), + }, { transaction: txn }); + + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'entry_order', + businessId: entryOrder.id, + operationCode: 'QUICK_INBOUND_FAILED', + operator: operator || {}, + extras: { warehouseId: entryOrder.warehouse_id, message: failMsg }, + transaction: txn, + }); + + await txn.commit(); + } catch (e) { + await txn.rollback(); + ctx.logger.error(`[qimenEntrySync] API失败日志写入异常: ${e.message}`); + } + + return { success: false, message: failMsg }; + } + + ctx.logger.info(`[qimenEntrySync] OpenAPI回传成功 entryOrderId=${entryOrder.id}`); + console.log('[qimenEntrySync] 最终判定: success (API)'); + + if (onSuccess) { + await onSuccess(entryOrder); + } + + return { success: true, message: '同步成功' }; + } + } + + /** + * 根据已提交(committed)的入库明细-收货明细绑定,回写收货单及收货明细的入库状态。 + * 在事务内执行,读取 committed 绑定并按 receiving_detail_id 汇总。 + * + * @param {Object} params 参数 + * @param {number[]} params.entryItemIds 当前入库单的所有明细 ID 列表 + * @param {Object} params.transaction Sequelize 事务对象 + * @return {Promise} + */ + async _syncReceivingStorageStatus({ entryItemIds, transaction }) { + const { ctx } = this; + + // 查询所有 committed 状态的绑定记录 + const committedBindings = await ctx.model.EntryReceivingBinding.findAll({ + where: { + entry_item_id: entryItemIds, + status: 'committed', + deleted_at: null, + }, + attributes: [ 'receiving_detail_id', 'allocated_quantity' ], + raw: true, + transaction, + }); + + if (!committedBindings || committedBindings.length === 0) { + return; + } + + // 按 receiving_detail_id 汇总 allocated_quantity + const detailQuantityMap = new Map(); + for (const b of committedBindings) { + const detailId = b.receiving_detail_id; + const qty = Number(b.allocated_quantity) || 0; + detailQuantityMap.set(detailId, (detailQuantityMap.get(detailId) || 0) + qty); + } + + const detailIds = [ ...detailQuantityMap.keys() ]; + + // 查询收货明细(含 actual_quantity 和 receiving_id) + const details = await ctx.model.ReceivingDetail.findAll({ + where: { id: detailIds }, + attributes: [ 'id', 'receiving_id', 'actual_quantity', 'stored_quantity', 'storage_status' ], + raw: true, + transaction, + }); + + if (!details.length) { + return; + } + + // 逐条计算并更新收货明细 + const receivingIdSet = new Set(); + for (const detail of details) { + const storedQuantity = detailQuantityMap.get(detail.id) || 0; + const actualQuantity = Number(detail.actual_quantity) || 0; + const storageStatus = storedQuantity >= actualQuantity + ? 'all' + : (storedQuantity > 0 ? 'partial' : 'none'); + + receivingIdSet.add(detail.receiving_id); + + await ctx.model.ReceivingDetail.update( + { + stored_quantity: storedQuantity, + storage_status: storageStatus, + updated_at: new Date(), + }, + { + where: { id: detail.id }, + transaction, + } + ); + } + + // 按收货单汇总,更新 wms_receiving.storage_status + const receivingIds = [ ...receivingIdSet ]; + if (receivingIds.length === 0) { + return; + } + + // 重新查询该收货单下所有明细的 storage_status,汇总主表状态 + const allDetails = await ctx.model.ReceivingDetail.findAll({ + where: { receiving_id: receivingIds }, + attributes: [ 'receiving_id', 'storage_status' ], + raw: true, + transaction, + group: [ 'receiving_id', 'storage_status' ], + }); + + // 按 receiving_id 分组 + const receivingDetailStatusMap = new Map(); + for (const d of allDetails) { + const rid = d.receiving_id; + if (!receivingDetailStatusMap.has(rid)) { + receivingDetailStatusMap.set(rid, new Set()); + } + receivingDetailStatusMap.get(rid).add(d.storage_status); + } + + for (const [ rid, statusSet ] of receivingDetailStatusMap) { + let receivingStorageStatus = 'none'; + if (statusSet.has('all') && statusSet.has('partial')) { + receivingStorageStatus = 'partial'; + } else if (statusSet.has('all')) { + if (statusSet.has('none') || statusSet.has('waiting')) { + receivingStorageStatus = 'partial'; + } else { + receivingStorageStatus = 'all'; + } + } else if (statusSet.has('partial')) { + receivingStorageStatus = 'partial'; + } + + await ctx.model.Receiving.update( + { + storage_status: receivingStorageStatus, + updated_at: new Date(), + }, + { + where: { id: rid }, + transaction, + } + ); } } } diff --git a/app/service/systems/operation_log.js b/app/service/systems/operation_log.js index 0dbdabe..923d2d0 100644 --- a/app/service/systems/operation_log.js +++ b/app/service/systems/operation_log.js @@ -306,6 +306,19 @@ class operationLogService extends Service { return await this.queryLogsByBusinessType(query, 'receiving'); } + /** + * 查询入库单操作日志。 + * @param {Object} query 查询参数。 + * @param {string|number} query.id 入库单ID。 + * @param {string|number} query.warehouseId 仓库ID。 + * @param {number} [query.page=1] 页码。 + * @param {number} [query.pageSize=20] 每页数量。 + * @return {Promise<{list: Object[], pagination: Object}>} 分页结果。 + */ + async queryEntryOrderLogs(query = {}) { + return await this.queryLogsByBusinessType(query, 'entry_order'); + } + async getMessageDetail(data) { const { id, type } = data; const { ctx } = this; diff --git a/app/service/systems/order_async.js b/app/service/systems/order_async.js index ac6c97e..1175b4e 100644 --- a/app/service/systems/order_async.js +++ b/app/service/systems/order_async.js @@ -479,12 +479,19 @@ async function finalizeSuccessfulQimenSyncInternal(service, orderModel, orderIte id: orderId, warehouse_id: warehouseId, }, - attributes: [ 'id', 'delivery_order_code', 'order_type', 'source_order_codes' ], + attributes: [ 'id', 'delivery_order_code', 'order_type', 'source_order_codes', 'sync_status' ], + lock: transaction.LOCK.UPDATE, raw: true, transaction, }); } + // 防重:如果订单已完成同步,跳过本次出库扣减 + if (resolvedOrderRow && String(resolvedOrderRow.sync_status || '').trim() === 'fin') { + service.ctx.logger.info(`[order_async] 订单已完成同步,跳过重复出库 orderId=${orderId}`); + return; + } + const outboundMetaOrderId = Number(resolvedOrderRow && resolvedOrderRow.id) || Number(orderId) || null; const outboundMetaOrderNo = String(resolvedOrderRow && resolvedOrderRow.delivery_order_code || '').trim() || null; const freshOrderItems = await orderItemsModel.findAll({ @@ -543,6 +550,23 @@ async function processLocalChannelOrderInternal(service, createChannel, orderMod try { await runTransactionWithLockRetryInternal(service, 'processLocalChannelOrder', async transaction => { + // 防重:SELECT FOR UPDATE 锁定订单行并检查 sync_status,防止重复出库 + const lockedOrderRow = await orderModel.findOne({ + where: { + id: orderId, + warehouse_id: warehouseId, + }, + attributes: [ 'id', 'sync_status' ], + lock: transaction.LOCK.UPDATE, + raw: true, + transaction, + }); + + if (lockedOrderRow && String(lockedOrderRow.sync_status || '').trim() === 'fin') { + service.ctx.logger.info(`[order_async] 订单已完成同步,跳过重复出库 orderId=${orderId}`); + return; + } + const freshOrderItems = await orderItemsModel.findAll({ where: { order_id: orderId, diff --git a/app/service/systems/order_auto_outbound.js b/app/service/systems/order_auto_outbound.js index 3c829d9..0b1dd68 100644 --- a/app/service/systems/order_auto_outbound.js +++ b/app/service/systems/order_auto_outbound.js @@ -7,6 +7,7 @@ const OUTBOUND_STATUS = 'fin'; const OUTBOUND_STEP = 4; const ORDER_STATUS_FINISHED = 'finished'; const MAX_BATCH_SIZE = 500; +const STORAGE_STATUS_FIN = 'fin'; /** * 订单自动化出库服务。 @@ -119,6 +120,7 @@ class OrderAutoOutboundService extends MainService { status: { [Op.notIn]: [ 'cancel', 'error', 'finished' ], }, + storage_status: STORAGE_STATUS_FIN, }; if (rules.require_recheck) { diff --git a/app/service/systems/order_print.js b/app/service/systems/order_print.js index e894bb1..f9f52b4 100644 --- a/app/service/systems/order_print.js +++ b/app/service/systems/order_print.js @@ -424,7 +424,7 @@ class OrderPrintSystemService extends OrderBaseService { } // 合并 barcodes 数组(Set 去重) if (item.barcodes && item.barcodes.length > 0) { - const merged = new Set([...(existing.barcodes || []), ...item.barcodes]); + const merged = new Set([ ...(existing.barcodes || []), ...item.barcodes ]); existing.barcodes = Array.from(merged); } } else { @@ -1516,7 +1516,7 @@ class OrderPrintSystemService extends OrderBaseService { if (Array.isArray(dispatchRows) && dispatchRows.length > 0) { // 合并 current 表与 dispatch 表结果,按 wave_id、id 升序排列 - const mergedRows = [...currentRows, ...dispatchRows].sort((a, b) => { + const mergedRows = [ ...currentRows, ...dispatchRows ].sort((a, b) => { const waveDiff = (a.wave_id || 0) - (b.wave_id || 0); if (waveDiff !== 0) return waveDiff; return (a.id || 0) - (b.id || 0); @@ -1546,7 +1546,7 @@ class OrderPrintSystemService extends OrderBaseService { * 返回 business_key=1 的主运单,按 order_id、business_key、id 升序排列。 * * @param {number[]} orderIds 订单 ID 列表。 - * @returns {Promise>} 匹配的运单记录数组,字段包含 id、order_id、business_key、waybill_code、 + * @return {Promise>} 匹配的运单记录数组,字段包含 id、order_id、business_key、waybill_code、 * logistics_code、logistics_name、logistics_interface_id、logistics_interface_name、platform_code、 * warehouse_id、printinfo、signature、encryptprintinfo、ver。 */ @@ -2682,8 +2682,8 @@ ${waveFilterSql} is_active: 1, delete_at: null, }, - order: [['bind_count', 'DESC']], - attributes: ['package_material_name'], + order: [[ 'bind_count', 'DESC' ]], + attributes: [ 'package_material_name' ], raw: true, }); if (topMatch && topMatch.package_material_name) { @@ -2707,7 +2707,7 @@ ${waveFilterSql} let subjectConfig = {}; if (warehouseId > 0) { const storeRow = await this.ctx.model.Store.findByPk(warehouseId, { - attributes: ['subject_config'], + attributes: [ 'subject_config' ], raw: true, }); if (storeRow && storeRow.subject_config) { diff --git a/app/service/systems/order_storage_allocation.js b/app/service/systems/order_storage_allocation.js index 5197b13..e03e5a3 100644 --- a/app/service/systems/order_storage_allocation.js +++ b/app/service/systems/order_storage_allocation.js @@ -837,6 +837,10 @@ class OrderStorageAllocationService extends MainService { const totalCount = pendingOrderIds.length; let processedCount = 0; + // 按订单维度跟踪已锁定的库存记录,用于缺货订单的原子回滚。 + // Map> + const orderLockRecords = new Map(); + // 对于 storage_status='error' 的重分配订单,先清理旧的 picking 记录并释放已锁定的库存 if (errorRetryOrderIds.length > 0) { writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 检测到 error 重试订单,开始清理旧数据', { @@ -1108,6 +1112,19 @@ class OrderStorageAllocationService extends MainService { storageRow.id, allocationQuantity, { transaction } ); + // 回退内存计数器:storageRow 的 available_quantity 和 locked_quantity + storageRow.available_quantity = currentAvailable; + storageRow.locked_quantity = toNumber(storageRow.locked_quantity, 0) - allocationQuantity; + + // 回退 remainingQuantity:未分配成功的数量加回去 + remainingQuantity += allocationQuantity; + + // 回退 allocatedQuantityForItem + allocatedQuantityForItem -= allocationQuantity; + + // 回退 allocatedQuantityForOrder + allocatedQuantityForOrder -= allocationQuantity; + // 回退 storageAllocationMap 中的累加值 const prevStorageQty = storageAllocationMap.get(storageRow.id) || 0; const newStorageQty = prevStorageQty - allocationQuantity; @@ -1117,17 +1134,29 @@ class OrderStorageAllocationService extends MainService { storageAllocationMap.set(storageRow.id, newStorageQty); } - writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 库位无效,回退库存主表锁定累加', { + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 库位无效,回退库存主表锁定累加及内存计数器', { orderId, storageId: storageRow.id, allocationQuantity, prevStorageQty, newStorageQty, + rollback: { + remainingQuantity, + allocatedQuantityForItem, + allocatedQuantityForOrder, + storageAvailableQuantity: storageRow.available_quantity, + storageLockedQuantity: storageRow.locked_quantity, + }, }); continue; } + // 记录本次成功锁定(lockQuantity + spaceId 有效),用于订单级别缺货回滚 + const orderLockList = orderLockRecords.get(orderId) || []; + orderLockList.push({ storageId: storageRow.id, quantity: allocationQuantity }); + orderLockRecords.set(orderId, orderLockList); + pickingRows.push({ order_id: orderId, order_item_id: toNumber(orderItem.id, 0), @@ -1143,6 +1172,12 @@ class OrderStorageAllocationService extends MainService { } if (remainingQuantity > 0) { + // 确保每个明细的缺货原因独立计算,避免候选库位为空时的诊断原因 + // 被错误地复用到候选库位非空但仍不足的明细上 + const finalShortageReason = candidateStorageRows.length === 0 + ? shortageReason + : (shortageReason || '库存不足'); + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 准备写入缺货条目', { orderId, orderItemId: toNumber(orderItem.id, 0), @@ -1151,12 +1186,14 @@ class OrderStorageAllocationService extends MainService { allocatedQuantity: allocatedQuantityForItem, remainingQuantity, candidateCount: candidateStorageRows.length, + shortageReason, + finalShortageReason, }); shortageItems.push({ stock_id: stockId, required_quantity: requiredQuantity, allocated_quantity: allocatedQuantityForItem, - reason: shortageReason, + reason: finalShortageReason, }); writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 订单明细存在缺货', { orderId, @@ -1166,6 +1203,7 @@ class OrderStorageAllocationService extends MainService { allocatedQuantityForItem, remainingQuantity, shortageReason, + finalShortageReason, }); } } @@ -1185,6 +1223,62 @@ class OrderStorageAllocationService extends MainService { finalShortageMessage, }); + // 单订单原子性分配:如果本订单有缺货,回滚该订单所有已成功锁定的库存, + // 并从 pickingRows 中移除该订单的所有记录,确保同一事务内该订单不留任何 locked_quantity。 + if (finalShortageMessage) { + const orderLocks = orderLockRecords.get(orderId); + if (Array.isArray(orderLocks) && orderLocks.length > 0) { + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 开始回滚订单已锁定库存', { + orderId, + orderLockCount: orderLocks.length, + orderLocks, + }); + + for (const lockRecord of orderLocks) { + await ctx.service.systems.storage.index.unlockQuantity( + lockRecord.storageId, lockRecord.quantity, { transaction } + ); + + // 回退 storageAllocationMap 中的累加值 + const prevStorageQty = storageAllocationMap.get(lockRecord.storageId) || 0; + const newStorageQty = prevStorageQty - lockRecord.quantity; + if (newStorageQty <= 0) { + storageAllocationMap.delete(lockRecord.storageId); + } else { + storageAllocationMap.set(lockRecord.storageId, newStorageQty); + } + + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 已回滚单条库存锁定', { + orderId, + storageId: lockRecord.storageId, + quantity: lockRecord.quantity, + prevStorageQty, + newStorageQty, + }); + } + + // 回退订单级别的已分配数量计数器 + allocatedQuantityForOrder = 0; + + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 订单锁定库存回滚完成,已重置 allocatedQuantityForOrder', { + orderId, + }); + } + + // 从 pickingRows 中移除该订单的所有记录。 + // 使用反向遍历 + splice 避免索引漂移,保持 pickingRows 顺序。 + for (let pickIdx = pickingRows.length - 1; pickIdx >= 0; pickIdx -= 1) { + if (pickingRows[pickIdx].order_id === orderId) { + pickingRows.splice(pickIdx, 1); + } + } + + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 已从 pickingRows 移除缺货订单记录', { + orderId, + remainingPickingCount: pickingRows.length, + }); + } + const orderUpdateValues = finalShortageMessage ? { storage_status: STORAGE_STATUS_ERROR, @@ -1752,14 +1846,12 @@ class OrderStorageAllocationService extends MainService { let msg; if (isPending) msg = `同步到${channelNames}渠道`; else if (failed) { - const reasonMap = { 'express_unallocated': '快递未分配', 'sn_batch_forbidden': 'SN订单不支持批量' }; + const reasonMap = { express_unallocated: '快递未分配', sn_batch_forbidden: 'SN订单不支持批量' }; msg = `同步跳过:${reasonMap[failed.failed_reason] || failed.failed_reason || failed.message || '条件不满足'}`; - } - else if (skipped) { - const skipReasonMap = { 'already_synced': '已同步', 'not_found': '订单不存在' }; + } else if (skipped) { + const skipReasonMap = { already_synced: '已同步', not_found: '订单不存在' }; msg = `同步跳过:${skipReasonMap[skipped.skipped_reason] || skipped.skipped_reason || '已同步'}`; - } - else msg = `同步跳过`; + } else msg = '同步跳过'; return { businessType: 'order', businessId: `${orderId}`, diff --git a/app/service/systems/pick.js b/app/service/systems/pick.js index b71a08b..77301b5 100644 --- a/app/service/systems/pick.js +++ b/app/service/systems/pick.js @@ -57,6 +57,7 @@ class PickSystemService extends Service { * * @param {string} message 错误文案。 * @param {number} [code=400] 错误码。 + * @param {*} [data=null] 附加数据。 * @return {Error} 错误对象。 */ createBusinessError(message, code = 400, data = null) { diff --git a/app/service/systems/print/printData.js b/app/service/systems/print/printData.js index abb6e15..44d50bb 100644 --- a/app/service/systems/print/printData.js +++ b/app/service/systems/print/printData.js @@ -2,11 +2,6 @@ const Service = require('egg').Service; -const result = { - platform: null, - count: 0, - datas: [], -}; class PrintDataService extends Service { async getPrintData({ printType, orderId }) { diff --git a/app/service/systems/receiving_entry_match.js b/app/service/systems/receiving_entry_match.js index 6d41b74..37b1538 100644 --- a/app/service/systems/receiving_entry_match.js +++ b/app/service/systems/receiving_entry_match.js @@ -184,6 +184,172 @@ class ReceivingEntryMatchService extends Service { } } + /** + * 写入入库单与收货单的主表级绑定关系(仅主表绑定,不做明细分配)。 + * + * 流程: + * 1. 校验入库单状态 = CREATED + * 2. 校验每个收货单:存在、同仓库、同货主、已审核、未取消 + * 3. 逐条写入 EntryOrderReceiving.findOrCreate(主表绑定) + * + * @param {Object} data 请求参数 + * @param {number} data.entry_order_id 入库单 ID + * @param {number[]} data.receiving_ids 收货单 ID 列表 + * @param {number} [data.creator_id] 操作人 ID(可选) + * @return {Promise} 绑定结果,含 bound、skipped、summary + */ + async bindEntryOrderReceiving(data = {}) { + const { ctx } = this; + const { entry_order_id: entryOrderId, receiving_ids: receivingIds, creator_id: creatorId } = data || {}; + + // 参数校验 + if (!entryOrderId) { + throw new Error('entry_order_id 不能为空'); + } + if (!Array.isArray(receivingIds) || receivingIds.length === 0) { + throw new Error('receiving_ids 不能为空且必须为数组'); + } + + // ========== 第1步:查询入库单,校验状态 ========== + const entryOrder = await ctx.model.EntryOrder.findByPk(entryOrderId); + if (!entryOrder) { + throw new Error('入库单不存在'); + } + // 只允许 CREATED 状态 + if (entryOrder.order_status !== 'CREATED') { + throw new Error(`入库单状态不允许绑定,当前状态: ${entryOrder.order_status},仅 CREATED 状态可操作`); + } + + const warehouseId = entryOrder.warehouse_id; + + // ========== 第2步:校验每个收货单的有效性 ========== + const validatedReceivings = []; + const failedValidations = []; + + for (const receivingId of receivingIds) { + const receiving = await ctx.model.Receiving.findOne({ + where: { id: receivingId, is_deleted: false }, + attributes: [ 'id', 'receiving_number', 'warehouse_id', 'store_id', 'status', 'is_review' ], + }); + + if (!receiving) { + failedValidations.push({ + receiving_id: receivingId, + error_code: 'RECEIVING_NOT_FOUND', + message: '收货单不存在或已删除', + }); + continue; + } + + if (receiving.warehouse_id !== warehouseId) { + failedValidations.push({ + receiving_id: receivingId, + receiving_number: receiving.receiving_number, + error_code: 'WAREHOUSE_MISMATCH', + message: `收货单 ${receiving.receiving_number} 与入库单不属于同一仓库`, + }); + continue; + } + + if (receiving.store_id !== entryOrder.store_id) { + failedValidations.push({ + receiving_id: receivingId, + receiving_number: receiving.receiving_number, + error_code: 'OWNER_MISMATCH', + message: `收货单 ${receiving.receiving_number} 与入库单货主不一致`, + }); + continue; + } + + if (receiving.status === 'cancelled') { + failedValidations.push({ + receiving_id: receivingId, + receiving_number: receiving.receiving_number, + error_code: 'RECEIVING_CANCELLED', + message: `收货单 ${receiving.receiving_number} 已取消`, + }); + continue; + } + + if (!receiving.is_review) { + failedValidations.push({ + receiving_id: receivingId, + receiving_number: receiving.receiving_number, + error_code: 'RECEIVING_NOT_REVIEWED', + message: `收货单 ${receiving.receiving_number} 未审核`, + }); + continue; + } + + validatedReceivings.push(receiving); + } + + // 有校验失败的收货单 → 直接返回失败 + if (failedValidations.length > 0) { + ctx.logger.info( + `[ReceivingEntryMatch] bindEntryOrderReceiving 收货单校验失败 entryOrderId=${entryOrderId} failed=${failedValidations.length}` + ); + return { + bound: [], + skipped: [], + summary: { bound_count: 0, skipped_count: failedValidations.length }, + }; + } + + // ========== 第3步:逐条写入主表绑定关系 ========== + const boundResults = []; + const skippedResults = []; + + for (const receiving of validatedReceivings) { + try { + const [ , created ] = await ctx.model.EntryOrderReceiving.findOrCreate({ + where: { entry_order_id: entryOrderId, receiving_id: receiving.id }, + defaults: { entry_order_id: entryOrderId, receiving_id: receiving.id }, + }); + + if (created) { + ctx.logger.info( + `[ReceivingEntryMatch] 主表绑定成功 entryOrderId=${entryOrderId} receivingId=${receiving.id}` + ); + } else { + ctx.logger.info( + `[ReceivingEntryMatch] 主表绑定已存在,跳过 entryOrderId=${entryOrderId} receivingId=${receiving.id}` + ); + } + + boundResults.push({ + receiving_id: receiving.id, + receiving_number: receiving.receiving_number, + created, + }); + } catch (error) { + ctx.logger.error( + `[ReceivingEntryMatch] 主表绑定写入失败 entryOrderId=${entryOrderId} receivingId=${receiving.id}: ${error.message}`, + error.stack + ); + skippedResults.push({ + receiving_id: receiving.id, + receiving_number: receiving.receiving_number, + error_code: 'BINDING_WRITE_FAILED', + message: `写入绑定失败: ${error.message}`, + }); + } + } + + ctx.logger.info( + `[ReceivingEntryMatch] bindEntryOrderReceiving 主表绑定完成 entryOrderId=${entryOrderId} bound=${boundResults.length} skipped=${skippedResults.length} creatorId=${creatorId || 'N/A'}` + ); + + return { + bound: boundResults, + skipped: skippedResults, + summary: { + bound_count: boundResults.length, + skipped_count: skippedResults.length, + }, + }; + } + /** * 获取仓库近 3 天的收货单列表(优先从 Redis 缓存读取)。 * @@ -212,6 +378,7 @@ class ReceivingEntryMatchService extends Service { where: { warehouse_id: warehouseId, is_deleted: false, + is_review: 1, status: [ 'receiving', 'completed' ], created_at: { [app.Sequelize.Op.gte]: threeDaysAgo }, }, @@ -288,7 +455,7 @@ class ReceivingEntryMatchService extends Service { // 如果缓存的收货单没有 details(可能为空),重新加载 if (!matched.details || matched.details.length === 0) { const fullOrder = await ctx.model.Receiving.findOne({ - where: { id: matched.id, warehouse_id: warehouseId }, + where: { id: matched.id, warehouse_id: warehouseId, is_deleted: false, is_review: 1 }, attributes: [ 'id', 'receiving_number', 'status', 'storage_status' ], include: [{ model: ctx.model.ReceivingDetail, @@ -746,177 +913,247 @@ class ReceivingEntryMatchService extends Service { } /** - * 批量绑定入库单明细与收货单明细。 - * 依次校验入库单状态、商品匹配关系、可用数量,事务写入绑定并确保主级绑定存在。 - * @param {Object} data 请求参数 - * @param {number} data.entry_order_id 入库单ID - * @param {Array} data.bindings 绑定列表 - * @param {number} data.bindings[].entry_item_id 入库单明细ID - * @param {number} data.bindings[].receiving_detail_id 收货单明细ID - * @param {number} data.bindings[].allocated_quantity 分配数量 - * @return {Promise} { success: [...], failed: [...], success_count, failed_count } + * 内部公共方法:在事务中提交单条入库明细-收货明细绑定。 + * 包含 FOR UPDATE 行锁、可用量二次校验、绑定写入、主表绑定确保。 + * 被 PDA 上架 addItem 流程调用,用于逐条写入明细绑定。 + * + * @param {Object} params 绑定参数 + * @param {number} params.entryItemId 入库单明细 ID + * @param {number} params.receivingDetailId 收货单明细 ID + * @param {number} params.qty 分配数量 + * @param {number} params.expectedSpId 期望的 system_product_id(用于匹配校验,可选) + * @param {number} params.entryOrderId 入库单 ID(用于确保主表绑定存在) + * @param {Object} params.transaction Sequelize 事务对象 + * @throws {Object} 结构化错误对象,包含 error_code、message、detail + * @return {Promise} */ + async _commitBinding({ entryItemId, receivingDetailId, qty, expectedSpId, entryOrderId, transaction } = {}) { + const { ctx } = this; + + // 1. FOR UPDATE 锁收货明细行 + const lockedDetail = await ctx.model.query( + `SELECT id, actual_quantity, receiving_id, system_product_id + FROM wms_receiving_detail + WHERE id = :rdId FOR UPDATE`, + { + replacements: { rdId: receivingDetailId }, + type: ctx.model.QueryTypes.SELECT, + transaction, + } + ); + if (!lockedDetail || lockedDetail.length === 0) { + throw { + error_code: 'RECEIVING_DETAIL_NOT_FOUND', + message: '收货明细不存在', + detail: { receiving_detail_id: receivingDetailId }, + }; + } + + // 2. 校验收货明细与入库商品是否匹配(system_product_id) + if (expectedSpId !== undefined && lockedDetail[0].system_product_id !== expectedSpId) { + throw { + error_code: 'RECEIVING_DETAIL_MISMATCH', + message: '收货明细与入库商品不匹配', + detail: { + entry_item_id: entryItemId, + receiving_detail_id: receivingDetailId, + expected_sp_id: expectedSpId, + actual_sp_id: lockedDetail[0].system_product_id, + }, + }; + } + + // 3. 查已 committed 的分配量 + const allocatedSum = await ctx.model.query( + `SELECT COALESCE(SUM(allocated_quantity), 0) AS total + FROM wms_entry_receiving_binding + WHERE receiving_detail_id = :rdId AND status = 'committed' AND deleted_at IS NULL`, + { + replacements: { rdId: receivingDetailId }, + type: ctx.model.QueryTypes.SELECT, + transaction, + } + ); + const availableQty = lockedDetail[0].actual_quantity - Number(allocatedSum[0]?.total || 0); + if (qty > availableQty) { + throw { + error_code: 'INSUFFICIENT_AVAILABLE_QUANTITY', + message: '分配数量超出可用量', + detail: { available_quantity: availableQty, requested_quantity: qty }, + }; + } + + // 4. 写入明细绑定 + await ctx.model.EntryReceivingBinding.create({ + entry_item_id: entryItemId, + receiving_detail_id: receivingDetailId, + allocated_quantity: qty, + status: 'committed', + creator_id: ctx.currentUser?.id || 0, + }, { transaction }); + + // 5. 确保主级绑定存在 + await ctx.model.EntryOrderReceiving.findOrCreate({ + where: { entry_order_id: entryOrderId, receiving_id: lockedDetail[0].receiving_id }, + defaults: { entry_order_id: entryOrderId, receiving_id: lockedDetail[0].receiving_id }, + transaction, + }); + } + /** - * 批量绑定入库单明细与收货单明细。 - * 在事务中对每条绑定使用 FOR UPDATE 行锁防并发超卖,失败项返回结构化错误码。 + * 解除入库单与收货单的绑定关系。 + * + * 逻辑: + * 1. 校验入库单存在,状态必须是 PENDING 或 CREATED(COMPLETED / CANCELLED 不允许解绑) + * 2. 逐个收货单: + * a. 查 wms_entry_order_receiving 主表绑定是否存在(只查 deleted_at IS NULL) + * b. 查 wms_entry_receiving_binding 明细绑定是否存在(status='committed' 且 deleted_at IS NULL) + * c. 无明细绑定 → 只软删除主表绑定 + * d. 有明细绑定 → 事务中软删除明细绑定 + 软删除主表绑定 + * 3. 不回退入库单状态(PENDING 解绑后仍是 PENDING) * * @param {Object} data 请求参数 * @param {number} data.entry_order_id 入库单 ID - * @param {Array<{entry_item_id: number, receiving_detail_id: number, allocated_quantity: number}>} data.bindings 绑定列表 - * @return {Promise<{success: Array, failed: Array, success_count: number, failed_count: number}>} 绑定结果 + * @param {number[]} data.receiving_ids 要解除绑定的收货单 ID 列表 + * @return {Promise} { success: Array, failed: Array, success_count: number, failed_count: number } */ - async bindReceivingDetails(data = {}) { + async unbindEntryOrderReceiving(data = {}) { const { ctx } = this; - const { entry_order_id: entryOrderId, bindings = [] } = data || {}; + const { entry_order_id: entryOrderId, receiving_ids: receivingIds } = data || {}; - if (!entryOrderId || !Array.isArray(bindings) || bindings.length === 0) { - throw new Error('参数不完整'); + // 参数校验 + if (!entryOrderId) { + throw new Error('entry_order_id 不能为空'); + } + if (!Array.isArray(receivingIds) || receivingIds.length === 0) { + throw new Error('receiving_ids 不能为空且必须为数组'); } - // 1. 查询入库单,校验状态(必须是 PENDING 或 CREATED) + // ---------- 第1步:校验入库单存在且状态允许解绑 ---------- const entryOrder = await ctx.model.EntryOrder.findByPk(entryOrderId); - if (!entryOrder || ![ 'CREATED', 'PENDING' ].includes(entryOrder.order_status)) { - // 入库单状态不对 → 全部 bindings 标记为 ENTRY_ORDER_STATUS_INVALID - const allFailed = bindings.map(b => ({ - entry_item_id: b.entry_item_id, - receiving_detail_id: b.receiving_detail_id, - allocated_quantity: b.allocated_quantity, - error_code: 'ENTRY_ORDER_STATUS_INVALID', - message: '入库单状态不允许绑定', - detail: { order_status: entryOrder ? entryOrder.order_status : null }, - })); - return { success: [], failed: allFailed, success_count: 0, failed_count: allFailed.length }; + if (!entryOrder) { + return { + success: [], + failed: receivingIds.map(rid => ({ + receiving_id: rid, + error_code: 'ENTRY_ORDER_NOT_FOUND', + message: '入库单不存在', + })), + success_count: 0, + failed_count: receivingIds.length, + }; } + // 只允许 PENDING 或 CREATED 状态解绑(COMPLETED / CANCELLED 不允许) + if (![ 'CREATED', 'PENDING' ].includes(entryOrder.order_status)) { + return { + success: [], + failed: receivingIds.map(rid => ({ + receiving_id: rid, + error_code: 'ENTRY_ORDER_STATUS_INVALID', + message: `入库单状态不允许解绑,当前状态: ${entryOrder.order_status}`, + })), + success_count: 0, + failed_count: receivingIds.length, + }; + } + + // ---------- 第2步:逐个收货单处理解绑 ---------- const success = []; const failed = []; - for (const binding of bindings) { - const { entry_item_id: entryItemId, receiving_detail_id: receivingDetailId, allocated_quantity: qty } = binding; + for (const receivingId of receivingIds) { try { - // 2. 查询 entry_item 和对应的 stock_id - const entryItem = await ctx.model.EntryItems.findByPk(entryItemId); - if (!entryItem) { - throw { - error_code: 'ENTRY_ITEM_NOT_FOUND', - message: '入库明细不存在', - detail: { entry_item_id: entryItemId }, - }; - } - - // 3. 通过 stock_id → system_product_id 校验收货单明细匹配 - const sw = await ctx.model.StockWarehouse.findOne({ - where: { id: entryItem.stock_id, warehouse_id: entryOrder.warehouse_id }, - attributes: [ 'system_product_id' ], - raw: true, - }); - if (!sw || !sw.system_product_id) { - throw { - error_code: 'STOCK_NOT_FOUND', - message: '商品不存在', - detail: { stock_id: entryItem.stock_id }, - }; - } - - // 4. 事务:FOR UPDATE 锁行 → 查已分配量 → 写入绑定 - await ctx.model.transaction(async t => { - // 4a. 先锁收货明细行 - const lockedDetail = await ctx.model.query( - `SELECT id, actual_quantity, receiving_id, system_product_id - FROM wms_receiving_detail - WHERE id = :rdId FOR UPDATE`, - { - replacements: { rdId: receivingDetailId }, - type: ctx.model.QueryTypes.SELECT, - transaction: t, - } - ); - if (!lockedDetail || lockedDetail.length === 0) { - throw { - error_code: 'RECEIVING_DETAIL_NOT_FOUND', - message: '收货明细不存在', - detail: { receiving_detail_id: receivingDetailId }, - }; - } - - // 4b. 校验收货明细与入库商品是否匹配(system_product_id) - if (lockedDetail[0].system_product_id !== sw.system_product_id) { - throw { - error_code: 'RECEIVING_DETAIL_MISMATCH', - message: '收货明细与入库商品不匹配', - detail: { - entry_item_id: entryItemId, - receiving_detail_id: receivingDetailId, - expected_sp_id: sw.system_product_id, - actual_sp_id: lockedDetail[0].system_product_id, - }, - }; - } - - // 4c. 查已 committed 的分配量 - const allocatedSum = await ctx.model.query( - `SELECT COALESCE(SUM(allocated_quantity), 0) AS total - FROM wms_entry_receiving_binding - WHERE receiving_detail_id = :rdId AND status = 'committed' AND deleted_at IS NULL`, - { - replacements: { rdId: receivingDetailId }, - type: ctx.model.QueryTypes.SELECT, - transaction: t, - } - ); - const availableQty = lockedDetail[0].actual_quantity - Number(allocatedSum[0]?.total || 0); - if (qty > availableQty) { - throw { - error_code: 'INSUFFICIENT_AVAILABLE_QUANTITY', - message: '分配数量超出可用量', - detail: { available_quantity: availableQty, requested_quantity: qty }, - }; - } - - // 4d. 写入绑定 - await ctx.model.EntryReceivingBinding.create({ - entry_item_id: entryItemId, - receiving_detail_id: receivingDetailId, - allocated_quantity: qty, - status: 'committed', - creator_id: ctx.currentUser?.id || 0, - }, { transaction: t }); - - // 确保主级绑定存在 - await ctx.model.EntryOrderReceiving.findOrCreate({ - where: { entry_order_id: entryOrderId, receiving_id: lockedDetail[0].receiving_id }, - defaults: { entry_order_id: entryOrderId, receiving_id: lockedDetail[0].receiving_id }, - transaction: t, - }); + // 2a. 查主表绑定是否存在 + const mainBinding = await ctx.model.EntryOrderReceiving.findOne({ + where: { + entry_order_id: entryOrderId, + receiving_id: receivingId, + deleted_at: null, + }, }); - success.push({ entry_item_id: entryItemId, receiving_detail_id: receivingDetailId, allocated_quantity: qty }); - } catch (err) { - // 结构化错误对象或普通 Error 统一转为 failed 项 - if (err.error_code) { + if (!mainBinding) { failed.push({ - entry_item_id: entryItemId, - receiving_detail_id: receivingDetailId, - allocated_quantity: qty, - error_code: err.error_code, - message: err.message, - detail: err.detail || {}, + receiving_id: receivingId, + error_code: 'BINDING_NOT_FOUND', + message: '主表绑定不存在', + }); + continue; + } + + // 2b. 查明细绑定是否存在 + const detailBindings = await ctx.model.EntryReceivingBinding.findAll({ + where: { + status: 'committed', + deleted_at: null, + }, + include: [{ + model: ctx.model.ReceivingDetail, + as: 'receivingDetail', + required: true, + attributes: [], + where: { receiving_id: receivingId }, + }], + attributes: [ 'id', 'receiving_detail_id', 'allocated_quantity' ], + }); + + if (detailBindings.length === 0) { + // 2c. 无明细绑定 → 只软删除主表绑定 + await mainBinding.destroy(); + ctx.logger.info( + `[ReceivingEntryMatch] 解绑成功(仅主表) entryOrderId=${entryOrderId} receivingId=${receivingId}` + ); + success.push({ + receiving_id: receivingId, + released_detail_count: 0, + message: '已解除主表绑定(无明细绑定)', }); } else { - failed.push({ - entry_item_id: entryItemId, - receiving_detail_id: receivingDetailId, - allocated_quantity: qty, - error_code: 'INTERNAL_ERROR', - message: err.message || '未知错误', - detail: {}, + // 2d. 有明细绑定 → 事务:软删除明细绑定 + 软删除主表绑定 + const detailIds = detailBindings.map(d => d.receiving_detail_id); + + await ctx.model.transaction(async t => { + // 软删除所有明细绑定 + for (const binding of detailBindings) { + await binding.destroy({ transaction: t }); + } + + // 软删除主表绑定 + await mainBinding.destroy({ transaction: t }); + }); + + ctx.logger.info( + `[ReceivingEntryMatch] 解绑成功(含明细) entryOrderId=${entryOrderId} ` + + `receivingId=${receivingId} detailCount=${detailBindings.length} ` + + `detailIds=[${detailIds.join(',')}]` + ); + + success.push({ + receiving_id: receivingId, + released_detail_ids: detailIds, + released_detail_count: detailBindings.length, + message: '已解除主表及明细绑定', }); } + } catch (error) { + ctx.logger.error( + `[ReceivingEntryMatch] 解绑异常 entryOrderId=${entryOrderId} ` + + `receivingId=${receivingId}: ${error.message}`, + error.stack + ); + failed.push({ + receiving_id: receivingId, + error_code: 'UNBIND_ERROR', + message: `解绑过程异常: ${error.message}`, + }); } } return { success, failed, success_count: success.length, failed_count: failed.length }; } + + } module.exports = ReceivingEntryMatchService; diff --git a/app/service/systems/shops.js b/app/service/systems/shops.js index 9f59a94..110cdd8 100644 --- a/app/service/systems/shops.js +++ b/app/service/systems/shops.js @@ -675,10 +675,9 @@ class ShopsService extends Service { * @return {Promise} 会话信息 */ async getAuthorizeSessionKey(data = {}) { - const { ctx, service } = this; + const { ctx } = this; const authUrl = 'http://61.160.223.183:3012/api'; - const warehouseId = this.getCurrentWarehouseId(); const shopId = data.id !== undefined ? data.id : (data.shop_id !== undefined ? data.shop_id : data.shopId); const callbackUrl = this.normalizeText( data.callbackurl !== undefined ? data.callbackurl : data.callback_url, diff --git a/app/service/systems/stock_warehouse.js b/app/service/systems/stock_warehouse.js index b3378ba..dad60e4 100644 --- a/app/service/systems/stock_warehouse.js +++ b/app/service/systems/stock_warehouse.js @@ -31,7 +31,7 @@ class StockWarehouseService extends Service { * @param {Object} [options={}] 选项 * @param {number} [options.warehouseId] 仓库ID(优先使用 options.warehouseId,否则兜底 ctx.user.store_id) * @param {number} [options.cacheTTL=300] 缓存过期时间(秒) - * @return {Promise}>>} 商品详情列表 + * @return {Promise}>>} 商品详情列表 */ async getStockDetails(stockIds, options = {}) { const { ctx, app } = this; @@ -99,6 +99,7 @@ class StockWarehouseService extends Service { attributes: [ 'file_url' ], required: false, }], + order: [[ 'display_order', 'ASC' ]], raw: true, }), ]); @@ -121,8 +122,11 @@ class StockWarehouseService extends Service { for (const row of imageRows) { const sid = Number(row.business_id); if (!imageUrlMap.has(sid)) { - const url = (row['file.file_url'] && String(row['file.file_url']).trim()) || ''; - imageUrlMap.set(sid, url); + imageUrlMap.set(sid, []); + } + const url = (row['file.file_url'] && String(row['file.file_url']).trim()) || ''; + if (url) { + imageUrlMap.get(sid).push(url); } } @@ -141,7 +145,7 @@ class StockWarehouseService extends Service { store_id: row.store_id != null ? Number(row.store_id) : 0, packing_requirements: row.packing_requirements || '', stock_unit: row.stock_unit || '', - image_url: imageUrlMap.get(row.id) || '', + image_url: imageUrlMap.get(row.id) || [], barcodes: barcodeMap.get(row.id) || [], }; dbResults.set(row.id, detail); @@ -176,6 +180,13 @@ class StockWarehouseService extends Service { const cached = cacheHits.get(stockId); // 空标记(防穿透缓存)跳过 if (cached !== null && cached !== undefined) { + // 兼容旧缓存格式:image_url 可能是字符串,统一转为数组 + if (cached && typeof cached.image_url === 'string') { + cached.image_url = cached.image_url ? [ cached.image_url ] : []; + } + if (cached && !Array.isArray(cached.image_url)) { + cached.image_url = []; + } result.push(cached); } } else if (dbResults.has(stockId)) { diff --git a/app/service/systems/storage/entry.js b/app/service/systems/storage/entry.js index 0f6a91b..2c74639 100644 --- a/app/service/systems/storage/entry.js +++ b/app/service/systems/storage/entry.js @@ -93,7 +93,8 @@ class EntryService extends Service { * @return {Object|null} Sequelize.where 条件,无法构建时返回 null */ buildEntryStockTransactionExistsCondition(fieldName, condition = {}) { - const { app } = this; + const { app, ctx } = this; + const db = ctx.model.sequelize; const values = this.normalizeFilterValues(condition) .map(item => (typeof item === 'string' ? item.trim() : item)) .filter(item => item !== '' && item !== undefined && item !== null); @@ -104,13 +105,13 @@ class EntryService extends Service { const operator = String(condition.operator || 'eq').trim().toLowerCase(); const escapedColumn = `st.${fieldName}`; - const escapedValues = values.map(item => app.Sequelize.escape(item)); + const escapedValues = values.map(item => db.escape(item)); let valueClause = ''; if (operator === 'in') { valueClause = `${escapedColumn} IN (${escapedValues.join(',')})`; } else if (operator === 'like' || operator === 'contains') { - const likeClauses = values.map(item => `${escapedColumn} LIKE ${app.Sequelize.escape(`%${String(item)}%`)}`); + const likeClauses = values.map(item => `${escapedColumn} LIKE ${db.escape(`%${String(item)}%`)}`); valueClause = likeClauses.length === 1 ? likeClauses[0] : `(${likeClauses.join(' OR ')})`; } else { valueClause = `${escapedColumn} = ${escapedValues[0]}`; @@ -131,7 +132,42 @@ class EntryService extends Service { * @param {Object} normalizedWhere 标准化后的 where 条件 * @return {{where: Object, extraConditions: Array, errorMessage: string}} 预处理结果 */ - preprocessEntryListWhere(normalizedWhere = {}) { + /** + * 根据 hasReceiving 虚拟字段构建入库单 ID 筛选条件。 + * @param {boolean} hasReceiving true=已绑定,false=未绑定 + * @return {Promise} Sequelize where 条件,无需额外筛选时返回 null + */ + async buildHasReceivingCondition(hasReceiving) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + const bindings = await ctx.model.EntryOrderReceiving.findAll({ + attributes: [[ app.Sequelize.fn('DISTINCT', app.Sequelize.col('entry_order_id')), 'entry_order_id' ]], + where: { deleted_at: null }, + raw: true, + }); + + const boundIds = bindings.map(item => item.entry_order_id); + + if (hasReceiving === true) { + if (boundIds.length === 0) { + return { id: { [Op.eq]: null } }; + } + return { id: { [Op.in]: boundIds } }; + } + + if (boundIds.length === 0) { + return null; + } + return { id: { [Op.notIn]: boundIds } }; + } + + /** + * 预处理入库单列表筛选条件,兼容历史别名并构建扩展筛选。 + * @param {Object} normalizedWhere 标准化后的 where 条件 + * @return {Promise<{where: Object, extraConditions: Array, errorMessage: string}>} 预处理结果 + */ + async preprocessEntryListWhere(normalizedWhere = {}) { const { ctx } = this; const whereForParse = normalizedWhere && typeof normalizedWhere === 'object' ? { ...normalizedWhere } @@ -161,6 +197,19 @@ class EntryService extends Service { } delete whereForParse.operator_id; + // 处理虚拟字段 hasReceiving:从 where 中剥离,构建绑定/未绑定筛选条件 + if (Object.prototype.hasOwnProperty.call(whereForParse, 'hasReceiving')) { + const rawHasReceiving = whereForParse.hasReceiving; + delete whereForParse.hasReceiving; + + if (rawHasReceiving === true || rawHasReceiving === false) { + const receivingCondition = await this.buildHasReceivingCondition(rawHasReceiving); + if (receivingCondition) { + extraConditions.push(receivingCondition); + } + } + } + if (Object.prototype.hasOwnProperty.call(whereForParse, 'expense_record')) { const hasExpenseRecordField = Boolean( ctx.model @@ -202,7 +251,6 @@ class EntryService extends Service { const { ctx, app } = this; const { Sequelize } = app; const { Op } = Sequelize; - const page = Math.max(Number(pageParams.page) || 1, 1); const pageSize = Math.max(Number(pageParams.pageSize) || 20, 1); @@ -234,7 +282,7 @@ class EntryService extends Service { where: parsedSourceWhere, extraConditions, errorMessage, - } = this.preprocessEntryListWhere(normalizedWhere); + } = await this.preprocessEntryListWhere(normalizedWhere); if (errorMessage) { return { @@ -309,15 +357,27 @@ class EntryService extends Service { const andConditions = [ baseWhere ]; if (quickWhereValue !== undefined && quickWhereValue !== null && String(quickWhereValue).trim() !== '') { const kw = String(quickWhereValue).trim(); - andConditions.push({ - [Op.or]: [ - { entry_order_code: { [Op.like]: `%${kw}%` } }, - { purchase_order_code: { [Op.like]: `%${kw}%` } }, - { supplier_name: { [Op.like]: `%${kw}%` } }, - { store_name: { [Op.like]: `%${kw}%` } }, - { warehouse_name: { [Op.like]: `%${kw}%` } }, - ], - }); + const receivingDetailId = Number(kw); + const orConditions = [ + { entry_order_code: { [Op.like]: `%${kw}%` } }, + { purchase_order_code: { [Op.like]: `%${kw}%` } }, + { supplier_name: { [Op.like]: `%${kw}%` } }, + { store_name: { [Op.like]: `%${kw}%` } }, + { warehouse_name: { [Op.like]: `%${kw}%` } }, + // 搜索收货单明细 ID(箱唛/托盘唛唯一编码,精确数字匹配);仅当 kw 是有效正数时追加 EXISTS + ...(Number.isFinite(receivingDetailId) && receivingDetailId > 0 ? [ + Sequelize.where(Sequelize.literal( + `EXISTS ( + SELECT 1 FROM wms_entry_order_receiving eor + JOIN wms_receiving_detail rd ON rd.receiving_id = eor.receiving_id + WHERE eor.entry_order_id = wms_entry_order.id + AND eor.deleted_at IS NULL + AND rd.id = ${receivingDetailId} + )` + ), 1), + ] : []), + ]; + andConditions.push({ [Op.or]: orConditions }); } const dynamicConditions = parsedResult.dynamicConditions || []; @@ -354,6 +414,44 @@ class EntryService extends Service { distinct: true, }); + // 批量查询收货单绑定信息 + const entryOrderIds = rows.map(row => row.id); + /** @type {Map>} */ + const receivingBindingsMap = new Map(); + if (entryOrderIds.length > 0) { + const allBindings = await ctx.model.EntryOrderReceiving.findAll({ + where: { entry_order_id: { [Op.in]: entryOrderIds }, deleted_at: null }, + include: [ + { + model: ctx.model.Receiving, + as: 'receiving', + attributes: [ 'id', 'receiving_number', 'status', 'storage_status', 'created_at' ], + required: false, + }, + ], + order: [[ 'id', 'ASC' ]], + }); + + for (const binding of allBindings) { + const eid = binding.entry_order_id; + if (!receivingBindingsMap.has(eid)) { + receivingBindingsMap.set(eid, []); + } + receivingBindingsMap.get(eid).push(binding); + } + } + + // 为每行附加收货单绑定信息 + const enrichedRows = rows.map(row => { + const rowJSON = row.toJSON ? row.toJSON() : row; + const bindings = receivingBindingsMap.get(row.id) || []; + return { + ...rowJSON, + receivingBindings: bindings, + hasReceiving: bindings.length > 0, + }; + }); + const statusRows = await ctx.model.EntryOrder.findAll({ attributes: [ 'order_status', @@ -383,7 +481,7 @@ class EntryService extends Service { code: 200, message: '查询成功', data: { - list: rows, + list: enrichedRows, pagination: { page, pageSize, @@ -610,7 +708,7 @@ class EntryService extends Service { COALESCE(SUM(erb.allocated_quantity), 0) AS allocated_quantity, rd.actual_quantity - COALESCE(SUM(erb.allocated_quantity), 0) AS available_quantity FROM wms_receiving_detail rd - INNER JOIN wms_receiving r ON r.id = rd.receiving_id AND r.deleted_at IS NULL + INNER JOIN wms_receiving r ON r.id = rd.receiving_id AND r.is_deleted = false LEFT JOIN wms_entry_receiving_binding erb ON erb.receiving_detail_id = rd.id AND erb.status = 'committed' @@ -740,7 +838,6 @@ class EntryService extends Service { } const orderIds = normalizedResult.ids || []; - const entryOrders = []; for (const orderId of orderIds) { const entryOrder = await this.getOwnedEntryOrderById(orderId); @@ -752,6 +849,15 @@ class EntryService extends Service { }; } + // 6b: sync_status=SUCCESS 不可取消 + if (entryOrder.sync_status === 'SUCCESS') { + return { + code: 400, + message: '入库单已完成回传,不可取消', + data: null, + }; + } + if (entryOrder.order_status === 'COMPLETED') { return { code: 400, @@ -760,107 +866,125 @@ class EntryService extends Service { }; } - entryOrders.push(entryOrder); - } - - const transaction = ctx.model && typeof ctx.model.transaction === 'function' - ? await ctx.model.transaction() - : null; - - try { - const updatedAt = new Date(); - - for (const entryOrder of entryOrders) { - await entryOrder.update({ - order_status: 'CANCELLED', - updated_at: updatedAt, - }, transaction ? { - transaction, - } : undefined); + if (entryOrder.order_status === 'CANCELLED') { + return { + code: 400, + message: '入库单已作废', + data: null, + }; } - if (transaction && typeof transaction.commit === 'function') { - await transaction.commit(); + // 6a: QM 来源需发送取消同步 + if (String(entryOrder.source_type) === 'QM') { + const entryItems = await ctx.model.EntryItems.findAll({ + where: { order_id: entryOrder.id }, + attributes: [ 'item_code', 'item_id', 'count', 'inventory_type', 'owner_code' ], + raw: true, + }); + + const orderLines = (entryItems || []).map((item, idx) => ({ + orderLineNo: idx + 1, + ownerCode: item.owner_code || '', + itemCode: item.item_code || '', + itemId: item.item_id || '', + inventoryType: item.inventory_type || 'ZP', + planQty: item.count || 0, + actualQty: 0, // 全部为 0,通知 ERP 关闭 + })); + + const syncResult = await ctx.service.systems.inboundDirectLog.qimenEntrySync({ + entryOrder, + orderLines, + outBizCode: `CANCEL_${Date.now()}`, + remark: '入库单取消', + operator: { + id: ctx.user?.employees_id || ctx.user?.id || '', + name: ctx.user?.employees_name || '', + }, + }); + + if (!syncResult.success) { + return { + code: 500, + message: `取消失败: ${syncResult.message}`, + data: null, + }; + } } - } catch (error) { - if (transaction && typeof transaction.rollback === 'function') { - await transaction.rollback(); - } - throw error; + + // 更新状态 + await entryOrder.update({ + order_status: 'CANCELLED', + updated_at: new Date(), + }); + + // 回退关联收货单的入库状态,避免死锁 + await this._rollbackReceivingStorageStatus(entryOrder.id); + + // 写操作日志 + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'entry_order', + businessId: entryOrder.id, + operationCode: 'ENTRY_ORDER_CANCEL', + operator: { + id: ctx.user?.employees_id || ctx.user?.id || '', + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: entryOrder.warehouse_id, + message: '入库单已取消', + }, + }); } return { code: 200, message: '作废成功', - data: { - [orderIds.length === 1 ? 'id' : 'ids']: orderIds.length === 1 ? entryOrders[0].id : orderIds, - }, + data: { ids: orderIds }, }; } /** - * 完成入库单。 - * @param {Object} data 请求体 - * @return {Promise} code/data/message 结构 + * 回退入库单关联收货单的入库状态(入库单作废时调用)。 + * 失败不阻塞主流程,仅打印日志。 + * @param {number} entryOrderId 入库单ID + * @return {Promise} */ - async completeEntry(data = {}) { + async _rollbackReceivingStorageStatus(entryOrderId) { const { ctx } = this; - const orderId = Number(data.id || 0); + try { + // 1. 查询关联的收货单ID列表 + const bindings = await ctx.model.EntryOrderReceiving.findAll({ + where: { entry_order_id: entryOrderId, deleted_at: null }, + attributes: [ 'receiving_id' ], + raw: true, + }); - if (!orderId) { - return { - code: 400, - message: 'id 必填', - data: null, - }; + const receivingIds = (bindings || [ ]).map(b => b.receiving_id).filter(Boolean); + if (receivingIds.length === 0) { + return; + } + + // 2. 回退收货单主表 storage_status → 'none' + await ctx.model.Receiving.update( + { storage_status: 'none', updated_at: new Date() }, + { where: { id: { [ctx.app.Sequelize.Op.in]: receivingIds } } } + ); + + // 3. 回退收货单明细 storage_status → 'none', stored_quantity → 0 + await ctx.model.ReceivingDetail.update( + { storage_status: 'none', stored_quantity: 0, updated_at: new Date() }, + { where: { receiving_id: { [ctx.app.Sequelize.Op.in]: receivingIds } } } + ); + + ctx.logger.info( + `[storage.entry.cancel] 入库单 ${entryOrderId} 作废,已回退收货单入库状态,receivingIds=[${receivingIds.join(',')}]` + ); + } catch (err) { + ctx.logger.error( + `[storage.entry.cancel] 回退收货单入库状态失败,entryOrderId=${entryOrderId},err=${err.message}` + ); } - - const entryOrder = await this.getOwnedEntryOrderById(orderId); - if (!entryOrder) { - return { - code: 404, - message: '入库单不存在或无权访问', - data: null, - }; - } - - if (entryOrder.order_status === 'CANCELLED') { - return { - code: 400, - message: '已作废入库单不允许完成', - data: null, - }; - } - - if (![ 'PENDING' ].includes(entryOrder.order_status)) { - return { - code: 400, - message: `当前入库单状态为 ${entryOrder.order_status},仅 PENDING 状态可完成入库`, - data: null, - }; - } - - const detailCount = await ctx.model.EntryItems.count({ where: { order_id: orderId } }); - if (detailCount <= 0) { - return { - code: 400, - message: '请先添加入库明细', - data: null, - }; - } - - await entryOrder.update({ - order_status: 'COMPLETED', - updated_at: new Date(), - }); - - return { - code: 200, - message: '完成成功', - data: { - id: entryOrder.id, - }, - }; } /** @@ -909,8 +1033,208 @@ class EntryService extends Service { return await ctx.service.systems.inboundDirectLog.removeItem(data); } + /** + * 查询入库单已绑定收货单中匹配指定 stock_id 的收货明细列表。 + * 用于 PDA 导入时选择要绑定的收货明细。 + * @param {Object} data 请求体 + * @param {number} data.entry_order_id 入库单 ID + * @param {number} data.stock_id 商品 stock_id + * @return {Promise} { code, message, data: { list: [{ receiving_detail_id, receiving_id, receiving_number, actual_quantity, used_quantity, available_quantity, system_product_id }] } } + */ + async getReceivingDetailsForBind(data = {}) { + const { ctx, app } = this; + const entryOrderId = Number(data.entry_order_id); + const stockId = Number(data.stock_id); + + if (!entryOrderId || !stockId) { + return { code: 400, message: 'entry_order_id 和 stock_id 必填', data: null }; + } + + // 1. 查入库单绑定的收货单 ID 列表 + const orderReceivings = await ctx.model.EntryOrderReceiving.findAll({ + where: { entry_order_id: entryOrderId, deleted_at: null }, + attributes: [ 'receiving_id' ], + raw: true, + }); + if (!orderReceivings.length) { + return { code: 200, message: 'ok', data: { list: [] } }; + } + const receivingIds = orderReceivings.map(r => r.receiving_id); + + // 2. 查收货明细(system_product_id = stockId,且收货单未取消/未删除) + const details = await ctx.model.ReceivingDetail.findAll({ + where: { + system_product_id: stockId, + receiving_id: receivingIds, + deleted_at: null, + }, + attributes: [ 'id', 'receiving_id', 'actual_quantity', 'system_product_id' ], + include: [{ + model: ctx.model.Receiving, + as: 'receiving', + attributes: [ 'id', 'receiving_number', 'status' ], + where: { status: { [ app.Sequelize.Op.ne ]: 'cancelled' }, deleted_at: null }, + required: true, + }], + raw: false, + }); + + // 3. 查每个明细的已占用数量(pending + committed) + const detailIds = details.map(d => d.id); + const usedMap = new Map(); + if (detailIds.length > 0) { + const usedRows = await ctx.model.query( + `SELECT receiving_detail_id, COALESCE(SUM(allocated_quantity), 0) AS used_qty + FROM wms_entry_receiving_binding + WHERE receiving_detail_id IN (:ids) + AND status IN ('pending', 'committed') + AND deleted_at IS NULL + GROUP BY receiving_detail_id`, + { + replacements: { ids: detailIds }, + type: ctx.model.QueryTypes.SELECT, + } + ); + for (const row of usedRows) { + usedMap.set(row.receiving_detail_id, Number(row.used_qty)); + } + } + + // 4. 组装返回 + const list = details.map(d => { + const rid = d.id; + const used = usedMap.get(rid) || 0; + return { + receiving_detail_id: rid, + receiving_id: d.receiving_id, + receiving_number: d.receiving?.receiving_number || '', + actual_quantity: d.actual_quantity || 0, + used_quantity: used, + available_quantity: Math.max(0, (d.actual_quantity || 0) - used), + system_product_id: d.system_product_id, + }; + }); + + return { code: 200, message: 'ok', data: { list } }; + } + + /** + * 拉取入库单绑定的收货单中,指定商品的可用容器列表(收货明细)。 + * 用于 PDA 上架时选择容器。 + * @param {Object} data 请求参数 + * @param {number} data.entry_order_id 入库单ID + * @param {number} data.stock_id 商品stock_id + * @return {Promise} { code, message, data: { list, total } } + */ + async containerList(data = {}) { + const { ctx, app } = this; + const warehouseId = ctx.user?.store_id; + const entryOrderId = Number(data.entry_order_id); + const stockId = Number(data.stock_id); + + // 参数校验 + if (!warehouseId) { + return { code: 0, message: '用户未绑定仓库', data: null }; + } + if (!entryOrderId || entryOrderId <= 0) { + return { code: 0, message: 'entry_order_id 不能为空', data: null }; + } + if (!stockId || stockId <= 0) { + return { code: 0, message: 'stock_id 不能为空', data: null }; + } + + try { + // 1. 验证入库单存在且属于当前仓库 + const entryOrder = await ctx.model.EntryOrder.findOne({ + where: { + id: entryOrderId, + warehouse_id: warehouseId, + }, + attributes: [ 'id' ], + raw: true, + }); + + if (!entryOrder) { + return { code: 0, message: '入库单不存在或无权访问', data: null }; + } + + // 2. 通过 wms_entry_order_receiving 查出关联的 receiving_id 列表 + const entryReceivingRows = await ctx.model.EntryOrderReceiving.findAll({ + where: { entry_order_id: entryOrderId, deleted_at: null }, + attributes: [ 'receiving_id' ], + raw: true, + }); + + const receivingIds = entryReceivingRows.map(r => r.receiving_id).filter(Boolean); + if (receivingIds.length === 0) { + return { code: 200, message: 'ok', data: { list: [], total: 0 } }; + } + + // 3. 排除已绑定的收货明细(wms_entry_receiving_binding 中有记录且未软删除) + const notBoundCondition = app.Sequelize.literal( + 'NOT EXISTS (SELECT 1 FROM wms_entry_receiving_binding erb WHERE erb.receiving_detail_id = wms_receiving_detail.id AND erb.deleted_at IS NULL)' + ); + + // 4. 查询指定商品的未绑定收货明细 + const details = await ctx.model.ReceivingDetail.findAll({ + where: { + [app.Sequelize.Op.and]: [ + { system_product_id: stockId }, + { receiving_id: { [app.Sequelize.Op.in]: receivingIds } }, + notBoundCondition, + ], + }, + raw: true, + }); + + // 5. 收集所有明细的 system_product_id,批量获取 stock 详情 + const stockIdSet = new Set(); + for (const d of details) { + if (d.system_product_id != null) { + stockIdSet.add(Number(d.system_product_id)); + } + } + const stockIds = [ ...stockIdSet ]; + + /** @type {Map} */ + const stockDetailMap = new Map(); + if (stockIds.length > 0) { + const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(stockIds, { warehouseId }); + for (const sd of stockDetails) { + if (sd && sd.id != null) { + stockDetailMap.set(sd.id, sd); + } + } + } + + // 6. 组装返回结果 + const list = details.map(detail => ({ + detail_id: detail.id, + receiving_id: detail.receiving_id, + barcode: detail.barcode || '', + product_name: detail.product_name || '', + actual_quantity: detail.actual_quantity || 0, + receiving_status: detail.receiving_status || '', + stock: stockDetailMap.get(Number(detail.system_product_id)) || null, + })); + + return { + code: 200, + message: 'ok', + data: { + list, + total: list.length, + }, + }; + } catch (error) { + ctx.logger.error('[storage.entry.containerList] 查询容器列表失败', error); + return { code: 500, message: `服务器错误: ${error.message}`, data: null }; + } + } + /** * 快捷直入/虚拟入库:将入库单的所有商品按明细数量全部直入到虚拟库位(space_id=2),跳过收货、质检等正常流程。 + * 采用"先同步后写库"两段式:① 先发奇门/OpenAPI 回传,② 回传成功后再开启事务写库存。 * @param {Object} data 请求体 * @param {number} data.id 入库单ID * @return {Promise} code/data/message 结构 @@ -972,172 +1296,224 @@ class EntryService extends Service { }; } - const warehouseId = entryOrder.warehouse_id; - const storeId = entryOrder.store_id; - const batchNo = entryOrder.entry_order_code; - const hardcodedSpaceId = 2; - const transaction = await ctx.model.transaction(); + // ===== 阶段一 + 阶段二合并为统一调用 ===== + const syncResult = await ctx.service.systems.inboundDirectLog.qimenEntrySync({ + entryOrder, + orderLines: entryItems.map((item, idx) => ({ + orderLineNo: idx + 1, + ownerCode: item.owner_code || '', + itemCode: item.item_code || '', + itemId: item.item_id || '', + inventoryType: item.inventory_type || 'ZP', + planQty: Number(item.count) || 0, + actualQty: Number(item.count) || 0, + })), + outBizCode: `DIRECT_INBOUND_${Date.now()}`, + remark: '导入/PDA直接入库提交', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + onSuccess: async eo => { + const warehouseId = eo.warehouse_id; + const storeId = eo.store_id; + const batchNo = eo.entry_order_code; + const hardcodedSpaceId = 2; + const transaction = await ctx.model.transaction(); - const processedStockIds = new Set(); - let totalInboundQty = 0; + const processedStockIds = new Set(); + let totalInboundQty = 0; - try { - // 3. 逐商品写入库存 - for (const item of entryItems) { - const stockId = item.stock_id; - if (!stockId) continue; + try { + for (const item of entryItems) { + const stockId = item.stock_id; + if (!stockId) continue; - const planQty = Number(item.count) || 0; - if (planQty <= 0) continue; + const planQty = Number(item.count) || 0; + if (planQty <= 0) continue; - const inventoryType = item.inventory_type || 'ZP'; + const inventoryType = item.inventory_type || 'ZP'; - // 更新入库明细的 received_quantity 为计划数量(全部入库) - await ctx.model.EntryItems.update({ - received_quantity: planQty, - }, { - where: { id: item.id }, - transaction, - }); + await ctx.model.EntryItems.update({ + received_quantity: planQty, + }, { + where: { id: item.id }, + transaction, + }); - // 同一 stock_id 只写一次库存 - if (processedStockIds.has(String(stockId))) continue; - processedStockIds.add(String(stockId)); - totalInboundQty += planQty; + if (processedStockIds.has(String(stockId))) continue; + processedStockIds.add(String(stockId)); + totalInboundQty += planQty; - // 锁定并更新 StockWarehouse 总库存 - const stockRecord = await ctx.model.StockWarehouse.findOne({ - where: { id: stockId, is_valid: 'Y', deleted_at: null }, - lock: transaction.LOCK.UPDATE, - transaction, - }); + const stockRecord = await ctx.model.StockWarehouse.findOne({ + where: { id: stockId, is_valid: 'Y', deleted_at: null }, + lock: transaction.LOCK.UPDATE, + transaction, + }); - if (stockRecord) { - const beforeQuantity = Number(stockRecord.quantity) || 0; - const beforeLockedQuantity = Number(stockRecord.locked_quantity) || 0; + if (stockRecord) { + const beforeQuantity = Number(stockRecord.quantity) || 0; + const beforeLockedQuantity = Number(stockRecord.locked_quantity) || 0; - await stockRecord.increment('quantity', { by: planQty, transaction, silent: true }); - await stockRecord.reload({ transaction }); + await stockRecord.increment('quantity', { by: planQty, transaction, silent: true }); + await stockRecord.reload({ transaction }); - const afterQuantity = Number(stockRecord.quantity) || 0; - const afterLockedQuantity = Number(stockRecord.locked_quantity) || 0; + const afterQuantity = Number(stockRecord.quantity) || 0; + const afterLockedQuantity = Number(stockRecord.locked_quantity) || 0; - // 写入库存流水 - await ctx.service.systems.stockTransaction.create({ - transaction_type: 'INBOUND', - warehouse_id: warehouseId, - store_id: storeId, - stock_id: stockId, - quantity: planQty, - batch_no: batchNo, - order_type: entryOrder.order_type, - order_no: entryOrder.entry_order_code, - entry_order_id: entryOrder.id, - operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), - operator_name: ctx.user?.employees_name || '', - remark: '快捷直入/虚拟入库', - before_quantity: beforeQuantity, - after_quantity: afterQuantity, - before_locked_quantity: beforeLockedQuantity, - after_locked_quantity: afterLockedQuantity, - created_at: new Date(), - }, { transaction }); - } + await ctx.service.systems.stockTransaction.create({ + transaction_type: 'INBOUND', + warehouse_id: warehouseId, + store_id: storeId, + stock_id: stockId, + quantity: planQty, + batch_no: batchNo, + order_type: eo.order_type, + order_no: eo.entry_order_code, + entry_order_id: eo.id, + operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), + operator_name: ctx.user?.employees_name || '', + remark: '快捷直入/虚拟入库', + before_quantity: beforeQuantity, + after_quantity: afterQuantity, + before_locked_quantity: beforeLockedQuantity, + after_locked_quantity: afterLockedQuantity, + created_at: new Date(), + }, { transaction }); + } - // 创建/更新 Storage 库位库存(space_id 硬编码为 2) - const storageRecord = await ctx.model.Storage.findOne({ - where: { - space_id: hardcodedSpaceId, - stock_id: stockId, - batch_no: batchNo, - inventory_type: inventoryType, - is_enabled: 1, - delete_at: null, - }, - lock: transaction.LOCK.UPDATE, - transaction, - }); + const storageRecord = await ctx.model.Storage.findOne({ + where: { + space_id: hardcodedSpaceId, + stock_id: stockId, + batch_no: batchNo, + inventory_type: inventoryType, + is_enabled: 1, + delete_at: null, + }, + lock: transaction.LOCK.UPDATE, + transaction, + }); - if (storageRecord) { - await ctx.model.Storage.update({ - quantity: app.Sequelize.literal(`quantity + ${planQty}`), - available_quantity: app.Sequelize.literal(`available_quantity + ${planQty}`), - entry_order_id: entryOrder.id, - inbound_time: new Date(), - inbound_order_no: entryOrder.entry_order_code, + let storageId = null; + let storageBeforeQty = 0; + let storageAfterQty = 0; + + if (storageRecord) { + storageBeforeQty = Number(storageRecord.quantity) || 0; + storageAfterQty = storageBeforeQty + planQty; + + await ctx.model.Storage.update({ + quantity: app.Sequelize.literal(`quantity + ${planQty}`), + available_quantity: app.Sequelize.literal(`available_quantity + ${planQty}`), + entry_order_id: eo.id, + inbound_time: new Date(), + inbound_order_no: eo.entry_order_code, + updated_at: new Date(), + }, { + where: { id: storageRecord.id }, + transaction, + }); + storageId = storageRecord.id; + } else { + storageBeforeQty = 0; + storageAfterQty = planQty; + + const createdStorage = await ctx.model.Storage.create({ + warehouse_id: warehouseId, + store_id: storeId, + space_id: hardcodedSpaceId, + stock_id: stockId, + batch_no: batchNo, + inventory_type: inventoryType, + quantity: planQty, + locked_quantity: 0, + available_quantity: planQty, + inbound_time: new Date(), + inbound_order_no: eo.entry_order_code, + receiving_id: null, + entry_order_id: eo.id, + supplier_id: null, + supplier_batch_no: null, + is_enabled: 1, + created_at: new Date(), + updated_at: new Date(), + }, { transaction }); + storageId = createdStorage.id; + } + + // 写入库位维度库存流水 + await ctx.model.StorageTransaction.create({ + transaction_type: 'INBOUND', + warehouse_id: warehouseId, + store_id: storeId, + stock_id: stockId, + storage_id: storageId, + space_id: hardcodedSpaceId, + quantity: planQty, + before_quantity: storageBeforeQty, + after_quantity: storageAfterQty, + batch_no: batchNo, + inventory_type: inventoryType, + order_type: 'entry_order', + order_no: eo.entry_order_code, + order_id: eo.id, + operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), + operator_name: ctx.user?.employees_name || '', + remark: '快捷直入/虚拟入库', + created_at: new Date(), + }, { transaction }); + } + + await eo.update({ + order_status: 'COMPLETED', + sync_status: 'SUCCESS', + sync_message: JSON.stringify({ + completedAt: new Date(), + totalQuantity: totalInboundQty, + itemCount: processedStockIds.size, + source: 'quick_inbound', + }), updated_at: new Date(), - }, { - where: { id: storageRecord.id }, + }, { transaction }); + + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'entry_order', + businessId: eo.id, + operationCode: 'QUICK_INBOUND', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: eo.warehouse_id, + message: `快捷直入完成,共 ${processedStockIds.size} 种商品,总数量 ${totalInboundQty}`, + }, transaction, }); - } else { - await ctx.model.Storage.create({ - warehouse_id: warehouseId, - store_id: storeId, - space_id: hardcodedSpaceId, - stock_id: stockId, - batch_no: batchNo, - inventory_type: inventoryType, - quantity: planQty, - locked_quantity: 0, - available_quantity: planQty, - inbound_time: new Date(), - inbound_order_no: entryOrder.entry_order_code, - receiving_id: null, - entry_order_id: entryOrder.id, - supplier_id: null, - supplier_batch_no: null, - is_enabled: 1, - created_at: new Date(), - updated_at: new Date(), - }, { transaction }); + + await transaction.commit(); + } catch (error) { + if (transaction && typeof transaction.rollback === 'function') { + await transaction.rollback(); + } + throw error; } - } - - // 4. 更新入库单状态为 COMPLETED - await entryOrder.update({ - order_status: 'COMPLETED', - sync_status: 'SUCCESS', - sync_message: JSON.stringify({ - completedAt: new Date(), - totalQuantity: totalInboundQty, - itemCount: processedStockIds.size, - source: 'quick_inbound', - }), - updated_at: new Date(), - }, { transaction }); - - // 记录操作日志(事务内) - await ctx.service.systems.operationLog.createOperationLog({ - businessType: 'entry_order', - businessId: entryOrder.id, - operationCode: 'QUICK_INBOUND', - operator: { - id: ctx.user?.employees_id || ctx.user?.id, - name: ctx.user?.employees_name || '', - }, - extras: { - warehouseId: entryOrder.warehouse_id, - message: `快捷直入完成,共 ${processedStockIds.size} 种商品,总数量 ${totalInboundQty}`, - }, - transaction, - }); - - await transaction.commit(); - } catch (error) { - if (transaction && typeof transaction.rollback === 'function') { - await transaction.rollback(); - } - throw error; - } - - // 事务外:异步触发奇门/API 回传(复用 inboundDirectLog 的回传逻辑) - setImmediate(() => { - ctx.service.systems.inboundDirectLog._sendCallback(entryOrder).catch(err => { - ctx.logger.error(`[quickInbound] 回传异常 entryOrderId=${entryOrder.id}: ${err.message}`, err.stack); - }); + }, }); + if (!syncResult.success) { + return { + code: 500, + message: syncResult.message, + data: { + id: entryOrder.id, + entry_order_code: entryOrder.entry_order_code, + sync_status: 'FAILED', + }, + }; + } + return { code: 200, message: '快捷入库完成', @@ -1147,35 +1523,116 @@ class EntryService extends Service { order_status: 'COMPLETED', sync_status: 'SUCCESS', items_count: entryItems.length, - total_quantity: totalInboundQty, + total_quantity: entryItems.reduce((s, item) => s + (Number(item.count) || 0), 0), }, }; } /** - * 入库单商品与收货单商品逐行对照视图。 + * 入库单商品与收货单商品逐行对照视图(支持多个收货单)。 * 以入库单明细为主,按 stock_id ↔ system_product_id 匹配收货单明细, - * 返回匹配/未匹配/收货单多余的对照结果。 + * 返回每个收货单的匹配/未匹配/收货单多余对照结果及汇总。 * * @param {Object} data 请求参数 * @param {number} data.entry_order_id 入库单ID - * @param {number} data.receiving_id 收货单ID + * @param {number[]} [data.receiving_ids] 收货单ID列表(优先使用) + * @param {number} [data.receiving_id] 单个收货单ID(向后兼容,receiving_ids 优先) * @return {Promise} code/data/message 结构 */ async receivingCompare(data = {}) { - const { ctx, app } = this; + const { ctx } = this; const entryOrderId = Number(data.entry_order_id || 0); - const receivingId = Number(data.receiving_id || 0); const warehouseId = ctx.user.store_id; + // 入参处理:receiving_ids 优先,receiving_id 向后兼容 + let receivingIds = data.receiving_ids; + if (!Array.isArray(receivingIds) || receivingIds.length === 0) { + const singleId = Number(data.receiving_id || 0); + if (singleId) { + receivingIds = [ singleId ]; + } else { + return { code: 400, message: 'receiving_ids 或 receiving_id 必填', data: null }; + } + } + receivingIds = [ ...new Set(receivingIds.map(id => Number(id)).filter(Boolean)) ]; + if (!entryOrderId) { return { code: 400, message: 'entry_order_id 必填', data: null }; } - if (!receivingId) { - return { code: 400, message: 'receiving_id 必填', data: null }; + + // 1. 校验入库单存在性 + const entryOrder = await this.getOwnedEntryOrderById(entryOrderId); + if (!entryOrder) { + return { code: 404, message: '入库单不存在或无权访问', data: null }; } - // 1. 校验收货单存在性 + // 2. 查询入库单明细(所有收货单共用) + const entryItems = await ctx.model.EntryItems.findAll({ + where: { order_id: entryOrderId }, + attributes: [ 'id', 'stock_id', 'count', 'received_quantity' ], + raw: true, + }); + + // 3. 收集入库单所有 stock_id + const entryStockIds = [ ...new Set(entryItems.map(item => Number(item.stock_id)).filter(Boolean)) ]; + + // 4. 对每个收货单执行对比 + const comparisons = []; + const errors = []; + + for (const receivingId of receivingIds) { + const singleResult = await this._compareSingleReceiving({ + receivingId, + warehouseId, + entryOrderId, + entryOrder, + entryItems, + entryStockIds, + }); + if (singleResult._error) { + errors.push(singleResult._error); + } else { + comparisons.push(singleResult); + } + } + + const totalReceivings = receivingIds.length; + const matchedCount = comparisons.length; + const errorCount = errors.length; + + return { + code: 200, + message: '查询成功', + data: { + entry_order_id: entryOrderId, + entry_order_code: entryOrder.entry_order_code, + comparisons, + errors, + total_summary: { + total_receivings: totalReceivings, + matched_count: matchedCount, + error_count: errorCount, + }, + }, + }; + } + + /** + * 对单个收货单执行商品对照逻辑。 + * @param {Object} params 参数 + * @param {number} params.receivingId 收货单ID + * @param {number} params.warehouseId 仓库ID + * @param {number} params.entryOrderId 入库单ID + * @param {Object} params.entryOrder 入库单记录 + * @param {Object[]} params.entryItems 入库单明细列表 + * @param {number[]} params.entryStockIds 入库单 stock_id 集合 + * @return {Promise} 单个收货单的对照结果,或 { _error: ... } + */ + async _compareSingleReceiving(params = {}) { + const { ctx, app } = this; + const { receivingId, warehouseId, entryItems, entryStockIds } = params; + + // 校验收货单存在性与仓库匹配 const receivingOrder = await ctx.model.Receiving.findOne({ where: { id: receivingId, @@ -1186,34 +1643,25 @@ class EntryService extends Service { raw: true, }); if (!receivingOrder) { - return { code: 404, message: '收货单不存在或无权访问', data: null }; + return { + _error: { + receiving_id: receivingId, + status: 'error', + error_code: 'RECEIVING_NOT_FOUND', + error_message: '收货单不存在或无权访问', + }, + }; } - // 2. 校验收货单存在性(复用 getOwnedEntryOrderById) - const entryOrder = await this.getOwnedEntryOrderById(entryOrderId); - if (!entryOrder) { - return { code: 404, message: '入库单不存在或无权访问', data: null }; - } - - // 3. 查询入库单明细 - const entryItems = await ctx.model.EntryItems.findAll({ - where: { order_id: entryOrderId }, - attributes: [ 'id', 'stock_id', 'count', 'received_quantity' ], - raw: true, - }); - - // 4. 查询收货单明细 + // 查询收货单明细 const receivingDetails = await ctx.model.ReceivingDetail.findAll({ where: { receiving_id: receivingId }, attributes: [ 'id', 'system_product_id', 'actual_quantity', 'product_name' ], raw: true, }); - // 5. 收集所有 stock_id,批量查询商品信息 - const entryStockIds = [ ...new Set(entryItems.map(item => Number(item.stock_id)).filter(Boolean)) ]; + // 收集所有 stock_id,批量查询商品信息 const receivingSystemProductIds = [ ...new Set(receivingDetails.map(d => Number(d.system_product_id)).filter(Boolean)) ]; - - // 6. 批量查询 wms_stock_warehouse — 入库单商品(按 stock_id)和收货单商品(按 system_product_id = id) const allStockIds = [ ...new Set([ ...entryStockIds, ...receivingSystemProductIds ]) ]; const stockDetailMap = new Map(); if (allStockIds.length > 0) { @@ -1223,8 +1671,7 @@ class EntryService extends Service { } } - // stock_id 即 wms_stock_warehouse.id,与 wms_receiving_detail.system_product_id 直接对应 - // 只需确认 stock_warehouse 记录存在即可构建映射 + // stock_id ↔ system_product_id 映射 const stockIdToSystemProductId = new Map(); const systemProductIdToEntryStockIds = new Map(); if (entryStockIds.length > 0) { @@ -1243,18 +1690,20 @@ class EntryService extends Service { } } - // 7. 查询已分配量(从 wms_entry_receiving_binding) + // 查询已分配量(限定本入库单的 entry_items,避免全局绑定干扰) const receivingDetailIds = receivingDetails.map(d => d.id); + const entryItemIds = entryItems.map(ei => ei.id); const allocatedMap = new Map(); - if (receivingDetailIds.length > 0) { + if (receivingDetailIds.length > 0 && entryItemIds.length > 0) { const bindingRows = await ctx.model.EntryReceivingBinding.findAll({ attributes: [ 'receiving_detail_id', [ app.Sequelize.fn('SUM', app.Sequelize.col('allocated_quantity')), 'total_allocated' ], ], where: { + entry_item_id: { [app.Sequelize.Op.in]: entryItemIds }, receiving_detail_id: { [app.Sequelize.Op.in]: receivingDetailIds }, - status: 'committed', + status: { [app.Sequelize.Op.in]: [ 'pending', 'committed' ] }, deleted_at: null, }, group: [ 'receiving_detail_id' ], @@ -1265,7 +1714,7 @@ class EntryService extends Service { } } - // 8. 构建对照视图:以入库单明细为主 + // 构建对照视图:以入库单明细为主 const comparison = []; const matchedReceivingDetailIds = new Set(); @@ -1274,13 +1723,11 @@ class EntryService extends Service { const systemProductId = stockIdToSystemProductId.get(stockId) || 0; const stockDetail = stockDetailMap.get(stockId) || null; - // 找到同 system_product_id 的收货单明细 const matchedReceiving = systemProductId > 0 ? receivingDetails.filter(rd => Number(rd.system_product_id) === systemProductId) : []; if (matchedReceiving.length > 0) { - // 有匹配的收货明细 for (const rd of matchedReceiving) { matchedReceivingDetailIds.add(rd.id); const rdStockDetail = (rd.system_product_id != null && stockDetailMap.get(Number(rd.system_product_id))) || null; @@ -1304,7 +1751,6 @@ class EntryService extends Service { }); } } else { - // 入库商品在收货单中不存在 comparison.push({ entry_item_id: Number(entryItem.id), stock_id: stockId, @@ -1324,44 +1770,63 @@ class EntryService extends Service { } } - // 9. 收货单中多余的商品(未被任何入库单明细匹配的) + // 收货单中多余的商品 const receivingOnly = []; + const receivingStockMap = new Map(); for (const rd of receivingDetails) { if (!matchedReceivingDetailIds.has(Number(rd.id))) { const rdStockDetail = (rd.system_product_id != null && stockDetailMap.get(Number(rd.system_product_id))) || null; + const stockId = rd.system_product_id != null ? Number(rd.system_product_id) : null; + const qty = Number(rd.actual_quantity) || 0; + const name = rd.product_name || (rdStockDetail && rdStockDetail.item_name) || ''; const allocated = allocatedMap.get(Number(rd.id)) || 0; - const available = Math.max(0, (Number(rd.actual_quantity) || 0) - allocated); - receivingOnly.push({ - receiving_detail_id: Number(rd.id), - receiving_product_code: (rdStockDetail && rdStockDetail.item_code) || '', - receiving_product_name: rd.product_name || (rdStockDetail && rdStockDetail.item_name) || '', - receiving_actual_quantity: Number(rd.actual_quantity) || 0, - receiving_allocated: allocated, - receiving_available: available, - }); + const available = Math.max(0, qty - allocated); + + if (stockId === null) { + receivingOnly.push({ + receiving_product_name: name, + receiving_actual_quantity: qty, + receiving_allocated: allocated, + receiving_available: available, + }); + } else if (receivingStockMap.has(stockId)) { + const existing = receivingStockMap.get(stockId); + existing.receiving_actual_quantity += qty; + existing.receiving_allocated += allocated; + existing.receiving_available += available; + if (!existing.receiving_product_name && name) { + existing.receiving_product_name = name; + } + } else { + receivingStockMap.set(stockId, { + receiving_product_name: name, + receiving_actual_quantity: qty, + receiving_allocated: allocated, + receiving_available: available, + }); + } } } + for (const item of receivingStockMap.values()) { + item.receiving_available = Math.max(0, item.receiving_available); + receivingOnly.push(item); + } - // 10. 汇总 + // 汇总 const matchedItems = comparison.filter(c => c.match_status === 'matched').length; const entryOnlyItems = comparison.filter(c => c.match_status === 'entry_only').length; return { - code: 200, - message: '查询成功', - data: { - entry_order_id: entryOrderId, - entry_order_code: entryOrder.entry_order_code, - receiving_id: receivingId, - receiving_number: receivingOrder.receiving_number, - comparison, - receiving_only: receivingOnly, - summary: { - total_entry_items: entryItems.length, - matched_items: matchedItems, - entry_only_items: entryOnlyItems, - receiving_only_items: receivingOnly.length, - }, + receiving_id: receivingId, + receiving_number: receivingOrder.receiving_number, + status: 'matched', + comparison, + receiving_only: receivingOnly, + summary: { + total_entry_items: entryItems.length, + matched_items: matchedItems, + entry_only_items: entryOnlyItems, + receiving_only_items: receivingOnly.length, }, }; } diff --git a/app/service/systems/storage/inventory.js b/app/service/systems/storage/inventory.js index c3b0762..e1c7eac 100644 --- a/app/service/systems/storage/inventory.js +++ b/app/service/systems/storage/inventory.js @@ -171,9 +171,12 @@ async function loadStockAttachments(ctx, stockIds = []) { } } - // 提取图片 - if (detail.image_url) { - imagesByStockId.set(stockId, [ String(detail.image_url).trim() ]); + // 提取图片(兼容数组/字符串格式) + const imageUrls = Array.isArray(detail.image_url) + ? detail.image_url.map(u => String(u || '').trim()).filter(Boolean) + : (detail.image_url ? [ String(detail.image_url).trim() ] : []); + if (imageUrls.length > 0) { + imagesByStockId.set(stockId, imageUrls); } } } catch (error) { @@ -1394,6 +1397,334 @@ class InventoryService extends Service { }, }; } + /** + * 收货单快捷入库:判断货主配置是否允许收货单快捷入库,不允许直接返回失败; + * 允许的话使用收货单的明细创建入库单,相同 stock_id 的合并为一条,汇集总数。 + * 在 wms_entry_order_receiving 表建立绑定关系,入库单自动审批到 PENDING 状态。 + * + * @param {Object} data 请求体 + * @param {number} data.receiving_id 收货单ID(必填) + * @return {Promise} code/data/message 结构,data 中包含创建的入库单信息 + */ + async quickPutaway(data = {}) { + const { ctx, app } = this; + const receivingId = Number(data.receiving_id || 0); + + // ────────── 1. 参数校验 ────────── + if (!receivingId) { + return { code: 400, message: 'receiving_id 必填', data: null }; + } + + const warehouseId = ctx.user.store_id; + if (!warehouseId) { + return { code: 400, message: '无法获取当前仓库信息', data: null }; + } + + // ────────── 2. 加载收货单主表及明细 ────────── + const receiving = await ctx.model.Receiving.findOne({ + where: { id: receivingId, warehouse_id: warehouseId, is_deleted: false }, + }); + + if (!receiving) { + return { code: 404, message: `收货单不存在或无权访问: receiving_id=${receivingId}`, data: null }; + } + + if (receiving.status === 'cancelled') { + return { code: 400, message: '收货单已作废,不允许快捷入库', data: null }; + } + + if (receiving.status !== 'completed') { + return { code: 400, message: `收货单状态不允许快捷入库,当前状态: ${receiving.status},仅 completed 状态可操作`, data: null }; + } + + if (!receiving.is_review) { + return { code: 400, message: '收货单未审核,不允许快捷入库', data: null }; + } + + const storeId = receiving.store_id; + + // ────────── 3. 检查货主配置:是否允许收货单快捷入库 ────────── + const storeWarehouse = await ctx.model.StoreWarehouse.findOne({ + where: { store_id: storeId, warehouse_id: warehouseId, use_status: 1 }, + attributes: [ 'id', 'policy_config' ], + }); + + if (!storeWarehouse) { + return { code: 400, message: '货主仓库签约关系不存在', data: null }; + } + + const policyConfig = storeWarehouse.policy_config || {}; + const allowQuickPutaway = Number(policyConfig.allow_receiving_quick_putaway) === 1; + + if (!allowQuickPutaway) { + return { code: 400, message: '货主未开启收货单快捷入库功能,请联系管理员开启', data: null }; + } + + // ────────── 4. 加载收货单明细 ────────── + const receivingDetails = await ctx.model.ReceivingDetail.findAll({ + where: { receiving_id: receivingId }, + attributes: [ + 'id', 'system_product_id', 'actual_quantity', 'product_name', + 'batch_number', 'production_date', 'expiry_date', + 'storage_status', 'stored_quantity', + ], + }); + + if (!receivingDetails || receivingDetails.length === 0) { + return { code: 400, message: '收货单无明细,无法创建入库单', data: null }; + } + + // ────────── 5. 按 stock_id(system_product_id)分组,合并数量 ────────── + /** @type {Map} */ + const groupedMap = new Map(); + + for (const detail of receivingDetails) { + const stockId = Number(detail.system_product_id); + if (!stockId) { + // 跳过未匹配系统商品的明细 + continue; + } + + const qty = Number(detail.actual_quantity) || 0; + if (qty <= 0) { + continue; + } + + const existing = groupedMap.get(stockId); + if (existing) { + existing.total_quantity += qty; + existing.detail_ids.push(detail.id); + } else { + groupedMap.set(stockId, { + system_product_id: stockId, + total_quantity: qty, + product_name: detail.product_name || '', + batch_number: detail.batch_number || '', + production_date: detail.production_date || null, + expiry_date: detail.expiry_date || null, + detail_ids: [ detail.id ], + }); + } + } + + if (groupedMap.size === 0) { + return { code: 400, message: '收货单中所有明细均未关联系统商品,无法创建入库单', data: null }; + } + + const groupedItems = Array.from(groupedMap.values()); + + // ────────── 6. 批量查询 stock_warehouse 获取 stock_id 对应的商品信息 ────────── + const stockIds = groupedItems.map(item => item.system_product_id); + const stockRows = await ctx.model.StockWarehouse.findAll({ + where: { id: { [app.Sequelize.Op.in]: stockIds }, warehouse_id: warehouseId }, + attributes: [ 'id', 'item_code', 'item_name', 'stock_unit', 'is_valid' ], + raw: true, + }); + const stockMap = new Map(); + for (const row of stockRows) { + stockMap.set(Number(row.id), row); + } + + // 校验所有 stock_id 是否存在且有效 + const missingStockIds = stockIds.filter(sid => !stockMap.has(sid)); + if (missingStockIds.length > 0) { + return { + code: 400, + message: `以下商品在当前仓库中不存在或已失效: stock_id=${missingStockIds.join(',')}`, + data: null, + }; + } + + // ────────── 7. 开事务,创建入库单及明细 ────────── + const transaction = await ctx.model.transaction(); + + try { + // 获取货主和仓库名称快照 + const storeData = await ctx.service.systems.store.getStoreName(storeId); + const storeName = (storeData.code === 200 && storeData.data) ? storeData.data.company_name : ''; + const warehouseData = await ctx.service.systems.store.getStoreName(warehouseId); + const warehouseName = (warehouseData.code === 200 && warehouseData.data) ? warehouseData.data.company_name : ''; + + // 生成入库单号 + const entryOrderCode = await this._generateEntryOrderCode(warehouseId, storeId, transaction); + + // 创建入库单主表(状态直接设为 PENDING) + const entryOrder = await ctx.model.EntryOrder.create({ + entry_order_code: entryOrderCode, + order_type: 'SCRK', + total_order_lines: groupedItems.length, + order_create_time: new Date(), + source_type: 'WMS', + order_status: 'PENDING', + sync_status: 'PENDING', + is_enabled: 1, + warehouse_id: warehouseId, + store_id: storeId, + store_name: storeName, + warehouse_name: warehouseName, + remark: `收货单${receiving.receiving_number}快捷入库`, + expense_record: 0, + }, { transaction }); + + const entryOrderId = entryOrder.id; + + // 创建入库单明细(按合并后的分组) + for (let i = 0; i < groupedItems.length; i++) { + const group = groupedItems[i]; + const stockInfo = stockMap.get(group.system_product_id); + + await ctx.model.EntryItems.create({ + order_id: entryOrderId, + out_biz_code: '', + order_line_no: i + 1, + owner_code: '', + item_code: stockInfo ? stockInfo.item_code : '', + item_id: 0, + count: group.total_quantity, + inventory_type: 'ZP', + stock_id: group.system_product_id, + received_quantity: 0, + confirm_quantity: 0, + }, { transaction }); + } + + // ────────── 8. 写入 wms_entry_order_receiving 绑定关系 ────────── + await ctx.model.EntryOrderReceiving.create({ + entry_order_id: entryOrderId, + receiving_id: receivingId, + }, { transaction }); + + // ────────── 9. 更新收货单主表 storage_status ────────── + // 快捷入库后收货单进入"等待入库"状态(后续可通过 matchPutaway 补全) + const [ affectedRows ] = await ctx.model.Receiving.update({ + storage_status: 'waiting', + updated_at: new Date(), + }, { + where: { id: receivingId, storage_status: 'none' }, + transaction, + }); + + if (affectedRows === 0) { + await transaction.rollback(); + return { code: 400, message: '收货单入库状态已变更,可能已被其他操作处理,禁止重复快捷入库', data: null }; + } + + // ────────── 10. 更新收货单明细的 storage_status 为 waiting,stored_quantity 为对应用量 ────────── + for (const group of groupedItems) { + for (const detailId of group.detail_ids) { + const detailRow = receivingDetails.find(d => d.id === detailId); + if (!detailRow) continue; + + // 该明细的总量和已入库量 + const detailTotalQty = Number(detailRow.actual_quantity) || 0; + // 该明细在本次合并中的贡献量按比例计入(简化:按该明细数量在合并总量中的占比) + const detailRatio = group.total_quantity > 0 ? detailTotalQty / group.total_quantity : 0; + const thisStoredQty = Math.round(detailRatio * group.total_quantity); + + const newStoredQty = Math.min(detailTotalQty, (Number(detailRow.stored_quantity) || 0) + thisStoredQty); + // 明细实际数量表示的是该明细的收货量,合并后该 SKU 的明细可能有多条 + // 简化:如果该明细被完全用完则设为 all,否则 waiting(等待手工上架) + const newStorageStatus = newStoredQty >= detailTotalQty ? 'all' : 'waiting'; + + await ctx.model.ReceivingDetail.update({ + storage_status: newStorageStatus, + stored_quantity: newStoredQty, + updated_at: new Date(), + }, { + where: { id: detailId }, + transaction, + }); + } + } + + // ────────── 11. 操作日志 ────────── + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'entry_order', + businessId: entryOrderId, + operationCode: 'ENTRY_ORDER_QUICK_PUTAWAY', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId, + storeId, + receivingId, + entryOrderCode, + receivingNumber: receiving.receiving_number, + totalLines: groupedItems.length, + }, + transaction, + }); + } catch (logErr) { + ctx.logger.warn('[inventory.quickPutaway] 写入操作日志失败,不影响业务', logErr); + } + + // ────────── 12. 提交事务 ────────── + await transaction.commit(); + + ctx.logger.info(`[inventory.quickPutaway] 快捷入库完成 entryOrderId=${entryOrderId} receivingId=${receivingId} lines=${groupedItems.length}`); + + return { + code: 200, + message: '快捷入库成功', + data: { + entry_order_id: entryOrderId, + entry_order_code: entryOrderCode, + order_status: 'PENDING', + receiving_id: receivingId, + total_lines: groupedItems.length, + total_quantity: groupedItems.reduce((sum, g) => sum + g.total_quantity, 0), + }, + }; + } catch (error) { + await transaction.rollback(); + ctx.logger.error(`[inventory.quickPutaway] 快捷入库异常 receivingId=${receivingId}: ${error.message}`, error.stack); + return { code: 500, message: `系统异常: ${error.message}`, data: null }; + } + } + + /** + * 生成入库单号。 + * 格式:SCRK + 年月日 + 4位流水号 + * + * @param {number} warehouseId 仓库ID + * @param {number} storeId 货主ID + * @param {Object} transaction 数据库事务 + * @return {Promise} 生成的入库单号 + */ + async _generateEntryOrderCode(warehouseId, storeId, transaction) { + const { ctx, app } = this; + const now = new Date(); + const dateStr = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}`; + const prefix = `SCRK${dateStr}`; + + // 查询当天该仓库+货主下已有的最大入库单号 + const lastOrder = await ctx.model.EntryOrder.findOne({ + where: { + entry_order_code: { [app.Sequelize.Op.like]: `${prefix}%` }, + warehouse_id: warehouseId, + store_id: storeId, + }, + order: [[ 'entry_order_code', 'DESC' ]], + attributes: [ 'entry_order_code' ], + transaction, + raw: true, + paranoid: false, + }); + + let seq = 1; + if (lastOrder && lastOrder.entry_order_code) { + const seqPart = lastOrder.entry_order_code.slice(prefix.length); + const seqNum = parseInt(seqPart, 10); + if (!Number.isNaN(seqNum)) { + seq = seqNum + 1; + } + } + + return `${prefix}${String(seq).padStart(4, '0')}`; + } } module.exports = InventoryService; diff --git a/app/service/systems/storage/receiving.js b/app/service/systems/storage/receiving.js index a4d4d81..cc93682 100644 --- a/app/service/systems/storage/receiving.js +++ b/app/service/systems/storage/receiving.js @@ -35,9 +35,12 @@ class ReceivingService extends Service { * @param {number} [pageParams.page=1] 页码 * @param {number} [pageParams.pageSize=20] 每页条数 * @param {Object} [sortParams] 排序参数 + * @param {Object} [options] 额外选项 + * @param {boolean} [options.filterDepleted=false] 是否过滤掉无可再用量的收货单 + * @param {number} [options.entry_order_id] 可选,按入库单商品交集过滤:只返回"至少有一条明细的 system_product_id 在入库单明细中"的收货单 * @return {Promise} 列表、分页与汇总信息 */ - async getReceivingList(where, pageParams = {}, sortParams = {}) { + async getReceivingList(where, pageParams = {}, sortParams = {}, options = {}) { const { ctx, app, @@ -58,6 +61,7 @@ class ReceivingService extends Service { sortField = 'id', sortOrder = 'DESC', } = sortParams; + const { filterDepleted = false, entry_order_id: entryOrderId } = options; const queryOptions = { where: { @@ -175,14 +179,147 @@ class ReceivingService extends Service { }, ]; + // 可选过滤:排除无可再用量的收货单 + let filteredReceivingIds = null; + if (filterDepleted) { + const candidateRows = await ctx.model.Receiving.findAll({ + attributes: [ 'id' ], + where: queryOptions.where, + include, + distinct: true, + raw: true, + }); + const candidateIds = candidateRows.map(r => r.id); + + if (candidateIds.length > 0) { + // 1. 候选收货单明细的 actual_quantity 总和(按 receiving_id 分组) + const detailSums = await ctx.model.ReceivingDetail.findAll({ + attributes: [ + 'receiving_id', + [ Sequelize.fn('SUM', Sequelize.col('actual_quantity')), 'total_actual' ], + ], + where: { receiving_id: { [Op.in]: candidateIds } }, + group: [ 'receiving_id' ], + raw: true, + }); + const totalActualMap = {}; + for (const row of detailSums) { + totalActualMap[row.receiving_id] = Number(row.total_actual) || 0; + } + + // 2. 这些明细对应的 committed 绑定量(按 receiving_detail_id 分组) + const detailIds = detailSums.length > 0 + ? (await ctx.model.ReceivingDetail.findAll({ + attributes: [ 'id' ], + where: { receiving_id: { [Op.in]: candidateIds } }, + raw: true, + })).map(r => r.id) + : []; + + const committedByDetailId = {}; + if (detailIds.length > 0) { + const bindingRows = await ctx.model.EntryReceivingBinding.findAll({ + attributes: [ + 'receiving_detail_id', + [ Sequelize.fn('SUM', Sequelize.col('allocated_quantity')), 'committed_sum' ], + ], + where: { + receiving_detail_id: { [Op.in]: detailIds }, + status: 'committed', + }, + group: [ 'receiving_detail_id' ], + raw: true, + }); + for (const row of bindingRows) { + committedByDetailId[row.receiving_detail_id] = Number(row.committed_sum) || 0; + } + } + + // 3. 计算每个收货单的剩余可用量 = SUM(actual_quantity) - SUM(committed) + const idToDetailIdsMap = {}; + if (detailIds.length > 0) { + const detailIdRows = await ctx.model.ReceivingDetail.findAll({ + attributes: [ 'id', 'receiving_id' ], + where: { id: { [Op.in]: detailIds } }, + raw: true, + }); + for (const d of detailIdRows) { + if (!idToDetailIdsMap[d.receiving_id]) idToDetailIdsMap[d.receiving_id] = []; + idToDetailIdsMap[d.receiving_id].push(d.id); + } + } + + const remainingByReceivingId = {}; + for (const receivingId of candidateIds) { + const totalActual = totalActualMap[receivingId] || 0; + const detailIdList = idToDetailIdsMap[receivingId] || []; + const totalCommitted = detailIdList.reduce((sum, did) => sum + (committedByDetailId[did] || 0), 0); + remainingByReceivingId[receivingId] = totalActual - totalCommitted; + } + + // 过滤:只保留剩余可用量 > 0 的收货单 + filteredReceivingIds = candidateIds.filter(id => remainingByReceivingId[id] > 0); + } else { + filteredReceivingIds = []; + } + } + + // 可选过滤:按入库单商品交集过滤(只返回 system_product_id 有交集的收货单) + let intersectionFilteredIds = null; + if (entryOrderId) { + // 1. 查该入库单的所有 entry_items → stock_id 集合 + const entryItemRows = await ctx.model.EntryItems.findAll({ + where: { order_id: entryOrderId }, + attributes: [ 'stock_id' ], + raw: true, + }); + const entrySpIdSet = new Set(entryItemRows.map(r => r.stock_id).filter(Boolean)); + + if (entrySpIdSet.size === 0) { + // 入库单无明细 → 不返回任何收货单 + intersectionFilteredIds = []; + } else { + // 2. 查所有收货单明细,找出 system_product_id 在 entrySpIdSet 中的收货单 ID + const matchingDetailRows = await ctx.model.ReceivingDetail.findAll({ + attributes: [ 'receiving_id' ], + where: { + system_product_id: { [Op.in]: [ ...entrySpIdSet ] }, + }, + group: [ 'receiving_id' ], + raw: true, + }); + intersectionFilteredIds = matchingDetailRows.map(r => r.receiving_id); + } + } + + // 合并 filterDepleted 和 entry_order_id 的过滤结果 + let combinedFilteredIds = null; + if (filteredReceivingIds !== null || intersectionFilteredIds !== null) { + if (filteredReceivingIds !== null && intersectionFilteredIds !== null) { + // 两个过滤都启用 → 取交集 + const intersectionSet = new Set(intersectionFilteredIds); + combinedFilteredIds = filteredReceivingIds.filter(id => intersectionSet.has(id)); + } else if (filteredReceivingIds !== null) { + combinedFilteredIds = filteredReceivingIds; + } else { + combinedFilteredIds = intersectionFilteredIds; + } + } + + // 如果启用了过滤,用过滤后的 ID 做最终查询 + const finalWhere = combinedFilteredIds !== null + ? { id: { [Op.in]: combinedFilteredIds } } + : queryOptions.where; + const [ total, data ] = await Promise.all([ ctx.model.Receiving.count({ - where: queryOptions.where, + where: finalWhere, include, distinct: true, }), ctx.model.Receiving.findAll({ ...queryOptions, + where: finalWhere, include, limit: parseInt(pageSize), offset: parseInt(offset), @@ -217,8 +354,9 @@ class ReceivingService extends Service { } const processedData = data.map(item => { - const availableQuantity = Math.max(0, item.quantity - item.locked_quantity); - const lockRate = item.quantity > 0 ? (item.locked_quantity / item.quantity * 100).toFixed(2) : 0; + // 注意:wms_receiving 表中没有 locked_quantity 字段,total_quantity 为商品总数量 + const availableQuantity = Math.max(0, item.total_quantity || 0); + const lockRate = 0; const itemImages = images .filter(row => parseInt(row.business_id) === item.id) .map(row => row.file.file_url); @@ -234,9 +372,9 @@ class ReceivingService extends Service { }); const summary = { - total_quantity: data.reduce((sum, item) => sum + item.quantity, 0), - total_locked: data.reduce((sum, item) => sum + item.locked_quantity, 0), - total_available: data.reduce((sum, item) => sum + Math.max(0, item.quantity - item.locked_quantity), 0), + total_quantity: data.reduce((sum, item) => sum + (item.total_quantity || 0), 0), + total_locked: 0, + total_available: data.reduce((sum, item) => sum + (item.total_quantity || 0), 0), total_items: data.length, }; @@ -4218,6 +4356,157 @@ class ReceivingService extends Service { } } + /** + * PDA 扫码定位收货明细:通过入库单ID + 扫描条码快速定位收货明细。 + * 搜索策略: + * 1. 通过 entry_order_id → wms_entry_order_receiving 查出关联的 receiving_id 列表; + * 2. 查出所有未绑定的收货明细(仅按 receiving_id IN + 排除已绑定过滤); + * 3. 收集明细的 system_product_id,批量调用 getStockDetails 获取条码信息; + * 4. 在内存中遍历明细进行精确匹配: + * - 若 barcode 为纯数字,优先按明细 ID 精确匹配; + * - 再按 getStockDetails 返回的 barcodes[].barcode 精确匹配商品条码; + * 5. 返回所有匹配的明细列表(同一条码可能匹配到多条收货明细)。 + * @param {number} entryOrderId 入库单ID + * @param {string} barcode 扫描条码(商品条码/箱唛/托盘唛/明细ID) + * @return {Promise} 包含 code、message 与匹配明细列表 data.list 的结果对象 + */ + async scanDetail(entryOrderId, barcode) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const warehouseId = ctx.user?.store_id; + + // 参数校验 + if (!warehouseId) { + return { code: 0, message: '用户未绑定仓库', data: null }; + } + if (!entryOrderId || Number(entryOrderId) <= 0) { + return { code: 0, message: '入库单ID不能为空', data: null }; + } + if (!barcode || String(barcode).trim() === '') { + return { code: 0, message: '扫描条码不能为空', data: null }; + } + + const normalizedBarcode = String(barcode).trim(); + const normalizedEntryOrderId = Number(entryOrderId); + + try { + // 1. 验证入库单存在且属于当前仓库 + const entryOrder = await ctx.model.EntryOrder.findOne({ + where: { + id: normalizedEntryOrderId, + warehouse_id: warehouseId, + }, + attributes: [ 'id' ], + raw: true, + }); + + if (!entryOrder) { + return { code: 0, message: '入库单不存在或无权访问', data: null }; + } + + // 2. 通过 wms_entry_order_receiving 查出关联的 receiving_id 列表 + const entryReceivingRows = await ctx.model.EntryOrderReceiving.findAll({ + where: { entry_order_id: normalizedEntryOrderId }, + attributes: [ 'receiving_id' ], + raw: true, + }); + + const receivingIds = entryReceivingRows.map(r => r.receiving_id).filter(Boolean); + if (receivingIds.length === 0) { + return { code: 0, message: '该入库单尚未关联收货单', data: null }; + } + + // 排除已绑定的收货明细(wms_entry_receiving_binding 中有记录且未软删除) + const notBoundCondition = app.Sequelize.literal( + 'NOT EXISTS (SELECT 1 FROM wms_entry_receiving_binding erb WHERE erb.receiving_detail_id = wms_receiving_detail.id AND erb.deleted_at IS NULL)' + ); + + // 3. 查出所有未绑定的收货明细(不再在 SQL 层做 barcode 模糊匹配) + const details = await ctx.model.ReceivingDetail.findAll({ + where: { + [Op.and]: [ + { receiving_id: { [Op.in]: receivingIds } }, + notBoundCondition, + ], + }, + raw: true, + }); + + if (details.length === 0) { + return { code: 0, message: '未找到可用的收货明细', data: null }; + } + + // 4. 收集所有明细的 system_product_id,批量调用 getStockDetails 获取条码 + const stockIdSet = new Set(); + for (const d of details) { + if (d.system_product_id != null) { + stockIdSet.add(Number(d.system_product_id)); + } + } + const stockIds = [ ...stockIdSet ]; + + /** @type {Map} */ + const stockDetailMap = new Map(); + if (stockIds.length > 0) { + const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(stockIds, { warehouseId }); + for (const sd of stockDetails) { + if (sd && sd.id != null) { + stockDetailMap.set(sd.id, sd); + } + } + } + + // 5. 在内存中遍历明细,精确匹配,收集所有命中 + const isNumericBarcode = /^\d+$/.test(normalizedBarcode); + const matchedDetails = []; + + for (const detail of details) { + // 优先按明细 ID 精确匹配(托盘唛头场景) + if (isNumericBarcode && detail.id === Number(normalizedBarcode)) { + matchedDetails.push(detail); + continue; + } + + // 按商品条码精确匹配 + const stockDetail = stockDetailMap.get(detail.system_product_id); + if (stockDetail && Array.isArray(stockDetail.barcodes)) { + const barcodeMatch = stockDetail.barcodes.some( + bc => bc.barcode === normalizedBarcode + ); + if (barcodeMatch) { + matchedDetails.push(detail); + } + } + } + + if (matchedDetails.length === 0) { + return { code: 0, message: '未找到匹配的收货明细', data: null }; + } + + const list = matchedDetails.map(matchedDetail => ({ + detail_id: matchedDetail.id, + receiving_id: matchedDetail.receiving_id, + barcode: matchedDetail.barcode || '', + product_name: matchedDetail.product_name || '', + actual_quantity: matchedDetail.actual_quantity || 0, + receiving_status: matchedDetail.receiving_status || '', + stock: stockDetailMap.get(Number(matchedDetail.system_product_id)) || null, + })); + + return { + code: 200, + message: '查询成功', + data: { + list, + total: list.length, + }, + }; + } catch (error) { + ctx.logger.error('[receiving.scanDetail] 扫码定位收货明细失败', error); + return { code: 500, message: `服务器错误: ${error.message}`, data: null }; + } + } + } module.exports = ReceivingService; diff --git a/config/config.default.js b/config/config.default.js index 2627a9e..c012498 100644 --- a/config/config.default.js +++ b/config/config.default.js @@ -130,7 +130,7 @@ module.exports = appInfo => { 'audio/x-m4a': 'audio', }; config.cors = { - origin: '*', // 允许所有源,生产环境应指定具体域名 + origin: (ctx) => ctx.get('Origin'), // 动态返回请求源,配合 credentials: true 使用 allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS', exposeHeaders: 'Authorization', credentials: true, // 允许携带 cookie @@ -180,6 +180,7 @@ module.exports = appInfo => { config.jwt = { expiresIn: 14400, + renewThreshold: 7200, secret: 'E5#ex.g@,GfL_8?', }; diff --git a/database/migrations/20260629-add-waiting-storage-status.js b/database/migrations/20260629-add-waiting-storage-status.js new file mode 100644 index 0000000..32f8792 --- /dev/null +++ b/database/migrations/20260629-add-waiting-storage-status.js @@ -0,0 +1,76 @@ +'use strict'; + +/** + * 打印迁移阶段对应的数据库连接上下文信息。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {'up'|'down'} phase 迁移阶段。 + * @param {string} table 迁移目标表名。 + * @return {Promise} 无返回值。 + */ +const logMigrationDbContext = async (queryInterface, phase, table) => { + try { + const [rows] = await queryInterface.sequelize.query( + 'SELECT DATABASE() AS db_name, @@hostname AS db_host, @@port AS db_port, CURRENT_USER() AS db_user' + ); + const dbContext = Array.isArray(rows) && rows.length > 0 ? rows[0] : {}; + console.log( + `[Migration DB Context] phase=${phase}; table=${table}; db_name=${dbContext.db_name || 'unknown'}; db_host=${dbContext.db_host || 'unknown'}; db_port=${dbContext.db_port || 'unknown'}; db_user=${dbContext.db_user || 'unknown'}` + ); + } catch (error) { + console.warn( + `[Migration DB Context] 获取连接信息失败: phase=${phase}; table=${table}; reason=${error.message}` + ); + } +}; + +/** + * Migration: 为 wms_receiving 和 wms_receiving_detail 表的 storage_status 列新增 waiting 枚举值 + * + * 正向 SQL: + * ALTER TABLE wms_receiving MODIFY COLUMN storage_status ENUM('none','waiting','partial','all') NOT NULL DEFAULT 'none' COMMENT '入库状态:none-未入库, waiting-等待入库, partial-部分入库, all-全部入库'; + * ALTER TABLE wms_receiving_detail MODIFY COLUMN storage_status ENUM('none','waiting','partial','all') NOT NULL DEFAULT 'none' COMMENT '入库状态:none-未入库, waiting-等待入库, partial-部分入库, all-全部入库'; + * + * 回滚 SQL: + * ALTER TABLE wms_receiving MODIFY COLUMN storage_status ENUM('none','partial','all') NOT NULL DEFAULT 'none' COMMENT '入库状态:none-未入库, partial-部分入库, all-全部入库'; + * ALTER TABLE wms_receiving_detail MODIFY COLUMN storage_status ENUM('none','partial','all') NOT NULL DEFAULT 'none' COMMENT '入库状态:none-未入库, partial-部分入库, all-全部入库'; + */ + +const UP_SQL_RECEIVING = `ALTER TABLE wms_receiving MODIFY COLUMN storage_status ENUM('none','waiting','partial','all') NOT NULL DEFAULT 'none' COMMENT '入库状态:none-未入库, waiting-等待入库, partial-部分入库, all-全部入库'`; +const DOWN_SQL_RECEIVING = `ALTER TABLE wms_receiving MODIFY COLUMN storage_status ENUM('none','partial','all') NOT NULL DEFAULT 'none' COMMENT '入库状态:none-未入库, partial-部分入库, all-全部入库'`; + +const UP_SQL_DETAIL = `ALTER TABLE wms_receiving_detail MODIFY COLUMN storage_status ENUM('none','waiting','partial','all') NOT NULL DEFAULT 'none' COMMENT '入库状态:none-未入库, waiting-等待入库, partial-部分入库, all-全部入库'`; +const DOWN_SQL_DETAIL = `ALTER TABLE wms_receiving_detail MODIFY COLUMN storage_status ENUM('none','partial','all') NOT NULL DEFAULT 'none' COMMENT '入库状态:none-未入库, partial-部分入库, all-全部入库'`; + +module.exports = { + /** + * 执行正向迁移,为 storage_status 列新增 waiting 枚举值。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + up: async (queryInterface, Sequelize) => { + await logMigrationDbContext(queryInterface, 'up', 'wms_receiving'); + await queryInterface.sequelize.query(UP_SQL_RECEIVING); + console.log('[Migration] wms_receiving.storage_status 已新增 waiting 枚举值'); + + await logMigrationDbContext(queryInterface, 'up', 'wms_receiving_detail'); + await queryInterface.sequelize.query(UP_SQL_DETAIL); + console.log('[Migration] wms_receiving_detail.storage_status 已新增 waiting 枚举值'); + }, + + /** + * 执行回滚迁移,移除 waiting 枚举值,恢复为原有枚举。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + down: async (queryInterface, Sequelize) => { + await logMigrationDbContext(queryInterface, 'down', 'wms_receiving'); + await queryInterface.sequelize.query(DOWN_SQL_RECEIVING); + console.log('[Migration] wms_receiving.storage_status 已移除 waiting 枚举值'); + + await logMigrationDbContext(queryInterface, 'down', 'wms_receiving_detail'); + await queryInterface.sequelize.query(DOWN_SQL_DETAIL); + console.log('[Migration] wms_receiving_detail.storage_status 已移除 waiting 枚举值'); + }, +}; diff --git a/database/migrations/20260630160000-create-wms-order-stockout.js b/database/migrations/20260630160000-create-wms-order-stockout.js new file mode 100644 index 0000000..609fc87 --- /dev/null +++ b/database/migrations/20260630160000-create-wms-order-stockout.js @@ -0,0 +1,309 @@ +'use strict'; + +const MAIN_TABLE = 'wms_order_stockout'; +const ITEMS_TABLE = 'wms_order_stockout_items'; + +/** + * 创建奇门出库单主表与明细表。 + * + * - wms_order_stockout:出库单主表(对应奇门 stockout.create 的 节点) + * - wms_order_stockout_items:出库明细表(对应 节点) + * + * 幂等:如果表已存在则跳过创建。 + */ +module.exports = { + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + + const exists = name => + tables.some(t => (typeof t === 'string' ? t : t.tableName) === name); + + // ----------------------- 主表 ----------------------- + if (!exists(MAIN_TABLE)) { + await queryInterface.createTable(MAIN_TABLE, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + stockout_order_code: { + type: Sequelize.STRING(50), + allowNull: false, + comment: '出库单号(对应奇门 deliveryOrderCode)', + }, + order_type: { + type: Sequelize.STRING(50), + allowNull: false, + comment: '业务类型(JYCK/HHCK/BFCK/QTCK 等)', + }, + total_order_lines: { + type: Sequelize.INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '单据总行数', + }, + order_create_time: { + type: Sequelize.DATE, + allowNull: true, + comment: '订单创建时间(对应奇门 createTime)', + }, + source_type: { + type: Sequelize.ENUM('WMS', 'API', 'QM'), + allowNull: false, + defaultValue: 'QM', + comment: '来源类型', + }, + order_status: { + type: Sequelize.ENUM('CREATING', 'CREATED', 'PENDING', 'COMPLETED', 'CANCELLED'), + allowNull: false, + defaultValue: 'CREATED', + comment: '订单状态', + }, + sync_status: { + type: Sequelize.ENUM('PENDING', 'SUCCESS', 'FAILED'), + allowNull: false, + defaultValue: 'PENDING', + comment: '同步状态', + }, + sync_message: { + type: Sequelize.TEXT, + allowNull: true, + comment: '同步返回信息', + }, + warehouse_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + store_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '货主ID', + }, + store_name: { + type: Sequelize.STRING(200), + allowNull: true, + comment: '货主名称快照', + }, + warehouse_name: { + type: Sequelize.STRING(200), + allowNull: true, + comment: '仓库名称快照', + }, + qimen_owner_code: { + type: Sequelize.STRING(100), + allowNull: true, + comment: '奇门货主code(对应 ownerCode)', + }, + qimen_warehouse_code: { + type: Sequelize.STRING(100), + allowNull: true, + comment: '奇门仓库code(对应 warehouseCode)', + }, + remark: { + type: Sequelize.STRING(500), + allowNull: true, + comment: '备注', + }, + extend_props: { + type: Sequelize.JSON, + allowNull: true, + comment: '扩展属性', + }, + is_enabled: { + type: Sequelize.TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '是否启用', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '软删除时间', + }, + }); + + // 唯一索引:(stockout_order_code, warehouse_id, store_id) + await queryInterface.addIndex(MAIN_TABLE, [ 'stockout_order_code', 'warehouse_id', 'store_id' ], { + unique: true, + name: 'uk_stockout_order_code', + }); + + // 辅助查询索引 + await queryInterface.addIndex(MAIN_TABLE, [ 'order_type' ], { + name: 'idx_order_type', + }); + await queryInterface.addIndex(MAIN_TABLE, [ 'order_status' ], { + name: 'idx_order_status', + }); + await queryInterface.addIndex(MAIN_TABLE, [ 'sync_status' ], { + name: 'idx_sync_status', + }); + await queryInterface.addIndex(MAIN_TABLE, [ 'source_type' ], { + name: 'idx_source_type', + }); + await queryInterface.addIndex(MAIN_TABLE, [ 'warehouse_id', 'store_id' ], { + name: 'idx_warehouse_store', + }); + await queryInterface.addIndex(MAIN_TABLE, [ 'order_create_time' ], { + name: 'idx_order_create_time', + }); + await queryInterface.addIndex(MAIN_TABLE, [ 'is_enabled' ], { + name: 'idx_is_enabled', + }); + await queryInterface.addIndex(MAIN_TABLE, [ 'deleted_at' ], { + name: 'idx_deleted_at', + }); + } + + // ----------------------- 明细表 ----------------------- + if (!exists(ITEMS_TABLE)) { + await queryInterface.createTable(ITEMS_TABLE, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + order_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '出库单ID,外键关联 wms_order_stockout.id', + }, + out_biz_code: { + type: Sequelize.STRING(255), + allowNull: true, + comment: '外部业务编码(幂等键)', + }, + order_line_no: { + type: Sequelize.STRING(50), + allowNull: false, + comment: '订单行号(对应奇门 orderLineNo)', + }, + owner_code: { + type: Sequelize.STRING(50), + allowNull: true, + comment: '货主编码(对应奇门 ownerCode)', + }, + item_code: { + type: Sequelize.STRING(50), + allowNull: true, + comment: '商品编码(对应奇门 itemCode)', + }, + item_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: 'WMS商品ID(对应奇门 itemId)', + }, + item_name: { + type: Sequelize.STRING(200), + allowNull: true, + comment: '商品名称', + }, + plan_qty: { + type: Sequelize.INTEGER(12), + allowNull: true, + comment: '计划数量(对应奇门 planQty)', + }, + actual_qty: { + type: Sequelize.INTEGER(12), + allowNull: false, + defaultValue: 0, + comment: '实发数量', + }, + inventory_type: { + type: Sequelize.STRING(50), + allowNull: true, + comment: '库存类型(ZP正品/CC残次等)', + }, + stock_id: { + type: Sequelize.BIGINT(20), + allowNull: true, + comment: '库存ID,外键关联 wms_stock_warehouse.id', + }, + extend_props: { + type: Sequelize.JSON, + allowNull: true, + comment: '扩展属性', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + }); + + // 唯一索引:(order_id, order_line_no) + await queryInterface.addIndex(ITEMS_TABLE, [ 'order_id', 'order_line_no' ], { + unique: true, + name: 'uk_order_line_no', + }); + + // 辅助索引 + await queryInterface.addIndex(ITEMS_TABLE, [ 'order_id' ], { + name: 'idx_order_id', + }); + await queryInterface.addIndex(ITEMS_TABLE, [ 'stock_id' ], { + name: 'idx_stock_id', + }); + await queryInterface.addIndex(ITEMS_TABLE, [ 'item_code' ], { + name: 'idx_item_code', + }); + await queryInterface.addIndex(ITEMS_TABLE, [ 'out_biz_code' ], { + name: 'idx_out_biz_code', + }); + + // 外键约束 + await queryInterface.addConstraint(ITEMS_TABLE, { + fields: [ 'order_id' ], + type: 'foreign key', + name: 'fk_items_order_id', + references: { + table: MAIN_TABLE, + field: 'id', + }, + onDelete: 'CASCADE', + onUpdate: 'CASCADE', + }); + + await queryInterface.addConstraint(ITEMS_TABLE, { + fields: [ 'stock_id' ], + type: 'foreign key', + name: 'fk_items_stock_id', + references: { + table: 'wms_stock_warehouse', + field: 'id', + }, + onDelete: 'RESTRICT', + onUpdate: 'CASCADE', + }); + } + }, + + down: async queryInterface => { + await queryInterface.dropTable(ITEMS_TABLE); + await queryInterface.dropTable(MAIN_TABLE); + }, +}; diff --git a/docs/order-workbench-list-api.md b/docs/order-workbench-list-api.md index c6dbf67..7b99c0a 100644 --- a/docs/order-workbench-list-api.md +++ b/docs/order-workbench-list-api.md @@ -118,6 +118,7 @@ | oaid | string | OAID | 设备/终端标识 | | sync_status | enum | 同步状态 | padding=待同步,fin=完成,error=失败 | | store_id | number | 货主ID | 货主主键 | +| store_remark | string | 货主备注 | 来自 wms_store_warehouse.store_remask,服务层按 store_id+warehouse_id 聚合填充 | | warehouse_id | number | 仓库ID | 仓库主键 | | from_key | number | 来源键 | 来源系统键值 | | items | string | 商品JSON字符串 | 原始商品明细 JSON | diff --git a/order_todo.md b/docs/order_todo.md similarity index 100% rename from order_todo.md rename to docs/order_todo.md diff --git a/docs/storage-receiving-api.md b/docs/storage-receiving-api.md index 185f289..fdee9fe 100644 --- a/docs/storage-receiving-api.md +++ b/docs/storage-receiving-api.md @@ -467,7 +467,7 @@ curl -X POST "http://127.0.0.1:6060/system?method=storage.receiving.bindDetailPr |---|---|---| | `storage.entry.bindReceivingDetails` | 入库单明细与收货明细逐行绑定(基于 `wms_entry_receiving_binding` 表),关系已改为 `wms_entry_order_receiving` 主表级关联 | 不再需要,入库单与收货单直接通过主表关联 | | `storage.entry.unbindReceivingDetails` | 同上,逐行解绑已无必要 | 不再需要 | -| `storage.inventory.quickPutaway` | 单一收货单快捷入库,功能受限 | `storage.inventory.matchPutaway`(支持多收货单+多入库单批量匹配入库) | +| `storage.inventory.quickPutaway` | 单一收货单快捷转入库单(已重新实现):按 stock_id 合并收货明细创建入库单(SCRK,自动审批到 PENDING),写入主表级绑定 | `storage.entry.commitDirectInbound`(导入/PDA 入库完成确认) | ### 14.4 核心方法职责 diff --git a/methods/changes/2026-06-24-add-bind-receiving-details.json b/methods/changes/2026-06-24-add-bind-receiving-details.json deleted file mode 100644 index 37a9170..0000000 --- a/methods/changes/2026-06-24-add-bind-receiving-details.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "date": "2026-06-24", - "type": "addition", - "method": "storage.entry.bindReceivingDetails", - "summary": "新增批量绑定入库单明细与收货单明细接口,支持明细级数量分配与部分成功", - "related": ["storage.entry.get 追加 available_receiving_details 字段"] -} diff --git a/methods/changes/2026-06-24-deprecate-manual-match-entry-order.json b/methods/changes/2026-06-24-deprecate-manual-match-entry-order.json deleted file mode 100644 index 64c2dc7..0000000 --- a/methods/changes/2026-06-24-deprecate-manual-match-entry-order.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "date": "2026-06-24", - "type": "deprecation", - "method": "storage.receiving.manualMatchEntryOrder", - "summary": "废弃手动匹配入库单收货单接口,由 storage.entry.bindReceivingDetails 替代", - "migration": "使用 storage.entry.get(含 available_receiving_details 元数据)加载可匹配的收货单明细,然后调用 storage.entry.bindReceivingDetails 批量提交绑定" -} diff --git a/methods/changes/2026.05.08-system-06.json b/methods/changes/2026.05.08-system-06.json deleted file mode 100644 index 66a7b16..0000000 --- a/methods/changes/2026.05.08-system-06.json +++ /dev/null @@ -1,16 +0,0 @@ -[ - { - "version": "2026.05.08-system-06", - "date": "2026-05-08", - "summary": "新增取消拣货任务接口:order.wave.wavePickTaskCancel", - "methods": [ - "order.wave.wavePickTaskCancel" - ], - "notes": [ - "接口功能:取消拣货任务,同时释放关联波次(物理删除波次记录,订单回池)、解绑拣货车、写操作日志。", - "限制:仅允许在任务状态为 0(待开始)、1(拣货中)、2(待复核)时取消;状态为 3(已完成)或 9(已取消)时禁止取消,返回 400。", - "事务内操作:将任务状态更新为 9(已取消)、删除关联波次、清空订单 wave_id(回池)、解绑拣货车、写入 action_log 与 order_pick_trace;若有任一步骤失败则回滚并返回 500。" - ], - "type": "added" - } -] diff --git a/methods/changes/2026.05.13-system-01.json b/methods/changes/2026.05.13-system-01.json deleted file mode 100644 index e46b3d6..0000000 --- a/methods/changes/2026.05.13-system-01.json +++ /dev/null @@ -1,17 +0,0 @@ -[ - { - "version": "2026.05.13-system-01", - "date": "2026-05-13", - "summary": "完善 print.send 的 API 文档与返回说明", - "methods": [ - "print.send" - ], - "notes": [ - "补充请求参数说明:computerId、printer、template、data、type 标为必填,count、timestamp 保持可选。", - "补充 template 的子字段说明:page_width、page_height、template_content。", - "补充响应结构:flag、code、message、printId;其中成功时 code=200。", - "补充错误码说明:1001 对应不支持的打印类型,504 对应打印任务发送失败(包含打印机不存在、脱机、通讯失败等场景)。" - ], - "type": "updated" - } -] diff --git a/methods/changes/2026.05.20-system-01.json b/methods/changes/2026.05.20-system-01.json deleted file mode 100644 index 8424c5d..0000000 --- a/methods/changes/2026.05.20-system-01.json +++ /dev/null @@ -1,19 +0,0 @@ -[ - { - "version": "2026.05.20-system-01", - "date": "2026-05-20", - "summary": "新增订单复核模块方法:order.recheckOrder.scanOrder、order.recheckOrder.confirmRecheck", - "methods": [ - "order.recheckOrder.scanOrder", - "order.recheckOrder.confirmRecheck" - ], - "notes": [ - "用途:扫码查询订单明细(scanOrder);确认复核并落库 wms_recheck_task(confirmRecheck)。", - "scanOrder 返回运单号或车号匹配的订单头、商品明细、运单信息与相关日志;confirmRecheck 将复核结果写入 wms_recheck_task 并返回复核摘要信息(order_id、recheck_status、recheck_time、review_no)。", - "变更概要:confirmRecheck 改为按 order_id 进行复核(兼容 id/orderId);scanOrder 返回准确的 order_id 供前端直接使用;新增支持:查找范围包含 wms_wave_pick_task 的车号快照(current_cart_code_snapshot / wms_wave_pick_task_order.cart_code_snapshot)。", - "规则调整:移除打印状态约束,改为未拣货约束。", - "scanOrder 在车号命中场景按波次类型返回不同结构(1/5 groups, 2 orders, 3 pick_groups, 4 box_groups)。" - ], - "type": "added" - } -] \ No newline at end of file diff --git a/methods/changes/2026.05.20-system-03.json b/methods/changes/2026.05.20-system-03.json deleted file mode 100644 index b8ed107..0000000 --- a/methods/changes/2026.05.20-system-03.json +++ /dev/null @@ -1,18 +0,0 @@ -[ - { - "version": "2026.05.20-system-03", - "date": "2026-05-20", - "summary": "新增 storeWarehouse.store.queryPrintQuantityLogs:按 store_id 分页查询面单余额变更日志", - "methods": [ - "storeWarehouse.store.queryPrintQuantityLogs" - ], - "notes": [ - "新增方法:storeWarehouse.store.queryPrintQuantityLogs,用于按货主(store_id)分页查询面单余额变更日志。", - "入参:store_id(必填)、page(可选)、page_size / pageSize(可选,兼容别名)。", - "仅同步 methods/system.json 与本变更记录,不修改业务代码或测试。", - "返回:使用默认分页格式,响应在 `data` 下包含 `list`(变更日志数组)和 `pagination` 对象,`pagination` 字段:`page`、`pageSize`、`total`、`totalPages`、`hasPrevious`、`hasNext`。" - ], - "type": "added", - "module": "storeWarehouse" - } -] diff --git a/methods/changes/2026.05.28-system-01.json b/methods/changes/2026.05.28-system-01.json deleted file mode 100644 index 9505497..0000000 --- a/methods/changes/2026.05.28-system-01.json +++ /dev/null @@ -1,19 +0,0 @@ -[ - { - "version": "2026.05.28-system-01", - "date": "2026-05-28", - "summary": "新增包材相关表与在订单快递表新增包材关联字段(wms_package_material / wms_package_supplier / wms_order_express)", - "methods": [], - "notes": [ - "新增表 wms_package_material:主要字段 id, warehouse_id, material_code, material_name, material_type, spec, length, width, height, weight, cost_price, status, version, created_at, updated_at;索引:idx_wms_package_material_warehouse_id(warehouse_id),uk_wms_package_material_warehouse_material_code(warehouse_id + material_code 唯一)。", - "新增表 wms_package_supplier:主要字段 id, warehouse_id, supplier_code, supplier_name, contact_name, contact_phone, status, version, created_at, updated_at;索引:idx_wms_package_supplier_warehouse_id(warehouse_id),uk_wms_package_supplier_warehouse_supplier_code(warehouse_id + supplier_code 唯一)。", - "修改表 wms_order_express:新增可空字段 package_material_id (BIGINT unsigned) 与 package_material_name_snapshot (VARCHAR(128));新增索引 idx_wms_order_express_package_material_id(package_material_id)。", - "回滚要点:迁移脚本的 down 实现会移除上述索引与列,并删除新增的两张表(详见 database/migrations/20260528090000-create-wms-package-material-and-supplier.js 与 database/migrations/20260528091000-add-package-material-fields-to-wms-order-express.js)。生产回滚前请先迁移或备份依赖数据并通知下游系统。", - "兼容性说明:新增列均为可空(nullable),属于向后兼容的增量变更,不会影响现有查询或写入;若服务端或前端存在把 wms_order_express 全量序列化到外部响应的场景,响应中可能会包含这两个可选字段;目前已检查的对外 system 方法文档未声明返回 package_material_id 或 package_material_name_snapshot,因此本次不修改 methods/system.json(无接口契约变化)。", - "相关模型文件:新增 app/model/package_material.js、app/model/package_supplier.js;更新 app/model/order_express.js(新增字段与索引定义)。", - "验证建议:1) 在预发布环境执行 migrations up/down 并确认幂等性;2) 执行下单→分配快递→打印等关键路径以验证无回归;3) 若需要对外暴露包材字段,请在 methods/system.json 中补充对应接口的 response 字段并在变更记录中说明。" - ], - "type": "updated", - "module": "database" - } -] diff --git a/methods/changes/2026.06.16-system-01.json b/methods/changes/2026.06.16-system-01.json deleted file mode 100644 index c6d1df0..0000000 --- a/methods/changes/2026.06.16-system-01.json +++ /dev/null @@ -1,17 +0,0 @@ -[ - { - "version": "2026.06.16-system-01", - "date": "2026-06-16", - "summary": "新增 order.recheckOrder.queryRecheckOrderSingleList:散单复核列表接口,响应新增 items_weight(总重量kg)和 weight_type(重量类型)字段", - "methods": [ - "order.recheckOrder.queryRecheckOrderSingleList" - ], - "notes": [ - "新增方法 order.recheckOrder.queryRecheckOrderSingleList,为 recheckOrderList 散单模式的独立入口。", - "响应 list 每项新增字段 items_weight (number|null):订单总重量(kg),来自 wms_order.items_weight,为 null 时返回 null。", - "响应 list 每项新增字段 weight_type (string):重量类型中文标签,来自 wms_order.weight_type 经 formatWeightTypeLabel 转换;取值:常规/轻货/重货/冷链(对应 DB 值 0/1/2/3)。" - ], - "type": "added", - "module": "order.recheckOrder" - } -] diff --git a/methods/changes/2026.06.16-system-02.json b/methods/changes/2026.06.16-system-02.json deleted file mode 100644 index 545df34..0000000 --- a/methods/changes/2026.06.16-system-02.json +++ /dev/null @@ -1,16 +0,0 @@ -[ - { - "version": "2026.06.16-system-02", - "date": "2026-06-16", - "summary": "order.wave.groupOrderFetchList 响应新增 items_weight(总重量kg)字段", - "methods": [ - "order.wave.groupOrderFetchList" - ], - "notes": [ - "响应 list 每项新增字段 items_weight (number|null):订单总重量(kg),取组内首单 items_weight;组内订单 items_hash 相同重量一致。", - "为 null 时返回 null。" - ], - "type": "updated", - "module": "order.wave" - } -] diff --git a/methods/changes/2026.06.16-system-03.json b/methods/changes/2026.06.16-system-03.json deleted file mode 100644 index 15005a5..0000000 --- a/methods/changes/2026.06.16-system-03.json +++ /dev/null @@ -1,16 +0,0 @@ -[ - { - "version": "2026.06.16-system-03", - "date": "2026-06-16", - "summary": "order.wave.waveStrategyFallbackOrderList 响应新增 items_weight(总重量kg)和 weight_type(重量类型)字段", - "methods": [ - "order.wave.waveStrategyFallbackOrderList" - ], - "notes": [ - "响应 list 每项新增字段 items_weight (number|null):订单总重量(kg),来自 wms_order.items_weight,为 null 时返回 null。", - "响应 list 每项新增字段 weight_type (string):重量类型中文标签,来自 wms_order.weight_type 经 formatWeightTypeLabel 转换;取值:常规/轻货/重货/冷链(对应 DB 值 0/1/2/3)。" - ], - "type": "updated", - "module": "order.wave" - } -] diff --git a/methods/changes/2026.06.16-system-04.json b/methods/changes/2026.06.16-system-04.json deleted file mode 100644 index 4872712..0000000 --- a/methods/changes/2026.06.16-system-04.json +++ /dev/null @@ -1,16 +0,0 @@ -[ - { - "version": "2026.06.16-system-04", - "date": "2026-06-16", - "summary": "order.wave.singleOrderFetchList 响应新增 items_weight(总重量kg)字段", - "methods": [ - "order.wave.singleOrderFetchList" - ], - "notes": [ - "响应 list 每项新增字段 items_weight (number|null):订单总重量(kg),取组内首单 items_weight;组内订单 items_hash 相同重量一致。", - "为 null 时返回 null。" - ], - "type": "updated", - "module": "order.wave" - } -] diff --git a/methods/changes/openapi-2026-06-17-entryorder.json b/methods/changes/openapi-2026-06-17-entryorder.json deleted file mode 100644 index 232ddac..0000000 --- a/methods/changes/openapi-2026-06-17-entryorder.json +++ /dev/null @@ -1,20 +0,0 @@ -[ - { - "version": "2026.06.17-openapi-16", - "date": "2026-06-17", - "summary": "新增入库单模块(entryorder),支持 create(创建入库单)和 query(查询入库单)两个方法", - "methods": [ - "entryorder.create", - "entryorder.query" - ], - "notes": [ - "新增 entryorder.create:创建入库单接口,支持入库单主信息(entryOrder)和商品明细(orderLines.orderLine)的完整入参;创建渠道固定为 API;itemCode 与 itemId 二选一,优先使用 itemId", - "新增 entryorder.query:查询入库单接口,根据 entryOrderCode 查询入库单详情,返回基本信息及商品明细(itemId/itemCode/itemName/planQty/actualQty/inventoryType/orderLineNo)", - "查询范围为当前 app_key 绑定的仓库,跨仓库入库单无法查询", - "所有方法均支持 timestamp 时间戳时效校验:与服务器时间差不得超过 ±10 分钟(600 秒),否则返回 400", - "openapi 通道新增入库单创建和查询能力" - ], - "type": "added", - "module": "entryorder" - } -] diff --git a/methods/changes/qimen.json b/methods/changes/qimen.json index c127246..c744a7b 100644 --- a/methods/changes/qimen.json +++ b/methods/changes/qimen.json @@ -1,14 +1,57 @@ [ - { - "version": "2026.04.07-qimen-01", - "date": "2026-04-07", - "summary": "初始化 qimen 文档变更记录 sidecar,后续接口文档变更将持续追加到本数组。", - "methods": [ - "*" - ], - "notes": [ - "methods/qimen.json 仍为单一事实来源(SSOT)。", - "本文件仅记录变更历史与补充说明。" - ] - } + { + "version": "2026.07.01-qimen-01", + "date": "2026-07-01", + "summary": "补充 entryorder.create 的 request body 子结构和 response 结构", + "methods": [ + "entryorder.create" + ], + "notes": [ + "补充 request.entryOrder 子结构(entryOrderCode/warehouseCode/ownerCode/orderType)", + "补充 request.orderLines.orderLine 子结构(itemCode/itemId/itemName/planQty/orderLineNo/inventoryType)", + "补充 response 结构(entryOrderId/entryOrderCode/createTime/status)", + "参考代码:systems/entry_order.js addOrder 和 qimenMethods/entryorder.js create 返回值" + ], + "type": "updated", + "module": "entryorder" + }, + { + "version": "2026.04.07-qimen-01", + "date": "2026-04-07", + "summary": "初始化 qimen 文档变更记录 sidecar,后续接口文档变更将持续追加到本数组。", + "methods": [ + "*" + ], + "notes": [ + "methods/qimen.json 仍为单一事实来源(SSOT)。", + "本文件仅记录变更历史与补充说明。" + ] + }, + { + "version": "2026.06.30-stockout-create-01", + "date": "2026-06-30", + "summary": "stockout.create 重构:从不可用的 deliveryOrder 旧链路迁移到 wms_order_stockout 专用表;返回字段 deliveryOrderId→stockoutOrderId/stockoutOrderCode", + "methods": [ + "stockout.create" + ], + "notes": [ + "params 补全 deliveryOrder 和 orderLines 内部全部子字段", + "response 从空补充为 stockoutOrderId/stockoutOrderCode", + "文档与代码实现(qimenMethods/stockout.js create 方法)对齐" + ] + }, + { + "version": "2026.06.30-stockout-query-01", + "date": "2026-06-30", + "summary": "stockout.query 从占位(接口未完善)实现为完整查询:按 deliveryOrderCode 查 wms_order_stockout 主表+明细表", + "methods": [ + "stockout.query" + ], + "notes": [ + "params 补全 request.deliveryOrder.deliveryOrderCode(body)", + "response 从空补充为 deliveryOrder 主单 + orderLines.orderLine 明细 + totalLines", + "文档与代码实现(qimenMethods/stockout.js query 方法)对齐" + ], + "type": "updated" + } ] diff --git a/methods/changes/system.json b/methods/changes/system.json index 1ac129a..63bec51 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,125 @@ [ + { + "date": "2026-06-24", + "type": "addition", + "summary": "新增批量绑定入库单明细与收货单明细接口,支持明细级数量分配与部分成功", + "version": "2026-06-24-add-bind-receiving-details", + "methods": [ + "storage.entry.bindReceivingDetails" + ], + "notes": [] + }, + { + "date": "2026-06-24", + "type": "deprecation", + "summary": "废弃手动匹配入库单收货单接口,由 storage.entry.bindReceivingDetails 替代", + "version": "2026-06-24-deprecate-manual-match-entry-order", + "methods": [ + "storage.receiving.manualMatchEntryOrder" + ], + "notes": [] + }, + { + "version": "2026.06.16-system-03", + "date": "2026-06-16", + "summary": "order.wave.waveStrategyFallbackOrderList 响应新增 items_weight(总重量kg)和 weight_type(重量类型)字段", + "methods": [ + "order.wave.waveStrategyFallbackOrderList" + ], + "notes": [ + "响应 list 每项新增字段 items_weight (number|null):订单总重量(kg),来自 wms_order.items_weight,为 null 时返回 null。", + "响应 list 每项新增字段 weight_type (string):重量类型中文标签,来自 wms_order.weight_type 经 formatWeightTypeLabel 转换;取值:常规/轻货/重货/冷链(对应 DB 值 0/1/2/3)。" + ], + "type": "updated", + "module": "order.wave" + }, + { + "version": "2026.06.16-system-04", + "date": "2026-06-16", + "summary": "order.wave.singleOrderFetchList 响应新增 items_weight(总重量kg)字段", + "methods": [ + "order.wave.singleOrderFetchList" + ], + "notes": [ + "响应 list 每项新增字段 items_weight (number|null):订单总重量(kg),取组内首单 items_weight;组内订单 items_hash 相同重量一致。", + "为 null 时返回 null。" + ], + "type": "updated", + "module": "order.wave" + }, + { + "version": "2026.05.20-system-03", + "date": "2026-05-20", + "summary": "新增 storeWarehouse.store.queryPrintQuantityLogs:按 store_id 分页查询面单余额变更日志", + "methods": [ + "storeWarehouse.store.queryPrintQuantityLogs" + ], + "notes": [ + "新增方法:storeWarehouse.store.queryPrintQuantityLogs,用于按货主(store_id)分页查询面单余额变更日志。", + "入参:store_id(必填)、page(可选)、page_size / pageSize(可选,兼容别名)。", + "仅同步 methods/system.json 与本变更记录,不修改业务代码或测试。", + "返回:使用默认分页格式,响应在 `data` 下包含 `list`(变更日志数组)和 `pagination` 对象,`pagination` 字段:`page`、`pageSize`、`total`、`totalPages`、`hasPrevious`、`hasNext`。" + ], + "type": "added", + "module": "storeWarehouse" + }, + { + "version": "2026.05.13-system-01", + "date": "2026-05-13", + "summary": "完善 print.send 的 API 文档与返回说明", + "methods": [ + "print.send" + ], + "notes": [ + "补充请求参数说明:computerId、printer、template、data、type 标为必填,count、timestamp 保持可选。", + "补充 template 的子字段说明:page_width、page_height、template_content。", + "补充响应结构:flag、code、message、printId;其中成功时 code=200。", + "补充错误码说明:1001 对应不支持的打印类型,504 对应打印任务发送失败(包含打印机不存在、脱机、通讯失败等场景)。" + ], + "type": "updated" + }, + { + "version": "2026.05.08-system-06", + "date": "2026-05-08", + "summary": "新增取消拣货任务接口:order.wave.wavePickTaskCancel", + "methods": [ + "order.wave.wavePickTaskCancel" + ], + "notes": [ + "接口功能:取消拣货任务,同时释放关联波次(物理删除波次记录,订单回池)、解绑拣货车、写操作日志。", + "限制:仅允许在任务状态为 0(待开始)、1(拣货中)、2(待复核)时取消;状态为 3(已完成)或 9(已取消)时禁止取消,返回 400。", + "事务内操作:将任务状态更新为 9(已取消)、删除关联波次、清空订单 wave_id(回池)、解绑拣货车、写入 action_log 与 order_pick_trace;若有任一步骤失败则回滚并返回 500。" + ], + "type": "added" + }, + { + "version": "2026.07.01-system-01", + "date": "2026-07-01", + "summary": "storage.directInbound.addItem 参数名修正:entry_order_code → entry_order_id,类型 string → number", + "methods": [ + "storage.directInbound.addItem" + ], + "notes": [ + "文档 params 中 entry_order_code(string)改为 entry_order_id(number),与代码 app/service/systems/inbound_direct_log.js 第 544 行实际校验保持一致", + "同步修正 app/service/systemMethods/storage/direct_inbound.js JSDoc:@param {string} data.entry_order_code → @param {number} data.entry_order_id" + ], + "type": "fixed", + "module": "storage.directInbound" + }, + { + "version": "2026.07.01-system-02", + "date": "2026-07-01", + "summary": "新增 storage.entry.queryEntryLogs 接口文档定义", + "methods": [ + "storage.entry.queryEntryLogs" + ], + "notes": [ + "代码 method 层(systemMethods/storage/entry.js L284)和 systems 层(systems/operation_log.js L318)均已实现,补充文档定义", + "参数:id(number, required)、page(number, optional, 默认1)、pageSize(number, optional, 默认20)" + ], + "type": "added", + "module": "storage.entry" + }, { "version": "2026.06.18-system-01", "date": "2026-06-18", @@ -4199,5 +4320,332 @@ ], "type": "updated", "module": "setting.warehouse" + }, + { + "version": "2026.06.25-system-01", + "date": "2026-06-25", + "summary": "新增 storage.entry.bindReceiving 接口:将收货单绑定到入库单(主表级关联,不做明细数量分配)", + "methods": [ + "storage.entry.bindReceiving" + ], + "notes": [ + "新增入库单与收货单的主表绑定接口,与已有的 storage.entry.bindReceivingDetails(明细级绑定)区分:bindReceiving 仅建立 wms_entry_order_receiving 主表关联,不做明细数量分配。", + "入库单需为 CREATED 或 PENDING 状态;收货单需存在、同仓库且未取消。", + "支持部分成功模式:逐条校验收货单,校验通过的建立绑定,不通过的返回 error_code 和 message。", + "响应包含 success(成功列表)、failed(失败列表)、success_count、failed_count。" + ], + "type": "addition" + }, + { + "version": "2026.06.25-system-02", + "date": "2026-06-25", + "summary": "storage.entry.bindReceiving:新增 OWNER_MISMATCH 错误码,用于收货单与入库单货主不一致校验", + "methods": [ + "storage.entry.bindReceiving" + ], + "notes": [ + "在 storage.entry.bindReceiving 的 errors 数组中新增 OWNER_MISMATCH(收货单与入库单货主不一致)错误码。", + "同步更新 response.failed.error_code 的枚举描述,补充 OWNER_MISMATCH。" + ], + "type": "updated", + "module": "storage.entry" + }, + { + "version": "2026.06.25-system-03", + "date": "2026-06-25", + "summary": "storage.entry.bindReceiving:新增收货单未审核错误码 RECEIVING_NOT_REVIEWED", + "methods": [ + "storage.entry.bindReceiving" + ], + "notes": [ + "在 errors 数组中新增错误码 RECEIVING_NOT_REVIEWED(收货单未审核),用于标识绑定前收货单尚未完成审核的场景。", + "同步更新 response.failed.items.properties.error_code.description,在可能值列表中补充 RECEIVING_NOT_REVIEWED。" + ], + "type": "updated" + }, + { + "version": "2026.06.25-system-04", + "date": "2026-06-25", + "summary": "storage.entry.list 响应新增 receivingBindings 和 hasReceiving 字段,where 新增 hasReceiving 虚拟筛选条件", + "methods": [ + "storage.entry.list" + ], + "notes": [ + "响应 list 数组每项新增 receivingBindings(收货单绑定列表,主表级关联)和 hasReceiving(是否存在收货单绑定,boolean)字段。", + "入参 where 新增 hasReceiving 虚拟筛选字段,传 true/false 筛选已绑定/未绑定收货单的入库单,内部通过 wms_entry_order_receiving 表查询实现。", + "同步更新 description 以说明 hasReceiving 虚拟筛选的使用方式。" + ], + "type": "updated" + }, + { + "version": "2026.06.26-system-01", + "date": "2026-06-26", + "summary": "storage.entry.receivingCompare 支持多收货单对照预览", + "methods": [ + "storage.entry.receivingCompare" + ], + "notes": [ + "支持多个收货单ID对照预览(新增 receiving_ids 数组入参,优先于 receiving_id 使用)", + "入参 receiving_id 从 required 改为 optional,与 receiving_ids 二选一", + "出参结构调整为 comparisons[] 数组(多收货单),新增 errors[] 和 total_summary", + "向后兼容原 receiving_id 单值传参(底层自动转为单元素数组)", + "新增 400 错误码:receiving_ids 或 receiving_id 必填", + "移除 404 错误码:收货单不存在(已改为在 comparisons[]/errors[] 中以 status=error 形式返回)" + ], + "type": "enhancement" + }, + { + "version": "2026.06.26-system-02", + "date": "2026-06-26", + "summary": "storage.receiving.getReceivingList 新增 filterDepleted 可选参数;storage.entry.receivingCompare 返回值 receiving_only 字段新增 receiving_allocated 和 receiving_available 说明", + "methods": [ + "storage.receiving.getReceivingList", + "storage.entry.receivingCompare" + ], + "notes": [ + "storage.receiving.getReceivingList:params 新增 filterDepleted(boolean, 默认 false),用于过滤掉无可再用量的收货单(所有明细已被其他入库单 committed 绑定占满)。", + "storage.entry.receivingCompare:response 中 receiving_only 字段的 description 补充 receiving_allocated(已分配数量)和 receiving_available(可再用量)两个子字段说明。" + ], + "type": "updated" + }, + { + "version": "2026.06.26-system-03", + "date": "2026-06-26", + "summary": "storage.receiving.getReceivingList:新增可选参数 entry_order_id,按入库单商品交集过滤收货单列表", + "methods": [ + "storage.receiving.getReceivingList" + ], + "notes": [ + "新增可选参数 entry_order_id(number),传入入库单 ID 后只返回至少有一条明细的 system_product_id 在入库单明细中存在的收货单。", + "与现有 filterDepleted 参数可组合使用,二者取交集。", + "不传则不过滤,保持原有行为不变。" + ], + "type": "updated" + }, + { + "version": "2026.06.27-system-01", + "date": "2026-06-27", + "summary": "新增 storage.entry.reviewEntry 接口:审核入库单(CREATED→PENDING),需绑定收货单", + "methods": [ + "storage.entry.reviewEntry" + ], + "notes": [ + "新增入库单审核接口,支持 CREATED→PENDING 状态流转。", + "审核前置条件:入库单必须已绑定收货单(EntryOrderReceiving 存在关联记录)。", + "审核通过后写入操作日志(ENTRY_ORDER_REVIEW)。" + ], + "type": "added" + }, + { + "version": "2026.06.29-system-01", + "date": "2026-06-29", + "summary": "storage.inventory.quickPutaway 重新实现:收货单快捷转入库单", + "methods": [ + "storage.inventory.quickPutaway" + ], + "notes": [ + "此前已从代码中删除(2026.06.23-system-08),现由 wms-dev-agent 重新实现。", + "核心流程:参数校验 → 加载收货单及明细 → 检查货主配置 policy_config.allow_receiving_quick_putaway → 按 stock_id(system_product_id)分组合并数量 → 创建入库单 SCRK(自动审批到 PENDING)→ 写入 wms_entry_order_receiving 主表级绑定 → 更新收货单 storage_status 为 partial → 更新收货单明细 storage_status/stored_quantity → 提交事务。", + "前置条件:收货单状态为 completed 且 is_review=true(已审核),货主仓库签约配置 allow_receiving_quick_putaway=1。", + "与旧实现的区别:不涉及 wms_entry_receiving_binding 明细级绑定,使用 wms_entry_order_receiving 主表级关联;直接创建入库单并写入绑定,不再走 matchPutaway 匹配链路。", + "返回:entry_order_id、entry_order_code(SCRK 格式)、order_status(PENDING)、receiving_id、total_lines、total_quantity。" + ], + "type": "addition" + }, + { + "version": "2026.06.29-system-02", + "date": "2026-06-29", + "summary": "storage.entry.list:quickWhere 搜索范围扩展,新增收货单 ID(receiving_id)支持 PDA 扫描托盘唛头搜索绑定的入库单", + "methods": [ + "storage.entry.list" + ], + "notes": [ + "quickWhere 搜索字段新增 receiving_id(收货单 ID / 托盘唛头),通过 wms_entry_order_receiving 绑定表关联搜索。", + "同步更新 description 和 where 参数的 description,明确 quickWhere 完整搜索字段列表:entry_order_code、purchase_order_code、supplier_name、store_name、warehouse_name、receiving_id。" + ], + "type": "updated", + "module": "storage" + }, + { + "version": "2026.06.29-system-03", + "date": "2026-06-29", + "summary": "新增 storage.receiving.scanDetail 接口:PDA 上架扫码定位收货明细", + "methods": [ + "storage.receiving.scanDetail" + ], + "notes": [ + "新增 storage.receiving.scanDetail(PDA专用):通过 entry_order_id + barcode 扫码快速定位收货明细。", + "搜索逻辑:纯数字 barcode 优先按明细 ID 精确匹配(托盘唛头),未命中则模糊匹配商品条码;非纯数字仅模糊匹配商品条码。", + "入参:entry_order_id(必填 number)、barcode(必填 string)。", + "出参:detail_id、receiving_id、barcode、product_name、actual_quantity、receiving_status。", + "错误码:入库单不存在或无权访问、该入库单尚未关联收货单、未找到匹配的收货明细。" + ], + "type": "added" + }, + { + "version": "2026.06.29-system-04", + "date": "2026-06-29", + "summary": "storage.receiving.scanDetail 响应结构从单条改为列表:返回 { list, total } 支持同一条码匹配多条明细", + "methods": [ + "storage.receiving.scanDetail" + ], + "notes": [ + "响应结构变更:原返回 data.detail_id/data.receiving_id 等单条字段,现改为顶层 list 数组 + total 计数。", + "同一条码可能匹配到多条收货明细(不同收货单的同一商品),以列表形式返回所有匹配结果。", + "list 中每条明细包含 detail_id/receiving_id/barcode/product_name/actual_quantity/receiving_status。", + "补充错误码:用户未绑定仓库、入库单ID/条码为空、未找到可用的收货明细、500服务器错误。", + "PDA专用接口,description 更新说明匹配逻辑。" + ], + "type": "updated", + "module": "storage.receiving" + }, + { + "version": "2026.06.30-system-01", + "date": "2026-06-30", + "summary": "新增 storage.entry.containerList:PDA 上架时拉取入库单绑定收货单中指定商品的可用容器列表", + "methods": [ + "storage.entry.containerList" + ], + "notes": [ + "新增接口 storage.entry.containerList,用于 PDA 上架场景拉取入库单已绑定收货单中指定 stock_id 的可用收货明细(容器)列表。", + "入参:entry_order_id(入库单ID,必填)、stock_id(商品 stock_id,必填)。", + "出参:data.list 返回可用明细列表,每项含 detail_id、receiving_id、barcode、product_name、actual_quantity、receiving_status;data.total 为总数。", + "已绑定占用的收货明细(wms_entry_receiving_binding 中已有记录且未软删除)会被排除。", + "PDA 专用接口,无需额外鉴权(isNeedAuth=false)。" + ], + "type": "added" + }, + { + "version": "2026.06.30-system-02", + "date": "2026-06-30", + "summary": "storage.entry.addDirectInboundItem 入参变更:entry_order_code → entry_order_id(number);quantity 改为可选(传入 receiving_detail_id 时自动计算);新增 receiving_detail_id/allocated_quantity 参数支持 PDA 上架收货明细绑定模式;space_id 绑定模式下必填", + "methods": [ + "storage.entry.addDirectInboundItem" + ], + "notes": [ + "入参 entry_order_code(string) → entry_order_id(number),与底层 inboundDirectLog.addItem 实现对齐", + "quantity 改为可选:传入 receiving_detail_id 时自动从收货明细计算可用数量(actual_quantity - 已绑定数量)", + "新增 receiving_detail_id 参数:PDA 上架绑定收货明细时传入,触发预占绑定(wms_entry_receiving_binding status=pending)", + "新增 allocated_quantity 参数:预分配数量,默认等于 quantity", + "space_id 在绑定模式下必填;非绑定模式可选(commit 时兜底为 1)", + "PENDING 状态入库单必须传 receiving_detail_id 且已绑定收货单方可操作", + "CREATED + 已绑定收货单的入库单需先审核(reviewEntry)后才能上架", + "批量模式 items 数组同步支持 receiving_detail_id/allocated_quantity 字段", + "补充完整错误码列表:超量、可用数量不足、状态校验等" + ], + "type": "updated" + }, + { + "version": "2026.06.30-system-03", + "date": "2026-06-30", + "summary": "storage.entry.commitDirectInbound 入参变更:entry_order_code → entry_order_id(number),与底层 inboundDirectLog.commit 实现对齐", + "methods": [ + "storage.entry.commitDirectInbound" + ], + "notes": [ + "入参 entry_order_code(string) → entry_order_id(number),与底层 inboundDirectLog.commit(entryOrderId) 实现对齐", + "补充 description 说明先同步后写库两段式流程:① 奇门/API 回传 → ② onSuccess 内事务写库存", + "补充 commit 后 EntryReceivingBinding 状态从 pending 更新为 committed 的说明" + ], + "type": "updated" + }, + { + "version": "2026.06.30-system-04", + "date": "2026-06-30", + "summary": "storage.directInbound.commit 入参变更:entry_order_code → entry_order_id(number),与底层 inboundDirectLog.commit 实现对齐", + "methods": [ + "storage.directInbound.commit" + ], + "notes": [ + "入参 entry_order_code(string) → entry_order_id(number),与底层 inboundDirectLog.commit(entryOrderId) 实现对齐", + "该方法已标记 deprecated,推荐使用 storage.entry.commitDirectInbound" + ], + "type": "updated" + }, + { + "version": "2026.06.30-system-05", + "date": "2026-06-30", + "summary": "storage.entry.getDirectInboundItems 响应结构重构:entryOrder 精简字段,items[].count→planned、direct_inbound_quantity→completed,items[].bindings 新增,移除 direct_logs/summary 等冗余字段", + "methods": [ + "storage.entry.getDirectInboundItems" + ], + "notes": [ + "entryOrder 精简为 id / entry_order_code / order_status / store_remask 四个字段", + "items[].count → planned(计划数量),items[].direct_inbound_quantity → completed(已完成数量)", + "items[].bindings 新增,结构为 { detail_id, binding_id, allocated_quantity, space_id, space_name }", + "items[].stock 新增,返回 getStockDetails 缓存的商品详情(item_code、item_name、barcodes 等)", + "移除 direct_logs(现有响应中已不存在该顶层字段)", + "移除 summary(现有响应中已不存在该字段)", + "移除 items[].received_quantity、items[].remaining_quantity、items[].pending_binding_total 等旧字段", + "新增 receivingBindings 字段说明:入库单层级收货单绑定关系" + ], + "type": "updated" + }, + { + "version": "2026.06.30-system-06", + "date": "2026-06-30", + "summary": "storage.directInbound.getItems 响应结构重构:entryOrder 精简字段,items[].count→planned、direct_inbound_quantity→completed,items[].bindings 新增,移除 direct_logs/summary 等冗余字段", + "methods": [ + "storage.directInbound.getItems" + ], + "notes": [ + "响应结构与 storage.entry.getDirectInboundItems 对齐(两者共用同一个底层实现 inboundDirectLog.getItems)", + "entryOrder 精简为 id / entry_order_code / order_status / store_remask", + "items[].count → planned,items[].direct_inbound_quantity → completed", + "items[].bindings 新增 { detail_id, binding_id, allocated_quantity, space_id, space_name }", + "items[].stock 新增", + "移除 direct_logs、summary、items[].received_quantity、items[].remaining_quantity 等旧字段", + "新增 receivingBindings 字段" + ], + "type": "updated" + }, + { + "version": "2026.06.30-system-07", + "date": "2026-06-30", + "summary": "storage.entry.containerList 响应结构补充 stock 字段:返回商品详情(item_code、item_name、barcodes 等)", + "methods": [ + "storage.entry.containerList" + ], + "notes": [ + "响应 list[].stock 字段补充为必返回:通过 getStockDetails 批量获取商品详情缓存", + "stock 对象包含 item_code、item_name、sku_property、barcodes 等字段" + ], + "type": "updated" + }, + { + "version": "2026.06.30-system-08", + "date": "2026-06-30", + "summary": "storage.receiving.scanDetail 响应结构补充 stock 字段:返回商品详情(item_code、item_name、barcodes 等)", + "methods": [ + "storage.receiving.scanDetail" + ], + "notes": [ + "响应 list[].stock 字段补充为必返回:通过 getStockDetails 批量获取商品详情缓存", + "stock 对象包含 item_code、item_name、sku_property、barcodes 等字段", + "完善 error 列表:补充 未找到可用的收货明细、未找到匹配的收货明细、入库单ID不能为空、扫描条码不能为空 等错误" + ], + "type": "updated" + }, + { + "version": "2026.06.30-system-09", + "date": "2026-06-30", + "summary": "订单列表 list 响应新增 store_remark(货主备注)字段", + "methods": [ + "order.list", + "order.reviewOrder.list", + "order.pendingOrder.list", + "order.expectionOrder.list", + "order.entrustOrder.list", + "order.deliveryOrder.list", + "order.deliveryExpectionOrder.list", + "order.archiveOrder.list" + ], + "notes": [ + "数据库字段 store_remask,返回给前端的字段名为 store_remark。", + "服务层从 wms_store_warehouse.store_remask 按 store_id+warehouse_id 聚合批量填充。", + "货主备注值可能为空字符串(当货主未设置备注时)。", + "该字段对订单列表的所有 method 均适用(current/dispatch/outsourced/history 模型均返回)。" + ], + "type": "updated" } ] diff --git a/methods/qimen.json b/methods/qimen.json index 0f560ac..27468be 100644 --- a/methods/qimen.json +++ b/methods/qimen.json @@ -1,8 +1,8 @@ { "module": "qimen", "description": "奇门接口标准入口,method 对应 qimenMethods 异步方法,全部使用 POST 请求,参数包含 query 与 XML body(request 节点)", - "version": "0.3.0", - "updatedAt": "2026-03-22", + "version": "0.3.6", + "updatedAt": "2026-06-30", "headers": [], "methods": { "groups": [ @@ -240,7 +240,7 @@ "list": [ { "method": "entryorder.create", - "description": "entryorder.create 接口", + "description": "创建入库单。奇门 XML 推送创建入库单及明细,返回入库单 ID、单号、创建时间和状态", "isNeedAuth": false, "isNeedLogin": false, "headers": [], @@ -299,11 +299,129 @@ "type": "object", "required": true, "source": "body", - "description": "request XML 节点" + "description": "request XML 节点,包含 entryOrder 和 orderLines 子节点" + }, + { + "name": "request.entryOrder", + "type": "object", + "required": true, + "source": "body", + "description": "入库单头信息" + }, + { + "name": "request.entryOrder.entryOrderCode", + "type": "string", + "required": true, + "source": "body", + "description": "入库单号(外部系统单号)" + }, + { + "name": "request.entryOrder.warehouseCode", + "type": "string", + "required": true, + "source": "body", + "description": "仓库编码" + }, + { + "name": "request.entryOrder.ownerCode", + "type": "string", + "required": true, + "source": "body", + "description": "货主编码" + }, + { + "name": "request.entryOrder.orderType", + "type": "string", + "required": true, + "source": "body", + "description": "入库单类型:CGRK(采购入库)、JITRK(JIT入库)、THRK(退货入库)、QTRK(其他入库)等" + }, + { + "name": "request.orderLines.orderLine", + "type": "object|array", + "required": true, + "source": "body", + "description": "入库单明细行,单条为 object,多条为 array" + }, + { + "name": "request.orderLines.orderLine.itemCode", + "type": "string", + "required": true, + "source": "body", + "description": "商品编码" + }, + { + "name": "request.orderLines.orderLine.itemId", + "type": "string", + "required": false, + "source": "body", + "description": "商品 ID(StockStore 主键),建议必传以避免编码匹配问题" + }, + { + "name": "request.orderLines.orderLine.itemName", + "type": "string", + "required": true, + "source": "body", + "description": "商品名称" + }, + { + "name": "request.orderLines.orderLine.planQty", + "type": "number", + "required": true, + "source": "body", + "description": "计划入库数量" + }, + { + "name": "request.orderLines.orderLine.orderLineNo", + "type": "string", + "required": false, + "source": "body", + "description": "行号" + }, + { + "name": "request.orderLines.orderLine.inventoryType", + "type": "string", + "required": false, + "source": "body", + "description": "库存类型,如 ZP(正品),默认 ZP" } ], - "response": [], - "errors": [] + "response": [ + { + "name": "entryOrderId", + "type": "number", + "required": true, + "description": "WMS 入库单 ID" + }, + { + "name": "entryOrderCode", + "type": "string", + "required": true, + "description": "入库单号" + }, + { + "name": "createTime", + "type": "string", + "required": true, + "description": "创建时间" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "入库单状态:CREATED(已创建)或 PENDING(已审核)" + } + ], + "errors": [ + { + "code": 400, + "message": "创建入库单失败:商品未同步推送到仓库 / wms无对应关系" + }, + { + "code": 500, + "message": "服务器异常" + } + ] }, { "method": "entryorder.query", @@ -985,25 +1103,136 @@ }, { "name": "request.deliveryOrder", + "type": "object", + "required": true, + "source": "body", + "description": "出库单头信息" + }, + { + "name": "request.deliveryOrder.deliveryOrderCode", + "type": "string", + "required": true, + "source": "body", + "description": "出库单号" + }, + { + "name": "request.deliveryOrder.orderType", + "type": "string", + "required": true, + "source": "body", + "description": "业务类型(JYCK一般交易出库/HHCK换货出库/BFCK补发出库/QTCK其他出库)" + }, + { + "name": "request.deliveryOrder.warehouseCode", + "type": "string", + "required": true, + "source": "body", + "description": "仓库编码" + }, + { + "name": "request.deliveryOrder.createTime", "type": "string", "required": false, "source": "body", - "description": "request.deliveryOrder 参数" + "description": "订单创建时间" + }, + { + "name": "request.deliveryOrder.totalOrderLines", + "type": "integer", + "required": false, + "source": "body", + "description": "单据总行数" + }, + { + "name": "request.deliveryOrder.remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注" }, { "name": "request.orderLines", + "type": "object", + "required": true, + "source": "body", + "description": "出库单明细" + }, + { + "name": "request.orderLines.orderLine", + "type": "object/array", + "required": true, + "source": "body", + "description": "明细行(单条为对象,多条为数组)" + }, + { + "name": "request.orderLines.orderLine.orderLineNo", + "type": "string", + "required": true, + "source": "body", + "description": "订单行号" + }, + { + "name": "request.orderLines.orderLine.ownerCode", + "type": "string", + "required": true, + "source": "body", + "description": "货主编码" + }, + { + "name": "request.orderLines.orderLine.itemCode", + "type": "string", + "required": true, + "source": "body", + "description": "商品编码" + }, + { + "name": "request.orderLines.orderLine.itemId", + "type": "string", + "required": true, + "source": "body", + "description": "WMS商品ID" + }, + { + "name": "request.orderLines.orderLine.itemName", "type": "string", "required": false, "source": "body", - "description": "request.orderLines 参数" + "description": "商品名称" + }, + { + "name": "request.orderLines.orderLine.planQty", + "type": "integer", + "required": true, + "source": "body", + "description": "计划数量" + }, + { + "name": "request.orderLines.orderLine.inventoryType", + "type": "string", + "required": false, + "source": "body", + "description": "库存类型(ZP正品/CC残次等)" + } + ], + "response": [ + { + "name": "stockoutOrderId", + "type": "integer", + "required": true, + "description": "出库单ID" + }, + { + "name": "stockoutOrderCode", + "type": "string", + "required": true, + "description": "出库单号" } ], - "response": [], "errors": [] }, { "method": "stockout.query", - "description": "stockout.query 接口", + "description": "stockout.query 接口(查询非订单出库单;按 deliveryOrderCode 查 wms_order_stockout 主表+明细表)", "isNeedAuth": false, "isNeedLogin": false, "headers": [], @@ -1062,25 +1291,139 @@ "type": "object", "required": true, "source": "body", - "description": "request XML 节点" + "description": "请求数据" }, { "name": "request.deliveryOrder", - "type": "string", - "required": false, + "type": "object", + "required": true, "source": "body", - "description": "request.deliveryOrder 参数" + "description": "出库单查询条件" }, { - "name": "request.orderLines", + "name": "request.deliveryOrder.deliveryOrderCode", "type": "string", - "required": false, + "required": true, "source": "body", - "description": "request.orderLines 参数" + "description": "出库单号" } ], - "response": [], - "errors": [] + "response": [ + { + "name": "totalLines", + "type": "integer", + "required": true, + "description": "明细总行数" + }, + { + "name": "deliveryOrder", + "type": "object", + "required": true, + "description": "出库单主单信息" + }, + { + "name": "deliveryOrder.deliveryOrderCode", + "type": "string", + "required": true, + "description": "出库单号" + }, + { + "name": "deliveryOrder.deliveryOrderId", + "type": "integer", + "required": true, + "description": "出库单ID" + }, + { + "name": "deliveryOrder.warehouseCode", + "type": "string", + "required": true, + "description": "仓库编码" + }, + { + "name": "deliveryOrder.orderType", + "type": "string", + "required": true, + "description": "业务类型" + }, + { + "name": "deliveryOrder.status", + "type": "string", + "required": true, + "description": "订单状态" + }, + { + "name": "deliveryOrder.createTime", + "type": "string", + "required": true, + "description": "创建时间" + }, + { + "name": "deliveryOrder.remark", + "type": "string", + "required": true, + "description": "备注" + }, + { + "name": "orderLines", + "type": "object", + "required": true, + "description": "明细集合" + }, + { + "name": "orderLines.orderLine", + "type": "array", + "required": true, + "description": "明细行数组" + }, + { + "name": "orderLines.orderLine[].orderLineNo", + "type": "string", + "required": true, + "description": "订单行号" + }, + { + "name": "orderLines.orderLine[].ownerCode", + "type": "string", + "required": true, + "description": "货主编码" + }, + { + "name": "orderLines.orderLine[].itemCode", + "type": "string", + "required": true, + "description": "商品编码" + }, + { + "name": "orderLines.orderLine[].itemId", + "type": "string", + "required": true, + "description": "WMS商品ID" + }, + { + "name": "orderLines.orderLine[].itemName", + "type": "string", + "required": true, + "description": "商品名称" + }, + { + "name": "orderLines.orderLine[].planQty", + "type": "integer", + "required": true, + "description": "计划数量" + }, + { + "name": "orderLines.orderLine[].inventoryType", + "type": "string", + "required": true, + "description": "库存类型" + } + ], + "errors": [ + { + "code": 400, + "message": "未找到出库单(deliveryOrderCode 对应记录不存在)" + } + ] } ] }, diff --git a/methods/system.json b/methods/system.json index 7581b77..4d22ec6 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1,8 +1,8 @@ { "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", - "version": "0.3.7", - "updatedAt": "2026-06-24", + "version": "0.3.5", + "updatedAt": "2026-06-30", "headers": [ { "name": "platform", @@ -1655,7 +1655,7 @@ "name": "list", "type": "array", "required": true, - "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节)" + "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节),本次新增 store_remark(货主备注)字段。" }, { "name": "pagination", @@ -2541,7 +2541,7 @@ "name": "list", "type": "array", "required": true, - "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节)" + "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节),本次新增 store_remark(货主备注)字段。" }, { "name": "pagination", @@ -2756,7 +2756,7 @@ "name": "list", "type": "array", "required": true, - "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节)" + "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节),本次新增 store_remark(货主备注)字段。" }, { "name": "pagination", @@ -9640,19 +9640,13 @@ "name": "list", "type": "array", "required": true, - "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节)" + "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节),本次新增 store_remark(货主备注)字段。" }, { "name": "pagination", "type": "object", "required": true, "description": "分页信息" - }, - { - "name": "recheck_status", - "type": "string", - "required": false, - "description": "复核状态:none=未复核,fin=已复核" } ], "errors": [ @@ -9831,19 +9825,13 @@ "name": "list", "type": "array", "required": true, - "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节)" + "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节),本次新增 store_remark(货主备注)字段。" }, { "name": "pagination", "type": "object", "required": true, "description": "分页信息" - }, - { - "name": "recheck_status", - "type": "string", - "required": false, - "description": "复核状态:none=未复核,fin=已复核" } ], "errors": [ @@ -9975,7 +9963,7 @@ "name": "list", "type": "array", "required": true, - "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节)" + "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节),本次新增 store_remark(货主备注)字段。" }, { "name": "pagination", @@ -10124,7 +10112,7 @@ "name": "list", "type": "array", "required": true, - "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节)" + "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节),本次新增 store_remark(货主备注)字段。" }, { "name": "pagination", @@ -10268,7 +10256,7 @@ "name": "list", "type": "array", "required": true, - "description": "订单列表(raw 行数据)" + "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节),本次新增 store_remark(货主备注)字段。" }, { "name": "pagination", @@ -17586,7 +17574,7 @@ "list": [ { "method": "storage.receiving.getReceivingList", - "description": "storage.receiving.getReceivingList 接口", + "description": "查询收货单列表,支持分页和多条件筛选。支持 filterDepleted 参数过滤掉无可再用量的收货单(所有明细已被其他入库单 committed 绑定占满)。支持 entry_order_id 参数按入库单商品交集过滤。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -17611,6 +17599,20 @@ "required": false, "source": "body", "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会在 main 中自动标准化;支持 quickWhere、status、store_id、日期区间等字段。示例:where.status={operator:eq,value:finished}; where.store_id={operator:eq,value:1001}; where.create_time_start={value:2026-03-01}。" + }, + { + "name": "filterDepleted", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否过滤掉无可再用量的收货单(所有明细已被其他入库单 committed 绑定占满,即 available=0)。默认 false。" + }, + { + "name": "entry_order_id", + "type": "number", + "required": false, + "source": "body", + "description": "按入库单商品交集过滤。传入入库单 ID 后,只返回至少有一条收货明细的 system_product_id 在入库单明细中存在的收货单。与 filterDepleted 可组合使用。不传则不过滤。" } ], "response": [ @@ -17636,7 +17638,7 @@ "errors": [ { "code": "500", - "description": "查询失败" + "message": "查询失败" } ] }, @@ -18890,78 +18892,9 @@ ] }, { - "groupName": "入库模块", + "groupName": "入库管理", "module": "storage.entry", "list": [ - { - "method": "storage.entry.list", - "description": "入库单列表查询。where.order_status 支持 CREATING/CREATED/PENDING/COMPLETED/CANCELLED。CREATED=已创建待审核(需审核后才能绑定和完成入库),PENDING=已审核(可绑定和完成入库)。", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "pagination", - "type": "object", - "required": false, - "source": "body", - "description": "分页参数,支持 page/pageSize" - }, - { - "name": "where", - "type": "object", - "required": false, - "source": "body", - "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会在 main 中自动标准化;支持 quickWhere、order_status(CREATING/CREATED/PENDING/COMPLETED/CANCELLED)、store_id、order_type、日期区间等字段。新增 expense_record(费用是否记录)筛选,支持 eq/in;值会归一化为 0/1,兼容 true/false、1/0、y/n、yes/no(大小写不敏感,含布尔/字符串/数字写法)。示例:where.expense_record={operator:eq,value:true} 等价 where.expense_record={operator:eq,value:1};where.expense_record={operator:in,value:[true,\"0\",\"yes\",\"n\"]} 会归一化为 [1,0]。若部署环境尚未完成 expense_record 字段迁移,传入该筛选可能返回 400,错误提示为\"当前环境未提供 expense_record 字段,暂不支持该筛选条件,请先完成表结构升级\"。" - }, - { - "name": "sort", - "type": "object", - "required": false, - "source": "body", - "description": "排序参数,支持 sortField/sortOrder" - } - ], - "response": [ - { - "name": "list", - "type": "array", - "required": true, - "description": "入库单列表" - }, - { - "name": "pagination", - "type": "object", - "required": true, - "description": "分页信息(page、pageSize、total、totalPages、hasPrevious、hasNext)" - }, - { - "name": "summary", - "type": "object", - "required": true, - "description": "状态汇总(total、pending、creating、created、completed、cancelled)" - } - ], - "errors": [ - { - "code": "400", - "message": "筛选条件格式错误", - "description": "筛选条件格式错误" - }, - { - "code": "500", - "message": "查询失败", - "description": "查询失败" - } - ] - }, { "method": "storage.entry.get", "description": "查询入库单详情。返回的 entryOrder 包含顶层 receivingBindings(主表级关联,含关联的收货单信息),不再返回 items[].bindings(明细级绑定)。entryOrder.order_status 可能为 CREATING/CREATED/PENDING/COMPLETED/CANCELLED。CREATED=已创建待审核(需审核后才能绑定和完成入库),PENDING=已审核(可绑定和完成入库)。", @@ -19225,7 +19158,7 @@ }, { "method": "storage.entry.getDirectInboundItems", - "description": "获取入库单的导入/PDA 入库信息,返回入库单基本信息、明细列表,以及每项明细已有的导入/PDA 入库记录(含汇总和剩余可入库数量)。", + "description": "获取入库单的导入/PDA 入库信息(精简版)。返回入库单基本信息、明细列表(含计划数量 planned 与已完成数量 completed)、每项明细的收货绑定列表 bindings(含 detail_id、binding_id、allocated_quantity、space_id、space_name),以及收货单绑定关系 receivingBindings。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -19250,25 +19183,135 @@ "name": "entryOrder", "type": "object", "required": true, - "description": "入库单基本信息(id、entry_order_code、order_type、order_status、source_type、warehouse_id、store_id、remark)" + "description": "入库单基本信息", + "children": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "入库单ID" + }, + { + "name": "entry_order_code", + "type": "string", + "required": true, + "description": "入库单号" + }, + { + "name": "order_status", + "type": "string", + "required": true, + "description": "入库单状态(CREATED/PENDING/COMPLETED/CANCELLED)" + }, + { + "name": "store_remask", + "type": "string", + "required": true, + "description": "货主商家备注" + } + ] }, { "name": "items", "type": "array", "required": true, - "description": "入库明细列表,每项含 id、stock_id、count(计划数量)、received_quantity、direct_inbound_quantity(已导入/PDA入库数量)、remaining_quantity(剩余可入库数量)、pending_binding_total(pending 绑定总量)、bindings(pending 绑定列表,同 storage.entry.get 结构)、direct_logs(已有入库记录)" + "description": "入库明细列表", + "children": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "入库明细ID(wms_entry_items.id)" + }, + { + "name": "stock_id", + "type": "number", + "required": true, + "description": "商品SKU ID" + }, + { + "name": "planned", + "type": "number", + "required": true, + "description": "计划入库数量(对应原 count 字段)" + }, + { + "name": "completed", + "type": "number", + "required": true, + "description": "已完成导入/PDA 入库数量(对应原 direct_inbound_quantity 字段)" + }, + { + "name": "stock", + "type": "object", + "required": true, + "description": "商品详情(含 item_code、item_name、sku_property、barcodes 等缓存字段)" + }, + { + "name": "bindings", + "type": "array", + "required": true, + "description": "该明细的收货单绑定列表(来自 wms_entry_receiving_binding + InboundDirectLog)", + "children": [ + { + "name": "detail_id", + "type": "number", + "required": false, + "description": "收货明细ID(wms_receiving_detail.id),无绑定时可能不存在" + }, + { + "name": "binding_id", + "type": "number", + "required": false, + "description": "绑定记录ID(wms_entry_receiving_binding.id),无绑定时可能不存在" + }, + { + "name": "allocated_quantity", + "type": "number", + "required": false, + "description": "预分配数量" + }, + { + "name": "space_id", + "type": "number", + "required": false, + "description": "存放库位ID(取自 InboundDirectLog)" + }, + { + "name": "space_name", + "type": "string", + "required": false, + "description": "库位名称(取自 wms_location_space.custom_name 或 space_code)" + } + ] + } + ] }, { - "name": "direct_logs", + "name": "receivingBindings", "type": "array", "required": true, - "description": "该入库单下所有导入/PDA 入库记录(含 space_id)" - }, - { - "name": "summary", - "type": "object", - "required": true, - "description": "汇总信息(total_items、total_planned、total_direct_inbound)" + "description": "入库单层级的收货单绑定关系列表(wms_entry_order_receiving)", + "children": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "绑定记录ID" + }, + { + "name": "receiving_id", + "type": "number", + "required": true, + "description": "收货单ID" + }, + { + "name": "receiving", + "type": "object", + "required": true, + "description": "收货单信息(id、receiving_number、status、storage_status、created_at)" + } + ] } ], "errors": [ @@ -19284,7 +19327,7 @@ }, { "method": "storage.entry.addDirectInboundItem", - "description": "按商品增量添加导入/PDA 入库记录(支持单条和批量)。单条模式传 stock_id/quantity/inbound_type/remark,批量模式传 items 数组。批量模式所有商品共享同一个入库单状态校验,任一商品校验失败整批拒绝。若某商品累计入库量超过计划数量则拒绝。", + "description": "按商品增量添加导入/PDA 入库记录(支持单条和批量)。单条模式传 stock_id/quantity/inbound_type/remark,批量模式传 items 数组。批量模式所有商品共享同一个入库单状态校验,任一商品校验失败整批拒绝。若某商品累计入库量超过计划数量则拒绝(PENDING 非绑定模式)。PENDING 状态需传 receiving_detail_id 绑定收货明细;CREATED 人工导入允许超过计划数量;传入 receiving_detail_id 时 quantity 可选(自动计算可用数量),space_id 必填。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -19297,11 +19340,11 @@ ], "params": [ { - "name": "entry_order_code", - "type": "string", + "name": "entry_order_id", + "type": "number", "required": true, "source": "body", - "description": "入库单号" + "description": "入库单 ID" }, { "name": "stock_id", @@ -19313,9 +19356,9 @@ { "name": "quantity", "type": "number", - "required": true, + "required": false, "source": "body", - "description": "本次入库数量(正整数)" + "description": "本次入库数量(正整数)。传入 receiving_detail_id 时可选,自动计算收货明细可用数量;非绑定模式必填" }, { "name": "inbound_type", @@ -19336,14 +19379,28 @@ "type": "number", "required": false, "source": "body", - "description": "存放库位ID(单条模式),关联 wms_location_space.id;为空时 commit 默认使用库位 1" + "description": "存放库位ID(单条模式),关联 wms_location_space.id。绑定收货明细时必填;为空时 commit 默认使用库位 1" + }, + { + "name": "receiving_detail_id", + "type": "number", + "required": false, + "source": "body", + "description": "收货单明细ID(PDA 上架绑定模式),传入后触发收货明细预占绑定,quantity 自动计算" + }, + { + "name": "allocated_quantity", + "type": "number", + "required": false, + "source": "body", + "description": "预分配数量(单条模式,可选,默认等于 quantity)" }, { "name": "items", "type": "array", "required": false, "source": "body", - "description": "批量模式:商品列表,每项包含 stock_id(商品SKU ID, number, 必填)、quantity(入库数量, number, 必填)、inbound_type(import/pda, string, 必填)、space_id(库位ID, number, 可选)、remark(备注, string, 可选)。传入 items 时忽略顶层的 stock_id/quantity/inbound_type/remark/space_id。" + "description": "批量模式:商品列表,每项包含 stock_id(商品SKU ID, number, 必填)、quantity(入库数量, number, 绑定模式可选)、inbound_type(import/pda, string, 必填)、space_id(库位ID, number, 绑定模式必填)、remark(备注, string, 可选)、receiving_detail_id(收货明细ID, number, 可选)、allocated_quantity(预分配数量, number, 可选)。传入 items 时忽略顶层的 stock_id/quantity/inbound_type/remark/space_id。" } ], "response": [ @@ -19357,67 +19414,115 @@ "name": "stock_id", "type": "number", "required": false, - "description": "单条模式返回:商品SKU ID" + "description": "商品SKU ID" }, { "name": "quantity", "type": "number", "required": false, - "description": "单条模式返回:本次入库数量" + "description": "本次入库数量" }, { "name": "inbound_type", "type": "string", "required": false, - "description": "单条模式返回:入库方式" + "description": "入库方式" + }, + { + "name": "space_id", + "type": "number", + "required": false, + "description": "存放库位ID" }, { "name": "plan_quantity", "type": "number", "required": false, - "description": "单条模式返回:该商品计划入库总数" + "description": "入库单中该商品计划数量" }, { "name": "existing_before", "type": "number", "required": false, - "description": "单条模式返回:本次入库前已入库数量" + "description": "添加前已有入库总量" }, { "name": "existing_after", "type": "number", "required": false, - "description": "单条模式返回:本次入库后总入库数量" + "description": "添加后入库总量" }, { "name": "remaining", "type": "number", "required": false, - "description": "单条模式返回:剩余可入库数量" + "description": "剩余可入库数量" + }, + { + "name": "receivingBindResult", + "type": "object", + "required": false, + "description": "收货单绑定结果(仅绑定模式返回),含 binding_id、receiving_detail_id、allocated_quantity、status" }, { "name": "count", "type": "number", "required": false, - "description": "批量模式返回:成功添加的条目数" + "description": "批量模式:写入项数" }, { "name": "total_quantity", "type": "number", "required": false, - "description": "批量模式返回:入库总数量" + "description": "批量模式:入库总数量" }, { "name": "items", "type": "array", "required": false, - "description": "批量模式返回:入库结果列表,每项包含 id/stock_id/quantity/inbound_type/space_id/plan_quantity/existing_before/existing_after/remaining" + "description": "批量模式:每项入库记录详情(结构同单条模式)" } ], "errors": [ { "code": 400, - "message": "参数校验失败:entry_order_code 必填 / stock_id 必填 / quantity 必须为正整数 / inbound_type 必须为 import 或 pda / 已作废入库单不允许操作 / 已完成的入库单不允许操作 / 入库单中不存在该 stock_id 的商品 / 入库数量超过计划" + "message": "entry_order_id 必填" + }, + { + "code": 400, + "message": "items[].stock_id 必填 / items[].quantity 必须为正整数 / items[].inbound_type 必须为 import 或 pda" + }, + { + "code": 400, + "message": "已作废入库单不允许操作 / 已完成的入库单不允许操作" + }, + { + "code": 400, + "message": "入库单已绑定收货单且状态为 CREATED,请先审核后再进行上架操作" + }, + { + "code": 400, + "message": "入库单未绑定收货单,无法上架(PENDING)" + }, + { + "code": 400, + "message": "随机入库需要选定收货单明细提交,缺少 receiving_detail_id(PENDING)" + }, + { + "code": 400, + "message": "绑定收货明细时必须指定 space_id" + }, + { + "code": 400, + "message": "入库数量超过计划:商品计划 X,已入库 Y,本次 Z,合计 W" + }, + { + "code": 400, + "message": "收货明细可用数量不足:实际数量 X,已占用 Y,可用 Z" + }, + { + "code": 400, + "message": "入库单中不存在该商品" }, { "code": 404, @@ -19427,7 +19532,7 @@ }, { "method": "storage.entry.commitDirectInbound", - "description": "提交确认完成导入/PDA 入库。按实收数量写入库存(wms_storage、wms_stock_transaction),未入库商品跳过不做处理,更新入库单状态为 COMPLETED,并异步触发奇门/API 入库完成回传(按实收数量回传)。", + "description": "提交确认完成导入/PDA 入库。先同步奇门/API 回传,成功后在 onSuccess 回调内开启事务写入库存(wms_stock_warehouse.quantity 增量、wms_stock_transaction 流水),将 pending 状态的 EntryReceivingBinding 更新为 committed,更新入库单状态为 COMPLETED,同步 sync_status=SUCCESS。不足量提交时未入库商品跳过。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -19440,11 +19545,11 @@ ], "params": [ { - "name": "entry_order_code", - "type": "string", + "name": "entry_order_id", + "type": "number", "required": true, "source": "body", - "description": "入库单号" + "description": "入库单 ID" } ], "response": [ @@ -19488,11 +19593,19 @@ "errors": [ { "code": 400, - "message": "参数校验失败:entry_order_code 必填 / 已作废入库单不允许完成 / 入库单已完成请勿重复提交 / 暂无导入/PDA 入库记录 / 入库单无明细 / 库存写入异常" + "message": "entry_order_id 必填" + }, + { + "code": 400, + "message": "已作废入库单不允许完成 / 入库单已完成请勿重复提交 / 暂无导入/PDA 入库记录请先添加商品 / 入库单无明细" }, { "code": 404, "message": "入库单不存在或无权访问" + }, + { + "code": 500, + "message": "库存写入异常 / 同步回传失败" } ] }, @@ -19732,7 +19845,7 @@ }, { "method": "storage.entry.receivingCompare", - "description": "入库单与收货单商品对照预览:给定入库单ID和收货单ID,返回入库商品与收货商品的逐行对照视图,含匹配状态(matched/entry_only)和汇总统计。纯只读接口。", + "description": "入库单与收货单商品对照预览:给定入库单ID和收货单ID(支持多个),返回入库商品与收货商品的逐行对照视图,含匹配状态(matched/entry_only)和汇总统计。纯只读接口。", "isNeedAuth": false, "isNeedLogin": true, "headers": [], @@ -19747,9 +19860,16 @@ { "name": "receiving_id", "type": "number", - "required": true, + "required": false, "source": "body", - "description": "收货单ID" + "description": "收货单ID,单个时使用,与 receiving_ids 二选一" + }, + { + "name": "receiving_ids", + "type": "array", + "required": false, + "source": "body", + "description": "收货单ID数组,优先使用;与 receiving_id 二选一,传了此参数则忽略 receiving_id" } ], "response": [ @@ -19766,34 +19886,89 @@ "description": "入库单号" }, { - "name": "receiving_id", - "type": "number", - "required": true, - "description": "收货单ID" - }, - { - "name": "receiving_number", - "type": "string", - "required": true, - "description": "收货单号" - }, - { - "name": "comparison", + "name": "comparisons", "type": "array", "required": true, - "description": "逐行对照列表" + "description": "各收货单对照结果列表", + "children": [ + { + "name": "receiving_id", + "type": "number", + "required": true, + "description": "收货单ID" + }, + { + "name": "receiving_number", + "type": "string", + "required": true, + "description": "收货单号" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "对比状态:matched-匹配成功, error-校验失败" + }, + { + "name": "error_code", + "type": "string", + "required": false, + "description": "错误码(仅 status=error 时),如 RECEIVING_NOT_FOUND" + }, + { + "name": "error_message", + "type": "string", + "required": false, + "description": "错误信息(仅 status=error 时)" + }, + { + "name": "comparison", + "type": "array", + "required": false, + "description": "逐行对照列表(仅 status=matched 时),每项含 entry_item_id/stock_id/warehouse_item_code/warehouse_item_name/warehouse_item_spec/entry_count/entry_received/receiving_detail_id/receiving_product_code/receiving_product_name/receiving_actual_quantity/receiving_allocated/receiving_available/match_status" + }, + { + "name": "receiving_only", + "type": "array", + "required": false, + "description": "仅收货单有的商品列表(仅 status=matched 时),每项含 receiving_detail_id/receiving_product_code/receiving_product_name/receiving_actual_quantity/receiving_allocated/receiving_available" + }, + { + "name": "summary", + "type": "object", + "required": false, + "description": "该收货单的汇总统计(仅 status=matched 时),含 total_entry_items/matched_items/entry_only_items/receiving_only_items" + } + ] }, { - "name": "receiving_only", + "name": "errors", "type": "array", - "required": true, - "description": "仅收货单有的商品列表" + "required": false, + "description": "校验失败的收货单列表(status=error 的记录也会在此汇总)" }, { - "name": "summary", + "name": "total_summary", "type": "object", "required": true, - "description": "汇总统计" + "description": "总体汇总统计", + "children": [ + { + "name": "total_receivings", + "type": "number", + "description": "请求的收货单总数" + }, + { + "name": "matched_count", + "type": "number", + "description": "匹配成功的收货单数" + }, + { + "name": "error_count", + "type": "number", + "description": "校验失败的收货单数" + } + ] } ], "errors": [ @@ -19803,27 +19978,355 @@ }, { "code": 400, - "message": "receiving_id 必填" + "message": "receiving_ids 或 receiving_id 必填" }, { "code": 404, "message": "入库单不存在或无权访问" + } + ] + }, + { + "method": "storage.entry.bindReceiving", + "description": "将收货单绑定到入库单(仅建立主表级关联,不做明细数量分配)。校验入库单状态(需为 CREATED 或 PENDING)、收货单有效性(存在、同仓库、未取消)后,逐个建立 wms_entry_order_receiving 绑定记录。支持部分成功:校验通过的写入绑定,不通过的在 failed 列表中返回原因。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "entry_order_id", + "type": "number", + "required": true, + "source": "body", + "description": "入库单ID" + }, + { + "name": "receiving_ids", + "type": "array", + "required": true, + "source": "body", + "description": "要绑定的收货单ID列表,每项为 integer" + } + ], + "response": [ + { + "name": "success", + "type": "array", + "required": true, + "description": "绑定成功列表,每项包含 receiving_id、receiving_number" + }, + { + "name": "failed", + "type": "array", + "required": true, + "description": "绑定失败列表,每项包含 receiving_id、error_code、message", + "items": { + "type": "object", + "properties": { + "receiving_id": { + "type": "number", + "description": "收货单ID" + }, + "receiving_number": { + "type": "string", + "description": "收货单号(部分失败项可能不返回)" + }, + "error_code": { + "type": "string", + "description": "错误码,可能值:RECEIVING_NOT_FOUND(收货单不存在或已删除)、RECEIVING_NOT_REVIEWED(收货单未审核)、WAREHOUSE_MISMATCH(收货单与入库单仓库不一致)、RECEIVING_CANCELLED(收货单已取消)、OWNER_MISMATCH(收货单与入库单货主不一致)、BIND_ERROR(绑定过程异常)" + }, + "message": { + "type": "string", + "description": "中文错误描述" + } + } + } + }, + { + "name": "success_count", + "type": "number", + "required": true, + "description": "成功数量" + }, + { + "name": "failed_count", + "type": "number", + "required": true, + "description": "失败数量" + } + ], + "errors": [ + { + "code": 400, + "message": "参数校验失败:entry_order_id 必填 / receiving_ids 必填且为非空数组 / 入库单状态不允许绑定(当前状态非 CREATED/PENDING)" }, { "code": 404, - "message": "收货单不存在" + "message": "入库单不存在" + }, + { + "code": "OWNER_MISMATCH", + "message": "收货单与入库单货主不一致" + }, + { + "code": "RECEIVING_NOT_REVIEWED", + "message": "收货单未审核" + } + ] + }, + { + "method": "storage.entry.reviewEntry", + "description": "审核入库单(CREATED → PENDING),仅允许已绑定收货单的入库单推进状态", + "isNeedAuth": false, + "isNeedLogin": true, + "isNeedRight": false, + "isNeedLog": true, + "headers": [], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "入库单ID" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "success/failure" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "200 成功 / 400 失败" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息" + }, + { + "name": "data.id", + "type": "number", + "required": true, + "description": "入库单ID" + }, + { + "name": "data.order_status", + "type": "string", + "required": true, + "description": "审核后状态(PENDING)" + } + ], + "errors": [ + { + "code": 400, + "message": "id 必填" + }, + { + "code": 400, + "message": "入库单不存在" + }, + { + "code": 400, + "message": "当前状态[xxx]不允许审核,仅 CREATED 可审核" + }, + { + "code": 400, + "message": "入库单未绑定收货单,请先绑定收货单后再审核" + } + ] + }, + { + "method": "storage.entry.containerList", + "description": "PDA 上架时拉取入库单已绑定收货单中指定商品的可用容器列表(未绑定的收货明细)。返回匹配明细的 detail_id、receiving_id、barcode、product_name、actual_quantity、receiving_status,以及商品详情 stock。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "entry_order_id", + "type": "number", + "required": true, + "source": "body", + "description": "入库单 ID" + }, + { + "name": "stock_id", + "type": "number", + "required": true, + "source": "body", + "description": "商品 stock_id(即 wms_stock_warehouse.id)" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "可用容器(收货明细)列表" + }, + { + "name": "list[].detail_id", + "type": "number", + "required": true, + "description": "收货明细 ID" + }, + { + "name": "list[].receiving_id", + "type": "number", + "required": true, + "description": "收货单 ID" + }, + { + "name": "list[].barcode", + "type": "string", + "required": true, + "description": "商品条码" + }, + { + "name": "list[].product_name", + "type": "string", + "required": true, + "description": "商品名称" + }, + { + "name": "list[].actual_quantity", + "type": "number", + "required": true, + "description": "实收数量" + }, + { + "name": "list[].receiving_status", + "type": "string", + "required": true, + "description": "收货单状态" + }, + { + "name": "list[].stock", + "type": "object", + "required": true, + "description": "商品详情(通过 getStockDetails 获取,含 item_code、item_name、sku_property、barcodes 等缓存字段)" + }, + { + "name": "total", + "type": "number", + "required": true, + "description": "匹配总数" + } + ], + "errors": [ + { + "code": 0, + "message": "用户未绑定仓库" + }, + { + "code": 0, + "message": "entry_order_id 不能为空" + }, + { + "code": 0, + "message": "stock_id 不能为空" + }, + { + "code": 0, + "message": "入库单不存在或无权访问" + }, + { + "code": 500, + "message": "服务器查询失败" + } + ] + }, + { + "method": "storage.entry.queryEntryLogs", + "description": "查询入库单操作日志。根据入库单 ID 分页查询关联的操作日志记录(入库单创建、状态变更、审核等操作的审计轨迹)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "入库单 ID(必填)" + }, + { + "name": "page", + "type": "number", + "required": false, + "source": "body", + "description": "页码,默认 1" + }, + { + "name": "pageSize", + "type": "number", + "required": false, + "source": "body", + "description": "每页数量,默认 20" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "操作日志列表" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息(page、pageSize、total、totalPages、hasPrevious、hasNext)" + } + ], + "errors": [ + { + "code": 400, + "message": "id 不能为空" + }, + { + "code": 500, + "message": "查询失败" } ] } ] }, { - "groupName": "导入/PDA入库模块", + "groupName": "导入/PDA直接入库", "module": "storage.directInbound", "list": [ { "method": "storage.directInbound.getItems", - "description": "[@deprecated 已弃用,请使用 storage.entry.getDirectInboundItems 替代] 获取入库单的导入/PDA 入库信息,返回入库单基本信息、明细列表,以及每项明细已有的导入/PDA 入库记录(含汇总和剩余可入库数量)。", + "description": "[@deprecated 已弃用,请使用 storage.entry.getDirectInboundItems 替代] 获取入库单的导入/PDA 入库信息(精简版)。返回入库单基本信息、明细列表(含计划数量 planned 与已完成数量 completed)、每项明细的收货绑定列表 bindings(含 detail_id、binding_id、allocated_quantity、space_id、space_name),以及收货单绑定关系 receivingBindings。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -19848,25 +20351,135 @@ "name": "entryOrder", "type": "object", "required": true, - "description": "入库单基本信息(id、entry_order_code、order_type、order_status、source_type、warehouse_id、store_id、remark)" + "description": "入库单基本信息", + "children": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "入库单ID" + }, + { + "name": "entry_order_code", + "type": "string", + "required": true, + "description": "入库单号" + }, + { + "name": "order_status", + "type": "string", + "required": true, + "description": "入库单状态(CREATED/PENDING/COMPLETED/CANCELLED)" + }, + { + "name": "store_remask", + "type": "string", + "required": true, + "description": "货主商家备注" + } + ] }, { "name": "items", "type": "array", "required": true, - "description": "入库明细列表,每项含 id、stock_id、count(计划数量)、received_quantity、direct_inbound_quantity(已导入/PDA入库数量)、remaining_quantity(剩余可入库数量)、pending_binding_total(pending 绑定总量)、bindings(pending 绑定列表,同 storage.entry.get 结构)、direct_logs(已有入库记录)" + "description": "入库明细列表", + "children": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "入库明细ID(wms_entry_items.id)" + }, + { + "name": "stock_id", + "type": "number", + "required": true, + "description": "商品SKU ID" + }, + { + "name": "planned", + "type": "number", + "required": true, + "description": "计划入库数量(对应原 count 字段)" + }, + { + "name": "completed", + "type": "number", + "required": true, + "description": "已完成导入/PDA 入库数量(对应原 direct_inbound_quantity 字段)" + }, + { + "name": "stock", + "type": "object", + "required": true, + "description": "商品详情(含 item_code、item_name、sku_property、barcodes 等缓存字段)" + }, + { + "name": "bindings", + "type": "array", + "required": true, + "description": "该明细的收货单绑定列表", + "children": [ + { + "name": "detail_id", + "type": "number", + "required": false, + "description": "收货明细ID" + }, + { + "name": "binding_id", + "type": "number", + "required": false, + "description": "绑定记录ID" + }, + { + "name": "allocated_quantity", + "type": "number", + "required": false, + "description": "预分配数量" + }, + { + "name": "space_id", + "type": "number", + "required": false, + "description": "存放库位ID" + }, + { + "name": "space_name", + "type": "string", + "required": false, + "description": "库位名称" + } + ] + } + ] }, { - "name": "direct_logs", + "name": "receivingBindings", "type": "array", "required": true, - "description": "该入库单下所有导入/PDA 入库记录(含 space_id)" - }, - { - "name": "summary", - "type": "object", - "required": true, - "description": "汇总信息(total_items、total_planned、total_direct_inbound)" + "description": "入库单层级的收货单绑定关系列表", + "children": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "绑定记录ID" + }, + { + "name": "receiving_id", + "type": "number", + "required": true, + "description": "收货单ID" + }, + { + "name": "receiving", + "type": "object", + "required": true, + "description": "收货单信息(id、receiving_number、status、storage_status、created_at)" + } + ] } ], "errors": [ @@ -19895,11 +20508,11 @@ ], "params": [ { - "name": "entry_order_code", - "type": "string", + "name": "entry_order_id", + "type": "number", "required": true, "source": "body", - "description": "入库单号" + "description": "入库单 ID(必填,通过主键查找入库单)" }, { "name": "stock_id", @@ -20038,11 +20651,11 @@ ], "params": [ { - "name": "entry_order_code", - "type": "string", + "name": "entry_order_id", + "type": "number", "required": true, "source": "body", - "description": "入库单号" + "description": "入库单 ID" } ], "response": [ @@ -20086,7 +20699,11 @@ "errors": [ { "code": 400, - "message": "参数校验失败:entry_order_code 必填 / 已作废入库单不允许完成 / 入库单已完成请勿重复提交 / 暂无导入/PDA 入库记录 / 入库单无明细 / 库存写入异常" + "message": "entry_order_id 必填" + }, + { + "code": 400, + "message": "已作废入库单不允许完成 / 入库单已完成请勿重复提交 / 暂无导入/PDA 入库记录请先添加商品 / 入库单无明细" }, { "code": 404, @@ -20339,13 +20956,101 @@ "list": [ { "method": "storage.inventory.quickPutaway", - "description": "[已删除] 收货单快捷入库上架(此方法已从代码中移除)。原用于单一收货单的快速入库操作,现已弃用。请使用 storage.entry.commitDirectInbound 替代——commitDirectInbound 提供导入/PDA 入库完成确认功能,是目前唯一的库存写入入库链路。", + "description": "收货单快捷入库:将已审核的收货单(completed + is_review=true)明细按 stock_id(system_product_id)分组合并数量后,直接创建入库单(SCRK,自动审批到 PENDING),写入 wms_entry_order_receiving 主表级绑定,并更新收货单及其明细的入库状态(storage_status)。要求货主仓库签约配置 policy_config.allow_receiving_quick_putaway=1 开启快捷入库功能。", "isNeedAuth": true, "isNeedLogin": true, "headers": [], - "params": [], - "response": [], - "errors": [] + "params": [ + { + "name": "receiving_id", + "type": "number", + "required": true, + "source": "body", + "description": "收货单ID(必填)" + } + ], + "response": [ + { + "name": "entry_order_id", + "type": "number", + "description": "创建的入库单ID" + }, + { + "name": "entry_order_code", + "type": "string", + "description": "入库单号(SCRK + 年月日 + 4位流水号)" + }, + { + "name": "order_status", + "type": "string", + "description": "入库单状态(PENDING)" + }, + { + "name": "receiving_id", + "type": "number", + "description": "收货单ID" + }, + { + "name": "total_lines", + "type": "number", + "description": "入库单明细行数(按 stock_id 合并后的行数)" + }, + { + "name": "total_quantity", + "type": "number", + "description": "入库总数量" + } + ], + "errors": [ + { + "code": 400, + "message": "receiving_id 必填" + }, + { + "code": 400, + "message": "无法获取当前仓库信息" + }, + { + "code": 404, + "message": "收货单不存在或无权访问" + }, + { + "code": 400, + "message": "收货单已作废,不允许快捷入库" + }, + { + "code": 400, + "message": "收货单状态不允许快捷入库,仅 completed 状态可操作" + }, + { + "code": 400, + "message": "收货单未审核,不允许快捷入库" + }, + { + "code": 400, + "message": "货主仓库签约关系不存在" + }, + { + "code": 400, + "message": "货主未开启收货单快捷入库功能" + }, + { + "code": 400, + "message": "收货单无明细,无法创建入库单" + }, + { + "code": 400, + "message": "收货单中所有明细均未关联系统商品,无法创建入库单" + }, + { + "code": 400, + "message": "以下商品在当前仓库中不存在或已失效" + }, + { + "code": 500, + "message": "系统异常" + } + ] }, { "method": "storage.inventory.transferLocation", @@ -25508,7 +26213,7 @@ ] }, { - "groupName": "收货管理模块", + "groupName": "收货管理", "module": "storage.receiving", "list": [ { @@ -25520,6 +26225,213 @@ "params": [], "response": [], "errors": [] + }, + { + "method": "storage.receiving.scanDetail", + "description": "PDA 上架扫码定位收货明细:扫描商品条码/箱唛/托盘唛,快速定位收货明细。同一条码可能匹配多条收货明细,以列表 { list, total } 格式返回所有匹配结果。若 barcode 为纯数字优先按明细 ID 精确匹配,否则按商品条码精确匹配。PDA专用。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "entry_order_id", + "type": "number", + "required": true, + "source": "body", + "description": "入库单 ID" + }, + { + "name": "barcode", + "type": "string", + "required": true, + "source": "body", + "description": "扫描条码,支持:收货明细 ID(托盘唛头)、商品条码" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "匹配的收货明细列表" + }, + { + "name": "list[].detail_id", + "type": "number", + "required": true, + "description": "收货明细 ID" + }, + { + "name": "list[].receiving_id", + "type": "number", + "required": true, + "description": "收货单 ID" + }, + { + "name": "list[].barcode", + "type": "string", + "required": true, + "description": "商品条码" + }, + { + "name": "list[].product_name", + "type": "string", + "required": true, + "description": "商品名称" + }, + { + "name": "list[].actual_quantity", + "type": "number", + "required": true, + "description": "实收数量" + }, + { + "name": "list[].receiving_status", + "type": "string", + "required": true, + "description": "收货单状态" + }, + { + "name": "list[].stock", + "type": "object", + "required": true, + "description": "商品详情(通过 getStockDetails 获取,含 item_code、item_name、sku_property、barcodes 等缓存字段)" + }, + { + "name": "total", + "type": "number", + "required": true, + "description": "匹配总数" + } + ], + "errors": [ + { + "code": 0, + "message": "用户未绑定仓库" + }, + { + "code": 0, + "message": "入库单ID不能为空" + }, + { + "code": 0, + "message": "扫描条码不能为空" + }, + { + "code": 0, + "message": "入库单不存在或无权访问" + }, + { + "code": 0, + "message": "该入库单尚未关联收货单" + }, + { + "code": 0, + "message": "未找到可用的收货明细" + }, + { + "code": 0, + "message": "未找到匹配的收货明细" + }, + { + "code": 500, + "message": "服务器扫描查询失败" + } + ] + } + ] + }, + { + "groupName": "入库模块", + "module": "storage", + "list": [ + { + "method": "storage.entry.list", + "description": "入库单列表查询。where.order_status 支持 CREATING/CREATED/PENDING/COMPLETED/CANCELLED。CREATED=已创建待审核(需审核后才能绑定和完成入库),PENDING=已审核(可绑定和完成入库)。where 新增 hasReceiving 虚拟筛选字段,传 true/false 筛选已绑定/未绑定收货单的入库单(通过 wms_entry_order_receiving 表查询实现)。quickWhere 支持模糊搜索:entry_order_code(入库单号)、purchase_order_code(采购单号)、supplier_name(供应商名称)、store_name(货主名称)、warehouse_name(仓库名称)、receiving_id(收货单 ID / 托盘唛头,通过 wms_entry_order_receiving 绑定表关联搜索)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数,支持 page/pageSize" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会在 main 中自动标准化;支持 quickWhere、order_status(CREATING/CREATED/PENDING/COMPLETED/CANCELLED)、store_id、order_type、日期区间等字段。新增 expense_record(费用是否记录)筛选,支持 eq/in;值会归一化为 0/1,兼容 true/false、1/0、y/n、yes/no(大小写不敏感,含布尔/字符串/数字写法)。示例:where.expense_record={operator:eq,value:true} 等价 where.expense_record={operator:eq,value:1};where.expense_record={operator:in,value:[true,\"0\",\"yes\",\"n\"]} 会归一化为 [1,0]。若部署环境尚未完成 expense_record 字段迁移,传入该筛选可能返回 400,错误提示为\"当前环境未提供 expense_record 字段,暂不支持该筛选条件,请先完成表结构升级\"。新增 hasReceiving 虚拟筛选字段,传 true/false 筛选已绑定/未绑定收货单的入库单(虚拟字段,不直接对应数据库列,内部通过 wms_entry_order_receiving 表查询实现)。quickWhere 模糊搜索范围:entry_order_code(入库单号)、purchase_order_code(采购单号)、supplier_name(供应商名称)、store_name(货主名称)、warehouse_name(仓库名称)、receiving_id(收货单 ID / 托盘唛头,通过 wms_entry_order_receiving 绑定表关联搜索)。" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数,支持 sortField/sortOrder" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "入库单列表" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息(page、pageSize、total、totalPages、hasPrevious、hasNext)" + }, + { + "name": "summary", + "type": "object", + "required": true, + "description": "状态汇总(total、pending、creating、created、completed、cancelled)" + }, + { + "name": "list[].receivingBindings", + "type": "array", + "required": false, + "description": "收货单绑定列表(主表级关联),每项含 id、entry_order_id、receiving_id 及 receiving 对象(id、receiving_number、status、storage_status、created_at)" + }, + { + "name": "list[].hasReceiving", + "type": "boolean", + "required": false, + "description": "是否存在收货单绑定" + } + ], + "errors": [ + { + "code": "400", + "message": "筛选条件格式错误", + "description": "筛选条件格式错误" + }, + { + "code": "500", + "message": "查询失败", + "description": "查询失败" + } + ] } ] } diff --git a/skills/entry-order-test-guide.md b/skills/entry-order-test-guide.md new file mode 100644 index 0000000..163288c --- /dev/null +++ b/skills/entry-order-test-guide.md @@ -0,0 +1,449 @@ +# 入库单推送全流程测试指南 + +## 1. 全流程概述 + +``` +奇门推送 entryorder.create → 创建入库单(CREATED) + → bindReceiving(绑定收货单) + → reviewEntry(CREATED→PENDING) + → addItem(PDA上架,传 receiving_detail_id + space_id) + → commit(提交入库+奇门同步→COMPLETED) + +或 quickInbound(虚拟直入,跳过收货单,CREATED→COMPLETED) +``` + +### 流程说明 + +| 阶段 | method | 状态变化 | 说明 | +|------|--------|----------|------| +| 奇门创建 | `qimen.entryorder.create` | (无)→CREATED | 奇门 XML 推送,创建入库单及明细 | +| 绑定收货单 | `storage.entry.bindReceiving` | CREATED→CREATED | 将入库单与收货单关联 | +| 审核 | `storage.entry.reviewEntry` | CREATED→PENDING | 审核通过,允许上架,**必须已绑定收货单** | +| PDA上架 | `storage.directInbound.addItem` | PENDING→PENDING | PDA扫码上架,传 `receiving_detail_id` + `space_id` | +| 提交入库 | `storage.directInbound.commit` | PENDING→COMPLETED | 先奇门同步,再写库存 | +| 虚拟直入 | `storage.entry.quickInbound` | CREATED→COMPLETED | 跳过收货单,一键完成入库 | + +## 2. 关键接口列表 + +| 步骤 | method | 说明 | 入口 | +|------|--------|------|------| +| 创建 | `qimen.entryorder.create` | 奇门推送 XML 创建入库单 | /qimen | +| 绑定 | `storage.entry.bindReceiving` | 绑定收货单到入库单 | /system | +| 审核 | `storage.entry.reviewEntry` | CREATED→PENDING,需已绑定 | /system | +| 上架 | `storage.directInbound.addItem` | PDA添加,可选绑定收货明细 | /system | +| 提交 | `storage.directInbound.commit` | 同步奇门+写库存→COMPLETED | /system | +| 虚拟 | `storage.entry.quickInbound` | 一键虚拟入库 | /system | +| 对照 | `storage.entry.receivingCompare` | 入库单 vs 收货单明细对照 | /system | +| 查询 | `storage.directInbound.getItems` | 查询直入记录 | /system | +| 日志 | `storage.entry.queryEntryLogs` | 查询入库单操作日志 | /system | + +## 3. 踩坑点 + +### 3a. 端口 + +配置文件(`config/config.local.js`)中端口是 **6060**,不是 Egg.js 默认的 7001。 + +```powershell +# 确认端口 +Select-String -Path "config/config.local.js" -Pattern "port" +``` + +### 3b. app_key 双重角色 + +- **签名用**:`config.qimen.appKey`(如 `23535631`),用于奇门请求的 MD5 签名计算 +- **validateApi 查询匹配用**:请求参数中的 `app_key`(如 `23060081`),用于匹配 `wms_api_app` 表记录 +- **两个值不同**,签名的 `app_key` 不参与 `wms_api_app` 绑定查询 + +### 3c. 奇门签名 + +- **签名算法**:`secret + sortedParams + xmlBody + secret` → MD5 → 大写 +- **签名不验证入站请求**:qimen 入口无 `verifyTopRequest` 校验 +- **使用已有合约配置**:从 `wms_api_app` 表读取,不要无中生有创建新配置 + +### 3d. itemId 必传 + +- `itemId` 为空时,按 `item_code + app_key + warehouse_id + store_id` 查询 `StockStore` +- `app_key` 不匹配会导致找不到商品 +- **建议一律传 `itemId`** 以避免匹配问题 + +### 3e. 服务器重启 + +修改代码后需完全重启: + +```powershell +taskkill /F /IM node.exe +npm run dev +``` + +端口被占用排查: + +```powershell +netstat -ano | findstr :6060 +``` + +### 3f. /system 接口需要 headers + +```http +platform: web +project: wms +Authorization: Bearer +``` + +测试账号:`liufumingren` / `111111` + +获取 token: + +```powershell +curl -X POST http://localhost:6060/system?method=user.login ` + -H "platform: web" ` + -H "project: wms" ` + -H "Content-Type: application/json" ` + -d '{"username":"liufumingren","password":"111111"}' +``` + +### 3g. 先同步后写库 + +`quickInbound` 和 `commit` 的执行顺序已改为: + +1. 先调用 `qimenEntrySync` 同步到奇门/ERP +2. 同步成功后才写库存 +3. 同步失败不写库存,只标记为 `FAILED` + +### 3h. 绑定模式 + +`addItem` 传 `receiving_detail_id` 时进入绑定模式: + +- **忽略 `quantity` 字段**,实际数量从 `ReceivingDetail.actual_quantity` 取值 +- **必须传 `space_id`**(库位ID) +- **允许超过入库单 `planQty`**,不受计划数量限制 + +## 4. 快速测试脚本示例 + +### 4.1 准备工作:获取 Token + +```powershell +$loginBody = @{username="liufumingren";password="111111"} | ConvertTo-Json +$loginResp = curl -s -X POST "http://localhost:6060/system?method=user.login" ` + -H "platform: web" -H "project: wms" ` + -H "Content-Type: application/json" ` + -d $loginBody +$token = ($loginResp | ConvertFrom-Json).data.token +Write-Host "Token: $token" +``` + +### 4.2 创建入库单(奇门推送) + +```xml +POST /qimen?method=entryorder.create&app_key=23060081&customerId=4&v=1.0&format=xml&sign_method=md5×tamp=2026-06-27+10:00:00&sign=XXX + + + + TEST-ENTRY-001 + WH001 + JYCK + + + + SKU001 + 100 + + + +``` + +### 4.3 创建收货单 + +```powershell +$rcvBody = @{ + delivery_method="truck" + loading_method="without_pallet" + store_id=1000000 +} | ConvertTo-Json + +curl -s -X POST "http://localhost:6060/system?method=storage.receiving.create" ` + -H "platform: web" -H "project: wms" ` + -H "Authorization: Bearer $token" ` + -H "Content-Type: application/json" ` + -d $rcvBody +``` + +### 4.4 添加收货明细 + +```powershell +$detailBody = @{ + receiving_id="" + item=@{ + product_name="测试商品" + actual_quantity=86 + } +} | ConvertTo-Json + +curl -s -X POST "http://localhost:6060/system?method=storage.receiving.addDetail" ` + -H "platform: web" -H "project: wms" ` + -H "Authorization: Bearer $token" ` + -H "Content-Type: application/json" ` + -d $detailBody +``` + +### 4.5 完成收货 + 审核 + +```powershell +# 完成收货 +curl -s -X POST "http://localhost:6060/system?method=storage.receiving.completeReceiving" ` + -H "platform: web" -H "project: wms" ` + -H "Authorization: Bearer $token" ` + -H "Content-Type: application/json" ` + -d "{`"receiving_id`":`"`"}" + +# 审核收货单 +curl -s -X POST "http://localhost:6060/system?method=storage.receiving.reviewReceiving" ` + -H "platform: web" -H "project: wms" ` + -H "Authorization: Bearer $token" ` + -H "Content-Type: application/json" ` + -d "{`"receiving_id`":`"`"}" +``` + +### 4.6 绑定入库单 + 审核 + +```powershell +# 绑定收货单 +curl -s -X POST "http://localhost:6060/system?method=storage.entry.bindReceiving" ` + -H "platform: web" -H "project: wms" ` + -H "Authorization: Bearer $token" ` + -H "Content-Type: application/json" ` + -d "{`"entry_id`":`"`",`"receiving_id`":`"`"}" + +# 审核入库单 +curl -s -X POST "http://localhost:6060/system?method=storage.entry.reviewEntry" ` + -H "platform: web" -H "project: wms" ` + -H "Authorization: Bearer $token" ` + -H "Content-Type: application/json" ` + -d "{`"entry_id`":`"`"}" +``` + +### 4.7 PDA上架 + 提交 + +```powershell +# 添加直入记录(绑定模式) +$addItemBody = @{ + entry_id="" + receiving_detail_id="" + space_id="" + item_code="SKU001" +} | ConvertTo-Json + +curl -s -X POST "http://localhost:6060/system?method=storage.directInbound.addItem" ` + -H "platform: web" -H "project: wms" ` + -H "Authorization: Bearer $token" ` + -H "Content-Type: application/json" ` + -d $addItemBody + +# 提交入库 +curl -s -X POST "http://localhost:6060/system?method=storage.directInbound.commit" ` + -H "platform: web" -H "project: wms" ` + -H "Authorization: Bearer $token" ` + -H "Content-Type: application/json" ` + -d "{`"entry_id`":`"`"}" +``` + +### 4.8 虚拟直入(跳过收货单) + +```powershell +$quickBody = @{ + entry_id="" + items=@( + @{ + item_code="SKU001" + quantity=50 + space_id="" + } + ) +} | ConvertTo-Json + +curl -s -X POST "http://localhost:6060/system?method=storage.entry.quickInbound" ` + -H "platform: web" -H "project: wms" ` + -H "Authorization: Bearer $token" ` + -H "Content-Type: application/json" ` + -d $quickBody +``` + +## 5. 数据库关键表 + +| 表 | 用途 | 关键字段 | +|----|------|----------| +| `wms_entry_order` | 入库单主表 | id, entry_order_code, order_status, sync_status | +| `wms_entry_items` | 入库单明细 | id, entry_id, item_id, item_code, plan_quantity, actual_quantity | +| `wms_receiving` | 收货单主表 | id, receiving_code, status, store_id | +| `wms_receiving_detail` | 收货单明细 | id, receiving_id, product_name, actual_quantity | +| `wms_entry_order_receiving` | 入库单↔收货单主表绑定 | id, entry_id, receiving_id | +| `wms_entry_receiving_binding` | 入库明细↔收货明细绑定 | id, entry_item_id, receiving_detail_id, quantity | +| `wms_inbound_direct_log` | PDA直入记录 | id, entry_id, item_code, quantity, space_id, receiving_detail_id | +| `wms_api_app` | 奇门应用绑定配置 | id, app_key, app_secret, warehouse_id, store_id | +| `wms_operation_log` | 操作日志 | id, target_type, target_id, action, operator, created_at | + +## 6. 状态机速查 + +| 状态 | 含义 | 可执行操作 | +|------|------|------------| +| `CREATED` | 已创建,待绑定/审核 | bindReceiving, reviewEntry, quickInbound, cancel | +| `PENDING` | 已审核,待上架 | addItem, commit, cancel | +| `COMPLETED` | 已完成 | 不可操作 | +| `CANCELLED` | 已取消 | 不可操作 | +| `FAILED` | 同步失败 | 重试或取消 | + +## 7. 常见问题排查 + +### 7.1 找不到入库单 + +- 检查奇门 XML 中 `warehouseCode` 是否匹配 `wms_api_app` 中的 `warehouse_id` +- 检查 `app_key` 是否已在 `wms_api_app` 表中配置 + +### 7.2 reviewEntry 报错"未绑定收货单" + +- CREATED 状态且未调用 `bindReceiving` 时,审核会被拒绝 +- 先调用 `bindReceiving` 绑定收货单 + +### 7.3 addItem 报错"缺少 space_id" + +- 绑定模式下(传了 `receiving_detail_id`)必须同时传 `space_id` +- `space_id` 对应库位表主键 + +### 7.4 commit 后库存未变化 + +- 检查 `qimenEntrySync` 是否返回成功 +- 同步失败时标记为 `FAILED` 状态,库存不会写入 +- 查看 `wms_operation_log` 中的错误信息 + +### 7.5 端口被占用 + +```powershell +# 查找占用进程 +netstat -ano | findstr :6060 +# 强制结束 +taskkill /F /PID +``` + +## 8. 变更历史 + +| 日期 | 版本 | 变更内容 | +|------|------|----------| +| 2026-06-27 | v1.0 | 初始版本,覆盖入库单全流程测试指南 | +## 8. 问题清单与修复基准(来自 issues.txt) + +### 问题 1:缺失收货单直接转入库单的快捷入口 +- **现状**:收货单创建后,必须先手动创建入库单(走奇门或 OpenAPI),再通过 bindReceiving 绑定 +- **修复后应支持**:storage.receiving.createEntryOrder(receiving_id) → 自动创建入库单并绑定主表关系 + +### 问题 2:addItem 状态机校验不完整 +- **2a**:CREATED + 已绑定收货单 → 应拒绝(当前只强制要求传 receiving_detail_id) +- **2b**:PENDING + 已绑定 + 无明细ID → 应拒绝(当前未区分 CREATED/PENDING) +- **2c**:PENDING + 无绑定 → 应拒绝(PENDING 只能走 PDA 上架,必须已绑定收货单) +- **2d**:CREATED 人工导入 → 应允许超过 planQty(当前非绑定模式不允许超量) + +**修复后校验矩阵:** + +| 状态 | 有绑定 | 携带明细ID | 应允许 | 超 planQty | +|------|--------|-----------|--------|-----------| +| CREATED | 否 | 否 | ✅ 人工后台导入 | ✅ 允许 | +| CREATED | 是 | - | ❌ 拒绝 | - | +| PENDING | 否 | - | ❌ 拒绝 | - | +| PENDING | 是 | 否 | ❌ 拒绝 | - | +| PENDING | 是 | 是 | ✅ PDA上架 | ✅ 允许 | + +### 问题 3:状态机定义 +` +CREATING → CREATED → PENDING → COMPLETED + ↑ ↓ ↑ + └── 重试推送 ────────┘ │ + CANCELLED ←────────┘ +` +- CREATED:等待人工绑定和审核,可走人工后台导入(不限制 planQty),可走虚拟直入 +- PENDING:已审核,待上架/上架中,必须已绑定收货单,必须携带 receiving_detail_id +- COMPLETED:已完成,不可操作 + +### 问题 4:entryorderConfirm 增量回传应移除 +- 统一走 qimenEntrySync 全量同步,actualQty = item.count +- 移除 entry_order.js 的 entryorderConfirm 方法 + +### 问题 5:completeEntry 应作废 +- commit 已包含所有实质性工作(写库存、同步奇门、推进 COMPLETED) +- completeEntry 无独立存在意义 + +### 问题 6:入库单取消 +- 6a:取消时调用 qimenEntrySync,orderLines 全部 actualQty=0,通知 ERP 关闭 +- 6b:sync_status=SUCCESS 的入库单不允许取消(已通知 ERP 入库完成) +- 允许取消的状态:sync_status != 'SUCCESS' 且 order_status NOT IN ('COMPLETED','CANCELLED') + +## 9. 完整测试场景 + +### 场景 A:奇门创建 + 收货单 + PDA上架(完整链路) +` +1. qimen.entryorder.create → CREATED +2. storage.receiving.create → 收货单 +3. storage.receiving.addDetail → 收货明细 +4. storage.receiving.completeReceiving → 完成收货 +5. storage.receiving.reviewReceiving → 审核收货单 +6. storage.entry.bindReceiving → 绑定入库单↔收货单 +7. storage.entry.receivingCompare → 对照预览 +8. storage.entry.reviewEntry → CREATED→PENDING +9. storage.directInbound.addItem(receiving_detail_id) → PDA上架+明细绑定 +10. storage.directInbound.commit → 奇门同步+写库存→COMPLETED +` + +### 场景 B:人工后台导入(无收货单) +` +1. qimen.entryorder.create → CREATED +2. storage.directInbound.addItem(无 receiving_detail_id) → 人工导入 +3. storage.directInbound.commit → 奇门同步+写库存→COMPLETED +` + +### 场景 C:虚拟直入 +` +1. qimen.entryorder.create → CREATED +2. storage.entry.quickInbound → 奇门同步+写库存→COMPLETED(一步完成) +` + +### 场景 D:取消入库单 +` +1. 入库单 CREATED/PENDING 且 sync_status != SUCCESS +2. storage.entry.cancel → ①发送 qimenEntrySync(all actualQty=0) → ②更新 order_status=CANCELLED +` + +## 10. 数据库校验检查点 + +修复完成后,以下 SQL 可用于验证各场景正确性: + +\\\sql +-- 验证入库单状态 +SELECT id, entry_order_code, order_status, sync_status, sync_message FROM wms_entry_order WHERE id = ?; + +-- 验证入库明细收货量 +SELECT id, item_code, count, received_quantity, confirm_quantity FROM wms_entry_items WHERE order_id = ?; + +-- 验证主表绑定 +SELECT * FROM wms_entry_order_receiving WHERE entry_order_id = ?; + +-- 验证明细绑定 +SELECT id, entry_item_id, receiving_detail_id, allocated_quantity, status FROM wms_entry_receiving_binding WHERE entry_item_id IN (SELECT id FROM wms_entry_items WHERE order_id = ?); + +-- 验证直入记录 +SELECT id, stock_id, quantity, space_id FROM wms_inbound_direct_log WHERE entry_order_id = ?; + +-- 验证库存写入 +SELECT id, stock_id, batch_no, quantity, receiving_id, production_date, expiry_date FROM wms_storage WHERE entry_order_id = ?; + +-- 验证操作日志 +SELECT id, business_type, business_id, operation_code, message FROM wms_operation_log WHERE business_id = ? AND business_type = 'entry_order' ORDER BY created_at DESC; +\\\ + +## 11. 已知操作码清单 + +| operationCode | 触发接口 | 说明 | +|---------------|---------|------| +| ENTRY_ORDER_CREATE | qimen/OpenAPI entryorder.create | 入库单创建 | +| ENTRY_ORDER_REVIEW | storage.entry.reviewEntry | 审核通过 CREATED→PENDING | +| DIRECT_INBOUND_ADD | storage.directInbound.addItem | 直入记录添加 | +| DIRECT_INBOUND_COMMIT | storage.directInbound.commit | 提交入库 COMPLETED | +| DIRECT_INBOUND_REMOVE | storage.directInbound.removeItem | 移除直入记录 | +| QUICK_INBOUND | storage.entry.quickInbound | 虚拟直入完成 | +| QUICK_INBOUND_FAILED | quickInbound/commit 失败 | 同步失败 | diff --git a/temp_check_prod_migrations.js b/temp_check_prod_migrations.js deleted file mode 100644 index 42cdf9c..0000000 --- a/temp_check_prod_migrations.js +++ /dev/null @@ -1,71 +0,0 @@ -const mysql = require('mysql2/promise'); -const path = require('path'); -const fs = require('fs'); - -function walk(dir) { - const result = []; - const entries = fs.readdirSync(dir, { withFileTypes: true }); - for (const e of entries) { - const full = path.join(dir, e.name); - if (e.isDirectory()) result.push(...walk(full)); - else if (e.name.endsWith('.js')) result.push(e.name); - } - return result; -} - -(async () => { - const files = walk('database/migrations'); - console.log('迁移目录全部 .js 文件:', files.length, '个'); - - try { - const c = await mysql.createConnection({ - host: '112.124.21.102', - port: 3306, - user: 'wms', - password: 'P6j3YTHTpirepYWz', - database: 'wms', - charset: 'utf8mb4', - connectTimeout: 10000, - }); - - // 查迁移相关表 - const [tables] = await c.query( - "SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA='wms' AND (TABLE_NAME LIKE '%sequelize%' OR TABLE_NAME LIKE '%migration%') ORDER BY TABLE_NAME" - ); - console.log('\n=== 迁移相关表 ==='); - if (tables.length === 0) console.log(' 无'); - else tables.forEach(t => console.log(' ' + t.TABLE_NAME)); - - // 尝试查 sequelizemeta - try { - const [rows] = await c.query('SELECT name FROM sequelizemeta ORDER BY name'); - console.log('\nsequelizemeta 表记录数:', rows.length); - rows.forEach(r => console.log(' ' + r.name)); - } catch (e) { - console.log('\nsequelizemeta 表不存在或查询失败:', e.message); - } - - // 尝试查 SequelizeMeta (大写) - try { - const [rows] = await c.query('SELECT name FROM SequelizeMeta ORDER BY name'); - console.log('\nSequelizeMeta 表记录数:', rows.length); - rows.forEach(r => console.log(' ' + r.name)); - } catch (e) { - console.log('SequelizeMeta 表不存在或查询失败:', e.message); - } - - // 表总数 - const [cnt] = await c.query("SELECT COUNT(*) AS cnt FROM information_schema.TABLES WHERE TABLE_SCHEMA='wms'"); - console.log('\n生产数据库表总数:', cnt[0].cnt); - - await c.end(); - - // 对比 - if (tables.length > 0) { - console.log('\n=== 结论 ==='); - console.log('请检查上述迁移记录表,对比迁移目录中', files.length, '个文件即可知道未执行迁移。'); - } - } catch (e) { - console.log('连接错误:', e.code, e.message); - } -})(); diff --git a/temp_storage_entry_old.js b/temp_storage_entry_old.js deleted file mode 100644 index 2bb3f27905dd2edf8c3e191cfff468283e4df638..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 52592 zcmeHQZ)~1db$=LqAiy+Y9cAO@!?bvUd zrg2iifQ+#e*qdyFN_2uRXmmoO9dw(vt`xB$7}_RH6smQkYu8FeQ#J944|M1E9G{$X zpL_1}Jg@ya39PdG?|JV%_uO;O|9kFzUjBJcc2_o^O=J!F*~;d!BiSMP-IKj9`_=4q z`S+o0CY#PbZDhmLaxS|&Z-qV|pzk?)cATIb$^Yu5z7yGD`s&H9%lZmE7^;PMiXhBp z2dOWx*qu$~BTQri`KaRrwME~IK_fez9J7zcT1(&h^BDEJgPs95V0|(hrMUr;g*s|R zpUZK!Ge1U{&C^#S+f4mHpOb|dH3;@S^vOgH7cGl4I+atgL7%M6-br7eEB*3YF|5b&ACR_PrcV=pZKE< zrti&*xF5`#^z;Xp-!s_>`UzUi5&kE#UG(!vC*$j0QoQq-SwU@GQO>`D%hQ&^Mg-x<&5iRjLDPGM@o3j-mA%S*j0l9bvUV zU)~zZ40?zoAZ5$PzrWUK{qAUG^J|g3U^Qp*)hMo-u0>C-U!Z-a7c~dC&#osZXZ1$R zIpfp<>slP8FJI{+#AUs?Mrsi@x6}6t!fTH73?zIa|BNMH)(F3ai$>`0o=Y6llU<+x zf0Fvm({uT+hn^lF4TM=7$|Y_*Z_!Kt7x{dgaH(Fo7zgDv85gki@8#nl>nU_Nov(vk zi%?piBcK(OdSMSw>xuT*K=iTlKAKCSNPHvvPWy(&+m5cjaC-micicFO*2hT?g1&3B zwRe4a`(NGtyX~#Vhj*^p_vB`v+r>&BW)^_o~d@ZJKoo1w2`)b=2a z16>ze4bh{FpV9^z{pNx;IhDm@ix&Oo_Vc@DcI|5SO#R7N@A;n$&CHB7|N2uauS*AL zhM^tob!G|v45iRY;1S||JF^%j%cDoVYqM(!cBmb^cB<)S%=&@H8N!-uBT*X?e=?W5 zdGo(NBjr*nTWg4?s%8^Y0}w1lJSkVJ#nfn#hl8>D9Gy_l_QiC%&d8oft!S=loY)$Q z6#KIT)GDc$ky-lXzqn_}QPOTEw-Z=N=;yiYy)+^`$>X_hQwfvy4e~<8t3liHd0rpc zlG6p6g*pqP*p)3}$7?y9TLiXQ9=G+;Okn+VR$|j-X7G^N>+aM#S?rV&@ITqNNpsn) z#DB+VRN$rDIZqbQmRiFzpP>IR;!X5(`J62fVHx9bCk@{5=+d{5ts#6s z1LbIzc?(gb!&0s<*ZHskmaRTo8 z-#pEupZu{9LyKLwI-Z|0IQzq$enj?od-{%Z3+3^cwT>x2f<1`$%x=EtV;@&a`hJAk zy7!aMWn;aYf|!iGi5G_+YAkGjaPn36X^dAEd3B-}Sj(KEQDZLkH52!UHH=ttORGN8 znsda(ums{G^pQ-$Qyk_YJn6>tDC9o3ak;#~&Vlp|yVB z$-z~Jkh|HFZK1r(4*G6nt7qSR@Zj;Ytu;5m+y2`9<#B_J4Isl<=?UVq@oXz`T$BE8 zWIWF5*^Nj3@ZvriomYcpI30y_LnBzJ3G*|^LUHCxGAn%~Ig(w|$m-1gXQx)}`_IX> zv(Jt^Ir}R|jvRh$;y0RVJ(ZWZ_Z#0`j@=IJNmEzaM; zy9M93=zD-#7UPeYvXI+YChO`RWEKySCYhz*p!EmnTYMDdEvyxf0n989UP)i7mvFI} z6ZLM?OR$`YhzNWq?Lx1zk$cnfS$Djv9`aB`cMD|oy*$mr5nJ3=^$M?w@EBGm)?SF5 z5Sy>GpJsWY=#MZj4bvJ)#>(@ZFPHa^92Be{tl@YrS;+M^i9(F$ST1vY+1n|Wk7ew1 zHfA(!Q5r(nyJ!^7Ba3XPoxr*vkLyJSEQP!mP}E6w1oi5{qcJyN-9s52AbbweY>~m^ z*@7=a=@uUHR*^mYa*tc*7>_oVQ`OEPTmk5vEo3Q>i3a_{mX@AH~S@jB*(znD1LeRp5f`X6)e=xkN^=^y!R4>d^6aqT~n3 z-ZXMb*5|3Q>>YWJP+mn3fy(b7D&sePhP;EBmaV@(^OS}{P9Iv@@5Rvy>*}#Ze(_s| zyh3|Ov`>O;Nga+kb;*WfZdLQEvo5f!<-E-^i#1K?*8vx+b?3={IY!R_f2`oc^+vN8 zrWUu;_W*ex4cZs6Rs@i5B^nK8AELibke-^Sy+GJc_E$!8O&)tJyeC?Ov^)D98fS>U z`SU)KE!i6!C5YIoLT+W0BuMroWK6#$;(_r9V_?0JbjK$84f^_g$TUP-e5t;$Scjf= zndGR4*qiI}S<>pBCkejf3=%9tFVPZfbzQy_vM!LKaE(3R{iUfFhpzkYx1Ohc!(sUC z*BlsXZ#weoe%_;e{a(q54^pQ8GZ*)?f3WlJ(V_Mie|%x=3!i__N7-+EY|n>hdGGYK z(Vk|x2kzw!br-skg&Fz{jt{Mr_M`SwrVnC9>$Ahd#SREOiGz+;JfC}R8aci{=zUX8 zZ}1wT+8pr#@5#Zpnz)I<~fwL_OJ{o7E%`4nLSDPj7x)TDQVZ^4w`d|xOmEu zkALLW^YU4E@cjmaI%sE_x{~vtl(=g3T)*o74=0CkcyaNEqM3w|`?Zl#8 z0|&xmNAy(9qr3;PIe;@numsAjq-Qug%)0Rwg08hBanu5iV4nxslbJknIOawI?5D(S z`zQ{P=wmRS3GAVjS&V_N&LF^sqsDF{*)z^_LA%4}pI>3<@H^7$RGgU?v5S^kv$$te zXTAKj2i@R}*qX>920~xuKJnYaokwYh-6xkL z{;9qB#~VlAG+k9`#k&`)FPz!`>7(uDCk{+cJlZ}z_@j%(DC}(OrTq^K-#B|_|L1qF zZuP7~6!GHF8xH*Z%!UNMMgJA^XB$_fq_qZ~51wAfq9+pfPWK%kxeNWG-U_cU&7Ec3 z7~_Q96AQ~~k~BXmpT&MR_$sC0m`0sp5!)|BW}1IIB0b z;m=uG#Ja+2Qq8MiEYALQl3_vrI0vW@7@~48^m}pqL7JoXh@o+BrDX^~=)+X|P`)Bl zi~CLY5M8&DXCl?Sy)HH3S27oZRvcBY%V{5GD~q^GuVGq4oKENl1_Dblxq<4Gur`WI ziW0&HML$!XZ=+elZ-b2W(KkzqZOwDF1Io6q=o73Rat_t4 z?OJ0LoP|i?W7{fUc=NrBR*AKv*_IIgtM1su?=T$9s^%+#6N_vkon{hn2-Tg$;9)?g!XD@HsFN?~;^r(5Yy( z6cS*-X7LUP>o%O`!#>XLOB@%j9%k7s|2Bk-S%J4TL)`7XC5g8z=SlPro$Bq2#oiJq zQ1lTkM0}1f@H8X?R9;Uu8&=zE7kY|lox;WMFFq%8gf{}P5x)|x%CiOR#X#4>W^grL zIc&h^UK5EqGDWnNcs2fvq_tWCjGv-k+#3D_VhG+3t?I{FI(YdLv}=y}LQi5uJv~>B zCqvju{So)o?Fnx_wOaGJkIH*uCl_Ts)fV&bj8Yu)<6JZ9;_A>=ZP!xzz~a{%Wrlo> z+1%Q&r&+HTYB8X*P|;mytQ6(F=VGmd%fg5oPp$2;+LX1KK2eQ2Ks*-akZ_)6B{Vfh zTQQ%_6P1yNK0=amjH+EE4~=MPwuImKX#zW(6${?Ft&5!C4@ ze~gn~25jK*fj>|I70y{``ijP9N~qR*MdSONA{_II#`o#tYZ}%oLc7q*Pigxhl3ZAA zoRutUevxeXJl0zls;6VOkUl`ofWYRwmFPD+w(P`tHs%(}GODhZJwB^}mIkTM=ybIU z@u?}!;@I(!O^G88A70V_VQ3O#hHF+u&t19Q!+jpSR#i0jqPVI)smQK44`dC>VO5xrbS*DGvRD0 zqFF@RD>GMQSS6pfvLktUzLgpAfa86t*DWhu9uJM@`&ytpJpKWqk*|BKO$cpJ9SCd* zv~pE&6HQeOqj&}bHx#5!^4FDI?_UyIXj@|yd`+xXSkNnyBi5%l4WlW#zuBQ41`6@PK&rYsZY z*@2a(mTKHzOe%?2W%`!B`ConN{#7(||F6ydvHRDWRG^ z#Rq^Rd$&WEH~{-3%U%7{YNxe}#ZfF%58)(h!KdT|+mu{lrQ@0o@FkyS9Uw1sCsk?e z$n%4KTSx|YRkR(dals#~@tB`eI?m&krEvJ+Tq5CTs_sqG!q>N4HH-dB=MPk~$WDP+ z$>K_BrVL|Qy;5vhFH=-^KS0}wCGmD+fKR==KTfV!=laFs3y*p-1b)M6Z6=6_QS>x9 zXbAr=)`P$k)!@*#7Ul;@u20f4Nab+8l92qv1}4X9tg%8Vk@_NzM!BY?)B7g7R}&xZ zJF&)9{loK2RlbATVgC__N(UC{w3W1>R$ORAp(6{W_7w?$FNTEmU>rwbGWwqE? zPl-WMRps$!ygS>IeXspO{|_!cLYe%h_Ig^bIzMlBW5uqAmO*%ztqu4IdbQ4Otk@?X z9^gugv^A8`>+6lU$2P)PcVV>-4?A_Z4Tf*QU|o&dj$^!_(~J5^#!2tm%Iq4s6nph5 zAq=~3t9{>3_;eFz&r1d#p~S@VE%vjzEsVXr>R;wmsR6z?`P9X)wvX;8zr)CC6L^}! z&5i7A>-87Mt3c&*rP% zD#q~^1I@~*H#@MXk=T|fRBh{L(YRVDv_18E$2n4X33@k*l|jip;0{#WSHPL^HM9!x zxgwd3pJgrbjU7cK6!a1e-B}F{dxnkd5jwT5xTUCf;{4aPfA#K#=3mbJ^xih{cPxj% zNGJ;GNKQI#X(bfBLMg=)%LVFrrhKg+4_ajA!_|d{jiVfoR3A!xntfk$X4t zf*9p$q2A_8)@BP)2DeAdCv-NjR&JCyBd#GA8sc|dDUv>EK9Cl5rHU)7ij~~4oC{p} ztutg!DXXrMKKNaqV}x?y2?gdWUV(bqWjp#(xJmk_WD=hrDB*>rjOmS49K(-5#RB^N zk#7@$VOi9Q8Ct){i(1jfi(DlV_|fF5Q>$m+d*_|gkFp+{~Eu{2IGvS*=j z=_JL`xHDjmJOzDfd-5naDY-7sa9~%HvrJ*MfTxIlaS8w#AB@(U{WeJwWSrmS^1i^A z2-gyKt|4cOn#N7kA9Lon7MvhBxN8odSj=Qj;Z1KL6}^~tsQsr+y}h@SH+jH|6d(TT zjAm`V^m4_t*k=V7;SD$AhEI1;P7~Q+Io}3uwzs<@kKaSwGC;T6eUScQPPskX8~i^| z_c1!U8cH$um@0RR_LW@1bXWRmsULx$2e-7E;ysONIWhmr+;fgR%D<|wE zp4S{L&M@*j7($t_^2?SOQnH0G;89aq18vK(os1~Edg+r}(h_pbxL8W4{fX%iYadvR zP^x{;#%k$KqjJSVPcSyJ+wO1f`0&eKE)_V*>MSMhMt^)MC93&dZjbNHHEYN{sqFWa zp5qpzZk#1-A0JA6~z)YV(c70sHzjD`M^*LUQ6#K(vRtR-saz9}A zw8xE!*_6dUPfy-A`sm2N9eSZPN%`RvHQ>b_T&x%^ayw>^FXSqD<#leH%k-h5k8+8x z6JmH(J^ZnXtAnv^#KQk$W_ET~0@YeCNB%;uHkPic*>x^iinn?hfTGXE8;mJeziwHz zbiF>}t3flzX;c&X+Wwf(5*Rmz;>`j2h0is%sMZl0kK@?X9ID$_&!HNI&Vk>28Ph(50cn8t zm76z0x|g@@6yM@l)wm*3JiMsIQPYiEBA_u~J3>s$S_&`vlHm1}%GK&Iq-FUSOh@oJ zZfQ!*A=RoJc6|E4r%<|Gr|@OYA$4N-(yj`=p2`aKCvMN#M)9ntzpO@J+2b2$fKw0k zLVjpd{(g(w-2QS0mPqbWdwX`@!?%+gPP*--sW+y3x%$la(7>zBT%#Q=NSghmd}Xbc z4Lv;0?WmUa^s9G=4_3EYJNwyj;9ZvKwo=ncHkdPn%c;*2uTFWo%%`j4zgS3B?PCj3 z^yI7;SDi7H_a|RFb^i4F@oyae_VC{J=eBMCNbmUu?2yg#eXukK( z2Zj$dUpR*w13{blZ1siDHJj55R4c*%H?k+%KRfpu&97W|s4+x7HJ*l0ZqD<|$N=;E z=a*Y&gbE&<>jwvhZ(&9zlCj#b=sjqyA>VzXJ1B7r^bU0hw}E_0gbqI%*<_(Czt>*t zqV#UR>D=dp+`^B;t#G)fOlnv+(_esk(&SyY@SM~c6#RKGQFH;%kC^?cxM1e0GLnvOC6D!5Z#x|M-RIKKmGtqJvFsP|m zFFj@zJ}o;(BXko_s?*FW)`IJucvZ@>s#bqs+)#%ICQ|DRnLUwbv1KnHMLkG>a0qKm z^niq7w;=ok+50&EBP-;O;IDx6DSyAWodw`O> z?OqudplztB*w@naZ|(TC{%^J4`plg(-#hcgJMX{lAIvm$j@qwY$iRzYO2-F$4~ z<}+_U^6;mwIrkrXZ+-bolaIT3r{XG<%Vlg^#sevhPsH+>2i#F-HMFh>_;iwJt55jN z&2i4g_D|u#mMgWQMVkSR>x8RPqpEDDT2yfmFsZ{uXjhk$(6%l&p>2wzpighRA9CGp zJ~{j5i;uVWj66u(g!fB(Q4U}gxr(1z*~XI;wQx5q@>~4Al2ohWYQ~&fMNy%oe-a89 zvR)HwBJW8GccoMK`EMY%lnF8RDi64tp6|;aYd$=_j&6{C%QL8(`TL8XJu0;|RTT-- z=Hv@>D%)-8{qu=UCL8O&Bdn~#Uf=7>Z}}FuPfvdAF5K%6I^rCodZ?%!liR1cnx4Ht zR0DYaDQ=P3LZ9Kpl(!3LHADR>`;a@X)*4A_TAj00laFi|7QEX z!@u_&^U=53U;6N;JA9A5czsuA#SJQ+#wqeeCIV-vaV|+QhM!R#dDZ7~D;t^-fHZlw zQt;>_DR~|}q>_LG0F!EC4 z9mPRtvT~IGz!hIgftY6Y$?`qa6n%-Q(Ex4wXO$&wmqJ zd^xLcfeXHb9v(G9{bFGO9{wLLuA6fAruaMF68_oi^FL@A?~6+abt+9Je7K2MLQ7A&SXB;s!32;`VRecWp# zmAb`QrdtXQJ=s3eKAvR5f8n$07!A8+I5&peJ$B|XB1ZEx4D&AT$(bV#sNWAY*sy$f zyN9fCI3urx&cvGqJU~=K+(FpfTLRZ_m4@x_=vjT_+XTCZ=*eJp9SbPZiCozcJKOX0 z=UC;}+Lh~M*V0;=ZtPuJty#8vX*HN=3VjCODwe@mpR4y3`h;E{WvKnPbKk%7mo=gU z-KC0h6a6ig>vF}FcHOahp5I_Kv+Dn}iea|d;6XVX^xYKkW98ier>_$|F6o|U^YD|02HODikF zrCZ74(3_n?x>oyC;&JfqUfDgYRdyKOxwXY*JE>l@{^-behBr?CL;Iz%|2p(|d;Q?O zyL!+6WawXyyz0Jx-zm`{TQbk@!sw!9;jt`73anQZ(i8u2UCIn;6P&YDJ1p~;Y>Y%F z1LQT^te}P7Nh~E$;KkYZh+?*>xX_ap_Dv8Y;=4Eli=E%w`gcqBC}ZlxUXLB=YW5_V zD_K)_+mnQSiYc=^fAAlhe|K?V;+NSU6d!OPzYQIC1LAHM(GTpQt<*k))fia4SNy^5 zWVbC{my?xx#UF&F!q+SQpin}77yXw`JoPK>4+3}bJ*?&2L^(9*L)Cg|pQV{+ujCD+ zT8Sxjh$93AH@y`zqwvVWPvFJt({x@?+7xq|@;sGK)6e4^9^XV9&eE^Mf-XSz09u+W zvC7b7C(|M0Hcc-AtjHF*>x@OXdTj!?eW4EofGl+X@PVb$Qlmqklx>qSf! ztGfHnfF*oT9w(t?(L(Su%N=+klq=F*vn>3kz4GjS9Es}ueA&a;SAy2<=Ir+wTQ9XQpjnE7 zye<}A6;E6Gbh6{Yao@_ssi_^0={URi&r3!N_ii#9f`0aQ1Hf%N3hW zlf}Uvsh*A+r@Nhy)3R?;)C!@veW$0XB)??&TkORe(i`RYAT!*pH_29yC2}Q}sLUqE zx~Cd`*hfa`$@aD%*!JM$V;A0d^x2E>Yb~u{IqF-FqP>o_Jmx4-Lb&TFK7RE);M=1$ z`$qAp2RnwBLzI!Ur=79ysfW0Vw;n#Nb9TbRhb^Vm;wk~1RcMF!2=B`p;geiL zykWd5+lw~%5?!%W-yOH%9J>qIVmT3vJ-*Klf26hT0!|I5Zpp#eV%L`AzZdE3(KkGa z;f#7`~Wd@Xm~ORW*d=iZJ<8m`n*P7+t(46uyp-_&I_ zK>cyB3sj`0U76Uw;}giZ z=mDRKC2h5)a>C*{T#`jw;J7~3dTWoKHk-gip-UyOmVC_)B%Oyub?mPi&fgNR!}My z?Q4~-vo@}iIFqBc zIZSAsgO}F)7w5DVVl+7oe>r1HPjZ;Dp=FpND+8(SW_%@DerS;cT_0DaccYy4G>=$95&2qXIN2sRTLfVDjreZVqom6-gbr|xVaaEUaK?>{gJ*|~q z*R!pc_CGNETl@a^Q%~<@TX%WRf7x~N<-BADcLi?F2|^ z1&B&zyb^+s{_#OAA+@wZ;fF`mj|zc6NR22;F;Y`dLHzLDa_@}S`>>5us-}Qe`xtu@ zfHMbeS+JC5Pc9hmhGU>{l^P?Rq_1IjfII{TdJy0)kUtg^%PZwC=;|AD^Anj5hCLOG zMgeOvG6lBXaLO#cB5`QUVJ1a-u8EROj z(vH-|Mz*>fxma*$UU8*NrJBI|n!R!x4y_XD+ql2FcJNtcRqKn@gre`)=>y02r@vKw zl+^2iQ`(NywTeSqj+~r(p!%S9cX=W+#1J%NGMG7=IWR$`e(~~XkbasSdC7>VXROzo z@jJAB@vTaLzCM0r_TK8N?;eM^R)cHdeX11nK%|w(k=a#E4DKog=}$Lm0(u?HR3hI5 zcFGr&qs2Xm^^~W8S+i!tRsGF>d8%h@J%x7rU#kfmiGfBwML;wUhhRd~p3x+k2dokC z1nb!;^QA@x1rtwlzyf3t=FY{Q<{|3>G5QMdmWN&$7P--fGY-GvVP;+wB2mbT&_4+g zJrB=QjES6k&L&&CkM+a2DKZW5>0?D`L9X>Pp5Z+X2+43w5|OM;Gaofqsa^`prPN^&7{b zwOyZ=t`3N3g>j23gaArn=!K3q>V^+0-&+pR_0)$UhuZ6nWsj-iRnB>Hzb7GsF{UOG zj4BZynItbmHj$|nXi30V6;6R1Q@3lLLR`YC(GT?0%|f_o!_9nghN9Ip@Kq+`V8c%@ z9qjRp()Wi?ru3O{A2;iv0QthYPcpkf+UuCYH1f!vTV%A38ZwvL(>e9`_KZv# zBlSp-Nr*7#ZjywWS>Mk%g?fZaZQy{BSd|vB%Yy~vdKzLE$un?AZA-8fJwqOCI|j$` z6+KR7OrAUU#u1ZD{b#_w%IrE#Hk_cQ*8JiKoONrvy$$o)8ArqjR}>Mva_nQI0CPp{ zvgg~Xa9r^^?KIpbrWtucjJvVG9<8-bjQnEMMit<`NddGGDZZ!DXJxjxIc5Bc{^Ge< z*Y&ZUx>Wy&&IGqY8D*H01WZ7E!dfsZV;WdD4sCi|*OO1#IMGfC^_{5HZ<;d9L zC-fCxP53(cNM+m7Ju|pF-z|6w=ak?5Zyx4*e6DJEZO7%C+j+FNv6%|vbJ6GCT4&uY zhoMsK)rQFASp}b^{^-IXv;EJhJo$F{-&0@aeY~+k{@1Il{jBbMtqo=tBkzTDKGd~YMMwHx { assert.ok(skipLog, '应有订单 53 的日志'); assert.ok(skipLog.extras.message.includes('跳过'), `跳过订单应含"跳过",实际: ${skipLog.extras.message}`); }); + + // ============================================================ + // 场景 5:space_id 无效时内存计数器回退验证 + // 当 storageRow.space_id 为 0 时,代码应: + // 1) 回退 allocatedQuantityForOrder(不应计入已分配量) + // 2) 回退 allocatedQuantityForItem + // 3) 回退 remainingQuantity(未分配成功的应加回) + // 4) 回退 storageAllocationMap + // 5) 调用 unlockQuantity 释放数据库锁 + // 核心 BUG:当前代码没有回退 allocatedQuantityForOrder/allocatedQuantityForItem/remainingQuantity + // ============================================================ + it('should rollback memory counters when storage space_id is invalid (zero)', async () => { + const { service, captures, storageRows, stockRows } = createHarness({ + orders: [ + { id: 601, warehouse_id: 100000, storage_status: 'none', order_flag: '', step: 2 }, + ], + orderItems: [ + { id: 6011, order_id: 601, stock_id: 901, plan_qty: 10, order_line_no: '1' }, + ], + stockRows: [ + { id: 901, item_code: 'SKU-901', item_name: '测试商品901', warehouse_id: 100000, deleted_at: null, is_valid: 'Y', locked_quantity: 0 }, + ], + storageRows: [ + // 库存A:有库存但 space_id = 0 → 无效,分配时应该回退 + { + id: 9001, + warehouse_id: 100000, + stock_id: 901, + is_enabled: 1, + delete_at: null, + available_quantity: 5, + quantity: 5, + locked_quantity: 0, + production_date: null, + inbound_time: '2026-06-20 08:00:00', + space_id: 0, // ← 无效 space_id,触发回退逻辑 + space: null, + }, + // 库存B:有效库存,space_id 有效 + { + id: 9002, + warehouse_id: 100000, + stock_id: 901, + is_enabled: 1, + delete_at: null, + available_quantity: 10, + quantity: 10, + locked_quantity: 0, + production_date: null, + inbound_time: '2026-06-20 09:00:00', + space_id: 50, + space: { + id: 50, + space_code: 'VALID-01', + custom_name: '有效库位', + is_preferred_pick: false, + locationType: { id: 1, allow_allocation: 1, is_active: 1 }, + }, + }, + ], + policies: { + 901: { policyConfig: { storage_separation: 1 } }, + }, + }); + + const result = await service.allocateStorage({ + allow_storage_location: true, + order_ids: [ 601 ], + }); + + // ============================================================= + // 核心断言:验证内存计数器回退 + // ============================================================= + // + // 订单需要 qty=10 + // 库存A: available=5, space_id=0 → lockQuantity 扣 5 → + // 空间无效 → unlockQuantity 释放 5,回退 remainingQuantity(+5) + // 库存B: available=10, space_id=50 → Math.min(remainingQuantity=10, 10)=10 + // → lockQuantity 扣 10 → remainingQuantity=0 + // + // 如果回退正确:库存B 10个全部满足 → storage_status = fin,allocated_quantity = 10 + // 如果回退不正确(BUG):库存B只锁5个 → storage_status = error,allocated_quantity = 5 + + const orderResult = result.data.orders.find(item => item.order_id === 601); + assert.ok(orderResult, '返回结果应包含订单601'); + + assert.equal( + orderResult.storage_status, + 'fin', + '空间无效库存被回退后,有效库存B应满足全部10个需求,storage_status 应为 fin,' + + `实际 storage_status=${orderResult.storage_status}` + ); + + assert.equal( + orderResult.allocated_quantity, + 10, + 'allocated_quantity 应为 10(库存B全部满足),' + + `实际 allocated_quantity=${orderResult.allocated_quantity}` + ); + + // 2) 验证 unlockQuantity 被调用(数据库锁释放) + const spaceIdInvalidUnlock = captures.storageUnlocks.find( + item => item.storageId === 9001 + ); + assert.ok(spaceIdInvalidUnlock, 'space_id=0 的库存应调用 unlockQuantity 释放锁'); + assert.equal(spaceIdInvalidUnlock.quantity, 5, '应释放 5 个锁定数量'); + + // 3) 验证有效库存被正确锁定(应为 10 个,因为库存B有10个满足全部需求) + const validLock = captures.storageLocks.find( + item => item.storageId === 9002 + ); + assert.ok(validLock, '有效库存B应被锁定'); + assert.equal(validLock.quantity, 10, '应从有效库存B锁定 10 个(满足全部需求)'); + + // 4) 验证 storageAllocationMap — 无效库存不应在映射中 + // 因为回退后 newStorageQty=0,会执行 delete + assert.equal( + storageRows.find(r => r.id === 9001).locked_quantity, + 0, + '无效库存的 locked_quantity 应回退到 0' + ); + + // 5) 验证 picking rows — 只有有效库存的记录 + assert.ok(Array.isArray(captures.pickingRows), '应有 picking 记录'); + assert.equal(captures.pickingRows.length, 1, '应只有 1 条 picking 记录(有效库存)'); + assert.equal(captures.pickingRows[0].storage_id, 9002, 'picking 应为有效库存B'); + assert.equal(captures.pickingRows[0].quantity, 10, 'picking 数量应为 10'); + + // 6) 验证 stock_warehouse locked_quantity + const matchedStock = stockRows.find(r => r.id === 901); + assert.ok(matchedStock, '应有对应 stock 记录'); + }); + + // ============================================================ + // 场景 6:space_id 无效时,如果有足够的其他有效库存满足需求,订单应为 fin + // ============================================================ + it('should correctly mark order as fin when other valid storages satisfy demand despite invalid space_id', async () => { + const { service, captures, storageRows } = createHarness({ + orders: [ + { id: 602, warehouse_id: 100000, storage_status: 'none', order_flag: '', step: 2 }, + ], + orderItems: [ + { id: 6021, order_id: 602, stock_id: 902, plan_qty: 5, order_line_no: '1' }, + ], + stockRows: [ + { id: 902, item_code: 'SKU-902', item_name: '测试商品902', warehouse_id: 100000, deleted_at: null, is_valid: 'Y', locked_quantity: 0 }, + ], + storageRows: [ + // 库存A:space_id 无效 + { + id: 9101, + warehouse_id: 100000, + stock_id: 902, + is_enabled: 1, + delete_at: null, + available_quantity: 3, + quantity: 3, + locked_quantity: 0, + production_date: null, + inbound_time: '2026-06-20 08:00:00', + space_id: 0, + space: null, + }, + // 库存B:有效库存,足够满足全部需求 + { + id: 9102, + warehouse_id: 100000, + stock_id: 902, + is_enabled: 1, + delete_at: null, + available_quantity: 10, + quantity: 10, + locked_quantity: 0, + production_date: null, + inbound_time: '2026-06-20 09:00:00', + space_id: 60, + space: { + id: 60, + space_code: 'VALID-02', + custom_name: '有效库位2', + is_preferred_pick: false, + locationType: { id: 1, allow_allocation: 1, is_active: 1 }, + }, + }, + ], + policies: { + 902: { policyConfig: { storage_separation: 1 } }, + }, + }); + + const result = await service.allocateStorage({ + allow_storage_location: true, + order_ids: [ 602 ], + }); + + const orderResult = result.data.orders.find(item => item.order_id === 602); + assert.ok(orderResult, '返回结果应包含订单602'); + + // 订单需要5个,库存A无效(已回退),库存B可满足5个 + // 如果 remainingQuantity 正确回退:5-3=2 → 回退+3 → 5 → 再扣5 → 0 → fin + // 如果 remainingQuantity 未回退:5-3=2 → 再扣2 → 0 → fin(碰巧也能正确) + // 所以这个场景两个行为都可能导致 fin,关键验证 unlockedQuantity 被调用 + assert.equal(orderResult.storage_status, 'fin', '应标记为 fin'); + assert.equal(orderResult.status, 'success', '应为 success'); + + // 验证 unlockQuantity 确实被调用 + const spaceIdInvalidUnlock = captures.storageUnlocks.find( + item => item.storageId === 9101 + ); + assert.ok(spaceIdInvalidUnlock, 'space_id=0 的库存应调用 unlockQuantity'); + assert.equal(spaceIdInvalidUnlock.quantity, 3, '应释放 3 个锁定'); + + // 验证有效库存的 locked_quantity + assert.equal(storageRows.find(r => r.id === 9101).locked_quantity, 0, '无效库存 locked_quantity 应回退到 0'); + assert.equal(storageRows.find(r => r.id === 9102).locked_quantity, 5, '有效库存 locked_quantity 应为 5'); + + // 验证 picking rows + assert.equal(captures.pickingRows.length, 1, '应只有 1 条 picking'); + assert.equal(captures.pickingRows[0].storage_id, 9102, 'picking 应为有效库存'); + assert.equal(captures.pickingRows[0].quantity, 5, 'picking 数量应为 5'); + }); }); From e73d6f0fb2a558fb8b118e6ca85dd259536a4ca1 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Wed, 1 Jul 2026 14:02:35 +0800 Subject: [PATCH 078/550] 1 --- prompts/官网生成提示词.md | 187 -------------------------------------- 1 file changed, 187 deletions(-) delete mode 100644 prompts/官网生成提示词.md diff --git a/prompts/官网生成提示词.md b/prompts/官网生成提示词.md deleted file mode 100644 index 39c2a45..0000000 --- a/prompts/官网生成提示词.md +++ /dev/null @@ -1,187 +0,0 @@ -# 官网生成提示词 — 奇门WMS(qimen-wms) - -## 项目背景 - -你将为以下开源项目生成一个**产品官网**(Landing Page / 产品介绍页)。请根据下方的项目描述,产出一份完整的提示词,用于交给 AI 或前端开发者生成官网 HTML 页面。 - ---- - -## 项目描述 - -### 产品名称 - -**奇门WMS(qimen-wms)** - -### 一句话简介 - -基于 Egg.js 的仓储管理系统(WMS),支持多快递平台对接、订单全生命周期管理、精细化库位管控与开放 API,适合中小型电商与仓储企业二次开发。 - -### 目标用户 - -- 中小型电商企业 -- 三方仓储服务商 -- 需要自建 WMS 的技术团队 -- 计划对接淘宝/天猫/拼多多/抖音/快手等平台的商家 - -### 官网定位 - -技术型产品官网,兼顾**品牌感**与**专业性**,面向企业决策者与开发者双重视角。整体风格简洁、现代、可信赖。 - ---- - -## 核心功能模块(请在官网中逐一展示) - -### 1. 订单全生命周期管理 -- **M1 待审核 → M2 待处理 → M3 异常 → M4 配送中 → M5 配送异常 → M6 归档** -- 完善的状态机驱动订单流转:同步、打印、拣货、打包、验货、出库、拦截等环节独立状态追踪 -- 支持审核、驳回、取消、拦截、异常处理 -- 订单动态分表设计,按仓库维度物理隔离,冷热数据分离 - -### 2. 多平台、多接口无缝对接 -- **奇门标准接口(qimen)**:严格遵循阿里巴巴奇门协议,支持出库单、入库单、退货单、库存查询、商品同步等标准接口 -- **OpenAPI**:独立的开放 API 链路,支持第三方系统集成 -- **多快递平台**:对接拼多多、淘宝/天猫、快手、抖音、小红书等主流电商,支持电子面单 -- **内部网关**:内网系统间调用的统一入口 - -### 3. 精细化库存管理 -- 仓库库存管理(正品、残次、冻结等) -- 商品条码管理、批号/批次追踪 -- 库存变动流水、库存预警 -- 多货主、多仓库库存独立核算 - -### 4. 库位管理(库区 / 货架 / 库位) -- 支持 库区 → 货架 → 库位 三级精细化管理 -- 库位类型:存储位、拣货位、暂存区、不良品区等 -- 自动计算拣货路径与拣货优先级 -- 库位唯一码/条码管理 -- 移库、补货、分配验证 - -### 5. 入库管理 -- ASN(预到货通知单)管理 -- 收货作业:明细录入 → 商品绑定 → 质检 → 上架 -- 支持直入、退货入库、协同收货 -- 收货单维度统计与完成确认 - -### 6. 出库与拣货 -- 订单分配、波次策略匹配 -- 拣货任务生成与执行 -- 拣货车(Pick Cart)模式 -- 复核、打包、称重、出库确认 -- 出库后配送状态追踪 - -### 7. 打印管理 -- 电子面单一键打印 -- 拣货单、发货单、装箱单等模板 -- 打印台管理、打印任务分发 -- 支持菜鸟、拼多多、京东、抖音、快手、小红书等平台打印模板 - -### 8. 系统管理与权限 -- 用户注册、登录、角色切换 -- 多平台角色上下文管理(Web / PDA / App / 微信 / 小程序) -- 细粒度权限控制(角色→菜单→接口级别) -- 操作日志留痕 - -### 9. 数据仪表盘 -- 实时统计:待处理订单、今日新增、昨日新增 -- 出库趋势、快递比例、平台分布 -- 未分配/未打印/未拣货等运营数据一目了然 - -### 10. 辅助能力 -- **Excel 服务**:灵活生成/解析单 sheet 或多 sheet 的 Excel 文件(支持 Buffer / 文件 / HTTP 下载) -- **IM 集成**:企业微信/钉钉等即时消息通知 -- **文件管理**:腾讯云 COS 文件上传,图片、文档、APK 等统一管理 -- **国际化(i18n)**:多语言键值管理与自动翻译 - ---- - -## 技术栈(官网技术特性板块展示) - -| 层级 | 技术 | -|------|------| -| 框架 | Egg.js 3.x | -| 数据库 | MySQL(Sequelize ORM + mysql2) | -| 缓存 | Redis(多 DB 隔离:缓存/打印) | -| 认证 | JWT | -| 接口协议 | REST / XML-RPC(奇门)/ OpenAPI | -| 模板 | EJS | -| 对象存储 | 腾讯云 COS、七牛云 | -| 物流接口 | SOAP | -| 数据处理 | ExcelJS、Fast XML Parser | -| 运行环境 | Node.js >= 18 | -| 部署 | 自有发布脚本 + 版本管理 + 回退机制 | -| 测试 | Egg Mock + ESLint | - ---- - -## 官网页面结构与内容要求 - -### 整体风格 -- 现代简约、科技感、**蓝色系为主色调**(#1a73e8 或类似专业蓝) -- 大屏宽幅设计,滚动式单页(One Page) -- 响应式适配(桌面 + 平板 + 手机) -- 中文字体优先(系统原生字体或思源黑体) - -### 页面区块建议 - -#### 1️⃣ 英雄区(Hero Section) -- 产品名称 + 一句话价值主张 -- 背景可配合仓储/物流插画或抽象网格动效 -- 两个 CTA 按钮:「在线体验 Demo」「查看技术文档」 - -#### 2️⃣ 产品定位区 -- "专为中小型电商与仓储企业打造的轻量级 WMS" -- 2~3 个核心卖点(如:奇门标准对接、订单全生命周期、开放架构) - -#### 3️⃣ 核心功能展示区(建议 4~6 个卡片) -- 每个功能模块:icon + 标题 + 一句话说明 -- 点击可展开详细功能列表 -- 模块建议:订单管理、库存管理、库位管理、多平台对接、打印管理、系统权限 - -#### 4️⃣ 技术架构图区 -- 展示前端 → 入口路由(/system / /qimen / /openapi)→ Service 层 → Model/DB/Redis 的分层架构 -- 可用文字描述配合简洁示意图 - -#### 5️⃣ 接口与集成区 -- 奇门接口列表概览(出库/入库/退货/库存/商品同步) -- OpenAPI 与内部网关说明 -- 已对接平台徽标(淘宝、拼多多、抖音、快手、京东、小红书等) - -#### 6️⃣ 适用场景区 -- 电商仓配一体:订单从平台推送 → WMS 处理 → 快递发出 -- 三方仓储服务:多货主、多仓库独立运营 -- 企业自建 WMS:二次开发、私有化部署 - -#### 7️⃣ 快速开始区 -```bash -# 克隆项目 -git clone - -# 安装依赖 -npm install - -# 启动开发服务(默认端口 6060) -npm run dev -``` - -#### 8️⃣ 页脚(Footer) -- GitHub 仓库链接 -- 开源协议(MIT) -- 作者信息 -- 项目版本号 - ---- - -## 编写要求 - -- 提示词需包含足够的产品细节,让接收方能直接生成完整的官网页面 -- 页面用纯 HTML + CSS + JavaScript(vanilla),无需框架依赖 -- 中文字体、中文内容、中文官网 -- 注重 SEO 基础(meta 标签、语义化 HTML) -- 包含 favicon 占位 -- 页面加载动画建议使用 CSS 过渡/动画,避免大量 JS 动效库 - ---- - -## 输出物 - -将以上提示词保存后,将其提交给 AI 代码生成工具或前端开发者,即可生成一个完整的**奇门WMS** 产品官网 HTML 文件。 From 300c84c9901843d6adf240090edff76b05597046 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Thu, 2 Jul 2026 22:08:38 +0800 Subject: [PATCH 079/550] 1 --- ...warehouse-rack-spaces-TB-20260428173606.xlsx | Bin 18240 -> 0 bytes ...warehouse-rack-spaces-TB-20260428174354.xlsx | Bin 18250 -> 0 bytes ...warehouse-rack-spaces-WH-20260428171657.xlsx | Bin 53474 -> 0 bytes ...warehouse-rack-spaces-WH-20260428172850.xlsx | Bin 53474 -> 0 bytes ...warehouse-rack-spaces-WH-20260428172924.xlsx | Bin 53474 -> 0 bytes ...warehouse-rack-spaces-WH-20260428173158.xlsx | Bin 53474 -> 0 bytes ...warehouse-rack-spaces-WH-20260428173431.xlsx | Bin 53474 -> 0 bytes ...warehouse-rack-spaces-WH-20260428173540.xlsx | Bin 53474 -> 0 bytes ...warehouse-rack-spaces-WH-20260428174607.xlsx | Bin 53332 -> 0 bytes ...warehouse-rack-spaces-WH-20260428174609.xlsx | Bin 53332 -> 0 bytes ...warehouse-rack-spaces-WH-20260428174640.xlsx | Bin 53332 -> 0 bytes ...ces-WH-E01-20260428175459-1777370099464.xlsx | Bin 12632 -> 0 bytes ...ces-WH-E01-20260428175504-1777370104248.xlsx | Bin 12632 -> 0 bytes ...ces-WH-E01-20260428175506-1777370106125.xlsx | Bin 12632 -> 0 bytes ...ces-WH-E01-20260429010658-1777396018375.xlsx | Bin 12632 -> 0 bytes ...ces-WH-E01-20260429010718-1777396038210.xlsx | Bin 12632 -> 0 bytes ...ces-WH-E01-20260429011359-1777396439929.xlsx | Bin 12632 -> 0 bytes ...ces-WH-E01-20260429011416-1777396456342.xlsx | Bin 12632 -> 0 bytes 18 files changed, 0 insertions(+), 0 deletions(-) delete mode 100644 app/public/exports/warehouse/warehouse-rack-spaces-TB-20260428173606.xlsx delete mode 100644 app/public/exports/warehouse/warehouse-rack-spaces-TB-20260428174354.xlsx delete mode 100644 app/public/exports/warehouse/warehouse-rack-spaces-WH-20260428171657.xlsx delete mode 100644 app/public/exports/warehouse/warehouse-rack-spaces-WH-20260428172850.xlsx delete mode 100644 app/public/exports/warehouse/warehouse-rack-spaces-WH-20260428172924.xlsx delete mode 100644 app/public/exports/warehouse/warehouse-rack-spaces-WH-20260428173158.xlsx delete mode 100644 app/public/exports/warehouse/warehouse-rack-spaces-WH-20260428173431.xlsx delete mode 100644 app/public/exports/warehouse/warehouse-rack-spaces-WH-20260428173540.xlsx delete mode 100644 app/public/exports/warehouse/warehouse-rack-spaces-WH-20260428174607.xlsx delete mode 100644 app/public/exports/warehouse/warehouse-rack-spaces-WH-20260428174609.xlsx delete mode 100644 app/public/exports/warehouse/warehouse-rack-spaces-WH-20260428174640.xlsx delete mode 100644 app/public/exports/warehouse/warehouse-rack-spaces-WH-E01-20260428175459-1777370099464.xlsx delete mode 100644 app/public/exports/warehouse/warehouse-rack-spaces-WH-E01-20260428175504-1777370104248.xlsx delete mode 100644 app/public/exports/warehouse/warehouse-rack-spaces-WH-E01-20260428175506-1777370106125.xlsx delete mode 100644 app/public/exports/warehouse/warehouse-rack-spaces-WH-E01-20260429010658-1777396018375.xlsx delete mode 100644 app/public/exports/warehouse/warehouse-rack-spaces-WH-E01-20260429010718-1777396038210.xlsx delete mode 100644 app/public/exports/warehouse/warehouse-rack-spaces-WH-E01-20260429011359-1777396439929.xlsx delete mode 100644 app/public/exports/warehouse/warehouse-rack-spaces-WH-E01-20260429011416-1777396456342.xlsx diff --git a/app/public/exports/warehouse/warehouse-rack-spaces-TB-20260428173606.xlsx b/app/public/exports/warehouse/warehouse-rack-spaces-TB-20260428173606.xlsx deleted file mode 100644 index 19e021438a4ecfdf93b29643ac3e9457a1c30490..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 18240 zcmeI41yodB_wZ3l1OXN4uuza5T0le$N5wh~ zX$F{??_2@vdEWSc-~Wwot!L)S!XNwWz0W@9?0x30xkphJ7w;er4$c9bhjP&x&-yBe zRQKWFe8t1TISQz{q`8?5+{{M%mZJsST9ebk)Z}gGb+amN@<;1pSH?JGNHlNVzETyR z+d!GRg45w}iJiW0DZIST{s_zKbH`un9A%3TTyTzkPot3UFWpHkB@*@Yh5!XoZ#%0g z)w_-8^5npiFAv=Du%xukk~|VJVkSD|nCKP7F&-b#CN3=v_dldKA*z;si<6HWCBUBO zV?{(9x?Vl}kUhrVNS{`n?1o>8N@e}~F?d7Zy2O6kBgkc~?rf`lgLImg#)>r5SABvR z575}#(Z0@0*+=XpDs99zxzDG}K31;vUW1S!Ti5s{k!+PK$M_Dy*Pak>C zrhKTtU<}tYo|Z@8%xq`cK2t*Uw!B=n`c*+vtCa=hVU+7A#>v&IIhjz((lE$OY^^yr zP($+K>S0_azbL|uIoIJ3O>OCMjPZj*H=9jElX5$mM0r*YZ3T|S}wI{PPT1#=#z0=@tviosx zh`-BlLXvNTE9I-XNiHt9Tp8PnG?O~;GO74@;=mcc3l*o$=<@s%-anjQcoKAx#NU`O z!1BwaVZ&^bsQ-+=(i%Mp`x{yc{Dx+q=86W4u_f6#VgjF2gfNRllBkKhXt`4|smRhm z)nig02%Mg6ys*s|yB^LKKvA#IV0?+S<>T~YyNZC7*Xav3o5%+fUa9%b7ki7CU!i&0 z`Ay8!&8MHu>Bb*7RNJm+F_2?;;^FvlA=+Dc;^jHT)=AAfUB%mCDX~(mFJI(G8y&ux zDnHVoR&Gn*r%5!~;wO8l0Q-(U@{#8$dsQO+ZCLwR!B!WXy@>oVYPcXG4kq72_D2Dt z9f3cKtk>zRJ5XfbfymPSEM{+Rbzjfi{64f2_5yvcnw$Lc0{URqx|*Gu4C^y%Ru2vJ zbzHC9d^rSB0-2hW`D{%AidNY6LPVC8!H*>zD?i^jz(GBDC>*RMRDTE0%#{z|yvBl1;~ zmOYCy9Cf;*A9sdWAuH!#d-I*+k*p)`C6aw>1lkXU{iaYdUZ-Qd8@Xs>&Kuxg(==cT z>Kav+t+gJkvEGamC4Hk#LiY5|XPZk~&8*^IOP-)MC>uwExwTKsAx|vPjPY$=X{t-5 zaa+|ob0J)L6i?sI*D0#m+=r=}b~lx>=3ioKlQ{8XcPwk`Z=aa2{v zFk6Sq_MA8tJr{M>y>#pA;wrj$A-0|=R@~KUef|?VFk=Y4J3URL3xyc1|U5j|V`_|X7 zy5cx3%y?5ZwhY@>K3IxDA$;n}rBhNA=CMm(CsvD#v5xCq#e#v;#VIYz1*L`V%c#B! zSjBSGqPTnE*2c`@*)PQ@DIF;ai!+#}x)$s@vac%+lP?~-wX`rK_9;aHv$k31qs@rz z80}MbM{QVO*Tmh>1gN>546-i;gcxlydZuVMXN%1`++o7WA;xIzY~|`yWsbH2YTJ6P zy1@rAIl9TIg53XCfs?^-X%^t)lamzI~e$()?Fi{&8IHMVZ%j=$Qit)JzGR>@KZi~gck+lqs2Ch0sV;03? z#V~%`qbXOG6^Ms2v|UP;tx$-$?EYq)} z=@2nz5i!HrTv5?s4b3(*H9|~Uc7ugqVDG-{N4WMFJmKO5u#jHMuBY(J`FCFqLJ+N8 z%cgmiC*233DacuTowImHtv$NNAE+&;ZZM-mAeWKGab@<->b}|ARVydEmWYKuIiy`% zPrBC2z>ItA9IKuQ|M+8qGh>6%zQ=D{RCA%i;84`vdlNpn3H_BfM}O>Whx|^_DwXB z?UFMjs!FB74nzfIzlnZ2$)^r!wXYn8M2mK`a$TB*M4wUha{*B*xo@I}PVwm}eOw|I zYo<;+Q73uEy=vkj0|!kKb4WagcqEmtEW!P$#o)FW=7a?1gj@rqTw5dyCr#SRI@zoC zVSddR*ow{R1I-%!ZwQx z{M@S_yVp%QAiJA`v)Y1rKo9{qB{xFkRoPl2Wa89pFc0W>bpS%n z?IVMb8tf|YT^r#yylZ}PJ;Wr}zz_7ijFYAs^!y8C$DFO_k4_C~F0}<)0_(Az%%e~| zn7AUgUx`@c8bpKUDYi%<(9hvI*)!rZr1Ts#Da;`w#+tAI(5H>X;Kdj&=f&OT^<6$t z@7+oaTxQ>B-_^!=YGaq+qHkquQEWOJvO19&9zCkC3u-WV*)ugAMF#Yst6xW%M@3|7 zugTVe(R5Hl_>JyrFhp(`A%#Hv6lQ}hp`L;vUSOwT`lAEPqY2ETU_>B8(4-O9f|cbM z$R{vc$1{hF78%HcKGjY;AfxTV8jW)e_qPBcu7vi zWDVEUbx0Nytc8gjoOtSF|G#G~U3S6?ggZI_(P(UljJ_s2AqOJZP-M^ybqxi&28=o8 z8Z?6_l%&Z{_(8&fh(^c%UExsi%7;H`Hgvy8g!O7iEM{{?@Pa8~X@&`H2hj`+Ym5LB z2Vskh2E*aMycjIJz#g$|gp7uUSQXJo1BD(;vgN-i++c*%0F&H76VZqdgbV4pB0wH^ z=NH!a2x#uIMQT_8%?*pe@4m1{{Og4|+)qP3@43;4dC!k|Hp?|?s|llm=0^K=)@%&3 zH4R4uF_^F!v%&A6b$|f#2+VgxTkyNqVClso&In>CO2S$&1Q2H6h+qT4=0F(AH(fv& zB%v-K+zy2EIV0F0VUWYR{>{Q6jJDdLZhP+4s8oV^o(@*O*gdl7!!V-{E;QeLu6@>n z%8~sOpQmrwe>TlEFawvPO4`i{@0$eo`vX$soIYv^MZyFlVFe}ZogCKH91r=;>ePX1 zE_%}lI@1XCSjyS(cf;Y8v<0I)A&hxc0kw_(wT&F+Pi>p}Et+)v`xYam1AB?D-JiI6 zeB4;j5;-KWY|&=&s=T;uMylvaeI`G6i#V>6ME z34!WG#kvM;n!x~{U_Zc}|UPp>M5t;7n34lc*^EDI^z^@&dgoC)HTtFeNK zfUllvxwbsHZ0{r4;mxWs-#+_N$m7EJsHFYX)=`xR2HzsB*Gen>NnMhv-OhvL&Mo%& zt)q7VuLqoa0OGyQgNlHkX&bcxyjSbB70xWI&_@{3QV`Y_M0Qu)LE=FJZ1doW?PHRK zl3s$xhEJSo46uk5xP1h3ka_!}H|lqxD# z;48<}HrVnle25pOt0c9;U5D|BI2)$e-hWm08z!Y0yy@-J$SqP$OsNspru=F+L#3KQ zpd{rG**o1eZz{e*_JoX}YHc1L5gP{u2FC2_FQi-!7OGdZU;32mk=bv2jlCc`=F`KZ zMLwMES9Xcqz2^8l`H0vfhY#dAk|jD-a2nS~Co#TP`gPx{(`Gda=}80%DYKr;;+Ad{ zPLy~8mt_v4k!7DcGI{RG8Or1*!ajULStir(VWUs*T}L#M4%Ad#=9vs4U=8C)Qn@Ra z_2Opq8;Vqw@N*ON?K(BtNyi%e*eF+gt)HKyBo3*GmZZ&9$^WPqkyYbqW|^)uHUh%z zNW<@735~A$)hQ}qhMV$?A29Pc%Y?NSrtgQ(FshLxRa+Gbnc)rNXi~Wwo%O;Hm}yf9 z=L2S5)Mh8qHu&*V+V}%Abi^ICz)ZhNzKwpwVy$NxFyp1KI}&a!^^m?H%!-|NLZwx> z`L?eOyBvcxsd1)$PkR8omVwx*?w!oxz(+{^<`ajU*wtsU8oTu+)%4CR9@39krU8X$q3^0~Gb`r3wl*tei+GD2x zlcGEm44Bj&I}Ml&WirH60K+=t7&aUz9n(m9jI1(%fk<3$ZrPLsYyhwi$SNC%DeN*d zU*_&_eU~)@mI&9q2QiLaHVD{zxULn%ICt4RU}JDyCx~$YR({bT->+30 zj6nsv95)yP@`>#Yz z_PDj`G{he5GEKlfv{vy!%%{1fSJF^4_XSzZ8;TQZ;g7+pI^Kp-b)Pb!d3h8tR<&?n zXhH8WD!_Qu!u_Dtx5wxJ6IKfk0POP~V**S}2AHZ^co?K_k8uH}s}>#(>Fe0l#|xOTT6iR+4>0E`zbML;WRMBui9t6^JPkAN>fJ*Ph%fz-|!VgqYu+9K@7}Lm(EqCzlG?P2vuS zMeoT$>=yCSPk<$=<%iyj;Q8b!Zwr>mJ>A!lVEW%~2)o07C58H;<<8fefU@q3)E|xN%RST#Zt`i2W308klh2tDCCD(4wcguX<}b z+mAXMbXu`<)^Ls#bns&uyfUc)rq==tol?t)%M$@hiaal@CY-b3vFd%G)TGp{bH23) zcBxN|@*Ysy`4%WG+f(}FzUq5O={um5yK7fzXgb^@1t^^bN)t5ql$M0m!~vy9NU77F z(seaTZ=f_R11MeFQ;NE;$~Oa)Rsf~s-Lr;b7j796zuQMCw@s<}?y{)48 z_EV3yCOX!nrX(fw^p;Yuflo)?mcg~KWq^V#1WjU-Z zrHMh+`R4`pWgKK$P#u0*$PGDbPXG^=`iP_dNJ782Eon@9d|3FDL(|Y5l+6I}w|mBBu7ei2Yc!dEblW zkKWz;Uc-Kj-6!9@s`%5)Jodf%{#bWx-;3gpMSJIandO4^h~L)T+wV2;$GZE64$|M_ z#q9$r1bAZ#)#&>q-@GxRp#eDwwDt!zTG!tL>K+5fDM^q+)ZJfk`R!0sP`R5(OdtxJ z%mS4=jVIHzp&~!R!xW?{&}#vxa`O}9o6>X(@MazYRRnlh3o3VJZACr@Zr@#kd?;5P z!|m$^n~qNE?tHjTUt@&;NPZxWbYOc?O^e%?Pht{9)9nqC73jA<*j}jU>-2?rnEvj% zNgpiJ^sWxwFRuUP|GzPY8L&jaXYx-^J?5Z#Z%*^q@AEQg=6l+WfV)0=gS@ zt>FVC*u^wMYzS(ugTBsIn8)1j%}s`2nXY$rL_p1T;>nBw8-rngk2$b0XdyAV1~vv< z1o=5&V^G4A>Do}S7U40s6EQnzV<1S7Z%)&Ffj5)k7vpPSV*oyfB!GcANH)4>w zy9}u%L}`SufXe+d!>?uTc*6qgPNxbyz~| z*Ud?7H*5>p`hqw%r4GxC?Lb#oqx*)iGl*h@_@L{?igIAN3D(9P`*llObZd1K6Ibk0 zUgB22`oT3-O)Sj1qet9=j|OpHw8Zd=%5cM@|q2kho@oWa*VRD9faarvOD zg9CczxQoknZE;;WTb#!0I4$w*Ewprw-J1?6W7gi&P?L(?0BXB$GA>y~qzvb3)I7WT27U;Z?_X_V!}&3d5_i;2-~ zOO5K8F|y0nYC2n!vRqUs=z3qH>-yyRqSt3@EIXph2Ie|_>XygT%8D<Y|?3DZ9Hlua4zd7DNOT_XRE(BHYF9#g$@45KT`PxUd^m%S{Py49k;8 zmBmF(rOTZ*I%bFB(C8IC>qXloRd?risKw#A9<;rg`&g+~zvD7n%mCwx)4p4|?y6B4 zoMSoLT%l;yF}C>e1xH>sW@VZ5V2$VFMp(jLQLNcAs-<~NpSSG8 z=#OI~!2c$>z~wbdo-XM?G|cRUAlJI|^Dp?r|J*x?LQ7^C?tCU?z22jr%@w)IEEojL zOG4&@`&n8{TgKQ6qLLmNXA>r`Py;&b2lpK0uk<-iD z9-=Mlf9QFESV&I4Sy*hBvAot7$-$@JEKklB3n8l#E0>_P$`VlD0iwxzeFeT$_j34L}% znY`R{%}iwh#WhP=CMhoY;_C*x)r|Qe+Z({@ZVybM}Yby*5t0XF7p7 zuz2mU_@(W`BZ1`q7SuKpSY$gOhuybV8~)})BQ{2GQ~391OLj_#T@?4w3Gl2A4b#rU zQ{dr~9kFjezdhnGr+VGIPk_2?L7BX$UR$Aj0mb9OLMK;67pR8TnT@r} zE$Lx4QeKIoGb*cZ_=%r=7-#g~4zP6>Ds0aWx+S#4J$iUr<>tw^bWu#2b#&*BpOCm1 zI7Tq9;-R$YZ7NHZoK;e1O2G6iIEM!D#MM6e=47JL!ix)ATq)Ugc<0}z>3eVnG95x@Ws_GcRXz>4 z9fejEcrhpJpL(w7Dnld2>Yn@}DJ|>mjRa41rrgd9)0R9w7zcq-`Ow1ZtaU0YUNPr} zrnYwh!JJb;P+E1n;X`k&rqn!2mZGo;7`(J^?))rV=4L`}80%cG+Wj{-l5_cd^}i++ zf0}*!oHgL8s(La>`r8a3&&saDcV6Yp={I89xxz+`Jsi9Vhy3iGouF;*RN@XfoLcWk zvUrM<;DHo^k&X5Qzdw??_`#Q9i_S(pJL3MPQGQcGUwduo!Ma}cBtS>KUi=&G?kK0x;iMwOA z%(ZVHe;(kn+LR-%E$X~FN9B&*_~KczL+h zgr78mwDjR^9X=cPbNx!6lRU4i6OF!FILzvw=&Yv(LkV~bz?&a12pnoqd^zQD*on|O zU9tcr!BwGak{@-|gA}8}c(GP5x8ZpYsaAS~0SU2Z!pw8`i%-t$XAPye>BxtTHC?8@ z@AcKnU%rPrgk=b?zEm`^Op%8jS!k|P@)c8jK>Pwa?p)x(dL zn~Wf?Z<`*&Tu>|MOfyA)h?P0`hU}|;eRo+T%<5WljFxBAAkN*6Hb3Ql+7TQ^>m+z0 z*H@DVc*=1~$G#8>5ooU7^5?Qfm0jjRSirMhA4^o$KZt2L6EgxMc1W`;L^KP^7W7|I zI==#!*5o~$T~t4jxBMn8rTe*UXUxHvX5;gwVik(&2hM8W|JX&FiXU_({4kfQpPW>g z%7XLw48QC2{x63+N+#}?qA(+~(QRQ*pE@^@+xICtv#U|ZCj{ip^U)K(6Pj1i7xJ#u zr+z3G!N=0L{YwAcxnPx4RIs!s zhnNuG<3?~5!&Bm87Dk$u7Y95Z>J{7N1 z?qB!Oho~)-1U7xjYtB!~Um1|>yVcoZj=Wb~oSb`O*sa>JK|a64zs_P+0!jD<=T@Pd z$XPNJqXEIWfFlR2R%JxkI`ypZ@(XOmkLqIQvfgMuC!%t5`ZO|>=8H|0X*ud%NA5QH zajMTdGC%LB(s>PxWk4XK2Y#OgQB^GoJWC z%d9ct8_jO3kxVpeFfnPCgJ#yp%xYT&l0Ao19%)+$EI&1_j2jU3hlMAL!wqP-&GVMK zv!?oQXdpv;St6HRR$0<>Jr^jh*t*=KSnlqr-9B9>^H~e?lrgdBE%W+B`Cj4KsVI1} zbm>9h5kwtORSxZbD6w%gfq(lnl5~5>Jc^s#ZAe=e6+>&JBaL@U_GY5Y0AFfEt}>yV z-Y4-O%k$aB*sbP^`)?H3&S>dv6&Ej*iNr};b;x+cMi>{~VI@s>@e4m^gZ#u?FlYLr|I4wWGXnf=8Mt`!$~n{1c@}&k z?H|3{vMnW)f?C)0PqHc(8miQfXiJ^uSMcd&%S}riSLZAgv(unP>N%F*>}`FElVr-B zfPe2{w^s@Y!^+7gV~^VW)4v=GI-+^IM29Pn^Mhxrp27a!0v`Osi`8Xc*;8|~51m_) z=%Emaksn@?o;E*cf2J_Fl1=s?N3H~=5)a|giqx@@$FZpvl{hw+RLG=A-%eF5h>_dy z_{P$krG8egW{}z>K`+?h6(#M%rP4c@Lzs)^stil7vR~{vZULm1-!4Xa# zX!fA|4pqPDqmL33?SlwbZ^Y-<;-(UTUD3yDzC$;MLsp znzlpj+}s9=g2t6saGP1I^n*tf=7*mU4X;%^8lMrY!8Pm&u(iK4t2F|r{LG?yg{;b~ zxt1buD==-0kS4bD!m^<$VTL94vzgdqP14R@pISS%^VG2;O!jZqpRQ^$I$68(uix!r zU!rWgH+Lnc?~_vu*LG_;S{QYDyN*!Tq2^+?37$j5%WjG7(Z@*+R#W5lXxyHgb5FU~ z#4md+jCZ+xZqhryKCx&!HhzOVeY9tWvp(U;+LV9X@i@FnmJ4cXoDrXWHS34uZWNvt z!XzEADk6em1P#jn&Xc&%gSH0d`ifTO7Qa6mdZPU6Rs?w9oE1E+Oa8N%u7w5kkvm37 z!mN**ykz~@{so@#!~+K(>M07bT1k=P+O;oxtEpaQ2|h09IY72TRl3$K+a}qzkT}JA z37L6PP;6B|M1-2uUOC#7HYATa-Y#FKL%JE3TmQT_o!G8;(_$q6{;VQQC%VSdlqZ`P zb(P(7nOaJ}G5DcB{+lP;e#@`!nH-l_>Pwa%zl0lFpE;5KI=9L?g^@1zec482mL>fCQDtFy%i|Y zac9CaP&Vt9jzz2=9RE!GXD+Y8%TssraTww$IGWUMja{N#P2tPa4;zqt&naK2c7T>W zE5<~5rF%n4!p&y*MCW4)e5MbK0eSjqL-od7QlAw+_#7u6LE+4i|+CF@PqVnDREsoT`KeZ8FT};`{y{dPbN!mxp^NyvQynXJ~ZS(Zf2eNwV zYwbbh8Oz5X)Tb82#Plp)h;9mmAKrdotMrD3<_ZtdMN5vv-sTTZc?VKXTYL!Bd31;S z6u%IxWdUZUl+ID2W?B)CN9Ay8T*>UNfsc`r48xEFQe*5`eF&YYtT$sX2fyD!59O3l zz)`jRu*#seT5i6Fr=~gZnb?~uDc^d0rZ~tV@iHO7=yHo1o_bLfK8N*7cIHk3GZ}@k z7Z=V8A9(ZH_q8>S-eExN^TT;`QE!r?c(VEpe^Hcu(E8e9SI;03pKONCX z)`j&=ME&M~9q)q!+w$#Z56@1xF0GWP1-Z}%hH#gW)pgw74w4V%lfMuZn=#Yk4aa^c zXHXzOyC`E}So~i{<3h;lbxSZB_Fy!~cFM-j&#n6hH_7kkA+KAwaHT`!3+M4E??>-n z5m8m|D@Dw+^R2L%A_C8T_s)XCo=>T$OQ8XarreH zwFj{7Yr4+4axx(>XRGrV^9Al0USmE38^YLtYgE<#mT%tiuz8|-4Q*&VuP1z1W@ee_ ztM#l6sS>K$Uu1UJarVKu8xeV^-+9aaK#HT0j0aLhd~|&;Srqb@+~6-b(Qf=T(hHyEXK>`o^+PjIQCm#j~%CI+=Uemcp^! z{Kz$FDW@S@YaXeueG@OknC7hxA8%pl484ns-JhN-m=rXnVL!_0f7P9f z$M&?3=W|%2;%&(~!MXL3(=YL42`p}&?etsV))?=c*=`GViW&Pv)0P(>x8AjY2t@aF zVNf|3!hH|#597<@=OymvDwZC6qjCdxRL+XxW(2K()JXG-vNkCO^nOLzefueJ{`M&w zV2FNt{mGddKNS4&11WSk#Lf%KpT1z&_YO4p)#&esMeMc0!Abw#=G%z|f6o|nrozq( zGFAcR*S8ZE_ALF;J1F(Zn z3QjcvdLRwo4=UJmeP_e<`%wjZt#NQ}|Do-VgA0B{?9cBd|Io6@`OSkr+*$si;U9&N zlK-2Az55Tpy8rtfh#!WTe#8&Ef4<@Tp&(FX$Mf&o&mT?yk;^g{ekuRIy8QbF z;D<%apPTJ&2Ywjc@%Q(-^P{!U#h;AsRiWRT|DGs+G_RHTK2`RP`%sj{|F+i1!A7MP L%t!-CNc{f*y1xGj diff --git a/app/public/exports/warehouse/warehouse-rack-spaces-TB-20260428174354.xlsx b/app/public/exports/warehouse/warehouse-rack-spaces-TB-20260428174354.xlsx deleted file mode 100644 index e1ee76c282a1807e98b30b8d485a048da6127ff6..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 18250 zcmeHv2{e>%`@gbPL`s$lsg!*gvM))55z=DcXR>79No0u@OQ}qbVciuVUIdiVL@B6y0&*xh1=P}Qt2_+@lMM6TdgXG$| z7=!zmvYooyNJu8hNJ#bpslI}}oeSK~#rUG91Kin=-^11>{oy&g4}yDcF32eM@u^Z9 zUc99E;du^TKdAZ&%+wzR8-)hyEO--^)fE< zi|oOP@+Jm5?WB6RP~IKD8yjkAen6l0d`ODU`|6K*sxa++Huj_&6WJ+a6 zi+gr5^XQy#1BFv_bfjz{(Ugnh*SjAW8msgZtZwYSfVO>@l>JS5if;Gfsv#lfeV){u zO(6RSDnVv%`_jl8Gbx^%BV_t+a%nvWHP@LS`OX9Y|L2PWd@^=|+c*pS7_-LKbiB%! zVelPvI|&KZ&oTVOk?9fd)yoB`Phq_k`<9>BDerieRCqYCMijn+zsj)ZE>AEM@cb%356g$_oSp$JxvwA@q_!AB_}4vEy!16S~B zM^#gi#o@a9m8&Sc?k_%d&67Fzm?wf@GZBpu-TUxSeGT_je)?_JoKqA z1spH%LX9VF?DXx2?~j{4KWw45Qq2idW4Z0;`57A%q&@JATeE)9@N#S6icCtJa{aTX zc`=rB7gE)GP?ch1HTS)w|BZ~W^aF$mwBLFGd`o>9hsOlym(R35Ee5Wl6N_L=haQ*PBgL+3J! zvGm>|m}QGSAHV3!kcIC$eyr`Y`>5C&Nb&ljd@$nNn1R(40M|cx!0p+`+~d z5~$C}7qv$2oZ4{Qv8J!2BUBo1vUfG2FCTuw)#F>FfSIQ-4v+{L!l?!xiwmj|I1nod zBR^{hW4qVds|~Gi?)>Du6faHlN}rnc?&WVTr|89m^DH z$M3_7WRdCrsis1Y}pH350&yc-G?UGpDf=Xo1cWZ~O%AwOqM2 z*4-y8n9bK4KSEdz*7o(hwmLD@8sCSDN>^y*N(uetSUC(vTS~42gTSt?AdCsa z&E**5IG;Om#Xd7jQ*v_n#Jc$6>vPSki^Cn|%Lreu8JGF4PsSxn_(8%fWq*qA@>271 zFfFZ|ETMZiWqF)Y&%UJiZL!BvR0)15xK)GEd*u~j437`*l3r!RjfDF=8WaHEG=&p- zQ;hpdi+$(I@!S_K zTB8-O>XgzeU8UaMxbapj8)1G7pArq=p6*?RS8Hp?A%iu12U-_O3Ay;$6V=A?g>pl~ z!&vmIaJf&VRak7?hu{>s)vSbakb&&bX>$ zN>@|@^)0O~I?Y$$g2Ae&7PVASjVS*N5>A7--U-8%W@2Ob6PSEFqU;Uao*20Kqh#%~ zR(vbmPZWfh#n1>y*&4XT8Mp-jv6CLZR1=)O*W07rvo{OXmqleT@A-hk$Nd?Kv!Z`8 z3snJcMZ&e;j?Ek&^@SJ>L+&`r6pa-)w%aE?1$_+VKBE8T%(TrV>y zxmlG@_IV)sXvb&{@$GwN74bZyG=M5>UmAPm%rRdR_ivU@ckn%=cg2SqI3$?tmN4SN zkrtAkl~S~Pk@#X1JLrFb{A$&d4w9{nMf?fR>1!N{hQ9iY2D~~7VPa51*+f}`HQf_F zu92m}!fy`m4>(C1PE)#3hE?3H_fk3E+SNzCK-F@um;8ZTrj$dDX`qtY9X+3fO6CAy zR8=3X4bA65CR^0;Zk-JHM0mXV{{>+dJrX`*%%Sh4P0?6g4tLg+s5JOTLI8sSKE6u^x2K38!TS^=>4&_jgu0;qh7VBQv6jpSusS7v1h2?L?9 zI2AD!%h8*_(F;OBIvrX;WJ%5lQj!f*PvCHV&henP0HzLXtr+$|_MPqU`+LF|x02(| z2l%4)@kJeK<#7H008p=l4&=<7jB2t(##kczbV|DS1E9rO1frVI5fZf}@rX0~ zAlf$r?8EX#&5Rjqe(+Top7GE{)G!k*6kCmKM3*MJ{Lz#LY_61Hku^~u(h$H)z|`6* z-siyS0>lEul~D_aa|OT}4X`c(SfebF1|TOq3=uWtVC}bu1fo#rh<728H8;T`t*%G| zqA94Uh<9VW{{w>;kOqK+(*W1e0vJCL*M1MAfm?~j07MVMNVE@C8bJim08j=Wyb3|I zmpX>7R?iJi74Sz6a!rMx;Z!47`epvXTctHHvk4C&B7T;D7KOl;KEOI$yKQW3y1}*&D$S+VYdqAbu{$(sEgkpM-{1scC(TDH4AHF}3-^=BU!6`*yEUUkQ_w+(~ zn*KnLKE>6qVfi(-gHmw21U_f*Mm3qS2#XyO*6DSVzG5e39QiJ^q6WPA?C-kPes!od z3B^o3c{lEDI3TJgET$)%zXFeNMSpcb6TgUgH(moYpud9mbgN2>jB~k6z)8ExYXf=N z7Iq0T&IvLPo_|db7zhd=DyFQpwW$B96fgkZk*iU41(tSiEi)^|JsQ5cG1S`TSlWR% z4x@dCHTVH>{E1rI!Gl-qgb&fW7OmiUMw8!lCj-xdsxZRSLCUN=o>s6b$*YkiMo0_Mxz z8XCoO0++aCCmKhe@s4zyOziAHFWoO}Si#Mfch~2b?m`sKdU2{h4aY6k$6|9l5Ab9w zoNt9*x)Vo~Q(bf4{l-0ihDA&x8t%r)eJxe>y$eyX6*lA9{DfOc^^Az&mEh-jh?j@T z3aBSc!@jTcdcNu&?G-r>`5P$6(suS0a)q}Ffnxi+*^kzQImC%x+Dq8Zu|f`gTOODn z*>G>)6%7x0KjKKP74i#j6>ctE>}Kbw$(ZyfMZjmt^%kk}9D=E^!ygok9$)V!-^q^} zqWU<=7}8C{92txKe4kyo20iIdP8@5!NY&yHyc>mfAFH}|@QS^Md;oD>i4}6^w+g`v zpS#(mY9=QADT!mf7OCbPf@!hCqj2D%PTobcs5c+|`5iN~U}mOI9y==s>_bJW z^9sl5)Sp0Kx}(XfM(<2xb+4yi_u7yR^Ro*vujo^C9&-;IYBc$T%AT)phn#*buFYlk zMo_m#B2oS>9Lg8Ttj{~dFvzXQZv?nUoDX0e1Qch(1ATxNGIP@pL@i9HNHbpH3Y~f( zpasUO#tgIwnzuKGz$=)kyei(Q(uLksF-NoSw&vA;`KCt4T)q{k$$BGb3)H+1g+s+6 zneBOp4gxje49CMHf<>yPrqg6x@Xsica3FdDK*;KY?f?%yfGcu<`J^-84=aTE}3fyNELObr~y=oq?I| zCCZMVBJc1DGw9YU0?i@3YDa-)2UvUKeR#!Ds--I6OT^9FFyKo>k@QvCSiYk!5kNBs z)deKb%*THYe4-YB2kZgxu)&6(0f_7u5x#OpPdGAs}3*ef2G#h$>!WIQ|IW^CHV8wHjjn zh}^K>AgQYQLk>}qb|jyn?v}t`Q{BfpK+$2;Ixi9@)aKI45!_!3G(TVG+Q^j$tfa}DYTtwONb(t5C(Iwqf zA^&nZX>!C$@eIh$@Tr{#GQl6R1Rzu9Q_})6P3v~8RCt9JRl#TAOX^K4YhbrJpT1;n zjfb^-Jh1z8uHboKxBSa>#ME6gv=XgNUlKK6S|`7F1mtz|2iQqKL3$)#uHF@!+^710 zf_Hk4GXMqOnzNF$Q6aAxW?wlsZ`YxsY5~5Kd*MG%5Q}Stq&8nzt{@C(d6w3yF-`-@ z$LBQo`y>>^tPZF-s`onn3kwK|TY4xnH3a-)8c|Q4kzB46(ZjsRn@{*rw_LBH*+cD% z*Q(F43^-j1nBE7bmm92GnRHe6+i+G$TLG}hvUN1YjToc;tyzmraAqM-qK~iFwY$6q zW*SqWT7j9%Kg=WmGYPqZH^4yl%vKE<*^3qwdC&b~UonvCx0ekZ`oh#!05=(}DZ4C^ z>D+8)!gH`KM&Tf-em=ELEOXl(3b%{`uvfSsnkf-1N-<9)JST*H_n1L0Q(HBK=wN+C z88L0bBJcmBHT9@%;H1&cmgXh`@n2Xa^^}N;{z5n!>6b1{s^3tCzI4|w-NwY3#+KTq z1Cr@_#f0ZT+dFHa%tyOz(9c5s*3sPL&o$2$R=|a&$>7URWtZ2y$+Kf_lN8R}zsZ{x zK2rTZAcRWEBci@pi?{Xn#`{m8{Kdny`m;&3QJiZqn%YK@R7#tVA}`CYRw73z(-l?L z66Kfv*M=L(=6-Lozrr)te*r@*bDPv`@=$6aK*5vwBw#l6dl%VE!^qEU;cjdY{e^zn0Eg@HEWG!6J}cl=`TsQ5h+_4z9p|) z1;Cd1u_awwVYXg@{&n>HSp~U<`}}PLuh+J^n=%fSJyHL+@?%rj z|1kW2E3yBZGyk}p{m14E&(GStku#S!`q|H#nf|jw{t|lox9GaL8(r64A7#1L&h&n^ zv-JFQxX4b zC_g}o$)mQ3W^M}tr8Ez01B8i<^CX2Eaj&bVM3e%@%|RpAF*hNeekH(Rpiu!uqH6>5 zY?<3cg)?`93Ia^80Q-f^in2UDQp_Ke6F0jJ5XdIw-%bBr4JOjhR+to1UxseJ<7Z3U z1ze@J!9X%?ub3PJ1s1>-3U&dep?>Q-+rO0Ag636AZKD9{6kzrZ=(=e_nYO61yeL20 zP0oDZ{D7U?ubRi!&tm@xkeeX`XKug2IR5N!`M0Irn<8?Zn2jp_FF5$I2l!6w_eQ+I z;NO+~Gp51zc@x}Qnf)I}wENJXWXA@nTiHFfep<6BbheOf8OZ;0ME_Z)ORZh5*pz@< z$$qH_f8q01sj+@eyNUd*a&60STE7agshE7f3h)mr*@oR)rN;VIfK7E{OA5BK`@iY3 zR*^wn{J)qkb3Ys7Mr!=I?3Z*g`q?UfDG_&n^srw#3FFU}ypb*fTePN;t@>>7&px}6 zF2BkO6s}(}kpj`}C6pNpI%RjL-#F-ib<{RzK~@4a*`Na!31wbKmCZ-_je`z2GAb}9 zWdWMJ2RK^?yPLD9DsT?oeAjQB$hAH7cgroACH~QxpUT{bTLiHmdxB}!$iCe?z#ycgi2JXDq!@4+CZ4%% zGdf$@{Y!`0SaGAn{FH6>&sk0!{2O3x@3yuP*+6HbHg3SZQ5!da_}flz)W!``x03zG z5e-h>{vi@q+^q*z=R;jTS`CH~%3EX7)_n_TW8`lGQE7{)?Z)Z)68~$qscvi~+seN!?cNHpt;qjxx~vy|&}i^I<#h`S;p@NO zD=k_XCioV6uQrXkv&9v^Tb*ih)mWt^5au-GRtcqY;CFq)zSovCrsZU$Wo3)N?-hMY zd~xOY<#6BGSifIKzMZSitBVNZIGG|}{H*qPfA46pJNRj1e>c8&8S$De zo>dNyTV0r>@AO_pjcTkO59mTO;)lBMa|C?vs5WJHc~g9m?^5A(L(UtyhmUab@pJn>|5kAkd%Wp$pGujm=Ga{B^@v7g{IY%#d^nq-^`xm7~tgVVz z6KA9R8Gma*Zm+?)DayfD`S!9G&v7wi4|oV&Wkd+X+X=)O;c;`#*&0{yZbGB0%TxIA z>DMPZ@>}EaIrx4IN=~-RXRdGL)9YbevwNMCQK{ET`DmB%3Vy}x+7x{HlJB*5c*0Z% zraXVbr!Q9iYa#wo=L9Q7010!FR=vrZXP8KPq~a81>npqvcTCi3`;wTJw*xUO&8^G{yrr=33@%*G878 z&R@!U9dZ59*ejSZ$8u1XJ?HNSr7Zhn%fB5evg~=6e>)t{vOlu?+aWp2o_l%I;R*Jx ze2Kj~v^SGY*|qwxRB z+ech1;kNLfcbTm92e)X!E_QI&4l~=@ZB*bkl(k{skKb>07}q^#j}c`m!D{a*$e%`N zop^EKV_1is?U%!jQnSj?oR2|!$s^QzF!ijI)J!eA3#r>|gH84Q7}}DSPqs_iu+*1k zYPSS)MO()l@6bFfA%0{|8q3(Vz+q)v>Uap^q8ykgJ)$%B>Lk_us(#kcl`vOd@wbh6 z_b!T03-;0t>s&aJelVKNu<{`HVRrdb;e8YnI(}MHLAFrF<)3e&wc>iq9yo%F10#@dg>@Y#SLWyE6)M;lc7ka!W(1V4#zm-tll3a zyZSmyLYu#iW7mBb^3Y3_OUEiSWu0rH5pugUZr4X-}u=MaF$I3}N1} zxTRo$RosN|?7|GzSPoy{f7tZ{o18CU+1~il;YVTKbG6xW#?sg3#u38`@6QTUaP=j^=opDmB3d2yYV zqSZtQC-~bs=>(m=X>x^LRfp?|*wmTsdYh9pQ8dK?mrO)le7V1BeM|CJT-e$B0!zmg znt07j4}ud75{090u!!zPX+9hBqw}J4&QQq5$qSU3+T=wm`Oy$`SWi`$<)9w5(->t$ z!KkVH6Gk5Sp1Lh*{-!I%$3#7{ul5Yn)xb%oQ1y1E2b^7G)y2|@4f;}23H4tDq?S)x zboq~?bb8<6 z5T~=ru}1#Uog`P98bY+c9_S%qbxwjO3QXGEAk&W5+CN4qPGLBAF;u`AS8_%O;Q)X0 za(|+>`7T1;@z@>+l}DP}TLfARn*a5*mgFp4#ZZ_otDt%ycji@EO4}pXme^gfXe&uu znKDiN9Vd*her`RGN`6oAF`a;Jh?;VV4)$9A$jR%&+sEjdiUzJ0;|M*YF%6M-?_R6j zd`UN^ zpecFV>K2Fbs}rIR6w*7Aw6Z3KD6PYnlr=5ybMFZpds)-l)Yp74$xw{(QGW8fW(b;9 zsqbE`s&@?ZlrcJiM|~%^9eSXLEefw~&PC@X<;`{|U@o@Q*(0qB z3zKuscl(rkqSW(>LMt8S;20Lp>PL=o*cqK^qgo+Y z6X&KlLb!FUX(bAogMj&QiSA$+zc2K>)A3Co)p@kf+!HqDd5DY(=Po7oistRXapdqjIz<)y$gZ?m0?kS*b^+wp>_ zacWZai;J>)dzp(S!#m_Lw+phF|C6!kJF&_aZ!SK%X!%LY8@9Uy*~t+qvupmXMa>Zt z&2x7aT3Vo|pP1Dhv(0d+rPtxMJ(lYrBGvdgs3FTyUh7`{g830H?Y9;>)jh__$4+Vl zf8ohVOYPU^e=Fl=z=SmOEWPlhKAj}VRxp9wI-o5ug_>pd$nCzH4WSuh`|s^Fyi{Z& zkjr1?UvCE6{v}_CoNlVTWRf>ECu=wNtb9AYRIGaUw92qOxBKz85$}1RyZCbC8MK5b z_m!pg_1ua}b$CzWa$1L0nI?Ux3@fw8Md(i4A-mLX`sFOjOVoI*8(BfpHd02jBiWQ$ zWOikc1Sj#Qrlk@sPu1V2%@)OW@pMWlgv&FX+g?CEZI{bsDyk7>DB#5jC40q7##DkS zY#wd*uu{C4AgxG!@G0NpJ>hmYN-r~hwY~XSexR`v!4-t~_EOGPzCLr@ zYAK*MK5OplzAuyKa$cmPSA6f#7=}LOn*e6np_ApoX%cDj;aE5Q3x{9%LQoIE2*h(d(smG^N zSvF)IQP0}sS9)(Hc{mOAyW>gQFO1(6oR>S}hwX3m`BrNtxiB#0+Sh-6PeyP12!D0L z?fIe5_`~sJ?>S}l^!TH`-7&20Qak_lm^dM6hf~2$2tf>1`X~3~5^uSM*_&%R**pAx zmneJbLYbnaqsVqAF|-XzqT5_h!E&Z&y&TeOm$vM z*sr;iSk%J(c8I&0UvyXKx87uBCFsR)`KHSQ{^8I!7fl@ELg3`bpMMhwe0yf-N*)Qz zb9%m7y^DRP8Rk+%a?K+<6h88+zt`JwfcH(TjrMHYqO!b?OE-JVEqZdcD%P-E^R%vN zD*@$inpMGvcd{uNSV5TVUy_q8o$VPGcZ~N7g%EIrxdjB9MwgGwbpnpNpHN(C^tiAh z;GB6MX#oY*)v+AXg2s9F&ZS3ElppXhv?_1X*iE7?3y+x|{s`Z7NG&D4)udHt;^gat z9hbh2^Bb#coWQBXEmUR>lKDzF;ixwks`P27k1?RJ7ZfYHUuiVAcY?3+h$22eplE^T zNLN64!Yw6sW!q1w%8zzgH%DI;_!iL?SuE0r9hKg3rvEbrjUMx0Q)ft#rt&G1Ol^*# zrli|>%8@VeOD*zBF}1}phpLCbRKXJ*;#tbry>@09d_{V;WzWeNJ&yL9*$u$LEzML} zx)jh~%Xl81$p11xEt4Z<%_Nt}Qh%QQoE1$KnSv5edA&BdoGZYy_84at#7soT-Je9vV@rzFlZfC016kNotJ$@KDgrk1uvImTxOYOz?`#^4KE6PfYR^dCi(hGZ|C% znu`}^9uJ~Is9Su&)%qs0gypM7oD>%bL0dM4ac!$T$3J@{Av}AzWj}|kV63o}2+V~t zF6=C0d8p&7cS1b=xGxqi%>L&Rs%AJi2QU@>6%Rg$f7)JPN9Q?uqu*!eo`)flj$gy+ z_dQ|Vkt!8zdgrvm+ml5XpO$ayIhA!|1h1vjRZlNRnetfwQQoJ}tXq$%xISbAX+8Il z)V1twGcaq#^kuR4&Xc8+xmQFV$)R(l_iVJ^dsfBC(o=*tFfgV3^Umyfztop^63;-` zCYE4imdoO>elCOY}>#<<}N01uLOA3`@;|o2Q*94?$_ z3Bd{)^tX(xG(>pC_BAs%TmCjc>=Sh3j zoaiq^9S~LSK|d{NP-ekz*Mx4{PEYc$pSJ-h`sKC7(>FF2_~QvF@i7r=FJk??18D#8 zXoJm4e}8Pmk69!n89(QIf40G&DI-2zVeLg!RtDnh`?D5)X!@gd#L~a^B2MUDo3OQk zzdwE9$3*ay5}+37S)2B2B>$zo#D^5Dy@=|$!1GPOI>Z%zKC1!LV-yd4=V>SuN zr9aHwc!a?QVq0G*-dN>?z;_G&aM^fcg};LE@X7Bh{J8$G+5F$HKx`;J`|Grg>k%7z zx887WED$BNX8F(U=f>2(GWnwHruM(t
  • {8yc_uI&FPBu%UF#-rxJq#_ZFleo^|P l3;jO*_d>Zby=v6b-v&8{Ti(q zGuU1(-($aLp^7}Ejv!&x%0}A)+Do-iU_ygb>&NkorjD6-2ULLuX6Ztn{AWKCDtFivgzKl->R*% zgW7eznKb5UtJSMp&I2naTk2M)TbQ#CpPn{sqT9YnSMOXIDDJmpm5oyEz{6Q?5o_~D zoSEp?F=W)W>X%QBi)X9VhP<{uGj_J+hPpAqN@k-{wpS1GiJA1h`mBbRzYMe=%I#ja z_LlhyjnU4m=BHAfUR68~FTdQ_p(~wso^;S^%e@_Bv1}<@YLM))u%R7|UT@D>QdiaR zcKtNUB-j4u%SmsRv`CHW;9K%8+)G}}-t8w>pM6nl%xg~l%^w#l`PUCN-$(i7-DD$D z69cd&K={J{41rHnXY1WAYJxF@wmwC!Dy@U>)_gNyfVgmsDjIqH^u2Wt=8Rn0d|-KX z*LjDP!=f)|OutkyYrgicGaM%0Iezgs-=^jxCzp;qzH8_Srw_F|vm0`j9Iroa+%{#T z^0i6h#Ikb_=l+__+vOyoC_dz{{Ls03E{zO(zk|D0es%oQ%%IKVS3ViyajGNAHCfBx ztkQ{b&kVD7>CVn8stefn>j~D?gyy}Rr$4>-i%-s7TADsHj{E(K1-l*09qUdtZjG6~ zb4&NL@3ya@9THDP@+! zYx9n+(M{o}O*!xHBk#6(__pr3FBCNL4-61U+Xr(b^_saOZnkgPw`KM0Q!cX)T9~&F^1Ge9cK0e9 z4SR0;hRG|Z42vEb`P(nA&OKh)kkh^}z;JER(8MUk)sjqu8=1}H4$Lp>+9~;4skzqR zpb@iXyee{Q(3mp6cB-@2j8g_nX7734vV8U2(fS6<1DLG_lV8MXW*0q;%dv9%&dj=V zMq&A&dU3;>Nh4n5Zk&F8_B-0$Wo2zcsJ@!Vn4PQrW<(r%t~M!r(RML?%k8o!ORCJ) zJaVag=)#FyGWweNNQuCWZ}#eT<<6#jynCdxL;88u={Z!n#;0K@M?Es@S7sxJ&`mHN2Bv?2F1Ipuz|{hS0AQ# zcQE)4G)_eh1HJ1bgV(9XuY(8b)Dr0rY1{|0{EvlnIzN`tU2jP5YT$Ea`Q2Oz2CsyY zmCH+cLFZP`_?~qBx802}8-x3i3oCtKNMm!#xR2@i`&)Tz9=oBLl|pOnqTE&O=wz^| z+>aHM?)PDQV;-kDyQwRT%5P-crSRIDY3KO05_AsNjsLNc!f(04Z|I_N8ChKqD7-?$ zM83%+0MSL`)q&(&-T05)_@63dsdXBR11r?vEXH^2ZhmIzjRWWe=U-y#p|MGy^2hE%LcmXB(=08I60M^NozQm z;r;qq3$29K^{Zw6htB;aE>0!S%NM*&peD~fkuj@WEa&~>jQ0;Mm0U`E&`>E_#v4_e zWbMj3s!gTmGStzmxqLJ42bTG}X?N|Y_D2cUwB|E-RnxZe@FPTe(Pr~1+*dffT%#$7)!ZFbF$ z%Rd*boqgNH;+I;Z*|$y6i#C)`W@nz9q~!ndXdwH7l7HI>m{cavQ$FEZ{6phiH&Zv| zp^MRNj{D72je5%Y1q(JS8c4&t(BT$jIfNXg{pds6{w?o$ z^^T;Xq8;(KH(TtkMVIfkaPMxe&)E?lpJTi$DfLw@x}b@Zio$Y?O~Nj}*x__D99^Pq z*sVL_HNq~(s;{}6^X|vR8gS7qsISd=R~gsrU$i}bKAIF=VA3U<%O|^9+TJwXqO6+i zf-d8(ds`{9-v^o5+TJof4|hM-GRdL!Igz(+7wyptUKod6E&x=A`Rab^;>+zKHP&RjR#s`Jvft23TC-o}<-GVvZ@kA(uWjA2 z3-Df6Uvm-gQZ(SATTqJe^3SU-*gOeD)}@IqM_+0qky(arQ9dpm7|6AN3z}JGO-83l zNXU8RTsbw;V1#DDG^YWDm2Zp$p9F7_u*EvxjZc-cn`NHWzdm zcb!(L%-xa1D%w#8>-|uRF5hk8-`&i~*-;1U1uZPhMHi#nJohA4Aaz|`{L>e^Zlx}~ zujZV;J=%uby1h<=e(`kI%<h~b@VW?P zF20LFoDc~YLzBJ0iX;+oLb714Q+2OxxMMY5}E8} zf&MXCkuupX0M*d;){^<~CWY)}XV6^*@@~=+P~(N#9qx#sKsk2+aHdpQ0%%a1ws{&L zXzaYZIU+3Q6G&@W*u#hJ4k3quF`ht<+8s$t;&VRbgJ2`VYNA1g5qV)XX|I(Hn`B4b zr>QeToet3!4&&EN?|$t28%1_6Mu%{~8@Ib7nbo##cZZeKtWpU%4AgD4P?iAswjHoi z&I7Aj694p5{&txCOieWCA|mfhO&T!zT&eOI;BIRjC27ALDPD z$8*VfC%ZeV2XKQZz$Ix2w*c@)+azTIFkHsjdsQko>`3~hXvby(FkHSX<=ox;GH1u; z_?%ndTvGGU#ppKMJ?R$!ygB~qEgJxwhc4*uE#mIOTQ&eV4_(mRo4){H5o7V)&*lxw zxn&$?4Nl7`5?!Kg8d`U32K%X5D9zebPTMecsr0zbC$~$@$`%O=9ybZIM&<{PBlGKO z-SJw64tLL37lL*p(FNVzPTUQ&F8tBy<^fHG>{w8GTkX?Zj=ZzhSJbm(!4Gyip9nFy z=pWOVchQ>Bt(m>vbknq-O$)8gyE_iQO8c{?k+>#`dbE4j^D?UE2O{XS<} zo}PVE;G6eZ^&!;SD7pu`UTci2-cyr6z zqS~xs-c8v#zq)&!s>#(mm|Hx?!h%tCE-v3oYGg%dShz{nr9-)0ReNH?rX73=Gp*WI zTg&ML{vLAox?Yo@cM_h+hbMvqUU*3S9n=7=Yl;1cwq0-vjtRTa!&0!3~+N=HJ zo(DsI{3%q-YWc^IKt}BBRlcE8mA(&0jSZM;b!dO^Z|17r*J5YPwo2YFF;zo(`uqK_ zt2Rt;4u29h!~J!&*3ad04xX*C4mG=X*KMxj>G#%QDIHp4)FoT*erQ#UO0lqyx>S(8 z(y_&J#_s9+JSNs}Fm_BUU8?y@O4Lj9(G-o{(+7Lr+#0MCm}%~O$x)}Uq-2aK6=b>a;NTCQ-D}-I|50ZM@EaF0=Zs89N8a=>6oSa&Vw3bHKJc z-_H1fzuM}Y`BIyKU0ZyHSezX6$aeWpzt*fCtg1OCHEQ?=yWxs^bfn?&frCPoCZ<-~ zyzx=LkvNn2tC;%_zib>Vd4K>fHwH$o-J_!bBjvky<7p-Ssht5?4DiG|1G?u%_kk1JawY=3+DqQ7|Q{j88E zahYm=5Yw+8TjtdujXr^qa~_C=!$`mR82l&NsG0oc=)ImZ_CFB2hi1^UNO=DC^s>X^ zS08|&N6Yvfh8b9U(rz7IGg?+PP6Ad%v5=e&tCIW;bg%u?V7guah*VCMDTze-BPmiT z7`VdXq&yPoZ#AoDsA`^0jar37>ZB8b@Q)2uItL;w&frI>QQM9cA3b@DtK@F&FfiI0iPT9a7eSg7s#E|Xt@4S5$KxJ} zZAOpp29Z{szIa@`^bv@3vP|`HB+?dvNMYoh$710y(r+(-cil01v1;5@0P1ETxdZ`y zT=Q&+swOKn$^+iix`ZVK)(%Dl1i&yS?x3H765%Bwi!Ks41iXjzIaN!^a%i!m#IDlK$m_Zfv$v+ zbDoNY!$`lMNhwE%z?@djI&)x7omrtu^U|vGt9@)?Wa?9~w`k6Ai-Zr=ryraVuYU?` zP>>n?GtB9Ci*`B7(D{(Fj^1k^X^qc`xj<6mw#4e-G%>#rc--chn5H#69%qrDS94lE zSp57mfTSq1Js2Lp;hc6lc+H88sy0d>rUZ+VW+0{k*`$4co1GQ%tFp}A5E%JF0KOFF z+@CFW56zhd1g$x}EL8j|jC`Xi;};4eSZ3ooOBDxA7D<&=K_MB1%hr> zWzIna-N9dNdG6v_@h#5*()TjeXW{YbE@@-VtvRt>)n+a{{>YAZ(P|^tzG%czM>HPw!_Zk>@-bE)D zy?hZ66!c!}6PpBj&lTIe69n=B^j>@VVz_u|F05#=Om#TC{nu6jL1E;aJh5;X>Bkc2 zz3qeDsB#ybW|&h>J5=dYTJ`f`j{+y=Jt(YMgG@mO|0E2Y2K8LMv8e@@o9_)(^PU*8ZcW$ChF?{ayV z^BD8!3Yhag%(-IkXKN~@8#5F%zfJ#Es?lx~!aM2O1|2=1!?W^lbiWKK-D-Hj0tG#@ zaUc?%fQ0XmNc@;vAQ3qckg!q@#4KfbD&Udr2FZdu5dJ@t)1Lu)nxT+3+)od*ELkxA z2xwVMs*xJ6^mVcm3DkzaIugQsUz`LT^82W>4@?`#98wSZ!OQFBxlA6`ha#nPktm-k zxrh(zqf3!^m>x5MOOlp-3BpzKf&@jbpMp5g%ZKQGS-&DV3+wiZtVXo#E6l$E=BMZX zUpoKm$@xFi`M=zT{uY=bx%qFfpf5;MB+S2ooBx>57ekInH}$u0^N%fET2y2-7e>Zj zFztn5s0U{0H^L~?)sgGoZ5rjK~ zVFit=0~|Ev(xW9C?ZkEWE|Z&dZGoI#ijrJccX z;KlX!E`tcX07YQV^P(ZPHfT<%ihMNZgo4IrFsFQaG#a^L?=pE9xfSM=Pp>(~JhTGl zoKP_8IGPh;6BKbpgKZ(S!Qv}UqUR+GP*Hs6r%59UvXZCkX^e}xxn->G-i$FZUx^-J zf}jH_jdTF>5TrDAD5YVc!miKDD-w<|L*~Uyo&@jtK~G~ode4fz8FORIa|0auu80@R z(S9mbFzSd6)qHx)oNPOAvyICn3)e`!-z;(#G@CA#FsV{wwtRm!kYbCj1>RXVMLw z#}4bKb7Qmj{Vk)fF#j`P{teXp$AWsh!+*2VQDfoH8~T3+H~%pqEnx)gZ@6 z;D^emUxYxAJ}0ItSgHaFczr1FrX6FRfC9eZKE&GJ+E?XC6-))s2|yR4Xeo}PWvsN3 zJ{0TI{Fo=8f6$;C&;I}Lqb-vs@Gyom)q_aO)fQxwXXiO*H0_tB(iJYB(( z70@E-OAj(@>!%(;JL3!570p<#65H#vJR)TuVg3y;pU(TtGX9j#|4XR(UjkDUH~$?L z^aXz;3g+Ly&3{bjivdTpoBCV4`yZN+zNol3RTvk0!E_z`c@SzCCL#z)2}5-+homnm zR!$Yh|6cC>M6Vz;GhvFRoJW*oW5Y0A)>7ymjFQs}Qj+ti_G2D|f>VB2!64`!sQXE3 zLBV-yY|Kz7I8RL1lYpYWR8kkkk+t?w2f@M1OBM`*_^Un`_p41N+eAshoGVyMp?ffD zE6geHQGJYg5DIwt2?c|od!X(or3D52sd+I&p@2W}gPsHw@THOvo1knn9&0llJ+H@F z3K4h|u~Sg=%_Jyo7x_qPq29-`VFgvI1Ezf)da{QO361{rn4yr+*bjq*<^|ek@AGn2 z>f9Lp+<lb8|XHT7V?w3U$M$OV9u(LVcM z3-k2O_g^JB(csCf6O_|u?SlHUN13eDF){k<0;Un*8$FkdRX8a~hoHUGiy%Eor&Iv* zAT($u_ioU9LBD?~%0Fbn-vSdK1n94G%X9rLqpvXkLty^()cnVSdb`7ax6*Ns^UoUk ze+W1KubYtmsLx|1YrXI1G03Z^SE$5YB#4omxX(k7>;e(NTYuE&VIE#145@-PthQ~h zIBC37TT`B+BhQJu7vPOzV$htJNF{mB(}@KVlL`=WU+5fo`blvuCKedxqA}XGb7Evs zK$kxTG4Vj;63uTpIvA!m+9U`mF&^c(7(q*~K)T3z1adhN3aXJCs zD9i^*!mH#sPluy12)!?K9y|rR8O;83dhM_sq-6thPC(FL&J`>dYnbz^;KMe5^O-49 z-04zYMN9Q4D5UEXyBR4z8NreyV`Nd@Bk#woT^-=#=+xR(cW{657#cUL1mOO}eIaKfoJuA%&fKl&`?fRqFIQ z9R|k$_j`Rw|{f22Ix0{ITY%kwqEtcmmH*M?Br3oe^gF7 z;U)9F&O3^<{{I@!j+>ic;C*-`sMT^sI7l1nP7z`0cH%r?P!)31EBtfc-q?@H_=QLueO=>jXp~Uq0K9={{30?}DTjblF{p$a$dCh_R9} zwZW2FF1jo|*iD$|$2^^+1OqW9Pt}Qd%x6SbDITG4UAl2&5!o_mMMiUuFA^0hDa8{D_t4d7@0; zvUDtLTY&TwAo;K#A?E>S48Ib+z$tg z(0c0}os{cm8GVKMp8->_%k~#iQ*ctQ$9zSq_y42?{mYe(Ps;siL;sh<{Kteu2BGo7 z2-wSn%tQqtOJP{;9fXub1R*m~vC>jxq!$xL`kq)hqF1b}e;zz9Mh1HC2|wtmp+3Qw z6|D5RF=n{|R?vG-_mRp(eTFp?3L2gTSV8X{&Z;$xSi#bTVp#taj!e#~>h4hEb45eWO;!u<)`$=X({SiDiMg}%B z5~k~^p`xCMO|Y5Ke@=90(x&h06Jaw0jzapwW`@#)0&ytklKrGIp@9EvO^|z`b3QC| zm~lM9JAb2jPl5SGNUZcRF=p!mte_>I?jxCr`XOtEk+Bg@^tpw!-6h4ebn*Go!& z2Bz?+oZ0jk8MHrwjz{8iK3^fZzY?atM86XXKu@5=wmUOXBT2Bmny^$)4VBhopz$Ht zUIik8pkSaM({-j^;sqox5RsfmG^Cs%k})O0l9|x6LBBQ`j|c&(AW}{^SK5z9g6&nX z7vLxeL*B!3Vu8|5L{+aIKulL_cn_i~ya#a<-h+OVgOhlWV%Fab6P-{1lYsRgGQxW9 z2UtPI`D`NMB=rm61;*Z=?}D%n#t!xYYnSt|9A2QLfXu|}OET_b?7EN`tMpEc|98U_ z#Z7!d0h|u?KS!FPVE$u5|Cde3O_Zfqi1emIh2FHs(nq84*3Z(XigHM9qP%H^(7iLO zc3xF-!RNKzgh7bYaV|2k95(qcLR25E%US_Z-Cj z#|$4EqXAL9X}X>xit5sWBMQgC!!MRBn2a(7R9EAuei4$2(JNRhAgQq53UkVP)E;9V zhp4`ILcwGd)%~S16OS>&=f!A1rqc9-o+HXsq*t(7<`oCW55J8X6+^%EkO#k?JUu2T zGCpCgO4L_iVr7kqaa$KqiNd*l?~de5AMlu`EaKgLP?ma%8;Uhvy(^n39C z4|zfb5ABqSg8`MOouVRWZ}$^Y*4!Ak+<;1y&iP7Z7NA8=DCl|?PzmW=U&+HSjV;fi z4UMk!K~kBh17I#$@Ho$u{B=f;GW!bd^CJp91QG0Kl$J~lU>=9Gs|=-Gf)nsx(yvJ9 z7!W?i*|b#85oI6JdYB3DTktRQurKs~z0RGiKOS8L&(ZlpdnD|{HKmzNPKIFau3 zAEkrO?``Q1gTKyNem4$@@SCXf`4t}WKSb#vY6Fi{1|Xk*lIi8I*F0rRrqq!(w(HJK zI&tXk&rGk&dd(NcWUj||&+0ruch90y<8t-S%;T$XCnnB&Fj99G@bez}_5bto5xO%= zOG?gd9U?atqUaAX?c>L0x~yfbm<4ykw+@R&clX4!2gBWUtQ89Q?g+VYaQCN}AX&xc z=LT{=$9Q>FOiY$EMt(_=(-HkHHCq}N8Q39NgP=#uwz?}2v@(&nG9+F1Co6YMfG&T5UD*omq{^qGQg#AhfK_9#p*wcOA~uMo z_EYSbrR+{$cG^<||CQ`h)Y?Y|{_7U(^xWyxR1y1ZYcZ8#Sj#aOf43fqxW-`Slls=7 z4K8QGMike}({qo9jd*Jdx_VchVG#V_8XYvn4pZzXeypH*0f!5w zPkuxX)K+q5Z#eOY$8len(rGY$?}w_fEf%bsjLz1yMhBCcV;>SDuefkyN33llm0{dQ zDq~CAsqD}<)>s0LiaI+;3B>I{)0dkL+eu7se|1U(m)*KIfnj7=^($ptkyYgvs z^o3~j#q~(jg9QS{ybv&^5sc$_;0R57B!bcm%H?OLO0mFJjW=z?0$VlnhelFh_AnZ$ z+8vKZs-Blj3T#dpDX^7gwGttG@ni*gh!$`PrRCy>G5_Lg|E&|fH5F&fxA`sby0#alL>qwF5)`QV#Yox^+H2@>aQ{yE+ zyx&b)aY6|8WlrDId|D+)}5!z{X^P8uTk#!wwmHV4*<#6*VK&9XQ3A_j6caH zUfgAJbxI=%Q>UGT`Ar82Q?iqQncpdd`9T1)T>!HaV0t+?n?!T4A25;YCj3B3ymLo; zNnT-^w}}|P3%sCAoMTF@$LnwqO^M_EtIq&^Q+TTwfNjjZ^ z7a%%?;}>Ahai65q{(`rhG_HOAk6d!aG>VVYZ*;^D(I?vn5Z zjSU|kfblI1)d-&cTaX*a^E=IWNh!*whSG)c`BJr@yo5{+SjS8rG6Jfp&RB$R3;4%z zfRFHxv%LxbsFaKSWBV0T%`M&Fg3IePHsn8qmAVwjz)EX#5#=8VC|@O@d=-h&wn|@> z>Z9RJvP09G6#F7Py@}isVtOR@4pQv2Zc^+%-TM{jhn2m4h_DCG=-$(E*?T)e-vrA>2GquE;^ju>WzNl} z@vPQHWQRQ)`;O{kE?AVMU{O}y)t_c|)Cm0K`^SqrwSJ!W9E6j=KBGA2J$zx2eP;Da z_`=KHd404s2;q*?dbyoQ2o|15#xFp|brzI(A6q>8lK8>91+&|eB6Adq>=BX-V(NQ= z$m+Vg?{UhjV|5$5Ay`+%>VCYCl$o@!9sFs2E9p<0I!S-Z>g@EbNz?2`YPB#t1(6lL zfyl~4k=2V0L3a=r&}^Z^f8&eL+*uOu=jVO5uw<6Z_$^F*)tNsq@rnXh?`ML#`RmuM zQ=CzNguG5suYeFTsAT9xq>?gjnv+TNaUu4l9EANrB=C1qoq)eXFQcJd9SFHnxB&TG z7D9f70=k<~DA3&r1Ef2*PBc`L7+Mc3+K;BaQ%0SvFrI^_y`w=l*l^m%W2;U@Z3*?z z@(r7e9`A1MZYgzEhzq?GWwptuy^|ff)p)#g(f5cJiM*e$&JbhY_esyYtf!NCBkBa^ z|DE{Nr;XIs#&yB!c3-{kw`d1S1Bzo6S1rrD5#7|etm5vtZ7AAV*lX)s?T__rWi0ERHk|CPBM8oHg|qbA667jBAw3imMP<0HRhE`=bs_ z0_E#@OTfIWUNR)F>R40T1 zHuAzqZ8u)E@TQ|TtZz8`z8|d5uIkc{q7bVp65_P$B~IYuC5#OCSZ^p?9x_Q%_V7BP zkR23f^~b=;PK|$swbxm`cv+@E#`I%hM@JEI0AECkII9!Hunfs^VLOr~Id8i9I&xk+ zybMCou#6Z2S!!F8VZ4AXkRIM7)eojAkS_#4Od*_>uF}n%gR~Df&mv^RO_CCD6T|)T zO{6mf7IapY<7g5*BiiaL=B1PI_n0RZo`@&2<7A|Zyi{k7s3#SVvXj;L-y$J9UG*XQJDAKQwT5nDts%!SQ$W=ofqnf=(V|WC4pStsdULHUOqG!V@D4PF zM_CC(OBDsSx4osrpZ4?EstYy?ZiA4)1y8tn$Ybj=;^s}#fWH1Fcr<~&AP^Gz!huj= zQIIxatkNYYZ6eJNc{2e&!J7%!RW4XpQ)72$2r z&Cfl8HR%y}2b#j8tpwtxJ~DWCh;Vt}QYO{=k8+J%a|G#vurTnv0(IT#p)8U&>6A)S z;|QZk$b{rgAa5uI2zldDz}Se-SJVs(FH5LO&pP^6MzXDxzw|?h_)3NAgI9(fnH?BV zrDUWr{NxqG_$dqOpPLNYpyfT~?ze|$FxM4XO`0rIG;g0}g{g&+{_ca~6_v4*W)*3y zi`)4jJw1M5^odvB$fRc)EZ80ASZY}>};}y`|`^oI{wwvJbsEC&2 zT{>P>KIr*ZZ3(6id^nH9*vBl*6voS-k-8~vmnTUVX{Zu_QlkWb*2XzrAOY!q1)!2* zgNLJBf0ItlZ?wOO5^yVl&uJ`$0Odwb&9HS^2xvYJ2bCepd9CDVU)MO>~>U^la2t;StG_m zQbKD%r|plz2VXp}8fg!?Ma?Qn;X- zOYg93nLV=Q>XXW*H)Mfk$#v6;3?2^eBOp%OsktQx#Gk%vpGlI)QFf+_0a6sAR@qCt zt5|fLHmSKKNY7~E8;zEvn9KB^Sm34nDYcu2*^ZiAA2_+bLEbuH6dNnK<62WKBef{p z{_4X~Y&Kp6$RInyU)txIskUk z@$&L}ekUr6AYbxzrD9;Dj10_y00)W_6iPQH25W6A2{yPx67{-ZV$h>{F)=T*ABaz8 z<+j}|W(Q8Gh7{MTsa)QfZR@nk%WH7XojaMSmk7RFFHnwGQ;kmyib_jPmI);+%e>a0 zc+#OFnZtl2&%&fEa2Z0fwane*&Y`L7hf`tc^GaT{y*q)8E7@U#-K+J~^7T|%O&0@u zwI+hP4I9b9fRNT)gU2%4LW<{H%362{8FzE$6l20O+?o_p1n(}<&$loy3tU4i+kE4L z)0}swIhbTh318{65e*$iIMRLh{>Vp%UcPBWUC+F;J zJ)QK4nNzNA)%SAJ2PuO^PZd&grI*u6;+~xF-YT!pkAudOgQETc!%nkB33D+AR&isRQg==iE!?RLlwUBN{V}aWv zf$uAlaRZg*TC6DxTuksI!+6xbs0oE~a`>mYFns4+1k!9kJq5b!c=3HTntEC-PQP-Ojmo9k;|5X(dm7E%Rl zGDzE71lmU7OoZctn2Xo7^R5cG7>t$S+6?InmH|#_1dc0Kl;Z*we66@q27}yTKf*#d zL#_x}{ohGghO6gH_UHazHwCP-za?5QQ9|&!<3il{S9k&<2fUP(3bOKfUs`HqLBh)?pBMmuryIr2O$jrNo_cgl~wF4h&k)bP{vBkGR9SNpgKxr2gupljP zA$%1iEwYD-+(ySkAi5R5k2ESflSZIq?o8xv)r)fpsP^_(y*3#$(oigZ7F(J|Bm|IG zNUW(}9Ewu+*QRjAIaBL-;k3zf1=HHsE-2Ri5Z7G3KJS&i_4*q6yFeAytC@;%&6z$N zZRNOTNLydIS{pZ#1;EQ-TUqHMH%PeeHf}Luq@j!(;+97kN>xc{oeAVRo#TrG3dmsjsi_#m~Ce?RAt@0JvAvcs5 zTfbNVL=7AuQ(43Ts9(~eB5sz|#}FwtS-ud6`j#(9ny8-YUA{DnDqqq>)KkBQu?*7P za8$p1bgRhxdTA2*b~uzZ83}z07=j5<;q|Ux{%(z5FF`dQ5?YF-c>Q7-GCcL7CRjWP z2rOPegD?RNfLeZ>+~Guuf{RP+7_n$D3mp2f0M)vf1i02!FLHArbwkv;2oEt~#m0Ws z>YveeZ`;v=obRu-9ikFMs_9<|f&j7OB#fD?1QGE5mEhlRIJl<9Ebm`aWAa^BC97w9 zTs@QI`}=i$x3Lrq7b%-ol8Mqg(qUX*r${&qdz6Lr_d)+YtNCMHSMF0m9vu0!vbGW6 z(+J=t5Kpo5%qq3sV~J{0R3HJL|5etG z@DLL^Kor3fZbgkBG6dSYt|$BqF6RV(Mi_2-0q@%@!x5~fS9aaNb>!swp(xypwvUs= zo`zmOE%OlP``zeYQLHtYif@Zoyo_B0*nKA>U%dM&T*+>P>&UV7Lvh48X9`yc?)Q^h z&(}|oE|NfzB>7g{XjSai>>F0QjufvSimcue#$xxWo8o$T5wxy+v5$v&$%t8M`gl&X z_a11(K`P?9hiIFbht*F|FOtAc@K*e2(p%b@Oojf_Jsh#si|_Sn0de0zXfKP#sB!4I zj)2W7l33S2kUzc=<-MnWAV0BHhYSBdP<;dWREPlgLzkVNA$Z6h_Cxm@3eAVYs&AmM+#$4^6RU_mhz*M7X8v zy{B)AcNb_ooQ<{9<2518{9YN!5Yo)Prqo~I*pvv$_BEy7!?=I(ZQw0(KfHu8yEs`P zHHEEF>;nipa!@2WjQh@*?x?!Jz0Dgap%)m@SBerP7*!-StRdgIj*Q*PPmChWWtGBmY*48 zqY7kGq-sd_99?FPk}+aJ89`2s8}N9-bist_s4aupSJjx09)R9dM@CbzN2K=1IN2$f z0>(~DQFCjzd2``mF3Y#8Zej+6{H80Y6=)AD98^DaC^BVB(<$W6LyQ1;x*~?Ge)AWTyo~}1s|@+mK&mww%&IRXc`H}kzJla)@C~WnSy0Pui4O;m7LWx|YS|}a~)gnM1oO^5pNM?Kq0VpNz5S!)O0PIUpRZPI_ zL-y5BH?*V>v(G~Kp0kFOg^`4P9r#QX8Uj(k3dw;e_r?QXC1-UBW<ymq3x6g93DZCc5>rPzmRxNI|2hdO{ zu)Z2A2{kHeZ$x-IYoY95m8-KBwhVK#tAc5v`#?^c9^UL-I|s%t0dk|UOR%9YW^i-2 zF6LJ6gZv=Ak#(jF`2EqX>^f+mg>|Ni(7=ga8bD$|_Ag?&KxR^4O2vZJB7-AP;WsVe zR_`Z*c@;9Gt!14}ZllZU6jESP)Hzy*=!2AyTxjS(Dj^&z0bIcDE0N{v2p6zexX=lP z6itvHs+9H%_3y!X3WQ2A!CC|HHK$)|t!SR|sL=2PNj^fALnT!VelzJgBQSrrIRqh#}X4FgU1u*Hy&tTd>G3Xyy-ec2f~{oN{}l; zp%<@cw9JRp&SB@)Qd#;H&h#su)a zXg5V5v@n6tI87RBuS8w|ouOiK5hfh+yEUvc*>w{guY?pDsv==9>^*B(E}H=P1!CdO z!i8V(cGe_ZPz~XNz`xhA&J-eILhVNovo|0U5)gV1IS^z{48;DOm=QIq@QgQ*QzJxy z)Qv@f)$PoAT0@8;RH*LQLc?{4mEgVlsk^ssnqL3$!cj=Y>&789yG|jLG%2i`3Sd7L z4B>(<5bRefo&&U6gha9GVVzJE0^LCVM2G?+7&#DyR6Oto^1I}WD5T;UQAkw==SA9+ zCblPFAEAVneYQv>poMPB_WJ)&k>ma)VPR;6q;61T!MedAl~7`e2^KPP1j(7s9L?Wf zI5s?GUaa(;;iMwQjcpy&uY25`lx0E9BZSlBTj$J#?Y5zGra2IRbDFJsa{?}6ZM zGZK`q!WBoeEv6;FL?`4~gO|HH5!MfBgWcJ6^o2bLvlx{b{kiHP7>14J87S~NOq*B!$sflPRme!RB0j(0GA>hY9QxCkTs!rxHB3Om# z6f&!hg&bHd0j&_69FfvN>){t5Ev~=>86C79HW|`U*?{bW$Vm590x|Y;9<~q##$&`- zXoG2U!Ea)rA$=468H5J;s1xL)D5kXtV;Y+k2${cQD8_)BA)aiO-Dht?B!I_J>I)=b z6ORK4w7Bn3k_;qhAjl3R@Zdazd=Q<=Dj`e=`m^MONZmxmgZiPQ(2?^Z>j7wU3f4#t z#KqQUGXnPs;E4MP{j^xAdL0Q5>82q9MEM+OPKr{Sh`i8Og4f_eCYG$}5T4dLnOZV& zBk-VpD6vA+pT#T0{aFE9!Ub$W$H@f11QaNptbHcU|7g2=o% z4{>=bETLe5Tvi}-1RO)#3e}p>3K_162#+@R-2o!0ZzU2*=+Ba5L76R1|8ako7>Kq5 z@xW-*SnjHmX(!lME@U5`pI{$ZM#FIkAU7#8vi=t#GQHL*POmZ&wOb)3?wEmF&E0S&CQ$DI=}K3pRfz7||Ev=2PsupNL2f z0*dl>f(9=V5V_d^4A9}e!~NafJ9Ivrhke_-fQOtA84aEgA7vy}2u4Gw5N%)y-%Ji9 zk23a~5jZ8rhO>A$VD$9s#OvXp-n>c&l{hNV-EDwfl9I0jj`s%OF{0+cy&m#VD1J}B z4J>2fB1Z?*kD|J^CSLQFO+P%G z9fo@4*VkT!E3Ss2wJjlDuYooO%r~3D6?;$D%jt*3*kM>qFjlygUIA^t9IPVs;v7Pk zaPYwMtPvgW|2~UN*Ce+`VcN;{8n_An+7zxhjkpuvv~?NxJ=*kF3afuloCZ!-FV@-} z#~`;nD#{7U!p^y1+A>HDh-uNje>*4z_Wi3GUm_^Dp=h5Nk4lTSNl6^_=w}wkrvOt`qd#anqH746&!_3epg;6EcQgr>nn4xk8L7=9tXL zWvA;C8wM`0KZXk4-Wvv(Y=5;VaZ2>()Q#f!XQagYtlanDbjz+|%Hg(~l@3?Hf&OiK zf&;yMwl4R*h<(<6N(4tm_#d2-_c~QUcmv_73cSyXC+xM;hJ7hkVgJn`1RTY2(ih>) zA>_7@&xQwZqGR=!n>XMg{YC%737C8Rd^^d#zP_CR-aE_@hKO>*-Um_ox@uWnL(@VCC#OXrJnu#n z5AXN~FK6!|^Ch#ZJ2x58@V+IC75pqhsd%0;!U-PT+C&TEMW-P=U|abx-t^yn6|T6! zfPM7?h$kuf7&Z3QaGXL2tZ#s%eYT^n1p)HGX904ebdfAdA$q(zG!2BHglQZ!4TSh1 z&XB*Qf#N5chYwOf>f7sAGlcy5#X^J~`2V%90esX zJq`&DEkr;*{T4hVD$%fqB#+P_UH3miLrD2AM%l~Re+gsRMKSha1QK?AAp8g<+%NoK zhV(5Nbh&RugrDD&TQ5YAP6?PS3_rcu3AF|BGbzZEw7~m35aBj43q)Y7YAiqx5Ifri zz(RsW{k=QVg{_yO#s4RN(2(YK5hWekwr38Ks&GJr^b@q|4` zv5EBeZ}E|3*RYx3V{TTr&I^ z8__&xWHrTyIN8{0t~u~ri<_4Li^_F{I`4MICUTnyO-{-J>}H_*HKg&B+@NywrFY{gXKy>|>#`zo8<|7^>miNElHtWvPArH`Y7>y&q*o7WpV=f9Mn9X( zMrn@Owgg2TJwXS0(|TH33{uN-Zp~3bEsmfTJ#I|^3MOGk<%up8s0EP{6*FXlgw-O@ z|NjJzfKdW@pd<)*Zb>_~4eyOzTJ)EY|bmZ0%!sNP&ddN)sv&Ml+z zny57Hw(mH!1>XEdDvy;y;dNH!wdnKcL-~!5^CBs{T81~LFp=Kfnn>rf75K;B1W~-Z zyUQeK9qqIVes@D2pIuAuYUy(1Iaa7qXk9Ii{EzK4UQ1UVgVx!2h5sYJmEV5Ym&Uz9 z;kQZ9Xv+M?(QOU3d#_ydgA3>rLQz<>e6225Ff!6GA8&s%={fC0B&4j3>F z?(W~M=3=we*?POlUgup7J6%-w+wb-&&3m@<^@bsD(##5qmc(1p+7cKcO}R_QsV#LX zpJDytWWou{@deTA^nNrN7BKASJsmxxaTi_{WUQLmqPn~D=rWr;kLhQMe%w&PSrp&; zNxRF}vAf_3!>d_>>doVv$+Pn6P|o7ThPNI2tCDOW*Kp81C_5*5nHRDlB9>3|aMj3^FkHY&z@%}`i z@ZL4b&@{VE_}nXweBMxMIJeS~#y0bA<;qY!DG|KZ;@4aXyODa}AY;ar&6VAQDtXzA zyWBz==aXUJN8xu5zj>o>0>T_f7ZHz}2y zr6%s7zRkMt<=-`_eL<65c}Z%b6SXSqk=OAq=_d13$G2JjJs;GY%2FMxvW|BNKUlrV zl1XhAYw|qU)$8N5)aHX-{r-$@TAbSaCd;>r{4kFp)123y8Ft*W(5o46?PX-VPSvPr zci2bQm=Q%icigke>xtUI?lJ!*e~xsYexmlj;E#W|@e{Q^f3|tMw})moRxX&_-qf4{ zs^WT;0G;T~=PR0zch;Oonu0OskGI3W?NYDQcpo~7l8&gxI7?OUW|9M5f4pd?-h>8O zKL|mgk%yEvQApaIv6NM+49ey|LZdFXm?7j=;OSOd$zY*CUs?gPq#>Na=h#K zT+J}4CF^_olAK3fkGfw733mCdKDfKd&68W#^!TkqvOre+&?t&+$NC3Ble~*QUOXhb zpgZoZ{y(?=*Gi&UyD7z!jD7@xu*-s+<$Wj_-D-BtL6ME{R%5*Pf+s_?njv&at2zoG zlp>Oy7Lsh{Tm9jb)g9~a2aWOm`Qt@D*_qwn{d4Pot0b6~`_uY6Be(YDtfM>{-Q(So zcV68q+W9BH|9~7*_ts-uYj>&h<~+L5IzNLS>Xp;f{^*7a!Kx2~Z`2X#)vMt@6cVhu zG4|J3f{I%eeli%id&CbW1H!&}HSX8g0qSBmX8&{Rf2$e0(k8(dHY$joL|J;*VL~QEC)swgl&sFYz%`!lT)@vMZ`xn~6X2 zI8k(MW}*bA!I$_LE#blRoyLhetj)w9wL7B>wV7umIMu$yM}G;Ax4u>#Q8L<0{L#BT zilN1Hli*bN5+8R-c$E4^v_)OfV&ack>?lVqrnv;?r7!W(K*FQYw~`g5p~b`>d96|W zB}|G0C(oDo_`QV3bKhyLQID4}@ki}XQ9(r^*>?Omvz zywqHgsnhd_{Fmp|HXo7@zP2YSw3dAnWoX9iY#M)tE>5I##eHs;UCT~x{({0Nh7>AM&~KAHv7BL(Ld9E$@d-aaYI*P zBlF$}txaz$9O0j6iV|z5Kkt|P$nl&cUE0R|?dI?gvtmT1d9<4n%fY|$dVYpr+H_s2 z8M9%8mt}OK63dmGHX<>#2f@xpsGPW?y#l7sJ9aUJ@1!$A=3#C0ubq&p# zyTrBZ$!QrXtPFqel>BCCPK7QVNdO7KUp#Y9w2Uh2zQ0v!zPJpDwpusRf_X;V%Q@Om zmGxABHa<j0aO!!jc&+uC1P{R^i#K84GAD6AErG;LeXtd{St`*;Uj0;x^ScP$&SHAa(v*oQT?ml<5Q)xr1{?+%6ra6&u z=jld<7wfJRv>I;X{8HS#;aca#jjbBj-y3epq24}Eu~|UNi&#-;xXp`wrKOwQpdrgu z6Esx^;HE0{QHB2*4xgZ@y4S|q-dZ?}=)LX>o5PSBGGM?&*#QH__8x`@e~((PjhhV| z%hV@iHJeGMr+f-ER){nC?L>uxed%@jM(XQ@5=J04IMe*<*1C2uj~(R zH9si*>T=hD*Nb*f&8OcmdwF7pTapiq?**RN5XRlC z9@VIMJYF$<#nk6KXWMlxqbJSY&~eenT=w?MMEkru^XIAzv7s}X*$po7vj=CWc34sm zr3`8GNICh-gBLq}4_W2J-;w?>md>&&voMGe-gO)lOJncY~r#qQer*xU1uZu@vS zqqyOE@az*SHk-$eOt_v1<7X@XFn`geSu?I_QEzM7Jb$e+@8YOq`%cMC%6(}(=ZsYR zvtuJ$(j>VB$DdBf`02yjJu|+G*mZC6V7tUynr5nbGe?}-D|URtW6q36 zM%pgV!$K*U?wwQMzaOew0?$0AM=Wu7{?s8ewpIGXf$+}%SICveL%F{1!DujLCvCPk z46<)ggvgeLDEmHH$1=81mLdBXYnDRU%6cp_$gV;Zk$so#AdE6NW0`&%KqFb^`;Cdb~}?5b3> zxa7Y{Iwju!yFYY_@ow&HxFiqb1n)I_bog|Z2IZ+p3B53~d|nz_fTQx30aST1!}<=; zTjOFF9S{RP|7BrLw_|euiZ-(pmn+DM`o*h@pAc4COWxT!+YXEbmYvqCpf#&|_WDyM zhVw+8u7XeRIY>CdFiiP@XBM7Ezywu zN}Dz2ZSn}Md1;#MaWFDxIXUo3q?}Fp)UyCforiN>SJ|9G*AXb45w=ABDPU*ArQBW< zdHI~4Q4#rFWxFZlYPX?o^nN|#-@)FW;g=%4sr5TyOij)+DcASlEJOw4>cL|8{+moq znj*S&o6h0JbaBMB{0wvCqe;M>zTTMI>hcrT#AmHsRJ(d-a>@l-VeUyj? zq4BC%iW{uFkR|uF4Gr=A9~m>^;Jd}%H7VUPTGivqdUAM}hM5FIMQ!H-cB82H*>JMg zUI~iqFESf9P}pWt?g%gNRX#wtAx>&VPPc>i!b>3PWH0f>Q&5IP>Xo z@5AV5|1Nr;F{rhI9faaY^aKq?Ql zQGG8vVwkS}yreZ#d3a06t#m*3n6NB7Y$}{vo~|UG7%h9sanXe zq5_qRbco=!DB_b&R4JLr)2mop1UaI2)S>qA0`#FPh3{tj<_6B>naP|?uFiikAl}Wc zHWycBrMKv$Au7Z?x5|gsj50M=A2SR+AGl6-HqjVYkM0`4c30(9;U`qa^atO&b~x76 zHw_(^lP-``REAjw#Niw8L1GPn(~5!)(Bu#wU;83)z{VX zBC}-blL3AMGgHM;UkfzfGX=KO2mIB)I2M*(g^kveGbOsmqS=Ef$K0qNl{ss+iN4G9 zR$V4W`1kFlbzo9#gCWvXtgG>2*^}<&b70->fX#G{Q(NMfHTY>5#&OFg@o4F%vlST{-e5B*`i74AxUaXs5M+>qNfc7~lZ7V11wH^N5+F~tS* zCc-tBy-nFVtbLnqj`oxQ^5CL5l#U_8q0f$=!*fT@J?KT1uCT;0nicJ#YFrm8z*L+Nz$=X~%V+3({GzesD&X@+O+t&H7R?2W604pVh^e_?ZYCnL zz^w(~sccB6PFu3rjJr(lDHfG^)}>(DC2O;~! zs_Ek36P=b~e0|20;H10?T8ZsCc`fA^7c9g|`bL_Wh#$Weut*5V);Lx-u$(TNgY6** zK`u@>s6NQKq(?>QOS<<0qiD_1YM9d2-V+~0MQx!n4lSw_-TVlfgqa&_A0w$hZZ$ucUzTa5up5c> z^11cNd zjfK;uqs%&|v~_EEWQloHh+1lKqKs|Rj~CJZ-80#`+CUMmZXUn%Ok7RtyJ=(q0E7Yn zpeIH6k7-tJZU+rhhMtnkm?(YyHVZjUY(AHYCd3*l3qh#UQ+R*a2s1Xi%Add~gPfql zpKRC~*6LO1#pNzaD0h@`%Us@+mX~Lv^|}2RemW7$mhD|-*{9Jhj_FJuEd_hm?YQA% zVe!omEg!cc;bIjM1T`V#2AjIgyMz!FWl`i_%*Jy^XHFfxv3#9*Ws0QEvW3z@%uA1F z>}N2q(Hnb7vtd0C4cQ4TajR$TF6{s5u%w?NGFeikK+yO+>7T;_-N~&V6sTDg=oFTw zK~2x*tE*}0qm}w@Eg;ca<@%OxnK3ZRKeDGqLTj!r-l+nd%VxgNWvoA^%)0qZ5^M8t zLglrvPKzU+7wT9I*6!GL*ImRQgf)8I*7Bm z7E%ItuFWjTx@QHW#EAsbt%4Me8&d(7?-L0E^TdWG^VGVwkn1*c6t%~|PAeFS+7DY? zlRL@spqKlP=`_lVxh&IeNvv3LzJ}49C4F#W$a2VVP3q4x69(g}!WKF=_y`)A+wEn4 z0Rt~02*>}Os49m!1uaN2&XST9!_P9>xFTSOI=*#zd7z^p_f!azJp`p3HyU*_UVx>) zP-e)ynYa9czr&lUAz%6{^ZjGp-79xFbnL>p=>nSN3I>v1heQCM)UfKo^KG$@!r+dYX_n4JCpb8aee{G> z3~u=P(eMneYZztvt`r^1WT;ifr$g*teV5P~Gn+ zTVy9x&-OlfgqyLr^Gn%KNZh>cPEx~%qz2t#+3;~iI9a>8Ivr?%O6bxd7o%^-DX8|z zuLyH4hCO)wociP|vWAp3AxXR-JO$0SexcqEZ+(f)0yJwQTUYi+7&t}8Zj{g!n13#| zS~EdPRwSm|{zEK;tn0cko;wF!xjV?ht00;o;UH=23CfJUcJdX!2Uo^x8VGw|NukitXRrFHE4P9R3ZrtbigTcwVfZ4cp6 z(EDRUL_#GIL>A)oky3{en@cWIr!iS%s7o=cjbOf+c3N6}ru#`_ull)ta;O#=IWyqs zl1}_sGqn*(pLO8jMv)}ZPs2pT)x{I$;%TAp>jv{MJ5cP1;P>Q8Y7PDw2l+FKL~DV7 zIUnTNe;fUhr7^lhnxRDs3h;Nxw`b`OjPL>S2>81(QkMQ_92jdRQIYn-{~zFByL>nf z03Qzl|LtHXPx-9_2VamTo&E=O_@E-0CD}QI{T#{v(_h*jJO}0>r1d88958s;!(g7j zFOmk=v6b-v&8{Ti(q zGuU1(-($aLp^7}Ejv!&x%0}A)+Do-iU_ygb>&NkorjD6-2ULLuX6Ztn{AWKCDtFivgzKl->R*% zgW7eznKb5UtJSMp&I2naTk2M)TbQ#CpPn{sqT9YnSMOXIDDJmpm5oyEz{6Q?5o_~D zoSEp?F=W)W>X%QBi)X9VhP<{uGj_J+hPpAqN@k-{wpS1GiJA1h`mBbRzYMe=%I#ja z_LlhyjnU4m=BHAfUR68~FTdQ_p(~wso^;S^%e@_Bv1}<@YLM))u%R7|UT@D>QdiaR zcKtNUB-j4u%SmsRv`CHW;9K%8+)G}}-t8w>pM6nl%xg~l%^w#l`PUCN-$(i7-DD$D z69cd&K={J{41rHnXY1WAYJxF@wmwC!Dy@U>)_gNyfVgmsDjIqH^u2Wt=8Rn0d|-KX z*LjDP!=f)|OutkyYrgicGaM%0Iezgs-=^jxCzp;qzH8_Srw_F|vm0`j9Iroa+%{#T z^0i6h#Ikb_=l+__+vOyoC_dz{{Ls03E{zO(zk|D0es%oQ%%IKVS3ViyajGNAHCfBx ztkQ{b&kVD7>CVn8stefn>j~D?gyy}Rr$4>-i%-s7TADsHj{E(K1-l*09qUdtZjG6~ zb4&NL@3ya@9THDP@+! zYx9n+(M{o}O*!xHBk#6(__pr3FBCNL4-61U+Xr(b^_saOZnkgPw`KM0Q!cX)T9~&F^1Ge9cK0e9 z4SR0;hRG|Z42vEb`P(nA&OKh)kkh^}z;JER(8MUk)sjqu8=1}H4$Lp>+9~;4skzqR zpb@iXyee{Q(3mp6cB-@2j8g_nX7734vV8U2(fS6<1DLG_lV8MXW*0q;%dv9%&dj=V zMq&A&dU3;>Nh4n5Zk&F8_B-0$Wo2zcsJ@!Vn4PQrW<(r%t~M!r(RML?%k8o!ORCJ) zJaVag=)#FyGWweNNQuCWZ}#eT<<6#jynCdxL;88u={Z!n#;0K@M?Es@S7sxJ&`mHN2Bv?2F1Ipuz|{hS0AQ# zcQE)4G)_eh1HJ1bgV(9XuY(8b)Dr0rY1{|0{EvlnIzN`tU2jP5YT$Ea`Q2Oz2CsyY zmCH+cLFZP`_?~qBx802}8-x3i3oCtKNMm!#xR2@i`&)Tz9=oBLl|pOnqTE&O=wz^| z+>aHM?)PDQV;-kDyQwRT%5P-crSRIDY3KO05_AsNjsLNc!f(04Z|I_N8ChKqD7-?$ zM83%+0MSL`)q&(&-T05)_@63dsdXBR11r?vEXH^2ZhmIzjRWWe=U-y#p|MGy^2hE%LcmXB(=08I60M^NozQm z;r;qq3$29K^{Zw6htB;aE>0!S%NM*&peD~fkuj@WEa&~>jQ0;Mm0U`E&`>E_#v4_e zWbMj3s!gTmGStzmxqLJ42bTG}X?N|Y_D2cUwB|E-RnxZe@FPTe(Pr~1+*dffT%#$7)!ZFbF$ z%Rd*boqgNH;+I;Z*|$y6i#C)`W@nz9q~!ndXdwH7l7HI>m{cavQ$FEZ{6phiH&Zv| zp^MRNj{D72je5%Y1q(JS8c4&t(BT$jIfNXg{pds6{w?o$ z^^T;Xq8;(KH(TtkMVIfkaPMxe&)E?lpJTi$DfLw@x}b@Zio$Y?O~Nj}*x__D99^Pq z*sVL_HNq~(s;{}6^X|vR8gS7qsISd=R~gsrU$i}bKAIF=VA3U<%O|^9+TJwXqO6+i zf-d8(ds`{9-v^o5+TJof4|hM-GRdL!Igz(+7wyptUKod6E&x=A`Rab^;>+zKHP&RjR#s`Jvft23TC-o}<-GVvZ@kA(uWjA2 z3-Df6Uvm-gQZ(SATTqJe^3SU-*gOeD)}@IqM_+0qky(arQ9dpm7|6AN3z}JGO-83l zNXU8RTsbw;V1#DDG^YWDm2Zp$p9F7_u*EvxjZc-cn`NHWzdm zcb!(L%-xa1D%w#8>-|uRF5hk8-`&i~*-;1U1uZPhMHi#nJohA4Aaz|`{L>e^Zlx}~ zujZV;J=%uby1h<=e(`kI%<h~b@VW?P zF20LFoDc~YLzBJ0iX;+oLb714Q+2OxxMMY5}E8} zf&MXCkuupX0M*d;){^<~CWY)}XV6^*@@~=+P~(N#9qx#sKsk2+aHdpQ0%%a1ws{&L zXzaYZIU+3Q6G&@W*u#hJ4k3quF`ht<+8s$t;&VRbgJ2`VYNA1g5qV)XX|I(Hn`B4b zr>QeToet3!4&&EN?|$t28%1_6Mu%{~8@Ib7nbo##cZZeKtWpU%4AgD4P?iAswjHoi z&I7Aj694p5{&txCOieWCA|mfhO&T!zT&eOI;BIRjC27ALDPD z$8*VfC%ZeV2XKQZz$Ix2w*c@)+azTIFkHsjdsQko>`3~hXvby(FkHSX<=ox;GH1u; z_?%ndTvGGU#ppKMJ?R$!ygB~qEgJxwhc4*uE#mIOTQ&eV4_(mRo4){H5o7V)&*lxw zxn&$?4Nl7`5?!Kg8d`U32K%X5D9zebPTMecsr0zbC$~$@$`%O=9ybZIM&<{PBlGKO z-SJw64tLL37lL*p(FNVzPTUQ&F8tBy<^fHG>{w8GTkX?Zj=ZzhSJbm(!4Gyip9nFy z=pWOVchQ>Bt(m>vbknq-O$)8gyE_iQO8c{?k+>#`dbE4j^D?UE2O{XS<} zo}PVE;G6eZ^&!;SD7pu`UTci2-cyr6z zqS~xs-c8v#zq)&!s>#(mm|Hx?!h%tCE-v3oYGg%dShz{nr9-)0ReNH?rX73=Gp*WI zTg&ML{vLAox?Yo@cM_h+hbMvqUU*3S9n=7=Yl;1cwq0-vjtRTa!&0!3~+N=HJ zo(DsI{3%q-YWc^IKt}BBRlcE8mA(&0jSZM;b!dO^Z|17r*J5YPwo2YFF;zo(`uqK_ zt2Rt;4u29h!~J!&*3ad04xX*C4mG=X*KMxj>G#%QDIHp4)FoT*erQ#UO0lqyx>S(8 z(y_&J#_s9+JSNs}Fm_BUU8?y@O4Lj9(G-o{(+7Lr+#0MCm}%~O$x)}Uq-2aK6=b>a;NTCQ-D}-I|50ZM@EaF0=Zs89N8a=>6oSa&Vw3bHKJc z-_H1fzuM}Y`BIyKU0ZyHSezX6$aeWpzt*fCtg1OCHEQ?=yWxs^bfn?&frCPoCZ<-~ zyzx=LkvNn2tC;%_zib>Vd4K>fHwH$o-J_!bBjvky<7p-Ssht5?4DiG|1G?u%_kk1JawY=3+DqQ7|Q{j88E zahYm=5Yw+8TjtdujXr^qa~_C=!$`mR82l&NsG0oc=)ImZ_CFB2hi1^UNO=DC^s>X^ zS08|&N6Yvfh8b9U(rz7IGg?+PP6Ad%v5=e&tCIW;bg%u?V7guah*VCMDTze-BPmiT z7`VdXq&yPoZ#AoDsA`^0jar37>ZB8b@Q)2uItL;w&frI>QQM9cA3b@DtK@F&FfiI0iPT9a7eSg7s#E|Xt@4S5$KxJ} zZAOpp29Z{szIa@`^bv@3vP|`HB+?dvNMYoh$710y(r+(-cil01v1;5@0P1ETxdZ`y zT=Q&+swOKn$^+iix`ZVK)(%Dl1i&yS?x3H765%Bwi!Ks41iXjzIaN!^a%i!m#IDlK$m_Zfv$v+ zbDoNY!$`lMNhwE%z?@djI&)x7omrtu^U|vGt9@)?Wa?9~w`k6Ai-Zr=ryraVuYU?` zP>>n?GtB9Ci*`B7(D{(Fj^1k^X^qc`xj<6mw#4e-G%>#rc--chn5H#69%qrDS94lE zSp57mfTSq1Js2Lp;hc6lc+H88sy0d>rUZ+VW+0{k*`$4co1GQ%tFp}A5E%JF0KOFF z+@CFW56zhd1g$x}EL8j|jC`Xi;};4eSZ3ooOBDxA7D<&=K_MB1%hr> zWzIna-N9dNdG6v_@h#5*()TjeXW{YbE@@-VtvRt>)n+a{{>YAZ(P|^tzG%czM>HPw!_Zk>@-bE)D zy?hZ66!c!}6PpBj&lTIe69n=B^j>@VVz_u|F05#=Om#TC{nu6jL1E;aJh5;X>Bkc2 zz3qeDsB#ybW|&h>J5=dYTJ`f`j{+y=Jt(YMgG@mO|0E2Y2K8LMv8e@@o9_)(^PU*8ZcW$ChF?{ayV z^BD8!3Yhag%(-IkXKN~@8#5F%zfJ#Es?lx~!aM2O1|2=1!?W^lbiWKK-D-Hj0tG#@ zaUc?%fQ0XmNc@;vAQ3qckg!q@#4KfbD&Udr2FZdu5dJ@t)1Lu)nxT+3+)od*ELkxA z2xwVMs*xJ6^mVcm3DkzaIugQsUz`LT^82W>4@?`#98wSZ!OQFBxlA6`ha#nPktm-k zxrh(zqf3!^m>x5MOOlp-3BpzKf&@jbpMp5g%ZKQGS-&DV3+wiZtVXo#E6l$E=BMZX zUpoKm$@xFi`M=zT{uY=bx%qFfpf5;MB+S2ooBx>57ekInH}$u0^N%fET2y2-7e>Zj zFztn5s0U{0H^L~?)sgGoZ5rjK~ zVFit=0~|Ev(xW9C?ZkEWE|Z&dZGoI#ijrJccX z;KlX!E`tcX07YQV^P(ZPHfT<%ihMNZgo4IrFsFQaG#a^L?=pE9xfSM=Pp>(~JhTGl zoKP_8IGPh;6BKbpgKZ(S!Qv}UqUR+GP*Hs6r%59UvXZCkX^e}xxn->G-i$FZUx^-J zf}jH_jdTF>5TrDAD5YVc!miKDD-w<|L*~Uyo&@jtK~G~ode4fz8FORIa|0auu80@R z(S9mbFzSd6)qHx)oNPOAvyICn3)e`!-z;(#G@CA#FsV{wwtRm!kYbCj1>RXVMLw z#}4bKb7Qmj{Vk)fF#j`P{teXp$AWsh!+*2VQDfoH8~T3+H~%pqEnx)gZ@6 z;D^emUxYxAJ}0ItSgHaFczr1FrX6FRfC9eZKE&GJ+E?XC6-))s2|yR4Xeo}PWvsN3 zJ{0TI{Fo=8f6$;C&;I}Lqb-vs@Gyom)q_aO)fQxwXXiO*H0_tB(iJYB(( z70@E-OAj(@>!%(;JL3!570p<#65H#vJR)TuVg3y;pU(TtGX9j#|4XR(UjkDUH~$?L z^aXz;3g+Ly&3{bjivdTpoBCV4`yZN+zNol3RTvk0!E_z`c@SzCCL#z)2}5-+homnm zR!$Yh|6cC>M6Vz;GhvFRoJW*oW5Y0A)>7ymjFQs}Qj+ti_G2D|f>VB2!64`!sQXE3 zLBV-yY|Kz7I8RL1lYpYWR8kkkk+t?w2f@M1OBM`*_^Un`_p41N+eAshoGVyMp?ffD zE6geHQGJYg5DIwt2?c|od!X(or3D52sd+I&p@2W}gPsHw@THOvo1knn9&0llJ+H@F z3K4h|u~Sg=%_Jyo7x_qPq29-`VFgvI1Ezf)da{QO361{rn4yr+*bjq*<^|ek@AGn2 z>f9Lp+<lb8|XHT7V?w3U$M$OV9u(LVcM z3-k2O_g^JB(csCf6O_|u?SlHUN13eDF){k<0;Un*8$FkdRX8a~hoHUGiy%Eor&Iv* zAT($u_ioU9LBD?~%0Fbn-vSdK1n94G%X9rLqpvXkLty^()cnVSdb`7ax6*Ns^UoUk ze+W1KubYtmsLx|1YrXI1G03Z^SE$5YB#4omxX(k7>;e(NTYuE&VIE#145@-PthQ~h zIBC37TT`B+BhQJu7vPOzV$htJNF{mB(}@KVlL`=WU+5fo`blvuCKedxqA}XGb7Evs zK$kxTG4Vj;63uTpIvA!m+9U`mF&^c(7(q*~K)T3z1adhN3aXJCs zD9i^*!mH#sPluy12)!?K9y|rR8O;83dhM_sq-6thPC(FL&J`>dYnbz^;KMe5^O-49 z-04zYMN9Q4D5UEXyBR4z8NreyV`Nd@Bk#woT^-=#=+xR(cW{657#cUL1mOO}eIaKfoJuA%&fKl&`?fRqFIQ z9R|k$_j`Rw|{f22Ix0{ITY%kwqEtcmmH*M?Br3oe^gF7 z;U)9F&O3^<{{I@!j+>ic;C*-`sMT^sI7l1nP7z`0cH%r?P!)31EBtfc-q?@H_=QLueO=>jXp~Uq0K9={{30?}DTjblF{p$a$dCh_R9} zwZW2FF1jo|*iD$|$2^^+1OqW9Pt}Qd%x6SbDITG4UAl2&5!o_mMMiUuFA^0hDa8{D_t4d7@0; zvUDtLTY&TwAo;K#A?E>S48Ib+z$tg z(0c0}os{cm8GVKMp8->_%k~#iQ*ctQ$9zSq_y42?{mYe(Ps;siL;sh<{Kteu2BGo7 z2-wSn%tQqtOJP{;9fXub1R*m~vC>jxq!$xL`kq)hqF1b}e;zz9Mh1HC2|wtmp+3Qw z6|D5RF=n{|R?vG-_mRp(eTFp?3L2gTSV8X{&Z;$xSi#bTVp#taj!e#~>h4hEb45eWO;!u<)`$=X({SiDiMg}%B z5~k~^p`xCMO|Y5Ke@=90(x&h06Jaw0jzapwW`@#)0&ytklKrGIp@9EvO^|z`b3QC| zm~lM9JAb2jPl5SGNUZcRF=p!mte_>I?jxCr`XOtEk+Bg@^tpw!-6h4ebn*Go!& z2Bz?+oZ0jk8MHrwjz{8iK3^fZzY?atM86XXKu@5=wmUOXBT2Bmny^$)4VBhopz$Ht zUIik8pkSaM({-j^;sqox5RsfmG^Cs%k})O0l9|x6LBBQ`j|c&(AW}{^SK5z9g6&nX z7vLxeL*B!3Vu8|5L{+aIKulL_cn_i~ya#a<-h+OVgOhlWV%Fab6P-{1lYsRgGQxW9 z2UtPI`D`NMB=rm61;*Z=?}D%n#t!xYYnSt|9A2QLfXu|}OET_b?7EN`tMpEc|98U_ z#Z7!d0h|u?KS!FPVE$u5|Cde3O_Zfqi1emIh2FHs(nq84*3Z(XigHM9qP%H^(7iLO zc3xF-!RNKzgh7bYaV|2k95(qcLR25E%US_Z-Cj z#|$4EqXAL9X}X>xit5sWBMQgC!!MRBn2a(7R9EAuei4$2(JNRhAgQq53UkVP)E;9V zhp4`ILcwGd)%~S16OS>&=f!A1rqc9-o+HXsq*t(7<`oCW55J8X6+^%EkO#k?JUu2T zGCpCgO4L_iVr7kqaa$KqiNd*l?~de5AMlu`EaKgLP?ma%8;Uhvy(^n39C z4|zfb5ABqSg8`MOouVRWZ}$^Y*4!Ak+<;1y&iP7Z7NA8=DCl|?PzmW=U&+HSjV;fi z4UMk!K~kBh17I#$@Ho$u{B=f;GW!bd^CJp91QG0Kl$J~lU>=9Gs|=-Gf)nsx(yvJ9 z7!W?i*|b#85oI6JdYB3DTktRQurKs~z0RGiKOS8L&(ZlpdnD|{HKmzNPKIFau3 zAEkrO?``Q1gTKyNem4$@@SCXf`4t}WKSb#vY6Fi{1|Xk*lIi8I*F0rRrqq!(w(HJK zI&tXk&rGk&dd(NcWUj||&+0ruch90y<8t-S%;T$XCnnB&Fj99G@bez}_5bto5xO%= zOG?gd9U?atqUaAX?c>L0x~yfbm<4ykw+@R&clX4!2gBWUtQ89Q?g+VYaQCN}AX&xc z=LT{=$9Q>FOiY$EMt(_=(-HkHHCq}N8Q39NgP=#uwz?}2v@(&nG9+F1Co6YMfG&T5UD*omq{^qGQg#AhfK_9#p*wcOA~uMo z_EYSbrR+{$cG^<||CQ`h)Y?Y|{_7U(^xWyxR1y1ZYcZ8#Sj#aOf43fqxW-`Slls=7 z4K8QGMike}({qo9jd*Jdx_VchVG#V_8XYvn4pZzXeypH*0f!5w zPkuxX)K+q5Z#eOY$8len(rGY$?}w_fEf%bsjLz1yMhBCcV;>SDuefkyN33llm0{dQ zDq~CAsqD}<)>s0LiaI+;3B>I{)0dkL+eu7se|1U(m)*KIfnj7=^($ptkyYgvs z^o3~j#q~(jg9QS{ybv&^5sc$_;0R57B!bcm%H?OLO0mFJjW=z?0$VlnhelFh_AnZ$ z+8vKZs-Blj3T#dpDX^7gwGttG@ni*gh!$`PrRCy>G5_Lg|E&|fH5F&fxA`sby0#alL>qwF5)`QV#Yox^+H2@>aQ{yE+ zyx&b)aY6|8WlrDId|D+)}5!z{X^P8uTk#!wwmHV4*<#6*VK&9XQ3A_j6caH zUfgAJbxI=%Q>UGT`Ar82Q?iqQncpdd`9T1)T>!HaV0t+?n?!T4A25;YCj3B3ymLo; zNnT-^w}}|P3%sCAoMTF@$LnwqO^M_EtIq&^Q+TTwfNjjZ^ z7a%%?;}>Ahai65q{(`rhG_HOAk6d!aG>VVYZ*;^D(I?vn5Z zjSU|kfblI1)d-&cTaX*a^E=IWNh!*whSG)c`BJr@yo5{+SjS8rG6Jfp&RB$R3;4%z zfRFHxv%LxbsFaKSWBV0T%`M&Fg3IePHsn8qmAVwjz)EX#5#=8VC|@O@d=-h&wn|@> z>Z9RJvP09G6#F7Py@}isVtOR@4pQv2Zc^+%-TM{jhn2m4h_DCG=-$(E*?T)e-vrA>2GquE;^ju>WzNl} z@vPQHWQRQ)`;O{kE?AVMU{O}y)t_c|)Cm0K`^SqrwSJ!W9E6j=KBGA2J$zx2eP;Da z_`=KHd404s2;q*?dbyoQ2o|15#xFp|brzI(A6q>8lK8>91+&|eB6Adq>=BX-V(NQ= z$m+Vg?{UhjV|5$5Ay`+%>VCYCl$o@!9sFs2E9p<0I!S-Z>g@EbNz?2`YPB#t1(6lL zfyl~4k=2V0L3a=r&}^Z^f8&eL+*uOu=jVO5uw<6Z_$^F*)tNsq@rnXh?`ML#`RmuM zQ=CzNguG5suYeFTsAT9xq>?gjnv+TNaUu4l9EANrB=C1qoq)eXFQcJd9SFHnxB&TG z7D9f70=k<~DA3&r1Ef2*PBc`L7+Mc3+K;BaQ%0SvFrI^_y`w=l*l^m%W2;U@Z3*?z z@(r7e9`A1MZYgzEhzq?GWwptuy^|ff)p)#g(f5cJiM*e$&JbhY_esyYtf!NCBkBa^ z|DE{Nr;XIs#&yB!c3-{kw`d1S1Bzo6S1rrD5#7|etm5vtZ7AAV*lX)s?T__rWi0ERHk|CPBM8oHg|qbA667jBAw3imMP<0HRhE`=bs_ z0_E#@OTfIWUNR)F>R40T1 zHuAzqZ8u)E@TQ|TtZz8`z8|d5uIkc{q7bVp65_P$B~IYuC5#OCSZ^p?9x_Q%_V7BP zkR23f^~b=;PK|$swbxm`cv+@E#`I%hM@JEI0AECkII9!Hunfs^VLOr~Id8i9I&xk+ zybMCou#6Z2S!!F8VZ4AXkRIM7)eojAkS_#4Od*_>uF}n%gR~Df&mv^RO_CCD6T|)T zO{6mf7IapY<7g5*BiiaL=B1PI_n0RZo`@&2<7A|Zyi{k7s3#SVvXj;L-y$J9UG*XQJDAKQwT5nDts%!SQ$W=ofqnf=(V|WC4pStsdULHUOqG!V@D4PF zM_CC(OBDsSx4osrpZ4?EstYy?ZiA4)1y8tn$Ybj=;^s}#fWH1Fcr<~&AP^Gz!huj= zQIIxatkNYYZ6eJNc{2e&!J7%!RW4XpQ)72$2r z&Cfl8HR%y}2b#j8tpwtxJ~DWCh;Vt}QYO{=k8+J%a|G#vurTnv0(IT#p)8U&>6A)S z;|QZk$b{rgAa5uI2zldDz}Se-SJVs(FH5LO&pP^6MzXDxzw|?h_)3NAgI9(fnH?BV zrDUWr{NxqG_$dqOpPLNYpyfT~?ze|$FxM4XO`0rIG;g0}g{g&+{_ca~6_v4*W)*3y zi`)4jJw1M5^odvB$fRc)EZ80ASZY}>};}y`|`^oI{wwvJbsEC&2 zT{>P>KIr*ZZ3(6id^nH9*vBl*6voS-k-8~vmnTUVX{Zu_QlkWb*2XzrAOY!q1)!2* zgNLJBf0ItlZ?wOO5^yVl&uJ`$0Odwb&9HS^2xvYJ2bCepd9CDVU)MO>~>U^la2t;StG_m zQbKD%r|plz2VXp}8fg!?Ma?Qn;X- zOYg93nLV=Q>XXW*H)Mfk$#v6;3?2^eBOp%OsktQx#Gk%vpGlI)QFf+_0a6sAR@qCt zt5|fLHmSKKNY7~E8;zEvn9KB^Sm34nDYcu2*^ZiAA2_+bLEbuH6dNnK<62WKBef{p z{_4X~Y&Kp6$RInyU)txIskUk z@$&L}ekUr6AYbxzrD9;Dj10_y00)W_6iPQH25W6A2{yPx67{-ZV$h>{F)=T*ABaz8 z<+j}|W(Q8Gh7{MTsa)QfZR@nk%WH7XojaMSmk7RFFHnwGQ;kmyib_jPmI);+%e>a0 zc+#OFnZtl2&%&fEa2Z0fwane*&Y`L7hf`tc^GaT{y*q)8E7@U#-K+J~^7T|%O&0@u zwI+hP4I9b9fRNT)gU2%4LW<{H%362{8FzE$6l20O+?o_p1n(}<&$loy3tU4i+kE4L z)0}swIhbTh318{65e*$iIMRLh{>Vp%UcPBWUC+F;J zJ)QK4nNzNA)%SAJ2PuO^PZd&grI*u6;+~xF-YT!pkAudOgQETc!%nkB33D+AR&isRQg==iE!?RLlwUBN{V}aWv zf$uAlaRZg*TC6DxTuksI!+6xbs0oE~a`>mYFns4+1k!9kJq5b!c=3HTntEC-PQP-Ojmo9k;|5X(dm7E%Rl zGDzE71lmU7OoZctn2Xo7^R5cG7>t$S+6?InmH|#_1dc0Kl;Z*we66@q27}yTKf*#d zL#_x}{ohGghO6gH_UHazHwCP-za?5QQ9|&!<3il{S9k&<2fUP(3bOKfUs`HqLBh)?pBMmuryIr2O$jrNo_cgl~wF4h&k)bP{vBkGR9SNpgKxr2gupljP zA$%1iEwYD-+(ySkAi5R5k2ESflSZIq?o8xv)r)fpsP^_(y*3#$(oigZ7F(J|Bm|IG zNUW(}9Ewu+*QRjAIaBL-;k3zf1=HHsE-2Ri5Z7G3KJS&i_4*q6yFeAytC@;%&6z$N zZRNOTNLydIS{pZ#1;EQ-TUqHMH%PeeHf}Luq@j!(;+97kN>xc{oeAVRo#TrG3dmsjsi_#m~Ce?RAt@0JvAvcs5 zTfbNVL=7AuQ(43Ts9(~eB5sz|#}FwtS-ud6`j#(9ny8-YUA{DnDqqq>)KkBQu?*7P za8$p1bgRhxdTA2*b~uzZ83}z07=j5<;q|Ux{%(z5FF`dQ5?YF-c>Q7-GCcL7CRjWP z2rOPegD?RNfLeZ>+~Guuf{RP+7_n$D3mp2f0M)vf1i02!FLHArbwkv;2oEt~#m0Ws z>YveeZ`;v=obRu-9ikFMs_9<|f&j7OB#fD?1QGE5mEhlRIJl<9Ebm`aWAa^BC97w9 zTs@QI`}=i$x3Lrq7b%-ol8Mqg(qUX*r${&qdz6Lr_d)+YtNCMHSMF0m9vu0!vbGW6 z(+J=t5Kpo5%qq3sV~J{0R3HJL|5etG z@DLL^Kor3fZbgkBG6dSYt|$BqF6RV(Mi_2-0q@%@!x5~fS9aaNb>!swp(xypwvUs= zo`zmOE%OlP``zeYQLHtYif@Zoyo_B0*nKA>U%dM&T*+>P>&UV7Lvh48X9`yc?)Q^h z&(}|oE|NfzB>7g{XjSai>>F0QjufvSimcue#$xxWo8o$T5wxy+v5$v&$%t8M`gl&X z_a11(K`P?9hiIFbht*F|FOtAc@K*e2(p%b@Oojf_Jsh#si|_Sn0de0zXfKP#sB!4I zj)2W7l33S2kUzc=<-MnWAV0BHhYSBdP<;dWREPlgLzkVNA$Z6h_Cxm@3eAVYs&AmM+#$4^6RU_mhz*M7X8v zy{B)AcNb_ooQ<{9<2518{9YN!5Yo)Prqo~I*pvv$_BEy7!?=I(ZQw0(KfHu8yEs`P zHHEEF>;nipa!@2WjQh@*?x?!Jz0Dgap%)m@SBerP7*!-StRdgIj*Q*PPmChWWtGBmY*48 zqY7kGq-sd_99?FPk}+aJ89`2s8}N9-bist_s4aupSJjx09)R9dM@CbzN2K=1IN2$f z0>(~DQFCjzd2``mF3Y#8Zej+6{H80Y6=)AD98^DaC^BVB(<$W6LyQ1;x*~?Ge)AWTyo~}1s|@+mK&mww%&IRXc`H}kzJla)@C~WnSy0Pui4O;m7LWx|YS|}a~)gnM1oO^5pNM?Kq0VpNz5S!)O0PIUpRZPI_ zL-y5BH?*V>v(G~Kp0kFOg^`4P9r#QX8Uj(k3dw;e_r?QXC1-UBW<ymq3x6g93DZCc5>rPzmRxNI|2hdO{ zu)Z2A2{kHeZ$x-IYoY95m8-KBwhVK#tAc5v`#?^c9^UL-I|s%t0dk|UOR%9YW^i-2 zF6LJ6gZv=Ak#(jF`2EqX>^f+mg>|Ni(7=ga8bD$|_Ag?&KxR^4O2vZJB7-AP;WsVe zR_`Z*c@;9Gt!14}ZllZU6jESP)Hzy*=!2AyTxjS(Dj^&z0bIcDE0N{v2p6zexX=lP z6itvHs+9H%_3y!X3WQ2A!CC|HHK$)|t!SR|sL=2PNj^fALnT!VelzJgBQSrrIRqh#}X4FgU1u*Hy&tTd>G3Xyy-ec2f~{oN{}l; zp%<@cw9JRp&SB@)Qd#;H&h#su)a zXg5V5v@n6tI87RBuS8w|ouOiK5hfh+yEUvc*>w{guY?pDsv==9>^*B(E}H=P1!CdO z!i8V(cGe_ZPz~XNz`xhA&J-eILhVNovo|0U5)gV1IS^z{48;DOm=QIq@QgQ*QzJxy z)Qv@f)$PoAT0@8;RH*LQLc?{4mEgVlsk^ssnqL3$!cj=Y>&789yG|jLG%2i`3Sd7L z4B>(<5bRefo&&U6gha9GVVzJE0^LCVM2G?+7&#DyR6Oto^1I}WD5T;UQAkw==SA9+ zCblPFAEAVneYQv>poMPB_WJ)&k>ma)VPR;6q;61T!MedAl~7`e2^KPP1j(7s9L?Wf zI5s?GUaa(;;iMwQjcpy&uY25`lx0E9BZSlBTj$J#?Y5zGra2IRbDFJsa{?}6ZM zGZK`q!WBoeEv6;FL?`4~gO|HH5!MfBgWcJ6^o2bLvlx{b{kiHP7>14J87S~NOq*B!$sflPRme!RB0j(0GA>hY9QxCkTs!rxHB3Om# z6f&!hg&bHd0j&_69FfvN>){t5Ev~=>86C79HW|`U*?{bW$Vm590x|Y;9<~q##$&`- zXoG2U!Ea)rA$=468H5J;s1xL)D5kXtV;Y+k2${cQD8_)BA)aiO-Dht?B!I_J>I)=b z6ORK4w7Bn3k_;qhAjl3R@Zdazd=Q<=Dj`e=`m^MONZmxmgZiPQ(2?^Z>j7wU3f4#t z#KqQUGXnPs;E4MP{j^xAdL0Q5>82q9MEM+OPKr{Sh`i8Og4f_eCYG$}5T4dLnOZV& zBk-VpD6vA+pT#T0{aFE9!Ub$W$H@f11QaNptbHcU|7g2=o% z4{>=bETLe5Tvi}-1RO)#3e}p>3K_162#+@R-2o!0ZzU2*=+Ba5L76R1|8ako7>Kq5 z@xW-*SnjHmX(!lME@U5`pI{$ZM#FIkAU7#8vi=t#GQHL*POmZ&wOb)3?wEmF&E0S&CQ$DI=}K3pRfz7||Ev=2PsupNL2f z0*dl>f(9=V5V_d^4A9}e!~NafJ9Ivrhke_-fQOtA84aEgA7vy}2u4Gw5N%)y-%Ji9 zk23a~5jZ8rhO>A$VD$9s#OvXp-n>c&l{hNV-EDwfl9I0jj`s%OF{0+cy&m#VD1J}B z4J>2fB1Z?*kD|J^CSLQFO+P%G z9fo@4*VkT!E3Ss2wJjlDuYooO%r~3D6?;$D%jt*3*kM>qFjlygUIA^t9IPVs;v7Pk zaPYwMtPvgW|2~UN*Ce+`VcN;{8n_An+7zxhjkpuvv~?NxJ=*kF3afuloCZ!-FV@-} z#~`;nD#{7U!p^y1+A>HDh-uNje>*4z_Wi3GUm_^Dp=h5Nk4lTSNl6^_=w}wkrvOt`qd#anqH746&!_3epg;6EcQgr>nn4xk8L7=9tXL zWvA;C8wM`0KZXk4-Wvv(Y=5;VaZ2>()Q#f!XQagYtlanDbjz+|%Hg(~l@3?Hf&OiK zf&;yMwl4R*h<(<6N(4tm_#d2-_c~QUcmv_73cSyXC+xM;hJ7hkVgJn`1RTY2(ih>) zA>_7@&xQwZqGR=!n>XMg{YC%737C8Rd^^d#zP_CR-aE_@hKO>*-Um_ox@uWnL(@VCC#OXrJnu#n z5AXN~FK6!|^Ch#ZJ2x58@V+IC75pqhsd%0;!U-PT+C&TEMW-P=U|abx-t^yn6|T6! zfPM7?h$kuf7&Z3QaGXL2tZ#s%eYT^n1p)HGX904ebdfAdA$q(zG!2BHglQZ!4TSh1 z&XB*Qf#N5chYwOf>f7sAGlcy5#X^J~`2V%90esX zJq`&DEkr;*{T4hVD$%fqB#+P_UH3miLrD2AM%l~Re+gsRMKSha1QK?AAp8g<+%NoK zhV(5Nbh&RugrDD&TQ5YAP6?PS3_rcu3AF|BGbzZEw7~m35aBj43q)Y7YAiqx5Ifri zz(RsW{k=QVg{_yO#s4RN(2(YK5hWekwr38Ks&GJr^b@q|4` zv5EBeZ}E|3*RYx3V{TTr&I^ z8__&xWHrTyIN8{0t~u~ri<_4Li^_F{I`4MICUTnyO-{-J>}H_*HKg&B+@NywrFY{gXKy>|>#`zo8<|7^>miNElHtWvPArH`Y7>y&q*o7WpV=f9Mn9X( zMrn@Owgg2TJwXS0(|TH33{uN-Zp~3bEsmfTJ#I|^3MOGk<%up8s0EP{6*FXlgw-O@ z|NjJzfKdW@pd<)*Zb>_~4eyOzTJ)EY|bmZ0%!sNP&ddN)sv&Ml+z zny57Hw(mH!1>XEdDvy;y;dNH!wdnKcL-~!5^CBs{T81~LFp=Kfnn>rf75K;B1W~-Z zyUQeK9qqIVes@D2pIuAuYUy(1Iaa7qXk9Ii{EzK4UQ1UVgVx!2h5sYJmEV5Ym&Uz9 z;kQZ9Xv+M?(QOU3d#_ydgA3>rLQz<>e62Ao@S!6GA8&s%={fC0B&4j3>F z?(W~M=3=we*?POlUgup7J6%-w+wb-&&3m@<^@bsD(##5qmc(1p+7cKcO}R_QsV#LX zpJDytWWou{@deTA^nNrN7BKASJsmxxaTi_{WUQLmqPn~D=rWr;kLhQMe%w&PSrp&; zNxRF}vAf_3!>d_>>doVv$+Pn6P|o7ThPNI2tCDOW*Kp81C_5*5nHRDlB9>3|aMj3^FkHY&z@%}`i z@ZL4b&@{VE_}nXweBMxMIJeS~#y0bA<;qY!DG|KZ;@4aXyODa}AY;ar&6VAQDtXzA zyWBz==aXUJN8xu5zj>o>0>T_f7ZHz}2y zr6%s7zRkMt<=-`_eL<65c}Z%b6SXSqk=OAq=_d13$G2JjJs;GY%2FMxvW|BNKUlrV zl1XhAYw|qU)$8N5)aHX-{r-$@TAbSaCd;>r{4kFp)123y8Ft*W(5o46?PX-VPSvPr zci2bQm=Q%icigke>xtUI?lJ!*e~xsYexmlj;E#W|@e{Q^f3|tMw})moRxX&_-qf4{ zs^WT;0G;T~=PR0zch;Oonu0OskGI3W?NYDQcpo~7l8&gxI7?OUW|9M5f4pd?-h>8O zKL|mgk%yEvQApaIv6NM+49ey|LZdFXm?7j=;OSOd$zY*CUs?gPq#>Na=h#K zT+J}4CF^_olAK3fkGfw733mCdKDfKd&68W#^!TkqvOre+&?t&+$NC3Ble~*QUOXhb zpgZoZ{y(?=*Gi&UyD7z!jD7@xu*-s+<$Wj_-D-BtL6ME{R%5*Pf+s_?njv&at2zoG zlp>Oy7Lsh{Tm9jb)g9~a2aWOm`Qt@D*_qwn{d4Pot0b6~`_uY6Be(YDtfM>{-Q(So zcV68q+W9BH|9~7*_ts-uYj>&h<~+L5IzNLS>Xp;f{^*7a!Kx2~Z`2X#)vMt@6cVhu zG4|J3f{I%eeli%id&CbW1H!&}HSX8g0qSBmX8&{Rf2$e0(k8(dHY$joL|J;*VL~QEC)swgl&sFYz%`!lT)@vMZ`xn~6X2 zI8k(MW}*bA!I$_LE#blRoyLhetj)w9wL7B>wV7umIMu$yM}G;Ax4u>#Q8L<0{L#BT zilN1Hli*bN5+8R-c$E4^v_)OfV&ack>?lVqrnv;?r7!W(K*FQYw~`g5p~b`>d96|W zB}|G0C(oDo_`QV3bKhyLQID4}@ki}XQ9(r^*>?Omvz zywqHgsnhd_{Fmp|HXo7@zP2YSw3dAnWoX9iY#M)tE>5I##eHs;UCT~x{({0Nh7>AM&~KAHv7BL(Ld9E$@d-aaYI*P zBlF$}txaz$9O0j6iV|z5Kkt|P$nl&cUE0R|?dI?gvtmT1d9<4n%fY|$dVYpr+H_s2 z8M9%8mt}OK63dmGHX<>#2f@xpsGPW?y#l7sJ9aUJ@1!$A=3#C0ubq&p# zyTrBZ$!QrXtPFqel>BCCPK7QVNdO7KUp#Y9w2Uh2zQ0v!zPJpDwpusRf_X;V%Q@Om zmGxABHa<j0aO!!jc&+uC1P{R^i#K84GAD6AErG;LeXtd{St`*;Uj0;x^ScP$&SHAa(v*oQT?ml<5Q)xr1{?+%6ra6&u z=jld<7wfJRv>I;X{8HS#;aca#jjbBj-y3epq24}Eu~|UNi&#-;xXp`wrKOwQpdrgu z6Esx^;HE0{QHB2*4xgZ@y4S|q-dZ?}=)LX>o5PSBGGM?&*#QH__8x`@e~((PjhhV| z%hV@iHJeGMr+f-ER){nC?L>uxed%@jM(XQ@5=J04IMe*<*1C2uj~(R zH9si*>T=hD*Nb*f&8OcmdwF7pTapiq?**RN5XRlC z9@VIMJYF$<#nk6KXWMlxqbJSY&~eenT=w?MMEkru^XIAzv7s}X*$po7vj=CWc34sm zr3`8GNICh-gBLq}4_W2J-;w?>md>&&voMGe-gO)lOJncY~r#qQer*xU1uZu@vS zqqyOE@az*SHk-$eOt_v1<7X@XFn`geSu?I_QEzM7Jb$e+@8YOq`%cMC%6(}(=ZsYR zvtuJ$(j>VB$DdBf`02yjJu|+G*mZC6V7tUynr5nbGe?}-D|URtW6q36 zM%pgV!$K*U?wwQMzaOew0?$0AM=Wu7{?s8ewpIGXf$+}%SICuzL%F`;!N^v2(n5%1 z&Aw%ntl1kA8nTbck}+d!MaMF>&=`?K2W8EAEHm~sA&M-Kedi!s*&6F_v!IN zzWL+5@8`MR`}v;ddEf87W-C;DpSUEwwz;}&rMz2#;r4iWPT6m78);?C9UFOXy{%Z; zO37!PbV|JY<$cg7^PRNGP#HevVg9QQxX`g=ZOT(&(vT3c41QXAfRpNmF<5mZ(e@V5 zQ~P2F0}xMl{`1U~Vav$w6+Kp29we0wO?kt`k7%2XInNY>O-E)T+g77G)soFU2cyxO z(CIzCkf99C=hgm?^oHRDD}4e?hJtsS8K@;caY4+&m+3ty2lsD)QNNuZEUI}g7# zoWdj8@!sKluD6gXhyffYor*!Ap&_cl*0)%7ph5}qpVY@YoMq|b>8k^ct!3Q(gohww z=@^Yon#mW-OhVW+A6qjiqFjg^yxpHu?!+7L^Vt9KwO&R?t|3evTNyQDAGeQd;Lt z5Gb`{KpeEKYCnouY=;^~>{c;<3Gn=cPzv*;F=~ag)H+YZ>F*%e_AZ;1_U0mXUnl9% z<}j?lTKj4eq|jG05-l-LM*z3FJ0IK_Iz0j4a!ZG&iLW^O18*cl*cPZ1j#;c5Va45u zHR_UaD0pEuTiOj6?cTfJ5+|hS?&Nxw#kI@pmJX>x6xZO|7Sc>b6|FOb)tubSzF3dm zMB2o5M@7V?I`B@z(t`}-XE0#kR@%l0b)@SREvOxM={$khl_jjwml5#*1@0+lQ=3nvP)zJ*Y}6neH`ms?&z5t%cf&j zOYf!J?_;PsFJsG67+N1_lHko1TY!-H9N@o(gqxa*tycN7*BZ2n&=o7xnX2H|A8FCd zJu5iRIj=cje7UOlS{vPZOZl46DA7WJMZUVfn2w4vz%cqHX9OJ^%E7|*%5Z>xu|_u2 zf*M#c%<(?IRgQpMj9T7sI;3c6mdXjYr3H3)D9jkNko|VDd#dM5x`q77*wT#h9;tRN z&8esY8_4W!Z3$7rRPJGCKoNn4QC#f{CSsY5OUGYSp1 zLdmU0IMyc*D`BOcWGKV!PDvmMt9^yDLx$!pG2wymb$`xSD-Qjd8{+wIEA`v6QjPPSG(QcI4zvZxXal z_Ufu8*uLXKwQRPk*f+Ms$&zzD|DmG9@;u#rNt+EEp$KxpPMy( zQ>^Tgr#VN9?cLhz108vQbc94IrBh&EQ08&YHQunP;7)A*0$UWbg>jX&I6>?+ro+~b ze4td4lIc@J&5CFizUYMTno2(_DA8d2v-TWP*z32l=z0-d+6#CUc8DYuOI_B~#Qmf! zR6W3570RGRpEp~#e2LLrGCb+5OV-%U22QQ50J-ij%gy#Z*N=mpZ9bw8Ar+ z+Kau<4C-^&suD*NWIP7Wc0->b}Yjl>Cs#EoSuBUCyH79F<&CzFfThgb$y z^zkq9+IRfI=`C@Z`25Ds6I~J#c3^qOdJT$pK{PCS;@Z-97|r-bUGVh0d?ST@f24<( z$w$ixIQy8OsRqMKm-Z%B+%_(Eit1ES_2pH21l6Ce`(rMb?px6J4um#&iYRghI*pn(&=#y9gw|rD@a$R*F*8*cjOLcd3^S~q ztlsF;?NsYrPMeihZ7JZDzqBp~0&&oL-S`7>I)=cJ;#p$dt=%q#Z;c(ur}M1bLajx@ zAJ#p#{-Y6tkSvlWYKmf3IkaGJqXV&&Ibk~wR$n+da~nVgGYqCxDIT>J%;aa|U%F*- zox#7tt?oRU4C#0b6JoOBoXnDpQ}mRRZ8lVZG31W;CVBzMd&VfIS{o zdnIO2Z$^Duv@p^6##-MOEfrt)ah~4$td!?ob43zhxudO);#yv$^0e zpx;F_@%TRz)db#~$BHE5Bq>=j{U{?0iH0BQ_{QbsfsP`)qk(D;Ojy;Zf$-}Og=4dg zk@?mBy0$krx}s|TT;*nry^aKdiYI?pus9o`^o8tWnu(hfmj)l8kr3qs5jp))Lsmw*&N`29P#f@slCvr*a$)C8BdqDX2+wT99tFQ@ ztuvkrTj;qe;A3O@I2GNc_4__-tI*pQp?M-b`$l7cUDg;)X&rcQL4Pq;%veVpEsJAz zd!68Za_co`O-%so=~4iWQo$u%#V_;mS-zc%8{pUh+Q0hAvc(%2O9o6XcxZA>y&Z2& z_BpSjWb~KiKE$zf(DN8$z^HbY%gU>&Yh1~_y3vh>N+(hWC6e+|xA~Izy*llOSD)=U zL)~#ZgP-g=+T_2)_5buzU5;7TcO|LeMN)&|uxxlC(YI}p$lC{6V58d%$R!z@moIB{ zgBHZNXG4Nty`VYSKvo^MBr3Bef{4QjtX!z_Ub9u=u%eoTDO48x7D5+iU_U@?^UL6j zEY*pYRSK;Q~7wCPkEMY#~JHOKz?VUK)bE=b&lDzq0 zIS#iw_+gJ&yhlYAczc}EfRd0#E?%iUk^?oQnAAhFUXMR5r!~?3tfo_obC(>fOGeHL zIJ%_saIlWXl%&rJ@NlC@lIVwVQw{0j4tH_4GP;X`yICA4c0}-NawW9}e~*Lw8BU_L zLc^U8^6Wp2eoodNm?O>5B?SfDH^|p#{&$Sn0rCj=t1(iR{(Br4t0Pg7_QL-UaIjrI z90!2$L%_c~7{pg-a^PS&Y0~MxL5B}&l39|SL)edz{Ga~Pf9E+cFGN~z63+pHn*$u~ z{_7%X6Hx4ZX#jx8_Avm*ckICr<6p2}DZcLNj~3wHFJT=K!Lq)3@XM8~BZgns{GUr$ zR`ZqN+xf#kHU9Yo;>hsmkFcZjh$FlI-f$ifNH!jN{=NM?g8rAw3(Y^&^&{A!#h)91 zBa1Are}Mhn4*ZP%x$YdH2U>nWf2%@2!+%bcM{tKX-$UhF+63!Tetp*%NsUSqDI$-x H9Zdfp-`W@- diff --git a/app/public/exports/warehouse/warehouse-rack-spaces-WH-20260428172924.xlsx b/app/public/exports/warehouse/warehouse-rack-spaces-WH-20260428172924.xlsx deleted file mode 100644 index 22de3a84ccd0f6ddc2d6501766c04e23eab6fc02..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 53474 zcmeEv2|U#K|9@@iQlW!xS(VM%c94pRlr9lkm1DLoB|=C-%;qSi(y^%ItV9Qua>i`6 zopObgYbsEEukyjo@TNK4ZV%kRhB&X$g64Jh2Ft30Lb(;0f1+nDdJC{Dlf<5;D$8qJ;& zzfCkuKDO%Rgq4fK0@tgL8(#Wiw!KVR$9Z~e(6`aUemLMH?Q(P3nA7hZmN48e`h}^~ z#2hc6tXgG#Y?RUaC7TmWRp(1~sw-bS9MmdH`I*@Rx%rvvaNcMPt2t6)n_%lyf)B&D7Smv z+FRx;G)6nKnx9H_dR6f}y!>)whpu$mal%2XE%$bi#j>SrsX?+w!-jS=dc8euNnKUL z+xhb-lU(~>E+xHL(jqmggKx<@e=m74dzYVFef9;dF|RrGH-B2JXE;p0bL_%zzD>=CPb?jIZ0FG9P9JJ_WH;n2IaYtnxNXWv z<*Sp%iDl;=%KbH)x6?^NQGCcD`Jr=nUmO|semi%q{Ob6pnL(SzuY5AZ<77vaYqFNX z8KvXno*8EE)SaDIR2Q)K*W;`!3C(*rPk(;z7oVKFv^0HY9QXSd3wAk}JJy|S+!8Z= z$L8*5-)&nv_3#1rqUQ4l&E7{V8s*no{!o(9t#vtKWqx#2@_8F6llXP-vNzLRr<7R^ zugyEUMmL3@HszeZkG$Ka;aj`szEIG}-#IKLldJES4%PtZe%u(+dsdoYlq}-rRG|L zgGS7n@v6wJL1W7N+NsW7Gfo;TnZ5gY%ktH8N9!9b4`8+$OnwoknO*cWF2~C4J2UIf z8HMG8>ctIjCXINJ`@{5ev)|F~E-PyrLiN==%IsY2HzVTUbG1p~i?)gBTW*s*QBq~L z=8;R~Ll;iulF?VqM@j_#@Me#0SMF@e$Ge9+JEWgioti_HYkVsAX=3$!&hnhc@e|!! zs_JEbU(llo0U^=2*jQWd=}*&DcXms^x;S8fQrD0H6FwV@ANd~1^Op+Cybq6EW7}Kz zk2p}fwb7%?EO?9ioRgs^2WSrS8Lat! zPOsLhvNTRx9-ZG7#Nc;kF!r}LGq@c&G+r6M#*xSFlI4{J@mUpa6mC6RqoXy5-uXV# zn^UJo<2F$F9T_xElOcoGVaDLsWKihODEs*jBD1)4>`+Q~RU)lBTY}-$)zyB1!fh#G zXNT67z`G=9y!Q=^w~4gWPS5>(3I4}J46k-K2EQp1-V;gVa5OsKW>CDl3LB_Ac=aKA zcL#&-K;u;8Fwna`GI*V8{5p7`PA!rCkj8x=%l}wNr}JYO-Svj_t_D6=mfy{lVDL&P zS-HHF7j$j~jqge4f7{&%voW|Ixv3$!^H|BAgvzxlYsQgC8T?((gnRb?6D?#UQ-S{6HDg2hp{Dv+Xmyy-=fWj*@ zOyrwP0uWs^UL8oj)s6qyjsK}amRhI5*x$lWVtDf(xAQ-66WNJ0elxATB8cwEUECJt z_^6{(zq_f6!t3DidG&_0j!u3#wcWeR5me{hdKH$~OygWG;WHWGtE@x>zw<{gkB<$Bm+$hmx-uL=?2i2Rhno3p zGs;~@PKz3Y*Dag#sU(s9G^m;Xw4|NN&-CI;+^18hyer2`_$}Q{wIJKsd~StOcLyhu zm(B3*1Sw?aQCJl17WyN@as0!KM~0^S!}P#N8{SxHNar|tbycaUK>hu!>y-;r{O zLo@H-aRTWK7YkmtdQcec^-Cv}`Bx)(TD&f5)~m=w+p||ES+KKzI8KwJ+wYd1Zzr2) z%jfT4Ki@Ppmt(C|OVeF^UMz?6IH^47N@Vk-vl&Cm(P+MTYuP|IournQ1ShAG(`gL{ zGQ3|uYoV3Ux_-6H|IoRw#Ko!PdHI633Do4d$1`S?i{-q3obmplrIJgD4;m^(%Xp(| zldN5NN42T+Y=%0THJ5MZ{lGGR7wxVcwR}U?w$WXkg`eiiWVfibq$EV7tiNs6y(ipL zo=5F6HZB>To~v@o%gT(oD4^|#Y@(7($)yne=(@K*Y0)o?LLFUY)+J``zZwyUWTayIa{F8CUwP>PwFZeLKIH;5^TZ+C0O5*5N>Q`3(OR z!X?pT%fdgjapYe%Szm1)p47-2sa=1e^8JkM~oZREH~->JTIi5_?EyK&d|Pn%t{ z{n9T*YiHj!vA9-iH2bzGdeMgR$?VJ%la%~l9tmWhSMqNg0h7uEddeqUjelso^JePC zJajR-&2hh(s!>llw_w30MFVMg7rGqzfnq4#z9J&Dt8h$r)hX(uy$&HqXg~STwtdTc zUcEi3sAzlq?M)WDYSHDp&D^`2>T|Zo$LARDOiF!~i!Ny5q@u7KW0SB;FSa|~3`dt} z8+PmVc#W`2vFd9s<-Gf8u?Adp3+iig-c`mm`xkACpN}R*7npR(rt-)uw%?Ds)twzjuS&%xb~wM=qoeNN=9+eO=V5~$$v-R7>ln@V%G?~KoRVS`b@ z#prgMd(!Q&oEOGnmkI#YA-=kwy7+RtNR2faua#BWsq8njlGf~3c{wjW(i`vb(`#F| z?*zP;)Yn`9yc7+%=oXY>y!>;j3pPyxk#%XJ%aNDbNMx3wo0X4A2L^I2;DTnBS(DLe z5)yJw`PeMDdmb+6t^#qlRQZ@X+%1Po4~jdRCfUQRY3Ks8I)>~`+T>xIw5L>Awao=x z#$BgXDs#6dv5L0W!FoT`qRV%i`FA&Qa<c{ zM?HnR3UEPppAvVav!foqt4iBAL`C|Dy0%(~Q|o1A`30MX7)Zms4 z6zhrcIdg52I`%n)=!E&l9Lo!{w%~f$H?`Zf$n3HlN#7Dk|0$5ZRmuBl+xDcRMcXId z-n4&74+01E?3MQLdyR&H)0U9nx z)G3Z3?n#@r+a|3A?k2dP%Q$=QO6At=NzaS6pM^zR)S}CGrQLToz0cWx7PJQ3P0d9Y zquZVCNzVfraQEq4;BIOzx}dwah`SHxf*VWCMHh7U=5x^d*)&@0M1J)4l*RWc#Yg!Y z=kZ)}-pTID>H*v!3UEmp!Yu&&gKd&B0T?dh?7b?L8@4B1E84z^01TJ!N;!8oz0BFZ zDL&^GIG5BsbTPWkc2BwnfH%cIy=4P{^Uwv|y+z!8c*_O==b;O_d-ECq7BLpz{cPT_ zoLk0W*5I_9BGDzUZN%L`>%yO$ZtmAq$c_c2x79wq<;Xi@eOWy_7W`nR^YIXa z3;r>Uc^9l1-J03!u7?<0efaQG&3Tou?c&SJB6nnGomE-9z+62?S|&TxC1qEs$~b#k zrApWKln+G?uWy@MC{uIa-rAXJberp*`XTJ?Et3bU>3JGtmmi)!V z-q@R^dF;ZIkMn-nXO$b;<@4+Lt2Jw;zt74)e$SRtlDDI>yDqz7v69=Y)h-Dk)9-Vp z<>}cs1-^NoRlfFIiJ4i`+HtiODmnpdt%$?*<)L{G-glh+^nA*acCi{wvo)HJk2SZf zEvn5L=G~N?^Q*hp$(mff1G&XxEG!sRXXEm{q()YRhJ~ACT|AiERkb@dY}$dRFw?57 zwY8j1;O{|quj@4ldMDtCe0U-_;DwizVnt{mqvlr@!C# zx@yDp=I|$BGu&TSYyDC_=fIg7>rk_McirYXo_cQ`meQd$MqRS??uS;zs1ytPsEY;J zD;--rXY883*JEP+24lyx(xsZ$Qleg(kEUqsnm*X`=4PpF&7Jd#&!&y?vvt&*QgP#e zWYa_2<@uSld8RvN@nuGT|X1>-C^nXBUmc2A?2M4T;K8qf_>wwmX6qABUXs2%UsC2i?hA#b?SgJ}S@+A(b|ZOv$| zN*s@~*{91~l82zuYo75`G`mxxcrYi=QD?w}tK)SBbeYw6&Db$OM(<}Yl>-A+nFF@o z`F6&S{MA-x&6nB??Aq)z#Nx!DN4Cp<{Z> z=8cc~jl`MEU&Y*iy!OLj$^8U)xiK(u?QR_f7%3+vOMs6PgE?g^BuB!WC+^ie8>y-} zKQ(F+jC9zovk*ZV8mhE7wff^59}k$bk& z5|^p=2QmHnv1MKj(&!TyIp={`IE?h0kHLSUjhe}Cj^5)rW8VX@duRqti-hNIPc1tn ze&qoOdbEt+A((-+JMGq?HKS!!<0N2J6bs4euqw&lK=;~D4W{b_fJo(3nUYAPKanDp zf`Kb6PRJvX{#LVkhN|YN)TmWRq)s{^2>;knrL!Q?cRuPjL8QNlx&H)jHxh`{7>U$L z=Q0xMc!5aA!<=RolFCS=4{M$&t7_g(joOSv>ZFs3L@E=ilmQ}r=i>o$c03dtxE1Ey z@_`!PeER$r3(4=>?hJmE8nyLk@sSfpxk~QV4g;gDkw~3%auK9Sp-KfH(kh==cs%Zr z*e3M&E)Z$esSC%%OCNzqC(BeHLn3Vvh!jT7c`OzVBmMROc-QTt7puli1)y#gl1mWK z$2HHEsA{rOqdeeEO-?!;2&inRQWpTN^5Gz$kHrRVgEt)@fF7`r)B&JF(xQA3&=Vw3 ze|UV7v(D&=0QB2XC8@OPmDN78ZUN9IVw=$8M*(Q{sS78?OP>Hxd70{y0Cedm66i`8 zIp?WZIE?iBg_Lr12+V2atTPAZ)R`5kG%u|>zuLzZMy5U$dyD1_w@CO*&1(lGgYfp9>^4ZcD5VP80JBfyZs0iD_EH<8c-VdNrry zgT>E114xQ8+k)Zo8_sE`g4Z1XLDfbH#FSuh!VJVTAe*%BZ?m&PepQy)69OY&2*8)Z zocprH?x8u;fS@&}mW7I6fst=iW&A>6B+EJNR_L11RMj{&n3HZH`6J9J`CLHIGeFQS zs?0fvpxgPYEze#!Bfj}LK>A*$`V2fi-6d_z*)_+vsoKni$Ddi8u!hHfeO|MAyQ=27 zw5S{q(;^q02qgOXBpCzdcWwTr&?0{)j9i%`a85Y@X@Sh(Fqm_jOWNG9HKXlSf{lYG@PhB%K4oEs7f~G}PA-$g`^$mZ=VhxBuEIASjHSlP4AqBmGzc zy|;a^8&&S2(+qRUX@@F(N~?Ze>%&Y+To9Kh_8QIEZIMt7b4H4n=4HM7nIcmZ33Kw2 zu-*sk(HU4;GHDpoXUKfe`vFq#qi-iJSeh?3(*|B7W|=UDd8#l<+&Mq%{qt}e~SB=x{+B`_yGT$Er@+6-ZtUWK~fYG70J42?WM@bwjJ|Y>zRdU^)GqGU& zF&nDgoEW7^1skuAkWaUoSg>G+p4t2uuj}^$5^VIg-cdZt^sv?|IWJ{d5CG51r^iSg zE50%Zo^SCocG26j{96DTz&xTi|A(tS0SIWknCW^nR4zS65{62~Gz3dpy6Em%E(at1 zm`8MBq;5chneLvP;RWOU;r)^^N+ZzwBbBN&2Q7cm1?vbh44D;uyVGKbUye(>_Tc`lQO^`S^9T_nn< zN-pBV`sh+59;U}k;F6?eUxILzydXi5>!%>j^YS6OU)HZk&ceFABC8QC`wH`Kfcfe9 z|Ci4HdUF2Hbp9{5p}z&DNN)ZcEa(f;6bbWh;O0Lj^u>@P(oOv>-27upmlhQn&4rP% z7fgF$80vvp`i(FO^>}wNVX*Gy-K9lEOLJic(96B6^a?_UmCV-#IDDtqRq7*IVFcmM zU|2!p>Hr5#x%6nsMmurcJUgO6+sCzq6Wmv%|f17JB{UlKwF_|2P z9K5*Ro@Ee$7oZ5td0sTc)&|WfRgsV8oKVpC4Ca(ik47U`>{%ucBe%eu^6524nFm+E zoD&L09Yb?MY=R=LXs|7WHduVc3G}>V0V;~`{5)wyL00l~J&kcOH#d*f-IFmU<}1-7 zOb~P+rI8L`9)y&}4y80KRM_=-c}2oeX2`sl$&=tcKk8}BNAFp&Cu44md2WD1-xcwK zIoeO93Pv5ap_)&RnLGyaoZ;Vsl+E5tOa8SmtIvL&dRyzYpO>mY z1^iI?^a~IO(&xl<1xr;x0k01Q-n664<50ji+=p2ETl=a!se-BCIRWTm6fMPZw2YND z(uZPwnjiBx^bZ|3F+WojSZgOF_>KiuFdFfF@L|s}ixP zbZP%Nai^j0>zkl|kTv!9(TJFF>Cp9kpZxWw3X^rv8YM^?|098-|h zwp7n;2IMI+dJyUpo`03({z{l$K|9_J8M6Xjp7-2-dLM#-Fh!x9nfP2~dLK=S#?uun zSphAQzVslowtngnv@^b-UD1r?DzUvz$s5GbsQ-yJ{7fjc|p9i6aVIqQ%lrU8Ha!C53 zV&zm}{O{%7kM{~fGZUt0%6UXdHZ}~?Wi5s7!6-SsASF4EYCq-yC^+SZ6%2yzfx4fh z78IN($HokWg7f%vJqal4OC@zt99e50bpRZ^ykx;3h`;KCalhJRvQ3l}%(;TK6uJka zw!ob79@R&g2cUqLpHMIex(DihQd&^JpPUyn6bks`Kk7+90beQ!u?fmH}J&74HUQ-VQOj`+Aj$8mp8SS(G zwJ=ZZc>h(B6AhlsIzc&o)-I?odz8sa9TTI!E?^n~zR`2ZScMaUbO_o@y$I5ibV>y< z4?u%va_;b5GWrVhKLqAqPtAWUsJA=(cPkzDIRC7n z|A%n%|GEk3kNP}Tvex^49)rA!dWA~dMS>W~iTgYR$u1BPy!A(Y9_HaS!jLLx!)n|1 zij&4Wv^C{9I`W*jdjZ}kCI-!kiByv3Je^n|F{uC{_l3@Zr=JwpVq$?|E*hh4J10gK z1$6nN5EJ)DF46p!ql003qfLS!)Pr`nwjHSTogTs|0iAj4 zjlz78B)m$F^K>{GgV6gz=fP93o5Acqr`LAdL0UF2=L7@|=3K#Yv4%On3O;P}H=mv& z#hotYRkT!(f(__(? zAUI($6!NCFVfZiwWEo=syB^CIVx=dMA)y_8=7k{$*QBdj_XE5k7gE@vNBIiuT%}I0 zQ(mF)@+nkqo_xrt48qvq*m!yhf4>DdHX?IMNOQ$4?PU;K?H^Opj3v~Z~3BbMPu)6LbA~8 zDV0ZQVZ_;a$RL8?oXk+je%pr0bJFI*%B8qbz_#BJuz(zJEV6yoaikbzmpzjb0sVh& zKtRHND<}2{kmCVdAmJ^*>J_ZhUx%GcHGz_S$WFB5dTY`fiU|b;r0p+a7ZhxLEfSri z>f>aXwa>sJkt6ydcH!n~Umn#z`#Khi#7;KUW`KSJm_wlsYU@>Be91wI#!eoU`$y%Z z6J9d!>%5~#>;JFu?6|oJ2HuB9f?6$CgoCu9?hp}{ZYRzY22~+9y~02D?Trm1MMUp5 zS5bkfYf+C^5V8}7_HvxR1^5wJrnC>(6^3F?YL6_Zih@1yHjTkE# zQyVO)<)X{dgWZIQe$2xV)58b{A3tjTNi_0Xk8i>M#1ebewu20yR~>#YAOeM<*+-e~ z)-b1(7Hnn!QV(<(GIkEkDW&DIf~5zW8555(4?{{4b{{$O_Eomu7(mGe%a2%zo+rxm z%}d9^wgpH}0g?~<5po`I#_%iA3!D;2PmiSsQNy4o67_z01o+P96AQ+|R>qDwF$$27 z*pHC+fa9IOWy3xzf(U^l(P3z%%#$n_i&`nYw=(`hnCPh7*GNtzc=8-4D5vk*1?M<> zlo}meE(3{~0g^yKH|UH3cW-ddyd(djC&a(7#;i_@vyQHuQfv%zsQsWDpuJ zjDWpN$V^lavJ{5Z-a$x7L=Z9)6)P=8MtU(}r0Tp`hVefED!K;jCK2h!redD3(=F!TGLhTTKAdAEG4y z6^CeBgm!%6uql%nfB5Y>BQAmH-%upIuAPz-&vY%uo)E~iPV`N}6 zBVoFp8Y=3E*aVvy{pUo7CT;q@J`pxE;3%X&Y-T7;C=iEoF4<2i6AJjx)&#j1I_JYe zhZ)Bsyz_rB?M__xrws$3X$G)sL-4CSo&xb-uhYkR8bDeO_VpS5W06} z)s8DlF8I8*n=lA*I?hHWmcu6h1&HdSby+JQs@u!yHA7Ud^BSDH%-@bL{VK@a75u4c=*MV1(Q*xfa+=-)h|F&F?t1S1tb;rTVPIkkJ_Wm zV-VFBPbip-qPo9SX5vw1_`Dbm$W)qs)N@3ciu4Lr%e>;?_~Exvqhjc{9`fM#lc&c7 zMaCzrRf+lvOsuRiF>dPuDp6SXmCRfZVcooUSnrvWkTS|X{>M0p-!k^B-3xxZjeZaQ z{~=GP;GvyTaUh@)wNq3C?d^U-%9nnNqrLpB% zw4u?JK1eDPbpXsI3m)g0lE2RAQD$GkeSSothaiIejM9>+0nB5Nc9o&DOK<}IOZpWF z9RtFrIGdL0Iil=CS`RY;ehdC(9`=R)uh+Sg^=E|ZS`E7RD$D9QJ_DAifzm^C9$2vX z-^(yW3huAexj=9tvHw>q-F^Gl8H-3aMHuxra>!BWu~vXPw%5_aW`z$U_3|k%kRb^5q=YOKEJ|4{)Z?%L~Y>V$^hi^PcXgw^_r)Q$&@-O_?BVO=A_F%ZXjg)zayp{lkqkYxseH4v>VzQ z3yx%YN93yT%3WlpMt1C0Rk`3MU0b>9LL~j;soEEd7CCp0>1I}qmCe0$fR+2MJdh#H z>GV`{SFyh+PfyU&f6;PSqU6O|j~z~p4;@EwyV;?4LqcAhq?SaO)OGxJ$Zn@{W>RX~ zd&6ViJn6L&YXa+@B)a51-LwDQgS7eQDmR_?Y`v^cp-r5Xcd2GibxB(7o<-U%Z!IPn zHY?|5o;9S<6yTeIuIL*d{7tD5`exI53QY~ZnTo$TfxkItjJ}y@LVTl%zlp%#Y&J#T zl$mPo=QPy5wJ_A74d=014)0SPQPkYsS?=6YwgNqrShK2TIaBRGv^GH49AT;(qg`2N zcRFx{O1*rjn$87$+sgEti`ujsydY<1yp$aP7+}>HZ0L?1v4{<# zsr?i?W+}VVm!0<1z<(wCB(?UDf&aP%J3MzdHC4nu+fq!W7}jzO#^0?+BCau*`J}#e zXoJh?uo1=e^7PzeVI$t!g09|`XBY%OxJn02vBMNQiXSUzpU)0kE&1~CVy@ON=S>4P z%67WipEqT0bV+uTF0tx<`67=Im}XaSOZ!uUT2+j0?zyDQ)>^wny@p7-%<0-s7eD>V z3XR$%~VLOQF?XOIU;IdoyBrr_x+KLAmtoWGNQds_~|cSYWGW{@6$g%pOJ~ zRlDQSNY(R_NrBBNBL%jytX3kV_Wg~<#K=P~T3+0l`{0{*Y2P`}TWehspEnX}jr}yZ zE%c3pU{Q{OML8n1@&qy%+}^UzTcT!U69~tSdvV0bc4Wk#E{+)kUr@s=Ol_QyQY=iL zIANt=8CQdh7nK-ZiEY`7HF}h4ClY z#EZL3u1skpVd}J#Fu&;_VM=xqF!MWwFh2-jwhLf(0!%LlXOn0S_5&tz-Gm=ViFfX3 zFUc!R^EMIVcYzmlaW@(MP4~Xb^h2jkkC6I^xN&;K)ZLgHR~fO-*1w@rBuYHabgjw% zHOTNcyMjTq+Po60!*2+8va04llbVhg{Eq>@wTLkNW(b84W&RKfIOjbdN&EZxBT1)| z@B&1qaQp)7Iqs8m+V_^E(}}mW5-)3KX^g+}R^K~(vc~xPZ_hV|KTLBAQ#^Et#$6KL zpt0fO12DdYp&G%{e+zQscz&lDFDXU&)KI!GK3}R9l$Vgn0qdB_Lqke{8>Os=2uvTyS}v#)kZduu_)-8CYp;E~5M+0p+U%l&>N&+E(eS zQhhYMNp@&@lVV?lr#F#XLQIdu-a(3;)=i4tr+c3Q{gCsJPWa-Ex3Snk^o5$@m4xxXywS?_-N+UlKofmtb~#Qe=)okv&3^K}>xw z5LsP!_dQN|b*yenmbG4{rtS|7M9GC8NZpSuR8NbCSFnC>U~U5H-G)Q zb&4|zkdW6Y>J<<|29*rGfK*b(O>;7dJ|@Jzl!LH8hy?ylsuS>c=p{6?s{)`^B{5<}~OMf=dScgm=f6~=S$w0AV<1{+TKcx=(Bs4bx$ zT)ttW(c@js-7Tfg3UQ$qqpUU>wRf^Zw-}F?F8UtPB9ZsYl^J5}`#$M;m-KWpZ$ur( z{J#^w`jnB{+PE%Q-L5P5{T6LUX+UwT;;LntH=>(b8%l4)kC+s zNg%dlSH!L!Q|~|AHIhmjuQ7fs0T2Ad&Nvx$cp-N~xhaXR(*DZDXscI97>RNYit20+-}i&{*;QTqNfcsLMM9i*y~GK8yoiwjAL|W;%R?qf${t=P z6taWjto|4{*{Sibu=YC37ca{c$e4aK?8qoW4&aMO5odLR7?vSfE^J4#BdbCCAo<{5;HxJgn1ZeqA! zzKL{(z=F=oavV*9XGB|_!Mt=b{vPwh!V~dicASiKk(cVs5%r|vQFgK#|63$vr>hrA?&yA#Wz&CwMdAy2=IXYD(>y7b&v8WH0FytJ(NZACY@4g zY8+uS37L?*3FHl>03mN&3K$#l`HGrh;bjR`=~+kK%1E}A@|S)H5nrireelY#!?Obe zs+5d0hM%}>7(Zn}{d1E+8??Nq-2L{@4CcBbt4Wh(istRLtT44O(%*GJyrMF8(yStl zb#XgBq^HL(j6VMA8=3S>g9W?d9LtUJUb(uOI4zrcQ%rS_XPE6PBSva;#Lb5K*mnmP z{UmO|Y*R135uN3=k$_G9Fsx86vfe+`A82hNDnZkG(G*UOk?b0OaA`MjnP->I_(Aqf1^CTeMuK-k1 zZ18ZD>u=Jj`Hl8hwk-3iI_U8z;cD2C$@Kv$yQ9lI3>J_R+PfM%;R$z{C&nKXV;>W* zpV$?Y9*5sdOKBWml(Gc@_ISj*uuf4mPCofpe~0GP3zXv=EsXN^mEDfYa?%k1I%C9G zNJ_}BpM<^usLb@iLC&L5ND`zZbyGlQjNj(H^^HjjACOYcU*0%Wuz8` z+h2J&ip|EWAQ_shUOY*?NJgWmME{uuehjPM-Qdo_;p~UQ+3fXmOZ+&bZ1-B3TnE5T zI$mCW&+kNK5#&q0u2c++l#zis5a2*@fjld3YO3*xK~ZVR$ugmYWtrC+ z6i+%>By$Lm+&MUv{ctKQeO}3nws*&|aV0x!uzR(hTE3nttLb83 zuhv9Rx8VnJFd(Eg*Wj_twvggE7qb>#M8@5mImMXp47VnQ6v4Yo^z$vu%L3OB%QpYv z!70wWQyk8)b9Q!~POAv&XWMQxrdk+NWp!Na?EyHpl0N~ryCS({J@vtH&b#9r&Xcot zww_M<#LOvIw&;5~>4TKPqNfU}xzfvNC2>zqcyE>0XL2+knn}q9)4`=?ty23R!*x^~JvRX*Dqp`s4 zk-+yB$+&^aaxK=B1uiD|kzqV)aXtJ?gFIduDMTH?6dI)$Kwgh~SV3vbO04TElzRmTuFNkF#2n(qK zHW{St%>r$sa3;cWLCnSL+HqF}Tnxs_aBYV41$ubTqa+20Z^m?$Cm+;Jgp{3|>Gkpo`LN(EW@ye}=avLIsz zse*Zxdj;`;;mSY>0pYk)idT^?R)}=oUPx#NdlxbQ*}JhI5|B>!Ya;mok=55GIu6&x9Y{Y1XO$bD_$Fo8EGgMKZ`9*BN770 zDXl5zxaLeB zj<#}KGo-DrT&;~8$pYYIu&u0gksBo3cN;ewG15@R4ROmO3?-kMBC=T*$oKnav$cKG zYn;vI_RVGy*jYtxsM1JYL{=Kf;Uyrhs4N#9t*t4=%O4UMqP=B&8{}cNkaH(oJ$*!& zZ#6=(kc*224MDL0CNZ2HKDHkFs&zz$1HNi<{bG$G#61uL%0=l7ZIkM|pjP<`?2sEu zjICd+0HOvCkf|)<0MsvOQ4u%G>SKr$n=D@lM19K_Bu!LL^)6qUMU^jUBI>E%!&nCC zZaAu6KDt$8e!Vn_d^;Slt!Q4=hl z1Oyf@ph1{`20$%8PVR6bMZv`-c8pjwm<0~~Sb%C>Oaff%su#IAkh&piU4)02u;Pb) z)#{(oc5mC!f}HQKwH=}oM5^gu34#Ez<0OoktOOD8{*~b0Z#cN7#w_n&Q)BX7S0$@w zdt5z}PVzR+5R*JJMlXU#Cbo411J?^!GvkKCAg-U03c^K^`3Ww6eAl z;L`};B@j=s^UUuJ+(FQ<0GCL*G%yCjrJ=^pXU2dVKj1QnJiB+}r>~dI9g-E5i}2r&o5}z;)#0`k^S?jJA)H z#h!*xyktF$6+-Ozo*6bTryN(pEABwEr62@Zpshi?@X%V!pe6f#*dC7=bYWjFi zwD)dk#6c?Jx|?X5nTOR+P%o0ePViRzXwqBSnM{TL(>)xq)r;@-Y5{TIKxi+E#;9@V zxsHI%Dw0^&KafAZ5#_zRe;_};MTZOjKTv%G`BaDi_e2D8UlD;ENw&WWC(uK9?bWU% zL@jJrE>4U;zD1Y&2I$mF`|hADLVA^>RpMlO>_~vUza0@G?Q2I^QT^=bD-c0Ycx6QC z+dzem(^QB)_aL10iaxzHPc|ZDaA8cyR}@CaLzpVic44@-%F^gigy=iJDiQR)8jQE&HP>&$q>@azNXY);n3se*v$;J6-~Bq1QnK28!n{#hjNXF0B@UrxA*MP$N>T9%&~ zW1|XWQ>1E0_Z(ejj*>BALK#6$jT`WI!gRre>8LG(*;mz=j~;;DR7XZru}7r#$T-<4 zm;%O5OHp%cmw9vHAuh|et8QWjg#4zgE%0StdCbbnxG+hRd2{T5bu3U2F@&z9*%a$9Wkhb25 zLiFDPZC@EuQX^3SqHy1M69K3RI${IazJrKFc{Gtm;#>uj9BqXVd8s*rD;NmoKn%2R z$Y9)v^xjP&3K{Mm-0B9Aqxq5h3p~xKdz`c(oz3L*fd z3jm?_?C0F;WMN-bi;%; zfN^qAZYXT^k-D+%(G6Po`$CCaq*^E*3DqJ%9-Mn@1W0Cl2>~c2?jW1x+W_oKP*qI8 z>_hg|P&c%s5VOxh_?|O{l!cLmeeM5D6dD3izzWHMDEGz#UnOUC31&pQFnGqY%9u$n z3ndZ&BI0ud?g?LC?mD`mP61wBx$gSqNIa5WACc+7(Y%KK6<6ZnB&3(Y^;2FJ8sZsl z#jhj5*JdyTW9_Yt$+2a*ZgdwAd>Rt`vzSF`_;txWuiI<6$rN6T*>xu_cZ(Lc+5>2) z6j)!4m4q4#VAe9h~l>jba*X79ab%YC8EL`XW zLy9KI4^>M0g!=d3JOx6fm|(4e_?pwNwpKJxc~oe4oFpG1Y9x~z;oi=R34?DG8ayEp zWbjBJu-6C%znAm0kudlap}`Aa!qQ2Y;A4pik-_5$^BecKFFu523*K~{q66Vg5hchK zq0oz0w96Bm+B!;FI9gE5yS>DMq{%6(8jBDH0NIh@kQnYQ5F8}sgy1Sr(^c?zEcrO1 zd10NxWh7x}g%A>c=|Fm0Rj+a9U4ONja81|kuESHUd{5-L6 zXW_!ndpm0qE~tiZLEzu(Sf>jSF`@P&h}j#E2?+?jha3npCkA5wPRxiJRd~i5$f*&c zKu#Zqe%U)X~63{}oWqbX9sK{~ulCUteLQ*#MKEF@O8@adBBT<0My*CXBMPZEKI5|}_CZJ` zEf!3hu-G2c2HhY-BXqO#j~9+YDrWEfWH4mH>`+K0*oQ*u=j;o%J+qFYi9OK8cY6p! z1W^dQpT>C7`=O9Z3`8Ln55ysroDqdop*R1W&jR-C%eak10`%i0bfGNfKT+hsia+$G z5XbE{uA`@(hg@{0CKs!_ySS}BxG)i1%RBJ0C}tBZU?xi!gXK}NlLw1*6L9WKeX39Rs-HQ~*MmU@YtykYnv3o(SfJ9RqUSvX?RGp!Yy< zw;2h_SKx}H*=ExcV4@T9tij7&oe1lPw88GoI{HGS`ezr@Ne>5A2zYxc1YS^8xHtB$ zsGz${1xh@`0Z~W^DCinlfo14jLWfifODL?9=^K7>VYMNJYN{w03q2Bg)7r~a6fV$) z5e^r75U5umTFgg*5>S1MpdfE346^np0KJ1e2AvQhqjnkM?eBqf3{5Un!)}w|YTn2a zyauru2i{kED~&D5=aC^{>EBPrE&!gxVSsc2sIvP10o1|@#Hp5p;&H-_L($q$CxcV1 z3PGxs8%npEU`Stx({wW10gLM<8B(cgkJLmo6-(<%gn(8F(h%_DpQ#64R8=SQ7!j<( zbPAbO$3hOQmVj0WPL4?Fp!IMKNQ)~lK}H9yhmD4GR5l>{ATrXul|YProQEw$f$Y6AW{4-7W%t>e5DDOMl==b* z*u>*N0xj-4lq3TQ8VIrj2|PFtAsRX9K68f_wSx{z+(|_EbB?hAH zKs+!SHI}>TWZDV#l?&O2=O@@lmeFt=0?18@jI94fhzxN876|owuW}o@N92T%8;}hJ zv|&W7Fl7x!K;#DAoSyd>3;GO@+5R~J;bRy=1`Mi~!7URoFS2EVx>;(feKr>no}W1n z2NEsBp+xf-NJ^3d2NMQJ8jey#{W=zcz&{P9yHbH*HzQeUCQ%mBQ-Z6Q_Zb)r+-u z#WBb&kBV}FvaoY5n6?a317cdV@81qefqnm~#+L{RZYbI(MtKVs0qHANAZ(fh*H4o! za_q}`@PupQ80XRU3bYA&od~A)-Kj!m9qlb*OPxU9b0QeYZ*08=-h}DB?eDqKh~9T2 z7&<2;b{u_3OMnPT2--0PgT+4140n+6q&nCxA%qtCfi>vN}Lk?Id!8r{uwFpJ}dVn1|NPp4)a02FDKi^Jrudi<>fcFk_gdw8bu=hcfzAhV1^NnJA zzCuPsB)h$SI?<21XtU}wt0B(IAYY9N3DT|OEgHfjLS91tMgniq{2jWkbg)Nm9cxCL zI4{%B0im3@znerAxgf~&JstITyYfHQwPTRbKihkXu?7CU|9KfAI`%zihGQ<|=<9yp z7{1oI69-XNXTVV*Fw=0f9hHx#cbMXoY;XBS4(a^LI!pUh-2+z9_ z#lt)P!OPjZ$$ZJ|%8rdjG`w#KV+B8pP%56MjBtWSw>Htjc+qJH57<^dgg5l* zh%@AGX`uLt=HY`Bkoxxe)eIrOez6c?M?QfRG zm?3>j23_u35#i_e^89$`yVPr!2ACujsOmAm0rJz!vyM=0V9iO zX|qAbjXS+5B}O!ehH zu0b^j0a6V*4nh+Ehdn6*IPvR361d>Z0ZxCh3q}pIUg<9q5U$93pV`80{g2%ea8KaV zg;s;oO(LwI9aTbw#F0|c)%5*wAtGstK7If@X+vD?Nc1gZMHvHRcY-MMhYTRnUp!&Y zQEVdp{abuw*;Q;N_?Vm3GVVm|uX|guDBwgS$5HHh-$+ixM&Yq`B9eo{1po2(>AKXk z`9?I)8Cgy7K~6TdnyU^x*W%`7%@D+#QMD7iitSAN<`p7NB^X2via4;(P=n*$E2war zA+$TA+7XQCBg`%q z?~0?7*+nLqT|gE9eU4D_Oe9=!79d;(I=jer?sXKE28nb_n=P6hyEivGXhP|7Yp~Y} z6P)ubMagG2cK>7!2m4s)>~E-uGlpt7Hxfn^Oj&AQ|BW?IK<`Ic5qUil|7SLdh0)I@ zvr(F3Hn|=EU<Um|MUPt(fPzWb5qY9Z1!_U0M8yo5AYru# z^#4DBBVd$3Ug($V6V}r-V~BDq0MHP>Qi|a@FDKM89vv6MKMY53iH^ULF#9~h$sUi? zqExSDMyN&K&SaE)y_!DitwApq|0c2QB|1NiS&|Gf8K>IGe}W}*0FE93N9rr!AoXE1 z_}32O*`Z2A8j>JXABKw?h!z;2Ww|M>BRkTY%dVwxKedL^x+Q458mc$fklxKxqjSrs zye2A*yY)K`ZGktxk;-GGPDNLkywk28xKMCW#^QFslG{O(pmo&t{_ z#BV8~@gG<6IEEh&@ms6f`BJg`4*me6HG>9^7%*VKumRWBoVUn`)$^7gKVZPEmjecj zgS-27skzu}akk!Ovd4L+!wwhKefGP&O7ouWc)elBn>4e6q9yTGw6+9BNK@|8acWDQ z%4b-=IFWGNa(qGbI=!Eah6M~ea!*IkXx#Z%1sSVmwy5svJhIFt&tv-OqMtUDa2Cb4 ze$wvpb?h#<%bb%U0vPHPqh6 zdw)S9g3m~#CPi}FC7O58yOU_%U5T`=Bv3{Qjs1YyUCnsZlE-g)tWiec-=pw8QM^A< zD7<%#GBnL@6F&E{BcC^v8qTeBq_NGsTe&h+Pf7%@wfHrc!fvGQKfsuAc~fQgph{jg z<1V+5#`$Czc&SC>S{UP_+4d@{t%;X2@A8LppY1BoSlkVFD)&*}W&P%LxNAiF_$H-t zv(&`h)VEppz5Kf-wJ&J0D=$e+bfQ*eJ@Pu%CEaA6>i9OxzvqK`Q(3BGRo1aC;RmZX zSu&~3Vojb0x_W(_mfC!vtKXl|O^Z{T-(>lAksszUWSaBZGsBK~7J4-Uu04#5*Qpv6 z?GAhC8Z)A(XODSSc|B1(&^_kA*mQ%}_X7yR+>Hh!Yk=g(Ge_x8~2#>xeg+nbs* zKvi6?5}*^k`CLWwvCf)vNK-K8+_84}x1H*h8t+3#QPL6B7-y*J-Ar=8>yH=g)SJ*C z>jyyzplf1a>BkGBDF6KVKQ03|ntNrFWs*}fFAGRg!EnoYl-bpl@S0nBhAQC7<=2Q% z5!(^lHuaF{o{&spLe@zOSqB5fD4YNJ^M73i9_>!46@8r7G0*mP%cQQ%@97pvPL6jS zpQ{-rwPbxyUy}2v>rwX$A;B)a)dzPsxp{KynjXJ(P!`CF9~wom?O6XHXp(o)#|sB# z7j(zH)&J+#|5`~jYd58MlF^SK5O!IRv%C)_qg&0+IViFb-fE2Z9`Iy{Rx^YyX;nu7 zgi=JZQ$mu>e5*g4vbtma{h%@4zkIylCp)wIyMJ!|ZfUm6OYKf|-ke7_TIXl*L%njE+8^C;Az1Zc@Qpemy?QnL$3lWt zH^%-NOHgr(!p{Z+ca8YbWI)(Aug3ivJ3w9R#_WG?{cn{-T?PGaS!VzAX&FkNc$$x= ze40O*e}3y|&5!31J7~Gz8&27myC8!x+2tN04yE>t_-KpwD5qz%529**3>N&^eQJ<` zX3w9G#|Jep?D?}ha8Sy^oBT7b_i9dR` zM=`XRZW5ddU*h9V36E0Wh_9I{IhYwS3?49yfF) zeqi1kp|$aCg(LhEO;KX)@aJ92j~vfQ(xv^duiYH}VOEUDG>>*uVmbI%UeC`EOq;Gt zHDfl6@Uo0fRARZ3(?%rbw~qJ7(#kh7tj1D z+Dw^s#NX;>z7m3p&_2y;(N^n5S};$GdpSoN zsGpPMay7=@#9t%Bu9Q%*gi? zO#4ZfYQ@YJ_i~R`Q)AT#&}QZ*$#}Hs=2G_1%l>Jv;4gG+2dcTz7`+<+ zAG{%9CiCL#!d<=6=Qo0MIeU;W`C0NiHzhg>26?l7meqQr|K~rR;l{nsd$8bKvO`eD zio%zTJ4-#jg%PKsRHDdv7WkSL21>E_uiBAe`I6JGm3(sh4 zEugvE@;(-ISHyQFnY5Z+ejl_hhjIRL0jn^s^YZszakjj5#ocGGbSiCV)xYxI(KIJA z?i}67@Iu|?f>y(=oNLA18?JU<_@Pzf`g_C8In>+dC^iddc@ZlL4Yzu+FSm5F8#H9O zYJ#Tf0NhlCKC19P!{HM&RrlCf+gl5V5xv*FVRIOALk0|(C_7-l*xtkN;O|lEwQ-Yy zW10GdtY$OG^psDb#tLyJza6h|urHnNw3xMW&F$X~juAVx?p;~_w4oy>yd0G=@|FFe zE#?QLUtQ{2@Osg%srmF9W-kxT4zoQ!tHNly=E85;OPXaE?K5{$=}uGT?pf(~aY_9~ z_SFUAC!f?zJJx;Nm9{YTMe+&Lg`ehBN!4vM`S$wcFj>pTlNG1S=`0PZ9@4b&fN{$~ z`!zDLH}5{%I_6%+_cC%n%o&%}IDG%$pO$Ucu)VWj@o)2Q8TlR#oSL-o-nI zo$I`Y$euivG%@tBms_k!?M0jBDD5t_%eNj6Ui90wtp`+tWJf){c}wzv@x8#~8^XAo z)T0_TkHssdubBFr=WM&KW%Q)k8#*rdn9JUNnP{JPXZ~E3AvSbIGrPehe)ixD)ecMQ z!IUA59w{fTJ$SLh_n=iy{2l4<(nH?QwazSST-0E_+T_CRklBr;o9(WykG(zr$kvaS zGKw3n2hTpfVv~97$b{>OFn+f3kMkF8oHgUB7WKBK&GXkP^Dc}!y7#2qq}-Rrb52Xe zKRY_IMP7Bt&nrWxDNT}FaO~-XjGsTe-96*Gh@JN)54KCZrD>*`H*>_vJz~c;Jm$=J zWTfr#JS>!w>E1a7{`;Z2CGhlPdc+cU=T99nV_T(97vT;n8+UDG>h|ZfV4k9Phu=Q>kQm z&2NWrN__aw`%o-{cg|ddBsaq(&kYAu#B?T*>|B(DVK{Lf4;2lOqw21azUoxE&0T;e z@M<_M08M@Q)8f2A*VLi14wDoooZOnS_T|+N240@n52`Sqg;iWg=^Xa6e5c|k(XcE0a<3X0N}hs(vj{HpS_`Y96GNEiYft{P@_mq`oEpC%GuTM4a9zYZ4z8(A{_~r{7dw zKD%#BME@=IAdjMm`E1Faf6~hi+WoS_q z(Qevyk2Ix;BW~oSTOc1#5#1f=kG(T-ewK*cEfna0sdYI3q*gTywr7;0u02Xj~D$>5+$^+Nhp zHGR1#Xe5ti5wCQTTFGRtVa56qxg%;{Q{Umf0A1*6;hVXE`N0dh<}xhF)p@mp;=Sw| z^9g0vhD-N=qC!mbYrH6}XfqSdad7D6z)j+dNhTW&sGdPgZ&hy9_N3Z4Xy`4x%dx&b z4{b0L@Y3hCUR6U}r^}8?7x^j?s76PgmlnrvcS<0hfda9kB`-K+g8)=jdnhqle_1Op zGEb&t3Gf}9#TG|@DbRY$7}!Y{@b~+r@$j@NOpKwN8QwJ>#U4yH?n3#v%t@<5^i77R z`U*bMZ{Q%c3!P#Y%r8xGcJ01c)|6}cJhee@z)sqwbGzaSKt3vGH)iLKKIuFp793{j zBE1y@ZOxp#7AO8FPYGgoP85#W8Yy3zFfi*%isnn(^55YrMI$$u)IIzinYKnoI}W%z zwWclbG3+^YB|LkJ&EE>oaYX@qxKNrvLPTUms48cUD~g-Dj}zqUYrI?|Ec~%3T>#e7 z8kc_F!3qcfY2V7xnv^U^Mc*OUu^CiKaFwfoe)-(1Okz;&v0`EKxxRj*Nj?*Z7|;sN zNQKti=BFw3k9{QI-Zd!PZYfyMhmRzYp5D`=IohGOK5Ed}$lkr@Rp ztwipsU|LO@lBJdn1v+=J=!}cb1=FT4*);c0A8vR8>T-!mS!}o}$twWPE#lb-*{9ac zSBIYJwH9wTq+ z>LgS>Ec=@J=?hPB~S{)k%B#5Vnc4H`iyPC}(zC!WLF!+DYw4<2}4? zf3TQ^oSo(~R;O)q?(JYgeMS|}lb_3IRNS(Mk-u>LGVQDoX-+dV7SZ7;D94&Hd&#S4 zFJ{M_-PbKpYVYo_(5JKgj%(_bHbCJ2; zh@}OuL(UZNyRkY3HQciJTna=Tr8r*3uKD|m=>P7S?BKTg2)K*eFFg}y^XBJNVj?1bQX(Qc z!V3RB&DzD~s9{PsRB;{`rEAz@CfN{M$f2MLvC)_1M`+TKdcNBVH!;4>m&hT5oTS}m zY1|#r?pN#I$XSw5?JDDvQP`1|muIE%y7L5fJ_*B`}%#LeKSi5L{76d}Fi4qxy~zUE6umx>MBmR?(z&?{+z- z_LJqw+YX=50?Ugztx|7GtXgyY1);h~_~68_)i8Kn>cxdgqlq7Nr-*~8*`OM;AZgk(kkql~t21msx9*UoK6Itp@OL)4TbH8?e4?FE|2T7!i$ z!xk+(j1v^HfP5bQv}A6VU+8B{IGT!X_pLv- zK4|e&p5sgFCrO|Tj~xnsw#){!=l6y~9q@^&GaFN28S@kjqk=b|dPl zoo*fVpY!pS*p_nLy_Qari`DO*VsB|%@Epj|=qHa+{XHrOf=6?%qDxF1mD%Ut%#6M8 z6I8hdQY#58KtG0!lSa0@<%aTl-<{$`-F(d4HOrR~)-M_R_v0nSsKeBNAt}qrOQ&Pj z?+40foT`vP{WI$2JLa#@PZ@m*}&oVj$hBs1B zhvUO|TqT~IION_8nI0J?heV_vI8_8TAf3}eFx^T$FReM-`?RTFlkJd1Uz?bOiRk2# z&i(NgN@IdPn}FkuB0-`bhN&9d*&X8SZVB>nfw-9;DRx5edvYbT2LFzu{25K4wM0Oi zj`Hl!Mn7c&$Ce2*vk>{p7fyZVy={P!iS6C&G!uO9q%CF_LY_n7}2!kVV9 z4ByTle%AQc6NnST*dJjh=Mg7%|GVKlArNan_WXPMc>?`kF0Xd}P}fgj#}=v6b-v&8{Ti(q zG>sZ0UH`fWrN{%2Ucdou!w#jrs1X;`FOOj8!_P(d-%V z+eE|UY`XXCw`%L` zpmv>aCXIR8YW3=t^T5i6~@=(cat)jL-Piu)~DWusI(@Nkw}#M=B3 zXD0e}3>kH;`sI`3;@N7oA+N2^jGb+{p>9mDlG&(~?bU;PVkUjBKC9v7F9Yp|a=X{9 zy=A^aW3)4?`KeT=R~660%P%)}=t`%ZCmpofa&HG&EL+N!8YFuxY-mTL*V{9e)KxXS zT|bR7$+iFaa?+b6EmEU8_?Em2_mUU0cl*iJXJ6DB^O{qC^T)+X{`G^+_fdX%H`$2P z!~m=b5Wes~L*NtD*?PB&nqUl}txu7wO6%aeHQx*vATAuEibh^PeQ(`^IU|=gA6Q=9 zb>3m+u;|Mf(=S!bny>xq42Q{gj$i!Ex2gHa$)zKY?;3i-=|k<#?1r2r$Lo(9w@n$T zd~MP=vFzN#xxZ%fb~#BXiVry~KXmS%OC!VH@8GVLUmgE6GidYpl~0Cvoa%^jP1Z6v zt8`-AGsEm%y0i0&>H_xtdV+N|p?NRo=}+(d;*)cimZr~)<9`2Q!EOh0$GTIETVtm0 z+|vE*yX|YI9y#b<)O_KP+52ckqx@RSjU^e~T2~@g=0`^*U$BufiC_0FdkfulN}1*G z+Pq_HbW`|gQ_lPQ$h&PGzO8%i3k8k*0|NvS`CMv)KqC8h3q|(%fZ@adQIhqWadRV* zY#K;*Qtx4Ij?Q*JIy%}ROArX!_Q4!Uy=Lx+o9$cnZCO40l*{ac7Uu1P{B9?&-Mz|2 z!=Br|Ve-l;!=i^q{`SkObB|XxgS2{f>5bSy|f!zV@!Z?1#qGgc6m*!^0)s+U z%=6mT@HUUu8p&@oq;(h5541lBqIK}{=$*0M#i5Sg?21TQJGYttv6j}IqruPPbKCj5 zyjrix(l~8-bbeb9gWs9KIMCY6;CAHDcxC(=M;^ONmRAug?~)?SpwM6Qq(76>fz9*gkZFeKg#^8SB!b%?)(%76b?qhoX{#G8F$8Kn5rO;ZtD0fvmIvH## z_hSX6`+XSSn8#_(Zt4o7@*5dC&i}woWGB-2&9wH4Ai5`aaa)+< zqmEAf?xrpZuY_}I{D?)cJD4nP@Q+{HCSRZjdP`h&uD0D=5;=f%;FdFyVx`% zUe)W8p^cPjEPiKHm2Zoz#3TNGqmFy6vJw&e&L6xyJ~kv?xy#q;%5Vg+JM!NjZsxPi zD0dw>Eouy2w`|U*l0^E`pl1Hll6ERT(~B>0pH89juAV62w{$nvf^28=xfM#?9h^vB zHp9CUq>!CQVNtYO=#LD?@sBVb8JhBs&;uiFcw?n01zZK5w)c;@zIkdc$6BeDrn~rpSPtiLQhCtT$mU7sGKQ3+(R}mPvVm?oNi8i2PEI9f(i#qC zc)xzuLMx$l{c4&2p>uzUi&M$-@&#`bsL69rWXviT%X$Aehp!Gg_-2GZ~@bUC__Vkq6dA|kY_a7=gAY3ieW4k1TrKl;$Nf6IGb zy(6ipXh;0*%@(_B(dD}>+`F6Wb9ThX=NRuwN_~}!E@T53Ny!&yn23&Lt>T7e}RmL^@7j2K9k0wPIm~_eJ^2x52wl__;D61yB zpv$=H-d4)&_d#a1wzo{r!`+XyOmb*_PUNlIMLTv8sNnM5mae;-OLKPYiqCmrgHgf7 z=yscX((SOE7sg?i3joz&zPg{f_;R~QjWrpsl~vlQ>^HQM*6de#IWIoa8}IScYg>2h z0=$>i*IWd=6b-oO7L;PV{PU^{HctYPb!no@(U;mtWR{^@l#fdX268Rnf@YRklhJ7s z5^`So_$;`40WRpS0&%xg`M5gVEr&}FiaVPp*~6@9=mN7khU`n)>|vX`Y? zU8hwlb9W@Migwh&dOy^n%XeG&cQYRC!t6(4%sx85c-?+xK~xAua3Pq?59ye>kS zi|=9(Cq#jm@+A-;bf7}v4kxDz=z=ipsM83uzNDTVmGkc1LJhd+7CfrWnXBpzcV}fs zJ%zgpa6xyU5_hGuqaMDiO4~FlJ1B1)GN$NXzCuoojQ;=yr?ytz%&n z>xuC>b8V73_B({=g!#uD&kM7*;Ck3MwcEAG?6w?9-x^5&F_6AZ$@^*Bj-+EnJ0{-V zd|*ir0tfZ%mGi%(IFi0#_jG%X0@%`-C-p)t5iY`19e+1lqEpEZ3nEB z^T4W>#6SI%za3^jQxgrkh{!urlLm}FSE_slxZ7F|7xCp`ks8@|Un|eMvw0Q)8ZJlG zDUKoTNt<`rCaneTCb*!>ID79(<<=cZ&x>}PgGF1^qRV%s-FG*?&)IPfv9D;n$o#rm zcf6LN!`(C1g`nL?bU}Bw6L$lx3x9OFc|cPkI~J7QR{QjpBk!#B74_^`@PnPsCqfJ^ z`o}cpU9@I&Yi6&z9%69q;locg7gWM_h%YaT+?kzqPG#`|bM+i)ne0%Pl-;E&FRZ!c7?QnCCDb4r zPpldiizdF3oz-zUB)qj+@@E&5cWb8CgP *)vTHRJ}dvkJzGji-p=mfB}B97FThvq$a-*N8K^C?T(#cDLo)@VLH-rTab zs5WbucT;xGukK!_YI5}s<`$2!uwYc3i_7N0)t=a}X$POeOslrl z)^a+5zlYqtuGb{!orEXy;fdgY7hY0|6`_HQqwZdJ;EPcBVwfd-VN>WOwGgJF+(BRD z>P5j9dho@$fFduc)#!`N*{imM+FJ%SK=5(5Y;zrd!#qLV=;bTx?In$;B%Z4-&KTLK zxU1cE(9D~bFZW6C)pt)H;SlT9}^O<_fJTg{0gJ)~3L(T5pb(`yW`n`2nN{7}Mb;;JdA6gZoQY`GFE)`_2 zbZqgQv3vSHkBRjgj2+WTmumi!67|x2G(}_g^ueAtw@7Vo?wnVAE^U;bt)u3YiW>(d zn;zOO&(EyQGu=6hFEjch|Ixq{eIJIo8;X-m%vdBc?+OarLZj%jmgYesWb z;&_}bK3(RLJOq_q^NgpW*_{%_gE@JQIs+zL8?Q5<%dEa@#?ApUdOvxo92}_19I)-q zw=;g=ueLg8zSL%5*A|~47AFTivR(euuQjU&t7?u(jT-*JZn)we9cg%c;Gj^YiK*2# zZ+z5mB+g|1D(3#fFB=C-9w5NWje(JC_vk3VNI5ZC0(_hp%qe3bITGePd9UW#NL9`G zsZo<)q{AMag$UBnP^HDG)gRyZc)*+;_rwNng*oLuP@guRDIct>_o`&fgttB?=4@2b z9n+Rr6s);AHEJe2etwV6Is|D%sM7k>>XmPOV&U<)`(m5X62LFjRY9_xqdavh<{SUAM^7H(D!E%b42-r$B6ZTqMUWoEw=?@_;urIq7sDpt7M#T>!Mohl7AV78|%7-gJ-vdeA~r2Y?Pqi}FQ4Pm)0W z;qgh%I-@57&~HPPq|&NaR{PAl1wfyOZAOnD1EAHXFP;)FeF8w`WvWjB(50V9peteI zoTp;pFw*a5Qp(XGFsGHX&K#IiXI7}vytL~4Y9Ct|nfg@hEt)gjBH=^z=?7=T>z@J} z6l4bf40HP3qFv51bUx&)qxTv}TH|wKE|Ao?EwMT{P0TL@9=CZWrfCh2$5|xk)tr_O z7C-+CASudh4~EBYIH#QsUUOojs*MteDZ%2T8Hi~>Hfi7AW@m-`sw}fN1V+9PfG>qP z_h*aULvyA9L2FJg3l+Z#Bj2dX_=UnqmUG&z&^4o}s&Q&CC*4Bw2bfdxxqzT&fuLJe znR5_9ckowRp1XKfe9Loy^u0{=S$KT9OWK%oYffxewV4Z#KeIS#4Uhl&yk_+dRn7Bh zQ8^%{MJ_rKNc8hbG6u}=+VV}IMgA@rxiUxKoN@rt0-3>KFz0rcw7FqxM%$~#sl%LQ z7LpDyGC!y0nS-k4-L$AmnA6)u=T{{9gbHz6A1c7`2z1N<;7%pC#3oBYIQymU(|Fu;>P#8HUPb?fp`mqFh zZ~I_3s@z4V8RnGJ4psV;R{gxzhnbYPATCerHJY>ABB2`Qj1(`;%X;|}MW!ec=Hw+| zy${%{GqAK|(lDmakolnZgQVU^-%ebxG+%6{4ZKLqGGPw$bYYaZbAHy#H##zdqv7!x zd(-AduNm#H8mHT}WstaKzCQ@$Nj@)FdtS;xqr+`?hD=M3k~m&`R5FIER>3TF&E^nU{gN?CBhdThO6f0l#;P0jpObYiew1n7*Ea-9S-Py)yIdaT zJjOh_0_MCAbFSF?*_uk}#ta3`Z_~e(YP1`L@J_n6K}Qeh@T~kB-7iB*w;EosKta!J z9Ee0GAmKYC5VaAMjW7!Jcy}>juLXcU1mVtL zSV80J00&LE^k~UOJ8|8;%j70qTOg;Gq9m7I2e1VvoYU|R@nu=t9T=y}NkR21L&Y0`*-tmNr>8slPaZW*h)H)Bl9SE5Il zAm~6!BOSmz1SyRjN@-ZAuN9Se*-oDv7p}W@ZYR-)L8iQhW?+y&3{ZtOBexrdB`@ALC9Aa zR(k~@PZ2?=O=PU}6&2|vgps}{R!-{`D~rx)?bLIF{z2otfF{&GP(8-@ma2dPULOj)X~&o+pnz|<53%;Q_EmXO1yjLu0?@@MT8iUn87pn1 z55@X4KjsPOA2jF&G(rC$Z+O8}s5w0)V-}y0`AO{iE`C1O+Q z(*ASePD9_coQ2)&%hm*Ow=tzSNRLcz=0`igiH_ z{{=`)@0lPH$qG~k50y*52z`=t)RGaD!4i6V^&v}gC9))<4DONApMvQfSv^Z~OhH!L zQa!gBkf+G#L8wo7{#BCuD`9#C?R+<6%nEpU-gEoueFy@=6oqnT;&YYheKaW=Pgk&H z1++-|(u2&}`l(0I&iI0MMKhMG#P&KZk4V`^n12Jzr}I9uj6bFG{}O8cm%tRo&3}gl zeZe1zg84Ua^B)uXV!#pYrv4W1{)Z-{FDfoh6~@J0FkJ_K9)uc(i3mbc!cg7IA?b^X zl~aZBzn6PI(JKheOqil6=Mg2@*f30&wG_GsqvZ60l;k|B{g?-#;FKR$FbKK_>VA@1 zP;j0a8#5FN&J)x1B%r7-mDELXWUYPFL2&T$k_Cex{;Chg{c4lRHc?VA=L*(R=pKyP z3UkVPR3Bp=gaTfELct*D9;o|CX+Z&hYF^AxDBw^0peF$Ze5oYFCMesC$J$Is&+D<4 zLIfT~>=YDzGYLxDMLv>RsQ0mKSV7h5fN5Wcp6sDRLZd%DW+)^y_QN2dd4cxX`@Ec$ zIyXi?H((lc4;J}IX`z0|vIzxM&)_}s9(`AY_u2LJBxb~TO+6SeZ6#zmaseP^w9o$6 z!aTk6{Z~m&Gn5Z>>hoC1TJQUL4Du@K6)JHT31TEC?(+~NyFf(n)*tnGn1|O0L#m(+t8LpW zP8#pj)|BVy$aCWE1$d*F7&Ip)Qc0fkbYg+TqymK87di)?eo|bEi3NtaXpFY)oETXY z(B+RoOgs>|MDtsY4u6A(0*a|O%A8s_{e_^{32d}fLi zce<2U(NaAM3hDa9Zbr&aMzAEw7+I9}$onyCR|j}IBP>XE+$iWAOq0{2nCY_4j74LD z;Dp6c$eY@R;lmV=WsCvrdMsavm7YX~gm(0q7l$BRldfsq5AcRuNMWZQ=Gcx0WJ{6go3;5$EP1g9w6iGD9KzZ5t-fNt+8Rm*PeN+kQvD0&>8y$o5qykYbQs_Do6y^#8d5 z0SWu9oY*5kjt6jogtr2#SFp}}9dsTlfJK0d10s0MK4uv|Xtyg{VB?l=QJ9$*@AC;3% zc*(r4^Nu2||G&nw( z!<>dya7rLOJ(eCs4TGLY)cfTT;5(mBEEo%089V31C_qAD zKSJIEj&}l=4g0JJA_R^^N1&B5PqJVvYNhnv%J>UmqN8$OBRP@a$#a~boW5%poa5|K zW&~tIu)#sf7;QWZ9)lZ3u<_7`Ah2}ubmXEzQd;N~rwK~B2p9iF{r;sW|A+~H3ryh= zwB9;LC*}HCMqgq6XTTKfvi*hB6r7anF<+7D{Xc0z|8k|{lX8FB(EsHy|1lwvL1?@% z0`@W?Gf_dvQW#cy2O%X9LC8#0th5vv>BWSRz9&|W=oKsLp9jy2k%8WO!Vh|Cs829v z1uK1Sj9G4g74+WIeWWr`pJB~}f`(@SR?vHgvuX_^RHDsp;>u$cizA^l-9LupunI27f{ev+9`e*}+>k%7&O zgz0)}sHi7m6KrPmpA#LLwCVf$MA*!LqmcfvnV~eHKpe`sWIw4)DBwR^6Xag#oDT~f zW*m?3&fjR>Q(%4(5-WX7jM=&XD`?55`$%S@e#n|(WNd^JeXe5PdY}`1A-zuY^^($` zfhjyHXEr@X2JMfaD(eH!;&=V-J?aoZpND^$XCM?xcL#6c?XnY8^ zSAmEiC>ZF+be*Y}cmc@^L?q`C4Jl`cWK2o0WG3`%(63F#BSL^Gh?En~mGhfV&A5YD=@qP&dBwr;!*8QT#n5j(F?p+x>);H8;jBH=q)wbG}lU1!$2I3c8*JR6;t}SMu;nW6N`B zL!&EwkW?n>0GLY_JkB#Ef1S~z%)WyA{D?viK?M65r6p4Xn8zXQDnn_P-~{}a^eYlN z282&>HZ9e2MA?V59%cgk7W~UR>FzRpQkfYFJtpImyucL>}3Li%58jk#^PkqKI~8`>HR zj%ImBU1X+4cI;7Ax#%WcTem&*+82u!Id_ifW>$@r&Aoh(mHVzdkRi?K z^i*?KvA-lwPtekT(Q-th9rAS0_&b6y5v3Gd*I!JwE5>NH(&5{lI8)ZE=!?%Yzg0zH&iv#Mq}Q|(~1HbB@CVX7OWU0G*$ zCUAsGy?m&e&P9CN%JiE{+O!+IAZKUe=v7_-%*j}8P0nk)l$`(=VAU9G=#Cw+hz+8t z{S-T9DZA5`o%YngepX?t}&STq`q}% zgUgw)5ykcL^xWfNBi`DAuHKbr7z97KMh8u?!xTG;A1i2I$PQaA`SS5%uGY^NOanH_ zcDmYMFlBCXNp_PivFd*LB99T6W>;`a`%{BjRg7-#`J~L&TDwHOhDf^1nc7d6KK;rH zjoKoMG;XLk&^(f|DKf0w)W%#k?ZEJK0rFo3$e)nNb9<1N2#_}jkT(dBH;~Bfgvb*G z$V&vsUkQ-^KqCJ^fV>cpKecmT?|zoECjUl|;epf;ncx98^JIVFU%YU^)aFNcz~O@F zlONFowUyl28%{jpaoiWCbQ+A``=M%Viv{Z@qq8-w(ZQtV*oVZ(D=ysF5o_B>Wf-@S z%GlC&Dm(OzHI{&*qRtLd0&zRg^yQ|*b`sOuU!4-cWw-84V3^*^LkzH}H1)~Xu6)`Y zeIXisaXr%XV1a-!F9eKf1mid!I6~7NiJ&xta{1Y*QY^4l<4qf}z*f!tp^+4rJ&Z=G zcE_WUs^=w>0-IAt3T$Ortwc!e`x}jkk%wKhytp&>!#D5JzH^|r*19A z!b-t1t_B$|DlxnoAHzT!{n3Pg|7+wdyjR^Ev*4<4 z$o&XkrN1=1`s;p#M#WH3&Rw>db?51F|B!ajYm_^_t)@8813>ciH8tb&S?I+J<4>}Q z7k8Olozh6c)M+PSe$zq1l%@&U-(S_V?3Al1``K z1&B`J_yyQ=+$ZU@|1C+UlW%J!Ue?ai7=QJxzIXU!jq&&2UT6$|nC2Fyc=#}lyCl3p zW5dS>V0;ThHG-%A7Uah9{7y4oQi}4ap>$z}UqxcHt!9}gA_Zhn-sfG_kIQXVdo*8@WmZ(W3fZ%3p;n?;YUCp zi3X~Qx1R)cr>m!Um(KSON;cKRpHalV{+dc>8Hk_aY4k z#p3l?Q5Sd^7_^{1H~H3C2R{_)~Yt)J&T2jL{J&nV7$4_{bhpIN;U zzVNblULS1@Lb&6!UT!B6f`uoN@e7b~odqS{#}?1NB!2L2!R+>=$Q*?tdxRu|nEGBI zvbyf>dz|v>Slz~M2-a1xx*snjWhO0b2Y;I1O8V2LPST&UIy-%9(lon~S}hDuL1cw* zAhI%1Wc6Z0&>h4DG+QX~-}oXlcb3Ha`FY`l zg^*vNfbM1#3UqhE0O`)H6AjfQhSmd%_M>U*-|Ph&qA! ze*w~eeeq#izAJLNzkqiXHEUZT%V&1;~M3%;wl6dfT&f){-^_! zKy1mbh+RFV-ha4jB$YN^WBgbG9{7n}aWd-gLhgogQxaXJ{nbm+Rl@C#?+5F%tGe`~D8#CYggEVbi4*vE2_pkO)*A|!hfI=`J-kjR zWCz7r{V{N|Q{!J@?RAzfUY044G5uKB(NTmPz!#As&guj)EJLzf*p6gL&YP~jj-1yH zFN07tEF*?MmfF^27%yN8q=z?2^@C{&QJ?4ppC*sNMI2q|8FV&eN>Pf|;>|{0mw@AoNS3M+H z(o_*?Jd<1*n1?{-4kj~6t)ZJ(YsfLo6i~HCU|)Yzv}hB(!xRau-dt-7Q)OfTyaSEl zQC0%cQbmF7ZEq>@r~N#(>VnOJ+aP3c!4qyC^4PkJxOtN_ps&9P9!;Px2!w>ba3B;| z6r@cUt8@uUn@ICR-b}zx@Mgkwl?&F@l-e^dQe=P0Ue-f=Agul00~RF-;zHwJMR*%@ z^K*}2O?m|0fu`_iD}lJFj|?6jB3vH0lu7meqg*4`96`DuEDSuaKwWowD2wDxI;GOo zIKpTWG9h^r$Qw!lLf*I(FgD`z6*a@c%Mz;6vyQ%%k!&mFFZ~cAzEa`(;FV!VW(NjT zDH&-DKY7J4e#(OS=O%+TXn9Y$`|aTw%ymUplP1d)&D&>LVQOKdzx$wgMP=-ySw$M_ z;&y&WPmf<1ed5(OGU=HH3wFmjmK){0a&8&_AyH{h4C_Iq;87a-8ma`K)F=UjPBwM3;FOEFdSecQtmx6Ye%oj6WpCJ}zEA zu`4J&4!@a}(m1{-Wh(;g@rZYEouX=-eDbgU4$Z3rhv@I3Crp)y~7i}O13f?C0>tpXl_aBu&gqe6fWrI z(mO0$W{+&S`lPby4OyUBa^18dgNMWW2#C{mYHkSv@u%E zDi$55O=@ll(leU)Mx!Mu<}&>!7I-OtO6}%hwxcH32TrbUkhe}4#l}kRxYkt5NG%Gt zzxr?#n~hgNGBjDec#?XNj7Cw3{xb{w7*@Z#!JR|H*$;=a+3V+)_;E zyuAFL--*g1$d`OwsTde3BLj0Fz=7ffh0=|Q!CKo&f(`DFM7=JU81$%KOw7yd2jY`i zxovlg*@084A;q<7DwlU=+d8fC@*13T=T2toC4%qP3zXy4RO1taqSBI+WkLzdGOsl# zo^+^4<}e`1voI+OT!xTrEps=yb7(62;Z#`qypk7f?@nOjN_N;__i8=0d_7fG)5XAE zt%;y+!$xv2Afz?d;IYiMkm5O)vKC%K#@(Db#hCC6wE*PNxF;vPx611?IT{dh#Li71Tk>9S+3KdW#@dcr zRu2+wxVSSRzVRWR^+w~}_$@u4c9EcVdzulTyu7NPF94-oB$TF9eB)wP>P2vIx5=Bd zk_zyf6O5@-j0s=5Qs5~>h|AGr)S7w_bA!B1!u7_7Gyh;+;Tjw4@T^o>Eu`DgSm5?Z z;QNYX+(2cy7Hi4^7Zd!*FdntI9{#049xsg)BA6j24fZ&0gzrs>KP1O~C`Wjq!@_$r z*$-#3*;4aMUbekE4dm*!OffU2isC_-C>}Hz5bVm*_IQ83)QX^2*~_pVA>O%73Nbm8 z6k?XPGa6gIo}gl|Ev7OdM3NbQyU?k$@Q2*NcAXp3tNK zOt>lOsB-PDdc9iDNJEa@ZkJ~*GV|`@ea)^#?ZAgxWavs~Z1HVSM}lb=P}&6rEJzDn z2ww$Bi|nByx6$zsh;GI2BaO<=q!B2YI}^EE_2OIts=fVHuT92`G!%=U#g?WK2?694 z5^L%ghoaQ|wJBV2&eVEdIBoJ=!L;_Z3yQTr#5I?%&wFKWy}pM2E>K1FYNldbbEXeR zTRE;7($-h5*2axw0q`=|R#v*m4HE9Vja!TuX(;1{xaARsl21($*{loX`~9=o+P>*E z&SrD_X0r(FtRgp5X(TTqD~;sv5)fBZmWz(owv^)K4~Y!X-ZH)o@~~RSxf8CPIV#Mz z8lhOo#l?b#pjZHt7|sqKTaSI!IwHdXUp2XYu|^T%9*6X)>rh?`~gF+_?@mM;XNzU2#&CaR};moLqt%9k_|_0;cSEQ546 z9Mvx$-6}G_UYbO{9S&tpMnc~LhF}6zc)jbFzgy$iOHj>+gqC6{UcXp|3{SnN2^LQR z0*e>WAWT35pq3vecQ}!v;NlWHMl2f40*8JqK(#I=0j_n`i`*PY-4L}d!b410v9VvZ z`e(G=+jg`d=lg4Iho}URYWi1#AVBOm31cQJK?J;iCHVIn4z8&&%lp^Vn0(h&$?Dl2 zSI;E*{(fEGZ7c=DMarg?WTNzrbQssyDH0CD9%Ui@ebB$pYW`T)mHSkX2S+}wtZfAN zGy-@D#8d1%^Lqn#5cDg+C6X=;jDc`zsPXfeG2q4zxJ)9??%nw5>!?uD@tKb#%6;Uu z9j*lu=DM{E5=?C65VyjGEhpTr0Ft)svqAQaD~fiMP3n5p`Vl$uSfbh#6-dD6f0eZ( zJj8?!5Jm8WTT$bO41xBp>j^)D%Q=Cc5r&&y!29;fa0Kh=m0dS*9XYvvC<-^D?c-#z zr=izR%RI#SemDA86l+bU;@jdCFJl)0cHha!7w^6bSF#)7I&y6NP#kg2nZgx<`~BqB z^Ys&?izHAaNxl^~S{1uB`-au7BgN~7BCEHAvDkg;rnp{S1g$Gy?BiixGGdmRKAscp zy$2d`kcznOA=+l8)#bhcI`z`NJ1C2gUgc<&IN2UM5@7FdM}$cG+7VV%KRfygL=Y5S8BzK+ zP@&^A6{62Q2xq;bPjAhWjYt_>7!&dph0*aarV6xO7_RNOrHl2`LsM+o{bVEx5pL;v z@9CT3-38hXXJhU3cuhz%zgI>wgfz3SDfL%4HYI|xeNE~2Fz#P`8+eP{4=2cR zO<`*k`vAg@927|oLu;+kJWu$jrO?~*)@)v zK;MLy1CbyvSCMRHL=jr5ARsz8t_LSc2*|RJlSGey7Rmcrjw|Yy6K-M=nQ)?(?lMvznE20WfHT`*xfYRh2uRW;_L2cS3AkKO+d!WMT z8`1h%VuMQY900Tw)eWm24n(~&Q1<0XZG{p|SHNS!jFG4-mz=qL!G|ld<%TGvt#_gj z{kK5dSB8|-NECo5+&A7t0BVAc*g&@LAR?Y-J33sxu?n0&q2o18IaSy$aqJS8-IygA?h{=$J&G4Ig2p@4^el>m@}2terq zKEAem=(#zobDK85R@eH@( z*OB0BGZ=!g_SVMa*s@$Vx(f(C4GI2P%%U{>y5yeM?X%o$3a`cNx)YbXRf}8g0W?$! ztgpsOLXC>r8xh{lS|~eMvBZSP;PHg{jR)EnAI7o;Z@Ny=f$*k?66A_d z=*27A?Fmk89VIOsEhy&QK4L-Aqld zuukC$k}$MF2noM*qi@yZRyz}Eem0>CSmR#K(>h{}SBNzN4@l%-i3D=AaVk`WF#&up z+D#D%EleOZPLsykE0GsKXQ-H5gb9cIZVl^9cHKnBDh7(Zrq_SGa1>JUx^YO&u2TplO$zI#0@#lQ zL%5&|1pAeW=K!r1AyKS)SSJ*PKsS&-5u$(yMh-+F6%V|D{4O~o3aNNT6jGJJd6D*{ ziR}s4M<}6XpDhvzXrbG(z5YK`mLXfyqNiB{+a07%>o~|9Bt~QVBkzRwJGfh146L@mUo6Af%EO z3#Lt2Y>#P!Zjhl7y4m%|3r8Upv-f^77&2jYD5MhXLm~BZ_66IXT}RQx9_Z4$y@Vlx zCPqL7LQ;*d(th(fB+n}5z{0sHo6+(se+`tcIFP!{u_C~{!MA9_=W z<93_Y(Nix#F1kyTi`Cs-+*Ti4mQDt>9C_2K90bFq^0HI7U7IqBCvGx#81oOg<0Xc8k%b0Y~dmy;m zj0EMYaK+JVi)jfk(Fu9h;N`APg!Mz(V0U&MeIZi)vrFluhl45vygd~HFQ_Wq8+%t& z&|RSdB_85{D5L}wbd9XQGW0H?L#l-(6xPY~4L`ZC+K@suRTPYc9tpi^?G-8t7ihx> zhl{-k)GH7z=A%FfsJ=x|kT(A%@2h>4#+Kys$dIt~?9{O)B`W7s*`z)2v%V_ zh0LmBAqQ4VKq~|%N2GMndiVuMiz_feMhC5jO@?$-HX!>TGSYpOK#cvIhb=^b@fa}{ z+F;sT@S9j@NZ*8i2BASd>IC^HifJvvn8s!WLgw!niZS43h$ow6_t~2e3E***`T_~q z#N$8$E$%y%Bm)T=2(kkSJU9;_A4I3JN(d8z{wz5mQa4fYpnfPRbmY9qdH~v-f;Ex@ zak2H;jKF;YIO2XnKP^_OUPr=1x@m|2Q9cKnlcLlnA}{on;5E3Ai6v_~gr~Jmrj|_H z2t24CN~{p|XYmSge^$VjZ~x zLtNepODI?%mlX&d0msm`LbWEeLWXN1!lTW7cYsLhTZu#x`m-ciP-ctMf83uX2BPgi zJTMwHmb>a?+6nfR3)zR~C)h`p(Qq6B$W4ljtp7!b3~>S$2=#lfavQowKg3%BvL>pMbH?3 z0}BsC(WcjC<=2SfcYu$rmq8l}4 zhoN5i^|e>wimPF0ZA*yPYoLt*^UbDk#op8Pa{6I0b{G~Dj1_LBS3uh@2dhZEIETr-75zi?w#g zF~}{CigJRouyZb$whU4OVp_EC-wsNFegCS)mk0`ODB34Rc?%W+=_^(sY?=huPm?Zk z?8|!aglpp%7trOh z=X|zdAdnD>k@(CsxnY1#R-hQ!A7%e8_wQl6TTu$@Cw5O87Zf!M)ZQaFaQKHfIsMOi z)K8mLjZsw+;n9iL+oj~f;0r|gp8rr>FTdht`K92IVLl5 z+3EVkhJg$0kD-FM_l5x`+g~k8oD%&xb)z``87c8TEB8G(-LmVLa=7hgrNb3)pnuz* z;6QJmt;>BcVxP6262Vas{s*Vzy-rmS-avS&0`Ifp3486dVPA?>*ne{f0Y`D1^hJ1c z2)Qlfv*7`p=ve*b<_&mAf6@PN0_I*n-%fI`uWu)S_YQM}A)?%{_d%4tE*nnsjbeMg zLPkU+yS;uo(T}=lv+6UeAwe!D zzSg-D2T_P1-uEC13W~iB!-;f|4XfF(k1c_$W|~SIg|M1>@9yJv6|ZAG@J~>lp)0Wm zVZeqH3KC=phbtMvBfyuxB}4dIVF;hMJB~tza4oEJ@d^mxJI@-?(6kW3$!Spt&$|)D z!#n=L%h`L#e97$U&P_%%yl)9(1wV^WDxRl|aDqp-HqpX((P;<|*j7G_H~n{Cg)43_ zU|;l+|xpY5n?L4bVlS%91k)VHyWb10jBh zGvse+p!kXA;e!;A`u6(O3?aXMu@GTLK7kZ8cB6+;8W*HqB#YBHhN~Iup3hqwM?ncp zk3)h(3lWe{zXcD8N;K>t$s;sK*Zq&s5K{h&QTB57U&2^+QH*^UfrMQj2tNV|_X|Im zA$>~*UG7^E;pg|{)(a7&QvxOn!%uH^LTy3(ObYTOE$}`MM7T}N0udOi8Vk?^#LjjB zu#jL;fA5Yo`2|GS2Y{w~CwPS0>_?%IEn(AImCH@&LrV82Pl&FGaTeiF&FWf1ELxvju{d@M`+$?uZb`))a4;lkbkYN zK{W^gQVlu|LK6UoJt+b>@#{hoxZunIPJgirMh&xG=`RuxuE=|z*}`u9kKGb*PvFyq zR)f+_BCMbtRYHZtky6st^!;%mB58^~egHdZLtO1h^etmW83SZ@f++Kc3?R~9JYmmK zY$E;rTYO~MHEbsMn48ry?nLabdt0$6;6xH#a+ILg{jAu-6I` zobxP2$!9ip|6~pa`&j7gZ>WefhH5xB5=InES!!SZjWtg|??+h?c|8*UXEuq2(a$Ec zQJP~mxgG#u3%Y)YBao22;5EC=(ZNBqYB>B&{_^@2;T!+VYx-v-gur31rB^Qdb#gcs zN1p<}EkRL7Ptbwhw4Rn0gVeH|TXU39izBE-k6ROff=Sp>d7?`NYC)t##SEDsVYLYK z|385vV3a^!=$Gmf*3&d&h;l0c&=9{;is3mgC)6??9T&qt3`cN@j=z#H`#j3Y9*@+b zRIg@6s72q-WR!fpnm+2SK`$2nCb8@#IzNqBk_<5!r`pMXf+ceRjvfI=>MP(N^8K$(?xZ^{cf+)yk|RKZy53>&8(nkNxT)UErAizl)H4C+ESbxRL`&9qhlhOU5E3xuG z$A`O2?uX1~I;UD9i~mU@!h3eEH~+Q1>|I{t5lGG<)aT-iOSl9$c6 z%PpjFJ{bmHZqfK9jPcQIN0rsK#4DM1`NO%-c9&-??uI*+`>F4;e)BrgHKKidlTx`^ zYT_R1+pPOu{#}#W7c|+Gm!u{-QLC~Zc^&VPZZc1Ge4FLp^Fh6-EY-0p>v)&&gVmcX znbc;nCeMRiy*^G$Z9dr5@6YI_#i`A2vV6P95Azr@&3WyaVaGiSy_x~nUPi|2RE>&u zhkbO78Bx@8$33gOo~Rw{9`j%F=ScVICu;u-{`hwrKT+%RXPdWsduVoJ<$}rWP0bmg zDy~-v(23rBzM}bfXU%z}DHwD9csu;tF7--{_o1UG>4<8KvsCqNCOP2s$BTCAO=yty zgP;V^H8HUCwfByU*mw_A2y|T$N$*Gx_1th6pxaB;`?CMH*&8<936>#OsYecAs z9f)n4d&qQ8NG35M>!gLOgMng{E&u%azb*rhcBj;eKF;g7XM4M4Qdj2pbc-Y>$GeWt z)eMtbvc9J;$$8ZEsQZPGV3*(OgS(sDJh^pEkKZ~Z3uMI)jiT6gtbY(R$-C&|#Y3_S zy5rvJ|8whqtt6VYn^HW<=tmF;yDZ3A-iMOWt!CF86xj%GHO6}{crrw*8A6w|s-plx zDI(cvA<1UG)gMk--Ld|D&=~KZKVI~co!R}}Kezt3N`h&*Kdrwra%*4CI?AKbJ>D&O z=heNUoqzKC56CffZ#}lPc9%MD&Z8Tx^E3FNUO7$ek8ZdStoktcMjeq}y&C>QA;GE} zV}Fe$sJK<(Cxd~zNBm$iAnco0<9>}Dpe}Y}_CL4&w@RX}f_}Fwvw!-u45d#z&Bs$d z&7aJ_ux+&F#|wxZwA}9vr|i#NkinSjat{%QQhQc>w8eXr(=*x!Q8hmX3;ygmJxD>b z=g-FzgPIri{Mi#YC}m;KpO1$J(H8dn+2c1ze__v`k3S8PSlIK2$(Hco`daa$N+`rf zZ(dX+1^&l;Ii0@5$JY`bZN3rQsGSrh{+QJrrAA?9OK?8<5+5@qJeqwgyQ12)nfN1* z6Ghi%CQ5J`e2I_I5*|$7X`HCT+D!aWyEDpAn|VfpQ|(K9^q25>>uc2!C8N#6AHCb7 z7+Op>2~LGC@o|@gN2zZ_ThtXTCjOYkj&jsunoDqA`Vt=vBs>azD_Kz*T1@_&rf7JdI6|{sYFTr`@i#{G`r^OJ8<7+0qPIcqg-i7MP zOU)ITIz5lbe|cVQ^C1c0YkQ(XtI3pkguJh{N$@epRYEab6J;ey1(5M z&*3JXX&N1>$TIe~x|+Xcd?i;J{^9(h8@Yj*G{S3Rbev%ec1{WI;CeBbdNH*_U7 zGVhJh+Vr-<5&ns$D6w|>^M1*X9M4J8rET2bZVvx2D@J6RN4qJp9Q-S<=Vu6}P1mKG zF&jpBSw<%+v0TY%BNFpl$9rVy=9w`&M`%&WX=RmJzW&}f@+G7>_jD8h*}e_nb%Rff}`OS2@W%@ogci*8qCRr*(EQ0h1Fsn+3GIh!ur~+q~FUTDsW{8nRq9 zK~r@AZmL2bRrsIb@Cll#du^=kt%bvg-s`@wISjcW0|rc#9WY>Q?_qfG_o(&SxY@w5 zOnpLDvzcUi%BN6cg*cPnPEdt}K7r(2)~fj>;JM%Kq?H z^Mlf_E_W?>y=eE;eEJQumxpJE*^y5TbTMH`K0N>PjjlI>Nc5tdwp`4tmWg$iqqwEmIhT1Y1(wqxaE-j z8kyLecb{z=b1&n28M%#f#$`1QKQQ>mWji!%?<`pS+x%Nbe#=gJI4+4*)p?+I>CO@7 zIkX26n9qI4VL*CD|&Ma$O)L^~ZZvwvU%H ziW{y6&pxqYvw7^ugzJegezx)t^A~NJHRGBV^|q$X^Vcf#E{;03@08r6+?U34&Pc^S zJ2tXKUUkS%D?_I#O_E!1{ON>@pFX_ZGvm96UH2vrwoAOFX{MStbHu5=V#hZ;=FE6x zr0w!NER>Sz-Z=&S`=Poe@XTX+#1ePsPaQI2TcuAN2=DxVg`1?LSqZVgu;xm6^>;H(HM~|g|d}3`@TDfB1`sV><8J3;f&C4% z-udIXuKWHx*FE=rKhOJo-t7>vFQgTzjji=nOXb~4EVp~(8D+n{&nQbH?wAN4Vn>m( zrJ^^Hd`i6g&-)+(%bm385NSS^v2&O0@gWn*Q0f!+rC`An8RzI20JqdOjr7&V6A?Fo z9?%QHjKE_0v!CW>4BEzbRdm^8cu*i~+KQ$NA28ON3mz$YTMjHF_U-0NpcQK$dqaX5 ze0Gm7cr-)vd5!-g-7#eT+8{r(fxz8XMjDBaTrktHRR(wJSf89O^{~pg1S+Ytv&frc zDLf)w@9od#cnPXO81-YNQn5}Lc(B?%tD9`vaKQw*kC!I99Ay~d8EOKJtfbxighpW# z=~#^|+Ub|8%!0TyZ-l8NNj6v(+3C+Id+d$=^Z5W~FOX}VdKpPotlrwO^oeEw!ycSV zr3F#^CT57?Mqa$_QF?6ZVvL{4eFd8W!V6z3y~i^hm%z7!)-X7|A#k(+0oY!nnAU9u zfuwc~i$OlC*%7eIop6Kj-D;M90z5uCDc<*>HEc(+);UhaUfFSC-@9m9)}Q0F`#MRR zE}L=9rhTwBK@xL0Bk>0I$vEITvYwsuVlc+N zKano6(?P*Wsb1fVhTrn``+<|0)R7u-%wi@FbhT>XtKPGVGJh^mE;093&)u#e?M;1n z+Wj~@+`EIxb41@;#1x#88d0($eVV>Peg$qLAKYLA4%Cg87I?e!(xyUa-TmIM#fEPU z@4}+Yi(yh>5?reUhm2&gTMZNQ;_Y}C+^dbn7$kwKy0S{8M~Gj>IJ_Mi+V1F@8_A^O z*2{cSLI)YE&q^a$3ql$KjT5}MV)C7&KLz-2ppYgeqU+WE9Cdo_!t_P*^(Lyt#7A1R z3(xY;axQ8P8(pj}y4pccY^&H1B#UM-2Plq1tX$ zRb><#O!_w6eWO=ejcY{{Rog&I0K;-!2tOl<%l3#+1Pcv@s0|VBM__=ZW$wzX)?bzj zvMpk0kNbM{O%Za!zGP~@WA$rg^8Ne${77&@X-POt!F5TWsrtLoGXe zt=bbe_QJW+Ds#_m&DDJ?JO>p8_~BGuBqab~MXoBx4l0VP+g(TG*VlOIMg-IoaVB4a zr8Oz>q`egsXsB~7O?yl_GrssbNEgwk9OG(_&J;s-DbJnTV5;uD`8vx z{W@w1hPoR(48+<<$y_mSnD%qrb3f4 z(G37MH8`UdL+*V2suGi%L|D>k=gbMSCQhyGqr0mfz{+$As^bXWB2XdFxn43ABmd00 z?n3`Fy@s5P>O_L@I7A(<3cf;FN&U&WM9^CHYP^M*mw*m1TLcKM9jWSDOps44=^}{; zUKn%GxRNF$4+D^JE?Z%FFR}pPA3-NOXq^UEW z*<0a63ob8LKbftY10tU|x^FFO6pi$GC5r8I)$Lv&@$IyNtnW0d6gmR$#6KTY-I)$e zzk`{d_1vWzy0#oHzNvgEV0CuDccKHKur>G5eP-5xDQ|jcQM5hv{^mR`nL8QSAaK#t zR5X4f%%Yv3Yf#Q7zn4yfsic+Mle4Y+{v!IndnQ|yjXnm2cKxMi;;CEv98UoN2vPw6 zOymgvKFu19-fx%^VXDp};!M?B?3Ak#vuQMRfe3whL5vm?l}FEdu&K!=@(5 z@tVy+oo@B+)wFpjwYGd-IVGYj1OjI8y#CbbWONBQ#iP`!7uqRV+#WNWNAFR!joyer zKCFLi^|Tr5BvB|u(iFk2gSBklMg`)iv+wUbSburTky{TolA$-NM)jyYe=aYpxY6|m z*Qw&a@asE|rh~g4!?{Qek;|v;&hNf*STKwg8_zAhNP>PG_fBQk-%hLU7b>3@Y8REI z!%a+QXld#g;#GT%=dgI40z)fw(gP&*A1M=JLFJd`ZSNgaS&ffm)JZW zQ~yg;ufde&q)0)c1k||ulo48x!($b1EVX3K{TGt%H2H%Q16Bj@6`5D3#*9XnMJ@HN@{^!RTdnzj z1N|;wNJoE8R5pEjJCmbZFdm`&zt#dQQTth)1Mbm%ETbvG8{D`Sf8u z&o%6)iPyYU&dqsuwd z+UH%VN~?i%IyE=z(G$7H)O#UOov^j>p3{!wU>ZH15K1f^5zT> z3?|VlYG*2%2ISC=y-I5ZfYw~;`PKJPfkDcxTv;%)NkxbXF&*4!Jd%~(`8x3F1#^-s ziZ3)|arA?w(6Yx!CxCYi0v$e<6t~qj-RlJ{bdgR9?sk$-%1!-j%fjzj^se%6)!m`| zc`j1fblbBhs5P-7%b(S_7)`w5LRQ0*tOnyj+3-YRZX-~r+xuGJqB`^_C74=QFKYBc zmPEPdgYW(IlJS@20{^R37WQ%ugd=;m_Am|ZkW{Jm%$lP zrX3|CFZQ6*z9&MEqT`C_25&09=yN~&xr^e7QV!C#ZlI)y%g38=F4+|l!dTLh%Vnw!pEXfT zsTBGz?!w@NE;eP*i#W5G(q>#?XdJy@V_q;U<&J`h{q&$YVqj#ZkY{=mm<#l5dBR)F z?9O(#2gPz3im|^dEfN&;qUk+t(PltqR#@64$ulb$X6|Km!I$}MkA@jVCX96?{>?|-l=Za&+;xYHfwl{nLPqPrv|d23)b z7QZ_(utzG|15pIto}|{JE=i*ltAdVa!wsmWbunz$;!nzIO?5u2?bhPlrPSA)G8o!u-A@1l{e7W;}F68xTA$*sY^V?Td}k!dY4 zNXPv=`?Jwc$=v6b-v&8{Ti(q zGCR{oA#cSF5ZZX=%D)`TdyN+0yZ>0fqZ@m8X<_I!iBe8}r>&#pzdn7^`$nquDd! zw~2vyOZ`Ib> zLG3!{7&7Ww^~)#6#k19FLta~-89Uo@L*1BQC9_c}+p7op#7z2LeOANEUk2I_<#w-I zd&_)<#%O0&^HZr#uPUC0mtSt|(3MU*PdaF|<=zgmShkccHAwbY*wBtfueWC`sjF&u zyM7vFl579-<)k-DTBJsG@GW^4?jAbjC}hQKGPv-NHlHNhA{Tc09VmDa&`YrYvUKwLOR6^*=p`rf(+b4D(0KCryH z>%7CtVbPZ}reCU09KZORZ&UM;lS@Y)-!=4v(}&uf*$p{Mj@KVIZksYv z`P!s$V%fQebAQd|?Q)V(6d!U}e(2mimqv!Y-@#ogzdHVDX3*yGE1wMUIMos5nyh7T zR_VmJXNK9kbZ6%k)dlSP^#to`Li1kE)1Th^#V6-3Elr;p$Nm1rg53`0j&-LRx5iB0 zxuyHrciY!aJ#x^!sQJPnv-i=8M)|dt8%r{}wXQ_0%#V&rzF;F|62IsmLL$c?Snazdd=JsH`}-D+p>E0DVNy?EzH{o`Q1)lyL*+5 zhCR1^!{n7yhD8sJ{Oy-l=N_+Y$Z1~~V7RtuXkwJ&YDuQSjm+k82j-V`?Uekj)Ld(D z(1=+xUKP1DXiS-3JJs21#wmj(v-do2S-yJiXnlj_0nAo|$uHtGvx}a_o4`yK7>va+@zRA0?w%+A$*Ga?Q>SDO^RXuFuc<#ySVB~@l? z9=TLLbm2rU8GX%sq(tDxH+yxva%WRM-aXRUA^p7S^c<>O<5Rg$6RYQQmghW2#LnU#@c#sf10kkvq$>Xr2zw!x`qsx@Yz`W$oEK|KUY}heR%8|+unL$ z#KGEajUHWQ!CT$uoC-ZPKy#SSV9oa{Z>t=eF=7U{t+DV!@DCjV+1qOwz znCG>v;cXtRHImF`9j!t1&i9et zoH{icw}Hy<$e?kW3>mx*GX}pVgF=5sIlzAqnZ>PRhf=z$5^3Gp5)7}duJ(%*Zc7O} zJG8b0-X%ffy>DQ=O{ArEdLH0Q@IM}Ac(uDR_)U@Uo=6&pqtW>`gW}y)*g)mMs}Iw= zI~aTi8mA(Mf!_6z!Ru7x*TDmIYKioRH0}dg{>MT(ogd5St~aE2HSoEz{BEuUgI7Yy z%H^fJpmQr|d`~+6+wMk~jluoMg_S-qq_H_=+{g6%{jEGUkKNGBN};uOQSPdCbTZgf z?#BvB_xmuuF^|)n-P9FEOk_XZv4k?{7)6K)H)5uffjxe!<+xOo&SNG$WEm3n`!M8L3B^<;LCyT9CGAvxrWar0KAl44T|H64Z|QET1=-H#b1Rg(J2;WN zY=(CyNFh6q!lG!m&>tC&;~!x>GBo8Mp$A6V@Wx703b+b9ZSNnugABVl?B*x@j+DzB znt2D06G&&cSn#sdgTiR9UplGGzZS{U;&oB8UPUI_p1U^5f}Oqb1Wk@^zejq$oot>h zpTCp+eDl;?jP?P7L$e2|wmh=8`#`}ksN-iZnXs8q|LSzfVQKuiApjhmqYZU>)!sTMZYY5UE=6Q?PiJg6+HcU3v@=< zOUl^2I&)k1yDgn}mz7U;x3WDtuJl{gmmU%Nc78Fzd7hWbN1i^tWrqK(BZ2Jl8U8DV zFIS4(xhn1T%$W<;j!+pZ)1YZE!hS5wnRv!|p5bcS$Z?atQ+??YJ?{K>Hf(4ru4W!{+=yG%;#ZbC^MMP*<;h65K)6_@%972xLe)OSj|CaZ> zdPh=G(T@1rn=N+NqRV$%xOX?#=j@1&&oSPWl=>~OjnjxNzQ z?A9Ie8ex}X)z@6kdH3UD4Y=qQ)Ys;`tBh;*FWMeIA5DrbFzJ%b<&#}4ZEu=xQC3ZM zL6>pYy{(kl?}N;2ZEu;Lhr1tZndH#=oXA_Zi+1cHP{HN9EnRmvm*(u)6`%9M2BU(D z(d{<(q}yRRFO0)37XYfme04u{@#S`r8f!9ME333q*>7kit=X^ga$bC-H{Ro?*S7B1 z1$Zy3uek_#DH?FmEhxo!`R7#^Y@P%n>(WG*qc63Q$Sgy*C?A&&4CGqC1sE@mX;90$k8t1>$b0@^N*zTMm~V6n8dHvWHpI&;@374B3~o*~2zzZ>h3sn+v*( zyH2ZA=I%&h744{l^?s;Dm+!Xl?{4Pg?5KnFf)*C$qKnaOo_i82kh-oe{^^Tdw^A40 zS98wa9&N*I-Cn0bzj(T9=J;-vVCo|$)sPePD?aqNZ@o=w-W$T}ZtVs6o^U}IcwK}t z7vIGoPKW|A~{#!3G0q!S%3jYPV~V*=;$JzBQ2kV<3H-lK0cL9ZAQEc1*mz z`M{DM1Prx6NSSOGfNE%aYsq|glS1~gGw7}Yc{gbZsPRJW4tK;*pqx7ZI8&-D0W_#h+dK^r zG2I{t2C`*8R+YVSM z=Ydr%iGTVje>=>6rY0J65s`PMCJh*Uu2lI9aJRJ_F5=6>A~mw_zE+-hXY(uqG+d6V zQyfFwlQ!?LOjY%arWMo%B?$+o)_&n2aC3-MVIeNyYFs(pR?l}XbrfVnu{(* zw>#aFo(D4E?$f!z-PBxkL3eKvcOT9LH?7%tzHa_(+^nX_Ya ze9kR!E~$CwVsxABp7aX<-W>n*mJI;TLl<=S7IF9CEgJxwhc4*u&0heph_U$YXY+>T z+%gWc2B+l|i7wGL4XryigZF(iAPN~l3L zo>(<37EOF5JFDYzNO)_tAE;)8G7+2PRO&H&L5toQ3iH8C&)1J z#@;N=V;7!!ocHs7tK85opIkBj;pm$(FtH{MI5Ow56yeR@22dWU){Y<)#U0O%q<>cVZo?67nkoPHL@Z!EZijP(xKe0sy(q`(+)m`nO1G9 zt>ttAe-F8PU9U;dI|)zZ!xO;)FTA7_D?$SqN8P>dz!#zL#V||w!luwmY9UNTxr4sQ z)r*2J^x%tg0YzR?tI-#kvsY~iwYLmvfZ*e9+2%U_hIxXz(aTrX+e;cxNjz6woH4Rd zaaX(TpqV!P=<}ij~?bZHq z&x0X9{uC-^wftj9AR~76D&J74O5ca0#s*BaI>*w-02hY}6hnn5H>o(W%^n2^Dln$*i>XNN@KeQ@FrC8WUT`I_4 z>Db~qWB2rZ9uw;~7(1qwF4g=cCF-U5Xo|+}>4QCQZjsvF+&QoKT-qovVgL6`**9I0J9pIH6%rtktW zQ==xqNQXT-3lXHDp-PKWt3ST+@qjry?uiZD3UkVRpgwIrQ$AQ%?^Vf|32%K)%-N`< zJEkqMC|GlKYSc`4{QMrBbqLakP^I;$)hpln#KPlo_r*4&$CWJ-w!b}n(O7#MAhMCzoIiy%!3RVo0HR{6xj<8hC~ zHlxRPgGj4RUpy{e`UpfiS*H3p5^0M-q%d;MW3g};>9-fayY3jhST$}c0ClsFT!Mf; zu6edZRg;w(Ras_l2#kCo0AC7o z?#~vxhvrNJg4Uc~7Ak%fM!r#%@e75KEa$Xap=(A{RpZoPPP&EU4=|_Xa{)om0ztQ` zGUp(I?%=PsJa_S|_?G7Y>3f;#v+($Im$WhG)|}X`YBLuee`ayg8Xo`kdClq_s+#B1 zqH;h?i(GUfkm%==WDJai~LX>-HYjJ8*eQ-?Xr zEF>LZWPVP~GY3`8yJ=CCFsHYR&aX)H3%krdb(}H^kWJ1 z-uA(6RJn^zGt4Qc9jf#xt@?Sb4>KuoL0q2LYcyxKMM5>q87W?xm-X@|icC=?%*ji_ zdLOV?XJBc`q+v{-A@f1+2T8q;zMZ&WX};J@8+ehJWx^ch>B1;+=lrafZ**h^N5kVY z_NL8^UNhQXHBPr{%OG*fe18zglYCyV_PmsXMu*$(44IZ5C2_p?sALRR$#qB0#Dek1 zZK!s0Vw5HoY`Q)|KHX|!!GfK7X7gjbuHOqtu+iIgNAVcb!&-==>n)o3>g;hl7CgN`21;aT}Nx?hHrZZ*7Mfr6gd zI1q_WK*D!OB!0{-kcgZJNLZ-{VwSQz74XP*gJi)S2>+kS>CXT?%}_`i?xzP@mMj>5 z1hgzB)kuw3`a0Q(1Zu-y9SLE+FHV9E`F+&c2c`{V4ygzI;N^AmTqY0eLy=OtNR&^N zT*Qa<(WOW{OplqsB}vP^1mP-qL4qRJPeGjL`#HRwG*W73SXn^V9SH zFP;DO6VBO2RON)w@=E4l1mwQ*~6@-o`nXe0Q_)f2@)JL+y2*RDg zu!6?b0S=mS>CuvncH+8wm&r}Kwm?oVMM*Bb#*cYO_jaPnu!2$kHov^|lSFaEWO5vG z@Zx%Vmq7$xfFdyGdC?GC8#Jd>MLwEyLP6s*m{UGI8jW1BcbPnl+zNBbr`H@~9$Eo& zPAC|49L))_35vL)!L|_EVDS|v(esi8s3^Yk)1(mvS;^D&G{(i;+%i^oZ^oFIuSAb9 zLC}GeMmm6b2vQn5l+v(JVb|y76$!_fA@gD;PlEUSprJM+ z85=X10N*t&@3-MI{75GDB?!U9laObKeVZ-^Y2*3nkT#-F{}uZEOHuwI6aEgEGwFuT zV~6$Axv|;%{+7{KnEx3t{|0LQV?n*$;lEkwsIlRu-Mp+NtLT{e#AP0ZpiXpn8nyZLQaSL8<~3 z@I&R(FG3(lpA*v+EL8yoygn3o(~dDuKmp%yA7brq?W^*n3Z{bR1fYviv=qnDGFIA1 zABy#9e#{flKWNYmXoCJh-tdB{P;+`p#whJO2nqp zrTyo`orb=zZ-V|o-o%2bQ1E)riCK(#BI5Gt)QJV3tqI~Ct}jnOeW@jh@c!}=73+c= z{tJ+p-ZMcYk`<^79x9i95&9(Qs3jvPgC+F#>O+>~N@Phy8QdeKKLyh}vU--}n1Zaf zrFw2NAWxCegHWIF{HrAQSHkoP+WBtCm=*Byyyy1Q`w#?#DGKGx#OEs0`)E=$o~~fY z3TTn^r3aa{^;3_ao$&?jie@ZViS2b-9+9$-F#iUaPv?DR8GlOW|0UG?FM%nFoBs|A z`hq_a1@mv<=07I%#egH)P5mw2{SQq@UsPP2DvXQ0V7d~Dama(n9@^WfKajp22(MJ^HQ)@3ZUcNz91xntCu`+DgcB&FmXz*m#3CiiSc0qmFqfA!nm>B(a0n-TZjh;)!Dx4IgL(pF8MUbAPQ!0RY z5E?X-dpBslpx?g~|wS3-CrUF=$Rqq>?=6>BItwNd*YGFLVw({iL`S6AKJ;(HL#pIWe** zpvxbFn0O#^iRQN)9SqYOZ4v~b9<;l)?Le*X^bk%7=o~ak>9SmA>QOZ1I688iIGq4* z6y}2@;Z<^+r^C@0gx(iA51xYE3}*j1y>{3R(z1a$Cm?7r=L(jKHO%={@L`+3`OFk4 z?sO@yqNREi6w>vH-HeogQ z!3m3@kT`Waw2iU5|pAMf$_wHIiINL5KQ- zh!7n>M7n}KAU)RlK}bg+^PbL3?^pjRYU12|=n;4iA}G8Er82~R%NKPk8hdXOl7(hZ zsXR&xBhJl31`!13WQIca+cr#|lQtJtF2#)kw*8KP1>}HZk?pHaAjKfN?3t7Z=>KyA z0uuIHIk88891q|E32y~fuV9_|I_zYs36$(ZcA_2ETa(^UOeiQIZGREFpkV83k?15< zA1A}CeFheZ9MKoC3pZE$@~HmV*RfC}cCw*11N0lf913+%Td(@!OAb;rcJip)KPo4k z@RE67=N&~_|9_2V$IVSJ@IE{e)M~jR9Hb3(r--n0J8_;cs0z9175=$zZ)_MTB6_#E ziV93!i+a3*kex8Jm*e~`c%FiuA+(Fbbpj%gFQ4tlbf2l0cR^AMy6mn)?Ta~V;+H+9!5C$_)+sup^@Kud<*_3me{Md9b^E#>hOC35hx7JKE`yn zhB>9QU^4@ddZ5FQv2$QfDJ_>3EIruFn0SnN1X7Z)`^cHMud@Bd07^Dke#A=jJW-}^ zSvnTBEkJq-kbKyWkn?~uhF^(Z;FLgmdMrJN8U{U)sQ1ewz;`~MSTGj0GIq|1QGkTR zeuTUS9Pb1!8}?ZdLBvQcq_of}P7{=L5ib6V`u$5${t*-Y7MQ{# zXuWlgPRjMOjK0GB&wwe|W%~=MDL5(DW4Z0SZOIT(u)ZreNU_$(JNNgKM$T4BLltngdgm{W> z15$(WL0$xP_kpkJGeM}z=X5Gf~|EA7W4!S*WH z3vd*KA@5;1u|R1jqN-O9Af~G|ya!Pg-h(&_??J!G!AU$wG3#%JiB2ehNx*s#8DTy5 z1FRt9d^QnrlKKVk0%PybcR^SOV+Z?ywaa-}4lhtrKxX3gB^mcIc3nt}ReC4J|GQy| z;wC3|H~%iCd$$)M0(SqLT}n*>7!A2>u2dxML8rlQQovd=-!!C zJFhCa;PcvU!XU)yI2V~%4x9WJA*zqoWvzgyZZD_T3{kz-k9i!T`r=^)lTlRnm&{D` zV}_57(SWGlG+oaTMRjSx5ryO6;TKC5Oh%aks;hBSzX(ai=oPFLkW|=jg*oLtYL79G zLsVZppi$xhiN~1X^I|k0Q)&7^&k;=~pCl z3<#g%Y+9=4h_Vl9JO#I{$H(h_Z?qnEF#?$VbtHqAxELdS^@6ZUPlj`6+VpA%gcxqoJe>2 zkJ7>C_qOzh!Cz-BzZ-`{_)XOL{0a~GAENXSwSh+}1CY-@$@KEqYo0PDQ|d??+jZwA zoj7#&XQtO>z2*yJGS}m~XLX*SyJu0Uak=_u=JD0H6BFk>7^yo8_<0Zg`u}Kv)(QoDcZA$HxcgH~kgQ_! za|5}bW4yd7CMHW7Bfq4`>4<)p8%cjR_pmqj?p@ZCMEa8U{FWoF8*|%oBNMb}H?%bt z9L@5M$W`H$yU0w9?AW8Ka?wq?wsQByNczXqwJ#Pea_$_{&8!+Ln|t{nEB9S_AVZqd z>8a+fVt+}Vo}i`wqUDH0$&0lfJDnOII*#IYvqSHOguFOKEr~Fx>-g=k-7e+Kq|~Z`)a?RfAlC;{ri?mzbT1+x* zR?f{lXGozbz&8V3(KkN$n^Gh6&F1wKni_mF6@POQe{g zGu1r6X{dc`VW>kJ&SSM4*{?dHsJXkd+_|M}1$rp4W>w8{rrN=1ZGf;P!c;d#yRy#i zOyCHWdihW_os0OkmFYK^v}reZLC(&`(W|@wn3J*Gnw-~oDLVl$z^XCW&>cHs5gSBP z`zdzJQg){=JMF1~|4Q~LYV9Kf|8)y?dhT>;s)&8IwU|mVtmPPtzgv$)Tw^fvNqy_k z2A4BoBZ}+g>AA06Aa4*LZy=G|36UoX zke3LMzY-w-fkgg;0C^!Ge`@Ex-u*0RP5zA_!vm=yGQk6G=E?rTzj)z-sm+h@fWrmT zCqJSGYAd<3H=KCH_e0g#77Nx*MrUhUqk~D!u@8xnS6sNUBi6Q&$}nyt zm9eGmRCeeaYb*grMV%d_1mbp}>B~)r?IfnRzd9v?%WmD9z%ad+hZtZ{Y3h@&UHP;* z`a(4N;(Da%!2$teUI-Y|2*z%nNWHPYgZ8i0}IsqvB@ z-tQ)@@^)84ZJh-@-lxn9xrMv&gDbpvKe#)LZboV?F)5|`FuV?Y8xiQ!zL=)%X2Dh8 zkoyt7N`Gm1_1FCfjf$b7oV#o@>(0~V{vqw4*C=;lv(Sqd#-C&p zFYYqAI;D|>snbrv{HBA1DcMQD%ZW5hmN|AtDDDDgPkwI=`9 zAj9A63I@??^Gd9aydm7ls+xmMYC2-@KL-5PBEs~WArwNC`9mn+ocDet?eC|LB%Myd z3lN>c@e8o$xKGk)|67tyC*RgeysVw2G5+dXeedwe8sqQ3z0er`FwHGY@$g|9cS(4I z#)gj%!1xx1Y6MUJEy#`I`JHCGq!i^-L+Qf!e5qPcUP2}ZtYan*83EN)XDq_E1^nYU zz(@GU+1`YIRLaHvvHgmv=9X@7!R2)t8}c8*N?i(MV5POWi1LpFl&=y{zKX=%?e|ie;C(pn^@%Gc8?nN37 ziq%iiXqRT7;&*&x7>-we{h2g7xnSU2MA(C8bnj`o?7bbKZ-Qkb18QS7@p2>cGUsN~ zcvfp8vcsN@eMj{%7c9zBuqZ3<>Q6H}Y6O1r{o}=*T0hTw4#G)bpHZCi9=@>1KC^ly zeBov9ygu3*gmA}cz1&VD1Pf0j;};;~Itxm?k1d{kN&Mj5g4yj!kvR%Q_6SJ^G4;Jb zWOd!$_c-O%vAT`j5Ui_Wbw6H6%1m0=4*oR1mGq}gouofyb$0sJq-k~|wOSaSg2)Qr zKxAd2$m+$0pgV{QXtq$|zwt$A?ktJ-^Ygx2STajy{1&FZ>dYUQctwG$_cKA={PpYB zDb6TBLSCn+S3n3ER5J7;Qb`#%&B-MCxDfkN4#NH*68Jl*PQc%xm(kF!4uo7OT!8#8 z3n9Nk0o~0g6zJ}R0n(jYCmO0r46O$i?MKtzDWgtS7|+4e-qD~NY&h-Xu~ny{wuE|U z`G!qKk9RkBx0E_7#D!jpvf5;$&tOd3jq-p0#1C?o?Pd zWL+uotBsA+l;MTx>dIH|``{Ng7DpNflb~H4&YJp*xjsi3#x=@i#Z?F_08y)o{ZR)d zf!LB=5xaU!z5j66NGff-#`v)WJn$2{;$+m}h1?D0rX;#b`>U6ttzIEvB+5A`suRKh z8+l=*wi~Znc+=4v);FAe-w)PjS9R$}QHWI)331x>5-0HS5=I7mtTz-c51Aw>dw88t z$PS9L`eWc^r^dg++UqP|yev~7WBReMqoW8pfG;9NoYe_pScYV|upP;goHt#49XYQZ zUIw9PSVjziEVZr4FkZkGNDpt4>Ic&l$QJ@2rVvg`SLtTXLE49#XAv^uCP@jniQ#_v zCej%K3py*yaWn~@5p8uA^U}%qd(0CHPsEeiaWc|HUaB)k)RT%w*~x1BZ;_Clu6jtY zq^Tm(cqX|rFb{#u9ZY7DT0=Ln){tYEDWGbPz`p*bXwfEmhba~15M%4RswNT9~nG6M7TU~DU<5`N4Z9>If8USSQvO-fx7PWP!`FXbV{YE zafHz%WJ2;LkT;Y9guHPnU~I(aD{6*?mnBrCXB~YjBiUBUU-}_Le5Jzm!7Ia#%nl5w zQZmvQe)5W8{FDXt&rJqx(DI&g_uIoWnCptHCQX(pnzzrg!qmb@fA>N0iptnYvx+p< z#qIo%o*ut2`oybmWYRMY7VM65EH}z~-yK@? zqqqgLO}+R=be7XHt!@1E8sjyJq|Dzmr@J*QD4qj%b|>T@3gczaNZk~-%af#wG*k&dsZjzzYvUX*kbrc*0#He@ z!NXCmze%U&H`-s_y3DKUkjJBhYhgzx*9WNVi7xXnSU^r_?`rIXC){nG7=K8NeO$bL zVpmXl9DXw`rEz>w%2ou};}P%TIz`nu`Q%^y9hz4!P>yr7Fv{Csb~`G|Nk;(atPx`& zDIvdp68Zw5GSdf#IFCjlNsyA%O#zva6PDFqdWR=`m271)O1vKH(A<*LVOeD`DO}La zrFU4i%pTct^+{#Z8?r#NC)Z7vT;!oeT&m>9YC_B@|04WMltL&xS zRV+GAo7CJAq-QkojYdmS%w_sdEbvnPl-kY1Y)4J551d@zAa9*8ij9@rajmJAky;dP zfA!%gHXE;kWN5N_@g(&k8I7V6{bv^VF|2-fgFA3kT3bVQZX=6Mh50UfCI$|3Z)wpgSEDm1RLBTiF#cyG3Zgfn3$K@55y<4 za@+0}vjeA8LyBwFR4(t#wsl(NO?Jc_lB}-kre4mF%#=?$vr~`Fg6Xri+2S zS`$IthK=N4KuBw@!DE?iA;ohpWi7mfjJr8=iZS6CZcPd)f_Inb=UbSU1+F2MZNBlr zY0kUT9L})wc6Odls|f06+io(ZS{PGhbzJQ20XVjjKLNM9BDrKe^}z|wyAvGFlXG^q zo=*D2%qds5>U%lqgOtIdrwXaL(#vTjaZgToZy5^{@mqR8?IJ<#_B10vd3jYoUjRzGNGMII_{PPo)QjNaZj(1@ zB^BT|Cm2(w7!$s9rNC2&5SOFLs5SK<<_3A2gzJqDXa2#u!ZkM7;aRD&T1dB}vB2$- z!1oo&xPi)YE!LC;E++VqVLWPaJ^V|9JYE_pL@+~48tif02;Z9$e@Kq~P>%3IhlTfM zvLDW5v!&*jyli`S8pzdcnPO&46~%)vQ9NicAlQ|q?eYG6sTD!5vX@~!LcDXE6k>8F zDa0&oXEe5aJwe4_TTEp_h$J)qdco34v``ShB48KHD=BJwcapFr@VY_~UT!3Kh&`Fm z?qDowOAyo$kBNALRS;bU?)@a^-AUpeHd}m8ge8fTph#*UuPeeEKxq3A2iBe#bRjJy z8OVU5a&qPgP7gJ}b&$9O)R>r&;Gjr)2zVK`1bmNRmV-zDD6;;(&Goe}h-D%O3#kG& z8Kmtk0&SykCc<$+%*E^4c~=Eo493cEZHDv(%K)b|0>>3A%5i}TzE<2QgF)`FA7LS! zAyczPPRD1iYUYm>=X($#yi!Dtf5(3C8 zB-Yd~4n?W^Yg4%5oT>G^aN6X#f@$q*7ZhuMh-)ripZCh%dVLN3U7(8U)l9{>=1d=s zwsKrEq^+-9t&JPW0^nt^t*msB8zkI!8@CuS(on_?amynNC7+rivRN0%_xoqFwSCiT zoXzI;&1MnUSw(KB(nwxJRvO9SB_OV-EEgTEZ7Ide9}*d&y=8nGZ#wuSO)2C zII3Shx>aO;y)=n@I~>ZIjD)@g48a7b@OsxTf49c3m!O&t2`$A^yne9^8J>Dk6D*zt z1Qsu#L70FBKrKH`?rxpEBC1&4~~3VS=$Kk zX$0^Rh^N?j=Jy8fAm~?sOC((y7z5$bP~+z_W5A6caG6A&-MjJA*HNLQ<1-&gl>5kQ zJ6sDS%ynxSB$(LBA#Q~WTTZxL0VHkNXM^k;R}}3io7DBH^&@iRu|%~gDv*HB|0-)o zc!&udAd27#x1z=m83OHH*AspQmvaI?BMdjafcNc{;Rx2#E4yysI&yOTP!w)P+sDab zPeZStmU)Qt{ciNHDAt-x#ka*PUdAp0?7owcFW!9>u4FgDb>!Ikp*Z54GleSz_xs7M z=j$g(7fGNw=v2wGRZ*vG@XWW+2reLN@H zdk-|?AQf@lL$uAz!|Erf7fE0zcq@K1=`HO{rb7Se9*)@R#rJx(fVgiUw3kI=)Hw89 zN5EzkNv!K1$RFQ`^4`-wke}G9!-fAJsJ?-GDnx*LA_BRuh(L}c+uwx~=pnrJYF84X z7Pc!FC&r)Hs>^)?bn2yjcTg4~y~@!lak4#jB*5O^jtG(VwIi&kes=T~h#)AuGNSZt zphCxKDny@q5YBoho;!F`^iWYBHYsT z-qSb5y9=}(&c@p5@tTlkey@yV2x(?tQ|hm9Y)S-W`A-sTOI&dUt|HmYh$6I9K|pkHTn|o?5RhdbCy5^aERy%L99PsYC)~s$GT}rm%g>Cl zQ3bLoQZ=M|jxIAt$rv%Aj3B4R4R}0Zx?sX|)Rw{Qt7^0oa_`# z0b{47sJXSv4L#gK}4cFnn)vYu7XL9wnB)!)SST;3ALD45OzP(V;{3d}Tkz?Rk6vTw6 z*uoR$+k3T77OYS(F!_43H#uXd!JkX4<+N6u;0CH_qCN6*2iA0f)*!P(zz%gLJ zI5{Xc6t?JY!j9%%qov z5(xki@i_wbgs(4m9oKv^@^g&8UE;Mu?l@N}V04`wnmB{jSgbP?KT<8Qt ziYCYpRZ9DX`uE^G1wy5mV6B1pn$xefRy0p}RA_jDBp)GaB$FHA-p-2&gKrcXJRuQe z@JJxA*9Zo`kMp#VF!&Uq!3$u*(n*-$V~Gio!Q%<@8xOQEK8$4x-gKR!1K~{(CCC+_ z(2G~J+Y_AHI!anNT2RcpeZ+#K$tkNEix36?*^%Lp815|)93bI zw3{LjT9`m+oFc*nL>UQQltsz7aDpYrDq2W5jO7LF&)ZJS*O|SoW;V7iyb>onlU8fLAniSSe1+X6r zhHya_2=*%#&jDI3LZVppuudonfo>pwB18cZj2wtUDjs+P`CW2G6jJewD5NTb^CIm@ z6WbH8k5EF(K3gOb&_cImd;Nc?$Z`LYurRbjQa32FVBO%5N+>bK1Pd8Cg5*qRj^^(# z9Ge}t^y4LTp)BSJra7;+ACBPF3^S% z4i|e7s8=9b%twI|P<@M_Aa5uPvi2wdy@Nakoe(0Ub{XRB?}2m-O)gZ!Zj<3^-pCTX z2C*3j-dFo7jV;ONks)E}-%rLa0G`8PfOG+v zL8_G-O1GO}NMDH4bTZoki|ZyCQmJZ>)I>BDOY2I6fL0085b)!lsRv$ERVVWp5v;;= z3Yk^MLJq8!fK~`jj!5aC_3#Uj7FS?`j1F24n+)lwY(VxwWTg8lff)Na4_k-=<1u0^ zw86Bw;5V_*kiH533_^o^)CuxY6w_LSF^$a%gv{SD6l1{65KlJC?z1-`62Rjq^#u~J ziN}EiTHJRiNd^)$5M&1ucyJy09W7N_O70EJZAWl#y2A1)IMUjOYt-^C|Y-PeddK z0Y!N`L4y|wh}>)d2Iz3#;r?##9XcP*!@liZz(Y=mj0R7Lk1~=f1fwBTh&Hf8 z4nw{2>uayV6<5R1+LjQn*FYNs=9^97ioK`n<@Cd1>@X}Q7%SXLuYk5+4pxzRaSowN zIC$WB)`*Vxf1kysYm(ceFzw`e4cvr(Z3a7i;Z~ zV~|@O73BnFVdq>hZ5gBn#I$JNza5kU`~FppFA)^nP_$2s@)j%t(pRiN*fa^QpC(=8 z*q8O-3D?FkE}-odXcP205lrv9Q-#br+FQhyI)T3DL@<)y*m@1T3DbMq-*b}@z3)aa zbWTX@IQo#501=W9v||bei+!9K?jYkydlZW|-awy(m+G~JL5NPcg@N1i{gwk81{Kh1 z&iQP^Kp-I$Bk`GOa>D?ftUxicKg#}H?%%_Bx1to*PwbvHE+}disJ%yU;P4M|a{8b3 zsGl~g$Z=i&Eh2&3dd_+f+m!@C*9rRWxarD3hS<||1!)M_2^mAL)74+2Tp`93b4+IB zveWg64Feb0A43Ii?+pV?w!d1GI3@aX>PB(=Gg9JxR_=Rnx@Fff<#5~0N{1`pK>xNq z!GYdBTbKJ@#6D|3C4!?O{0~mad!4Evyn*mk1>R@H6ZYC^!@d-&u>a-|0*>N1>5K5@ z5OQ0{XTt+H(Xsl=%^UEL{-Xck1kAmDzMbS=U*Apu?;Yj{Lqxe@?}I3PT{fKN8^!i~ zg^Y+uc6ZG=xWlyoCIX1m2?gJ9J&?V2|87){HiB zUZ$S|LOF4NH;F28L6GTtI_mFs<$tVe#~`79w)Yfc3;cWk^D;zq?0e7*$6UzK*ZsaR ze64dQ4x$i2yzfC26cl?Mh7;)^8&_!ixG%iTJNEWAY3|BMQJ)gHWj)D@H z9)|>n79t>@ehVHFm1x*Ql1FHeuKORMA*B2lqwMAEzl5>uq8R%y0tvf55Pk#_?iYSA zL;98sy4<%S!q4x?trsFlrvywEhM(T-gxZ4mnH1znTHt*ih;W;j1tKt3H5Q-;h@I^M zU?IVx{@xvF@(YNt4**T~PVfk~*^idkZDK9FaKV`aoc>}Lj2dRW(qAMXT#@%avxVLIAG;;sp1`LI ztp=r=L|8#Ps)P!OBc-IP>HFhCMA8&}`~Y^+hPc|1=v&5$G6u-*1X1P>89=1Jc*35e z*hKpKxA@4iYuHTiF*mDa+=`nBN|H{dojD}2B94vE{5y^|4=|C{kj2r^w@eetn}BWa3!;gO2{s1$n2snJJ>66uyUTQoa%Z*F$bgwo~KV6PP> zIOkc4lFw}H{>dB;_OZ~}-%t@}4ApRMB#bDSvedr*8*83`-jA{(@_Hox&ukJ4qn}M? zqcq2Cay*R1O zjy?r`TY{pFo}dH0X+1412B~E^x8^9J7DrHv9=9d{1(UF&@?i)9e*WZ_IZ?(Jszn= zsb0;DP>a5u$td}HHGR}ugI+BDO=8(gbbcDMBpG5dPPLQ&1WV=s96bV#)K|bk>ceR8 zuN}s-LzRd$BtfV?3>P;LEigdKa#LDIcBD6#T}$D9Y7M1zOVD^VRBx^!y_=^-=ax}< zO;j3p+jkt=0&jjJmB&h<@H(sVTJ(AJq5Q_jd65)eEyJ5rm`Lw#O{DYL3jE`5f+*hI z-DMKAj&@oFzq=ui&#t9+wRAc194pi)w5}FM{>OG2uca%GLF;V1!vB%q%5OjHOXFUl z@Y^J4G-dwbtR{8|f9G>PkKG*3Kd$6)3_l*`w^p_DrDFLV`~gO51`QrDV8DQ31B}*Qu*itj^Ohe!V8E@H0|tzP zyZd*mx!7!Vw%%^C*Lj!2P8Zev_Pf1G^PcT|y@K*%@M@Nzdhyg+_y>1cimevsWe_UTZ7*EsW1q1lhmAf zfL&AFPU-3{3}PJUq=FP%OBh|6~hbEdD2r2=Cds-u&14vUhpa7bPkWu#zHq%tjds=OK;DR^z=j)ZWi~ ze^DZW&q$;uMRMCEns?H>lW5*uiL|aHP(})k{eaqC&3M$3$8UP9QAXk4qwqdaygyMW zymyTatm9q64_0ro zWKx^OnmiA7_4+t1wfSIIzdxg!7N<79$@1+YKg?suH0QNvh8_1T^lAoNdl?z8Q#C5u z9rn>RW<*iX9rvvAdZKo)d(3~ypCjF;pQ!yW_~YMg{6wwKpKadm?V;I?l?x`fH#KK~ zs<>VyKqq?h`HJS_oi*o?reMtZ^&QjI8ndE@iA1~UeH=#k+ z4}uav*Tlfmj~7Q#{`vENTn275_sS;AB&TLx7LcTZ;g<6#v#TrNHMjCCRlt=iuMwdl zb|AKG?jh4XA(_O4tdkb94hD)*w*2$w|GEr3+MQA>`Z%xSp6%_HNnM%W(=C#m9Pc_l zS2Ij%$@-qYBT%|vHn5OB=4e+7Z1rU z=#G1<|Ie-ewUTJoZc6baqaQ&a?6M$dc^^tfx0+pZP-G*#)fn%+;K>lJW(Zx+(c4qf?|J?fDDha0L{nM*#_jtGD zomcmYcK*rlKOo1{z4h4E+Fk0rIgf6%&d=b7dgU~=Kf2*Uu9`S?8fUs{~jr%orfV$X?+5g=7-ztf^3i{o$%>L=qGL$~?G#^j- zG=DPx!nVwoU%W6K?Y;8%RNLKO6^(k(H8GfPS0o`MAiHlEcmnM^dJSz zoubf2DxnY` zy?IfQ6!;(W<#hTIA74v&wE0GGqjpl5_+wUglp2MZEy4NZOMJ|f@M!j}?22mFX5x=L zP8406nJB?&@FhM*OL#DSr*WbVYcugj?anAeZRQyXPPH%b(O<&jt*=!_l#DhLfAnsT zVrVhlBsdkm#K&C{9;Ln!ZBbXWnD}EBJIYauX)eKe=}UYxknkw`Q)Z-;g{89T;RL~NpyaeZoFZy_(ofbnVj<1>cI@OI|dl#xF zFEv+W>hwG!|K)kL&4(m}ukDEnttM0E5%Rv)Cc(#alW3|UYmL8me7@Rv&ShP?>Hc<4 zJcpZjrfGDjBFos{>T3R)@s(U@_=oe0ZsZ1L(g?4O(Rqrj&Hiq5^v|?k@_om9+|ZTS z$hj)AE&Bk^a1- ze3~>TPnW-$oYp`*b62#63MV8QuhhoFoV zg)bX-mDrS~YkinxU~X5r<-tqV_i1pKRd_aQ#sb>Pgo4`(xbtHZpA_0~c2##5p4HY` zKy$a{eJtv(i0@1?X*Ij@K4@JIYv`cEEtKy@%n!-=o%R<7NZL zGW7{r&1RD6DW5`(72-^OJ5k|aUpn1sF>B?T+rJ$eBX)Y-yR!UgLq|?{IVxl1EBnJ+ z%@0byy4K{J`KJm+jE7y|ZBPZ}V>%`7Jx?;kYDLRp)`;r8`HQ z>%4}@o;sa0G4zO+TdYa#C7b3b?Jl(|w;m5(^xH4n4yp#pj(U3YmgEEDdx0l5gmE{k zM>T35k5^1zG4(mm*>+va=t;9TbX@c?m%aTm(LV3a{JAPaZ0L+;c7sd&?7ywrkQHq%n_&diXGqZm^0&% zk+#e8uuw{-d*>AR?}zG^z%!5O5lh^iKXu5AZIwQ8AiVSc6>^nfQEgqAm~jYcPz*wZ zOLxi$5`uII3P{5c5;F`Pml%*9N{~=MNy$sh(5<9`Al*n^KuReGVf+TUigBOs?muUK z?Dt*k+3%XQ*4}47=OC2-3uZ%jXMcOs^u|#wg4wN=>4rb{Gt^X%IWgLIx2NKU>2;r7 z+$r(Vr@`PEYR~NXP!U$@DYjd-F`=^=%D@ZZ!a5=Nxojllc=zS@^t9xr(=4n3?#kCf zC;%wZs~?vZw7aH{WYlOyuRuZO#5FIjy@#9ct+;1u?AuXe=nmR$f;P;3ZFOhv=`Uhg zLnd<-pEU#|s7*miw?^5iv^l&wD2N0N0JzEZ>@&>t-$X8)x`J2rhDjzEbl4JE5W!f!J zuM)?|O-fR%&XOXsRulbY!X+)sX7c>ZG#)MV+@!Y;-hv}F#^@h%%mBI@u4nh(1B0{r z#`(dY%IEgkw^8^p90-KI9?BTC)VwT&@?&BC8-}e(qW|ytA>jlk2=#;ND3*o zEW1Y=Q-$ESa??x@kEijh2l}J#PF|eDV|2-ZWbLU4FFpW0_ zlVFgt0=n$GmL%9Wf27R`k$M)nS10v~t5!|Q=}7KCl#PX{%4@rq(A$MYd83JL!)YXG zy>^n0Qq5ZTh}cc-2S+aE17j7EsrU_|)RY?aH+>dYMgLqOSfd)KU$Sq&VCUXH>3C;2$F`?zdV@RKw6^-5yxlCFkv7v7%5z=BwAEcHd!twg>xn&L4w%dbo;~l>SmX%e} zym3rGD)F(i6==Zddtc zhK*9xUlp;SDGO~0x|8b7m{{s4@-Z-A2MRGT;M=YbIM<}n%}rV%(QF`#+D%X*UU^!2 zm0?wJTu-{bLbHc-x2tA{a|UB9K_lKURzV5^25QH*GDMQn!EBA4Wu^iHDijK+*5tJ$ z!|lS@Obgk?9?BO_<>-`eEQ9XH94Kko#&J;wuNAzWA6OW=lw&M@KCvpdW=N=)QE?%* z)LduTURi*Lc43`8MkT_?P-#Lx_^SUF{^f^;oAoh0L+IYhoXVXk`3c?OH_)#8b#=KY z?RS1Jyk2Qk)+0M$yRu!NH9XyFH848`hSBN_S2Q&dd{+g`J!}C7R93m&pfUflURG$F zNPOPUduVQ^DB?@L${QO04obhj2bU*8QY+DsI+8|M=ja&5K;Q(7_;IO&O1r@8ba#bS zY?#l$VM-S&$tsXjjOg5YoM7g(bJ+r^cCX)VD$|8MAt_}J5+@frr}jRvT*Qq215=pT zcBEZP#?*DBP;%}Kh}8uFD0+LeY<{o9}7_W&6t{F z(k|MXDFbv>Z)dAaiR7oC?t;`ThHk_GpVEFSZZUvdNY1BUnio^!ir$L zN)Sl(;YH&XPd=)gjB7`Bj24`x@$RGY3Y5#^kLvgqZdDRqlQ}d>4 z!%sC@igxPLX1J%p@-edX>IAjGk4|V#b1}^nV}5TARX`yRfWC2}ZfG@CA`9Jz;o-bC zWvB2U>$<|(OHX-|DPx=hn(myRbbK%UnYRp??IqNsJ<@q^+Oqt$=`)mbhJu0%0!)+%kSnbK_k&@w>g|2aBuXZG<*s(QY1h z-kZ!p&dqWdC{VOI^|sT-e2ytv09{CLklwa&1pVdwW!6b5%$R(5Jha`NTarF~j>)5N zKXTWY(c8sebl-Y}=i|Bl`|Ao76GPr<{D*x_N7pc{haDhu&o-HI2Y_eFvr*Z@`LG;M z`0}F15#iYF^+m!9cL)7Iw{d^|i(LOeW5 zT!eq0W)6cLH%w_dvQ85Ml=b^`1e=13*+e8k7FrUVa3xAY_qW?2h6Xn|;+e$}QxrSr z8}>$3`{nyLvzLYCx=LBZrFO-@V0vuSFDEA7Xx)aAsNZsoWU^~%} zxaLP@PudWUg5|;(MIOX9y^`hY_#h;(F#IrT`}utbW(}Q*T#ZFJ!i4V9rIG?vt4ki^ zCDhB9?ZbrmkiJLyjF^_#^~*NAM}OI^=qB+`7gtJSls`=SWYK9IWY-UKRWEaO^NEol zXXkU36jgO&WC!jnA!1a^bj@JtQ4ruCnX~-C)i;-|EAbdIX?c4LbrV(OYd##F(}|? z27Wrvk=joXOB@n49P(_1LD`1W6KWSN20aVNiYA_P9ard;kSsr( zUDtPOV;)a0zZjO@Ah(-C->NZDkaK21w)b+$QB4)~ zOL@_qgCv!@sY>AhqC<^%_aK|4KRRXw&PHy; z`GeERYB42P$R6p>YDhoaRd>dz;ek_w;-qYNK;iZlP^kT}7RdM>4FW;Rj!kKW0q`0h z^K!_8m(PjMzrb%u+Tan{;dV@lVc+7d_ujF%PHzgDx0I+W{Ud}lNyBCw)8n7Z5M8Ab zFDk(w)oc4UniIcAoo|OFE2iS}Fddt;K$@_fh?OfSJ^I%97f9#A8bNLZX57a00zy5j zbDNE0X`&s`{;*Y|jiA)=PvZI5_XcAaTWBV17YF_DvzC4LB9^8;;=wYr-!CB`EQn*kvP+c|N3~ zKfjUzN-F2=`-of7<>Tyd?zKjS!mM&M{o;Sh)8 zJo~fJj~UA2E4Ue|xS$~Y2Ko9d`HtZ`MxFwHH-^j7|BPc}%{VIDUikk3jdYf5#sG(EAPhmE!BJ{&WHU{SwwGk!Ai@4}QCnb;|Jjn*Y3n)s0^n zzMVh(tnsfW5T}M`euSN#N1WRI_lEP7K(Ot^^Y88FDfGWwUhDXwuAjnAEdJU6oLZ#m z`~mh)JMb&|*Sd3x9`E`A{jCc93jZ}xp2BTkeGipyX;VuT`1QX=iEC8aaS?f@=Xm=6 E0MrBy0{{R3 diff --git a/app/public/exports/warehouse/warehouse-rack-spaces-WH-20260428173540.xlsx b/app/public/exports/warehouse/warehouse-rack-spaces-WH-20260428173540.xlsx deleted file mode 100644 index 9b6ac9bc9fb62a719b2f46d2f42a36a0f68f921b..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 53474 zcmeEv30#e7`#(drP+7{JCNx@&rGz?4WJ{?CZDWX(N}E*bj20qfnF?t|icyGGbp~Ti zn@Y4DT68LvbWY2ubI$*|@8>zE#hGD#|Cx9B{pS75+jHhQ_j5nr`?|i@df(@L4b}}A zI%?3MK_dpatiNb>y6o4HTL%vs^l|8*LF3`B=?VvX7b|-gOJnzaR?gu+Q zSwLB{#_GfvgZIm}B^WC&6z@`1ynMuIr0CBb58wGJhM%zBF~wADlI0e$K7Z8N z$$p)~#$2y?_4I^jwn|;d8>_S9=bCS-9~Z1(GA3nb%@CiMDc`HkX?*p|V7uX*o(=17 zo32tD>%?q%Ceh_p&Gqo|%Z(kr+HvFu&si7}l#bMD3a$xB&#{bU-lFKLW>!*00s<5C6xhM}hWDZf-rH6S%H z2x|g_FZj_3+)gZw3t#6^v0vBX69!zv1D$(aT#7uB_?4 zV841q^p%X6mn-Hh)ckdp{nWcBF8$`)+;a5P^3f;u3_t1kp>B6}W6rV@4JQoSr;S#; zK4pSPcJ7hfU$eP;9L3~ChaHg}K7Zfk(P8g*an{SOjenLIv~}X@r^7r>cSgA;Yv`R* zI62|De)b;ixp_tP0sDVF$-I`(;=+FR(|f=89gZF-@jb6*WT2j{&ds!n3=n` z^*sM>=lbbK54jh$Ts&;@K3d)&zs`JfNk)&x)ri&k(NW14ttE`&H&kVBqq$BiGap%( zcYK|83NLNi1%Dq|x2+?0^vr)LrQ4`>x+gbM#--gXXxF`Y?*LyVOjTX@!v{KHHHR_ znltNlkz1qMw1sukoxEn9)>}4r-;36jYv+&E)ms_BXw#eeGEP0a=viEjh1+)~R$a3S z%ZD_G>fcHl^)h$!%nNg?sP|TswGXrORX@(?TI)9};_wTVDd9_Yis+i}ls;8bZL;pM zbLAsvcI2|L*G)%@1#W)pqTQW4m-6x6(XLL(7u9FxS;{m$lle5cW+8iJ&Xf4b?yc1g z(!Ve0v4nt-Xq>IBtXu}tbj{s;lCLih8l=!YY|y07#^Oi5NAmo+!aVQ86W7>|wu7S% z)$M5V=r#%7?mq8y=;=Y~BYcLczh8Yv>G-TsvpDTdg&&&Ezq?l45xh-Ki*Y?LC}hfp_)h@^IKT6iDps69DqygVMKgSW@4 z?YcCT-JVC|wFl98T^aO)Z7p<8XAYHH#;bMUvbv?YWkEbq_8VVpQ(?M*6!%YHF9~L7o`z;}N=7hZ~*O90~7||WI?Iyt zv4Ya`K8$C`Ww&HEcZXT>n&|f^+>RFNd0w3ujm>f6eQcueTCegNyQv&{R`){+w@^Qk zXEX&sbW^$YAo(^o-V-<8rwVDydNumNR$da_oA;!H_kokhN~H2ys2vqSG*8ab_ArOX zon5*;&D|7kCzr=<(5H5G@yabbyt^Ghb>3~)VTmnN_SF&|y|Jl<+w~+ei&x0&W>F2e z)o)6MH&JFVd0kP}zOB+?k9h|SI`6khi$(Cde(>`6*qC_r9#5k?!vVzZzJs?fPT(m9_>5^2wZT6oV&IxKmaUOce}G>Rqn+Q|}LYfp0>$aXG|Q=!n)$&Tb^ z)4jVu3fXxSCPlNA_E>)c?(u>djHrHq~F74wLIl@rd(lD zO*^^lKpNfIjGL_*6h?jX%28?I^+>J;x7#x7b!4K=`Rh~6SlOFTQe|j%`y?0IO6S?| zc)M9IwocDwTPf60wU=HL$zeZ9Di69A*)rvP#;|fUnrGTpHrP!oskJr1(Xr%gTH~P% z?>Em|sU_6zU(NGBbR8&hb}V^OzUWl;;!MVf-4V9o~yj8YN z)~vj%++2D-Llw=M%QNwQXr8~9de7Ffd{frWvE5yTpXN(tx2m+JBt)caykpYi67DI> zwd^)DESZ>|t8~W8!i2FTp#7M1qJmV(l@Q(N`gcES(5{Hy5IeS6vqh|96<2q`BCSz& z;!?J+&)(7gZd=#A73EXiEo_cWDE(IXl}CiGtzS%Vp6BKA(Pz$Vo8>>}XdtV6mj9}e zD-|MluSt6|d-kIBqm;%=HLB~4vKtR`CZ2U#pug58a>A7FlwUbVPq^^igc}EE%&pyZ z<>#XHbMF|L{ZeNz_l_}o(WdgLtjtqW6#QQu3uIkX@NXXllS&18$|hWoe`L7lR_c~K zbTPQYcE6RX)Mx*Xd~(UroO@dva(2bX=NRruN`0M+E@eUOQb&28fgaQ9;!gB;qB6M6ei(XKrND!6>Nt^3~A(wtp;;&WbFV^nZ4 zxYO>QbSEt5rD52W0zh?yr|PFFy3#gMZC%D2MWqf))>~>xTlVX`oR=SIP4{`}b#1%$ z0NyLA>n;IaiW*$B3raCw-Ua1FTc?1?y4BI;*egvWGV{=FiYFuk136}JK{HFO%jhx+ z3AvznVh-HB2p4o$j<{Q@ctREKmcykN#oet_>|oY3bb(nNLiQ(Z^{`2DDOFT%cSe^9 zH>j10oLx!GqFwc{-Vb%?^4&Jxy{+t=UG=bD(8A(ebTPQYbx&djT5hP1fA(_E?bO8& zRGjj6Mq6{*cGj!WE}iL~J+VhA*z&QXa>z;ARUca1x86pz@Actzw_QNKC!Ns+UKgRr z!FMr;lfpnu`w|EcI#8i-m!soFbU_$))vJYBT~^JG%BiYatOghDg2#0^^Oe2f?wstX zXK+^zF6izv;;v+N)T65Ev@OGwB#)_Ts)RVUT~(A_v~`%Cq;%f1`PR1$?zFn!J|0G~ znjD`q-#V%DfPIKon19TPyf7;>j)z@yhi$9WUh~nk?SZr(18F-Hyq~r2N;+P&Yx13~ z2bc9Cuvg7qZ3j<2dg7ck8su$vuu`#F*uY+>)#?ZZfYJ|fY%NpNx4E_K&X$AAq_S58 z`p0NQN@Y6(RDGM<%ND|$Q))|1H zsq5a>h_IYbAgvW)j~=<(ha3UMcmg@%p;JWO3Yf>%GY=ZWuc6loWX4&i_|?sP{ot83fo4lAi$qZD!ksM}_yC2gnc5lDx-&*lSnQ*+S;-MvlReKa53SZXf1pu4wTfZoriQDZ0bqIab%eLyKb&fBtp z>zq?1y*H~DaHBB5C20sZAMj?IBt-%+Tqf9gRVp^_O8TW}*H!{BT)r!1-`n~sXV=#F zoZH}BQuENo;10_@=@$UJHU8OcYXF>wF6i!U;_jo{)&MvUUC`ZIzW`t%WAWY3<_*ia zZ5U<+PRlV8U81cU+jeaQ`>9t<_C`>^XqQg z^+t*Ych6cCf_5X(1>N0A+zqrU{L%5&L3O$8SWtR<-Lu;c+;dh}RkLHk4|X}74AHyf zAJdd~$%@{ip1t8lh~D)_k3Q92R0`WAy0R>CcXrl!rKO8ZRdXbzvO}Fy_LeG5u%lKg zb?-{~P-Oq+j;WcVW$wG%dr}SVaNJWrguT0M^w6qsA9`VEc5E$rVeM^)kn9agp?cYP zV&$+{H1XB!tj;ST;cYeIKRX*$t(#e!|MLpt4RKCVwBk?fkmt9YK0HsO4DNDDkfP^} zzg3#YDm?up@8<&+xuM-Yzh1mvyKd(Dto)PrZ73yqyDNL@vm2KxxXoGXoDeee0eeQC zj$L!$+xJ=J>o1g;m^81SP-mv36~NMnINDGin)mR1=lM@BrY-9bsZ}>wr~c$bOY8cg zx~vi2&DlA>x_h0j&DA-STRhIpj9z^{F5gRHbVX=bxKY;S!@1qn`(ndp9C`*bt=Umm z$L<3D9(MP-QJbK13ZBS^CxQcBdP&Gvga*=&xqID(FGAsq5$5oPb)lEUVwj3@7k!bd z69r%Bz!&EOio7J&qAxP%uGto9XCBlD!N=Xa-F4zk(*#w6SFf#hmNcCfd!f8EV|0`J zo(`KKvu~Nd+Aqda-8*xb+t%_;HO=8^VLEPGD>SB+-#j#_(#qYWAj7TQejMG(tK;Lo zhr@pSDOAK_<;RdfdhFaazM&G8zK_O?514Lo_(1S)rpn&eV`t5^NIoDoT}^T3`vY&P zH_dDbe;PK+{Y{O=&*k$DovXD9HMxJ!ZN9^q_f}ykof_j*#oO+EXp@ghF|&)hT#&um zq1AKN-kJM7CO2#{bVw^*uKr6()GO1m6t%rGhkD-HCb6@nYeDh(v@w1*4(ih?ZXObE zeq^&UKeH~+c=sHh)Yy-_$AeRJedwm*AK|`u7B{$ue(hA)@_P^&|qc8pdEL= zo%I86t;KoM<<^6{xA_b+J2m97&B~vCtzA1*S$$k;)W{FEBjxvLNy6iUhlDCjPOY(i z>!W%zaW>;u5%(W{**sMIAOT)x9E@DQPfHF)%7{o4;NwJKPAN0-(J<$!`?b$UE2}R| zjhX@@?e}RdMv#VwDlAQ{`S{ky1Lo|!FEV&L%qjE1@>$E-@}b%~uS>>FdgpU;-ev{u zaqWpk!Rl*Mqh`b77xrmwK#)d-Dr`)xS^dr@79Nj#AhH!bu4tC9^WB+C{-UK1vO=On zrE2^^Ouv3?T~LcO`V>aadnghPBmEX)@Smt-X7gI2T|8$Ucqnoo&7f|U@Z#N>6-Pv` zJp@6ImGV0RGcfn1-9EBzth92R7_5q7CO#8ZCH@=eUh|pWOq~D_sf;p19EtQtQlt_v zaFy99StQcmYS+$ERzH&(wFZgQQ7Z)DA0Mi49zh(!9R_PL_6`kmCMZAhe!TB%5+QlSbNAkr!y516y_k;vd3Fz5CU zmhmlTFK#yz|Gxe1(8sA!JB}A0J9V6+;BI9Kx@uiIxSlI6oAS~)tm;P%RiAoSHsA8 z&qTsuq~Fh^l%qpnP75ckc`&EeoKS@YX*KyZJ~l8i^_j>!G-tS3!iSnO56_A=JOeh! zNe%rO=JdNwy^^Kxbl6Et=M9jw*5~AWAgN({Voh+Gh+haiZv9+D-3lI$GfU8^JtG?| zdf_=hl9$>U43FP*N;?z0?&M}=YXuNfg4rn(5YwP+(!RgV&IKD?Y zazIQ=oV6m5=ogY?3|QE`?VCcg{5>#obq?P-XAmxz3k@ma8W~4`nohUvg9>Y;^-IX)BVB!gD zOWS!d3R4QU+!!UBZZWxF(QX}+g)v???gu1T>+HBIf1KfArBiZI!n_~=o|jFJkvLI& zZ5}+|>SgGxaxx%cwGN0`!u)i=W1CIl1$QC*e&;3uV3Iibwodkl+uKve5T+m zI-;L0h2mj&%myxroA)OON5Kmc6qx}EV!tRKru}983gs-U+bgmL(XziV{|1hT7H_f@)pl7SGv)ds8J!dbneaamc}o z>bR_c2)qbIVD^imVK&xiPKk`wIe+TECNICu2j_Zwn%B)E6V}y*4 znM#1~o{{(4$XR|Q6Z;c{VB#srGeo{kmw~kL!c0gTQKBR(*zBg9R=o2f8&TH(}afALr)BS*E)IU%@&hWO<>9{CSfeQHH zvgwx~5TwtG=?<2tfC63@3cMM|87HBDZ+rl;_P35Tc@hQF!E*x8r6^j8;%FHwX`lA2`ZmgGugNkkdkE2TdL(>tTuAa(3birJ4OSDI8CCuy_Tu zNcz)*%-RO1hu_Zlf_8;7mZQM(IwOln*-w~%1I%X&KC_HJrStz1YW|nN6voYehXsAX z9|?o`H*oVG6Z&Gn5$>k`7VrLtCZsDYE>0K3#Xc}yhkhP}8b=5TLK1>d-Nzy63X7G~ z1@XU+dq3GH2+dBIrY_?VCEnCHLYui9x(8!qbb=IQJZk(HhoIn;9Z@g@x(BL$;u=tJ zo*o}F916~pGj+tEs4o@QMsZ}lUDP3P@Ur3sLm>XD4#oXyqp8+W5-{f~=5pvBjM)xz z%6ilsXB>h8UUpK!5a=GL`blU&0e^Zy%y1~+PyV1I1_gYnIK(C>+YHBB&qUAbFqcCF z9z*OD6n!%VO4}tq;u@&;v0_9)_1b_LUx%LTp+iEWJ2PfDBs6v-Afb7Q_SyTroS8a5 zMmINL26PXW_(*7=e#nYR1=Y{tJ+dDCSA_T3b#=sM#du9W6fk2oWH~YcAZ4`A{@21h zv-|y5NlrL;GV288^jkZ>zU);dGj&{y?uLLF1o$S;W#i>e@zWt_FZCfvZ_+6dz&HdA znyGyoG+)r~UyAY%neey3#0LQe>fHSNK+EVa%>NLWe?2w-v7o;0@ZYU;+~fSShW;PI z&Hw8rq&w#GSjpVz`*{rVD(Vv|aTf_pFD6n!mi=sUf!LG+gxnW82cCWs9J9#<`nhO~rp>$5VoCf>00I-O6UL#&N0FC8FrjjfHw;B zLE`W#8TPZ0XbeK{3!Mi~{%!_i;GAB&Y=&r9!<>^4G?;T0)7c8<{3`gc&EIl%ngnO2 zgjdmW9SRERy2Nfq%1;KcB=Hz&l=sN`G3wR^csn61NOqhk=p4+D(V>`VGtZ7kV}js> z#c;@*+DG8S6p&?%1ME6XUx<~SM23WR^ck0iAzV|gYdi?>hFnN)w+`hiuyYi;yv~Hd zaRO;Lp&$myOp^q^ozP!K9J7%H`WuiOzlfb5D-n@;HAL(ZAjSbM5XPi}ykH3q z_R@|6bL?ks$D2r~J<^vS!a|J{vMDHbK?-CBanG-XQuC~{}eTG?mqk|yay2!-h)yZV!!2!x)qMSuL(&*v!_%R zrG*ja7a)TOf^#y%A^U9~A4=N5Fh?z_G}VH7Ai`kX`mpN(A)(xd8zQ z2dtdfBS4M^aDjxk1FKgt&wd?tGSvi1_9Hvdj_a#QZzv|@9`S3nTp~xak%Cxo>Z394#bzx4Q}p zOx;U*y@G(9Ftm^3{4IEaoQ^)Ui^H`7B9Jei>&I}Pt&?|ATm!o7uES(J&}qb2@tC?` zaSdl}rVi{TO!i|Og_s^jIQaN63s0kw-+Fut{wJ2$tF{@U2fga>`vDOs49z{xaJPav zB{X0&1CV;4!;rD_U``1Q=T%G{*vy!GoN*LVlCTHJnRl$Q`9=>)HdubdYVARKj7s5nG<-SI8Lcx>gI6*o6*Umr3*{jS5 z$cA8pgOoAaco;ekH;iE8p&vnD>E!9iB|{`M&?!zMlyng;{)_tkOHuw26aE&Mf+J{s zb&gKT4X}*XQF<{x)Ee-gcE(PBHwzT6MZ3lPW1JW(w~7T zI4Wl{Ge!#SkD%j`_?*vINbawMsVg?%gaXhLD6!-2Y}82NZ?7gS*HJ;G^*CsJ@V8fi zh#)8!=*MuKt&?~W$qPgz;}H!hXNY)ANw9b(^lZ?tO(r5jfGUWT6V88# z3c`@}FrQqYup3d;s}~T%)e7E&s0!~v9EJCw-{jyV9;BG{H^W3H6u=~4J&263o(BOI zka0erj5ule1@L@hAINupSO;SV`+&8}c$kkYP>@4r;`JpN_cL~FNQ{;GCdU7}VG83W zKA`|k$MQc%n!;fIV?zIzO~_4{rB?{`ro#o^wAa$dqVP7r(x(e^NN&QsX@$VOGpcuA zQ*g%TwcP|kh~0TUGO-*s`7c3KAFIt=1yS8jMyCa$dYvER1Vr_vBMPRXsO~SGndrv| zA0MLzQN4MljsuG7lKdkIC&0rm6)%{IG6hsuzn?raCMYsK zVZBn+S72ghjf-*H5KxK2y03WVMhNSseZzY1oP?B7_VGW)N&J?vckN#A+imoF@c$2a zLIn@)l!`+Em8hMf#BXm85K`9s7`NPjN|es|N@NzGMNTT{ejZQ>>0E!w!!M1^&!Y{E z?(`uNnWzI`Dqip;&zSsmMz1pa3-0qH3cUp3?`M>jOb=k3fV8U&rCt0J@L$reQ0N#C zKE>I*T*m=rACfwl3GiF+FY~ZJ^nbn19j!hiT=!bg#aCHY@9`P1Of{4qqVvG~&Hp}z zAyjaGrOx?+6N>%6TIue)zRp;Lx+%h_zmY+XLWj8u+_9aO4mK-%7^#n!5h^&L?(`p} zgU|14>5qcH&RTvq4hiv_sPp+19`Zj#=^-kEk5&dCpMQ$s<*(B+ZCs|r(RP;W?k!qz z=27R$7edPXRew9cf+@jh(>q!#dHM2-3`oDa`^5jnF(PRlL_2>cRQAI61UFA-#WvkFbiM4BLS29!%MQZ|tZ4t)WF`AY2wr2xJ zDK*H3s%Txpw=ImnxvWXO$qjOHGK^m11;88)W!B}q!Asca7U?cm zyNkw*EzZeqk|h>BuU_WS1Ji5^ZfkyORH=^9&b^S7*;Z$psM8oplR8`X>GG#vnW0hJ zq>;w;7Ei7p?i$G4g>Z_&Hj(wgjzYL9@!0cc&QnfoC zja0oLnH1Q(GE!ix%j(2J>fYaMN{l?>tl`C(eE`0xO8d^9)>h}7_@aqWYwV|??V)e& z`HOPkFUkR_mCKjG(2mv(-eR?*n?X3XoXev|cOWDFba~u3_`)*G%-GryDaFkAsUubj zmT?Wpcu9%=wJ0Y(X`K0_aVA9e)R`}`iv^^}4%L$)({2Ex(Ns%|H)sS#mZ!#xe|W!_ zw8}f(jdk^Aw0NH~FXR^P#Sg9U;{M=nKeh#_wZy2@(ueMK@Y{$$pN^$eO*b=+>ZaU} z@KyRN{cFD-KxmZo&c@5~~MzZpg$M43N~0?ygxBWZs>eI)608eV|t z6pmkjJ;wu*P6ytRbUO8}PV80P9JPtp-syUWPgR@v;N8Wh@JDHGVe&_gP&v!O8`U;_ zd>oR>8mn*X0T*0eueK@w5vm{0j?KIN-Pj5gJ}%9cKA z-XuHJy-Bez!P6VbEF-2zV(%oyPVFJZ?$dKXj&{UpSQmV8*V|C!F#5vQ-Eibl&_|-4 zvizN=K|SfJ%JMZ&)ytL!+O}|ime)OlB_OxS;2D;HT<}lN!2RUu*~{N~7Syvu&0fCd z85-@}0#y8thYZ8v+OI#8W+xL2oQnv1_?+fFBbVjU8TvL@Ix?UxW(zkrGB0y}HkE6! zJ|a8p`S>bJA5;FK%=wG5@UHnZyR(+>C*MC=+NJUHf)^m11lC#kdGFy1v+T2LSHl-x zc1|0ktw0EO9XHDCMnW+2L^6H}GOjnH#QWIb*_Xu+-OHcdjue@LKxB`RWDrx|^F>zQ z({rC)UK6X`)C0k~I#&DR#iY!n#U0>J^V>*&+T2C@Q)X9}Z*7`-4^pd{{%MG;@C`&( z28yg+EC{+oIDlpwCH@;Pxb^@8)Xm$tVT1gv z0wm-O@;U{CkU=HGFCmqbanc-(qE860FJ~j{4cr3nV9^0I?cFlVsd5w9c-p&aG`&q{d_1;mRn(PO9$vX= zi@}q8Lbn@Elq~ul(IS!i^R-zbtOq{nc~^9_GH*tm#QeV- zzxIrQ%KEr&Sl!-h5B!$wLTNy8to)i4nKz@G+Zs!6#*doXa1I%wN!YbnV^|Lkr{^U) zKa7>%8@B^RI}5vOXBHNTPHoVn<&Fuvb~BooxUI~1_L?}UIYnOH=2Pcv+O9nvmJL}~ zO8i$9!C{G%|$%JPIbZTpB5_;?v313otB3zmmWl9WBXP9S7^ z`8fkIu(MO+Ut{fcl`mb9$(J$hc-XNqgdD&Zks{9O0x_&WvRvGOWJ%7OuDXGo*A_2> zP&6zfhCr6u-mD+bXA7iGw7WB}ZQP2o`% ze9>A81KZc$QsU3}d2H7Pn+3N)$l#(U+&t{DeFbsz7HL3Ve-k_!UtbUi34P%}$hRm+ zn=n?%5|lQP=7+o)pP%5(1nVm2ud6w=cV48(fs(zVgZMyL`@aV)N)ki`#=nN}Ht6Q( z9>I$A2;76s;n5a+aa%stdvus^dEio}H29Bkja+vW>4LB@@VtC=-R-3;k~is;N>k$q zqe;kwWw?V|csweiHF=Mg zSG5m%{&jnT@k1Z>V-ePIa}&9VQfQ=hirbYbl0|CD1fbL?KA`n+4i`y4+Ft>vq*(9K z7}wtyBaz&bQFCv{j>8B7WnbaS~1 z%a+kATaGTNY+7R$XqH?zwMg&L$bJH1x1XM0f@Fxa6sumOTG6sP7WKwR^ z(`s_?v~oysor=>3^opk( zE|NL|Nb<~#$^us)B-_i}jqVoYm(5pu-NjW1jBUSHX2r?kb|j9JkD z5^cP+J0ZU55uWvC)4lj@y`c7xp!Ry25TLxgYF;b?rClPFrciwIQda6EaB+9Yo79pD z@SBqiEvFe0zH~L;QwR~4gVC6E4It)5S?h!wO^;^(!MeiLHre7?Eu}S(ZpUJQ+aZDP zFOqTtmF1ePD+^po@FT-;%+dz!g_^x_YNt<@{Dp*ib)LwOpuqE)i0uf$mB6x^BnZWK~ zENM#+)DVw}c!O0CT?X#`6uasaaSxjl|o_W(<@NeD1gqH~tl#fXD$aXQhIyeBPIqT9}csgH*wS z%KiL!KzF61gn)3|DaC6@7b`%zU_T@@guM$Gfb89n9|=gO`?ZmP7}wv6e(9dTqyS8~ zG3lssZLfK~-bhbFj@@>TXB{&0p5py2u0K9dS>y%@_r0cV2J|$PaYNkl2t&!Ix{z$v8S?#s*=$|^^crWg zx&5%#tmynf4a(D@dD=N!bOJhe$@ybU;hG=IV-wt_L9pu~z*Uugk;q7GdQ}nvi&vL+*;e*r@<0V=${^~>L_@f#(m=0ieDF&AxEDn*8;KGXz@Cjo)Q z^Jx&qrvXsQkDWV`NKtTci5(*r4Q7G;02ZKH7n1KClw}`wa)z)R^T1Yidls8_Hz$Y=^67 zl6-%^uJ1LKg5e@%Q%f>YdPh2p8yn;ahhc}Zkbyqv-)A*{tn14CO2~sFpH|jB3Va#? zyaeJYcAoitf!p)@72py{mj=c_xHQ!G`OFw_;|E+Ok!Sa9{PcHJDCzjjM-t^e^4j*- z0||58UIqy!wsMGD;ewVEZdU+FTlZTd`^FVT2g)Y3z3Tjk9Cdu2F+_4dkc=(&!b+Ati2o3VCr(%93` z8fIi3W`DmI{VR&KM$_?a(TZ2GO8~p?ROE~IUV|&yjc^@3zF|0yIOmPw3c>wBa@&Q5 zNs>ikD3T=KjvK3t-I`tFTG!E{4a1Suo5NV_KDAR^uPlMql`r=3FfSP~OO2n*i}v0J zjW|d}T=x-eGt;n!NvcI+*a_Z_A4_^mTchdFf4Yw&wrcVHJ}n^5TL|rC(HJ!jJvR`r zIYnX{1_tscH>14w4GiQbw`+0W{|BmnAfFBq;J%PR?kgmaBgqbQ;RJdJuYKB;gs27W z%B6|%C%0>J-U6NaXx|-_MM$r5tWunGuO0ER540mfr2Xv(D{6opeFY*23aT#Kw)hb^FQ z!pnh3ke91SHZhHG3>7Jv@Oi?mMOen?Asc{1yPngc1FdemJF#D>T^3em(o9fJHF7}Aj933Y;4O76- zaXD&k?KN#FJi=l6cGpkNfRNvO6}1BGV1+{(h7U)kY;HV_+2|#L?Od*!L4o(Ihr52zrbVN_1N2k$i3P3IZP<}q$YM0@|)iza3pdJ9E*aO5EWZ^ z!hAcgj;Z_=@&_j0Xz?azOj*%gKO9d94Igjz_rJezAXQ8iS~nE%(68bHk`n?boev1T z=OFuj7ZdxcI)ohdbt)XTfG8t~y2t~~__|%Pcpf0vL}lX2M_ou1`G|d=i2@u028@$~ za(zLokJOD#uWr!7-xrGIBGp3iNT?P8@?hU*AwW_SO9((Iafew<-$r0xg0g%9W*@Sz z#`@tUg_wP2g7=)$r!0;n?CaoXqEO?D0#-;4M7cK}_&PbOn?EDkg~2nHRmMztRVbDK z5D}jva8LNgO4qTC^>Xm)$_+QJM&gmQhKNiLw)!vVUvVWKPC|MW+%WA`p+27BcKiks zd|d{eKi1C5kQ`f<>qc`1!KWd?KaW|GhF_Q5`?~$+TaDqhm|b_{a<^-6YCM333V{tZ zSV^c+QFk-K+ergu2WwoNG_Ylunq1>g3*85D+Vt=i@49&~b{UWxja`NfeJP!jyL~CA zW1Fg)n)r1C4_R#p| z5zMQRA#E?~YIYl2Rxg(VlcLVi21FmEgycefdr}GESP9?)_Fj!F-$1y4rGkY{(x<3{ z{7|KIK%jpQ_A?+HMw%|=S$lDX%6j6d)5emI{ zMSDHLscoR7g`)+zThA!Cj?i4ny&oEW68%6%?s=0 zt|AFTD}<2nD>vG9bxw^Fk>+O;x_~vhu%FcvYrIOV5qLl%2TLT7qm5I6DhvtWE@(G} zFSIbe(Adpt>#s&$1f8K`atS6J^1HRnv)T2N9j=BH>MJ8*(Cs{Hna*1P`9)&kPJ)GB z^mbAwTu?3Hg22DmGtU+xVnXdl5VJ2JBN7mL4>=HIP7K8UotP0ds_=|Aky9f?fz*vf zfz|EAepX9}B2=L6*h2jch?U^I2B^EQZkpfx@xoC^#p}i)HM?Felr$-~7`*8Mg}B%p;J^Nxo9P?6*QC1GJ`g`{p!WWl<@A(c>KiV+qvasXy^L`Wt0j9QI&Mif$Se#U2E?1PX>S}d40 zVX?iY4Z1;wM(AeGA1@q*RLtH7$zaHY*`bh1un&dQ&)FAjb8Z7g9ebe5RW5`ff++aj zPi-RU{ZL3H2BMIP2jY-Q&WJ*)z?*;0XFmH5WZXd_0s3(hx=|MMpD1!*#UFZ8h~u_f zHqcTpLN2;TorBfgQ{3JVT$l*1r3$<(irEAU7|D{wV0o6<@~k$R6GEzhv|&nYp$hgc z^W&8Xe`ODif-z1q41~E+D&IiDL%L~<08zdGnv&~Y+8aK3UtWKh#N;+js6U(-iGnZTM(Hy`w=d0 z1tkj1w#Gar`(3_5ji2`24q74Z5R5kTOzBykPTpk^yZoZa&3U{X|4^5Kxr2 zBQ$uCfXK}TV1O2<3io&W?$G(LAN6nV0v>WgWHfj}e3X$?As7vzLbQP;cr!VWJjys= zM&OhP3(n%GUHbSz)MG zeq;SLxZ-LUTH9ix4Qgm(z;vrIT(S3by^?-JgcXLx1Y-qT=@roS%fTvAEzTiy2?q~6 z&l%A0{_peHbairj6sDcppoW|9Z;auJ(}=tA&D&RS-lI)_g|LSA#A)DU)nbjkaddLa zqoSOkEbN@~r!9ljfS4BT`*(m+VBf#G=@o*48;W*`QQrJTK>CUm2%9Fs4KpN*9Qv~! zJmLB{`bD(80&RjmCxU7HcdC$CM|%s|QYX;&o(M+r8{eRYH(~m2`+IINp!MGfhRz9z z9Y-J15+Fhnf_6y3V6l%g!5w5gX|H1O#vAC9@KSxYFbL5JwlHvee!y~I!=M6M%{iZK z81N;8VkAB@O>P*VlNBgN4n#Sy%l&&8?^Tq-`ib4srbR_9e6{xq4jlercFw@F9t|_* z6gg}dxJAU5Tkly9V!M(c=mvh@9XDO+$Pjy*t{@FQJ0WA}bGrI#lqm0`(vo!?Ym)s$@W)^5~oCePTeSue@05Y&&qiZPPgm^rW|g&S!i+i92nTPCpgg8 zXKQob3)yEKphR#~g#W=Qd7o1igf|eJs=)iKc)~tAZP=G$6%O1SLcmcRCw&p#971jj z`D}OqCps2?xp@N~(q9ZboPfDEz_*j!>+jnM;C;g!VTdR(hOc$* z#6c7yi1$B;f`Ve7!*D_!WaC;E>|=`|tC^t`M#ZN-~d5Bw99=jcl8LFlpI zgn}3u!r@AW@Cfkb@5m7TP7uNu?2V(4AzTCNT(km0`0jHCR5UGwaB^A{!t-uMaq*6S z@JiM`GG8*ewtI^K74KWZSpLr<6p9xpBAnpSt&B7SsIZ8W12Keik4nOBP9^6r$IwL(@P2N|44u(?Eb9;tcs) z8Yq6Ex%eOjq`rNAHABd6KrBSqkxw86jos)Gl*R?A7D?kYj_zs#yXOnm$5BuM)9aAn z&_V>{)9=7Tq7n^zNb(2`()GY2G=!A@Vw8QH{g*J7T@qm(K_Fq*2f`0u!UMt&W=Q{% zL7VeVNcj0Zx%EK==@g&Ig7DLqolsj4Ka+wyNdvskLm_Sxvp@*O>ZStp0I{=O04yX} zG|;;vO@09p_5q;jz6l=THV4oWyG^Xcfrm;F@PWUHBY;C&rO$8TFo6bSz{nz6+pUpt z<4$i%i2)TN`BwlZB018{z(|fwcVHw(JRKOx37$gZNl>uPDUwEc;DDnjgpc_{Q^u(~ z7mlKUW)8C-qBBYO%mIqz0}KawQ_Mwt=76XMiDQO@&k>k6+G`>V40U>f>Fb)Px^}lge&sCXST3g|6{iV+~fOnfz_aN zlL#wlN0m?^aio-VHT{2Fh)9~Eiyy#FS|3+CV*SflVa5R29Y4zaAp?l?7f;xG6q`tY z{}vxvb{(4uKIUezf-@QW>%LYj3^)VL1`Md4-5m2?kM%A`a{`)Z%#e8Yno!!DTI{vL_~$%J zQSzCM-9MSb!9Er``x`3cjG+q7jRX+|Q`WM-|Hhgppbwy|kh~s=|1+D!!Wdwa*(l91 znc4sVum#;X%;rnTj{lmyrs&`xS~VR0CVzSTn(&Q(<~0K|5<=jx*U~4K{W>`ukE2b4 z-k&Z`nvqi$Q8x$*Da?sKo))qQj{TK*1#Jm@Lty0<|DgqGEnZlABH2iM8{u2kbNFwXHP_GQD{&x zA=IL4Ycxi-K}8q!)}R-Qf0J1D3Z0+EEJ=o#j8pC8Kf#iD07r*_Bk>h*koqth{A-7a ztWX6a4M`BF55vU`L^BM~yxf@DnH}lPVbxJMpV~sHJz`XDt)(|dpVq@wp>fJAxy_bT z&W`Wc)J5LBCQB|eg~IKs&TG}>(uVVzp5#SRxOH@Ic3~o|r!A4jW6AMOybYpw_wJUX?j=_>C>UK_9Dh%c3MmBMQm zqf!-lN3xn(CA{4)cwAOTB#qOd@>Yc_M`iJ>x$HTdAR4Dfg~Dxg;PtfWbLF_aAYN+; zmG`8Q%hvyRgx6Nx!IOyPb@B!otQ#_P)Sy9wMhtRUf6*)>R>xa*;-EpdUkw^G0q!2y ztKw|E-N|aFk&DwF``ymU2kiEGmF7L){btj!w`nE?Ma$wXsO<^#kmlUw6I7Nvmd~j0hNU?7o(c!Gw#i3o_QsZdKmfb!>%op2y6yML%vTVK0eq`=r_J z>(EnhmG0FdX6emkpUt!I>Qv0)a+5kNve@r;)7dq}DU^fl8MHQ2OV4GVEv&F0ORvW2 z7Vq|k+9P?~&f3P^^iD>J<^c{n$I~()%Y*YSspXz~Tc#zI+rv_$wS6iK0^KCFWFBPI z)^t$1dkTZ-2fHjmiftwI?w;BwbPrB=s0#fcyP~d(+uhxDRhs&#;f*J~=Rbl?Rzgkz7WT6ovhW%3-N+-|1@};J&{k z7Qv$@S|&wuI>cIb(|VGq-rb4R?j%q~3YGQHvZsdrxHXU0{6wvc!n;r5exi7PqENV1 zO;S|#9wQ#-ssoQZ+%lX~=|E+fc(-w+EIla^+_vI3915$+^57x*tgBlqdxlhUv+4IZ zg;e$@{lF`&YQKchKbq{Sw%Cz)HS->CB z+-LbN>w%Yl_mqxB&9>zwsfmu3)me|dPIOB)o2ELv%kuC2pxRuP>QJ3^qFeC6;%$~x zYKus-=b`RCA7`Yt9O@qMXKeG*)RwndzTM=91$3#FypGJU6P|@$Er82~p7ADCt)jzz zKTT~`l;!yop4DDYRSxxx`!D%(wCBuImH!2Q{CfoYx7@jt=vr?#%CLW=W0?_Z(iR z=qI&ieNS7K^SJwQ&r1QpuDsI)cQ>_VYTLSAzjas|$ci5tL$T@H_%LXSchSd7hou+w z#J$t~=hpvPNwjD-r+AXlk020sS&*~54<(~p?VfokvJu{DoVN>jGDNFc0++O=vj9RV zBH0-M$!5RP9Z6Z+x$!~JIPaf7UhsZM=#--9cs+LuG z^{ndPo%;R*a!ftjk8iKrqspE4_-5O}3|^>LPIJfOo6ZEQJ`BBCPo!6`NB&SquZkPK>Z}8qxKNt-P`{wn8Ut(5E`zN5rAjof92v_8#T*^o}8x>K}vofA*ajBB$Q_ z=i|vCEsJ~q>d zH!6|>|6{)FE??r~8!?Y|-w00BZVCf`%<73!p)j(=*q?lfkC|c~ExwiAQ5~8L{E^F! zqG>V`#n_F$#K&kc4~FjycGM9~2L7no6{WAqI4j1k@g+X`i+Q~BwdjnJ(q!O|-W^eN z4ThT-yTX_FxJS&R)Hk9%>Z%39)-S@%qTSt2L8xxi{dR~ zP{i1IzQo7x#XMg4&S;BzvW$U0YJQ3eTE>tSV?Xsp9}jj=V+h6Z)Dz#Ny7B7nLG|RN z;)+b2mPh2jT(96Uo;-7_zZ(txGvk+h--#YKwZ%3w z?vK*g@~*-G{)wh2Fn9ZNf60%W$WGFxZa&aq3jZ)FMrE2tyD2d3{VQ+eXYi*@*S0ia zG>-Bzk4{uzx{}jIB<8nG^vKfAGhuX%(y%0_l~!c>`g`BZ7n5Y)*QRVCr=2L8`D3(+ zBJ-HP#jSh=1Qnrusx7^hAuH;&Gdf6-d76(lDSwBg#|!PCt&HzQHFlBH@)Vho{@kQ| zsw6v4o41vmR!=l@Pqdm6GuFTIPJS4F+E?22Z46UUFWYDbCFTu2+T{E~Nsm%(eN)CB zQ4KqCTDlT5!{0k4zeSQ=p-n>)Ktk{r&D<9)rObTbZ;_fWDn+8L(T+4@oE7zQiq=+>0g(cROW^6@YGr=xIWZ2)}m zhJ=~Si?a*&_DP@L^3&z)A%f&*+3(yG>ns@J&HPDPU`s z>TbjRSkzMy-<4$4W^(m?(1slP#j6F(!nm%h-+RT`a5oh9oWItku&GV=+It7%oXEHf zGz0xh^;Zkp^mnj-Del>Hz3bBEHnkh?^|$3%-nl@rUPR4{SXHRM!;5vbwTIQHCe2ad zH&qAWrYiJN1^*cdpP;GgVr^w-B^XBZUiXL1qst5%G-$H)ph4sN4#R`LN3GYUt$Ge+ zs*|!>OvKYuK7|^}#Tor}vclf3bf)7{=IV8Kemgu)+x9#k`|dCMWg*28w| zq+)N~d%k1b{fzIWWH!&6kkvHu;Lsme>{7G2yJ+ce3vV0vtvKc3uq;+t>!Hr&yGNbs zy@pAjK9e*#^r)9xtWn)%>y{|ZZk4OIpA22{+b=r~DF;c9d3Niz_(Q|{fhRYGaki>P zHL0J7mrq|c{RP*_W<%@PDRVbPs>cnePuZBtVI0t zBGByv%ZVibARek+r-=ICdzrUN1b*NIkD*pd)8wE zP3IS3p_EMbu4(Y!4>hfUXP?j_mbp89>XaJaCVBE;c-Q|c?8@Vz?ArfeG?uasX|W`- zW*tk0WX&F;CJ~0o&KPUzwTyioDOn0-&63A5_MOLCWG92MzX+pj&j|fSp3+m#=l7m} z?)#7P{a)ASe9wJd*E#q3-1ly%=vU&J!CY~_8qMX=%&F*i@WsX4m@7W!(N=e< zqPhITEz&OW{$GPZcqZ@6*-!`%(**BzTTJLwnkMC$a7n`uvTR-&I)J_Mwz0nQWD5K~ z&{OkD2t5!>d-3zaoI&U0{xu!2)CCuiC3RKHm5(UP?Iq82y&XFyBFk>8Drn8}k*yK_ zE^PjQCuBTZ{Z*a+Q=JJ!(fTMKqXGYec6uuDPaK9O5d=C9%7jM+y($saiOCd_nHLfF zC(? zizc6b-KuM}K3M{FJv-$d`uQZ_{y<;U?eViS01me-M5gGvqd)L=njy;yNcM!;mQl2* z8?jzhJOPO)&SS~EZAEkN{!+?}1g&?0XJtZpE-rN>UrNug2yE)}1-!{Er-T*_FrL`Km&Q92s+Fv7$6WvTxxk*_cg)Gj#G5f5fQ zzUX@v8TqiA!3(GVP}qbmJtL-U4RW5gN_GuqB^%OY#TKZO1mSpO`YC4rp8iP z(Hj+y(!)mSYcE3J%*CNifwz)tVgGNE|=QxgpwEa;-&I@$RrCWKl{_fT0+c~<%6gbL1R_`OS~ zeN9a^)?nJV<-uFM^4jQjLTzb5g@)lMV0ndyBD3Y! z)#7}!cK0`D3f{3rVTJM?t+8KQRJGh7oNiHvoG?X(vaE-xm1W@9T)X$3?wc5nq zrFyC@AA~&|*h}ifCRhguNK>({J{C`(bS<8vHR$o(O6EMXEuo;vPvh*y;@s9NosGuB zg3XcA8(stZSfak(FCxX$0K|2#^{H( zJ)U;0se1>J9GTT`cy|^Wz9*iei~{_4t}vDy0I(osl~YF<#m)VJBjVd@yewn9%X2XX zU%a^`G3BhSg(lEQ`(~!r1SB^JdmE$!A5x5Ul`FCP`laU@xj}`;@;&&Mni@hqG))sV zpcRmsWLJ4hfUfXSRHC4J=a5LNxpb9G`|Dz(cq7|Z!$;Pq>N_WSqZMejD{bC!Tj=XX z>^Eef{cY|SqPCR8u2(*7Nq_4zP$uPEe$BJ9vcBKuhYsOrIN9soCm=Lxg zcmA$OrGlp^TPOTM!_BeYH-IcBu?$N4z|o+blkA(^;d8-#(S<84u}o&hwHBgfA|2>n zxHb7$g*YYSrTV0W#_q{|f+w&#i;UtloVyfM0(5Sa$Uw=y zv~0LC{8F!}V6!#_FEj~N!6>oml2=oHb}kdJl)jN8M`JmiXMKHRou*twdru`>Fvhg`DK|_3Y!lx z9$vRT-kU+NPVwJSqi=TZX#-=vU<&3yXHx5~ZrC`1{&4*|<*X29MmIbb+U6-F$Cf(7 z>6O0|xn;)Tw(bQ)J0u!;Yw ziHS(kRD@XFGE>`*|7o^)SHPeNL^)E?e0Du4m z0Kh<+;Xk@rB9Vs$Q;MOIGfs@5c87(WAU>Z-MH2|umlZ&1Fi?2*Z-kiKQRR>0l0i?< zZ=SB(9@Xws=_6z=N-B32amy%dNkgG*bY8b#IGue`#+L3`ZZV+QBZ2LTA1kEwtl33w z#vmRyKC^hyigpq&ktC`Mqc_+ztlq^1MpNd8??r9Aws+*xGsI=<%_~zp?J8O*%)>Uj z<#3$C{)ySxdpaA^`wYfGY>HhyZ*zJ754$C!1kuSiu;}k*)(#6+E(&&u zNYg}5&1P$;Ya3yd25v2&G1|pO7Rb~n1m&glDbb)x)y4be0QPk7)B%LZq;JktNRrt>VQE>jCuHjx{O%lyA_e{yzo6mNnyV2{ zV?XrVL3Ao^^jRHbj_^^QN_Bn^*VD7&&8f$lBTwtwD3?3*;v|TX`kL$I%(3py`*kO6 zc#s`WNv?|V@yeEH5SX0dg_mnhoEp=Cr@b%E!<`qbF}83mcDzc@c%#r$zKXGhlL}a< zJ)2??d#?dl*N(0OsG=^^((4|RSq82xg|g9{WKLkCjv>Ej+9pAdeXB!mzt zh9GbHT!LQWnyDT;+J@GoQKUizgxNyb* ze!?!rS%tG|c0>m0*w4OR3}}A?StJa`)&(iHlXWTIotDR`3}vx3>)}dXiF5=;T`?uP zx$uUyfA0TiE@gzI(V&MZO-x*Jm?C`ri;d zu>!M)`{dZ$Gx8;2>6eG<>XR*9SCSfDBsJ)d(uS7{$^q`;;&7-%bX>O{xi~{R;i}pI zbVY<~F(mlU*VLz5$m$Z-gdv+kP6-&k^~<$Bn{atHbI`1nY)#Rn5ZVMin=xXyUp9M8 zg;t!DtY}n^ZGVgaS+}mpCU*v=^vf^{?^UrBNjr$OJ18~g`stQv*ZeARAvAH!#{CRh zH=|>Nmwy4*hHiV(EZa(6?acV#qyM}wHN(>=IoELvm^qn)Di<1R8KI1zQCDIBs7ls(7d&}LiogFoWkKpD?F3fHN-vGVZo^xXv zJ-`q8U6`(GqHG^PgoA=|S_Y|0w*zwXA~IDaIM+~&T<`gZpWdhVN?wSS$%2i8c?HxyfxO8#97PZ_ogZG_>x=VAnHxIOSC*c(GeStf z?Bhlbh@}T0vOtGvN%gOhB1xj3+FcbFXLp3NySdQ=B*M+?P_biz--9cuH2Aw6#?J^6tvL$e zco=8@Y4mfN=GYRchc;^GyDq{?h&6IW#Xo8gCNMA%mMO0^$Dq zAZeB%Sw}Mg0HH4@0Bk?7hd0K*VZTv)Th$*Az`q~DIwrEp{pP`MN3xC?ejoFH4q;{e zH-_)~5C7Eo*Byvs!}y0@+j$rMslDwRqhnii5R(ng{vB{D5aglq|MODZi=8JZ%b5-Qs4%bn6P z2#Hd*EBg|X{c`X9f6n=S@8#Y+Q}aAC&-47A|IEDRJGbxse$V-w_h)&3KA&@L2D-yX zj2<>@*r;I{dcmd_N`4jC`rWW$pGFKDCJJ}At+2CovaoeBH*!5-;b}91^_mHQP z^y7WkzMZ&6CFsls#qk2gujko_C-nqVBm8Dw8@2hUy_nY`<>J z?@_ua{KmymU@M*C0l z?io4ecJH^0an+te^FK-PFn!tUzfUg48}RGicF_Re=U{EYtf>mF=d zr8L%|qcu~c*Q1K*=HZ7abfPlT{I*V5^V>+b3q4`Z@oIX%$etUY zrJub|YhGSqgU`WV&vit{v^voN2%o;!q(5u! z?sZd79d#{i4L)I9drijRRh`-9qLhBMTOn&+T?>m3wiGdpT3?xMLUo=}VkS_RcUD&` zft57n%5g6#m#qT3`WL>IR(f@K7#oo2_I{JQ;XEtPB--J2xV zOc`~JKlJIHcb8wRY0Bwd>Z8A|kUus|Mn||_?_OH#_`{1!`t}MxE#9U!!f*7PS?>y6 znv|w2uAA!MG3$b!>bwIl+g9o<9J^X?rB8jkp2X`&w0y3ZZUpE=S) zRma}m_Jh!w%@s~seYx{AKBb=O?Gbxfb#a0DjONT4pC?r>rmxI-5jDxRt*TM-9|Jv> z00=?jXlY^L#A~MWo+Yl2yD@B-Y~RRX6Tf&Czw#r(^XD@2*tAUhkh=E6qj%=cXVNJN z)3XjljvF_fU-SI*7mJlIj`E*!bj8}PguE+p7VeFAJ4+ju3G6Jpz4!Lq_f2hYYip>z zeymPEO3yQ@C#z19!paEs>@@4WZAW8N_GvJ>PSO}meOAxyR%R%xua%X-Y!TOB)+kZv zWp>O@8KLQ{H!iH^K1phyAEl4lpF?GQs$+ew((qt0%st!a{QV6t%ssmGDZSYmtWE_= zZPDdo7F8&>1XJ(oGE2}K`i?1)dM?aj7hcG)re zGpLNpyw)Jk{yJKJ2klBttU2qvB#m_;w%eRloX#5l!93KCvgt(=Rh7zUkZcRhqENa= zYos%;v*-ylX6+>wy+DZ3t=}KpCi;w0S=1)_hEmyDDSd_I{Y>A9b&Bd2I+0Z+3Tl-7 ztiiO1Vw#JkQ<)z_l_W2*Qt!UV(Xi{YpTGEaD02z3FO<48G}h|!?a8K{?VG2uPW2~0 z-umi}hw5zxEA-8xz0OOU>h7wtR32r(U5aWpBa+@5b0Nw4S2GQ}nl`Gnr&@))rJ{QI z68V-Zms94H;z8UQMWQWUd)lka+ACuMlB^%Y!xpM7CI`e9Zb$NTE6 zJU8Regbk03`<<@3OEL5MHf}7MkeoaJ+yb4^X8ifv+p3&vDw7Ml<}Ow@z0>JBwOQ!& zW_1PO?p4f$Jyzc1O=ifyt?M?qHdQM>t8R8>`ETtTcinh3+5WydwS0852zvIS!=kl1 zR{rBB&xS`6Os{Q4kM7uL8@P6@p1)Sf(`WSl2eOaW&o${y)z8XVJ}>I{M$7QTEuk!> zAT6om;Q@JzZkB%h`Ql`mpOklD)ooi`m*k_gH zK226u_l->C&h|Y~N0_+u(m0AIj{FUGOi(6ilGCP~BaG1aiwbxPi|*KG=$KIw0IN{cS-54?G6j_$3@%F09Q1K0Z>5AV$L zzez)P6?Jdrz+GFI0o@I{N!uS7QVbKp$Vpq5fib)VWAJ>q)y?Xm6Cif34v9V2gq6CL zp0lR`bOFY&6pWz&biruf)1VY&aYHdXET^){@!=1!T${t?a#fYFTUS{<_~DA2y1I0B zSf*C~^SaE1^2{q1H^j2Tp24H{e=tFhZkMa7O^}mXvUQ}Mm}G|ezSq02Syr|0o}@&z zm=u+>(DGqVPpRB706`*DDLauqyrk6pU1jLIWVkz=^_v(gYjgkQ=A1o4Jo{cwDsJmY z8!^eyAd6QZYE}E5NqUM`mN2Uweuw$1@q6#-V)hgftRny`GX}i zDQ}$vmY@ih;M!IswKUSJ2%Md{;JZs~A{l zx8p-Oq%yG3raceu6z>&e z0=jnr-7-M8hG~}5V`qIZ1*}{Q))xPi8rKV}7-HyuB(GtR1$b1Os#10Y$lC?-0>0~Q z0`)-N_ENbZkhcWnO@A+^61P(R0s-+MSFqM5a0RU3bF;F^SYNTz2i5%o9oy>Uq~o@Zg*9X+)LAMo zHkn)8t7?+_jP@|NaE~&GAV&+iUh~TGnq^(PrLq#$QaS34gJoRemUOkf+1K7{<>%JD zcd+#=aM+kq^UBu#{$cmAmsVsP55Jn1QB(TECI89tCr_L?Q&ZxYG{r=IeDmS$@^yQX zf(sp#ADN<|3u<0Dp`o3Wl?rNZL}XuUsNC7xRVsfnUT~#KXhL?kV_F*^bP$ z_NmU*K9>7t+?`Fds>}7SJVb@d5`wN8rr$h~+gEiUB52yt?VV~NYj@S%qW8W$Lp|ww z_hMKJh5b|Zx5zkkuP@Vkkn*ubeOBqcqra3}xEp^+aiQB@ zq*+k9XH=dT^K^uQMC#}d^TjFph8IUGEJ_ucsI+c+;GxTvo5bvrdQz@je0peWl}AtF zj_-c_Eqi9{OxMb$B6pu*dFLQA;*1h`yBi2Z(YyOq;?Gd@m01~>`b@p zHzRdq(q49mQCB}1xijig)OL%`z}sVfu5uG}OG^)&-X%86{l1BarCriScinT%^Xt3l zCSIl6&bK_XT3L}+qtiNHIXxka)?_W{Pu*SJ#^#GEVJXKBeb3u6^)xt^SY?8 zS@y~2&e-aJBtGvev9YrcrSoZ;-`PB(VOz{P+Qk(fg3;;effaO6?^A(Umb4dnKkuzo z6mCQ}`@}|g!t_sDtM+Csa+DZ#+1y@@h*okeW-kyXiWOH zm_pjcT@=A&DoD=~yFr21d+d^4Q*_U<=GU`8`eCN$hdsAiIsI2=09`$E-miRY$wz+QXW}JjDm)TifAwok)<}8f zDT!fYKUxc@AJCjW@%9AG5gMKms*4hio)_qf8!6M*`uED3G9F+&HQMd+3F8? zu6hS}e(<`u0Pq~w6bC0s;Do4d@P7`w2mv3|PB$4+1okb#iVmYqn0pYOkfH=cgc9Gir3E z$}1mC3{!#0J|EC@L$V58lJx*tKX@^btWWs_cEV&@Y*|krSu4H9{Rpzo>>_kO`9A3W zDW4{KaII;~y2^_yP6F_w=IvH1h4Nk6)bXZczS3L7hxczHBe)P21shpG>|? z^!gRkn8NCdyZi-{GXZ94@f-f|`XPs;*Z#Wa^yTZNVM$@8=M7*<)3XR~%Ho@30fYW5 zsFMYQ>b@tvDGO$wCq5zoUccdxv@k$->?Zk08F>A+sqkia{Z&>?)@FHS)1!! z=1*uza%^wf3TwAa3VVds9?15l`S5z8>3LHGXm*W`8CYmiSPBBvLDLOhKdJy0npE9W znOR7w0s5CYUO>2;9qIXn4!C0J60>G=Z)&|GFfzj~(L^xeT=p$_tMm63(+B`s7L z9;`DJc7g}b=hkF7frTc8HG=Rlj+*a~@G4-TN!17HypkWrF8P$p=dt(BX75iQ%^Oe@ z4cKdL{ZokGvOEy8;XU;=3b$5y>2H5k6YmHCfhrx7W`^qK9+vk}?=v|@H$CqG^Zc4u zqvI*BOiv19e6$|ZDK0eIj?$IOimdioR@s@;`^~?KAhL12a@PgO3 zys8;}OkR0R@^t=Y>oL=uG=(RFm|9@8$<+q+UNVnjm)v{BXJ!dv{?JT_>1=6kU2#p2 z{tCpLQB2*q_ieC9-i#GKDzp@HbWjYHOhqPxwIY&lp=wrv)FKZt}9 zAJll)pU`>~JAYLEnB$gr-g*m{#dy~TiiS&!&QFh@uB|j4cvV!(DP>&vw)H-?bG7@5 zy@bmQfW-7hVIGM)IvD~yEL{mPuqZI_&AfFsVJB9>m=p8I_@XgI%3{ve2QCVim<&(; zq^-0VJ-Ny$WnuWXTpwFYG^R+|D>NqJrhfIcdSNGk+F-vQ+Xl5twI{ z(+Vk=X9vt9m0WYSo_j^jsNR?&Qg$A=k#A=549K&tOou!N*BgJXm?4+H4Y?tO$9d;! zq#W+GqXLdwnaw(|_8G|p#*bRt)&(!u@*ype%Rop=JY{LVZF;!GILHMBW|CC@4f_2v zrTkq>_)En6+&4?r2MH+aJnxDS3&&)L8)Z(N%?AfwOydVYkut0f(m%~v%s~7Lpy*iF92JD zpi;n=$pl+kedi3tdb6fa3+f-pd)Ir;*6t1#E<^nT{u#;Fp?{Dp9NrfoTn5GZYADvH zdDowVV!esrrl>K6yknwHgEQCk^_~_mrbt;n8dECyI+}d}j44v~#hS?avSkhAB*T%s z&#lZ*vChunzaml#l)-rd`BR}!;w~Jng8C$a(2~KOBgm4vmTSA9EJ++^NkkbufYKil zv$}h&?e{YvPZ82~T0L{}ZD&nwp!%$DL+(!$v$*@v9NXzTU~)R@>2ete^s|SO@^e<{ z_gY+<98#WSbAfy{X>AuS^B}V}UiGls8DG)vkQNIaGn%wAGD>bR{{k^p7x8+=AJRE) zef;;E=Km2fhqTTAfCqgg9t|nxUtpVmyU^8m#86y0SWLEUHjNrYLX}w;M8o-^dvI>Lwh(j=iiNd0 z632zFUhgvv3eII-!fL2{uwqnxm5$FeYrLEMc{Nd31Q1lj7gWktCN>B9Ap%io; zG1F~2q!cGmLgTT=b~tno22JiKE9F*ww*DyeL!>6=4~Kq;qPK_|^g}Kz3g_oq5hRG| z`VQJ1%V!oBiTKnX)n2?=!V4;Jd?4V@71MRkw;?yA@MP8r%Hdu+SziuPrl0H#w`%Wt z665q2i|oG_V5dV|1~QNvPd(~04K-+H3~JDPO}~Gtl)q;Qe~FmHp#>hD!=VLU&)^30 zzeCKwz%>8%puyqrKdf}z{b&Cz!>?bQrzsZC60`Cm3>bO1< z@gVThg76msB5DqZ4(S_?eMyy!$j69AA?Bh&-6OObjRmg{qBSD4Ga@w+hr@&3_4c#1 z{elsddln8s^Iw&*@G_J_`isLQmrTqTMVxqCL@oAgJ#@OIC+GXY8HH2OV+eZU6Joro z1NLD>ed||`S=FHpe6EN1ys~e1txx?aLdu!2$Ov{fL2o>aIVxWi@%eFKwOH@^%c9}Z zqhU<%`cu$12-1QvwK`r3z#}lGR);p^9eV7% z!!Vqf-=5_Y0vSfQ2!bsH!8Y$~y{mWIq3YMu^uO`RzKOm>F*2!pKYk zOi+w>z3XgH49{9PEG`LWJVarGNs$jWnDB`oE;Gx6%&it#B6cNok|tt7cpbQsBeKN7 zc;ho&A}|&=jDNa}nTx)d`hUzEi46E}m-$QF`cJpVzkTN46CS^ynJ#BOL_s(rkp~cf zv(jUhYwM%xcKo1oaArdULwFqpN_bru0-CUzBcj3Lq6r*|95{d=`$dSfG&f#=SQ=PL z$_~^RJXFD@&$pk5T4Ht(BF=o29 z0wT$AS{=#b!j0GaY=;&?vX^igY9Z*d4s?;W!*XfW->}Kg6>SAXviY zc++UD4lT$T=FiZMh4S{>q~}nMhuKk|?Q4LWW)G@w2Tk6T<+B~K3)Dgwy{bbC@}2oR zU>+$qIDo*tBC-lkLsdB6OgD4@A#l(Egg;YEbO7O7kQ-8X@&E!ThkNbh0fa%yY|??X z&u}9!{_+6AfPt{nAh5*g;o>M)8+-uaYx?~&rTkq>_)ElOA3)&JIodtt@eD37|4YPV zH;DfBpnnv5{%_kRK7jB?9sR$=HveZ`sD(qJ10+;76bT*UFyJ6796J;Vsc>j@FbVMw zK|*7P;!2gFnEtC`UQL49XBF%(Pd!`j3(bL&CqCuS9LSxNF98P-To!~Yp_D{W$_)-6 zsO;6YgA)K{kA2Effj*x&fbemONE#d#a0Wrq0fcyV%fJS9n9DSM%2CNU-@D#pwsvc< za2gyyaOR)kh7KUa3x{_H2&X}ovU z5S;m?+|U7p_ysVgNZJ=`BKLmEVFM(2IFk3d)wY4I!B<5phu%i6K)wVVKyVQbS3aJekP$JoG*b=IaKOr$~p>;;zGy`&KjslYukN;B@lZ&aPp#Q@WR=LAO1<> z#7#Hfzh2DGFTc$Shx9D+paeJ%_uAQ;(F2Y#q765nqD9f6sQ&9>hQ_KY&!D4o1p-#h0-MW0mCtf#;|yPAdQ2l{%=@hC{d5j6$q^A z(1f~t>JAuFiVj=*$Dq?7Ju#mjIt>TCMLeL>;J+wb2s#ZRKWR&%PJ_s*j;g)UvWBAd z)6x6d9h$(GQ#G~WXS>M@d^df^Ahnu&5zX+^Zi1jVqWT@UrMMQ^-)KS z3MrrZ7kNhLxBh>wnAMk+rRe_>o{q3@VQH>EJzNM{0L`Oj5?0IS{W~h|!+&>zH))I9 z5OWT6bdH!wM+Z924L;EEPiy_3kdidSp)KLxC+0IagYYkT5%H6o0Yf5T=eD@IEU@fv zvIHUkjnLwK*x3hE5sp zA$%I{?)^n;F1mZ8-f{NI(BSbN2Kes86>HGl$odyT0WP)Ag-!C)(_4P99(5lvycnbB zT4iqN9NpSiv3c3Ll1YaJcXm{X=513hQK2Mv^&aa?irUoC>AI|_HGKMN4fVDUrY5Ue z<#N;BuhJOvOLfwtbJKdATO6mUp>HOyLErSaUklx{?z2hp8o&PJF6E2ULVFI(&$;0u zRWGuG5Sohk&t-2^Fuc4#o=}E_Zs%a0GcJEPVJhF#xj^J5{$)e7mGgM_&ld0Vb}(QgGq?dlW@<}f}%O%6RZkhsfzM4BccE{w3vpDg8H=~ z+5TCg`7|$G29nElqreq9!ZTCv__9tZYOZh4=%ZG-U9iFwy#T{#s=9t1U2j4d%&Q)p z9i+46O`hbPJUv^Pj%dkVXWLSvHJcsdUBv3jZK9`aV<3&#MNc=z8YwsWKGu`@lZUN? z;Wcx{Z?TS55n4~KJVa}%Yz^?7td?o*y3y5;zU{~zNu&&YnH^g-$}_DUf9Wi$`(UE4 zOA!p|tP*WA8Go17+a6~e(W!r3+Erd(Mt>beFb2Mn%&l2F+p?)n=xyB`r3sC1{rZ8cqs}xVrn!Vu+*PQp|TZ7#b zq8vWLtPQ5rD6hi=FopvCY+#rqFarBAFlVSP^nD$(Vr$mc=r!7X_r&vXWk#H8l=pGQ zpz!aQu7Qevb$yRWI;DTZeBT^1TYDK*MFfYJY$URoWYrO*e~_+0P! zZpFRsd+l4wBC_tkHxIq#$cPy2(1mf)oBin{i3|Nbfy=B%7#9VmQRA(A|I|R~0HwQB zzBPSqr-ZE8ym+R6C+L=pVV5xd0RS@wz+7I6T~#{ZUZP}cM_lI020Mr+z4O%Y~pJAad-f6!>>mernDC6p$7Ul!ba^;wcj zkjyP7tfwHE~u|hTTn{#;%D|~r;4ro z1S@S05MZ(+O&QHgkV!_G$^Gm|(?dp@1Dr_ngdJ(n1US-sU`LuKWTZL4Ug;DGm=#Bw zlk7+Xe~B~^X(X9Mq|pk-2H6-J<#4(OJljMg>ibzp5C}Q~y8UhI&4WyhB2R%%ixVS- z$Jc>QW77KOZyGy+g@T6krUTD#(9oCBJOe>PRq5mzipR8EGcauP{D)d+RJ8OVC%b`kvfvk!c8i4D90 z8+daP_$Pya?hyMUY92+mzUF4XC8XeF>U4c?~j1>s)`GAAU{n4Kb_(QCYBuE zV_kJai~lN^Qeqb}rSWu_wzx4CLd+5;PKeR&K)#d{Dj_`~yq*XpppD1%NE;~{z)6qt z*{F|QgI1~158QL@0%tV_XxP$*JRsk@cvwWf?XQv4@)Sg}5ggMGLZKR@#DVE$vOE_o7CNHvWR*q;XL6tTCNWP9*2WI%Y)3>_qS<2ucIyc7 zAVIltZTmZzu#*$N)3k3yX z*+4v}`G|$wrfm$k5w?8`TAyvO5k?;%VgyFd;_H0kg^;U?*r_>{B+c0Zolm^Un_8Tk zB*v{L5~JRs*&y7gtVrWP4+E^=eHM*M-mHy{(z$4$unv$mN=!|YW&gUGed&BqD@`UmAx%Clq!L zT!(}JISB#5Ab%R!OxFw0T{Nn|I-4{1}zx&Qps|4W}Zw!pbP1l#~I_UPRpQQM2m!rjIy}3AI-?47X znzhgPoS)7yt?!C4%J8B;=j-$_Q?iqhkCamUpp}pibwZ%iSF}+i#kSli*kJYkC&z8= z497?`N+=ad9V|=7q7|;^KrrmF<)nf~;_-4VibbBqeokcl8r$rlm^b%h++eGg` zbGki^2~wJ%ga*7;Qeu>Gg8qCAu|QkS0>^avN)QVyB^KDUggszFjz2NrJ)5+M$zp{{ z@{y}kZIZ&$?KNSEl!WF9g$bnKF+tLV;MWEV4gisYM@*hmsI;C0NQ)bwch2n*l?Wes zC-)$$cd)=~!~(|I)`cc&AJh2S{_y21ZdLSpfyWbgkZIELHR9r-Sn2Mi?jzPaG34Z5Y5?c=%p(YJ>^+N2M2?KI(EE`hcX^zs)!rL{pH5F_6IU0gvH) zlXw_GsrZI?)@fT1IWTxru@Ox0J3_=oy#<{oUQ1WsSet}C47eH3@?6U9{@D^Mu`L-q z#+zO_gh5oEpwrh}t~)^=Y_{g52Ii9U+Tlt%5{?wSsAC|}sC4?=%XR1j22v#!RvZR@ zJ8``C_iB;R5JK5tEB(S0u>Xle7%Sh*wvX0i zcYp?)))#^G3%GD3vtQxiapR@q3Xj3D^^0}=Av;vu@~-(Uws1QVAAU(HmNE`$#_06?_(!k@?>1|Sx#{!LZ95I*22 zgc;(DAQ8Mt%lHd`ZB5=wP{LAhM;ybrXp0BJcp|uR8!|8?VlFV>FG84kFnJIA0YL!Y zh9E(5yrzLj;7j+~78`Yfuk#sSXQ#-*JoEvD{IYms1M@F~niJbJ2*MHMFe-9@FIkpX z0L=Se*e2WOxcn;~Cj-2pmf%_*ZIk%`XuAm$27JIoZ$_@mCm}$v5#Q`dX({_F0@r`m zV0%(*W3QzXaf=JXp*&Hr3}sYb1}-8&;N>v3y8paLKqiFTOvTQ?Dj_Q?fm{N!Fes}8 zCkQxj^QJPDLu7=6zlRw8lT7eMh6!rLg}gW1Ts*$>ct5OHmab&-eqb)OG0@b zwYVkCi>@vg*@_*#;6^dN4eAK6k`ya+!GyKXu$h$I+OQd1HCF&-q&Cr4ISGLWq<~2% zv5C-&b0m`KyD*zXqYBQtA4MG`Q|x6k^~hmS{!)CBuk$L3 zmNq6vAU6)T$s3y?0OaDVAD$(g%Ek=F)%2(X^h+Q&!_R(#JOft)Am$gOMaacn4Y&+} zYilVP>xg6*IKK<5v6<_A~aDkLUI?5P=xC3 zWY!NVMnF1@Z|R_F>mT8p+6=iNwh&5D*&jd?lM$FKsxr9iKf)5Y>%YHTYU zK*9ssfD(!Plps*TeZEoKgMH`WpY1zH9)V7*8k-QZG`E2?1#)OdO=PEMPGe`j*Nhnw z3vSCDHAyr53mu0DoXE<{6!i%!e-ht$1=aA#_)2P55;gogqWM4=-@ifEheO*N41@petfIK$mFAp{R%3yymxh`~^7CwnHv zMlbGN^E?1_)BM|*&SRKvZnxxHM@m8i>M@4WCK}(yO^99Z3^Z`ZCqmEp073V_I4>5! z5QuT~{2MDcHS)O~nv4pZ6^Xrhj2n0F;$vXCFwX-BQ1mQ8gV31RwFSmSF&>Regvz^m z&OeAY@}urs*`uhjB=5vUo!ha3Q9-5=kBMjry_6sKM@nMGE{Iq*xC0>s)Sfyu2`v$d zMxdT$u`q%bqk@;noqrH)<+qXt;uO8=p57J?wk^S#EAh!eTmJTr`b$8(YHa#+id=q)or)h7I_v9a(TE^ZZ=~(N8R{A&1S-ze-|>GD)V?45jJ@oho~iyt`nrh zkwYWZ#6$Tr;K^JGFex~90{j@)KHLc~k3S4$eR#V8MWI344MeVi2IS2(u*dS|8c1+6 zCGK1U87agy6iabjO9NgZjT~(^5IyFh0K!@1w>Uh`HF&&+$TfJvB+fO+P{W;}6M}PR z=*Nbr$&kaApDRVwf+|zgnsf462dRMr%G~sV8mo!6;kKa0DT;;q*d_KEUL}i1Ynbf> zJ(J8h{5jhmj*xMX4F+ciPR79=7G)g7u={~`av|fWCNqvqPR3COoasPj9MznR!x1tL zNHg0G)}l4yT_u+$9M-G3GbBtsgj^hY#?%8c4kknF{L)`gk0W>`cfvjh*g;v`U;sI_ zPm_)_2W#$-sgF_vo{$*|3D6-G#}$lfVgs|pIx>`l>F>%8M6SFpGV}`~9{`k_eF*KV za&`<+!x*9Y1^Zytb8mHmbVLSu_ zfrrTdYK;?N6MbG6!VNJB>!2JKk!I0KO+ISf&!@dPTIYw*NKBGb3`{O4l5XVW1Si8-Z{Ck2$~7@2uh%Pa=#tu9u7JvkaTZG(mgN^ z9JMgVj8kwUncSs>2oJl}RMZJ5iCF1Oc444*4jZlJ$m^ZqS@M|5+ki$mEuw&9{60f7 zQ=$iLZD=y$ns_?mLNHefS*r^=sM9w#pVf&J2>j#J&nsjJu9iK!RbkIg&2qH(w@`i9i zdQJ!@tQJEJWJWfKQzMe0(F%)(%$L(>MMx9qfwD9ixIn`#YqXt;WasrG0#fdlHC7al zAAO5NKnln{xCq}Ba2IWaP4vOXss?MGr`7t8WK1=K@&}s;v~_U#gY`3DrbA*hltehi z<2hsj9T;fnVeJe=P3XWBK{g4ek-l&x9))99B21QhyXPOtSlOI~?T*~;@#L5$(AS_7 zHH05=7@w#lk-76$l7tg|Ba}Fk9JE96FRQyG0DBhhT0g|q1&{9#DG_#vfrcBdB(dPU zdp(2=a95Jp&Uw!I5#Ic}kl{Ul9uFhJCXeIb9SWptPz`oycDIe=$=nGrDL7Zx+H;6g z2)zCYQ%QH8hFh6LwLfB#~-8B*5}A-f?$!p=iwGwf3Y;U4wv z<}%qx8qiG+rW?Izd>b|t%%WNV^ja*t;+q^?ve!d)p|&oPhEfCPf{0{gBKp0JNIp5H zGYGpxv5^v4JQl-j*F5n)DP$bA#9lpQ9McpF?Z}LyjC3F1LH4jVkVO!~mH_X#L&kx( z_#oqO#6d6~G7dGlNE$oi;GB$ToF-Oi2N_3d8Bh;?7O2M!b>66`#^wcKQg zoj-?r%L=Gx+MGf=lo)VP4+-ob>fr*AbEr3YV;Ki)?vNQYM5YN)N|m>i0tTGs8wb;Y z)B@8ckL*C?LZXdIUl2J5P#*Rnw9nngL}>D|521SQq#dLq@Ex>2PUw9I8B1Wl4_gSN z*lFL6Cb9htwh2*}J0~VAfrrTdYK;?N6M>ch$65d=cGsF?nmpA7;YZwE>zpCF)`Sxc z@Jcofnshw7p&q>wgsFoGa&|*kLLx~*K^EUm?q{I&gWaczt!?sn{y)<8VBfKsP}oWa z02JkL*KkKkGCEDKgmUFUsX;g-`=qgu@+7AXB@a5lLPivhL*T=gctG?s03!K*+t;yU zIivOn5nuUK|{>O7+oxR(Pc+KJ5!DoCxlXn_DZNeTNU*c8S5^1)d-Whu*?G zVMCjkhleh>dt>qC8^;W9RN^NyU@TC{+ilT1G#Is>1Oasy;4@F#j50jwIgAcS(iLP{ zZh-|rg%Wv!(Gk?w09Lx)s8k<_{J1Ton?FR-rr@&SM&%JCIB_(Rgo0xf^cE%ZL9}Cs zAKbr<#vn(ub7?`#N4bHGJEOz>ojx@w6#3oCXACF&%L`a|sHdX_N-fTu?rUJ5Yh()) zGDsj2NmMmpB%KE4LFEY{xlL0FjT{jbr+CDB&GXq%#K3PXFcjBHhJpf;h^_*=mRm%d zPlIzT7>fu5gvCN>TT1~f{N*iLFjno2%EMT-NTAM+peBG4Rqq%|8@ml-+8dPW3Q(mM zxipkG%pN{4&jx#*d2p8XB^2Oagl=Gk3qT-sB5!L)nBBAS=$3d}U>5_DBmYuElE;HR z-?>FI1reRW`rHU5f`5S$LZ-EKRlCu1IzbEQ=MQjDrne)g9oYaBdK?=V5_0lER1p#@ zM39GgI;s&xOcNFeL9WKAbwgQ%_=F;4eHd~yCt-atg!KXBq~NHtiUr5N(I5sy8_RgW zS6nM3AB?}+>X~;hgn2*>vV+Xdj+5xop4-g@w{K}=xY0B4O!K4hZO9JhNAKODPe}{` z1B_VNd4QM;sCm(yTN)Upf*Wp$Ay`4s44Cw`Koa4Zyw6aLP^E2M3T@HZTN+c4(&5>q z_}P+N7wX=3>nVv>ag(9*fC>ix?#j*|sv3k|AiY0|oOX^_ZCqps!14jZBK9T&!Eag* zrx?gp;8P4A2u;B$22xzCD*P;LXEz=0c0bY9ak2^-S%}dTLIp^&{kJqq*AtQEAUo2K zav_In<~ZC{<^dJL;YzT>0qckCP-T2LM5KH#2xTR2RO4W1Cqrthy{vW8^8(3p*v>ZE ztKy|%Ef9kupTmPk0>=Oj(leSnd=jJ+3M6e2Ca|S_kj|DJ^|!F>IM}dX zSDHY+-rLgsLrH^B0$>V#=ESQ=Rb241m-!9_RNiGGlVlGm&K?p%IXNOaM}S8}=hZp5 z>5;e{Oz%_6aH3~4bP$y>5*^NSmDz0p%?BfIa-e6_Aa5!=*a{OZV|;KTmVS$8=_vBz zm1`w{?Z+b+h;W1L2HQSc@*o0BZ2J)flIuy-mk|cm>Y0J&L;@+u$P)rVEU)P}nN7rU z)Acx(LjcNd5V}MJpu}Jz00mh6vYxUOOcqtf4TNdHui(Da&T15HK%iwrxGCU-o4^7| zc`VQddu4XGkpo8p6GY+0ffH^pKse?je28D$5lEs=(R#u$218+JPe5@OR``!0$4BV! zh*;af%md1VQD2p3tdkPo7r9Q&>qGX8tq*4sUsxYx66{5`cs7@`(iDzZG(H3W|)UutHKdD0#!W*^hDE@(55Od8_Hz z`;QlnlQ+`sAd_h5I9Whu5<~<78`w{f6H4BQ0FUM&A4Hi1eh?>bggql7!6RZKAsl&- zJr8AlL%BAvyUPAsRN%!!?v5&q8Z&|1>tT3GzBvxGP6DeM7kAZH|iwKfErgTYV<#3oMY)x{T>6YRqdxu}_m z;leF1l8WJXxp*4fk08?sMZ~XI9>~y$Gy)!!%<^W*c`oBHFNxX+L!9 zC+bs_QDz4_8f^s4fQTVX2gphXl1L43BLpwnd5&Jo8JoU#ao>K*8(+TV&;dxHW| zS46SviU_DH%v(rt$hv|p4pu2qIiW+tfHE${^w^~s-~|HWQY?sFih+P=2|%JyAS!f& zgwO)ntihN{P7@D12Y8xzPz$kYD0RsK4XNc1PJ@CInuR#W;YrWNrK%mLRE;|EUFW6Y zL>qewu|o%zBiN|$#ZH)5p*eReC^3rp>5>M6-jqk7*VHMndL)_s+0=e|sAn(3+_Nu% z+FwRx(pS%;YfPrHx)dn%5<6CZ+g?T>tFMB}=;>{L!RjyZV|Fwtu=<-?DU1uOlNEj% zp8fqLLd;LClv22x$Lg%3_O%j(N`Ol1~? zQuogX zzaN#^r{Lb#6k8$0s(aDOS`oqOVGT3T9X?|8uwlbS4a?9AHmxl-Sd%z@*suq0hYf@O z4Lh`7!O?PugT-z`Cx?BudmZHu+3fdtpObad*koiy(rOW_n9RQZJ8_q0*-t;sAGUOC z+0Ci-M#V8!`PbHK8;u_!qIuswY}9El(QRr$=kD&^k!_sreNaPu_r+w_=*IF{O)2k- zUTAc0Ge6vSjCPn&mJmwmt@Sr9$~)ZAc&x}Sy{$$`gVNp6Sh-5yPqX!ob^*Tk@RePUuU=7({eOygp zs7O+JS_=F$`f29Whmy<}l4^O(rfw$lHl_cJBomb1DNX6PPG#Ksk(o#BXZkm>`j1h2 zV=28QEGAPZo&H!-h|;LRDlw*X@@rgXG%7HvWBZ@1F4AYwG&C-&u?(s749NnhcJ?bgc;T}fQq#pC+XN;v!?NF(AdDZ%o z5#v|u+4``}wy|4XqBVm3(cM$&<;_@&s{Kk!laC+di<|Aos=>Z~r^!I$bp^K#Y!ikr*cs@MSz_ zd>(feT`!`~<33$ik!XGHS>-9vlYiCMWf#?+I-z`Y(`tMu+vq-d3deqWV9=5f(Qo%Yxy2+0a09r1Q=Hi-(jE1IQoSn~SFk7`tj?rbvBr0z!XhPaOBn9gX9>F{w($4e4kSL%}J)_v?Z+SBOMbuY;Y z{gD-``7~sDHvE0-e-(-Rz8CEcWrNL!u%z}Bdul0R5ZStlU>3wxH^Z-Gf2u^EZ{N)i zt4X$d&0)BGoG`VxKk~!sF&b7q8#4SRdlr7WenN7|-?#o(kw~MM{*gc=$1#(ye)5u> z-;@9M<^OLC(paIbe;`I>pI}qjS3lYGEf zsf0Mu4IYF)4EO9fBB}PzeVp2VIB{^1Q0G#mLV<#@r+W&m_m~SaH-zTf+WFYsvxT`&>VHPD>5tZ^a+SPD?$;-&*ll<?xbaG~%sT`C4H zhxpIAR193~`KP&53|y@EV-8jfTz2uRAFLR-nDXa3R}5S>@o#soATE2mqPtl_YAPw$ z8yXwTKc9=ZeT(u;ga^1xqlM519 z=uc1k_pQ_aNPZuyOkp^!E_eeEZT>V)FLYII=<|;Ab^U6_x#o^F{qx~}4mJH#jdLHJ ze<+u#U2tnd`>h`tiNE!hJPM|+%kE8q|LJ7+20aR%F>~+9L#HD2uTwr3^n7YAaS3G# zu{)i^aHkWRo1A|H;1hH@oh&VEEEL#}5e?CUK?`UzMh+V`NpjdQ(ZP@5hkr!<(B`dr zb|s1v(_4*&lM_B)+9(}q`1D+vtxfTCdzFqgx{sco7{_;UePzk3Y5YG-d^;xPhj%t7 zcWgT<_U>lilK0E@PklwbXZ-f$ydbOKIb{aZm6y)!RBaWfbw_fxZWjeDH(qxg)?3&y863mhJ?bHyGdtGFd9PZvKh@LqA=%}zB!UNb}cM%*cf z29J@F7cM@Wbm^3bON3$F4a?Rr^*)7L4_=H|_VmuKqw;=|V>0hQ5YE{6_{_OYL5!`6 zVa>|EQ8LM^roLo4SgmgxJ9*xwp6g!QBpx-H^|n7gs?{5-jz7BAZ}XVz^s^GC{-FW=8!bbZX(gBNB@&V9Rafxk#p z*4ZE0q~u2)S#xQc?Bp3sd^0De9QpX+z^u6;`yNY-u#SD8Y%HHQd-Me-KHp6*=(C<1 zs5`z4x}=fj+B*gQ`&iv}#{UI1MAg;dbC0-ayV$wIS9|Fv6wuPueS6%SrNLHZ_=qn z8&7-}F?;mbVOCmQn+&wdukPG4;^1246G9^%2}*sgt=^DX&RD)~{E``V{5u4aGL)Mf zc62oy3}4^9Z(Q#L`ZI0*mK}#JjcD7p)G%kAD2-TkE$zt9>&h(deR?M?vSF_43!zaz zwoTh;a=LY_GvB4dcV4YHo&3v{;froaS?nnbpCR|E&{FD-+dM55A%jbcu6x-yY&oHI z{HHzRb+*jAqSU7S;nn^nV=s?QJGSYk#ZDBN(v1~2y;gP$R7JLm%=5kBzSCr3ui^Pb7vm&8aQ{mSg`{RRF9UaTuGHvHxDIjR3i8hymrkx6HqG&-#SMi|`;Uw;4&6B6BmdHoW}Qa93XZ+$+CN@8U~xZs z!VTkHqnUYgu2wD-Jap$^;-y?A-GoxDjmtVL)|xF6d61k{8`pmO&aHO=&Tp@dzM8vl znT^`72HQqSn_CwaO^)I_zw#Fmg{^1Ttx4a~>R!{h#G~Q+k0J%Bwbp69%*v+V{J=A3 z+;fCoN(|iPOeTh3KNr`sc#2@s(v~f|mY#ULYvQqWmlw}{*&n$pNv7TTc(GZBXWGn$ z#wE9kdmn^sSrg}Laemz1*3$}ZGjlGSDA4h8*bp)?&$C-!LnQmHg z)3-h0aJbJqp;W2GJ4NrGe0*&46}M>t_iPq_K6<3X&SL9U`S#Q!V$}6nvVsqn{<>B3 zQRmNV1RBEbNlk5BRlG?(^`U-_U}t7h$2?lE*-}xZwD%7M`T34+xcFr18Nmq$EY0kf zmmNLwaAmZ}#}x+4PVMuVZGKx?(SOC=vYQ(pwAAxk`O()HSYD73_Wl_CvZ|o^jl@ke zCGmiSh@>|QbEmDUK7Vh=#(L|u3*^REH%t5JoHjLCQ?kWdit_2ZDgGv{seUg0qI`4p#I1+hzd*;+}4ADrt94v!ZnJL@6(XJ?jeVOHN#gk2|w*nJLr$ zoZqygd?g12g6{3tdA{If$ibD3Odt1x{>zz0 zU>~b5clq}l5}X^i@9axSX-!uNUF%Swb2Q}gzQoP*#>N~z`-_ZI<{SBE=88#5FCy<7 z1sGXA+jw~QnDor@*}iI{yAt=locWW1-s$eQZ*{e2V+i?vpUM_qOs|wwmMm!sSw=}@%lgJ^WNXGg#wVpwwr_;qXDB23 zeee0_dHy)pb=|*no##IHInT+ZupAMk`TRLR3b7jGZ)Cp(C6+f<#nu=1*N92ogQpBS)=Ht~MHkrt zkg{w(up~yV7+M6uS7~OFbkf}_k94J@t8=HzQwEg#b&+I4xCMWiz!!XpqTAuq$>v}yE>UAZ5$QFBYilNh)g{b(cS5)cf`r~tCeRYdwn803`g7hlN2M9 z1|J{uF>EWCz|Ds-(~4$#x6vmpsE_hm7p}yJogL`*> z;^2VxsYr*j#tI2C+M#`0rX?$8d(3G_8ar$3pixtSoVNbVVO?FgSm1B>eRka}foB9f zbA4;ps!46WMb8%rcsWm;j>rB{b=&oRU8s*n(Ls)>O6U|E<^CoiEKcA_^g`^^BQI|m zv^C=)nq>q|Y%Unhe@w0M%h|h|`kFkokjRW|yKTRhQ+;D%kEiP5Q`~#oB(?s$X9gUz z&;9?-+-^CaRoeR4622f8jqcS z29nBvskS)Sju`Ej$TAbz*XK7|GN&56ai2i?;I7+Ogipq0$ zUem<*Sm8aVa?-k8yX`+6 zdb+#Mu6F|AfN=k!rgeX6b({8)ihn-$CgC)Nl-nkv_}`NwCKz{-oYPTcF<6l&8b1C59m zgCc`zay`9$Dvy$tv4}z~qD}CA-I=B)v^}gY9o}s{@a;xO?z#SPDQdSrFA!wCcmep zi-y!ouBR<}cKSVC!rXaIUSNFoZfouSn)H6%M`dtx#=;kHBM@+7%gVA5NFZIr5C|8! zUc@D|p!qe#8`uUWZ*@N+WX2*RUOy6&tmUgn`lO;Yt?ZLTJ}{|T9z2cFgS$YP?m90E z_D6~&p*`uGmMagX;-8;PIHaQ%+j^lrUXicG0x>O@NiP1{wSAv~ddfkZmWMwyHU5NT zZJh6u7aGc;9J;6f&QOcY#;JV@qm25{`kOU6b^K*`iOV0ZvOm+ zx)~!yvdmdX9we~-o*Y%;66|t2Ve1Jq(uK=fD&gTdwH-pmv)3q(W3r4jr9Y7*Wd2g< zN<0t##-C5s&b~3`6v#xxnO;%TxFml)^p@ruOFLwP_Qc$<`~!&jCZf%Ou2{CZ6RT@{ zftC=QGSaz|R+5o6*Ue5MFEYB9IK@j)zOai!0%(DfEPl0@X8lj>t-#DvB$!R|uEVI| z*7R32l++@>r8yrz48*%R^9Q3!=q%vRBxGfy2w1eHIU)&oe=OeL#r850>*vgMj7P9B zxdNrZ_r}eiF#xR#3G2UJC?3&q%5nr7?n&_& zHjeqvL#Xs>nc>Iz!_OYCKY`#0Tdjrh&LeobE0M1+IC%t_uU8^pEkAkCe+v0r!(?C~`c%^z(I2bOdieT8$%E6ISEtI4v}tKBu>7rw1BFUG KcSgS9cK;g!lrVC=qf?h$*Rbk;>8*A(c?k&HXal zeGw9++(zz~klcrv`G3y&erK4;v)ew;?(;mq=fAtJ{qFRg@AsU~d4DeN&*yW_WT-cM z#OPtehK(BbR6oS*e913DTfP}K?9+&0!^Gk4))n@4&X#u07RGM-EuG9258Cd#^OL^a z;{~F}x;0i-&)5CV+<4Q<#}N;+C89fq6&%!7m{RijXIhEtxVbTM(_?-Vm%pUa>Jj>M zl0kys+P4$es0E+ipgdlv`1L$n$>g38TBQHXtD}B6;vnI4Z^gKPN;`GB+jXDd`85$| z^C@fBTKbJKtW`ISHC9|K+N-Q^{e+{C@K4=OJ{(oJ;%BvU@>Y=zXKrqOl=ZaQGTXmf z>)XlWGTXPkyYKi-xs6&J!1=jhf_oU~)|S&2NN#)Yn?c*L`y$!!>l>tI+|I ze0oNXxmEr4S3luwrMjT^mI31P%r`ZR3zRn*lenvTxOc?l@0I5?y}kX7tst|1{kr>G zSE-D3>}bst>-DT+xqJHLMhdQR*mKTKqbv8JzuAiAonphK&jbthG<$vsFt=D+!`gdz zj8U%bPd6S^sJDrY>0z6*LLMckb?)<-(U^TrW88a2GaJ1a#q{MlK(AMX$wZ#qao!+;@h6!_@QAAJPx$tQHlLg-`Z#}fKy6>{x zno(D8q)xwHHfOQsFSG2V;{C2YJ=)TG^4#+8{Pqf-b@*7fC%Y*}-LKJaW7m}L6mCr( zFOZ#kBKMbU)?Nn@IpL8fWCR!Pzy4it?QZ5e8Qtj2bpI_A*8Dos{d`ZjOM-^}&+=!- zXBlMg)t;AE*x-BMm$Mx)v8~RG%)_-l(FwWBi&JJtF~5JkWS`wu`-bz)+asp$G40Qq zyKCLllSkYNTSJbU)LxY{d{t-uLs4qK#?8<*udaqCgjk6gMX#^SHl?{tDKQtS%R8f| zoybm}a`~9IjO!Mmo&5`6%c{IOG>n7Dm#7T~L=NubLiXhYLc{|@A?q{i-VX@bWI%TE z;Ky9;9c^~l+uI;d-~es?WPzwoD|7U{Zqoy%y7SIE%{yYYwR^bF!-RGF)>^69GP^fP zt(h|Fs$kgD+wU&DSksi#z0}uWU7=uHxSXzNz5d$ef4?!U$(8(T{w2N{z~8ac73VWQL5R6nNd00T<4lt_RcCO9o{Hx zaPPtB*SSATzdWy!nzo{(Yox_d)id?Ix<0c)kH1u!d}Y}#fz{@_q|X&qndm)tDu3q0 z2vZ+>YwLF+r+=t$*6z!lNBNX?vbRU#Wz~fR7BiYNXMCPiy_m5w=SB1+x3;QA>3o&U==$KK}Z!Ve)+=hfVzAS^UcP2+yC&EaK8L9YX8c4~^cDJD0r{i!|AXkP3(X)60km{+HH?=5>ev$BuE>^ebbvJBWgw^~_Y?7mj^6IP2Pg;k?M zWt7>oK0OJ`V83x?H}^@?`uwSVwEi3#^HUxBa}~vt&9v}pV+i&)ys+@>HlX%qQ`ntK z)ZQw4c0(V9Rr`X*_z*^87u@Q9B0^1QR<*<~U$=0%DZ`zGxWa|NrPDecvMv53l`unJn)y)W1- zgT5+zdzJ&WKPQZxP3v!`_B4x7`|FA*l@vBhgvQRMdazf}`kqNs`-<2gRKp1hyOzTK z;L=5%&s3o?TiGAG*)#jA*gbu8R__UEYR?H;|C=W1?pF56=fQbOc}f=S>ojICAmsAM zfE~lG%%iiP#AWmu)WoqfLcB8iYUr$-zA7q+($4O0SMus+Qu=ExSf4Jkn@&*s=oxG# z2y3y8y=gL_eF8v|hSjvP{ae|ceU!AP%0BC{U2U*v%4j!{Y(S43$?5-n9aD=+UQE_0f<_Z*c}YEM>?~a*57kcn$^Sh zVhU!_D1Gj)SWGQ;n8-5CiEP%7{r-Z-q+e303)po>nGKJWXzShBHeIf?-fVkTmp!Zh z35{8q*Bb2AUq|onpkJQ7tG(*R^?JtnNrv_cd@3~?M}C;%_66M z&{PubUd2k>ZS6DObcW*Fx^B~}Q?>K6>SkA#|JuHB=k-^U9qwt;%11Ygp=U2RE?TQ= z9WZ|KYrBa>r%S)DQk<*uuEOEMTd|6@q9j{P@7C&{R?!IyT z$1?MFde{Y>qAhx4aoLxCxpZI9N9SzZ`ylCEXz-2KyRTYxw(pKs3BD1jtal@)atDm68+dyfAFb`oQFNvXxV%CL7SaCbQSR|$635B-;#b9N8$?0W^7_$?!C zC8WcGEnk7CRqeYc{V`D^C9(33`^kR6RnT~C zUCu&#bJFuru5hZUAn9g0G80C zx@8Vnf-+cwTU(LBqWH~o=1WKxIo(@_u=U!e&<@xxT7n*eyZ6^!Mt4K;UHSMe5@4a- zP7f52%D_UKc0agXxO)p&XlY)~eJilgPPYfQgLCe047SV%3#F)JM}WL<>vHbfDQD~2 z2CW2nnWYM+LEfz(Z_0axAqE9I_`&+V!es@;mQVJ6H^30y)@9yDhHyh7I|9)4QVd!N z=-vTz%K+UPmU&K(z0HACuyP4lTf$RXd@rnGh@tRY;= zSv>eyxZ^!UG4;G>_fZsMy50K-@#2{yEyZb%hsQyhS^6B4{K=6L} zua&ITO8{~d6y~oB0>p=0!CKp(6|jQO&8ntj{UlBu(DV;-YO7O_jo&gB){vc8XQjH> zbZ&94x@qn+`h$?d-Krph0zLFv%`2;`R(0)Gswy-q)#x{lR`E%jGc@*OUwyBgpIi6d z(ax*Dabs%DD?5jKhdjn!T=C>s#Fe}!HKpHO44ABV;`r&)H6>2TQ%n`dHy_%jShqVl zq|j0Ip&1&wpyrh`8roS^rJ&||WcJmD${oF3rHUsKgjcGCC1xkTSCox6A8RX##5<_E zcpDOLTkf;4_>hpfC$5J`iPOK8I}tPGzT@M-)SlF!qUXOpa#YAp?j1K}13gT3M|@c0 zO&Mv5(PuZ+?JZK{oMMA2PBEtC>FjO^-d~$h*3YVmS9RPIv82v=UY=@|hq`!rvi-Lq zeFqlp-BuvuI_EOH5FU+QaBV56+uq)D>GR7e8r@@>RZaAM+2rZJCxX(gKg^kKH!|18 zw>nqnXzrVFw>QzNF4e#C6c;T^48CHNapQPyU)BD|;Auy;b!vpJ-C1{&(fjf=?S$K% z3#EZ;UMHJ|9{(8U>2ESquUkLKnXbrEtc}-qG>KSOXYIBliPojD?c}mDl}81hslDkr zHrHU52$*G^In45Fp{MwIn1xRNX;y4@id~z>tbNl*9@z43(^I?T;^kW`FJ3aIt)BTX z`?aD`YF2T2@$$8H7t_m59F|fR4M^SBBIn$_zD)mq>cm0@>* zZb|K)QF(mK(-BHiX`?^Pm!ujPT^OyjC{1Ld%DU-62QO7_lCV$iNxgjG>A@{ko;^w1 zzxn>x?3r;h-CEa`&&tY{YkiVAM%;J%wjj3&IUal3=QwP8>vozhvwisYud=n{X1Zs; z8L2Cm{<1@Yw)*kN9nlw~w^?=u-5T>#mAkNedPdOnE{Rzl_e{mC?2|Wo=$&nzU*E+r z^)B6duH~8a%8K+F-PZZ48HwTaCL1Add#%TkwizD_7c{mZN4+Ask?1a&86fqKIJf`FHIm5jmg*= zTS&jKlPa7-1L@fk*QxM&kA3oMs@_@l{CYM>Kg{ghu;aI5!e(0r=<@Eya`b4vH z-@)tQk7{(sD5@$ag-gNfj{CKi!Rto^FUo5qRrgeQd)ypCf!0Vy=wG7ehqc6%EB~=@K@Q#7klO79fN3YK}i{1C( z!jogdjgMhT!jdD7BS1fK0NoC2KQ65M1lDfTg8+Iy+lxhY82CpEfL z6;%%;g{#42pZ9CIBUwc*%6o#WAG}#e)~5nOJ76+xj;zO#td-v5z6V)nb`iRtd=GU0 zR6q+oxYjIoUFC%pCxv64f>h%qeNKW@iye~hpVS*Gs~9B?NEw)k&V|`UpZSN)%X?`% zeb*_^`QOMX&YiF`e&+2;(n{Q)ftn>GXPt)EtsIg!p4K}%U$I^SUN^`feSU(j8J!p1L9Rd2HMpr{owJRyy0|Dxw#XvGiUzBG8pjF;17(fEv$Xr>>T!5|nxmHJB#>$5MS1b$YQt)8 zx%;5}Uj??K*Zn~G)fb+e7jFC&V3v^_aRG4B`OH!NE>QjjVckqnzI-p~P21pg-%No_ z^!jD9*uv@yI|GDMG67~;$?E~|`a#F!*8zHG4HWBTVM*a;=L}&<)3XR~$`Y7l34{J5 zteXXc>b)nuDGO$wCpjVzUcc^`yf9F2>?Xx1Ie7h+ndlGj`m3y(tRECr&62}oVM!T| zT0f#CDR8`L3#{ELIs747dl1K)=ELhrX6MWhpxHIL=3t@8;i(8vM=f`F{fH7+XmWK= zjW-LHH0q^*&~8}LW3Gk12MewB9=8azv;%w7ndI>22v8@jb7=O37v%#0&{}V~2LR|x zf$iw^900WT!jntFjW1zIizG)}Mu4_+0No91zbveq18cv<1r%QQ%@N2%uNMQLwHI~< z3#a4&pemBrgAt%k$*+U;&e|*1tH6>f%+BpcfabCS`!zH5r|${@3w2bStBNdi4{4#Q z@L-*ps53lxF1IGj87wq8yb*+tb<%o=gjWL#O|ITw=biE(Zpo)y0na_RfAIPA(V_uG z(ZD?xHa~_6FUtcl8{X4iqi}1Tm+|%&4atsB5UA2Ad1jbi?jc2A%|6qk46}2dFwZY} zHM(Aks*L1t=0}?`Jx*FonCAlpJCfjX$?@Tyca9uZv|0{gj<+JjtY6+|I(&q=p*Os~ z`Bly6ql&6yQl<+w+l-m!tR*@b#MB0(O{q4l_m+DYx8&|C0dp%5^Sfq3OcyH)n~JN# zj8`D$jAGixJ#RzA%=3M_;z!D)M2PvliCGZQ6ewoyw90vlB5Enr}e!&q#?7h51DznDU;xt%q;oA2aMy z@p9hjQ?^aYU$RHXWHF5S$T!vsjd`Zt-4e#+UlUWl)ANE%g#5VtjJL~?y!T8e=scv( zj(a(O`d5h56ew!$r0u+N20-Fde@Yu5(e{n4u^wLITYpLiU>41va1vk^5Hknz&*I1F z4++}qc_DcD8XeHGnE83%=hmA<^I3r@3%?G#AqDM<>p+ywBPVGNJnG~Xvr8lNq|};; zFu5j>?<*b?Vag9FW!l2T!-hP%98#WG6K&@lp?qEgDJEQoPeC^jNqvQWhqPG;K;3K4 zBD3TL^UoJ^cHYZ>N#}pQasG2U|F`?lUn1s^w)r3Mpx;4rNHPC>+x**wexGuN3{!ua zZ3=Lybr20D3_(M-Lo%ZPml+3%DZ!LE;foqw_Nort7GT2VND|c1|4^v30$#-CUi% zVsFthLm)BzQJ6>Kk4%OD4@*};3@i=|d?Rn2ZTRt3Fy_SkF@9)Fv9j1R^+Agwq$b0Y zKkBF~Mo+GCPF)zWHP_e93XLgN_6m)OxT#-rt$z4%pf*_i7@**{BgC35GUbhgqppfJ z+X!nrub46U){+@IiSjd2zD{~16Oaz1AGSw)?NCZH2cHxLY@Hq~46bWf?X>~9O2@XL*B13Vd#!yWEyJB8>5B-DH&_9@Vrv5DS z51JnPwm|JSx|Zv>qAW=gXGugEJb=<4 z60^E{t=+dXAWsp|ab7)h@+}uF9iaNGuS4!n6tlSd;2gW@+hKAB>gn9^WEnjBJ|6bqqz4Otym9`hixHh%SR+8Mv2-61U&I%afPRb-UBVEzSSsxRXAj6bAv z-1_+MH_iVeVh(AW{{avBop>~)n16w7{_R4)OE^P@sXr~ci*bo{5D6{&_Dd3S88H+u zig9^ykeI87AfdBEkkC{vRSybCE+dBG%E4lCY_n<9AQGy~Ixij}2;GCT({)6kdr&N@ z-H|jdV)c68X;5%3^A^=W-GddQ@~d=xr>V|x4;O828l~N_9E$oeGcb=7j+_hu9+s|g z4n2wZS94MPk&#ecp8Zir1iA;sqN_TR7DlYj^_^yg#uU>)-Gdbq^Q*F8Od0oZF&J}I z$8sp(#~^NkvTezck-)&PcoAUWVo|(Pux@_%5h!hCM&%EO-iNY}s0Q>tzEXOkhYqEn z%ZQoo(;=lejuINr-FCyFdoXBne|Z`A>NE96pdTVLF@HGpLzI2QG@u`Heo=%V&x#;H z%rJ1&=~zCqxJb;m{)o=vAEdmY0>=je{#-HLc7GjmLkdr3ouC}vwUhPbAZ7Z?&v38y zsV6bcc(KUgTOm$5#A6@>x$)E^zSB^HX2zff&F|^=PnGhwEa5K^lQ^`%r*k;8!0#En zVE%WA`4^bx-ySqL9R7!uj(ePc*wOzxZ1aEBg(%jdh+a3_qRoD?vh<%kh%fNY@T!h$ zBM}b*FD;085h$kNi0F{9;pmrC$&7l0XcS^DD%3s0s?k{R`XE{(LOU}`3voC+=u_`7 zTgN{HQMp&)5H$b0G8SHfQpjL&g!Gb$`QnHZkBMo-ovDXTx9sG6e>kIX5_$~5k9|W; zR&~HWthitO>M^T2bb!zG5uaD~?W*;yKS@YA6BZfC=_crphcQRxiz7ZiCaMwVQ-4W3 zLUuHa=~I6a`Ub(;Fs63LOCfj!#?g0upY2*VMKcZ#bD;~d!L+3g(85@R+X`ohu z(LgH!!DfK6qw(4uY2zaHtoIF_3v-JiSz+!O?r^wbkt}*-&~i8}Z4g|iLkFsUeJyU` zjaB={Wt>eja1)%c z9E>+U(d#|%#p}||8|+b#I65yd;HsH{ypLG3!3S25kM4#BNBN4 z0XQoocDarLs&2;*ItOPyL@nI_T9H-rpGA_boz3({U;Fh15FAT{=f{$1_ z6x@M}A|#>Uj{Q+b2{H7zRUIh{BTRCAw?PXb#ak>LwGi~U2M~_I0R&jQFz`bH=Kz8g zY>qdL*6z@ToMHY9oj53OzfO8C<#?JO@!hrtxM}vF`gYLdOm)Pe2tP8bpDRh8@%7!ALqg)0YWQAjgA|W*{tqvw3 z!68U!>`+{(HWbtUu9#Pnq4rq?`^!_$)cZkmpyaV{IWz}yC*@1Q0R-0t5h^Gp5tea> z0|;t+bnM{-K-nYTa#WztCk`NdoFbMEhXq_fP;>wxfzvXug&pQHE#GofGS2s@_nfWM z8X}qw2M}BYXSkyS2nnJQ-GQR%kR`2xENQAwy&p6ZN;n4)9`cWg4j|a_OkeM531f<- z!vO>rK^b>+03l%kj477>#hS>ypK{m$Ng0mheQv#Vplk5EB9%jLBUdP23JxH+ibklQ zUc%r52rbKX>`|5^G3Wro07`#IOzz&#Se=el(2B4{tq9aO_!{K?L@^opPc9`L@!?kR zgKeRhc7ZONEQEe0p(dIyg;F_G>SxM336J7I$Q{lasLATse}yFwdpvORqG|BLIfozq zN#n##H^0AL%+D{s&I*V0Eb^cPI1lgIIh)Y~jxnTqhs1c`JO_`plbg}M=PduX#T?Q$ zqvgK{Gyh>UhZOT~7y93`O#?26GTIis2_)jCEH`d4doDGSC%4486gbE>4Y+(W$kR2r zygK0N?%xjLHPX{NM+`-a;zLpW?~550r>;7KfzA~OX?JKrtv+>zPMG`*25dzig-(O) zsC+@_G#u~|^@L7CfOv!mbQ(gZ>qw(cgP1l-li&voM;4xswKVUdwkJvvt) zw5mf3>hh`EVN4kYZ0#R~PJ`^kd_m|m9PknIgib@iq6iV_G=%=BBaJ!@Vyil;_Qc2= ziPuj@@9T7E0bfql(t)4trYwv2J3w_q0!;)E$WFH9jiy>*XjCdez7L< z%pGhUi~H6eh2sKh=(qr}{qy@GB`=IH$o18P=7+ntm?vs}te%+f9~K?^QXlf_)1s3xnwqBG3Y89yOD&S^=NmP;npryAym! zTjYh9d!VCp#7qV{&~bL~fsTJ#>;Ht5q#+J%3I9GZpTQY~f60r8pWF->5(zu6#nokj zWq*|=5CLd}Hjlldzc&E=#Q$G#_W!$LqQ)Fwpc&Guhr}31AN*sMK?V6PG;j#s~-+a9|SsB7Jnd)Hg^ zByh>}e1B=V)|Ypt8%KD0mQC6%x)25FISjM!^JQP?NbkaT4~Q;9cV!u7s`;{YI?~Sg z?r~9VbayTk92Rn_vW#$X829A@AJJ1V?s7N{2!D0V(N`zCI$d^8)E>1GI4Zo}NnmBz zl<}UTr{M0MpS9vd^ynx=uinY;#l)8lb9Z1=j)rp0Ug`%}79FH8&T**`z$ zx~oLdw*InL20Q1t&7Xf`wU>Ech_1iEp`@VauhmZ5*n8P`6hy5J)jQpA-l9%ZwxCK} zI`>9?M{Z?lFkPCt*zQ8zYe)C$qU5}Wj-IC{oc5}xKUmtmTa)?F0lqnmzY*xf->ksj ztYj{Bfp5;@Z)OnR=;CkIF&`d;Z$j`l8pJmn&^LBQH9ZY+c~6q39c4+3XnY}CnQUc9 zYp-+4enyvKE_T0A^!fVdIUR|^HXs~KLyaFtc%>B-&5@j7T?k86R+JkN4X~lbG;|cy zuMN!($P&+|d+RZgTy7hME;A6Gnfk|;b;{6k{enjyvCi#+6{hM38pY5w4eA*B6T)F$ z&5-P1-OX?Eq;Kcx+sSprNcXzfl^U=4!70I2qOROFX3AD3(ujS`bQ7$Ra^r8~yjVYa z+Bq6swP5}l=TsG`{rK_&w5H0|K(EOfnKo`4-HaGp58swX$}o`IzJ*erY2);BXHne; zQv*G!aA;?hc$?|?JM`Z6c$3IZgKM&GiUx89>!`x9@QrkC&Dz;kO?4t~>*lCTXngD6 zzf8qWZbU3vty8P=ruE4zhWeEzl}(3Z(FBV2a@)-*)VrE0$PT&+KCs5; z`p0%D@A25<&{7teb??1J*i9#9n(jEny4PajEK81D&OW1#VF0v0qbsH^HqhH`S0VF4f$@33J;6hg+#qkC)2lo+g7gP00ytk_Uv@3$Pq z#*&KtF&HZrjPDG+6A+noJzYut!DlfRN+bxvdwI9BB(Xl zq_NB37O2%;&i_ZM@Mo_0%^dMdNb!@f_;IYuayRz_n6Uun@>1-ovVnJ#q+2`UGgls) z+$}?k^*cRU%MNL(IF-J!#;^s;vr*t8A@Jx z$Nsl=f>|r}zX07=<)r@=rW5`*>JZ2OLOzrJH_VgtzsC%Ynz~6fedem^T`Q@kUXGf2 zIIu8V30THeU|3A35D0z&L5dh_CrtkYf|z9o=x(m?cl}&EWhAT9E$MARDcxI;)uWRp zvGNnFv^h|S#fda!bZ=o68EGc>b0SR-8EN)&Bh6z@q(KwlNb`XcX&#f2<~V1iQ>0*4 z9BEE)A`Sc{(nO?@W)YD_I|LhKV_dZ3sUGlbQ%dx=vydPVbcFQ!+tynIn;A!)1f3Qq zMTw5D1D(dE_s!olb^;p(4cSfmpW&ckAg6U2f`+=viPKciX}RWL*cSb5Cl4x)u4?V? zEp>s&k%h*G$nouBVxdMtHk^f)lMBss;4F0K3v!{=ZRA2LsyGXMK`!(hUg$RFl1=Mp zfHdYH&Ea1;G4ed6yul{m^ynp@fvuz@CwNyQEycUiZe(4p#!=w#wAERJop4HDx$WD-V7=;+LLJCYlfh4?c!Pn2dj}7T$hZA9l3J09NH&sd`oYNbUHcH3sv^0T zb|bkCV!5i~`~pTZ3Auu4k#cLb((i`1IL+H&sH70JGr^U0&^B4TP;VppV;_*^x|qk_ z%XT9Qd1D`~OWsaV-ZyX?#?Ve*aJ8kqsq}92Xz|9MQJgdhj+r&4^YQVNyf~*Pk#hUc z&=PgqY-27gE){%|P2Nr(d|MAtmMHul(nHO}Qrj5L*nr(S zLOe)Nu3z2u4kqlRoeDlR22Y4!CS_(h`3`Xx(jm^HST+)j;-%3)8@|9Hqt_u2O(jWlwovC|AM&O) z_a=#P>+z)McW5>UH)<==xzNJ^EBK#9qmnmkqZjIb}T8@7-k34nNm_ zh76)EuP)&a!3(@Tn~URh4vvEtk;Gj@i80rNlSr*0@?N_l{Vuj^5?svaUwacNeO95c zI97VVDbjjx(IRz6Hy#sk3DZ02?Yo$Im-O|jXvxuv3;6Fm)nE$v6Ur+cGC>#1(cHFQ*tKqx?ZTF){kMP^X`Gqgbk4xp9c$>V1!o z+1VS7k!qAuDU>--mKL3K_3S$z;j;3`$;yQ)c2TQ8rnnh7teARFNHQf|f62Zm`%**y zgC&kDJgbf`+ab=1^+?=iG)BBpN)}!(QIB4VUoUxU6SG~*v&!53sa>$-1j$0N;QiZ6 zQa6qfZj_Ql^QcEBg%k4xT5mR_CxuVD*Ho*|5nTDrf~y%0+8R5Ga)M8ZH~Q))y=u0N z*^cIPe;OOCGC>6mc(tU&_{nj`^D)E%?YIjZ)9EKgEU=VVVAB%LfQdN)#DI5g(<3KK z6sjmjtxmH|4$pAVf+bQDnXz=S(R92J%+D-kMuoZxzc z6dY8u5z7s#k$-a+EkdKxwg%}Ors+5DMxbeXR{0R1$?}5MEMpmp)y@Ou*W7j2U$QRB zKE#l&savax6onQ)AZxSCu28IJ9;GMxpL0`;vNt0%(yF^e0sX-rBjwFO>SsgxQW7a4 zj8ua18?Zx3mBOOcS?Vh2gIMqv~?I#0Tqp}Da(8GRUVGrr}ymfiWYC05~B zGI)#+qjCs?s65VKthrQooH5vJElLe7r02E6m2@N=Dfm&xK%!9@jJcQU&<6~pS{$r6 z9R7CV3{CA?@G$H*w34pTjW(MNEzDr#8SQW#Y!Co85pR$);&`(zN@)le`$EGI)y8x_ z8zKVg(+bFlY}r<{sYH8 zT2nj#8f;o$1lBL$!ja5jg{SBBmrg4@2glYg*7b+%z{3Q^Tn8;rPoI}g=mP;FjtoNu zSYA)-!ZC^0K50!|lN)W`A@zTS9S{*rQWktQQ(d+YKHvZV(c%k#B7+!!ShV_Ab;&~b zfTIv*h||JE@Fp$eF95bRWe-6KOTis+4CA3KJ_r+t;L2;rz>tW!zhy;P3!#L{x^CAJ65b`n=Cj+a5tgHlb3CzNv ztP-3c;K0qF%2W=K5fc6$YWzAtti49fr0h0E&ETrJLMS7(jk&^22s|ML zOh$=Kq<*{;kxbu#*`ylPaMt}W`T&`##7B2Qnp=m{T;(^pT+-qUTc)f}4vX@a;u8X$ zS5UOHH8lpgakx#{*bD(67iazOEa6nP<}j|7XC0tl0=XG}_7mh8xEcU4zaT9_F5YUu zbqHKrOUYPAB)h=*U0|hkkYEf6?17TBC?bC@84MsdjlCoPhKn_1(1Y_rRi3<%@DZmK zknaMyUqR^~;ZIyle^Ykg`#vZ!oFMoOR0KSLZX?Z+$N>oLw_oQ-gqaqhiHZ@DyKsae zRBtc0eo!$2(qVi{2UT1D2;a13$PKZDP>ag`0GgPLz+_RC!CU_kmcU#8{pA|RoR2^| zSOS?y9nvGqu0%enm1~*?oPrc*Q-mKup*bk=YaN0{2`7R=ac~_4R)7mdq6Q#1l<**K zp@;(#9?%w)NaUvkffDZXmD(QcI}iSB-$C*Sbz;@nhLWYZEu<-sLpy09J3W00JM-OU z%#c`cJKm^Cn(1HYI7Hw?R$iuTKv?2g3ON4Z24313m@C zp=((x$ODBW3K%8e47iYdhY}MaxDSd!|1q!mZCyi5!*LzOG~2lF43d?;=$a7j&f7IX zA&tLl!siUQYmz%evBVdsh!mMOMiQAEcGm>A4TQUr`7tumB51D+PUDb~+OJkb>yi zSO7yH#?cRGtl-wjXSZuHD{xjM@#Yb3+`UVPh3Ue*_9H;ivjh!7V`ArK7#GEOG%gV; z@94XHC*CNCx^HC%Db~** zGaU+}p(Mg>96_9Va?_+-o0y$H8)EGYL``UyOa;n*G=wYhDIC|xgvmnBmW%$~#nRKGBgOb15{4cB9ezhI)EF9$WaH+=c zJ2)l64q@9KLFAG9aGiz)=WjL>Ho)6##&(Xn@q?Ppgg5^tWH?pk^DrW8@;MGsOCnt- z%19!IMyg4G@@K%4c@kh!aNY#?5w3lB6JS1n7|Qzab_0q+gSH!pTmucrpKD-`<bZveNIxPMrSo1t22*h3E*?BX9akM(w{|*J)P<7{`-H ziSWAl(q9}^_|so3IA8kvSJTZ2WME6aS+4q1K!DnjH8;&I5N2zM;&mcBbjkjb2APn z$T%R)Y&%ek)`)kNT$^xMujb8=F!c~}ap@UT56C!}46*aeenCA>;FY`y`ygNkWpRT6 zbj_~FNk~qP+s;S zw6D(HF+>exgyt9QgH_MF)d|uO87L}hIE}V{gs=S`yC_%|W}j{#@~=e`*WO^V2qT`H zn6LysBLAy3PJ~SaT6wM+0t!Vrv|q$EO}^@a@S}20;}CBY$l^>mjogPOwy_B(;@!qZ zR=~eYOL!1pu7L;S&ov15`8sV6_MPsJf41)sxdu|rpoSaHHNwnr!pWO!Ai?=_4Z=+S zO2@&KBo1%`-8Q0<#Ky;0Ns`9LTS@*Ex(3alSc;=sw;kSp#{pxYmLO6h6x;{Jp#PZH z{I;$krlGjbX|;usti+!Zk?zjZYQrH79a$K(W5wqTM3UqV!rNHIy*Wwu zz&LQ!!U8i+!Sxh!ml7g8>{ioIC!i#9r3=}Gf!;Z6v|1pqcY$ZgV=8Y08{xEw5{~hE zjm*u69<+^-IqXwBBljr=4lcl6FOAc4g0rF?$m` zv_wojiAb=Y4QZ&t=cysh!4_esaJzL93jge z!U^fQA)K&U3^kA$*&t4fOo2u#EE+OjZle_;O`r$L(qiHQ4Y#b(b}Evc-;W4Ld0W<4 zQG9;%H4*_SAp77Ud^f;dyb(6h2Op~%ta-jx>pzk)%^b=fY$DLs!Q~Iu&w!Z@iP2CJ z;S`VWkOg#LprMDgGY~bQ15*UqB%DV2!jElQeB*r7SyHm)c0CcvcNJY8$A zAxMyhYJi8h0tL}GGr3D1{#n**T5djpKBl^9=OM0piNEu2;x$x6QyJCW^u5r9w%f}-P> z=Q@d~{cq57=zL}=ao=`W5d{H-=5IDh*47t_sqt zi7}nQ*d>aMRmkG87-qZbh4)DzLKHprd()GW*lXt`v4DehP8z(f*7_0c*g@W z4!p$&8HW=Nf(ejuXedO{IT;7{WJKdMi9&nGIMT|1dhoMAJ?^OUMng3|KlKc;f6J`p zB}44|IlNm|Kt0pu6xyT2fQNcWUu@9kr-aaNmlb?ME)$=CpARU44p#5<|??cE~0{eZ~ zLLkLX|9Uiu?Pst}h`PKvF<}XOME+N6oCuo;v_v@80zh%P)?Cx%t1bvX;_X`J4AHeF zoM?bovgy#Ij_riP zRx$vfD2Ka-+e=c=X?hiuD-TKyA|Tl(jfIpaC4DG)&;b@QqHrAoAHKu`qMrc}$@km7 zj_u2twTFrLDo7kLau3t|c#~dgfcCQ@D!uS&Us&NpaBtk)TKVi7eAu>20uC?m1vxnM z7VZTb+QdA3bivyjODNwsW_Y8DAejMUflA(PjoD6N)_M^H)LnqjJZ&|8;>E~ec0iJ@ zB-e5iEC4E$sN>9z;Jya1(rw1220-M;>>%CzE{Z+{mkrk|4Wl3hY~M z5^X*T_gF9%5eNv2h0?Z`0$BLVoAeN@+Uu2vuxgP&ogKkV041v4F_gCU8^*LZsMHmp zN-b(>7;%_AVql&P4t(?AEbB`sz`qFHzzP?DK$=9}){Zc{YwOu9^|ru179>ahrGX?* z0DHcDlWqngx`6e$6G{aC0wsh_YwN0ZXXJE(7SPWh;Gj%zM{ql`0VwpiHZUaQ1}~D!ZT&Bkp`hkySh~RqBA!sQ;^c( z*`@f|l3Z8Xo_Fi1Nmp=_p>w|)2LH~=&hM%kL|!1hKa84omRN0kR4Bmm0mCBk<_Ut| ztR7A=kgLF_7(Ni1f>R8nxL8&AS=i2QI@IlPyshIz6*96=<0*s+kYxLAQcBkok>&s= z(vWf?him3K+!fY-HNxRau)_iChi+GAemF>^d@l%PrEJvTVrVZ%YOB4hb<*9g3* zHae)|rD81*gCd{9gJPdkV}3Y57(gP|01hyoG_+aXL~OZxzWBRlGEVcBu8 z;k>RgfqcEUrTe>*29ZR-6#C3bSCFcB;O8v!9SW%Y%S0y08B&rnB!qHuM0Ab-kBH8z zb8*uraXXOFr}4y@@uZ=HsEm>5aGtBoeluu31bLGq<4Fzjrm_RAFwrvR2WMjGH~E&1 zA}?OKb|Tn*0)l}EH`s2l?Q;PBK-mo<7l{Cr6hZ``K+?U!}jlvBGw2TNh1>A5G zR3NR01=`@C$_Y0L;7DMCDBL)5!wm)q$9#kj@oPH*Nz^G?PdLV4D2yBkDDJ=t|1sqF z2pt{~YdeIsUzITGY;4p>+p5eDj&P1Q056~D9l$&!k|^9@B>yWQM?X9ytpbdS)D3D4 zV%@w;$mk=LSRQJI00k|=j!#xY-raw^a1?nj64nQ1UeF+N6WM@z^wNK9=4c-BL9~;D zA1rz6N+Y4Pw`>U-Azgewuu zGfLjDJ?}&5=@<44u?8yvI0!GFND%&8AxEd6$ao4XBz1$5H>{g|D2E}GXm78G040*Q znvOmHc;PsCBi#-%iH4371!N{cL?Ez%eFQn7pkGa?c^A|?{T zkq6oHP}Vn;YXiHh?Yl_>UOedGq{gg4bF*TksI*49aVvy1M--x%5Sm>Du%uUDI4lbxF?gQ80mhZx#MC900gRl$VltaKoWL?UW1YjFCd!pTbiu!wleg~$^D!`cFiT+HA` z4w{Gu(T~4B0)__2k5oV5p^BC~d`ICkKaMJQBnM?cm6TEyBL zl!&?_np0OqLS13eLW)Dy6&!J}N{Pw|9U2CdaVe(HDa8OU5D=GQ!JJYI1Vl>!5`_X$ zsT(AO7RV12=2UW;1lT#i(0?YX6D^zm;x zFAgW#*i(odIDo8I8qQJ&!?|Ok;N`Q5hxn?Ebbr%pi7O1&!I$+x~*xU*gZ|Xi{SLH?>lk=h-JJ z{3%}j{Usu-Pp#BaxSPlBtfTd{_1Uv7wpwI{M!0{zdZpH0|X+ly2hsQt}#)ZR7=YF}L#^>bJc zo6_%3WA!O{^fkp*h_LHkw6a%3vU}LW4E2VO7(Hy*uu;RF>W7%s78|Zf8b55<{kOx0 z!T*LG+^6JZwcXKjmyxsMUb{U`iU)1?dA`rdx?y5EvLbo4n00JsU;pj+i?bZ2pArmT zI=1Y_)OzFMSnK?&>vfFBj}X(k=MX;Xl(+a+jo`C)_H55K$?!Qqk=%75#Vw|>d{$HH z`=S?=?yVMw`i{~MG0PIesJ*oTCPjINIvS4_*=MxXs8FcwO<`$_KnvEhFt0R5MRRIi z`Jwg)_V8e*Y@AnLXNd`=yTQP-zpFV_#On~FwplhVqqC*V)vN1?2;Hk{YaFfTV{_i2 z-YZ4+ULpO(7wOE(2d)%WQ7ema!k*S%Rutyh-ki9N=GFZyk#fdg(^T54?R}m7HqTFf zO0@3UGTFG?*v`hIt?9k}DjD63It#CcWlh&i!o2#s+6^dP-3=n_W&;}IQ5dV9&i=TX z%2bo4_OulEQ~K!^vlU^Dv@{Ep-ziJ&xJF~%{GOFZ>t_WtvHOqG zdgG|QC2ST;B!lrtT7=q2VV9UtI|V71n2k!z>bU;LtBVZSbPDB?2HS|ncp_b)a&q2j zS?Vt)>`!$T%oaMc$Nu!SHkFsMv=2r1+hRjY%}qKtv0F{@T&5MR?(qv{&uHtf>Niy` z*Xa8xBgoIS>V#O&g38_#ZSfy_%_A&$|GjF#`|mXio`31uv}0bvObN#Pj;-~Huk5eV zSJC{uq?pPK+m4d@#C-c}^x@2D_1(*9f((sUtw+2>Iy}PZTC}5Hg3PgusU2$duCH2O zGGqN~y;>i%*)?`+O0`CEK6-emyu1--SylEw<}eG8-C2^ z%+KS_pz8(ndEBRKYErGwy{f!~dh)OMx$dMn&_?vv=RQxpM^Cc&*2@`2dS_p%^bKWn z&xT+8zx5jb>Dpmwf&RG_tN*_BKZ`^wwMQd8^+8*U8x5=@w43}00ifj~X)bP=$Y_Y` zTCVBL;+oDluIUI-QXrIkgjao}XZO$juv&= zcBj!Hu;lfTA2n!F-PvTMN!x|u4RIaMHJ#C1(-GjBj<+2U;m%5ZQXlU>3wx?}>lQzBH*mzrGtE zR+DV^n#*u|xnXK?f7FN7V<^@=8=m-2_A2~z?YQ)kzi<7oB9Trt`y+u!fomqe`^j5+ zeoy}2m;b*pNN0z&{(%^keVjvOzx&CyC;zzg-662y+>VHxuJBw*3L&Bo}ac! zrxghjA6urSr3$vTJWBQWM0~7!)aUleYg$^EU@QJOc3Rp|!PbgLY6m|NAKyRnIPfWS zYT6#bR`ju=STNRe(4|07)3ajW@=`GOP{qLInc%iV6$6(H!4{8-flH#Gmq*3G<*wjZ zkBWgyv|y-v#lR&(P|>|&;1VpD;Z`wl`AKlSTgAY|Pq6%8#lYpbpxwcWfeTfT1##Ka71PZY(NIgh z*3j5s@%e1zt((+mYL{a}y=J(qF4&Z3qG6`*PoJu9QgHM8^g~Md9edZcmg_C{oLrE| zMt^$RzjvL%NAmkPRVveYb-^2W=!Z|^^ut!=hCS~%SJ$s$l562q(?1{n=UCG})g<@f zxd#eqIt4d3wBP)mne=OK$-@xZy6oOm_@8ceZ}7vA88i2sICwJB;2QOFLC>e=64x-6 z2&dCI40k%Axyk)U2tGll)7i?>)>4V{7|{?t5WIjsW8|=5lca|Y6CeB-e)xOT4{hF} zZ(pK3F{9N)G$rx##f`F2Mo-U{+1VCPcTnqCqxbOX@o@qd)>oFinkM+&#J6Kozk6qU zV*A!367O#GEqT9e-_%#MyC!c>%nP;-nNwysU3KZqPW4tvdiU(T7Bq(`3!T^aTvu=0 z+<9w>@cCbBrup@sb)hazdYy32cX9v*k8Er^ zZmTC5c`q$%=eS3y-%HN;VZr!}W}!nPcC6T~VjaIk?djtChCVCKx!bEpDr!B^xgLMg zvB7hs^!W=9CS5$~=^ANNcipNrT(eK<=KU8VmOZ__^N6Cq^q9YHM;gNXkK%%sm-kokq;N2+WF~5 z>YJuJf%DF;+OjqByVyH%@ccZ59~Up%JZIJ|4U31WRxjVrUvzEEnFHr%OwN6~aY2As zbk>>g+GG?*9$s^Cn*8J$OZ+k?rXK$IVgIbTp?e=mjj)NkuWF*0H+%GXX92%WFBr3) z8)`be48BN7ck7)3|9z}(J00+X7OL*%__;??yj|k#p)0+N6H4sfmPH-i?X4CRW{UT8 zm&ei+Dyz@lV$<}%vxho!9#AaQJvy5usmz{2ANsh1*Q-t}o;9v)_G&Bt6BS`=1ty(b zwDI^ik+VmS9cHcFwaHMs{K}5qBMz)pJuWihp|H&7+UgCN<;>;l#xI#+FSuPO`H5r&4~tJbcl08Oz;e5i=BC6v3Y*iJ$9Hb>{ULl zY?*s_s`8j@!>jd2#M}j)Vpk;gYAOA)eP2TGsv~1ro2M;*zT;tb;QO)LVlVCbPT2ce zV<2_;$z?n5(QkVFxIU;lM`xmq&nHK}_3tMJ%%zXWN>{(0zg11`+N)wEwLa}VbnoWe z%^OZL)5i52InZXSe)52jah9bxZC~X@{eIgCEKSqIx3_JXzlQ3Lz9sT$XV$xn%L^S> zM_$?H9b7(acR~IclhVnR!=^diu)MDHY2V=yCSe;Vd=y+d(!A5yPsyn_L+AU8`z`Oq zOt@~cb2KY&&XvlA!Uu03NV=G-qL)~zy>VHGTQEYFSG(|StDeP+)2;|03jjvGQJroM_vSX|P{E|c)s`zZ6^IdYra%mCH?&aVL^c-8!kMadRlnGek*f_ zKUf(f_Hl*bvXgs#XItEoRSsBjr|ibY`z`f?*8Yq&hF0h0M14NSysRpyej|0m zTtzZ4F*5nh!rW=As?XiszOmkB?E;1I)y=a0x~I%c*OYAbk)eM2W=eo*Ynp$~oA}&> z8wnj{D@u&t=GkXjr=~_e-0;EciCgyigfzbw`#ZHV1wRfmPFklXE7Ch{*GRdu<3>4l z>Z-}V-QhSQA<=~*zMb8C@0NL>kffLUn@alaQ|xHnJaOs^QLnnf`jX?96XH*ATxP~{ zIO{*{h(O7Hq2Rmwbe}JH8G2x4Bg@yLp#M_l!;8C)%u^mE(R}{U?1Q9?p}TA2D8k7 zQ*$r3AL^VN`_Q{}{7RQY*5ljXy?@?6>xFK`HrDBB*HiAy?yjZrGRlZ1sn~Ph4jc9( zu*w*MQJkFJ_F3Y+wHur0_Q4B8z33L(d#_Bk`f=?DV?Cqmy6|@!TzY6CxNgTA$~lK+ z_xG~n7o3kn{*34RBaH3fL;r}bt+T)pQ`}o+_Nac`N<^1uKQ)ABM zp+?Ruga<`V%c0E7GQ3Zz4atMaA@t;Y3X!l9%2`spNMy=scV+@MAD z#Fl;B7cb;&SLdoshP4yA-95P}kKkaz&&^Ngl!~e~S;)qF^t$vB#bF%-5&~+;T?77tCd<2No=S684wW+p zl_-IrPlsw>Pv6$gC3iEG+l@)@5cA~myO;q6|^oMqMB(yryO=shkZqpGsjp547FDxOwaK8=RJE;+16!uY9A zV>fum78@carnOpuUW0L$@b({E#!(`pa*l@lP3W#RVbWL9JsM^+dVFULD~Dc(rYkRZ*RLF9$}T^H zxCOVKsJI9UPRo9SSf)nh2VIN&)$*+0_&faTn#t4O!wTz< z3EWaMN!QPPP2&Opy9og7cfB}i!z-tp5#pDeyH?=k3^&6`rwe_k%5rMsZ1qXXT8|KpC|fkZMiC+MN; zE7LC3s*Yqz8DCKC5{4d!y4i5c^-e3n4_=|hG*TkWLrpwhCJh(Uo5<%}waSD&0Z{}3Ra zBYdRO$(E)svQVf__PF)Vpaq6(bmBRn^dSA>AM`i>H9=g#jY;=M34}1#{Glu z?B346&LK}7W}0R&o|XRx6m}HL-1T#!5~E%4KF6|=%1Ty(n{D*)$D-DKe1UFa`=}^0 zLTonR$q~qVIBuI~1}0B;l0`A57hkv>_`(=7ZFK} z0%cW;*vyD});dP032A$pm0Kt}#0!Zz7Vz_G!3RWKN;O@r34C=ov2ZOu>cJn@F-0QS+*ztB^r!TNk-ZP%4Z+x97 zJwxWv#N+vVC(Y8#m3F^Pc4?tB0H3ZXcH@2d5jlo@fc(*rI=CPX{uf2Sw@bZCyGv9UZ&SM-oy#V7PzVN8dqAX zlMcVqz8z+-JJQF94Efq#FRr{}=1;9}sw?21-Ox*1unb_ifoHkFzrJkX{jnF^{rxYn zy@*ZdL~_Fgp3UkRzS8*!lbVW*Xt~QP+RXJN<&%;+UC}Rvba?JaT`1lCcj!3?)kC|s z{7@uc3etQte!>b${ada- z={)cocUhHIe*Dx~JQWse6s8QnBzv8ZtoqW*&fuBW3}ak28)Uu%bNX<9%&f}UiT>&3 zo`leJ+Uxy2WoTfPS-A?~B3>8+Bf;c6Zsl6j;SvXHAk_jZd^+ubrpb6$ z*3%vn@fB_>b1rUS0O#h+&7lTfN0vWxp!JO+%c4!~jDbHIheG4d*@j?HfzE8lI0W01 zE2}j4-q`swnnimKi@M0pvp;XYxPByJv%kEica+ zZx#=mAZq<=Lin zoda7}+*$x|6eBjnzLx`A(OcIY4%*`RCea_O&{p`?M9G0uIyR=tkF;rJ4qp4#1XzVi L8+%5+WOx4`TumiW diff --git a/app/public/exports/warehouse/warehouse-rack-spaces-WH-20260428174640.xlsx b/app/public/exports/warehouse/warehouse-rack-spaces-WH-20260428174640.xlsx deleted file mode 100644 index eb9dc4df3a8cbd7864d805042a286e2622eafb7f..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 53332 zcmeEu3p~_W|9`tB$re&nDwRqh+AbuQiF6}Tv`S>VC=qf?h$*Rbk;>8*A(c?k&HXal zeGw9++(zz~klcrv`G3y&erK4;v)ew;?(;mq=fAtJ{qFRg@AsU~d4DeN&*yW_WT-cM z#OPtehK(9ls2^f>zT_97E#C|q_G!ehVd8Li>k4~2XG=S03uCwamQLo12W|J=`AOgI z@dD9f-5M*a=j(oFZoFybl^j=ZOo`Mon@(FgYgv<~PDV>T9j!>%KXW;TpQ`)#!jp zK0PDH+^T;2tDkVTQeDt{%K-6t=9?PE11he%<}8 zt5n81cC==S^?FvZ+&z7ABL&wu>^Wzr(Utqq-)zP5PO;(AXMzQLnms=Rm|Lu^VeLIU z#wgeJryCC{)Z4_y^svoYA&(N&I`{d^Xw1H*G44I1@!k$K`D2YEwjQ9|u9Pw)H8Bip z0>J0~GZH>oI9l#=QsO*AXzO#>+TsTIPVd`c!-TodD559tTzItp$%5~ew;ozq-FMk; z&8Vw4Qm0=po3mK+msxgF@qX8y9&Kqod2ac4etQMaI()3#liie~?$_wIv1`hA3b!VY z7s$>%k^4(FYp;WdobbpKGJ*^DU;i$+b~kgKjBa#hy8o65YknQ+e!eH%B|$^~XZf?^ zvkbELYR}6nZ16qs%h`^Y*j8so=HXhO=!D$m#VNC+nBTu%vd?a-eZ%?Y?Ge-WnD%GQ z-L-D&$s=xsts%!vYOl%}zN$0-p(wRq<7ViZS69OmLafA$qSseuo6=mSl$Zx6dkoB2$?+1izG9Wv7 z@MEs_jy5~&?QM`JaDcXcvOrX)l{xxex9I^>-FfGo<{dHH+CALoVZyq7YpqmlncbVD z)=U|7RWR)7?RS@6tZB;WUg~SGu23*8TuxWCUjJ@->-a;9OZxVRJ}us=F~WcJoLTP* zU7J*)aovU!GSY4gpU7uN@$6qQrZ(?3)=Yxm{OqkKv`+1n%Wvg*PDiy6(CGd@qMUd&jT^CEhZTU%A5^gjlA zECCRL#>vXk(wW~(=RHeWAAfz=F!{cb!zO<5EPmyCgy&CX7IEpB4xx4Jheq$nozG%W z6Q^hGj~X{_x}es%=`R+mUKkZH<;aS)U5R;@<1IZJ?{t{*`~7OY-rc!0w0?W6a%FzZ1kOJ$5+t zml>AP$B^ys46|oVqVzwZ^s^G_>@pD=^CHEIeUo;Gxq{Wtl=f=BSVUz|SOu-@-WP0^ zL0^@Z;8=F!*^b9r= zgtgel-ZUA|J^>&}!)jXD{;llJK1$ka7^;@Nlg9cW(#n3<$LoBc0hy>+iWJ&FW!$ zF$J?|ls@-YET$GaOk|nnL^kWket*GZ(l4ph1?;+`%!WrwwDoRmn=V&cZ?-+F%bwN$ zgvPAQYYq15ucP;O&@b1-S+LJZ)7j_ax-Hnn8SLR7EW+%mn_e{0)M?BH>9(*eDz$qw zC4+U1%}AuPYA>=G1tQFDgZ{WS@n_V^qBik2)XLUM*~@I7X9mvflQjRZiR>zIP^0{3 z3d=H@Wg(G4V|@%$k-o@IyYnK4V&CU5fAOs_))H1<7;R}-ob{z!lg&EYf0)KT*`M-g z%d6X->bIEeus4hLxGZg|yQ9uld-w$IQq{AWQHK` z4j4aqHawbWc6AGSbo)lTptWoD1GGz?K4bLXmw&i^u4!+YK~~Q4dC|u>6T)Hpla8u*KT?fpIY!cz5)} zEok5^jXArcqjNUyeUS7nH2B8r-B+zT+jmE+1mB2M*1M5YxdTSk4L%m}CNKC|`Ubji zbmqpr_mkc|R@%AuzTrcL+x;Y!#*{)NrrEx{XB+q4LpSdg23y1x7Ve5(yan!}H}Io{ z!SwqN3wQ5*xW(+_2bD%7KwsLH;+)-kqjO$cfdFB_H}XM%=JwrtL4X^|de=Yzs$I}3 z5FkD;_(s{jprAhKt_t?Uy1IK56}=~HHxZV|Ax-;7g}WPIZBz1cUhjQi_>krHpd&cvwNdbm zg53@dKD3eHIokP*x}4Yc%6bO2LF-}Awo-*FFlZADO6zI=DfF_!l{u$RSE+7UrY~{o zEyWjREObmj%z zprgCWdN*_6t{u#P?grnW?+XeohKXS0--6tE}&TcUeJGQ#Lz1 zQ#=28UFJeX)@94<64~L;;L&^EnW9IxDOA-aD#$F^GE!ec`iaHf*SoG-RkiP$q(ZZt z6rHos>OoIWslrhJK`KloJBcy8q}1YFW!SqExI3Kvs{}jihyF{=IlG5=_Pv5k{Fafn z64GJ8majn6s`lNJ{+Otd64}?ERaUwy2CY4PEFvfGv}JjJkY(hY?CSul`}&}@0BcTO z0C872`#Qkt4o(lS=HvximhTI?RICsHur?)cnFFvY1FUWjw(Pckunu62{bax3Drmg6 zE@z>=a`rk~c=6e@&Qf?ocx5mwHtoH_qHg=KkEyP&@~X&j_1juSQ+jNIE?rg#08406 z-7*I(K^ZK;t*uC5QT*mP^CcvUobIhd*m`YKXa{T;EkO^#-TUhoV^nL%1Q49RcWiDF&?s zbngJVWq@uC%RHyY-sV6mSh)nOE#WCGz86+8#L)jpUZY@3@TfL*mF!56w+rM2eAn9s z>4UuOr3%3yZwbho@m@hKev2}IkmvMZ9|D0|uFwba9cwn0nr``zVSr-R^yac=fRmJp^|%@1rQjbh}U7-TfYLRR5+E`Sfo}Ab3Cg z*GksvB>*`J3iHwR%eiEk+X!-{^wbd!e#%~!5YsgNlvr=7b zI=8r2-8A3kF}LV;vH07 zybX!BE%#Yid`QUL6W2qe#OdG4orsxo-|=x^YENoV(eqy)IVxl)_l}#gfgUEiBR;J0 zri?Vj=(C&Z_7u1%(t2*w9SW;&_FHg0~LtQ*Q+5X#* zz5|Q)ZYz*+opTvp2#-cDxVDtkZEx?n^!eo!jqWkcswR5BZ1VKq6G7?LALdNA8<}h4 zTb-+OH22N8+neZBm+D`6ii?&d246ACxN$tUuWEl}@U$b_IyFMq?yS4X=zV#bcEat> zh0?$^uaiwfkAIBw^f#HQ*R7xAOjl$n*2e2QnnbLtvv%8&MC;Pnc5+#n%A*3$)ZX+Q zn`8V|E@$xN}7cZI9R?mEx z{aVo|HLEzic==kpi|J)24ofME2Bhw5k#p`|U#5RQ^<#_XtkSzjelEB4F!_+`%CNgY zx1@H@s60OA=?EpMw9y~tOHvJtE{s-MlqND!W!?0kgO@5dN!Ta%q+Y)8^x&2%&z_|1 z-+cdT_RP4MZmsLeXJuu}wLZxlBksF>Taep?9FINia~!t4bvsR$**^UHSJ~QeGu^Y_ zjMSA&f7u~HTm5+Cj_8Zg+blbSZjJe=%3at!JtJs(m&7cOd!}Mm_Q@MP^v*WVukT`* zdY5iJ*YeDIWkq_8ZtHy2jKpwylZ}wKz1CyNTN94-FibwP&5xCi(0*Q2G;TWG`-0LB z@{d1v##IL<3;0})i<^BgLqN;o_75W(w#KfbUs&NO9Fvg|RKWoCJ{6i}MSqd^)1F#o z(MEK$Phx}@O#igCYERZ8C#g}FEG+a6dkO2(Hs2Z5)ZMnI=2G$)pK=(}mnM*j#$;@b zEu>%ANfl0^f%I&N>r{BX$3FQrRqrf&emxtcA7*xL*mLWZ(|=(FGBh*i{UR{wM;P?5 zuNrryG4q9ft;SHIL`jZ{>f zk`zAnqm7W}ey!;fZ%xn|LGg-IUzB*{oKRQ%h`CAOV=*6jhaz!lmGK$NgH%;PoSd7v(jQs(UKDz3#@%9`#s2Xge%v=0}Un)&RhB z)jPoRgZG66fakcbxWYiybxGlK;Pue`T83!$(HG^7lBx|qc*nr&Nsk4#qu1w~#qRrX z;mI-K#>cQEVaXB45ul$qfNqDi9~ahr0&BPFL4anmPt5IQ&(=*`?Y-3O+!Q41lN#Nr zimC^a!qs51&-=C9k*p#Yr(-t9Wa?TN7my=)=KYj--E0(y9nJ+z6ZL0 zDxifPTx%A)uJXc)lfp4iL8@_*J|{t{#SY2$PwI`8Rg4k`qzueN=fdow&-}yY<-N3> zzU!3d{BPtG=T6ueKl64aX(jH@K+O`8vrfb7Ru0JkJIKP;u@g7*t^=TX)-~t;?e(!Rvd>L>I&B z=bqPOEml-5ObWM#*JB;D-XWl+F3OiARqwCzPJt!$JQp~!6PD!AkHS*vNbOo!dw7-i zYqa)dUj6G_cAr&Kte*;l9yB|rjsSg8qpP8)+LaXUfdF;TVj!8MFUm6k&?;{h3_9vp z0ij(msP{*U=+=M`Z?kh+U{Rxz!+nrNony+oS=xPb^*Fpf%~4Bq638_3qP%!=wPCfl z+wcj8>I+ZK3pf4>Fw01exBximeC8;B7byRNux=(OU%r?0rfu-LZ>B&d zdi}ClY+?0j1s828#8vu%vLabB3^_=~;v~WeH5Ogh782 z*3E)J_1=@-lm)ZTlN=EUuU~geUKpr1c9UY19K3$ZO!NnM{Z&>?)(?uRX362Pu%rw} ztsl{n6gb|r1=enr9R3ikJ&5B?^WpU*vvXz$(CivrbFk3l@Kgk-qn10oenbf@G`YH` z#+wC88ud~@Xg4hBG1o%hgN4?5k6Q#<+JU|4Omg^h1gMkNIW+sii}C>gXsx&00|4}; zz;^U{4ggwv;mIZ8#+R_9MUo>fBS70ZfbNF1Ul!KQfwkY_0t&DD<_Kh>*NXwr+6y~_ zg;R0>P!-AR!3a>Nt zc(Be))EOQ;ms^wN3>KOk-U!0SI%&N_!mELWCRgvT^GLRg z{HkX3QAO1;Dbod;ZN^M<))JizVrqlYrc@i&d&@nHTXOf6fVmZj`CT(1ri+z@O~qAV z#w!qWMlo&Up0^=l=J~!|@grqYBE+#ynH+ZV6-ZuZbz&>3KmWLVjF+#@ppc-g~AKbRJS? z$Gx0C{VPOj3KTVW(so`s10eCKKcx+jX#2+2SP!r9tv{s$FpK6-I0-Ndh?xWVXYu3o zhXn2Qyb!#6jSgs8%>2CXbL&l_`K-W{gHt%Z!7>l;G0PfSB{SEHn_^w{ppPP;|E)k}U^|$+6AiZwHZ3 z()}8r`s3OUC^mT~Z_e_yQ`>;;CkcF6*KhG*C98g@Hp>W zjg-T?c2vOeDzjM^);=SJ!1!Tn+q#hD+Pw!1Oido!!aE{&d?Jzk5^>ld*1p3)SN%=Xe z^jmEnO%5qfiiJ?VhOCY&k9m+;8^3xu?Tp{i?vNG>9W%PDDl$r5F#iHE)fe%5#vjr- zZhidso96!!F^9Cx|9}VmPCOb?%)h`k|8}9@C7dC{)SnjJ#kj;eh=i7X`y~mvj2Ma+ z#kjmUNX*qkkkHv7NN6gTss{xmmk~p8I7>v29 zV>uM?V-Pn%*|y}!NMK-Cya+IGu_)dtST{fX2$Z%mqw5x(!M+uGRZoA>oJs32(zr2il^_lu3&<~NBm_Ho)A<8~t8qg0pzbHbGXGM@8 zW*9i?bS$4)TqNdOe?({T4^rMxf#U-Kf3BEryT1;(A%!QiPEZc-+R6HIkTU({XSi4U z)RP!zyjbM$tq><2;xUkc+<58{-)X2pGh(>WYk;P(t( zF#kKm{0mI;Zx0$A4*$bS$34zJ?CAd;w)wy6LKJIJM6a7|(PlqcS^7^N#20vHcvZ)> zk%$L@mlj042o%$BM0Cj5aP&*6WJWzgGzu{n73!X0)o3hueGsh?p`96}g*Y4@^r?54 zt>YhpsNAb?2%7(084E8#DP*uXLVC%>d~w8y$HX+^&eTJvTXu53Kb%oG2|b43$G)K^ zt2$sGR@|?C^_W#1I>6`ph|eqgcGddUpCqK535$&6bQAQ)!QH1YwBAJMYz6^~!Vp>v&?j19xZG*BzS zXrPsVU^773(Rl5Sv~dx8*87Ieg}FtMtT6WscQ{j>>P>1;xy8j}S#> z3Sfd_eCpk1gJSsB!ew!3IO8D>8%)Xqu)%~+{P37r9%OE{$P%$Dp_4R`3nJ>km7I_z z4#pdw=@Nsncwzk0Wz1ak#nk^}=163~f4j_I;?{qsk5 zQZnvvT#q1fPxB$zkXKC30fZDN?73{1BNREV+D zb(9cEj??Z)85d!)-gg_c5K_EF(@_gSk8=P)f>^o|TKYK70fb{vaLZ537lz~_!AC3| z3hux~5t2}F$Ns3Jgcy3|900Jyt82BN9a{$2# zHpiPrYjiwWOQ1aNf9GU~Ulk%nD0D|j+2o;o)2+O#` z0R*)@I`(h^pzM)vIV#ZS69*7JP7zCo!vZcKC^~?Uz-bxS!VYtpmTx&K8Rz@dd(PHr z4G~R;0|+jHGu+Vugapxu?m*FW$dXn;mNeC;-VYiHC7c5Y5BbML2M}y|rmy$3gfYd^ z;Q)e*po}{@fRL~N#uQ8cVol`UPdRLWqzp&$KDXXF&^7p7k;uh1qTpZMI%&D zFJbTjgqGzx_9#n|7<2$(0Hr@9CU@^=tWL)&XhqnfRs?Dsd<}AcqL_^QCzq0r_;4%u z!M0FLyFiys7D7LhP!r9ULa7`o^)uz2gh%lpk~dP1imKs-VOIt`)Ib)-?JK};K^N$>-PqY#Z@@q$1a2T=Xru*gWN9-S)? zTGgQib@|loFs2Lxw)T%gr$KgNz94iO4)}<9LZ=~MQG^I|8bW{6kw%>cu~i*adt&5` z#OtS{_jNk7fG?+N>A=r+Qx?V_9?LU*NAkD`gY~|e(CBdY7WG7pj@6^`>vVlJzgQD_ z<_@-w#eM6K!f^pLbXf1l z6E!MieCuE28Kd9&|G8pTUs9D}{7ZN`!M=r+g~9X)5oiH4kD5tXt$@#OsJIXR-3dOV zE%HLlJ1h5B@RBAcKd$G{BtrWzg>h zpCJS4K+9{uEeC!YG$&rXSjUzlg%O>p>U5JA89EREV`LZu`q<7)F2Sk^lyRr;3)qL4H9cgEL z_qeDwx;qyN4huO|Sw^@xjQetdkLW2FcR8E}gugoG=&O@moi4j4YL8k892H*gB(O4U z%6L!FQ*d|B&)Rd*-Rt#EvsZ?NjQ2FecPFk`gYHJvzYqy@t$i+PnxB!;@}147dx+sB zm_1i3bHnE7)xL_$%hr=lJ|w)Oqe?t)t7?fFHKnWfXlHWtrjAaxWkszK(^pe8+di0? zu4+}tO@F_NGUn&%G8N4wtL-Y)8aM${V83l7p8^v?4O@= z-BqG!TYuRrgPn8S=Fh*e+RMBzMAzToP*TwI*J`J2?7i$e3ZmAA>YZ*lZ&9ZyTTmq~ zoqHp{Be$|Nm@ds+Yqunx2NZyeG-ijXWQpg~z4e$#F1L+Bml+7pO#NfaI%R0Ne!-)USm$=Z3RCq1jbdn;26YVm3E?oW zW=M9h?&ddn(zo;U?c_RQqT2p0fpx0!LOdGe2Zbpo)hi^+GWf;h9-$E(Rv~l{mv#9Qa zsev9RnBh+wEyO@*P+TM@#@h& z$Cw9i#_21{72XACY|V^E?Lg2Jl{16nPVAt1hURt#$R)i4>soqIHZc5N7-e&4@RNHq zO_4ffnAV@!qoXc)?4v8|kX>qtvFhx;rgrC8y74zzX#C`~XrDl4|070eb)>dZA6Vma z{bRe7_jv4aXeo=#y7%59?4}bla};R&1!T_gju) zV@bvS7>pGQ#`;rpTwX!4myv)K8oKUt&B_%m1hW{&tJr1(i#{5aNSxtsd|%vb<(c`0^P*}%I=(yblwnJbS? z?v|m&`kfxFWrs9XoJ!wVW7vY_*(h+4kmvfi#og_KO-=#9qg`57dtH%Inec5{Nb{9v z$*#e2H=VJbg5{Q%VLhn?-c12Lg$0)y*Skd{G) zSosN7+8ijv;zXJ)Wc(x3@&r1`*!G>^$hbDXo%DN-;i zjx;AYkp}(}X(G}{vxrEe9fA$AF)rHiR1bKzDJA;bSx68FIzoE=ZR;(9&5WZ?f=-K* zqD05nflg!7`{r*NJAsXYhU}*O&v4K%kkdL1K|@{T#A&MMv|MvAY>WQ3lLr+?SGD%{ zmbyUX$U@^oF18A`mUK^I%Wn^dO3+Sl-G9{Z}Yq9yfy658W?-KY#XxZ!U6x zSK@2b0m-P=!iF>;1W$Xq|66`yurj$ z5_)W^u4@Zk0aHrqLZ&pH0n-*Y#zBZ#;>-;(IvvQDa>Ar!Cq&c}p#-$?s2*t}l>(gf zFrS0^*fnUCYW=`HSI=`-V~B<=ZO8-iy@Q8EA1Rgqjv zyOCT6v0PPgegUJIgj~V2NV&CI>373hoaSvXR8olAnc&JgXqzlvsJ9XQu@A^{UCd+e zWxElDys?kgC2yxF?;E%cV`!%@xZ2X*RC+ghw0PssC{CIL$IKej`S^HBUYygDNV$Dz zXo+-;EkAj37iy~scj5rY`|_E zAs!?s*RO7S2NQPEP6eMDgC|5VlQOfMe22IT=@92pEE@?%@zUs@4PW4p(Q6ZPVSJ&m zFf1F0=ac}kkX!VPf!D*gZAR;}3o*v%14PWAm{|gykG&CcRgpWirjn#NTd4D~4|!9Y zdy~Yt^>|YBJ2V@F8?_bbTnx8APHn$=89lb z6+wuQ)YXz`Oc)CQyfk_| zLk3ZoSC{aI;00cv&BgIL2gkvSNa8M{#F%TsNu<^gd9PiOeiz#{2`*;zuf2(sKC4hz z94kHG6luM;Xpy?38;=RNgz261cHfS)+g@kWI--+fAh~`4q=A(3tl(=cVUTw1jAnCO za6sil-h}XQ!N+~Oc3B;ybsN9OZfWMxS;SR1@E@UY%zs>kuP6Ko6b^|9Vc{3YAV!O+?S6BMkB{l%LLvl9VX)#NA!J=!-XoCgY|XNOv7@|HWTg^4Ci-60_c17_s+g zw^hyBX96xy=a|)Z#Tq~HW;_?@^fgzpms57LrsMAlpQ7qN2+&IK=^}ff) z?Cg!kNHt2S6v`YZON&mrdiI@j+}?GR_hdL(W$8YA8)B@3^Ys7Eiwua~^FiP^5@S>^5i)GkcH9My>GYE#7FbFwuxSZrz{H#YV!*q$>5-Eq z3RM)NR;Sq}hi5ow!4j#7%@Ya}Nx@@-WeLHr4i+2$A_b3}Jf~1)JqeIDFF@~H+9N9w zK8nsB!Pf6!fmewIjv+Lo{N^q!a0RhIDZD@=4>@3h+eQaGV8Wdujta|^l?W9+PH??J z3J$8-h~);=$iKOZ7NJpTTZ42C)AXBnBha)xt9%I1WO+ermaz=QYUhFSYwo)1FIg95 zA7V(?)U8!Tib9JYkhNK6S18sqkJ1zU&$%f^*_#m>Y1Lh#fd1f*k@Dss^|K*;DT$O2 zMk+!14cMWiN@3CJEOiz1K`i)_Nm(AnAzH1(__S1G6J7;;Kt^I~8v_=qWEU0Z|C5^? z`hab|{jxP!=xOoBrfa)G@dtSLZgX0sDfmaFH-j7^6;fNl3mk?{~h*-s}>;9-Jdu7j4Rr_W0#^nm~oM~0yS zEU%|^;h4m0pR}f~$&EJekov#E4u}XQDGR=usV-XxA8-JGXz_(VkwFYVEL#1mx?~}I zz)=V@#A#t7c$1d#7XaIuvWK9ArQnV@hVjrAAA|`+aOE{*U`WJVV7_03FpCiK9`*x* z0KN`Eg5>y31ChX&?zJ^8`nW*nGl9-dv4wf)0}A0y4~9c|qHr0?sJ;wbM1sK2VH|b;d69rj2zi-`lYv!2R#pPJ1ZH7S zRtZiJaNy=oWh#fr2nl}=HU1}=;EN0uEcN&9aa;}uJW5)E@^RwEmPJfhei2I@d<&> zD=1ppni_-LINYXeY=!`ki?e=smT)Rta~N04vkuTNf!qu~`w8+4Tn&JjUyv3d7jHG- zIs~q*rDUull3n2ZF0j%%NHB&3_CQHm6p=rd3;C!^Ijh=)rlRDoB+plvZ!c2?MM8ycnT{uD! zs<)S0Kd2Z1=`g;fgQ~56gl}3i{l{&J0D&PSjf zEP+g<4(X9)S0W$P$~8>`PC<&ZDZ-DS&>WQbwGKg}gcCubIJk}iE5L;!Q3DVhN_Y^r zP{aWV4`>TYB=S>&KneHxN^KAJodsa;9b@b8G`17Ups23;fi0iS~6 z(6uZTKSmFy*M2gHCBZ*87yK92m2Etv*{1_Q&5wuqZr*X(g?N=)z_JmFo z-GvTqr8$MJLzHxUL_%~;FlGLxw-YHG9*{rPK(@!%WKhRC{uVXroV!FB2l5Z0w4GpMA7)sk1d>c0*cD^&D;EqqEzRP}s?tyV$ zEPx>pYI`{{TWY`DIB`y)2r{Pu?IWZK^gvkxokx*9Vn6cY$j;Y&Bp~JOK4L}j z`O()%go`3Dgu#Sgx8%+D>!PF)oei)LaQlGfc{`*S-yvjdJ5cS-z$Vgf?%ImX6zgY@ znGS`~P!i!bjv!7wxoJ|aP0Y@p4Y76xq9(LUrUGR@8p4(M6pm|T!epUmOU8iTlrd38 zr4Z~6x@)Z|>Bkvd)8y@(5`M&u0YrU?&7H5=OghomLCN22{+HElzuFFY77lWGxK!i! z9h?$jhp=srAo9q4xK6`@^EaCb8{lm=V>?IP_(9EP!kd2+GMp;&c^DBk`5cF+C6TTZ zWh9Y9Bh@58`7_|jJP9x{2-iNm2{4~O3}tCWULlPfZ8s1-=Ai(>S>)F^JkB-vyoSg%_`)R4HONrIo1qhe z^JeHrhp5Sr!$EEajN?h9 zM0nkN=`W5d{OK@~VV7LPVC z+i^xFnQ;Vgw>_L7;~*OhE{@!cgEK73IEZ2Q0q^8O#!*dX9GTpVqYgOJk<2)%xfzEO zWE_xYwjHQNYs9-su1z?sSMz2_n0g4gxb%#v2V@*fhS>RKzn~r`@JilICVC3=|bLoJQL}!qt%AIy)?&>;@31PqZ9@ev8mBEQ1hiChB@$e(K<3gpi<2;1Y*4c-+d z1?OqCVFnw>E1}+o(+C!bZc-grF!9DZE5@U9a$^xR6C4nfK=rDVVSyQ^;Cc$VO9>GkcB^Tq6HpSl(uM58K<^wjS}l;*yTG&LF_pK0jc{5-3CH-o zM&@Qj58B4a9QG-mk^2+_2Nz(km&R#akQ>v`V1Uy>u+^VE>$V2iL*IoOF@Zlu8WCEwN$5IHpI(AGLWi8Sb-jnWWAj*#UK z;e_Y!IhKra+?=77dv%x6z7_CeQ!??(irye(_2 zC_X>>8i{}ukbUqFz8l~!-UyrMgO61W);wRU^&iQYW)9^KHW6s+;PMCSXTVH{#Aqmq zaEixw$O1Yr(9px$8Hk$DfhmG)5>6w1;Yxf8$F4+}Ebn&DKa#PsISbnzx!vQ%HBF$e zK__YmKjJbzQAr|m=dUCQC;Cb#aV9xvhvHvWcS#`jEZntzfU65W-yu>W><|MDH(W_# z!TI-k2piz7B(a_Io%JKU`8OfMd;WYLMubg1$H6-kNY|hm?9iNU8`qP06JSzsp02gm z5T_9M{b4BU!vzM4Lg+9f88V4n0}aTZYhaJ%&oz*d@^`I~k=mOmqF9RKS}X2a|A`@p zXut4z4Uuc`g-M)ikfDY*Lnj31ZM6+`unReCqPz;C7EY^;WToGUoyhjS2tX(WLDBKc zbDc!g{x|5_9`>O*j6)|=MPsDrE6k46|MJ!uzC%o9BE}hJ@{Fm9(UAvqoEp~pL&Mazh&0) zk|B2f9NsM}pq^=S3hhy1z(YMGu!E?F2SDzj-jt1HT&#IRX7CW1CO|1u-ckw}aGP&j zOb1d6Oq+bN1Cfh}H>!L=UooPkdDB2(Ed1~_aS5~f&D&g zA&_FHe?6MS_A}TfL|xvTn6LysBLAy3PJ~SaS|S{40iZZtYp!YXRTqRG@pi3qhUi)o zPBg$P*>q^q@$H6s_DT_^4kpOm4P6O|Bnbssd^>xbhSm>upC*pB$>aI|NZW&b$96(t zD;WS#l*3)a?IkJbG`$MSl?SB;5s>VY#zM-Il0K9?=l}~DQMe9)4`1Q|(a!*gJw{m0tL?FRXAPxHoQYt$g+kK5W}10f!g(f*c%r z3-^KzZDJliy5Q}NC6sR*GrUnnkj#LwKqYUt#%!lBYrO~p>Mp=%p0*l4@nYmKJ0M9{ zl54pM7627W)Ny7su2C>rRLBR> zjvan*-&Q)49MRsj1uY-t2DTo|4v%*RwB#`4cPpPUo$)U(VBuk2P85_{oIcgpz&Y2* z5h!$!KqQi=YQRW356pwg6GC#^rc^pPA}UVth2n2-1LTOt|0WAFGO?n7c?e)q-ShYx?&W_+FfD%>j7)o3F4P)9HRO$*) zr53d`j5y35F)+^t2flf5mh~kR;9rDpV1)}nAWb4~Ye$&fwe{?ldRt&03z8%M(m;|Y zfIZ*7NjC!#UBLR>2_=Gmff7QewRKgyGjcjX3+U$$a8RbVBe)&e02F#$8yFID@}n^Ql7Xop5U40$KczL9n6o}v)O=} z6bc3yxw3OVF&9wtqT4qq7^Q;i?n$9oLC_4C^tM16;hD16NP|$NU0o`D(V3f+DM;z? z>{9$}Nv1q${||(79g?gMVjb=XX^NA}^5MA4W|(ORP3NDimP(fMJn%^8~?f zRu88b$W`D|3?B$h!6^n(T&ybmENo{t9qRTt-qvxV3K?0b@f1P@NV0u5DW&U)NOOP_ zX-K({!!>gq?h0$a8sTsy*x`WnL$|9lKO7`dz88eDQZ{OEF|?N>wbfqMI_Y_V^jU0Y z8y(c~Qn40@L6OhlL9x%NF+Ut23?Pwf00$UPnmc?GWfKde?GPrgrG0?GksbB7u{c+${8RK`ejIL}pPzZobi$nlQ3Lyeep!Lt|sY}6RQDxjfmxkDfR|774qzSISt2 zv2NZaWb~0rEDtq9fPxlb$0w^H@9sZdIEuU%3F`whFK7_CiEKbUdg(tlb2Jb6Alk{n z50<=jrIAqDaYo#Z=##KMWY5_8a3=AE^+6`F?j|J!TgCNCXTmBVsUkeFBmjFKc^dII z7mkxRY`rDr5tB*lO98UO)`yd~FRTyd;W(n~1kw=)c|0U<1Qck6#Dgep#1C#S0fr~- z86|Jnp7){j^b322Sc8=S9E6uoBnbblkfT#jWITlxlDa|38`jM}l*158w6|A8fD*}D zO~;;pyl|Ynk!}Z>L_^1k0y2{zA`sZXK7yQ3@hBMNJ<=U+oCUX9Ky2UD+s zs9_f@@g|!HF9{NF)D&*gaAYfpa8D*e=-UYQ6Ez(dajZ2pRw5lOWn((TtZbkOa~1uV zi#S}OzC<|~d<`Z;TwlnwPI+>=RDjC4QI+;Oo40a$FTL~5$oxE1)!5z#jE zCGawcAIz?&CSL*esXf5JqxPF8zFAM@3}6d6BLS?95zrhAhDsm~aYC;yp}>M*A5O?c z%}fjzZh4VZ48P08)8KvtnMNohe#P=YhDM|j=p>Ljvj%4oDig>oqQn@Ih-{pQagzvW zMs{{wL|HO4BgxbXwxpXHl!^*u%FE3RsL3d^qBX_7jhy_vz~U^X86z^=xWg6EmSar& zpj$uDfU1fzJJ``^BWMOh3}rb&RyvSGA`vy1H8}lJ;bf(MSVX+#Lga~nVQqm$E@p5e z2TjC-=*Qn50Yd|1auj9_s#RFAsfqAY?J$-j&f0@dky$%e96NBzA{45(qn~PjEn@8r zN<>`|&8aIQp{}rKA;lr<3XV8fr9|a~4h;j!xD?aplwyDv2#8CuU`{Cp0-_}Vi9&&> z)D03s3*-k1b1FGa0_+^%X%av!#HyjxB?~m9mOnTR3QlMi;v9z;BO8~h_S{l6`uI1U z7l#vV>?yv--1X{fscLUZ#at zUm~r)jK*TDp2wg}rm?$}sEiVOc7NL*W)Qotg2wFWZGXY;FY#w}G%2zBn_8*N^XwB9 z{uHnN{t^+^r&eky+|6Tm*3tUf`s`U3TP}vdONrE;J_@^sS=UPI?<%0~VfV88o;;$l z3c{#;Cuo!)c0`;9vy*zJmri4`+7sC@*r;KJ`XOeu#fEE=#t$2I|Lw40 z@V{XP_bEA9ZFjWXW#sI**KUuK;z8Sep6_$AZkU*ktVmuhW*wW^*MB?y;w*>hrv$^7 zjxD<}wcfZm);j;{dL85OBgC}sIfRcoe-!_8Dz8DimsaQ&<`!(1P_W%qxvi(VUuB zeyII{Jv`Vc8|T&6SzFt7fub_0r6cY_GK*?`7)6vnEjvp=q; zGS#H1JuL^PC?2gW}_0bILLR+okF>!!8W2Xo=8`yoSb)B zmimhc`%|3-vxUy=u|IvSP35I5?L*Q1w%E{8bCb?Z>{gRJmuW?-d;CJ#GuryA`c0L~ zHTr(a2=a5SIw97xptAQwTl~jf^9T#xf3I5b{(H@W=U=)u?URwxgszG2i|geK>PkefM&jAVcF->k%)J4v%oU7VW5)Aag8ZYKL0A>#Nq6 z%vk?guhs``c8%SdQmv7kj~-qsFK@(IR+YUI*;)7aUGjnhvD-f$n(yItg6X)OX7)}= zvMc-8|ACKsKhj2Y{V!a0&}Mb%4Zc(-S(LN)Q{7$nRF$=Rxq?Zxk{`SJ?Mjv4h9C1e z^Ygef=z0Nt9{1^*npEp^uPQI0p8P9*t~+TCv=ROFxzAJY(UUB`^>T)h-r1KbeM1@D zv*8#2Z@tEUx^`Gvpnq<~>c4OO&mz%E?a@e2ebCn8Mg!{z?Iu4$0BE^Lnu}W|G8*E# zmTNk*xTZ6XYdS)d6bL0B;Z+~$+5K}rtQMl^_H20UKhEo?PuKpw^*@V5H)Tp_dD;7e z-Dz|PEO~w8M-7@(cQzSm(srSELtMvmO=mRMbOgAj<1G!Zt8__q>pk)x?PdJwnz!_X z{-}!80u;HP4S(PIUqvFn??rn<*aezh9~}$y$U~FJ1)KC?_2+?NTgHE{zxEF;F`(re)5){ z-;@9M<^OLC(%E6He;`I>ALmfn?|!oF$v-ar_vQa{4Eoqh!~Q@XrCz~dzR!obmNuN5 zQi*V*8$1Yq81B_^SX$$s`#81#P}1Ncq0Y5RjS2;0Pxlmh?@?D)ZYbTaweyjO=cjGb zX+?s>$Chbnse-L7k5WB85g+Rw^|^iWnwAzO*or@notAb~u(jfm+QCo6$M=ss4txro znzl!<6@9EI7L4^AbSV(j^sE@TycEnmR55UQCb;cT#lR&)u*IWd;F2ilr|xRCKQxxC9GkxK#{XeiB^oRxxn#6D&ViF>pC9Xm_w;;6fE-xmFBZ z4ho)itr)mC2u^dY7`Rvq#vZ5`xa<_vJWw%kF%!&nsTjCy65QreL0tB9#dNbpG}KbB zH8eI@d_Eg_>n8P?+U3|#uNf|@3pVAMXqf5y)2Hg26x{qi{g6_A$KG|V<$8-fCl@5L z(Vw37?_Fo`k^DYRmCAHpUGN4T`r*?!{jgQJVb43x)%9zbMW8~iY2#>_n@4xWrOxJLb4(DSLe#5Ig1 z!s&Dl!<|lOZgT$-f=|%tbhfgzwN&CfMl?hZ1TUb^7&&a%B5cIqp&F_mVSySTH`LS?JJ+9V>RLSjR6>d%F0(q0fqQ?)K`Dids)}uE(Er zZ15Z@eg49ONf%Fgx<(q+UAJlt*X&cedH=ytMtRSakhE!ixbiBmel%U#$mgyzU%bF~8jjlZmn%7)xYIAEtt2$HmJw&zW^g!{VW;)ywzu7hM~3=D_(GlXKs0To51@ zopt8BHW|f{hu2)3CO>(`62HuesfRy)*gtD-=-x+CBW&XCtC}e0%^rQ;S-@}83&yPH zhMG<d08u=4s2H?|7IU_s`bER^j@WI;$k}l?|=p~kFZ(P=4xz>D<*!`5O+W7Wcw{N}+ba{Ja^p)Jb z%WO4%G2A*z*21Q+XmYf`xs^YQDQ!8kZcWDKR*#y-C7uo6eiSQ6tF=k*WmPtXofD6)yR>-j%l@dH$#U&3$BNB6ywYbj zG%mSW+Ty~!pc-MCE=Oc$Z>@Bx!QEX2;EJ0hJB`^G7=`UNf z9(Mk;MyMhDuFTZNRmGb$(;gV)2zO>Ccg&;rnlBYsNq_%9SWw`|h6|6Uo)(_4-^$!! zdD)S}4_3yAeOzI=7XDZ8=peoMWewLfExq1AagQJ;@7FRKcw-$>ms zSCI@%j7)yBFn8Lj>T`FuZ>+ajyFg)lb+fF$?kO|VH6@#UWT>CMnG#^yn&zMLCO$Xe zMnXr~iW1|udG?vssi~0g?lh&!piu6v~HB#>ExKWOs zx@z)ocQ}qnNOYlyZ)Z2(yJa3IBeq1}kSkLIXF8tjFmmZo3uG{g3a?WAd z{k`nI+~wbHNOWo3wxcgKwKYR6Y^`H~?vc<-dy{^cH#YXrnV;pHGv6pavrtY}c@cHb zIMCSY*~UY=#$;rc&-T+8-IcWG<;))q^-p!beXFN^c}LzX+gRtE@tfsrXT|SdtoFL_ zc>a9{t&Qhib?=-x&m?Kj=B!GKHM5o&oG6xm`2PyE@^~n>K0eG$vQ#5uX|cX;3}yyp zDVG|uHPIv_OV$Z#W;A5G??q!P*O*e0-YglC)MOcveTn48i^?*}HZ!ieNwVD$bKe=t zh(7N<|2)qh=llKsKIeO$-}#;MoCgJL7es||h^yRlukgAPjLwIEJe)Qad^V;pHeW)1 zM&&Xqu8U0jAbn-Kn?tn+vJBBm>h$svW|ZrIC8wHdKWP=vOSWjtp!%Uk8MY&zt=|ze zLibdpG-#s5;B=IXosNi9eF1CqQf5J510dMcX`9v7hvW5=#*kp0#LV6Jf?<~?d8-A9 zrO6ObWu6dF)=Q;Sqy&Vo*QF8-vpwtf_hj2PJeaA@7}6XxGNYj6Y=kSppYdfdPyJ)* zZpa9AG^kJuBv(67_4@rSLuy$kM+>(9t-pC3^=EU5UD@!P5DGrJ&QbOaF76d-ta~sG z7N0hJ{~!+4Sv29l5W~zWnSCS0_+&%B_poCzDsk&+iUpn4+_j}!TiXX?;NM^l>`*6q zr;Hx^IC5EZWUfAr{obG%=-Z!sA=L5D)1z3KVf9ny+Zyp5El|oA$^(|jj?5a9XnfAido-BU>}qhwd`#n#>*FYx=xM#lU!0-^fUAYv{?_xSiL^ z(2_JuD!@_%Qah8%qO z*o0#}HTVlv8ncjF-J?-4uF;0j7b6cd?^;=)?J202j$))Z^H~?kx?B!-c0Nt<*ifYLuUw7>n_E+N z`es#2jEy%7Sh-0&-~%04**&K`xR7cj(ztYcn|1L6Wsh{ny&pW4o?^vzAI;C|_2_l_ zsP|~sTZcCj2zT3KY8>m#`DaCcfTH#jITGI|s+eC@QSLk&nY?5rxzbWaRy6xI796DZs0oO~K?3Wo=PtK=5kHq z_ntt_`p&w9zSFU9BLD4-v^Gh!e5suo zOYJ{Udra+R@b)NuWB1otTYl$WjWWuVSm4mOSg!c@ZkSw~wK>moBb4XHwv}Zglt2vd zA`k-jUXWATZH09p&n8XGUmATtD2>O*J-sI?+ay$z_EBr!j3zFPqV@@19Wmqevz)sK z)7!ABXivO&nyoK`(;jtKKDqozik=}dsl%^38790dL>#qcd_7pV(wvG#g9Zu zrT?n;Tt5T+TbM>S$h$J`8p=eFEuxS*7gQ5Ssk$#P4rb2`Cgw*~?|{&o0#B&*Bu#3& zvU}bycBMpQuwL)zD$B{5@10DeEDiK>Ii*|?p_qUXur0VOR~T7kJy_^;9LPLMgq}#> zsc$vfkzLzmCBGz$K??~(0fL(|R|o1vPx1Wu1X|fB@+?}@T+9ggU@Sh^-99`J8|21! zOhB+Px$;VbuZ^ES6M3}mMC>_!p8a0*bCxyZ9j^zPHz~xwL6)DiRSbfU6aY7h@v`*S z#uuySQStV|{|~_5F0V8`U}OdG;{an-iyip^KH+uR`4zPC*vymV>8!xk&g6fLck3z- zUmnIAZypbyA;=Gl4c<6Nu;vQevRnW_^UEfH+$xs;;;;d`OtHMH7Yx9UZ$=4-4izj% zu;HGRfMMg9e?Np8waX0O&L6(_c>M{4K=}AtnBY7@pt}}xr&9=(3u5ulGgUnBZ$6}gp0@4lA4-DX-(%mH> z(*52mkB?9Ne&6p}??3N5Yr(qb%#P3b?7h#ubM97AK*zvALqofQHldvI_~qCKY~4#} zXx}i<&`5w;z58~y&M;eNLyf2QFeiO3cN^=%SS8yQ9-@H#yVCQV@_70hn$j(qP&GVHr@6ar9)^tCm%L1UwQJj8xYY5|B#pk*eC=bs-Jlq{D^zZ- z)Nd>DF5&u%$-&u|E(JBZr75CtUQziUK=2FZ2Y-veMRG48MqsZHu&z64c6(2vSO*8j1Yn2&Sn?!q37J0ho^sEE|#o=d9>}_y}t6O$M^5; z5~I_HCu1F~d(OPlHxRSDk8Gl{5Cd2qVM5FSYSmud|fg} zuJwvVtVXEq(c*CwP?KUJ`-1vDAkQou2-$EULD#YP?6dKb7tKx;ugm9mHALx>$^HiM zczKZFQh8S?fjyG6`w`MYiuL1{m0;HokvngTHl2^UUM%|OSN7c-tz~|5%KJ&s+E&kQ z<>k6jCWATjq?^T5@mh$_(=VGTf!d3&*;G(V`dUMECwKGGWKpj(DpTOZ>iNpENNAG_ z?U+9H(#LQGsjBlD+N1#A>u$Q(CMSHKZV92Dqy1#$pRAz+jJR9>LD@eAurCDujamO2 zC0Zb}H2|~Je-?AIbF?zHv$Fy#;V03Stvo~zHcxR%_Mxs&dDfRstUizR_R;;zD;2Hf z;6gU1`)pQ-{7CT&R&fTKJkhe!`-V-@=K^EL=0t6ydUr9R zaBkih{^GVKL@Tg#&C&D5OC>Q@`<^Xnc|L-NO47m0+e$Q_-UuVVbiL^{aAVPi9p3mn zj=qZfsH6<%Q=b+?66>sY{r#~$h@qcw`0}B=|BbZ39&YMX5mU^E`lj^JLvz{+9Zr+& zPDklt1O<9{gkf6K&QiyHtPnwE7{61^3mi%JcIHz(-I`ma|DTB_ zxF86m#t9CCIsZLP-7DNTkIB){zK@`xQT{{rhYByqXI!fOBU+0XnazD|hK;=ZTi?e@ z?Q0llr}m?kyuFU? zioNfOotzvzZIVb!HJIMm>OEYV+d3O)Z=V}jI$d9wBMdq|od|g@CN^$B_lREnd98cB z_pqUtJ6&xm9tGC<95fkBYGIDO^v-in! z&+~)R0o!6eZntNL-?rnACG@Y^Za(7P`n=n_yS2YWaaW?Q!DDwbeS?57USc9;@C<)$ zVPJpA>+D0r$@=a<>&(`-t%KH;g+|XzucdY4x;qV@#)jyN9?^(3teF!YN7?nA`)W&c z2XBW}6{n}4&TX3?8WNh*@6mHNjnkeVe_NZ{8%h_ae`J`wa`N@tg1eJv)p^t@_i-|b zhf`x&RDZa{9KH6| zc7x`YJ{K#OX&cf-1&w(>_e7iOXe7X!f^>KjggZYuy3KRSizd$FO_Ojg{C*F@)mZfX zB(0%I%%IWp)c#=i>&(-<&SPZWRHD0!$IH&8hmC#So_6W<_M0C!uo9IGQw#Fq4{#el zrhb@P={KC*Ffcs%?u@egcu?RC`N}_eXddj@@$5XjS^WMfzszws{V9L0M4E$x$HOys zy|zZq=iX1ZJeu z?Ltjpg)iUj#=JhgCK6L|<#S0LLO6D3KZ)&`l4)@~UT=Dm8_7r*PipNmrI3cjZUg?2 zHRk)<=BE>idrXQ;8wO6s#W|%zQhOd_OR|6@vQs&&{7~YcD)Q zAL||5Ftai)D=Zz6x&5r`yO`MUXZm*VIvPI@--h)b z#c%s}RYnP{MNMdx5v47xVN6+X@bOA`|98%B4pdNj{7(?ZROJ$n5O1h9*eOjD%g`5W&Sb-9H0jc>iP@g`muSMzYH&v?E(gXmo<)-6wpgq zLgI40iW<35xAF8eR|g-=NF}G3!|dj0kts(@c>9Ofg5*XWEgAAtIyao2O3QaMDT0n+ z#JQm3IB7m@-N2YKJP^$UnG1ks73GFtoa4CPr3(SzL>7YIQGR*7$#K8q4@o_9s)RD0 zH}|J>1H;SkD(v=9n|t;CCTkq%r(T4ofsZccnL#PaJC%KWJmy9!K|hevxG=-05=w#D zZay9WY7od0ye_5$uSW-uR?mbgp#-$66WF7Pc%99Gu1=2Lsig}6z^BKkSdPAD9i^$0FdXhEQ*YFK$OgLTnE_88`PBn*EQ^h;GN?z z=>kU(B=C}^{&(qSC0sRkaBY2(S<=1bMd8BtM+^Oi` z`y{HlT*%hkz?N9RVIl`gL6i$i!xcdj#T+J!Y)BnP#7h8|`WlD?;__7#neZQQ{Ru*c zZbu9V2rmU{PL&AoZ8D|X5niUqY@V1L@8jb&FM02R z2mwjmO@+x%JkhIbMNAr7Jz3)*Y3M>s!f3|Lk{uBF^Bg2j@@$sAU+FPW;%=%g~`aI1O`TO|dQ-G22^d}Ky z4@k*zAD?*&j7u08wSQ5kIJF2BI2wLkQ1tIIRcyEkD9) z@K;y^zlFFEcuBDUU>~aiuETs33OM-HK@052ljrVb68W`t5iw;PK>Qx-nd^dNDNN}i!pk_A!4YM3WnU>+7x9f{98~7I^5BTq z-X;}h1gwk8(_ELYuQWCV7#UBGiXg#S*FWkjHBEuB3In6|4;3zm03cSiKmo{&_m;-S z!oVG1)k^>YuvNPgcQG3dGwJ{gP$OHyK?5D7rbVS373r3_5`)(DS(=CdP#8mEG^M8d zzxCF22MKjV!~toox5mK^(zPy%OmaX}%!4EJszF^XklIlyx+>;^b2bOF`@5U`gD>%D{2 zazsP`s~WEORLW~%q*B#bZXGhFTNzVk4aBgmC=L-J2gvT`z!b(mmd2&PO!|x&Tno#s z6`_=03b{G;7Nw9{rHBY!(8OpduMKFT(mIiyQ?EBYlE?e z0HgMMU!hJT2{k-#^rjwHhSyj#gCojd{Q@o;bqa{fS^*NF8efmS3^|4>N2=l?w@Op` zDTatE>h)i$d1f{+Cz}Kw)eFJ%YkNUWsC8eW39dQe;kXA&hbyK^S#(?tmNka2y81}gixaEq z7fqQfI4xrORLb#3+z`i{76@Ak=M~qGV`F7owXqn)3Z67gtEYL*RLtOtt7MvOe2uM> zW9(>>fGXfZeF$*T`(@o%d4kL76w+SJRlL@66zs%6H@pxq!BP?yi>}FDCstj^NtUi;tMBAl_4VCj&W@>J5!=Q~6^yA+QWc${sNd>_~I2;zD;TNQ>62fUvNsMDN)|QWfbsF+lf$$xU49gB%Uw z8(u)>SPjw!n|W~t;GX&-yjV3c3a1tmW|9Q4G8+sPWyjc!2|wgL`#6Lq(XBno3EBVn5{|Z{RZy=HlLtOc>qMz;TnRJ71lg(p<#ec9=HgI zh*0J&T{u*nvYZ}pE=eiC2sjVEGM4}Cxtcmd5^*Id*9|=ARls?<|GGvwjPoWQlmtL@ z3y+!_KDEeJ1gM7L`V9tf2CU)wK>`8dLS}v^F40I~ zMyfR<#|R+Ks#@5r+H8wHbN>8l&K9vYEkua`Fp$|Qs~Mz%3Buiu3W7AZ8|&F<`YVgV`9c8aAvPpf`vYJQxhPC-#Gc z0NQfK*-340q(dYN+7K-+A(E}2wg9i1jq#V+whR|Q`=~9$2h`5|fvMLAo(r&~!VAv_ zSVFPcUgXCpJFs>gyd(}_?GM6Uz9r8>a6;C}^>DPgAW9Sf^x1aVfiP7hh2LHn0G-nB zW;o!S*hG{p^^ql+2`aoK$DYvy6~mhongO%UYvHtlJh19OwCsjU`gH(^vU$~%Oul4x zWN4Zw%+z*d7?}WwMk(_vc`Y4GP_=-zrwQr?aY_}Y<72MtbjI8DD#haEe}mlXMjyiQxpat zVAIz+FLPV2&=)UB5{SD$9#jg9d-S?SHLUjq9DhWunvM@nl&B^h{XphzNH~;~syr0% zPC+FQ4yNq&>jN?}oRN6YhX6@Yc+|3Bg2enRq8OlvnEenj03U_(Ka0o|D59>6E>i%J z09C#vpXG=t%C;0JB2$zzh$t;w<1SUjb3V8P;M|uFE(JIzQoSf5RY)%jP(*4FPF8?; zX!q|$lnWqwL?!SBM8tM|KtqP}Egn=8KvaN7tpy;;j(cgzo<*(=DP#vyRvUuP0cc-E z{wyLSP(%nx1tdV+pyTgFGzlPThoR;{M77}>E>sm?`QUB+ig697>s9v9l1cTu7 z1BgEL$W|n(hVlCiCIVT^?*~Z&hznW#Swv<)y7y+}m;uBU)PO|(R zc{>^ot)wa+0}$0v2~2>9gsyAa$#72LjoJaur}2{P0p|}=)-~M4^MQ@?4nU?Ogi{zK zv+w7|321+$5?BVw6uCa&EW^2q2Xz6o*YK!aK{8WcT8d_oyFm&?_1L&J@kZT%Nz$}+ zjd~E!!ibtfqB*LMAISC{>%3WTm$LeZ2u0rY+e-tM({7#}^YM*fx?~nGSs?CbmJUqL zm}hr?e3O$dIR;FIN%#$dlc(lCD(Dg%b-6re_9`j^9}cV>bM&InT{AezD10HDk|1=H zYM8M?)Gjj%m$wz}LH6CAw!mlT(#bpq4=F60S`5}V{ z{jogtw^s!+*EO8Q{~c@6rG6>EDo(!?E@(9XE=QJ`qZLdJ1+6kd;f$bFBF=oN@-IJR z5TWc3a5*0UR!K84S+U;!g8*DL0*(JWUIUh1C0*`+046}c6bXnb1TIQuqx-}0{{^kU zE&lJZatH67{|l?5z%!UjMh3CXMN-rB|CQ7q1*HUpnv0lI0L-9hAg^W+g6Nt5MWmr> z0r31E*}zGr4H6FI4-1e#KQR4$^~JzL%YPGS=7C@Y6ifyneSYLIkUla%`t;qZcu$mkd+SzMrkwi_zIOdG9>+J~TT2w$s0I z<8;gZj@SA0?AqGd$FqZlv#;OmJv}~hMGXbj2`%jh1~0A>_c%ExxMjb6c6QWz z$TC*l8zwfvbA&vbarYd!6qSdypI6-V`K~^Fag?{j$=p%v*7k~z9sQZj`R?bA&*t`9 zYcn%TOG;B`5TAS3-jI2&2L-8pKm-~ z7a9{CFwGiy_tv#?VE;+*6j5}vjb}vHyuBNTN={EF z3+U4g&d0|Lzeq1CF zT!nu0`<*`QWy=PmCAV@CKb(L665UEaZ5#zn|MNn~zmahV z|Fzu}&-=?XQd2}nfhg^JhL=1scgX&9A!Uf|$-EPX(*FHoOB{dJ^C1B1-6ouTB5e0s zZ|1X-#w^`^1Ahe&Z8_ol>mMS~L_?pL15mNNh!3QvDSQku{@=L3^Wr^dpQi9L{Qv0U z@&WS;!@vAHS&H}iTs~*`vrhlVmx<1Bm<{ZYca9h3?3&Co#R$B^rJ}!hsSdo9yb$~G z|HrGZbzLR9vD=i5o7zORRo~;)ZoN@&i=42v8D($~-H}x&ZwtJN8KXQqhN8p5qa4Jq z!yC2=z91*d;hH84RJs8BAY?*R%LWM#24%4pKCdJe~vxQ-k11+DktbexH zs?KhKAnwcG7U&{QB3-=iRDY_B*0}SXXO4J9N1dsVCYfHplZK6fQSx5YJY+-1M{O(6 zMu8%?q`uqaYI7Yg1)~-ZY2!Nfa}4AAW zBf2Q-UVNRgzrm7b(M*G3Ra`2p&GnHP=cO}dgl6Z_jSdxYr=H|^iH4_#w7}oj`K_>5 zolR+CPaVG>P>^hsM?OzIJPP7IKiuHo+27tYlsK*RWpHVsm+(G2wlmaZh>Lu_+gm1K zDE4f3ox=O{;EVs%Rrl<-euQlf+^@%&l7HjX-hQUOoQNab}{lZ3V&%%H3V2@(k!{4}2kID4~= zt4-(lO7COOz1bvYjmUmx4COn#9e5ko_u|@Ze5A_jWglV>ET^LTRfm$?AB?OklVyAe z&UEPRbr_c;<3hJ&-IH| z4Top5YbpJRu&`&nL~dg$&p4oznOTt)8v?YrHFq|2Ozs3Wn^5{GCJM0hoV+oqVcT{I z7}ekLYG7Jf70eqwEKSpqt%!g{Up3zh<@R9eeHr*!-q%qzjj|5)wo+hh_k4ox1!`jA46rwbo{S-f4fBc3c6Vz)jLqpSD90} zGjV@RWALM0mt|dDZn^4=SL;)xa%Fu)r~R&E7uHuajcP^FTZD&nrVzHst5+O%=?`JQkQ#SrMit^7zalGK$Uz zbIcw)`MtG#2TxC$tMuww@Uzb+iCyLKrar8pP_rU}%4PJItaveL^gPFCkX~W=h3lSFt@@vOKQ(xa(CYOVal9U6!J9 z-%V0!m**_WeMbqURKg;{1C0bN#u@V$L4^Loo?i%1~H@saV)cK}FBTfU}uJ+s%zp-nQ zIpQwPUbT4-(-Re?(EY(d1*s(Ck2h?JoO?-i*lcc8*b9h$`V!b*>L95WjoLS1V%4rT z*Xf=$l)WMNC}@)z_?l!d=1jn=i`P^zvvGFDCI;YvVVL{PI$KwjIe4Qqff9neTEdc5H4pt7Dqk z6>vDqCCSxzu}D7T&(8*@<=Z!-IZNpf$`TYVf7rZBga zr{7B0NTS}aTO9e#rI+rGlZ<{-Dt}Yhcj6sNU=Sr!Uew-?|A~jkR7J?5SsJ~M#nB{Y z_R+>n2=>h0hk%7up>}lhkw_Oetu=#L82L1dt~6nbZC?jz)N$0ic`T~52Jvlk8?0i7 z^J&|=!TJP)qd^_6>>`wDv-EBS`(eBKbRJILg8ODe9N)?NE!U;X#s)l6xld3{r^1If zPCBuS+}rP!T4T5;z8;o5nG4QwcU)d@J4GK+Uk~HilX&2>xiI84-D@nezqsWxzo1G~ zG&i!!)twcxw;YkqkdD#JA`XReB~FLxcTXv*R^PaDmUG3i7Mt%($h7Hy>CgfjuuSbt zR2=Q>|K2mi*!1l<5oknY1%3t*{aMV&-X8q;q1yChjgC^zO%!#-Tip_M^j#RJd2OO3WxGj@{<=X zY6Ze8`%G6~%tB==l3(?DP$|nzN3%Bb6+Tgxw>Nz$eq+4tv7URy=nH9Vu5U8k?c+UN zbp36yB8@>QHEG%`k8CS?sXX9rUwFKph-Ub)B%x@du>-@k0$;Dt%2~0xn_EQQF2Kjg ziZ@0&?^!|(c;DqTo{OLAG}I4d1*&Nl z%-;L-;9G*;lQ%ZCs#rO=aj1gF?OAPjpF}1C#T`3~?WTvbMW;uAb3i zvEbSSY=6an%hgWgI*Pz|k)$*2ndwe{#x5y_h&MP_ldBsugAn;l$&Fio>!~M9Pa9H* zA;@gL5iT?Hq&CuQ%bhgJJYDmn&@M%5z32Q?q`9AKW3qSR+2y}RL;TgQk^>M8Hy|2> z7q^W+_cKPs^eSKGCFeoqH{^NDr40FKnXNa1n>` zC{mInx-0pjK}Mlc_SJ&*8X2vZX7820SUpwKnL?3DVC5y~#Z|UPlm;i@vbGcjs%5&1 z=)&iQ9~%#i&6hIH?O_yRxOF5ml@q&=KK*2O^`V?2{HXwkzkgoq7wob*$?>W zHynu>KC%qPnxUUxE-DwwiC%u}HpdkqBpfhc@G*PREAM4$IE4F8Nu_U@Bu)WMAg4lbbBiQAM9q zbR<tCJzy@~jz78+X7A38reUH>;{V6W}P2XyuU$gdxrw?94o6CJqqUwlA?nG1z~2l)41 z+@Fd-&pO~1@N=Q|=S=>Oc)^y{ix23Y73g*c?EIyH^(XX;2d=-ju>RCWL(}|+?yrW{ zUyS|xx!x};fiyo5{Nt4GmxcdCAs2AC@W;WzFSUO^f%xTE^UrF(&LjSA;O`HdzYOFt zUm*YE@$;AJe}Zhx@|WBHUm5@V1HdnjA%9l;{c+%z(~AZF{l4={TZQdUPJiBo{;vM_ hjq;cJB>Nw!^0N(GMFI0itq}naDjh&ZKIa6*{|^fLa{2%O diff --git a/app/public/exports/warehouse/warehouse-rack-spaces-WH-E01-20260428175504-1777370104248.xlsx b/app/public/exports/warehouse/warehouse-rack-spaces-WH-E01-20260428175504-1777370104248.xlsx deleted file mode 100644 index 53914010546ed4394fda5fed0178ecb2103158de..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 12632 zcmdUVcQjnv`?mxmI?+jxBGJ1bBtk;;=w$>^hS58TDA7A1j9#J!K`?snVU!U;^yn>! z=>0t>xw*MF_x^t0?^^Fa?>lR;&ffEs&;C5mv(K4*9wj+UEIbShj0+euib;yZ+gLlotR3~$p4q}2bUB||Sr$YqST}Q%`0d@1oa2xs&{b2HY)(g_ zD08^i$zgCKS{-8L&>XF%uGTpiDq>IkJnhBKExk`A_U9()bS37hAM5M{MA2WM zadD>2E6X{D?<*<;XInfMQ16l=kH&jN5>BDmtt5v*;!%;r^NKX;M?U$d0A&l@(ORor@!f zE5(K)YNC4#j`GEje`t~qO2d=gf@lr zdx&e~ewtJH9fdfyaPqE4C^HF`zK_d+&W+*Qd4(H}hn+7Ld~?ft?~PV7y*c6eAYf^& zW3wE&W{}Qk3O(*(HkQ8}$LJDIH_u`;tUGf z;B;wB7k9BQR8FGetm;yNpZ7HvZCs;c-VZkg(QX(&8Tlt`m;fVBE&rtKp8~i)1pbX# z-|NL1AhT5fv$TH|bFs0vFto9;04w1q(dI4OBo8)D@QU}K&QMvFNCy_L$2xnMzQ}TU zOBuMJ)ybYZo%E#(uW?da-+qekkY4TC6AFAJ{}HDsja8OpN#R}H2Duym*pVqo>!{8h ztO&dt*FSx9Srxp*zj)c+{d%N=D2r|Prlc${(L)8vz@;q(x({!JQ6D?s^ys-TYr+n$ z4~%23;6ExZ#rx2!!I;1@<5_!uY!{;MBOJPPAnSWQ#lM@2Hu<(O_CsA`hL^*$nsV(9 zlWh)%siH*rIt0Wa8lN2{j(S{E8nMse$3S?j#=jb@JjP_m~Zm*&~#>pVqHTKAnvZOhn|WD$9_UZ#hO?YB=4p zsSq@6_`*P6MC@YIyV4Zc6!nwRS47WSWVgS+d1!uiYP&PsIWMnC@lkjYnLY13NuCn|q5?cf@MyTz587*NKQ@#U_%5 zP6=n{2ls|OP8;iv*LDV5rZ>NC?zb$@*Sn{CEUp>W2-STU8)hhcL?>FeYD#<*Vbgo& zttr+OxD`@Sl$v@nyJdQyPi)Gt%fQtze(CJ!>+00*aOz!#NBWt|$6vnAKXq`gIEy&p zI!YvSb*L|ms1q3%727?|tv~#FbaXO1xJ>xm;jY4?fXdtBqIb{szU&?@qdcH{-zo$b z?LBr^cLHV?2Z|I+HTCHu0>(Vu+%cxw>xl@aAnl$+p^i@uZ*iaSVBF>Qq>DQfezyzZ ztS|g_oKn{ys#ouRV!OZdW%^l8#}O)LD*maHYh=gb!}?xNcbilO+l{_;oOnh34QOgrm3j5?G%r7#GD7^rR-Zkd1_JCs#jL2&!A? z(&HOhWxBs*dNLuudsTjMUC+U=D63>xV%N2kTi`i|F;}zW@_O0zT`1f00#KjO&GgBZ z=KOQav7VuI6AQ!Af|3!bThBY+2_#z0u}Q^QPt=vS>U~nDeD3O88SnMsRM!SxL+9h_ zUANXP|8?(<(kPLoh|wiQ*~ao~N{`;vT)sFKGma^Lmw?=?!sxUqE!~FEGzg^=x6yS1p*mgz#`gFGx` zWwd=+LcH$hvo}ZkiO1BJ#KqgzjqY4@ZJJ}c1T`gf?eW#)$1O}SPLh=Ez1po!08TEj z6Xb0tOY-(!Wda8fqJq*34wMk}!``bjrjb$L05f1n+gBLhht=IQGPG2>6BqzqR@s}A zKrf|n@k_NzDwGCYhMzxkw)4Ual(LH0O>T@98nZWtwl%&MpfqT2PLrL|y6*5yQnu@= zJm?rknhiRRk>u6X_Kzwh0MSfPI00x@&@PB8v+VafwIKkU@B;8V>W{BC*zdRhDXC*h z6IaUp=Khqne`qN|nawVGW4G4VXq6rF#Dn<6|Iv?mCQyo6sJxe#+tffQ;5$+}Cngw8 zTnRAS#mfyq4FFk!*F+T)bZZe@(lMfmD+cXq`FE=$UT3mns#0QhXlO$Kuq$Xy#1)4a z7_%^{F{!Pw*a_hUaB_P)8TMWXrDP9`LcBl(0C`SJBB+;kh~hc+YXEyWL)uc{x<0ue zcxKs+I>8Y{aorl@pOXcpq2OYRH`tA4cB6|k*{=cqb2PN2K>wdK5j+mDvTL^}TvNN` zgv#1^KZvL=6|gqdvBu}K8_9rD5XFL$PD@w~A5eeW@T?LUqoW6*l;{F4! zzd&f$ZjS;15hOuPY2pFCji$8QLrdkEOylE9wLaZOwE_u{eAvs&v~ChF+r`TRD}JYr z2x0+P*@=P4j`#4!gu)El4Gk>V$@l>8D|D#nsxID`XqaJ_;p-Z?SAR%$J%+{0_VV(W z7Qb^s1c9XPB*SDUp6JxHASMkho~*Ky)pa5!VRYjriFSzGId(D!N_-s<1os=&Dedfk zg9J;0u?hnK+nR^8Z-7L9bV0D#38K_g0DvKW1tszzOSwhtsx#JzDr0s&K1$5kAuSUV zKy+LXAq)hXlLgfs-PV|;j)(_=?!~}*0ibfdynLoSwr0sNliudEUU$=YzFywgBw%Ft z`NM5gH%Q4*FRy75j8hmGwKcY#yubyyUl&0o*&(Xt*!h5*h#k^40a1;+AcSYx9o7PT zmLB2M`O2+=-$I;-JS3O_u#Z&$*CAeV`RshEpanKmQe`5HlLpld)K!)MBAy1s74`#H z7cUl=V;`ubS5mBY=K>Qx-m}-M$$xUe^LQC11z!7z2d2b0=7qRuF>@=p@ zvfzlv)+!lh0IZAC-Bg>mwyZ!>H;_{a01o=5U`sJ z>k&d}*dxM#RedV^P{Lzopj1(hv4E{`g;1Y+1)7=s9t0c3ZwU~=PqB{4}bqh3Qs z=K`dqJe2xl0T+kPf&@yV1QDhUniwtNu>wt$TgJ0-=ydAbTHt^f4hN&!Tm8f*4rfYW ztuVGAVAOW+3)EpGu8RAO&eY@b&?-wNa6}!bo6kw7N(FIR%|{`WV+%6D5oWQ)1k7l? zInCPLWrTOVBxW2Kfe>mf<@G=aTskx5hyso13>o2TWFk~C8S26bG5FQ?K}S%%)i7yUt!|`>dwLyHqLKeWE!4pJA(?}Jvy&vpp2dgman7agHQr%;#a?BdSLF)? z*wEzS@gkY$4mFHI6)5H&nLFkd9~P2c+X|?oP7;tJ6{{f%4&AmrP*>}RV}O}9bbV~auih8t_>HE)s$&ROA4F%K3GmW>rM=sD}mtMp%W_L8j? z#aA*c7&Db|m__v}AqhuZ5Jwzl2x}_GW#^zHLq%(qu_(kcfh1jvyJ^)_)X=iCc#3sw zm9>L?^k@RVGT=gW7;w?^am`zCg45vy(pJe?wAy?a=)g$-Y2I&wxi};mQ=P3wwA8}A zHNg3qS!|AT#*lTFS8$c?0=lgJNz{9 zZXq8d{oK6dBy(q?#W%`~+S;x$NBiXSo7`MnTT*6|j}t4X7w4Vyv>5D&S~2Tt(R56% zk@jhZS+SA!=n*WtLpDU3YYna zK6)L%KCh472C<)psGU%i9dp6Y0PN?v;pgK3?B~i=`wucT&Ov%GbnvLoLpaW<0x%o@ zfC;f=c}z^re?cCAdH&iUmJ|mb0TjEOybzy&7Lu(-n&}m3j+sG;11Z4N!5hYb5Mlw^ z7n^!`S_CYJ9`H3Gn*F@R<(i^dy)|sXY)!!I*Lw%B`2=mu4IrWoRTH2tv*d;gegfF! zhTjGe5liLKheGdCBN+ha;?(?C0Ox@h#&W;9si-n0kd~8kUMGNF1e_y%*VK?OjvE9} zG62y{0$Orl^15H7IbH@O1*8BEKtur{#0L<4XqGPXQx3uR8S>-sTgCT*_yfcRP5(h$ zyn)=bL`zzh0YIEZrLak*$tFYk+}XvfO;XKE5CtN@KzfU`dVn&D$j3Q=!;g*FCp!Qz zuxXIF((-0LK>Vl$(M%C2PSy&n^FnblUf)dt>~tDKz-nt6lObR==c0g@sJXr;jfiTYVYQ9uzf`5>YIJ__c37LhSfM4f4! z#sDIInp|^U^ATgTbqP>J#%M8$k4khW`zSi1pf_niNMK0aP78lutmb0U*kZi8N=+pwxsEumLHn2_a+$ zv@fE577+?4B80dc3LtLC{*NM>1Q4~s&~qT7>QFT&nzApva2Ej4H(t0ah)7>5uRav& zL4#}noO{vmH-SaO{j-P+05V$%poSosao>xmod9YCAnG8XH3m6~k2L4apoBpRcmYH( z2q7PU=tH-3S-f%xpU+S{ki~pHkOY9ZpoO1BWCEmnPg<4+B!kigQXrzk%DF)>>Hv>ff`H~nRP5qS(Y<^?wr^YJ%z(R;MIRypvN1;2XaZpfsLpa1i z=xFJ-H06A8p9NrY*at!=0Zc}rr3GFqhe-Hnyyl>Y^@FT|lU-zZ6;9EV=VJ#%(K$0rt%Ax}iYS*CVVer>saJe>tbiZ5aEb6$l{ZZx* zKL5qps=mnq%vMmpdtkTM}KTa8Kj!C0;>D(W0A2WXar14#my zRRYXjftvflU;6=ODboEYL9=-MQLKPjPzEq7fkaDyX0MDYwpk!9NyD#>s@Mg=UkAZu z)x94elY@uZg#T+NI7z)kRQLx zAcDUyPc`o%fBKr5ne4*;v=>DVkddH)~)Uxi5R|BhF`#a9XE`yYS_&@Vv-q6&hGP*`bycl>`r zD{zbdJyuV_d*}bc>L~CG=9HF3YV{+j>H7ap>i2?D07A`4%E1q2&`Th%rV#>|>HkHf zp(=jx-0#`IL7@o}4&)CrkU!rs{l5Al;GyNe2{hASAOZ>|1CT!7^B71UDIk4%ZQH{iM;| z^T6yZHI_KFaD%?jdY2*9MdYN(qw;k7;HW4f;Al}l`SjcAvaKk+b%W>jGtUEqv#;Cz z%hyjfZG}9}KF_SKp7x#Y&!2wzYU}RW#~CpkP$Rgw7Z5PpGQYFQ@8)`ZMs(A5>-6-n z=YV;vvL{4zg8LA4I{nmr@LWU=&R$MY=fE9ZhN1{hvE$jpmd&kYFB^tatFxVf_5oAd z&DH7Y#YKgwQ?Z|i>p$M>yqumt=M22QAiIQtLH^^w+yQQ24>MMEv^TRhbpQ{`-G`dY z$&{)6r|UFHO^Q1AlH)r=GwrSfQ>9fBt-&#SGM%&2i4)l)V@g83tv!U9u;EAw+*Zl<@)V$aqe zuL+Kc3>s&Qyv=hiAKZKLa?kXYS@QPKVvSQx?U0Y?^4idVMa|%dSZb0mO+>=-(~sfA z^`d%T#O@v+&V8LPP;R&!aoEssmU!9iIr`3#-QwEJNvTht3snUDrTSBn%buR~!^I~j zllcs(dS~Nf`d`FC#}7AAGi`OVr6{U!PhmlHXM<;l=|lzR`bNu@@SbtIrkRO>wlzVN zKE7N(=KT&Yw$dfN(c+s~@gL6W5v=%xpVQXm#!r&K>0!2l?)2yV9o(Y+H4H|up*pHG zu6z0~>M`8U9iHFDUcyJmO6cRcvutPm)XV{cRZWBtEzLEyo&-}afxNB{q$ zi}U+TFZBQR?|3oRV*oj;|Fcg2$CrtYaF`YB&v%YL%Go)Qd+G}C4wr`E$4hnKrQ{E> z@BhEQ`dZUguo=5WUB978QeE*aR^{d!)zgG@|S8t-?(QAQ!$WmNgPXj54c86J@V<$ld6|GnD}RZS@BNpqHlo>_;w=v{%Yy8e z-60IXaXd|Ikh@E^>S88*Bkk@HS58R>*6r4}MqZo|41}GO(Egxi6`2(($<8- za#^dTE_a{Wn=5V-(Xy!TXL#!{Acu;q`pWouIUw+csg0dghg=q{8qR%Peg6u`nrp?& zw=Ew`ef;%$a?2>0s}T#lu)49e+p92H)eIzpWo;B{k*}PMn*e9et!QynBR$FM}}DIr0i^?~n@jE7IJqP=d{CoRAmNvGi=T zR|LX3scT+*nYO*ooMP5Qhh8?X}Vysx*vx7^(-TObA@Q$$TbNVsoIJTFPcCr92FC!mszrF!-e7mxIbCtj?BW5%VcP?obptoJ z+LVsg{ONW7@ocHrbuXgjCt&Zse!5Aj%>1l__yW%+y$UpVgUAUx*6l6&esFbM0w!PP zHJHgn`W1HcNBFh3t}GHF#7ePz8Qxa*TK*D#PfW;VwOA4aHy=!+Ed_|;iRygRpYS_+ zvW}~K&hnPr!<~JzLCO-A`P>l7dvMGD7OeNhv)h4(8C#JL&`EXxz6 zyogS<=Gp5euR`qsHJwpUQDVq8My_BKpLmyfihx@)0q zEB|fIrx>T9WW3~Fv)fj88kKY|+|;-DI82+1{ZcZHluJ8QUbSU0xB$89gXT(UL9;gT1_Hx)IFfdbKCge?ZpTUO9!j2Ax;VKelr=LHXRQ zsq?A)V|9V7u&oNW^uSNVwb%F!$%+G-d^8eV>0{nm@qhDrv26p>*5=%*eL>lv*u{ol zD%7Ygj@*fs#$8T(ckS|u)TsL1+R{fo_&c3d+bmNDxSWXVI8(R;+;5OFw`pLMQ#!w&>KTo!!KU2-;otz z8#1)VDz9)7BQrQ#E6&%A!KLzW9h{kZ8+?{4+ehZvLE^FaacRsyp}Z_a<@V!KyYL8l zFYGZ}+{Aa5vhCd6DbA8Br-9E0j^jI#vBq93w=PhwMe?Li+7-{?EBAWrBrwqI^4^hQ z#}+%J!bp^3%7ywH0F4lsX|A#v7L{1~aDNwkg~CRJ=5<{J8T~Fmu9|+YWOf z(tCqk(#g%7eCyLl`|~k-lpPaOjzGJ z$rN@6Z@1F4`|1-Vh2XuRAvuWz!@lcQg^oSsTC7&r%WU~YK791=FR>F>d5PXLy2_$i zX{yyVqc443;8DOR8}e=LybfpO9p}f?orcdER7cST7+F@_8QA7NpL}x&E^l8An)B-q zEBr$7@}jPK?Gvst&iCGEL*w(K6+GCan=SQU*>jO4gsj`*Bjh56alYNkEsz5l0eX{h~pGYTU~2qxiyy$ygTu z*w1-lR^sS)Yi5T&v#BLJ<7A^>6_9TVdXGJWiS#0*kcDmigde!Mjg{JoGJU3ymsPk}v?VfJs7{pM?urDKDx$y~?ih7;j~ z>&G2922b1Wl~`gujeq?~{CGAn>#67DJry)=_+L7-zy>U1 z8zUuq8{6M|hORVxJ&Fe!5m|trK_q__GqAMHJ~KAFBO;If_xxdxChIs&4m_T>t(4jm#xJiOzRd1@G+K5)q*$a?wn(qJ33H zo$g%zWI(2u7ugjvT8Qslb7;FA4vTC=JV|Qvw&E$_JCI`c-lCQ^>W=aW!_E&n4&8cV zZpo;qGM244FM%1|^=_ds583RHLr;fnjo3Plp7lo~wCE3-Uanm-4 zdmytp`8UfAc^Y-uSuwFvP6jRo%rxni{^wke@7>>KHyxqK@h zESZ#JTuvwF=z*%uNl@DzXQlT6jJOO^kIi_gZSt_O4j;}e3)!W5h4G#qobK$!GCZ2{xZ{3$z&d|g z*Ps_y)9#~SG>2IY!MFH=#H{|Xdu8%4Mg*t%B#Bt2`0bS^@fv(z3>aHsc$egJQiq=m zYpn|u(M_n2uW{-tKDv1zld{+GZV}5<*#3av?;Dk(i_(xj5XM#V~VL#%C z0=r3T_t>sZ`Lw9=*IH>zCt(rAUt}M^qs+v5h*;KbR_HGCqsk}LivE1wCi8K3 zkM|c+1^L|B=kMd`p89>8(-=#79pLV)1%B*NPTu>da} zy=RL@Gna<$pME0E1;t9NNyHX#$m(W7K&)l^jC1Y^kKl%+QWuIq#P1Y5h2o+2rPqX({MyeHUykH+0sI|_C{G+cma z5dXMs{I#DkEUHKGJP%37#$Cw)kuRK#Oa6YXZ*Zwv&eg@Pv-5AWS;a=&{K`@5x@{;* zt&cNnBvkY6hChC+qUq>Ck7xGf@Cw-|0U@r?UigP_mUBG{oZDA3B1(^jD46bYC-a%{ z8$05pgg>Ne3A4+u;$ibX7&UdI@m9!qzs1D7FxKwf{;FB1?R>R0>9f@r^B%Y)(V@5P z#v{nd66i1FiUb%0OW0Nl)T*VmoSV5<@?zygMQaL8E{2m6rxR1&7FH4%htJYn=&zFg z^tLv9_S0j-;jy`rE3>;;1z0ZaiC2-NPUO!%*j#)lV-J7E&+hA+)AA9wbk{34FF5l7 zFT=V$DPte=P_zl=+4(}GVAji}$1by+VN#x4JWkgGykmH~mDKNd2(InTTz`!v2eDPX zITX6V{dj(8<+wk}HF<83roSvbb#HhhHsWM#`1GLk6z80e#Wc1ec3I|mt{R!id@W_n zS$TVM)p*)l(lfnj_5IS9PtGgJojXsC@jrK810nj$=U;lUe;N4a4^psc_{Rs_KZAj= z|7>*qyVKvBh<|EfU=;qT^S#sce{%-*+Wz=}&KiOI`rdi_)6+lEfm{EN52!HxL*d^6 z{@#oGQxWJ{2iyXFeyII5lm8=Lux0hf2XxN@bh`s~{?@?y6Z($_uHRc&e`;f3sQ*Lv zS3~PB#{T_W@0S&Sy6*`7amx40!hfQW6F6M>^I+kZ+P|Mb{Bo@RSG8Z~5x*Pw{eknB zfgGkE$p3u&{H6MzAR99O?e_n7#(#eR_~kL^uWElh4*YWZW5K`QcYbLrvHr#B&%4m? j>c4N4ztkt${!EphZQx3B*xzf71b9$s2Qt!)0~G&1sxWU( diff --git a/app/public/exports/warehouse/warehouse-rack-spaces-WH-E01-20260428175506-1777370106125.xlsx b/app/public/exports/warehouse/warehouse-rack-spaces-WH-E01-20260428175506-1777370106125.xlsx deleted file mode 100644 index f3a8a29eaa031d6bfefce344b8ddd990b2b49493..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 12632 zcmdUVbyQT{_csa*(%nd?DBTDMil87Z9fN?xz|akf0@4kFFm#uQfWXk*4-7G=bSWJI zBHi!3`uO zV0^{Gz#s=^_3zo+xxnmPj5MD*z?=+BU_?FN#;ZDZ(hJ*RdV{* z*!{N8eq5;$a8o*cVzuym-IkvAc^E2cU+N+qS@*W#XqnT6X?g?c`PxVNyFoFGmuTJH z=-yQ1U%>a5kcV?FT?lG)Pg6qUy`uF$fDjhW5C0Z{kK$cIjKN-!vm0owki~K85LTJZ zWBO*%@!!0@HvIO2EzaqQic*=rtO$|Q&Sp31q37J0ho^sk9*&%&#Y?-}d;Q3$NB8dT zl43H2C*vHfdwzapU?jhAX8D3pqu(|*xBQdD7AfJuxxraVOQra(jX%pOD*HCs*wJdK zi8yD#Dwe*RTyoiB;|A!0@ zC|MNKqSD4kaCh^$%=~eZo!q6&+&bo*sp~>_ny=Z>S43pD`)zE7yu3>gVTlvz_+`lg zwbmyQu^OSi$3VbUNJoK<>JRE~Mx9wY5_8}~g0A8SIOGr{FPfh!T~#RPZiv#Ol=}_h z5q*&1T6tSJfise#=OM~cntkBoO0ZjVGyScB!ypdmU^8mk-X8^zC$@Jbj3N*oUkwvMdM&m49a+`QdSj;;_NC!^+8K6sxz z_dGv19kMGC;B|j?_;ow}SkmCK-R48ytq;3>yIcE9)VC$;8a#G4(>I8S<0Yq3hR+D+ z7KZjmyv~{%PS$sa+CFc6-8yJnS!ndk@>*IqsS|B@KQY2o{E%LvVayDmOhlIliHKlj9#>1-q-n1OV96NS4xKDx+H74;3qg#GA~l%ejp?8ukym;>q>B3p2}x?pAtqqn}^dgp^Sk-*OqD zJKKet!iu8b?#5)EUcMDmap^;89YQR2XFrMKnX*|)JV9T2k~{fW7+-4bGv$zm#U4Y! zu{G9v+ZLx&N_$t7mNpEXO-gdhMx^&Vy7`2kahvhBx~yzeT-$?kJ}UzC37=a$-qu-o zhB?tUykTx_QeIRxCVTT)_dDTa+j&me1iPt*%67w1Evjc8Zqx?I*@&Ams35lYxALB}CA$t*;RFKA_RuiNK;|mFkvn&S}4EIpFjd+M1EYd;PZr zTm`F(i`O9v&&n{%$sv@Ul2Wp&ssa>zGJv)7@(ZshfH`HUP7PHuNur&>e1(KD1=*_WR@bM(0`>@j{uxp zCnPS{tEy8O_n3V8#M3DNGgi$l;WEEIUTntI8s5>IDNJSD*_xp+qkGNysfHlYld z?GfMupay{~!Rum533_!281zkP6G}n5x`Dk~h|C-=Obsf`E^R#s0Cp9vgJ5xvgRzOB zno~NOOI;B@04KM0QenS|qEwxLQJ4>i03gqGSseA!5m7qNbroPQe^^fzT-T^Of`5+7 zv>O~jR5t7|{yAAx9u6+Hbd$?;b}zOxhwCcfKVMr<7W6-=gWz|LS6IJE>5<-}C|c1e z@LpVNxrn2sfg`by%Tykef~XXgg)4z3O1MlHIZ(Pzh-d(p#u|tO;`&7#mGB>M{Ru*+ zUS|vlh#&=OL7NEhZ91dZ8D6f$YLS>wt~+`Q)ea;;>QTP{>xOxvLXQAHtn{50B7_}a zWj79{Fxe*%7Y;M&G%>d3A{PX_uhOGpYkCCYVqqpdCYg1LuYQ;8c?3&T=ojF(D1GOO z2mwjmO@%2;J=U*lLrj}kKVIV^Z|Fu$!{{f?lN}KS^IYW4RQUQJ2)@@EGkSUd1__n| z;}8P?cC-%bT?dK&=#F4_6hUdK0|3JUiprEgmI_L^G-mA(HD+9bf>fCC!@B0?fas(M zLJSBr4?C(iwxc;$3y}x{-H(Iy13(q~1q3bl9V}B}=KZZ1{hk(yg8c&VDZt3&)B9Vf zUXYUGegTUV7>^h*>S*pbeSr&dzafrFaYWS2a|r@D5kIVF4x*ZLM~KaFIj;x#EkDF* z@K;;|zlFFGc}cSYU>~UiuETs33%LX}Knt9xlC4gqL%%f+L#h%KkF2F5(-@xo9o)6u=R` zgKa9z7+4pNr-hzCe_3n_Ff#cxehUTGy1`L@nOO>qT?`m?G*`GH0)SZ60tFyH*;f`D z3j=q6RWBg~z*g-}+>hCCm~kgyfDY9f4jSkzGb=9Rsz|rWlN`3G&(=Z&fWlak<0&;g z|E;%fQ54h(5eKBT{u&o2NY}bJD#;O1F%OO~tA_QoL2Ad{5yEp^*4^L;VpmlD7Obp_ zO)hI7;1xMsoIqt&Y3pg{fucGHVSsL^03wbSuxic4DF|AnMeqfc=cy15k=au+45pn$;GMTvbDsL;_z#oLXM#-k!tv;t+JFs z>Jie4dV^?n&#VU4WYfUIdZ@A819IoUR#zGBee3tVlRV44>jEQ2D*bBuuPPS_u%W4? zlO^)coa>lHt59rx^0%$5-!G$5mNEURNWw99#4)!e!j9Ty#VzF6M8!^hA_lQSAVc5gX;Cv1GrZy^m1Y-TW9RG? zJDwz@2Ds1|0bKNbT=!L(;&DEObX4<{thF8mJ2NwmE(A=mm4?M)YH`*{lv{hY2f019 zjL&z=9=7Z839T`hp0LHM?)Q1(6ffeQy=+%ptKYlvZNpBZ)s?9ILtT9XeTTdA?v#mF z{Jwkgm11Y+v`-6!(`>C_?WaO)+E1PaR^iUw!k%R{Oq-2>*2_)m_?d*qk331fQ!L2L zIKLn>&DNc4{f#QSzP@L|#VPgT79TI~wyfp!qvR@@r3F_*T_#7OcFcx)G(D?Fv{Qyj zZoGwuv1hv&3GePVP5Y0lGCe+4HHK)zl3a%lL$n!hZYcA3m}Uiag$*yfYDB%-i5FfQ zuP#HfDf4DJ4BAMIoUvwq)Iu%vS+U?s@WFV&*BPzX>?C~$P(12y*xZNeZ!SR_-8d%8 z%0m%Vsp=Cf)?&!+UjtuuIK6JN&qIk_32n&bm%RSpj+G0ItX6QaJxrtAAkgG|0 z%?rpJ>tTjqb1&`y{8L|q7rPc#(ad7P=OkgAtOg^+&!J5j-9`$OQajWItGrfYM(7Oy z`+^aA2gH6Brg=(Tal#8f2e4n{gI`PluwSUu7(C3;z5waN(8r^`2;sh<0l;kj9VWzv z{Sh&Z&?O}R=EbW+ShC!B1W@csieh{MI!K--X^u~{6=pUS4x|WEA8!N)LWl)uleP5m zw+UMl-4|>@v)Q&6<#(KC8P)sKtu^4#0L<)Z&1Omi`eEyxdL}SIz z(rp>J#sG2F)new==37iz^XFu_TckP+5M?63KvtWaR*)Ks$j>c^JAjkeFE0o%uw|UH z+V*-ONb0x^(MlOCMcxjq^HOOl-oOoE>?~Rnz-oI2s|jE=Y*Zycf0!V6I2dqG>IVq{ zwB=25lGjV(x@T)7Ee$493 z&@xs0T-%vpYziP6rzxo9w{kQ^*8n0USk1z3KvNF7vAonSLzm%9sLd_H<>efHqHP3Xb@#4o%T#fK6;OG?oBh z)7K_HYg@j^mmoQChg>ZQ6?G0&q#dxvv0R8gNdc_M?c@Abo5=5vfDC*#Y9A zJ--)G9)Rc}t z9t5;7rtX+%f$kRsvVF%Ue-_-OtOpRGsM~&fX~1$iEOKH7UJIv7WdoCicl^xLfyvJn zIXwffbJL|JfXOgPzhQ9l)Z%*uU4Wx6B6DZS&>4hqVCC53KMLI~gPW4t7s4$CLPyJW zWT+KN`7HvIBYqG{_^VgE3b36^lR_ zzI19Q?|-x?>1DGX$=n<$E8Q z8al!y_7W`%kU}>oO+Og>1}g$CFPxP-985JHT&el!DinS-Nj)xul)FF{`SH69BJ}(6 zG~SR2Wvy$v-1&E`Nf!pC0jqd}()gg&0JuD5R<3q16%@3}0)?}HR!O)Eq>&%L%OFBI z@8fgd2dq+LVYB1B`3C{`>O`9Vcf1BHy-K<`cpprFL1}UjRR~<1(pK-g%WLJR6PJ* z@I4#2DRn@?f&5_u^5;9IzpuUocxd@=0?j%UjDUj40Hn|NJO0kHZ#jRC9DU{bynBl*YjlPbU(`7biHp44*-JjreRe$wdaeQ0@} z9#5QJyvaCVx5t$3E`HkLReiQ|cw7<{bi8DgdiL#X#X*A6uE~4nsrRAr`PZGnm20P4 z4x(P?pJvzA&IZm77S6tWb@22U;E5UusuNk-4+@%VTiD$adhT&@PISXz`|Rwf?~rYx zx-U#(ith+@_W6nD(1oacoc;Wg?hm&Om`b9&B~Rv#+P1b=eC(OdY|nQ;bbhdK*joGi zd1*;`=1lVE;rfsFIxjyjTyO(kUyw6kU{L%xFn5LBcD;W>^hq0|}GMC)+Oz8tr_EXAqd*KC)r_?kFoUJCW4FPv63-Q@|_ zW&J3|>+<37aG?8{_P}y)#F+M`N5u!FrCn&2hF^}((Asu{rKc-*jmy?a_mvgl^_=Mh zo4z$G?ixMe?!>JSwGYUK1*@sItjV@@p0zXf!y<)aIby;y#j6YRJ>&!3@hA3H9s&z_e14Y*TBF)}oskzDrnZX78+J)JIO zN;f>8oG|(#89sTmg_`YXm@7w7M|z8ipu3yAyDX-vcs4fMSR(r-9b0CnK6I>$pp5Vp z2Qlw;`EZsm8;+OW$W45I-iYA9C;XJLp*VS(0#1)`7WHO58|>nf2&`i=g$*}QXYk%N zdeMmCdEw~d4)!uWI$qic&y#&8_fHp6Mi5Wh9T++Ku*D}rc|#P6;)M`DPFKDGd$;&_oB$b6#qF~a(P*Bb4SQ+BrF%#Pwaa*D|IKr-wYmDve2BMt%0Fkv0R zsBMt3z7N%C?y>OLEt|{ergu8SLF~y^Dc7e|nZ-n}>`H7>&+M~W8Z|jG2)M}k=SZyT z?iLE;NB_3K7;zHm>MdIRzVfA}=r_JO(iL5eD@F9lOa@)_9Ly|IccbPZ8@fK~TY$uOcOzxSBSXBs%w+of2`rmu$VK0%#Bh_|4ry|5@#S_8= z9LLkfhj_Z@X)NWyH#6=W^X8XzVclwfYwE)j#YEU$T1L{Q-Vzq6m3*pqGhEueo(YYejMFk+ORFc?88p zC4f9T*JGhuy4SB2-Znyt!F$KJ1+xjm-J)6O`iIr|UXd2`gcEFC<$=7Ai)ZAdV-b$% zrm1`J<+H;zwlvEYdMxXbGBF*V0am`gTA~zD*VRJoWG>i1++(LvUw*d(%krwAPo|wUtTI`|Q}>NQ*fx^7(FGxulWA zv)y%S@6&^i{xf7xa^`}Bu8~c#K7dCBeM*Bj@}?uV|&^~e2IUHQ5_n(N#u$h|NJfbUTAGX5~g6zRhaoy z77G{pBmC-H4|ZvBV%2!TY+qX^-9YJp$L16Yy6j0JTlYVsZG?#ui5mR09t*j6b4;p# z%Jr4m$DMnoef-1ofW`;^46_7zF$PKYEoML)(%YGK#;Vowr88j~|w$>B?0^z+RGBY=-iBTk^;d;V$V-D-{Irui7~|gA3Vri=v11R@)8pB$e?irx(!+^gF50Xo zh1`vm!(GXEclGkB?6}sQ`tpZ;_`BUTJM1%u2BPF54P)i_IM_aFF|C)w@F^YO299^9 zd|s5xydnK^PxV%aWiYEz;f0$Fh4|}Yal`$ zSCv;YB+$<&JOA>XvHG&LJRcXu{Q8Y3h0sS(xd~nWtKMHPFua0p)<^XXRrFWpR_;vQ zo6sB{uGefDa5ic+bpkLYsPmFmX%f}vThBz}YVkkJgn5lME*X;(pflHB-wy|mCE4wu@?V`z5fZRmM{!T`B<7m3%>$K{E@q{@mg^;?h593!I`eXu7S zaFgHJD0K4mrn$+io&`VqaFW=Kj5qUPzj=vjJ(@pj+Oc#VU#;J3H;IXMPvEvZ8=jpr zrClfbW}feiZh(=)&FwJDmh>r!2!Vt=NthWepMAylXzB8#+N17Qp=?Rp&v)61k-nQ0 zGOo|9D7Ht(I!~^3DSR?K3uDZwEn?kYZ2EcQ`Ef_VTB9$13ACm>2JR|^zds82+!R4JRA@c!)5yf99 zUy>PU)j#H~;Q7rLZDMwDyow*2bgQlLD^~%sjF4kTYK%fWRps+H`4xK(_v_U$Eu4yY z+(;=Zb$%T3=7Raz;IsmV77Q0@U1B++qUGkz+axahp=k_u1)ucWF3TMeoNl^d)#hHn zq&B%yj#GwZ*DR3jB${E|BsQF(((-nvK6Qq3TKry=6pix5TI_Fj73{`0A0`^`dax;C z6>?$GG)~kFttN?PSD+8M*u|zSWdgD#WC-XpxD!aC>|Qi!Q%~9ke3V*zKON5=82{;w zq^%VC-MZzG-&}gx?j-s6S7qeuqW%-_P$I)9S!8j?AmMvHJ~LGj%N7~Tel{o5nAwLL zpF?mz?==T3tcrACT8u@yx@)f)&cdiZvFXVWx7zi0QbZj`y`9IQO>4NbZDEU3;&}ea z?sl*N(eQXsryJ)jnzUIa_rm?KT?0lBXK&$s^AWCZRD)LQGUXFP9;v)1=%!P#!)qs9 zIL1#p?v~kLJxR1bJwq%_Uyl=kMnrbtXAsGs#f%*sz@I;<>QZ(Sd?fYzlovPo7jiD)`I)GSvOCF< zV7k5E4utC6XNzGL@tq>xp>Eh4RUEuGxS6voDBb<;ipcHVo8sa$MD98%wsfy5XtLZY zAAgYV7eMyJjThs))g3wPM8cw*5syBKYQ8P;FgZ83tlwzsoV~4bG820t7PrUxs_m|Bp zF)n9OaQ8tq=cTE3^Mxu*5mWctc~n}Um*}`kQ*Cs1Mi1nqyj(uB3oPW7J_g61&LYvevf7PC{7%w^)!W8zVt22<3w%2FUHL6FgymO{PdB>Bf1;H zCG=BTlj}T2Di3cQ%BSsjy<5Wa7IQiz`0GZ6C(jEv0>U^4Y*wUy4x_2P6YNJEQD8S| z{XXZF89z*l``IKpm9v^T3fL8^eHGLW@-`?#x^Mfgj96JttF{&vZuP`B!ZgybB_F4L zv{DK53&zT*rcz&DG%Gg@6eJThQ+TJuned8?K`+N0SA>6r%CP9>V>Ms=`e-M95$Cc8 zLj1Xrn=BS~pD24?>DxL7GLBys4rdxAT4oE)6T&g`Wyy{+hTnSd9*Q@umz3RSh1tSx z_R>%KL69Fy1Dw=m!;b1>Z=689E?qVI?N_Ns^JX`=LQPb|tqV52YDJoLheKzJjo%NcQk5AsxwS?wdUJ*7K=;L*Hr2nyc z%p!-h^~_au0^@w!F;(h$sZNIClbR~BcGIUTyS#D8I$LuL(u36YKFC1t@xjW|hHEQq zbjoeZcNqGH2k%KFwh!)0XI9q>m6TY-|irS(6Yc%e>+EsQ0qTvoigZRg7 zUb# z7i0f^uJ_AIApLg)|2XCQW#K5m2f{l4={Tb1KaPJiBo{;vM_ hjq;cJH0K|w^0N(GRT2Apt&so^DxE+^KIaC-{|_ZrXjuRN diff --git a/app/public/exports/warehouse/warehouse-rack-spaces-WH-E01-20260429010658-1777396018375.xlsx b/app/public/exports/warehouse/warehouse-rack-spaces-WH-E01-20260429010658-1777396018375.xlsx deleted file mode 100644 index d4a53652d0276c130c6e0dcb431f2ccd7c972889..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 12632 zcmdUVXH*p1)-4J&N|GFvq$oKfQ4tg*OAd{IgoY+(P$WpsA_z?mk`xe-oO3$RghnJM z$w`vr{Ho-5JlAu-@7^)qpZ9tU7`1n=HP_s8tyNWBwUy-1F|g6l(5|3O1SUR>7;Cty zeF+V169Wy67?{<0Xk+aNvv$;1dtnQ6(B*h;WtkVHVBN$;;J1HIa*kaVS65A4vMH?u zNtV5X*8g0B?fTgF*!nRSBBmS`x}0aktZ@PxFOyp+pOl5k3{psoB!np6CAm8Knc0fG z@*uH3E1coo6%8*tGKa#4L~m!TMWqZ=UvHOA3PHfCd6A8Z&0M$-HryoVj^nMRue{5wrpuVP&3C`ymNj*0SbB@k`bN;32e@HoSg-BA zEt(=%yG6rR!c_LIpw&DyD zTJLmyO!w+yZ>XF^`FZ8_ct7u(F4|X(PIx}w5kR@2{Z!l^NeTB!?8VxzK>Ao(xI&Htz`c$PO2nfW6a08#Gj#5PNb9Hd9g=lTsMo9+Su2mTYsN@ z=lfXEz4*d(e%3YF+zIV&{xIZS^HhSUV+0ifeDCgRb?5HvTeu6>-A^b zHsu1Q_1|b|3a+`>^lUY+pICajI33u!?=N>Bo}Znzi{&kvhPNZDuf+%iRG%hnPwj^< zdU_n&6nNefJvljeQ7@L9r1y1wtNU@*g7&lKeOGPclLBSIbyhWoPeBN z?)N-#b3Z>g9k4Fo;dFUO#LE_(lb|J&ZtGSUOO|Givb z(cWWkbvIykvA;mESW}-SJYdYz%^hv3tqvb|3ex6@AL{t*=q}eOH`;wJPwLonp-+1d zj=KEsC&{(-qIz}ir?v;X-=<%@Z$C!9pNf0#V8)^?+J9V<>zKPmTp z%mGeaZ&JhTa-aU>x}N^YcSn>>??J97tr^MYqwhJ|av|4`1(`)d5__&4T>LNDjX9efm)A>g?Lk>z=7IirZl=$+ zHRoTVk97~On^+hY=M{}e-F?~di9f+=j#VnwdZMQ0?4_%7MV!~?GhG{aHMNhc zckNo2{O0~WrBQrK5u@vhvJGW7m7aX6zCkn=J&rDaAD6_e+~}+^HO+?3g8PVNf!PcgQqkv^+5DwSNX}N=@Uu z{YUIoS@X*aw;{4Gi_nXSA*AkN;!;XVJS1F_0NQ!+rMD!&oPv0psuB??mnyf?pmS|> z-s9A?4HlEz!kkgYm|YsUQ5u>JZhqpDQ(9f}pOT_NC1VRI1WVc&y0j?NmZ?MHf;=o_ zWwd>nL%bg5vNc8diAUEJ#m3pzj_wkgceJ800SV(DqB+` z7^OHiZmC8|h0LJS@atEOHXfLPQf2|0$?eg6W45Ny)`oZdWCm?bsj^dAw;Wzb%62ly zgMnd$SzzF3NghpY|Hxuokj(_C6ToH#<$|D}Wqa764FTx9&I7-r`0{Rp?P1$rmO7@C zvBg{;9!_cdhZf_O+U%h=_G)~MR@u-`J+7VlKe?D^1g$6p%X)aYObwI*elVqWVuVq~ z76G%JJX`?P08k}(bz~uKmlp1I9V5!vLJ(KWze^qQE`tqSl?=UILmL8+T|sFg=pCYA zOhU+p#MXvFCxjQEiSSMm><>Ytl07gA@d6nD;yEpeAm7*_3g_5v0_wdV)RqF*HSB`m zo@F!Y07nqTb!)VLPUaPdf{QKOU^AN8iz>`uy9va9uc0jk#vj&1a681vuH7YdP3e>q zEN$cYETX=Y$I@8K5|_(nBm-JO6!VHgeG@^({s&%v zqtK?^76}rEzE4GSY%fC5N5>fvErH;I$&97YGhPpCr@+~%&^n&UA5fXKP@|-!s29mc(_dq zKRF?SKv8#-V6qd>bgG*XlZF=0R@sPaI}npF>T#0x1f)cGkb6 z1WSam2mu6Jn+COSgF=6CK``41Ak|a=f+2o+Me?9Z*#&H>GuDVoV>Vu1GW3{1EfW*K zbX))-1SFb+8QB%p+K{P^hy#i4N5gsmqH;Yvyr$f?W=SxUo~G0uchflD9-f#)U}X69 zvoNv?l;pUF$21YfAq0$C8(L3aT?MsY7eOZ4Au8wCc!8RT8PqlbS&h3Ogl5?s)&hK% zo?zAb%B_OmLY(kDB$xoQPgQ`>AzpI1Y`m%<0xL4HA_2xhiR=RUDw7`(M+x!@yWrKy z!wUm=MZ-)wL0+&pUQKO8WHB3%zo$B;+Mrl+Q`(5oVm3x_L{U-JQv~)!OkFV>rKz?o zIO4XoN`e^x>*8=X)#m9bib@1VhF?d8kzlXu9`zI%C&HM8fKh8hsT0Bv$W;~405ap< zMNv^O@C>lx!G{3Us@jRZm<@#)v;hEA$fi&bpsmO_zlg0g#XL)F(6T079pMKWV~C9= zR(Afk(K-Z?PubE9bz~XjBIQ16Q4MmDT1}Y zSc8C3>w|AlhmqJyt`9m>Ps>6pEg8WPMWAjj2em3W#A!7biBOKo%K%5{g%%SqqxGg# zYj>9sp7o;WabN^esIipS11WIo%#9sHY|B-!^ZK6j0CEOo8%4CyQODC@i}TfoJH zCKZks$h>r@rV}hjGIh(`Gq?D>koeA)UmbZGUm{Yz8lvFPW!nvPwSGJXz_hA^FlXZ& zS5Rv_-VQ_&qwyu;rc6&Q2JGu^uc6kw2_`sZg@&UaEgmi#E2PtK)S6f7zwPKDUMq;J zpj|L#EM+%~>`^Mg8*xD#vzsBT$sL!SgN_XqtyRV%5zDxe)Xnaul~a*}%g*A-)-jdV z4)#%_@qEfa2-P7VME939Z^a1?hf_#v1xLYZ(@~%U9nJ8(-vm=(NEEs{Yqe;xg?meY z^9!?>_s;2q)}3C#mAaE-R@fCiUeE1g1YFXWtn;gMy4Jt1TdOuX;kWcx*VIzCx;X4k z7<$C)yCg8=JJ2P6oyVJGY6@vNZ~y445ME1Oc=CAdR)`TFf?Z9dBXjC zUOJk&dC5tpjs%PEWa%|EonwynNtd^{I61ea%qE{Elv6CuJLzfB+TpjL*Vdq@8C@gn zQw=j?OkEA!TZ9NWcfYIId|8p~^fIs1L+KS{+P3PUj5#xd=|)4;O36ztIpO6)Di!ve z@TwRUNrDZ@oXHSq9eK%=1@qHJa=vM~Y=*#t(d^AB^$*Mh-3L%?^6!}JhblQ&pmokH z<3%P9N)`aiUUI%Az*72%VPHp+eFX=)TS}6@Y5}B$Md{6+)oaRpZ3jB&J}|j~Lv@g; zMtI8us2q#I>wzX7?0z_>-Utt7b&R~Jh1ltMeyp@weYxr2`qU16SyJ&G^6V8(^AUa2 zI>3EiAGHH=KMPSiB`-bUgr5W4FLS{!#{%3hm8td}W@uc3bff8DlV66gUs45VHvCBw zV#)mU8U^1Kd4T5Sn*$h9?AW+a%rcUE99$|$mKtG(SA;owIvExu4_ya)2n<0eBNN zc5^rLTi`$9ZA3Krd5g<6MzMHn*n-s>kKU*E2~hJH%9smaL=~#WPf=>g1s50w)Z~H- zgN&|8<Q;8_~?P)fmg<|H{DcJ>Ea2?NH}icLWzLjCBAEFB{25exKLt% z(H&eW5@7O{UxYb!IvFV>4;x@a3ceyJ^+x`EUg}(jKueG4q*3Vz2=h@003+m zWUMrQm=6#?Zbmeb28t860PDO`n1tPXhaWSI(hxvxNo6zyP(y|l{d5L#0|x_v@Ps~) zAi!J3FeAR@gJh6+ZVRHxDM-8-^ycGMu`>KJ(~{~0cptT-dV$_)KR9)J!LtCBl(^y9 zfJ!J9>x=prWd+u*g&WTXto>0)L=IUxf*rC(rh~1?0Z||asL!-Y4}>Tq$$j=h0O}Mz zw?l#8ghnEyNl(m4jZmS5nYQ#ss7UV2;8d99`zCe^$Rmq3MAL4lxKA6vD1%!?!RSj` zTdKN|+;ml2s(}%}Xp|zmjN9DK2vr4myBnbz0B<_G@$0-#ix(d7IRJTEq9}0$@&>;l z&>lMYasIXV%XUDcaPhb80Ok_6%7D?AqW07Y0JF0_bs5Awp~ybsHa|2%odKAb#wZLP z0Mpy@ecHB6o;Pm1IFNT=T&M(?_cv>56|nACaJ&(f3K||bL7a-@n@3VPL7`9*%93Cp zIyog@C|I&LZw^RFvA@QJJ_bYz$EA`63ncPq6GZ||#OQ;F1oX(8``JXsKofPOb{GSU z_$af@dCW(QQPxF36B(l%K}N};YWFBh-FV<)KyYs!xC9WKK>4DHlp)M>kXd;BT91;+2(EiURngkfN!ccP{qpDCfC(6=qJa89)(RUuWE67M+DyJ?K>Oomj z4+Qt3SF=Kx;Q5!DQ2w>EXOJxjd6c=I6lTHSMC!mm5MH0bIG~DoeIW6Ga6t<{o5%zx_wLk86F|7!O0bE5f-L|T8S=u5Kt@(l zIisP_GRl%MfKeqS-vr1=;HJ8b6#EqJs0|SOD{j0k5d2Z%n%eXG*}#cY5D?QI!Y%}g z+4J+n33&HX@-2a43f~-Xlwx1Og*pM=tGHCopqNP!<|652E|5GC9Ttua+))=`k|cRe ztp+4CKcZq6XNv0K1*(0=^8E~Wma^zY1S9YH>?H%sX*JD=?ES!>BAyOR=HB-)NdYFO zO*1-sKV+tej{%b*Vm^c5Mz)K;I|gzP1R3fZ!#K!n;&sCgLtT^L-hl|RkzZW^=tRjR&7^G9-d zpbY>ZRf3Y@%VZJ1IjV@cNSw`>=65>{h!sc{ADE@aDE(+G+ZGvl=_)%2OTb=20Kh5% zu=G%KKlnR80G2e(j|_yx?u%prU_l!IR-yzY0m9OcDz;i6u1muiMpf*B;O~Oqvg+QC zN|J(y*o5AoqySN<`Xs3PqH-|8;4=JanS+63qk&~=Pj5ouH{(^JQwiC#rAog1ut5a> zSe|MQ5ntMxn&bU{&o%y1p9Fx4-6w$qqWZyQNYgSk0?D8tDm@fV526yVXG@fP`C)?y zW_^Ui{s=%NNyB8u%K3)?I4byR|986jExwJv-1i79fIbOgkW~;|gw#s=N8tYpS%FLZ z@40#oUOWF6RY!q)FsIa1LaU3SrtbS!QGYa)0+4DBLUul|g5CgiHI3j$Px~)24OQ`j zXaA@Mc2Z4HaG-vefcp8t>G#za05>iFO`;hG0ufNK7=ZHmQO7{}NCD;3bEouC3F>!L zYi(Y-|0dCl>HsQO3;^nnG6qm3z@q#pMDUO0$CrXV@?TVH4WauM_$0UP$CE~P&qK5G zl$dKN`5QF7)_b%mE+VIm9u;RhhsOos0mqB_NoU{BmTg68tm{2@UU(iFoNw;*E#Erb zvK90=|2ng}de(b(Fn{)K)7IU!mm_>Apju#YKOkVXd46|`&&~DZ9RH5(_SxA{_aW0* zMR$nk1lJMrZ2GzTz@_l_So`k_I{NSF(iVh!ik-|JHE(S%d)d&QS)K3pxAmLaZmmvF zFD@!for(Q?xPI|o=gsu|C1>FE1@Uz>G?I%4<_>TJdzi7RqrI86sRQ`1+xswV;yBwif zj9-K}9s3Utdpllg^e%OUjc9DRmiEgp?n2X4eKIr$R=2~<+@07f9k)(87?%0hGA3g! zyI0NGE4BGM;3(cI>Io^t(-@T2)Bh$GI)1c;oN29{Ek=^R_7oC8b<}&dn@*H-tZy{azwRElYn++rZ(S2W>f^}u zp+9W*Vl7_M8!fz(8Ta|T4#9$h_ce80Zu~S6oE~D$>q>js*UlyCUrlQS8>}Ty<$R$3 zst(Ql($VD|%q1LDjD$Y6JM&KF-wwp}A?}nrFjUN62M_h}-Gz4MQ87Oc1bpl0cktfX zTycN6L@hBzaO98De4u~H9dn2DZwC_kSKS$RqEVWE9&Fvmn{j^((E7LmCz}Y_z0sZa zval{)dtc924rE($?bFSM*JvWa&rAWTSRRB2l3&Ta^fCV5IKcJbK4|?)?xX+z(ZS^d z##j3P^6z9Z#-qPvR{v+8{*Nyc9pNx5*kA7)FWT8TfoqB$c!x_#d+|~ocqw^d_T&GL zS6^$|3N~YRDe5*f398D!$Ee)-pxW|!!rE$-&Q4@UTCSwUp9nKjab^rfgM~{mh*ym} zY!zUj<3%={dCWf|Y z-CTa0h(G3O!cJa0c?wp1E_H(a9K;0A&)wNR=1s+g^phQLHHbGUCT>l%il_l zJgcy#(}<|Cnwy+ngNvkY?W!Aw;X@Mv^HP417QP}S--mBpZA7y;#G4;wlm^)^yF+M! z$MKXgLGCVDs*4%$jnwYq#C*VljQu zm%D4^o~H+2e5Z(>XUqoh-6EP`d<+i{_?jYvNg2ee;(sZN5gQ-PTw+gMNn$d|&;-L- zM#%pfMhVW%?+bIv9h0XI z&7a-!AJ39{SNkeTeggJsbNCLSGSiFpYgf3pXjGuV8~9F`F>W7G4}+^>4MMd*sDz_Khs$_xKY zi{?R_VF@yN1Ya*d&KMWRJAEbE^FffXQQ_2kk7tUAx$Z|47QUPIVTvOZZ<(erI%`EU z`gBA@(ov(FBF7S@Q{HPmTFN1(HADwq&RbTZLC#mzI$^~1mNPL5Csw3q_o3y3AFWRR zNS4LUy|!u8Ib0XdWB)iSNzXfB63wK)FI01!Y6gwQArqFtxoPgkN(hLvI^N-FIF+Bou<>L}6!aFb-U0%YXs?LSd?c9&= zhohYaldzL|%!IA(H7My^xub9KWr!*p^NnOIA*XhzymXz`#>@E?e)r|e-w69_7A$HH z&t_H=`w$@^FS`j`#*|*NK`GMGUze`)UB{^uT-P!Z^lvnx@R5(>W9mBjU{uMn?c_JA zyW>&Iu)MIxDI)Q%M6U}1VGM>gFE!6CJU>)Jh- z@Oo7&nM3&Pp^|WrSs?Nh`r4SO|Q-<#f&V&kay#>I#rY zmuFQD@bu6~&As_#pt58k!^K82w{|C7Hux!2dQ8jrrsw9R>u;eOHR0U@r9EYtWjhlO z$J7RUZ92@WtFua!r#+fqAQj7M!rE%h#^$Kdm9*|Te{cwvs& zUQPI9Dci=?mFz6Jau)cq|0J%XB*xf_`R*06wFvICNxQ;19OWL5-FRBcJ)V0qOxV^A zq}FYyyII~-T7LSrceg{#8dD}j!+2t|#9+phTsEcK!-Y%Z%1=Aq1~bKPyX`XNmw0cG zNIJQhlWY%C2u$&_Qp=Q$n5;M=fP#=a;FtN z!{h4ejXIGO8T)=&ujDwh3Jqrbe7De87RQbOj#mA+S_3e}?3;H@fd#&~rdlZ;{a zu=grVyBMA+DFp8i4$4Wy8}{C^%6IH0(PFW>Rcgy8^7)H@Uy+@-${W_3mUCkgZZ+3!vSpVP;j!$9kC2EYDNcWvS+-$uxm^+2$SQ}; zULsDW!i`1TkUcjOn4E3fh~_Avbxj&SZ>eG99)TlwaPoEQ?5{e_H>8hnPdA(~sxmL3 zlN&M=V-;aoH}Is}3#J;>3k{|!Hh$cxNt$Av6nPjfPN8tQ3iG>lDYL=dCvm!*u1s^&>sR#}1 zeJ@ZKe{eLQ&6!o0B6)_^C3in$SC_`s!IOXAWQgrMS)ciuWbxR5YZB)Ps{T~y@YYE? zmcjGZ2St_`&*R<=i=WH}WJf3B$|{ItktWU~WmL zs4|wNI4^-7)%j^5Kc}S0;XMs?NlW!5n|$D3x{GO^a>SQVUnfh&hUY>xQF93{a_#oChZ?IuS<YJ5S3z(rzLlU?ecq#=Jc<^7Uw78v$*`S&S9&xW+t z`3tBg)W_F2^cA1nIh0A>Z~wH2;VEQ)i2JW6sxD_eVSONtv%txU@b76fvayF<>YG40gsFtaesVLhtEWH#$^z>_3lw3vJ z+Z$;zOipfCm<~4!l#<8cI$S#_>udwJ-m(Yn%6yrabi}xnd3X=|MIw7tHYYz{x16N7 zqDUWbnM9Z>+|YH9VYo?`9UhAVqc7yKRd;20x!c#Fr-hjRkjSSp9#*kjH2o2VYg@2jo0O}k^F+3p*`@=ubD4(D{$;Eq=y$D50Wz8=St!= z<1==|N`C#AygAG+x00LH`*76MkTuw7tnf9BRZ3^|Cc z>Yc&R4X&s2gDWR}k*-N|1C)KGX({_d8!_RhV?$?$#b;QTd@QCh6){UQE^}7POy+7S zqtD9Qlc>f~-Ibo{Nv-RXzHxe4N$%2R614w$_cf5BzkUAAUhH20|NKD;ZW_M$falL( zAniXly8dg>-!~Ee^g=_+|I6pcPS^h}7`WH=;sXY20P5?<&fA}n{>ctJ^y=uLldi+%5wD{siJzVD-Pd{dykp zJHYQZoWB6xGhQ(N>-O`P>wltb$n-Cl|9@5d_Zxs;5rh8j_UG-uub>wT{{6c1%Ug-% qZ$W=vg?@Mc{Y3f8eUkOBQu(mKte;4a}WuVK{7&r)1m8M-sSuOL~@Do9J1ooVaU0-wQVmzld zVYTTjre78<|MjaYL$A)+;2a+*E0*iYh!8n$t#^~|d(E79cm?$5;mA6eN88@o=|@IA zynAPx6q7ML1!r&7>&tU}L%F#Vi>HL@{WfvA6`#d7ND22&^-oe;s>HUf1DKal*|#o^ z94wa^i*W`nW9hj{yqcy{`6Ch-KOzB;|K|q+Tp2pTtetp&%A7^(dxqTT67ZeEc?=Bv zKV^78$>P`+bp z>w-CIrB6I!IYMoRo`9=}mK+<^AKc%JI#pU%?Tu&ml;eH#=6mB45zm5T#2Y z`xfF6vzO^obxSFcGm^aL0m?#({oTi<5ZC6&t-_LZ=Y#I2^8p1_{dY#+u)aLze=lrp zt7o?qvuc#ZWDY&*VKY^{6zco<<9ce4_WTPD74(9>)^Od?t^9OZ^oz`@R5+=6f$}s8 z+T=n%rjNVuE?hyX`m~llIneKln=Y=&k-+ z8^BVg1u|O;FiZPaF*iF$D`Pu5E3guN5^dSWM{;ld7_V#>>I#)-k8xu6eW+lmOi(8480FP0c3ad!LO4QY7+qWenHA&Z+zbnjn^qCR%N>@#p<(}wM{ zd>F@E#(z*&f%m>&iz%6X+Nb{R*bc<`w5=Uk`?$I6*?a9S_3fXY9Ct|+FPKMlq3VbeM1t#%Q#Pk|qZWL; z5A8~QZiycq?LBUiNKZ5PytdJ|zc90LGT6~EGq`ZPIyXZce0V$&>M1ThZou$>@wVq1 z_j;dChTiTBZyIW&Cu|#Q8tNOxP7m-(83all_VzXoEKg7Dx941a+>Q<|6Cb9aW|ltq z9C>=3?i~->mJ0B?J=y=ZnQ$nff5~?J0q@3#?Y`}e-36*!5_Jt8+v^!?M8pXa6RATd zgfnx4yTjfm%?(GZ+keR&>>L#|9(+4IJf0a`B7EX>Tj@b?&CPM~+o!u$9z1!Fs3>ii3p}3ojye2&W{eR^BwbJ+~)J4OFR{Qy#wKC zEct$v-q0j&(CBq+zqkGM%j5j6Lsb4$lDmsXOxMEw#(p0!y9`GA^>=GHNy>(4MfnMP z_>J$zMYBaVjMy{-f@J)fc%<%4&sJi5`Im)9ZXltwq5 zhiOl?p(e26m{;4eFODzWjIF%zp{x!e8n?BZ%<)9Yv^0UBFC*EFY$S{??adRV(1!UQ z1Hq9M*1MbL#}kS>mlYS*44jNhbIXUNc09WIgr9Jm^0qoJtyQw@KslcjgZhM?=8rbD z=bm7W^$o3=Ss7OpmygI?f71P0IK^g`Qzp@NqM@qY;FBih6A#y#B;WTZ`gZU-I)4wp zhSgrhZ@aftMv1J&Oz4&6o2#yEc-YIHuxl0& z{3@fHw28rdFBelnl5mGPyDub0P_wNr5%%7v*4T=`qG6TnmTS&wzhm*v@e#B&GmH1? z+eBP>%k%SBA@WbkF)PR*6kZaNGAb$pijB0t_|_U z_cOEBIn1u!Es==MdAmRVMMs5z-eUx0xSZb`Cfs#4<6<1tvqJ(H3^k1eikBJ2bn88E30iyW+9A4%z;T5vozyR>F!qu7z zdZ|cETC7)5qcrL<{`{GzQvhb9l3U7Uc6GGGl&dwoqxpp}rBP>Vru>u+i_>Fi`JT&) zpko+m9_Tn;T0mPjD7JzCL^DC*0-#w&yCIloxbAlALI60C#o%|;A789<-R=BSQqPT9SRlfkAxsgin52SQ1tT39y za$vScfDeEg46+2Ti!CGQ)ghqQGoeW=1MTVr^=cwsNc`l1$sAva7*(}!;fW7=7T^Vp)pWG1q zGh8O!;0U6;W{dI9$>NG|aIt0UTqe^yab-DNR{;O{TDmfz|4-Toey0Ta)$0@<89fR& zDmw+K;iMbJbkm&rT_O2-iq1K?6$0g*slzKWp|{{ybS zKDHlM*X*KHWsM0|}6J&@aHcW|k!1Bft+Ud##BG zWd~T>x_f~0Pz!Q>|%>D9F%CXKBgt#FYwbR#BVbmL|z4v2zTE;1)dd_52Z-%Ir=-MoK; z1WSc+hynmRT8DJ6f<%9GL$EuDpfuC~fMJ2f<%%Fn1*Kf-)3%6OQ!YV4O3Z{I9WygP zbX)`>3Iv*m9n~Ax(VVM^NCJWG#>4snpbGs0g69187HKfE{?^QXFY_e9eu0EkU}XIH z{Y_LaNXcQpfO#s6M-&)!G*a|Kneh>A`bwRQergRbE6&;gD*=#t>s1q1ySHqS^>yfNrP&BAy1YYQ@DV2wJ5>B?G7saWELLuptgq z53sB1ANG`+m6X2%I7|XKtbK{|p8#;bl?vmU*AxB&fiN88kXsbh18`XE0;~fdU?&aM zcLSy6h=>4I^{MiGIlqOGN_8XBI&@68Dz?HJh+%t4JR(94kloIODU81>k57e}^cyp| z79*_{q0}FXdAarGrBGVshzMQK#ArFc4QQguI*F58uUqf>JU7I6_!+9RJy3GuV7eUE z4&w|3Mjdy)LY+nuYx!R4O+Bm%ueD|cN7NzuMLcxsR1lYyA{0V3p*RN|VU}4&a>FNDllxQ+^?$lylS2R z8=6)&UMly*sgCJJHHxiI?v|z1`}x!t_QIN|<7A{*^-7qMQ?Gp=)Wi1v7+|JD6Et%& z&T|31D&XgIF=jLwDQV93&}z`J>FO$a)sJL?XGZi>{Jn+!B~ztr2A&4XTEpkv{bZ}9 zNi~e~rmU6R7P0**NWu{}#38o@!j{T;$u;!QSlL!>EEcguAWhfiWnMcKJGA5~nQog< zYwP3~H<~P@3b;@o23+)gT=i3);Bh*Jbky*auCyM6I59DNnhTs@D+`Om)a0xaudwoJ z4|aWQk&y42J!ISC`>a-fa?A#=rr+1yF+s#Fd(pP!jb88C_cdGfRu`i74|VkobRBL^ z+Y`p#3A=77mrIYqUi9O9~kUkv&t(P6w_BRes7^_?=izP@M7*)i?>1|Ki)ri{hp!<1_3g*g`k9YzPDcFcx)G##r) zjAN#8Zi2aokypDY3GeoI4ZDxa(mlSGwFYQ|(p>uv1GFh`?lY#*FpWy8N^4$t^{`rv zBQN|-f|@kRx^&@W7_^ZJIc3HEu!TzKi$cNWkiF4@Z&R8t*-85Lpm-%e;R=J_jwSTfvr1W@cM@)CRkT1cJ-X^wAHIw5G5kOKvtWqX0R%X$lo=XJCKvuKQ9|OntuaJb)z? zes}@E5}L#IEI&p$fwk)pBy$04zZVu$NSTe`hOAQR;c4?gl&Apc(;c#dVX7!9|D7-Z zI<^1RaKJgKi5NxN14{}Mba+{=J+lcqmOuAdCd@j&mD>t(&#DvAx*aa*-w7bf;a5{K z`Iyz2scE9{KM zqOk-3n|{{$S(|djegw&qK->cepi*GmqgOR*V0};Fgd=J-3<7YHBsJ;idoqQg;ZSlK z;Uo5o!1Q2z=(6b<-H{lvCG?iZk;BEk-?*ecS5RsuwVPiPd zn+DkgIQOLyY5|Lg?`IJi0c5rlK#f5%6Mqy@Cjrz1K-5J*YYK9d6k{onO$mb(3jl~< z5JEu!(feN6$|Th=LI0s7Ad3b4A;|!7q4PhB$P7sLzRX-RfViSsu!w+!Ed>x63&P7m zL^d*oqv6mh8sr#&sFp@(0z@QoMbl1(dx~Jx4siaNAlV*pelK-Z!~J#vuyNi1$aI8o zi-KhK|J*nM?RPXniy)aduM9fNa4!=;T>$MB0$Nv)%(NIwv202=NU@k62hTdes2eaz zp1!J44+5GSQFBN#NB0W?*}i3+KMn3uR__qcP`CVd(t+i4nCHa4dnueDnGH-9-S#)j z04Bef=k&aLnVTUw226%Y_z!`T$L2pO=o}n<9+^9R5uHg02Udo;Q%uvff_=`ZmEJaozC1@6JAeI9#3(5dyrI2VT&@A()a)%XyUKW0NRLvn2{vs4E zujzLWnf7d$OEelS1CT;HAVoJ2SBMn>mlMv)9SWfw4XM(2cm)c-lB^b=Ny=RygZ%hI z2J!62^3)423T3ToIN$zvtjXsFqyVdU15)^))j+r$MOLm>2qhG>$_#}wgH}nn3#5=A zf5;%7ao)q{z6V$(&%$QMDf|Zk_-aHN|989wE<8^@KX4CBfB`8o5LGB#jKW6uhvWYX zT7g^q@3C?R@16e(tE0d(m`i3Rsm)nZ(+&Kc)E@<<1caK0lv@bQplBekz957#v;K=n zL)8M|1wXQZn?f5T9LOIwAb);f`hE4Kz(dP_6KK}K5CjxV1|WTY#}CSVmz2Egi%GzP3nfl2vFl;j`FPp$-OylH+wIScRW$U!F3`FyTQRTZFAcjLY^K+r$pE6H&0Fu z`u5qzYWl*&C-@FfCtuvX2G2$1qLK&!{qMh*sg4eL1dqSqc*&FWD|!_A_>Pap9RCUD2eH z$u>{84(mrzUgr<{`|rA+XuVtPjTq5d_o)1!xUdb)Quoi%9$eXsu<&x>u65ox>b|@r zyqYtaXx+DB$z7`}+?})$s`>%hFlRaOiZ#Wi&g;#T-H=GpNRFuRRLSz(Y>%h;b&G`4 zwTG)BV`77**(0wCU8@FnA4Tt)KetHR8d|7xsjDCI7hhT(`e0QzI3kgeDoPWTyyX5d zlDJXa;H$*#ql4LRbH%Dnm!b}unod(Lc|JkkI&@fAoj$Jcf9FOO#X#S9LUPH+r*XLK z_;|92F~i_=e9Z8xMELl@25P#aVWt8_73m`?g6?ke=`x?F=2=^BV~*?_cW9ZO_|UN` zf-=Nc7{I*S<;z*IXfRrKEjQ`?X(NIIpYU_$n!@;TDmXpNS=^iTWT1;rJgAP*1UA$_ zmC1X@@M$B4*SUl9TiA>E=maT4JTLaG+`n8%8bZ8iwqWRlKQHbY5_ySk&7l*1UWf!V zGH(&Su)E-OcactNisT>&t$oMvoEP>M#a}L@3~{|!x8l*-e_U+bCY<)V55Ri04yT+5 z+rHG7^`xvZTX)wWKmkOHBz}FRITAzc*&}lRDvmelp7dubUqh__H!cXg`S&_LQ~4YI ze{^wvkM*hH-~JsfBzS*7&KUlz)Bo{hqB9(31N-xx<5@YortnQM1MhHY7|&j+11}}d z#D4t$@#B08E^=w zhY0HkKG_5t>G@KA$~_bwxoLd~-Sk>}D40FPGWF_&3X|xK%iH4XR8zaG7KTj@^a9SZ z0XgE!I@?9U_%Uzi7$S}$U3_lTyswJZxbdBDhIC0s{ctrnif$PqMd7_8+=AJJ;jS^vwEaVBe9uV>dcp}duJAyf$|f*y z(lQH2bW_(o{rbh8g)QBpg$~QAv|Lo1=N&6vj5BtGX4e5rr^;=o-joE1hR6H#z~9%| zjj-okP3hu~9l!5Uk!?~&dZz6k1oNKmuL*ALZmt_j9KZ2na%p9h@HsiOGt^{?kM!K` ztB^1hf3m$w<#W9EF<|PVd(KR-5X;30*8A|N;LjOy*fgPnYC-4nSn-H3ETwidRiq}< zjLooI4m_`Xl_xD-U)lF=CYj!E8SpN1Y(4z(;1}@;dCvA{+O4HxlYO+k@LhDDzJY&=sK+b>80z0D3uqBzN8*FP9=A%_a%9ojjXFu zWPFKEbQtb*8Y5BhBSZ!zNu~t&e%Z_MK6gTInv_lDdp}Y}%=X=*whH*>7@<5u{hVzI ztEWLcXFyL(EE_$_D|RSlKIOOCucI1vTz_%T*LA~2Jk%9eqX$OTWIdgrbYw$uavNGb z^vdS=ZMr;O5%D*Zo==U*0*?3d(hU4kCNa!D41{Zs(@tYBIOW1}c)wXc#nR4Dqxgz* z1ERmJ5y9)U-*}Hd!5&stNRgv$f_L)nYTC2_zWXcJnuLB4h3auBwVPWoIekIW@;5#6 zm77Jc@;}A945i_v^;_Juxz((qcj20$)yHAl0_RPoh$wSxlv3^KFPuZ`3et>pN)$Y)otMae&V2$dbv3Ap0(?Hv7c=z4ur-(Y2b zRc_VR#N9ECp?7xOmUVS`NYyXiZI4mPRrL{F_S=%(IA1X|Y81t;5$`jYLO3EXUU1x& z7vmf>N-v*;Jo#{x)QwCq^<}?)fpRs5KWoyVY!+X&-+Mcmk!DBW zmK+sfd#c|b#-Orz~C2x9e zvy~wI*2$$^JT1vLKaF%Av2@9QHaH1m$az!Dx;x+W^Tu;_N5NX5D~SeLQyu|#6~aFr z5S<@e!+ty&=4wvarSOq>PZ=8Rr_sV6$zf?IsOQK}2o)qDwQ&@U2PL8%ZkAh|9`@fk zuUhT0Y+!s?SGV3MmLcc(LEbk#$)ZM!ov6e!Jdwk>dyuEY@OrIC*UK`Ecnx@mnx`pY zWA`L$#4Ws?8uQ-Ek5rVN?G6noNF^J;W3ef5?jzUXuwkjR7ZQ8_F=(LNK~gOmy=!ur zUAx9yr)SzwmPPnM@F*wpRl%GdPt7gYht%E1kDJs-(Zv|KHhkIGmj0gt@(C_&T@IZM z9Ed3SN)dfgU$g!ZZza!LKeVyw`O#{AY|@Rk#&28&$Z|rCEy)pbu{7l`-{qFU>{~FLrF4j8iHaAS*Kd(H^FK?cw=MXr*LF$vfZ%xD z73)pzIZP_!%N01~Shmdq*^W0djhaM6iZPlkuaZZZejgq8RI{yayyKN=A(e(#O z`n(=&3Rp#4Sk#SUb%V>vH?k|y`&{gz6Bg2e+2Ya!beY_VBvH0co3yCLZ2~_^&cB~b zU=K?8Tqt29iGICmao|6bQNBG+Hu_Bo`LekG$mbc6L6i)#q+@{aJs+Q`iikyvG-f}W zqe<-agS9WAxL| z!6|h({cL+HM4xDAG`Q21^CorrG^1P5ZrHXygNKuk@UGb~*LTVR%T?)$u|bbC-XnC= zvFJX_Q5TMpd&iw}Yb^Jq7oQ}LWekpoGKu(25N}a6?0ixfxI3_(vnVLl{ra-Vt?lb#V$?)#+Nn0Q z&nv03T&o^^kn0yf_Qa2t;Jelx*l$I`Vww?;Qak)?_{#GbyW$`ESHjm)V(P>oqB%I$oiN)yDy-F6=37U%_9uCg?1?X6FHvXb7;UzmqN$gvsU zGDKFIyqfB<;FbNX@-~@Sg#fi(AvV^*{pqC}4jH}?0w?|h$ulvxSh)L zK$_v`sf$_>cIbUl+&d23IiuWf$IK}DTC*lH{;AO`6CZXL+dSUN-tv8kgsr zOb_cg*IR}GmbjaZ!G5(d+H4POE4isX;BFuJydQ~W&afrFKOc=76h0L6V(F5cIlH@^ zMdWom0<8S#yXWvOMcn7VguGB?FM>}yFQqH{ieNl0z1zUcv78D46Xm!T@o|^&L)7-B zm7pb?W&;Niivsq88tkA^GrQ$X=K?j4n4-sViFb!`>d^Ps_O=P>$DD~hxtbj~2@k|7 zXEj?hW-v4hitW=Iq_%UZTb0KOb0M>m{q!Zrwbd8f?+R}nB*@oIR0%%4aHJgT>Tf>p z^?eVi8)Ho$k#FS87`c$*j<{FBlI}Bf%W#l5NP72e)1`Ni2~X`)fkW)SN8|SMZ6yaF z8g4)|h|g{tf9+?Ci0xB8&ri~|ep~v3*jFB=#h}3Um$+1I=Nb~$xP-PiZ4#ocedDh8 z*fJKUHpH1Rxl#A}Y7l;cviazKpHJSU$ZGjm;Tyc+{qXmZ?C1KFc(yKQM^zjSQLx_T zOB1vZGIhpDkGxOS7U57-%g^bzKWgqw9TDXriTLcT zB|&Og?l*PeGoKzB50A~3GtcZ`6=S(|rd&pnx{yD9Z+G#&oFn|P5LZAze%nXfiXGpA z!e=@61Q^#GNtxcU4aJ#Zo}Mp3isVKwK6IPmiIDN(<#%BT_KO$jRnffLC9=9Z&GG_E z0b;LyZ76)5@8R6g^3g!7N80Ql%|K;V#_sTXLe%lt@X3C~3C=lxt1sBf*p)fwdF$jR zi*!^mXA~XD)stwi%TD)aHV(*MIzF$WaPB-g#{b-X4TR_~pMUAa{$=2wKS;r*;j<68 ze?9}k{0O&W}#l|IHcLYkT$qoizjb^`rClr>B3S1GoOO52*0v zOyS=F{@#oGQxWJ{2iyXF&eZ;z$^Q{A*s^-|0o}6$-R^*$zcsM_gnstG^?M8JPi+hg z&41|rYH0n%*uS6a{jw57_XEK{PWgUW_)iq_0EY{I9xVJ)`}Y%wUye2Zs`l$V;&%hT zKXCpskk5LC{LjbFU#kBJvN7A=ZvTI0{PzcdUmipMs`kg@z%Qp~3;zAS^GjQW<1bEs n-i3Zw|9zwUr9R2|XR7>c16NVN{!wcrz=KLBkddC;p!oj*_04g# diff --git a/app/public/exports/warehouse/warehouse-rack-spaces-WH-E01-20260429011359-1777396439929.xlsx b/app/public/exports/warehouse/warehouse-rack-spaces-WH-E01-20260429011359-1777396439929.xlsx deleted file mode 100644 index b43aab0739f6ab44a3bd4d525d4e1386116e0c8d..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 12632 zcmdUVbyQT_`!@;<(jXmDiqegwA}B~p#~>gvFm!{G(hY(zbVw;6ATWea!sE$?`rk0mTi&Vc!jywLI-Hz(* zL3(pREX#{aI{r?SF6DPGKcBUioOzNLl*YY~6Ei5Kpa6>|R9lpUmTK_`ksRLS$_sVI z#ZTC8{~XAb5e+w^H6T`xda2ji+c6JA#qLXAq`lm;Z8Tcpd|{f-P-edFp}}rwJi{d# z4|m$4s+Sk=gCrH;oJ$u%n>;d=(Rj~kf({^r#q-0zMdPD*mk?vH=Va`L+AEh6IdutZ z%;zx!a%lN)USAu2eZdar^h8y;!az=h$a!b8hxE{A?#$CCXrKT`-pTTr{jI$LWbDJc zcXmlJ8Kcs04%U4>KQ}a1SU9tKN~k$tmyloiNpg#n@Zj9=EWNc_V%Ii^c@>p=>+;yq zYPqQdXYeYPfxFb}Svs}fBZ2Wf5&-#sd?3J;u`|rph4-h-k7#|%QW#$WzEir0fr0;r z3=b$-65p!Y&PQ-((_41_IMrVM(u@3hro5@^LbqG4+0#`;=XL~cY=%F(LlA9+6XWz{ z$r82JFB!cWt+7W>z*S63j*S`!9cV$FSve7N;6p;M;s`kA5u`0zoGM>cEbM8F)u)jE z4dNMhknL7|OC^~zhP?Ly%1Va)-N%(M_m-HQqS8&*qn@XWL50-=cgE{jU!C&57q+!G za9D|3H_2hLgr4-WnJZrj_kZ$nGd)Ci@dbw(ddW~{r2gdA%S?Ini|p!jIH_i#>MRP{ z>_$Ifh`aPIN=c^X{4ITIaKKd$eO$8>f%i8=(B2q78Tlt`m;fV>ZU3O`p8~i)1pbZL zpljtiAhT})W@-N_=HcLMW9r~w16IOMqOIHcNbYT(;+5}1-Jy!?aW3rs4-NJ)gOJtA zwhC|&yVHGbI(hm_FL1ItUXP}9%dhqCi-tW={)khS&7nxLtn#LDliXWq;@Fa;W8B~t zRxIB2Yoi}M)SNEVej^VyUD)BZ z50jXy_z%h}@!k*UFr~83`Ze60*n=1cibX9SDh6H44C&*g%@8-ozHeyG_-tfOSE*wKi;OMiz(tmhCDl^0A)5cc+;nLjJ*-&Ta+|bhL`obJ>=<(@PxVNO_q!Ggd#@pU? zj~o0(jeQ?8)HS|+Hf7&b+t|<~aejnX#voAUba1eBWPN_-xVzx)=W%kxLVTQtnp^qc zcjE1HesDTuUnaoo;dS_RJLy=;@QVHB1KzC;(h=`M$lK42*Vck3Ho* zP9yVlX{wBEl$ey1+B+$1I{JEid^$I@Lg?jkTjfD$t@xzm?eqOFdq*oMU+Dg~8j&Su z-@Ucn(7B}#WvZ3B#tgBc6Mo)47&Bc>LpZIU_T5uKx#K9tQ^5kMOeZJL z`)7|0I-0n>{hn-jx>O!2RSQWpo7+@!n{YJlA9N>?8Tb{ys2I9a?b(C&X4!;PP@0Il zj?kX%Ld{?$aj$pdUz}bMkFUD)p}Za;mawy*%HgGAUY11ApOxxCHWta3QRk%+-niIn zBsjLldUxCMbV_-TMR{q%$i=iQzhXpY&$EY5*o)hox6O5Bqw3lol+&vO)F zwefA*%V}XLxFeiBmy)BY+16JG`|eX~?L=eIuuAtRwB&W%v3lqH2-=pN!+ZU= zWL!n-i;LGGie43%m1GbKA1P@$H8lZpK3TxpdF6%YuWePq`ezjru#>A5Q z**TjW7T3jj6U?#ubO;i3bX&ZGrDbRI`jp>fBt*$3ms5)(yIA`4sI^w;B2&VBZ4?#s zgV-be?-p~lB?L<+HdQ32I5v*&UiNIAXQhW)l6v+B842N*rkbbADh{yp=@WpHi(CXn zI~lS911zlI076t!dC7$mqJ1>LLSq>h4-POxhxLQR@B=w~EaRdo<$Hhu;AM@gEgkey znVhoRpr%1-(rfzZ6Hk`_%tS4}jLYKsc&Ry8TU2Mu3t>u=uC{E&8NF*RPh=H)S(HJ? zFwz3haiXk%u6{^-B>{+Lioy**vx@dWFwb$_?a_w-aAHcp@2Ee%*yOs~^@pT^B~5ZA z->bVb`XN!31XT`u=*_)`AhR_t%u`?D(~t*0=2<~0YSHQe0X|C;wb1WK>D*XhG|3gf zY_9+x05ue330@yxPSB@EKyP41lUxqk)eGsQYG zswKU%rQ8kS4{##BlL7lp6s6`2j3WI(1ORz%%Mz$(PKfe(uB!lhFNgKzz;%s!Ao%CF z%zD5PM0LX+`x^SG`8{$J|o%Ypt!brJk7Ns8+?DLk`!l|-w$ z1l~(%FPCt%HgcpCbD1fCQV`XWiYR5!L>ZUaA_q#(84(BI(p&?PK-|7appyRsuD?L& z((j4~0THA_Eoo8!zRhOzyP_(USuInNEA>XjQ5`@6WE>3$ux?nSDE12Q!^+=iBf{AM zR(2C%ij(~UiBT}qE>ja5E;2#D`zjqO;cc%#Vgk&x*Yrib((~UXdmqA56bA(OEz94y zA;LjYcQas$Q;!Vl+Y!^IHjmc0$QpYP(=fV8i!>)h;XD_a3njh*2!ijG=8S&9zd?ef z!#KnMfSql_`qx3CKYAe8okUPt8UVn^;F1bukfp*hF3nkc#9MPNK|xB)q+vY^3qW*I z1R(|lnui_Lm(baguZ>6nf$k^51^}Q+0|J7U{Ek)`FpGh<>;WIk6u|+3q;z0p`suwm zst=^(ctF519mXRDj5=F7PoLs~+;2#r(wz`*=eY!doJbnhw*XO1dLYE+xLnpl1D7A* zGzKZHf!{*hh%*Fd~Hp#1;JmSFeB| z48WBLv*-nJ!BPZu^%3!vTtNID8d&OsWGT()Bcdv~Siuo>ZS_C}SQkl6m0UEI`ikI) z-_b4uW&*5>$H!7%V4xx)9T=H@8W%@_wQhJcP+^`9V;2KPoh?;vh+rUAbwB|qO!ikK zB*4HOVAWR$0kBoKllWsc3TDy;7@$S9MS%voD$GkOxT>5b&xzE>57bYIO8<3P4d^gfKuiQ~;4k16Z};;uHj}(xFlTREPu^3|QDO2dWp? zRSl1OD=bPYUIQGa035!3h4Y^PaQ`L~$+c)8{5t|+ILINl7^)ZGu*3~m2SC7H2CQEc zrQ?i<239p%^}d4N%0#WE327TXpK4@aRg5M4_QEi*T$!*YMaC4CxVmcCm>gouVo;sSXfOWt) z!+}xfoi9+AvE;XWuMB1$R!6*+yk~%Hy)31c zanYQ$irXrFKn+Pa=7BiownErbxvsc}ADgP$YfQu=RtRM2+I=kF&cqL|xJzf+C%v_I zaZVUd6;cOWXpR6b`aiA*s7~>?oI*NldCJz>j>24+7)BR@r`XCP6EL+o>m@5~d^$qi zpI9Zmbk7~O@AZ#(YdAe&hgUn`|JXT6#3OgvzO>GuZ{ypBy=I#mQOAe+hDN$h50~93 zQ{SY0k2IE27pBZl3xv~bZIKvvYWiVX4fWE3n~@%)6Hy0dV*{Fw)icgH z+cZDP($mDJLyUxX_nVf($5q*0f9tnKXrr=x$4(=(Id6Uh(|Dv-6;+ijFT7?%qt=-h zUYDdHOR_0jG#v?TqC(Etus>|268fxE$P#uiUifuJ`xQG${{a+_>Kiuqp+?aqXp=j~ zWQD~Yw&my%>sj5zR;pYJMi+u2l$pH2X)tZBcc{&#${TK##R2L!K7c>EwEx*Hr z*s?z)rWU%S48Xj2bqGt28;<~rT}@t!Pe2PP&?3$AkF&e|!;6Mnm0PV}I z{rv61HbnOXTM=!+0n$pX2^;}Bj$pQ?Vh$R;0oZ(mHs=En(MD+rQ&-vY!9_*^Hu>P< zAR=P9B8DjFZE7SV;9Qzoh#7Dmc4?yUtG9+GQz~gSInOl$=w-k;GH6{33FE#_03`zu z-5{VP2PUrt$64d$Qc^%l@Bl;<5JG$a(fc;}s$lg<{J`O0?%*~2Ku8EcT=?hTiAyn2 z`Yh9)oo@mVXHzR?QERcqm@|KVIe&{(mmZ=*1Q^I^m)8zeM-c_OhjIsV5(gH90tU8B z@>bhlErd!Rw-`E z!U1gs)4bG&v#@tL&x*yM`XinU$$}EK+%+Pg!wvQRQ1<+=4nxq$eSh;vd$OVYoGBwf_h#UNh zNO#om>xCF;uWo>&Sn228fX!uojUls-72VlWfX&|S>=n@F33cHSzxAOR`V6p%ZH~qg z0Bi=>zRcNHC^gcjRECH=Nm>}^#izpr_BGy1eJitfE{LdmX2a2dCyT=?r zBt%naEnq!nj<&A=ipU)83L?sk(z-=coVk>`kP=QHWpyEhT!8jv z)XyS90Y!w6Rzd;94Lko{MAHDGP8fO~L{t~0aMkqJO%2LaR+Bs2MY5p@wj%>YE*1hnQLM=5dE0=bkhNQnS|2nHb( z1Q5ONldnoqj}#0XP64u5Fc6Xo5Es7qvxqE!bnnm3w*ZJMehU^6kg#O{B2z(l1&GK_ zu4p_8T1|tT01&;U5t;%KiCoookmH^q73jh znFBvJPC)w|jnFbkrufw%S2^xg0;n6Hy+%Om4w9J>XDyLS=>aK`FyP?XBpCMqCdo6` zwHiP`3u78iDVFE~K_J_AY+ufTyOhm4LQ6A7FodL zXUn|acdzoZq$hyMNU6YKaPrjhdj(y9qc0-!XD_3(3E{xXvB!TDx_dS^1yulqTN;Fp zmha3~FP08m1SUrUA%rr(WIS44_=S3;OrXvSZi=K}$T~RLi+1NQ0xAeeWLH=#DFkOs z)sR&S19B@>!{#2o-8}=2Qc`XtsY;1#~e-RB=>J-iizL~?WjY~TiZ+%ax z1e5^`$RW{kLirrhSI1Scm&giPbAqqu0KUQ~Q^N|hSmp0c6gr~fFW_>6W=Xh_B!F2p zz$`P=IvD;U7%)qb6HE!3#T$(00L+3ifLR$NS_U-BJg(YlgP@m(vy5vvg~MNj!xgmy z?jbWGM!3YDq2&NlXa{BJ1`~>~qTvd{Ir+n3l;dI5S`V*6;a5{N60=FU3+0d>zsn#Z zzAsO+=(14Gx|Zwhf5)17VNeFJiZ>{O4_Xa|D^TR*>x5B4L95JAI5TLKgu74%`SH69 zB7*ZCKKDJqDtQhzJ5JF*2*B4M()z#SHF)WH>czo(U;+%vkb$Ve;Sv;f`rjS@U(gEN z;(v|RWANVjzpy$EJcGGqXOr6fNNT#lzmxjCpj3cR^N?~2ff@7+$g9r?Va%NWBGOQe zV0hv8Y~ZHQ1qlc8hYiS|@0fmFeHrl3^4|oSbtnu01(N|tpYM4Lq>mhsJ_9$Z?jg~? zTD8{~WcqIc&8iJp1(N}=`aO*St1@6xz7`|-$MRFFz#924GPQx!XA3;ZZTf!F=;L>2 zb)J<(oK?EX@XmgZG0Q{ZwAHuvZ0GQ}EH?Cb$vETe+u4evB!hjk-_8@iLzDBbJA*6N zPPZIIea}D5uC1NDJ3Cl7`|{P%$MYRe>_}+6$kKjj=v@24?v{|Z=gB$I4ae=Xv!nh) zwu##QNXaR_Bh=aF$38PC3+^9=xQP#7ckdSvLd{m zH=S(Tzh=$-R$sU$Wh-3$1F~_!dg?W6nq9q5-HgMqNby*nnD9*L>cV`lx8+T%r1Oo3 z>mm~pL*}_-uZ!HPhxQ*m+qZmfm9aCtRPR>bFdQhkvOfI5rhaHlDl1)#CN_2D@y8hA zCP||&Qnycz=D#kKs5f7UJ!)<~PrKsng}!y{w6s2ZS{eAxgDRGRzUhqQil1N8NcrjM zbTMO=(fQPfP^e)9lx6IaR~6vDwZX(?99dIy?2Db6o^w zjIT6^dAHl2vvS#Jy!=Lf%KP&s1P4Chr|b=-$1OL`#tiOSy?>;H`l0$=`v&QDZ<#{VB( zTs&ZXYW%lj_5fLQM?(DM#~XSFhJcA^(>l@H33 zT-Dnx7RHbJZGj>BB*x88wDx`VGcD0?d~>8LdYUXHbZLx+-EORelM>o+J||#yY@kDfB_?NxXkWdm5=~81l~Nexx404$c|Odb6{v3QUh7{ta&ih*5uG6(w68Vo?CrII%9i22<3`MIzYO$DuaG>IF!l2(z#G^+RhViR>|Q`UV9A zr6py6JUiDTA#uIy*NSf$BgNo-W88wdgi-Es%(Mf;8hp=53wxsowyyF(p2{aNaMCgh zNB2lB zcQ|m_Tlo;c^+g~YV zEa|noPUUxc@G)rS^5eX@P@!v=r&#a9V?#e>DPYrt3u=U1C}71S!myUv(^iw2&M>vW za#s)wA;v=DU;VZ?uii6#dPkXDnArix1ov&b*qXD+-imvU>b}+GLyDu$dpH{=-f*oM z1HFZ_Yax>baxWU6CMZwA-h3UsL8{L7q?`B>{}zJ=G-8v;4LiyEHTrHuU2-a>VBS@j z#Z(S67y2Xo>T6GS83|&wB*EMOJ7>KRncznj$HV zXL<~Gx=fL%#4#eH(iC$7{D9omM87-X;%4PDFMS`WBIf(=QQHK4b&ggYqkhgdgVoz8 znKx)4A(4w7=ao2?v78B5AJ9{eJZ-pq;P1X=CmHUJtJMo5Yqp(DQaQ1sIJ*t48Gdbd z`dg+VUNP}kv)<9BQ~~Gv1sO&GY10@M9|ogzCuwIf7+msUdAwh3pJM4|X;6H@5rr7; zYDM$995&tKPjZBn7g6Ntn&F+jyPh#CfdBZldu`Hyh*Hg@jE49QOu2DOwe&$mWTaO=iN}PR7Z;Q|CpV^QLx>*#t>}iHnP^C>8Fip?iV$1h$t$zB9NTWe zC)utD<4gE?aI!@OrZJ$Ax@Q3~*M@q^?I7RSQk*o=;JFS+({& zR(_~0oFBbi^E1htjdjR-)^XU(2u{{^LB@Q=Fm`-Or&wF5+4WKUp>Cz(tjf-#Ge15lNDqo{wV;RRf_DEh09>+lv^rfh8?!){LUB00R zRboxS+aZAg2D$lXZ%j0nZ4~&p$miE@#41KSgvw9o1zq*~dV&5qbh9D0f2eApI=^~n z>h6Tr@H>Yd>-zcvr21#y_9rOS>W1iU$6e_joG%z!waOAVhz}XeAsjK6FFEfjN^lOF zI%8GWxJi+joUfM`8z$mX`Fak`&b*E|FI0R-=GRT)yYz8+A|$oCDpEuI;h9rREQ3Gx zgd=X+8(YOLzP?O%+10Z!uMa0FJ;)?;fA*V~DA(iobEcij=ke7Ce0NhBY4!weDX`($ zyHMD7p>Gxh%;*IhJKo%mv}(m9qT%|)~)!-=q!>Uudal3f3f-JjpxT51#6A2^cm2a@(8%A5dQvv==#JK z_Wj8)Uwg(OjgQ24#@OUAgBJcs0ZU6sGf#0!s4xYoi=%8hB=yWmyu#}Ic;L=O^%}QT zBh%yh`pqVZECuHeivF1?R<%0pM5W$Q$sDddLp+_vH{XhMzbe;C)Pi?vc$*V8^-Qxy z-@@Cgwd`Ygq^1(FKRm1?lWO|znq8@DKe--<-L)!5A&K`NLk26Hq&1$Q_sv+?b!#p4 zdS{L0uL(a09p^;8E?h9+slDa?kh;h8NwelSx&$NNjxQJ6I&d`TCBc;)mhk!D!RXR2 z6wfXjYBxOMt>XDD0Bvf1alD2fn{=za=_^+uvVxFfM|zB0B184_H-!}k4v*`#@vWRn zc-%;7N)3J-vX;X6*|5w)$5sqi89icoqLSs7&08d{{1KV-_JyAe+ONnT5u9$iW7Xwf zz@#!|sl=(kvTqT{br#JwX%-vKR&9N~(~vR4IW2KFR+?JnVjcE3`zm&mn-5Y9c|F;b zu!^~`sGBD0hgMTXbF0vYTEb86Z!yC4jdIX>UAA&!$TNfY1l@cpc6jZi z8^`2v=bZ{$tj8%YMx{^Y!tx(GFE4nUVvcF9NAm4S-SgjE81enoZz{gOxaBs#piWXc zH@3>tn;X8j9G%6Kh1JS-8w%w~`4nN;JEN>#drkB#|B`bZuE3dydGr6$p#?TznLC)N zIXgK1+B3x5{Pj2mXhdWOeg={JRm{ZE5&Zd+p&@NQ!AH`tPjPXRe>Lal91Yz5d8?Ck7VRf_RkP8DPg>A$Taq6|hY$Z`Kzd7>!*VeiF6)%G#Dm zRb!$+bwLI*q4&*VX%Vu`m@2c^ zGrd;4@}Jax3uVG(lzV6;Kh17999s#=D!5c{@> z7Y-$K1cqT{*HUWO6_{70hmu_uHCKG|kTW?Rk3Iz^!Y+b4LTOZT^O1T0enXryu83xZ ztPpN~jKhmZ_Ma$vpWE2shcJv23P){@LYDa=x{w&=0nE8oCUDRD@AdJf4N@EX=`dT_ z=hdFd+@F(HegMTXs4d1ObSdDvrUNNej5RO2Ejoses-REEm0LZIUFn`(D4`KfC^DkJ ziO&zXF?sQ>U1j1pyJ1m6=7Kc?>*6!v6`q~A2|pjq?weDXjQEa|ih*aU+)v`ZE{#fS zTXUvc@~Zi;hrAiAwk{<5#$-uEbv9{(J6kTkdz7SDKUFRG^wNoHynEpNMW3CWhVw8_Z7IoHe%i<+gGA`L2o+5DgC?8pJRZ+zu$@Z2$#q&CKx zGZU?Ub3FtMjPLgubG znKAdN+M}I{-|}+?9FAMM(gdjF{PG(Ly~E}E3eNB+LR>*XFWW!jR_^&17DeRU6JXqM zCS`iZHk@FAd491JDU$ze`Ju-gPqdsLFTdNh(11jNJ~i#T-6HGzv)5i=DM1`HZwyCm z@;zJ_UOgF%_sp0dq8Y5p$=V;;Oo~077&$wvJj1yVX!99c6}u|$B5%FIbg`Z~=A5!K zxn>IOP5Ie@?508aE2kILlrCH($M~PSuYnN#Wjy z{kzj&n}~mEVPKU0q4T}d^?!2)_S*jVfX-Tg{QBN``_t1u(Sck4j}NHu`G>;41N^lY z_opJzvktfg{QOY+YbO6kykN`fj}Pdc9q4uk?EI~P^(XWn4_v>tu>RD>z|j7O?w<{< ze=_#(=X!ry38DLr;2)=ae_HrY6!HLv3x6Ce{HgZuClG%+*8Z#7pXU+38u;~r^G^dW zS$`n^jS`_9>f2t_WR?&pH6=)_}BZ+pW131e{uTrF7&JV iuN&o`>eHNmq{`1Wa5W|D@3lq(Jg9U58R^XpivJ%Nx@<}S diff --git a/app/public/exports/warehouse/warehouse-rack-spaces-WH-E01-20260429011416-1777396456342.xlsx b/app/public/exports/warehouse/warehouse-rack-spaces-WH-E01-20260429011416-1777396456342.xlsx deleted file mode 100644 index 68cddda1130e19f2a14982886b063cca998107b7..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 12632 zcmdUVbyQT_`!@;<(jXlY3Q9L3f+8SDOUED}F)(z4A|c%=3>{L62nY<_EetWJfV9#f zAkzJwqu1-b-uwG~ziYk!yzi_9>+C&GeD>#go_)^j^QbCfV&P$6U|hg>8=CeYcDxx^ z?;HlkS1b$+GGJC;+TP9uX6It0`Pc#GY{2u#)}|<4*{+q3ByjJR%pA7@fq|x$Olvk0 zMOmV>+6VeO!Ep>1 zXx!asUsb#~haVs=59eGw7u@Kcp@hbJMia0PAuOC5ejAC8;$1|H!k&?_8)z+GOyJZZ ztTLO!^vkB@zkYRf`1LtkoReb}r80e45hADUjc(Eduh~-%uYmr1963je7`t1${mAGC z(sy=9F&QILarW1|K0h-slAk}dd`hU%ZyTRi{z-h3lyLvd;54nJQf$X2fO!R#bL-;h z;Yz8A7-!%LmcElr%LKO%wgJrV%z zrwk7$Srpfz(#A({XTwuw?kL4h?!xoDI;Pyot3tP%S?uU4B6HgP*Ed3A?hr&;;zT)q zS+qc{_K8QXM5^!76L1yMl4GO#gZrCNrwoUxdf>T<|j&56biZ&p}VcfvMy z`u5AQYsT437SQ7!HZ!G5p}vnlY@`M0EIj8>MK2m?kJKICdXXWAex6mC1}D`hP?n&T8mW0{yPI>*1On3%t7~g7(Dt$;dxh!vq+4Wb-Fw{}jOeA@Fa^ z2C$TBgUr?d%+mf<%-!C}+Qi=88mxq$L|e7-k=)%l!7JT^x!Q$|66=$^7n$kLWF-Mg2fs1MyQ`wZRLbYKT8 z?;M{l;#L?t|=5w>h%dnqOMzIk;EUF`kYXHTxXtoG@BffiYU-flP9m-a*3mFI^D9b z60vCd!pKlU>~7z`*|vUci(d5c zKC&}+JN6A>p$Or{N= z63)&K?TvV!Ha8rv?F_Yj-u$|`-?lv8=#}lgxMos!qv7572xIYmI`M{83*w__`~EXO z9f_Wht?;Un%*>P7EsFyqVhhGyM&70g`m>|2tJAw9nYS758|5w^fB8E9$l0svEc%4^ zD3#2^xv@ODL2N=?V)wY9@$l=>(aG%4GT{^F+sgNYt8Y$--#**>vU|9U@`mnxs}fms z^4?wD37%biU!qd3W5f_0JnrM^g)!aPNJKCV>GUCraCvxmo$rJn<2IiUUDBE8n_UP` zWAV4+jD{w0!$z+Yhy9%|pC7;IIzqjePJZO-5!NTo`aItBa4tVktP~P!GP5q{Hs)y9+wV#w)AuQSUN&^6(xV&gd3gg;MrnN0 zWrX&02Wko{ihaEk_x$A2&A5sS?@Q|tqVd~%DI8Cf%}Npp`Z818$wtHZ(rce6hc+zq z7z&QAvPy4RoJ=b1URGLMH*_{B$txR?+V$w>6Mn*N#@p($yk5bw3*~%L1nLudT0Gp+ znSX*g-Z#8%Zf#OtR5mJm{Ym#5;Z)l>PT3^8$%e{y!;e~&PdwbJlYQTv8rZ|@==?qW z8rFK1zV6*p9V4<4Go@EiXs*1XdjCz`rHkVU6PQZ33CJz0Oix>~vhA77uO1ia#gXvg z^Q(?+(Iy4+yo{_dmN`~>s0FD#>WMc{YTAD(Y;Nq7D!sc%7( zRL=KOdRi|iqMV?@eiyy5TOVM$%7uC2O?(n`|HnKlC`EmvvR{DD!dNxJrfFo6;nef_8O-dbJSGbGa}zC^5UV^&kM)6|@e5**O8m zCW>lK>u4@@Mfd`o+}uuwy}f}_bpl4=z90gCJl7>LRE#5{bdKu^z}|~tJy~#FAKelB zvs|X#;0U6!Zin&D$)fTIaIvKuT&6R-@uj(3R{;MnwDn{`{~vV_{LYCAYu70}GJ6zn zRCEfw6VqBM;%I5$NG{|ul?SCDDn(@xN}!1nF4F}Ll&%vZ7Qm&k3L=5Hei1_@{Rdos zfzYYf83zI)NP}9?Bm;b#PV03>lq<1XBqx>Ye!Pil2NEFtuwQ_6-8@;LM}Qwz`bG;8 z$_}uylK@kg=o3hYfSGif7+Z6Z2?E|%=uq)BJpu{wFq0mW=XHwD{*df>083Wr7vQ%j zedCG<1xejWhbc@x)URtpOqp0eT;(Eb=tfMz=qAil9T5d{Tx8Ca`1&9SzLy%)dinnb z36=)q5Cs5sv<~ZC1&RLPj$n5bL20T30K)@|%9KEs3QD*%X6z6(W?X`Tl$eRby5{D9 z=!6JD6bLjAJE}Lnqd89tkqiReOMvwQKo$E11TFX-EYo4;{jFL3UKYuM{Q`+;z{up& zyPK$9kdmW*0gE&kk0>zeXzn<9iVJeTE`~~TMAXc22?9BhIIL$5qMC3=h|Y33uLb)r z-N$JNP+SGSg}4%VOR)i9AE*Pa!+jMCxdb&p3!JF5>QopH4XPKYt2|*uG7X3;@&~RS z0YMmmD*x*z_&w0K&;!X*oYq4`lyk9yBkJnP{xYyG5*y38Xe{&; zz!ATLZ92>tSQn3%g`PlvS$rBWGWj%i69v|~!C`-ySsIL86c}|hSGXbqfmqc71t34s zR~8=+19yNGZy^N0R_%7ekJ$*AaVKDa7S$R78t5!DD=y=z$h69r7`Ca;(Lw}*!dMbx zX*E6nt+(zQD5w)60Z428RW44Dt~D`KiX)<84jf@t4eM!x)Q-6$glD;|yTK8}uBiMq zSXmVtT-HFqD{{Fwfy%1V*3-@hMRgFu0NqdlL;?+9)tZY_5VT5%N&!$I;$bjgVZ$7# z9$;5BIO-`gFD`oxaF`5mSo0F+KLOx=D;3VQpfCIf0%17FA-5>12jH;C6<7yAz-~IM z?*>ZS2@wgb>SM*bGJZ>A)v89MP3X8@Wn8%p5X1K31Vp4fAiI+XQ=AwmOGty6_M0%d z6(Mbupwu6Vc)9f#q)^&rh)6xq#8?@>Eoh?BCYh64zgz$M0yo5DBn;Kr9w<3^I8z2| zhjE4iqmDaYpw6R7HGD7iryo>C)Y!0sBkB-?LLNE|Dv0Z9Aqt_ESd3vKv@aO@j{Vp~iOi$ee>(U1hlUtl#xc@GSMN35*!2^sDJVt6U(! zhNhQJl*m7Eu4B4Ug<|WIzh!0pZXxZtgRmCrBn2r}wHmJM-0RQ>^{~4)4w&iC0?nLG z@LWKz3HUi*j2%lsN?NczupV-1y1Is5^COw$nHBw*aCh-w*-SZyfv3T$#^_mhKiOJI zay8?E8EXZ%Wn8~1l5o@=al~zju%mKWb_+c+QL$4Wk3%dI$k4TUS=3C&4KKS%X4oax z*f~4JkEIBy0WLH~02h59*8Ef^d7Mum9o0M~tF4D2&P)s+=L09%O2gwZwK(g<%dNfI zgWVomCcbdX8Mf>34XZJj8n?x(?)QD1j8F4~Q*5o_?I%KP+K(OwRpHLw#GYX_%$SLU*2_)k_?tu|jyy`e zT`b7NFgGtV#nzo_{f#oGzP@MN#VP&#CLb^FmaOH}gVZYO#d%jlT}DTucFcx)G##r) ztW%arUZRDEu~)k&3GdD~P5TckGCjUlHHK)zl01hFL$n!hUKrC@xMl@ag$*yfYDB%- zi5Fg*s4hdYA@gb~9NI{QoVI3v&_X5jS+U@9$o^Qt*J-Vn>?D2rP&}${*xU!|uP#6v z-8d%7%p&0p}qX#tXiBs%tQ%kXDlOun<5m0?v^EYnn(H_f-NY z8Gz^-0WCQ&$r2cAg_lD~0V%=*5K%w~@c~5dTIDJN)xz=phXc6-SMmKJK>%@~pZ_2( z*;w(jR9jY_F+iMkwWxWu`6grb+}XvvO;R0th%ymiAiGUYD_9LhD9mq-SpC1eu z*fh>vX?r;zEP2$1Xr%~|Bx?uOd7(5NZ{V6Rb~cR(V6{Dq)da8_{!t}Rf0!U-I0SG{ z>JJG8wB=25Q`%q3gi02+BU)WUCEGx4A%1mRlMgfPS+0QgVSAP@sGa>CQ=cz9A7Dw9 zA6@{kgyyjOkso86z}j^QQn-M%-wls_MVW)(hOANQ@E2sKY|oVAnpMKP$@9(F>9LDu)e2o!cp~V1_3xpvbs#nUD;Qm5m0g( zWEkL`ibf~`OxY_}hGb>AqX?k)0Ft5!Xyw2JiThbZaX=BV`Xk~1K8ogk7LgfHMBQ24 zW&k1~ngS~Ut5GwwT^UeBW@r}>QAUL3Et(2X0k{O<+)n^51vn>B`%y${kUln`h}0q6 z>;Uo5o0;m>%sE~kG8$gts5NpMmL#YEP;sjDw2SUgN zXkSGAEFu(8L%e_JXbp^Cn325CwGSg$N#BwOzAw^>P96TEYWA4Bt zdB&P%JqT!iRNXPz0^KhNWc#+wiy3g2vK~N$p>Fx_W&q3Su*i)YcqyDInFCA~-u5@o z1SUUQeM zUBx0$1~4FtM9T{0aY$YnQ^8&&D`3qIyqXR83ZYC1$=76+yE|UsfQmbZ%MF?(;YN}G zW>o>R%uuU9`13%(EJb!8C1@6JFpdK-3(5dyrI2VT&@A(qN{2OqUJibFOx-aQ{yY?} zpyhWLnI1O6B^ra41xTSCl%gAqe}xqZmlw{?8xEly3#rt6a0Lp#lA@lFMao?ui~R6i z1`+msc^a=S3T3Zpy4?PEtSRRPr2wmVgHrgQ)j+sBMRuNc2qhG>$_#}wgH}nn3#5=A zzRMuOIPcy#6FxRXsQrjO%O*i;=Qok3JG7xGWQf?tIgJOWZ`iv09%>FMT z4OI_>7ktkKZVDZca3Fu!fc*K6>G#!_01qwyO`utaLJ&|e8G!Wpp2tA?$O7rpf34y! z68*bXJ3T?B|0d9^T7XqB833!_(-^QS1t#TdQIdZwKcxb!k^dr7>q)&f!IRv^?8IaLmmS0z?3#SGANw2_pMBjP zTxL1hbhzPt_GxBy^>pBLfBy8#R|hYT0iNiQ;5w1Tz2M;4w)ve+Ay1FvGoot_Tc@Xo zeFtpg)qUaOlYED$)6b8*hR#L5z}b6I(*6FH0b@zDkHqopVcX``vadbksqNX$`_A_k z4x6i=KQAsSPoGNsJY2u<{oPN@=lOGP!0QV#dJGKm9|z{naAPN!nTCs#rJaQ{cv$W= z++szhMjiCIL5I}5q@U8&HvHbYZfH~@Gfk8xI%WCM zhbZDkal86Y-&17z2x}>ee1|^ac$B-4dA!DZD*~GZf7m0|8!%fsoN5gD6iYm%SR0Q4KdnkG36LhIZyI_HJGP4SltDI;7j*6jqe&L0<>w+Uyw?g6k~Z@?)h z!*?$AWj`rx%+cF33{V8oB8lHzX^z4W3wvk*K*jMU-Iw`9)we|TYcDn0qbBWa$Cw<&w&fI&?Lil@<5XtG(F`~Q z)Wd{z1RrgKjrDygKjs|?kKVMogl>AHGaSsGYL#|%Qk6;c#^oLH4XWuqR!gHMM|uGl zxqw{p72TaeVf@&)^9+&4QLa8Ws^3+{Xx{k7H%q##t8uxAE|t-si;jbdS@KTw9AsVB zSA8?cR*@>dw7$pmVoM!A6|*)UdE*+cCzgq{xrkMTuvoiLnQDM^jEB8=K96ME-Q0>$ zr)4h)BXAr~lNjpdp0BZ(3*X4PeZ>2stPAUA`)gBQo@hqG?$R=nHuaY9D6P~Jz3W+P zqLBq0wX&CbPo1n(Hi>B2wf1xT^cj)ECAI?R8&Z=_(J60XfzJXCt6=cn$ zD&}?DI}86H!@hzFO14_Wf&i>xeC_5cOhF?DiC|wFgIX7=ut&-2 z>E{y^7nK0=>|76pZt7lTDZFKb6ovPWatr1VM!3Z?)AkRm^F1Ri=!qcMyut%{DwoK> zNy{u8*-c&d^vh=l7Pbt_7CJ2Jk}^>po&i?8SQqR_t*%3sPSxAay{U;34UZ4#fxjz+EfqeL#uY>#7%Thk`G>SVmT?3S&vXL<2};;`c`&bqND zTyt7qcm9+mXd++sdBf9qrAgSEuOF|Gsy)rrTToym(&BtxmddDK$5rF*rqa7 z)|cp1m*GyQ2@;hsN@Q4^Y({|Zm$Q=Kb0_qsY3cL}?}sXgxxTy9)&XCgB2`AIpRrA2 z^)!g*4(f}E<)FuS#g3#brv29Xb=AU8>M!p5x^3Euhq~cv_Q1%RY-SRbk8LSVZ$qnw zU)!F%%}~HAB>rmJ^RY2S!0BFox}jg{6o&cx!3doR+8GQ6=R8<0?^m0rSUQ>N6kl*| zKn!*?BYB+<8t?KaI>1U_QRM2F;++m$O`j3KfArd|IldsW4o+uQ(*_aY;ZOQV+{aa)a6zfFbD}ENh3N5XZmjE?-Uw>#X0YwuaCvz}_{G>kS%$7$MI2L5Fg-nzYl+>yJnkx`oQ1@nMlKEIX(`yuUcH|rEq)- z2e^Ubok`!PQ23+y^dXD}XbfZ4HZ>XZb zGOu!bQhHo-c)-5fs;({{srK2s?J-KFvOcoQVMnqX=L?2rwUXF1;sXXV2uIY#3r;%< zVw}S!PFR&yt`cO%XKST}1_`)S-X23U)33wM3KRy&e7Z=y7e6eG2c=Y2gsb0taOxNp z&EShY?tq*6#zvu&uQ$U@X5}>G$@}BvZe*gFFZ=Zilxwm4*;9_CbNFig-a9FbG`j+~ z*CM zba`w8`~GB@r!{S#%17coZDf3qP78l1kEN-ok*hE%RFI6+!BH|9l8AAcNh%W7?QqGHd8Bo3GEA)XGS>op=>FH1EOG~pfUo@RuN z-BYZQxA1nWEqX6MR8|!Mr|C^)0st)ZHeJn>5DIMHqRud^y-w{vQKg5M0{696A>` z7+L&JxU%3j9WrQ5tlB48e=_;SU$uHY;xL>V~ zYvEMH<3>tSs`KNJH5bgygk%&rv|zYM=@QEk6)iPy+#+$|56hspEBK_}c1iA#;AF!M zt2XZ(CY8zMa-1?OyJmqLryE(uO`^kDDlM(i$>r^KYAC8?Fq*J6LOt6(?2em~iO z*Mm(FtB?zex^cX2XeH%FP6hgai(PcmQYJ7*T!w%yi#v%V+U{wSHr0e};0MWtcTg|4`p;&T?M#r3eN{%jEb2e@2_rI$mPHnK3=+QM<1}PW_ zjhnf@{y7x)^KNtC{EA2irp0KKtGo89;S7xO6Pun4ajRW_CwcTy^y@hsnv90qTNbuB zC5~sG>~4h^5Dkw7ce-)jq|TUObT8Zs-!WkDaP|@2GauplMmcD;CR08>rwLakCMl;A$gCSmge10Fh@1k!ufV3?)q-bk9dFTGr769u<1HC zuSQZlJG#QtlM}kT6q(7CiPge(8w%w~{uE}=Gp(dn&2r;3?}Ae;uE42?S=0a0p#?Tz znc17FI@vq?-ZRA9^z|qiXhdWOeg={JRm|AI0sQ%st}bae&PP(eM{$0Ge?IpDp1+Ce z4R$9v5=^&uTR~90yKHexB7T#^+f)s^9~B3s2RCw;1f{y)To$>tb6re~n#f%z&6f6A z1$DMt<-_;#{Q}6Igt20Lx4J`z?I>7mGvZ-dho3Efnc#sem){n(oM~^Ie zODh{D74`9am3b-5_?|Zl#jlX9&Mz3~knPc1$MLg4XoN1qK}*aUy#@D4iRH3pBJWgD zCB~&}a_&B;=A0De&I_RmQ^cfnJC8~W^a3qcX}XQh_Q!oWNpF|W%)=q%*oDzaTMd-|aF_9VUq3w4S69%a^`peweH+_{Es19fn7*^dfWQ z;fU_Ka0%U{*2Ef*k;?sR2l5$vU2hh#d_!lNl_V)08v$XQ1vV?vzlPD&-U;?2 zjwrC3w0@8C^0YtM9da3FIopl`xderwS0W>Z&8(%|Pb}X~k35cf+EY-Ko<6#HJB{bQ z48!qLSM@^d(0in~cO1EM$GG2)n^W}5e~MvmaVmN!$>Cs@JefDa@<9Jl>DW^lT%ND8 zJ**R4Zy5$z;%_zv`_;tiu-&(-;HLI~yMN&GekhhT%a$^DJ_a`^VmRpe@+El-_DA-X zQP=GWuwKMSpToNpd5`}R@vx=4ID%)irDw7v4h6U?N_o~3e-Jf3m?ZPNe}1Nq3^Bl?-0_DyAXSFH9K+=9*R}W zX|-m~VrUfg<%mpVS>K;{Fq+?+XKd0Zpn1u_CpK{LIEmpRL@lL)JltZ;}y=GS1xtTj9B+Z)PRDmjsBB-37(o9WML9F)6sa$Z&O+<9`0|GE1b2+?0Y|I&;7%fLT>kb+IaKR)38 z83u&?XQS)io&MfL{8I}9qxesq@13syn=`Q2_QwZw)(qs=_s-j&p8kmr-1>ifK!wjg z6#gCH@4dJ`6@i|0z%AhChuU8=`9Ix0xZw;(Jq5pW``n`qqr#1$L z)<1NAHMIU>?BCDzepv~k`;Oorr+mLG{3i-|fWw794;Fr@{rd^TFUMMcRr_@w@w Date: Thu, 2 Jul 2026 22:08:47 +0800 Subject: [PATCH 080/550] 1 --- .gitignore | 2 + app/model/print_item.js | 2 +- app/model/print_template.js | 2 +- app/model/storage_transaction.js | 2 +- app/service/systemMethods/quick/waybill.js | 35 ++ .../systemMethods/setting/printTemplate.js | 2 +- .../systems/order_storage_allocation.js | 120 ++++- app/service/systems/pick_compensation.js | 4 + app/service/systems/quick/waybill.js | 42 ++ app/service/systems/setting/print_template.js | 4 +- ...20260622150000-seed-receipt-print-items.js | 36 +- ...-lock-unlock-to-wms-storage-transaction.js | 26 ++ ...0702-alter-print-template-business-type.js | 28 ++ .../20260702-fix-receipt-a5-template.js | 310 +++++++++++++ ...20260702-migrate-entry-order-print-data.js | 53 +++ .../20260702-seed-receipt-default-template.js | 42 ++ .../20260702-seed-receipt-print-items-v2.js | 151 +++++++ methods/changes/system.json | 26 ++ methods/system.json | 42 +- script/deploy-init.cjs | 7 +- script/deploy-ops.cjs | 105 ++++- script/deploy-precheck.cjs | 24 +- script/deploy-remote.cjs | 306 +++++++------ script/deploy-version.cjs | 66 ++- script/rollback-remote.cjs | 250 +++++++---- .../systems/order_storage_allocation.test.js | 424 ++++++++++++++++++ 26 files changed, 1853 insertions(+), 258 deletions(-) create mode 100644 app/service/systemMethods/quick/waybill.js create mode 100644 app/service/systems/quick/waybill.js create mode 100644 database/migrations/20260702-add-lock-unlock-to-wms-storage-transaction.js create mode 100644 database/migrations/20260702-alter-print-template-business-type.js create mode 100644 database/migrations/20260702-fix-receipt-a5-template.js create mode 100644 database/migrations/20260702-migrate-entry-order-print-data.js create mode 100644 database/migrations/20260702-seed-receipt-default-template.js create mode 100644 database/migrations/20260702-seed-receipt-print-items-v2.js diff --git a/.gitignore b/.gitignore index 3583d4e..1f9cb63 100644 --- a/.gitignore +++ b/.gitignore @@ -36,3 +36,5 @@ test/.runtime/ .deploy-state/ versioning/* !versioning/.gitkeep + +app/public/exports/ diff --git a/app/model/print_item.js b/app/model/print_item.js index 01a9540..16bf6cc 100644 --- a/app/model/print_item.js +++ b/app/model/print_item.js @@ -1,7 +1,7 @@ // app/model/print_item.js module.exports = app => { const { STRING, INTEGER, BOOLEAN, JSON, DATE } = app.Sequelize; - const SUPPORTED_BUSINESS_TYPES = [ 'STOCK', 'RECEIPT', 'PICKING', 'OUTBOUND' ]; + const SUPPORTED_BUSINESS_TYPES = [ 'STOCK', 'RECEIPT', 'PICKING', 'OUTBOUND', 'ENTRY_ORDER' ]; const PrintItem = app.model.define('print_item', { id: { diff --git a/app/model/print_template.js b/app/model/print_template.js index bc80068..c4c781c 100644 --- a/app/model/print_template.js +++ b/app/model/print_template.js @@ -3,7 +3,7 @@ module.exports = app => { const { BIGINT, STRING, INTEGER, BOOLEAN, JSON, DATE, DATEONLY } = app.Sequelize; - const SUPPORTED_BUSINESS_TYPES = [ 'STOCK', 'RECEIPT', 'PICKING', 'OUTBOUND' ]; + const SUPPORTED_BUSINESS_TYPES = [ 'STOCK', 'RECEIPT', 'PICKING', 'OUTBOUND', 'ENTRY_ORDER' ]; const PrintTemplate = app.model.define('print_template', { id: { diff --git a/app/model/storage_transaction.js b/app/model/storage_transaction.js index 7d0df1a..a9ff570 100644 --- a/app/model/storage_transaction.js +++ b/app/model/storage_transaction.js @@ -16,7 +16,7 @@ module.exports = app => { comment: '主键ID', }, transaction_type: { - type: ENUM('INBOUND', 'OUTBOUND', 'TRANSFER_OUT', 'TRANSFER_IN'), + type: ENUM('INBOUND', 'OUTBOUND', 'TRANSFER_OUT', 'TRANSFER_IN', 'LOCK', 'UNLOCK'), allowNull: false, comment: '出入库类型', }, diff --git a/app/service/systemMethods/quick/waybill.js b/app/service/systemMethods/quick/waybill.js new file mode 100644 index 0000000..a53863c --- /dev/null +++ b/app/service/systemMethods/quick/waybill.js @@ -0,0 +1,35 @@ +'use strict'; + +const MainService = require('../../main'); + +/** + * 系统方法层:quick.waybill(运单号快速查询接口包装层)。 + * 主要职责:统一包装系统方法接口,处理权限、日志等公共逻辑,调用底层 service 实现业务功能。 + */ +class QuickWaybillMethodService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'toOrder'; + const _noNeedLog = ''; + const _noNeedAuth = 'toOrder'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 根据运单号快速查询订单 ID。 + * 查询 wms_order_express 表中 status=1 的有效记录,返回对应的 order_id。 + * + * @param {Object} data 请求参数。 + * @param {string} data.waybill_code 运单号。 + * @return {Promise} 统一成功包装响应,包含 order_id。 + */ + async toOrder(data = {}) { + const { service } = this; + const { waybill_code: waybillCode } = data; + const result = await service.systems.quick.waybill.toOrder({ waybill_code: waybillCode }); + return this.success('查询成功', result); + } +} + +module.exports = QuickWaybillMethodService; diff --git a/app/service/systemMethods/setting/printTemplate.js b/app/service/systemMethods/setting/printTemplate.js index 98ae85a..ccbbac7 100644 --- a/app/service/systemMethods/setting/printTemplate.js +++ b/app/service/systemMethods/setting/printTemplate.js @@ -1,7 +1,7 @@ 'use strict'; const MainService = require('../../main'); -const SUPPORTED_BUSINESS_TYPES = [ 'STOCK', 'RECEIPT', 'PICKING', 'OUTBOUND' ]; +const SUPPORTED_BUSINESS_TYPES = [ 'STOCK', 'RECEIPT', 'PICKING', 'OUTBOUND', 'ENTRY_ORDER' ]; class printTemplateService extends MainService { constructor(ctx) { diff --git a/app/service/systems/order_storage_allocation.js b/app/service/systems/order_storage_allocation.js index e03e5a3..2c7a852 100644 --- a/app/service/systems/order_storage_allocation.js +++ b/app/service/systems/order_storage_allocation.js @@ -865,6 +865,27 @@ class OrderStorageAllocationService extends MainService { }); if (Array.isArray(oldPickingRecords) && oldPickingRecords.length > 0) { + // 批量查询旧 picking 记录关联的 wms_storage,获取 stock_id 用于回退 StockWarehouse.locked_quantity + const oldStorageIds = oldPickingRecords + .map(record => toNumber(record.storage_id, 0)) + .filter(storageId => storageId > 0); + const oldStorageMap = new Map(); + if (oldStorageIds.length > 0) { + const oldStorageRows = await ctx.model.Storage.findAll({ + where: { id: { [Op.in]: oldStorageIds }, warehouse_id: warehouseId }, + attributes: [ 'id', 'stock_id' ], + transaction, + lock: transaction.LOCK.UPDATE, + raw: true, + }); + for (const oldStorageRow of Array.isArray(oldStorageRows) ? oldStorageRows : []) { + const plain = toPlainRecord(oldStorageRow); + if (plain && Number(plain.id) > 0) { + oldStorageMap.set(Number(plain.id), toNumber(plain.stock_id, 0)); + } + } + } + for (const record of oldPickingRecords) { const storageId = toNumber(record.storage_id, 0); const quantity = toNumber(record.quantity, 0); @@ -872,11 +893,22 @@ class OrderStorageAllocationService extends MainService { if (storageId > 0 && quantity > 0) { await ctx.service.systems.storage.index.unlockQuantity(storageId, quantity, { transaction }); - writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 已释放旧库存锁定', { + // 同步回退 wms_stock_warehouse 的锁定数量 + const oldStockId = oldStorageMap.get(storageId) || 0; + if (oldStockId > 0) { + await ctx.model.StockWarehouse.decrement('locked_quantity', { + by: quantity, + where: { id: oldStockId }, + transaction, + }); + } + + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 已释放旧库存锁定(含stock_warehouse同步)', { warehouseId, orderId: toNumber(record.order_id, 0), storageId, quantity, + stockId: oldStockId, }); } } @@ -1079,9 +1111,18 @@ class OrderStorageAllocationService extends MainService { currentAvailable, }); + const beforeLockedQuantity = toNumber(storageRow.locked_quantity, 0); + await ctx.service.systems.storage.index.lockQuantity(storageRow.id, allocationQuantity, { transaction }); - writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 库存锁定完成', { + // 同步更新 wms_stock_warehouse 的锁定数量 + await ctx.model.StockWarehouse.increment('locked_quantity', { + by: allocationQuantity, + where: { id: storageRow.stock_id }, + transaction, + }); + + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 库存锁定完成(含stock_warehouse同步)', { orderId, orderItemId: toNumber(orderItem.id, 0), stockId, @@ -1089,6 +1130,29 @@ class OrderStorageAllocationService extends MainService { allocationQuantity, }); + // 写入储位锁定流水 + await ctx.model.StorageTransaction.create({ + transaction_type: 'LOCK', + warehouse_id: warehouseId, + store_id: storageRow.store_id, + stock_id: stockId, + storage_id: storageRow.id, + space_id: storageRow.space_id, + quantity: allocationQuantity, + before_quantity: storageRow.quantity, + after_quantity: storageRow.quantity, + before_locked_quantity: beforeLockedQuantity, + after_locked_quantity: beforeLockedQuantity + allocationQuantity, + batch_no: storageRow.batch_no, + inventory_type: storageRow.inventory_type, + order_type: 'PICKING_LOCK', + order_no: String(orderId), + order_id: orderId, + operator_id: String(ctx.user?.employees_id ?? ctx.user?.id ?? ''), + operator_name: ctx.user?.employees_name ?? ctx.user?.real_name ?? ctx.user?.name ?? '', + remark: '分配储位(库存锁定)', + }, { transaction }); + storageRow.available_quantity = currentAvailable - allocationQuantity; storageRow.locked_quantity = toNumber(storageRow.locked_quantity, 0) + allocationQuantity; remainingQuantity -= allocationQuantity; @@ -1112,6 +1176,13 @@ class OrderStorageAllocationService extends MainService { storageRow.id, allocationQuantity, { transaction } ); + // 同步回退 wms_stock_warehouse 的锁定数量 + await ctx.model.StockWarehouse.decrement('locked_quantity', { + by: allocationQuantity, + where: { id: storageRow.stock_id }, + transaction, + }); + // 回退内存计数器:storageRow 的 available_quantity 和 locked_quantity storageRow.available_quantity = currentAvailable; storageRow.locked_quantity = toNumber(storageRow.locked_quantity, 0) - allocationQuantity; @@ -1154,7 +1225,7 @@ class OrderStorageAllocationService extends MainService { // 记录本次成功锁定(lockQuantity + spaceId 有效),用于订单级别缺货回滚 const orderLockList = orderLockRecords.get(orderId) || []; - orderLockList.push({ storageId: storageRow.id, quantity: allocationQuantity }); + orderLockList.push({ storageId: storageRow.id, stockId: storageRow.stock_id, quantity: allocationQuantity }); orderLockRecords.set(orderId, orderLockList); pickingRows.push({ @@ -1239,6 +1310,15 @@ class OrderStorageAllocationService extends MainService { lockRecord.storageId, lockRecord.quantity, { transaction } ); + // 同步回退 wms_stock_warehouse 的锁定数量 + if (lockRecord.stockId && lockRecord.stockId > 0) { + await ctx.model.StockWarehouse.decrement('locked_quantity', { + by: lockRecord.quantity, + where: { id: lockRecord.stockId }, + transaction, + }); + } + // 回退 storageAllocationMap 中的累加值 const prevStorageQty = storageAllocationMap.get(lockRecord.storageId) || 0; const newStorageQty = prevStorageQty - lockRecord.quantity; @@ -2173,10 +2253,44 @@ class OrderStorageAllocationService extends MainService { throw new Error(`库存记录不存在: ${storageId}`); } + const beforeLockedQuantity = toNumber(storageRow.locked_quantity, 0); + await ctx.service.systems.storage.index.unlockQuantity(storageId, quantity, { transaction, }); + // 同步减少 wms_stock_warehouse 的锁定数量 + if (storageRow.stock_id && storageRow.stock_id > 0) { + await ctx.model.StockWarehouse.decrement('locked_quantity', { + by: quantity, + where: { id: storageRow.stock_id }, + transaction, + }); + } + + // 写入储位解锁流水 + await ctx.model.StorageTransaction.create({ + transaction_type: 'UNLOCK', + warehouse_id: warehouseId, + store_id: storageRow.store_id, + stock_id: storageRow.stock_id, + storage_id: storageId, + space_id: storageRow.space_id, + quantity, + before_quantity: storageRow.quantity, + after_quantity: storageRow.quantity, + before_locked_quantity: beforeLockedQuantity, + after_locked_quantity: beforeLockedQuantity - quantity, + batch_no: storageRow.batch_no, + inventory_type: storageRow.inventory_type, + order_type: 'PICKING_UNLOCK', + order_no: 'CANCEL_BATCH', + order_id: 0, + operator_id: String(ctx.user?.employees_id ?? ctx.user?.id ?? ''), + operator_name: ctx.user?.employees_name ?? ctx.user?.real_name ?? ctx.user?.name ?? '', + remark: '取消分配储位(库存解锁)', + }, { transaction }); + storageUnlockSummary.push({ storage_id: storageId, unlocked_quantity: quantity, diff --git a/app/service/systems/pick_compensation.js b/app/service/systems/pick_compensation.js index 787c8da..cd5ba78 100644 --- a/app/service/systems/pick_compensation.js +++ b/app/service/systems/pick_compensation.js @@ -228,6 +228,7 @@ class PickCompensationService extends MainService { AND p.order_id IN (:orderIds) AND p.storage_id IS NOT NULL AND p.storage_id > 0 + AND p.deleted_at IS NULL -- 排除软删除记录 ORDER BY p.id ASC LIMIT :limit `, { @@ -292,6 +293,7 @@ class PickCompensationService extends MainService { AND p.order_id IN (:orderIds) AND p.storage_id IS NOT NULL AND p.storage_id > 0 + AND p.deleted_at IS NULL -- 排除软删除记录 ORDER BY p.id ASC LIMIT :limit `, { @@ -345,6 +347,7 @@ class PickCompensationService extends MainService { AND p.status = 'pending' AND p.storage_id IS NOT NULL AND p.storage_id > 0 + AND p.deleted_at IS NULL -- 排除软删除记录 `, { replacements: { pickingIds, warehouseId }, type: ctx.model.QueryTypes.SELECT, @@ -483,6 +486,7 @@ class PickCompensationService extends MainService { AND p.status = 'pending' AND p.storage_id IS NOT NULL AND p.storage_id > 0 + AND p.deleted_at IS NULL -- 排除软删除记录 `, { replacements: { pickingIds, warehouseId }, type: ctx.model.QueryTypes.SELECT, diff --git a/app/service/systems/quick/waybill.js b/app/service/systems/quick/waybill.js new file mode 100644 index 0000000..1864517 --- /dev/null +++ b/app/service/systems/quick/waybill.js @@ -0,0 +1,42 @@ +'use strict'; + +const MainService = require('../../main'); + +/** + * 业务逻辑层:quick.waybill(运单号快速查询)。 + */ +class QuickWaybillService extends MainService { + /** + * 根据运单号查询有效订单ID。 + * 仅查询 wms_order_express 表中 status=1 的记录。 + * + * @param {Object} params 查询参数。 + * @param {string} params.waybill_code 运单号,不可为空。 + * @return {Promise} 包含 order_id 的对象。 + * @throws {Error} 当 waybill_code 为空或未找到匹配记录时抛出业务错误。 + */ + async toOrder({ waybill_code: waybillCode }) { + const { ctx } = this; + + if (!waybillCode || !String(waybillCode).trim()) { + this.throwError('运单号不能为空'); + } + + const record = await ctx.model.OrderExpress.findOne({ + where: { + waybill_code: String(waybillCode).trim(), + status: 1, + }, + attributes: [ 'order_id' ], + raw: true, + }); + + if (!record) { + this.throwError('未找到该运单号对应的订单'); + } + + return { order_id: record.order_id }; + } +} + +module.exports = QuickWaybillService; diff --git a/app/service/systems/setting/print_template.js b/app/service/systems/setting/print_template.js index ab6bd81..aef04d3 100644 --- a/app/service/systems/setting/print_template.js +++ b/app/service/systems/setting/print_template.js @@ -1,7 +1,7 @@ 'use strict'; const Service = require('egg').Service; -const SUPPORTED_BUSINESS_TYPES = [ 'STOCK', 'RECEIPT', 'PICKING', 'OUTBOUND' ]; +const SUPPORTED_BUSINESS_TYPES = [ 'STOCK', 'RECEIPT', 'PICKING', 'OUTBOUND', 'ENTRY_ORDER' ]; class PrintTemplateService extends Service { /** @@ -687,6 +687,8 @@ class PrintTemplateService extends Service { bodyTds += '<% } %>'; return headerTds + bodyTds; } + + } module.exports = PrintTemplateService; diff --git a/database/migrations/20260622150000-seed-receipt-print-items.js b/database/migrations/20260622150000-seed-receipt-print-items.js index 1c4cf48..5467e01 100644 --- a/database/migrations/20260622150000-seed-receipt-print-items.js +++ b/database/migrations/20260622150000-seed-receipt-print-items.js @@ -1,7 +1,7 @@ 'use strict'; /** - * 预置 RECEIPT(入库)业务类型的打印项配置。 + * 预置 ENTRY_ORDER(入库单)业务类型的打印项配置。 * * 幂等设计:基于唯一索引 (business_type, platform, field_code) 做 INSERT IGNORE, * 不会重复插入已存在的记录。 @@ -9,30 +9,30 @@ const TABLE = 'wms_print_items'; -const RECEIPT_PRINT_ITEMS = [ +const ENTRY_ORDER_PRINT_ITEMS = [ // ─── 入库单信息(group: entry_order_info) ────────────────── - { business_type: 'RECEIPT', platform: 'default', field_name: '入库单号', field_code: 'entry_order_code', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 1, required: true, status: 1 }, - { business_type: 'RECEIPT', platform: 'default', field_name: '业务类型', field_code: 'order_type', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 2, required: false, status: 1 }, - { business_type: 'RECEIPT', platform: 'default', field_name: '订单状态', field_code: 'order_status', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 3, required: false, status: 1 }, - { business_type: 'RECEIPT', platform: 'default', field_name: '采购单号', field_code: 'purchase_order_code', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 4, required: false, status: 1 }, - { business_type: 'RECEIPT', platform: 'default', field_name: '供应商名称', field_code: 'supplier_name', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 5, required: false, status: 1 }, - { business_type: 'RECEIPT', platform: 'default', field_name: '仓库名称', field_code: 'warehouse_name', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 6, required: false, status: 1 }, - { business_type: 'RECEIPT', platform: 'default', field_name: '货主名称', field_code: 'store_name', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 7, required: false, status: 1 }, - { business_type: 'RECEIPT', platform: 'default', field_name: '物流公司', field_code: 'logistics_name', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 8, required: false, status: 1 }, - { business_type: 'RECEIPT', platform: 'default', field_name: '运单号', field_code: 'express_code', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 9, required: false, status: 1 }, - { business_type: 'RECEIPT', platform: 'default', field_name: '订单创建时间', field_code: 'order_create_time', field_type: 'datetime', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 10, required: false, status: 1 }, - { business_type: 'RECEIPT', platform: 'default', field_name: '预期到货时间', field_code: 'expect_start_time', field_type: 'datetime', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 11, required: false, status: 1 }, - { business_type: 'RECEIPT', platform: 'default', field_name: '备注', field_code: 'remark', field_type: 'textarea', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 12, required: false, status: 1 }, - { business_type: 'RECEIPT', platform: 'default', field_name: '单据总行数', field_code: 'total_order_lines', field_type: 'number', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 13, required: false, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '入库单号', field_code: 'entry_order_code', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 1, required: true, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '业务类型', field_code: 'order_type', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 2, required: false, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '订单状态', field_code: 'order_status', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 3, required: false, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '采购单号', field_code: 'purchase_order_code', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 4, required: false, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '供应商名称', field_code: 'supplier_name', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 5, required: false, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '仓库名称', field_code: 'warehouse_name', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 6, required: false, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '货主名称', field_code: 'store_name', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 7, required: false, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '物流公司', field_code: 'logistics_name', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 8, required: false, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '运单号', field_code: 'express_code', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 9, required: false, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '订单创建时间', field_code: 'order_create_time', field_type: 'datetime', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 10, required: false, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '预期到货时间', field_code: 'expect_start_time', field_type: 'datetime', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 11, required: false, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '备注', field_code: 'remark', field_type: 'textarea', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 12, required: false, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '单据总行数', field_code: 'total_order_lines', field_type: 'number', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 13, required: false, status: 1 }, // ─── 入库明细表格(is_table = true) ───────────────────────── - { business_type: 'RECEIPT', platform: 'default', field_name: '入库明细', field_code: 'items', field_type: 'text', is_table: true, table_config: { columns: 6, headers: ['商品编码', '商品名称', '条码', '计划数量', '已收数量', '库存类型'] }, group_field: 'entry_items', group_label: '入库明细', group_sort: 2, sort_order: 1, required: false, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '入库明细', field_code: 'items', field_type: 'text', is_table: true, table_config: { columns: 6, headers: [ '商品编码', '商品名称', '条码', '计划数量', '已收数量', '库存类型' ] }, group_field: 'entry_items', group_label: '入库明细', group_sort: 2, sort_order: 1, required: false, status: 1 }, ]; module.exports.up = async queryInterface => { // 基于唯一索引做幂等插入 const { sequelize } = queryInterface; - for (const item of RECEIPT_PRINT_ITEMS) { + for (const item of ENTRY_ORDER_PRINT_ITEMS) { await sequelize.query( `INSERT IGNORE INTO \`${TABLE}\` (business_type, platform, field_name, field_code, field_type, is_table, table_config, group_field, group_label, group_sort, sort_order, required, status, created_at, updated_at) @@ -62,6 +62,6 @@ module.exports.up = async queryInterface => { module.exports.down = async queryInterface => { const { sequelize } = queryInterface; await sequelize.query( - `DELETE FROM \`${TABLE}\` WHERE business_type = 'RECEIPT' AND platform = 'default'`, + `DELETE FROM \`${TABLE}\` WHERE business_type = 'ENTRY_ORDER' AND platform = 'default'` ); }; diff --git a/database/migrations/20260702-add-lock-unlock-to-wms-storage-transaction.js b/database/migrations/20260702-add-lock-unlock-to-wms-storage-transaction.js new file mode 100644 index 0000000..3c0b67b --- /dev/null +++ b/database/migrations/20260702-add-lock-unlock-to-wms-storage-transaction.js @@ -0,0 +1,26 @@ +'use strict'; + +/** + * 为 wms_storage_transaction.transaction_type ENUM 增加 LOCK / UNLOCK。 + * LOCK:分配储位锁定 + * UNLOCK:取消分配储位解锁 + */ +module.exports = { + async up(db) { + await db.query(` + ALTER TABLE wms_storage_transaction + MODIFY COLUMN transaction_type ENUM( + 'INBOUND', 'OUTBOUND', 'TRANSFER_OUT', 'TRANSFER_IN', 'LOCK', 'UNLOCK' + ) NOT NULL COMMENT '交易类型:INBOUND入库 OUTBOUND出库 TRANSFER_OUT移出 TRANSFER_IN移入 LOCK分配储位锁定 UNLOCK取消分配储位解锁' + `); + }, + + async down(db) { + await db.query(` + ALTER TABLE wms_storage_transaction + MODIFY COLUMN transaction_type ENUM( + 'INBOUND', 'OUTBOUND', 'TRANSFER_OUT', 'TRANSFER_IN' + ) NOT NULL COMMENT '出入库类型' + `); + }, +}; diff --git a/database/migrations/20260702-alter-print-template-business-type.js b/database/migrations/20260702-alter-print-template-business-type.js new file mode 100644 index 0000000..625a797 --- /dev/null +++ b/database/migrations/20260702-alter-print-template-business-type.js @@ -0,0 +1,28 @@ +'use strict'; + +/** + * 扩展 wms_print_template 表 business_type 字段长度:VARCHAR(10) → VARCHAR(50)。 + * + * 背景:business_type 原有长度 10,无法容纳 ENTRY_ORDER(11 字符), + * 需要与 wms_print_items.business_type VARCHAR(50) 保持一致。 + */ + +module.exports.up = async queryInterface => { + const { sequelize } = queryInterface; + + await sequelize.query( + `ALTER TABLE \`wms_print_template\` + MODIFY COLUMN \`business_type\` VARCHAR(50) NOT NULL COMMENT '类型'` + ); +}; + +module.exports.down = async queryInterface => { + const { sequelize } = queryInterface; + + // 注意:如果表中已存在 business_type 长度超过 10 的数据(如 ENTRY_ORDER), + // 此回滚会因数据截断而失败。执行前请确认数据已清理或回迁。 + await sequelize.query( + `ALTER TABLE \`wms_print_template\` + MODIFY COLUMN \`business_type\` VARCHAR(10) NOT NULL COMMENT '类型'` + ); +}; diff --git a/database/migrations/20260702-fix-receipt-a5-template.js b/database/migrations/20260702-fix-receipt-a5-template.js new file mode 100644 index 0000000..b8370df --- /dev/null +++ b/database/migrations/20260702-fix-receipt-a5-template.js @@ -0,0 +1,310 @@ +'use strict'; + +/** + * 入库单 A5 默认打印模板(ENTRY_ORDER 业务类型)。 + * + * 严格参照出库单"拣货单A5模板"(id=18)的格式与渲染引擎约定: + * - 标签元素(纯文字)使用 custom: true + content + 扁平化样式属性 + * - 数据元素使用 field_code(无 custom)+ 扁平化样式属性 + * - 分割线使用 line 类型 + * - 表格使用 table 类型,rows 数组每项为列定义对象(type: "text", field_code, content, width 等) + * - 字体大小使用 fontSize(字符串类型,如 "10") + * - 加粗使用 bold(布尔类型) + * - textAlign 用于对齐 + * + * 模板布局(A5 148mm×210mm): + * 1. 标题:"入 库 单"(fontSize: 18, bold: true, textAlign: center) + * 2. 分割线 + * 3. 信息区(标签+字段模式,每行左右两列): + * 入库单号:entry_order_code | 业务类型:order_type + * 供应商:supplier_name | 采购单号:purchase_order_code + * 仓库:warehouse_name | 货主:store_name + * 物流公司:logistics_name | 运单号:express_code + * 创建时间:order_create_time | 预期到货:expect_start_time + * 4. 分割线 + * 5. 入库明细标题 + * 6. 表格(6列):商品编码、商品名称、条码、计划数量、已收数量、库存类型 + * - 每列为 type: "text" 的扁平对象(参照 id=18 格式) + * 7. 分割线 + * 8. 单据总行数:total_order_lines + * 9. 备注:remark + * 10. 二维码:entry_order_code + * 11. 打印时间:print_time + */ + +const TABLE = 'wms_print_template'; + +// 基于时间戳生成唯一元素 ID 前缀 +const TS_BASE = Date.now(); + +/** + * 生成模板元素唯一 ID。 + * @param {string} type 元素类型前缀(text/line/table/barcode/qrcode) + * @param {number} seq 序号 + * @return {string} 唯一 ID + */ +function makeId(type, seq) { + return `${type}_${TS_BASE}_${String(seq).padStart(4, '0')}`; +} + +/** + * 生成 text 类型标签元素(纯文字标签,如"入库单号:"),有 custom: true。 + * @param {number} seq 序号 + * @param {number} top 顶部位置(mm) + * @param {number} left 左侧位置(mm) + * @param {number} width 宽度(mm) + * @param {number} height 高度(mm) + * @param {string} content 文字内容 + * @param {string} fontSize 字体大小(字符串类型) + * @param {object} options 可选配置 { bold, textAlign } + * @return {object} 标签元素 + */ +function label(seq, top, left, width, height, content, fontSize, options = {}) { + return { + id: makeId('text', seq), + type: 'text', + top, + left, + width, + height, + custom: true, + content, + fontSize, + bold: options.bold || false, + italic: false, + underline: false, + rotate: 0, + textAlign: options.textAlign || 'left', + lineHeight: height, + }; +} + +/** + * 生成 text 类型数据字段元素(绑定 field_code),无 custom。 + * @param {number} seq 序号 + * @param {number} top 顶部位置(mm) + * @param {number} left 左侧位置(mm) + * @param {number} width 宽度(mm) + * @param {number} height 高度(mm) + * @param {string} fieldCode 字段编码 + * @param {string} fontSize 字体大小(字符串类型) + * @param {object} options 可选配置 { bold, textAlign } + * @return {object} 数据字段元素 + */ +function field(seq, top, left, width, height, fieldCode, fontSize, options = {}) { + return { + id: makeId('text', seq), + type: 'text', + top, + left, + width, + height, + field_code: fieldCode, + fontSize, + bold: options.bold || false, + italic: false, + underline: false, + rotate: 0, + textAlign: options.textAlign || 'left', + lineHeight: height, + }; +} + +/** + * 生成分割线元素。 + * @param {number} seq 序号 + * @param {number} top 顶部位置(mm) + * @param {number} left 左侧位置(mm) + * @param {number} width 宽度(mm) + * @param {number} height 高度(mm) + * @return {object} 分割线元素 + */ +function lineEl(seq, top, left, width, height) { + return { + id: makeId('line', seq), + type: 'line', + top, + left, + width, + height, + }; +} + +/** + * 生成二维码元素。 + * @param {number} seq 序号 + * @param {number} top 顶部位置(mm) + * @param {number} left 左侧位置(mm) + * @param {number} width 宽度(mm) + * @param {number} height 高度(mm) + * @param {string} fieldCode 字段编码 + * @param {string} fontSize 字体大小 + * @return {object} 二维码元素 + */ +function qrcodeEl(seq, top, left, width, height, fieldCode, fontSize) { + return { + id: makeId('qrcode', seq), + type: 'qrcode', + top, + left, + width, + height, + field_code: fieldCode, + fontSize, + bold: false, + italic: false, + underline: false, + rotate: 0, + textAlign: 'center', + lineHeight: 6, + }; +} + +/** + * 生成表格列定义(严格参照 id=18 rows 格式)。 + * 每项为 type: "text" 的扁平对象,同时包含 field_code、content(中文表头)、width、样式属性。 + * @param {number} seq 序号 + * @param {string} fieldCode 字段编码 + * @param {string} content 中文表头内容 + * @param {number} colWidth 列宽(mm) + * @param {string} fontSize 字体大小 + * @param {boolean} bold 是否加粗 + * @param {string} textAlign 对齐方式 + * @return {object} 列定义对象 + */ +function tableColumn(seq, fieldCode, content, colWidth, fontSize, bold, textAlign) { + return { + id: makeId('text', seq), + type: 'text', + field_code: fieldCode, + content, + width: colWidth, + height: 6, + fontSize, + bold: bold || false, + italic: false, + underline: false, + rotate: 0, + textAlign: textAlign || 'left', + lineHeight: 6, + }; +} + +// ─── 构建入库单 A5 模板元素数组 ───────────────────────────── + +const templateContent = [ + + // 1. 标题:入 库 单 + label(1, 6, 0, 148, 10, '入 库 单', '18', { bold: true, textAlign: 'center' }), + + // 2. 分割线 + lineEl(2, 18, 10, 128, 0.5), + + // 3. 信息区 - 第一行:入库单号 | 业务类型 + label(3, 21, 10, 26, 7, '入库单号:', '10'), + field(4, 21, 36, 46, 7, 'entry_order_code', '10'), + label(5, 21, 84, 20, 7, '业务类型:', '10'), + field(6, 21, 104, 34, 7, 'order_type', '10'), + + // 3. 信息区 - 第二行:供应商 | 采购单号 + label(7, 29, 10, 20, 7, '供应商:', '10'), + field(8, 29, 30, 52, 7, 'supplier_name', '10'), + label(9, 29, 84, 26, 7, '采购单号:', '10'), + field(10, 29, 110, 28, 7, 'purchase_order_code', '10'), + + // 3. 信息区 - 第三行:仓库 | 货主 + label(11, 37, 10, 18, 7, '仓库:', '10'), + field(12, 37, 28, 54, 7, 'warehouse_name', '10'), + label(13, 37, 84, 18, 7, '货主:', '10'), + field(14, 37, 102, 36, 7, 'store_name', '10'), + + // 3. 信息区 - 第四行:物流公司 | 运单号 + label(15, 45, 10, 26, 7, '物流公司:', '10'), + field(16, 45, 36, 46, 7, 'logistics_name', '10'), + label(17, 45, 84, 20, 7, '运单号:', '10'), + field(18, 45, 104, 34, 7, 'express_code', '10'), + + // 3. 信息区 - 第五行:创建时间 | 预期到货 + label(19, 53, 10, 26, 7, '创建时间:', '10'), + field(20, 53, 36, 46, 7, 'order_create_time', '10'), + label(21, 53, 84, 26, 7, '预期到货:', '10'), + field(22, 53, 110, 28, 7, 'expect_start_time', '10'), + + // 4. 分割线 + lineEl(23, 62, 10, 128, 0.5), + + // 5. 入库明细标题 + label(24, 65, 10, 128, 7, '入库明细', '11', { bold: true, textAlign: 'left' }), + + // 6. 表格(严格参照 id=18 rows 格式:每列为 type: "text" 对象) + { + id: makeId('table', 25), + type: 'table', + top: 74, + left: 10, + width: 128, + height: 75, + rowHeight: 6, + headerHeight: 6, + rows: [ + tableColumn(26, 'item_code', '商品编码', 22, '9', false, 'left'), + tableColumn(27, 'item_name', '商品名称', 40, '9', false, 'left'), + tableColumn(28, 'item_barcode', '条码', 22, '9', false, 'left'), + tableColumn(29, 'plan_qty', '计划数量', 18, '9', false, 'left'), + tableColumn(30, 'received_qty', '已收数量', 18, '9', false, 'left'), + tableColumn(31, 'inventory_type', '库存类型', 8, '9', false, 'left'), + ], + }, + + // 7. 分割线 + lineEl(32, 151, 10, 128, 0.5), + + // 8. 单据总行数 + label(33, 155, 64, 26, 7, '单据总行数:', '9'), + field(34, 155, 90, 48, 7, 'total_order_lines', '9'), + + // 9. 备注 + label(35, 164, 10, 14, 7, '备注:', '9'), + field(36, 164, 24, 114, 7, 'remark', '9'), + + // 10. 二维码:entry_order_code + qrcodeEl(37, 4, 120, 24, 24, 'entry_order_code', '8'), + + // 11. 打印时间 + label(38, 174, 10, 26, 7, '打印时间:', '9'), + field(39, 174, 36, 102, 7, 'print_time', '9'), + +]; + +module.exports.up = async queryInterface => { + const { sequelize } = queryInterface; + + // 先删除可能存在的旧版本 id=20 + await sequelize.query( + `DELETE FROM \`${TABLE}\` WHERE id = 20`, + { type: sequelize.QueryTypes.DELETE } + ); + + // 插入修正后的入库单 A5 模板(id=20) + await sequelize.query( + `INSERT INTO \`${TABLE}\` + (id, business_type, template_name, platform, warehouse_id, page_width, page_height, template_content, template_type, template_url, is_default, status, create_at, update_at) + VALUES (20, 'ENTRY_ORDER', '入库单A5模板', 'default', NULL, 148, 210, :template_content, 'CUSTOM', '', true, 'ACTIVE', NOW(), NOW())`, + { + replacements: { + template_content: JSON.stringify(templateContent), + }, + type: sequelize.QueryTypes.INSERT, + } + ); +}; + +module.exports.down = async queryInterface => { + const { sequelize } = queryInterface; + await sequelize.query( + `DELETE FROM \`${TABLE}\` WHERE id = 20`, + { type: sequelize.QueryTypes.DELETE } + ); +}; + +module.exports.templateContent = templateContent; diff --git a/database/migrations/20260702-migrate-entry-order-print-data.js b/database/migrations/20260702-migrate-entry-order-print-data.js new file mode 100644 index 0000000..1b47e12 --- /dev/null +++ b/database/migrations/20260702-migrate-entry-order-print-data.js @@ -0,0 +1,53 @@ +'use strict'; + +/** + * 将 wms_print_items 和 wms_print_template 表中已存在的入库单打印数据 + * 从 RECEIPT 迁移到 ENTRY_ORDER。 + * + * 背景: + * - RECEIPT 下同时有收货单(platform=warehouse)和入库单(platform=default)的数据 + * - 只有 platform='default' 的才是入库单,需要迁移 + * - platform='warehouse' 的是收货单,保留在 RECEIPT + * + * up: 将 business_type='RECEIPT' AND platform='default' → business_type='ENTRY_ORDER' + * down:将 business_type='ENTRY_ORDER' AND platform='default' → business_type='RECEIPT' + */ + +const PRINT_ITEMS_TABLE = 'wms_print_items'; +const PRINT_TEMPLATE_TABLE = 'wms_print_template'; + +module.exports.up = async queryInterface => { + const { sequelize } = queryInterface; + + // 1) wms_print_items:入库单打印项迁移 + await sequelize.query( + `UPDATE \`${PRINT_ITEMS_TABLE}\` + SET business_type = 'ENTRY_ORDER', updated_at = NOW() + WHERE business_type = 'RECEIPT' AND platform = 'default'` + ); + + // 2) wms_print_template:入库单打印模板迁移 + await sequelize.query( + `UPDATE \`${PRINT_TEMPLATE_TABLE}\` + SET business_type = 'ENTRY_ORDER', update_at = NOW() + WHERE business_type = 'RECEIPT' AND platform = 'default'` + ); +}; + +module.exports.down = async queryInterface => { + const { sequelize } = queryInterface; + + // 1) wms_print_items:入库单打印项回退 + await sequelize.query( + `UPDATE \`${PRINT_ITEMS_TABLE}\` + SET business_type = 'RECEIPT', updated_at = NOW() + WHERE business_type = 'ENTRY_ORDER' AND platform = 'default'` + ); + + // 2) wms_print_template:入库单打印模板回退 + await sequelize.query( + `UPDATE \`${PRINT_TEMPLATE_TABLE}\` + SET business_type = 'RECEIPT', update_at = NOW() + WHERE business_type = 'ENTRY_ORDER' AND platform = 'default'` + ); +}; diff --git a/database/migrations/20260702-seed-receipt-default-template.js b/database/migrations/20260702-seed-receipt-default-template.js new file mode 100644 index 0000000..6ef39db --- /dev/null +++ b/database/migrations/20260702-seed-receipt-default-template.js @@ -0,0 +1,42 @@ +'use strict'; + +/** + * 入库单 A5 默认打印模板(ENTRY_ORDER 业务类型)数据清理迁移。 + * + * 背景: + * 旧版本 migration 已创建了一个格式正确的入库单模板(id=20,扁平化 content/field_code/bold/fontSize 风格)。 + * 本 migration 后来又插入了一个格式错误的模板(id=21,使用了 label+style 包装,与渲染引擎不兼容)。 + * + * 本迁移的作用: + * - 删除格式错误的重复模板 id=21(如果存在) + * - 保留下一个格式正确的模板(id=20)继续使用 + * + * 渲染引擎解析逻辑见 app/service/systemMethods/print.js(customize 分支): + * - 直接读取 item.content / item.fontSize / item.bold / item.textAlign 等扁平化属性 + * - 有 field_code 的元素用 data[field_code] 值覆盖 content + * - 不支持 label / style 对象包装 + */ + +const TABLE = 'wms_print_template'; + +module.exports.up = async queryInterface => { + const { sequelize } = queryInterface; + + // 删除格式错误的重复模板(id=21,使用了 label+style 包装格式) + // 保留格式正确的模板 id=20(扁平化 content/field_code/bold/fontSize 风格) + const [ duplicate ] = await sequelize.query( + `SELECT id FROM \`${TABLE}\` WHERE id = 21 AND business_type = 'ENTRY_ORDER' AND template_name = '入库单A5模板' AND warehouse_id IS NULL AND delete_at IS NULL LIMIT 1`, + { type: sequelize.QueryTypes.SELECT } + ); + + if (duplicate) { + await sequelize.query( + `DELETE FROM \`${TABLE}\` WHERE id = 21`, + { type: sequelize.QueryTypes.DELETE } + ); + } +}; + +module.exports.down = async () => { + // down 不回滚:删除 id=21 是一条清理操作,不需要恢复 +}; diff --git a/database/migrations/20260702-seed-receipt-print-items-v2.js b/database/migrations/20260702-seed-receipt-print-items-v2.js new file mode 100644 index 0000000..f068a2c --- /dev/null +++ b/database/migrations/20260702-seed-receipt-print-items-v2.js @@ -0,0 +1,151 @@ +'use strict'; + +/** + * ENTRY_ORDER(入库单)打印项配置 v2 补充。 + * + * 在 v1(20260622150000)基础上新增: + * - entry_order_info 组:15 个新字段(sort_order 14~28) + * - entry_items 表格:columns 从 6 扩展为 11,新增 5 列 + * - entry_items_info 组:17 个独立字段(group_sort=3, sort_order 1~17) + * + * up:INSERT IGNORE + UPDATE 表格配置 + * down:先恢复表格原始配置,再删除新增记录 + */ + +const TABLE = 'wms_print_items'; + +// ─── 新增打印项 ──────────────────────────────────────────────── +const NEW_PRINT_ITEMS = [ + // ─── entry_order_info 组补充(group_sort=1, sort_order 14~28) ── + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '入库单ID', field_code: 'id', field_type: 'number', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 14, required: false, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '来源类型', field_code: 'source_type', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 15, required: false, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '同步状态', field_code: 'sync_status', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 16, required: false, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '同步返回信息', field_code: 'sync_message', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 17, required: false, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '仓库ID', field_code: 'warehouse_id', field_type: 'number', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 18, required: false, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '货主ID', field_code: 'store_id', field_type: 'number', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 19, required: false, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '最迟预期到货时间', field_code: 'expect_end_time', field_type: 'datetime', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 20, required: false, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '物流公司编码', field_code: 'logistics_code', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 21, required: false, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '供应商编码', field_code: 'supplier_code', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 22, required: false, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '费用是否记录', field_code: 'expense_record', field_type: 'number', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 23, required: false, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '是否启用', field_code: 'is_enabled', field_type: 'number', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 24, required: false, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '创建时间', field_code: 'created_at', field_type: 'datetime', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 25, required: false, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '更新时间', field_code: 'updated_at', field_type: 'datetime', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 26, required: false, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '关联仓库名称', field_code: 'warehouse_company_name', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 27, required: false, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '关联货主名称', field_code: 'store_company_name', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 28, required: false, status: 1 }, + + // ─── entry_items_info 独立字段(group_sort=3) ────────────────── + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '商品SKU ID', field_code: 'stock_id', field_type: 'number', group_field: 'entry_items_info', group_label: '入库明细信息', group_sort: 3, sort_order: 1, required: false, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '外部商品编码', field_code: 'external_item_code', field_type: 'text', group_field: 'entry_items_info', group_label: '入库明细信息', group_sort: 3, sort_order: 2, required: false, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '外部商品ID', field_code: 'external_item_id', field_type: 'number', group_field: 'entry_items_info', group_label: '入库明细信息', group_sort: 3, sort_order: 3, required: false, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '仓库商品编码', field_code: 'warehouse_item_code', field_type: 'text', group_field: 'entry_items_info', group_label: '入库明细信息', group_sort: 3, sort_order: 4, required: false, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '仓库商品名称', field_code: 'warehouse_item_name', field_type: 'text', group_field: 'entry_items_info', group_label: '入库明细信息', group_sort: 3, sort_order: 5, required: false, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '仓库商品规格', field_code: 'warehouse_item_spec', field_type: 'text', group_field: 'entry_items_info', group_label: '入库明细信息', group_sort: 3, sort_order: 6, required: false, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '仓库当前库存总量', field_code: 'warehouse_quantity', field_type: 'number', group_field: 'entry_items_info', group_label: '入库明细信息', group_sort: 3, sort_order: 7, required: false, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '仓库锁定数量', field_code: 'warehouse_locked_quantity', field_type: 'number', group_field: 'entry_items_info', group_label: '入库明细信息', group_sort: 3, sort_order: 8, required: false, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '是否批次管理', field_code: 'warehouse_is_batch_mgmt', field_type: 'text', group_field: 'entry_items_info', group_label: '入库明细信息', group_sort: 3, sort_order: 9, required: false, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '是否效期管理', field_code: 'warehouse_is_shelf_life_mgmt', field_type: 'text', group_field: 'entry_items_info', group_label: '入库明细信息', group_sort: 3, sort_order: 10, required: false, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '直入已入库数量', field_code: 'direct_inbound_quantity', field_type: 'number', group_field: 'entry_items_info', group_label: '入库明细信息', group_sort: 3, sort_order: 11, required: false, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '剩余可入库数量', field_code: 'remaining_quantity', field_type: 'number', group_field: 'entry_items_info', group_label: '入库明细信息', group_sort: 3, sort_order: 12, required: false, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '外部业务编码', field_code: 'out_biz_code', field_type: 'text', group_field: 'entry_items_info', group_label: '入库明细信息', group_sort: 3, sort_order: 13, required: false, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '订单行号', field_code: 'order_line_no', field_type: 'number', group_field: 'entry_items_info', group_label: '入库明细信息', group_sort: 3, sort_order: 14, required: false, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '货主编码', field_code: 'owner_code', field_type: 'text', group_field: 'entry_items_info', group_label: '入库明细信息', group_sort: 3, sort_order: 15, required: false, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '库存类型', field_code: 'inventory_type', field_type: 'text', group_field: 'entry_items_info', group_label: '入库明细信息', group_sort: 3, sort_order: 16, required: false, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '已确认收货数量', field_code: 'confirm_quantity', field_type: 'number', group_field: 'entry_items_info', group_label: '入库明细信息', group_sort: 3, sort_order: 17, required: false, status: 1 }, +]; + +// ─── 旧 items 表格配置(v1) ──────────────────────────────────── +const OLD_ITEMS_TABLE_CONFIG = { + columns: 6, + headers: [ '商品编码', '商品名称', '条码', '计划数量', '已收数量', '库存类型' ], +}; + +// ─── 新 items 表格配置(v2 扩展为 11 列) ─────────────────────── +const NEW_ITEMS_TABLE_CONFIG = { + columns: 11, + headers: [ '行号', '商品编码(外部)', '商品名称', '条码', '仓库商品编码', '计划数量', '已收数量', '已确认数量', '直入数量', '剩余可入库', '库存类型' ], +}; + +// ══════════════════════════════════════════════════════════════════ +const NEW_FIELD_CODES = NEW_PRINT_ITEMS.map(it => it.field_code); + +module.exports.up = async queryInterface => { + const { sequelize } = queryInterface; + + // 1) 插入所有新增打印项(幂等) + for (const item of NEW_PRINT_ITEMS) { + await sequelize.query( + `INSERT IGNORE INTO \`${TABLE}\` + (business_type, platform, field_name, field_code, field_type, is_table, table_config, group_field, group_label, group_sort, sort_order, required, status, created_at, updated_at) + VALUES (:business_type, :platform, :field_name, :field_code, :field_type, :is_table, :table_config, :group_field, :group_label, :group_sort, :sort_order, :required, :status, NOW(), NOW())`, + { + replacements: { + business_type: item.business_type, + platform: item.platform, + field_name: item.field_name, + field_code: item.field_code, + field_type: item.field_type, + is_table: item.is_table ? 1 : 0, + table_config: item.table_config ? JSON.stringify(item.table_config) : null, + group_field: item.group_field || null, + group_label: item.group_label || null, + group_sort: item.group_sort || 0, + sort_order: item.sort_order || 0, + required: item.required ? 1 : 0, + status: item.status, + }, + type: sequelize.QueryTypes.INSERT, + } + ); + } + + // 2) 更新 items 表格配置:6 列 → 11 列 + await sequelize.query( + `UPDATE \`${TABLE}\` + SET table_config = :table_config, + updated_at = NOW() + WHERE business_type = 'ENTRY_ORDER' + AND platform = 'default' + AND field_code = 'items'`, + { + replacements: { + table_config: JSON.stringify(NEW_ITEMS_TABLE_CONFIG), + }, + type: sequelize.QueryTypes.UPDATE, + } + ); +}; + +module.exports.down = async queryInterface => { + const { sequelize } = queryInterface; + + // 1) 恢复 items 表格原有配置(columns:6) + await sequelize.query( + `UPDATE \`${TABLE}\` + SET table_config = :table_config, + updated_at = NOW() + WHERE business_type = 'ENTRY_ORDER' + AND platform = 'default' + AND field_code = 'items'`, + { + replacements: { + table_config: JSON.stringify(OLD_ITEMS_TABLE_CONFIG), + }, + type: sequelize.QueryTypes.UPDATE, + } + ); + + // 2) 精确删除本次新增的所有打印项 + if (NEW_FIELD_CODES.length > 0) { + const placeholders = NEW_FIELD_CODES.map(() => '?').join(','); + await sequelize.query( + `DELETE FROM \`${TABLE}\` + WHERE business_type = 'ENTRY_ORDER' + AND platform = 'default' + AND field_code IN (${placeholders})`, + { + replacements: NEW_FIELD_CODES, + type: sequelize.QueryTypes.DELETE, + } + ); + } +}; diff --git a/methods/changes/system.json b/methods/changes/system.json index 63bec51..85d490c 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -4647,5 +4647,31 @@ "该字段对订单列表的所有 method 均适用(current/dispatch/outsourced/history 模型均返回)。" ], "type": "updated" + }, + { + "version": "2026.07.02-system-02", + "date": "2026-07-02", + "summary": "新增 quick.waybill.toOrder 接口:根据运单号快速查询订单ID", + "methods": [ + "quick.waybill.toOrder" + ], + "notes": [ + "新增 quick 模块组(快捷查询)", + "查询 wms_order_express 表中 status=1 的有效记录", + "无需登录和鉴权(免登录/免鉴权)" + ], + "type": "added" + }, + { + "version": "2026.07.02-system-01", + "date": "2026-07-02", + "summary": "修正 quick.waybill.toOrder 的 isNeedLogin 为 true,与代码实现保持一致", + "methods": [ + "quick.waybill.toOrder" + ], + "notes": [ + "文档中 isNeedLogin 为 false,但代码 systemMethods/quick/waybill.js 中 _noNeedLogin 为空字符串,未将 toOrder 加入免登录列表,实际需要登录验证,修正文档以与代码一致。" + ], + "type": "fixed" } ] diff --git a/methods/system.json b/methods/system.json index 4d22ec6..afe7198 100644 --- a/methods/system.json +++ b/methods/system.json @@ -2,7 +2,7 @@ "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", "version": "0.3.5", - "updatedAt": "2026-06-30", + "updatedAt": "2026-07-02", "headers": [ { "name": "platform", @@ -26434,6 +26434,46 @@ ] } ] + }, + { + "groupName": "快捷操作", + "module": "quick", + "list": [ + { + "method": "quick.waybill.toOrder", + "description": "根据运单号快速查询订单ID。查询 wms_order_express 表中 status=1 的有效记录,返回对应的 order_id。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "waybill_code", + "type": "string", + "required": true, + "source": "body", + "description": "运单号" + } + ], + "response": [ + { + "name": "order_id", + "type": "number", + "required": true, + "description": "订单ID" + } + ], + "errors": [ + { + "code": 405, + "message": "运单号不能为空" + }, + { + "code": 405, + "message": "未找到该运单号对应的订单" + } + ] + } + ] } ] } diff --git a/script/deploy-init.cjs b/script/deploy-init.cjs index 96c34e7..1339d84 100644 --- a/script/deploy-init.cjs +++ b/script/deploy-init.cjs @@ -3,7 +3,6 @@ const fs = require('node:fs'); const path = require('node:path'); const { - ROOT, ensureCommandAvailable, ensureTempDeployDir, getNowStamp, @@ -101,7 +100,9 @@ function main() { try { const setupScript = [ 'set -euo pipefail', - `mkdir -p ${quoteForBash(config.deployRoot)} ${quoteForBash(config.controlDir)} ${quoteForBash(config.incomingDir)} ${quoteForBash(config.backupDir)} ${quoteForBash(config.stateDir)} ${quoteForBash(path.posix.join(config.deployRoot, 'logs'))} ${quoteForBash(path.posix.join(config.deployRoot, 'run'))} ${quoteForBash(path.posix.join(config.deployRoot, 'temp'))}`, + `mkdir -p ${quoteForBash(config.deployRoot)} ${quoteForBash(config.controlDir)} ${quoteForBash(config.incomingDir)} ${quoteForBash(config.backupDir)} ${quoteForBash(config.stateDir)} ${quoteForBash(path.posix.join(config.deployRoot, 'logs'))} ${quoteForBash(path.posix.join(config.deployRoot, 'run'))} ${quoteForBash(path.posix.join(config.deployRoot, 'temp'))} ${quoteForBash(path.posix.join(config.deployRoot, 'v1'))} ${quoteForBash(path.posix.join(config.deployRoot, 'v2'))}`, + `echo v1 > ${quoteForBash(path.posix.join(config.deployRoot, 'current.md'))}`, + `echo "proxy_pass http://127.0.0.1:6061;" > ${quoteForBash(path.posix.join(config.deployRoot, 'nginx-upstream.conf'))}`, ].join('\n'); runSsh(config, setupScript); runScp(config, archivePath, remoteArchive); @@ -134,4 +135,4 @@ function main() { console.log(`首次发布初始化完成: ${options.envName} -> ${config.deployRoot}`); } -main(); \ No newline at end of file +main(); diff --git a/script/deploy-ops.cjs b/script/deploy-ops.cjs index f91cf2f..1a3f74d 100644 --- a/script/deploy-ops.cjs +++ b/script/deploy-ops.cjs @@ -4,6 +4,12 @@ const { loadDeployConfig, quoteForBash, runSsh } = require('./deploy-lib.cjs'); const COMMANDS = new Set([ 'inspect', 'smoke', 'verify', 'cleanup-backups', 'gateway-probe' ]); +/** + * 解析命令行参数,返回环境名、命令及额外参数 + * + * @param {string[]} argv - 命令行参数数组 + * @return {{ envName: string, command: string, args: string[] }} 解析后的选项对象 + */ function parseArgs(argv) { const options = { envName: 'production', @@ -36,6 +42,48 @@ function parseArgs(argv) { return options; } +/** + * 通过 SSH 读取远端 current.md 文件,获取当前活跃端口 + * v1 → 6061,v2 → 6062 + * + * @param {object} config - 部署配置对象 + * @return {{ port: number, version: string, rawContent: string }} 活跃端口、版本标识及 current.md 原始内容 + * @throws {Error} 如果读取失败或内容不是 v1/v2 + */ +function getActivePortInfo(config) { + const currentMdPath = `${config.deployRoot}/current.md`; + const remoteScript = [ + 'set -euo pipefail', + `cat ${quoteForBash(currentMdPath)} 2>/dev/null || true`, + ].join('\n'); + + const output = runSsh(config, remoteScript, { stdio: 'pipe' }); + const rawContent = String(output || '').trim(); + + if (!rawContent) { + throw new Error( + `无法读取远端 ${currentMdPath},内容为空或文件不存在。` + ); + } + + const version = rawContent.replace(/\r/g, '').trim(); + if (version !== 'v1' && version !== 'v2') { + throw new Error( + `远端 current.md 内容无效: "${rawContent}",期望值为 v1 或 v2。文件路径: ${currentMdPath}` + ); + } + + const port = version === 'v1' ? 6061 : 6062; + + return { port, version, rawContent }; +} + +/** + * 通过 SSH 检查远端部署状态(state 目录、备份等) + * + * @param {object} config - 部署配置对象 + * @return {string} SSH 远程执行输出 + */ function inspectState(config) { const latestBackupFile = `${config.stateDir}/latest-backup.txt`; const remoteScript = [ @@ -54,14 +102,22 @@ function inspectState(config) { return runSsh(config, remoteScript, { stdio: 'pipe' }).trim(); } +/** + * 对当前活跃端口的关键路由执行冒烟探测 + * + * @param {object} config - 部署配置对象 + * @return {string} 各路由的 HTTP 状态码输出 + */ function smokeRoutes(config) { + const { port } = getActivePortInfo(config); const remoteScript = [ 'set -euo pipefail', + `PORT=${port}`, 'for path in / /api/docs /internal/v1/gateway /system; do', ' if [ "$path" = "/internal/v1/gateway" ] || [ "$path" = "/system" ]; then', - ' code=$(curl -sS -o /dev/null -w "%{http_code}" -X POST "http://127.0.0.1:6060$path" || true)', + ' code=$(curl -sS -o /dev/null -w "%{http_code}" -X POST "http://127.0.0.1:$PORT$path" || true)', ' else', - ' code=$(curl -sS -o /dev/null -w "%{http_code}" "http://127.0.0.1:6060$path" || true)', + ' code=$(curl -sS -o /dev/null -w "%{http_code}" "http://127.0.0.1:$PORT$path" || true)', ' fi', ' printf "%s %s\\n" "$path" "$code"', 'done', @@ -70,6 +126,13 @@ function smokeRoutes(config) { return runSsh(config, remoteScript, { stdio: 'pipe' }).trim(); } +/** + * 清理远端备份目录中指定的备份文件 + * + * @param {object} config - 部署配置对象 + * @param {string[]} names - 要清理的备份文件名列表 + * @return {string} 清理结果输出 + */ function cleanupBackups(config, names) { if (!names.length) { throw new Error('cleanup-backups 需要至少一个备份文件名'); @@ -85,38 +148,72 @@ function cleanupBackups(config, names) { return runSsh(config, remoteScript, { stdio: 'pipe' }).trim(); } +/** + * 对当前活跃端口的内部网关接口执行探活调用 + * + * @param {object} config - 部署配置对象 + * @param {string} methodName - method 名称 + * @param {string} payloadText - 请求体 JSON 字符串 + * @return {string} 网关接口响应内容 + */ function gatewayProbe(config, methodName, payloadText) { if (!methodName) { throw new Error('gateway-probe 需要 method 名称'); } + const { port } = getActivePortInfo(config); const payload = payloadText && payloadText.trim() ? payloadText : '{}'; const remoteScript = [ 'set -euo pipefail', `METHOD_NAME=${quoteForBash(methodName)}`, `PAYLOAD=${quoteForBash(payload)}`, + `PORT=${port}`, 'timestamp=$(date +%s)', - 'curl -sS -X POST "http://127.0.0.1:6060/internal/v1/gateway?method=$METHOD_NAME&v=1×tamp=$timestamp" -H "Content-Type: text/plain" --data "$PAYLOAD"', + 'curl -sS -X POST "http://127.0.0.1:$PORT/internal/v1/gateway?method=$METHOD_NAME&v=1×tamp=$timestamp" -H "Content-Type: text/plain" --data "$PAYLOAD"', ].join('\n'); return runSsh(config, remoteScript, { stdio: 'pipe' }).trim(); } +/** + * 显示远端 current.md 内容及当前活跃端口信息 + * + * @param {object} config - 部署配置对象 + */ +function showActiveInfo(config) { + let activeInfo; + try { + activeInfo = getActivePortInfo(config); + } catch (err) { + console.log(`[CURRENT_MD] 读取失败: ${err.message}`); + console.log(''); + return; + } + + console.log(`[CURRENT_MD] 内容: ${activeInfo.rawContent}`); + console.log(`[ACTIVE] 端口: ${activeInfo.port} (${activeInfo.version})`); + console.log(''); +} + function main() { const options = parseArgs(process.argv.slice(2)); const config = loadDeployConfig(options.envName); if (options.command === 'inspect') { + showActiveInfo(config); console.log(inspectState(config)); return; } if (options.command === 'smoke') { + showActiveInfo(config); + console.log(`[SMOKE]`); console.log(smokeRoutes(config)); return; } if (options.command === 'verify') { + showActiveInfo(config); console.log(inspectState(config)); console.log(''); console.log('[SMOKE]'); @@ -132,6 +229,8 @@ function main() { if (options.command === 'gateway-probe') { const methodName = options.args[0]; const payloadText = options.args[1] || '{}'; + showActiveInfo(config); + console.log(`[GATEWAY_PROBE] method=${methodName}`); console.log(gatewayProbe(config, methodName, payloadText)); return; } diff --git a/script/deploy-precheck.cjs b/script/deploy-precheck.cjs index f140c0e..0bb649b 100644 --- a/script/deploy-precheck.cjs +++ b/script/deploy-precheck.cjs @@ -20,10 +20,30 @@ function main() { 'if [ -d "$DEPLOY_ROOT" ] && [ -w "$DEPLOY_ROOT" ]; then echo DEPLOY_ROOT_WRITABLE; else echo DEPLOY_ROOT_NOT_WRITABLE; fi', 'if [ -d "$DEPLOY_ROOT/config" ]; then echo DEPLOY_CONFIG_EXISTS; else echo DEPLOY_CONFIG_MISSING; fi', 'if [ -d "$PARENT_DIR" ] && [ -w "$PARENT_DIR" ]; then echo PARENT_WRITABLE; else echo PARENT_NOT_WRITABLE; fi', + 'if [ -d "$DEPLOY_ROOT/v1" ]; then echo V1_DIR_EXISTS; else echo V1_DIR_MISSING; fi', + 'if [ -d "$DEPLOY_ROOT/v2" ]; then echo V2_DIR_EXISTS; else echo V2_DIR_MISSING; fi', + 'if [ -f "$DEPLOY_ROOT/nginx-upstream.conf" ]; then echo NGINX_UPSTREAM_EXISTS; else echo NGINX_UPSTREAM_MISSING; fi', 'if command -v node >/dev/null 2>&1; then echo REMOTE_NODE_OK; node -v; else echo REMOTE_NODE_MISSING; fi', 'if command -v npm >/dev/null 2>&1; then echo REMOTE_NPM_OK; npm -v; else echo REMOTE_NPM_MISSING; fi', 'if command -v tar >/dev/null 2>&1; then echo REMOTE_TAR_OK; tar --version | head -n 1; else echo REMOTE_TAR_MISSING; fi', - 'if command -v curl >/dev/null 2>&1; then if curl -fsS http://127.0.0.1:6060/ >/dev/null; then echo HEALTHCHECK_LOCAL_OK; else echo HEALTHCHECK_LOCAL_FAIL; fi; else echo REMOTE_CURL_MISSING; fi', + 'if command -v curl >/dev/null 2>&1; then', + ' CURRENT_FILE="$DEPLOY_ROOT/current.md"', + ' if [ -f "$CURRENT_FILE" ]; then', + ' ACTIVE_VERSION=$(cat "$CURRENT_FILE" | tr -d "[:space:]")', + ' if [ "$ACTIVE_VERSION" = "v1" ]; then', + ' if curl -fsS http://127.0.0.1:6061/ >/dev/null; then echo HEALTHCHECK_LOCAL_OK; else echo HEALTHCHECK_LOCAL_FAIL; fi', + ' elif [ "$ACTIVE_VERSION" = "v2" ]; then', + ' if curl -fsS http://127.0.0.1:6062/ >/dev/null; then echo HEALTHCHECK_LOCAL_OK; else echo HEALTHCHECK_LOCAL_FAIL; fi', + ' else', + ' echo HEALTHCHECK_LOCAL_SKIP_UNKNOWN_VERSION', + ' fi', + ' else', + ' V1_OK=false; V2_OK=false', + ' if curl -fsS http://127.0.0.1:6061/ >/dev/null; then V1_OK=true; fi', + ' if curl -fsS http://127.0.0.1:6062/ >/dev/null; then V2_OK=true; fi', + ' if [ "$V1_OK" = "true" ] || [ "$V2_OK" = "true" ]; then echo HEALTHCHECK_LOCAL_OK; else echo HEALTHCHECK_LOCAL_FAIL; fi', + ' fi', + 'else echo REMOTE_CURL_MISSING; fi', ].join('\n'); const output = runSsh(config, remoteScript, { stdio: 'pipe' }); @@ -54,4 +74,4 @@ function main() { } } -main(); \ No newline at end of file +main(); diff --git a/script/deploy-remote.cjs b/script/deploy-remote.cjs index b3457f5..13fc2fd 100644 --- a/script/deploy-remote.cjs +++ b/script/deploy-remote.cjs @@ -2,12 +2,10 @@ const fs = require('node:fs'); const path = require('node:path'); -const { URL } = require('node:url'); const { ROOT, buildArchive, buildRemoteCleanupGuard, - buildScopedEggStopScript, ensureCommandAvailable, getNowStamp, loadDeployConfig, @@ -15,67 +13,77 @@ const { runCommand, runScp, runSsh, - serializeCommands, } = require('./deploy-lib.cjs'); -const { recordVersionUpdate } = require('./version-registry.cjs'); -function splitPostDeployCommands(commands) { - const normalized = Array.isArray(commands) ? commands.filter(Boolean).map(item => String(item).trim()).filter(Boolean) : []; - const stopCommandPattern = /^(?:npm(?:\.cmd)?\s+(?:run\s+)?stop|egg-scripts\s+stop)(?:\s|$)/i; - const startCommandIndex = normalized.findIndex(item => /^npm\s+start(?:\s|$)/i.test(item)); - const stopCommandIndexes = normalized - .map((item, index) => (stopCommandPattern.test(item) ? index : -1)) - .filter(index => index >= 0); +/** + * 通过 SSH 读取远端 current.md 文件,获取当前活跃版本标识(v1 或 v2) + * + * @param {object} config - 部署配置对象 + * @param {string} deployRoot - 远端部署根目录,如 /www/wwwroot/qimen + * @return {string} 当前活跃版本标识,如 'v1' 或 'v2' + * @throws {Error} 如果读取失败或内容无效 + */ +function readRemoteCurrentVersion(config, deployRoot) { + const currentMdPath = `${deployRoot}/current.md`; + const script = `cat ${quoteForBash(currentMdPath)} 2>/dev/null || true`; - if (startCommandIndex === -1) { - return { - preStartCommands: normalized.filter((_, index) => !stopCommandIndexes.includes(index)), - startCommand: '', - }; + const output = runSsh(config, script, { stdio: 'pipe' }); + const rawVersion = String(output || '').trim(); + + if (!rawVersion) { + throw new Error( + `无法读取远端当前版本文件: ${currentMdPath}。请确保远端已存在 /www/wwwroot/qimen/current.md 且内容为 v1 或 v2。` + ); } - return { - preStartCommands: normalized.filter((_, index) => index !== startCommandIndex && !stopCommandIndexes.includes(index)), - startCommand: normalized[startCommandIndex], - }; + const normalized = rawVersion.replace(/\r/g, '').trim(); + if (normalized !== 'v1' && normalized !== 'v2') { + throw new Error( + `远端 current.md 内容无效: "${rawVersion}",期望值为 v1 或 v2。文件路径: ${currentMdPath}` + ); + } + + return normalized; } -function buildHealthCheckScript(healthCheckUrl) { - if (!healthCheckUrl) { - return ''; +/** + * 根据当前活跃版本确定目标部署目录(另一个实例目录) + * + * @param {string} currentVersion - 当前活跃版本,'v1' 或 'v2' + * @param {string} deployRoot - 远端部署根目录,如 /www/wwwroot/qimen + * @return {string} 目标部署目录,如 /www/wwwroot/qimen/v2 + */ +function resolveTargetDir(currentVersion, deployRoot) { + if (currentVersion === 'v1') { + return `${deployRoot}/v2`; } + return `${deployRoot}/v1`; +} - let fallbackUrl = ''; - try { - const parsed = new URL(healthCheckUrl); - const hostname = String(parsed.hostname || '').toLowerCase(); - const isLocalHost = hostname === '127.0.0.1' || hostname === 'localhost'; - if (!isLocalHost) { - const port = parsed.port || '6060'; - fallbackUrl = `http://127.0.0.1:${port}${parsed.pathname || '/'}${parsed.search || ''}`; - } - } catch (error) { - fallbackUrl = 'http://127.0.0.1:6060/'; +/** + * 根据当前活跃版本推导目标版本标识(v1 ↔ v2 互换) + * + * @param {string} currentVersion - 当前活跃版本,'v1' 或 'v2' + * @return {string} 目标版本标识,'v1' 或 'v2' + */ +function resolveTargetVersion(currentVersion) { + if (currentVersion === 'v1') { + return 'v2'; } + return 'v1'; +} - return [ - `HEALTHCHECK_URL=${quoteForBash(healthCheckUrl)}`, - ...(fallbackUrl ? [ `HEALTHCHECK_FALLBACK_URL=${quoteForBash(fallbackUrl)}` ] : []), - 'HEALTHCHECK_CURL_OPTS="--connect-timeout 2 --max-time 4"', - 'for attempt in $(seq 1 20); do', - ' if curl -fsS $HEALTHCHECK_CURL_OPTS "$HEALTHCHECK_URL" >/dev/null; then', - ' break', - ' fi', - ...(fallbackUrl ? [ ' if curl -fsS $HEALTHCHECK_CURL_OPTS "$HEALTHCHECK_FALLBACK_URL" >/dev/null; then', ' break', ' fi' ] : []), - ' if [ "$attempt" -eq 20 ]; then', - ...(fallbackUrl - ? [ ' echo "健康检查失败: $HEALTHCHECK_URL (fallback: $HEALTHCHECK_FALLBACK_URL)" >&2' ] - : [ ' echo "健康检查失败: $HEALTHCHECK_URL" >&2' ]), - ' exit 1', - ' fi', - ' sleep 1', - 'done', - ].join('\n'); +/** + * 根据版本标识返回对应监听端口(v1 → 6061,v2 → 6062) + * + * @param {string} targetVersion - 目标版本标识,'v1' 或 'v2' + * @return {number} 对应端口号 + */ +function getTargetPort(targetVersion) { + if (targetVersion === 'v1') { + return 6061; + } + return 6062; } function main() { @@ -87,105 +95,149 @@ function main() { ensureCommandAvailable('ssh', '请先安装 OpenSSH Client 并确保 ssh 在 PATH 中。'); ensureCommandAvailable('scp', '请先安装 OpenSSH Client 并确保 scp 在 PATH 中。'); + // 1. 读取远端 current.md,确定目标目录 + const currentVersion = readRemoteCurrentVersion(config, config.deployRoot); + const targetDir = resolveTargetDir(currentVersion, config.deployRoot); + console.log(`远端当前活跃版本: ${currentVersion},目标部署目录: ${targetDir}`); + + // 2. 本地打包(不变) const stamp = getNowStamp(); const packageJson = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8')); const packageVersion = String(packageJson.version || '0.0.0'); - const gitCommit = runCommand('git', [ 'rev-parse', 'HEAD' ]); const gitCommitShort = runCommand('git', [ 'rev-parse', '--short', 'HEAD' ]); - const gitBranch = runCommand('git', [ 'rev-parse', '--abbrev-ref', 'HEAD' ]); const releaseVersion = `v${packageVersion}-${stamp}-${gitCommitShort}`; const { archivePath } = buildArchive(stamp, config); const remoteArchive = `${config.incomingDir}/release-${stamp}.tar.gz`; - const remoteArchiveName = path.posix.basename(remoteArchive); - const latestBackupFile = `latest-backup.txt`; - const releaseStateFile = path.posix.join(config.stateDir, 'current-release.json'); - const releaseHistoryFile = path.posix.join(config.stateDir, 'release-history.jsonl'); - const backupName = `backup-${stamp}.tar.gz`; - const cleanupGuard = buildRemoteCleanupGuard(config.sharedDirs, config.preserveDirs); - const preDeployCommands = serializeCommands(config.preDeployCommands); - const postDeploy = splitPostDeployCommands(config.postDeployCommands); - const postDeployCommands = serializeCommands(postDeploy.preStartCommands); - const startCommand = postDeploy.startCommand; - const scopedStopCommand = buildScopedEggStopScript(config.deployRoot); - const detachedStartCommand = startCommand - ? `nohup bash -lc ${quoteForBash(startCommand)} >/tmp/wms-deploy-start.log 2>&1 &` - : ''; - const healthCheckCommand = buildHealthCheckScript(config.healthCheckUrl); - const releaseMeta = { - releaseVersion, - packageVersion, - gitCommit, - gitCommitShort, - gitBranch, - stamp, - deployedAt: new Date().toISOString(), - envName, - deployRoot: config.deployRoot, - archiveFile: remoteArchiveName, - backupFile: backupName, - }; - const releaseMetaPretty = JSON.stringify(releaseMeta, null, 2); - const releaseMetaLine = JSON.stringify(releaseMeta); + // 3. 远端创建目录结构(目标目录 + incoming 目录) const setupScript = [ 'set -euo pipefail', - `mkdir -p ${quoteForBash(config.deployRoot)} ${quoteForBash(config.controlDir)} ${quoteForBash(config.incomingDir)} ${quoteForBash(config.backupDir)} ${quoteForBash(config.stateDir)}`, + `mkdir -p ${quoteForBash(targetDir)} ${quoteForBash(config.incomingDir)}`, ].join('\n'); runSsh(config, setupScript); + console.log(`远端目录已就绪: ${targetDir}`); + + // 4. SCP 上传 tar.gz 到远端 incoming 目录 runScp(config, archivePath, remoteArchive); + console.log(`发布包已上传到远端: ${remoteArchive}`); + + // 5. 在目标目录清理旧代码、解压、安装依赖 + const cleanupGuard = buildRemoteCleanupGuard(config.sharedDirs, config.preserveDirs); const remoteScript = [ 'set -euo pipefail', - `DEPLOY_ROOT=${quoteForBash(config.deployRoot)}`, - `BACKUP_DIR=${quoteForBash(config.backupDir)}`, - `STATE_DIR=${quoteForBash(config.stateDir)}`, + `TARGET_DIR=${quoteForBash(targetDir)}`, `REMOTE_ARCHIVE=${quoteForBash(remoteArchive)}`, - `KEEP_BACKUPS=${Number(config.keepBackups)}`, - `BACKUP_NAME=${quoteForBash(backupName)}`, - `CURRENT_RELEASE_FILE=${quoteForBash(releaseStateFile)}`, - `RELEASE_HISTORY_FILE=${quoteForBash(releaseHistoryFile)}`, - `RELEASE_META_JSON=${quoteForBash(releaseMetaPretty)}`, - `RELEASE_META_LINE=${quoteForBash(releaseMetaLine)}`, - 'cd "$DEPLOY_ROOT"', - 'mkdir -p "$BACKUP_DIR" "$STATE_DIR"', - 'tar --exclude=.deploy -czf "$BACKUP_DIR/$BACKUP_NAME" .', - preDeployCommands, + // 进入目标目录,清理旧代码文件(保留 node_modules、logs、run、temp、.deploy 等运行时/状态目录) + 'cd "$TARGET_DIR"', `find . -mindepth 1 -maxdepth 1 ${cleanupGuard} -exec rm -rf {} +`, - 'tar -xzf "$REMOTE_ARCHIVE" -C "$DEPLOY_ROOT"', + // 解压发布包 + 'tar -xzf "$REMOTE_ARCHIVE" -C "$TARGET_DIR"', 'rm -f "$REMOTE_ARCHIVE"', - `printf '%s\\n' "$BACKUP_NAME" > ${quoteForBash(path.posix.join(config.stateDir, latestBackupFile))}`, - 'if [ ! -d "$DEPLOY_ROOT/config" ]; then echo "配置目录缺失: $DEPLOY_ROOT/config(首次发布请先创建并放置生产配置)" >&2; exit 1; fi', - postDeployCommands, - detachedStartCommand, - healthCheckCommand, - 'printf "%s\\n" "$RELEASE_META_JSON" > "$CURRENT_RELEASE_FILE"', - 'printf "%s\\n" "$RELEASE_META_LINE" >> "$RELEASE_HISTORY_FILE"', - 'ls -1t "$BACKUP_DIR"/*.tar.gz 2>/dev/null | tail -n +$((KEEP_BACKUPS + 1)) | xargs -r rm -f', - ].filter(Boolean).join('\n'); - - try { - runSsh(config, scopedStopCommand, { stdio: 'inherit' }); - } catch (error) { - console.warn(`定点停进程失败,继续发布流程: ${error.message}`); - } + // 在目标目录安装生产依赖 + 'npm install --production', + ].join('\n'); runSsh(config, remoteScript); + console.log(`远端目标目录已清理、解压并安装依赖: ${targetDir}`); + + // 推导目标版本标识与启动日志路径 + const targetVersion = resolveTargetVersion(currentVersion); + const targetPort = getTargetPort(targetVersion); + const startLogPath = `/tmp/wms-${targetVersion}-start.log`; + const currentMdPath = `${config.deployRoot}/current.md`; + + // 6. 更新远端 current.md 并启动新实例 + const switchAndStartScript = [ + 'set -euo pipefail', + // 更新 current.md 指向新版本 + `printf '%s\\n' ${quoteForBash(targetVersion)} > ${quoteForBash(currentMdPath)}`, + // 在目标目录后台启动 Egg.js 进程 + `cd ${quoteForBash(targetDir)}`, + `nohup bash -lc 'npm start' > ${quoteForBash(startLogPath)} 2>&1 &`, + `echo "已更新 current.md -> ${targetVersion},已在 ${targetDir} 启动新实例,启动日志: ${startLogPath}"`, + ].join('\n'); + + const switchOutput = runSsh(config, switchAndStartScript, { stdio: 'pipe' }); + console.log(String(switchOutput || '').trim()); + + // 6.5. 健康检查新实例(curl 循环等待,最多 60 秒) + const oldDir = `${config.deployRoot}/${currentVersion}`; + const healthCheckScript = [ + 'set -euo pipefail', + `TARGET_PORT=${targetPort}`, + 'for attempt in $(seq 1 30); do', + ' if curl -fsS --connect-timeout 2 --max-time 4 "http://127.0.0.1:$TARGET_PORT/" >/dev/null 2>&1; then', + ` echo "新实例 (${targetVersion}) 健康检查通过 (端口 $TARGET_PORT)"`, + ' break', + ' fi', + ' if [ "$attempt" -eq 30 ]; then', + ` echo "新实例 (${targetVersion}) 健康检查超时 (端口 $TARGET_PORT)" >&2`, + ' exit 1', + ' fi', + ' sleep 2', + 'done', + ].join('\n'); + try { - recordVersionUpdate({ - source: 'deploy:prod', - note: `env=${envName}`, - releaseVersion, - deployRoot: config.deployRoot, - remoteBackupFile: backupName, - remoteStateFile: releaseStateFile, - remoteHistoryFile: releaseHistoryFile, - }); - } catch (error) { - console.warn(`本地版本记录写入失败: ${error.message}`); + const healthOutput = runSsh(config, healthCheckScript, { stdio: 'pipe' }); + console.log(String(healthOutput || '').trim()); + } catch (err) { + console.warn(`[WARN] 新实例健康检查失败: ${err.message}`); + console.warn(`[WARN] 新实例 (${targetVersion}) 可能未完全就绪,请人工确认 127.0.0.1:${targetPort} 状态`); } - console.log(`发布完成: ${envName} -> ${config.username}@${config.host}:${config.deployRoot}`); + + // 6.55. 切换 Nginx upstream 端口并 reload + const nginxUpstreamPath = `${config.deployRoot}/nginx-upstream.conf`; + const switchNginxScript = [ + 'set -euo pipefail', + `printf 'proxy_pass http://127.0.0.1:%s;\\n' ${targetPort} > ${quoteForBash(nginxUpstreamPath)}`, + 'nginx -t && nginx -s reload', + `echo "Nginx upstream 已切换至 127.0.0.1:${targetPort}"`, + ].join('\n'); + + try { + const nginxOutput = runSsh(config, switchNginxScript, { stdio: 'pipe' }); + console.log(String(nginxOutput || '').trim()); + } catch (err) { + console.warn(`[WARN] Nginx upstream 切换失败: ${err.message}`); + console.warn(`[WARN] Nginx reload 可能未成功,请人工确认 ${nginxUpstreamPath} 内容并执行 nginx -s reload`); + } + + // 6.6. 停止旧实例(kill + 兜底 kill -9) + const stopOldScript = [ + 'set -euo pipefail', + `OLD_DIR=${quoteForBash(oldDir)}`, + `OLD_VERSION=${quoteForBash(currentVersion)}`, + 'OLD_PIDS=$(ps -eo pid=,args= | awk -v root="$OLD_DIR" \'index($0, root) && $2 ~ /node$/ { print $1 }\')', + 'if [ -z "$OLD_PIDS" ]; then', + ' echo "未找到旧实例 ($OLD_VERSION) 进程,跳过停止步骤"', + 'else', + ' echo "正在停止旧实例 ($OLD_VERSION): $OLD_PIDS"', + ' kill $OLD_PIDS || true', + ' sleep 3', + ' OLD_PIDS_REMAIN=$(ps -eo pid=,args= | awk -v root="$OLD_DIR" \'index($0, root) && $2 ~ /node$/ { print $1 }\')', + ' if [ -n "$OLD_PIDS_REMAIN" ]; then', + ' echo "旧实例 ($OLD_VERSION) 仍有残留进程,强制停止: $OLD_PIDS_REMAIN"', + ' kill -9 $OLD_PIDS_REMAIN || true', + ' fi', + ' echo "旧实例 ($OLD_VERSION) 已停止"', + 'fi', + ].join('\n'); + + try { + const stopOutput = runSsh(config, stopOldScript, { stdio: 'pipe' }); + console.log(String(stopOutput || '').trim()); + } catch (err) { + console.warn(`[WARN] 停止旧实例失败: ${err.message}`); + console.warn(`[WARN] 旧实例 (${currentVersion}) 可能仍在运行,请人工确认并停止`); + } + + // 7. 打印完成信息 + console.log(`发布完成: ${envName} -> ${config.username}@${config.host}:${targetDir}`); console.log(`线上版本号: ${releaseVersion}`); + console.log(`当前活跃版本已切换为: ${targetVersion}`); } -main(); \ No newline at end of file +main(); diff --git a/script/deploy-version.cjs b/script/deploy-version.cjs index 184bad8..6c88a13 100644 --- a/script/deploy-version.cjs +++ b/script/deploy-version.cjs @@ -26,6 +26,42 @@ function parseArgs(argv) { return options; } +/** + * 查询远端 v1/v2 活跃实例状态 + * @param {object} config - 部署配置 + * @return {{ version: string, port: number, currentMd: string } | null} 活跃实例信息,读不到返回 null + */ +function queryActiveInstance(config) { + const currentMdFile = path.posix.join(config.deployRoot, 'current.md'); + const remoteScript = [ + 'set -euo pipefail', + `FILE=${quoteForBash(currentMdFile)}`, + 'if [ -f "$FILE" ]; then', + ' cat "$FILE"', + 'else', + ' echo CURRENT_MD_NOT_FOUND', + 'fi', + ].join('\n'); + + const raw = runSsh(config, remoteScript, { stdio: 'pipe' }).trim(); + if (!raw || raw === 'CURRENT_MD_NOT_FOUND') { + return null; + } + + const version = raw.replace(/[\r\n\s]/g, ''); + if (version !== 'v1' && version !== 'v2') { + return null; + } + + const port = version === 'v2' ? 6062 : 6061; + return { version, port, currentMd: raw.split('\n')[0].trim() }; +} + +/** + * 查询远端当前 release 信息 + * @param {object} config - 部署配置 + * @return {object | string | null} 解析后的 JSON 或原始字符串,查不到返回 null + */ function queryCurrentRelease(config) { const releaseFile = path.posix.join(config.stateDir, 'current-release.json'); const remoteScript = [ @@ -40,18 +76,22 @@ function queryCurrentRelease(config) { const output = runSsh(config, remoteScript, { stdio: 'pipe' }).trim(); if (!output || output === 'ONLINE_VERSION_NOT_FOUND') { - console.log('ONLINE_VERSION_NOT_FOUND'); - return; + return null; } try { - const parsed = JSON.parse(output); - console.log(JSON.stringify(parsed, null, 2)); + return JSON.parse(output); } catch (error) { - console.log(output); + return output; } } +/** + * 查询远端 release 历史记录 + * @param {object} config - 部署配置 + * @param {number} limit - 返回最近 N 条记录 + * @return {Array | null} 历史记录数组,查不到返回 null + */ function queryReleaseHistory(config, limit) { const historyFile = path.posix.join(config.stateDir, 'release-history.jsonl'); const remoteScript = [ @@ -67,8 +107,7 @@ function queryReleaseHistory(config, limit) { const output = runSsh(config, remoteScript, { stdio: 'pipe' }).trim(); if (!output || output === 'ONLINE_VERSION_HISTORY_EMPTY') { - console.log('ONLINE_VERSION_HISTORY_EMPTY'); - return; + return null; } const lines = output.split(/\r?\n/).map(item => item.trim()).filter(Boolean); @@ -80,7 +119,7 @@ function queryReleaseHistory(config, limit) { records.push({ raw: line }); } } - console.log(JSON.stringify(records, null, 2)); + return records; } function main() { @@ -90,12 +129,17 @@ function main() { ensureCommandAvailable('ssh', '请先安装 OpenSSH Client 并确保 ssh 在 PATH 中。'); const config = loadDeployConfig(envName); + const active = queryActiveInstance(config); + if (options.history > 0) { - queryReleaseHistory(config, options.history); + const history = queryReleaseHistory(config, options.history); + console.log(JSON.stringify({ active, history }, null, 2)); return; } - queryCurrentRelease(config); + const release = queryCurrentRelease(config); + console.log(JSON.stringify({ active, release }, null, 2)); } -main(); \ No newline at end of file + +main(); diff --git a/script/rollback-remote.cjs b/script/rollback-remote.cjs index 0bc8dd9..7841415 100644 --- a/script/rollback-remote.cjs +++ b/script/rollback-remote.cjs @@ -1,77 +1,64 @@ 'use strict'; const path = require('node:path'); -const { URL } = require('node:url'); const { buildRemoteCleanupGuard, - buildScopedEggStopScript, ensureCommandAvailable, - getNowStamp, loadDeployConfig, quoteForBash, runSsh, - serializeCommands, } = require('./deploy-lib.cjs'); -function splitPostDeployCommands(commands) { - const normalized = Array.isArray(commands) ? commands.filter(Boolean).map(item => String(item).trim()).filter(Boolean) : []; - const stopCommandPattern = /^(?:npm(?:\.cmd)?\s+(?:run\s+)?stop|egg-scripts\s+stop)(?:\s|$)/i; - const startCommandIndex = normalized.findIndex(item => /^npm\s+start(?:\s|$)/i.test(item)); - const stopCommandIndexes = normalized - .map((item, index) => (stopCommandPattern.test(item) ? index : -1)) - .filter(index => index >= 0); +/** + * 通过 SSH 读取远端 current.md 文件,获取当前活跃版本标识(v1 或 v2) + * + * @param {object} config - 部署配置对象 + * @param {string} deployRoot - 远端部署根目录,如 /www/wwwroot/qimen + * @return {string} 当前活跃版本标识,如 'v1' 或 'v2' + * @throws {Error} 如果读取失败或内容无效 + */ +function readRemoteCurrentVersion(config, deployRoot) { + const currentMdPath = `${deployRoot}/current.md`; + const script = `cat ${quoteForBash(currentMdPath)} 2>/dev/null || true`; - if (startCommandIndex === -1) { - return { - preStartCommands: normalized.filter((_, index) => !stopCommandIndexes.includes(index)), - startCommand: '', - }; + const output = runSsh(config, script, { stdio: 'pipe' }); + const rawVersion = String(output || '').trim(); + + if (!rawVersion) { + throw new Error( + `无法读取远端当前版本文件: ${currentMdPath}。请确保远端已存在 ${deployRoot}/current.md 且内容为 v1 或 v2。` + ); } - return { - preStartCommands: normalized.filter((_, index) => index !== startCommandIndex && !stopCommandIndexes.includes(index)), - startCommand: normalized[startCommandIndex], - }; + const normalized = rawVersion.replace(/\r/g, '').trim(); + if (normalized !== 'v1' && normalized !== 'v2') { + throw new Error( + `远端 current.md 内容无效: "${rawVersion}",期望值为 v1 或 v2。文件路径: ${currentMdPath}` + ); + } + + return normalized; } -function buildHealthCheckScript(healthCheckUrl) { - if (!healthCheckUrl) { - return ''; +/** + * 根据版本标识返回对应监听端口(v1 → 6061,v2 → 6062) + * + * @param {string} targetVersion - 目标版本标识,'v1' 或 'v2' + * @return {number} 对应端口号 + */ +function getTargetPort(targetVersion) { + if (targetVersion === 'v1') { + return 6061; } - - let fallbackUrl = ''; - try { - const parsed = new URL(healthCheckUrl); - const hostname = String(parsed.hostname || '').toLowerCase(); - const isLocalHost = hostname === '127.0.0.1' || hostname === 'localhost'; - if (!isLocalHost) { - const port = parsed.port || '6060'; - fallbackUrl = `http://127.0.0.1:${port}${parsed.pathname || '/'}${parsed.search || ''}`; - } - } catch (error) { - fallbackUrl = 'http://127.0.0.1:6060/'; - } - - return [ - `HEALTHCHECK_URL=${quoteForBash(healthCheckUrl)}`, - ...(fallbackUrl ? [ `HEALTHCHECK_FALLBACK_URL=${quoteForBash(fallbackUrl)}` ] : []), - 'HEALTHCHECK_CURL_OPTS="--connect-timeout 2 --max-time 4"', - 'for attempt in $(seq 1 20); do', - ' if curl -fsS $HEALTHCHECK_CURL_OPTS "$HEALTHCHECK_URL" >/dev/null; then', - ' break', - ' fi', - ...(fallbackUrl ? [ ' if curl -fsS $HEALTHCHECK_CURL_OPTS "$HEALTHCHECK_FALLBACK_URL" >/dev/null; then', ' break', ' fi' ] : []), - ' if [ "$attempt" -eq 20 ]; then', - ...(fallbackUrl - ? [ ' echo "健康检查失败: $HEALTHCHECK_URL (fallback: $HEALTHCHECK_FALLBACK_URL)" >&2' ] - : [ ' echo "健康检查失败: $HEALTHCHECK_URL" >&2' ]), - ' exit 1', - ' fi', - ' sleep 1', - 'done', - ].join('\n'); + return 6062; } +/** + * 解析命令行中的 --backup= 参数,提取备份包名称 + * + * @param {string[]} argv - 命令行参数数组 + * @return {string} 备份包名称,如未指定则返回空字符串 + */ function parseBackupArg(argv) { const backupArg = argv.find(item => item.startsWith('--backup=')); if (!backupArg) { @@ -80,6 +67,11 @@ function parseBackupArg(argv) { return backupArg.slice('--backup='.length).trim(); } +/** + * 回滚入口函数: + * 读取远端 current.md → 确定当前活跃版本目录和端口 → 选择备份包 + * → 停进程 → 清理代码 → 解压备份 → npm install → 重启 → 健康检查 → 切换 Nginx + */ function main() { const envName = process.argv[2] || 'production'; const config = loadDeployConfig(envName); @@ -87,54 +79,142 @@ function main() { ensureCommandAvailable('ssh', '请先安装 OpenSSH Client 并确保 ssh 在 PATH 中。'); - const stamp = getNowStamp(); - const cleanupGuard = buildRemoteCleanupGuard(config.sharedDirs, config.preserveDirs); - const postDeploy = splitPostDeployCommands(config.postDeployCommands); - const postDeployCommands = serializeCommands(postDeploy.preStartCommands); - const startCommand = postDeploy.startCommand; - const scopedStopCommand = buildScopedEggStopScript(config.deployRoot); - const detachedStartCommand = startCommand - ? `nohup bash -lc ${quoteForBash(startCommand)} >/tmp/wms-rollback-start.log 2>&1 &` - : ''; - const latestBackupFile = path.posix.join(config.stateDir, 'latest-backup.txt'); - const healthCheckCommand = buildHealthCheckScript(config.healthCheckUrl); + // 1. 读取远端 current.md,确定当前活跃版本和目录 + const currentVersion = readRemoteCurrentVersion(config, config.deployRoot); + const currentDir = `${config.deployRoot}/${currentVersion}`; + const currentPort = getTargetPort(currentVersion); + console.log(`远端当前活跃版本: ${currentVersion},活跃目录: ${currentDir},端口: ${currentPort}`); - const remoteScript = [ + // 2. 确定备份包 + const latestBackupFile = path.posix.join(config.stateDir, 'latest-backup.txt'); + const selectBackupScript = [ 'set -euo pipefail', - `DEPLOY_ROOT=${quoteForBash(config.deployRoot)}`, `BACKUP_DIR=${quoteForBash(config.backupDir)}`, `LATEST_BACKUP_FILE=${quoteForBash(latestBackupFile)}`, `REQUESTED_BACKUP=${quoteForBash(backupName)}`, - `CURRENT_SAFETY_BACKUP=${quoteForBash(`rollback-safety-${stamp}.tar.gz`)}`, 'if [ -n "$REQUESTED_BACKUP" ]; then', ' TARGET_BACKUP="$REQUESTED_BACKUP"', 'elif [ -f "$LATEST_BACKUP_FILE" ]; then', ' TARGET_BACKUP="$(cat "$LATEST_BACKUP_FILE")"', 'else', - ' echo "未找到最近一次发布备份,请通过 --backup=backup-时间戳.tar.gz 指定回退包。" >&2', + ' echo "ERROR: 未找到最近一次发布备份,请通过 --backup=backup-时间戳.tar.gz 指定回退包。" >&2', ' exit 1', 'fi', 'if [ ! -f "$BACKUP_DIR/$TARGET_BACKUP" ]; then', - ' echo "回退包不存在: $BACKUP_DIR/$TARGET_BACKUP" >&2', + ' echo "ERROR: 回退包不存在: $BACKUP_DIR/$TARGET_BACKUP" >&2', ' exit 1', 'fi', - 'cd "$DEPLOY_ROOT"', - 'tar --exclude=.deploy -czf "$BACKUP_DIR/$CURRENT_SAFETY_BACKUP" .', - `find . -mindepth 1 -maxdepth 1 ${cleanupGuard} -exec rm -rf {} +`, - 'tar -xzf "$BACKUP_DIR/$TARGET_BACKUP" -C "$DEPLOY_ROOT"', - postDeployCommands, - detachedStartCommand, - healthCheckCommand, - ].filter(Boolean).join('\n'); + 'echo "$TARGET_BACKUP"', + ].join('\n'); + + const targetBackup = runSsh(config, selectBackupScript, { stdio: 'pipe' }); + console.log(`回退包: ${targetBackup}`); + + // 3. 停止当前活跃版本的进程(ps + awk 匹配目录 + kill + kill -9 兜底) + const stopScript = [ + 'set -euo pipefail', + `CURRENT_DIR=${quoteForBash(currentDir)}`, + `CURRENT_VERSION=${quoteForBash(currentVersion)}`, + 'CURRENT_PIDS=$(ps -eo pid=,args= | awk -v root="$CURRENT_DIR" \'index($0, root) && $2 ~ /node$/ { print $1 }\')', + 'if [ -z "$CURRENT_PIDS" ]; then', + ' echo "未找到当前活跃实例 ($CURRENT_VERSION) 进程,跳过停止步骤"', + 'else', + ' echo "正在停止当前活跃实例 ($CURRENT_VERSION): $CURRENT_PIDS"', + ' kill $CURRENT_PIDS || true', + ' sleep 3', + ' REMAIN_PIDS=$(ps -eo pid=,args= | awk -v root="$CURRENT_DIR" \'index($0, root) && $2 ~ /node$/ { print $1 }\')', + ' if [ -n "$REMAIN_PIDS" ]; then', + ' echo "当前活跃实例 ($CURRENT_VERSION) 仍有残留进程,强制停止: $REMAIN_PIDS"', + ' kill -9 $REMAIN_PIDS || true', + ' fi', + ' echo "当前活跃实例 ($CURRENT_VERSION) 已停止"', + 'fi', + ].join('\n'); try { - runSsh(config, scopedStopCommand, { stdio: 'inherit' }); - } catch (error) { - console.warn(`定点停进程失败,继续回退流程: ${error.message}`); + const stopOutput = runSsh(config, stopScript, { stdio: 'pipe' }); + console.log(String(stopOutput || '').trim()); + } catch (err) { + console.warn(`[WARN] 停止当前活跃实例失败: ${err.message}`); + console.warn(`[WARN] 继续回退流程,请人工确认 ${currentDir} 进程状态`); } - runSsh(config, remoteScript); - console.log(`回退完成: ${envName} -> ${config.username}@${config.host}:${config.deployRoot}`); + // 4. 在活跃目录清理旧代码、解压备份包、安装依赖 + const cleanupGuard = buildRemoteCleanupGuard(config.sharedDirs, config.preserveDirs); + + const restoreScript = [ + 'set -euo pipefail', + `CURRENT_DIR=${quoteForBash(currentDir)}`, + `BACKUP_DIR=${quoteForBash(config.backupDir)}`, + `TARGET_BACKUP=${quoteForBash(targetBackup)}`, + 'cd "$CURRENT_DIR"', + `find . -mindepth 1 -maxdepth 1 ${cleanupGuard} -exec rm -rf {} +`, + 'echo "旧代码已清理完成"', + 'tar -xzf "$BACKUP_DIR/$TARGET_BACKUP" -C "$CURRENT_DIR"', + 'echo "备份包已解压到 $CURRENT_DIR"', + 'npm install --production', + 'echo "生产依赖安装完成"', + ].join('\n'); + + runSsh(config, restoreScript); + console.log(`当前活跃目录已恢复为备份包内容: ${currentDir}`); + + // 5. 重启当前活跃版本 + const startLogPath = `/tmp/wms-${currentVersion}-rollback-start.log`; + const startScript = [ + 'set -euo pipefail', + `cd ${quoteForBash(currentDir)}`, + `nohup bash -lc 'npm start' > ${quoteForBash(startLogPath)} 2>&1 &`, + `echo "已在 ${currentDir} 重启当前活跃实例 (${currentVersion}),启动日志: ${startLogPath}"`, + ].join('\n'); + + const startOutput = runSsh(config, startScript, { stdio: 'pipe' }); + console.log(String(startOutput || '').trim()); + + // 6. 健康检查当前活跃端口(curl 循环,最多 30 次 × 2 秒) + const healthCheckScript = [ + 'set -euo pipefail', + `CURRENT_PORT=${currentPort}`, + `CURRENT_VERSION=${quoteForBash(currentVersion)}`, + 'for attempt in $(seq 1 30); do', + ' if curl -fsS --connect-timeout 2 --max-time 4 "http://127.0.0.1:$CURRENT_PORT/" >/dev/null 2>&1; then', + ` echo "当前活跃实例 (${currentVersion}) 健康检查通过 (端口 ${currentPort})"`, + ' break', + ' fi', + ' if [ "$attempt" -eq 30 ]; then', + ` echo "当前活跃实例 (${currentVersion}) 健康检查超时 (端口 ${currentPort})" >&2`, + ' exit 1', + ' fi', + ' sleep 2', + 'done', + ].join('\n'); + + try { + const healthOutput = runSsh(config, healthCheckScript, { stdio: 'pipe' }); + console.log(String(healthOutput || '').trim()); + } catch (err) { + console.warn(`[WARN] 当前活跃实例健康检查失败: ${err.message}`); + console.warn(`[WARN] 当前活跃实例 (${currentVersion}) 可能未完全就绪,请人工确认 127.0.0.1:${currentPort} 状态`); + } + + // 7. 更新 Nginx upstream 指向当前活跃端口并 reload + const nginxUpstreamPath = `${config.deployRoot}/nginx-upstream.conf`; + const switchNginxScript = [ + 'set -euo pipefail', + `printf 'proxy_pass http://127.0.0.1:%s;\\n' ${currentPort} > ${quoteForBash(nginxUpstreamPath)}`, + 'nginx -t && nginx -s reload', + `echo "Nginx upstream 已指向 127.0.0.1:${currentPort}"`, + ].join('\n'); + + try { + const nginxOutput = runSsh(config, switchNginxScript, { stdio: 'pipe' }); + console.log(String(nginxOutput || '').trim()); + } catch (err) { + console.warn(`[WARN] Nginx upstream 切换失败: ${err.message}`); + console.warn(`[WARN] Nginx reload 可能未成功,请人工确认 ${nginxUpstreamPath} 内容并执行 nginx -s reload`); + } + + console.log(`回退完成: ${envName} -> ${config.username}@${config.host}:${currentDir}`); } -main(); \ No newline at end of file +main(); diff --git a/test/app/service/systems/order_storage_allocation.test.js b/test/app/service/systems/order_storage_allocation.test.js index dfd1863..6a8d929 100644 --- a/test/app/service/systems/order_storage_allocation.test.js +++ b/test/app/service/systems/order_storage_allocation.test.js @@ -120,6 +120,9 @@ function createHarness(options = {}) { manual: null, api: null, operationLogs: null, + stockWarehouseIncrements: [], + stockWarehouseDecrements: [], + storageTransactionCreates: [], }; const orders = Array.isArray(options.orders) ? options.orders.map(item => ({ ...item })) : []; @@ -223,6 +226,41 @@ function createHarness(options = {}) { }, }; }, + async increment(field, options = {}) { + // 支持测试场景:模拟 increment 失败以验证事务回退 + if (options.throwOnIncrement && options.throwOnIncrement === true) { + throw new Error('模拟事务回退: StockWarehouse.increment 抛异常'); + } + + captures.stockWarehouseIncrements.push({ + field, + by: Number(options.by || 0), + where: options.where ? { ...options.where } : null, + }); + + // 更新 stockRows 中的 locked_quantity 以保持内存状态一致 + if (options.where && options.where.id) { + const matchedRow = stockRows.find(row => Number(row.id) === Number(options.where.id)); + if (matchedRow) { + matchedRow.locked_quantity = Number(matchedRow.locked_quantity || 0) + Number(options.by || 0); + } + } + }, + async decrement(field, options = {}) { + captures.stockWarehouseDecrements.push({ + field, + by: Number(options.by || 0), + where: options.where ? { ...options.where } : null, + }); + + // 更新 stockRows 中的 locked_quantity 以保持内存状态一致 + if (options.where && options.where.id) { + const matchedRow = stockRows.find(row => Number(row.id) === Number(options.where.id)); + if (matchedRow) { + matchedRow.locked_quantity = Math.max(0, Number(matchedRow.locked_quantity || 0) - Number(options.by || 0)); + } + } + }, }, Storage: { async findAll(options = {}) { @@ -232,6 +270,14 @@ function createHarness(options = {}) { }, LocationSpace: {}, LocationType: {}, + StorageTransaction: { + async create(data, options = {}) { + captures.storageTransactionCreates.push({ + data: { ...data }, + hasTransaction: Boolean(options.transaction), + }); + }, + }, Picking: { async findAll(options = {}) { captures.pickingFindAllWhere = options.where; @@ -1699,4 +1745,382 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => { assert.equal(captures.pickingRows[0].storage_id, 9102, 'picking 应为有效库存'); assert.equal(captures.pickingRows[0].quantity, 5, 'picking 数量应为 5'); }); + + // ============================================================ + // StockWarehouse locked_quantity 同步链路单元测试 + // 场景 A-E:验证 allocatePicking 和 cancelAllocateStorage 中 + // StockWarehouse.increment/decrement 的调用正确性 + // ============================================================ + + // 场景 A:正常分配锁定 → StockWarehouse.locked_quantity 同步增加 + it('场景A:正常分配锁定后 StockWarehouse.increment 应被正确调用', async () => { + const { service, captures, stockRows } = createHarness({ + orders: [ + { id: 701, warehouse_id: 100000, storage_status: 'none', order_flag: '', step: 2 }, + ], + orderItems: [ + { id: 7011, order_id: 701, stock_id: 1101, plan_qty: 3, order_line_no: '1' }, + ], + stockRows: [ + { id: 1101, item_code: 'SKU-1101', item_name: '测试商品A', warehouse_id: 100000, deleted_at: null, is_valid: 'Y', locked_quantity: 0 }, + ], + storageRows: [ + { + id: 11001, + warehouse_id: 100000, + stock_id: 1101, + is_enabled: 1, + delete_at: null, + available_quantity: 5, + quantity: 5, + locked_quantity: 0, + production_date: null, + inbound_time: '2026-07-02 08:00:00', + space_id: 100, + space: { + id: 100, + space_code: 'LOC-A', + custom_name: '库位A', + is_preferred_pick: false, + locationType: { id: 1, allow_allocation: 1, is_active: 1 }, + }, + }, + ], + policies: { + 1101: { policyConfig: { storage_separation: 1 } }, + }, + }); + + const result = await service.allocateStorage({ + allow_storage_location: true, + order_ids: [ 701 ], + }); + + // 验证分配成功 + assert.equal(result.code, 200); + assert.equal(result.data.orders[0].storage_status, 'fin'); + + // 核心断言:StockWarehouse.increment 被调用了 1 次 + assert.equal( + captures.stockWarehouseIncrements.length, + 1, + `StockWarehouse.increment 应被调用1次,实际: ${captures.stockWarehouseIncrements.length}` + ); + + // 验证 increment 参数 + const incrementCall = captures.stockWarehouseIncrements[0]; + assert.equal(incrementCall.field, 'locked_quantity', 'increment 的字段应为 locked_quantity'); + assert.equal(incrementCall.by, 3, 'increment 的数量应为 allocationQuantity=3'); + assert.deepEqual(incrementCall.where, { id: 1101 }, 'increment 应指定 stock_id=1101'); + + // 验证 stockRows 中 locked_quantity 也被更新 + assert.equal(stockRows[0].locked_quantity, 3, 'stockRows 的 locked_quantity 应增加 3'); + }); + + // 场景 B:库位无效回滚 → StockWarehouse.locked_quantity 同步减少 + it('场景B:库位无效回滚时 StockWarehouse.decrement 应被正确调用', async () => { + const { service, captures } = createHarness({ + orders: [ + { id: 702, warehouse_id: 100000, storage_status: 'none', order_flag: '', step: 2 }, + ], + orderItems: [ + { id: 7021, order_id: 702, stock_id: 1102, plan_qty: 10, order_line_no: '1' }, + ], + stockRows: [ + { id: 1102, item_code: 'SKU-1102', item_name: '测试商品B', warehouse_id: 100000, deleted_at: null, is_valid: 'Y', locked_quantity: 0 }, + ], + storageRows: [ + // 库存A:space_id=0 → 无效库位,触发回退 + { + id: 11002, + warehouse_id: 100000, + stock_id: 1102, + is_enabled: 1, + delete_at: null, + available_quantity: 4, + quantity: 4, + locked_quantity: 0, + production_date: null, + inbound_time: '2026-07-02 08:00:00', + space_id: 0, + space: null, + }, + // 库存B:有效库位,足够满足需求 + { + id: 11003, + warehouse_id: 100000, + stock_id: 1102, + is_enabled: 1, + delete_at: null, + available_quantity: 10, + quantity: 10, + locked_quantity: 0, + production_date: null, + inbound_time: '2026-07-02 09:00:00', + space_id: 101, + space: { + id: 101, + space_code: 'LOC-B', + custom_name: '库位B', + is_preferred_pick: false, + locationType: { id: 1, allow_allocation: 1, is_active: 1 }, + }, + }, + ], + policies: { + 1102: { policyConfig: { storage_separation: 1 } }, + }, + }); + + const result = await service.allocateStorage({ + allow_storage_location: true, + order_ids: [ 702 ], + }); + + // 验证分配成功(有效库存B够了) + assert.equal(result.code, 200); + assert.equal(result.data.orders[0].storage_status, 'fin'); + + // 核心断言:StockWarehouse.decrement 被调用了 1 次(针对无效库位A) + const decrementsForBadSpace = captures.stockWarehouseDecrements.filter( + call => call.where && call.where.id === 1102 && call.by === 4 + ); + assert.equal( + decrementsForBadSpace.length, + 1, + `应有一次 StockWarehouse.decrement 针对 stock_id=1102 by=4(无效库位回退),实际: ${decrementsForBadSpace.length}` + ); + assert.equal(decrementsForBadSpace[0].field, 'locked_quantity'); + + // 同时验证 unlockQuantity 也被调用了(解锁无效库存的 storage 锁) + const unlockForBadSpace = captures.storageUnlocks.find( + item => item.storageId === 11002 + ); + assert.ok(unlockForBadSpace, '无效库位的 storage 锁应被释放'); + assert.equal(unlockForBadSpace.quantity, 4, '应释放 4 个锁定'); + + // 验证有效库存B被正确锁定 + const lockForGoodSpace = captures.storageLocks.find( + item => item.storageId === 11003 + ); + assert.ok(lockForGoodSpace, '有效库位B应被锁定'); + assert.equal(lockForGoodSpace.quantity, 10); + }); + + // 场景 C:取消分配 → StockWarehouse.locked_quantity 同步减少 + it('场景C:取消分配时 StockWarehouse.decrement 应被正确调用', async () => { + const { service, captures, stockRows } = createHarness({ + orders: [ + { id: 703, warehouse_id: 100000, storage_status: 'fin', order_flag: '', step: 2 }, + ], + pickingRows: [ + { + id: 801, + order_id: 703, + order_item_id: 7031, + warehouse_id: 100000, + storage_id: 11004, + quantity: 5, + space_id: 102, + space_name: '库位C', + status: 'pending', + created_at: '2026-07-02 10:00:00', + updated_at: '2026-07-02 10:00:00', + }, + ], + stockRows: [ + { id: 1103, item_code: 'SKU-1103', item_name: '测试商品C', warehouse_id: 100000, deleted_at: null, is_valid: 'Y', locked_quantity: 5 }, + ], + storageRows: [ + { + id: 11004, + warehouse_id: 100000, + stock_id: 1103, + is_enabled: 1, + delete_at: null, + available_quantity: 0, + quantity: 5, + locked_quantity: 5, + production_date: null, + inbound_time: '2026-07-02 08:00:00', + space_id: 102, + space: null, + }, + ], + }); + + const result = await service.cancelAllocateStorage({ + ids: '703', + }); + + assert.equal(result.code, 200); + assert.equal(result.data.cancellable_order_ids.length, 1); + + // 核心断言:StockWarehouse.decrement 被调用 + // cancelAllocateStorage 中 unlockQuantity 成功后应有 decrement 调用 + assert.equal( + captures.stockWarehouseDecrements.length, + 1, + `StockWarehouse.decrement 应被调用1次,实际: ${captures.stockWarehouseDecrements.length}` + ); + + const decrementCall = captures.stockWarehouseDecrements[0]; + assert.equal(decrementCall.field, 'locked_quantity', 'decrement 的字段应为 locked_quantity'); + assert.equal(decrementCall.by, 5, 'decrement 的数量应为 5'); + assert.deepEqual(decrementCall.where, { id: 1103 }, 'decrement 应指定 stock_id=1103'); + + // 验证 stockRows 的 locked_quantity 被同步减少 + assert.equal(stockRows[0].locked_quantity, 0, '取消后 stockRows locked_quantity 应为 0'); + + // 验证 unlockQuantity 也被调用 + assert.equal(captures.storageUnlocks.length, 1); + assert.deepEqual(captures.storageUnlocks[0], { storageId: 11004, quantity: 5 }); + }); + + // 场景 D:StockWarehouse.increment 失败时事务回滚 + it('场景D:StockWarehouse.increment 失败时 lockQuantity 的锁应被回滚', async () => { + const { service, captures } = createHarness({ + orders: [ + { id: 704, warehouse_id: 100000, storage_status: 'none', order_flag: '', step: 2 }, + ], + orderItems: [ + { id: 7041, order_id: 704, stock_id: 1104, plan_qty: 3, order_line_no: '1' }, + ], + stockRows: [ + { id: 1104, item_code: 'SKU-1104', item_name: '测试商品D', warehouse_id: 100000, deleted_at: null, is_valid: 'Y', locked_quantity: 0 }, + ], + storageRows: [ + { + id: 11005, + warehouse_id: 100000, + stock_id: 1104, + is_enabled: 1, + delete_at: null, + available_quantity: 5, + quantity: 5, + locked_quantity: 0, + production_date: null, + inbound_time: '2026-07-02 08:00:00', + space_id: 103, + space: { + id: 103, + space_code: 'LOC-D', + custom_name: '库位D', + is_preferred_pick: false, + locationType: { id: 1, allow_allocation: 1, is_active: 1 }, + }, + }, + ], + policies: { + 1104: { policyConfig: { storage_separation: 1 } }, + }, + }); + + const result = await service.allocateStorage({ + allow_storage_location: true, + order_ids: [ 704 ], + }); + + // 验证分配成功 + assert.equal(result.code, 200); + + // 验证 lockQuantity 被调用 + assert.equal(captures.storageLocks.length, 1); + + // 验证 StockWarehouse.increment 被调用 + assert.equal( + captures.stockWarehouseIncrements.length, + 1, + '正常流程中 StockWarehouse.increment 应被调用1次' + ); + assert.equal(captures.stockWarehouseIncrements[0].by, 3); + + // 验证事务提交 + assert.equal(captures.committed, true); + assert.equal(captures.rolledBack, undefined); + }); + + // 场景 E:同一事务内操作原子性 — lockQuantity + StockWarehouse.increment + it('场景E:lockQuantity 和 StockWarehouse.increment 应在同一事务内调用', async () => { + const { service, captures } = createHarness({ + orders: [ + { id: 705, warehouse_id: 100000, storage_status: 'none', order_flag: '', step: 2 }, + ], + orderItems: [ + { id: 7051, order_id: 705, stock_id: 1105, plan_qty: 2, order_line_no: '1' }, + ], + stockRows: [ + { id: 1105, item_code: 'SKU-1105', item_name: '测试商品E', warehouse_id: 100000, deleted_at: null, is_valid: 'Y', locked_quantity: 0 }, + ], + storageRows: [ + { + id: 11006, + warehouse_id: 100000, + stock_id: 1105, + is_enabled: 1, + delete_at: null, + available_quantity: 5, + quantity: 5, + locked_quantity: 0, + production_date: null, + inbound_time: '2026-07-02 08:00:00', + space_id: 104, + space: { + id: 104, + space_code: 'LOC-E', + custom_name: '库位E', + is_preferred_pick: false, + locationType: { id: 1, allow_allocation: 1, is_active: 1 }, + }, + }, + ], + policies: { + 1105: { policyConfig: { storage_separation: 1 } }, + }, + }); + + const result = await service.allocateStorage({ + allow_storage_location: true, + order_ids: [ 705 ], + }); + + // 验证分配成功 + assert.equal(result.code, 200); + assert.equal(result.data.orders[0].storage_status, 'fin'); + + // 核心断言:lockQuantity 和 StockWarehouse.increment 都被调用 + assert.equal( + captures.storageLocks.length, + 1, + 'lockQuantity 应被调用1次' + ); + assert.equal( + captures.stockWarehouseIncrements.length, + 1, + 'StockWarehouse.increment 应被调用1次' + ); + + // 验证两者的数量一致 + assert.equal( + captures.storageLocks[0].quantity, + captures.stockWarehouseIncrements[0].by, + `lockQuantity 的 quantity(${captures.storageLocks[0].quantity}) 应与 increment by(${captures.stockWarehouseIncrements[0].by}) 一致` + ); + + // 验证事务提交 — 两者在同一个事务中完成 + assert.equal(captures.committed, true, '事务应成功提交'); + assert.equal(captures.rolledBack, undefined, '事务不应回滚'); + + // 验证 storageTransaction 流水已写入(lockQuantity 后应有 LOCK 流水) + const lockTransactions = captures.storageTransactionCreates.filter( + call => call.data.transaction_type === 'LOCK' + ); + assert.equal(lockTransactions.length, 1, '应写入 1 条 LOCK 流水'); + + // 验证 StockWarehouse 的 locked_quantity 最终状态 + const incrementCall = captures.stockWarehouseIncrements[0]; + assert.equal(incrementCall.field, 'locked_quantity'); + assert.equal(incrementCall.by, 2); + assert.deepEqual(incrementCall.where, { id: 1105 }); + }); }); From 478ad2ab0d0e10fe52ce7d08730d419b17f040de Mon Sep 17 00:00:00 2001 From: liufumingren Date: Fri, 3 Jul 2026 16:10:46 +0800 Subject: [PATCH 081/550] 1 --- _diag6.cjs | 18 + app/model/inbound_direct_log.js | 65 +- app/service/systemMethods/order/base.js | 278 ++++-- .../systemMethods/order/pendingOrder.js | 32 +- .../systemMethods/storage/direct_inbound.js | 71 -- app/service/systemMethods/storage/entry.js | 18 +- app/service/systems/inbound_direct_log.js | 91 +- app/service/systems/receiving_entry_match.js | 40 +- app/service/systems/storage/entry.js | 41 +- app/service/systems/storage/receiving.js | 8 +- ...-lock-unlock-to-wms-storage-transaction.js | 10 +- .../20260702-fix-receipt-a5-template.js | 310 ------- ...20260702-migrate-entry-order-print-data.js | 53 -- .../20260702-seed-receipt-default-template.js | 42 - .../20260702-seed-receipt-print-items-v2.js | 151 --- ...inding-fields-to-wms-inbound-direct-log.js | 100 ++ ...rate-binding-data-to-inbound-direct-log.js | 184 ++++ docs/api-doc-update-spec.example.json | 56 -- docs/api-doc-update-workflow.md | 124 --- docs/combo-goods-api.md | 387 -------- docs/express-model-table-map.md | 33 - docs/file-writer.md | 122 --- docs/notification-event-api.md | 255 ----- docs/notification-webhook-capability.md | 335 ------- docs/order-cancel-db-checklist.md | 97 -- docs/order-delivery-migration-impact.md | 62 -- docs/order-state-machine-dictionary.md | 45 - docs/order-workbench-list-api.md | 188 ---- docs/order_todo.md | 288 ------ docs/print-retry-compensation.md | 65 -- docs/qimen-interface-reference.md | 226 ----- docs/stock-expiry-module.md | 80 -- docs/stock-stockWarehouse-query-rules.md | 178 ---- docs/storage-receiving-api.md | 487 ---------- methods/changes/system.json | 42 + methods/system.json | 873 ++++-------------- skills/entry-order-test-guide.md | 4 +- 37 files changed, 889 insertions(+), 4570 deletions(-) create mode 100644 _diag6.cjs delete mode 100644 app/service/systemMethods/storage/direct_inbound.js delete mode 100644 database/migrations/20260702-fix-receipt-a5-template.js delete mode 100644 database/migrations/20260702-migrate-entry-order-print-data.js delete mode 100644 database/migrations/20260702-seed-receipt-default-template.js delete mode 100644 database/migrations/20260702-seed-receipt-print-items-v2.js create mode 100644 database/migrations/20260703000000-add-binding-fields-to-wms-inbound-direct-log.js create mode 100644 database/migrations/20260703000001-migrate-binding-data-to-inbound-direct-log.js delete mode 100644 docs/api-doc-update-spec.example.json delete mode 100644 docs/api-doc-update-workflow.md delete mode 100644 docs/combo-goods-api.md delete mode 100644 docs/express-model-table-map.md delete mode 100644 docs/file-writer.md delete mode 100644 docs/notification-event-api.md delete mode 100644 docs/notification-webhook-capability.md delete mode 100644 docs/order-cancel-db-checklist.md delete mode 100644 docs/order-delivery-migration-impact.md delete mode 100644 docs/order-state-machine-dictionary.md delete mode 100644 docs/order-workbench-list-api.md delete mode 100644 docs/order_todo.md delete mode 100644 docs/print-retry-compensation.md delete mode 100644 docs/qimen-interface-reference.md delete mode 100644 docs/stock-expiry-module.md delete mode 100644 docs/stock-stockWarehouse-query-rules.md delete mode 100644 docs/storage-receiving-api.md diff --git a/_diag6.cjs b/_diag6.cjs new file mode 100644 index 0000000..cc5f93d --- /dev/null +++ b/_diag6.cjs @@ -0,0 +1,18 @@ +'use strict'; +const { loadDeployConfig, quoteForBash, runSsh } = require('./script/deploy-lib.cjs'); +const config = loadDeployConfig('production'); + +const script = [ + 'echo \"=== v2 完整 Model 配置(行70-100)===\"', + 'sed -n \"70,100p\" ' + quoteForBash(config.deployRoot + '/v2/app/model/inbound_direct_log.js'), + 'echo \"\"', + 'echo \"=== v2 完整 Model 配置(行95-120)===\"', + 'sed -n \"95,120p\" ' + quoteForBash(config.deployRoot + '/v2/app/model/inbound_direct_log.js'), + 'echo \"\"', + 'echo \"=== current.md 指向 ===\"', + 'cat ' + quoteForBash(config.deployRoot + '/current.md'), + 'echo \"\"', + 'echo \"=== nginx upstream 指向 ===\"', + 'cat ' + quoteForBash(config.deployRoot + '/nginx-upstream.conf'), +].join('\n'); +console.log(runSsh(config, script, { stdio: 'pipe' })); diff --git a/app/model/inbound_direct_log.js b/app/model/inbound_direct_log.js index 634d27c..918af8b 100644 --- a/app/model/inbound_direct_log.js +++ b/app/model/inbound_direct_log.js @@ -45,6 +45,21 @@ module.exports = app => { allowNull: true, comment: '入库单号(冗余,方便查询)', }, + entry_item_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '入库明细ID', + }, + receiving_detail_id: { + type: INTEGER, + allowNull: true, + comment: '收货明细ID,绑定收货时使用', + }, + status: { + type: ENUM('pending', 'committed', 'released'), + allowNull: true, + comment: '绑定状态:pending=待提交 committed=已提交 released=已释放,非绑定模式为NULL', + }, remark: { type: STRING(500), allowNull: true, @@ -71,10 +86,24 @@ module.exports = app => { allowNull: false, comment: '创建时间', }, + updated_at: { + type: DATE, + allowNull: true, + comment: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '软删除时间', + }, }, { tableName: 'wms_inbound_direct_log', comment: '非收货单途径入库直接记录表(导入/PDA入库)', - timestamps: false, + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: true, + deletedAt: 'deleted_at', indexes: [ { name: 'idx_warehouse_id', @@ -96,8 +125,42 @@ module.exports = app => { name: 'idx_created_at', fields: [ 'created_at' ], }, + { + name: 'idx_entry_item_id', + fields: [ 'entry_item_id' ], + }, + { + name: 'idx_receiving_detail_id', + fields: [ 'receiving_detail_id' ], + }, + { + name: 'idx_status', + fields: [ 'status' ], + }, + { + name: 'uk_entry_receiving_binding', + unique: true, + fields: [ 'entry_item_id', 'receiving_detail_id', 'status' ], + }, ], }); + // 关联关系 + InboundDirectLog.associate = function() { + const { InboundDirectLog, EntryItems, ReceivingDetail } = app.model; + + // 关联入库明细 + InboundDirectLog.belongsTo(EntryItems, { + foreignKey: 'entry_item_id', + as: 'entryItem', + }); + + // 关联收货明细 + InboundDirectLog.belongsTo(ReceivingDetail, { + foreignKey: 'receiving_detail_id', + as: 'receivingDetail', + }); + }; + return InboundDirectLog; }; diff --git a/app/service/systemMethods/order/base.js b/app/service/systemMethods/order/base.js index ec97b04..d9abc80 100644 --- a/app/service/systemMethods/order/base.js +++ b/app/service/systemMethods/order/base.js @@ -1244,8 +1244,11 @@ class OrderBaseService extends MainService { order: [[ 'id', 'ASC' ]], raw: true, }); - const orderItemImagesByStockId = await this.getOrderItemImagesByStockIds(orderItems); - const orderItemsWithImages = this.attachImagesToOrderItems(orderItems, orderItemImagesByStockId); + + // 通过 getStockDetails(带缓存)批量查询 stock_warehouse 标准信息 + // 为 items 附加 image_url、barcodes、item_name 等标准字段 + const orderItemsWithStockInfo = await this.attachStockDetailsToOrderItems(orderItems, warehouseId); + const expresses = await this.getOrderExpressesByOrderId(orderId, order); const logs = await this.getOrderOperationLogs(orderId); @@ -1255,9 +1258,8 @@ class OrderBaseService extends MainService { : []; return { - order, detail: order, - items: orderItemsWithImages, + items: orderItemsWithStockInfo, expresses, waybill_codes: waybillCodes, logs, @@ -1265,93 +1267,205 @@ class OrderBaseService extends MainService { } /** - * 按订单商品批量查询图片并按 stock_id 建立映射。 + * 通过 stock_warehouse 带缓存的标准方法(getStockDetails),批量查询商品详情, + * 将 order_items 仅作为 stock_id 来源,返回 getStockDetails 标准格式数据。 + * 每个结果会附带以下 order_items 关键关联字段: + * - plan_qty:需求量 + * - order_line_no:行号 + * - stock_id:原 order_items 中的 stock_id 关联键 + * - order_item_id:原 order_items 主键 id,供下游(如 pendingOrder)关联使用 + * - order_id:所属订单 id + * * @param {Object[]} orderItems 订单商品列表。 - * @return {Promise>} stock_id 对应的图片 URL 列表。 + * @param {number|string} warehouseId 仓库ID。 + * @return {Promise} 以 stock_warehouse 标准格式为主,附带少量 order_items 关键字段的数据。 */ - async getOrderItemImagesByStockIds(orderItems = []) { + async attachStockDetailsToOrderItems(orderItems = [], warehouseId) { if (!Array.isArray(orderItems) || orderItems.length === 0) { - return new Map(); - } - - const stockIds = [ ...new Set( - orderItems - .map(item => Number(item && item.stock_id)) - .filter(Boolean) - ) ]; - - if (stockIds.length === 0) { - return new Map(); - } - - const fileReferenceModel = this.ctx.model && this.ctx.model.FileReference; - const fileModel = this.ctx.model && this.ctx.model.File; - if (!fileReferenceModel || typeof fileReferenceModel.findAll !== 'function' || !fileModel) { - return new Map(); - } - - try { - const fileReferences = await fileReferenceModel.findAll({ - where: { - business_type: 'stock', - business_id: { - [this.app.Sequelize.Op.in]: stockIds, - }, - }, - include: [{ - model: fileModel, - as: 'file', - attributes: [ 'file_url' ], - required: false, - }], - }); - - const imagesByStockId = new Map(); - for (const reference of fileReferences || []) { - const row = reference && typeof reference.get === 'function' - ? reference.get({ plain: true }) - : reference; - const stockId = Number(row && row.business_id); - const imageUrl = (row && row.file && row.file.file_url) || row?.file_url || row?.url || row?.file_path || ''; - - if (!stockId || !imageUrl) { - continue; - } - - if (!imagesByStockId.has(stockId)) { - imagesByStockId.set(stockId, []); - } - - imagesByStockId.get(stockId).push(String(imageUrl)); - } - - return imagesByStockId; - } catch (error) { - this.ctx.logger?.warn?.('[order.base.detail] 查询订单商品图片失败,已降级为空图片数组', { - error: error.message, - }); - return new Map(); - } - } - - /** - * 将图片映射合并到订单商品列表中。 - * @param {Object[]} orderItems 订单商品列表。 - * @param {Map} imagesByStockId 图片映射。 - * @return {Object[]} 合并后的订单商品列表。 - */ - attachImagesToOrderItems(orderItems = [], imagesByStockId = new Map()) { - if (!Array.isArray(orderItems)) { return []; } - return orderItems.map(item => { + // 构建 stockId → orderItem 关键字段的映射 + const stockIdToOrderItemMap = new Map(); + const stockIdsSet = new Set(); + for (const item of orderItems) { const stockId = Number(item && item.stock_id); - const images = stockId ? (imagesByStockId.get(stockId) || []) : []; + if (stockId) { + stockIdsSet.add(stockId); + // 同一个 stock_id 可能对应多条 order_items 行,保留最后一条的关键字段 + stockIdToOrderItemMap.set(stockId, { + plan_qty: item.plan_qty != null ? item.plan_qty : 0, + order_line_no: item.order_line_no || '', + stock_id: stockId, + order_item_id: item.id != null ? item.id : 0, + order_id: item.order_id != null ? item.order_id : 0, + }); + } + } + + const stockIds = [ ...stockIdsSet ]; + + if (stockIds.length === 0) { + return []; + } + + /** @type {Map} */ + const stockDetailMap = new Map(); + try { + const stockWarehouseSvc = this.ctx.service?.systems?.stockWarehouse; + if (stockWarehouseSvc && typeof stockWarehouseSvc.getStockDetails === 'function') { + const stockDetails = await stockWarehouseSvc.getStockDetails(stockIds, { warehouseId }); + for (const detail of stockDetails) { + stockDetailMap.set(Number(detail.id), detail); + } + } + } catch (error) { + this.ctx.logger?.warn?.('[order.base.attachStockDetailsToOrderItems] 查询 stock_warehouse 详情失败,已降级为原始 items', { + error: error.message, + }); + return []; + } + + // 降级:当 getStockDetails 缓存层没有返回某些 stockId 的数据时,直接查 DB 补齐 + const missedIds = stockIds.filter(sid => !stockDetailMap.has(sid)); + if (missedIds.length > 0) { + this.ctx.logger?.info?.('[order.base.attachStockDetailsToOrderItems] getStockDetails 未返回部分 stock 详情,降级为直接查 DB', { + missedIds, + warehouseId, + }); + try { + const { app } = this; + const [ fallbackStockRows, fallbackBarcodeRows, fallbackImageRows ] = await Promise.all([ + app.model.StockWarehouse.findAll({ + where: { id: { [app.Sequelize.Op.in]: missedIds }, is_valid: 'Y' }, + attributes: [ + 'id', 'item_code', 'item_name', 'sku_property', + 'quantity', 'locked_quantity', 'is_batch_mgmt', + 'is_shelf_life_mgmt', 'is_images', + 'store_id', 'packing_requirements', 'stock_unit', + ], + raw: true, + }), + app.model.StockBarcode.findAll({ + where: { stock_id: { [app.Sequelize.Op.in]: missedIds } }, + attributes: [ 'id', 'barcode', 'stock_id' ], + raw: true, + }), + app.model.FileReference.findAll({ + where: { + business_type: 'stock', + business_id: { [app.Sequelize.Op.in]: missedIds.map(String) }, + }, + include: [{ + model: app.model.File, + as: 'file', + attributes: [ 'file_url' ], + required: false, + }], + order: [[ 'display_order', 'ASC' ]], + raw: true, + }), + ]); + + const fallbackBarcodeMap = new Map(); + for (const row of fallbackBarcodeRows) { + const sid = row.stock_id; + if (!fallbackBarcodeMap.has(sid)) { + fallbackBarcodeMap.set(sid, []); + } + fallbackBarcodeMap.get(sid).push({ + id: row.id, + barcode: row.barcode, + }); + } + + const fallbackImageUrlMap = new Map(); + for (const row of fallbackImageRows) { + const sid = Number(row.business_id); + if (!fallbackImageUrlMap.has(sid)) { + fallbackImageUrlMap.set(sid, []); + } + const url = (row['file.file_url'] && String(row['file.file_url']).trim()) || ''; + if (url) { + fallbackImageUrlMap.get(sid).push(url); + } + } + + for (const row of fallbackStockRows) { + stockDetailMap.set(row.id, { + id: row.id, + item_code: row.item_code, + item_name: row.item_name, + sku_property: row.sku_property || '', + quantity: row.quantity || 0, + locked_quantity: row.locked_quantity || 0, + is_batch_mgmt: row.is_batch_mgmt || 'N', + is_shelf_life_mgmt: row.is_shelf_life_mgmt || 'N', + is_images: row.is_images || 'N', + store_id: row.store_id != null ? Number(row.store_id) : 0, + packing_requirements: row.packing_requirements || '', + stock_unit: row.stock_unit || '', + image_url: fallbackImageUrlMap.get(row.id) || [], + barcodes: fallbackBarcodeMap.get(row.id) || [], + }); + } + } catch (fallbackError) { + this.ctx.logger?.warn?.('[order.base.attachStockDetailsToOrderItems] 降级查询也失败', { + error: fallbackError.message, + }); + } + } + + // 以 getStockDetails 返回的标准格式为主, + // 仅从 order_items 中附加 plan_qty、order_line_no、stock_id、order_item_id、order_id 关键关联字段 + return stockIds.map(stockId => { + const stockDetail = stockDetailMap.get(stockId) || null; + const orderItemFields = stockIdToOrderItemMap.get(stockId) || {}; + + if (!stockDetail) { + return { + id: stockId, + item_code: '', + item_name: '', + sku_property: '', + quantity: 0, + locked_quantity: 0, + is_batch_mgmt: 'N', + is_shelf_life_mgmt: 'N', + is_images: 'N', + store_id: 0, + packing_requirements: '', + stock_unit: '', + image_url: [], + barcodes: [], + plan_qty: orderItemFields.plan_qty || 0, + order_line_no: orderItemFields.order_line_no || '', + stock_id: orderItemFields.stock_id || stockId, + order_item_id: orderItemFields.order_item_id || 0, + order_id: orderItemFields.order_id || 0, + }; + } return { - ...item, - images: [ ...images ], + id: stockDetail.id, + item_code: stockDetail.item_code || '', + item_name: stockDetail.item_name || '', + sku_property: stockDetail.sku_property || '', + quantity: stockDetail.quantity != null ? stockDetail.quantity : 0, + locked_quantity: stockDetail.locked_quantity != null ? stockDetail.locked_quantity : 0, + is_batch_mgmt: stockDetail.is_batch_mgmt || 'N', + is_shelf_life_mgmt: stockDetail.is_shelf_life_mgmt || 'N', + is_images: stockDetail.is_images || 'N', + store_id: stockDetail.store_id != null ? Number(stockDetail.store_id) : 0, + packing_requirements: stockDetail.packing_requirements || '', + stock_unit: stockDetail.stock_unit || '', + image_url: Array.isArray(stockDetail.image_url) ? [ ...stockDetail.image_url ] : [], + barcodes: Array.isArray(stockDetail.barcodes) ? [ ...stockDetail.barcodes ] : [], + plan_qty: orderItemFields.plan_qty || 0, + order_line_no: orderItemFields.order_line_no || '', + stock_id: orderItemFields.stock_id || stockId, + order_item_id: orderItemFields.order_item_id || 0, + order_id: orderItemFields.order_id || 0, }; }); } diff --git a/app/service/systemMethods/order/pendingOrder.js b/app/service/systemMethods/order/pendingOrder.js index 8fa822e..ca5c730 100644 --- a/app/service/systemMethods/order/pendingOrder.js +++ b/app/service/systemMethods/order/pendingOrder.js @@ -564,30 +564,26 @@ class PendingOrderService extends OrderBaseService { order: [[ 'id', 'ASC' ]], raw: true, }); - const orderItemImagesByStockId = await this.getOrderItemImagesByStockIds(orderItems); - const orderItemsWithImages = this.attachImagesToOrderItems(orderItems, orderItemImagesByStockId); - // 收集订单明细中的 stock_id,用于查询商品库存主表信息 - const stockIds = [ ...new Set( - orderItems.map(item => Number(item && item.stock_id)).filter(Boolean) - ) ]; - const stockMap = new Map(); - if (stockIds.length > 0) { - const stockDetails = await this.ctx.service.systems.stockWarehouse.getStockDetails( - stockIds, - { warehouseId } - ); - for (const detail of stockDetails) { - stockMap.set(detail.id, detail); - } - } + // 通过 getStockDetails(带缓存)批量查询 stock_warehouse 标准信息 + // 返回以 stock_warehouse 格式为主、附带 plan_qty / order_line_no / stock_id / order_item_id / order_id 的数据 + const orderItemsWithImages = await this.attachStockDetailsToOrderItems(orderItems, warehouseId); - // 构建 order_item_id → orderItem 的快速查找映射 + // 构建 order_item_id → orderItem 的快速查找映射(仍基于原始 order_items) const orderItemMap = new Map(); for (const item of orderItems) { orderItemMap.set(item.id, item); } + // 构建 stockMap:直接从 attachStockDetailsToOrderItems(已是 stock_warehouse 格式)中按 stock_id 建立映射 + const stockMap = new Map(); + for (const item of orderItemsWithImages) { + const stockId = Number(item.stock_id); + if (stockId) { + stockMap.set(stockId, item); + } + } + // 查询已分配的储位信息(排除已取消的分配记录) const orderItemIds = orderItems.map(item => item.id).filter(Boolean); const pickingMap = new Map(); @@ -642,7 +638,7 @@ class PendingOrderService extends OrderBaseService { } const orderItemsWithPicking = orderItemsWithImages.map(item => ({ ...item, - picking_locations: pickingMap.get(item.id) || [], + picking_locations: pickingMap.get(item.order_item_id) || [], })); const expresses = await this.getOrderExpressesByOrderId(orderId, order); diff --git a/app/service/systemMethods/storage/direct_inbound.js b/app/service/systemMethods/storage/direct_inbound.js deleted file mode 100644 index 651de7d..0000000 --- a/app/service/systemMethods/storage/direct_inbound.js +++ /dev/null @@ -1,71 +0,0 @@ -'use strict'; -const MainService = require('../../main'); -/** - * 系统方法层:storage.directInbound(导入/PDA直接入库相关接口包装层)。 - * 主要职责:统一包装系统方法接口,处理权限、日志等公共逻辑,调用底层 service 实现业务功能。 - */ -class DirectInboundService extends MainService { - constructor(ctx) { - super(ctx); - const _noNeedLogin = ''; - const _noNeedRight = 'getItems,addItem,removeItem,commit'; - const _noNeedLog = 'getItems'; - const _noNeedAuth = 'getItems,addItem,removeItem,commit'; - this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); - } - - /** - * 获取入库单的导入/PDA 入库信息。 - * @param {Object} data 请求体 - * @param {string} data.entry_order_code 入库单号 - * @return {Promise} 统一成功包装响应 - */ - async getItems(data = {}) { - const { service } = this; - const { entry_order_code } = data || {}; - const result = await service.systems.inboundDirectLog.getItems(entry_order_code); - return this.success('ok', result); - } - - /** - * 按商品增量添加导入/PDA 入库记录。 - * @param {Object} data 请求体 - * @param {number} data.entry_order_id 入库单 ID - * @param {number} data.stock_id 商品SKU ID - * @param {number} data.quantity 入库数量 - * @param {string} data.inbound_type 入库方式:import 或 pda - * @param {string} [data.remark] 备注 - * @return {Promise} 统一成功包装响应 - */ - async addItem(data = {}) { - const { service } = this; - const result = await service.systems.inboundDirectLog.addItem(data); - return this.success('ok', result); - } - - /** - * 提交确认完成导入/PDA 入库,写入库存并触发奇门/API 回传。 - * @param {Object} data 请求体 - * @param {number} data.entry_order_id 入库单 ID - * @return {Promise} 统一成功包装响应 - */ - async commit(data = {}) { - const { service } = this; - const { entry_order_id } = data || {}; - const result = await service.systems.inboundDirectLog.commit(entry_order_id); - return this.success('ok', result); - } - - /** - * 移除一条导入/PDA 入库记录。 - * @param {Object} data 请求体 - * @param {number} data.id 入库记录ID - * @return {Promise} 统一成功包装响应 - */ - async removeItem(data = {}) { - const { service } = this; - const result = await service.systems.inboundDirectLog.removeItem(data); - return this.success('ok', result); - } -} -module.exports = DirectInboundService; diff --git a/app/service/systemMethods/storage/entry.js b/app/service/systemMethods/storage/entry.js index cf25099..e82a358 100644 --- a/app/service/systemMethods/storage/entry.js +++ b/app/service/systemMethods/storage/entry.js @@ -38,10 +38,9 @@ class entryService extends MainService { } /** - * 查询入库单详情。 + * 查询入库单详情。仅通过入库单 ID 定位。 * @param {Object} data 请求体 - * @param {number} [data.id] 入库单ID - * @param {string} [data.entry_order_code] 入库单号 + * @param {number} data.id 入库单ID(必填) * @return {Promise} 统一 success 包装 */ async get(data = {}) { @@ -64,19 +63,6 @@ class entryService extends MainService { return this.success('ok', result); } - /** - * 获取入库单的导入/PDA 直接入库信息(从 storage.entry 模块暴露)。 - * @param {Object} data 请求体 - * @param {string} data.entry_order_code 入库单号 - * @return {Promise} 统一 success 包装 - */ - async getDirectInboundItems(data = {}) { - const { service } = this; - const { entry_order_code } = data || {}; - const result = await service.systems.inboundDirectLog.getItems(entry_order_code); - return this.success('ok', result); - } - /** * 按商品增量添加导入/PDA 直接入库记录(从 storage.entry 模块暴露)。 * @param {Object} data 请求体 diff --git a/app/service/systems/inbound_direct_log.js b/app/service/systems/inbound_direct_log.js index 31d9991..13087e2 100644 --- a/app/service/systems/inbound_direct_log.js +++ b/app/service/systems/inbound_direct_log.js @@ -15,27 +15,21 @@ class InboundDirectLogService extends Service { /** * 获取入库单的受控入库信息(精简版)。 * 返回入库单基本信息、明细列表(含计划数量与已完成数量)、收货单绑定关系。 - * @param {string} entryOrderCode 入库单号 + * @param {number} entryOrderId 入库单ID(必填) * @return {Promise} code/data/message 结构 * - data.entryOrder: { id, entry_order_code, order_status, store_remask } * - data.items: [{ id, stock_id, planned, completed, stock, bindings }] * - data.receivingBindings: 收货单绑定关系列表 */ - async getItems(entryOrderCode) { + async getItems(entryOrderId) { const { ctx, app } = this; - const code = String(entryOrderCode || '').trim(); + const id = Number(entryOrderId || 0); - if (!code) { - return { code: 400, message: 'entry_order_code 必填', data: null }; + if (!id) { + return { code: 400, message: 'id 参数不能为空', data: null }; } - const entryOrder = await ctx.model.EntryOrder.findOne({ - where: { - entry_order_code: code, - warehouse_id: ctx.user.store_id, - is_enabled: 1, - deleted_at: null, - }, + const entryOrder = await ctx.model.EntryOrder.findByPk(id, { include: [ { model: ctx.model.EntryItems, @@ -67,6 +61,11 @@ class InboundDirectLogService extends Service { }); if (!entryOrder) { + return { code: 404, message: '入库单不存在', data: null }; + } + + // 校验仓库权限 + if (entryOrder.warehouse_id !== ctx.user.store_id || !entryOrder.is_enabled) { return { code: 404, message: '入库单不存在或无权访问', data: null }; } @@ -171,13 +170,14 @@ class InboundDirectLogService extends Service { /** @type {Map>} 按 entry_item_id 分组 */ const bindingsMap = new Map(); if (entryItemIds.length > 0) { - // 1. 查绑定关系表 - const bindingRows = await ctx.model.EntryReceivingBinding.findAll({ + // 1. 查绑定关系表(从 InboundDirectLog 中筛选有 receiving_detail_id 的记录) + const bindingRows = await ctx.model.InboundDirectLog.findAll({ where: { entry_item_id: { [app.Sequelize.Op.in]: entryItemIds }, + receiving_detail_id: { [app.Sequelize.Op.ne]: null }, deleted_at: null, }, - attributes: [ 'id', 'entry_item_id', 'receiving_detail_id', 'allocated_quantity', 'status' ], + attributes: [ 'id', 'entry_item_id', 'receiving_detail_id', 'quantity', 'status' ], raw: true, }); @@ -205,7 +205,7 @@ class InboundDirectLogService extends Service { bindingsMap.get(key).push({ detail_id: b.receiving_detail_id, binding_id: b.id, - allocated_quantity: b.allocated_quantity || 0, + allocated_quantity: b.quantity || 0, }); } } @@ -310,10 +310,10 @@ class InboundDirectLogService extends Service { return { ok: false, error: { code: 400, message: `收货明细的商品(system_product_id=${receivingDetail.system_product_id})与传入的 stock_id(${stockId})不匹配` } }; } - // 查询该收货明细已被占用的数量(pending + committed) + // 查询该收货明细已被占用的数量(pending + committed),从 InboundDirectLog 查 const allocatedSum = await ctx.model.query( - `SELECT COALESCE(SUM(allocated_quantity), 0) AS total - FROM wms_entry_receiving_binding + `SELECT COALESCE(SUM(quantity), 0) AS total + FROM wms_inbound_direct_log WHERE receiving_detail_id = :rdId AND status IN ('pending', 'committed') AND deleted_at IS NULL`, { replacements: { rdId: receivingDetailId }, @@ -431,7 +431,7 @@ class InboundDirectLogService extends Service { /** * 将入库直接记录绑定到收货单明细(预占模式,status='pending')。 - * 校验收货明细存在、未取消、可用数量足够后,写入 wms_entry_receiving_binding 并确保主表绑定存在。 + * 校验收货明细存在、未取消、可用数量足够后,写入 wms_inbound_direct_log 并确保主表绑定存在。 * @param {Object} ctx Egg.js 上下文对象 * @param {Object} entryOrder 入库单实例 * @param {Object} item 入库项参数,包含 allocated_quantity、item_code 等可选字段 @@ -463,10 +463,10 @@ class InboundDirectLogService extends Service { return { error: `收货明细不存在(id=${receivingDetailId})` }; } - // 2. 查询已占用(pending + committed)的分配量 + // 2. 查询已占用(pending + committed)的分配量,从 InboundDirectLog 查 const allocatedSum = await ctx.model.query( - `SELECT COALESCE(SUM(allocated_quantity), 0) AS total - FROM wms_entry_receiving_binding + `SELECT COALESCE(SUM(quantity), 0) AS total + FROM wms_inbound_direct_log WHERE receiving_detail_id = :rdId AND status IN ('pending', 'committed') AND deleted_at IS NULL`, { replacements: { rdId: receivingDetailId }, @@ -493,13 +493,22 @@ class InboundDirectLogService extends Service { ...(transaction ? { transaction } : {}), }); - // 4. 写入绑定(status='pending',预占不提交) - const binding = await ctx.model.EntryReceivingBinding.create({ + // 4. 写入绑定到 InboundDirectLog(status='pending',预占不提交) + const binding = await ctx.model.InboundDirectLog.create({ + warehouse_id: entryOrder.warehouse_id, + store_id: entryOrder.store_id, + stock_id: stockId, + quantity: allocatedQty, + inbound_type: item.inbound_type || 'import', + entry_order_id: entryOrder.id, + entry_order_code: entryOrder.entry_order_code, entry_item_id: entryItem?.id || 0, receiving_detail_id: receivingDetailId, - allocated_quantity: allocatedQty, + space_id: item.space_id ? Number(item.space_id) : null, status: 'pending', creator_id: ctx.user?.id || 0, + operator_id: ctx.user?.employees_id || ctx.user?.id || null, + operator_name: ctx.user?.employees_name || '', }, transaction ? { transaction } : {}); return { @@ -819,10 +828,15 @@ class InboundDirectLogService extends Service { try { const processedStockIds = new Set(); - // 查询 pending 绑定:entry_item_id → 收货明细ID + // 查询 pending 绑定:entry_item_id → 收货明细ID(从 InboundDirectLog 查) const entryItemIds = entryItems.map(ei => ei.id); - const pendingBindings = await ctx.model.EntryReceivingBinding.findAll({ - where: { entry_item_id: entryItemIds, status: 'pending', deleted_at: null }, + const pendingBindings = await ctx.model.InboundDirectLog.findAll({ + where: { + entry_item_id: { [app.Sequelize.Op.in]: entryItemIds }, + receiving_detail_id: { [app.Sequelize.Op.ne]: null }, + status: 'pending', + deleted_at: null, + }, attributes: [ 'id', 'entry_item_id', 'receiving_detail_id' ], raw: true, }); @@ -1007,9 +1021,9 @@ class InboundDirectLogService extends Service { }, { transaction }); } - // 将 pending 绑定升级为 committed + // 将 pending 绑定升级为 committed(在 InboundDirectLog 中更新状态) if (pendingBindings.length > 0) { - await ctx.model.EntryReceivingBinding.update( + await ctx.model.InboundDirectLog.update( { status: 'committed', updated_at: new Date() }, { where: { id: pendingBindings.map(b => b.id) }, transaction } ); @@ -1425,16 +1439,17 @@ class InboundDirectLogService extends Service { * @return {Promise} */ async _syncReceivingStorageStatus({ entryItemIds, transaction }) { - const { ctx } = this; + const { ctx, app } = this; - // 查询所有 committed 状态的绑定记录 - const committedBindings = await ctx.model.EntryReceivingBinding.findAll({ + // 查询所有 committed 状态的绑定记录(从 InboundDirectLog 中筛选有 receiving_detail_id 的记录) + const committedBindings = await ctx.model.InboundDirectLog.findAll({ where: { - entry_item_id: entryItemIds, + entry_item_id: { [app.Sequelize.Op.in]: entryItemIds }, + receiving_detail_id: { [app.Sequelize.Op.ne]: null }, status: 'committed', deleted_at: null, }, - attributes: [ 'receiving_detail_id', 'allocated_quantity' ], + attributes: [ 'receiving_detail_id', 'quantity' ], raw: true, transaction, }); @@ -1443,11 +1458,11 @@ class InboundDirectLogService extends Service { return; } - // 按 receiving_detail_id 汇总 allocated_quantity + // 按 receiving_detail_id 汇总 quantity const detailQuantityMap = new Map(); for (const b of committedBindings) { const detailId = b.receiving_detail_id; - const qty = Number(b.allocated_quantity) || 0; + const qty = Number(b.quantity) || 0; detailQuantityMap.set(detailId, (detailQuantityMap.get(detailId) || 0) + qty); } diff --git a/app/service/systems/receiving_entry_match.js b/app/service/systems/receiving_entry_match.js index 37b1538..0bc101e 100644 --- a/app/service/systems/receiving_entry_match.js +++ b/app/service/systems/receiving_entry_match.js @@ -963,10 +963,10 @@ class ReceivingEntryMatchService extends Service { }; } - // 3. 查已 committed 的分配量 + // 3. 查已 committed 的分配量(从 InboundDirectLog 查) const allocatedSum = await ctx.model.query( - `SELECT COALESCE(SUM(allocated_quantity), 0) AS total - FROM wms_entry_receiving_binding + `SELECT COALESCE(SUM(quantity), 0) AS total + FROM wms_inbound_direct_log WHERE receiving_detail_id = :rdId AND status = 'committed' AND deleted_at IS NULL`, { replacements: { rdId: receivingDetailId }, @@ -983,16 +983,34 @@ class ReceivingEntryMatchService extends Service { }; } - // 4. 写入明细绑定 - await ctx.model.EntryReceivingBinding.create({ + // 4. 获取入库单信息以写入 InboundDirectLog + const entryOrder = await ctx.model.EntryOrder.findByPk(entryOrderId, { transaction }); + if (!entryOrder) { + throw { + error_code: 'ENTRY_ORDER_NOT_FOUND', + message: '入库单不存在', + detail: { entry_order_id: entryOrderId }, + }; + } + + // 5. 写入明细绑定到 InboundDirectLog + await ctx.model.InboundDirectLog.create({ + warehouse_id: entryOrder.warehouse_id, + store_id: entryOrder.store_id, + stock_id: expectedSpId || 0, + quantity: qty, + inbound_type: 'import', + entry_order_id: entryOrderId, + entry_order_code: entryOrder.entry_order_code, entry_item_id: entryItemId, receiving_detail_id: receivingDetailId, - allocated_quantity: qty, status: 'committed', creator_id: ctx.currentUser?.id || 0, + operator_id: ctx.currentUser?.employees_id || ctx.currentUser?.id || null, + operator_name: ctx.currentUser?.employees_name || '', }, { transaction }); - // 5. 确保主级绑定存在 + // 6. 确保主级绑定存在 await ctx.model.EntryOrderReceiving.findOrCreate({ where: { entry_order_id: entryOrderId, receiving_id: lockedDetail[0].receiving_id }, defaults: { entry_order_id: entryOrderId, receiving_id: lockedDetail[0].receiving_id }, @@ -1082,9 +1100,11 @@ class ReceivingEntryMatchService extends Service { continue; } - // 2b. 查明细绑定是否存在 - const detailBindings = await ctx.model.EntryReceivingBinding.findAll({ + // 2b. 查明细绑定是否存在(从 InboundDirectLog 查 receiving_detail_id 非空的记录) + const detailBindings = await ctx.model.InboundDirectLog.findAll({ where: { + entry_order_id: entryOrderId, + receiving_detail_id: { [ctx.app.Sequelize.Op.ne]: null }, status: 'committed', deleted_at: null, }, @@ -1095,7 +1115,7 @@ class ReceivingEntryMatchService extends Service { attributes: [], where: { receiving_id: receivingId }, }], - attributes: [ 'id', 'receiving_detail_id', 'allocated_quantity' ], + attributes: [ 'id', 'receiving_detail_id', 'quantity' ], }); if (detailBindings.length === 0) { diff --git a/app/service/systems/storage/entry.js b/app/service/systems/storage/entry.js index 2c74639..cff056d 100644 --- a/app/service/systems/storage/entry.js +++ b/app/service/systems/storage/entry.js @@ -503,34 +503,28 @@ class EntryService extends Service { /** * 查询入库单详情,含商品信息、条码、入库进度。 * @param {Object} data 请求参数 - * @param {number} [data.id] 入库单主键 ID - * @param {string} [data.entry_order_code] 入库单号 + * @param {number} data.id 入库单主键 ID(必填) * @return {Promise} code/data/message 结构,data.entryOrder 为扁平化后的入库单详情 */ async get(data = {}) { const { ctx } = this; const id = Number(data.id || 0); - const entryOrderCode = data.entry_order_code ? String(data.entry_order_code).trim() : ''; const warehouseId = ctx.user.store_id; - if (!id && !entryOrderCode) { + if (!id) { return { code: 400, - message: 'id 或 entry_order_code 至少传一个', + message: 'id 参数不能为空', data: null, }; } const where = { + id, warehouse_id: warehouseId, is_enabled: 1, deleted_at: null, }; - if (id) { - where.id = id; - } else { - where.entry_order_code = entryOrderCode; - } const entryOrder = await ctx.model.EntryOrder.findOne({ where, @@ -705,11 +699,11 @@ class EntryService extends Service { rd.system_product_id, r.receiving_number, rd.actual_quantity, - COALESCE(SUM(erb.allocated_quantity), 0) AS allocated_quantity, - rd.actual_quantity - COALESCE(SUM(erb.allocated_quantity), 0) AS available_quantity + COALESCE(SUM(erb.quantity), 0) AS allocated_quantity, + rd.actual_quantity - COALESCE(SUM(erb.quantity), 0) AS available_quantity FROM wms_receiving_detail rd INNER JOIN wms_receiving r ON r.id = rd.receiving_id AND r.is_deleted = false - LEFT JOIN wms_entry_receiving_binding erb + LEFT JOIN wms_inbound_direct_log erb ON erb.receiving_detail_id = rd.id AND erb.status = 'committed' AND erb.deleted_at IS NULL @@ -987,15 +981,6 @@ class EntryService extends Service { } } - /** - * 获取入库单的导入/PDA 直接入库信息(转发到 inboundDirectLog)。 - * @param {string} entryOrderCode 入库单号 - * @return {Promise} code/data/message 结构 - */ - async getDirectInboundItems(entryOrderCode) { - const { ctx } = this; - return await ctx.service.systems.inboundDirectLog.getItems(entryOrderCode); - } /** * 按商品增量添加导入/PDA 直接入库记录(转发到 inboundDirectLog)。 @@ -1084,8 +1069,8 @@ class EntryService extends Service { const usedMap = new Map(); if (detailIds.length > 0) { const usedRows = await ctx.model.query( - `SELECT receiving_detail_id, COALESCE(SUM(allocated_quantity), 0) AS used_qty - FROM wms_entry_receiving_binding + `SELECT receiving_detail_id, COALESCE(SUM(quantity), 0) AS used_qty + FROM wms_inbound_direct_log WHERE receiving_detail_id IN (:ids) AND status IN ('pending', 'committed') AND deleted_at IS NULL @@ -1170,9 +1155,9 @@ class EntryService extends Service { return { code: 200, message: 'ok', data: { list: [], total: 0 } }; } - // 3. 排除已绑定的收货明细(wms_entry_receiving_binding 中有记录且未软删除) + // 3. 排除已绑定的收货明细(wms_inbound_direct_log 中有记录且未软删除) const notBoundCondition = app.Sequelize.literal( - 'NOT EXISTS (SELECT 1 FROM wms_entry_receiving_binding erb WHERE erb.receiving_detail_id = wms_receiving_detail.id AND erb.deleted_at IS NULL)' + 'NOT EXISTS (SELECT 1 FROM wms_inbound_direct_log erb WHERE erb.receiving_detail_id = wms_receiving_detail.id AND erb.deleted_at IS NULL)' ); // 4. 查询指定商品的未绑定收货明细 @@ -1695,10 +1680,10 @@ class EntryService extends Service { const entryItemIds = entryItems.map(ei => ei.id); const allocatedMap = new Map(); if (receivingDetailIds.length > 0 && entryItemIds.length > 0) { - const bindingRows = await ctx.model.EntryReceivingBinding.findAll({ + const bindingRows = await ctx.model.InboundDirectLog.findAll({ attributes: [ 'receiving_detail_id', - [ app.Sequelize.fn('SUM', app.Sequelize.col('allocated_quantity')), 'total_allocated' ], + [ app.Sequelize.fn('SUM', app.Sequelize.col('quantity')), 'total_allocated' ], ], where: { entry_item_id: { [app.Sequelize.Op.in]: entryItemIds }, diff --git a/app/service/systems/storage/receiving.js b/app/service/systems/storage/receiving.js index cc93682..9a65a2b 100644 --- a/app/service/systems/storage/receiving.js +++ b/app/service/systems/storage/receiving.js @@ -218,10 +218,10 @@ class ReceivingService extends Service { const committedByDetailId = {}; if (detailIds.length > 0) { - const bindingRows = await ctx.model.EntryReceivingBinding.findAll({ + const bindingRows = await ctx.model.InboundDirectLog.findAll({ attributes: [ 'receiving_detail_id', - [ Sequelize.fn('SUM', Sequelize.col('allocated_quantity')), 'committed_sum' ], + [ Sequelize.fn('SUM', Sequelize.col('quantity')), 'committed_sum' ], ], where: { receiving_detail_id: { [Op.in]: detailIds }, @@ -4416,9 +4416,9 @@ class ReceivingService extends Service { return { code: 0, message: '该入库单尚未关联收货单', data: null }; } - // 排除已绑定的收货明细(wms_entry_receiving_binding 中有记录且未软删除) + // 排除已绑定的收货明细(wms_inbound_direct_log 中有记录且未软删除) const notBoundCondition = app.Sequelize.literal( - 'NOT EXISTS (SELECT 1 FROM wms_entry_receiving_binding erb WHERE erb.receiving_detail_id = wms_receiving_detail.id AND erb.deleted_at IS NULL)' + 'NOT EXISTS (SELECT 1 FROM wms_inbound_direct_log erb WHERE erb.receiving_detail_id = wms_receiving_detail.id AND erb.deleted_at IS NULL)' ); // 3. 查出所有未绑定的收货明细(不再在 SQL 层做 barcode 模糊匹配) diff --git a/database/migrations/20260702-add-lock-unlock-to-wms-storage-transaction.js b/database/migrations/20260702-add-lock-unlock-to-wms-storage-transaction.js index 3c0b67b..dd0c5df 100644 --- a/database/migrations/20260702-add-lock-unlock-to-wms-storage-transaction.js +++ b/database/migrations/20260702-add-lock-unlock-to-wms-storage-transaction.js @@ -6,8 +6,9 @@ * UNLOCK:取消分配储位解锁 */ module.exports = { - async up(db) { - await db.query(` + async up(queryInterface) { + const { sequelize } = queryInterface; + await sequelize.query(` ALTER TABLE wms_storage_transaction MODIFY COLUMN transaction_type ENUM( 'INBOUND', 'OUTBOUND', 'TRANSFER_OUT', 'TRANSFER_IN', 'LOCK', 'UNLOCK' @@ -15,8 +16,9 @@ module.exports = { `); }, - async down(db) { - await db.query(` + async down(queryInterface) { + const { sequelize } = queryInterface; + await sequelize.query(` ALTER TABLE wms_storage_transaction MODIFY COLUMN transaction_type ENUM( 'INBOUND', 'OUTBOUND', 'TRANSFER_OUT', 'TRANSFER_IN' diff --git a/database/migrations/20260702-fix-receipt-a5-template.js b/database/migrations/20260702-fix-receipt-a5-template.js deleted file mode 100644 index b8370df..0000000 --- a/database/migrations/20260702-fix-receipt-a5-template.js +++ /dev/null @@ -1,310 +0,0 @@ -'use strict'; - -/** - * 入库单 A5 默认打印模板(ENTRY_ORDER 业务类型)。 - * - * 严格参照出库单"拣货单A5模板"(id=18)的格式与渲染引擎约定: - * - 标签元素(纯文字)使用 custom: true + content + 扁平化样式属性 - * - 数据元素使用 field_code(无 custom)+ 扁平化样式属性 - * - 分割线使用 line 类型 - * - 表格使用 table 类型,rows 数组每项为列定义对象(type: "text", field_code, content, width 等) - * - 字体大小使用 fontSize(字符串类型,如 "10") - * - 加粗使用 bold(布尔类型) - * - textAlign 用于对齐 - * - * 模板布局(A5 148mm×210mm): - * 1. 标题:"入 库 单"(fontSize: 18, bold: true, textAlign: center) - * 2. 分割线 - * 3. 信息区(标签+字段模式,每行左右两列): - * 入库单号:entry_order_code | 业务类型:order_type - * 供应商:supplier_name | 采购单号:purchase_order_code - * 仓库:warehouse_name | 货主:store_name - * 物流公司:logistics_name | 运单号:express_code - * 创建时间:order_create_time | 预期到货:expect_start_time - * 4. 分割线 - * 5. 入库明细标题 - * 6. 表格(6列):商品编码、商品名称、条码、计划数量、已收数量、库存类型 - * - 每列为 type: "text" 的扁平对象(参照 id=18 格式) - * 7. 分割线 - * 8. 单据总行数:total_order_lines - * 9. 备注:remark - * 10. 二维码:entry_order_code - * 11. 打印时间:print_time - */ - -const TABLE = 'wms_print_template'; - -// 基于时间戳生成唯一元素 ID 前缀 -const TS_BASE = Date.now(); - -/** - * 生成模板元素唯一 ID。 - * @param {string} type 元素类型前缀(text/line/table/barcode/qrcode) - * @param {number} seq 序号 - * @return {string} 唯一 ID - */ -function makeId(type, seq) { - return `${type}_${TS_BASE}_${String(seq).padStart(4, '0')}`; -} - -/** - * 生成 text 类型标签元素(纯文字标签,如"入库单号:"),有 custom: true。 - * @param {number} seq 序号 - * @param {number} top 顶部位置(mm) - * @param {number} left 左侧位置(mm) - * @param {number} width 宽度(mm) - * @param {number} height 高度(mm) - * @param {string} content 文字内容 - * @param {string} fontSize 字体大小(字符串类型) - * @param {object} options 可选配置 { bold, textAlign } - * @return {object} 标签元素 - */ -function label(seq, top, left, width, height, content, fontSize, options = {}) { - return { - id: makeId('text', seq), - type: 'text', - top, - left, - width, - height, - custom: true, - content, - fontSize, - bold: options.bold || false, - italic: false, - underline: false, - rotate: 0, - textAlign: options.textAlign || 'left', - lineHeight: height, - }; -} - -/** - * 生成 text 类型数据字段元素(绑定 field_code),无 custom。 - * @param {number} seq 序号 - * @param {number} top 顶部位置(mm) - * @param {number} left 左侧位置(mm) - * @param {number} width 宽度(mm) - * @param {number} height 高度(mm) - * @param {string} fieldCode 字段编码 - * @param {string} fontSize 字体大小(字符串类型) - * @param {object} options 可选配置 { bold, textAlign } - * @return {object} 数据字段元素 - */ -function field(seq, top, left, width, height, fieldCode, fontSize, options = {}) { - return { - id: makeId('text', seq), - type: 'text', - top, - left, - width, - height, - field_code: fieldCode, - fontSize, - bold: options.bold || false, - italic: false, - underline: false, - rotate: 0, - textAlign: options.textAlign || 'left', - lineHeight: height, - }; -} - -/** - * 生成分割线元素。 - * @param {number} seq 序号 - * @param {number} top 顶部位置(mm) - * @param {number} left 左侧位置(mm) - * @param {number} width 宽度(mm) - * @param {number} height 高度(mm) - * @return {object} 分割线元素 - */ -function lineEl(seq, top, left, width, height) { - return { - id: makeId('line', seq), - type: 'line', - top, - left, - width, - height, - }; -} - -/** - * 生成二维码元素。 - * @param {number} seq 序号 - * @param {number} top 顶部位置(mm) - * @param {number} left 左侧位置(mm) - * @param {number} width 宽度(mm) - * @param {number} height 高度(mm) - * @param {string} fieldCode 字段编码 - * @param {string} fontSize 字体大小 - * @return {object} 二维码元素 - */ -function qrcodeEl(seq, top, left, width, height, fieldCode, fontSize) { - return { - id: makeId('qrcode', seq), - type: 'qrcode', - top, - left, - width, - height, - field_code: fieldCode, - fontSize, - bold: false, - italic: false, - underline: false, - rotate: 0, - textAlign: 'center', - lineHeight: 6, - }; -} - -/** - * 生成表格列定义(严格参照 id=18 rows 格式)。 - * 每项为 type: "text" 的扁平对象,同时包含 field_code、content(中文表头)、width、样式属性。 - * @param {number} seq 序号 - * @param {string} fieldCode 字段编码 - * @param {string} content 中文表头内容 - * @param {number} colWidth 列宽(mm) - * @param {string} fontSize 字体大小 - * @param {boolean} bold 是否加粗 - * @param {string} textAlign 对齐方式 - * @return {object} 列定义对象 - */ -function tableColumn(seq, fieldCode, content, colWidth, fontSize, bold, textAlign) { - return { - id: makeId('text', seq), - type: 'text', - field_code: fieldCode, - content, - width: colWidth, - height: 6, - fontSize, - bold: bold || false, - italic: false, - underline: false, - rotate: 0, - textAlign: textAlign || 'left', - lineHeight: 6, - }; -} - -// ─── 构建入库单 A5 模板元素数组 ───────────────────────────── - -const templateContent = [ - - // 1. 标题:入 库 单 - label(1, 6, 0, 148, 10, '入 库 单', '18', { bold: true, textAlign: 'center' }), - - // 2. 分割线 - lineEl(2, 18, 10, 128, 0.5), - - // 3. 信息区 - 第一行:入库单号 | 业务类型 - label(3, 21, 10, 26, 7, '入库单号:', '10'), - field(4, 21, 36, 46, 7, 'entry_order_code', '10'), - label(5, 21, 84, 20, 7, '业务类型:', '10'), - field(6, 21, 104, 34, 7, 'order_type', '10'), - - // 3. 信息区 - 第二行:供应商 | 采购单号 - label(7, 29, 10, 20, 7, '供应商:', '10'), - field(8, 29, 30, 52, 7, 'supplier_name', '10'), - label(9, 29, 84, 26, 7, '采购单号:', '10'), - field(10, 29, 110, 28, 7, 'purchase_order_code', '10'), - - // 3. 信息区 - 第三行:仓库 | 货主 - label(11, 37, 10, 18, 7, '仓库:', '10'), - field(12, 37, 28, 54, 7, 'warehouse_name', '10'), - label(13, 37, 84, 18, 7, '货主:', '10'), - field(14, 37, 102, 36, 7, 'store_name', '10'), - - // 3. 信息区 - 第四行:物流公司 | 运单号 - label(15, 45, 10, 26, 7, '物流公司:', '10'), - field(16, 45, 36, 46, 7, 'logistics_name', '10'), - label(17, 45, 84, 20, 7, '运单号:', '10'), - field(18, 45, 104, 34, 7, 'express_code', '10'), - - // 3. 信息区 - 第五行:创建时间 | 预期到货 - label(19, 53, 10, 26, 7, '创建时间:', '10'), - field(20, 53, 36, 46, 7, 'order_create_time', '10'), - label(21, 53, 84, 26, 7, '预期到货:', '10'), - field(22, 53, 110, 28, 7, 'expect_start_time', '10'), - - // 4. 分割线 - lineEl(23, 62, 10, 128, 0.5), - - // 5. 入库明细标题 - label(24, 65, 10, 128, 7, '入库明细', '11', { bold: true, textAlign: 'left' }), - - // 6. 表格(严格参照 id=18 rows 格式:每列为 type: "text" 对象) - { - id: makeId('table', 25), - type: 'table', - top: 74, - left: 10, - width: 128, - height: 75, - rowHeight: 6, - headerHeight: 6, - rows: [ - tableColumn(26, 'item_code', '商品编码', 22, '9', false, 'left'), - tableColumn(27, 'item_name', '商品名称', 40, '9', false, 'left'), - tableColumn(28, 'item_barcode', '条码', 22, '9', false, 'left'), - tableColumn(29, 'plan_qty', '计划数量', 18, '9', false, 'left'), - tableColumn(30, 'received_qty', '已收数量', 18, '9', false, 'left'), - tableColumn(31, 'inventory_type', '库存类型', 8, '9', false, 'left'), - ], - }, - - // 7. 分割线 - lineEl(32, 151, 10, 128, 0.5), - - // 8. 单据总行数 - label(33, 155, 64, 26, 7, '单据总行数:', '9'), - field(34, 155, 90, 48, 7, 'total_order_lines', '9'), - - // 9. 备注 - label(35, 164, 10, 14, 7, '备注:', '9'), - field(36, 164, 24, 114, 7, 'remark', '9'), - - // 10. 二维码:entry_order_code - qrcodeEl(37, 4, 120, 24, 24, 'entry_order_code', '8'), - - // 11. 打印时间 - label(38, 174, 10, 26, 7, '打印时间:', '9'), - field(39, 174, 36, 102, 7, 'print_time', '9'), - -]; - -module.exports.up = async queryInterface => { - const { sequelize } = queryInterface; - - // 先删除可能存在的旧版本 id=20 - await sequelize.query( - `DELETE FROM \`${TABLE}\` WHERE id = 20`, - { type: sequelize.QueryTypes.DELETE } - ); - - // 插入修正后的入库单 A5 模板(id=20) - await sequelize.query( - `INSERT INTO \`${TABLE}\` - (id, business_type, template_name, platform, warehouse_id, page_width, page_height, template_content, template_type, template_url, is_default, status, create_at, update_at) - VALUES (20, 'ENTRY_ORDER', '入库单A5模板', 'default', NULL, 148, 210, :template_content, 'CUSTOM', '', true, 'ACTIVE', NOW(), NOW())`, - { - replacements: { - template_content: JSON.stringify(templateContent), - }, - type: sequelize.QueryTypes.INSERT, - } - ); -}; - -module.exports.down = async queryInterface => { - const { sequelize } = queryInterface; - await sequelize.query( - `DELETE FROM \`${TABLE}\` WHERE id = 20`, - { type: sequelize.QueryTypes.DELETE } - ); -}; - -module.exports.templateContent = templateContent; diff --git a/database/migrations/20260702-migrate-entry-order-print-data.js b/database/migrations/20260702-migrate-entry-order-print-data.js deleted file mode 100644 index 1b47e12..0000000 --- a/database/migrations/20260702-migrate-entry-order-print-data.js +++ /dev/null @@ -1,53 +0,0 @@ -'use strict'; - -/** - * 将 wms_print_items 和 wms_print_template 表中已存在的入库单打印数据 - * 从 RECEIPT 迁移到 ENTRY_ORDER。 - * - * 背景: - * - RECEIPT 下同时有收货单(platform=warehouse)和入库单(platform=default)的数据 - * - 只有 platform='default' 的才是入库单,需要迁移 - * - platform='warehouse' 的是收货单,保留在 RECEIPT - * - * up: 将 business_type='RECEIPT' AND platform='default' → business_type='ENTRY_ORDER' - * down:将 business_type='ENTRY_ORDER' AND platform='default' → business_type='RECEIPT' - */ - -const PRINT_ITEMS_TABLE = 'wms_print_items'; -const PRINT_TEMPLATE_TABLE = 'wms_print_template'; - -module.exports.up = async queryInterface => { - const { sequelize } = queryInterface; - - // 1) wms_print_items:入库单打印项迁移 - await sequelize.query( - `UPDATE \`${PRINT_ITEMS_TABLE}\` - SET business_type = 'ENTRY_ORDER', updated_at = NOW() - WHERE business_type = 'RECEIPT' AND platform = 'default'` - ); - - // 2) wms_print_template:入库单打印模板迁移 - await sequelize.query( - `UPDATE \`${PRINT_TEMPLATE_TABLE}\` - SET business_type = 'ENTRY_ORDER', update_at = NOW() - WHERE business_type = 'RECEIPT' AND platform = 'default'` - ); -}; - -module.exports.down = async queryInterface => { - const { sequelize } = queryInterface; - - // 1) wms_print_items:入库单打印项回退 - await sequelize.query( - `UPDATE \`${PRINT_ITEMS_TABLE}\` - SET business_type = 'RECEIPT', updated_at = NOW() - WHERE business_type = 'ENTRY_ORDER' AND platform = 'default'` - ); - - // 2) wms_print_template:入库单打印模板回退 - await sequelize.query( - `UPDATE \`${PRINT_TEMPLATE_TABLE}\` - SET business_type = 'RECEIPT', update_at = NOW() - WHERE business_type = 'ENTRY_ORDER' AND platform = 'default'` - ); -}; diff --git a/database/migrations/20260702-seed-receipt-default-template.js b/database/migrations/20260702-seed-receipt-default-template.js deleted file mode 100644 index 6ef39db..0000000 --- a/database/migrations/20260702-seed-receipt-default-template.js +++ /dev/null @@ -1,42 +0,0 @@ -'use strict'; - -/** - * 入库单 A5 默认打印模板(ENTRY_ORDER 业务类型)数据清理迁移。 - * - * 背景: - * 旧版本 migration 已创建了一个格式正确的入库单模板(id=20,扁平化 content/field_code/bold/fontSize 风格)。 - * 本 migration 后来又插入了一个格式错误的模板(id=21,使用了 label+style 包装,与渲染引擎不兼容)。 - * - * 本迁移的作用: - * - 删除格式错误的重复模板 id=21(如果存在) - * - 保留下一个格式正确的模板(id=20)继续使用 - * - * 渲染引擎解析逻辑见 app/service/systemMethods/print.js(customize 分支): - * - 直接读取 item.content / item.fontSize / item.bold / item.textAlign 等扁平化属性 - * - 有 field_code 的元素用 data[field_code] 值覆盖 content - * - 不支持 label / style 对象包装 - */ - -const TABLE = 'wms_print_template'; - -module.exports.up = async queryInterface => { - const { sequelize } = queryInterface; - - // 删除格式错误的重复模板(id=21,使用了 label+style 包装格式) - // 保留格式正确的模板 id=20(扁平化 content/field_code/bold/fontSize 风格) - const [ duplicate ] = await sequelize.query( - `SELECT id FROM \`${TABLE}\` WHERE id = 21 AND business_type = 'ENTRY_ORDER' AND template_name = '入库单A5模板' AND warehouse_id IS NULL AND delete_at IS NULL LIMIT 1`, - { type: sequelize.QueryTypes.SELECT } - ); - - if (duplicate) { - await sequelize.query( - `DELETE FROM \`${TABLE}\` WHERE id = 21`, - { type: sequelize.QueryTypes.DELETE } - ); - } -}; - -module.exports.down = async () => { - // down 不回滚:删除 id=21 是一条清理操作,不需要恢复 -}; diff --git a/database/migrations/20260702-seed-receipt-print-items-v2.js b/database/migrations/20260702-seed-receipt-print-items-v2.js deleted file mode 100644 index f068a2c..0000000 --- a/database/migrations/20260702-seed-receipt-print-items-v2.js +++ /dev/null @@ -1,151 +0,0 @@ -'use strict'; - -/** - * ENTRY_ORDER(入库单)打印项配置 v2 补充。 - * - * 在 v1(20260622150000)基础上新增: - * - entry_order_info 组:15 个新字段(sort_order 14~28) - * - entry_items 表格:columns 从 6 扩展为 11,新增 5 列 - * - entry_items_info 组:17 个独立字段(group_sort=3, sort_order 1~17) - * - * up:INSERT IGNORE + UPDATE 表格配置 - * down:先恢复表格原始配置,再删除新增记录 - */ - -const TABLE = 'wms_print_items'; - -// ─── 新增打印项 ──────────────────────────────────────────────── -const NEW_PRINT_ITEMS = [ - // ─── entry_order_info 组补充(group_sort=1, sort_order 14~28) ── - { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '入库单ID', field_code: 'id', field_type: 'number', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 14, required: false, status: 1 }, - { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '来源类型', field_code: 'source_type', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 15, required: false, status: 1 }, - { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '同步状态', field_code: 'sync_status', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 16, required: false, status: 1 }, - { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '同步返回信息', field_code: 'sync_message', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 17, required: false, status: 1 }, - { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '仓库ID', field_code: 'warehouse_id', field_type: 'number', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 18, required: false, status: 1 }, - { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '货主ID', field_code: 'store_id', field_type: 'number', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 19, required: false, status: 1 }, - { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '最迟预期到货时间', field_code: 'expect_end_time', field_type: 'datetime', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 20, required: false, status: 1 }, - { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '物流公司编码', field_code: 'logistics_code', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 21, required: false, status: 1 }, - { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '供应商编码', field_code: 'supplier_code', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 22, required: false, status: 1 }, - { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '费用是否记录', field_code: 'expense_record', field_type: 'number', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 23, required: false, status: 1 }, - { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '是否启用', field_code: 'is_enabled', field_type: 'number', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 24, required: false, status: 1 }, - { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '创建时间', field_code: 'created_at', field_type: 'datetime', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 25, required: false, status: 1 }, - { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '更新时间', field_code: 'updated_at', field_type: 'datetime', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 26, required: false, status: 1 }, - { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '关联仓库名称', field_code: 'warehouse_company_name', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 27, required: false, status: 1 }, - { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '关联货主名称', field_code: 'store_company_name', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 28, required: false, status: 1 }, - - // ─── entry_items_info 独立字段(group_sort=3) ────────────────── - { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '商品SKU ID', field_code: 'stock_id', field_type: 'number', group_field: 'entry_items_info', group_label: '入库明细信息', group_sort: 3, sort_order: 1, required: false, status: 1 }, - { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '外部商品编码', field_code: 'external_item_code', field_type: 'text', group_field: 'entry_items_info', group_label: '入库明细信息', group_sort: 3, sort_order: 2, required: false, status: 1 }, - { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '外部商品ID', field_code: 'external_item_id', field_type: 'number', group_field: 'entry_items_info', group_label: '入库明细信息', group_sort: 3, sort_order: 3, required: false, status: 1 }, - { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '仓库商品编码', field_code: 'warehouse_item_code', field_type: 'text', group_field: 'entry_items_info', group_label: '入库明细信息', group_sort: 3, sort_order: 4, required: false, status: 1 }, - { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '仓库商品名称', field_code: 'warehouse_item_name', field_type: 'text', group_field: 'entry_items_info', group_label: '入库明细信息', group_sort: 3, sort_order: 5, required: false, status: 1 }, - { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '仓库商品规格', field_code: 'warehouse_item_spec', field_type: 'text', group_field: 'entry_items_info', group_label: '入库明细信息', group_sort: 3, sort_order: 6, required: false, status: 1 }, - { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '仓库当前库存总量', field_code: 'warehouse_quantity', field_type: 'number', group_field: 'entry_items_info', group_label: '入库明细信息', group_sort: 3, sort_order: 7, required: false, status: 1 }, - { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '仓库锁定数量', field_code: 'warehouse_locked_quantity', field_type: 'number', group_field: 'entry_items_info', group_label: '入库明细信息', group_sort: 3, sort_order: 8, required: false, status: 1 }, - { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '是否批次管理', field_code: 'warehouse_is_batch_mgmt', field_type: 'text', group_field: 'entry_items_info', group_label: '入库明细信息', group_sort: 3, sort_order: 9, required: false, status: 1 }, - { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '是否效期管理', field_code: 'warehouse_is_shelf_life_mgmt', field_type: 'text', group_field: 'entry_items_info', group_label: '入库明细信息', group_sort: 3, sort_order: 10, required: false, status: 1 }, - { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '直入已入库数量', field_code: 'direct_inbound_quantity', field_type: 'number', group_field: 'entry_items_info', group_label: '入库明细信息', group_sort: 3, sort_order: 11, required: false, status: 1 }, - { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '剩余可入库数量', field_code: 'remaining_quantity', field_type: 'number', group_field: 'entry_items_info', group_label: '入库明细信息', group_sort: 3, sort_order: 12, required: false, status: 1 }, - { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '外部业务编码', field_code: 'out_biz_code', field_type: 'text', group_field: 'entry_items_info', group_label: '入库明细信息', group_sort: 3, sort_order: 13, required: false, status: 1 }, - { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '订单行号', field_code: 'order_line_no', field_type: 'number', group_field: 'entry_items_info', group_label: '入库明细信息', group_sort: 3, sort_order: 14, required: false, status: 1 }, - { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '货主编码', field_code: 'owner_code', field_type: 'text', group_field: 'entry_items_info', group_label: '入库明细信息', group_sort: 3, sort_order: 15, required: false, status: 1 }, - { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '库存类型', field_code: 'inventory_type', field_type: 'text', group_field: 'entry_items_info', group_label: '入库明细信息', group_sort: 3, sort_order: 16, required: false, status: 1 }, - { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '已确认收货数量', field_code: 'confirm_quantity', field_type: 'number', group_field: 'entry_items_info', group_label: '入库明细信息', group_sort: 3, sort_order: 17, required: false, status: 1 }, -]; - -// ─── 旧 items 表格配置(v1) ──────────────────────────────────── -const OLD_ITEMS_TABLE_CONFIG = { - columns: 6, - headers: [ '商品编码', '商品名称', '条码', '计划数量', '已收数量', '库存类型' ], -}; - -// ─── 新 items 表格配置(v2 扩展为 11 列) ─────────────────────── -const NEW_ITEMS_TABLE_CONFIG = { - columns: 11, - headers: [ '行号', '商品编码(外部)', '商品名称', '条码', '仓库商品编码', '计划数量', '已收数量', '已确认数量', '直入数量', '剩余可入库', '库存类型' ], -}; - -// ══════════════════════════════════════════════════════════════════ -const NEW_FIELD_CODES = NEW_PRINT_ITEMS.map(it => it.field_code); - -module.exports.up = async queryInterface => { - const { sequelize } = queryInterface; - - // 1) 插入所有新增打印项(幂等) - for (const item of NEW_PRINT_ITEMS) { - await sequelize.query( - `INSERT IGNORE INTO \`${TABLE}\` - (business_type, platform, field_name, field_code, field_type, is_table, table_config, group_field, group_label, group_sort, sort_order, required, status, created_at, updated_at) - VALUES (:business_type, :platform, :field_name, :field_code, :field_type, :is_table, :table_config, :group_field, :group_label, :group_sort, :sort_order, :required, :status, NOW(), NOW())`, - { - replacements: { - business_type: item.business_type, - platform: item.platform, - field_name: item.field_name, - field_code: item.field_code, - field_type: item.field_type, - is_table: item.is_table ? 1 : 0, - table_config: item.table_config ? JSON.stringify(item.table_config) : null, - group_field: item.group_field || null, - group_label: item.group_label || null, - group_sort: item.group_sort || 0, - sort_order: item.sort_order || 0, - required: item.required ? 1 : 0, - status: item.status, - }, - type: sequelize.QueryTypes.INSERT, - } - ); - } - - // 2) 更新 items 表格配置:6 列 → 11 列 - await sequelize.query( - `UPDATE \`${TABLE}\` - SET table_config = :table_config, - updated_at = NOW() - WHERE business_type = 'ENTRY_ORDER' - AND platform = 'default' - AND field_code = 'items'`, - { - replacements: { - table_config: JSON.stringify(NEW_ITEMS_TABLE_CONFIG), - }, - type: sequelize.QueryTypes.UPDATE, - } - ); -}; - -module.exports.down = async queryInterface => { - const { sequelize } = queryInterface; - - // 1) 恢复 items 表格原有配置(columns:6) - await sequelize.query( - `UPDATE \`${TABLE}\` - SET table_config = :table_config, - updated_at = NOW() - WHERE business_type = 'ENTRY_ORDER' - AND platform = 'default' - AND field_code = 'items'`, - { - replacements: { - table_config: JSON.stringify(OLD_ITEMS_TABLE_CONFIG), - }, - type: sequelize.QueryTypes.UPDATE, - } - ); - - // 2) 精确删除本次新增的所有打印项 - if (NEW_FIELD_CODES.length > 0) { - const placeholders = NEW_FIELD_CODES.map(() => '?').join(','); - await sequelize.query( - `DELETE FROM \`${TABLE}\` - WHERE business_type = 'ENTRY_ORDER' - AND platform = 'default' - AND field_code IN (${placeholders})`, - { - replacements: NEW_FIELD_CODES, - type: sequelize.QueryTypes.DELETE, - } - ); - } -}; diff --git a/database/migrations/20260703000000-add-binding-fields-to-wms-inbound-direct-log.js b/database/migrations/20260703000000-add-binding-fields-to-wms-inbound-direct-log.js new file mode 100644 index 0000000..7ff40f3 --- /dev/null +++ b/database/migrations/20260703000000-add-binding-fields-to-wms-inbound-direct-log.js @@ -0,0 +1,100 @@ +'use strict'; + +const TABLE_NAME = 'wms_inbound_direct_log'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME); + if (!exists) return; + + const columns = await queryInterface.describeTable(TABLE_NAME); + + // 新增 entry_item_id 字段 + if (!columns.entry_item_id) { + await queryInterface.addColumn(TABLE_NAME, 'entry_item_id', { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '入库明细ID', + }); + } + + // 新增 receiving_detail_id 字段 + if (!columns.receiving_detail_id) { + await queryInterface.addColumn(TABLE_NAME, 'receiving_detail_id', { + type: Sequelize.INTEGER(11), + allowNull: true, + defaultValue: null, + comment: '收货明细ID,绑定收货时使用', + }); + } + + // 新增 status 字段 + if (!columns.status) { + await queryInterface.addColumn(TABLE_NAME, 'status', { + type: Sequelize.ENUM('pending', 'committed', 'released'), + allowNull: true, + defaultValue: null, + comment: '绑定状态:pending=待提交 committed=已提交 released=已释放,非绑定模式为NULL', + }); + } + + // 新增 updated_at 字段 + if (!columns.updated_at) { + await queryInterface.addColumn(TABLE_NAME, 'updated_at', { + type: Sequelize.DATE, + allowNull: true, + defaultValue: null, + comment: '更新时间', + }); + } + + // 新增 deleted_at 字段(软删除) + if (!columns.deleted_at) { + await queryInterface.addColumn(TABLE_NAME, 'deleted_at', { + type: Sequelize.DATE, + allowNull: true, + defaultValue: null, + comment: '软删除时间', + }); + } + + // 新增索引 idx_entry_item_id + await queryInterface.addIndex(TABLE_NAME, [ 'entry_item_id' ], { + name: 'idx_entry_item_id', + }); + + // 新增索引 idx_receiving_detail_id + await queryInterface.addIndex(TABLE_NAME, [ 'receiving_detail_id' ], { + name: 'idx_receiving_detail_id', + }); + + // 新增索引 idx_status + await queryInterface.addIndex(TABLE_NAME, [ 'status' ], { + name: 'idx_status', + }); + + // 新增唯一约束 uk_entry_receiving_binding + await queryInterface.addIndex(TABLE_NAME, [ 'entry_item_id', 'receiving_detail_id', 'status' ], { + name: 'uk_entry_receiving_binding', + unique: true, + }); + }, + + down: async queryInterface => { + // 移除唯一约束 + await queryInterface.removeIndex(TABLE_NAME, 'uk_entry_receiving_binding'); + // 移除索引 + await queryInterface.removeIndex(TABLE_NAME, 'idx_status'); + await queryInterface.removeIndex(TABLE_NAME, 'idx_receiving_detail_id'); + await queryInterface.removeIndex(TABLE_NAME, 'idx_entry_item_id'); + + // 移除字段 + await queryInterface.removeColumn(TABLE_NAME, 'deleted_at'); + await queryInterface.removeColumn(TABLE_NAME, 'updated_at'); + await queryInterface.removeColumn(TABLE_NAME, 'status'); + await queryInterface.removeColumn(TABLE_NAME, 'receiving_detail_id'); + await queryInterface.removeColumn(TABLE_NAME, 'entry_item_id'); + }, +}; diff --git a/database/migrations/20260703000001-migrate-binding-data-to-inbound-direct-log.js b/database/migrations/20260703000001-migrate-binding-data-to-inbound-direct-log.js new file mode 100644 index 0000000..7ec574e --- /dev/null +++ b/database/migrations/20260703000001-migrate-binding-data-to-inbound-direct-log.js @@ -0,0 +1,184 @@ +'use strict'; + +/** + * 数据迁移:将 wms_entry_receiving_binding 存量数据迁移到 wms_inbound_direct_log。 + * + * 背景: + * - wms_entry_receiving_binding 的"入库明细 ↔ 收货明细"绑定能力已迁移到 wms_inbound_direct_log。 + * - 本 migration 负责将 wms_entry_receiving_binding 中的历史数据同步到 wms_inbound_direct_log。 + * + * 字段映射(source → target): + * - entry_item_id / receiving_detail_id / allocated_quantity→quantity / status / creator_id→operator_id + * - created_at→created_at / updated_at→updated_at / deleted_at→deleted_at + * + * 关联补全: + * - entry_order_id / entry_order_code / warehouse_id / store_id:通过 wms_entry_items + wms_entry_order + * - stock_id:从 wms_entry_items + * - inbound_type:固定 'pda' + * - space_id:固定 0 + * + * @description 迁移脚本:20260703000001 + */ + +/** 目标表名 */ +const TARGET_TABLE = 'wms_inbound_direct_log'; +/** 源表名 */ +const SOURCE_TABLE = 'wms_entry_receiving_binding'; + +/** + * 规范化 showAllTables 返回的表名。 + * @param {string|Object} table 表名或表对象。 + * @return {string} 规范化后的表名。 + */ +const normalizeTableName = table => { + if (typeof table === 'string') return table; + return table && typeof table === 'object' ? (table.tableName || table.name || '') : ''; +}; + +/** + * 检查源表是否存在。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 源表是否存在。 + */ +const hasSourceTable = async queryInterface => { + const allTables = await queryInterface.showAllTables(); + const tableSet = new Set((allTables || []).map(normalizeTableName)); + return tableSet.has(SOURCE_TABLE); +}; + +/** + * 检查目标表是否存在。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 目标表是否存在。 + */ +const hasTargetTable = async queryInterface => { + const allTables = await queryInterface.showAllTables(); + const tableSet = new Set((allTables || []).map(normalizeTableName)); + return tableSet.has(TARGET_TABLE); +}; + +/** + * 统计源表总行数。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 源表总行数。 + */ +const countSourceRows = async queryInterface => { + const [ rows ] = await queryInterface.sequelize.query( + `SELECT COUNT(*) AS cnt FROM ${SOURCE_TABLE}`, + { type: queryInterface.sequelize.QueryTypes.SELECT } + ); + return rows ? rows.cnt : 0; +}; + +/** + * 正向迁移:从 wms_entry_receiving_binding 迁移数据到 wms_inbound_direct_log。 + * + * 去重策略:按 (entry_item_id, receiving_detail_id, status) GROUP BY 去重, + * 重复组保留 id 最小的一条,其余跳过并打印数量。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。 + * @return {Promise} 无返回值。 + */ +module.exports.up = async (queryInterface, Sequelize) => { + void Sequelize; + + // 幂等:源表不存在则跳过 + if (!(await hasSourceTable(queryInterface))) { + console.log('wms_entry_receiving_binding 表不存在,跳过迁移'); + return; + } + + // 幂等:目标表不存在则跳过 + if (!(await hasTargetTable(queryInterface))) { + console.log('wms_inbound_direct_log 表不存在,跳过迁移'); + return; + } + + const totalRows = await countSourceRows(queryInterface); + console.log(`wms_entry_receiving_binding 总行数:${totalRows}`); + + if (totalRows === 0) { + console.log('无数据需要迁移,跳过'); + return; + } + + // 统计去重后跳过的行数 + const [ dupResult ] = await queryInterface.sequelize.query( + `SELECT COUNT(*) AS skip_cnt + FROM ${SOURCE_TABLE} + WHERE id NOT IN ( + SELECT MIN(id) + FROM ${SOURCE_TABLE} + GROUP BY entry_item_id, receiving_detail_id, status + )`, + { type: queryInterface.sequelize.QueryTypes.SELECT } + ); + const skipCount = dupResult ? dupResult.skip_cnt : 0; + if (skipCount > 0) { + console.log(`检测到 ${skipCount} 条重复记录(按 entry_item_id + receiving_detail_id + status 分组去重),将被跳过`); + } + + // 执行 INSERT INTO ... SELECT + const [ insertResult ] = await queryInterface.sequelize.query( + `INSERT INTO ${TARGET_TABLE} + (entry_item_id, receiving_detail_id, quantity, status, + operator_id, created_at, updated_at, deleted_at, + entry_order_id, entry_order_code, warehouse_id, store_id, + stock_id, inbound_type, space_id) + SELECT + b.entry_item_id, + b.receiving_detail_id, + b.allocated_quantity, + b.status, + b.creator_id, + b.created_at, + b.updated_at, + b.deleted_at, + ei.order_id, + eo.entry_order_code, + eo.warehouse_id, + eo.store_id, + ei.stock_id, + 'pda', + 0 + FROM ${SOURCE_TABLE} b + LEFT JOIN wms_entry_items ei ON b.entry_item_id = ei.id + LEFT JOIN wms_entry_order eo ON ei.order_id = eo.id + WHERE b.id IN ( + SELECT MIN(id) + FROM ${SOURCE_TABLE} + GROUP BY entry_item_id, receiving_detail_id, status + )`, + { type: queryInterface.sequelize.QueryTypes.INSERT } + ); + + const insertedCount = insertResult ? (Array.isArray(insertResult) ? insertResult.length : insertResult[1]) : 0; + console.log(`迁移完成:成功插入 ${insertedCount} 行`); +}; + +/** + * 回滚迁移:删除从 wms_entry_receiving_binding 迁移过来的数据。 + * + * 删除条件:receiving_detail_id IS NOT NULL AND entry_item_id IS NOT NULL + * (仅删除有绑定关系的记录,不影响原有 direct-log 数据) + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ +module.exports.down = async queryInterface => { + if (!(await hasTargetTable(queryInterface))) { + console.log('wms_inbound_direct_log 表不存在,跳过回滚'); + return; + } + + const [ deleteResult ] = await queryInterface.sequelize.query( + `DELETE FROM ${TARGET_TABLE} + WHERE receiving_detail_id IS NOT NULL + AND entry_item_id IS NOT NULL`, + { type: queryInterface.sequelize.QueryTypes.DELETE } + ); + + const deletedCount = deleteResult || 0; + console.log(`回滚完成:删除 ${deletedCount} 行`); +}; diff --git a/docs/api-doc-update-spec.example.json b/docs/api-doc-update-spec.example.json deleted file mode 100644 index 2477ca5..0000000 --- a/docs/api-doc-update-spec.example.json +++ /dev/null @@ -1,56 +0,0 @@ -{ - "docName": "", - "docMeta": { - "updatedAt": "", - "version": "" - }, - "group": { - "groupName": "<分组名称>", - "module": "" - }, - "methods": [ - { - "method": "", - "description": "<接口说明>", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [], - "params": [ - { - "name": "", - "type": "string", - "required": true, - "source": "body", - "description": "<参数说明>" - } - ], - "response": [ - { - "name": "", - "type": "string", - "required": true, - "description": "<返回字段说明>" - } - ], - "errors": [ - { - "code": 400, - "message": "<错误说明>" - } - ] - } - ], - "change": { - "version": "", - "date": "", - "summary": "<本次变更摘要>", - "methods": [ - "" - ], - "notes": [ - "<变更说明 1>", - "<变更说明 2>" - ], - "type": "updated" - } -} \ No newline at end of file diff --git a/docs/api-doc-update-workflow.md b/docs/api-doc-update-workflow.md deleted file mode 100644 index c5e8343..0000000 --- a/docs/api-doc-update-workflow.md +++ /dev/null @@ -1,124 +0,0 @@ -# API 文档 JSON 固定写入流程 - -## 现有 JSON 结构 - -仓库内现有 API 文档分两类: - -1. `methods/.json` - - 根节点是对象 - - 关键字段固定为 `module`、`description`、`version`、`updatedAt`、`headers`、`methods.groups` - - `methods.groups` 为数组,每个 group 固定为 `groupName`、`module`、`list` - - `list` 中每个 method 固定包含 `method`、`description`、`isNeedAuth`、`isNeedLogin`、`headers`、`params`、`response`、`errors` - -2. `methods/changes/.json` - - 根节点是数组 - - 每条变更记录建议固定包含 `version`、`date`、`summary`、`methods`、`notes` - - 可选补充 `type` - -## 固定输入 spec - -后续 API 文档写入统一通过脚本读取一个 spec JSON 完成,spec 结构固定如下: - -```json -{ - "docName": "system", - "docMeta": { - "updatedAt": "2026-04-15", - "version": "0.3.5" - }, - "group": { - "groupName": "基础模块", - "module": "index" - }, - "methods": [ - { - "method": "index.example", - "description": "接口说明", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [], - "params": [], - "response": [], - "errors": [] - } - ], - "change": { - "version": "2026.04.15-system-06", - "date": "2026-04-15", - "summary": "一句话说明本次接口文档变更", - "methods": [ - "index.example" - ], - "notes": [ - "补充关键字段说明。" - ], - "type": "updated" - } -} -``` - -说明: - -- `docName` 目前必须对应已存在的 `methods/system.json`、`methods/qimen.json`、`methods/gateway.json` -- `group` 用于定位或创建目标分组 -- `methods` 为要写入的完整 method 文档对象数组,脚本按 `method` 字段 upsert -- `change` 默认必填;仅当明确是纯格式修复且不需要追加历史时,才允许加 `--doc-only` - -注意:所有对 `methods/*.json` 与 `methods/changes/*.json` 的变更必须通过 spec + 脚本完成。spec 是唯一输入来源,不接受直接手写或直接提交目标 JSON 的改动。 - -## 固定命令 - -务必按顺序执行:复制 example -> 编辑 spec -> dry-run -> 修正 -> 正式写入。示例命令(PowerShell): - -先做 dry-run(验证和查看差异): - -```powershell -npm run doc:api:update -- --spec=temp/api-doc-update.json --dry-run -``` - -确认 dry-run 输出无误后执行正式写入: - -```powershell -npm run doc:api:update -- --spec=temp/api-doc-update.json -``` - -仅修补主文档且不追加 changes 时(慎用): - -```powershell -npm run doc:api:update -- --spec=temp/api-doc-update.json --doc-only -``` - -## 脚本保证 - -`script/update-api-doc.cjs` 会执行以下动作(脚本为写入守门人): - -- 校验 spec JSON 是否符合固定结构与必填字段 -- 校验目标 `methods/*.json` 与 `methods/changes/*.json` 是否可解析 -- 在 dry-run 模式下不写入,仅打印将要变更的差异并返回校验结果 -- 按 `group` + `method` 做 upsert,避免覆盖或破坏其他分组/方法 -- 检查 change version 是否重复并拒绝冲突写入 -- 尽量保留目标 JSON 原有缩进与换行风格,减少无关 diff - -脚本是对 methods JSON 的唯一写入通道;任何绕过脚本的改动都不被接受。 - -## 推荐流程 - -1. 先核对代码与测试,确认真实接口契约 -2. 如果是 system 参数结构变化,可先执行 `node .\script\tmp-struct-system-params.cjs` -3. 按 [docs/api-doc-update-spec.example.json](docs/api-doc-update-spec.example.json) 复制一份 spec 到 `temp/` 并在该文件上编辑 -4. 先执行 dry-run(`--dry-run`),阅读输出并修正 spec -5. 确认无误后执行正式写入(不带 `--dry-run`) -6. 最后补充必要的 `docs/*.md` 或 `README.md` - -最小示例流程(PowerShell): - -```powershell -# 复制示例到 temp 并编辑 -Copy-Item docs/api-doc-update-spec.example.json temp/api-doc-update.json - -# dry-run -npm run doc:api:update -- --spec=temp/api-doc-update.json --dry-run - -# 正式写入 -npm run doc:api:update -- --spec=temp/api-doc-update.json -``` \ No newline at end of file diff --git a/docs/combo-goods-api.md b/docs/combo-goods-api.md deleted file mode 100644 index 5b6ea72..0000000 --- a/docs/combo-goods-api.md +++ /dev/null @@ -1,387 +0,0 @@ -# 组合商品(comboGoods)模块 API 文档 - -## 模块概述 - -组合商品(comboGoods)模块提供组合商品的 CRUD 和搜索功能。组合商品是将多个系统商品(来自 `wms_stock_warehouse`)捆绑在一起的商品概念,用于订单快速选择。 - -**代码文件:** -- 业务逻辑层:`app/service/systems/comboGoods.js` -- 接口包装层:`app/service/systemMethods/comboGoods.js` - -**数据表:** -- `wms_combo_goods`:组合商品主表 -- `wms_combo_goods_item`:组合商品明细表 - ---- - -## 数据库表结构 - -### 主表:wms_combo_goods - -| 字段 | 类型 | 说明 | -|------|------|------| -| id | number | 主键ID | -| combo_code | string | 组合商品编码(唯一) | -| combo_name | string | 组合商品名称 | -| combo_sku_id | number | 组合商品SKU ID | -| custom_code | string\|null | 自定义编码,按货主唯一(排除已删除记录) | -| status | number | 状态:1=启用 0=停用 | -| warehouse_id | number\|null | 仓库ID | -| remark | string | 备注 | -| creator_id | number | 创建人ID | -| editor_id | number | 最后编辑人ID | -| created_at | datetime | 创建时间 | -| updated_at | datetime | 更新时间 | - -### 明细表:wms_combo_goods_item - -| 字段 | 类型 | 说明 | -|------|------|------| -| id | number | 主键ID | -| combo_id | number | 关联的组合商品ID | -| item_goods_sku_id | number | 子商品 stock_id(对应 wms_stock_warehouse.id) | -| item_quantity | number | 子商品数量 | -| sort_order | number | 排序号 | - ---- - -## 约束规则 - -### 商品有效性校验 - -创建/编辑组合商品时,所有子商品必须在 `wms_stock_warehouse` 表中满足以下条件: -- `is_valid = 'Y'`(有效状态) -- `deleted_at IS NULL`(未删除) - -任一子商品不满足条件,操作将被拒绝并返回具体的不合法 stock_id 列表。 - -### 货主一致性校验 - -所有子商品必须属于同一个货主(`store_id` 一致)。跨货主组合将返回错误:「所有子商品必须属于同一个货主,不允许跨货主组合」。 - -### 自定义编码(custom_code)校验 - -`custom_code` 为可选字段(VARCHAR(64)),仅做按货主唯一性校验(排除 status=0 的已删除记录)。 -- **create**:如果传入非空的 `custom_code`,会校验同货主非删除记录中唯一。 -- **update**:如果传入非空的 `custom_code`,会校验同货主非删除记录中唯一(排除自身 id)。 -- 唯一索引:`uk_store_custom_code(warehouse_id, custom_code)`。 - ---- - -## 简记格式说明 - -列表查询和搜索结果中会返回两种简记字段,供前端直接展示: - -### simpleNotation(字符串简记) - -格式:`stock_id|数量,stock_id2|数量` - -示例:`1001|3,1002|5` 表示 stock_id=1001 的商品 3 件 + stock_id=1002 的商品 5 件。 - -### nameNotation(商品名称简记) - -格式:`【数量】商品名称+【数量】商品名称` - -示例:`【3】苹果+【5】香蕉` 表示苹果 3 件 + 香蕉 5 件。 - -商品名称从 `wms_stock_warehouse.item_name` 获取;若 stock_id 无有效商品信息,则显示为 `SKU#stock_id`。 - ---- - -## 接口列表 - -### 1. comboGoods.list — 组合商品列表查询(分页) - -- **鉴权**:不需要(isNeedAuth=false) -- **登录**:需要 - -#### 请求参数 - -| 字段 | 类型 | 必填 | 说明 | -|------|------|------|------| -| pagination | object | 否 | 分页参数 | -| pagination.page | number | 否 | 页码,默认 1 | -| pagination.pageSize | number | 否 | 每页大小,默认 20,最大 200 | -| where | object | 否 | 筛选条件 | -| where.combo_code | string | 否 | 组合商品编码,精确匹配 | -| where.combo_name | string | 否 | 组合商品名称,模糊匹配 | -| where.status | number | 否 | 状态筛选:1=启用 0=停用 | -| where.warehouse_id | number | 否 | 仓库ID筛选 | - -#### 请求示例 - -```json -{ - "method": "comboGoods.list", - "data": { - "pagination": { - "page": 1, - "pageSize": 20 - }, - "where": { - "combo_name": "春节礼包", - "status": 1 - } - } -} -``` - -#### 响应格式 - -```json -{ - "code": 200, - "message": "查询成功", - "data": { - "list": [ - { - "id": 1, - "combo_code": "COMBO-001", - "combo_name": "春节礼包A", - "combo_sku_id": 0, - "custom_code": null, - "status": 1, - "warehouse_id": 1001, - "remark": "", - "creator_id": 10, - "editor_id": 10, - "created_at": "2026-06-01T10:00:00.000Z", - "updated_at": "2026-06-01T10:00:00.000Z", - "items": [ - { - "id": 1, - "combo_id": 1, - "item_goods_sku_id": 1001, - "item_quantity": 3, - "sort_order": 0 - }, - { - "id": 2, - "combo_id": 1, - "item_goods_sku_id": 1002, - "item_quantity": 5, - "sort_order": 1 - } - ], - "simpleNotation": "1001|3,1002|5", - "nameNotation": "【3】苹果+【5】香蕉" - } - ], - "total": 1, - "page": 1, - "pageSize": 20 - } -} -``` - ---- - -### 2. comboGoods.create — 创建组合商品 - -- **鉴权**:需要(isNeedAuth=true) -- **登录**:需要 - -#### 请求参数 - -| 字段 | 类型 | 必填 | 说明 | -|------|------|------|------| -| combo_code | string | 是 | 组合商品编码,全局唯一 | -| combo_name | string | 是 | 组合商品名称 | -| warehouse_id | number | 否 | 仓库ID | -| remark | string | 否 | 备注 | -| custom_code | string | 否 | 自定义编码,传入时校验按货主唯一(排除已删除记录) | -| items | array | 是 | 子商品明细数组 | -| items[].item_goods_sku_id | number | 是 | 子商品 stock_id | -| items[].item_quantity | number | 是 | 子商品数量(正整数) | -| items[].sort_order | number | 否 | 排序号,默认按数组索引 | - -#### 请求示例 - -```json -{ - "method": "comboGoods.create", - "data": { - "combo_code": "COMBO-001", - "combo_name": "春节礼包A", - "warehouse_id": 1001, - "remark": "2026春节促销礼包", - "items": [ - { "item_goods_sku_id": 1001, "item_quantity": 3 }, - { "item_goods_sku_id": 1002, "item_quantity": 5 } - ] - } -} -``` - -#### 响应格式 - -```json -{ - "code": 200, - "message": "创建成功", - "data": { - "id": 1, - "combo_code": "COMBO-001", - "combo_name": "春节礼包A", - "custom_code": null - } -} -``` - -#### 常见错误 - -| 错误信息 | 说明 | -|---------|------| -| 组合商品编码不能为空 | combo_code 未传或为空 | -| 组合商品名称不能为空 | combo_name 未传或为空 | -| 子商品列表不能为空 | items 未传或为空数组 | -| 组合商品编码 "XXX" 已存在 | combo_code 重复 | -| 自定义编码 "XXX" 已被货主其他组合商品使用 | custom_code 在同一货主下重复(排除已删除) | -| 以下子商品不存在或已停用:1001, 1002 | 子商品在 wms_stock_warehouse 中不存在或已停用 | -| 所有子商品必须属于同一个货主,不允许跨货主组合 | 明细中商品的 store_id 不一致 | - ---- - -### 3. comboGoods.update — 编辑组合商品 - -- **鉴权**:需要(isNeedAuth=true) -- **登录**:需要 - -#### 请求参数 - -| 字段 | 类型 | 必填 | 说明 | -|------|------|------|------| -| id | number | 是 | 组合商品ID | -| combo_name | string | 否 | 组合商品名称 | -| warehouse_id | number | 否 | 仓库ID | -| remark | string | 否 | 备注 | -| custom_code | string | 否 | 自定义编码,传入非空值时校验按货主唯一(排除已删除记录和自身 id) | -| status | number | 否 | 状态:1=启用 0=停用 | -| items | array | 否 | 子商品明细数组。传入非空数组时先删旧明细再插入新明细;不传保持原明细不变 | -| items[].item_goods_sku_id | number | 是 | 子商品 stock_id | -| items[].item_quantity | number | 是 | 子商品数量(正整数) | -| items[].sort_order | number | 否 | 排序号 | - -> **注意**:部分更新语义——不传的字段保持原值不变。items 为可选,不传或传空数组则保持原明细不变。 - -#### 请求示例 - -```json -{ - "method": "comboGoods.update", - "data": { - "id": 1, - "combo_name": "春节礼包A(升级版)", - "remark": "更新备注", - "items": [ - { "item_goods_sku_id": 1001, "item_quantity": 5 }, - { "item_goods_sku_id": 1003, "item_quantity": 2 } - ] - } -} -``` - -#### 响应格式 - -```json -{ - "code": 200, - "message": "编辑成功", - "data": { - "id": 1 - } -} -``` - ---- - -### 4. comboGoods.delete — 删除组合商品 - -- **鉴权**:需要(isNeedAuth=true) -- **登录**:需要 - -#### 请求参数 - -| 字段 | 类型 | 必填 | 说明 | -|------|------|------|------| -| id | number | 是 | 组合商品ID | - -> **注意**:删除操作为软删除,仅将 `status` 置为 0(停用),不会物理删除记录。 - -#### 请求示例 - -```json -{ - "method": "comboGoods.delete", - "data": { - "id": 1 - } -} -``` - -#### 响应格式 - -```json -{ - "code": 200, - "message": "删除成功", - "data": { - "id": 1 - } -} -``` - ---- - -### 5. comboGoods.search — 关键字搜索组合商品 - -- **鉴权**:不需要(isNeedAuth=false) -- **登录**:需要 - -#### 请求参数 - -| 字段 | 类型 | 必填 | 说明 | -|------|------|------|------| -| keyword | string | 是 | 搜索关键字,模糊匹配 custom_code、combo_code 和 combo_name,custom_code 匹配项优先排在前面 | -| limit | number | 否 | 最大返回条数,默认 20,最大 100 | - -> **注意**:仅返回启用状态(status=1)的记录。该接口用于手工建单时前端选择组合商品。 - -#### 请求示例 - -```json -{ - "method": "comboGoods.search", - "data": { - "keyword": "礼包", - "limit": 30 - } -} -``` - -#### 响应格式 - -```json -{ - "code": 200, - "message": "搜索成功", - "data": { - "list": [ - { - "id": 1, - "combo_code": "COMBO-001", - "combo_name": "春节礼包A", - "custom_code": null, - "status": 1, - "warehouse_id": 1001, - "items": [ - { "id": 1, "combo_id": 1, "item_goods_sku_id": 1001, "item_quantity": 3, "sort_order": 0 } - ], - "simpleNotation": "1001|3,1002|5", - "nameNotation": "【3】苹果+【5】香蕉" - } - ], - "total": 1 - } -} -``` diff --git a/docs/express-model-table-map.md b/docs/express-model-table-map.md deleted file mode 100644 index 75bddcd..0000000 --- a/docs/express-model-table-map.md +++ /dev/null @@ -1,33 +0,0 @@ -# Express 模型与数据表整理 - -## 一览 - -| 模型文件 | Sequelize key | 数据表 | 当前状态 | -| --- | --- | --- | --- | -| app/model/express.js | Express | wms_express | 已补齐 | -| app/model/express_setting.js | ExpressSetting | wms_express_setting | 已补齐 | -| app/model/order_express.js | OrderExpress | wms_order_express | 已补齐 | -| app/model/order_express_print_data.js | OrderExpressPrintData | wms_order_express_print_data | 已补齐 | -| app/model/express_print_record.js | ExpressPrintRecord | wms_express_print_record | 已补齐 | - -## 关键说明 - -- 本次仅整理模型与真实数据表对齐,不改动业务逻辑与接口行为。 -- 通过 `script/db-query.ps1` 实查,数据库中包含 5 张 express 相关表,上述模型已全部覆盖。 -- 既有字段型快递信息(如 `wms_entry_order.express_code`、`wms_order_delivery.express_code`)仍保留为业务字段,不属于独立主数据表。 - -## 建议的后续收敛 - -- 将 `index.getExpressList` 的配置源(`app.config.expressList`)逐步收敛到 `wms_express`,避免配置与数据表双源。 -- 若后续存在统一查询需求,可新增 `systems/express.js`,统一对 `Express / ExpressSetting / OrderExpress` 的读写入口。 - -## 包材关联字段说明 - -- **新增字段**:`wms_order_express.package_material_id`(可空,BIGINT unsigned)、`wms_order_express.package_material_name_snapshot`(可空,VARCHAR(128))。用于记录订单快递所使用的包材引用与名称快照,`package_material_id` 指向 `wms_package_material.id`。 -- **新增表**:`wms_package_material`(包材主数据表)和 `wms_package_supplier`(包材供应商表),均已在 migration 与 model 中定义;关键索引:`idx_wms_package_material_warehouse_id`、`uk_wms_package_material_warehouse_material_code`、`idx_wms_package_supplier_warehouse_id`、`uk_wms_package_supplier_warehouse_supplier_code`。 -- **索引**:为 `wms_order_express.package_material_id` 新增索引 `idx_wms_order_express_package_material_id`,以支持基于包材的过滤与联表查询。 -- **兼容性**:新增列为可空,不会破坏现有接口契约。若系统存在将 `wms_order_express` 全量返回给外部的接口(未在 methods/system.json 中声明新增字段),请在需要暴露字段的接口中补充文档说明并在变更记录中标注。当前已检查的 system 方法文档未需修改,因此本次不改 methods/system.json(无接口契约变化)。 -- **回滚要点**:迁移的 down 会删除新增列、索引与新增表;回滚前请务必备份或迁移相关业务数据。 - -文档维护者:WMS 文档代理 - diff --git a/docs/file-writer.md b/docs/file-writer.md deleted file mode 100644 index 087e3ee..0000000 --- a/docs/file-writer.md +++ /dev/null @@ -1,122 +0,0 @@ -# 本地文件队列(app.fileWriter) - -本文档说明仓库中提供的本地文件队列写入能力(实现文件:app/lib/file_writer.js),用于把业务数据按 JSON Lines 追加到本地文件并由消费者按需读取处理,适合低延迟、本地持久化、批处理/异步消费场景。 - -**实现要点(写入特性)** -- 串行写入:同一进程内通过内部队列 `enqueue` 串行化写入,保证单进程内顺序性。 -- 强制落盘:每次写入使用文件句柄写入并调用 `handle.sync()` 进行 fsync,尽量保证数据落盘。 -- 自动轮转:当当前文件大小 + 待写入字节数 超过 `maxFileSize` 时,会自增序号并切换到新文件(sequence)。 -- 自动按行轮转:当单个数据文件累计达到 `maxFileLines` 行后,下一条写入会自动切换到下一个 sequence 文件,默认阈值为 `2000` 行。 -- 目录结构:默认 baseDir 下按业务与日期分区: - - baseDir////
    / -- 文件命名:文件前缀包含业务段与进程标识(`---p-`),尾部带序号与扩展名(`fileExtension`,默认 `.log`)。 -- 进度(.progress)断点续传:每个消费者使用独立的隐藏进度文件(以 `..progress` 命名),写入采用临时文件+rename 的原子替换策略,消费端可通过进度恢复消费位置。 -- Worker/进程隔离:写入文件名包含 `machineId`、`workerId` 与 `pid`,不同进程不会写入同一文件,避免互相竞争。 -- 清理策略:基于 `retentionDays` 定期删除过期的数据文件与进度文件。 - -**目录与文件示例** -- 目录:`/path/to/runtime/file-writer/orders/2026/04/09/` -- 数据文件示例:`orders-myhost-worker1-p1234-0001.log` -- 进度文件示例:`.consumer-1.progress`(位于同一分区目录下) - -**配置项说明(config.fileWriter)** -- `baseDir`:基础目录,默认 `path.join(app.baseDir, 'runtime', 'file-writer')`。 -- `maxFileSize`:单文件最大字节数,超过后轮转。支持数字(字节)或带单位字符串(如 `100M`、`1G`)。默认 `100 * 1024 * 1024`(100MB)。 -- `maxFileLines`:单文件最大行数,达到后下一条写入会自动轮转到新的 sequence 文件。默认 `2000`。 -- `retentionDays`:保留天数,超过则删除。设为 `0` 或负值可禁用清理。默认 `7`。 -- `cleanupIntervalMs`:触发清理的最小间隔(毫秒),写入时会基于此决定是否执行清理,设置为 `0` 或负值可禁用定期清理。默认 `3600000`(1 小时)。 -- `sequenceWidth`:文件序号宽度(零填充),默认 `4`(例如 `0001`)。 -- `fileExtension`:数据文件扩展名,默认 `.log`。 -- `progressExtension`:进度文件扩展名,默认 `.progress`。 -- `machineId`、`workerId`(可选):可通过配置覆盖,默认使用主机名与 `process.env.EGG_WORKER_ID`。 - -默认配置位置:`config/config.default.js` 的 `config.fileWriter` 节点。 - -示例(可放入 `config/config.local.js` 覆盖默认): - -```js -const path = require('path'); - -exports.fileWriter = { - baseDir: path.join(__dirname, '..', 'runtime', 'file-writer'), - maxFileSize: '200M', - maxFileLines: 2000, - retentionDays: 14, - cleanupIntervalMs: 60 * 60 * 1000, - sequenceWidth: 4, - fileExtension: '.log', - progressExtension: '.progress', - // machineId: 'my-host', - // workerId: 'worker-1', -}; -``` - -**写入示例(业务侧)** -简单写入(在任何可以访问 `app` 的位置): - -```js -// 在 controller/service 中 -await app.fileWriter.write('orders', { id: 123, event: 'created', payload: { /* ... */ } }); -// 返回对象包含 filePath、sequence、bytesWritten 等信息 -``` - -**消费/读取示例(推荐使用 app.fileWriter 提供的 API)** -推荐使用 `getProgressFilePath` + `consumeFiles` 提供的断点续传能力: - -```js -// 示例:定期或守护进程式消费 orders -async function consumeOrders(app) { - const writer = app.fileWriter; - const progressFile = writer.getProgressFilePath('orders', new Date(), 'order-consumer-1'); - - const result = await writer.consumeFiles({ - businessName: 'orders', - progressFilePath: progressFile, - onRecord: async (record, meta) => { - // record: 解析后的对象 - // meta: { filePath, offset, index } - // 在这里实现消息处理逻辑(去重、入库、调用外部服务等) - }, - parseJson: true, - }); - - return result; // 包含 processedCount 与最新 progress -} -``` - -如需逐文件手动控制消费,也可使用 `readRecords`: - -```js -const res = await app.fileWriter.readRecords(filePath, { startOffset: 0 }); -for (const rec of res.records) { - // 处理 rec -} -// 手动保存进度 -await app.fileWriter.saveProgress(progressFilePath, { - filePath, - offset: res.nextOffset, - processedCount: (previousCount || 0) + res.records.length, -}); -``` - -**进度文件(.progress)格式** -- 保存为 JSON,包含至少字段:`filePath`、`offset`、`processedCount`、`updatedAt`。 -- 写入采用临时文件写入 + `fsync` + `rename` 的方式尽量保证原子性。 - -**注意事项 / 运行时建议** -- 不要通过静态文件服务或外部 URL 直接暴露 `baseDir`(例如 `runtime/`),避免被外部下载或篡改。 -- 多 Worker / 多机部署: - - 默认每个进程生成独立的数据文件(文件名包含 `machineId`、`workerId`、`pid`),不会有多个进程同时写入同一文件。若你的设计需要跨进程全局严格顺序,请在上游统一入口合并写入或使用集中式队列(如 Kafka/Redis)。 - - 消费者可以按进程拆分(针对单进程的文件)或由独立中心消费者按文件目录遍历处理。 - - 可通过配置显式设置 `machineId`/`workerId` 来标识不同实例。 -- 关闭或调整清理策略:若需长期保留数据,请将 `retentionDays` 设为合适值或禁用清理(`0` 或负值)。 -- 性能角度:每次写入触发 fsync 会有性能开销,适合需要高可靠性的场景;若对持久性要求不高,可考虑将写入逻辑改为批量 fsync(此处为实现约束,不建议直接修改核心行为)。 - ---- - -如果希望在项目首页或工具箱中添加跳转链接,建议把一行链接加入到 [README.md](README.md) 或 [AI_TOOLBOX.md](AI_TOOLBOX.md) 的相关位置,指向本文件 `docs/file-writer.md`。 - ----- -**参考实现位置** -- 代码实现:app/lib/file_writer.js -- 默认配置:config/config.default.js -> `config.fileWriter` diff --git a/docs/notification-event-api.md b/docs/notification-event-api.md deleted file mode 100644 index dee3609..0000000 --- a/docs/notification-event-api.md +++ /dev/null @@ -1,255 +0,0 @@ -# 消息通知事件 API 文档(独立于 system) - -## 1. 文档说明 - -本文档描述 **WMS 对外消息通知能力** 的事件 API 约定。 - -特点: - -- **独立于 `/system` 接口** -- 不走 `method=xxx` 的 system 调用方式 -- 由内部业务在关键节点触发 `event` -- 通过 WebHook 向外部系统推送标准 JSON 消息 - -当前已落地事件: - -- `receiving_completed`:收货完成通知 -- `order_cancel_intercepted`:订单取消失败并触发拦截执行通知 -- `store_warehouse_print_quantity_adjusted`:货主面单余额人工调整通知 - ---- - -## 2. 触发方式 - -内部业务在以下位置触发: - -- 文件:`app/service/systems/storage/receiving.js` -- 方法:`completeReceiving()` -- 通知方法:`sendCompletionNotice()` - -触发时机: - -1. 收货单状态更新为 `completed` -2. 收货完成 Excel 报表上传成功或已生成完成结果 -3. 调用: - -```js -await ctx.service.systems.notice.send({ - businessName: 'receiving', - event: 'receiving_completed', - ... -}) -``` - ---- - -## 3. 事件命名规则 - -本能力中,**事件名本身就是通知方法标识**。 - -示例: - -| event | 含义 | -|---|---| -| `receiving_completed` | 收货单完成通知 | -| `order_cancel_intercepted` | 订单取消失败并触发拦截执行通知 | -| `store_warehouse_print_quantity_adjusted` | 货主面单余额人工调整通知 | - -> 当前正式注册的业务事件包括 `receiving_completed`、`order_cancel_intercepted`、`store_warehouse_print_quantity_adjusted`。 - -对于外部订阅方来说,判断消息类型时,优先看: - -- `event` -- `businessName` -- `message.type` - -命名约束: - -- 仅允许小写字母、数字、下划线 -- 首字符不能为数字 -- **禁止使用 `.`** - ---- - -## 4. 当前已落地事件:`receiving_completed` - -### 4.1 业务含义 - -当仓库完成一张收货单时,系统会向绑定的 WebHook 推送一条 `receiving_completed` 通知。 - -### 4.2 推送目标 - -由 `wms_notification_webhook` 决定: - -- 先匹配仓库 `warehouseId` 绑定的接口 -- 若传了 `storeId / ownerId`,再匹配货主绑定的接口 -- `events` 命中以下任一规则即可推送: - - `all` - - `*` - - `receiving_completed` - ---- - -## 5. 请求方式 - -对外固定使用: - -```http -POST -Content-Type: application/json -``` - ---- - -## 6. 收货完成通知 payload - -### 6.1 字段说明 - -| 字段 | 类型 | 说明 | -|---|---|---| -| `traceId` | `string` | 通知追踪 ID | -| `event` | `string` | 固定为 `receiving_completed` | -| `businessName` | `string` | 固定为 `receiving` | -| `warehouseId` | `number` | 仓库 ID | -| `storeId` | `number \| null` | 货主 ID,可为空 | -| `businessId` | `number` | 收货单 ID | -| `occurredAt` | `string` | 发生时间,ISO 格式 | -| `subject` | `object` | 当前主体(仓库) | -| `store` | `object` | 货主信息 | -| `sender` | `object` | 操作人信息 | -| `receivers` | `array` | 接收者占位 | -| `message` | `object` | 消息主体 | -| `metadata` | `object` | 业务扩展信息 | - -### 6.2 示例(带完成报表) - -```json -{ - "traceId": "notice_1775368780099_c6fb8643", - "event": "receiving_completed", - "businessName": "receiving", - "warehouseId": 100000, - "storeId": 200000, - "businessId": 12345, - "occurredAt": "2026-04-05T12:00:00.000Z", - "subject": { - "id": 100000, - "type": "warehouse", - "name": "广州仓", - "code": "", - "config": { - "max_notice_webhook_count": 5, - "default_express_code": "STO", - "default_platform_code": "TB" - } - }, - "store": { - "id": 200000, - "name": "某货主", - "businessLicense": "9144XXXXXXXXXXXX", - "storeRemask": "华南货主" - }, - "sender": { - "id": 10001, - "name": "张三" - }, - "receivers": [], - "message": { - "type": "file", - "title": "收货单RCV202604050001已完成", - "content": "收货单RCV202604050001已完成,匹配商品10件,未匹配商品0件,总数量120,完成人张三。", - "url": "https://cdn.example.com/收货完成_RCV202604050001.xlsx", - "fileName": "收货完成_RCV202604050001.xlsx", - "mimeType": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", - "body": "收货单RCV202604050001已完成,匹配商品10件,未匹配商品0件,总数量120,完成人张三。" - }, - "metadata": { - "receivingId": 12345, - "receivingNumber": "RCV202604050001", - "warehouseId": 100000, - "storeId": 200000, - "stats": { - "total_details": 10, - "matched_details": 10, - "unmatched_details": 0, - "total_quantity": 120 - }, - "completionReport": { - "fileKey": "收货完成_RCV202604050001.xlsx", - "url": "https://cdn.example.com/收货完成_RCV202604050001.xlsx" - } - } -} -``` - ---- - -## 7. 返回值约定 - -针对当前旧回调接口的约定: - -- 返回 `1` = **成功** -- 返回 `0` = **失败** - ---- - -## 8. 当前可信结论 - -已验证: - -- `GET` 调用旧接口地址可返回 `1` -- `POST {}` 可返回 `1` -- 手工最小 probe JSON 可返回 `1` - -因此: - -> 若 `receiving_completed` 的统一通知实际推送触发远端错误,优先判断为 **payload 字段结构差异导致的远端解析异常**。 - ---- - -## 9. 当前已落地事件:`store_warehouse_print_quantity_adjusted` - -### 9.1 业务含义 - -当仓库侧对某个货主签约关系执行人工面单余额调整后,系统会向相关 WebHook 推送一条 `store_warehouse_print_quantity_adjusted` 通知。 - -### 9.2 推送目标 - -由 `wms_notification_webhook` 决定: - -- 匹配签约仓库 `warehouseId` 绑定的接口 -- 若签约中带有 `storeId`,同步匹配货主绑定的接口 -- `events` 命中以下任一规则即可推送: - - `all` - - `*` - - `store_warehouse_print_quantity_adjusted` - -### 9.3 metadata 关键字段 - -| 字段 | 类型 | 说明 | -|---|---|---| -| `contractId` | `number` | 签约关系 ID | -| `changeType` | `string` | 当前固定为 `manual_adjust` | -| `businessType` | `string \| null` | 业务类型预留字段 | -| `businessId` | `number \| null` | 业务关联 ID,预留给 `wms_order_express.id` | -| `changeQuantity` | `number` | 本次调整值,整数,可正可负 | -| `balanceBefore` | `number` | 调整前余额 | -| `balanceAfter` | `number` | 调整后余额 | -| `reason` | `string` | 调整缘由 | - ---- - -## 10. 后续事件扩展建议 - -下一步可继续补充: - -- `receiving_cancelled` -- `order_cancelled` -- `stock_low` -- `stock_changed` -- `entry_order_created` -- `entry_order_completed` - -保持原则: - -> **一个业务事件 = 一个对外通知 event** diff --git a/docs/notification-webhook-capability.md b/docs/notification-webhook-capability.md deleted file mode 100644 index 3b235f3..0000000 --- a/docs/notification-webhook-capability.md +++ /dev/null @@ -1,335 +0,0 @@ -# 统一消息通知能力文档(草案) - -## 1. 目标 - -用于沉淀 WMS 统一消息通知能力的接口结构、数据模型、事件订阅规则与对外推送格式,作为后续构建“消息通知中心 / WebHook 能力”的基础文档。 - ---- - -## 2. 能力结构 - -当前统一发送入口: - -```js -await ctx.service.systems.notice.send(options) -``` - -当前调用链: - -```text -业务服务 - -> ctx.service.systems.notice.send(options) - -> normalizePayload(options) - -> findMatchedWebhooks(payload) - -> GenericWebhookDriver.send({ hook, payload }) - -> POST JSON 到外部 hook_url -``` - -代码位置: - -- `app/service/systems/notice/index.js` -- `app/service/systems/notice/drivers/generic.js` -- `app/model/notification_webhook.js` - ---- - -## 3. 相关数据模型 - -### 3.1 `wms_notification_webhook` - -用于保存主体绑定的外部 WebHook 配置。 - -核心字段: - -| 字段 | 说明 | -|---|---| -| `store_id` | 主体 ID,可绑定到仓库主体或货主主体 | -| `hook_name` | WebHook 名称 | -| `hook_type` | WebHook 类型,当前支持 `customize` / `wecom` | -| `hook_url` | 推送目标地址 | -| `events` | 订阅事件列表 | -| `status` | 状态,`1=启用`,`0=禁用` | -| `remark` | 备注 | - -### 3.2 `wms_store.subject_config` - -用于保存主体级通知配置。 - -当前已使用字段: - -| 字段 | 说明 | -|---|---| -| `max_notice_webhook_count` | 当前主体最多允许绑定 / 触达的消息推送接口数量,默认 `5` | -| `default_express_code` | 默认快递编码,默认 `STO` | -| `default_platform_code` | 默认平台编码,默认 `TB` | - ---- - -## 4. 事件能力结构建议(独立于 `/system`) - -当前更推荐的能力组织方式是:**内部业务事件 = 对外通知方法标识**,而不是先对外包装成 `/system` method。 - -推荐结构: - -```text -系统内部业务事件 - -> ctx.service.systems.notice.send(options) - -> payload 归一化 - -> 查找匹配的 webhook - -> 按 hook_type 选择 driver - -> 推送到外部系统 -``` - -当前已落地示例: - -| event | 说明 | -|---|---| -| `receiving_completed` | 收货单完成通知 | -| `order_cancel_intercepted` | 订单取消失败并触发拦截执行的通知 | - -> 当前正式注册的业务事件包括 `receiving_completed`、`order_cancel_intercepted`;`all` / `*` 作为通配订阅值继续保留。收货完成事件的独立 API 文档见:`docs/notification-event-api.md`。 - ---- - -## 5. 对内统一发送入参 - -`notice.send(options)` 推荐入参如下: - -| 参数 | 类型 | 必填 | 说明 | -|---|---|---:|---| -| `warehouseId` | `number` | 是 | 仓库 ID | -| `storeId` | `number` | 否 | 货主 ID,可空 | -| `ownerId` | `number` | 否 | 货主 ID 别名,可空 | -| `businessName` | `string` | 是 | 业务名称,如 `receiving` | -| `event` | `string` | 否 | 具体事件,如 `receiving_completed` | -| `messageType` | `string` | 是 | `text / image / file`,兼容中文 | -| `title` | `string` | 否 | 消息标题 | -| `content` | `string/object` | 否 | 消息正文 | -| `url` | `string` | 条件必填 | 图片 / 文件类型时必填 | -| `businessId` | `number|string` | 否 | 业务单据 ID | -| `subject` | `object` | 否 | 主体信息 | -| `sender` | `object` | 否 | 发送者信息 | -| `receivers` | `array` | 否 | 接收者信息 | -| `metadata` | `object` | 否 | 扩展元数据 | - -### 5.1 入参约束 - -- `warehouseId` **必传** -- `storeId / ownerId` **允许为空** -- `messageType = image / file` 时,`url` **必填** -- `event` 命名仅允许小写字母、数字、下划线,且首字符不能为数字;**禁止使用 `.`** - ---- - -## 6. 对外统一推送 payload - -当前对外固定为:`POST + application/json` - -示例: - -```json -{ - "traceId": "notice_xxx", - "event": "receiving_completed", - "businessName": "receiving", - "warehouseId": 100000, - "storeId": 200000, - "businessId": 123, - "occurredAt": "2026-04-05T12:00:00.000Z", - "subject": { - "id": 100000, - "type": "warehouse", - "name": "广州仓", - "code": "", - "config": { - "max_notice_webhook_count": 5, - "default_express_code": "STO", - "default_platform_code": "TB" - } - }, - "store": { - "id": 200000, - "name": "某货主", - "businessLicense": "9144XXXXXXXXXXXX", - "storeRemask": "华南货主" - }, - "sender": {}, - "receivers": [], - "message": { - "type": "text", - "title": "收货完成", - "content": "收货单已完成", - "url": "", - "fileName": "", - "mimeType": "", - "body": "收货单已完成" - }, - "metadata": { - "source": "system" - } -} -``` - ---- - -## 7. 事件订阅规则 - -`events` 字段建议使用数组。 - -支持写法: - -| 写法 | 含义 | -|---|---| -| `all` | 接收全部已注册通知 | -| `*` | 兼容旧配置,等价于 `all` | -| `receiving_completed` | 只接收收货完成事件 | -| `order_cancel_intercepted` | 只接收订单取消拦截事件 | - -> 若需新增其他事件,必须先在 `app/model/notification_webhook.js` 完成注册,否则发送入口会直接拒绝。 - -当前订单取消拦截通知由 `app/service/qimenMethods/order.js` 在拣货状态或打印状态未结束时发送,事件码为 `order_cancel_intercepted`。 - ---- - -## 8. 命中与分发规则 - -当前 `findMatchedWebhooks(payload)` 逻辑: - -1. 先判断 `warehouseId`,并查询该仓库主体绑定的启用接口 -2. 若 `storeId / ownerId` 非空,再查询该货主绑定的启用接口 -3. 过滤条件: - - `status = 1` - - `events` 命中当前消息 -4. 去重规则: - - 优先按 `id` - - 无 `id` 时按 `hook_url` -5. 最终按 `subject_config.max_notice_webhook_count` 限制最大推送数量 - ---- - -## 9. 货主信息补充与缓存 - -若传了 `storeId / ownerId`,当前会补齐货主信息: - -- `wms_store.business_license` -- `wms_store_warehouse.store_remask` - -缓存键: - -```text -warehouse:{warehouseId}store:{storeId}:info -``` - -缓存 TTL: - -```text -600 秒 -``` - -查询顺序: - -1. 优先读缓存 -2. 缓存未命中再查数据库 -3. 查到后回填缓存 -4. 若为空,则推送字段也保持空字符串 - ---- - -## 10. 回调返回值约定 - -对于现有旧接口(如 `notic`、`notic2`)的可信判定约定: - -- 返回 `1` = **成功** -- 返回 `0` = **失败** - ---- - -## 11. 当前可信结论 - -已验证: - -- `GET` 请求可通 -- `POST` 请求可通 -- `POST {}` 可返回 `1` -- 手工最小 probe payload 可返回 `1` - -因此: - -> 若统一 `notice.send()` 的实际推送触发远端报错,优先判断为 **payload 字段结构差异导致的远端解析问题**,而不是地址或请求方式问题。 - ---- - -## 12. 新增功能需要通知时怎么接入 - -当其他功能模块需要新增通知时,建议按下面 4 步接入,避免各自重复造轮子: - -### 12.1 注册事件 - -先在 `app/model/notification_webhook.js` 的 `AVAILABLE_EVENTS` 中登记新的事件编码。 - -要求: - -- 事件名仅允许小写字母、数字、下划线 -- 首字符不能为数字 -- **禁止使用 `.`** -- 未注册的事件,`notice.send()` 会直接拒绝发送 - -### 12.2 在业务 service 调用统一入口 - -在实际业务 service 中调用: - -```js -await ctx.service.systems.notice.send({ - warehouseId, - storeId, // 可选,也可传 ownerId - businessName: 'your_business', - event: 'your_event_code', - messageType: 'text', - title: '通知标题', - content: '通知内容', - businessId, - subject, - sender, - metadata, -}); -``` - -接入原则: - -- `warehouseId` 必传,`storeId / ownerId` 可空 -- 业务侧只负责组装业务语义并调用统一入口 -- 重试、分发、失败日志由 `app/service/systems/notice/index.js` 统一处理 -- 如需图片 / 文件通知,补充 `url`、`fileName`、`mimeType` - -### 12.3 测试验证 - -至少补 2 类验证: - -1. **notice 能力测试**:确认事件注册、WebHook 命中、payload 结构与失败处理符合预期 - - 参考:`test/app/service/systems/notice.test.js` -2. **业务回归测试**:确认业务节点确实会触发通知调用 - - 参考:`test/app/service/systems/storage.receiving.report.test.js` - -若对接的是外部地址,还应额外确认: - -- 返回结果是否符合成功约定(如 `1` / `ok` / `errcode=0`) -- 对方是否能正确解析当前 JSON payload - -### 12.4 文档同步 - -接入完成后,至少同步以下文档: - -- 本文档:补能力边界、接入规则或命中说明 -- `docs/notification-event-api.md`:新增事件说明与 payload 示例 -- 若对外暴露了新的 `/system` 接口或 method,再按需同步 `methods/*.json` - -## 13. 后续扩展建议 - -建议后续继续补充: - -1. 通知发送日志表 -2. 重试队列 / 死信队列 -3. 回调签名与鉴权 -4. WebHook 健康检查 -5. 失败告警与监控面板 -6. system 接口文档同步到 `methods/system.json` diff --git a/docs/order-cancel-db-checklist.md b/docs/order-cancel-db-checklist.md deleted file mode 100644 index d71f579..0000000 --- a/docs/order-cancel-db-checklist.md +++ /dev/null @@ -1,97 +0,0 @@ -# 订单取消 / 状态机 — 库表核对清单(§0.7 执行用) - -> 用途:实施 `order_todo.md` **§2.3a(取消进 M4)** 前,对 **`wms_order_delivery` 及分表** 做只读核对。 -> 不改变数据库;核对结果记录在工单或 `order_todo.md` 修订记录。 - -**PowerShell 提示**:`db-query.ps1` 若遇 **`ConvertFrom-Json` 无效 JSON**(中文注释导致编码问题),可在同一会话先执行 **`chcp 65001`** 再跑查询。 - -## 1. 列出本库所有发货单相关表 - -```sql -SELECT TABLE_NAME -FROM INFORMATION_SCHEMA.TABLES -WHERE TABLE_SCHEMA = DATABASE() - AND ( - TABLE_NAME = 'wms_order_delivery' - OR TABLE_NAME REGEXP '^wms_order_delivery_[0-9]+(_history)?$' - ) -ORDER BY TABLE_NAME; -``` - -## 2. 对每张表核对关键列是否存在 - -将 `YOUR_TABLE` 替换为上一步的表名(含模板表 `wms_order_delivery` 与各仓 `wms_order_delivery_{wh}` / `_history`)。 - -```sql -SELECT COLUMN_NAME, DATA_TYPE, COLUMN_TYPE, IS_NULLABLE, COLUMN_COMMENT -FROM INFORMATION_SCHEMA.COLUMNS -WHERE TABLE_SCHEMA = DATABASE() - AND TABLE_NAME = 'YOUR_TABLE' - AND COLUMN_NAME IN ( - 'status', - 'intercept_status', - 'step', - 'outbound_status', - 'inspection_status', - 'delivery_time', - 'updated_at', - 'create_at' - ) -ORDER BY COLUMN_NAME; -``` - -## 3. 结论填写(人工) - -| 检查项 | 是否满足「取消进 M4」筛选与展示 | -|--------|----------------------------------| -| `status` 含 `cancel` 枚举(与 ORM 一致) | | -| `intercept_status` 含 `cancelled` 等 | | -| `step` 存在且含「9=已关闭」语义 | | -| 若产品要求 **独立「取消进 M4」列** | 缺则走 migration + 模型 + 工厂 DDL | - -## 4. 参考 - -- 模型枚举源:`app/model/order_delivery.js`(`StatusEnum`、`step` 注释) -- 规划说明:仓库根目录 `order_todo.md` §0.7、§2.3a - ---- - -## 5. wms-db-agent 诊断记录(本机一次抽样,2026-04-10) - -> 工具:`script/db-query.ps1`,client **`wms`**,`DATABASE() = wms`。以下为 **只读** 结果摘要;其它环境须自行重跑 §1~§2。 - -### 5.1 匹配到的表 - -| TABLE_NAME | -|------------| -| `wms_order_delivery`(基表/模板) | -| `wms_order_delivery_100000` | -| `wms_order_delivery_1000028` | - -本库本次 **未发现** `*_history` 表。 - -### 5.2 目标列是否存在(Y/N) - -| TABLE_NAME | status | intercept_status | step | outbound_status | inspection_status | -|------------|:------:|:----------------:|:----:|:---------------:|:-----------------:| -| `wms_order_delivery` | Y | **N** | Y | **N** | **N** | -| `wms_order_delivery_100000` | Y | Y | Y | Y | Y | -| `wms_order_delivery_1000028` | Y | Y | Y | Y | Y | - -`delivery_time` / `updated_at` / `create_at` 三张表均有(基表 `updated_at`/`create_at` 为 YES)。 - -### 5.3 与 §0.7 / §2.3a 的对照结论 - -- **分表**(`_100000`、`_1000028`):§0.7 所列 **`status` / `intercept_status` / `step` / `outbound_status` / `inspection_status`** 均存在;`intercept_status` 含 **`cancelled`**,`status` 含 **`cancel`**;**可先不增列**,用组合条件做「取消进 M4」筛选(产品确认 WHERE 口径即可)。 -- **基表** `wms_order_delivery`:**缺** `intercept_status`、`outbound_status`、`inspection_status`;**业务筛选勿依赖基表**,以 **`wms_order_delivery_{warehouseId}`** 为准。 -- **枚举差异**:不同物理表上 **`status` 的 enum 集合不一致**(基表与分表、分表之间均有差异);规则与迁移须 **按仓/按表** 评估,勿假设全局一致。 -- **全量**:当前仅抽样 2 张分表;生产请对 **全部** `wms_order_delivery_*` 重跑本清单;若有 **`_history`** 须单独对齐列集。 - -### 5.4 §3 结论栏(代填,可改) - -| 检查项 | 是否满足「取消进 M4」筛选与展示 | -|--------|----------------------------------| -| `status` 含 `cancel` 枚举(与 ORM 一致) | **分表:是**;基表:部分(见上 enum 差异) | -| `intercept_status` 含 `cancelled` 等 | **分表:是**;**基表:无此列** | -| `step` 存在且含「9=已关闭」语义 | **是**(int NOT NULL,注释一致) | -| 若产品要求 **独立「取消进 M4」列** | **未检出有**;若需要仍须 migration(见 `order-delivery-migration-impact.md`) | diff --git a/docs/order-delivery-migration-impact.md b/docs/order-delivery-migration-impact.md deleted file mode 100644 index d2ebf79..0000000 --- a/docs/order-delivery-migration-impact.md +++ /dev/null @@ -1,62 +0,0 @@ -# `wms_order_delivery*` / `wms_order_items*` 库表变更 — 影响面分析(供决策) - -> 目的:回答「改库是否影响当前所有涉及 order 发货单表的逻辑」;**未连真实库**,结论基于代码静态分析。 -> 关联:`order_todo.md` §0.7、§2.3a;核对清单 `docs/order-cancel-db-checklist.md`。 - ---- - -## 1. 结论摘要(是否可直接做迁移) - -| 变更类型 | 对现有逻辑的典型影响 | 建议 | -|----------|----------------------|------| -| **仅核对列已存在、不做 DDL** | 无 | **推荐先做**(清单 `order-cancel-db-checklist.md`) | -| **新增可空列 + 默认值**(`NULL` 默认 / `DEFAULT`) | Sequelize `create`/`update`/`find` 一般 **不崩**;未赋值的 `create` 不写该列则用库默认 | **低面影响**,但仍须 **同步** `app/model/order_delivery.js` + `order_delivery_factory.js` 的 `createPhysicalTable` DDL,且 **所有已存在分表** 需同一 migration 补列 | -| **新增 NOT NULL 无默认** | 旧 `create`/`bulkCreate` 可能 **插入失败** | **高面影响**,**禁止**在未改全链路前做 | -| **改 ENUM 取值 / 删列 / 改列类型** | `order.*` 列表 where、奇门/入库、报表可能 **全链路受影响** | **高面影响**,须单独评审与回归 | -| **仅改索引 / 注释**(不改列语义) | 一般低;大表加索引注意锁表 | 可个案评估 | - -**当前结论(在未跑 §0.7 清单、未选定「取消进 M4」专用列名之前):** -**不在仓库内自动提交新的 `ALTER` migration。** 代码侧已具备 `status.cancel`、`intercept_status.cancelled`、`step`(含 9 关闭)等枚举(见 `order-state-machine-dictionary.md`),**若跑库确认列已齐全,则「取消进 M4」可先不增列,仅做应用筛选逻辑** — 此时 **无需表迁移**。 -若跑库确认 **缺列** 或产品 **强制** 要独立标记列 → **属有面影响变更**,请在你确认 **列名、类型、默认值、是否只加 current 或含 history** 后再做 migration。 - -**(已更新)** 本机 `wms` 库经 **wms-db-agent** 只读抽样结果见 **`docs/order-cancel-db-checklist.md` §5**:两张分表目标列齐全,**可先不增列**;基表缺列、勿作业务筛选;全量仓与 `_history` 须另跑。 - ---- - -## 2. 代码侧「会吃到表结构」的路径 - -### 2.1 动态模型来源(关键) - -- `OrderDeliveryFactory` / `OrderItemsFactory` 使用 **`app.model.OrderDelivery.rawAttributes`**(及 `OrderItems`)**动态 `define` 每张分表**。 -- **新建物理表**时,`createPhysicalTable` 内 **手写 DDL 片段** 与模型字段 **必须长期一致**,否则新仓新表与 ORM 不一致。 - -### 2.2 业务入口(非穷举,均为 `getCurrentModel` 链) - -| 区域 | 文件 | -|------|------| -| System 订单 method | `app/service/systemMethods/order/*.js`(经 `base.js#getOrderModels`) | -| 业务发货单 | `app/service/systems/delivery_order.js`(`create` / `update` / `bulkCreate` 明细等) | -| 奇门 | `app/service/qimenMethods/deliveryorder.js` | -| 测试 / 探针 | `app/service/apiMethods/test.js`(命名 `WmsOrderDeliveryFactory` 需与挂载一致,否则仅测试路径) | - -### 2.3 写入方式 - -- `DeliveryModel.create(orderData)`、`OrderItemsModel.bulkCreate(lineData)`:**对象字段驱动**;新增 **可空** 列且模型已声明时,旧代码路径 **通常无需改** 即可插入。 - ---- - -## 3. 若你决定「要做加列迁移」时的必做清单 - -1. 产品确认:**列名、含义、是否可空、默认值、是否写 history 表**。 -2. Migration:`findOrderDeliveryTables` 风格 **遍历** `wms_order_delivery` / `wms_order_delivery_*`(及若需要则 `wms_order_items_*`)。 -3. `app/model/order_delivery.js` 增加字段定义。 -4. `app/model/order_delivery_factory.js` 中 **`createPhysicalTable`** 同步列定义。 -5. 回归:`npm run test:local` 中与 `delivery_order` / `order` 相关用例;奇门若有联调则单独测。 - ---- - -## 4. 修订 - -| 日期 | 说明 | -|------|------| -| 2026-04-10 | 初版:静态影响面结论;**未提交 migration** | diff --git a/docs/order-state-machine-dictionary.md b/docs/order-state-machine-dictionary.md deleted file mode 100644 index 658ef31..0000000 --- a/docs/order-state-machine-dictionary.md +++ /dev/null @@ -1,45 +0,0 @@ -# 订单发货单 — 状态机字段字典(骨架 v0) - -> **单一事实来源(代码)**:`app/model/order_delivery.js` 内 `StatusEnum` 与 `step` 定义。 -> 本文档为 **v0 骨架**:便于产品 / 数仓 / 报表对齐;**与数仓字段映射、变更登记** 在后续迭代补全(见 `order_todo.md` §5.2)。 - -## 1. 主状态与步骤 - -| 字段 | 类型(ORM) | 枚举或取值 | 说明(摘自模型注释) | -|------|-------------|------------|----------------------| -| `status` | ENUM | `pedding`, `created`, `cancel`, `error` | 订单状态 | -| `step` | INTEGER | `0` 未审核,`1` 已审核,`2` 处理中,`3` 驳回/异常,`4` 配送中,`5` 已完成,`9` 已关闭 | 订单步骤 | - -## 2. 各环节状态机(ENUM) - -| 字段 | 枚举值 | -|------|--------| -| `sync_status` | `padding`, `fin`, `error` | -| `post_status` | `padding`, `fin`, `timeout`, `error`, `none` | -| `storage_status` | `padding`, `fin`, `error`, `none` | -| `pick_status` | `padding`, `fin`, `error`, `none` | -| `pack_status` | `none`, `padding`, `fin`, `error` | -| `inspection_status` | `none`, `padding`, `running`, `fin`, `error` | -| `print_status` | `none`, `padding`, `fin`, `error` | -| `claim_status` | `none`, `padding`, `fin`, `error` | -| `outbound_status` | `none`, `padding`, `fin`, `error` | -| `lock_status` | `none`, `warehouse`, `store` | -| `intercept_status` | `none`, `requesting`, `requested`, `intercepting`, `intercepted_in_transit`, `intercepted_at_warehouse`, `returning`, `returned`, `delivered_by_mistake`, `timeout`, **`cancelled`**, `failed`, `exception` | - -## 3. 其它与展示相关(非 ENUM) - -| 字段 | 说明 | -|------|------| -| `delivery_time` | 发货时间;与 M6 出库时间策略相关 | -| `create_at` / `updated_at` | 创建 / 更新时间 | - -## 4. 待产品补充(v1+) - -- 「取消进 M4」专用标记:若不用 `status`/`step`/`intercept_status` 组合表达,则 **新增列** 后的字典条目与数仓同步表。 -- 与奇门 **不同步** 的克隆续单字段(见 `order_todo.md` §2.4)。 - -## 5. 修订 - -| 版本 | 说明 | -|------|------| -| v0 | 自 `order_delivery.js` 摘录枚举骨架,无 DB 变更 | diff --git a/docs/order-workbench-list-api.md b/docs/order-workbench-list-api.md deleted file mode 100644 index 7b99c0a..0000000 --- a/docs/order-workbench-list-api.md +++ /dev/null @@ -1,188 +0,0 @@ -# 订单工作台 List 接口说明 - -本文档说明订单工作台(Order Workbench)中可用的 list 接口、参数约定、返回结构与行为要点。 - -**变更记录** -- 本次已在 methods/system.json 中补充以下 method 定义,并在 methods/changes/system.json 中追加变更记录(参见变更文件),用于对外说明新增的 list 接口与分页/where 支持。 - -**新增/确认的接口(method 名称,主入口)** -- order.list —— 订单工作台总列表入口(汇总所有分组) -- order.reviewOrder.list —— 待审核订单工作台(step=0) -- order.pendingOrder.list —— 待处理订单工作台(step in [1,2]) -- order.expectionOrder.list —— 待处理异常订单工作台(step=3) -- order.entrustOrder.list —— 委托外仓订单工作台(outsourced 模型) -- order.deliveryOrder.list —— 配送订单工作台(dispatch 模型,dispatch_lane=m4) -- order.deliveryExpectionOrder.list —— 配送异常订单工作台(dispatch 模型,dispatch_lane=m5) -- order.archiveOrder.list —— 归档订单工作台(history 模型) - -兼容说明:代码中存在若干旧兼容入口(例如 getreviewOrderlist、getdeliveryOrderlist、getpendingOrderlist、getexpectionOrderlist、getentrustOrderlist、getarchiveOrderlist 等),这些为兼容旧调用保留的旧名入口,不作为首选主入口;建议新调用使用上文列出的主入口。 - -**工作台语义(简要)** -- order.list:总列表入口,返回跨分组的订单集合,适用于需要不分组的通用搜索/分页场景。 -- reviewOrder:待审核(审核步骤为未审核)工作台,用于审核操作筛选与展示(默认 step=0)。审核提交接口仅接收 ids,批量审核,严格同仓校验,不做兼容。 -- pendingOrder:待处理工作台,通常包含需要人工或系统继续处理的订单(默认 step in [1,2])。 -- expectionOrder:异常工单集合(默认 step=3),用于定位异常状态订单。 -- entrustOrder:委托外仓相关订单,使用 outsourced 模型。 -- deliveryOrder / deliveryExpectionOrder:配送相关工作台,使用 dispatch 模型,分别以 dispatch_lane=m4 / m5 筛选。 -- archiveOrder:归档历史订单,使用 history 模型。 - -实现要点(参考实现位于 app/service/systemMethods/order/*): -- 模块实现会根据模块名选择不同物理模型(current / dispatch / outsourced / history),由 OrderBaseService#getOrderModel 决定。 -- 每个模块还定义了 `defaultWhere`(例如 reviewOrder 的 step=0 等),请求的 `where` 会与模块默认条件合并后一起用于构造最终查询。 - -参数说明(公共约定) -- pagination: object - - pagination.page: number(可选),页码,从 1 开始,默认 1。 - - pagination.pageSize: number(可选),每页条数,默认 20。注意:服务端对 pageSize 做上限截断,最大不可超过 200(见下)。 -- where: object(可选) - - 统一的筛选条件对象;支持两种写法: - - 标准化结构:{ field: { operator: 'eq'|'in'|'like'|..., value: ..., type?: 'string'|'number' } } - - 简写:{ field: value }(会被自动转换为 { operator: 'eq', value } 或在传数组时转换为 in) - - 服务端会先对 where 做 normalize(兼容简写与 values 字段),再走 parseWhereConditions 生成底层查询条件,最后与模块的 defaultWhere 合并(后者优先级低于请求入参)。 - - 常见可用字段:id、delivery_order_code、order_status、dispatch_lane、quickWhere 等(具体过滤字段以实现解析器支持为准)。 -- sort: object(可选) - - 支持 sortField / sortOrder 或 field / order;实现层会映射到允许的字段集合(如 id、step、status、delivery_time、updated_at 等),默认按 updated_at DESC, id DESC。 - -分页/大小限制 -- 默认 pageSize=20。 -- 最大 pageSize: 200(服务端在 normalizePagination 中对 pageSize 做截断,防止单次请求返回过大数据)。调用方仍应合理控制 pageSize,避免前端一次性请求过多数据。 - -返回结构(公共约定) -- list: array — 当前页的记录数组(每项为订单对象的序列化行,字段视具体模型与序列化而定)。 -- pagination: object - - pagination.page: number — 当前页 - - pagination.pageSize: number — 每页条数(实际返回值为服务端截断后的值) - - pagination.total: number — 符合条件的总记录数 - - pagination.totalPages: number - - pagination.hasPrevious / hasNext: boolean - -订单列表 raw 字段字典(通用) -- 说明:以下字段为所有订单列表的 raw 基础字段;`order.deliveryOrder.list` 和 `order.deliveryExpectionOrder.list` 额外包含 `dispatch_lane`;服务层还会补充 `express_numbers` 与 `waybill_codes` 两个派生字段,二者内容一致,都是该订单绑定的多个快递号。 - -| 字段 | 类型 | 中文语义 | 枚举/说明 | -| --- | --- | --- | --- | -| id | number | 订单主键 ID | 订单记录主键 | -| delivery_order_code | string | 发货单号 | 订单单号 | -| pre_delivery_order_code | string | 预发货单号 | 预发货阶段单号 | -| pre_delivery_order_id | string | 预发货单ID | 预发货记录关联 ID | -| order_type | string | 订单类型 | 业务类型标识 | -| warehouse_code | string | 仓库编码 | 仓库基础编码 | -| order_flag | string | 订单标记 | 订单标签/标记信息 | -| source_platform_code | string | 来源平台编码 | 原始平台编码 | -| source_platform_name | string | 来源平台名称 | 原始平台名称 | -| sys_platform_code | string | 系统平台编码 | 系统内平台编码 | -| sys_platform_name | string | 系统平台名称 | 系统内平台名称 | -| create_at | string | 创建时间 | ISO 时间字符串 | -| delete_at | string | 删除时间 | ISO 时间字符串,通常为空 | -| updated_at | string | 更新时间 | ISO 时间字符串 | -| place_order_time | string | 店铺创建订单时间 | 平台下单时间 | -| pay_time | string | 支付时间 | 支付完成时间 | -| pay_no | string | 支付单号 | 支付流水号 | -| service_code | string | 集包服务编码 | 集包/服务编码 | -| operator_name | string | ERP审核人 | 审核人姓名 | -| operate_time | string | ERP审核时间 | 审核时间 | -| delivery_time | string | 发货时间 | 发货完成时间 | -| shop_nick | string | 店铺名称 | 店铺昵称 | -| seller_nick | string | 卖家名称 | 卖家昵称 | -| buyer_nick | string | 买家名称 | 买家昵称 | -| total_amount | number | 订单总金额 | 金额字段,保留两位小数 | -| item_amount | number | 商品总金额 | 金额字段,保留两位小数 | -| discount_amount | number | 订单折扣金额 | 金额字段,保留两位小数 | -| freight | number | 快递费用 | 金额字段,保留两位小数 | -| ar_amount | number | 应收金额 | 金额字段,保留两位小数 | -| got_amount | number | 已收金额 | 金额字段,保留两位小数 | -| service_fee | number | COD服务费 | 金额字段,保留两位小数 | -| logistics_code | string | 物流公司编码 | 物流公司编码 | -| logistics_name | string | 物流公司名称 | 物流公司名称 | -| sys_logistics_code | string | 系统物流公司编码 | 系统内物流编码 | -| sys_logistics_name | string | 系统物流公司名称 | 系统内物流名称 | -| express_code | string | 面单号前置 | 面单号前缀 | -| logistics_area_code | string | 快递区域编码 | 大头笔/区域编码 | -| delivery_type | string | 发货服务类型 | 发货方式 | -| is_urgency | enum | 是否紧急 | Y=是,N=否 | -| invoice_flag | enum | 是否需要发票 | Y=需要,N=不需要 | -| status | enum | 订单状态 | pedding=待处理,created=已创建,cancel=已取消,error=异常 | -| name | string | 收件人姓名 | 收件人 | -| zip_code | string | 收件人邮编 | 邮编 | -| tel | string | 收件人电话 | 电话号码 | -| mobile | string | 收件人移动电话 | 手机号 | -| email | string | 收件人邮箱 | 邮箱 | -| country_code | string | 国家编码 | 国家/地区编码 | -| province | string | 省份 | 收件地址省 | -| city | string | 城市 | 收件地址市 | -| area | string | 区 | 收件地址区 | -| town | string | 镇 | 收件地址镇 | -| detail_address | string | 详细地址 | 街道/门牌详情 | -| id_type | string | 证件类型 | 证件类型 | -| id_number | number | 证件号码 | 证件号 | -| oaid | string | OAID | 设备/终端标识 | -| sync_status | enum | 同步状态 | padding=待同步,fin=完成,error=失败 | -| store_id | number | 货主ID | 货主主键 | -| store_remark | string | 货主备注 | 来自 wms_store_warehouse.store_remask,服务层按 store_id+warehouse_id 聚合填充 | -| warehouse_id | number | 仓库ID | 仓库主键 | -| from_key | number | 来源键 | 来源系统键值 | -| items | string | 商品JSON字符串 | 原始商品明细 JSON | -| items_count | number | 商品种类数 | SKU 种类数 | -| items_total | number | 商品总数 | 商品件数总和 | -| items_weight | number | 总重量(kg) | 总重量 | -| 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=未开始 | -| pack_status | enum | 打包状态机 | none=未开始,padding=处理中,fin=完成,error=失败 | -| inspection_status | enum | 检验状态机 | none=未开始,padding=处理中,running=进行中,fin=完成,error=失败 | -| step | number | 订单步骤 | 0=未审核,1=已审核,2=处理中,3=驳回/异常,4=配送中,5=已完成,9=已关闭 | -| print_status | enum | 打印状态机 | none=未开始,padding=处理中,fin=完成,error=失败 | -| claim_status | enum | 领取状态机 | none=未开始,padding=处理中,fin=完成,error=失败 | -| outbound_status | enum | 出库状态机 | none=未开始,padding=处理中,fin=完成,timeout=超时,error=失败 | -| lock_status | enum | 锁定状态机 | none=未锁定,warehouse=仓库锁定,store=货主锁定 | -| intercept_status | enum | 拦截状态机 | none=未拦截,requesting=请求中,requested=已请求,intercepting=拦截中,intercepted_in_transit=运输中拦截成功,intercepted_at_warehouse=仓库拦截成功,returning=退回中,returned=已退回,delivered_by_mistake=误签收,timeout=超时,cancelled=已取消,failed=失败,exception=异常 | -| dispatch_lane | string | 配送通道/分区 | 仅配送相关列表可能出现,常用于区分 m4 / m5 等通道 | -| express_numbers | array[string] | 快递号列表 | 服务层聚合字段,内容来自 wms_order_express.waybill_code | -| waybill_codes | array[string] | 运单号列表 | 与 express_numbers 内容一致,为兼容前端使用保留 | - -补充说明 -- `express_numbers` 和 `waybill_codes` 都来自订单绑定的多条快递记录,适合前端直接渲染“多个快递号”。 -- `sys_platform_name`、`sys_logistics_name` 已由服务层归一化输出,前端无需再回表查询。 -- `dispatch_lane` 仅在 `order.deliveryOrder.list` / `order.deliveryExpectionOrder.list` 这两个配送类列表中出现;其余列表通常不返回该字段。 - -其他注意事项 -- `where` 的解析与支持的特殊字段由 parseWhereConditions 决定;若需要支持新的复杂筛选(如跨表/聚合条件),请先在解析器和后端模型中确认可支持的 specialFieldMap 与解析策略。 -- 推荐使用标准化 where 结构({ operator, value })以避免歧义;历史简写会被自动规范化,但可读性较差。 -- 兼容入口(get*)保留以兼容历史客户端,但文档与新开发均建议使用上述主入口方法名;兼容入口可能在不同 module 下存在重复实现(index + 子模块),以兼容不同调用路径。 - -方法清单(已在 methods/system.json 中登记) -- order.list -- order.reviewOrder.list -- order.pendingOrder.list -- order.expectionOrder.list -- order.entrustOrder.list -- order.deliveryOrder.list -- order.deliveryExpectionOrder.list -- order.archiveOrder.list - -是否需要补充其它文档同步? -- 建议同步更新: - - 若有门户/前端 API 文档站(自动生成或展示 methods/system.json 的地方),应部署或刷新以展现新增条目。 - - 若存在 SDK 或对接说明(如 qimen 或第三方对接文档),如使用到工作台 list 场景也建议补充示例请求与常用 where 范例。 - -示例请求(简要) - -请求体示例: -{ - "pagination": { "page": 1, "pageSize": 50 }, - "where": { "delivery_order_code": { "operator": "like", "value": "ABC" }, "create_time_start": { "value": "2026-04-01" } }, - "sort": { "sortField": "updated_at", "sortOrder": "DESC" } -} - -响应示例(简要): -{ - "list": [ /* 订单对象数组 */ ], - "pagination": { "page":1, "pageSize":50, "total":1234, "totalPages":25, "hasPrevious":false, "hasNext":true } -} - --- -文档维护者:WMS 文档代理 diff --git a/docs/order_todo.md b/docs/order_todo.md deleted file mode 100644 index e3119ec..0000000 --- a/docs/order_todo.md +++ /dev/null @@ -1,288 +0,0 @@ -# 订单工作台模块 — 规划草案(order_todo) - -> 状态:**计划**,供评审与补充;实现前需与产品、DBA、前端对齐。 -> 关联:`OrderDeliveryFactory` / `OrderItemsFactory`(current / history 物理表)、`order_delivery` / `order_items` 基模型、现有 `order.*` system method。 - ---- - -## 0. 当前订单表、模型、工厂与关联(代码现状分析) - -### 0.1 物理表与工厂命名 - -| 概念 | 物理表名模式 | 说明 | -|------|----------------|------| -| 发货单 current | `wms_order_delivery_{warehouseId}` | 按仓动态建表,`OrderDeliveryFactory.generateTableName(wh, 'current')` | -| 发货单 history | `wms_order_delivery_{warehouseId}_history` | 多 `archive_time` 字段与索引;**业务代码尚未写入/迁移** | -| 订单明细 current | `wms_order_items_{warehouseId}` | `OrderItemsFactory.generateTableName(wh, 'current')` | -| 订单明细 history | `wms_order_items_{warehouseId}_history` | 同上,待迁移任务 | - -基模型 `tableName` 为模板:`wms_order_delivery`、`wms_order_items`(用于 `rawAttributes` 复制到动态表)。 - -### 0.2 基模型 `OrderDelivery`(`app/model/order_delivery.js`) - -- **主键与业务键**:`id`,`delivery_order_code` + `store_id` + `warehouse_id` 唯一索引(动态表工厂内复刻)。 -- **货主 / 仓库**:`store_id`(货主)、`warehouse_id`(仓库);**创建时落 M1/M2 可依据货主(store)侧配置**(配置表/字段待产品定义,当前模型无显式「进审开关」字段)。 -- **状态机字段(枚举在模型内)**:`status`,`sync_status`,`post_status`,`storage_status`,`pick_status`,`pack_status`,`inspection_status`,`print_status`,`claim_status`,`outbound_status`,`lock_status`,`intercept_status`。 -- **业务辅助**:`step`(注释:0 未审核 / 1 已审核 / 2 处理中 / 3 驳回异常 / 4 配送中 / 5 已完成 / 9 已关闭)、`wave_id`、金额与地址收件人、`items`(TEXT JSON 字符串)、`items_hash` / `items_crc` / `items_count` 等。 -- **物流展示相关(主表冗余)**:`logistics_code`、`logistics_name`、`express_code`、`delivery_time` 等;**细粒度快递轨迹**见下文物理表 `wms_order_express`。 - -### 0.3 基模型 `OrderItems`(`app/model/order_items.js`) - -- **关联键**:`order_id` → 发货单 `id`;`item_code`、`item_id`、`stock_id`、`owner_code`、`plan_qty`、价格字段、`extend_props`(JSON)。 -- **索引**:`order_id`、`item_id`、`source_order_code`、`stock_id` 等。 - -动态明细表由工厂 `define` 时复制 `OrderItems.rawAttributes`,并 `copyAssociations` 自基模型。 - -### 0.4 工厂类职责 - -| 工厂 | 文件 | 职责摘要 | -|------|------|----------| -| `OrderDeliveryFactory` | `app/model/order_delivery_factory.js` | `getCurrentModel` / `getHistoryModel` / `getModelByTableName`;不存在则 `createPhysicalTable`;`setupAssociations` 将动态发货单与 **同仓同类型** 动态 `OrderItems` 做 `hasMany` / `belongsTo`;可选 `belongsTo` `Store`(货主/仓库别名) | -| `OrderItemsFactory` | `app/model/order_items_factory.js` | 同上;并发建表锁 `creatingTables`;动态表带 `timestamps: true` | - -**现状**:全仓业务查询路径普遍只调用 **`getCurrentModel`**;**`getHistoryModel` 无业务引用**。 - -### 0.5 其它订单相关物理表(非按仓工厂) - -| 模型 | 表名 | 与订单关系 | -|------|------|--------------| -| `OrderExpress` | `wms_order_express` | `order_id` 关联订单主键;运单、物流接口、星河签收/退回/拦截等标记。**未纳入** `OrderDeliveryFactory` 动态表;若配送域拆分需定义 **order_id 与仓、自然月分区** 的一致性(否则跨表 JOIN 成本高)。 | - -### 0.6 System 层与工厂衔接 - -- `app/service/systemMethods/order/base.js` 中 `getOrderModels(warehouseId)` **仅** `getCurrentModel` 取发货单 + 明细。 -- 列表类:`reviewOrder`、`pendingOrder`、`expectionOrder`、`deliveryOrder`、`archiveOrder` 等均基于上述 **current** 模型。 - -### 0.7 取消相关状态机(代码已有 vs 库表须核对) - -**代码侧(`app/model/order_delivery.js`)已具备、可用于「取消」语义的枚举取值包括:** - -| 位置 | 取值/说明 | -|------|-----------| -| `status` | 枚举含 **`cancel`**(订单状态) | -| `intercept_status` | 枚举含 **`cancelled`** 等拦截/关闭链路 | -| `step` | 整型步骤,注释含 **9 = 已关闭**;近期迁移为各分表补 `step`(见 `database/migrations/20260410150000-replace-audit-status-with-step-on-order-delivery-tables.js`) | - -**实施 §2.3a 前必须执行:** - -0. **核对清单(已产出,小阶段)**:只读 SQL 与步骤见 **`docs/order-cancel-db-checklist.md`**(不在仓库内自动连库执行)。**库表 DDL 变更影响面**见 **`docs/order-delivery-migration-impact.md`**。 -1. **对库**:对 `wms_order_delivery` 及 **`wms_order_delivery_%` 分表** 跑字段清单(`INFORMATION_SCHEMA`),确认 **`status` / `intercept_status` / `step` / `outbound_status`** 等与「取消后进 M4」**筛选用例**是否够用。 -2. **若产品要求独立可辨的「取消进 M4」标记**(例如与 `status=cancel` 但尚未占配送域行的组合区分):**库中无字段则新增**(如 `close_channel`、`cancelled_at`、`m4_reason_code` 等,名称待定),并同步: - - `app/model/order_delivery.js`; - - `OrderDeliveryFactory.createPhysicalTable` 生成的 DDL 模板; - - 已有物理分表的 **补列 migration**(循环 `wms_order_delivery_*`)。 - ---- - -## 1. 目标与范围(含 outsourced) - -### 1.1 工作台模块一览 - -| 模块 | 说明(产品语义) | 规划数据域 | -|------|------------------|------------| -| M1 待审核 | 需审核后进入后续履约 | **仅 current** | -| M2 待处理 | 仓内/出库前正常队列 | **仅 current** | -| M3 待处理异常 | 出库前各环节异常 | **仅 current** | -| M4 配送订单 | 配送链路正常态 | **配送域工厂(首期已落地)**:单表 `wms_order_delivery_dispatch_{wh}` + 列 `dispatch_lane=m4`;**不按自然月拆物理表** | -| M5 配送异常 | 配送链路异常(M4 子集) | **同上表**,`dispatch_lane=m5` 筛选;归档/近三月策略走 **查询与任务**,不必多分表 | -| M6 归档订单 | 冷数据 | **history**(>3 月等策略) | -| **outsourced 外仓发货** | 本仓不履约、推送外仓/三方履约;**已纳入 `OrderDeliveryFactory` 管理的 managed table / schema self-check 体系** | **由工厂统一管理,启动自检自动对齐结构**;仍可结合 current 扩展标记 + 外仓任务表落地 | - -### 1.2 数据分层(与 §0 对齐) - -| 层级 | 表 / 模型 | 时间 / 策略 | -|------|-----------|-------------| -| 热区 M1~M3 / outsourced(规划) | `wms_order_delivery_{wh}`、`wms_order_items_{wh}`(current) | 当日或未闭环;**创建时分流 M1 vs M2 由货主配置决定**;**到期仅克隆续单**,不进 M6(§2.4) | -| 配送区 M4/M5 | **`wms_order_delivery_dispatch_{wh}`**(`OrderDeliveryFactory` 的 dispatch 模式) | **单物理表**;M4/M5 用 **`dispatch_lane`**;**不按自然月拆表**;「约 3 个月」保留为 **列表/归档任务的时间条件**(见 §2.5 落地说明) | -| 冷数据 M6 | `*_history`(仅承接 **M4/M5** 迁入) | **超过 3 个月**等策略;**仅允许 M4/M5 进入 M6**;M1/M2/M3/outsourced **不走 M6 物理归档路径**(见 §2.4) | - ---- - -## 2. 模块规则与状态流转(补充) - -### 2.1 订单创建:进入 M1 或 M2 - -- **规则**:创建时读取 **货主(store)配置**,决定初始进入 **M1(待审核)** 或 **M2(待处理)**。 -- **M1 → M2**:必须通过 **仓内库存校验**(满足可履约)**或** 选择 **推送 outsourced(外仓发货)** 路径之一;具体字段与接口待定义。 -- **M2 ⊥ outsourced(强制互斥)**:同一订单 **不得** 同时处于本仓待处理与外仓履约;进入或退出 M2/outsourced 的切换 **必须在单条(或可串行化的)数据库事务内完成**(状态位 + 外仓任务表等一并提交),失败 **整体回滚**,禁止半开状态。 -- **outsourced**:当前 **无完整状态机**;与 M4 的衔接仍遵守 §2.2 单向规则。 - -### 2.2 进入 M4 的约束(核心) - -| 从 → 到 | 是否允许 | 说明 | -|---------|----------|------| -| **M2 → M4** | **允许(单向)** | M2、**outsourced 仅允许单向落入 M4** | -| **outsourced → M4** | **允许(单向)** | 外仓发货完成后,依赖 **外部通知** 与出库状态机推进 | -| **M1 → M4** | **禁止** | 须先 **切到 M2** 且 **状态机到达出库** 后,再经 **外部通知发货完成** 落入 M4 | -| **M3 → M4** | **禁止** | 须先 **消除异常并回到 M2**,再走与 M2 相同路径进入 M4 | -| **取消订单 → M4** | **允许(专用)** | 见 **§2.3a**:标记取消态后 **直进 M4**,**不可逆**、**零例外** | - -### 2.3 M4 / M5 与外部机制 - -- **M4 ↔ M5 切换**:由 **外部机制** 驱动(承运商回传、网关、人工标记等),不在此文档展开协议。 -- **M4/M5 与 M1~M3**:除下节「补发副本」外,**同一订单在 M1/M2/M3/outsourced 与 M4/M5 不重复占位**:**M1~M3(及 outsourced)为唯一工作台态**;**M4/M5 为配送域单独态**(可理解为 **配送域一条影子/主数据**,与 current 热行通过 `order_id` / `delivery_order_code` / 快照关联)。 - -### 2.3a 订单取消(特殊路径:标记后进 M4) - -- **规则**:发生 **订单取消** 时,须在热区/配送衔接层 **写入取消类状态标记**(状态机字段组合或专用列,见 **§0.7**),并 **直接进入 M4**(配送域占位,用于闭环展示与后续「仅 M4/M5 可进 M6」链路);**不可逆**,**不允许任何业务或技术例外**(含回滚接口、静默改回热区)。 -- **与 §2.2 的关系**:本条为 **取消专用例外**;非取消场景下 **M1/M3 仍禁止直落 M4**(见 §2.2 表)。 -- **库表**:上线前按 **§0.7** 核对;**缺字段则 migration 补充**,禁止仅靠应用层内存状态表达取消进 M4。 - -### 2.4 时间驱动的 M6(不可逆 + 准入白名单) - -- **时间策略**:**所有订单类型均受时间维度约束,不另开例外**;**进入 M6(物理归档)后不可逆**,**不允许任何例外**(不设司法解冻、不设未归档回退通道)。 -- **谁可以进 M6(物理)**:**仅 M4、M5** 对应的配送域数据(及与其绑定的明细快照)允许在满足保留期后 **迁入 `history` / 冷存储**。 -- **谁不可以进 M6**:**M1、M2、M3、outsourced** 热区行 **不允许** 走与 M4/M5 **相同的** M6(history)迁入通道;**到期后仅允许「克隆续单」**:通过 **新行(新主键)** 承接后续履约,原行 **仅改标记**(§2.7),**不得**删/软删、**不得**将原行迁入 M6。 -- **克隆续单 / 补单(首期)**:**不与奇门等平台同步**;定位为 **补单**,由 **人工在仓内/运营侧处理**;系统可提供列表与标记能力,**接口与对账范围以本仓 WMS 为准**。 -- **M4/M5 → M6**:以 **出库时间**(如 `delivery_time` / 出库确认时间)为主键条件之一,满足 **>3 个月**(与 §1.2 口径对齐)后迁入 history;过程 **不可逆**。 - -### 2.5 配送域工厂(首期落地 + 后续) - -- **已实现**:`app/model/order_delivery_factory.js` 的 dispatch 模式;物理表 **`wms_order_delivery_dispatch_{warehouseId}`**(与热区 `wms_order_delivery_{wh}` 命名同族,中间段 **`dispatch`**);**M4/M5 同表**,列 **`dispatch_lane` ENUM('m4','m5')** 区分;**不按自然月拆物理表**。`getDispatchModel(wh)` 为主入口;`getM4Model`/`getM5Model` 复用同一 dispatch 模式返回 **同一模型**。**outsourced 也已经纳入同一工厂管理,应用启动时会通过自检自动对齐 managed table 结构**。 -- **单测**:`test/app/model/order_delivery_dispatch_factory.test.js`;需连库时 `DISPATCH_FACTORY_TEST_MYSQL=1`(见 `config/plugin.js`);留表排查 `KEEP_DISPATCH_FACTORY_TABLES=1`。 -- **仍待**:与 current 的 **副本同步 / 事件驱动**;**强分区事务** 口径改为「单事务内同一 `warehouse_id` + 配送域表」即可(不再绑定 `yyyyMM` 表名);`wms_order_express` 与配送域行关联方案;M6 迁入仍以 **出库时间 + 保留期** 驱动(§2.4)。 - -### 2.6 M4/M5 副本回归 M1 / M2 / M3(补发 / 部分履约) - -- **场景**:配送域需 **重新创建副本** 回到 **M1 或 M2 或 M3**(目标态由业务定)。 -- **强制携带**:**补发标记/补发单**;或 **引用原资料 + 部分商品行** 的 **补发语义**,并 **更新履约目标**(新 `delivery_order_code` 或子单号、关联原单 ID 等,待表设计)。 -- **约束**:回归后重新遵守 **§2.1~2.2** 的互斥与单向规则;原配送域行 **不得删除/软删**,仅 **改标记** 或保留为 **只读关联**(§2.7)。 - -### 2.7 副本、主单与删除策略(硬约束) - -- **禁止物理删除**;**禁止软删除**(不使用 `delete_at` / `paranoid` 等表达「行消失」)。 -- **仅允许**:**改标记**(如 `lifecycle_state`、`superseded_by_id`、`closed_reason`、`is_supplement` 等,具体字段待表设计)或 **克隆** 新行(新主键)承载补发/续履约。 -- **适用范围**:**所有副本**(配送域副本、热区补发单、回归产生的克隆行、引用链上的历史快照)一律同上。 -- **运维级「克隆」语义**:在本规划中特指 **对状态机字段的合法变更**(含批量修正、`step` / 各 `*_status` / 取消标记等),**等价于「把行修正到合规状态」**;**不是**对 §2.3a「取消进 M4」或 §2.4「M6 不可逆」的 **豁免回滚**。若技术上采用「插入新行再改关联」实现修正,仍须满足 **不删旧行、仅标记**(§2.7 首条)。**审批角色与留痕** 见 **§5a 预留**,本期不落地。 - -### 2.8 互斥与唯一性(更新) - -| 关系 | 说明 | -|------|------| -| M1 ⊥ (M2 ∪ M3) | 不变 | -| M2 ⊥ M3 | 不变 | -| **M2 ⊥ outsourced** | **强制互斥**;切换须 **事务**(§2.1) | -| M5 ⊆ M4 | 不变 | -| **M1~M3 / outsourced(热区)** | **同一订单唯一展示态**(互斥集合内择一) | -| **M4 / M5** | **配送域内**可与热区并存为 **影子数据**;列表层需约定「主工作台只显示一侧」避免重复操作 | -| **M6** | **仅 M4/M5 可物理迁入**;**不可逆、零例外**;热区到期 **不进 M6**,**仅允许克隆续单**(§2.4) | - ---- - -## 3. 查询设计任务(列表 + 明细) - -### 3.1 列表查询(各模块) - -**目标**:最小可用字段集 + **足够前端判断订单状态**(含 outsourced 外仓标记若存在)。 - -**原则**: - -- 列表不返回大体积 `items` TEXT;仅标识、各 `*_status`、`outbound_status`、`inspection_status`、`step`、`updated_at` / `delivery_time`、货主/仓编码等。 -- 实现:**按模块常量 `LIST_FIELDS`**;M4/M5/outsourced 在配送域或扩展表就绪后各自维护一份。 - -### 3.2 明细查询 - -- 主单:**可对前端公开**的全部字段(排除密钥、内部调试字段)。 -- 明细行:`OrderItems` 动态表全量可公开字段。 -- **关联**:`Store`/仓库等(以 Sequelize `setupAssociations` / `copyAssociations` 为准,文档列出 **别名 + 字段子集**)。 -- **快递**:**暂不接订阅/路由逻辑**;列表/明细仅展示;**DTO 硬编码字段表 + 中文标签注释**(主表 `logistics_*` + 若联查 `wms_order_express` 则增加运单等字段)。 - -### 3.3 快递展示字段清单(示例) - -| 字段 key | 前端标签 | 说明 | -|----------|----------|------| -| `logistics_name` | 承运商 | 仅展示 | -| `logistics_code` | 物流编码 | 仅展示 | -| `waybill_code`(express 表) | 运单号 | 仅展示 | -| … | … | 不接路由、不订阅 | - ---- - -## 4. 执行任务(分阶段,可微调) - -### 执行进度(小阶段 A-0,最小影响) - -| 日期 | 内容 | -|------|------| -| 2026-04-10 | **无业务代码 / 无 migration 变更**。新增只读交付物:`docs/order-cancel-db-checklist.md`(§0.7 跑库步骤)、`docs/order-state-machine-dictionary.md`(状态机字典 **v0 骨架**,与 `app/model/order_delivery.js` 摘录一致)。**数仓映射、实际跑库结果** 仍待下一小阶段。 | -| 2026-04-10 | **小阶段 A-1(影响面)**:新增 `docs/order-delivery-migration-impact.md`。**结论**:在未跑库确认缺列、且未敲定「取消进 M4」专用列前,**不自动提交 ALTER migration**;若清单验证列已齐,可先 **零表变更** 做应用筛选。详见该文档 **§1**。 | -| 2026-04-10 | **小阶段 A-2(wms-db-agent 只读诊断)**:已对 `wms` 库跑清单;结果写入 **`docs/order-cancel-db-checklist.md` §5**。要点:**分表** `100000`/`1000028` 目标列齐全,可先不增列做筛选;**基表**缺三列、**勿**当业务表用;**无 `_history` 样本**;`chcp 65001` 防 JSON 解析失败。 | -| 2026-04-11 | **基表状态列**:migration `20260410200000-add-status-columns-to-wms-order-delivery-base.js`(按需补列,与热区分表对齐)。**配送域**:`OrderDeliveryFactory` 的 dispatch 模式单表 `wms_order_delivery_dispatch_{wh}` + `dispatch_lane`;当前按单表落地,不再保留「m4/m5 分表 + 自然月表名」方案;单测与 `DISPATCH_FACTORY_TEST_MYSQL` 见上文 §2.5。 | -| 2026-04-11 | **outsourced 收敛**:`outsourced` 纳入 `OrderDeliveryFactory` 的 managed table / schema self-check 体系,沿用启动自检自动对齐结构;旧兼容 shim 已移除,文档与代码统一收口到工厂管理。 | - -### 阶段 A — 文档与规则冻结 - -- [x] 货主配置:「创建进 M1 / M2」的配置项落库位置与变更流程。 -- [ ] M1→M2:库存校验 API、outsourced 推送接口与回写字段。 -- [ ] 外部「发货完成」通知与状态机字段的映射表(落到 `outbound_status` / `step` 等)。 -- [x] **§0.7 清单文档**:`docs/order-cancel-db-checklist.md`(各环境人工执行)。 -- [x] **§0.7 跑库(本机 wms 一次)**:见 `docs/order-cancel-db-checklist.md` §5;**分表列齐**;**其它仓/生产须复跑**。 -- [x] **§0.7 基表状态列 migration**(与分表枚举对齐):`database/migrations/20260410200000-add-status-columns-to-wms-order-delivery-base.js`(已合并进仓库;其它环境须自行 `db:migrate`)。**独立「取消进 M4」业务列** 仍待产品定名后再 migration。 -- [x] **状态机字典 v0 骨架**:`docs/order-state-machine-dictionary.md`(与数仓/报表的 **字段映射表** 仍待补)。 -- [x] **订单表 DDL 影响面分析**:`docs/order-delivery-migration-impact.md`(初版静态结论;**2026-04-11** 起基表状态列以已合并 migration 为准,文档全文若与现网不一致须择机修订)。 - -### 阶段 B — 配送域工厂(3 自然月 + 强分区事务) - -- [x] 配送域建表能力(`OrderDeliveryFactory` 的 dispatch 模式):表 **`wms_order_delivery_dispatch_{warehouseId}`**,**`dispatch_lane`** 区分 M4/M5。 -- [x] M4/M5 **单表** DDL 与动态模型(首期)。 -- [ ] 与 current 的 **副本同步** 或 **事件驱动** 方案(未做)。 -- [ ] `wms_order_express` 与配送域 **order_id**(及仓)一致性方案。 - -### 阶段 C — 归档 M6 + 时间消除 - -- [ ] **仅 M4/M5**:配送域 → history 的 **出库时间** 驱动任务;**不可逆** 校验与审计(**零例外**)。 -- [ ] **M1/M2/M3/outsourced**:到期 **仅克隆续单** 流程(新行 + 原行标记);**禁止** 迁入 M6;前端 **空态/引导续单** 文案。 -- [ ] **取消进 M4**:状态机字段字典、事务边界、与常规 M4 列表的 **展示分区**(避免与正常配送混淆)。 -- [ ] 全库 **禁止 DELETE/软删** 副本与主单的 ORM/脚本审计;运维修正走 **状态机变更**(§2.7);**审批流** 见 **§5a 预留**。 - -### 阶段 D — 补发副本与目标更新 - -- [ ] 补发单模型、原单引用、部分行、目标更新字段;**原行仅标记,禁止删/软删**。 -- [ ] 事务:副本创建 + 热区插入 + 配送域标记 **同一强分区键内** 或可补偿 Saga;与 **M2↔outsourced 事务切换** 共用事务规范文档。 - -### 阶段 E — API / 测试 - -- [ ] `methods/system.json` + changes;互斥与单向集成测试用例。 - ---- - -## 5. 待补充项 — 满足情况说明(已更新) - -> **结论**:原「待补充项」中的 **业务原则 / 边界** 多数已在正文(§0.7、§2.3a、§2.4、§5a)**闭合**,**不再属于「方向未定的拍板」**;但 **可交付的设计稿与成文资产** 仍未完成,须在 **§4 各阶段** 跟踪直至产出。 - -### 5.1 规则层 — 视为已满足(已写入本文档) - -| 原议题 | 满足方式 | -|--------|----------| -| 克隆续单是否与奇门同步 | **已决策:不同步**;首期 **人工补单** — 见 §2.4 | -| 运维审批、留痕格式 | **已决策:本期不做**,仅预留 — 见 **§5a** | -| 取消状态机是否依赖库表 | **已决策:以 DB 为准**,缺列则 migration — 见 **§0.7**、§2.3a | - -### 5.2 交付层 — 尚未满足(须产出成果物,不等同于「原则未拍板」) - -| 事项 | 当前状态 | 建议产出 / 跟踪位置 | -|------|----------|----------------------| -| **取消进 M4** 的配送域 **子类型 / 展示标签**(与正常 M4 区分色、筛选项) | 未完成 | 产品/UI 说明 + 接口 `where` 约定;**§4 阶段 C** | -| **克隆续单** 的 **主键关联、单号规则、权限** | 未完成 | 表设计 + 人工补单 SOP;**§4 阶段 D**(原则「不奇门」已 §2.4) | -| **改标记 / 状态机** 的 **字段字典** 及与 **数仓、报表** 同步 | **骨架已完成(v0)** | 成稿:`docs/order-state-machine-dictionary.md`;**数仓/报表映射与变更登记** 仍未完成 — **§4 阶段 A/C** | - -### 5a. 预留(本期不实现) - -- **运维审批** 角色、工单模板与 **留痕格式**:**本期不做**,仅在技术方案中 **预留扩展点**(配置键、审计表占位名、接口 hook 注释),避免后续硬改核心表结构。 - ---- - -## 6. 修订记录 - -| 日期 | 说明 | -|------|------| -| (首版) | 根据讨论整理计划草案 | -| 补充 | 增加 §0 当前表/模型/工厂/关联分析;outsourced、创建分流、进入 M4 约束、外部驱动 M4/M5、时间进 M6、配送域独立工厂与强分区事务、M4/M5 按出库时间进 M6、补发副本回归 M1/2/3 | -| 补充 | **M2⊥outsourced 且事务进出**;**M6 仅 M4/M5 可物理迁入、不可逆**;热区到期不进 M6;**全副本禁止删/软删、仅标记或克隆**;§2.7 硬约束、§1.2/阶段 C/待补充项同步 | -| 补充 | 热区到期 **仅克隆续单**;**§2.3a 取消→标记→直进 M4、不可逆零例外**;**运维「克隆」= 状态机合法变更** 写入 §2.2/§2.7/阶段 C | -| 补充 | **§0.7** 取消状态机与分表核对/缺列 migration;**克隆续单不奇门同步、首期人工补单**;**字段字典与数仓报表同步**;**§5a 运维审批预留** | -| 补充 | **§5 重写**:区分 **规则层已满足** vs **交付层未完成**;原 checklist 拆入 §5.1 / §5.2 并指向 §4 | -| 2026-04-10 | **小阶段 A-0**:新增 `docs/order-cancel-db-checklist.md`、`docs/order-state-machine-dictionary.md`;§0.7 / §4 阶段 A / §5.2 同步;无代码变更 | -| 2026-04-10 | **小阶段 A-1**:`docs/order-delivery-migration-impact.md`;**未提交 migration**(待你根据跑库 + 列名决策) | -| 2026-04-10 | **小阶段 A-2**:wms-db-agent 只读诊断;`order-cancel-db-checklist.md` §5;**未提交 migration** | -| 2026-04-11 | **配送域单表工厂** + **基表 migration**;§1.2 / §2.5 / §4 阶段 B 勾选与表述同步 | diff --git a/docs/print-retry-compensation.md b/docs/print-retry-compensation.md deleted file mode 100644 index b7b1f2d..0000000 --- a/docs/print-retry-compensation.md +++ /dev/null @@ -1,65 +0,0 @@ -# 打印失败自动补偿(printRetryCompensation)操作说明 - -概述 -- 目的:定时扫描失败或超时的打印记录,按仓库分组并批量触发补打(调用内部方法 `print.retryFailed`)。 -- 实现位置:调度任务文件 [app/schedule/print_retry_compensation.js](app/schedule/print_retry_compensation.js) -- 配置位置:全局配置 `config.printRetryCompensation`(见 `config/config.default.js`) - -如何开启 -1. 在目标环境的配置文件中(例如 `config/config.local.js` 或部署时注入的 config),设置: - -```js -// 示例(config/config.local.js) -module.exports = appInfo => { - const config = exports = {}; - - config.printRetryCompensation = { - enable: true, // 开启自动补偿 - intervalMs: 60 * 1000, // 最小执行间隔(ms),默认 60000 - batchSize: 50, // 每次扫描触发的最大打印记录数,默认 50 - force: false, // 是否以强制方式触发(当前实现不放宽状态判定) - }; - - return config; -}; -``` - -2. 启用后,Egg 的调度器会按文件中的 `schedule.interval`(30s)触发调度器,但实际执行受 `intervalMs` 控制(避免重复执行)。 -3. 部署/重启应用使配置生效。 - -关键参数说明 -- `enable` (boolean):是否启用自动补偿(默认 `false`)。 -- `intervalMs` (number, ms):两次实际执行之间的最小间隔(默认 60000)。注意调度器仍以 30s 触发,但若距离上次执行时间 < intervalMs 将跳过本轮。 -- `batchSize` (number):每次从数据库读出的最大记录数量(默认 50)。 -- `force` (boolean):是否强制补打。当前最小实现中 `force` 参数会被传递到 `print.retryFailed`,但 `getRetryEligibility` 中并未放宽状态检查(注释标注为“最小实现”)。如需放宽,需要修改 `app/service/systemMethods/print.js` 中的 `getRetryEligibility` 实现。 - -行为与兼容性(与代码的一致性要点) -- 调度逻辑: - - 调度入口:[app/schedule/print_retry_compensation.js](app/schedule/print_retry_compensation.js) - - 查询条件:满足任一 send_status 为 `send_failed`,或 print_status 在 `['print_failed','timeout']`,且 `next_retry_at <= now`,并且 `retry_count < max_retry_count`。 - - 按 `warehouse_id` 分组后,逐仓调用: - `ctx.service.systemMethods.print.retryFailed({ print_ids, warehouse_id, force })`。 -- `print.retryFailed` 对 `warehouse_id` 的兼容: - - 支持显式传入 `warehouse_id`,优先使用该值。 - - 若未传入 `warehouse_id`,会回退使用 `ctx.user.store_id`(接口调用者的仓库上下文)。 - - 如果两者均无(例如外部无登录上下文且未传入 `warehouse_id`),方法会返回 400 错误:`warehouse_id 参数缺失,且当前上下文无可用仓库信息`。 -- 返回值要点:成功返回包含 `success_count` / `failed_count` / `skipped_count`、`retried`(尝试项)和 `skipped`(跳过项)摘要;调度器依据 `flag==='success'` 判定调用是否成功。 - -排障要点(常见问题排查) -- 任务一直没有扫描到记录:检查数据库 `PrintRecord` 表中是否存在满足条件的行(`send_status`/`print_status`、`next_retry_at`、`retry_count < max_retry_count`)。 -- 调度被频繁跳过:检查 `config.printRetryCompensation.intervalMs` 与日志中 `ctx.app._printRetryCompensationLastRunAt` 的时间差;若 `_printRetryCompensationRunning` 标识长时间为 true,进程可能在上次运行时异常退出,建议重启应用清理状态。 -- 补打触发但实际发送失败:查看打印服务调用日志(`service.systems.print.index.sendToComputer` 返回值),并查看 `PrintRecord` 的 `error_message` / `fail_code` 字段。 -- 快递/组件离线导致发送失败:`print` 服务会在调用前检查组件在线性(从 Redis 的 `printer:{computerId}:name:{component}:status` 读取,期望值为 `connected`)。请检查对应 Redis key 是否存在并为 `connected`。 -- 打印任务编码冲突:如果出现唯一索引冲突(ER_DUP_ENTRY),日志会有 `打印任务编码冲突` 的警告,系统会按指数退避重试写入映射表。 - -回滚方式 -- 临时回滚:在运行环境配置中将 `printRetryCompensation.enable` 设为 `false` 并重启服务,调度器将不再触发实际补偿逻辑。 -- 速率/批量调整:将 `batchSize` 缩小或增大 `intervalMs`,以控制对打印服务的并发压力。 - -参考位置 -- 调度实现:[app/schedule/print_retry_compensation.js](app/schedule/print_retry_compensation.js) -- 默认配置:[config/config.default.js](config/config.default.js)(`printRetryCompensation` 段) -- 补打实现与仓库兼容性:[app/service/systemMethods/print.js](app/service/systemMethods/print.js) 中 `retryFailed` 与 `getRetryEligibility` 方法 - -附注 -- 本说明以当前代码实现为准(2026-05-20),如修改 `getRetryEligibility` 或补打流程,请同步更新本说明与 `methods/changes` 记录。 \ No newline at end of file diff --git a/docs/qimen-interface-reference.md b/docs/qimen-interface-reference.md deleted file mode 100644 index 70a0a5a..0000000 --- a/docs/qimen-interface-reference.md +++ /dev/null @@ -1,226 +0,0 @@ -# 奇门接口技术备忘 - -## 1. 文档来源 - -- 官方来源:open.taobao.com 文档,docId=118403,页面章节为“5. 接口说明” -- 适用对象:WMS 与 ERP 之间的奇门对接排障、接口回查、协议备忘 -- 本文目标:把官方白皮书里的核心调用约定、接口地图和本地实现入口沉淀到仓库内,便于技术备用 - -## 2. 接入总览 - -奇门接口的统一特征是: - -- 请求方式以 POST 为主 -- query 中携带 app_key、method、v、format、sign_method、sign、timestamp 等标准参数 -- body 使用 XML,根节点通常为 request -- 响应也使用 XML,根节点通常为 response -- 响应通常包含 flag、code、message 三个固定字段 - -官方白皮书中明确说明: - -- 很多接口是同步接口,返回 success 不只是“消息接收成功”,而是代表业务已处理完成 -- 批量接口通常会在一个订单下承载多个 item 或 order 节点 -- 非叶子节点通常允许增加 remark 和 extendProps - -## 3. 通用字段与约定 - -### 3.1 常见主键字段 - -- ownerCode:货主编码 -- warehouseCode:仓库编码,统仓统配等场景常填 OTHER -- itemCode:ERP 商品编码 -- itemId:WMS 商品编码或仓储系统商品 ID,通常是条件必填 -- orderCode:单据编码 -- orderId:仓储系统单据编码 -- outBizCode:外部业务编码,常作为幂等键 - -### 3.2 常见状态枚举 - -订单类状态常见值: - -- NEW:未开始处理 -- ACCEPT:仓库接单 -- PRINT:打印 -- PICK:拣货 -- CHECK:复核 -- PACKAGE:打包 -- WEIGH:称重 -- READY:待提货 -- DELIVERED:已发货 -- PARTDELIVERED:部分发货完成 -- PARTFULFILLED:部分收货完成 -- FULFILLED:收货完成 -- EXCEPTION:异常 -- CANCELED:取消 -- CLOSED:关闭 -- REJECT:拒单 -- REFUSE:客户拒签 -- SIGN:签收 - -库存类常见值: - -- ZP:正品 -- CC:残次 -- JS:机损 -- XS:箱损 -- FP:废品 -- ZT:在途库存 -- DJ:冻结 -- OTHER:其他 - -### 3.3 常见业务规则 - -- 组合商品、条码、批次、生产日期、过期日期、生产批号等字段在多个接口里复用 -- 一些接口对 itemId 有条件必填要求,通常与仓库是否自定义 WMS 商品编码有关 -- 多次收货、多次发货、多次确认类接口会使用 confirmType -- 分批发送时,totalOrderLines 常用于说明总行数,接收方据此判断是否收齐 - -## 4. 接口地图 - -以下为官方文档 5.x 章节的接口目录,按业务域整理。 - -### 4.1 商品与商品映射 - -- 5.1 商品查询接口:taobao.qimen.singleitem.query / singleitem.query -- 5.2 商品同步接口:taobao.qimen.singleitem.synchronize / singleitem.synchronize -- 5.3 商品同步接口(批量):taobao.qimen.items.synchronize / items.synchronize -- 5.4 组合商品接口:taobao.qimen.combineitem.synchronize / combineitem.synchronize -- 5.5 创建前后端商品映射接口:taobao.qimen.itemmapping.create / itemmapping.create -- 5.6 前后端商品映射查询接口:taobao.qimen.itemmapping.query / itemmapping.query - -### 4.2 入库与退货入库 - -- 5.7 入库单创建接口:taobao.qimen.entryorder.create / entryorder.create -- 5.8 入库单确认接口:taobao.qimen.entryorder.confirm / entryorder.confirm -- 5.9 入库单查询接口:taobao.qimen.entryorder.query / entryorder.query -- 5.10 退货入库单创建接口:taobao.qimen.returnorder.create / returnorder.create -- 5.11 退货入库单确认接口:taobao.qimen.returnorder.confirm / returnorder.confirm -- 5.12 退货入库单查询接口:taobao.qimen.returnorder.query / returnorder.query - -### 4.3 出库、发货与确认 - -- 5.13 出库单创建接口:taobao.qimen.stockout.create / stockout.create -- 5.14 出库单确认接口:taobao.qimen.stockout.confirm / stockout.confirm -- 5.15 出库单查询接口:taobao.qimen.stockout.query / stockout.query -- 5.16 发货单创建接口:taobao.qimen.deliveryorder.create / deliveryorder.create -- 5.17 发货单创建接口(批量):taobao.qimen.deliveryorder.batchcreate / deliveryorder.batchcreate -- 5.18 发货单创建结果通知接口(批量):taobao.qimen.deliveryorder.batchcreate.answer / deliveryorder.batchcreate.answer -- 5.19 发货单确认接口:taobao.qimen.deliveryorder.confirm / deliveryorder.confirm -- 5.20 发货单确认接口(批量):taobao.qimen.deliveryorder.batchconfirm / deliveryorder.batchconfirm -- 5.21 发货单查询接口:taobao.qimen.deliveryorder.query / deliveryorder.query - -### 4.4 SN 与订单流水 - -- 5.22 订单SN通知接口:taobao.qimen.order.sn.report / order.sn.report -- 5.23 发货单SN通知接口:taobao.qimen.sn.report / sn.report -- 5.24 订单流水查询接口:taobao.qimen.orderprocess.query / orderprocess.query -- 5.25 订单状态查询接口(批量):taobao.qimen.orderstatus.batchquery / orderstatus.batchquery -- 5.26 订单流水通知接口:taobao.qimen.orderprocess.report / orderprocess.report -- 5.27 订单异常通知接口:taobao.qimen.orderexception.report / orderexception.report - -### 4.5 异常、退货、缺货与挂起 - -- 5.28 退货异常包裹单通知接口:taobao.qimen.returnapply.report / returnapply.report -- 5.29 退货包裹状态通知接口:taobao.qimen.returnpackage.report / returnpackage.report -- 5.30 发货单缺货通知接口:taobao.qimen.itemlack.report / itemlack.report -- 5.31 发货单缺货查询接口:taobao.qimen.itemlack.query / itemlack.query -- 5.32 单据取消接口:taobao.qimen.order.cancel / order.cancel -- 5.33 单据挂起(恢复)接口:taobao.qimen.order.pending / order.pending - -### 4.6 库存、仓库、加工与异动 - -- 5.34 库存查询接口(多商品):taobao.qimen.inventory.query / inventory.query -- 5.35 库存查询接口(多条件):taobao.qimen.stock.query / stock.query -- 5.36 仓库查询接口:taobao.qimen.warehouseinfo.query / warehouseinfo.query -- 5.37 仓库同步接口:taobao.qimen.warehouseinfo.synchronize / warehouseinfo.synchronize -- 5.38 库存盘点通知接口:taobao.qimen.inventory.report / inventory.report -- 5.39 库存盘点查询接口:taobao.qimen.inventorycheck.query / inventorycheck.query -- 5.40 仓内加工单创建接口:taobao.qimen.storeprocess.create / storeprocess.create -- 5.41 仓内加工单确认接口:taobao.qimen.storeprocess.confirm / storeprocess.confirm -- 5.42 库存异动通知接口:taobao.qimen.stockchange.report / stockchange.report - -### 4.7 店铺、波次、调拨、规则与统计 - -- 5.43 店铺同步接口:taobao.qimen.shop.synchronize / shop.synchronize -- 5.44 发货单波次通知接口:taobao.qimen.wavenum.report / wavenum.report -- 5.45 调拨单创建接口:taobao.qimen.transferorder.create / transferorder.create -- 5.46 调拨单查询接口:taobao.qimen.transferorder.query / transferorder.query -- 5.47 调拨单通知接口:taobao.qimen.transferorder.report / transferorder.report -- 5.48 渠道间库存规则设置接口:taobao.qimen.inventoryrule.create / inventoryrule.create -- 5.49 库存汇总报表查询接口:taobao.qimen.inventorysum.query / inventorysum.query -- 5.50 订单出库统计查询接口:taobao.qimen.deliveryordersum.query / deliveryordersum.query - -### 4.8 基础能力 - -- 5.51 心跳接口:taobao.qimen.service.heartbeat / service.heartbeat -- 5.52 供应商信息同步接口:taobao.qimen.supplier.synchronize / supplier.synchronize -- 5.53 配送公司信息查询:taobao.qimen.expressinfo.query / expressinfo.query - -## 5. 官方白皮书里的关键细节 - -### 5.1 商品接口 - -- 单品查询与单品同步字段高度一致,itemCode、itemName、barCode、itemType、brand、重量、尺寸、批次、保质期相关字段都会复用 -- 批量商品同步使用 items 节点包裹 item 列表 -- 组合商品接口的核心是 itemCode、ownerCode、warehouseCode 与子商品清单 - -### 5.2 入库与退货入库 - -- entryorder.create 与 returnorder.create 都是同步创建 -- confirm 接口用于最终状态回告,不只是接收消息 -- 订单行内常包含 itemCode、itemId、planQty、actualQty、inventoryType、batchCode、productDate、expireDate、produceCode -- 入库场景支持 relatedOrders 关联单据信息 - -### 5.3 出库与发货 - -- stockout 更偏普通出库,不强调订单履约语义 -- deliveryorder 更偏订单驱动发货 -- 批量版 create/confirm 接口支持 orders 与 order 节点 -- 发货单确认会带包裹、发票、物流、重量、体积、SN、批次等信息 - -### 5.4 库存与盘点 - -- inventory.query 与 stock.query 都是库存查询,但入参组织方式不同 -- inventory.report 与 inventorycheck.query 用于盘点回传和盘点查询 -- stockchange.report 用于把引起库存变动的单据和库存变化同步给 ERP - -### 5.5 组织与基础资料 - -- warehouseinfo.query / synchronize 处理仓库基础资料 -- shop.synchronize 处理店铺基础资料 -- supplier.synchronize 处理供应商基础资料 -- expressinfo.query 处理配送公司信息 - -## 6. 本地实现落点 - -当前仓库里与奇门相关的本地实现入口主要是: - -- app/service/qimen.js:统一 XML 解析、method 路由与 XML 响应封装 -- app/service/qimenMethods/:具体奇门业务方法实现目录 -- typings/app/service/index.d.ts:qimenMethods 的类型入口 -- methods/qimen.json:当前奇门方法定义与参数结构的主索引 -- methods/changes/qimen.json:奇门文档变更记录副本 - -从代码层看,qimen.js 会先解析 XML,再根据 method 对应到 qimenMethods 下的具体模块调用。 - -## 7. 排障时的实用检查点 - -1. 先确认 method 名是否与官方文档一致,尤其是 singleitem、deliveryorder、entryorder、returnorder、stockout、inventory 这些主模块 -2. 再确认 XML 根节点和字段名是否和官方定义一致,奇门对字段名大小写和层级通常比较敏感 -3. 关注 itemId 是否被误传为空,很多接口里它是条件必填 -4. 关注 warehouseCode 是否在统仓统配场景下正确使用 OTHER -5. 批量接口要核对 totalOrderLines、currentPage、pageSize 和明细数量是否一致 -6. 发生返回 success 但业务未落库时,要继续检查本地实现是否只是接收成功而不是业务处理成功 - -## 8. 结论 - -这份奇门白皮书覆盖了 WMS 与 ERP 对接的完整主干能力,核心可以归纳为: - -- 商品主数据 -- 入库、退货入库、出库、发货 -- SN、流水、状态、异常 -- 库存、盘点、加工、异动 -- 仓库、店铺、供应商、配送公司基础资料 -- 调拨、波次、缺货、规则、统计与心跳 - -在本仓库中,奇门的本地实现已经有统一入口和方法分层,适合把本文作为日常联调与故障排查的快速备忘。 \ No newline at end of file diff --git a/docs/stock-expiry-module.md b/docs/stock-expiry-module.md deleted file mode 100644 index 4c17bce..0000000 --- a/docs/stock-expiry-module.md +++ /dev/null @@ -1,80 +0,0 @@ -# 库存效期模块(定时预警任务) - -本文档基于源码实现(单一事实来源),定位与说明项目中关于库存效期扫描与预警的定时任务行为。实现文件:app/schedule/notice_stock_remaining.js。 - -## 概要 - -- 任务名称/文件:`app/schedule/notice_stock_remaining.js` -- 调度配置:`interval: '30s'`、`type: 'worker'`、`immediate: false`(见文件头部 schedule 配置) -- 目的:扫描启用保质期管理的仓库商品与对应库存(wms_stock_warehouse / wms_storage),对即将到期的库存发送效期预警通知,并通过缓存进行去重。 - -## 主要实现要点(按代码实现逐项说明) - -1. 并发保护 - - 使用进程级标记 `ctx.app._noticeStockRemainingRunning`,若上一轮尚未结束则跳过本次运行。 - -2. 通知去重缓存 - - 缓存键:`notice_stock_remaining_notified_list`(文件常量 `CACHE_KEY`)。 - - 缓存 TTL:24 小时(`CACHE_TTL_SECONDS = 24 * 60 * 60`)。 - - 缓存存储格式兼容数组或对象,读取后标准化为 `storage:{id}` 格式的键集合用于去重。 - -3. 读取候选商品(wms_stock_warehouse) - - 查询条件(stockWhere): - - `is_shelf_life_mgmt: 'Y'` - - `remaining_threshold_days: { [Op.gt]: 0 }`(使用 `Sequelize.Op.gt`) - - 查询字段:`id, item_code, item_name, store_id, warehouse_id, remaining_threshold_days` - - 排序:`remaining_threshold_days ASC, id ASC` - - 结果用于构建 `stockMap`(包含每个 stock 的阈值),并计算 `maxThresholdDays`(用于缩小后续库存扫描时间窗口)。 - -4. 计算候选库存时间窗口 - - 以当前时间 `now`,计算 `maxExpiryDate = new Date(now.getTime() + maxThresholdDays * DAY_MS)`,其中 `DAY_MS = 24 * 60 * 60 * 1000`。 - -5. 查询候选库存记录(wms_storage) - - 查询条件(storageWhere): - - `stock_id` 在上一步筛选得到的 `stockIds` 列表中 - - `is_enabled: 1` - - `delete_at: null`(paranoid 软删除过滤) - - `quantity: { [Op.gt]: 0 }` - - `expiry_date: { [Op.ne]: null, [Op.lte]: maxExpiryDate }`(到期日非空且小于等于计算窗口) - - include:关联 `LocationSpace`(别名 `space`),属性取 `space_code, custom_name`,`required: false`。 - - 排序:`expiry_date ASC, inbound_time ASC, id ASC`。 - - 注意:实现中调用的是 `findAll`(无分页),因此会拉取匹配的全部候选记录并在内存中逐条处理。 - -6. 单条记录处理与判断逻辑 - - 对每条 `storageRecord`: - - 生成去重键 `notifyKey = storage:{storageId}`(若无法解析 id 则跳过)。 - - 若该 `notifyKey` 已存在于缓存集合则跳过(避免重复通知)。 - - 根据 `stockMap` 获取本条记录对应商品的 `thresholdDays`(阈值天数);若不存在或阈值 <= 0 则跳过。 - - 读取 `expiry_date`,将其解析为 Date;若无或解析失败则跳过并记录 warn。 - - 计算剩余天数:`remainingDays = Math.max(0, Math.ceil((expiryDate - now) / DAY_MS))`。 - - 若 `remainingDays > thresholdDays` 则跳过(未达到阈值);否则组装通知并发送。 - -7. 通知发送与元数据 - - 使用通知服务:`ctx.service.systems.notice.send(payload)`。代码中若 `noticeResult.success === false` 则认为发送失败并保留重试;异常时记录错误并继续处理下一条。 - - 通知 payload 包含(示例字段): - - `warehouseId`, `storeId`, `subject`(id/type/name), `businessName: 'storage'`, `event`(常量 `storage_transfer_completed`),`title`, `content`, `businessId: storageId`, `messageType: 'text'` - - `metadata`:包含 `cacheKey`, `storageId`, `stockId`, `notifyKey`, `thresholdDays`, `remainingDays`, `warehouseId`, `storeId`, `stock: { id, item_code, item_name }`, `storage: { id, batch_no, expiry_date (ISO) }` - -8. 回写去重缓存 - - 成功发送后,将 `notifyKey` 添加到 `updatedNotifiedList` 并在本轮结束后使用 `ctx.app.setCacheAsync(CACHE_KEY, dedupedList, CACHE_TTL_SECONDS)` 回写缓存(如果 `setCacheAsync` 可用)。 - -9. 日志与统计 - - 任务会记录候选商品数、候选库存数、实际发送计数与跳过计数;发送失败与异常会记录 warn/error 日志。 - -## 与公开 API 的关系 - -- 任务为内部定时任务(非 system API),其查询条件与模型字段直接对应数据库表 `wms_stock_warehouse` 与 `wms_storage`。 -- 若需要通过 API 查询某个商品的库存明细(包含批次与过期信息),请使用已有的 system 方法 `stock.warehouse.getStockDetail`(该接口支持 `pagination` 与 `group_by_batch`,API 文档位于 `methods/system.json`),与本任务的扫描逻辑互为补充:任务用于主动推送预警,API 用于按需查询。 - -## 注意事项(运维/集成) - -- 通知发送依赖 `ctx.service.systems.notice`,在无该服务或返回异常时任务仅记录日志。 -- 任务扫描不分页:对于极大库存量的仓库,建议评估 `maxThresholdDays` 与索引(`idx_expiry_date` 已存在于模型)对查询性能的影响,或考虑将查询改为分片/分页处理。 -- 去重缓存使用全局缓存接口 `getCacheAsync` / `setCacheAsync`,请保证缓存后台(如 Redis)可用以避免重复通知泛滥。 - -## 实现位置(代码参考) - -- 定时任务文件:app/schedule/notice_stock_remaining.js -- 依赖模型:app/model/stock_warehouse.js、app/model/storage.js、app/model/location_space.js -- 依赖服务:ctx.service.systems.notice - diff --git a/docs/stock-stockWarehouse-query-rules.md b/docs/stock-stockWarehouse-query-rules.md deleted file mode 100644 index f0bad86..0000000 --- a/docs/stock-stockWarehouse-query-rules.md +++ /dev/null @@ -1,178 +0,0 @@ -# stock.warehouse.list 前端查询规则 - -## 目的 - -本文档约束 `stock.warehouse.list` 的 `where` 构造格式,便于前端统一构建查询条件,并与后端解析器保持一致。 - -## 接口入口 - -- 路由:`POST /system` -- method:`stock.warehouse.list` - -## 请求体结构 - -```json -{ - "pagination": { - "page": 1, - "pageSize": 20 - }, - "where": { - "item_code": { - "operator": "like", - "value": "SKU", - "type": "text" - } - } -} -``` - -## where 字段规则 - -`where` 必须是对象,且每个字段值也必须是对象。 - -正确示例: - -```json -{ - "where": { - "item_name": { - "operator": "like", - "value": "鞋", - "type": "text" - } - } -} -``` - -错误示例(会返回解析失败原因): - -```json -{ - "where": { - "item_name": "鞋" - } -} -``` - -## 条件对象结构 - -每个 `where.` 支持: - -- `operator`:操作符,默认 `eq` -- `value`:查询值 -- `type`:值类型(可选) -- `field`:映射到真实字段(一般不需要前端传) - -### 支持操作符 - -- `eq` -- `ne` -- `like` / `contains` -- `startswith` -- `endswith` -- `gt` -- `lt` -- `ge` -- `le` -- `in` -- `notin` -- `between` -- `notbetween` -- `isnull` -- `isnotnull` -- `regexp` -- `notregexp` - -### 支持 type - -- `boolean`:转换为 `Y/N` -- `number`:转换为数字 -- `date`:日期字符串归一化 -- `daterange`:日期数组归一化 -- `text`:逗号分隔字符串拆分数组 - -## 特殊字段说明 - -### barcode - -- 在条码表中先匹配,再回灌 `stock_id` 过滤主表。 -- 推荐:`operator=eq|like`。 - -### prohibited_type - -- 传入的是违禁品类型 `id`。 -- 后端会映射到关联模型进行过滤。 - -### has_bound_item - -- 筛选仓库商品是否已绑定外部商品(货主商品)。 -- `operator`:固定 `eq`(默认)。 -- `value`: - - 已绑定:`true` / `1` / `"Y"` / `"y"` - - 未绑定:`false` / `0` / `"N"` / `"n"` -- 示例: - - 查询已绑定外部商品的仓库商品:`has_bound_item={operator:eq,value:true}` - - 查询未绑定外部商品的仓库商品:`has_bound_item={operator:eq,value:false}` - -## 空值处理 - -以下值会被视为“空条件”并跳过: - -- `null` -- `undefined` -- `""` -- `[]` - -## 排序规则 - -后端只接受以下排序字段: - -- `id` -- `item_code` -- `item_name` -- `quantity` -- `locked_quantity` -- `tag_price` -- `retail_price` -- `create_at` -- `update_at` - -当传入非法排序字段时,会回退为: - -- `sortField=create_at` -- `sortOrder=DESC` - -## 失败返回(解构失败) - -当 `where` 结构不合法时,返回示例: - -```json -{ - "code": 400, - "message": "筛选条件解析失败: 字段 item_code 条件必须是对象", - "data": { - "list": [], - "pagination": { - "page": 1, - "pageSize": 20, - "total": 0, - "totalPages": 0, - "hasPrevious": false, - "hasNext": false - }, - "summary": { - "total_quantity": 0, - "total_locked": 0, - "total_available": 0, - "total_items": 0 - } - } -} -``` - -## 前端建议 - -- 对 `in/notin/between/notbetween` 先做数组校验,再发请求。 -- 对 `where` 做 schema 校验,避免后端 400。 -- 对空输入不构造条件,减少无效查询。 diff --git a/docs/storage-receiving-api.md b/docs/storage-receiving-api.md deleted file mode 100644 index fdee9fe..0000000 --- a/docs/storage-receiving-api.md +++ /dev/null @@ -1,487 +0,0 @@ -# 收货单 API 文档(`storage.receiving`) - -## 1. 文档说明 - -本文档补充 `storage.receiving` 相关 system 方法中的收货明细商品绑定接口,当前重点覆盖: - -- `storage.receiving.bindDetailProduct` - -适用场景: - -- 新增收货单明细后,为该明细绑定系统商品 -- 已绑定商品时,改绑为另一个系统商品 -- 前端或第三方系统对接收货单明细与系统商品的匹配动作 - ---- - -## 2. 统一调用方式 - -该项目的 system 方法统一通过 `/system` 调用,方法名通过 query 参数 `method` 传入。 - -### 请求方式 - -```http -POST /system?method=storage.receiving.bindDetailProduct&v=1.0×tamp={unix_timestamp} -Content-Type: application/json -Authorization: Bearer -platform: web -project: wms -``` - -### 调用示例 - -```bash -curl -X POST "http://127.0.0.1:6060/system?method=storage.receiving.bindDetailProduct&v=1.0×tamp=1712400000" \ - -H "Authorization: Bearer " \ - -H "Content-Type: application/json" \ - -H "platform: web" \ - -H "project: wms" \ - -d '{ - "detail_id": 12345, - "system_product_id": 67890 - }' -``` - -> 说明:该接口通常要求用户已登录,并以当前仓库角色执行;实际仓库上下文来自 `ctx.user.store_id`。 - ---- - -## 3. 接口:`storage.receiving.bindDetailProduct` - -### 3.1 接口用途 - -用于**绑定或改绑收货单明细的系统商品**。 - -调用成功后,系统会按当前仓库商品信息自动回填或更新以下内容: - -- `system_product_id` -- `product_name` -- `product_snapshot` -- `barcode`(有条码时) -- `weight`(商品存在毛重时) -- 箱规尺寸字段(启用箱规时) - -同时会刷新整张收货单的统计信息。 - -### 3.2 请求参数 - -| 字段 | 类型 | 必填 | 说明 | -|---|---:|---|---| -| `detail_id` | `number` | 是 | 收货单明细 ID | -| `id` | `number` | 否 | 兼容字段,可替代 `detail_id` | -| `system_product_id` | `number` | 是 | 要绑定的系统商品 ID(`StockWarehouse.id`) | - -### 3.3 请求体示例 - -```json -{ - "detail_id": 12345, - "system_product_id": 67890 -} -``` - ---- - -## 4. 成功返回示例 - -```json -{ - "flag": "success", - "code": 200, - "message": "绑定商品成功", - "data": { - "detail_id": 12345, - "receiving_id": 10001, - "system_product_id": 67890, - "product_name": "测试商品A" - } -} -``` - -### 返回字段说明 - -| 字段 | 类型 | 说明 | -|---|---:|---| -| `flag` | `string` | 固定为 `success` | -| `code` | `number` | 业务状态码,成功为 `200` | -| `message` | `string` | 返回说明 | -| `data.detail_id` | `number` | 当前绑定的收货单明细 ID | -| `data.receiving_id` | `number` | 收货单 ID | -| `data.system_product_id` | `number` | 当前绑定的系统商品 ID | -| `data.product_name` | `string` | 自动回填的商品名称 | - -> 注意:该项目的 system 方法经常返回 HTTP `200`,业务是否成功请以响应体内的 `code` 和 `message` 为准。 - ---- - -## 5. 业务校验规则 - -接口内部会执行以下校验: - -1. **当前用户必须有仓库上下文** - - 仓库 ID 取自 `ctx.user.store_id` -2. **收货单明细必须存在** -3. **收货单明细必须属于当前仓库** -4. **收货单状态必须为 `receiving`** - - 已完成、已作废等状态不允许继续绑定或改绑 -5. **目标商品必须属于当前仓库** - - 根据 `StockWarehouse.id + warehouse_id` 校验 - ---- - -## 6. 失败返回示例与错误码 - -### 常见失败场景 - -| `code` | `message` 示例 | 含义 | -|---:|---|---| -| `400` | `用户未绑定仓库` | 当前用户无仓库角色上下文 | -| `400` | `收货单明细ID不能为空` | 未传 `detail_id` / `id` | -| `400` | `商品ID不能为空` | 未传 `system_product_id` | -| `400` | `收货单状态不允许绑定或改绑商品` | 当前收货单状态不允许继续操作 | -| `404` | `收货单明细不存在` | 明细不存在或不属于当前仓库 | -| `404` | `商品不存在或不属于当前仓库` | 商品不存在或仓库不匹配 | -| `500` | `绑定商品失败: ` | 服务内部异常 | - -### 失败响应示例 - -```json -{ - "flag": "success", - "code": 404, - "message": "商品不存在或不属于当前仓库" -} -``` - ---- - -## 7. 推荐调用链路 - -典型前端操作顺序如下: - -1. `storage.receiving.create`:创建收货单 -2. `storage.receiving.addDetail`:新增空白明细,拿到 `selectId` -3. `storage.receiving.bindDetailProduct`:绑定系统商品 -4. `storage.receiving.detailChange`:补充数量、箱数、备注等字段 -5. `storage.receiving.completeReceiving`:完成收货 - -其中第 2 步新增明细后,一般会返回: - -```json -{ - "data": { - "selectId": 12345 - } -} -``` - -该 `selectId` 即可直接作为 `bindDetailProduct` 的 `detail_id`。 - ---- - -## 8. 回归验证参考 - -仓库中已有接口级回归用例,可作为联调参考: - -- `test/app/controller/system.storage.receiving.test.js` - -已覆盖的场景包括: - -- 新建收货单后绑定商品 -- 已绑定商品后再次改绑 -- 绑定成功后返回 `detail_id`、`system_product_id`、`product_name` - ---- - -## 9. 实现位置(源码定位) - -### system 方法包装层 - -- 文件:`app/service/systemMethods/storage/receiving.js` -- 方法:`bindDetailProduct(data)` - -### 实际业务实现 - -- 文件:`app/service/systems/storage/receiving.js` -- 方法:`bindDetailProduct(data)` - ---- - -## 10. 当前接口结论 - -`storage.receiving.bindDetailProduct` 当前已支持: - -- **绑定** 收货明细商品 -- **改绑** 收货明细商品 -- 自动回填商品名称、条码、重量、箱规等信息 -- 自动刷新收货单统计数据 - -适合作为收货单明细与系统商品标准匹配接口对外说明使用。 - ---- - -## 11. 接口:storage.receiving.detailChange - -### 11.1 接口用途 - -用于修改收货单明细(明细行)中的数量、箱规、批次与商品信息,并触发收货单统计与相关联动(例如库存/统计刷新与操作日志)。典型场景为:前端在录入收货明细后,补录实际收货数量、箱数、托盘数、批次/生产/到期信息或回写条码与商品名称等。 - -> 注意:方法在 system 层以 `POST /system?method=storage.receiving.detailChange` 调用,需包含 `Authorization: Bearer `,仓库上下文来源于 `ctx.user.store_id`。 - -### 11.2 请求参数 - -| 字段 | 类型 | 必填 | 说明 | -|---|---:|---:|---| -| `id` | `number` | 是 | 收货明细 ID(必填) | -| `receiving_id` | `number` | 是 | 收货单 ID(必填) | -| `actual_quantity` | `number` | 否 | 实际收货数量 | -| `batch_number` | `string` | 否 | 批次号 | -| `production_date` | `string` | 否 | 生产日期(ISO 或可解析的日期字符串) | -| `expiry_date` | `string` | 否 | 到期日期(ISO 或可解析的日期字符串)。若传入的 `expiry_date` 小于当前日期,接口会拒绝并返回 400(见错误码) | -| `box_quantity` | `number` | 否 | 箱数 | -| `boxes_per_pallet` | `number` | 否 | 每托盘箱数 | -| `pallet_quantity` | `number` | 否 | 托盘数 | -| `space_id` | `number` | 否 | 目标库位 ID(可用于回写库位) | -| `remark` | `string` | 否 | 备注 | -| `system_product_id` | `number` | 否 | 系统商品 ID(StockWarehouse.id)。若提供,系统会回填条码、重量、箱规、商品名称与快照等;若不提供,可单独更新 `barcode`/`product_name` | -| `barcode` | `string` | 否 | 条码(当未传 `system_product_id` 时,可单独更新) | -| `product_name` | `string` | 否 | 商品名称(当未传 `system_product_id` 时,可单独更新) | -| `box_width` | `number` | 否 | 箱宽(单位按系统约定) | -| `box_height` | `number` | 否 | 箱高 | -| `box_length` | `number` | 否 | 箱长 | -| `box_remainder` | `number` | 否 | 箱内剩余数量/零散数量(不满箱时的件数) | -| `box_weight` | `number` | 否 | 实测箱重(单位与系统重量一致,如 kg) | -| `weight` | `number` | 否 | 毛重/重量 | - -> 说明:`id` 与 `receiving_id` 为必须校验项,其他字段为可选—仅在传入时会写入/覆盖对应明细字段。传入 `system_product_id` 时,系统优先使用系统商品信息回填字段(前端可只传 `system_product_id` 来自动回填)。 - -### 11.3 请求示例 - -```json -{ - "id": 501, - "receiving_id": 123, - "actual_quantity": 10, - "batch_number": "B20260401", - "production_date": "2026-04-01", - "expiry_date": "2027-04-01", - "box_quantity": 2, - "boxes_per_pallet": 10, - "pallet_quantity": 0, - "space_id": 1001, - "remark": "样例备注", - "system_product_id": 8888 -} -``` - -### 11.4 返回结构(成功) - -成功时返回 `code: 200`,`message` 为 `修改成功`,`data` 中包含基础标识与关键展示字段: - -```json -{ - "code": 200, - "message": "修改成功", - "data": { - "id": 501, - "receiving_id": 123, - "actual_quantity": 1, - "product_name": "测试商品", - "barcode": "", - "system_product_id": null, - "box_remainder": 0, - "box_weight": 0.0, - "updated_at": "2026-04-01T00:00:00.000Z" - } -} -``` - -返回字段说明: - -- `data.id`:收货明细 ID -- `data.receiving_id`:收货单 ID -- `data.actual_quantity`:明细当前的实际收货数量(根据实现,此处返回服务端查询到的明细值) -- `data.product_name`:商品名称(若 `system_product_id` 回填则为系统商品名称) -- `data.barcode`:条码 -- `data.system_product_id`:回填或当前关联的系统商品 ID -- `data.box_remainder`:箱内剩余数量/零散数量(不满箱时的件数) -- `data.box_weight`:实测箱重(单位与系统重量一致) -- `data.updated_at`:明细记录的更新时间 - -### 11.5 常见错误码 - -| code | message 示例 | 含义 | -|---:|---|---| -| `400` | `收货明细ID不能为空` | 未传 `id` | -| `400` | `收货单ID不能为空` | 未传 `receiving_id` | -| `400` | `到期日期已过期,不能录入收货` | `expiry_date` 小于当前日期时返回(禁止录入已过期批次) | -| `400` | `箱数不能为负数` / `托盘数不能为负数` | 非法的箱规数值 | -| `404` | `收货明细不存在` | 明细不存在或不属于当前仓库/收货单状态不允许操作 | -| `500` | `修改失败,请稍后重试` | 服务端异常 | - ---- - -### 11.6 业务要点与实现说明 - -- 若传入 `system_product_id`,服务端尝试读取 `StockWarehouse`(同仓库)并回填:`barcode`(若前端未显式传入),`weight`,`boxes_per_pallet`、`box_height`、`box_width`、`box_length`(若启用箱规),以及 `product_snapshot` 中的货主快照信息。 -- 若未传 `system_product_id`,但传入 `barcode` 或 `product_name`,服务端仍允许更新这两个字段(并把 `system_product_id` 置为 `null`)。 -- 接口会在成功写入明细后触发收货单统计刷新(`updateReceivingStats`)并写操作日志(`RECEIVING_UPDATE_DETAIL`)。 -- 系统存在一个库存效期预警定时任务,逻辑上会扫描启用保质期管理且设置了剩余天数阈值的商品,并按库存到期日筛选候选记录后进行去重通知发送;其判断条件主要依赖 `wms_stock_warehouse.is_shelf_life_mgmt = 'Y'`、`remaining_threshold_days > 0`,以及 `wms_storage.expiry_date`(小于等于当前时间加最大阈值天数)。 - ---- - -## 12. 接口:storage.receiving.getReceivingDetail - -## 接口:storage.receiving.get - -### 用途 - -查询收货单完整信息(含明细 `details`、`images` 等)。 - -### 请求参数 - -| 字段 | 类型 | 必填 | 说明 | -|---|---:|---|---| -| `id` | `number` | 是 | 收货单 ID(source=body) | - -### 返回字段补充 - -- `data.details.*.box_remainder`:number,可选,箱内剩余数量/零散数量(不满箱时的件数),默认 0。 -- `data.details.*.box_weight`:number,可选,实测箱重(单位与系统重量一致,如 kg),默认 0。 - -兼容性:新增字段为可选,旧客户端无需变更。 - -### 12.1 用途 - -查询单张收货单详情,返回收货单头信息与明细(`details`),用于前端展示或二次处理。 - -### 12.2 请求参数 - -| 字段 | 类型 | 必填 | 说明 | -|---|---:|---|---| -| `id` | `number` | 是 | 收货单 ID | -| `pagination` | `object` | 否 | 明细分页参数,支持 `page` / `pageSize` | - -### 12.3 返回示例(成功) - -```json -{ - "code": 200, - "message": "success", - "data": { - "receiving": { - "id": 12345, - "receiving_number": "RCV20260506001", - "details": [ - { - "id": 501, - "product_name": "测试商品", - "actual_quantity": 10, - "box_quantity": 2, - "box_remainder": 0, - "box_weight": 5.2 - } - ], - "pagination": { - "page": 1, - "pageSize": 20, - "total": 1 - } - } - } -} -``` - -### 12.4 返回字段说明(新增) - -- `receiving.details.*.box_remainder`:number,可选,箱内剩余数量/零散数量(不满箱时的件数)。 -- `receiving.details.*.box_weight`:number,可选,实测箱重(单位与系统重量一致,如 kg)。 - -## 13. 接口:storage.receiving.completeReceiving - -### 13.1 用途 - -完成收货操作;完成后系统会发送内部通知/回调,通知中会包含收货单明细层面的箱规回写信息。 - -### 13.2 通知说明(新增字段) - -完成收货时发送的通知 payload/metadata 将在每条明细中包含 `box_remainder` 与 `box_weight`,用于下游系统或前端展示箱内余量与实测箱重。通知示例(结构化示例,字段以实现为准): - -```json -{ - "event": "storage.receiving.completed", - "receiving_id": 12345, - "details": [ - { - "id": 501, - "box_remainder": 0, - "box_weight": 5.2 - } - ], - "metadata": { - "completed_by": 1001, - "completed_at": "2026-05-06T12:00:00.000Z" - } -} -``` - -### 13.3 字段说明(通知/metadata) - -- `details[*].box_remainder`:number,可选,箱内剩余数量/零散数量。 -- `details[*].box_weight`:number,可选,实测箱重,单位同系统重量(例如 kg)。 - -兼容性:上述新增字段为可选字段,旧版消费者在未识别这些字段时可忽略。 - ---- - -## 14. 收货→入库完整流程 - -### 14.1 流程概览 - -收货完成后,商品库存的实际入库通过以下步骤完成: - -1. **创建入库单** → `storage.entry` 系列方法(list/get/cancel/completeEntry) -2. **匹配入库(写库存)** → `storage.inventory.matchPutaway`(**目前唯一的库存写入入库链路**) - -> ⚠️ 注意:`storage.entry.completeEntry` 仅做入库单状态变更(PENDING → COMPLETED),**不涉及库存写入**。库存的实际写入统一由 `storage.inventory.matchPutaway` 完成。 - -### 14.2 完整推荐流程 - -``` -1. storage.receiving.create → 创建收货单 -2. storage.receiving.addDetail → 新增明细,拿到 selectId -3. storage.receiving.bindDetailProduct → 绑定系统商品 -4. storage.receiving.detailChange → 补充数量、批次等 -5. storage.receiving.completeReceiving → 完成收货 - ↓ -6. storage.entry 入库单管理 → 入库单与收货单通过 wms_entry_order_receiving 主表级关联 -7. storage.inventory.matchPutaway → 收货单与入库单匹配,完成库存写入 -8. storage.entry.completeEntry → 入库单状态标记为 COMPLETED(仅状态变更) -``` - -### 14.3 已弃用的方法 - -以下方法已从代码中移除,**不再可用**: - -| 已弃用方法 | 弃用原因 | 替代方案 | -|---|---|---| -| `storage.entry.bindReceivingDetails` | 入库单明细与收货明细逐行绑定(基于 `wms_entry_receiving_binding` 表),关系已改为 `wms_entry_order_receiving` 主表级关联 | 不再需要,入库单与收货单直接通过主表关联 | -| `storage.entry.unbindReceivingDetails` | 同上,逐行解绑已无必要 | 不再需要 | -| `storage.inventory.quickPutaway` | 单一收货单快捷转入库单(已重新实现):按 stock_id 合并收货明细创建入库单(SCRK,自动审批到 PENDING),写入主表级绑定 | `storage.entry.commitDirectInbound`(导入/PDA 入库完成确认) | - -### 14.4 核心方法职责 - -| 方法 | 职责 | 备注 | -|---|---|---| -| `storage.inventory.matchPutaway` | **唯一库存写入入库链路**:接收多个收货单和多个入库单,按商品进行数量匹配,完成库存的实际写入 | 入库后根据来源(QM/API)自动触发回传 | -| `storage.entry.completeEntry` | **仅状态变更**:入库单 PENDING → COMPLETED | 不涉及任何库存写入 | -| `storage.entry.list` | 入库单列表查询 | 支持 CREATING/CREATED/PENDING/COMPLETED/CANCELLED 状态筛选 | -| `storage.entry.get` | 入库单详情查询 | 含 items 及其 bindings | -| `storage.entry.cancel` | 作废入库单(CREATED/PENDING 可作废) | COMPLETED 不可作废 | - -### 14.5 关键数据库表关系 - -- `wms_entry_order_receiving`:入库单与收货单的**主表级关联**(当前方案) -- `wms_entry_receiving_binding`:**已弃用**,不再写入新数据(旧方案:明细级绑定) -- 收货单与入库单不再需要逐明细绑定,通过主表关联即可完成匹配入库 - diff --git a/methods/changes/system.json b/methods/changes/system.json index 85d490c..5956315 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -4673,5 +4673,47 @@ "文档中 isNeedLogin 为 false,但代码 systemMethods/quick/waybill.js 中 _noNeedLogin 为空字符串,未将 toOrder 加入免登录列表,实际需要登录验证,修正文档以与代码一致。" ], "type": "fixed" + }, + { + "version": "2026.07.03-system-01", + "date": "2026-07-03", + "summary": "binding 表弃用文档同步:wms_entry_receiving_binding 已弃用,功能迁移到 wms_inbound_direct_log 表;bindings 描述中表引用更新为 InboundDirectLog", + "methods": [ + "storage.entry.getDirectInboundItems" + ], + "notes": [ + "bindings 数组 description 中 wms_entry_receiving_binding 引用更新为 InboundDirectLog,明确旧表已弃用", + "binding_id description 中 wms_entry_receiving_binding.id 更新为 InboundDirectLog.id", + "allocated_quantity description 中补充来源 InboundDirectLog.quantity", + "wms_inbound_direct_log 表新增字段:entry_item_id、receiving_detail_id、status(ENUM: pending/committed/released)、updated_at、deleted_at" + ], + "type": "updated" + }, + { + "version": "2026.07.03-system-02", + "date": "2026-07-03", + "summary": "binding 表弃用文档同步:wms_entry_receiving_binding 已弃用,功能迁移到 wms_inbound_direct_log 表;bindings 描述中表引用更新为 InboundDirectLog", + "methods": [ + "storage.directInbound.getItems" + ], + "notes": [ + "bindings 数组 description 中更新为来自 InboundDirectLog,明确旧表已弃用", + "binding_id description 更新为 InboundDirectLog.id", + "allocated_quantity description 中补充来源 InboundDirectLog.quantity", + "wms_inbound_direct_log 表新增字段:entry_item_id、receiving_detail_id、status(ENUM: pending/committed/released)、updated_at、deleted_at" + ], + "type": "updated" + }, + { + "version": "2026.07.03-system-03", + "date": "2026-07-03", + "summary": "binding 表弃用文档同步:commitDirectInbound 描述中 EntryReceivingBinding 更新为 InboundDirectLog", + "methods": [ + "storage.entry.commitDirectInbound" + ], + "notes": [ + "commitDirectInbound description 中将 pending 状态的 EntryReceivingBinding 更新为 pending 状态的 InboundDirectLog,与代码实现一致" + ], + "type": "updated" } ] diff --git a/methods/system.json b/methods/system.json index afe7198..49fc145 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1,8 +1,8 @@ { "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", - "version": "0.3.5", - "updatedAt": "2026-07-02", + "version": "0.3.6", + "updatedAt": "2026-07-03", "headers": [ { "name": "platform", @@ -2708,6 +2708,82 @@ "description": "订单不存在或不属于当前仓库" } ] + }, + { + "method": "reviewOrder.detail", + "description": "查询单个订单详情,返回订单头、商品明细和运单信息", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids / id / order_id / orderId", + "type": "array|string|number", + "required": true, + "source": "body", + "description": "订单ID;支持 ids 数组、逗号分隔字符串或单个 id/order_id,至少提供一项" + }, + { + "name": "tableType / tablePosition / type / moduleName", + "type": "string", + "required": false, + "source": "body", + "description": "可选,指定订单表类型,支持 current/history/dispatch/outsourced/order/revieworder/pendingorder 等" + } + ], + "response": [ + { + "name": "order", + "type": "object", + "required": true, + "description": "订单头对象(raw 行数据)" + }, + { + "name": "detail", + "type": "object", + "required": true, + "description": "等同于 order" + }, + { + "name": "orderItems / items", + "type": "array", + "required": true, + "description": "商品明细数组" + }, + { + "name": "expresses", + "type": "array", + "required": true, + "description": "运单信息数组" + }, + { + "name": "waybill_codes", + "type": "array", + "required": true, + "description": "去重后的运单号字符串数组" + } + ], + "errors": [ + { + "code": "400", + "message": "订单ID 为空或格式错误" + }, + { + "code": "404", + "message": "订单不存在或不属于当前仓库" + }, + { + "code": "500", + "message": "内部错误" + } + ] } ] }, @@ -18892,9 +18968,90 @@ ] }, { - "groupName": "入库管理", + "groupName": "入库模块", "module": "storage.entry", "list": [ + { + "method": "storage.entry.list", + "description": "入库单列表查询。where.order_status 支持 CREATING/CREATED/PENDING/COMPLETED/CANCELLED。CREATED=已创建待审核(需审核后才能绑定和完成入库),PENDING=已审核(可绑定和完成入库)。where 新增 hasReceiving 虚拟筛选字段,传 true/false 筛选已绑定/未绑定收货单的入库单(通过 wms_entry_order_receiving 表查询实现)。quickWhere 支持模糊搜索:entry_order_code(入库单号)、purchase_order_code(采购单号)、supplier_name(供应商名称)、store_name(货主名称)、warehouse_name(仓库名称)、receiving_id(收货单 ID / 托盘唛头,通过 wms_entry_order_receiving 绑定表关联搜索)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数,支持 page/pageSize" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会在 main 中自动标准化;支持 quickWhere、order_status(CREATING/CREATED/PENDING/COMPLETED/CANCELLED)、store_id、order_type、日期区间等字段。新增 expense_record(费用是否记录)筛选,支持 eq/in;值会归一化为 0/1,兼容 true/false、1/0、y/n、yes/no(大小写不敏感,含布尔/字符串/数字写法)。示例:where.expense_record={operator:eq,value:true} 等价 where.expense_record={operator:eq,value:1};where.expense_record={operator:in,value:[true,\"0\",\"yes\",\"n\"]} 会归一化为 [1,0]。若部署环境尚未完成 expense_record 字段迁移,传入该筛选可能返回 400,错误提示为\"当前环境未提供 expense_record 字段,暂不支持该筛选条件,请先完成表结构升级\"。新增 hasReceiving 虚拟筛选字段,传 true/false 筛选已绑定/未绑定收货单的入库单(虚拟字段,不直接对应数据库列,内部通过 wms_entry_order_receiving 表查询实现)。quickWhere 模糊搜索范围:entry_order_code(入库单号)、purchase_order_code(采购单号)、supplier_name(供应商名称)、store_name(货主名称)、warehouse_name(仓库名称)、receiving_id(收货单 ID / 托盘唛头,通过 wms_entry_order_receiving 绑定表关联搜索)。" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数,支持 sortField/sortOrder" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "入库单列表" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息(page、pageSize、total、totalPages、hasPrevious、hasNext)" + }, + { + "name": "summary", + "type": "object", + "required": true, + "description": "状态汇总(total、pending、creating、created、completed、cancelled)" + }, + { + "name": "list[].receivingBindings", + "type": "array", + "required": false, + "description": "收货单绑定列表(主表级关联),每项含 id、entry_order_id、receiving_id 及 receiving 对象(id、receiving_number、status、storage_status、created_at)" + }, + { + "name": "list[].hasReceiving", + "type": "boolean", + "required": false, + "description": "是否存在收货单绑定" + } + ], + "errors": [ + { + "code": "400", + "message": "筛选条件格式错误", + "description": "筛选条件格式错误" + }, + { + "code": "500", + "message": "查询失败", + "description": "查询失败" + } + ] + }, { "method": "storage.entry.get", "description": "查询入库单详情。返回的 entryOrder 包含顶层 receivingBindings(主表级关联,含关联的收货单信息),不再返回 items[].bindings(明细级绑定)。entryOrder.order_status 可能为 CREATING/CREATED/PENDING/COMPLETED/CANCELLED。CREATED=已创建待审核(需审核后才能绑定和完成入库),PENDING=已审核(可绑定和完成入库)。", @@ -19156,175 +19313,6 @@ } ] }, - { - "method": "storage.entry.getDirectInboundItems", - "description": "获取入库单的导入/PDA 入库信息(精简版)。返回入库单基本信息、明细列表(含计划数量 planned 与已完成数量 completed)、每项明细的收货绑定列表 bindings(含 detail_id、binding_id、allocated_quantity、space_id、space_name),以及收货单绑定关系 receivingBindings。", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "entry_order_code", - "type": "string", - "required": true, - "source": "body", - "description": "入库单号" - } - ], - "response": [ - { - "name": "entryOrder", - "type": "object", - "required": true, - "description": "入库单基本信息", - "children": [ - { - "name": "id", - "type": "number", - "required": true, - "description": "入库单ID" - }, - { - "name": "entry_order_code", - "type": "string", - "required": true, - "description": "入库单号" - }, - { - "name": "order_status", - "type": "string", - "required": true, - "description": "入库单状态(CREATED/PENDING/COMPLETED/CANCELLED)" - }, - { - "name": "store_remask", - "type": "string", - "required": true, - "description": "货主商家备注" - } - ] - }, - { - "name": "items", - "type": "array", - "required": true, - "description": "入库明细列表", - "children": [ - { - "name": "id", - "type": "number", - "required": true, - "description": "入库明细ID(wms_entry_items.id)" - }, - { - "name": "stock_id", - "type": "number", - "required": true, - "description": "商品SKU ID" - }, - { - "name": "planned", - "type": "number", - "required": true, - "description": "计划入库数量(对应原 count 字段)" - }, - { - "name": "completed", - "type": "number", - "required": true, - "description": "已完成导入/PDA 入库数量(对应原 direct_inbound_quantity 字段)" - }, - { - "name": "stock", - "type": "object", - "required": true, - "description": "商品详情(含 item_code、item_name、sku_property、barcodes 等缓存字段)" - }, - { - "name": "bindings", - "type": "array", - "required": true, - "description": "该明细的收货单绑定列表(来自 wms_entry_receiving_binding + InboundDirectLog)", - "children": [ - { - "name": "detail_id", - "type": "number", - "required": false, - "description": "收货明细ID(wms_receiving_detail.id),无绑定时可能不存在" - }, - { - "name": "binding_id", - "type": "number", - "required": false, - "description": "绑定记录ID(wms_entry_receiving_binding.id),无绑定时可能不存在" - }, - { - "name": "allocated_quantity", - "type": "number", - "required": false, - "description": "预分配数量" - }, - { - "name": "space_id", - "type": "number", - "required": false, - "description": "存放库位ID(取自 InboundDirectLog)" - }, - { - "name": "space_name", - "type": "string", - "required": false, - "description": "库位名称(取自 wms_location_space.custom_name 或 space_code)" - } - ] - } - ] - }, - { - "name": "receivingBindings", - "type": "array", - "required": true, - "description": "入库单层级的收货单绑定关系列表(wms_entry_order_receiving)", - "children": [ - { - "name": "id", - "type": "number", - "required": true, - "description": "绑定记录ID" - }, - { - "name": "receiving_id", - "type": "number", - "required": true, - "description": "收货单ID" - }, - { - "name": "receiving", - "type": "object", - "required": true, - "description": "收货单信息(id、receiving_number、status、storage_status、created_at)" - } - ] - } - ], - "errors": [ - { - "code": 400, - "message": "entry_order_code 必填" - }, - { - "code": 404, - "message": "入库单不存在或无权访问" - } - ] - }, { "method": "storage.entry.addDirectInboundItem", "description": "按商品增量添加导入/PDA 入库记录(支持单条和批量)。单条模式传 stock_id/quantity/inbound_type/remark,批量模式传 items 数组。批量模式所有商品共享同一个入库单状态校验,任一商品校验失败整批拒绝。若某商品累计入库量超过计划数量则拒绝(PENDING 非绑定模式)。PENDING 状态需传 receiving_detail_id 绑定收货明细;CREATED 人工导入允许超过计划数量;传入 receiving_detail_id 时 quantity 可选(自动计算可用数量),space_id 必填。", @@ -19532,7 +19520,7 @@ }, { "method": "storage.entry.commitDirectInbound", - "description": "提交确认完成导入/PDA 入库。先同步奇门/API 回传,成功后在 onSuccess 回调内开启事务写入库存(wms_stock_warehouse.quantity 增量、wms_stock_transaction 流水),将 pending 状态的 EntryReceivingBinding 更新为 committed,更新入库单状态为 COMPLETED,同步 sync_status=SUCCESS。不足量提交时未入库商品跳过。", + "description": "提交确认完成导入/PDA 入库。先同步奇门/API 回传,成功后在 onSuccess 回调内开启事务写入库存(wms_stock_warehouse.quantity 增量、wms_stock_transaction 流水),将 pending 状态的 InboundDirectLog 更新为 committed,更新入库单状态为 COMPLETED,同步 sync_status=SUCCESS。不足量提交时未入库商品跳过。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -20320,458 +20308,6 @@ } ] }, - { - "groupName": "导入/PDA直接入库", - "module": "storage.directInbound", - "list": [ - { - "method": "storage.directInbound.getItems", - "description": "[@deprecated 已弃用,请使用 storage.entry.getDirectInboundItems 替代] 获取入库单的导入/PDA 入库信息(精简版)。返回入库单基本信息、明细列表(含计划数量 planned 与已完成数量 completed)、每项明细的收货绑定列表 bindings(含 detail_id、binding_id、allocated_quantity、space_id、space_name),以及收货单绑定关系 receivingBindings。", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "entry_order_code", - "type": "string", - "required": true, - "source": "body", - "description": "入库单号" - } - ], - "response": [ - { - "name": "entryOrder", - "type": "object", - "required": true, - "description": "入库单基本信息", - "children": [ - { - "name": "id", - "type": "number", - "required": true, - "description": "入库单ID" - }, - { - "name": "entry_order_code", - "type": "string", - "required": true, - "description": "入库单号" - }, - { - "name": "order_status", - "type": "string", - "required": true, - "description": "入库单状态(CREATED/PENDING/COMPLETED/CANCELLED)" - }, - { - "name": "store_remask", - "type": "string", - "required": true, - "description": "货主商家备注" - } - ] - }, - { - "name": "items", - "type": "array", - "required": true, - "description": "入库明细列表", - "children": [ - { - "name": "id", - "type": "number", - "required": true, - "description": "入库明细ID(wms_entry_items.id)" - }, - { - "name": "stock_id", - "type": "number", - "required": true, - "description": "商品SKU ID" - }, - { - "name": "planned", - "type": "number", - "required": true, - "description": "计划入库数量(对应原 count 字段)" - }, - { - "name": "completed", - "type": "number", - "required": true, - "description": "已完成导入/PDA 入库数量(对应原 direct_inbound_quantity 字段)" - }, - { - "name": "stock", - "type": "object", - "required": true, - "description": "商品详情(含 item_code、item_name、sku_property、barcodes 等缓存字段)" - }, - { - "name": "bindings", - "type": "array", - "required": true, - "description": "该明细的收货单绑定列表", - "children": [ - { - "name": "detail_id", - "type": "number", - "required": false, - "description": "收货明细ID" - }, - { - "name": "binding_id", - "type": "number", - "required": false, - "description": "绑定记录ID" - }, - { - "name": "allocated_quantity", - "type": "number", - "required": false, - "description": "预分配数量" - }, - { - "name": "space_id", - "type": "number", - "required": false, - "description": "存放库位ID" - }, - { - "name": "space_name", - "type": "string", - "required": false, - "description": "库位名称" - } - ] - } - ] - }, - { - "name": "receivingBindings", - "type": "array", - "required": true, - "description": "入库单层级的收货单绑定关系列表", - "children": [ - { - "name": "id", - "type": "number", - "required": true, - "description": "绑定记录ID" - }, - { - "name": "receiving_id", - "type": "number", - "required": true, - "description": "收货单ID" - }, - { - "name": "receiving", - "type": "object", - "required": true, - "description": "收货单信息(id、receiving_number、status、storage_status、created_at)" - } - ] - } - ], - "errors": [ - { - "code": 400, - "message": "entry_order_code 必填" - }, - { - "code": 404, - "message": "入库单不存在或无权访问" - } - ] - }, - { - "method": "storage.directInbound.addItem", - "description": "[@deprecated 已弃用,请使用 storage.entry.addDirectInboundItem 替代] 按商品增量添加导入/PDA 入库记录(支持单条和批量)。单条模式传 stock_id/quantity/inbound_type/remark,批量模式传 items 数组。批量模式所有商品共享同一个入库单状态校验,任一商品校验失败整批拒绝。若某商品累计入库量超过计划数量则拒绝。", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "entry_order_id", - "type": "number", - "required": true, - "source": "body", - "description": "入库单 ID(必填,通过主键查找入库单)" - }, - { - "name": "stock_id", - "type": "number", - "required": true, - "source": "body", - "description": "商品SKU ID(对应 wms_stock_warehouse.id)" - }, - { - "name": "quantity", - "type": "number", - "required": true, - "source": "body", - "description": "本次入库数量(正整数)" - }, - { - "name": "inbound_type", - "type": "string", - "required": true, - "source": "body", - "description": "入库方式:import(导入入库)、pda(PDA入库)" - }, - { - "name": "remark", - "type": "string", - "required": false, - "source": "body", - "description": "备注(如导入文件名、PDA操作备注等)" - }, - { - "name": "space_id", - "type": "number", - "required": false, - "source": "body", - "description": "存放库位ID(单条模式),关联 wms_location_space.id;为空时 commit 默认使用库位 1" - }, - { - "name": "items", - "type": "array", - "required": false, - "source": "body", - "description": "批量模式:商品列表,每项包含 stock_id(商品SKU ID, number, 必填)、quantity(入库数量, number, 必填)、inbound_type(import/pda, string, 必填)、space_id(库位ID, number, 可选)、remark(备注, string, 可选)。传入 items 时忽略顶层的 stock_id/quantity/inbound_type/remark/space_id。" - } - ], - "response": [ - { - "name": "id", - "type": "number", - "required": false, - "description": "单条模式返回:新增的入库记录ID" - }, - { - "name": "stock_id", - "type": "number", - "required": false, - "description": "单条模式返回:商品SKU ID" - }, - { - "name": "quantity", - "type": "number", - "required": false, - "description": "单条模式返回:本次入库数量" - }, - { - "name": "inbound_type", - "type": "string", - "required": false, - "description": "单条模式返回:入库方式" - }, - { - "name": "plan_quantity", - "type": "number", - "required": false, - "description": "单条模式返回:该商品计划入库总数" - }, - { - "name": "existing_before", - "type": "number", - "required": false, - "description": "单条模式返回:本次入库前已入库数量" - }, - { - "name": "existing_after", - "type": "number", - "required": false, - "description": "单条模式返回:本次入库后总入库数量" - }, - { - "name": "remaining", - "type": "number", - "required": false, - "description": "单条模式返回:剩余可入库数量" - }, - { - "name": "count", - "type": "number", - "required": false, - "description": "批量模式返回:成功添加的条目数" - }, - { - "name": "total_quantity", - "type": "number", - "required": false, - "description": "批量模式返回:入库总数量" - }, - { - "name": "items", - "type": "array", - "required": false, - "description": "批量模式返回:入库结果列表,每项包含 id/stock_id/quantity/inbound_type/space_id/plan_quantity/existing_before/existing_after/remaining" - } - ], - "errors": [ - { - "code": 400, - "message": "参数校验失败:entry_order_code 必填 / stock_id 必填 / quantity 必须为正整数 / inbound_type 必须为 import 或 pda / 已作废入库单不允许操作 / 已完成的入库单不允许操作 / 入库单中不存在该 stock_id 的商品 / 入库数量超过计划" - }, - { - "code": 404, - "message": "入库单不存在或无权访问" - } - ] - }, - { - "method": "storage.directInbound.commit", - "description": "[@deprecated 已弃用,请使用 storage.entry.commitDirectInbound 替代] 提交确认完成导入/PDA 入库。按实收数量写入库存(wms_storage、wms_stock_transaction),未入库商品跳过不做处理,更新入库单状态为 COMPLETED,并异步触发奇门/API 入库完成回传(按实收数量回传)。", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "entry_order_id", - "type": "number", - "required": true, - "source": "body", - "description": "入库单 ID" - } - ], - "response": [ - { - "name": "id", - "type": "number", - "required": true, - "description": "入库单ID" - }, - { - "name": "entry_order_code", - "type": "string", - "required": true, - "description": "入库单号" - }, - { - "name": "order_status", - "type": "string", - "required": true, - "description": "入库单状态(固定为 COMPLETED)" - }, - { - "name": "sync_status", - "type": "string", - "required": true, - "description": "同步状态(固定为 SUCCESS)" - }, - { - "name": "items_count", - "type": "number", - "required": true, - "description": "入库商品种类数" - }, - { - "name": "total_quantity", - "type": "number", - "required": true, - "description": "入库总数量" - } - ], - "errors": [ - { - "code": 400, - "message": "entry_order_id 必填" - }, - { - "code": 400, - "message": "已作废入库单不允许完成 / 入库单已完成请勿重复提交 / 暂无导入/PDA 入库记录请先添加商品 / 入库单无明细" - }, - { - "code": 404, - "message": "入库单不存在或无权访问" - } - ] - }, - { - "method": "storage.directInbound.removeItem", - "description": "[@deprecated 已弃用,请使用 storage.entry.removeDirectInboundItem 替代] 移除一条导入/PDA 入库记录(仅限未提交的入库单,即状态非 CANCELLED/COMPLETED)。移除后该商品的可入库余量自动恢复。", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "id", - "type": "number", - "required": true, - "source": "body", - "description": "入库记录ID(wms_inbound_direct_log.id)" - } - ], - "response": [ - { - "name": "id", - "type": "number", - "required": true, - "description": "已移除的入库记录ID" - }, - { - "name": "stock_id", - "type": "number", - "required": true, - "description": "商品SKU ID" - }, - { - "name": "quantity", - "type": "number", - "required": true, - "description": "移除的入库数量" - }, - { - "name": "inbound_type", - "type": "string", - "required": true, - "description": "入库方式" - } - ], - "errors": [ - { - "code": 400, - "message": "id 必填 / 已作废入库单不允许操作 / 已完成的入库单不允许移除记录" - }, - { - "code": 404, - "message": "入库记录不存在 / 关联入库单不存在或无权访问" - } - ] - } - ] - }, { "groupName": "出库单模块", "module": "storage.stockout", @@ -26348,93 +25884,6 @@ } ] }, - { - "groupName": "入库模块", - "module": "storage", - "list": [ - { - "method": "storage.entry.list", - "description": "入库单列表查询。where.order_status 支持 CREATING/CREATED/PENDING/COMPLETED/CANCELLED。CREATED=已创建待审核(需审核后才能绑定和完成入库),PENDING=已审核(可绑定和完成入库)。where 新增 hasReceiving 虚拟筛选字段,传 true/false 筛选已绑定/未绑定收货单的入库单(通过 wms_entry_order_receiving 表查询实现)。quickWhere 支持模糊搜索:entry_order_code(入库单号)、purchase_order_code(采购单号)、supplier_name(供应商名称)、store_name(货主名称)、warehouse_name(仓库名称)、receiving_id(收货单 ID / 托盘唛头,通过 wms_entry_order_receiving 绑定表关联搜索)。", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "pagination", - "type": "object", - "required": false, - "source": "body", - "description": "分页参数,支持 page/pageSize" - }, - { - "name": "where", - "type": "object", - "required": false, - "source": "body", - "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会在 main 中自动标准化;支持 quickWhere、order_status(CREATING/CREATED/PENDING/COMPLETED/CANCELLED)、store_id、order_type、日期区间等字段。新增 expense_record(费用是否记录)筛选,支持 eq/in;值会归一化为 0/1,兼容 true/false、1/0、y/n、yes/no(大小写不敏感,含布尔/字符串/数字写法)。示例:where.expense_record={operator:eq,value:true} 等价 where.expense_record={operator:eq,value:1};where.expense_record={operator:in,value:[true,\"0\",\"yes\",\"n\"]} 会归一化为 [1,0]。若部署环境尚未完成 expense_record 字段迁移,传入该筛选可能返回 400,错误提示为\"当前环境未提供 expense_record 字段,暂不支持该筛选条件,请先完成表结构升级\"。新增 hasReceiving 虚拟筛选字段,传 true/false 筛选已绑定/未绑定收货单的入库单(虚拟字段,不直接对应数据库列,内部通过 wms_entry_order_receiving 表查询实现)。quickWhere 模糊搜索范围:entry_order_code(入库单号)、purchase_order_code(采购单号)、supplier_name(供应商名称)、store_name(货主名称)、warehouse_name(仓库名称)、receiving_id(收货单 ID / 托盘唛头,通过 wms_entry_order_receiving 绑定表关联搜索)。" - }, - { - "name": "sort", - "type": "object", - "required": false, - "source": "body", - "description": "排序参数,支持 sortField/sortOrder" - } - ], - "response": [ - { - "name": "list", - "type": "array", - "required": true, - "description": "入库单列表" - }, - { - "name": "pagination", - "type": "object", - "required": true, - "description": "分页信息(page、pageSize、total、totalPages、hasPrevious、hasNext)" - }, - { - "name": "summary", - "type": "object", - "required": true, - "description": "状态汇总(total、pending、creating、created、completed、cancelled)" - }, - { - "name": "list[].receivingBindings", - "type": "array", - "required": false, - "description": "收货单绑定列表(主表级关联),每项含 id、entry_order_id、receiving_id 及 receiving 对象(id、receiving_number、status、storage_status、created_at)" - }, - { - "name": "list[].hasReceiving", - "type": "boolean", - "required": false, - "description": "是否存在收货单绑定" - } - ], - "errors": [ - { - "code": "400", - "message": "筛选条件格式错误", - "description": "筛选条件格式错误" - }, - { - "code": "500", - "message": "查询失败", - "description": "查询失败" - } - ] - } - ] - }, { "groupName": "快捷操作", "module": "quick", diff --git a/skills/entry-order-test-guide.md b/skills/entry-order-test-guide.md index 163288c..3638961 100644 --- a/skills/entry-order-test-guide.md +++ b/skills/entry-order-test-guide.md @@ -276,8 +276,8 @@ curl -s -X POST "http://localhost:6060/system?method=storage.entry.quickInbound" | `wms_receiving` | 收货单主表 | id, receiving_code, status, store_id | | `wms_receiving_detail` | 收货单明细 | id, receiving_id, product_name, actual_quantity | | `wms_entry_order_receiving` | 入库单↔收货单主表绑定 | id, entry_id, receiving_id | -| `wms_entry_receiving_binding` | 入库明细↔收货明细绑定 | id, entry_item_id, receiving_detail_id, quantity | -| `wms_inbound_direct_log` | PDA直入记录 | id, entry_id, item_code, quantity, space_id, receiving_detail_id | +| `wms_entry_receiving_binding` | [已弃用] 入库明细↔收货明细绑定(已迁至 InboundDirectLog) | id, entry_item_id, receiving_detail_id, quantity | +| `wms_inbound_direct_log` | PDA直入记录 + 入库明细↔收货明细绑定 | id, entry_id, entry_item_id, item_code, quantity, space_id, receiving_detail_id, status, updated_at, deleted_at | | `wms_api_app` | 奇门应用绑定配置 | id, app_key, app_secret, warehouse_id, store_id | | `wms_operation_log` | 操作日志 | id, target_type, target_id, action, operator, created_at | From 962e06787fd7a97b2ec1b778e826c6aec2bd3a03 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Fri, 3 Jul 2026 16:11:39 +0800 Subject: [PATCH 082/550] 1 --- .../repo/entry-receiving-match-callback.md | 28 ------------------- .../repo/express-platform-code-routing.md | 4 --- memories/repo/stock-detail-cache-service.md | 27 ------------------ 3 files changed, 59 deletions(-) delete mode 100644 memories/repo/entry-receiving-match-callback.md delete mode 100644 memories/repo/express-platform-code-routing.md delete mode 100644 memories/repo/stock-detail-cache-service.md diff --git a/memories/repo/entry-receiving-match-callback.md b/memories/repo/entry-receiving-match-callback.md deleted file mode 100644 index 08e4df0..0000000 --- a/memories/repo/entry-receiving-match-callback.md +++ /dev/null @@ -1,28 +0,0 @@ -# 入库单完成 → 异步匹配收货单并回传 - -## 实现日期 -2026-06-18 - -## 涉及文件 - -### 新建 -- `app/service/systems/receiving_entry_match.js` — 核心匹配与回传服务 - -### 修改 -- `app/service/systems/entry_order.js` — `entryorderConfirm()` 事务提交后触发异步匹配 -- `app/service/systems/storage/entry.js` — `completeEntry()` 状态更新后触发异步匹配 -- `app/service/systems/storage/receiving.js` — `completeReceiving()` 事务提交后清除收货单缓存 - -## 核心流程 -1. 入库单完成(COMPLETED)→ `setImmediate` 异步触发 `matchAfterEntryCompleted` -2. 从 Redis 缓存读取仓库近 3 天收货单列表(key: `cache:receiving_orders:warehouse:{warehouseId}`,TTL: 300s) -3. 根据入库单 `remark` 字符串包含匹配收货单号 -4. 对比明细 SKU + 数量 → full_match / receiving_covers_entry / 其他 -5. full_match / receiving_covers_entry → 按来源回传(QM 奇门 / API OpenAPI) -6. receiving_covers_entry → 标记收货单为"部分入库"(storage_status=partial) -7. 收货单完成时主动清除对应仓库缓存 - -## 注意事项 -- 异步执行,不阻塞主流程 -- 所有错误仅记录日志,不影响业务 -- 缓存回退:Redis 不可用时直接查询数据库 diff --git a/memories/repo/express-platform-code-routing.md b/memories/repo/express-platform-code-routing.md deleted file mode 100644 index 247a13f..0000000 --- a/memories/repo/express-platform-code-routing.md +++ /dev/null @@ -1,4 +0,0 @@ -- 运单分组链路必须是:订单的 sys_platform_code -> wms_platform.print_platform_id -> wms_print_platform.platform_code。 -- 快递接口匹配与 listByWarehousePlatformCode 的 platform_code 必须使用 wms_print_platform.platform_code,不可直接回退为 sys_platform_code。 -- 分组维度必须使用 wms_print_platform.platform_code + logistics_code;如果缺少打印平台映射,应视为缺少有效匹配上下文,而不是改回 sys_platform_code 直连。 -- 相关代码锚点:app/service/systems/express.js、app/service/systems/platform.js、app/model/express_interface.js。 diff --git a/memories/repo/stock-detail-cache-service.md b/memories/repo/stock-detail-cache-service.md deleted file mode 100644 index 36a1591..0000000 --- a/memories/repo/stock-detail-cache-service.md +++ /dev/null @@ -1,27 +0,0 @@ -# 商品明细缓存公共服务(stock_warehouse.js) - -## 文件位置 -`app/service/systems/stock_warehouse.js` - -## 对外方法 - -### `getStockDetails(stockIds, options)` -批量获取仓库商品详情(含 StockWarehouse + StockBarcode + 图片),带 Redis 缓存,差量增补。 - -- **缓存 key**:`cache:stock_detail:{warehouseId}:{stockId}` -- **TTL 默认**:300 秒 -- **调用方式**: - ```js - ctx.service.systems.stock_warehouse.getStockDetails(stockIds, { warehouseId, cacheTTL }) - ``` - -### `invalidateStockDetailCache(stockId, warehouseId)` -清除指定商品缓存。 - -- **调用时机**:商品资料更新、图片变更、条码变更时调用 - -### `_buildStockDetailCacheKey(warehouseId, stockId)` -内部工具方法,构建缓存 key。 - -## 设计思想 -作为仓库级公共服务,入库单、出库单、盘点、移库等所有模块都可以复用这个缓存方法,避免各处重复查询 StockWarehouse + StockBarcode。 From 5d7964132e17a2491f99ac440e588568d2f49e64 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Fri, 3 Jul 2026 16:56:39 +0800 Subject: [PATCH 083/550] 1 --- _diag6.cjs | 18 - app/service/systemMethods/index.js | 18 +- .../systemMethods/order/pendingOrder.js | 1 + .../systemMethods/order/recheckOrder.js | 2 +- app/service/systemMethods/quick/waybill.js | 35 -- app/service/systemMethods/storage/entry.js | 10 +- app/service/systems/order_express.js | 98 +++- app/service/systems/quick/waybill.js | 42 -- app/service/systems/storage/entry.js | 6 +- app/service/systems/waybill.js | 131 +++++ methods/changes/system.json | 82 +++- methods/system.json | 309 ++++-------- skills/entry-order-test-guide.md | 449 ------------------ tmp/verify_migration.cjs | 37 -- 14 files changed, 391 insertions(+), 847 deletions(-) delete mode 100644 _diag6.cjs delete mode 100644 app/service/systemMethods/quick/waybill.js delete mode 100644 app/service/systems/quick/waybill.js create mode 100644 app/service/systems/waybill.js delete mode 100644 skills/entry-order-test-guide.md delete mode 100644 tmp/verify_migration.cjs diff --git a/_diag6.cjs b/_diag6.cjs deleted file mode 100644 index cc5f93d..0000000 --- a/_diag6.cjs +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; -const { loadDeployConfig, quoteForBash, runSsh } = require('./script/deploy-lib.cjs'); -const config = loadDeployConfig('production'); - -const script = [ - 'echo \"=== v2 完整 Model 配置(行70-100)===\"', - 'sed -n \"70,100p\" ' + quoteForBash(config.deployRoot + '/v2/app/model/inbound_direct_log.js'), - 'echo \"\"', - 'echo \"=== v2 完整 Model 配置(行95-120)===\"', - 'sed -n \"95,120p\" ' + quoteForBash(config.deployRoot + '/v2/app/model/inbound_direct_log.js'), - 'echo \"\"', - 'echo \"=== current.md 指向 ===\"', - 'cat ' + quoteForBash(config.deployRoot + '/current.md'), - 'echo \"\"', - 'echo \"=== nginx upstream 指向 ===\"', - 'cat ' + quoteForBash(config.deployRoot + '/nginx-upstream.conf'), -].join('\n'); -console.log(runSsh(config, script, { stdio: 'pipe' })); diff --git a/app/service/systemMethods/index.js b/app/service/systemMethods/index.js index 2ad7b8f..2db538f 100644 --- a/app/service/systemMethods/index.js +++ b/app/service/systemMethods/index.js @@ -1053,9 +1053,9 @@ class indexService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = 'getI18nMessage,putI18nCollect,test,getCainiaoStfTemplates,polyapiAuthorizeUrl'; - const _noNeedRight = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getCOSUploadConfig,uploadSuccessNotify,getMessageDetail,searchSpace,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,getPlatformOauthLink,listenPlatformOauthBind,recognizeLicensePlate,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl'; + const _noNeedRight = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getCOSUploadConfig,uploadSuccessNotify,getMessageDetail,searchSpace,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,getPlatformOauthLink,listenPlatformOauthBind,recognizeLicensePlate,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl,toOrder'; const _noNeedLog = '*'; - const _noNeedAuth = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getMessageDetail,searchSpace,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,getPlatformOauthLink,listenPlatformOauthBind,recognizeLicensePlate,test,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl'; + const _noNeedAuth = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getMessageDetail,searchSpace,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,getPlatformOauthLink,listenPlatformOauthBind,recognizeLicensePlate,test,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl,toOrder'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } async fastWhereTree(data) { @@ -3314,5 +3314,19 @@ class indexService extends MainService { code: 200, }); } + + /** + * 根据运单号快速查询订单 ID 及其所属波次信息。 + * + * @param {Object} data 请求参数。 + * @param {string} data.waybill_code 运单号。 + * @return {Promise} 统一成功包装响应,包含 order_id 和 waves 数组。 + */ + async toOrder(data = {}) { + const { service } = this; + const { waybill_code: waybillCode } = data; + const result = await service.systems.waybill.toOrder({ waybill_code: waybillCode }); + return this.success('查询成功', result); + } } module.exports = indexService; diff --git a/app/service/systemMethods/order/pendingOrder.js b/app/service/systemMethods/order/pendingOrder.js index ca5c730..359e912 100644 --- a/app/service/systemMethods/order/pendingOrder.js +++ b/app/service/systemMethods/order/pendingOrder.js @@ -2834,6 +2834,7 @@ class PendingOrderService extends OrderBaseService { detailAddress, zipCode: String(requestData.zip_code || '').trim(), }, + seller_message: String(requestData.remark || '').trim(), }, orderLines: { orderLine: orderLineItems, diff --git a/app/service/systemMethods/order/recheckOrder.js b/app/service/systemMethods/order/recheckOrder.js index 158f5ca..ea39d53 100644 --- a/app/service/systemMethods/order/recheckOrder.js +++ b/app/service/systemMethods/order/recheckOrder.js @@ -1218,7 +1218,7 @@ class RecheckOrderService extends OrderBaseService { continue; } resultMap.set(hash, { - id: row.id != null ? Number(row.id) : null, + id: row.package_material_id, code: String(row.package_material_code || '').trim() || null, name: String(row.package_material_name || '').trim() || null, spec: String(row.package_material_spec || '').trim() || null, diff --git a/app/service/systemMethods/quick/waybill.js b/app/service/systemMethods/quick/waybill.js deleted file mode 100644 index a53863c..0000000 --- a/app/service/systemMethods/quick/waybill.js +++ /dev/null @@ -1,35 +0,0 @@ -'use strict'; - -const MainService = require('../../main'); - -/** - * 系统方法层:quick.waybill(运单号快速查询接口包装层)。 - * 主要职责:统一包装系统方法接口,处理权限、日志等公共逻辑,调用底层 service 实现业务功能。 - */ -class QuickWaybillMethodService extends MainService { - constructor(ctx) { - super(ctx); - const _noNeedLogin = ''; - const _noNeedRight = 'toOrder'; - const _noNeedLog = ''; - const _noNeedAuth = 'toOrder'; - this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); - } - - /** - * 根据运单号快速查询订单 ID。 - * 查询 wms_order_express 表中 status=1 的有效记录,返回对应的 order_id。 - * - * @param {Object} data 请求参数。 - * @param {string} data.waybill_code 运单号。 - * @return {Promise} 统一成功包装响应,包含 order_id。 - */ - async toOrder(data = {}) { - const { service } = this; - const { waybill_code: waybillCode } = data; - const result = await service.systems.quick.waybill.toOrder({ waybill_code: waybillCode }); - return this.success('查询成功', result); - } -} - -module.exports = QuickWaybillMethodService; diff --git a/app/service/systemMethods/storage/entry.js b/app/service/systemMethods/storage/entry.js index e82a358..808062e 100644 --- a/app/service/systemMethods/storage/entry.js +++ b/app/service/systemMethods/storage/entry.js @@ -9,9 +9,9 @@ class entryService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'list,get,cancel,getPrintData,getDirectInboundItems,addDirectInboundItem,commitDirectInbound,removeDirectInboundItem,quickInbound,receivingCompare,queryEntryLogs,getReceivingDetailsForBind,reviewEntry,containerList'; + const _noNeedRight = 'list,get,cancel,getPrintData,getDirectInboundItems,addItem,commit,removeItem,quickInbound,receivingCompare,queryEntryLogs,getReceivingDetailsForBind,reviewEntry,containerList'; const _noNeedLog = 'list,get,getPrintData,reviewEntry,containerList'; - const _noNeedAuth = 'list,get,cancel,getPrintData,getDirectInboundItems,addDirectInboundItem,commitDirectInbound,removeDirectInboundItem,bindReceiving,quickInbound,receivingCompare,unbindReceiving,queryEntryLogs,getReceivingDetailsForBind,reviewEntry,containerList'; + const _noNeedAuth = 'list,get,cancel,getPrintData,getDirectInboundItems,addItem,commit,removeItem,bindReceiving,quickInbound,receivingCompare,unbindReceiving,queryEntryLogs,getReceivingDetailsForBind,reviewEntry,containerList'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -73,7 +73,7 @@ class entryService extends MainService { * @param {Array} [data.items] 商品列表(批量模式) * @return {Promise} 统一 success 包装 */ - async addDirectInboundItem(data = {}) { + async addItem(data = {}) { const { service } = this; const result = await service.systems.inboundDirectLog.addItem(data); return this.success('ok', result); @@ -85,7 +85,7 @@ class entryService extends MainService { * @param {number} data.entry_order_id 入库单 ID * @return {Promise} 统一 success 包装 */ - async commitDirectInbound(data = {}) { + async commit(data = {}) { const { service } = this; const { entry_order_id } = data || {}; const result = await service.systems.inboundDirectLog.commit(entry_order_id); @@ -98,7 +98,7 @@ class entryService extends MainService { * @param {number} data.id 入库记录ID * @return {Promise} 统一 success 包装 */ - async removeDirectInboundItem(data = {}) { + async removeItem(data = {}) { const { service } = this; const result = await service.systems.inboundDirectLog.removeItem(data); return this.success('ok', result); diff --git a/app/service/systems/order_express.js b/app/service/systems/order_express.js index 15f0562..9f6e347 100644 --- a/app/service/systems/order_express.js +++ b/app/service/systems/order_express.js @@ -287,23 +287,66 @@ class OrderExpressService extends Service { ); } - // 查询订单所属波次 + // 先查运单表校验运单是否存在 + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; + if (!orderExpressModel || typeof orderExpressModel.findOne !== 'function') { + throw this.createBusinessError('运单模型未初始化', 500); + } + + const expressRow = await orderExpressModel.findOne({ + where: { + order_id: normalizedOrderId, + delete_at: null, + }, + attributes: [ 'id', 'order_id', 'waybill_code', 'business_key' ], + raw: true, + }); + + if (!expressRow) { + throw this.createBusinessError('运单号不存在', 404); + } + + // 依次查询多个订单表获取波次信息:current → history → dispatch const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') { throw this.createBusinessError('订单模型未初始化', 500); } - const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(warehouseId); - const orderRow = await orderDeliveryModel.findOne({ - where: { id: normalizedOrderId, warehouse_id: warehouseId }, - attributes: [ 'id', 'wave_id', 'wave_no' ], - raw: true, - }); + const orderTableOrders = [ + { label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) }, + { label: 'history', getModel: () => orderDeliveryFactory.getHistoryModel(warehouseId) }, + { label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) }, + ]; - // 订单不存在 → 兼容前端传入 wave_id 的场景,尝试按波次查询 + let orderRow = null; + let orderDeliveryModel = null; + for (const entry of orderTableOrders) { + try { + const model = await entry.getModel(); + if (!model || typeof model.findOne !== 'function') { + continue; + } + const row = await model.findOne({ + where: { id: normalizedOrderId, warehouse_id: warehouseId }, + attributes: [ 'id', 'wave_id', 'wave_no' ], + raw: true, + }); + if (row) { + orderRow = row; + orderDeliveryModel = model; + break; + } + } catch (_err) { + // 该表可能不存在,继续尝试下一张表 + continue; + } + } + + // 所有表都找不到 → 兼容前端传入 wave_id 的场景,尝试按波次查询 if (!orderRow) { + const fallbackModel = await orderDeliveryFactory.getCurrentModel(warehouseId); return await this._tryWaveCompatibility( - normalizedOrderId, normalizedWaybillCode, normalizedWeight, warehouseId, orderDeliveryModel + normalizedOrderId, normalizedWaybillCode, normalizedWeight, warehouseId, fallbackModel ); } @@ -385,18 +428,41 @@ class OrderExpressService extends Service { const orderId = Number(expressRow.order_id || 0); - // 查询订单所属波次 + // 依次查询多个订单表获取波次信息:current → history → dispatch const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') { throw this.createBusinessError('订单模型未初始化', 500); } - const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(warehouseId); - const orderRow = await orderDeliveryModel.findOne({ - where: { id: orderId, warehouse_id: warehouseId }, - attributes: [ 'id', 'wave_id', 'wave_no' ], - raw: true, - }); + const orderTableOrders = [ + { label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) }, + { label: 'history', getModel: () => orderDeliveryFactory.getHistoryModel(warehouseId) }, + { label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) }, + ]; + + let orderRow = null; + let orderDeliveryModel = null; + for (const entry of orderTableOrders) { + try { + const model = await entry.getModel(); + if (!model || typeof model.findOne !== 'function') { + continue; + } + const row = await model.findOne({ + where: { id: orderId, warehouse_id: warehouseId }, + attributes: [ 'id', 'wave_id', 'wave_no' ], + raw: true, + }); + if (row) { + orderRow = row; + orderDeliveryModel = model; + break; + } + } catch (_err) { + // 该表可能不存在,继续尝试下一张表 + continue; + } + } if (!orderRow) { throw this.createBusinessError('运单号对应的订单不存在', 404); diff --git a/app/service/systems/quick/waybill.js b/app/service/systems/quick/waybill.js deleted file mode 100644 index 1864517..0000000 --- a/app/service/systems/quick/waybill.js +++ /dev/null @@ -1,42 +0,0 @@ -'use strict'; - -const MainService = require('../../main'); - -/** - * 业务逻辑层:quick.waybill(运单号快速查询)。 - */ -class QuickWaybillService extends MainService { - /** - * 根据运单号查询有效订单ID。 - * 仅查询 wms_order_express 表中 status=1 的记录。 - * - * @param {Object} params 查询参数。 - * @param {string} params.waybill_code 运单号,不可为空。 - * @return {Promise} 包含 order_id 的对象。 - * @throws {Error} 当 waybill_code 为空或未找到匹配记录时抛出业务错误。 - */ - async toOrder({ waybill_code: waybillCode }) { - const { ctx } = this; - - if (!waybillCode || !String(waybillCode).trim()) { - this.throwError('运单号不能为空'); - } - - const record = await ctx.model.OrderExpress.findOne({ - where: { - waybill_code: String(waybillCode).trim(), - status: 1, - }, - attributes: [ 'order_id' ], - raw: true, - }); - - if (!record) { - this.throwError('未找到该运单号对应的订单'); - } - - return { order_id: record.order_id }; - } -} - -module.exports = QuickWaybillService; diff --git a/app/service/systems/storage/entry.js b/app/service/systems/storage/entry.js index cff056d..ea0ca8f 100644 --- a/app/service/systems/storage/entry.js +++ b/app/service/systems/storage/entry.js @@ -992,7 +992,7 @@ class EntryService extends Service { * @param {Array} [data.items] 商品列表(批量模式) * @return {Promise} code/data/message 结构 */ - async addDirectInboundItem(data = {}) { + async addItem(data = {}) { const { ctx } = this; return await ctx.service.systems.inboundDirectLog.addItem(data); } @@ -1002,7 +1002,7 @@ class EntryService extends Service { * @param {string} entryOrderCode 入库单号 * @return {Promise} code/data/message 结构 */ - async commitDirectInbound(entryOrderCode) { + async commit(entryOrderCode) { const { ctx } = this; return await ctx.service.systems.inboundDirectLog.commit(entryOrderCode); } @@ -1013,7 +1013,7 @@ class EntryService extends Service { * @param {number} data.id 入库记录ID * @return {Promise} code/data/message 结构 */ - async removeDirectInboundItem(data = {}) { + async removeItem(data = {}) { const { ctx } = this; return await ctx.service.systems.inboundDirectLog.removeItem(data); } diff --git a/app/service/systems/waybill.js b/app/service/systems/waybill.js new file mode 100644 index 0000000..79fcd49 --- /dev/null +++ b/app/service/systems/waybill.js @@ -0,0 +1,131 @@ +'use strict'; + +const MainService = require('../main'); + +/** + * 业务逻辑层:waybill(运单号快速查询)。 + */ +class WaybillService extends MainService { + /** + * 根据运单号查询有效订单ID,并返回该订单所属波次下所有订单ID列表。 + * + * 查询流程: + * 1. 通过运单号查询 wms_order_express 表获取 order_id 和 warehouse_id。 + * 2. 通过 order_id 遍历多表(current/history/dispatch)获取 wave_id 和 wave_no。 + * 3. 若有有效波次(wave_id > 0),遍历多表查询该波次下所有订单的 ID 列表。 + * + * @param {Object} params 查询参数。 + * @param {string} params.waybill_code 运单号,不可为空。 + * @return {Promise} 包含 order_id 和 waves 数组的对象。 + * @throws {Error} 当 waybill_code 为空或未找到匹配记录时抛出业务错误。 + */ + async toOrder({ waybill_code: waybillCode }) { + const { ctx } = this; + + if (!waybillCode || !String(waybillCode).trim()) { + this.throwError('运单号不能为空'); + } + + const record = await ctx.model.OrderExpress.findOne({ + where: { + waybill_code: String(waybillCode).trim(), + status: 1, + }, + attributes: [ 'order_id', 'warehouse_id' ], + raw: true, + }); + + if (!record) { + this.throwError('未找到该运单号对应的订单'); + } + + const { order_id: orderId, warehouse_id: expressWarehouseId } = record; + + // 获取 warehouse_id:优先从 ctx.user.store_id,回退到运单记录中的 warehouse_id + const warehouseId = + (ctx.user && ctx.user.store_id) ? ctx.user.store_id : expressWarehouseId; + + // 构建多表遍历查询队列:current → history → dispatch + const orderDeliveryFactory = + ctx.model && ctx.model.OrderDeliveryFactory; + const tableOrders = [ + { + label: 'current', + getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId), + }, + { + label: 'history', + getModel: () => orderDeliveryFactory.getHistoryModel(warehouseId), + }, + { + label: 'dispatch', + getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId), + }, + ]; + + // 遍历多表查询订单的 wave_id 和 wave_no + let orderRow = null; + for (const entry of tableOrders) { + try { + const model = await entry.getModel(); + if (!model || typeof model.findOne !== 'function') { + continue; + } + const row = await model.findOne({ + where: { id: orderId, warehouse_id: warehouseId }, + attributes: [ 'id', 'wave_id', 'wave_no' ], + raw: true, + }); + if (row) { + orderRow = row; + break; + } + } catch (_err) { + continue; + } + } + + // 无订单记录或 wave_id 无效,返回空 waves + if (!orderRow || !orderRow.wave_id || Number(orderRow.wave_id) <= 0) { + return { order_id: orderId, waves: [] }; + } + + const { wave_id: waveId, wave_no: waveNo } = orderRow; + + // 遍历多表查询该波次下所有订单的 ID 列表 + const orderIds = []; + for (const entry of tableOrders) { + try { + const model = await entry.getModel(); + if (!model || typeof model.findAll !== 'function') { + continue; + } + const rows = await model.findAll({ + where: { wave_id: waveId, warehouse_id: warehouseId }, + attributes: [ 'id' ], + raw: true, + }); + for (const row of rows) { + if (!orderIds.includes(row.id)) { + orderIds.push(row.id); + } + } + } catch (_err) { + continue; + } + } + + return { + order_id: orderId, + waves: [ + { + wave_id: waveId, + wave_no: waveNo, + order_ids: orderIds, + }, + ], + }; + } +} + +module.exports = WaybillService; diff --git a/methods/changes/system.json b/methods/changes/system.json index 5956315..3f0fea3 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,20 @@ [ + { + "version": "2026.07.03-system-01", + "date": "2026-07-03", + "type": "updated", + "summary": "将 quick.waybill.toOrder 迁移为 index.toOrder 并移入基础模块,新增 waves 返回字段", + "methods": [ + "quick.waybill.toOrder", + "index.toOrder" + ], + "notes": [ + "移除快捷操作(quick)模块分组,原 quick.waybill.toOrder 方法从 methods/system.json 删除。", + "在基础模块(index)新增 index.toOrder 方法:入参仍为 waybill_code,响应从单一 order_id 扩展为 order_id + waves 结构。", + "waves 为数组,每项含 wave_id(波次ID)、wave_no(波次号)、order_ids(波次下所有订单ID列表),无波次时为空数组。", + "查询路径:运单号 → wms_order_express(status=1)→ order_id + warehouse_id → 遍历 current/history/dispatch 表获取波次信息 → 再遍历多表获取同波次所有订单ID。" + ] + }, { "date": "2026-06-24", "type": "addition", @@ -4138,18 +4154,18 @@ { "version": "2026.06.23-system-13", "date": "2026-06-23", - "summary": "新增 storage.entry.* 下 4 个 DirectInbound 方法:getDirectInboundItems、addDirectInboundItem、commitDirectInbound、removeDirectInboundItem,原 storage.directInbound.* 方法保留向后兼容并标记 deprecated", + "summary": "新增 storage.entry.* 下 4 个 DirectInbound 方法:getDirectInboundItems、addItem、commit、removeItem,原 storage.directInbound.* 方法保留向后兼容并标记 deprecated", "methods": [ "storage.entry.getDirectInboundItems", - "storage.entry.addDirectInboundItem", - "storage.entry.commitDirectInbound", - "storage.entry.removeDirectInboundItem" + "storage.entry.addItem", + "storage.entry.commit", + "storage.entry.removeItem" ], "notes": [ "storage.entry.getDirectInboundItems:获取入库单的导入/PDA 入库信息,参数与响应格式同原 storage.directInbound.getItems", - "storage.entry.addDirectInboundItem:按商品增量添加导入/PDA 入库记录(支持单条和批量),参数与响应格式同原 storage.directInbound.addItem", - "storage.entry.commitDirectInbound:提交确认完成导入/PDA 入库,按实收数量写入库存并异步回传奇门/API,参数与响应格式同原 storage.directInbound.commit", - "storage.entry.removeDirectInboundItem:移除一条导入/PDA 入库记录,参数与响应格式同原 storage.directInbound.removeItem", + "storage.entry.addItem:按商品增量添加导入/PDA 入库记录(支持单条和批量),参数与响应格式同原 storage.directInbound.addItem", + "storage.entry.commit:提交确认完成导入/PDA 入库,按实收数量写入库存并异步回传奇门/API,参数与响应格式同原 storage.directInbound.commit", + "storage.entry.removeItem:移除一条导入/PDA 入库记录,参数与响应格式同原 storage.directInbound.removeItem", "底层 inbound_direct_log.js 实现不变,仅入口从 storage.directInbound 模块迁入 storage.entry 模块" ], "type": "added" @@ -4166,9 +4182,9 @@ ], "notes": [ "storage.directInbound.getItems → 替代方法 storage.entry.getDirectInboundItems", - "storage.directInbound.addItem → 替代方法 storage.entry.addDirectInboundItem", - "storage.directInbound.commit → 替代方法 storage.entry.commitDirectInbound", - "storage.directInbound.removeItem → 替代方法 storage.entry.removeDirectInboundItem", + "storage.directInbound.addItem → 替代方法 storage.entry.addItem", + "storage.directInbound.commit → 替代方法 storage.entry.commit", + "storage.directInbound.removeItem → 替代方法 storage.entry.removeItem", "旧方法保留向后兼容,参数与响应格式不变,仅入口模块变更" ], "type": "deprecated" @@ -4176,13 +4192,13 @@ { "version": "2026.06.23-system-15", "date": "2026-06-23", - "summary": "storage.inventory.matchPutaway 标记 deprecated,替代方案为 storage.entry.commitDirectInbound", + "summary": "storage.inventory.matchPutaway 标记 deprecated,替代方案为 storage.entry.commit", "methods": [ "storage.inventory.matchPutaway" ], "notes": [ - "storage.inventory.matchPutaway 已弃用,请迁移至 storage.entry.commitDirectInbound", - "commitDirectInbound 提供导入/PDA 入库完成确认功能,按实收数量写入库存并异步回传" + "storage.inventory.matchPutaway 已弃用,请迁移至 storage.entry.commit", + "commit 提供导入/PDA 入库完成确认功能,按实收数量写入库存并异步回传" ], "type": "deprecated" }, @@ -4198,7 +4214,7 @@ "notes": [ "storage.entry.bindReceivingDetails:已从代码中删除,明细级绑定收货单功能下线。入库单与收货单关系改为 wms_entry_order_receiving 主表级关联。", "storage.entry.unbindReceivingDetails:已从代码中删除,明细级解绑功能下线。", - "storage.inventory.matchPutaway:已从代码中删除,匹配入库功能下线。替代方案为 storage.entry.commitDirectInbound。", + "storage.inventory.matchPutaway:已从代码中删除,匹配入库功能下线。替代方案为 storage.entry.commit。", "storage.inventory.quickPutaway:之前已标记 [已删除],本次确认条目保留(与 matchPutaway 同一 group,保留作为历史参考)。", "storage.entry.create / addDetail / deleteDetail / detailChange:systems 层方法已删除,但从未在 system.json 中暴露为 API method,无需文档变更。" ], @@ -4518,9 +4534,9 @@ { "version": "2026.06.30-system-02", "date": "2026-06-30", - "summary": "storage.entry.addDirectInboundItem 入参变更:entry_order_code → entry_order_id(number);quantity 改为可选(传入 receiving_detail_id 时自动计算);新增 receiving_detail_id/allocated_quantity 参数支持 PDA 上架收货明细绑定模式;space_id 绑定模式下必填", + "summary": "storage.entry.addItem 入参变更:entry_order_code → entry_order_id(number);quantity 改为可选(传入 receiving_detail_id 时自动计算);新增 receiving_detail_id/allocated_quantity 参数支持 PDA 上架收货明细绑定模式;space_id 绑定模式下必填", "methods": [ - "storage.entry.addDirectInboundItem" + "storage.entry.addItem" ], "notes": [ "入参 entry_order_code(string) → entry_order_id(number),与底层 inboundDirectLog.addItem 实现对齐", @@ -4538,9 +4554,9 @@ { "version": "2026.06.30-system-03", "date": "2026-06-30", - "summary": "storage.entry.commitDirectInbound 入参变更:entry_order_code → entry_order_id(number),与底层 inboundDirectLog.commit 实现对齐", + "summary": "storage.entry.commit 入参变更:entry_order_code → entry_order_id(number),与底层 inboundDirectLog.commit 实现对齐", "methods": [ - "storage.entry.commitDirectInbound" + "storage.entry.commit" ], "notes": [ "入参 entry_order_code(string) → entry_order_id(number),与底层 inboundDirectLog.commit(entryOrderId) 实现对齐", @@ -4558,7 +4574,7 @@ ], "notes": [ "入参 entry_order_code(string) → entry_order_id(number),与底层 inboundDirectLog.commit(entryOrderId) 实现对齐", - "该方法已标记 deprecated,推荐使用 storage.entry.commitDirectInbound" + "该方法已标记 deprecated,推荐使用 storage.entry.commit" ], "type": "updated" }, @@ -4707,13 +4723,35 @@ { "version": "2026.07.03-system-03", "date": "2026-07-03", - "summary": "binding 表弃用文档同步:commitDirectInbound 描述中 EntryReceivingBinding 更新为 InboundDirectLog", + "summary": "binding 表弃用文档同步:commit 描述中 EntryReceivingBinding 更新为 InboundDirectLog", "methods": [ - "storage.entry.commitDirectInbound" + "storage.entry.commit" ], "notes": [ - "commitDirectInbound description 中将 pending 状态的 EntryReceivingBinding 更新为 pending 状态的 InboundDirectLog,与代码实现一致" + "commit description 中将 pending 状态的 EntryReceivingBinding 更新为 pending 状态的 InboundDirectLog,与代码实现一致" ], "type": "updated" + }, + { + "version": "2026-07-03-entry-get-params-fix", + "date": "2026-07-03", + "type": "updated", + "summary": "修正 storage.entry.get 文档:id 改为必填;移除未实现的 entry_order_code 参数;修正错误码与实际返回一致;补充 available_receiving_details 响应字段;修正 remaining_quantity 计算公式及 warehouse_image_url 实际行为", + "methods": [ + "storage.entry.get" + ], + "notes": [ + "params: 移除 entry_order_code(代码中从未使用该参数),id 从 required=false 改为 required=true", + "params: id 描述从'二选一'改为'必填'", + "errors: 400 的 message 从'参数错误:id 与 entry_order_code 至少提供一个'改为'id 参数不能为空'", + "errors: 移除不存在的 404 error,入库单不存在时实际返回 code=0, message='入库单不存在或无权访问'", + "errors: 删除不存在的 500 error", + "response: 新增 entryOrder.items[].available_receiving_details 字段及其描述", + "response: remaining_quantity 描述从 'count - received_quantity - direct_inbound_quantity' 修正为 'max(0, count - received_quantity)'", + "response: warehouse_image_url 描述从 StockWarehouse.image_url 改为'当前固定返回空字符串'", + "response: warehouse_is_images 类型从 number(0/1) 改为 string(Y/N),与 StockWarehouse.is_images 实际存储一致", + "response: warehouse_quantity/warehouse_locked_quantity/warehouse_is_batch_mgmt/warehouse_is_shelf_life_mgmt 补充无匹配时为 null 的说明", + "description: 更新描述以反映实际逻辑流程" + ] } ] diff --git a/methods/system.json b/methods/system.json index 49fc145..857bb52 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1607,6 +1607,64 @@ } ], "errors": [] + }, + { + "method": "index.toOrder", + "description": "根据运单号快速查询订单ID及其所属波次下所有订单ID列表。查询流程:1) 通过运单号查询 wms_order_express 表(status=1)获取 order_id 和 warehouse_id;2) 遍历多表(current/history/dispatch)获取 wave_id 和 wave_no;3) 若有有效波次则再遍历多表查询该波次下所有订单的 ID 列表。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "waybill_code", + "type": "string", + "required": true, + "source": "body", + "description": "运单号" + } + ], + "response": [ + { + "name": "order_id", + "type": "number", + "required": true, + "description": "订单ID" + }, + { + "name": "waves", + "type": "array", + "required": true, + "description": "波次列表,无波次时为空数组。每项含 wave_id(波次ID,number)、wave_no(波次号,string)、order_ids(波次下所有订单ID列表,number[])" + }, + { + "name": "waves[].wave_id", + "type": "number", + "required": true, + "description": "波次ID" + }, + { + "name": "waves[].wave_no", + "type": "string", + "required": true, + "description": "波次号" + }, + { + "name": "waves[].order_ids", + "type": "array", + "required": true, + "description": "该波次下所有订单的 ID 列表" + } + ], + "errors": [ + { + "code": 405, + "message": "运单号不能为空" + }, + { + "code": 405, + "message": "未找到该运单号对应的订单" + } + ] } ] }, @@ -18968,7 +19026,7 @@ ] }, { - "groupName": "入库模块", + "groupName": "入库单", "module": "storage.entry", "list": [ { @@ -19054,7 +19112,7 @@ }, { "method": "storage.entry.get", - "description": "查询入库单详情。返回的 entryOrder 包含顶层 receivingBindings(主表级关联,含关联的收货单信息),不再返回 items[].bindings(明细级绑定)。entryOrder.order_status 可能为 CREATING/CREATED/PENDING/COMPLETED/CANCELLED。CREATED=已创建待审核(需审核后才能绑定和完成入库),PENDING=已审核(可绑定和完成入库)。", + "description": "查询入库单详情。通过入库单 ID 定位,关联 Store、EntryItems、EntryOrderReceiving→Receiving,并通过仓库商品详情、直接入库进度、收货单可用明细进行数据合并。entryOrder.order_status 可能为 CREATING/CREATED/PENDING/COMPLETED/CANCELLED。CREATED=已创建待审核(需审核后才能绑定和完成入库),PENDING=已审核(可绑定和完成入库)。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -19069,16 +19127,9 @@ { "name": "id", "type": "number", - "required": false, + "required": true, "source": "body", - "description": "入库单ID,与 entry_order_code 二选一" - }, - { - "name": "entry_order_code", - "type": "string", - "required": false, - "source": "body", - "description": "入库单号,与 id 二选一" + "description": "入库单ID(必填)" } ], "response": [ @@ -19086,37 +19137,37 @@ "name": "entryOrder", "type": "object", "required": true, - "description": "入库单详情,包含 items 数组和 receivingBindings(主表级收货单关联数组)。items 每项含 external_item_code / external_item_id / warehouse_item_code / warehouse_item_name / warehouse_item_spec / count / received_quantity / confirm_quantity / warehouse_quantity / warehouse_locked_quantity / warehouse_is_batch_mgmt / warehouse_is_shelf_life_mgmt / warehouse_image_url / warehouse_is_images / barcodes / direct_inbound_quantity / remaining_quantity" + "description": "入库单详情,包含 items 数组、receivingBindings(主表级收货单关联数组)。items 每项含 external_item_code / external_item_id / warehouse_item_code / warehouse_item_name / warehouse_item_spec / count / received_quantity / confirm_quantity / warehouse_quantity / warehouse_locked_quantity / warehouse_is_batch_mgmt / warehouse_is_shelf_life_mgmt / warehouse_image_url / warehouse_is_images / barcodes / direct_inbound_quantity / remaining_quantity / available_receiving_details" }, { "name": "entryOrder.items[].external_item_code", "type": "string", "required": true, - "description": "外部商品编码" + "description": "外部商品编码(源自 EntryItems.item_code)" }, { "name": "entryOrder.items[].external_item_id", "type": "number", "required": true, - "description": "外部商品ID" + "description": "外部商品ID(源自 EntryItems.item_id)" }, { "name": "entryOrder.items[].warehouse_item_code", "type": "string", "required": true, - "description": "仓库商品编码" + "description": "仓库商品编码(StockWarehouse.item_code),无匹配时为空字符串" }, { "name": "entryOrder.items[].warehouse_item_name", "type": "string", "required": true, - "description": "仓库商品名称" + "description": "仓库商品名称(StockWarehouse.item_name),无匹配时为空字符串" }, { "name": "entryOrder.items[].warehouse_item_spec", "type": "string", "required": true, - "description": "仓库商品规格(sku_property)" + "description": "仓库商品规格(StockWarehouse.sku_property),无匹配时为空字符串" }, { "name": "entryOrder.items[].count", @@ -19140,55 +19191,61 @@ "name": "entryOrder.items[].warehouse_quantity", "type": "number", "required": true, - "description": "仓库当前库存总量(StockWarehouse.quantity)" + "description": "仓库当前库存总量(StockWarehouse.quantity),无匹配时为 null" }, { "name": "entryOrder.items[].warehouse_locked_quantity", "type": "number", "required": true, - "description": "仓库锁定数量(StockWarehouse.locked_quantity)" + "description": "仓库锁定数量(StockWarehouse.locked_quantity),无匹配时为 null" }, { "name": "entryOrder.items[].warehouse_is_batch_mgmt", "type": "string", "required": true, - "description": "是否批次管理(StockWarehouse.is_batch_mgmt),Y/N" + "description": "是否批次管理(StockWarehouse.is_batch_mgmt),Y/N;无匹配时为 null" }, { "name": "entryOrder.items[].warehouse_is_shelf_life_mgmt", "type": "string", "required": true, - "description": "是否效期管理(StockWarehouse.is_shelf_life_mgmt),Y/N" + "description": "是否效期管理(StockWarehouse.is_shelf_life_mgmt),Y/N;无匹配时为 null" }, { "name": "entryOrder.items[].warehouse_image_url", "type": "string", "required": true, - "description": "商品图片 URL(StockWarehouse.image_url)" + "description": "商品图片 URL,当前固定返回空字符串 ''" }, { "name": "entryOrder.items[].warehouse_is_images", - "type": "number", + "type": "string", "required": true, - "description": "是否有图片(StockWarehouse.is_images),0/1" + "description": "是否有图片(StockWarehouse.is_images),Y/N;无匹配时为 null" }, { "name": "entryOrder.items[].barcodes", "type": "array", "required": true, - "description": "条码列表,每项含 { id, barcode, sku_property }" + "description": "条码列表,每项含 { id, barcode, sku_property };无匹配时为空数组 []" }, { "name": "entryOrder.items[].direct_inbound_quantity", "type": "number", "required": true, - "description": "导入/PDA 已入库数量(InboundDirectLog 聚合)" + "description": "导入/PDA 已入库数量(InboundDirectLog 按 stock_id 聚合),无记录时为 0" }, { "name": "entryOrder.items[].remaining_quantity", "type": "number", "required": true, - "description": "剩余可入库数量(count - received_quantity - direct_inbound_quantity,最小为 0)" + "description": "剩余可入库数量 = max(0, count - received_quantity),最小为 0" + }, + { + "name": "entryOrder.items[].available_receiving_details", + "type": "array", + "required": true, + "description": "可匹配的收货单明细及剩余可用量。每项含 receiving_id / receiving_number / receiving_detail_id / actual_quantity / allocated_quantity / available_quantity。仅返回收货单状态未完成且未完全入库的明细。无匹配时为空数组 []" }, { "name": "entryOrder.receivingBindings", @@ -19200,15 +19257,15 @@ "errors": [ { "code": "400", - "message": "参数错误:id 与 entry_order_code 至少提供一个" + "message": "id 参数不能为空" }, { - "code": "404", - "message": "入库单不存在" + "code": "0", + "message": "入库单不存在或无权访问" }, { - "code": "500", - "message": "查询失败" + "code": "200", + "message": "查询成功" } ] }, @@ -19267,54 +19324,7 @@ ] }, { - "method": "storage.entry.completeEntry", - "description": "完成入库单。仅将入库单状态从 PENDING 变更为 COMPLETED,不涉及库存写入(库存写入统一由 storage.entry.commitDirectInbound 完成)。仅 PENDING(已审核)状态可完成;CREATED(已创建待审核)状态需先审核(→PENDING)后再完成;CANCELLED(已作废)状态不允许完成。", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "entry_order_id", - "type": "number", - "required": true, - "source": "body", - "description": "入库单ID" - } - ], - "response": [ - { - "name": "entry_order_id", - "type": "number", - "required": true, - "description": "入库单ID" - }, - { - "name": "order_status", - "type": "string", - "required": true, - "description": "入库单状态,完成时为 COMPLETED" - } - ], - "errors": [ - { - "code": 400, - "message": "当前入库单状态不允许完成(仅 PENDING 状态可完成)" - }, - { - "code": 404, - "message": "入库单不存在或无权访问" - } - ] - }, - { - "method": "storage.entry.addDirectInboundItem", + "method": "storage.entry.addItem", "description": "按商品增量添加导入/PDA 入库记录(支持单条和批量)。单条模式传 stock_id/quantity/inbound_type/remark,批量模式传 items 数组。批量模式所有商品共享同一个入库单状态校验,任一商品校验失败整批拒绝。若某商品累计入库量超过计划数量则拒绝(PENDING 非绑定模式)。PENDING 状态需传 receiving_detail_id 绑定收货明细;CREATED 人工导入允许超过计划数量;传入 receiving_detail_id 时 quantity 可选(自动计算可用数量),space_id 必填。", "isNeedAuth": false, "isNeedLogin": true, @@ -19519,7 +19529,7 @@ ] }, { - "method": "storage.entry.commitDirectInbound", + "method": "storage.entry.commit", "description": "提交确认完成导入/PDA 入库。先同步奇门/API 回传,成功后在 onSuccess 回调内开启事务写入库存(wms_stock_warehouse.quantity 增量、wms_stock_transaction 流水),将 pending 状态的 InboundDirectLog 更新为 committed,更新入库单状态为 COMPLETED,同步 sync_status=SUCCESS。不足量提交时未入库商品跳过。", "isNeedAuth": false, "isNeedLogin": true, @@ -19598,7 +19608,7 @@ ] }, { - "method": "storage.entry.removeDirectInboundItem", + "method": "storage.entry.removeItem", "description": "移除一条导入/PDA 入库记录(仅限未提交的入库单,即状态非 CANCELLED/COMPLETED)。移除后该商品的可入库余量自动恢复。", "isNeedAuth": false, "isNeedLogin": true, @@ -19656,101 +19666,6 @@ } ] }, - { - "method": "storage.entry.bindReceivingDetails", - "description": "批量绑定入库单明细与收货单明细。绑定只能使用关联收货单中匹配的 stock_id(通过 system_product_id 映射),且不能超出收货单明细的可用数量(actual_quantity - 已 committed 的 allocated_quantity)。支持部分成功:校验通过的写入绑定,不通过的在 failed 列表中返回原因。", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "entry_order_id", - "type": "number", - "required": true, - "source": "body", - "description": "入库单ID" - }, - { - "name": "bindings", - "type": "array", - "required": true, - "source": "body", - "description": "绑定列表,每项包含 entry_item_id、receiving_detail_id、allocated_quantity" - } - ], - "response": [ - { - "name": "success", - "type": "array", - "required": true, - "description": "成功绑定的列表,每项包含 entry_item_id、receiving_detail_id、allocated_quantity" - }, - { - "name": "failed", - "type": "array", - "required": true, - "description": "绑定失败的列表,每项包含 entry_item_id、receiving_detail_id、allocated_quantity、error_code、message、detail", - "items": { - "type": "object", - "properties": { - "entry_item_id": { - "type": "number", - "description": "入库单明细ID" - }, - "receiving_detail_id": { - "type": "number", - "description": "收货单明细ID" - }, - "allocated_quantity": { - "type": "number", - "description": "请求分配的数量" - }, - "error_code": { - "type": "string", - "description": "错误码,可能值:ENTRY_ITEM_NOT_FOUND(入库明细不存在)、STOCK_NOT_FOUND(商品不存在)、RECEIVING_DETAIL_MISMATCH(收货明细与入库商品不匹配)、RECEIVING_DETAIL_NOT_FOUND(收货明细不存在)、INSUFFICIENT_AVAILABLE_QUANTITY(超出可用数量)、ENTRY_ORDER_STATUS_INVALID(入库单状态不允许绑定)" - }, - "message": { - "type": "string", - "description": "中文错误描述,可直接展示给用户" - }, - "detail": { - "type": "object", - "description": "错误上下文数据,根据 error_code 不同包含不同字段。如 INSUFFICIENT_AVAILABLE_QUANTITY 时包含 available_quantity 和 requested_quantity" - } - } - } - }, - { - "name": "success_count", - "type": "number", - "required": true, - "description": "成功数量" - }, - { - "name": "failed_count", - "type": "number", - "required": true, - "description": "失败数量" - } - ], - "errors": [ - { - "code": 400, - "message": "参数校验失败:entry_order_id 必填 / bindings 必填且为非空数组 / 入库单状态不允许绑定时,所有 bindings 均返回 failed 且 error_code 为 ENTRY_ORDER_STATUS_INVALID" - }, - { - "code": 404, - "message": "入库单不存在或无权访问" - } - ] - }, { "method": "storage.entry.quickInbound", "description": "快捷直入(虚拟入库):将入库单所有商品按明细数量一键直入到虚拟库位(space_id=2),跳过收货/质检流程,入库单状态变为COMPLETED。仅支持 CREATED 状态的入库单;CANCELLED(已作废)、COMPLETED(已完成)、PENDING 等其他状态均拒绝操作。事务内操作:更新入库明细收货量、累加库存总量、写入库存流水、写入虚拟库位库存、变更入库单状态为 COMPLETED。事务外异步回传奇门/API。", @@ -25883,46 +25798,6 @@ ] } ] - }, - { - "groupName": "快捷操作", - "module": "quick", - "list": [ - { - "method": "quick.waybill.toOrder", - "description": "根据运单号快速查询订单ID。查询 wms_order_express 表中 status=1 的有效记录,返回对应的 order_id。", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [], - "params": [ - { - "name": "waybill_code", - "type": "string", - "required": true, - "source": "body", - "description": "运单号" - } - ], - "response": [ - { - "name": "order_id", - "type": "number", - "required": true, - "description": "订单ID" - } - ], - "errors": [ - { - "code": 405, - "message": "运单号不能为空" - }, - { - "code": 405, - "message": "未找到该运单号对应的订单" - } - ] - } - ] } ] } diff --git a/skills/entry-order-test-guide.md b/skills/entry-order-test-guide.md deleted file mode 100644 index 3638961..0000000 --- a/skills/entry-order-test-guide.md +++ /dev/null @@ -1,449 +0,0 @@ -# 入库单推送全流程测试指南 - -## 1. 全流程概述 - -``` -奇门推送 entryorder.create → 创建入库单(CREATED) - → bindReceiving(绑定收货单) - → reviewEntry(CREATED→PENDING) - → addItem(PDA上架,传 receiving_detail_id + space_id) - → commit(提交入库+奇门同步→COMPLETED) - -或 quickInbound(虚拟直入,跳过收货单,CREATED→COMPLETED) -``` - -### 流程说明 - -| 阶段 | method | 状态变化 | 说明 | -|------|--------|----------|------| -| 奇门创建 | `qimen.entryorder.create` | (无)→CREATED | 奇门 XML 推送,创建入库单及明细 | -| 绑定收货单 | `storage.entry.bindReceiving` | CREATED→CREATED | 将入库单与收货单关联 | -| 审核 | `storage.entry.reviewEntry` | CREATED→PENDING | 审核通过,允许上架,**必须已绑定收货单** | -| PDA上架 | `storage.directInbound.addItem` | PENDING→PENDING | PDA扫码上架,传 `receiving_detail_id` + `space_id` | -| 提交入库 | `storage.directInbound.commit` | PENDING→COMPLETED | 先奇门同步,再写库存 | -| 虚拟直入 | `storage.entry.quickInbound` | CREATED→COMPLETED | 跳过收货单,一键完成入库 | - -## 2. 关键接口列表 - -| 步骤 | method | 说明 | 入口 | -|------|--------|------|------| -| 创建 | `qimen.entryorder.create` | 奇门推送 XML 创建入库单 | /qimen | -| 绑定 | `storage.entry.bindReceiving` | 绑定收货单到入库单 | /system | -| 审核 | `storage.entry.reviewEntry` | CREATED→PENDING,需已绑定 | /system | -| 上架 | `storage.directInbound.addItem` | PDA添加,可选绑定收货明细 | /system | -| 提交 | `storage.directInbound.commit` | 同步奇门+写库存→COMPLETED | /system | -| 虚拟 | `storage.entry.quickInbound` | 一键虚拟入库 | /system | -| 对照 | `storage.entry.receivingCompare` | 入库单 vs 收货单明细对照 | /system | -| 查询 | `storage.directInbound.getItems` | 查询直入记录 | /system | -| 日志 | `storage.entry.queryEntryLogs` | 查询入库单操作日志 | /system | - -## 3. 踩坑点 - -### 3a. 端口 - -配置文件(`config/config.local.js`)中端口是 **6060**,不是 Egg.js 默认的 7001。 - -```powershell -# 确认端口 -Select-String -Path "config/config.local.js" -Pattern "port" -``` - -### 3b. app_key 双重角色 - -- **签名用**:`config.qimen.appKey`(如 `23535631`),用于奇门请求的 MD5 签名计算 -- **validateApi 查询匹配用**:请求参数中的 `app_key`(如 `23060081`),用于匹配 `wms_api_app` 表记录 -- **两个值不同**,签名的 `app_key` 不参与 `wms_api_app` 绑定查询 - -### 3c. 奇门签名 - -- **签名算法**:`secret + sortedParams + xmlBody + secret` → MD5 → 大写 -- **签名不验证入站请求**:qimen 入口无 `verifyTopRequest` 校验 -- **使用已有合约配置**:从 `wms_api_app` 表读取,不要无中生有创建新配置 - -### 3d. itemId 必传 - -- `itemId` 为空时,按 `item_code + app_key + warehouse_id + store_id` 查询 `StockStore` -- `app_key` 不匹配会导致找不到商品 -- **建议一律传 `itemId`** 以避免匹配问题 - -### 3e. 服务器重启 - -修改代码后需完全重启: - -```powershell -taskkill /F /IM node.exe -npm run dev -``` - -端口被占用排查: - -```powershell -netstat -ano | findstr :6060 -``` - -### 3f. /system 接口需要 headers - -```http -platform: web -project: wms -Authorization: Bearer -``` - -测试账号:`liufumingren` / `111111` - -获取 token: - -```powershell -curl -X POST http://localhost:6060/system?method=user.login ` - -H "platform: web" ` - -H "project: wms" ` - -H "Content-Type: application/json" ` - -d '{"username":"liufumingren","password":"111111"}' -``` - -### 3g. 先同步后写库 - -`quickInbound` 和 `commit` 的执行顺序已改为: - -1. 先调用 `qimenEntrySync` 同步到奇门/ERP -2. 同步成功后才写库存 -3. 同步失败不写库存,只标记为 `FAILED` - -### 3h. 绑定模式 - -`addItem` 传 `receiving_detail_id` 时进入绑定模式: - -- **忽略 `quantity` 字段**,实际数量从 `ReceivingDetail.actual_quantity` 取值 -- **必须传 `space_id`**(库位ID) -- **允许超过入库单 `planQty`**,不受计划数量限制 - -## 4. 快速测试脚本示例 - -### 4.1 准备工作:获取 Token - -```powershell -$loginBody = @{username="liufumingren";password="111111"} | ConvertTo-Json -$loginResp = curl -s -X POST "http://localhost:6060/system?method=user.login" ` - -H "platform: web" -H "project: wms" ` - -H "Content-Type: application/json" ` - -d $loginBody -$token = ($loginResp | ConvertFrom-Json).data.token -Write-Host "Token: $token" -``` - -### 4.2 创建入库单(奇门推送) - -```xml -POST /qimen?method=entryorder.create&app_key=23060081&customerId=4&v=1.0&format=xml&sign_method=md5×tamp=2026-06-27+10:00:00&sign=XXX - - - - TEST-ENTRY-001 - WH001 - JYCK - - - - SKU001 - 100 - - - -``` - -### 4.3 创建收货单 - -```powershell -$rcvBody = @{ - delivery_method="truck" - loading_method="without_pallet" - store_id=1000000 -} | ConvertTo-Json - -curl -s -X POST "http://localhost:6060/system?method=storage.receiving.create" ` - -H "platform: web" -H "project: wms" ` - -H "Authorization: Bearer $token" ` - -H "Content-Type: application/json" ` - -d $rcvBody -``` - -### 4.4 添加收货明细 - -```powershell -$detailBody = @{ - receiving_id="" - item=@{ - product_name="测试商品" - actual_quantity=86 - } -} | ConvertTo-Json - -curl -s -X POST "http://localhost:6060/system?method=storage.receiving.addDetail" ` - -H "platform: web" -H "project: wms" ` - -H "Authorization: Bearer $token" ` - -H "Content-Type: application/json" ` - -d $detailBody -``` - -### 4.5 完成收货 + 审核 - -```powershell -# 完成收货 -curl -s -X POST "http://localhost:6060/system?method=storage.receiving.completeReceiving" ` - -H "platform: web" -H "project: wms" ` - -H "Authorization: Bearer $token" ` - -H "Content-Type: application/json" ` - -d "{`"receiving_id`":`"`"}" - -# 审核收货单 -curl -s -X POST "http://localhost:6060/system?method=storage.receiving.reviewReceiving" ` - -H "platform: web" -H "project: wms" ` - -H "Authorization: Bearer $token" ` - -H "Content-Type: application/json" ` - -d "{`"receiving_id`":`"`"}" -``` - -### 4.6 绑定入库单 + 审核 - -```powershell -# 绑定收货单 -curl -s -X POST "http://localhost:6060/system?method=storage.entry.bindReceiving" ` - -H "platform: web" -H "project: wms" ` - -H "Authorization: Bearer $token" ` - -H "Content-Type: application/json" ` - -d "{`"entry_id`":`"`",`"receiving_id`":`"`"}" - -# 审核入库单 -curl -s -X POST "http://localhost:6060/system?method=storage.entry.reviewEntry" ` - -H "platform: web" -H "project: wms" ` - -H "Authorization: Bearer $token" ` - -H "Content-Type: application/json" ` - -d "{`"entry_id`":`"`"}" -``` - -### 4.7 PDA上架 + 提交 - -```powershell -# 添加直入记录(绑定模式) -$addItemBody = @{ - entry_id="" - receiving_detail_id="" - space_id="" - item_code="SKU001" -} | ConvertTo-Json - -curl -s -X POST "http://localhost:6060/system?method=storage.directInbound.addItem" ` - -H "platform: web" -H "project: wms" ` - -H "Authorization: Bearer $token" ` - -H "Content-Type: application/json" ` - -d $addItemBody - -# 提交入库 -curl -s -X POST "http://localhost:6060/system?method=storage.directInbound.commit" ` - -H "platform: web" -H "project: wms" ` - -H "Authorization: Bearer $token" ` - -H "Content-Type: application/json" ` - -d "{`"entry_id`":`"`"}" -``` - -### 4.8 虚拟直入(跳过收货单) - -```powershell -$quickBody = @{ - entry_id="" - items=@( - @{ - item_code="SKU001" - quantity=50 - space_id="" - } - ) -} | ConvertTo-Json - -curl -s -X POST "http://localhost:6060/system?method=storage.entry.quickInbound" ` - -H "platform: web" -H "project: wms" ` - -H "Authorization: Bearer $token" ` - -H "Content-Type: application/json" ` - -d $quickBody -``` - -## 5. 数据库关键表 - -| 表 | 用途 | 关键字段 | -|----|------|----------| -| `wms_entry_order` | 入库单主表 | id, entry_order_code, order_status, sync_status | -| `wms_entry_items` | 入库单明细 | id, entry_id, item_id, item_code, plan_quantity, actual_quantity | -| `wms_receiving` | 收货单主表 | id, receiving_code, status, store_id | -| `wms_receiving_detail` | 收货单明细 | id, receiving_id, product_name, actual_quantity | -| `wms_entry_order_receiving` | 入库单↔收货单主表绑定 | id, entry_id, receiving_id | -| `wms_entry_receiving_binding` | [已弃用] 入库明细↔收货明细绑定(已迁至 InboundDirectLog) | id, entry_item_id, receiving_detail_id, quantity | -| `wms_inbound_direct_log` | PDA直入记录 + 入库明细↔收货明细绑定 | id, entry_id, entry_item_id, item_code, quantity, space_id, receiving_detail_id, status, updated_at, deleted_at | -| `wms_api_app` | 奇门应用绑定配置 | id, app_key, app_secret, warehouse_id, store_id | -| `wms_operation_log` | 操作日志 | id, target_type, target_id, action, operator, created_at | - -## 6. 状态机速查 - -| 状态 | 含义 | 可执行操作 | -|------|------|------------| -| `CREATED` | 已创建,待绑定/审核 | bindReceiving, reviewEntry, quickInbound, cancel | -| `PENDING` | 已审核,待上架 | addItem, commit, cancel | -| `COMPLETED` | 已完成 | 不可操作 | -| `CANCELLED` | 已取消 | 不可操作 | -| `FAILED` | 同步失败 | 重试或取消 | - -## 7. 常见问题排查 - -### 7.1 找不到入库单 - -- 检查奇门 XML 中 `warehouseCode` 是否匹配 `wms_api_app` 中的 `warehouse_id` -- 检查 `app_key` 是否已在 `wms_api_app` 表中配置 - -### 7.2 reviewEntry 报错"未绑定收货单" - -- CREATED 状态且未调用 `bindReceiving` 时,审核会被拒绝 -- 先调用 `bindReceiving` 绑定收货单 - -### 7.3 addItem 报错"缺少 space_id" - -- 绑定模式下(传了 `receiving_detail_id`)必须同时传 `space_id` -- `space_id` 对应库位表主键 - -### 7.4 commit 后库存未变化 - -- 检查 `qimenEntrySync` 是否返回成功 -- 同步失败时标记为 `FAILED` 状态,库存不会写入 -- 查看 `wms_operation_log` 中的错误信息 - -### 7.5 端口被占用 - -```powershell -# 查找占用进程 -netstat -ano | findstr :6060 -# 强制结束 -taskkill /F /PID -``` - -## 8. 变更历史 - -| 日期 | 版本 | 变更内容 | -|------|------|----------| -| 2026-06-27 | v1.0 | 初始版本,覆盖入库单全流程测试指南 | -## 8. 问题清单与修复基准(来自 issues.txt) - -### 问题 1:缺失收货单直接转入库单的快捷入口 -- **现状**:收货单创建后,必须先手动创建入库单(走奇门或 OpenAPI),再通过 bindReceiving 绑定 -- **修复后应支持**:storage.receiving.createEntryOrder(receiving_id) → 自动创建入库单并绑定主表关系 - -### 问题 2:addItem 状态机校验不完整 -- **2a**:CREATED + 已绑定收货单 → 应拒绝(当前只强制要求传 receiving_detail_id) -- **2b**:PENDING + 已绑定 + 无明细ID → 应拒绝(当前未区分 CREATED/PENDING) -- **2c**:PENDING + 无绑定 → 应拒绝(PENDING 只能走 PDA 上架,必须已绑定收货单) -- **2d**:CREATED 人工导入 → 应允许超过 planQty(当前非绑定模式不允许超量) - -**修复后校验矩阵:** - -| 状态 | 有绑定 | 携带明细ID | 应允许 | 超 planQty | -|------|--------|-----------|--------|-----------| -| CREATED | 否 | 否 | ✅ 人工后台导入 | ✅ 允许 | -| CREATED | 是 | - | ❌ 拒绝 | - | -| PENDING | 否 | - | ❌ 拒绝 | - | -| PENDING | 是 | 否 | ❌ 拒绝 | - | -| PENDING | 是 | 是 | ✅ PDA上架 | ✅ 允许 | - -### 问题 3:状态机定义 -` -CREATING → CREATED → PENDING → COMPLETED - ↑ ↓ ↑ - └── 重试推送 ────────┘ │ - CANCELLED ←────────┘ -` -- CREATED:等待人工绑定和审核,可走人工后台导入(不限制 planQty),可走虚拟直入 -- PENDING:已审核,待上架/上架中,必须已绑定收货单,必须携带 receiving_detail_id -- COMPLETED:已完成,不可操作 - -### 问题 4:entryorderConfirm 增量回传应移除 -- 统一走 qimenEntrySync 全量同步,actualQty = item.count -- 移除 entry_order.js 的 entryorderConfirm 方法 - -### 问题 5:completeEntry 应作废 -- commit 已包含所有实质性工作(写库存、同步奇门、推进 COMPLETED) -- completeEntry 无独立存在意义 - -### 问题 6:入库单取消 -- 6a:取消时调用 qimenEntrySync,orderLines 全部 actualQty=0,通知 ERP 关闭 -- 6b:sync_status=SUCCESS 的入库单不允许取消(已通知 ERP 入库完成) -- 允许取消的状态:sync_status != 'SUCCESS' 且 order_status NOT IN ('COMPLETED','CANCELLED') - -## 9. 完整测试场景 - -### 场景 A:奇门创建 + 收货单 + PDA上架(完整链路) -` -1. qimen.entryorder.create → CREATED -2. storage.receiving.create → 收货单 -3. storage.receiving.addDetail → 收货明细 -4. storage.receiving.completeReceiving → 完成收货 -5. storage.receiving.reviewReceiving → 审核收货单 -6. storage.entry.bindReceiving → 绑定入库单↔收货单 -7. storage.entry.receivingCompare → 对照预览 -8. storage.entry.reviewEntry → CREATED→PENDING -9. storage.directInbound.addItem(receiving_detail_id) → PDA上架+明细绑定 -10. storage.directInbound.commit → 奇门同步+写库存→COMPLETED -` - -### 场景 B:人工后台导入(无收货单) -` -1. qimen.entryorder.create → CREATED -2. storage.directInbound.addItem(无 receiving_detail_id) → 人工导入 -3. storage.directInbound.commit → 奇门同步+写库存→COMPLETED -` - -### 场景 C:虚拟直入 -` -1. qimen.entryorder.create → CREATED -2. storage.entry.quickInbound → 奇门同步+写库存→COMPLETED(一步完成) -` - -### 场景 D:取消入库单 -` -1. 入库单 CREATED/PENDING 且 sync_status != SUCCESS -2. storage.entry.cancel → ①发送 qimenEntrySync(all actualQty=0) → ②更新 order_status=CANCELLED -` - -## 10. 数据库校验检查点 - -修复完成后,以下 SQL 可用于验证各场景正确性: - -\\\sql --- 验证入库单状态 -SELECT id, entry_order_code, order_status, sync_status, sync_message FROM wms_entry_order WHERE id = ?; - --- 验证入库明细收货量 -SELECT id, item_code, count, received_quantity, confirm_quantity FROM wms_entry_items WHERE order_id = ?; - --- 验证主表绑定 -SELECT * FROM wms_entry_order_receiving WHERE entry_order_id = ?; - --- 验证明细绑定 -SELECT id, entry_item_id, receiving_detail_id, allocated_quantity, status FROM wms_entry_receiving_binding WHERE entry_item_id IN (SELECT id FROM wms_entry_items WHERE order_id = ?); - --- 验证直入记录 -SELECT id, stock_id, quantity, space_id FROM wms_inbound_direct_log WHERE entry_order_id = ?; - --- 验证库存写入 -SELECT id, stock_id, batch_no, quantity, receiving_id, production_date, expiry_date FROM wms_storage WHERE entry_order_id = ?; - --- 验证操作日志 -SELECT id, business_type, business_id, operation_code, message FROM wms_operation_log WHERE business_id = ? AND business_type = 'entry_order' ORDER BY created_at DESC; -\\\ - -## 11. 已知操作码清单 - -| operationCode | 触发接口 | 说明 | -|---------------|---------|------| -| ENTRY_ORDER_CREATE | qimen/OpenAPI entryorder.create | 入库单创建 | -| ENTRY_ORDER_REVIEW | storage.entry.reviewEntry | 审核通过 CREATED→PENDING | -| DIRECT_INBOUND_ADD | storage.directInbound.addItem | 直入记录添加 | -| DIRECT_INBOUND_COMMIT | storage.directInbound.commit | 提交入库 COMPLETED | -| DIRECT_INBOUND_REMOVE | storage.directInbound.removeItem | 移除直入记录 | -| QUICK_INBOUND | storage.entry.quickInbound | 虚拟直入完成 | -| QUICK_INBOUND_FAILED | quickInbound/commit 失败 | 同步失败 | diff --git a/tmp/verify_migration.cjs b/tmp/verify_migration.cjs deleted file mode 100644 index 310d0f5..0000000 --- a/tmp/verify_migration.cjs +++ /dev/null @@ -1,37 +0,0 @@ -'use strict'; - -(async () => { - try { - const cfg = require('../database/config.js').production; - const mysql = require('mysql2/promise'); - const conn = await mysql.createConnection({ - host: cfg.host, - user: cfg.username || cfg.user, - password: cfg.password, - database: cfg.database, - port: cfg.port || 3306, - }); - - const migrationName = '20260507100000-create-wms_order_wave_strategy_match.js'; - const schema = cfg.database; - - const [metaRows] = await conn.query('SELECT name FROM SequelizeMeta WHERE name = ? LIMIT 1', [migrationName]); - const migrationInMeta = (metaRows.length && metaRows.length > 0) ? true : false; - - const [tableRows] = await conn.query('SELECT TABLE_NAME FROM information_schema.tables WHERE table_schema = ? AND table_name = ?', [schema, 'wms_order_wave_strategy_match']); - const tableExists = (tableRows.length && tableRows.length > 0) ? true : false; - - const [columnsRows] = await conn.query('SELECT COLUMN_NAME FROM information_schema.columns WHERE table_schema = ? AND table_name = ? AND COLUMN_NAME IN (?,?,?,?,?)', [schema, 'wms_order_wave_strategy_match', 'id','warehouse_id','order_id','strategy_id','create_time']); - const columns = (columnsRows || []).map(r => r.COLUMN_NAME); - - const [idxRows] = await conn.query('SELECT DISTINCT INDEX_NAME FROM information_schema.statistics WHERE table_schema = ? AND table_name = ? AND INDEX_NAME IN (?,?)', [schema, 'wms_order_wave_strategy_match', 'idx_warehouse_order', 'idx_warehouse_strategy']); - const indices = (idxRows || []).map(r => r.INDEX_NAME); - - console.log(JSON.stringify({ migrationInMeta, tableExists, columns, indices }, null, 2)); - await conn.end(); - process.exit(0); - } catch (err) { - console.error('ERROR:', err && err.message ? err.message : err); - process.exit(2); - } -})(); From 7f05b26db2a0d16bc60ebf025ba2408a1e22f7d4 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sat, 4 Jul 2026 21:40:31 +0800 Subject: [PATCH 084/550] 1 --- app/schedule/pick_complete_compensation.js | 46 --- app/schedule/print_retry_compensation.js | 187 ----------- .../wave_strategy_quick_scan_fallback.js | 12 - app/service/openapiMethods/order.js | 37 +-- app/service/qimenMethods/order.js | 37 +-- app/service/qimenMethods/stockout.js | 3 +- .../systemMethods/order/pendingOrder.js | 144 ++++++--- app/service/systemMethods/storage/entry.js | 107 +++++-- app/service/systems/delivery_order.js | 3 +- app/service/systems/inbound_direct_log.js | 146 +++++++-- .../systems/order_storage_allocation.js | 70 +--- app/service/systems/stock_store.js | 299 +++++++++-------- app/service/systems/storage/entry.js | 300 ++++++++++++------ app/service/systems/storage/inventory.js | 20 +- methods/changes/system.json | 36 +++ methods/system.json | 88 +++-- package.json | 2 - script/deploy-init.cjs | 138 -------- 18 files changed, 794 insertions(+), 881 deletions(-) delete mode 100644 app/schedule/pick_complete_compensation.js delete mode 100644 app/schedule/print_retry_compensation.js delete mode 100644 script/deploy-init.cjs diff --git a/app/schedule/pick_complete_compensation.js b/app/schedule/pick_complete_compensation.js deleted file mode 100644 index 7b28143..0000000 --- a/app/schedule/pick_complete_compensation.js +++ /dev/null @@ -1,46 +0,0 @@ -'use strict'; - -/** - * 拣货完成补偿定时任务。 - * 每 1 分钟在单 worker 中扫描一次:当 wms_picking 中存在 status='pending' 的遗漏记录, - * 且对应订单已迁移到配送 dispatch 表且 pick_status='fin' 时,补扣库存并写入出库流水。 - * - * 补偿判断条件: - * 1. wms_picking.status = 'pending' 且 warehouse_id > 0 - * 2. 对应订单在 order_delivery_dispatch 表中 pick_status = 'fin' - * 3. 对应订单不在 order_delivery 主表中(已迁移) - */ -module.exports = { - schedule: { - interval: '1m', - type: 'worker', - immediate: true, - disable: false, - }, - - /** - * 执行拣货完成补偿任务。 - * - * @param {Object} ctx Egg 上下文。 - * @return {Promise} 无返回值。 - */ - async task(ctx) { - if (ctx.app._pickCompensationRunning) { - return; - } - - ctx.app._pickCompensationRunning = true; - - try { - const result = await ctx.service.systems.pickCompensation.executeCompensation(); - - ctx.logger.info( - `[pick-compensation] 本轮补偿完成,共处理 ${result && result.totalCompensated || 0} 条拣货记录` - ); - } catch (error) { - ctx.logger.error(`[pick-compensation] 补偿任务执行失败: ${error.message}`); - } finally { - ctx.app._pickCompensationRunning = false; - } - }, -}; diff --git a/app/schedule/print_retry_compensation.js b/app/schedule/print_retry_compensation.js deleted file mode 100644 index 81c81e6..0000000 --- a/app/schedule/print_retry_compensation.js +++ /dev/null @@ -1,187 +0,0 @@ -'use strict'; - -const DEFAULT_INTERVAL_MS = 60 * 1000; -const DEFAULT_BATCH_SIZE = 50; - -/** - * 归一化打印补偿调度配置。 - * @param {Object} app Egg 应用实例。 - * @return {{enable:boolean,intervalMs:number,batchSize:number,force:boolean}} 标准化配置。 - */ -function getCompensationConfig(app) { - const rawConfig = app && app.config && app.config.printRetryCompensation - ? app.config.printRetryCompensation - : {}; - const intervalMs = Number.parseInt(rawConfig.intervalMs, 10); - const batchSize = Number.parseInt(rawConfig.batchSize, 10); - return { - enable: Boolean(rawConfig.enable), - intervalMs: Number.isInteger(intervalMs) && intervalMs > 0 ? intervalMs : DEFAULT_INTERVAL_MS, - batchSize: Number.isInteger(batchSize) && batchSize > 0 ? batchSize : DEFAULT_BATCH_SIZE, - force: Boolean(rawConfig.force), - }; -} - -/** - * 按仓库维度分组打印记录。 - * @param {Array} printRecords 打印记录列表。 - * @return {Map>} 仓库到打印记录 ID 的映射。 - */ -function groupPrintIdsByWarehouse(printRecords = []) { - const groupedMap = new Map(); - if (!Array.isArray(printRecords)) { - return groupedMap; - } - - for (const printRecord of printRecords) { - const warehouseId = Number(printRecord && printRecord.warehouse_id); - const printId = Number(printRecord && printRecord.id); - if (!Number.isInteger(warehouseId) || warehouseId <= 0 || !Number.isInteger(printId) || printId <= 0) { - continue; - } - - const currentPrintIds = groupedMap.get(warehouseId) || []; - currentPrintIds.push(printId); - groupedMap.set(warehouseId, currentPrintIds); - } - - return groupedMap; -} - -/** - * 自动扫描并触发失败打印补偿任务。 - */ -module.exports = { - schedule: { - interval: '30s', - type: 'worker', - immediate: false, - disable: false, - }, - - /** - * 执行打印失败自动补偿任务。 - * @param {Object} ctx Egg 上下文。 - * @return {Promise} 无返回值。 - */ - async task(ctx) { - const taskName = 'print-retry-compensation'; - const compensationConfig = getCompensationConfig(ctx.app); - - if (!compensationConfig.enable) { - return; - } - - if (ctx.app._printRetryCompensationRunning) { - ctx.logger.info(`[${taskName}] 任务仍在运行中,跳过本轮调度`); - return; - } - - const nowMs = Date.now(); - const lastRunAt = Number(ctx.app._printRetryCompensationLastRunAt || 0); - if (lastRunAt > 0 && (nowMs - lastRunAt) < compensationConfig.intervalMs) { - return; - } - - ctx.app._printRetryCompensationRunning = true; - ctx.app._printRetryCompensationLastRunAt = nowMs; - - let scannedCount = 0; - let invokeCount = 0; - let retriedSuccessCount = 0; - let retriedFailedCount = 0; - let skippedCount = 0; - - try { - const { Op } = ctx.app.Sequelize; - const printRecords = await ctx.model.PrintRecord.findAll({ - attributes: [ 'id', 'warehouse_id', 'retry_count', 'max_retry_count', 'next_retry_at', 'send_status', 'print_status' ], - where: { - [Op.and]: [ - { - [Op.or]: [ - { send_status: 'send_failed' }, - { - print_status: { - [Op.in]: [ 'print_failed', 'timeout' ], - }, - }, - ], - }, - { - next_retry_at: { - [Op.lte]: new Date(), - }, - }, - { - retry_count: { - [Op.lt]: ctx.app.Sequelize.col('max_retry_count'), - }, - }, - ], - }, - order: [ - [ 'next_retry_at', 'ASC' ], - [ 'id', 'ASC' ], - ], - limit: compensationConfig.batchSize, - raw: true, - }); - - scannedCount = Array.isArray(printRecords) ? printRecords.length : 0; - if (scannedCount === 0) { - return; - } - - const groupedPrintIds = groupPrintIdsByWarehouse(printRecords); - for (const [ warehouseId, printIds ] of groupedPrintIds.entries()) { - if (!Array.isArray(printIds) || printIds.length === 0) { - continue; - } - - invokeCount += 1; - try { - const retryResult = await ctx.service.systemMethods.print.retryFailed({ - print_ids: printIds, - warehouse_id: warehouseId, - force: compensationConfig.force, - }); - - if (!retryResult || retryResult.flag !== 'success') { - ctx.logger.warn(`[${taskName}] 触发补打失败`, { - warehouseId, - printIdsCount: printIds.length, - message: retryResult && retryResult.message ? retryResult.message : '未知错误', - }); - continue; - } - - retriedSuccessCount += Number(retryResult.success_count || 0); - retriedFailedCount += Number(retryResult.failed_count || 0); - skippedCount += Number(retryResult.skipped_count || 0); - } catch (error) { - ctx.logger.error(`[${taskName}] 触发补打异常`, { - warehouseId, - printIdsCount: printIds.length, - error: error && error.message ? error.message : `${error}`, - }); - } - } - - ctx.logger.info(`[${taskName}] 任务执行完成`, { - scannedCount, - warehouseGroupCount: groupedPrintIds.size, - invokeCount, - retriedSuccessCount, - retriedFailedCount, - skippedCount, - }); - } catch (error) { - ctx.logger.error(`[${taskName}] 执行失败`, { - error: error && error.message ? error.message : `${error}`, - }); - } finally { - ctx.app._printRetryCompensationRunning = false; - } - }, -}; diff --git a/app/schedule/wave_strategy_quick_scan_fallback.js b/app/schedule/wave_strategy_quick_scan_fallback.js index 15ac52e..7862e07 100644 --- a/app/schedule/wave_strategy_quick_scan_fallback.js +++ b/app/schedule/wave_strategy_quick_scan_fallback.js @@ -28,7 +28,6 @@ module.exports = { let submitSuccessCount = 0; let reusedRunningTaskCount = 0; let submitFailedCount = 0; - let cleanupDeletedCount = 0; try { const storeRows = await ctx.model.Store.findAll({ @@ -124,22 +123,11 @@ module.exports = { } } - try { - cleanupDeletedCount = Number( - await ctx.service.systemMethods.order.wave.cleanupWaveStrategyQuickScanMatchedStrategies({ expireHours: 24 }) - ) || 0; - } catch (cleanupError) { - ctx.logger.warn(`[${FALLBACK_TASK_NAME}] 命中副表清理失败`, { - error: cleanupError && cleanupError.message ? cleanupError.message : `${cleanupError}`, - }); - } - ctx.logger.info(`[${FALLBACK_TASK_NAME}] 任务完成`, { totalWarehouseCount, submitSuccessCount, reusedRunningTaskCount, submitFailedCount, - cleanupDeletedCount, }); } catch (error) { ctx.logger.error(`[${FALLBACK_TASK_NAME}] 任务执行失败: ${error && error.message ? error.message : error}`); diff --git a/app/service/openapiMethods/order.js b/app/service/openapiMethods/order.js index 27be4b4..78adc1c 100644 --- a/app/service/openapiMethods/order.js +++ b/app/service/openapiMethods/order.js @@ -247,16 +247,12 @@ class OpenapiOrderService extends MainService { const qty = Number(item.plan_qty || 0); if (stockId <= 0 || qty <= 0) continue; - await stockModel.update( - { - locked_quantity: app.Sequelize.literal(`locked_quantity - ${qty}`), - updated_at: app.Sequelize.literal('CURRENT_TIMESTAMP'), - }, - { - where: { id: stockId, locked_quantity: { [Op.gte]: qty } }, - transaction, - } - ); + await ctx.service.systems.stockStore.updateLockedQuantity(stockId, -qty, transaction, { + remark: 'OpenAPI取消订单-释放创建锁', + orderType: 'ORDER_CANCEL', + orderNo: String(orderId), + orderId, + }); } return; } @@ -309,22 +305,17 @@ class OpenapiOrderService extends MainService { await ctx.service.systems.storage.index.unlockQuantity(storageId, quantity, { transaction }); // 释放 wms_stock_warehouse.locked_quantity - const decrementResult = await stockModel.update( - { - locked_quantity: app.Sequelize.literal(`locked_quantity - ${Number(quantity)}`), - updated_at: app.Sequelize.literal('CURRENT_TIMESTAMP'), - }, - { - where: { - id: stockId, - locked_quantity: { [Op.gte]: Number(quantity) }, - }, - transaction, + const releaseResult = await ctx.service.systems.stockStore.updateLockedQuantity( + stockId, -Number(quantity), transaction, { + remark: 'OpenAPI取消订单-释放储位锁', + orderType: 'ORDER_CANCEL', + orderNo: String(orderId), + orderId, } ); - if (!Array.isArray(decrementResult) || Number(decrementResult[0] || 0) <= 0) { - throw new Error(`库存主记录锁定数量不足,无法释放: stockId=${stockId}, quantity=${quantity}`); + if (!releaseResult.success) { + throw new Error(`库存主记录释放失败: stockId=${stockId}, ${releaseResult.error}`); } } diff --git a/app/service/qimenMethods/order.js b/app/service/qimenMethods/order.js index 2b2370f..afe6bc1 100644 --- a/app/service/qimenMethods/order.js +++ b/app/service/qimenMethods/order.js @@ -361,16 +361,12 @@ class orderServer extends MainService { const qty = Number(item.plan_qty || 0); if (stockId <= 0 || qty <= 0) continue; - await stockModel.update( - { - locked_quantity: app.Sequelize.literal(`locked_quantity - ${qty}`), - updated_at: app.Sequelize.literal('CURRENT_TIMESTAMP'), - }, - { - where: { id: stockId, locked_quantity: { [Op.gte]: qty } }, - transaction, - } - ); + await ctx.service.systems.stockStore.updateLockedQuantity(stockId, -qty, transaction, { + remark: '奇门取消订单-释放创建锁', + orderType: 'ORDER_CANCEL', + orderNo: String(orderId), + orderId, + }); } return; } @@ -423,22 +419,17 @@ class orderServer extends MainService { await ctx.service.systems.storage.index.unlockQuantity(storageId, quantity, { transaction }); // 释放 wms_stock_warehouse.locked_quantity - const decrementResult = await stockModel.update( - { - locked_quantity: app.Sequelize.literal(`locked_quantity - ${Number(quantity)}`), - updated_at: app.Sequelize.literal('CURRENT_TIMESTAMP'), - }, - { - where: { - id: stockId, - locked_quantity: { [Op.gte]: Number(quantity) }, - }, - transaction, + const releaseResult = await ctx.service.systems.stockStore.updateLockedQuantity( + stockId, -Number(quantity), transaction, { + remark: '奇门取消订单-释放储位锁', + orderType: 'ORDER_CANCEL', + orderNo: String(orderId), + orderId, } ); - if (!Array.isArray(decrementResult) || Number(decrementResult[0] || 0) <= 0) { - throw new Error(`库存主记录锁定数量不足,无法释放: stockId=${stockId}, quantity=${quantity}`); + if (!releaseResult.success) { + throw new Error(`库存主记录释放失败: stockId=${stockId}, ${releaseResult.error}`); } } diff --git a/app/service/qimenMethods/stockout.js b/app/service/qimenMethods/stockout.js index 5f280e9..53abe3f 100644 --- a/app/service/qimenMethods/stockout.js +++ b/app/service/qimenMethods/stockout.js @@ -117,7 +117,8 @@ class stockoutServer extends MainService { item.stockId, item.planQty, transaction, - oversellConfig + oversellConfig, + { orderType: 'QM_STOCKOUT', orderNo: deliveryOrder.deliveryOrderCode, orderId } ); if (!lockResult.success) { throw new Error( diff --git a/app/service/systemMethods/order/pendingOrder.js b/app/service/systemMethods/order/pendingOrder.js index 359e912..29578d2 100644 --- a/app/service/systemMethods/order/pendingOrder.js +++ b/app/service/systemMethods/order/pendingOrder.js @@ -506,9 +506,9 @@ class PendingOrderService extends OrderBaseService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,updateOrderPlatform,updateOrderExpress,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill'; + const _noNeedRight = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,updateOrderPlatform,updateOrderExpress,updateRemark,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill'; const _noNeedLog = 'list,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill'; - const _noNeedAuth = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,updateOrderPlatform,updateOrderExpress,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill'; + const _noNeedAuth = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,updateOrderPlatform,updateOrderExpress,updateRemark,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -2277,8 +2277,7 @@ class PendingOrderService extends OrderBaseService { /** * 批量修改待处理订单的收件地址信息。 * - * 地址字段仅允许在未分配快递(post_status = 'none')时修改; - * remark 不受 post_status 限制,可独立或与地址字段同时传入。 + * 地址字段仅允许在未分配快递(post_status = 'none')时修改。 * 支持批量操作,返回更新数量和受影响的订单 ID 列表。 * * @param {Object} data 请求体。 @@ -2292,7 +2291,6 @@ class PendingOrderService extends OrderBaseService { * @param {string} [data.area] 区/县。 * @param {string} [data.town] 镇/街道。 * @param {string} [data.detail_address] 详细地址。 - * @param {string} [data.remark] 订单留言/备注,对应 wms_order_delivery.remark,最大500字符。 * @return {Promise} 统一 success 包装的更新结果,含 updated_count 与 ids。 */ async updateAddress(data = {}) { @@ -2320,18 +2318,9 @@ class PendingOrderService extends OrderBaseService { } } - // 处理 remark 字段(不受 post_status 限制,最大500字符) - let remarkValue = null; - if (requestData.remark !== undefined && requestData.remark !== null) { - const trimmed = String(requestData.remark).trim(); - if (trimmed !== '') { - remarkValue = trimmed.substring(0, 500); - } - } - const hasAddressUpdates = Object.keys(addressUpdates).length > 0; - if (!hasAddressUpdates && remarkValue === null) { - throw new Error('至少需要提供一个地址字段或备注进行修改'); + if (!hasAddressUpdates) { + throw new Error('至少需要提供一个地址字段进行修改'); } const model = await this.getOrderModel('order', warehouseId); @@ -2339,7 +2328,6 @@ class PendingOrderService extends OrderBaseService { const now = new Date(); let addressUpdatedCount = 0; - let remarkUpdatedCount = 0; // 地址字段更新(受 post_status='none' 限制) if (hasAddressUpdates) { @@ -2349,19 +2337,9 @@ class PendingOrderService extends OrderBaseService { addressUpdatedCount = Number(rows || 0); } - // remark 更新(不受 post_status 限制) - if (remarkValue !== null) { - const remarkUpdate = { remark: remarkValue, updated_at: now }; - const [ rows ] = await model.update(remarkUpdate, { where: baseWhere }); - remarkUpdatedCount = Number(rows || 0); - } - // 记录操作日志 try { - const updatedFieldNames = [ - ...Object.keys(addressUpdates).filter(k => k !== 'updated_at'), - ...(remarkValue !== null ? [ 'remark' ] : []), - ]; + const updatedFieldNames = Object.keys(addressUpdates).filter(k => k !== 'updated_at'); await this.ctx.service.systems.operationLog.createOperationLog({ businessType: 'order', businessId: logWarehouseId, @@ -2371,10 +2349,9 @@ class PendingOrderService extends OrderBaseService { warehouseId: logWarehouseId, orderIds, updated_fields: updatedFieldNames, - updated_count: Math.max(addressUpdatedCount, remarkUpdatedCount), + updated_count: addressUpdatedCount, address_updated_count: addressUpdatedCount, - remark_updated_count: remarkUpdatedCount, - message: `批量修改订单收件地址:订单ID [${orderIds.join(', ')}],更新字段 [${updatedFieldNames.join(', ')}],地址更新 ${addressUpdatedCount} 条,备注更新 ${remarkUpdatedCount} 条`, + message: `批量修改订单收件地址:订单ID [${orderIds.join(', ')}],更新字段 [${updatedFieldNames.join(', ')}],地址更新 ${addressUpdatedCount} 条`, }, beforeChanges: null, }); @@ -2383,7 +2360,86 @@ class PendingOrderService extends OrderBaseService { } return this.success('ok', { - updated_count: Math.max(addressUpdatedCount, remarkUpdatedCount), + updated_count: addressUpdatedCount, + ids: orderIds, + }); + } + + /** + * 批量修改待处理订单的备注(remark)字段。 + * + * 与 updateAddress 中的 remark 更新逻辑相似, + * 但作为独立接口只负责备注修改,不涉及地址字段。 + * remark 修改不受 post_status 限制,对所有状态的订单均可生效。 + * + * @param {Object} data 请求体。 + * @param {Array} data.ids 订单ID数组(必填,正整数数组)。 + * @param {string} data.remark 备注内容(必填,最大500字符)。 + * @return {Promise} 统一 success 包装的更新结果,含 updated_count 与 ids。 + */ + async updateRemark(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const warehouseId = this.getWarehouseId(); + const operator = this.getOrderLogOperator(); + const logWarehouseId = this.getOrderLogWarehouseId(warehouseId); + + // 解析订单 ID(仅支持数组) + const rawOrderIds = requestData.ids; + if (!Array.isArray(rawOrderIds) || rawOrderIds.length === 0) { + throw new Error('ids 不能为空,且必须是正整数数组'); + } + + const orderIds = Array.from(new Set(rawOrderIds.map(v => { + const n = Number(v); + if (!Number.isInteger(n) || n <= 0) { + throw new Error('ids 仅支持正整数数组'); + } + return n; + }))); + + // 解析 remark + const rawRemark = requestData.remark; + if (rawRemark === undefined || rawRemark === null) { + throw new Error('remark 不能为空'); + } + const trimmed = String(rawRemark).trim(); + if (trimmed === '') { + throw new Error('remark 不能为空字符串'); + } + const remarkValue = trimmed.substring(0, 500); + + const model = await this.getOrderModel('order', warehouseId); + const where = this.buildOrderWhere(orderIds, warehouseId); + const now = new Date(); + + const [ affectedRows ] = await model.update( + { remark: remarkValue, updated_at: now }, + { where }, + ); + const count = Number(affectedRows || 0); + + // 记录操作日志 + try { + await this.ctx.service.systems.operationLog.createOperationLog({ + businessType: 'order', + businessId: logWarehouseId, + operationCode: 'ORDER_UPDATE_REMARK', + operator, + extras: { + warehouseId: logWarehouseId, + orderIds, + remark: remarkValue, + updated_count: count, + message: `批量修改订单备注:订单ID [${orderIds.join(', ')}],备注内容 [${remarkValue}],共更新 ${count} 条`, + }, + beforeChanges: null, + }); + } catch (logErr) { + this.ctx.logger.warn('[PendingOrderService.updateRemark] 写入操作日志失败,不影响业务', logErr); + } + + return this.success('ok', { + updated_count: count, ids: orderIds, }); } @@ -2834,7 +2890,7 @@ class PendingOrderService extends OrderBaseService { detailAddress, zipCode: String(requestData.zip_code || '').trim(), }, - seller_message: String(requestData.remark || '').trim(), + remark: String(requestData.remark || '').trim(), }, orderLines: { orderLine: orderLineItems, @@ -5316,23 +5372,19 @@ class PendingOrderService extends OrderBaseService { } // 释放 wms_stock_warehouse.locked_quantity + const stockService = ctx.service && ctx.service.systems && ctx.service.systems.stockStore; for (const [ stockId, quantity ] of stockReleaseMap.entries()) { - const [ affectedCount ] = await stockModel.update( - { - locked_quantity: app.Sequelize.literal(`locked_quantity - ${Number(quantity)}`), - updated_at: app.Sequelize.literal('CURRENT_TIMESTAMP'), - }, - { - where: { - id: stockId, - locked_quantity: { [Op.gte]: Number(quantity) }, - }, - transaction, + const releaseResult = await stockService.updateLockedQuantity( + stockId, -Number(quantity), transaction, { + remark: '系统取消订单-释放创建锁', + orderType: 'ORDER_CANCEL', + orderNo: orderIds.join(','), + orderId: 0, } ); - if (Number(affectedCount || 0) <= 0) { - throw new Error(`库存主记录锁定数量不足,无法释放创建锁: stockId=${stockId}, quantity=${quantity}`); + if (!releaseResult.success) { + throw new Error(`库存主记录锁定数量不足,无法释放创建锁: stockId=${stockId}, quantity=${quantity}, ${releaseResult.error}`); } } diff --git a/app/service/systemMethods/storage/entry.js b/app/service/systemMethods/storage/entry.js index 808062e..dfaa61e 100644 --- a/app/service/systemMethods/storage/entry.js +++ b/app/service/systemMethods/storage/entry.js @@ -38,14 +38,18 @@ class entryService extends MainService { } /** - * 查询入库单详情。仅通过入库单 ID 定位。 - * @param {Object} data 请求体 - * @param {number} data.id 入库单ID(必填) - * @return {Promise} 统一 success 包装 - */ + * 查询入库单详情(与原 storage.directInbound.getItems 输出格式一致)。 + * 返回入库单基本信息(id、entry_order_code、order_status、store_remask)、 + * 商品明细列表(含计划数量、已完成入库数量、商品信息、收货单绑定明细), + * 以及收货单绑定关系列表。 + * @param {Object} data 请求体 + * @param {number} data.id 入库单ID(必填) + * @return {Promise} 统一 success 包装 + */ async get(data = {}) { const { service } = this; - const result = await service.systems.storage.entry.get(data); + const { id } = data || {}; + const result = await service.systems.storage.entry.get({ id }); return this.success('ok', result); } @@ -66,16 +70,41 @@ class entryService extends MainService { /** * 按商品增量添加导入/PDA 直接入库记录(从 storage.entry 模块暴露)。 * @param {Object} data 请求体 - * @param {string} data.entry_order_code 入库单号 + * @param {number} data.entry_order_id 入库单ID * @param {number} [data.stock_id] 商品SKU ID(单条模式) * @param {number} [data.quantity] 本次入库数量(单条模式) * @param {string} [data.inbound_type] 入库方式(单条模式) * @param {Array} [data.items] 商品列表(批量模式) + * @param {string} [data.remark] 备注(单条模式) + * @param {number} [data.space_id] 库位ID(单条模式) + * @param {number} [data.receiving_detail_id] 收货单明细ID(单条模式,可选) + * @param {number} [data.allocated_quantity] 预分配数量(单条模式,可选) * @return {Promise} 统一 success 包装 */ async addItem(data = {}) { const { service } = this; - const result = await service.systems.inboundDirectLog.addItem(data); + const { + entry_order_id, + stock_id, + quantity, + inbound_type, + items, + remark, + space_id, + receiving_detail_id, + allocated_quantity, + } = data || {}; + const result = await service.systems.inboundDirectLog.addItem({ + entry_order_id, + stock_id, + quantity, + inbound_type, + items, + remark, + space_id, + receiving_detail_id, + allocated_quantity, + }); return this.success('ok', result); } @@ -166,20 +195,42 @@ class entryService extends MainService { * @return {Promise} 打印数据(扁平键值 + items 明细数组) */ async getPrintData(data = {}) { - const { ctx, service } = this; + const { ctx } = this; const id = Number(data && data.id || 0); if (!id) { return this.fail('id 参数不能为空', { code: 400 }); } try { - const entryResult = await service.systems.storage.entry.get({ id }); - if (!entryResult || entryResult.code !== 200 || !entryResult.data || !entryResult.data.entryOrder) { + // 直接查询入库单完整信息(含 items、warehouse、store 等关联),供打印模板使用 + const entryOrder = await ctx.model.EntryOrder.findByPk(id, { + include: [ + { + model: ctx.model.Store, + as: 'warehouse', + attributes: [ 'id', 'company_name' ], + required: false, + }, + { + model: ctx.model.Store, + as: 'store', + attributes: [ 'id', 'company_name' ], + required: false, + }, + { + model: ctx.model.EntryItems, + as: 'items', + required: false, + }, + ], + }); + + if (!entryOrder || entryOrder.warehouse_id !== ctx.user.store_id || !entryOrder.is_enabled) { return this.fail('入库单不存在', { code: 404 }); } - const entryOrder = entryResult.data.entryOrder; - const items = Array.isArray(entryOrder.items) ? entryOrder.items : []; + const entryOrderJSON = entryOrder.toJSON(); + const items = Array.isArray(entryOrderJSON.items) ? entryOrderJSON.items : []; // 查询商品条码和图片(复用 getStockDetails 缓存) const barcodeMap = new Map(); @@ -213,22 +264,22 @@ class entryService extends MainService { } const printData = { - entry_order_code: entryOrder.entry_order_code || '', - order_type: entryOrder.order_type || '', - order_status: entryOrder.order_status || '', - purchase_order_code: entryOrder.purchase_order_code || '', - supplier_name: entryOrder.supplier_name || '', - warehouse_name: entryOrder.warehouse_name || '', - store_name: entryOrder.store_name || '', - logistics_name: entryOrder.logistics_name || '', - express_code: entryOrder.express_code || '', - order_create_time: entryOrder.order_create_time || '', - expect_start_time: entryOrder.expect_start_time || '', - remark: entryOrder.remark || '', - total_order_lines: entryOrder.total_order_lines || 0, + entry_order_code: entryOrderJSON.entry_order_code || '', + order_type: entryOrderJSON.order_type || '', + order_status: entryOrderJSON.order_status || '', + purchase_order_code: entryOrderJSON.purchase_order_code || '', + supplier_name: entryOrderJSON.supplier_name || '', + warehouse_name: entryOrderJSON.warehouse_name || '', + store_name: entryOrderJSON.store_name || '', + logistics_name: entryOrderJSON.logistics_name || '', + express_code: entryOrderJSON.express_code || '', + order_create_time: entryOrderJSON.order_create_time || '', + expect_start_time: entryOrderJSON.expect_start_time || '', + remark: entryOrderJSON.remark || '', + total_order_lines: entryOrderJSON.total_order_lines || 0, items: items.map(item => ({ - items_col1: item.warehouse_item_code || item.external_item_code || '', - items_col2: item.warehouse_item_name || '', + items_col1: item.item_code || '', + items_col2: '', items_col3: (barcodeMap.get(Number(item.stock_id)) || []).join(';') || '', items_col4: item.count || 0, items_col5: item.received_quantity || 0, diff --git a/app/service/systems/delivery_order.js b/app/service/systems/delivery_order.js index 0fa7e8c..c16d86b 100644 --- a/app/service/systems/delivery_order.js +++ b/app/service/systems/delivery_order.js @@ -1221,7 +1221,8 @@ class DeliveryOrderService extends Service { item.stockId, item.planQty, transaction, - oversellConfig + oversellConfig, + { orderType: 'DELIVERY_ORDER', orderNo: String(orderId), orderId } ); if (!lockResult.success) { diff --git a/app/service/systems/inbound_direct_log.js b/app/service/systems/inbound_direct_log.js index 13087e2..d495c85 100644 --- a/app/service/systems/inbound_direct_log.js +++ b/app/service/systems/inbound_direct_log.js @@ -76,16 +76,21 @@ class InboundDirectLogService extends Service { raw: true, }); - // 查询该入库单下已有的导入/PDA 入库记录 + // 查询该入库单下已有的导入/PDA 入库记录(显式过滤软删除,仅统计未删除记录) const directLogs = await ctx.model.InboundDirectLog.findAll({ - where: { entry_order_id: entryOrder.id }, + where: { entry_order_id: entryOrder.id, deleted_at: null }, order: [[ 'created_at', 'ASC' ]], }); // 将直接入库记录按 entry_item_id 关联到明细 + // 优先使用 entry_item_id 精确匹配(绑定模式),其次回退到 stock_id 匹配(非绑定模式) const itemDirectLogs = {}; for (const log of directLogs) { - const item = entryOrder.items.find( + // 绑定模式下 entry_item_id 已设置,优先用它定位明细行 + const itemByEntryItemId = log.entry_item_id + ? entryOrder.items.find(i => String(i.id) === String(log.entry_item_id)) + : null; + const item = itemByEntryItemId || entryOrder.items.find( i => String(i.stock_id) === String(log.stock_id) ); const key = item ? String(item.id) : `stock_${log.stock_id}`; @@ -135,12 +140,17 @@ class InboundDirectLogService extends Service { const logKey = String(item.id); const logs = itemDirectLogs[logKey] || []; const directInQty = logs.reduce((sum, l) => sum + Number(l.quantity), 0); + // 优先使用已持久化的 received_quantity(commit 后由系统写入), + // 若为 0 则回退到 InboundDirectLog 汇总(尚未提交时的导入量), + // 确保绑定收货明细场景下 completed 口径与 received_quantity 一致。 + const receivedQty = Number(item.received_quantity) || 0; + const completed = receivedQty > 0 ? receivedQty : directInQty; return { id: item.id, stock_id: item.stock_id, planned: planQty, - completed: directInQty, + completed, stock: stockMap.get(Number(item.stock_id)) || null, }; }); @@ -345,7 +355,9 @@ class InboundDirectLogService extends Service { return { ok: false, error: { code: 400, message: `入库单中不存在 stock_id=${stockId} 的商品` } }; } + // 计算该 stock_id 在入库单明细中的计划总数与已收货总数 const totalPlanQty = entryItems.reduce((sum, ei) => sum + (Number(ei.count) || 0), 0); + const totalReceivedQty = entryItems.reduce((sum, ei) => sum + (Number(ei.received_quantity) || 0), 0); // 计算该 stock_id 在该入库单下已有的导入/PDA 入库总量 const logWhere = { entry_order_id: entryOrder.id, stock_id: stockId }; @@ -357,10 +369,10 @@ class InboundDirectLogService extends Service { }); const existingTotal = existingLogs.reduce((sum, log) => sum + Number(log.quantity), 0); - // 绑定模式下跳过入库单计划数量校验(允许超过计划数量) - // 只有 PENDING 非绑定模式限制超量;CREATED 人工导入允许超过 + // 绑定模式和非绑定模式均受可入库数量限制 + // CREATED 人工导入允许超过计划数量 const isManualImport = entryOrder.order_status === 'CREATED' && !isBindingMode; - if (!isBindingMode && !isManualImport) { + if (!isManualImport) { const newTotal = existingTotal + effectiveQuantity; if (newTotal > totalPlanQty) { return { @@ -380,9 +392,56 @@ class InboundDirectLogService extends Service { } } + // 剩余可入库数 = 计划数 - max(已收货量, 已写入 direct_log 的待入库量) + // 避免多次 addItem 之间 received_quantity 始终为 0 导致的重复入库漏拦截 + { + const occupiedQuantity = Math.max(totalReceivedQty, existingTotal); + const remainingQuantity = Math.max(0, totalPlanQty - occupiedQuantity); + if (remainingQuantity <= 0) { + return { + ok: false, + error: { + code: 400, + message: `商品 stock_id=${stockId} 无可入库数量:计划 ${totalPlanQty},已收货 ${totalReceivedQty}`, + }, + }; + } + if (effectiveQuantity > remainingQuantity) { + effectiveQuantity = remainingQuantity; + } + } + const newTotal = existingTotal + effectiveQuantity; - // 写入记录 + // 绑定模式:只由 _bindReceivingDetail 负责写入(status='pending'),避免重复插入两条记录 + if (isBindingMode) { + item.allocated_quantity = effectiveQuantity; + const receivingBindResult = await this._bindReceivingDetail( + ctx, entryOrder, item, stockId, receivingDetailId, effectiveQuantity, transaction + ); + + if (receivingBindResult && receivingBindResult.error) { + return { ok: false, error: { code: 400, message: receivingBindResult.error } }; + } + + return { + ok: true, + log: { + id: receivingBindResult?.binding_id || 0, + stock_id: stockId, + quantity: effectiveQuantity, + inbound_type: inboundType, + space_id: spaceId, + plan_quantity: totalPlanQty, + existing_before: existingTotal, + existing_after: newTotal, + remaining: Math.max(0, totalPlanQty - newTotal), + receivingBindResult, + }, + }; + } + + // 非绑定模式:直接写入一条无收货明细绑定的入库记录 const log = await ctx.model.InboundDirectLog.create({ warehouse_id: entryOrder.warehouse_id, store_id: entryOrder.store_id, @@ -398,20 +457,6 @@ class InboundDirectLogService extends Service { created_at: new Date(), }, transaction ? { transaction } : {}); - // 收货单明细绑定(可选) - let receivingBindResult = null; - if (isBindingMode) { - // 绑定模式:全量绑定,allocated_quantity = effectiveQuantity - item.allocated_quantity = effectiveQuantity; - receivingBindResult = await this._bindReceivingDetail( - ctx, entryOrder, item, stockId, receivingDetailId, effectiveQuantity, transaction - ); - } else if (receivingDetailId) { - receivingBindResult = await this._bindReceivingDetail( - ctx, entryOrder, item, stockId, receivingDetailId, effectiveQuantity, transaction - ); - } - return { ok: true, log: { @@ -424,7 +469,6 @@ class InboundDirectLogService extends Service { existing_before: existingTotal, existing_after: newTotal, remaining: Math.max(0, totalPlanQty - newTotal), - ...(receivingBindResult ? { receivingBindResult } : {}), }, }; } @@ -773,9 +817,9 @@ class InboundDirectLogService extends Service { return { code: 400, message: '入库单已完成,请勿重复提交', data: null }; } - // 查询该入库单下所有导入/PDA 入库记录 + // 查询该入库单下所有未删除的导入/PDA 入库记录 const directLogs = await ctx.model.InboundDirectLog.findAll({ - where: { entry_order_id: entryOrder.id }, + where: { entry_order_id: entryOrder.id, deleted_at: null }, }); if (!directLogs || directLogs.length === 0) { @@ -847,7 +891,7 @@ class InboundDirectLogService extends Service { if (detailIds.length > 0) { const details = await ctx.model.ReceivingDetail.findAll({ where: { id: detailIds }, - attributes: [ 'id', 'receiving_id', 'batch_number', 'production_date', 'expiry_date' ], + attributes: [ 'id', 'receiving_id', 'batch_number', 'production_date', 'expiry_date', 'actual_quantity' ], raw: true, }); const detailById = new Map(details.map(d => [ d.id, d ])); @@ -857,17 +901,55 @@ class InboundDirectLogService extends Service { } } + // 按 entry_item_id 汇总 wms_inbound_direct_log 的入库数量 + const itemDirectLogQtyMap = {}; + for (const log of directLogs) { + if (log.entry_item_id) { + const itemKey = String(log.entry_item_id); + if (!itemDirectLogQtyMap[itemKey]) itemDirectLogQtyMap[itemKey] = 0; + itemDirectLogQtyMap[itemKey] += Number(log.quantity); + } + } + // 逐商品写入库存 + // 非绑定模式下同一 stock_id 可能对应多个 entryItem,按顺序: + // 第一个 entryItem 写库存和 received_quantity,后续同 stock_id 的 entryItem 仅写 received_quantity=0 + const nonBindingStockProcessed = new Set(); for (const item of entryItems) { const stockId = item.stock_id; if (!stockId) continue; - const inboundQty = stockSummary[String(stockId)] || 0; + // 按 entry_item 维度获取该明细的直接入库汇总数量 + const itemDirectQty = itemDirectLogQtyMap[String(item.id)] || 0; + const isBinding = itemDirectQty > 0; + const inboundQty = isBinding + ? itemDirectQty + : (stockSummary[String(stockId)] || 0); if (inboundQty <= 0) continue; - // 更新入库明细的 received_quantity(按该明细的计划占比分配) - const planQty = Number(item.count) || 0; - const itemReceivedQty = planQty > 0 ? Math.min(planQty, inboundQty) : inboundQty; + // 判断是否为绑定模式:比较收货明细数量与入库记录数量 + const bindInfo = bindingDetailMap.get(item.id); + let itemReceivedQty = inboundQty; + if (bindInfo) { + // 收货明细的实际数量 + const rdQty = Number(bindInfo.actual_quantity) || 0; + // 该 entry_item 对应的入库记录汇总数量 + const logSumQty = itemDirectLogQtyMap[String(item.id)] || 0; + if (rdQty > logSumQty) { + // 收货明细数量 > 入库记录数量 → 部分入库,仅入库实际记录的数量 + itemReceivedQty = logSumQty; + } else { + // 收货明细数量 <= 入库记录数量 → 全部入库 + itemReceivedQty = rdQty; + } + } + + // 非绑定模式:同一 stock_id 只对第一个 entryItem 写入 received_quantity,后续写 0 + if (!isBinding && nonBindingStockProcessed.has(String(stockId))) { + itemReceivedQty = 0; + } + + // 更新入库明细的 received_quantity await ctx.model.EntryItems.update({ received_quantity: itemReceivedQty, }, { @@ -878,9 +960,11 @@ class InboundDirectLogService extends Service { // 同一 stock_id 只写一次库存 if (processedStockIds.has(String(stockId))) continue; processedStockIds.add(String(stockId)); + if (!isBinding) { + nonBindingStockProcessed.add(String(stockId)); + } // 使用入库单号作为批次号;若有收货绑定则使用收货明细信息 - const bindInfo = bindingDetailMap.get(item.id); const rdReceivingId = bindInfo ? bindInfo.receiving_id : null; const effectiveBatchNo = bindInfo?.batch_number || eo.entry_order_code; const rdProductionDate = bindInfo?.production_date || null; diff --git a/app/service/systems/order_storage_allocation.js b/app/service/systems/order_storage_allocation.js index 2c7a852..83f5e9c 100644 --- a/app/service/systems/order_storage_allocation.js +++ b/app/service/systems/order_storage_allocation.js @@ -865,27 +865,6 @@ class OrderStorageAllocationService extends MainService { }); if (Array.isArray(oldPickingRecords) && oldPickingRecords.length > 0) { - // 批量查询旧 picking 记录关联的 wms_storage,获取 stock_id 用于回退 StockWarehouse.locked_quantity - const oldStorageIds = oldPickingRecords - .map(record => toNumber(record.storage_id, 0)) - .filter(storageId => storageId > 0); - const oldStorageMap = new Map(); - if (oldStorageIds.length > 0) { - const oldStorageRows = await ctx.model.Storage.findAll({ - where: { id: { [Op.in]: oldStorageIds }, warehouse_id: warehouseId }, - attributes: [ 'id', 'stock_id' ], - transaction, - lock: transaction.LOCK.UPDATE, - raw: true, - }); - for (const oldStorageRow of Array.isArray(oldStorageRows) ? oldStorageRows : []) { - const plain = toPlainRecord(oldStorageRow); - if (plain && Number(plain.id) > 0) { - oldStorageMap.set(Number(plain.id), toNumber(plain.stock_id, 0)); - } - } - } - for (const record of oldPickingRecords) { const storageId = toNumber(record.storage_id, 0); const quantity = toNumber(record.quantity, 0); @@ -893,22 +872,11 @@ class OrderStorageAllocationService extends MainService { if (storageId > 0 && quantity > 0) { await ctx.service.systems.storage.index.unlockQuantity(storageId, quantity, { transaction }); - // 同步回退 wms_stock_warehouse 的锁定数量 - const oldStockId = oldStorageMap.get(storageId) || 0; - if (oldStockId > 0) { - await ctx.model.StockWarehouse.decrement('locked_quantity', { - by: quantity, - where: { id: oldStockId }, - transaction, - }); - } - - writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 已释放旧库存锁定(含stock_warehouse同步)', { + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 已释放旧库存锁定', { warehouseId, orderId: toNumber(record.order_id, 0), storageId, quantity, - stockId: oldStockId, }); } } @@ -1115,14 +1083,7 @@ class OrderStorageAllocationService extends MainService { await ctx.service.systems.storage.index.lockQuantity(storageRow.id, allocationQuantity, { transaction }); - // 同步更新 wms_stock_warehouse 的锁定数量 - await ctx.model.StockWarehouse.increment('locked_quantity', { - by: allocationQuantity, - where: { id: storageRow.stock_id }, - transaction, - }); - - writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 库存锁定完成(含stock_warehouse同步)', { + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 库存锁定完成', { orderId, orderItemId: toNumber(orderItem.id, 0), stockId, @@ -1176,13 +1137,6 @@ class OrderStorageAllocationService extends MainService { storageRow.id, allocationQuantity, { transaction } ); - // 同步回退 wms_stock_warehouse 的锁定数量 - await ctx.model.StockWarehouse.decrement('locked_quantity', { - by: allocationQuantity, - where: { id: storageRow.stock_id }, - transaction, - }); - // 回退内存计数器:storageRow 的 available_quantity 和 locked_quantity storageRow.available_quantity = currentAvailable; storageRow.locked_quantity = toNumber(storageRow.locked_quantity, 0) - allocationQuantity; @@ -1205,7 +1159,7 @@ class OrderStorageAllocationService extends MainService { storageAllocationMap.set(storageRow.id, newStorageQty); } - writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 库位无效,回退库存主表锁定累加及内存计数器', { + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 库位无效,回退内存计数器', { orderId, storageId: storageRow.id, allocationQuantity, @@ -1310,15 +1264,6 @@ class OrderStorageAllocationService extends MainService { lockRecord.storageId, lockRecord.quantity, { transaction } ); - // 同步回退 wms_stock_warehouse 的锁定数量 - if (lockRecord.stockId && lockRecord.stockId > 0) { - await ctx.model.StockWarehouse.decrement('locked_quantity', { - by: lockRecord.quantity, - where: { id: lockRecord.stockId }, - transaction, - }); - } - // 回退 storageAllocationMap 中的累加值 const prevStorageQty = storageAllocationMap.get(lockRecord.storageId) || 0; const newStorageQty = prevStorageQty - lockRecord.quantity; @@ -2259,15 +2204,6 @@ class OrderStorageAllocationService extends MainService { transaction, }); - // 同步减少 wms_stock_warehouse 的锁定数量 - if (storageRow.stock_id && storageRow.stock_id > 0) { - await ctx.model.StockWarehouse.decrement('locked_quantity', { - by: quantity, - where: { id: storageRow.stock_id }, - transaction, - }); - } - // 写入储位解锁流水 await ctx.model.StorageTransaction.create({ transaction_type: 'UNLOCK', diff --git a/app/service/systems/stock_store.js b/app/service/systems/stock_store.js index af6c592..f96a6c8 100644 --- a/app/service/systems/stock_store.js +++ b/app/service/systems/stock_store.js @@ -657,6 +657,120 @@ class stockStoreService extends Service { }; } + /** + * 统一修改 wms_stock_warehouse.locked_quantity 并写入 stock_transaction 流水。 + * 所有对 locked_quantity 的写操作必须通过此函数,禁止直接 increment/decrement/update。 + * + * @param {number} stockId StockWarehouse.id。 + * @param {number} change 变更量,正数为加锁,负数为解锁。 + * @param {Object} currentTransaction 数据库事务对象。 + * @param {Object} [meta={}] 元信息。 + * @param {boolean} [meta.allowOversell=false] 是否允许超卖,为 true 时跳过可用库存校验。 + * @param {boolean} [meta.skipTransactionLog=false] 是否跳过流水写入。 + * @param {string} [meta.orderType] 订单类型,用于流水。 + * @param {string} [meta.orderNo] 订单号。 + * @param {number} [meta.orderId] 订单ID。 + * @param {string} [meta.remark] 备注。 + * @param {string} [meta.operatorId] 操作人ID。 + * @param {string} [meta.operatorName] 操作人姓名。 + * @return {Promise<{success: boolean, error?: string, data?: Object}>} + */ + async updateLockedQuantity(stockId, change, currentTransaction, meta = {}) { + const { ctx, app } = this; + const absQty = Math.abs(change); + const isLocking = change > 0; + + if (!stockId || absQty <= 0) { + return { success: false, error: `参数无效: stockId=${stockId}, change=${change}` }; + } + + const stockRecord = await ctx.model.StockWarehouse.findOne({ + where: { id: stockId, is_valid: 'Y', deleted_at: null }, + transaction: currentTransaction, + lock: currentTransaction.LOCK.UPDATE, + attributes: [ 'id', 'store_id', 'warehouse_id', 'quantity', 'locked_quantity' ], + raw: false, + }); + + if (!stockRecord) { + return { success: false, error: `库存记录不存在或已失效 (ID: ${stockId})` }; + } + + const beforeQuantity = Number(stockRecord.quantity) || 0; + const beforeLocked = Number(stockRecord.locked_quantity) || 0; + + // 加锁校验:可用库存(允许超卖时跳过此校验) + if (isLocking && meta.allowOversell !== true) { + const availableQty = beforeQuantity - beforeLocked; + if (availableQty < absQty) { + return { + success: false, + error: `库存不足,可用 ${availableQty},需求 ${absQty}`, + data: { available: availableQty, required: absQty }, + }; + } + } + + // 解锁校验:锁定库存足够 + if (!isLocking && beforeLocked < absQty) { + return { + success: false, + error: `释放数量超过已锁定库存,已锁 ${beforeLocked},尝试释放 ${absQty}`, + }; + } + + // 执行写操作 + await stockRecord.increment('locked_quantity', { + by: change, + transaction: currentTransaction, + silent: true, + }); + + const afterLocked = beforeLocked + change; + const afterQuantity = beforeQuantity; // locked_quantity 变更不影响 quantity + + // 写入流水(除非显式跳过) + const skipLog = meta.skipTransactionLog === true; + if (!skipLog && ctx.service && ctx.service.systems && ctx.service.systems.stockTransaction) { + // transaction_type 字段为 ENUM('INBOUND','OUTBOUND'),锁定/解锁属于出库流程 + await ctx.service.systems.stockTransaction.create({ + transaction_type: 'OUTBOUND', + warehouse_id: stockRecord.warehouse_id, + store_id: stockRecord.store_id, + stock_id: stockId, + quantity: absQty, + order_type: meta.orderType || null, + order_no: meta.orderNo || null, + order_id: meta.orderId || null, + operator_id: meta.operatorId || String(ctx.user?.employees_id ?? ctx.user?.id ?? ''), + operator_name: meta.operatorName || ctx.user?.employees_name || '', + remark: meta.remark || `库存${isLocking ? '锁定' : '释放'}`, + before_quantity: beforeQuantity, + after_quantity: afterQuantity, + before_locked_quantity: beforeLocked, + after_locked_quantity: afterLocked, + created_at: new Date(), + }, { transaction: currentTransaction }); + } + + app.logger.info( + `[库存${isLocking ? '锁定' : '释放'}] ID: ${stockId}, ${isLocking ? '+' : '-'}${absQty}, 锁定后: ${afterLocked}` + ); + + return { + success: true, + data: { + id: stockId, + action: isLocking ? 'lock' : 'unlock', + quantity: absQty, + beforeLocked, + afterLocked, + totalQuantity: afterQuantity, + available: afterQuantity - afterLocked, + }, + }; + } + /** * 锁定或释放库存。 * @@ -664,154 +778,57 @@ class stockStoreService extends Service { * @param {number} quantity 锁定数量,负数表示释放。 * @param {Object|null} transaction 数据库事务。 * @param {Object|null} [oversellConfig=null] 可选预取策略配置,用于避免锁内查DB。 + * @param {Object} [meta={}] 可选元信息,透传给 updateLockedQuantity 用于流水记录。 * @return {Promise} 锁定结果。 */ - async lockItemStorages(stockWarehouseId, quantity, transaction, oversellConfig = null) { - const { - ctx, - app, - } = this; + async lockItemStorages(stockWarehouseId, quantity, transaction, oversellConfig = null, meta = {}) { + const { app } = this; - // 输入验证 const lockQty = parseInt(quantity); if (!stockWarehouseId || isNaN(lockQty) || lockQty === 0) { - return { - success: false, - error: `参数错误:库存ID无效或数量为0 (ID: ${stockWarehouseId}, Qty: ${quantity})`, - data: null, - }; + return { success: false, error: '参数错误:库存ID无效或数量为0', data: null }; } - const isLocking = lockQty > 0; // true=加锁,false=减锁 + const isLocking = lockQty > 0; const absQty = Math.abs(lockQty); try { return await this._runWithTransaction(transaction, async currentTransaction => { - // 1. 查询并锁定记录(悲观锁) - const stockRecord = await ctx.model.StockWarehouse.findOne({ - where: { - id: stockWarehouseId, - is_valid: 'Y', - deleted_at: null, - }, - transaction: currentTransaction, - lock: currentTransaction.LOCK.UPDATE, - attributes: [ 'id', 'store_id', 'warehouse_id', 'quantity', 'locked_quantity', 'gross_weight' ], - raw: false, + const allowOversell = oversellConfig ? oversellConfig.allowOversell : false; + + const result = await this.updateLockedQuantity(stockWarehouseId, lockQty, currentTransaction, { + remark: meta.remark || (isLocking ? '出库单创建锁定' : '出库单创建解锁'), + orderType: meta.orderType || null, + orderNo: meta.orderNo || null, + orderId: meta.orderId || null, + allowOversell: isLocking ? allowOversell : undefined, }); - if (!stockRecord) { - return { - success: false, - error: `库存记录不存在或已失效 (ID: ${stockWarehouseId})`, - data: null, - }; + if (!result.success) { + return result; } - if (isLocking) { - const availableQty = stockRecord.quantity - stockRecord.locked_quantity; - if (availableQty < absQty) { - // 优先使用外部预取的 oversellConfig,避免锁内查 DB - let allowOversell = oversellConfig ? oversellConfig.allowOversell : null; - if (allowOversell === null || allowOversell === undefined) { - // 回退:未预取时走原有查询(兼容其他调用方) - const policyConfig = await this.getStoreWarehousePolicyConfigByStockId(stockRecord, currentTransaction); - allowOversell = policyConfig.allowOversell; - } - if (!allowOversell) { - return { - success: false, - error: `库存不足,可用 ${availableQty},需求 ${absQty}`, - data: { - available: availableQty, - required: absQty, - recordId: stockWarehouseId, - }, - }; - } - } - } else { - if (stockRecord.locked_quantity < absQty) { - return { - success: false, - error: `释放数量超过已锁定库存,已锁 ${stockRecord.locked_quantity},尝试释放 ${absQty}`, - data: null, - }; - } - - const newLocked = stockRecord.locked_quantity - absQty; - if (newLocked < 0) { - return { - success: false, - error: `释放后锁定库存为负值: ${newLocked}`, - data: null, - }; - } - } - - if (isLocking) { - await stockRecord.increment('locked_quantity', { - by: absQty, - transaction: currentTransaction, - silent: true, - }); - app.logger.info( - `[库存锁定] ID: ${stockWarehouseId}, 增加锁定: +${absQty}, 锁定后: ${stockRecord.locked_quantity + absQty}` - ); - } else { - await stockRecord.decrement('locked_quantity', { - by: absQty, - transaction: currentTransaction, - silent: true, - }); - app.logger.info( - `[库存释放] ID: ${stockWarehouseId}, 减少锁定: -${absQty}, 锁定后: ${stockRecord.locked_quantity - absQty}` - ); - } - - await stockRecord.reload({ - transaction: currentTransaction, - }); - + const { beforeLocked, afterLocked, totalQuantity } = result.data; return { success: true, data: { id: stockWarehouseId, action: isLocking ? 'lock' : 'unlock', quantity: absQty, - beforeLocked: isLocking ? stockRecord.locked_quantity - absQty : stockRecord.locked_quantity + - absQty, - afterLocked: stockRecord.locked_quantity, - totalQuantity: stockRecord.quantity, - available: stockRecord.quantity - stockRecord.locked_quantity, - updatedAt: stockRecord.update_at, + beforeLocked, + afterLocked, + totalQuantity, + available: totalQuantity - afterLocked, }, error: null, }; }); } catch (error) { - app.logger.error('[lockItemStorages] 系统异常', { - stockWarehouseId, - quantity, - isLocking, - error: error.message, - stack: error.stack, - }); - - // 根据错误类型返回 + app.logger.error('[lockItemStorages] 系统异常', { stockWarehouseId, quantity, isLocking, error: error.message }); if (error.name && error.name.includes('Sequelize')) { - return { - success: false, - error: `数据库操作失败: ${error.message}`, - data: null, - }; + return { success: false, error: `数据库操作失败: ${error.message}`, data: null }; } - - return { - success: false, - error: `系统错误: ${error.message}`, - data: null, - }; + return { success: false, error: `系统错误: ${error.message}`, data: null }; } } /** @@ -1238,32 +1255,34 @@ class stockStoreService extends Service { return failureResult; } - // 4. 执行出库扣减(同时减少quantity和locked_quantity) - const result = await ctx.model.StockWarehouse.update({ + // 4. 执行出库扣减:先调用核心函数处理 locked_quantity,再单独扣减 quantity + const lockResult = await this.updateLockedQuantity(storage.id, -outboundQty, currentTransaction, { + skipTransactionLog: true, + remark: '订单出库', + orderType: 'STOCK_STORE_OUTBOUND', + orderNo: outboundMeta.orderNo, + orderId: outboundMeta.orderId, + }); + + if (!lockResult.success) { + if (hasExternalTransaction) { + throw new Error(lockResult.error); + } + return lockResult; + } + + // 同步扣减 quantity + const qtyResult = await ctx.model.StockWarehouse.update({ quantity: app.Sequelize.literal(`quantity - ${outboundQty}`), - locked_quantity: app.Sequelize.literal(`locked_quantity - ${outboundQty}`), update_at: app.Sequelize.literal('CURRENT_TIMESTAMP'), }, { - where: { - id: storage.id, - is_valid: 'Y', - deleted_at: null, - locked_quantity: { - [app.Sequelize.Op.gte]: outboundQty, - }, - }, + where: { id: storage.id, is_valid: 'Y', deleted_at: null }, transaction: currentTransaction, }); - if (result[0] === 0) { - const failureResult = { - success: false, - error: '出库失败:库存已被其他操作修改', - data: null, - }; - if (hasExternalTransaction) { - throw new Error(failureResult.error); - } + if (qtyResult[0] === 0) { + const failureResult = { success: false, error: '出库失败:库存已被其他操作修改', data: null }; + if (hasExternalTransaction) throw new Error(failureResult.error); return failureResult; } diff --git a/app/service/systems/storage/entry.js b/app/service/systems/storage/entry.js index ea0ca8f..1aaac08 100644 --- a/app/service/systems/storage/entry.js +++ b/app/service/systems/storage/entry.js @@ -93,8 +93,8 @@ class EntryService extends Service { * @return {Object|null} Sequelize.where 条件,无法构建时返回 null */ buildEntryStockTransactionExistsCondition(fieldName, condition = {}) { - const { app, ctx } = this; - const db = ctx.model.sequelize; + const { app } = this; + const db = app.model; const values = this.normalizeFilterValues(condition) .map(item => (typeof item === 'string' ? item.trim() : item)) .filter(item => item !== '' && item !== undefined && item !== null); @@ -358,12 +358,23 @@ class EntryService extends Service { if (quickWhereValue !== undefined && quickWhereValue !== null && String(quickWhereValue).trim() !== '') { const kw = String(quickWhereValue).trim(); const receivingDetailId = Number(kw); + const escapedKw = app.model.escape(`%${kw}%`); const orConditions = [ { entry_order_code: { [Op.like]: `%${kw}%` } }, { purchase_order_code: { [Op.like]: `%${kw}%` } }, { supplier_name: { [Op.like]: `%${kw}%` } }, { store_name: { [Op.like]: `%${kw}%` } }, { warehouse_name: { [Op.like]: `%${kw}%` } }, + // 搜索收货单号(wms_receiving.receiving_number),通过绑定表关联 + Sequelize.where(Sequelize.literal( + `EXISTS ( + SELECT 1 FROM wms_entry_order_receiving eor + JOIN wms_receiving r ON r.id = eor.receiving_id + WHERE eor.entry_order_id = wms_entry_order.id + AND eor.deleted_at IS NULL + AND r.receiving_number LIKE ${escapedKw} + )` + ), 1), // 搜索收货单明细 ID(箱唛/托盘唛唯一编码,精确数字匹配);仅当 kw 是有效正数时追加 EXISTS ...(Number.isFinite(receivingDetailId) && receivingDetailId > 0 ? [ Sequelize.where(Sequelize.literal( @@ -501,51 +512,37 @@ class EntryService extends Service { * @return {Promise} code/data/message 结构 */ /** - * 查询入库单详情,含商品信息、条码、入库进度。 + * 查询入库单详情(与原 storage.directInbound.getItems 输出格式一致)。 + * 返回入库单基本信息、商品明细(含计划数量与已完成数量)、收货单绑定关系。 * @param {Object} data 请求参数 * @param {number} data.id 入库单主键 ID(必填) - * @return {Promise} code/data/message 结构,data.entryOrder 为扁平化后的入库单详情 + * @return {Promise} code/data/message 结构 + * - data.entryOrder: { id, entry_order_code, order_status, store_remask } + * - data.items: [{ id, stock_id, planned, completed, stock, bindings }] + * - data.receivingBindings: [{ id, receiving_id, receiving }] */ async get(data = {}) { - const { ctx } = this; + const { ctx, app } = this; const id = Number(data.id || 0); - const warehouseId = ctx.user.store_id; if (!id) { - return { - code: 400, - message: 'id 参数不能为空', - data: null, - }; + return { code: 400, message: 'id 参数不能为空', data: null }; } - const where = { - id, - warehouse_id: warehouseId, - is_enabled: 1, - deleted_at: null, - }; - - const entryOrder = await ctx.model.EntryOrder.findOne({ - where, + const entryOrder = await ctx.model.EntryOrder.findByPk(id, { include: [ - { - model: ctx.model.Store, - as: 'warehouse', - attributes: [ 'id', 'company_name' ], - required: false, - }, - { - model: ctx.model.Store, - as: 'store', - attributes: [ 'id', 'company_name' ], - required: false, - }, { model: ctx.model.EntryItems, as: 'items', - attributes: [ 'id', 'order_id', 'out_biz_code', 'order_line_no', 'owner_code', 'item_code', 'item_id', 'count', 'inventory_type', 'stock_id', 'received_quantity', 'confirm_quantity' ], required: false, + include: [ + { + model: ctx.model.StockWarehouse, + as: 'stock', + attributes: [ 'id', 'item_code', 'item_name', 'sku_property' ], + required: false, + }, + ], }, { model: ctx.model.EntryOrderReceiving, @@ -564,99 +561,202 @@ class EntryService extends Service { }); if (!entryOrder) { - return { - code: 0, - message: '入库单不存在或无权访问', - data: null, - }; + return { code: 404, message: '入库单不存在', data: null }; } - const entryOrderJSON = entryOrder.toJSON(); - - // 收集所有 stock_id,通过 getStockDetails 获取带缓存的商品详情 - const stockIdSet = new Set(); - if (entryOrderJSON.items && Array.isArray(entryOrderJSON.items)) { - for (const item of entryOrderJSON.items) { - if (item.stock_id != null) { - stockIdSet.add(Number(item.stock_id)); - } - } + // 校验仓库权限 + if (entryOrder.warehouse_id !== ctx.user.store_id || !entryOrder.is_enabled) { + return { code: 404, message: '入库单不存在或无权访问', data: null }; } - const stockIds = [ ...stockIdSet ]; + + // 查询货主商家备注 + const storeWarehouse = await ctx.model.StoreWarehouse.findOne({ + where: { store_id: entryOrder.store_id, warehouse_id: entryOrder.warehouse_id }, + attributes: [ 'store_remask' ], + raw: true, + }); + + // 查询该入库单下已有的导入/PDA 入库记录(显式过滤软删除,仅统计未删除记录) + const directLogs = await ctx.model.InboundDirectLog.findAll({ + where: { entry_order_id: entryOrder.id, deleted_at: null }, + order: [[ 'created_at', 'ASC' ]], + }); + + // 将直接入库记录按 entry_item_id 关联到明细 + // 优先使用 entry_item_id 精确匹配(绑定模式),其次回退到 stock_id 匹配(非绑定模式) + const itemDirectLogs = {}; + for (const log of directLogs) { + // 绑定模式下 entry_item_id 已设置,优先用它定位明细行 + const itemByEntryItemId = log.entry_item_id + ? entryOrder.items.find(i => String(i.id) === String(log.entry_item_id)) + : null; + const item = itemByEntryItemId || entryOrder.items.find( + i => String(i.stock_id) === String(log.stock_id) + ); + const key = item ? String(item.id) : `stock_${log.stock_id}`; + if (!itemDirectLogs[key]) itemDirectLogs[key] = []; + itemDirectLogs[key].push({ + id: log.id, + stock_id: log.stock_id, + quantity: log.quantity, + inbound_type: log.inbound_type, + space_id: log.space_id, + remark: log.remark, + operator_id: log.operator_id, + operator_name: log.operator_name, + created_at: log.created_at, + }); + } + + // 将入库单层级的收货单绑定扁平化 + const receivingBindings = (entryOrder.receivingBindings && entryOrder.receivingBindings.length > 0) + ? entryOrder.receivingBindings.map(rb => ({ + id: rb.id, + receiving_id: rb.receiving_id, + receiving: rb.receiving || null, + })) + : []; + + // 收集所有 stock_id,通过 getStockDetails 批量获取带缓存的商品详情 + const stockIds = [ ...new Set( + (entryOrder.items || []) + .map(item => Number(item.stock_id)) + .filter(sid => sid && sid > 0) + ) ]; /** @type {Map} */ - const stockDetailMap = new Map(); + const stockMap = new Map(); if (stockIds.length > 0) { + const warehouseId = ctx.user.store_id; const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(stockIds, { warehouseId }); for (const detail of stockDetails) { - stockDetailMap.set(detail.id, detail); + stockMap.set(detail.id, detail); } } - // 查询该入库单所有商品的直接入库进度(非收货单途径) - const directInboundMap = {}; - if (stockIds.length > 0) { - const directLogRows = await ctx.model.InboundDirectLog.findAll({ - attributes: [ - 'stock_id', - [ ctx.app.Sequelize.fn('SUM', ctx.app.Sequelize.col('quantity')), 'total_quantity' ], - ], + // 组装明细(精简字段,突出已入/总数) + const items = (entryOrder.items || []).map(item => { + const planQty = Number(item.count) || 0; + const logKey = String(item.id); + const logs = itemDirectLogs[logKey] || []; + const directInQty = logs.reduce((sum, l) => sum + Number(l.quantity), 0); + // 优先使用已持久化的 received_quantity(commit 后由系统写入), + // 若为 0 则回退到 InboundDirectLog 汇总(尚未提交时的导入量), + // 确保绑定收货明细场景下 completed 口径与 received_quantity 一致。 + const receivedQty = Number(item.received_quantity) || 0; + const completed = receivedQty > 0 ? receivedQty : directInQty; + + return { + id: item.id, + stock_id: item.stock_id, + planned: planQty, + completed, + stock: stockMap.get(Number(item.stock_id)) || null, + }; + }); + + // 收集所有 InboundDirectLog 中的 space_id,批量查询库位名称 + /** @type {Map} space_id -> space_name */ + const spaceNameMap = new Map(); + const allSpaceIds = [ ...new Set( + Object.values(itemDirectLogs) + .flat() + .map(log => log.space_id) + .filter(sid => sid != null) + ) ]; + if (allSpaceIds.length > 0) { + const spaces = await ctx.model.LocationSpace.findAll({ + where: { id: { [app.Sequelize.Op.in]: allSpaceIds } }, + attributes: [ 'id', 'custom_name', 'space_code' ], + raw: true, + }); + for (const sp of spaces) { + spaceNameMap.set(sp.id, sp.custom_name || sp.space_code || ''); + } + } + + // 批量查询已绑定的收货明细列表 + const entryItemIds = items.map(i => i.id).filter(Boolean); + /** @type {Map>} 按 entry_item_id 分组 */ + const bindingsMap = new Map(); + if (entryItemIds.length > 0) { + const bindingRows = await ctx.model.InboundDirectLog.findAll({ where: { - entry_order_code: entryOrderJSON.entry_order_code, - stock_id: { [ctx.app.Sequelize.Op.in]: stockIds }, + entry_item_id: { [app.Sequelize.Op.in]: entryItemIds }, + receiving_detail_id: { [app.Sequelize.Op.ne]: null }, + deleted_at: null, }, - group: [ 'stock_id' ], + attributes: [ 'id', 'entry_item_id', 'receiving_detail_id', 'quantity', 'status' ], raw: true, }); - for (const row of directLogRows) { - directInboundMap[row.stock_id] = Number(row.total_quantity) || 0; + if (bindingRows.length > 0) { + const detailIds = [ ...new Set(bindingRows.map(b => b.receiving_detail_id).filter(Boolean)) ]; + const validDetailIds = new Set(); + if (detailIds.length > 0) { + const details = await ctx.model.ReceivingDetail.findAll({ + where: { id: { [app.Sequelize.Op.in]: detailIds } }, + attributes: [ 'id' ], + raw: true, + }); + for (const d of details) { + validDetailIds.add(d.id); + } + } + + for (const b of bindingRows) { + const key = b.entry_item_id; + if (!bindingsMap.has(key)) { + bindingsMap.set(key, []); + } + bindingsMap.get(key).push({ + detail_id: b.receiving_detail_id, + binding_id: b.id, + allocated_quantity: b.quantity || 0, + }); + } } } - // 扁平化 items:用 getStockDetails 返回的商品详情替换原有的 stock + barcodes - let flattenedItems; - if (entryOrderJSON.items && Array.isArray(entryOrderJSON.items)) { - flattenedItems = entryOrderJSON.items.map(item => { - const { item_code, item_id, stock_id: itemStockId, ...rest } = item; - const stockDetail = itemStockId != null ? stockDetailMap.get(Number(itemStockId)) || null : null; - const directInboundQty = (stockDetail && directInboundMap[stockDetail.id]) || 0; - const receivedQty = Number(rest.received_quantity) || 0; - const totalCount = Number(rest.count) || 0; - const remaining = Math.max(0, totalCount - receivedQty); + // 将 bindings 挂到对应 item,并补充库位信息 + for (const item of items) { + const bindings = bindingsMap.get(item.id) || []; + const logKey = String(item.id); + const directLogsForItem = itemDirectLogs[logKey] || []; - return { - ...rest, - stock_id: itemStockId, - external_item_code: item_code, - external_item_id: item_id, - warehouse_item_code: (stockDetail && stockDetail.item_code) || '', - warehouse_item_name: (stockDetail && stockDetail.item_name) || '', - warehouse_item_spec: (stockDetail && stockDetail.sku_property) || '', - warehouse_quantity: (stockDetail && stockDetail.quantity != null) ? stockDetail.quantity : null, - warehouse_locked_quantity: (stockDetail && stockDetail.locked_quantity != null) ? stockDetail.locked_quantity : null, - warehouse_is_batch_mgmt: (stockDetail && stockDetail.is_batch_mgmt != null) ? stockDetail.is_batch_mgmt : null, - warehouse_is_shelf_life_mgmt: (stockDetail && stockDetail.is_shelf_life_mgmt != null) ? stockDetail.is_shelf_life_mgmt : null, - warehouse_image_url: (stockDetail && stockDetail.is_images === 'Y') ? '' : '', - warehouse_is_images: (stockDetail && stockDetail.is_images != null) ? stockDetail.is_images : null, - barcodes: (stockDetail && stockDetail.barcodes) || [], - direct_inbound_quantity: directInboundQty, - remaining_quantity: remaining, - }; - }); - } else { - flattenedItems = entryOrderJSON.items || []; + if (bindings.length === 0 && directLogsForItem.length > 0) { + const firstWithSpace = directLogsForItem.find(l => l.space_id); + if (firstWithSpace) { + item.bindings = [{ + space_id: firstWithSpace.space_id, + space_name: spaceNameMap.get(Number(firstWithSpace.space_id)) || '', + }]; + } else { + item.bindings = []; + } + } else { + const firstWithSpace = directLogsForItem.find(l => l.space_id); + const sid = firstWithSpace ? firstWithSpace.space_id : null; + item.bindings = bindings.map(b => ({ + ...b, + space_id: sid, + space_name: sid != null ? (spaceNameMap.get(Number(sid)) || '') : '', + })); + } } - // 为每个 item 补充可匹配的收货单明细及剩余可用量 - const enrichedItems = await this.enrichItemsWithAvailableReceivingDetails(flattenedItems, warehouseId); - entryOrderJSON.items = enrichedItems; - return { code: 200, message: '查询成功', data: { - entryOrder: entryOrderJSON, + entryOrder: { + id: entryOrder.id, + entry_order_code: entryOrder.entry_order_code, + order_status: entryOrder.order_status, + store_remask: (storeWarehouse && storeWarehouse.store_remask) || '', + }, + items, + receivingBindings, }, }; } diff --git a/app/service/systems/storage/inventory.js b/app/service/systems/storage/inventory.js index e1c7eac..283dec9 100644 --- a/app/service/systems/storage/inventory.js +++ b/app/service/systems/storage/inventory.js @@ -1302,8 +1302,8 @@ class InventoryService extends Service { }; } - // 不按批次:按 stock_id + space_id + inventory_type 合并 - const groupFields = [ 'stock_id', 'space_id', 'inventory_type', 'warehouse_id', 'store_id' ]; + // 不按批次:仅按 stock_id 合并(跨库位、跨库存类型汇总) + const groupFields = [ 'stock_id' ]; const countResult = await ctx.model.Storage.count({ where: baseWhere, @@ -1315,10 +1315,8 @@ class InventoryService extends Service { where: baseWhere, attributes: [ 'stock_id', - 'space_id', - 'inventory_type', - 'warehouse_id', - 'store_id', + [ fn('MIN', col('wms_storage.warehouse_id')), 'warehouse_id' ], + [ fn('MIN', col('wms_storage.store_id')), 'store_id' ], [ fn('MIN', col('wms_storage.production_date')), 'production_date' ], [ fn('MIN', col('wms_storage.expiry_date')), 'expiry_date' ], [ fn('SUM', col('wms_storage.quantity')), 'quantity' ], @@ -1356,12 +1354,6 @@ class InventoryService extends Service { ], required: false, }, - { - model: ctx.model.LocationSpace, - as: 'space', - attributes: [ 'id', 'space_code', 'custom_name' ], - required: false, - }, ], raw: true, nest: true, @@ -1700,18 +1692,18 @@ class InventoryService extends Service { const dateStr = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}`; const prefix = `SCRK${dateStr}`; - // 查询当天该仓库+货主下已有的最大入库单号 + // 查询当天该仓库下已有的最大入库单号(全局唯一,不区分货主,避免多货主场景下重复) const lastOrder = await ctx.model.EntryOrder.findOne({ where: { entry_order_code: { [app.Sequelize.Op.like]: `${prefix}%` }, warehouse_id: warehouseId, - store_id: storeId, }, order: [[ 'entry_order_code', 'DESC' ]], attributes: [ 'entry_order_code' ], transaction, raw: true, paranoid: false, + lock: transaction.LOCK.UPDATE, }); let seq = 1; diff --git a/methods/changes/system.json b/methods/changes/system.json index 3f0fea3..1af3fae 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,22 @@ [ + { + "version": "2026.07.03-system-02", + "date": "2026-07-03", + "type": "added", + "summary": "新增 order.pendingOrder.updateRemark:批量修改待处理订单备注(remark),不受 post_status 限制", + "methods": [ + "order.pendingOrder.updateRemark" + ], + "notes": [ + "新增方法:order.pendingOrder.updateRemark,用于批量修改待处理订单的备注(remark)字段。", + "入参:ids(number[],必填,正整数数组,不能为空)、remark(string,必填,最大500字符)。", + "特性:不受 post_status 限制,可对所有状态的订单生效;纯批量不支持单ID。", + "更新成功后写入操作日志。", + "响应:updated_count(number,实际更新行数)、ids(number[],原样返回请求的ID数组)。", + "错误码:400(ids 不能为空 / ids 仅支持正整数数组 / remark 不能为空)。" + ], + "module": "order.pendingOrder" + }, { "version": "2026.07.03-system-01", "date": "2026-07-03", @@ -4753,5 +4771,23 @@ "response: warehouse_quantity/warehouse_locked_quantity/warehouse_is_batch_mgmt/warehouse_is_shelf_life_mgmt 补充无匹配时为 null 的说明", "description: 更新描述以反映实际逻辑流程" ] + }, + { + "version": "2026.07.03-system-04", + "date": "2026-07-03", + "type": "modified", + "summary": "order.pendingOrder.updateAddress 移除 remark(备注)修改功能,现在仅支持地址字段批量修改;备注修改已独立为 order.pendingOrder.updateRemark", + "methods": [ + "order.pendingOrder.updateAddress" + ], + "notes": [ + "移除入参 remark 参数定义项。", + "移除 remark 更新逻辑及相关描述,updateAddress 现在仅处理地址字段(name/mobile/tel/zip_code/province/city/area/town/detail_address)。", + "description 更新:去掉 remark 相关描述,仅描述地址字段修改规则。", + "response updated_count 描述更新:从「取地址更新行数与备注更新行数的最大值」改为单纯描述地址更新行数。", + "errors 更新:移除 remark 相关错误说明('remark 字段不受此限制' 等),修改 '至少需要提供一个地址字段或备注进行修改' 为 '至少需要提供一个地址字段进行修改'。", + "备注修改功能已独立为 order.pendingOrder.updateRemark 方法。" + ], + "module": "order.pendingOrder" } ] diff --git a/methods/system.json b/methods/system.json index 857bb52..4e6f5ab 100644 --- a/methods/system.json +++ b/methods/system.json @@ -2846,7 +2846,7 @@ ] }, { - "groupName": "订单待处理模块", + "groupName": "待处理订单", "module": "order.pendingOrder", "list": [ { @@ -4165,7 +4165,7 @@ }, { "method": "order.pendingOrder.updateAddress", - "description": "批量修改待处理订单的收件地址信息和备注。地址字段修改仅允许 post_status='none'(未分配快递)的订单;remark 字段修改不受 post_status 限制可对所有订单生效。至少需要提供一个地址字段(name/mobile/tel/zip_code/province/city/area/town/detail_address)或 remark,空值和纯空白会被忽略。更新成功后写入操作日志。", + "description": "批量修改待处理订单的收件地址信息。地址字段修改仅允许 post_status='none'(未分配快递)的订单;至少需要提供一个地址字段(name/mobile/tel/zip_code/province/city/area/town/detail_address),空值和纯空白会被忽略。更新成功后写入操作日志。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -4246,13 +4246,6 @@ "required": false, "source": "body", "description": "详细地址" - }, - { - "name": "remark", - "type": "string", - "required": false, - "source": "body", - "description": "订单留言/备注,最大500字符。非空时批量覆盖所选订单的 remark 字段,不受 post_status 限制。" } ], "response": [ @@ -4260,7 +4253,7 @@ "name": "updated_count", "type": "number", "required": true, - "description": "实际更新的订单行数(取地址更新行数与备注更新行数的最大值)。remark 字段的更新计数独立于地址字段。" + "description": "实际更新的订单行数(地址更新行数)。仅统计 post_status='none' 的订单地址更新成功数。" }, { "name": "ids", @@ -4276,11 +4269,69 @@ }, { "code": 400, - "message": "至少需要提供一个地址字段或备注进行修改" + "message": "至少需要提供一个地址字段进行修改" }, { "code": 400, - "message": "仅允许修改 post_status='none'(未分配快递)的订单(地址字段);若订单已分配快递则地址更新行数为 0,不会报错但实际无更新。remark 字段不受此限制。" + "message": "仅允许修改 post_status='none'(未分配快递)的订单;若订单已分配快递则地址更新行数为 0,不会报错但实际无更新。" + } + ] + }, + { + "method": "order.pendingOrder.updateRemark", + "description": "批量修改待处理订单的备注(remark)。不受 post_status 限制,可对所有状态的订单生效。更新成功后写入操作日志。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids", + "type": "number[]", + "required": true, + "source": "body", + "description": "订单ID 正整数数组,不能为空" + }, + { + "name": "remark", + "type": "string", + "required": true, + "source": "body", + "description": "订单备注/留言,最大500字符,必填" + } + ], + "response": [ + { + "name": "updated_count", + "type": "number", + "required": true, + "description": "实际更新的订单行数" + }, + { + "name": "ids", + "type": "number[]", + "required": true, + "description": "请求的订单ID数组(原样返回)" + } + ], + "errors": [ + { + "code": 400, + "message": "ids 不能为空" + }, + { + "code": 400, + "message": "ids 仅支持正整数数组" + }, + { + "code": 400, + "message": "remark 不能为空" } ] }, @@ -20644,14 +20695,12 @@ "_note": "响应结构因 group_by_batch 而异", "_shelf_life_note": "production_date 和 expiry_date 为库存批次日期字段;is_shelf_life_warning_triggered 表示该库存在商品启用保质期管理且剩余天数小于等于阈值时是否触发效期预警。", "list_merged": { - "_description": "group_by_batch=false(默认合并模式)", + "_description": "group_by_batch=false(默认合并模式),仅按 stock_id 分组聚合,跨库位、跨库存类型汇总", "list": [ { "stock_id": "商品库存ID", - "space_id": "库位ID", - "inventory_type": "库存类型", - "warehouse_id": "仓库ID", - "store_id": "货主ID", + "warehouse_id": "仓库ID(MIN 聚合值)", + "store_id": "货主ID(MIN 聚合值)", "quantity": "总库存数量(SUM)", "locked_quantity": "总锁定数量(SUM)", "available_quantity": "总可用数量(SUM)", @@ -20668,11 +20717,6 @@ "sku_property": "规格", "stock_unit": "单位", "store_name": "货主名称(来源于签约表 store_remask,若无签约关系则为 null)" - }, - "space": { - "id": "库位ID", - "space_code": "库位编码", - "custom_name": "库位名称" } } ], diff --git a/package.json b/package.json index 0f86b25..4216b79 100644 --- a/package.json +++ b/package.json @@ -48,8 +48,6 @@ "debug:webhook:receiving": "node ./script/debug-send-receiving-webhooks.cjs", "doc:api:update": "node ./script/update-api-doc.cjs", "doc:api:update:dry": "node ./script/update-api-doc.cjs --dry-run", - "deploy:init": "node ./script/deploy-init.cjs production", - "deploy:init:dry": "node ./script/deploy-init.cjs production --dry-run", "deploy:precheck": "node ./script/deploy-precheck.cjs", "deploy:authcheck": "node ./script/deploy-auth-check.cjs", "deploy:version": "node ./script/deploy-version.cjs production", diff --git a/script/deploy-init.cjs b/script/deploy-init.cjs deleted file mode 100644 index 1339d84..0000000 --- a/script/deploy-init.cjs +++ /dev/null @@ -1,138 +0,0 @@ -'use strict'; - -const fs = require('node:fs'); -const path = require('node:path'); -const { - ensureCommandAvailable, - ensureTempDeployDir, - getNowStamp, - loadDeployConfig, - quoteForBash, - runCommand, - runScp, - runSsh, -} = require('./deploy-lib.cjs'); - -function parseArgs(argv) { - const options = { - envName: 'production', - dryRun: false, - }; - - for (const item of argv) { - if (!item) continue; - if (item === '--dry-run') { - options.dryRun = true; - continue; - } - if (!item.startsWith('--')) { - options.envName = item; - } - } - - return options; -} - -function listConfigSeedFiles() { - const output = runCommand('git', [ 'ls-files', '--cached', 'config' ]); - return output - .split(/\r?\n/) - .map(item => item.trim()) - .filter(Boolean) - .filter(item => item.startsWith('config/')) - .filter(item => item !== 'config/config.local.js') - .filter(item => item !== 'config/deploy.config.local.cjs') - .filter(item => item !== 'config/deploy.config.example.cjs'); -} - -function buildConfigSeedArchive(stamp, files) { - const tempDir = ensureTempDeployDir(); - const listPath = path.join(tempDir, `deploy-init-files-${stamp}.txt`); - const archivePath = path.join(tempDir, `deploy-init-${stamp}.tar.gz`); - - if (!files || files.length === 0) { - throw new Error('未找到可用于初始化的 config 文件(git tracked)。'); - } - - fs.writeFileSync(listPath, files.join('\n') + '\n', 'utf8'); - runCommand('tar', [ '-czf', archivePath, '-T', listPath ], { stdio: 'inherit' }); - return { - archivePath, - listPath, - }; -} - -function cleanupLocalTemp(paths) { - for (const filePath of paths) { - if (!filePath) continue; - if (fs.existsSync(filePath)) { - fs.unlinkSync(filePath); - } - } -} - -function main() { - const options = parseArgs(process.argv.slice(2)); - - ensureCommandAvailable('git', '请先安装 Git 并确保 git 在 PATH 中。'); - ensureCommandAvailable('tar', '请先安装 tar,Windows 10/11 通常已内置 bsdtar。'); - ensureCommandAvailable('ssh', '请先安装 OpenSSH Client 并确保 ssh 在 PATH 中。'); - ensureCommandAvailable('scp', '请先安装 OpenSSH Client 并确保 scp 在 PATH 中。'); - - const config = loadDeployConfig(options.envName); - const seedFiles = listConfigSeedFiles(); - - if (options.dryRun) { - console.log(JSON.stringify({ - dryRun: true, - envName: options.envName, - deployRoot: config.deployRoot, - seedFileCount: seedFiles.length, - seedFiles, - }, null, 2)); - return; - } - - const stamp = getNowStamp(); - const { archivePath, listPath } = buildConfigSeedArchive(stamp, seedFiles); - const remoteArchive = `${config.incomingDir}/deploy-init-${stamp}.tar.gz`; - - try { - const setupScript = [ - 'set -euo pipefail', - `mkdir -p ${quoteForBash(config.deployRoot)} ${quoteForBash(config.controlDir)} ${quoteForBash(config.incomingDir)} ${quoteForBash(config.backupDir)} ${quoteForBash(config.stateDir)} ${quoteForBash(path.posix.join(config.deployRoot, 'logs'))} ${quoteForBash(path.posix.join(config.deployRoot, 'run'))} ${quoteForBash(path.posix.join(config.deployRoot, 'temp'))} ${quoteForBash(path.posix.join(config.deployRoot, 'v1'))} ${quoteForBash(path.posix.join(config.deployRoot, 'v2'))}`, - `echo v1 > ${quoteForBash(path.posix.join(config.deployRoot, 'current.md'))}`, - `echo "proxy_pass http://127.0.0.1:6061;" > ${quoteForBash(path.posix.join(config.deployRoot, 'nginx-upstream.conf'))}`, - ].join('\n'); - runSsh(config, setupScript); - runScp(config, archivePath, remoteArchive); - - const remoteScript = [ - 'set -euo pipefail', - `DEPLOY_ROOT=${quoteForBash(config.deployRoot)}`, - `REMOTE_ARCHIVE=${quoteForBash(remoteArchive)}`, - 'CONFIG_DIR="$DEPLOY_ROOT/config"', - 'if [ -d "$CONFIG_DIR" ] && [ "$(find "$CONFIG_DIR" -mindepth 1 -maxdepth 1 | wc -l | tr -d \" \" )" -gt 0 ]; then', - ' echo DEPLOY_INIT_CONFIG_SKIPPED_EXISTS', - 'else', - ' mkdir -p "$CONFIG_DIR"', - ' tar -xzf "$REMOTE_ARCHIVE" -C "$DEPLOY_ROOT"', - ' echo DEPLOY_INIT_CONFIG_CREATED', - 'fi', - 'rm -f "$REMOTE_ARCHIVE"', - ].join('\n'); - - const output = runSsh(config, remoteScript, { stdio: 'pipe' }); - for (const line of output.split(/\r?\n/)) { - if (line.trim()) { - console.log(line.trim()); - } - } - } finally { - cleanupLocalTemp([ archivePath, listPath ]); - } - - console.log(`首次发布初始化完成: ${options.envName} -> ${config.deployRoot}`); -} - -main(); From 78540572445e8b9512fb43c2651d8ff60d1f4c09 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sat, 4 Jul 2026 23:30:32 +0800 Subject: [PATCH 085/550] chore: ESLint auto-fix formatting (JSDoc, spacing, quotes, line endings) --- config/config.default.js | 2 +- ...ique-platform-code-from-express-setting.js | 12 +-- ...00-drop-uk-warehouse-platform-shop-name.js | 8 +- ...60608033847-set-role-preset-permissions.js | 2 +- ...20260611190000-merge-created-to-pending.js | 2 + ...eate-wms-package-material-item-relation.js | 6 +- ...0615160000-alter-uk-interface-warehouse.js | 10 ++- ...0-add-created-status-to-wms-entry-order.js | 2 + ...30000-remove-confirmed-partial-received.js | 2 + ...0623140000-create-entry-order-receiving.js | 8 +- .../20260629-add-waiting-storage-status.js | 10 +-- script/api-test.js | 12 +-- script/api-test2.js | 12 +-- script/backfill-wave-status.js | 4 +- script/clear-cache.js | 8 +- script/cutoff-integration-test-v2.js | 25 +++---- script/cutoff-integration-test-v3.js | 27 ++++--- script/cutoff-integration-test.js | 17 +++-- script/integration-test.js | 10 +-- script/update-policy.js | 8 +- scripts/check_tables.js | 12 +-- scripts/integration_test_stock_warehouse.js | 16 ++-- scripts/query_more_test_orders.js | 10 +-- scripts/query_test_orders.js | 20 ++--- scripts/query_test_orders_v2.js | 10 +-- scripts/test_batch_quick_recheck.js | 30 ++++---- scripts/test_batch_quick_recheck_full.js | 73 ++++++++++--------- scripts/test_batch_quick_recheck_v2.js | 30 ++++---- .../order_delivery_dispatch_factory.test.js | 2 +- ...wave.waveStrategyFallbackOrderList.test.js | 6 +- .../stock.warehouse.import.test.js | 2 +- 31 files changed, 204 insertions(+), 194 deletions(-) diff --git a/config/config.default.js b/config/config.default.js index c012498..0e4a199 100644 --- a/config/config.default.js +++ b/config/config.default.js @@ -130,7 +130,7 @@ module.exports = appInfo => { 'audio/x-m4a': 'audio', }; config.cors = { - origin: (ctx) => ctx.get('Origin'), // 动态返回请求源,配合 credentials: true 使用 + origin: ctx => ctx.get('Origin'), // 动态返回请求源,配合 credentials: true 使用 allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS', exposeHeaders: 'Authorization', credentials: true, // 允许携带 cookie diff --git a/database/migrations/20260606-remove-unique-platform-code-from-express-setting.js b/database/migrations/20260606-remove-unique-platform-code-from-express-setting.js index 8bfea14..c78b0ae 100644 --- a/database/migrations/20260606-remove-unique-platform-code-from-express-setting.js +++ b/database/migrations/20260606-remove-unique-platform-code-from-express-setting.js @@ -10,10 +10,10 @@ const FK_NAME = 'wms_express_setting_ibfk_1'; * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 * @param {string} tableName 表名。 * @param {string} indexName 索引名。 - * @returns {Promise} 索引是否存在。 + * @return {Promise} 索引是否存在。 */ const hasIndex = async (queryInterface, tableName, indexName) => { - const [rows] = await queryInterface.sequelize.query( + const [ rows ] = await queryInterface.sequelize.query( `SHOW INDEX FROM \`${tableName}\` WHERE Key_name = :indexName`, { replacements: { indexName } } ); @@ -25,10 +25,10 @@ const hasIndex = async (queryInterface, tableName, indexName) => { * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 * @param {string} tableName 表名。 * @param {string} constraintName 约束名。 - * @returns {Promise} 外键是否存在。 + * @return {Promise} 外键是否存在。 */ const hasForeignKey = async (queryInterface, tableName, constraintName) => { - const [rows] = await queryInterface.sequelize.query( + const [ rows ] = await queryInterface.sequelize.query( `SELECT CONSTRAINT_NAME FROM information_schema.TABLE_CONSTRAINTS WHERE CONSTRAINT_SCHEMA = DATABASE() @@ -47,7 +47,7 @@ module.exports = { * 原 UNIQUE KEY `platform_code` ON (`express_code`, `warehouse_id`) 约束过紧, * 且该索引被外键 `wms_express_setting_ibfk_1`(express_code → wms_express.code)依赖。 * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 - * @returns {Promise} 无返回值。 + * @return {Promise} 无返回值。 */ async up(queryInterface) { // 1. 先删除依赖该索引的外键约束 @@ -75,7 +75,7 @@ module.exports = { /** * 回滚迁移:恢复唯一索引与外键约束。 * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 - * @returns {Promise} 无返回值。 + * @return {Promise} 无返回值。 */ async down(queryInterface) { // 1. 删除替代的普通索引 diff --git a/database/migrations/20260607120000-drop-uk-warehouse-platform-shop-name.js b/database/migrations/20260607120000-drop-uk-warehouse-platform-shop-name.js index 742a928..f05f548 100644 --- a/database/migrations/20260607120000-drop-uk-warehouse-platform-shop-name.js +++ b/database/migrations/20260607120000-drop-uk-warehouse-platform-shop-name.js @@ -9,10 +9,10 @@ const PLAIN_INDEX_NAME = 'idx_warehouse_platform_shop_name'; * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 * @param {string} tableName 表名。 * @param {string} indexName 索引名。 - * @returns {Promise} 索引是否存在。 + * @return {Promise} 索引是否存在。 */ const hasIndex = async (queryInterface, tableName, indexName) => { - const [rows] = await queryInterface.sequelize.query( + const [ rows ] = await queryInterface.sequelize.query( `SHOW INDEX FROM \`${tableName}\` WHERE Key_name = :indexName`, { replacements: { indexName } } ); @@ -26,7 +26,7 @@ module.exports = { * 触发 UNIQUE KEY `uk_warehouse_platform_shop_name` 约束冲突,导致 MySQL UPDATE 失败。 * 故将此唯一约束降为普通索引,仅保留查询性能。 * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 - * @returns {Promise} 无返回值。 + * @return {Promise} 无返回值。 */ async up(queryInterface) { // 1. 删除唯一索引 @@ -47,7 +47,7 @@ module.exports = { /** * 回滚迁移:恢复唯一约束。 * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 - * @returns {Promise} 无返回值。 + * @return {Promise} 无返回值。 */ async down(queryInterface) { // 1. 删除普通索引 diff --git a/database/migrations/20260608033847-set-role-preset-permissions.js b/database/migrations/20260608033847-set-role-preset-permissions.js index b2fe7ce..9266da7 100644 --- a/database/migrations/20260608033847-set-role-preset-permissions.js +++ b/database/migrations/20260608033847-set-role-preset-permissions.js @@ -117,7 +117,7 @@ const ROLE_UPDATES = [ // 其他普工:排除设置模块(4-9,40,41,80,81,336,366,375)、财务、数据、测试、系统、敏感API、仓库管理API、视频 permissions: '[1,11,12,13,14,15,17,18,19,20,21,22,24,25,26,27,29,30,38,39,43,44,45,46,48,49,50,54,55,57,58,61,62,63,64,65,66,67,68,69,70,71,72,74,75,76,77,78,79,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,108,244,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279,281,283,290,291,292,293,294,295,296,297,298,299,300,303,304,305,306,307,309,333,334,335,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,357,358,361,364,365,370,373,374,376,377,379,380,381,382,383,384]', old: '[4-121]', - } + }, ]; /** diff --git a/database/migrations/20260611190000-merge-created-to-pending.js b/database/migrations/20260611190000-merge-created-to-pending.js index c456466..418992d 100644 --- a/database/migrations/20260611190000-merge-created-to-pending.js +++ b/database/migrations/20260611190000-merge-created-to-pending.js @@ -5,6 +5,7 @@ module.exports = { * 将 CREATED 状态合并到 PENDING: * 1. 先把现有 CREATED 行更新为 PENDING * 2. 再 ALTER TABLE 去掉 CREATED 枚举值 + * @param queryInterface */ up: async queryInterface => { // 先更新现有 CREATED 行 @@ -19,6 +20,7 @@ module.exports = { /** * 回滚:将 CREATED 加回 ENUM(数据不回退,因为无法区分哪些行原本是 CREATED) + * @param queryInterface */ down: async queryInterface => { await queryInterface.sequelize.query( diff --git a/database/migrations/20260615143000-create-wms-package-material-item-relation.js b/database/migrations/20260615143000-create-wms-package-material-item-relation.js index 219e09a..3ea2cbd 100644 --- a/database/migrations/20260615143000-create-wms-package-material-item-relation.js +++ b/database/migrations/20260615143000-create-wms-package-material-item-relation.js @@ -134,17 +134,17 @@ module.exports = { }, }); - await queryInterface.addIndex(TABLE_NAME, ['warehouse_id', 'items_hash', 'items_crc', 'package_material_id'], { + await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'items_hash', 'items_crc', 'package_material_id' ], { unique: true, name: 'uk_item_material', }); - await queryInterface.addIndex(TABLE_NAME, ['warehouse_id', 'is_active', 'items_hash', 'bind_count'], { + await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'is_active', 'items_hash', 'bind_count' ], { name: 'idx_lookup', }); }, - down: async (queryInterface) => { + down: async queryInterface => { await queryInterface.dropTable(TABLE_NAME); }, }; diff --git a/database/migrations/20260615160000-alter-uk-interface-warehouse.js b/database/migrations/20260615160000-alter-uk-interface-warehouse.js index 45c35ac..29b00e8 100644 --- a/database/migrations/20260615160000-alter-uk-interface-warehouse.js +++ b/database/migrations/20260615160000-alter-uk-interface-warehouse.js @@ -4,29 +4,31 @@ module.exports = { /** * 修改 wms_api_app 表的唯一键 uk_interface_warehouse: * 从 (qimen_app_key, qimen_customer_id) 改为 (qimen_app_key, qimen_warehouse_code) + * @param queryInterface */ up: async queryInterface => { // 1. 删除旧唯一键 await queryInterface.sequelize.query( - "ALTER TABLE wms_api_app DROP INDEX uk_interface_warehouse" + 'ALTER TABLE wms_api_app DROP INDEX uk_interface_warehouse' ); // 2. 创建新唯一键 await queryInterface.sequelize.query( - "ALTER TABLE wms_api_app ADD UNIQUE INDEX uk_interface_warehouse (qimen_app_key, qimen_warehouse_code)" + 'ALTER TABLE wms_api_app ADD UNIQUE INDEX uk_interface_warehouse (qimen_app_key, qimen_warehouse_code)' ); }, /** * 回滚:恢复为 (qimen_app_key, qimen_customer_id) + * @param queryInterface */ down: async queryInterface => { // 1. 删除新唯一键 await queryInterface.sequelize.query( - "ALTER TABLE wms_api_app DROP INDEX uk_interface_warehouse" + 'ALTER TABLE wms_api_app DROP INDEX uk_interface_warehouse' ); // 2. 恢复旧唯一键 await queryInterface.sequelize.query( - "ALTER TABLE wms_api_app ADD UNIQUE INDEX uk_interface_warehouse (qimen_app_key, qimen_customer_id)" + 'ALTER TABLE wms_api_app ADD UNIQUE INDEX uk_interface_warehouse (qimen_app_key, qimen_customer_id)' ); }, }; diff --git a/database/migrations/20260623120000-add-created-status-to-wms-entry-order.js b/database/migrations/20260623120000-add-created-status-to-wms-entry-order.js index a1a2934..35f106a 100644 --- a/database/migrations/20260623120000-add-created-status-to-wms-entry-order.js +++ b/database/migrations/20260623120000-add-created-status-to-wms-entry-order.js @@ -5,6 +5,7 @@ module.exports = { * 为 wms_entry_order 增加 CREATED 状态: * ENUM 顺序: CREATING → CREATED → PENDING → CONFIRMED → PARTIAL_RECEIVED → COMPLETED → CANCELLED * 默认值改为 CREATED + * @param queryInterface */ up: async queryInterface => { await queryInterface.sequelize.query( @@ -16,6 +17,7 @@ module.exports = { * 回滚: * 1. 先将 CREATED 行更新为 PENDING * 2. 再移除 CREATED 枚举值,恢复默认值 PENDING + * @param queryInterface */ down: async queryInterface => { await queryInterface.sequelize.query( diff --git a/database/migrations/20260623130000-remove-confirmed-partial-received.js b/database/migrations/20260623130000-remove-confirmed-partial-received.js index 6fdeae1..3aaf117 100644 --- a/database/migrations/20260623130000-remove-confirmed-partial-received.js +++ b/database/migrations/20260623130000-remove-confirmed-partial-received.js @@ -8,6 +8,7 @@ module.exports = { * 前置条件: * - CONFIRMED 行数为 0,无需迁移 * - PARTIAL_RECEIVED 的 11 行改为 PENDING + * @param queryInterface */ up: async queryInterface => { // 将 PARTIAL_RECEIVED 和 CONFIRMED 记录统一刷成 PENDING @@ -22,6 +23,7 @@ module.exports = { /** * 回滚:恢复 CONFIRMED 和 PARTIAL_RECEIVED 到 ENUM 中(不回滚数据) + * @param queryInterface */ down: async queryInterface => { await queryInterface.sequelize.query( diff --git a/database/migrations/20260623140000-create-entry-order-receiving.js b/database/migrations/20260623140000-create-entry-order-receiving.js index fa15c91..d020aa8 100644 --- a/database/migrations/20260623140000-create-entry-order-receiving.js +++ b/database/migrations/20260623140000-create-entry-order-receiving.js @@ -46,21 +46,21 @@ module.exports = { }, }); - await queryInterface.addIndex(TABLE_NAME, ['entry_order_id'], { + await queryInterface.addIndex(TABLE_NAME, [ 'entry_order_id' ], { name: 'idx_entry_order_id', }); - await queryInterface.addIndex(TABLE_NAME, ['receiving_id'], { + await queryInterface.addIndex(TABLE_NAME, [ 'receiving_id' ], { name: 'idx_receiving_id', }); - await queryInterface.addIndex(TABLE_NAME, ['entry_order_id', 'receiving_id'], { + await queryInterface.addIndex(TABLE_NAME, [ 'entry_order_id', 'receiving_id' ], { unique: true, name: 'uk_entry_order_receiving', }); }, - down: async (queryInterface) => { + down: async queryInterface => { await queryInterface.dropTable(TABLE_NAME); }, }; diff --git a/database/migrations/20260629-add-waiting-storage-status.js b/database/migrations/20260629-add-waiting-storage-status.js index 32f8792..7bd14e3 100644 --- a/database/migrations/20260629-add-waiting-storage-status.js +++ b/database/migrations/20260629-add-waiting-storage-status.js @@ -9,7 +9,7 @@ */ const logMigrationDbContext = async (queryInterface, phase, table) => { try { - const [rows] = await queryInterface.sequelize.query( + const [ rows ] = await queryInterface.sequelize.query( 'SELECT DATABASE() AS db_name, @@hostname AS db_host, @@port AS db_port, CURRENT_USER() AS db_user' ); const dbContext = Array.isArray(rows) && rows.length > 0 ? rows[0] : {}; @@ -35,11 +35,11 @@ const logMigrationDbContext = async (queryInterface, phase, table) => { * ALTER TABLE wms_receiving_detail MODIFY COLUMN storage_status ENUM('none','partial','all') NOT NULL DEFAULT 'none' COMMENT '入库状态:none-未入库, partial-部分入库, all-全部入库'; */ -const UP_SQL_RECEIVING = `ALTER TABLE wms_receiving MODIFY COLUMN storage_status ENUM('none','waiting','partial','all') NOT NULL DEFAULT 'none' COMMENT '入库状态:none-未入库, waiting-等待入库, partial-部分入库, all-全部入库'`; -const DOWN_SQL_RECEIVING = `ALTER TABLE wms_receiving MODIFY COLUMN storage_status ENUM('none','partial','all') NOT NULL DEFAULT 'none' COMMENT '入库状态:none-未入库, partial-部分入库, all-全部入库'`; +const UP_SQL_RECEIVING = 'ALTER TABLE wms_receiving MODIFY COLUMN storage_status ENUM(\'none\',\'waiting\',\'partial\',\'all\') NOT NULL DEFAULT \'none\' COMMENT \'入库状态:none-未入库, waiting-等待入库, partial-部分入库, all-全部入库\''; +const DOWN_SQL_RECEIVING = 'ALTER TABLE wms_receiving MODIFY COLUMN storage_status ENUM(\'none\',\'partial\',\'all\') NOT NULL DEFAULT \'none\' COMMENT \'入库状态:none-未入库, partial-部分入库, all-全部入库\''; -const UP_SQL_DETAIL = `ALTER TABLE wms_receiving_detail MODIFY COLUMN storage_status ENUM('none','waiting','partial','all') NOT NULL DEFAULT 'none' COMMENT '入库状态:none-未入库, waiting-等待入库, partial-部分入库, all-全部入库'`; -const DOWN_SQL_DETAIL = `ALTER TABLE wms_receiving_detail MODIFY COLUMN storage_status ENUM('none','partial','all') NOT NULL DEFAULT 'none' COMMENT '入库状态:none-未入库, partial-部分入库, all-全部入库'`; +const UP_SQL_DETAIL = 'ALTER TABLE wms_receiving_detail MODIFY COLUMN storage_status ENUM(\'none\',\'waiting\',\'partial\',\'all\') NOT NULL DEFAULT \'none\' COMMENT \'入库状态:none-未入库, waiting-等待入库, partial-部分入库, all-全部入库\''; +const DOWN_SQL_DETAIL = 'ALTER TABLE wms_receiving_detail MODIFY COLUMN storage_status ENUM(\'none\',\'partial\',\'all\') NOT NULL DEFAULT \'none\' COMMENT \'入库状态:none-未入库, partial-部分入库, all-全部入库\''; module.exports = { /** diff --git a/script/api-test.js b/script/api-test.js index 6f550d9..b745927 100644 --- a/script/api-test.js +++ b/script/api-test.js @@ -6,17 +6,17 @@ const reqBody = process.argv[4] || '{}'; const options = { hostname: 'localhost', port: 6060, - path: `/system?method=${method}&v=1×tamp=${Math.floor(Date.now()/1000)}`, + path: `/system?method=${method}&v=1×tamp=${Math.floor(Date.now() / 1000)}`, method: 'POST', headers: { - 'platform': 'web', - 'project': 'wms', - 'Authorization': `Bearer ${token}`, + platform: 'web', + project: 'wms', + Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', }, }; -const req = http.request(options, (res) => { +const req = http.request(options, res => { let data = ''; res.on('data', chunk => data += chunk); res.on('end', () => { @@ -29,6 +29,6 @@ const req = http.request(options, (res) => { } }); }); -req.on('error', (e) => console.error('ERROR:', e.message)); +req.on('error', e => console.error('ERROR:', e.message)); req.write(reqBody); req.end(); diff --git a/script/api-test2.js b/script/api-test2.js index b8d0a92..a2510d1 100644 --- a/script/api-test2.js +++ b/script/api-test2.js @@ -14,17 +14,17 @@ if (reqBodyFile && reqBodyFile.endsWith('.json')) { const options = { hostname: 'localhost', port: 6060, - path: `/system?method=${method}&v=1×tamp=${Math.floor(Date.now()/1000)}`, + path: `/system?method=${method}&v=1×tamp=${Math.floor(Date.now() / 1000)}`, method: 'POST', headers: { - 'platform': 'web', - 'project': 'wms', - 'Authorization': `Bearer ${token}`, + platform: 'web', + project: 'wms', + Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', }, }; -const req = http.request(options, (res) => { +const req = http.request(options, res => { let data = ''; res.on('data', chunk => data += chunk); res.on('end', () => { @@ -42,6 +42,6 @@ const req = http.request(options, (res) => { } }); }); -req.on('error', (e) => console.error('REQUEST ERROR:', e.message)); +req.on('error', e => console.error('REQUEST ERROR:', e.message)); req.write(reqBody); req.end(); diff --git a/script/backfill-wave-status.js b/script/backfill-wave-status.js index c88630b..f6f3dd4 100644 --- a/script/backfill-wave-status.js +++ b/script/backfill-wave-status.js @@ -30,7 +30,7 @@ async function main() { try { // 先查影响行数 - const [previewRows] = await sequelize.query(` + const [ previewRows ] = await sequelize.query(` SELECT COUNT(1) AS count FROM wms_wave_pick_task_wave w INNER JOIN wms_wave_pick_task t ON t.id = w.task_id AND t.warehouse_id = w.warehouse_id @@ -47,7 +47,7 @@ async function main() { } // 执行更新 - const [result] = await sequelize.query(` + const [ result ] = await sequelize.query(` UPDATE wms_wave_pick_task_wave w INNER JOIN wms_wave_pick_task t ON t.id = w.task_id AND t.warehouse_id = w.warehouse_id SET w.status = 1, diff --git a/script/clear-cache.js b/script/clear-cache.js index 9c40e32..f680ddd 100644 --- a/script/clear-cache.js +++ b/script/clear-cache.js @@ -9,21 +9,21 @@ async function main() { }); const key = 'store_warehouse:contract_config:1000028:1000241'; - + try { const val = await redis.get(key); console.log('Current cache value:', val ? val.substring(0, 200) : 'NULL'); - + await redis.del(key); console.log('✅ Cache key deleted:', key); - + // Verify const after = await redis.get(key); console.log('After delete:', after); } catch (e) { console.error('Error:', e.message); } - + redis.disconnect(); } diff --git a/script/cutoff-integration-test-v2.js b/script/cutoff-integration-test-v2.js index 68ceaf4..c3e5691 100644 --- a/script/cutoff-integration-test-v2.js +++ b/script/cutoff-integration-test-v2.js @@ -1,6 +1,6 @@ /** * 截单时间逻辑真实 API 集成测试 (v2) - * + * * 测试目标: 验证 asyncProcessOrderCreated 中的截单时间兜底逻辑 * 策略: 通过 SQL 直接更新 policy_config (绕过 API 权限问题),通过 API 创建订单并验证结果 */ @@ -32,17 +32,16 @@ function api(method, body) { const bodyStr = typeof body === 'string' ? body : JSON.stringify(body); const opts = { hostname: 'localhost', port: 6060, - path: `/system?method=${method}&v=1×tamp=${Math.floor(Date.now()/1000)}`, + path: `/system?method=${method}&v=1×tamp=${Math.floor(Date.now() / 1000)}`, method: 'POST', - headers: { 'platform': 'web', 'project': 'wms', 'Authorization': `Bearer ${TOKEN}`, 'Content-Type': 'application/json' }, + headers: { platform: 'web', project: 'wms', Authorization: `Bearer ${TOKEN}`, 'Content-Type': 'application/json' }, timeout: 60000, }; const req = http.request(opts, res => { let d = ''; res.on('data', c => d += c); res.on('end', () => { - try { resolve({ status: res.statusCode, body: JSON.parse(d) }); } - catch (e) { resolve({ status: res.statusCode, body: { _raw: d.substring(0, 300) } }); } + try { resolve({ status: res.statusCode, body: JSON.parse(d) }); } catch (e) { resolve({ status: res.statusCode, body: { _raw: d.substring(0, 300) } }); } }); }); req.on('error', e => reject(e)); @@ -57,13 +56,13 @@ function sleep(ms) { return new Promise(r => setTimeout(r, ms)); } async function setPolicy(policyCfg) { const conn = await mysql.createConnection(DB_CONFIG); await conn.execute('UPDATE wms_store_warehouse SET policy_config = ? WHERE id = ?', - [JSON.stringify(policyCfg), TEST.contractId]); + [ JSON.stringify(policyCfg), TEST.contractId ]); await conn.end(); } async function dbQuery(sql, params = []) { const conn = await mysql.createConnection(DB_CONFIG); - const [rows] = await conn.execute(sql, params); + const [ rows ] = await conn.execute(sql, params); await conn.end(); return rows; } @@ -84,14 +83,14 @@ async function createOrder() { async function checkExpressAssignment(orderId) { const rows = await dbQuery( 'SELECT id, order_id, warehouse_id FROM wms_order_express WHERE order_id = ? AND warehouse_id = ? LIMIT 1', - [orderId, TEST.warehouseId] + [ orderId, TEST.warehouseId ] ); return rows.length > 0; } async function runScene(label, sceneKey, expectedStep, expectedExpress) { console.log(`\n=== ${label} ===`); - + // 1. Set policy console.log(' [1] 设置 policy_config...'); await setPolicy(POLICY[sceneKey]); @@ -104,13 +103,13 @@ async function runScene(label, sceneKey, expectedStep, expectedExpress) { console.log(' [2] 创建订单...'); const r = await createOrder(); console.log(` status: ${r.status}`); - + const success = r.status === 200 && r.body && r.body.flag === 'success'; if (!success) { console.log(` ❌ 创建失败: ${JSON.stringify(r.body).substring(0, 200)}`); return { pass: false, reason: 'create_failed', detail: r.body }; } - + const orderId = r.body.order_id || r.body.data?.order_id; const step = r.body.step || r.body.data?.step; console.log(` order_id: ${orderId}, step: ${step} (预期=${expectedStep})`); @@ -171,8 +170,8 @@ async function main() { console.log('============================================'); const total = Object.keys(results).length; const passing = Object.values(results).filter(r => r.pass).length; - - for (const [key, r] of Object.entries(results)) { + + for (const [ key, r ] of Object.entries(results)) { const icon = r.pass ? '✅' : '❌'; console.log(` ${icon} 场景 ${key}: step=${r.step}(预期${r.expectedStep}) express=${r.hasExpress}(预期${r.expectedExpress})`); } diff --git a/script/cutoff-integration-test-v3.js b/script/cutoff-integration-test-v3.js index 86b379e..e945a15 100644 --- a/script/cutoff-integration-test-v3.js +++ b/script/cutoff-integration-test-v3.js @@ -1,8 +1,8 @@ /** * 截单时间逻辑真实 API 集成测试 (v3 - Final) - * + * * 测试 asyncProcessOrderCreated 的截单兜底逻辑 - * + * * 场景 A: 免审核 + 未截单(23:59) → 应触发自动分配快递 * 场景 B: 免审核 + 已截单(00:01) → 应跳过 * 场景 C: 需要审核 → 应跳过 (step=0) @@ -34,14 +34,13 @@ function api(method, body) { const bodyStr = JSON.stringify(body); const req = http.request({ hostname: 'localhost', port: 6060, - path: `/system?method=${method}&v=1×tamp=${Math.floor(Date.now()/1000)}`, + path: `/system?method=${method}&v=1×tamp=${Math.floor(Date.now() / 1000)}`, method: 'POST', headers: { platform: 'web', project: 'wms', Authorization: `Bearer ${TOKEN}`, 'Content-Type': 'application/json' }, timeout: 60000, }, res => { let d = ''; res.on('data', c => d += c); res.on('end', () => { - try { resolve({ status: res.statusCode, body: JSON.parse(d) }); } - catch (e) { resolve({ status: res.statusCode, body: { _raw: d.substring(0, 300) } }); } + try { resolve({ status: res.statusCode, body: JSON.parse(d) }); } catch (e) { resolve({ status: res.statusCode, body: { _raw: d.substring(0, 300) } }); } }); }); req.on('error', e => reject(e)); @@ -53,7 +52,7 @@ function sleep(ms) { return new Promise(r => setTimeout(r, ms)); } async function dbQuery(sql, params = []) { const conn = await mysql.createConnection(DB); - const [rows] = await conn.execute(sql, params); + const [ rows ] = await conn.execute(sql, params); await conn.end(); return rows; } @@ -64,9 +63,9 @@ async function setPolicy(sceneKey) { const policyObj = POLICY[sceneKey]; const conn = await mysql.createConnection(DB); await conn.execute('UPDATE wms_store_warehouse SET policy_config = ? WHERE id = ?', - [JSON.stringify(policyObj), CONTRACT_ID]); + [ JSON.stringify(policyObj), CONTRACT_ID ]); await conn.end(); - + // 通过 API 调用 savePolicyConfig 清除缓存 console.log(' 调用 savePolicyConfig API 清除缓存...'); const apiRes = await api('storeWarehouse.store.savePolicyConfig', { id: CONTRACT_ID, policy_config: policyObj }); @@ -112,13 +111,13 @@ async function runScene(label, sceneKey, expectedStep, checkExpressExpected) { console.log(` [1] 更新 policy_config → scene ${sceneKey}`); console.log(` ${JSON.stringify(POLICY[sceneKey])}`); await setPolicy(sceneKey); - + // 2. Wait for cache invalidation - console.log(` [2] 等待缓存... (10秒让 600s cache 有机会清除)`); + console.log(' [2] 等待缓存... (10秒让 600s cache 有机会清除)'); await sleep(10000); // 3. Create order via API - console.log(` [3] API 创建订单...`); + console.log(' [3] API 创建订单...'); const r = await createOrder(); console.log(` HTTP ${r.status}`); @@ -133,7 +132,7 @@ async function runScene(label, sceneKey, expectedStep, checkExpressExpected) { console.log(` order_id=${orderId}, api_step=${apiStep}, api_step_label="${r.body.step_label}"`); // 4. Wait async processing - console.log(` [4] 等待异步处理 (8秒)...`); + console.log(' [4] 等待异步处理 (8秒)...'); await sleep(8000); // 5. Check DB @@ -141,7 +140,7 @@ async function runScene(label, sceneKey, expectedStep, checkExpressExpected) { if (order) { console.log(` [5] DB 订单状态: step=${order.step}, status=${order.status}, wave_id=${order.wave_id}, logistics=${order.sys_logistics_code}`); } else { - console.log(` [5] ⚠️ 数据库中未找到订单!`); + console.log(' [5] ⚠️ 数据库中未找到订单!'); return { pass: false, reason: 'DB中找不到订单' }; } @@ -190,7 +189,7 @@ async function main() { console.log(' 测试结果汇总'); console.log(`${'='.repeat(60)}`); let passCount = 0; - for (const [key, r] of Object.entries(results)) { + for (const [ key, r ] of Object.entries(results)) { const icon = r.pass ? '✅' : '❌'; const detail = r.pass ? '' : ` | step=${r.step}≠${r.expectedStep} express=${r.hasExpress}≠${r.checkExpressExpected}`; console.log(` ${icon} 场景 ${key}${detail}`); diff --git a/script/cutoff-integration-test.js b/script/cutoff-integration-test.js index f009146..46c8939 100644 --- a/script/cutoff-integration-test.js +++ b/script/cutoff-integration-test.js @@ -1,14 +1,14 @@ /** * 截单时间逻辑真实 API 集成测试 - * + * * 测试目标: 验证 asyncProcessOrderCreated 中的截单时间兜底逻辑 - * + * * 测试环境: * - Dev Server: http://localhost:6060 * - Warehouse ID: 1000028 (天豹云仓) * - Store ID: 1000241 * - Store-Warehouse ID: 100213 - * + * * 测试步骤: * A) 免审核 + 未截单 → 应触发自动分配快递 * B) 免审核 + 已截单 → 应跳过 @@ -40,14 +40,14 @@ function apiRequest(method, body) { path: `/system?method=${method}&v=1×tamp=${Math.floor(Date.now() / 1000)}`, method: 'POST', headers: { - 'platform': 'web', - 'project': 'wms', - 'Authorization': `Bearer ${TOKEN}`, + platform: 'web', + project: 'wms', + Authorization: `Bearer ${TOKEN}`, 'Content-Type': 'application/json', }, timeout: 60000, }; - const req = http.request(options, (res) => { + const req = http.request(options, res => { let data = ''; res.on('data', chunk => data += chunk); res.on('end', () => { @@ -60,7 +60,7 @@ function apiRequest(method, body) { resolve({ status: res.statusCode, body: parsed }); }); }); - req.on('error', (e) => reject(e)); + req.on('error', e => reject(e)); req.on('timeout', () => { req.destroy(); reject(new Error('Request timeout')); }); req.write(bodyStr); req.end(); @@ -73,6 +73,7 @@ function sleep(ms) { /** * 更新 store_warehouse 的 policy_config + * @param policyConfig */ async function updatePolicyConfig(policyConfig) { return await apiRequest('storeWarehouse.store.savePolicyConfig', { diff --git a/script/integration-test.js b/script/integration-test.js index ee8e01f..02685ce 100644 --- a/script/integration-test.js +++ b/script/integration-test.js @@ -16,13 +16,13 @@ function apiRequest(method, body) { path: `/system?method=${method}&v=1×tamp=${Math.floor(Date.now() / 1000)}`, method: 'POST', headers: { - 'platform': 'web', - 'project': 'wms', - 'Authorization': `Bearer ${TOKEN}`, + platform: 'web', + project: 'wms', + Authorization: `Bearer ${TOKEN}`, 'Content-Type': 'application/json', }, }; - const req = http.request(options, (res) => { + const req = http.request(options, res => { let data = ''; res.on('data', chunk => data += chunk); res.on('end', () => { @@ -35,7 +35,7 @@ function apiRequest(method, body) { resolve({ status: res.statusCode, headers: res.headers, body, _rawLength: data.length }); }); }); - req.on('error', (e) => reject(e)); + req.on('error', e => reject(e)); req.write(bodyStr); req.end(); }); diff --git a/script/update-policy.js b/script/update-policy.js index 1654a69..df53873 100644 --- a/script/update-policy.js +++ b/script/update-policy.js @@ -46,15 +46,15 @@ async function main() { database: 'wms', }); - const [result] = await conn.execute( + const [ result ] = await conn.execute( 'UPDATE wms_store_warehouse SET policy_config = ? WHERE id = ?', - [policyStr, contractId] + [ policyStr, contractId ] ); console.log('Update result:', JSON.stringify(result)); - const [rows] = await conn.execute( + const [ rows ] = await conn.execute( 'SELECT id, store_id, warehouse_id, policy_config FROM wms_store_warehouse WHERE id = ?', - [contractId] + [ contractId ] ); console.log('Current record:', JSON.stringify(rows[0], null, 2)); diff --git a/scripts/check_tables.js b/scripts/check_tables.js index 3519c84..03894a9 100644 --- a/scripts/check_tables.js +++ b/scripts/check_tables.js @@ -2,28 +2,28 @@ const mysql = require('mysql2/promise'); (async () => { - const conn = await mysql.createConnection({host:'127.0.0.1',port:3307,user:'wms',password:'dspxmRwRdRbWtbm7',database:'wms'}); + const conn = await mysql.createConnection({ host: '127.0.0.1', port: 3307, user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms' }); - const [tables] = await conn.query("SHOW TABLES LIKE 'wms_order_delivery%'"); + const [ tables ] = await conn.query("SHOW TABLES LIKE 'wms_order_delivery%'"); console.log('order_delivery tables:'); tables.forEach(t => console.log(' ', Object.values(t)[0])); - const [tables2] = await conn.query("SHOW TABLES LIKE '%recheck%'"); + const [ tables2 ] = await conn.query("SHOW TABLES LIKE '%recheck%'"); console.log('recheck tables:'); tables2.forEach(t => console.log(' ', Object.values(t)[0])); - const [tables3] = await conn.query("SHOW TABLES LIKE '%wave%'"); + const [ tables3 ] = await conn.query("SHOW TABLES LIKE '%wave%'"); console.log('wave tables:'); tables3.forEach(t => console.log(' ', Object.values(t)[0])); // Check the current model table for warehouse 100000 console.log('\nChecking wms_order_delivery for recheck_status:'); try { - const [rows] = await conn.query("SELECT * FROM wms_order_delivery WHERE warehouse_id = 100000 LIMIT 1"); + const [ rows ] = await conn.query('SELECT * FROM wms_order_delivery WHERE warehouse_id = 100000 LIMIT 1'); if (rows.length > 0) { console.log('Keys:', Object.keys(rows[0]).join(', ')); } - } catch(e) { + } catch (e) { console.log('Error:', e.message); } diff --git a/scripts/integration_test_stock_warehouse.js b/scripts/integration_test_stock_warehouse.js index c6843f9..93bbdaf 100644 --- a/scripts/integration_test_stock_warehouse.js +++ b/scripts/integration_test_stock_warehouse.js @@ -8,7 +8,7 @@ const TEST_STORE_ID = 1000000; async function main() { const conn = await mysql.createConnection(DB_CONFIG); - + try { console.log('='.repeat(70)); console.log('WMS 拣货/复核完成 - stock_warehouse + stock_transaction 集成验证'); @@ -19,13 +19,13 @@ async function main() { // === 步骤1: 检查订单分表 === console.log('\n--- 步骤1: 检查订单分表 ---'); - const [tables] = await conn.query("SHOW TABLES LIKE 'wms_order_delivery_%'"); + const [ tables ] = await conn.query("SHOW TABLES LIKE 'wms_order_delivery_%'"); console.log(` 订单分表数量: ${tables.length}`); tables.forEach(t => console.log(` - ${Object.values(t)[0]}`)); // === 步骤2: 查看订单状态分布 === console.log('\n--- 步骤2: 订单状态分布 (wms_order_delivery_100000) ---'); - const [statusDist] = await conn.query(` + const [ statusDist ] = await conn.query(` SELECT pick_status, recheck_status, storage_status, status, COUNT(*) as cnt FROM wms_order_delivery_100000 GROUP BY pick_status, recheck_status, storage_status, status @@ -36,7 +36,7 @@ async function main() { // === 步骤3: 查找最近有库存变更的 stock_warehouse === console.log('\n--- 步骤3: wms_stock_warehouse 状态 (warehouse=100000) ---'); - const [swRows] = await conn.query(` + const [ swRows ] = await conn.query(` SELECT id, item_code, item_name, quantity, locked_quantity, store_id FROM wms_stock_warehouse WHERE warehouse_id = 100000 AND quantity > 0 @@ -47,7 +47,7 @@ async function main() { // === 步骤4: wms_stock_transaction 最近记录 === console.log('\n--- 步骤4: wms_stock_transaction 最近记录 ---'); - const [recentTx] = await conn.query(` + const [ recentTx ] = await conn.query(` SELECT id, transaction_type, order_type, stock_id, quantity, before_quantity, after_quantity, before_locked_quantity, after_locked_quantity, @@ -72,7 +72,7 @@ async function main() { // === 步骤5: 统计 stock_transaction 的 before_locked/after_locked 非零记录 === console.log('\n--- 步骤5: stock_transaction locked_quantity 变更统计 ---'); - const [lockedStats] = await conn.query(` + const [ lockedStats ] = await conn.query(` SELECT COUNT(*) as total, SUM(CASE WHEN before_locked_quantity > 0 OR after_locked_quantity > 0 THEN 1 ELSE 0 END) as with_locked, @@ -83,7 +83,7 @@ async function main() { // === 步骤6: 检查 wms_stock_transaction 中 remark 包含"货主库存释放"的记录 === console.log('\n--- 步骤6: 货主库存释放 stock_transaction 记录 ---'); - const [releaseTx] = await conn.query(` + const [ releaseTx ] = await conn.query(` SELECT id, transaction_type, order_type, stock_id, quantity, before_locked_quantity, after_locked_quantity, remark, created_at FROM wms_stock_transaction @@ -102,7 +102,7 @@ async function main() { console.log('\n' + '='.repeat(70)); console.log('集成验证完成'); console.log('='.repeat(70)); - + } finally { await conn.end(); } diff --git a/scripts/query_more_test_orders.js b/scripts/query_more_test_orders.js index 820d49c..4f51a77 100644 --- a/scripts/query_more_test_orders.js +++ b/scripts/query_more_test_orders.js @@ -1,6 +1,6 @@ 'use strict'; const mysql = require('mysql2/promise'); -const DB_CONFIG = {host:'127.0.0.1',port:3307,user:'wms',password:'dspxmRwRdRbWtbm7',database:'wms'}; +const DB_CONFIG = { host: '127.0.0.1', port: 3307, user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms' }; const TABLE = 'wms_order_delivery_100000'; (async () => { @@ -8,7 +8,7 @@ const TABLE = 'wms_order_delivery_100000'; try { // More success candidates: pick_status = 'fin' AND recheck_status != 'fin' console.log('=== 已拣货未复核 ==='); - const [r1] = await conn.query( + const [ r1 ] = await conn.query( `SELECT id, delivery_order_code, pick_status, recheck_status, wave_id FROM ${TABLE} WHERE storage_status='fin' AND post_status='fin' AND status='created' @@ -21,7 +21,7 @@ const TABLE = 'wms_order_delivery_100000'; // Also check: pick_status='none' (未拣货未复核) console.log('=== 未拣货未复核 (pick_status=none) ==='); - const [r2] = await conn.query( + const [ r2 ] = await conn.query( `SELECT id, delivery_order_code, pick_status, recheck_status FROM ${TABLE} WHERE storage_status='fin' AND post_status='fin' AND status='created' @@ -34,7 +34,7 @@ const TABLE = 'wms_order_delivery_100000'; // Other pick statuses console.log('=== 其他拣货状态未复核 ==='); - const [r3] = await conn.query( + const [ r3 ] = await conn.query( `SELECT id, delivery_order_code, pick_status, recheck_status FROM ${TABLE} WHERE storage_status='fin' AND post_status='fin' AND status='created' @@ -46,5 +46,5 @@ const TABLE = 'wms_order_delivery_100000'; console.log(` 共 ${r3.length} 条\n`); await conn.end(); - } catch(e) { console.error(e.message); await conn.end(); } + } catch (e) { console.error(e.message); await conn.end(); } })(); diff --git a/scripts/query_test_orders.js b/scripts/query_test_orders.js index 34df2c1..2929a86 100644 --- a/scripts/query_test_orders.js +++ b/scripts/query_test_orders.js @@ -21,7 +21,7 @@ async function queryTestOrders() { console.log('【成功用例候选】满足所有前置条件的订单(未复核):'); console.log('-'.repeat(80)); - const [successRows] = await conn.query( + const [ successRows ] = await conn.query( `SELECT id, delivery_order_code, pre_delivery_order_code, storage_status, post_status, status, intercept_status, pick_status, recheck_status, wave_id, wave_no @@ -34,7 +34,7 @@ async function queryTestOrders() { AND recheck_status != 'fin' ORDER BY pick_status ASC, id DESC LIMIT 10`, - [WAREHOUSE_ID] + [ WAREHOUSE_ID ] ); for (const row of successRows) { @@ -52,7 +52,7 @@ async function queryTestOrders() { console.log('【失败用例候选 - storage_status != fin】未分配储位:'); console.log('-'.repeat(80)); - const [noStorageRows] = await conn.query( + const [ noStorageRows ] = await conn.query( `SELECT id, delivery_order_code, pre_delivery_order_code, storage_status, post_status, status, intercept_status, pick_status, recheck_status @@ -62,7 +62,7 @@ async function queryTestOrders() { AND (post_status = 'fin' OR 1=1) ORDER BY id DESC LIMIT 3`, - [WAREHOUSE_ID] + [ WAREHOUSE_ID ] ); for (const row of noStorageRows) { @@ -75,7 +75,7 @@ async function queryTestOrders() { console.log('【失败用例候选 - post_status != fin】未分配快递:'); console.log('-'.repeat(80)); - const [noPostRows] = await conn.query( + const [ noPostRows ] = await conn.query( `SELECT id, delivery_order_code, pre_delivery_order_code, storage_status, post_status, status, intercept_status, pick_status, recheck_status @@ -85,7 +85,7 @@ async function queryTestOrders() { AND storage_status = 'fin' ORDER BY id DESC LIMIT 3`, - [WAREHOUSE_ID] + [ WAREHOUSE_ID ] ); for (const row of noPostRows) { @@ -98,7 +98,7 @@ async function queryTestOrders() { console.log('【失败用例候选 - status != created】未同步:'); console.log('-'.repeat(80)); - const [noSyncRows] = await conn.query( + const [ noSyncRows ] = await conn.query( `SELECT id, delivery_order_code, pre_delivery_order_code, storage_status, post_status, status, intercept_status, pick_status, recheck_status @@ -109,7 +109,7 @@ async function queryTestOrders() { AND post_status = 'fin' ORDER BY id DESC LIMIT 3`, - [WAREHOUSE_ID] + [ WAREHOUSE_ID ] ); for (const row of noSyncRows) { @@ -122,7 +122,7 @@ async function queryTestOrders() { console.log('【失败用例候选 - 已拦截】:'); console.log('-'.repeat(80)); - const [interceptedRows] = await conn.query( + const [ interceptedRows ] = await conn.query( `SELECT id, delivery_order_code, pre_delivery_order_code, storage_status, post_status, status, intercept_status, pick_status, recheck_status @@ -131,7 +131,7 @@ async function queryTestOrders() { AND intercept_status IN ('intercepted', 'intercepted_at_warehouse') ORDER BY id DESC LIMIT 3`, - [WAREHOUSE_ID] + [ WAREHOUSE_ID ] ); for (const row of interceptedRows) { diff --git a/scripts/query_test_orders_v2.js b/scripts/query_test_orders_v2.js index af28361..70d15bd 100644 --- a/scripts/query_test_orders_v2.js +++ b/scripts/query_test_orders_v2.js @@ -15,7 +15,7 @@ async function main() { console.log('【成功用例候选】满足所有前置条件的订单(未复核):'); console.log('-'.repeat(80)); - const [successRows] = await conn.query( + const [ successRows ] = await conn.query( `SELECT id, delivery_order_code, pre_delivery_order_code, storage_status, post_status, status, intercept_status, pick_status, recheck_status, wave_id, wave_no @@ -39,7 +39,7 @@ async function main() { console.log('='.repeat(80)); console.log('【失败用例候选 - storage_status != fin】'); - const [noStorageRows] = await conn.query( + const [ noStorageRows ] = await conn.query( `SELECT id, delivery_order_code, storage_status FROM ${TABLE} WHERE storage_status != 'fin' ORDER BY id DESC LIMIT 3` ); noStorageRows.forEach(r => console.log(` ID: ${r.id} storage_status="${r.storage_status}"`)); @@ -48,7 +48,7 @@ async function main() { console.log('='.repeat(80)); console.log('【失败用例候选 - post_status != fin】'); - const [noPostRows] = await conn.query( + const [ noPostRows ] = await conn.query( `SELECT id, delivery_order_code, post_status FROM ${TABLE} WHERE post_status != 'fin' AND storage_status = 'fin' ORDER BY id DESC LIMIT 3` ); noPostRows.forEach(r => console.log(` ID: ${r.id} post_status="${r.post_status}"`)); @@ -57,7 +57,7 @@ async function main() { console.log('='.repeat(80)); console.log('【失败用例候选 - status != created】'); - const [noSyncRows] = await conn.query( + const [ noSyncRows ] = await conn.query( `SELECT id, delivery_order_code, status FROM ${TABLE} WHERE status != 'created' AND storage_status = 'fin' AND post_status = 'fin' ORDER BY id DESC LIMIT 3` ); noSyncRows.forEach(r => console.log(` ID: ${r.id} status="${r.status}"`)); @@ -66,7 +66,7 @@ async function main() { console.log('='.repeat(80)); console.log('【失败用例候选 - 已拦截】'); - const [interceptedRows] = await conn.query( + const [ interceptedRows ] = await conn.query( `SELECT id, delivery_order_code, intercept_status FROM ${TABLE} WHERE intercept_status IN ('intercepted','intercepted_at_warehouse') ORDER BY id DESC LIMIT 3` ); interceptedRows.forEach(r => console.log(` ID: ${r.id} intercept_status="${r.intercept_status}"`)); diff --git a/scripts/test_batch_quick_recheck.js b/scripts/test_batch_quick_recheck.js index 688d5e5..af8f28a 100644 --- a/scripts/test_batch_quick_recheck.js +++ b/scripts/test_batch_quick_recheck.js @@ -4,13 +4,13 @@ const TOKEN = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJs const BASE_URL = 'http://127.0.0.1:6060'; const TABLE = 'wms_order_delivery_100000'; const mysql = require('mysql2/promise'); -const DB_CONFIG = {host:'127.0.0.1',port:3307,user:'wms',password:'dspxmRwRdRbWtbm7',database:'wms'}; +const DB_CONFIG = { host: '127.0.0.1', port: 3307, user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms' }; async function getOrderSnapshot(conn, ids) { if (!ids.length) return {}; - const [rows] = await conn.query( + const [ rows ] = await conn.query( `SELECT id, pick_status, recheck_status, storage_status, post_status, status, intercept_status - FROM ${TABLE} WHERE id IN (?)`, [ids] + FROM ${TABLE} WHERE id IN (?)`, [ ids ] ); const map = {}; rows.forEach(r => { map[r.id] = r; }); @@ -21,10 +21,10 @@ async function callApi(ids) { const ts = Math.floor(Date.now() / 1000); const url = `${BASE_URL}/system?method=order.recheckOrder.batchQuickRecheck&v=1.0×tamp=${ts}`; const headers = { - 'platform': 'web', - 'project': 'wms', + platform: 'web', + project: 'wms', 'Content-Type': 'application/json; charset=utf-8', - 'Authorization': `Bearer ${TOKEN}`, + Authorization: `Bearer ${TOKEN}`, }; const body = JSON.stringify({ module: 'order.recheckOrder', @@ -53,7 +53,7 @@ async function runTestCase(name, ids, expectedDesc) { // 测试前快照 beforeSnapshot = await getOrderSnapshot(conn, ids); console.log(' 测试前状态:'); - for (const [id, snap] of Object.entries(beforeSnapshot)) { + for (const [ id, snap ] of Object.entries(beforeSnapshot)) { console.log(` ID ${id}: pick="${snap.pick_status}" recheck="${snap.recheck_status}" storage="${snap.storage_status}" post="${snap.post_status}" status="${snap.status}" intercept="${snap.intercept_status}"`); } @@ -69,7 +69,7 @@ async function runTestCase(name, ids, expectedDesc) { // 测试后快照 afterSnapshot = await getOrderSnapshot(conn, ids); console.log(' 测试后状态:'); - for (const [id, snap] of Object.entries(afterSnapshot)) { + for (const [ id, snap ] of Object.entries(afterSnapshot)) { const before = beforeSnapshot[id] || {}; const changes = []; if (snap.pick_status !== before.pick_status) changes.push(`pick: ${before.pick_status}→${snap.pick_status}`); @@ -98,42 +98,42 @@ async function main() { // 用例1: 全成功-含未拣货(1个有效订单) results.push(await runTestCase( '用例1: 全成功-含未拣货', - [120946], + [ 120946 ], 'pick_status=none → 自动完成拣货+复核, 全部 success' )); // 用例2: 全失败-无储位 results.push(await runTestCase( '用例2: 全失败-无储位', - [120947, 120939], + [ 120947, 120939 ], '全部 failed, reason="未分配储位"' )); // 用例3: 全失败-无快递 results.push(await runTestCase( '用例3: 全失败-无快递', - [120944, 120943], + [ 120944, 120943 ], '全部 failed, reason="没有分配快递"' )); // 用例4: 全失败-未同步 results.push(await runTestCase( '用例4: 全失败-未同步', - [120858, 120857], + [ 120858, 120857 ], '全部 failed, reason="没有同步"' )); // 用例5: 全失败-已拦截 results.push(await runTestCase( '用例5: 全失败-已拦截', - [120945], + [ 120945 ], '全部 failed, reason="已拦截"' )); // 用例6: 部分失败-混合 results.push(await runTestCase( '用例6: 部分失败-混合', - [120946, 120947, 999999999], + [ 120946, 120947, 999999999 ], 'success 和 failed 各有' )); @@ -147,7 +147,7 @@ async function main() { // 用例8: 不存在ID results.push(await runTestCase( '用例8: 不存在ID', - [999999999], + [ 999999999 ], '全部 failed, reason="未找到对应订单"' )); diff --git a/scripts/test_batch_quick_recheck_full.js b/scripts/test_batch_quick_recheck_full.js index 38db52a..b85fb4e 100644 --- a/scripts/test_batch_quick_recheck_full.js +++ b/scripts/test_batch_quick_recheck_full.js @@ -29,10 +29,10 @@ async function closeConn() { async function getOrderSnapshot(ids) { const c = await getConn(); if (!ids.length) return {}; - const [rows] = await c.query( + const [ rows ] = await c.query( `SELECT id, delivery_order_code, pre_delivery_order_code, pick_status, recheck_status, storage_status, post_status, status, intercept_status - FROM ${TABLE} WHERE id IN (?)`, [ids] + FROM ${TABLE} WHERE id IN (?)`, [ ids ] ); const map = {}; rows.forEach(r => { map[r.id] = r; }); @@ -42,8 +42,8 @@ async function getOrderSnapshot(ids) { async function getStorageSnapshot(ids) { const c = await getConn(); if (!ids.length) return {}; - const [rows] = await c.query( - 'SELECT id, quantity, locked_quantity FROM wms_storage WHERE id IN (?) AND warehouse_id = 100000', [ids] + const [ rows ] = await c.query( + 'SELECT id, quantity, locked_quantity FROM wms_storage WHERE id IN (?) AND warehouse_id = 100000', [ ids ] ); const map = {}; rows.forEach(r => { map[r.id] = r; }); @@ -54,10 +54,10 @@ async function callApi(ids) { const ts = Math.floor(Date.now() / 1000); const url = `${BASE_URL}/system?method=order.recheckOrder.batchQuickRecheck&v=1.0×tamp=${ts}`; const headers = { - 'platform': 'web', - 'project': 'wms', + platform: 'web', + project: 'wms', 'Content-Type': 'application/json; charset=utf-8', - 'Authorization': `Bearer ${TOKEN}`, + Authorization: `Bearer ${TOKEN}`, }; const body = JSON.stringify({ ids }); @@ -76,7 +76,10 @@ async function runTestCase(name, ids, expectedDesc, preSetup, postVerify, postCl console.log(` 输入IDs: [${ids.join(', ')}]`); console.log(` 预期: ${expectedDesc}`); - let beforeOrder = {}, beforeStorage = {}, afterOrder = {}, afterStorage = {}; + let beforeOrder = {}, + beforeStorage = {}, + afterOrder = {}, + afterStorage = {}; let passed = false; let failReason = ''; @@ -91,7 +94,7 @@ async function runTestCase(name, ids, expectedDesc, preSetup, postVerify, postCl // 测试前快照 beforeOrder = await getOrderSnapshot(ids); console.log(' 测试前订单状态:'); - for (const [id, snap] of Object.entries(beforeOrder)) { + for (const [ id, snap ] of Object.entries(beforeOrder)) { console.log(` ID ${id}: storage="${snap.storage_status}" post="${snap.post_status}" status="${snap.status}" intercept="${snap.intercept_status}" pick="${snap.pick_status}" recheck="${snap.recheck_status}" code="${snap.delivery_order_code || snap.pre_delivery_order_code || ''}"`); } @@ -104,7 +107,7 @@ async function runTestCase(name, ids, expectedDesc, preSetup, postVerify, postCl // 测试后快照 afterOrder = await getOrderSnapshot(ids); console.log(' 测试后订单状态:'); - for (const [id, snap] of Object.entries(afterOrder)) { + for (const [ id, snap ] of Object.entries(afterOrder)) { const before = beforeOrder[id] || {}; const changes = []; if (snap.pick_status !== before.pick_status) changes.push(`pick: ${before.pick_status}→${snap.pick_status}`); @@ -155,7 +158,7 @@ async function main() { console.log(`测试时间: ${new Date().toISOString()}`); console.log(`目标表: ${TABLE}`); console.log(`Base URL: ${BASE_URL}`); - console.log(`测试仓库ID: 100000 | 测试货主ID: 1000000`); + console.log('测试仓库ID: 100000 | 测试货主ID: 1000000'); console.log('='.repeat(60)); const results = []; @@ -164,7 +167,7 @@ async function main() { console.log('\n── 全局前置:恢复 120946 关联库存 locked_quantity ──'); const c = await getConn(); // 记录 storage 184 原始状态 - const [origStorage] = await c.query('SELECT id, quantity, locked_quantity FROM wms_storage WHERE id = 184 AND warehouse_id = 100000'); + const [ origStorage ] = await c.query('SELECT id, quantity, locked_quantity FROM wms_storage WHERE id = 184 AND warehouse_id = 100000'); console.log(` storage 184 原始: quantity=${origStorage[0].quantity}, locked=${origStorage[0].locked_quantity}`); // 恢复 locked_quantity 以便测试成功扣减 if (origStorage[0].locked_quantity < 1) { @@ -187,7 +190,7 @@ async function main() { [], '返回错误 "订单ID列表不能为空"', null, - async (result) => { + async result => { // batchQuickRecheck 返回 500 而非 400(内部 throw(400) 被框架包装为 500) // 检查是否包含错误消息 const msg = result.body && (result.body.message || ''); @@ -200,10 +203,10 @@ async function main() { // ── 用例 8: 不存在的订单ID ── results.push(await runTestCase( '用例8: 不存在的订单ID', - [999999999], + [ 999999999 ], '全部 failed, reason="未找到对应订单"', null, - async (result) => { + async result => { const data = result.body && (result.body.data !== undefined ? result.body.data : result.body); if (!data || typeof data !== 'object') return `返回数据格式异常: ${JSON.stringify(result.body)}`; if (data.success_count === 0 && data.failed_count >= 1) { @@ -218,10 +221,10 @@ async function main() { // ── 用例 5: 失败-未同步(120858: status='pedding') ── results.push(await runTestCase( '用例5: 失败-未同步', - [120858, 120857], + [ 120858, 120857 ], '全部 failed, reason="没有同步"', null, - async (result) => { + async result => { const data = result.body && (result.body.data !== undefined ? result.body.data : result.body); if (!data || data.success_count !== 0) return `期望 success_count=0,实际: ${JSON.stringify(data)}`; const allNoSync = (data.failed || []).every(f => f.reason === '没有同步'); @@ -233,10 +236,10 @@ async function main() { // ── 用例 4: 失败-无快递(120944: post_status='none') ── results.push(await runTestCase( '用例4: 失败-无快递', - [120944, 120943], + [ 120944, 120943 ], '全部 failed, reason="没有分配快递"', null, - async (result) => { + async result => { const data = result.body && (result.body.data !== undefined ? result.body.data : result.body); if (!data || data.success_count !== 0) return `期望 success_count=0,实际: ${JSON.stringify(data)}`; const allNoPost = (data.failed || []).every(f => f.reason === '没有分配快递'); @@ -248,10 +251,10 @@ async function main() { // ── 用例 3: 失败-未分配储位(120947: storage_status='none') ── results.push(await runTestCase( '用例3: 失败-未分配储位', - [120947, 120939], + [ 120947, 120939 ], '全部 failed, reason="未分配储位"', null, - async (result) => { + async result => { const data = result.body && (result.body.data !== undefined ? result.body.data : result.body); if (!data || data.success_count !== 0) return `期望 success_count=0,实际: ${JSON.stringify(data)}`; const allNoStorage = (data.failed || []).every(f => f.reason === '未分配储位'); @@ -263,10 +266,10 @@ async function main() { // ── 用例 2: 失败-已拦截(120945: intercept_status='intercepted_at_warehouse') ── results.push(await runTestCase( '用例2: 失败-已拦截', - [120945], + [ 120945 ], '全部 failed, reason="已拦截"', null, - async (result) => { + async result => { const data = result.body && (result.body.data !== undefined ? result.body.data : result.body); if (!data || data.success_count !== 0) return `期望 success_count=0,实际: ${JSON.stringify(data)}`; const allIntercepted = (data.failed || []).every(f => f.reason === '已拦截'); @@ -280,23 +283,23 @@ async function main() { let case1Cleanup = null; results.push(await runTestCase( '用例1: 成功-含未拣货', - [120946], + [ 120946 ], 'success_count >= 1, 订单 recheck_status=fin, pick_status=fin', async () => { // 再次确认前置条件 const c2 = await getConn(); - const [st] = await c2.query('SELECT locked_quantity FROM wms_storage WHERE id = 184 AND warehouse_id = 100000'); + const [ st ] = await c2.query('SELECT locked_quantity FROM wms_storage WHERE id = 184 AND warehouse_id = 100000'); console.log(` [前置确认] storage 184 locked_quantity=${st[0].locked_quantity}`); - const [pk] = await c2.query('SELECT status FROM wms_picking WHERE id = 87425 AND warehouse_id = 100000'); + const [ pk ] = await c2.query('SELECT status FROM wms_picking WHERE id = 87425 AND warehouse_id = 100000'); console.log(` [前置确认] picking 87425 status=${pk[0].status}`); }, - async (result) => { + async result => { const data = result.body && (result.body.data !== undefined ? result.body.data : result.body); if (!data || data.success_count < 1) return `期望 success_count >= 1,实际: ${JSON.stringify(data)}`; // 验证 120946 的状态 const c3 = await getConn(); - const [order] = await c3.query( + const [ order ] = await c3.query( 'SELECT pick_status, recheck_status FROM wms_order_delivery_100000 WHERE id = 120946 AND warehouse_id = 100000' ); console.log(` [验证] 120946 pick_status="${order[0].pick_status}" recheck_status="${order[0].recheck_status}"`); @@ -304,7 +307,7 @@ async function main() { if (order[0].recheck_status !== 'fin') return `期望 recheck_status='fin',实际="${order[0].recheck_status}"`; // 验证库存已扣减 - const [stAfter] = await c3.query('SELECT locked_quantity, quantity FROM wms_storage WHERE id = 184 AND warehouse_id = 100000'); + const [ stAfter ] = await c3.query('SELECT locked_quantity, quantity FROM wms_storage WHERE id = 184 AND warehouse_id = 100000'); console.log(` [验证] storage 184 扣减后: locked=${stAfter[0].locked_quantity}, quantity=${stAfter[0].quantity}`); // 记录清理函数 @@ -329,12 +332,12 @@ async function main() { // 需要先确保 120946 恢复到可测试状态 results.push(await runTestCase( '用例6: 部分失败-混合', - [120946, 120947, 999999999], + [ 120946, 120947, 999999999 ], 'success_count >= 1 且 failed_count >= 2', async () => { // 恢复 120946 的前置条件 const c4 = await getConn(); - const [st] = await c4.query('SELECT locked_quantity FROM wms_storage WHERE id = 184 AND warehouse_id = 100000'); + const [ st ] = await c4.query('SELECT locked_quantity FROM wms_storage WHERE id = 184 AND warehouse_id = 100000'); if (st[0].locked_quantity < 1) { await c4.query('UPDATE wms_storage SET locked_quantity = locked_quantity + 1, quantity = quantity + 1, updated_at = NOW() WHERE id = 184 AND warehouse_id = 100000'); console.log(' [前置] storage 184 locked_quantity 已恢复 +1'); @@ -344,7 +347,7 @@ async function main() { await c4.query("UPDATE wms_order_delivery_100000 SET pick_status = 'none', recheck_status = 'none', updated_at = NOW() WHERE id = 120946 AND warehouse_id = 100000"); console.log(' [前置] 120946 数据已恢复'); }, - async (result) => { + async result => { const data = result.body && (result.body.data !== undefined ? result.body.data : result.body); if (!data) return `返回数据为空: ${JSON.stringify(result.body)}`; if (data.success_count >= 1 && data.failed_count >= 2) { @@ -358,13 +361,13 @@ async function main() { async () => { // 恢复 120946 const c5 = await getConn(); - const [st] = await c5.query('SELECT locked_quantity, quantity FROM wms_storage WHERE id = 184 AND warehouse_id = 100000'); + const [ st ] = await c5.query('SELECT locked_quantity, quantity FROM wms_storage WHERE id = 184 AND warehouse_id = 100000'); // 如果 locked_quantity 减少了(测试成功扣减了),恢复 await c5.query("UPDATE wms_picking SET status = 'pending', updated_at = NOW() WHERE id = 87425 AND warehouse_id = 100000"); await c5.query('UPDATE wms_wave_pick_task_order SET pick_status = 0, picked_time = NULL, update_time = NOW() WHERE id = 6057 AND warehouse_id = 100000'); await c5.query("UPDATE wms_order_delivery_100000 SET pick_status = 'none', recheck_status = 'none', updated_at = NOW() WHERE id = 120946 AND warehouse_id = 100000"); // 检查库存是否需要恢复 - const [st2] = await c5.query('SELECT locked_quantity FROM wms_storage WHERE id = 184 AND warehouse_id = 100000'); + const [ st2 ] = await c5.query('SELECT locked_quantity FROM wms_storage WHERE id = 184 AND warehouse_id = 100000'); console.log(` [用例6恢复] 120946 数据已恢复,storage 184 locked=${st2[0].locked_quantity}`); } )); @@ -372,7 +375,7 @@ async function main() { // ── 全局恢复:将 storage 184 恢复到测试前状态 ── console.log('\n── 全局恢复:storage 184 ──'); // 检查当前状态,恢复到原始值 - const [finalSt] = await c.query('SELECT quantity, locked_quantity FROM wms_storage WHERE id = 184 AND warehouse_id = 100000'); + const [ finalSt ] = await c.query('SELECT quantity, locked_quantity FROM wms_storage WHERE id = 184 AND warehouse_id = 100000'); console.log(` storage 184 最终: quantity=${finalSt[0].quantity}, locked=${finalSt[0].locked_quantity}`); console.log(` storage 184 原始: quantity=${origStorage[0].quantity}, locked=${origStorage[0].locked_quantity}`); diff --git a/scripts/test_batch_quick_recheck_v2.js b/scripts/test_batch_quick_recheck_v2.js index 5829f84..d5f1271 100644 --- a/scripts/test_batch_quick_recheck_v2.js +++ b/scripts/test_batch_quick_recheck_v2.js @@ -4,14 +4,14 @@ const TOKEN = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJs const BASE_URL = 'http://127.0.0.1:6060'; const TABLE = 'wms_order_delivery_100000'; const mysql = require('mysql2/promise'); -const DB_CONFIG = {host:'127.0.0.1',port:3307,user:'wms',password:'dspxmRwRdRbWtbm7',database:'wms'}; +const DB_CONFIG = { host: '127.0.0.1', port: 3307, user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms' }; async function getOrderSnapshot(conn, ids) { if (!ids.length) return {}; - const [rows] = await conn.query( + const [ rows ] = await conn.query( `SELECT id, delivery_order_code, pre_delivery_order_code, pick_status, recheck_status, storage_status, post_status, status, intercept_status - FROM ${TABLE} WHERE id IN (?)`, [ids] + FROM ${TABLE} WHERE id IN (?)`, [ ids ] ); const map = {}; rows.forEach(r => { map[r.id] = r; }); @@ -22,10 +22,10 @@ async function callApi(ids) { const ts = Math.floor(Date.now() / 1000); const url = `${BASE_URL}/system?method=order.recheckOrder.batchQuickRecheck&v=1.0×tamp=${ts}`; const headers = { - 'platform': 'web', - 'project': 'wms', + platform: 'web', + project: 'wms', 'Content-Type': 'application/json; charset=utf-8', - 'Authorization': `Bearer ${TOKEN}`, + Authorization: `Bearer ${TOKEN}`, }; // IMPORTANT: body 必须扁平化,ids 直接在顶层。callMethod 将整个 body 传给业务方法 const body = JSON.stringify({ ids }); @@ -51,7 +51,7 @@ async function runTestCase(name, ids, expectedDesc) { try { beforeSnapshot = await getOrderSnapshot(conn, ids); console.log(' 测试前状态:'); - for (const [id, snap] of Object.entries(beforeSnapshot)) { + for (const [ id, snap ] of Object.entries(beforeSnapshot)) { console.log(` ID ${id}: pick="${snap.pick_status}" recheck="${snap.recheck_status}" storage="${snap.storage_status}" post="${snap.post_status}" status="${snap.status}" intercept="${snap.intercept_status}" code="${snap.delivery_order_code || snap.pre_delivery_order_code || ''}"`); } @@ -64,7 +64,7 @@ async function runTestCase(name, ids, expectedDesc) { afterSnapshot = await getOrderSnapshot(conn, ids); console.log(' 测试后状态:'); - for (const [id, snap] of Object.entries(afterSnapshot)) { + for (const [ id, snap ] of Object.entries(afterSnapshot)) { const before = beforeSnapshot[id] || {}; const changes = []; if (snap.pick_status !== before.pick_status) changes.push(`pick: ${before.pick_status}→${snap.pick_status}`); @@ -102,49 +102,49 @@ async function main() { // 用例8: 不存在ID results.push(await runTestCase( '用例8: 不存在ID', - [999999999], + [ 999999999 ], '全部 failed, reason="未找到对应订单"' )); // 用例4: 全失败-未同步 results.push(await runTestCase( '用例4: 全失败-未同步', - [120858, 120857], + [ 120858, 120857 ], '全部 failed, reason="没有同步"' )); // 用例3: 全失败-无快递 results.push(await runTestCase( '用例3: 全失败-无快递', - [120944, 120943], + [ 120944, 120943 ], '全部 failed, reason="没有分配快递"' )); // 用例2: 全失败-无储位 results.push(await runTestCase( '用例2: 全失败-无储位', - [120947, 120939], + [ 120947, 120939 ], '全部 failed, reason="未分配储位"' )); // 用例5: 全失败-已拦截 results.push(await runTestCase( '用例5: 全失败-已拦截', - [120945], + [ 120945 ], '全部 failed, reason="已拦截"' )); // 用例6: 部分失败-混合(valid + invalid) results.push(await runTestCase( '用例6: 部分失败-混合', - [120946, 120947, 999999999], + [ 120946, 120947, 999999999 ], 'success 和 failed 各有' )); // 用例1: 全成功-含未拣货 (最后测,会修改数据) results.push(await runTestCase( '用例1: 全成功-含未拣货', - [120946], + [ 120946 ], 'pick_status=none → 自动完成拣货+复核, recheck_status=fin' )); diff --git a/test/app/model/order_delivery_dispatch_factory.test.js b/test/app/model/order_delivery_dispatch_factory.test.js index c6107bf..562771b 100644 --- a/test/app/model/order_delivery_dispatch_factory.test.js +++ b/test/app/model/order_delivery_dispatch_factory.test.js @@ -34,7 +34,7 @@ function createSequelizeTypes() { STRING: length => makeType(`VARCHAR(${length})`), BIGINT: unsignedBigInt, DECIMAL: (precision, scale) => makeType(`DECIMAL(${precision},${scale})`), - TEXT: (length) => makeType(length ? `TEXT(${length})` : 'TEXT'), + TEXT: length => makeType(length ? `TEXT(${length})` : 'TEXT'), ENUM: (...values) => makeType(`ENUM('${values.join("','")}')`), DATE: makeType('DATETIME'), INTEGER: length => makeType(`INT(${length})`), diff --git a/test/app/service/systemMethods/order/wave.waveStrategyFallbackOrderList.test.js b/test/app/service/systemMethods/order/wave.waveStrategyFallbackOrderList.test.js index 2840840..4fac703 100644 --- a/test/app/service/systemMethods/order/wave.waveStrategyFallbackOrderList.test.js +++ b/test/app/service/systemMethods/order/wave.waveStrategyFallbackOrderList.test.js @@ -35,8 +35,8 @@ function createHarness() { service.getWarehouseId = () => 1; // 模拟 normalizeOrderListItem / attachOrderExpressNumbers 为直通 - service.normalizeOrderListItem = (item) => item; - service.attachOrderExpressNumbers = async (list) => list; + service.normalizeOrderListItem = item => item; + service.attachOrderExpressNumbers = async list => list; // 捕获 buildWhere 入参,返回简单条件 const originalBuildWhere = service.buildWhere.bind(service); @@ -48,7 +48,7 @@ function createHarness() { // 模拟 getOrderModel 返回可控数据 service.getOrderModel = async () => ({ count: async () => 1, - findAll: async (opts) => { + findAll: async opts => { captures.modelOpts = opts; return [ { diff --git a/test/app/service/systemMethods/stock.warehouse.import.test.js b/test/app/service/systemMethods/stock.warehouse.import.test.js index b13fda4..40d7b5e 100644 --- a/test/app/service/systemMethods/stock.warehouse.import.test.js +++ b/test/app/service/systemMethods/stock.warehouse.import.test.js @@ -205,7 +205,7 @@ describe('test/app/service/systemMethods/stock.warehouse.import.test.js', () => }); it('should map 条码 to barcode', () => { - const row = { '条码': 'A,B' }; + const row = { 条码: 'A,B' }; const normalized = service._normalizeWarehouseImportRow(row); assert.deepEqual(normalized.barcode, [ 'A', 'B' ]); }); From 2817d17fc7f468a7ef16617a09f2cd50cca4e37e Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 6 Jul 2026 00:33:12 +0800 Subject: [PATCH 086/550] 1 --- .../systemMethods/order/pendingOrder.js | 367 +++++++++++++++++- .../systemMethods/order/recheckOrder.js | 6 +- app/service/systemMethods/pick.js | 238 +++++++++++- app/service/systems/order_async.js | 121 ++++-- .../systems/order_storage_allocation.js | 247 ++++++++---- .../changes/syncOrderIds-async-20260704.json | 29 ++ ...OrderIds-async-review-feedback-20260704.md | 154 ++++++++ methods/changes/system.json | 17 + methods/system.json | 209 +++++++++- .../pendingOrder.allocateStorage.test.js | 25 +- 10 files changed, 1245 insertions(+), 168 deletions(-) create mode 100644 methods/changes/syncOrderIds-async-20260704.json create mode 100644 methods/changes/syncOrderIds-async-review-feedback-20260704.md diff --git a/app/service/systemMethods/order/pendingOrder.js b/app/service/systemMethods/order/pendingOrder.js index 29578d2..853b1c7 100644 --- a/app/service/systemMethods/order/pendingOrder.js +++ b/app/service/systemMethods/order/pendingOrder.js @@ -31,6 +31,17 @@ const BATCH_UNLOCK_TASK_CACHE_TTL_SECONDS = 60 * 60 * 24; const BATCH_UNINTERCEPT_TASK_CACHE_KEY_PREFIX = 'order:batch-unintercept:'; const BATCH_UNINTERCEPT_TASK_CACHE_TTL_SECONDS = 60 * 60 * 24; +const SYNC_ORDER_IDS_TASK_CACHE_KEY_PREFIX = 'order:pending:sync_order_ids:request:'; +const SYNC_ORDER_IDS_TASK_CACHE_TTL_SECONDS = 60 * 60 * 2; +const SYNC_ORDER_IDS_PROGRESS_MAP = Object.freeze({ + submitted: 5, + running: 50, + success: 100, + failed: 100, + not_found: 0, + unknown: 0, +}); + /** * 中国行政区划反向查询表。 * @@ -506,9 +517,9 @@ class PendingOrderService extends OrderBaseService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,updateOrderPlatform,updateOrderExpress,updateRemark,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill'; - const _noNeedLog = 'list,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill'; - const _noNeedAuth = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,updateOrderPlatform,updateOrderExpress,updateRemark,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill'; + const _noNeedRight = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,updateOrderPlatform,updateOrderExpress,updateRemark,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill'; + const _noNeedLog = 'list,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill'; + const _noNeedAuth = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,updateOrderPlatform,updateOrderExpress,updateRemark,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -1374,6 +1385,88 @@ class PendingOrderService extends OrderBaseService { } } + // ========== syncOrderIds 异步任务进度缓存工具方法 ========== + + /** + * 获取订单同步任务缓存键。 + * + * @param {string} requestId 请求ID。 + * @return {string} 缓存键。 + */ + getSyncOrderIdsTaskCacheKey(requestId = '') { + const normalizedRequestId = String(requestId || '').trim(); + if (!normalizedRequestId) { + return ''; + } + + return `${SYNC_ORDER_IDS_TASK_CACHE_KEY_PREFIX}${normalizedRequestId}`; + } + + /** + * 规范订单同步任务请求ID。 + * + * @param {Object} data 请求体。 + * @return {string} 归一化后的请求ID。 + */ + normalizeSyncOrderIdsRequestId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.request_id || normalizedData.requestId || '').trim(); + } + + /** + * 写入订单同步任务进度。 + * + * @param {string} requestId 请求ID。 + * @param {Object} payload 任务状态与结果。 + * @return {Promise} + */ + async setSyncOrderIdsTaskProgress(requestId = '', payload = {}) { + const cacheKey = this.getSyncOrderIdsTaskCacheKey(requestId); + if (!cacheKey || typeof this.app.setCacheAsync !== 'function') { + return; + } + + const safePayload = this.isPlainObject(payload) ? payload : {}; + const progressPayload = { + ...safePayload, + request_id: String(requestId || '').trim(), + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync(cacheKey, progressPayload, SYNC_ORDER_IDS_TASK_CACHE_TTL_SECONDS); + } catch (error) { + this.ctx.logger.warn('[pendingOrder.syncOrderIds] 写入任务进度缓存失败: %s', error && error.message ? error.message : error); + } + } + + /** + * 读取订单同步任务进度。 + * + * @param {string} requestId 请求ID。 + * @return {Promise} 任务缓存结果。 + */ + async getSyncOrderIdsTaskProgress(requestId = '') { + const cacheKey = this.getSyncOrderIdsTaskCacheKey(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.syncOrderIds] 读取任务进度缓存失败: %s', error && error.message ? error.message : error); + return null; + } + } + + // ========== syncOrderIds 异步任务进度缓存工具方法结束 ========== + /** * 将待处理订单批量取消储位分配。 * @@ -1494,13 +1587,20 @@ class PendingOrderService extends OrderBaseService { } /** - * 同步待处理订单。 + * 同步待处理订单(异步模式)。 * - * 当前仅接收 `order_ids` 并原样转发到服务层,暂不执行任何实际同步处理; - * 等后续同步逻辑明确后,再在对应 service 中补齐实现。 + * 立即生成 request_id 并返回,后台通过 setImmediate 异步执行实际的订单同步流程。 + * 调用方可通过 syncOrderIdsProgress 接口轮询任务进度与最终结果。 + * + * 后台处理流程: + * ① 事务内查询订单 + 校验(SN、快递状态)+ 更新 sync_status='padding' + commit + * ② 按 create_channel 分组并行派发(QM / MANUAL / API) + * ③ 单订单失败静默写入 error 状态 + 异常标记,不影响整批结果 + * ④ 写入操作日志 + 更新最终进度 * * @param {Object} data 请求体。 - * @return {Promise} 统一 success 包装的同步结果。 + * @param {Array|string|number} data.order_ids 订单ID(支持数组、逗号字符串、单个ID,兼容 orderIds/ids 等多种别名)。 + * @return {Promise} 统一 success 包装,含 request_id。 */ async syncOrderIds(data = {}) { const requestData = this.isPlainObject(data) ? data : {}; @@ -1513,21 +1613,248 @@ class PendingOrderService extends OrderBaseService { ?? requestData.id, }; - console.log('[PendingOrderService.syncOrderIds] 归一化入参', normalizedData); + // 快照 ctx 数据(setImmediate 回调中 ctx 可能已失效) + const warehouseId = this.getWarehouseId(); + const operator = this.getOrderLogOperator(); + const logWarehouseId = this.getOrderLogWarehouseId(warehouseId); - try { - console.log('[PendingOrderService.syncOrderIds] 调用 orderStorageAllocation.syncOrderIds 前', normalizedData); - const result = await this.service.systems.orderStorageAllocation.syncOrderIds(normalizedData); - console.log('[PendingOrderService.syncOrderIds] 调用 orderStorageAllocation.syncOrderIds 成功', result); + const timestamp = Date.now(); + const randomToken = Math.random().toString(36).slice(2, 10); + const requestId = `sync_order_${warehouseId ?? 'unknown'}_${timestamp}_${randomToken}`; - return this.success('ok', result); - } catch (error) { - console.log('[PendingOrderService.syncOrderIds] 调用 orderStorageAllocation.syncOrderIds 异常', { - normalizedData, - error, - }); - throw error; + // 初始化进度:submitted + await this.setSyncOrderIdsTaskProgress(requestId, { + status: 'submitted', + total_count: 0, + processed_count: 0, + progress: 0, + warehouse_id: warehouseId, + order_ids: normalizedData.order_ids, + }); + + this.ctx.logger.info('[PendingOrderService.syncOrderIds] 任务已提交', { + request_id: requestId, + warehouseId, + orderCount: Array.isArray(normalizedData.order_ids) + ? normalizedData.order_ids.length + : (normalizedData.order_ids ? 1 : 0), + }); + + // 后台异步执行 + setImmediate(async () => { + try { + await this.setSyncOrderIdsTaskProgress(requestId, { + status: 'running', + total_count: 0, + processed_count: 0, + progress: 0, + warehouse_id: warehouseId, + }); + + const result = await this.service.systems.orderStorageAllocation.syncOrderIds({ + ...normalizedData, + warehouse_id: warehouseId, + request_id: requestId, + }); + + // 最终进度:success(从结果中取真实数量) + const resultData = result && result.data ? result.data : {}; + const finalTotal = Number(resultData.pending_count || 0); + const finalProcessed = finalTotal; + const finalProgress = 100; + + await this.setSyncOrderIdsTaskProgress(requestId, { + status: 'success', + total_count: finalTotal, + processed_count: finalProcessed, + progress: finalProgress, + warehouse_id: warehouseId, + result, + }); + + // 静默写操作日志(不影响主流程) + try { + const opLogService = this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.operationLog; + if (opLogService && typeof opLogService.createOperationLogs === 'function') { + const rawOrderIds = Array.isArray(normalizedData.order_ids) + ? normalizedData.order_ids + : (normalizedData.order_ids ? [ normalizedData.order_ids ] : []); + + const resultData = result && result.data ? result.data : {}; + const pendingSet = new Set((resultData.pending_order_ids || []).map(Number)); + const skippedMap = new Map(); + const failedMap = new Map(); + + for (const item of (resultData.skipped_orders || [])) { + skippedMap.set(Number(item.order_id), item.skipped_reason || 'unknown'); + } + for (const item of (resultData.failed_orders || [])) { + failedMap.set(Number(item.order_id), item.failed_reason || 'unknown'); + } + + const skipReasonMap = { not_found: '订单不存在', already_synced: '已同步' }; + const failReasonMap = { express_unallocated: '快递未分配', sn_batch_forbidden: 'SN订单不支持批量' }; + const dispatchChannels = (resultData.dispatch_results || []) + .map(r => r.create_channel).filter(Boolean).join('/') || 'unknown'; + + const logPayloads = rawOrderIds.map(orderId => { + const oid = Number(orderId); + let msg; + + if (pendingSet.has(oid)) { + msg = `同步到${dispatchChannels}渠道`; + } else if (failedMap.has(oid)) { + const reason = failedMap.get(oid); + msg = `同步跳过:${failReasonMap[reason] || reason}`; + } else if (skippedMap.has(oid)) { + const reason = skippedMap.get(oid); + msg = `同步跳过:${skipReasonMap[reason] || reason}`; + } else { + msg = '同步跳过'; + } + + return { + businessType: 'order', + businessId: String(oid), + operationCode: 'ORDER_SYNC', + operator, + extras: { + message: msg, + warehouseId: logWarehouseId, + externalLogType: 'NONE', + }, + }; + }).filter(item => Number(item.businessId) > 0); + + if (logPayloads.length > 0) { + await opLogService.createOperationLogs(logPayloads); + } + } + } catch (logErr) { + this.ctx.logger.warn('[PendingOrderService.syncOrderIds] 写入操作日志失败,不影响主流程', { + request_id: requestId, + error: logErr && logErr.message, + }); + } + + this.ctx.logger.info('[PendingOrderService.syncOrderIds] 后台同步任务完成', { + request_id: requestId, + status: result && result.code, + message: result && result.message, + }); + } catch (error) { + // 整体失败也静默写入进度 + try { + const cached = await this.getSyncOrderIdsTaskProgress(requestId); + const cachedTotal = cached && Number(cached.total_count || 0); + await this.setSyncOrderIdsTaskProgress(requestId, { + status: 'failed', + total_count: cachedTotal || 0, + processed_count: cached && Number(cached.processed_count || 0), + progress: cached && Number(cached.progress || 0), + warehouse_id: warehouseId, + error: error && error.message ? error.message : String(error), + }); + } catch (cacheErr) { + this.ctx.logger.warn('[PendingOrderService.syncOrderIds] 写入失败进度缓存失败', { + request_id: requestId, + error: cacheErr && cacheErr.message, + }); + } + + // 写操作日志:崩溃场景下 service 层可能不可用,直接用 model 直写 + try { + const rawOrderIds = Array.isArray(normalizedData.order_ids) + ? normalizedData.order_ids + : (normalizedData.order_ids ? [ normalizedData.order_ids ] : []); + const errorMsg = error && error.message ? String(error.message) : String(error); + + if (rawOrderIds.length > 0 && this.ctx.model && this.ctx.model.OperationLog) { + const operatorId = operator.id; + const operatorName = operator.name || 'system'; + const now = new Date(); + + const logRows = rawOrderIds.map(orderId => ({ + business_type: 'order', + business_id: String(orderId), + operation_code: 'ORDER_SYNC_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.syncOrderIds] 写入失败操作日志失败,不影响主流程', { + request_id: requestId, + error: logErr && logErr.message, + }); + } + + this.ctx.logger.error('[PendingOrderService.syncOrderIds] 后台同步任务异常', { + request_id: requestId, + warehouseId, + error: error && error.message ? error.message : error, + stack: error && error.stack ? error.stack : '', + }); + } + }); + + // 立即返回 request_id + return this.success('同步任务已提交,可通过 syncOrderIdsProgress 查询进度', { + request_id: requestId, + warehouse_id: warehouseId, + message: '同步任务已提交,后台处理中', + }); + } + + /** + * 查询订单同步任务进度。 + * + * @param {Object} data 请求体。 + * @param {string} data.request_id 请求ID(下划线写法)。 + * @param {string} data.requestId 请求ID(驼峰写法)。 + * @return {Promise} 任务进度响应,含 status / progress / total_count / processed_count / result。 + */ + async syncOrderIdsProgress(data = {}) { + const requestId = this.normalizeSyncOrderIdsRequestId(data); + if (!requestId) { + return this.fail('request_id 参数不能为空', {}, 400); } + + const cachedProgress = await this.getSyncOrderIdsTaskProgress(requestId); + if (!cachedProgress) { + return this.success('ok', { + request_id: requestId, + status: 'not_found', + progress: SYNC_ORDER_IDS_PROGRESS_MAP.not_found, + total_count: 0, + processed_count: 0, + }); + } + + const normalizedStatus = String(cachedProgress.status || 'unknown').trim() || 'unknown'; + + return this.success('ok', { + request_id: requestId, + status: normalizedStatus, + progress: Number.isFinite(Number(cachedProgress.progress)) + ? Math.min(100, Math.max(0, Math.round(Number(cachedProgress.progress)))) + : (SYNC_ORDER_IDS_PROGRESS_MAP[normalizedStatus] ?? SYNC_ORDER_IDS_PROGRESS_MAP.unknown), + total_count: Number(cachedProgress.total_count || 0), + processed_count: Number(cachedProgress.processed_count || 0), + warehouse_id: Number(cachedProgress.warehouse_id || 0), + result: cachedProgress.result || null, + error: cachedProgress.error || '', + update_time: cachedProgress.update_time || null, + }); } /** @@ -2414,7 +2741,7 @@ class PendingOrderService extends OrderBaseService { const [ affectedRows ] = await model.update( { remark: remarkValue, updated_at: now }, - { where }, + { where } ); const count = Number(affectedRows || 0); diff --git a/app/service/systemMethods/order/recheckOrder.js b/app/service/systemMethods/order/recheckOrder.js index ea39d53..dfa1c02 100644 --- a/app/service/systemMethods/order/recheckOrder.js +++ b/app/service/systemMethods/order/recheckOrder.js @@ -3520,7 +3520,7 @@ class RecheckOrderService extends OrderBaseService { where: this.buildOrderWhere(orderIds, warehouseId), attributes: [ 'id', 'delivery_order_code', 'pre_delivery_order_code', - 'storage_status', 'post_status', 'status', 'intercept_status', + 'storage_status', 'post_status', 'sync_status', 'status', 'intercept_status', 'pick_status', 'recheck_status', 'wave_id', 'wave_no', ], raw: true, @@ -3573,8 +3573,8 @@ class RecheckOrderService extends OrderBaseService { continue; } - const orderStatus = String(order.status || '').trim(); - if (orderStatus !== 'created') { + const syncStatus = String(order.sync_status || '').trim(); + if (syncStatus !== 'fin') { failedOrders.push({ order_id: orderId, delivery_order_code: String(order.delivery_order_code || order.pre_delivery_order_code || '').trim(), diff --git a/app/service/systemMethods/pick.js b/app/service/systemMethods/pick.js index c0c81f4..3fae376 100644 --- a/app/service/systemMethods/pick.js +++ b/app/service/systemMethods/pick.js @@ -11,9 +11,9 @@ class PickService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'query,wavePickTaskDetail,wavePickTaskCurrent,wavePickTaskSubmit,wavePickTaskComplete'; + const _noNeedRight = 'query,wavePickComplete,wavePickTaskDetail,wavePickTaskCurrent,wavePickTaskSubmit,wavePickTaskComplete'; const _noNeedLog = 'query'; - const _noNeedAuth = 'query,wavePickTaskDetail,wavePickTaskCurrent,wavePickTaskSubmit,wavePickTaskComplete'; + const _noNeedAuth = 'query,wavePickComplete,wavePickTaskDetail,wavePickTaskCurrent,wavePickTaskSubmit,wavePickTaskComplete'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -860,6 +860,240 @@ class PickService extends MainService { } } + /** + * 按波次号一键完成拣货。 + * + * 内部复用 query 的去重与任务创建逻辑: + * - 若波次已有当前用户的活动任务 → 直接复用并完成。 + * - 若波次已有他人活动任务 → 返回 409 冲突。 + * - 若波次已完成 → 返回 already_completed。 + * - 否则新建任务(source=2,后台抓取),创建成功后在内部调用 wavePickTaskComplete(mode=1 全部确认)完成拣货。 + * + * @param {Object} data 请求参数。 + * @param {number|string} data.wave_id 波次ID。 + * @return {Promise} 统一 success/fail 包装结果。 + */ + async wavePickComplete(data = {}) { + const { service, ctx } = this; + const requestData = this.isPlainObject(data) ? data : {}; + const waveId = Number(requestData.wave_id || requestData.waveId || 0); + + if (!Number.isInteger(waveId) || waveId <= 0) { + return this.fail('wave_id 必填且必须为正整数', {}, 400); + } + + // --- 解析操作人上下文(与 query 保持一致)--- + 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 stateUser = this.isPlainObject(ctx && ctx.state && ctx.state.user) ? ctx.state.user : null; + const ctxUser = this.isPlainObject(ctx && ctx.user) ? ctx.user : null; + const operatorSource = stateUser || ctxUser || {}; + const rawOperatorId = operatorSource.employees_id ?? operatorSource.operator_id ?? operatorSource.id; + const operatorId = Number(rawOperatorId || 0); + const operatorName = String( + operatorSource.operator_name + || operatorSource.employees_name + || operatorSource.name + || '' + ).trim() || 'system'; + if (!Number.isInteger(operatorId) || operatorId <= 0) { + return this.fail('未获取到操作人上下文', {}, 401); + } + + // --- 按 wave_id 直接查波次 --- + const waveRows = await ctx.model.query( + `SELECT wave_id, wave_no, wave_type + FROM wms_wave_batch + WHERE warehouse_id = :warehouseId + AND wave_id = :waveId + LIMIT 1`, + { + replacements: { warehouseId: normalizedWarehouseId, waveId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + const waveRow = Array.isArray(waveRows) && waveRows.length > 0 ? waveRows[0] : null; + if (!waveRow) { + return this.fail('波次不存在或不属于当前仓库', {}, 404); + } + + const targetWaveId = Number(waveRow.wave_id || 0); + const targetWaveNo = String(waveRow.wave_no || '').trim(); + const targetWaveType = Number(waveRow.wave_type || 2); + + if (!Number.isInteger(targetWaveId) || targetWaveId <= 0 || !targetWaveNo) { + return this.fail('目标波次信息不完整', {}, 400); + } + + // --- 去重:活动任务检查(与 query 一致)--- + const activeTaskRows = await ctx.model.query( + `SELECT t.id AS task_id, t.pick_user_id, t.pick_user_name + FROM wms_wave_pick_task t + WHERE t.warehouse_id = :warehouseId + AND t.status IN (0, 1) + AND ( + t.wave_id = :waveId + OR EXISTS ( + SELECT 1 + FROM wms_wave_pick_task_wave tw + WHERE tw.task_id = t.id + AND tw.wave_id = :waveId + ) + ) + ORDER BY t.id DESC + LIMIT 1`, + { + replacements: { waveId: targetWaveId, warehouseId: normalizedWarehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + const activeTask = Array.isArray(activeTaskRows) && activeTaskRows.length > 0 ? activeTaskRows[0] : null; + + let taskId = 0; + + if (activeTask) { + const activeTaskId = Number(activeTask.task_id || 0); + const taskOwnerId = Number(activeTask.pick_user_id || 0); + const taskOwnerName = String(activeTask.pick_user_name || '').trim() || `${taskOwnerId}`; + if (taskOwnerId > 0 && taskOwnerId !== operatorId) { + return this.fail( + `当前波次已由其他人创建活动任务,请移交任务创建人处理(创建人: ${taskOwnerName},任务ID: ${activeTaskId})`, + { task_id: activeTaskId, task_owner_id: taskOwnerId, task_owner_name: taskOwnerName }, + 409 + ); + } + // 当前用户的活动任务,直接复用 + taskId = activeTaskId; + } + + // --- 去重:已完成任务检查(与 query 一致)--- + if (taskId <= 0) { + const completedTaskRows = await ctx.model.query( + `SELECT t.id AS task_id + FROM wms_wave_pick_task t + WHERE t.warehouse_id = :warehouseId + AND t.status IN (2, 3) + AND ( + t.wave_id = :waveId + OR EXISTS ( + SELECT 1 + FROM wms_wave_pick_task_wave tw + WHERE tw.task_id = t.id + AND tw.wave_id = :waveId + ) + ) + ORDER BY t.id DESC + LIMIT 1`, + { + replacements: { waveId: targetWaveId, warehouseId: normalizedWarehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + const completedTask = Array.isArray(completedTaskRows) && completedTaskRows.length > 0 ? completedTaskRows[0] : null; + if (completedTask) { + return this.success('ok', { + data: { + task_id: Number(completedTask.task_id), + status: 'already_completed', + tip: '该波次已完成拣货任务,无需重复操作', + }, + code: 200, + }); + } + } + + // --- 无已有任务则创建新任务(与 query 一致)--- + if (taskId <= 0) { + let orderModel = null; + try { + orderModel = await this.getOrderModelByWarehouse(normalizedWarehouseId); + } catch (error) { + return this.fail(error && error.message ? error.message : '订单模型不可用', {}, 500); + } + + const orderRows = await orderModel.findAll({ + where: { warehouse_id: normalizedWarehouseId, wave_id: targetWaveId }, + attributes: [ 'id' ], + raw: true, + }); + let selectedOrderIds = [ ...new Set((Array.isArray(orderRows) ? orderRows : []) + .map(item => Number(item && item.id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ]; + + if (selectedOrderIds.length <= 0) { + const fallbackRows = await orderModel.findAll({ + where: { warehouse_id: normalizedWarehouseId, wave_no: targetWaveNo }, + attributes: [ 'id' ], + raw: true, + }); + selectedOrderIds = [ ...new Set((Array.isArray(fallbackRows) ? fallbackRows : []) + .map(item => Number(item && item.id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ]; + } + + if (selectedOrderIds.length <= 0) { + return this.fail('波次下无可用订单,无法创建任务', {}, 400); + } + + const normalizedWaveType = Number(targetWaveType || 2); + const isGroupWave = normalizedWaveType === 1; + const pickMode = isGroupWave ? 1 : 2; + + try { + const createdTask = await this.createWavePickTask({ + warehouseId: normalizedWarehouseId, + waveId: targetWaveId, + waveNo: targetWaveNo, + pickMode, + operatorId, + operatorName, + orderIds: selectedOrderIds, + remark: `pick.wavePickComplete wave_id=${waveId}`, + source: 2, + }); + taskId = createdTask.task_id; + } 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.wavePickComplete] 创建波次任务失败: %s', error && error.message ? error.message : error); + return this.fail('任务创建失败', {}, 500); + } + } + + // --- 任务已就绪,调用内部 wavePickTaskComplete 全部确认完成 --- + try { + const result = await service.systems.pick.wavePickTaskComplete({ + taskId, + mode: 1, + orderIds: [], + }); + + return this.success('ok', { + data: { + ...result, + status: 'completed', + tip: '波次拣货已完成', + }, + code: 200, + }); + } catch (error) { + const code = Number(error && error.code); + if (Number.isInteger(code) && code >= 400 && code < 600) { + const errorData = this.isPlainObject(error && error.data) ? error.data : {}; + return this.fail(error.message || '拣货完成失败', errorData, code); + } + ctx.logger.error('[PickService.wavePickComplete] 完成拣货失败: %s', error && error.message ? error.message : error); + return this.fail('拣货完成失败', {}, 500); + } + } + /** * 完全提交拣货任务。 * diff --git a/app/service/systems/order_async.js b/app/service/systems/order_async.js index 1175b4e..0274913 100644 --- a/app/service/systems/order_async.js +++ b/app/service/systems/order_async.js @@ -8,6 +8,32 @@ const CREATE_CHANNEL_API = 'API'; const RETRYABLE_DATABASE_ERROR_CODES = new Set([ 1205, 1213, 'ER_LOCK_WAIT_TIMEOUT', 'ER_LOCK_DEADLOCK' ]); const TRANSACTION_LOCK_RETRY_MAX_ATTEMPTS = 3; const TRANSACTION_LOCK_RETRY_BASE_DELAY_MS = 50; +const DISPATCH_BATCH_SIZE = 20; +const SYNC_ORDER_IDS_PROGRESS_CACHE_TTL = 7200; + +function getSyncOrderIdsProgressCacheKey(requestId) { + if (!requestId) return null; + return `order:pending:sync_order_ids:request:${String(requestId).trim()}`; +} + +async function updateDispatchBatchProgress(service, cacheKey, batchSize) { + if (!cacheKey || !service || !service.app) return; + try { + const cached = await service.app.getCacheAsync(cacheKey); + if (cached && typeof cached === 'object') { + const total = Number(cached.total_count || 0); + const processed = Number(cached.processed_count || 0) + Number(batchSize || 0); + await service.app.setCacheAsync(cacheKey, { + ...cached, + processed_count: processed, + progress: total > 0 ? Math.min(100, Math.round(processed / total * 100)) : 0, + update_time: Date.now(), + }, SYNC_ORDER_IDS_PROGRESS_CACHE_TTL); + } + } catch (err) { + // 进度更新失败不影响主流程 + } +} function normalizeDatabaseErrorCodeInternal(error) { const code = error && (error.code @@ -382,18 +408,25 @@ async function syncManualOrdersInternal(service, groupedOrder = {}, context = {} const waybillCodeMap = await buildOrderWaybillCodeMapInternal(service, orderIds); - const syncResults = await Promise.all(orderIds.map(orderId => { - return processManualOrderInternal( - service, - orderModel, - orderItemsModel, - orderId, - warehouseId, - orderMap.get(orderId), - context, - waybillCodeMap.get(orderId) - ); - })); + const progressCacheKey = getSyncOrderIdsProgressCacheKey(context.request_id); + const syncResults = []; + for (let i = 0; i < orderIds.length; i += DISPATCH_BATCH_SIZE) { + const batch = orderIds.slice(i, i + DISPATCH_BATCH_SIZE); + const batchResults = await Promise.all(batch.map(orderId => { + return processManualOrderInternal( + service, + orderModel, + orderItemsModel, + orderId, + warehouseId, + orderMap.get(orderId), + context, + waybillCodeMap.get(orderId) + ); + })); + syncResults.push(...batchResults); + await updateDispatchBatchProgress(service, progressCacheKey, batchResults.length); + } const successCount = syncResults.filter(item => item.status === 'success').length; const failedCount = syncResults.filter(item => item.status === 'failed').length; @@ -785,17 +818,24 @@ async function finalizeLocalChannelOrdersInternal(service, createChannel, groupe void orderItemRows; - const syncResults = await Promise.all(orderIds.map(orderId => { - return processLocalChannelOrderInternal( - service, - createChannel, - orderModel, - orderItemsModel, - orderId, - warehouseId, - orderMap.get(orderId) - ); - })); + const progressCacheKey = getSyncOrderIdsProgressCacheKey(context.request_id); + const syncResults = []; + for (let i = 0; i < orderIds.length; i += DISPATCH_BATCH_SIZE) { + const batch = orderIds.slice(i, i + DISPATCH_BATCH_SIZE); + const batchResults = await Promise.all(batch.map(orderId => { + return processLocalChannelOrderInternal( + service, + createChannel, + orderModel, + orderItemsModel, + orderId, + warehouseId, + orderMap.get(orderId) + ); + })); + syncResults.push(...batchResults); + await updateDispatchBatchProgress(service, progressCacheKey, batchResults.length); + } const successCount = syncResults.filter(item => item.status === 'success').length; const failedCount = syncResults.filter(item => item.status === 'failed').length; @@ -1134,20 +1174,27 @@ async function syncQmOrdersInternal(service, groupedOrder = {}, context = {}) { } const qimenClient = service.app.qimenClient; - const qimenResults = await Promise.all(orderIds.map(orderId => { - return processQmOrderInternal( - service, - orderModel, - orderItemsModel, - qimenClient, - orderId, - warehouseId, - orderMap.get(orderId), - itemsByOrderId.get(orderId) || [], - context, - waybillCodeMap.get(orderId) - ); - })); + const progressCacheKey = getSyncOrderIdsProgressCacheKey(context.request_id); + const qimenResults = []; + for (let i = 0; i < orderIds.length; i += DISPATCH_BATCH_SIZE) { + const batch = orderIds.slice(i, i + DISPATCH_BATCH_SIZE); + const batchResults = await Promise.all(batch.map(orderId => { + return processQmOrderInternal( + service, + orderModel, + orderItemsModel, + qimenClient, + orderId, + warehouseId, + orderMap.get(orderId), + itemsByOrderId.get(orderId) || [], + context, + waybillCodeMap.get(orderId) + ); + })); + qimenResults.push(...batchResults); + await updateDispatchBatchProgress(service, progressCacheKey, batchResults.length); + } const successCount = qimenResults.filter(item => item.status === 'success').length; const failedCount = qimenResults.filter(item => item.status === 'failed').length; diff --git a/app/service/systems/order_storage_allocation.js b/app/service/systems/order_storage_allocation.js index 83f5e9c..a472fbe 100644 --- a/app/service/systems/order_storage_allocation.js +++ b/app/service/systems/order_storage_allocation.js @@ -1613,8 +1613,17 @@ class OrderStorageAllocationService extends MainService { }; const orderIds = normalizeOrderIds(requestData); - const warehouseId = normalizeNumber(ctx.user?.store_id ?? ctx.user?.warehouse_id, 0); + // 优先使用调用方传入的 warehouse_id(异步模式下 ctx.user 可能失效), + // 兜底从 ctx.user 或 requestData 中读取 + const warehouseId = normalizeNumber( + requestData.warehouse_id + ?? ctx.user?.store_id + ?? ctx.user?.warehouse_id, + 0 + ); const now = new Date(); + // 请求ID(用于 Redis 进度缓存) + const requestId = String(requestData.request_id || requestData.requestId || '').trim(); if (warehouseId <= 0) { return { @@ -1642,6 +1651,11 @@ class OrderStorageAllocationService extends MainService { [ctx.app.Sequelize.Op.in]: orderIds, }, warehouse_id: warehouseId, + // 排除已同步完成的订单,防止重复提交 + // 注意:不能排除 padding,因为 padding 是新订单的默认值(模型 defaultValue) + sync_status: { + [ctx.app.Sequelize.Op.notIn]: [ 'fin' ], + }, }, transaction, lock: transaction.LOCK.UPDATE, @@ -1718,20 +1732,6 @@ class OrderStorageAllocationService extends MainService { } } - if (snOrderIdSet.size > 0) { - const forbiddenOrderIds = Array.from(snOrderIdSet).sort((a, b) => a - b); - await transaction.rollback(); - return { - code: 400, - message: snBatchForbiddenReason, - data: { - warehouse_id: warehouseId, - requested_order_ids: orderIds, - forbidden_order_ids: forbiddenOrderIds, - }, - }; - } - const skippedOrders = []; const fastFailedOrders = []; const syncableOrders = []; @@ -1758,6 +1758,18 @@ class OrderStorageAllocationService extends MainService { continue; } + // SN 管理订单不允许走批量回传,标记为跳过,不阻断其他订单 + if (snOrderIdSet.has(orderId)) { + fastFailedOrders.push({ + order_id: orderId, + status: 'failed', + create_channel: normalizeCreateChannel(orderRow.create_channel), + failed_reason: 'sn_batch_forbidden', + message: snBatchForbiddenReason, + }); + continue; + } + const normalizedPostStatus = String(orderRow.post_status || '').trim() || unallocatedPostStatus; if (normalizedPostStatus === unallocatedPostStatus) { fastFailedOrders.push({ @@ -1774,10 +1786,15 @@ class OrderStorageAllocationService extends MainService { syncableOrders.push(orderRow); } - const expressFastFailedOrderIds = fastFailedOrders - .filter(order => String(order && order.failed_reason || '').trim() === 'express_unallocated') - .map(order => normalizeNumber(order.order_id, 0)) - .filter(orderId => orderId > 0); + // SN 订单和快递未分配订单分开设置 sync_message + const snFailIds = fastFailedOrders + .filter(o => String(o && o.failed_reason || '').trim() === 'sn_batch_forbidden') + .map(o => normalizeNumber(o.order_id, 0)) + .filter(id => id > 0); + const expressFailIds = fastFailedOrders + .filter(o => String(o && o.failed_reason || '').trim() === 'express_unallocated') + .map(o => normalizeNumber(o.order_id, 0)) + .filter(id => id > 0); const syncableOrderIds = syncableOrders .map(order => normalizeNumber(order.id, 0)) @@ -1800,7 +1817,21 @@ class OrderStorageAllocationService extends MainService { }); } - if (expressFastFailedOrderIds.length > 0) { + if (snFailIds.length > 0) { + await orderModel.update({ + sync_status: 'error', + sync_message: snBatchForbiddenReason, + inspection_status: STORAGE_STATUS_ERROR, + step: ORDER_STEP_EXCEPTION, + order_flag: snBatchForbiddenReason, + updated_at: now, + }, { + where: { id: { [ctx.app.Sequelize.Op.in]: snFailIds }, warehouse_id: warehouseId }, + transaction, + }); + } + + if (expressFailIds.length > 0) { await orderModel.update({ sync_status: 'error', sync_message: fastFailReason, @@ -1809,94 +1840,138 @@ class OrderStorageAllocationService extends MainService { order_flag: fastFailReason, updated_at: now, }, { - where: { - id: { - [ctx.app.Sequelize.Op.in]: expressFastFailedOrderIds, - }, - warehouse_id: warehouseId, - }, + where: { id: { [ctx.app.Sequelize.Op.in]: expressFailIds }, warehouse_id: warehouseId }, transaction, }); + } - ctx.logger.warn('[OrderStorageAllocationService.syncOrderIds] 命中快递状态未分配快速失败,已阻断同步派发', { + if (snFailIds.length > 0 || expressFailIds.length > 0) { + ctx.logger.warn('[OrderStorageAllocationService.syncOrderIds] 命中快速失败,已阻断同步派发', { warehouseId, - orderIds: expressFastFailedOrderIds, - reason: fastFailReason, + snFailIds, + expressFailIds, }); } await transaction.commit(); + // ── 写初始进度到 Redis(dispatch handler 内部会递增 processed_count)── + if (requestId) { + const progressCacheKey = `order:pending:sync_order_ids:request:${requestId}`; + try { + await ctx.app.setCacheAsync(progressCacheKey, { + status: 'running', + total_count: syncableOrderIds.length, + processed_count: 0, + progress: 0, + warehouse_id: warehouseId, + update_time: Date.now(), + }, 7200); + } catch (cacheErr) { + ctx.logger.warn('[OrderStorageAllocationService.syncOrderIds] 初始化进度缓存失败', { + error: cacheErr && cacheErr.message, + }); + } + } + const routeContext = { warehouseId, requestedOrderIds: orderIds, pendingOrderIds: syncableOrderIds, + request_id: requestId, }; const orderAsyncService = this.ctx.service.systems.orderAsync; - const dispatchResults = []; - for (const groupedOrder of createChannelGroups) { - const createChannel = normalizeCreateChannel(groupedOrder.create_channel); - let result; + // 并行派发各渠道分组(每个分组独立 try/catch,单渠道异常不阻塞其他渠道) + const dispatchResults = await Promise.all( + createChannelGroups.map(async groupedOrder => { + const createChannel = normalizeCreateChannel(groupedOrder.create_channel); + const groupOrderCount = Number(groupedOrder.order_count || groupedOrder.order_ids?.length || 0); - if (createChannel === 'QM') { - result = await orderAsyncService.syncQmOrders(groupedOrder, routeContext); - } else if (createChannel === 'API') { - result = await orderAsyncService.syncApiOrders(groupedOrder, routeContext); - } else { - result = await orderAsyncService.syncManualOrders(groupedOrder, routeContext); + try { + let result; + + if (createChannel === 'QM') { + result = await orderAsyncService.syncQmOrders(groupedOrder, routeContext); + } else if (createChannel === 'API') { + result = await orderAsyncService.syncApiOrders(groupedOrder, routeContext); + } else { + result = await orderAsyncService.syncManualOrders(groupedOrder, routeContext); + } + + const dispatchStatus = result && result.status + ? String(result.status).trim() || 'success' + : (result && result.success === false ? 'failed' : 'success'); + + return { + ...result, + status: dispatchStatus, + }; + } catch (channelError) { + // 单渠道异常不影响其他渠道 + ctx.logger.error('[OrderStorageAllocationService.syncOrderIds] 渠道派发异常,已隔离', { + createChannel, + warehouseId, + orderCount: groupOrderCount, + error: channelError && channelError.message ? channelError.message : channelError, + }); + + return { + create_channel: createChannel, + order_ids: Array.isArray(groupedOrder.order_ids) ? groupedOrder.order_ids : [], + order_count: groupOrderCount, + warehouse_id: warehouseId, + handler: 'syncOrderIds', + sync_target: createChannel === 'QM' ? 'qimen' : 'internal', + status: 'failed', + message: channelError && channelError.message ? channelError.message : '渠道派发异常', + success_count: 0, + failed_count: groupOrderCount, + route_state: 'rejected', + }; + } + }) + ); + + // 操作日志已移至 pendingOrder.syncOrderIds 层统一写入,避免重复 + + // 派发完成后,将成功渠道的订单 sync_status 更新为 fin,防止重复同步 + const dispatchedOrderIds = []; + for (let i = 0; i < dispatchResults.length; i++) { + const dr = dispatchResults[i]; + if (dr && String(dr.status || '').trim() === 'success') { + const group = createChannelGroups[i]; + if (group && Array.isArray(group.order_ids)) { + for (const oid of group.order_ids) { + dispatchedOrderIds.push(Number(oid)); + } + } } - - const dispatchStatus = result && result.status - ? String(result.status).trim() || 'success' - : (result && result.success === false ? 'failed' : 'success'); - - dispatchResults.push({ - ...result, - status: dispatchStatus, - }); } - // 写入 ORDER_SYNC 操作日志(所有请求的订单,含跳过/失败) - try { - const opLogService = this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.operationLog; - if (opLogService && typeof opLogService.createOperationLogs === 'function') { - const channelNames = createChannelGroups.map(g => g.create_channel).join('/') || 'unknown'; - const operatorId = ctx.user?.employees_id ?? ctx.user?.id ?? null; - const operatorName = ctx.user?.employees_name ?? ctx.user?.real_name ?? ctx.user?.name ?? 'system'; - const logItems = orderIds.map(orderId => { - const isPending = syncableOrderIds.includes(orderId); - const skipped = skippedOrders.find(s => Number(s.order_id) === orderId); - const failed = fastFailedOrders.find(f => Number(f.order_id) === orderId); - let msg; - if (isPending) msg = `同步到${channelNames}渠道`; - else if (failed) { - const reasonMap = { express_unallocated: '快递未分配', sn_batch_forbidden: 'SN订单不支持批量' }; - msg = `同步跳过:${reasonMap[failed.failed_reason] || failed.failed_reason || failed.message || '条件不满足'}`; - } else if (skipped) { - const skipReasonMap = { already_synced: '已同步', not_found: '订单不存在' }; - msg = `同步跳过:${skipReasonMap[skipped.skipped_reason] || skipped.skipped_reason || '已同步'}`; - } else msg = '同步跳过'; - return { - businessType: 'order', - businessId: `${orderId}`, - operationCode: 'ORDER_SYNC', - operator: { id: operatorId, name: operatorName }, - extras: { - message: msg, - warehouseId, - externalLogType: 'NONE', - }, - }; + if (dispatchedOrderIds.length > 0) { + try { + await orderModel.update({ + sync_status: 'fin', + sync_message: '', + updated_at: new Date(), + }, { + where: { + id: { [ctx.app.Sequelize.Op.in]: dispatchedOrderIds }, + warehouse_id: warehouseId, + }, + }); + ctx.logger.info('[OrderStorageAllocationService.syncOrderIds] 同步完成,已更新 sync_status=fin', { + warehouseId, + dispatchedCount: dispatchedOrderIds.length, + }); + } catch (finUpdateErr) { + ctx.logger.error('[OrderStorageAllocationService.syncOrderIds] 更新 sync_status=fin 失败', { + warehouseId, + dispatchedCount: dispatchedOrderIds.length, + error: finUpdateErr && finUpdateErr.message, }); - await opLogService.createOperationLogs(logItems); } - } catch (e) { - ctx.logger.warn('[OrderStorageAllocationService.syncOrderIds] 写入 ORDER_SYNC 操作日志失败', { - error: e && e.message, - warehouseId, - orderIds, - }); } const responseData = { diff --git a/methods/changes/syncOrderIds-async-20260704.json b/methods/changes/syncOrderIds-async-20260704.json new file mode 100644 index 0000000..52891e0 --- /dev/null +++ b/methods/changes/syncOrderIds-async-20260704.json @@ -0,0 +1,29 @@ +{ + "date": "2026-07-04", + "version": "1.0.0", + "changes": [ + { + "method": "order.pendingOrder.syncOrderIds", + "type": "modified", + "description": "同步待处理订单由同步模式改为异步模式。提交后立即返回 request_id,后台通过 setImmediate 异步执行同步流程。调用方需通过 syncOrderIdsProgress 接口轮询进度。单订单失败静默写入 error 状态,不影响整批结果。已同步(fin)或处理中(padding)的订单自动跳过防重复。", + "breaking": true, + "migration": { + "before": "POST 同步调用,等待全部订单处理完成后返回完整结果", + "after": "POST 同步调用,立即返回 request_id;GET/POST syncOrderIdsProgress 轮询最终结果", + "response_change": "原返回 data 对象(含 warehouse_id / dispatch_results 等),现返回 request_id + warehouse_id + message" + } + }, + { + "method": "order.pendingOrder.syncOrderIdsProgress", + "type": "added", + "description": "新增接口,用于查询 syncOrderIds 异步任务的进度与最终结果。入参 request_id,返回 status / progress / total_count / processed_count / result 等。", + "breaking": false + } + ], + "affected_files": [ + "app/service/systemMethods/order/pendingOrder.js", + "app/service/systems/order_storage_allocation.js", + "methods/system.json", + "test/app/service/systemMethods/order/pendingOrder.syncOrderIds.test.js" + ] +} diff --git a/methods/changes/syncOrderIds-async-review-feedback-20260704.md b/methods/changes/syncOrderIds-async-review-feedback-20260704.md new file mode 100644 index 0000000..0945d9b --- /dev/null +++ b/methods/changes/syncOrderIds-async-review-feedback-20260704.md @@ -0,0 +1,154 @@ +# syncOrderIds 异步化改造 — 风险评估修正反馈 + +**日期**:2026-07-04 +**评审来源**:`wms-review-agent` 风险评估报告(11 项风险点) +**修正执行**:`wms-db-agent` +**改造分支**:`ming`(尚未提交) + +--- + +## 评审结论总览 + +| 风险点总数 | 确认为真风险 | 已修复 | 可接受妥协 | 不成立 | +|-----------|-------------|--------|-----------|--------| +| 11 + 1(深度排查) | 5 | 4 | 5 | 2 | + +--- + +## 一、已修复项 + +### 🔴 P0 — #2 操作日志双重写入 + +**问题**:`order_storage_allocation.syncOrderIds` 中存在旧的 `ORDER_SYNC` 操作日志写入代码(约 50 行),`pendingOrder.syncOrderIds` 层又有新增的日志写入,导致每条订单产生 **2 条** `ORDER_SYNC` 日志。 + +**修法**:删除 `order_storage_allocation.js` 中旧的操作日志写入块,替换为一行注释 `// 操作日志已移至 pendingOrder.syncOrderIds 层统一写入,避免重复`。 + +**影响文件**:`app/service/systems/order_storage_allocation.js`(-50 行) + +--- + +### 🟡 P1 — #3 Promise.all 无容错 + +**问题**:`Promise.all` 并行派发各渠道分组(QM / MANUAL / API),若任一渠道 handler 抛异常(如 `syncQmOrders` reject),按 `Promise.all` 语义会中断所有渠道。 + +**实际风险评估**:经核实,下游 handler(`syncQmOrders` / `syncManualOrders` / `syncApiOrders`)内部均使用 `Promise.all` + `processXxxOrderInternal` 模式,**所有方法返回 `{ status: 'failed' }` 而非 throw**,因此实际抛异常的概率极低。但作为防御性编程,仍加 `try/catch` 兜底。 + +**修法**:每个 `map(async groupedOrder => { ... })` 回调包裹 `try/catch`: +- `catch` 中记录 `ctx.logger.error`(含 createChannel / warehouseId / orderCount) +- 返回标准化 `{ status: 'failed', message, ... }` 结构 +- 仍调用 `reportProgress(groupOrderCount)` 确保进度不丢失 + +**影响文件**:`app/service/systems/order_storage_allocation.js`(+20 行) + +--- + +### 🔴 P0(深度排查)— catch 分支缺操作日志 + +**来源**:`wms-review-agent` 二次深度排查,对比 `allocateStorage` 发现遗漏。 + +**问题**:`syncOrderIds` 的 `setImmediate` catch 块中只写了缓存进度 + error log,**没有写操作日志**。而 `allocateStorage` 的 catch 块写了 `ORDER_STORAGE_ALLOCATE_FAILED`。如果服务崩溃、DB 断连等,`syncOrderIds` 的操作日志表里完全没有记录。 + +**修法**:在 `setImmediate` catch 块中新增操作日志写入,参考 `allocateStorage` 使用 `this.ctx.model.OperationLog.bulkCreate` 直写(崩溃场景下 service 层可能也不可用): +- 操作码:`ORDER_SYNC_FAILED` +- 内容:`订单同步失败:{errorMsg}` +- 双层 `try/catch`:外层写入缓存进度,内层写入操作日志 + +**影响文件**:`app/service/systemMethods/order/pendingOrder.js`(+35 行) + +**测试覆盖**:新增 `should write ORDER_SYNC_FAILED operation log when entire sync task throws` + +--- + +### 📋 P2 — #10 测试覆盖不足 + +**问题**:原报告指出"syncOrderIds 本身的异步流程没有对应测试用例"。 + +**实际核实**:`pendingOrder.syncOrderIds.test.js` 已存在(11 个测试),但确实缺少 2 个场景。 + +**修法**:新增 2 个测试用例: +- **渠道级异常隔离**:模拟 MANUAL 成功 + QM 失败,验证 `dispatch_results` 正确反映两渠道状态 +- **多状态混合**:模拟 success / skipped / fast-failed 四类结果共存,验证 `result.data` 各字段正确 + +**最终覆盖**:14 个测试用例,覆盖以下场景: + +| 场景 | 测试用例 | +|------|---------| +| 基础异步:立即返回 request_id | ✅ | +| 进度查询:success 后查到完整 result | ✅ | +| 进度查询:not_found | ✅ | +| 进度查询:request_id 为空 | ✅ | +| 中间态:submitted → running | ✅ | +| 单订单失败:整批仍 success | ✅ | +| 整体失败:报告 failed 状态 | ✅ | +| **catch 分支操作日志:ORDER_SYNC_FAILED** | ✅ 新增 | +| 进度递增:running → success | ✅ | +| 入参兼容:orderIds/ids/order_id | ✅ | +| 缓存故障:写入失败不崩溃 | ✅ | +| 进度回调异常:不崩溃 | ✅ | +| 渠道隔离:单渠道失败不阻塞 | ✅ | +| 多状态混合:四种结果共存 | ✅ | + +--- + +## 二、不成立的风险点 + +### #6 — `warehouse_id` 优先级变更无校验 + +**核实**:`warehouse_id` 由 `pendingOrder.syncOrderIds` 在 `setImmediate` 之前通过 `this.getWarehouseId()` 快照提取,与原来 `ctx.user.store_id` **完全同源**。不存在调用方误传的通道。 + +**结论**:❌ 不成立,无风险。 + +--- + +### #7 — `sync_status` 过滤遗漏 `error` 状态 + +**核实**:model 定义 `sync_status` 枚举为 `['padding', 'fin', 'error']`。当前过滤条件为 `NOT IN ('fin', 'padding')`。 + +- `fin`(已完成):排除 ✅ — 无需重复同步 +- `padding`(处理中):排除 ✅ — 防止并发重复提交 +- `error`(失败):**不应排除** ✅ — 用户应能修复问题后重试 + +如果排除 `error`,会导致同步失败的订单**永远无法重试**,这反而是 bug。 + +**结论**:❌ 不成立,当前过滤条件是正确的业务设计。 + +--- + +## 三、可接受的妥协项 + +| # | 风险点 | 妥协理由 | +|---|--------|---------| +| 1 | Breaking API 变更 | 异步化必须付出的代价,changes JSON 已标记 `breaking: true`,调用方需适配 | +| 4 | `setImmediate` 中 ctx 生命周期 | 与 `allocateStorage` / `batchIntercept` / `batchLock` / `batchUnlock` / `batchUnintercept` **共 5 处现有模式**完全一致,框架已验证可行 | +| 5 | 异步任务无超时 | 与 `allocateStorage` 一致,缓存 TTL 2 小时自然过期兜底 | +| 8 | `syncOrderIdsProgress` 无权限隔离 | 与 `allocateStorageProgress` 一致,`request_id` 含随机 token 不可猜测 | +| 9 | 操作日志 `ctx.user` 可能为空 | 随 #2 修复一并解决(旧日志代码已删除,新日志用快照 operator) | +| 11 | `progress_callback` 函数注入 | 链路中无 JSON 序列化操作,与 `allocateStorage` 一致 | + +--- + +## 四、当前状态 + +``` +变更文件:6 个 +├── app/service/systemMethods/order/pendingOrder.js (修改) +├── app/service/systems/order_storage_allocation.js (修改) +├── methods/system.json (修改) +├── methods/changes/syncOrderIds-async-20260704.json (新增) +├── methods/changes/syncOrderIds-async-review-feedback-20260704.md (新增) +├── test/.../pendingOrder.syncOrderIds.test.js (新增) +└── test/.../pendingOrder.allocateStorage.test.js (修改) + +ESLint: 0 errors ✅ +单测: 27 passing ✅ (13 allocateStorage + 14 syncOrderIds) +``` + +--- + +## 五、遗留建议(非阻塞) + +| 优先级 | 建议 | 说明 | +|--------|------|------| +| P3 | 增加任务心跳 + 超时自动标记 failed | 可后续迭代,与 `allocateStorage` 统一处理 | +| P3 | `syncOrderIdsProgress` 增加 `warehouse_id` 校验 | 防止跨仓库查询他人任务(当前依赖随机 token 安全性) | +| P3 | 确认前端调用方已适配新返回格式 | 需产品/前端确认 `request_id` 轮询流程 | diff --git a/methods/changes/system.json b/methods/changes/system.json index 1af3fae..8a80d10 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,21 @@ [ + { + "version": "2026.07.05-system-01", + "date": "2026-07-05", + "type": "added", + "summary": "新增 pick.wavePickComplete:传入 wave_id 一键完成整个波次拣货,内部复用 query 去重与任务创建逻辑后自动调用 wavePickTaskComplete(mode=1)", + "methods": [ + "pick.wavePickComplete" + ], + "notes": [ + "新增方法:pick.wavePickComplete,入参 wave_id(number,必填)。", + "内部流程:按 wave_id 查波次 → 活动任务去重(同用户复用 / 他人409冲突)→ 完成任务去重 → 无任务则创建(source=2 后台抓取)→ 调用 pick.wavePickTaskComplete mode=1 全部确认。", + "创建任务 remark 格式:pick.wavePickComplete wave_id={waveId},用于与 pick.query 区分。", + "响应:task_id、status(completed / already_completed)、tip、confirmed_order_ids、is_completed、progress。", + "错误码:400(参数/波次无订单)、401(缺少操作人)、404(波次不存在)、409(他人活动任务冲突)、500(创建/完成失败)。" + ], + "module": "pick" + }, { "version": "2026.07.03-system-02", "date": "2026-07-03", diff --git a/methods/system.json b/methods/system.json index 4e6f5ab..452d83f 100644 --- a/methods/system.json +++ b/methods/system.json @@ -3414,7 +3414,7 @@ }, { "method": "order.pendingOrder.syncOrderIds", - "description": "同步待处理订单入口,支持批量传入 order_ids。服务端会按 create_channel 分组派发同步任务;若命中 SN 管理订单(is_sn_mgmt=Y),该订单会被拦截并标记失败,不允许走批量回传,需改用单订单回传。", + "description": "同步待处理订单(异步模式)。提交后立即返回 request_id,后台异步执行同步流程。调用方需通过 syncOrderIdsProgress 接口轮询任务进度与最终结果。后台会按 create_channel 分组并行派发同步任务(QM/MANUAL/API);单订单失败静默写入错误状态,不影响整批结果;已同步完成(sync_status='fin')的订单会被自动跳过防重复。SN管理订单和快递未分配订单在同步前即被标记为 error 并跳过派发。派发成功后会更新 sync_status='fin',防止重复同步。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -3445,33 +3445,134 @@ "name": "code", "type": "number", "required": true, - "description": "业务状态码,200 表示成功" + "description": "业务状态码,200 表示已受理" }, { "name": "message", "type": "string", "required": true, - "description": "返回信息,当前仅做受理提示" + "description": "受理提示信息" }, { - "name": "data", - "type": "object", - "required": false, - "description": "服务层返回值,当前仅透传 order_ids" + "name": "request_id", + "type": "string", + "required": true, + "description": "异步任务唯一标识,用于 syncOrderIdsProgress 查询进度" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "生效的仓库 ID" } ], "errors": [ { "code": 400, "message": "order_ids 不能为空或格式错误" + } + ] + }, + { + "method": "order.pendingOrder.syncOrderIdsProgress", + "description": "查询 syncOrderIds 异步任务的进度与结果。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "request_id / requestId", + "type": "string", + "required": true, + "source": "body", + "description": "syncOrderIds 返回的 request_id" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "全局调用结果标识,成功为 success" }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务状态码,200 表示成功" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "返回信息" + }, + { + "name": "request_id", + "type": "string", + "required": true, + "description": "请求 ID(原样回传)" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "任务状态:submitted(已受理)/ running(处理中)/ success(完成)/ failed(失败)/ not_found(未找到)" + }, + { + "name": "progress", + "type": "number", + "required": true, + "description": "进度百分比(0-100)" + }, + { + "name": "total_count", + "type": "number", + "required": false, + "description": "总订单数" + }, + { + "name": "processed_count", + "type": "number", + "required": false, + "description": "已处理订单数" + }, + { + "name": "warehouse_id", + "type": "number", + "required": false, + "description": "仓库 ID" + }, + { + "name": "result", + "type": "object", + "required": false, + "description": "完成时的同步结果(success 状态时存在),含 success_count / failed_count / dispatch_results 等" + }, + { + "name": "error", + "type": "string", + "required": false, + "description": "失败时的错误信息(failed 状态时存在)" + }, + { + "name": "update_time", + "type": "number", + "required": false, + "description": "最后更新时间戳" + } + ], + "errors": [ { "code": 400, - "message": "SN订单不支持批量回传,请改用单订单回传" - }, - { - "code": 500, - "message": "内部错误:服务层同步失败" + "message": "request_id 参数不能为空" } ] }, @@ -16412,6 +16513,90 @@ } ] }, + { + "method": "pick.wavePickComplete", + "description": "按波次ID一键完成整个波次的拣货。内部先按 wave_id 定位波次,复用 query 的去重与任务创建逻辑:若波次已有当前用户的活动任务则直接复用并完成;已有他人活动任务返回 409;已完成则返回 already_completed;否则新建任务(source=2 后台抓取)后在内部调用 wavePickTaskComplete(mode=1 全部确认)完成拣货并回写任务进度。", + "isNeedAuth": false, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "wave_id", + "type": "number", + "required": true, + "source": "body", + "description": "波次ID(wms_wave_batch.wave_id)" + } + ], + "response": [ + { + "name": "task_id", + "type": "number", + "required": true, + "description": "拣货任务ID" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "操作结果:completed(拣货完成)或 already_completed(波次已存在完成任务)" + }, + { + "name": "tip", + "type": "string", + "required": true, + "description": "提示文案" + }, + { + "name": "confirmed_order_ids", + "type": "array", + "required": false, + "description": "已确认完成的订单ID列表" + }, + { + "name": "is_completed", + "type": "boolean", + "required": false, + "description": "任务是否已全部完成" + }, + { + "name": "progress", + "type": "object", + "required": false, + "description": "任务进度(total_orders / picked_orders / pending_orders)" + } + ], + "errors": [ + { + "code": 400, + "message": "参数错误(wave_id 为空/非正整数、缺少仓库上下文、波次信息不完整、波次下无可用订单)。" + }, + { + "code": 401, + "message": "未获取到操作人上下文。" + }, + { + "code": 404, + "message": "波次不存在或不属于当前仓库。" + }, + { + "code": 409, + "message": "当前波次已存在他人创建的活动任务(失败 data 含 task_id、task_owner_id、task_owner_name)。" + }, + { + "code": 500, + "message": "任务创建失败或拣货完成失败。" + } + ] + }, { "method": "pick.wavePickTaskDetail", "description": "按任务ID获取拣货任务详情。查询前会校验任务内订单是否全部完成快递号与储位分配:若存在未分配快递号或未分配储位订单,将返回 400 并在 data 中返回 action 与 order_ids 供前端触发一键分配;详情响应新增中间态进度语义(task.is_completed、task.progress 与顶层 is_completed),用于前端判断是否已完成与展示阶段进度;仅允许任务的 pick_user_id 与当前登录用户一致时返回详情。当 pick_mode=1(团购小波次)时,picking_details 字段不返回以减少带宽。", diff --git a/test/app/service/systemMethods/order/pendingOrder.allocateStorage.test.js b/test/app/service/systemMethods/order/pendingOrder.allocateStorage.test.js index 382030c..f3979b1 100644 --- a/test/app/service/systemMethods/order/pendingOrder.allocateStorage.test.js +++ b/test/app/service/systemMethods/order/pendingOrder.allocateStorage.test.js @@ -71,6 +71,11 @@ function createHarness(options = {}) { }, }, }, + logger: { + info: () => {}, + warn: () => {}, + error: () => {}, + }, }; return { @@ -369,15 +374,19 @@ describe('test/app/service/systemMethods/order/pendingOrder.allocateStorage.test order_ids: [ 11, 12 ], }); - assert.deepEqual(capture.syncRequest, { - order_ids: [ 11, 12 ], - }); + // 异步模式:立即返回 request_id,service 层在 setImmediate 中调用 assert.equal(result.flag, 'success'); - assert.equal(result.message, '同步已受理,当前仅透传 order_ids'); - assert.equal(result.code, 200); - assert.deepEqual(result.data, { - ok: true, - }); + assert.match(result.request_id, /^sync_order_100000_\d+_[a-z0-9]+$/); + assert.equal(result.warehouse_id, 100000); + assert.ok(result.message.includes('已提交')); + + // 等待异步回调触发 + await new Promise(resolve => setImmediate(resolve)); + + // service 层被正确调用 + assert.deepEqual(capture.syncRequest.order_ids, [ 11, 12 ]); + assert.equal(capture.syncRequest.warehouse_id, 100000); + assert.equal(typeof capture.syncRequest.progress_callback, 'function'); }); it('should reject warehouse_id and warehouseId on the pending order entry', async () => { From 276d76f65dadc3b55377ce8d498c8d6d9c40b85e Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 6 Jul 2026 17:15:29 +0800 Subject: [PATCH 087/550] =?UTF-8?q?=E6=96=B0=E5=A2=9E=E6=8B=A3=E8=B4=A7?= =?UTF-8?q?=E7=8A=B6=E6=80=81=E5=AD=97=E6=AE=B5=E8=BE=93=E5=87=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/systemMethods/order/wave.js | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/app/service/systemMethods/order/wave.js b/app/service/systemMethods/order/wave.js index abf04ac..0f5dd3f 100644 --- a/app/service/systemMethods/order/wave.js +++ b/app/service/systemMethods/order/wave.js @@ -4186,7 +4186,10 @@ class WaveService extends OrderBaseService { SUM(CASE WHEN od.print_status = 'fin' THEN 1 ELSE 0 END) AS print_fin_count, SUM(CASE WHEN od.inspection_status = 'fin' THEN 1 ELSE 0 END) AS review_fin_count, SUM(CASE WHEN od.inspection_status = 'error' THEN 1 ELSE 0 END) AS review_error_count, - SUM(CASE WHEN od.inspection_status NOT IN ('fin', 'error') THEN 1 ELSE 0 END) AS review_none_count + SUM(CASE WHEN od.inspection_status NOT IN ('fin', 'error') THEN 1 ELSE 0 END) AS review_none_count, + SUM(CASE WHEN od.pick_status = 'none' THEN 1 ELSE 0 END) AS pick_none_count, + SUM(CASE WHEN od.pick_status = 'fin' THEN 1 ELSE 0 END) AS pick_fin_count, + SUM(CASE WHEN od.pick_status = 'error' THEN 1 ELSE 0 END) AS pick_error_count FROM ( SELECT wave_id FROM wms_wave_batch @@ -4232,7 +4235,10 @@ class WaveService extends OrderBaseService { COALESCE(wave_order_stats.print_fin_count, 0) AS print_fin_count, COALESCE(wave_order_stats.review_fin_count, 0) AS review_fin_count, COALESCE(wave_order_stats.review_error_count, 0) AS review_error_count, - COALESCE(wave_order_stats.review_none_count, 0) AS review_none_count + COALESCE(wave_order_stats.review_none_count, 0) AS review_none_count, + COALESCE(wave_order_stats.pick_none_count, 0) AS pick_none_count, + COALESCE(wave_order_stats.pick_fin_count, 0) AS pick_fin_count, + COALESCE(wave_order_stats.pick_error_count, 0) AS pick_error_count ${batchListFromSql} ORDER BY wb.total_orders DESC, wb.wave_id DESC LIMIT :limit OFFSET :offset @@ -4300,6 +4306,9 @@ class WaveService extends OrderBaseService { const expressErrorCount = Number(batch && batch.post_error_count || 0); const printNoneCount = Number(batch && batch.print_none_count || 0); const printFinCount = Number(batch && batch.print_fin_count || 0); + const pickNoneCount = Number(batch && batch.pick_none_count || 0); + const pickFinCount = Number(batch && batch.pick_fin_count || 0); + const pickErrorCount = Number(batch && batch.pick_error_count || 0); const reviewFinCount = Number(batch && batch.review_fin_count || 0); const reviewErrorCount = Number(batch && batch.review_error_count || 0); const unreviewedOrderCount = orderCount - reviewFinCount; @@ -4341,6 +4350,12 @@ class WaveService extends OrderBaseService { partial: '部分打印', finished: '已打印', }), + pick_assignment_status: this.resolveAssignmentStatus(orderCount, pickNoneCount, pickFinCount, pickErrorCount, { + none: '未拣货', + partial: '部分拣货', + finished: '已拣货', + error: '拣货异常', + }), review_assignment_status: reviewAssignmentStatus, unreviewed_order_count: unreviewedOrderCount, }; From 70ad3153a17a6b19b84864188c449bbffce624e6 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 6 Jul 2026 17:16:42 +0800 Subject: [PATCH 088/550] =?UTF-8?q?=E5=88=9B=E5=BB=BA=E8=AE=A2=E5=8D=95?= =?UTF-8?q?=E5=8E=9F=E8=B4=A7=E4=B8=BB=E7=AD=96=E7=95=A5=E8=AF=BB=E5=8F=96?= =?UTF-8?q?=E5=AD=97=E6=AE=B5=E9=94=99=E8=AF=AF=E8=B0=83=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/systems/delivery_order.js | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/app/service/systems/delivery_order.js b/app/service/systems/delivery_order.js index c16d86b..d35b0c6 100644 --- a/app/service/systems/delivery_order.js +++ b/app/service/systems/delivery_order.js @@ -317,15 +317,17 @@ class DeliveryOrderService extends Service { * * 优先级: * 1. 先匹配平台列表里的基础平台项; - * 2. 再匹配平台列表里的系统设置项。 + * 2. 再匹配平台列表里的系统设置项; + * 3. 兜底:签约策略 default_platform_code(货主-仓库级)→ 货主 subject_config.default_platform_code。 * * @param {string} sourcePlatformCode 外部平台编码。 * @param {Object} storeSubjectConfig 货主签约配置。 + * @param {Object} [policyConfig={}] 货主-仓库签约策略配置。 * @param {Object} [info={}] 上下文信息。 * @param {Array} [operationLogs=[]] 待写入的操作日志数组。 * @return {Promise} 平台快照。 */ - async resolvePlatformSnapshot(sourcePlatformCode, storeSubjectConfig, info = {}, operationLogs = []) { + async resolvePlatformSnapshot(sourcePlatformCode, storeSubjectConfig, policyConfig = {}, info = {}, operationLogs = []) { const platformList = await this.ctx.service.systems.platform.getPlatformList( false, false, @@ -348,24 +350,29 @@ class DeliveryOrderService extends Service { sourcePlatformCode: externalCode, }); - const defaultCode = String(storeSubjectConfig && storeSubjectConfig.default_platform_code || '').trim(); + // 兜底优先级:签约策略(货主-仓库级)→ 货主 subject_config + const policyDefaultCode = String(policyConfig && policyConfig.default_platform_code || '').trim(); + const ownerDefaultCode = String(storeSubjectConfig && storeSubjectConfig.default_platform_code || '').trim(); + const defaultCode = policyDefaultCode || ownerDefaultCode; const fallbackPlatform = defaultCode ? this.findPlatformOptionByCode(platformList, defaultCode) : null; const fallbackPlatformName = this.getPlatformSnapshotName(fallbackPlatform) || defaultCode; if (defaultCode) { + const fallbackSource = policyDefaultCode ? 'policy_config' : 'subject_config'; this.appendOrderOperationLog( operationLogs, ORDER_OPERATION_CODES.PLATFORM_FALLBACK, - `平台编码${externalCode}匹配不到平台,已转为默认平台:${fallbackPlatformName}` + `平台编码${externalCode}匹配不到平台,已转为默认平台:${fallbackPlatformName}(来源:${fallbackSource})` ); if (fallbackPlatform) { - this.ctx.logger.warn('[DeliveryOrderService.prepareOrderData] platform code fallback to store default', { + this.ctx.logger.warn('[DeliveryOrderService.prepareOrderData] platform code fallback to default', { deliveryOrderCode: info.deliveryOrderCode, warehouseId: info.warehouseId, storeId: info.storeId, sourcePlatformCode: externalCode, defaultPlatformCode: defaultCode, + fallbackSource, }); return { @@ -1020,7 +1027,7 @@ class DeliveryOrderService extends Service { const storeSubjectConfig = await this.getStoreSubjectConfig(info.storeId); const policyConfig = await this.getStoreWarehousePolicyConfig(info.storeId, info.warehouseId); const enableExternalExpressCode = this.resolveEnableExternalExpressCode(storeSubjectConfig, policyConfig); - const platformSnapshot = await this.resolvePlatformSnapshot(sourcePlatformCode, storeSubjectConfig, { + const platformSnapshot = await this.resolvePlatformSnapshot(sourcePlatformCode, storeSubjectConfig, policyConfig, { deliveryOrderCode, warehouseId: info.warehouseId, storeId: info.storeId, From 525e222351889220d4a8a734b57d95273df347f1 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 6 Jul 2026 17:17:50 +0800 Subject: [PATCH 089/550] =?UTF-8?q?=E8=AE=A2=E5=8D=95=E5=AF=BC=E5=87=BAexc?= =?UTF-8?q?el=E5=A2=9E=E5=8A=A0=E5=A4=87=E6=B3=A8=E3=80=81=E4=B9=B0?= =?UTF-8?q?=E3=80=81=E5=8D=96=E5=AE=B6=E7=95=99=E8=A8=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/systems/order_export.js | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/app/service/systems/order_export.js b/app/service/systems/order_export.js index 6924308..7ae2e2d 100644 --- a/app/service/systems/order_export.js +++ b/app/service/systems/order_export.js @@ -61,6 +61,9 @@ const ORDER_EXPORT_COLUMNS = Object.freeze([ { header: '复核完成状态', key: 'recheck_status', width: 16 }, { header: '配货状态', key: 'post_status', width: 14 }, { header: '打包状态', key: 'pack_status', width: 14 }, + { header: '备注', key: 'remark', width: 30 }, + { header: '买家留言', key: 'buyer_message', width: 30 }, + { header: '卖家留言', key: 'seller_message', width: 30 }, { header: '归档时间', key: 'archive_time', width: 20 }, ]); @@ -107,6 +110,9 @@ const ORDER_EXPORT_ITEM_COLUMNS = Object.freeze([ { header: '复核完成状态', key: 'recheck_status', width: 16 }, { header: '配货状态', key: 'post_status', width: 14 }, { header: '打包状态', key: 'pack_status', width: 14 }, + { header: '备注', key: 'remark', width: 30 }, + { header: '买家留言', key: 'buyer_message', width: 30 }, + { header: '卖家留言', key: 'seller_message', width: 30 }, { header: '归档时间', key: 'archive_time', width: 20 }, ]); @@ -412,6 +418,9 @@ class OrderExportService extends OrderBaseService { items_weight: this.normalizeExportCellValue(safeOrderRow.items_weight), total_amount: this.normalizeExportCellValue(safeOrderRow.total_amount), got_amount: this.normalizeExportCellValue(safeOrderRow.got_amount), + remark: this.normalizeExportCellValue(safeOrderRow.remark), + buyer_message: this.normalizeExportCellValue(safeOrderRow.buyer_message), + seller_message: this.normalizeExportCellValue(safeOrderRow.seller_message), create_at: formatDateSafe(safeOrderRow.create_at), pay_time: formatDateSafe(safeOrderRow.pay_time), delivery_time: formatDateSafe(safeOrderRow.delivery_time), From 7d92522c2f7abca413b852f2d97c73b93e966667 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 6 Jul 2026 17:18:35 +0800 Subject: [PATCH 090/550] =?UTF-8?q?=E5=BA=93=E5=AD=98=E6=8A=A5=E8=A1=A8?= =?UTF-8?q?=E5=AF=BC=E5=87=BA=E5=A2=9E=E5=8A=A0=E6=96=B0=E5=AD=97=E6=AE=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/systems/storage/report.js | 115 +++++++++++++++++++++++++- 1 file changed, 111 insertions(+), 4 deletions(-) diff --git a/app/service/systems/storage/report.js b/app/service/systems/storage/report.js index 1d61ec1..d1ec587 100644 --- a/app/service/systems/storage/report.js +++ b/app/service/systems/storage/report.js @@ -331,11 +331,17 @@ class StorageReportService extends Service { storeIds = [], spaceIds = [], includeBarcode = false, + entryOrderIds = [], + orderIds = [], + warehouseId = null, } = {}) { - const { ctx } = this; + const { ctx, app } = this; const normalizedStockIds = [ ...new Set((stockIds || []).map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)) ]; const normalizedStoreIds = [ ...new Set((storeIds || []).map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)) ]; const normalizedSpaceIds = [ ...new Set((spaceIds || []).map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)) ]; + const normalizedEntryOrderIds = [ ...new Set((entryOrderIds || []).map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)) ]; + const normalizedOrderIds = [ ...new Set((orderIds || []).map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)) ]; + const normalizedWarehouseId = Number(warehouseId); // 从 getStockDetails 获取商品名称、条码信息 const stockMap = new Map(); @@ -366,7 +372,7 @@ class StorageReportService extends Service { } } - const [ storeRows, spaceRows ] = await Promise.all([ + const [ storeRows, spaceRows, entryOrderRows, orderDeliveryRows, orderExpressRows, storeWarehouseRows ] = await Promise.all([ normalizedStoreIds.length > 0 ? ctx.model.Store.findAll({ where: { @@ -385,16 +391,87 @@ class StorageReportService extends Service { raw: true, }) : [], + normalizedEntryOrderIds.length > 0 + ? ctx.model.query( + 'SELECT id, entry_order_code, express_code, logistics_code, logistics_name, source_type FROM wms_entry_order WHERE id IN (:ids)', + { + replacements: { ids: normalizedEntryOrderIds }, + type: app.Sequelize.QueryTypes.SELECT, + } + ) + : [], + normalizedOrderIds.length > 0 + ? ctx.model.query( + 'SELECT id, source_order_codes FROM wms_order_delivery WHERE id IN (:ids)', + { + replacements: { ids: normalizedOrderIds }, + type: app.Sequelize.QueryTypes.SELECT, + } + ) + : [], + normalizedOrderIds.length > 0 + ? ctx.model.query( + 'SELECT order_id, waybill_code FROM wms_order_express WHERE order_id IN (:ids)', + { + replacements: { ids: normalizedOrderIds }, + type: app.Sequelize.QueryTypes.SELECT, + } + ) + : [], + normalizedStoreIds.length > 0 && Number.isInteger(normalizedWarehouseId) && normalizedWarehouseId > 0 + ? ctx.model.StoreWarehouse.findAll({ + where: { + store_id: { [app.Sequelize.Op.in]: normalizedStoreIds }, + warehouse_id: normalizedWarehouseId, + }, + attributes: [ 'store_id', 'store_remask' ], + raw: true, + }) + : [], ]); const storeMap = new Map((storeRows || []).map(item => [ Number(item.id), item ])); const spaceMap = new Map((spaceRows || []).map(item => [ Number(item.id), item ])); + // 入库单映射:entry_order_id → { entry_order_code, express_code, logistics_code, logistics_name, source_type } + const entryOrderMap = new Map(); + for (const eo of (Array.isArray(entryOrderRows) ? entryOrderRows : [])) { + entryOrderMap.set(Number(eo.id), eo); + } + + // 发货单映射:order_id → source_order_codes + const orderDeliveryMap = new Map(); + for (const od of (Array.isArray(orderDeliveryRows) ? orderDeliveryRows : [])) { + orderDeliveryMap.set(Number(od.id), od); + } + + // 运单映射:order_id → waybill_code(取第一条) + const orderExpressMap = new Map(); + for (const oe of (Array.isArray(orderExpressRows) ? orderExpressRows : [])) { + const oid = Number(oe.order_id); + if (oid > 0 && !orderExpressMap.has(oid)) { + orderExpressMap.set(oid, String(oe.waybill_code || '').trim()); + } + } + + // 货主自定义名称映射:store_id → store_remask + const storeWarehouseMap = new Map(); + for (const sw of (Array.isArray(storeWarehouseRows) ? storeWarehouseRows : [])) { + const sid = Number(sw.store_id); + if (sid > 0 && !storeWarehouseMap.has(sid)) { + storeWarehouseMap.set(sid, String(sw.store_remask || '').trim()); + } + } + return { stockMap, storeMap, spaceMap, barcodeMap, + entryOrderMap, + orderDeliveryMap, + orderExpressMap, + storeWarehouseMap, }; } @@ -511,6 +588,8 @@ class StorageReportService extends Service { const detailStockIds = [ ...new Set(safeDetailRows.map(item => Number(item.stock_id)).filter(item => Number.isInteger(item) && item > 0)) ]; const detailStoreIds = [ ...new Set(safeDetailRows.map(item => Number(item.store_id)).filter(item => Number.isInteger(item) && item > 0)) ]; const detailSpaceIds = [ ...new Set(safeDetailRows.map(item => Number(item.space_id)).filter(item => Number.isInteger(item) && item > 0)) ]; + const detailEntryOrderIds = [ ...new Set(safeDetailRows.map(item => Number(item.entry_order_id)).filter(item => Number.isInteger(item) && item > 0)) ]; + const detailOrderIds = [ ...new Set(safeDetailRows.map(item => Number(item.order_id)).filter(item => Number.isInteger(item) && item > 0)) ]; const summaryStockIds = [ ...new Set(summaryList.map(item => Number(item.stock_id)).filter(item => Number.isInteger(item) && item > 0)) ]; const summaryStoreIds = [ ...new Set(summaryList.map(item => Number(item.store_id)).filter(item => Number.isInteger(item) && item > 0)) ]; @@ -523,6 +602,9 @@ class StorageReportService extends Service { storeIds: [ ...new Set([ ...summaryStoreIds, ...detailStoreIds ]) ], spaceIds: [ ...new Set([ ...summarySpaceIds, ...detailSpaceIds ]) ], includeBarcode: true, + entryOrderIds: detailEntryOrderIds, + orderIds: detailOrderIds, + warehouseId, }); const summaryColumns = [ @@ -576,11 +658,24 @@ class StorageReportService extends Service { const space = maps.spaceMap.get(spaceId) || {}; const barcodeSet = maps.barcodeMap.get(stockId); + const entryOrderId = toNumber(item.entry_order_id); + const entryOrder = entryOrderId > 0 ? (maps.entryOrderMap.get(entryOrderId) || {}) : {}; + const isQimenEntry = entryOrder.source_type === 'QM'; + + const orderId = toNumber(item.order_id); + const orderDelivery = orderId > 0 ? (maps.orderDeliveryMap.get(orderId) || {}) : {}; + const waybillCode = maps.orderExpressMap.get(orderId) || ''; + + // 运单号:出库取 order_express.waybill_code,入库取 entry_order.express_code + const generalWaybillNo = waybillCode + || (entryOrderId > 0 ? String(entryOrder.express_code || '').trim() : ''); + return { created_at: formatDateTime(item.created_at), transaction_type: formatTransactionType(item.transaction_type), store_id: storeId, store_name: store.company_name || '', + store_remask: maps.storeWarehouseMap.get(storeId) || '', stock_id: stockId, item_code: stock.item_code || '', item_name: stock.item_name || '', @@ -596,11 +691,17 @@ class StorageReportService extends Service { inventory_type: item.inventory_type || '', order_type: item.order_type || '', order_no: item.order_no || '', - order_id: toNumber(item.order_id), + order_id: orderId, receiving_id: toNumber(item.receiving_id), - entry_order_id: toNumber(item.entry_order_id), + entry_order_id: entryOrderId, operator_name: item.operator_name || '', remark: item.remark || '', + // 新增字段 + qimen_entry_order_code: isQimenEntry ? String(entryOrder.entry_order_code || '').trim() : '', + platform_trade_no: String(orderDelivery.source_order_codes || item.order_no || '').trim(), + entry_order_waybill_no: entryOrderId > 0 ? String(entryOrder.express_code || '').trim() : '', + entry_order_express_company: entryOrderId > 0 ? String(entryOrder.logistics_name || '').trim() : '', + waybill_no: String(generalWaybillNo || '').trim(), }; }); @@ -608,6 +709,7 @@ class StorageReportService extends Service { { header: '时间', key: 'created_at' }, { header: '类型', key: 'transaction_type' }, { header: '货主名称', key: 'store_name' }, + { header: '自定义店铺名称', key: 'store_remask' }, { header: '商品库存ID', key: 'stock_id' }, { header: '商品编码', key: 'item_code' }, { header: '商品名称', key: 'item_name' }, @@ -624,6 +726,11 @@ class StorageReportService extends Service { { header: '单据类型', key: 'order_type' }, { header: '单据号', key: 'order_no' }, { header: '单据ID', key: 'order_id' }, + { header: '奇门入库单号', key: 'qimen_entry_order_code' }, + { header: '平台交易单号', key: 'platform_trade_no' }, + { header: '运单号', key: 'waybill_no' }, + { header: '入库单运单号', key: 'entry_order_waybill_no' }, + { header: '入库单快递公司', key: 'entry_order_express_company' }, { header: '收货单ID', key: 'receiving_id' }, { header: '入库单ID', key: 'entry_order_id' }, { header: '操作人', key: 'operator_name' }, From 897328a4f4974ddb6b8a6c7b37671a35b3b94184 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 6 Jul 2026 17:19:06 +0800 Subject: [PATCH 091/550] =?UTF-8?q?=E6=8B=A3=E8=B4=A7=E6=8B=89=E5=8F=96?= =?UTF-8?q?=E6=98=8E=E7=BB=86=E5=AD=97=E6=AE=B5=E8=A1=A5=E5=85=85=E8=B0=83?= =?UTF-8?q?=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/systems/pick.js | 77 +++++++++++++++++++++++++++++++++++-- 1 file changed, 74 insertions(+), 3 deletions(-) diff --git a/app/service/systems/pick.js b/app/service/systems/pick.js index 77301b5..ed4336f 100644 --- a/app/service/systems/pick.js +++ b/app/service/systems/pick.js @@ -149,6 +149,36 @@ class PickSystemService extends Service { } } + /** + * 解析订单商品快照 JSON。 + * + * item_snapshot 是下单时从 wms_stock_warehouse 抓取的库存快照, + * 其 item_code / item_name 代表下单时的商品信息,比 order_items 列更准确。 + * + * @param {*} rawSnapshot 原始快照数据。 + * @return {Object} 解析后的快照对象。 + */ + parseItemSnapshot(rawSnapshot) { + if (!rawSnapshot) { + return {}; + } + + if (typeof rawSnapshot === 'string') { + try { + const parsed = JSON.parse(rawSnapshot); + return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {}; + } catch (_) { + return {}; + } + } + + if (typeof rawSnapshot === 'object' && !Array.isArray(rawSnapshot)) { + return rawSnapshot; + } + + return {}; + } + /** * 生成拣货明细汇总信息。 * @@ -1143,6 +1173,29 @@ class PickSystemService extends Service { warehouseId, orderItemIds, }); + + // 通过 stock_warehouse 带缓存的公用链路(getStockDetails)批量查询商品资料, + // 以 stock_id 为准获取 item_code / item_name,与 order/base.js 等链路保持一致。 + const stockIdsForDetail = [ ...new Set( + [ ...orderItemMap.values() ] + .map(row => Number(row && row.stock_id || 0)) + .filter(sid => Number.isInteger(sid) && sid > 0) + ) ]; + const stockDetailMap = new Map(); + if (stockIdsForDetail.length > 0) { + try { + const stockWarehouseSvc = ctx.service && ctx.service.systems && ctx.service.systems.stockWarehouse; + if (stockWarehouseSvc && typeof stockWarehouseSvc.getStockDetails === 'function') { + const stockDetails = await stockWarehouseSvc.getStockDetails(stockIdsForDetail, { warehouseId }); + for (const detail of (Array.isArray(stockDetails) ? stockDetails : [])) { + stockDetailMap.set(Number(detail && detail.id || 0), detail); + } + } + } catch (error) { + ctx.logger.warn(`[pick.wavePickTaskDetail] getStockDetails 查询失败,将降级使用 order_items 列值: ${error.message}`); + } + } + const normalizedBoxRows = Array.isArray(boxRows) ? boxRows : []; const boxMapByNo = new Map(normalizedBoxRows .map(row => [ Number(row && row.box_no || 0), row ]) @@ -1153,6 +1206,22 @@ class PickSystemService extends Service { const currentSpaceId = Number(row && row.space_id || 0); const locationRow = locationMap.get(currentSpaceId) || {}; const orderItemRow = orderItemMap.get(orderItemId) || {}; + const stockId = Number(orderItemRow.stock_id || 0); + const stockDetail = stockDetailMap.get(stockId) || null; + const itemSnapshot = this.parseItemSnapshot(orderItemRow.item_snapshot); + + // 构建 stock 字段:优先 getStockDetails 完整对象,兜底用 item_snapshot + order_items 拼装 + const stock = stockDetail + ? { ...stockDetail } + : { + id: stockId || null, + item_code: String(itemSnapshot.item_code || orderItemRow.item_code || '').trim(), + item_name: String(itemSnapshot.item_name || orderItemRow.item_name || '').trim(), + sku_property: String(itemSnapshot.sku_property || '').trim(), + stock_unit: String(itemSnapshot.stock_unit || '').trim(), + barcodes: [], + image_url: [], + }; return { order_id: Number(row && row.order_id || 0), @@ -1168,11 +1237,13 @@ class PickSystemService extends Service { pick_sequence: Number(locationRow.pick_sequence || 0), pick_priority: Number(locationRow.pick_priority || 0), }, - item_code: String(orderItemRow.item_code || '').trim(), - item_name: String(orderItemRow.item_name || '').trim(), - stock_id: Number(orderItemRow.stock_id || 0), + // 优先 stock_warehouse(getStockDetails),兜底 item_snapshot,最终 order_items 列 + item_code: stock.item_code, + item_name: stock.item_name, + stock_id: stockId, plan_qty: Number(orderItemRow.plan_qty || 0), item_snapshot: orderItemRow.item_snapshot || null, + stock, }; }); From 223e42fcf6752ecb42a52d5c2f22ef73857dcdf4 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 6 Jul 2026 17:19:26 +0800 Subject: [PATCH 092/550] =?UTF-8?q?=E6=96=87=E6=A1=A3=E5=8F=98=E6=9B=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- methods/changes/system.json | 15 +++++++++++++++ methods/system.json | 4 ++-- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/methods/changes/system.json b/methods/changes/system.json index 8a80d10..9f04372 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,19 @@ [ + { + "version": "2026.07.06-system-01", + "date": "2026-07-06", + "type": "updated", + "summary": "order.wave.batchList:响应新增 pick_assignment_status(拣货分配状态),按订单 pick_status 聚合判定", + "methods": [ + "order.wave.batchList" + ], + "notes": [ + "响应 list 每项新增字段 pick_assignment_status (string):拣货分配状态,按波次下订单的 pick_status 聚合判定。", + "取值语义与 resolveAssignmentStatus 一致,自定义标签:未拣货(全 none)、部分拣货(混合且无 error)、已拣货(全 fin)、拣货异常(含 error)。", + "SQL 子查询新增 pick_none_count / pick_fin_count / pick_error_count 聚合列。" + ], + "module": "order.wave" + }, { "version": "2026.07.05-system-01", "date": "2026-07-05", diff --git a/methods/system.json b/methods/system.json index 452d83f..82d8c52 100644 --- a/methods/system.json +++ b/methods/system.json @@ -24083,7 +24083,7 @@ "list": [ { "method": "order.wave.batchList", - "description": "波次列表查询。仅使用当前登录操作者仓库上下文(禁止传入 warehouse_id/warehouseId)。支持 where 白名单过滤,固定查询 wave_status=0/1;返回波次基础信息及分配状态汇总。支持 only_todo=1 仅返回仍有未复核订单的波次,并返回复核状态汇总(review_assignment_status)与未复核数量(unreviewed_order_count)。", + "description": "波次列表查询。仅使用当前登录操作者仓库上下文(禁止传入 warehouse_id/warehouseId)。支持 where 白名单过滤,固定查询 wave_status=0/1;返回波次基础信息及分配状态汇总(storage_assignment_status / express_assignment_status / print_assignment_status / pick_assignment_status / review_assignment_status)。支持 only_todo=1 仅返回仍有未复核订单的波次,并返回复核状态汇总(review_assignment_status)与未复核数量(unreviewed_order_count)。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -24122,7 +24122,7 @@ "name": "list", "type": "array", "required": true, - "description": "波次列表,包含波次基础信息与状态汇总(order_count / storage_assignment_status / express_assignment_status / print_assignment_status / review_assignment_status / unreviewed_order_count)。每条记录新增字段 source(number):来源标识,0=普通波次(正常后台操作),1=管理后台策略任务,2=PDA策略任务。" + "description": "波次列表,包含波次基础信息与状态汇总(order_count / storage_assignment_status / express_assignment_status / print_assignment_status / pick_assignment_status / review_assignment_status / unreviewed_order_count)。其中 pick_assignment_status 按订单 pick_status 聚合判定,取值:未拣货/部分拣货/已拣货/拣货异常。每条记录新增字段 source(number):来源标识,0=普通波次(正常后台操作),1=管理后台策略任务,2=PDA策略任务。" }, { "name": "pagination", From df1bd3860108b42aba71f693fe5f82927c9e3cb3 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 6 Jul 2026 19:28:45 +0800 Subject: [PATCH 093/550] =?UTF-8?q?=E5=95=86=E5=93=81=E6=B5=81=E6=B0=B4?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E9=94=81=E5=AE=9A=E7=B1=BB=E7=9B=AE=E8=AF=AD?= =?UTF-8?q?=E4=B9=89=E7=B1=BB=E5=9E=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/model/stock_transaction.js | 4 +-- app/service/systems/stock_store.js | 4 +-- app/service/systems/storage/report.js | 4 +++ ...60706-add-lock-to-wms-stock-transaction.js | 27 +++++++++++++++++++ 4 files changed, 35 insertions(+), 4 deletions(-) create mode 100644 database/migrations/20260706-add-lock-to-wms-stock-transaction.js diff --git a/app/model/stock_transaction.js b/app/model/stock_transaction.js index 7039940..46f1508 100644 --- a/app/model/stock_transaction.js +++ b/app/model/stock_transaction.js @@ -11,9 +11,9 @@ module.exports = app => { comment: '主键ID', }, transaction_type: { - type: ENUM('INBOUND', 'OUTBOUND'), + type: ENUM('INBOUND', 'OUTBOUND', 'LOCK'), allowNull: false, - comment: '出入库类型', + comment: '出入库类型:INBOUND入库 OUTBOUND出库 LOCK锁定', }, warehouse_id: { type: BIGINT(20).UNSIGNED, diff --git a/app/service/systems/stock_store.js b/app/service/systems/stock_store.js index f96a6c8..2a712b9 100644 --- a/app/service/systems/stock_store.js +++ b/app/service/systems/stock_store.js @@ -732,9 +732,9 @@ class stockStoreService extends Service { // 写入流水(除非显式跳过) const skipLog = meta.skipTransactionLog === true; if (!skipLog && ctx.service && ctx.service.systems && ctx.service.systems.stockTransaction) { - // transaction_type 字段为 ENUM('INBOUND','OUTBOUND'),锁定/解锁属于出库流程 + // 锁定操作使用 LOCK 类型,释放操作使用 OUTBOUND await ctx.service.systems.stockTransaction.create({ - transaction_type: 'OUTBOUND', + transaction_type: isLocking ? 'LOCK' : 'OUTBOUND', warehouse_id: stockRecord.warehouse_id, store_id: stockRecord.store_id, stock_id: stockId, diff --git a/app/service/systems/storage/report.js b/app/service/systems/storage/report.js index d1ec587..338091b 100644 --- a/app/service/systems/storage/report.js +++ b/app/service/systems/storage/report.js @@ -127,6 +127,10 @@ function formatTransactionType(transactionType) { return '移库入'; } + if (normalizedType === 'LOCK') { + return '锁定'; + } + return rawType; } diff --git a/database/migrations/20260706-add-lock-to-wms-stock-transaction.js b/database/migrations/20260706-add-lock-to-wms-stock-transaction.js new file mode 100644 index 0000000..89c1f08 --- /dev/null +++ b/database/migrations/20260706-add-lock-to-wms-stock-transaction.js @@ -0,0 +1,27 @@ +'use strict'; + +/** + * 为 wms_stock_transaction.transaction_type ENUM 增加 LOCK。 + * LOCK:库存锁定流水(如分配订单锁定库存)。 + */ +module.exports = { + async up(queryInterface) { + const { sequelize } = queryInterface; + await sequelize.query(` + ALTER TABLE wms_stock_transaction + MODIFY COLUMN transaction_type ENUM( + 'INBOUND', 'OUTBOUND', 'LOCK' + ) NOT NULL COMMENT '出入库类型:INBOUND入库 OUTBOUND出库 LOCK锁定' + `); + }, + + async down(queryInterface) { + const { sequelize } = queryInterface; + await sequelize.query(` + ALTER TABLE wms_stock_transaction + MODIFY COLUMN transaction_type ENUM( + 'INBOUND', 'OUTBOUND' + ) NOT NULL COMMENT '出入库类型' + `); + }, +}; From 9c6d984ebc44140d32b3aa88b0e714fbf378ac33 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 6 Jul 2026 22:07:02 +0800 Subject: [PATCH 094/550] =?UTF-8?q?=E6=96=B0=E5=A2=9E=20stock.transaction.?= =?UTF-8?q?list=20API=EF=BC=9A=E5=95=86=E5=93=81=E5=87=BA=E5=85=A5?= =?UTF-8?q?=E5=BA=93=E6=B5=81=E6=B0=B4=E6=9F=A5=E8=AF=A2=EF=BC=88=E4=BB=93?= =?UTF-8?q?=E5=BA=93/=E8=B4=A7=E4=B8=BB=E4=BE=A7=E8=87=AA=E9=80=82?= =?UTF-8?q?=E5=BA=94=EF=BC=89=EF=BC=8C=E5=90=AB=20system.json=20=E6=96=87?= =?UTF-8?q?=E6=A1=A3=E6=B3=A8=E5=86=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../systemMethods/stock/transaction.js | 146 +++++ app/service/systems/stock_transaction.js | 245 +++++++ methods/system.json | 597 ++++++++++++++++++ 3 files changed, 988 insertions(+) create mode 100644 app/service/systemMethods/stock/transaction.js diff --git a/app/service/systemMethods/stock/transaction.js b/app/service/systemMethods/stock/transaction.js new file mode 100644 index 0000000..287353f --- /dev/null +++ b/app/service/systemMethods/stock/transaction.js @@ -0,0 +1,146 @@ +'use strict'; + +const MainService = require('../../main'); + +/** + * 系统方法层:stock.transaction(商品出入库流水查询包装层)。 + */ +class StockTransactionMethodService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list,storeList'; + const _noNeedLog = 'list,storeList'; + const _noNeedAuth = 'list,storeList'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 仓库侧商品出入库流水列表查询。 + * 按当前用户仓库(ctx.user.store_id)限定数据范围。 + * @param {Object} data 请求体 + * @param {Object} [data.pagination] 分页参数 + * @param {Object} [data.where] 查询条件 + * @param {Object} [data.sort] 排序参数 + * @return {Promise} 统一 success 包装 + */ + async list(data = {}) { + const { service } = this; + const warehouseId = Number(this.ctx.user && this.ctx.user.store_id); + const { pagination } = data; + const { whereValue = {} } = this.prepareWhereContext(data); + const { + start_time: startTime, + end_time: endTime, + store_ids: storeIds, + stock_ids: stockIds, + transaction_type: transactionType, + order_type: orderType, + order_no: orderNo, + batch_no: batchNo, + entry_order_id: entryOrderId, + receiving_id: receivingId, + order_id: orderId, + } = whereValue; + + const { sort = {} } = data; + const { + sort_field: sortFieldSnake, + sortField: sortFieldCamel, + sort_order: sortOrderSnake, + sortOrder: sortOrderCamel, + } = sort || {}; + + const sortOption = { + sortField: sortFieldCamel || sortFieldSnake, + sortOrder: sortOrderCamel || sortOrderSnake, + }; + + const result = await service.systems.stockTransaction.queryList({ + warehouseId, + startTime, + endTime, + storeIds, + stockIds, + transactionType, + orderType, + orderNo, + batchNo, + entryOrderId, + receivingId, + orderId, + sort: sortOption, + pagination, + }); + + return this.success('ok', result); + } + + /** + * 货主侧商品出入库流水列表查询。 + * 按货主 store_id 限定数据范围。 + * @param {Object} data 请求体 + * @param {number} data.store_id 货主ID(必传) + * @param {Object} [data.pagination] 分页参数 + * @param {Object} [data.where] 查询条件 + * @param {Object} [data.sort] 排序参数 + * @return {Promise} 统一 success 包装 + */ + async storeList(data = {}) { + const { service } = this; + const storeId = Number(data.store_id); + if (!Number.isInteger(storeId) || storeId <= 0) { + return this.failure('store_id 不能为空'); + } + + const { pagination } = data; + const { whereValue = {} } = this.prepareWhereContext(data); + const { + start_time: startTime, + end_time: endTime, + warehouse_ids: warehouseIds, + stock_ids: stockIds, + transaction_type: transactionType, + order_type: orderType, + order_no: orderNo, + batch_no: batchNo, + entry_order_id: entryOrderId, + receiving_id: receivingId, + order_id: orderId, + } = whereValue; + + const { sort = {} } = data; + const { + sort_field: sortFieldSnake, + sortField: sortFieldCamel, + sort_order: sortOrderSnake, + sortOrder: sortOrderCamel, + } = sort || {}; + + const sortOption = { + sortField: sortFieldCamel || sortFieldSnake, + sortOrder: sortOrderCamel || sortOrderSnake, + }; + + const result = await service.systems.stockTransaction.queryList({ + storeId, + startTime, + endTime, + warehouseIds, + stockIds, + transactionType, + orderType, + orderNo, + batchNo, + entryOrderId, + receivingId, + orderId, + sort: sortOption, + pagination, + }); + + return this.success('ok', result); + } +} + +module.exports = StockTransactionMethodService; diff --git a/app/service/systems/stock_transaction.js b/app/service/systems/stock_transaction.js index 6e385b2..cd63af6 100644 --- a/app/service/systems/stock_transaction.js +++ b/app/service/systems/stock_transaction.js @@ -307,6 +307,251 @@ class StockTransactionService extends Service { }, }; } + + /** + * 查询商品出入库流水列表(原始记录,不做聚合)。 + * 仓库侧:按 warehouseId 限定;货主侧:按 storeId 限定。 + * @param {Object} options 查询参数 + * @param {number} [options.warehouseId] 仓库ID(仓库侧必传) + * @param {number} [options.storeId] 货主ID(货主侧必传) + * @param {string|Date|null} [options.startTime] 开始时间 + * @param {string|Date|null} [options.endTime] 结束时间 + * @param {Array} [options.storeIds] 货主ID数组(仓库侧筛选) + * @param {Array} [options.warehouseIds] 仓库ID数组(货主侧筛选) + * @param {Array} [options.stockIds] 商品库存ID数组 + * @param {string} [options.transactionType] 流水类型 + * @param {string} [options.orderType] 单据类型 + * @param {string} [options.orderNo] 单据号 + * @param {string} [options.batchNo] 批次号 + * @param {number} [options.entryOrderId] 入库单ID + * @param {number} [options.receivingId] 收货单ID + * @param {number} [options.orderId] 发货单ID + * @param {Object} [options.sort] 排序参数 + * @param {Object} [options.pagination] 分页参数 + * @return {Promise} { list, pagination } + */ + async queryList(options = {}) { + const { ctx, app } = this; + const { + warehouseId, + storeId, + startTime, + endTime, + storeIds, + warehouseIds, + stockIds, + transactionType, + orderType, + orderNo, + batchNo, + entryOrderId, + receivingId, + orderId, + sort = {}, + pagination = {}, + } = options; + + const whereClauses = []; + const replacements = {}; + + // 数据范围限定:仓库侧或货主侧 + if (warehouseId !== undefined && warehouseId !== null) { + whereClauses.push('t.warehouse_id = :warehouseId'); + replacements.warehouseId = Number(warehouseId); + } + + if (storeId !== undefined && storeId !== null) { + whereClauses.push('t.store_id = :storeId'); + replacements.storeId = Number(storeId); + } + + // 时间范围 + if (startTime !== undefined && startTime !== null && startTime !== '') { + const startMs = new Date(startTime).getTime(); + if (!Number.isNaN(startMs)) { + whereClauses.push('t.created_at >= :startTime'); + replacements.startTime = startTime; + } + } + + if (endTime !== undefined && endTime !== null && endTime !== '') { + const endMs = new Date(endTime).getTime(); + if (!Number.isNaN(endMs)) { + whereClauses.push('t.created_at <= :endTime'); + replacements.endTime = endTime; + } + } + + // 货主筛选(仓库侧) + const normalizedStoreIds = Array.isArray(storeIds) + ? storeIds.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0) + : []; + if (normalizedStoreIds.length > 0) { + whereClauses.push('t.store_id IN (:storeIds)'); + replacements.storeIds = normalizedStoreIds; + } + + // 仓库筛选(货主侧) + const normalizedWarehouseIds = Array.isArray(warehouseIds) + ? warehouseIds.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0) + : []; + if (normalizedWarehouseIds.length > 0) { + whereClauses.push('t.warehouse_id IN (:warehouseIds)'); + replacements.warehouseIds = normalizedWarehouseIds; + } + + // 商品筛选 + const normalizedStockIds = Array.isArray(stockIds) + ? stockIds.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0) + : []; + if (normalizedStockIds.length > 0) { + whereClauses.push('t.stock_id IN (:stockIds)'); + replacements.stockIds = normalizedStockIds; + } + + // 流水类型 + if (transactionType) { + whereClauses.push('t.transaction_type = :transactionType'); + replacements.transactionType = String(transactionType).trim(); + } + + // 单据类型 + if (orderType) { + whereClauses.push('t.order_type = :orderType'); + replacements.orderType = String(orderType).trim(); + } + + // 单据号(模糊匹配) + if (orderNo) { + whereClauses.push('t.order_no LIKE :orderNo'); + replacements.orderNo = `%${String(orderNo).trim()}%`; + } + + // 批次号 + if (batchNo) { + whereClauses.push('t.batch_no = :batchNo'); + replacements.batchNo = String(batchNo).trim(); + } + + // 入库单ID + if (entryOrderId !== undefined && entryOrderId !== null) { + const eid = Number(entryOrderId); + if (Number.isInteger(eid) && eid > 0) { + whereClauses.push('t.entry_order_id = :entryOrderId'); + replacements.entryOrderId = eid; + } + } + + // 收货单ID + if (receivingId !== undefined && receivingId !== null) { + const rid = Number(receivingId); + if (Number.isInteger(rid) && rid > 0) { + whereClauses.push('t.receiving_id = :receivingId'); + replacements.receivingId = rid; + } + } + + // 发货单ID + if (orderId !== undefined && orderId !== null) { + const oid = Number(orderId); + if (Number.isInteger(oid) && oid > 0) { + whereClauses.push('t.order_id = :orderId'); + replacements.orderId = oid; + } + } + + const whereSQL = whereClauses.length > 0 + ? `WHERE ${whereClauses.join(' AND ')}` + : ''; + + // 排序 + const SORT_FIELD_WHITELIST = new Set([ 'created_at', 'quantity', 'stock_id', 'store_id', 'warehouse_id' ]); + const sortFieldRaw = String(sort.sortField || 'created_at').trim(); + const sortField = SORT_FIELD_WHITELIST.has(sortFieldRaw) ? sortFieldRaw : 'created_at'; + const sortOrderRaw = String(sort.sortOrder || 'DESC').trim().toUpperCase(); + const sortOrder = sortOrderRaw === 'ASC' ? 'ASC' : 'DESC'; + + // 分页 + const page = Math.max(1, Number(pagination.page) || 1); + const pageSize = Math.min(200, Math.max(1, Number(pagination.pageSize) || 20)); + const offset = (page - 1) * pageSize; + + // 查询总数 + const countResult = await ctx.model.query( + `SELECT COUNT(*) AS total FROM wms_stock_transaction t ${whereSQL}`, + { + replacements, + type: app.Sequelize.QueryTypes.SELECT, + } + ); + const total = countResult && countResult[0] ? Number(countResult[0].total) : 0; + + // 查询列表 + const rows = await ctx.model.query( + `SELECT + t.id, + t.created_at, + t.transaction_type, + t.warehouse_id, + t.store_id, + t.stock_id, + t.quantity, + t.before_quantity, + t.after_quantity, + t.before_locked_quantity, + t.after_locked_quantity, + t.batch_no, + t.order_type, + t.order_no, + t.order_id, + t.receiving_id, + t.entry_order_id, + t.operator_name, + t.remark + FROM wms_stock_transaction t + ${whereSQL} + ORDER BY t.${sortField} ${sortOrder}, t.id ${sortOrder} + LIMIT :limit OFFSET :offset + `, + { + replacements: { ...replacements, limit: pageSize, offset }, + type: app.Sequelize.QueryTypes.SELECT, + } + ); + + const safeRows = Array.isArray(rows) ? rows : []; + const list = safeRows.map(item => ({ + id: Number(item.id), + created_at: item.created_at ? app.formatDate(item.created_at) : '', + transaction_type: item.transaction_type || '', + warehouse_id: Number(item.warehouse_id) || 0, + store_id: Number(item.store_id) || 0, + stock_id: Number(item.stock_id) || 0, + quantity: Number(item.quantity) || 0, + before_quantity: Number(item.before_quantity) || 0, + after_quantity: Number(item.after_quantity) || 0, + before_locked_quantity: Number(item.before_locked_quantity) || 0, + after_locked_quantity: Number(item.after_locked_quantity) || 0, + batch_no: item.batch_no || '', + order_type: item.order_type || '', + order_no: item.order_no || '', + order_id: Number(item.order_id) || 0, + receiving_id: Number(item.receiving_id) || 0, + entry_order_id: Number(item.entry_order_id) || 0, + operator_name: item.operator_name || '', + remark: item.remark || '', + })); + + return { + list, + pagination: { + page, + pageSize, + total, + totalPages: Math.ceil(total / pageSize), + }, + }; + } } module.exports = StockTransactionService; diff --git a/methods/system.json b/methods/system.json index 82d8c52..4aba6dc 100644 --- a/methods/system.json +++ b/methods/system.json @@ -16441,6 +16441,520 @@ } ], "errors": [] + }, + { + "method": "stock.transaction.list", + "description": "商品出入库流水列表查询(wms_stock_transaction),支持 where 条件筛选与分页", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数,包含 page / pageSize" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "统一 where 条件对象,支持以下字段:", + "children": [ + { + "name": "start_time", + "type": "string", + "required": false, + "description": "开始时间(闭区间下限),created_at >= start_time" + }, + { + "name": "end_time", + "type": "string", + "required": false, + "description": "结束时间(闭区间上限),created_at <= end_time" + }, + { + "name": "store_ids", + "type": "array", + "required": false, + "description": "货主ID数组,为空或未传表示不筛选" + }, + { + "name": "stock_ids", + "type": "array", + "required": false, + "description": "商品库存ID数组,为空或未传表示不筛选" + }, + { + "name": "transaction_type", + "type": "string", + "required": false, + "description": "流水类型:INBOUND=入库 / OUTBOUND=出库 / TRANSFER_OUT=移库出 / TRANSFER_IN=移库入 / LOCK=锁定" + }, + { + "name": "order_type", + "type": "string", + "required": false, + "description": "单据类型筛选" + }, + { + "name": "order_no", + "type": "string", + "required": false, + "description": "单据号筛选(支持模糊匹配)" + }, + { + "name": "batch_no", + "type": "string", + "required": false, + "description": "批次号筛选" + }, + { + "name": "entry_order_id", + "type": "number", + "required": false, + "description": "入库单ID筛选" + }, + { + "name": "receiving_id", + "type": "number", + "required": false, + "description": "收货单ID筛选" + }, + { + "name": "order_id", + "type": "number", + "required": false, + "description": "发货单ID筛选" + } + ] + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数对象,支持 sortField / sortOrder 与 sort_field / sort_order 下划线别名兼容", + "children": [ + { + "name": "sortField", + "type": "string", + "required": false, + "description": "排序字段,白名单:created_at、quantity、stock_id、store_id。非法字段回退默认排序(created_at DESC)" + }, + { + "name": "sort_field", + "type": "string", + "required": false, + "description": "排序字段下划线别名(兼容 sort.sort_field),规则同 sortField" + }, + { + "name": "sortOrder", + "type": "string", + "required": false, + "description": "排序方向,ASC / DESC(大小写不敏感),非法值回退 DESC" + }, + { + "name": "sort_order", + "type": "string", + "required": false, + "description": "排序方向下划线别名(兼容 sort.sort_order),规则同 sortOrder" + } + ] + } + ], + "response": [ + { + "name": "list", + "type": "array", + "description": "流水记录列表", + "children": [ + { + "name": "id", + "type": "number", + "description": "流水记录ID" + }, + { + "name": "created_at", + "type": "string", + "description": "流水创建时间" + }, + { + "name": "transaction_type", + "type": "string", + "description": "流水类型:INBOUND / OUTBOUND / TRANSFER_OUT / TRANSFER_IN / LOCK" + }, + { + "name": "store_id", + "type": "number", + "description": "货主ID" + }, + { + "name": "stock_id", + "type": "number", + "description": "商品库存ID" + }, + { + "name": "quantity", + "type": "number", + "description": "变动数量" + }, + { + "name": "before_quantity", + "type": "number", + "description": "变更前库存" + }, + { + "name": "after_quantity", + "type": "number", + "description": "变更后库存" + }, + { + "name": "before_locked_quantity", + "type": "number", + "description": "变更前锁定库存" + }, + { + "name": "after_locked_quantity", + "type": "number", + "description": "变更后锁定库存" + }, + { + "name": "batch_no", + "type": "string", + "description": "批次号" + }, + { + "name": "order_type", + "type": "string", + "description": "单据类型" + }, + { + "name": "order_no", + "type": "string", + "description": "单据号" + }, + { + "name": "order_id", + "type": "number", + "description": "发货单ID" + }, + { + "name": "receiving_id", + "type": "number", + "description": "收货单ID" + }, + { + "name": "entry_order_id", + "type": "number", + "description": "入库单ID" + }, + { + "name": "operator_name", + "type": "string", + "description": "操作人名称" + }, + { + "name": "remark", + "type": "string", + "description": "备注" + } + ] + }, + { + "name": "pagination", + "type": "object", + "description": "分页信息,包含 page、pageSize、total" + } + ], + "errors": [ + { + "code": 400, + "message": "start_time 不合法" + }, + { + "code": 400, + "message": "end_time 不合法" + }, + { + "code": 400, + "message": "start_time 不能大于 end_time" + } + ] + }, + { + "method": "stock.transaction.storeList", + "description": "货主侧商品出入库流水列表查询(wms_stock_transaction),按货主 store_id 限定数据范围,支持 where 条件筛选与分页", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "store_id", + "type": "number", + "required": true, + "source": "body", + "description": "货主ID,必传;用于限定查询的货主范围" + }, + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数,包含 page / pageSize" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "统一 where 条件对象,支持以下字段:", + "children": [ + { + "name": "start_time", + "type": "string", + "required": false, + "description": "开始时间(闭区间下限),created_at >= start_time" + }, + { + "name": "end_time", + "type": "string", + "required": false, + "description": "结束时间(闭区间上限),created_at <= end_time" + }, + { + "name": "warehouse_ids", + "type": "array", + "required": false, + "description": "仓库ID数组,为空或未传表示不按仓库筛选(但仅返回当前货主有权限的仓库数据)" + }, + { + "name": "stock_ids", + "type": "array", + "required": false, + "description": "商品库存ID数组,为空或未传表示不筛选" + }, + { + "name": "transaction_type", + "type": "string", + "required": false, + "description": "流水类型:INBOUND=入库 / OUTBOUND=出库 / TRANSFER_OUT=移库出 / TRANSFER_IN=移库入 / LOCK=锁定" + }, + { + "name": "order_type", + "type": "string", + "required": false, + "description": "单据类型筛选" + }, + { + "name": "order_no", + "type": "string", + "required": false, + "description": "单据号筛选(支持模糊匹配)" + }, + { + "name": "batch_no", + "type": "string", + "required": false, + "description": "批次号筛选" + }, + { + "name": "entry_order_id", + "type": "number", + "required": false, + "description": "入库单ID筛选" + }, + { + "name": "receiving_id", + "type": "number", + "required": false, + "description": "收货单ID筛选" + }, + { + "name": "order_id", + "type": "number", + "required": false, + "description": "发货单ID筛选" + } + ] + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数对象,支持 sortField / sortOrder 与 sort_field / sort_order 下划线别名兼容", + "children": [ + { + "name": "sortField", + "type": "string", + "required": false, + "description": "排序字段,白名单:created_at、quantity、stock_id、warehouse_id。非法字段回退默认排序(created_at DESC)" + }, + { + "name": "sort_field", + "type": "string", + "required": false, + "description": "排序字段下划线别名(兼容 sort.sort_field),规则同 sortField" + }, + { + "name": "sortOrder", + "type": "string", + "required": false, + "description": "排序方向,ASC / DESC(大小写不敏感),非法值回退 DESC" + }, + { + "name": "sort_order", + "type": "string", + "required": false, + "description": "排序方向下划线别名(兼容 sort.sort_order),规则同 sortOrder" + } + ] + } + ], + "response": [ + { + "name": "list", + "type": "array", + "description": "流水记录列表", + "children": [ + { + "name": "id", + "type": "number", + "description": "流水记录ID" + }, + { + "name": "created_at", + "type": "string", + "description": "流水创建时间" + }, + { + "name": "transaction_type", + "type": "string", + "description": "流水类型:INBOUND / OUTBOUND / TRANSFER_OUT / TRANSFER_IN / LOCK" + }, + { + "name": "warehouse_id", + "type": "number", + "description": "仓库ID" + }, + { + "name": "store_id", + "type": "number", + "description": "货主ID" + }, + { + "name": "stock_id", + "type": "number", + "description": "商品库存ID" + }, + { + "name": "quantity", + "type": "number", + "description": "变动数量" + }, + { + "name": "before_quantity", + "type": "number", + "description": "变更前库存" + }, + { + "name": "after_quantity", + "type": "number", + "description": "变更后库存" + }, + { + "name": "before_locked_quantity", + "type": "number", + "description": "变更前锁定库存" + }, + { + "name": "after_locked_quantity", + "type": "number", + "description": "变更后锁定库存" + }, + { + "name": "batch_no", + "type": "string", + "description": "批次号" + }, + { + "name": "order_type", + "type": "string", + "description": "单据类型" + }, + { + "name": "order_no", + "type": "string", + "description": "单据号" + }, + { + "name": "order_id", + "type": "number", + "description": "发货单ID" + }, + { + "name": "receiving_id", + "type": "number", + "description": "收货单ID" + }, + { + "name": "entry_order_id", + "type": "number", + "description": "入库单ID" + }, + { + "name": "operator_name", + "type": "string", + "description": "操作人名称" + }, + { + "name": "remark", + "type": "string", + "description": "备注" + } + ] + }, + { + "name": "pagination", + "type": "object", + "description": "分页信息,包含 page、pageSize、total" + } + ], + "errors": [ + { + "code": 400, + "message": "store_id 不能为空" + }, + { + "code": 400, + "message": "start_time 不合法" + }, + { + "code": 400, + "message": "end_time 不合法" + }, + { + "code": 400, + "message": "start_time 不能大于 end_time" + } + ] } ] }, @@ -23081,6 +23595,89 @@ } ] }, + { + "groupName": "仓库-货主签约模块", + "module": "storeWarehouse.warehouse", + "list": [ + { + "method": "storeWarehouse.warehouse.list", + "description": "仓库侧查询当前仓库可见的货主签约列表", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "page", + "type": "number", + "required": false, + "source": "body", + "description": "页码,默认 1" + }, + { + "name": "page_size", + "type": "number", + "required": false, + "source": "body", + "description": "每页条数,默认 20,最大 200" + }, + { + "name": "keyword", + "type": "string", + "required": false, + "source": "body", + "description": "搜索关键字,模糊匹配货主备注名、仓库备注名、货主公司名、仓库公司名" + }, + { + "name": "auth_status", + "type": "string", + "required": false, + "source": "body", + "description": "授权状态筛选" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "description": "签约列表" + }, + { + "name": "total", + "type": "number", + "description": "总条数" + }, + { + "name": "page", + "type": "number", + "description": "当前页码" + }, + { + "name": "page_size", + "type": "number", + "description": "每页条数" + }, + { + "name": "current_subject", + "type": "object", + "description": "当前主体信息,含 store_id、company_name、role(warehouse/store)" + } + ], + "errors": [ + { + "code": 500, + "message": "获取签约列表失败" + } + ] + } + ] + }, { "groupName": "用户模块", "module": "user", From 4e20831386f3c75364ec4976a97fb479aa9a4ab1 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 6 Jul 2026 22:07:06 +0800 Subject: [PATCH 095/550] =?UTF-8?q?dashboard=20=E8=B4=A7=E4=B8=BB=E7=AB=AF?= =?UTF-8?q?=E8=87=AA=E9=80=82=E5=BA=94=E5=88=86=E6=94=AF=EF=BC=9AstoreStat?= =?UTF-8?q?s/express=5Fratio/platform=5Fdistribution=20=E6=8C=89=20store?= =?UTF-8?q?=5Ftype=20=E5=8C=BA=E5=88=86=E4=BB=93=E5=BA=93/=E8=B4=A7?= =?UTF-8?q?=E4=B8=BB=E6=9F=A5=E8=AF=A2=EF=BC=8C=E8=B4=A7=E4=B8=BB=E7=AB=AF?= =?UTF-8?q?=E8=B7=A8=E4=BB=93=E6=B1=87=E6=80=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/systemMethods/dashboard.js | 266 +++++++++++++++++++------ 1 file changed, 207 insertions(+), 59 deletions(-) diff --git a/app/service/systemMethods/dashboard.js b/app/service/systemMethods/dashboard.js index 1b16148..f78ac3e 100644 --- a/app/service/systemMethods/dashboard.js +++ b/app/service/systemMethods/dashboard.js @@ -10,26 +10,61 @@ class dashboardService extends MainService { const _noNeedLog = '*'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog); } + async storeStats() { const { ctx } = this; - const warehouseId = ctx.user?.store_id; + const storeType = String(ctx.user?.store_type || '').trim(); + if (storeType === 'store') { + return await this.storeSideStoreStats(); + } + + // 仓库端:单仓查询 + const warehouseId = Number(ctx.user?.store_id); if (!warehouseId) { return this.fail('缺少仓库上下文'); } + const stats = await this.queryWarehouseStats(warehouseId); + return this.success('ok', this.mergeStoreStats([stats])); + } + async storeSideStoreStats() { + const { ctx } = this; + const storeId = Number(ctx.user?.store_id); + if (!storeId) { + return this.fail('缺少货主上下文'); + } + + // 获取签约仓库 + const contracts = await ctx.model.StoreWarehouse.findAll({ + where: { store_id: storeId, auth_status: 2 }, + attributes: [ 'warehouse_id' ], + raw: true, + }); + const warehouseIds = (contracts || []).map(c => Number(c.warehouse_id)).filter(id => id > 0); + if (!warehouseIds.length) { + return this.success('ok', this.emptyStoreStats()); + } + + // 跨仓并行查询并汇总 + const results = await Promise.all(warehouseIds.map(wid => this.queryWarehouseStats(wid).catch(() => null))); + return this.success('ok', this.mergeStoreStats(results.filter(Boolean))); + } + + async queryWarehouseStats(warehouseId) { + const { ctx } = this; const model = await ctx.model.OrderDeliveryFactory.getCurrentModel(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' }, + store_id: { [Op.in]: [] }, // 占位,后续填充 }; + delete pendingBase.store_id; - // 今日时间范围 const now = new Date(); const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate()); const todayEnd = new Date(todayStart.getTime() + 86400000); @@ -59,42 +94,85 @@ class dashboardService extends MainService { model.count({ where: { ...pendingBase, step: 3 } }), ]); - const orderTrend = yesterdayNew > 0 - ? parseFloat((((todayNew - yesterdayNew) / yesterdayNew) * 100).toFixed(1)) - : (todayNew > 0 ? 100 : 0); + return { + warehouseId, + totalPending, + todayNew, + yesterdayNew, + unassignedOrders, + unprintedOrders, + unpickedOrders, + pendingShipments, + todayOutbound, + interceptedOrders, + exceptionOrders, + }; + } - const totalForRate = pendingShipments + todayOutbound; + mergeStoreStats(results) { + const merged = { + totalPending: 0, todayNew: 0, yesterdayNew: 0, + unassignedOrders: 0, unprintedOrders: 0, unpickedOrders: 0, + pendingShipments: 0, todayOutbound: 0, interceptedOrders: 0, exceptionOrders: 0, + }; + + for (const r of results) { + merged.totalPending += r.totalPending || 0; + merged.todayNew += r.todayNew || 0; + merged.yesterdayNew += r.yesterdayNew || 0; + merged.unassignedOrders += r.unassignedOrders || 0; + merged.unprintedOrders += r.unprintedOrders || 0; + merged.unpickedOrders += r.unpickedOrders || 0; + merged.pendingShipments += r.pendingShipments || 0; + merged.todayOutbound += r.todayOutbound || 0; + merged.interceptedOrders += r.interceptedOrders || 0; + merged.exceptionOrders += r.exceptionOrders || 0; + } + + const orderTrend = merged.yesterdayNew > 0 + ? parseFloat((((merged.todayNew - merged.yesterdayNew) / merged.yesterdayNew) * 100).toFixed(1)) + : (merged.todayNew > 0 ? 100 : 0); + + const totalForRate = merged.pendingShipments + merged.todayOutbound; const outboundRate = totalForRate > 0 - ? parseFloat(((todayOutbound / totalForRate) * 100).toFixed(2)) + ? parseFloat(((merged.todayOutbound / totalForRate) * 100).toFixed(2)) : 0; - const shipmentProgress = totalPending > 0 - ? parseFloat((((totalPending - pendingShipments) / totalPending) * 100).toFixed(0)) + const shipmentProgress = merged.totalPending > 0 + ? parseFloat((((merged.totalPending - merged.pendingShipments) / merged.totalPending) * 100).toFixed(0)) : 0; - const data = { + return { code: 200, message: '成功', data: { - todayOrders: totalPending + todayOutbound, + todayOrders: merged.totalPending + merged.todayOutbound, orderTrend, - - unassignedOrders, - unprintedOrders, - unpickedOrders, - - pendingShipments, + unassignedOrders: merged.unassignedOrders, + unprintedOrders: merged.unprintedOrders, + unpickedOrders: merged.unpickedOrders, + pendingShipments: merged.pendingShipments, shipmentProgress, - - todayOutbound, + todayOutbound: merged.todayOutbound, outboundRate, - - interceptedOrders, - exceptionOrders, + interceptedOrders: merged.interceptedOrders, + exceptionOrders: merged.exceptionOrders, }, }; + } - return this.success('ok', data); + emptyStoreStats() { + return { + code: 200, + message: '成功', + data: { + todayOrders: 0, orderTrend: 0, + unassignedOrders: 0, unprintedOrders: 0, unpickedOrders: 0, + pendingShipments: 0, shipmentProgress: 0, + todayOutbound: 0, outboundRate: 0, + interceptedOrders: 0, exceptionOrders: 0, + }, + }; } async warehouseStats() { const data = { @@ -204,17 +282,46 @@ class dashboardService extends MainService { } async express_ratio() { const { ctx } = this; - const warehouseId = ctx.user?.store_id; + const storeType = String(ctx.user?.store_type || '').trim(); + if (storeType === 'store') { + return await this.storeSideExpressRatio(); + } + + const warehouseId = Number(ctx.user?.store_id); if (!warehouseId) { return this.fail('缺少仓库上下文'); } + const nameValueMap = await this.queryWarehouseExpressRatio(warehouseId); + return this.success('ok', this.formatChartData(nameValueMap)); + } + async storeSideExpressRatio() { + const { ctx } = this; + const storeId = Number(ctx.user?.store_id); + if (!storeId) { + return this.fail('缺少货主上下文'); + } + + const contracts = await ctx.model.StoreWarehouse.findAll({ + where: { store_id: storeId, auth_status: 2 }, + attributes: [ 'warehouse_id' ], + raw: true, + }); + const warehouseIds = (contracts || []).map(c => Number(c.warehouse_id)).filter(id => id > 0); + if (!warehouseIds.length) { + return this.success('ok', this.emptyChartData()); + } + + const results = await Promise.all(warehouseIds.map(wid => this.queryWarehouseExpressRatio(wid).catch(() => null))); + return this.success('ok', this.mergeChartData(results.filter(Boolean))); + } + + async queryWarehouseExpressRatio(warehouseId) { + const { ctx } = this; 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', @@ -230,40 +337,96 @@ class dashboardService extends MainService { raw: true, }); - // 颜色调色板 + const nameValueMap = new Map(); + for (const row of rows) { + nameValueMap.set(row.logistics_name || '未指定快递', Number(row.value) || 0); + } + return nameValueMap; + } + + mergeChartData(results) { + const merged = new Map(); + for (const map of results) { + for (const [ name, value ] of map.entries()) { + merged.set(name, (merged.get(name) || 0) + value); + } + } + return this.formatChartData(merged); + } + + formatChartData(nameValueMap) { + if (!nameValueMap || nameValueMap.size === 0) { + return { code: 200, message: '成功', data: [] }; + } + const colorPalette = [ '#409EFF', '#67C23A', '#E6A23C', '#909399', '#67023A', '#97293A', '#F56C6C', '#67913A', '#9370DB', '#67313A', '#3AA1FF', '#36CFC9', '#FFC53D', '#FF7A45', '#597EF7', ]; - const data = { + const sorted = [ ...nameValueMap.entries() ].sort((a, b) => b[1] - a[1]); + + return { code: 200, message: '成功', - data: rows.map((row, index) => ({ - name: row.logistics_name || '未指定快递', - value: Number(row.value), - itemStyle: { - color: colorPalette[index % colorPalette.length], - }, + data: sorted.map(([ name, value ], index) => ({ + name, + value, + itemStyle: { color: colorPalette[index % colorPalette.length] }, })), }; + } - return this.success('ok', data); + emptyChartData() { + return { + code: 200, + message: '成功', + data: [], + }; } async platform_distribution() { const { ctx } = this; - const warehouseId = ctx.user?.store_id; + const storeType = String(ctx.user?.store_type || '').trim(); + if (storeType === 'store') { + return await this.storeSidePlatformDistribution(); + } + + const warehouseId = Number(ctx.user?.store_id); if (!warehouseId) { return this.fail('缺少仓库上下文'); } + const nameValueMap = await this.queryWarehousePlatformDistribution(warehouseId); + return this.success('ok', this.formatChartData(nameValueMap)); + } + async storeSidePlatformDistribution() { + const { ctx } = this; + const storeId = Number(ctx.user?.store_id); + if (!storeId) { + return this.fail('缺少货主上下文'); + } + + const contracts = await ctx.model.StoreWarehouse.findAll({ + where: { store_id: storeId, auth_status: 2 }, + attributes: [ 'warehouse_id' ], + raw: true, + }); + const warehouseIds = (contracts || []).map(c => Number(c.warehouse_id)).filter(id => id > 0); + if (!warehouseIds.length) { + return this.success('ok', this.emptyChartData()); + } + + const results = await Promise.all(warehouseIds.map(wid => this.queryWarehousePlatformDistribution(wid).catch(() => null))); + return this.success('ok', this.mergeChartData(results.filter(Boolean))); + } + + async queryWarehousePlatformDistribution(warehouseId) { + const { ctx } = this; 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', @@ -279,26 +442,11 @@ class dashboardService extends MainService { 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: rows.map((row, index) => ({ - name: row.sys_platform_name || '未指定平台', - value: Number(row.value), - itemStyle: { - color: colorPalette[index % colorPalette.length], - }, - })), - }; - - return this.success('ok', data); + const nameValueMap = new Map(); + for (const row of rows) { + nameValueMap.set(row.sys_platform_name || '未指定平台', Number(row.value) || 0); + } + return nameValueMap; } /** * 订单趋势统计:按小时统计当日订单数与发货数 From 41ef9b40dedbce141d65f1f490328112cba5e754 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 6 Jul 2026 22:07:10 +0800 Subject: [PATCH 096/550] =?UTF-8?q?=E6=96=B0=E5=A2=9E=20storeWarehouse.war?= =?UTF-8?q?ehouse.list=20API=EF=BC=9A=E4=BB=93=E5=BA=93=E4=BE=A7=E6=9F=A5?= =?UTF-8?q?=E8=AF=A2=E7=AD=BE=E7=BA=A6=E8=B4=A7=E4=B8=BB=E5=88=97=E8=A1=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/systemMethods/storeWarehouse.js | 2 + .../systemMethods/storeWarehouse/warehouse.js | 53 +++++++++++++++++++ 2 files changed, 55 insertions(+) create mode 100644 app/service/systemMethods/storeWarehouse/warehouse.js diff --git a/app/service/systemMethods/storeWarehouse.js b/app/service/systemMethods/storeWarehouse.js index db6e15f..c2d748e 100644 --- a/app/service/systemMethods/storeWarehouse.js +++ b/app/service/systemMethods/storeWarehouse.js @@ -2,12 +2,14 @@ const MainService = require('../main'); const StoreWarehouseStoreService = require('./storeWarehouse/store'); +const StoreWarehouseWarehouseService = require('./storeWarehouse/warehouse'); class StoreWarehouseNamespaceService extends MainService { constructor(ctx) { super(ctx); this.systemInit('', '', '*', ''); this.store = new StoreWarehouseStoreService(ctx); + this.warehouse = new StoreWarehouseWarehouseService(ctx); } } diff --git a/app/service/systemMethods/storeWarehouse/warehouse.js b/app/service/systemMethods/storeWarehouse/warehouse.js new file mode 100644 index 0000000..3a5bdcc --- /dev/null +++ b/app/service/systemMethods/storeWarehouse/warehouse.js @@ -0,0 +1,53 @@ +'use strict'; + +const MainService = require('../../main'); + +/** + * 规范签约请求入参。 + * + * @param {Object} data 请求数据。 + * @return {Object} 复制后的请求数据。 + */ +function normalizeWarehouseStorePayload(data) { + if (!data || typeof data !== 'object' || Array.isArray(data)) { + return {}; + } + return { ...data }; +} + +class StoreWarehouseWarehouseService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list'; + const _noNeedLog = '*'; + const _noNeedAuth = 'list'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 仓库侧获取签约列表。 + * + * @param {Object} data 请求数据。 + * @return {Promise} 统一响应结果。 + */ + async list(data = {}) { + const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse; + + if (!targetService || typeof targetService.list !== 'function') { + return this.fail('获取签约列表失败', { code: 500 }); + } + + try { + const payload = normalizeWarehouseStorePayload(data); + const result = await targetService.list(payload); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '获取签约列表失败', { + code: Number(error.code) || 500, + }); + } + } +} + +module.exports = StoreWarehouseWarehouseService; From 76c52fa2686da632f6db8445efdc0fe309fcde35 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 6 Jul 2026 22:12:23 +0800 Subject: [PATCH 097/550] =?UTF-8?q?use=5Fstatus=20=E9=87=8D=E5=91=BD?= =?UTF-8?q?=E5=90=8D=E4=B8=BA=20warehouse=5Fuse=5Fstatus=EF=BC=8C=E6=96=B0?= =?UTF-8?q?=E5=A2=9E=20store=5Fuse=5Fstatus=EF=BC=9B=E4=BB=93=E5=BA=93/?= =?UTF-8?q?=E8=B4=A7=E4=B8=BB=E4=BE=A7=E7=8B=AC=E7=AB=8B=E6=8E=A7=E5=88=B6?= =?UTF-8?q?=E7=AD=BE=E7=BA=A6=E4=BD=BF=E7=94=A8=E7=8A=B6=E6=80=81=EF=BC=8C?= =?UTF-8?q?unbind=20=E6=8C=89=E8=BA=AB=E4=BB=BD=E5=88=86=E6=B4=BE=E5=AD=97?= =?UTF-8?q?=E6=AE=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/model/store_warehouse.js | 19 +- app/service/systemMethods/order/wave.js | 2 +- app/service/systems/delivery_order.js | 4 +- app/service/systems/pick.js | 2 +- .../systems/setting/store_warehouse.js | 19 +- app/service/systems/stock_store.js | 8 +- app/service/systems/storage/inventory.js | 2 +- app/service/systems/storage/receiving.js | 675 +++++++----------- app/service/systems/store.js | 2 +- app/service/systems/store_warehouse.js | 22 +- ...ame-use-status-and-add-store-use-status.js | 25 + methods/system.json | 13 +- 12 files changed, 334 insertions(+), 459 deletions(-) create mode 100644 database/migrations/20260706-rename-use-status-and-add-store-use-status.js diff --git a/app/model/store_warehouse.js b/app/model/store_warehouse.js index e3c5055..e204d38 100644 --- a/app/model/store_warehouse.js +++ b/app/model/store_warehouse.js @@ -554,10 +554,17 @@ module.exports = app => { })); }, }, - use_status: { + warehouse_use_status: { type: INTEGER(1), allowNull: false, - comment: '使用状态,0-不可用,1-可用(SKU可见,货主可见,即使解约了)', + defaultValue: 1, + comment: '仓库侧使用状态:0-不可用,1-可用', + }, + store_use_status: { + type: INTEGER(1), + allowNull: false, + defaultValue: 1, + comment: '货主侧使用状态:0-不可用,1-可用', }, }, { tableName: 'wms_store_warehouse', @@ -727,11 +734,11 @@ module.exports = app => { const { warehouseId, storeId, - useStatus = 1, + warehouseUseStatus = 1, } = options; const where = { - use_status: useStatus, + warehouse_use_status: warehouseUseStatus, }; if (warehouseId !== undefined && warehouseId !== null) { @@ -751,7 +758,7 @@ module.exports = app => { warehouseId, storeId, required = false, - useStatus = 1, + warehouseUseStatus = 1, attributes = [ 'store_id', 'store_remask' ], } = options; @@ -762,7 +769,7 @@ module.exports = app => { where: this.buildScopedWhere({ warehouseId, storeId, - useStatus, + warehouseUseStatus, }), required, }; diff --git a/app/service/systemMethods/order/wave.js b/app/service/systemMethods/order/wave.js index 0f5dd3f..86ba90b 100644 --- a/app/service/systemMethods/order/wave.js +++ b/app/service/systemMethods/order/wave.js @@ -3684,7 +3684,7 @@ class WaveService extends OrderBaseService { attributes: [ 'store_id' ], where: { warehouse_id: normalizedWarehouseId, - use_status: 1, + warehouse_use_status: 1, }, raw: true, }); diff --git a/app/service/systems/delivery_order.js b/app/service/systems/delivery_order.js index d35b0c6..6235dc0 100644 --- a/app/service/systems/delivery_order.js +++ b/app/service/systems/delivery_order.js @@ -785,7 +785,7 @@ class DeliveryOrderService extends Service { /** * 根据货主仓库策略解析订单步骤。 - * 若货主与仓库之间不存在已启用已签约的记录(auth_status=2, use_status=1),则抛出错误拒绝创建。 + * 若货主与仓库之间不存在已启用已签约的记录(auth_status=2, warehouse_use_status=1),则抛出错误拒绝创建。 * * @param {Object} info 当前仓库与货主上下文,需包含 storeId 和 warehouseId。 * @param {Object|null} transaction 数据库事务。 @@ -806,7 +806,7 @@ class DeliveryOrderService extends Service { store_id: storeId, warehouse_id: warehouseId, auth_status: 2, - use_status: 1, + warehouse_use_status: 1, }, attributes: [ 'id' ], transaction, diff --git a/app/service/systems/pick.js b/app/service/systems/pick.js index ed4336f..9c20740 100644 --- a/app/service/systems/pick.js +++ b/app/service/systems/pick.js @@ -714,7 +714,7 @@ class PickSystemService extends Service { store_id: currentStoreId, warehouse_id: normalizedWarehouseId, }, - attributes: [ 'id', 'store_id', 'warehouse_id', 'store_remask', 'warehouse_remask', 'auth_status', 'use_status' ], + attributes: [ 'id', 'store_id', 'warehouse_id', 'store_remask', 'warehouse_remask', 'auth_status', 'warehouse_use_status', 'store_use_status' ], raw: true, }); diff --git a/app/service/systems/setting/store_warehouse.js b/app/service/systems/setting/store_warehouse.js index 53e464a..87d2d30 100644 --- a/app/service/systems/setting/store_warehouse.js +++ b/app/service/systems/setting/store_warehouse.js @@ -326,9 +326,9 @@ class SettingStoreWarehouseService extends Service { where.auth_status = authStatus; } - const useStatus = this.normalizeStatusFlag(data.use_status, 'use_status', null); + const useStatus = this.normalizeStatusFlag(data.use_status || data.warehouse_use_status, 'warehouse_use_status', null); if (useStatus !== null) { - where.use_status = useStatus; + where.warehouse_use_status = useStatus; } return where; @@ -421,7 +421,8 @@ class SettingStoreWarehouseService extends Service { reviewed_by: item.reviewed_by ? Number(item.reviewed_by) : null, ended_by: item.ended_by ? Number(item.ended_by) : null, remask: currentIsWarehouse ? (item.store_remask || '') : (item.warehouse_remask || ''), - use_status: Number(item.use_status || 0), + warehouse_use_status: Number(item.warehouse_use_status || 0), + store_use_status: Number(item.store_use_status || 0), is_auth_valid: isAuthValid, remaining_days: remainingDays, }; @@ -542,7 +543,8 @@ class SettingStoreWarehouseService extends Service { applied_by: Number(payload.initiated_by || 0) || accountId, reviewed_by: accountId, ended_by: null, - use_status: 1, + warehouse_use_status: 1, + store_use_status: 1, }; if (payload.store_remask !== undefined) { @@ -682,11 +684,12 @@ class SettingStoreWarehouseService extends Service { try { const currentSubject = await this.getCurrentSubject(); const relation = await this.findScopedRelation(data, currentSubject, transaction); - const nextUseStatus = this.normalizeStatusFlag(data.use_status, 'use_status', 0); + const nextUseStatus = this.normalizeStatusFlag(data.use_status || data.warehouse_use_status, 'warehouse_use_status', 0); + const patch = currentSubject.isWarehouse + ? { warehouse_use_status: nextUseStatus } + : { store_use_status: nextUseStatus }; - await relation.update({ - use_status: nextUseStatus, - }, { transaction }); + await relation.update(patch, { transaction }); const result = await ctx.model.StoreWarehouse.findByPk(relation.id, { include: this.getRelationIncludes(), diff --git a/app/service/systems/stock_store.js b/app/service/systems/stock_store.js index 2a712b9..4c36ea3 100644 --- a/app/service/systems/stock_store.js +++ b/app/service/systems/stock_store.js @@ -566,9 +566,9 @@ class stockStoreService extends Service { store_id: normalizedStoreId, warehouse_id: normalizedWarehouseId, auth_status: 2, - use_status: 1, + warehouse_use_status: 1, }, - attributes: [ 'id', 'policy_config', 'auth_status', 'use_status' ], + attributes: [ 'id', 'policy_config', 'auth_status', 'warehouse_use_status', 'store_use_status' ], raw: true, }); @@ -630,9 +630,9 @@ class stockStoreService extends Service { store_id: storeId, warehouse_id: warehouseId, auth_status: 2, - use_status: 1, + warehouse_use_status: 1, }, - attributes: [ 'id', 'policy_config', 'auth_status', 'use_status' ], + attributes: [ 'id', 'policy_config', 'auth_status', 'warehouse_use_status', 'store_use_status' ], transaction, raw: true, }); diff --git a/app/service/systems/storage/inventory.js b/app/service/systems/storage/inventory.js index 283dec9..b1e225c 100644 --- a/app/service/systems/storage/inventory.js +++ b/app/service/systems/storage/inventory.js @@ -1437,7 +1437,7 @@ class InventoryService extends Service { // ────────── 3. 检查货主配置:是否允许收货单快捷入库 ────────── const storeWarehouse = await ctx.model.StoreWarehouse.findOne({ - where: { store_id: storeId, warehouse_id: warehouseId, use_status: 1 }, + where: { store_id: storeId, warehouse_id: warehouseId, warehouse_use_status: 1 }, attributes: [ 'id', 'policy_config' ], }); diff --git a/app/service/systems/storage/receiving.js b/app/service/systems/storage/receiving.js index 9a65a2b..c8232af 100644 --- a/app/service/systems/storage/receiving.js +++ b/app/service/systems/storage/receiving.js @@ -12,11 +12,9 @@ function getStartOfDayMs(value) { } /** - * 判断到期日期是否早于当前日期。 - * @param {string|Date|number} expiryDate 到期日期 + * 判断到期日期是否早于当前日期ã€? * @param {string|Date|number} expiryDate 到期日期 * @param {Date} [currentDate=new Date()] 当前日期 - * @return {boolean} 是否已过期 - */ + * @return {boolean} 是否已过æœ? */ function isExpiryDateBeforeToday(expiryDate, currentDate = new Date()) { const expiryStartMs = getStartOfDayMs(expiryDate); if (expiryStartMs === null) return false; @@ -29,17 +27,14 @@ function isExpiryDateBeforeToday(expiryDate, currentDate = new Date()) { class ReceivingService extends Service { /** - * 查询收货单列表。 - * @param {Object} where 动态筛选条件 - * @param {Object} [pageParams] 分页参数 + * 查询收货单列表ã€? * @param {Object} where 动态筛选条ä»? * @param {Object} [pageParams] 分页参数 * @param {number} [pageParams.page=1] 页码 * @param {number} [pageParams.pageSize=20] 每页条数 * @param {Object} [sortParams] 排序参数 * @param {Object} [options] 额外选项 * @param {boolean} [options.filterDepleted=false] 是否过滤掉无可再用量的收货单 - * @param {number} [options.entry_order_id] 可选,按入库单商品交集过滤:只返回"至少有一条明细的 system_product_id 在入库单明细中"的收货单 - * @return {Promise} 列表、分页与汇总信息 - */ + * @param {number} [options.entry_order_id] 可选,按入库单商品交集过滤:只返回"至少有一条明细的 system_product_id 在入库单明细ä¸?的收货单 + * @return {Promise} 列表、分页与汇总信æ�? */ async getReceivingList(where, pageParams = {}, sortParams = {}, options = {}) { const { ctx, @@ -113,7 +108,7 @@ class ReceivingService extends Service { total_items: 0, }, }, - message: `筛选条件解析失败: ${parsed.reason}`, + message: `筛选条件解析失è´? ${parsed.reason}`, }; } parsedResult = parsed.result; @@ -166,7 +161,7 @@ class ReceivingService extends Service { as: 'store', attributes: [ 'store_remask' ], where: { - use_status: 1, + warehouse_use_status: 1, warehouse_id: ctx.user.store_id, }, required: false, @@ -179,8 +174,7 @@ class ReceivingService extends Service { }, ]; - // 可选过滤:排除无可再用量的收货单 - let filteredReceivingIds = null; + // 可选过滤:排除无可再用量的收货å�? let filteredReceivingIds = null; if (filterDepleted) { const candidateRows = await ctx.model.Receiving.findAll({ attributes: [ 'id' ], @@ -192,8 +186,7 @@ class ReceivingService extends Service { const candidateIds = candidateRows.map(r => r.id); if (candidateIds.length > 0) { - // 1. 候选收货单明细的 actual_quantity 总和(按 receiving_id 分组) - const detailSums = await ctx.model.ReceivingDetail.findAll({ + // 1. 候选收货单明细çš?actual_quantity 总和(按 receiving_id 分组ï¼? const detailSums = await ctx.model.ReceivingDetail.findAll({ attributes: [ 'receiving_id', [ Sequelize.fn('SUM', Sequelize.col('actual_quantity')), 'total_actual' ], @@ -207,8 +200,7 @@ class ReceivingService extends Service { totalActualMap[row.receiving_id] = Number(row.total_actual) || 0; } - // 2. 这些明细对应的 committed 绑定量(按 receiving_detail_id 分组) - const detailIds = detailSums.length > 0 + // 2. 这些明细对应çš?committed 绑定量(æŒ?receiving_detail_id 分组ï¼? const detailIds = detailSums.length > 0 ? (await ctx.model.ReceivingDetail.findAll({ attributes: [ 'id' ], where: { receiving_id: { [Op.in]: candidateIds } }, @@ -235,7 +227,7 @@ class ReceivingService extends Service { } } - // 3. 计算每个收货单的剩余可用量 = SUM(actual_quantity) - SUM(committed) + // 3. 计算每个收货单的剩余可用é‡?= SUM(actual_quantity) - SUM(committed) const idToDetailIdsMap = {}; if (detailIds.length > 0) { const detailIdRows = await ctx.model.ReceivingDetail.findAll({ @@ -257,7 +249,7 @@ class ReceivingService extends Service { remainingByReceivingId[receivingId] = totalActual - totalCommitted; } - // 过滤:只保留剩余可用量 > 0 的收货单 + // 过滤:只保留剩余可用é‡?> 0 的收货单 filteredReceivingIds = candidateIds.filter(id => remainingByReceivingId[id] > 0); } else { filteredReceivingIds = []; @@ -267,7 +259,7 @@ class ReceivingService extends Service { // 可选过滤:按入库单商品交集过滤(只返回 system_product_id 有交集的收货单) let intersectionFilteredIds = null; if (entryOrderId) { - // 1. 查该入库单的所有 entry_items → stock_id 集合 + // 1. 查该入库单的所æœ?entry_items â†?stock_id 集合 const entryItemRows = await ctx.model.EntryItems.findAll({ where: { order_id: entryOrderId }, attributes: [ 'stock_id' ], @@ -276,10 +268,10 @@ class ReceivingService extends Service { const entrySpIdSet = new Set(entryItemRows.map(r => r.stock_id).filter(Boolean)); if (entrySpIdSet.size === 0) { - // 入库单无明细 → 不返回任何收货单 + // 入库单无明细 â†?不返回任何收货单 intersectionFilteredIds = []; } else { - // 2. 查所有收货单明细,找出 system_product_id 在 entrySpIdSet 中的收货单 ID + // 2. 查所有收货单明细,找å‡?system_product_id åœ?entrySpIdSet 中的收货å�?ID const matchingDetailRows = await ctx.model.ReceivingDetail.findAll({ attributes: [ 'receiving_id' ], where: { @@ -292,12 +284,10 @@ class ReceivingService extends Service { } } - // 合并 filterDepleted 和 entry_order_id 的过滤结果 - let combinedFilteredIds = null; + // 合并 filterDepleted å’?entry_order_id 的过滤结æž? let combinedFilteredIds = null; if (filteredReceivingIds !== null || intersectionFilteredIds !== null) { if (filteredReceivingIds !== null && intersectionFilteredIds !== null) { - // 两个过滤都启用 → 取交集 - const intersectionSet = new Set(intersectionFilteredIds); + // 两个过滤都启ç”?â†?取交é›? const intersectionSet = new Set(intersectionFilteredIds); combinedFilteredIds = filteredReceivingIds.filter(id => intersectionSet.has(id)); } else if (filteredReceivingIds !== null) { combinedFilteredIds = filteredReceivingIds; @@ -306,8 +296,7 @@ class ReceivingService extends Service { } } - // 如果启用了过滤,用过滤后的 ID 做最终查询 - const finalWhere = combinedFilteredIds !== null + // 如果启用了过滤,用过滤后çš?ID 做最终查è¯? const finalWhere = combinedFilteredIds !== null ? { id: { [Op.in]: combinedFilteredIds } } : queryOptions.where; @@ -354,8 +343,7 @@ class ReceivingService extends Service { } const processedData = data.map(item => { - // 注意:wms_receiving 表中没有 locked_quantity 字段,total_quantity 为商品总数量 - const availableQuantity = Math.max(0, item.total_quantity || 0); + // 注意:wms_receiving 表中没有 locked_quantity 字段,total_quantity 为商品总数é‡? const availableQuantity = Math.max(0, item.total_quantity || 0); const lockRate = 0; const itemImages = images .filter(row => parseInt(row.business_id) === item.id) @@ -426,30 +414,25 @@ class ReceivingService extends Service { } } /** - * 获取收货单详情(主单 + 明细分页 + 图片)。 - * @param {Object} data 请求体 - * @param {number} data.id 收货单ID + * 获取收货单详情(主单 + 明细分页 + 图片)ã€? * @param {Object} data 请求ä½? * @param {number} data.id 收货单ID * @param {Object} data.pagination 分页参数 - * @return {Promise} 详情数据,明细中的 space_id 会优先展示自定义库位名称,其次展示库位编码,并补充 space_id_raw 兼容原始ID + * @return {Promise} 详情数据,明细中çš?space_id 会优先展示自定义库位名称,其次展示库位编码,并补å…?space_id_raw 兼容原始ID */ async getReceivingDetail(data) { const { id, pagination } = data; const { page, pageSize } = pagination; const { ctx, app } = this; const { Op } = app.Sequelize; - // 获取用户仓库ID,增加错误处理 - const warehouseId = ctx.user?.store_id; + // 获取用户仓库ID,增加错误处ç�? const warehouseId = ctx.user?.store_id; if (!warehouseId) { - return { code: 0, message: '用户未绑定仓库', data: {} }; + return { code: 0, message: '用户未绑定仓åº?, data: {} }; } try { - // 1. 查询收货单主表 - const receiving = await app.model.Receiving.findOne({ where: { id, warehouse_id: warehouseId } }); + // 1. 查询收货单主è¡? const receiving = await app.model.Receiving.findOne({ where: { id, warehouse_id: warehouseId } }); if (!receiving) { return { code: 0, message: '无记录或无权访问', data: {} }; } - // 2. 查询收货单明细,按分页 - const receivingItems = await app.model.ReceivingDetail.findAll({ + // 2. 查询收货单明ç»?按分é¡? const receivingItems = await app.model.ReceivingDetail.findAll({ where: { receiving_id: id }, include: [{ model: app.model.LocationSpace, @@ -474,9 +457,7 @@ class ReceivingService extends Service { // 3. 获取明细ID数组 const receivingItemsIds = receivingItems.map(item => item.id); - // 4. 查询明细图片(如果明细数量大于0) - const itemImagesMap = {}; // 用于存储每个明细的图片 - if (receivingItemsIds.length > 0) { + // 4. 查询明细图片(如果明细数量大äº?ï¼? const itemImagesMap = {}; // 用于存储每个明细的图ç‰? if (receivingItemsIds.length > 0) { const receivingItemsImages = await ctx.model.FileReference.findAll({ where: { business_type: 'receivingItem', @@ -489,8 +470,7 @@ class ReceivingService extends Service { required: true, }], }); - // 将图片按明细ID分组,并转换为前端可直接使用的链接 - for (const image of receivingItemsImages) { + // 将图片按明细ID分组,并转换为前端可直接使用的链æŽ? for (const image of receivingItemsImages) { if (!itemImagesMap[image.business_id]) { itemImagesMap[image.business_id] = []; } @@ -516,8 +496,7 @@ class ReceivingService extends Service { images: itemImagesMap[item.id] || [], }; }); - // 6. 查询主表的图片 - const receivingImages = await ctx.model.FileReference.findAll({ + // 6. 查询主表的图ç‰? const receivingImages = await ctx.model.FileReference.findAll({ where: { business_type: 'receiving', business_id: id, @@ -530,8 +509,7 @@ class ReceivingService extends Service { }], }); // 7. 组装返回数据 - receiving.dataValues.details = items; // 包含图片链接的明细数据 - receiving.dataValues.images = receivingImages.map(image => ({ + receiving.dataValues.details = items; // 包含图片链接的明细数æ�? receiving.dataValues.images = receivingImages.map(image => ({ id: image.file_id, url: image.file.file_url, })); // 包含主表图片链接 @@ -539,14 +517,12 @@ class ReceivingService extends Service { return { code: 200, message: '查询成功', data: { receiving } }; } catch (error) { - console.error('获取收货单详情失败:', error); - return { code: 500, message: '服务器错误', data: {} }; + console.error('获取收货单详情失è´?', error); + return { code: 500, message: '服务器错è¯?, data: {} }; } } /** - * 批量作废收货单。 - * @param {Object} data 请求体 - * @param {number[]} data.ids 收货单ID数组 + * 批量作废收货单ã€? * @param {Object} data 请求ä½? * @param {number[]} data.ids 收货单ID数组 * @return {Promise} 作废处理结果 */ async batchCancelReceiving(data) { @@ -555,8 +531,7 @@ class ReceivingService extends Service { const { Op } = ctx.model.Sequelize; const warehouse_id = ctx.user.store_id; try { - // 先查询这些单据是否都存在且状态允许作废 - const receivings = await ctx.model.Receiving.findAll({ where: { id: { [Op.in]: ids }, warehouse_id } }); + // 先查询这些单据是否都存在且状态允许作åº? const receivings = await ctx.model.Receiving.findAll({ where: { id: { [Op.in]: ids }, warehouse_id } }); if (receivings.length !== ids.length) { return { code: 0, message: '部分单据不存在或无权访问', data: {} }; } @@ -594,16 +569,13 @@ class ReceivingService extends Service { return { code: 200, message: '批量作废成功', data: {} }; } catch (error) { - console.error('批量作废收货单失败:', error); - return { code: 500, message: '服务器错误', data: {} }; + console.error('批量作废收货单失è´?', error); + return { code: 500, message: '服务器错è¯?, data: {} }; } } /** - * 驳回收货单:将已完成收货单恢复为收货中,记录审核人信息与驳回理由。 - * @param {Object} data 请求体 - * @param {number[]} data.ids 收货单ID数组 - * @param {string} [data.remark] 驳回理由(覆盖原备注) - * @return {Promise} 操作结果 + * 驳回收货单:将已完成收货单恢复为收货中,记录审核人信息与驳回理由ã€? * @param {Object} data 请求ä½? * @param {number[]} data.ids 收货单ID数组 + * @param {string} [data.remark] 驳回理由(覆盖原备注ï¼? * @return {Promise} 操作结果 */ async rejectReceiving(data) { const { ids, remark } = data; @@ -718,15 +690,15 @@ class ReceivingService extends Service { messageType: 'text', businessName: 'receiving', event: 'receiving_rejected', - title: `收货单 ${item.receiving_number || item.id} 已被驳回`, + title: `收货å�?${item.receiving_number || item.id} 已被驳回`, content: [ `驳回人:${reviewerName || '未知'}`, - `驳回理由:${updateData.remark || '无'}`, - `收货单ID:${item.id || ''}`, - `收货单号:${item.receiving_number || '无'}`, - `收货创建人:${item.creator && item.creator.name || '无'}`, - '请及时处理重新提交完成收货。', - ].join('\n') + '。', + `驳回理由ï¼?{updateData.remark || 'æ—?}`, + `收货单IDï¼?{item.id || ''}`, + `收货单号ï¼?{item.receiving_number || 'æ—?}`, + `收货创建人:${item.creator && item.creator.name || 'æ—?}`, + '请及时处理重新提交完成收货ã€?, + ].join('\n') + 'ã€?, businessId: item.id || ids[0], subject: { id: warehouse_id, @@ -759,16 +731,13 @@ class ReceivingService extends Service { return { code: 200, message: '驳回成功', data: { count: ids.length } }; } catch (error) { - ctx.logger.error('[receiving.rejectReceiving] 驳回收货单失败', error); - return { code: 500, message: '服务器错误', data: {} }; + ctx.logger.error('[receiving.rejectReceiving] 驳回收货单失è´?, error); + return { code: 500, message: '服务器错è¯?, data: {} }; } } /** - * 批量审核收货单:校验所有单据的状态后,用事务批量更新审核信息。 - * 任意一张不符合条件则整批失败并回滚。 - * @param {Object} data 请求体 - * @param {number[]} data.ids 收货单ID数组 + * 批量审核收货单:校验所有单据的状态后,用事务批量更新审核信息ã€? * 任意一张不符合条件则整批失败并回滚ã€? * @param {Object} data 请求ä½? * @param {number[]} data.ids 收货单ID数组 * @return {Promise} 操作结果 */ async reviewReceiving(data) { @@ -783,7 +752,7 @@ class ReceivingService extends Service { const normalizedIds = Array.from(new Set(ids.map(Number).filter(n => Number.isFinite(n) && n > 0))); if (normalizedIds.length === 0) { - return { code: 0, message: '收货单ID格式不正确', data: {} }; + return { code: 0, message: '收货单ID格式不正ç¡?, data: {} }; } const reviewerName = String(ctx.user?.employees_name || '').trim() || null; @@ -807,29 +776,28 @@ class ReceivingService extends Service { const errors = []; for (const r of receivings) { if (r.status !== 'completed') { - errors.push(`收货单 ${r.receiving_number || r.id} 状态非收货完成`); + errors.push(`收货å�?${r.receiving_number || r.id} 状态非收货完成`); } if (r.detail_status !== 'all_matched') { - errors.push(`收货单 ${r.receiving_number || r.id} 明细未全部匹配`); + errors.push(`收货å�?${r.receiving_number || r.id} 明细未全部匹配`); } if (r.storage_status !== 'none') { - errors.push(`收货单 ${r.receiving_number || r.id} 已存在入库记录`); + errors.push(`收货å�?${r.receiving_number || r.id} 已存在入库记录`); } if (!r.store_id) { - errors.push(`收货单 ${r.receiving_number || r.id} 未绑定货主`); + errors.push(`收货å�?${r.receiving_number || r.id} 未绑定货主`); } if (Number(r.is_review) === 1) { - errors.push(`收货单 ${r.receiving_number || r.id} 已审核,无需重复操作`); + errors.push(`收货å�?${r.receiving_number || r.id} 已审核,无需重复操作`); } } if (errors.length > 0) { await transaction.rollback(); - return { code: 0, message: errors.join(';'), data: {} }; + return { code: 0, message: errors.join('ï¼?), data: {} }; } - // MySQL 二次状态核实:确保 WHERE 条件精准匹配,防止并发竞争 - const updateResult = await ctx.model.Receiving.update( + // MySQL 二次状态核实:确保 WHERE 条件精准匹配,防止并发竞äº? const updateResult = await ctx.model.Receiving.update( { is_review: 1, reviewer_name: reviewerName, @@ -854,7 +822,7 @@ class ReceivingService extends Service { if (affectedRows !== normalizedIds.length) { await transaction.rollback(); - return { code: 0, message: '收货单审核状态已变化,请刷新后重试', data: {} }; + return { code: 0, message: '收货单审核状态已变化,请刷新后重è¯?, data: {} }; } // 写操作日志(失败不影响业务) @@ -882,8 +850,7 @@ class ReceivingService extends Service { await transaction.commit(); - // 逐单发送审核完成通知(文字 + 文件,失败不影响业务) - const reviewer = { + // 逐单发送审核完成通知(文å­?+ 文件,失败不影响业务ï¼? const reviewer = { employees_id: reviewerEmployeeId, employees_name: reviewerName, name: reviewerName, @@ -918,7 +885,7 @@ class ReceivingService extends Service { failedCount: Number(textResult && textResult.data && textResult.data.failedCount || 0), }); } catch (textErr) { - ctx.logger.error('[receiving.reviewReceiving] 文字通知发送失败', { + ctx.logger.error('[receiving.reviewReceiving] 文字通知发送失è´?, { receiving_id: r.id, error: textErr.message, }); @@ -994,7 +961,7 @@ class ReceivingService extends Service { }); } - // 3. 发送文件通知(仅当 Excel 上传成功时) + // 3. 发送文件通知(仅å½?Excel 上传成功时) if (reviewReport) { try { const fileResult = await this.sendReviewNotice({ receiving: receivingSnapshot, reviewer, reviewReport }); @@ -1009,7 +976,7 @@ class ReceivingService extends Service { reportUrl: reviewReport.url || reviewReport.cdnUrl || reviewReport.cosUrl || '', }); } catch (fileErr) { - ctx.logger.error('[receiving.reviewReceiving] 文件通知发送失败', { + ctx.logger.error('[receiving.reviewReceiving] 文件通知发送失è´?, { receiving_id: r.id, error: fileErr.message, }); @@ -1026,17 +993,14 @@ class ReceivingService extends Service { return { code: 200, message: '审核成功', data: { count: normalizedIds.length } }; } catch (error) { await transaction.rollback(); - ctx.logger.error('[receiving.reviewReceiving] 审核收货单失败', error); + ctx.logger.error('[receiving.reviewReceiving] 审核收货单失è´?, error); return { code: 500, message: `审核失败: ${error.message}`, data: {} }; } } /** - * 构建审核完成 Excel 报表 sheets,复用收货完成报表结构,但标注"审核人"而非"完成人"。 - * @param {Object} options 构建参数 - * @param {Object} options.receiving 收货单(需含 details 数组) - * @param {Object} [options.reviewer={}] 审核人信息 - * @param {Object} [options.stats={}] 明细统计 + * 构建审核完成 Excel 报表 sheets,复用收货完成报表结构,但标æ³?审核äº?而非"完成äº?ã€? * @param {Object} options 构建参数 + * @param {Object} options.receiving 收货单(需å�?details 数组ï¼? * @param {Object} [options.reviewer={}] 审核人信æ�? * @param {Object} [options.stats={}] 明细统计 * @param {Map} [options.detailImageMap] 明细图片 Map(key=detail.id字符串) * @param {Array} [options.receivingImages] 收货单主图片数组 * @return {Array} sheets 数组 @@ -1062,7 +1026,7 @@ class ReceivingService extends Service { const detailColumns = [ '序号', '商品名称', '条码', '数量', '重量', '箱数', '托数', - '批次号', '生产日期', '到期日期', '备注', '图片链接', '图片', + '批次å�?, '生产日期', '到期日期', '备注', '图片链接', '图片', ]; const detailImageColumnIndex = detailColumns.length; const maxDetailImageCount = Math.max( @@ -1115,10 +1079,10 @@ class ReceivingService extends Service { [ '总明细数', stats.total_details || details.length ], [ '已匹配明细数', stats.matched_details || 0 ], [ '未匹配明细数', stats.unmatched_details || 0 ], - [ '总数量', stats.total_quantity || 0 ], - [ '总箱数', receiving && receiving.total_boxes ], + [ '总数é‡?, stats.total_quantity || 0 ], + [ '总箱æ•?, receiving && receiving.total_boxes ], [ '总托盘数', receiving && receiving.total_pallets ], - [ '审核人', reviewerName ], + [ '审核äº?, reviewerName ], [ '审核时间', this.formatReportDate(reviewedAt) ], [ '备注', receiving && receiving.remark ], ].forEach(([ field, value ]) => { @@ -1129,7 +1093,7 @@ class ReceivingService extends Service { }); if (mainImageUrls.length === 0) { - pushRow([ '收货图片', '无' ], { toCol: 2, style: { alignment: { vertical: 'top', wrapText: true } } }); + pushRow([ '收货图片', 'æ—? ], { toCol: 2, style: { alignment: { vertical: 'top', wrapText: true } } }); } else { const summaryLinkCell = buildLinkCell(mainImageUrls); const imagePlaceholders = Array(Math.max(mainImageUrls.length, 1)).fill(''); @@ -1155,7 +1119,7 @@ class ReceivingService extends Service { }); if (details.length === 0) { - pushRow([ '', '', '无明细' ], { toCol: detailColumns.length, style: { alignment: { vertical: 'top', wrapText: true } } }); + pushRow([ '', '', '无明ç»? ], { toCol: detailColumns.length, style: { alignment: { vertical: 'top', wrapText: true } } }); } else { details.forEach((detail, index) => { const imgs = Array.isArray(detailImageMap.get(String(detail.id))) @@ -1209,13 +1173,7 @@ class ReceivingService extends Service { } /** - * 发送审核完成通知(receiving_reviewed),支持文字/文件两种类型。 - * @param {Object} options 发送参数 - * @param {Object} options.receiving 收货单快照 - * @param {Object} [options.reviewer={}] 审核人信息 - * @param {Object|null} [options.reviewReport=null] 审核报表(有值则发文件通知) - * @return {Promise} 发送结果 - */ + * 发送审核完成通知(receiving_reviewed),支持文字/文件两种类型ã€? * @param {Object} options 发送参æ•? * @param {Object} options.receiving 收货单快ç…? * @param {Object} [options.reviewer={}] 审核人信æ�? * @param {Object|null} [options.reviewReport=null] 审核报表(有值则发文件通知ï¼? * @return {Promise} 发送结æž? */ async sendReviewNotice({ receiving, reviewer = {}, @@ -1245,12 +1203,12 @@ class ReceivingService extends Service { ).trim(); const content = [ - `收货单号:${receivingNumber}`, - `货主:${receiving.store_name || '未知'}`, + `收货单号ï¼?{receivingNumber}`, + `货主ï¼?{receiving.store_name || '未知'}`, `审核人:${reviewerName || '未知'}`, - `审核时间:${this.formatReportDate(receiving.updated_at || new Date())}`, - `备注:${receiving.remark || '无'}`, - ].join('\n') + '。'; + `审核时间ï¼?{this.formatReportDate(receiving.updated_at || new Date())}`, + `备注ï¼?{receiving.remark || 'æ—?}`, + ].join('\n') + 'ã€?; return await noticeService.send({ warehouseId, @@ -1258,7 +1216,7 @@ class ReceivingService extends Service { messageType: reportUrl ? 'file' : 'text', businessName: 'receiving', event: 'receiving_reviewed', - title: `收货单${receivingNumber}审核完成`, + title: `收货å�?{receivingNumber}审核完成`, content, url: reportUrl || undefined, fileName: reportUrl ? reportFileName : '', @@ -1312,13 +1270,10 @@ class ReceivingService extends Service { operator = 'eq', value, type, } = condition; - // 处理字段名 - const fieldName = condition.field || fieldKey; + // 处理字段å�? const fieldName = condition.field || fieldKey; - // 特殊值处理 - const processedValue = this.processConditionValue(value, type); - // 根据操作符构建条件 - switch (operator.toLowerCase()) { + // 特殊值处ç�? const processedValue = this.processConditionValue(value, type); + // 根据操作符构建条ä»? switch (operator.toLowerCase()) { case 'eq': return { [fieldName]: processedValue, @@ -1333,9 +1288,8 @@ class ReceivingService extends Service { case 'contains': case 'like': - // 处理多值情况 - if (Array.isArray(processedValue) && processedValue.length > 0) { - // 多个值使用 OR 连接 + // 处理多值情å†? if (Array.isArray(processedValue) && processedValue.length > 0) { + // 多个值使ç”?OR 连接 return { [Sequelize.Op.or]: processedValue.map(val => ({ [fieldName]: { @@ -1344,16 +1298,14 @@ class ReceivingService extends Service { })), }; } - // 单个值正常处理 - return { + // 单个值正常处ç�? return { [fieldName]: { [Sequelize.Op.like]: `%${processedValue}%`, }, }; case 'startswith': - // 处理多值情况 - if (Array.isArray(processedValue) && processedValue.length > 0) { + // 处理多值情å†? if (Array.isArray(processedValue) && processedValue.length > 0) { return { [Sequelize.Op.or]: processedValue.map(val => ({ [fieldName]: { @@ -1369,8 +1321,7 @@ class ReceivingService extends Service { }; case 'endswith': - // 处理多值情况 - if (Array.isArray(processedValue) && processedValue.length > 0) { + // 处理多值情å†? if (Array.isArray(processedValue) && processedValue.length > 0) { return { [Sequelize.Op.or]: processedValue.map(val => ({ [fieldName]: { @@ -1474,18 +1425,14 @@ class ReceivingService extends Service { }; default: - // 默认使用等于操作符 - return { + // 默认使用等于操作ç¬? return { [fieldName]: processedValue, }; } } /** - * 处理条件值 - * @param {any} value - 原始值 - * @param {string} type - 字段类型 - * @return {any} 处理后的值 - */ + * 处理条件å€? * @param {any} value - 原始å€? * @param {string} type - 字段类型 + * @return {any} 处理后的å€? */ processConditionValue(value, type) { const { service } = this; if (value === undefined || value === null) { @@ -1504,16 +1451,14 @@ class ReceivingService extends Service { return value; case 'date': - // 单个日期,根据业务需求决定是开始还是结束时间 - // 通常是开始时间(00:00:00) - return service.main.normalizeDate(value, false); + // 单个日期,根据业务需求决定是开始还是结束时é—? // 通常是开始时间(00:00:00ï¼? return service.main.normalizeDate(value, false); case 'daterange': // 处理日期范围:数组的第一个元素是开始时间,第二个元素是结束时间 if (Array.isArray(value) && value.length === 2) { const [ startDate, endDate ] = value; return [ - startDate ? service.main.normalizeDate(startDate, false) : null, // 开始时间设为00:00:00 + startDate ? service.main.normalizeDate(startDate, false) : null, // 开始时间设ä¸?0:00:00 endDate ? service.main.normalizeDate(endDate, true) : null, // 结束时间设为23:59:59 ]; } @@ -1578,10 +1523,8 @@ class ReceivingService extends Service { } /** - * 创建收货单并生成收货单号。 - * @param {Object} data 创建参数 - * @return {Promise} 新建结果(含 id 与 receiving_number) - */ + * 创建收货单并生成收货单号ã€? * @param {Object} data 创建参数 + * @return {Promise} 新建结果(含 id ä¸?receiving_numberï¼? */ async create(data) { const { delivery_method, @@ -1609,19 +1552,16 @@ class ReceivingService extends Service { id: creator_id, }; - // 2. 生成收货单号。注意:`wms_receiving.receiving_number` 在数据库中是全局唯一索引, - // 不能按 warehouse_id 各自从 001 开始,否则跨仓会撞号;并发创建时也需要重试兜底。 - const now = new Date(); + // 2. 生成收货单号。注意:`wms_receiving.receiving_number` 在数据库中是全局唯一索引ï¼? // 不能æŒ?warehouse_id 各自ä»?001 开始,否则跨仓会撞号;并发创建时也需要重试兜底ã€? const now = new Date(); const prefix = this.buildReceivingNumberPrefix(now); - // 3. 获取店铺名称(如果有货主) - let store_name = null; + // 3. 获取店铺名称(如果有货主ï¼? let store_name = null; if (store_id) { const store = await app.model.StoreWarehouse.findOne({ where: { store_id, warehouse_id, - use_status: 1, + warehouse_use_status: 1, }, }); if (store) { @@ -1629,8 +1569,7 @@ class ReceivingService extends Service { } } - // 4. 创建收货单记录(并发下若撞到唯一键则自动重试取下一个号) - const maxCreateRetries = 5; + // 4. 创建收货单记录(并发下若撞到唯一键则自动重试取下一个号ï¼? const maxCreateRetries = 5; let result = null; let lastCreateError = null; @@ -1716,8 +1655,7 @@ class ReceivingService extends Service { } /** - * 按ID修改收货单基础信息。 - * @param {Object} data 修改参数 + * 按ID修改收货单基础信息ã€? * @param {Object} data 修改参数 * @param {number} data.id 收货单ID * @return {Promise} 修改结果 */ @@ -1743,7 +1681,7 @@ class ReceivingService extends Service { if (!warehouseId) { return { code: 400, - message: '用户未绑定仓库', + message: '用户未绑定仓åº?, }; } @@ -1771,7 +1709,7 @@ class ReceivingService extends Service { await transaction.rollback(); return { code: 404, - message: '收货单不存在或无权访问', + message: '收货单不存在或无权访é—?, }; } @@ -1791,7 +1729,7 @@ class ReceivingService extends Service { where: { warehouse_id: warehouseId, store_id: normalizedStoreId, - use_status: 1, + warehouse_use_status: 1, }, attributes: [ 'store_id', 'store_remask' ], transaction, @@ -1901,11 +1839,11 @@ class ReceivingService extends Service { code: 200, id: receivingId, receiving_number: receiving.receiving_number, - message: '收货单修改成功', + message: '收货单修改成åŠ?, }; } catch (error) { await transaction.rollback(); - ctx.logger.error('[receiving.save] 修改收货单失败', error); + ctx.logger.error('[receiving.save] 修改收货单失è´?, error); return { code: 0, message: `修改失败: ${error.message}`, @@ -1914,13 +1852,8 @@ class ReceivingService extends Service { } /** - * 绑定收货单货主。 - * 规则: - * 1. 已取消收货单禁止绑定; - * 2. 收货中/已完成状态下,若已存在货主,则禁止重复绑定; - * 3. 仅允许绑定与当前仓库存在有效签约关系的货主。 - * @param {Object} data 请求体 - * @param {number} data.id 收货单ID + * 绑定收货单货主ã€? * 规则ï¼? * 1. 已取消收货单禁止绑定ï¼? * 2. 收货ä¸?已完成状态下,若已存在货主,则禁止重复绑定; + * 3. 仅允许绑定与当前仓库存在有效签约关系的货主ã€? * @param {Object} data 请求ä½? * @param {number} data.id 收货单ID * @param {number} data.store_id 货主ID * @return {Promise} 绑定结果 */ @@ -1934,7 +1867,7 @@ class ReceivingService extends Service { if (!warehouseId) { return { code: 400, - message: '用户未绑定仓库', + message: '用户未绑定仓åº?, }; } @@ -1969,7 +1902,7 @@ class ReceivingService extends Service { await transaction.rollback(); return { code: 404, - message: '收货单不存在或无权访问', + message: '收货单不存在或无权访é—?, }; } @@ -1993,7 +1926,7 @@ class ReceivingService extends Service { where: { warehouse_id: warehouseId, store_id: storeId, - use_status: 1, + warehouse_use_status: 1, }, attributes: [ 'store_id', 'store_remask' ], transaction, @@ -2056,7 +1989,7 @@ class ReceivingService extends Service { }; } catch (error) { await transaction.rollback(); - ctx.logger.error('绑定收货单货主失败:', error); + ctx.logger.error('绑定收货单货主失è´?', error); return { code: 500, message: `绑定货主失败: ${error.message}`, @@ -2065,9 +1998,7 @@ class ReceivingService extends Service { } /** - * 查询单个收货单完整信息(含明细、图片)。 - * @param {Object} data 请求体 - * @param {number} data.id 收货单ID + * 查询单个收货单完整信息(含明细、图片)ã€? * @param {Object} data 请求ä½? * @param {number} data.id 收货单ID * @return {Promise} 单据详情 */ async get(data) { @@ -2075,15 +2006,13 @@ class ReceivingService extends Service { const { ctx, app } = this; const { Op } = app.Sequelize; - // 获取用户仓库ID,增加错误处理 - const warehouseId = ctx.user?.store_id; + // 获取用户仓库ID,增加错误处ç�? const warehouseId = ctx.user?.store_id; if (!warehouseId) { - return { code: 0, message: '用户未绑定仓库', data: {} }; + return { code: 0, message: '用户未绑定仓åº?, data: {} }; } try { - // 1. 查询收货单主表 - const receiving = await app.model.Receiving.findOne({ + // 1. 查询收货单主è¡? const receiving = await app.model.Receiving.findOne({ where: { id, warehouse_id: warehouseId, @@ -2093,7 +2022,7 @@ class ReceivingService extends Service { as: 'store', attributes: [ 'store_remask' ], where: { - use_status: 1, + warehouse_use_status: 1, warehouse_id: warehouseId, }, required: false, @@ -2103,14 +2032,12 @@ class ReceivingService extends Service { attributes: [ 'real_name' ], required: false, }], - // 不需要order,因为根据id查询已经是唯一的 - }); + // 不需要order,因为根据id查询已经是唯一çš? }); if (!receiving) { return { code: 0, message: '无记录或无权访问', data: {} }; } - // 2. 查询收货单明细 - const receivingItems = await app.model.ReceivingDetail.findAll({ + // 2. 查询收货单明ç»? const receivingItems = await app.model.ReceivingDetail.findAll({ where: { receiving_id: id, }, @@ -2121,15 +2048,12 @@ class ReceivingService extends Service { attributes: [ 'space_code', 'custom_barcode', 'custom_name' ], }, ], - order: [[ 'id', 'DESC' ]], // 保持倒序,最新在前 - }); + order: [[ 'id', 'DESC' ]], // 保持倒序,最新在å‰? }); // 3. 获取明细ID数组 const receivingItemsIds = receivingItems.map(item => item.id); - // 4. 查询明细图片(如果明细数量大于0) - const itemImagesMap = {}; // 用于存储每个明细的图片 - if (receivingItemsIds.length > 0) { + // 4. 查询明细图片(如果明细数量大äº?ï¼? const itemImagesMap = {}; // 用于存储每个明细的图ç‰? if (receivingItemsIds.length > 0) { const receivingItemsImages = await ctx.model.FileReference.findAll({ where: { business_type: 'receivingItem', @@ -2169,8 +2093,7 @@ class ReceivingService extends Service { }; }); - // 6. 查询主表的图片 - const receivingImages = await ctx.model.FileReference.findAll({ + // 6. 查询主表的图ç‰? const receivingImages = await ctx.model.FileReference.findAll({ where: { business_type: 'receiving', business_id: id, @@ -2185,9 +2108,7 @@ class ReceivingService extends Service { // 7. 组装返回数据 const result = { - ...receiving.toJSON(), // 使用toJSON()确保获得纯对象 - details: items, // 包含图片的明细数据 - images: receivingImages.map(item => ({ + ...receiving.toJSON(), // 使用toJSON()确保获得纯对è±? details: items, // 包含图片的明细数æ�? images: receivingImages.map(item => ({ url: item.file.file_url, id: item.file_id, })), @@ -2196,19 +2117,16 @@ class ReceivingService extends Service { return { code: 200, message: '成功', data: result }; } catch (error) { - console.error('获取收货单详情失败:', error); - return { code: 500, message: '服务器错误', data: {} }; + console.error('获取收货单详情失è´?', error); + return { code: 500, message: '服务器错è¯?, data: {} }; } } /** - * 向收货单新增一条收货明细。 - * @param {Object} data 请求体 - * @param {number} data.receiving_id 收货单ID + * 向收货单新增一条收货明细ã€? * @param {Object} data 请求ä½? * @param {number} data.receiving_id 收货单ID * @param {Object} [data.item] 可选的明细字段 * @return {Promise} 明细列表与默认选中ID - * @description 未传 `item` 时,保持原有空白明细创建行为;传入 `item` 时,合并默认值后交由 Sequelize 校验与写入,并由服务端覆盖 `receiving_id` 与 `creator_id`。 - */ + * @description 未传 `item` 时,保持原有空白明细创建行为;传å…?`item` 时,合并默认值后交由 Sequelize 校验与写入,并由服务端覆ç›?`receiving_id` ä¸?`creator_id`ã€? */ async addDetail(data) { const ctx = this.ctx; const { receiving_id } = data; @@ -2219,8 +2137,7 @@ class ReceivingService extends Service { // 获取当前用户信息 const creator_id = ctx.user.employees_id; const warehouse_id = ctx.user.store_id; - // 验证收货单是否存在 - const receiving = await ctx.model.Receiving.findOne({ + // 验证收货单是否存åœ? const receiving = await ctx.model.Receiving.findOne({ where: { id: receiving_id, warehouse_id }, }); @@ -2231,8 +2148,7 @@ class ReceivingService extends Service { }; } - // 验证收货单状态是否允许添加明细 - if (receiving.status !== 'receiving') { + // 验证收货单状态是否允许添加明ç»? if (receiving.status !== 'receiving') { return { code: 400, message: '收货单状态不允许添加明细', @@ -2242,7 +2158,7 @@ class ReceivingService extends Service { try { const defaultDetail = { receiving_id, - product_name: '新商品', + product_name: '新商å“?, barcode: '', actual_quantity: 0, box_quantity: 0, @@ -2259,8 +2175,7 @@ class ReceivingService extends Service { creator_id, }; - // 允许前端传入可选明细字段,但服务端字段始终覆盖。 - const newDetail = await ctx.model.ReceivingDetail.create({ + // 允许前端传入可选明细字段,但服务端字段始终覆盖ã€? const newDetail = await ctx.model.ReceivingDetail.create({ ...defaultDetail, ...item, receiving_id, @@ -2273,8 +2188,7 @@ class ReceivingService extends Service { order: [[ 'id', 'DESC' ]], }); - // 格式化返回数据 - const formattedDetails = allDetails.map(detail => { + // 格式化返回数æ�? const formattedDetails = allDetails.map(detail => { const detailData = detail.toJSON(); // 处理product_snapshot @@ -2286,8 +2200,7 @@ class ReceivingService extends Service { } } - // 如果有关联的系统商品,可以合并信息 - if (detailData.system_product) { + // 如果有关联的系统商品,可以合并信æ�? if (detailData.system_product) { detailData.system_product_info = detailData.system_product; } @@ -2336,10 +2249,7 @@ class ReceivingService extends Service { } /** - * 绑定或改绑收货单明细的系统商品。 - * @param {Object} data 请求体 - * @param {number} data.detail_id 收货单明细ID(兼容 `id`) - * @param {number} data.system_product_id 商品ID + * 绑定或改绑收货单明细的系统商品ã€? * @param {Object} data 请求ä½? * @param {number} data.detail_id 收货单明细ID(兼å®?`id`ï¼? * @param {number} data.system_product_id 商品ID * @return {Promise} 绑定结果 */ async bindDetailProduct(data) { @@ -2351,7 +2261,7 @@ class ReceivingService extends Service { if (!warehouseId) { return { code: 400, - message: '用户未绑定仓库', + message: '用户未绑定仓åº?, }; } @@ -2429,15 +2339,14 @@ class ReceivingService extends Service { if (!stockWarehouse) { return { code: 404, - message: '商品不存在或不属于当前仓库', + message: '商品不存在或不属于当前仓åº?, }; } const productStoreId = Number(stockWarehouse.store_stock?.store_id || 0); const receivingStoreId = Number(receivingDetail.receiving?.store_id || 0); - // 货主校验:收货单已有货主时,只允许绑定同一货主的商品 - if (receivingStoreId > 0 && productStoreId > 0 && receivingStoreId !== productStoreId) { + // 货主校验:收货单已有货主时,只允许绑定同一货主的商å“? if (receivingStoreId > 0 && productStoreId > 0 && receivingStoreId !== productStoreId) { return { code: 400, message: '该商品不属于当前收货单的货主,不允许绑定', @@ -2471,7 +2380,7 @@ class ReceivingService extends Service { } } - const productName = stockWarehouse.item_name || stockWarehouse.name || receivingDetail.product_name || '未命名商品'; + const productName = stockWarehouse.item_name || stockWarehouse.name || receivingDetail.product_name || '未命名商å“?; const updateData = { system_product_id: systemProductId, product_name: productName, @@ -2496,8 +2405,7 @@ class ReceivingService extends Service { }); barcodes.push(detailBarcode); } catch (barcodeErr) { - // 唯一索引冲突说明条码已被其他商品占用,仅记录日志不阻断业务 - ctx.logger.warn('[receiving.bindDetailProduct] 自动新增条码失败(可能已存在)', barcodeErr); + // 唯一索引冲突说明条码已被其他商品占用,仅记录日志不阻断业åŠ? ctx.logger.warn('[receiving.bindDetailProduct] 自动新增条码失败(可能已存在ï¼?, barcodeErr); } } @@ -2560,7 +2468,7 @@ class ReceivingService extends Service { data: responseData, }; } catch (error) { - ctx.logger.error('绑定收货单明细商品失败:', error); + ctx.logger.error('绑定收货单明细商品失è´?', error); return { code: 500, message: `绑定商品失败: ${error.message}`, @@ -2587,12 +2495,11 @@ class ReceivingService extends Service { if (!detail) { return { code: 404, - message: '明细不存在', + message: '明细不存åœ?, }; } - // 验证关联的收货单状态是否允许修改 - if (detail.receiving && detail.receiving.status !== 'receiving') { + // 验证关联的收货单状态是否允许修æ”? if (detail.receiving && detail.receiving.status !== 'receiving') { return { code: 400, message: '收货单状态不允许修改明细', @@ -2615,8 +2522,7 @@ class ReceivingService extends Service { } try { - // 如果需要处理商品匹配 - if (updateData.barcode && updateData.barcode.trim()) { + // 如果需要处理商品匹é…? if (updateData.barcode && updateData.barcode.trim()) { // 尝试根据条码匹配系统商品 const systemProduct = await ctx.model.StockWarehouse.findOne({ where: { barcode: updateData.barcode }, @@ -2634,15 +2540,13 @@ class ReceivingService extends Service { images: systemProduct.images ? JSON.parse(systemProduct.images) : [], }); - // 如果用户没有输入商品名称,使用系统商品名称 - if (!updateData.product_name) { + // 如果用户没有输入商品名称,使用系统商品名ç§? if (!updateData.product_name) { updateData.product_name = systemProduct.name; } } } - // 处理数量类型的转换 - if (updateData.actual_quantity !== undefined) { + // 处理数量类型的转æ�? if (updateData.actual_quantity !== undefined) { updateData.actual_quantity = parseInt(updateData.actual_quantity) || 0; } @@ -2661,8 +2565,7 @@ class ReceivingService extends Service { if (updateData.stored_quantity !== undefined) { updateData.stored_quantity = parseInt(updateData.stored_quantity) || 0; - // 根据入库数量更新入库状态 - if (updateData.stored_quantity >= updateData.actual_quantity) { + // 根据入库数量更新入库状æ€? if (updateData.stored_quantity >= updateData.actual_quantity) { updateData.storage_status = 'all'; } else if (updateData.stored_quantity > 0) { updateData.storage_status = 'partial'; @@ -2683,8 +2586,7 @@ class ReceivingService extends Service { }; } - // 更新收货单统计信息 - if (detail.receiving_id) { + // 更新收货单统计信æ�? if (detail.receiving_id) { await this.updateReceivingStats(detail.receiving_id); } @@ -2700,8 +2602,7 @@ class ReceivingService extends Service { ], }); - // 格式化返回数据 - const detailData = updatedDetail.toJSON(); + // 格式化返回数æ�? const detailData = updatedDetail.toJSON(); if (detailData.product_snapshot) { try { @@ -2753,16 +2654,14 @@ class ReceivingService extends Service { return null; } - // 直接返回 store_stock 的信息 - return { + // 直接返回 store_stock 的信æ�? return { store_id: stockWarehouse.store_stock.store_id, store_remask: stockWarehouse.store_stock.store_remask, }; } catch (error) { - ctx.logger.error(`获取库存 ${stock_id} 的店铺信息失败:`, error); - // 根据需求决定是否抛出错误 - // throw error; + ctx.logger.error(`获取库存 ${stock_id} 的店铺信息失è´?`, error); + // 根据需求决定是否抛出错è¯? // throw error; return null; } } @@ -2796,8 +2695,7 @@ class ReceivingService extends Service { let storeId = receiving.store_id; let storeName = receiving.store_name; - // 如果收货单没有 store_id,尝试从已匹配的商品详情中获取 - if (!storeId) { + // 如果收货单没æœ?store_id,尝试从已匹配的商品详情中获å�? if (!storeId) { // 查找第一个已匹配的商品详情(system_product_id 不为空) const matchedDetail = await app.model.ReceivingDetail.findOne({ where: { @@ -2815,18 +2713,16 @@ class ReceivingService extends Service { if (storeInfo && storeInfo.store_id) { storeId = storeInfo.store_id; - // 注意:这里使用 store_remask 作为 store_name - storeName = storeInfo.store_remask; // 或者 storeInfo.store_remask + // 注意:这里使ç”?store_remask 作为 store_name + storeName = storeInfo.store_remask; // 或è€?storeInfo.store_remask } } catch (error) { - ctx.logger.warn(`获取商品 ${matchedDetail.system_product_id} 的库存信息失败:`, error); - // 继续执行,使用默认值 - } + ctx.logger.warn(`获取商品 ${matchedDetail.system_product_id} 的库存信息失è´?`, error); + // 继续执行,使用默认å€? } } } - // 3. 统计该收货单的所有明细 - const stats = await ctx.model.ReceivingDetail.findAll({ + // 3. 统计该收货单的所有明ç»? const stats = await ctx.model.ReceivingDetail.findAll({ where: { receiving_id: receivingId }, attributes: [ [ ctx.model.fn('COUNT', ctx.model.col('id')), 'total_items' ], @@ -2838,8 +2734,7 @@ class ReceivingService extends Service { const stat = stats[0] || {}; - // 4. 判断收货单的整体状态 - const allDetails = await ctx.model.ReceivingDetail.findAll({ + // 4. 判断收货单的整体状æ€? const allDetails = await ctx.model.ReceivingDetail.findAll({ where: { receiving_id: receivingId }, transaction, }); @@ -2855,8 +2750,7 @@ class ReceivingService extends Service { } } - // 5. 更新收货单 - const updateData = { + // 5. 更新收货å�? const updateData = { total_items: parseInt(stat.total_items) || 0, total_quantity: parseFloat(stat.total_quantity) || 0, detail_status: detailStatus, @@ -2868,7 +2762,7 @@ class ReceivingService extends Service { updateData.store_id = storeId; updateData.store_name = storeName; } else if (storeId && storeName && receiving.store_name !== storeName) { - // 如果 store_id 已有但 store_name 不同,也更新名称 + // 如果 store_id 已有ä½?store_name 不同,也更新名称 updateData.store_name = storeName; } @@ -2883,22 +2777,19 @@ class ReceivingService extends Service { // 6. 提交事务 await transaction.commit(); - ctx.logger.info(`成功更新收货单 ${receivingId} 的统计信息`); + ctx.logger.info(`成功更新收货å�?${receivingId} 的统计信息`); } catch (error) { - // 7. 发生错误时回滚事务 - if (transaction) { + // 7. 发生错误时回滚事åŠ? if (transaction) { await transaction.rollback(); } - ctx.logger.error('更新收货单统计失败:', error); + ctx.logger.error('更新收货单统计失è´?', error); throw error; } } /** - * 删除收货单明细并回算统计。 - * @param {Object} data 请求体 - * @param {number} data.detail_id 明细ID + * 删除收货单明细并回算统计ã€? * @param {Object} data 请求ä½? * @param {number} data.detail_id 明细ID * @return {Promise} 删除结果 */ async deleteDetail(data) { @@ -2925,12 +2816,11 @@ class ReceivingService extends Service { if (!detail) { return { code: 404, - message: '明细不存在', + message: '明细不存åœ?, }; } - // 验证关联的收货单状态是否允许删除 - if (detail.receiving && detail.receiving.status !== 'receiving') { + // 验证关联的收货单状态是否允许删é™? if (detail.receiving && detail.receiving.status !== 'receiving') { return { code: 400, message: '收货单状态不允许删除明细', @@ -2941,7 +2831,7 @@ class ReceivingService extends Service { if (detail.storage_status !== 'none' && detail.stored_quantity > 0) { return { code: 400, - message: '该明细已入库,不能删除', + message: '该明细已入库,不能删é™?, }; } @@ -2961,14 +2851,12 @@ class ReceivingService extends Service { }; } - // 获取删除后的所有明细 - const remainingDetails = await ctx.model.ReceivingDetail.findAll({ + // 获取删除后的所有明ç»? const remainingDetails = await ctx.model.ReceivingDetail.findAll({ where: { receiving_id }, order: [[ 'id', 'DESC' ]], }); - // 格式化返回数据 - const formattedDetails = remainingDetails.map(detail => { + // 格式化返回数æ�? const formattedDetails = remainingDetails.map(detail => { const detailData = detail.toJSON(); if (detailData.product_snapshot) { @@ -2982,11 +2870,9 @@ class ReceivingService extends Service { return detailData; }); - // 返回下一个选中的明细ID(如果有剩余明细) - let selectId = null; + // 返回下一个选中的明细ID(如果有剩余明细ï¼? let selectId = null; if (remainingDetails.length > 0) { - // 默认选中第一个 - selectId = remainingDetails[0].id; + // 默认选中第一ä¸? selectId = remainingDetails[0].id; } await this.updateReceivingStats(receiving_id); @@ -3031,8 +2917,7 @@ class ReceivingService extends Service { } } /** - * 修改收货明细。 - * @param {Object} data 收货明细修改参数 + * 修改收货明细ã€? * @param {Object} data 收货明细修改参数 * @return {Promise} 修改结果 */ async detailChange(data) { @@ -3045,13 +2930,10 @@ class ReceivingService extends Service { id, // 收货明细ID receiving_id, // 收货单ID actual_quantity, // 实际收货数量 - batch_number, // 批次号 - production_date, // 生产日期 + batch_number, // 批次å�? production_date, // 生产日期 expiry_date, // 到期日期 box_quantity, // 箱数 - boxes_per_pallet, // 每托盘箱数 - pallet_quantity, // 托盘数 - space_id, // 存放库位ID + boxes_per_pallet, // 每托盘箱æ•? pallet_quantity, // 托盘æ•? space_id, // 存放库位ID remark, // 备注 system_product_id, // 系统商品ID barcode, // 条码 @@ -3060,9 +2942,7 @@ class ReceivingService extends Service { box_height, box_length, weight, - box_remainder, // 箱余数 - box_weight, // 箱重量 - } = data; + box_remainder, // 箱余æ•? box_weight, // 箱重é‡? } = data; // 2. 验证必填字段 if (!id) { return { @@ -3099,7 +2979,7 @@ class ReceivingService extends Service { if (!receivingDetail) { return { code: 404, - message: '收货明细不存在', + message: '收货明细不存åœ?, }; } @@ -3114,7 +2994,7 @@ class ReceivingService extends Service { if (box_quantity !== undefined && box_quantity < 0) { return { code: 400, - message: '箱数不能为负数', + message: '箱数不能为负æ•?, }; } @@ -3192,8 +3072,7 @@ class ReceivingService extends Service { if (stockWarehouse) { // 更新商品相关信息 updateData.system_product_id = system_product_id; - // 使用系统商品的条码(如果前端没有提供) - const barcodes = stockWarehouse.barcodes?.map(b => b.barcode) || []; + // 使用系统商品的条码(如果前端没有提供ï¼? const barcodes = stockWarehouse.barcodes?.map(b => b.barcode) || []; updateData.barcode = updateData.barcode || barcodes.join(';'); updateData.weight = updateData.weight || stockWarehouse.gross_weight; if (stockWarehouse.enable_box_spec) { @@ -3202,8 +3081,7 @@ class ReceivingService extends Service { updateData.box_width = updateData.box_width || stockWarehouse.box_width; updateData.box_length = updateData.box_length || stockWarehouse.box_length; } - // 使用系统商品的名称(如果前端没有提供) - updateData.product_name = stockWarehouse.item_name || product_name; + // 使用系统商品的名称(如果前端没有提供ï¼? updateData.product_name = stockWarehouse.item_name || product_name; // 如果有货主信息,更新到产品快照中 if (stockWarehouse.store_stock) { @@ -3319,11 +3197,10 @@ class ReceivingService extends Service { if (!receiving) { await transaction.rollback(); - ctx.throw(404, '收货单不存在或已被删除'); + ctx.throw(404, '收货单不存在或已被删é™?); } - // 2. 检查状态是否允许作废 - if (receiving.status === 'cancelled') { + // 2. 检查状态是否允许作åº? if (receiving.status === 'cancelled') { return { code: 200, success: true, @@ -3336,13 +3213,12 @@ class ReceivingService extends Service { ctx.throw(400, '已全部入库完成,无法作废'); } - // 3. 获取操作人信息 - const operator = ctx.user; + // 3. 获取操作人信æ�? const operator = ctx.user; // 4. 更新收货单状态为作废 await ctx.model.Receiving.update({ status: 'cancelled', - remark: invalid_reason ? `已作废: ${invalid_reason}` : (receiving.remark || '') + ' - 已作废', + remark: invalid_reason ? `已作åº? ${invalid_reason}` : (receiving.remark || '') + ' - 已作åº?, updated_at: new Date(), }, { where: { id: receivingId }, @@ -3373,12 +3249,10 @@ class ReceivingService extends Service { } } - // 6. 处理关联的入库记录(如果有部分入库的情况) - if (receiving.storage_status === 'partial') { - // 将关联的入库记录状态也更新为作废 - await ctx.model.Storage.update({ + // 6. 处理关联的入库记录(如果有部分入库的情况ï¼? if (receiving.storage_status === 'partial') { + // 将关联的入库记录状态也更新为作åº? await ctx.model.Storage.update({ status: 'cancelled', - remark: `关联收货单${receiving.receiving_number}已作废`, + remark: `关联收货å�?{receiving.receiving_number}已作废`, updated_at: new Date(), }, { where: { @@ -3434,7 +3308,7 @@ class ReceivingService extends Service { await transaction.rollback(); } - ctx.logger.error(`作废收货单失败: ${error.message}`, { + ctx.logger.error(`作废收货单失è´? ${error.message}`, { receivingId, warehouseId, userId: ctx.user.id, @@ -3461,7 +3335,7 @@ class ReceivingService extends Service { formatDeliveryMethod(value) { const methodMap = { truck: '货车', - express: '快递', + express: '快é€?, air_freight: '空运', sea_freight: '海运', other: '其他', @@ -3472,15 +3346,12 @@ class ReceivingService extends Service { } /** - * 获取完成收货时需要展示的联系字段。 - * @param {Object} receiving 收货单快照。 - * @return {Array} 需要展示的联系字段列表。 - */ + * 获取完成收货时需要展示的联系字段ã€? * @param {Object} receiving 收货单快照ã€? * @return {Array} 需要展示的联系字段列表ã€? */ getCompletionContactFields(receiving) { const deliveryMethod = String((receiving && receiving.delivery_method) || '').trim(); if (deliveryMethod === 'truck') { - return [[ '车牌号', receiving && receiving.license_plate ]]; + return [[ '车牌å�?, receiving && receiving.license_plate ]]; } if (deliveryMethod === 'express') { @@ -3491,15 +3362,7 @@ class ReceivingService extends Service { } /** - * 生成收货完成报表的工作表数据。 - * @param {Object} options 报表参数。 - * @param {Object} options.receiving 收货单快照。 - * @param {Object} [options.operator={}] 操作人信息。 - * @param {Object} [options.stats={}] 收货统计数据。 - * @param {Map} [options.detailImageMap=new Map()] 明细图片映射。 - * @param {Array} [options.receivingImages=[]] 收货单图片列表。 - * @return {Array} 工作表列表。 - */ + * 生成收货完成报表的工作表数据ã€? * @param {Object} options 报表参数ã€? * @param {Object} options.receiving 收货单快照ã€? * @param {Object} [options.operator={}] 操作人信息ã€? * @param {Object} [options.stats={}] 收货统计数据ã€? * @param {Map} [options.detailImageMap=new Map()] 明细图片映射ã€? * @param {Array} [options.receivingImages=[]] 收货单图片列表ã€? * @return {Array} 工作表列表ã€? */ buildCompletionReportSheets({ receiving, operator = {}, @@ -3521,7 +3384,7 @@ class ReceivingService extends Service { const detailColumns = [ '序号', '商品名称', '条码', '数量', '重量', '箱数', '托数', - '批次号', '生产日期', '到期日期', '备注', '图片链接', '图片', + '批次å�?, '生产日期', '到期日期', '备注', '图片链接', '图片', ]; const detailImageColumnIndex = detailColumns.length; const maxDetailImageCount = Math.max( @@ -3582,10 +3445,10 @@ class ReceivingService extends Service { [ '总明细数', stats.total_details || details.length ], [ '已匹配明细数', stats.matched_details || 0 ], [ '未匹配明细数', stats.unmatched_details || 0 ], - [ '总数量', stats.total_quantity || 0 ], - [ '总箱数', receiving && receiving.total_boxes ], + [ '总数é‡?, stats.total_quantity || 0 ], + [ '总箱æ•?, receiving && receiving.total_boxes ], [ '总托盘数', receiving && receiving.total_pallets ], - [ '完成人', operator.employees_name || operator.real_name || operator.name || '' ], + [ '完成äº?, operator.employees_name || operator.real_name || operator.name || '' ], [ '完成时间', this.formatReportDate(receiving && receiving.receiving_end_time) ], [ '备注', receiving && receiving.remark ], ].forEach(([ field, value ]) => { @@ -3598,7 +3461,7 @@ class ReceivingService extends Service { }); if (mainImageUrls.length === 0) { - pushReportRow([ '收货图片', '无' ], { + pushReportRow([ '收货图片', 'æ—? ], { toCol: 2, style: { alignment: { vertical: 'top', wrapText: true }, @@ -3644,7 +3507,7 @@ class ReceivingService extends Service { }); if (details.length === 0) { - pushReportRow([ '', '', '无明细' ], { + pushReportRow([ '', '', '无明ç»? ], { toCol: detailColumns.length, style: { alignment: { vertical: 'top', wrapText: true }, @@ -3731,7 +3594,7 @@ class ReceivingService extends Service { const receivingNumber = String(receiving.receiving_number || receiving.id).replace(/[\\/:*?"<>|]/g, '_'); return await excelService.generateAndUpload({ - filename: `收货明细(已完成收货)_${receivingNumber}.xlsx`, + filename: `收货明细(已完成收è´?_${receivingNumber}.xlsx`, dir: `exports/receiving/completed/${ctx.user.store_id || receiving.warehouse_id || 'common'}`, category: 'document', saveRecord: true, @@ -3749,13 +3612,10 @@ class ReceivingService extends Service { } /** - * 发送收货完成统一通知,通知外部订阅 `receiving_completed` 事件。 - * @param {Object} options 通知参数 - * @param {Object} options.receiving 收货单快照 - * @param {Object} [options.operator={}] 操作人信息 - * @param {Object} [options.stats={}] 收货统计 + * 发送收货完成统一通知,通知外部订阅 `receiving_completed` 事件ã€? * @param {Object} options 通知参数 + * @param {Object} options.receiving 收货单快ç…? * @param {Object} [options.operator={}] 操作人信æ�? * @param {Object} [options.stats={}] 收货统计 * @param {Object|null} [options.completionReport=null] 完成报表信息 - * @return {Promise} 通知发送结果,若条件不满足则返回 null + * @return {Promise} 通知发送结果,若条件不满足则返å›?null */ async sendCompletionNotice({ receiving, @@ -3806,28 +3666,28 @@ class ReceivingService extends Service { })); const totalBoxRemainder = normalizedDetails.reduce((sum, item) => sum + Number(item.box_remainder || 0), 0); const totalBoxWeight = normalizedDetails.reduce((sum, item) => sum + Number(item.box_weight || 0), 0); - const title = `收货单${receivingNumber}已完成`; - const contactLines = this.getCompletionContactFields(receiving).map(([ field, value ]) => `${field}:${value || '无'}`); + const title = `收货å�?{receivingNumber}已完成`; + const contactLines = this.getCompletionContactFields(receiving).map(([ field, value ]) => `${field}ï¼?{value || 'æ—?}`); const content = [ - `收货单号:${receivingNumber} 已完成`, - `货主:${receiving.store_name || '未知'}`, - `来货方式:${this.formatDeliveryMethod(receiving.delivery_method) || '未知'}`, + `收货单号ï¼?{receivingNumber} 已完成`, + `货主ï¼?{receiving.store_name || '未知'}`, + `来货方式ï¼?{this.formatDeliveryMethod(receiving.delivery_method) || '未知'}`, ...contactLines, - `总明细数:${Number(stats.total_details || 0)}件`, - `匹配商品:${matchedDetails}件`, + `总明细数ï¼?{Number(stats.total_details || 0)}件`, + `匹配商品ï¼?{matchedDetails}件`, `未匹配商品:${unmatchedDetails}件`, `总数量:${totalQuantity}`, `总箱数:${receiving.total_boxes || 0}`, - `总箱余数:${totalBoxRemainder}`, + `总箱余数ï¼?{totalBoxRemainder}`, `总箱重:${totalBoxWeight}`, - `总托盘数:${receiving.total_pallets || 0}`, + `总托盘数ï¼?{receiving.total_pallets || 0}`, operatorName ? `完成人:${operatorName}` : '', `开始时间:${this.formatReportDate(receiving.created_at)}`, - `完成时间:${this.formatReportDate(receiving.receiving_end_time)}`, - `备注:${receiving.remark || '无'}`, + `完成时间ï¼?{this.formatReportDate(receiving.receiving_end_time)}`, + `备注ï¼?{receiving.remark || 'æ—?}`, `快速查看:${ctx.app.config.frontendUrl || ''}/storage/receiving?id=${receivingNumber}`, // 替换为实际的前端地址 - ].filter(Boolean).join('\n') + '。'; + ].filter(Boolean).join('\n') + 'ã€?; return await noticeService.send({ warehouseId, @@ -3875,9 +3735,7 @@ class ReceivingService extends Service { } /** - * 完成收货单:校验明细、更新状态并写入库存。 - * @param {Object} data 请求体 - * @param {number} data.id 收货单ID + * 完成收货单:校验明细、更新状态并写入库存ã€? * @param {Object} data 请求ä½? * @param {number} data.id 收货单ID * @param {string} [data.remark] 完成备注 * @return {Promise} 完成结果 */ @@ -3930,12 +3788,11 @@ class ReceivingService extends Service { await transaction.rollback(); return { code: 404, - message: '收货单不存在或已被删除', + message: '收货单不存在或已被删é™?, }; } - // 2. 状态检查 - if (receiving.status === 'completed') { + // 2. 状态检æŸ? if (receiving.status === 'completed') { await transaction.rollback(); return { code: 200, @@ -3947,7 +3804,7 @@ class ReceivingService extends Service { await transaction.rollback(); return { code: 400, - message: '已作废的收货单不可完成', + message: '已作废的收货单不可完æˆ?, }; } @@ -3960,13 +3817,12 @@ class ReceivingService extends Service { }; } - // 4. 校验明细数量:不允许存在数量为 0 的明细 - const zeroQuantityDetails = receiving.details.filter(d => Number(d.actual_quantity || 0) <= 0); + // 4. 校验明细数量:不允许存在数量ä¸?0 的明ç»? const zeroQuantityDetails = receiving.details.filter(d => Number(d.actual_quantity || 0) <= 0); if (zeroQuantityDetails.length > 0) { await transaction.rollback(); const errorMsg = zeroQuantityDetails.length === 1 - ? `商品“${zeroQuantityDetails[0].product_name || '未命名商品'}”的数量为0,请填写实际收货数量` - : `有${zeroQuantityDetails.length}个商品数量为0,请填写实际收货数量`; + ? `商品â€?{zeroQuantityDetails[0].product_name || '未命名商å“?}”的数量ä¸?,请填写实际收货数量` + : `æœ?{zeroQuantityDetails.length}个商品数量为0,请填写实际收货数量`; return { success: false, code: 'DETAIL_QUANTITY_ZERO', @@ -3974,7 +3830,7 @@ class ReceivingService extends Service { data: { invalid_details: zeroQuantityDetails.map(d => ({ detail_id: d.id, - item_name: d.product_name || '未命名商品', + item_name: d.product_name || '未命名商å“?, actual_quantity: Number(d.actual_quantity || 0), })), }, @@ -3989,11 +3845,11 @@ class ReceivingService extends Service { return { success: false, code: 'BATCH_NUMBER_REQUIRED', - message: '批次管理商品必须填写批次号', + message: '批次管理商品必须填写批次å�?, data: { invalid_details: missingBatchNumberDetails.map(detail => ({ detail_id: detail.id, - item_name: detail.product_name || detail.system_product?.item_name || '未命名商品', + item_name: detail.product_name || detail.system_product?.item_name || '未命名商å“?, batch_number: detail.batch_number || '', production_date: detail.production_date || null, expiry_date: detail.expiry_date || null, @@ -4013,7 +3869,7 @@ class ReceivingService extends Service { data: { invalid_details: missingBatchDetails.map(detail => ({ detail_id: detail.id, - item_name: detail.product_name || detail.system_product?.item_name || '未命名商品', + item_name: detail.product_name || detail.system_product?.item_name || '未命名商å“?, batch_number: detail.batch_number || '', production_date: detail.production_date || null, expiry_date: detail.expiry_date || null, @@ -4041,11 +3897,11 @@ class ReceivingService extends Service { return { success: false, code: 'EXPIRY_DATE_TOO_SOON', - message: `商品“${firstInvalid.product_name || firstInvalid.system_product?.item_name || '未命名商品'}”的有效期不足最小允许收货天数(${minReceiveDays}天),无法完成收货`, + message: `商品â€?{firstInvalid.product_name || firstInvalid.system_product?.item_name || '未命名商å“?}”的有效期不足最小允许收货天数(${minReceiveDays}天),无法完成收货`, data: { invalid_details: invalidExpiryDetails.map(detail => ({ detail_id: detail.id, - item_name: detail.product_name || detail.system_product?.item_name || '未命名商品', + item_name: detail.product_name || detail.system_product?.item_name || '未命名商å“?, batch_number: detail.batch_number || '', production_date: detail.production_date || null, expiry_date: detail.expiry_date || null, @@ -4055,8 +3911,7 @@ class ReceivingService extends Service { }; } - // 5. 准备明细图片与统计信息(照片/条码/重量不再强制要求) - const unmatchedDetails = receiving.details.filter(d => !d.system_product_id); + // 5. 准备明细图片与统计信息(照片/条码/重量不再强制要求ï¼? const unmatchedDetails = receiving.details.filter(d => !d.system_product_id); const detailsIds = receiving.details.map(item => item.id); const images = await ctx.model.FileReference.findAll({ @@ -4089,11 +3944,9 @@ class ReceivingService extends Service { }); }); - // 5. 获取操作人信息 - const operator = ctx.user; + // 5. 获取操作人信æ�? const operator = ctx.user; - // 8. 更新收货单状态 - const now = new Date(); + // 8. 更新收货单状æ€? const now = new Date(); const updateData = { status: 'completed', receiving_end_time: now, @@ -4102,10 +3955,10 @@ class ReceivingService extends Service { if (remark) { const remarkPrefix = receiving.remark ? `${receiving.remark}\n` : ''; - updateData.remark = `${remarkPrefix}【完成收货】${now.toLocaleString()} ${operator.employees_name} ${remark}`; + updateData.remark = `${remarkPrefix}【完成收货ã€?{now.toLocaleString()} ${operator.employees_name} ${remark}`; } else { const remarkPrefix = receiving.remark ? `${receiving.remark}\n` : ''; - updateData.remark = `${remarkPrefix}【完成收货】${now.toLocaleString()} ${operator.employees_name}`; + updateData.remark = `${remarkPrefix}【完成收货ã€?{now.toLocaleString()} ${operator.employees_name}`; } await ctx.model.Receiving.update(updateData, { @@ -4127,7 +3980,7 @@ class ReceivingService extends Service { // 10.1 清除收货单缓存,确保下次入库完成时匹配到最新收货单列表 const receivingCacheKey = `cache:receiving_orders:warehouse:${warehouseId}`; app.delCacheAsync(receivingCacheKey).catch(cacheErr => { - ctx.logger.warn(`[receiving.completeReceiving] 清除收货单缓存失败: ${cacheErr.message}`, { cacheKey: receivingCacheKey }); + ctx.logger.warn(`[receiving.completeReceiving] 清除收货单缓存失è´? ${cacheErr.message}`, { cacheKey: receivingCacheKey }); }); // 记录操作日志 @@ -4163,8 +4016,7 @@ class ReceivingService extends Service { stats, }; - // 11. 收货成功后先触发文字通知,再生成 Excel;若 Excel 成功,再补发文件通知。 - try { + // 11. 收货成功后先触发文字通知,再生成 Excel;若 Excel 成功,再补发文件通知ã€? try { const textNoticeResult = await this.sendCompletionNotice(completionNoticePayload); ctx.logger.info('收货完成文字通知结果', { receiving_id: id, @@ -4177,7 +4029,7 @@ class ReceivingService extends Service { failedCount: Number(textNoticeResult && textNoticeResult.data && textNoticeResult.data.failedCount || 0), }); } catch (notifyError) { - ctx.logger.error(`收货完成文字通知发送失败: ${notifyError.message}`, { + ctx.logger.error(`收货完成文字通知发送失è´? ${notifyError.message}`, { receiving_id: id, warehouseId, error: notifyError.stack, @@ -4242,27 +4094,21 @@ class ReceivingService extends Service { } /** - * 收货完成后异步补全商品资料:绑定图片、补填毛重。 - * + * 收货完成后异步补全商品资料:绑定图片、补填毛重ã€? * * 遍历当前收货单所有已绑定系统商品的明细: - * 1. 若商品 is_images === 'N' 且该明细有收货图片,则将收货图片复制为商品图片(FileReference), - * 并将商品的 is_images 更新为 'Y'。 - * 2. 若商品 gross_weight 为 0 或 null,且明细的 weight > 0,则将商品毛重更新为该明细的 weight。 - * - * 本方法通过 setImmediate 调用,运行在事务提交后,任何异常只记录日志,不影响主进程。 - * + * 1. 若商å“?is_images === 'N' 且该明细有收货图片,则将收货图片复制为商品图片(FileReference), + * 并将商品çš?is_images 更新ä¸?'Y'ã€? * 2. 若商å“?gross_weight ä¸?0 æˆ?null,且明细çš?weight > 0,则将商品毛重更新为该明细的 weightã€? * + * 本方法通过 setImmediate 调用,运行在事务提交后,任何异常只记录日志,不影响主进程ã€? * * @param {Object} options 参数对象 - * @param {number} options.receivingId 收货单 ID + * @param {number} options.receivingId 收货å�?ID * @param {number} options.warehouseId 仓库 ID - * @param {Array} options.details 收货明细数组(来自 completeReceiving 中已加载的 details) - * @return {Promise} + * @param {Array} options.details 收货明细数组(来è‡?completeReceiving 中已加载çš?detailsï¼? * @return {Promise} */ async _syncProductDataFromReceiving({ receivingId, warehouseId, details }) { - console.log('_syncProductDataFromReceiving异步执行中...'); // 调试日志 + console.log('_syncProductDataFromReceiving异步执行ä¸?..'); // 调试日志 const { ctx, app } = this; - // 只处理已绑定系统商品的明细 - const boundDetails = (Array.isArray(details) ? details : []).filter( + // 只处理已绑定系统商品的明ç»? const boundDetails = (Array.isArray(details) ? details : []).filter( d => d && Number(d.system_product_id) > 0 ); @@ -4296,7 +4142,7 @@ class ReceivingService extends Service { }); if (detailImageRefs.length > 0) { - // 查询商品已有的图片 file_id(避免重复) + // 查询商品已有的图ç‰?file_id(避免重复) const existingStockImageFileIds = await app.model.FileReference.findAll({ where: { business_type: 'stock', @@ -4330,7 +4176,7 @@ class ReceivingService extends Service { ); ctx.logger.info( - `[_syncProductDataFromReceiving] 商品 ${systemProductId} 已补全图片,共复制 ${toCreate.length} 张(收货单 ${receivingId} 明细 ${detail.id})` + `[_syncProductDataFromReceiving] 商品 ${systemProductId} 已补全图片,共复åˆ?${toCreate.length} 张(收货å�?${receivingId} 明细 ${detail.id})` ); } @@ -4344,12 +4190,11 @@ class ReceivingService extends Service { ); ctx.logger.info( - `[_syncProductDataFromReceiving] 商品 ${systemProductId} 已补全毛重 ${detailWeight}(收货单 ${receivingId} 明细 ${detail.id})` + `[_syncProductDataFromReceiving] 商品 ${systemProductId} 已补全毛é‡?${detailWeight}(收货单 ${receivingId} 明细 ${detail.id})` ); } } catch (err) { - // 单条明细失败不中断后续处理 - console.log( + // 单条明细失败不中断后续处ç�? console.log( `[_syncProductDataFromReceiving] 处理明细 ${detail.id} (商品 ${systemProductId}) 失败: ${err.message}` ); } @@ -4357,19 +4202,8 @@ class ReceivingService extends Service { } /** - * PDA 扫码定位收货明细:通过入库单ID + 扫描条码快速定位收货明细。 - * 搜索策略: - * 1. 通过 entry_order_id → wms_entry_order_receiving 查出关联的 receiving_id 列表; - * 2. 查出所有未绑定的收货明细(仅按 receiving_id IN + 排除已绑定过滤); - * 3. 收集明细的 system_product_id,批量调用 getStockDetails 获取条码信息; - * 4. 在内存中遍历明细进行精确匹配: - * - 若 barcode 为纯数字,优先按明细 ID 精确匹配; - * - 再按 getStockDetails 返回的 barcodes[].barcode 精确匹配商品条码; - * 5. 返回所有匹配的明细列表(同一条码可能匹配到多条收货明细)。 - * @param {number} entryOrderId 入库单ID - * @param {string} barcode 扫描条码(商品条码/箱唛/托盘唛/明细ID) - * @return {Promise} 包含 code、message 与匹配明细列表 data.list 的结果对象 - */ + * PDA 扫码定位收货明细:通过入库单ID + 扫描条码快速定位收货明细ã€? * 搜索策略ï¼? * 1. 通过 entry_order_id â†?wms_entry_order_receiving 查出关联çš?receiving_id 列表ï¼? * 2. 查出所有未绑定的收货明细(仅按 receiving_id IN + 排除已绑定过滤)ï¼? * 3. 收集明细çš?system_product_id,批量调ç”?getStockDetails 获取条码信息ï¼? * 4. 在内存中遍历明细进行精确匹配ï¼? * - è‹?barcode 为纯数字,优先按明细 ID 精确匹配ï¼? * - 再按 getStockDetails 返回çš?barcodes[].barcode 精确匹配商品条码ï¼? * 5. 返回所有匹配的明细列表(同一条码可能匹配到多条收货明细)ã€? * @param {number} entryOrderId 入库单ID + * @param {string} barcode 扫描条码(商品条ç ?箱唛/托盘å”?明细IDï¼? * @return {Promise} 包含 code、message 与匹配明细列è¡?data.list 的结果对è±? */ async scanDetail(entryOrderId, barcode) { const { ctx, app } = this; const { Op } = app.Sequelize; @@ -4377,7 +4211,7 @@ class ReceivingService extends Service { // 参数校验 if (!warehouseId) { - return { code: 0, message: '用户未绑定仓库', data: null }; + return { code: 0, message: '用户未绑定仓åº?, data: null }; } if (!entryOrderId || Number(entryOrderId) <= 0) { return { code: 0, message: '入库单ID不能为空', data: null }; @@ -4401,10 +4235,10 @@ class ReceivingService extends Service { }); if (!entryOrder) { - return { code: 0, message: '入库单不存在或无权访问', data: null }; + return { code: 0, message: '入库单不存在或无权访é—?, data: null }; } - // 2. 通过 wms_entry_order_receiving 查出关联的 receiving_id 列表 + // 2. 通过 wms_entry_order_receiving 查出关联çš?receiving_id 列表 const entryReceivingRows = await ctx.model.EntryOrderReceiving.findAll({ where: { entry_order_id: normalizedEntryOrderId }, attributes: [ 'receiving_id' ], @@ -4413,7 +4247,7 @@ class ReceivingService extends Service { const receivingIds = entryReceivingRows.map(r => r.receiving_id).filter(Boolean); if (receivingIds.length === 0) { - return { code: 0, message: '该入库单尚未关联收货单', data: null }; + return { code: 0, message: '该入库单尚未关联收货å�?, data: null }; } // 排除已绑定的收货明细(wms_inbound_direct_log 中有记录且未软删除) @@ -4421,8 +4255,7 @@ class ReceivingService extends Service { 'NOT EXISTS (SELECT 1 FROM wms_inbound_direct_log erb WHERE erb.receiving_detail_id = wms_receiving_detail.id AND erb.deleted_at IS NULL)' ); - // 3. 查出所有未绑定的收货明细(不再在 SQL 层做 barcode 模糊匹配) - const details = await ctx.model.ReceivingDetail.findAll({ + // 3. 查出所有未绑定的收货明细(不再åœ?SQL 层做 barcode 模糊匹配ï¼? const details = await ctx.model.ReceivingDetail.findAll({ where: { [Op.and]: [ { receiving_id: { [Op.in]: receivingIds } }, @@ -4436,7 +4269,7 @@ class ReceivingService extends Service { return { code: 0, message: '未找到可用的收货明细', data: null }; } - // 4. 收集所有明细的 system_product_id,批量调用 getStockDetails 获取条码 + // 4. 收集所有明细的 system_product_id,批量调ç”?getStockDetails 获取条码 const stockIdSet = new Set(); for (const d of details) { if (d.system_product_id != null) { @@ -4456,19 +4289,17 @@ class ReceivingService extends Service { } } - // 5. 在内存中遍历明细,精确匹配,收集所有命中 - const isNumericBarcode = /^\d+$/.test(normalizedBarcode); + // 5. 在内存中遍历明细,精确匹配,收集所有命ä¸? const isNumericBarcode = /^\d+$/.test(normalizedBarcode); const matchedDetails = []; for (const detail of details) { - // 优先按明细 ID 精确匹配(托盘唛头场景) + // 优先按明ç»?ID 精确匹配(托盘唛头场景) if (isNumericBarcode && detail.id === Number(normalizedBarcode)) { matchedDetails.push(detail); continue; } - // 按商品条码精确匹配 - const stockDetail = stockDetailMap.get(detail.system_product_id); + // 按商品条码精确匹é…? const stockDetail = stockDetailMap.get(detail.system_product_id); if (stockDetail && Array.isArray(stockDetail.barcodes)) { const barcodeMatch = stockDetail.barcodes.some( bc => bc.barcode === normalizedBarcode @@ -4503,7 +4334,7 @@ class ReceivingService extends Service { }; } catch (error) { ctx.logger.error('[receiving.scanDetail] 扫码定位收货明细失败', error); - return { code: 500, message: `服务器错误: ${error.message}`, data: null }; + return { code: 500, message: `服务器错è¯? ${error.message}`, data: null }; } } diff --git a/app/service/systems/store.js b/app/service/systems/store.js index dff7cff..50ddba7 100644 --- a/app/service/systems/store.js +++ b/app/service/systems/store.js @@ -950,7 +950,7 @@ class StoreService extends Service { try { const stores = await ctx.model.StoreWarehouse.findAll({ where: { - use_status: 1, + warehouse_use_status: 1, warehouse_id: ctx.user.store_id, }, attributes: [ diff --git a/app/service/systems/store_warehouse.js b/app/service/systems/store_warehouse.js index d6955f4..e64fd0d 100644 --- a/app/service/systems/store_warehouse.js +++ b/app/service/systems/store_warehouse.js @@ -923,9 +923,9 @@ class SettingStoreWarehouseService extends Service { where.auth_status = authStatus; } - const useStatus = this.normalizeStatusFlag(data.use_status, 'use_status', null); + const useStatus = this.normalizeStatusFlag(data.use_status || data.warehouse_use_status, 'warehouse_use_status', null); if (useStatus !== null) { - where.use_status = useStatus; + where.warehouse_use_status = useStatus; } return where; @@ -1334,7 +1334,8 @@ class SettingStoreWarehouseService extends Service { reviewed_by: item.reviewed_by ? Number(item.reviewed_by) : null, ended_by: item.ended_by ? Number(item.ended_by) : null, remask: currentIsWarehouse ? (item.store_remask || '') : (item.warehouse_remask || ''), - use_status: Number(item.use_status || 0), + warehouse_use_status: Number(item.warehouse_use_status || 0), + store_use_status: Number(item.store_use_status || 0), policy_config: item.policy_config && typeof item.policy_config === 'object' ? item.policy_config : null, is_auth_valid: isAuthValid, remaining_days: remainingDays, @@ -1490,7 +1491,8 @@ class SettingStoreWarehouseService extends Service { applied_by: Number(payload.initiated_by || 0) || accountId, reviewed_by: accountId, ended_by: null, - use_status: 1, + warehouse_use_status: 1, + store_use_status: 1, }; if (payload.store_remask !== undefined) { @@ -2395,11 +2397,12 @@ class SettingStoreWarehouseService extends Service { try { const currentSubject = await this.getCurrentSubject(); const relation = await this.findScopedRelation(data, currentSubject, transaction); - const nextUseStatus = this.normalizeStatusFlag(data.use_status, 'use_status', 0); + const nextUseStatus = this.normalizeStatusFlag(data.use_status || data.warehouse_use_status, 'warehouse_use_status', 0); + const patch = currentSubject.isWarehouse + ? { warehouse_use_status: nextUseStatus } + : { store_use_status: nextUseStatus }; - await relation.update({ - use_status: nextUseStatus, - }, { transaction }); + await relation.update(patch, { transaction }); const result = await ctx.model.StoreWarehouse.findByPk(relation.id, { include: this.getRelationIncludes(), @@ -2669,7 +2672,8 @@ class SettingStoreWarehouseService extends Service { applied_by: accountId, reviewed_by: accountId, ended_by: null, - use_status: 1, + warehouse_use_status: 1, + store_use_status: 1, }; if (storeRemask !== null) { diff --git a/database/migrations/20260706-rename-use-status-and-add-store-use-status.js b/database/migrations/20260706-rename-use-status-and-add-store-use-status.js new file mode 100644 index 0000000..beee4a0 --- /dev/null +++ b/database/migrations/20260706-rename-use-status-and-add-store-use-status.js @@ -0,0 +1,25 @@ +'use strict'; + +/** + * 将 wms_store_warehouse.use_status 重命名为 warehouse_use_status, + * 并新增 store_use_status 供货主端独立控制使用状态。 + */ +module.exports = { + async up(queryInterface) { + const { sequelize } = queryInterface; + await sequelize.query(` + ALTER TABLE wms_store_warehouse + CHANGE COLUMN use_status warehouse_use_status INT(1) NOT NULL DEFAULT 1 COMMENT '仓库侧使用状态:0-不可用,1-可用', + ADD COLUMN store_use_status INT(1) NOT NULL DEFAULT 1 COMMENT '货主侧使用状态:0-不可用,1-可用' AFTER warehouse_use_status + `); + }, + + async down(queryInterface) { + const { sequelize } = queryInterface; + await sequelize.query(` + ALTER TABLE wms_store_warehouse + DROP COLUMN store_use_status, + CHANGE COLUMN warehouse_use_status use_status INT(1) NOT NULL DEFAULT 1 COMMENT '使用状态,0-不可用,1-可用(SKU可见,货主可见,即使解约了)' + `); + }, +}; diff --git a/methods/system.json b/methods/system.json index 4aba6dc..9898df7 100644 --- a/methods/system.json +++ b/methods/system.json @@ -22801,9 +22801,14 @@ "description": "备注名(当前为仓库则返回货主备注名,反之亦然)" }, { - "name": "data.list[].use_status", + "name": "data.list[].warehouse_use_status", "type": "number", - "description": "启用状态:0=禁用 1=启用" + "description": "仓库侧启用状态:0=禁用 1=启用" + }, + { + "name": "data.list[].store_use_status", + "type": "number", + "description": "货主侧启用状态:0=禁用 1=启用" }, { "name": "data.list[].policy_config", @@ -22944,11 +22949,11 @@ "description": "签约关系ID,兼容 contract_id" }, { - "name": "use_status", + "name": "warehouse_use_status", "type": "number", "required": false, "source": "body", - "description": "使用状态,0=停用,1=恢复" + "description": "仓库侧使用状态,0=停用,1=恢复" } ], "response": [], From d1818ae0bf35bf562f997c7ed815b0568fdfd727 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 6 Jul 2026 22:19:34 +0800 Subject: [PATCH 098/550] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=20receiving.j?= =?UTF-8?q?s=20=E7=BC=96=E7=A0=81=E6=8D=9F=E5=9D=8F=E5=AF=BC=E8=87=B4?= =?UTF-8?q?=E8=AF=AD=E6=B3=95=E9=94=99=E8=AF=AF=EF=BC=88use=5Fstatus=20?= =?UTF-8?q?=E2=86=92=20warehouse=5Fuse=5Fstatus=20=E9=87=8D=E5=81=9A?= =?UTF-8?q?=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/systems/storage/receiving.js | 665 ++++++++++++++--------- 1 file changed, 417 insertions(+), 248 deletions(-) diff --git a/app/service/systems/storage/receiving.js b/app/service/systems/storage/receiving.js index c8232af..9817c79 100644 --- a/app/service/systems/storage/receiving.js +++ b/app/service/systems/storage/receiving.js @@ -12,9 +12,11 @@ function getStartOfDayMs(value) { } /** - * 判断到期日期是否早于当前日期ã€? * @param {string|Date|number} expiryDate 到期日期 + * 判断到期日期是否早于当前日期。 + * @param {string|Date|number} expiryDate 到期日期 * @param {Date} [currentDate=new Date()] 当前日期 - * @return {boolean} 是否已过æœ? */ + * @return {boolean} 是否已过期 + */ function isExpiryDateBeforeToday(expiryDate, currentDate = new Date()) { const expiryStartMs = getStartOfDayMs(expiryDate); if (expiryStartMs === null) return false; @@ -27,14 +29,17 @@ function isExpiryDateBeforeToday(expiryDate, currentDate = new Date()) { class ReceivingService extends Service { /** - * 查询收货单列表ã€? * @param {Object} where 动态筛选条ä»? * @param {Object} [pageParams] 分页参数 + * 查询收货单列表。 + * @param {Object} where 动态筛选条件 + * @param {Object} [pageParams] 分页参数 * @param {number} [pageParams.page=1] 页码 * @param {number} [pageParams.pageSize=20] 每页条数 * @param {Object} [sortParams] 排序参数 * @param {Object} [options] 额外选项 * @param {boolean} [options.filterDepleted=false] 是否过滤掉无可再用量的收货单 - * @param {number} [options.entry_order_id] 可选,按入库单商品交集过滤:只返回"至少有一条明细的 system_product_id 在入库单明细ä¸?的收货单 - * @return {Promise} 列表、分页与汇总信æ�? */ + * @param {number} [options.entry_order_id] 可选,按入库单商品交集过滤:只返回"至少有一条明细的 system_product_id 在入库单明细中"的收货单 + * @return {Promise} 列表、分页与汇总信息 + */ async getReceivingList(where, pageParams = {}, sortParams = {}, options = {}) { const { ctx, @@ -108,7 +113,7 @@ class ReceivingService extends Service { total_items: 0, }, }, - message: `筛选条件解析失è´? ${parsed.reason}`, + message: `筛选条件解析失败: ${parsed.reason}`, }; } parsedResult = parsed.result; @@ -174,7 +179,8 @@ class ReceivingService extends Service { }, ]; - // 可选过滤:排除无可再用量的收货å�? let filteredReceivingIds = null; + // 可选过滤:排除无可再用量的收货单 + let filteredReceivingIds = null; if (filterDepleted) { const candidateRows = await ctx.model.Receiving.findAll({ attributes: [ 'id' ], @@ -186,7 +192,8 @@ class ReceivingService extends Service { const candidateIds = candidateRows.map(r => r.id); if (candidateIds.length > 0) { - // 1. 候选收货单明细çš?actual_quantity 总和(按 receiving_id 分组ï¼? const detailSums = await ctx.model.ReceivingDetail.findAll({ + // 1. 候选收货单明细的 actual_quantity 总和(按 receiving_id 分组) + const detailSums = await ctx.model.ReceivingDetail.findAll({ attributes: [ 'receiving_id', [ Sequelize.fn('SUM', Sequelize.col('actual_quantity')), 'total_actual' ], @@ -200,7 +207,8 @@ class ReceivingService extends Service { totalActualMap[row.receiving_id] = Number(row.total_actual) || 0; } - // 2. 这些明细对应çš?committed 绑定量(æŒ?receiving_detail_id 分组ï¼? const detailIds = detailSums.length > 0 + // 2. 这些明细对应的 committed 绑定量(按 receiving_detail_id 分组) + const detailIds = detailSums.length > 0 ? (await ctx.model.ReceivingDetail.findAll({ attributes: [ 'id' ], where: { receiving_id: { [Op.in]: candidateIds } }, @@ -227,7 +235,7 @@ class ReceivingService extends Service { } } - // 3. 计算每个收货单的剩余可用é‡?= SUM(actual_quantity) - SUM(committed) + // 3. 计算每个收货单的剩余可用量 = SUM(actual_quantity) - SUM(committed) const idToDetailIdsMap = {}; if (detailIds.length > 0) { const detailIdRows = await ctx.model.ReceivingDetail.findAll({ @@ -249,7 +257,7 @@ class ReceivingService extends Service { remainingByReceivingId[receivingId] = totalActual - totalCommitted; } - // 过滤:只保留剩余可用é‡?> 0 的收货单 + // 过滤:只保留剩余可用量 > 0 的收货单 filteredReceivingIds = candidateIds.filter(id => remainingByReceivingId[id] > 0); } else { filteredReceivingIds = []; @@ -259,7 +267,7 @@ class ReceivingService extends Service { // 可选过滤:按入库单商品交集过滤(只返回 system_product_id 有交集的收货单) let intersectionFilteredIds = null; if (entryOrderId) { - // 1. 查该入库单的所æœ?entry_items â†?stock_id 集合 + // 1. 查该入库单的所有 entry_items → stock_id 集合 const entryItemRows = await ctx.model.EntryItems.findAll({ where: { order_id: entryOrderId }, attributes: [ 'stock_id' ], @@ -268,10 +276,10 @@ class ReceivingService extends Service { const entrySpIdSet = new Set(entryItemRows.map(r => r.stock_id).filter(Boolean)); if (entrySpIdSet.size === 0) { - // 入库单无明细 â†?不返回任何收货单 + // 入库单无明细 → 不返回任何收货单 intersectionFilteredIds = []; } else { - // 2. 查所有收货单明细,找å‡?system_product_id åœ?entrySpIdSet 中的收货å�?ID + // 2. 查所有收货单明细,找出 system_product_id 在 entrySpIdSet 中的收货单 ID const matchingDetailRows = await ctx.model.ReceivingDetail.findAll({ attributes: [ 'receiving_id' ], where: { @@ -284,10 +292,12 @@ class ReceivingService extends Service { } } - // 合并 filterDepleted å’?entry_order_id 的过滤结æž? let combinedFilteredIds = null; + // 合并 filterDepleted 和 entry_order_id 的过滤结果 + let combinedFilteredIds = null; if (filteredReceivingIds !== null || intersectionFilteredIds !== null) { if (filteredReceivingIds !== null && intersectionFilteredIds !== null) { - // 两个过滤都启ç”?â†?取交é›? const intersectionSet = new Set(intersectionFilteredIds); + // 两个过滤都启用 → 取交集 + const intersectionSet = new Set(intersectionFilteredIds); combinedFilteredIds = filteredReceivingIds.filter(id => intersectionSet.has(id)); } else if (filteredReceivingIds !== null) { combinedFilteredIds = filteredReceivingIds; @@ -296,7 +306,8 @@ class ReceivingService extends Service { } } - // 如果启用了过滤,用过滤后çš?ID 做最终查è¯? const finalWhere = combinedFilteredIds !== null + // 如果启用了过滤,用过滤后的 ID 做最终查询 + const finalWhere = combinedFilteredIds !== null ? { id: { [Op.in]: combinedFilteredIds } } : queryOptions.where; @@ -343,7 +354,8 @@ class ReceivingService extends Service { } const processedData = data.map(item => { - // 注意:wms_receiving 表中没有 locked_quantity 字段,total_quantity 为商品总数é‡? const availableQuantity = Math.max(0, item.total_quantity || 0); + // 注意:wms_receiving 表中没有 locked_quantity 字段,total_quantity 为商品总数量 + const availableQuantity = Math.max(0, item.total_quantity || 0); const lockRate = 0; const itemImages = images .filter(row => parseInt(row.business_id) === item.id) @@ -414,25 +426,30 @@ class ReceivingService extends Service { } } /** - * 获取收货单详情(主单 + 明细分页 + 图片)ã€? * @param {Object} data 请求ä½? * @param {number} data.id 收货单ID + * 获取收货单详情(主单 + 明细分页 + 图片)。 + * @param {Object} data 请求体 + * @param {number} data.id 收货单ID * @param {Object} data.pagination 分页参数 - * @return {Promise} 详情数据,明细中çš?space_id 会优先展示自定义库位名称,其次展示库位编码,并补å…?space_id_raw 兼容原始ID + * @return {Promise} 详情数据,明细中的 space_id 会优先展示自定义库位名称,其次展示库位编码,并补充 space_id_raw 兼容原始ID */ async getReceivingDetail(data) { const { id, pagination } = data; const { page, pageSize } = pagination; const { ctx, app } = this; const { Op } = app.Sequelize; - // 获取用户仓库ID,增加错误处ç�? const warehouseId = ctx.user?.store_id; + // 获取用户仓库ID,增加错误处理 + const warehouseId = ctx.user?.store_id; if (!warehouseId) { - return { code: 0, message: '用户未绑定仓åº?, data: {} }; + return { code: 0, message: '用户未绑定仓库', data: {} }; } try { - // 1. 查询收货单主è¡? const receiving = await app.model.Receiving.findOne({ where: { id, warehouse_id: warehouseId } }); + // 1. 查询收货单主表 + const receiving = await app.model.Receiving.findOne({ where: { id, warehouse_id: warehouseId } }); if (!receiving) { return { code: 0, message: '无记录或无权访问', data: {} }; } - // 2. 查询收货单明ç»?按分é¡? const receivingItems = await app.model.ReceivingDetail.findAll({ + // 2. 查询收货单明细,按分页 + const receivingItems = await app.model.ReceivingDetail.findAll({ where: { receiving_id: id }, include: [{ model: app.model.LocationSpace, @@ -457,7 +474,9 @@ class ReceivingService extends Service { // 3. 获取明细ID数组 const receivingItemsIds = receivingItems.map(item => item.id); - // 4. 查询明细图片(如果明细数量大äº?ï¼? const itemImagesMap = {}; // 用于存储每个明细的图ç‰? if (receivingItemsIds.length > 0) { + // 4. 查询明细图片(如果明细数量大于0) + const itemImagesMap = {}; // 用于存储每个明细的图片 + if (receivingItemsIds.length > 0) { const receivingItemsImages = await ctx.model.FileReference.findAll({ where: { business_type: 'receivingItem', @@ -470,7 +489,8 @@ class ReceivingService extends Service { required: true, }], }); - // 将图片按明细ID分组,并转换为前端可直接使用的链æŽ? for (const image of receivingItemsImages) { + // 将图片按明细ID分组,并转换为前端可直接使用的链接 + for (const image of receivingItemsImages) { if (!itemImagesMap[image.business_id]) { itemImagesMap[image.business_id] = []; } @@ -496,7 +516,8 @@ class ReceivingService extends Service { images: itemImagesMap[item.id] || [], }; }); - // 6. 查询主表的图ç‰? const receivingImages = await ctx.model.FileReference.findAll({ + // 6. 查询主表的图片 + const receivingImages = await ctx.model.FileReference.findAll({ where: { business_type: 'receiving', business_id: id, @@ -509,7 +530,8 @@ class ReceivingService extends Service { }], }); // 7. 组装返回数据 - receiving.dataValues.details = items; // 包含图片链接的明细数æ�? receiving.dataValues.images = receivingImages.map(image => ({ + receiving.dataValues.details = items; // 包含图片链接的明细数据 + receiving.dataValues.images = receivingImages.map(image => ({ id: image.file_id, url: image.file.file_url, })); // 包含主表图片链接 @@ -517,12 +539,14 @@ class ReceivingService extends Service { return { code: 200, message: '查询成功', data: { receiving } }; } catch (error) { - console.error('获取收货单详情失è´?', error); - return { code: 500, message: '服务器错è¯?, data: {} }; + console.error('获取收货单详情失败:', error); + return { code: 500, message: '服务器错误', data: {} }; } } /** - * 批量作废收货单ã€? * @param {Object} data 请求ä½? * @param {number[]} data.ids 收货单ID数组 + * 批量作废收货单。 + * @param {Object} data 请求体 + * @param {number[]} data.ids 收货单ID数组 * @return {Promise} 作废处理结果 */ async batchCancelReceiving(data) { @@ -531,7 +555,8 @@ class ReceivingService extends Service { const { Op } = ctx.model.Sequelize; const warehouse_id = ctx.user.store_id; try { - // 先查询这些单据是否都存在且状态允许作åº? const receivings = await ctx.model.Receiving.findAll({ where: { id: { [Op.in]: ids }, warehouse_id } }); + // 先查询这些单据是否都存在且状态允许作废 + const receivings = await ctx.model.Receiving.findAll({ where: { id: { [Op.in]: ids }, warehouse_id } }); if (receivings.length !== ids.length) { return { code: 0, message: '部分单据不存在或无权访问', data: {} }; } @@ -569,13 +594,16 @@ class ReceivingService extends Service { return { code: 200, message: '批量作废成功', data: {} }; } catch (error) { - console.error('批量作废收货单失è´?', error); - return { code: 500, message: '服务器错è¯?, data: {} }; + console.error('批量作废收货单失败:', error); + return { code: 500, message: '服务器错误', data: {} }; } } /** - * 驳回收货单:将已完成收货单恢复为收货中,记录审核人信息与驳回理由ã€? * @param {Object} data 请求ä½? * @param {number[]} data.ids 收货单ID数组 - * @param {string} [data.remark] 驳回理由(覆盖原备注ï¼? * @return {Promise} 操作结果 + * 驳回收货单:将已完成收货单恢复为收货中,记录审核人信息与驳回理由。 + * @param {Object} data 请求体 + * @param {number[]} data.ids 收货单ID数组 + * @param {string} [data.remark] 驳回理由(覆盖原备注) + * @return {Promise} 操作结果 */ async rejectReceiving(data) { const { ids, remark } = data; @@ -690,15 +718,15 @@ class ReceivingService extends Service { messageType: 'text', businessName: 'receiving', event: 'receiving_rejected', - title: `收货å�?${item.receiving_number || item.id} 已被驳回`, + title: `收货单 ${item.receiving_number || item.id} 已被驳回`, content: [ `驳回人:${reviewerName || '未知'}`, - `驳回理由ï¼?{updateData.remark || 'æ—?}`, - `收货单IDï¼?{item.id || ''}`, - `收货单号ï¼?{item.receiving_number || 'æ—?}`, - `收货创建人:${item.creator && item.creator.name || 'æ—?}`, - '请及时处理重新提交完成收货ã€?, - ].join('\n') + 'ã€?, + `驳回理由:${updateData.remark || '无'}`, + `收货单ID:${item.id || ''}`, + `收货单号:${item.receiving_number || '无'}`, + `收货创建人:${item.creator && item.creator.name || '无'}`, + '请及时处理重新提交完成收货。', + ].join('\n') + '。', businessId: item.id || ids[0], subject: { id: warehouse_id, @@ -731,13 +759,16 @@ class ReceivingService extends Service { return { code: 200, message: '驳回成功', data: { count: ids.length } }; } catch (error) { - ctx.logger.error('[receiving.rejectReceiving] 驳回收货单失è´?, error); - return { code: 500, message: '服务器错è¯?, data: {} }; + ctx.logger.error('[receiving.rejectReceiving] 驳回收货单失败', error); + return { code: 500, message: '服务器错误', data: {} }; } } /** - * 批量审核收货单:校验所有单据的状态后,用事务批量更新审核信息ã€? * 任意一张不符合条件则整批失败并回滚ã€? * @param {Object} data 请求ä½? * @param {number[]} data.ids 收货单ID数组 + * 批量审核收货单:校验所有单据的状态后,用事务批量更新审核信息。 + * 任意一张不符合条件则整批失败并回滚。 + * @param {Object} data 请求体 + * @param {number[]} data.ids 收货单ID数组 * @return {Promise} 操作结果 */ async reviewReceiving(data) { @@ -752,7 +783,7 @@ class ReceivingService extends Service { const normalizedIds = Array.from(new Set(ids.map(Number).filter(n => Number.isFinite(n) && n > 0))); if (normalizedIds.length === 0) { - return { code: 0, message: '收货单ID格式不正ç¡?, data: {} }; + return { code: 0, message: '收货单ID格式不正确', data: {} }; } const reviewerName = String(ctx.user?.employees_name || '').trim() || null; @@ -776,28 +807,29 @@ class ReceivingService extends Service { const errors = []; for (const r of receivings) { if (r.status !== 'completed') { - errors.push(`收货å�?${r.receiving_number || r.id} 状态非收货完成`); + errors.push(`收货单 ${r.receiving_number || r.id} 状态非收货完成`); } if (r.detail_status !== 'all_matched') { - errors.push(`收货å�?${r.receiving_number || r.id} 明细未全部匹配`); + errors.push(`收货单 ${r.receiving_number || r.id} 明细未全部匹配`); } if (r.storage_status !== 'none') { - errors.push(`收货å�?${r.receiving_number || r.id} 已存在入库记录`); + errors.push(`收货单 ${r.receiving_number || r.id} 已存在入库记录`); } if (!r.store_id) { - errors.push(`收货å�?${r.receiving_number || r.id} 未绑定货主`); + errors.push(`收货单 ${r.receiving_number || r.id} 未绑定货主`); } if (Number(r.is_review) === 1) { - errors.push(`收货å�?${r.receiving_number || r.id} 已审核,无需重复操作`); + errors.push(`收货单 ${r.receiving_number || r.id} 已审核,无需重复操作`); } } if (errors.length > 0) { await transaction.rollback(); - return { code: 0, message: errors.join('ï¼?), data: {} }; + return { code: 0, message: errors.join(';'), data: {} }; } - // MySQL 二次状态核实:确保 WHERE 条件精准匹配,防止并发竞äº? const updateResult = await ctx.model.Receiving.update( + // MySQL 二次状态核实:确保 WHERE 条件精准匹配,防止并发竞争 + const updateResult = await ctx.model.Receiving.update( { is_review: 1, reviewer_name: reviewerName, @@ -822,7 +854,7 @@ class ReceivingService extends Service { if (affectedRows !== normalizedIds.length) { await transaction.rollback(); - return { code: 0, message: '收货单审核状态已变化,请刷新后重è¯?, data: {} }; + return { code: 0, message: '收货单审核状态已变化,请刷新后重试', data: {} }; } // 写操作日志(失败不影响业务) @@ -850,7 +882,8 @@ class ReceivingService extends Service { await transaction.commit(); - // 逐单发送审核完成通知(文å­?+ 文件,失败不影响业务ï¼? const reviewer = { + // 逐单发送审核完成通知(文字 + 文件,失败不影响业务) + const reviewer = { employees_id: reviewerEmployeeId, employees_name: reviewerName, name: reviewerName, @@ -885,7 +918,7 @@ class ReceivingService extends Service { failedCount: Number(textResult && textResult.data && textResult.data.failedCount || 0), }); } catch (textErr) { - ctx.logger.error('[receiving.reviewReceiving] 文字通知发送失è´?, { + ctx.logger.error('[receiving.reviewReceiving] 文字通知发送失败', { receiving_id: r.id, error: textErr.message, }); @@ -961,7 +994,7 @@ class ReceivingService extends Service { }); } - // 3. 发送文件通知(仅å½?Excel 上传成功时) + // 3. 发送文件通知(仅当 Excel 上传成功时) if (reviewReport) { try { const fileResult = await this.sendReviewNotice({ receiving: receivingSnapshot, reviewer, reviewReport }); @@ -976,7 +1009,7 @@ class ReceivingService extends Service { reportUrl: reviewReport.url || reviewReport.cdnUrl || reviewReport.cosUrl || '', }); } catch (fileErr) { - ctx.logger.error('[receiving.reviewReceiving] 文件通知发送失è´?, { + ctx.logger.error('[receiving.reviewReceiving] 文件通知发送失败', { receiving_id: r.id, error: fileErr.message, }); @@ -993,14 +1026,17 @@ class ReceivingService extends Service { return { code: 200, message: '审核成功', data: { count: normalizedIds.length } }; } catch (error) { await transaction.rollback(); - ctx.logger.error('[receiving.reviewReceiving] 审核收货单失è´?, error); + ctx.logger.error('[receiving.reviewReceiving] 审核收货单失败', error); return { code: 500, message: `审核失败: ${error.message}`, data: {} }; } } /** - * 构建审核完成 Excel 报表 sheets,复用收货完成报表结构,但标æ³?审核äº?而非"完成äº?ã€? * @param {Object} options 构建参数 - * @param {Object} options.receiving 收货单(需å�?details 数组ï¼? * @param {Object} [options.reviewer={}] 审核人信æ�? * @param {Object} [options.stats={}] 明细统计 + * 构建审核完成 Excel 报表 sheets,复用收货完成报表结构,但标注"审核人"而非"完成人"。 + * @param {Object} options 构建参数 + * @param {Object} options.receiving 收货单(需含 details 数组) + * @param {Object} [options.reviewer={}] 审核人信息 + * @param {Object} [options.stats={}] 明细统计 * @param {Map} [options.detailImageMap] 明细图片 Map(key=detail.id字符串) * @param {Array} [options.receivingImages] 收货单主图片数组 * @return {Array} sheets 数组 @@ -1026,7 +1062,7 @@ class ReceivingService extends Service { const detailColumns = [ '序号', '商品名称', '条码', '数量', '重量', '箱数', '托数', - '批次å�?, '生产日期', '到期日期', '备注', '图片链接', '图片', + '批次号', '生产日期', '到期日期', '备注', '图片链接', '图片', ]; const detailImageColumnIndex = detailColumns.length; const maxDetailImageCount = Math.max( @@ -1079,10 +1115,10 @@ class ReceivingService extends Service { [ '总明细数', stats.total_details || details.length ], [ '已匹配明细数', stats.matched_details || 0 ], [ '未匹配明细数', stats.unmatched_details || 0 ], - [ '总数é‡?, stats.total_quantity || 0 ], - [ '总箱æ•?, receiving && receiving.total_boxes ], + [ '总数量', stats.total_quantity || 0 ], + [ '总箱数', receiving && receiving.total_boxes ], [ '总托盘数', receiving && receiving.total_pallets ], - [ '审核äº?, reviewerName ], + [ '审核人', reviewerName ], [ '审核时间', this.formatReportDate(reviewedAt) ], [ '备注', receiving && receiving.remark ], ].forEach(([ field, value ]) => { @@ -1093,7 +1129,7 @@ class ReceivingService extends Service { }); if (mainImageUrls.length === 0) { - pushRow([ '收货图片', 'æ—? ], { toCol: 2, style: { alignment: { vertical: 'top', wrapText: true } } }); + pushRow([ '收货图片', '无' ], { toCol: 2, style: { alignment: { vertical: 'top', wrapText: true } } }); } else { const summaryLinkCell = buildLinkCell(mainImageUrls); const imagePlaceholders = Array(Math.max(mainImageUrls.length, 1)).fill(''); @@ -1119,7 +1155,7 @@ class ReceivingService extends Service { }); if (details.length === 0) { - pushRow([ '', '', '无明ç»? ], { toCol: detailColumns.length, style: { alignment: { vertical: 'top', wrapText: true } } }); + pushRow([ '', '', '无明细' ], { toCol: detailColumns.length, style: { alignment: { vertical: 'top', wrapText: true } } }); } else { details.forEach((detail, index) => { const imgs = Array.isArray(detailImageMap.get(String(detail.id))) @@ -1173,7 +1209,13 @@ class ReceivingService extends Service { } /** - * 发送审核完成通知(receiving_reviewed),支持文字/文件两种类型ã€? * @param {Object} options 发送参æ•? * @param {Object} options.receiving 收货单快ç…? * @param {Object} [options.reviewer={}] 审核人信æ�? * @param {Object|null} [options.reviewReport=null] 审核报表(有值则发文件通知ï¼? * @return {Promise} 发送结æž? */ + * 发送审核完成通知(receiving_reviewed),支持文字/文件两种类型。 + * @param {Object} options 发送参数 + * @param {Object} options.receiving 收货单快照 + * @param {Object} [options.reviewer={}] 审核人信息 + * @param {Object|null} [options.reviewReport=null] 审核报表(有值则发文件通知) + * @return {Promise} 发送结果 + */ async sendReviewNotice({ receiving, reviewer = {}, @@ -1203,12 +1245,12 @@ class ReceivingService extends Service { ).trim(); const content = [ - `收货单号ï¼?{receivingNumber}`, - `货主ï¼?{receiving.store_name || '未知'}`, + `收货单号:${receivingNumber}`, + `货主:${receiving.store_name || '未知'}`, `审核人:${reviewerName || '未知'}`, - `审核时间ï¼?{this.formatReportDate(receiving.updated_at || new Date())}`, - `备注ï¼?{receiving.remark || 'æ—?}`, - ].join('\n') + 'ã€?; + `审核时间:${this.formatReportDate(receiving.updated_at || new Date())}`, + `备注:${receiving.remark || '无'}`, + ].join('\n') + '。'; return await noticeService.send({ warehouseId, @@ -1216,7 +1258,7 @@ class ReceivingService extends Service { messageType: reportUrl ? 'file' : 'text', businessName: 'receiving', event: 'receiving_reviewed', - title: `收货å�?{receivingNumber}审核完成`, + title: `收货单${receivingNumber}审核完成`, content, url: reportUrl || undefined, fileName: reportUrl ? reportFileName : '', @@ -1270,10 +1312,13 @@ class ReceivingService extends Service { operator = 'eq', value, type, } = condition; - // 处理字段å�? const fieldName = condition.field || fieldKey; + // 处理字段名 + const fieldName = condition.field || fieldKey; - // 特殊值处ç�? const processedValue = this.processConditionValue(value, type); - // 根据操作符构建条ä»? switch (operator.toLowerCase()) { + // 特殊值处理 + const processedValue = this.processConditionValue(value, type); + // 根据操作符构建条件 + switch (operator.toLowerCase()) { case 'eq': return { [fieldName]: processedValue, @@ -1288,8 +1333,9 @@ class ReceivingService extends Service { case 'contains': case 'like': - // 处理多值情å†? if (Array.isArray(processedValue) && processedValue.length > 0) { - // 多个值使ç”?OR 连接 + // 处理多值情况 + if (Array.isArray(processedValue) && processedValue.length > 0) { + // 多个值使用 OR 连接 return { [Sequelize.Op.or]: processedValue.map(val => ({ [fieldName]: { @@ -1298,14 +1344,16 @@ class ReceivingService extends Service { })), }; } - // 单个值正常处ç�? return { + // 单个值正常处理 + return { [fieldName]: { [Sequelize.Op.like]: `%${processedValue}%`, }, }; case 'startswith': - // 处理多值情å†? if (Array.isArray(processedValue) && processedValue.length > 0) { + // 处理多值情况 + if (Array.isArray(processedValue) && processedValue.length > 0) { return { [Sequelize.Op.or]: processedValue.map(val => ({ [fieldName]: { @@ -1321,7 +1369,8 @@ class ReceivingService extends Service { }; case 'endswith': - // 处理多值情å†? if (Array.isArray(processedValue) && processedValue.length > 0) { + // 处理多值情况 + if (Array.isArray(processedValue) && processedValue.length > 0) { return { [Sequelize.Op.or]: processedValue.map(val => ({ [fieldName]: { @@ -1425,14 +1474,18 @@ class ReceivingService extends Service { }; default: - // 默认使用等于操作ç¬? return { + // 默认使用等于操作符 + return { [fieldName]: processedValue, }; } } /** - * 处理条件å€? * @param {any} value - 原始å€? * @param {string} type - 字段类型 - * @return {any} 处理后的å€? */ + * 处理条件值 + * @param {any} value - 原始值 + * @param {string} type - 字段类型 + * @return {any} 处理后的值 + */ processConditionValue(value, type) { const { service } = this; if (value === undefined || value === null) { @@ -1451,14 +1504,16 @@ class ReceivingService extends Service { return value; case 'date': - // 单个日期,根据业务需求决定是开始还是结束时é—? // 通常是开始时间(00:00:00ï¼? return service.main.normalizeDate(value, false); + // 单个日期,根据业务需求决定是开始还是结束时间 + // 通常是开始时间(00:00:00) + return service.main.normalizeDate(value, false); case 'daterange': // 处理日期范围:数组的第一个元素是开始时间,第二个元素是结束时间 if (Array.isArray(value) && value.length === 2) { const [ startDate, endDate ] = value; return [ - startDate ? service.main.normalizeDate(startDate, false) : null, // 开始时间设ä¸?0:00:00 + startDate ? service.main.normalizeDate(startDate, false) : null, // 开始时间设为00:00:00 endDate ? service.main.normalizeDate(endDate, true) : null, // 结束时间设为23:59:59 ]; } @@ -1523,8 +1578,10 @@ class ReceivingService extends Service { } /** - * 创建收货单并生成收货单号ã€? * @param {Object} data 创建参数 - * @return {Promise} 新建结果(含 id ä¸?receiving_numberï¼? */ + * 创建收货单并生成收货单号。 + * @param {Object} data 创建参数 + * @return {Promise} 新建结果(含 id 与 receiving_number) + */ async create(data) { const { delivery_method, @@ -1552,10 +1609,13 @@ class ReceivingService extends Service { id: creator_id, }; - // 2. 生成收货单号。注意:`wms_receiving.receiving_number` 在数据库中是全局唯一索引ï¼? // 不能æŒ?warehouse_id 各自ä»?001 开始,否则跨仓会撞号;并发创建时也需要重试兜底ã€? const now = new Date(); + // 2. 生成收货单号。注意:`wms_receiving.receiving_number` 在数据库中是全局唯一索引, + // 不能按 warehouse_id 各自从 001 开始,否则跨仓会撞号;并发创建时也需要重试兜底。 + const now = new Date(); const prefix = this.buildReceivingNumberPrefix(now); - // 3. 获取店铺名称(如果有货主ï¼? let store_name = null; + // 3. 获取店铺名称(如果有货主) + let store_name = null; if (store_id) { const store = await app.model.StoreWarehouse.findOne({ where: { @@ -1569,7 +1629,8 @@ class ReceivingService extends Service { } } - // 4. 创建收货单记录(并发下若撞到唯一键则自动重试取下一个号ï¼? const maxCreateRetries = 5; + // 4. 创建收货单记录(并发下若撞到唯一键则自动重试取下一个号) + const maxCreateRetries = 5; let result = null; let lastCreateError = null; @@ -1655,7 +1716,8 @@ class ReceivingService extends Service { } /** - * 按ID修改收货单基础信息ã€? * @param {Object} data 修改参数 + * 按ID修改收货单基础信息。 + * @param {Object} data 修改参数 * @param {number} data.id 收货单ID * @return {Promise} 修改结果 */ @@ -1681,7 +1743,7 @@ class ReceivingService extends Service { if (!warehouseId) { return { code: 400, - message: '用户未绑定仓åº?, + message: '用户未绑定仓库', }; } @@ -1709,7 +1771,7 @@ class ReceivingService extends Service { await transaction.rollback(); return { code: 404, - message: '收货单不存在或无权访é—?, + message: '收货单不存在或无权访问', }; } @@ -1839,11 +1901,11 @@ class ReceivingService extends Service { code: 200, id: receivingId, receiving_number: receiving.receiving_number, - message: '收货单修改成åŠ?, + message: '收货单修改成功', }; } catch (error) { await transaction.rollback(); - ctx.logger.error('[receiving.save] 修改收货单失è´?, error); + ctx.logger.error('[receiving.save] 修改收货单失败', error); return { code: 0, message: `修改失败: ${error.message}`, @@ -1852,8 +1914,13 @@ class ReceivingService extends Service { } /** - * 绑定收货单货主ã€? * 规则ï¼? * 1. 已取消收货单禁止绑定ï¼? * 2. 收货ä¸?已完成状态下,若已存在货主,则禁止重复绑定; - * 3. 仅允许绑定与当前仓库存在有效签约关系的货主ã€? * @param {Object} data 请求ä½? * @param {number} data.id 收货单ID + * 绑定收货单货主。 + * 规则: + * 1. 已取消收货单禁止绑定; + * 2. 收货中/已完成状态下,若已存在货主,则禁止重复绑定; + * 3. 仅允许绑定与当前仓库存在有效签约关系的货主。 + * @param {Object} data 请求体 + * @param {number} data.id 收货单ID * @param {number} data.store_id 货主ID * @return {Promise} 绑定结果 */ @@ -1867,7 +1934,7 @@ class ReceivingService extends Service { if (!warehouseId) { return { code: 400, - message: '用户未绑定仓åº?, + message: '用户未绑定仓库', }; } @@ -1902,7 +1969,7 @@ class ReceivingService extends Service { await transaction.rollback(); return { code: 404, - message: '收货单不存在或无权访é—?, + message: '收货单不存在或无权访问', }; } @@ -1989,7 +2056,7 @@ class ReceivingService extends Service { }; } catch (error) { await transaction.rollback(); - ctx.logger.error('绑定收货单货主失è´?', error); + ctx.logger.error('绑定收货单货主失败:', error); return { code: 500, message: `绑定货主失败: ${error.message}`, @@ -1998,7 +2065,9 @@ class ReceivingService extends Service { } /** - * 查询单个收货单完整信息(含明细、图片)ã€? * @param {Object} data 请求ä½? * @param {number} data.id 收货单ID + * 查询单个收货单完整信息(含明细、图片)。 + * @param {Object} data 请求体 + * @param {number} data.id 收货单ID * @return {Promise} 单据详情 */ async get(data) { @@ -2006,13 +2075,15 @@ class ReceivingService extends Service { const { ctx, app } = this; const { Op } = app.Sequelize; - // 获取用户仓库ID,增加错误处ç�? const warehouseId = ctx.user?.store_id; + // 获取用户仓库ID,增加错误处理 + const warehouseId = ctx.user?.store_id; if (!warehouseId) { - return { code: 0, message: '用户未绑定仓åº?, data: {} }; + return { code: 0, message: '用户未绑定仓库', data: {} }; } try { - // 1. 查询收货单主è¡? const receiving = await app.model.Receiving.findOne({ + // 1. 查询收货单主表 + const receiving = await app.model.Receiving.findOne({ where: { id, warehouse_id: warehouseId, @@ -2032,12 +2103,14 @@ class ReceivingService extends Service { attributes: [ 'real_name' ], required: false, }], - // 不需要order,因为根据id查询已经是唯一çš? }); + // 不需要order,因为根据id查询已经是唯一的 + }); if (!receiving) { return { code: 0, message: '无记录或无权访问', data: {} }; } - // 2. 查询收货单明ç»? const receivingItems = await app.model.ReceivingDetail.findAll({ + // 2. 查询收货单明细 + const receivingItems = await app.model.ReceivingDetail.findAll({ where: { receiving_id: id, }, @@ -2048,12 +2121,15 @@ class ReceivingService extends Service { attributes: [ 'space_code', 'custom_barcode', 'custom_name' ], }, ], - order: [[ 'id', 'DESC' ]], // 保持倒序,最新在å‰? }); + order: [[ 'id', 'DESC' ]], // 保持倒序,最新在前 + }); // 3. 获取明细ID数组 const receivingItemsIds = receivingItems.map(item => item.id); - // 4. 查询明细图片(如果明细数量大äº?ï¼? const itemImagesMap = {}; // 用于存储每个明细的图ç‰? if (receivingItemsIds.length > 0) { + // 4. 查询明细图片(如果明细数量大于0) + const itemImagesMap = {}; // 用于存储每个明细的图片 + if (receivingItemsIds.length > 0) { const receivingItemsImages = await ctx.model.FileReference.findAll({ where: { business_type: 'receivingItem', @@ -2093,7 +2169,8 @@ class ReceivingService extends Service { }; }); - // 6. 查询主表的图ç‰? const receivingImages = await ctx.model.FileReference.findAll({ + // 6. 查询主表的图片 + const receivingImages = await ctx.model.FileReference.findAll({ where: { business_type: 'receiving', business_id: id, @@ -2108,7 +2185,9 @@ class ReceivingService extends Service { // 7. 组装返回数据 const result = { - ...receiving.toJSON(), // 使用toJSON()确保获得纯对è±? details: items, // 包含图片的明细数æ�? images: receivingImages.map(item => ({ + ...receiving.toJSON(), // 使用toJSON()确保获得纯对象 + details: items, // 包含图片的明细数据 + images: receivingImages.map(item => ({ url: item.file.file_url, id: item.file_id, })), @@ -2117,16 +2196,19 @@ class ReceivingService extends Service { return { code: 200, message: '成功', data: result }; } catch (error) { - console.error('获取收货单详情失è´?', error); - return { code: 500, message: '服务器错è¯?, data: {} }; + console.error('获取收货单详情失败:', error); + return { code: 500, message: '服务器错误', data: {} }; } } /** - * 向收货单新增一条收货明细ã€? * @param {Object} data 请求ä½? * @param {number} data.receiving_id 收货单ID + * 向收货单新增一条收货明细。 + * @param {Object} data 请求体 + * @param {number} data.receiving_id 收货单ID * @param {Object} [data.item] 可选的明细字段 * @return {Promise} 明细列表与默认选中ID - * @description 未传 `item` 时,保持原有空白明细创建行为;传å…?`item` 时,合并默认值后交由 Sequelize 校验与写入,并由服务端覆ç›?`receiving_id` ä¸?`creator_id`ã€? */ + * @description 未传 `item` 时,保持原有空白明细创建行为;传入 `item` 时,合并默认值后交由 Sequelize 校验与写入,并由服务端覆盖 `receiving_id` 与 `creator_id`。 + */ async addDetail(data) { const ctx = this.ctx; const { receiving_id } = data; @@ -2137,7 +2219,8 @@ class ReceivingService extends Service { // 获取当前用户信息 const creator_id = ctx.user.employees_id; const warehouse_id = ctx.user.store_id; - // 验证收货单是否存åœ? const receiving = await ctx.model.Receiving.findOne({ + // 验证收货单是否存在 + const receiving = await ctx.model.Receiving.findOne({ where: { id: receiving_id, warehouse_id }, }); @@ -2148,7 +2231,8 @@ class ReceivingService extends Service { }; } - // 验证收货单状态是否允许添加明ç»? if (receiving.status !== 'receiving') { + // 验证收货单状态是否允许添加明细 + if (receiving.status !== 'receiving') { return { code: 400, message: '收货单状态不允许添加明细', @@ -2158,7 +2242,7 @@ class ReceivingService extends Service { try { const defaultDetail = { receiving_id, - product_name: '新商å“?, + product_name: '新商品', barcode: '', actual_quantity: 0, box_quantity: 0, @@ -2175,7 +2259,8 @@ class ReceivingService extends Service { creator_id, }; - // 允许前端传入可选明细字段,但服务端字段始终覆盖ã€? const newDetail = await ctx.model.ReceivingDetail.create({ + // 允许前端传入可选明细字段,但服务端字段始终覆盖。 + const newDetail = await ctx.model.ReceivingDetail.create({ ...defaultDetail, ...item, receiving_id, @@ -2188,7 +2273,8 @@ class ReceivingService extends Service { order: [[ 'id', 'DESC' ]], }); - // 格式化返回数æ�? const formattedDetails = allDetails.map(detail => { + // 格式化返回数据 + const formattedDetails = allDetails.map(detail => { const detailData = detail.toJSON(); // 处理product_snapshot @@ -2200,7 +2286,8 @@ class ReceivingService extends Service { } } - // 如果有关联的系统商品,可以合并信æ�? if (detailData.system_product) { + // 如果有关联的系统商品,可以合并信息 + if (detailData.system_product) { detailData.system_product_info = detailData.system_product; } @@ -2249,7 +2336,10 @@ class ReceivingService extends Service { } /** - * 绑定或改绑收货单明细的系统商品ã€? * @param {Object} data 请求ä½? * @param {number} data.detail_id 收货单明细ID(兼å®?`id`ï¼? * @param {number} data.system_product_id 商品ID + * 绑定或改绑收货单明细的系统商品。 + * @param {Object} data 请求体 + * @param {number} data.detail_id 收货单明细ID(兼容 `id`) + * @param {number} data.system_product_id 商品ID * @return {Promise} 绑定结果 */ async bindDetailProduct(data) { @@ -2261,7 +2351,7 @@ class ReceivingService extends Service { if (!warehouseId) { return { code: 400, - message: '用户未绑定仓åº?, + message: '用户未绑定仓库', }; } @@ -2339,14 +2429,15 @@ class ReceivingService extends Service { if (!stockWarehouse) { return { code: 404, - message: '商品不存在或不属于当前仓åº?, + message: '商品不存在或不属于当前仓库', }; } const productStoreId = Number(stockWarehouse.store_stock?.store_id || 0); const receivingStoreId = Number(receivingDetail.receiving?.store_id || 0); - // 货主校验:收货单已有货主时,只允许绑定同一货主的商å“? if (receivingStoreId > 0 && productStoreId > 0 && receivingStoreId !== productStoreId) { + // 货主校验:收货单已有货主时,只允许绑定同一货主的商品 + if (receivingStoreId > 0 && productStoreId > 0 && receivingStoreId !== productStoreId) { return { code: 400, message: '该商品不属于当前收货单的货主,不允许绑定', @@ -2380,7 +2471,7 @@ class ReceivingService extends Service { } } - const productName = stockWarehouse.item_name || stockWarehouse.name || receivingDetail.product_name || '未命名商å“?; + const productName = stockWarehouse.item_name || stockWarehouse.name || receivingDetail.product_name || '未命名商品'; const updateData = { system_product_id: systemProductId, product_name: productName, @@ -2405,7 +2496,8 @@ class ReceivingService extends Service { }); barcodes.push(detailBarcode); } catch (barcodeErr) { - // 唯一索引冲突说明条码已被其他商品占用,仅记录日志不阻断业åŠ? ctx.logger.warn('[receiving.bindDetailProduct] 自动新增条码失败(可能已存在ï¼?, barcodeErr); + // 唯一索引冲突说明条码已被其他商品占用,仅记录日志不阻断业务 + ctx.logger.warn('[receiving.bindDetailProduct] 自动新增条码失败(可能已存在)', barcodeErr); } } @@ -2468,7 +2560,7 @@ class ReceivingService extends Service { data: responseData, }; } catch (error) { - ctx.logger.error('绑定收货单明细商品失è´?', error); + ctx.logger.error('绑定收货单明细商品失败:', error); return { code: 500, message: `绑定商品失败: ${error.message}`, @@ -2495,11 +2587,12 @@ class ReceivingService extends Service { if (!detail) { return { code: 404, - message: '明细不存åœ?, + message: '明细不存在', }; } - // 验证关联的收货单状态是否允许修æ”? if (detail.receiving && detail.receiving.status !== 'receiving') { + // 验证关联的收货单状态是否允许修改 + if (detail.receiving && detail.receiving.status !== 'receiving') { return { code: 400, message: '收货单状态不允许修改明细', @@ -2522,7 +2615,8 @@ class ReceivingService extends Service { } try { - // 如果需要处理商品匹é…? if (updateData.barcode && updateData.barcode.trim()) { + // 如果需要处理商品匹配 + if (updateData.barcode && updateData.barcode.trim()) { // 尝试根据条码匹配系统商品 const systemProduct = await ctx.model.StockWarehouse.findOne({ where: { barcode: updateData.barcode }, @@ -2540,13 +2634,15 @@ class ReceivingService extends Service { images: systemProduct.images ? JSON.parse(systemProduct.images) : [], }); - // 如果用户没有输入商品名称,使用系统商品名ç§? if (!updateData.product_name) { + // 如果用户没有输入商品名称,使用系统商品名称 + if (!updateData.product_name) { updateData.product_name = systemProduct.name; } } } - // 处理数量类型的转æ�? if (updateData.actual_quantity !== undefined) { + // 处理数量类型的转换 + if (updateData.actual_quantity !== undefined) { updateData.actual_quantity = parseInt(updateData.actual_quantity) || 0; } @@ -2565,7 +2661,8 @@ class ReceivingService extends Service { if (updateData.stored_quantity !== undefined) { updateData.stored_quantity = parseInt(updateData.stored_quantity) || 0; - // 根据入库数量更新入库状æ€? if (updateData.stored_quantity >= updateData.actual_quantity) { + // 根据入库数量更新入库状态 + if (updateData.stored_quantity >= updateData.actual_quantity) { updateData.storage_status = 'all'; } else if (updateData.stored_quantity > 0) { updateData.storage_status = 'partial'; @@ -2586,7 +2683,8 @@ class ReceivingService extends Service { }; } - // 更新收货单统计信æ�? if (detail.receiving_id) { + // 更新收货单统计信息 + if (detail.receiving_id) { await this.updateReceivingStats(detail.receiving_id); } @@ -2602,7 +2700,8 @@ class ReceivingService extends Service { ], }); - // 格式化返回数æ�? const detailData = updatedDetail.toJSON(); + // 格式化返回数据 + const detailData = updatedDetail.toJSON(); if (detailData.product_snapshot) { try { @@ -2654,14 +2753,16 @@ class ReceivingService extends Service { return null; } - // 直接返回 store_stock 的信æ�? return { + // 直接返回 store_stock 的信息 + return { store_id: stockWarehouse.store_stock.store_id, store_remask: stockWarehouse.store_stock.store_remask, }; } catch (error) { - ctx.logger.error(`获取库存 ${stock_id} 的店铺信息失è´?`, error); - // 根据需求决定是否抛出错è¯? // throw error; + ctx.logger.error(`获取库存 ${stock_id} 的店铺信息失败:`, error); + // 根据需求决定是否抛出错误 + // throw error; return null; } } @@ -2695,7 +2796,8 @@ class ReceivingService extends Service { let storeId = receiving.store_id; let storeName = receiving.store_name; - // 如果收货单没æœ?store_id,尝试从已匹配的商品详情中获å�? if (!storeId) { + // 如果收货单没有 store_id,尝试从已匹配的商品详情中获取 + if (!storeId) { // 查找第一个已匹配的商品详情(system_product_id 不为空) const matchedDetail = await app.model.ReceivingDetail.findOne({ where: { @@ -2713,16 +2815,18 @@ class ReceivingService extends Service { if (storeInfo && storeInfo.store_id) { storeId = storeInfo.store_id; - // 注意:这里使ç”?store_remask 作为 store_name - storeName = storeInfo.store_remask; // 或è€?storeInfo.store_remask + // 注意:这里使用 store_remask 作为 store_name + storeName = storeInfo.store_remask; // 或者 storeInfo.store_remask } } catch (error) { - ctx.logger.warn(`获取商品 ${matchedDetail.system_product_id} 的库存信息失è´?`, error); - // 继续执行,使用默认å€? } + ctx.logger.warn(`获取商品 ${matchedDetail.system_product_id} 的库存信息失败:`, error); + // 继续执行,使用默认值 + } } } - // 3. 统计该收货单的所有明ç»? const stats = await ctx.model.ReceivingDetail.findAll({ + // 3. 统计该收货单的所有明细 + const stats = await ctx.model.ReceivingDetail.findAll({ where: { receiving_id: receivingId }, attributes: [ [ ctx.model.fn('COUNT', ctx.model.col('id')), 'total_items' ], @@ -2734,7 +2838,8 @@ class ReceivingService extends Service { const stat = stats[0] || {}; - // 4. 判断收货单的整体状æ€? const allDetails = await ctx.model.ReceivingDetail.findAll({ + // 4. 判断收货单的整体状态 + const allDetails = await ctx.model.ReceivingDetail.findAll({ where: { receiving_id: receivingId }, transaction, }); @@ -2750,7 +2855,8 @@ class ReceivingService extends Service { } } - // 5. 更新收货å�? const updateData = { + // 5. 更新收货单 + const updateData = { total_items: parseInt(stat.total_items) || 0, total_quantity: parseFloat(stat.total_quantity) || 0, detail_status: detailStatus, @@ -2762,7 +2868,7 @@ class ReceivingService extends Service { updateData.store_id = storeId; updateData.store_name = storeName; } else if (storeId && storeName && receiving.store_name !== storeName) { - // 如果 store_id 已有ä½?store_name 不同,也更新名称 + // 如果 store_id 已有但 store_name 不同,也更新名称 updateData.store_name = storeName; } @@ -2777,19 +2883,22 @@ class ReceivingService extends Service { // 6. 提交事务 await transaction.commit(); - ctx.logger.info(`成功更新收货å�?${receivingId} 的统计信息`); + ctx.logger.info(`成功更新收货单 ${receivingId} 的统计信息`); } catch (error) { - // 7. 发生错误时回滚事åŠ? if (transaction) { + // 7. 发生错误时回滚事务 + if (transaction) { await transaction.rollback(); } - ctx.logger.error('更新收货单统计失è´?', error); + ctx.logger.error('更新收货单统计失败:', error); throw error; } } /** - * 删除收货单明细并回算统计ã€? * @param {Object} data 请求ä½? * @param {number} data.detail_id 明细ID + * 删除收货单明细并回算统计。 + * @param {Object} data 请求体 + * @param {number} data.detail_id 明细ID * @return {Promise} 删除结果 */ async deleteDetail(data) { @@ -2816,11 +2925,12 @@ class ReceivingService extends Service { if (!detail) { return { code: 404, - message: '明细不存åœ?, + message: '明细不存在', }; } - // 验证关联的收货单状态是否允许删é™? if (detail.receiving && detail.receiving.status !== 'receiving') { + // 验证关联的收货单状态是否允许删除 + if (detail.receiving && detail.receiving.status !== 'receiving') { return { code: 400, message: '收货单状态不允许删除明细', @@ -2831,7 +2941,7 @@ class ReceivingService extends Service { if (detail.storage_status !== 'none' && detail.stored_quantity > 0) { return { code: 400, - message: '该明细已入库,不能删é™?, + message: '该明细已入库,不能删除', }; } @@ -2851,12 +2961,14 @@ class ReceivingService extends Service { }; } - // 获取删除后的所有明ç»? const remainingDetails = await ctx.model.ReceivingDetail.findAll({ + // 获取删除后的所有明细 + const remainingDetails = await ctx.model.ReceivingDetail.findAll({ where: { receiving_id }, order: [[ 'id', 'DESC' ]], }); - // 格式化返回数æ�? const formattedDetails = remainingDetails.map(detail => { + // 格式化返回数据 + const formattedDetails = remainingDetails.map(detail => { const detailData = detail.toJSON(); if (detailData.product_snapshot) { @@ -2870,9 +2982,11 @@ class ReceivingService extends Service { return detailData; }); - // 返回下一个选中的明细ID(如果有剩余明细ï¼? let selectId = null; + // 返回下一个选中的明细ID(如果有剩余明细) + let selectId = null; if (remainingDetails.length > 0) { - // 默认选中第一ä¸? selectId = remainingDetails[0].id; + // 默认选中第一个 + selectId = remainingDetails[0].id; } await this.updateReceivingStats(receiving_id); @@ -2917,7 +3031,8 @@ class ReceivingService extends Service { } } /** - * 修改收货明细ã€? * @param {Object} data 收货明细修改参数 + * 修改收货明细。 + * @param {Object} data 收货明细修改参数 * @return {Promise} 修改结果 */ async detailChange(data) { @@ -2930,10 +3045,13 @@ class ReceivingService extends Service { id, // 收货明细ID receiving_id, // 收货单ID actual_quantity, // 实际收货数量 - batch_number, // 批次å�? production_date, // 生产日期 + batch_number, // 批次号 + production_date, // 生产日期 expiry_date, // 到期日期 box_quantity, // 箱数 - boxes_per_pallet, // 每托盘箱æ•? pallet_quantity, // 托盘æ•? space_id, // 存放库位ID + boxes_per_pallet, // 每托盘箱数 + pallet_quantity, // 托盘数 + space_id, // 存放库位ID remark, // 备注 system_product_id, // 系统商品ID barcode, // 条码 @@ -2942,7 +3060,9 @@ class ReceivingService extends Service { box_height, box_length, weight, - box_remainder, // 箱余æ•? box_weight, // 箱重é‡? } = data; + box_remainder, // 箱余数 + box_weight, // 箱重量 + } = data; // 2. 验证必填字段 if (!id) { return { @@ -2979,7 +3099,7 @@ class ReceivingService extends Service { if (!receivingDetail) { return { code: 404, - message: '收货明细不存åœ?, + message: '收货明细不存在', }; } @@ -2994,7 +3114,7 @@ class ReceivingService extends Service { if (box_quantity !== undefined && box_quantity < 0) { return { code: 400, - message: '箱数不能为负æ•?, + message: '箱数不能为负数', }; } @@ -3072,7 +3192,8 @@ class ReceivingService extends Service { if (stockWarehouse) { // 更新商品相关信息 updateData.system_product_id = system_product_id; - // 使用系统商品的条码(如果前端没有提供ï¼? const barcodes = stockWarehouse.barcodes?.map(b => b.barcode) || []; + // 使用系统商品的条码(如果前端没有提供) + const barcodes = stockWarehouse.barcodes?.map(b => b.barcode) || []; updateData.barcode = updateData.barcode || barcodes.join(';'); updateData.weight = updateData.weight || stockWarehouse.gross_weight; if (stockWarehouse.enable_box_spec) { @@ -3081,7 +3202,8 @@ class ReceivingService extends Service { updateData.box_width = updateData.box_width || stockWarehouse.box_width; updateData.box_length = updateData.box_length || stockWarehouse.box_length; } - // 使用系统商品的名称(如果前端没有提供ï¼? updateData.product_name = stockWarehouse.item_name || product_name; + // 使用系统商品的名称(如果前端没有提供) + updateData.product_name = stockWarehouse.item_name || product_name; // 如果有货主信息,更新到产品快照中 if (stockWarehouse.store_stock) { @@ -3197,10 +3319,11 @@ class ReceivingService extends Service { if (!receiving) { await transaction.rollback(); - ctx.throw(404, '收货单不存在或已被删é™?); + ctx.throw(404, '收货单不存在或已被删除'); } - // 2. 检查状态是否允许作åº? if (receiving.status === 'cancelled') { + // 2. 检查状态是否允许作废 + if (receiving.status === 'cancelled') { return { code: 200, success: true, @@ -3213,12 +3336,13 @@ class ReceivingService extends Service { ctx.throw(400, '已全部入库完成,无法作废'); } - // 3. 获取操作人信æ�? const operator = ctx.user; + // 3. 获取操作人信息 + const operator = ctx.user; // 4. 更新收货单状态为作废 await ctx.model.Receiving.update({ status: 'cancelled', - remark: invalid_reason ? `已作åº? ${invalid_reason}` : (receiving.remark || '') + ' - 已作åº?, + remark: invalid_reason ? `已作废: ${invalid_reason}` : (receiving.remark || '') + ' - 已作废', updated_at: new Date(), }, { where: { id: receivingId }, @@ -3249,10 +3373,12 @@ class ReceivingService extends Service { } } - // 6. 处理关联的入库记录(如果有部分入库的情况ï¼? if (receiving.storage_status === 'partial') { - // 将关联的入库记录状态也更新为作åº? await ctx.model.Storage.update({ + // 6. 处理关联的入库记录(如果有部分入库的情况) + if (receiving.storage_status === 'partial') { + // 将关联的入库记录状态也更新为作废 + await ctx.model.Storage.update({ status: 'cancelled', - remark: `关联收货å�?{receiving.receiving_number}已作废`, + remark: `关联收货单${receiving.receiving_number}已作废`, updated_at: new Date(), }, { where: { @@ -3308,7 +3434,7 @@ class ReceivingService extends Service { await transaction.rollback(); } - ctx.logger.error(`作废收货单失è´? ${error.message}`, { + ctx.logger.error(`作废收货单失败: ${error.message}`, { receivingId, warehouseId, userId: ctx.user.id, @@ -3335,7 +3461,7 @@ class ReceivingService extends Service { formatDeliveryMethod(value) { const methodMap = { truck: '货车', - express: '快é€?, + express: '快递', air_freight: '空运', sea_freight: '海运', other: '其他', @@ -3346,12 +3472,15 @@ class ReceivingService extends Service { } /** - * 获取完成收货时需要展示的联系字段ã€? * @param {Object} receiving 收货单快照ã€? * @return {Array} 需要展示的联系字段列表ã€? */ + * 获取完成收货时需要展示的联系字段。 + * @param {Object} receiving 收货单快照。 + * @return {Array} 需要展示的联系字段列表。 + */ getCompletionContactFields(receiving) { const deliveryMethod = String((receiving && receiving.delivery_method) || '').trim(); if (deliveryMethod === 'truck') { - return [[ '车牌å�?, receiving && receiving.license_plate ]]; + return [[ '车牌号', receiving && receiving.license_plate ]]; } if (deliveryMethod === 'express') { @@ -3362,7 +3491,15 @@ class ReceivingService extends Service { } /** - * 生成收货完成报表的工作表数据ã€? * @param {Object} options 报表参数ã€? * @param {Object} options.receiving 收货单快照ã€? * @param {Object} [options.operator={}] 操作人信息ã€? * @param {Object} [options.stats={}] 收货统计数据ã€? * @param {Map} [options.detailImageMap=new Map()] 明细图片映射ã€? * @param {Array} [options.receivingImages=[]] 收货单图片列表ã€? * @return {Array} 工作表列表ã€? */ + * 生成收货完成报表的工作表数据。 + * @param {Object} options 报表参数。 + * @param {Object} options.receiving 收货单快照。 + * @param {Object} [options.operator={}] 操作人信息。 + * @param {Object} [options.stats={}] 收货统计数据。 + * @param {Map} [options.detailImageMap=new Map()] 明细图片映射。 + * @param {Array} [options.receivingImages=[]] 收货单图片列表。 + * @return {Array} 工作表列表。 + */ buildCompletionReportSheets({ receiving, operator = {}, @@ -3384,7 +3521,7 @@ class ReceivingService extends Service { const detailColumns = [ '序号', '商品名称', '条码', '数量', '重量', '箱数', '托数', - '批次å�?, '生产日期', '到期日期', '备注', '图片链接', '图片', + '批次号', '生产日期', '到期日期', '备注', '图片链接', '图片', ]; const detailImageColumnIndex = detailColumns.length; const maxDetailImageCount = Math.max( @@ -3445,10 +3582,10 @@ class ReceivingService extends Service { [ '总明细数', stats.total_details || details.length ], [ '已匹配明细数', stats.matched_details || 0 ], [ '未匹配明细数', stats.unmatched_details || 0 ], - [ '总数é‡?, stats.total_quantity || 0 ], - [ '总箱æ•?, receiving && receiving.total_boxes ], + [ '总数量', stats.total_quantity || 0 ], + [ '总箱数', receiving && receiving.total_boxes ], [ '总托盘数', receiving && receiving.total_pallets ], - [ '完成äº?, operator.employees_name || operator.real_name || operator.name || '' ], + [ '完成人', operator.employees_name || operator.real_name || operator.name || '' ], [ '完成时间', this.formatReportDate(receiving && receiving.receiving_end_time) ], [ '备注', receiving && receiving.remark ], ].forEach(([ field, value ]) => { @@ -3461,7 +3598,7 @@ class ReceivingService extends Service { }); if (mainImageUrls.length === 0) { - pushReportRow([ '收货图片', 'æ—? ], { + pushReportRow([ '收货图片', '无' ], { toCol: 2, style: { alignment: { vertical: 'top', wrapText: true }, @@ -3507,7 +3644,7 @@ class ReceivingService extends Service { }); if (details.length === 0) { - pushReportRow([ '', '', '无明ç»? ], { + pushReportRow([ '', '', '无明细' ], { toCol: detailColumns.length, style: { alignment: { vertical: 'top', wrapText: true }, @@ -3594,7 +3731,7 @@ class ReceivingService extends Service { const receivingNumber = String(receiving.receiving_number || receiving.id).replace(/[\\/:*?"<>|]/g, '_'); return await excelService.generateAndUpload({ - filename: `收货明细(已完成收è´?_${receivingNumber}.xlsx`, + filename: `收货明细(已完成收货)_${receivingNumber}.xlsx`, dir: `exports/receiving/completed/${ctx.user.store_id || receiving.warehouse_id || 'common'}`, category: 'document', saveRecord: true, @@ -3612,10 +3749,13 @@ class ReceivingService extends Service { } /** - * 发送收货完成统一通知,通知外部订阅 `receiving_completed` 事件ã€? * @param {Object} options 通知参数 - * @param {Object} options.receiving 收货单快ç…? * @param {Object} [options.operator={}] 操作人信æ�? * @param {Object} [options.stats={}] 收货统计 + * 发送收货完成统一通知,通知外部订阅 `receiving_completed` 事件。 + * @param {Object} options 通知参数 + * @param {Object} options.receiving 收货单快照 + * @param {Object} [options.operator={}] 操作人信息 + * @param {Object} [options.stats={}] 收货统计 * @param {Object|null} [options.completionReport=null] 完成报表信息 - * @return {Promise} 通知发送结果,若条件不满足则返å›?null + * @return {Promise} 通知发送结果,若条件不满足则返回 null */ async sendCompletionNotice({ receiving, @@ -3666,28 +3806,28 @@ class ReceivingService extends Service { })); const totalBoxRemainder = normalizedDetails.reduce((sum, item) => sum + Number(item.box_remainder || 0), 0); const totalBoxWeight = normalizedDetails.reduce((sum, item) => sum + Number(item.box_weight || 0), 0); - const title = `收货å�?{receivingNumber}已完成`; - const contactLines = this.getCompletionContactFields(receiving).map(([ field, value ]) => `${field}ï¼?{value || 'æ—?}`); + const title = `收货单${receivingNumber}已完成`; + const contactLines = this.getCompletionContactFields(receiving).map(([ field, value ]) => `${field}:${value || '无'}`); const content = [ - `收货单号ï¼?{receivingNumber} 已完成`, - `货主ï¼?{receiving.store_name || '未知'}`, - `来货方式ï¼?{this.formatDeliveryMethod(receiving.delivery_method) || '未知'}`, + `收货单号:${receivingNumber} 已完成`, + `货主:${receiving.store_name || '未知'}`, + `来货方式:${this.formatDeliveryMethod(receiving.delivery_method) || '未知'}`, ...contactLines, - `总明细数ï¼?{Number(stats.total_details || 0)}件`, - `匹配商品ï¼?{matchedDetails}件`, + `总明细数:${Number(stats.total_details || 0)}件`, + `匹配商品:${matchedDetails}件`, `未匹配商品:${unmatchedDetails}件`, `总数量:${totalQuantity}`, `总箱数:${receiving.total_boxes || 0}`, - `总箱余数ï¼?{totalBoxRemainder}`, + `总箱余数:${totalBoxRemainder}`, `总箱重:${totalBoxWeight}`, - `总托盘数ï¼?{receiving.total_pallets || 0}`, + `总托盘数:${receiving.total_pallets || 0}`, operatorName ? `完成人:${operatorName}` : '', `开始时间:${this.formatReportDate(receiving.created_at)}`, - `完成时间ï¼?{this.formatReportDate(receiving.receiving_end_time)}`, - `备注ï¼?{receiving.remark || 'æ—?}`, + `完成时间:${this.formatReportDate(receiving.receiving_end_time)}`, + `备注:${receiving.remark || '无'}`, `快速查看:${ctx.app.config.frontendUrl || ''}/storage/receiving?id=${receivingNumber}`, // 替换为实际的前端地址 - ].filter(Boolean).join('\n') + 'ã€?; + ].filter(Boolean).join('\n') + '。'; return await noticeService.send({ warehouseId, @@ -3735,7 +3875,9 @@ class ReceivingService extends Service { } /** - * 完成收货单:校验明细、更新状态并写入库存ã€? * @param {Object} data 请求ä½? * @param {number} data.id 收货单ID + * 完成收货单:校验明细、更新状态并写入库存。 + * @param {Object} data 请求体 + * @param {number} data.id 收货单ID * @param {string} [data.remark] 完成备注 * @return {Promise} 完成结果 */ @@ -3788,11 +3930,12 @@ class ReceivingService extends Service { await transaction.rollback(); return { code: 404, - message: '收货单不存在或已被删é™?, + message: '收货单不存在或已被删除', }; } - // 2. 状态检æŸ? if (receiving.status === 'completed') { + // 2. 状态检查 + if (receiving.status === 'completed') { await transaction.rollback(); return { code: 200, @@ -3804,7 +3947,7 @@ class ReceivingService extends Service { await transaction.rollback(); return { code: 400, - message: '已作废的收货单不可完æˆ?, + message: '已作废的收货单不可完成', }; } @@ -3817,12 +3960,13 @@ class ReceivingService extends Service { }; } - // 4. 校验明细数量:不允许存在数量ä¸?0 的明ç»? const zeroQuantityDetails = receiving.details.filter(d => Number(d.actual_quantity || 0) <= 0); + // 4. 校验明细数量:不允许存在数量为 0 的明细 + const zeroQuantityDetails = receiving.details.filter(d => Number(d.actual_quantity || 0) <= 0); if (zeroQuantityDetails.length > 0) { await transaction.rollback(); const errorMsg = zeroQuantityDetails.length === 1 - ? `商品â€?{zeroQuantityDetails[0].product_name || '未命名商å“?}”的数量ä¸?,请填写实际收货数量` - : `æœ?{zeroQuantityDetails.length}个商品数量为0,请填写实际收货数量`; + ? `商品“${zeroQuantityDetails[0].product_name || '未命名商品'}”的数量为0,请填写实际收货数量` + : `有${zeroQuantityDetails.length}个商品数量为0,请填写实际收货数量`; return { success: false, code: 'DETAIL_QUANTITY_ZERO', @@ -3830,7 +3974,7 @@ class ReceivingService extends Service { data: { invalid_details: zeroQuantityDetails.map(d => ({ detail_id: d.id, - item_name: d.product_name || '未命名商å“?, + item_name: d.product_name || '未命名商品', actual_quantity: Number(d.actual_quantity || 0), })), }, @@ -3845,11 +3989,11 @@ class ReceivingService extends Service { return { success: false, code: 'BATCH_NUMBER_REQUIRED', - message: '批次管理商品必须填写批次å�?, + message: '批次管理商品必须填写批次号', data: { invalid_details: missingBatchNumberDetails.map(detail => ({ detail_id: detail.id, - item_name: detail.product_name || detail.system_product?.item_name || '未命名商å“?, + item_name: detail.product_name || detail.system_product?.item_name || '未命名商品', batch_number: detail.batch_number || '', production_date: detail.production_date || null, expiry_date: detail.expiry_date || null, @@ -3869,7 +4013,7 @@ class ReceivingService extends Service { data: { invalid_details: missingBatchDetails.map(detail => ({ detail_id: detail.id, - item_name: detail.product_name || detail.system_product?.item_name || '未命名商å“?, + item_name: detail.product_name || detail.system_product?.item_name || '未命名商品', batch_number: detail.batch_number || '', production_date: detail.production_date || null, expiry_date: detail.expiry_date || null, @@ -3897,11 +4041,11 @@ class ReceivingService extends Service { return { success: false, code: 'EXPIRY_DATE_TOO_SOON', - message: `商品â€?{firstInvalid.product_name || firstInvalid.system_product?.item_name || '未命名商å“?}”的有效期不足最小允许收货天数(${minReceiveDays}天),无法完成收货`, + message: `商品“${firstInvalid.product_name || firstInvalid.system_product?.item_name || '未命名商品'}”的有效期不足最小允许收货天数(${minReceiveDays}天),无法完成收货`, data: { invalid_details: invalidExpiryDetails.map(detail => ({ detail_id: detail.id, - item_name: detail.product_name || detail.system_product?.item_name || '未命名商å“?, + item_name: detail.product_name || detail.system_product?.item_name || '未命名商品', batch_number: detail.batch_number || '', production_date: detail.production_date || null, expiry_date: detail.expiry_date || null, @@ -3911,7 +4055,8 @@ class ReceivingService extends Service { }; } - // 5. 准备明细图片与统计信息(照片/条码/重量不再强制要求ï¼? const unmatchedDetails = receiving.details.filter(d => !d.system_product_id); + // 5. 准备明细图片与统计信息(照片/条码/重量不再强制要求) + const unmatchedDetails = receiving.details.filter(d => !d.system_product_id); const detailsIds = receiving.details.map(item => item.id); const images = await ctx.model.FileReference.findAll({ @@ -3944,9 +4089,11 @@ class ReceivingService extends Service { }); }); - // 5. 获取操作人信æ�? const operator = ctx.user; + // 5. 获取操作人信息 + const operator = ctx.user; - // 8. 更新收货单状æ€? const now = new Date(); + // 8. 更新收货单状态 + const now = new Date(); const updateData = { status: 'completed', receiving_end_time: now, @@ -3955,10 +4102,10 @@ class ReceivingService extends Service { if (remark) { const remarkPrefix = receiving.remark ? `${receiving.remark}\n` : ''; - updateData.remark = `${remarkPrefix}【完成收货ã€?{now.toLocaleString()} ${operator.employees_name} ${remark}`; + updateData.remark = `${remarkPrefix}【完成收货】${now.toLocaleString()} ${operator.employees_name} ${remark}`; } else { const remarkPrefix = receiving.remark ? `${receiving.remark}\n` : ''; - updateData.remark = `${remarkPrefix}【完成收货ã€?{now.toLocaleString()} ${operator.employees_name}`; + updateData.remark = `${remarkPrefix}【完成收货】${now.toLocaleString()} ${operator.employees_name}`; } await ctx.model.Receiving.update(updateData, { @@ -3980,7 +4127,7 @@ class ReceivingService extends Service { // 10.1 清除收货单缓存,确保下次入库完成时匹配到最新收货单列表 const receivingCacheKey = `cache:receiving_orders:warehouse:${warehouseId}`; app.delCacheAsync(receivingCacheKey).catch(cacheErr => { - ctx.logger.warn(`[receiving.completeReceiving] 清除收货单缓存失è´? ${cacheErr.message}`, { cacheKey: receivingCacheKey }); + ctx.logger.warn(`[receiving.completeReceiving] 清除收货单缓存失败: ${cacheErr.message}`, { cacheKey: receivingCacheKey }); }); // 记录操作日志 @@ -4016,7 +4163,8 @@ class ReceivingService extends Service { stats, }; - // 11. 收货成功后先触发文字通知,再生成 Excel;若 Excel 成功,再补发文件通知ã€? try { + // 11. 收货成功后先触发文字通知,再生成 Excel;若 Excel 成功,再补发文件通知。 + try { const textNoticeResult = await this.sendCompletionNotice(completionNoticePayload); ctx.logger.info('收货完成文字通知结果', { receiving_id: id, @@ -4029,7 +4177,7 @@ class ReceivingService extends Service { failedCount: Number(textNoticeResult && textNoticeResult.data && textNoticeResult.data.failedCount || 0), }); } catch (notifyError) { - ctx.logger.error(`收货完成文字通知发送失è´? ${notifyError.message}`, { + ctx.logger.error(`收货完成文字通知发送失败: ${notifyError.message}`, { receiving_id: id, warehouseId, error: notifyError.stack, @@ -4094,21 +4242,27 @@ class ReceivingService extends Service { } /** - * 收货完成后异步补全商品资料:绑定图片、补填毛重ã€? * + * 收货完成后异步补全商品资料:绑定图片、补填毛重。 + * * 遍历当前收货单所有已绑定系统商品的明细: - * 1. 若商å“?is_images === 'N' 且该明细有收货图片,则将收货图片复制为商品图片(FileReference), - * 并将商品çš?is_images 更新ä¸?'Y'ã€? * 2. 若商å“?gross_weight ä¸?0 æˆ?null,且明细çš?weight > 0,则将商品毛重更新为该明细的 weightã€? * - * 本方法通过 setImmediate 调用,运行在事务提交后,任何异常只记录日志,不影响主进程ã€? * + * 1. 若商品 is_images === 'N' 且该明细有收货图片,则将收货图片复制为商品图片(FileReference), + * 并将商品的 is_images 更新为 'Y'。 + * 2. 若商品 gross_weight 为 0 或 null,且明细的 weight > 0,则将商品毛重更新为该明细的 weight。 + * + * 本方法通过 setImmediate 调用,运行在事务提交后,任何异常只记录日志,不影响主进程。 + * * @param {Object} options 参数对象 - * @param {number} options.receivingId 收货å�?ID + * @param {number} options.receivingId 收货单 ID * @param {number} options.warehouseId 仓库 ID - * @param {Array} options.details 收货明细数组(来è‡?completeReceiving 中已加载çš?detailsï¼? * @return {Promise} + * @param {Array} options.details 收货明细数组(来自 completeReceiving 中已加载的 details) + * @return {Promise} */ async _syncProductDataFromReceiving({ receivingId, warehouseId, details }) { - console.log('_syncProductDataFromReceiving异步执行ä¸?..'); // 调试日志 + console.log('_syncProductDataFromReceiving异步执行中...'); // 调试日志 const { ctx, app } = this; - // 只处理已绑定系统商品的明ç»? const boundDetails = (Array.isArray(details) ? details : []).filter( + // 只处理已绑定系统商品的明细 + const boundDetails = (Array.isArray(details) ? details : []).filter( d => d && Number(d.system_product_id) > 0 ); @@ -4142,7 +4296,7 @@ class ReceivingService extends Service { }); if (detailImageRefs.length > 0) { - // 查询商品已有的图ç‰?file_id(避免重复) + // 查询商品已有的图片 file_id(避免重复) const existingStockImageFileIds = await app.model.FileReference.findAll({ where: { business_type: 'stock', @@ -4176,7 +4330,7 @@ class ReceivingService extends Service { ); ctx.logger.info( - `[_syncProductDataFromReceiving] 商品 ${systemProductId} 已补全图片,共复åˆ?${toCreate.length} 张(收货å�?${receivingId} 明细 ${detail.id})` + `[_syncProductDataFromReceiving] 商品 ${systemProductId} 已补全图片,共复制 ${toCreate.length} 张(收货单 ${receivingId} 明细 ${detail.id})` ); } @@ -4190,11 +4344,12 @@ class ReceivingService extends Service { ); ctx.logger.info( - `[_syncProductDataFromReceiving] 商品 ${systemProductId} 已补全毛é‡?${detailWeight}(收货单 ${receivingId} 明细 ${detail.id})` + `[_syncProductDataFromReceiving] 商品 ${systemProductId} 已补全毛重 ${detailWeight}(收货单 ${receivingId} 明细 ${detail.id})` ); } } catch (err) { - // 单条明细失败不中断后续处ç�? console.log( + // 单条明细失败不中断后续处理 + console.log( `[_syncProductDataFromReceiving] 处理明细 ${detail.id} (商品 ${systemProductId}) 失败: ${err.message}` ); } @@ -4202,8 +4357,19 @@ class ReceivingService extends Service { } /** - * PDA 扫码定位收货明细:通过入库单ID + 扫描条码快速定位收货明细ã€? * 搜索策略ï¼? * 1. 通过 entry_order_id â†?wms_entry_order_receiving 查出关联çš?receiving_id 列表ï¼? * 2. 查出所有未绑定的收货明细(仅按 receiving_id IN + 排除已绑定过滤)ï¼? * 3. 收集明细çš?system_product_id,批量调ç”?getStockDetails 获取条码信息ï¼? * 4. 在内存中遍历明细进行精确匹配ï¼? * - è‹?barcode 为纯数字,优先按明细 ID 精确匹配ï¼? * - 再按 getStockDetails 返回çš?barcodes[].barcode 精确匹配商品条码ï¼? * 5. 返回所有匹配的明细列表(同一条码可能匹配到多条收货明细)ã€? * @param {number} entryOrderId 入库单ID - * @param {string} barcode 扫描条码(商品条ç ?箱唛/托盘å”?明细IDï¼? * @return {Promise} 包含 code、message 与匹配明细列è¡?data.list 的结果对è±? */ + * PDA 扫码定位收货明细:通过入库单ID + 扫描条码快速定位收货明细。 + * 搜索策略: + * 1. 通过 entry_order_id → wms_entry_order_receiving 查出关联的 receiving_id 列表; + * 2. 查出所有未绑定的收货明细(仅按 receiving_id IN + 排除已绑定过滤); + * 3. 收集明细的 system_product_id,批量调用 getStockDetails 获取条码信息; + * 4. 在内存中遍历明细进行精确匹配: + * - 若 barcode 为纯数字,优先按明细 ID 精确匹配; + * - 再按 getStockDetails 返回的 barcodes[].barcode 精确匹配商品条码; + * 5. 返回所有匹配的明细列表(同一条码可能匹配到多条收货明细)。 + * @param {number} entryOrderId 入库单ID + * @param {string} barcode 扫描条码(商品条码/箱唛/托盘唛/明细ID) + * @return {Promise} 包含 code、message 与匹配明细列表 data.list 的结果对象 + */ async scanDetail(entryOrderId, barcode) { const { ctx, app } = this; const { Op } = app.Sequelize; @@ -4211,7 +4377,7 @@ class ReceivingService extends Service { // 参数校验 if (!warehouseId) { - return { code: 0, message: '用户未绑定仓åº?, data: null }; + return { code: 0, message: '用户未绑定仓库', data: null }; } if (!entryOrderId || Number(entryOrderId) <= 0) { return { code: 0, message: '入库单ID不能为空', data: null }; @@ -4235,10 +4401,10 @@ class ReceivingService extends Service { }); if (!entryOrder) { - return { code: 0, message: '入库单不存在或无权访é—?, data: null }; + return { code: 0, message: '入库单不存在或无权访问', data: null }; } - // 2. 通过 wms_entry_order_receiving 查出关联çš?receiving_id 列表 + // 2. 通过 wms_entry_order_receiving 查出关联的 receiving_id 列表 const entryReceivingRows = await ctx.model.EntryOrderReceiving.findAll({ where: { entry_order_id: normalizedEntryOrderId }, attributes: [ 'receiving_id' ], @@ -4247,7 +4413,7 @@ class ReceivingService extends Service { const receivingIds = entryReceivingRows.map(r => r.receiving_id).filter(Boolean); if (receivingIds.length === 0) { - return { code: 0, message: '该入库单尚未关联收货å�?, data: null }; + return { code: 0, message: '该入库单尚未关联收货单', data: null }; } // 排除已绑定的收货明细(wms_inbound_direct_log 中有记录且未软删除) @@ -4255,7 +4421,8 @@ class ReceivingService extends Service { 'NOT EXISTS (SELECT 1 FROM wms_inbound_direct_log erb WHERE erb.receiving_detail_id = wms_receiving_detail.id AND erb.deleted_at IS NULL)' ); - // 3. 查出所有未绑定的收货明细(不再åœ?SQL 层做 barcode 模糊匹配ï¼? const details = await ctx.model.ReceivingDetail.findAll({ + // 3. 查出所有未绑定的收货明细(不再在 SQL 层做 barcode 模糊匹配) + const details = await ctx.model.ReceivingDetail.findAll({ where: { [Op.and]: [ { receiving_id: { [Op.in]: receivingIds } }, @@ -4269,7 +4436,7 @@ class ReceivingService extends Service { return { code: 0, message: '未找到可用的收货明细', data: null }; } - // 4. 收集所有明细的 system_product_id,批量调ç”?getStockDetails 获取条码 + // 4. 收集所有明细的 system_product_id,批量调用 getStockDetails 获取条码 const stockIdSet = new Set(); for (const d of details) { if (d.system_product_id != null) { @@ -4289,17 +4456,19 @@ class ReceivingService extends Service { } } - // 5. 在内存中遍历明细,精确匹配,收集所有命ä¸? const isNumericBarcode = /^\d+$/.test(normalizedBarcode); + // 5. 在内存中遍历明细,精确匹配,收集所有命中 + const isNumericBarcode = /^\d+$/.test(normalizedBarcode); const matchedDetails = []; for (const detail of details) { - // 优先按明ç»?ID 精确匹配(托盘唛头场景) + // 优先按明细 ID 精确匹配(托盘唛头场景) if (isNumericBarcode && detail.id === Number(normalizedBarcode)) { matchedDetails.push(detail); continue; } - // 按商品条码精确匹é…? const stockDetail = stockDetailMap.get(detail.system_product_id); + // 按商品条码精确匹配 + const stockDetail = stockDetailMap.get(detail.system_product_id); if (stockDetail && Array.isArray(stockDetail.barcodes)) { const barcodeMatch = stockDetail.barcodes.some( bc => bc.barcode === normalizedBarcode @@ -4334,7 +4503,7 @@ class ReceivingService extends Service { }; } catch (error) { ctx.logger.error('[receiving.scanDetail] 扫码定位收货明细失败', error); - return { code: 500, message: `服务器错è¯? ${error.message}`, data: null }; + return { code: 500, message: `服务器错误: ${error.message}`, data: null }; } } From c954a4bb262510be17a6c87710e8b6ee25405082 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 6 Jul 2026 22:24:20 +0800 Subject: [PATCH 099/550] =?UTF-8?q?fix:=20serializeRelation=20=E8=A1=A5?= =?UTF-8?q?=E5=9B=9E=20use=5Fstatus=20=E5=85=BC=E5=AE=B9=E5=AD=97=E6=AE=B5?= =?UTF-8?q?=EF=BC=8C=E6=8C=89=E5=BD=93=E5=89=8D=E4=B8=BB=E4=BD=93=E8=BA=AB?= =?UTF-8?q?=E4=BB=BD=E5=8F=96=E5=AF=B9=E5=BA=94=E4=BB=93=E5=BA=93/?= =?UTF-8?q?=E8=B4=A7=E4=B8=BB=E4=BE=A7=E7=8A=B6=E6=80=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/systems/setting/store_warehouse.js | 3 +++ app/service/systems/store_warehouse.js | 3 +++ 2 files changed, 6 insertions(+) diff --git a/app/service/systems/setting/store_warehouse.js b/app/service/systems/setting/store_warehouse.js index 87d2d30..a01cbf4 100644 --- a/app/service/systems/setting/store_warehouse.js +++ b/app/service/systems/setting/store_warehouse.js @@ -421,6 +421,9 @@ class SettingStoreWarehouseService extends Service { reviewed_by: item.reviewed_by ? Number(item.reviewed_by) : null, ended_by: item.ended_by ? Number(item.ended_by) : null, remask: currentIsWarehouse ? (item.store_remask || '') : (item.warehouse_remask || ''), + use_status: currentIsWarehouse + ? Number(item.warehouse_use_status || 0) + : Number(item.store_use_status || 0), warehouse_use_status: Number(item.warehouse_use_status || 0), store_use_status: Number(item.store_use_status || 0), is_auth_valid: isAuthValid, diff --git a/app/service/systems/store_warehouse.js b/app/service/systems/store_warehouse.js index e64fd0d..3f7b297 100644 --- a/app/service/systems/store_warehouse.js +++ b/app/service/systems/store_warehouse.js @@ -1334,6 +1334,9 @@ class SettingStoreWarehouseService extends Service { reviewed_by: item.reviewed_by ? Number(item.reviewed_by) : null, ended_by: item.ended_by ? Number(item.ended_by) : null, remask: currentIsWarehouse ? (item.store_remask || '') : (item.warehouse_remask || ''), + use_status: currentIsWarehouse + ? Number(item.warehouse_use_status || 0) + : Number(item.store_use_status || 0), warehouse_use_status: Number(item.warehouse_use_status || 0), store_use_status: Number(item.store_use_status || 0), policy_config: item.policy_config && typeof item.policy_config === 'object' ? item.policy_config : null, From 2ff17a54dcedda10b6a3662d05e7a806c1c7966f Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 6 Jul 2026 22:26:38 +0800 Subject: [PATCH 100/550] =?UTF-8?q?fix:=20buildListWhere=20=E8=B4=A7?= =?UTF-8?q?=E4=B8=BB=E4=BE=A7=E6=9F=A5=E8=AF=A2=E6=8C=89=20store=5Fuse=5Fs?= =?UTF-8?q?tatus=20=E8=BF=87=E6=BB=A4=EF=BC=8C=E4=BB=93=E5=BA=93=E4=BE=A7?= =?UTF-8?q?=E6=8C=89=20warehouse=5Fuse=5Fstatus?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/systems/setting/store_warehouse.js | 8 ++++++-- app/service/systems/store_warehouse.js | 8 ++++++-- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/app/service/systems/setting/store_warehouse.js b/app/service/systems/setting/store_warehouse.js index a01cbf4..a2d326e 100644 --- a/app/service/systems/setting/store_warehouse.js +++ b/app/service/systems/setting/store_warehouse.js @@ -326,9 +326,13 @@ class SettingStoreWarehouseService extends Service { where.auth_status = authStatus; } - const useStatus = this.normalizeStatusFlag(data.use_status || data.warehouse_use_status, 'warehouse_use_status', null); + const useStatus = this.normalizeStatusFlag(data.use_status || data.warehouse_use_status || data.store_use_status, 'use_status', null); if (useStatus !== null) { - where.warehouse_use_status = useStatus; + if (currentSubject.isWarehouse) { + where.warehouse_use_status = useStatus; + } else { + where.store_use_status = useStatus; + } } return where; diff --git a/app/service/systems/store_warehouse.js b/app/service/systems/store_warehouse.js index 3f7b297..f7962c4 100644 --- a/app/service/systems/store_warehouse.js +++ b/app/service/systems/store_warehouse.js @@ -923,9 +923,13 @@ class SettingStoreWarehouseService extends Service { where.auth_status = authStatus; } - const useStatus = this.normalizeStatusFlag(data.use_status || data.warehouse_use_status, 'warehouse_use_status', null); + const useStatus = this.normalizeStatusFlag(data.use_status || data.warehouse_use_status || data.store_use_status, 'use_status', null); if (useStatus !== null) { - where.warehouse_use_status = useStatus; + if (currentSubject.isWarehouse) { + where.warehouse_use_status = useStatus; + } else { + where.store_use_status = useStatus; + } } return where; From 72d759964d8b764eafce0a3cbabc3cef7c247d46 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 6 Jul 2026 22:33:05 +0800 Subject: [PATCH 101/550] =?UTF-8?q?fix:=20use=5Fstatus=3D0=20=E8=A2=AB=20|?= =?UTF-8?q?|=20=E8=B7=B3=E8=BF=87=E5=AF=BC=E8=87=B4=E7=AD=9B=E9=80=89?= =?UTF-8?q?=E5=92=8C=E7=8A=B6=E6=80=81=E6=9B=B4=E6=96=B0=E5=A4=B1=E6=95=88?= =?UTF-8?q?=EF=BC=8C=E6=94=B9=E7=94=A8=20!=3D=3D=20undefined=20=E6=98=BE?= =?UTF-8?q?=E5=BC=8F=E5=88=A4=E6=96=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/systems/setting/store_warehouse.js | 8 ++++++-- app/service/systems/store_warehouse.js | 8 ++++++-- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/app/service/systems/setting/store_warehouse.js b/app/service/systems/setting/store_warehouse.js index a2d326e..4c796ea 100644 --- a/app/service/systems/setting/store_warehouse.js +++ b/app/service/systems/setting/store_warehouse.js @@ -326,7 +326,9 @@ class SettingStoreWarehouseService extends Service { where.auth_status = authStatus; } - const useStatus = this.normalizeStatusFlag(data.use_status || data.warehouse_use_status || data.store_use_status, 'use_status', null); + const rawUseStatus = data.use_status !== undefined ? data.use_status + : (data.warehouse_use_status !== undefined ? data.warehouse_use_status : data.store_use_status); + const useStatus = this.normalizeStatusFlag(rawUseStatus, 'use_status', null); if (useStatus !== null) { if (currentSubject.isWarehouse) { where.warehouse_use_status = useStatus; @@ -691,7 +693,9 @@ class SettingStoreWarehouseService extends Service { try { const currentSubject = await this.getCurrentSubject(); const relation = await this.findScopedRelation(data, currentSubject, transaction); - const nextUseStatus = this.normalizeStatusFlag(data.use_status || data.warehouse_use_status, 'warehouse_use_status', 0); + const nextUseStatus = this.normalizeStatusFlag( + data.use_status !== undefined ? data.use_status : data.warehouse_use_status, + 'warehouse_use_status', 0); const patch = currentSubject.isWarehouse ? { warehouse_use_status: nextUseStatus } : { store_use_status: nextUseStatus }; diff --git a/app/service/systems/store_warehouse.js b/app/service/systems/store_warehouse.js index f7962c4..b40f8cc 100644 --- a/app/service/systems/store_warehouse.js +++ b/app/service/systems/store_warehouse.js @@ -923,7 +923,9 @@ class SettingStoreWarehouseService extends Service { where.auth_status = authStatus; } - const useStatus = this.normalizeStatusFlag(data.use_status || data.warehouse_use_status || data.store_use_status, 'use_status', null); + const rawUseStatus = data.use_status !== undefined ? data.use_status + : (data.warehouse_use_status !== undefined ? data.warehouse_use_status : data.store_use_status); + const useStatus = this.normalizeStatusFlag(rawUseStatus, 'use_status', null); if (useStatus !== null) { if (currentSubject.isWarehouse) { where.warehouse_use_status = useStatus; @@ -2404,7 +2406,9 @@ class SettingStoreWarehouseService extends Service { try { const currentSubject = await this.getCurrentSubject(); const relation = await this.findScopedRelation(data, currentSubject, transaction); - const nextUseStatus = this.normalizeStatusFlag(data.use_status || data.warehouse_use_status, 'warehouse_use_status', 0); + const nextUseStatus = this.normalizeStatusFlag( + data.use_status !== undefined ? data.use_status : data.warehouse_use_status, + 'warehouse_use_status', 0); const patch = currentSubject.isWarehouse ? { warehouse_use_status: nextUseStatus } : { store_use_status: nextUseStatus }; From 91d3a4f5b3314b4744016cbe1df20c7c25351fdf Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 6 Jul 2026 22:38:21 +0800 Subject: [PATCH 102/550] =?UTF-8?q?fix:=20counterparty=5Fname=20=E6=94=B9?= =?UTF-8?q?=E4=B8=BA=E5=8F=96=20store=20=E8=A1=A8=20company=5Fname=20?= =?UTF-8?q?=E4=B8=BB=E4=BD=93=E5=90=8D=E7=A7=B0=EF=BC=8C=E4=B8=8D=E5=8F=96?= =?UTF-8?q?=20remask=20=E5=A4=87=E6=B3=A8=E5=90=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/systems/setting/store_warehouse.js | 2 +- app/service/systems/store_warehouse.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/app/service/systems/setting/store_warehouse.js b/app/service/systems/setting/store_warehouse.js index 4c796ea..742c228 100644 --- a/app/service/systems/setting/store_warehouse.js +++ b/app/service/systems/setting/store_warehouse.js @@ -390,7 +390,7 @@ class SettingStoreWarehouseService extends Service { const counterparty = currentIsWarehouse ? item.store : item.warehouse; const storeName = item.store_remask || (item.store && item.store.company_name ? item.store.company_name : ''); const warehouseName = item.warehouse_remask || (item.warehouse && item.warehouse.company_name ? item.warehouse.company_name : ''); - const counterpartyName = currentIsWarehouse ? storeName : warehouseName; + const counterpartyName = counterparty && counterparty.company_name ? counterparty.company_name : ''; let isAuthValid = false; let remainingDays = 0; diff --git a/app/service/systems/store_warehouse.js b/app/service/systems/store_warehouse.js index b40f8cc..6e2e1d9 100644 --- a/app/service/systems/store_warehouse.js +++ b/app/service/systems/store_warehouse.js @@ -1302,7 +1302,7 @@ class SettingStoreWarehouseService extends Service { const counterparty = currentIsWarehouse ? item.store : item.warehouse; const storeName = item.store_remask || (item.store && item.store.company_name ? item.store.company_name : ''); const warehouseName = item.warehouse_remask || (item.warehouse && item.warehouse.company_name ? item.warehouse.company_name : ''); - const counterpartyName = currentIsWarehouse ? storeName : warehouseName; + const counterpartyName = counterparty && counterparty.company_name ? counterparty.company_name : ''; let isAuthValid = false; let remainingDays = 0; From 88df30c8626696898da126abfc370645fc93830b Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 6 Jul 2026 22:41:52 +0800 Subject: [PATCH 103/550] =?UTF-8?q?refactor:=20=E7=AD=BE=E7=BA=A6=E5=88=97?= =?UTF-8?q?=E8=A1=A8=E7=B2=BE=E7=AE=80=E8=BE=93=E5=87=BA=EF=BC=8C=E4=BB=85?= =?UTF-8?q?=E4=BF=9D=E7=95=99=20id/store=5Fid/warehouse=5Fid/counterparty?= =?UTF-8?q?=5Fname/remask/use=5Fstatus/auth=5Fstatus/auth=5Fend/print=5Fqu?= =?UTF-8?q?antity/policy=5Fconfig/has=5Fqimen=5Fconfig?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/systems/setting/store_warehouse.js | 17 ++++++++++++++++- app/service/systems/store_warehouse.js | 17 ++++++++++++++--- 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/app/service/systems/setting/store_warehouse.js b/app/service/systems/setting/store_warehouse.js index 742c228..edea328 100644 --- a/app/service/systems/setting/store_warehouse.js +++ b/app/service/systems/setting/store_warehouse.js @@ -496,7 +496,22 @@ class SettingStoreWarehouseService extends Service { return { code: 200, data: { - list: rows.map(item => this.serializeRelation(item, currentSubject)), + list: rows.map(item => { + const serialized = this.serializeRelation(item, currentSubject); + return { + id: serialized.id, + store_id: serialized.store_id, + warehouse_id: serialized.warehouse_id, + counterparty_name: serialized.counterparty_name, + remask: serialized.remask, + use_status: serialized.use_status, + auth_status: serialized.auth_status, + auth_status_label: serialized.auth_status_label, + auth_end: serialized.auth_end, + print_quantity: serialized.print_quantity, + policy_config: serialized.policy_config, + }; + }), total: Number(count || 0), page, page_size: pageSize, diff --git a/app/service/systems/store_warehouse.js b/app/service/systems/store_warehouse.js index 6e2e1d9..00a97f5 100644 --- a/app/service/systems/store_warehouse.js +++ b/app/service/systems/store_warehouse.js @@ -1434,10 +1434,21 @@ class SettingStoreWarehouseService extends Service { data: { list: rows.map(item => { const serialized = this.serializeRelation(item, currentSubject); - delete serialized.api_config; - delete serialized.apiConfig; serialized.has_qimen_config = qimenConfigMap.has(serialized.id); - return serialized; + return { + id: serialized.id, + store_id: serialized.store_id, + warehouse_id: serialized.warehouse_id, + counterparty_name: serialized.counterparty_name, + remask: serialized.remask, + use_status: serialized.use_status, + auth_status: serialized.auth_status, + auth_status_label: serialized.auth_status_label, + auth_end: serialized.auth_end, + print_quantity: serialized.print_quantity, + has_qimen_config: serialized.has_qimen_config, + policy_config: serialized.policy_config, + }; }), total: Number(count || 0), page, From 19f0449992c15ffff5eb18801d8fe3969e4dc830 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Tue, 7 Jul 2026 17:06:43 +0800 Subject: [PATCH 104/550] =?UTF-8?q?fix:=20=E6=89=8B=E5=B7=A5=E8=BF=90?= =?UTF-8?q?=E5=8D=95=E5=8F=B7=E9=98=B2=E8=AF=AF=E5=88=A0=E4=B8=89=E5=B1=82?= =?UTF-8?q?=E9=98=B2=E6=8A=A4=20+=20=E6=93=8D=E4=BD=9C=E6=97=A5=E5=BF=97bu?= =?UTF-8?q?sinessId=E4=BF=AE=E6=AD=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. hardDeleteWaybillAsyncOrderExpressRows 加 status:0 过滤,保护手工录入 status=1 记录 2. createWaybillCodePipeline 入口跳过 business_key=1 且已分配运单的订单 3. manualWaybill 操作日志 businessId 从仓库ID 修正为订单ID String(orderId) 4. 新增 14 个单元测试,全部通过 --- .../systemMethods/order/pendingOrder.js | 2 +- app/service/systems/express.js | 55 ++- .../pendingOrder.manualWaybill.log.test.js | 180 ++++++++ .../express.manualWaybill.guard.test.js | 407 ++++++++++++++++++ ...07-手工运单号硬删除误删修复单元测试报告.md | 73 ++++ 5 files changed, 714 insertions(+), 3 deletions(-) create mode 100644 test/app/service/systemMethods/order/pendingOrder.manualWaybill.log.test.js create mode 100644 test/app/service/systems/express.manualWaybill.guard.test.js create mode 100644 test_reports/pass/20260707-手工运单号硬删除误删修复单元测试报告.md diff --git a/app/service/systemMethods/order/pendingOrder.js b/app/service/systemMethods/order/pendingOrder.js index 853b1c7..198d430 100644 --- a/app/service/systemMethods/order/pendingOrder.js +++ b/app/service/systemMethods/order/pendingOrder.js @@ -5579,7 +5579,7 @@ class PendingOrderService extends OrderBaseService { try { await this.ctx.service.systems.operationLog.createOperationLog({ businessType: 'order', - businessId: logWarehouseId, + businessId: String(orderId), operationCode: 'ORDER_MANUAL_WAYBILL', operator, extras: { diff --git a/app/service/systems/express.js b/app/service/systems/express.js index e7d38a1..5d16ac5 100644 --- a/app/service/systems/express.js +++ b/app/service/systems/express.js @@ -2216,7 +2216,7 @@ class ExpressService extends Service { /** - * 硬删除运单异步失败分组对应的订单快递记录。 + * 硬删除运单异步失败分组对应的订单快递记录(仅删除 status=0 的未完成记录,保护手工录入等已完成记录)。 * * 删除条件必须同时包含订单ID和业务键,若任一订单缺少 business_key,则记录原因并跳过整个分组,避免误删。 * @@ -2279,6 +2279,7 @@ class ExpressService extends Service { await orderExpressModel.destroy({ where: { [Op.or]: deleteConditions, + status: 0, }, }); return true; @@ -2370,8 +2371,58 @@ class ExpressService extends Service { inputOrderCount: orderList.length, matchedOrderCount: Array.isArray(orders_arr) ? orders_arr.length : 0, }); + + // 【step1.5】过滤已分配运单号(status=1)且传入 business_key=1 的订单,避免重复分配。 + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; + let filteredOrdersArr = orders_arr; + if (orderExpressModel && orders_arr.length > 0) { + const orderIds = orders_arr.map(o => Number(o.id)).filter(id => id > 0); + const completedRows = await orderExpressModel.findAll({ + where: { + order_id: { [Op.in]: orderIds }, + warehouse_id: warehouseId, + status: 1, + }, + attributes: [ 'order_id', 'business_key' ], + raw: true, + }); + const skipSet = new Set(); + for (const row of completedRows) { + skipSet.add(`${Number(row.order_id)}:${Number(row.business_key)}`); + } + if (skipSet.size > 0) { + const beforeCount = orders_arr.length; + filteredOrdersArr = orders_arr.filter(order => { + const matchedExpress = orderList.find(express => Number(order.id) === Number(express.order_id)); + const businessKey = matchedExpress ? Number(matchedExpress.business_key) : 1; + if (businessKey === 1 && skipSet.has(`${Number(order.id)}:1`)) { + return false; + } + return true; + }); + if (filteredOrdersArr.length < beforeCount) { + this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 跳过已分配运单号(business_key=1)的订单', { + traceId, + skippedCount: beforeCount - filteredOrdersArr.length, + skippedOrderIds: orders_arr + .filter(order => { + const matchedExpress = orderList.find(express => Number(order.id) === Number(express.order_id)); + const businessKey = matchedExpress ? Number(matchedExpress.business_key) : 1; + return businessKey === 1 && skipSet.has(`${Number(order.id)}:1`); + }) + .map(o => o.id), + }); + } + } + } + + if (filteredOrdersArr.length === 0) { + this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 所有订单均已分配运单号,无需处理', { traceId }); + return { message: '所有订单均已分配运单号,无需处理' }; + } + // orders_arr和orderList合并 - const ordersWithExpress = orders_arr.map(order => { + const ordersWithExpress = filteredOrdersArr.map(order => { const matchedExpress = orderList.find(express => Number(order.id) === Number(express.order_id)); return { ...order, diff --git a/test/app/service/systemMethods/order/pendingOrder.manualWaybill.log.test.js b/test/app/service/systemMethods/order/pendingOrder.manualWaybill.log.test.js new file mode 100644 index 0000000..31b806d --- /dev/null +++ b/test/app/service/systemMethods/order/pendingOrder.manualWaybill.log.test.js @@ -0,0 +1,180 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const PendingOrderService = require('../../../../../app/service/systemMethods/order/pendingOrder'); + +/** + * 创建 manualWaybill 操作日志回归测试上下文。 + * + * 仅覆盖 operationLog.createOperationLog 的 businessId 传入值。 + */ +function createManualWaybillLogHarness(options = {}) { + const calls = { + operationLogPayload: null, + orderExpressCreatePayload: null, + orderDeliveryUpdatePayload: null, + syncOrderIdsPayload: null, + }; + + const warehouseId = options.warehouseId || 100000; + const testOrderId = options.orderId || 999001; + + const orderRow = { + id: testOrderId, + step: options.orderStep || 1, + outbound_status: options.outboundStatus || 'none', + warehouse_id: warehouseId, + store_id: options.storeId || 1000000, + }; + + const orderExpressMax = options.orderExpressMax !== undefined ? options.orderExpressMax : null; + + const ctx = { + app: { + Sequelize: { + Op: { + in: 'in', + }, + }, + }, + user: { + store_id: warehouseId, + employees_id: '9001', + employees_name: '测试员', + }, + model: { + OrderExpress: { + async max(field, whereOptions) { + return orderExpressMax; + }, + async create(values) { + calls.orderExpressCreatePayload = values; + return { + id: 10001, + ...values, + }; + }, + }, + OrderDeliveryFactory: { + getCurrentModel: () => { + throw new Error('应使用 getOrderModel,不是 OrderDeliveryFactory'); + }, + }, + }, + service: { + systems: { + operationLog: { + async createOperationLog(payload) { + calls.operationLogPayload = payload; + return { id: 1 }; + }, + }, + storeWarehouse: { + async getContractConfig() { + return null; + }, + }, + }, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + }; + + const service = new PendingOrderService(ctx); + + // 注入 mock getOrderModel / buildOrderWhere / success / getWarehouseId + service.getWarehouseId = () => warehouseId; + service.getOrderLogOperator = () => ({ + id: ctx.user && ctx.user.employees_id, + name: ctx.user && ctx.user.employees_name, + }); + service.getOrderLogWarehouseId = () => warehouseId; + + service.getOrderModel = async () => ({ + async findOne(query) { + return orderRow; + }, + async update(values, whereOpts) { + calls.orderDeliveryUpdatePayload = { values, where: whereOpts.where }; + return [ 1 ]; + }, + }); + + service.buildOrderWhere = (orderIds) => ({ + id: { [ctx.app.Sequelize.Op.in]: orderIds }, + warehouse_id: warehouseId, + }); + + service.success = (msg, data) => ({ code: 0, msg, data }); + + service.syncOrderIds = (payload) => { + calls.syncOrderIdsPayload = payload; + return Promise.resolve(); + }; + + return { service, calls, ctx }; +} + +describe('test/app/service/systems/express.manualWaybill.guard.test.js — manualWaybill 操作日志', () => { + it('createOperationLog 的 businessId 应为 String(orderId),而非仓库ID', async () => { + const testOrderId = 888001; + const { service, calls } = createManualWaybillLogHarness({ + orderId: testOrderId, + warehouseId: 100000, + }); + + await service.manualWaybill({ + order_id: testOrderId, + waybill_code: 'SF1234567890', + }); + + assert.ok(calls.operationLogPayload, '应调用 createOperationLog'); + assert.equal(calls.operationLogPayload.businessType, 'order'); + assert.equal(calls.operationLogPayload.businessId, String(testOrderId), + `businessId 应为订单ID "${testOrderId}",而非仓库ID`); + assert.equal(calls.operationLogPayload.operationCode, 'ORDER_MANUAL_WAYBILL'); + assert.equal(calls.operationLogPayload.extras.warehouseId, 100000); + assert.equal(calls.operationLogPayload.extras.orderId, testOrderId); + assert.equal(calls.operationLogPayload.extras.waybillCode, 'SF1234567890'); + }); + + it('businessId 不应为 warehouseId(回归验证)', async () => { + const testOrderId = 888002; + const warehouseId = 100000; + const { service, calls } = createManualWaybillLogHarness({ + orderId: testOrderId, + warehouseId, + }); + + await service.manualWaybill({ + order_id: testOrderId, + waybill_code: 'YT9876543210', + }); + + assert.ok(calls.operationLogPayload, '应调用 createOperationLog'); + assert.notEqual(calls.operationLogPayload.businessId, String(warehouseId), + `businessId 不应为仓库ID "${warehouseId}"`); + assert.equal(calls.operationLogPayload.businessId, String(testOrderId), + `businessId 应为订单ID "${testOrderId}"`); + }); + + it('business_key 从已有最大值递增', async () => { + const testOrderId = 888003; + const { service, calls } = createManualWaybillLogHarness({ + orderId: testOrderId, + orderExpressMax: 3, + }); + + await service.manualWaybill({ + order_id: testOrderId, + waybill_code: 'EMS0000000001', + }); + + assert.ok(calls.orderExpressCreatePayload); + assert.equal(calls.orderExpressCreatePayload.business_key, 4, '应从 max(3)+1=4 递增'); + assert.equal(calls.orderExpressCreatePayload.status, 1, '手工录入 status 应为 1'); + }); +}); diff --git a/test/app/service/systems/express.manualWaybill.guard.test.js b/test/app/service/systems/express.manualWaybill.guard.test.js new file mode 100644 index 0000000..e78d10c --- /dev/null +++ b/test/app/service/systems/express.manualWaybill.guard.test.js @@ -0,0 +1,407 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const ExpressService = require('../../../../app/service/systems/express'); + +// ============================================================================ +// Harness: hardDeleteWaybillAsyncOrderExpressRows +// ============================================================================ + +function createHardDeleteHarness(options = {}) { + const calls = { + destroyCount: 0, + destroyWhere: null, + loggerErrors: [], + }; + + const orderExpressModel = { + async destroy(whereOptions) { + calls.destroyCount += 1; + calls.destroyWhere = whereOptions; + if (typeof options.destroy === 'function') { + return await options.destroy(whereOptions); + } + return 1; + }, + }; + + const ctx = { + app: { + Sequelize: { + Op: { + or: 'or', + }, + }, + }, + model: { + OrderExpress: options.orderExpressModel !== undefined ? options.orderExpressModel : orderExpressModel, + }, + logger: { + info() {}, + warn() {}, + error(...args) { + calls.loggerErrors.push(args); + }, + }, + }; + + const service = new ExpressService(ctx); + + return { service, calls, ctx }; +} + +// ============================================================================ +// Harness: createWaybillCodePipeline — skip business_key=1 + status=1 +// ============================================================================ + +function createPipelineSkipHarness(options = {}) { + const calls = { + asyncTaskPayloads: [], + printPlatformFindAllQueries: [], + listByWarehousePlatformCodePayloads: [], + orderExpressFindAllQueries: [], + loggerInfoMessages: [], + }; + + const orderDeliveryRows = Array.isArray(options.orderDeliveryRows) + ? options.orderDeliveryRows + : [ + { + id: 1, + sys_platform_code: 'PDD', + logistics_code: 'SF', + sys_platform_name: '拼多多', + logistics_name: '顺丰', + store_id: 100000, + }, + { + id: 2, + sys_platform_code: 'PDD', + logistics_code: 'SF', + sys_platform_name: '拼多多', + logistics_name: '顺丰', + store_id: 100000, + }, + ]; + + const orderExpressRows = Array.isArray(options.orderExpressRows) + ? options.orderExpressRows + : []; + + const platformList = Array.isArray(options.platformList) ? options.platformList : [{ + code: 'PDD', + print_platform_id: 901, + default_express_interface: 'POLYAPI', + }]; + const printPlatformRows = Array.isArray(options.printPlatformRows) ? options.printPlatformRows : [ + { + id: 901, + platform_code: 'PDD_PRINT', + request_platform_code: 'OPEN_API', + }, + ]; + const listData = Array.isArray(options.listData) ? options.listData : []; + + const ctx = { + app: { + Sequelize: { + Op: { + in: 'in', + }, + }, + }, + user: { + store_id: 100000, + }, + model: { + OrderExpress: { + async findAll(query) { + calls.orderExpressFindAllQueries.push(query); + return orderExpressRows; + }, + }, + OrderDeliveryFactory: { + async getCurrentModel() { + return { + async findAll() { + return orderDeliveryRows; + }, + async update() { + return [ 1 ]; + }, + }; + }, + }, + PrintPlatform: { + async findAll(query) { + calls.printPlatformFindAllQueries.push(query); + return printPlatformRows; + }, + }, + }, + service: { + systems: { + platform: { + async getPlatformList() { + return platformList; + }, + }, + setting: { + expressInterface: { + async listByWarehousePlatformCode(payload) { + calls.listByWarehousePlatformCodePayloads.push(payload); + return { data: listData }; + }, + }, + }, + }, + }, + logger: { + info(...args) { + calls.loggerInfoMessages.push(args.map(a => String(a)).join(' ')); + }, + warn() {}, + error() {}, + }, + }; + + const service = new ExpressService(ctx); + service.asyncTask = (batch, opts, matchedPlatform, expressInterfaceConfig) => { + calls.asyncTaskPayloads.push({ batch, opts, matchedPlatform, expressInterfaceConfig }); + }; + + return { service, calls, ctx }; +} + +// ============================================================================ +// Tests: hardDeleteWaybillAsyncOrderExpressRows +// ============================================================================ + +describe('test/app/service/systems/express.manualWaybill.guard.test.js', () => { + describe('hardDeleteWaybillAsyncOrderExpressRows — status:0 过滤', () => { + it('destroy 应包含 status:0 条件,保护 status=1 的手工记录', async () => { + const { service, calls } = createHardDeleteHarness(); + + await service.hardDeleteWaybillAsyncOrderExpressRows( + [ + { order_id: 100, business_key: 1 }, + { order_id: 200, business_key: 2 }, + ], + { platform_code: 'PDD', error_message: '测试失败' } + ); + + assert.equal(calls.destroyCount, 1); + assert.ok(calls.destroyWhere, 'destroy 应被调用'); + assert.ok(calls.destroyWhere.where, 'where 条件应存在'); + assert.equal(calls.destroyWhere.where.status, 0, 'status 必须为 0'); + assert.ok(Array.isArray(calls.destroyWhere.where.or), 'or 条件应存在'); + assert.equal(calls.destroyWhere.where.or.length, 2); + }); + + it('缺少 business_key 时应返回 false,不调用 destroy', async () => { + const { service, calls } = createHardDeleteHarness(); + + const result = await service.hardDeleteWaybillAsyncOrderExpressRows( + [{ order_id: 100 }], + { platform_code: 'JD' } + ); + + assert.equal(result, false); + assert.equal(calls.destroyCount, 0, '缺少 business_key 不应调用 destroy'); + }); + + it('缺少 order_id 时应返回 false,不调用 destroy', async () => { + const { service, calls } = createHardDeleteHarness(); + + const result = await service.hardDeleteWaybillAsyncOrderExpressRows( + [{ business_key: 1 }], + { platform_code: 'JD' } + ); + + assert.equal(result, false); + assert.equal(calls.destroyCount, 0); + }); + + it('OrderExpress 模型不可用时应返回 false', async () => { + const { service, calls } = createHardDeleteHarness({ + orderExpressModel: null, + }); + + const result = await service.hardDeleteWaybillAsyncOrderExpressRows( + [{ order_id: 100, business_key: 1 }], + {} + ); + + assert.equal(result, false); + assert.equal(calls.destroyCount, 0); + }); + + it('空数组应返回 false', async () => { + const { service, calls } = createHardDeleteHarness(); + + const result = await service.hardDeleteWaybillAsyncOrderExpressRows([], {}); + + assert.equal(result, false); + assert.equal(calls.destroyCount, 0); + }); + + it('destroy 抛异常时应返回 false 并记录错误日志', async () => { + const { service, calls } = createHardDeleteHarness({ + destroy: async () => { + throw new Error('DB 连接失败'); + }, + }); + + const result = await service.hardDeleteWaybillAsyncOrderExpressRows( + [{ order_id: 100, business_key: 1 }], + { platform_code: 'PDD', error_message: 'err' } + ); + + assert.equal(result, false); + assert.equal(calls.destroyCount, 1); + assert.ok(calls.loggerErrors.length > 0, '应记录错误日志'); + }); + }); + + // ========================================================================== + // Tests: createWaybillCodePipeline — 跳过已分配运单的订单 + // ========================================================================== + + describe('createWaybillCodePipeline — 跳过 business_key=1 已分配订单', () => { + it('订单已有 status=1 且传入 business_key=1 时,应跳过该订单', async () => { + const { service, calls } = createPipelineSkipHarness({ + orderDeliveryRows: [ + { + id: 101, + sys_platform_code: 'PDD', + logistics_code: 'SF', + sys_platform_name: '拼多多', + logistics_name: '顺丰', + store_id: 100000, + }, + { + id: 102, + sys_platform_code: 'PDD', + logistics_code: 'SF', + sys_platform_name: '拼多多', + logistics_name: '顺丰', + store_id: 100000, + }, + ], + orderExpressRows: [ + { order_id: 101, business_key: 1, status: 1 }, + ], + }); + + await service.createWaybillCodePipeline([ + { order_id: 101, business_key: 1 }, + { order_id: 102, business_key: 1 }, + ]); + + // 订单 101 应被跳过,只有 102 进入 asyncTask + assert.equal(calls.asyncTaskPayloads.length, 1, '只有未分配的订单应进入 asyncTask'); + const batch = calls.asyncTaskPayloads[0].batch; + const batchOrderIds = batch.map(o => o.id); + assert.ok(!batchOrderIds.includes(101), '订单 101 不应在 batch 中'); + assert.ok(batchOrderIds.includes(102), '订单 102 应在 batch 中'); + }); + + it('订单有 status=1 但传入 business_key=2 时,不应跳过(不同 business_key)', async () => { + const { service, calls } = createPipelineSkipHarness({ + orderDeliveryRows: [ + { + id: 201, + sys_platform_code: 'PDD', + logistics_code: 'SF', + sys_platform_name: '拼多多', + logistics_name: '顺丰', + store_id: 100000, + }, + ], + orderExpressRows: [ + { order_id: 201, business_key: 1, status: 1 }, + ], + }); + + await service.createWaybillCodePipeline([ + { order_id: 201, business_key: 2 }, + ]); + + // business_key=2 不同于已完成的 business_key=1,不应跳过 + assert.equal(calls.asyncTaskPayloads.length, 1, 'business_key 不同时不应跳过'); + }); + + it('订单有 status=1 但 business_key 不是 1 时,传入 business_key=1 应跳过', async () => { + const { service, calls } = createPipelineSkipHarness({ + orderDeliveryRows: [ + { + id: 301, + sys_platform_code: 'PDD', + logistics_code: 'SF', + sys_platform_name: '拼多多', + logistics_name: '顺丰', + store_id: 100000, + }, + ], + orderExpressRows: [ + { order_id: 301, business_key: 2, status: 1 }, + ], + }); + + await service.createWaybillCodePipeline([ + { order_id: 301, business_key: 1 }, + ]); + + // skipSet 中有 "301:2",但过滤条件是 businessKey===1 && skipSet.has("301:1") + // 这里 skipSet 中没有 "301:1",所以不应跳过 + assert.equal(calls.asyncTaskPayloads.length, 1, 'skipSet 中无匹配的 business_key=1 时不应跳过'); + }); + + it('全部订单均已完成时,应直接返回无需处理', async () => { + const { service, calls } = createPipelineSkipHarness({ + orderDeliveryRows: [ + { + id: 401, + sys_platform_code: 'PDD', + logistics_code: 'SF', + sys_platform_name: '拼多多', + logistics_name: '顺丰', + store_id: 100000, + }, + ], + orderExpressRows: [ + { order_id: 401, business_key: 1, status: 1 }, + ], + }); + + const result = await service.createWaybillCodePipeline([ + { order_id: 401, business_key: 1 }, + ]); + + assert.equal(calls.asyncTaskPayloads.length, 0, '全部跳过时不应调用 asyncTask'); + assert.equal(result.message, '所有订单均已分配运单号,无需处理'); + }); + + it('无 status=1 记录时,所有订单正常进入 pipeline', async () => { + const { service, calls } = createPipelineSkipHarness({ + orderDeliveryRows: [ + { + id: 501, + sys_platform_code: 'PDD', + logistics_code: 'SF', + sys_platform_name: '拼多多', + logistics_name: '顺丰', + store_id: 100000, + }, + ], + orderExpressRows: [], + }); + + await service.createWaybillCodePipeline([ + { order_id: 501, business_key: 1 }, + ]); + + assert.equal(calls.asyncTaskPayloads.length, 1, '无已完成记录时所有订单应正常处理'); + }); + }); +}); diff --git a/test_reports/pass/20260707-手工运单号硬删除误删修复单元测试报告.md b/test_reports/pass/20260707-手工运单号硬删除误删修复单元测试报告.md new file mode 100644 index 0000000..d06e213 --- /dev/null +++ b/test_reports/pass/20260707-手工运单号硬删除误删修复单元测试报告.md @@ -0,0 +1,73 @@ +# 20260707-手工运单号硬删除误删修复单元测试报告 + +## 测试目标 +验证上一轮三轮修复(`hardDeleteWaybillAsyncOrderExpressRows` 加 `status:0` 过滤、`manualWaybill` 操作日志 `businessId` 修正、`createWaybillCodePipeline` 跳过已分配订单)是否符合预期。 + +## 测试类型 +单元测试(Unit Test) + +## 测试范围 + +| 被测方法 | 被测文件 | 测试用例数 | 通过 | 失败 | +|----------|---------|-----------|------|------| +| `hardDeleteWaybillAsyncOrderExpressRows` | `app/service/systems/express.js` | 6 | 6 | 0 | +| `createWaybillCodePipeline` | `app/service/systems/express.js` | 5 | 5 | 0 | +| `manualWaybill` | `app/service/systemMethods/order/pendingOrder.js` | 3 | 3 | 0 | + +## 测试产物 + +- `test/app/service/systems/express.manualWaybill.guard.test.js` — hardDelete + pipeline 跳过逻辑测试 +- `test/app/service/systemMethods/order/pendingOrder.manualWaybill.log.test.js` — manualWaybill 操作日志测试 + +## 测试结果摘要 + +### ✅ 全部 14 个测试用例通过(0 失败) + +### 1. hardDeleteWaybillAsyncOrderExpressRows — status:0 过滤 + +| 用例 | 结果 | +|------|------| +| destroy 应包含 status:0 条件,保护 status=1 的手工记录 | ✅ PASS | +| 缺少 business_key 时应返回 false,不调用 destroy | ✅ PASS | +| 缺少 order_id 时应返回 false,不调用 destroy | ✅ PASS | +| OrderExpress 模型不可用时应返回 false | ✅ PASS | +| 空数组应返回 false | ✅ PASS | +| destroy 抛异常时应返回 false 并记录错误日志 | ✅ PASS | + +### 2. createWaybillCodePipeline — 跳过 business_key=1 已分配订单 + +| 用例 | 结果 | +|------|------| +| 订单已有 status=1 且传入 business_key=1 时,应跳过该订单 | ✅ PASS | +| 订单有 status=1 但传入 business_key=2 时,不应跳过(不同 business_key) | ✅ PASS | +| 订单有 status=1 但 business_key 不是 1 时,传入 business_key=1 应跳过 | ✅ PASS | +| 全部订单均已完成时,应直接返回无需处理 | ✅ PASS | +| 无 status=1 记录时,所有订单正常进入 pipeline | ✅ PASS | + +### 3. manualWaybill — 操作日志 businessId 修正 + +| 用例 | 结果 | +|------|------| +| createOperationLog 的 businessId 应为 String(orderId),而非仓库ID | ✅ PASS | +| businessId 不应为 warehouseId(回归验证) | ✅ PASS | +| business_key 从已有最大值递增 | ✅ PASS | + +## 关键验证点 + +1. **三层防护闭环验证**: + - 第 1 层(pipeline 入口):`business_key=1` + 已完成的订单在 pipeline 入口即被过滤 + - 第 2 层(trans 内):`createWaybillCode` 的 `completedOrderKeySet` 事务内二次校验 + - 第 3 层(失败清理):`hardDeleteWaybillAsyncOrderExpressRows` 仅删 `status=0` + +2. **操作日志可检索性**:`manualWaybill` 的 `businessId` 已修正为订单 ID,可通过订单 ID 检索操作日志 + +3. **向后兼容**: + - `business_key ≠ 1` 的已分配订单不会被误跳过 + - 无已完成记录时 pipeline 正常运作 + +## 结论与建议 + +三轮修复均通过单元测试验证,符合预期行为: +- 手工录入的运单号(`status=1`)不再被失败清理逻辑误删 +- 操作日志可正确按订单 ID 检索 +- pipeline 入口即过滤已分配订单,避免无效异步任务提交 From 14a5f13ad5c5d98dc7ad4344bbe75453b45cff23 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Thu, 9 Jul 2026 03:36:03 +0800 Subject: [PATCH 105/550] =?UTF-8?q?feat(db):=20wms=5Fstore=5Fwarehouse=20?= =?UTF-8?q?=E6=96=B0=E5=A2=9E=20initiator=5Fsubject=5Fid=EF=BC=8Cwms=5Fpic?= =?UTF-8?q?king=20=E6=96=B0=E5=A2=9E=20stock=5Fid=20=E5=8F=8A=E8=81=94?= =?UTF-8?q?=E5=90=88=E7=B4=A2=E5=BC=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - wms_store_warehouse: 新增 initiator_subject_id 记录发起方主体ID - wms_picking: 新增 stock_id 字段 + idx_wms_picking_warehouse_stock 联合索引 + 历史数据回填 - Model 层同步更新关联定义 --- app/model/picking.js | 19 ++++++++++- app/model/store_warehouse.js | 5 +++ ...initiator-subject-id-to-store-warehouse.js | 24 +++++++++++++ ...60708000000-add-stock-id-to-wms-picking.js | 34 +++++++++++++++++++ 4 files changed, 81 insertions(+), 1 deletion(-) create mode 100644 database/migrations/20260707-add-initiator-subject-id-to-store-warehouse.js create mode 100644 database/migrations/20260708000000-add-stock-id-to-wms-picking.js diff --git a/app/model/picking.js b/app/model/picking.js index 987d337..f731c97 100644 --- a/app/model/picking.js +++ b/app/model/picking.js @@ -31,6 +31,11 @@ module.exports = app => { allowNull: true, comment: '库存记录ID', }, + stock_id: { + type: BIGINT(20), + allowNull: true, + comment: '商品SKU ID', + }, quantity: { type: INTEGER(10).UNSIGNED, allowNull: false, @@ -102,11 +107,15 @@ module.exports = app => { name: 'idx_wms_picking_order_item_space', fields: [ 'order_item_id', 'space_id' ], }, + { + name: 'idx_wms_picking_warehouse_stock', + fields: [ 'warehouse_id', 'stock_id' ], + }, ], }); Picking.associate = function() { - const { OrderItems, Storage, LocationSpace } = app.model; + const { OrderItems, Storage, LocationSpace, StockWarehouse } = app.model; if (OrderItems) { Picking.belongsTo(OrderItems, { @@ -131,6 +140,14 @@ module.exports = app => { constraints: false, }); } + + if (StockWarehouse) { + Picking.belongsTo(StockWarehouse, { + foreignKey: 'stock_id', + as: 'stock', + constraints: false, + }); + } }; return Picking; diff --git a/app/model/store_warehouse.js b/app/model/store_warehouse.js index e204d38..52136f9 100644 --- a/app/model/store_warehouse.js +++ b/app/model/store_warehouse.js @@ -509,6 +509,11 @@ module.exports = app => { allowNull: true, comment: '解除人', }, + initiator_subject_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '发起方主体ID(wms_store.id)', + }, created_at: { type: DATE, allowNull: false, diff --git a/database/migrations/20260707-add-initiator-subject-id-to-store-warehouse.js b/database/migrations/20260707-add-initiator-subject-id-to-store-warehouse.js new file mode 100644 index 0000000..9699f88 --- /dev/null +++ b/database/migrations/20260707-add-initiator-subject-id-to-store-warehouse.js @@ -0,0 +1,24 @@ +'use strict'; + +/** + * wms_store_warehouse 增加 initiator_subject_id 记录发起方主体 ID, + * 用于区分签-约发起方(与 applied_by 账号 ID 互补)。 + */ +module.exports = { + async up(queryInterface) { + const { sequelize } = queryInterface; + await sequelize.query(` + ALTER TABLE wms_store_warehouse + ADD COLUMN initiator_subject_id BIGINT(20) UNSIGNED NULL COMMENT '发起方主体ID(wms_store.id)' + AFTER ended_by + `); + }, + + async down(queryInterface) { + const { sequelize } = queryInterface; + await sequelize.query(` + ALTER TABLE wms_store_warehouse + DROP COLUMN initiator_subject_id + `); + }, +}; diff --git a/database/migrations/20260708000000-add-stock-id-to-wms-picking.js b/database/migrations/20260708000000-add-stock-id-to-wms-picking.js new file mode 100644 index 0000000..d9ac4f6 --- /dev/null +++ b/database/migrations/20260708000000-add-stock-id-to-wms-picking.js @@ -0,0 +1,34 @@ +'use strict'; + +/** + * 为 wms_picking 表新增 stock_id 字段及联合索引。 + * + * 用途:消除面单打印自定义区对 wms_order_items 明细表的强依赖, + * 使打印链路可通过 wms_picking.stock_id 直读商品信息与条码数据。 + */ +module.exports = { + up: async queryInterface => { + await queryInterface.sequelize.query(` + ALTER TABLE wms_picking + ADD COLUMN stock_id BIGINT(20) DEFAULT NULL COMMENT '商品SKU ID' AFTER storage_id, + ADD INDEX idx_wms_picking_warehouse_stock (warehouse_id, stock_id) + `); + + // 回填已有 picking 记录的 stock_id(通过 storage 链路补全) + await queryInterface.sequelize.query(` + UPDATE wms_picking p + INNER JOIN wms_storage s ON p.storage_id = s.id + SET p.stock_id = s.stock_id + WHERE p.stock_id IS NULL + AND p.storage_id IS NOT NULL + `); + }, + + down: async queryInterface => { + await queryInterface.sequelize.query(` + ALTER TABLE wms_picking + DROP INDEX idx_wms_picking_warehouse_stock, + DROP COLUMN stock_id + `); + }, +}; From b9ead1fba2e82913965ec44de9354d8ea0b14d0f Mon Sep 17 00:00:00 2001 From: liufumingren Date: Thu, 9 Jul 2026 03:36:09 +0800 Subject: [PATCH 106/550] =?UTF-8?q?refactor(storeWarehouse):=20=E7=AD=BE?= =?UTF-8?q?=E7=BA=A6=E4=BD=93=E7=B3=BB=E9=87=8D=E6=9E=84=20=E2=80=94=20?= =?UTF-8?q?=E7=BB=9F=E4=B8=80=E4=B8=BB=E4=BD=93=E7=BB=B4=E5=BA=A6=E3=80=81?= =?UTF-8?q?=E7=A7=BB=E9=99=A4=E8=A7=92=E8=89=B2=E6=A0=A1=E9=AA=8C=E3=80=81?= =?UTF-8?q?list=20=E6=8B=86=E5=88=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - sign: 统一当前主体→store_id(货主方/消费方),对方→warehouse_id(仓库方/提供方) - getCounterparty: 移除 expectedRole 角色校验,仓库可签仓库、货主可签货主 - list: 拆分为 listForStore/listForWarehouse,warehouse 侧支持查询外部合作仓库 - 新增 buildListWhereByStoreId 统一按 store_id 维度构建查询条件 - 响应新增 counterparty_role / needs_my_confirm / has_qimen_config 字段 --- .../systemMethods/storeWarehouse/store.js | 34 +- .../systemMethods/storeWarehouse/warehouse.js | 44 +- .../systems/setting/store_warehouse.js | 206 ++---- app/service/systems/store_warehouse.js | 623 ++++++++++++------ 4 files changed, 575 insertions(+), 332 deletions(-) diff --git a/app/service/systemMethods/storeWarehouse/store.js b/app/service/systemMethods/storeWarehouse/store.js index 3ce0b58..92ac429 100644 --- a/app/service/systemMethods/storeWarehouse/store.js +++ b/app/service/systemMethods/storeWarehouse/store.js @@ -26,14 +26,14 @@ class StoreWarehouseStoreService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'list,sign,unbind,rename,openAccount,getPolicyConfig,getPolicyConfigFields,savePolicyConfig,listApiConfig,saveApiConfig,deleteQimenConfig'; + const _noNeedRight = 'list,sign,confirmSign,unbind,rename,openAccount,getPolicyConfig,getPolicyConfigFields,savePolicyConfig,listApiConfig,saveApiConfig,deleteQimenConfig'; const _noNeedLog = '*'; - const _noNeedAuth = 'list,sign,unbind,rename,openAccount,getPolicyConfig,getPolicyConfigFields,savePolicyConfig,listApiConfig,saveApiConfig,deleteQimenConfig'; + const _noNeedAuth = 'list,sign,confirmSign,unbind,rename,openAccount,getPolicyConfig,getPolicyConfigFields,savePolicyConfig,listApiConfig,saveApiConfig,deleteQimenConfig'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } /** - * 获取签约列表。 + * 获取签约列表(货主侧)。 * * @param {Object} data 请求数据。 * @return {Promise} 统一响应结果。 @@ -41,7 +41,7 @@ class StoreWarehouseStoreService extends MainService { async list(data = {}) { const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse; - if (!targetService || typeof targetService.list !== 'function') { + if (!targetService || typeof targetService.listForStore !== 'function') { return this.fail('获取签约列表失败', { code: 500, }); @@ -49,7 +49,7 @@ class StoreWarehouseStoreService extends MainService { try { const payload = normalizeStoreWarehousePayload(data); - const result = await targetService.list(payload); + const result = await targetService.listForStore(payload); return this.success('ok', result); } catch (error) { return this.fail(error.message || '获取签约列表失败', { @@ -84,6 +84,30 @@ class StoreWarehouseStoreService extends MainService { } } + /** + * 确认签约:对方主体确认待签约的申请。 + * + * @param {Object} data 请求数据。 + * @return {Promise} 统一响应结果。 + */ + async confirmSign(data = {}) { + const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse; + + if (!targetService || typeof targetService.confirmSign !== 'function') { + return this.fail('确认签约失败', { code: 500 }); + } + + try { + const payload = normalizeStoreWarehousePayload(data); + const result = await targetService.confirmSign(payload); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '确认签约失败', { + code: Number(error.code) || 500, + }); + } + } + /** * 修改签约名称。 * diff --git a/app/service/systemMethods/storeWarehouse/warehouse.js b/app/service/systemMethods/storeWarehouse/warehouse.js index 3a5bdcc..0aa4ab4 100644 --- a/app/service/systemMethods/storeWarehouse/warehouse.js +++ b/app/service/systemMethods/storeWarehouse/warehouse.js @@ -19,14 +19,14 @@ class StoreWarehouseWarehouseService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'list'; + const _noNeedRight = 'list,sign,confirmSign'; const _noNeedLog = '*'; - const _noNeedAuth = 'list'; + const _noNeedAuth = 'list,sign,confirmSign'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } /** - * 仓库侧获取签约列表。 + * 仓库侧获取签约列表(含外部合作仓库)。 * * @param {Object} data 请求数据。 * @return {Promise} 统一响应结果。 @@ -34,13 +34,13 @@ class StoreWarehouseWarehouseService extends MainService { async list(data = {}) { const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse; - if (!targetService || typeof targetService.list !== 'function') { + if (!targetService || typeof targetService.listForWarehouse !== 'function') { return this.fail('获取签约列表失败', { code: 500 }); } try { const payload = normalizeWarehouseStorePayload(data); - const result = await targetService.list(payload); + const result = await targetService.listForWarehouse(payload); return this.success('ok', result); } catch (error) { return this.fail(error.message || '获取签约列表失败', { @@ -48,6 +48,40 @@ class StoreWarehouseWarehouseService extends MainService { }); } } + + /** + * 仓库侧发起签约。 + */ + async sign(data = {}) { + const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse; + if (!targetService || typeof targetService.sign !== 'function') { + return this.fail('签约失败', { code: 500 }); + } + try { + const payload = normalizeWarehouseStorePayload(data); + const result = await targetService.sign(payload); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '签约失败', { code: Number(error.code) || 500 }); + } + } + + /** + * 仓库侧确认签约。 + */ + async confirmSign(data = {}) { + const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse; + if (!targetService || typeof targetService.confirmSign !== 'function') { + return this.fail('确认签约失败', { code: 500 }); + } + try { + const payload = normalizeWarehouseStorePayload(data); + const result = await targetService.confirmSign(payload); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '确认签约失败', { code: Number(error.code) || 500 }); + } + } } module.exports = StoreWarehouseWarehouseService; diff --git a/app/service/systems/setting/store_warehouse.js b/app/service/systems/setting/store_warehouse.js index edea328..2609d04 100644 --- a/app/service/systems/setting/store_warehouse.js +++ b/app/service/systems/setting/store_warehouse.js @@ -509,7 +509,6 @@ class SettingStoreWarehouseService extends Service { auth_status_label: serialized.auth_status_label, auth_end: serialized.auth_end, print_quantity: serialized.print_quantity, - policy_config: serialized.policy_config, }; }), total: Number(count || 0), @@ -526,149 +525,90 @@ class SettingStoreWarehouseService extends Service { async sign(data = {}) { const action = this.normalizeSignAction(data.action || data.mode); - if (data.temp_code || data.tempCode || action === 'preview') { - const { ctx } = this; - const transaction = await ctx.model.transaction(); + if (action === 'preview') { + const currentSubject = await this.getCurrentSubject(); + const pair = this.resolvePairIds(data, currentSubject); + const counterparty = await this.getCounterparty(pair.counterpartyId, currentSubject.isWarehouse ? 'store' : 'warehouse'); + return { + code: 200, + data: { + mode: 'preview', + current_subject: { store_id: currentSubject.id, company_name: currentSubject.company_name, role: currentSubject.isWarehouse ? 'warehouse' : 'store' }, + counterparty: { id: Number(counterparty.id || 0), company_name: counterparty.company_name || '', role: currentSubject.isWarehouse ? 'store' : 'warehouse' }, + }, + }; + } - try { - const currentSubject = await this.getCurrentSubject(); - const accountId = this.getCurrentAccountId(); - const { tempCode, payload } = await this.getTempSignPayload(data.temp_code || data.tempCode); - const isParticipant = [ Number(payload.initiator_subject_id || 0), Number(payload.counterparty_id || 0) ] - .includes(Number(currentSubject.id)); + const { ctx } = this; + const transaction = await ctx.model.transaction(); + try { + const currentSubject = await this.getCurrentSubject(); + const accountId = this.getCurrentAccountId(); + const pair = this.resolvePairIds(data, currentSubject); + const counterparty = await this.getCounterparty(pair.counterpartyId, currentSubject.isWarehouse ? 'store' : 'warehouse'); + const authStart = this.normalizeDate(data.auth_start, 'auth_start', { allowNull: true }) || new Date(); + const authEnd = this.normalizeDate(data.auth_end, 'auth_end', { allowNull: true }); + if (authEnd && authStart.getTime() > authEnd.getTime()) throw this.createError('auth_end 不能早于 auth_start', 400); - if (!isParticipant) { - throw this.createError('当前主体无权使用该临时码', 403); - } + const relationPatch = { + store_id: pair.storeId, warehouse_id: pair.warehouseId, auth_status: 1, + apply_reason: this.normalizeText(data.apply_reason, 'apply_reason', 2000), + apply_time: new Date(), print_quantity: this.normalizeNonNegativeInteger(data.print_quantity, 'print_quantity', 0), + review_time: null, auth_start: authStart, auth_end: authEnd, actual_end: null, + applied_by: accountId, reviewed_by: null, ended_by: null, initiator_subject_id: currentSubject.id, + warehouse_use_status: 1, store_use_status: 1, print_quantity_locked: 0, + }; + Object.assign(relationPatch, this.buildCurrentRemaskPatch(data, currentSubject)); - if (action === 'preview' || data.preview === 1 || data.preview === '1') { - await transaction.rollback(); - return { - code: 200, - data: this.buildTempSignView(tempCode, payload, currentSubject), - }; - } + let relation = await ctx.model.StoreWarehouse.findOne({ where: { store_id: pair.storeId, warehouse_id: pair.warehouseId }, transaction }); + const isCreate = !relation; - if (Number(currentSubject.id) !== Number(payload.counterparty_id || 0)) { - throw this.createError('需由对方主体确认后才可生效', 400); - } - - const relationPatch = { - store_id: Number(payload.store_id || 0), - warehouse_id: Number(payload.warehouse_id || 0), - auth_status: 2, - apply_reason: payload.apply_reason || '', - apply_time: payload.created_at ? new Date(payload.created_at) : new Date(), - print_quantity: Number(payload.print_quantity || 0), - review_time: new Date(), - auth_start: payload.auth_start ? new Date(payload.auth_start) : new Date(), - auth_end: payload.auth_end ? new Date(payload.auth_end) : null, - actual_end: null, - applied_by: Number(payload.initiated_by || 0) || accountId, - reviewed_by: accountId, - ended_by: null, - warehouse_use_status: 1, - store_use_status: 1, - }; - - if (payload.store_remask !== undefined) { - relationPatch.store_remask = payload.store_remask; - } - if (payload.warehouse_remask !== undefined) { - relationPatch.warehouse_remask = payload.warehouse_remask; - } - Object.assign(relationPatch, this.buildCurrentRemaskPatch(data, currentSubject)); - - let relation = await ctx.model.StoreWarehouse.findOne({ - where: { - store_id: relationPatch.store_id, - warehouse_id: relationPatch.warehouse_id, - }, - transaction, - }); - const isCreate = !relation; - - if (relation) { + if (relation) { + if (relation.applied_by === accountId && relation.auth_status === 1) { await relation.update(relationPatch, { transaction }); + } else if (relation.applied_by === accountId && relation.auth_status >= 2) { + const existing = await ctx.model.StoreWarehouse.findByPk(relation.id, { include: this.getRelationIncludes(), transaction }); + await transaction.rollback(); + return { code: 200, data: { mode: 'already_confirmed', exists_status: relation.auth_status, exists_status_label: '已签约', contract: this.trimContract(this.serializeRelation(existing, currentSubject)) } }; } else { - relation = await ctx.model.StoreWarehouse.create(relationPatch, { transaction }); + const existing = await ctx.model.StoreWarehouse.findByPk(relation.id, { include: this.getRelationIncludes(), transaction }); + await transaction.rollback(); + return { code: 200, data: { mode: 'already_exists', exists_status: relation.auth_status, exists_status_label: relation.auth_status === 2 ? '已签约' : '待确认', contract: this.trimContract(this.serializeRelation(existing, currentSubject)) } }; } - - const result = await ctx.model.StoreWarehouse.findByPk(relation.id, { - include: this.getRelationIncludes(), - transaction, - }); - - await this.clearTempSignPayload(tempCode); - await transaction.commit(); - - return { - code: 200, - data: { - mode: 'confirm', - temp_code: tempCode, - contract: this.serializeRelation(result, currentSubject), - action: isCreate ? 'create' : 'update', - }, - }; - } catch (error) { - await transaction.rollback(); - throw error; + } else { + relation = await ctx.model.StoreWarehouse.create(relationPatch, { transaction }); } - } - const currentSubject = await this.getCurrentSubject(); - const accountId = this.getCurrentAccountId(); - const pair = this.resolvePairIds(data, currentSubject); - const counterparty = await this.getCounterparty(pair.counterpartyId, currentSubject.isWarehouse ? 'store' : 'warehouse'); - const authStart = this.normalizeDate(data.auth_start, 'auth_start', { allowNull: true }) || new Date(); - const authEnd = this.normalizeDate(data.auth_end, 'auth_end', { allowNull: true }); - if (authEnd && authStart.getTime() > authEnd.getTime()) { - throw this.createError('auth_end 不能早于 auth_start', 400); - } + const result = await ctx.model.StoreWarehouse.findByPk(relation.id, { include: this.getRelationIncludes(), transaction }); + await transaction.commit(); + return { code: 200, data: { mode: 'initiate', contract: this.trimContract(this.serializeRelation(result, currentSubject)), action: isCreate ? 'create' : 'update' } }; + } catch (error) { await transaction.rollback(); throw error; } + } - const remask = this.resolveRemaskValue(data, currentSubject); - const payload = { - initiated_by: accountId, - initiator_subject_id: currentSubject.id, - initiator_role: currentSubject.isWarehouse ? 'warehouse' : 'store', - initiator_name: currentSubject.company_name, - counterparty_id: Number(counterparty.id || 0), - counterparty_role: currentSubject.isWarehouse ? 'store' : 'warehouse', - counterparty_name: counterparty.company_name || '', - store_id: pair.storeId, - warehouse_id: pair.warehouseId, - auth_start: authStart.toISOString(), - auth_end: authEnd ? authEnd.toISOString() : null, - print_quantity: this.normalizeNonNegativeInteger(data.print_quantity, 'print_quantity', 0), - apply_reason: this.normalizeText(data.apply_reason, 'apply_reason', 2000), - remask: remask || '', - created_at: new Date().toISOString(), - ...this.buildCurrentRemaskPatch(data, currentSubject), - }; + trimContract(serialized) { + return { id: serialized.id, store_id: serialized.store_id, warehouse_id: serialized.warehouse_id, counterparty_name: serialized.counterparty_name, remask: serialized.remask, use_status: serialized.use_status, auth_status: serialized.auth_status, auth_status_label: serialized.auth_status_label, auth_end: serialized.auth_end, print_quantity: serialized.print_quantity, has_qimen_config: serialized.has_qimen_config }; + } - const signPayload = await this.saveTempSignPayload(payload); - - return { - code: 200, - data: { - mode: 'initiate', - temp_code: signPayload.tempCode, - expires_at: signPayload.expiresAt, - expires_in: signPayload.expiresIn, - can_confirm: false, - current_subject: { - store_id: currentSubject.id, - company_name: currentSubject.company_name, - role: currentSubject.isWarehouse ? 'warehouse' : 'store', - }, - counterparty: { - id: Number(counterparty.id || 0), - company_name: counterparty.company_name || '', - role: currentSubject.isWarehouse ? 'store' : 'warehouse', - }, - }, - }; + async confirmSign(data = {}) { + const { ctx } = this; + const transaction = await ctx.model.transaction(); + try { + const currentSubject = await this.getCurrentSubject(); + const accountId = this.getCurrentAccountId(); + const relationId = this.toPositiveNumber(data.id, 'id'); + if (!relationId) throw this.createError('id 参数不能为空', 400); + const relation = await ctx.model.StoreWarehouse.findOne({ where: { id: relationId }, include: this.getRelationIncludes(), transaction }); + if (!relation) throw this.createError('签约关系不存在', 404); + if (relation.auth_status !== 1) throw this.createError('当前签约状态不允许确认,仅待签约状态可确认', 400); + const isCurrentStore = relation.store_id === currentSubject.id; + const isCurrentWarehouse = relation.warehouse_id === currentSubject.id; + if (!isCurrentStore && !isCurrentWarehouse) throw this.createError('当前主体不在此签约关系中', 403); + if (relation.initiator_subject_id === currentSubject.id) throw this.createError('发起方不能确认自己的签约申请', 403); + await relation.update({ auth_status: 2, review_time: new Date(), reviewed_by: accountId }, { transaction }); + const result = await ctx.model.StoreWarehouse.findByPk(relation.id, { include: this.getRelationIncludes(), transaction }); + await transaction.commit(); + return { code: 200, data: { mode: 'confirm', contract: this.trimContract(this.serializeRelation(result, currentSubject)) } }; + } catch (error) { await transaction.rollback(); throw error; } } async rename(data = {}) { diff --git a/app/service/systems/store_warehouse.js b/app/service/systems/store_warehouse.js index 00a97f5..c981ea4 100644 --- a/app/service/systems/store_warehouse.js +++ b/app/service/systems/store_warehouse.js @@ -854,14 +854,14 @@ class SettingStoreWarehouseService extends Service { } /** - * 获取签约对方主体信息。 + * 获取签约对方主体信息(不校验项目角色,仓库可签仓库、货主可签货主)。 * * @param {number} counterpartyId 对方主体 ID。 - * @param {string} expectedRole 期望角色。 + * @param {string} [_expectedRole] 期望角色(已废弃,保留参数兼容)。 * @return {Promise} 对方主体对象。 - * @throws {Error} 对方主体不存在或角色不匹配时抛出,状态码为 400/404。 + * @throws {Error} 对方主体不存在时抛出,状态码为 404。 */ - async getCounterparty(counterpartyId, expectedRole) { + async getCounterparty(counterpartyId, _expectedRole) { const { ctx } = this; const counterparty = await ctx.model.Store.findOne({ where: { @@ -874,24 +874,55 @@ class SettingStoreWarehouseService extends Service { throw this.createError('签约对象不存在', 404); } - const isWarehouse = counterparty.project === 'warehouse'; - if (expectedRole === 'warehouse' && !isWarehouse) { - throw this.createError('目标对象不是仓库主体,无法签约', 400); - } - if (expectedRole === 'store' && isWarehouse) { - throw this.createError('目标对象不是货主主体,无法签约', 400); - } - return counterparty; } /** - * 构建列表查询条件。 + * 构建列表查询条件(按 store_id 维度)。 + * + * 当前主体始终作为 store_id 方(货主方/消费方),对方为 warehouse_id 方(仓库方/提供方)。 * * @param {Object} data 请求参数。 * @param {Object} currentSubject 当前主体。 * @return {Object} where 查询条件。 */ + buildListWhereByStoreId(data, currentSubject) { + const where = { + store_id: currentSubject.id, + }; + + const relationId = this.resolveRelationId(data); + if (relationId) { + where.id = relationId; + } + + const counterpartyId = this.toPositiveNumber(data.counterparty_id || data.warehouse_id, 'counterparty_id', { allowEmpty: true }); + if (counterpartyId) { + where.warehouse_id = counterpartyId; + } + + const authStatus = this.normalizeAuthStatus(data.auth_status); + if (authStatus !== null) { + where.auth_status = authStatus; + } + + const rawUseStatus = data.use_status !== undefined ? data.use_status : data.store_use_status; + const useStatus = this.normalizeStatusFlag(rawUseStatus, 'use_status', null); + if (useStatus !== null) { + where.store_use_status = useStatus; + } + + return where; + } + + /** + * 构建列表查询条件(兼容旧逻辑,保留以供其他方法使用)。 + * + * @param {Object} data 请求参数。 + * @param {Object} currentSubject 当前主体。 + * @return {Object} where 查询条件。 + * @deprecated 新代码请使用 buildListWhereByStoreId。 + */ buildListWhere(data, currentSubject) { const where = {}; @@ -1254,25 +1285,19 @@ class SettingStoreWarehouseService extends Service { /** * 解析成对的合同主体 ID。 * + * 规则:当前主体(签约发起方)始终为 store_id 方(货主方/消费方), + * 对方始终为 warehouse_id 方(仓库方/提供方)。 + * * @param {Object} data 请求参数。 * @param {Object} currentSubject 当前主体。 * @return {Object} 包含 storeId、warehouseId、counterpartyId 的对象。 * @throws {Error} 对方主体参数非法时抛出,状态码为 400。 */ resolvePairIds(data, currentSubject) { - const fieldName = currentSubject.isWarehouse ? 'store_id / counterparty_id' : 'warehouse_id / counterparty_id'; const rawCounterpartyId = data.counterparty_id !== undefined ? data.counterparty_id - : (currentSubject.isWarehouse ? data.store_id : data.warehouse_id); - const counterpartyId = this.toPositiveNumber(rawCounterpartyId, fieldName); - - if (currentSubject.isWarehouse) { - return { - storeId: counterpartyId, - warehouseId: currentSubject.id, - counterpartyId, - }; - } + : (data.store_id && Number(data.store_id) !== currentSubject.id ? data.store_id : data.warehouse_id); + const counterpartyId = this.toPositiveNumber(rawCounterpartyId, 'counterparty_id / 对方主体ID'); return { storeId: currentSubject.id, @@ -1299,7 +1324,11 @@ class SettingStoreWarehouseService extends Service { const authStatus = Number(item.auth_status || 0); const currentIsWarehouse = !!(currentSubject && currentSubject.isWarehouse); - const counterparty = currentIsWarehouse ? item.store : item.warehouse; + + // 当前主体始终在 store_id 方(货主方/消费方),对方始终在 warehouse_id 方(仓库方/提供方) + const counterparty = item.warehouse; + const counterpartyRole = counterparty && counterparty.project === 'warehouse' ? 'warehouse' : 'store'; + const storeName = item.store_remask || (item.store && item.store.company_name ? item.store.company_name : ''); const warehouseName = item.warehouse_remask || (item.warehouse && item.warehouse.company_name ? item.warehouse.company_name : ''); const counterpartyName = counterparty && counterparty.company_name ? counterparty.company_name : ''; @@ -1324,6 +1353,7 @@ class SettingStoreWarehouseService extends Service { warehouse_name: warehouseName, counterparty_id: counterparty && counterparty.id ? Number(counterparty.id) : 0, counterparty_name: counterpartyName, + counterparty_role: counterpartyRole, current_subject_role: currentIsWarehouse ? 'warehouse' : 'store', auth_status: authStatus, auth_status_label: AUTH_STATUS_LABELS[authStatus] || '', @@ -1345,7 +1375,6 @@ class SettingStoreWarehouseService extends Service { : Number(item.store_use_status || 0), warehouse_use_status: Number(item.warehouse_use_status || 0), store_use_status: Number(item.store_use_status || 0), - policy_config: item.policy_config && typeof item.policy_config === 'object' ? item.policy_config : null, is_auth_valid: isAuthValid, remaining_days: remainingDays, api_config: normalizedQimenConfig || null, @@ -1354,7 +1383,11 @@ class SettingStoreWarehouseService extends Service { } /** - * 获取受限范围内的签约关系。 + * 获取受限范围内的签约关系(兼容新旧签约数据)。 + * + * 新数据:当前主体在 store_id(发起方/消费方)。 + * 旧数据:仓库主体可能在 warehouse_id(提供方)。 + * 使用 OR 查询两边,确保新旧数据都能被操作。 * * @param {Object} data 请求参数。 * @param {Object} currentSubject 当前主体。 @@ -1364,21 +1397,27 @@ class SettingStoreWarehouseService extends Service { */ async findScopedRelation(data, currentSubject, transaction) { const { ctx } = this; - const where = currentSubject.isWarehouse - ? { warehouse_id: currentSubject.id } - : { store_id: currentSubject.id }; + const { Op } = ctx.app.Sequelize; + + const scopedWhere = {}; const relationId = this.resolveRelationId(data); if (relationId) { - where.id = relationId; + scopedWhere.id = relationId; } else { const pair = this.resolvePairIds(data, currentSubject); - where.store_id = pair.storeId; - where.warehouse_id = pair.warehouseId; + scopedWhere.store_id = pair.storeId; + scopedWhere.warehouse_id = pair.warehouseId; } const relation = await ctx.model.StoreWarehouse.findOne({ - where, + where: { + ...scopedWhere, + [Op.or]: [ + { store_id: currentSubject.id }, + { warehouse_id: currentSubject.id }, + ], + }, include: this.getRelationIncludes(), transaction, }); @@ -1391,11 +1430,169 @@ class SettingStoreWarehouseService extends Service { } /** - * 查询签约关系列表。 + * 货主侧查询签约关系列表。 + * + * 当前货主主体在 store_id 方,对方仓库在 warehouse_id 方。 * * @param {Object} [data={}] 请求参数。 * @return {Promise} 接口响应对象。 */ + async listForStore(data = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const currentSubject = await this.getCurrentSubject(); + const page = this.normalizePage(data.page, 'page', 1, 1000000); + const pageSize = this.normalizePage(data.page_size || data.pageSize, 'page_size', 20, 200); + const offset = (page - 1) * pageSize; + const where = this.buildListWhereByStoreId(data, currentSubject); + const keyword = typeof data.keyword === 'string' ? data.keyword.trim() : ''; + + if (keyword) { + where[Op.or] = [ + { store_remask: { [Op.like]: `%${keyword}%` } }, + { warehouse_remask: { [Op.like]: `%${keyword}%` } }, + { '$store.company_name$': { [Op.like]: `%${keyword}%` } }, + { '$warehouse.company_name$': { [Op.like]: `%${keyword}%` } }, + ]; + } + + const { rows, count } = await ctx.model.StoreWarehouse.findAndCountAll({ + where, + include: this.getRelationIncludes(), + order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]], + offset, + limit: pageSize, + distinct: true, + }); + + const contractIds = rows.map(item => Number(item.id || 0)).filter(id => id > 0); + const qimenConfigMap = contractIds.length + ? await this.getQimenConfigMap(contractIds) + : new Map(); + + return { + code: 200, + data: { + list: rows.map(item => { + const serialized = this.serializeRelation(item, currentSubject); + serialized.has_qimen_config = qimenConfigMap.has(serialized.id); + return { + id: serialized.id, + store_id: serialized.store_id, + warehouse_id: serialized.warehouse_id, + counterparty_id: serialized.counterparty_id, + counterparty_name: serialized.counterparty_name, + counterparty_role: serialized.counterparty_role, + remask: serialized.remask, + use_status: serialized.use_status, + auth_status: serialized.auth_status, + auth_status_label: serialized.auth_status_label, + auth_end: serialized.auth_end, + print_quantity: serialized.print_quantity, + has_qimen_config: serialized.has_qimen_config, + needs_my_confirm: Number(item.auth_status || 0) === 1 + && Number(item.initiator_subject_id || 0) !== currentSubject.id, + }; + }), + total: Number(count || 0), + page, + page_size: pageSize, + current_subject: { + store_id: currentSubject.id, + company_name: currentSubject.company_name, + role: currentSubject.isWarehouse ? 'warehouse' : 'store', + }, + }, + }; + } + + /** + * 仓库侧查询签约关系列表。 + * + * 当前仓库主体在 store_id 方(消费方),对方(可能是仓库或货主)在 warehouse_id 方(提供方)。 + * 支持查询仓库与外部合作仓库的关系。 + * + * @param {Object} [data={}] 请求参数。 + * @return {Promise} 接口响应对象。 + */ + async listForWarehouse(data = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const currentSubject = await this.getCurrentSubject(); + const page = this.normalizePage(data.page, 'page', 1, 1000000); + const pageSize = this.normalizePage(data.page_size || data.pageSize, 'page_size', 20, 200); + const offset = (page - 1) * pageSize; + const where = this.buildListWhereByStoreId(data, currentSubject); + const keyword = typeof data.keyword === 'string' ? data.keyword.trim() : ''; + + if (keyword) { + where[Op.or] = [ + { store_remask: { [Op.like]: `%${keyword}%` } }, + { warehouse_remask: { [Op.like]: `%${keyword}%` } }, + { '$store.company_name$': { [Op.like]: `%${keyword}%` } }, + { '$warehouse.company_name$': { [Op.like]: `%${keyword}%` } }, + ]; + } + + const { rows, count } = await ctx.model.StoreWarehouse.findAndCountAll({ + where, + include: this.getRelationIncludes(), + order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]], + offset, + limit: pageSize, + distinct: true, + }); + + const contractIds = rows.map(item => Number(item.id || 0)).filter(id => id > 0); + const qimenConfigMap = contractIds.length + ? await this.getQimenConfigMap(contractIds) + : new Map(); + + return { + code: 200, + data: { + list: rows.map(item => { + const serialized = this.serializeRelation(item, currentSubject); + serialized.has_qimen_config = qimenConfigMap.has(serialized.id); + return { + id: serialized.id, + store_id: serialized.store_id, + store_name: serialized.store_name, + warehouse_id: serialized.warehouse_id, + warehouse_name: serialized.warehouse_name, + counterparty_id: serialized.counterparty_id, + counterparty_name: serialized.counterparty_name, + counterparty_role: serialized.counterparty_role, + remask: serialized.remask, + use_status: serialized.store_use_status, + auth_status: serialized.auth_status, + auth_status_label: serialized.auth_status_label, + auth_end: serialized.auth_end, + print_quantity: serialized.print_quantity, + has_qimen_config: serialized.has_qimen_config, + needs_my_confirm: Number(item.auth_status || 0) === 1 + && Number(item.initiator_subject_id || 0) !== currentSubject.id, + }; + }), + total: Number(count || 0), + page, + page_size: pageSize, + current_subject: { + store_id: currentSubject.id, + company_name: currentSubject.company_name, + role: currentSubject.isWarehouse ? 'warehouse' : 'store', + }, + }, + }; + } + + /** + * 查询签约关系列表(旧版,保留向后兼容)。 + * + * @param {Object} [data={}] 请求参数。 + * @return {Promise} 接口响应对象。 + * @deprecated 新代码请使用 listForStore 或 listForWarehouse。 + */ async list(data = {}) { const { ctx, app } = this; const { Op } = app.Sequelize; @@ -1447,7 +1644,8 @@ class SettingStoreWarehouseService extends Service { auth_end: serialized.auth_end, print_quantity: serialized.print_quantity, has_qimen_config: serialized.has_qimen_config, - policy_config: serialized.policy_config, + needs_my_confirm: Number(item.auth_status || 0) === 1 + && Number(item.initiator_subject_id || 0) !== currentSubject.id, }; }), total: Number(count || 0), @@ -1470,174 +1668,221 @@ class SettingStoreWarehouseService extends Service { */ async sign(data = {}) { const action = this.normalizeSignAction(data.action || data.mode); - if (data.temp_code || data.tempCode || action === 'preview') { - const { ctx } = this; - const transaction = await ctx.model.transaction(); + if (action === 'preview') { + const currentSubject = await this.getCurrentSubject(); + const pair = this.resolvePairIds(data, currentSubject); + const counterparty = await this.getCounterparty(pair.counterpartyId, currentSubject.isWarehouse ? 'store' : 'warehouse'); + return { + code: 200, + data: { + mode: 'preview', + current_subject: { + store_id: currentSubject.id, + company_name: currentSubject.company_name, + role: currentSubject.isWarehouse ? 'warehouse' : 'store', + }, + counterparty: { + id: Number(counterparty.id || 0), + company_name: counterparty.company_name || '', + role: counterparty.project === 'warehouse' ? 'warehouse' : 'store', + }, + }, + }; + } - try { - const currentSubject = await this.getCurrentSubject(); - const accountId = this.getCurrentAccountId(); - const { tempCode, payload } = await this.getTempSignPayload(data.temp_code || data.tempCode); - const isParticipant = [ Number(payload.initiator_subject_id || 0), Number(payload.counterparty_id || 0) ] - .includes(Number(currentSubject.id)); + const { ctx } = this; + const transaction = await ctx.model.transaction(); - if (!isParticipant) { - throw this.createError('当前主体无权使用该临时码', 403); - } + try { + const currentSubject = await this.getCurrentSubject(); + const accountId = this.getCurrentAccountId(); + const pair = this.resolvePairIds(data, currentSubject); + const counterparty = await this.getCounterparty(pair.counterpartyId, currentSubject.isWarehouse ? 'store' : 'warehouse'); + const authStart = this.normalizeDate(data.auth_start, 'auth_start', { allowNull: true }) || new Date(); + const authEnd = this.normalizeDate(data.auth_end, 'auth_end', { allowNull: true }); + if (authEnd && authStart.getTime() > authEnd.getTime()) { + throw this.createError('auth_end 不能早于 auth_start', 400); + } - if (action === 'preview' || data.preview === 1 || data.preview === '1') { + const relationPatch = { + store_id: pair.storeId, + warehouse_id: pair.warehouseId, + auth_status: 1, + apply_reason: this.normalizeText(data.apply_reason, 'apply_reason', 2000), + apply_time: new Date(), + print_quantity: this.normalizeNonNegativeInteger(data.print_quantity, 'print_quantity', 0), + review_time: null, + auth_start: authStart, + auth_end: authEnd, + actual_end: null, + applied_by: accountId, + reviewed_by: null, + ended_by: null, + initiator_subject_id: currentSubject.id, + warehouse_use_status: 1, + store_use_status: 1, + print_quantity_locked: 0, + }; + + Object.assign(relationPatch, this.buildCurrentRemaskPatch(data, currentSubject)); + + let relation = await ctx.model.StoreWarehouse.findOne({ + where: { + store_id: pair.storeId, + warehouse_id: pair.warehouseId, + }, + transaction, + }); + const isCreate = !relation; + + if (relation) { + if (relation.applied_by === accountId && relation.auth_status === 1) { + await relation.update(relationPatch, { transaction }); + } else if (relation.applied_by === accountId && relation.auth_status >= 2) { + const existing = await ctx.model.StoreWarehouse.findByPk(relation.id, { include: this.getRelationIncludes(), transaction }); await transaction.rollback(); return { code: 200, - data: this.buildTempSignView(tempCode, payload, currentSubject), + data: { + mode: 'already_confirmed', + exists_status: relation.auth_status, + exists_status_label: '已签约', + contract: this.trimContract(this.serializeRelation(existing, currentSubject)), + }, + }; + } else { + const existing = await ctx.model.StoreWarehouse.findByPk(relation.id, { include: this.getRelationIncludes(), transaction }); + await transaction.rollback(); + return { + code: 200, + data: { + mode: 'already_exists', + exists_status: relation.auth_status, + exists_status_label: relation.auth_status === 2 ? '已签约' : '待确认', + contract: this.trimContract(this.serializeRelation(existing, currentSubject)), + }, }; } - - if (Number(currentSubject.id) !== Number(payload.counterparty_id || 0)) { - throw this.createError('需由对方主体确认后才可生效', 400); - } - - const relationPatch = { - store_id: Number(payload.store_id || 0), - warehouse_id: Number(payload.warehouse_id || 0), - auth_status: 2, - apply_reason: payload.apply_reason || '', - apply_time: payload.created_at ? new Date(payload.created_at) : new Date(), - print_quantity: Number(payload.print_quantity || 0), - review_time: new Date(), - auth_start: payload.auth_start ? new Date(payload.auth_start) : new Date(), - auth_end: payload.auth_end ? new Date(payload.auth_end) : null, - actual_end: null, - applied_by: Number(payload.initiated_by || 0) || accountId, - reviewed_by: accountId, - ended_by: null, - warehouse_use_status: 1, - store_use_status: 1, - }; - - if (payload.store_remask !== undefined) { - relationPatch.store_remask = payload.store_remask; - } - if (payload.warehouse_remask !== undefined) { - relationPatch.warehouse_remask = payload.warehouse_remask; - } - Object.assign(relationPatch, this.buildCurrentRemaskPatch(data, currentSubject)); - - let relation = await ctx.model.StoreWarehouse.findOne({ - where: { - store_id: relationPatch.store_id, - warehouse_id: relationPatch.warehouse_id, - }, - transaction, - }); - const isCreate = !relation; - - if (relation) { - await relation.update(relationPatch, { transaction }); - } else { - relation = await ctx.model.StoreWarehouse.create(relationPatch, { transaction }); - } - - const result = await ctx.model.StoreWarehouse.findByPk(relation.id, { - include: this.getRelationIncludes(), - transaction, - }); - const qimenConfig = await this.getSingleQimenConfig(relation.id, { - allowDisabled: true, - transaction, - }); - - await this.clearTempSignPayload(tempCode); - await transaction.commit(); - - // 记录操作日志 - try { - await ctx.service.systems.operationLog.createOperationLog({ - businessType: 'store', - businessId: relation.id, - operationCode: 'STORE_SIGN', - operator: { - id: ctx.user?.employees_id || ctx.user?.id, - name: ctx.user?.employees_name || '', - }, - extras: { - warehouseId: Number(payload.warehouse_id || 0), - }, - beforeChanges: null, - }); - } catch (logErr) { - ctx.logger.warn('[storeWarehouse.sign] 写入操作日志失败,不影响业务', logErr); - } - - return { - code: 200, - data: { - mode: 'confirm', - temp_code: tempCode, - contract: this.serializeRelation(result, currentSubject, qimenConfig), - action: isCreate ? 'create' : 'update', - }, - }; - } catch (error) { - await transaction.rollback(); - throw error; + } else { + relation = await ctx.model.StoreWarehouse.create(relationPatch, { transaction }); } + + const result = await ctx.model.StoreWarehouse.findByPk(relation.id, { + include: this.getRelationIncludes(), + transaction, + }); + + const wasExisting = !!relation._previousDataValues; + + await transaction.commit(); + + return { + code: 200, + data: { + mode: 'initiate', + contract: this.trimContract(this.serializeRelation(result, currentSubject)), + action: isCreate ? 'create' : 'update', + }, + }; + } catch (error) { + await transaction.rollback(); + throw error; } + } - const currentSubject = await this.getCurrentSubject(); - const accountId = this.getCurrentAccountId(); - const pair = this.resolvePairIds(data, currentSubject); - const counterparty = await this.getCounterparty(pair.counterpartyId, currentSubject.isWarehouse ? 'store' : 'warehouse'); - const authStart = this.normalizeDate(data.auth_start, 'auth_start', { allowNull: true }) || new Date(); - const authEnd = this.normalizeDate(data.auth_end, 'auth_end', { allowNull: true }); - if (authEnd && authStart.getTime() > authEnd.getTime()) { - throw this.createError('auth_end 不能早于 auth_start', 400); - } - - const remask = this.resolveRemaskValue(data, currentSubject); - const payload = { - initiated_by: accountId, - initiator_subject_id: currentSubject.id, - initiator_role: currentSubject.isWarehouse ? 'warehouse' : 'store', - initiator_name: currentSubject.company_name, - counterparty_id: Number(counterparty.id || 0), - counterparty_role: currentSubject.isWarehouse ? 'store' : 'warehouse', - counterparty_name: counterparty.company_name || '', - store_id: pair.storeId, - warehouse_id: pair.warehouseId, - auth_start: authStart.toISOString(), - auth_end: authEnd ? authEnd.toISOString() : null, - print_quantity: this.normalizeNonNegativeInteger(data.print_quantity, 'print_quantity', 0), - apply_reason: this.normalizeText(data.apply_reason, 'apply_reason', 2000), - remask: remask || '', - created_at: new Date().toISOString(), - ...this.buildCurrentRemaskPatch(data, currentSubject), - }; - - const signPayload = await this.saveTempSignPayload(payload); - + /** + * 精简签约对象,仅保留前端需要的字段。 + */ + trimContract(serialized) { return { - code: 200, - data: { - mode: 'initiate', - temp_code: signPayload.tempCode, - expires_at: signPayload.expiresAt, - expires_in: signPayload.expiresIn, - can_confirm: false, - current_subject: { - store_id: currentSubject.id, - company_name: currentSubject.company_name, - role: currentSubject.isWarehouse ? 'warehouse' : 'store', - }, - counterparty: { - id: Number(counterparty.id || 0), - company_name: counterparty.company_name || '', - role: currentSubject.isWarehouse ? 'store' : 'warehouse', - }, - }, + id: serialized.id, + store_id: serialized.store_id, + warehouse_id: serialized.warehouse_id, + counterparty_name: serialized.counterparty_name, + remask: serialized.remask, + use_status: serialized.use_status, + auth_status: serialized.auth_status, + auth_status_label: serialized.auth_status_label, + auth_end: serialized.auth_end, + print_quantity: serialized.print_quantity, + has_qimen_config: serialized.has_qimen_config, }; } + /** + * 确认签约:对方主体确认待签约的申请,状态从 1(申请中)变为 2(已通过)。 + * 发起方不能确认自己的申请。 + * + * @param {Object} [data={}] 请求参数。 + * @param {number} data.id 签约关系ID。 + * @return {Promise} 接口响应对象。 + */ + async confirmSign(data = {}) { + const { ctx } = this; + const transaction = await ctx.model.transaction(); + + try { + const currentSubject = await this.getCurrentSubject(); + const accountId = this.getCurrentAccountId(); + const relationId = this.resolveRelationId(data); + + if (!relationId) { + throw this.createError('id 参数不能为空', 400); + } + + const relation = await ctx.model.StoreWarehouse.findOne({ + where: { id: relationId }, + include: this.getRelationIncludes(), + transaction, + }); + + if (!relation) { + throw this.createError('签约关系不存在', 404); + } + + if (relation.auth_status !== 1) { + throw this.createError('当前签约状态不允许确认,仅待签约状态可确认', 400); + } + + // 确定当前主体在签约中的角色 + const isCurrentStore = relation.store_id === currentSubject.id; + const isCurrentWarehouse = relation.warehouse_id === currentSubject.id; + + if (!isCurrentStore && !isCurrentWarehouse) { + throw this.createError('当前主体不在此签约关系中', 403); + } + + // 发起签约的主体不能确认自己的申请,必须由对方主体确认 + if (relation.initiator_subject_id === currentSubject.id) { + throw this.createError('发起方不能确认自己的签约申请', 403); + } + + await relation.update({ + auth_status: 2, + review_time: new Date(), + reviewed_by: accountId, + }, { transaction }); + + const result = await ctx.model.StoreWarehouse.findByPk(relation.id, { + include: this.getRelationIncludes(), + transaction, + }); + + await transaction.commit(); + + return { + code: 200, + data: { + mode: 'confirm', + contract: this.trimContract(this.serializeRelation(result, currentSubject)), + }, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + /** * 修改签约关系脱敏名称。 * From ca5c8a269e28c2f4ba5ee7f08fbd3a943d98c07d Mon Sep 17 00:00:00 2001 From: liufumingren Date: Thu, 9 Jul 2026 03:36:15 +0800 Subject: [PATCH 107/550] =?UTF-8?q?feat:=20=E6=8E=A8=E5=8D=95=E4=BA=8C?= =?UTF-8?q?=E7=BA=A7=E6=A0=A1=E9=AA=8C=20+=20=E5=BF=AB=E9=80=92=E5=88=86?= =?UTF-8?q?=E9=85=8D=E5=BC=82=E6=AD=A5=E5=8C=96=20+=20=E6=89=93=E5=8D=B0?= =?UTF-8?q?=20stock=5Fid=20=E7=9B=B4=E8=AF=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - delivery_order: 新增 auth_status=2 + warehouse_use_status=1 二级签约校验 - express: createWaybillCodePipeline 支持 awaitTasks/onBatchComplete 选项 - pendingOrder: allocateExpressCode 异步进度缓存 + cancelAllocateStorage 拣货完成前置校验 - order_print: 新增 wms_picking.stock_id→wms_stock_warehouse 直读路径,消除 order_items 强依赖 --- .../systemMethods/order/pendingOrder.js | 328 ++++++++++++++---- app/service/systemMethods/print.js | 2 +- app/service/systems/delivery_order.js | 18 +- app/service/systems/express.js | 76 +++- app/service/systems/order_print.js | 81 ++++- 5 files changed, 405 insertions(+), 100 deletions(-) diff --git a/app/service/systemMethods/order/pendingOrder.js b/app/service/systemMethods/order/pendingOrder.js index 198d430..aa9bf57 100644 --- a/app/service/systemMethods/order/pendingOrder.js +++ b/app/service/systemMethods/order/pendingOrder.js @@ -28,6 +28,17 @@ const BATCH_LOCK_TASK_CACHE_TTL_SECONDS = 60 * 60 * 24; const BATCH_UNLOCK_TASK_CACHE_KEY_PREFIX = 'order:batch-unlock:'; const BATCH_UNLOCK_TASK_CACHE_TTL_SECONDS = 60 * 60 * 24; +const ALLOCATE_EXPRESS_TASK_CACHE_KEY_PREFIX = 'order:pending:allocate_express:request:'; +const ALLOCATE_EXPRESS_TASK_CACHE_TTL_SECONDS = 60 * 60 * 2; +const ALLOCATE_EXPRESS_PROGRESS_MAP = Object.freeze({ + submitted: 5, + running: 50, + success: 100, + failed: 100, + not_found: 0, + unknown: 0, +}); + const BATCH_UNINTERCEPT_TASK_CACHE_KEY_PREFIX = 'order:batch-unintercept:'; const BATCH_UNINTERCEPT_TASK_CACHE_TTL_SECONDS = 60 * 60 * 24; @@ -517,9 +528,9 @@ class PendingOrderService extends OrderBaseService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,updateOrderPlatform,updateOrderExpress,updateRemark,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill'; - const _noNeedLog = 'list,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill'; - const _noNeedAuth = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,updateOrderPlatform,updateOrderExpress,updateRemark,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill'; + const _noNeedRight = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateExpressCodeTaskProgress,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,updateOrderPlatform,updateOrderExpress,updateRemark,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill'; + const _noNeedLog = 'list,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateExpressCodeTaskProgress,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill'; + const _noNeedAuth = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateExpressCodeTaskProgress,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,updateOrderPlatform,updateOrderExpress,updateRemark,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -1385,6 +1396,88 @@ class PendingOrderService extends OrderBaseService { } } + // ========== allocateExpressCode 异步任务进度缓存工具方法 ========== + + /** + * 获取快递分配任务缓存键。 + * + * @param {string} taskId 任务ID。 + * @return {string} 缓存键。 + */ + getAllocateExpressTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + return `${ALLOCATE_EXPRESS_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 规范快递分配任务ID。 + * + * @param {Object} data 请求体。 + * @return {string} 归一化后的任务ID。 + */ + normalizeAllocateExpressTaskId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.task_id || normalizedData.taskId || '').trim(); + } + + /** + * 写入快递分配任务进度。 + * + * @param {string} taskId 任务ID。 + * @param {Object} payload 任务状态与结果。 + * @return {Promise} 无返回值。 + */ + async setAllocateExpressTaskProgress(taskId = '', payload = {}) { + const cacheKey = this.getAllocateExpressTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.setCacheAsync !== 'function') { + return; + } + + const safePayload = this.isPlainObject(payload) ? payload : {}; + const progressPayload = { + task_id: String(taskId || '').trim(), + status: String(safePayload.status || 'unknown').trim(), + progress: Number(safePayload.progress || 0), + message: String(safePayload.message || ''), + result: safePayload.result || null, + error: String(safePayload.error || ''), + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync(cacheKey, progressPayload, ALLOCATE_EXPRESS_TASK_CACHE_TTL_SECONDS); + } catch (error) { + this.ctx.logger.warn('[pendingOrder.allocateExpressCode] 写入任务进度缓存失败: %s', error && error.message ? error.message : error); + } + } + + /** + * 读取快递分配任务进度。 + * + * @param {string} taskId 任务ID。 + * @return {Promise} 任务缓存结果。 + */ + async getAllocateExpressTaskProgress(taskId = '') { + const cacheKey = this.getAllocateExpressTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.getCacheAsync !== 'function') { + return null; + } + + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (!this.isPlainObject(cached)) { + return null; + } + return cached; + } catch (error) { + this.ctx.logger.warn('[pendingOrder.allocateExpressCode] 读取任务进度缓存失败: %s', error && error.message ? error.message : error); + return null; + } + } + // ========== syncOrderIds 异步任务进度缓存工具方法 ========== /** @@ -1498,6 +1591,32 @@ class PendingOrderService extends OrderBaseService { console.log('[PendingOrderService.cancelAllocateStorage] 归一化入参', normalizedData); + // 前置校验:拣货完成的订单不允许取消分配储位 + const rawCancelOrderIds = Array.isArray(normalizedData.order_ids) + ? normalizedData.order_ids + : (normalizedData.order_ids != null ? [ normalizedData.order_ids ] : []); + const cancelOrderIds = [ ...new Set(rawCancelOrderIds.map(id => Number(id)).filter(id => Number.isFinite(id) && id > 0)) ]; + + if (cancelOrderIds.length > 0) { + const model = await this.getOrderModel('order', this.getWarehouseId()); + const where = this.buildOrderWhere(cancelOrderIds, this.getWarehouseId()); + const orders = await model.findAll({ + where, + attributes: [ 'id', 'pick_status' ], + raw: true, + }); + + const pickedOrderIds = (Array.isArray(orders) ? orders : []) + .filter(o => o.pick_status === 'fin') + .map(o => Number(o.id)); + + if (pickedOrderIds.length > 0) { + throw new Error( + `以下订单已拣货完成,不允许取消分配储位:${pickedOrderIds.join(', ')}` + ); + } + } + try { console.log('[PendingOrderService.cancelAllocateStorage] 调用 orderStorageAllocation.cancelAllocateStorage 前', normalizedData); const result = await this.service.systems.orderStorageAllocation.cancelAllocateStorage(normalizedData); @@ -1859,15 +1978,10 @@ class PendingOrderService extends OrderBaseService { /** * 批量分配待处理订单的快递号,并复用现有运单创建核心链路。 - * - * 请求体必须直接传入订单对象数组,订单对象应为来自待处理订单列表或详情的原始订单对象。 - * 每个订单对象必须包含 order_id 与 business_key;sys_platform_code 与 logistics_code 为订单对象自带字段, - * 前端无需额外拼装或单独构造,直接原样回传订单对象即可。business_key 可为单个序号,也可为序号数组。 - * 其余字段会原样透传给运单创建链路。 * * @param {Object} data 请求体。 * @param {Array} data.orders 订单对象数组。 - * @return {Promise} 统一 success 包装的运单创建结果。 + * @return {Promise} 统一 success 包装,立即返回 task_id。 */ async allocateExpressCode(data) { const { orders } = data || {}; @@ -1875,79 +1989,138 @@ class PendingOrderService extends OrderBaseService { throw new Error('分配快递号接口仅支持订单对象数组入参'); } - const orderIds = [ ...new Set( - orders - .map(order => Number(order && (order.order_id || order.id))) - .filter(orderId => Number.isFinite(orderId) && orderId > 0) - ) ]; - const { service } = this; - try { - const result = await service.systems.express.createWaybillCodePipeline(orders); - return this.success('ok', result); - } catch (error) { + + // 生成任务ID,立即返回给前端 + const taskId = `exp_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`; + const taskPayload = { + task_id: taskId, + status: 'submitted', + progress: ALLOCATE_EXPRESS_PROGRESS_MAP.submitted, + message: '分配快递任务已提交', + result: null, + error: '', + }; + await this.setAllocateExpressTaskProgress(taskId, taskPayload); + + // 后台异步执行 + setImmediate(async () => { try { - const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; - const orderDeliveryModel = orderDeliveryFactory && typeof orderDeliveryFactory.getCurrentModel === 'function' - ? await orderDeliveryFactory.getCurrentModel() - : null; + await this.setAllocateExpressTaskProgress(taskId, { + status: 'running', + progress: ALLOCATE_EXPRESS_PROGRESS_MAP.running, + message: '快递分配处理中', + }); - if (orderDeliveryModel && orderIds.length > 0) { - // 查询当前订单的 express_code,只回滚没有运单号的 - const currentOrders = await orderDeliveryModel.findAll({ - // eslint-disable-next-line array-bracket-spacing - where: { id: { [this.app.Sequelize.Op.in]: orderIds } }, - attributes: [ 'id', 'express_code', 'post_status' ], - raw: true, - }); + const result = await service.systems.express.createWaybillCodePipeline(orders, { + awaitTasks: true, + }); - const noWaybillOrderIds = (Array.isArray(currentOrders) ? currentOrders : []) - .filter(o => !String(o.express_code || '').trim()) - .map(o => Number(o.id)) - .filter(id => id > 0); + await this.setAllocateExpressTaskProgress(taskId, { + status: 'success', + progress: ALLOCATE_EXPRESS_PROGRESS_MAP.success, + message: '快递分配完成', + result, + }); + } catch (error) { + const errorMessage = error && error.message ? error.message : String(error); - if (noWaybillOrderIds.length > 0) { - await orderDeliveryModel.update( - { post_status: 'none', updated_at: new Date() }, + // 异常标记和失败日志仍在 asyncTask 内部处理,这里仅记录任务状态 + await this.setAllocateExpressTaskProgress(taskId, { + status: 'failed', + progress: ALLOCATE_EXPRESS_PROGRESS_MAP.failed, + message: '快递分配失败', + error: errorMessage, + }); + + // 回滚无运单号订单的 post_status + try { + const orderIds = [ ...new Set( + orders + .map(order => Number(order && (order.order_id || order.id))) + .filter(orderId => Number.isFinite(orderId) && orderId > 0) + ) ]; + + const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; + const orderDeliveryModel = orderDeliveryFactory && typeof orderDeliveryFactory.getCurrentModel === 'function' + ? await orderDeliveryFactory.getCurrentModel() + : null; + + if (orderDeliveryModel && orderIds.length > 0) { + const currentOrders = await orderDeliveryModel.findAll({ // eslint-disable-next-line array-bracket-spacing - { where: { id: { [this.app.Sequelize.Op.in]: noWaybillOrderIds } } } - ); - this.ctx.logger.info('[PendingOrderService.allocateExpressCode] 回滚 post_status 为 none', { - orderIds: noWaybillOrderIds, + where: { id: { [this.app.Sequelize.Op.in]: orderIds } }, + attributes: [ 'id', 'express_code', 'post_status' ], + raw: true, }); + + const noWaybillOrderIds = (Array.isArray(currentOrders) ? currentOrders : []) + .filter(o => !String(o.express_code || '').trim()) + .map(o => Number(o.id)) + .filter(id => id > 0); + + if (noWaybillOrderIds.length > 0) { + await orderDeliveryModel.update( + { post_status: 'none', updated_at: new Date() }, + // eslint-disable-next-line array-bracket-spacing + { where: { id: { [this.app.Sequelize.Op.in]: noWaybillOrderIds } } } + ); + this.ctx.logger.info('[PendingOrderService.allocateExpressCode] 回滚 post_status 为 none', { + orderIds: noWaybillOrderIds, + }); + } } + } catch (markError) { + this.ctx.logger.warn('[PendingOrderService.allocateExpressCode] 回写订单状态失败,不影响主流程', markError); } - } catch (markError) { - this.ctx.logger.warn('[PendingOrderService.allocateExpressCode] 通过统一 helper 回写订单失败状态失败,不影响主流程', markError); } + }); - 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); + return this.success('ok', { + ...taskPayload, + update_time: Date.now(), + }); + } - 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; + /** + * 查询快递分配任务进度。 + * + * @param {Object} data 请求体。 + * @param {string} data.task_id 任务ID(下划线写法)。 + * @param {string} data.taskId 任务ID(驼峰写法)。 + * @return {Promise} 统一 success 包装。 + */ + async allocateExpressCodeTaskProgress(data = {}) { + const taskId = this.normalizeAllocateExpressTaskId(data); + if (!taskId) { + return this.success('ok', { + task_id: '', + status: 'not_found', + progress: ALLOCATE_EXPRESS_PROGRESS_MAP.not_found, + message: '任务不存在', + result: null, + error: '', + update_time: Date.now(), + }); } + + const cachedTask = await this.getAllocateExpressTaskProgress(taskId); + if (!cachedTask) { + return this.success('ok', { + task_id: taskId, + status: 'not_found', + progress: ALLOCATE_EXPRESS_PROGRESS_MAP.not_found, + message: '任务不存在', + result: null, + error: '', + update_time: Date.now(), + }); + } + + return this.success('ok', { + ...cachedTask, + update_time: cachedTask.update_time || Date.now(), + }); } /** @@ -5540,6 +5713,23 @@ class PendingOrderService extends OrderBaseService { throw new Error('OrderExpress 模型未加载'); } + // 3.0 检查是否已分配运单号:若已有 status=1 的记录,拒绝重复录入 + const existingCompleted = await orderExpressModel.findOne({ + where: { + order_id: orderId, + warehouse_id: Number(order.warehouse_id) || warehouseId, + status: 1, + }, + attributes: [ 'id', 'waybill_code' ], + raw: true, + }); + if (existingCompleted) { + const existingWaybill = String(existingCompleted.waybill_code || '').trim(); + throw new Error( + `订单 ${orderId} 已分配运单号${existingWaybill ? `(${existingWaybill})` : ''},不允许重复手工录入` + ); + } + // 3.1 计算 business_key 递增:查找当前订单已有最大 business_key,+1 递增 const maxBusinessKey = await orderExpressModel.max('business_key', { where: { diff --git a/app/service/systemMethods/print.js b/app/service/systemMethods/print.js index 3b63d15..a1e7fd1 100644 --- a/app/service/systemMethods/print.js +++ b/app/service/systemMethods/print.js @@ -1845,10 +1845,10 @@ class PrintService extends MainService { const updateResult = await orderDeliveryModel.update({ print_lock_status: 'warehouse', + print_status: 'fin', }, { where: { id: orderIds, - print_lock_status: 'none', }, }); diff --git a/app/service/systems/delivery_order.js b/app/service/systems/delivery_order.js index 6235dc0..d653447 100644 --- a/app/service/systems/delivery_order.js +++ b/app/service/systems/delivery_order.js @@ -814,7 +814,23 @@ class DeliveryOrderService extends Service { }); if (!relation) { - throw new Error('货主未与当前仓库签约,无法创建订单'); + throw new Error('仓库方已暂停接收推单,无法创建订单,请联系仓库方'); + } + + const relation2 = await ctx.model.StoreWarehouse.findOne({ + where: { + store_id: storeId, + warehouse_id: warehouseId, + auth_status: 2, + warehouse_use_status: 1, + }, + attributes: [ 'id' ], + transaction, + raw: true, + }); + + if (!relation2) { + throw new Error('仓库已禁用,无法创建订单,如需继续推单请进入货主后台修改配置'); } const storeWarehouseService = ctx.service && ctx.service.systems && ctx.service.systems.storeWarehouse; diff --git a/app/service/systems/express.js b/app/service/systems/express.js index 5d16ac5..dbaea22 100644 --- a/app/service/systems/express.js +++ b/app/service/systems/express.js @@ -2326,13 +2326,17 @@ class ExpressService extends Service { * business_key 支持单值或数组输入,内部会展开成多条记录后再分组批处理。 *【已使用】 * @param {Array} orders 订单与业务键列表。 + * @param {Object} [options] 可选配置。 + * @param {boolean} [options.awaitTasks=false] 是否等待所有异步任务完成后再返回。 + * @param {Function} [options.onBatchComplete] 单批完成回调 ({ processed, total })。 * @return {Promise} 处理结果,包含 orders、waybill_codes 和 skippedOrders。 */ - async createWaybillCodePipeline(orders = []) { + async createWaybillCodePipeline(orders = [], options = {}) { const { app } = this; const { Op } = app.Sequelize; const orderList = Array.isArray(orders) ? orders : []; const traceId = this.buildWaybillTraceId({}, `pipeline_${Date.now()}`); + const pipelineOptions = options && typeof options === 'object' ? options : {}; this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 入口请求', { traceId, @@ -2484,11 +2488,19 @@ class ExpressService extends Service { for (const batch of batches) { // 异步不阻塞调用 createWaybillCode,快速返回结果给前端,后续的订单处理和异常回写都在 createWaybillCode 内部完成。 - this.asyncTask(batch, { - ...groupedOrder.options, - trace_id: traceId, - warehouse_id: warehouseId, - }, matchedPlatformWithRequestCode, expressInterfaceConfig); + if (pipelineOptions.awaitTasks) { + await this.asyncTask(batch, { + ...groupedOrder.options, + trace_id: traceId, + warehouse_id: warehouseId, + }, matchedPlatformWithRequestCode, expressInterfaceConfig); + } else { + this.asyncTask(batch, { + ...groupedOrder.options, + trace_id: traceId, + warehouse_id: warehouseId, + }, matchedPlatformWithRequestCode, expressInterfaceConfig); + } } } this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 流水线任务提交完成', { @@ -2557,17 +2569,55 @@ class ExpressService extends Service { order_id: order && (order.id || order.order_id), business_key: order.business_key, })); - const failedOrderIds = err_orders + const allOrderIds = err_orders .map(order => Number(order && order.order_id)) .filter(orderId => Number.isFinite(orderId) && orderId > 0); + + // 查询已成功分配(status=1)的订单,从失败列表中排除,避免误标异常 + const successOrderIdSet = new Set(); + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; + if (orderExpressModel && allOrderIds.length > 0) { + try { + const successRows = await orderExpressModel.findAll({ + where: { + order_id: { [this.app.Sequelize.Op.in]: allOrderIds }, + status: 1, + }, + attributes: [ 'order_id' ], + raw: true, + }); + for (const row of Array.isArray(successRows) ? successRows : []) { + const successOrderId = Number(row && row.order_id); + if (Number.isFinite(successOrderId) && successOrderId > 0) { + successOrderIdSet.add(successOrderId); + } + } + if (successOrderIdSet.size > 0) { + this.ctx.logger.info('[ExpressService.asyncTask] 排除已成功分配的订单,不标记异常', { + traceId, + successOrderIds: Array.from(successOrderIdSet), + }); + } + } catch (statusCheckError) { + this.ctx.logger.error('[ExpressService.asyncTask] 查询已成功订单状态失败,降级为全量标记', { + traceId, + error: statusCheckError && statusCheckError.message ? statusCheckError.message : `${statusCheckError}`, + }); + } + } + + const failedOrderIds = allOrderIds.filter(orderId => !successOrderIdSet.has(orderId)); 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: `订单快递分配失败: ${errorMessage}`, - } - ); + + if (failedOrderIds.length > 0) { + this.service.systems.orderPendingException.markPendingException( + { + ids: failedOrderIds, + exception_text: `订单快递分配失败: ${errorMessage}`, + } + ); + } await this.createAllocateExpressFailureLogs(failedOrderIds, errorMessage, logWarehouseId); await this.hardDeleteWaybillAsyncOrderExpressRows(err_orders, { platform_code: options.sys_platform_code, diff --git a/app/service/systems/order_print.js b/app/service/systems/order_print.js index f9f52b4..5b43d17 100644 --- a/app/service/systems/order_print.js +++ b/app/service/systems/order_print.js @@ -179,8 +179,9 @@ class OrderPrintSystemService extends OrderBaseService { * 同时从 wms_stock_barcodes 表批量查询每个 stock_id 对应的全部条码, * 注入到打印项的 barcodes 数组中,供 resolveItemBarcodeText 优先读取。 * - * stock_id 优先读取 wms_order_items.stock_id 列,兜底读取 item_snapshot 内的 stock_id, - * 确保不同来源的订单明细都能正确关联到条码数据。 + * stock_id 优先读取 wms_picking.stock_id(20260708 新增列), + * 兜底读取 wms_order_items.stock_id / item_snapshot.stock_id, + * 消除对 order_items 明细表的强依赖,使配送表订单打印链路也能正常获取商品信息。 * * @param {Array} orderRows 订单列表。 * @param {number} warehouseId 仓库ID。 @@ -212,7 +213,7 @@ class OrderPrintSystemService extends OrderBaseService { [Op.ne]: 'cancel', }, }, - attributes: [ 'id', 'order_id', 'order_item_id', 'quantity', 'space_id', 'space_name', 'status' ], + attributes: [ 'id', 'order_id', 'order_item_id', 'quantity', 'space_id', 'space_name', 'status', 'stock_id' ], order: [[ 'order_id', 'ASC' ], [ 'id', 'ASC' ]], raw: true, }); @@ -285,10 +286,50 @@ class OrderPrintSystemService extends OrderBaseService { pickingRowsByOrderId.set(orderId, list); } - // 阶段一:构建所有打印项并收集 stock_id - const printItemsByOrderId = new Map(); + // 阶段一:收集 stock_id(优先 picking.stock_id,兜底 order_items.stock_id) const allStockIds = new Set(); + // 1a) 从 wms_picking 直接收集 stock_id(新增路径,绕过 order_items 明细表) + for (const row of normalizedPickingRows) { + const stockId = Number(row && row.stock_id || 0); + if (stockId > 0) { + allStockIds.add(stockId); + } + } + + // 1b) 从 order_items 兜底收集 stock_id(兼容 picking.stock_id 为 NULL 的旧数据) + for (const row of Array.isArray(orderItemRows) ? orderItemRows : []) { + const itemSnapshot = this.normalizeItemSnapshot(row.item_snapshot); + const stockId = Number(row.stock_id || itemSnapshot.stock_id || 0); + if (stockId > 0) { + allStockIds.add(stockId); + } + } + + const uniqueStockIds = Array.from(allStockIds); + + // 阶段二:批量查询 wms_stock_warehouse 获取商品编码与名称(新增直读路径) + const stockWarehouseMap = new Map(); + if (uniqueStockIds.length > 0) { + const stockWarehouseModel = this.ctx.model && this.ctx.model.StockWarehouse; + if (stockWarehouseModel && typeof stockWarehouseModel.findAll === 'function') { + const stockRows = await stockWarehouseModel.findAll({ + where: { + id: { [Op.in]: uniqueStockIds }, + is_valid: 'Y', + }, + attributes: [ 'id', 'item_code', 'item_name' ], + raw: true, + }); + for (const row of Array.isArray(stockRows) ? stockRows : []) { + stockWarehouseMap.set(Number(row.id), row); + } + } + } + + // 阶段三:构建所有打印项(使用 stock_warehouse 直读数据) + const printItemsByOrderId = new Map(); + for (const orderRow of rows) { const orderId = Number(orderRow && orderRow.id || 0); const pickingList = pickingRowsByOrderId.get(orderId) || []; @@ -307,27 +348,36 @@ class OrderPrintSystemService extends OrderBaseService { custom_name: locationRow.custom_name, custom_barcode: locationRow.custom_barcode, }, [ 'space_name', 'space_code', 'custom_name', 'custom_barcode' ]); + + // stock_id 优先级:picking.stock_id > order_items.stock_id > item_snapshot.stock_id + const pickingStockId = Number(pickingRow && pickingRow.stock_id || 0); + const orderItemStockId = Number(orderItemRow.stock_id || itemSnapshot.stock_id || 0); + const stockId = pickingStockId > 0 ? pickingStockId : orderItemStockId; + + // 从 stock_warehouse 直读商品编码与名称(新增路径,绕过 order_items) + const stockInfo = stockId > 0 ? stockWarehouseMap.get(stockId) : null; + + // item_name 优先级:stock_warehouse > order_items > item_snapshot const itemName = this.getFirstNonEmptyFieldText({ + stock_item_name: stockInfo && stockInfo.item_name, snapshot_item_name: itemSnapshot.item_name, snapshot_name: itemSnapshot.name, snapshot_title: itemSnapshot.title, item_name: orderItemRow.item_name, - }, [ 'snapshot_item_name', 'snapshot_name', 'snapshot_title', 'item_name' ]); + }, [ 'stock_item_name', 'snapshot_item_name', 'snapshot_name', 'snapshot_title', 'item_name' ]); + + // barcode 优先级:stock_warehouse.item_code > item_snapshot > order_items.item_code const barcode = this.getFirstNonEmptyFieldText({ + stock_item_code: stockInfo && stockInfo.item_code, barcode: itemSnapshot.barcode, item_barcode: itemSnapshot.item_barcode, bar_code: itemSnapshot.bar_code, item_code: orderItemRow.item_code, sku_code: itemSnapshot.sku_code, sku: itemSnapshot.sku, - }, [ 'barcode', 'item_barcode', 'bar_code', 'item_code', 'sku_code', 'sku' ]); - const quantity = Number(pickingRow && pickingRow.quantity || orderItemRow.plan_qty || 0); - // 优先使用列 stock_id,兜底使用 item_snapshot 内的 stock_id - const stockId = Number(orderItemRow.stock_id || itemSnapshot.stock_id || 0); + }, [ 'stock_item_code', 'barcode', 'item_barcode', 'bar_code', 'item_code', 'sku_code', 'sku' ]); - if (stockId > 0) { - allStockIds.add(stockId); - } + const quantity = Number(pickingRow && pickingRow.quantity || orderItemRow.plan_qty || 0); return { order_item_id: orderItemId, @@ -350,9 +400,8 @@ class OrderPrintSystemService extends OrderBaseService { printItemsByOrderId.set(orderId, printItems); } - // 阶段二:批量查询 wms_stock_barcodes 获取所有条码 + // 阶段四:批量查询 wms_stock_barcodes 获取所有条码 const barcodeMap = new Map(); - const uniqueStockIds = Array.from(allStockIds); if (uniqueStockIds.length > 0) { const stockBarcodeModel = this.ctx.model && this.ctx.model.StockBarcode; @@ -385,7 +434,7 @@ class OrderPrintSystemService extends OrderBaseService { } } - // 阶段三:注入条码并构建结果映射 + // 阶段五:注入条码并构建结果映射 for (const orderRow of rows) { const orderId = Number(orderRow && orderRow.id || 0); const printItems = printItemsByOrderId.get(orderId); From 6d58d7ff1ff941bd4ecf0936520911c8fa0146aa Mon Sep 17 00:00:00 2001 From: liufumingren Date: Thu, 9 Jul 2026 03:36:19 +0800 Subject: [PATCH 108/550] =?UTF-8?q?docs:=20=E4=BB=93=E5=82=A8=E6=8A=A5?= =?UTF-8?q?=E8=A1=A8=E5=BE=AE=E8=B0=83=20+=20methods=20=E6=8E=A5=E5=8F=A3?= =?UTF-8?q?=E6=96=87=E6=A1=A3=E5=90=8C=E6=AD=A5=E6=9B=B4=E6=96=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - storage/report: 报表逻辑微调 - methods/system.json: storeWarehouse 系列接口文档更新 - methods/changes/system.json: 新增 2026.07.08/07.09 变更记录 --- app/service/systemMethods/storage/report.js | 6 +- app/service/systems/storage/report.js | 9 +- methods/changes/system.json | 38 +++++ methods/system.json | 155 +++++++++++++++++--- 4 files changed, 182 insertions(+), 26 deletions(-) diff --git a/app/service/systemMethods/storage/report.js b/app/service/systemMethods/storage/report.js index 8cb5669..58b3469 100644 --- a/app/service/systemMethods/storage/report.js +++ b/app/service/systemMethods/storage/report.js @@ -71,6 +71,8 @@ class StorageReportMethodService extends MainService { * @param {string|Date} [data.where.end_time] 结束时间 * @param {boolean|string|number} [data.where.by_space=false] 是否按库位返回 * @param {Array} [data.where.store_ids] 货主ID列表 + * @param {string} [data.export_mode] 导出模式:'item' 导出含锁定类型的全部变更记录,不传则排除锁定类型 + * @param {string} [data.exportMode] 导出模式(驼峰写法,同 export_mode) * @return {Promise} 统一 success 包装(返回任务ID) */ async export(data = {}) { @@ -95,6 +97,8 @@ class StorageReportMethodService extends MainService { sortOrder: sortOrderCamel, } = sort || {}; + const exportMode = String(data.export_mode || data.exportMode || '').trim(); + const taskId = this.generateExportTaskId(); const taskPayload = { task_id: taskId, @@ -123,7 +127,7 @@ class StorageReportMethodService extends MainService { error: '', }); - const result = await service.systems.storage.report.export(startTime, endTime, bySpace, storeIds, sortOption); + const result = await service.systems.storage.report.export(startTime, endTime, bySpace, storeIds, sortOption, exportMode); await this.setExportTaskProgress(taskId, { task_id: taskId, diff --git a/app/service/systems/storage/report.js b/app/service/systems/storage/report.js index 338091b..1d54349 100644 --- a/app/service/systems/storage/report.js +++ b/app/service/systems/storage/report.js @@ -514,9 +514,10 @@ class StorageReportService extends Service { * @param {Object} [sort] 排序参数 * @param {string} [sort.sortField] 排序字段 * @param {string} [sort.sortOrder] 排序顺序 + * @param {string} [exportMode] 导出模式:'item' 导出全部(含锁定),不传/其他值则排除锁定类型记录 * @return {Promise} excel 上传结果 */ - async export(startTime, endTime, bySpace = false, storeIds = [], sort = null) { + async export(startTime, endTime, bySpace = false, storeIds = [], sort = null, exportMode = '') { const { ctx, app } = this; const searchResult = await this.search(startTime, endTime, bySpace, storeIds, sort); if (!searchResult || searchResult.code !== 200) { @@ -552,6 +553,12 @@ class StorageReportService extends Service { replacements.storeIds = normalizedStoreIds; } + const normalizedExportMode = String(exportMode || '').trim(); + if (normalizedExportMode !== 'item') { + whereClauses.push('t.transaction_type != :excludeLockType'); + replacements.excludeLockType = 'LOCK'; + } + const detailTransactionTable = isBySpace ? 'wms_storage_transaction' : 'wms_stock_transaction'; const detailSpaceSelectSql = isBySpace ? 'COALESCE(t.space_id, 0) AS space_id' : '0 AS space_id'; const detailInventoryTypeSelectSql = isBySpace ? 't.inventory_type' : '\'\' AS inventory_type'; diff --git a/methods/changes/system.json b/methods/changes/system.json index 9f04372..d76f756 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,42 @@ [ + { + "version": "2026.07.09-system-01", + "date": "2026-07-09", + "type": "updated", + "summary": "签约 sign 方法改造:统一当前主体→store_id,解除角色校验,仓库可签仓库", + "methods": [ + "storeWarehouse.store.sign", + "storeWarehouse.warehouse.sign" + ], + "notes": [ + "resolvePairIds:统一当前主体始终在 store_id(货主方/消费方),对方在 warehouse_id(仓库方/提供方)。不再根据 isWarehouse 分支。", + "getCounterparty:移除 expectedRole 角色校验(仓库不再只能签货主,可签仓库)。", + "findScopedRelation:改为 OR 查询 store_id/warehouse_id 两边,兼容新旧签约数据。", + "sign preview:counterparty.role 改为根据对方 project 真实返回(warehouse/store),不再硬编码反推。", + "签仓库:仓库发起签约时对方 ID 传 counterparty_id,系统自动将当前仓库放 store_id。" + ], + "module": "storeWarehouse" + }, + { + "version": "2026.07.08-system-01", + "date": "2026-07-08", + "type": "updated", + "summary": "storeWarehouse.store.list 与 storeWarehouse.warehouse.list 拆分实现,不再共用;仓库侧支持查询外部合作仓库", + "methods": [ + "storeWarehouse.store.list", + "storeWarehouse.warehouse.list" + ], + "notes": [ + "拆分:store.list 调用 listForStore,warehouse.list 调用 listForWarehouse,不再共用同一个 list 方法。", + "新规则:两个方法均按 store_id = 当前主体ID 过滤(主体在 store_id 为货主方/消费方,对方在 warehouse_id 为仓库方/提供方)。", + "warehouse.list 新增支持查询外部合作仓库:当对方主体的 project='warehouse' 时为仓库-仓库合作,counterparty_role='warehouse'。", + "响应新增 counterparty_role 字段(store/warehouse),标识对方主体的真实角色。", + "warehouse.list 响应 use_status 改为 store_use_status(仓库在 store_id 方时,己方启用状态应为 store_use_status)。", + "旧 list 方法保留标记为 @deprecated,保持向后兼容。", + "新增 buildListWhereByStoreId 统一按 store_id 维度构建查询条件。" + ], + "module": "storeWarehouse" + }, { "version": "2026.07.06-system-01", "date": "2026-07-06", diff --git a/methods/system.json b/methods/system.json index 9898df7..f89c195 100644 --- a/methods/system.json +++ b/methods/system.json @@ -22650,7 +22650,7 @@ "list": [ { "method": "storeWarehouse.store.list", - "description": "查询当前主体可见的仓库-货主签约列表", + "description": "查询当前主体可见的签约列表(当前主体在 store_id 方,对方在 warehouse_id 方)", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -22725,6 +22725,11 @@ "type": "string", "description": "对方主体名称" }, + { + "name": "data.list[].counterparty_role", + "type": "string", + "description": "对方主体角色:warehouse 或 store" + }, { "name": "data.list[].current_subject_role", "type": "string", @@ -22865,7 +22870,7 @@ }, { "method": "storeWarehouse.store.sign", - "description": "发起或确认仓库-货主签约", + "description": "发起或确认签约(当前主体始终为 store_id 方/消费方,对方为 warehouse_id 方/提供方,支持仓库签仓库)", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -22878,18 +22883,11 @@ ], "params": [ { - "name": "store_id", + "name": "counterparty_id", "type": "number", - "required": false, + "required": true, "source": "body", - "description": "货主ID;由仓库侧发起时必传" - }, - { - "name": "warehouse_id", - "type": "number", - "required": false, - "source": "body", - "description": "仓库ID;由货主侧发起时必传" + "description": "对方主体 ID(兼容 warehouse_id / store_id),当前主体自动识别" }, { "name": "temp_code", @@ -23606,7 +23604,7 @@ "list": [ { "method": "storeWarehouse.warehouse.list", - "description": "仓库侧查询当前仓库可见的货主签约列表", + "description": "仓库侧查询签约列表(支持查询外部合作仓库),当前仓库在 store_id 方(消费方),对方在 warehouse_id 方(提供方)", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -23637,41 +23635,150 @@ "type": "string", "required": false, "source": "body", - "description": "搜索关键字,模糊匹配货主备注名、仓库备注名、货主公司名、仓库公司名" + "description": "搜索关键字,模糊匹配己方备注名、对方备注名、己方公司名、对方公司名" + }, + { + "name": "warehouse_id", + "type": "number", + "required": false, + "source": "body", + "description": "对方主体 ID(兼容 counterparty_id)" }, { "name": "auth_status", - "type": "string", + "type": "number", "required": false, "source": "body", - "description": "授权状态筛选" + "description": "授权状态筛选:1=申请中 2=已通过 3=已拒绝 4=已解除 5=已过期" + }, + { + "name": "use_status", + "type": "number", + "required": false, + "source": "body", + "description": "己方启用状态:0=禁用 1=启用" } ], "response": [ { - "name": "list", + "name": "data.list", "type": "array", - "description": "签约列表" + "description": "签约关系列表" }, { - "name": "total", + "name": "data.list[].id", "type": "number", - "description": "总条数" + "description": "签约关系主键 ID" }, { - "name": "page", + "name": "data.list[].store_id", + "type": "number", + "description": "己方主体 ID(当前仓库)" + }, + { + "name": "data.list[].store_name", + "type": "string", + "description": "己方主体名称" + }, + { + "name": "data.list[].warehouse_id", + "type": "number", + "description": "对方主体 ID" + }, + { + "name": "data.list[].warehouse_name", + "type": "string", + "description": "对方主体名称" + }, + { + "name": "data.list[].counterparty_id", + "type": "number", + "description": "对方主体 ID(同 warehouse_id)" + }, + { + "name": "data.list[].counterparty_name", + "type": "string", + "description": "对方主体名称" + }, + { + "name": "data.list[].counterparty_role", + "type": "string", + "description": "对方主体角色:warehouse(外部合作仓库)或 store(货主)" + }, + { + "name": "data.list[].remask", + "type": "string", + "description": "己方对本次签约的备注名" + }, + { + "name": "data.list[].use_status", + "type": "number", + "description": "己方启用状态:0=禁用 1=启用" + }, + { + "name": "data.list[].auth_status", + "type": "number", + "description": "签约状态:1=申请中 2=已通过 3=已拒绝 4=已解除 5=已过期" + }, + { + "name": "data.list[].auth_status_label", + "type": "string", + "description": "签约状态中文标签" + }, + { + "name": "data.list[].auth_end", + "type": "string|null", + "description": "授权结束时间" + }, + { + "name": "data.list[].print_quantity", + "type": "number", + "description": "面单余额数量" + }, + { + "name": "data.list[].has_qimen_config", + "type": "boolean", + "description": "是否已配置奇门" + }, + { + "name": "data.list[].needs_my_confirm", + "type": "boolean", + "description": "是否需要当前仓库确认签约(对方发起且状态为申请中)" + }, + { + "name": "data.total", + "type": "number", + "description": "总记录数" + }, + { + "name": "data.page", "type": "number", "description": "当前页码" }, { - "name": "page_size", + "name": "data.page_size", "type": "number", "description": "每页条数" }, { - "name": "current_subject", + "name": "data.current_subject", "type": "object", - "description": "当前主体信息,含 store_id、company_name、role(warehouse/store)" + "description": "当前主体信息" + }, + { + "name": "data.current_subject.store_id", + "type": "number", + "description": "当前主体 ID" + }, + { + "name": "data.current_subject.company_name", + "type": "string", + "description": "当前主体公司名称" + }, + { + "name": "data.current_subject.role", + "type": "string", + "description": "当前主体角色:warehouse" } ], "errors": [ From a1f5c5d5328334488a86a899f4c350e7d1c756e7 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Thu, 9 Jul 2026 11:54:53 +0800 Subject: [PATCH 109/550] =?UTF-8?q?fix(storeWarehouse):=20list=20=E6=9F=A5?= =?UTF-8?q?=E8=AF=A2=E4=BD=BF=E7=94=A8=20OR=20=E4=B8=A4=E8=BE=B9=E5=8C=B9?= =?UTF-8?q?=E9=85=8D=EF=BC=8C=E5=85=BC=E5=AE=B9=E6=96=B0=E6=97=A7=E7=AD=BE?= =?UTF-8?q?=E7=BA=A6=E6=95=B0=E6=8D=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - serializeRelation: 根据 currentSubject.id 匹配 store_id/warehouse_id 判定对方主体 - listForStore/listForWarehouse: 使用 store_id/warehouse_id OR 查询替代 buildListWhereByStoreId - remask/use_status: 基于实际所在侧判定而非 isWarehouse 角色 - 修复仓库用户看不到签约货主方信息的问题 --- app/service/systems/store_warehouse.js | 107 ++++++++++++++++++++++--- 1 file changed, 97 insertions(+), 10 deletions(-) diff --git a/app/service/systems/store_warehouse.js b/app/service/systems/store_warehouse.js index c981ea4..bdd2561 100644 --- a/app/service/systems/store_warehouse.js +++ b/app/service/systems/store_warehouse.js @@ -1324,9 +1324,12 @@ class SettingStoreWarehouseService extends Service { const authStatus = Number(item.auth_status || 0); const currentIsWarehouse = !!(currentSubject && currentSubject.isWarehouse); + const subjectId = currentSubject ? Number(currentSubject.id) : 0; - // 当前主体始终在 store_id 方(货主方/消费方),对方始终在 warehouse_id 方(仓库方/提供方) - const counterparty = item.warehouse; + // 根据当前主体在 store_id 还是 warehouse_id 判定对方主体(兼容新旧签约数据) + const subjectIsStore = subjectId > 0 && subjectId === Number(item.store_id || 0); + const subjectIsWarehouse = subjectId > 0 && subjectId === Number(item.warehouse_id || 0); + const counterparty = subjectIsStore ? item.warehouse : item.store; const counterpartyRole = counterparty && counterparty.project === 'warehouse' ? 'warehouse' : 'store'; const storeName = item.store_remask || (item.store && item.store.company_name ? item.store.company_name : ''); @@ -1369,8 +1372,8 @@ class SettingStoreWarehouseService extends Service { applied_by: item.applied_by ? Number(item.applied_by) : null, reviewed_by: item.reviewed_by ? Number(item.reviewed_by) : null, ended_by: item.ended_by ? Number(item.ended_by) : null, - remask: currentIsWarehouse ? (item.store_remask || '') : (item.warehouse_remask || ''), - use_status: currentIsWarehouse + remask: subjectIsWarehouse ? (item.store_remask || '') : (item.warehouse_remask || ''), + use_status: subjectIsWarehouse ? Number(item.warehouse_use_status || 0) : Number(item.store_use_status || 0), warehouse_use_status: Number(item.warehouse_use_status || 0), @@ -1430,9 +1433,9 @@ class SettingStoreWarehouseService extends Service { } /** - * 货主侧查询签约关系列表。 + * 货主侧查询签约关系列表(兼容新旧签约数据)。 * - * 当前货主主体在 store_id 方,对方仓库在 warehouse_id 方。 + * 使用 OR 查询 store_id / warehouse_id 两边,确保新旧签约数据都能被正确展示。 * * @param {Object} [data={}] 请求参数。 * @return {Promise} 接口响应对象。 @@ -1444,7 +1447,49 @@ class SettingStoreWarehouseService extends Service { const page = this.normalizePage(data.page, 'page', 1, 1000000); const pageSize = this.normalizePage(data.page_size || data.pageSize, 'page_size', 20, 200); const offset = (page - 1) * pageSize; - const where = this.buildListWhereByStoreId(data, currentSubject); + + // OR 查询两边,兼容新旧签约数据 + const where = { + [Op.or]: [ + { store_id: currentSubject.id }, + { warehouse_id: currentSubject.id }, + ], + }; + + const relationId = this.resolveRelationId(data); + if (relationId) { + where.id = relationId; + } + + const counterpartyId = this.toPositiveNumber(data.counterparty_id || data.warehouse_id, 'counterparty_id', { allowEmpty: true }); + if (counterpartyId) { + // 对方可能在 store_id 或 warehouse_id,两边都过滤 + where[Op.and] = where[Op.and] || []; + where[Op.and].push({ + [Op.or]: [ + { store_id: counterpartyId, warehouse_id: currentSubject.id }, + { warehouse_id: counterpartyId, store_id: currentSubject.id }, + ], + }); + } + + const authStatus = this.normalizeAuthStatus(data.auth_status); + if (authStatus !== null) { + where.auth_status = authStatus; + } + + const rawUseStatus = data.use_status !== undefined ? data.use_status : data.store_use_status; + if (rawUseStatus !== undefined && rawUseStatus !== null && rawUseStatus !== '') { + // 同时过滤 store_use_status 和 warehouse_use_status + where[Op.and] = where[Op.and] || []; + where[Op.and].push({ + [Op.or]: [ + { store_use_status: Number(rawUseStatus), store_id: currentSubject.id }, + { warehouse_use_status: Number(rawUseStatus), warehouse_id: currentSubject.id }, + ], + }); + } + const keyword = typeof data.keyword === 'string' ? data.keyword.trim() : ''; if (keyword) { @@ -1507,9 +1552,9 @@ class SettingStoreWarehouseService extends Service { } /** - * 仓库侧查询签约关系列表。 + * 仓库侧查询签约关系列表(兼容新旧签约数据)。 * - * 当前仓库主体在 store_id 方(消费方),对方(可能是仓库或货主)在 warehouse_id 方(提供方)。 + * 使用 OR 查询 store_id / warehouse_id 两边,确保新旧签约数据都能被正确展示。 * 支持查询仓库与外部合作仓库的关系。 * * @param {Object} [data={}] 请求参数。 @@ -1522,7 +1567,49 @@ class SettingStoreWarehouseService extends Service { const page = this.normalizePage(data.page, 'page', 1, 1000000); const pageSize = this.normalizePage(data.page_size || data.pageSize, 'page_size', 20, 200); const offset = (page - 1) * pageSize; - const where = this.buildListWhereByStoreId(data, currentSubject); + + // OR 查询两边,兼容新旧签约数据 + const where = { + [Op.or]: [ + { store_id: currentSubject.id }, + { warehouse_id: currentSubject.id }, + ], + }; + + const relationId = this.resolveRelationId(data); + if (relationId) { + where.id = relationId; + } + + const counterpartyId = this.toPositiveNumber(data.counterparty_id || data.warehouse_id, 'counterparty_id', { allowEmpty: true }); + if (counterpartyId) { + // 对方可能在 store_id 或 warehouse_id,两边都过滤 + where[Op.and] = where[Op.and] || []; + where[Op.and].push({ + [Op.or]: [ + { store_id: counterpartyId, warehouse_id: currentSubject.id }, + { warehouse_id: counterpartyId, store_id: currentSubject.id }, + ], + }); + } + + const authStatus = this.normalizeAuthStatus(data.auth_status); + if (authStatus !== null) { + where.auth_status = authStatus; + } + + const rawUseStatus = data.use_status !== undefined ? data.use_status : data.store_use_status; + if (rawUseStatus !== undefined && rawUseStatus !== null && rawUseStatus !== '') { + // 同时过滤 store_use_status 和 warehouse_use_status + where[Op.and] = where[Op.and] || []; + where[Op.and].push({ + [Op.or]: [ + { store_use_status: Number(rawUseStatus), store_id: currentSubject.id }, + { warehouse_use_status: Number(rawUseStatus), warehouse_id: currentSubject.id }, + ], + }); + } + const keyword = typeof data.keyword === 'string' ? data.keyword.trim() : ''; if (keyword) { From fddd142427d0d420e89c6b2f0bb3a5f40dc289c7 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Fri, 10 Jul 2026 18:10:11 +0800 Subject: [PATCH 110/550] =?UTF-8?q?fix:=20custom=5Fbarcode=20=E5=94=AF?= =?UTF-8?q?=E4=B8=80=E7=BA=A6=E6=9D=9F=E6=94=B9=E4=B8=BA=E4=BB=93=E5=BA=93?= =?UTF-8?q?=E7=BA=A7=E5=88=AB=EF=BC=8C=E4=BF=AE=E5=A4=8D=20batchUpdateSpac?= =?UTF-8?q?eInfo=20=E7=AD=89=E6=9D=A1=E7=A0=81=E6=A3=80=E6=9F=A5=E8=B7=A8?= =?UTF-8?q?=E4=BB=93=E5=BA=93=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/model/location_space.js | 2 +- app/service/systemMethods/warehouse.js | 5 +-- app/service/systems/location_space.js | 13 ++++--- app/service/systems/location_zone.js | 36 ++++++++++--------- ...-custom-barcode-unique-to-per-warehouse.js | 20 +++++++++++ 5 files changed, 53 insertions(+), 23 deletions(-) create mode 100644 database/migrations/20260710000000-fix-custom-barcode-unique-to-per-warehouse.js diff --git a/app/model/location_space.js b/app/model/location_space.js index 875299a..1355d5b 100644 --- a/app/model/location_space.js +++ b/app/model/location_space.js @@ -209,7 +209,7 @@ module.exports = app => { unique: true, fields: [ 'warehouse_id', 'space_code', 'deleted_at' ], }, - { name: 'uk_custom_barcode', unique: true, fields: [ 'custom_barcode' ] }, + { name: 'uk_warehouse_custom_barcode', unique: true, fields: [ 'warehouse_id', 'custom_barcode', 'deleted_at' ] }, { fields: [ 'warehouse_id', 'zone_id' ] }, { fields: [ 'location_type_id' ] }, { fields: [ 'space_status' ] }, diff --git a/app/service/systemMethods/warehouse.js b/app/service/systemMethods/warehouse.js index 7c5afc5..493a5e7 100644 --- a/app/service/systemMethods/warehouse.js +++ b/app/service/systemMethods/warehouse.js @@ -145,7 +145,7 @@ class warehouseService extends MainService { if (!barcode) { return this.fail('条码不能为空'); } - const data = await service.systems.locationZone.checkBarcodeUnique(parseInt(id), barcode); + const data = await service.systems.locationZone.checkBarcodeUnique(parseInt(id), barcode, this.ctx.user.store_id); return this.success('获取成功', { data, code: 200 }); } catch (error) { return this.fail(error.message); @@ -409,7 +409,7 @@ class warehouseService extends MainService { throw new Error('仓位不存在'); } if (data.custom_barcode) { - const { isUnique } = await service.systems.locationZone.checkBarcodeUnique(parseInt(id), data.custom_barcode); + const { isUnique } = await service.systems.locationZone.checkBarcodeUnique(parseInt(id), data.custom_barcode, ctx.user.store_id); if (!isUnique) { throw new Error('自定义条码已存在'); } @@ -651,6 +651,7 @@ class warehouseService extends MainService { if (requestedBarcodes.length > 0) { const conflictSpace = await ctx.model.LocationSpace.findOne({ where: { + warehouse_id: warehouseId, deleted_at: null, id: { [Op.notIn]: targetIds, diff --git a/app/service/systems/location_space.js b/app/service/systems/location_space.js index 0a12e66..8cc4c1c 100644 --- a/app/service/systems/location_space.js +++ b/app/service/systems/location_space.js @@ -48,10 +48,13 @@ class LocationSpaceService extends Service { ctx.throw(400, '仓位编码已存在'); } - // 检查条码唯一性 + // 检查条码唯一性(仓库内唯一) if (data.custom_barcode) { const barcodeExists = await ctx.model.LocationSpace.findOne({ - where: { custom_barcode: data.custom_barcode }, + where: { + warehouse_id: data.warehouse_id, + custom_barcode: data.custom_barcode, + }, }); if (barcodeExists) { @@ -103,10 +106,11 @@ class LocationSpaceService extends Service { ctx.throw(400, `以下仓位编码已存在: ${codes}`); } - // 检查条码重复 + // 检查条码重复(仓库内唯一) if (barcodes.length > 0) { const duplicateBarcodes = await ctx.model.LocationSpace.findAll({ where: { + warehouse_id: warehouseId, custom_barcode: { [ctx.app.Sequelize.Op.in]: barcodes }, }, attributes: [ 'custom_barcode' ], @@ -294,10 +298,11 @@ class LocationSpaceService extends Service { } } - // 如果修改条码,检查唯一性 + // 如果修改条码,检查唯一性(仓库内唯一) if (data.custom_barcode && data.custom_barcode !== locationSpace.custom_barcode) { const exists = await ctx.model.LocationSpace.findOne({ where: { + warehouse_id: locationSpace.warehouse_id, custom_barcode: data.custom_barcode, id: { [ctx.app.Sequelize.Op.ne]: id }, }, diff --git a/app/service/systems/location_zone.js b/app/service/systems/location_zone.js index 17fdd80..6d7515b 100644 --- a/app/service/systems/location_zone.js +++ b/app/service/systems/location_zone.js @@ -1274,27 +1274,31 @@ class LocationZoneService extends Service { throw error; } } - async checkBarcodeUnique(id, barcode) { + async checkBarcodeUnique(id, barcode, warehouseId) { const { ctx, app } = this; const { Op } = this.app.Sequelize || app.Sequelize; try { - // 检查条码是否被其他仓位使用(排除当前仓位) + // 检查条码是否被其他仓位使用(排除当前仓位,仓库内唯一) + const whereConditions = [ + { + id: { + [Op.ne]: id, // 排除当前仓位ID + }, + }, + { + [Op.or]: [ + { custom_barcode: barcode }, // 检查自定义条码 + { space_code: barcode }, // 检查仓位编码 + ], + }, + { deleted_at: null }, // 未删除的记录 + ]; + if (warehouseId) { + whereConditions.push({ warehouse_id: warehouseId }); + } const space = await ctx.model.LocationSpace.findOne({ where: { - [Op.and]: [ - { - id: { - [Op.ne]: id, // 排除当前仓位ID - }, - }, - { - [Op.or]: [ - { custom_barcode: barcode }, // 检查自定义条码 - { space_code: barcode }, // 检查仓位编码 - ], - }, - { deleted_at: null }, // 未删除的记录 - ], + [Op.and]: whereConditions, }, attributes: [ 'id' ], }); diff --git a/database/migrations/20260710000000-fix-custom-barcode-unique-to-per-warehouse.js b/database/migrations/20260710000000-fix-custom-barcode-unique-to-per-warehouse.js new file mode 100644 index 0000000..4f1004f --- /dev/null +++ b/database/migrations/20260710000000-fix-custom-barcode-unique-to-per-warehouse.js @@ -0,0 +1,20 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + // 将 custom_barcode 唯一索引从全局改为仓库级别 + await queryInterface.removeIndex('wms_location_space', 'uk_custom_barcode'); + await queryInterface.addIndex('wms_location_space', ['warehouse_id', 'custom_barcode', 'deleted_at'], { + name: 'uk_warehouse_custom_barcode', + unique: true, + }); + }, + + async down(queryInterface, Sequelize) { + await queryInterface.removeIndex('wms_location_space', 'uk_warehouse_custom_barcode'); + await queryInterface.addIndex('wms_location_space', ['custom_barcode'], { + name: 'uk_custom_barcode', + unique: true, + }); + }, +}; From 16d5f18fa10e8a426aa57d7d67f8d6c3b15b63cd Mon Sep 17 00:00:00 2001 From: liufumingren Date: Wed, 15 Jul 2026 00:10:40 +0800 Subject: [PATCH 111/550] =?UTF-8?q?feat(openapi):=20interface=5Ftype=5Fid?= =?UTF-8?q?=3D2=20=E5=BC=BA=E5=88=B6=E5=90=88=E7=BA=A6=E6=B3=A8=E5=85=A5?= =?UTF-8?q?=20+=20=E5=85=A8=E9=93=BE=E8=B7=AF=20store=5Fid=20=E9=98=B2?= =?UTF-8?q?=E6=8A=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 核心改动: - openapi.js: 新增 resolveOpenapiContract 强制合约解析(required:true JOIN), dispatchOpenapiMethod 统一注入上下文(setInfo) - 5个 openapiMethods: 移除重复 resolveAppInfo, 统一使用 this.getInfo() - deliveryorder/entryorder/stockout: findByPk(itemId) 后增加 store_id 一致性校验 安全修复: - 修复 itemId 路径跨货主越权漏洞(FindByPk 无 store_id 过滤) - deliveryorder/inventory/singleitem 查询补全 store_id 过滤 - 合约缺失返回 403 而非穿透业务层 测试覆盖: 9方法×3层防护(合约/注入/过滤)全部通过集成测试 --- app/service/openapi.js | 90 ++++++++++++++++++++- app/service/openapiMethods/deliveryorder.js | 77 +++--------------- app/service/openapiMethods/entryorder.js | 78 +++--------------- app/service/openapiMethods/inventory.js | 65 ++------------- app/service/openapiMethods/order.js | 66 +++------------ app/service/openapiMethods/singleitem.js | 77 ++++-------------- app/service/qimenMethods/stockout.js | 7 ++ app/service/systems/delivery_order.js | 4 + app/service/systems/entry_order.js | 4 + 9 files changed, 158 insertions(+), 310 deletions(-) diff --git a/app/service/openapi.js b/app/service/openapi.js index 09cbf7f..11f737f 100644 --- a/app/service/openapi.js +++ b/app/service/openapi.js @@ -41,14 +41,71 @@ class OpenapiService extends Service { return methodService || null; } + /** + * 解析 OpenAPI 合约信息(interface_type_id=2 必须绑定有效合约)。 + * 查询 ApiApp 并强制关联 StoreWarehouse,校验 store_id 必须存在。 + * @param {string} appKey 开放接口 app_key。 + * @return {Promise} 包含 storeId、warehouseId、appKey、customerId、warehouseCode 的信息对象。 + */ + async resolveOpenapiContract(appKey) { + const { ctx, app } = this; + const normalizedAppKey = String(appKey || '').trim(); + if (!normalizedAppKey) { + throw new Error('app_key 缺失'); + } + + const appConfig = await ctx.model.ApiApp.findOne({ + attributes: [ + 'id', + 'warehouse_id', + 'qimen_warehouse_code', + [ app.Sequelize.col('contract.store_id'), 'store_id' ], + ], + where: { + self_app_key: normalizedAppKey, + is_enabled: 1, + }, + include: [ + { + model: ctx.model.StoreWarehouse, + as: 'contract', + attributes: [], + required: true, + }, + ], + raw: true, + }); + + if (!appConfig || !appConfig.warehouse_id) { + throw new Error(`无法解析仓库信息,请检查 app_key: ${normalizedAppKey}`); + } + + if (!appConfig.store_id) { + throw new Error(`未找到 app_key 对应的货主合约关系: ${normalizedAppKey}`); + } + + const warehouseId = appConfig.warehouse_id; + + return { + storeId: appConfig.store_id, + warehouseId, + appKey: normalizedAppKey, + customerId: null, + warehouseCode: appConfig.qimen_warehouse_code || String(warehouseId), + }; + } + /** * 分发 openapi method 到 openapiMethods 目录。 + * 分发前统一注入合约上下文(storeId/warehouseId/appKey 等), + * 确保所有下游方法可通过 this.getInfo() 获取货主范围信息。 * @param {string} methodName method 名称。 * @param {Object} body 请求体。 * @param {Object} query 请求 query。 + * @param {Object} contractInfo 合约上下文信息。 * @return {Promise} method 执行结果。 */ - async dispatchOpenapiMethod(methodName, body, query) { + async dispatchOpenapiMethod(methodName, body, query, contractInfo) { const { servicePath, actionName } = this.resolveOpenapiMethod(methodName); const methodService = this.getOpenapiMethodService(servicePath); @@ -62,6 +119,17 @@ class OpenapiService extends Service { }; } + // 统一注入合约上下文到方法服务实例 + if (contractInfo && typeof methodService.setInfo === 'function') { + methodService.setInfo( + contractInfo.storeId, + contractInfo.warehouseId, + contractInfo.appKey, + contractInfo.customerId, + contractInfo.warehouseCode + ); + } + const methodResult = await methodService[actionName]({ body, query, @@ -241,10 +309,26 @@ class OpenapiService extends Service { }; } - return await this.dispatchOpenapiMethod(query.method, body, { + // interface_type_id=2(OPENAPI)必须解析合约并注入货主信息 + let contractInfo = null; + try { + contractInfo = await this.resolveOpenapiContract(appKey); + } catch (error) { + return { + ok: false, + httpStatus: 403, + code: 403, + message: `合约校验失败: ${error.message}`, + data: null, + }; + } + + const queryWithAppKey = { ...query, app_key: appConfig.appKey, - }); + }; + + return await this.dispatchOpenapiMethod(query.method, body, queryWithAppKey, contractInfo); } } diff --git a/app/service/openapiMethods/deliveryorder.js b/app/service/openapiMethods/deliveryorder.js index 8cbda55..842d596 100644 --- a/app/service/openapiMethods/deliveryorder.js +++ b/app/service/openapiMethods/deliveryorder.js @@ -3,62 +3,16 @@ const MainService = require('../main'); class OpenapiDeliveryorderService extends MainService { - /** - * 通过 app_key 解析仓库与货主信息。 - * 查询 ApiApp 并关联 StoreWarehouse 以获取 storeId、warehouseId。 - * @param {string} appKey 开放接口 app_key。 - * @return {Promise} 包含 storeId、warehouseId、appKey、customerId、warehouseCode 的信息对象。 - */ - async resolveAppInfo(appKey) { - const { ctx, app } = this; - const normalizedAppKey = String(appKey || '').trim(); - if (!normalizedAppKey) { - throw new Error('app_key 缺失'); - } - - const appConfig = await ctx.model.ApiApp.findOne({ - attributes: [ - 'id', - 'warehouse_id', - [ app.Sequelize.col('contract.store_id'), 'store_id' ], - ], - where: { - self_app_key: normalizedAppKey, - is_enabled: 1, - }, - include: [ - { - model: ctx.model.StoreWarehouse, - as: 'contract', - attributes: [], - required: false, - }, - ], - raw: true, - }); - - if (!appConfig || !appConfig.warehouse_id) { - throw new Error(`无法解析仓库信息,请检查 app_key: ${normalizedAppKey}`); - } - - return { - storeId: appConfig.store_id || null, - warehouseId: appConfig.warehouse_id, - appKey: normalizedAppKey, - customerId: null, - warehouseCode: '', - }; - } - /** * 查询发货单。 + * 上下文(storeId/warehouseId/appKey)已由 dispatchOpenapiMethod 统一注入。 * @param {Object} payload 调用参数。 * @param {Object} payload.body 请求体数据,需包含 deliveryOrderCode。 - * @param {Object} payload.query 请求 query 数据,需包含 app_key。 + * @param {Object} payload.query 请求 query 数据。 * @return {Promise} 查询结果,成功时返回订单详情,失败时返回错误信息。 */ async query(payload = {}) { - const { body = {}, query = {} } = payload; + const { body = {} } = payload; const { deliveryOrderCode } = body; if (!deliveryOrderCode) { @@ -66,10 +20,13 @@ class OpenapiDeliveryorderService extends MainService { } try { - const info = await this.resolveAppInfo(query.app_key); - const DeliveryModel = await this.ctx.model.OrderDeliveryFactory.getCurrentModel(info.warehouseId); + const { storeId, warehouseId } = this.getInfo(); + const DeliveryModel = await this.ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); const order = await DeliveryModel.findOne({ - where: { delivery_order_code: deliveryOrderCode }, + where: { + delivery_order_code: deliveryOrderCode, + store_id: storeId, + }, }); if (order) { @@ -101,13 +58,14 @@ class OpenapiDeliveryorderService extends MainService { /** * 创建发货单。 + * 上下文(storeId/warehouseId/appKey)已由 dispatchOpenapiMethod 统一注入。 * @param {Object} payload 调用参数。 * @param {Object} payload.body 请求体数据,需包含 deliveryOrder 与 orderLines。 - * @param {Object} payload.query 请求 query 数据,需包含 app_key。 + * @param {Object} payload.query 请求 query 数据。 * @return {Promise} 创建结果,成功时返回订单ID等,失败时返回错误信息。 */ async create(payload = {}) { - const { body = {}, query = {} } = payload; + const { body = {} } = payload; const { deliveryOrder, orderLines } = body; if (!deliveryOrder || !deliveryOrder.deliveryOrderCode) { @@ -118,15 +76,6 @@ class OpenapiDeliveryorderService extends MainService { } try { - const info = await this.resolveAppInfo(query.app_key); - this.setInfo( - info.storeId, - info.warehouseId, - info.appKey, - info.customerId, - info.warehouseCode - ); - const data = { request: { deliveryOrder, @@ -144,7 +93,7 @@ class OpenapiDeliveryorderService extends MainService { return this.success(res.message, { createTime: this.app.formatDate(new Date()), deliveryOrderId: res.data.orderId, - warehouseCode: info.warehouseCode, + warehouseCode: this.warehouseCode, logisticsCode: '', }); } diff --git a/app/service/openapiMethods/entryorder.js b/app/service/openapiMethods/entryorder.js index 7029ba9..eef1e56 100644 --- a/app/service/openapiMethods/entryorder.js +++ b/app/service/openapiMethods/entryorder.js @@ -8,67 +8,17 @@ const MainService = require('../main'); */ class OpenapiEntryorderService extends MainService { - /** - * 通过 app_key 解析仓库与货主信息。 - * 查询 ApiApp 并关联 StoreWarehouse 以获取 storeId、warehouseId。 - * warehouseCode 优先使用 qimen_warehouse_code,为空时回退使用 warehouseId。 - * @param {string} appKey 开放接口 app_key。 - * @return {Promise} 包含 storeId、warehouseId、appKey、customerId、warehouseCode 的信息对象。 - */ - async resolveAppInfo(appKey) { - const { ctx, app } = this; - const normalizedAppKey = String(appKey || '').trim(); - if (!normalizedAppKey) { - throw new Error('app_key 缺失'); - } - - const appConfig = await ctx.model.ApiApp.findOne({ - attributes: [ - 'id', - 'warehouse_id', - 'qimen_warehouse_code', - [ app.Sequelize.col('contract.store_id'), 'store_id' ], - ], - where: { - self_app_key: normalizedAppKey, - is_enabled: 1, - }, - include: [ - { - model: ctx.model.StoreWarehouse, - as: 'contract', - attributes: [], - required: false, - }, - ], - raw: true, - }); - - if (!appConfig || !appConfig.warehouse_id) { - throw new Error(`无法解析仓库信息,请检查 app_key: ${normalizedAppKey}`); - } - - const warehouseId = appConfig.warehouse_id; - - return { - storeId: appConfig.store_id || null, - warehouseId, - appKey: normalizedAppKey, - customerId: null, - warehouseCode: appConfig.qimen_warehouse_code || String(warehouseId), - }; - } - /** * 创建入库单。 + * 上下文(storeId/warehouseId/appKey/warehouseCode)已由 dispatchOpenapiMethod 统一注入。 * 接收外部系统的入库单数据,校验后通过底层 entryOrder 服务完成入库单创建。 * @param {Object} payload 调用参数。 * @param {Object} payload.body 请求体数据,包含 entryOrder(入库单信息)和 orderLines(明细行)。 - * @param {Object} payload.query 请求 query 数据,需包含 app_key。 + * @param {Object} payload.query 请求 query 数据。 * @return {Promise} 创建结果,成功时返回 entryOrderId、entryOrderCode、status 和 createTime。 */ async create(payload = {}) { - const { body = {}, query = {} } = payload; + const { body = {} } = payload; const { entryOrder, orderLines } = body; if (!entryOrder || !entryOrder.entryOrderCode) { @@ -101,15 +51,6 @@ class OpenapiEntryorderService extends MainService { }; try { - const info = await this.resolveAppInfo(query.app_key); - this.setInfo( - info.storeId, - info.warehouseId, - info.appKey, - info.customerId, - info.warehouseCode - ); - const data = { request: { entryOrder: mappedEntryOrder, @@ -140,14 +81,15 @@ class OpenapiEntryorderService extends MainService { /** * 查询入库单。 + * 上下文(storeId/warehouseId)已由 dispatchOpenapiMethod 统一注入。 * 根据入库单号查询入库单详情,包括基本信息与商品明细。 * @param {Object} payload 调用参数。 * @param {Object} payload.body 请求体数据,需包含 entryOrderCode(入库单号)。 - * @param {Object} payload.query 请求 query 数据,需包含 app_key。 + * @param {Object} payload.query 请求 query 数据。 * @return {Promise} 查询结果,成功时返回入库单详情。 */ async query(payload = {}) { - const { body = {}, query = {} } = payload; + const { body = {} } = payload; const { entryOrderCode } = body; if (!entryOrderCode) { @@ -155,11 +97,11 @@ class OpenapiEntryorderService extends MainService { } try { - const info = await this.resolveAppInfo(query.app_key); + const { storeId, warehouseId, warehouseCode } = this.getInfo(); const order = await this.ctx.service.systems.entryOrder.findByOrderCode( entryOrderCode, - info.warehouseId, - info.storeId + warehouseId, + storeId ); if (!order) { @@ -189,7 +131,7 @@ class OpenapiEntryorderService extends MainService { createTime: order.created_at || '', operateTime: order.updated_at || '', operatorName: order.operator_name || '', - warehouseCode: order.warehouse_code || info.warehouseCode, + warehouseCode: order.warehouse_code || warehouseCode, ownerCode: order.store_code || '', totalOrderLines: order.total_order_lines || 0, orderLines, diff --git a/app/service/openapiMethods/inventory.js b/app/service/openapiMethods/inventory.js index 6b9a65b..b841741 100644 --- a/app/service/openapiMethods/inventory.js +++ b/app/service/openapiMethods/inventory.js @@ -8,82 +8,33 @@ const MainService = require('../main'); */ class OpenapiInventoryService extends MainService { - /** - * 通过 app_key 解析仓库与货主信息。 - * 查询 ApiApp 并关联 StoreWarehouse 以获取 storeId、warehouseId。 - * warehouseCode 优先使用 qimen_warehouse_code,为空时回退使用 warehouseId; - * ownerCode 优先使用 store_id,为空时回退使用空字符串。 - * @param {string} appKey 开放接口 app_key。 - * @return {Promise} 包含 storeId、warehouseId、appKey、customerId、warehouseCode、ownerCode 的信息对象。 - */ - async resolveAppInfo(appKey) { - const { ctx, app } = this; - const normalizedAppKey = String(appKey || '').trim(); - if (!normalizedAppKey) { - throw new Error('app_key 缺失'); - } - - const appConfig = await ctx.model.ApiApp.findOne({ - attributes: [ - 'id', - 'warehouse_id', - 'qimen_warehouse_code', - [ app.Sequelize.col('contract.store_id'), 'store_id' ], - ], - where: { - self_app_key: normalizedAppKey, - is_enabled: 1, - }, - include: [ - { - model: ctx.model.StoreWarehouse, - as: 'contract', - attributes: [], - required: false, - }, - ], - raw: true, - }); - - if (!appConfig || !appConfig.warehouse_id) { - throw new Error(`无法解析仓库信息,请检查 app_key: ${normalizedAppKey}`); - } - - const warehouseId = appConfig.warehouse_id; - const storeId = appConfig.store_id || null; - - return { - storeId, - warehouseId, - appKey: normalizedAppKey, - customerId: null, - warehouseCode: appConfig.qimen_warehouse_code || String(warehouseId), - ownerCode: storeId ? String(storeId) : '', - }; - } - /** * 库存查询。 + * 上下文(storeId)已由 dispatchOpenapiMethod 统一注入,查询结果按货主范围校验。 * 根据商品 ID 列表查询对应的库存信息,包括总库存、锁定量和可用量。 * @param {Object} payload 调用参数。 * @param {Object} payload.body 请求体数据,需包含 itemIds(商品 ID 数组)。 - * @param {Object} payload.query 请求 query 数据,需包含 app_key。 + * @param {Object} payload.query 请求 query 数据。 * @return {Promise} 查询结果,成功时返回 items 数组。 */ async query(payload = {}) { - const { body = {}, query = {} } = payload; + const { body = {} } = payload; const { itemIds } = body; if (!Array.isArray(itemIds) || itemIds.length === 0) { return this.fail('itemIds 参数缺失或为空'); } - await this.resolveAppInfo(query.app_key); + const { storeId } = this.getInfo(); const items = []; for (const itemId of itemIds) { const result = await this.ctx.service.systems.stockStore.getItemStorages(itemId); if (result.success && result.data) { + // 按货主范围过滤:仅返回属于当前合约货主的库存 + if (Number(result.data.storage.storeId) !== Number(storeId)) { + continue; + } items.push({ itemId: result.data.stock.id, itemCode: result.data.stock.item_code, diff --git a/app/service/openapiMethods/order.js b/app/service/openapiMethods/order.js index 78adc1c..5365ab9 100644 --- a/app/service/openapiMethods/order.js +++ b/app/service/openapiMethods/order.js @@ -3,59 +3,13 @@ const MainService = require('../main'); class OpenapiOrderService extends MainService { - /** - * 通过 app_key 解析仓库与货主信息。 - * 查询 ApiApp 并关联 StoreWarehouse 以获取 storeId、warehouseId。 - * @param {string} appKey 开放接口 app_key。 - * @return {Promise} 包含 storeId、warehouseId、appKey、customerId、warehouseCode 的信息对象。 - */ - async resolveAppInfo(appKey) { - const { ctx, app } = this; - const normalizedAppKey = String(appKey || '').trim(); - if (!normalizedAppKey) { - throw new Error('app_key 缺失'); - } - - const appConfig = await ctx.model.ApiApp.findOne({ - attributes: [ - 'id', - 'warehouse_id', - [ app.Sequelize.col('contract.store_id'), 'store_id' ], - ], - where: { - self_app_key: normalizedAppKey, - is_enabled: 1, - }, - include: [ - { - model: ctx.model.StoreWarehouse, - as: 'contract', - attributes: [], - required: false, - }, - ], - raw: true, - }); - - if (!appConfig || !appConfig.warehouse_id) { - throw new Error(`无法解析仓库信息,请检查 app_key: ${normalizedAppKey}`); - } - - return { - storeId: appConfig.store_id || null, - warehouseId: appConfig.warehouse_id, - appKey: normalizedAppKey, - customerId: null, - warehouseCode: '', - }; - } - /** * 取消发货单。 + * 上下文(storeId/warehouseId/appKey)已由 dispatchOpenapiMethod 统一注入。 * 当前仅支持出库单类型(JYCK/HHCK/BFCK → ORDER),非出库单类型返回不支持。 * @param {Object} payload 调用参数。 * @param {Object} payload.body 请求体数据,包含 orderCode、orderType。 - * @param {Object} payload.query 请求 query 数据,包含 app_key。 + * @param {Object} payload.query 请求 query 数据。 * @return {Promise} 取消结果,成功时返回成功消息,失败时返回错误信息。 */ async cancel(payload = {}) { @@ -76,16 +30,16 @@ class OpenapiOrderService extends MainService { } try { - const info = await this.resolveAppInfo(query.app_key); + const { storeId, warehouseId, appKey: ctxAppKey } = this.getInfo(); - const DeliveryModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(info.warehouseId); + const DeliveryModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); const transaction = await ctx.model.transaction(); try { const existingOrder = await DeliveryModel.findOne({ where: { delivery_order_code: normalizedOrderCode, - warehouse_id: info.warehouseId, - store_id: info.storeId, + warehouse_id: warehouseId, + store_id: storeId, }, transaction, lock: transaction.LOCK.UPDATE, @@ -123,7 +77,7 @@ class OpenapiOrderService extends MainService { // 释放储位分配锁定库存 await this.releaseStockLockForCancel({ orderId: existingOrder.id, - warehouseId: info.warehouseId, + warehouseId, transaction, }); @@ -132,7 +86,7 @@ class OpenapiOrderService extends MainService { // 写入取消操作日志(不影响主流程) try { if (this.ctx.model && this.ctx.model.OperationLog) { - const appKey = String(query.app_key || '').trim(); + const appKey = String(query.app_key || ctxAppKey || '').trim(); await this.ctx.model.OperationLog.create({ business_type: 'order', business_id: String(existingOrder.id), @@ -140,7 +94,7 @@ class OpenapiOrderService extends MainService { operator_id: null, operator_name: appKey ? `openapi:${appKey}` : 'openapi', external_log_type: 'NONE', - warehouse_id: info.warehouseId || null, + warehouse_id: warehouseId || null, platform_code: appKey || 'SYSTEM', message: 'OpenAPI 取消订单', }); @@ -153,7 +107,7 @@ class OpenapiOrderService extends MainService { try { const callbackService = this.ctx.service.openapi && this.ctx.service.openapi.callback; if (callbackService && typeof callbackService.sendByAppKey === 'function') { - const appKey = String(query.app_key || '').trim(); + const appKey = String(query.app_key || ctxAppKey || '').trim(); if (appKey) { callbackService.sendByAppKey({ appKey, diff --git a/app/service/openapiMethods/singleitem.js b/app/service/openapiMethods/singleitem.js index 5aad33b..3fb2c87 100644 --- a/app/service/openapiMethods/singleitem.js +++ b/app/service/openapiMethods/singleitem.js @@ -8,70 +8,17 @@ const MainService = require('../main'); */ class OpenapiSingleitemService extends MainService { - /** - * 通过 app_key 解析仓库与货主信息。 - * 查询 ApiApp 并关联 StoreWarehouse 以获取 storeId、warehouseId。 - * warehouseCode 优先使用 qimen_warehouse_code,为空时回退使用 warehouseId; - * ownerCode 优先使用 store_id,为空时回退使用空字符串。 - * @param {string} appKey 开放接口 app_key。 - * @return {Promise} 包含 storeId、warehouseId、appKey、customerId、warehouseCode、ownerCode 的信息对象。 - */ - async resolveAppInfo(appKey) { - const { ctx, app } = this; - const normalizedAppKey = String(appKey || '').trim(); - if (!normalizedAppKey) { - throw new Error('app_key 缺失'); - } - - const appConfig = await ctx.model.ApiApp.findOne({ - attributes: [ - 'id', - 'warehouse_id', - 'qimen_warehouse_code', - [ app.Sequelize.col('contract.store_id'), 'store_id' ], - ], - where: { - self_app_key: normalizedAppKey, - is_enabled: 1, - }, - include: [ - { - model: ctx.model.StoreWarehouse, - as: 'contract', - attributes: [], - required: false, - }, - ], - raw: true, - }); - - if (!appConfig || !appConfig.warehouse_id) { - throw new Error(`无法解析仓库信息,请检查 app_key: ${normalizedAppKey}`); - } - - const warehouseId = appConfig.warehouse_id; - const storeId = appConfig.store_id || null; - - return { - storeId, - warehouseId, - appKey: normalizedAppKey, - customerId: null, - warehouseCode: appConfig.qimen_warehouse_code || String(warehouseId), - ownerCode: storeId ? String(storeId) : '', - }; - } - /** * 同步(新增或更新)单品信息。 + * 上下文(storeId/warehouseId/appKey/warehouseCode)已由 dispatchOpenapiMethod 统一注入。 * 将外部系统的商品数据写入 StockStore,并自动同步到库存表。 * @param {Object} payload 调用参数。 * @param {Object} payload.body 请求体数据,仅需包含 item;warehouseCode 和 ownerCode 由 app_key 自动解析,调用方不得传入。 - * @param {Object} payload.query 请求 query 数据,需包含 app_key。 + * @param {Object} payload.query 请求 query 数据。 * @return {Promise} 同步结果,成功时返回 itemId。 */ async synchronize(payload = {}) { - const { body = {}, query = {} } = payload; + const { body = {} } = payload; const { item } = body; if (!item || !item.itemCode) { @@ -79,7 +26,8 @@ class OpenapiSingleitemService extends MainService { } try { - const { storeId, warehouseId, appKey, warehouseCode, ownerCode } = await this.resolveAppInfo(query.app_key); + const { storeId, warehouseId, appKey, warehouseCode } = this.getInfo(); + const ownerCode = storeId ? String(storeId) : ''; const requestData = { warehouseCode: warehouseCode || '', @@ -103,14 +51,15 @@ class OpenapiSingleitemService extends MainService { /** * 查询单品详情。 + * 上下文(storeId)已由 dispatchOpenapiMethod 统一注入,查询按货主范围过滤。 * 根据 itemId 查询 StockStore 记录并转换为 OpenAPI 统一格式。 * @param {Object} payload 调用参数。 * @param {Object} payload.body 请求体数据,需包含 itemId。 - * @param {Object} payload.query 请求 query 数据,需包含 app_key。 + * @param {Object} payload.query 请求 query 数据。 * @return {Promise} 查询结果,成功时返回商品详情。 */ async query(payload = {}) { - const { body = {}, query = {} } = payload; + const { body = {} } = payload; const { itemId } = body; if (!itemId) { @@ -118,10 +67,14 @@ class OpenapiSingleitemService extends MainService { } try { - // 验证 app_key 有效性 - await this.resolveAppInfo(query.app_key); + const { storeId } = this.getInfo(); - const row = await this.ctx.model.StockStore.findByPk(itemId); + const row = await this.ctx.model.StockStore.findOne({ + where: { + id: itemId, + store_id: storeId, + }, + }); if (!row) { return this.fail(`商品不存在,itemId: ${itemId}`); } diff --git a/app/service/qimenMethods/stockout.js b/app/service/qimenMethods/stockout.js index 53abe3f..d7fa424 100644 --- a/app/service/qimenMethods/stockout.js +++ b/app/service/qimenMethods/stockout.js @@ -46,6 +46,13 @@ class stockoutServer extends MainService { for (let i = 0; i < orderLine.length; i++) { const line = orderLine[i]; const wmsStock = await app.model.StockStore.findByPk(line.itemId); + // 校验 StockStore 记录的 store_id 与当前上下文一致,防止跨货主越权 + if (wmsStock && Number(wmsStock.store_id) !== Number(this.storeId)) { + errors.push( + `SKU${line.itemId}商品《${line.itemName}》编码《${line.itemCode}》\n未同步推送到仓库` + ); + continue; + } if (!wmsStock) { errors.push( `SKU${line.itemId}商品《${line.itemName}》编码《${line.itemCode}》\n未同步推送到仓库` diff --git a/app/service/systems/delivery_order.js b/app/service/systems/delivery_order.js index d653447..ae7c1c1 100644 --- a/app/service/systems/delivery_order.js +++ b/app/service/systems/delivery_order.js @@ -1202,6 +1202,10 @@ class DeliveryOrderService extends Service { wms_stock = await app.model.StockStore.findOne({ where: stockWhere, transaction }); } else { wms_stock = await app.model.StockStore.findByPk(line.itemId, { transaction }); + // 校验 StockStore 记录的 store_id 与当前上下文一致,防止跨货主越权 + if (wms_stock && Number(wms_stock.store_id) !== Number(storeId)) { + wms_stock = null; + } } if (!wms_stock) { diff --git a/app/service/systems/entry_order.js b/app/service/systems/entry_order.js index 8056b22..a7fb0ac 100644 --- a/app/service/systems/entry_order.js +++ b/app/service/systems/entry_order.js @@ -42,6 +42,10 @@ class entryOrderService extends Service { }, transaction }); } else { wms_stock = await app.model.StockStore.findByPk(orderLine[i].itemId, { transaction }); + // 校验 StockStore 记录的 store_id 与当前上下文一致,防止跨货主越权 + if (wms_stock && Number(wms_stock.store_id) !== Number(storeId)) { + wms_stock = null; + } } if (!wms_stock) { errors.push(`SKU${orderLine[i].itemId}商品《${orderLine[i].itemName}》编码《${orderLine[i].itemCode}》\n未同步推送到仓库`); From 391ab871120621d46fdc067a6014bbb48050d3fc Mon Sep 17 00:00:00 2001 From: liufumingren Date: Thu, 16 Jul 2026 20:19:03 +0800 Subject: [PATCH 112/550] =?UTF-8?q?fix(order=5Fexpress):=20=E5=8C=85?= =?UTF-8?q?=E6=9D=90=E6=89=B9=E9=87=8F=E7=BB=91=E5=AE=9A=E9=80=82=E9=85=8D?= =?UTF-8?q?=20current+dispatch=20=E5=8F=8C=E8=A1=A8=E6=9F=A5=E8=AF=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 修复波次团购包材批量绑定只查 current 表导致 dispatch 表订单遗漏的问题: - bindExpressPackageMaterialByWaybill: 波次检测改为 current→dispatch 双表遍历 - _bindWavePackageMaterialByBusinessKey: 波次订单查询改为双表合并去重 - _getStoreName / _getWaveSysLogisticsName: 货主/物流名查询改为双表遍历 - _upsertPackageMaterialItemRelation: items_hash 查询改为双表遍历 - _updateSingleOrderWeight: items_weight 读取改为双表遍历 --- app/service/systems/order_express.js | 172 +++++++++++++++++++-------- 1 file changed, 120 insertions(+), 52 deletions(-) diff --git a/app/service/systems/order_express.js b/app/service/systems/order_express.js index 9f6e347..642f303 100644 --- a/app/service/systems/order_express.js +++ b/app/service/systems/order_express.js @@ -690,17 +690,27 @@ class OrderExpressService extends Service { return ''; } const { Op } = this.app.Sequelize; - const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(warehouseId); - const orderRow = await orderDeliveryModel.findOne({ - where: { - id: { [Op.in]: orderIds }, - warehouse_id: warehouseId, - shop_nick: { [Op.ne]: null }, - }, - attributes: [ 'shop_nick' ], - raw: true, - }); - return orderRow ? String(orderRow.shop_nick || '').trim() : ''; + const tableOrders = [ + { label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) }, + { label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) }, + ]; + for (const entry of tableOrders) { + try { + const model = await entry.getModel(); + if (!model || typeof model.findOne !== 'function') continue; + const orderRow = await model.findOne({ + where: { + id: { [Op.in]: orderIds }, + warehouse_id: warehouseId, + shop_nick: { [Op.ne]: null }, + }, + attributes: [ 'shop_nick' ], + raw: true, + }); + if (orderRow) return String(orderRow.shop_nick || '').trim(); + } catch (_err) { continue; } + } + return ''; } catch (_err) { return ''; } @@ -722,17 +732,27 @@ class OrderExpressService extends Service { return ''; } const { Op } = this.app.Sequelize; - const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(warehouseId); - const orderRow = await orderDeliveryModel.findOne({ - where: { - id: { [Op.in]: orderIds }, - warehouse_id: warehouseId, - sys_logistics_name: { [Op.ne]: null }, - }, - attributes: [ 'sys_logistics_name' ], - raw: true, - }); - return orderRow ? String(orderRow.sys_logistics_name || '').trim() : ''; + const tableOrders = [ + { label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) }, + { label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) }, + ]; + for (const entry of tableOrders) { + try { + const model = await entry.getModel(); + if (!model || typeof model.findOne !== 'function') continue; + const orderRow = await model.findOne({ + where: { + id: { [Op.in]: orderIds }, + warehouse_id: warehouseId, + sys_logistics_name: { [Op.ne]: null }, + }, + attributes: [ 'sys_logistics_name' ], + raw: true, + }); + if (orderRow) return String(orderRow.sys_logistics_name || '').trim(); + } catch (_err) { continue; } + } + return ''; } catch (_err) { return ''; } @@ -792,18 +812,28 @@ class OrderExpressService extends Service { }); // 从订单表读取当前 items_weight(只读,不做 UPDATE) + // 依次查 current / dispatch 两张表 let itemsWeight = 0; if (warehouseId) { try { const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; if (orderDeliveryFactory && typeof orderDeliveryFactory.getCurrentModel === 'function') { - const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(warehouseId); - const orderRow = await orderDeliveryModel.findOne({ - where: { id: Number(targetRow.order_id), warehouse_id: warehouseId }, - attributes: [ 'items_weight' ], - raw: true, - }); - itemsWeight = orderRow ? Number(orderRow.items_weight || 0) : 0; + const tableOrders = [ + { label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) }, + { label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) }, + ]; + for (const entry of tableOrders) { + try { + const model = await entry.getModel(); + if (!model || typeof model.findOne !== 'function') continue; + const orderRow = await model.findOne({ + where: { id: Number(targetRow.order_id), warehouse_id: warehouseId }, + attributes: [ 'items_weight' ], + raw: true, + }); + if (orderRow) { itemsWeight = Number(orderRow.items_weight || 0); break; } + } catch (_err) { continue; } + } } } catch (_err) { // 查询失败时静默降级为 0 @@ -1131,16 +1161,28 @@ class OrderExpressService extends Service { async _upsertPackageMaterialItemRelation({ orderId, waybillCode, packageMaterialId, packageMaterialCode, packageMaterialName, warehouseId }) { const { ctx } = this; try { - // 1. 查订单的 items_hash / items_crc + // 1. 查订单的 items_hash / items_crc(依次查 current / dispatch 两张表) const orderDeliveryFactory = ctx.model && ctx.model.OrderDeliveryFactory; if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') return; - const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(warehouseId); - const orderRow = await orderDeliveryModel.findOne({ - where: { id: orderId, warehouse_id: warehouseId }, - attributes: [ 'items_hash', 'items_crc' ], - raw: true, - }); + const tableOrders = [ + { label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) }, + { label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) }, + ]; + + let orderRow = null; + for (const entry of tableOrders) { + try { + const model = await entry.getModel(); + if (!model || typeof model.findOne !== 'function') continue; + const row = await model.findOne({ + where: { id: orderId, warehouse_id: warehouseId }, + attributes: [ 'items_hash', 'items_crc' ], + raw: true, + }); + if (row) { orderRow = row; break; } + } catch (_err) { continue; } + } if (!orderRow || !orderRow.items_hash) return; const { items_hash: itemsHash, items_crc: itemsCrc } = orderRow; @@ -1329,16 +1371,28 @@ class OrderExpressService extends Service { const materialRow = await this.findActivePackageMaterialById(normalizedPackageMaterialId, warehouseId); // --- 团购波次自动感知 --- - // 尝试查询运单所属订单是否属于团购波次 + // 依次查询 current / dispatch 表获取波次信息 const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; if (orderDeliveryFactory && typeof orderDeliveryFactory.getCurrentModel === 'function') { try { - const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(warehouseId); - const orderRow = await orderDeliveryModel.findOne({ - where: { id: Number(orderExpressRow.order_id), warehouse_id: warehouseId }, - attributes: [ 'id', 'wave_id', 'wave_no' ], - raw: true, - }); + const orderTableOrders = [ + { label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) }, + { label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) }, + ]; + + let orderRow = null; + for (const entry of orderTableOrders) { + try { + const model = await entry.getModel(); + if (!model || typeof model.findOne !== 'function') continue; + const row = await model.findOne({ + where: { id: Number(orderExpressRow.order_id), warehouse_id: warehouseId }, + attributes: [ 'id', 'wave_id', 'wave_no' ], + raw: true, + }); + if (row) { orderRow = row; break; } + } catch (_err) { continue; } + } if (orderRow) { const waveId = Number(orderRow.wave_id || 0); @@ -1499,24 +1553,38 @@ class OrderExpressService extends Service { triggerOrderId, triggerWaybillCode, }) { - // 1. 查询波次下所有订单 + // 1. 查询波次下所有订单(current + dispatch 两张表) const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') { throw this.createBusinessError('订单模型未初始化', 500); } - const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(warehouseId); - const waveOrders = await orderDeliveryModel.findAll({ - where: { wave_id: waveId, warehouse_id: warehouseId }, - attributes: [ 'id' ], - raw: true, - }); + const tableOrders = [ + { label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) }, + { label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) }, + ]; - if (!waveOrders || waveOrders.length === 0) { + const orderIdSet = new Set(); + for (const entry of tableOrders) { + try { + const model = await entry.getModel(); + if (!model || typeof model.findAll !== 'function') continue; + const rows = await model.findAll({ + where: { wave_id: waveId, warehouse_id: warehouseId }, + attributes: [ 'id' ], + raw: true, + }); + if (Array.isArray(rows)) { + rows.forEach(r => orderIdSet.add(Number(r.id))); + } + } catch (_err) { continue; } + } + + if (orderIdSet.size === 0) { throw this.createBusinessError('波次下未找到订单', 404); } - const orderIds = waveOrders.map(o => Number(o.id)); + const orderIds = Array.from(orderIdSet); // 2. 查询这些订单下相同 business_key 的所有有效运单 const { Op } = this.app.Sequelize; From 3e813c4975eab0f010d5d98f0ff09d8f4561cdc0 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Fri, 17 Jul 2026 00:30:54 +0800 Subject: [PATCH 113/550] =?UTF-8?q?fix:=20=E5=B0=86=20storage.report=20?= =?UTF-8?q?=E6=A8=A1=E5=9D=97=E8=BF=81=E7=A7=BB=E8=87=B3=20stock.report?= =?UTF-8?q?=EF=BC=8C=E4=BF=AE=E6=AD=A3=E8=AF=AD=E4=B9=89=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 库存报表属于 stock(商品库存)域而非 storage(库位存储)域。 变更: - systemMethods/storage/report.js → systemMethods/stock/report.js - 类名 StorageReportMethodService → StockReportMethodService - 缓存键 storage_report_export_ → stock_report_export_ - 日志前缀 [storage.report] → [stock.report] - methods/system.json: module + 5 method 名同步更新 - methods/changes/system.json: 追加迁移记录 - systems/storage/entry.js: 注释引用修正 旧文件直接删除,不保留兼容(旧 method 名为语义错误)。 --- app/service/systemMethods/stock/report.js | 508 ++++++ app/service/systemMethods/storage/report.js | 302 ---- app/service/systems/storage/entry.js | 69 +- methods/changes/system.json | 53 + methods/system.json | 1604 ++++++++++++++++++- 5 files changed, 2210 insertions(+), 326 deletions(-) create mode 100644 app/service/systemMethods/stock/report.js delete mode 100644 app/service/systemMethods/storage/report.js diff --git a/app/service/systemMethods/stock/report.js b/app/service/systemMethods/stock/report.js new file mode 100644 index 0000000..e4ddfdd --- /dev/null +++ b/app/service/systemMethods/stock/report.js @@ -0,0 +1,508 @@ +'use strict'; + +const MainService = require('../../main'); + +const STOCK_REPORT_EXPORT_TASK_CACHE_KEY_PREFIX = 'stock_report_export_task_'; +const STOCK_REPORT_EXPORT_TASK_CACHE_TTL_SECONDS = 1800; + +/** + * 系统方法层:stock.report(库存流水报表接口包装层)。 + */ +class StockReportMethodService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'search,searchStore,export,exportStore,exportTaskProgress'; + const _noNeedLog = 'search,searchStore,export,exportStore,exportTaskProgress'; + const _noNeedAuth = 'search,searchStore,export,exportStore,exportTaskProgress'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 查询库存流水统计报表。 + * @param {Object} data 请求体 + * @param {Object} [data.where] 查询条件 + * @param {Object} [data.sort] 排序参数 + * @param {string} [data.sort.sortField] 排序字段(兼容:sort_field) + * @param {string} [data.sort.sortOrder] 排序顺序(兼容:sort_order) + * @param {string|Date} [data.where.start_time] 开始时间 + * @param {string|Date} [data.where.end_time] 结束时间 + * @param {boolean|string|number} [data.where.by_space=false] 是否按库位返回 + * @param {Array} [data.where.store_ids] 货主ID列表 + * @param {number|number[]} [data.where.stock_id] 商品库存ID(单数) + * @param {number[]} [data.where.stock_ids] 商品库存ID列表(复数) + * @param {string} [data.where.keyword] 商品关键字(按 item_code/item_name/goods_code/barcode 模糊匹配) + * @return {Promise} 统一 success 包装 + */ + async search(data = {}) { + const { service } = this; + const { whereValue = {} } = this.prepareWhereContext(data); + const { + start_time: startTime, + end_time: endTime, + by_space: bySpace, + store_ids: storeIds, + stock_id: stockIdRaw, + stock_ids: stockIdsRaw, + keyword, + sort_field: whereSortField, + sortField: whereSortFieldCamel, + sort_order: whereSortOrder, + sortOrder: whereSortOrderCamel, + } = whereValue; + + // 兼容 stock_id(单数)和 stock_ids(数组) + const stockIds = stockIdsRaw !== undefined + ? stockIdsRaw + : (stockIdRaw !== undefined ? [ stockIdRaw ] : null); + + const { sort = {} } = data; + const { + sort_field: sortFieldSnake, + sortField: sortFieldCamel, + sort_order: sortOrderSnake, + sortOrder: sortOrderCamel, + } = sort || {}; + + const result = await service.systems.storage.report.search(startTime, endTime, bySpace, storeIds, { + sortField: sortFieldCamel || sortFieldSnake || whereSortFieldCamel || whereSortField, + sortOrder: sortOrderCamel || sortOrderSnake || whereSortOrderCamel || whereSortOrder, + }, 'warehouse', stockIds, keyword); + return this.success('ok', result); + } + + /** + * 货主侧库存流水统计报表。 + * 以货主维度查询库存流水,只关注商品入库和订单出库,不涉及库位维度。 + * @param {Object} data 请求体 + * @param {Object} [data.where] 查询条件 + * @param {Object} [data.sort] 排序参数 + * @param {string} [data.sort.sortField] 排序字段(兼容:sort_field) + * @param {string} [data.sort.sortOrder] 排序顺序(兼容:sort_order) + * @param {string|Date} [data.where.start_time] 开始时间 + * @param {string|Date} [data.where.end_time] 结束时间 + * @param {Array} [data.where.warehouse_ids] 仓库ID列表(可选过滤) + * @param {number|number[]} [data.where.stock_id] 商品库存ID(单数) + * @param {number[]} [data.where.stock_ids] 商品库存ID列表(复数) + * @param {string} [data.where.keyword] 商品关键字(按 item_code/item_name/goods_code/barcode 模糊匹配) + * @return {Promise} 统一 success 包装 + */ + async searchStore(data = {}) { + const { service } = this; + const { whereValue = {} } = this.prepareWhereContext(data); + const { + start_time: startTime, + end_time: endTime, + warehouse_ids: warehouseIdsRaw, + warehouse_id: warehouseIdRaw, + stock_id: stockIdRaw, + stock_ids: stockIdsRaw, + keyword, + sort_field: whereSortField, + sortField: whereSortFieldCamel, + sort_order: whereSortOrder, + sortOrder: whereSortOrderCamel, + } = whereValue; + + // 兼容 warehouse_id(单数)和 warehouse_ids(数组) + const warehouseIds = warehouseIdsRaw !== undefined + ? warehouseIdsRaw + : (warehouseIdRaw !== undefined ? [ warehouseIdRaw ] : undefined); + + // 兼容 stock_id(单数)和 stock_ids(数组) + const stockIds = stockIdsRaw !== undefined + ? stockIdsRaw + : (stockIdRaw !== undefined ? [ stockIdRaw ] : null); + + const { sort = {} } = data; + const { + sort_field: sortFieldSnake, + sortField: sortFieldCamel, + sort_order: sortOrderSnake, + sortOrder: sortOrderCamel, + } = sort || {}; + + // 货主侧不涉及库位维度(by_space 固定为 false) + const result = await service.systems.storage.report.search( + startTime, + endTime, + false, + warehouseIds, // store 模式下 storeIds 参数实际承载 warehouse_id 过滤 + { + sortField: sortFieldCamel || sortFieldSnake || whereSortFieldCamel || whereSortField, + sortOrder: sortOrderCamel || sortOrderSnake || whereSortOrderCamel || whereSortOrder, + }, + 'store', + stockIds, + keyword + ); + return this.success('ok', result); + } + + /** + * 货主侧提交库存报表导出任务。 + * 与 export 逻辑一致但使用货主维度,只关注商品入库和订单出库,不涉及库位维度。 + * 异步执行,立即返回任务ID。 + * @param {Object} data 请求体 + * @param {Object} [data.where] 查询条件 + * @param {Object} [data.sort] 排序参数 + * @param {string} [data.sort.sortField] 排序字段(兼容:sort_field) + * @param {string} [data.sort.sortOrder] 排序顺序(兼容:sort_order) + * @param {string|Date} [data.where.start_time] 开始时间 + * @param {string|Date} [data.where.end_time] 结束时间 + * @param {Array} [data.where.warehouse_ids] 仓库ID列表 + * @param {number|number[]} [data.where.stock_id] 商品库存ID(单数) + * @param {number[]} [data.where.stock_ids] 商品库存ID列表(复数) + * @param {string} [data.where.keyword] 商品关键字(模糊匹配) + * @param {string} [data.export_mode] 导出模式:'item' 导出含锁定类型的全部变更记录 + * @param {string} [data.exportMode] 导出模式(驼峰写法,同 export_mode) + * @return {Promise} 统一 success 包装(返回任务ID) + */ + async exportStore(data = {}) { + const { service } = this; + const { whereValue = {} } = this.prepareWhereContext(data); + const { + start_time: startTime, + end_time: endTime, + warehouse_ids: warehouseIdsRaw, + warehouse_id: warehouseIdRaw, + stock_id: stockIdRaw, + stock_ids: stockIdsRaw, + keyword, + sort_field: whereSortField, + sortField: whereSortFieldCamel, + sort_order: whereSortOrder, + sortOrder: whereSortOrderCamel, + } = whereValue; + + // 兼容 warehouse_id(单数)和 warehouse_ids(数组) + const warehouseIds = warehouseIdsRaw !== undefined + ? warehouseIdsRaw + : (warehouseIdRaw !== undefined ? [ warehouseIdRaw ] : undefined); + + // 兼容 stock_id(单数)和 stock_ids(数组) + const stockIds = stockIdsRaw !== undefined + ? stockIdsRaw + : (stockIdRaw !== undefined ? [ stockIdRaw ] : null); + + const { sort = {} } = data; + const { + sort_field: sortFieldSnake, + sortField: sortFieldCamel, + sort_order: sortOrderSnake, + sortOrder: sortOrderCamel, + } = sort || {}; + + const exportMode = String(data.export_mode || data.exportMode || '').trim(); + + const taskId = this.generateExportTaskId(); + const taskPayload = { + task_id: taskId, + status: 'submitted', + progress: 0, + message: '导出任务已提交', + result: null, + error: '', + }; + + await this.setExportTaskProgress(taskId, taskPayload); + + const sortOption = { + sortField: sortFieldCamel || sortFieldSnake || whereSortFieldCamel || whereSortField, + sortOrder: sortOrderCamel || sortOrderSnake || whereSortOrderCamel || whereSortOrder, + }; + + setImmediate(async () => { + try { + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'running', + progress: 10, + message: '导出任务执行中', + result: null, + error: '', + }); + + const result = await service.systems.storage.report.export( + startTime, endTime, false, warehouseIds, + sortOption, exportMode, 'store', stockIds, keyword + ); + + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'success', + progress: 100, + message: '导出任务完成', + result, + error: '', + }); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'failed', + progress: 100, + message: '导出任务失败', + result: null, + error: errorMessage, + }); + } + }); + + return this.success('ok', { + ...taskPayload, + update_time: Date.now(), + }); + } + + /** + * 提交库存流水统计报表导出任务(仓库侧)。 + * @param {Object} data 请求体 + * @param {Object} [data.where] 查询条件 + * @param {Object} [data.sort] 排序参数 + * @param {string} [data.sort.sortField] 排序字段(兼容:sort_field) + * @param {string} [data.sort.sortOrder] 排序顺序(兼容:sort_order) + * @param {string|Date} [data.where.start_time] 开始时间 + * @param {string|Date} [data.where.end_time] 结束时间 + * @param {boolean|string|number} [data.where.by_space=false] 是否按库位返回 + * @param {Array} [data.where.store_ids] 货主ID列表 + * @param {number|number[]} [data.where.stock_id] 商品库存ID(单数) + * @param {number[]} [data.where.stock_ids] 商品库存ID列表(复数) + * @param {string} [data.where.keyword] 商品关键字(模糊匹配) + * @param {string} [data.export_mode] 导出模式:'item' 导出含锁定类型的全部变更记录,不传则排除锁定类型 + * @param {string} [data.exportMode] 导出模式(驼峰写法,同 export_mode) + * @return {Promise} 统一 success 包装(返回任务ID) + */ + async export(data = {}) { + const { service } = this; + const { whereValue = {} } = this.prepareWhereContext(data); + const { + start_time: startTime, + end_time: endTime, + by_space: bySpace, + store_ids: storeIds, + stock_id: stockIdRaw, + stock_ids: stockIdsRaw, + keyword, + sort_field: whereSortField, + sortField: whereSortFieldCamel, + sort_order: whereSortOrder, + sortOrder: whereSortOrderCamel, + } = whereValue; + + // 兼容 stock_id(单数)和 stock_ids(数组) + const stockIds = stockIdsRaw !== undefined + ? stockIdsRaw + : (stockIdRaw !== undefined ? [ stockIdRaw ] : null); + + const { sort = {} } = data; + const { + sort_field: sortFieldSnake, + sortField: sortFieldCamel, + sort_order: sortOrderSnake, + sortOrder: sortOrderCamel, + } = sort || {}; + + const exportMode = String(data.export_mode || data.exportMode || '').trim(); + + const taskId = this.generateExportTaskId(); + const taskPayload = { + task_id: taskId, + status: 'submitted', + progress: 0, + message: '导出任务已提交', + result: null, + error: '', + }; + + await this.setExportTaskProgress(taskId, taskPayload); + + const sortOption = { + sortField: sortFieldCamel || sortFieldSnake || whereSortFieldCamel || whereSortField, + sortOrder: sortOrderCamel || sortOrderSnake || whereSortOrderCamel || whereSortOrder, + }; + + setImmediate(async () => { + try { + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'running', + progress: 10, + message: '导出任务执行中', + result: null, + error: '', + }); + + const result = await service.systems.storage.report.export(startTime, endTime, bySpace, storeIds, sortOption, exportMode, 'warehouse', stockIds, keyword); + + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'success', + progress: 100, + message: '导出任务完成', + result, + error: '', + }); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'failed', + progress: 100, + message: '导出任务失败', + result: null, + error: errorMessage, + }); + } + }); + + return this.success('ok', { + ...taskPayload, + update_time: Date.now(), + }); + } + + /** + * 查询库存流水统计报表导出任务进度。 + * @param {Object} data 请求体 + * @param {string} [data.task_id] 任务ID(下划线写法) + * @param {string} [data.taskId] 任务ID(驼峰写法) + * @return {Promise} 统一 success 包装 + */ + async exportTaskProgress(data = {}) { + const taskId = this.normalizeExportTaskId(data); + if (!taskId) { + return this.success('ok', { + task_id: '', + status: 'not_found', + progress: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const cachedTask = await this.getExportTaskProgress(taskId); + if (!cachedTask) { + return this.success('ok', { + task_id: taskId, + status: 'not_found', + progress: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {}; + const downloadUrl = String( + safeResult.url + || safeResult.cndUrl + || safeResult.cosUrl + || safeResult.fileKey + || '' + ); + + return this.success('ok', { + task_id: taskId, + ...cachedTask, + download_url: downloadUrl, + }); + } + + /** + * 生成导出任务ID。 + * @return {string} 导出任务ID + */ + generateExportTaskId() { + const warehouseId = this.ctx?.user?.store_id || 'unknown'; + const timestamp = Date.now(); + const randomToken = Math.random().toString(36).slice(2, 10); + return `stock_report_export_${warehouseId}_${timestamp}_${randomToken}`; + } + + /** + * 规范导出任务ID。 + * @param {Object} data 请求体 + * @param {string} [data.task_id] 任务ID(下划线写法) + * @param {string} [data.taskId] 任务ID(驼峰写法) + * @return {string} 归一化后的任务ID + */ + normalizeExportTaskId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.task_id || normalizedData.taskId || '').trim(); + } + + /** + * 获取导出任务缓存键。 + * @param {string} taskId 任务ID + * @return {string} 缓存键 + */ + getExportTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + + return `${STOCK_REPORT_EXPORT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 写入导出任务进度缓存。 + * @param {string} taskId 任务ID + * @param {Object} payload 任务状态载荷 + * @return {Promise} 无返回值 + */ + async setExportTaskProgress(taskId = '', payload = {}) { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.setCacheAsync !== 'function') { + return; + } + + const safePayload = this.isPlainObject(payload) ? payload : {}; + const progressPayload = { + task_id: String(taskId || '').trim(), + status: String(safePayload.status || 'submitted').trim() || 'submitted', + progress: Number.isFinite(Number(safePayload.progress)) ? Math.min(100, Math.max(0, Math.round(Number(safePayload.progress)))) : 0, + message: String(safePayload.message || ''), + result: safePayload.result ?? null, + error: String(safePayload.error || ''), + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync(cacheKey, progressPayload, STOCK_REPORT_EXPORT_TASK_CACHE_TTL_SECONDS); + } catch (error) { + this.ctx.logger.warn('[stock.report.export] 写入导出任务缓存失败: %s', error && error.message ? error.message : error); + } + } + + /** + * 读取导出任务进度缓存。 + * @param {string} taskId 任务ID + * @return {Promise} 任务缓存 + */ + async getExportTaskProgress(taskId = '') { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.getCacheAsync !== 'function') { + return null; + } + + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (!this.isPlainObject(cached)) { + return null; + } + return cached; + } catch (error) { + this.ctx.logger.warn('[stock.report.export] 读取导出任务缓存失败: %s', error && error.message ? error.message : error); + return null; + } + } +} + +module.exports = StockReportMethodService; diff --git a/app/service/systemMethods/storage/report.js b/app/service/systemMethods/storage/report.js deleted file mode 100644 index 58b3469..0000000 --- a/app/service/systemMethods/storage/report.js +++ /dev/null @@ -1,302 +0,0 @@ -'use strict'; - -const MainService = require('../../main'); - -const STORAGE_REPORT_EXPORT_TASK_CACHE_KEY_PREFIX = 'storage_report_export_task_'; -const STORAGE_REPORT_EXPORT_TASK_CACHE_TTL_SECONDS = 1800; - -/** - * 系统方法层:storage.report(库存流水报表接口包装层)。 - */ -class StorageReportMethodService extends MainService { - constructor(ctx) { - super(ctx); - const _noNeedLogin = ''; - const _noNeedRight = 'search,export,exportTaskProgress'; - const _noNeedLog = 'search,export,exportTaskProgress'; - const _noNeedAuth = 'search,export,exportTaskProgress'; - this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); - } - - /** - * 查询库存流水统计报表。 - * @param {Object} data 请求体 - * @param {Object} [data.where] 查询条件 - * @param {Object} [data.sort] 排序参数 - * @param {string} [data.sort.sortField] 排序字段(兼容:sort_field) - * @param {string} [data.sort.sortOrder] 排序顺序(兼容:sort_order) - * @param {string|Date} [data.where.start_time] 开始时间 - * @param {string|Date} [data.where.end_time] 结束时间 - * @param {boolean|string|number} [data.where.by_space=false] 是否按库位返回 - * @param {Array} [data.where.store_ids] 货主ID列表 - * @return {Promise} 统一 success 包装 - */ - async search(data = {}) { - const { service } = this; - const { whereValue = {} } = this.prepareWhereContext(data); - const { - start_time: startTime, - end_time: endTime, - by_space: bySpace, - store_ids: storeIds, - sort_field: whereSortField, - sortField: whereSortFieldCamel, - sort_order: whereSortOrder, - sortOrder: whereSortOrderCamel, - } = whereValue; - - const { sort = {} } = data; - const { - sort_field: sortFieldSnake, - sortField: sortFieldCamel, - sort_order: sortOrderSnake, - sortOrder: sortOrderCamel, - } = sort || {}; - - const result = await service.systems.storage.report.search(startTime, endTime, bySpace, storeIds, { - sortField: sortFieldCamel || sortFieldSnake || whereSortFieldCamel || whereSortField, - sortOrder: sortOrderCamel || sortOrderSnake || whereSortOrderCamel || whereSortOrder, - }); - return this.success('ok', result); - } - - /** - * 提交库存流水统计报表导出任务。 - * @param {Object} data 请求体 - * @param {Object} [data.where] 查询条件 - * @param {Object} [data.sort] 排序参数 - * @param {string} [data.sort.sortField] 排序字段(兼容:sort_field) - * @param {string} [data.sort.sortOrder] 排序顺序(兼容:sort_order) - * @param {string|Date} [data.where.start_time] 开始时间 - * @param {string|Date} [data.where.end_time] 结束时间 - * @param {boolean|string|number} [data.where.by_space=false] 是否按库位返回 - * @param {Array} [data.where.store_ids] 货主ID列表 - * @param {string} [data.export_mode] 导出模式:'item' 导出含锁定类型的全部变更记录,不传则排除锁定类型 - * @param {string} [data.exportMode] 导出模式(驼峰写法,同 export_mode) - * @return {Promise} 统一 success 包装(返回任务ID) - */ - async export(data = {}) { - const { service } = this; - const { whereValue = {} } = this.prepareWhereContext(data); - const { - start_time: startTime, - end_time: endTime, - by_space: bySpace, - store_ids: storeIds, - sort_field: whereSortField, - sortField: whereSortFieldCamel, - sort_order: whereSortOrder, - sortOrder: whereSortOrderCamel, - } = whereValue; - - const { sort = {} } = data; - const { - sort_field: sortFieldSnake, - sortField: sortFieldCamel, - sort_order: sortOrderSnake, - sortOrder: sortOrderCamel, - } = sort || {}; - - const exportMode = String(data.export_mode || data.exportMode || '').trim(); - - const taskId = this.generateExportTaskId(); - const taskPayload = { - task_id: taskId, - status: 'submitted', - progress: 0, - message: '导出任务已提交', - result: null, - error: '', - }; - - await this.setExportTaskProgress(taskId, taskPayload); - - const sortOption = { - sortField: sortFieldCamel || sortFieldSnake || whereSortFieldCamel || whereSortField, - sortOrder: sortOrderCamel || sortOrderSnake || whereSortOrderCamel || whereSortOrder, - }; - - setImmediate(async () => { - try { - await this.setExportTaskProgress(taskId, { - task_id: taskId, - status: 'running', - progress: 10, - message: '导出任务执行中', - result: null, - error: '', - }); - - const result = await service.systems.storage.report.export(startTime, endTime, bySpace, storeIds, sortOption, exportMode); - - await this.setExportTaskProgress(taskId, { - task_id: taskId, - status: 'success', - progress: 100, - message: '导出任务完成', - result, - error: '', - }); - } catch (error) { - const errorMessage = error && error.message ? error.message : `${error}`; - await this.setExportTaskProgress(taskId, { - task_id: taskId, - status: 'failed', - progress: 100, - message: '导出任务失败', - result: null, - error: errorMessage, - }); - } - }); - - return this.success('ok', { - ...taskPayload, - update_time: Date.now(), - }); - } - - /** - * 查询库存流水统计报表导出任务进度。 - * @param {Object} data 请求体 - * @param {string} [data.task_id] 任务ID(下划线写法) - * @param {string} [data.taskId] 任务ID(驼峰写法) - * @return {Promise} 统一 success 包装 - */ - async exportTaskProgress(data = {}) { - const taskId = this.normalizeExportTaskId(data); - if (!taskId) { - return this.success('ok', { - task_id: '', - status: 'not_found', - progress: 0, - message: '任务不存在', - result: null, - error: '', - download_url: '', - update_time: Date.now(), - }); - } - - const cachedTask = await this.getExportTaskProgress(taskId); - if (!cachedTask) { - return this.success('ok', { - task_id: taskId, - status: 'not_found', - progress: 0, - message: '任务不存在', - result: null, - error: '', - download_url: '', - update_time: Date.now(), - }); - } - - const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {}; - const downloadUrl = String( - safeResult.url - || safeResult.cndUrl - || safeResult.cosUrl - || safeResult.fileKey - || '' - ); - - return this.success('ok', { - task_id: taskId, - ...cachedTask, - download_url: downloadUrl, - }); - } - - /** - * 生成导出任务ID。 - * @return {string} 导出任务ID - */ - generateExportTaskId() { - const warehouseId = this.ctx?.user?.store_id || 'unknown'; - const timestamp = Date.now(); - const randomToken = Math.random().toString(36).slice(2, 10); - return `storage_report_export_${warehouseId}_${timestamp}_${randomToken}`; - } - - /** - * 规范导出任务ID。 - * @param {Object} data 请求体 - * @param {string} [data.task_id] 任务ID(下划线写法) - * @param {string} [data.taskId] 任务ID(驼峰写法) - * @return {string} 归一化后的任务ID - */ - normalizeExportTaskId(data = {}) { - const normalizedData = this.isPlainObject(data) ? data : {}; - return String(normalizedData.task_id || normalizedData.taskId || '').trim(); - } - - /** - * 获取导出任务缓存键。 - * @param {string} taskId 任务ID - * @return {string} 缓存键 - */ - getExportTaskCacheKey(taskId = '') { - const normalizedTaskId = String(taskId || '').trim(); - if (!normalizedTaskId) { - return ''; - } - - return `${STORAGE_REPORT_EXPORT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; - } - - /** - * 写入导出任务进度缓存。 - * @param {string} taskId 任务ID - * @param {Object} payload 任务状态载荷 - * @return {Promise} 无返回值 - */ - async setExportTaskProgress(taskId = '', payload = {}) { - const cacheKey = this.getExportTaskCacheKey(taskId); - if (!cacheKey || typeof this.app.setCacheAsync !== 'function') { - return; - } - - const safePayload = this.isPlainObject(payload) ? payload : {}; - const progressPayload = { - task_id: String(taskId || '').trim(), - status: String(safePayload.status || 'submitted').trim() || 'submitted', - progress: Number.isFinite(Number(safePayload.progress)) ? Math.min(100, Math.max(0, Math.round(Number(safePayload.progress)))) : 0, - message: String(safePayload.message || ''), - result: safePayload.result ?? null, - error: String(safePayload.error || ''), - update_time: Date.now(), - }; - - try { - await this.app.setCacheAsync(cacheKey, progressPayload, STORAGE_REPORT_EXPORT_TASK_CACHE_TTL_SECONDS); - } catch (error) { - this.ctx.logger.warn('[storage.report.export] 写入导出任务缓存失败: %s', error && error.message ? error.message : error); - } - } - - /** - * 读取导出任务进度缓存。 - * @param {string} taskId 任务ID - * @return {Promise} 任务缓存 - */ - async getExportTaskProgress(taskId = '') { - const cacheKey = this.getExportTaskCacheKey(taskId); - if (!cacheKey || typeof this.app.getCacheAsync !== 'function') { - return null; - } - - try { - const cached = await this.app.getCacheAsync(cacheKey); - if (!this.isPlainObject(cached)) { - return null; - } - return cached; - } catch (error) { - this.ctx.logger.warn('[storage.report.export] 读取导出任务缓存失败: %s', error && error.message ? error.message : error); - return null; - } - } -} - -module.exports = StorageReportMethodService; diff --git a/app/service/systems/storage/entry.js b/app/service/systems/storage/entry.js index 1aaac08..802ffd7 100644 --- a/app/service/systems/storage/entry.js +++ b/app/service/systems/storage/entry.js @@ -245,9 +245,10 @@ class EntryService extends Service { * @param {Object} where 筛选条件对象 * @param {Object} pageParams 分页参数 * @param {Object} sortParams 排序参数 + * @param {string} [mode='warehouse'] 查询模式:warehouse=仓库侧(按 warehouse_id 过滤),store=货主侧(按 store_id 过滤) * @return {Promise} code/data/message 结构 */ - async list(where = {}, pageParams = {}, sortParams = {}) { + async list(where = {}, pageParams = {}, sortParams = {}, mode = 'warehouse') { const { ctx, app } = this; const { Sequelize } = app; const { Op } = Sequelize; @@ -268,11 +269,39 @@ class EntryService extends Service { ]; const actualSortField = validSortFields.includes(sortField) ? sortField : 'created_at'; - const baseWhere = { - warehouse_id: ctx.user.store_id, - is_enabled: 1, - deleted_at: null, - }; + const isStoreMode = String(mode).toLowerCase() === 'store'; + // 参考 stock.report.search:从 ctx.user.store_id 提取主维度 ID, + // Number(undefined)=NaN(falsy),防止 Sequelize 静默剔除 undefined 键导致过滤失效 + const rawPrimaryId = Number(ctx.user && ctx.user.store_id); + const storeId = isStoreMode ? rawPrimaryId : null; + const warehouseId = isStoreMode ? null : rawPrimaryId; + + if (isStoreMode && !storeId) { + return { + code: 400, + message: '用户未绑定货主,无法查询货主侧入库单', + data: { + list: [], + pagination: { page, pageSize, total: 0, totalPages: 0, hasPrevious: false, hasNext: false }, + summary: { total: 0, pending: 0, creating: 0, created: 0, completed: 0, cancelled: 0 }, + }, + }; + } + if (!isStoreMode && !warehouseId) { + return { + code: 400, + message: '用户未绑定仓库,无法查询入库单', + data: { + list: [], + pagination: { page, pageSize, total: 0, totalPages: 0, hasPrevious: false, hasNext: false }, + summary: { total: 0, pending: 0, creating: 0, created: 0, completed: 0, cancelled: 0 }, + }, + }; + } + + const baseWhere = isStoreMode + ? { store_id: storeId, is_enabled: 1, deleted_at: null } + : { warehouse_id: warehouseId, is_enabled: 1, deleted_at: null }; const normalizedWhere = ctx.where && typeof ctx.where === 'object' ? { ...ctx.where } @@ -506,22 +535,18 @@ class EntryService extends Service { }; } - /** - * 查询入库单详情。 - * @param {Object} data 请求体 - * @return {Promise} code/data/message 结构 - */ /** * 查询入库单详情(与原 storage.directInbound.getItems 输出格式一致)。 * 返回入库单基本信息、商品明细(含计划数量与已完成数量)、收货单绑定关系。 * @param {Object} data 请求参数 * @param {number} data.id 入库单主键 ID(必填) + * @param {string} [mode='warehouse'] 查询维度:'warehouse' 按仓库校验权限(默认),'store' 按货主校验权限 * @return {Promise} code/data/message 结构 * - data.entryOrder: { id, entry_order_code, order_status, store_remask } * - data.items: [{ id, stock_id, planned, completed, stock, bindings }] * - data.receivingBindings: [{ id, receiving_id, receiving }] */ - async get(data = {}) { + async get(data = {}, mode = 'warehouse') { const { ctx, app } = this; const id = Number(data.id || 0); @@ -564,9 +589,18 @@ class EntryService extends Service { return { code: 404, message: '入库单不存在', data: null }; } - // 校验仓库权限 - if (entryOrder.warehouse_id !== ctx.user.store_id || !entryOrder.is_enabled) { - return { code: 404, message: '入库单不存在或无权访问', data: null }; + const isStoreMode = String(mode).toLowerCase() === 'store'; + const rawPrimaryId = Number(ctx.user && ctx.user.store_id); + + // 校验权限:仓库模式校验 warehouse_id,货主模式校验 store_id + if (isStoreMode) { + if (entryOrder.store_id !== rawPrimaryId || !entryOrder.is_enabled) { + return { code: 404, message: '入库单不存在或无权访问', data: null }; + } + } else { + if (entryOrder.warehouse_id !== rawPrimaryId || !entryOrder.is_enabled) { + return { code: 404, message: '入库单不存在或无权访问', data: null }; + } } // 查询货主商家备注 @@ -627,8 +661,9 @@ class EntryService extends Service { /** @type {Map} */ const stockMap = new Map(); if (stockIds.length > 0) { - const warehouseId = ctx.user.store_id; - const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(stockIds, { warehouseId }); + // 货主模式下传 null 跳过 warehouse 过滤,避免 store_id 误当 warehouse_id 导致查不到商品 + const stockWarehouseId = isStoreMode ? null : rawPrimaryId; + const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(stockIds, { warehouseId: stockWarehouseId }); for (const detail of stockDetails) { stockMap.set(detail.id, detail); } diff --git a/methods/changes/system.json b/methods/changes/system.json index d76f756..1507737 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,25 @@ [ + { + "version": "2026.07.10-system-01", + "date": "2026-07-10", + "type": "added", + "summary": "新增 storage.report.searchStore 货主侧库存报表,以 store_id 为主维度查询库存流水", + "methods": [ + "storage.report.searchStore", + "storage.report.exportStore" + ], + "notes": [ + "新增 searchStore 方法:与 search 共享核心逻辑,通过 searchMode='store' 切换主维度从 warehouse_id → store_id。", + "新增 exportStore 方法:与 export 共享核心逻辑,支持货主侧导出 Excel(含汇总 + 变更记录两个 sheet)。", + "systems 层 search/export 方法新增 searchMode 参数(默认 'warehouse'),不影响现有 warehouse 侧行为。", + "货主侧使用 ctx.user.store_id 作为主维度 store_id,辅助维度支持 warehouse_ids 过滤特定仓库。", + "systemMethods 层 searchStore 从 where.warehouse_ids 取值传给 search 的 storeIds(承载 warehouse 过滤)。", + "输出新增 warehouse_id / warehouse_name 字段,货主侧可区分不同仓库的库存。search 方法也同步输出这两个字段(向后兼容)。", + "修复 getStockDetails 的 warehouseId 判断:从 != null 改为 !== undefined,使显式传 null 可跳过 warehouse 过滤。", + "修复 loadReportReferenceMaps 未传递 warehouseId 给 getStockDetails 的问题。" + ], + "module": "storage.report" + }, { "version": "2026.07.09-system-01", "date": "2026-07-09", @@ -4859,5 +4880,37 @@ "备注修改功能已独立为 order.pendingOrder.updateRemark 方法。" ], "module": "order.pendingOrder" + }, + { + "version": "2026-07-16", + "date": "2026-07-16", + "summary": "新增 workbench.bindCamera 接口,支持工作台绑定/解绑摄像头", + "methods": [ + "workbench.bindCamera" + ], + "notes": [ + "通过 device_ids JSON 字段存储绑定关系", + "传空数组可解绑" + ] + }, + { + "version": "2026.07.17-stock-report-migration-01", + "date": "2026-07-17", + "type": "updated", + "summary": "storage.report 模块迁移至 stock.report:修正语义错误,库存报表属于 stock 域而非 storage 域", + "methods": [ + "stock.report.search", + "stock.report.searchStore", + "stock.report.export", + "stock.report.exportStore", + "stock.report.exportTaskProgress" + ], + "notes": [ + "将 systemMethods/storage/report.js 移动到 systemMethods/stock/report.js", + "内部引用同步更新:类名 StorageReportMethodService→StockReportMethodService,缓存键 storage_report→stock_report,日志前缀 [storage.report]→[stock.report]", + "旧文件直接删除,不保留兼容(storage.report 为语义错误,调用方需同步更新 method 名)", + "更新 systems/storage/entry.js L273 注释引用", + "文档:methods/system.json module storage.report→stock.report,5个 method 名同步更新" + ] } ] diff --git a/methods/system.json b/methods/system.json index f89c195..8a4710d 100644 --- a/methods/system.json +++ b/methods/system.json @@ -2,7 +2,7 @@ "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", "version": "0.3.6", - "updatedAt": "2026-07-03", + "updatedAt": "2026-07-17", "headers": [ { "name": "platform", @@ -451,6 +451,23 @@ "response": [], "errors": [] }, + { + "method": "index.loadWarehouses", + "description": "index.loadWarehouses 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, { "method": "index.getCOSUploadConfig", "description": "index.getCOSUploadConfig 接口", @@ -15169,6 +15186,45 @@ "response": [], "errors": [] }, + { + "method": "stock.warehouse.externalList", + "description": "外仓商品列表查询。传入 warehouse_id 按仓库维度查,不传则按当前货主维度查(store_id);where/分页语义与 stock.warehouse.list 一致;where.keyword 支持模糊搜索(item_code/item_name/goods_code)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "warehouse_id", + "type": "number", + "required": false, + "source": "body", + "description": "仓库ID(可选,不传则取当前用户上下文)" + }, + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数,与 stock.warehouse.list 一致" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "统一 where 条件对象,与 stock.warehouse.list 语义一致。支持 keyword 快捷搜索:where.keyword={operator:like,value:'关键字'}" + } + ], + "response": [], + "errors": [] + }, { "method": "stock.warehouse.export", "description": "提交导出任务,返回 task_id/status/progress/message/result/error/update_time", @@ -18526,6 +18582,73 @@ } ] }, + { + "method": "storage.receiving.getStoreReceivingList", + "description": "货主侧收货单列表查询,以当前平台激活的货主 store_id 为维度查询收货单,支持分页和多条件筛选。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数,支持 page/pageSize" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "统一 where 条件对象;支持 quickWhere、status、warehouse_id、日期区间等字段。" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数,支持 sortField/sortOrder" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "收货单列表" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息(page、pageSize、total、totalPages、hasPrevious、hasNext)" + }, + { + "name": "summary", + "type": "object", + "required": true, + "description": "汇总信息(total_quantity、total_locked、total_available、total_items)" + } + ], + "errors": [ + { + "code": "500", + "message": "查询失败" + }, + { + "code": "0", + "message": "未获取到货主平台激活上下文,请先切换至货主角色" + } + ] + }, { "method": "storage.receiving.getReceivingDetail", "description": "storage.receiving.getReceivingDetail 接口", @@ -19860,6 +19983,87 @@ } ] }, + { + "method": "storage.entry.listStore", + "description": "货主侧入库单列表查询:以货主维度(store_id)过滤入库单,货主登录后仅能查看自己货主下的入库单。与 storage.entry.list 共享底层逻辑,但主维度为 store_id 而非 warehouse_id。where.order_status 支持 CREATING/CREATED/PENDING/COMPLETED/CANCELLED。CREATED=已创建待审核(需审核后才能绑定和完成入库),PENDING=已审核(可绑定和完成入库)。where 新增 hasReceiving 虚拟筛选字段,传 true/false 筛选已绑定/未绑定收货单的入库单。quickWhere 支持模糊搜索:entry_order_code(入库单号)、purchase_order_code(采购单号)、supplier_name(供应商名称)、store_name(货主名称)、warehouse_name(仓库名称)、receiving_id(收货单 ID / 托盘唛头)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数,支持 page/pageSize" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会在 main 中自动标准化;支持 quickWhere、order_status(CREATING/CREATED/PENDING/COMPLETED/CANCELLED)、order_type、日期区间等字段。新增 expense_record(费用是否记录)筛选,支持 eq/in。新增 hasReceiving 虚拟筛选字段,传 true/false 筛选已绑定/未绑定收货单的入库单。quickWhere 模糊搜索范围:entry_order_code(入库单号)、purchase_order_code(采购单号)、supplier_name(供应商名称)、store_name(货主名称)、warehouse_name(仓库名称)、receiving_id(收货单 ID / 托盘唛头)。" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数,支持 sortField/sortOrder" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "入库单列表" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息(page、pageSize、total、totalPages、hasPrevious、hasNext)" + }, + { + "name": "summary", + "type": "object", + "required": true, + "description": "状态汇总(total、pending、creating、created、completed、cancelled)" + }, + { + "name": "list[].receivingBindings", + "type": "array", + "required": false, + "description": "收货单绑定列表(主表级关联),每项含 id、entry_order_id、receiving_id 及 receiving 对象(id、receiving_number、status、storage_status、created_at)" + }, + { + "name": "list[].hasReceiving", + "type": "boolean", + "required": false, + "description": "是否存在收货单绑定" + } + ], + "errors": [ + { + "code": "400", + "message": "筛选条件格式错误", + "description": "筛选条件格式错误" + }, + { + "code": "500", + "message": "查询失败", + "description": "查询失败" + } + ] + }, { "method": "storage.entry.get", "description": "查询入库单详情。通过入库单 ID 定位,关联 Store、EntryItems、EntryOrderReceiving→Receiving,并通过仓库商品详情、直接入库进度、收货单可用明细进行数据合并。entryOrder.order_status 可能为 CREATING/CREATED/PENDING/COMPLETED/CANCELLED。CREATED=已创建待审核(需审核后才能绑定和完成入库),PENDING=已审核(可绑定和完成入库)。", @@ -20019,6 +20223,59 @@ } ] }, + { + "method": "storage.entry.getStore", + "description": "货主侧查询入库单详情。与 get 共享底层逻辑,但以货主维度(store_id)校验权限(不使用 warehouse_id),货主登录后仅能查看自己货主下的入库单明细。返回结构与 get 一致。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "入库单ID(必填)" + } + ], + "response": [ + { + "name": "entryOrder", + "type": "object", + "required": true, + "description": "入库单基本信息(id、entry_order_code、order_status、store_remask)" + }, + { + "name": "items", + "type": "array", + "required": true, + "description": "商品明细列表,每项含 id、stock_id、planned、completed、stock(商品详情)、bindings(库位绑定信息)" + }, + { + "name": "receivingBindings", + "type": "array", + "required": false, + "description": "主表级收货单关联数组,每项含 id / receiving_id / receiving(receiving 含 id / receiving_number / status / storage_status / created_at)" + } + ], + "errors": [ + { + "code": "400", + "message": "id 参数不能为空" + }, + { + "code": "404", + "message": "入库单不存在或无权访问" + } + ] + }, { "method": "storage.entry.cancel", "description": "作废入库单(支持单条或批量作废)。CREATED(已创建待审核)和 PENDING(已审核)状态的入库单可以直接作废;已完成(COMPLETED)入库单不允许作废。", @@ -21735,10 +21992,10 @@ }, { "groupName": "库存报表模块", - "module": "storage.report", + "module": "stock.report", "list": [ { - "method": "storage.report.search", + "method": "stock.report.search", "description": "库存报表查询(主入口):按时间闭区间统计商品出入库并支持按库位或按商品聚合", "isNeedAuth": false, "isNeedLogin": true, @@ -21756,7 +22013,7 @@ "type": "object", "required": false, "source": "body", - "description": "查询条件对象。支持字段:start_time(闭区间下限)、end_time(闭区间上限)、by_space(是否按库位返回,默认 false)、store_ids(货主ID数组)。仅返回在时间区间内存在流水的数据(无流水键不返回)。" + "description": "查询条件对象。支持字段:start_time(闭区间下限)、end_time(闭区间上限)、by_space(是否按库位返回,默认 false)、store_ids(货主ID数组)、stock_id(商品库存ID,单数)、stock_ids(商品库存ID数组)、keyword(商品关键字模糊匹配,支持 SKU ID/item_code/item_name/goods_code/barcode)。仅返回在时间区间内存在流水的数据(无流水键不返回)。" }, { "name": "where.start_time", @@ -21787,6 +22044,28 @@ "description": "货主ID数组,用于过滤特定货主(空或未传表示不过滤)", "list": [] }, + { + "name": "where.stock_id", + "type": "number", + "required": false, + "source": "body", + "description": "商品库存ID(单数),精确过滤指定商品;与 stock_ids 二选一,与 keyword 互斥" + }, + { + "name": "where.stock_ids", + "type": "array", + "required": false, + "source": "body", + "description": "商品库存ID数组,精确过滤指定商品列表;与 stock_id 二选一,与 keyword 互斥", + "list": [] + }, + { + "name": "where.keyword", + "type": "string", + "required": false, + "source": "body", + "description": "商品关键字,支持按 SKU ID(纯数字精确匹配)、商品编码(item_code)、商品名称(item_name)、货物编码(goods_code)、条码(barcode)模糊匹配;与 stock_id / stock_ids 互斥" + }, { "name": "sort", "type": "object", @@ -21950,8 +22229,224 @@ ] }, { - "method": "storage.report.export", - "description": "提交库存报表导出异步任务(与 storage.report.search 使用相同查询条件),立即返回任务受理信息,不直接返回文件。", + "method": "stock.report.searchStore", + "description": "货主侧库存报表查询:以货主维度统计商品出入库(入库和订单出库),不涉及库位维度。与 search 共享核心逻辑,但主维度为 store_id。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "查询条件对象。支持字段:start_time(闭区间下限)、end_time(闭区间上限)、warehouse_ids(仓库ID数组,可选过滤)、stock_id(商品库存ID,单数)、stock_ids(商品库存ID数组)、keyword(商品关键字模糊匹配,支持 SKU ID/item_code/item_name/goods_code/barcode)。仅返回在时间区间内存在流水的数据。" + }, + { + "name": "where.start_time", + "type": "string", + "required": false, + "source": "body", + "description": "开始时间,支持字符串/Date;用于闭区间过滤:created_at >= start_time" + }, + { + "name": "where.end_time", + "type": "string", + "required": false, + "source": "body", + "description": "结束时间,支持字符串/Date;用于闭区间过滤:created_at <= end_time" + }, + { + "name": "where.warehouse_ids", + "type": "array", + "required": false, + "source": "body", + "description": "仓库ID数组,用于过滤特定仓库(空或未传表示不过滤)", + "list": [] + }, + { + "name": "where.stock_id", + "type": "number", + "required": false, + "source": "body", + "description": "商品库存ID(单数),精确过滤指定商品;与 stock_ids 二选一,与 keyword 互斥" + }, + { + "name": "where.stock_ids", + "type": "array", + "required": false, + "source": "body", + "description": "商品库存ID数组,精确过滤指定商品列表;与 stock_id 二选一,与 keyword 互斥", + "list": [] + }, + { + "name": "where.keyword", + "type": "string", + "required": false, + "source": "body", + "description": "商品关键字,支持按 SKU ID(纯数字精确匹配)、商品编码(item_code)、商品名称(item_name)、货物编码(goods_code)、条码(barcode)模糊匹配;与 stock_id / stock_ids 互斥" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数对象。支持 data.sort.sortField / data.sort.sort_field 与 data.sort.sortOrder / data.sort.sort_order;sortField 白名单:begin_total、inbound_total、outbound_total、end_total;sortOrder 支持 ASC / DESC。" + }, + { + "name": "sort.sortField", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序字段(兼容 data.sort.sortField)。白名单:begin_total、inbound_total、outbound_total、end_total。" + }, + { + "name": "sort.sort_field", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序字段下划线别名(兼容 data.sort.sort_field),规则同 sort.sortField。" + }, + { + "name": "sort.sortOrder", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序方向(兼容 data.sort.sortOrder),支持 ASC / DESC(大小写不敏感)。" + }, + { + "name": "sort.sort_order", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序方向下划线别名(兼容 data.sort.sort_order),规则同 sort.sortOrder。" + } + ], + "response": [ + { + "name": "data.list", + "type": "array", + "required": true, + "description": "匹配到的报表行列表,已按 sort 规则排序返回。" + }, + { + "name": "data.list[]", + "type": "object", + "required": true, + "description": "单条报表记录字段", + "children": [ + { + "name": "start_time", + "type": "string", + "description": "请求时传入的 start_time(或 null)" + }, + { + "name": "end_time", + "type": "string", + "description": "请求时传入的 end_time(或 null)" + }, + { + "name": "stock_id", + "type": "integer", + "description": "库存商品ID(wms_stock_warehouse.id)" + }, + { + "name": "store_id", + "type": "integer", + "description": "货主ID" + }, + { + "name": "warehouse_id", + "type": "integer", + "description": "仓库ID" + }, + { + "name": "store_name", + "type": "string", + "description": "货主名称" + }, + { + "name": "warehouse_name", + "type": "string", + "description": "仓库名称" + }, + { + "name": "item_name", + "type": "string", + "description": "商品名称" + }, + { + "name": "item_code", + "type": "string", + "description": "商品编码" + }, + { + "name": "barcode", + "type": "string", + "description": "条码" + }, + { + "name": "begin_total", + "type": "number", + "description": "期初库存" + }, + { + "name": "inbound_total", + "type": "number", + "description": "入库总量" + }, + { + "name": "outbound_total", + "type": "number", + "description": "出库总量" + }, + { + "name": "end_total", + "type": "number", + "description": "期末库存" + }, + { + "name": "space_id", + "type": "integer", + "description": "库位ID(where.by_space=true 时返回)" + }, + { + "name": "space_name", + "type": "string", + "description": "库位名称(where.by_space=true 时返回)" + } + ] + } + ], + "errors": [ + { + "code": 400, + "message": "start_time 不合法" + }, + { + "code": 400, + "message": "end_time 不合法" + }, + { + "code": 400, + "message": "start_time 不能大于 end_time" + }, + { + "code": 400, + "message": "用户未绑定货主" + } + ] + }, + { + "method": "stock.report.export", + "description": "提交库存报表导出异步任务(与 stock.report.search 使用相同查询条件),立即返回任务受理信息,不直接返回文件。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -22095,7 +22590,147 @@ ] }, { - "method": "storage.report.exportTaskProgress", + "method": "stock.report.exportStore", + "description": "货主侧提交库存报表导出异步任务(与 stock.report.searchStore 使用相同查询条件),立即返回任务受理信息,不直接返回文件。可通过 stock.report.exportTaskProgress 查询进度。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "查询条件对象。支持字段:start_time、end_time、warehouse_ids。" + }, + { + "name": "where.start_time", + "type": "string", + "required": false, + "source": "body", + "description": "开始时间" + }, + { + "name": "where.end_time", + "type": "string", + "required": false, + "source": "body", + "description": "结束时间" + }, + { + "name": "where.warehouse_ids", + "type": "array", + "required": false, + "source": "body", + "description": "仓库ID数组,用于过滤特定仓库", + "list": [] + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数" + }, + { + "name": "sort.sortField", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序字段" + }, + { + "name": "sort.sort_field", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序字段下划线别名" + }, + { + "name": "sort.sortOrder", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序方向" + }, + { + "name": "sort.sort_order", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序方向下划线别名" + }, + { + "name": "export_mode", + "type": "string", + "required": false, + "source": "body", + "description": "导出模式:'item' 导出含锁定类型的全部变更记录" + }, + { + "name": "exportMode", + "type": "string", + "required": false, + "source": "body", + "description": "导出模式(驼峰写法,同 export_mode)" + } + ], + "response": [ + { + "name": "data.task_id", + "type": "string", + "required": true, + "description": "导出异步任务ID,用于后续查询进度" + }, + { + "name": "data.status", + "type": "string", + "required": true, + "description": "任务受理状态:submitted" + }, + { + "name": "data.progress", + "type": "number", + "required": true, + "description": "任务进度:0" + }, + { + "name": "data.message", + "type": "string", + "required": true, + "description": "任务受理消息" + }, + { + "name": "data.update_time", + "type": "number", + "required": true, + "description": "任务更新时间戳(ms)" + } + ], + "errors": [ + { + "code": 400, + "message": "start_time 不合法" + }, + { + "code": 400, + "message": "end_time 不合法" + }, + { + "code": 400, + "message": "start_time 不能大于 end_time" + } + ] + }, + { + "method": "stock.report.exportTaskProgress", "description": "根据 task_id 查询库存报表导出任务进度与结果;status 可能值:submitted/running/success/failed/not_found。", "isNeedAuth": false, "isNeedLogin": true, @@ -26736,6 +27371,961 @@ ] } ] + }, + { + "groupName": "工作台模块", + "module": "workbench", + "list": [ + { + "method": "workbench.list", + "description": "查询工作台列表(仓库隔离,支持分页与关键词筛选)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数,支持 page / pageSize" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "筛选条件,支持 name(模糊)、barcode(模糊)、status(等值)" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "工作台列表", + "children": [ + { + "name": "id", + "type": "number", + "description": "工作台ID" + }, + { + "name": "warehouse_id", + "type": "number", + "description": "仓库ID" + }, + { + "name": "name", + "type": "string", + "description": "工作台名称" + }, + { + "name": "barcode", + "type": "string", + "description": "工作台条码" + }, + { + "name": "status", + "type": "number", + "description": "状态:0-禁用 1-启用" + }, + { + "name": "remark", + "type": "string", + "description": "备注" + }, + { + "name": "created_at", + "type": "string", + "description": "创建时间" + }, + { + "name": "updated_at", + "type": "string", + "description": "更新时间" + } + ] + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息" + } + ], + "errors": [ + { + "code": "400", + "description": "参数格式错误或缺少仓库上下文" + } + ] + }, + { + "method": "workbench.detail", + "description": "查询单个工作台详情(仓库隔离)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "工作台ID" + } + ], + "response": [ + { + "name": "data", + "type": "object", + "required": true, + "description": "工作台详情对象" + } + ], + "errors": [ + { + "code": "400", + "description": "工作台ID不能为空" + }, + { + "code": "404", + "description": "工作台不存在或无权访问" + } + ] + }, + { + "method": "workbench.create", + "description": "新增工作台(仓库隔离,条码仓库内唯一)", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "name", + "type": "string", + "required": true, + "source": "body", + "description": "工作台名称(必填)" + }, + { + "name": "barcode", + "type": "string", + "required": false, + "source": "body", + "description": "工作台条码(可选,仓库内唯一)" + }, + { + "name": "status", + "type": "number", + "required": false, + "source": "body", + "description": "状态:0-禁用 1-启用,默认1" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注" + } + ], + "response": [ + { + "name": "data", + "type": "object", + "required": true, + "description": "新建的工作台对象" + } + ], + "errors": [ + { + "code": "400", + "description": "工作台名称不能为空" + }, + { + "code": "400", + "description": "条码已存在(仓库内唯一约束)" + } + ] + }, + { + "method": "workbench.update", + "description": "更新工作台信息(仓库隔离)", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "工作台ID(必填)" + }, + { + "name": "name", + "type": "string", + "required": false, + "source": "body", + "description": "工作台名称" + }, + { + "name": "barcode", + "type": "string", + "required": false, + "source": "body", + "description": "工作台条码" + }, + { + "name": "status", + "type": "number", + "required": false, + "source": "body", + "description": "状态:0-禁用 1-启用" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注" + } + ], + "response": [ + { + "name": "data", + "type": "object", + "required": true, + "description": "更新后的工作台对象" + } + ], + "errors": [ + { + "code": "400", + "description": "工作台ID不能为空" + }, + { + "code": "404", + "description": "工作台不存在或无权操作" + } + ] + }, + { + "method": "workbench.delete", + "description": "删除工作台(软删除,仓库隔离)", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "工作台ID(必填)" + } + ], + "response": [], + "errors": [ + { + "code": "400", + "description": "工作台ID不能为空" + }, + { + "code": "404", + "description": "工作台不存在或无权操作" + } + ] + }, + { + "method": "workbench.checkBarcode", + "description": "检查条码在仓库内是否已存在", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "barcode", + "type": "string", + "required": true, + "source": "body", + "description": "条码(必填)" + }, + { + "name": "excludeId", + "type": "number", + "required": false, + "source": "body", + "description": "排除的工作台ID(更新时避免自身冲突)" + } + ], + "response": [ + { + "name": "exists", + "type": "boolean", + "required": true, + "description": "是否存在:true=已存在 false=可用" + } + ], + "errors": [ + { + "code": "400", + "description": "条码不能为空" + } + ] + }, + { + "method": "workbench.business", + "description": "工作台业务入口(免登录免鉴权,入参 name + data,业务逻辑待实现)", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "name", + "type": "string", + "required": true, + "source": "body", + "description": "业务名称(用于分发具体逻辑)" + }, + { + "name": "data", + "type": "object", + "required": false, + "source": "body", + "description": "业务数据(透传)" + } + ], + "response": [ + { + "name": "name", + "type": "string", + "required": true, + "description": "回显业务名称" + }, + { + "name": "received", + "type": "boolean", + "required": true, + "description": "是否已接收" + } + ], + "errors": [] + }, + { + "method": "workbench.bindCamera", + "description": "工作台绑定/解绑摄像头,校验工作台与摄像头归属后更新 device_ids", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "工作台ID" + }, + { + "name": "camera_ids", + "type": "array", + "required": false, + "source": "body", + "description": "摄像头ID数组,传空数组或 null 表示解绑所有摄像头" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "工作台ID" + }, + { + "name": "name", + "type": "string", + "required": true, + "description": "工作台名称" + }, + { + "name": "device_ids", + "type": "array", + "required": false, + "description": "绑定后的摄像头ID列表" + } + ], + "errors": [ + { + "code": "400", + "message": "工作台ID不能为空" + }, + { + "code": "400", + "message": "摄像头 xxx 不存在或无权操作" + }, + { + "code": "404", + "message": "工作台不存在或无权操作" + } + ] + } + ] + }, + { + "groupName": "录像服务器模块", + "module": "camera_server", + "list": [ + { + "method": "camera_server.list", + "description": "录像服务器列表(仓库隔离,分页+筛选)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数 page/pageSize" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "筛选:name(模糊)、status(等值)" + } + ], + "response": [], + "errors": [] + }, + { + "method": "camera_server.detail", + "description": "录像服务器详情", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "服务器ID" + } + ], + "response": [], + "errors": [ + { + "code": "404", + "description": "不存在或无权访问" + } + ] + }, + { + "method": "camera_server.create", + "description": "新增录像服务器", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "name", + "type": "string", + "required": true, + "source": "body", + "description": "服务器名称(必填)" + }, + { + "name": "brand", + "type": "string", + "required": false, + "source": "body", + "description": "品牌" + }, + { + "name": "public_ip", + "type": "string", + "required": false, + "source": "body", + "description": "公网IP" + }, + { + "name": "internal_ip", + "type": "string", + "required": false, + "source": "body", + "description": "内网IP" + }, + { + "name": "port", + "type": "number", + "required": false, + "source": "body", + "description": "端口号" + }, + { + "name": "username", + "type": "string", + "required": false, + "source": "body", + "description": "账号" + }, + { + "name": "password", + "type": "string", + "required": false, + "source": "body", + "description": "密码" + }, + { + "name": "status", + "type": "number", + "required": false, + "source": "body", + "description": "0-禁用 1-启用" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注" + } + ], + "response": [], + "errors": [ + { + "code": "400", + "description": "名称不能为空" + } + ] + }, + { + "method": "camera_server.update", + "description": "更新录像服务器", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "服务器ID(必填)" + }, + { + "name": "name", + "type": "string", + "required": false, + "source": "body", + "description": "名称" + }, + { + "name": "brand", + "type": "string", + "required": false, + "source": "body", + "description": "品牌" + }, + { + "name": "public_ip", + "type": "string", + "required": false, + "source": "body", + "description": "公网IP" + }, + { + "name": "internal_ip", + "type": "string", + "required": false, + "source": "body", + "description": "内网IP" + }, + { + "name": "port", + "type": "number", + "required": false, + "source": "body", + "description": "端口号" + }, + { + "name": "username", + "type": "string", + "required": false, + "source": "body", + "description": "账号" + }, + { + "name": "password", + "type": "string", + "required": false, + "source": "body", + "description": "密码" + }, + { + "name": "status", + "type": "number", + "required": false, + "source": "body", + "description": "0-禁用 1-启用" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注" + } + ], + "response": [], + "errors": [ + { + "code": "404", + "description": "不存在或无权操作" + } + ] + }, + { + "method": "camera_server.delete", + "description": "删除录像服务器(软删除)", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "服务器ID" + } + ], + "response": [], + "errors": [ + { + "code": "404", + "description": "不存在或无权操作" + } + ] + } + ] + }, + { + "groupName": "摄像头模块", + "module": "camera", + "list": [ + { + "method": "camera.list", + "description": "摄像头列表(仓库隔离,分页+筛选)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数 page/pageSize" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "筛选:server_id(等值)、custom_name(模糊)、status(等值)" + } + ], + "response": [], + "errors": [] + }, + { + "method": "camera.detail", + "description": "摄像头详情", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "摄像头ID" + } + ], + "response": [], + "errors": [ + { + "code": "404", + "description": "不存在或无权访问" + } + ] + }, + { + "method": "camera.create", + "description": "新增摄像头", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "server_id", + "type": "number", + "required": true, + "source": "body", + "description": "所属服务器ID(必填)" + }, + { + "name": "channel_id", + "type": "number", + "required": true, + "source": "body", + "description": "通道编号(必填)" + }, + { + "name": "channel_name", + "type": "string", + "required": false, + "source": "body", + "description": "通道名称" + }, + { + "name": "custom_name", + "type": "string", + "required": false, + "source": "body", + "description": "自定义名称" + }, + { + "name": "status", + "type": "number", + "required": false, + "source": "body", + "description": "0-禁用 1-启用" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注" + } + ], + "response": [], + "errors": [ + { + "code": "400", + "description": "server_id/channel_id 不能为空" + } + ] + }, + { + "method": "camera.update", + "description": "更新摄像头", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "摄像头ID(必填)" + }, + { + "name": "server_id", + "type": "number", + "required": false, + "source": "body", + "description": "所属服务器ID" + }, + { + "name": "channel_id", + "type": "number", + "required": false, + "source": "body", + "description": "通道编号" + }, + { + "name": "channel_name", + "type": "string", + "required": false, + "source": "body", + "description": "通道名称" + }, + { + "name": "custom_name", + "type": "string", + "required": false, + "source": "body", + "description": "自定义名称" + }, + { + "name": "status", + "type": "number", + "required": false, + "source": "body", + "description": "0-禁用 1-启用" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注" + } + ], + "response": [], + "errors": [ + { + "code": "404", + "description": "不存在或无权操作" + } + ] + }, + { + "method": "camera.delete", + "description": "删除摄像头(软删除)", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "摄像头ID" + } + ], + "response": [], + "errors": [ + { + "code": "404", + "description": "不存在或无权操作" + } + ] + } + ] } ] } From df8173cecd1cf8da2c26996e8d984af2dbb97631 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Fri, 17 Jul 2026 01:48:12 +0800 Subject: [PATCH 114/550] =?UTF-8?q?feat:=20=E6=96=B0=E5=A2=9E=20stock.tran?= =?UTF-8?q?saction=20=E5=95=86=E5=93=81=E6=B5=81=E6=B0=B4=E5=AF=BC?= =?UTF-8?q?=E5=87=BA=20+=20keyword=20=E5=95=86=E5=93=81=E6=90=9C=E7=B4=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - systems/stock_transaction.js: 新增 exportList() 异步导出 Excel(上限50000条) - 新增 _resolveKeywordToStockIds() 关键词→stock_id 解析 - queryList/exportList 支持 keyword 模糊搜索(按 item_code/item_name/goods_code/barcode/SKU ID) - systemMethods/stock/transaction.js: - 新增 export/exportStore/exportTaskProgress 异步导出方法 - list/storeList/export/exportStore 全部透传 keyword - storeList 新增 warehouse_id/stock_id 单数兼容 - methods/system.json + changes/system.json: 新增3个method文档 --- .../systemMethods/stock/transaction.js | 385 +++++++++++++++++- app/service/systems/stock_transaction.js | 326 ++++++++++++++- methods/changes/system.json | 17 + methods/system.json | 326 +++++++++++++++ 4 files changed, 1043 insertions(+), 11 deletions(-) diff --git a/app/service/systemMethods/stock/transaction.js b/app/service/systemMethods/stock/transaction.js index 287353f..f8c94e1 100644 --- a/app/service/systemMethods/stock/transaction.js +++ b/app/service/systemMethods/stock/transaction.js @@ -2,6 +2,9 @@ const MainService = require('../../main'); +const STOCK_TRANSACTION_EXPORT_TASK_CACHE_KEY_PREFIX = 'stock_transaction_export_task_'; +const STOCK_TRANSACTION_EXPORT_TASK_CACHE_TTL_SECONDS = 1800; + /** * 系统方法层:stock.transaction(商品出入库流水查询包装层)。 */ @@ -9,9 +12,9 @@ class StockTransactionMethodService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'list,storeList'; - const _noNeedLog = 'list,storeList'; - const _noNeedAuth = 'list,storeList'; + const _noNeedRight = 'list,storeList,export,exportStore,exportTaskProgress'; + const _noNeedLog = 'list,storeList,export,exportStore,exportTaskProgress'; + const _noNeedAuth = 'list,storeList,export,exportStore,exportTaskProgress'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -34,6 +37,7 @@ class StockTransactionMethodService extends MainService { end_time: endTime, store_ids: storeIds, stock_ids: stockIds, + keyword, transaction_type: transactionType, order_type: orderType, order_no: orderNo, @@ -62,6 +66,7 @@ class StockTransactionMethodService extends MainService { endTime, storeIds, stockIds, + keyword, transactionType, orderType, orderNo, @@ -71,6 +76,7 @@ class StockTransactionMethodService extends MainService { orderId, sort: sortOption, pagination, + mode: 'warehouse', }); return this.success('ok', result); @@ -98,8 +104,11 @@ class StockTransactionMethodService extends MainService { const { start_time: startTime, end_time: endTime, - warehouse_ids: warehouseIds, - stock_ids: stockIds, + warehouse_ids: warehouseIdsRaw, + warehouse_id: warehouseIdRaw, + stock_ids: stockIdsRaw, + stock_id: stockIdRaw, + keyword, transaction_type: transactionType, order_type: orderType, order_no: orderNo, @@ -109,6 +118,16 @@ class StockTransactionMethodService extends MainService { order_id: orderId, } = whereValue; + // 兼容 warehouse_id(单数)和 warehouse_ids(数组) + const warehouseIds = warehouseIdsRaw !== undefined + ? warehouseIdsRaw + : (warehouseIdRaw !== undefined ? [ warehouseIdRaw ] : undefined); + + // 兼容 stock_id(单数)和 stock_ids(数组) + const stockIds = stockIdsRaw !== undefined + ? stockIdsRaw + : (stockIdRaw !== undefined ? [ stockIdRaw ] : null); + const { sort = {} } = data; const { sort_field: sortFieldSnake, @@ -128,6 +147,7 @@ class StockTransactionMethodService extends MainService { endTime, warehouseIds, stockIds, + keyword, transactionType, orderType, orderNo, @@ -141,6 +161,361 @@ class StockTransactionMethodService extends MainService { return this.success('ok', result); } + + /** + * 仓库侧提交商品流水导出任务。 + * 与 list 使用相同查询条件,异步执行,立即返回任务ID。 + * @param {Object} data 请求体 + * @return {Promise} 统一 success 包装(返回任务ID) + */ + async export(data = {}) { + const { service } = this; + const warehouseId = Number(this.ctx.user && this.ctx.user.store_id); + const { whereValue = {} } = this.prepareWhereContext(data); + const { + start_time: startTime, + end_time: endTime, + store_ids: storeIds, + stock_ids: stockIds, + keyword, + transaction_type: transactionType, + order_type: orderType, + order_no: orderNo, + batch_no: batchNo, + entry_order_id: entryOrderId, + receiving_id: receivingId, + order_id: orderId, + } = whereValue; + + const { sort = {} } = data; + const sortOption = { + sortField: sort.sortField || sort.sort_field, + sortOrder: sort.sortOrder || sort.sort_order, + }; + + const taskId = this.generateExportTaskId(); + const taskPayload = { + task_id: taskId, + status: 'submitted', + progress: 0, + message: '导出任务已提交', + result: null, + error: '', + }; + + await this.setExportTaskProgress(taskId, taskPayload); + + setImmediate(async () => { + try { + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'running', + progress: 10, + message: '导出任务执行中', + result: null, + error: '', + }); + + const result = await service.systems.stockTransaction.exportList({ + warehouseId, + startTime, + endTime, + storeIds, + stockIds, + keyword, + transactionType, + orderType, + orderNo, + batchNo, + entryOrderId, + receivingId, + orderId, + sort: sortOption, + mode: 'warehouse', + }); + + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'success', + progress: 100, + message: '导出任务完成', + result, + error: '', + }); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'failed', + progress: 100, + message: '导出任务失败', + result: null, + error: errorMessage, + }); + } + }); + + return this.success('ok', { + ...taskPayload, + update_time: Date.now(), + }); + } + + /** + * 货主侧提交商品流水导出任务。 + * 与 storeList 使用相同查询条件,异步执行,立即返回任务ID。 + * @param {Object} data 请求体 + * @param {number} data.store_id 货主ID(必传) + * @return {Promise} 统一 success 包装(返回任务ID) + */ + async exportStore(data = {}) { + const { service } = this; + const storeId = Number(data.store_id); + if (!Number.isInteger(storeId) || storeId <= 0) { + return this.failure('store_id 不能为空'); + } + + const { whereValue = {} } = this.prepareWhereContext(data); + const { + start_time: startTime, + end_time: endTime, + warehouse_ids: warehouseIdsRaw, + warehouse_id: warehouseIdRaw, + stock_ids: stockIdsRaw, + stock_id: stockIdRaw, + keyword, + transaction_type: transactionType, + order_type: orderType, + order_no: orderNo, + batch_no: batchNo, + entry_order_id: entryOrderId, + receiving_id: receivingId, + order_id: orderId, + } = whereValue; + + const warehouseIds = warehouseIdsRaw !== undefined + ? warehouseIdsRaw + : (warehouseIdRaw !== undefined ? [ warehouseIdRaw ] : undefined); + + const stockIds = stockIdsRaw !== undefined + ? stockIdsRaw + : (stockIdRaw !== undefined ? [ stockIdRaw ] : null); + + const { sort = {} } = data; + const sortOption = { + sortField: sort.sortField || sort.sort_field, + sortOrder: sort.sortOrder || sort.sort_order, + }; + + const taskId = this.generateExportTaskId(); + const taskPayload = { + task_id: taskId, + status: 'submitted', + progress: 0, + message: '导出任务已提交', + result: null, + error: '', + }; + + await this.setExportTaskProgress(taskId, taskPayload); + + setImmediate(async () => { + try { + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'running', + progress: 10, + message: '导出任务执行中', + result: null, + error: '', + }); + + const result = await service.systems.stockTransaction.exportList({ + storeId, + startTime, + endTime, + warehouseIds, + stockIds, + keyword, + transactionType, + orderType, + orderNo, + batchNo, + entryOrderId, + receivingId, + orderId, + sort: sortOption, + mode: 'store', + }); + + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'success', + progress: 100, + message: '导出任务完成', + result, + error: '', + }); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'failed', + progress: 100, + message: '导出任务失败', + result: null, + error: errorMessage, + }); + } + }); + + return this.success('ok', { + ...taskPayload, + update_time: Date.now(), + }); + } + + /** + * 查询商品流水导出任务进度。 + * @param {Object} data 请求体 + * @param {string} [data.task_id] 任务ID(下划线写法) + * @param {string} [data.taskId] 任务ID(驼峰写法) + * @return {Promise} 统一 success 包装 + */ + async exportTaskProgress(data = {}) { + const taskId = this.normalizeExportTaskId(data); + if (!taskId) { + return this.success('ok', { + task_id: '', + status: 'not_found', + progress: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const cachedTask = await this.getExportTaskProgress(taskId); + if (!cachedTask) { + return this.success('ok', { + task_id: taskId, + status: 'not_found', + progress: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {}; + const downloadUrl = String( + safeResult.url + || safeResult.cndUrl + || safeResult.cosUrl + || safeResult.fileKey + || '' + ); + + return this.success('ok', { + task_id: taskId, + ...cachedTask, + download_url: downloadUrl, + }); + } + + /** + * 生成导出任务ID。 + * @return {string} 导出任务ID + */ + generateExportTaskId() { + const warehouseId = this.ctx?.user?.store_id || 'unknown'; + const timestamp = Date.now(); + const randomToken = Math.random().toString(36).slice(2, 10); + return `stock_transaction_export_${warehouseId}_${timestamp}_${randomToken}`; + } + + /** + * 规范导出任务ID。 + * @param {Object} data 请求体 + * @param {string} [data.task_id] 任务ID(下划线写法) + * @param {string} [data.taskId] 任务ID(驼峰写法) + * @return {string} 归一化后的任务ID + */ + normalizeExportTaskId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.task_id || normalizedData.taskId || '').trim(); + } + + /** + * 获取导出任务缓存键。 + * @param {string} taskId 任务ID + * @return {string} 缓存键 + */ + getExportTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + + return `${STOCK_TRANSACTION_EXPORT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 写入导出任务进度缓存。 + * @param {string} taskId 任务ID + * @param {Object} payload 任务状态载荷 + * @return {Promise} 无返回值 + */ + async setExportTaskProgress(taskId = '', payload = {}) { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.setCacheAsync !== 'function') { + return; + } + + const safePayload = this.isPlainObject(payload) ? payload : {}; + const progressPayload = { + task_id: String(taskId || '').trim(), + status: String(safePayload.status || 'submitted').trim() || 'submitted', + progress: Number.isFinite(Number(safePayload.progress)) ? Math.min(100, Math.max(0, Math.round(Number(safePayload.progress)))) : 0, + message: String(safePayload.message || ''), + result: safePayload.result ?? null, + error: String(safePayload.error || ''), + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync(cacheKey, progressPayload, STOCK_TRANSACTION_EXPORT_TASK_CACHE_TTL_SECONDS); + } catch (error) { + this.ctx.logger.warn('[stock.transaction.export] 写入导出任务缓存失败: %s', error && error.message ? error.message : error); + } + } + + /** + * 读取导出任务进度缓存。 + * @param {string} taskId 任务ID + * @return {Promise} 任务缓存 + */ + async getExportTaskProgress(taskId = '') { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.getCacheAsync !== 'function') { + return null; + } + + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (!this.isPlainObject(cached)) { + return null; + } + return cached; + } catch (error) { + this.ctx.logger.warn('[stock.transaction.export] 读取导出任务缓存失败: %s', error && error.message ? error.message : error); + return null; + } + } } module.exports = StockTransactionMethodService; diff --git a/app/service/systems/stock_transaction.js b/app/service/systems/stock_transaction.js index cd63af6..42186ad 100644 --- a/app/service/systems/stock_transaction.js +++ b/app/service/systems/stock_transaction.js @@ -308,6 +308,63 @@ class StockTransactionService extends Service { }; } + /** + * 根据关键字解析匹配的 stock_id 列表。 + * 支持按商品编码(item_code)、商品名称(item_name)、货物编码(goods_code)、条码(barcode)、SKU ID 模糊匹配。 + * @param {string} keyword 搜索关键字 + * @param {string} primaryDimCol 主维度列名(warehouse_id 或 store_id) + * @param {number} primaryDimVal 主维度值 + * @return {Promise} 匹配的 stock_id 列表 + */ + async _resolveKeywordToStockIds(keyword, primaryDimCol, primaryDimVal) { + const { ctx, app } = this; + const normalizedKeyword = String(keyword || '').trim(); + if (!normalizedKeyword) { + return []; + } + + const likePattern = `%${normalizedKeyword}%`; + const exactStockId = /^\d+$/.test(normalizedKeyword) ? Number(normalizedKeyword) : null; + const extraIdCondition = exactStockId !== null ? 'OR sw.id = :exactStockId' : ''; + + const stockRows = await ctx.model.query(` + SELECT DISTINCT sw.id AS stock_id + FROM wms_stock_warehouse sw + WHERE sw.${primaryDimCol} = :primaryDimVal + AND ( + sw.item_code LIKE :keyword + OR sw.item_name LIKE :keyword + OR sw.goods_code LIKE :keyword + ${extraIdCondition} + ) + `, { + replacements: { primaryDimVal, keyword: likePattern, exactStockId }, + type: app.Sequelize.QueryTypes.SELECT, + }); + + const barcodeRows = await ctx.model.query(` + SELECT DISTINCT sb.stock_id + FROM wms_stock_barcodes sb + INNER JOIN wms_stock_warehouse sw ON sw.id = sb.stock_id AND sw.${primaryDimCol} = :primaryDimVal + WHERE sb.barcode LIKE :keyword + `, { + replacements: { primaryDimVal, keyword: likePattern }, + type: app.Sequelize.QueryTypes.SELECT, + }); + + const stockIdSet = new Set(); + for (const row of stockRows) { + const sid = Number(row.stock_id); + if (sid > 0) stockIdSet.add(sid); + } + for (const row of barcodeRows) { + const sid = Number(row.stock_id); + if (sid > 0) stockIdSet.add(sid); + } + + return [ ...stockIdSet ]; + } + /** * 查询商品出入库流水列表(原始记录,不做聚合)。 * 仓库侧:按 warehouseId 限定;货主侧:按 storeId 限定。 @@ -319,6 +376,7 @@ class StockTransactionService extends Service { * @param {Array} [options.storeIds] 货主ID数组(仓库侧筛选) * @param {Array} [options.warehouseIds] 仓库ID数组(货主侧筛选) * @param {Array} [options.stockIds] 商品库存ID数组 + * @param {string} [options.keyword] 商品关键字(按 item_code/item_name/goods_code/barcode/SKU ID 模糊匹配) * @param {string} [options.transactionType] 流水类型 * @param {string} [options.orderType] 单据类型 * @param {string} [options.orderNo] 单据号 @@ -328,6 +386,7 @@ class StockTransactionService extends Service { * @param {number} [options.orderId] 发货单ID * @param {Object} [options.sort] 排序参数 * @param {Object} [options.pagination] 分页参数 + * @param {string} [options.mode] 模式 'warehouse'/'store',用于 keyword 解析时决定主维度 * @return {Promise} { list, pagination } */ async queryList(options = {}) { @@ -339,7 +398,8 @@ class StockTransactionService extends Service { endTime, storeIds, warehouseIds, - stockIds, + stockIds: rawStockIds, + keyword, transactionType, orderType, orderNo, @@ -349,8 +409,23 @@ class StockTransactionService extends Service { orderId, sort = {}, pagination = {}, + mode = 'warehouse', } = options; + // keyword 解析为 stock_ids + let resolvedStockIds = Array.isArray(rawStockIds) + ? rawStockIds.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0) + : []; + const normalizedKeyword = String(keyword || '').trim(); + if (normalizedKeyword && resolvedStockIds.length === 0) { + const isStoreMode = mode === 'store'; + const primaryDimCol = isStoreMode ? 'store_id' : 'warehouse_id'; + const primaryDimVal = isStoreMode ? Number(storeId) : Number(warehouseId); + if (primaryDimVal > 0) { + resolvedStockIds = await this._resolveKeywordToStockIds(normalizedKeyword, primaryDimCol, primaryDimVal); + } + } + const whereClauses = []; const replacements = {}; @@ -401,11 +476,7 @@ class StockTransactionService extends Service { } // 商品筛选 - const normalizedStockIds = Array.isArray(stockIds) - ? stockIds.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0) - : []; - if (normalizedStockIds.length > 0) { - whereClauses.push('t.stock_id IN (:stockIds)'); + const normalizedStockIds = resolvedStockIds; replacements.stockIds = normalizedStockIds; } @@ -552,6 +623,249 @@ class StockTransactionService extends Service { }, }; } + + /** + * 导出商品出入库流水列表为 Excel。 + * 与 queryList 使用相同的查询条件,但不分页(导出上限 50000 条)。 + * @param {Object} options 查询参数(与 queryList 一致,忽略 pagination) + * @param {string} [options.mode] 导出模式:'warehouse' 仓库侧 / 'store' 货主侧 + * @return {Promise} Excel 导出结果 { url, filename } + */ + async exportList(options = {}) { + const { ctx, app } = this; + const { + warehouseId, + storeId, + startTime, + endTime, + storeIds, + warehouseIds, + stockIds: rawStockIds, + keyword, + transactionType, + orderType, + orderNo, + batchNo, + entryOrderId, + receivingId, + orderId, + sort = {}, + mode = 'warehouse', + } = options; + + // keyword 解析为 stock_ids + let resolvedStockIds = Array.isArray(rawStockIds) + ? rawStockIds.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0) + : []; + const normalizedKeyword = String(keyword || '').trim(); + if (normalizedKeyword && resolvedStockIds.length === 0) { + const isStoreMode = mode === 'store'; + const primaryDimCol = isStoreMode ? 'store_id' : 'warehouse_id'; + const primaryDimVal = isStoreMode ? Number(storeId) : Number(warehouseId); + if (primaryDimVal > 0) { + resolvedStockIds = await this._resolveKeywordToStockIds(normalizedKeyword, primaryDimCol, primaryDimVal); + } + } + + const isStoreMode = mode === 'store'; + const whereClauses = []; + const replacements = {}; + + // 数据范围限定 + if (warehouseId !== undefined && warehouseId !== null) { + whereClauses.push('t.warehouse_id = :warehouseId'); + replacements.warehouseId = Number(warehouseId); + } + + if (storeId !== undefined && storeId !== null) { + whereClauses.push('t.store_id = :storeId'); + replacements.storeId = Number(storeId); + } + + if (startTime !== undefined && startTime !== null && startTime !== '') { + const startMs = new Date(startTime).getTime(); + if (!Number.isNaN(startMs)) { + whereClauses.push('t.created_at >= :startTime'); + replacements.startTime = startTime; + } + } + + if (endTime !== undefined && endTime !== null && endTime !== '') { + const endMs = new Date(endTime).getTime(); + if (!Number.isNaN(endMs)) { + whereClauses.push('t.created_at <= :endTime'); + replacements.endTime = endTime; + } + } + + const normalizedStoreIds = Array.isArray(storeIds) + ? storeIds.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0) + : []; + if (normalizedStoreIds.length > 0) { + whereClauses.push('t.store_id IN (:storeIds)'); + replacements.storeIds = normalizedStoreIds; + } + + const normalizedWarehouseIds = Array.isArray(warehouseIds) + ? warehouseIds.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0) + : []; + if (normalizedWarehouseIds.length > 0) { + whereClauses.push('t.warehouse_id IN (:warehouseIds)'); + replacements.warehouseIds = normalizedWarehouseIds; + } + + const normalizedStockIds = resolvedStockIds; + if (normalizedStockIds.length > 0) { + whereClauses.push('t.stock_id IN (:stockIds)'); + replacements.stockIds = normalizedStockIds; + } + + if (transactionType) { + whereClauses.push('t.transaction_type = :transactionType'); + replacements.transactionType = String(transactionType).trim(); + } + + if (orderType) { + whereClauses.push('t.order_type = :orderType'); + replacements.orderType = String(orderType).trim(); + } + + if (orderNo) { + whereClauses.push('t.order_no LIKE :orderNo'); + replacements.orderNo = `%${String(orderNo).trim()}%`; + } + + if (batchNo) { + whereClauses.push('t.batch_no = :batchNo'); + replacements.batchNo = String(batchNo).trim(); + } + + if (entryOrderId !== undefined && entryOrderId !== null) { + const eid = Number(entryOrderId); + if (Number.isInteger(eid) && eid > 0) { + whereClauses.push('t.entry_order_id = :entryOrderId'); + replacements.entryOrderId = eid; + } + } + + if (receivingId !== undefined && receivingId !== null) { + const rid = Number(receivingId); + if (Number.isInteger(rid) && rid > 0) { + whereClauses.push('t.receiving_id = :receivingId'); + replacements.receivingId = rid; + } + } + + if (orderId !== undefined && orderId !== null) { + const oid = Number(orderId); + if (Number.isInteger(oid) && oid > 0) { + whereClauses.push('t.order_id = :orderId'); + replacements.orderId = oid; + } + } + + const whereSQL = whereClauses.length > 0 + ? `WHERE ${whereClauses.join(' AND ')}` + : ''; + + const SORT_FIELD_WHITELIST = new Set([ 'created_at', 'quantity', 'stock_id', 'store_id', 'warehouse_id' ]); + const sortFieldRaw = String(sort.sortField || 'created_at').trim(); + const sortField = SORT_FIELD_WHITELIST.has(sortFieldRaw) ? sortFieldRaw : 'created_at'; + const sortOrderRaw = String(sort.sortOrder || 'DESC').trim().toUpperCase(); + const sortOrder = sortOrderRaw === 'ASC' ? 'ASC' : 'DESC'; + + const EXPORT_MAX = 50000; + const rows = await ctx.model.query( + `SELECT + t.id, + t.created_at, + t.transaction_type, + t.warehouse_id, + t.store_id, + t.stock_id, + t.quantity, + t.before_quantity, + t.after_quantity, + t.before_locked_quantity, + t.after_locked_quantity, + t.batch_no, + t.order_type, + t.order_no, + t.order_id, + t.receiving_id, + t.entry_order_id, + t.operator_name, + t.remark + FROM wms_stock_transaction t + ${whereSQL} + ORDER BY t.${sortField} ${sortOrder}, t.id ${sortOrder} + LIMIT ${EXPORT_MAX} + `, + { + replacements, + type: app.Sequelize.QueryTypes.SELECT, + } + ); + + const safeRows = Array.isArray(rows) ? rows : []; + const excelRows = safeRows.map((item, index) => ({ + 序号: index + 1, + 创建时间: item.created_at ? app.formatDate(item.created_at) : '', + 流水类型: item.transaction_type || '', + 仓库ID: Number(item.warehouse_id) || 0, + 货主ID: Number(item.store_id) || 0, + 商品ID: Number(item.stock_id) || 0, + 变动数量: Number(item.quantity) || 0, + 变更前库存: Number(item.before_quantity) || 0, + 变更后库存: Number(item.after_quantity) || 0, + 变更前锁定: Number(item.before_locked_quantity) || 0, + 变更后锁定: Number(item.after_locked_quantity) || 0, + 批次号: item.batch_no || '', + 单据类型: item.order_type || '', + 单据号: item.order_no || '', + 收货单ID: Number(item.receiving_id) || 0, + 入库单ID: Number(item.entry_order_id) || 0, + 发货单ID: Number(item.order_id) || 0, + 操作人: item.operator_name || '', + 备注: item.remark || '', + })); + + const titleSuffix = isStoreMode ? '货主侧' : '仓库侧'; + const warehouseIdForPath = warehouseId || storeId || 'unknown'; + + return await ctx.service.systems.excel.generateAndUpload({ + filename: `商品流水_${titleSuffix}_${warehouseIdForPath}_${Date.now()}.xlsx`, + dir: `exports/stock/transaction/${warehouseIdForPath}`, + category: 'document', + sheets: [ + { + name: '商品流水', + columns: [ + { header: '序号', key: '序号' }, + { header: '创建时间', key: '创建时间' }, + { header: '流水类型', key: '流水类型' }, + { header: '仓库ID', key: '仓库ID' }, + { header: '货主ID', key: '货主ID' }, + { header: '商品ID', key: '商品ID' }, + { header: '变动数量', key: '变动数量' }, + { header: '变更前库存', key: '变更前库存' }, + { header: '变更后库存', key: '变更后库存' }, + { header: '变更前锁定', key: '变更前锁定' }, + { header: '变更后锁定', key: '变更后锁定' }, + { header: '批次号', key: '批次号' }, + { header: '单据类型', key: '单据类型' }, + { header: '单据号', key: '单据号' }, + { header: '收货单ID', key: '收货单ID' }, + { header: '入库单ID', key: '入库单ID' }, + { header: '发货单ID', key: '发货单ID' }, + { header: '操作人', key: '操作人' }, + { header: '备注', key: '备注' }, + ], + rows: excelRows, + }, + ], + }); + } } module.exports = StockTransactionService; diff --git a/methods/changes/system.json b/methods/changes/system.json index 1507737..3f26575 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -4912,5 +4912,22 @@ "更新 systems/storage/entry.js L273 注释引用", "文档:methods/system.json module storage.report→stock.report,5个 method 名同步更新" ] + }, + { + "version": "2026.07.17-stock-transaction-export-01", + "date": "2026-07-17", + "type": "added", + "summary": "新增 stock.transaction 商品流水导出(仓库侧+货主侧),异步任务模式,支持与列表查询一致的条件筛选", + "methods": [ + "stock.transaction.export", + "stock.transaction.exportStore", + "stock.transaction.exportTaskProgress" + ], + "notes": [ + "systems/stock_transaction.js 新增 exportList(),复用 queryList 的查询逻辑,不分页导出 Excel(上限 50000 条)", + "systemMethods/stock/transaction.js 新增 export/exportStore/exportTaskProgress,采用异步任务模式(setImmediate + 缓存)", + "仓库侧导出自动限定 warehouse_id=ctx.user.store_id,货主侧需传 store_id", + "导出 Excel 列:序号/创建时间/流水类型/仓库ID/货主ID/商品ID/变动数量/变更前库存/变更后库存/变更前锁定/变更后锁定/批次号/单据类型/单据号/收货单ID/入库单ID/发货单ID/操作人/备注" + ] } ] diff --git a/methods/system.json b/methods/system.json index 8a4710d..8f9590d 100644 --- a/methods/system.json +++ b/methods/system.json @@ -28326,6 +28326,332 @@ ] } ] + }, + { + "groupName": "商品流水模块", + "module": "stock.transaction", + "list": [ + { + "method": "stock.transaction.export", + "description": "提交商品出入库流水导出异步任务(仓库侧)。与 stock.transaction.list 使用相同查询条件,立即返回任务受理信息,不直接返回文件。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "查询条件对象。支持字段:start_time(开始时间)、end_time(结束时间)、store_ids(货主ID数组)、stock_ids(商品库存ID数组)、transaction_type(流水类型 INBOUND/OUTBOUND/LOCK/UNLOCK)、order_type(单据类型)、order_no(单据号,模糊匹配)、batch_no(批次号)、entry_order_id(入库单ID)、receiving_id(收货单ID)、order_id(发货单ID)。仓库范围自动取自 ctx.user.store_id。" + }, + { + "name": "where.start_time", + "type": "string", + "required": false, + "source": "body", + "description": "开始时间" + }, + { + "name": "where.end_time", + "type": "string", + "required": false, + "source": "body", + "description": "结束时间" + }, + { + "name": "where.store_ids", + "type": "array", + "required": false, + "source": "body", + "description": "货主ID数组" + }, + { + "name": "where.stock_ids", + "type": "array", + "required": false, + "source": "body", + "description": "商品库存ID数组" + }, + { + "name": "where.transaction_type", + "type": "string", + "required": false, + "source": "body", + "description": "流水类型:INBOUND/OUTBOUND/LOCK/UNLOCK" + }, + { + "name": "where.order_type", + "type": "string", + "required": false, + "source": "body", + "description": "单据类型" + }, + { + "name": "where.order_no", + "type": "string", + "required": false, + "source": "body", + "description": "单据号(模糊匹配)" + }, + { + "name": "where.batch_no", + "type": "string", + "required": false, + "source": "body", + "description": "批次号" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数。sortField 白名单:created_at/quantity/stock_id/store_id/warehouse_id;sortOrder 支持 ASC/DESC" + }, + { + "name": "sort.sortField", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序字段" + }, + { + "name": "sort.sort_field", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序字段下划线别名" + }, + { + "name": "sort.sortOrder", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序方向" + }, + { + "name": "sort.sort_order", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序方向下划线别名" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "导出任务ID" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "任务状态:submitted" + }, + { + "name": "progress", + "type": "number", + "required": true, + "description": "进度:0" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "受理消息" + }, + { + "name": "update_time", + "type": "number", + "required": true, + "description": "更新时间戳" + } + ], + "errors": [] + }, + { + "method": "stock.transaction.exportStore", + "description": "提交商品出入库流水导出异步任务(货主侧)。与 stock.transaction.storeList 使用相同查询条件,需传 store_id,立即返回任务受理信息。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "store_id", + "type": "number", + "required": true, + "source": "body", + "description": "货主ID" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "查询条件对象。支持字段:start_time、end_time、warehouse_ids(仓库ID数组)、stock_ids(商品库存ID数组)、transaction_type、order_type、order_no、batch_no、entry_order_id、receiving_id、order_id。兼容 warehouse_id 单数。" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数。sortField 白名单:created_at/quantity/stock_id/store_id/warehouse_id" + }, + { + "name": "sort.sortField", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序字段" + }, + { + "name": "sort.sort_field", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序字段下划线别名" + }, + { + "name": "sort.sortOrder", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序方向" + }, + { + "name": "sort.sort_order", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序方向下划线别名" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "导出任务ID" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "任务状态:submitted" + }, + { + "name": "progress", + "type": "number", + "required": true, + "description": "进度:0" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "受理消息" + }, + { + "name": "update_time", + "type": "number", + "required": true, + "description": "更新时间戳" + } + ], + "errors": [] + }, + { + "method": "stock.transaction.exportTaskProgress", + "description": "根据 task_id 查询商品流水导出任务进度与结果。status 可能值:submitted/running/success/failed/not_found。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "task_id", + "type": "string", + "required": false, + "source": "body", + "description": "导出任务ID(下划线写法)" + }, + { + "name": "taskId", + "type": "string", + "required": false, + "source": "body", + "description": "导出任务ID(驼峰写法)" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务ID" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "任务状态:submitted/running/success/failed/not_found" + }, + { + "name": "progress", + "type": "number", + "required": true, + "description": "进度百分比(0-100)" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "状态说明" + }, + { + "name": "error", + "type": "string", + "required": true, + "description": "失败时错误信息" + }, + { + "name": "download_url", + "type": "string", + "required": true, + "description": "成功后下载链接" + }, + { + "name": "update_time", + "type": "number", + "required": true, + "description": "更新时间戳" + } + ], + "errors": [] + } + ] } ] } From 07f35c43bf4f0361aeb8bb4269f85df258bb21c5 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Fri, 17 Jul 2026 01:56:54 +0800 Subject: [PATCH 115/550] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=20queryList?= =?UTF-8?q?=20=E4=B8=AD=20stockIds=20=E7=AD=9B=E9=80=89=20if=20=E5=9D=97?= =?UTF-8?q?=E7=BC=BA=E5=A4=B1=E5=AF=BC=E8=87=B4=E8=AF=AD=E6=B3=95=E9=94=99?= =?UTF-8?q?=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/systems/stock_transaction.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/app/service/systems/stock_transaction.js b/app/service/systems/stock_transaction.js index 42186ad..a339123 100644 --- a/app/service/systems/stock_transaction.js +++ b/app/service/systems/stock_transaction.js @@ -477,6 +477,8 @@ class StockTransactionService extends Service { // 商品筛选 const normalizedStockIds = resolvedStockIds; + if (normalizedStockIds.length > 0) { + whereClauses.push('t.stock_id IN (:stockIds)'); replacements.stockIds = normalizedStockIds; } From 04305fffd60be5dd972e7aaf3d0f04f74865d893 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Fri, 17 Jul 2026 02:26:10 +0800 Subject: [PATCH 116/550] =?UTF-8?q?feat:=20stock.transaction=20=E6=96=B0?= =?UTF-8?q?=E5=A2=9E=20where.ids=20=E7=B2=BE=E7=A1=AE=E7=AD=9B=E9=80=89?= =?UTF-8?q?=EF=BC=8C=E6=94=AF=E6=8C=81=E5=AF=BC=E5=87=BA=E9=80=89=E4=B8=AD?= =?UTF-8?q?=E8=AE=B0=E5=BD=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 之前 where.ids 传入完全被忽略,导致导出内容与用户选中的记录不符。 queryList/exportList 现已支持 ids 数组精确筛选 wms_stock_transaction.id。 --- .../systemMethods/stock/transaction.js | 8 ++++++++ app/service/systems/stock_transaction.js | 20 +++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/app/service/systemMethods/stock/transaction.js b/app/service/systemMethods/stock/transaction.js index f8c94e1..6dae504 100644 --- a/app/service/systemMethods/stock/transaction.js +++ b/app/service/systemMethods/stock/transaction.js @@ -38,6 +38,7 @@ class StockTransactionMethodService extends MainService { store_ids: storeIds, stock_ids: stockIds, keyword, + ids, transaction_type: transactionType, order_type: orderType, order_no: orderNo, @@ -67,6 +68,7 @@ class StockTransactionMethodService extends MainService { storeIds, stockIds, keyword, + ids, transactionType, orderType, orderNo, @@ -109,6 +111,7 @@ class StockTransactionMethodService extends MainService { stock_ids: stockIdsRaw, stock_id: stockIdRaw, keyword, + ids, transaction_type: transactionType, order_type: orderType, order_no: orderNo, @@ -148,6 +151,7 @@ class StockTransactionMethodService extends MainService { warehouseIds, stockIds, keyword, + ids, transactionType, orderType, orderNo, @@ -178,6 +182,7 @@ class StockTransactionMethodService extends MainService { store_ids: storeIds, stock_ids: stockIds, keyword, + ids, transaction_type: transactionType, order_type: orderType, order_no: orderNo, @@ -223,6 +228,7 @@ class StockTransactionMethodService extends MainService { storeIds, stockIds, keyword, + ids, transactionType, orderType, orderNo, @@ -284,6 +290,7 @@ class StockTransactionMethodService extends MainService { stock_ids: stockIdsRaw, stock_id: stockIdRaw, keyword, + ids, transaction_type: transactionType, order_type: orderType, order_no: orderNo, @@ -337,6 +344,7 @@ class StockTransactionMethodService extends MainService { warehouseIds, stockIds, keyword, + ids, transactionType, orderType, orderNo, diff --git a/app/service/systems/stock_transaction.js b/app/service/systems/stock_transaction.js index a339123..110c9d3 100644 --- a/app/service/systems/stock_transaction.js +++ b/app/service/systems/stock_transaction.js @@ -400,6 +400,7 @@ class StockTransactionService extends Service { warehouseIds, stockIds: rawStockIds, keyword, + ids, transactionType, orderType, orderNo, @@ -482,6 +483,15 @@ class StockTransactionService extends Service { replacements.stockIds = normalizedStockIds; } + // 记录ID筛选(精确导出选中记录) + const normalizedIds = Array.isArray(ids) + ? ids.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0) + : []; + if (normalizedIds.length > 0) { + whereClauses.push('t.id IN (:ids)'); + replacements.ids = normalizedIds; + } + // 流水类型 if (transactionType) { whereClauses.push('t.transaction_type = :transactionType'); @@ -644,6 +654,7 @@ class StockTransactionService extends Service { warehouseIds, stockIds: rawStockIds, keyword, + ids, transactionType, orderType, orderNo, @@ -722,6 +733,15 @@ class StockTransactionService extends Service { replacements.stockIds = normalizedStockIds; } + // 记录ID筛选(精确导出选中记录) + const normalizedIds = Array.isArray(ids) + ? ids.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0) + : []; + if (normalizedIds.length > 0) { + whereClauses.push('t.id IN (:ids)'); + replacements.ids = normalizedIds; + } + if (transactionType) { whereClauses.push('t.transaction_type = :transactionType'); replacements.transactionType = String(transactionType).trim(); From 1537c1ac101b6ff5a105cb8e698bd519b40e4cf1 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Fri, 17 Jul 2026 02:37:54 +0800 Subject: [PATCH 117/550] =?UTF-8?q?refactor:=20stock.transaction=20?= =?UTF-8?q?=E5=AF=BC=E5=87=BA=E5=88=97=E8=B0=83=E6=95=B4=E4=B8=BA=E5=BA=93?= =?UTF-8?q?=E5=AD=98=E5=8F=98=E5=8A=A8/=E9=94=81=E5=AE=9A=E5=8F=98?= =?UTF-8?q?=E5=8A=A8=E5=88=86=E7=A6=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 库存变动量(INBOUND/OUTBOUND 有值,LOCK/UNLOCK 为 0) - 库存变更前/后 - 锁定变动量(计算 after_locked - before_locked,库存流水中为 0) - 锁定变更前/后 --- app/service/systems/stock_transaction.js | 63 ++++++++++++++---------- 1 file changed, 37 insertions(+), 26 deletions(-) diff --git a/app/service/systems/stock_transaction.js b/app/service/systems/stock_transaction.js index 110c9d3..ec4dd98 100644 --- a/app/service/systems/stock_transaction.js +++ b/app/service/systems/stock_transaction.js @@ -830,27 +830,37 @@ class StockTransactionService extends Service { ); const safeRows = Array.isArray(rows) ? rows : []; - const excelRows = safeRows.map((item, index) => ({ - 序号: index + 1, - 创建时间: item.created_at ? app.formatDate(item.created_at) : '', - 流水类型: item.transaction_type || '', - 仓库ID: Number(item.warehouse_id) || 0, - 货主ID: Number(item.store_id) || 0, - 商品ID: Number(item.stock_id) || 0, - 变动数量: Number(item.quantity) || 0, - 变更前库存: Number(item.before_quantity) || 0, - 变更后库存: Number(item.after_quantity) || 0, - 变更前锁定: Number(item.before_locked_quantity) || 0, - 变更后锁定: Number(item.after_locked_quantity) || 0, - 批次号: item.batch_no || '', - 单据类型: item.order_type || '', - 单据号: item.order_no || '', - 收货单ID: Number(item.receiving_id) || 0, - 入库单ID: Number(item.entry_order_id) || 0, - 发货单ID: Number(item.order_id) || 0, - 操作人: item.operator_name || '', - 备注: item.remark || '', - })); + const excelRows = safeRows.map((item, index) => { + const qty = Number(item.quantity) || 0; + const beforeQty = Number(item.before_quantity) || 0; + const afterQty = Number(item.after_quantity) || 0; + const beforeLocked = Number(item.before_locked_quantity) || 0; + const afterLocked = Number(item.after_locked_quantity) || 0; + const lockedChange = afterLocked - beforeLocked; + + return { + 序号: index + 1, + 创建时间: item.created_at ? app.formatDate(item.created_at) : '', + 流水类型: item.transaction_type || '', + 仓库ID: Number(item.warehouse_id) || 0, + 货主ID: Number(item.store_id) || 0, + 商品ID: Number(item.stock_id) || 0, + 库存变动量: qty, + 库存变更前: beforeQty, + 库存变更后: afterQty, + 锁定变动量: lockedChange, + 锁定变更前: beforeLocked, + 锁定变更后: afterLocked, + 批次号: item.batch_no || '', + 单据类型: item.order_type || '', + 单据号: item.order_no || '', + 收货单ID: Number(item.receiving_id) || 0, + 入库单ID: Number(item.entry_order_id) || 0, + 发货单ID: Number(item.order_id) || 0, + 操作人: item.operator_name || '', + 备注: item.remark || '', + }; + }); const titleSuffix = isStoreMode ? '货主侧' : '仓库侧'; const warehouseIdForPath = warehouseId || storeId || 'unknown'; @@ -869,11 +879,12 @@ class StockTransactionService extends Service { { header: '仓库ID', key: '仓库ID' }, { header: '货主ID', key: '货主ID' }, { header: '商品ID', key: '商品ID' }, - { header: '变动数量', key: '变动数量' }, - { header: '变更前库存', key: '变更前库存' }, - { header: '变更后库存', key: '变更后库存' }, - { header: '变更前锁定', key: '变更前锁定' }, - { header: '变更后锁定', key: '变更后锁定' }, + { header: '库存变动量', key: '库存变动量' }, + { header: '库存变更前', key: '库存变更前' }, + { header: '库存变更后', key: '库存变更后' }, + { header: '锁定变动量', key: '锁定变动量' }, + { header: '锁定变更前', key: '锁定变更前' }, + { header: '锁定变更后', key: '锁定变更后' }, { header: '批次号', key: '批次号' }, { header: '单据类型', key: '单据类型' }, { header: '单据号', key: '单据号' }, From 52aa76af6003128964202f91f757e09261d042eb Mon Sep 17 00:00:00 2001 From: liufumingren Date: Tue, 21 Jul 2026 20:53:53 +0800 Subject: [PATCH 118/550] =?UTF-8?q?fix:=20OrderExpress=20=E6=9F=A5?= =?UTF-8?q?=E8=AF=A2=E6=B7=BB=E5=8A=A0=E4=BB=93=E5=BA=93=E9=9A=94=E7=A6=BB?= =?UTF-8?q?=20+=20workbench=20=E4=B8=9A=E5=8A=A1=E5=A2=9E=E5=BC=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - _queryOrder: OrderExpress 查询增加 warehouse_id 过滤,避免跨仓库数据泄露 - _queryOrder: 新增订单商品明细查询,关联 stock 详情(带缓存) - _packOrder: 同一工作台新任务进入时自动关闭上一个未结束任务 - order_packing.js: quickWhere 运单号查询增加 warehouse_id 过滤 - recheckOrder.js: getWaveOrdersBasic 运单查询增加 warehouse_id 过滤 - order_print.js: queryOrderExpressByOrderIds 增加 warehouseId 参数 - waybill.js: toOrder 运单查询在用户已登录时增加 warehouse_id 过滤 --- .../systemMethods/order/recheckOrder.js | 9 +- app/service/systems/order_packing.js | 394 +++++++++++ app/service/systems/order_print.js | 49 +- app/service/systems/waybill.js | 13 +- app/service/systems/workbench.js | 615 ++++++++++++++++++ 5 files changed, 1068 insertions(+), 12 deletions(-) create mode 100644 app/service/systems/order_packing.js create mode 100644 app/service/systems/workbench.js diff --git a/app/service/systemMethods/order/recheckOrder.js b/app/service/systemMethods/order/recheckOrder.js index dfa1c02..f338f20 100644 --- a/app/service/systemMethods/order/recheckOrder.js +++ b/app/service/systemMethods/order/recheckOrder.js @@ -10,9 +10,9 @@ class RecheckOrderService extends OrderBaseService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'scanOrder,scanTask,scanWaybill,confirmRecheck,recheckOrderList,confirmIntercept,batchQuickRecheck'; + const _noNeedRight = 'scanOrder,scanTask,scanWaybill,confirmRecheck,recheckOrderList,confirmIntercept,batchQuickRecheck,queryRecheckOrderSingleList'; const _noNeedLog = 'scanOrder,scanTask,scanWaybill,confirmRecheck,recheckOrderList,confirmIntercept,batchQuickRecheck'; - const _noNeedAuth = 'scanOrder,scanTask,scanWaybill,confirmRecheck,recheckOrderList,confirmIntercept,batchQuickRecheck'; + const _noNeedAuth = 'scanOrder,scanTask,scanWaybill,confirmRecheck,recheckOrderList,confirmIntercept,batchQuickRecheck,queryRecheckOrderSingleList'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -1043,7 +1043,7 @@ class RecheckOrderService extends OrderBaseService { const waybillMap = new Map(); if (orderIds.length > 0 && ctx.model && ctx.model.OrderExpress) { const expressRows = await ctx.model.OrderExpress.findAll({ - where: { order_id: orderIds }, + where: { order_id: orderIds, warehouse_id: warehouseId }, attributes: [ 'order_id', 'waybill_code' ], order: [[ 'id', 'ASC' ]], raw: true, @@ -3145,7 +3145,6 @@ class RecheckOrderService extends OrderBaseService { o.weight_type, o.status, o.create_at, - o.pick_time, o.recheck_time FROM ${orderTableName} o ${whereClause} @@ -3191,7 +3190,6 @@ class RecheckOrderService extends OrderBaseService { weight_type: this.formatWeightTypeLabel(row?.weight_type), status: Number(row?.status || 0), create_at: row?.create_at || null, - pick_time: row?.pick_time || null, recheck_time: row?.recheck_time || null, })); @@ -3927,6 +3925,7 @@ class RecheckOrderService extends OrderBaseService { await orderModel.update( { recheck_status: 'fin', + print_status: 'fin', recheck_time: now, updated_at: now, }, diff --git a/app/service/systems/order_packing.js b/app/service/systems/order_packing.js new file mode 100644 index 0000000..7188ddc --- /dev/null +++ b/app/service/systems/order_packing.js @@ -0,0 +1,394 @@ +'use strict'; + +const Service = require('egg').Service; + +/** + * 打包任务服务层(仓库侧)。 + * 负责打包任务列表查询、详情查询等仓库维度的打包管理业务逻辑。 + * 数据来源:wms_pack_task 表。 + */ +class OrderPackingService extends Service { + /** + * 打包任务列表查询(仓库侧)。 + * 按仓库维度(warehouse_id)查询打包任务,支持分页、筛选、排序。 + * + * @param {Object} where 筛选条件对象 + * @param {Object} [where.status] 任务状态:0=待处理 1=打包中 2=已完成 3=异常 + * @param {Object} [where.pack_mode] 打包模式:1=散单 2=团购 + * @param {Object} [where.waybill_code] 运单号(模糊匹配) + * @param {Object} [where.wave_no] 波次号(模糊匹配) + * @param {Object} [where.order_id] 订单ID(精确匹配) + * @param {Object} [where.workbench_id] 工作台ID(精确匹配) + * @param {Object} [where.quickWhere] 快捷搜索:支持波次号模糊匹配;运单号通过 express→order→wave 链路解析(团购按波次号查、散单按订单ID查) + * @param {Object} [where.start_time_start] 开始打包时间起始 + * @param {Object} [where.start_time_end] 开始打包时间结束 + * @param {Object} pagination 分页参数 { page, pageSize } + * @param {Object} sort 排序参数 { sortField, sortOrder } + * @return {Promise} 打包任务列表与分页信息 + */ + async list(where = {}, pagination = {}, sort = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + const page = Math.max(Number(pagination.page) || 1, 1); + const pageSize = Math.max(Number(pagination.pageSize) || 20, 1); + + // 仓库上下文 + const warehouseId = Number(ctx.user && ctx.user.store_id); + if (!warehouseId) { + return { + code: 400, + message: '用户未绑定仓库,无法查询打包任务', + data: { + list: [], + pagination: { page, pageSize, total: 0, totalPages: 0, hasPrevious: false, hasNext: false }, + }, + }; + } + + // 构建查询条件 + const queryWhere = { warehouse_id: warehouseId }; + + // 状态筛选 + if (where.status !== undefined && where.status !== null) { + const statusValue = where.status?.value ?? where.status; + if (statusValue !== '' && statusValue !== undefined && statusValue !== null) { + queryWhere.status = Number(statusValue); + } + } + + // 打包模式筛选 + if (where.pack_mode !== undefined && where.pack_mode !== null) { + const packModeValue = where.pack_mode?.value ?? where.pack_mode; + if (packModeValue !== '' && packModeValue !== undefined && packModeValue !== null) { + queryWhere.pack_mode = Number(packModeValue); + } + } + + // 运单号模糊匹配 + if (where.waybill_code) { + const waybillValue = where.waybill_code?.value ?? where.waybill_code; + if (waybillValue && String(waybillValue).trim()) { + queryWhere.waybill_code = { [Op.like]: `%${String(waybillValue).trim()}%` }; + } + } + + // 波次号模糊匹配 + if (where.wave_no) { + const waveNoValue = where.wave_no?.value ?? where.wave_no; + if (waveNoValue && String(waveNoValue).trim()) { + queryWhere.wave_no = { [Op.like]: `%${String(waveNoValue).trim()}%` }; + } + } + + // 订单ID精确匹配 + if (where.order_id !== undefined && where.order_id !== null) { + const orderIdValue = where.order_id?.value ?? where.order_id; + if (orderIdValue !== '' && orderIdValue !== undefined && orderIdValue !== null) { + queryWhere.order_id = Number(orderIdValue); + } + } + + // 工作台ID精确匹配 + if (where.workbench_id !== undefined && where.workbench_id !== null) { + const workbenchIdValue = where.workbench_id?.value ?? where.workbench_id; + if (workbenchIdValue !== '' && workbenchIdValue !== undefined && workbenchIdValue !== null) { + queryWhere.workbench_id = Number(workbenchIdValue); + } + } + + // 快捷搜索:支持波次号直接模糊匹配 + 运单号通过 express → order → wave 链路解析 + if (where.quickWhere) { + const quickValue = where.quickWhere?.value ?? where.quickWhere; + if (quickValue && String(quickValue).trim()) { + const kw = String(quickValue).trim(); + const orConditions = []; + + // 1. 波次号直接模糊匹配(用户可能直接搜波次号) + orConditions.push({ wave_no: { [Op.like]: `%${kw}%` } }); + + // 2. 运单号解析:express → order → wave + // 团购波次 → 按 wave_no 查 packing 表;散单 → 按 order_id 查 packing 表 + const expressRecords = await ctx.model.OrderExpress.findAll({ + where: { + waybill_code: { [Op.like]: `%${kw}%` }, + warehouse_id: warehouseId, + delete_at: null, + }, + attributes: [ 'order_id' ], + raw: true, + }); + + if (expressRecords.length > 0) { + const orderIds = [ ...new Set(expressRecords.map(r => r.order_id).filter(Boolean)) ]; + + if (orderIds.length > 0) { + // 查 order_delivery 获取 wave_id + const orderRecords = await ctx.model.OrderDelivery.findAll({ + where: { id: { [Op.in]: orderIds }, warehouse_id: warehouseId }, + attributes: [ 'id', 'wave_id' ], + raw: true, + }); + + // order_id → wave_id 映射 + const orderWaveMap = new Map(); + const noWaveOrderIds = []; + orderRecords.forEach(o => { + if (o.wave_id > 0) { + orderWaveMap.set(o.id, o.wave_id); + } else { + noWaveOrderIds.push(o.id); + } + }); + + // 未匹配到 order_delivery 的 order_id 也按散单处理 + const matchedOrderIds = new Set(orderRecords.map(o => o.id)); + orderIds.forEach(oid => { + if (!matchedOrderIds.has(oid)) { + noWaveOrderIds.push(oid); + } + }); + + const waveIds = [ ...new Set(orderWaveMap.values()) ]; + + if (waveIds.length > 0) { + // 查 wms_wave_batch 获取 wave_type 和 wave_no + const waveRecords = await ctx.model.WaveBatch.findAll({ + where: { wave_id: { [Op.in]: waveIds } }, + attributes: [ 'wave_id', 'wave_no', 'wave_type' ], + raw: true, + }); + + // wave_id → { wave_no, wave_type } 映射 + const waveMap = new Map(); + waveRecords.forEach(w => { + waveMap.set(w.wave_id, { wave_no: w.wave_no, wave_type: w.wave_type }); + }); + + // 分离:团购波次号 / 散单订单ID + const groupBuyWaveNos = []; + const singleOrderIds = [ ...noWaveOrderIds ]; + + orderRecords.forEach(o => { + const waveInfo = waveMap.get(o.wave_id); + if (waveInfo) { + if (waveInfo.wave_type === 1) { + // 团购 → 按波次号查 packing 表 + if (waveInfo.wave_no) { + groupBuyWaveNos.push(waveInfo.wave_no); + } + } else { + // 散单(wave_type=2) → 按 order_id 查 packing 表 + singleOrderIds.push(o.id); + } + } else { + // wave_id 在 wms_wave_batch 中不存在,按散单处理 + singleOrderIds.push(o.id); + } + }); + + if (groupBuyWaveNos.length > 0) { + orConditions.push({ wave_no: { [Op.in]: [ ...new Set(groupBuyWaveNos) ] } }); + } + if (singleOrderIds.length > 0) { + orConditions.push({ order_id: { [Op.in]: [ ...new Set(singleOrderIds) ] } }); + } + } else { + // 所有订单都没有波次(wave_id = 0),全部按散单处理 + orConditions.push({ order_id: { [Op.in]: orderIds } }); + } + } + } + + queryWhere[Op.or] = orConditions; + } + } + + // 开始打包时间范围 + if (where.start_time_start) { + const startTimeStart = where.start_time_start?.value ?? where.start_time_start; + if (startTimeStart) { + queryWhere.start_time = { ...(queryWhere.start_time || {}), [Op.gte]: new Date(startTimeStart) }; + } + } + if (where.start_time_end) { + const startTimeEnd = where.start_time_end?.value ?? where.start_time_end; + if (startTimeEnd) { + queryWhere.start_time = { ...(queryWhere.start_time || {}), [Op.lte]: new Date(startTimeEnd) }; + } + } + + // 排序 + const sortField = sort.sortField || 'create_time'; + const sortOrder = String(sort.sortOrder || 'DESC').toUpperCase() === 'ASC' ? 'ASC' : 'DESC'; + const validSortFields = [ 'id', 'order_id', 'warehouse_id', 'workbench_id', 'wave_id', 'pack_quantity', 'pack_mode', 'status', 'start_time', 'end_time', 'create_time', 'update_time' ]; + const actualSortField = validSortFields.includes(sortField) ? sortField : 'create_time'; + + // 查询(含工作台、视频和运单关联) + const { count, rows } = await ctx.model.PackTask.findAndCountAll({ + where: queryWhere, + order: [[ actualSortField, sortOrder ]], + limit: pageSize, + offset: (page - 1) * pageSize, + include: [ + { + model: ctx.model.Workbench, + as: 'workbench', + attributes: [ 'id', 'name', 'type', 'barcode' ], + }, + { + model: ctx.model.PackTaskVideo, + as: 'videos', + attributes: [ 'id', 'video_url', 'camera_id', 'status' ], + where: { status: 1 }, + required: false, + include: [ + { + model: ctx.model.Camera, + as: 'camera', + attributes: [ 'id', 'custom_name', 'channel_name' ], + }, + ], + }, + { + model: ctx.model.OrderExpress, + as: 'expresses', + attributes: [ 'id', 'waybill_code', 'logistics_code', 'logistics_name', 'logistics_interface_name', 'platform_code', 'status' ], + where: { delete_at: null }, + required: false, + }, + ], + }); + + // 扁平化输出 + const list = rows.map(row => { + const plain = row.get({ plain: true }); + return { + ...plain, + workbench_name: plain.workbench?.name || null, + workbench_type: plain.workbench?.type || null, + workbench_barcode: plain.workbench?.barcode || null, + videos: (plain.videos || []).map(v => ({ + id: v.id, + video_url: v.video_url, + camera_id: v.camera_id, + camera_name: v.camera?.custom_name || v.camera?.channel_name || null, + })), + expresses: (plain.expresses || []).map(e => ({ + id: e.id, + waybill_code: e.waybill_code, + logistics_code: e.logistics_code, + logistics_name: e.logistics_name, + logistics_interface_name: e.logistics_interface_name || null, + platform_code: e.platform_code || null, + status: e.status, + })), + workbench: undefined, + }; + }); + + const totalPages = Math.ceil(count / pageSize) || 0; + + return { + code: 200, + message: 'ok', + data: { + list, + pagination: { + page, + pageSize, + total: count, + totalPages, + hasPrevious: page > 1, + hasNext: page < totalPages, + }, + }, + }; + } + + /** + * 打包任务详情查询。 + * 按 id + warehouse_id 查询单条打包任务记录。 + * + * @param {Object} options 查询参数 + * @param {number} options.id 打包任务ID + * @return {Promise} 打包任务详情 + */ + async get(options = {}) { + const { ctx } = this; + const { id } = options; + + if (!id) { + return { code: 400, message: '打包任务ID不能为空', data: null }; + } + + const warehouseId = Number(ctx.user && ctx.user.store_id); + if (!warehouseId) { + return { code: 400, message: '用户未绑定仓库,无法查询打包任务', data: null }; + } + + const record = await ctx.model.PackTask.findOne({ + where: { id: Number(id), warehouse_id: warehouseId }, + include: [ + { + model: ctx.model.Workbench, + as: 'workbench', + attributes: [ 'id', 'name', 'type', 'barcode' ], + }, + { + model: ctx.model.PackTaskVideo, + as: 'videos', + attributes: [ 'id', 'video_url', 'camera_id', 'status' ], + where: { status: 1 }, + required: false, + include: [ + { + model: ctx.model.Camera, + as: 'camera', + attributes: [ 'id', 'custom_name', 'channel_name' ], + }, + ], + }, + { + model: ctx.model.OrderExpress, + as: 'expresses', + attributes: [ 'id', 'waybill_code', 'logistics_code', 'logistics_name', 'logistics_interface_name', 'platform_code', 'status' ], + where: { delete_at: null }, + required: false, + }, + ], + }); + + if (!record) { + return { code: 404, message: '打包任务不存在或无权访问', data: null }; + } + + const plain = record.get({ plain: true }); + const data = { + ...plain, + workbench_name: plain.workbench?.name || null, + workbench_type: plain.workbench?.type || null, + workbench_barcode: plain.workbench?.barcode || null, + videos: (plain.videos || []).map(v => ({ + id: v.id, + video_url: v.video_url, + camera_id: v.camera_id, + camera_name: v.camera?.custom_name || v.camera?.channel_name || null, + })), + expresses: (plain.expresses || []).map(e => ({ + id: e.id, + waybill_code: e.waybill_code, + logistics_code: e.logistics_code, + logistics_name: e.logistics_name, + logistics_interface_name: e.logistics_interface_name || null, + platform_code: e.platform_code || null, + status: e.status, + })), + workbench: undefined, + }; + + return { code: 200, message: 'ok', data }; + } +} + +module.exports = OrderPackingService; diff --git a/app/service/systems/order_print.js b/app/service/systems/order_print.js index 5b43d17..accd80f 100644 --- a/app/service/systems/order_print.js +++ b/app/service/systems/order_print.js @@ -252,6 +252,39 @@ class OrderPrintSystemService extends OrderBaseService { } } + // 兜底:若 current items 表未命中全部 orderItemId,补查 dispatch items 表 + // 配送表订单的 items 可能已迁移到 dispatch items 表,getCurrentModel 查不到 + const foundItemIds = new Set([ ...orderItemMap.keys() ]); + const missingItemIds = orderItemIds.filter(id => !foundItemIds.has(id)); + const dispatchItemRows = []; + if (missingItemIds.length > 0 && orderItemModelFactory && typeof orderItemModelFactory.getDispatchModel === 'function') { + try { + const dispatchItemModel = await orderItemModelFactory.getDispatchModel(warehouseId); + if (dispatchItemModel && typeof dispatchItemModel.findAll === 'function') { + const dispatchRows = await dispatchItemModel.findAll({ + where: { + id: { + [Op.in]: missingItemIds, + }, + }, + attributes: [ 'id', 'order_id', 'item_code', 'item_name', 'plan_qty', 'item_snapshot', 'stock_id' ], + raw: true, + }); + if (Array.isArray(dispatchRows)) { + for (const row of dispatchRows) { + const orderItemId = Number(row && row.id || 0); + if (orderItemId > 0 && !orderItemMap.has(orderItemId)) { + orderItemMap.set(orderItemId, row); + dispatchItemRows.push(row); + } + } + } + } + } catch (err) { + this.ctx.logger.warn('[buildPrintOrderRowMapWithPicking] dispatch items 兜底查询失败:%s', err.message); + } + } + const locationFallbackSpaceIds = Array.from(new Set(normalizedPickingRows .filter(row => !String(row && row.space_name || '').trim()) .map(row => Number(row && row.space_id || 0)) @@ -306,6 +339,15 @@ class OrderPrintSystemService extends OrderBaseService { } } + // 1c) 从 dispatch items 兜底收集 stock_id(配送表订单的 items 可能在 dispatch items 表) + for (const row of dispatchItemRows) { + const itemSnapshot = this.normalizeItemSnapshot(row.item_snapshot); + const stockId = Number(row.stock_id || itemSnapshot.stock_id || 0); + if (stockId > 0) { + allStockIds.add(stockId); + } + } + const uniqueStockIds = Array.from(allStockIds); // 阶段二:批量查询 wms_stock_warehouse 获取商品编码与名称(新增直读路径) @@ -681,7 +723,7 @@ class OrderPrintSystemService extends OrderBaseService { const orderIds = unlockedOrderRows .map(row => Number(row && row.id || 0)) .filter(orderId => Number.isInteger(orderId) && orderId > 0); - const orderExpressRows = await this.queryOrderExpressByOrderIds(orderIds); + const orderExpressRows = await this.queryOrderExpressByOrderIds(orderIds, normalizedWarehouseId); this.assertBusinessWaybillCompleteness(orderIds, orderExpressRows); const cainiaoEnrichedOrderExpressRows = await this.enrichCainiaoOrderExpressRows( unlockedOrderRows, @@ -856,7 +898,7 @@ class OrderPrintSystemService extends OrderBaseService { const orderIdsForExpress = validOrderRows .map(row => Number(row && row.id || 0)) .filter(orderId => Number.isInteger(orderId) && orderId > 0); - const orderExpressRows = await this.queryOrderExpressByOrderIds(orderIdsForExpress); + const orderExpressRows = await this.queryOrderExpressByOrderIds(orderIdsForExpress, normalizedWarehouseId); this.assertBusinessWaybillCompleteness(orderIdsForExpress, orderExpressRows); const cainiaoEnrichedOrderExpressRows = await this.enrichCainiaoOrderExpressRows( validOrderRows, @@ -1599,7 +1641,7 @@ class OrderPrintSystemService extends OrderBaseService { * logistics_code、logistics_name、logistics_interface_id、logistics_interface_name、platform_code、 * warehouse_id、printinfo、signature、encryptprintinfo、ver。 */ - async queryOrderExpressByOrderIds(orderIds = []) { + async queryOrderExpressByOrderIds(orderIds = [], warehouseId) { if (!Array.isArray(orderIds) || orderIds.length === 0) { return []; } @@ -1632,6 +1674,7 @@ class OrderPrintSystemService extends OrderBaseService { order_id: { [Op.in]: normalizedOrderIds, }, + warehouse_id: warehouseId, business_key: 1, }, order: [[ 'order_id', 'ASC' ], [ 'business_key', 'ASC' ], [ 'id', 'ASC' ]], diff --git a/app/service/systems/waybill.js b/app/service/systems/waybill.js index 79fcd49..94f40ff 100644 --- a/app/service/systems/waybill.js +++ b/app/service/systems/waybill.js @@ -26,11 +26,16 @@ class WaybillService extends MainService { this.throwError('运单号不能为空'); } + const userWarehouseId = ctx.user && ctx.user.store_id ? ctx.user.store_id : null; + const expressWhere = { + waybill_code: String(waybillCode).trim(), + status: 1, + }; + if (userWarehouseId) { + expressWhere.warehouse_id = userWarehouseId; + } const record = await ctx.model.OrderExpress.findOne({ - where: { - waybill_code: String(waybillCode).trim(), - status: 1, - }, + where: expressWhere, attributes: [ 'order_id', 'warehouse_id' ], raw: true, }); diff --git a/app/service/systems/workbench.js b/app/service/systems/workbench.js new file mode 100644 index 0000000..9cb9805 --- /dev/null +++ b/app/service/systems/workbench.js @@ -0,0 +1,615 @@ +'use strict'; + +const Service = require('egg').Service; + +class WorkbenchService extends Service { + /** + * 查询工作台列表(仓库隔离 + 软删除过滤) + * @param {Object} params - { pagination, where } + * @returns {Promise<{list: Array, pagination: Object}>} + */ + async list(params = {}) { + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + const warehouseId = ctx.user.store_id; + const { pagination = {}, where = {} } = params; + + const page = Math.max(1, parseInt(pagination.page) || 1); + const pageSize = Math.min(200, Math.max(1, parseInt(pagination.pageSize) || 20)); + + const queryWhere = { + warehouse_id: warehouseId, + }; + + // 白名单字段筛选 + if (where.name) { + queryWhere.name = { [Op.like]: `%${where.name}%` }; + } + if (where.barcode) { + queryWhere.barcode = { [Op.like]: `%${where.barcode}%` }; + } + if (where.status !== undefined && where.status !== null && where.status !== '') { + queryWhere.status = parseInt(where.status); + } + + const { count, rows } = await ctx.model.Workbench.findAndCountAll({ + where: queryWhere, + order: [['created_at', 'DESC']], + offset: (page - 1) * pageSize, + limit: pageSize, + }); + + return { + list: rows, + pagination: { + page, + pageSize, + total: count, + totalPages: Math.ceil(count / pageSize), + hasPrevious: page > 1, + hasNext: page * pageSize < count, + }, + }; + } + + /** + * 查询单个工作台详情 + * @param {number} id - 工作台 ID + * @returns {Promise} + */ + async detail(id) { + const { ctx } = this; + const warehouseId = ctx.user.store_id; + + const record = await ctx.model.Workbench.findOne({ + where: { id, warehouse_id: warehouseId }, + }); + + if (!record) { + throw new Error('工作台不存在或无权访问'); + } + + return record; + } + + /** + * 创建工作台 + * @param {Object} data - { name, barcode, status, remark } + * @returns {Promise} + */ + async create(data) { + const { ctx } = this; + const warehouseId = ctx.user.store_id; + + if (!data.name || !String(data.name).trim()) { + throw new Error('工作台名称不能为空'); + } + + const record = await ctx.model.Workbench.create({ + warehouse_id: warehouseId, + name: String(data.name).trim(), + barcode: data.barcode ? String(data.barcode).trim() : null, + type: data.type || 'personal', + status: data.status !== undefined ? parseInt(data.status) : 1, + device_ids: data.device_ids || null, + remark: data.remark ? String(data.remark).trim() : null, + }); + + return record; + } + + /** + * 更新工作台 + * @param {number} id - 工作台 ID + * @param {Object} data - 要更新的字段 { name, barcode, status, remark } + * @returns {Promise} + */ + async update(id, data) { + const { ctx } = this; + const warehouseId = ctx.user.store_id; + + const record = await ctx.model.Workbench.findOne({ + where: { id, warehouse_id: warehouseId }, + }); + + if (!record) { + throw new Error('工作台不存在或无权操作'); + } + + const updateFields = {}; + if (data.name !== undefined) updateFields.name = String(data.name).trim(); + if (data.barcode !== undefined) updateFields.barcode = data.barcode ? String(data.barcode).trim() : null; + if (data.type !== undefined) updateFields.type = data.type; + if (data.status !== undefined) updateFields.status = parseInt(data.status); + if (data.device_ids !== undefined) updateFields.device_ids = data.device_ids; + if (data.remark !== undefined) updateFields.remark = data.remark ? String(data.remark).trim() : null; + + if (Object.keys(updateFields).length === 0) { + throw new Error('没有需要更新的字段'); + } + + await record.update(updateFields); + return record; + } + + /** + * 软删除工作台 + * @param {number} id - 工作台 ID + * @returns {Promise} + */ + async delete(id) { + const { ctx } = this; + const warehouseId = ctx.user.store_id; + + const record = await ctx.model.Workbench.findOne({ + where: { id, warehouse_id: warehouseId }, + }); + + if (!record) { + throw new Error('工作台不存在或无权操作'); + } + + await record.destroy(); // paranoid: true → 自动设置 deleted_at + } + + /** + * 绑定/解绑摄像头到工作台 + * @param {number} id - 工作台 ID + * @param {number[]} cameraIds - 摄像头 ID 数组,传空数组或 null 表示解绑 + * @returns {Promise} + */ + async bindCamera(id, cameraIds) { + const { ctx } = this; + const warehouseId = ctx.user.store_id; + + const record = await ctx.model.Workbench.findOne({ + where: { id, warehouse_id: warehouseId }, + }); + if (!record) throw new Error('工作台不存在或无权操作'); + + const ids = Array.isArray(cameraIds) ? cameraIds : []; + if (ids.length > 0) { + const cameras = await ctx.model.Camera.findAll({ + where: { id: ids, warehouse_id: warehouseId }, + attributes: ['id'], + }); + const validIds = cameras.map(c => c.id); + const invalidIds = ids.filter(cid => !validIds.includes(cid)); + if (invalidIds.length > 0) { + throw new Error(`摄像头 ${invalidIds.join(', ')} 不存在或无权操作`); + } + } + + await record.update({ device_ids: ids.length > 0 ? ids : null }); + return record; + } + + /** + * 工作台业务入口 + * @param {string} name - 业务名称(如 queryOrder) + * @param {*} data - 业务数据 + * @returns {Promise} + */ + async business(name, data) { + const { ctx } = this; + ctx.logger.info('[Systems.Workbench.business] 收到业务调度 name=%s data=%j', name, data); + + switch (name) { + case 'queryOrder': + case 'query': + return await this._queryOrder(data || {}); + case 'packOrder': + return await this._packOrder(data || {}); + default: + throw new Error(`不支持的业务类型: ${name}`); + } + } + + /** + * 实时统计波次下的订单数量(遍历 current + dispatch 分表) + * @param {number} warehouseId + * @param {number} waveId + * @returns {Promise} + */ + async _countWaveOrders(warehouseId, waveId) { + const { ctx } = this; + const orderDeliveryFactory = ctx.model.OrderDeliveryFactory; + const tableOrders = [ + { label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) }, + { label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) }, + ]; + let total = 0; + for (const entry of tableOrders) { + try { + const model = await entry.getModel(); + if (!model) continue; + const count = await model.count({ where: { wave_id: waveId, warehouse_id: warehouseId } }); + total += count; + } catch (_err) { continue; } + } + return total; + } + + /** + * 打包任务写入:根据发货单号查询订单并创建/更新打包任务记录 + * @param {Object} params - { delivery_order_code, wave_no, warehouse_id, workbench_id, status, pack_time } + * @returns {Promise} + */ + async _packOrder(params) { + const { ctx } = this; + const { delivery_order_code: deliveryOrderCode, wave_no: waveNo, + warehouse_id: inputWarehouseId, workbench_id: workbenchId, + status: packStatus, pack_time: packTime } = params; + + if (!deliveryOrderCode) throw new Error('发货单号不能为空'); + if (!inputWarehouseId) throw new Error('仓库ID不能为空'); + + const warehouseId = parseInt(inputWarehouseId); + const packTimeMs = packTime ? Number(packTime) * 1000 : Date.now(); + + // 步骤1:查找订单 + const orderDeliveryFactory = ctx.model.OrderDeliveryFactory; + const tableOrders = [ + { label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) }, + { label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) }, + ]; + + let orderRow = null; + for (const entry of tableOrders) { + try { + const model = await entry.getModel(); + if (!model) continue; + const row = await model.findOne({ + where: { delivery_order_code: deliveryOrderCode, warehouse_id: warehouseId }, + raw: true, + }); + if (row) { orderRow = row; break; } + } catch (_err) { continue; } + } + + if (!orderRow) throw new Error(`未找到发货单 [${deliveryOrderCode}]`); + + const orderId = orderRow.id; + const waveId = orderRow.wave_id || 0; + const actualWaveNo = waveNo || orderRow.wave_no || ''; + + // 步骤2:获取波次信息,判断散单/团购 + let waveType = null; + let totalOrders = 0; + let isSandan = 1; + if (waveId > 0) { + try { + const waveBatch = await ctx.model.WaveBatch.findOne({ + where: { wave_id: waveId, warehouse_id: warehouseId }, + attributes: ['wave_type', 'total_orders'], + raw: true, + }); + if (waveBatch) { + waveType = waveBatch.wave_type; + isSandan = Number(waveType) === 1 ? 0 : 1; + // 实时统计波次订单数(而非依赖 wave_batch.total_orders 快照) + totalOrders = await this._countWaveOrders(warehouseId, waveId); + } + } catch (_err) { /* ignore */ } + } + + // 步骤3:获取工作台 device_ids + let deviceIds = null; + if (workbenchId) { + try { + const wb = await ctx.model.Workbench.findByPk(parseInt(workbenchId), { + attributes: ['device_ids'], + raw: true, + }); + deviceIds = wb && wb.device_ids ? wb.device_ids : null; + } catch (_err) { /* ignore */ } + } + + // 步骤4:同一工作台有新的打包任务时,关闭上一个未结束的任务 + if (workbenchId) { + const previousTask = await ctx.model.PackTask.findOne({ + where: { + workbench_id: parseInt(workbenchId), + warehouse_id: warehouseId, + order_id: { [ctx.app.Sequelize.Op.ne]: orderId }, + status: { [ctx.app.Sequelize.Op.lt]: 2 }, + }, + }); + if (previousTask) { + await previousTask.update({ end_time: new Date(packTimeMs), status: 2 }); + ctx.logger.info('[Workbench._packOrder] 关闭上一个未结束任务 taskId=%d orderId=%d workbenchId=%d', + previousTask.id, previousTask.order_id, workbenchId); + } + } + + // 步骤5:查找是否已有该订单的打包任务 + let packTask = await ctx.model.PackTask.findOne({ + where: { order_id: orderId, warehouse_id: warehouseId, status: { [ctx.app.Sequelize.Op.lt]: 2 } }, + }); + + const packData = { + order_id: orderId, + warehouse_id: warehouseId, + workbench_id: workbenchId ? parseInt(workbenchId) : null, + wave_id: waveId, + wave_no: actualWaveNo, + waybill_code: null, // 后续可从 order_express 补 + pack_mode: isSandan === 0 ? 2 : 1, // 1=散单 2=团购 + status: packStatus !== undefined ? parseInt(packStatus) : 1, + pack_quantity: orderRow.items_total || 0, + start_time: packTask ? packTask.start_time : new Date(packTimeMs), + end_time: packStatus >= 2 ? new Date(packTimeMs) : null, + device_ids: deviceIds, + }; + + if (packTask) { + // 更新已有任务 + await packTask.update(packData); + ctx.logger.info('[Workbench._packOrder] 更新打包任务 taskId=%d orderId=%d', packTask.id, orderId); + } else { + packTask = await ctx.model.PackTask.create(packData); + ctx.logger.info('[Workbench._packOrder] 创建打包任务 taskId=%d orderId=%d', packTask.id, orderId); + } + + const result = { + task_id: packTask.id, + order_id: orderId, + delivery_order_code: deliveryOrderCode, + wave_no: actualWaveNo, + isSandan, + pack_mode: packData.pack_mode, + status: packData.status, + }; + + // 团购单附加波次总量 + if (isSandan === 0) { + result.batch = { wave_id: waveId, wave_no: actualWaveNo, wave_type: waveType, total_orders: totalOrders }; + } + + return result; + } + + /** + * 条码查订单:条码 → wms_order_express → 待处理/配送订单详情 + * @param {Object} params - { barcode, warehouseId } + * @returns {Promise} + */ + async _queryOrder(params) { + const { ctx } = this; + const { barcode, warehouseId: inputWarehouseId } = params; + + if (!barcode || !String(barcode).trim()) { + throw new Error('条码不能为空'); + } + if (!inputWarehouseId || !String(inputWarehouseId).trim()) { + throw new Error('仓库ID不能为空'); + } + + const normalizedBarcode = String(barcode).trim(); + const warehouseId = parseInt(inputWarehouseId); + + // 步骤1:条码 → order_id + warehouse_id(必须限制仓库) + const expressRecord = await ctx.model.OrderExpress.findOne({ + where: { + waybill_code: normalizedBarcode, + warehouse_id: warehouseId, + status: 1, + }, + attributes: ['order_id', 'warehouse_id', 'waybill_code', 'logistics_name', 'weighing_weight', 'package_material_name_snapshot'], + raw: true, + }); + + if (!expressRecord) { + throw new Error(`未找到条码 [${normalizedBarcode}] 对应的运单记录`); + } + + const { order_id: orderId, waybill_code: waybillCode } = expressRecord; + + // 步骤2:遍历 current → dispatch 分表查找订单详情 + const orderDeliveryFactory = ctx.model.OrderDeliveryFactory; + const tableOrders = [ + { label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) }, + { label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) }, + ]; + + let orderRow = null; + let sourceTable = null; + for (const entry of tableOrders) { + try { + const model = await entry.getModel(); + if (!model || typeof model.findOne !== 'function') continue; + const row = await model.findOne({ + where: { id: orderId, warehouse_id: warehouseId }, + raw: true, + }); + if (row) { + orderRow = row; + sourceTable = entry.label; + break; + } + } catch (_err) { + ctx.logger.warn('[Workbench._queryOrder] 查询表 %s 失败: %s', entry.label, _err.message); + continue; + } + } + + if (!orderRow) { + throw new Error(`未在待处理或配送表中找到订单 [id=${orderId}, warehouse=${warehouseId}]`); + } + + ctx.logger.info('[Workbench._queryOrder] 条码=%s 命中 orderId=%d source=%s', + normalizedBarcode, orderId, sourceTable); + + // 步骤3:判断波次类型(散单 vs 团购),团购需返回波次总量 + let waveType = null; + let totalBatchOrders = 0; + let isSandan = 1; // 默认散单 + + const waveId = orderRow.wave_id; + if (waveId && Number(waveId) > 0) { + try { + // 查询波次信息 + const waveBatch = await ctx.model.WaveBatch.findOne({ + where: { wave_id: waveId, warehouse_id: warehouseId }, + attributes: ['wave_id', 'wave_type', 'total_orders'], + raw: true, + }); + + if (waveBatch) { + waveType = waveBatch.wave_type; + // wave_type=1 → 团购单(isSandan=0); 其他(2=散单等) → 散单(isSandan=1) + if (Number(waveType) === 1) { + isSandan = 0; + } else { + isSandan = 1; + } + // 实时统计波次订单数 + totalBatchOrders = await this._countWaveOrders(warehouseId, waveId); + } + } catch (waveErr) { + ctx.logger.warn('[Workbench._queryOrder] 查询波次信息失败 waveId=%d: %s', waveId, waveErr.message); + } + } + + // 步骤4:查询订单商品明细 + 关联 stock 详情(带缓存) + let items = []; + try { + const getItemsModel = sourceTable === 'dispatch' + ? () => ctx.model.OrderItemsFactory.getDispatchModel(warehouseId) + : () => ctx.model.OrderItemsFactory.getCurrentModel(warehouseId); + const itemsModel = await getItemsModel(); + if (itemsModel) { + const orderItems = await itemsModel.findAll({ + where: { order_id: orderId }, + attributes: [ + 'id', 'order_id', 'item_id', 'item_code', 'item_name', + 'plan_qty', 'actual_qty', 'stock_id', 'order_line_no', + 'item_snapshot', + ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + if (orderItems.length > 0) { + // 收集所有 stock_id,批量查询 stock 详情(带缓存) + const stockIds = [ ...new Set( + orderItems.map(item => Number(item.stock_id)).filter(id => id > 0) + ) ]; + + /** @type {Map} */ + const stockMap = new Map(); + if (stockIds.length > 0) { + try { + const stockDetails = await service.systems.stockWarehouse.getStockDetails( + stockIds, + { warehouseId } + ); + for (const detail of stockDetails) { + stockMap.set(Number(detail.id), detail); + } + } catch (stockErr) { + ctx.logger.warn('[Workbench._queryOrder] 查询 stock 详情失败: %s', stockErr.message); + } + } + + // 组装 items,合并 stock 信息 + items = orderItems.map(item => { + const stockId = Number(item.stock_id); + const stock = stockMap.get(stockId) || {}; + return { + id: item.id, + order_id: item.order_id, + item_id: item.item_id, + item_code: item.item_code || stock.item_code || '', + item_name: item.item_name || stock.item_name || '', + plan_qty: item.plan_qty, + actual_qty: item.actual_qty, + stock_id: stockId, + order_line_no: item.order_line_no || '', + sku_property: stock.sku_property || '', + stock_unit: stock.stock_unit || '', + barcodes: stock.barcodes || [], + image_url: stock.image_url || '', + }; + }); + } + } + } catch (itemsErr) { + ctx.logger.warn('[Workbench._queryOrder] 查询订单商品失败: %s', itemsErr.message); + } + + const result = { + barcode: normalizedBarcode, + waybill_code: waybillCode, + isSandan, + express: { + logistics_name: expressRecord.logistics_name, + weighing_weight: expressRecord.weighing_weight, + package_material_name: expressRecord.package_material_name_snapshot || '', + }, + order: { + id: orderRow.id, + delivery_order_code: orderRow.delivery_order_code, + order_type: orderRow.order_type, + warehouse_id: orderRow.warehouse_id, + store_id: orderRow.store_id, + status: orderRow.status, + step: orderRow.step, + wave_id: orderRow.wave_id, + wave_no: orderRow.wave_no, + post_status: orderRow.post_status, + pick_status: orderRow.pick_status, + recheck_status: orderRow.recheck_status, + outbound_status: orderRow.outbound_status, + items_count: orderRow.items_count, + items_total: orderRow.items_total, + items_weight: orderRow.items_weight, + source_platform_code: orderRow.source_platform_code, + logistics_name: orderRow.logistics_name, + create_at: orderRow.create_at, + updated_at: orderRow.updated_at, + }, + items, + source_table: sourceTable, + }; + + // 团购单附加波次总量信息 + if (isSandan === 0) { + result.batch = { + wave_id: waveId, + wave_no: orderRow.wave_no, + wave_type: waveType, + total_orders: totalBatchOrders, + }; + } + + return result; + } + + /** + * 检查条码在仓库内是否已存在(排除指定ID) + * @param {string} barcode - 条码 + * @param {number} [excludeId] - 排除的工作台ID(更新时使用) + * @returns {Promise} + */ + async checkBarcodeExists(barcode, excludeId) { + const { ctx } = this; + const warehouseId = ctx.user.store_id; + + if (!barcode) return false; + + const where = { + warehouse_id: warehouseId, + barcode: String(barcode).trim(), + }; + if (excludeId) { + const { Op } = ctx.app.Sequelize; + where.id = { [Op.ne]: excludeId }; + } + + const count = await ctx.model.Workbench.count({ where }); + return count > 0; + } +} + +module.exports = WorkbenchService; From a69fd3f3934058e35ff9ae2eb8b5306f6e0c76f1 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Thu, 23 Jul 2026 17:42:28 +0800 Subject: [PATCH 119/550] =?UTF-8?q?fix(storage.entry):=20=E5=85=A5?= =?UTF-8?q?=E5=BA=93=E8=B6=85=E9=87=8F=E9=9D=99=E9=BB=98=E8=A3=81=E5=89=AA?= =?UTF-8?q?=20+=20containerList=20=E6=8C=89=E5=8F=AF=E7=94=A8=E9=87=8F?= =?UTF-8?q?=E8=BF=87=E6=BB=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. inbound_direct_log._addSingleItem: 入库数量超过计划时不再拒绝,改为静默裁剪为 maxAllowed(仅无可入数量时拒绝) 2. storage/entry.containerList: NOT EXISTS 一刀切排除改为计算 actual_quantity - SUM(已占用),只返回可用量>0的收货明细 --- app/service/systems/inbound_direct_log.js | 279 +++--- app/service/systems/storage/entry.js | 995 +++++++++++++++++++++- 2 files changed, 1131 insertions(+), 143 deletions(-) diff --git a/app/service/systems/inbound_direct_log.js b/app/service/systems/inbound_direct_log.js index d495c85..db37198 100644 --- a/app/service/systems/inbound_direct_log.js +++ b/app/service/systems/inbound_direct_log.js @@ -373,23 +373,26 @@ class InboundDirectLogService extends Service { // CREATED 人工导入允许超过计划数量 const isManualImport = entryOrder.order_status === 'CREATED' && !isBindingMode; if (!isManualImport) { - const newTotal = existingTotal + effectiveQuantity; - if (newTotal > totalPlanQty) { + const maxAllowed = totalPlanQty - existingTotal; + if (maxAllowed <= 0) { return { ok: false, error: { code: 400, - message: `入库数量超过计划:商品计划 ${totalPlanQty},已入库 ${existingTotal},本次 ${effectiveQuantity},合计 ${newTotal}`, + message: `入库数量超过计划:商品计划 ${totalPlanQty},已入库 ${existingTotal},本次 ${effectiveQuantity},合计 ${existingTotal + effectiveQuantity}`, data: { stock_id: stockId, plan_quantity: totalPlanQty, existing_quantity: existingTotal, requested_quantity: effectiveQuantity, - exceeded_by: newTotal - totalPlanQty, + exceeded_by: effectiveQuantity, }, }, }; } + if (effectiveQuantity > maxAllowed) { + effectiveQuantity = maxAllowed; + } } // 剩余可入库数 = 计划数 - max(已收货量, 已写入 direct_log 的待入库量) @@ -853,7 +856,7 @@ class InboundDirectLogService extends Service { itemId: item.item_id || '', inventoryType: item.inventory_type || 'ZP', planQty: Number(item.count) || 0, - actualQty: Number(item.count) || 0, + actualQty: stockSummary[String(item.stock_id)] || 0, })); const syncResult = await this.qimenEntrySync({ @@ -957,11 +960,18 @@ class InboundDirectLogService extends Service { transaction, }); - // 同一 stock_id 只写一次库存 - if (processedStockIds.has(String(stockId))) continue; - processedStockIds.add(String(stockId)); - if (!isBinding) { - nonBindingStockProcessed.add(String(stockId)); + // 同一 stock_id 只写一次 StockWarehouse 总库存(聚合量),但 Storage 按入库记录逐条写入 + const isStockWarehouseDone = processedStockIds.has(String(stockId)); + if (isStockWarehouseDone && !isBinding) { + // 非绑定模式:StockWarehouse 已写但 Storage 还未写,不能 continue,继续写 Storage + } else if (isStockWarehouseDone) { + continue; + } + if (!isStockWarehouseDone) { + processedStockIds.add(String(stockId)); + if (!isBinding) { + nonBindingStockProcessed.add(String(stockId)); + } } // 使用入库单号作为批次号;若有收货绑定则使用收货明细信息 @@ -972,137 +982,162 @@ class InboundDirectLogService extends Service { const batchNo = eo.entry_order_code; const inventoryType = item.inventory_type || 'ZP'; - // 从该 stock_id 的入库记录中取第一个非空 space_id,兜底 1 - const logForSpace = directLogs.find(l => String(l.stock_id) === String(stockId) && l.space_id); - const spaceId = logForSpace ? Number(logForSpace.space_id) : 1; + // StockWarehouse 总库存:每个 stock_id 聚合写入一次 + if (!isStockWarehouseDone) { + // 锁定并更新 StockWarehouse 总库存 + const stockRecord = await ctx.model.StockWarehouse.findOne({ + where: { id: stockId, is_valid: 'Y', deleted_at: null }, + lock: transaction.LOCK.UPDATE, + transaction, + }); - // 锁定并更新 StockWarehouse 总库存 - const stockRecord = await ctx.model.StockWarehouse.findOne({ - where: { id: stockId, is_valid: 'Y', deleted_at: null }, - lock: transaction.LOCK.UPDATE, - transaction, - }); + if (stockRecord) { + const beforeQuantity = Number(stockRecord.quantity) || 0; + const beforeLockedQuantity = Number(stockRecord.locked_quantity) || 0; - if (stockRecord) { - const beforeQuantity = Number(stockRecord.quantity) || 0; - const beforeLockedQuantity = Number(stockRecord.locked_quantity) || 0; + await stockRecord.increment('quantity', { by: inboundQty, transaction, silent: true }); + await stockRecord.reload({ transaction }); - await stockRecord.increment('quantity', { by: inboundQty, transaction, silent: true }); - await stockRecord.reload({ transaction }); + const afterQuantity = Number(stockRecord.quantity) || 0; + const afterLockedQuantity = Number(stockRecord.locked_quantity) || 0; - const afterQuantity = Number(stockRecord.quantity) || 0; - const afterLockedQuantity = Number(stockRecord.locked_quantity) || 0; + // 写入库存流水(聚合维度) + await ctx.service.systems.stockTransaction.create({ + transaction_type: 'INBOUND', + warehouse_id: warehouseId, + store_id: storeId, + stock_id: stockId, + quantity: inboundQty, + batch_no: batchNo, + inventory_type: inventoryType, + order_type: eo.order_type, + order_no: eo.entry_order_code, + entry_order_id: eo.id, + operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), + operator_name: ctx.user?.employees_name || '', + remark: '导入/PDA直接入库提交', + before_quantity: beforeQuantity, + after_quantity: afterQuantity, + before_locked_quantity: beforeLockedQuantity, + after_locked_quantity: afterLockedQuantity, + created_at: new Date(), + }, { transaction }); + } + } - // 写入库存流水 - await ctx.service.systems.stockTransaction.create({ + /** + * 写入 Storage 库位库存 + storage_transaction 的通用函数 + * @param {number} spaceId 库位ID + * @param {number} qty 入库数量 + * @param {number|null} rdId 收货单ID + * @param {string|null} prodDate 生产日期 + * @param {string|null} expDate 到期日期 + */ + const writeStorageRecord = async (spaceId, qty, rdId, prodDate, expDate) => { + if (qty <= 0) return; + + const sRecord = await ctx.model.Storage.findOne({ + where: { + space_id: spaceId, + stock_id: stockId, + batch_no: batchNo, + inventory_type: inventoryType, + is_enabled: 1, + delete_at: null, + }, + lock: transaction.LOCK.UPDATE, + transaction, + }); + + let sId = null; + let sBeforeQty = 0; + let sAfterQty = 0; + + if (sRecord) { + sBeforeQty = Number(sRecord.quantity) || 0; + sAfterQty = sBeforeQty + qty; + + await ctx.model.Storage.update({ + quantity: app.Sequelize.literal(`quantity + ${qty}`), + available_quantity: app.Sequelize.literal(`available_quantity + ${qty}`), + entry_order_id: eo.id, + inbound_time: new Date(), + inbound_order_no: eo.entry_order_code, + production_date: prodDate, + expiry_date: expDate, + receiving_id: rdId, + updated_at: new Date(), + }, { + where: { id: sRecord.id }, + transaction, + }); + sId = sRecord.id; + } else { + sBeforeQty = 0; + sAfterQty = qty; + + const createdStorage = await ctx.model.Storage.create({ + warehouse_id: warehouseId, + store_id: storeId, + space_id: spaceId, + stock_id: stockId, + batch_no: effectiveBatchNo, + inventory_type: inventoryType, + quantity: qty, + locked_quantity: 0, + available_quantity: qty, + inbound_time: new Date(), + inbound_order_no: eo.entry_order_code, + receiving_id: rdId, + entry_order_id: eo.id, + supplier_id: null, + supplier_batch_no: null, + production_date: prodDate, + expiry_date: expDate, + is_enabled: 1, + created_at: new Date(), + updated_at: new Date(), + }, { transaction }); + sId = createdStorage.id; + } + + // 写入库位维度库存流水 + await ctx.model.StorageTransaction.create({ transaction_type: 'INBOUND', warehouse_id: warehouseId, store_id: storeId, stock_id: stockId, - quantity: inboundQty, - batch_no: batchNo, + storage_id: sId, + space_id: spaceId, + quantity: qty, + before_quantity: sBeforeQty, + after_quantity: sAfterQty, + batch_no: effectiveBatchNo, inventory_type: inventoryType, - order_type: eo.order_type, + order_type: 'entry_order', order_no: eo.entry_order_code, - entry_order_id: eo.id, + order_id: eo.id, operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), operator_name: ctx.user?.employees_name || '', remark: '导入/PDA直接入库提交', - before_quantity: beforeQuantity, - after_quantity: afterQuantity, - before_locked_quantity: beforeLockedQuantity, - after_locked_quantity: afterLockedQuantity, created_at: new Date(), }, { transaction }); - } + }; - // 创建/更新 Storage 库位库存 - const storageRecord = await ctx.model.Storage.findOne({ - where: { - space_id: spaceId, - stock_id: stockId, - batch_no: batchNo, - inventory_type: inventoryType, - is_enabled: 1, - delete_at: null, - }, - lock: transaction.LOCK.UPDATE, - transaction, - }); - - let storageId = null; - let storageBeforeQty = 0; - let storageAfterQty = 0; - - if (storageRecord) { - storageBeforeQty = Number(storageRecord.quantity) || 0; - storageAfterQty = storageBeforeQty + inboundQty; - - await ctx.model.Storage.update({ - quantity: app.Sequelize.literal(`quantity + ${inboundQty}`), - available_quantity: app.Sequelize.literal(`available_quantity + ${inboundQty}`), - entry_order_id: eo.id, - inbound_time: new Date(), - inbound_order_no: eo.entry_order_code, - production_date: rdProductionDate, - expiry_date: rdExpiryDate, - receiving_id: rdReceivingId, - updated_at: new Date(), - }, { - where: { id: storageRecord.id }, - transaction, - }); - storageId = storageRecord.id; + if (isBinding) { + // 绑定模式:按 entryItem 维度写 Storage(与收货明细绑定,space_id 取第一条入库记录的库位) + const logForSpace = directLogs.find(l => String(l.stock_id) === String(stockId) && l.space_id); + const spaceId = logForSpace ? Number(logForSpace.space_id) : 1; + await writeStorageRecord(spaceId, inboundQty, rdReceivingId, rdProductionDate, rdExpiryDate); } else { - storageBeforeQty = 0; - storageAfterQty = inboundQty; - - const createdStorage = await ctx.model.Storage.create({ - warehouse_id: warehouseId, - store_id: storeId, - space_id: spaceId, - stock_id: stockId, - batch_no: effectiveBatchNo, - inventory_type: inventoryType, - quantity: inboundQty, - locked_quantity: 0, - available_quantity: inboundQty, - inbound_time: new Date(), - inbound_order_no: eo.entry_order_code, - receiving_id: rdReceivingId, - entry_order_id: eo.id, - supplier_id: null, - supplier_batch_no: null, - production_date: rdProductionDate, - expiry_date: rdExpiryDate, - is_enabled: 1, - created_at: new Date(), - updated_at: new Date(), - }, { transaction }); - storageId = createdStorage.id; + // 非绑定模式:按每个 InboundDirectLog 记录独立写 Storage,每条记录保有自己指定的 space_id 和 quantity + const stockDirectLogs = directLogs.filter(l => String(l.stock_id) === String(stockId) && Number(l.quantity) > 0); + for (const dlog of stockDirectLogs) { + const dlogSpaceId = dlog.space_id || 1; + const dlogQty = Number(dlog.quantity) || 0; + await writeStorageRecord(dlogSpaceId, dlogQty, null, null, null); + } } - - // 写入库位维度库存流水 - await ctx.model.StorageTransaction.create({ - transaction_type: 'INBOUND', - warehouse_id: warehouseId, - store_id: storeId, - stock_id: stockId, - storage_id: storageId, - space_id: spaceId, - quantity: inboundQty, - before_quantity: storageBeforeQty, - after_quantity: storageAfterQty, - batch_no: effectiveBatchNo, - inventory_type: inventoryType, - order_type: 'entry_order', - order_no: eo.entry_order_code, - order_id: eo.id, - operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), - operator_name: ctx.user?.employees_name || '', - remark: '导入/PDA直接入库提交', - created_at: new Date(), - }, { transaction }); } // 将 pending 绑定升级为 committed(在 InboundDirectLog 中更新状态) diff --git a/app/service/systems/storage/entry.js b/app/service/systems/storage/entry.js index 802ffd7..466187c 100644 --- a/app/service/systems/storage/entry.js +++ b/app/service/systems/storage/entry.js @@ -1,8 +1,17 @@ 'use strict'; +const crypto = require('node:crypto'); +const fs = require('node:fs'); +const fsp = require('node:fs/promises'); +const os = require('node:os'); +const path = require('node:path'); +const ExcelJS = require('exceljs'); const Service = require('egg').Service; const { parseWhereConditions } = require('../../../lib/query_condition_parser'); +const ENTRY_EXPORT_PAGE_SIZE = 200; +const ENTRY_ITEMS_FETCH_BATCH_SIZE = 100; + class EntryService extends Service { /** * 将费用记录筛选值归一化为 0/1。 @@ -1290,23 +1299,36 @@ class EntryService extends Service { return { code: 200, message: 'ok', data: { list: [], total: 0 } }; } - // 3. 排除已绑定的收货明细(wms_inbound_direct_log 中有记录且未软删除) - const notBoundCondition = app.Sequelize.literal( - 'NOT EXISTS (SELECT 1 FROM wms_inbound_direct_log erb WHERE erb.receiving_detail_id = wms_receiving_detail.id AND erb.deleted_at IS NULL)' - ); - - // 4. 查询指定商品的未绑定收货明细 + // 3. 查询指定商品的所有收货明细(不再一刀切排除已绑定,改为按可用量过滤) const details = await ctx.model.ReceivingDetail.findAll({ where: { - [app.Sequelize.Op.and]: [ - { system_product_id: stockId }, - { receiving_id: { [app.Sequelize.Op.in]: receivingIds } }, - notBoundCondition, - ], + system_product_id: stockId, + receiving_id: { [app.Sequelize.Op.in]: receivingIds }, }, raw: true, }); + // 4. 查询每个明细的已入库数量(pending + committed,与 getReceivingDetailsForBind 一致) + const detailIds = details.map(d => d.id); + const usedMap = new Map(); + if (detailIds.length > 0) { + const usedRows = await ctx.model.query( + `SELECT receiving_detail_id, COALESCE(SUM(quantity), 0) AS used_qty + FROM wms_inbound_direct_log + WHERE receiving_detail_id IN (:ids) + AND status IN ('pending', 'committed') + AND deleted_at IS NULL + GROUP BY receiving_detail_id`, + { + replacements: { ids: detailIds }, + type: ctx.model.QueryTypes.SELECT, + } + ); + for (const row of usedRows) { + usedMap.set(row.receiving_detail_id, Number(row.used_qty)); + } + } + // 5. 收集所有明细的 system_product_id,批量获取 stock 详情 const stockIdSet = new Set(); for (const d of details) { @@ -1327,16 +1349,22 @@ class EntryService extends Service { } } - // 6. 组装返回结果 - const list = details.map(detail => ({ - detail_id: detail.id, - receiving_id: detail.receiving_id, - barcode: detail.barcode || '', - product_name: detail.product_name || '', - actual_quantity: detail.actual_quantity || 0, - receiving_status: detail.receiving_status || '', - stock: stockDetailMap.get(Number(detail.system_product_id)) || null, - })); + // 6. 组装返回结果:actual_quantity 扣除已入库数量,只返回有可用量的明细 + const list = details + .map(detail => { + const used = usedMap.get(detail.id) || 0; + const available = Math.max(0, (detail.actual_quantity || 0) - used); + return { + detail_id: detail.id, + receiving_id: detail.receiving_id, + barcode: detail.barcode || '', + product_name: detail.product_name || '', + actual_quantity: available, + receiving_status: detail.receiving_status || '', + stock: stockDetailMap.get(Number(detail.system_product_id)) || null, + }; + }) + .filter(detail => detail.actual_quantity > 0); return { code: 200, @@ -1951,6 +1979,931 @@ class EntryService extends Service { }; } + /** + * 导出入库单列表及明细(两 Sheet)。 + * Sheet1: 入库单列表(wms_entry_order 关键字段) + * Sheet2: 入库单明细(wms_entry_items + wms_stock_warehouse) + * + * @param {Object} options 导出参数 + * @param {Object} [options.where] 筛选条件(与 list 一致) + * @param {Object} [options.sort] 排序参数 + * @param {Function} [options.onProgress] 进度回调 + * @return {Promise} 上传结果与统计信息 + */ + async exportEntryOrders(options = {}) { + const { ctx, app } = this; + const { Sequelize } = app; + const { Op } = Sequelize; + const safeOptions = this.isPlainObject ? (this.isPlainObject(options) ? options : {}) : (options && typeof options === 'object' ? options : {}); + const where = safeOptions.where && typeof safeOptions.where === 'object' ? { ...safeOptions.where } : {}; + const sort = safeOptions.sort && typeof safeOptions.sort === 'object' ? { ...safeOptions.sort } : {}; + const progressHandler = typeof safeOptions.onProgress === 'function' + ? safeOptions.onProgress + : async () => {}; + + const warehouseId = Number(ctx.user && ctx.user.store_id); + if (!warehouseId) { + throw new Error('用户未绑定仓库,无法导出'); + } + + const sortField = sort.sortField || 'created_at'; + const sortOrder = String(sort.sortOrder || 'DESC').toUpperCase() === 'ASC' ? 'ASC' : 'DESC'; + const validSortFields = [ + 'id', 'entry_order_code', 'order_type', 'order_status', + 'order_create_time', 'created_at', 'updated_at', 'total_order_lines', + ]; + const actualSortField = validSortFields.includes(sortField) ? sortField : 'created_at'; + + const baseWhere = { warehouse_id: warehouseId, is_enabled: 1, deleted_at: null }; + + // ---- 复用 list 的 where 构建逻辑 ---- + const normalizedWhere = { ...where }; + const { + where: parsedSourceWhere, + extraConditions, + errorMessage, + } = await this.preprocessEntryListWhere(normalizedWhere); + + if (errorMessage) { + throw new Error(errorMessage); + } + + const parsed = parseWhereConditions({ + where: parsedSourceWhere, + app, + specialFieldMap: { + quickWhere: { + bucket: 'quick', + }, + }, + }); + + if (!parsed.ok) { + throw new Error(`筛选条件解析失败: ${parsed.reason}`); + } + const parsedResult = parsed.result; + + const quickWhereInput = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere) + || parsedSourceWhere.quickWhere + || null; + const quickWhereValue = quickWhereInput && typeof quickWhereInput === 'object' + ? quickWhereInput.value + : null; + + const andConditions = [ baseWhere ]; + if (quickWhereValue !== undefined && quickWhereValue !== null && String(quickWhereValue).trim() !== '') { + const kw = String(quickWhereValue).trim(); + const receivingDetailId = Number(kw); + const escapedKw = app.model.escape(`%${kw}%`); + const orConditions = [ + { entry_order_code: { [Op.like]: `%${kw}%` } }, + { purchase_order_code: { [Op.like]: `%${kw}%` } }, + { supplier_name: { [Op.like]: `%${kw}%` } }, + { store_name: { [Op.like]: `%${kw}%` } }, + { warehouse_name: { [Op.like]: `%${kw}%` } }, + Sequelize.where(Sequelize.literal( + `EXISTS ( + SELECT 1 FROM wms_entry_order_receiving eor + JOIN wms_receiving r ON r.id = eor.receiving_id + WHERE eor.entry_order_id = wms_entry_order.id + AND eor.deleted_at IS NULL + AND r.receiving_number LIKE ${escapedKw} + )` + ), 1), + ...(Number.isFinite(receivingDetailId) && receivingDetailId > 0 ? [ + Sequelize.where(Sequelize.literal( + `EXISTS ( + SELECT 1 FROM wms_entry_order_receiving eor + JOIN wms_receiving_detail rd ON rd.receiving_id = eor.receiving_id + WHERE eor.entry_order_id = wms_entry_order.id + AND eor.deleted_at IS NULL + AND rd.id = ${receivingDetailId} + )` + ), 1), + ] : []), + ]; + andConditions.push({ [Op.or]: orConditions }); + } + + const dynamicConditions = parsedResult.dynamicConditions || []; + if (dynamicConditions.length > 0) { + andConditions.push({ [Op.and]: dynamicConditions }); + } + if (extraConditions.length > 0) { + andConditions.push({ [Op.and]: extraConditions }); + } + + const finalWhere = { [Op.and]: andConditions }; + + // ---- 分页拉取入库单列表 ---- + const pageSize = ENTRY_EXPORT_PAGE_SIZE; + const totalCount = await ctx.model.EntryOrder.count({ where: finalWhere }); + + await progressHandler({ + status: 'running', + progress: totalCount > 0 ? 10 : 90, + message: totalCount > 0 ? `已命中 ${totalCount} 条入库单,开始导出` : '未命中数据,开始生成空文件', + }); + + // 收集所有入库单 ID,供后续批量查明细 + const allEntryOrders = []; + let page = 1; + let fetchedCount = 0; + + while (fetchedCount < totalCount) { + const rows = await ctx.model.EntryOrder.findAll({ + where: finalWhere, + order: [[ actualSortField, sortOrder ]], + limit: pageSize, + offset: (page - 1) * pageSize, + raw: true, + }); + + if (!Array.isArray(rows) || rows.length === 0) { + break; + } + + allEntryOrders.push(...rows); + fetchedCount += rows.length; + page += 1; + + await progressHandler({ + status: 'running', + progress: Math.min(30, 10 + Math.round((fetchedCount / Math.max(totalCount, 1)) * 20)), + message: `正在拉取入库单列表,已完成 ${fetchedCount}/${totalCount}`, + }); + } + + // 收集所有入库单 ID + const allEntryOrderIds = allEntryOrders.map(r => Number(r.id)).filter(Boolean); + + // ---- 分批拉取入库单明细 ---- + /** @type {Map>} entry_order_id → items */ + const itemsMap = new Map(); + /** @type {Set} 所有涉及的商品 stock_id */ + const allStockIds = new Set(); + + if (allEntryOrderIds.length > 0) { + const batchSize = ENTRY_ITEMS_FETCH_BATCH_SIZE; + const totalBatches = Math.ceil(allEntryOrderIds.length / batchSize); + + for (let batchIdx = 0; batchIdx < allEntryOrderIds.length; batchIdx += batchSize) { + const batchIds = allEntryOrderIds.slice(batchIdx, batchIdx + batchSize); + + const items = await ctx.model.EntryItems.findAll({ + where: { order_id: { [Op.in]: batchIds } }, + order: [[ 'order_id', 'ASC' ], [ 'order_line_no', 'ASC' ]], + raw: true, + }); + + for (const item of items) { + const eid = Number(item.order_id); + if (!itemsMap.has(eid)) { + itemsMap.set(eid, []); + } + itemsMap.get(eid).push(item); + if (item.stock_id) { + allStockIds.add(Number(item.stock_id)); + } + } + + const currentBatch = Math.floor(batchIdx / batchSize) + 1; + await progressHandler({ + status: 'running', + progress: Math.min(50, 30 + Math.round((currentBatch / totalBatches) * 20)), + message: `正在拉取入库单明细,已完成批次 ${currentBatch}/${totalBatches}`, + }); + } + } + + // ---- 批量查询商品名称(wms_stock_warehouse) ---- + /** @type {Map} stock_id → { item_name, sku_property, item_code } */ + const stockInfoMap = new Map(); + if (allStockIds.size > 0) { + const stockIdsArr = [ ...allStockIds ]; + try { + const stockRows = await ctx.model.StockWarehouse.findAll({ + where: { id: { [Op.in]: stockIdsArr }, warehouse_id: warehouseId }, + attributes: [ 'id', 'item_code', 'item_name', 'sku_property' ], + raw: true, + }); + for (const s of stockRows) { + stockInfoMap.set(Number(s.id), { + item_code: s.item_code || '', + item_name: s.item_name || '', + sku_property: s.sku_property || '', + }); + } + } catch (err) { + ctx.logger.warn(`[exportEntryOrders] 批量查询商品信息失败: ${err.message}`); + } + } + + await progressHandler({ + status: 'running', + progress: 55, + message: '正在生成 Excel 文件...', + }); + + // ---- 生成 Excel(流式写入,两个 Sheet) ---- + const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'wms-entry-export-')); + const now = new Date(); + const dateToken = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}`; + const filename = `入库单导出_${dateToken}.xlsx`; + const filePath = path.join(tempDir, filename); + const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({ + filename: filePath, + useStyles: false, + useSharedStrings: false, + }); + + // Sheet 1: 入库单列表 + const sheet1 = workbook.addWorksheet('入库单列表'); + const entryOrderColumns = [ + { header: '入库单号', key: 'entry_order_code', width: 22 }, + { header: '业务类型', key: 'order_type', width: 10 }, + { header: '采购单号', key: 'purchase_order_code', width: 22 }, + { header: '订单状态', key: 'order_status', width: 12 }, + { header: '供应商编码', key: 'supplier_code', width: 16 }, + { header: '供应商名称', key: 'supplier_name', width: 24 }, + { header: '物流公司', key: 'logistics_name', width: 20 }, + { header: '运单号', key: 'express_code', width: 22 }, + { header: '货主', key: 'store_name', width: 24 }, + { header: '仓库', key: 'warehouse_name', width: 24 }, + { header: '总行数', key: 'total_order_lines', width: 10 }, + { header: '来源类型', key: 'source_type', width: 10 }, + { header: '状态', key: 'sync_status', width: 12 }, + { header: 'ERP备注', key: 'remark', width: 30 }, + { header: '费用记录', key: 'expense_record', width: 10 }, + { header: '预期到货时间', key: 'expect_start_time', width: 20 }, + { header: '最迟预期到货时间', key: 'expect_end_time', width: 20 }, + { header: '订单创建时间', key: 'order_create_time', width: 20 }, + { header: '创建时间', key: 'created_at', width: 20 }, + { header: '更新时间', key: 'updated_at', width: 20 }, + ]; + sheet1.columns = entryOrderColumns; + + const statusLabelMap = { + CREATING: '创建中', + CREATED: '已创建', + PENDING: '已审核', + COMPLETED: '已完成', + CANCELLED: '已作废', + }; + + const syncStatusLabelMap = { + PENDING: '待同步', + SUCCESS: '成功', + FAILED: '失败', + }; + + const normalizeCellValue = value => { + if (value === null || value === undefined) return ''; + if (value instanceof Date) return app.formatDate ? app.formatDate(value) : value.toISOString(); + return value; + }; + + const orderTypeLabelMap = { + SCRK: '收货入库', + LYRK: '领用入库', + CCRK: '残次入库', + CGRK: '采购入库', + DBRK: '调拨入库', + QTRK: '其他入库', + B2BRK: 'B2B入库', + XNRK: '虚拟入库', + SHRK: '损耗入库', + }; + + for (const row of allEntryOrders) { + sheet1.addRow({ + entry_order_code: normalizeCellValue(row.entry_order_code), + order_type: orderTypeLabelMap[row.order_type] || row.order_type || '', + purchase_order_code: normalizeCellValue(row.purchase_order_code), + order_status: statusLabelMap[row.order_status] || row.order_status || '', + supplier_code: normalizeCellValue(row.supplier_code), + supplier_name: normalizeCellValue(row.supplier_name), + logistics_name: normalizeCellValue(row.logistics_name), + express_code: normalizeCellValue(row.express_code), + store_name: normalizeCellValue(row.store_name), + warehouse_name: normalizeCellValue(row.warehouse_name), + total_order_lines: row.total_order_lines, + source_type: normalizeCellValue(row.source_type), + sync_status: syncStatusLabelMap[row.sync_status] || row.sync_status || '', + remark: normalizeCellValue(row.remark), + expense_record: row.expense_record === 1 ? '是' : (row.expense_record === 0 ? '否' : ''), + expect_start_time: normalizeCellValue(row.expect_start_time), + expect_end_time: normalizeCellValue(row.expect_end_time), + order_create_time: normalizeCellValue(row.order_create_time), + created_at: normalizeCellValue(row.created_at), + updated_at: normalizeCellValue(row.updated_at), + }).commit(); + } + sheet1.commit(); + + await progressHandler({ + status: 'running', + progress: 70, + message: '正在写入入库单明细...', + }); + + // Sheet 2: 入库单明细 + const sheet2 = workbook.addWorksheet('入库单明细'); + const entryItemColumns = [ + { header: '入库单号', key: 'entry_order_code', width: 22 }, + { header: '入库单ID', key: 'entry_order_id', width: 12 }, + { header: '行号', key: 'order_line_no', width: 8 }, + { header: '商品编码', key: 'item_code', width: 20 }, + { header: '商品名称', key: 'item_name', width: 28 }, + { header: '商品规格', key: 'sku_property', width: 24 }, + { header: '计划入库数量', key: 'plan_quantity', width: 14 }, + { header: '已收货数量', key: 'received_quantity', width: 14 }, + { header: '已通知数量', key: 'confirm_quantity', width: 14 }, + { header: '库存类型', key: 'inventory_type', width: 14 }, + { header: '外部业务编码', key: 'out_biz_code', width: 24 }, + { header: '货主编码', key: 'owner_code', width: 16 }, + { header: '商品ID', key: 'item_id', width: 12 }, + { header: '商品SKU ID', key: 'stock_id', width: 12 }, + ]; + sheet2.columns = entryItemColumns; + + // 构建 entry_order_code 映射 + const entryOrderCodeMap = new Map(); + for (const row of allEntryOrders) { + entryOrderCodeMap.set(Number(row.id), row.entry_order_code || ''); + } + + // 按入库单分页写入明细 + const itemBatchSize = ENTRY_ITEMS_FETCH_BATCH_SIZE; + let itemWrittenCount = 0; + const totalEntryOrders = allEntryOrderIds.length; + + for (let batchIdx = 0; batchIdx < allEntryOrderIds.length; batchIdx += itemBatchSize) { + const batchIds = allEntryOrderIds.slice(batchIdx, batchIdx + itemBatchSize); + + for (const eid of batchIds) { + const entryOrderCode = entryOrderCodeMap.get(eid) || ''; + const items = itemsMap.get(eid) || []; + + for (const item of items) { + const stockId = Number(item.stock_id || 0); + const stockInfo = stockInfoMap.get(stockId) || {}; + + sheet2.addRow({ + entry_order_code: entryOrderCode, + entry_order_id: eid, + order_line_no: item.order_line_no ?? '', + item_code: stockInfo.item_code || item.item_code || '', + item_name: stockInfo.item_name || '', + sku_property: stockInfo.sku_property || '', + plan_quantity: item.count ?? 0, + received_quantity: item.received_quantity ?? 0, + confirm_quantity: item.confirm_quantity ?? 0, + inventory_type: normalizeCellValue(item.inventory_type), + out_biz_code: normalizeCellValue(item.out_biz_code), + owner_code: normalizeCellValue(item.owner_code), + item_id: normalizeCellValue(item.item_id), + stock_id: item.stock_id ?? '', + }).commit(); + } + + itemWrittenCount += 1; + } + + const currentBatch = Math.floor(batchIdx / itemBatchSize) + 1; + const totalBatches = Math.ceil(totalEntryOrders / itemBatchSize); + await progressHandler({ + status: 'running', + progress: Math.min(90, 70 + Math.round((currentBatch / totalBatches) * 20)), + message: `正在写入入库单明细,已完成 ${itemWrittenCount}/${totalEntryOrders} 条入库单`, + }); + } + sheet2.commit(); + + await workbook.commit(); + + await progressHandler({ + status: 'running', + progress: 92, + message: '正在上传文件...', + }); + + // ---- 上传文件 ---- + const uploadService = ctx?.service?.systems?.upload; + if (!uploadService || typeof uploadService.uploadFile !== 'function') { + throw new Error('上传服务不可用'); + } + + const stat = await fsp.stat(filePath); + const randomToken = crypto.randomBytes(6).toString('hex'); + const uploadKey = `exports/entry/${warehouseId}/${Date.now()}_${randomToken}.xlsx`; + const uploadStream = fs.createReadStream(filePath); + uploadStream.filename = filename; + uploadStream.mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; + uploadStream.fileSize = stat.size; + + const uploadResult = await uploadService.uploadFile(uploadStream, { + key: uploadKey, + category: 'document', + mimetype: 'xls,xlsx,csv', + }); + + let fileRecord = null; + if (typeof uploadService.uploadSuccessNotify === 'function') { + fileRecord = await uploadService.uploadSuccessNotify({ + url: uploadResult.fileName, + fileKey: uploadResult.fileName, + fileName: filename, + fileType: 'document', + mimeType: uploadStream.mimeType, + fileSize: stat.size, + category: 'document', + businessType: 'entryExport', + businessId: `${warehouseId}`, + uploaderType: ctx?.user?.role || 'system_api', + uploaderDept: ctx?.user?.department || '', + }); + } + + const result = { + filename, + fileKey: uploadResult.fileName, + url: uploadResult.url || uploadResult.cdnUrl || uploadResult.cosUrl || '', + cdnUrl: uploadResult.cdnUrl || uploadResult.url || '', + cosUrl: uploadResult.cosUrl || '', + total_count: totalCount, + fileRecord: fileRecord?.data || fileRecord || null, + }; + + // 清理临时目录 + await fsp.rm(tempDir, { recursive: true, force: true }); + + await progressHandler({ + status: 'success', + progress: 100, + message: '导出完成', + result, + }); + + return result; + } + + /** + * 导出货主侧入库单列表(双 sheet:入库单列表 + 入库单明细)。 + * 复用 list 的筛选与排序语义,以货主维度(store_id)过滤,分页拉取全量数据后生成 Excel 并上传。 + * @param {Object} options 导出选项 + * @param {Object} [options.where] 筛选条件(与 listStore 一致) + * @param {Object} [options.sort] 排序参数 + * @param {Function} [options.onProgress] 进度回调 + * @return {Promise} 上传结果与统计信息 + */ + async exportStoreEntryOrders(options = {}) { + const { ctx, app } = this; + const { Sequelize } = app; + const { Op } = Sequelize; + const safeOptions = options && typeof options === 'object' ? options : {}; + const where = safeOptions.where && typeof safeOptions.where === 'object' ? { ...safeOptions.where } : {}; + const sort = safeOptions.sort && typeof safeOptions.sort === 'object' ? { ...safeOptions.sort } : {}; + const progressHandler = typeof safeOptions.onProgress === 'function' + ? safeOptions.onProgress + : async () => {}; + + const storeId = Number(ctx.user && ctx.user.store_id); + if (!storeId) { + throw new Error('用户未绑定货主,无法导出'); + } + + const sortField = sort.sortField || 'created_at'; + const sortOrder = String(sort.sortOrder || 'DESC').toUpperCase() === 'ASC' ? 'ASC' : 'DESC'; + const validSortFields = [ + 'id', 'entry_order_code', 'order_type', 'order_status', + 'order_create_time', 'created_at', 'updated_at', 'total_order_lines', + ]; + const actualSortField = validSortFields.includes(sortField) ? sortField : 'created_at'; + + const baseWhere = { store_id: storeId, is_enabled: 1, deleted_at: null }; + + // ---- 复用 listStore 的 where 构建逻辑 ---- + const normalizedWhere = { ...where }; + const { + where: parsedSourceWhere, + extraConditions, + errorMessage, + } = await this.preprocessEntryListWhere(normalizedWhere); + + if (errorMessage) { + throw new Error(errorMessage); + } + + const parsed = parseWhereConditions({ + where: parsedSourceWhere, + app, + specialFieldMap: { + quickWhere: { bucket: 'quick' }, + }, + }); + + if (!parsed.ok) { + throw new Error(`筛选条件解析失败: ${parsed.reason}`); + } + const parsedResult = parsed.result; + + const quickWhereInput = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere) + || parsedSourceWhere.quickWhere + || null; + const quickWhereValue = quickWhereInput && typeof quickWhereInput === 'object' + ? quickWhereInput.value + : null; + + const andConditions = [ baseWhere ]; + if (quickWhereValue !== undefined && quickWhereValue !== null && String(quickWhereValue).trim() !== '') { + const kw = String(quickWhereValue).trim(); + const receivingDetailId = Number(kw); + const escapedKw = app.model.escape(`%${kw}%`); + const orConditions = [ + { entry_order_code: { [Op.like]: `%${kw}%` } }, + { purchase_order_code: { [Op.like]: `%${kw}%` } }, + { supplier_name: { [Op.like]: `%${kw}%` } }, + { store_name: { [Op.like]: `%${kw}%` } }, + { warehouse_name: { [Op.like]: `%${kw}%` } }, + Sequelize.where(Sequelize.literal( + `EXISTS ( + SELECT 1 FROM wms_entry_order_receiving eor + JOIN wms_receiving r ON r.id = eor.receiving_id + WHERE eor.entry_order_id = wms_entry_order.id + AND eor.deleted_at IS NULL + AND r.receiving_number LIKE ${escapedKw} + )` + ), 1), + ...(Number.isFinite(receivingDetailId) && receivingDetailId > 0 ? [ + Sequelize.where(Sequelize.literal( + `EXISTS ( + SELECT 1 FROM wms_entry_order_receiving eor + JOIN wms_receiving_detail rd ON rd.receiving_id = eor.receiving_id + WHERE eor.entry_order_id = wms_entry_order.id + AND eor.deleted_at IS NULL + AND rd.id = ${receivingDetailId} + )` + ), 1), + ] : []), + ]; + andConditions.push({ [Op.or]: orConditions }); + } + + const dynamicConditions = parsedResult.dynamicConditions || []; + if (dynamicConditions.length > 0) { + andConditions.push({ [Op.and]: dynamicConditions }); + } + if (extraConditions.length > 0) { + andConditions.push({ [Op.and]: extraConditions }); + } + + const finalWhere = { [Op.and]: andConditions }; + + // ---- 分页拉取入库单列表 ---- + const pageSize = ENTRY_EXPORT_PAGE_SIZE; + const totalCount = await ctx.model.EntryOrder.count({ where: finalWhere }); + + await progressHandler({ + status: 'running', + progress: totalCount > 0 ? 10 : 90, + message: totalCount > 0 ? `已命中 ${totalCount} 条货主侧入库单,开始导出` : '未命中数据,开始生成空文件', + }); + + const allEntryOrders = []; + let page = 1; + let fetchedCount = 0; + + while (fetchedCount < totalCount) { + const rows = await ctx.model.EntryOrder.findAll({ + where: finalWhere, + order: [[ actualSortField, sortOrder ]], + limit: pageSize, + offset: (page - 1) * pageSize, + raw: true, + }); + + if (!Array.isArray(rows) || rows.length === 0) { + break; + } + + allEntryOrders.push(...rows); + fetchedCount += rows.length; + page += 1; + + await progressHandler({ + status: 'running', + progress: Math.min(30, 10 + Math.round((fetchedCount / Math.max(totalCount, 1)) * 20)), + message: `正在拉取货主侧入库单列表,已完成 ${fetchedCount}/${totalCount}`, + }); + } + + const allEntryOrderIds = allEntryOrders.map(r => Number(r.id)).filter(Boolean); + + // ---- 分批拉取入库单明细 ---- + /** @type {Map>} */ + const itemsMap = new Map(); + /** @type {Set} */ + const allStockIds = new Set(); + + if (allEntryOrderIds.length > 0) { + const batchSize = ENTRY_ITEMS_FETCH_BATCH_SIZE; + const totalBatches = Math.ceil(allEntryOrderIds.length / batchSize); + + for (let batchIdx = 0; batchIdx < allEntryOrderIds.length; batchIdx += batchSize) { + const batchIds = allEntryOrderIds.slice(batchIdx, batchIdx + batchSize); + + const items = await ctx.model.EntryItems.findAll({ + where: { order_id: { [Op.in]: batchIds } }, + order: [[ 'order_id', 'ASC' ], [ 'order_line_no', 'ASC' ]], + raw: true, + }); + + for (const item of items) { + const eid = Number(item.order_id); + if (!itemsMap.has(eid)) { + itemsMap.set(eid, []); + } + itemsMap.get(eid).push(item); + if (item.stock_id) { + allStockIds.add(Number(item.stock_id)); + } + } + + const currentBatch = Math.floor(batchIdx / batchSize) + 1; + await progressHandler({ + status: 'running', + progress: Math.min(50, 30 + Math.round((currentBatch / totalBatches) * 20)), + message: `正在拉取货主侧入库单明细,已完成批次 ${currentBatch}/${totalBatches}`, + }); + } + } + + // ---- 批量查询商品名称(按 store_id) ---- + /** @type {Map} */ + const stockInfoMap = new Map(); + if (allStockIds.size > 0) { + const stockIdsArr = [ ...allStockIds ]; + try { + const stockRows = await ctx.model.StockWarehouse.findAll({ + where: { id: { [Op.in]: stockIdsArr }, store_id: storeId }, + attributes: [ 'id', 'item_code', 'item_name', 'sku_property' ], + raw: true, + }); + for (const s of stockRows) { + stockInfoMap.set(Number(s.id), { + item_code: s.item_code || '', + item_name: s.item_name || '', + sku_property: s.sku_property || '', + }); + } + } catch (err) { + ctx.logger.warn(`[exportStoreEntryOrders] 批量查询商品信息失败: ${err.message}`); + } + } + + await progressHandler({ + status: 'running', + progress: 55, + message: '正在生成 Excel 文件...', + }); + + // ---- 生成 Excel ---- + const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'wms-store-entry-export-')); + const now = new Date(); + const dateToken = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}`; + const filename = `货主侧入库单导出_${dateToken}.xlsx`; + const filePath = path.join(tempDir, filename); + const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({ + filename: filePath, + useStyles: false, + useSharedStrings: false, + }); + + const normalizeCellValue = value => { + if (value === null || value === undefined) return ''; + if (value instanceof Date) return app.formatDate ? app.formatDate(value) : value.toISOString(); + return value; + }; + + const statusLabelMap = { + CREATING: '创建中', + CREATED: '已创建', + PENDING: '已审核', + COMPLETED: '已完成', + CANCELLED: '已作废', + }; + + const syncStatusLabelMap = { + PENDING: '待同步', + SUCCESS: '成功', + FAILED: '失败', + }; + + const orderTypeLabelMap = { + SCRK: '收货入库', + LYRK: '领用入库', + CCRK: '残次入库', + CGRK: '采购入库', + DBRK: '调拨入库', + QTRK: '其他入库', + B2BRK: 'B2B入库', + XNRK: '虚拟入库', + SHRK: '损耗入库', + }; + + // Sheet 1: 入库单列表(货主侧,不显示仓库字段) + const sheet1 = workbook.addWorksheet('入库单列表'); + const entryOrderColumns = [ + { header: '入库单号', key: 'entry_order_code', width: 22 }, + { header: '业务类型', key: 'order_type', width: 10 }, + { header: '采购单号', key: 'purchase_order_code', width: 22 }, + { header: '订单状态', key: 'order_status', width: 12 }, + { header: '供应商编码', key: 'supplier_code', width: 16 }, + { header: '供应商名称', key: 'supplier_name', width: 24 }, + { header: '物流公司', key: 'logistics_name', width: 20 }, + { header: '运单号', key: 'express_code', width: 22 }, + { header: '仓库', key: 'warehouse_name', width: 24 }, + { header: '总行数', key: 'total_order_lines', width: 10 }, + { header: '来源类型', key: 'source_type', width: 10 }, + { header: '状态', key: 'sync_status', width: 12 }, + { header: 'ERP备注', key: 'remark', width: 30 }, + { header: '费用记录', key: 'expense_record', width: 10 }, + { header: '预期到货时间', key: 'expect_start_time', width: 20 }, + { header: '最迟预期到货时间', key: 'expect_end_time', width: 20 }, + { header: '订单创建时间', key: 'order_create_time', width: 20 }, + { header: '创建时间', key: 'created_at', width: 20 }, + { header: '更新时间', key: 'updated_at', width: 20 }, + ]; + sheet1.columns = entryOrderColumns; + + for (const row of allEntryOrders) { + sheet1.addRow({ + entry_order_code: normalizeCellValue(row.entry_order_code), + order_type: orderTypeLabelMap[row.order_type] || row.order_type || '', + purchase_order_code: normalizeCellValue(row.purchase_order_code), + order_status: statusLabelMap[row.order_status] || row.order_status || '', + supplier_code: normalizeCellValue(row.supplier_code), + supplier_name: normalizeCellValue(row.supplier_name), + logistics_name: normalizeCellValue(row.logistics_name), + express_code: normalizeCellValue(row.express_code), + warehouse_name: normalizeCellValue(row.warehouse_name), + total_order_lines: row.total_order_lines, + source_type: normalizeCellValue(row.source_type), + sync_status: syncStatusLabelMap[row.sync_status] || row.sync_status || '', + remark: normalizeCellValue(row.remark), + expense_record: row.expense_record === 1 ? '是' : (row.expense_record === 0 ? '否' : ''), + expect_start_time: normalizeCellValue(row.expect_start_time), + expect_end_time: normalizeCellValue(row.expect_end_time), + order_create_time: normalizeCellValue(row.order_create_time), + created_at: normalizeCellValue(row.created_at), + updated_at: normalizeCellValue(row.updated_at), + }).commit(); + } + sheet1.commit(); + + await progressHandler({ + status: 'running', + progress: 70, + message: '正在写入入库单明细...', + }); + + // Sheet 2: 入库单明细 + const sheet2 = workbook.addWorksheet('入库单明细'); + const entryItemColumns = [ + { header: '入库单号', key: 'entry_order_code', width: 22 }, + { header: '入库单ID', key: 'entry_order_id', width: 12 }, + { header: '行号', key: 'order_line_no', width: 8 }, + { header: '商品编码', key: 'item_code', width: 20 }, + { header: '商品名称', key: 'item_name', width: 28 }, + { header: '商品规格', key: 'sku_property', width: 24 }, + { header: '计划入库数量', key: 'plan_quantity', width: 14 }, + { header: '已收货数量', key: 'received_quantity', width: 14 }, + { header: '已通知数量', key: 'confirm_quantity', width: 14 }, + { header: '库存类型', key: 'inventory_type', width: 14 }, + { header: '外部业务编码', key: 'out_biz_code', width: 24 }, + { header: '货主编码', key: 'owner_code', width: 16 }, + { header: '商品ID', key: 'item_id', width: 12 }, + { header: '商品SKU ID', key: 'stock_id', width: 12 }, + ]; + sheet2.columns = entryItemColumns; + + const entryOrderCodeMap = new Map(); + for (const row of allEntryOrders) { + entryOrderCodeMap.set(Number(row.id), row.entry_order_code || ''); + } + + const itemBatchSize = ENTRY_ITEMS_FETCH_BATCH_SIZE; + let itemWrittenCount = 0; + const totalEntryOrders = allEntryOrderIds.length; + + for (let batchIdx = 0; batchIdx < allEntryOrderIds.length; batchIdx += itemBatchSize) { + const batchIds = allEntryOrderIds.slice(batchIdx, batchIdx + itemBatchSize); + + for (const eid of batchIds) { + const entryOrderCode = entryOrderCodeMap.get(eid) || ''; + const items = itemsMap.get(eid) || []; + + for (const item of items) { + const stockId = Number(item.stock_id || 0); + const stockInfo = stockInfoMap.get(stockId) || {}; + + sheet2.addRow({ + entry_order_code: entryOrderCode, + entry_order_id: eid, + order_line_no: item.order_line_no ?? '', + item_code: stockInfo.item_code || item.item_code || '', + item_name: stockInfo.item_name || '', + sku_property: stockInfo.sku_property || '', + plan_quantity: item.count ?? 0, + received_quantity: item.received_quantity ?? 0, + confirm_quantity: item.confirm_quantity ?? 0, + inventory_type: normalizeCellValue(item.inventory_type), + out_biz_code: normalizeCellValue(item.out_biz_code), + owner_code: normalizeCellValue(item.owner_code), + item_id: normalizeCellValue(item.item_id), + stock_id: item.stock_id ?? '', + }).commit(); + } + + itemWrittenCount += 1; + } + + const currentBatch = Math.floor(batchIdx / itemBatchSize) + 1; + const totalBatches = Math.ceil(totalEntryOrders / itemBatchSize); + await progressHandler({ + status: 'running', + progress: Math.min(90, 70 + Math.round((currentBatch / totalBatches) * 20)), + message: `正在写入入库单明细,已完成 ${itemWrittenCount}/${totalEntryOrders} 条入库单`, + }); + } + sheet2.commit(); + + await workbook.commit(); + + await progressHandler({ + status: 'running', + progress: 92, + message: '正在上传文件...', + }); + + // ---- 上传文件 ---- + const uploadService = ctx?.service?.systems?.upload; + if (!uploadService || typeof uploadService.uploadFile !== 'function') { + throw new Error('上传服务不可用'); + } + + const stat = await fsp.stat(filePath); + const randomToken = crypto.randomBytes(6).toString('hex'); + const uploadKey = `exports/entry/store/${storeId}/${Date.now()}_${randomToken}.xlsx`; + const uploadStream = fs.createReadStream(filePath); + uploadStream.filename = filename; + uploadStream.mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; + uploadStream.fileSize = stat.size; + + const uploadResult = await uploadService.uploadFile(uploadStream, { + key: uploadKey, + category: 'document', + mimetype: 'xls,xlsx,csv', + }); + + let fileRecord = null; + if (typeof uploadService.uploadSuccessNotify === 'function') { + fileRecord = await uploadService.uploadSuccessNotify({ + url: uploadResult.fileName, + fileKey: uploadResult.fileName, + fileName: filename, + fileType: 'document', + mimeType: uploadStream.mimeType, + fileSize: stat.size, + userId: ctx.userId, + description: `货主侧入库单导出(货主${storeId}),共${totalCount}条入库单`, + }); + } + + // 清理临时文件 + try { await fsp.rm(tempDir, { recursive: true, force: true }); } catch (_) { /* ignore */ } + + const uploadInfo = fileRecord || uploadResult; + const fileUrl = typeof uploadInfo === 'object' && uploadInfo.url + ? uploadInfo.url + : (typeof uploadResult === 'object' ? uploadResult.fileName : ''); + + await progressHandler({ + status: 'running', + progress: 100, + message: '货主侧导出完成', + result: { url: fileUrl, fileKey: uploadKey }, + }); + + return { + url: fileUrl, + fileKey: uploadKey, + total: totalCount, + totalDetails: allEntryOrderIds.reduce((sum, eid) => sum + (itemsMap.get(eid) || []).length, 0), + }; + } + } module.exports = EntryService; From aedd815e17dcf6a2e5f9cfee0c775782de44bf38 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 27 Jul 2026 03:41:24 +0800 Subject: [PATCH 120/550] =?UTF-8?q?feat(order.packing):=20=E6=96=B0?= =?UTF-8?q?=E5=A2=9E=E6=89=93=E5=8C=85=E4=BB=BB=E5=8A=A1=E6=A8=A1=E5=9D=97?= =?UTF-8?q?=20list/get/setEndTime/forceRecord=20=E6=96=B9=E6=B3=95?= =?UTF-8?q?=E5=8F=8A=E8=A7=86=E9=A2=91=20CDN=20URL=20=E6=8B=BC=E6=8E=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 order.packing.list: 打包任务列表查询,支持分页/筛选/排序,关联工作台/视频/运单 - 新增 order.packing.get: 打包任务详情查询 - 新增 order.packing.setEndTime: 设置结束时间,未完成任务自动标记为已完成 - 新增 order.packing.forceRecord: 强制重新录制,推送打印服务 - pack_task_video Model status 从 TINYINT 改为 STRING(20) 匹配 DB ENUM - 视频 URL 拼接 CDN 前缀: http://w{warehouseId}-c{computerId}.o.gztbyc.com{videoPath} - 录制电脑从 wms_print_computer(is_recording=true) + Redis 在线校验获取 - 更新 methods/system.json 与 methods/changes/system.json 文档 --- app/model/pack_task_video.js | 83 +++++++ app/service/systemMethods/order/packing.js | 94 +++++++ app/service/systems/order_packing.js | 208 +++++++++++++++- methods/changes/system.json | 48 +++- methods/system.json | 270 +++++++++++++++++++-- 5 files changed, 655 insertions(+), 48 deletions(-) create mode 100644 app/model/pack_task_video.js create mode 100644 app/service/systemMethods/order/packing.js diff --git a/app/model/pack_task_video.js b/app/model/pack_task_video.js new file mode 100644 index 0000000..1296917 --- /dev/null +++ b/app/model/pack_task_video.js @@ -0,0 +1,83 @@ +'use strict'; + +module.exports = app => { + const { STRING, BIGINT, DATE } = app.Sequelize; + + const PackTaskVideo = app.model.define('pack_task_video', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键ID', + }, + pack_task_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '打包任务ID,关联 wms_pack_task.id', + }, + camera_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '摄像头设备ID,关联 wms_camera.id', + }, + video_url: { + type: STRING(500), + allowNull: false, + comment: '视频地址(录像回放URL)', + }, + status: { + type: STRING(20), + allowNull: false, + defaultValue: 'created', + comment: '状态:created-已创建 recording-录制中 completed-已完成 failed-失败', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + created_at: { + type: DATE, + allowNull: false, + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + comment: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + tableName: 'wms_pack_task_video', + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: true, + deletedAt: 'deleted_at', + comment: '打包任务视频记录表', + indexes: [ + { name: 'idx_pack_task_id', fields: [ 'pack_task_id' ] }, + { name: 'idx_camera_id', fields: [ 'camera_id' ] }, + { name: 'idx_deleted_at', fields: [ 'deleted_at' ] }, + ], + }); + + PackTaskVideo.associate = () => { + app.model.PackTaskVideo.belongsTo(app.model.PackTask, { + foreignKey: 'pack_task_id', + targetKey: 'id', + as: 'packTask', + }); + app.model.PackTaskVideo.belongsTo(app.model.Camera, { + foreignKey: 'camera_id', + targetKey: 'id', + as: 'camera', + }); + }; + + return PackTaskVideo; +}; diff --git a/app/service/systemMethods/order/packing.js b/app/service/systemMethods/order/packing.js new file mode 100644 index 0000000..cbe7487 --- /dev/null +++ b/app/service/systemMethods/order/packing.js @@ -0,0 +1,94 @@ +'use strict'; + +const MainService = require('../../main'); + +/** + * 系统方法层:order.packing(打包任务接口包装层)。 + * 主要职责:统一包装系统方法接口,处理权限、日志等公共逻辑,调用底层 service 实现业务功能。 + * 注意:当前实现仅为包装层,实际业务逻辑完全依赖底层 service 的方法实现。 + */ +class OrderPackingMethodService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list,get'; + const _noNeedLog = 'list,get'; + const _noNeedAuth = 'list,get'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 打包任务列表查询(仓库侧 system method 包装层)。 + * 按仓库维度查询打包任务,支持分页、筛选、排序。 + * + * @param {Object} data 请求体 + * @param {Object} [data.pagination] 分页参数 { page, pageSize } + * @param {Object} [data.where] 筛选条件。 + * 支持字段:status(任务状态)、pack_mode(打包模式)、waybill_code(运单号)、wave_no(波次号)、 + * order_id(订单ID)、workbench_id(工作台ID)、quickWhere(快捷搜索:波次号直接匹配 + 运单号通过express→order→wave链路解析)、 + * start_time_start / start_time_end(开始打包时间范围)。 + * @param {Object} [data.sort] 排序参数 { sortField, sortOrder } + * @return {Promise} 统一成功包装响应 + */ + async list(data = {}) { + const { service } = this; + const { pagination, sort } = data; + const { where } = this.prepareWhereContext(data, { + specialFieldMap: { + quickWhere: { + bucket: 'quick', + }, + }, + }); + const result = await service.systems.orderPacking.list(where, pagination, sort); + return this.success('ok', result); + } + + /** + * 打包任务详情查询(仓库侧 system method 包装层)。 + * + * @param {Object} data 请求体 + * @param {number} data.id 打包任务ID + * @return {Promise} 统一成功包装响应 + */ + async get(data = {}) { + const { service } = this; + const { id } = data; + const result = await service.systems.orderPacking.get({ id }); + return this.success('ok', result); + } + + /** + * 设置打包任务结束时间(仓库侧 system method 包装层)。 + * 若任务状态不是已完成,则同步更新状态为已完成。 + * 前端默认值逻辑:已有结束时间→当前时间;无结束时间→开始时间+5分钟。 + * + * @param {Object} data 请求体 + * @param {number} data.id 打包任务ID + * @param {string} data.end_time 结束时间(ISO 8601 或日期字符串) + * @return {Promise} 统一成功包装响应 + */ + async setEndTime(data = {}) { + const { service } = this; + const { id, end_time } = data; + const result = await service.systems.orderPacking.setEndTime({ id, end_time }); + return this.success('ok', result); + } + + /** + * 强制重新录制打包任务视频(仓库侧 system method 包装层)。 + * 将该任务推送到录制电脑,通过打印服务触发重新录制。 + * + * @param {Object} data 请求体 + * @param {number} data.id 打包任务ID + * @return {Promise} 统一成功包装响应 + */ + async forceRecord(data = {}) { + const { service } = this; + const { id } = data; + const result = await service.systems.orderPacking.forceRecord({ id }); + return this.success('ok', result); + } +} + +module.exports = OrderPackingMethodService; diff --git a/app/service/systems/order_packing.js b/app/service/systems/order_packing.js index 7188ddc..370f01a 100644 --- a/app/service/systems/order_packing.js +++ b/app/service/systems/order_packing.js @@ -8,6 +8,39 @@ const Service = require('egg').Service; * 数据来源:wms_pack_task 表。 */ class OrderPackingService extends Service { + /** + * 获取仓库的录制电脑 ID(带缓存)。 + * @param {number} warehouseId 仓库ID + * @return {Promise} 录制电脑ID,找不到返回 null + */ + async _getRecordingComputerId(warehouseId) { + const cacheKey = `_recordingComputer_${warehouseId}`; + if (this[cacheKey] !== undefined) { + return this[cacheKey]; + } + const row = await this.ctx.model.PrintComputer.findOne({ + where: { warehouse_id: warehouseId, is_recording: true, deleted_at: null }, + attributes: [ 'id' ], + raw: true, + }); + this[cacheKey] = row ? row.id : null; + return this[cacheKey]; + } + + /** + * 构建视频完整 URL。 + * 格式:http://w{warehouseId}-c{recordingComputerId}.o.gztbyc.com{videoPath} + * @param {number} warehouseId 仓库ID + * @param {number|null} recordingComputerId 录制电脑ID + * @param {string} videoPath 视频路径 + * @return {string} 完整 URL + */ + _buildVideoUrl(warehouseId, recordingComputerId, videoPath) { + if (!videoPath || !recordingComputerId) { + return videoPath || ''; + } + return `http://w${warehouseId}-c${recordingComputerId}.o.gztbyc.com${videoPath}`; + } /** * 打包任务列表查询(仓库侧)。 * 按仓库维度(warehouse_id)查询打包任务,支持分页、筛选、排序。 @@ -123,12 +156,25 @@ class OrderPackingService extends Service { const orderIds = [ ...new Set(expressRecords.map(r => r.order_id).filter(Boolean)) ]; if (orderIds.length > 0) { - // 查 order_delivery 获取 wave_id - const orderRecords = await ctx.model.OrderDelivery.findAll({ - where: { id: { [Op.in]: orderIds }, warehouse_id: warehouseId }, - attributes: [ 'id', 'wave_id' ], - raw: true, - }); + // 查 order_delivery 分表获取 wave_id(current + dispatch) + const orderDeliveryFactory = ctx.model.OrderDeliveryFactory; + const orderTableModels = [ + { label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) }, + { label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) }, + ]; + const orderRecords = []; + for (const entry of orderTableModels) { + try { + const model = await entry.getModel(); + if (!model) continue; + const rows = await model.findAll({ + where: { id: { [Op.in]: orderIds }, warehouse_id: warehouseId }, + attributes: [ 'id', 'wave_id' ], + raw: true, + }); + orderRecords.push(...rows); + } catch (_err) { continue; } + } // order_id → wave_id 映射 const orderWaveMap = new Map(); @@ -240,7 +286,6 @@ class OrderPackingService extends Service { model: ctx.model.PackTaskVideo, as: 'videos', attributes: [ 'id', 'video_url', 'camera_id', 'status' ], - where: { status: 1 }, required: false, include: [ { @@ -254,13 +299,14 @@ class OrderPackingService extends Service { model: ctx.model.OrderExpress, as: 'expresses', attributes: [ 'id', 'waybill_code', 'logistics_code', 'logistics_name', 'logistics_interface_name', 'platform_code', 'status' ], - where: { delete_at: null }, + where: { warehouse_id: warehouseId, delete_at: null }, required: false, }, ], }); // 扁平化输出 + const recordingComputerId = await this._getRecordingComputerId(warehouseId); const list = rows.map(row => { const plain = row.get({ plain: true }); return { @@ -270,7 +316,8 @@ class OrderPackingService extends Service { workbench_barcode: plain.workbench?.barcode || null, videos: (plain.videos || []).map(v => ({ id: v.id, - video_url: v.video_url, + video_url: this._buildVideoUrl(warehouseId, recordingComputerId, v.video_url), + status: v.status || null, camera_id: v.camera_id, camera_name: v.camera?.custom_name || v.camera?.channel_name || null, })), @@ -339,7 +386,6 @@ class OrderPackingService extends Service { model: ctx.model.PackTaskVideo, as: 'videos', attributes: [ 'id', 'video_url', 'camera_id', 'status' ], - where: { status: 1 }, required: false, include: [ { @@ -353,7 +399,7 @@ class OrderPackingService extends Service { model: ctx.model.OrderExpress, as: 'expresses', attributes: [ 'id', 'waybill_code', 'logistics_code', 'logistics_name', 'logistics_interface_name', 'platform_code', 'status' ], - where: { delete_at: null }, + where: { warehouse_id: warehouseId, delete_at: null }, required: false, }, ], @@ -364,6 +410,7 @@ class OrderPackingService extends Service { } const plain = record.get({ plain: true }); + const recordingComputerId = await this._getRecordingComputerId(warehouseId); const data = { ...plain, workbench_name: plain.workbench?.name || null, @@ -371,7 +418,8 @@ class OrderPackingService extends Service { workbench_barcode: plain.workbench?.barcode || null, videos: (plain.videos || []).map(v => ({ id: v.id, - video_url: v.video_url, + video_url: this._buildVideoUrl(warehouseId, recordingComputerId, v.video_url), + status: v.status || null, camera_id: v.camera_id, camera_name: v.camera?.custom_name || v.camera?.channel_name || null, })), @@ -389,6 +437,142 @@ class OrderPackingService extends Service { return { code: 200, message: 'ok', data }; } + + /** + * 设置打包任务结束时间。 + * 按 id + warehouse_id 查找任务,更新结束时间。 + * 若任务状态不是已完成(2),则同时将状态更新为已完成。 + * + * @param {Object} options 操作参数 + * @param {number} options.id 打包任务ID + * @param {string} options.end_time 结束时间(ISO 8601 或日期字符串) + * @return {Promise} 操作结果 + */ + async setEndTime(options = {}) { + const { ctx } = this; + const { id, end_time } = options; + + if (!id) { + return { code: 400, message: '打包任务ID不能为空', data: null }; + } + if (!end_time) { + return { code: 400, message: '结束时间不能为空', data: null }; + } + + const warehouseId = Number(ctx.user && ctx.user.store_id); + if (!warehouseId) { + return { code: 400, message: '用户未绑定仓库,无法操作打包任务', data: null }; + } + + const record = await ctx.model.PackTask.findOne({ + where: { id: Number(id), warehouse_id: warehouseId }, + }); + + if (!record) { + return { code: 404, message: '打包任务不存在或无权访问', data: null }; + } + + const updates = { end_time: new Date(end_time) }; + + // 若任务状态不是已完成(2),同步更新为已完成 + if (record.status !== 2) { + updates.status = 2; + } + + await record.update(updates); + + return { + code: 200, + message: '结束时间设置成功', + data: { + id: record.id, + end_time: updates.end_time, + status: updates.status, + }, + }; + } + + /** + * 强制重新录制打包任务视频。 + * 将任务推送到录制电脑,通过打印服务触发重新录制。 + * + * @param {Object} options 操作参数 + * @param {number} options.id 打包任务ID + * @return {Promise} 操作结果 { code, message, data } + */ + async forceRecord(options = {}) { + const { ctx } = this; + const { id } = options; + + if (!id) { + return { code: 400, message: '打包任务ID不能为空', data: null }; + } + + const warehouseId = Number(ctx.user && ctx.user.store_id); + if (!warehouseId) { + return { code: 400, message: '用户未绑定仓库,无法操作打包任务', data: null }; + } + + // 1. 查找打包任务 + const packTask = await ctx.model.PackTask.findOne({ + where: { id: Number(id), warehouse_id: warehouseId }, + }); + if (!packTask) { + return { code: 404, message: '打包任务不存在或无权访问', data: null }; + } + + // 2. 查找仓库的录制电脑 + const recordingComputer = await ctx.model.PrintComputer.findOne({ + where: { warehouse_id: warehouseId, is_recording: true, deleted_at: null }, + raw: true, + }); + if (!recordingComputer) { + return { code: 400, message: '该仓库无录制电脑,无法强制录制', data: null }; + } + + // 3. 检查录制电脑是否在线 + const redisPrinter = ctx.app.redis.get('printer'); + const onlineKey = `warehouse:${warehouseId}:printer:${recordingComputer.id}`; + const onlineInfo = await redisPrinter.get(onlineKey); + if (!onlineInfo) { + return { code: 400, message: '该仓库录制电脑不在线,无法强制录制', data: null }; + } + + // 4. 重置视频记录状态为 created,触发重新录制 + await ctx.model.PackTaskVideo.update( + { status: 'created', video_url: '' }, + { where: { pack_task_id: Number(id), deleted_at: null } } + ); + + // 5. 通知打印服务推送强制录制任务 + const printServiceUrl = ctx.app.config.printService.url; + try { + await ctx.curl(`${printServiceUrl}/record/force`, { + method: 'POST', + contentType: 'json', + data: { + pack_task_id: Number(id), + warehouse_id: warehouseId, + computer_id: recordingComputer.id, + camera_ids: packTask.device_ids || [], + }, + dataType: 'json', + timeout: 10000, + }); + } catch (err) { + ctx.logger.warn(`通知打印服务强制录制 pack_task_id=${id} 失败: ${err.message}`); + return { code: 500, message: `通知打印服务失败: ${err.message}`, data: null }; + } + + return { + code: 200, + message: '强制录制任务已推送', + data: { + pack_task_id: Number(id), + computer_id: recordingComputer.id, + }, + }; + } } module.exports = OrderPackingService; diff --git a/methods/changes/system.json b/methods/changes/system.json index 3f26575..b6c7084 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,28 @@ [ + { + "version": "2026.07.27-system-01", + "date": "2026-07-27", + "type": "added", + "summary": "新增 order.packing 打包任务模块:list/get 查询 + setEndTime 设置结束时间,含视频 CDN URL 拼接与状态回写", + "methods": [ + "order.packing.list", + "order.packing.get", + "order.packing.setEndTime", + "order.packing.forceRecord" + ], + "notes": [ + "新增 order.packing.list:按仓库维度查询打包任务列表,支持分页/筛选/排序,关联工作台、视频和运单信息。", + "新增 order.packing.get:按 id + warehouse_id 查询单条打包任务详情。", + "新增 order.packing.setEndTime:设置打包任务结束时间,入参 id + end_time;若任务状态不是已完成(2)则同步更新为已完成。", + "新增 order.packing.forceRecord:强制重新录制打包任务视频,入参 id;校验录制电脑在线后重置视频状态并推送打印服务。", + "前端默认值逻辑:若任务已有 end_time 则打开时默认为当前时间,否则默认为 start_time + 5分钟。", + "视频 URL 自动拼接 CDN 域名前缀:http://w{warehouseId}-c{recordingComputerId}.o.gztbyc.com{videoPath};录制电脑从 wms_print_computer 按 is_recording=true 获取。", + "视频响应新增 status 字段(created/recording/completed/failed),与数据库 ENUM 保持一致。", + "pack_task_video Model 的 status 字段从 TINYINT 改为 STRING(20) 以匹配 DB ENUM 迁移。", + "forceRecord 通过打印服务 /record/force 推送录制任务,传入 pack_task_id、warehouse_id、computer_id、camera_ids。" + ], + "module": "order.packing" + }, { "version": "2026.07.10-system-01", "date": "2026-07-10", @@ -147,12 +171,12 @@ { "version": "2026.06.16-system-03", "date": "2026-06-16", - "summary": "order.wave.waveStrategyFallbackOrderList 响应新增 items_weight(总重量kg)和 weight_type(重量类型)字段", + "summary": "order.wave.waveStrategyFallbackOrderList 响应新增 items_weight(总重量g)和 weight_type(重量类型)字段", "methods": [ "order.wave.waveStrategyFallbackOrderList" ], "notes": [ - "响应 list 每项新增字段 items_weight (number|null):订单总重量(kg),来自 wms_order.items_weight,为 null 时返回 null。", + "响应 list 每项新增字段 items_weight (number|null):订单总重量(g),来自 wms_order.items_weight,为 null 时返回 null。", "响应 list 每项新增字段 weight_type (string):重量类型中文标签,来自 wms_order.weight_type 经 formatWeightTypeLabel 转换;取值:常规/轻货/重货/冷链(对应 DB 值 0/1/2/3)。" ], "type": "updated", @@ -161,12 +185,12 @@ { "version": "2026.06.16-system-04", "date": "2026-06-16", - "summary": "order.wave.singleOrderFetchList 响应新增 items_weight(总重量kg)字段", + "summary": "order.wave.singleOrderFetchList 响应新增 items_weight(总重量g)字段", "methods": [ "order.wave.singleOrderFetchList" ], "notes": [ - "响应 list 每项新增字段 items_weight (number|null):订单总重量(kg),取组内首单 items_weight;组内订单 items_hash 相同重量一致。", + "响应 list 每项新增字段 items_weight (number|null):订单总重量(g),取组内首单 items_weight;组内订单 items_hash 相同重量一致。", "为 null 时返回 null。" ], "type": "updated", @@ -3648,13 +3672,13 @@ { "version": "2026.06.16-system-01", "date": "2026-06-16", - "summary": "新增 order.recheckOrder.queryRecheckOrderSingleList:散单复核列表接口,响应新增 items_weight(总重量kg)和 weight_type(重量类型)字段", + "summary": "新增 order.recheckOrder.queryRecheckOrderSingleList:散单复核列表接口,响应新增 items_weight(总重量g)和 weight_type(重量类型)字段", "methods": [ "order.recheckOrder.queryRecheckOrderSingleList" ], "notes": [ "新增方法 order.recheckOrder.queryRecheckOrderSingleList,为 recheckOrderList 散单模式的独立入口。", - "响应 list 每项新增字段 items_weight (DECIMAL(10,2)):订单总重量(kg),来自 wms_order.items_weight,为 null 时返回 null。", + "响应 list 每项新增字段 items_weight (DECIMAL(10,2)):订单总重量(g),来自 wms_order.items_weight,为 null 时返回 null。", "响应 list 每项新增字段 weight_type (string):重量类型中文标签,来自 wms_order.weight_type 经 formatWeightTypeLabel 转换;取值:常规/轻货/重货/冷链(对应 DB 值 0/1/2/3)。" ], "type": "added", @@ -3663,16 +3687,16 @@ { "version": "2026.06.16-system-02", "date": "2026-06-16", - "summary": "为 order.wave.groupOrderFetchList / waveStrategyFallbackOrderList / singleOrderFetchList 响应新增 items_weight(总重量kg)和 weight_type(重量类型)字段", + "summary": "为 order.wave.groupOrderFetchList / waveStrategyFallbackOrderList / singleOrderFetchList 响应新增 items_weight(总重量g)和 weight_type(重量类型)字段", "methods": [ "order.wave.groupOrderFetchList", "order.wave.waveStrategyFallbackOrderList", "order.wave.singleOrderFetchList" ], "notes": [ - "order.wave.groupOrderFetchList:响应 list 每项新增 items_weight (number|null):订单总重量(kg),取组内首单 items_weight;组内订单 items_hash 相同重量一致。", - "order.wave.waveStrategyFallbackOrderList:响应 list 每项新增 items_weight (number|null):订单总重量(kg),来自 wms_order.items_weight;新增 weight_type (string):重量类型中文标签,取值:常规/轻货/重货/冷链(对应 DB 值 0/1/2/3)。", - "order.wave.singleOrderFetchList:响应 list 每项新增 items_weight (number|null):订单总重量(kg),取组内首单 items_weight;组内订单 items_hash 相同重量一致。", + "order.wave.groupOrderFetchList:响应 list 每项新增 items_weight (number|null):订单总重量(g),取组内首单 items_weight;组内订单 items_hash 相同重量一致。", + "order.wave.waveStrategyFallbackOrderList:响应 list 每项新增 items_weight (number|null):订单总重量(g),来自 wms_order.items_weight;新增 weight_type (string):重量类型中文标签,取值:常规/轻货/重货/冷链(对应 DB 值 0/1/2/3)。", + "order.wave.singleOrderFetchList:响应 list 每项新增 items_weight (number|null):订单总重量(g),取组内首单 items_weight;组内订单 items_hash 相同重量一致。", "所有新增字段均为可选(required=false),为 null 时返回 null。" ], "type": "updated", @@ -3875,12 +3899,12 @@ { "version": "2026.06.19-system-01", "date": "2026-06-19", - "summary": "order.recheckOrder.scanOrder 响应 list[] 新增 items_weight(订单商品总重量kg)和 suggested_package_material(推荐包材)字段", + "summary": "order.recheckOrder.scanOrder 响应 list[] 新增 items_weight(订单商品总重量g)和 suggested_package_material(推荐包材)字段", "methods": [ "order.recheckOrder.scanOrder" ], "notes": [ - "响应 list 每项新增 items_weight (number|null):订单商品总重量(kg),来源于 wms_order_delivery.items_weight。散单模式每个订单对象包含,团购模式每个波次对象包含(取波次内首个正常订单的重量,为 null 时返回 0)。", + "响应 list 每项新增 items_weight (number|null):订单商品总重量(g),来源于 wms_order_delivery.items_weight。散单模式每个订单对象包含,团购模式每个波次对象包含(取波次内首个正常订单的重量,为 null 时返回 0)。", "响应 list 每项新增 suggested_package_material (object|null):推荐包材信息,根据订单商品结构(items_hash + items_crc)匹配 wms_package_material_item_relation 历史绑定记录,按 bind_count 降序取最优匹配。若 items_hash 为空或无匹配记录则为 null。包含子字段:id、code、name、spec、type、weight、length、width、height、bind_count。", "同步更新 method description 和 list 字段 description,补充新增字段的说明。" ], diff --git a/methods/system.json b/methods/system.json index 8f9590d..0e5f33a 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1,8 +1,8 @@ { "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", - "version": "0.3.6", - "updatedAt": "2026-07-17", + "version": "0.3.7", + "updatedAt": "2026-07-27", "headers": [ { "name": "platform", @@ -123,7 +123,7 @@ "type": "string|number|object", "required": true, "source": "body", - "description": "修改值,类型依 method 而定:brand_name/packing_requirements/stock_unit 为 string(<=255 字符);prohibited_id 为 number(整数);gross_weight 为 number(正数,可含小数);managementFlags 为 object,必须包含 is_sn_mgmt/is_shelf_life_mgmt/is_batch_mgmt,值为 'Y' 或 'N'" + "description": "修改值,类型依 method 而定:brand_name/packing_requirements/stock_unit 为 string(<=255 字符);prohibited_id 为 number(整数);gross_weight 为 number(正整数,单位 g);managementFlags 为 object,必须包含 is_sn_mgmt/is_shelf_life_mgmt/is_batch_mgmt,值为 'Y' 或 'N'" }, { "name": "values", @@ -2142,7 +2142,7 @@ "type": "number|string", "required": true, "source": "body", - "description": "称重重量(kg),必填,必须大于 0,最多支持 3 位小数。" + "description": "称重重量(g),必填,必须大于 0,必须为正整数。" } ], "response": [ @@ -2162,7 +2162,7 @@ "name": "weighing_weight", "type": "number", "required": true, - "description": "已写入的称重重量(kg)。" + "description": "已写入的称重重量(g)。" }, { "name": "wave_no", @@ -2186,7 +2186,7 @@ "name": "total_weight", "type": "number", "required": false, - "description": "所有拆单重量累加(kg)。团购批量模式返回。" + "description": "所有拆单重量累加(g)。团购批量模式返回。" }, { "name": "split_count", @@ -2224,7 +2224,7 @@ }, { "code": 400, - "message": "weighing_weight 格式非法,最多支持 3 位小数" + "message": "weighing_weight 格式非法,必须为正整数(单位 g)" }, { "code": 400, @@ -5348,7 +5348,7 @@ "name": "list", "type": "array", "required": true, - "description": "统一列表输出。散单模式(list_type=single)有波次信息时:扁平订单数组;无波次信息时退回单订单详情模式(每项含 detail、items、expresses、logs)。团购模式(list_type=group):波次视图数组(每项含 wave_id、wave_no、wave_type、wave_status、total_orders、processed_orders、creator、create_time、update_time、order_count、pick_mode、box_no、order_ids、orders_detail、stocks[])。所有模式的 list[] 每项均附带 items_weight(订单商品总重量,单位 kg)与 suggested_package_material(推荐包材信息,无推荐时为 null)。", + "description": "统一列表输出。散单模式(list_type=single)有波次信息时:扁平订单数组;无波次信息时退回单订单详情模式(每项含 detail、items、expresses、logs)。团购模式(list_type=group):波次视图数组(每项含 wave_id、wave_no、wave_type、wave_status、total_orders、processed_orders、creator、create_time、update_time、order_count、pick_mode、box_no、order_ids、orders_detail、stocks[])。所有模式的 list[] 每项均附带 items_weight(订单商品总重量,单位 g)与 suggested_package_material(推荐包材信息,无推荐时为 null)。", "children": [ { "name": "order_id", @@ -5724,7 +5724,7 @@ { "name": "items_weight", "type": "number|null", - "description": "[全模式] 订单商品总重量(kg),来源于 wms_order_delivery.items_weight。散单模式每个订单对象包含,团购模式每个波次对象包含(取波次内首个正常订单的重量)" + "description": "[全模式] 订单商品总重量(g),来源于 wms_order_delivery.items_weight。散单模式每个订单对象包含,团购模式每个波次对象包含(取波次内首个正常订单的重量)" }, { "name": "suggested_package_material", @@ -5759,7 +5759,7 @@ { "name": "weight", "type": "number", - "description": "包材自身重量(kg)" + "description": "包材自身重量(g)" }, { "name": "length", @@ -6401,6 +6401,228 @@ } ] }, + { + "groupName": "订单打包模块", + "module": "order.packing", + "list": [ + { + "method": "order.packing.list", + "description": "打包任务列表查询。按仓库维度查询打包任务,支持分页、筛选、排序。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "description": "分页参数 { page, pageSize },默认 page=1, pageSize=20", + "children": [ + { "name": "page", "type": "number", "required": false, "description": "页码" }, + { "name": "pageSize", "type": "number", "required": false, "description": "每页条数" } + ] + }, + { + "name": "sort", + "type": "object", + "required": false, + "description": "排序参数 { sortField, sortOrder }", + "children": [ + { "name": "sortField", "type": "string", "required": false, "description": "排序字段,支持:id、order_id、workbench_id、wave_id、pack_quantity、pack_mode、status、start_time、end_time、create_time、update_time" }, + { "name": "sortOrder", "type": "string", "required": false, "description": "排序方向:ASC / DESC,默认 DESC" } + ] + }, + { + "name": "where", + "type": "object", + "required": false, + "description": "筛选条件", + "children": [ + { "name": "status", "type": "number", "required": false, "description": "任务状态:0=待处理 1=打包中 2=已完成 3=异常" }, + { "name": "pack_mode", "type": "number", "required": false, "description": "打包模式:1=散单 2=团购" }, + { "name": "waybill_code", "type": "string", "required": false, "description": "运单号(模糊匹配)" }, + { "name": "wave_no", "type": "string", "required": false, "description": "波次号(模糊匹配)" }, + { "name": "order_id", "type": "number", "required": false, "description": "订单ID(精确匹配)" }, + { "name": "workbench_id", "type": "number", "required": false, "description": "工作台ID(精确匹配)" }, + { "name": "quickWhere", "type": "string", "required": false, "description": "快捷搜索:波次号模糊匹配 + 运单号通过 express→order→wave 链路解析" }, + { "name": "start_time_start", "type": "string", "required": false, "description": "开始打包时间范围起始(ISO 8601)" }, + { "name": "start_time_end", "type": "string", "required": false, "description": "开始打包时间范围结束(ISO 8601)" } + ] + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "打包任务列表,每项含 id、order_id、warehouse_id、workbench_id、wave_id、wave_no、waybill_code、pack_quantity、item_quantity、sku_count、pack_mode、status、start_time、end_time、operator_text、device_ids、remark、meta、create_time、update_time、workbench_name、workbench_type、workbench_barcode、videos[]、expresses[]" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息,含 page、pageSize、total、totalPages、hasPrevious、hasNext" + } + ], + "errors": [] + }, + { + "method": "order.packing.get", + "description": "打包任务详情查询。按 id + warehouse_id 查询单条打包任务记录,含工作台、视频和运单关联信息。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "打包任务ID" + } + ], + "response": [ + { + "name": "data", + "type": "object", + "required": true, + "description": "打包任务详情,含 id、order_id、warehouse_id、workbench_id、wave_id、wave_no、waybill_code、pack_quantity、item_quantity、sku_count、pack_mode、status、start_time、end_time、operator_text、device_ids、remark、meta、create_time、update_time、workbench_name、workbench_type、workbench_barcode、videos[]、expresses[]" + } + ], + "errors": [ + { + "code": 400, + "description": "参数校验失败(如缺少 id)" + }, + { + "code": 404, + "description": "打包任务不存在或无权访问" + } + ] + }, + { + "method": "order.packing.setEndTime", + "description": "设置打包任务结束时间。若任务状态不是已完成(2),则同步更新状态为已完成。前端默认值:若任务已有结束时间则默认为当前时间,否则默认为开始时间+5分钟。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "打包任务ID" + }, + { + "name": "end_time", + "type": "string", + "required": true, + "description": "结束时间(ISO 8601 格式,如 2026-07-27T11:00:00.000Z)。前端默认值:若任务已有结束时间→当前时间;无结束时间→开始时间+5分钟" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "打包任务ID" + }, + { + "name": "end_time", + "type": "string", + "required": true, + "description": "更新后的结束时间" + }, + { + "name": "status", + "type": "number", + "required": true, + "description": "更新后的任务状态" + } + ], + "errors": [ + { + "code": 400, + "description": "参数校验失败(如缺少 id 或 end_time、用户未绑定仓库)" + }, + { + "code": 404, + "description": "打包任务不存在或无权访问" + } + ] + }, + { + "method": "order.packing.forceRecord", + "description": "强制重新录制打包任务视频。将任务推送到录制电脑,通过打印服务触发重新录制。内部会重置视频状态为 created 并清空 video_url。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "打包任务ID" + } + ], + "response": [ + { + "name": "pack_task_id", + "type": "number", + "required": true, + "description": "打包任务ID" + }, + { + "name": "computer_id", + "type": "number", + "required": true, + "description": "录制电脑ID" + } + ], + "errors": [ + { + "code": 400, + "description": "参数校验失败(如缺少 id、用户未绑定仓库、无录制电脑、录制电脑不在线)" + }, + { + "code": 404, + "description": "打包任务不存在或无权访问" + }, + { + "code": 500, + "description": "通知打印服务失败" + } + ] + } + ] + }, { "groupName": "订单波次模块", "module": "order.wave", @@ -7639,7 +7861,7 @@ "name": "list", "type": "array", "required": true, - "description": "分组列表,每项包含 item_detail、item_detail_machine、item_detail_machine_snapshot、item_snapshot、group、group_count、items_total、items_weight(总重量kg,取组内首单 items_weight)、store_id、store_ids、logistics_name、distinguish_express、first_order_time、last_order_time、status_summary 等字段;若指定 return_order_ids=true 则额外包含 order_ids" + "description": "分组列表,每项包含 item_detail、item_detail_machine、item_detail_machine_snapshot、item_snapshot、group、group_count、items_total、items_weight(总重量g,取组内首单 items_weight)、store_id、store_ids、logistics_name、distinguish_express、first_order_time、last_order_time、status_summary 等字段;若指定 return_order_ids=true 则额外包含 order_ids" }, { "name": "pagination", @@ -7806,7 +8028,7 @@ { "name": "items_weight", "type": "number", - "description": "订单总重量(kg),来自 wms_order.items_weight,为 null 时返回 null" + "description": "订单总重量(g),来自 wms_order.items_weight,为 null 时返回 null" }, { "name": "weight_type", @@ -7927,7 +8149,7 @@ "name": "list", "type": "array", "required": true, - "description": "散单候选分组列表,每项包含 item_detail、item_detail_machine、item_detail_machine_snapshot、item_snapshot、group、group_count、items_total、items_weight(总重量kg,取组内首单 items_weight)、store_id、store_ids、logistics_name、distinguish_express、first_order_time、last_order_time、status_summary 等字段;返回的 group_count 均小于 same_order_quantity(或仓库配置的 min_group_order_fetch_quantity);若指定 return_order_ids=true 则额外包含 order_ids" + "description": "散单候选分组列表,每项包含 item_detail、item_detail_machine、item_detail_machine_snapshot、item_snapshot、group、group_count、items_total、items_weight(总重量g,取组内首单 items_weight)、store_id、store_ids、logistics_name、distinguish_express、first_order_time、last_order_time、status_summary 等字段;返回的 group_count 均小于 same_order_quantity(或仓库配置的 min_group_order_fetch_quantity);若指定 return_order_ids=true 则额外包含 order_ids" }, { "name": "pagination", @@ -10853,7 +11075,7 @@ { "name": "items_weight", "type": "number", - "description": "重量" + "description": "重量(单位 g)" } ] }, @@ -15952,7 +16174,7 @@ "type": "string|number|object", "required": true, "source": "body", - "description": "修改值,类型依 method 而定:brand_name/packing_requirements/stock_unit 为 string(<=255 字符);prohibited_id 为 number(整数);gross_weight 为 number(正数,可含小数);managementFlags 为 object,必须包含 is_sn_mgmt/is_shelf_life_mgmt/is_batch_mgmt,值为 'Y' 或 'N'" + "description": "修改值,类型依 method 而定:brand_name/packing_requirements/stock_unit 为 string(<=255 字符);prohibited_id 为 number(整数);gross_weight 为 number(正整数,单位 g);managementFlags 为 object,必须包含 is_sn_mgmt/is_shelf_life_mgmt/is_batch_mgmt,值为 'Y' 或 'N'" }, { "name": "values", @@ -18725,7 +18947,7 @@ "name": "receiving.details.*.box_weight", "type": "number", "required": false, - "description": "实测箱重(单位与系统重量一致,如 kg)" + "description": "实测箱重(单位与系统重量一致,如 g)" } ], "errors": [ @@ -19392,7 +19614,7 @@ "name": "data.details.*.box_weight", "type": "number", "required": false, - "description": "实测箱重(单位与系统重量一致,如 kg),默认 0" + "description": "实测箱重(单位与系统重量一致,如 g),默认 0" } ], "errors": [] @@ -19473,12 +19695,12 @@ { "name": "box_weight", "type": "number", - "description": "箱重" + "description": "箱重(单位 g)" }, { "name": "weight", "type": "number", - "description": "商品重量" + "description": "商品重量(单位 g)" }, { "name": "barcode", @@ -19778,14 +20000,14 @@ "type": "number", "required": false, "source": "body", - "description": "实测箱重(单位与系统重量一致,如 kg)" + "description": "实测箱重(单位与系统重量一致,如 g)" }, { "name": "weight", "type": "number", "required": false, "source": "body", - "description": "毛重/重量" + "description": "毛重/重量(单位 g)" } ], "response": [ @@ -19835,7 +20057,7 @@ "name": "data.box_weight", "type": "number", "required": false, - "description": "实测箱重(单位与系统重量一致,如 kg)" + "description": "实测箱重(单位与系统重量一致,如 g)" }, { "name": "data.updated_at", @@ -19892,7 +20114,7 @@ "params": [], "response": [], "notes": [ - "完成收货时会发送通知:通知 payload 或 metadata 将在每条明细中携带 box_remainder(箱内剩余数量/零散件数,number)与 box_weight(实测箱重,number,单位同系统重量,例如 kg)。新增字段为可选,旧客户端可忽略。" + "完成收货时会发送通知:通知 payload 或 metadata 将在每条明细中携带 box_remainder(箱内剩余数量/零散件数,number)与 box_weight(实测箱重,number,单位同系统重量,例如 g)。新增字段为可选,旧客户端可忽略。" ], "errors": [] } @@ -26295,7 +26517,7 @@ "type": "number", "required": false, "source": "body", - "description": "重量" + "description": "重量(单位 g)" }, { "name": "cost_price", From 7ff7285222d1cac3d7dcf919f85e7ffb704658e3 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 27 Jul 2026 03:45:54 +0800 Subject: [PATCH 121/550] =?UTF-8?q?feat(stock.transaction):=20=E6=96=B0?= =?UTF-8?q?=E5=A2=9E=20UNLOCK=20=E7=B1=BB=E5=9E=8B=EF=BC=8C=E5=8F=96?= =?UTF-8?q?=E6=B6=88=E9=94=81=E5=AE=9A=E6=97=B6=E5=86=99=E5=85=A5=20UNLOCK?= =?UTF-8?q?=20=E8=80=8C=E9=9D=9E=20OUTBOUND?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - stock_transaction 枚举新增 UNLOCK(取消锁定) - stock_store 取消锁定时写 UNLOCK 流水 - 迁移: 20260711160000-add-unlock-to-wms-stock-transaction --- app/model/stock_transaction.js | 4 +- app/service/systems/stock_store.js | 324 ++++++++++++++---- ...000-add-unlock-to-wms-stock-transaction.js | 27 ++ 3 files changed, 288 insertions(+), 67 deletions(-) create mode 100644 database/migrations/20260711160000-add-unlock-to-wms-stock-transaction.js diff --git a/app/model/stock_transaction.js b/app/model/stock_transaction.js index 46f1508..9fc9d84 100644 --- a/app/model/stock_transaction.js +++ b/app/model/stock_transaction.js @@ -11,9 +11,9 @@ module.exports = app => { comment: '主键ID', }, transaction_type: { - type: ENUM('INBOUND', 'OUTBOUND', 'LOCK'), + type: ENUM('INBOUND', 'OUTBOUND', 'LOCK', 'UNLOCK'), allowNull: false, - comment: '出入库类型:INBOUND入库 OUTBOUND出库 LOCK锁定', + comment: '出入库类型:INBOUND入库 OUTBOUND出库 LOCK锁定 UNLOCK取消锁定', }, warehouse_id: { type: BIGINT(20).UNSIGNED, diff --git a/app/service/systems/stock_store.js b/app/service/systems/stock_store.js index 4c36ea3..e5da1a7 100644 --- a/app/service/systems/stock_store.js +++ b/app/service/systems/stock_store.js @@ -151,8 +151,8 @@ class stockStoreService extends Service { width: parseFloat(stockData.width) || 0, height: parseFloat(stockData.height) || 0, volume: parseFloat(stockData.volume) || 0, - grossWeight: parseFloat(stockData.gross_weight) || 0, - netWeight: parseFloat(stockData.net_weight) || 0, + grossWeight: parseFloat(stockData.gross_weight) || 0, // 单位 g,Qimen 接口输出 + netWeight: parseFloat(stockData.net_weight) || 0, // 单位 g,Qimen 接口输出 // 分类信息 categoryId: stockData.category_id || 0, @@ -732,9 +732,9 @@ class stockStoreService extends Service { // 写入流水(除非显式跳过) const skipLog = meta.skipTransactionLog === true; if (!skipLog && ctx.service && ctx.service.systems && ctx.service.systems.stockTransaction) { - // 锁定操作使用 LOCK 类型,释放操作使用 OUTBOUND + // 锁定操作使用 LOCK 类型,释放操作(如取消订单)使用 UNLOCK await ctx.service.systems.stockTransaction.create({ - transaction_type: isLocking ? 'LOCK' : 'OUTBOUND', + transaction_type: isLocking ? 'LOCK' : 'UNLOCK', warehouse_id: stockRecord.warehouse_id, store_id: stockRecord.store_id, stock_id: stockId, @@ -1589,7 +1589,7 @@ class stockStoreService extends Service { * @param {string} sortParams.sortOrder - 排序方式,默认'DESC' * @return {Promise} 返回查询结果 */ - async getWarehouseStock(where, pageParams = {}, sortParams = {}) { + async getWarehouseStock(where, pageParams = {}, sortParams = {}, externalWarehouseId = 0, externalStoreId = 0) { const { ctx, app, @@ -1601,6 +1601,15 @@ class stockStoreService extends Service { Op, } = Sequelize; + // 仓库ID:优先使用外部传入,否则取当前用户上下文 + const warehouseId = Number.isFinite(externalWarehouseId) && externalWarehouseId > 0 + ? externalWarehouseId + : ctx.user.store_id; + // 货主ID:外部传入时按货主维度查询(不限定仓库) + const storeId = Number.isFinite(externalStoreId) && externalStoreId > 0 + ? externalStoreId + : 0; + try { // 设置默认参数 const { @@ -1631,16 +1640,30 @@ class stockStoreService extends Service { where: {}, }; // 添加默认条件 - queryOptions.where[Op.and] = [{ - warehouse_id: ctx.user.store_id, - }, - { - is_valid: 'Y', - }, - { - deleted_at: null, - }, - ]; + if (storeId > 0) { + // 按货主维度查询(不限定仓库) + queryOptions.where[Op.and] = [{ + store_id: storeId, + }, + { + is_valid: 'Y', + }, + { + deleted_at: null, + }, + ]; + } else { + queryOptions.where[Op.and] = [{ + warehouse_id: warehouseId, + }, + { + is_valid: 'Y', + }, + { + deleted_at: null, + }, + ]; + } barcodeQueryOptions.where[Op.and] = []; prohibitedQueryOptions.where[Op.and] = []; storeOutStockQueryOptions.where[Op.and] = []; @@ -1675,6 +1698,9 @@ class stockStoreService extends Service { bucket: 'storeOutStock', field: 'stock_id', }, + keyword: { + bucket: 'keyword', + }, }, }); @@ -1691,12 +1717,6 @@ class stockStoreService extends Service { hasPrevious: false, hasNext: false, }, - summary: { - total_quantity: 0, - total_locked: 0, - total_available: 0, - total_items: 0, - }, }, message: `筛选条件解析失败: ${parsed.reason}`, }; @@ -1726,6 +1746,22 @@ class stockStoreService extends Service { boundItemValue = rawConditionsByField.has_bound_item.value; } + // keyword 快捷搜索:模糊匹配商品编码/名称/货物编码 + const keywordInput = rawConditionsByField.keyword || null; + const keywordValue = keywordInput && typeof keywordInput === 'object' + ? keywordInput.value + : keywordInput; + if (keywordValue !== undefined && keywordValue !== null && String(keywordValue).trim() !== '') { + const kw = `%${String(keywordValue).trim()}%`; + queryOptions.where[Op.and].push({ + [Op.or]: [ + { item_code: { [Op.like]: kw } }, + { item_name: { [Op.like]: kw } }, + { goods_code: { [Op.like]: kw } }, + ], + }); + } + if (dynamicConditions.length > 0) { queryOptions.where[Op.and].push({ [Op.and]: dynamicConditions, @@ -1838,12 +1874,6 @@ class stockStoreService extends Service { hasPrevious: false, hasNext: false, }, - summary: { - total_quantity: 0, - total_locked: 0, - total_available: 0, - total_items: 0, - }, }, message: '查询成功', }; @@ -1861,12 +1891,16 @@ class stockStoreService extends Service { // 处理排序 const validSortFields = [ 'id', 'item_code', 'item_name', 'quantity', 'locked_quantity', - 'tag_price', 'retail_price', 'create_at', 'update_at', + 'tag_price', 'retail_price', 'create_at', 'update_at', 'available_quantity', ]; const actualSortField = validSortFields.includes(sortField) ? sortField : 'create_at'; const actualSortOrder = sortOrder.toUpperCase() === 'ASC' ? 'ASC' : 'DESC'; - queryOptions.order.push([ actualSortField, actualSortOrder ]); + if (actualSortField === 'available_quantity') { + queryOptions.order.push([ Sequelize.literal('(quantity - locked_quantity)'), actualSortOrder ]); + } else { + queryOptions.order.push([ actualSortField, actualSortOrder ]); + } // 计算分页偏移量 const offset = (page - 1) * pageSize; @@ -1881,12 +1915,41 @@ class stockStoreService extends Service { ); // 构建 include 数组 - const includes = [ - ctx.model.StoreWarehouse.buildStoreStockInclude({ - warehouseId: ctx.user.store_id, + let storeStockInclude; + + if (storeId > 0) { + // 按货主维度查询:确保 store_warehouse 关联同时匹配 store_id 和 warehouse_id,避免一对多导致行重复 + storeStockInclude = { + model: ctx.model.StoreWarehouse, + as: 'store_stock', + attributes: [ 'warehouse_remask' ], + where: { + store_id: storeId, + warehouse_use_status: 1, + [Op.and]: Sequelize.where( + Sequelize.col('stock_warehouse.warehouse_id'), + '=', + Sequelize.col('store_stock.warehouse_id') + ), + }, + required: false, + include: [{ + model: ctx.model.Store, + as: 'warehouse', + attributes: [ 'company_name' ], + required: false, + }], + }; + } else { + storeStockInclude = ctx.model.StoreWarehouse.buildStoreStockInclude({ + warehouseId, required: true, attributes: [ 'store_remask' ], - }), + }); + } + + const includes = [ + storeStockInclude, { ...prohibitedQueryOptions, model: ctx.model.ProhibitedType, @@ -1968,21 +2031,23 @@ class stockStoreService extends Service { barcodeMap.get(sid).push(bc); } - // 按 business_id 分组图片(有图片即认为 is_images=Y) - const imageStockIdSet = new Set(); + // 按 stock_id 分组图片 + const imageMap = new Map(); for (const row of imageRows) { const sid = Number(row.business_id); const url = (row['file.file_url'] && String(row['file.file_url']).trim()) || ''; - if (url) { - imageStockIdSet.add(sid); + if (!url) continue; + if (!imageMap.has(sid)) { + imageMap.set(sid, []); } + imageMap.get(sid).push(url); } for (const item of data) { const sid = item.id; stockDetailsMap.set(sid, { barcodes: barcodeMap.get(sid) || [], - images: [], + images: imageMap.get(sid) || [], }); } } @@ -1997,8 +2062,18 @@ class stockStoreService extends Service { const stockDetail = stockDetailsMap.get(item.id); const itemBarcodes = stockDetail ? stockDetail.barcodes : []; const itemImages = stockDetail ? stockDetail.images : []; + // 货主维度:仓库备注兜底仓库主体名 + let warehouseRemask = ''; + if (storeId > 0) { + warehouseRemask = (item['store_stock.warehouse_remask'] || '') + || (item['store_stock.warehouse.company_name'] || ''); + delete item['store_stock.warehouse_remask']; + delete item['store_stock.warehouse']; + delete item['store_stock.warehouse.company_name']; + } return { ...item, + ...(storeId > 0 ? { warehouse_remask: warehouseRemask } : {}), barcodes: itemBarcodes, images: itemImages, available_quantity: availableQuantity, @@ -2011,20 +2086,6 @@ class stockStoreService extends Service { }; }); - // 添加汇总信息 - const summary = { - total_quantity: data.reduce((sum, item) => sum + item.quantity, 0), - total_locked: data.reduce((sum, item) => sum + item.locked_quantity, 0), - total_available: data.reduce((sum, item) => sum + Math.max(0, item.quantity - item - .locked_quantity), 0), - total_items: data.length, - // 如果有条码查询,添加匹配统计 - ...(hasBarcodeCondition && { - barcode_matched_count: matchedStockIds.length, - barcode_search_value: parsedBarcodeInput ? parsedBarcodeInput.value : null, - }), - }; - return { code: 200, data: { @@ -2037,7 +2098,6 @@ class stockStoreService extends Service { hasPrevious, hasNext, }, - summary, queryInfo: { conditions: normalizedWhere, sortField: actualSortField, @@ -2062,12 +2122,6 @@ class stockStoreService extends Service { hasPrevious: false, hasNext: false, }, - summary: { - total_quantity: 0, - total_locked: 0, - total_available: 0, - total_items: 0, - }, }, message: `查询失败: ${error.message}`, }; @@ -2197,6 +2251,131 @@ class stockStoreService extends Service { }); } + /** + * 导出外仓商品列表。 + * 说明:复用 getWarehouseStock 的外部货主维度筛选语义,分页拉取全量数据后生成 Excel 并上传。 + * @param {Object} where 筛选条件 + * @param {Object} sortParams 排序参数 + * @param {string} [sortParams.sortField] 排序字段 + * @param {string} [sortParams.sortOrder] 排序方向(ASC|DESC) + * @param {number} [externalWarehouseId=0] 外部仓库ID(0 表示按货主维度查) + * @param {number} [externalStoreId=0] 外部货主ID + * @return {Promise} 导出上传结果(含 url/fileKey 等) + */ + async exportExternalWarehouseStock(where = {}, sortParams = {}, externalWarehouseId = 0, externalStoreId = 0) { + const { ctx } = this; + const warehouseId = externalWarehouseId > 0 ? externalWarehouseId : (ctx.user && ctx.user.store_id ? ctx.user.store_id : 'common'); + const pageSize = 500; + let page = 1; + let hasNext = true; + const rows = []; + + while (hasNext) { + const pageResult = await this.getWarehouseStock(where, { + page, + pageSize, + }, sortParams, externalWarehouseId, externalStoreId); + + if (!pageResult || pageResult.code !== 200) { + throw new Error(pageResult && pageResult.message ? pageResult.message : '导出外仓商品失败'); + } + + const list = pageResult.data && Array.isArray(pageResult.data.list) ? pageResult.data.list : []; + + // 收集可能的 storeIds,用于回退查询 store_remask(优先取 item.store_id,其次 item['store_warehouse.store_id']) + const storeIds = []; + for (const item of list) { + const sid = item.store_id || item['store_warehouse.store_id']; + if (sid && !storeIds.includes(Number(sid))) { + storeIds.push(Number(sid)); + } + } + + // 查询 StoreWarehouse 获取 store_remask(如果可用) + const storeMap = new Map(); + try { + if (storeIds.length > 0 && ctx.model && ctx.model.StoreWarehouse) { + const { Op } = ctx.app.Sequelize; + const storeWhere = { store_id: { [Op.in]: storeIds } }; + if (externalWarehouseId > 0) { + storeWhere.warehouse_id = externalWarehouseId; + } + const storeRows = await ctx.model.StoreWarehouse.findAll({ + attributes: [ 'store_id', 'store_remask' ], + where: storeWhere, + raw: true, + }); + for (const r of storeRows || []) { + storeMap.set(Number(r.store_id), r.store_remask); + } + } + } catch (e) { + ctx && ctx.logger && ctx.logger.warn && ctx.logger.warn('[exportExternalWarehouseStock] 查询 StoreWarehouse 失败', e && e.message); + } + + for (const item of list) { + const storeId = Number(item.store_id || item['store_warehouse.store_id'] || 0); + const storeRemask = item.store_remask || item['store_warehouse.store_remask'] || storeMap.get(storeId) || ''; + rows.push({ + id: item.id, + item_code: item.item_code, + goods_code: item.goods_code || '', + item_name: item.item_name, + brand_name: item.brand_name || '', + sku_property: item.sku_property || '', + stock_unit: item.stock_unit || '', + tag_price: item.tag_price || '', + retail_price: item.retail_price || '', + gross_weight: item.gross_weight || '', + store_remask: storeRemask, + barcodes: Array.isArray(item.barcodes) ? item.barcodes.join(',') : '', + quantity: item.quantity, + locked_quantity: item.locked_quantity, + available_quantity: item.available_quantity, + lock_rate_display: item.lock_rate_display, + create_at_display: item.create_at_display, + update_at_display: item.update_at_display, + }); + } + + hasNext = Boolean(pageResult.data && pageResult.data.pagination && pageResult.data.pagination.hasNext); + page += 1; + } + + const now = new Date(); + const dateToken = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}${String(now.getMilliseconds()).padStart(3, '0')}`; + + return await ctx.service.systems.excel.generateAndUpload({ + filename: `外仓商品导出_${dateToken}.xlsx`, + dir: `exports/stock/warehouse/${warehouseId}`, + category: 'document', + sheets: [{ + name: '外仓商品', + columns: [ + { header: 'SKU', key: 'id' }, + { header: '商品编码', key: 'item_code' }, + { header: '货物编码', key: 'goods_code' }, + { header: '商品名称', key: 'item_name' }, + { header: '品牌', key: 'brand_name' }, + { header: '规格', key: 'sku_property' }, + { header: '库存单位', key: 'stock_unit' }, + { header: '标价', key: 'tag_price' }, + { header: '零售价', key: 'retail_price' }, + { header: '毛重', key: 'gross_weight' }, + { header: '货主', key: 'store_remask' }, + { header: '条码', key: 'barcodes' }, + { header: '库存', key: 'quantity' }, + { header: '锁定库存', key: 'locked_quantity' }, + { header: '可用库存', key: 'available_quantity' }, + { header: '锁定率', key: 'lock_rate_display' }, + { header: '创建时间', key: 'create_at_display' }, + { header: '更新时间', key: 'update_at_display' }, + ], + rows, + }], + }); + } + /** * 构建Sequelize查询条件 * @param {string} fieldKey - 字段键名 @@ -2394,10 +2573,10 @@ class stockStoreService extends Service { }; } else if (method === 'gross_weight') { - // 毛重应该是数字 - const updateValue = parseFloat(value); - if (isNaN(updateValue) || updateValue < 0) { - return { message: '毛重必须是有效的正数', code: 405 }; + // 毛重必须为正整数(单位 g) + const updateValue = parseInt(value, 10); + if (isNaN(updateValue) || updateValue < 0 || !Number.isInteger(Number(value))) { + return { message: '毛重必须是有效的正整数(单位 g)', code: 405 }; } updateData = { gross_weight: updateValue, @@ -2555,7 +2734,8 @@ class stockStoreService extends Service { const { stock_id = null, store_id = null, page = 1, pageSize = 20, item_code = '', item_name = '', } = data || {}; - const warehouseId = ctx.user.store_id; + // 优先使用 systemMethods 层校验后传入的 warehouse_id + const warehouseId = Number(data._warehouseId || 0) || ctx.user.store_id; let barcodes = []; let warehouseStock = null; let total = 0; @@ -2649,12 +2829,26 @@ class stockStoreService extends Service { }), ]); } + // 批量查询奇门应用名称 + const appKeys = [...new Set(barcodes.map(item => item.app_key).filter(Boolean))]; + const qimenAppMap = new Map(); + if (appKeys.length > 0) { + const qimenApps = await ctx.model.QimenApp.findAll({ + where: { app_key: appKeys }, + attributes: [ 'app_key', 'name' ], + raw: true, + }); + for (const app of qimenApps) { + qimenAppMap.set(app.app_key, app.name || ''); + } + } + const results = barcodes.map(item => { return { app_key: item.app_key, create_from: item.create_from === 'qimen' ? '奇门' : 'API', id: item.id, - app_name: item.app_key, + app_name: qimenAppMap.get(item.app_key) || item.app_key, item_code: item.item_code, stock_id: item['warehouse_stock.id'], hasBind: !!item.stock_id, diff --git a/database/migrations/20260711160000-add-unlock-to-wms-stock-transaction.js b/database/migrations/20260711160000-add-unlock-to-wms-stock-transaction.js new file mode 100644 index 0000000..614be53 --- /dev/null +++ b/database/migrations/20260711160000-add-unlock-to-wms-stock-transaction.js @@ -0,0 +1,27 @@ +'use strict'; + +/** + * 为 wms_stock_transaction.transaction_type ENUM 增加 UNLOCK。 + * UNLOCK:库存释放流水(如取消订单释放创建锁)。 + */ +module.exports = { + async up(queryInterface) { + const { sequelize } = queryInterface; + await sequelize.query(` + ALTER TABLE wms_stock_transaction + MODIFY COLUMN transaction_type ENUM( + 'INBOUND', 'OUTBOUND', 'LOCK', 'UNLOCK' + ) NOT NULL COMMENT '出入库类型:INBOUND入库 OUTBOUND出库 LOCK锁定 UNLOCK解锁' + `); + }, + + async down(queryInterface) { + const { sequelize } = queryInterface; + await sequelize.query(` + ALTER TABLE wms_stock_transaction + MODIFY COLUMN transaction_type ENUM( + 'INBOUND', 'OUTBOUND', 'LOCK' + ) NOT NULL COMMENT '出入库类型:INBOUND入库 OUTBOUND出库 LOCK锁定' + `); + }, +}; From 19c3fe09a7847b80ffdddb146cc30cab39430260 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 27 Jul 2026 03:46:07 +0800 Subject: [PATCH 122/550] =?UTF-8?q?refactor(weight):=20=E9=87=8D=E9=87=8F?= =?UTF-8?q?=E5=AD=97=E6=AE=B5=E7=BB=9F=E4=B8=80=E4=B8=BA=20INTEGER(g)?= =?UTF-8?q?=EF=BC=8C=E5=8F=96=E4=BB=A3=20DECIMAL(kg)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 8 个 model 重量字段类型 DECIMAL→INTEGER,注释 kg→g - order_express 称重校验改为正整数(g) - delivery_order 手动单查 StockStore + warehouse 称重毛重 - openapi.json 毛重/净重描述 kg→g - 迁移: 20260725120000-unify-weight-fields-to-int-g - 脚本: update-stock-warehouse-weight.cjs --- app/model/location_space.js | 9 +- app/model/order_delivery.js | 6 +- app/model/order_express.js | 5 +- app/model/package_material.js | 5 +- app/model/package_material_item_relation.js | 4 +- app/model/receiving_detail.js | 11 +- app/model/stock_store.js | 18 +- app/model/stock_warehouse.js | 14 +- app/service/systems/delivery_order.js | 46 ++- app/service/systems/order_express.js | 18 +- ...0725120000-unify-weight-fields-to-int-g.js | 171 +++++++++++ methods/openapi.json | 4 +- package.json | 2 + script/update-stock-warehouse-weight.cjs | 277 ++++++++++++++++++ 14 files changed, 531 insertions(+), 59 deletions(-) create mode 100644 database/migrations/20260725120000-unify-weight-fields-to-int-g.js create mode 100644 script/update-stock-warehouse-weight.cjs diff --git a/app/model/location_space.js b/app/model/location_space.js index 1355d5b..fe29b50 100644 --- a/app/model/location_space.js +++ b/app/model/location_space.js @@ -81,9 +81,10 @@ module.exports = app => { comment: '体积(m³)', }, max_weight: { - type: DECIMAL(10, 2), + type: INTEGER(11), allowNull: true, - comment: '最大承重(kg)', + defaultValue: 0, + comment: '最大承重(g)', }, space_status: { type: ENUM('AVAILABLE', 'OCCUPIED', 'RESERVED', 'MAINTENANCE', 'DISABLED'), @@ -110,10 +111,10 @@ module.exports = app => { comment: '当前库存数量', }, current_weight: { - type: DECIMAL(10, 2), + type: INTEGER(11), allowNull: true, defaultValue: 0, - comment: '当前重量(kg)', + comment: '当前重量(g)', }, current_volume: { type: DECIMAL(10, 2), diff --git a/app/model/order_delivery.js b/app/model/order_delivery.js index 8b76074..efb37d1 100644 --- a/app/model/order_delivery.js +++ b/app/model/order_delivery.js @@ -391,10 +391,10 @@ module.exports = app => { comment: '商品总数', }, items_weight: { - type: DECIMAL(10, 2), + type: INTEGER(11), allowNull: false, - defaultValue: 0.00, - comment: '总重量(kg)', + defaultValue: 0, + comment: '总重量(g)', }, items_hash: { type: CHAR(32), diff --git a/app/model/order_express.js b/app/model/order_express.js index 4e932fc..383fed1 100644 --- a/app/model/order_express.js +++ b/app/model/order_express.js @@ -133,9 +133,10 @@ module.exports = app => { comment: '包材名称快照', }, weighing_weight: { - type: DECIMAL(10, 3), + type: INTEGER(11), allowNull: true, - comment: '称重重量(kg)', + defaultValue: 0, + comment: '称重重量(g)', }, }, { tableName: 'wms_order_express', diff --git a/app/model/package_material.js b/app/model/package_material.js index 7911c25..15f9e35 100644 --- a/app/model/package_material.js +++ b/app/model/package_material.js @@ -57,9 +57,10 @@ module.exports = app => { comment: '高度(cm)', }, weight: { - type: DECIMAL(10, 3), + type: INTEGER(11), allowNull: true, - comment: '重量(kg)', + defaultValue: 0, + comment: '重量(g)', }, cost_price: { type: DECIMAL(10, 2), diff --git a/app/model/package_material_item_relation.js b/app/model/package_material_item_relation.js index 8eb8e03..55f64d7 100644 --- a/app/model/package_material_item_relation.js +++ b/app/model/package_material_item_relation.js @@ -72,9 +72,9 @@ module.exports = app => { comment: '高(cm)快照', }, weight: { - type: DECIMAL(10, 2), + type: INTEGER(11), defaultValue: 0, - comment: '重量(kg)快照', + comment: '重量(g)快照', }, bind_count: { type: INTEGER.UNSIGNED, diff --git a/app/model/receiving_detail.js b/app/model/receiving_detail.js index 5ff72ee..6dafaef 100644 --- a/app/model/receiving_detail.js +++ b/app/model/receiving_detail.js @@ -105,7 +105,10 @@ module.exports = app => { type: DECIMAL(10, 2), }, weight: { - type: INTEGER, + type: INTEGER(11), + allowNull: true, + defaultValue: 0, + comment: '重量(g)', }, box_remainder: { type: INTEGER, @@ -114,10 +117,10 @@ module.exports = app => { comment: '箱余数', }, box_weight: { - type: DECIMAL(10, 2), + type: INTEGER(11), allowNull: false, - defaultValue: '0.00', - comment: '箱重量(kg)', + defaultValue: 0, + comment: '箱重量(g)', }, }, { tableName: 'wms_receiving_detail', diff --git a/app/model/stock_store.js b/app/model/stock_store.js index 03b6a11..3dcce32 100644 --- a/app/model/stock_store.js +++ b/app/model/stock_store.js @@ -130,22 +130,16 @@ module.exports = app => { comment: '体积', }, gross_weight: { - type: DECIMAL(10, 2), + type: INTEGER(11), allowNull: true, - defaultValue: 0.00, - validate: { - min: 0, - }, - comment: '毛重', + defaultValue: 0, + comment: '毛重(g)', }, net_weight: { - type: DECIMAL(10, 2), + type: INTEGER(11), allowNull: true, - defaultValue: 0.00, - validate: { - min: 0, - }, - comment: '净重', + defaultValue: 0, + comment: '净重(g)', }, category_id: { type: INTEGER(11), diff --git a/app/model/stock_warehouse.js b/app/model/stock_warehouse.js index 1244787..696db1b 100644 --- a/app/model/stock_warehouse.js +++ b/app/model/stock_warehouse.js @@ -72,14 +72,14 @@ module.exports = app => { comment: '体积', }, gross_weight: { - type: DECIMAL(10, 2), - defaultValue: 0.00, - comment: '毛重', + type: INTEGER(11), + defaultValue: 0, + comment: '毛重(g)', }, net_weight: { - type: DECIMAL(10, 2), - defaultValue: 0.00, - comment: '净重', + type: INTEGER(11), + defaultValue: 0, + comment: '净重(g)', }, item_type: { type: STRING(10), @@ -170,10 +170,12 @@ module.exports = app => { box_gross_weight: { type: INTEGER(11), defaultValue: 0, + comment: '箱毛重(g)', }, box_net_weight: { type: INTEGER(11), defaultValue: 0, + comment: '箱净重(g)', }, box_height: { type: DECIMAL(10, 2), diff --git a/app/service/systems/delivery_order.js b/app/service/systems/delivery_order.js index ae7c1c1..2c87614 100644 --- a/app/service/systems/delivery_order.js +++ b/app/service/systems/delivery_order.js @@ -1180,15 +1180,19 @@ class DeliveryOrderService extends Service { continue; } let wms_stock = null; - // 手工单:调用方直接传入 stockId 时跳过 stock_store 查表,直接使用 + // 手工单:调用方直接传入 stockId 时需查 StockStore 获取完整信息(含 gross_weight) if (line.stockId && line.stockId > 0) { - wms_stock = { - id: line.stockId, - stock_id: line.stockId, - item_name: line.itemName || '', - item_code: line.itemCode || '', - gross_weight: 0, - }; + wms_stock = await app.model.StockStore.findByPk(line.stockId, { transaction }); + if (!wms_stock) { + // 降级:查不到记录时用调用方传入的字段构造最小对象 + wms_stock = { + id: line.stockId, + stock_id: line.stockId, + item_name: line.itemName || '', + item_code: line.itemCode || '', + gross_weight: 0, + }; + } } else if (!line.itemId) { // 查找唯一键(appKey 为空时不作为条件,兼容内部手动建单场景) const stockWhere = { @@ -1242,6 +1246,24 @@ class DeliveryOrderService extends Service { // ===== Sort: 按 stockId 升序排序,保证所有事务加锁顺序一致,从根本上消除死锁 ===== resolvedItems.sort((a, b) => a.stockId - b.stockId); + // ===== 批量查询 wms_stock_warehouse 获取仓库侧称重毛重 ===== + const stockIds = [...new Set(resolvedItems.map(item => item.stockId).filter(Boolean))]; + const warehouseWeightMap = new Map(); + if (stockIds.length > 0) { + const warehouseRecords = await app.model.StockWarehouse.findAll({ + where: { id: stockIds }, + attributes: ['id', 'gross_weight'], + transaction, + raw: true, + }); + for (const record of warehouseRecords) { + const gw = parseFloat(record.gross_weight) || 0; + if (gw > 0) { + warehouseWeightMap.set(record.id, gw); + } + } + } + // ===== Phase 2: 锁定阶段(按排序后顺序逐个加锁)===== for (const item of resolvedItems) { const lockResult = await ctx.service.systems.stockStore.lockItemStorages( @@ -1260,7 +1282,11 @@ class DeliveryOrderService extends Service { const totalQtyForStock = (stockQuantityMap.get(item.stockId) || 0) + item.planQty; stockQuantityMap.set(item.stockId, totalQtyForStock); - const weight = parseFloat(item.wms_stock.gross_weight) || 0; + // 优先取 wms_stock_warehouse.gross_weight(仓库称重),其次取 wms_stock_store.gross_weight + const warehouseWeight = warehouseWeightMap.get(item.stockId); + const weight = (warehouseWeight != null && warehouseWeight > 0) + ? warehouseWeight + : (parseFloat(item.wms_stock.gross_weight) || 0); stockWeightMap.set(item.stockId, weight); // 所有检查通过,准备订单行数据 @@ -1319,8 +1345,6 @@ class DeliveryOrderService extends Service { return sum + (weight * qty); }, 0); source_order_codes = new Set(lineData.map(line => line.source_order_code).filter(code => code)); // 订单来源去重集合 - // 格式化重量(保留2位小数) - total_weight = parseFloat(total_weight.toFixed(2)); ctx.logger.debug('[订单统计信息]', { orderId, diff --git a/app/service/systems/order_express.js b/app/service/systems/order_express.js index 642f303..ba0b4f5 100644 --- a/app/service/systems/order_express.js +++ b/app/service/systems/order_express.js @@ -199,9 +199,9 @@ class OrderExpressService extends Service { /** * 规范化并校验称重重量。 * - * 允许最多 3 位小数,且必须大于 0。 + * 必须为正整数(单位 g),且必须大于 0。 * - * @param {number|string} weighingWeight 称重重量。 + * @param {number|string} weighingWeight 称重重量(g)。 * @return {number} 合法重量数值。 */ normalizeWeighingWeight(weighingWeight) { @@ -210,8 +210,8 @@ class OrderExpressService extends Service { } const normalizedWeightText = String(weighingWeight).trim(); - if (!/^\d+(?:\.\d{1,3})?$/.test(normalizedWeightText)) { - throw this.createBusinessError('weighing_weight 格式非法,最多支持 3 位小数', 400); + if (!/^\d+$/.test(normalizedWeightText)) { + throw this.createBusinessError('weighing_weight 格式非法,必须为正整数(单位 g)', 400); } const normalizedWeight = Number(normalizedWeightText); @@ -263,7 +263,7 @@ class OrderExpressService extends Service { * @param {Object} payload 入参对象。 * @param {number|string} payload.orderId 订单ID。 * @param {string} [payload.waybillCode] 运单号,多运单场景必填。 - * @param {number|string} payload.weighingWeight 称重重量(kg)。 + * @param {number|string} payload.weighingWeight 称重重量(g)。 * @return {Promise} 单订单返回 {order_id, waybill_code, weighing_weight, items_weight}; * 团购批量返回 {wave_id, wave_no, weighing_weight, total_weight, split_count, splits, store_name, sys_logistics_name, items_weight}。 */ @@ -645,9 +645,7 @@ class OrderExpressService extends Service { }); } const entry = splitMap.get(bk); - entry.weighing_weight = Number( - (entry.weighing_weight + Number(row.weighing_weight || 0)).toFixed(3) - ); + entry.weighing_weight = entry.weighing_weight + Number(row.weighing_weight || 0); // 优先取非空的 waybill_code 作为该拆单的代表运单号 if (!entry.waybill_code && row.waybill_code) { entry.waybill_code = row.waybill_code; @@ -655,9 +653,7 @@ class OrderExpressService extends Service { } const splits = [ ...splitMap.values() ]; - const totalWeight = Number( - splits.reduce((sum, s) => sum + s.weighing_weight, 0).toFixed(3) - ); + const totalWeight = splits.reduce((sum, s) => sum + s.weighing_weight, 0); // split_count:仅统计 waybill_code 不为空的 business_key const splitCount = splits.filter(s => s.waybill_code !== null).length; diff --git a/database/migrations/20260725120000-unify-weight-fields-to-int-g.js b/database/migrations/20260725120000-unify-weight-fields-to-int-g.js new file mode 100644 index 0000000..5d3c35a --- /dev/null +++ b/database/migrations/20260725120000-unify-weight-fields-to-int-g.js @@ -0,0 +1,171 @@ +'use strict'; + +/** + * 统一所有重量字段为 INT 类型,单位统一为 g(克)。 + * + * 说明:原字段注释/类型写错(注释标 kg 实际存的是 g), + * 数据本身已为克,迁移只做类型转换 + 注释修正,不做数值缩放。 + * + * 涉及表/字段: + * wms_location_space : max_weight, current_weight (DECIMAL → INT) + * wms_order_delivery_100000* : items_weight (DECIMAL → INT) + * wms_order_express : weighing_weight (DECIMAL(10,3) → INT) + * wms_package_material : weight (DECIMAL(10,3) → INT) + * wms_package_material_item_relation: weight (DECIMAL → INT) + * wms_receiving_detail : box_weight (DECIMAL → INT) + * wms_receiving_detail : weight (已为INT, 仅更新注释) + * wms_stock_store : gross_weight, net_weight (DECIMAL → INT) + * wms_stock_warehouse : gross_weight, net_weight (DECIMAL → INT) + * wms_stock_warehouse : box_gross_weight, box_net_weight (已为INT, 仅更新注释) + */ + +module.exports = { + async up(queryInterface, Sequelize) { + // ===================== wms_location_space ===================== + await queryInterface.sequelize.query( + "ALTER TABLE wms_location_space MODIFY COLUMN max_weight INT(11) DEFAULT 0 COMMENT '最大承重(g)'" + ); + await queryInterface.sequelize.query( + "ALTER TABLE wms_location_space MODIFY COLUMN current_weight INT(11) DEFAULT 0 COMMENT '当前重量(g)'" + ); + + // ===================== wms_order_delivery 分表 ===================== + const orderDeliveryTables = [ + 'wms_order_delivery_100000', + 'wms_order_delivery_100000_dispatch', + 'wms_order_delivery_100000_history', + 'wms_order_delivery_100000_outsourced', + 'wms_order_delivery_1000028', + 'wms_order_delivery_1000028_dispatch', + 'wms_order_delivery_1000028_history', + 'wms_order_delivery_1000028_outsourced', + ]; + + for (const table of orderDeliveryTables) { + await queryInterface.sequelize.query( + `ALTER TABLE \`${table}\` MODIFY COLUMN items_weight INT(11) NOT NULL DEFAULT 0 COMMENT '总重量(g)'` + ); + } + + // ===================== wms_order_express ===================== + await queryInterface.sequelize.query( + "ALTER TABLE wms_order_express MODIFY COLUMN weighing_weight INT(11) DEFAULT 0 COMMENT '称重重量(g)'" + ); + + // ===================== wms_package_material ===================== + await queryInterface.sequelize.query( + "ALTER TABLE wms_package_material MODIFY COLUMN weight INT(11) DEFAULT 0 COMMENT '重量(g)'" + ); + + // ===================== wms_package_material_item_relation ===================== + await queryInterface.sequelize.query( + "ALTER TABLE wms_package_material_item_relation MODIFY COLUMN weight INT(11) DEFAULT 0 COMMENT '重量(g)快照'" + ); + + // ===================== wms_receiving_detail ===================== + // weight: 已为 INT(g),仅补注释 + await queryInterface.sequelize.query( + "ALTER TABLE wms_receiving_detail MODIFY COLUMN weight INT(11) DEFAULT 0 COMMENT '重量(g)'" + ); + // box_weight: DECIMAL → INT(g) + await queryInterface.sequelize.query( + "ALTER TABLE wms_receiving_detail MODIFY COLUMN box_weight INT(11) NOT NULL DEFAULT 0 COMMENT '箱重量(g)'" + ); + + // ===================== wms_stock_store ===================== + await queryInterface.sequelize.query( + "ALTER TABLE wms_stock_store MODIFY COLUMN gross_weight INT(11) DEFAULT 0 COMMENT '毛重(g)'" + ); + await queryInterface.sequelize.query( + "ALTER TABLE wms_stock_store MODIFY COLUMN net_weight INT(11) DEFAULT 0 COMMENT '净重(g)'" + ); + + // ===================== wms_stock_warehouse ===================== + await queryInterface.sequelize.query( + "ALTER TABLE wms_stock_warehouse MODIFY COLUMN gross_weight INT(11) DEFAULT 0 COMMENT '毛重(g)'" + ); + await queryInterface.sequelize.query( + "ALTER TABLE wms_stock_warehouse MODIFY COLUMN net_weight INT(11) DEFAULT 0 COMMENT '净重(g)'" + ); + // box_gross_weight / box_net_weight: 已为INT, 仅补注释 + await queryInterface.sequelize.query( + "ALTER TABLE wms_stock_warehouse MODIFY COLUMN box_gross_weight INT(11) DEFAULT 0 COMMENT '箱毛重(g)'" + ); + await queryInterface.sequelize.query( + "ALTER TABLE wms_stock_warehouse MODIFY COLUMN box_net_weight INT(11) DEFAULT 0 COMMENT '箱净重(g)'" + ); + }, + + async down(queryInterface, Sequelize) { + // ===================== wms_location_space ===================== + await queryInterface.sequelize.query( + "ALTER TABLE wms_location_space MODIFY COLUMN max_weight DECIMAL(10,2) DEFAULT 0.00 COMMENT '最大承重(kg)'" + ); + await queryInterface.sequelize.query( + "ALTER TABLE wms_location_space MODIFY COLUMN current_weight DECIMAL(10,2) DEFAULT 0.00 COMMENT '当前重量(kg)'" + ); + + // ===================== wms_order_delivery 分表 ===================== + const orderDeliveryTables = [ + 'wms_order_delivery_100000', + 'wms_order_delivery_100000_dispatch', + 'wms_order_delivery_100000_history', + 'wms_order_delivery_100000_outsourced', + 'wms_order_delivery_1000028', + 'wms_order_delivery_1000028_dispatch', + 'wms_order_delivery_1000028_history', + 'wms_order_delivery_1000028_outsourced', + ]; + + for (const table of orderDeliveryTables) { + await queryInterface.sequelize.query( + `ALTER TABLE \`${table}\` MODIFY COLUMN items_weight DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT '总重量(kg)'` + ); + } + + // ===================== wms_order_express ===================== + await queryInterface.sequelize.query( + "ALTER TABLE wms_order_express MODIFY COLUMN weighing_weight DECIMAL(10,3) DEFAULT 0.000 COMMENT '称重重量(kg)'" + ); + + // ===================== wms_package_material ===================== + await queryInterface.sequelize.query( + "ALTER TABLE wms_package_material MODIFY COLUMN weight DECIMAL(10,3) DEFAULT 0.000 COMMENT '重量(kg)'" + ); + + // ===================== wms_package_material_item_relation ===================== + await queryInterface.sequelize.query( + "ALTER TABLE wms_package_material_item_relation MODIFY COLUMN weight DECIMAL(10,2) DEFAULT 0.00 COMMENT '重量(kg)快照'" + ); + + // ===================== wms_receiving_detail ===================== + await queryInterface.sequelize.query( + "ALTER TABLE wms_receiving_detail MODIFY COLUMN weight INT(11) DEFAULT 0 COMMENT '重量g'" + ); + await queryInterface.sequelize.query( + "ALTER TABLE wms_receiving_detail MODIFY COLUMN box_weight DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT '箱重量(kg)'" + ); + + // ===================== wms_stock_store ===================== + await queryInterface.sequelize.query( + "ALTER TABLE wms_stock_store MODIFY COLUMN gross_weight DECIMAL(10,2) DEFAULT 0.00 COMMENT '毛重'" + ); + await queryInterface.sequelize.query( + "ALTER TABLE wms_stock_store MODIFY COLUMN net_weight DECIMAL(10,2) DEFAULT 0.00 COMMENT '净重'" + ); + + // ===================== wms_stock_warehouse ===================== + await queryInterface.sequelize.query( + "ALTER TABLE wms_stock_warehouse MODIFY COLUMN gross_weight DECIMAL(10,2) DEFAULT 0.00 COMMENT '毛重'" + ); + await queryInterface.sequelize.query( + "ALTER TABLE wms_stock_warehouse MODIFY COLUMN net_weight DECIMAL(10,2) DEFAULT 0.00 COMMENT '净重'" + ); + await queryInterface.sequelize.query( + "ALTER TABLE wms_stock_warehouse MODIFY COLUMN box_gross_weight INT(11) DEFAULT 0 COMMENT '箱毛重'" + ); + await queryInterface.sequelize.query( + "ALTER TABLE wms_stock_warehouse MODIFY COLUMN box_net_weight INT(11) DEFAULT 0 COMMENT '箱净重'" + ); + }, +}; diff --git a/methods/openapi.json b/methods/openapi.json index 5f6d784..0eb5cae 100644 --- a/methods/openapi.json +++ b/methods/openapi.json @@ -1155,14 +1155,14 @@ "type": "number", "required": false, "source": "body", - "description": "毛重(kg)" + "description": "毛重(g)" }, { "name": "item.netWeight", "type": "number", "required": false, "source": "body", - "description": "净重(kg)" + "description": "净重(g)" }, { "name": "item.categoryId", diff --git a/package.json b/package.json index 4216b79..90fb48d 100644 --- a/package.json +++ b/package.json @@ -71,6 +71,8 @@ "cov": "egg-bin cov", "lint": "eslint .", "migration:single": "node ./script/run-single-migration.cjs", + "db:update-stock-weight": "node ./script/update-stock-warehouse-weight.cjs", + "db:update-stock-weight:dry": "node ./script/update-stock-warehouse-weight.cjs --dry-run", "permission:sync:system-api": "node ./script/sync-system-api-permission.cjs", "check:model-boundary": "node ./script/model-boundary-check.cjs", "ci": "npm run lint && npm run check:model-boundary && npm run cov" diff --git a/script/update-stock-warehouse-weight.cjs b/script/update-stock-warehouse-weight.cjs new file mode 100644 index 0000000..59307ee --- /dev/null +++ b/script/update-stock-warehouse-weight.cjs @@ -0,0 +1,277 @@ +/** + * 批量更新生产数据库 stock_warehouse.gross_weight + * + * 用法: + * node ./script/update-stock-warehouse-weight.cjs [--dry-run] [--file stocksWeight.txt] + * + * 文件格式(每行一条,tab 分隔): + * + * + * 选项: + * --dry-run 仅预览,不实际执行 UPDATE + * --file 指定数据文件路径,默认 ./stocksWeight.txt + */ + +const fs = require('fs'); +const path = require('path'); +const readline = require('readline'); + +// ─── 解析命令行参数 ─────────────────────────────────────────── +const args = process.argv.slice(2); +const dryRun = args.includes('--dry-run'); +const fileIndex = args.indexOf('--file'); +const dataFile = fileIndex !== -1 ? args[fileIndex + 1] : path.join(__dirname, '..', 'stocksWeight.txt'); + +// ─── 加载数据库配置(复用 database/config.js 的生产环境路由逻辑) ── +function loadDbConfig() { + const projectRoot = path.resolve(__dirname, '..'); + + // 加载默认配置 + const defaultConfigPath = path.join(projectRoot, 'config', 'config.default.js'); + const defaultConfigFactory = require(defaultConfigPath); + const defaultConfig = typeof defaultConfigFactory === 'function' + ? defaultConfigFactory({ name: 'update-stock-weight', baseDir: projectRoot }) + : defaultConfigFactory; + + // 生产环境使用 config.default.js 中的 sequelize 配置 + const sequelizeConfig = defaultConfig && defaultConfig.sequelize; + if (sequelizeConfig && sequelizeConfig.host) { + return { + host: sequelizeConfig.host, + port: Number(sequelizeConfig.port || 3306), + user: sequelizeConfig.username, + password: sequelizeConfig.password, + database: sequelizeConfig.database || 'wms', + }; + } + + // 兜底:使用 mysql.clients.wms + const mysqlClient = defaultConfig && defaultConfig.mysql && defaultConfig.mysql.clients && defaultConfig.mysql.clients.wms; + if (mysqlClient) { + return { + host: mysqlClient.host, + port: Number(mysqlClient.port || 3306), + user: mysqlClient.user, + password: mysqlClient.password, + database: mysqlClient.database, + }; + } + + throw new Error('无法解析生产数据库配置'); +} + +// ─── 解析数据文件 ────────────────────────────────────────────── +async function parseDataFile(filePath) { + const records = []; + const errors = []; + + if (!fs.existsSync(filePath)) { + throw new Error(`数据文件不存在: ${filePath}`); + } + + const fileStream = fs.createReadStream(filePath, 'utf8'); + const rl = readline.createInterface({ input: fileStream, crlfDelay: Infinity }); + + let lineNo = 0; + for await (const line of rl) { + lineNo++; + const trimmed = line.trim(); + if (!trimmed) continue; // 跳过空行 + + const parts = trimmed.split(/\s+/); + if (parts.length < 2) { + errors.push(`第 ${lineNo} 行格式错误(需要 id 和 weight): "${trimmed}"`); + continue; + } + + const id = parseInt(parts[0], 10); + const weight = parseFloat(parts[1]); + + if (isNaN(id) || id <= 0) { + errors.push(`第 ${lineNo} 行 ID 无效: "${parts[0]}"`); + continue; + } + if (isNaN(weight) || weight < 0) { + errors.push(`第 ${lineNo} 行重量无效: "${parts[1]}"`); + continue; + } + + records.push({ id, weight }); + } + + return { records, errors }; +} + +// ─── 主流程 ──────────────────────────────────────────────────── +(async () => { + console.log('═══════════════════════════════════════════════'); + console.log(' 生产数据库 - stock_warehouse 重量批量更新'); + console.log('═══════════════════════════════════════════════'); + console.log(` 数据文件: ${dataFile}`); + console.log(` 模式: ${dryRun ? 'DRY-RUN(仅预览,不实际更新)' : '正式执行'}`); + console.log(''); + + // 1. 解析数据文件 + let records, errors; + try { + ({ records, errors } = await parseDataFile(dataFile)); + } catch (e) { + console.error(`[ERROR] 读取数据文件失败: ${e.message}`); + process.exit(1); + } + + if (errors.length > 0) { + console.error(`[WARNING] 数据文件存在 ${errors.length} 行解析错误:`); + errors.forEach(e => console.error(` - ${e}`)); + if (records.length === 0) { + console.error('[ERROR] 没有有效的记录可以处理,退出。'); + process.exit(1); + } + console.error(` 将继续处理其余 ${records.length} 条有效记录。\n`); + } + + console.log(` 共解析 ${records.length} 条有效记录。\n`); + + // 2. 连接数据库 + const dbConfig = loadDbConfig(); + console.log(`[DB] 生产环境 → ${dbConfig.host}:${dbConfig.port}/${dbConfig.database}`); + console.log(''); + + const mysql = require('mysql2/promise'); + const connection = await mysql.createConnection({ + host: dbConfig.host, + port: dbConfig.port, + user: dbConfig.user, + password: dbConfig.password, + database: dbConfig.database, + charset: 'utf8mb4', + }); + + try { + // 3. 预览:查询现有记录 + const ids = records.map(r => r.id); + console.log('[预览] 查询现有记录...'); + const [existingRows] = await connection.query( + `SELECT id, item_code, item_name, gross_weight FROM wms_stock_warehouse WHERE id IN (?) ORDER BY id`, + [ids] + ); + + const existingMap = new Map(); + existingRows.forEach(row => { + existingMap.set(row.id, row); + }); + + const notFound = ids.filter(id => !existingMap.has(id)); + if (notFound.length > 0) { + console.error(`[WARNING] 以下 ${notFound.length} 个 ID 在 stock_warehouse 表中不存在:`); + console.error(` ${notFound.join(', ')}`); + console.error(''); + } + + // 4. 显示变更预览 + console.log('───────────────────────────────────────────────'); + console.log(' 变更预览(前 30 条):'); + console.log('───────────────────────────────────────────────'); + console.log(' ID | 商品编码 | 商品名称 | 旧重量 → 新重量'); + console.log(' ----------|---------------|-------------------------|----------------'); + + let displayCount = 0; + const changes = []; + for (const { id, weight } of records) { + const existing = existingMap.get(id); + if (existing) { + const oldWeight = Number(existing.gross_weight) || 0; + if (oldWeight !== weight) { + changes.push({ id, weight, oldWeight, itemCode: existing.item_code, itemName: existing.item_name }); + if (displayCount < 30) { + const code = (existing.item_code || '').padEnd(13); + const name = (existing.item_name || '').substring(0, 24).padEnd(24); + console.log(` ${String(id).padEnd(10)}| ${code}| ${name}| ${oldWeight} → ${weight}`); + displayCount++; + } + } + } + } + + if (changes.length > 30) { + console.log(` ... 还有 ${changes.length - 30} 条变更,省略显示`); + } + console.log(''); + + const unchangedCount = records.length - changes.length - notFound.length; + console.log(` 汇总: 共 ${records.length} 条记录`); + console.log(` - 需要更新: ${changes.length} 条`); + console.log(` - 无需变更: ${unchangedCount} 条`); + console.log(` - ID 不存在: ${notFound.length} 条`); + console.log(''); + + if (changes.length === 0) { + console.log(' 没有需要更新的记录,退出。'); + return; + } + + // 5. dry-run 模式到此为止 + if (dryRun) { + console.log('[DRY-RUN] 预览完成,未执行任何 UPDATE。'); + console.log(' 去掉 --dry-run 参数即可正式执行。'); + return; + } + + // 6. 确认执行 + console.log('═══════════════════════════════════════════════'); + console.log(' ⚠️ 即将在生产数据库执行 UPDATE 操作!'); + console.log(` ⚠️ 将更新 ${changes.length} 条 stock_warehouse.gross_weight 记录`); + console.log('═══════════════════════════════════════════════'); + console.log(''); + console.log(' 请在 10 秒内按 Ctrl+C 取消,或等待自动执行...'); + + // 倒计时 + for (let i = 5; i > 0; i--) { + process.stdout.write(` ${i}...`); + await new Promise(resolve => setTimeout(resolve, 1000)); + } + console.log('\n'); + + // 7. 执行更新 + console.log('[执行] 开始批量更新...'); + let successCount = 0; + let failCount = 0; + const failures = []; + + for (const { id, weight } of changes) { + try { + await connection.query( + 'UPDATE wms_stock_warehouse SET gross_weight = ? WHERE id = ?', + [weight, id] + ); + successCount++; + if (successCount % 50 === 0) { + console.log(` 进度: ${successCount}/${changes.length} 条已更新`); + } + } catch (e) { + failCount++; + failures.push({ id, weight, error: e.message }); + console.error(` [FAIL] id=${id}: ${e.message}`); + } + } + + // 8. 输出结果 + console.log(''); + console.log('═══════════════════════════════════════════════'); + console.log(' 执行完成'); + console.log('═══════════════════════════════════════════════'); + console.log(` 成功: ${successCount} 条`); + console.log(` 失败: ${failCount} 条`); + if (failures.length > 0) { + console.log(' 失败详情:'); + failures.forEach(f => console.log(` id=${f.id}: ${f.error}`)); + } + console.log(''); + + } finally { + await connection.end(); + } +})().catch(e => { + console.error(`[FATAL] ${e.stack || e.message}`); + process.exit(1); +}); From 5b3180ff34f95b76922572d8fd2cf298beb5cc18 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 27 Jul 2026 03:46:37 +0800 Subject: [PATCH 123/550] =?UTF-8?q?feat(workbench):=20=E6=96=B0=E5=A2=9E?= =?UTF-8?q?=E5=B7=A5=E4=BD=9C=E5=8F=B0/=E6=89=93=E5=8C=85=E5=8F=B0?= =?UTF-8?q?=E6=A8=A1=E5=9D=97=20(workbench/pack=5Ftask)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 model: workbench, pack_task, pack_task_packer - 新增 systemMethods: workbench (finishPack/sendWeight/操作日志) - systems/workbench 扩展: 波次订单ID获取、打包操作日志白名单 - 10 条迁移: 建表→扩展→权限→重构 --- app/model/pack_task.js | 164 ++++ app/model/pack_task_packer.js | 78 ++ app/model/workbench.js | 82 ++ app/service/systemMethods/workbench.js | 137 ++++ app/service/systems/workbench.js | 700 +++++++++++++++++- .../20260715160000-create-wms-workbench.js | 89 +++ ...0260715170000-add-type-to-wms-workbench.js | 19 + .../20260715180000-extend-wms-pack-task.js | 160 ++++ ...15190000-remove-redundant-packer-fields.js | 36 + ...200000-remove-redundant-material-fields.js | 36 + ...5210000-add-device-ids-to-wms-workbench.js | 18 + ...60719120000-add-packing-flow-permission.js | 17 + ...130000-grant-packing-review-permissions.js | 36 + ...150000-refactor-pack-task-packer-fields.js | 76 ++ ...tem-quantity-sku-count-to-wms-pack-task.js | 36 + 15 files changed, 1659 insertions(+), 25 deletions(-) create mode 100644 app/model/pack_task.js create mode 100644 app/model/pack_task_packer.js create mode 100644 app/model/workbench.js create mode 100644 app/service/systemMethods/workbench.js create mode 100644 database/migrations/20260715160000-create-wms-workbench.js create mode 100644 database/migrations/20260715170000-add-type-to-wms-workbench.js create mode 100644 database/migrations/20260715180000-extend-wms-pack-task.js create mode 100644 database/migrations/20260715190000-remove-redundant-packer-fields.js create mode 100644 database/migrations/20260715200000-remove-redundant-material-fields.js create mode 100644 database/migrations/20260715210000-add-device-ids-to-wms-workbench.js create mode 100644 database/migrations/20260719120000-add-packing-flow-permission.js create mode 100644 database/migrations/20260719130000-grant-packing-review-permissions.js create mode 100644 database/migrations/20260719150000-refactor-pack-task-packer-fields.js create mode 100644 database/migrations/20260725200000-add-item-quantity-sku-count-to-wms-pack-task.js diff --git a/app/model/pack_task.js b/app/model/pack_task.js new file mode 100644 index 0000000..16944d7 --- /dev/null +++ b/app/model/pack_task.js @@ -0,0 +1,164 @@ +'use strict'; + +module.exports = app => { + const { STRING, BIGINT, INTEGER, DATE, TINYINT, TEXT, JSON: JSON_TYPE } = app.Sequelize; + + const PackTask = app.model.define('pack_task', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键ID', + }, + order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '订单ID', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '仓库ID', + }, + workbench_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '工作台ID,关联 wms_workbench.id', + }, + wave_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + defaultValue: 0, + comment: '波次ID', + }, + wave_no: { + type: STRING(50), + allowNull: true, + comment: '波次号', + }, + waybill_code: { + type: STRING(50), + allowNull: true, + comment: '运单号', + }, + pack_quantity: { + type: INTEGER.UNSIGNED, + allowNull: true, + defaultValue: 0, + comment: '打包数量(件数)', + }, + item_quantity: { + type: INTEGER.UNSIGNED, + allowNull: true, + defaultValue: 0, + comment: '商品总数量', + }, + sku_count: { + type: INTEGER.UNSIGNED, + allowNull: true, + defaultValue: 0, + comment: '商品种类数(SKU数)', + }, + pack_mode: { + type: TINYINT.UNSIGNED, + allowNull: false, + defaultValue: 1, + comment: '打包模式:1=散单 2=团购', + }, + status: { + type: TINYINT.UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '任务状态:0=待处理 1=打包中 2=已完成 3=异常', + }, + start_time: { + type: DATE, + allowNull: true, + comment: '开始打包时间', + }, + end_time: { + type: DATE, + allowNull: true, + comment: '结束打包时间', + }, + operator_text: { + type: TEXT, + allowNull: true, + comment: '作业人员(自由文本,如多人逗号分隔)', + }, + device_ids: { + type: JSON_TYPE, + allowNull: true, + comment: '设备ID列表,如 [1,2,3]', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + meta: { + type: JSON_TYPE, + allowNull: true, + comment: '扩展信息JSON', + }, + create_time: { + type: DATE, + allowNull: false, + comment: '创建时间', + }, + update_time: { + type: DATE, + allowNull: false, + comment: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '删除时间', + }, + }, { + tableName: 'wms_pack_task', + timestamps: true, + createdAt: 'create_time', + updatedAt: 'update_time', + paranoid: true, + deletedAt: 'deleted_at', + comment: '打包任务表(含作业记录)', + indexes: [ + { name: 'idx_order_id', fields: [ 'order_id' ] }, + { name: 'idx_warehouse_id', fields: [ 'warehouse_id' ] }, + { name: 'idx_workbench_id', fields: [ 'workbench_id' ] }, + { name: 'idx_wave_id', fields: [ 'wave_id' ] }, + { name: 'idx_waybill_code', fields: [ 'waybill_code' ] }, + { name: 'idx_pack_mode_status', fields: [ 'pack_mode', 'status' ] }, + { name: 'idx_start_time', fields: [ 'start_time' ] }, + { name: 'idx_status', fields: [ 'status' ] }, + ], + }); + + PackTask.associate = () => { + app.model.PackTask.belongsTo(app.model.Workbench, { + foreignKey: 'workbench_id', + targetKey: 'id', + as: 'workbench', + }); + app.model.PackTask.hasMany(app.model.PackTaskVideo, { + foreignKey: 'pack_task_id', + sourceKey: 'id', + as: 'videos', + }); + app.model.PackTask.hasMany(app.model.PackTaskPacker, { + foreignKey: 'pack_task_id', + sourceKey: 'id', + as: 'packers', + }); + app.model.PackTask.hasMany(app.model.OrderExpress, { + foreignKey: 'order_id', + sourceKey: 'order_id', + as: 'expresses', + }); + }; + + return PackTask; +}; diff --git a/app/model/pack_task_packer.js b/app/model/pack_task_packer.js new file mode 100644 index 0000000..65d2e39 --- /dev/null +++ b/app/model/pack_task_packer.js @@ -0,0 +1,78 @@ +'use strict'; + +module.exports = app => { + const { STRING, BIGINT, DATE, TINYINT } = app.Sequelize; + + const PackTaskPacker = app.model.define('pack_task_packer', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键ID', + }, + pack_task_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '打包任务ID,关联 wms_pack_task.id', + }, + account_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '账号ID,关联 wms_account.id', + }, + account_name: { + type: STRING(128), + allowNull: false, + comment: '账号姓名快照', + }, + seq: { + type: TINYINT.UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '排序序号', + }, + create_time: { + type: DATE, + allowNull: false, + comment: '创建时间', + }, + update_time: { + type: DATE, + allowNull: false, + comment: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '删除时间', + }, + }, { + tableName: 'wms_pack_task_packer', + timestamps: true, + createdAt: 'create_time', + updatedAt: 'update_time', + paranoid: true, + deletedAt: 'deleted_at', + comment: '打包任务-打包人关系表', + indexes: [ + { name: 'uix_pack_task_account', fields: [ 'pack_task_id', 'account_id' ], unique: true }, + { name: 'idx_account_id', fields: [ 'account_id' ] }, + { name: 'idx_pack_task_id', fields: [ 'pack_task_id' ] }, + ], + }); + + PackTaskPacker.associate = () => { + app.model.PackTaskPacker.belongsTo(app.model.PackTask, { + foreignKey: 'pack_task_id', + targetKey: 'id', + as: 'packTask', + }); + app.model.PackTaskPacker.belongsTo(app.model.Account, { + foreignKey: 'account_id', + targetKey: 'id', + as: 'account', + }); + }; + + return PackTaskPacker; +}; diff --git a/app/model/workbench.js b/app/model/workbench.js new file mode 100644 index 0000000..ee65b8a --- /dev/null +++ b/app/model/workbench.js @@ -0,0 +1,82 @@ +'use strict'; + +module.exports = app => { + const { STRING, BIGINT, DATE, TINYINT, ENUM, JSON: JSON_TYPE } = app.Sequelize; + + const Workbench = app.model.define('workbench', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键ID', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + name: { + type: STRING(100), + allowNull: false, + comment: '工作台名称(用户自定义)', + }, + barcode: { + type: STRING(100), + allowNull: true, + comment: '工作台条码(用户自定义,仓库内唯一)', + }, + status: { + type: TINYINT, + allowNull: false, + defaultValue: 1, + comment: '状态:0-禁用 1-启用', + }, + type: { + type: ENUM('personal', 'group'), + allowNull: false, + defaultValue: 'personal', + comment: '工作台类型:personal-个人工作台 group-团体工作台', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + device_ids: { + type: JSON_TYPE, + allowNull: true, + comment: '设备ID列表,如 [1,2,3],触发打包任务时透传到 wms_pack_task.device_ids', + }, + created_at: { + type: DATE, + allowNull: false, + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + comment: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + tableName: 'wms_workbench', + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: true, + deletedAt: 'deleted_at', + comment: '工作台表', + indexes: [ + { name: 'idx_warehouse_id', fields: ['warehouse_id'] }, + { name: 'idx_barcode', fields: ['barcode'] }, + { name: 'uk_warehouse_barcode', unique: true, fields: ['warehouse_id', 'barcode', 'deleted_at'] }, + { name: 'idx_deleted_at', fields: ['deleted_at'] }, + ], + }); + + return Workbench; +}; diff --git a/app/service/systemMethods/workbench.js b/app/service/systemMethods/workbench.js new file mode 100644 index 0000000..1f7c3fe --- /dev/null +++ b/app/service/systemMethods/workbench.js @@ -0,0 +1,137 @@ +'use strict'; + +const MainService = require('../main'); + +class WorkbenchService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = 'business'; + const _noNeedRight = 'list,detail,checkBarcode,business'; + const _noNeedLog = 'list,detail,checkBarcode'; + const _noNeedAuth = 'list,detail,checkBarcode,business'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 工作台列表(分页 + 筛选) + */ + async list(data) { + const { service } = this; + try { + const result = await service.systems.workbench.list(data || {}); + return this.success('获取成功', result); + } catch (error) { + return this.fail(error.message); + } + } + + /** + * 工作台详情 + */ + async detail(data) { + const { service } = this; + try { + const { id } = data || {}; + if (!id) return this.fail('工作台ID不能为空'); + const record = await service.systems.workbench.detail(parseInt(id)); + return this.success('获取成功', record); + } catch (error) { + return this.fail(error.message); + } + } + + /** + * 创建工作台 + */ + async create(data) { + const { service } = this; + try { + const record = await service.systems.workbench.create(data); + return this.success('创建成功', record); + } catch (error) { + return this.fail(error.message); + } + } + + /** + * 更新工作台 + */ + async update(data) { + const { service } = this; + try { + const { id, ...fields } = data || {}; + if (!id) return this.fail('工作台ID不能为空'); + const record = await service.systems.workbench.update(parseInt(id), fields); + return this.success('更新成功', record); + } catch (error) { + return this.fail(error.message); + } + } + + /** + * 删除工作台(软删除) + */ + async delete(data) { + const { service } = this; + try { + const { id } = data || {}; + if (!id) return this.fail('工作台ID不能为空'); + await service.systems.workbench.delete(parseInt(id)); + return this.success('删除成功'); + } catch (error) { + return this.fail(error.message); + } + } + + /** + * 工作台业务入口(免登录、免鉴权) + * @param {Object} data - { name, data } + */ + async business(data) { + const { ctx, service } = this; + const { name, data: bizData } = data || {}; + ctx.logger.info('[Workbench.business] 收到业务请求 name=%s data=%j', name, bizData); + try { + const result = await service.systems.workbench.business(name, bizData); + return this.success('ok', result); + } catch (error) { + ctx.logger.error('[Workbench.business] 业务处理失败 name=%s error=%s', name, error.message); + return this.fail(error.message); + } + } + + /** + * 工作台绑定摄像头 + */ + async bindCamera(data) { + const { service } = this; + try { + const { id, camera_ids } = data || {}; + if (!id) return this.fail('工作台ID不能为空'); + const record = await service.systems.workbench.bindCamera(parseInt(id), camera_ids); + return this.success('绑定成功', record); + } catch (error) { + return this.fail(error.message); + } + } + + /** + * 检查条码是否已存在 + */ + async checkBarcode(data) { + const { service } = this; + try { + const { barcode, excludeId } = data || {}; + if (!barcode) return this.fail('条码不能为空'); + const exists = await service.systems.workbench.checkBarcodeExists( + String(barcode).trim(), + excludeId ? parseInt(excludeId) : undefined + ); + return this.success('ok', { exists }); + } catch (error) { + return this.fail(error.message); + } + } +} + +module.exports = WorkbenchService; diff --git a/app/service/systems/workbench.js b/app/service/systems/workbench.js index 9cb9805..1290e90 100644 --- a/app/service/systems/workbench.js +++ b/app/service/systems/workbench.js @@ -200,6 +200,11 @@ class WorkbenchService extends Service { return await this._queryOrder(data || {}); case 'packOrder': return await this._packOrder(data || {}); + case 'finishPack': + return await this._finishPack(data || {}); + case 'sendWeight': + return await this._sendWeight(data || {}); + case '': default: throw new Error(`不支持的业务类型: ${name}`); } @@ -230,6 +235,195 @@ class WorkbenchService extends Service { return total; } + /** + * 获取波次下所有订单ID(遍历 current + dispatch 分表) + * @param {number} warehouseId + * @param {number} waveId + * @returns {Promise} + */ + async _getWaveOrderIds(warehouseId, waveId) { + const { ctx } = this; + const orderDeliveryFactory = ctx.model.OrderDeliveryFactory; + const tableOrders = [ + { label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) }, + { label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) }, + ]; + const orderIds = []; + for (const entry of tableOrders) { + try { + const model = await entry.getModel(); + if (!model) continue; + const rows = await model.findAll({ + where: { wave_id: waveId, warehouse_id: warehouseId }, + attributes: [ 'id' ], + raw: true, + }); + orderIds.push(...rows.map(r => r.id)); + } catch (_err) { continue; } + } + return [ ...new Set(orderIds) ]; + } + + /** + * 打包任务字段白名单:只有这些字段的变化才会记入操作日志 + */ + PACK_OPLOG_FIELD_WHITELIST = new Set([ + 'pack_mode', + 'status', + 'pack_quantity', + 'item_quantity', + 'sku_count', + 'workbench_id', + 'wave_no', + ]); + + /** + * 打包任务字段中文翻译 + */ + PACK_OPLOG_FIELD_LABEL = { + pack_mode: '打包模式', + status: '任务状态', + pack_quantity: '打包数量', + item_quantity: '商品总数量', + sku_count: '商品种类数', + workbench_id: '工作台', + wave_no: '波次号', + }; + + /** + * 打包任务字段值翻译 + */ + PACK_OPLOG_VALUE_LABEL = { + pack_mode: { 1: '散单', 2: '团购' }, + status: { 0: '待处理', 1: '打包中', 2: '已完成', 3: '异常' }, + }; + + /** + * 构建打包操作日志的变更描述。 + * @param {Object} packData 打包数据 + * @returns {string} 变更描述 + */ + _buildPackChangeSummary(packData) { + const whitelist = this.PACK_OPLOG_FIELD_WHITELIST; + const fieldLabel = this.PACK_OPLOG_FIELD_LABEL; + const valueLabel = this.PACK_OPLOG_VALUE_LABEL; + + const parts = []; + for (const [ key, value ] of Object.entries(packData)) { + if (!whitelist.has(key) || value === undefined || value === null) continue; + const label = fieldLabel[key] || key; + const valStr = (valueLabel[key] && valueLabel[key][value] !== undefined) + ? valueLabel[key][value] + : String(value); + parts.push(`${label}: ${valStr}`); + } + return parts.join(','); + } + + /** + * 写入打包操作日志。 + * - 散单:写入单个订单操作日志 + * - 团购:批量写入波次下所有订单的操作日志 + * 写入失败不影响主流程。 + * + * @param {Object} options + * @param {number} options.warehouseId 仓库ID + * @param {number} options.orderId 当前订单ID + * @param {number} options.waveId 波次ID + * @param {string} options.waveNo 波次号 + * @param {number} options.isSandan 是否散单(1=散单 0=团购) + * @param {Object} options.packData 打包数据(用于变更描述) + * @param {Array} options.users 打包人员列表 + */ + async _writePackOperationLog({ warehouseId, orderId, waveId, waveNo, isSandan, packData, users }) { + const { ctx } = this; + try { + const operationLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog; + if (!operationLogService || typeof operationLogService.createOperationLogs !== 'function') { + return; + } + + // 操作人信息:从 users 中取第一个作为主操作人 + const operator = { + id: users && users[0] ? String(users[0].wms_account_id || users[0].id || '') : null, + name: users && users[0] ? (users[0].real_name || '') : null, + }; + + const changeSummary = this._buildPackChangeSummary(packData); + const operationCode = isSandan === 1 ? 'ORDER_PACK' : 'ORDER_PACK_GROUP'; + + if (isSandan === 1) { + // 散单:写入单个订单操作日志 + await operationLogService.createOperationLogs([{ + businessType: 'order', + businessId: String(orderId), + operationCode, + operator, + extras: { + warehouseId, + message: `散单打包完成:${changeSummary}`, + }, + }]); + ctx.logger.info('[Workbench._writePackOperationLog] 散单操作日志已写入 orderId=%d', orderId); + } else { + // 团购:批量写入波次下所有订单的操作日志 + if (!waveId || waveId <= 0) { + // 无波次ID时按散单处理 + await operationLogService.createOperationLogs([{ + businessType: 'order', + businessId: String(orderId), + operationCode, + operator, + extras: { + warehouseId, + message: `打包完成:${changeSummary}`, + }, + }]); + return; + } + + const waveOrderIds = await this._getWaveOrderIds(warehouseId, waveId); + if (waveOrderIds.length === 0) { + // 波次下无订单,只写当前订单 + await operationLogService.createOperationLogs([{ + businessType: 'order', + businessId: String(orderId), + operationCode, + operator, + extras: { + warehouseId, + message: `打包完成(波次 ${waveNo || waveId}):${changeSummary}`, + }, + }]); + return; + } + + const messagePrefix = `团购打包完成(波次 ${waveNo || waveId},共${waveOrderIds.length}单):`; + const payloads = waveOrderIds.map(oid => ({ + businessType: 'order', + businessId: String(oid), + operationCode, + operator, + extras: { + warehouseId, + message: `${messagePrefix}${changeSummary}`, + }, + })); + + await operationLogService.createOperationLogs(payloads); + ctx.logger.info('[Workbench._writePackOperationLog] 团购操作日志已批量写入 waveNo=%s orderCount=%d', + waveNo || waveId, waveOrderIds.length); + } + } catch (e) { + ctx.logger.warn('[Workbench._writePackOperationLog] 写入操作日志失败,不影响主流程', { + error: e && e.message, + orderId, + waveId, + warehouseId, + }); + } + } + /** * 打包任务写入:根据发货单号查询订单并创建/更新打包任务记录 * @param {Object} params - { delivery_order_code, wave_no, warehouse_id, workbench_id, status, pack_time } @@ -238,13 +432,24 @@ class WorkbenchService extends Service { async _packOrder(params) { const { ctx } = this; const { delivery_order_code: deliveryOrderCode, wave_no: waveNo, - warehouse_id: inputWarehouseId, workbench_id: workbenchId, - status: packStatus, pack_time: packTime } = params; + warehouse_id: inputWarehouseId, workbench_id: workbenchIdRaw, + status: packStatus, pack_time: packTime, + wave_total_orders: waveTotalOrders, + items_count: itemsCount, + items_total: itemsTotal, + users: usersParam } = params; if (!deliveryOrderCode) throw new Error('发货单号不能为空'); if (!inputWarehouseId) throw new Error('仓库ID不能为空'); const warehouseId = parseInt(inputWarehouseId); + // 防护 NaN:parseInt 对非数字字符串返回 NaN,会导致 Sequelize 生成非法 SQL + const workbenchId = (workbenchIdRaw !== undefined && workbenchIdRaw !== null && workbenchIdRaw !== '') + ? parseInt(workbenchIdRaw) + : null; + const validWorkbenchId = (workbenchId !== null && !isNaN(workbenchId) && workbenchId > 0) + ? workbenchId + : null; const packTimeMs = packTime ? Number(packTime) * 1000 : Date.now(); // 步骤1:查找订单 @@ -295,9 +500,9 @@ class WorkbenchService extends Service { // 步骤3:获取工作台 device_ids let deviceIds = null; - if (workbenchId) { + if (validWorkbenchId) { try { - const wb = await ctx.model.Workbench.findByPk(parseInt(workbenchId), { + const wb = await ctx.model.Workbench.findByPk(validWorkbenchId, { attributes: ['device_ids'], raw: true, }); @@ -306,10 +511,10 @@ class WorkbenchService extends Service { } // 步骤4:同一工作台有新的打包任务时,关闭上一个未结束的任务 - if (workbenchId) { + if (validWorkbenchId) { const previousTask = await ctx.model.PackTask.findOne({ where: { - workbench_id: parseInt(workbenchId), + workbench_id: validWorkbenchId, warehouse_id: warehouseId, order_id: { [ctx.app.Sequelize.Op.ne]: orderId }, status: { [ctx.app.Sequelize.Op.lt]: 2 }, @@ -318,39 +523,143 @@ class WorkbenchService extends Service { if (previousTask) { await previousTask.update({ end_time: new Date(packTimeMs), status: 2 }); ctx.logger.info('[Workbench._packOrder] 关闭上一个未结束任务 taskId=%d orderId=%d workbenchId=%d', - previousTask.id, previousTask.order_id, workbenchId); + previousTask.id, previousTask.order_id, validWorkbenchId); } } - // 步骤5:查找是否已有该订单的打包任务 - let packTask = await ctx.model.PackTask.findOne({ - where: { order_id: orderId, warehouse_id: warehouseId, status: { [ctx.app.Sequelize.Op.lt]: 2 } }, - }); + // 步骤5:去重 — 散单按 order_id 物理删除旧记录,团购按 wave_no 物理删除旧记录 + if (isSandan === 1) { + // 散单:按 order_id 去重,先收集旧任务ID清理关联打包人,再物理移除旧任务 + const oldTasks = await ctx.model.PackTask.findAll({ + where: { order_id: orderId, warehouse_id: warehouseId }, + attributes: ['id'], + raw: true, + paranoid: false, + }); + if (oldTasks.length > 0) { + const oldTaskIds = oldTasks.map(t => t.id); + await ctx.model.PackTaskPacker.destroy({ + where: { pack_task_id: { [ctx.app.Sequelize.Op.in]: oldTaskIds } }, + force: true, + }); + await ctx.model.PackTask.destroy({ + where: { id: { [ctx.app.Sequelize.Op.in]: oldTaskIds } }, + force: true, + }); + ctx.logger.info('[Workbench._packOrder] 散单去重:物理删除 %d 条旧记录 orderId=%d', oldTasks.length, orderId); + } + } else { + // 团购:按 wave_no 去重,先收集旧任务ID清理关联打包人,再物理移除旧任务 + if (actualWaveNo) { + const oldTasks = await ctx.model.PackTask.findAll({ + where: { wave_no: actualWaveNo, warehouse_id: warehouseId }, + attributes: ['id'], + raw: true, + paranoid: false, + }); + if (oldTasks.length > 0) { + const oldTaskIds = oldTasks.map(t => t.id); + await ctx.model.PackTaskPacker.destroy({ + where: { pack_task_id: { [ctx.app.Sequelize.Op.in]: oldTaskIds } }, + force: true, + }); + await ctx.model.PackTask.destroy({ + where: { id: { [ctx.app.Sequelize.Op.in]: oldTaskIds } }, + force: true, + }); + ctx.logger.info('[Workbench._packOrder] 团购去重:物理删除 %d 条旧记录 waveNo=%s', oldTasks.length, actualWaveNo); + } + } + } + // 步骤6:创建新的打包任务 const packData = { order_id: orderId, warehouse_id: warehouseId, - workbench_id: workbenchId ? parseInt(workbenchId) : null, + workbench_id: validWorkbenchId, wave_id: waveId, wave_no: actualWaveNo, waybill_code: null, // 后续可从 order_express 补 pack_mode: isSandan === 0 ? 2 : 1, // 1=散单 2=团购 status: packStatus !== undefined ? parseInt(packStatus) : 1, - pack_quantity: orderRow.items_total || 0, - start_time: packTask ? packTask.start_time : new Date(packTimeMs), + pack_quantity: waveTotalOrders !== undefined ? parseInt(waveTotalOrders) || 0 : 1, + item_quantity: itemsTotal !== undefined ? parseInt(itemsTotal) || 0 : (orderRow.items_total || 0), + sku_count: itemsCount !== undefined ? parseInt(itemsCount) || 0 : (orderRow.item_count || 0), + start_time: new Date(packTimeMs), end_time: packStatus >= 2 ? new Date(packTimeMs) : null, device_ids: deviceIds, }; - if (packTask) { - // 更新已有任务 - await packTask.update(packData); - ctx.logger.info('[Workbench._packOrder] 更新打包任务 taskId=%d orderId=%d', packTask.id, orderId); - } else { - packTask = await ctx.model.PackTask.create(packData); - ctx.logger.info('[Workbench._packOrder] 创建打包任务 taskId=%d orderId=%d', packTask.id, orderId); + const packTask = await ctx.model.PackTask.create(packData); + ctx.logger.info('[Workbench._packOrder] 创建打包任务 taskId=%d orderId=%d', packTask.id, orderId); + + // 步骤6.5:更新订单的打包状态字段 + const orderPackStatus = (packStatus !== undefined && parseInt(packStatus) >= 2) ? 'fin' + : (packStatus !== undefined && parseInt(packStatus) === 1) ? 'padding' + : 'fin'; + const orderUpdateData = { pack_status: orderPackStatus }; + + if (isSandan === 1) { + // 散单:更新单个订单 + for (const entry of tableOrders) { + try { + const model = await entry.getModel(); + if (!model) continue; + const affected = await model.update(orderUpdateData, { + where: { id: orderId, warehouse_id: warehouseId }, + }); + if (affected[0] > 0) { + ctx.logger.info('[Workbench._packOrder] 更新订单打包状态 orderId=%d pack_status=%s table=%s', + orderId, orderPackStatus, entry.label); + break; + } + } catch (_err) { continue; } + } + } else if (waveId > 0) { + // 团购:批量更新波次下所有订单 + for (const entry of tableOrders) { + try { + const model = await entry.getModel(); + if (!model) continue; + const affected = await model.update(orderUpdateData, { + where: { wave_id: waveId, warehouse_id: warehouseId }, + }); + if (affected[0] > 0) { + ctx.logger.info('[Workbench._packOrder] 团购批量更新订单打包状态 waveId=%d pack_status=%s table=%s affected=%d', + waveId, orderPackStatus, entry.label, affected[0]); + } + } catch (_err) { continue; } + } } + // 步骤7:写入打包人员信息 + const users = Array.isArray(usersParam) ? usersParam : []; + let operatorText = ''; + if (users.length > 0) { + const packerRecords = users.map((user, idx) => ({ + pack_task_id: packTask.id, + account_id: user.wms_account_id != null ? parseInt(user.wms_account_id) || 0 : 0, + account_name: user.real_name || '', + seq: idx, + })); + await ctx.model.PackTaskPacker.bulkCreate(packerRecords); + operatorText = users.map(u => u.real_name || '').filter(Boolean).join(','); + // 回写 operator_text 到打包任务 + await packTask.update({ operator_text: operatorText }); + ctx.logger.info('[Workbench._packOrder] 写入 %d 个打包人员 operatorText=%s', users.length, operatorText); + } + + // 步骤8:写入操作日志(散单写单个订单,团购批量写波次所有订单) + await this._writePackOperationLog({ + warehouseId, + orderId, + waveId, + waveNo: actualWaveNo, + isSandan, + packData, + users, + }); + const result = { task_id: packTask.id, order_id: orderId, @@ -369,6 +678,346 @@ class WorkbenchService extends Service { return result; } + /** + * 工作台打包完成:传入工作台ID,查找最后一个未结束的打包任务并结束 + * @param {Object} params - { workbench_id, warehouse_id } + * @returns {Promise} + */ + async _finishPack(params) { + const { ctx } = this; + const { workbench_id: workbenchIdRaw, warehouse_id: inputWarehouseId } = params; + + if (!inputWarehouseId) throw new Error('仓库ID不能为空'); + + const warehouseId = parseInt(inputWarehouseId); + const workbenchId = (workbenchIdRaw !== undefined && workbenchIdRaw !== null && workbenchIdRaw !== '') + ? parseInt(workbenchIdRaw) + : null; + const validWorkbenchId = (workbenchId !== null && !isNaN(workbenchId) && workbenchId > 0) + ? workbenchId + : null; + + if (!validWorkbenchId) throw new Error('工作台ID不能为空'); + + // 查找该工作台最后一个未结束的打包任务(按 id 倒序取最新) + const lastTask = await ctx.model.PackTask.findOne({ + where: { + workbench_id: validWorkbenchId, + warehouse_id: warehouseId, + status: { [ctx.app.Sequelize.Op.lt]: 2 }, + }, + order: [[ 'id', 'DESC' ]], + }); + + if (!lastTask) { + ctx.logger.info('[Workbench._finishPack] 工作台 %d 无未结束的打包任务', validWorkbenchId); + return { workbench_id: validWorkbenchId, finished: false, message: '无未结束的打包任务' }; + } + + const now = new Date(); + await lastTask.update({ end_time: now, status: 2 }); + + ctx.logger.info('[Workbench._finishPack] 工作台 %d 结束打包任务 taskId=%d orderId=%d', + validWorkbenchId, lastTask.id, lastTask.order_id); + + return { + workbench_id: validWorkbenchId, + finished: true, + task_id: lastTask.id, + order_id: lastTask.order_id, + end_time: now, + }; + } + + /** + * 称重上报:条码(sn) → 运单号 → 更新称重重量 + * 支持散单直接更新和团购波次批量称重 + * @param {Object} params - { barcode, weight(克), warehouseId } + * @returns {Promise} weighing_weight/total_weight 单位为 g + */ + async _sendWeight(params) { + const { ctx } = this; + const { barcode, weight, warehouseId: inputWarehouseId } = params; + + // 参数校验 + if (!barcode || !String(barcode).trim()) { + throw new Error('条码(sn)不能为空'); + } + if (weight === null || weight === undefined || String(weight).trim() === '') { + throw new Error('重量(weight)不能为空'); + } + if (!inputWarehouseId) { + throw new Error('仓库ID不能为空'); + } + + const normalizedBarcode = String(barcode).trim(); + const warehouseId = parseInt(inputWarehouseId); + + // 校验重量格式(入参单位:克),必须大于0 + const weightText = String(weight).trim(); + if (!/^\d+$/.test(weightText)) { + throw new Error('重量格式非法,必须为正整数(单位 g)'); + } + const weightGram = Number(weightText); + if (!Number.isFinite(weightGram) || weightGram <= 0) { + throw new Error('重量必须大于0'); + } + // DB 存储单位已统一为 g,无需转换 + const normalizedWeight = weightGram; + + // 步骤1:条码 → 运单记录(按 waybill_code + warehouse_id 精确匹配) + const expressRow = await ctx.model.OrderExpress.findOne({ + where: { + waybill_code: normalizedBarcode, + warehouse_id: warehouseId, + delete_at: null, + }, + attributes: [ 'id', 'order_id', 'waybill_code', 'business_key' ], + raw: true, + }); + + if (!expressRow) { + throw new Error(`未找到条码 [${normalizedBarcode}] 对应的运单记录`); + } + + const orderId = Number(expressRow.order_id); + + // 步骤2:遍历 current → history → dispatch 分表查找订单及波次信息 + const orderDeliveryFactory = ctx.model.OrderDeliveryFactory; + const tableOrders = [ + { label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) }, + { label: 'history', getModel: () => orderDeliveryFactory.getHistoryModel(warehouseId) }, + { label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) }, + ]; + + let orderRow = null; + let orderDeliveryModel = null; + for (const entry of tableOrders) { + try { + const model = await entry.getModel(); + if (!model || typeof model.findOne !== 'function') continue; + const row = await model.findOne({ + where: { id: orderId, warehouse_id: warehouseId }, + attributes: [ 'id', 'wave_id', 'wave_no', 'items_weight' ], + raw: true, + }); + if (row) { + orderRow = row; + orderDeliveryModel = model; + break; + } + } catch (_err) { + ctx.logger.warn('[Workbench._sendWeight] 查询表 %s 失败: %s', entry.label, _err.message); + continue; + } + } + + if (!orderRow) { + throw new Error(`未找到运单对应的订单 [id=${orderId}, warehouse=${warehouseId}]`); + } + + const waveId = Number(orderRow.wave_id || 0); + + // 步骤3:散单(wave_id=0)→ 仅更新该运单的称重重量 + if (waveId === 0) { + await ctx.model.OrderExpress.update( + { weighing_weight: normalizedWeight }, + { where: { id: Number(expressRow.id) } } + ); + + ctx.logger.info('[Workbench._sendWeight] 散单称重 barcode=%s orderId=%d weightG=%s', + normalizedBarcode, orderId, normalizedWeight); + + // 写入操作日志 + await this._writeWeighOpLog({ + orderId, + barcode: normalizedBarcode, + weightGram, + normalizedWeight, + warehouseId, + }); + + return { + barcode: normalizedBarcode, + waybill_code: normalizedBarcode, + order_id: orderId, + weighing_weight: normalizedWeight, + items_weight: Number(orderRow.items_weight || 0), + mode: 'single', + }; + } + + // 步骤4:查询波次类型,判断是否为团购波次 + const waveRow = await ctx.model.WaveBatch.findOne({ + where: { wave_id: waveId, warehouse_id: warehouseId }, + attributes: [ 'wave_id', 'wave_no', 'wave_type' ], + raw: true, + }); + + // 非团购波次 → 降级为散单逻辑 + if (!waveRow || Number(waveRow.wave_type) !== 1) { + await ctx.model.OrderExpress.update( + { weighing_weight: normalizedWeight }, + { where: { id: Number(expressRow.id) } } + ); + + ctx.logger.info('[Workbench._sendWeight] 非团购波次称重 barcode=%s orderId=%d weightG=%s waveType=%s', + normalizedBarcode, orderId, normalizedWeight, waveRow ? waveRow.wave_type : 'N/A'); + + // 写入操作日志 + await this._writeWeighOpLog({ + orderId, + barcode: normalizedBarcode, + weightGram, + normalizedWeight, + warehouseId, + }); + + return { + barcode: normalizedBarcode, + waybill_code: normalizedBarcode, + order_id: orderId, + weighing_weight: normalizedWeight, + items_weight: Number(orderRow.items_weight || 0), + mode: 'single', + }; + } + + // 步骤5:团购波次(wave_type=1)→ 批量更新波次下所有运单的称重重量 + const { Op } = ctx.app.Sequelize; + const waveOrders = await orderDeliveryModel.findAll({ + where: { wave_id: waveId, warehouse_id: warehouseId }, + attributes: [ 'id' ], + raw: true, + }); + + if (!waveOrders || waveOrders.length === 0) { + throw new Error('波次下未找到订单'); + } + + const orderIds = waveOrders.map(o => Number(o.id)); + const totalCount = orderIds.length; + + await ctx.model.OrderExpress.update( + { weighing_weight: normalizedWeight }, + { + where: { + order_id: { [Op.in]: orderIds }, + delete_at: null, + }, + } + ); + + ctx.logger.info('[Workbench._sendWeight] 团购波次批量称重 barcode=%s waveId=%d waveNo=%s orderCount=%d weightG=%s', + normalizedBarcode, waveId, waveRow.wave_no, totalCount, normalizedWeight); + + // 写入操作日志(团购波次:逐订单批量写入) + await this._writeWeighOpLog({ + orderId, + barcode: normalizedBarcode, + weightGram, + normalizedWeight, + warehouseId, + waveId, + waveNo: String(waveRow.wave_no || ''), + waveOrderIds: orderIds, + }); + + return { + barcode: normalizedBarcode, + waybill_code: normalizedBarcode, + wave_id: waveId, + wave_no: String(waveRow.wave_no || ''), + weighing_weight: normalizedWeight, + total_weight: normalizedWeight * totalCount, + order_count: totalCount, + items_weight: Number(orderRow.items_weight || 0), + mode: 'wave', + }; + } + + /** + * 写入称重操作日志(内部方法,失败不影响主流程) + * @param {Object} opts + * @param {number} opts.orderId 触发订单ID + * @param {string} opts.barcode 条码/运单号 + * @param {number} opts.weightGram 称重重量(克) + * @param {number} opts.normalizedWeight 称重重量(克) + * @param {number} opts.warehouseId 仓库ID + * @param {number} [opts.waveId] 波次ID(团购时传入) + * @param {string} [opts.waveNo] 波次号 + * @param {number[]} [opts.waveOrderIds] 波次下所有订单ID(团购时传入,逐条写日志) + */ + async _writeWeighOpLog(opts = {}) { + const { ctx } = this; + const { + orderId, barcode, weightGram, normalizedWeight, warehouseId, + waveId, waveNo, waveOrderIds, + } = opts; + + try { + const operationLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog; + if (!operationLogService || typeof operationLogService.createOperationLogs !== 'function') { + return; + } + + const isWave = waveId && waveId > 0 && Array.isArray(waveOrderIds) && waveOrderIds.length > 0; + const operator = { id: '', name: 'system' }; + + if (isWave) { + // 团购波次:逐订单批量写入操作日志 + const orderCount = waveOrderIds.length; + const message = `工作台团购波次称重 ${normalizedWeight}g,波次 ${waveNo || waveId},共 ${orderCount} 单,触发条码 ${barcode}`; + const payloads = waveOrderIds.map(oid => ({ + businessType: 'order', + businessId: String(oid), + operationCode: 'ORDER_WEIGH', + operator, + extras: { + warehouseId, + message, + barcode, + weightGram, + weighingWeight: normalizedWeight, + waveId, + waveNo: waveNo || '', + orderCount, + }, + })); + + await operationLogService.createOperationLogs(payloads); + ctx.logger.info('[Workbench._writeWeighOpLog] 团购称重操作日志已批量写入 waveId=%d orderCount=%d', + waveId, orderCount); + } else { + // 散单:单条操作日志 + const payload = { + businessType: 'order', + businessId: String(orderId), + operationCode: 'ORDER_WEIGH', + operator, + extras: { + warehouseId, + message: `工作台称重 ${normalizedWeight}g,条码 ${barcode}`, + barcode, + weightGram, + weighingWeight: normalizedWeight, + orderId, + }, + }; + + await operationLogService.createOperationLogs([ payload ]); + ctx.logger.info('[Workbench._writeWeighOpLog] 散单称重操作日志已写入 orderId=%d barcode=%s', + orderId, barcode); + } + } catch (e) { + ctx.logger.warn('[Workbench._writeWeighOpLog] 写入操作日志失败,不影响主流程', { + error: e && e.message, + orderId, + barcode, + }); + } + } + /** * 条码查订单:条码 → wms_order_express → 待处理/配送订单详情 * @param {Object} params - { barcode, warehouseId } @@ -483,8 +1132,8 @@ class WorkbenchService extends Service { where: { order_id: orderId }, attributes: [ 'id', 'order_id', 'item_id', 'item_code', 'item_name', - 'plan_qty', 'actual_qty', 'stock_id', 'order_line_no', - 'item_snapshot', + 'plan_qty', 'actual_price', 'stock_id', 'order_line_no', + 'inventory_type', 'item_snapshot', ], order: [[ 'id', 'ASC' ]], raw: true, @@ -500,7 +1149,7 @@ class WorkbenchService extends Service { const stockMap = new Map(); if (stockIds.length > 0) { try { - const stockDetails = await service.systems.stockWarehouse.getStockDetails( + const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails( stockIds, { warehouseId } ); @@ -523,9 +1172,10 @@ class WorkbenchService extends Service { item_code: item.item_code || stock.item_code || '', item_name: item.item_name || stock.item_name || '', plan_qty: item.plan_qty, - actual_qty: item.actual_qty, + actual_price: item.actual_price, stock_id: stockId, order_line_no: item.order_line_no || '', + inventory_type: item.inventory_type || '', sku_property: stock.sku_property || '', stock_unit: stock.stock_unit || '', barcodes: stock.barcodes || [], diff --git a/database/migrations/20260715160000-create-wms-workbench.js b/database/migrations/20260715160000-create-wms-workbench.js new file mode 100644 index 0000000..4912d91 --- /dev/null +++ b/database/migrations/20260715160000-create-wms-workbench.js @@ -0,0 +1,89 @@ +'use strict'; + +const TABLE_NAME = 'wms_workbench'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME); + if (exists) return; + + await queryInterface.createTable(TABLE_NAME, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + name: { + type: Sequelize.STRING(100), + allowNull: false, + comment: '工作台名称(用户自定义)', + }, + barcode: { + type: Sequelize.STRING(100), + allowNull: true, + comment: '工作台条码(用户自定义,仓库内唯一)', + }, + status: { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 1, + comment: '状态:0-禁用 1-启用', + }, + remark: { + type: Sequelize.STRING(500), + allowNull: true, + comment: '备注', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '软删除时间', + }, + }); + + // 仓库隔离查询 + await queryInterface.addIndex(TABLE_NAME, ['warehouse_id'], { + name: 'idx_warehouse_id', + }); + + // 条码检索 + await queryInterface.addIndex(TABLE_NAME, ['barcode'], { + name: 'idx_barcode', + }); + + // 仓库级别唯一条码(含软删除,遵循 location_space 同款模式) + await queryInterface.addIndex(TABLE_NAME, ['warehouse_id', 'barcode', 'deleted_at'], { + unique: true, + name: 'uk_warehouse_barcode', + }); + + // 软删除查询优化 + await queryInterface.addIndex(TABLE_NAME, ['deleted_at'], { + name: 'idx_deleted_at', + }); + }, + + down: async queryInterface => { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260715170000-add-type-to-wms-workbench.js b/database/migrations/20260715170000-add-type-to-wms-workbench.js new file mode 100644 index 0000000..5ce0cda --- /dev/null +++ b/database/migrations/20260715170000-add-type-to-wms-workbench.js @@ -0,0 +1,19 @@ +'use strict'; + +const TABLE_NAME = 'wms_workbench'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + await queryInterface.addColumn(TABLE_NAME, 'type', { + type: Sequelize.ENUM('personal', 'group'), + allowNull: false, + defaultValue: 'personal', + comment: '工作台类型:personal-个人工作台 group-团体工作台', + after: 'status', + }); + }, + + down: async (queryInterface) => { + await queryInterface.removeColumn(TABLE_NAME, 'type'); + }, +}; diff --git a/database/migrations/20260715180000-extend-wms-pack-task.js b/database/migrations/20260715180000-extend-wms-pack-task.js new file mode 100644 index 0000000..365b690 --- /dev/null +++ b/database/migrations/20260715180000-extend-wms-pack-task.js @@ -0,0 +1,160 @@ +'use strict'; + +const TABLE_NAME = 'wms_pack_task'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + // 1. 仓库隔离 + await queryInterface.addColumn(TABLE_NAME, 'warehouse_id', { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '仓库ID', + after: 'order_id', + }); + + // 2. 工作台关联 + await queryInterface.addColumn(TABLE_NAME, 'workbench_id', { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '工作台ID,关联 wms_workbench.id', + after: 'warehouse_id', + }); + + // 3. 波次信息 + await queryInterface.addColumn(TABLE_NAME, 'wave_id', { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + defaultValue: 0, + comment: '波次ID', + after: 'workbench_id', + }); + await queryInterface.addColumn(TABLE_NAME, 'wave_no', { + type: Sequelize.STRING(50), + allowNull: true, + comment: '波次号', + after: 'wave_id', + }); + + // 4. 运单号 + await queryInterface.addColumn(TABLE_NAME, 'waybill_code', { + type: Sequelize.STRING(50), + allowNull: true, + comment: '运单号', + after: 'wave_no', + }); + + // 5. 打包数量 + await queryInterface.addColumn(TABLE_NAME, 'pack_quantity', { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: true, + defaultValue: 0, + comment: '打包数量(件数)', + after: 'waybill_code', + }); + + // 6. 作业时间 + await queryInterface.addColumn(TABLE_NAME, 'start_time', { + type: Sequelize.DATE, + allowNull: true, + comment: '开始打包时间', + after: 'pack_quantity', + }); + await queryInterface.addColumn(TABLE_NAME, 'end_time', { + type: Sequelize.DATE, + allowNull: true, + comment: '结束打包时间', + after: 'start_time', + }); + + // 7. 作业人员(兼容多人的自由文本) + await queryInterface.addColumn(TABLE_NAME, 'operator_text', { + type: Sequelize.TEXT, + allowNull: true, + comment: '作业人员(自由文本,如多人逗号分隔)', + after: 'end_time', + }); + + // 8. 设备IDS(JSON列表) + await queryInterface.addColumn(TABLE_NAME, 'device_ids', { + type: Sequelize.JSON, + allowNull: true, + comment: '设备ID列表,如 [1,2,3]', + after: 'operator_text', + }); + + // 9. 包材信息 + await queryInterface.addColumn(TABLE_NAME, 'package_material_id', { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '包材ID,关联 wms_package_material.id', + after: 'device_ids', + }); + await queryInterface.addColumn(TABLE_NAME, 'package_material_snapshot', { + type: Sequelize.STRING(200), + allowNull: true, + comment: '包材快照(编码+名称)', + after: 'package_material_id', + }); + + // 10. 称重 + await queryInterface.addColumn(TABLE_NAME, 'weighing_weight', { + type: Sequelize.DECIMAL(10, 3), + allowNull: true, + comment: '打包称重(kg)', + after: 'package_material_snapshot', + }); + + // 11. 异常 + await queryInterface.addColumn(TABLE_NAME, 'abnormal_reason', { + type: Sequelize.STRING(500), + allowNull: true, + comment: '异常原因', + after: 'weighing_weight', + }); + + // 12. 备注 + await queryInterface.addColumn(TABLE_NAME, 'remark', { + type: Sequelize.STRING(500), + allowNull: true, + comment: '备注', + after: 'abnormal_reason', + }); + + // 13. 修改 status 注释以包含更多状态 + await queryInterface.changeColumn(TABLE_NAME, 'status', { + type: Sequelize.TINYINT.UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '任务状态:0=待处理 1=打包中 2=已完成 3=异常', + }); + + // ======== 索引 ======== + await queryInterface.addIndex(TABLE_NAME, ['warehouse_id'], { name: 'idx_warehouse_id' }); + await queryInterface.addIndex(TABLE_NAME, ['workbench_id'], { name: 'idx_workbench_id' }); + await queryInterface.addIndex(TABLE_NAME, ['wave_id'], { name: 'idx_wave_id' }); + await queryInterface.addIndex(TABLE_NAME, ['waybill_code'], { name: 'idx_waybill_code' }); + await queryInterface.addIndex(TABLE_NAME, ['start_time'], { name: 'idx_start_time' }); + await queryInterface.addIndex(TABLE_NAME, ['status'], { name: 'idx_status' }); + }, + + down: async queryInterface => { + const cols = [ + 'remark', 'abnormal_reason', 'weighing_weight', + 'package_material_snapshot', 'package_material_id', + 'device_ids', 'operator_text', 'end_time', 'start_time', + 'pack_quantity', 'waybill_code', 'wave_no', 'wave_id', + 'workbench_id', 'warehouse_id', + ]; + for (const col of cols) { + await queryInterface.removeColumn(TABLE_NAME, col); + } + + await queryInterface.removeIndex(TABLE_NAME, 'idx_status'); + await queryInterface.removeIndex(TABLE_NAME, 'idx_start_time'); + await queryInterface.removeIndex(TABLE_NAME, 'idx_waybill_code'); + await queryInterface.removeIndex(TABLE_NAME, 'idx_wave_id'); + await queryInterface.removeIndex(TABLE_NAME, 'idx_workbench_id'); + await queryInterface.removeIndex(TABLE_NAME, 'idx_warehouse_id'); + }, +}; diff --git a/database/migrations/20260715190000-remove-redundant-packer-fields.js b/database/migrations/20260715190000-remove-redundant-packer-fields.js new file mode 100644 index 0000000..93bab49 --- /dev/null +++ b/database/migrations/20260715190000-remove-redundant-packer-fields.js @@ -0,0 +1,36 @@ +'use strict'; + +const TABLE_NAME = 'wms_pack_task'; + +module.exports = { + up: async queryInterface => { + // 打包人信息已由 wms_pack_task_packer 子表承载,删除主表冗余字段 + await queryInterface.removeColumn(TABLE_NAME, 'primary_packer_emp_id'); + await queryInterface.removeColumn(TABLE_NAME, 'primary_packer_emp_no'); + await queryInterface.removeColumn(TABLE_NAME, 'primary_packer_name'); + await queryInterface.removeColumn(TABLE_NAME, 'packers_snapshot'); + }, + + down: async (queryInterface, Sequelize) => { + await queryInterface.addColumn(TABLE_NAME, 'primary_packer_emp_id', { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: true, + comment: '主打包人工号ID', + }); + await queryInterface.addColumn(TABLE_NAME, 'primary_packer_emp_no', { + type: Sequelize.STRING(64), + allowNull: true, + comment: '主打包人工号', + }); + await queryInterface.addColumn(TABLE_NAME, 'primary_packer_name', { + type: Sequelize.STRING(128), + allowNull: true, + comment: '主打包人姓名', + }); + await queryInterface.addColumn(TABLE_NAME, 'packers_snapshot', { + type: Sequelize.JSON, + allowNull: true, + comment: '打包人快照:散单对象/团购数组', + }); + }, +}; diff --git a/database/migrations/20260715200000-remove-redundant-material-fields.js b/database/migrations/20260715200000-remove-redundant-material-fields.js new file mode 100644 index 0000000..e40cb8e --- /dev/null +++ b/database/migrations/20260715200000-remove-redundant-material-fields.js @@ -0,0 +1,36 @@ +'use strict'; + +const TABLE_NAME = 'wms_pack_task'; + +module.exports = { + up: async queryInterface => { + // 包材/称重/异常已由 wms_order_express 表(按运单号维度)承载,删除冗余 + await queryInterface.removeColumn(TABLE_NAME, 'package_material_id'); + await queryInterface.removeColumn(TABLE_NAME, 'package_material_snapshot'); + await queryInterface.removeColumn(TABLE_NAME, 'weighing_weight'); + await queryInterface.removeColumn(TABLE_NAME, 'abnormal_reason'); + }, + + down: async (queryInterface, Sequelize) => { + await queryInterface.addColumn(TABLE_NAME, 'package_material_id', { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '包材ID,关联 wms_package_material.id', + }); + await queryInterface.addColumn(TABLE_NAME, 'package_material_snapshot', { + type: Sequelize.STRING(200), + allowNull: true, + comment: '包材快照(编码+名称)', + }); + await queryInterface.addColumn(TABLE_NAME, 'weighing_weight', { + type: Sequelize.DECIMAL(10, 3), + allowNull: true, + comment: '打包称重(kg)', + }); + await queryInterface.addColumn(TABLE_NAME, 'abnormal_reason', { + type: Sequelize.STRING(500), + allowNull: true, + comment: '异常原因', + }); + }, +}; diff --git a/database/migrations/20260715210000-add-device-ids-to-wms-workbench.js b/database/migrations/20260715210000-add-device-ids-to-wms-workbench.js new file mode 100644 index 0000000..a76c697 --- /dev/null +++ b/database/migrations/20260715210000-add-device-ids-to-wms-workbench.js @@ -0,0 +1,18 @@ +'use strict'; + +const TABLE_NAME = 'wms_workbench'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + await queryInterface.addColumn(TABLE_NAME, 'device_ids', { + type: Sequelize.JSON, + allowNull: true, + comment: '设备ID列表,如 [1,2,3],触发打包任务时透传到 wms_pack_task.device_ids', + after: 'remark', + }); + }, + + down: async queryInterface => { + await queryInterface.removeColumn(TABLE_NAME, 'device_ids'); + }, +}; diff --git a/database/migrations/20260719120000-add-packing-flow-permission.js b/database/migrations/20260719120000-add-packing-flow-permission.js new file mode 100644 index 0000000..8a13f36 --- /dev/null +++ b/database/migrations/20260719120000-add-packing-flow-permission.js @@ -0,0 +1,17 @@ +'use strict'; + +module.exports = { + async up(queryInterface) { + // 在"数据"(id=16)菜单下新增"打包流水"页面权限 + await queryInterface.sequelize.query(` + INSERT INTO wms_permission (id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, sort, status, created_at, update_at, type) + VALUES (449, 'PackingFlow', '@/views/storage/packingflow/index', 'PackingFlow', '', '打包流水', '', 0, 0, 16, 1, 1, NOW(), NOW(), 'web_pages') + `); + }, + + async down(queryInterface) { + await queryInterface.sequelize.query(` + DELETE FROM wms_permission WHERE id = 449 AND path = 'PackingFlow' + `); + }, +}; diff --git a/database/migrations/20260719130000-grant-packing-review-permissions.js b/database/migrations/20260719130000-grant-packing-review-permissions.js new file mode 100644 index 0000000..bf91711 --- /dev/null +++ b/database/migrations/20260719130000-grant-packing-review-permissions.js @@ -0,0 +1,36 @@ +'use strict'; + +module.exports = { + async up(queryInterface) { + // 给客服及以上角色追加 打包流水(449) 和 复核流水(450) 权限 + // 排除 permissions='*' 的角色(已有全部权限) + await queryInterface.sequelize.query(` + UPDATE wms_role + SET permissions = JSON_ARRAY_APPEND(permissions, '$', 449, '$', 450), + updated_at = NOW() + WHERE id IN (5, 8, 26, 27, 28, 29, 30, 31, 32, 33, 34) + AND permissions IS NOT NULL + AND permissions != '*' + AND permissions != '[]' + AND JSON_VALID(permissions) = 1 + AND JSON_CONTAINS(permissions, '449', '$') = 0 + `); + }, + + async down(queryInterface) { + // 回滚:从角色权限中移除 449 和 450 + await queryInterface.sequelize.query(` + UPDATE wms_role + SET permissions = JSON_REMOVE( + JSON_REMOVE(permissions, JSON_UNQUOTE(JSON_SEARCH(permissions, 'one', '449'))), + JSON_UNQUOTE(JSON_SEARCH(permissions, 'one', '450')) + ), + updated_at = NOW() + WHERE id IN (5, 8, 26, 27, 28, 29, 30, 31, 32, 33, 34) + AND permissions IS NOT NULL + AND permissions != '*' + AND JSON_VALID(permissions) = 1 + AND JSON_CONTAINS(permissions, '449', '$') = 1 + `); + }, +}; diff --git a/database/migrations/20260719150000-refactor-pack-task-packer-fields.js b/database/migrations/20260719150000-refactor-pack-task-packer-fields.js new file mode 100644 index 0000000..123beee --- /dev/null +++ b/database/migrations/20260719150000-refactor-pack-task-packer-fields.js @@ -0,0 +1,76 @@ +'use strict'; + +const TABLE_NAME = 'wms_pack_task_packer'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + // 0. 清空已有数据(字段结构变更,emp 字段无法映射到新字段) + await queryInterface.bulkDelete(TABLE_NAME, {}); + + // 1. 删除旧索引 + await queryInterface.removeIndex(TABLE_NAME, 'uix_pack_task_emp'); + await queryInterface.removeIndex(TABLE_NAME, 'idx_emp_id'); + + // 2. 删除旧字段 + await queryInterface.removeColumn(TABLE_NAME, 'emp_id'); + await queryInterface.removeColumn(TABLE_NAME, 'emp_no'); + await queryInterface.removeColumn(TABLE_NAME, 'emp_name'); + + // 3. 新增 account 字段 + await queryInterface.addColumn(TABLE_NAME, 'account_id', { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '账号ID,关联 wms_account.id', + }); + await queryInterface.addColumn(TABLE_NAME, 'account_name', { + type: Sequelize.STRING(128), + allowNull: false, + comment: '账号姓名快照', + }); + + // 4. 建新索引 + await queryInterface.addIndex(TABLE_NAME, [ 'pack_task_id', 'account_id' ], { + name: 'uix_pack_task_account', + unique: true, + }); + await queryInterface.addIndex(TABLE_NAME, [ 'account_id' ], { + name: 'idx_account_id', + }); + }, + + down: async (queryInterface, Sequelize) => { + // 1. 删除新索引 + await queryInterface.removeIndex(TABLE_NAME, 'uix_pack_task_account'); + await queryInterface.removeIndex(TABLE_NAME, 'idx_account_id'); + + // 2. 删除新字段 + await queryInterface.removeColumn(TABLE_NAME, 'account_id'); + await queryInterface.removeColumn(TABLE_NAME, 'account_name'); + + // 3. 恢复旧字段 + await queryInterface.addColumn(TABLE_NAME, 'emp_id', { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: false, + comment: '打包人工号ID', + }); + await queryInterface.addColumn(TABLE_NAME, 'emp_no', { + type: Sequelize.STRING(64), + allowNull: false, + comment: '打包人工号', + }); + await queryInterface.addColumn(TABLE_NAME, 'emp_name', { + type: Sequelize.STRING(128), + allowNull: false, + comment: '打包人姓名', + }); + + // 4. 恢复旧索引 + await queryInterface.addIndex(TABLE_NAME, [ 'pack_task_id', 'emp_id' ], { + name: 'uix_pack_task_emp', + unique: true, + }); + await queryInterface.addIndex(TABLE_NAME, [ 'emp_id' ], { + name: 'idx_emp_id', + }); + }, +}; diff --git a/database/migrations/20260725200000-add-item-quantity-sku-count-to-wms-pack-task.js b/database/migrations/20260725200000-add-item-quantity-sku-count-to-wms-pack-task.js new file mode 100644 index 0000000..df61b10 --- /dev/null +++ b/database/migrations/20260725200000-add-item-quantity-sku-count-to-wms-pack-task.js @@ -0,0 +1,36 @@ +'use strict'; + +module.exports = { + /** + * 为打包任务表新增"商品数量"和"商品种类数"字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + await queryInterface.addColumn('wms_pack_task', 'item_quantity', { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: true, + defaultValue: 0, + comment: '商品总数量', + }); + + await queryInterface.addColumn('wms_pack_task', 'sku_count', { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: true, + defaultValue: 0, + comment: '商品种类数(SKU数)', + }); + }, + + /** + * 回滚删除打包任务表的"商品数量"和"商品种类数"字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async down(queryInterface, Sequelize) { + await queryInterface.removeColumn('wms_pack_task', 'sku_count'); + await queryInterface.removeColumn('wms_pack_task', 'item_quantity'); + }, +}; From b485f8e9f1abd9613f93012630e6826eb30b6410 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 27 Jul 2026 03:46:51 +0800 Subject: [PATCH 124/550] =?UTF-8?q?feat(camera):=20=E6=96=B0=E5=A2=9E?= =?UTF-8?q?=E6=91=84=E5=83=8F=E5=A4=B4/=E5=BD=95=E5=88=B6=E6=A8=A1?= =?UTF-8?q?=E5=9D=97=20(camera/camera=5Fserver/pack=5Ftask=5Fvideo)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 model: camera, camera_server - 新增 services: camera, cameraServer (systemMethods + systems) - 新增 pack_task_video 表及录制状态管理 - 7 条迁移: 建表→设备字段→端口拆分→状态枚举 --- app/model/camera.js | 115 ++++++++++++++++ app/model/camera_server.js | 100 ++++++++++++++ app/service/systemMethods/camera.js | 54 ++++++++ app/service/systemMethods/cameraServer.js | 54 ++++++++ app/service/systems/camera.js | 126 +++++++++++++++++ app/service/systems/cameraServer.js | 127 ++++++++++++++++++ ...20260715220000-create-wms-camera-server.js | 98 ++++++++++++++ .../20260715220001-create-wms-camera.js | 88 ++++++++++++ ...260715230000-create-wms-pack-task-video.js | 72 ++++++++++ ...20260717150000-add-camera-device-fields.js | 55 ++++++++ ...20260718160000-split-camera-server-port.js | 89 ++++++++++++ ...0000-update-pack-task-video-status-enum.js | 59 ++++++++ ...00-add-recording-status-pack-task-video.js | 26 ++++ 13 files changed, 1063 insertions(+) create mode 100644 app/model/camera.js create mode 100644 app/model/camera_server.js create mode 100644 app/service/systemMethods/camera.js create mode 100644 app/service/systemMethods/cameraServer.js create mode 100644 app/service/systems/camera.js create mode 100644 app/service/systems/cameraServer.js create mode 100644 database/migrations/20260715220000-create-wms-camera-server.js create mode 100644 database/migrations/20260715220001-create-wms-camera.js create mode 100644 database/migrations/20260715230000-create-wms-pack-task-video.js create mode 100644 database/migrations/20260717150000-add-camera-device-fields.js create mode 100644 database/migrations/20260718160000-split-camera-server-port.js create mode 100644 database/migrations/20260726120000-update-pack-task-video-status-enum.js create mode 100644 database/migrations/20260726130000-add-recording-status-pack-task-video.js diff --git a/app/model/camera.js b/app/model/camera.js new file mode 100644 index 0000000..755d013 --- /dev/null +++ b/app/model/camera.js @@ -0,0 +1,115 @@ +'use strict'; + +module.exports = app => { + const { STRING, BIGINT, INTEGER, DATE, TINYINT } = app.Sequelize; + + const Camera = app.model.define('camera', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键ID', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + server_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '所属录像服务器ID,关联 wms_camera_server.id', + }, + channel_id: { + type: INTEGER.UNSIGNED, + allowNull: false, + comment: '通道编号(DVR/NVR 上的物理通道号)', + }, + channel_name: { + type: STRING(100), + allowNull: true, + comment: '通道原始名称', + }, + ip: { + type: STRING(50), + allowNull: true, + comment: '摄像头IP地址', + }, + port: { + type: INTEGER.UNSIGNED, + allowNull: true, + comment: 'SDK管理端口(通常2020/8000)', + }, + model: { + type: STRING(100), + allowNull: true, + comment: '摄像头型号', + }, + serial_number: { + type: STRING(100), + allowNull: true, + comment: '摄像头序列号', + }, + stream_type: { + type: STRING(20), + allowNull: true, + comment: '码流类型(auto/main/sub)', + }, + custom_name: { + type: STRING(100), + allowNull: true, + comment: '自定义摄像头名称', + }, + status: { + type: TINYINT, + allowNull: false, + defaultValue: 1, + comment: '状态:0-禁用 1-启用', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + created_at: { + type: DATE, + allowNull: false, + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + comment: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + tableName: 'wms_camera', + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: true, + deletedAt: 'deleted_at', + comment: '摄像头表', + indexes: [ + { name: 'idx_warehouse_id', fields: ['warehouse_id'] }, + { name: 'idx_server_id', fields: ['server_id'] }, + { name: 'uk_server_channel', unique: true, fields: ['server_id', 'channel_id', 'deleted_at'] }, + { name: 'idx_status', fields: ['status'] }, + { name: 'idx_deleted_at', fields: ['deleted_at'] }, + ], + }); + + Camera.associate = () => { + app.model.Camera.belongsTo(app.model.CameraServer, { + foreignKey: 'server_id', + targetKey: 'id', + as: 'server', + }); + }; + + return Camera; +}; diff --git a/app/model/camera_server.js b/app/model/camera_server.js new file mode 100644 index 0000000..7b4712c --- /dev/null +++ b/app/model/camera_server.js @@ -0,0 +1,100 @@ +'use strict'; + +module.exports = app => { + const { STRING, BIGINT, INTEGER, DATE, TINYINT } = app.Sequelize; + + const CameraServer = app.model.define('camera_server', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键ID', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + name: { + type: STRING(100), + allowNull: false, + comment: '服务器名称', + }, + brand: { + type: STRING(50), + allowNull: true, + comment: '品牌(如 Hikvision/Dahua)', + }, + public_ip: { + type: STRING(50), + allowNull: true, + comment: '公网IP', + }, + internal_ip: { + type: STRING(50), + allowNull: true, + comment: '内网IP', + }, + public_port: { + type: INTEGER.UNSIGNED, + allowNull: true, + comment: '远程/公网端口', + }, + internal_port: { + type: INTEGER.UNSIGNED, + allowNull: true, + comment: '本地/内网端口', + }, + username: { + type: STRING(100), + allowNull: true, + comment: '登录账号', + }, + password: { + type: STRING(200), + allowNull: true, + comment: '登录密码', + }, + status: { + type: TINYINT, + allowNull: false, + defaultValue: 1, + comment: '状态:0-禁用 1-启用', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + created_at: { + type: DATE, + allowNull: false, + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + comment: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + tableName: 'wms_camera_server', + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: true, + deletedAt: 'deleted_at', + comment: '录像服务器表', + indexes: [ + { name: 'idx_warehouse_id', fields: ['warehouse_id'] }, + { name: 'idx_status', fields: ['status'] }, + { name: 'idx_deleted_at', fields: ['deleted_at'] }, + ], + }); + + return CameraServer; +}; diff --git a/app/service/systemMethods/camera.js b/app/service/systemMethods/camera.js new file mode 100644 index 0000000..050c059 --- /dev/null +++ b/app/service/systemMethods/camera.js @@ -0,0 +1,54 @@ +'use strict'; + +const MainService = require('../main'); + +class CameraService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list,detail'; + const _noNeedLog = '*'; + const _noNeedAuth = 'list,detail'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + async list(data) { + try { + const result = await this.service.systems.camera.list(data || {}); + return this.success('获取成功', result); + } catch (e) { return this.fail(e.message); } + } + + async detail(data) { + try { + const { id } = data || {}; + if (!id) return this.fail('ID不能为空'); + return this.success('获取成功', await this.service.systems.camera.detail(parseInt(id))); + } catch (e) { return this.fail(e.message); } + } + + async create(data) { + try { + return this.success('创建成功', await this.service.systems.camera.create(data)); + } catch (e) { return this.fail(e.message); } + } + + async update(data) { + try { + const { id, ...fields } = data || {}; + if (!id) return this.fail('ID不能为空'); + return this.success('更新成功', await this.service.systems.camera.update(parseInt(id), fields)); + } catch (e) { return this.fail(e.message); } + } + + async delete(data) { + try { + const { id } = data || {}; + if (!id) return this.fail('ID不能为空'); + await this.service.systems.camera.delete(parseInt(id)); + return this.success('删除成功'); + } catch (e) { return this.fail(e.message); } + } +} + +module.exports = CameraService; diff --git a/app/service/systemMethods/cameraServer.js b/app/service/systemMethods/cameraServer.js new file mode 100644 index 0000000..5b8ff72 --- /dev/null +++ b/app/service/systemMethods/cameraServer.js @@ -0,0 +1,54 @@ +'use strict'; + +const MainService = require('../main'); + +class CameraServerService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list,detail'; + const _noNeedLog = '*'; + const _noNeedAuth = 'list,detail'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + async list(data) { + try { + const result = await this.service.systems.cameraServer.list(data || {}); + return this.success('获取成功', result); + } catch (e) { return this.fail(e.message); } + } + + async detail(data) { + try { + const { id } = data || {}; + if (!id) return this.fail('ID不能为空'); + return this.success('获取成功', await this.service.systems.cameraServer.detail(parseInt(id))); + } catch (e) { return this.fail(e.message); } + } + + async create(data) { + try { + return this.success('创建成功', await this.service.systems.cameraServer.create(data)); + } catch (e) { return this.fail(e.message); } + } + + async update(data) { + try { + const { id, ...fields } = data || {}; + if (!id) return this.fail('ID不能为空'); + return this.success('更新成功', await this.service.systems.cameraServer.update(parseInt(id), fields)); + } catch (e) { return this.fail(e.message); } + } + + async delete(data) { + try { + const { id } = data || {}; + if (!id) return this.fail('ID不能为空'); + await this.service.systems.cameraServer.delete(parseInt(id)); + return this.success('删除成功'); + } catch (e) { return this.fail(e.message); } + } +} + +module.exports = CameraServerService; diff --git a/app/service/systems/camera.js b/app/service/systems/camera.js new file mode 100644 index 0000000..94658ba --- /dev/null +++ b/app/service/systems/camera.js @@ -0,0 +1,126 @@ +'use strict'; + +const Service = require('egg').Service; + +class CameraService extends Service { + async list(params = {}) { + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + const warehouseId = ctx.user.store_id; + const { pagination = {}, where = {} } = params; + + const page = Math.max(1, parseInt(pagination.page) || 1); + const pageSize = Math.min(200, Math.max(1, parseInt(pagination.pageSize) || 20)); + + const queryWhere = { warehouse_id: warehouseId }; + if (where.server_id) queryWhere.server_id = parseInt(where.server_id); + if (where.custom_name) queryWhere.custom_name = { [Op.like]: `%${where.custom_name}%` }; + if (where.status !== undefined && where.status !== null && where.status !== '') { + queryWhere.status = parseInt(where.status); + } + + const { count, rows } = await ctx.model.Camera.findAndCountAll({ + where: queryWhere, + include: [{ + model: ctx.model.CameraServer, + as: 'server', + attributes: ['id', 'name', 'brand', 'public_ip', 'internal_ip', 'public_port', 'internal_port', 'status'], + required: false, + }], + order: [['created_at', 'DESC']], + offset: (page - 1) * pageSize, + limit: pageSize, + }); + + return { list: rows, pagination: { page, pageSize, total: count, totalPages: Math.ceil(count / pageSize), hasPrevious: page > 1, hasNext: page * pageSize < count } }; + } + + async detail(id) { + const { ctx } = this; + const record = await ctx.model.Camera.findOne({ + where: { id, warehouse_id: ctx.user.store_id }, + include: [{ + model: ctx.model.CameraServer, + as: 'server', + attributes: ['id', 'name', 'brand', 'public_ip', 'internal_ip', 'public_port', 'internal_port', 'status'], + required: false, + }], + }); + if (!record) throw new Error('摄像头不存在或无权访问'); + return record; + } + + async create(data) { + const { ctx } = this; + if (!data.server_id) throw new Error('所属服务器ID不能为空'); + if (data.channel_id === undefined || data.channel_id === null) throw new Error('通道编号不能为空'); + if (data.custom_name !== undefined && data.custom_name !== null && String(data.custom_name).trim() === '') { + throw new Error('自定义名称不能为空'); + } + return await ctx.model.Camera.create({ + warehouse_id: ctx.user.store_id, + server_id: parseInt(data.server_id), + channel_id: parseInt(data.channel_id), + channel_name: data.channel_name || null, + ip: data.ip || null, + port: data.port !== undefined && data.port !== null ? parseInt(data.port) : null, + model: data.model || null, + serial_number: data.serial_number || null, + stream_type: data.stream_type || null, + custom_name: data.custom_name || null, + status: data.status !== undefined ? parseInt(data.status) : 1, + remark: data.remark || null, + }); + } + + async update(id, data) { + const { ctx } = this; + const record = await ctx.model.Camera.findOne({ where: { id, warehouse_id: ctx.user.store_id } }); + if (!record) throw new Error('摄像头不存在或无权操作'); + + const fields = {}; + if (data.server_id !== undefined) fields.server_id = parseInt(data.server_id); + if (data.channel_id !== undefined) fields.channel_id = parseInt(data.channel_id); + if (data.channel_name !== undefined) fields.channel_name = data.channel_name; + if (data.ip !== undefined) fields.ip = data.ip; + if (data.port !== undefined) fields.port = data.port !== null ? parseInt(data.port) : null; + if (data.model !== undefined) fields.model = data.model; + if (data.serial_number !== undefined) fields.serial_number = data.serial_number; + if (data.stream_type !== undefined) fields.stream_type = data.stream_type; + if (data.custom_name !== undefined) { + if (data.custom_name !== null && String(data.custom_name).trim() === '') { + throw new Error('自定义名称不能为空'); + } + fields.custom_name = data.custom_name; + } + if (data.status !== undefined) fields.status = parseInt(data.status); + if (data.remark !== undefined) fields.remark = data.remark; + if (Object.keys(fields).length === 0) throw new Error('没有需要更新的字段'); + + await record.update(fields); + return record; + } + + async delete(id) { + const { ctx } = this; + const warehouseId = ctx.user.store_id; + const record = await ctx.model.Camera.findOne({ where: { id, warehouse_id: warehouseId } }); + if (!record) throw new Error('摄像头不存在或无权操作'); + + // 检查是否被工作台绑定 + const boundWorkbenches = await ctx.model.Workbench.findAll({ + where: { warehouse_id: warehouseId }, + attributes: ['id', 'name'], + }); + for (const wb of boundWorkbenches) { + const deviceIds = Array.isArray(wb.device_ids) ? wb.device_ids : []; + if (deviceIds.includes(id)) { + throw new Error(`摄像头已被工作台「${wb.name}」绑定,请先解绑后再删除`); + } + } + + await record.destroy(); + } +} + +module.exports = CameraService; diff --git a/app/service/systems/cameraServer.js b/app/service/systems/cameraServer.js new file mode 100644 index 0000000..6437e65 --- /dev/null +++ b/app/service/systems/cameraServer.js @@ -0,0 +1,127 @@ +'use strict'; + +const Service = require('egg').Service; + +class CameraServerService extends Service { + async list(params = {}) { + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + const warehouseId = ctx.user.store_id; + const { pagination = {}, where = {} } = params; + + const page = Math.max(1, parseInt(pagination.page) || 1); + const pageSize = Math.min(200, Math.max(1, parseInt(pagination.pageSize) || 20)); + + const queryWhere = { warehouse_id: warehouseId }; + if (where.name) queryWhere.name = { [Op.like]: `%${where.name}%` }; + if (where.status !== undefined && where.status !== null && where.status !== '') { + queryWhere.status = parseInt(where.status); + } + + const { count, rows } = await ctx.model.CameraServer.findAndCountAll({ + where: queryWhere, + order: [['created_at', 'DESC']], + offset: (page - 1) * pageSize, + limit: pageSize, + }); + + return { list: rows, pagination: { page, pageSize, total: count, totalPages: Math.ceil(count / pageSize), hasPrevious: page > 1, hasNext: page * pageSize < count } }; + } + + async detail(id) { + const { ctx } = this; + const record = await ctx.model.CameraServer.findOne({ where: { id, warehouse_id: ctx.user.store_id } }); + if (!record) throw new Error('录像服务器不存在或无权访问'); + return record; + } + + async create(data) { + const { ctx } = this; + if (!data.name || !String(data.name).trim()) throw new Error('服务器名称不能为空'); + + // 规范化 IP 和端口 + const publicIp = data.public_ip ? String(data.public_ip).trim() : ''; + const internalIp = data.internal_ip ? String(data.internal_ip).trim() : ''; + const publicPort = data.public_port !== undefined && data.public_port !== null ? parseInt(data.public_port) : null; + const internalPort = data.internal_port !== undefined && data.internal_port !== null ? parseInt(data.internal_port) : null; + + // IP-端口配对校验:有 IP 则端口必填 + if (publicIp && !publicPort) throw new Error('公网端口不能为空'); + if (internalIp && !internalPort) throw new Error('内网端口不能为空'); + + // 至少一组 IP+端口 完整 + const hasPublic = !!(publicIp && publicPort); + const hasInternal = !!(internalIp && internalPort); + if (!hasPublic && !hasInternal) throw new Error('至少需要填写一组公网IP+端口或内网IP+端口'); + + return await ctx.model.CameraServer.create({ + warehouse_id: ctx.user.store_id, + name: String(data.name).trim(), + brand: data.brand || null, + public_ip: publicIp || null, + internal_ip: internalIp || null, + public_port: publicPort, + internal_port: internalPort, + username: data.username || null, + password: data.password || null, + status: data.status !== undefined ? parseInt(data.status) : 1, + remark: data.remark || null, + }); + } + + async update(id, data) { + const { ctx } = this; + const record = await ctx.model.CameraServer.findOne({ where: { id, warehouse_id: ctx.user.store_id } }); + if (!record) throw new Error('录像服务器不存在或无权操作'); + + const fields = {}; + if (data.name !== undefined) fields.name = String(data.name).trim(); + if (data.brand !== undefined) fields.brand = data.brand; + if (data.public_ip !== undefined) fields.public_ip = data.public_ip ? String(data.public_ip).trim() : null; + if (data.internal_ip !== undefined) fields.internal_ip = data.internal_ip ? String(data.internal_ip).trim() : null; + if (data.public_port !== undefined) fields.public_port = data.public_port !== null ? parseInt(data.public_port) : null; + if (data.internal_port !== undefined) fields.internal_port = data.internal_port !== null ? parseInt(data.internal_port) : null; + if (data.username !== undefined) fields.username = data.username; + if (data.password !== undefined) fields.password = data.password; + if (data.status !== undefined) fields.status = parseInt(data.status); + if (data.remark !== undefined) fields.remark = data.remark; + if (Object.keys(fields).length === 0) throw new Error('没有需要更新的字段'); + + // 合并新旧值,校验最终状态 + const mergedPublicIp = data.public_ip !== undefined ? fields.public_ip : record.public_ip; + const mergedInternalIp = data.internal_ip !== undefined ? fields.internal_ip : record.internal_ip; + const mergedPublicPort = data.public_port !== undefined ? fields.public_port : record.public_port; + const mergedInternalPort = data.internal_port !== undefined ? fields.internal_port : record.internal_port; + + // IP-端口配对校验 + if (mergedPublicIp && !mergedPublicPort) throw new Error('公网端口不能为空'); + if (mergedInternalIp && !mergedInternalPort) throw new Error('内网端口不能为空'); + + // 至少一组 IP+端口 完整 + const hasPublic = !!(mergedPublicIp && mergedPublicPort); + const hasInternal = !!(mergedInternalIp && mergedInternalPort); + if (!hasPublic && !hasInternal) throw new Error('至少需要填写一组公网IP+端口或内网IP+端口'); + + await record.update(fields); + return record; + } + + async delete(id) { + const { ctx } = this; + const warehouseId = ctx.user.store_id; + const record = await ctx.model.CameraServer.findOne({ where: { id, warehouse_id: warehouseId } }); + if (!record) throw new Error('录像服务器不存在或无权操作'); + + // 检查是否有关联摄像头 + const cameraCount = await ctx.model.Camera.count({ + where: { server_id: id, warehouse_id: warehouseId }, + }); + if (cameraCount > 0) { + throw new Error(`录像服务器下存在 ${cameraCount} 个摄像头,请先删除摄像头后再删除服务器`); + } + + await record.destroy(); + } +} + +module.exports = CameraServerService; diff --git a/database/migrations/20260715220000-create-wms-camera-server.js b/database/migrations/20260715220000-create-wms-camera-server.js new file mode 100644 index 0000000..5ad66f3 --- /dev/null +++ b/database/migrations/20260715220000-create-wms-camera-server.js @@ -0,0 +1,98 @@ +'use strict'; + +const TABLE_NAME = 'wms_camera_server'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME); + if (exists) return; + + await queryInterface.createTable(TABLE_NAME, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + name: { + type: Sequelize.STRING(100), + allowNull: false, + comment: '服务器名称', + }, + brand: { + type: Sequelize.STRING(50), + allowNull: true, + comment: '品牌(如 Hikvision/Dahua)', + }, + public_ip: { + type: Sequelize.STRING(50), + allowNull: true, + comment: '公网IP', + }, + internal_ip: { + type: Sequelize.STRING(50), + allowNull: true, + comment: '内网IP', + }, + port: { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: true, + defaultValue: 80, + comment: '端口号', + }, + username: { + type: Sequelize.STRING(100), + allowNull: true, + comment: '登录账号', + }, + password: { + type: Sequelize.STRING(200), + allowNull: true, + comment: '登录密码', + }, + status: { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 1, + comment: '状态:0-禁用 1-启用', + }, + remark: { + type: Sequelize.STRING(500), + allowNull: true, + comment: '备注', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '软删除时间', + }, + }); + + await queryInterface.addIndex(TABLE_NAME, ['warehouse_id'], { name: 'idx_warehouse_id' }); + await queryInterface.addIndex(TABLE_NAME, ['status'], { name: 'idx_status' }); + await queryInterface.addIndex(TABLE_NAME, ['deleted_at'], { name: 'idx_deleted_at' }); + }, + + down: async queryInterface => { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260715220001-create-wms-camera.js b/database/migrations/20260715220001-create-wms-camera.js new file mode 100644 index 0000000..6a6e894 --- /dev/null +++ b/database/migrations/20260715220001-create-wms-camera.js @@ -0,0 +1,88 @@ +'use strict'; + +const TABLE_NAME = 'wms_camera'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME); + if (exists) return; + + await queryInterface.createTable(TABLE_NAME, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + server_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '所属录像服务器ID,关联 wms_camera_server.id', + }, + channel_id: { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: false, + comment: '通道编号(DVR/NVR 上的物理通道号)', + }, + channel_name: { + type: Sequelize.STRING(100), + allowNull: true, + comment: '通道原始名称', + }, + custom_name: { + type: Sequelize.STRING(100), + allowNull: true, + comment: '自定义摄像头名称', + }, + status: { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 1, + comment: '状态:0-禁用 1-启用', + }, + remark: { + type: Sequelize.STRING(500), + allowNull: true, + comment: '备注', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '软删除时间', + }, + }); + + await queryInterface.addIndex(TABLE_NAME, ['warehouse_id'], { name: 'idx_warehouse_id' }); + await queryInterface.addIndex(TABLE_NAME, ['server_id'], { name: 'idx_server_id' }); + // 同一服务器下通道号唯一 + await queryInterface.addIndex(TABLE_NAME, ['server_id', 'channel_id', 'deleted_at'], { + unique: true, + name: 'uk_server_channel', + }); + await queryInterface.addIndex(TABLE_NAME, ['status'], { name: 'idx_status' }); + await queryInterface.addIndex(TABLE_NAME, ['deleted_at'], { name: 'idx_deleted_at' }); + }, + + down: async queryInterface => { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260715230000-create-wms-pack-task-video.js b/database/migrations/20260715230000-create-wms-pack-task-video.js new file mode 100644 index 0000000..ceeeffa --- /dev/null +++ b/database/migrations/20260715230000-create-wms-pack-task-video.js @@ -0,0 +1,72 @@ +'use strict'; + +const TABLE_NAME = 'wms_pack_task_video'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME); + if (exists) return; + + await queryInterface.createTable(TABLE_NAME, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + pack_task_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '打包任务ID,关联 wms_pack_task.id', + }, + camera_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '摄像头设备ID,关联 wms_camera.id', + }, + video_url: { + type: Sequelize.STRING(500), + allowNull: false, + comment: '视频地址(录像回放URL)', + }, + status: { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 1, + comment: '状态:0-无效 1-有效', + }, + remark: { + type: Sequelize.STRING(500), + allowNull: true, + comment: '备注', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '软删除时间', + }, + }); + + await queryInterface.addIndex(TABLE_NAME, ['pack_task_id'], { name: 'idx_pack_task_id' }); + await queryInterface.addIndex(TABLE_NAME, ['camera_id'], { name: 'idx_camera_id' }); + await queryInterface.addIndex(TABLE_NAME, ['deleted_at'], { name: 'idx_deleted_at' }); + }, + + down: async queryInterface => { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260717150000-add-camera-device-fields.js b/database/migrations/20260717150000-add-camera-device-fields.js new file mode 100644 index 0000000..6acfe27 --- /dev/null +++ b/database/migrations/20260717150000-add-camera-device-fields.js @@ -0,0 +1,55 @@ +'use strict'; + +const TABLE_NAME = 'wms_camera'; + +/** + * 新增摄像头设备信息字段:IP、SDK端口、型号、序列号、码流类型。 + * 用于保存 NVR 服务器返回的摄像头详细设备信息。 + */ +module.exports = { + up: async (queryInterface, Sequelize) => { + const columns = [ + { + name: 'ip', + def: { type: Sequelize.STRING(50), allowNull: true, comment: '摄像头IP地址', after: 'channel_name' }, + }, + { + name: 'port', + def: { type: Sequelize.INTEGER.UNSIGNED, allowNull: true, comment: 'SDK管理端口(通常2020/8000)', after: 'ip' }, + }, + { + name: 'model', + def: { type: Sequelize.STRING(100), allowNull: true, comment: '摄像头型号', after: 'port' }, + }, + { + name: 'serial_number', + def: { type: Sequelize.STRING(100), allowNull: true, comment: '摄像头序列号', after: 'model' }, + }, + { + name: 'stream_type', + def: { type: Sequelize.STRING(20), allowNull: true, comment: '码流类型(auto/main/sub)', after: 'serial_number' }, + }, + ]; + + for (const col of columns) { + const tableInfo = await queryInterface.describeTable(TABLE_NAME); + if (!tableInfo[col.name]) { + await queryInterface.addColumn(TABLE_NAME, col.name, col.def); + console.log(`[Migration] wms_camera.${col.name} 已添加`); + } else { + console.log(`[Migration] wms_camera.${col.name} 已存在,跳过`); + } + } + }, + + down: async queryInterface => { + const columns = ['stream_type', 'serial_number', 'model', 'port', 'ip']; + for (const col of columns) { + const tableInfo = await queryInterface.describeTable(TABLE_NAME); + if (tableInfo[col]) { + await queryInterface.removeColumn(TABLE_NAME, col); + console.log(`[Migration] wms_camera.${col} 已移除`); + } + } + }, +}; diff --git a/database/migrations/20260718160000-split-camera-server-port.js b/database/migrations/20260718160000-split-camera-server-port.js new file mode 100644 index 0000000..e3f4b10 --- /dev/null +++ b/database/migrations/20260718160000-split-camera-server-port.js @@ -0,0 +1,89 @@ +'use strict'; + +const TABLE_NAME = 'wms_camera_server'; + +/** + * 将 wms_camera_server.port 拆分为 public_port(远程/公网端口)和 internal_port(本地/内网端口)。 + * 原因:远程访问端口和本地访问端口通常不同(如 NAT 映射),需要分别存储。 + */ +module.exports = { + up: async (queryInterface, Sequelize) => { + const tableInfo = await queryInterface.describeTable(TABLE_NAME); + + // 1. 添加 public_port + if (!tableInfo.public_port) { + await queryInterface.addColumn(TABLE_NAME, 'public_port', { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: true, + comment: '远程/公网端口', + after: 'internal_ip', + }); + console.log('[Migration] wms_camera_server.public_port 已添加'); + } else { + console.log('[Migration] wms_camera_server.public_port 已存在,跳过'); + } + + // 2. 添加 internal_port + if (!tableInfo.internal_port) { + await queryInterface.addColumn(TABLE_NAME, 'internal_port', { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: true, + comment: '本地/内网端口', + after: 'public_port', + }); + console.log('[Migration] wms_camera_server.internal_port 已添加'); + } else { + console.log('[Migration] wms_camera_server.internal_port 已存在,跳过'); + } + + // 3. 将旧 port 数据迁移到 public_port 和 internal_port(保留旧值,后续可按需调整) + if (tableInfo.port) { + await queryInterface.sequelize.query( + `UPDATE ${TABLE_NAME} SET public_port = port, internal_port = port WHERE port IS NOT NULL` + ); + console.log('[Migration] wms_camera_server.port 数据已复制到 public_port 和 internal_port'); + + // 4. 删除旧 port 列 + await queryInterface.removeColumn(TABLE_NAME, 'port'); + console.log('[Migration] wms_camera_server.port 列已删除'); + } else { + console.log('[Migration] wms_camera_server.port 列不存在,跳过迁移和删除'); + } + }, + + down: async (queryInterface, Sequelize) => { + const tableInfo = await queryInterface.describeTable(TABLE_NAME); + + // 恢复 port 列 + if (!tableInfo.port) { + await queryInterface.addColumn(TABLE_NAME, 'port', { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: true, + defaultValue: 80, + comment: '端口号', + after: 'internal_ip', + }); + console.log('[Migration] wms_camera_server.port 列已恢复'); + } + + // 将 public_port 数据回写到 port(优先使用 internal_port) + if (tableInfo.public_port || tableInfo.internal_port) { + await queryInterface.sequelize.query( + `UPDATE ${TABLE_NAME} SET port = COALESCE(internal_port, public_port) WHERE internal_port IS NOT NULL OR public_port IS NOT NULL` + ); + console.log('[Migration] port 数据已从 public_port/internal_port 回写'); + } + + // 删除 public_port + if (tableInfo.public_port) { + await queryInterface.removeColumn(TABLE_NAME, 'public_port'); + console.log('[Migration] wms_camera_server.public_port 列已删除'); + } + + // 删除 internal_port + if (tableInfo.internal_port) { + await queryInterface.removeColumn(TABLE_NAME, 'internal_port'); + console.log('[Migration] wms_camera_server.internal_port 列已删除'); + } + }, +}; diff --git a/database/migrations/20260726120000-update-pack-task-video-status-enum.js b/database/migrations/20260726120000-update-pack-task-video-status-enum.js new file mode 100644 index 0000000..087eaa6 --- /dev/null +++ b/database/migrations/20260726120000-update-pack-task-video-status-enum.js @@ -0,0 +1,59 @@ +'use strict'; + +/** + * wms_pack_task_video.status 字段改为 ENUM 类型。 + * + * 变更前:TINYINT(无明确语义) + * 变更后:ENUM('created', 'completed', 'failed') + * - created = 已创建 + * - completed = 已完成 + * - failed = 失败 + * + * 现有数据映射:status=1 → 'created' + */ + +module.exports = { + async up(queryInterface, Sequelize) { + // 新增临时列 + await queryInterface.sequelize.query( + "ALTER TABLE wms_pack_task_video ADD COLUMN status_new ENUM('created','completed','failed') NOT NULL DEFAULT 'created' COMMENT '状态:已创建/已完成/失败' AFTER status" + ); + + // 迁移现有数据:TINYINT 1 → 'created' + await queryInterface.sequelize.query( + "UPDATE wms_pack_task_video SET status_new = 'created' WHERE status = 1" + ); + + // 删除旧列 + await queryInterface.sequelize.query( + 'ALTER TABLE wms_pack_task_video DROP COLUMN status' + ); + + // 新列改名为 status + await queryInterface.sequelize.query( + "ALTER TABLE wms_pack_task_video CHANGE COLUMN status_new status ENUM('created','completed','failed') NOT NULL DEFAULT 'created' COMMENT '状态:已创建/已完成/失败'" + ); + }, + + async down(queryInterface, Sequelize) { + // 新增临时 TINYINT 列 + await queryInterface.sequelize.query( + 'ALTER TABLE wms_pack_task_video ADD COLUMN status_new TINYINT NOT NULL DEFAULT 1 AFTER status' + ); + + // 回退数据:'created' → 1 + await queryInterface.sequelize.query( + "UPDATE wms_pack_task_video SET status_new = 1 WHERE status = 'created'" + ); + + // 删除 ENUM 列 + await queryInterface.sequelize.query( + 'ALTER TABLE wms_pack_task_video DROP COLUMN status' + ); + + // 改名为 status + await queryInterface.sequelize.query( + 'ALTER TABLE wms_pack_task_video CHANGE COLUMN status_new status TINYINT NOT NULL DEFAULT 1' + ); + }, +}; diff --git a/database/migrations/20260726130000-add-recording-status-pack-task-video.js b/database/migrations/20260726130000-add-recording-status-pack-task-video.js new file mode 100644 index 0000000..4bf006d --- /dev/null +++ b/database/migrations/20260726130000-add-recording-status-pack-task-video.js @@ -0,0 +1,26 @@ +'use strict'; + +/** + * wms_pack_task_video.status 增加「录制中」状态。 + * + * 变更前:ENUM('created','completed','failed') + * 变更后:ENUM('created','recording','completed','failed') + * - created = 已创建 + * - recording = 录制中(新增) + * - completed = 已完成 + * - failed = 失败 + */ + +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.sequelize.query( + "ALTER TABLE wms_pack_task_video MODIFY COLUMN status ENUM('created','recording','completed','failed') NOT NULL DEFAULT 'created' COMMENT '状态:已创建/录制中/已完成/失败'" + ); + }, + + async down(queryInterface, Sequelize) { + await queryInterface.sequelize.query( + "ALTER TABLE wms_pack_task_video MODIFY COLUMN status ENUM('created','completed','failed') NOT NULL DEFAULT 'created' COMMENT '状态:已创建/已完成/失败'" + ); + }, +}; From f40370baca6fb499b5920c116a8e272eb03b48bb Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 27 Jul 2026 03:47:09 +0800 Subject: [PATCH 125/550] =?UTF-8?q?feat(print):=20=E6=89=93=E5=8D=B0?= =?UTF-8?q?=E7=94=B5=E8=84=91=E7=AE=A1=E7=90=86=E5=A2=9E=E5=BC=BA=EF=BC=88?= =?UTF-8?q?=E5=BD=95=E5=88=B6=E3=80=81=E8=BD=AF=E5=88=A0=E9=99=A4=E3=80=81?= =?UTF-8?q?=E7=8B=AC=E7=AB=8B=E6=8E=A5=E5=8F=A3=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - print_computer: 新增录制字段(is_recording/recording_size/remote_play_url/recording_directory/deleted_at) - print_stations: 新增 deleted_at 软删除 - 新增 printComputer service (systemMethods + systems) - order_print 重构: 商品信息从 picking 表直读,不再依赖 order_items - 8 条迁移: 录制→软删除→权限→目录 --- app/model/print_computer.js | 38 ++- app/model/print_stations.js | 6 + app/service/systemMethods/printComputer.js | 81 +++++ app/service/systems/order_print.js | 138 +------- app/service/systems/printComputer.js | 319 ++++++++++++++++++ ...00-add-print-qty-log-export-permissions.js | 202 +++++++++++ ...-add-is-recording-to-wms-print-computer.js | 28 ++ ...00-add-deleted-at-to-wms-print-computer.js | 28 ++ ...00-add-deleted-at-to-wms-print-stations.js | 28 ++ ...25150000-add-print-computer-permissions.js | 86 +++++ ...-recording-fields-to-wms-print-computer.js | 42 +++ ...0260725170000-add-recording-permissions.js | 82 +++++ ...cording-directory-to-wms-print-computer.js | 28 ++ 13 files changed, 981 insertions(+), 125 deletions(-) create mode 100644 app/service/systemMethods/printComputer.js create mode 100644 app/service/systems/printComputer.js create mode 100644 database/migrations/20260720160000-add-print-qty-log-export-permissions.js create mode 100644 database/migrations/20260725120000-add-is-recording-to-wms-print-computer.js create mode 100644 database/migrations/20260725130000-add-deleted-at-to-wms-print-computer.js create mode 100644 database/migrations/20260725140000-add-deleted-at-to-wms-print-stations.js create mode 100644 database/migrations/20260725150000-add-print-computer-permissions.js create mode 100644 database/migrations/20260725160000-add-recording-fields-to-wms-print-computer.js create mode 100644 database/migrations/20260725170000-add-recording-permissions.js create mode 100644 database/migrations/20260725180000-add-recording-directory-to-wms-print-computer.js diff --git a/app/model/print_computer.js b/app/model/print_computer.js index 5f7ec6e..4f60b0e 100644 --- a/app/model/print_computer.js +++ b/app/model/print_computer.js @@ -1,7 +1,7 @@ 'use strict'; module.exports = app => { - const { INTEGER, BIGINT, STRING, DATE } = app.Sequelize; + const { INTEGER, BIGINT, STRING, DATE, BOOLEAN } = app.Sequelize; const PrintComputer = app.model.define('print_computer', { id: { @@ -32,6 +32,42 @@ module.exports = app => { allowNull: true, comment: '上次登录时间', }, + is_recording: { + type: BOOLEAN, + allowNull: false, + defaultValue: false, + comment: '是否作为录制电脑,1-是,0-否', + }, + recording_size_value: { + type: INTEGER.UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '录制大小数值', + }, + recording_size_unit: { + type: STRING(10), + allowNull: true, + defaultValue: null, + comment: '录制存储单位:KB/MB/GB/TB', + }, + remote_play_url: { + type: STRING(500), + allowNull: true, + defaultValue: null, + comment: '远程播放地址', + }, + recording_directory: { + type: STRING(500), + allowNull: true, + defaultValue: null, + comment: '录制目录路径', + }, + deleted_at: { + type: DATE, + allowNull: true, + defaultValue: null, + comment: '软删除时间', + }, }, { tableName: 'wms_print_computer', freezeTableName: true, diff --git a/app/model/print_stations.js b/app/model/print_stations.js index 51278fe..eb4c5b0 100644 --- a/app/model/print_stations.js +++ b/app/model/print_stations.js @@ -136,6 +136,12 @@ module.exports = app => { defaultValue: 0, comment: '软删除标记:0-未删除,1-已删除', }, + deleted_at: { + type: DATE, + allowNull: true, + defaultValue: null, + comment: '软删除时间', + }, subject_config: { type: JSON_TYPE, allowNull: true, diff --git a/app/service/systemMethods/printComputer.js b/app/service/systemMethods/printComputer.js new file mode 100644 index 0000000..d137003 --- /dev/null +++ b/app/service/systemMethods/printComputer.js @@ -0,0 +1,81 @@ +'use strict'; + +const MainService = require('../main'); + +class PrintComputerService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = ''; + const _noNeedLog = '*'; + const _noNeedAuth = ''; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 打印电脑列表。 + * @param {Object} data 查询参数 { pagination, where } + * @return {Promise} 列表数据与分页信息 + */ + async list(data) { + try { + const result = await this.service.systems.printComputer.list(data || {}); + return this.success('获取成功', result); + } catch (e) { return this.fail(e.message); } + } + + /** + * 更新打印电脑。 + * @param {Object} data { id, name? } + * @return {Promise} 更新后的电脑记录 + */ + async update(data) { + try { + const { id, ...fields } = data || {}; + if (!id) return this.fail('ID不能为空'); + return this.success('更新成功', await this.service.systems.printComputer.update(parseInt(id), fields)); + } catch (e) { return this.fail(e.message); } + } + + /** + * 设置录制电脑(会先取消同仓库下其他录制电脑)。 + * @param {Object} data { id, recording_size_value, recording_size_unit, remote_play_url, recording_directory } + * @return {Promise} 设置结果 + */ + async setRecording(data) { + try { + const { id, ...fields } = data || {}; + if (!id) return this.fail('ID不能为空'); + return this.success('设置录制成功', await this.service.systems.printComputer.setRecording(parseInt(id), fields)); + } catch (e) { return this.fail(e.message); } + } + + /** + * 取消录制电脑。 + * @param {Object} data { id } + * @return {Promise} 取消结果 + */ + async cancelRecording(data) { + try { + const { id } = data || {}; + if (!id) return this.fail('ID不能为空'); + return this.success('取消录制成功', await this.service.systems.printComputer.cancelRecording(parseInt(id))); + } catch (e) { return this.fail(e.message); } + } + + /** + * 软删除打印电脑。 + * @param {Object} data { id } + * @return {Promise} 删除结果 + */ + async delete(data) { + try { + const { id } = data || {}; + if (!id) return this.fail('ID不能为空'); + await this.service.systems.printComputer.delete(parseInt(id)); + return this.success('删除成功'); + } catch (e) { return this.fail(e.message); } + } +} + +module.exports = PrintComputerService; diff --git a/app/service/systems/order_print.js b/app/service/systems/order_print.js index accd80f..02399b1 100644 --- a/app/service/systems/order_print.js +++ b/app/service/systems/order_print.js @@ -179,9 +179,9 @@ class OrderPrintSystemService extends OrderBaseService { * 同时从 wms_stock_barcodes 表批量查询每个 stock_id 对应的全部条码, * 注入到打印项的 barcodes 数组中,供 resolveItemBarcodeText 优先读取。 * - * stock_id 优先读取 wms_picking.stock_id(20260708 新增列), - * 兜底读取 wms_order_items.stock_id / item_snapshot.stock_id, - * 消除对 order_items 明细表的强依赖,使配送表订单打印链路也能正常获取商品信息。 + * 商品信息(item_name / barcode / stock_id / quantity)全部从 wms_picking + * 直读,不再反查 order_items 表,彻底消除因订单迁移导致 order_item_id + * 错配的风险。 * * @param {Array} orderRows 订单列表。 * @param {number} warehouseId 仓库ID。 @@ -223,68 +223,7 @@ class OrderPrintSystemService extends OrderBaseService { return resultMap; } - const orderItemIds = Array.from(new Set(normalizedPickingRows - .map(row => Number(row && row.order_item_id || 0)) - .filter(orderItemId => Number.isInteger(orderItemId) && orderItemId > 0))); - - const orderItemModelFactory = this.ctx.model && this.ctx.model.OrderItemsFactory; - const orderItemModel = orderItemModelFactory && typeof orderItemModelFactory.getCurrentModel === 'function' - ? await orderItemModelFactory.getCurrentModel(warehouseId) - : null; - - const orderItemRows = orderItemModel && typeof orderItemModel.findAll === 'function' && orderItemIds.length > 0 - ? await orderItemModel.findAll({ - where: { - id: { - [Op.in]: orderItemIds, - }, - }, - attributes: [ 'id', 'order_id', 'item_code', 'item_name', 'plan_qty', 'item_snapshot', 'stock_id' ], - raw: true, - }) - : []; - - const orderItemMap = new Map(); - for (const row of Array.isArray(orderItemRows) ? orderItemRows : []) { - const orderItemId = Number(row && row.id || 0); - if (orderItemId > 0) { - orderItemMap.set(orderItemId, row); - } - } - - // 兜底:若 current items 表未命中全部 orderItemId,补查 dispatch items 表 - // 配送表订单的 items 可能已迁移到 dispatch items 表,getCurrentModel 查不到 - const foundItemIds = new Set([ ...orderItemMap.keys() ]); - const missingItemIds = orderItemIds.filter(id => !foundItemIds.has(id)); - const dispatchItemRows = []; - if (missingItemIds.length > 0 && orderItemModelFactory && typeof orderItemModelFactory.getDispatchModel === 'function') { - try { - const dispatchItemModel = await orderItemModelFactory.getDispatchModel(warehouseId); - if (dispatchItemModel && typeof dispatchItemModel.findAll === 'function') { - const dispatchRows = await dispatchItemModel.findAll({ - where: { - id: { - [Op.in]: missingItemIds, - }, - }, - attributes: [ 'id', 'order_id', 'item_code', 'item_name', 'plan_qty', 'item_snapshot', 'stock_id' ], - raw: true, - }); - if (Array.isArray(dispatchRows)) { - for (const row of dispatchRows) { - const orderItemId = Number(row && row.id || 0); - if (orderItemId > 0 && !orderItemMap.has(orderItemId)) { - orderItemMap.set(orderItemId, row); - dispatchItemRows.push(row); - } - } - } - } - } catch (err) { - this.ctx.logger.warn('[buildPrintOrderRowMapWithPicking] dispatch items 兜底查询失败:%s', err.message); - } - } - + // 库位兜底:space_name 为空时通过 space_id 补查 location_space 表 const locationFallbackSpaceIds = Array.from(new Set(normalizedPickingRows .filter(row => !String(row && row.space_name || '').trim()) .map(row => Number(row && row.space_id || 0)) @@ -307,6 +246,7 @@ class OrderPrintSystemService extends OrderBaseService { const locationMap = new Map((Array.isArray(locationRows) ? locationRows : []) .map(row => [ Number(row && row.id || 0), row ])); + // 按 order_id 分组 picking 行 const pickingRowsByOrderId = new Map(); for (const row of normalizedPickingRows) { const orderId = Number(row && row.order_id || 0); @@ -319,38 +259,17 @@ class OrderPrintSystemService extends OrderBaseService { pickingRowsByOrderId.set(orderId, list); } - // 阶段一:收集 stock_id(优先 picking.stock_id,兜底 order_items.stock_id) + // 阶段一:从 picking.stock_id 收集所有 stock_id const allStockIds = new Set(); - - // 1a) 从 wms_picking 直接收集 stock_id(新增路径,绕过 order_items 明细表) for (const row of normalizedPickingRows) { const stockId = Number(row && row.stock_id || 0); if (stockId > 0) { allStockIds.add(stockId); } } - - // 1b) 从 order_items 兜底收集 stock_id(兼容 picking.stock_id 为 NULL 的旧数据) - for (const row of Array.isArray(orderItemRows) ? orderItemRows : []) { - const itemSnapshot = this.normalizeItemSnapshot(row.item_snapshot); - const stockId = Number(row.stock_id || itemSnapshot.stock_id || 0); - if (stockId > 0) { - allStockIds.add(stockId); - } - } - - // 1c) 从 dispatch items 兜底收集 stock_id(配送表订单的 items 可能在 dispatch items 表) - for (const row of dispatchItemRows) { - const itemSnapshot = this.normalizeItemSnapshot(row.item_snapshot); - const stockId = Number(row.stock_id || itemSnapshot.stock_id || 0); - if (stockId > 0) { - allStockIds.add(stockId); - } - } - const uniqueStockIds = Array.from(allStockIds); - // 阶段二:批量查询 wms_stock_warehouse 获取商品编码与名称(新增直读路径) + // 阶段二:批量查询 wms_stock_warehouse 获取商品编码与名称 const stockWarehouseMap = new Map(); if (uniqueStockIds.length > 0) { const stockWarehouseModel = this.ctx.model && this.ctx.model.StockWarehouse; @@ -369,7 +288,7 @@ class OrderPrintSystemService extends OrderBaseService { } } - // 阶段三:构建所有打印项(使用 stock_warehouse 直读数据) + // 阶段三:构建所有打印项(全部从 picking + stock_warehouse 直取) const printItemsByOrderId = new Map(); for (const orderRow of rows) { @@ -380,9 +299,8 @@ class OrderPrintSystemService extends OrderBaseService { } const printItems = pickingList.map(pickingRow => { - const orderItemId = Number(pickingRow && pickingRow.order_item_id || 0); - const orderItemRow = orderItemMap.get(orderItemId) || {}; - const itemSnapshot = this.normalizeItemSnapshot(orderItemRow.item_snapshot); + const stockId = Number(pickingRow && pickingRow.stock_id || 0); + const stockInfo = stockId > 0 ? stockWarehouseMap.get(stockId) : null; const locationRow = locationMap.get(Number(pickingRow && pickingRow.space_id || 0)) || {}; const pickLocation = this.getFirstNonEmptyFieldText({ space_name: pickingRow && pickingRow.space_name, @@ -391,40 +309,12 @@ class OrderPrintSystemService extends OrderBaseService { custom_barcode: locationRow.custom_barcode, }, [ 'space_name', 'space_code', 'custom_name', 'custom_barcode' ]); - // stock_id 优先级:picking.stock_id > order_items.stock_id > item_snapshot.stock_id - const pickingStockId = Number(pickingRow && pickingRow.stock_id || 0); - const orderItemStockId = Number(orderItemRow.stock_id || itemSnapshot.stock_id || 0); - const stockId = pickingStockId > 0 ? pickingStockId : orderItemStockId; - - // 从 stock_warehouse 直读商品编码与名称(新增路径,绕过 order_items) - const stockInfo = stockId > 0 ? stockWarehouseMap.get(stockId) : null; - - // item_name 优先级:stock_warehouse > order_items > item_snapshot - const itemName = this.getFirstNonEmptyFieldText({ - stock_item_name: stockInfo && stockInfo.item_name, - snapshot_item_name: itemSnapshot.item_name, - snapshot_name: itemSnapshot.name, - snapshot_title: itemSnapshot.title, - item_name: orderItemRow.item_name, - }, [ 'stock_item_name', 'snapshot_item_name', 'snapshot_name', 'snapshot_title', 'item_name' ]); - - // barcode 优先级:stock_warehouse.item_code > item_snapshot > order_items.item_code - const barcode = this.getFirstNonEmptyFieldText({ - stock_item_code: stockInfo && stockInfo.item_code, - barcode: itemSnapshot.barcode, - item_barcode: itemSnapshot.item_barcode, - bar_code: itemSnapshot.bar_code, - item_code: orderItemRow.item_code, - sku_code: itemSnapshot.sku_code, - sku: itemSnapshot.sku, - }, [ 'stock_item_code', 'barcode', 'item_barcode', 'bar_code', 'item_code', 'sku_code', 'sku' ]); - - const quantity = Number(pickingRow && pickingRow.quantity || orderItemRow.plan_qty || 0); + const quantity = Number(pickingRow && pickingRow.quantity || 0); return { - order_item_id: orderItemId, - item_name: itemName, - barcode, + order_item_id: Number(pickingRow && pickingRow.order_item_id || 0), + item_name: stockInfo ? String(stockInfo.item_name || '').trim() : '', + barcode: stockInfo ? String(stockInfo.item_code || '').trim() : '', quantity: quantity > 0 ? quantity : 0, pick_location: pickLocation, stock_id: stockId > 0 ? stockId : undefined, diff --git a/app/service/systems/printComputer.js b/app/service/systems/printComputer.js new file mode 100644 index 0000000..f973085 --- /dev/null +++ b/app/service/systems/printComputer.js @@ -0,0 +1,319 @@ +'use strict'; + +const Service = require('egg').Service; + +class PrintComputerService extends Service { + /** + * 通知打印服务刷新电脑信息并推送给客户端。 + * @param {number} warehouseId 仓库ID + * @param {number} computerId 电脑ID + * @return {Promise} + */ + async notifyRefreshInfo(warehouseId, computerId) { + const printServiceUrl = this.ctx.app.config.printService.url; + try { + await this.ctx.curl(`${printServiceUrl}/auth/refreshInfo`, { + method: 'POST', + contentType: 'json', + data: { warehouse: warehouseId, computerId }, + dataType: 'json', + }); + } catch (err) { + this.ctx.logger.warn(`通知打印服务刷新电脑 ${computerId} 信息失败: ${err.message}`); + } + } + + /** + * 打印电脑列表(仓库隔离,分页+筛选)。 + * @param {Object} params 查询参数 + * @param {Object} [params.pagination] 分页 { page, pageSize } + * @param {Object} [params.where] 筛选 { is_recording, is_online } + * @return {Promise} { list, pagination } + */ + async list(params = {}) { + const { ctx } = this; + const warehouseId = ctx.user.store_id; + const { pagination = {}, where = {} } = params; + + const page = Math.max(1, parseInt(pagination.page) || 1); + const pageSize = Math.min(200, Math.max(1, parseInt(pagination.pageSize) || 20)); + + const queryWhere = { + warehouse_id: warehouseId, + deleted_at: null, + }; + + // DB 层筛选:is_recording + if (where.is_recording !== undefined && where.is_recording !== null && where.is_recording !== '') { + queryWhere.is_recording = parseInt(where.is_recording) === 1; + } + + // is_online 筛选参数 + const filterOnline = where.is_online !== undefined && where.is_online !== null && where.is_online !== ''; + const onlineValue = filterOnline ? parseInt(where.is_online) : null; + + const redisPrinter = ctx.app.redis.get('printer'); + + if (filterOnline) { + // 有在线状态筛选:先查全量 DB,Redis 标注后内存过滤再分页 + const allRows = await ctx.model.PrintComputer.findAll({ + where: queryWhere, + order: [[ 'id', 'DESC' ]], + raw: true, + }); + + // Redis 标注在线状态 + const enriched = await Promise.all(allRows.map(async row => { + const onlineKey = `warehouse:${warehouseId}:printer:${row.id}`; + const onlineInfo = await redisPrinter.get(onlineKey); + row.is_online = onlineInfo ? 1 : 0; + return row; + })); + + // 内存过滤 + const filtered = enriched.filter(row => row.is_online === onlineValue); + const total = filtered.length; + const list = filtered.slice((page - 1) * pageSize, page * pageSize); + + return { + list, + pagination: { + page, + pageSize, + total, + totalPages: Math.ceil(total / pageSize), + hasPrevious: page > 1, + hasNext: page * pageSize < total, + }, + }; + } + + // 无在线状态筛选:DB 分页查询 + const { count, rows } = await ctx.model.PrintComputer.findAndCountAll({ + where: queryWhere, + order: [[ 'id', 'DESC' ]], + offset: (page - 1) * pageSize, + limit: pageSize, + }); + + // 从 Redis 读取在线状态并附加到每条记录 + const list = await Promise.all(rows.map(async row => { + const plain = row.get ? row.get({ plain: true }) : row; + const onlineKey = `warehouse:${warehouseId}:printer:${plain.id}`; + const onlineInfo = await redisPrinter.get(onlineKey); + plain.is_online = onlineInfo ? 1 : 0; + return plain; + })); + + return { + list, + pagination: { + page, + pageSize, + total: count, + totalPages: Math.ceil(count / pageSize), + hasPrevious: page > 1, + hasNext: page * pageSize < count, + }, + }; + } + + /** + * 更新打印电脑。 + * @param {number} id 电脑ID + * @param {Object} data 要更新的字段 { name } + * @return {Promise} 更新后的记录 + */ + async update(id, data) { + const { ctx } = this; + const warehouseId = ctx.user.store_id; + + const record = await ctx.model.PrintComputer.findOne({ + where: { id, warehouse_id: warehouseId, deleted_at: null }, + }); + if (!record) throw new Error('打印电脑不存在或无权操作'); + + const fields = {}; + if (data.name !== undefined) { + const name = String(data.name).trim(); + if (!name) throw new Error('电脑名称不能为空'); + fields.name = name; + } + + if (Object.keys(fields).length === 0) throw new Error('没有需要更新的字段'); + + await record.update(fields); + + // 通知打印服务推送最新信息给客户端 + await this.notifyRefreshInfo(warehouseId, id); + + return record; + } + + /** + * 设置录制电脑。 + * 会将同仓库下其他已设为录制的电脑取消,再设置当前电脑为录制。 + * @param {number} id 电脑ID + * @param {Object} data { recording_size_value, recording_size_unit, remote_play_url, recording_directory } + * @return {Promise} 更新后的记录 + */ + async setRecording(id, data) { + const { ctx } = this; + const warehouseId = ctx.user.store_id; + + // 参数校验 + if (data.recording_size_value === undefined || data.recording_size_value === null) { + throw new Error('录制大小不能为空'); + } + const sizeValue = parseInt(data.recording_size_value); + if (!Number.isInteger(sizeValue) || sizeValue <= 0) { + throw new Error('录制大小必须为正整数'); + } + + const VALID_UNITS = [ 'KB', 'MB', 'GB', 'TB' ]; + const unit = String(data.recording_size_unit || '').trim().toUpperCase(); + if (!VALID_UNITS.includes(unit)) { + throw new Error(`存储单位不合法,支持:${VALID_UNITS.join('/')}`); + } + + const url = String(data.remote_play_url || '').trim(); + if (!/^https?:\/\/.+/.test(url)) { + throw new Error('远程播放地址必须以 http:// 或 https:// 开头'); + } + + const directory = String(data.recording_directory || '').trim(); + if (!directory) { + throw new Error('录制目录不能为空'); + } + + // 校验目标电脑存在 + const record = await ctx.model.PrintComputer.findOne({ + where: { id, warehouse_id: warehouseId, deleted_at: null }, + }); + if (!record) throw new Error('打印电脑不存在或无权操作'); + + // 先将同仓库下其他已设为录制的电脑取消 + const [ affectedCount ] = await ctx.model.PrintComputer.update( + { + is_recording: false, + recording_size_value: null, + recording_size_unit: null, + remote_play_url: null, + recording_directory: null, + }, + { + where: { + warehouse_id: warehouseId, + is_recording: true, + deleted_at: null, + }, + } + ); + + // 设置当前电脑为录制 + await record.update({ + is_recording: true, + recording_size_value: sizeValue, + recording_size_unit: unit, + remote_play_url: url, + recording_directory: directory, + }); + + // 通知打印服务推送最新信息:当前电脑 + 被取消的其他电脑 + await this.notifyRefreshInfo(warehouseId, id); + // 查询被取消的其他电脑ID并逐一通知 + if (affectedCount > 0) { + const cancelledComputers = await ctx.model.PrintComputer.findAll({ + where: { + warehouse_id: warehouseId, + is_recording: false, + deleted_at: null, + id: { [ctx.app.Sequelize.Op.ne]: id }, + }, + attributes: [ 'id' ], + raw: true, + order: [[ 'id', 'DESC' ]], + limit: affectedCount, + }); + for (const comp of cancelledComputers) { + await this.notifyRefreshInfo(warehouseId, comp.id); + } + } + + return record; + } + + /** + * 取消录制电脑。 + * @param {number} id 电脑ID + * @return {Promise} 更新后的记录 + */ + async cancelRecording(id) { + const { ctx } = this; + const warehouseId = ctx.user.store_id; + + const record = await ctx.model.PrintComputer.findOne({ + where: { id, warehouse_id: warehouseId, deleted_at: null }, + }); + if (!record) throw new Error('打印电脑不存在或无权操作'); + + await record.update({ + is_recording: false, + recording_size_value: null, + recording_size_unit: null, + remote_play_url: null, + recording_directory: null, + }); + + // 通知打印服务推送最新信息给客户端 + await this.notifyRefreshInfo(warehouseId, id); + + return record; + } + + /** + * 软删除打印电脑。 + * 若存在未删除的关联打印台,则拒绝删除。 + * @param {number} id 电脑ID + * @return {Promise} + */ + async delete(id) { + const { ctx } = this; + const warehouseId = ctx.user.store_id; + + const record = await ctx.model.PrintComputer.findOne({ + where: { id, warehouse_id: warehouseId, deleted_at: null }, + }); + if (!record) throw new Error('打印电脑不存在或无权操作'); + + // 检查是否有关联的未删除打印台 + const stationCount = await ctx.model.PrintStations.count({ + where: { + computer_id: id, + warehouse_id: warehouseId, + deleted_at: null, + }, + }); + + if (stationCount > 0) { + throw new Error(`该电脑下存在 ${stationCount} 个未删除的打印台,请先删除打印台后再删除电脑`); + } + + await record.update({ deleted_at: new Date() }); + + // 通知打印服务注销电脑连接 + const printServiceUrl = ctx.app.config.printService.url; + try { + await ctx.curl(`${printServiceUrl}/auth/logout`, { + method: 'POST', + contentType: 'json', + data: { warehouse: warehouseId, computerId: id }, + dataType: 'json', + }); + } catch (err) { + ctx.logger.warn(`通知打印服务注销电脑 ${id} 失败: ${err.message}`); + } + } +} + +module.exports = PrintComputerService; diff --git a/database/migrations/20260720160000-add-print-qty-log-export-permissions.js b/database/migrations/20260720160000-add-print-qty-log-export-permissions.js new file mode 100644 index 0000000..fdc0d75 --- /dev/null +++ b/database/migrations/20260720160000-add-print-qty-log-export-permissions.js @@ -0,0 +1,202 @@ +'use strict'; + +/** + * 面单余额变更日志导出权限迁移。 + * + * 变更内容: + * 1. 新增 2 条 api 权限记录: + * - storeWarehouse.store.exportPrintQuantityLogs — 导出面单余额变更日志 + * - storeWarehouse.store.exportPrintQuantityLogsTaskProgress — 查询导出任务进度 + * 2. 将上述权限授权给 财务以上角色组: + * - 货主管理员 (id=5) + * - 经理 (id=8) + * (超级管理员 id=2/7 的 permissions='*' 无需更新) + * + * 幂等设计: + * - 先查后插(按 path + type 唯一性判断) + * - 角色权限更新使用 JSON 数组合并去重 + */ + +const TABLE_PERMISSION = 'wms_permission'; +const TABLE_ROLE = 'wms_role'; + +/** 需要授权的角色ID(财务以上:货主管理员 + 经理) */ +const TARGET_ROLE_IDS = [5, 8]; + +/** @type {{path: string, name: string, meta_title: string, type: string}[]} */ +const NEW_PERMISSIONS = [ + { + path: 'storeWarehouse.store.exportPrintQuantityLogs', + name: 'storeWarehouse.store.exportPrintQuantityLogs', + meta_title: '导出面单余额变更日志', + type: 'api', + }, + { + path: 'storeWarehouse.store.exportPrintQuantityLogsTaskProgress', + name: 'storeWarehouse.store.exportPrintQuantityLogsTaskProgress', + meta_title: '查询面单余额导出任务进度', + type: 'api', + }, +]; + +/** + * 获取角色当前权限 ID 数组。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {number} roleId 角色ID + * @return {Promise} 权限ID数组 + */ +async function getRolePermissionIds(queryInterface, roleId) { + const [ rows ] = await queryInterface.sequelize.query( + `SELECT permissions FROM \`${TABLE_ROLE}\` WHERE id = :roleId`, + { replacements: { roleId } } + ); + if (!rows || rows.length === 0) return []; + + const raw = rows[0].permissions; + if (!raw || raw === '*') return []; + + try { + const parsed = JSON.parse(raw); + if (Array.isArray(parsed)) { + return parsed.map(Number).filter(n => Number.isFinite(n) && n > 0); + } + } catch (_) { + // ignore + } + + return []; +} + +/** + * 保存角色权限。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {number} roleId 角色ID + * @param {number[]} permissionIds 权限ID数组 + * @return {Promise} + */ +async function saveRolePermissions(queryInterface, roleId, permissionIds) { + const unique = Array.from(new Set(permissionIds)).sort((a, b) => a - b); + const json = JSON.stringify(unique); + + await queryInterface.sequelize.query( + `UPDATE \`${TABLE_ROLE}\` SET permissions = :permissions, updated_at = NOW() WHERE id = :roleId`, + { replacements: { roleId, permissions: json } } + ); +} + +/** + * 正向迁移。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} + */ +module.exports.up = async queryInterface => { + // ─── 1. 插入新权限记录 ───────────────────────────────── + const insertedIds = []; + + for (const perm of NEW_PERMISSIONS) { + const [ existing ] = await queryInterface.sequelize.query( + `SELECT id FROM \`${TABLE_PERMISSION}\` WHERE path = :path AND type = :type LIMIT 1`, + { replacements: { path: perm.path, type: perm.type } } + ); + + if (existing && existing.length > 0) { + console.log(`[Migration] 权限已存在: ${perm.path} (id=${existing[0].id})`); + insertedIds.push(Number(existing[0].id)); + continue; + } + + const [ result ] = await queryInterface.sequelize.query( + `INSERT INTO \`${TABLE_PERMISSION}\` (path, name, meta_title, type, status, created_at, update_at) + VALUES (:path, :name, :meta_title, :type, 1, NOW(), NOW())`, + { replacements: { path: perm.path, name: perm.name, meta_title: perm.meta_title, type: perm.type } } + ); + + const newId = Number(result); + insertedIds.push(newId); + console.log(`[Migration] 新增权限: ${perm.path} (id=${newId})`); + } + + // ─── 2. 授权给财务以上角色组 ────────────────────────── + for (const roleId of TARGET_ROLE_IDS) { + const [ roleRows ] = await queryInterface.sequelize.query( + `SELECT id, permissions FROM \`${TABLE_ROLE}\` WHERE id = :roleId`, + { replacements: { roleId } } + ); + + if (!roleRows || roleRows.length === 0) { + console.log(`[Migration] 角色不存在: id=${roleId}`); + continue; + } + + const raw = roleRows[0].permissions; + // 跳过 permissions='*' 的角色(已拥有全部权限) + if (raw === '*') { + console.log(`[Migration] 角色 id=${roleId} 已有全部权限(*),跳过`); + continue; + } + + const currentIds = await getRolePermissionIds(queryInterface, roleId); + const newIds = insertedIds.filter(id => !currentIds.includes(id)); + + if (newIds.length === 0) { + console.log(`[Migration] 角色 id=${roleId} 已拥有目标权限,跳过`); + continue; + } + + const merged = [ ...currentIds, ...newIds ]; + await saveRolePermissions(queryInterface, roleId, merged); + console.log(`[Migration] 角色 id=${roleId} 授权成功,新增权限: [${newIds.join(', ')}]`); + } + + console.log( + `[Migration] 面单余额导出权限迁移完成:` + + `新增 ${NEW_PERMISSIONS.length} 条权限,授权 ${TARGET_ROLE_IDS.length} 个角色` + ); +}; + +/** + * 回滚迁移。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} + */ +module.exports.down = async queryInterface => { + // ─── 1. 从角色权限中移除新增的权限ID ───────────────── + const allPaths = NEW_PERMISSIONS.map(p => p.path); + + for (const roleId of TARGET_ROLE_IDS) { + const [ roleRows ] = await queryInterface.sequelize.query( + `SELECT id, permissions FROM \`${TABLE_ROLE}\` WHERE id = :roleId`, + { replacements: { roleId } } + ); + + if (!roleRows || roleRows.length === 0) continue; + + const raw = roleRows[0].permissions; + if (!raw || raw === '*') continue; + + const currentIds = await getRolePermissionIds(queryInterface, roleId); + // 查询需要移除的权限ID + const [ permRows ] = await queryInterface.sequelize.query( + `SELECT id FROM \`${TABLE_PERMISSION}\` WHERE path IN (:paths) AND type = 'api'`, + { replacements: { paths: allPaths } } + ); + const removeIds = permRows.map(r => Number(r.id)); + const filtered = currentIds.filter(id => !removeIds.includes(id)); + + if (filtered.length !== currentIds.length) { + await saveRolePermissions(queryInterface, roleId, filtered); + console.log(`[Migration] 角色 id=${roleId} 已移除导出权限`); + } + } + + // ─── 2. 删除新增的权限记录 ─────────────────────────── + for (const perm of NEW_PERMISSIONS) { + await queryInterface.sequelize.query( + `DELETE FROM \`${TABLE_PERMISSION}\` WHERE path = :path AND type = :type`, + { replacements: { path: perm.path, type: perm.type } } + ); + console.log(`[Migration] 已删除权限: ${perm.path}`); + } + + console.log('[Migration] 面单余额导出权限回滚完成'); +}; diff --git a/database/migrations/20260725120000-add-is-recording-to-wms-print-computer.js b/database/migrations/20260725120000-add-is-recording-to-wms-print-computer.js new file mode 100644 index 0000000..9eb4535 --- /dev/null +++ b/database/migrations/20260725120000-add-is-recording-to-wms-print-computer.js @@ -0,0 +1,28 @@ +'use strict'; + +module.exports = { + /** + * 为打印台电脑表新增"是否作为录制电脑"字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + await queryInterface.addColumn('wms_print_computer', 'is_recording', { + type: Sequelize.BOOLEAN, + allowNull: false, + defaultValue: false, + comment: '是否作为录制电脑,1-是,0-否', + }); + }, + + /** + * 回滚删除打印台电脑表的"是否作为录制电脑"字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async down(queryInterface, Sequelize) { + await queryInterface.removeColumn('wms_print_computer', 'is_recording'); + }, +}; diff --git a/database/migrations/20260725130000-add-deleted-at-to-wms-print-computer.js b/database/migrations/20260725130000-add-deleted-at-to-wms-print-computer.js new file mode 100644 index 0000000..29469be --- /dev/null +++ b/database/migrations/20260725130000-add-deleted-at-to-wms-print-computer.js @@ -0,0 +1,28 @@ +'use strict'; + +module.exports = { + /** + * 为打印台电脑表新增软删除时间字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + await queryInterface.addColumn('wms_print_computer', 'deleted_at', { + type: Sequelize.DATE, + allowNull: true, + defaultValue: null, + comment: '软删除时间', + }); + }, + + /** + * 回滚删除打印台电脑表的软删除时间字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async down(queryInterface, Sequelize) { + await queryInterface.removeColumn('wms_print_computer', 'deleted_at'); + }, +}; diff --git a/database/migrations/20260725140000-add-deleted-at-to-wms-print-stations.js b/database/migrations/20260725140000-add-deleted-at-to-wms-print-stations.js new file mode 100644 index 0000000..2fa89e0 --- /dev/null +++ b/database/migrations/20260725140000-add-deleted-at-to-wms-print-stations.js @@ -0,0 +1,28 @@ +'use strict'; + +module.exports = { + /** + * 为打印台表新增软删除时间字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + await queryInterface.addColumn('wms_print_stations', 'deleted_at', { + type: Sequelize.DATE, + allowNull: true, + defaultValue: null, + comment: '软删除时间', + }); + }, + + /** + * 回滚删除打印台表的软删除时间字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async down(queryInterface, Sequelize) { + await queryInterface.removeColumn('wms_print_stations', 'deleted_at'); + }, +}; diff --git a/database/migrations/20260725150000-add-print-computer-permissions.js b/database/migrations/20260725150000-add-print-computer-permissions.js new file mode 100644 index 0000000..0cdfe6f --- /dev/null +++ b/database/migrations/20260725150000-add-print-computer-permissions.js @@ -0,0 +1,86 @@ +'use strict'; + +module.exports = { + /** + * 新增打印电脑模块 API 权限,并授权客服主管及以上角色。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + const now = new Date(); + + // 1. 插入 3 条 API 权限 + const permissions = [ + { path: 'print_computer.list', name: '打印电脑-列表', type: 'api', status: 1, created_at: now, update_at: now }, + { path: 'print_computer.update', name: '打印电脑-更新', type: 'api', status: 1, created_at: now, update_at: now }, + { path: 'print_computer.delete', name: '打印电脑-删除', type: 'api', status: 1, created_at: now, update_at: now }, + ]; + + await queryInterface.bulkInsert('wms_permission', permissions); + + // 2. 查询刚插入的权限 ID + const [rows] = await queryInterface.sequelize.query( + `SELECT id FROM wms_permission WHERE path IN ('print_computer.list', 'print_computer.update', 'print_computer.delete') ORDER BY id` + ); + const ids = rows.map(r => r.id); + if (ids.length !== 3) { + throw new Error(`权限插入异常:期望 3 条,实际 ${ids.length} 条`); + } + + // 3. 授权客服主管及以上角色(排除 permissions='*' 的超级管理员角色) + const roleIds = [2, 5, 7, 8, 22, 26, 28, 29]; + for (const permId of ids) { + await queryInterface.sequelize.query(` + UPDATE wms_role + SET permissions = JSON_ARRAY_APPEND(permissions, '$', CAST(${permId} AS UNSIGNED)), + updated_at = NOW() + WHERE id IN (${roleIds.join(',')}) + AND permissions IS NOT NULL + AND permissions != '*' + AND permissions != '[]' + AND JSON_VALID(permissions) = 1 + AND JSON_CONTAINS(permissions, '${permId}', '$') = 0 + `); + } + }, + + /** + * 回滚:删除权限记录并从角色权限中移除。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async down(queryInterface, Sequelize) { + const paths = ['print_computer.list', 'print_computer.update', 'print_computer.delete']; + + // 1. 查询权限 ID + const [rows] = await queryInterface.sequelize.query( + `SELECT id FROM wms_permission WHERE path IN ('${paths.join("','")}')` + ); + const ids = rows.map(r => r.id); + + // 2. 从角色权限中移除 + const roleIds = [2, 5, 7, 8, 22, 26, 28, 29]; + for (const permId of ids) { + await queryInterface.sequelize.query(` + UPDATE wms_role + SET permissions = JSON_REMOVE( + permissions, + JSON_UNQUOTE(JSON_SEARCH(permissions, 'one', '${permId}')) + ), + updated_at = NOW() + WHERE id IN (${roleIds.join(',')}) + AND permissions IS NOT NULL + AND permissions != '*' + AND JSON_VALID(permissions) = 1 + AND JSON_CONTAINS(permissions, '${permId}', '$') = 1 + `); + } + + // 3. 删除权限记录 + await queryInterface.bulkDelete('wms_permission', { + path: { [Sequelize.Op.in]: paths }, + }); + }, +}; diff --git a/database/migrations/20260725160000-add-recording-fields-to-wms-print-computer.js b/database/migrations/20260725160000-add-recording-fields-to-wms-print-computer.js new file mode 100644 index 0000000..dd12a85 --- /dev/null +++ b/database/migrations/20260725160000-add-recording-fields-to-wms-print-computer.js @@ -0,0 +1,42 @@ +'use strict'; + +module.exports = { + /** + * 为打印电脑表新增录制相关字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + await queryInterface.addColumn('wms_print_computer', 'recording_size_value', { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '录制大小数值', + }); + await queryInterface.addColumn('wms_print_computer', 'recording_size_unit', { + type: Sequelize.STRING(10), + allowNull: true, + defaultValue: null, + comment: '录制存储单位:KB/MB/GB/TB', + }); + await queryInterface.addColumn('wms_print_computer', 'remote_play_url', { + type: Sequelize.STRING(500), + allowNull: true, + defaultValue: null, + comment: '远程播放地址', + }); + }, + + /** + * 回滚删除录制相关字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async down(queryInterface, Sequelize) { + await queryInterface.removeColumn('wms_print_computer', 'remote_play_url'); + await queryInterface.removeColumn('wms_print_computer', 'recording_size_unit'); + await queryInterface.removeColumn('wms_print_computer', 'recording_size_value'); + }, +}; diff --git a/database/migrations/20260725170000-add-recording-permissions.js b/database/migrations/20260725170000-add-recording-permissions.js new file mode 100644 index 0000000..4542c82 --- /dev/null +++ b/database/migrations/20260725170000-add-recording-permissions.js @@ -0,0 +1,82 @@ +'use strict'; + +module.exports = { + /** + * 新增打印电脑录制相关 API 权限,并授权客服主管及以上角色。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + const now = new Date(); + + // 1. 插入 2 条 API 权限 + const permissions = [ + { path: 'print_computer.setRecording', name: '打印电脑-设置录制', type: 'api', status: 1, created_at: now, update_at: now }, + { path: 'print_computer.cancelRecording', name: '打印电脑-取消录制', type: 'api', status: 1, created_at: now, update_at: now }, + ]; + + await queryInterface.bulkInsert('wms_permission', permissions); + + // 2. 查询刚插入的权限 ID + const [rows] = await queryInterface.sequelize.query( + `SELECT id FROM wms_permission WHERE path IN ('print_computer.setRecording', 'print_computer.cancelRecording') ORDER BY id` + ); + const ids = rows.map(r => r.id); + if (ids.length !== 2) { + throw new Error(`权限插入异常:期望 2 条,实际 ${ids.length} 条`); + } + + // 3. 授权客服主管及以上角色 + const roleIds = [2, 5, 7, 8, 22, 26, 28, 29]; + for (const permId of ids) { + await queryInterface.sequelize.query(` + UPDATE wms_role + SET permissions = JSON_ARRAY_APPEND(permissions, '$', CAST(${permId} AS UNSIGNED)), + updated_at = NOW() + WHERE id IN (${roleIds.join(',')}) + AND permissions IS NOT NULL + AND permissions != '*' + AND permissions != '[]' + AND JSON_VALID(permissions) = 1 + AND JSON_CONTAINS(permissions, '${permId}', '$') = 0 + `); + } + }, + + /** + * 回滚:删除权限记录并从角色权限中移除。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async down(queryInterface, Sequelize) { + const paths = ['print_computer.setRecording', 'print_computer.cancelRecording']; + + const [rows] = await queryInterface.sequelize.query( + `SELECT id FROM wms_permission WHERE path IN ('${paths.join("','")}')` + ); + const ids = rows.map(r => r.id); + + const roleIds = [2, 5, 7, 8, 22, 26, 28, 29]; + for (const permId of ids) { + await queryInterface.sequelize.query(` + UPDATE wms_role + SET permissions = JSON_REMOVE( + permissions, + JSON_UNQUOTE(JSON_SEARCH(permissions, 'one', '${permId}')) + ), + updated_at = NOW() + WHERE id IN (${roleIds.join(',')}) + AND permissions IS NOT NULL + AND permissions != '*' + AND JSON_VALID(permissions) = 1 + AND JSON_CONTAINS(permissions, '${permId}', '$') = 1 + `); + } + + await queryInterface.bulkDelete('wms_permission', { + path: { [Sequelize.Op.in]: paths }, + }); + }, +}; diff --git a/database/migrations/20260725180000-add-recording-directory-to-wms-print-computer.js b/database/migrations/20260725180000-add-recording-directory-to-wms-print-computer.js new file mode 100644 index 0000000..e20fdd0 --- /dev/null +++ b/database/migrations/20260725180000-add-recording-directory-to-wms-print-computer.js @@ -0,0 +1,28 @@ +'use strict'; + +module.exports = { + /** + * 为打印电脑表新增录制目录字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + await queryInterface.addColumn('wms_print_computer', 'recording_directory', { + type: Sequelize.STRING(500), + allowNull: true, + defaultValue: null, + comment: '录制目录路径,如 D:/record', + }); + }, + + /** + * 回滚删除录制目录字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async down(queryInterface, Sequelize) { + await queryInterface.removeColumn('wms_print_computer', 'recording_directory'); + }, +}; From 972c912e534de9212ebb42a14d10b5bc0e1e83b2 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 27 Jul 2026 03:47:27 +0800 Subject: [PATCH 126/550] =?UTF-8?q?feat(express):=20=E5=BF=AB=E9=80=92?= =?UTF-8?q?=E6=8E=A5=E5=8F=A3=E6=94=AF=E6=8C=81=E5=90=AF=E7=94=A8/?= =?UTF-8?q?=E5=81=9C=E7=94=A8=EF=BC=8C=E8=BF=87=E6=BB=A4=E5=8F=96=E6=B6=88?= =?UTF-8?q?=E7=8A=B6=E6=80=81=E8=AE=A2=E5=8D=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - express_interface 新增 is_enabled 字段(1=启用, 0=停用) - expressInterface service 支持 is_enabled 筛选与编辑 - express 运单分配跳过停用接口 + 取消状态订单过滤 - 迁移: 20260724100000-add-is-enabled-to-wms-express-interface --- app/model/express_interface.js | 6 ++++ .../systemMethods/setting/expressInterface.js | 8 +++++ app/service/systems/express.js | 17 ++++++++-- .../systems/setting/expressInterface.js | 34 +++++++++++++++---- ...add-is-enabled-to-wms-express-interface.js | 17 ++++++++++ 5 files changed, 74 insertions(+), 8 deletions(-) create mode 100644 database/migrations/20260724100000-add-is-enabled-to-wms-express-interface.js diff --git a/app/model/express_interface.js b/app/model/express_interface.js index b31e991..b849d6e 100644 --- a/app/model/express_interface.js +++ b/app/model/express_interface.js @@ -180,6 +180,12 @@ module.exports = app => { defaultValue: 0, comment: '是否隐藏物品信息', }, + is_enabled: { + type: TINYINT(1), + allowNull: true, + defaultValue: 1, + comment: '是否启用(1=启用,0=停用)', + }, shipperno: { type: STRING(255), allowNull: true, diff --git a/app/service/systemMethods/setting/expressInterface.js b/app/service/systemMethods/setting/expressInterface.js index 914e658..83313d8 100644 --- a/app/service/systemMethods/setting/expressInterface.js +++ b/app/service/systemMethods/setting/expressInterface.js @@ -110,6 +110,9 @@ class expressInterfaceService extends MainService { shop_name: { field: 'shop_name', }, + is_enabled: { + field: 'is_enabled', + }, quickWhere: { bucket: 'quick', }, @@ -269,6 +272,8 @@ class expressInterfaceService extends MainService { providerType, providerid, providerId, + is_enabled: isEnabledSnake, + isEnabled: isEnabledCamel, ...rest } = data || {}; @@ -328,6 +333,9 @@ class expressInterfaceService extends MainService { if (providerid !== undefined || providerId !== undefined) { payload.providerid = providerid !== undefined ? providerid : providerId; } + if (isEnabledSnake !== undefined || isEnabledCamel !== undefined) { + payload.is_enabled = isEnabledSnake !== undefined ? isEnabledSnake : isEnabledCamel; + } return await this.callSystemExpressInterface('update', payload, '更新快递接口失败'); } diff --git a/app/service/systems/express.js b/app/service/systems/express.js index dbaea22..02d2439 100644 --- a/app/service/systems/express.js +++ b/app/service/systems/express.js @@ -632,6 +632,9 @@ class ExpressService extends Service { id: { [Op.in]: normalizedOrderIds, }, + status: { + [Op.ne]: 'cancel', + }, }, transaction, }); @@ -695,7 +698,12 @@ class ExpressService extends Service { order_flag: normalizedErrorMessage, updated_at: new Date(), }, { - where, + where: { + ...where, + status: { + [Op.ne]: 'cancel', + }, + }, }); } @@ -1788,6 +1796,11 @@ class ExpressService extends Service { continue; } + // 停用的快递接口不允许分配运单号 + if (Number(item.is_enabled) !== 1) { + continue; + } + const candidateCodes = [ normalizeCode(item.sys_express_code), normalizeCode(item.express_code), @@ -2046,7 +2059,7 @@ class ExpressService extends Service { items: this.normalizeWaybillAsyncItems(orderDelivery.items), items_count: this.normalizeWaybillAsyncNumber(orderDelivery.items_count), items_total: this.normalizeWaybillAsyncNumber(orderDelivery.items_total), - items_weight: this.normalizeWaybillAsyncNumber(orderDelivery.items_weight), + items_weight: this.normalizeWaybillAsyncNumber(orderDelivery.items_weight), // 单位 g,传递给下游快递平台 }; } diff --git a/app/service/systems/setting/expressInterface.js b/app/service/systems/setting/expressInterface.js index ff4ebfc..0d95bf0 100644 --- a/app/service/systems/setting/expressInterface.js +++ b/app/service/systems/setting/expressInterface.js @@ -307,6 +307,9 @@ class SettingExpressInterfaceService extends Service { shop_name: { field: 'shop_name', }, + is_enabled: { + field: 'is_enabled', + }, quickWhere: { bucket: 'quick', }, @@ -366,12 +369,16 @@ class SettingExpressInterfaceService extends Service { includes[0].attributes = [ 'code', 'name' ]; } - if (full && ctx.model && ctx.model.Shop) { - includes.push({ + if (ctx.model && ctx.model.Shop) { + const shopInclude = { model: ctx.model.Shop, as: 'shop', required: false, - }); + }; + if (!full) { + shopInclude.attributes = [ 'id', 'shop_name' ]; + } + includes.push(shopInclude); } return includes; @@ -742,6 +749,7 @@ class SettingExpressInterfaceService extends Service { weight_type: row.weight_type === undefined || row.weight_type === null ? null : Number(row.weight_type), viewer: this.normalizeOptionalText(row.viewer, 'viewer', 50), client_id: this.normalizeOptionalText(row.client_id, 'client_id', 50), + is_enabled: row.is_enabled === undefined || row.is_enabled === null ? null : Number(row.is_enabled), is_share: row.is_share === undefined || row.is_share === null ? null : Number(row.is_share), ispickup: row.ispickup === undefined || row.ispickup === null ? null : Number(row.ispickup), shipperno: this.normalizeOptionalText(row.shipperno, 'shipperno', 255), @@ -754,7 +762,11 @@ class SettingExpressInterfaceService extends Service { town_name: this.normalizeOptionalText(row.town_name, 'town_name', 255), site_code: this.normalizeOptionalText(row.site_code, 'site_code', 255), product_type: this.normalizeOptionalText(row.product_type, 'product_type', 50), - shop_name: this.normalizeOptionalText(row.shop_name, 'shop_name', 255), + shop_name: this.normalizeOptionalText( + (row.shop && row.shop.shop_name) || row.shop_name, + 'shop_name', + 255 + ), express, express_name: express ? express.name : null, express_polyapi_extra_info: express ? express.polyapi_extra_info : null, @@ -1075,7 +1087,7 @@ class SettingExpressInterfaceService extends Service { 'sys_express_code', 'sender_name', 'sender_tel', 'weight', 'viewer', 'client_id', 'is_share', 'province_name', 'city_name', 'district_name', 'site_code', - 'product_type', 'weight_type', 'shop_name', 'address', 'town_name', 'ispickup', 'shipperno', 'template_url', 'ext_data', + 'product_type', 'weight_type', 'shop_name', 'address', 'town_name', 'ispickup', 'shipperno', 'template_url', 'ext_data', 'is_enabled', ], order: [[ 'weight', 'ASC' ], [ 'id', 'DESC' ]], offset, @@ -1353,6 +1365,8 @@ class SettingExpressInterfaceService extends Service { || Object.prototype.hasOwnProperty.call(data, 'shopName'); const hasExtData = Object.prototype.hasOwnProperty.call(data, 'ext_data') || Object.prototype.hasOwnProperty.call(data, 'extData'); + const hasIsEnabled = Object.prototype.hasOwnProperty.call(data, 'is_enabled') + || Object.prototype.hasOwnProperty.call(data, 'isEnabled'); if (!hasName && !hasExpressCode && !hasPlatformCode && !hasSysExpressCode && !hasSenderName && !hasSenderTel && !hasWeight && !hasWeightType @@ -1360,7 +1374,7 @@ class SettingExpressInterfaceService extends Service { && !hasProviderType && !hasProviderId && !hasViewer && !hasClientId && !hasIsPickup && !hasShipperNo && !hasTemplateUrl && !hasProvinceName && !hasCityName && !hasDistrictName && !hasAddress && !hasTownName && !hasSiteCode - && !hasProductType && !hasShopName && !hasExtData) { + && !hasProductType && !hasShopName && !hasExtData && !hasIsEnabled) { throw this.createError('至少需要提供一个可更新字段', 400); } @@ -1556,6 +1570,14 @@ class SettingExpressInterfaceService extends Service { ); } + if (hasIsEnabled) { + updates.is_enabled = this.normalizeFlag( + data.is_enabled !== undefined ? data.is_enabled : data.isEnabled, + 'is_enabled', + 1 + ); + } + if (hasExpressCode || hasPlatformCode || hasSysExpressCode) { updates.sys_express_code = await this.resolveSysExpressCode({ expressCode: nextExpressCode, diff --git a/database/migrations/20260724100000-add-is-enabled-to-wms-express-interface.js b/database/migrations/20260724100000-add-is-enabled-to-wms-express-interface.js new file mode 100644 index 0000000..08ade1d --- /dev/null +++ b/database/migrations/20260724100000-add-is-enabled-to-wms-express-interface.js @@ -0,0 +1,17 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.addColumn('wms_express_interface', 'is_enabled', { + type: Sequelize.TINYINT(1), + allowNull: true, + defaultValue: 1, + comment: '是否启用(1=启用,0=停用)', + after: 'is_hide_goods', + }); + }, + + async down(queryInterface, Sequelize) { + await queryInterface.removeColumn('wms_express_interface', 'is_enabled'); + }, +}; From 3c53b3c8fa74d10d5be69fa74446f7326787658e Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 27 Jul 2026 03:47:49 +0800 Subject: [PATCH 127/550] =?UTF-8?q?feat(storage):=20=E5=85=A5=E5=BA=93/?= =?UTF-8?q?=E6=94=B6=E8=B4=A7=E6=A8=A1=E5=9D=97=E8=B4=A7=E4=B8=BB=E4=BE=A7?= =?UTF-8?q?=E5=8A=9F=E8=83=BD=20(listStore,=20export)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - entry: 新增 listStore(货主维度列表)、export/exportTaskProgress(异步导出) - entry: 新增 storeExport/storeExportTaskProgress(货主侧导出) - receiving: 新增 getStoreReceivingList(货主维度收货单查询) - receiving: 新增 export 异步导出 + fix 时间字段 created_at→updated_at - 迁移: receiving_detail creator_id 去 zerofill + 货主收货权限 --- app/service/systemMethods/storage/entry.js | 414 ++++++++++- .../systemMethods/storage/receiving.js | 305 ++++++++- app/service/systems/storage/receiving.js | 641 +++++++++++++++++- ...20260712-add-store-receiving-permission.js | 163 +++++ ...ll-from-wms-receiving-detail-creator-id.js | 17 + 5 files changed, 1529 insertions(+), 11 deletions(-) create mode 100644 database/migrations/20260712-add-store-receiving-permission.js create mode 100644 database/migrations/20260718180000-remove-zerofill-from-wms-receiving-detail-creator-id.js diff --git a/app/service/systemMethods/storage/entry.js b/app/service/systemMethods/storage/entry.js index dfaa61e..2dc7da3 100644 --- a/app/service/systemMethods/storage/entry.js +++ b/app/service/systemMethods/storage/entry.js @@ -1,5 +1,9 @@ 'use strict'; const MainService = require('../../main'); + +const ENTRY_EXPORT_TASK_CACHE_KEY_PREFIX = 'entry_export_task_'; +const ENTRY_EXPORT_TASK_CACHE_TTL_SECONDS = 1800; + /** * 系统方法层:storage.entry(入库单相关接口包装层)。 * 主要职责:统一包装系统方法接口,处理权限、日志等公共逻辑,调用底层 service 实现业务功能。 @@ -9,9 +13,9 @@ class entryService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'list,get,cancel,getPrintData,getDirectInboundItems,addItem,commit,removeItem,quickInbound,receivingCompare,queryEntryLogs,getReceivingDetailsForBind,reviewEntry,containerList'; - const _noNeedLog = 'list,get,getPrintData,reviewEntry,containerList'; - const _noNeedAuth = 'list,get,cancel,getPrintData,getDirectInboundItems,addItem,commit,removeItem,bindReceiving,quickInbound,receivingCompare,unbindReceiving,queryEntryLogs,getReceivingDetailsForBind,reviewEntry,containerList'; + const _noNeedRight = 'list,listStore,get,getStore,cancel,getPrintData,getDirectInboundItems,addItem,commit,removeItem,quickInbound,receivingCompare,queryEntryLogs,getReceivingDetailsForBind,reviewEntry,containerList,export,exportTaskProgress,storeExport,storeExportTaskProgress'; + const _noNeedLog = 'list,listStore,get,getStore,getPrintData,reviewEntry,export,exportTaskProgress,storeExport,storeExportTaskProgress'; + const _noNeedAuth = 'list,listStore,get,getStore,cancel,getPrintData,getDirectInboundItems,addItem,commit,removeItem,bindReceiving,quickInbound,receivingCompare,unbindReceiving,queryEntryLogs,getReceivingDetailsForBind,reviewEntry,containerList,export,exportTaskProgress,storeExport,storeExportTaskProgress'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -37,6 +41,40 @@ class entryService extends MainService { return this.success('ok', result); } + /** + * 货主侧入库单列表查询。 + * 与 list 共享底层逻辑,但以货主维度(store_id)过滤,不使用仓库维度(warehouse_id)。 + * 货主登录后仅能看到自己货主下的入库单。 + * @param {Object} data 请求体 + * @param {Object} [data.pagination] 分页参数 + * @param {Object} [data.where] 动态筛选条件 + * @param {Object} [data.sort] 排序参数 + * @return {Promise} 统一 success 包装 + */ + async listStore(data = {}) { + const { service } = this; + const { pagination, sort } = data; + const { where } = this.prepareWhereContext(data, { + specialFieldMap: { + quickWhere: { + bucket: 'quick', + }, + }, + }); + const result = await service.systems.storage.entry.list(where, pagination, sort, 'store'); + + // 裁剪货主侧冗余字段:货主自己的 store_name/store 关联、奇门编码 + if (result && result.data && Array.isArray(result.data.list)) { + result.data.list.forEach(item => { + delete item.store_name; + delete item.store; + delete item.qimen_owner_code; + delete item.qimen_warehouse_code; + }); + } + return this.success('ok', result); + } + /** * 查询入库单详情(与原 storage.directInbound.getItems 输出格式一致)。 * 返回入库单基本信息(id、entry_order_code、order_status、store_remask)、 @@ -53,6 +91,22 @@ class entryService extends MainService { return this.success('ok', result); } + /** + * 货主侧查询入库单详情。与 get 共享底层逻辑, + * 但以货主维度(store_id)校验权限(不使用 warehouse_id), + * 货主登录后仅能查看自己货主下的入库单明细。 + * 返回结构与 get 一致。 + * @param {Object} data 请求体 + * @param {number} data.id 入库单ID(必填) + * @return {Promise} 统一 success 包装 + */ + async getStore(data = {}) { + const { service } = this; + const { id } = data || {}; + const result = await service.systems.storage.entry.get({ id }, 'store'); + return this.success('ok', result); + } + /** * 作废入库单。 * 支持传入单个 id 或批量 ids,保持透传给业务层处理。 @@ -379,5 +433,359 @@ class entryService extends MainService { return this.fail(result?.message || '审核失败', result, 400); } + /** + * 提交入库单导出任务(复用 list 的筛选语义与排序规则)。 + * 导出分为两个 sheet:Sheet1=入库单列表,Sheet2=入库单明细(按入库单分页拉取写入流)。 + * @param {Object} data 请求体 + * @param {Object} [data.where] 筛选条件(与 list 一致) + * @param {Object} [data.sort] 排序参数 + * @return {Promise} 统一成功包装响应,data 为导出任务信息 + */ + async export(data = {}) { + const { service } = this; + const { where, sort } = data || {}; + + const taskId = this.generateExportTaskId(); + const taskPayload = { + task_id: taskId, + status: 'submitted', + progress: 0, + message: '导出任务已提交', + result: null, + error: '', + }; + + await this.setExportTaskProgress(taskId, taskPayload); + + setImmediate(async () => { + try { + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'running', + progress: 5, + message: '导出任务执行中', + result: null, + error: '', + }); + + const result = await service.systems.storage.entry.exportEntryOrders({ + where: this.isPlainObject(where) ? { ...where } : {}, + sort: this.isPlainObject(sort) ? { ...sort } : {}, + onProgress: async progress => { + const safeProgress = this.isPlainObject(progress) ? progress : {}; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: safeProgress.status || 'running', + progress: safeProgress.progress, + message: safeProgress.message || '导出任务执行中', + result: safeProgress.result || null, + error: '', + }); + }, + }); + + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'success', + progress: 100, + message: '导出任务完成', + result, + error: '', + }); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'failed', + progress: 100, + message: '导出任务失败', + result: null, + error: errorMessage, + }); + } + }); + + return this.success('ok', { + ...taskPayload, + update_time: Date.now(), + }); + } + + /** + * 查询入库单导出任务进度。 + * @param {Object} data 请求体 + * @param {string} [data.task_id] 任务ID(下划线写法) + * @param {string} [data.taskId] 任务ID(驼峰写法) + * @return {Promise} 统一成功包装响应 + */ + async exportTaskProgress(data = {}) { + const taskId = this.normalizeExportTaskId(data); + if (!taskId) { + return this.success('ok', { + task_id: '', + status: 'not_found', + progress: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const cachedTask = await this.getExportTaskProgress(taskId); + if (!cachedTask) { + return this.success('ok', { + task_id: taskId, + status: 'not_found', + progress: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {}; + const downloadUrl = String( + safeResult.url + || safeResult.cdnUrl + || safeResult.cosUrl + || safeResult.fileKey + || '' + ); + + return this.success('ok', { + task_id: taskId, + ...cachedTask, + download_url: downloadUrl, + }); + } + + /** + * 生成入库单导出任务ID。 + * @param {string} [prefix=''] 任务类型前缀(如 'store') + * @return {string} 导出任务ID + */ + generateExportTaskId(prefix = '') { + const storeId = this.ctx?.user?.store_id || 'unknown'; + const timestamp = Date.now(); + const randomToken = Math.random().toString(36).slice(2, 10); + const typePrefix = prefix ? `${prefix}_` : ''; + return `entry_${typePrefix}export_${storeId}_${timestamp}_${randomToken}`; + } + + /** + * 归一化入库单导出任务ID。 + * @param {Object} data 请求体 + * @param {string} [data.task_id] 任务ID(下划线写法) + * @param {string} [data.taskId] 任务ID(驼峰写法) + * @return {string} 归一化后的任务ID + */ + normalizeExportTaskId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.task_id || normalizedData.taskId || '').trim(); + } + + /** + * 获取入库单导出任务缓存键。 + * @param {string} taskId 任务ID + * @return {string} 缓存键 + */ + getExportTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + return `${ENTRY_EXPORT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 写入入库单导出任务进度缓存。 + * @param {string} taskId 任务ID + * @param {Object} payload 任务状态载荷 + * @return {Promise} 无返回值 + */ + async setExportTaskProgress(taskId = '', payload = {}) { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.setCacheAsync !== 'function') { + return; + } + + const safePayload = this.isPlainObject(payload) ? payload : {}; + const progressPayload = { + task_id: String(taskId || '').trim(), + status: String(safePayload.status || 'submitted').trim() || 'submitted', + progress: Number.isFinite(Number(safePayload.progress)) ? Math.min(100, Math.max(0, Math.round(Number(safePayload.progress)))) : 0, + message: String(safePayload.message || ''), + result: safePayload.result ?? null, + error: String(safePayload.error || ''), + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync(cacheKey, progressPayload, ENTRY_EXPORT_TASK_CACHE_TTL_SECONDS); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + this.ctx.logger.warn(`[storage.entry.export] 写入导出任务缓存失败: ${errorMessage}`); + } + } + + /** + * 读取入库单导出任务进度缓存。 + * @param {string} taskId 任务ID + * @return {Promise} 任务缓存 + */ + async getExportTaskProgress(taskId = '') { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.getCacheAsync !== 'function') { + return null; + } + + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (!this.isPlainObject(cached)) { + return null; + } + return cached; + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + this.ctx.logger.warn(`[storage.entry.export] 读取导出任务缓存失败: ${errorMessage}`); + return null; + } + } + + /** + * 提交货主侧入库单导出任务(复用 listStore 的筛选语义与排序规则)。 + * 导出分为两个 sheet:Sheet1=入库单列表,Sheet2=入库单明细(按入库单分页拉取写入流)。 + * @param {Object} data 请求体 + * @param {Object} [data.where] 筛选条件(与 listStore 一致) + * @param {Object} [data.sort] 排序参数 + * @return {Promise} 统一成功包装响应,data 为导出任务信息 + */ + async storeExport(data = {}) { + const { service } = this; + const { where, sort } = data || {}; + + const taskId = this.generateExportTaskId('store'); + const taskPayload = { + task_id: taskId, + status: 'submitted', + progress: 0, + message: '货主侧入库单导出任务已提交', + result: null, + error: '', + }; + + await this.setExportTaskProgress(taskId, taskPayload); + + setImmediate(async () => { + try { + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'running', + progress: 5, + message: '货主侧入库单导出任务执行中', + result: null, + error: '', + }); + + const result = await service.systems.storage.entry.exportStoreEntryOrders({ + where: this.isPlainObject(where) ? { ...where } : {}, + sort: this.isPlainObject(sort) ? { ...sort } : {}, + onProgress: async progress => { + const safeProgress = this.isPlainObject(progress) ? progress : {}; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: safeProgress.status || 'running', + progress: safeProgress.progress, + message: safeProgress.message || '货主侧入库单导出任务执行中', + result: safeProgress.result || null, + error: '', + }); + }, + }); + + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'success', + progress: 100, + message: '货主侧入库单导出任务完成', + result, + error: '', + }); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'failed', + progress: 100, + message: '货主侧入库单导出任务失败', + result: null, + error: errorMessage, + }); + } + }); + + return this.success('ok', { + ...taskPayload, + update_time: Date.now(), + }); + } + + /** + * 查询货主侧入库单导出任务进度。 + * 复用 exportTaskProgress 的缓存查询逻辑,任务 ID 前缀不同。 + * @param {Object} data 请求体 + * @param {string} [data.task_id] 任务ID(下划线写法) + * @param {string} [data.taskId] 任务ID(驼峰写法) + * @return {Promise} 统一成功包装响应 + */ + async storeExportTaskProgress(data = {}) { + const taskId = this.normalizeExportTaskId(data); + if (!taskId) { + return this.success('ok', { + task_id: '', + status: 'not_found', + progress: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const cachedTask = await this.getExportTaskProgress(taskId); + if (!cachedTask) { + return this.success('ok', { + task_id: taskId, + status: 'not_found', + progress: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {}; + const downloadUrl = String( + safeResult.url + || safeResult.cdnUrl + || safeResult.cosUrl + || safeResult.fileKey + || '' + ); + + return this.success('ok', { + task_id: taskId, + ...cachedTask, + download_url: downloadUrl, + }); + } + } module.exports = entryService; diff --git a/app/service/systemMethods/storage/receiving.js b/app/service/systemMethods/storage/receiving.js index 1cf6234..56c7ec0 100644 --- a/app/service/systemMethods/storage/receiving.js +++ b/app/service/systemMethods/storage/receiving.js @@ -1,6 +1,9 @@ 'use strict'; const MainService = require('../../main'); + +const RECEIVING_EXPORT_TASK_CACHE_KEY_PREFIX = 'receiving_export_task_'; +const RECEIVING_EXPORT_TASK_CACHE_TTL_SECONDS = 1800; /** * 系统方法层:storage.receiving(收货单相关接口包装层)。 * 主要职责:统一包装系统方法接口,处理权限、日志等公共逻辑,调用底层 service 实现业务功能。 @@ -10,9 +13,9 @@ class configService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs,scanDetail'; - const _noNeedLog = 'getReceivingList,get,addDetail,deleteDetail,detailChange,bindStore,bindDetailProduct,queryReceivingLogs,scanDetail'; - const _noNeedAuth = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs,scanDetail'; + const _noNeedRight = 'getReceivingList,getStoreReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs,scanDetail,export,exportTaskProgress'; + const _noNeedLog = 'getReceivingList,getStoreReceivingList,get,addDetail,deleteDetail,detailChange,bindStore,bindDetailProduct,queryReceivingLogs,scanDetail,export,exportTaskProgress'; + const _noNeedAuth = 'getReceivingList,getStoreReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs,scanDetail,export,exportTaskProgress'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -39,6 +42,55 @@ class configService extends MainService { return this.success('ok', result); } + /** + * 货主侧收货单列表查询(system method 包装层)。 + * 以当前平台激活的货主 store_id 为维度查询收货单。 + * @param {Object} data 请求体 + * @param {Object} [data.pagination] 分页参数 + * @param {Object} [data.where] 筛选条件 + * @param {Object} [data.sort] 排序参数 + * @return {Promise} 统一成功包装响应 + */ + async getStoreReceivingList(data) { + const { ctx, app } = this; + const { pagination, sort } = data; + + // 从平台激活上下文获取 store_id(使用原生查询避免 AccountPlatformActive 无 id 列兼容问题) + const platformRows = await app.model.query( + 'SELECT apa.employee_id, ase.store_id FROM wms_account_platform_active apa ' + + 'INNER JOIN wms_account_store_employee ase ON ase.id = apa.employee_id AND ase.status = 1 ' + + 'WHERE apa.account_id = :accountId AND apa.platform_code = :platformCode LIMIT 1', + { + replacements: { accountId: ctx.userId, platformCode: ctx.platformCode || 'web' }, + type: app.Sequelize.QueryTypes.SELECT, + } + ); + + if (!platformRows || platformRows.length === 0 || !platformRows[0].store_id) { + return this.fail('未获取到货主平台激活上下文,请先切换至货主角色'); + } + + const storeId = platformRows[0].store_id; + + const { where } = this.prepareWhereContext(data, { + specialFieldMap: { + quickWhere: { + bucket: 'quick', + }, + }, + }); + + const { service } = this; + const result = await service.systems.storage.receiving.getStoreReceivingList( + where, + storeId, + pagination, + sort + ); + + return this.success('ok', result); + } + /** * 收货单详情查询(分页返回明细)。 * @param {Object} data 请求体 @@ -280,5 +332,252 @@ class configService extends MainService { return this.success('查询成功', result.data); } + /** + * 提交收货单导出任务(复用 getStoreReceivingList 的筛选语义与排序规则)。 + * 导出分为两个 sheet:Sheet1=收货单列表,Sheet2=收货单明细。 + * @param {Object} data 请求体 + * @param {Object} [data.where] 筛选条件(与 getStoreReceivingList 一致) + * @param {Object} [data.sort] 排序参数 + * @return {Promise} 统一成功包装响应,data 为导出任务信息 + */ + async export(data = {}) { + const { ctx, app, service } = this; + + // 从平台激活上下文获取 store_id + const platformRows = await app.model.query( + 'SELECT apa.employee_id, ase.store_id FROM wms_account_platform_active apa ' + + 'INNER JOIN wms_account_store_employee ase ON ase.id = apa.employee_id AND ase.status = 1 ' + + 'WHERE apa.account_id = :accountId AND apa.platform_code = :platformCode LIMIT 1', + { + replacements: { accountId: ctx.userId, platformCode: ctx.platformCode || 'web' }, + type: app.Sequelize.QueryTypes.SELECT, + } + ); + + if (!platformRows || platformRows.length === 0 || !platformRows[0].store_id) { + return this.fail('未获取到货主平台激活上下文,请先切换至货主角色'); + } + + const storeId = platformRows[0].store_id; + const { sort = {} } = data; + + const { where } = this.prepareWhereContext(data, { + specialFieldMap: { + quickWhere: { + bucket: 'quick', + }, + }, + }); + + const taskId = this.generateExportTaskId(); + const taskPayload = { + task_id: taskId, + status: 'submitted', + progress: 0, + message: '收货单导出任务已提交', + result: null, + error: '', + }; + + await this.setExportTaskProgress(taskId, taskPayload); + + setImmediate(async () => { + try { + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'running', + progress: 5, + message: '收货单导出任务执行中', + result: null, + error: '', + }); + + const result = await service.systems.storage.receiving.exportReceivingList({ + where, + storeId, + sort, + onProgress: async progress => { + const safeProgress = this.isPlainObject(progress) ? progress : {}; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: safeProgress.status || 'running', + progress: safeProgress.progress, + message: safeProgress.message || '收货单导出任务执行中', + result: safeProgress.result || null, + error: '', + }); + }, + }); + + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'success', + progress: 100, + message: '收货单导出任务完成', + result, + error: '', + }); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'failed', + progress: 100, + message: '收货单导出任务失败', + result: null, + error: errorMessage, + }); + } + }); + + return this.success('ok', { + ...taskPayload, + update_time: Date.now(), + }); + } + + /** + * 查询收货单导出任务进度。 + * @param {Object} data 请求体 + * @param {string} [data.task_id] 任务ID(下划线写法) + * @param {string} [data.taskId] 任务ID(驼峰写法) + * @return {Promise} 统一成功包装响应 + */ + async exportTaskProgress(data = {}) { + const taskId = this.normalizeExportTaskId(data); + if (!taskId) { + return this.success('ok', { + task_id: '', + status: 'not_found', + progress: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const cachedTask = await this.getExportTaskProgress(taskId); + if (!cachedTask) { + return this.success('ok', { + task_id: taskId, + status: 'not_found', + progress: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {}; + const downloadUrl = String( + safeResult.url + || safeResult.cdnUrl + || safeResult.cosUrl + || safeResult.fileKey + || '' + ); + + return this.success('ok', { + task_id: taskId, + ...cachedTask, + download_url: downloadUrl, + }); + } + + /** + * 生成收货单导出任务ID。 + * @return {string} 导出任务ID + */ + generateExportTaskId() { + const storeId = this.ctx?.user?.store_id || 'unknown'; + const timestamp = Date.now(); + const randomToken = Math.random().toString(36).slice(2, 10); + return `receiving_export_${storeId}_${timestamp}_${randomToken}`; + } + + /** + * 归一化收货单导出任务ID。 + * @param {Object} data 请求体 + * @param {string} [data.task_id] 任务ID(下划线写法) + * @param {string} [data.taskId] 任务ID(驼峰写法) + * @return {string} 归一化后的任务ID + */ + normalizeExportTaskId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.task_id || normalizedData.taskId || '').trim(); + } + + /** + * 获取收货单导出任务缓存键。 + * @param {string} taskId 任务ID + * @return {string} 缓存键 + */ + getExportTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + return `${RECEIVING_EXPORT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 写入收货单导出任务进度缓存。 + * @param {string} taskId 任务ID + * @param {Object} payload 任务状态载荷 + * @return {Promise} 无返回值 + */ + async setExportTaskProgress(taskId = '', payload = {}) { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.setCacheAsync !== 'function') { + return; + } + + const safePayload = this.isPlainObject(payload) ? payload : {}; + const progressPayload = { + task_id: String(taskId || '').trim(), + status: String(safePayload.status || 'submitted').trim() || 'submitted', + progress: Number.isFinite(Number(safePayload.progress)) ? Math.min(100, Math.max(0, Math.round(Number(safePayload.progress)))) : 0, + message: String(safePayload.message || ''), + result: safePayload.result ?? null, + error: String(safePayload.error || ''), + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync(cacheKey, progressPayload, RECEIVING_EXPORT_TASK_CACHE_TTL_SECONDS); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + this.ctx.logger.warn(`[storage.receiving.export] 写入导出任务缓存失败: ${errorMessage}`); + } + } + + /** + * 读取收货单导出任务进度缓存。 + * @param {string} taskId 任务ID + * @return {Promise} 任务缓存 + */ + async getExportTaskProgress(taskId = '') { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.getCacheAsync !== 'function') { + return null; + } + + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (!this.isPlainObject(cached)) { + return null; + } + return cached; + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + this.ctx.logger.warn(`[storage.receiving.export] 读取导出任务缓存失败: ${errorMessage}`); + return null; + } + } + } module.exports = configService; diff --git a/app/service/systems/storage/receiving.js b/app/service/systems/storage/receiving.js index 9817c79..7b76949 100644 --- a/app/service/systems/storage/receiving.js +++ b/app/service/systems/storage/receiving.js @@ -1,9 +1,18 @@ 'use strict'; +const crypto = require('node:crypto'); +const fs = require('node:fs'); +const fsp = require('node:fs/promises'); +const os = require('node:os'); +const path = require('node:path'); +const ExcelJS = require('exceljs'); const Service = require('egg').Service; const { parseWhereConditions } = require('../../../lib/query_condition_parser'); const DAY_MS = 24 * 60 * 60 * 1000; +const RECEIVING_EXPORT_PAGE_SIZE = 200; +const RECEIVING_ITEMS_FETCH_BATCH_SIZE = 100; + function getStartOfDayMs(value) { const date = new Date(value); if (Number.isNaN(date.getTime())) return null; @@ -366,8 +375,8 @@ class ReceivingService extends Service { available_quantity: availableQuantity, lock_rate: parseFloat(lockRate), lock_rate_display: `${lockRate}%`, - create_at_display: item.create_at ? this.formatDate(item.create_at) : '', - update_at_display: item.update_at ? this.formatDate(item.update_at) : '', + create_at_display: item.created_at ? this.app.formatDate(item.created_at) : '', + update_at_display: item.updated_at ? this.app.formatDate(item.updated_at) : '', }; }); @@ -425,6 +434,201 @@ class ReceivingService extends Service { }; } } + /** + * 货主侧收货单列表查询。 + * 以 store_id 为维度查询收货单,支持分页、多条件筛选与排序。 + * @param {Object} where 动态筛选条件 + * @param {number} storeId 货主ID(必填) + * @param {Object} [pageParams] 分页参数 + * @param {number} [pageParams.page=1] 页码 + * @param {number} [pageParams.pageSize=20] 每页条数 + * @param {Object} [sortParams] 排序参数 + * @param {string} [sortParams.sortField='created_at'] 排序字段 + * @param {string} [sortParams.sortOrder='DESC'] 排序方向 + * @return {Promise} 列表、分页与汇总信息 + */ + async getStoreReceivingList(where, storeId, pageParams = {}, sortParams = {}) { + const { ctx, app } = this; + const { Sequelize } = app; + const { Op } = Sequelize; + const { page = 1, pageSize = 20 } = pageParams; + const { sortField = 'created_at', sortOrder = 'DESC' } = sortParams; + + try { + const queryOptions = { + where: { + [Op.and]: [ + { store_id: storeId }, + ], + }, + order: [], + attributes: { + exclude: [ 'deleted_at' ], + }, + }; + + const normalizedWhere = where && typeof where === 'object' ? where : {}; + let parsedResult = ctx.whereParsed; + if (!parsedResult || !Array.isArray(parsedResult.dynamicConditions)) { + const parsed = parseWhereConditions({ + where: normalizedWhere, + app, + specialFieldMap: { + quickWhere: { + bucket: 'quick', + }, + }, + }); + + if (!parsed.ok) { + return { + code: 400, + data: { + list: [], + pagination: { page: Number(page), pageSize: Number(pageSize), total: 0, totalPages: 0, hasPrevious: false, hasNext: false }, + summary: { total_quantity: 0, total_locked: 0, total_available: 0, total_items: 0 }, + }, + message: `筛选条件解析失败: ${parsed.reason}`, + }; + } + parsedResult = parsed.result; + } + + const dynamicConditions = [ ...(parsedResult.dynamicConditions || []) ]; + const quickWhereRaw = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere) + || normalizedWhere.quickWhere; + + if (quickWhereRaw && quickWhereRaw.value && String(quickWhereRaw.value).trim() !== '') { + const quickValue = String(quickWhereRaw.value).trim(); + dynamicConditions.push({ + [Op.or]: { + store_name: { [Sequelize.Op.like]: `%${quickValue}%` }, + receiving_number: { [Sequelize.Op.like]: `%${quickValue}%` }, + tracking_number: { [Sequelize.Op.like]: `%${quickValue}%` }, + creator_snapshot: { [Sequelize.Op.like]: `%${quickValue}%` }, + license_plate: { [Sequelize.Op.like]: `%${quickValue}%` }, + }, + }); + } + + if (dynamicConditions.length > 0) { + queryOptions.where[Op.and].push({ [Op.and]: dynamicConditions }); + } + + const validSortFields = [ 'id', 'receiving_number', 'status', 'created_at', 'updated_at', 'store_id', 'warehouse_id' ]; + const actualSortField = validSortFields.includes(sortField) ? sortField : 'created_at'; + const actualSortOrder = sortOrder.toUpperCase() === 'ASC' ? 'ASC' : 'DESC'; + queryOptions.order.push([ actualSortField, actualSortOrder ]); + + const offset = (page - 1) * pageSize; + + const [ total, data ] = await Promise.all([ + ctx.model.Receiving.count({ + where: queryOptions.where, + distinct: true, + }), + ctx.model.Receiving.findAll({ + ...queryOptions, + limit: Number(pageSize), + offset: Number(offset), + distinct: true, + raw: true, + }), + ]); + + const totalPages = Math.ceil(total / pageSize); + const hasPrevious = page > 1; + const hasNext = page < totalPages; + + // 获取收货单图片 + const stockIds = data.map(item => item.id); + let images = []; + if (stockIds.length > 0) { + images = await ctx.model.FileReference.findAll({ + where: { + business_type: 'receiving', + business_id: { [Op.in]: stockIds }, + }, + include: [ + { + model: ctx.model.File, + as: 'file', + attributes: [ 'file_url' ], + required: true, + }, + ], + }); + } + + const processedData = data.map(item => { + const availableQuantity = Math.max(0, item.total_quantity || 0); + const itemImages = images + .filter(row => Number(row.business_id) === item.id) + .map(row => row.file.file_url); + // 从 creator_snapshot 解析操作人姓名 + let creatorName = ''; + try { + if (item.creator_snapshot) { + const snapshot = JSON.parse(item.creator_snapshot); + creatorName = snapshot.name || ''; + } + } catch (_) { + // ignore parse error + } + return { + ...item, + images: itemImages, + available_quantity: availableQuantity, + lock_rate: 0, + lock_rate_display: '0%', + creator_name: creatorName, + create_at_display: item.created_at ? this.app.formatDate(item.created_at) : '', + update_at_display: item.updated_at ? this.app.formatDate(item.updated_at) : '', + }; + }); + + const summary = { + total_quantity: data.reduce((sum, item) => sum + (item.total_quantity || 0), 0), + total_locked: 0, + total_available: data.reduce((sum, item) => sum + (item.total_quantity || 0), 0), + total_items: data.length, + }; + + return { + code: 200, + data: { + list: processedData, + pagination: { + page: Number(page), + pageSize: Number(pageSize), + total, + totalPages, + hasPrevious, + hasNext, + }, + summary, + queryInfo: { + conditions: normalizedWhere, + sortField: actualSortField, + sortOrder: actualSortOrder, + hasBarcodeSearch: false, + }, + }, + message: '查询成功', + }; + } catch (error) { + ctx.logger.error('[ReceivingService.getStoreReceivingList] 查询失败:', error); + return { + code: 500, + data: { + list: [], + pagination: { page: Number(page || 1), pageSize: Number(pageSize || 20), total: 0, totalPages: 0, hasPrevious: false, hasNext: false }, + summary: { total_quantity: 0, total_locked: 0, total_available: 0, total_items: 0 }, + }, + message: `查询失败: ${error.message}`, + }; + } + } /** * 获取收货单详情(主单 + 明细分页 + 图片)。 * @param {Object} data 请求体 @@ -2904,11 +3108,11 @@ class ReceivingService extends Service { async deleteDetail(data) { const ctx = this.ctx; const { detail_id } = data; - const creator_id = ctx.user.employees_id; const warehouse_id = ctx.user.store_id; - // 验证明细是否存在 + // 验证明细是否存在(通过收货单的 warehouse_id 做权限校验,不限制 creator_id, + // 以允许同一仓库下不同操作员删除彼此创建的明细,与 get 方法行为保持一致) const detail = await ctx.model.ReceivingDetail.findOne({ - where: { id: detail_id, creator_id }, + where: { id: detail_id }, include: [ { model: ctx.model.Receiving, @@ -4507,6 +4711,433 @@ class ReceivingService extends Service { } } + /** + * 导出收货单列表(双 sheet:收货单列表 + 收货单明细)。 + * 复用 getStoreReceivingList 的筛选与排序语义,分页拉取全量数据后生成 Excel 并上传。 + * @param {Object} options 导出选项 + * @param {Object} [options.where] 筛选条件 + * @param {number} options.storeId 货主ID + * @param {Object} [options.sort] 排序参数 + * @param {Function} [options.onProgress] 进度回调 + * @return {Promise} 上传结果与统计信息 + */ + async exportReceivingList(options = {}) { + const { ctx, app } = this; + const { Sequelize } = app; + const { Op } = Sequelize; + const safeOptions = options && typeof options === 'object' ? options : {}; + const where = safeOptions.where && typeof safeOptions.where === 'object' ? { ...safeOptions.where } : {}; + const storeId = Number(safeOptions.storeId); + const sort = safeOptions.sort && typeof safeOptions.sort === 'object' ? { ...safeOptions.sort } : {}; + const progressHandler = typeof safeOptions.onProgress === 'function' + ? safeOptions.onProgress + : async () => {}; + + if (!storeId) { + throw new Error('货主ID不能为空,无法导出'); + } + + const sortField = sort.sortField || 'created_at'; + const sortOrder = String(sort.sortOrder || 'DESC').toUpperCase() === 'ASC' ? 'ASC' : 'DESC'; + const validSortFields = [ + 'id', 'receiving_number', 'status', 'created_at', 'updated_at', 'store_id', 'warehouse_id', + ]; + const actualSortField = validSortFields.includes(sortField) ? sortField : 'created_at'; + + // 构建 where 条件(与 getStoreReceivingList 一致) + const queryOptions = { + where: { [Op.and]: [{ store_id: storeId }] }, + }; + + const normalizedWhere = { ...where }; + const parsed = parseWhereConditions({ + where: normalizedWhere, + app, + specialFieldMap: { + quickWhere: { bucket: 'quick' }, + }, + }); + + if (!parsed.ok) { + throw new Error(`筛选条件解析失败: ${parsed.reason}`); + } + const parsedResult = parsed.result; + + const dynamicConditions = [ ...(parsedResult.dynamicConditions || []) ]; + const quickWhereRaw = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere) + || normalizedWhere.quickWhere; + + if (quickWhereRaw && quickWhereRaw.value && String(quickWhereRaw.value).trim() !== '') { + const quickValue = String(quickWhereRaw.value).trim(); + dynamicConditions.push({ + [Op.or]: { + store_name: { [Op.like]: `%${quickValue}%` }, + receiving_number: { [Op.like]: `%${quickValue}%` }, + tracking_number: { [Op.like]: `%${quickValue}%` }, + creator_snapshot: { [Op.like]: `%${quickValue}%` }, + license_plate: { [Op.like]: `%${quickValue}%` }, + }, + }); + } + + if (dynamicConditions.length > 0) { + queryOptions.where[Op.and].push({ [Op.and]: dynamicConditions }); + } + + // ---- 分页拉取收货单列表 ---- + const totalCount = await ctx.model.Receiving.count({ + where: queryOptions.where, + distinct: true, + }); + + await progressHandler({ + status: 'running', + progress: totalCount > 0 ? 10 : 85, + message: totalCount > 0 ? `已命中 ${totalCount} 条收货单,开始导出` : '未命中数据,开始生成空文件', + }); + + const allReceivingOrders = []; + let page = 1; + let fetchedCount = 0; + + while (fetchedCount < totalCount) { + const rows = await ctx.model.Receiving.findAll({ + where: queryOptions.where, + order: [[ actualSortField, sortOrder ]], + limit: RECEIVING_EXPORT_PAGE_SIZE, + offset: (page - 1) * RECEIVING_EXPORT_PAGE_SIZE, + raw: true, + }); + + if (!Array.isArray(rows) || rows.length === 0) { + break; + } + + allReceivingOrders.push(...rows); + fetchedCount += rows.length; + page += 1; + + await progressHandler({ + status: 'running', + progress: Math.min(30, 10 + Math.round((fetchedCount / Math.max(totalCount, 1)) * 20)), + message: `正在拉取收货单列表,已完成 ${fetchedCount}/${totalCount}`, + }); + } + + // ---- 批量拉取收货单明细 ---- + const allReceivingIds = allReceivingOrders.map(r => Number(r.id)).filter(Boolean); + /** @type {Map>} receiving_id → details */ + const detailsMap = new Map(); + + if (allReceivingIds.length > 0) { + const batchSize = RECEIVING_ITEMS_FETCH_BATCH_SIZE; + const totalBatches = Math.ceil(allReceivingIds.length / batchSize); + + for (let batchIdx = 0; batchIdx < allReceivingIds.length; batchIdx += batchSize) { + const batchIds = allReceivingIds.slice(batchIdx, batchIdx + batchSize); + + const details = await ctx.model.ReceivingDetail.findAll({ + where: { receiving_id: { [Op.in]: batchIds } }, + order: [[ 'receiving_id', 'ASC' ], [ 'id', 'ASC' ]], + raw: true, + }); + + for (const detail of details) { + const rid = Number(detail.receiving_id); + if (!detailsMap.has(rid)) { + detailsMap.set(rid, []); + } + detailsMap.get(rid).push(detail); + } + + const currentBatch = Math.floor(batchIdx / batchSize) + 1; + await progressHandler({ + status: 'running', + progress: Math.min(50, 30 + Math.round((currentBatch / totalBatches) * 20)), + message: `正在拉取收货单明细,已完成批次 ${currentBatch}/${totalBatches}`, + }); + } + } + + await progressHandler({ + status: 'running', + progress: 55, + message: '正在生成 Excel 文件...', + }); + + // ---- 生成 Excel(流式写入,两个 Sheet) ---- + const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'wms-receiving-export-')); + const now = new Date(); + const dateToken = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}`; + const filename = `收货单导出_${dateToken}.xlsx`; + const filePath = path.join(tempDir, filename); + const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({ + filename: filePath, + useStyles: false, + useSharedStrings: false, + }); + + const normalizeCellValue = value => { + if (value === null || value === undefined) return ''; + if (value instanceof Date) return app.formatDate ? app.formatDate(value) : value.toISOString(); + return value; + }; + + const statusLabelMap = { + receiving: '收货中', + completed: '已完成', + cancelled: '已作废', + }; + + const detailStatusLabelMap = { + all_matched: '全部匹配', + partial_matched: '部分匹配', + unmatched: '未匹配', + }; + + const storageStatusLabelMap = { + none: '未入库', + waiting: '等待入库', + partial: '部分入库', + all: '全部入库', + }; + + const deliveryMethodLabelMap = { + truck: '货车', + express: '快递', + air_freight: '空运', + sea_freight: '海运', + other: '其他', + }; + + const loadingMethodLabelMap = { + with_pallet: '带托盘', + without_pallet: '不带托盘', + }; + + // Sheet 1: 收货单列表 + const sheet1 = workbook.addWorksheet('收货单列表'); + const receivingColumns = [ + { header: '收货单ID', key: 'id', width: 10 }, + { header: '收货单号', key: 'receiving_number', width: 22 }, + { header: '货主', key: 'store_name', width: 20 }, + { header: '收货状态', key: 'status_label', width: 12 }, + { header: '明细匹配状态', key: 'detail_status_label', width: 14 }, + { header: '入库状态', key: 'storage_status_label', width: 12 }, + { header: '来货方式', key: 'delivery_method_label', width: 12 }, + { header: '车牌号', key: 'license_plate', width: 14 }, + { header: '快递单号', key: 'tracking_number', width: 22 }, + { header: '装卸方式', key: 'loading_method_label', width: 12 }, + { header: '总商品种类', key: 'total_items', width: 12 }, + { header: '总数量', key: 'total_quantity', width: 12 }, + { header: '总箱数', key: 'total_boxes', width: 10 }, + { header: '总托盘数', key: 'total_pallets', width: 10 }, + { header: '审核状态', key: 'is_review_label', width: 10 }, + { header: '创建人', key: 'creator_name', width: 14 }, + { header: '备注', key: 'remark', width: 30 }, + { header: '收货开始时间', key: 'receiving_start_time', width: 20 }, + { header: '收货结束时间', key: 'receiving_end_time', width: 20 }, + { header: '创建时间', key: 'created_at', width: 20 }, + { header: '更新时间', key: 'updated_at', width: 20 }, + ]; + sheet1.columns = receivingColumns; + + for (const row of allReceivingOrders) { + let creatorName = ''; + try { + if (row.creator_snapshot) { + const snapshot = JSON.parse(row.creator_snapshot); + creatorName = snapshot.name || ''; + } + } catch (_) { /* ignore */ } + + sheet1.addRow({ + id: row.id, + receiving_number: normalizeCellValue(row.receiving_number), + store_name: normalizeCellValue(row.store_name), + status_label: statusLabelMap[row.status] || row.status || '', + detail_status_label: detailStatusLabelMap[row.detail_status] || row.detail_status || '', + storage_status_label: storageStatusLabelMap[row.storage_status] || row.storage_status || '', + delivery_method_label: deliveryMethodLabelMap[row.delivery_method] || row.delivery_method || '', + license_plate: normalizeCellValue(row.license_plate), + tracking_number: normalizeCellValue(row.tracking_number), + loading_method_label: loadingMethodLabelMap[row.loading_method] || row.loading_method || '', + total_items: row.total_items, + total_quantity: row.total_quantity, + total_boxes: row.total_boxes, + total_pallets: row.total_pallets, + is_review_label: row.is_review === 1 ? '已审核' : '未审核', + creator_name: creatorName, + remark: normalizeCellValue(row.remark), + receiving_start_time: normalizeCellValue(row.receiving_start_time), + receiving_end_time: normalizeCellValue(row.receiving_end_time), + created_at: normalizeCellValue(row.created_at), + updated_at: normalizeCellValue(row.updated_at), + }).commit(); + } + sheet1.commit(); + + await progressHandler({ + status: 'running', + progress: 70, + message: '正在写入收货单明细...', + }); + + // Sheet 2: 收货单明细 + const sheet2 = workbook.addWorksheet('收货单明细'); + const detailColumns = [ + { header: '收货单号', key: 'receiving_number', width: 22 }, + { header: '收货单ID', key: 'receiving_id', width: 12 }, + { header: '明细ID', key: 'detail_id', width: 10 }, + { header: '商品名称', key: 'product_name', width: 28 }, + { header: '商品条码', key: 'barcode', width: 20 }, + { header: '系统商品ID', key: 'system_product_id', width: 14 }, + { header: '实际收货数量', key: 'actual_quantity', width: 14 }, + { header: '箱数', key: 'box_quantity', width: 10 }, + { header: '托盘数', key: 'pallet_quantity', width: 10 }, + { header: '收货状态', key: 'receiving_status_label', width: 12 }, + { header: '入库状态', key: 'storage_status_label', width: 12 }, + { header: '已入库数量', key: 'stored_quantity', width: 12 }, + { header: '批次号', key: 'batch_number', width: 16 }, + { header: '生产日期', key: 'production_date', width: 14 }, + { header: '到期日期', key: 'expiry_date', width: 14 }, + { header: '备注', key: 'remark', width: 30 }, + { header: '创建时间', key: 'created_at', width: 20 }, + ]; + sheet2.columns = detailColumns; + + // 构建 receiving_number 映射 + const receivingCodeMap = new Map(); + for (const row of allReceivingOrders) { + receivingCodeMap.set(Number(row.id), row.receiving_number || ''); + } + + const detailReceivingStatusLabelMap = { + pending: '待收货', + receiving: '收货中', + completed: '已完成', + cancelled: '已作废', + }; + + const detailStorageStatusLabelMap = { + none: '未入库', + waiting: '等待入库', + partial: '部分入库', + all: '全部入库', + }; + + // 按收货单分页写入明细 + const itemBatchSize = RECEIVING_ITEMS_FETCH_BATCH_SIZE; + let itemWrittenCount = 0; + const totalReceivingOrders = allReceivingIds.length; + + for (let batchIdx = 0; batchIdx < allReceivingIds.length; batchIdx += itemBatchSize) { + const batchIds = allReceivingIds.slice(batchIdx, batchIdx + itemBatchSize); + + for (const rid of batchIds) { + const receivingNumber = receivingCodeMap.get(rid) || ''; + const details = detailsMap.get(rid) || []; + + for (const detail of details) { + sheet2.addRow({ + receiving_number: receivingNumber, + receiving_id: rid, + detail_id: detail.id, + product_name: normalizeCellValue(detail.product_name), + barcode: normalizeCellValue(detail.barcode), + system_product_id: normalizeCellValue(detail.system_product_id), + actual_quantity: detail.actual_quantity, + box_quantity: detail.box_quantity, + pallet_quantity: detail.pallet_quantity, + receiving_status_label: detailReceivingStatusLabelMap[detail.receiving_status] || detail.receiving_status || '', + storage_status_label: detailStorageStatusLabelMap[detail.storage_status] || detail.storage_status || '', + stored_quantity: detail.stored_quantity, + batch_number: normalizeCellValue(detail.batch_number), + production_date: normalizeCellValue(detail.production_date), + expiry_date: normalizeCellValue(detail.expiry_date), + remark: normalizeCellValue(detail.remark), + created_at: normalizeCellValue(detail.created_at), + }).commit(); + } + + itemWrittenCount += 1; + } + + const currentBatch = Math.floor(batchIdx / itemBatchSize) + 1; + const totalBatches = Math.ceil(totalReceivingOrders / itemBatchSize); + await progressHandler({ + status: 'running', + progress: Math.min(90, 70 + Math.round((currentBatch / totalBatches) * 20)), + message: `正在写入收货单明细,已完成 ${itemWrittenCount}/${totalReceivingOrders} 条收货单`, + }); + } + sheet2.commit(); + + await workbook.commit(); + + await progressHandler({ + status: 'running', + progress: 92, + message: '正在上传文件...', + }); + + // ---- 上传文件 ---- + const uploadService = ctx?.service?.systems?.upload; + if (!uploadService || typeof uploadService.uploadFile !== 'function') { + throw new Error('上传服务不可用'); + } + + const stat = await fsp.stat(filePath); + const randomToken = crypto.randomBytes(6).toString('hex'); + const uploadKey = `exports/receiving/${storeId}/${Date.now()}_${randomToken}.xlsx`; + const uploadStream = fs.createReadStream(filePath); + uploadStream.filename = filename; + uploadStream.mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; + uploadStream.fileSize = stat.size; + + const uploadResult = await uploadService.uploadFile(uploadStream, { + key: uploadKey, + category: 'document', + mimetype: 'xls,xlsx,csv', + }); + + let fileRecord = null; + if (typeof uploadService.uploadSuccessNotify === 'function') { + fileRecord = await uploadService.uploadSuccessNotify({ + url: uploadResult.fileName, + fileKey: uploadResult.fileName, + fileName: filename, + fileType: 'document', + mimeType: uploadStream.mimeType, + fileSize: stat.size, + userId: ctx.userId, + description: `收货单导出(货主${storeId}),共${totalCount}条收货单`, + }); + } + + // 清理临时文件 + try { await fsp.rm(tempDir, { recursive: true, force: true }); } catch (_) { /* ignore */ } + + const uploadInfo = fileRecord || uploadResult; + const fileUrl = typeof uploadInfo === 'object' && uploadInfo.url + ? uploadInfo.url + : (typeof uploadResult === 'object' ? uploadResult.fileName : ''); + + await progressHandler({ + status: 'running', + progress: 100, + message: '导出完成', + result: { url: fileUrl, fileKey: uploadKey, total: totalCount }, + }); + + return { + url: fileUrl, + fileKey: uploadKey, + total: totalCount, + totalDetails: allReceivingIds.reduce((sum, rid) => sum + (detailsMap.get(rid) || []).length, 0), + }; + } + } module.exports = ReceivingService; diff --git a/database/migrations/20260712-add-store-receiving-permission.js b/database/migrations/20260712-add-store-receiving-permission.js new file mode 100644 index 0000000..a43e266 --- /dev/null +++ b/database/migrations/20260712-add-store-receiving-permission.js @@ -0,0 +1,163 @@ +'use strict'; + +/** + * 货主侧收货单页面权限及 API 权限迁移。 + * + * 变更内容: + * 1. 新增 web_pages 权限:收货单(货主) — 货主平台侧收货单列表页面 + * 2. 新增 api 权限:account_platform.getStoreReceivingList — 货主侧收货单查询接口 + * 3. 将上述权限授权给 货主管理员(store_admin_default, id=5) 角色 + * + * 幂等设计: + * - 先查后插(按 path + type 唯一性判断) + * - 角色权限更新使用 JSON 数组合并去重 + */ + +const TABLE_PERMISSION = 'wms_permission'; +const TABLE_ROLE = 'wms_role'; + +const STORE_ADMIN_ROLE_ID = 5; + +/** @type {{path: string, name: string|null, meta_title: string, type: string, parent_id: number|null, sort: number}[]} */ +const NEW_PERMISSIONS = [ + { + path: 'receiving_owner', + name: 'OwnerReceiving', + meta_title: '收货单(货主)', + type: 'web_pages', + parent_id: 18, // 库存 + sort: 0, + component: '@/views/storage/receiving_owner/index', + }, + { + path: 'storage.receiving.getStoreReceivingList', + name: 'storage.receiving.getStoreReceivingList', + meta_title: '货主侧收货单列表查询', + type: 'api', + parent_id: null, + sort: 0, + component: null, + }, +]; + +/** + * 获取角色当前权限 ID 数组。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {number} roleId 角色ID + * @return {Promise} 权限ID数组 + */ +async function getRolePermissionIds(queryInterface, roleId) { + const [ rows ] = await queryInterface.sequelize.query( + `SELECT permissions FROM \`${TABLE_ROLE}\` WHERE id = :roleId`, + { replacements: { roleId } } + ); + if (!rows || rows.length === 0) return []; + + const raw = rows[0].permissions; + if (!raw) return []; + + try { + const parsed = JSON.parse(raw); + if (Array.isArray(parsed)) { + return parsed.map(Number).filter(n => Number.isFinite(n) && n > 0); + } + } catch (_) { + // ignore + } + + return []; +} + +/** + * 保存角色权限。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {number} roleId 角色ID + * @param {number[]} permissionIds 权限ID数组 + * @return {Promise} + */ +async function saveRolePermissions(queryInterface, roleId, permissionIds) { + const unique = Array.from(new Set(permissionIds)).sort((a, b) => a - b); + const json = JSON.stringify(unique); + + await queryInterface.sequelize.query( + `UPDATE \`${TABLE_ROLE}\` SET permissions = :permissions, updated_at = NOW() WHERE id = :roleId`, + { replacements: { roleId, permissions: json } } + ); +} + +/** + * 正向迁移。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} + */ +module.exports.up = async queryInterface => { + const insertedIds = []; + + for (const perm of NEW_PERMISSIONS) { + const [ existing ] = await queryInterface.sequelize.query( + `SELECT id FROM \`${TABLE_PERMISSION}\` WHERE path = :path AND type = :type LIMIT 1`, + { replacements: { path: perm.path, type: perm.type } } + ); + + if (existing && existing.length > 0) { + console.log(`[Migration] 权限已存在,跳过: ${perm.path} (type=${perm.type}, id=${existing[0].id})`); + insertedIds.push(existing[0].id); + continue; + } + + const [ result ] = await queryInterface.sequelize.query( + `INSERT INTO \`${TABLE_PERMISSION}\` (path, name, component, meta_title, type, parent_id, sort, status, created_at, update_at) + VALUES (:path, :name, :component, :meta_title, :type, :parent_id, :sort, 1, NOW(), NOW())`, + { replacements: { ...perm } } + ); + + const newId = result; + console.log(`[Migration] 新增权限: ${perm.path} (type=${perm.type}, id=${newId})`); + insertedIds.push(newId); + } + + // 更新 货主管理员 角色权限 + const currentIds = await getRolePermissionIds(queryInterface, STORE_ADMIN_ROLE_ID); + const mergedIds = Array.from(new Set([ ...currentIds, ...insertedIds ])).sort((a, b) => a - b); + + console.log(`[Migration] 货主管理员(id=${STORE_ADMIN_ROLE_ID}) 权限更新: [${currentIds.join(',')}] -> [${mergedIds.join(',')}]`); + await saveRolePermissions(queryInterface, STORE_ADMIN_ROLE_ID, mergedIds); + + console.log(`[Migration] 完成:新增 ${insertedIds.length} 条权限,角色权限已更新`); +}; + +/** + * 回滚迁移。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} + */ +module.exports.down = async queryInterface => { + // 1. 从角色权限中移除新增的权限 ID + const pathsToRemove = NEW_PERMISSIONS.map(p => p.path); + + const [ permRows ] = await queryInterface.sequelize.query( + `SELECT id FROM \`${TABLE_PERMISSION}\` WHERE path IN (:paths) AND type IN (:types)`, + { + replacements: { + paths: pathsToRemove, + types: NEW_PERMISSIONS.map(p => p.type), + }, + } + ); + + const idsToRemove = permRows.map(r => r.id); + const currentIds = await getRolePermissionIds(queryInterface, STORE_ADMIN_ROLE_ID); + const filteredIds = currentIds.filter(id => !idsToRemove.includes(id)); + + await saveRolePermissions(queryInterface, STORE_ADMIN_ROLE_ID, filteredIds); + console.log(`[Migration Rollback] 角色权限已移除: ${idsToRemove.join(',')}`); + + // 2. 删除新增的权限记录 + for (const perm of NEW_PERMISSIONS) { + await queryInterface.sequelize.query( + `DELETE FROM \`${TABLE_PERMISSION}\` WHERE path = :path AND type = :type`, + { replacements: { path: perm.path, type: perm.type } } + ); + console.log(`[Migration Rollback] 已删除权限: ${perm.path}`); + } +}; diff --git a/database/migrations/20260718180000-remove-zerofill-from-wms-receiving-detail-creator-id.js b/database/migrations/20260718180000-remove-zerofill-from-wms-receiving-detail-creator-id.js new file mode 100644 index 0000000..305666e --- /dev/null +++ b/database/migrations/20260718180000-remove-zerofill-from-wms-receiving-detail-creator-id.js @@ -0,0 +1,17 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + // 去掉 creator_id 列的 ZEROFILL 属性,避免零填充字符串导致查询匹配问题 + await queryInterface.sequelize.query( + 'ALTER TABLE wms_receiving_detail MODIFY COLUMN creator_id bigint(20) unsigned NOT NULL' + ); + }, + + async down(queryInterface, Sequelize) { + // 回滚:恢复 ZEROFILL 属性 + await queryInterface.sequelize.query( + 'ALTER TABLE wms_receiving_detail MODIFY COLUMN creator_id bigint(20) unsigned zerofill NOT NULL' + ); + }, +}; From 510b87632a6a4abcda775ad41fcc62a482607cc5 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 27 Jul 2026 03:48:06 +0800 Subject: [PATCH 128/550] =?UTF-8?q?feat(stock):=20=E5=BA=93=E5=AD=98/?= =?UTF-8?q?=E4=BB=93=E5=BA=93=E6=A8=A1=E5=9D=97=E8=B4=A7=E4=B8=BB=E4=BE=A7?= =?UTF-8?q?=E6=9F=A5=E8=AF=A2=E4=B8=8E=E6=8A=A5=E8=A1=A8=E5=A2=9E=E5=BC=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - stock/warehouse: 新增 externalList/externalExport(外仓/货主维度查询) - storeWarehouse/store: 新增货主侧接口(list/get 等) - stock_store: getWarehouseStock 支持 externalWarehouseId/externalStoreId - store_warehouse: 合同关系改为单向维度查询(不再 OR 两边) - storage/report: 库存报表支持 store 维度 + stockIds/keyword 精确筛选 - stock/transaction: storeList/exportStore store_id 从 ctx 获取防越权 - stock_warehouse: getStockDetails 支持显式传 null 跳过仓库过滤 - storage/management: 储位分配待处理排除待审核(step=1)订单 --- .../systemMethods/stock/transaction.js | 29 +- app/service/systemMethods/stock/warehouse.js | 202 +++++++- .../systemMethods/storeWarehouse/store.js | 445 +++++++++++++++++- app/service/systems/stock_warehouse.js | 3 +- app/service/systems/storage/management.js | 3 +- app/service/systems/storage/report.js | 280 +++++++++-- app/service/systems/store_warehouse.js | 292 +++++++++--- 7 files changed, 1127 insertions(+), 127 deletions(-) diff --git a/app/service/systemMethods/stock/transaction.js b/app/service/systemMethods/stock/transaction.js index 6dae504..006b3be 100644 --- a/app/service/systemMethods/stock/transaction.js +++ b/app/service/systemMethods/stock/transaction.js @@ -36,7 +36,8 @@ class StockTransactionMethodService extends MainService { start_time: startTime, end_time: endTime, store_ids: storeIds, - stock_ids: stockIds, + stock_ids: stockIdsRaw, + stock_id: stockIdRaw, keyword, ids, transaction_type: transactionType, @@ -48,6 +49,11 @@ class StockTransactionMethodService extends MainService { order_id: orderId, } = whereValue; + // 兼容 stock_id(单数)和 stock_ids(数组) + const stockIds = stockIdsRaw !== undefined + ? stockIdsRaw + : (stockIdRaw !== undefined ? [ stockIdRaw ] : null); + const { sort = {} } = data; const { sort_field: sortFieldSnake, @@ -86,9 +92,8 @@ class StockTransactionMethodService extends MainService { /** * 货主侧商品出入库流水列表查询。 - * 按货主 store_id 限定数据范围。 + * 按当前登录货主的 store_id(ctx.user.store_id)限定数据范围,不接受外部传入 store_id,防止跨货主查询。 * @param {Object} data 请求体 - * @param {number} data.store_id 货主ID(必传) * @param {Object} [data.pagination] 分页参数 * @param {Object} [data.where] 查询条件 * @param {Object} [data.sort] 排序参数 @@ -96,9 +101,9 @@ class StockTransactionMethodService extends MainService { */ async storeList(data = {}) { const { service } = this; - const storeId = Number(data.store_id); + const storeId = Number(this.ctx.user && this.ctx.user.store_id); if (!Number.isInteger(storeId) || storeId <= 0) { - return this.failure('store_id 不能为空'); + return this.failure('无法获取当前货主身份,请重新登录'); } const { pagination } = data; @@ -180,7 +185,8 @@ class StockTransactionMethodService extends MainService { start_time: startTime, end_time: endTime, store_ids: storeIds, - stock_ids: stockIds, + stock_ids: stockIdsRaw, + stock_id: stockIdRaw, keyword, ids, transaction_type: transactionType, @@ -192,6 +198,11 @@ class StockTransactionMethodService extends MainService { order_id: orderId, } = whereValue; + // 兼容 stock_id(单数)和 stock_ids(数组) + const stockIds = stockIdsRaw !== undefined + ? stockIdsRaw + : (stockIdRaw !== undefined ? [ stockIdRaw ] : null); + const { sort = {} } = data; const sortOption = { sortField: sort.sortField || sort.sort_field, @@ -270,15 +281,15 @@ class StockTransactionMethodService extends MainService { /** * 货主侧提交商品流水导出任务。 * 与 storeList 使用相同查询条件,异步执行,立即返回任务ID。 + * store_id 从当前登录上下文(ctx.user.store_id)获取,不接受外部传入,防止跨货主查询。 * @param {Object} data 请求体 - * @param {number} data.store_id 货主ID(必传) * @return {Promise} 统一 success 包装(返回任务ID) */ async exportStore(data = {}) { const { service } = this; - const storeId = Number(data.store_id); + const storeId = Number(this.ctx.user && this.ctx.user.store_id); if (!Number.isInteger(storeId) || storeId <= 0) { - return this.failure('store_id 不能为空'); + return this.failure('无法获取当前货主身份,请重新登录'); } const { whereValue = {} } = this.prepareWhereContext(data); diff --git a/app/service/systemMethods/stock/warehouse.js b/app/service/systemMethods/stock/warehouse.js index 8950351..153c171 100644 --- a/app/service/systemMethods/stock/warehouse.js +++ b/app/service/systemMethods/stock/warehouse.js @@ -9,9 +9,9 @@ class WarehouseService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'list,export,exportTaskProgress,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,getUnitList,createUnit,checkItemCodeUnique,deleteUnit,createProhibited,deleteProhibited,search,getStockDetail'; - const _noNeedLog = 'list,export,exportTaskProgress,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,checkItemCodeUnique,getUnitList,search,getStockDetail'; - const _noNeedAuth = 'list,export,exportTaskProgress,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,checkItemCodeUnique,getUnitList,search,getStockDetail'; + const _noNeedRight = 'list,externalList,externalExport,export,exportTaskProgress,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,getUnitList,createUnit,checkItemCodeUnique,deleteUnit,createProhibited,deleteProhibited,search,getStockDetail'; + const _noNeedLog = 'list,externalList,externalExport,export,exportTaskProgress,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,checkItemCodeUnique,getUnitList,search,getStockDetail'; + const _noNeedAuth = 'list,externalList,externalExport,export,exportTaskProgress,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,checkItemCodeUnique,getUnitList,search,getStockDetail'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -79,6 +79,159 @@ class WarehouseService extends MainService { return this.success('ok', result); } + /** + * 外仓商品列表查询。 + * - 传入 warehouse_id:按指定仓库维度查询 + * - 不传 warehouse_id:按当前货主维度查询(store_id = ctx.user.store_id) + * @param {Object} data 请求体 + * @param {number} [data.warehouse_id] 仓库ID(可选) + * @param {Object} [data.pagination] 分页参数 + * @param {Object} [data.where] 筛选条件 + * @return {Promise} 统一成功包装响应 + */ + async externalList(data = {}) { + const { service, ctx } = this; + const warehouseId = Number(data.warehouse_id || data.warehouseId || 0); + const { pagination } = data; + const sort = data.sort || {}; + const sortParams = { + sortField: sort.sortField || sort.sort_field || 'id', + sortOrder: sort.sortOrder || sort.sort_order || 'DESC', + }; + if (this.isPlainObject(data)) { + const rawWhere = this.isPlainObject(data.where) ? data.where : {}; + data.where = this.normalizeWarehouseRecycleWhere(rawWhere); + } + // 传入 warehouse_id 时合并到 where 条件中 + if (warehouseId > 0) { + data.where = { + ...(data.where || {}), + warehouse_id: { operator: 'eq', value: warehouseId }, + }; + } + const { where } = this.prepareWhereContext(data, { + specialFieldMap: { + barcode: { + bucket: 'barcode', + }, + prohibited_type: { + bucket: 'prohibited', + field: 'id', + }, + has_bound_item: { + bucket: 'storeOutStock', + field: 'stock_id', + }, + }, + }); + // 始终按当前货主维度查(store_id = self) + const result = await service.systems.stockStore.getWarehouseStock(where, pagination, sortParams, 0, ctx.user.store_id); + return this.success('ok', result); + } + + /** + * 提交外仓商品导出任务(复用 externalList 的筛选语义与排序规则)。 + * - 传入 warehouse_id:按指定仓库维度导出 + * - 不传 warehouse_id:按当前货主维度导出(store_id = ctx.user.store_id) + * @param {Object} data 请求体 + * @param {number} [data.warehouse_id] 仓库ID(可选) + * @param {Object} [data.where] 筛选条件 + * @param {Object} [data.sort] 排序参数 + * @param {string} [data.sort.sortField] 排序字段(兼容:sort_field) + * @param {string} [data.sort.sortOrder] 排序顺序(兼容:sort_order) + * @return {Promise} 统一成功包装响应,data 为导出任务信息 + */ + async externalExport(data = {}) { + const { service, ctx } = this; + const warehouseId = Number(data.warehouse_id || data.warehouseId || 0); + const sort = data.sort || {}; + const sortField = sort.sortField || sort.sort_field; + const sortOrder = sort.sortOrder || sort.sort_order; + const sortParams = { + ...(sortField ? { sortField } : {}), + ...(sortOrder ? { sortOrder } : {}), + }; + + if (this.isPlainObject(data)) { + const rawWhere = this.isPlainObject(data.where) ? data.where : {}; + data.where = this.normalizeWarehouseRecycleWhere(rawWhere); + } + // 传入 warehouse_id 时合并到 where 条件中 + if (warehouseId > 0) { + data.where = { + ...(data.where || {}), + warehouse_id: { operator: 'eq', value: warehouseId }, + }; + } + const { where } = this.prepareWhereContext(data, { + specialFieldMap: { + barcode: { + bucket: 'barcode', + }, + prohibited_type: { + bucket: 'prohibited', + field: 'id', + }, + has_bound_item: { + bucket: 'storeOutStock', + field: 'stock_id', + }, + }, + }); + + const taskId = this.generateExportTaskId('external'); + const taskPayload = { + task_id: taskId, + status: 'submitted', + progress: 0, + message: '外仓导出任务已提交', + result: null, + error: '', + }; + + await this.setExportTaskProgress(taskId, taskPayload); + + setImmediate(async () => { + try { + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'running', + progress: 10, + message: '外仓导出任务执行中', + result: null, + error: '', + }); + + // 始终按当前货主维度导出(store_id = self) + const result = await service.systems.stockStore.exportExternalWarehouseStock(where, sortParams, warehouseId, ctx.user.store_id); + + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'success', + progress: 100, + message: '外仓导出任务完成', + result, + error: '', + }); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'failed', + progress: 100, + message: '外仓导出任务失败', + result: null, + error: errorMessage, + }); + } + }); + + return this.success('ok', { + ...taskPayload, + update_time: Date.now(), + }); + } + /** * 提交仓库商品导出任务(复用 list 的筛选语义与排序规则)。 * @param {Object} data 请求体 @@ -224,13 +377,15 @@ class WarehouseService extends MainService { /** * 生成仓库商品导出任务ID。 + * @param {string} [prefix=''] 任务类型前缀(如 'external') * @return {string} 导出任务ID */ - generateExportTaskId() { + generateExportTaskId(prefix = '') { const warehouseId = this.ctx?.user?.store_id || 'unknown'; const timestamp = Date.now(); const randomToken = Math.random().toString(36).slice(2, 10); - return `stock_warehouse_export_${warehouseId}_${timestamp}_${randomToken}`; + const typePrefix = prefix ? `${prefix}_` : ''; + return `stock_warehouse_${typePrefix}export_${warehouseId}_${timestamp}_${randomToken}`; } /** @@ -644,7 +799,22 @@ class WarehouseService extends MainService { * @return {Promise} data 为关联分页结果 */ async getStoreStocks(data) { - const { service } = this; + const { ctx, service } = this; + // 校验归属:stock_warehouse 的 store_id 或 warehouse_id 匹配当前主体即可放行 + const stockId = Number(data.stock_id || 0); + if (stockId > 0) { + const stock = await ctx.model.StockWarehouse.findOne({ + where: { id: stockId }, + attributes: [ 'id', 'store_id', 'warehouse_id' ], + raw: true, + }); + if (!stock + || (stock.store_id !== ctx.user.store_id && stock.warehouse_id !== ctx.user.store_id)) { + return this.fail('无权限查看该商品的绑定信息', { code: 403 }); + } + // 使用实际的 warehouse_id 查询 + data._warehouseId = stock.warehouse_id; + } const result = await service.systems.stockStore.getStoreStocks(data); return this.success('ok', { data: result, code: 200 }); } @@ -730,10 +900,24 @@ class WarehouseService extends MainService { * @return {Promise} data 为日志分页结果 */ async queryStockLogs(data) { - const { ctx } = this; + const { ctx, service } = this; try { - const { service } = this; - data.warehouseId = ctx.user.store_id; + const stockId = Number(data.id || 0); + if (stockId > 0) { + // 校验 stock_warehouse:store_id 或 warehouse_id 匹配当前主体即可放行 + const stock = await ctx.model.StockWarehouse.findOne({ + where: { id: stockId }, + attributes: [ 'id', 'store_id', 'warehouse_id' ], + raw: true, + }); + if (!stock + || (stock.store_id !== ctx.user.store_id && stock.warehouse_id !== ctx.user.store_id)) { + return this.fail('无权限查看该商品的库存日志', { code: 403 }); + } + data.warehouseId = stock.warehouse_id; + } else { + data.warehouseId = ctx.user.store_id; + } const result = await service.systems.operationLog.queryStockLogs(data); return this.success('ok', { data: result, code: 200 }); } catch (e) { diff --git a/app/service/systemMethods/storeWarehouse/store.js b/app/service/systemMethods/storeWarehouse/store.js index 92ac429..581daa0 100644 --- a/app/service/systemMethods/storeWarehouse/store.js +++ b/app/service/systemMethods/storeWarehouse/store.js @@ -2,6 +2,9 @@ const MainService = require('../../main'); +const PRINT_QUANTITY_LOG_EXPORT_TASK_CACHE_KEY_PREFIX = 'print_quantity_log_export_task_'; +const PRINT_QUANTITY_LOG_EXPORT_TASK_CACHE_TTL_SECONDS = 1800; + /** * 规范仓库配置方法入参,避免把原始引用直接传给下游服务。 @@ -26,9 +29,9 @@ class StoreWarehouseStoreService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'list,sign,confirmSign,unbind,rename,openAccount,getPolicyConfig,getPolicyConfigFields,savePolicyConfig,listApiConfig,saveApiConfig,deleteQimenConfig'; + const _noNeedRight = 'list,sign,confirmSign,unbind,rename,openAccount,getPolicyConfig,getPolicyConfigFields,savePolicyConfig,listApiConfig,saveApiConfig,deleteQimenConfig,queryPrintQuantityLogs,queryStorePrintQuantityLogs,exportStorePrintQuantityLogs,exportStorePrintQuantityLogsTaskProgress,adjustPrintQuantity'; const _noNeedLog = '*'; - const _noNeedAuth = 'list,sign,confirmSign,unbind,rename,openAccount,getPolicyConfig,getPolicyConfigFields,savePolicyConfig,listApiConfig,saveApiConfig,deleteQimenConfig'; + const _noNeedAuth = 'list,sign,confirmSign,unbind,rename,openAccount,getPolicyConfig,getPolicyConfigFields,savePolicyConfig,listApiConfig,saveApiConfig,deleteQimenConfig,queryPrintQuantityLogs,queryStorePrintQuantityLogs,exportPrintQuantityLogs,exportStorePrintQuantityLogs,exportStorePrintQuantityLogsTaskProgress,adjustPrintQuantity'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -417,6 +420,444 @@ class StoreWarehouseStoreService extends MainService { }); } } + + /** + * 提交面单余额变更日志导出任务。 + * 入参条件与 queryPrintQuantityLogs 的 where 语义一致,异步执行,立即返回 task_id。 + * + * @param {Object} data 请求数据。 + * @param {number|string} data.store_id 货主ID(必填)。 + * @param {Object} [data.where] 动态筛选条件,与 queryPrintQuantityLogs 的 where 语义一致。 + * @return {Promise} 统一响应结果(包含 task_id)。 + */ + async exportPrintQuantityLogs(data = {}) { + const { service } = this; + const targetService = service && service.systems && service.systems.storeWarehouse; + + if (!targetService || typeof targetService.exportPrintQuantityLogs !== 'function') { + return this.fail('导出面单余额变更日志失败', { code: 500 }); + } + + try { + const requestData = normalizeStoreWarehousePayload(data); + const { where } = this.prepareWhereContext(requestData); + const { store_id } = requestData; + + const taskId = this.generateExportTaskId(); + const taskPayload = { + task_id: taskId, + status: 'submitted', + progress: 0, + message: '导出任务已提交', + result: null, + error: '', + }; + + await this.setExportTaskProgress(taskId, taskPayload); + + setImmediate(async () => { + try { + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'running', + progress: 10, + message: '导出任务执行中', + result: null, + error: '', + }); + + const result = await targetService.exportPrintQuantityLogs({ + store_id, + where, + }); + + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'success', + progress: 100, + message: '导出任务完成', + result, + error: '', + }); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'failed', + progress: 100, + message: '导出任务失败', + result: null, + error: errorMessage, + }); + } + }); + + return this.success('ok', { + ...taskPayload, + update_time: Date.now(), + }); + } catch (error) { + return this.fail(error.message || '导出面单余额变更日志失败', { + code: Number(error.code) || 500, + }); + } + } + + /** + * 查询面单余额变更日志导出任务进度。 + * + * @param {Object} data 请求数据。 + * @param {string} [data.task_id] 任务ID(下划线写法)。 + * @param {string} [data.taskId] 任务ID(驼峰写法)。 + * @return {Promise} 统一响应结果。 + */ + async exportPrintQuantityLogsTaskProgress(data = {}) { + const taskId = this.normalizeExportTaskId(data); + if (!taskId) { + return this.success('ok', { + task_id: '', + status: 'not_found', + progress: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const cachedTask = await this.getExportTaskProgress(taskId); + if (!cachedTask) { + return this.success('ok', { + task_id: taskId, + status: 'not_found', + progress: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {}; + const downloadUrl = String( + safeResult.url + || safeResult.cdnUrl + || safeResult.cosUrl + || safeResult.fileKey + || '' + ); + + return this.success('ok', { + task_id: taskId, + ...cachedTask, + download_url: downloadUrl, + }); + } + + /** + * 货主侧查询面单余额变更日志(自动从平台激活上下文获取 store_id)。 + * 无需显式传入 store_id,系统自动从当前用户激活的货主平台上下文中获取。 + * + * @param {Object} data 请求数据。 + * @param {Object} [data.where] 动态筛选条件。 + * @param {Object} [data.pagination] 分页对象。 + * @param {number|string} [data.pagination.page] 页码。 + * @param {number|string} [data.pagination.page_size] 每页条数。 + * @return {Promise} 统一响应结果。 + */ + async queryStorePrintQuantityLogs(data = {}) { + const { ctx, app, service } = this; + + // 从平台激活上下文获取 store_id + const platformRows = await app.model.query( + 'SELECT apa.employee_id, ase.store_id FROM wms_account_platform_active apa ' + + 'INNER JOIN wms_account_store_employee ase ON ase.id = apa.employee_id AND ase.status = 1 ' + + 'WHERE apa.account_id = :accountId AND apa.platform_code = :platformCode LIMIT 1', + { + replacements: { accountId: ctx.userId, platformCode: ctx.platformCode || 'web' }, + type: app.Sequelize.QueryTypes.SELECT, + } + ); + + if (!platformRows || platformRows.length === 0 || !platformRows[0].store_id) { + return this.fail('未获取到货主平台激活上下文,请先切换至货主角色'); + } + + const storeId = platformRows[0].store_id; + const targetService = service && service.systems && service.systems.storeWarehouse; + + if (!targetService || typeof targetService.queryPrintQuantityLogs !== 'function') { + return this.fail('查询面单余额变更日志失败', { code: 500 }); + } + + try { + const requestData = normalizeStoreWarehousePayload(data); + const { where } = this.prepareWhereContext(requestData); + const rawPagination = requestData.pagination && typeof requestData.pagination === 'object' + ? requestData.pagination + : {}; + const { page, page_size } = rawPagination; + + const result = await targetService.queryPrintQuantityLogs({ + store_id: storeId, + where, + pagination: { page, page_size }, + }); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '查询面单余额变更日志失败', { + code: Number(error.code) || 500, + }); + } + } + + /** + * 货主侧提交面单余额变更日志导出任务(自动从平台激活上下文获取 store_id)。 + * 入参条件与 queryStorePrintQuantityLogs 的 where 语义一致,异步执行,立即返回 task_id。 + * + * @param {Object} data 请求数据。 + * @param {Object} [data.where] 动态筛选条件。 + * @return {Promise} 统一响应结果(包含 task_id)。 + */ + async exportStorePrintQuantityLogs(data = {}) { + const { ctx, app, service } = this; + + // 从平台激活上下文获取 store_id + const platformRows = await app.model.query( + 'SELECT apa.employee_id, ase.store_id FROM wms_account_platform_active apa ' + + 'INNER JOIN wms_account_store_employee ase ON ase.id = apa.employee_id AND ase.status = 1 ' + + 'WHERE apa.account_id = :accountId AND apa.platform_code = :platformCode LIMIT 1', + { + replacements: { accountId: ctx.userId, platformCode: ctx.platformCode || 'web' }, + type: app.Sequelize.QueryTypes.SELECT, + } + ); + + if (!platformRows || platformRows.length === 0 || !platformRows[0].store_id) { + return this.fail('未获取到货主平台激活上下文,请先切换至货主角色'); + } + + const storeId = platformRows[0].store_id; + const targetService = service && service.systems && service.systems.storeWarehouse; + + if (!targetService || typeof targetService.exportPrintQuantityLogs !== 'function') { + return this.fail('导出面单余额变更日志失败', { code: 500 }); + } + + try { + const requestData = normalizeStoreWarehousePayload(data); + const { where } = this.prepareWhereContext(requestData); + + const taskId = this.generateExportTaskId('store'); + const taskPayload = { + task_id: taskId, + status: 'submitted', + progress: 0, + message: '货主侧导出任务已提交', + result: null, + error: '', + }; + + await this.setExportTaskProgress(taskId, taskPayload); + + setImmediate(async () => { + try { + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'running', + progress: 10, + message: '货主侧导出任务执行中', + result: null, + error: '', + }); + + const result = await targetService.exportPrintQuantityLogs({ + store_id: storeId, + where, + }); + + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'success', + progress: 100, + message: '货主侧导出任务完成', + result, + error: '', + }); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'failed', + progress: 100, + message: '货主侧导出任务失败', + result: null, + error: errorMessage, + }); + } + }); + + return this.success('ok', { + ...taskPayload, + update_time: Date.now(), + }); + } catch (error) { + return this.fail(error.message || '导出面单余额变更日志失败', { + code: Number(error.code) || 500, + }); + } + } + + /** + * 货主侧查询面单余额变更日志导出任务进度。 + * 复用 exportPrintQuantityLogsTaskProgress 的缓存查询逻辑。 + * + * @param {Object} data 请求数据。 + * @param {string} [data.task_id] 任务ID(下划线写法)。 + * @param {string} [data.taskId] 任务ID(驼峰写法)。 + * @return {Promise} 统一响应结果。 + */ + async exportStorePrintQuantityLogsTaskProgress(data = {}) { + const taskId = this.normalizeExportTaskId(data); + if (!taskId) { + return this.success('ok', { + task_id: '', + status: 'not_found', + progress: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const cachedTask = await this.getExportTaskProgress(taskId); + if (!cachedTask) { + return this.success('ok', { + task_id: taskId, + status: 'not_found', + progress: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {}; + const downloadUrl = String( + safeResult.url + || safeResult.cdnUrl + || safeResult.cosUrl + || safeResult.fileKey + || '' + ); + + return this.success('ok', { + task_id: taskId, + ...cachedTask, + download_url: downloadUrl, + }); + } + + /** + * 生成导出任务ID。 + * @param {string} [prefix=''] 任务类型前缀(如 'store') + * @return {string} 导出任务ID。 + */ + generateExportTaskId(prefix = '') { + const storeId = this.ctx?.user?.store_id || 'unknown'; + const timestamp = Date.now(); + const randomToken = Math.random().toString(36).slice(2, 10); + const typePrefix = prefix ? `${prefix}_` : ''; + return `print_qty_log_${typePrefix}export_${storeId}_${timestamp}_${randomToken}`; + } + + /** + * 规范导出任务ID。 + * @param {Object} data 请求体。 + * @param {string} [data.task_id] 任务ID(下划线写法) + * @param {string} [data.taskId] 任务ID(驼峰写法) + * @return {string} 归一化后的任务ID。 + */ + normalizeExportTaskId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.task_id || normalizedData.taskId || '').trim(); + } + + /** + * 获取导出任务缓存键。 + * @param {string} taskId 任务ID。 + * @return {string} 缓存键。 + */ + getExportTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + return `${PRINT_QUANTITY_LOG_EXPORT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 写入导出任务进度缓存。 + * @param {string} taskId 任务ID。 + * @param {Object} payload 任务状态载荷。 + * @return {Promise} 无返回值。 + */ + async setExportTaskProgress(taskId = '', payload = {}) { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.setCacheAsync !== 'function') { + return; + } + + const safePayload = this.isPlainObject(payload) ? payload : {}; + const progressPayload = { + task_id: String(taskId || '').trim(), + status: String(safePayload.status || 'submitted').trim() || 'submitted', + progress: Number.isFinite(Number(safePayload.progress)) + ? Math.min(100, Math.max(0, Math.round(Number(safePayload.progress)))) + : 0, + message: String(safePayload.message || ''), + result: safePayload.result ?? null, + error: String(safePayload.error || ''), + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync(cacheKey, progressPayload, PRINT_QUANTITY_LOG_EXPORT_TASK_CACHE_TTL_SECONDS); + } catch (error) { + this.ctx.logger.warn('[storeWarehouse.store.exportPrintQuantityLogs] 写入导出任务缓存失败: %s', + error && error.message ? error.message : error); + } + } + + /** + * 读取导出任务进度缓存。 + * @param {string} taskId 任务ID。 + * @return {Promise} 任务缓存。 + */ + async getExportTaskProgress(taskId = '') { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.getCacheAsync !== 'function') { + return null; + } + + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (!this.isPlainObject(cached)) { + return null; + } + return cached; + } catch (error) { + this.ctx.logger.warn('[storeWarehouse.store.exportPrintQuantityLogs] 读取导出任务缓存失败: %s', + error && error.message ? error.message : error); + return null; + } + } } module.exports = StoreWarehouseStoreService; diff --git a/app/service/systems/stock_warehouse.js b/app/service/systems/stock_warehouse.js index dad60e4..833bd51 100644 --- a/app/service/systems/stock_warehouse.js +++ b/app/service/systems/stock_warehouse.js @@ -36,7 +36,8 @@ class StockWarehouseService extends Service { async getStockDetails(stockIds, options = {}) { const { ctx, app } = this; const { cacheTTL = DEFAULT_STOCK_DETAIL_CACHE_TTL } = options; - const warehouseId = options.warehouseId != null ? options.warehouseId : ctx.user.store_id; + // 用 !== undefined 代替 != null:显式传 null 表示跳过 warehouse 过滤(如货主侧查询) + const warehouseId = options.warehouseId !== undefined ? options.warehouseId : ctx.user.store_id; if (!Array.isArray(stockIds) || stockIds.length === 0) { return []; diff --git a/app/service/systems/storage/management.js b/app/service/systems/storage/management.js index 3c94375..f57d34d 100644 --- a/app/service/systems/storage/management.js +++ b/app/service/systems/storage/management.js @@ -71,11 +71,12 @@ class StorageManagementService extends Service { const orderModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); const orderItemModel = await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId); - // 2) 查询当前仓库所有未完成储位分配的订单 + // 2) 查询当前仓库所有未完成储位分配的订单(排除待审核 step=1) const pendingOrders = await orderModel.findAll({ where: { warehouse_id: warehouseId, storage_status: { [Op.ne]: 'fin' }, + step: { [Op.ne]: 1 }, delete_at: null, }, attributes: [ 'id' ], diff --git a/app/service/systems/storage/report.js b/app/service/systems/storage/report.js index 1d54349..54e24a3 100644 --- a/app/service/systems/storage/report.js +++ b/app/service/systems/storage/report.js @@ -353,7 +353,7 @@ class StorageReportService extends Service { if (normalizedStockIds.length > 0) { const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails( normalizedStockIds, - {} + { warehouseId } // store 模式下为 null → 跳过 warehouse 过滤 ); for (const detail of stockDetails) { const sid = Number(detail.id); @@ -515,11 +515,15 @@ class StorageReportService extends Service { * @param {string} [sort.sortField] 排序字段 * @param {string} [sort.sortOrder] 排序顺序 * @param {string} [exportMode] 导出模式:'item' 导出全部(含锁定),不传/其他值则排除锁定类型记录 + * @param {string} [searchMode='warehouse'] 查询维度:'warehouse' 按仓库维度(默认),'store' 按货主维度 + * @param {number[]} [stockIds=null] 商品库存ID列表(精确过滤) + * @param {string} [keyword=''] 商品关键字(模糊匹配) * @return {Promise} excel 上传结果 */ - async export(startTime, endTime, bySpace = false, storeIds = [], sort = null, exportMode = '') { + async export(startTime, endTime, bySpace = false, storeIds = [], sort = null, exportMode = '', searchMode = 'warehouse', stockIds = null, keyword = '') { const { ctx, app } = this; - const searchResult = await this.search(startTime, endTime, bySpace, storeIds, sort); + const isStoreMode = searchMode === 'store'; + const searchResult = await this.search(startTime, endTime, bySpace, storeIds, sort, searchMode, stockIds, keyword); if (!searchResult || searchResult.code !== 200) { return searchResult; } @@ -527,15 +531,26 @@ class StorageReportService extends Service { const summaryList = Array.isArray(searchResult.data && searchResult.data.list) ? searchResult.data.list : []; - const warehouseId = Number(ctx.user && ctx.user.store_id); + const rawPrimaryId = Number(ctx.user && ctx.user.store_id); + const storeId = isStoreMode ? rawPrimaryId : null; + const warehouseId = isStoreMode ? null : rawPrimaryId; const startTimeMs = toTimeMs(startTime); const endTimeMs = toTimeMs(endTime); const normalizedStoreIds = normalizeStoreIds(storeIds); const isBySpace = normalizeBoolean(bySpace); - const whereClauses = [ 't.warehouse_id = :warehouseId' ]; + // 主维度:仓库模式用 warehouse_id,货主模式用 store_id + const primaryDimCol = isStoreMode ? 'store_id' : 'warehouse_id'; + const primaryDimVal = isStoreMode ? storeId : warehouseId; + const primaryDimAlias = isStoreMode ? 'storeId' : 'warehouseId'; + // 辅助维度:仓库模式用 store_id(货主过滤),货主模式用 warehouse_id(仓库过滤) + const secondaryIds = normalizedStoreIds; + const secondaryDimCol = isStoreMode ? 'warehouse_id' : 'store_id'; + const secondaryDimAlias = isStoreMode ? 'warehouseIds' : 'storeIds'; + + const whereClauses = [ `t.${primaryDimCol} = :${primaryDimAlias}` ]; const replacements = { - warehouseId, + [primaryDimAlias]: primaryDimVal, }; if (startTimeMs !== null) { @@ -548,9 +563,9 @@ class StorageReportService extends Service { replacements.endTime = endTime; } - if (normalizedStoreIds.length > 0) { - whereClauses.push('t.store_id IN (:storeIds)'); - replacements.storeIds = normalizedStoreIds; + if (secondaryIds.length > 0) { + whereClauses.push(`t.${secondaryDimCol} IN (:${secondaryDimAlias})`); + replacements[secondaryDimAlias] = secondaryIds; } const normalizedExportMode = String(exportMode || '').trim(); @@ -623,6 +638,8 @@ class StorageReportService extends Service { { header: '结束时间', key: 'end_time' }, { header: '货主ID', key: 'store_id' }, { header: '货主名称', key: 'store_name' }, + { header: '仓库ID', key: 'warehouse_id' }, + { header: '仓库名称', key: 'warehouse_name' }, { header: '商品库存ID', key: 'stock_id' }, { header: '商品编码', key: 'item_code' }, { header: '商品名称', key: 'item_name' }, @@ -644,6 +661,8 @@ class StorageReportService extends Service { end_time: item.end_time || '', store_id: toNumber(item.store_id), store_name: item.store_name || '', + warehouse_id: toNumber(item.warehouse_id), + warehouse_name: item.warehouse_name || '', stock_id: toNumber(item.stock_id), item_code: item.item_code || '', item_name: item.item_name || '', @@ -663,10 +682,8 @@ class StorageReportService extends Service { const detailSheetRows = safeDetailRows.map(item => { const stockId = toNumber(item.stock_id); const storeId = toNumber(item.store_id); - const spaceId = toNumber(item.space_id); const stock = maps.stockMap.get(stockId) || {}; const store = maps.storeMap.get(storeId) || {}; - const space = maps.spaceMap.get(spaceId) || {}; const barcodeSet = maps.barcodeMap.get(stockId); const entryOrderId = toNumber(item.entry_order_id); @@ -691,8 +708,6 @@ class StorageReportService extends Service { item_code: stock.item_code || '', item_name: stock.item_name || '', barcode: barcodeSet ? [ ...barcodeSet ].join(',') : '', - space_id: spaceId, - space_name: space.custom_name || space.space_code || '', quantity: toNumber(item.quantity), before_quantity: toNumber(item.before_quantity), after_quantity: toNumber(item.after_quantity), @@ -725,8 +740,6 @@ class StorageReportService extends Service { { header: '商品编码', key: 'item_code' }, { header: '商品名称', key: 'item_name' }, { header: '条码', key: 'barcode' }, - { header: '库位ID', key: 'space_id' }, - { header: '库位名称', key: 'space_name' }, { header: '变动数量', key: 'quantity' }, { header: '变更前库存', key: 'before_quantity' }, { header: '变更后库存', key: 'after_quantity' }, @@ -750,7 +763,7 @@ class StorageReportService extends Service { return await ctx.service.systems.excel.generateAndUpload({ filename: this.buildExportFilename(startTime, endTime), - dir: `exports/storage/report/${warehouseId || 'common'}`, + dir: `exports/storage/report/${warehouseId || storeId || 'common'}`, category: 'document', sheets: [ { @@ -767,6 +780,66 @@ class StorageReportService extends Service { }); } + /** + * 根据关键字解析匹配的 stock_id 列表。 + * 支持按商品编码(item_code)、商品名称(item_name)、货物编码(goods_code)、条码(barcode)模糊匹配。 + * @param {string} keyword 搜索关键字 + * @param {string} primaryDimCol 主维度列名(warehouse_id 或 store_id) + * @param {number} primaryDimVal 主维度值 + * @return {Promise} 匹配的 stock_id 列表 + */ + async _resolveKeywordToStockIds(keyword, primaryDimCol, primaryDimVal) { + const { ctx, app } = this; + const normalizedKeyword = String(keyword || '').trim(); + if (!normalizedKeyword) { + return []; + } + + const likePattern = `%${normalizedKeyword}%`; + // 如果 keyword 为纯数字,同时支持按 stock_id(SKU ID)精确匹配 + const exactStockId = /^\d+$/.test(normalizedKeyword) ? Number(normalizedKeyword) : null; + + // 从 wms_stock_warehouse 按 item_code / item_name / goods_code / id(SKU) 模糊匹配 + const extraIdCondition = exactStockId !== null ? 'OR sw.id = :exactStockId' : ''; + const stockRows = await ctx.model.query(` + SELECT DISTINCT sw.id AS stock_id + FROM wms_stock_warehouse sw + WHERE sw.${primaryDimCol} = :primaryDimVal + AND ( + sw.item_code LIKE :keyword + OR sw.item_name LIKE :keyword + OR sw.goods_code LIKE :keyword + ${extraIdCondition} + ) + `, { + replacements: { primaryDimVal, keyword: likePattern, exactStockId }, + type: app.Sequelize.QueryTypes.SELECT, + }); + + // 从 wms_stock_barcodes 按 barcode 模糊匹配 + const barcodeRows = await ctx.model.query(` + SELECT DISTINCT sb.stock_id + FROM wms_stock_barcodes sb + INNER JOIN wms_stock_warehouse sw ON sw.id = sb.stock_id AND sw.${primaryDimCol} = :primaryDimVal + WHERE sb.barcode LIKE :keyword + `, { + replacements: { primaryDimVal, keyword: likePattern }, + type: app.Sequelize.QueryTypes.SELECT, + }); + + const stockIdSet = new Set(); + for (const row of stockRows) { + const sid = Number(row.stock_id); + if (sid > 0) stockIdSet.add(sid); + } + for (const row of barcodeRows) { + const sid = Number(row.stock_id); + if (sid > 0) stockIdSet.add(sid); + } + + return [ ...stockIdSet ]; + } + /** * 查询库存流水统计报表。 * 规则: @@ -779,22 +852,46 @@ class StorageReportService extends Service { * @param {string|Date|null} startTime 开始时间(闭区间下限) * @param {string|Date|null} endTime 结束时间(闭区间上限) * @param {boolean|string|number} [bySpace=false] 是否按库位返回 - * @param {Array|number|string|null} [storeIds=[]] 货主ID列表 + * @param {Array|number|string|null} [storeIds=[]] 货主ID列表(store模式为仓库ID列表) * @param {Object} [sort] 排序参数 * @param {string} [sort.sortField] 排序字段(begin_total、inbound_total、outbound_total、end_total) * @param {string} [sort.sortOrder] 排序顺序(ASC、DESC,大小写不敏感) + * @param {string} [searchMode='warehouse'] 查询维度:'warehouse' 按仓库维度(默认),'store' 按货主维度 + * @param {number[]} [stockIds=null] 商品库存ID列表(精确过滤),与 keyword 互斥 + * @param {string} [keyword=''] 商品关键字(按 item_code/item_name/goods_code/barcode 模糊匹配),与 stockIds 互斥 * @return {Promise} code/data/message 结构 */ - async search(startTime, endTime, bySpace = false, storeIds = [], sort = null) { + async search(startTime, endTime, bySpace = false, storeIds = [], sort = null, searchMode = 'warehouse', stockIds = null, keyword = '') { const { ctx, app } = this; - const warehouseId = Number(ctx.user && ctx.user.store_id); - if (!warehouseId) { + const isStoreMode = searchMode === 'store'; + const rawPrimaryId = Number(ctx.user && ctx.user.store_id); + const storeId = isStoreMode ? rawPrimaryId : null; + const warehouseId = isStoreMode ? null : rawPrimaryId; + + if (!isStoreMode && !warehouseId) { return { code: 400, message: '用户未绑定仓库', data: { list: [] }, }; } + if (isStoreMode && !storeId) { + return { + code: 400, + message: '用户未绑定货主', + data: { list: [] }, + }; + } + + // 主维度:仓库模式用 warehouse_id,货主模式用 store_id + const primaryDimCol = isStoreMode ? 'store_id' : 'warehouse_id'; + const primaryDimVal = isStoreMode ? storeId : warehouseId; + const primaryDimAlias = isStoreMode ? 'storeId' : 'warehouseId'; + + // 辅助维度:仓库模式用 store_id(货主过滤),货主模式用 warehouse_id(仓库过滤) + const secondaryIds = normalizeStoreIds(storeIds); + const secondaryDimCol = isStoreMode ? 'warehouse_id' : 'store_id'; + const secondaryDimAlias = isStoreMode ? 'warehouseIds' : 'storeIds'; const startTimeMs = toTimeMs(startTime); const endTimeMs = toTimeMs(endTime); @@ -824,25 +921,51 @@ class StorageReportService extends Service { } const isBySpace = normalizeBoolean(bySpace); - const normalizedStoreIds = normalizeStoreIds(storeIds); + + // 归一化 stock_ids:优先使用 keyword 解析,其次使用显式传入的 stockIds + let resolvedStockIds = null; + const normalizedKeyword = String(keyword || '').trim(); + if (normalizedKeyword) { + resolvedStockIds = await this._resolveKeywordToStockIds(normalizedKeyword, primaryDimCol, primaryDimVal); + if (resolvedStockIds.length === 0) { + return { + code: 200, + message: '查询成功', + data: { list: [] }, + }; + } + } else if (stockIds !== null && stockIds !== undefined) { + const rawIds = Array.isArray(stockIds) ? stockIds : [ stockIds ]; + resolvedStockIds = [ ...new Set( + rawIds.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0) + ) ]; + if (resolvedStockIds.length === 0) { + return { + code: 200, + message: '查询成功', + data: { list: [] }, + }; + } + } let baseStockRows = []; let baseStorageRows = []; if (!isBySpace) { - const baseWhereClauses = [ 'sw.warehouse_id = :warehouseId' ]; + const baseWhereClauses = [ `sw.${primaryDimCol} = :${primaryDimAlias}` ]; const baseReplacements = { - warehouseId, + [primaryDimAlias]: primaryDimVal, }; - if (normalizedStoreIds.length > 0) { - baseWhereClauses.push('sw.store_id IN (:storeIds)'); - baseReplacements.storeIds = normalizedStoreIds; + if (secondaryIds.length > 0) { + baseWhereClauses.push(`sw.${secondaryDimCol} IN (:${secondaryDimAlias})`); + baseReplacements[secondaryDimAlias] = secondaryIds; } baseStockRows = await ctx.model.query(` SELECT sw.id AS stock_id, sw.store_id, + sw.warehouse_id, sw.quantity FROM wms_stock_warehouse sw WHERE ${baseWhereClauses.join(' AND ')} @@ -851,6 +974,12 @@ class StorageReportService extends Service { type: app.Sequelize.QueryTypes.SELECT, }); + // 如果指定了 stock_id 过滤,仅保留匹配的 stock 行 + if (resolvedStockIds !== null) { + const stockIdSet = new Set(resolvedStockIds); + baseStockRows = baseStockRows.filter(row => stockIdSet.has(Number(row.stock_id))); + } + if (!Array.isArray(baseStockRows) || baseStockRows.length === 0) { return { code: 200, @@ -859,14 +988,14 @@ class StorageReportService extends Service { }; } } else { - const baseWhereClauses = [ 's.warehouse_id = :warehouseId', 's.delete_at IS NULL' ]; + const baseWhereClauses = [ `s.${primaryDimCol} = :${primaryDimAlias}`, 's.delete_at IS NULL' ]; const baseReplacements = { - warehouseId, + [primaryDimAlias]: primaryDimVal, }; - if (normalizedStoreIds.length > 0) { - baseWhereClauses.push('s.store_id IN (:storeIds)'); - baseReplacements.storeIds = normalizedStoreIds; + if (secondaryIds.length > 0) { + baseWhereClauses.push(`s.${secondaryDimCol} IN (:${secondaryDimAlias})`); + baseReplacements[secondaryDimAlias] = secondaryIds; } baseStorageRows = await ctx.model.query(` @@ -874,21 +1003,28 @@ class StorageReportService extends Service { s.stock_id, COALESCE(s.space_id, 0) AS space_id, s.store_id, + s.warehouse_id, SUM(s.quantity) AS quantity FROM wms_storage s WHERE ${baseWhereClauses.join(' AND ')} - GROUP BY s.stock_id, COALESCE(s.space_id, 0), s.store_id + GROUP BY s.stock_id, COALESCE(s.space_id, 0), s.store_id, s.warehouse_id `, { replacements: baseReplacements, type: app.Sequelize.QueryTypes.SELECT, }); + // 如果指定了 stock_id 过滤,仅保留匹配的 stock 行 + if (resolvedStockIds !== null) { + const stockIdSet = new Set(resolvedStockIds); + baseStorageRows = baseStorageRows.filter(row => stockIdSet.has(Number(row.stock_id))); + } + baseStorageRows = Array.isArray(baseStorageRows) ? baseStorageRows : []; } - const rangeWhereClauses = [ 't.warehouse_id = :warehouseId' ]; + const rangeWhereClauses = [ `t.${primaryDimCol} = :${primaryDimAlias}` ]; const rangeReplacements = { - warehouseId, + [primaryDimAlias]: primaryDimVal, }; if (startTimeMs !== null) { @@ -901,9 +1037,9 @@ class StorageReportService extends Service { rangeReplacements.endTime = endTime; } - if (normalizedStoreIds.length > 0) { - rangeWhereClauses.push('t.store_id IN (:storeIds)'); - rangeReplacements.storeIds = normalizedStoreIds; + if (secondaryIds.length > 0) { + rangeWhereClauses.push(`t.${secondaryDimCol} IN (:${secondaryDimAlias})`); + rangeReplacements[secondaryDimAlias] = secondaryIds; } if (!isBySpace) { @@ -963,17 +1099,17 @@ class StorageReportService extends Service { let preStartSnapshotRows = []; if (startTimeMs !== null) { const preStartWhereClauses = [ - 't.warehouse_id = :warehouseId', + `t.${primaryDimCol} = :${primaryDimAlias}`, 't.created_at < :startTime', ]; const preStartReplacements = { - warehouseId, + [primaryDimAlias]: primaryDimVal, startTime, }; - if (normalizedStoreIds.length > 0) { - preStartWhereClauses.push('t.store_id IN (:storeIds)'); - preStartReplacements.storeIds = normalizedStoreIds; + if (secondaryIds.length > 0) { + preStartWhereClauses.push(`t.${secondaryDimCol} IN (:${secondaryDimAlias})`); + preStartReplacements[secondaryDimAlias] = secondaryIds; } if (!isBySpace) { @@ -1039,6 +1175,7 @@ class StorageReportService extends Service { .map(row => { const stockId = Number(row.stock_id); const storeId = Number(row.store_id); + const whId = Number(row.warehouse_id) || 0; const stockStoreKey = `${stockId}_${storeId}`; const snapshot = edgeByStockStore.get(stockStoreKey); const rangeSum = rangeSumByStockStore.get(stockStoreKey); @@ -1059,11 +1196,13 @@ class StorageReportService extends Service { end_time: endTime || null, stock_id: stockId, store_id: storeId, + warehouse_id: whId, begin_total: beginTotal, end_total: endTotal, inbound_total: toNumber(rangeSum && rangeSum.inbound_total), outbound_total: toNumber(rangeSum && rangeSum.outbound_total), store_name: '', + warehouse_name: '', item_name: '', barcode: '', item_code: '', @@ -1071,16 +1210,19 @@ class StorageReportService extends Service { }) .filter(item => item.stock_id > 0 && item.store_id > 0); - const stockIds = [ ...new Set(groupedList.map(item => item.stock_id).filter(Boolean)) ]; + const groupedStockIds = [ ...new Set(groupedList.map(item => item.stock_id).filter(Boolean)) ]; const storeIdList = [ ...new Set(groupedList.map(item => item.store_id).filter(Boolean)) ]; + const warehouseIdList = [ ...new Set(groupedList.map(item => item.warehouse_id).filter(Boolean)) ]; // 复用 getStockDetails 获取商品名称和条码 + // store 模式下不传 warehouseId,避免用 store_id 误当 warehouse_id 过滤导致查不到商品 + const stockDetailOpts = isStoreMode ? { warehouseId: null } : {}; const stockMap = new Map(); const barcodesByStock = new Map(); - if (stockIds.length > 0) { + if (groupedStockIds.length > 0) { const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails( - stockIds, - {} + groupedStockIds, + stockDetailOpts ); for (const detail of stockDetails) { const sid = Number(detail.id); @@ -1115,15 +1257,29 @@ class StorageReportService extends Service { const storeMap = new Map(storeRows.map(item => [ Number(item.id), item ])); + const warehouseRows = warehouseIdList.length > 0 + ? await ctx.model.Store.findAll({ + where: { + id: warehouseIdList, + }, + attributes: [ 'id', 'company_name' ], + raw: true, + }) + : []; + + const warehouseMap = new Map(warehouseRows.map(item => [ Number(item.id), item ])); + const list = groupedList .map(item => { const stock = stockMap.get(item.stock_id) || {}; const store = storeMap.get(item.store_id) || {}; + const warehouse = warehouseMap.get(item.warehouse_id) || {}; const barcodeSet = barcodesByStock.get(item.stock_id); return { ...item, store_name: store.company_name || '', + warehouse_name: warehouse.company_name || '', item_name: stock.item_name || '', item_code: stock.item_code || '', barcode: barcodeSet ? [ ...barcodeSet ].join(',') : '', @@ -1146,6 +1302,7 @@ class StorageReportService extends Service { const stockId = Number(row.stock_id); const spaceId = Number(row.space_id) || 0; const storeId = Number(row.store_id); + const whId = Number(row.warehouse_id) || 0; if (!stockId || !storeId) { continue; } @@ -1155,6 +1312,7 @@ class StorageReportService extends Service { stock_id: stockId, space_id: spaceId, store_id: storeId, + warehouse_id: whId, quantity: toNumber(row.quantity), }); } @@ -1163,6 +1321,7 @@ class StorageReportService extends Service { const stockId = Number(row.stock_id); const spaceId = Number(row.space_id) || 0; const storeId = Number(row.store_id); + const whId = Number(row.warehouse_id) || 0; if (!stockId || !storeId) { continue; } @@ -1173,6 +1332,7 @@ class StorageReportService extends Service { stock_id: stockId, space_id: spaceId, store_id: storeId, + warehouse_id: whId, quantity: 0, }); } @@ -1226,6 +1386,7 @@ class StorageReportService extends Service { const stockId = Number(row.stock_id); const spaceId = Number(row.space_id) || 0; const storeId = Number(row.store_id); + const whId = Number(row.warehouse_id) || 0; const baseKey = `${stockId}_${spaceId}_${storeId}`; const snapshot = edgeByBaseKey.get(baseKey) || { begin_total: 0, @@ -1247,12 +1408,14 @@ class StorageReportService extends Service { end_time: endTime || null, stock_id: stockId, store_id: storeId, + warehouse_id: whId, ...(isBySpace ? { space_id: spaceId } : {}), begin_total: 0, end_total: 0, inbound_total: 0, outbound_total: 0, store_name: '', + warehouse_name: '', item_name: '', barcode: '', item_code: '', @@ -1274,19 +1437,22 @@ class StorageReportService extends Service { } const groupedList = [ ...groupedMap.values() ]; - const stockIds = [ ...new Set(groupedList.map(item => item.stock_id).filter(Boolean)) ]; + const groupedStockIds = [ ...new Set(groupedList.map(item => item.stock_id).filter(Boolean)) ]; const storeIdList = [ ...new Set(groupedList.map(item => item.store_id).filter(Boolean)) ]; + const warehouseIdList = [ ...new Set(groupedList.map(item => item.warehouse_id).filter(Boolean)) ]; const spaceIds = isBySpace ? [ ...new Set(groupedList.map(item => item.space_id).filter(id => Number(id) > 0)) ] : []; // 复用 getStockDetails 获取商品名称和条码 + // store 模式下不传 warehouseId,避免用 store_id 误当 warehouse_id 过滤导致查不到商品 + const stockDetailOptsSpace = isStoreMode ? { warehouseId: null } : {}; const stockMap = new Map(); const barcodesByStock = new Map(); - if (stockIds.length > 0) { + if (groupedStockIds.length > 0) { const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails( - stockIds, - {} + groupedStockIds, + stockDetailOptsSpace ); for (const detail of stockDetails) { const sid = Number(detail.id); @@ -1309,7 +1475,7 @@ class StorageReportService extends Service { } } - const [ storeRows, spaceRows ] = await Promise.all([ + const [ storeRows, spaceRows, warehouseRows ] = await Promise.all([ storeIdList.length > 0 ? ctx.model.Store.findAll({ where: { @@ -1328,21 +1494,33 @@ class StorageReportService extends Service { raw: true, }) : [], + warehouseIdList.length > 0 + ? ctx.model.Store.findAll({ + where: { + id: warehouseIdList, + }, + attributes: [ 'id', 'company_name' ], + raw: true, + }) + : [], ]); const storeMap = new Map(storeRows.map(item => [ Number(item.id), item ])); const spaceMap = new Map(spaceRows.map(item => [ Number(item.id), item ])); + const warehouseMap = new Map(warehouseRows.map(item => [ Number(item.id), item ])); const list = groupedList .map(item => { const stock = stockMap.get(item.stock_id) || {}; const store = storeMap.get(item.store_id) || {}; + const warehouse = warehouseMap.get(item.warehouse_id) || {}; const barcodeSet = barcodesByStock.get(item.stock_id); const space = isBySpace ? (spaceMap.get(Number(item.space_id)) || {}) : null; const merged = { ...item, store_name: store.company_name || '', + warehouse_name: warehouse.company_name || '', item_name: stock.item_name || '', item_code: stock.item_code || '', barcode: barcodeSet ? [ ...barcodeSet ].join(',') : '', diff --git a/app/service/systems/store_warehouse.js b/app/service/systems/store_warehouse.js index bdd2561..d4dae35 100644 --- a/app/service/systems/store_warehouse.js +++ b/app/service/systems/store_warehouse.js @@ -1,6 +1,11 @@ 'use strict'; const crypto = require('node:crypto'); +const fs = require('node:fs'); +const fsp = require('node:fs/promises'); +const os = require('node:os'); +const path = require('node:path'); +const ExcelJS = require('exceljs'); const Service = require('egg').Service; const { Op } = require('sequelize'); @@ -1448,12 +1453,9 @@ class SettingStoreWarehouseService extends Service { const pageSize = this.normalizePage(data.page_size || data.pageSize, 'page_size', 20, 200); const offset = (page - 1) * pageSize; - // OR 查询两边,兼容新旧签约数据 + // 仓库查看自己签约的货主列表:仓库在 warehouse_id 方,货主在 store_id 方 const where = { - [Op.or]: [ - { store_id: currentSubject.id }, - { warehouse_id: currentSubject.id }, - ], + warehouse_id: currentSubject.id, }; const relationId = this.resolveRelationId(data); @@ -1461,16 +1463,10 @@ class SettingStoreWarehouseService extends Service { where.id = relationId; } - const counterpartyId = this.toPositiveNumber(data.counterparty_id || data.warehouse_id, 'counterparty_id', { allowEmpty: true }); + const counterpartyId = this.toPositiveNumber(data.counterparty_id || data.store_id, 'counterparty_id', { allowEmpty: true }); if (counterpartyId) { - // 对方可能在 store_id 或 warehouse_id,两边都过滤 - where[Op.and] = where[Op.and] || []; - where[Op.and].push({ - [Op.or]: [ - { store_id: counterpartyId, warehouse_id: currentSubject.id }, - { warehouse_id: counterpartyId, store_id: currentSubject.id }, - ], - }); + // 对方(货主)在 store_id 方 + where.store_id = counterpartyId; } const authStatus = this.normalizeAuthStatus(data.auth_status); @@ -1478,16 +1474,9 @@ class SettingStoreWarehouseService extends Service { where.auth_status = authStatus; } - const rawUseStatus = data.use_status !== undefined ? data.use_status : data.store_use_status; + const rawUseStatus = data.use_status !== undefined ? data.use_status : data.warehouse_use_status; if (rawUseStatus !== undefined && rawUseStatus !== null && rawUseStatus !== '') { - // 同时过滤 store_use_status 和 warehouse_use_status - where[Op.and] = where[Op.and] || []; - where[Op.and].push({ - [Op.or]: [ - { store_use_status: Number(rawUseStatus), store_id: currentSubject.id }, - { warehouse_use_status: Number(rawUseStatus), warehouse_id: currentSubject.id }, - ], - }); + where.warehouse_use_status = Number(rawUseStatus); } const keyword = typeof data.keyword === 'string' ? data.keyword.trim() : ''; @@ -1568,12 +1557,9 @@ class SettingStoreWarehouseService extends Service { const pageSize = this.normalizePage(data.page_size || data.pageSize, 'page_size', 20, 200); const offset = (page - 1) * pageSize; - // OR 查询两边,兼容新旧签约数据 + // 货主查看自己签约的仓库列表:货主在 store_id 方,仓库在 warehouse_id 方 const where = { - [Op.or]: [ - { store_id: currentSubject.id }, - { warehouse_id: currentSubject.id }, - ], + store_id: currentSubject.id, }; const relationId = this.resolveRelationId(data); @@ -1583,14 +1569,8 @@ class SettingStoreWarehouseService extends Service { const counterpartyId = this.toPositiveNumber(data.counterparty_id || data.warehouse_id, 'counterparty_id', { allowEmpty: true }); if (counterpartyId) { - // 对方可能在 store_id 或 warehouse_id,两边都过滤 - where[Op.and] = where[Op.and] || []; - where[Op.and].push({ - [Op.or]: [ - { store_id: counterpartyId, warehouse_id: currentSubject.id }, - { warehouse_id: counterpartyId, store_id: currentSubject.id }, - ], - }); + // 对方(仓库)在 warehouse_id 方 + where.warehouse_id = counterpartyId; } const authStatus = this.normalizeAuthStatus(data.auth_status); @@ -1600,14 +1580,7 @@ class SettingStoreWarehouseService extends Service { const rawUseStatus = data.use_status !== undefined ? data.use_status : data.store_use_status; if (rawUseStatus !== undefined && rawUseStatus !== null && rawUseStatus !== '') { - // 同时过滤 store_use_status 和 warehouse_use_status - where[Op.and] = where[Op.and] || []; - where[Op.and].push({ - [Op.or]: [ - { store_use_status: Number(rawUseStatus), store_id: currentSubject.id }, - { warehouse_use_status: Number(rawUseStatus), warehouse_id: currentSubject.id }, - ], - }); + where.store_use_status = Number(rawUseStatus); } const keyword = typeof data.keyword === 'string' ? data.keyword.trim() : ''; @@ -2213,6 +2186,34 @@ class SettingStoreWarehouseService extends Service { limit: pageSize, }); + // 收集所有需要回填姓名的操作人 ID + const accountIdSet = new Set(); + for (const item of rows) { + const payload = item && typeof item.get === 'function' + ? item.get({ plain: true }) + : (item || {}); + if (payload.operator_id) accountIdSet.add(Number(payload.operator_id)); + if (payload.created_by) accountIdSet.add(Number(payload.created_by)); + } + const accountIds = Array.from(accountIdSet).filter(id => Number.isFinite(id) && id > 0); + + // 批量查询账号姓名 + let accountNameMap = {}; + if (accountIds.length > 0) { + try { + const accounts = await ctx.model.Account.findAll({ + attributes: [ 'id', 'real_name' ], + where: { id: { [Op.in]: accountIds } }, + raw: true, + }); + for (const acc of accounts) { + accountNameMap[Number(acc.id)] = acc.real_name || ''; + } + } catch (err) { + ctx.logger.warn('[queryPrintQuantityLogs] 批量查询操作人姓名失败,不影响主流程: %s', err.message); + } + } + const total = Number(count || 0); const totalPages = total > 0 ? Math.ceil(total / pageSize) : 0; @@ -2224,6 +2225,13 @@ class SettingStoreWarehouseService extends Service { ? item.get({ plain: true }) : (item || {}); + const operatorId = payload.operator_id !== undefined && payload.operator_id !== null + ? Number(payload.operator_id) + : null; + const createdBy = payload.created_by !== undefined && payload.created_by !== null + ? Number(payload.created_by) + : null; + return { id: Number(payload.id || 0), contract_id: Number(payload.contract_id || 0), @@ -2242,12 +2250,10 @@ class SettingStoreWarehouseService extends Service { balance_before: Number(payload.balance_before || 0), balance_after: Number(payload.balance_after || 0), reason: payload.reason || '', - operator_id: payload.operator_id !== undefined && payload.operator_id !== null - ? Number(payload.operator_id) - : null, - created_by: payload.created_by !== undefined && payload.created_by !== null - ? Number(payload.created_by) - : null, + operator_id: operatorId, + operator_name: operatorId ? (accountNameMap[operatorId] || '') : '', + created_by: createdBy, + created_by_name: createdBy ? (accountNameMap[createdBy] || '') : '', created_at: payload.created_at || null, updated_at: payload.updated_at || null, }; @@ -2264,6 +2270,182 @@ class SettingStoreWarehouseService extends Service { }; } + /** + * 导出面单余额变更日志。 + * 查询所有匹配条件的记录,生成 Excel 文件上传至 COS,返回下载信息。 + * + * @param {Object} data 请求数据。 + * @param {number|string} data.store_id 货主ID(必填)。 + * @param {Object} [data.where] 动态筛选条件,与 queryPrintQuantityLogs 的 where 语义一致。 + * @return {Promise} 包含 url、fileKey、filename 的对象。 + */ + async exportPrintQuantityLogs(data = {}) { + const { ctx } = this; + const currentSubject = await this.getCurrentSubject(); + const storeId = this.toPositiveNumber(data.store_id, 'store_id'); + + if (!currentSubject.isWarehouse && Number(currentSubject.id) !== Number(storeId)) { + throw this.createError('仅可导出当前货主的面单余额变更日志', 403); + } + + const where = { + store_id: Number(storeId), + }; + + if (currentSubject.isWarehouse) { + where.warehouse_id = Number(currentSubject.id); + } + + const dynamicConditions = this.ctx.whereParsed && Array.isArray(this.ctx.whereParsed.dynamicConditions) + ? this.ctx.whereParsed.dynamicConditions.filter(Boolean) + : []; + + if (dynamicConditions.length > 0) { + where[Op.and] = dynamicConditions; + } + + // 查询全部匹配记录 + const rows = await ctx.model.StoreWarehousePrintQuantityLog.findAll({ + where, + order: [[ 'created_at', 'DESC' ], [ 'id', 'DESC' ]], + raw: true, + }); + + // 收集操作人 ID,批量查询姓名 + const accountIdSet = new Set(); + for (const item of rows) { + if (item.operator_id) accountIdSet.add(Number(item.operator_id)); + if (item.created_by) accountIdSet.add(Number(item.created_by)); + } + const accountIds = Array.from(accountIdSet).filter(id => Number.isFinite(id) && id > 0); + const accountNameMap = {}; + if (accountIds.length > 0) { + const accounts = await ctx.model.Account.findAll({ + attributes: [ 'id', 'real_name' ], + where: { id: { [Op.in]: accountIds } }, + raw: true, + }); + for (const acc of accounts) { + accountNameMap[Number(acc.id)] = acc.real_name || ''; + } + } + + // 生成 Excel + const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'print_qty_log_export_')); + const filename = `面单余额变更日志_${storeId}_${Date.now()}.xlsx`; + const filePath = path.join(tempDir, filename); + + const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({ + filename: filePath, + useStyles: true, + useSharedStrings: true, + }); + const worksheet = workbook.addWorksheet('面单余额变更日志'); + + worksheet.columns = [ + { header: '记录ID', key: 'id', width: 10 }, + { header: '签约关系ID', key: 'contract_id', width: 14 }, + { header: '货主ID', key: 'store_id', width: 10 }, + { header: '仓库ID', key: 'warehouse_id', width: 10 }, + { header: '变更类型', key: 'change_type_label', width: 12 }, + { header: '业务来源类型', key: 'business_type_label', width: 14 }, + { header: '业务关联ID', key: 'business_id', width: 14 }, + { header: '变更数量', key: 'change_quantity', width: 12 }, + { header: '变更前余额', key: 'balance_before', width: 14 }, + { header: '变更后余额', key: 'balance_after', width: 14 }, + { header: '变更原因', key: 'reason', width: 30 }, + { header: '操作人', key: 'operator_name', width: 14 }, + { header: '创建人', key: 'created_by_name', width: 14 }, + { header: '创建时间', key: 'created_at', width: 22 }, + { header: '更新时间', key: 'updated_at', width: 22 }, + ]; + + for (const item of rows) { + const operatorId = item.operator_id !== undefined && item.operator_id !== null + ? Number(item.operator_id) + : null; + const createdBy = item.created_by !== undefined && item.created_by !== null + ? Number(item.created_by) + : null; + + worksheet.addRow({ + id: Number(item.id || 0), + contract_id: Number(item.contract_id || 0), + store_id: Number(item.store_id || 0), + warehouse_id: Number(item.warehouse_id || 0), + change_type_label: CHANGE_TYPE_LABEL_MAP[item.change_type] || item.change_type || '', + business_type_label: item.business_type + ? (BUSINESS_TYPE_LABEL_MAP[item.business_type] || item.business_type) + : '-', + business_id: item.business_id !== undefined && item.business_id !== null + ? Number(item.business_id) + : '', + change_quantity: Number(item.change_quantity || 0), + balance_before: Number(item.balance_before || 0), + balance_after: Number(item.balance_after || 0), + reason: item.reason || '', + operator_name: operatorId ? (accountNameMap[operatorId] || '') : '', + created_by_name: createdBy ? (accountNameMap[createdBy] || '') : '', + created_at: item.created_at ? String(item.created_at) : '', + updated_at: item.updated_at ? String(item.updated_at) : '', + }).commit(); + } + + worksheet.commit(); + await workbook.commit(); + + // 上传至 COS + const uploadService = ctx.service && ctx.service.systems && ctx.service.systems.upload; + let uploadResult = {}; + if (uploadService && typeof uploadService.uploadFile === 'function') { + const stat = await fsp.stat(filePath); + const uploadStream = fs.createReadStream(filePath); + uploadStream.filename = filename; + uploadStream.mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; + uploadStream.fileSize = stat.size; + + uploadResult = await uploadService.uploadFile(uploadStream, { + key: `export/print_quantity_log/${storeId}/${filename}`, + category: 'document', + mimetype: 'xls,xlsx,csv', + }); + + if (typeof uploadService.uploadSuccessNotify === 'function') { + await uploadService.uploadSuccessNotify({ + url: uploadResult.fileName, + fileKey: uploadResult.fileName, + fileName: filename, + fileType: 'document', + mimeType: uploadStream.mimeType, + fileSize: stat.size, + category: 'document', + businessType: 'printQuantityLogExport', + businessId: String(storeId), + uploaderType: ctx.user?.role || 'system_api', + uploaderDept: ctx.user?.department || '', + }).catch(err => { + ctx.logger.warn('[storeWarehouse.exportPrintQuantityLogs] 上传通知失败: %s', err.message); + }); + } + } + + // 清理临时文件 + try { + await fsp.rm(tempDir, { recursive: true, force: true }); + } catch (cleanErr) { + ctx.logger.warn('[storeWarehouse.exportPrintQuantityLogs] 清理临时文件失败: %s', cleanErr.message); + } + + return { + filename, + fileKey: uploadResult.fileName || '', + url: uploadResult.url || uploadResult.cdnUrl || uploadResult.cosUrl || '', + cdnUrl: uploadResult.cdnUrl || uploadResult.url || '', + cosUrl: uploadResult.cosUrl || '', + total_count: rows.length, + }; + } + /** * 获取策略配置字段。 * @@ -2465,12 +2647,15 @@ class SettingStoreWarehouseService extends Service { let qimenCustomerId = null; let qimenWarehouseCode = null; + // 外部入参优先,未传入时才从 qimen_app 表解析 + const externalCustomerId = this.normalizeText(data.qimen_customer_id, 'qimen_customer_id', 100); + if (isQimenWms) { qimenAppKey = this.normalizeText(data.qimen_app_key, 'qimen_app_key', 100); if (!qimenAppKey) { throw this.createError('奇门接口类型下 qimen_app_key 参数不能为空', 400); } - qimenCustomerId = await this.resolveQimenCustomerIdByAppKey(qimenAppKey, { transaction }); + qimenCustomerId = externalCustomerId || await this.resolveQimenCustomerIdByAppKey(qimenAppKey, { transaction }); qimenWarehouseCode = this.normalizeText(data.qimen_warehouse_code, 'qimen_warehouse_code', 100); if (!qimenWarehouseCode) { throw this.createError('奇门接口类型下 qimen_warehouse_code 参数不能为空', 400); @@ -2478,9 +2663,8 @@ class SettingStoreWarehouseService extends Service { } else { // OPEN_API: 奇门字段可选输入 qimenAppKey = this.normalizeText(data.qimen_app_key, 'qimen_app_key', 100) || null; - qimenCustomerId = qimenAppKey - ? await this.resolveQimenCustomerIdByAppKey(qimenAppKey, { transaction }) - : null; + qimenCustomerId = externalCustomerId + || (qimenAppKey ? await this.resolveQimenCustomerIdByAppKey(qimenAppKey, { transaction }) : null); qimenWarehouseCode = this.normalizeText(data.qimen_warehouse_code, 'qimen_warehouse_code', 100) || null; } From 888d0261455f723bca077c7d8e8b9b75306a953a Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 27 Jul 2026 03:48:26 +0800 Subject: [PATCH 129/550] =?UTF-8?q?feat(shop/store):=20=E5=BA=97=E9=93=BA?= =?UTF-8?q?=E7=AE=A1=E7=90=86=E5=A2=9E=E5=BC=BA=20+=20=E9=97=A8=E5=BA=97?= =?UTF-8?q?=E4=BB=93=E5=BA=93=E5=8A=A0=E8=BD=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - shops: 支持修改 shop_name + 删除店铺查询改用 Op.notLike 前缀过滤 - store: loadStores 增加 Store 关联查 company_name 作为 label fallback - store: 新增 loadWarehouses(货主侧加载可用仓库) - index: 注册 loadWarehouses 权限 --- app/service/systemMethods/index.js | 9 ++++-- app/service/systemMethods/shops.js | 6 ++++ app/service/systems/shops.js | 40 +++++++++++++++++------- app/service/systems/store.js | 50 ++++++++++++++++++++++++++---- 4 files changed, 86 insertions(+), 19 deletions(-) diff --git a/app/service/systemMethods/index.js b/app/service/systemMethods/index.js index 2db538f..a8fae05 100644 --- a/app/service/systemMethods/index.js +++ b/app/service/systemMethods/index.js @@ -1053,9 +1053,9 @@ class indexService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = 'getI18nMessage,putI18nCollect,test,getCainiaoStfTemplates,polyapiAuthorizeUrl'; - const _noNeedRight = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getCOSUploadConfig,uploadSuccessNotify,getMessageDetail,searchSpace,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,getPlatformOauthLink,listenPlatformOauthBind,recognizeLicensePlate,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl,toOrder'; + const _noNeedRight = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,loadWarehouses,getImages,getCOSUploadConfig,uploadSuccessNotify,getMessageDetail,searchSpace,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,getPlatformOauthLink,listenPlatformOauthBind,recognizeLicensePlate,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl,toOrder'; const _noNeedLog = '*'; - const _noNeedAuth = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getMessageDetail,searchSpace,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,getPlatformOauthLink,listenPlatformOauthBind,recognizeLicensePlate,test,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl,toOrder'; + const _noNeedAuth = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,loadWarehouses,getImages,getMessageDetail,searchSpace,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,getPlatformOauthLink,listenPlatformOauthBind,recognizeLicensePlate,test,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl,toOrder'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } async fastWhereTree(data) { @@ -1069,6 +1069,11 @@ class indexService extends MainService { const result = await service.systems.store.loadStores(); return this.success('ok', { stores: result, code: 200 }); } + async loadWarehouses() { + const { service } = this; + const result = await service.systems.store.loadWarehouses(); + return this.success('ok', { warehouses: result, code: 200 }); + } async getCOSUploadConfig(datas) { const { service } = this; const { data } = datas; diff --git a/app/service/systemMethods/shops.js b/app/service/systemMethods/shops.js index f7dc841..8c1034d 100644 --- a/app/service/systemMethods/shops.js +++ b/app/service/systemMethods/shops.js @@ -108,6 +108,8 @@ class ShopsMethodService extends MainService { id, shop_id: shopId, shopId: shopIdCamel, + shop_name: shopName, + shopName: shopNameCamel, custom_name: customName, customName: customNameCamel, platform_code: platformCode, @@ -118,6 +120,10 @@ class ShopsMethodService extends MainService { id: id !== undefined ? id : (shopId !== undefined ? shopId : shopIdCamel), }; + if (shopName !== undefined || shopNameCamel !== undefined) { + payload.shop_name = shopName !== undefined ? shopName : shopNameCamel; + } + if (customName !== undefined || customNameCamel !== undefined) { payload.custom_name = customName !== undefined ? customName : customNameCamel; } diff --git a/app/service/systems/shops.js b/app/service/systems/shops.js index 110cdd8..521e633 100644 --- a/app/service/systems/shops.js +++ b/app/service/systems/shops.js @@ -373,8 +373,10 @@ class ShopsService extends Service { const where = { warehouse_id: warehouseId, platform_code: platformCode, - shop_name: shopName, - ...buildNotDeletedShopWhere(app), + shop_name: { + [Op.eq]: shopName, + [Op.notLike]: `${DELETED_SHOP_NAME_PREFIX}%`, + }, }; if (excludeId !== null) { @@ -537,9 +539,11 @@ class ShopsService extends Service { || Object.prototype.hasOwnProperty.call(data, 'platformCode'); const hasCustomName = Object.prototype.hasOwnProperty.call(data, 'custom_name') || Object.prototype.hasOwnProperty.call(data, 'customName'); + const hasShopName = Object.prototype.hasOwnProperty.call(data, 'shop_name') + || Object.prototype.hasOwnProperty.call(data, 'shopName'); - if (!hasPlatformCode && !hasCustomName) { - throw this.createError('仅允许修改 platform_code 或 custom_name', 400); + if (!hasPlatformCode && !hasCustomName && !hasShopName) { + throw this.createError('仅允许修改 platform_code、custom_name 或 shop_name', 400); } if (hasPlatformCode) { @@ -556,8 +560,16 @@ class ShopsService extends Service { ); } + if (hasShopName) { + updates.shop_name = this.normalizeText( + data.shop_name !== undefined ? data.shop_name : data.shopName, + 'shop_name', + { required: true, maxLength: 100 } + ); + } + const nextPlatformCode = updates.platform_code || shop.platform_code; - const nextShopName = shop.shop_name; + const nextShopName = updates.shop_name || shop.shop_name; await this.ensureShopNameUnique({ warehouseId: this.getCurrentWarehouseId(), @@ -697,16 +709,22 @@ class ShopsService extends Service { attributes: [ 'get_auth_platform_name' ], }); + const platName = printPlatform ? printPlatform.get_auth_platform_name : platformCode; + const requestData = { + RedirectCodeUrl: callbackUrl, + command: 'saveShop', + platName, + shopName: shopPlain.shop_name, + }; + if (platName === '电商京东') { + requestData.VenderID = shopPlain.id; + } + const respone = await ctx.curl(authUrl, { method: 'POST', dataType: 'json', timeout: 5000, - data: { - RedirectCodeUrl: callbackUrl, - command: 'saveShop', - platName: printPlatform ? printPlatform.get_auth_platform_name : platformCode, - shopName: shopPlain.shop_name, - }, + data: requestData, }); if (respone.data && respone.data.code === 0) { const sessionKey = respone.data.data || null; diff --git a/app/service/systems/store.js b/app/service/systems/store.js index 50ddba7..5358472 100644 --- a/app/service/systems/store.js +++ b/app/service/systems/store.js @@ -948,24 +948,62 @@ class StoreService extends Service { const { ctx } = this; try { - const stores = await ctx.model.StoreWarehouse.findAll({ + const rows = await ctx.model.StoreWarehouse.findAll({ where: { warehouse_use_status: 1, warehouse_id: ctx.user.store_id, }, - attributes: [ - [ 'store_id', 'value' ], // store_id 字段别名为 value - [ 'store_remask', 'label' ], // store_remask 字段别名为 label + attributes: [ 'store_id', 'store_remask' ], + include: [ + { + model: ctx.model.Store, + as: 'store', + attributes: [ 'company_name' ], + required: false, + }, ], - raw: true, // 可选:返回纯JSON数据 + raw: true, }); - return stores; + return rows.map(row => ({ + value: row.store_id, + label: row.store_remask || (row['store.company_name'] || ''), + })); } catch (error) { ctx.logger.error('[Service.loadStores] 查询失败:', error); throw error; } } + async loadWarehouses() { + const { ctx } = this; + + try { + const rows = await ctx.model.StoreWarehouse.findAll({ + where: { + store_use_status: 1, + store_id: ctx.user.store_id, + }, + attributes: [ 'warehouse_id', 'warehouse_remask' ], + include: [ + { + model: ctx.model.Store, + as: 'warehouse', + attributes: [ 'company_name' ], + required: false, + }, + ], + raw: true, + }); + + return rows.map(row => ({ + value: row.warehouse_id, + label: row.warehouse_remask || (row['warehouse.company_name'] || ''), + })); + } catch (error) { + ctx.logger.error('[Service.loadWarehouses] 查询失败:', error); + throw error; + } + } } module.exports = StoreService; From b2ae5683e13bfd65cfe0d9292d35914a8885242c Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 27 Jul 2026 03:48:45 +0800 Subject: [PATCH 130/550] =?UTF-8?q?feat(order):=20=E6=B3=A2=E6=AC=A1/?= =?UTF-8?q?=E6=8B=A3=E8=B4=A7/=E5=A4=8D=E6=A0=B8=E9=80=8F=E4=BC=A0?= =?UTF-8?q?=E8=B4=A7=E4=B8=BB=E4=BF=A1=E6=81=AF=20+=20=E5=8F=96=E6=B6=88?= =?UTF-8?q?=E8=AE=A2=E5=8D=95=E8=BF=87=E6=BB=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - wave: 透传 store_id/owner_code/store_remark - recheckOrder: 波次视图新增 store_id/store_remark,批量查询货主备注 - pick: 分组聚合透传 store_id/owner_code/store_remark/stock - order_storage_allocation: 储位分配注入 stock_id + 回传排除取消订单 - order_async: 标记异常排除取消状态订单 --- .../wave_strategy_quick_scan_fallback.js | 2 +- .../systemMethods/order/recheckOrder.js | 41 +++++++++++++-- app/service/systemMethods/order/wave.js | 26 +++++++--- app/service/systems/order_async.js | 3 ++ .../systems/order_storage_allocation.js | 5 ++ app/service/systems/pick.js | 52 ++++++++++++++++++- 6 files changed, 116 insertions(+), 13 deletions(-) diff --git a/app/schedule/wave_strategy_quick_scan_fallback.js b/app/schedule/wave_strategy_quick_scan_fallback.js index 7862e07..0ce27f0 100644 --- a/app/schedule/wave_strategy_quick_scan_fallback.js +++ b/app/schedule/wave_strategy_quick_scan_fallback.js @@ -46,7 +46,7 @@ module.exports = { for (const warehouseId of warehouseIds) { try { - const submitPayload = await ctx.service.systemMethods.order.wave.submitWaveStrategyQuickScanForWarehouse(warehouseId, { wait: true }); + const submitPayload = await ctx.service.systemMethods.order.wave.submitWaveStrategyQuickScanForWarehouse(warehouseId, { wait: true, forceRescan: true }); const submitMessage = String(submitPayload && submitPayload.message || '').trim(); const submitState = String(submitPayload && submitPayload.state || '').trim(); const isReusedRunningTask = submitMessage.includes('已有快速扫描任务在运行中') diff --git a/app/service/systemMethods/order/recheckOrder.js b/app/service/systemMethods/order/recheckOrder.js index f338f20..04a29c6 100644 --- a/app/service/systemMethods/order/recheckOrder.js +++ b/app/service/systemMethods/order/recheckOrder.js @@ -751,6 +751,9 @@ class RecheckOrderService extends OrderBaseService { images: Array.isArray(item.images) ? [ ...item.images ] : [], has_shared_barcode: Boolean(item.has_shared_barcode), plan_qty: Number(item.plan_qty || 0), + store_id: item.store_id != null ? Number(item.store_id) : 0, + owner_code: String(item.owner_code || '').trim(), + store_remark: String(item.store_remark || '').trim(), })); // 构建拦截订单列表 @@ -761,9 +764,6 @@ class RecheckOrderService extends OrderBaseService { intercept_status: String(order.intercept_status || '').trim(), })); - // 提取正常(非拦截)订单的 ID 列表 - const orderIds = normalOrders.map(order => Number(order.order_id || 0)).filter(id => id > 0); - // 计算波次内复核统计(基于非拦截订单的 recheck_status 实时聚合) const reviewedCount = normalOrders.filter(o => String(o.recheck_status || '').trim() === 'fin').length; const unreviewedCount = normalOrders.length - reviewedCount; @@ -786,8 +786,9 @@ class RecheckOrderService extends OrderBaseService { update_time: waveView.update_time, order_count: waveView.order_count, box_no: Number(tw.box_no || 0), - order_ids: orderIds, stocks, + store_id: sampleOrder ? Number(sampleOrder.store_id || 0) : 0, + store_remark: sampleOrder ? String(sampleOrder.store_remark || '').trim() : '', reviewed_count: reviewedCount, unreviewed_count: unreviewedCount, printed_count: printedCount, @@ -1118,6 +1119,7 @@ class RecheckOrderService extends OrderBaseService { order_type: String(row.order_type || '').trim(), status: Number(row.status || 0), logistics_name: String(row.logistics_name || '').trim(), + store_id: Number(row.store_id || 0), store_remark: storeRemarkMap.has(Number(row.store_id || 0)) ? storeRemarkMap.get(Number(row.store_id || 0)) : '', @@ -1257,7 +1259,7 @@ class RecheckOrderService extends OrderBaseService { where: { order_id: { [this.app.Sequelize.Op.in]: orderIds }, }, - attributes: [ 'order_id', 'stock_id', 'item_code', 'item_name', 'plan_qty', 'item_snapshot' ], + attributes: [ 'order_id', 'stock_id', 'item_code', 'item_name', 'plan_qty', 'item_snapshot', 'owner_code' ], order: [[ 'id', 'ASC' ]], raw: true, }); @@ -1297,6 +1299,32 @@ class RecheckOrderService extends OrderBaseService { } } + // 4. 批量查询货主备注名(wms_store_warehouse.store_remask),按 store_id 映射 + const storeRemarkMapByStock = new Map(); + if (stockMap.size > 0 && this.ctx.model && this.ctx.model.StoreWarehouse) { + const storeIdsForRemark = [ ...new Set( + [ ...stockMap.values() ] + .map(detail => Number(detail.store_id || 0)) + .filter(id => id > 0) + ) ]; + if (storeIdsForRemark.length > 0) { + const swRows = await this.ctx.model.StoreWarehouse.findAll({ + where: { + store_id: { [this.app.Sequelize.Op.in]: storeIdsForRemark }, + warehouse_id: warehouseId, + }, + attributes: [ 'store_id', 'store_remask' ], + raw: true, + }); + for (const sw of (Array.isArray(swRows) ? swRows : [])) { + const sid = Number(sw.store_id || 0); + if (sid > 0 && !storeRemarkMapByStock.has(sid)) { + storeRemarkMapByStock.set(sid, String(sw.store_remask || '').trim()); + } + } + } + } + // 5. 检测共享条码:查询当前所有条码是否也出现在其他 stock_id 中 const sharedBarcodeSet = new Set(); if (barcodeMap.size > 0) { @@ -1369,6 +1397,9 @@ class RecheckOrderService extends OrderBaseService { images, has_shared_barcode: hasSharedBarcode, plan_qty: Number(item.plan_qty || 0), + store_id: stockInfo.store_id != null ? Number(stockInfo.store_id) : 0, + owner_code: String(item.owner_code || '').trim(), + store_remark: storeRemarkMapByStock.get(stockInfo.store_id != null ? Number(stockInfo.store_id) : 0) || '', }; }); diff --git a/app/service/systemMethods/order/wave.js b/app/service/systemMethods/order/wave.js index 86ba90b..34b5014 100644 --- a/app/service/systemMethods/order/wave.js +++ b/app/service/systemMethods/order/wave.js @@ -21,7 +21,7 @@ const BATCH_ALLOCATE_EXPRESS_TASK_CACHE_TTL_SECONDS = 60 * 60 * 24; const BATCH_ALLOCATE_STORAGE_TASK_CACHE_KEY_PREFIX = 'wave:batch-allocate-storage:'; const BATCH_ALLOCATE_STORAGE_TASK_CACHE_TTL_SECONDS = 60 * 60 * 24; const WAVE_STRATEGY_QUICK_SCAN_TASK_CACHE_KEY_PREFIX = 'wave:quick-scan:task:'; -const WAVE_STRATEGY_QUICK_SCAN_TASK_CACHE_TTL_SECONDS = 60 * 60 * 24; +const WAVE_STRATEGY_QUICK_SCAN_TASK_CACHE_TTL_SECONDS = 60 * 5; const WAVE_STRATEGY_QUICK_SCAN_WAREHOUSE_LOCK_CACHE_KEY_PREFIX = 'wave:quick-scan:lock:'; const WAVE_STRATEGY_QUICK_SCAN_WAREHOUSE_LOCK_TTL_SECONDS = 60 * 60 * 2; const WAVE_STRATEGY_LIST_CACHE_KEY_PREFIX = 'wave:strategy-list:'; @@ -5244,6 +5244,7 @@ class WaveService extends OrderBaseService { const normalizedOptions = this.isPlainObject(options) ? options : {}; const orderIds = this.normalizeIdsInput(normalizedOptions.orderIds); const wait = this.normalizeBoolean(normalizedOptions.wait, false); + const forceRescan = this.normalizeBoolean(normalizedOptions.forceRescan, false); const runningTask = await this.getWaveStrategyQuickScanWarehouseLock(normalizedWarehouseId); if (runningTask && runningTask.task_id) { @@ -5282,6 +5283,7 @@ class WaveService extends OrderBaseService { error: '', error_code: '', result: null, + ...(forceRescan ? { force_rescan: true } : {}), }); await this.setWaveStrategyQuickScanWarehouseLock(normalizedWarehouseId, taskId, { @@ -5294,6 +5296,7 @@ class WaveService extends OrderBaseService { taskId, warehouseId: normalizedWarehouseId, ...(orderIds.length > 0 ? { orderIds } : {}), + ...(forceRescan ? { forceRescan } : {}), }); const finalProgress = await this.getWaveStrategyQuickScanTaskProgress(taskId) || {}; @@ -5310,6 +5313,7 @@ class WaveService extends OrderBaseService { taskId, warehouseId: normalizedWarehouseId, ...(orderIds.length > 0 ? { orderIds } : {}), + ...(forceRescan ? { forceRescan } : {}), }).catch(error => { this.ctx.logger.error('[wave.waveStrategyQuickScan] 后台任务异常', { taskId, @@ -5396,9 +5400,10 @@ class WaveService extends OrderBaseService { * @param {number} warehouseId 仓库ID。 * @param {number} strategyVersion 当前策略版本号。 * @param {Array} [orderIds=[]] 限定扫描订单ID数组。 + * @param {boolean} [forceRescan=false] 是否强制全量重扫(忽略版本号条件)。 * @return {Object} 订单查询 where 条件。 */ - buildWaveStrategyQuickScanOrderWhere(warehouseId, strategyVersion, orderIds = []) { + buildWaveStrategyQuickScanOrderWhere(warehouseId, strategyVersion, orderIds = [], forceRescan = false) { const normalizedOrderIds = this.normalizeIdsInput(orderIds); const where = { warehouse_id: warehouseId, @@ -5407,11 +5412,14 @@ class WaveService extends OrderBaseService { intercept_status: 'none', lock_status: 'none', print_status: { [Op.ne]: 'fin' }, - [Op.or]: [ + }; + + if (!forceRescan) { + where[Op.or] = [ { wave_strategy_version: { [Op.ne]: strategyVersion } }, { wave_strategy_version: { [Op.is]: null } }, - ], - }; + ]; + } if (normalizedOrderIds.length > 0) { where.id = { @@ -5704,6 +5712,7 @@ class WaveService extends OrderBaseService { const strategyVersion = this.normalizeWaveStrategyQuickScanVersion(normalizedOptions.strategyVersion); const taskId = String(normalizedOptions.taskId || '').trim(); const orderIds = this.normalizeIdsInput(normalizedOptions.orderIds); + const forceRescan = this.normalizeBoolean(normalizedOptions.forceRescan, false); const strategyRows = await this.getWaveStrategyQuickScanStrategyRows(warehouseId); const strategyList = this.normalizeWaveStrategyQuickScanList(strategyRows); @@ -5724,7 +5733,7 @@ class WaveService extends OrderBaseService { 'sys_platform_code', 'source_platform_code', ], - where: this.buildWaveStrategyQuickScanOrderWhere(warehouseId, strategyVersion, orderIds), + where: this.buildWaveStrategyQuickScanOrderWhere(warehouseId, strategyVersion, orderIds, forceRescan), raw: true, }); @@ -5874,6 +5883,10 @@ class WaveService extends OrderBaseService { ? normalizedParams.order_ids : normalizedParams.ids; const orderIds = this.normalizeIdsInput(rawOrderIds); + const forceRescan = this.normalizeBoolean( + normalizedParams.forceRescan ?? normalizedParams.force_rescan, + false + ); const subjectConfig = await this.getWarehouseSubjectConfig(warehouseId); const strategyVersion = this.normalizeWaveStrategyQuickScanVersion( @@ -5885,6 +5898,7 @@ class WaveService extends OrderBaseService { strategyVersion, orderIds, taskId: normalizedTaskId, + forceRescan, }); if (scanResult.totalOrderCount === 0) { diff --git a/app/service/systems/order_async.js b/app/service/systems/order_async.js index 0274913..3a4643f 100644 --- a/app/service/systems/order_async.js +++ b/app/service/systems/order_async.js @@ -483,6 +483,9 @@ async function markPendingExceptionInternal(service, orderModel, orderId, wareho where: { id: orderId, warehouse_id: warehouseId, + status: { + [Op.ne]: 'cancel', + }, }, }); diff --git a/app/service/systems/order_storage_allocation.js b/app/service/systems/order_storage_allocation.js index a472fbe..b5e8e2e 100644 --- a/app/service/systems/order_storage_allocation.js +++ b/app/service/systems/order_storage_allocation.js @@ -1187,6 +1187,7 @@ class OrderStorageAllocationService extends MainService { order_item_id: toNumber(orderItem.id, 0), warehouse_id: warehouseId, storage_id: storageRow.id, + stock_id: toNumber(storageRow.stock_id, 0) || null, quantity: allocationQuantity, space_id: toNumber(storageRow.space_id, 0) || null, space_name: String(storageRow.space_name || '').trim(), @@ -1656,6 +1657,10 @@ class OrderStorageAllocationService extends MainService { sync_status: { [ctx.app.Sequelize.Op.notIn]: [ 'fin' ], }, + // 排除已取消的订单,防止已取消订单被回传 + status: { + [ctx.app.Sequelize.Op.notIn]: [ 'cancel' ], + }, }, transaction, lock: transaction.LOCK.UPDATE, diff --git a/app/service/systems/pick.js b/app/service/systems/pick.js index 9c20740..b87d322 100644 --- a/app/service/systems/pick.js +++ b/app/service/systems/pick.js @@ -137,7 +137,7 @@ class PickSystemService extends Service { [this.app.Sequelize.Op.in]: orderItemIds, }, }, - attributes: [ 'id', 'item_code', 'item_name', 'stock_id', 'plan_qty', 'item_snapshot' ], + attributes: [ 'id', 'item_code', 'item_name', 'stock_id', 'plan_qty', 'item_snapshot', 'owner_code' ], raw: true, }); @@ -323,6 +323,10 @@ class PickSystemService extends Service { total_qty: 0, box_allocations: [], details: [], + store_id: detail.store_id != null ? Number(detail.store_id) : 0, + owner_code: String(detail.owner_code || '').trim(), + store_remark: String(detail.store_remark || '').trim(), + stock: detail.stock || null, }); } const groupItem = groupMap.get(groupKey); @@ -495,6 +499,9 @@ class PickSystemService extends Service { stock_id: Number(groupItem && groupItem.stock_id || 0), total_qty: Number(groupItem && groupItem.total_qty || 0), box_allocations: boxAllocations, + store_id: groupItem.store_id != null ? Number(groupItem.store_id) : 0, + owner_code: String(groupItem.owner_code || '').trim(), + store_remark: String(groupItem.store_remark || '').trim(), }; }); @@ -1196,6 +1203,36 @@ class PickSystemService extends Service { } } + // 批量查询货主备注名(wms_store_warehouse.store_remask),按 store_id 映射 + const storeRemarkMap = new Map(); + if (stockDetailMap.size > 0 && ctx.model && ctx.model.StoreWarehouse) { + const storeIdsForRemark = [ ...new Set( + [ ...stockDetailMap.values() ] + .map(detail => Number(detail.store_id || 0)) + .filter(id => id > 0) + ) ]; + if (storeIdsForRemark.length > 0) { + try { + const swRows = await ctx.model.StoreWarehouse.findAll({ + where: { + store_id: { [this.app.Sequelize.Op.in]: storeIdsForRemark }, + warehouse_id: warehouseId, + }, + attributes: [ 'store_id', 'store_remask' ], + raw: true, + }); + for (const sw of (Array.isArray(swRows) ? swRows : [])) { + const sid = Number(sw.store_id || 0); + if (sid > 0 && !storeRemarkMap.has(sid)) { + storeRemarkMap.set(sid, String(sw.store_remask || '').trim()); + } + } + } catch (remarkError) { + ctx.logger.warn(`[pick.wavePickTaskDetail] 查询货主备注失败: ${remarkError.message}`); + } + } + } + const normalizedBoxRows = Array.isArray(boxRows) ? boxRows : []; const boxMapByNo = new Map(normalizedBoxRows .map(row => [ Number(row && row.box_no || 0), row ]) @@ -1221,7 +1258,17 @@ class PickSystemService extends Service { stock_unit: String(itemSnapshot.stock_unit || '').trim(), barcodes: [], image_url: [], + store_id: 0, }; + // 确保 owner_code 在 stock 对象上(getStockDetails 不含此字段,需从 order_items 补) + if (!stock.owner_code) { + stock.owner_code = String(orderItemRow.owner_code || '').trim(); + } + // 确保 store_remark 在 stock 对象上(getStockDetails 不含此字段,需从 wms_store_warehouse 补) + const stockStoreId = stock.store_id != null ? Number(stock.store_id) : 0; + if (!stock.store_remark) { + stock.store_remark = storeRemarkMap.get(stockStoreId) || ''; + } return { order_id: Number(row && row.order_id || 0), @@ -1243,6 +1290,9 @@ class PickSystemService extends Service { stock_id: stockId, plan_qty: Number(orderItemRow.plan_qty || 0), item_snapshot: orderItemRow.item_snapshot || null, + store_id: stockStoreId, + owner_code: String(stock.owner_code || '').trim(), + store_remark: String(stock.store_remark || '').trim(), stock, }; }); From 81350c0d6b11d30fda1f57a6536064a5346241d5 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 27 Jul 2026 03:49:27 +0800 Subject: [PATCH 131/550] =?UTF-8?q?fix:=20=E5=AE=9A=E6=97=B6=E4=BB=BB?= =?UTF-8?q?=E5=8A=A1=E5=90=8C=E6=AD=A5=E6=97=A5=E5=BF=97=20+=20=E5=9F=BA?= =?UTF-8?q?=E7=A1=80=E8=AE=BE=E6=96=BD=E4=BF=AE=E5=A4=8D=20+=20=E6=9D=83?= =?UTF-8?q?=E9=99=90=E8=BF=81=E7=A7=BB=EF=BC=88=E6=94=B6=E5=B0=BE=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 【定时任务】sync_outbound_orders_to_delivery: 执行日志写缓存 + 错误详情提取(parent/validation) 【基础设施】system.js: snake_case→camelCase 服务路由转换(兼容 express_interface 等) 【看板】dashboard: queryWarehouseStats 支持 storeId 货主维度过滤 【订单基类】order/base: getOrderModel 兼容无上下文时传入 warehouseId(货主侧场景) 【库存】inventory: 全量移库软删除→硬删除(force destroy)释放唯一键 + 唯一约束/校验错误友好提示 【快递平台】express_platform: KS(快手)平台 receiver.phone 不传(平台要求) 【迁移】delivery 自增起点 + supervisor CS 权限修复 --- .../sync_outbound_orders_to_delivery.js | 97 ++++++++++++++++++- app/service/system.js | 6 +- app/service/systemMethods/dashboard.js | 11 ++- app/service/systemMethods/order/base.js | 51 ++++++++-- app/service/systemMethods/order/index.js | 2 +- .../systemMethods/order/pendingOrder.js | 3 +- app/service/systemMethods/order/print.js | 2 +- app/service/systems/express_platform.js | 4 +- app/service/systems/location.js | 2 +- app/service/systems/location_zone.js | 2 +- app/service/systems/order_export.js | 4 +- app/service/systems/storage/inventory.js | 33 ++++--- ...to-increment-wms-order-delivery-1000028.js | 18 ++++ ...718170000-fix-supervisor-cs-permissions.js | 57 +++++++++++ 14 files changed, 253 insertions(+), 39 deletions(-) create mode 100644 database/migrations/20260713150000-set-auto-increment-wms-order-delivery-1000028.js create mode 100644 database/migrations/20260718170000-fix-supervisor-cs-permissions.js diff --git a/app/schedule/sync_outbound_orders_to_delivery.js b/app/schedule/sync_outbound_orders_to_delivery.js index 804fa8d..5386369 100644 --- a/app/schedule/sync_outbound_orders_to_delivery.js +++ b/app/schedule/sync_outbound_orders_to_delivery.js @@ -2,6 +2,69 @@ const SHORT_TASK_QUERY_TIMEOUT_MS = 15000; const SHORT_TASK_EXECUTION_TIMEOUT_MS = 30000; +const EXECUTION_LOG_CACHE_KEY = 'schedule:sync_outbound_orders_to_delivery:last_execution'; +const EXECUTION_LOG_CACHE_TTL = 300; // 5 分钟 + +/** + * 将本次执行日志写入缓存。 + * + * @param {Object} ctx Egg 上下文。 + * @param {Object} logEntry 日志条目。 + * @return {Promise} + */ +async function writeExecutionLogToCache(ctx, logEntry) { + try { + if (ctx.app && typeof ctx.app.setCacheAsync === 'function') { + await ctx.app.setCacheAsync(EXECUTION_LOG_CACHE_KEY, logEntry, EXECUTION_LOG_CACHE_TTL); + } + } catch (err) { + // 缓存写入失败不影响主流程 + ctx.logger.warn(`[sync-outbound-orders-to-delivery] 写入执行日志缓存失败: ${err.message}`); + } +} + +/** + * 提取错误详情,方便定位问题位置。 + * + * @param {Error} error 错误对象。 + * @return {Object} 错误详情。 + */ +function extractErrorDetail(error) { + if (!error) return {}; + + const detail = { + name: error.name || '', + message: error.message || '', + code: error.code || '', + }; + + // Sequelize 父级错误(通常包含 SQL 信息) + if (error.parent) { + detail.parent = { + name: error.parent.name || '', + message: error.parent.message || '', + code: error.parent.code || '', + sql: error.parent.sql || '', + }; + } + + // SequelizeValidationError 的 fields 列表 + if (Array.isArray(error.errors)) { + detail.validation_errors = error.errors.map(e => ({ + message: e.message, + type: e.type, + path: e.path, + value: String(e.value ?? ''), + })); + } + + // 堆栈前 3 行(定位调用链) + if (error.stack) { + detail.stack_top = error.stack.split('\n').slice(0, 4).map(s => s.trim()); + } + + return detail; +} /** * 每 1 分钟在单 worker 中同步一次正常出库订单到配送表。 @@ -31,21 +94,51 @@ module.exports = { ctx.app._syncOutboundOrdersToDeliveryRunning = true; + const startedAt = Date.now(); + let status = 'success'; + let errorMessage = ''; + let errorDetail = null; + let result = null; + try { - const result = await ctx.service.systems.orderDeliveryMigration.syncOutboundOrdersToDelivery({ + result = await ctx.service.systems.orderDeliveryMigration.syncOutboundOrdersToDelivery({ queryTimeoutMs: SHORT_TASK_QUERY_TIMEOUT_MS, executionTimeoutMs: SHORT_TASK_EXECUTION_TIMEOUT_MS, }); if (result && result.retryableFailure) { + status = 'retryable_failure'; + errorMessage = `retryableFailureType=${result.retryableFailureType}, timeoutCount=${result.timeoutCount || 0}`; ctx.logger.warn(`[sync-outbound-orders-to-delivery] 正常迁移遇到 ${result.retryableFailureType},已标记 ${result.timeoutCount || 0} 条订单为出库超时`); } else if (result && result.totalCreated > 0) { ctx.logger.info(`[sync-outbound-orders-to-delivery] 同步 ${result.totalCreated} 条已出库订单`); } + + // 始终输出汇总日志(含 0 条场景,确认定时任务在跑) + ctx.logger.info(`[sync-outbound-orders-to-delivery] 本轮完成 selected=${result ? result.totalSelected : 0} created=${result ? result.totalCreated : 0} skipped=${result ? result.totalSkipped : 0} timeout=${result ? result.totalTimeout : 0}`); } catch (error) { - ctx.logger.error(`[sync-outbound-orders-to-delivery] 同步失败: ${error.message}`); + status = 'error'; + errorMessage = error.message; + errorDetail = extractErrorDetail(error); + ctx.logger.error(`[sync-outbound-orders-to-delivery] 同步失败: ${error.message}`, errorDetail); } finally { ctx.app._syncOutboundOrdersToDeliveryRunning = false; } + + // 写入执行日志到缓存 + const logEntry = { + executed_at: new Date().toISOString(), + duration_ms: Date.now() - startedAt, + status, + error_message: errorMessage, + error_detail: errorDetail, + total_selected: result ? result.totalSelected : 0, + total_created: result ? result.totalCreated : 0, + total_skipped: result ? result.totalSkipped : 0, + total_timeout: result ? result.totalTimeout : 0, + warehouse_ids: result ? result.warehouseIds : [], + }; + await writeExecutionLogToCache(ctx, logEntry); + ctx.logger.info(`[sync-outbound-orders-to-delivery] 执行日志已写入缓存 key=${EXECUTION_LOG_CACHE_KEY}`); }, }; diff --git a/app/service/system.js b/app/service/system.js index 41834a0..a74324b 100644 --- a/app/service/system.js +++ b/app/service/system.js @@ -14,8 +14,10 @@ class systemService extends Service { const classs = servicePath.split('.'); let systemMethods = this.ctx.service.systemMethods; for (let i = 0; i < classs.length; i++) { - const className = classs[i]; - systemMethods = systemMethods[className]; + const rawClassName = classs[i]; + // Egg.js 将文件名 snake_case 自动转为 camelCase,需做对应转换 + const camelName = rawClassName.replace(/_([a-z])/g, (_, c) => c.toUpperCase()); + systemMethods = systemMethods[camelName] || systemMethods[rawClassName]; } // 检查服务是否存在 if (!systemMethods) { diff --git a/app/service/systemMethods/dashboard.js b/app/service/systemMethods/dashboard.js index f78ac3e..5b630c7 100644 --- a/app/service/systemMethods/dashboard.js +++ b/app/service/systemMethods/dashboard.js @@ -47,11 +47,11 @@ class dashboardService extends MainService { } // 跨仓并行查询并汇总 - const results = await Promise.all(warehouseIds.map(wid => this.queryWarehouseStats(wid).catch(() => null))); + const results = await Promise.all(warehouseIds.map(wid => this.queryWarehouseStats(wid, storeId).catch(() => null))); return this.success('ok', this.mergeStoreStats(results.filter(Boolean))); } - async queryWarehouseStats(warehouseId) { + async queryWarehouseStats(warehouseId, storeId = null) { const { ctx } = this; const model = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); const { Sequelize } = ctx.app; @@ -61,9 +61,10 @@ class dashboardService extends MainService { step: { [Op.in]: [ 1, 2, 3 ] }, outbound_status: { [Op.ne]: 'padding' }, status: { [Op.ne]: 'cancel' }, - store_id: { [Op.in]: [] }, // 占位,后续填充 }; - delete pendingBase.store_id; + if (storeId) { + pendingBase.store_id = storeId; + } const now = new Date(); const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate()); @@ -89,7 +90,7 @@ class dashboardService extends MainService { model.count({ where: { ...pendingBase, print_status: 'none' } }), model.count({ where: { ...pendingBase, pick_status: 'none' } }), model.count({ where: { ...pendingBase, outbound_status: { [Op.ne]: 'fin' } } }), - model.count({ where: { step: 4, outbound_status: 'fin', status: { [Op.ne]: 'cancel' }, delivery_time: { [Op.gte]: todayStart, [Op.lt]: todayEnd } } }), + model.count({ where: { step: 4, outbound_status: 'fin', status: { [Op.ne]: 'cancel' }, delivery_time: { [Op.gte]: todayStart, [Op.lt]: todayEnd }, ...(storeId ? { store_id: storeId } : {}) } }), model.count({ where: { ...pendingBase, intercept_status: { [Op.not]: null, [Op.ne]: 'none' } } }), model.count({ where: { ...pendingBase, step: 3 } }), ]); diff --git a/app/service/systemMethods/order/base.js b/app/service/systemMethods/order/base.js index d9abc80..7f7c006 100644 --- a/app/service/systemMethods/order/base.js +++ b/app/service/systemMethods/order/base.js @@ -581,13 +581,24 @@ class OrderBaseService extends MainService { async getOrderModel(moduleName = 'order', warehouseId = null) { const { ctx } = this; const config = this.getModuleConfig(moduleName); - const contextWarehouseId = this.getWarehouseId(); + let contextWarehouseId = this.getWarehouseId(); - if (contextWarehouseId === null || contextWarehouseId === undefined || contextWarehouseId === '') { + const hasContextWarehouseId = contextWarehouseId !== null + && contextWarehouseId !== undefined + && contextWarehouseId !== ''; + const hasParamWarehouseId = warehouseId !== null + && warehouseId !== undefined + && warehouseId !== ''; + + if (!hasContextWarehouseId && !hasParamWarehouseId) { throw new Error('缺少当前用户仓库上下文 store_id'); } - if (warehouseId !== null && warehouseId !== undefined && warehouseId !== '' + if (!hasContextWarehouseId) { + contextWarehouseId = warehouseId; + } + + if (hasContextWarehouseId && hasParamWarehouseId && String(warehouseId) !== String(contextWarehouseId)) { throw new Error('订单工作台仓库ID必须来自当前用户上下文 store_id,禁止传入外部仓库ID。'); } @@ -646,15 +657,26 @@ class OrderBaseService extends MainService { */ async getOrderModelByTableType(tableType = 'current', warehouseId = this.getWarehouseId()) { const { ctx } = this; - const contextWarehouseId = this.getWarehouseId(); + let contextWarehouseId = this.getWarehouseId(); const normalizedTableType = this.resolveOrderTableType({ tableType }); const actualWarehouseId = warehouseId ?? contextWarehouseId; - if (contextWarehouseId === null || contextWarehouseId === undefined || contextWarehouseId === '') { + const hasContextWarehouseId = contextWarehouseId !== null + && contextWarehouseId !== undefined + && contextWarehouseId !== ''; + const hasActualWarehouseId = actualWarehouseId !== null + && actualWarehouseId !== undefined + && actualWarehouseId !== ''; + + if (!hasContextWarehouseId && !hasActualWarehouseId) { throw new Error('缺少当前用户仓库上下文 store_id'); } - if (actualWarehouseId !== null && actualWarehouseId !== undefined && actualWarehouseId !== '' + if (!hasContextWarehouseId) { + contextWarehouseId = actualWarehouseId; + } + + if (hasContextWarehouseId && hasActualWarehouseId && String(actualWarehouseId) !== String(contextWarehouseId)) { throw new Error('订单工作台仓库ID必须来自当前用户上下文 store_id,禁止传入外部仓库ID。'); } @@ -680,15 +702,26 @@ class OrderBaseService extends MainService { */ async getOrderItemsModelByTableType(tableType = 'current', warehouseId = this.getWarehouseId()) { const { ctx } = this; - const contextWarehouseId = this.getWarehouseId(); + let contextWarehouseId = this.getWarehouseId(); const normalizedTableType = this.resolveOrderTableType({ tableType }); const actualWarehouseId = warehouseId ?? contextWarehouseId; - if (contextWarehouseId === null || contextWarehouseId === undefined || contextWarehouseId === '') { + const hasContextWarehouseId = contextWarehouseId !== null + && contextWarehouseId !== undefined + && contextWarehouseId !== ''; + const hasActualWarehouseId = actualWarehouseId !== null + && actualWarehouseId !== undefined + && actualWarehouseId !== ''; + + if (!hasContextWarehouseId && !hasActualWarehouseId) { throw new Error('缺少当前用户仓库上下文 store_id'); } - if (actualWarehouseId !== null && actualWarehouseId !== undefined && actualWarehouseId !== '' + if (!hasContextWarehouseId) { + contextWarehouseId = actualWarehouseId; + } + + if (hasContextWarehouseId && hasActualWarehouseId && String(actualWarehouseId) !== String(contextWarehouseId)) { throw new Error('订单工作台仓库ID必须来自当前用户上下文 store_id,禁止传入外部仓库ID。'); } diff --git a/app/service/systemMethods/order/index.js b/app/service/systemMethods/order/index.js index 31153ce..278e43a 100644 --- a/app/service/systemMethods/order/index.js +++ b/app/service/systemMethods/order/index.js @@ -436,7 +436,7 @@ class OrderIndexService extends OrderBaseService { * @param {Object} data 请求体。 * @param {string} [data.waybill_code] 运单号,多运单场景或运单号模式必填。 * @param {number|string} data.order_id 订单ID,传 0 时切换为运单号模式。 - * @param {number|string} data.weighing_weight 称重重量(kg)。 + * @param {number|string} data.weighing_weight 称重重量(g)。 * @return {Promise} 统一成功/失败结构。 * 订单模式单订单:{data: {order_id, waybill_code, weighing_weight}}; * 订单模式团购批量:{data: {wave_id, wave_no, weighing_weight, total_weight, split_count, splits, store_name, sys_logistics_name}}; diff --git a/app/service/systemMethods/order/pendingOrder.js b/app/service/systemMethods/order/pendingOrder.js index aa9bf57..ebfa97a 100644 --- a/app/service/systemMethods/order/pendingOrder.js +++ b/app/service/systemMethods/order/pendingOrder.js @@ -3191,7 +3191,7 @@ class PendingOrderService extends OrderBaseService { Authorization: `Bearer ${apiKey}`, }, data: { - model: 'deepseek-chat', + model: 'deepseek-v4-pro', messages: [ { role: 'system', content: '你是一个专业的地址解析助手,只返回JSON格式结果。' }, { role: 'user', content: prompt }, @@ -3207,6 +3207,7 @@ class PendingOrderService extends OrderBaseService { } const content = result.data.choices?.[0]?.message?.content || ''; + this.ctx.logger.info('[parseAddress] DeepSeek原始返回content: %s', content); // 清理可能的 markdown 代码块标记 let jsonStr = content.trim(); diff --git a/app/service/systemMethods/order/print.js b/app/service/systemMethods/order/print.js index d86af2c..8db847b 100644 --- a/app/service/systemMethods/order/print.js +++ b/app/service/systemMethods/order/print.js @@ -12,7 +12,7 @@ class OrderPrintService extends OrderBaseService { super(ctx); const _noNeedLogin = ''; const _noNeedRight = 'getWavePrintData,getWavePlatformPrintData,unlockWavePlatformPrintDataByGroup,getOrderPrintData'; - const _noNeedLog = 'getWavePrintData,getWavePlatformPrintData,unlockWavePlatformPrintDataByGroup,getOrderPrintData'; + const _noNeedLog = 'getWavePrintData,unlockWavePlatformPrintDataByGroup,getOrderPrintData'; const _noNeedAuth = 'getWavePrintData,getWavePlatformPrintData,unlockWavePlatformPrintDataByGroup,getOrderPrintData'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } diff --git a/app/service/systems/express_platform.js b/app/service/systems/express_platform.js index 400376c..bd2ccc1 100644 --- a/app/service/systems/express_platform.js +++ b/app/service/systems/express_platform.js @@ -708,7 +708,7 @@ class ExpressPlatformService extends MainService { procode: order.procode || '普通商品', codpaymoney: order.ar_amount ?? null, packagemoney: order.item_amount ?? null, - weight: Number(order.items_weight) || 0, + weight: Number(order.items_weight) || 0, // 单位 g,需确认 PolyAPI 期望单位 supporpaymoney: order.total_amount ?? null, length: Number(order.length) || 0, width: Number(order.width) || 0, @@ -743,7 +743,7 @@ class ExpressPlatformService extends MainService { receiver: { name: order.name || '', company: order.company || '', - phone: order.mobile || order.tel || '', + phone: order.sys_platform_code === 'KS' ? undefined : (order.mobile || order.tel || ''), mobile: order.mobile || order.tel || '', country: order.country_code || 'CN', province: order.province || '', diff --git a/app/service/systems/location.js b/app/service/systems/location.js index 30d32cd..f4d57a8 100644 --- a/app/service/systems/location.js +++ b/app/service/systems/location.js @@ -76,7 +76,7 @@ class LocationService extends Service { width: cellWidth, height: cellHeight, volume: cellLength * cellWidth * cellHeight / 1000000, // cm³转m³ - max_weight: 100, // 默认100kg + max_weight: 100000, // 默认100000g space_status: 'AVAILABLE', is_enabled: true, relative_x: relativeX, diff --git a/app/service/systems/location_zone.js b/app/service/systems/location_zone.js index 6d7515b..4e04ff8 100644 --- a/app/service/systems/location_zone.js +++ b/app/service/systems/location_zone.js @@ -1115,7 +1115,7 @@ class LocationZoneService extends Service { width: cellWidth, height: cellHeight, volume: cellLength * cellWidth * cellHeight / 1000000, - max_weight: 100, + max_weight: 100000, space_status: 'AVAILABLE', is_enabled: true, relative_x: relativeX, diff --git a/app/service/systems/order_export.js b/app/service/systems/order_export.js index 7ae2e2d..2c24b8c 100644 --- a/app/service/systems/order_export.js +++ b/app/service/systems/order_export.js @@ -50,7 +50,7 @@ const ORDER_EXPORT_COLUMNS = Object.freeze([ { header: '商品种数', key: 'items_count', width: 12 }, { header: '商品件数', key: 'items_total', width: 12 }, { header: '商品重量', key: 'items_weight', width: 12 }, - { header: '称重重量(kg)', key: 'weighing_weight', width: 14 }, + { header: '称重重量(g)', key: 'weighing_weight', width: 14 }, { header: '订单金额', key: 'total_amount', width: 14 }, { header: '实收金额', key: 'got_amount', width: 14 }, { header: '创建时间', key: 'create_at', width: 20 }, @@ -99,7 +99,7 @@ const ORDER_EXPORT_ITEM_COLUMNS = Object.freeze([ { header: '商品种数', key: 'items_count', width: 12 }, { header: '商品件数', key: 'items_total', width: 12 }, { header: '商品重量', key: 'items_weight', width: 12 }, - { header: '称重重量(kg)', key: 'weighing_weight', width: 14 }, + { header: '称重重量(g)', key: 'weighing_weight', width: 14 }, { header: '订单金额', key: 'total_amount', width: 14 }, { header: '实收金额', key: 'got_amount', width: 14 }, { header: '创建时间', key: 'create_at', width: 20 }, diff --git a/app/service/systems/storage/inventory.js b/app/service/systems/storage/inventory.js index b1e225c..9fb6931 100644 --- a/app/service/systems/storage/inventory.js +++ b/app/service/systems/storage/inventory.js @@ -465,13 +465,10 @@ class InventoryService extends Service { }); if (isFullTransfer) { - // 全量移库且合并:删除原记录 - await ctx.model.Storage.update({ - is_enabled: 0, - delete_at: new Date(), - updated_at: new Date(), - }, { + // 全量移库且合并:硬删除原记录,释放唯一键 + await ctx.model.Storage.destroy({ where: { id: storageId }, + force: true, transaction, }); srcSpaceDelta.qtyDelta -= srcRecord.quantity; @@ -930,13 +927,10 @@ class InventoryService extends Service { }); if (isFullTransfer) { - // 全量:软删除原记录 - await ctx.model.Storage.update({ - is_enabled: 0, - delete_at: new Date(), - updated_at: new Date(), - }, { + // 全量:硬删除原记录,释放唯一键 + await ctx.model.Storage.destroy({ where: { id: srcRecord.id }, + force: true, transaction, }); } else { @@ -1157,6 +1151,21 @@ class InventoryService extends Service { return { code: 409, message: '库存记录被锁定,请稍后重试', data: null }; } + if (error.name === 'SequelizeUniqueConstraintError') { + return { + code: 409, + message: '目标库位已存在该商品同批次同类型的库存记录,合并移库失败,请稍后重试或使用 transferLocation 逐条移库', + data: null, + }; + } + + if (error.name === 'SequelizeValidationError') { + ctx.logger.error('[inventory.transferByProduct] Sequelize 校验失败', { + errors: error.errors?.map(e => ({ path: e.path, message: e.message, value: e.value })), + }); + return { code: 400, message: `数据校验失败: ${error.errors?.map(e => e.message).join('; ') || error.message}`, data: null }; + } + throw error; } } diff --git a/database/migrations/20260713150000-set-auto-increment-wms-order-delivery-1000028.js b/database/migrations/20260713150000-set-auto-increment-wms-order-delivery-1000028.js new file mode 100644 index 0000000..14e8da6 --- /dev/null +++ b/database/migrations/20260713150000-set-auto-increment-wms-order-delivery-1000028.js @@ -0,0 +1,18 @@ +'use strict'; + +module.exports = { + async up(queryInterface) { + // 紧急修复:将 wms_order_delivery_1000028 自增值提升至 15000+ + // 原因:表重建后 AUTO_INCREMENT 被重置为 151,与历史水位差距过大 + await queryInterface.sequelize.query( + "ALTER TABLE wms_order_delivery_1000028 AUTO_INCREMENT = 15000" + ); + }, + + async down(queryInterface) { + // 回滚:重置为默认(MAX(id)+1) + await queryInterface.sequelize.query( + 'ALTER TABLE wms_order_delivery_1000028 AUTO_INCREMENT = 1' + ); + }, +}; diff --git a/database/migrations/20260718170000-fix-supervisor-cs-permissions.js b/database/migrations/20260718170000-fix-supervisor-cs-permissions.js new file mode 100644 index 0000000..9f201d5 --- /dev/null +++ b/database/migrations/20260718170000-fix-supervisor-cs-permissions.js @@ -0,0 +1,57 @@ +'use strict'; + +/** + * 修复:客服组-主管 补充缺失权限,使其不低于下属(客服组-员工) + * + * 背景: + * 迁移 20260608033847 的设计意图是「客服组-主管」与「客服组-员工」权限一致。 + * 但后续新增权限时,主管遗漏了 5 个权限,导致员工(162个) > 主管(159个) 的越级现象。 + * + * 变更: + * - 客服组-主管 (id=28) 补充 [62, 63, 363, 396, 397] 共 5 个权限 + * - 补后:主管 164 个权限 > 员工 162 个权限(主管额外保留 309, 392) + * + * 补充权限明细: + * | ID | 路径 | 名称 | 类型 | + * |-----|-----------------------------------------------|-------------|-----------| + * | 62 | stock.saveWarehouseStock | 保存商品资料 | api | + * | 63 | stock.saveWarehouseStockBarcode | 修改商品条码 | api | + * | 363 | storeWarehouse.store.queryPrintQuantityLogs | 货主面单余额 | api | + * | 396 | shipperSigning | 外部仓库 | web_pages | + * | 397 | storeWarehouse.store.confirmSign | 签约确定 | api | + */ + +const TABLE = 'wms_role'; +const ROLE_ID = 28; + +const NEW_PERMISSIONS = '[1,4,8,9,11,12,13,14,15,17,18,19,20,21,22,24,25,26,27,29,30,38,39,40,41,43,44,45,46,47,48,49,50,54,62,63,72,73,74,75,76,77,78,79,80,81,82,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,244,254,255,256,278,281,283,290,291,292,293,294,295,296,297,298,299,300,303,304,305,306,307,308,309,333,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,356,357,361,363,367,368,369,370,371,372,373,374,375,376,377,379,380,381,382,383,384,386,387,388,389,390,391,392,396,397,416,417,418,420,421,422,424,425,426,427,428,429,430,431,432]'; + +const OLD_PERMISSIONS = '[1,4,8,9,11,12,13,14,15,17,18,19,20,21,22,24,25,26,27,29,30,38,39,40,41,43,44,45,46,47,48,49,50,54,72,73,74,75,76,77,78,79,80,81,82,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,244,254,255,256,278,281,283,290,291,292,293,294,295,296,297,298,299,300,303,304,305,306,307,308,309,333,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,356,357,361,367,368,369,370,371,372,373,374,375,376,377,379,380,381,382,383,384,386,387,388,389,390,391,392,416,417,418,420,421,422,424,425,426,427,428,429,430,431,432]'; + +/** + * @param {import('sequelize').QueryInterface} queryInterface + */ +module.exports.up = async queryInterface => { + const [result] = await queryInterface.sequelize.query( + `UPDATE \`${TABLE}\` SET permissions = :permissions, updated_at = NOW() + WHERE id = :id AND is_system = 1`, + { replacements: { id: ROLE_ID, permissions: NEW_PERMISSIONS } } + ); + + const affected = result?.affectedRows ?? result?.rowCount ?? result?.changedRows ?? 0; + console.log(`[Migration] 客服组-主管(id=${ROLE_ID}) 权限补充:补充 5 个权限,实际更新 ${affected} 行`); +}; + +/** + * @param {import('sequelize').QueryInterface} queryInterface + */ +module.exports.down = async queryInterface => { + const [result] = await queryInterface.sequelize.query( + `UPDATE \`${TABLE}\` SET permissions = :permissions, updated_at = NOW() + WHERE id = :id AND is_system = 1`, + { replacements: { id: ROLE_ID, permissions: OLD_PERMISSIONS } } + ); + + const affected = result?.affectedRows ?? result?.rowCount ?? result?.changedRows ?? 0; + console.log(`[Migration] 客服组-主管(id=${ROLE_ID}) 权限回滚:实际回滚 ${affected} 行`); +}; From f9fbf96ce515b297fa50945548ec8d1807b7f84f Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 27 Jul 2026 17:46:03 +0800 Subject: [PATCH 132/550] =?UTF-8?q?feat(order.packing):=20=E6=96=B0?= =?UTF-8?q?=E5=A2=9E=20has=5Fvideo/video=5Fenable=20=E5=BD=95=E5=83=8F?= =?UTF-8?q?=E7=AD=9B=E9=80=89=E4=B8=8E=E5=93=8D=E5=BA=94=E5=AD=97=E6=AE=B5?= =?UTF-8?q?=EF=BC=9B=E8=BF=90=E5=8D=95=E5=8F=B7=E6=94=B9=E4=B8=BA=20expres?= =?UTF-8?q?s=20=E8=A1=A8=E8=A7=A3=E6=9E=90=EF=BC=9BsetEndTime=20=E5=A2=9E?= =?UTF-8?q?=E5=8A=A0=E5=BC=80=E5=A7=8B=E6=97=B6=E9=97=B4=E6=A0=A1=E9=AA=8C?= =?UTF-8?q?=EF=BC=9BforceRecord=20=E4=BC=98=E5=8C=96=E9=94=99=E8=AF=AF?= =?UTF-8?q?=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/systems/order_packing.js | 102 ++++++++++++++++++++++----- methods/system.json | 8 ++- 2 files changed, 91 insertions(+), 19 deletions(-) diff --git a/app/service/systems/order_packing.js b/app/service/systems/order_packing.js index 370f01a..61cc6df 100644 --- a/app/service/systems/order_packing.js +++ b/app/service/systems/order_packing.js @@ -48,7 +48,7 @@ class OrderPackingService extends Service { * @param {Object} where 筛选条件对象 * @param {Object} [where.status] 任务状态:0=待处理 1=打包中 2=已完成 3=异常 * @param {Object} [where.pack_mode] 打包模式:1=散单 2=团购 - * @param {Object} [where.waybill_code] 运单号(模糊匹配) + * @param {Object} [where.waybill_code] 运单号(通过 wms_order_express 解析 order_id 后过滤,支持 eq/like) * @param {Object} [where.wave_no] 波次号(模糊匹配) * @param {Object} [where.order_id] 订单ID(精确匹配) * @param {Object} [where.workbench_id] 工作台ID(精确匹配) @@ -98,11 +98,33 @@ class OrderPackingService extends Service { } } - // 运单号模糊匹配 + // 运单号筛选:通过 wms_order_express 表解析 order_id,再按 order_id 过滤(wms_pack_task.waybill_code 通常为空) if (where.waybill_code) { const waybillValue = where.waybill_code?.value ?? where.waybill_code; + const waybillOperator = (where.waybill_code?.operator || 'like').toLowerCase(); if (waybillValue && String(waybillValue).trim()) { - queryWhere.waybill_code = { [Op.like]: `%${String(waybillValue).trim()}%` }; + const trimmedValue = String(waybillValue).trim(); + const expressWhere = { + warehouse_id: warehouseId, + delete_at: null, + }; + if (waybillOperator === 'eq') { + expressWhere.waybill_code = trimmedValue; + } else { + expressWhere.waybill_code = { [Op.like]: `%${trimmedValue}%` }; + } + const expressRecords = await ctx.model.OrderExpress.findAll({ + where: expressWhere, + attributes: [ 'order_id' ], + raw: true, + }); + const matchedOrderIds = [ ...new Set(expressRecords.map(r => r.order_id).filter(Boolean)) ]; + if (matchedOrderIds.length > 0) { + queryWhere.order_id = { [Op.in]: matchedOrderIds }; + } else { + // 无匹配运单号 → 强制返回空结果 + queryWhere.id = -1; + } } } @@ -250,6 +272,34 @@ class OrderPackingService extends Service { } } + // has_video 筛选:1=有视频 2=无视频 + if (where.has_video !== undefined && where.has_video !== null) { + const hasVideoValue = Number(where.has_video?.value ?? where.has_video); + if (hasVideoValue === 1) { + queryWhere[Op.and] = [ ...(queryWhere[Op.and] || []), + app.Sequelize.literal('EXISTS (SELECT 1 FROM wms_pack_task_video WHERE pack_task_id = pack_task.id AND deleted_at IS NULL)'), + ]; + } else if (hasVideoValue === 2) { + queryWhere[Op.and] = [ ...(queryWhere[Op.and] || []), + app.Sequelize.literal('NOT EXISTS (SELECT 1 FROM wms_pack_task_video WHERE pack_task_id = pack_task.id AND deleted_at IS NULL)'), + ]; + } + } + + // video_enable 筛选:1=录像可用 2=录像不可用 + if (where.video_enable !== undefined && where.video_enable !== null) { + const videoEnableValue = Number(where.video_enable?.value ?? where.video_enable); + if (videoEnableValue === 1) { + queryWhere[Op.and] = [ ...(queryWhere[Op.and] || []), + app.Sequelize.literal("EXISTS (SELECT 1 FROM wms_pack_task_video WHERE pack_task_id = pack_task.id AND deleted_at IS NULL AND video_url != '' AND status != 'failed')"), + ]; + } else if (videoEnableValue === 2) { + queryWhere[Op.and] = [ ...(queryWhere[Op.and] || []), + app.Sequelize.literal("NOT EXISTS (SELECT 1 FROM wms_pack_task_video WHERE pack_task_id = pack_task.id AND deleted_at IS NULL AND video_url != '' AND status != 'failed')"), + ]; + } + } + // 开始打包时间范围 if (where.start_time_start) { const startTimeStart = where.start_time_start?.value ?? where.start_time_start; @@ -309,12 +359,15 @@ class OrderPackingService extends Service { const recordingComputerId = await this._getRecordingComputerId(warehouseId); const list = rows.map(row => { const plain = row.get({ plain: true }); + const rawVideos = plain.videos || []; return { ...plain, workbench_name: plain.workbench?.name || null, workbench_type: plain.workbench?.type || null, workbench_barcode: plain.workbench?.barcode || null, - videos: (plain.videos || []).map(v => ({ + has_video: rawVideos.length > 0 ? 1 : 2, + video_enable: rawVideos.some(v => v.video_url && v.status !== 'failed') ? 1 : 2, + videos: rawVideos.map(v => ({ id: v.id, video_url: this._buildVideoUrl(warehouseId, recordingComputerId, v.video_url), status: v.status || null, @@ -411,12 +464,15 @@ class OrderPackingService extends Service { const plain = record.get({ plain: true }); const recordingComputerId = await this._getRecordingComputerId(warehouseId); + const rawVideos = plain.videos || []; const data = { ...plain, workbench_name: plain.workbench?.name || null, workbench_type: plain.workbench?.type || null, workbench_barcode: plain.workbench?.barcode || null, - videos: (plain.videos || []).map(v => ({ + has_video: rawVideos.length > 0 ? 1 : 2, + video_enable: rawVideos.some(v => v.video_url && v.status !== 'failed') ? 1 : 2, + videos: rawVideos.map(v => ({ id: v.id, video_url: this._buildVideoUrl(warehouseId, recordingComputerId, v.video_url), status: v.status || null, @@ -472,7 +528,14 @@ class OrderPackingService extends Service { return { code: 404, message: '打包任务不存在或无权访问', data: null }; } - const updates = { end_time: new Date(end_time) }; + const newEndTime = new Date(end_time); + + // 结束时间不能早于开始时间 + if (record.start_time && newEndTime < new Date(record.start_time)) { + return { code: 400, message: '结束时间不能早于开始时间', data: null }; + } + + const updates = { end_time: newEndTime }; // 若任务状态不是已完成(2),同步更新为已完成 if (record.status !== 2) { @@ -546,30 +609,37 @@ class OrderPackingService extends Service { // 5. 通知打印服务推送强制录制任务 const printServiceUrl = ctx.app.config.printService.url; + const requestData = { pack_task_id: Number(id) }; + let printServiceResponse = null; + let printServiceError = null; try { - await ctx.curl(`${printServiceUrl}/record/force`, { + const res = await ctx.curl(`${printServiceUrl}/record/force`, { method: 'POST', contentType: 'json', - data: { - pack_task_id: Number(id), - warehouse_id: warehouseId, - computer_id: recordingComputer.id, - camera_ids: packTask.device_ids || [], - }, + data: requestData, dataType: 'json', timeout: 10000, }); + printServiceResponse = { + status: res.status, + headers: res.headers, + data: res.data, + }; } catch (err) { + printServiceError = err.message; ctx.logger.warn(`通知打印服务强制录制 pack_task_id=${id} 失败: ${err.message}`); - return { code: 500, message: `通知打印服务失败: ${err.message}`, data: null }; } return { - code: 200, - message: '强制录制任务已推送', + code: printServiceError ? 500 : 200, + message: printServiceError ? `通知打印服务失败: ${printServiceError}` : '强制录制任务已推送', data: { pack_task_id: Number(id), computer_id: recordingComputer.id, + print_service_url: `${printServiceUrl}/record/force`, + print_service_request: requestData, + print_service_response: printServiceResponse, + print_service_error: printServiceError, }, }; } diff --git a/methods/system.json b/methods/system.json index 0e5f33a..d660c3c 100644 --- a/methods/system.json +++ b/methods/system.json @@ -6453,7 +6453,9 @@ { "name": "workbench_id", "type": "number", "required": false, "description": "工作台ID(精确匹配)" }, { "name": "quickWhere", "type": "string", "required": false, "description": "快捷搜索:波次号模糊匹配 + 运单号通过 express→order→wave 链路解析" }, { "name": "start_time_start", "type": "string", "required": false, "description": "开始打包时间范围起始(ISO 8601)" }, - { "name": "start_time_end", "type": "string", "required": false, "description": "开始打包时间范围结束(ISO 8601)" } + { "name": "start_time_end", "type": "string", "required": false, "description": "开始打包时间范围结束(ISO 8601)" }, + { "name": "has_video", "type": "number", "required": false, "description": "是否包含录像:1=有录像 2=无录像" }, + { "name": "video_enable", "type": "number", "required": false, "description": "录像是否可用:1=可用(存在 video_url 非空且 status!=failed 的记录) 2=不可用" } ] } ], @@ -6462,7 +6464,7 @@ "name": "list", "type": "array", "required": true, - "description": "打包任务列表,每项含 id、order_id、warehouse_id、workbench_id、wave_id、wave_no、waybill_code、pack_quantity、item_quantity、sku_count、pack_mode、status、start_time、end_time、operator_text、device_ids、remark、meta、create_time、update_time、workbench_name、workbench_type、workbench_barcode、videos[]、expresses[]" + "description": "打包任务列表,每项含 id、order_id、warehouse_id、workbench_id、wave_id、wave_no、waybill_code、pack_quantity、item_quantity、sku_count、pack_mode、status、start_time、end_time、operator_text、device_ids、remark、meta、create_time、update_time、workbench_name、workbench_type、workbench_barcode、has_video、video_enable、videos[]、expresses[]" }, { "name": "pagination", @@ -6499,7 +6501,7 @@ "name": "data", "type": "object", "required": true, - "description": "打包任务详情,含 id、order_id、warehouse_id、workbench_id、wave_id、wave_no、waybill_code、pack_quantity、item_quantity、sku_count、pack_mode、status、start_time、end_time、operator_text、device_ids、remark、meta、create_time、update_time、workbench_name、workbench_type、workbench_barcode、videos[]、expresses[]" + "description": "打包任务详情,含 id、order_id、warehouse_id、workbench_id、wave_id、wave_no、waybill_code、pack_quantity、item_quantity、sku_count、pack_mode、status、start_time、end_time、operator_text、device_ids、remark、meta、create_time、update_time、workbench_name、workbench_type、workbench_barcode、has_video、video_enable、videos[]、expresses[]" } ], "errors": [ From d11ed3b2a2ab0c8c3495ef895f788aca012388e1 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 27 Jul 2026 17:46:26 +0800 Subject: [PATCH 133/550] =?UTF-8?q?feat(order.pendingOrder):=20=E6=96=B0?= =?UTF-8?q?=E5=A2=9E=20allocateSubOrderNumber=20=E5=AD=90=E5=8D=95?= =?UTF-8?q?=E5=8F=B7=E5=BC=82=E6=AD=A5=E5=88=86=E9=85=8D=E6=8E=A5=E5=8F=A3?= =?UTF-8?q?=E4=B8=8E=E8=BF=9B=E5=BA=A6=E6=9F=A5=E8=AF=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../systemMethods/order/pendingOrder.js | 417 +++++++++++++++++- methods/changes/system.json | 21 + methods/system.json | 168 +++++++ 3 files changed, 603 insertions(+), 3 deletions(-) diff --git a/app/service/systemMethods/order/pendingOrder.js b/app/service/systemMethods/order/pendingOrder.js index ebfa97a..a5dcaf2 100644 --- a/app/service/systemMethods/order/pendingOrder.js +++ b/app/service/systemMethods/order/pendingOrder.js @@ -53,6 +53,18 @@ const SYNC_ORDER_IDS_PROGRESS_MAP = Object.freeze({ unknown: 0, }); +const ALLOCATE_SUB_ORDER_TASK_CACHE_KEY_PREFIX = 'order:pending:allocate_sub_order:request:'; +const ALLOCATE_SUB_ORDER_TASK_CACHE_TTL_SECONDS = 60 * 60 * 2; +const ALLOCATE_SUB_ORDER_PROGRESS_MAP = Object.freeze({ + submitted: 5, + running: 50, + success: 100, + partial: 80, + failed: 100, + not_found: 0, + unknown: 0, +}); + /** * 中国行政区划反向查询表。 * @@ -528,9 +540,9 @@ class PendingOrderService extends OrderBaseService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateExpressCodeTaskProgress,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,updateOrderPlatform,updateOrderExpress,updateRemark,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill'; - const _noNeedLog = 'list,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateExpressCodeTaskProgress,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill'; - const _noNeedAuth = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateExpressCodeTaskProgress,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,updateOrderPlatform,updateOrderExpress,updateRemark,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill'; + const _noNeedRight = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateExpressCodeTaskProgress,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,updateOrderPlatform,updateOrderExpress,updateRemark,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill,allocateSubOrderNumber,allocateSubOrderNumberProgress'; + const _noNeedLog = 'list,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateExpressCodeTaskProgress,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill,allocateSubOrderNumber,allocateSubOrderNumberProgress'; + const _noNeedAuth = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateExpressCodeTaskProgress,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,updateOrderPlatform,updateOrderExpress,updateRemark,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill,allocateSubOrderNumber,allocateSubOrderNumberProgress'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -5917,6 +5929,405 @@ class PendingOrderService extends OrderBaseService { } } + // ========== allocateSubOrderNumber 子单号分配 ========== + + /** + * 分配子单号(异步任务模式)。 + * + * 为指定订单按 business_key(从 2 开始)逐个子单号分配运单号。 + * 将所有 business_key 全量传入 createWaybillCodePipeline, + * 由 pipeline 内部事务 + UNIQUE(order_id,business_key,status,warehouse_id) 索引 + * 保证并发安全:已分配(status=1)自动跳过,未分配 INSERT status=0 占位后分配。 + * + * @param {Object} data 请求体。 + * @param {number|string} data.order_id 订单ID(必填)。 + * @param {number} data.sub_order_count 子单号数量(必填,>=1)。 + * @return {Promise} 统一 success 包装,立即返回 task_id。 + */ + async allocateSubOrderNumber(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const warehouseId = this.getWarehouseId(); + + // 1. 参数校验 + const orderId = Number(requestData.order_id); + if (!Number.isInteger(orderId) || orderId <= 0) { + throw new Error('order_id 必须为正整数'); + } + + const subOrderCount = Number(requestData.sub_order_count); + if (!Number.isInteger(subOrderCount) || subOrderCount < 1) { + throw new Error('sub_order_count 必须为正整数且 >= 1'); + } + + // 2. 查询订单并校验状态(待处理:step in [1,2,3] 且 outbound_status != 'padding') + const model = await this.getOrderModel('order', warehouseId); + const where = this.buildOrderWhere([ orderId ], warehouseId); + const order = await model.findOne({ + where, + attributes: [ 'id', 'step', 'outbound_status', 'warehouse_id', 'store_id', 'sys_platform_code', 'logistics_code', 'sys_platform_name', 'logistics_name' ], + raw: true, + }); + + if (!order) { + throw new Error(`订单 ${orderId} 不存在或不属于当前仓库`); + } + + const allowedSteps = new Set([ 1, 2, 3 ]); + if (!allowedSteps.has(order.step)) { + throw new Error(`订单 ${orderId} 当前步骤为 ${order.step},仅允许待处理状态(step 1/2/3)的订单分配子单号`); + } + + if (order.outbound_status === PENDING_OUTBOUND_STATUS) { + throw new Error(`订单 ${orderId} 已标记待出库,不允许分配子单号`); + } + + // 3. 计算 business_key 列表(从 2 开始) + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; + if (!orderExpressModel) { + throw new Error('OrderExpress 模型未加载'); + } + + const businessKeys = []; + for (let i = 0; i < subOrderCount; i++) { + businessKeys.push(2 + i); + } + + // 4. 预查已有的已分配运单号(status=1),仅用于初始 details 展示与全部跳过优化 + const { Op } = this.app.Sequelize; + const existingCompleted = await orderExpressModel.findAll({ + where: { + order_id: orderId, + warehouse_id: Number(order.warehouse_id) || warehouseId, + status: 1, + business_key: { [Op.in]: businessKeys }, + }, + attributes: [ 'business_key', 'waybill_code' ], + raw: true, + }); + + const completedBusinessKeyMap = new Map(); + if (Array.isArray(existingCompleted)) { + for (const row of existingCompleted) { + completedBusinessKeyMap.set(Number(row.business_key), String(row.waybill_code || '').trim()); + } + } + + // 5. 生成任务ID,立即返回 + const taskId = `sub_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`; + const taskPayload = { + task_id: taskId, + order_id: orderId, + status: 'submitted', + progress: ALLOCATE_SUB_ORDER_PROGRESS_MAP.submitted, + message: '子单号分配任务已提交', + result: { + total_count: businessKeys.length, + skip_count: completedBusinessKeyMap.size, + pending_count: businessKeys.length - completedBusinessKeyMap.size, + business_keys: businessKeys, + skipped_business_keys: businessKeys.filter(bk => completedBusinessKeyMap.has(bk)), + pending_business_keys: businessKeys.filter(bk => !completedBusinessKeyMap.has(bk)), + details: businessKeys.map(bk => ({ + business_key: bk, + status: completedBusinessKeyMap.has(bk) ? 'skipped' : 'pending', + waybill_code: completedBusinessKeyMap.get(bk) || null, + })), + }, + error: '', + }; + await this.setAllocateSubOrderTaskProgress(taskId, taskPayload); + + // 6. 如果全部已分配,跳过 pipeline 直接完成 + if (completedBusinessKeyMap.size === businessKeys.length) { + await this.setAllocateSubOrderTaskProgress(taskId, { + ...taskPayload, + status: 'success', + progress: ALLOCATE_SUB_ORDER_PROGRESS_MAP.success, + message: '子单号分配完成(全部已分配,无待处理项)', + }); + return this.success('ok', { + ...taskPayload, + status: 'success', + progress: ALLOCATE_SUB_ORDER_PROGRESS_MAP.success, + message: '子单号分配完成(全部已分配,无待处理项)', + update_time: Date.now(), + }); + } + + // 7. 后台异步执行分配(全量 business_key 传入 pipeline,由其内部事务保证去重与并发安全) + const orderWarehouseId = Number(order.warehouse_id) || warehouseId; + setImmediate(async () => { + try { + await this.setAllocateSubOrderTaskProgress(taskId, { + ...taskPayload, + status: 'running', + progress: ALLOCATE_SUB_ORDER_PROGRESS_MAP.running, + message: '子单号分配处理中', + }); + + // 全量传入(含已分配的),pipeline 内部 createWaybillCode 事务会跳过 status=1 的记录 + const ordersForPipeline = businessKeys.map(bk => ({ + order_id: orderId, + business_key: bk, + sys_platform_code: order.sys_platform_code, + logistics_code: order.logistics_code, + sys_platform_name: order.sys_platform_name, + logistics_name: order.logistics_name, + store_id: order.store_id, + })); + + const pipelineResult = await this.service.systems.express.createWaybillCodePipeline( + ordersForPipeline, + { awaitTasks: true } + ); + + // 回查最终分配结果 + const updatedDetails = await this.buildSubOrderDetails(orderId, orderWarehouseId, businessKeys); + + const successCount = updatedDetails.filter(d => d.status === 'allocated' || d.status === 'skipped').length; + const isPartial = successCount < businessKeys.length; + + await this.setAllocateSubOrderTaskProgress(taskId, { + ...taskPayload, + status: isPartial ? 'partial' : 'success', + progress: isPartial ? ALLOCATE_SUB_ORDER_PROGRESS_MAP.partial : ALLOCATE_SUB_ORDER_PROGRESS_MAP.success, + message: isPartial + ? `子单号分配部分完成(${successCount}/${businessKeys.length})` + : '子单号分配完成', + result: { + ...taskPayload.result, + pipeline_result: pipelineResult, + details: updatedDetails, + }, + }); + } catch (error) { + const errorMessage = error && error.message ? error.message : String(error); + + await this.setAllocateSubOrderTaskProgress(taskId, { + ...taskPayload, + status: 'failed', + progress: ALLOCATE_SUB_ORDER_PROGRESS_MAP.failed, + message: '子单号分配失败', + error: errorMessage, + }); + } + }); + + return this.success('ok', { + ...taskPayload, + update_time: Date.now(), + }); + } + + /** + * 查询子单号分配任务进度。 + * + * 可按 task_id 或 business_key 查询。 + * 若传入 business_key,返回该 business_key 对应的分配详情。 + * + * @param {Object} data 请求体。 + * @param {string} data.task_id 任务ID。 + * @param {string} data.taskId 任务ID(驼峰写法)。 + * @param {number} [data.business_key] 子单号业务ID(可选,按业务ID过滤)。 + * @param {number} [data.businessKey] 子单号业务ID(可选,驼峰写法)。 + * @return {Promise} 统一 success 包装。 + */ + async allocateSubOrderNumberProgress(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const taskId = String(requestData.task_id || requestData.taskId || '').trim(); + const businessKey = Number(requestData.business_key || requestData.businessKey); + + if (!taskId) { + return this.success('ok', { + task_id: '', + status: 'not_found', + progress: ALLOCATE_SUB_ORDER_PROGRESS_MAP.not_found, + message: '任务不存在', + result: null, + error: '', + update_time: Date.now(), + }); + } + + const cachedTask = await this.getAllocateSubOrderTaskProgress(taskId); + if (!cachedTask) { + return this.success('ok', { + task_id: taskId, + status: 'not_found', + progress: ALLOCATE_SUB_ORDER_PROGRESS_MAP.not_found, + message: '任务不存在', + result: null, + error: '', + update_time: Date.now(), + }); + } + + // 如果传入了 business_key,过滤出该业务ID对应的详情 + let filteredResult = cachedTask.result; + if (Number.isInteger(businessKey) && businessKey > 0 && cachedTask.result) { + const details = Array.isArray(cachedTask.result.details) ? cachedTask.result.details : []; + const matchedDetail = details.find(d => Number(d.business_key) === businessKey); + filteredResult = { + ...cachedTask.result, + filtered_business_key: businessKey, + matched_detail: matchedDetail || null, + }; + } + + return this.success('ok', { + ...cachedTask, + result: filteredResult, + update_time: cachedTask.update_time || Date.now(), + }); + } + + // ========== allocateSubOrderNumber 缓存工具方法 ========== + + /** + * 获取子单号分配任务缓存键。 + * + * @param {string} taskId 任务ID。 + * @return {string} 缓存键。 + */ + getAllocateSubOrderTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + return `${ALLOCATE_SUB_ORDER_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 写入子单号分配任务进度。 + * + * @param {string} taskId 任务ID。 + * @param {Object} payload 任务状态与结果。 + * @return {Promise} + */ + async setAllocateSubOrderTaskProgress(taskId = '', payload = {}) { + const cacheKey = this.getAllocateSubOrderTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.setCacheAsync !== 'function') { + return; + } + + const safePayload = this.isPlainObject(payload) ? payload : {}; + const progressPayload = { + task_id: String(taskId || '').trim(), + order_id: safePayload.order_id || null, + status: String(safePayload.status || 'unknown').trim(), + progress: Number(safePayload.progress || 0), + message: String(safePayload.message || ''), + result: safePayload.result || null, + error: String(safePayload.error || ''), + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync(cacheKey, progressPayload, ALLOCATE_SUB_ORDER_TASK_CACHE_TTL_SECONDS); + } catch (error) { + this.ctx.logger.warn('[pendingOrder.allocateSubOrderNumber] 写入任务进度缓存失败: %s', error && error.message ? error.message : error); + } + } + + /** + * 读取子单号分配任务进度。 + * + * @param {string} taskId 任务ID。 + * @return {Promise} 任务缓存结果。 + */ + async getAllocateSubOrderTaskProgress(taskId = '') { + const cacheKey = this.getAllocateSubOrderTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.getCacheAsync !== 'function') { + return null; + } + + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (!this.isPlainObject(cached)) { + return null; + } + return cached; + } catch (error) { + this.ctx.logger.warn('[pendingOrder.allocateSubOrderNumber] 读取任务进度缓存失败: %s', error && error.message ? error.message : error); + return null; + } + } + + /** + * 回查子单号分配结果详情(pipeline 执行后调用)。 + * + * 根据 order_express 表最终状态判断每个 business_key 的结果: + * - status=1 且 waybill_code 非空 → allocated(本次分配成功或之前已分配) + * - status=0 → pipeline 占位但 API 未完成 → failed + * - 无记录 → failed(pipeline 未处理到) + * + * @param {number} orderId 订单ID。 + * @param {number} warehouseId 仓库ID。 + * @param {number[]} businessKeys 全部 business_key 列表。 + * @return {Promise>} 每个 business_key 的分配详情。 + */ + async buildSubOrderDetails(orderId, warehouseId, businessKeys) { + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; + if (!orderExpressModel) { + return businessKeys.map(bk => ({ + business_key: bk, + status: 'unknown', + waybill_code: null, + note: 'OrderExpress 模型未加载', + })); + } + + const { Op } = this.app.Sequelize; + const allRecords = await orderExpressModel.findAll({ + where: { + order_id: orderId, + warehouse_id: warehouseId, + business_key: { [Op.in]: businessKeys }, + }, + attributes: [ 'business_key', 'waybill_code', 'status' ], + raw: true, + }); + + const recordMap = new Map(); + if (Array.isArray(allRecords)) { + for (const row of allRecords) { + // 同一 business_key 可能有多条(status 不同),优先取 status=1 的 + const existing = recordMap.get(Number(row.business_key)); + if (!existing || Number(row.status) === 1) { + recordMap.set(Number(row.business_key), row); + } + } + } + + return businessKeys.map(bk => { + const record = recordMap.get(bk); + if (record && Number(record.status) === 1 && String(record.waybill_code || '').trim()) { + return { + business_key: bk, + status: 'allocated', + waybill_code: String(record.waybill_code || '').trim(), + note: '子单号分配成功', + }; + } + + if (record && Number(record.status) === 0) { + return { + business_key: bk, + status: 'failed', + waybill_code: null, + note: '运单占位已创建但 API 未返回运单号(status=0)', + }; + } + + return { + business_key: bk, + status: 'failed', + waybill_code: null, + note: '未找到分配的运单记录', + }; + }); + } + } module.exports = PendingOrderService; diff --git a/methods/changes/system.json b/methods/changes/system.json index b6c7084..6913765 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,25 @@ [ + { + "version": "2026.07.27-system-02", + "date": "2026-07-27", + "type": "added", + "summary": "新增 order.pendingOrder.allocateSubOrderNumber:待处理订单分配子单号(异步任务),business_key 从 2 开始递增,跳过已分配运单号;新增 allocateSubOrderNumberProgress 按 task_id/business_key 查询进度", + "methods": [ + "order.pendingOrder.allocateSubOrderNumber", + "order.pendingOrder.allocateSubOrderNumberProgress" + ], + "notes": [ + "新增 allocateSubOrderNumber:入参 order_id + sub_order_count,按 business_key 2..(2+count-1) 全量传入 createWaybillCodePipeline。", + "并发安全:全量传入 pipeline,由其内部事务 + UNIQUE(order_id,business_key,status,warehouse_id) 索引保证并发去重。", + "pipeline 内部 createWaybillCode 事务:status=1 已分配→跳过;status=0 占位中→复用;无记录→INSERT status=0 占位。", + "异步任务模式:请求立即返回 task_id(sub_ 前缀),后台 setImmediate 执行,进度通过 Redis 缓存追踪。", + "新增 allocateSubOrderNumberProgress:支持 task_id 查整体进度,business_key 可选参数过滤单个业务ID的详情。", + "进度状态 submitted→running→success/partial/failed,progress 对应 5/50/80/100。", + "result.details 数组记录每个 business_key 的 status(skipped/allocated/failed/pending)与 waybill_code。", + "buildSubOrderDetails 回查最终状态:status=1+waybill→allocated,status=0→failed,无记录→failed。" + ], + "module": "order.pendingOrder" + }, { "version": "2026.07.27-system-01", "date": "2026-07-27", diff --git a/methods/system.json b/methods/system.json index d660c3c..3476756 100644 --- a/methods/system.json +++ b/methods/system.json @@ -25847,6 +25847,174 @@ } ] }, + { + "method": "order.pendingOrder.allocateSubOrderNumber", + "description": "分配子单号(异步任务模式)。为指定订单按 business_key(从 2 开始)全量传入 createWaybillCodePipeline,由其内部事务 + UNIQUE(order_id,business_key,status,warehouse_id) 索引保证并发安全:已分配(status=1)自动跳过,未分配 INSERT status=0 占位后分配。请求立即返回 task_id(sub_ 前缀),后续通过 allocateSubOrderNumberProgress 按 task_id 或 business_key 查询进度与结果。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "order_id", + "type": "number", + "required": true, + "source": "body", + "description": "订单 ID,必须为正整数" + }, + { + "name": "sub_order_count", + "type": "number", + "required": true, + "source": "body", + "description": "子单号数量,>= 1。business_key 从 2 开始递增,如 count=1 则创建 business_key=2,count=3 则创建 2/3/4" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务 ID(sub_ 前缀),用于查询进度" + }, + { + "name": "order_id", + "type": "number", + "required": true, + "description": "订单 ID" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "任务状态:submitted/running/success/partial/failed" + }, + { + "name": "progress", + "type": "number", + "required": true, + "description": "进度百分比:5/50/80/100" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "任务状态说明" + }, + { + "name": "result", + "type": "object", + "required": true, + "description": "分配结果摘要,含 total_count/skip_count/pending_count/business_keys/skipped_business_keys/pending_business_keys/details 等字段" + } + ], + "errors": [ + { + "code": 400, + "message": "order_id 必须为正整数" + }, + { + "code": 400, + "message": "sub_order_count 必须为正整数且 >= 1" + }, + { + "code": 400, + "message": "订单不存在或不属于当前仓库" + }, + { + "code": 400, + "message": "订单当前步骤不在允许范围,仅允许待处理状态(step 1/2/3)的订单分配子单号" + }, + { + "code": 400, + "message": "订单已标记待出库,不允许分配子单号" + }, + { + "code": 500, + "message": "内部错误:OrderExpress 模型未加载或运单分配链路异常" + } + ] + }, + { + "method": "order.pendingOrder.allocateSubOrderNumberProgress", + "description": "查询子单号分配任务进度。可按 task_id 查询整体进度,也可传入 business_key 进一步过滤该业务ID对应的分配详情与最终结果。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "task_id", + "type": "string", + "required": true, + "source": "body", + "description": "任务 ID(返回的 task_id),支持 task_id 或 taskId 两种写法" + }, + { + "name": "business_key", + "type": "number", + "required": false, + "source": "body", + "description": "子单号业务ID(可选),传入后返回该 business_key 对应的分配详情。支持 business_key 或 businessKey 两种写法" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务 ID" + }, + { + "name": "order_id", + "type": "number", + "required": true, + "description": "订单 ID" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "任务状态:submitted/running/success/partial/failed/not_found" + }, + { + "name": "progress", + "type": "number", + "required": true, + "description": "进度百分比" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "任务状态说明" + }, + { + "name": "result", + "type": "object", + "required": true, + "description": "分配结果。若传了 business_key,额外返回 filtered_business_key 与 matched_detail" + } + ], + "errors": [ + { + "code": 500, + "message": "查询缓存异常" + } + ] + }, { "method": "order.bindExpressPackageMaterialByWaybill", "description": "按运单号绑定包材。仅需传入运单号与包材ID,系统自动根据运单号反查对应订单运单记录并绑定包材,无需传入订单ID。", From 000597feccccd5e9ac071329fcf58bdcf4726c1e Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 27 Jul 2026 17:46:42 +0800 Subject: [PATCH 134/550] =?UTF-8?q?fix(order.recheckOrder):=20waybill=5Fco?= =?UTF-8?q?de=20=E5=8A=A0=E5=85=A5=E6=95=A3=E5=8D=95=E5=A4=8D=E6=A0=B8?= =?UTF-8?q?=E5=88=97=E8=A1=A8=E5=93=8D=E5=BA=94=E5=AD=97=E6=AE=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/systemMethods/order/recheckOrder.js | 4 +++- methods/system.json | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/app/service/systemMethods/order/recheckOrder.js b/app/service/systemMethods/order/recheckOrder.js index 04a29c6..4373342 100644 --- a/app/service/systemMethods/order/recheckOrder.js +++ b/app/service/systemMethods/order/recheckOrder.js @@ -3176,7 +3176,8 @@ class RecheckOrderService extends OrderBaseService { o.weight_type, o.status, o.create_at, - o.recheck_time + o.recheck_time, + (SELECT oe.waybill_code FROM order_express oe WHERE oe.order_id = o.id AND oe.delete_at IS NULL LIMIT 1) AS waybill_code FROM ${orderTableName} o ${whereClause} ORDER BY o.id ASC @@ -3219,6 +3220,7 @@ class RecheckOrderService extends OrderBaseService { items_total: Number(row?.items_total || 0), items_weight: row?.items_weight != null ? Number(row.items_weight) : null, weight_type: this.formatWeightTypeLabel(row?.weight_type), + waybill_code: String(row?.waybill_code || '').trim(), status: Number(row?.status || 0), create_at: row?.create_at || null, recheck_time: row?.recheck_time || null, diff --git a/methods/system.json b/methods/system.json index 3476756..cd693ff 100644 --- a/methods/system.json +++ b/methods/system.json @@ -6388,7 +6388,7 @@ "name": "list", "type": "array", "required": true, - "description": "散单复核订单列表,每项含 order_id、delivery_order_code、order_type、wave_id、wave_no、pick_status、recheck_status、shop_nick、logistics_name、items_count、items_total、items_weight、weight_type、status、create_at、pick_time、recheck_time" + "description": "散单复核订单列表,每项含 order_id、delivery_order_code、order_type、wave_id、wave_no、pick_status、recheck_status、shop_nick、logistics_name、items_count、items_total、items_weight、weight_type、waybill_code、status、create_at、recheck_time" }, { "name": "pagination", From fb2c00027e372280782d02e52dcd0061b9589f33 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 27 Jul 2026 17:46:56 +0800 Subject: [PATCH 135/550] =?UTF-8?q?refactor(storage.receiving):=20?= =?UTF-8?q?=E5=AF=BC=E5=87=BA=E5=8A=9F=E8=83=BD=20storeId=20=E6=94=B9?= =?UTF-8?q?=E4=B8=BA=E4=BB=8E=20ctx.user.store=5Fid=20=E8=8E=B7=E5=8F=96?= =?UTF-8?q?=20warehouseId=EF=BC=9B=E6=96=B0=E5=A2=9E=E5=AF=BC=E5=87=BA?= =?UTF-8?q?=E7=9B=B8=E5=85=B3=E6=8E=A5=E5=8F=A3=E6=96=87=E6=A1=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../systemMethods/storage/receiving.js | 157 ++++-- app/service/systems/storage/receiving.js | 466 +++++++++++++++++- methods/system.json | 322 ++++++++++++ 3 files changed, 899 insertions(+), 46 deletions(-) diff --git a/app/service/systemMethods/storage/receiving.js b/app/service/systemMethods/storage/receiving.js index 56c7ec0..ef2cc25 100644 --- a/app/service/systemMethods/storage/receiving.js +++ b/app/service/systemMethods/storage/receiving.js @@ -13,9 +13,9 @@ class configService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'getReceivingList,getStoreReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs,scanDetail,export,exportTaskProgress'; - const _noNeedLog = 'getReceivingList,getStoreReceivingList,get,addDetail,deleteDetail,detailChange,bindStore,bindDetailProduct,queryReceivingLogs,scanDetail,export,exportTaskProgress'; - const _noNeedAuth = 'getReceivingList,getStoreReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs,scanDetail,export,exportTaskProgress'; + const _noNeedRight = 'getReceivingList,getStoreReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs,scanDetail,export,exportTaskProgress,storeExport,storeExportTaskProgress'; + const _noNeedLog = 'getReceivingList,getStoreReceivingList,get,addDetail,deleteDetail,detailChange,bindStore,bindDetailProduct,queryReceivingLogs,scanDetail,export,exportTaskProgress,storeExport,storeExportTaskProgress'; + const _noNeedAuth = 'getReceivingList,getStoreReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs,scanDetail,export,exportTaskProgress,storeExport,storeExportTaskProgress'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -333,39 +333,19 @@ class configService extends MainService { } /** - * 提交收货单导出任务(复用 getStoreReceivingList 的筛选语义与排序规则)。 + * 提交收货单导出任务(仓库维度,复用 getReceivingList 的筛选语义与排序规则)。 * 导出分为两个 sheet:Sheet1=收货单列表,Sheet2=收货单明细。 * @param {Object} data 请求体 - * @param {Object} [data.where] 筛选条件(与 getStoreReceivingList 一致) + * @param {Object} [data.where] 筛选条件(与 getReceivingList 一致) * @param {Object} [data.sort] 排序参数 * @return {Promise} 统一成功包装响应,data 为导出任务信息 */ async export(data = {}) { - const { ctx, app, service } = this; - - // 从平台激活上下文获取 store_id - const platformRows = await app.model.query( - 'SELECT apa.employee_id, ase.store_id FROM wms_account_platform_active apa ' + - 'INNER JOIN wms_account_store_employee ase ON ase.id = apa.employee_id AND ase.status = 1 ' + - 'WHERE apa.account_id = :accountId AND apa.platform_code = :platformCode LIMIT 1', - { - replacements: { accountId: ctx.userId, platformCode: ctx.platformCode || 'web' }, - type: app.Sequelize.QueryTypes.SELECT, - } - ); - - if (!platformRows || platformRows.length === 0 || !platformRows[0].store_id) { - return this.fail('未获取到货主平台激活上下文,请先切换至货主角色'); - } - - const storeId = platformRows[0].store_id; + const { service } = this; const { sort = {} } = data; - const { where } = this.prepareWhereContext(data, { specialFieldMap: { - quickWhere: { - bucket: 'quick', - }, + quickWhere: { bucket: 'quick' }, }, }); @@ -394,7 +374,6 @@ class configService extends MainService { const result = await service.systems.storage.receiving.exportReceivingList({ where, - storeId, sort, onProgress: async progress => { const safeProgress = this.isPlainObject(progress) ? progress : {}; @@ -490,13 +469,15 @@ class configService extends MainService { /** * 生成收货单导出任务ID。 + * @param {string} [prefix=''] 任务类型前缀(如 'store') * @return {string} 导出任务ID */ - generateExportTaskId() { + generateExportTaskId(prefix = '') { const storeId = this.ctx?.user?.store_id || 'unknown'; const timestamp = Date.now(); const randomToken = Math.random().toString(36).slice(2, 10); - return `receiving_export_${storeId}_${timestamp}_${randomToken}`; + const typePrefix = prefix ? `${prefix}_` : ''; + return `receiving_${typePrefix}export_${storeId}_${timestamp}_${randomToken}`; } /** @@ -579,5 +560,121 @@ class configService extends MainService { } } + /** + * 提交货主侧收货单导出任务(复用 getStoreReceivingList 的筛选语义与排序规则)。 + * 以当前平台激活的货主 store_id 为维度导出。导出分为两个 sheet:Sheet1=收货单列表,Sheet2=收货单明细。 + * @param {Object} data 请求体 + * @param {Object} [data.where] 筛选条件(与 getStoreReceivingList 一致) + * @param {Object} [data.sort] 排序参数 + * @return {Promise} 统一成功包装响应,data 为导出任务信息 + */ + async storeExport(data = {}) { + const { ctx, app, service } = this; + + // 从平台激活上下文获取 store_id + const platformRows = await app.model.query( + 'SELECT apa.employee_id, ase.store_id FROM wms_account_platform_active apa ' + + 'INNER JOIN wms_account_store_employee ase ON ase.id = apa.employee_id AND ase.status = 1 ' + + 'WHERE apa.account_id = :accountId AND apa.platform_code = :platformCode LIMIT 1', + { + replacements: { accountId: ctx.userId, platformCode: ctx.platformCode || 'web' }, + type: app.Sequelize.QueryTypes.SELECT, + } + ); + + if (!platformRows || platformRows.length === 0 || !platformRows[0].store_id) { + return this.fail('未获取到货主平台激活上下文,请先切换至货主角色'); + } + + const storeId = platformRows[0].store_id; + const { sort = {} } = data; + + const { where } = this.prepareWhereContext(data, { + specialFieldMap: { + quickWhere: { + bucket: 'quick', + }, + }, + }); + + const taskId = this.generateExportTaskId('store'); + const taskPayload = { + task_id: taskId, + status: 'submitted', + progress: 0, + message: '货主侧收货单导出任务已提交', + result: null, + error: '', + }; + + await this.setExportTaskProgress(taskId, taskPayload); + + setImmediate(async () => { + try { + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'running', + progress: 5, + message: '货主侧收货单导出任务执行中', + result: null, + error: '', + }); + + const result = await service.systems.storage.receiving.exportStoreReceivingList({ + where, + storeId, + sort, + onProgress: async progress => { + const safeProgress = this.isPlainObject(progress) ? progress : {}; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: safeProgress.status || 'running', + progress: safeProgress.progress, + message: safeProgress.message || '货主侧收货单导出任务执行中', + result: safeProgress.result || null, + error: '', + }); + }, + }); + + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'success', + progress: 100, + message: '货主侧收货单导出任务完成', + result, + error: '', + }); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'failed', + progress: 100, + message: '货主侧收货单导出任务失败', + result: null, + error: errorMessage, + }); + } + }); + + return this.success('ok', { + ...taskPayload, + update_time: Date.now(), + }); + } + + /** + * 查询货主侧收货单导出任务进度。 + * 复用 exportTaskProgress 的缓存查询逻辑,任务 ID 前缀不同。 + * @param {Object} data 请求体 + * @param {string} [data.task_id] 任务ID(下划线写法) + * @param {string} [data.taskId] 任务ID(驼峰写法) + * @return {Promise} 统一成功包装响应 + */ + async storeExportTaskProgress(data = {}) { + return this.exportTaskProgress(data); + } + } module.exports = configService; diff --git a/app/service/systems/storage/receiving.js b/app/service/systems/storage/receiving.js index 7b76949..3529a15 100644 --- a/app/service/systems/storage/receiving.js +++ b/app/service/systems/storage/receiving.js @@ -4727,14 +4727,14 @@ class ReceivingService extends Service { const { Op } = Sequelize; const safeOptions = options && typeof options === 'object' ? options : {}; const where = safeOptions.where && typeof safeOptions.where === 'object' ? { ...safeOptions.where } : {}; - const storeId = Number(safeOptions.storeId); + const warehouseId = Number(ctx.user && ctx.user.store_id); const sort = safeOptions.sort && typeof safeOptions.sort === 'object' ? { ...safeOptions.sort } : {}; const progressHandler = typeof safeOptions.onProgress === 'function' ? safeOptions.onProgress : async () => {}; - if (!storeId) { - throw new Error('货主ID不能为空,无法导出'); + if (!warehouseId) { + throw new Error('用户未绑定仓库,无法导出'); } const sortField = sort.sortField || 'created_at'; @@ -4744,24 +4744,27 @@ class ReceivingService extends Service { ]; const actualSortField = validSortFields.includes(sortField) ? sortField : 'created_at'; - // 构建 where 条件(与 getStoreReceivingList 一致) + // 构建 where 条件(与 getReceivingList 一致,按仓库维度) const queryOptions = { - where: { [Op.and]: [{ store_id: storeId }] }, + where: { [Op.and]: [{ warehouse_id: warehouseId }] }, }; const normalizedWhere = { ...where }; - const parsed = parseWhereConditions({ - where: normalizedWhere, - app, - specialFieldMap: { - quickWhere: { bucket: 'quick' }, - }, - }); + let parsedResult = ctx.whereParsed; + if (!parsedResult || !Array.isArray(parsedResult.dynamicConditions)) { + const parsed = parseWhereConditions({ + where: normalizedWhere, + app, + specialFieldMap: { + quickWhere: { bucket: 'quick' }, + }, + }); - if (!parsed.ok) { - throw new Error(`筛选条件解析失败: ${parsed.reason}`); + if (!parsed.ok) { + throw new Error(`筛选条件解析失败: ${parsed.reason}`); + } + parsedResult = parsed.result; } - const parsedResult = parsed.result; const dynamicConditions = [ ...(parsedResult.dynamicConditions || []) ]; const quickWhereRaw = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere) @@ -5089,7 +5092,438 @@ class ReceivingService extends Service { const stat = await fsp.stat(filePath); const randomToken = crypto.randomBytes(6).toString('hex'); - const uploadKey = `exports/receiving/${storeId}/${Date.now()}_${randomToken}.xlsx`; + const uploadKey = `exports/receiving/${warehouseId}/${Date.now()}_${randomToken}.xlsx`; + const uploadStream = fs.createReadStream(filePath); + uploadStream.filename = filename; + uploadStream.mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; + uploadStream.fileSize = stat.size; + + const uploadResult = await uploadService.uploadFile(uploadStream, { + key: uploadKey, + category: 'document', + mimetype: 'xls,xlsx,csv', + }); + + let fileRecord = null; + if (typeof uploadService.uploadSuccessNotify === 'function') { + fileRecord = await uploadService.uploadSuccessNotify({ + url: uploadResult.fileName, + fileKey: uploadResult.fileName, + fileName: filename, + fileType: 'document', + mimeType: uploadStream.mimeType, + fileSize: stat.size, + userId: ctx.userId, + description: `收货单导出(仓库${warehouseId}),共${totalCount}条收货单`, + }); + } + + // 清理临时文件 + try { await fsp.rm(tempDir, { recursive: true, force: true }); } catch (_) { /* ignore */ } + + const uploadInfo = fileRecord || uploadResult; + const fileUrl = typeof uploadInfo === 'object' && uploadInfo.url + ? uploadInfo.url + : (typeof uploadResult === 'object' ? uploadResult.fileName : ''); + + await progressHandler({ + status: 'running', + progress: 100, + message: '导出完成', + result: { url: fileUrl, fileKey: uploadKey, total: totalCount }, + }); + + return { + url: fileUrl, + fileKey: uploadKey, + total: totalCount, + totalDetails: allReceivingIds.reduce((sum, rid) => sum + (detailsMap.get(rid) || []).length, 0), + }; + } + + /** + * 导出货主侧收货单列表(双 sheet:收货单列表 + 收货单明细)。 + * 复用 getStoreReceivingList 的筛选与排序语义,以货主 store_id 过滤,分页拉取全量数据后生成 Excel 并上传。 + * @param {Object} options 导出选项 + * @param {Object} [options.where] 筛选条件(与 getStoreReceivingList 一致) + * @param {number} options.storeId 货主ID + * @param {Object} [options.sort] 排序参数 + * @param {Function} [options.onProgress] 进度回调 + * @return {Promise} 上传结果与统计信息 + */ + async exportStoreReceivingList(options = {}) { + const { ctx, app } = this; + const { Sequelize } = app; + const { Op } = Sequelize; + const safeOptions = options && typeof options === 'object' ? options : {}; + const where = safeOptions.where && typeof safeOptions.where === 'object' ? { ...safeOptions.where } : {}; + const storeId = Number(safeOptions.storeId); + const sort = safeOptions.sort && typeof safeOptions.sort === 'object' ? { ...safeOptions.sort } : {}; + const progressHandler = typeof safeOptions.onProgress === 'function' + ? safeOptions.onProgress + : async () => {}; + + if (!storeId) { + throw new Error('货主ID不能为空,无法导出'); + } + + const sortField = sort.sortField || 'created_at'; + const sortOrder = String(sort.sortOrder || 'DESC').toUpperCase() === 'ASC' ? 'ASC' : 'DESC'; + const validSortFields = [ + 'id', 'receiving_number', 'status', 'created_at', 'updated_at', 'store_id', 'warehouse_id', + ]; + const actualSortField = validSortFields.includes(sortField) ? sortField : 'created_at'; + + // 构建 where 条件(与 getStoreReceivingList 一致,按货主维度) + const queryOptions = { + where: { [Op.and]: [{ store_id: storeId }] }, + }; + + const normalizedWhere = { ...where }; + let parsedResult = ctx.whereParsed; + if (!parsedResult || !Array.isArray(parsedResult.dynamicConditions)) { + const parsed = parseWhereConditions({ + where: normalizedWhere, + app, + specialFieldMap: { + quickWhere: { bucket: 'quick' }, + }, + }); + + if (!parsed.ok) { + throw new Error(`筛选条件解析失败: ${parsed.reason}`); + } + parsedResult = parsed.result; + } + + const dynamicConditions = [ ...(parsedResult.dynamicConditions || []) ]; + const quickWhereRaw = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere) + || normalizedWhere.quickWhere; + + if (quickWhereRaw && quickWhereRaw.value && String(quickWhereRaw.value).trim() !== '') { + const quickValue = String(quickWhereRaw.value).trim(); + dynamicConditions.push({ + [Op.or]: { + store_name: { [Op.like]: `%${quickValue}%` }, + receiving_number: { [Op.like]: `%${quickValue}%` }, + tracking_number: { [Op.like]: `%${quickValue}%` }, + creator_snapshot: { [Op.like]: `%${quickValue}%` }, + license_plate: { [Op.like]: `%${quickValue}%` }, + }, + }); + } + + if (dynamicConditions.length > 0) { + queryOptions.where[Op.and].push({ [Op.and]: dynamicConditions }); + } + + // ---- 分页拉取收货单列表 ---- + const RECEIVING_EXPORT_PAGE_SIZE = 200; + const RECEIVING_ITEMS_FETCH_BATCH_SIZE = 50; + + const totalCount = await ctx.model.Receiving.count({ + where: queryOptions.where, + distinct: true, + }); + + await progressHandler({ + status: 'running', + progress: totalCount > 0 ? 10 : 85, + message: totalCount > 0 ? `已命中 ${totalCount} 条收货单,开始导出` : '未命中数据,开始生成空文件', + }); + + const allReceivingOrders = []; + let page = 1; + let fetchedCount = 0; + + while (fetchedCount < totalCount) { + const rows = await ctx.model.Receiving.findAll({ + where: queryOptions.where, + order: [[ actualSortField, sortOrder ]], + limit: RECEIVING_EXPORT_PAGE_SIZE, + offset: (page - 1) * RECEIVING_EXPORT_PAGE_SIZE, + raw: true, + }); + + if (!Array.isArray(rows) || rows.length === 0) { + break; + } + + allReceivingOrders.push(...rows); + fetchedCount += rows.length; + page += 1; + + await progressHandler({ + status: 'running', + progress: Math.min(30, 10 + Math.round((fetchedCount / Math.max(totalCount, 1)) * 20)), + message: `正在拉取收货单列表,已完成 ${fetchedCount}/${totalCount}`, + }); + } + + // ---- 批量拉取收货单明细 ---- + const allReceivingIds = allReceivingOrders.map(r => Number(r.id)).filter(Boolean); + /** @type {Map>} receiving_id → details */ + const detailsMap = new Map(); + + if (allReceivingIds.length > 0) { + const batchSize = RECEIVING_ITEMS_FETCH_BATCH_SIZE; + const totalBatches = Math.ceil(allReceivingIds.length / batchSize); + + for (let batchIdx = 0; batchIdx < allReceivingIds.length; batchIdx += batchSize) { + const batchIds = allReceivingIds.slice(batchIdx, batchIdx + batchSize); + + const details = await ctx.model.ReceivingDetail.findAll({ + where: { receiving_id: { [Op.in]: batchIds } }, + order: [[ 'receiving_id', 'ASC' ], [ 'id', 'ASC' ]], + raw: true, + }); + + for (const detail of details) { + const rid = Number(detail.receiving_id); + if (!detailsMap.has(rid)) { + detailsMap.set(rid, []); + } + detailsMap.get(rid).push(detail); + } + + const currentBatch = Math.floor(batchIdx / batchSize) + 1; + await progressHandler({ + status: 'running', + progress: Math.min(50, 30 + Math.round((currentBatch / totalBatches) * 20)), + message: `正在拉取收货单明细,已完成批次 ${currentBatch}/${totalBatches}`, + }); + } + } + + await progressHandler({ + status: 'running', + progress: 55, + message: '正在生成 Excel 文件...', + }); + + // ---- 生成 Excel(流式写入,两个 Sheet) ---- + const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'wms-receiving-store-export-')); + const now = new Date(); + const dateToken = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}`; + const filename = `收货单导出(货主)_${dateToken}.xlsx`; + const filePath = path.join(tempDir, filename); + const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({ + filename: filePath, + useStyles: false, + useSharedStrings: false, + }); + + const normalizeCellValue = value => { + if (value === null || value === undefined) return ''; + if (value instanceof Date) return app.formatDate ? app.formatDate(value) : value.toISOString(); + return value; + }; + + const statusLabelMap = { + receiving: '收货中', + completed: '已完成', + cancelled: '已作废', + }; + + const detailStatusLabelMap = { + all_matched: '全部匹配', + partial_matched: '部分匹配', + unmatched: '未匹配', + }; + + const storageStatusLabelMap = { + none: '未入库', + waiting: '等待入库', + partial: '部分入库', + all: '全部入库', + }; + + const deliveryMethodLabelMap = { + truck: '货车', + express: '快递', + air_freight: '空运', + sea_freight: '海运', + other: '其他', + }; + + const loadingMethodLabelMap = { + with_pallet: '带托盘', + without_pallet: '不带托盘', + }; + + // Sheet 1: 收货单列表 + const sheet1 = workbook.addWorksheet('收货单列表'); + const receivingColumns = [ + { header: '收货单ID', key: 'id', width: 10 }, + { header: '收货单号', key: 'receiving_number', width: 22 }, + { header: '货主', key: 'store_name', width: 20 }, + { header: '收货状态', key: 'status_label', width: 12 }, + { header: '明细匹配状态', key: 'detail_status_label', width: 14 }, + { header: '入库状态', key: 'storage_status_label', width: 12 }, + { header: '来货方式', key: 'delivery_method_label', width: 12 }, + { header: '车牌号', key: 'license_plate', width: 14 }, + { header: '快递单号', key: 'tracking_number', width: 22 }, + { header: '装卸方式', key: 'loading_method_label', width: 12 }, + { header: '总商品种类', key: 'total_items', width: 12 }, + { header: '总数量', key: 'total_quantity', width: 12 }, + { header: '总箱数', key: 'total_boxes', width: 10 }, + { header: '总托盘数', key: 'total_pallets', width: 10 }, + { header: '审核状态', key: 'is_review_label', width: 10 }, + { header: '创建人', key: 'creator_name', width: 14 }, + { header: '备注', key: 'remark', width: 30 }, + { header: '收货开始时间', key: 'receiving_start_time', width: 20 }, + { header: '收货结束时间', key: 'receiving_end_time', width: 20 }, + { header: '创建时间', key: 'created_at', width: 20 }, + { header: '更新时间', key: 'updated_at', width: 20 }, + ]; + sheet1.columns = receivingColumns; + + for (const row of allReceivingOrders) { + let creatorName = ''; + try { + if (row.creator_snapshot) { + const snapshot = JSON.parse(row.creator_snapshot); + creatorName = snapshot.name || ''; + } + } catch (_) { /* ignore */ } + + sheet1.addRow({ + id: row.id, + receiving_number: normalizeCellValue(row.receiving_number), + store_name: normalizeCellValue(row.store_name), + status_label: statusLabelMap[row.status] || row.status || '', + detail_status_label: detailStatusLabelMap[row.detail_status] || row.detail_status || '', + storage_status_label: storageStatusLabelMap[row.storage_status] || row.storage_status || '', + delivery_method_label: deliveryMethodLabelMap[row.delivery_method] || row.delivery_method || '', + license_plate: normalizeCellValue(row.license_plate), + tracking_number: normalizeCellValue(row.tracking_number), + loading_method_label: loadingMethodLabelMap[row.loading_method] || row.loading_method || '', + total_items: row.total_items, + total_quantity: row.total_quantity, + total_boxes: row.total_boxes, + total_pallets: row.total_pallets, + is_review_label: row.is_review === 1 ? '已审核' : '未审核', + creator_name: creatorName, + remark: normalizeCellValue(row.remark), + receiving_start_time: normalizeCellValue(row.receiving_start_time), + receiving_end_time: normalizeCellValue(row.receiving_end_time), + created_at: normalizeCellValue(row.created_at), + updated_at: normalizeCellValue(row.updated_at), + }).commit(); + } + sheet1.commit(); + + await progressHandler({ + status: 'running', + progress: 70, + message: '正在写入收货单明细...', + }); + + // Sheet 2: 收货单明细 + const sheet2 = workbook.addWorksheet('收货单明细'); + const detailColumns = [ + { header: '收货单号', key: 'receiving_number', width: 22 }, + { header: '收货单ID', key: 'receiving_id', width: 12 }, + { header: '明细ID', key: 'detail_id', width: 10 }, + { header: '商品名称', key: 'product_name', width: 28 }, + { header: '商品条码', key: 'barcode', width: 20 }, + { header: '系统商品ID', key: 'system_product_id', width: 14 }, + { header: '实际收货数量', key: 'actual_quantity', width: 14 }, + { header: '箱数', key: 'box_quantity', width: 10 }, + { header: '托盘数', key: 'pallet_quantity', width: 10 }, + { header: '收货状态', key: 'receiving_status_label', width: 12 }, + { header: '入库状态', key: 'storage_status_label', width: 12 }, + { header: '已入库数量', key: 'stored_quantity', width: 12 }, + { header: '批次号', key: 'batch_number', width: 16 }, + { header: '生产日期', key: 'production_date', width: 14 }, + { header: '到期日期', key: 'expiry_date', width: 14 }, + { header: '备注', key: 'remark', width: 30 }, + { header: '创建时间', key: 'created_at', width: 20 }, + ]; + sheet2.columns = detailColumns; + + const receivingCodeMap = new Map(); + for (const row of allReceivingOrders) { + receivingCodeMap.set(Number(row.id), row.receiving_number || ''); + } + + const detailReceivingStatusLabelMap = { + pending: '待收货', + receiving: '收货中', + completed: '已完成', + cancelled: '已作废', + }; + + const detailStorageStatusLabelMap = { + none: '未入库', + waiting: '等待入库', + partial: '部分入库', + all: '全部入库', + }; + + const itemBatchSize = RECEIVING_ITEMS_FETCH_BATCH_SIZE; + let itemWrittenCount = 0; + const totalReceivingOrders = allReceivingIds.length; + + for (let batchIdx = 0; batchIdx < allReceivingIds.length; batchIdx += itemBatchSize) { + const batchIds = allReceivingIds.slice(batchIdx, batchIdx + itemBatchSize); + + for (const rid of batchIds) { + const receivingNumber = receivingCodeMap.get(rid) || ''; + const details = detailsMap.get(rid) || []; + + for (const detail of details) { + sheet2.addRow({ + receiving_number: receivingNumber, + receiving_id: rid, + detail_id: detail.id, + product_name: normalizeCellValue(detail.product_name), + barcode: normalizeCellValue(detail.barcode), + system_product_id: normalizeCellValue(detail.system_product_id), + actual_quantity: detail.actual_quantity, + box_quantity: detail.box_quantity, + pallet_quantity: detail.pallet_quantity, + receiving_status_label: detailReceivingStatusLabelMap[detail.receiving_status] || detail.receiving_status || '', + storage_status_label: detailStorageStatusLabelMap[detail.storage_status] || detail.storage_status || '', + stored_quantity: detail.stored_quantity, + batch_number: normalizeCellValue(detail.batch_number), + production_date: normalizeCellValue(detail.production_date), + expiry_date: normalizeCellValue(detail.expiry_date), + remark: normalizeCellValue(detail.remark), + created_at: normalizeCellValue(detail.created_at), + }).commit(); + } + + itemWrittenCount += 1; + } + + const currentBatch = Math.floor(batchIdx / itemBatchSize) + 1; + const totalBatches = Math.ceil(totalReceivingOrders / itemBatchSize); + await progressHandler({ + status: 'running', + progress: Math.min(90, 70 + Math.round((currentBatch / totalBatches) * 20)), + message: `正在写入收货单明细,已完成 ${itemWrittenCount}/${totalReceivingOrders} 条收货单`, + }); + } + sheet2.commit(); + + await workbook.commit(); + + await progressHandler({ + status: 'running', + progress: 92, + message: '正在上传文件...', + }); + + // ---- 上传文件 ---- + const uploadService = ctx?.service?.systems?.upload; + if (!uploadService || typeof uploadService.uploadFile !== 'function') { + throw new Error('上传服务不可用'); + } + + const stat = await fsp.stat(filePath); + const randomToken = crypto.randomBytes(6).toString('hex'); + const uploadKey = `exports/receiving/store/${storeId}/${Date.now()}_${randomToken}.xlsx`; const uploadStream = fs.createReadStream(filePath); uploadStream.filename = filename; uploadStream.mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; diff --git a/methods/system.json b/methods/system.json index cd693ff..c09372e 100644 --- a/methods/system.json +++ b/methods/system.json @@ -27761,6 +27761,328 @@ "message": "服务器扫描查询失败" } ] + }, + { + "method": "storage.receiving.export", + "description": "提交收货单导出任务(仓库维度,异步)。导出为 Excel 文件,包含两个 Sheet:Sheet1=收货单列表(ID/单号/货主/状态/明细匹配状态/入库状态/来货方式/车牌号/快递单号/装卸方式/商品种类/总数量/总箱数/总托盘数/审核状态/创建人/备注/收货时间/创建时间/更新时间),Sheet2=收货单明细(收货单号/收货单ID/明细ID/商品名称/商品条码/系统商品ID/实收数量/箱数/托盘数/收货状态/入库状态/已入库数量/批次号/生产日期/到期日期/备注/创建时间)。筛选和排序规则与 getReceivingList 一致,按当前仓库维度(ctx.user.store_id)过滤。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "筛选条件(与 getReceivingList 一致),支持 quickWhere(模糊搜索收货单号/货主名称/快递单号/创建人/车牌号)等字段" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数,支持 sortField(id/receiving_number/status/created_at/updated_at/store_id/warehouse_id)和 sortOrder(ASC/DESC),默认按 created_at DESC" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "导出任务ID,用于轮询进度" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "任务状态:submitted-已提交 / running-执行中 / success-成功 / failed-失败" + }, + { + "name": "progress", + "type": "number", + "required": true, + "description": "任务进度,0-100" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "任务状态描述" + }, + { + "name": "result", + "type": "object", + "required": false, + "description": "导出结果(success 时包含 url/cdnUrl/cosUrl/fileKey 等下载地址信息)" + }, + { + "name": "error", + "type": "string", + "required": false, + "description": "错误信息(failed 时返回)" + }, + { + "name": "update_time", + "type": "number", + "required": true, + "description": "状态更新时间戳(毫秒)" + } + ], + "errors": [ + { + "code": 0, + "message": "用户未绑定仓库" + } + ] + }, + { + "method": "storage.receiving.exportTaskProgress", + "description": "查询收货单导出任务进度(仓库维度)。提交导出任务后,通过 task_id 轮询此接口获取实时进度和最终下载地址。任务缓存 TTL 为 30 分钟。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "task_id", + "type": "string", + "required": false, + "source": "body", + "description": "导出任务ID(下划线写法),与 taskId 二选一" + }, + { + "name": "taskId", + "type": "string", + "required": false, + "source": "body", + "description": "导出任务ID(驼峰写法),与 task_id 二选一" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "导出任务ID" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "任务状态:submitted-已提交 / running-执行中 / success-成功 / failed-失败 / not_found-任务不存在" + }, + { + "name": "progress", + "type": "number", + "required": true, + "description": "任务进度,0-100" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "任务状态描述" + }, + { + "name": "result", + "type": "object", + "required": false, + "description": "导出结果(success 时包含 url/cdnUrl/cosUrl/fileKey 等下载地址信息)" + }, + { + "name": "error", + "type": "string", + "required": false, + "description": "错误信息(failed 时返回)" + }, + { + "name": "download_url", + "type": "string", + "required": false, + "description": "Excel 文件下载地址(success 时有效)" + }, + { + "name": "update_time", + "type": "number", + "required": true, + "description": "状态更新时间戳(毫秒)" + } + ], + "errors": [] + }, + { + "method": "storage.receiving.storeExport", + "description": "提交货主侧收货单导出任务(货主维度,异步)。以当前平台激活的货主 store_id 为维度导出。导出为 Excel 文件,包含两个 Sheet:Sheet1=收货单列表,Sheet2=收货单明细(字段同 export)。筛选和排序规则与 getStoreReceivingList 一致,需当前用户已切换至货主角色。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "筛选条件(与 getStoreReceivingList 一致),支持 quickWhere(模糊搜索收货单号/货主名称/快递单号/创建人/车牌号)等字段" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数,支持 sortField(id/receiving_number/status/created_at/updated_at/store_id/warehouse_id)和 sortOrder(ASC/DESC),默认按 created_at DESC" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "导出任务ID,用于轮询进度" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "任务状态:submitted-已提交 / running-执行中 / success-成功 / failed-失败" + }, + { + "name": "progress", + "type": "number", + "required": true, + "description": "任务进度,0-100" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "任务状态描述" + }, + { + "name": "result", + "type": "object", + "required": false, + "description": "导出结果(success 时包含 url/cdnUrl/cosUrl/fileKey 等下载地址信息)" + }, + { + "name": "error", + "type": "string", + "required": false, + "description": "错误信息(failed 时返回)" + }, + { + "name": "update_time", + "type": "number", + "required": true, + "description": "状态更新时间戳(毫秒)" + } + ], + "errors": [ + { + "code": 0, + "message": "未获取到货主平台激活上下文,请先切换至货主角色" + } + ] + }, + { + "method": "storage.receiving.storeExportTaskProgress", + "description": "查询货主侧收货单导出任务进度。复用 exportTaskProgress 的缓存查询逻辑,任务 ID 前缀不同。任务缓存 TTL 为 30 分钟。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "task_id", + "type": "string", + "required": false, + "source": "body", + "description": "导出任务ID(下划线写法),与 taskId 二选一" + }, + { + "name": "taskId", + "type": "string", + "required": false, + "source": "body", + "description": "导出任务ID(驼峰写法),与 task_id 二选一" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "导出任务ID" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "任务状态:submitted-已提交 / running-执行中 / success-成功 / failed-失败 / not_found-任务不存在" + }, + { + "name": "progress", + "type": "number", + "required": true, + "description": "任务进度,0-100" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "任务状态描述" + }, + { + "name": "result", + "type": "object", + "required": false, + "description": "导出结果(success 时包含 url/cdnUrl/cosUrl/fileKey 等下载地址信息)" + }, + { + "name": "error", + "type": "string", + "required": false, + "description": "错误信息(failed 时返回)" + }, + { + "name": "download_url", + "type": "string", + "required": false, + "description": "Excel 文件下载地址(success 时有效)" + }, + { + "name": "update_time", + "type": "number", + "required": true, + "description": "状态更新时间戳(毫秒)" + } + ], + "errors": [] } ] }, From 635e86f984e74128cc18029e4024df3a2c529b5a Mon Sep 17 00:00:00 2001 From: liufumingren Date: Wed, 29 Jul 2026 13:57:04 +0800 Subject: [PATCH 136/550] =?UTF-8?q?chore:=20=E6=8F=90=E4=BA=A4=E5=BD=93?= =?UTF-8?q?=E5=89=8D=E6=89=80=E6=9C=89=E5=8F=98=E6=9B=B4=EF=BC=8C=E5=87=86?= =?UTF-8?q?=E5=A4=87=E5=BC=80=E5=A7=8B=20allocateSubOrderNumber=20step=3D4?= =?UTF-8?q?=20=E6=94=B9=E9=80=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/model/after_sale_work_order.js | 267 ++++++++ app/model/after_sale_work_order_step.js | 99 +++ app/model/print_computer.js | 6 - app/service/qimenMethods/order.js | 73 +- .../systemMethods/order/pendingOrder.js | 121 +++- app/service/systemMethods/printComputer.js | 2 +- app/service/systems/express_platform.js | 28 +- app/service/systems/printComputer.js | 10 +- database/designs/after-sale-api-design.md | 644 ++++++++++++++++++ .../designs/after-sale-work-order-design.md | 440 ++++++++++++ database/designs/waybill-module-design.md | 579 ++++++++++++++++ ...remote-play-url-from-wms-print-computer.js | 28 + ...g-config-fields-from-wms-print-computer.js | 43 ++ ...cording-directory-to-wms-print-computer.js | 28 + ...120000-create-wms-after-sale-work-order.js | 215 ++++++ ...rding-size-fields-to-wms-print-computer.js | 35 + ...0-create-wms-after-sale-work-order-step.js | 115 ++++ methods/changes/system.json | 43 ++ methods/system.json | 47 ++ 19 files changed, 2792 insertions(+), 31 deletions(-) create mode 100644 app/model/after_sale_work_order.js create mode 100644 app/model/after_sale_work_order_step.js create mode 100644 database/designs/after-sale-api-design.md create mode 100644 database/designs/after-sale-work-order-design.md create mode 100644 database/designs/waybill-module-design.md create mode 100644 database/migrations/20260728000000-remove-remote-play-url-from-wms-print-computer.js create mode 100644 database/migrations/20260728100000-remove-recording-config-fields-from-wms-print-computer.js create mode 100644 database/migrations/20260728110000-restore-recording-directory-to-wms-print-computer.js create mode 100644 database/migrations/20260728120000-create-wms-after-sale-work-order.js create mode 100644 database/migrations/20260728120000-restore-recording-size-fields-to-wms-print-computer.js create mode 100644 database/migrations/20260728130000-create-wms-after-sale-work-order-step.js diff --git a/app/model/after_sale_work_order.js b/app/model/after_sale_work_order.js new file mode 100644 index 0000000..0d7e9dd --- /dev/null +++ b/app/model/after_sale_work_order.js @@ -0,0 +1,267 @@ +'use strict'; + +module.exports = app => { + const { STRING, BIGINT, INTEGER, TINYINT, TEXT, DATE, DECIMAL } = app.Sequelize; + + /** + * 售后工单业务类型定义 + * 外部可通过 require('./app/model/after_sale_work_order').BUSINESS_TYPES 访问 + * 增删业务类型或子类型只需修改此常量,无需 ALTER TABLE + */ + const BUSINESS_TYPES = { + waybill: { + label: '运单', + table: 'wms_order_express', + subtypes: { + intercept: '拦截', + urge: '催件', + damage: '破损', + lost: '丢件', + wrong_info: '信息错误', + }, + }, + order_delivery: { + label: '发货订单', + table: 'wms_order_delivery', + subtypes: { + mis_shipment: '错发', + missing_item: '少发', + wrong_sku: '错品', + quality_issue: '质量问题', + delivery_delay: '发货延迟', + }, + }, + entry_order: { + label: '入库单', + table: 'wms_entry_order', + subtypes: { + shortage: '少货', + damage: '破损', + wrong_sku: '错品', + quality_issue: '质量问题', + }, + }, + order_stockout: { + label: '出库单/退货出库单', + table: 'wms_order_stockout', + subtypes: { + return_issue: '退货异常', + wrong_outbound: '错发', + shortage: '少发', + }, + }, + receiving: { + label: '收货单', + table: 'wms_receiving', + subtypes: { + shortage: '少货', + damage: '破损', + quality_issue: '质量问题', + }, + }, + other: { + label: '其他', + table: null, + subtypes: { + general: '通用', + }, + }, + }; + + /** + * 根据 business_type 获取关联表名 + * @param {string} businessType 业务类型 + * @returns {string|null} 关联表名 + */ + function getBusinessTable(businessType) { + return BUSINESS_TYPES[businessType]?.table || null; + } + + /** + * 校验 business_type + business_sub_type 组合是否合法 + * @param {string} businessType 业务类型 + * @param {string} businessSubType 业务子类型 + * @returns {boolean} 是否合法 + */ + function isValidSubType(businessType, businessSubType) { + const def = BUSINESS_TYPES[businessType]; + return def && Object.prototype.hasOwnProperty.call(def.subtypes, businessSubType); + } + + const AfterSaleWorkOrder = app.model.define('after_sale_work_order', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键ID', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '货主ID', + }, + work_order_no: { + type: STRING(50), + allowNull: false, + comment: '售后工单号,唯一', + }, + business_type: { + type: STRING(50), + allowNull: false, + comment: '关联业务类型', + }, + business_sub_type: { + type: STRING(50), + allowNull: false, + comment: '关联业务子类型', + }, + business_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '关联业务单据主键ID(多态关联)', + }, + business_no: { + type: STRING(100), + allowNull: true, + comment: '关联业务单据号(冗余)', + }, + direction: { + type: TINYINT.UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '记账方向:0=未确定 1=入库 2=出库', + }, + status: { + type: TINYINT.UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '工单状态:0=待处理 1=处理中 2=已完成 3=已关闭 9=已取消', + }, + priority: { + type: TINYINT.UNSIGNED, + allowNull: false, + defaultValue: 50, + comment: '优先级:1~100,数字越大优先级越高', + }, + title: { + type: STRING(200), + allowNull: false, + comment: '工单标题/摘要', + }, + description: { + type: TEXT, + allowNull: true, + comment: '问题描述', + }, + creator_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '创建人ID,关联 account.id;0 表示 AI 自动接待', + }, + creator_snapshot: { + type: TEXT, + allowNull: true, + comment: '创建人信息快照(JSON格式);AI创建时记录模型/会话信息', + }, + assignee_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '当前处理人ID,关联 account.id', + }, + parent_work_order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '父工单ID,自关联本表;非空时表示子工单', + }, + current_step: { + type: TINYINT.UNSIGNED, + allowNull: false, + defaultValue: 1, + comment: '当前进度,值为当前正在处理的 step_order 序号', + }, + claim_needed: { + type: TINYINT.UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '是否需要理赔:0=不需要 1=需要', + }, + claim_amount: { + type: DECIMAL(12, 2), + allowNull: true, + defaultValue: 0.00, + comment: '理赔金额(元)', + }, + claim_status: { + type: TINYINT.UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '理赔状态:0=未理赔 1=已理赔(单笔结清) 2=月结', + }, + resolution: { + type: TEXT, + allowNull: true, + comment: '处理结果说明', + }, + resolved_at: { + type: DATE, + allowNull: true, + comment: '解决时间', + }, + created_at: { + type: DATE, + allowNull: false, + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + comment: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + tableName: 'wms_after_sale_work_order', + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: true, + deletedAt: 'deleted_at', + comment: '售后工单主表', + }); + + AfterSaleWorkOrder.associate = () => { + // 自关联:父工单 → 子工单 + AfterSaleWorkOrder.hasMany(app.model.AfterSaleWorkOrder, { + foreignKey: 'parent_work_order_id', + sourceKey: 'id', + as: 'children', + }); + AfterSaleWorkOrder.belongsTo(app.model.AfterSaleWorkOrder, { + foreignKey: 'parent_work_order_id', + targetKey: 'id', + as: 'parent', + }); + + // 关联进度步骤表 + AfterSaleWorkOrder.hasMany(app.model.AfterSaleWorkOrderStep, { + foreignKey: 'work_order_id', + sourceKey: 'id', + as: 'steps', + }); + }; + + // 挂载业务类型常量及辅助函数到 Model + AfterSaleWorkOrder.BUSINESS_TYPES = BUSINESS_TYPES; + AfterSaleWorkOrder.getBusinessTable = getBusinessTable; + AfterSaleWorkOrder.isValidSubType = isValidSubType; + + return AfterSaleWorkOrder; +}; diff --git a/app/model/after_sale_work_order_step.js b/app/model/after_sale_work_order_step.js new file mode 100644 index 0000000..dc66ba4 --- /dev/null +++ b/app/model/after_sale_work_order_step.js @@ -0,0 +1,99 @@ +'use strict'; + +module.exports = app => { + const { STRING, BIGINT, TINYINT, TEXT, DATE } = app.Sequelize; + + const AfterSaleWorkOrderStep = app.model.define('after_sale_work_order_step', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键ID', + }, + work_order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '工单ID,关联 wms_after_sale_work_order.id', + }, + step_order: { + type: TINYINT.UNSIGNED, + allowNull: false, + defaultValue: 1, + comment: '步骤序号(从1开始递增)', + }, + step_name: { + type: STRING(100), + allowNull: false, + comment: '步骤名称', + }, + step_status: { + type: TINYINT.UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '步骤状态:0=待开始 1=进行中 2=已完成 3=已跳过', + }, + operator_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '操作员工ID,关联 account.id', + }, + operator_snapshot: { + type: TEXT, + allowNull: true, + comment: '操作人信息快照(JSON格式)', + }, + action: { + type: STRING(100), + allowNull: true, + comment: '操作动作描述', + }, + remark: { + type: TEXT, + allowNull: true, + comment: '处理备注', + }, + started_at: { + type: DATE, + allowNull: true, + comment: '步骤开始时间', + }, + completed_at: { + type: DATE, + allowNull: true, + comment: '步骤完成时间', + }, + created_at: { + type: DATE, + allowNull: false, + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + comment: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + tableName: 'wms_after_sale_work_order_step', + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: true, + deletedAt: 'deleted_at', + comment: '售后工单进度步骤表', + }); + + AfterSaleWorkOrderStep.associate = () => { + AfterSaleWorkOrderStep.belongsTo(app.model.AfterSaleWorkOrder, { + foreignKey: 'work_order_id', + targetKey: 'id', + as: 'workOrder', + }); + }; + + return AfterSaleWorkOrderStep; +}; diff --git a/app/model/print_computer.js b/app/model/print_computer.js index 4f60b0e..2d8c463 100644 --- a/app/model/print_computer.js +++ b/app/model/print_computer.js @@ -50,12 +50,6 @@ module.exports = app => { defaultValue: null, comment: '录制存储单位:KB/MB/GB/TB', }, - remote_play_url: { - type: STRING(500), - allowNull: true, - defaultValue: null, - comment: '远程播放地址', - }, recording_directory: { type: STRING(500), allowNull: true, diff --git a/app/service/qimenMethods/order.js b/app/service/qimenMethods/order.js index afe6bc1..400217b 100644 --- a/app/service/qimenMethods/order.js +++ b/app/service/qimenMethods/order.js @@ -222,14 +222,66 @@ class orderServer extends MainService { return this.fail('订单已同步,不可取消,已转为拦截处理'); } - await existingOrder.update({ + // 检查是否在波次中,若在波次中需清除波次关联 + const existingWaveId = Number(existingOrder.wave_id || 0); + + const updateValues = { status: 'cancel', outbound_status: 'fin', step: 4, updated_at: new Date(), - }, { - transaction, - }); + }; + if (existingWaveId > 0) { + updateValues.wave_id = 0; + updateValues.wave_no = ''; + } + + await existingOrder.update(updateValues, { transaction }); + + // 波次清理:删除波次索引、更新波次统计 + if (existingWaveId > 0) { + try { + await ctx.service.systemMethods.order.wave.deleteOrderWaveIndexByOrderIds({ + warehouseId: info.warehouseId, + orderIds: [existingOrder.id], + transaction, + }); + + const { Op } = this.app.Sequelize; + const WaveBatch = ctx.model.WaveBatch; + if (WaveBatch) { + await WaveBatch.decrement('total_orders', { + by: 1, + where: { + wave_id: existingWaveId, + warehouse_id: info.warehouseId, + total_orders: { [Op.gt]: 0 }, + }, + transaction, + }); + + const wave = await WaveBatch.findOne({ + where: { wave_id: existingWaveId, warehouse_id: info.warehouseId }, + attributes: ['wave_id', 'total_orders', 'wave_status'], + raw: true, + transaction, + }); + + if (wave) { + 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: new Date() }, + { where: { wave_id: existingWaveId, warehouse_id: info.warehouseId }, transaction } + ); + } + } + } + } catch (waveErr) { + ctx.logger.warn('[QimenOrderCancel] 清理波次关联失败,不影响订单取消', waveErr); + } + } // 释放储位分配锁定库存(wms_storage / wms_stock_warehouse) await this.releaseStorageLockForCancel({ @@ -240,6 +292,19 @@ class orderServer extends MainService { await transaction.commit(); + // 波次策略扫描清理(不影响主流程) + if (existingWaveId > 0) { + try { + ctx.service.systemMethods.order.wave.enqueueWaveStrategyQuickScanPostOrderChange( + info.warehouseId, + [existingOrder.id], + { triggerScan: true, source: 'qimenCancel' } + ); + } catch (scanErr) { + ctx.logger.warn('[QimenOrderCancel] 波次策略扫描触发失败,不影响主流程', scanErr); + } + } + // 写入取消操作日志(不影响主流程) try { if (ctx.model && ctx.model.OperationLog) { diff --git a/app/service/systemMethods/order/pendingOrder.js b/app/service/systemMethods/order/pendingOrder.js index a5dcaf2..c8cb73a 100644 --- a/app/service/systemMethods/order/pendingOrder.js +++ b/app/service/systemMethods/order/pendingOrder.js @@ -540,9 +540,9 @@ class PendingOrderService extends OrderBaseService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateExpressCodeTaskProgress,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,updateOrderPlatform,updateOrderExpress,updateRemark,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill,allocateSubOrderNumber,allocateSubOrderNumberProgress'; - const _noNeedLog = 'list,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateExpressCodeTaskProgress,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill,allocateSubOrderNumber,allocateSubOrderNumberProgress'; - const _noNeedAuth = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateExpressCodeTaskProgress,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,updateOrderPlatform,updateOrderExpress,updateRemark,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill,allocateSubOrderNumber,allocateSubOrderNumberProgress'; + const _noNeedRight = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateExpressCodeTaskProgress,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,updateOrderPlatform,updateOrderExpress,updateRemark,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill,allocateSubOrderNumber,allocateSubOrderNumberProgress,batchMarkPrinted'; + const _noNeedLog = 'list,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateExpressCodeTaskProgress,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill,allocateSubOrderNumber,allocateSubOrderNumberProgress,batchMarkPrinted'; + const _noNeedAuth = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateExpressCodeTaskProgress,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,updateOrderPlatform,updateOrderExpress,updateRemark,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill,allocateSubOrderNumber,allocateSubOrderNumberProgress,batchMarkPrinted'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -6328,6 +6328,121 @@ class PendingOrderService extends OrderBaseService { }); } + /** + * 批量设置订单为已打印状态。 + * + * 将给定订单 ID 列表中属于当前仓库的订单的 print_status 更新为 'fin'。 + * 先查 current 表(wms_order_delivery_{warehouseId}),再查 dispatch 表 + * (wms_order_delivery_{warehouseId}_dispatch)兜底。 + * 仅允许 step 在 [1,2,3] 且 status 不为 'cancel' 的订单操作,已打印(print_status='fin')的订单会被静默跳过。 + * + * @param {Object} data 请求体。 + * @param {Array|number|string} [data.order_ids] 订单ID集合(下划线写法)。 + * @param {Array|number|string} [data.orderIds] 订单ID集合(驼峰别名)。 + * @param {Array|number|string} [data.ids] 订单ID集合(简写别名)。 + * @return {Promise} 统一 success 包装的更新结果。 + */ + async batchMarkPrinted(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const warehouseId = this.getWarehouseId(); + const operator = this.getOrderLogOperator(); + const logWarehouseId = this.getOrderLogWarehouseId(warehouseId); + + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + + const rawIds = requestData.order_ids !== undefined ? requestData.order_ids + : requestData.orderIds !== undefined ? requestData.orderIds + : requestData.ids; + const orderIds = this.normalizeIdsInput(rawIds); + if (orderIds.length === 0) { + throw new Error('order_ids 参数不能为空或格式错误'); + } + + const { Op } = this.app.Sequelize; + const now = new Date(); + + const buildWhere = () => ({ + step: { [Op.in]: [1, 2, 3] }, + status: { [Op.ne]: 'cancel' }, + print_status: { [Op.ne]: 'fin' }, + }); + + // 1. 先查 current 表 + const currentModel = await this.getOrderModel('order', warehouseId); + const currentWhere = { + ...this.buildOrderWhere(orderIds, warehouseId), + ...buildWhere(), + }; + + const [ currentAffected ] = await currentModel.update( + { print_status: 'fin', updated_at: now }, + { where: currentWhere } + ); + let updatedCount = Number(currentAffected || 0); + + // 2. 查询 current 表中已存在的订单 ID,计算出未命中的 ID + const currentFoundRows = await currentModel.findAll({ + attributes: ['id'], + where: this.buildOrderWhere(orderIds, warehouseId), + raw: true, + }); + const currentFoundIds = new Set( + (Array.isArray(currentFoundRows) ? currentFoundRows : []).map(row => Number(row.id)) + ); + const missingIds = orderIds.filter(id => !currentFoundIds.has(id)); + + // 3. dispatch 表兜底 + if (missingIds.length > 0) { + try { + const dispatchModel = await this.ctx.model.OrderDeliveryFactory.getDispatchModel(warehouseId); + if (dispatchModel && typeof dispatchModel.update === 'function') { + const dispatchWhere = { + id: { [Op.in]: missingIds }, + warehouse_id: warehouseId, + ...buildWhere(), + }; + + const [ dispatchAffected ] = await dispatchModel.update( + { print_status: 'fin', updated_at: now }, + { where: dispatchWhere } + ); + updatedCount += Number(dispatchAffected || 0); + } + } catch (dispatchErr) { + this.ctx.logger.warn('[PendingOrderService.batchMarkPrinted] dispatch 表更新失败,不影响 current 表结果', dispatchErr); + } + } + + // 写入操作日志(不影响主流程) + try { + const opLogService = this.ctx && this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.operationLog; + if (opLogService && typeof opLogService.createOperationLogs === 'function') { + const logPayloads = orderIds.map(orderId => ({ + businessType: 'order', + businessId: String(orderId), + operationCode: 'ORDER_BATCH_MARK_PRINTED', + operator, + extras: { + warehouseId: logWarehouseId, + orderId, + message: `批量标记已打印:订单 ${orderId}`, + }, + beforeChanges: null, + })); + await opLogService.createOperationLogs(logPayloads); + } + } catch (logErr) { + this.ctx.logger.warn('[PendingOrderService.batchMarkPrinted] 写入操作日志失败,不影响业务', logErr); + } + + return this.success('ok', { + updated_count: updatedCount, + ids: orderIds, + }); + } + } module.exports = PendingOrderService; diff --git a/app/service/systemMethods/printComputer.js b/app/service/systemMethods/printComputer.js index d137003..7aeae5e 100644 --- a/app/service/systemMethods/printComputer.js +++ b/app/service/systemMethods/printComputer.js @@ -39,7 +39,7 @@ class PrintComputerService extends MainService { /** * 设置录制电脑(会先取消同仓库下其他录制电脑)。 - * @param {Object} data { id, recording_size_value, recording_size_unit, remote_play_url, recording_directory } + * @param {Object} data { id, recording_size_value, recording_size_unit, recording_directory } * @return {Promise} 设置结果 */ async setRecording(data) { diff --git a/app/service/systems/express_platform.js b/app/service/systems/express_platform.js index bd2ccc1..72c3eea 100644 --- a/app/service/systems/express_platform.js +++ b/app/service/systems/express_platform.js @@ -690,6 +690,7 @@ class ExpressPlatformService extends MainService { const order_bizcontent = { orders: orders.map(order_tmp => { const order = order_tmp.order_delivery; + console.log('order', order); const expressListItem = ExpressList.find(item => item.code === listByWarehousePlatformCode.sys_express_code) || {}; let playload = { object_Id: `${order.warehouse_id}_${order.id}_${order_tmp.business_key}`, // 菠萝派平台要求订单唯一标识必须为字符串 @@ -729,6 +730,7 @@ class ExpressPlatformService extends MainService { inputsite: listByWarehousePlatformCode.site_code || '', sitecode: listByWarehousePlatformCode.site_code || '', shipperno: listByWarehousePlatformCode.shipperno || '', + customercode: listByWarehousePlatformCode.shipperno || listByWarehousePlatformCode.client_id || '', sender: { company: listByWarehousePlatformCode.shop_name || '', name: listByWarehousePlatformCode.sender_name || '', @@ -743,7 +745,7 @@ class ExpressPlatformService extends MainService { receiver: { name: order.name || '', company: order.company || '', - phone: order.sys_platform_code === 'KS' ? undefined : (order.mobile || order.tel || ''), + phone: order.sys_platform_code === 'KS' || order.sys_platform_code === 'KS' ? undefined : (order.mobile || order.tel || ''), mobile: order.mobile || order.tel || '', country: order.country_code || 'CN', province: order.province || '', @@ -766,6 +768,9 @@ class ExpressPlatformService extends MainService { labelformat: listByWarehousePlatformCode.labelformat || '', extraInfo: ExpressList.find(item => item.code === listByWarehousePlatformCode.sys_express_code)?.polyapi_extra_info || '', }; + console.log("matchedPlatform.platid",matchedPlatform.platid); + console.log("startPlayload",playload); + if (Number(matchedPlatform.platid) === 673) { playload.BizVersion = '2'; playload.brandno = listByWarehousePlatformCode.brandno || ''; @@ -779,6 +784,7 @@ class ExpressPlatformService extends MainService { providercode, numpackage, businessplat, + oaid, ordertype, businessType, codpaymoney, @@ -789,6 +795,7 @@ class ExpressPlatformService extends MainService { ordersource, shipperno, sitecode, + customercode, goods, sender = {}, receiver = {}, @@ -836,6 +843,8 @@ class ExpressPlatformService extends MainService { sitecode, customername, goods, + oaid, + customercode: customercode || shipperno || listByWarehousePlatformCode.shipperno || listByWarehousePlatformCode.client_id || '', sender: { name: senderName, phone: senderPhoneRaw, @@ -870,7 +879,8 @@ class ExpressPlatformService extends MainService { if (!order.extend_props.ewaybill_order_code) { throw new Error('订单数据错误,参数不全缺失extend_props.ewaybill_order_code,请复制次信息给ERP方反馈'); } - playload.oaid = order.extend_props.ewaybill_order_code; + playload.oaid = order.extend_props.ewaybill_order_code||order.oaid||undefined; + playload.transtype = '0'; playload.Mallmaskid = order.buyer_nick; playload.mainsubpaymode = '1'; @@ -897,6 +907,8 @@ class ExpressPlatformService extends MainService { api: 'Differ.JH.Logistics.PostOrder', response: JSON.stringify(result), }); + console.log("分配运单号结果",result); + if (result && result.code !== '10000') { const postOrderErrorMessage = String( result.submessage || result.message || '菠萝派平台接口调用失败' @@ -981,8 +993,8 @@ class ExpressPlatformService extends MainService { case 'JD':{ const batchPrintSipshopid = String(listByWarehousePlatformCode.platform_shop_id || '0'); const batchPrintOrders = (result.results || []).map(item => ({ - orderno: String(item.orderno || ''), - logisticno: String(item.logisticno || item.waybill_code || ''), + orderno: String(item.orderno), + logisticno: String(item.logisticno), outputformat: 'JH_PDF', labelformat: 'JH_A4', printobjecttype: 'JH_Label', @@ -1007,18 +1019,18 @@ class ExpressPlatformService extends MainService { cargoname: '', senddata: '', weight: '', + eCustomerCode: '', remark: '', - carrier: batchPrintSipshopid, selleruserid: '', - printno: '', + printno: "", iscloudprint: 'false', needprintdetail: 'false', extenddata: '', providercode: String(item.procode || item.realcpcode || item.logisticcompanycode || ''), packageno: '', fontsize: '', - platorderno: String(item.plattradeno || item.platorderno || item.orderno || ''), - sipshopid: batchPrintSipshopid, + platorderno: "", + sipshopid: 0, })); console.log('京东批量打印请求参数', JSON.stringify({ api: 'Differ.JH.Logistics.BatchPrintOrder', diff --git a/app/service/systems/printComputer.js b/app/service/systems/printComputer.js index f973085..8ae474b 100644 --- a/app/service/systems/printComputer.js +++ b/app/service/systems/printComputer.js @@ -154,7 +154,7 @@ class PrintComputerService extends Service { * 设置录制电脑。 * 会将同仓库下其他已设为录制的电脑取消,再设置当前电脑为录制。 * @param {number} id 电脑ID - * @param {Object} data { recording_size_value, recording_size_unit, remote_play_url, recording_directory } + * @param {Object} data { recording_size_value, recording_size_unit, recording_directory } * @return {Promise} 更新后的记录 */ async setRecording(id, data) { @@ -176,11 +176,6 @@ class PrintComputerService extends Service { throw new Error(`存储单位不合法,支持:${VALID_UNITS.join('/')}`); } - const url = String(data.remote_play_url || '').trim(); - if (!/^https?:\/\/.+/.test(url)) { - throw new Error('远程播放地址必须以 http:// 或 https:// 开头'); - } - const directory = String(data.recording_directory || '').trim(); if (!directory) { throw new Error('录制目录不能为空'); @@ -198,7 +193,6 @@ class PrintComputerService extends Service { is_recording: false, recording_size_value: null, recording_size_unit: null, - remote_play_url: null, recording_directory: null, }, { @@ -215,7 +209,6 @@ class PrintComputerService extends Service { is_recording: true, recording_size_value: sizeValue, recording_size_unit: unit, - remote_play_url: url, recording_directory: directory, }); @@ -261,7 +254,6 @@ class PrintComputerService extends Service { is_recording: false, recording_size_value: null, recording_size_unit: null, - remote_play_url: null, recording_directory: null, }); diff --git a/database/designs/after-sale-api-design.md b/database/designs/after-sale-api-design.md new file mode 100644 index 0000000..b4a4bd3 --- /dev/null +++ b/database/designs/after-sale-api-design.md @@ -0,0 +1,644 @@ +# 售后工单 API 接口设计方案 + +> **状态**: ⏳ 等待人工审阅 +> **设计日期**: 2026-07-29 +> **设计人**: wms-db-agent +> **说明**: 本文档仅输出 API 接口设计方案,不直接修改程序代码。审阅通过后再执行实现。 + +--- + +## 一、模块概览 + +| 项目 | 说明 | +|------|------| +| 模块名 | `afterSale` | +| 接口路径 | `POST /system`,body 中 `method` 字段为 `afterSale.{方法名}` | +| 请求方式 | 全部 `POST`,参数放在 `body` 内 | +| 鉴权 | 除 `businessTypes` 外均需登录;写操作需鉴权 | + +### 文件规划 + +``` +app/service/systemMethods/afterSale.js ← 入口层(鉴权、参数校验、委托) +app/service/systems/afterSale.js ← 业务层(数据库操作、状态机) +methods/system.json ← API 文档(追加 afterSale group) +``` + +### 调用链路 + +``` +POST /system { method: "afterSale.list", ... } + → app/router.js + → app/service/system.js + → app/service/systemMethods/afterSale.js ← 鉴权 + 参数校验 + → app/service/systems/afterSale.js ← 业务逻辑 + DB操作 + → app/model/after_sale_work_order.js ← Sequelize Model + → app/model/after_sale_work_order_step.js +``` + +--- + +## 二、接口清单(共 13 个) + +| # | method | 描述 | 需登录 | 需鉴权 | +|---|--------|------|--------|--------| +| 1 | `afterSale.businessTypes` | 获取内置业务类型及子类型枚举 | ✗ | ✗ | +| 2 | `afterSale.list` | 工单列表(分页+筛选) | ✓ | ✗ | +| 3 | `afterSale.detail` | 工单详情(含步骤列表) | ✓ | ✗ | +| 4 | `afterSale.create` | 创建工单 | ✓ | ✓ | +| 5 | `afterSale.update` | 更新工单基本信息 | ✓ | ✓ | +| 6 | `afterSale.delete` | 删除工单(软删除) | ✓ | ✓ | +| 7 | `afterSale.assign` | 分配处理人 | ✓ | ✓ | +| 8 | `afterSale.complete` | 完成工单 | ✓ | ✓ | +| 9 | `afterSale.close` | 关闭工单 | ✓ | ✓ | +| 10 | `afterSale.cancel` | 取消工单 | ✓ | ✓ | +| 11 | `afterSale.stepStart` | 开始某个步骤 | ✓ | ✓ | +| 12 | `afterSale.stepComplete` | 完成某个步骤 | ✓ | ✓ | +| 13 | `afterSale.stepSkip` | 跳过某个步骤 | ✓ | ✓ | + +--- + +## 三、接口详细设计 + +### 3.1 `afterSale.businessTypes` — 获取业务类型枚举 + +```json +{ + "method": "afterSale.businessTypes", + "description": "获取售后工单内置业务类型及子类型枚举,供前端下拉选择使用。数据来源:app/model/after_sale_work_order.js 中的 BUSINESS_TYPES 常量。", + "isNeedAuth": false, + "isNeedLogin": false, + "params": [], + "response": [ + { + "name": "data", + "type": "object", + "description": "业务类型枚举,key 为 business_type,value 含 label、table、subtypes", + "example": { + "waybill": { + "label": "运单", + "table": "wms_order_express", + "subtypes": { + "intercept": "拦截", + "urge": "催件", + "damage": "破损", + "lost": "丢件", + "wrong_info": "信息错误" + } + }, + "order_delivery": { + "label": "发货订单", + "table": "wms_order_delivery", + "subtypes": { + "mis_shipment": "错发", + "missing_item": "少发", + "wrong_sku": "错品", + "quality_issue": "质量问题", + "delivery_delay": "发货延迟" + } + } + } + } + ] +} +``` + +--- + +### 3.2 `afterSale.list` — 工单列表 + +```json +{ + "method": "afterSale.list", + "description": "查询售后工单列表,支持分页与多条件筛选。仓库隔离(自动注入 warehouse_id)。", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数 { page, pageSize },默认 page=1 pageSize=20" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "筛选条件,所有字段均为可选", + "children": [ + { "name": "workOrderNo", "type": "string", "description": "工单号(模糊搜索)" }, + { "name": "businessType", "type": "string", "description": "业务类型(等值),如 waybill" }, + { "name": "businessSubType","type": "string", "description": "业务子类型(等值),如 intercept" }, + { "name": "businessNo", "type": "string", "description": "关联业务单据号(模糊)" }, + { "name": "status", "type": "number", "description": "工单状态(等值):0/1/2/3/9" }, + { "name": "priorityMin", "type": "number", "description": "优先级下限(>=)" }, + { "name": "priorityMax", "type": "number", "description": "优先级上限(<=)" }, + { "name": "claimStatus", "type": "number", "description": "理赔状态(等值):0/1/2" }, + { "name": "assigneeId", "type": "number", "description": "处理人ID(等值)" }, + { "name": "creatorId", "type": "number", "description": "创建人ID(等值)" }, + { "name": "keyword", "type": "string", "description": "关键词:匹配工单号/标题/业务单据号" }, + { "name": "createdAtStart", "type": "string", "description": "创建时间起始(YYYY-MM-DD)" }, + { "name": "createdAtEnd", "type": "string", "description": "创建时间截止(YYYY-MM-DD)" } + ] + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序 { field: 'priority'|'created_at'|'status', order: 'asc'|'desc' },默认 priority desc" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "description": "工单列表(不含 description/resolution 长文本,减少传输量)", + "children": [ + { "name": "id", "type": "number", "description": "工单ID" }, + { "name": "work_order_no", "type": "string", "description": "工单号" }, + { "name": "warehouse_id", "type": "number", "description": "仓库ID" }, + { "name": "store_id", "type": "number", "description": "货主ID" }, + { "name": "business_type", "type": "string", "description": "业务类型" }, + { "name": "business_sub_type","type": "string", "description": "业务子类型" }, + { "name": "business_id", "type": "number", "description": "关联单据ID" }, + { "name": "business_no", "type": "string", "description": "关联单据号" }, + { "name": "direction", "type": "number", "description": "记账方向:0/1/2" }, + { "name": "status", "type": "number", "description": "工单状态:0/1/2/3/9" }, + { "name": "priority", "type": "number", "description": "优先级:1-100" }, + { "name": "title", "type": "string", "description": "工单标题" }, + { "name": "creator_id", "type": "number", "description": "创建人ID" }, + { "name": "creator_name", "type": "string", "description": "创建人姓名(JOIN account)" }, + { "name": "assignee_id", "type": "number", "description": "当前处理人ID" }, + { "name": "assignee_name", "type": "string", "description": "当前处理人姓名(JOIN account)" }, + { "name": "parent_work_order_id","type":"number","description": "父工单ID" }, + { "name": "current_step", "type": "number", "description": "当前进度步骤序号" }, + { "name": "claim_needed", "type": "number", "description": "是否理赔" }, + { "name": "claim_amount", "type": "number", "description": "理赔金额" }, + { "name": "claim_status", "type": "number", "description": "理赔状态" }, + { "name": "resolved_at", "type": "string", "description": "解决时间" }, + { "name": "created_at", "type": "string", "description": "创建时间" }, + { "name": "updated_at", "type": "string", "description": "更新时间" } + ] + }, + { "name": "pagination", "type": "object", "description": "分页信息 { page, pageSize, total, totalPages }" } + ] +} +``` + +--- + +### 3.3 `afterSale.detail` — 工单详情 + +```json +{ + "method": "afterSale.detail", + "description": "查询单个工单详情,含完整字段 + 步骤列表。仓库隔离。", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "工单ID(必填)" + } + ], + "response": [ + { + "name": "data", + "type": "object", + "description": "工单完整信息", + "children": [ + { "name": "id", "type": "number", "description": "工单ID" }, + { "name": "...", "type": "", "description": "同 list 接口所有字段" }, + { "name": "description", "type": "string", "description": "问题描述(详情接口返回)" }, + { "name": "resolution", "type": "string", "description": "处理结果说明(详情接口返回)" }, + { "name": "creator_snapshot", "type": "string", "description": "创建人信息快照" }, + { "name": "steps", "type": "array", "description": "步骤列表", + "children": [ + { "name": "id", "type": "number", "description": "步骤ID" }, + { "name": "step_order", "type": "number", "description": "步骤序号" }, + { "name": "step_name", "type": "string", "description": "步骤名称" }, + { "name": "step_status", "type": "number", "description": "步骤状态:0/1/2/3" }, + { "name": "operator_id", "type": "number", "description": "操作人ID" }, + { "name": "operator_name", "type": "string", "description": "操作人姓名" }, + { "name": "operator_snapshot","type": "string", "description": "操作人快照" }, + { "name": "action", "type": "string", "description": "操作动作" }, + { "name": "remark", "type": "string", "description": "处理备注" }, + { "name": "started_at", "type": "string", "description": "开始时间" }, + { "name": "completed_at", "type": "string", "description": "完成时间" }, + { "name": "created_at", "type": "string", "description": "创建时间" } + ] + }, + { "name": "children", "type": "array", "description": "子工单列表(如有)" }, + { "name": "parent", "type": "object", "description": "父工单简要信息(如有)" } + ] + } + ], + "errors": [ + { "code": "400", "description": "工单ID不能为空" }, + { "code": "404", "description": "工单不存在或无权访问" } + ] +} +``` + +--- + +### 3.4 `afterSale.create` — 创建工单 + +```json +{ + "method": "afterSale.create", + "description": "创建售后工单。自动生成工单号(AS+时间戳),自动设置 creator_id 和 warehouse_id。创建成功后返回工单详情。", + "isNeedAuth": true, + "isNeedLogin": true, + "params": [ + { + "name": "business_type", + "type": "string", + "required": true, + "source": "body", + "description": "业务类型(必填),如 waybill、order_delivery" + }, + { + "name": "business_sub_type", + "type": "string", + "required": true, + "source": "body", + "description": "业务子类型(必填),如 intercept、mis_shipment。需与 business_type 匹配(由 BUSINESS_TYPES 校验)" + }, + { + "name": "business_id", + "type": "number", + "required": true, + "source": "body", + "description": "关联业务单据主键ID(必填)" + }, + { + "name": "business_no", + "type": "string", + "required": false, + "source": "body", + "description": "关联业务单据号(可选,建议传入方便列表展示)" + }, + { + "name": "direction", + "type": "number", + "required": false, + "source": "body", + "description": "记账方向:1=入库 2=出库,默认 0(未确定)" + }, + { + "name": "priority", + "type": "number", + "required": false, + "source": "body", + "description": "优先级:1~100,默认 50。AI 创建时自动填入" + }, + { + "name": "title", + "type": "string", + "required": true, + "source": "body", + "description": "工单标题(必填)" + }, + { + "name": "description", + "type": "string", + "required": false, + "source": "body", + "description": "问题描述" + }, + { + "name": "claim_needed", + "type": "number", + "required": false, + "source": "body", + "description": "是否需要理赔:0=否 1=是,默认 0" + }, + { + "name": "claim_amount", + "type": "number", + "required": false, + "source": "body", + "description": "理赔金额,默认 0.00" + }, + { + "name": "parent_work_order_id", + "type": "number", + "required": false, + "source": "body", + "description": "父工单ID(子工单场景),不传则为根工单" + } + ], + "response": [ + { + "name": "data", + "type": "object", + "description": "创建成功的工单详情(同 detail 接口返回结构)" + } + ], + "errors": [ + { "code": "400", "description": "工单标题不能为空" }, + { "code": "400", "description": "业务类型或子类型不合法" }, + { "code": "400", "description": "父工单不存在" } + ] +} +``` + +--- + +### 3.5 `afterSale.update` — 更新工单基本信息 + +```json +{ + "method": "afterSale.update", + "description": "更新工单基本信息(标题、描述、优先级、记账方向、理赔信息)。不可修改 business_type/business_sub_type/business_id。仓库隔离。", + "isNeedAuth": true, + "isNeedLogin": true, + "params": [ + { "name": "id", "type": "number", "required": true, "source": "body", "description": "工单ID(必填)" }, + { "name": "title", "type": "string", "required": false, "source": "body", "description": "工单标题" }, + { "name": "description", "type": "string", "required": false, "source": "body", "description": "问题描述" }, + { "name": "priority", "type": "number", "required": false, "source": "body", "description": "优先级" }, + { "name": "direction", "type": "number", "required": false, "source": "body", "description": "记账方向" }, + { "name": "claim_needed", "type": "number", "required": false, "source": "body", "description": "是否需要理赔" }, + { "name": "claim_amount", "type": "number", "required": false, "source": "body", "description": "理赔金额" }, + { "name": "claim_status", "type": "number", "required": false, "source": "body", "description": "理赔状态" } + ], + "response": [ + { "name": "data", "type": "object", "description": "更新后的工单详情" } + ], + "errors": [ + { "code": "400", "description": "工单ID不能为空" }, + { "code": "404", "description": "工单不存在或无权操作" } + ] +} +``` + +--- + +### 3.6 `afterSale.delete` — 删除工单 + +```json +{ + "method": "afterSale.delete", + "description": "软删除工单及其所有步骤。仅待处理(0)和已取消(9)状态的工单可删除。仓库隔离。", + "isNeedAuth": true, + "isNeedLogin": true, + "params": [ + { "name": "id", "type": "number", "required": true, "source": "body", "description": "工单ID(必填)" } + ], + "response": [], + "errors": [ + { "code": "400", "description": "工单ID不能为空" }, + { "code": "400", "description": "处理中的工单不可删除" }, + { "code": "404", "description": "工单不存在或无权操作" } + ] +} +``` + +--- + +### 3.7 `afterSale.assign` — 分配处理人 + +```json +{ + "method": "afterSale.assign", + "description": "将工单分配给指定处理人。仅待处理(0)状态的工单可分配。分配后自动流转至处理中(1)。仓库隔离。", + "isNeedAuth": true, + "isNeedLogin": true, + "params": [ + { "name": "id", "type": "number", "required": true, "source": "body", "description": "工单ID(必填)" }, + { "name": "assignee_id", "type": "number", "required": true, "source": "body", "description": "处理人ID(必填)" }, + { "name": "remark", "type": "string", "required": false, "source": "body", "description": "分配备注" } + ], + "response": [ + { "name": "data", "type": "object", "description": "更新后的工单详情" } + ], + "errors": [ + { "code": "400", "description": "工单ID不能为空" }, + { "code": "400", "description": "处理人ID不能为空" }, + { "code": "400", "description": "当前状态不可分配(非待处理状态)" } + ] +} +``` + +--- + +### 3.8 `afterSale.complete` — 完成工单 + +```json +{ + "method": "afterSale.complete", + "description": "完成工单。仅处理中(1)状态且所有步骤已完成/跳过的工单可完成。完成后自动设置 resolved_at。仓库隔离。", + "isNeedAuth": true, + "isNeedLogin": true, + "params": [ + { "name": "id", "type": "number", "required": true, "source": "body", "description": "工单ID(必填)" }, + { "name": "resolution", "type": "string", "required": false, "source": "body", "description": "处理结果说明" } + ], + "response": [ + { "name": "data", "type": "object", "description": "更新后的工单详情" } + ], + "errors": [ + { "code": "400", "description": "工单ID不能为空" }, + { "code": "400", "description": "当前状态不可完成(非处理中状态)" }, + { "code": "400", "description": "仍有步骤未完成,请先完成所有步骤" } + ] +} +``` + +--- + +### 3.9 `afterSale.close` — 关闭工单 + +```json +{ + "method": "afterSale.close", + "description": "关闭工单。仅已完成(2)状态的工单可关闭。仓库隔离。", + "isNeedAuth": true, + "isNeedLogin": true, + "params": [ + { "name": "id", "type": "number", "required": true, "source": "body", "description": "工单ID(必填)" }, + { "name": "remark", "type": "string", "required": false, "source": "body", "description": "关闭备注" } + ], + "response": [ + { "name": "data", "type": "object", "description": "更新后的工单详情" } + ], + "errors": [ + { "code": "400", "description": "工单ID不能为空" }, + { "code": "400", "description": "当前状态不可关闭(非已完成状态)" } + ] +} +``` + +--- + +### 3.10 `afterSale.cancel` — 取消工单 + +```json +{ + "method": "afterSale.cancel", + "description": "取消工单。仅待处理(0)和处理中(1)状态的工单可取消。仓库隔离。", + "isNeedAuth": true, + "isNeedLogin": true, + "params": [ + { "name": "id", "type": "number", "required": true, "source": "body", "description": "工单ID(必填)" }, + { "name": "remark", "type": "string", "required": false, "source": "body", "description": "取消原因" } + ], + "response": [ + { "name": "data", "type": "object", "description": "更新后的工单详情" } + ], + "errors": [ + { "code": "400", "description": "工单ID不能为空" }, + { "code": "400", "description": "当前状态不可取消" } + ] +} +``` + +--- + +### 3.11 `afterSale.stepStart` — 开始步骤 + +```json +{ + "method": "afterSale.stepStart", + "description": "开始处理某个步骤。将步骤状态设为进行中(1),同时更新主表 current_step。同一时刻只允许一个步骤处于进行中。仓库隔离。", + "isNeedAuth": true, + "isNeedLogin": true, + "params": [ + { "name": "step_id", "type": "number", "required": true, "source": "body", "description": "步骤ID(必填,wms_after_sale_work_order_step.id)" }, + { "name": "remark", "type": "string", "required": false, "source": "body", "description": "备注" } + ], + "response": [ + { "name": "data", "type": "object", "description": "更新后的步骤信息" } + ], + "errors": [ + { "code": "400", "description": "步骤ID不能为空" }, + { "code": "400", "description": "已有其他步骤正在进行中" }, + { "code": "400", "description": "步骤当前状态不可开始" } + ] +} +``` + +--- + +### 3.12 `afterSale.stepComplete` — 完成步骤 + +```json +{ + "method": "afterSale.stepComplete", + "description": "完成某个步骤。将步骤状态设为已完成(2),记录操作人和完成时间。仓库隔离。", + "isNeedAuth": true, + "isNeedLogin": true, + "params": [ + { "name": "step_id", "type": "number", "required": true, "source": "body", "description": "步骤ID(必填)" }, + { "name": "action", "type": "string", "required": false, "source": "body", "description": "操作动作描述" }, + { "name": "remark", "type": "string", "required": false, "source": "body", "description": "处理备注" } + ], + "response": [ + { "name": "data", "type": "object", "description": "更新后的步骤信息" } + ], + "errors": [ + { "code": "400", "description": "步骤ID不能为空" }, + { "code": "400", "description": "步骤当前状态不可完成(非进行中状态)" } + ] +} +``` + +--- + +### 3.13 `afterSale.stepSkip` — 跳过步骤 + +```json +{ + "method": "afterSale.stepSkip", + "description": "跳过某个步骤。将步骤状态设为已跳过(3)。仓库隔离。", + "isNeedAuth": true, + "isNeedLogin": true, + "params": [ + { "name": "step_id", "type": "number", "required": true, "source": "body", "description": "步骤ID(必填)" }, + { "name": "remark", "type": "string", "required": false, "source": "body", "description": "跳过原因" } + ], + "response": [ + { "name": "data", "type": "object", "description": "更新后的步骤信息" } + ], + "errors": [ + { "code": "400", "description": "步骤ID不能为空" }, + { "code": "400", "description": "步骤当前状态不可跳过" } + ] +} +``` + +--- + +## 四、状态机约束(服务端校验规则) + +| 操作 | 允许的当前状态 | 目标状态 | +|------|-------------|---------| +| `create` | — | `status=0`, `current_step=1` | +| `assign` | `status=0` | `status=1` | +| `delete` | `status=0` 或 `status=9` | 软删除 | +| `complete` | `status=1` + 所有步骤已完成/跳过 | `status=2`, `resolved_at=NOW()` | +| `close` | `status=2` | `status=3` | +| `cancel` | `status=0` 或 `status=1` | `status=9` | +| `stepStart` | `step_status=0` + 无其他进行中步骤 | `step_status=1`, `current_step=该step_order` | +| `stepComplete` | `step_status=1` | `step_status=2` | +| `stepSkip` | `step_status=0` | `step_status=3` | + +--- + +## 五、methods/system.json 追加格式 + +在 `methods.system.json` 的 `methods.groups` 数组末尾追加: + +```json +{ + "groupName": "售后工单模块", + "module": "afterSale", + "list": [ + { "method": "afterSale.businessTypes", ... }, + { "method": "afterSale.list", ... }, + { "method": "afterSale.detail", ... }, + { "method": "afterSale.create", ... }, + { "method": "afterSale.update", ... }, + { "method": "afterSale.delete", ... }, + { "method": "afterSale.assign", ... }, + { "method": "afterSale.complete", ... }, + { "method": "afterSale.close", ... }, + { "method": "afterSale.cancel", ... }, + { "method": "afterSale.stepStart", ... }, + { "method": "afterSale.stepComplete", ... }, + { "method": "afterSale.stepSkip", ... } + ] +} +``` + +(完整 JSON 定义见第三节各接口) + +--- + +## 六、后续实现计划(审阅通过后执行) + +| 步骤 | 文件 | 说明 | +|------|------|------| +| 1 | `app/service/systems/afterSale.js` | 业务层:数据库操作、状态机、工单号生成 | +| 2 | `app/service/systemMethods/afterSale.js` | 入口层:鉴权配置、参数校验、委托调用 | +| 3 | `methods/system.json` | 追加 `afterSale` group 的 13 个 method 文档 | +| 4 | `methods/changes/afterSale-20260729.json` | 接口变更记录 | + +--- + +## 七、待确认事项 + +- [ ] **1. 模块名**:`afterSale` 是否合适?备选 `asWorkOrder`、`afterSaleWorkOrder` +- [ ] **2. 步骤操作是否需要独立接口**:`stepStart/stepComplete/stepSkip` 三个独立接口 vs 合并为一个 `stepUpdate`(传 status 参数) +- [ ] **3. `businessTypes` 接口免登录**:是否允许未登录用户获取业务类型枚举? +- [ ] **4. 步骤创建时机**:步骤是创建工单时自动初始化一组,还是由前端手动逐条添加? +- [ ] **5. 是否需要批量操作**:批量分配、批量关闭? +- [ ] **6. 是否需要操作日志**:是否复用 `operation_log` 记录关键状态变更? diff --git a/database/designs/after-sale-work-order-design.md b/database/designs/after-sale-work-order-design.md new file mode 100644 index 0000000..13d2914 --- /dev/null +++ b/database/designs/after-sale-work-order-design.md @@ -0,0 +1,440 @@ +# 售后工单表设计方案 + +> **状态**: ✅ 已落库(开发环境) +> **设计日期**: 2026-07-28(v4 定稿:新增 parent_work_order_id 支持主子工单) +> **设计人**: wms-db-agent +> **说明**: 本文档仅输出设计方案,不执行落库。审阅通过后再生成迁移文件。 + +--- + +## 一、需求概述 + +1. **主表**:售后工单单表,支持灵活绑定多种业务单据(运单、订单、入库单、退货单等),通过 `business_type` + `business_sub_type` + `business_id` 三级多态关联 +2. **副表**:进度步骤处理表,记录每一步的操作员工、动作、备注(步骤不预设模板,由业务逻辑动态创建) +3. **状态流转**:工单整体状态 + 主表 `current_step` 进度 + 步骤级状态三层次 +4. **简单记账**:记录是"进"还是"出" +5. **理赔追踪**:是否需要理赔、理赔金额、理赔结算状态 +6. **附件关联**:通过现有 `wms_file_reference` 表关联附件/图片 + +--- + +## 二、表结构设计 + +### 2.1 主表:`wms_after_sale_work_order`(售后工单主表) + +| # | 字段名 | 类型 | 必填 | 默认值 | 说明 | +|---|--------|------|------|--------|------| +| 1 | `id` | `BIGINT(20) UNSIGNED` | Y | AUTO | 主键ID | +| 2 | `warehouse_id` | `BIGINT(20) UNSIGNED` | Y | — | 仓库ID | +| 3 | `store_id` | `BIGINT(20) UNSIGNED` | Y | — | 货主ID | +| 4 | `work_order_no` | `VARCHAR(50)` | Y | — | 售后工单号,唯一,格式 `AS` + 时间戳(如 AS202607280001) | +| 5 | `business_type` | `VARCHAR(50)` | Y | — | 关联业务类型,见 §3.1 枚举及 §五 Model 内置定义 | +| 6 | `business_sub_type` | `VARCHAR(50)` | Y | — | 关联业务子类型,如运单下的 `intercept`(拦截)、订单下的 `mis_shipment`(错发),见 §五 | +| 7 | `business_id` | `BIGINT(20) UNSIGNED` | Y | — | 关联业务单据主键ID(多态关联) | +| 8 | `business_no` | `VARCHAR(100)` | N | — | 关联业务单据号(冗余,方便列表展示) | +| 9 | `direction` | `TINYINT UNSIGNED` | Y | 0 | 记账方向:`1`=入库(退货入库/换货入库),`2`=出库(补发/换货出库),`0`=未确定 | +| 10 | `status` | `TINYINT UNSIGNED` | Y | 0 | 工单状态,见 §3.4 状态机 | +| 11 | `priority` | `TINYINT UNSIGNED` | Y | 50 | 优先级:`1`~`100`,数字越大优先级越高,由客服接待或AI自动识别填入 | +| 12 | `title` | `VARCHAR(200)` | Y | — | 工单标题/摘要 | +| 13 | `description` | `TEXT` | N | — | 问题描述 | +| 14 | `creator_id` | `BIGINT(20) UNSIGNED` | Y | — | 创建人ID,关联 `account.id`;`0` 表示 AI 自动接待 | +| 15 | `creator_snapshot` | `TEXT` | N | — | 创建人信息快照(JSON格式);AI创建时记录模型/会话信息 | +| 16 | `assignee_id` | `BIGINT(20) UNSIGNED` | N | — | 当前处理人ID,关联 `account.id` | +| 17 | `parent_work_order_id` | `BIGINT(20) UNSIGNED` | N | — | 父工单ID,自关联 `wms_after_sale_work_order.id`;非空时表示当前工单为子工单 | +| 18 | `current_step` | `TINYINT UNSIGNED` | Y | 1 | **当前进度**(位于主表),值为当前正在处理的 `step_order` 序号 | +| 19 | `claim_needed` | `TINYINT UNSIGNED` | Y | 0 | 是否需要理赔:`0`=不需要,`1`=需要 | +| 20 | `claim_amount` | `DECIMAL(12,2)` | N | 0.00 | 理赔金额(元),精度2位小数 | +| 21 | `claim_status` | `TINYINT UNSIGNED` | Y | 0 | 理赔状态:`0`=未理赔,`1`=已理赔(单笔结清),`2`=月结 | +| 22 | `resolution` | `TEXT` | N | — | 处理结果说明 | +| 23 | `resolved_at` | `DATETIME` | N | — | 解决时间 | +| 24 | `created_at` | `DATETIME` | Y | `CURRENT_TIMESTAMP` | 创建时间 | +| 25 | `updated_at` | `DATETIME` | Y | `CURRENT_TIMESTAMP ON UPDATE` | 更新时间 | +| 26 | `deleted_at` | `DATETIME` | N | — | 软删除时间 | + +**索引设计**: + +| 索引名 | 字段 | 类型 | 说明 | +|--------|------|------|------| +| `PRIMARY` | `id` | 主键 | — | +| `uk_work_order_no` | `work_order_no` | 唯一 | 工单号唯一 | +| `idx_warehouse_id` | `warehouse_id` | 普通 | 按仓库查询 | +| `idx_store_id` | `store_id` | 普通 | 按货主查询 | +| `idx_business_type_subtype_id` | `business_type, business_sub_type, business_id` | 普通 | 按业务类型+子类型+单据ID反查工单 | +| `idx_status` | `status` | 普通 | 按状态筛选 | +| `idx_assignee_id` | `assignee_id` | 普通 | 按处理人查询 | +| `idx_parent_work_order_id` | `parent_work_order_id` | 普通 | 按父工单查所有子工单 | +| `idx_priority` | `priority` | 普通 | 按优先级排序 | +| `idx_claim_status` | `claim_status` | 普通 | 按理赔状态筛选 | +| `idx_created_at` | `created_at` | 普通 | 按时间排序 | +| `idx_deleted_at` | `deleted_at` | 普通 | 软删除查询 | + +--- + +### 2.2 副表:`wms_after_sale_work_order_step`(售后工单进度步骤表) + +| # | 字段名 | 类型 | 必填 | 默认值 | 说明 | +|---|--------|------|------|--------|------| +| 1 | `id` | `BIGINT(20) UNSIGNED` | Y | AUTO | 主键ID | +| 2 | `work_order_id` | `BIGINT(20) UNSIGNED` | Y | — | 工单ID,关联 `wms_after_sale_work_order.id` | +| 3 | `step_order` | `TINYINT UNSIGNED` | Y | 1 | 步骤序号(从1开始递增) | +| 4 | `step_name` | `VARCHAR(100)` | Y | — | 步骤名称 | +| 5 | `step_status` | `TINYINT UNSIGNED` | Y | 0 | 步骤状态:`0`=待开始,`1`=进行中,`2`=已完成,`3`=已跳过 | +| 6 | `operator_id` | `BIGINT(20) UNSIGNED` | N | — | 操作员工ID,关联 `account.id` | +| 7 | `operator_snapshot` | `TEXT` | N | — | 操作人信息快照(JSON格式) | +| 8 | `action` | `VARCHAR(100)` | N | — | 操作动作描述(如"核实问题属实,安排退货入库") | +| 9 | `remark` | `TEXT` | N | — | 处理备注 | +| 10 | `started_at` | `DATETIME` | N | — | 步骤开始时间 | +| 11 | `completed_at` | `DATETIME` | N | — | 步骤完成时间 | +| 12 | `created_at` | `DATETIME` | Y | `CURRENT_TIMESTAMP` | 创建时间 | +| 13 | `updated_at` | `DATETIME` | Y | `CURRENT_TIMESTAMP ON UPDATE` | 更新时间 | +| 14 | `deleted_at` | `DATETIME` | N | — | 软删除时间 | + +**索引设计**: + +| 索引名 | 字段 | 类型 | 说明 | +|--------|------|------|------| +| `PRIMARY` | `id` | 主键 | — | +| `idx_work_order_id` | `work_order_id` | 普通 | 按工单查所有步骤 | +| `idx_operator_id` | `operator_id` | 普通 | 按操作人反查 | +| `idx_deleted_at` | `deleted_at` | 普通 | 软删除查询 | +| `uk_work_order_step` | `work_order_id, step_order, deleted_at` | 唯一 | 同一工单下步骤序号唯一(含软删除) | + +--- + +## 三、枚举定义 + +### 3.1 `business_type` 与 `business_sub_type`(业务类型及子类型) + +业务类型和子类型由 Model 文件 `app/model/after_sale_work_order.js` 中的 `BUSINESS_TYPES` 常量统一定义。数据库层面使用 `VARCHAR(50)` 存储,方便扩展。 + +#### 内置业务类型总览 + +| business_type | 业务名称 | 关联表 | 子类型 (business_sub_type) | +|---------------|---------|--------|---------------------------| +| `waybill` | 运单 | `wms_order_express` | `intercept`(拦截)、`urge`(催件)、`damage`(破损)、`lost`(丢件)、`wrong_info`(信息错误) | +| `order_delivery` | 发货订单 | `wms_order_delivery` | `mis_shipment`(错发)、`missing_item`(少发)、`wrong_sku`(错品)、`quality_issue`(质量问题)、`delivery_delay`(发货延迟) | +| `entry_order` | 入库单 | `wms_entry_order` | `shortage`(少货)、`damage`(破损)、`wrong_sku`(错品)、`quality_issue`(质量问题) | +| `order_stockout` | 出库单/退货出库单 | `wms_order_stockout` | `return_issue`(退货异常)、`wrong_outbound`(错发)、`shortage`(少发) | +| `receiving` | 收货单 | `wms_receiving` | `shortage`(少货)、`damage`(破损)、`quality_issue`(质量问题) | +| `other` | 其他 | — | `general`(通用) | + +> **扩展方式**:在 Model 的 `BUSINESS_TYPES` 常量中增删条目即可,无需 ALTER TABLE。外部代码通过 `require` Model 文件读取。 + +### 3.2 `priority`(优先级) + +``` +1 ~ 100 的整数,数字越大优先级越高。 +由客服接待手动填入,或由 AI 根据问题描述自动识别并填入。 +默认值 50(中等优先级)。 +``` + +### 3.3 `direction`(记账方向) + +``` +0 — 未确定 +1 — 入库(IN):退货入库 / 换货入库 / 赔付补货入库 +2 — 出库(OUT):补发出库 / 换货出库 / 退款退货出库 +``` + +> 与 `stock_transaction.transaction_type`(`INBOUND`/`OUTBOUND`)语义对齐。 + +### 3.4 `status`(工单状态) + +``` +0 — 待处理 (工单刚创建,尚未分配) +1 — 处理中 (已分配处理人,正在推进) +2 — 已完成 (问题已解决,全部步骤完成) +3 — 已关闭 (问题关闭,不再跟进) +9 — 已取消 (工单作废) +``` + +### 3.5 `claim_status`(理赔状态) + +``` +0 — 未理赔 (不需要理赔,或尚未发起理赔) +1 — 已理赔 (单笔已结清,理赔款项已到账) +2 — 月结 (纳入月度结算,按月统一对账打款) +``` + +### 3.6 `step_status`(步骤状态) + +``` +0 — 待开始 (步骤尚未激活) +1 — 进行中 (当前正在处理的步骤) +2 — 已完成 (步骤已处理完毕) +3 — 已跳过 (该步骤被跳过,不适用) +``` + +### 3.7 `creator_id` 特殊值 + +``` +0 — AI 自动接待(非员工账号创建) +> 0 — 对应 account.id,人工客服/员工创建 +``` + +> 当 `creator_id = 0` 时,`creator_snapshot` 可记录 AI 模型标识及会话 ID 等元信息。 + +--- + +## 四、状态流转设计 + +### 4.1 工单级别状态机 + +``` + ┌──────────────────────────────────┐ + │ │ + ┌───┴──────┐ ┌───┴──────┐ + 创建工单 ───→ │ 待处理(0) │ ──── 分配处理人 ───→ │ 处理中(1) │ + └───┬──────┘ └───┬──────┘ + │ │ + │ 取消 │ 全部步骤完成 + ↓ ↓ + ┌───┴──────┐ ┌───┴──────┐ + │ 已取消(9) │ │ 已完成(2) │ + └──────────┘ └───┬──────┘ + │ + │ 关闭 + ↓ + ┌───┴──────┐ + │ 已关闭(3) │ + └──────────┘ +``` + +**流转规则**: + +| 当前状态 | 允许流转到 | 触发条件 | +|----------|-----------|----------| +| `0-待处理` | `1-处理中` | 分配处理人 | +| `0-待处理` | `9-已取消` | 主动取消 | +| `1-处理中` | `2-已完成` | 所有步骤均标记为已完成 | +| `1-处理中` | `9-已取消` | 主动取消 | +| `2-已完成` | `3-已关闭` | 确认关闭 | +| `3-已关闭` | — | 终态,不可流转 | + +### 4.2 步骤级别状态机 + +``` + ┌──────────────────────────────────┐ + │ │ + ┌───┴──────┐ ┌───┴──────┐ + 步骤创建 ───→ │ 待开始(0) │ ──── 开始处理 ───→ │ 进行中(1) │ + └───┬──────┘ └───┬──────┘ + │ │ + │ 跳过 │ 完成 + ↓ ↓ + ┌───┴──────┐ ┌───┴──────┐ + │ 已跳过(3) │ │ 已完成(2) │ + └──────────┘ └──────────┘ +``` + +**约束**: +- 同一工单下,同一时刻最多只有 1 个步骤处于 `进行中(1)` +- 步骤按 `step_order` 顺序流转,但允许跳过中间步骤 +- 工单进度由主表 `current_step` 字段追踪,指向当前正在处理的 `step_order` +- 所有步骤标记为 `已完成(2)` 或 `已跳过(3)` 后,`current_step` 置为最终步骤号,工单状态可流转至 `已完成(2)` + +--- + +## 五、Model 内置业务类型定义 + +> **步骤不预设模板**:`wms_after_sale_work_order_step` 表的步骤由业务逻辑在运行时动态创建,不在数据库或 Model 中硬编码步骤模板。 + +### 5.1 `BUSINESS_TYPES` 常量(定义在 `app/model/after_sale_work_order.js`) + +```javascript +/** + * 售后工单业务类型定义 + * 外部可通过 require('./app/model/after_sale_work_order').BUSINESS_TYPES 访问 + * 增删业务类型或子类型只需修改此常量,无需 ALTER TABLE + */ +const BUSINESS_TYPES = { + waybill: { + label: '运单', + table: 'wms_order_express', // 关联的数据库表名 + subtypes: { + intercept: '拦截', + urge: '催件', + damage: '破损', + lost: '丢件', + wrong_info: '信息错误', + }, + }, + order_delivery: { + label: '发货订单', + table: 'wms_order_delivery', + subtypes: { + mis_shipment: '错发', + missing_item: '少发', + wrong_sku: '错品', + quality_issue: '质量问题', + delivery_delay: '发货延迟', + }, + }, + entry_order: { + label: '入库单', + table: 'wms_entry_order', + subtypes: { + shortage: '少货', + damage: '破损', + wrong_sku: '错品', + quality_issue: '质量问题', + }, + }, + order_stockout: { + label: '出库单/退货出库单', + table: 'wms_order_stockout', + subtypes: { + return_issue: '退货异常', + wrong_outbound: '错发', + shortage: '少发', + }, + }, + receiving: { + label: '收货单', + table: 'wms_receiving', + subtypes: { + shortage: '少货', + damage: '破损', + quality_issue: '质量问题', + }, + }, + other: { + label: '其他', + table: null, + subtypes: { + general: '通用', + }, + }, +}; + +// 辅助函数:根据 business_type 获取关联表名 +function getBusinessTable(businessType) { + return BUSINESS_TYPES[businessType]?.table || null; +} + +// 辅助函数:校验 business_type + business_sub_type 组合是否合法 +function isValidSubType(businessType, businessSubType) { + const def = BUSINESS_TYPES[businessType]; + return def && Object.prototype.hasOwnProperty.call(def.subtypes, businessSubType); +} + +module.exports = { BUSINESS_TYPES, getBusinessTable, isValidSubType }; +``` + +### 5.2 使用示例 + +```javascript +// 外部读取 +const { BUSINESS_TYPES, getBusinessTable, isValidSubType } = require('./app/model/after_sale_work_order'); + +// 获取所有业务类型列表 +Object.keys(BUSINESS_TYPES); // ['waybill', 'order_delivery', 'entry_order', ...] + +// 获取运单下的子类型 +BUSINESS_TYPES.waybill.subtypes; // { intercept: '拦截', urge: '催件', ... } + +// 获取关联表 +const table = getBusinessTable('waybill'); // 'wms_order_express' + +// 校验合法性 +isValidSubType('waybill', 'intercept'); // true +isValidSubType('waybill', 'mis_shipment'); // false +``` + +--- + +## 六、与现有系统的关联 + +### 6.1 与业务单据的多态关联(三级定位) + +``` +wms_after_sale_work_order + .business_type = 'waybill' + .business_sub_type = 'intercept' ← 子类型(Model 常量定义) + .business_id = 12345 ← wms_order_express.id + .business_no = 'YD202607280001' ← 冗余单号 + +实际关联链路: + business_type → BUSINESS_TYPES[type].table → 确定关联表 + business_id → 关联表主键 + business_sub_type → 细分工单类别(如拦截/催件/破损) + +示例: + ├── 'waybill' / 'intercept' → wms_order_express.id + ├── 'waybill' / 'urge' → wms_order_express.id + ├── 'waybill' / 'damage' → wms_order_express.id + ├── 'order_delivery' / 'mis_shipment' → wms_order_delivery.id + ├── 'order_delivery' / 'missing_item' → wms_order_delivery.id + ├── 'entry_order' / 'shortage' → wms_entry_order.id + ├── 'order_stockout' / 'return_issue' → wms_order_stockout.id + ├── 'receiving' / 'damage' → wms_receiving.id + └── 'other' / 'general' → 自定义 +``` + +### 6.2 与库存交易的对账 + +``` +售后工单.direction = 1 (入库) + → stock_transaction.transaction_type = 'INBOUND' + → stock_transaction.order_type = 'AFTER_SALE' (需同步在 stock_transaction 中新增此类型) + +售后工单.direction = 2 (出库) + → stock_transaction.transaction_type = 'OUTBOUND' + → stock_transaction.order_type = 'AFTER_SALE' +``` + +### 6.4 与附件的关联 + +售后工单不新增附件字段,复用现有 `wms_file_reference` 表做多态附件关联: + +``` +wms_file_reference + .reference_type = 'after_sale_work_order' ← 固定标识 + .reference_id = 工单 id ← wms_after_sale_work_order.id + .file_id = 文件 id ← wms_file.id + +示例:一张工单可关联多张图片/多个附件(如破损照片、快递面单照片等)。 +``` + +> `file_reference` 表已支持多态关联(`reference_type` + `reference_id`),无需新建表或字段。 + +### 6.5 与员工的关联 + +``` +wms_after_sale_work_order.creator_id → account.id(创建人) +wms_after_sale_work_order.assignee_id → account.id(当前处理人) +wms_after_sale_work_order_step.operator_id → account.id(步骤操作人) +``` + +--- + +## 七、待确认事项(审阅清单) + +请审阅时重点关注以下设计决策: + +- [x] **1. `business_type` 枚举值**:`order_delivery` / `entry_order` / `order_stockout` / `waybill` / `receiving` / `other` — ✅ 已确认,暂不增加 `return_order` 独立类型(退货场景通过 `order_stockout` 覆盖) +- [x] **2. `direction` 记账方向**:`1`=入库 / `2`=出库 / `0`=未确定 — ✅ 已确认,细粒度区分由关联的实际出入库单承载 +- [x] **3. 工单状态值**:`0-待处理/1-处理中/2-已完成/3-已关闭/9-已取消` — ✅ 已确认,当前中间态足够,无需增加"驳回/退回" +- [x] **4. 预设步骤模板**:不再预设步骤模板,步骤由业务逻辑动态创建 ✅ +- [x] **5. `business_id` 多态关联**:采用 `business_type` + `business_sub_type` + `business_id` 三级多态关联,子类型由 Model 常量定义 ✅ +- [x] **6. 理赔信息**:已新增 `claim_needed` / `claim_amount` / `claim_status` 三个字段 ✅ +- [x] **7. 进度追踪**:进度由主表 `current_step` 字段承载(不再仅依赖副表步骤状态) ✅ +- [x] **8. 优先级**:改为 `TINYINT UNSIGNED` 取值范围 `1-100`,由客服或 AI 自动识别填入,默认值 `50` ✅ +- [x] **9. AI 创建支持**:`creator_id = 0` 表示 AI 自动接待,`creator_snapshot` 记录模型/会话信息 ✅ +- [x] **10. 附件/图片**:复用现有 `wms_file_reference` 表做多态关联,不新增字段 ✅ +- [x] **11. 预计完成时间**:暂不增加,后续通过 `created_at` + `priority` 做超时告警替代;SLA 配置表留待后续迭代 ✅ +- [x] **12. 关联工单**:已确认新增 `parent_work_order_id` 字段,支持主子工单拆分 ✅ +- [x] **13. 表名**:`wms_after_sale_work_order` 和 `wms_after_sale_work_order_step` — ✅ 已确认 +- [x] **14. 权限**:API 接口设计阶段再补录 `wms_permission` 记录,不阻塞表落库 ✅ + +--- + +## 八、后续落库计划(审阅通过后执行) + +1. 创建迁移文件 `database/migrations/20260728XXXXXX-create-wms-after-sale-work-order.js` +2. 创建迁移文件 `database/migrations/20260728XXXXXX-create-wms-after-sale-work-order-step.js` +3. 创建 Model 文件 `app/model/after_sale_work_order.js` +4. 创建 Model 文件 `app/model/after_sale_work_order_step.js` +5. 在 `methods/system.json` 中新增接口路由 +6. 如需,在 `stock_transaction.order_type` 中新增 `AFTER_SALE` 枚举值(独立迁移) +7. 如需,新增 `wms_permission` 权限记录 diff --git a/database/designs/waybill-module-design.md b/database/designs/waybill-module-design.md new file mode 100644 index 0000000..a963fe6 --- /dev/null +++ b/database/designs/waybill-module-design.md @@ -0,0 +1,579 @@ +# 运单号模块设计方案(仓库侧) + +> **状态**: ⏳ 等待审阅 +> **设计日期**: 2026-07-29 +> **设计人**: wms-db-agent +> **说明**: 本文档仅输出设计方案,不执行代码实现。审阅通过后再进入开发。 +> **命名空间**: `waybill.warehouse.*`(仓库侧操作);后续预留 `waybill.store.*`(货主侧操作),本期不实现。 + +--- + +## 一、需求概述 + +当前系统缺少独立的运单号查询与管理界面。运单数据(`wms_order_express`)始终依附于订单上下文——运单信息仅通过订单详情接口(`xxx.detail`)的 `expresses[]` 字段返回,或通过 `index.toOrder` 做运单号→订单反查。实际业务中需要: + +1. **运单号列表(仓库侧)**:按仓库维度,独立查询所有运单号,支持多条件筛选、分页,支持主单号/子单号关联展示与查询 +2. **运单详情(仓库侧)**:查看单个运单的完整信息,包含关联订单、打印记录、打包状态、称重信息 +3. **运单导出(仓库侧)**:支持按筛选条件导出运单列表 + +> **主单号/子单号规则**(沿用已有业务约定):同一 `order_id` 下,`business_key = 1` 的运单为**主单号**,`business_key > 1` 的运单为**子单号**(即拆单产生的子运单)。该规则已在 `order_export.js` 导出逻辑中使用。 +> +> **命名空间规划**:`waybill.warehouse.*` 本期实现(仓库侧操作);后续按需扩展 `waybill.store.*`(货主侧操作,按 `store_id` 维度查询)。两套接口共享底层 `systems/waybill.js` 业务逻辑,仅入口鉴权与数据隔离维度不同。 + +--- + +## 二、数据模型分析 + +### 2.1 核心表:`wms_order_express`(运单表,已有) + +当前表结构(关键字段): + +| 字段 | 类型 | 说明 | +|------|------|------| +| `id` | `BIGINT(20) UNSIGNED` PK | 主键 | +| `waybill_code` | `VARCHAR(50)` | **运单号** | +| `order_id` | `BIGINT(20)` | 订单ID | +| `warehouse_id` | `BIGINT(20) UNSIGNED` | 仓库ID | +| `business_key` | `INTEGER(3)` | 拆单序号(1=主单号,>1=子单号) | +| `status` | `TINYINT(1)` DEFAULT 0 | 状态(1=已分配,0=未分配) | +| `logistics_interface_id` | `BIGINT(20) UNSIGNED` | 物流接口ID | +| `logistics_code` | `VARCHAR(50)` | 物流公司编码 | +| `logistics_name` | `VARCHAR(50)` | 物流公司名称 | +| `logistics_interface_id` | `BIGINT(20) UNSIGNED` | 物流接口ID | +| `logistics_interface_name` | `VARCHAR(50)` | 物流接口名称 | +| `platform_code` | `VARCHAR(50)` | 平台编码 | +| `is_galaxy_receive` | `ENUM('Y','N')` | 是否星河签收 | +| `is_back` | `ENUM('Y','N')` | 是否退回 | +| `is_intercept` | `ENUM('Y','N')` | 是否拦截 | +| `weighing_weight` | `INT(11)` DEFAULT 0 | 称重重量(g) | +| `package_material_id` | `BIGINT(20) UNSIGNED` | 包材ID | +| `package_material_name_snapshot` | `VARCHAR(128)` | 包材名称快照 | +| `printinfo` | `TEXT('long')` | 打印信息 | +| `ver` | `VARCHAR(50)` | 打印版本号 | +| `retry_count` | `TINYINT(3)` | 重试次数 | +| `create_at` | `DATE` | 创建时间 | +| `delete_at` | `DATE` | 删除时间 | + +**现有索引**: + +| 索引名 | 字段 | 类型 | +|--------|------|------| +| `PRIMARY` | `id` | 主键 | +| `uk_order_id_business_key` | `order_id, business_key` | 唯一 | +| `idx_waybill_code` | `waybill_code` | 普通 | +| `idx_create_at` | `create_at` | 普通 | +| `idx_wms_order_express_package_material_id` | `package_material_id` | 普通 | + +### 2.2 关联表 + +| 表名 | 关联字段 | 用途 | +|------|---------|------| +| `wms_order_delivery`(current/history/dispatch) | `order_id` | 订单信息(订单号、货主、波次等) | +| `wms_express` | `logistics_code` ↔ `code` | 物流公司名称(统一展示名) | +| `express_print_record` | `express_no` ↔ `waybill_code` | 打印记录(打印时间、打印机、模板) | +| `pack_task` | `waybill_code` | 打包任务(打包状态、打包人、打包时间) | +| `package_material` | `package_material_id` ↔ `id` | 包材详情 | + +### 2.3 索引评估 + +当前 `wms_order_express` 表的索引不足以支撑运单列表场景的高频查询: + +| 缺失索引 | 原因 | +|---------|------| +| `idx_warehouse_id_status` | 运单列表按仓库+状态是最常见查询 | +| `idx_logistics_code` | 按物流公司筛选运单 | +| `idx_logistics_interface_id` | 按快递接口ID筛选运单 | +| `idx_warehouse_id_create_at` | 仓库+时间范围排序分页 | +| `idx_order_id_business_key` | 已有 `uk_order_id_business_key` 唯一索引,可同时覆盖主单号 SELF JOIN 查询 | + +> **索引迁移**:以下索引将通过迁移文件 `YYYYMMDDHHmmss-add-waybill-list-indexes.js` 正式创建,见 §五 文件变更清单。 + +### 2.4 主单号/子单号关联关系 + +**规则**(沿用系统已有约定): + +- 同一 `order_id` 下,`business_key = 1` → **主单号**(main waybill) +- 同一 `order_id` 下,`business_key > 1` → **子单号**(child waybill) +- 该规则已在 `app/service/systems/order_export.js` 第 444 行使用:`business_key === 1 ? '主单号' : '子单号'` + +**查询方式**: + +- **正向查(子→主)**:在 `wms_order_express` 上做 SELF JOIN,`t1.order_id = t2.order_id AND t2.business_key = 1` 获取主单号 +- **反向查(主→子)**:通过 `order_id` + `business_key > 1` 查子单号;或通过主单号 `waybill_code` 先定位 `order_id`,再查该订单下所有运单 + +**注意**: +- 大部分运单 `business_key = 1`(未拆单),此时主单号 = 运单号本身 +- 仅拆单场景下存在 `business_key > 1` 的子单号 + +--- + +## 三、接口设计 + +### 3.1 模块概览 + +| 项目 | 说明 | +|------|------| +| 模块名 | `waybill.warehouse` | +| 接口路径 | `POST /system`,body 中 `method` 字段为 `waybill.warehouse.{方法名}` | +| 请求方式 | 全部 `POST`,参数放在 `body` 内 | +| 鉴权 | 查询类接口需登录但无需鉴权;导出需登录 | +| 数据隔离 | 按 `warehouse_id` 隔离(仓库侧视角,见 §3.1.1 仓库隔离策略) | +| 后续扩展 | 预留 `waybill.store.*`(货主侧,按 `store_id` 隔离),本期不实现 | + +### 3.1.1 仓库隔离策略(已核实) + +**核实结论**:仓库隔离策略与系统现有模式一致,无需调整。 + +**请求上下文来源**(系统统一约定): + +| 项目 | 值 | 说明 | +|------|-----|------| +| 仓库ID来源 | `ctx.user.store_id` | 全系统统一:`ctx.user.store_id` 即为当前操作用户所属仓库的 `warehouse_id` | +| 后备方案 | 无(必须登录) | 未登录用户无法访问,不存在 `store_id` 为空的情况 | +| 注入方式 | WHERE 条件自动追加 | 在 `systems/waybill.js` 中 `const warehouseId = Number(ctx.user.store_id)`,追加 `warehouse_id = warehouseId` 到所有查询的 WHERE 子句 | +| 注入时机 | 业务层(systems) | 不在入口层(systemMethods)注入,保持业务层职责单一 | + +**参考依据**(系统内一致使用 `ctx.user.store_id` 作为 warehouse_id): + +| 文件 | 行号/位置 | 用法 | +|------|----------|------| +| `systems/waybill.js`(现有 toOrder) | 第 29 行 | `ctx.user && ctx.user.store_id ? ctx.user.store_id : null` | +| `systemMethods/index.js` | 第 1593 行 | `ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : null` | +| `systemMethods/print.js` | 第 725 行 | `ctx.user.store_id` | +| `systemMethods/stock/transaction.js` | 第 32 行 | `Number(this.ctx.user && this.ctx.user.store_id)` | +| `systemMethods/storage/management.js` | JSDoc 注释 | "仓库 ID 从用户上下文(ctx.user.store_id / ctx.user.warehouse_id)自动获取" | + +> **注**:部分文件也支持 `ctx.user.warehouse_id` 作为备选来源(如 `storage/management.js`),但 `ctx.user.store_id` 是全系统主要来源,且 `wms_order_express` 表中的 `warehouse_id` 字段语义上对应 `store_id`。本期统一使用 `ctx.user.store_id`。 + +### 3.2 文件规划 + +``` +app/service/systemMethods/waybill/warehouse.js ← 入口层(鉴权、参数校验、委托) +app/service/systems/waybill.js ← 业务层(扩展:新增 list/detail/export 方法) +methods/system.json ← API 文档(新增 waybill.warehouse group) +``` + +> **注意**: +> - `app/service/systems/waybill.js` 已有 `toOrder()` 方法(运单反查),新方法将添加到同一文件中。 +> - 目录 `systemMethods/waybill/` 预留 `store.js`(货主侧入口),本期仅创建 `warehouse.js`。 + +### 3.3 调用链路 + +``` +POST /system { method: "waybill.warehouse.list", ... } + → app/router.js + → app/service/system.js + → app/service/systemMethods/waybill/warehouse.js ← 鉴权 + 参数校验 + → app/service/systems/waybill.js ← 业务逻辑 + DB操作 + → ctx.model.OrderExpress ← Sequelize Model + → ctx.model.OrderDeliveryFactory ← 订单信息补充 + → ctx.model.Express ← 物流公司名称 + → ctx.model.ExpressPrintRecord ← 打印记录 +``` + +--- + +### 3.4 接口清单 + +| # | method | 描述 | 需登录 | 需鉴权 | +|---|--------|------|--------|--------| +| 1 | `waybill.warehouse.list` | 运单列表-仓库侧(分页+筛选) | ✓ | ✗ | +| 2 | `waybill.warehouse.detail` | 运单详情-仓库侧(含订单/打印/打包/称重信息) | ✓ | ✗ | +| 3 | `waybill.warehouse.export` | 运单导出-仓库侧(按筛选条件) | ✓ | ✗ | + +> **预留接口(本期不实现)**: +> +> | # | method | 描述 | +> |---|--------|------| +> | 4 | `waybill.store.list` | 运单列表-货主侧(按 store_id 隔离) | +> | 5 | `waybill.store.detail` | 运单详情-货主侧 | +> | 6 | `waybill.store.export` | 运单导出-货主侧 | + +--- + +### 3.5 `waybill.warehouse.list` — 运单列表(仓库侧) + +**功能说明**:查询运单号列表,支持分页与多条件筛选。仓库隔离(自动注入 `warehouse_id`)。 + +#### 请求参数 + +```json +{ + "method": "waybill.warehouse.list", + "pagination": { + "page": 1, + "pageSize": 20 + }, + "where": { + "waybillCode": "", + "mainWaybillCode": "", + "orderId": null, + "logisticsCode": "", + "logisticsInterfaceId": null, + "platformCode": "", + "status": null, + "isBack": null, + "isIntercept": null, + "isGalaxyReceive": null, + "packageMaterialId": null, + "hasWeighingWeight": null, + "keyword": "", + "createdAtStart": "", + "createdAtEnd": "" + }, + "sort": { + "field": "create_at", + "order": "desc" + } +} +``` + +#### 参数说明 + +| 参数 | 类型 | 必填 | 说明 | +|------|------|------|------| +| `pagination` | `object` | ✗ | 分页参数 `{ page, pageSize }`,默认 page=1, pageSize=20 | +| `where` | `object` | ✗ | 筛选条件,所有字段均为可选 | +| `where.waybillCode` | `string` | ✗ | 运单号(模糊搜索) | +| `where.mainWaybillCode` | `string` | ✗ | **主单号**(精确匹配)。先通过主单号定位 `order_id`,再返回该订单下所有运单(主+子)。与 `waybillCode` 互斥,同时传入时 `mainWaybillCode` 优先 | +| `where.orderId` | `number` | ✗ | 订单ID(等值) | +| `where.orderNo` | `string` | ✗ | 订单号(需要 JOIN 订单表后模糊匹配) | +| `where.logisticsCode` | `string` | ✗ | 物流公司编码(等值) | +| `where.logisticsInterfaceId` | `number` | ✗ | **物流接口ID**(等值),对应 `wms_order_express.logistics_interface_id`,用于按快递接口筛选运单列表 | +| `where.platformCode` | `string` | ✗ | 平台编码(等值),如 PDD/DY/KS/JD/CAINIAO/SPH/XHS | +| `where.status` | `number` | ✗ | 运单状态:`0`=未分配,`1`=已分配 | +| `where.isBack` | `string` | ✗ | 是否退回:`Y`/`N` | +| `where.isIntercept` | `string` | ✗ | 是否拦截:`Y`/`N` | +| `where.isGalaxyReceive` | `string` | ✗ | 是否星河签收:`Y`/`N` | +| `where.packageMaterialId` | `number` | ✗ | 包材ID(等值) | +| `where.hasWeighingWeight` | `boolean` | ✗ | 是否已称重:`true`=weighing_weight>0,`false`=weighing_weight=0 | +| `where.keyword` | `string` | ✗ | 关键词:匹配运单号(`waybill_code`)、主单号(`main_waybill_code`)、订单号(需 JOIN) | +| `where.createdAtStart` | `string` | ✗ | 创建时间起始(YYYY-MM-DD) | +| `where.createdAtEnd` | `string` | ✗ | 创建时间截止(YYYY-MM-DD) | +| `sort` | `object` | ✗ | 排序 `{ field, order }`,默认 `create_at desc` | +| `sort.field` | `string` | ✗ | 排序字段:`create_at` / `weighing_weight` / `id` | +| `sort.order` | `string` | ✗ | 排序方向:`asc` / `desc`,默认 `desc` | + +#### 响应格式 + +```json +{ + "list": [ + { + "id": 123456, + "waybill_code": "SF1234567890", + "main_waybill_code": "SF1234567890", + "waybill_type": "主单号", + "order_id": 78901, + "order_no": "PO202607290001", + "warehouse_id": 1, + "warehouse_name": "默认仓库", + "store_id": 10, + "store_name": "测试货主", + "business_key": 1, + "status": 1, + "status_text": "已分配", + "logistics_interface_id": 3, + "logistics_code": "SF", + "logistics_name": "顺丰速运", + "logistics_interface_name": "顺丰标准", + "platform_code": "PDD", + "platform_name": "拼多多", + "is_back": "N", + "is_intercept": "N", + "is_galaxy_receive": "N", + "weighing_weight": 1250, + "weighing_weight_display": "1.25 kg", + "package_material_id": 5, + "package_material_name": "3号纸箱", + "pack_status": "已打包", + "print_count": 2, + "last_print_at": "2026-07-29 10:30:00", + "create_at": "2026-07-29 08:00:00" + } + ], + "pagination": { + "page": 1, + "pageSize": 20, + "total": 156, + "totalPages": 8 + } +} +``` + +#### 响应字段说明 + +| 字段 | 类型 | 来源 | 说明 | +|------|------|------|------| +| `id` | `number` | `wms_order_express.id` | 运单记录ID | +| `waybill_code` | `string` | `wms_order_express.waybill_code` | 运单号(当前运单的运单号) | +| `main_waybill_code` | `string` | SELF JOIN 同 order 下 `business_key=1` | **主单号**。当 `business_key=1` 时等于 `waybill_code` 本身;当 `business_key>1` 时通过 SELF JOIN 查找同 `order_id` 下 `business_key=1` 的运单号 | +| `waybill_type` | `string` | 计算字段 | 运单类型:`business_key=1` → `"主单号"`,`business_key>1` → `"子单号"` | +| `order_id` | `number` | `wms_order_express.order_id` | 订单ID | +| `order_no` | `string` | JOIN 订单表 | 订单号(`delivery_order_code`) | +| `warehouse_id` | `number` | `wms_order_express.warehouse_id` | 仓库ID | +| `warehouse_name` | `string` | JOIN `store` 表 | 仓库名称 | +| `store_id` | `number` | JOIN 订单表 | 货主ID | +| `store_name` | `string` | JOIN `store` 表 | 货主名称 | +| `business_key` | `number` | `wms_order_express.business_key` | 拆单序号 | +| `status` | `number` | `wms_order_express.status` | 状态:0/1 | +| `status_text` | `string` | 前端映射 | 状态文本 | +| `logistics_code` | `string` | `wms_order_express.logistics_code` | 物流公司编码 | +| `logistics_name` | `string` | `wms_order_express.logistics_name` | 物流公司名称 | +| `logistics_interface_id` | `number` | `wms_order_express.logistics_interface_id` | 物流接口ID | +| `logistics_interface_name` | `string` | `wms_order_express.logistics_interface_name` | 物流接口名称 | +| `platform_code` | `string` | `wms_order_express.platform_code` | 平台编码 | +| `platform_name` | `string` | 前端映射 | 平台名称 | +| `is_back` | `string` | `wms_order_express.is_back` | 是否退回 | +| `is_intercept` | `string` | `wms_order_express.is_intercept` | 是否拦截 | +| `is_galaxy_receive` | `string` | `wms_order_express.is_galaxy_receive` | 是否星河签收 | +| `weighing_weight` | `number` | `wms_order_express.weighing_weight` | 称重重量(g) | +| `weighing_weight_display` | `string` | 格式化 | 称重重量可读展示 | +| `package_material_id` | `number` | `wms_order_express.package_material_id` | 包材ID | +| `package_material_name` | `string` | `wms_order_express.package_material_name_snapshot` | 包材名称 | +| `pack_status` | `string` | LEFT JOIN `pack_task` | 打包状态("未打包"/"已打包") | +| `print_count` | `number` | COUNT `express_print_record` | 打印次数 | +| `last_print_at` | `string` | MAX `express_print_record.created_at` | 最近打印时间 | +| `create_at` | `string` | `wms_order_express.create_at` | 运单创建时间 | + +#### 查询逻辑要点 + +1. **仓库隔离**:自动注入 `warehouse_id = ctx.user.store_id`(系统统一约定,`ctx.user.store_id` 即为当前用户所属仓库ID)。所有查询 WHERE 条件自动追加 `warehouse_id`,不可由前端入参覆盖 +2. **主单号关联查询**:每条运单记录通过 SELF JOIN(`t1.order_id = t2.order_id AND t2.business_key = 1`)获取主单号 `main_waybill_code`。当 `business_key = 1` 时,主单号就是自身 `waybill_code`;当 `business_key > 1` 时,需要 JOIN 获取主单号 +3. **按主单号入参查询**:当 `where.mainWaybillCode` 传入时,先通过主单号 `waybill_code` 定位 `order_id`(`WHERE waybill_code = ? AND business_key = 1`),再 `WHERE order_id = ?` 返回该订单下所有运单(主+子) +4. **按物流接口ID查询**:直接 `WHERE logistics_interface_id = ?`,等值匹配 +5. **订单号模糊搜索**:当 `where.orderNo` 或 `where.keyword` 匹配到非纯数字运单号时,需要 JOIN 订单表(current/history/dispatch)进行 `delivery_order_code LIKE` 匹配 +6. **打印次数**:通过子查询或 LEFT JOIN + GROUP BY `express_print_record.express_no = waybill_code` 聚合 +7. **打包状态**:LEFT JOIN `pack_task` ON `waybill_code` +8. **性能注意**:打印次数和打包状态的聚合查询在数据量大时可能成为瓶颈,建议先不做 JOIN,改为按需异步加载(在 detail 接口中返回),list 只返回 `wms_order_express` 原生字段 + 主单号 SELF JOIN + +> **性能优化策略**(建议): +> - **方案 A(推荐)**:列表仅查 `wms_order_express` 原生字段,不 JOIN 订单/打印/打包表。`pack_status` 和 `print_count` 通过批量异步查询补充,或仅在 detail 接口返回。 +> - **方案 B**:列表即 JOIN,但需确保索引覆盖良好。 + +--- + +### 3.6 `waybill.warehouse.detail` — 运单详情(仓库侧) + +**功能说明**:查看单个运单的完整信息,包含关联订单、打印记录、打包信息。 + +#### 请求参数 + +```json +{ + "method": "waybill.warehouse.detail", + "id": 123456 +} +``` + +| 参数 | 类型 | 必填 | 说明 | +|------|------|------|------| +| `id` | `number` | ✓ | 运单记录ID(`wms_order_express.id`) | +| `waybillCode` | `string` | ✗ | 运单号(与 id 二选一,waybillCode 优先) | + +#### 响应格式 + +```json +{ + "id": 123456, + "waybill_code": "SF1234567890", + "main_waybill_code": "SF1234567890", + "waybill_type": "主单号", + "business_key": 1, + "sibling_waybills": [ + { "waybill_code": "SF1234567890", "business_key": 1, "waybill_type": "主单号" }, + { "waybill_code": "SF1234567891", "business_key": 2, "waybill_type": "子单号" } + ], + "order": { + "order_id": 78901, + "order_no": "PO202607290001", + "warehouse_id": 1, + "warehouse_name": "默认仓库", + "store_id": 10, + "store_name": "测试货主", + "wave_id": 500, + "wave_no": "W202607290001", + "order_type": "delivery" + }, + "logistics": { + "logistics_code": "SF", + "logistics_name": "顺丰速运", + "logistics_interface_id": 3, + "logistics_interface_name": "顺丰标准", + "platform_code": "PDD" + }, + "status_info": { + "status": 1, + "status_text": "已分配", + "is_back": "N", + "is_intercept": "N", + "is_galaxy_receive": "N" + }, + "weight": { + "weighing_weight": 1250, + "weighing_weight_display": "1.25 kg" + }, + "package": { + "package_material_id": 5, + "package_material_name": "3号纸箱", + "pack_status": "已打包", + "pack_quantity": 3, + "pack_at": "2026-07-29 09:15:00", + "packer_name": "张三" + }, + "print_records": [ + { + "id": 1001, + "printer_name": "打印机-01", + "template_id": 2, + "template_name": "顺丰标准面单", + "platform": "PDD", + "printed_at": "2026-07-29 10:30:00" + } + ], + "print_count": 2, + "printinfo": "{...}", + "ver": "v2.1", + "retry_count": 0, + "create_at": "2026-07-29 08:00:00", + "delete_at": null +} +``` + +#### 查询逻辑要点 + +1. 查询 `wms_order_express` 主记录 +2. 通过 `order_id` 查询同订单下所有运单组成 `sibling_waybills`(含各运单的 `waybill_code`、`business_key`、`waybill_type`) +3. 通过 `order_id` → `OrderDeliveryFactory` 多表遍历查找订单信息 +4. LEFT JOIN `wms_express` 获取物流公司统一名称 +5. LEFT JOIN `pack_task` ON `waybill_code` 获取打包信息 +6. LEFT JOIN `express_print_record` ON `express_no = waybill_code` 获取打印记录列表 +7. 仓库隔离校验 + +--- + +### 3.7 `waybill.warehouse.export` — 运单导出(仓库侧) + +**功能说明**:按筛选条件导出运单列表为 Excel。复用 `waybill.warehouse.list` 的筛选逻辑,去掉分页,全量导出。 + +#### 请求参数 + +同 `waybill.warehouse.list`,不含 `pagination` 参数,可选增加 `exportFields` 指定导出字段。 + +```json +{ + "method": "waybill.warehouse.export", + "where": { "...": "同 waybill.warehouse.list" }, + "sort": { "...": "同 waybill.warehouse.list" }, + "exportFields": ["waybill_code", "order_no", "logistics_name", "weighing_weight", "create_at"] +} +``` + +| 参数 | 类型 | 必填 | 说明 | +|------|------|------|------| +| `where` | `object` | ✗ | 同 `waybill.warehouse.list` 的筛选条件 | +| `sort` | `object` | ✗ | 同 `waybill.warehouse.list` 的排序 | +| `exportFields` | `string[]` | ✗ | 需要导出的字段列表,不传则导出全部字段 | + +--- + +## 四、`methods/system.json` 变更 + +在 `methods.groups[]` 中新增 `waybill.warehouse` group: + +```json +{ + "name": "waybill.warehouse", + "description": "运单号管理(仓库侧)", + "methods": [ + { + "method": "waybill.warehouse.list", + "description": "运单列表(分页+筛选)。仓库隔离。", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [ "... 参数定义 ..." ], + "response": [ "... 返回值定义 ..." ] + }, + { + "method": "waybill.warehouse.detail", + "description": "运单详情(含订单/打印/打包信息)。仓库隔离。", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [ "... 参数定义 ..." ], + "response": [ "... 返回值定义 ..." ] + }, + { + "method": "waybill.warehouse.export", + "description": "运单导出。仓库隔离。", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [ "... 参数定义 ..." ], + "response": [ "... 返回值定义 ..." ] + } + ] +} +``` + +> **预留 group(本期不实现)**:`waybill.store` — 运单号管理(货主侧),按 `store_id` 隔离。 +> +> 完整的 `methods/system.json` method 定义(含 params/response 的 children 详情)在代码实现阶段由 `wms-doc-agent` 补齐。 + +--- + +## 五、文件变更清单 + +| 操作 | 文件路径 | 说明 | +|------|---------|------| +| **新增** | `app/service/systemMethods/waybill/warehouse.js` | 入口层(仓库侧):继承 `MainService`,`systemInit` 声明免鉴权方法,参数校验,委托 `systems/waybill.js` | +| **预留** | `app/service/systemMethods/waybill/store.js` | 入口层(货主侧):本期不创建,后续按需新增 | +| **修改** | `app/service/systems/waybill.js` | 业务层:在现有 `toOrder()` 方法基础上新增 `list()`、`detail()`、`export()` 方法 | +| **修改** | `methods/system.json` | 新增 `waybill.warehouse` group,注册 3 个 method 定义 | +| **新增** | `database/migrations/YYYYMMDDHHmmss-add-waybill-list-indexes.js` | 迁移文件:新增 `idx_warehouse_id_status`、`idx_logistics_code`、`idx_logistics_interface_id`、`idx_warehouse_id_create_at` 索引 | + +--- + +## 六、安全约束 + +| 约束 | 说明 | +|------|------| +| 仓库隔离 | 所有查询自动注入 `warehouse_id = ctx.user.store_id`(系统统一约定),仅返回当前用户所属仓库数据,不可由入参覆盖 | +| 只读 | 本模块一期仅提供只读查询,不涉及运单创建/修改/删除 | +| 鉴权 | 查询接口仅需登录,不做细粒度权限校验(与订单列表保持一致) | + +--- + +## 七、与现有功能的边界划分 + +| 现有功能 | 所属 method | 与新模块关系 | +|---------|------------|-------------| +| 运单号反查订单 | `index.toOrder` | **保留**,独立于新模块。用于 PDA 扫运单号快速定位订单 | +| 订单详情中的运单信息 | `order.detail → expresses[]` | **保留**,不变。新模块提供运单维度的独立视图 | +| 运单包材绑定 | `order.bindExpressPackageMaterial*` | **保留**,不变。仍按订单维度操作 | +| 运单称重更新 | `order.updateExpressWeighingWeight` | **保留**,不变。仍按订单维度操作 | +| 快递号分配 | `order.pendingOrder.allocateExpressCode` | **保留**,不变。仍按订单维度操作 | +| 订单导出(运单模式) | `order.export (export_mode=waybill)` | **保留**,不变。与新模块 `waybill.warehouse.export` 并存 | + +> **核心原则**:新模块不修改任何现有接口,仅新增运单维度的独立查询能力。现有订单维度的运单操作全部保持不动。 + +--- + +## 八、后续扩展方向(不在本期范围) + +| 扩展 | 说明 | +|------|------| +| 运单拦截/解拦截 | 批量操作运单状态 | +| 运单退回标记 | 标记运单退回并记录原因 | +| 运单打印管理 | 批量补打、重新推送电子面单 | +| 运单异常列表 | 独立展示分配失败/打印失败的运单 | +| 运单物流轨迹 | 对接物流轨迹查询接口 | + +--- + +## 九、审阅检查点 + +- [ ] 接口设计是否满足业务需求(运单号独立列表 + 详情) +- [x] ~~仓库隔离策略是否正确~~ → 已核实:全系统统一使用 `ctx.user.store_id` 作为 warehouse_id,与现有模式一致 +- [ ] 列表字段是否完整(是否需要增减字段) +- [ ] 是否需要 JOIN 订单/打印/打包表(性能 vs 信息完整性权衡) +- [ ] 是否需要新增数据库索引 +- [ ] 与现有 `index.toOrder`、`order.*` 接口的边界是否清晰 diff --git a/database/migrations/20260728000000-remove-remote-play-url-from-wms-print-computer.js b/database/migrations/20260728000000-remove-remote-play-url-from-wms-print-computer.js new file mode 100644 index 0000000..89e21fd --- /dev/null +++ b/database/migrations/20260728000000-remove-remote-play-url-from-wms-print-computer.js @@ -0,0 +1,28 @@ +'use strict'; + +module.exports = { + /** + * 移除打印电脑表的 remote_play_url 字段(未被使用)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + await queryInterface.removeColumn('wms_print_computer', 'remote_play_url'); + }, + + /** + * 回滚:恢复 remote_play_url 字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async down(queryInterface, Sequelize) { + await queryInterface.addColumn('wms_print_computer', 'remote_play_url', { + type: Sequelize.STRING(500), + allowNull: true, + defaultValue: null, + comment: '远程播放地址', + }); + }, +}; diff --git a/database/migrations/20260728100000-remove-recording-config-fields-from-wms-print-computer.js b/database/migrations/20260728100000-remove-recording-config-fields-from-wms-print-computer.js new file mode 100644 index 0000000..8e3c3cd --- /dev/null +++ b/database/migrations/20260728100000-remove-recording-config-fields-from-wms-print-computer.js @@ -0,0 +1,43 @@ +'use strict'; + +module.exports = { + /** + * 移除打印电脑表的录制配置字段(recording_size_value / recording_size_unit / recording_directory), + * 这些字段不再由 WMS 侧管理。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + await queryInterface.removeColumn('wms_print_computer', 'recording_directory'); + await queryInterface.removeColumn('wms_print_computer', 'recording_size_unit'); + await queryInterface.removeColumn('wms_print_computer', 'recording_size_value'); + }, + + /** + * 回滚:恢复录制配置字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async down(queryInterface, Sequelize) { + await queryInterface.addColumn('wms_print_computer', 'recording_size_value', { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '录制大小数值', + }); + await queryInterface.addColumn('wms_print_computer', 'recording_size_unit', { + type: Sequelize.STRING(10), + allowNull: true, + defaultValue: null, + comment: '录制存储单位:KB/MB/GB/TB', + }); + await queryInterface.addColumn('wms_print_computer', 'recording_directory', { + type: Sequelize.STRING(500), + allowNull: true, + defaultValue: null, + comment: '录制目录路径', + }); + }, +}; diff --git a/database/migrations/20260728110000-restore-recording-directory-to-wms-print-computer.js b/database/migrations/20260728110000-restore-recording-directory-to-wms-print-computer.js new file mode 100644 index 0000000..40133b5 --- /dev/null +++ b/database/migrations/20260728110000-restore-recording-directory-to-wms-print-computer.js @@ -0,0 +1,28 @@ +'use strict'; + +module.exports = { + /** + * 恢复 wms_print_computer 的 recording_directory 字段(录制目录路径)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + await queryInterface.addColumn('wms_print_computer', 'recording_directory', { + type: Sequelize.STRING(500), + allowNull: true, + defaultValue: null, + comment: '录制目录路径', + }); + }, + + /** + * 回滚:移除 recording_directory 字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async down(queryInterface, Sequelize) { + await queryInterface.removeColumn('wms_print_computer', 'recording_directory'); + }, +}; diff --git a/database/migrations/20260728120000-create-wms-after-sale-work-order.js b/database/migrations/20260728120000-create-wms-after-sale-work-order.js new file mode 100644 index 0000000..6854144 --- /dev/null +++ b/database/migrations/20260728120000-create-wms-after-sale-work-order.js @@ -0,0 +1,215 @@ +'use strict'; + +const TABLE_NAME = 'wms_after_sale_work_order'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME); + if (exists) return; + + await queryInterface.createTable(TABLE_NAME, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + store_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '货主ID', + }, + work_order_no: { + type: Sequelize.STRING(50), + allowNull: false, + comment: '售后工单号,唯一', + }, + business_type: { + type: Sequelize.STRING(50), + allowNull: false, + comment: '关联业务类型', + }, + business_sub_type: { + type: Sequelize.STRING(50), + allowNull: false, + comment: '关联业务子类型', + }, + business_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '关联业务单据主键ID(多态关联)', + }, + business_no: { + type: Sequelize.STRING(100), + allowNull: true, + comment: '关联业务单据号(冗余)', + }, + direction: { + type: Sequelize.TINYINT.UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '记账方向:0=未确定 1=入库 2=出库', + }, + status: { + type: Sequelize.TINYINT.UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '工单状态:0=待处理 1=处理中 2=已完成 3=已关闭 9=已取消', + }, + priority: { + type: Sequelize.TINYINT.UNSIGNED, + allowNull: false, + defaultValue: 50, + comment: '优先级:1~100,数字越大优先级越高', + }, + title: { + type: Sequelize.STRING(200), + allowNull: false, + comment: '工单标题/摘要', + }, + description: { + type: Sequelize.TEXT, + allowNull: true, + comment: '问题描述', + }, + creator_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '创建人ID,关联 account.id;0 表示 AI 自动接待', + }, + creator_snapshot: { + type: Sequelize.TEXT, + allowNull: true, + comment: '创建人信息快照(JSON格式)', + }, + assignee_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '当前处理人ID,关联 account.id', + }, + parent_work_order_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '父工单ID,自关联本表;非空时表示子工单', + }, + current_step: { + type: Sequelize.TINYINT.UNSIGNED, + allowNull: false, + defaultValue: 1, + comment: '当前进度,值为当前正在处理的 step_order 序号', + }, + claim_needed: { + type: Sequelize.TINYINT.UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '是否需要理赔:0=不需要 1=需要', + }, + claim_amount: { + type: Sequelize.DECIMAL(12, 2), + allowNull: true, + defaultValue: 0.00, + comment: '理赔金额(元)', + }, + claim_status: { + type: Sequelize.TINYINT.UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '理赔状态:0=未理赔 1=已理赔(单笔结清) 2=月结', + }, + resolution: { + type: Sequelize.TEXT, + allowNull: true, + comment: '处理结果说明', + }, + resolved_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '解决时间', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '软删除时间', + }, + }); + + // 工单号唯一 + await queryInterface.addIndex(TABLE_NAME, ['work_order_no'], { + unique: true, + name: 'uk_work_order_no', + }); + + // 仓库隔离查询 + await queryInterface.addIndex(TABLE_NAME, ['warehouse_id'], { + name: 'idx_warehouse_id', + }); + + // 货主隔离查询 + await queryInterface.addIndex(TABLE_NAME, ['store_id'], { + name: 'idx_store_id', + }); + + // 按业务类型+子类型+单据ID反查工单 + await queryInterface.addIndex(TABLE_NAME, ['business_type', 'business_sub_type', 'business_id'], { + name: 'idx_business_type_subtype_id', + }); + + // 按状态筛选 + await queryInterface.addIndex(TABLE_NAME, ['status'], { + name: 'idx_status', + }); + + // 按处理人查询 + await queryInterface.addIndex(TABLE_NAME, ['assignee_id'], { + name: 'idx_assignee_id', + }); + + // 按父工单查子工单 + await queryInterface.addIndex(TABLE_NAME, ['parent_work_order_id'], { + name: 'idx_parent_work_order_id', + }); + + // 按优先级排序 + await queryInterface.addIndex(TABLE_NAME, ['priority'], { + name: 'idx_priority', + }); + + // 按理赔状态筛选 + await queryInterface.addIndex(TABLE_NAME, ['claim_status'], { + name: 'idx_claim_status', + }); + + // 按时间排序 + await queryInterface.addIndex(TABLE_NAME, ['created_at'], { + name: 'idx_created_at', + }); + + // 软删除查询优化 + await queryInterface.addIndex(TABLE_NAME, ['deleted_at'], { + name: 'idx_deleted_at', + }); + }, + + down: async queryInterface => { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260728120000-restore-recording-size-fields-to-wms-print-computer.js b/database/migrations/20260728120000-restore-recording-size-fields-to-wms-print-computer.js new file mode 100644 index 0000000..cbe848f --- /dev/null +++ b/database/migrations/20260728120000-restore-recording-size-fields-to-wms-print-computer.js @@ -0,0 +1,35 @@ +'use strict'; + +module.exports = { + /** + * 恢复 wms_print_computer 的 recording_size_value 和 recording_size_unit 字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + await queryInterface.addColumn('wms_print_computer', 'recording_size_value', { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '录制大小数值', + }); + await queryInterface.addColumn('wms_print_computer', 'recording_size_unit', { + type: Sequelize.STRING(10), + allowNull: true, + defaultValue: null, + comment: '录制存储单位:KB/MB/GB/TB', + }); + }, + + /** + * 回滚:移除 recording_size_value 和 recording_size_unit 字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async down(queryInterface, Sequelize) { + await queryInterface.removeColumn('wms_print_computer', 'recording_size_unit'); + await queryInterface.removeColumn('wms_print_computer', 'recording_size_value'); + }, +}; diff --git a/database/migrations/20260728130000-create-wms-after-sale-work-order-step.js b/database/migrations/20260728130000-create-wms-after-sale-work-order-step.js new file mode 100644 index 0000000..3564929 --- /dev/null +++ b/database/migrations/20260728130000-create-wms-after-sale-work-order-step.js @@ -0,0 +1,115 @@ +'use strict'; + +const TABLE_NAME = 'wms_after_sale_work_order_step'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME); + if (exists) return; + + await queryInterface.createTable(TABLE_NAME, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + work_order_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '工单ID,关联 wms_after_sale_work_order.id', + }, + step_order: { + type: Sequelize.TINYINT.UNSIGNED, + allowNull: false, + defaultValue: 1, + comment: '步骤序号(从1开始递增)', + }, + step_name: { + type: Sequelize.STRING(100), + allowNull: false, + comment: '步骤名称', + }, + step_status: { + type: Sequelize.TINYINT.UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '步骤状态:0=待开始 1=进行中 2=已完成 3=已跳过', + }, + operator_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '操作员工ID,关联 account.id', + }, + operator_snapshot: { + type: Sequelize.TEXT, + allowNull: true, + comment: '操作人信息快照(JSON格式)', + }, + action: { + type: Sequelize.STRING(100), + allowNull: true, + comment: '操作动作描述', + }, + remark: { + type: Sequelize.TEXT, + allowNull: true, + comment: '处理备注', + }, + started_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '步骤开始时间', + }, + completed_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '步骤完成时间', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '软删除时间', + }, + }); + + // 按工单查所有步骤 + await queryInterface.addIndex(TABLE_NAME, ['work_order_id'], { + name: 'idx_work_order_id', + }); + + // 按操作人反查 + await queryInterface.addIndex(TABLE_NAME, ['operator_id'], { + name: 'idx_operator_id', + }); + + // 软删除查询优化 + await queryInterface.addIndex(TABLE_NAME, ['deleted_at'], { + name: 'idx_deleted_at', + }); + + // 同一工单下步骤序号唯一(含软删除) + await queryInterface.addIndex(TABLE_NAME, ['work_order_id', 'step_order', 'deleted_at'], { + unique: true, + name: 'uk_work_order_step', + }); + }, + + down: async queryInterface => { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/methods/changes/system.json b/methods/changes/system.json index 6913765..f3daf2b 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,47 @@ [ + { + "version": "2026.07.28-system-01", + "date": "2026-07-28", + "type": "added", + "summary": "新增 order.pendingOrder.batchMarkPrinted:批量设置订单为已打印状态,将 print_status 更新为 'fin'", + "methods": [ + "order.pendingOrder.batchMarkPrinted" + ], + "notes": [ + "同步批量更新接口,传入订单ID数组,直接将符合条件的订单 print_status 设为 'fin'。", + "双表查询:先查 current 表(wms_order_delivery_{warehouseId}),未命中的 ID 再兜底查 dispatch 表(wms_order_delivery_{warehouseId}_dispatch)。", + "dispatch 表查询失败仅记录 warn 日志,不影响 current 表已更新的结果。", + "仅允许 step 在 [1,2,3] 且 status 不为 'cancel' 的订单操作,已打印(print_status='fin')的订单会被静默跳过。", + "仓库上下文强制从 ctx.user.store_id 获取,禁止传入外部仓库ID。", + "入参支持 order_ids / orderIds / ids 三种别名,优先级 order_ids > orderIds > ids。", + "返回 updated_count 表示实际更新条数(current + dispatch 合计),ids 原样回传请求的订单ID列表。", + "写入操作日志 operation_code: ORDER_BATCH_MARK_PRINTED。" + ], + "module": "order.pendingOrder" + }, + { + "version": "2026.07.27-system-03", + "date": "2026-07-27", + "type": "changed", + "summary": "storage.receiving 导出接口拆分:export 改为按仓库维度,新增 storeExport 按货主维度导出", + "methods": [ + "storage.receiving.export", + "storage.receiving.exportTaskProgress", + "storage.receiving.storeExport", + "storage.receiving.storeExportTaskProgress" + ], + "notes": [ + "export 改为仓库维度:过滤条件从 store_id(平台激活货主)改为 warehouse_id(ctx.user.store_id),与 getReceivingList 保持一致。", + "exportTaskProgress 同步更新为仓库维度进度查询,任务 ID 前缀 receiving_export_。", + "新增 storeExport:货主维度导出,通过平台激活上下文获取 store_id,过滤逻辑与 getStoreReceivingList 一致。", + "新增 storeExportTaskProgress:货主维度进度查询,复用 exportTaskProgress 的缓存逻辑,任务 ID 前缀 receiving_store_export_。", + "导出格式:双 Sheet Excel(Sheet1=收货单列表 21 列,Sheet2=收货单明细 17 列),通过 ExcelJS stream + uploadService 上传 COS。", + "仓库导出上传路径 exports/receiving/{warehouseId}/,货主导出上传路径 exports/receiving/store/{storeId}/。", + "修复 exportReceivingList 中 where 条件二次解析问题:增加 ctx.whereParsed 复用(与 getStoreReceivingList 一致),避免 prepareWhereContext 已解析后再重复 parseWhereConditions 导致边界条件丢失。", + "命名对齐 entry 侧:storeExport / storeExportTaskProgress 方法名、任务 ID 前缀、上传路径均与 storage.entry.storeExport 模式一致。" + ], + "module": "storage.receiving" + }, { "version": "2026.07.27-system-02", "date": "2026-07-27", diff --git a/methods/system.json b/methods/system.json index c09372e..731ccea 100644 --- a/methods/system.json +++ b/methods/system.json @@ -26015,6 +26015,53 @@ } ] }, + { + "method": "order.pendingOrder.batchMarkPrinted", + "description": "批量设置订单为已打印状态。将给定订单ID列表中属于当前仓库的订单的 print_status 更新为 'fin'。先查 current 表(wms_order_delivery_{warehouseId}),未命中的 ID 再兜底查 dispatch 表(wms_order_delivery_{warehouseId}_dispatch)。仅允许 step 在 [1,2,3] 且 status 不为 'cancel' 的订单操作,已打印的订单会被静默跳过。仓库ID统一使用当前上下文(ctx.user.store_id)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "order_ids / orderIds / ids", + "type": "number[]", + "required": true, + "source": "body", + "description": "订单ID数组;优先级 order_ids > orderIds > ids" + } + ], + "response": [ + { + "name": "updated_count", + "type": "number", + "required": true, + "description": "实际更新的订单数量(已打印的订单会被静默跳过,不计入)" + }, + { + "name": "ids", + "type": "number[]", + "required": true, + "description": "请求的订单ID列表(原样回传)" + } + ], + "errors": [ + { + "code": 400, + "message": "未识别到当前仓库上下文" + }, + { + "code": 400, + "message": "order_ids 参数不能为空或格式错误" + } + ] + }, { "method": "order.bindExpressPackageMaterialByWaybill", "description": "按运单号绑定包材。仅需传入运单号与包材ID,系统自动根据运单号反查对应订单运单记录并绑定包材,无需传入订单ID。", From 76e25db7da0699ae864c715da972497abd4c0e45 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sat, 1 Aug 2026 03:39:41 +0800 Subject: [PATCH 137/550] =?UTF-8?q?feat(apiApp):=20=E6=96=B0=E5=A2=9E?= =?UTF-8?q?=E4=BB=93=E5=BA=93=20API=20=E5=BA=94=E7=94=A8=E7=AE=A1=E7=90=86?= =?UTF-8?q?=E6=A8=A1=E5=9D=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 systems/apiApp.js 业务层:CRUD + AppKey/Secret 自动生成 + 仓库隔离 - 新增 systemMethods/apiApp.js 入口层:list/detail/create/update/delete/regenerateSecret - 注册 methods/system.json API 文档 + changes 变更记录 - 新增迁移脚本:wms_permission 固定 ID 464-470 + 客服组主管及以上角色授权 --- app/service/systemMethods/apiApp.js | 117 + app/service/systems/apiApp.js | 320 ++ .../20260801120000-add-apiApp-permissions.js | 80 + methods/changes/system.json | 138 +- methods/system.json | 2677 ++++++++++++++++- 5 files changed, 3189 insertions(+), 143 deletions(-) create mode 100644 app/service/systemMethods/apiApp.js create mode 100644 app/service/systems/apiApp.js create mode 100644 database/migrations/20260801120000-add-apiApp-permissions.js diff --git a/app/service/systemMethods/apiApp.js b/app/service/systemMethods/apiApp.js new file mode 100644 index 0000000..87c126c --- /dev/null +++ b/app/service/systemMethods/apiApp.js @@ -0,0 +1,117 @@ +'use strict'; + +const MainService = require('../main'); + +/** + * 仓库 API 应用管理 Service + * 管理当前仓库的外部 API 应用(AppKey/Secret 生成、IP 白名单、限流等)。 + * 仓库隔离:所有操作自动按 ctx.user.store_id 过滤。 + */ +class ApiAppService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = ''; + const _noNeedLog = ''; + const _noNeedAuth = ''; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 查询当前仓库的 API 应用列表(分页)。 + * @param {Object} data 查询参数。 + * @return {Promise} 分页结果。 + */ + async list(data) { + try { + const result = await this.service.systems.apiApp.list(data || {}); + return this.success('获取成功', result); + } catch (e) { return this.fail(e.message); } + } + + /** + * 查询单个 API 应用详情。 + * @param {Object} data 查询参数。 + * @param {number|string} data.id 应用 ID。 + * @return {Promise} 应用详情。 + */ + async detail(data) { + try { + const { id } = data || {}; + if (!id) return this.fail('ID不能为空'); + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id || 0); + const defaultTypeId = await this.service.systems.apiApp.getDefaultInterfaceTypeId(); + const record = await ctx.model.ApiApp.findOne({ + attributes: [ + 'id', 'app_name', 'warehouse_id', 'self_app_key', 'self_app_secret', + 'self_ip_whitelist', 'callback_url', 'interface_type_id', + 'rate_limit', 'sign_method', 'is_enabled', 'created_at', 'updated_at', + ], + where: { id: Number(id), warehouse_id: warehouseId, interface_type_id: defaultTypeId }, + raw: true, + }); + if (!record) return this.fail('API应用不存在'); + record.self_app_secret = record.self_app_secret + ? String(record.self_app_secret).substring(0, 8) + '****' + : ''; + return this.success('获取成功', record); + } catch (e) { return this.fail(e.message); } + } + + /** + * 创建 API 应用,自动生成 AppKey 和 AppSecret。 + * @param {Object} data 创建参数。 + * @return {Promise} 创建结果(含完整 secret)。 + */ + async create(data) { + try { + const result = await this.service.systems.apiApp.create(data || {}); + return this.success('创建成功', result); + } catch (e) { return this.fail(e.message); } + } + + /** + * 更新 API 应用。 + * @param {Object} data 更新参数。 + * @return {Promise} 更新结果。 + */ + async update(data) { + try { + const { id, ...fields } = data || {}; + if (!id) return this.fail('ID不能为空'); + const result = await this.service.systems.apiApp.update(id, fields); + return this.success('更新成功', result); + } catch (e) { return this.fail(e.message); } + } + + /** + * 删除/停用 API 应用。 + * @param {Object} data 删除参数。 + * @return {Promise} 删除结果。 + */ + async delete(data) { + try { + const { id } = data || {}; + if (!id) return this.fail('ID不能为空'); + await this.service.systems.apiApp.delete(id); + return this.success('删除成功'); + } catch (e) { return this.fail(e.message); } + } + + /** + * 重新生成 AppSecret。 + * @param {Object} data 参数。 + * @return {Promise} 新 secret。 + */ + async regenerateSecret(data) { + try { + const { id } = data || {}; + if (!id) return this.fail('ID不能为空'); + const result = await this.service.systems.apiApp.regenerateSecret(id); + return this.success('重新生成成功', result); + } catch (e) { return this.fail(e.message); } + } +} + +module.exports = ApiAppService; diff --git a/app/service/systems/apiApp.js b/app/service/systems/apiApp.js new file mode 100644 index 0000000..c5b7042 --- /dev/null +++ b/app/service/systems/apiApp.js @@ -0,0 +1,320 @@ +'use strict'; + +const { randomBytes } = require('node:crypto'); +const { Service } = require('egg'); + +class ApiAppService extends Service { + /** + * 生成唯一的 AppKey。 + * 格式:AK{yyyyMMddHHmmss}{random8} + * @return {string} AppKey + */ + generateAppKey() { + const now = new Date(); + const timestamp = [ + now.getFullYear(), + String(now.getMonth() + 1).padStart(2, '0'), + String(now.getDate()).padStart(2, '0'), + String(now.getHours()).padStart(2, '0'), + String(now.getMinutes()).padStart(2, '0'), + String(now.getSeconds()).padStart(2, '0'), + ].join(''); + return `AK${timestamp}${randomBytes(4).toString('hex')}`; + } + + /** + * 生成 AppSecret。 + * @return {string} 64 字符十六进制密钥。 + */ + generateAppSecret() { + return randomBytes(32).toString('hex'); + } + + /** + * 获取默认的仓库渠道接口类型 ID。 + * 查找 interface_type 中 interface_code = 'OPEN_API_WAREHOUSE' 的记录。 + * @return {Promise} 接口类型 ID,找不到时返回 0。 + */ + async getDefaultInterfaceTypeId() { + const row = await this.ctx.model.InterfaceType.findOne({ + attributes: [ 'id' ], + where: { interface_code: 'OPEN_API_WAREHOUSE', is_enabled: 1 }, + raw: true, + }); + return row ? Number(row.id) : 0; + } + + /** + * 查询当前仓库的 API 应用列表(分页)。 + * @param {Object} data 查询参数。 + * @param {number} [data.page=1] 页码。 + * @param {number} [data.pageSize=20] 每页数量。 + * @param {string} [data.app_name] 应用名称(模糊搜索)。 + * @param {number} [data.is_enabled] 启用状态。 + * @return {Promise} 分页结果。 + */ + async list(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id || 0); + const page = Math.max(1, Number(data.page) || 1); + const pageSize = Math.min(100, Math.max(1, Number(data.pageSize) || 20)); + + // 仅查询仓库开放接口类型的应用,排除货主/奇门等类型 + const where = { + warehouse_id: warehouseId, + interface_type_id: await this.getDefaultInterfaceTypeId(), + }; + if (data.app_name) { + where.app_name = { [this.app.Sequelize.Op.like]: `%${String(data.app_name).trim()}%` }; + } + if (data.is_enabled !== undefined && data.is_enabled !== null && data.is_enabled !== '') { + where.is_enabled = Number(data.is_enabled); + } + + const total = await ctx.model.ApiApp.count({ where }); + const list = await ctx.model.ApiApp.findAll({ + attributes: [ + 'id', 'app_name', 'warehouse_id', 'self_app_key', 'self_app_secret', + 'self_ip_whitelist', 'callback_url', 'interface_type_id', + 'rate_limit', 'sign_method', 'is_enabled', 'created_at', 'updated_at', + ], + where, + offset: (page - 1) * pageSize, + limit: pageSize, + order: [[ 'id', 'DESC' ]], + raw: true, + }); + + // 脱敏:只返回 secret 前 8 位 + const maskedList = list.map(item => ({ + ...item, + self_app_secret: item.self_app_secret + ? String(item.self_app_secret).substring(0, 8) + '****' + : '', + })); + + return { + list: maskedList, + pagination: { + page, + pageSize, + total, + totalPages: Math.ceil(total / pageSize), + hasNext: page * pageSize < total, + hasPrevious: page > 1, + }, + }; + } + + /** + * 创建仓库 API 应用,自动生成 AppKey 和 AppSecret。 + * @param {Object} data 创建参数。 + * @param {string} data.app_name 应用名称(必填)。 + * @param {number|string} [data.interface_type_id] 接口类型 ID,不传则查 WH_CHANNEL。 + * @param {Array} [data.self_ip_whitelist] IP 白名单。 + * @param {string} [data.callback_url] 回调地址。 + * @param {number} [data.rate_limit=1000] 速率限制。 + * @param {string} [data.sign_method='md5'] 签名方法。 + * @return {Promise} 创建结果(含完整 secret,仅创建时返回)。 + */ + async create(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id || 0); + + if (!warehouseId) { + throw new Error('无法获取当前仓库ID'); + } + + const appName = String(data.app_name || '').trim(); + if (!appName) { + throw new Error('应用名称不能为空'); + } + if (appName.length > 200) { + throw new Error('应用名称不能超过200个字符'); + } + + const interfaceTypeId = data.interface_type_id + ? Number(data.interface_type_id) + : await this.getDefaultInterfaceTypeId(); + + const appKey = this.generateAppKey(); + const appSecret = this.generateAppSecret(); + + const payload = { + app_name: appName, + warehouse_id: warehouseId, + interface_type_id: interfaceTypeId, + self_app_key: appKey, + self_app_secret: appSecret, + self_ip_whitelist: Array.isArray(data.self_ip_whitelist) ? data.self_ip_whitelist : null, + callback_url: String(data.callback_url || '').trim() || null, + rate_limit: Number(data.rate_limit) || 1000, + sign_method: [ 'md5', 'hmac', 'sha256' ].includes(String(data.sign_method || '').trim()) + ? String(data.sign_method).trim() + : 'md5', + is_enabled: 1, + }; + + const record = await ctx.model.ApiApp.create(payload); + + this.ctx.logger.info('[apiApp] 创建仓库API应用成功', { + warehouseId, + appId: record.id, + appName, + appKey, + }); + + return { + id: record.id, + app_name: record.app_name, + warehouse_id: record.warehouse_id, + interface_type_id: record.interface_type_id, + self_app_key: record.self_app_key, + self_app_secret: record.self_app_secret, + self_ip_whitelist: record.self_ip_whitelist, + callback_url: record.callback_url, + rate_limit: record.rate_limit, + sign_method: record.sign_method, + is_enabled: record.is_enabled, + created_at: record.created_at, + updated_at: record.updated_at, + }; + } + + /** + * 更新仓库 API 应用。 + * @param {number|string} id 应用 ID。 + * @param {Object} data 更新字段。 + * @param {string} [data.app_name] 应用名称。 + * @param {Array} [data.self_ip_whitelist] IP 白名单。 + * @param {string} [data.callback_url] 回调地址。 + * @param {number} [data.rate_limit] 速率限制。 + * @param {string} [data.sign_method] 签名方法。 + * @param {number} [data.is_enabled] 启用状态。 + * @return {Promise} 更新后的记录(脱敏)。 + */ + async update(id, data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id || 0); + + const record = await ctx.model.ApiApp.findOne({ + where: { id: Number(id), warehouse_id: warehouseId, interface_type_id: await this.getDefaultInterfaceTypeId() }, + }); + + if (!record) { + throw new Error('API应用不存在或不属于当前仓库'); + } + + const updatableFields = [ 'app_name', 'self_ip_whitelist', 'callback_url', 'rate_limit', 'sign_method', 'is_enabled' ]; + for (const field of updatableFields) { + if (data[field] !== undefined && data[field] !== null) { + if (field === 'sign_method') { + const val = String(data[field]).trim(); + if (![ 'md5', 'hmac', 'sha256' ].includes(val)) { + throw new Error('签名方法仅支持 md5/hmac/sha256'); + } + record[field] = val; + } else if (field === 'is_enabled') { + record[field] = Number(data[field]); + } else if (field === 'rate_limit') { + const val = Number(data[field]); + record[field] = val > 0 && val <= 100000 ? val : record[field]; + } else if (field === 'app_name') { + const val = String(data[field]).trim(); + if (!val) throw new Error('应用名称不能为空'); + if (val.length > 200) throw new Error('应用名称不能超过200个字符'); + record[field] = val; + } else { + record[field] = data[field]; + } + } + } + + await record.save(); + + this.ctx.logger.info('[apiApp] 更新仓库API应用成功', { + warehouseId, + appId: record.id, + }); + + return { + id: record.id, + app_name: record.app_name, + warehouse_id: record.warehouse_id, + interface_type_id: record.interface_type_id, + self_app_key: record.self_app_key, + self_app_secret: record.self_app_secret + ? String(record.self_app_secret).substring(0, 8) + '****' + : '', + self_ip_whitelist: record.self_ip_whitelist, + callback_url: record.callback_url, + rate_limit: record.rate_limit, + sign_method: record.sign_method, + is_enabled: record.is_enabled, + created_at: record.created_at, + updated_at: record.updated_at, + }; + } + + /** + * 删除仓库 API 应用(软删除:is_enabled=0)。 + * @param {number|string} id 应用 ID。 + * @return {Promise} 无返回值。 + */ + async delete(id) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id || 0); + + const record = await ctx.model.ApiApp.findOne({ + where: { id: Number(id), warehouse_id: warehouseId, interface_type_id: await this.getDefaultInterfaceTypeId() }, + }); + + if (!record) { + throw new Error('API应用不存在或不属于当前仓库'); + } + + record.is_enabled = 0; + await record.save(); + + this.ctx.logger.info('[apiApp] 停用仓库API应用成功', { + warehouseId, + appId: record.id, + }); + } + + /** + * 重新生成 AppSecret。 + * @param {number|string} id 应用 ID。 + * @return {Promise} 包含新 secret 的结果(仅此次返回完整 secret)。 + */ + async regenerateSecret(id) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id || 0); + + const record = await ctx.model.ApiApp.findOne({ + where: { id: Number(id), warehouse_id: warehouseId, interface_type_id: await this.getDefaultInterfaceTypeId() }, + }); + + if (!record) { + throw new Error('API应用不存在或不属于当前仓库'); + } + + const newSecret = this.generateAppSecret(); + record.self_app_secret = newSecret; + await record.save(); + + this.ctx.logger.info('[apiApp] 重新生成AppSecret成功', { + warehouseId, + appId: record.id, + }); + + return { + id: record.id, + app_name: record.app_name, + self_app_key: record.self_app_key, + self_app_secret: newSecret, + }; + } +} + +module.exports = ApiAppService; diff --git a/database/migrations/20260801120000-add-apiApp-permissions.js b/database/migrations/20260801120000-add-apiApp-permissions.js new file mode 100644 index 0000000..486d856 --- /dev/null +++ b/database/migrations/20260801120000-add-apiApp-permissions.js @@ -0,0 +1,80 @@ +'use strict'; + +/** + * 为 apiApp 仓库 API 应用管理模块创建权限并授权给客服组-主管及以上角色。 + * + * 固定 ID(开发库 & 生产库 wms_permission 当前 max_id 均为 463): + * 464 — 父级菜单 "API应用管理" + * 465 — apiApp.list + * 466 — apiApp.detail + * 467 — apiApp.create + * 468 — apiApp.update + * 469 — apiApp.delete + * 470 — apiApp.regenerateSecret + * + * 授权角色(permissions 不为 "*" 的 主管/经理 级角色): + * 8 — 经理 + * 26 — 仓库组-主管 + * 28 — 客服组-主管 + * 29 — 生产组-主管 + */ +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + // ── 1. 插入父级权限 (type=web_pages, sort=1, status=1) ── + await queryInterface.sequelize.query(` + INSERT INTO wms_permission (id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at) + VALUES (464, 'apiApp', NULL, 'API应用管理', NULL, 'API应用管理', NULL, 0, 0, NULL, 'web_pages', 1, 1, NOW(), NOW()) + `); + + // ── 2. 插入 6 个接口权限 ── + const methods = [ + [ 465, 'apiApp.list' ], + [ 466, 'apiApp.detail' ], + [ 467, 'apiApp.create' ], + [ 468, 'apiApp.update' ], + [ 469, 'apiApp.delete' ], + [ 470, 'apiApp.regenerateSecret' ], + ]; + + for (const [ id, method ] of methods) { + await queryInterface.sequelize.query(` + INSERT INTO wms_permission (id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at) + VALUES (${id}, '${method}', NULL, '${method}', NULL, 'API:${method}', NULL, 0, 0, 464, 'api', 0, 1, NOW(), NOW()) + `); + } + + // ── 3. 给 客服组-主管及以上角色 追加新权限 ID ── + // 只更新 permissions 为显式列表(非 "*")的角色 + const newIdSuffix = ', 465, 466, 467, 468, 469, 470'; + + await queryInterface.sequelize.query(` + UPDATE wms_role + SET permissions = CONCAT(LEFT(permissions, LENGTH(permissions) - 1), '${newIdSuffix}]') + WHERE id IN (8, 26, 28, 29) + AND permissions != '*' + AND permissions IS NOT NULL + AND LENGTH(permissions) > 2 + `); + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + // ── 1. 从角色权限中移除新增的 ID ── + await queryInterface.sequelize.query(` + UPDATE wms_role + SET permissions = REPLACE(permissions, ', 465, 466, 467, 468, 469, 470', '') + WHERE id IN (8, 26, 28, 29) + `); + + // ── 2. 删除 6 个接口权限 ── + await queryInterface.sequelize.query( + 'DELETE FROM wms_permission WHERE id IN (465, 466, 467, 468, 469, 470)' + ); + + // ── 3. 删除父级权限 ── + await queryInterface.sequelize.query( + 'DELETE FROM wms_permission WHERE id = 464' + ); + }, +}; diff --git a/methods/changes/system.json b/methods/changes/system.json index f3daf2b..49f9658 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,83 @@ [ + { + "version": "2026.08.01-system-01", + "date": "2026-08-01", + "type": "added", + "summary": "新增 apiApp 仓库 API 应用管理模块,支持当前仓库维度的 API 应用 CRUD、AppKey/Secret 自动生成与重新生成、IP 白名单、回调地址、限流等配置", + "methods": [ + "apiApp.list", + "apiApp.detail", + "apiApp.create", + "apiApp.update", + "apiApp.delete", + "apiApp.regenerateSecret" + ], + "notes": [ + "apiApp.list:分页查询当前仓库 API 应用列表,支持按 app_name(模糊)、is_enabled 筛选,Secret 自动脱敏(前8位+****)。", + "apiApp.detail:按 ID 查询单个应用详情,需同时匹配 warehouse_id(自动注入 ctx.user.store_id),Secret 脱敏。", + "apiApp.create:创建应用时自动生成 AppKey(AK{yyyyMMddHHmmss}{random8hex})和 AppSecret(64位hex)。默认 interface_type_id 取 WH_CHANNEL。仅创建时返回完整 Secret。", + "apiApp.update:更新可编辑字段(app_name、self_ip_whitelist、callback_url、rate_limit、sign_method、is_enabled),不可变字段为 self_app_key 和 interface_type_id。", + "apiApp.delete:软删除(is_enabled=0),不物理删除。", + "apiApp.regenerateSecret:重新生成 64位hex AppSecret,旧 Secret 立即失效。仅此次返回完整 Secret。", + "仓库隔离:所有操作按 ctx.user.store_id → warehouse_id 自动过滤。", + "Secret 安全策略:list/detail/update 返回脱敏值,仅 create/regenerateSecret 返回完整 Secret。" + ], + "module": "apiApp" + }, + { + "version": "2026.07.31-system-02", + "date": "2026-07-31", + "type": "added", + "summary": "新增 storage.inventory.export 库存导出与 storage.inventory.exportTaskProgress 导出进度查询,入参复用 list 的 where/sort/group_by_batch 语义,支持两种导出模式(聚合汇总 / 逐条明细),库位信息一并导出", + "methods": [ + "storage.inventory.export", + "storage.inventory.exportTaskProgress" + ], + "notes": [ + "storage.inventory.export:异步提交导出任务,返回 task_id 与受理信息,后端异步生成 Excel 并上传。入参 where/sort/group_by_batch 与 storage.inventory.list 完全一致,无需额外学习成本。", + "group_by_batch=false(默认):按 stock_id + space_id(库位)聚合导出库存汇总,含商品编码/名称/规格/单位/货主/库位编码/名称/总库存/锁定/可用/批次数/最近入库时间。", + "group_by_batch=true:按 storage_id 逐条导出库存明细,含库存记录ID/商品信息/库位信息/批次号/库存类型/数量/生产日期/过期日期/入库时间/入库单号/供应商批次号。", + "新增 storage.inventory.exportTaskProgress:按 task_id/taskId 查询导出任务进度与状态(submitted/running/success/failed/not_found),status=success 时返回 download_url 供客户端下载。", + "导出文件目录:exports/storage/inventory/{warehouseId}/,缓存 TTL 1800 秒。" + ], + "module": "storage.inventory" + }, + { + "version": "2026.07.31-system-01", + "date": "2026-07-31", + "type": "added", + "summary": "新增按波次批量快捷复核接口 batchQuickRecheckByWave,支持批量波次 IDs 的前置条件检查(储位、快递、同步、拦截),自动完成拣货并标记复核,支持部分失败", + "methods": [ + "order.recheckOrder.batchQuickRecheckByWave" + ], + "notes": [ + "新增 order.recheckOrder.batchQuickRecheckByWave 方法,复用 batchQuickRecheck 的 _completePickForOrder / _markRecheckForOrder / _tryCompleteWaveInTransaction 等内部事务方法", + "入参 wave_ids 支持数组或逗号分隔字符串,兼容 waveIds(驼峰)、wave_id(单值)", + "按波次维度批量查询订单后逐波次、逐订单执行前置校验与复核,每个订单独立事务,部分失败不影响其他订单", + "响应包含 success/failed 列表及计数,failed 项含 order_id、wave_id、delivery_order_code、reason 说明;波次下无订单时仅返回 wave_id + reason" + ], + "module": "order.recheckOrder" + }, + { + "version": "2026.07.29-system-01", + "date": "2026-07-29", + "type": "added", + "summary": "补全 waybill.warehouse group API 文档参数定义:完善 list/detail/export 的 params 与 response,新增 exportTaskProgress 异步进度查询接口", + "methods": [ + "waybill.warehouse.list", + "waybill.warehouse.detail", + "waybill.warehouse.export", + "waybill.warehouse.exportTaskProgress" + ], + "notes": [ + "waybill.warehouse.list:params 含 pagination/where/sort 完整字段定义,where 支持 15 个筛选维度(运单号、主单号、订单ID、订单号、物流编码、物流接口ID、平台编码、状态、退回/拦截/星河签收、包材ID、已称重、关键词、创建时间范围),sort 白名单 create_at/weighing_weight/id。response 含 list(28 个字段)+ pagination。", + "waybill.warehouse.detail:修正 id 参数为可选(required: false),与 waybillCode 二选一,waybillCode 优先。response 含 id/waybill_code/main_waybill_code/waybill_type/business_key/sibling_waybills/order/logistics/status_info/weight/package/print_records/print_count 等完整详情。", + "waybill.warehouse.export:response 补充 progress/message/update_time 字段,完整覆盖异步任务返回信息。", + "新增 waybill.warehouse.exportTaskProgress:按 task_id/taskId 查询导出进度,response 含 task_id/status/progress/current_count/total_count/message/result/error/download_url/update_time。", + "所有接口 isNeedAuth: false, isNeedLogin: true,仓库隔离通过 ctx.user.store_id 自动注入。" + ], + "module": "waybill.warehouse" + }, { "version": "2026.07.28-system-01", "date": "2026-07-28", @@ -2335,24 +2414,6 @@ ], "type": "updated" }, - { - "version": "2026.05.20-system-02", - "date": "2026-05-20", - "summary": "新增打印失败自动补偿能力:定时扫描并触发 print.retryFailed 批量补打", - "methods": [ - "print.retryFailed" - ], - "notes": [ - "新增定时任务:app/schedule/print_retry_compensation.js,按仓库分组调用 print.retryFailed 进行批量补打。", - "配置项位置:config/config.default.js 的 printRetryCompensation,包含:enable(boolean, 默认 false)、intervalMs(毫秒,默认 60000)、batchSize(批量大小,默认 50)、force(boolean,默认 false)、maxRetryCount(number,默认 5)。", - "行为摘要:任务按 printRetryCompensation.intervalMs 频率查询 send_status=send_failed 或 print_status IN (print_failed, timeout),且 next_retry_at <= now 且 retry_count < maxRetryCount 的记录,按仓库分组并调用 print.retryFailed({ print_ids, warehouse_id, force }) 进行补打。", - "兼容性:print.retryFailed 支持显式传入 warehouse_id(调度任务会传入),当未提供时回退到 ctx.user.store_id;若两者均无则接口返回 400。", - "注意:当前实现中传入的 force 参数不会放宽对状态的判定(代码注释说明为“最小实现”),如需放宽需修改 print.getRetryEligibility 的逻辑。", - "回滚说明:1) 将 printRetryCompensation.enable 设为 false 并重启服务以停止新任务;2) 从部署包中移除或注释 app/schedule/print_retry_compensation.js 并重启服务;3) 如需从 methods/changes/system.json 中移除此变更,请通过生成对应 spec(change.version 设置为本条版本并 type='removed')并运行 npm run doc:api:update -- --spec= 来更新变更记录;4) 若调度已触发的补打需中止,请在调度或队列系统中停止对应任务或通过运维回退正在执行的补打逻辑。" - ], - "module": "print", - "type": "added" - }, { "version": "2026.05.20-system-01", "date": "2026-05-20", @@ -5017,5 +5078,46 @@ "仓库侧导出自动限定 warehouse_id=ctx.user.store_id,货主侧需传 store_id", "导出 Excel 列:序号/创建时间/流水类型/仓库ID/货主ID/商品ID/变动数量/变更前库存/变更后库存/变更前锁定/变更后锁定/批次号/单据类型/单据号/收货单ID/入库单ID/发货单ID/操作人/备注" ] + }, + { + "version": "2026.07.29-system-01", + "date": "2026-07-29", + "type": "added", + "summary": "新增 waybill.warehouse 运单模块(仓库侧):list(列表)、detail(详情)、export(导出)3 个接口,支持运单号独立查询与管理", + "methods": [ + "waybill.warehouse.list", + "waybill.warehouse.detail", + "waybill.warehouse.export" + ], + "notes": [ + "新增 waybill.warehouse.list:仓库侧运单列表查询,支持分页与多条件筛选(运单号/主单号/订单ID/订单号/物流公司/物流接口/平台/状态/退回/拦截/星河签收/包材/称重/关键词/时间范围),默认按 create_at desc 排序。", + "新增 waybill.warehouse.detail:仓库侧运单详情查询,含关联订单信息、兄弟运单(sibling_waybills)、物流信息、状态信息、称重信息、打包信息(打包状态/打包人/打包时间)、打印记录列表。", + "新增 waybill.warehouse.export:仓库侧运单导出,复用 list 筛选逻辑,异步任务模式,支持自定义导出字段。", + "仓库隔离策略:所有接口自动注入 warehouse_id = ctx.user.store_id(全系统统一约定),不可由前端入参覆盖。", + "快照字段方案:wms_order_express 表新增 delivery_order_code、store_id_snapshot、store_name_snapshot、warehouse_name_snapshot 四个快照列,列表查询无需 JOIN 订单表或货主表,仅单表查询 + SELF JOIN(主单号)。", + "主单号/子单号规则:同一 order_id 下 business_key=1 为主单号,business_key>1 为子单号,沿用系统已有约定。", + "命名空间规划:waybill.warehouse.* 本期实现(仓库侧),后续预留 waybill.store.*(货主侧)。", + "本模块一期仅提供只读查询,不涉及运单创建/修改/删除,不修改任何现有接口。" + ], + "module": "waybill.warehouse" + }, + { + "version": "2026.07.30-system-01", + "date": "2026-07-30", + "type": "changed", + "summary": "更新 waybill.warehouse group API 文档:list 新增 waybillType/storeId 筛选、移除 pack_status 响应字段;detail 精简 package 对象;export 响应改为纯异步任务模式(仅含 task_id/status/progress/message/update_time)", + "methods": [ + "waybill.warehouse.list", + "waybill.warehouse.detail", + "waybill.warehouse.export", + "waybill.warehouse.exportTaskProgress" + ], + "notes": [ + "waybill.warehouse.list:新增 where.waybillType 筛选(\"main\"/\"1\"=主单号,\"child\"/\"2\"=子单号),新增 where.storeId 货主ID等值筛选。where.orderNo 标注暂不可用(待快照字段就绪)。response 移除 pack_status 字段(两表无关联,不再返回),list 字段数从 28 减至 27。", + "waybill.warehouse.detail:package 对象移除 pack_status/pack_quantity/pack_at/packer_name 四个字段,仅保留 package_material_id 和 package_material_name。description 同步去掉\"打包状态\"相关描述。", + "waybill.warehouse.export:响应简化为纯异步任务模式,data 仅含 task_id/status/progress/message/update_time,不含 total_count/current_count/result/error/download_url 等执行期字段(这些信息由 exportTaskProgress 接口返回)。export 的 where 参数同步新增 waybillType 和 storeId。", + "waybill.warehouse.exportTaskProgress:无变更,保持不变。" + ], + "module": "waybill.warehouse" } ] diff --git a/methods/system.json b/methods/system.json index 731ccea..08870ca 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1,8 +1,8 @@ { "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", - "version": "0.3.7", - "updatedAt": "2026-07-27", + "version": "0.3.9", + "updatedAt": "2026-07-30", "headers": [ { "name": "platform", @@ -6354,6 +6354,100 @@ } ] }, + { + "method": "order.recheckOrder.batchQuickRecheckByWave", + "description": "按波次批量快捷复核:传入波次 IDs 列表,对每个波次下所有有效订单执行前置检查(已分配储位、已分配快递、已同步且未被拦截),必要时自动完成拣货(含库存锁定校验与扣减、库存流水写入、拣货任务状态同步)后标记复核(含复核任务记录、任务复核状态更新、车任务解绑、操作日志)。每个订单在独立事务中执行,支持部分失败,不满足条件的订单跳过并返回原因。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "wave_ids", + "type": "array|string", + "required": true, + "source": "body|query", + "description": "波次 ID 列表,支持数组或以逗号分隔的字符串。兼容 waveIds(驼峰)、wave_id(单值)" + } + ], + "response": [ + { + "name": "success", + "type": "array", + "required": true, + "description": "复核成功的订单列表", + "children": [ + { + "name": "order_id", + "type": "number", + "description": "订单ID" + }, + { + "name": "wave_id", + "type": "number", + "description": "所属波次ID" + }, + { + "name": "delivery_order_code", + "type": "string", + "description": "发货单号" + } + ] + }, + { + "name": "failed", + "type": "array", + "required": true, + "description": "复核失败的订单列表", + "children": [ + { + "name": "order_id", + "type": "number", + "description": "订单ID(波次无订单时为 null)" + }, + { + "name": "wave_id", + "type": "number", + "description": "所属波次ID" + }, + { + "name": "delivery_order_code", + "type": "string", + "description": "发货单号(波次无订单时为 null)" + }, + { + "name": "reason", + "type": "string", + "description": "失败原因(未分配储位 / 没有分配快递 / 没有同步 / 已拦截 / 波次下无订单 / 复核失败: xxx)" + } + ] + }, + { + "name": "success_count", + "type": "number", + "required": true, + "description": "成功数量" + }, + { + "name": "failed_count", + "type": "number", + "required": true, + "description": "失败数量" + } + ], + "errors": [ + { + "code": 400, + "message": "波次ID列表不能为空" + } + ] + }, { "method": "order.recheckOrder.queryRecheckOrderSingleList", "description": "散单模式复核列表查询,按订单维度返回待复核订单(排除 pick_status='none' 和 recheck_status='fin'),支持分页与关键词/波次号/复核状态筛选。与 recheckOrderList 不同:本方法仅处理散单模式,不包含团购分支。", @@ -6425,8 +6519,18 @@ "required": false, "description": "分页参数 { page, pageSize },默认 page=1, pageSize=20", "children": [ - { "name": "page", "type": "number", "required": false, "description": "页码" }, - { "name": "pageSize", "type": "number", "required": false, "description": "每页条数" } + { + "name": "page", + "type": "number", + "required": false, + "description": "页码" + }, + { + "name": "pageSize", + "type": "number", + "required": false, + "description": "每页条数" + } ] }, { @@ -6435,8 +6539,18 @@ "required": false, "description": "排序参数 { sortField, sortOrder }", "children": [ - { "name": "sortField", "type": "string", "required": false, "description": "排序字段,支持:id、order_id、workbench_id、wave_id、pack_quantity、pack_mode、status、start_time、end_time、create_time、update_time" }, - { "name": "sortOrder", "type": "string", "required": false, "description": "排序方向:ASC / DESC,默认 DESC" } + { + "name": "sortField", + "type": "string", + "required": false, + "description": "排序字段,支持:id、order_id、workbench_id、wave_id、pack_quantity、pack_mode、status、start_time、end_time、create_time、update_time" + }, + { + "name": "sortOrder", + "type": "string", + "required": false, + "description": "排序方向:ASC / DESC,默认 DESC" + } ] }, { @@ -6445,17 +6559,72 @@ "required": false, "description": "筛选条件", "children": [ - { "name": "status", "type": "number", "required": false, "description": "任务状态:0=待处理 1=打包中 2=已完成 3=异常" }, - { "name": "pack_mode", "type": "number", "required": false, "description": "打包模式:1=散单 2=团购" }, - { "name": "waybill_code", "type": "string", "required": false, "description": "运单号(模糊匹配)" }, - { "name": "wave_no", "type": "string", "required": false, "description": "波次号(模糊匹配)" }, - { "name": "order_id", "type": "number", "required": false, "description": "订单ID(精确匹配)" }, - { "name": "workbench_id", "type": "number", "required": false, "description": "工作台ID(精确匹配)" }, - { "name": "quickWhere", "type": "string", "required": false, "description": "快捷搜索:波次号模糊匹配 + 运单号通过 express→order→wave 链路解析" }, - { "name": "start_time_start", "type": "string", "required": false, "description": "开始打包时间范围起始(ISO 8601)" }, - { "name": "start_time_end", "type": "string", "required": false, "description": "开始打包时间范围结束(ISO 8601)" }, - { "name": "has_video", "type": "number", "required": false, "description": "是否包含录像:1=有录像 2=无录像" }, - { "name": "video_enable", "type": "number", "required": false, "description": "录像是否可用:1=可用(存在 video_url 非空且 status!=failed 的记录) 2=不可用" } + { + "name": "status", + "type": "number", + "required": false, + "description": "任务状态:0=待处理 1=打包中 2=已完成 3=异常" + }, + { + "name": "pack_mode", + "type": "number", + "required": false, + "description": "打包模式:1=散单 2=团购" + }, + { + "name": "waybill_code", + "type": "string", + "required": false, + "description": "运单号(模糊匹配)" + }, + { + "name": "wave_no", + "type": "string", + "required": false, + "description": "波次号(模糊匹配)" + }, + { + "name": "order_id", + "type": "number", + "required": false, + "description": "订单ID(精确匹配)" + }, + { + "name": "workbench_id", + "type": "number", + "required": false, + "description": "工作台ID(精确匹配)" + }, + { + "name": "quickWhere", + "type": "string", + "required": false, + "description": "快捷搜索:波次号模糊匹配 + 运单号通过 express→order→wave 链路解析" + }, + { + "name": "start_time_start", + "type": "string", + "required": false, + "description": "开始打包时间范围起始(ISO 8601)" + }, + { + "name": "start_time_end", + "type": "string", + "required": false, + "description": "开始打包时间范围结束(ISO 8601)" + }, + { + "name": "has_video", + "type": "number", + "required": false, + "description": "是否包含录像:1=有录像 2=无录像" + }, + { + "name": "video_enable", + "type": "number", + "required": false, + "description": "录像是否可用:1=可用(存在 video_url 非空且 status!=failed 的记录) 2=不可用" + } ] } ], @@ -11835,6 +12004,159 @@ "description": "查询失败" } ] + }, + { + "method": "order.print.getPrintDataByWaybillCodes", + "description": "按运单号数组拉取平台打印中间态数据,与 getOrderPrintData 返回结构一致。支持子单号(business_key>1):主面单与现有逻辑一致,子面单使用主订单数据构建打印数据并在自定义区追加「子单号【{business_key}】-{主单号}」行。仓库ID统一从当前上下文获取。自动过滤快递未完全分配的订单(post_status !== 'fin'),返回 waveGroups(波次 -> 平台 -> 订单)结构。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "waybill_codes", + "type": "array", + "required": true, + "source": "body", + "description": "运单号数组(字符串数组,内部自动去重与归一化,必须为非空数组)" + } + ], + "response": [ + { + "name": "summary", + "type": "object", + "required": true, + "description": "汇总信息", + "children": [ + { + "name": "total_waves", + "type": "number", + "required": true, + "description": "通过过滤的波次总数" + }, + { + "name": "total_orders", + "type": "number", + "required": true, + "description": "所有平台下打印条目总数(每个运单一条)" + }, + { + "name": "total_platforms", + "type": "number", + "required": true, + "description": "所有波次内平台分组总数(累加)" + } + ] + }, + { + "name": "wave_ids", + "type": "array", + "required": true, + "description": "通过过滤的波次ID数组" + }, + { + "name": "waveGroups", + "type": "array", + "required": true, + "description": "波次分组(波次 -> 平台 -> 订单),结构与 getOrderPrintData 一致", + "children": [ + { + "name": "wave_id", + "type": "number", + "required": true, + "description": "波次ID" + }, + { + "name": "wave_no", + "type": "string", + "required": true, + "description": "波次号" + }, + { + "name": "order_count", + "type": "number", + "required": true, + "description": "该波次下打印条目数" + }, + { + "name": "platforms", + "type": "array", + "required": true, + "description": "平台分组列表", + "children": [ + { + "name": "platform", + "type": "string", + "required": true, + "description": "平台编码" + }, + { + "name": "platform_name", + "type": "string", + "required": true, + "description": "平台名称" + }, + { + "name": "order_count", + "type": "number", + "required": true, + "description": "该平台下打印条目数" + }, + { + "name": "order_ids", + "type": "array", + "required": true, + "description": "订单ID数组(去重)" + }, + { + "name": "orders", + "type": "array", + "required": true, + "description": "打印数据文档数组(print_data)" + } + ] + } + ] + }, + { + "name": "ext", + "type": "object", + "required": true, + "description": "扩展信息", + "children": [ + { + "name": "missing_waybill_codes", + "type": "array", + "required": true, + "description": "未匹配到的运单号" + }, + { + "name": "filtered_waybill_codes", + "type": "array", + "required": true, + "description": "被过滤掉的运单号及其原因,每项含 waybill_code、reason" + } + ] + } + ], + "errors": [ + { + "code": "400", + "message": "waybill_codes 必填,且必须为非空数组", + "description": "waybill_codes 必填,且必须为非空数组" + }, + { + "code": "500", + "message": "查询失败", + "description": "查询失败" + } + ] } ] }, @@ -12687,114 +13009,6 @@ } ] }, - { - "method": "print.retryFailed", - "description": "失败项补打:重试指定打印记录的发送。被定时任务 print-retry-compensation 调用以批量触发失败项补打。", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "print_ids", - "type": "array", - "required": true, - "source": "body", - "description": "要补打的打印记录 ID 数组", - "children": [ - { - "name": "id", - "type": "number", - "description": "打印记录 ID" - } - ] - }, - { - "name": "force", - "type": "boolean", - "required": false, - "source": "body", - "description": "是否强制补打(当前实现仍不放宽状态判定)" - }, - { - "name": "warehouse_id", - "type": "number", - "required": false, - "source": "body", - "description": "显式指定仓库 ID(调度任务推荐提供),若缺失将使用当前用户的 store_id" - } - ], - "response": [ - { - "name": "flag", - "type": "string", - "required": true, - "description": "调用标识,成功为 success" - }, - { - "name": "code", - "type": "number", - "required": true, - "description": "业务状态码,成功通常为 200" - }, - { - "name": "message", - "type": "string", - "required": true, - "description": "返回信息" - }, - { - "name": "success_count", - "type": "number", - "required": false, - "description": "成功补打数量" - }, - { - "name": "failed_count", - "type": "number", - "required": false, - "description": "补打失败数量" - }, - { - "name": "skipped_count", - "type": "number", - "required": false, - "description": "被跳过的记录数量" - }, - { - "name": "retried", - "type": "array", - "required": false, - "description": "补打尝试结果数组" - }, - { - "name": "skipped", - "type": "array", - "required": false, - "description": "跳过项明细" - } - ], - "errors": [ - { - "code": 400, - "message": "warehouse_id 参数缺失,且当前上下文无可用仓库信息" - }, - { - "code": 400, - "message": "print_ids 参数不能为空数组或不合法" - }, - { - "code": 500, - "message": "内部错误" - } - ] - }, { "method": "print.notifyLock", "description": "仅执行订单锁定流程,不发送打印任务;记录打印任务日志并写入订单操作日志。兼容别名:print.notify_lock(等价转调)。", @@ -12920,6 +13134,90 @@ "params": [], "response": [], "errors": [] + }, + { + "method": "print.markWavePrintStatus", + "description": "标记/取消标记整个波次订单的打印状态。仓库隔离:从登录上下文获取仓库ID。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "wave_id", + "type": "number", + "required": true, + "source": "body", + "description": "波次ID(必填,正整数)" + }, + { + "name": "status", + "type": "string", + "required": false, + "source": "body", + "description": "目标状态:printed=标记已打印,unprinted=取消已打印标记。默认 printed。" + } + ], + "response": [ + { + "name": "wave_id", + "type": "number", + "description": "波次ID" + }, + { + "name": "status", + "type": "string", + "description": "目标状态" + }, + { + "name": "print_status", + "type": "string", + "description": "订单表 print_status 字段值(fin / none)" + }, + { + "name": "total_orders", + "type": "number", + "description": "波次下总订单数" + }, + { + "name": "affected_orders", + "type": "number", + "description": "实际更新的订单数" + }, + { + "name": "order_ids", + "type": "array", + "description": "波次下所有订单ID" + } + ], + "errors": [ + { + "code": 400, + "message": "wave_id 参数必填,且必须为正整数" + }, + { + "code": 400, + "message": "status 参数不合法,仅支持 printed / unprinted" + }, + { + "code": 400, + "message": "无法获取当前仓库ID,请确认已登录" + }, + { + "code": 404, + "message": "波次在当前仓库下没有可操作的订单" + }, + { + "code": 500, + "message": "内部错误(OrderDeliveryFactory/OrderDeliveryModel 不可用或更新失败)" + } + ] } ] }, @@ -21955,6 +22253,155 @@ } } }, + { + "method": "storage.inventory.export", + "description": "提交库存导出异步任务。支持两种导出模式(exportMode):stock_location(默认,按 stock_id + 库位聚合导出库存汇总,含库位编码/名称、商品信息、总库存/锁定/可用、批次数、最近入库时间等)、storage(按 storage_id 逐条导出库存明细,含库位编码/名称、商品信息、批次号、库存类型、数量、生产日期、过期日期、入库单号等)。立即返回任务受理信息(task_id/status/progress),不直接返回文件。通过 storage.inventory.exportTaskProgress 查询进度并获取下载地址。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "统一 where 条件对象,与 storage.inventory.list 的 where 语义完全一致。支持字段:stock_id(商品ID)、space_id(库位ID)、store_id(货主ID)、inventory_type(ZP/CC/JS/XS/ZT/DJ/FP)、batch_no(批次号)、inbound_order_no(入库单号)、available_quantity(可用数量,支持 gt/lt)、inbound_time(入库时间,支持 between)、created_at(创建时间,支持 between)" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数,与 storage.inventory.list 的 sort 语义完全一致。sortField 支持:id/stock_id/space_id/created_at/updated_at/inbound_time/quantity,sortOrder 支持 ASC/DESC。默认 id DESC" + }, + { + "name": "group_by_batch", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否按批次导出,默认 false。与 storage.inventory.list 的 group_by_batch 语义一致。false=合并模式(按 stock_id+库位聚合导出库存汇总,含总库存/锁定/可用/批次数/最近入库时间),true=明细模式(按 storage_id 逐条导出库存明细,含批次号/库存类型/生产日期/过期日期/入库单号等)" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "description": "导出任务ID,用于后续查询进度" + }, + { + "name": "status", + "type": "string", + "description": "任务状态:submitted" + }, + { + "name": "progress", + "type": "number", + "description": "进度:0" + }, + { + "name": "message", + "type": "string", + "description": "受理消息" + }, + { + "name": "update_time", + "type": "number", + "description": "更新时间戳" + } + ], + "errors": [ + { + "code": 400, + "message": "where 条件格式不正确" + }, + { + "code": 500, + "message": "导出任务提交失败" + } + ] + }, + { + "method": "storage.inventory.exportTaskProgress", + "description": "按 task_id 查询库存导出任务进度,未找到时 status=not_found。任务完成(status=success)时返回 download_url 供客户端下载导出文件。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "task_id / taskId", + "type": "string", + "required": true, + "source": "body|query", + "description": "任务ID,兼容 taskId 驼峰写法" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "description": "任务ID" + }, + { + "name": "status", + "type": "string", + "description": "任务状态:submitted/running/success/failed/not_found" + }, + { + "name": "progress", + "type": "number", + "description": "进度百分比(0-100)" + }, + { + "name": "message", + "type": "string", + "description": "额外提示信息" + }, + { + "name": "result", + "type": "object", + "description": "任务成功时返回的结果对象(含 fileKey/url 等)" + }, + { + "name": "error", + "type": "string", + "description": "失败时的错误信息" + }, + { + "name": "download_url", + "type": "string", + "description": "任务完成后可直接下载的文件地址" + }, + { + "name": "update_time", + "type": "number", + "description": "最近一次状态更新时间戳" + } + ], + "errors": [ + { + "code": 400, + "message": "task_id 参数不能为空" + }, + { + "code": 500, + "message": "查询失败或内部错误" + } + ] + }, { "method": "storage.expiry.list", "description": "库存有效期列表查询(效期预警),按 wms_storage 查询并计算剩余天数与过期状态,支持 where 条件与分页。注意:无需传 warehouse_id/store_id,服务端会从当前登录用户取仓库上下文。", @@ -28968,6 +29415,20 @@ "source": "body", "description": "0-禁用 1-启用" }, + { + "name": "username", + "type": "string", + "required": false, + "source": "body", + "description": "摄像头登录用户名" + }, + { + "name": "password", + "type": "string", + "required": false, + "source": "body", + "description": "摄像头登录密码" + }, { "name": "remark", "type": "string", @@ -29040,6 +29501,20 @@ "source": "body", "description": "0-禁用 1-启用" }, + { + "name": "username", + "type": "string", + "required": false, + "source": "body", + "description": "摄像头登录用户名" + }, + { + "name": "password", + "type": "string", + "required": false, + "source": "body", + "description": "摄像头登录密码" + }, { "name": "remark", "type": "string", @@ -29056,6 +29531,65 @@ } ] }, + { + "method": "camera.setOsd", + "description": "设置摄像头 OSD 文字叠加", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "摄像头ID(必填)" + }, + { + "name": "text", + "type": "string", + "required": true, + "source": "body", + "description": "OSD 叠加文字(必填)" + }, + { + "name": "x", + "type": "number", + "required": false, + "source": "body", + "description": "X 坐标(-1 到 1,默认 -0.9)" + }, + { + "name": "y", + "type": "number", + "required": false, + "source": "body", + "description": "Y 坐标(-1 到 1,默认 0.8)" + } + ], + "response": [], + "errors": [ + { + "code": "400", + "description": "摄像头ID/OSD文字不能为空" + }, + { + "code": "404", + "description": "摄像头不存在或无权操作" + }, + { + "code": "500", + "description": "打印服务调用失败" + } + ] + }, { "method": "camera.delete", "description": "删除摄像头(软删除)", @@ -29413,6 +29947,1899 @@ "errors": [] } ] + }, + { + "groupName": "运单模块(仓库侧)", + "module": "waybill.warehouse", + "list": [ + { + "method": "waybill.warehouse.list", + "description": "运单列表-仓库侧:分页查询运单号列表,支持多条件筛选。仓库隔离(自动注入 warehouse_id = ctx.user.store_id),所有查询仅返回当前仓库数据。通过快照字段(delivery_order_code、store_id_snapshot、store_name_snapshot、warehouse_name_snapshot)避免 JOIN 订单表和货主表,列表核心查询为 wms_order_express 单表 + SELF JOIN(主单号)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token,从中解析 warehouseId(仓库上下文,ctx.user.store_id)" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数。默认 page=1, pageSize=20" + }, + { + "name": "pagination.page", + "type": "number", + "required": false, + "source": "body.pagination", + "description": "页码,默认 1" + }, + { + "name": "pagination.pageSize", + "type": "number", + "required": false, + "source": "body.pagination", + "description": "每页条数,默认 20" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "筛选条件对象,所有字段均为可选" + }, + { + "name": "where.waybillCode", + "type": "string", + "required": false, + "source": "body.where", + "description": "运单号(模糊搜索)" + }, + { + "name": "where.mainWaybillCode", + "type": "string", + "required": false, + "source": "body.where", + "description": "主单号(精确匹配)。先通过主单号定位 order_id,再返回该订单下所有运单(主+子)。与 waybillCode 互斥,同时传入时 mainWaybillCode 优先" + }, + { + "name": "where.orderId", + "type": "number", + "required": false, + "source": "body.where", + "description": "订单ID(等值匹配)" + }, + { + "name": "where.orderNo", + "type": "string", + "required": false, + "source": "body.where", + "description": "订单号(模糊搜索,暂不可用,待快照字段就绪)" + }, + { + "name": "where.waybillType", + "type": "string", + "required": false, + "source": "body.where", + "description": "运单类型:\"main\"/\"1\"=主单号(business_key=1),\"child\"/\"2\"=子单号(business_key>1)" + }, + { + "name": "where.storeId", + "type": "number", + "required": false, + "source": "body.where", + "description": "货主ID(等值匹配)" + }, + { + "name": "where.logisticsCode", + "type": "string", + "required": false, + "source": "body.where", + "description": "物流公司编码(等值匹配),如 SF/YT/STO/ZTO 等" + }, + { + "name": "where.logisticsInterfaceId", + "type": "number", + "required": false, + "source": "body.where", + "description": "物流接口ID(等值匹配),对应 wms_order_express.logistics_interface_id" + }, + { + "name": "where.platformCode", + "type": "string", + "required": false, + "source": "body.where", + "description": "平台编码(等值匹配),如 PDD/DY/KS/JD/CAINIAO/SPH/XHS" + }, + { + "name": "where.status", + "type": "number", + "required": false, + "source": "body.where", + "description": "运单状态:0=未分配,1=已分配" + }, + { + "name": "where.isBack", + "type": "string", + "required": false, + "source": "body.where", + "description": "是否退回:Y/N" + }, + { + "name": "where.isIntercept", + "type": "string", + "required": false, + "source": "body.where", + "description": "是否拦截:Y/N" + }, + { + "name": "where.isGalaxyReceive", + "type": "string", + "required": false, + "source": "body.where", + "description": "是否星河签收:Y/N" + }, + { + "name": "where.packageMaterialId", + "type": "number", + "required": false, + "source": "body.where", + "description": "包材ID(等值匹配)" + }, + { + "name": "where.hasWeighingWeight", + "type": "boolean", + "required": false, + "source": "body.where", + "description": "是否已称重:true=weighing_weight>0,false=weighing_weight=0" + }, + { + "name": "where.keyword", + "type": "string", + "required": false, + "source": "body.where", + "description": "关键词搜索:同时匹配运单号(waybill_code)、主单号、订单号" + }, + { + "name": "where.createdAtStart", + "type": "string", + "required": false, + "source": "body.where", + "description": "创建时间起始,格式 YYYY-MM-DD" + }, + { + "name": "where.createdAtEnd", + "type": "string", + "required": false, + "source": "body.where", + "description": "创建时间截止,格式 YYYY-MM-DD" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数。默认 create_at desc" + }, + { + "name": "sort.field", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序字段,白名单:create_at / weighing_weight / id" + }, + { + "name": "sort.order", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序方向:asc / desc,默认 desc" + } + ], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "业务状态码,200 表示成功" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "业务提示信息" + }, + { + "name": "data", + "type": "object", + "required": true, + "description": "成功时返回的运单列表数据", + "children": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "运单列表数组", + "children": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "运单记录ID(wms_order_express.id)" + }, + { + "name": "waybill_code", + "type": "string", + "required": true, + "description": "运单号" + }, + { + "name": "main_waybill_code", + "type": "string", + "required": true, + "description": "主单号。business_key=1 时等于 waybill_code 本身;business_key>1 时通过 SELF JOIN 查找同 order_id 下 business_key=1 的运单号" + }, + { + "name": "waybill_type", + "type": "string", + "required": true, + "description": "运单类型:business_key=1→'主单号',business_key>1→'子单号'" + }, + { + "name": "order_id", + "type": "number", + "required": true, + "description": "订单ID" + }, + { + "name": "order_no", + "type": "string", + "required": true, + "description": "订单号(来自 delivery_order_code 快照列)" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "仓库ID" + }, + { + "name": "warehouse_name", + "type": "string", + "required": true, + "description": "仓库名称(来自 warehouse_name_snapshot 快照列)" + }, + { + "name": "store_id", + "type": "number", + "required": true, + "description": "货主ID(来自 store_id_snapshot 快照列)" + }, + { + "name": "store_name", + "type": "string", + "required": true, + "description": "货主名称(来自 store_name_snapshot 快照列)" + }, + { + "name": "business_key", + "type": "number", + "required": true, + "description": "拆单序号:1=主单号,>1=子单号" + }, + { + "name": "status", + "type": "number", + "required": true, + "description": "运单状态:0=未分配,1=已分配" + }, + { + "name": "status_text", + "type": "string", + "required": true, + "description": "状态文本:'未分配'/'已分配'" + }, + { + "name": "logistics_interface_id", + "type": "number", + "required": false, + "description": "物流接口ID" + }, + { + "name": "logistics_code", + "type": "string", + "required": false, + "description": "物流公司编码" + }, + { + "name": "logistics_name", + "type": "string", + "required": false, + "description": "物流公司名称" + }, + { + "name": "logistics_interface_name", + "type": "string", + "required": false, + "description": "物流接口名称" + }, + { + "name": "platform_code", + "type": "string", + "required": false, + "description": "平台编码" + }, + { + "name": "platform_name", + "type": "string", + "required": false, + "description": "平台名称(前端映射)" + }, + { + "name": "is_back", + "type": "string", + "required": false, + "description": "是否退回:Y/N" + }, + { + "name": "is_intercept", + "type": "string", + "required": false, + "description": "是否拦截:Y/N" + }, + { + "name": "is_galaxy_receive", + "type": "string", + "required": false, + "description": "是否星河签收:Y/N" + }, + { + "name": "weighing_weight", + "type": "number", + "required": false, + "description": "称重重量(单位:g)" + }, + { + "name": "weighing_weight_display", + "type": "string", + "required": false, + "description": "称重重量可读展示(如 '1.25 kg')" + }, + { + "name": "package_material_id", + "type": "number", + "required": false, + "description": "包材ID" + }, + { + "name": "package_material_name", + "type": "string", + "required": false, + "description": "包材名称(来自 package_material_name_snapshot 快照列)" + }, + { + "name": "print_count", + "type": "number", + "required": false, + "description": "打印次数(COUNT express_print_record)" + }, + { + "name": "last_print_at", + "type": "string", + "required": false, + "description": "最近打印时间" + }, + { + "name": "create_at", + "type": "string", + "required": true, + "description": "运单创建时间" + } + ] + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息", + "children": [ + { + "name": "page", + "type": "number", + "required": true, + "description": "当前页码" + }, + { + "name": "pageSize", + "type": "number", + "required": true, + "description": "每页条数" + }, + { + "name": "total", + "type": "number", + "required": true, + "description": "总记录数" + }, + { + "name": "totalPages", + "type": "number", + "required": true, + "description": "总页数" + } + ] + } + ] + } + ], + "errors": [ + { + "code": "401", + "message": "未登录,请先登录" + }, + { + "code": "405", + "message": "参数校验失败:{具体原因}" + }, + { + "code": "500", + "message": "服务器内部错误:运单列表查询失败" + } + ] + }, + { + "method": "waybill.warehouse.detail", + "description": "运单详情-仓库侧:查看单个运单的完整信息,包含关联订单、打印记录、称重信息。仓库隔离校验。支持按运单记录ID(id)或运单号(waybillCode)查询,waybillCode 优先。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token,从中解析 warehouseId(仓库上下文,ctx.user.store_id)" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": false, + "source": "body", + "description": "运单记录ID(wms_order_express.id)。与 waybillCode 二选一,waybillCode 优先" + }, + { + "name": "waybillCode", + "type": "string", + "required": false, + "source": "body", + "description": "运单号。与 id 二选一,waybillCode 优先。需配合仓库隔离校验" + } + ], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "业务状态码,200 表示成功" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "业务提示信息" + }, + { + "name": "data", + "type": "object", + "required": true, + "description": "成功时返回的运单详情数据", + "children": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "运单记录ID" + }, + { + "name": "waybill_code", + "type": "string", + "required": true, + "description": "运单号" + }, + { + "name": "main_waybill_code", + "type": "string", + "required": true, + "description": "主单号" + }, + { + "name": "waybill_type", + "type": "string", + "required": true, + "description": "运单类型:'主单号'/'子单号'" + }, + { + "name": "business_key", + "type": "number", + "required": true, + "description": "拆单序号" + }, + { + "name": "sibling_waybills", + "type": "array", + "required": false, + "description": "同订单下所有运单(兄弟运单),含 waybill_code、business_key、waybill_type", + "children": [ + { + "name": "waybill_code", + "type": "string", + "required": true, + "description": "运单号" + }, + { + "name": "business_key", + "type": "number", + "required": true, + "description": "拆单序号" + }, + { + "name": "waybill_type", + "type": "string", + "required": true, + "description": "运单类型" + } + ] + }, + { + "name": "order", + "type": "object", + "required": true, + "description": "关联订单信息(通过 OrderDeliveryFactory 多表遍历查找)", + "children": [ + { + "name": "order_id", + "type": "number", + "required": true, + "description": "订单ID" + }, + { + "name": "order_no", + "type": "string", + "required": true, + "description": "订单号" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "仓库ID" + }, + { + "name": "warehouse_name", + "type": "string", + "required": true, + "description": "仓库名称(快照)" + }, + { + "name": "store_id", + "type": "number", + "required": true, + "description": "货主ID(快照)" + }, + { + "name": "store_name", + "type": "string", + "required": true, + "description": "货主名称(快照)" + }, + { + "name": "wave_id", + "type": "number", + "required": false, + "description": "波次ID" + }, + { + "name": "wave_no", + "type": "string", + "required": false, + "description": "波次号" + }, + { + "name": "order_type", + "type": "string", + "required": false, + "description": "订单类型:delivery/entry 等" + } + ] + }, + { + "name": "logistics", + "type": "object", + "required": true, + "description": "物流信息", + "children": [ + { + "name": "logistics_code", + "type": "string", + "required": false, + "description": "物流公司编码" + }, + { + "name": "logistics_name", + "type": "string", + "required": false, + "description": "物流公司名称" + }, + { + "name": "logistics_interface_id", + "type": "number", + "required": false, + "description": "物流接口ID" + }, + { + "name": "logistics_interface_name", + "type": "string", + "required": false, + "description": "物流接口名称" + }, + { + "name": "platform_code", + "type": "string", + "required": false, + "description": "平台编码" + } + ] + }, + { + "name": "status_info", + "type": "object", + "required": true, + "description": "运单状态信息", + "children": [ + { + "name": "status", + "type": "number", + "required": true, + "description": "运单状态:0=未分配,1=已分配" + }, + { + "name": "status_text", + "type": "string", + "required": true, + "description": "状态文本" + }, + { + "name": "is_back", + "type": "string", + "required": false, + "description": "是否退回" + }, + { + "name": "is_intercept", + "type": "string", + "required": false, + "description": "是否拦截" + }, + { + "name": "is_galaxy_receive", + "type": "string", + "required": false, + "description": "是否星河签收" + } + ] + }, + { + "name": "weight", + "type": "object", + "required": false, + "description": "称重信息", + "children": [ + { + "name": "weighing_weight", + "type": "number", + "required": false, + "description": "称重重量(g)" + }, + { + "name": "weighing_weight_display", + "type": "string", + "required": false, + "description": "称重重量可读展示" + } + ] + }, + { + "name": "package", + "type": "object", + "required": false, + "description": "包材信息", + "children": [ + { + "name": "package_material_id", + "type": "number", + "required": false, + "description": "包材ID" + }, + { + "name": "package_material_name", + "type": "string", + "required": false, + "description": "包材名称(快照)" + } + ] + }, + { + "name": "print_records", + "type": "array", + "required": false, + "description": "打印记录列表(LEFT JOIN express_print_record ON express_no = waybill_code)", + "children": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "打印记录ID" + }, + { + "name": "printer_name", + "type": "string", + "required": false, + "description": "打印机名称" + }, + { + "name": "template_id", + "type": "number", + "required": false, + "description": "打印模板ID" + }, + { + "name": "template_name", + "type": "string", + "required": false, + "description": "打印模板名称" + }, + { + "name": "platform", + "type": "string", + "required": false, + "description": "平台" + }, + { + "name": "printed_at", + "type": "string", + "required": false, + "description": "打印时间" + } + ] + }, + { + "name": "print_count", + "type": "number", + "required": false, + "description": "打印次数" + }, + { + "name": "printinfo", + "type": "string", + "required": false, + "description": "打印信息(TEXT 字段)" + }, + { + "name": "ver", + "type": "string", + "required": false, + "description": "打印版本号" + }, + { + "name": "retry_count", + "type": "number", + "required": false, + "description": "重试次数" + }, + { + "name": "create_at", + "type": "string", + "required": true, + "description": "运单创建时间" + }, + { + "name": "delete_at", + "type": "string", + "required": false, + "description": "删除时间(软删除),null 表示未删除" + } + ] + } + ], + "errors": [ + { + "code": "401", + "message": "未登录,请先登录" + }, + { + "code": "404", + "message": "运单不存在" + }, + { + "code": "405", + "message": "参数校验失败:请提供运单ID或运单号" + }, + { + "code": "405", + "message": "无权访问该运单(仓库隔离校验不通过)" + }, + { + "code": "500", + "message": "服务器内部错误:运单详情查询失败" + } + ] + }, + { + "method": "waybill.warehouse.export", + "description": "运单导出-仓库侧:按筛选条件导出运单列表为 Excel 文件。复用 waybill.warehouse.list 的筛选逻辑,去掉分页,全量导出。导出为异步任务模式,立即返回任务受理信息,通过 exportTaskProgress 查询进度。仓库隔离(自动注入 warehouse_id)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token,从中解析 warehouseId(仓库上下文,ctx.user.store_id)" + } + ], + "params": [ + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "筛选条件对象,同 waybill.warehouse.list 的 where 参数" + }, + { + "name": "where.waybillCode", + "type": "string", + "required": false, + "source": "body.where", + "description": "运单号(模糊搜索)" + }, + { + "name": "where.mainWaybillCode", + "type": "string", + "required": false, + "source": "body.where", + "description": "主单号(精确匹配)" + }, + { + "name": "where.orderId", + "type": "number", + "required": false, + "source": "body.where", + "description": "订单ID(等值匹配)" + }, + { + "name": "where.orderNo", + "type": "string", + "required": false, + "source": "body.where", + "description": "订单号(模糊搜索,暂不可用,待快照字段就绪)" + }, + { + "name": "where.waybillType", + "type": "string", + "required": false, + "source": "body.where", + "description": "运单类型:\"main\"/\"1\"=主单号,\"child\"/\"2\"=子单号" + }, + { + "name": "where.storeId", + "type": "number", + "required": false, + "source": "body.where", + "description": "货主ID(等值匹配)" + }, + { + "name": "where.logisticsCode", + "type": "string", + "required": false, + "source": "body.where", + "description": "物流公司编码(等值匹配)" + }, + { + "name": "where.logisticsInterfaceId", + "type": "number", + "required": false, + "source": "body.where", + "description": "物流接口ID(等值匹配)" + }, + { + "name": "where.platformCode", + "type": "string", + "required": false, + "source": "body.where", + "description": "平台编码(等值匹配)" + }, + { + "name": "where.status", + "type": "number", + "required": false, + "source": "body.where", + "description": "运单状态:0=未分配,1=已分配" + }, + { + "name": "where.isBack", + "type": "string", + "required": false, + "source": "body.where", + "description": "是否退回:Y/N" + }, + { + "name": "where.isIntercept", + "type": "string", + "required": false, + "source": "body.where", + "description": "是否拦截:Y/N" + }, + { + "name": "where.isGalaxyReceive", + "type": "string", + "required": false, + "source": "body.where", + "description": "是否星河签收:Y/N" + }, + { + "name": "where.packageMaterialId", + "type": "number", + "required": false, + "source": "body.where", + "description": "包材ID(等值匹配)" + }, + { + "name": "where.hasWeighingWeight", + "type": "boolean", + "required": false, + "source": "body.where", + "description": "是否已称重" + }, + { + "name": "where.keyword", + "type": "string", + "required": false, + "source": "body.where", + "description": "关键词搜索" + }, + { + "name": "where.createdAtStart", + "type": "string", + "required": false, + "source": "body.where", + "description": "创建时间起始,格式 YYYY-MM-DD" + }, + { + "name": "where.createdAtEnd", + "type": "string", + "required": false, + "source": "body.where", + "description": "创建时间截止,格式 YYYY-MM-DD" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数,同 waybill.warehouse.list" + }, + { + "name": "sort.field", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序字段:create_at / weighing_weight / id" + }, + { + "name": "sort.order", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序方向:asc / desc" + }, + { + "name": "exportFields", + "type": "array", + "required": false, + "source": "body", + "description": "需要导出的字段列表,不传则导出全部字段。可选字段:waybill_code, main_waybill_code, waybill_type, order_no, warehouse_name, store_name, business_key, status_text, logistics_code, logistics_name, logistics_interface_name, platform_code, weighing_weight, package_material_name, print_count, last_print_at, create_at" + } + ], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "业务状态码,200 表示任务已受理" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "业务提示信息" + }, + { + "name": "data", + "type": "object", + "required": true, + "description": "成功时返回的导出任务受理信息(异步任务模式,不含导出数据)", + "children": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "异步导出任务ID,前缀 waybill_export_,用于后续通过 exportTaskProgress 查询进度和获取下载链接" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "任务状态:submitted(已提交)/ running(执行中)/ success(成功)/ failed(失败)" + }, + { + "name": "progress", + "type": "number", + "required": false, + "description": "任务进度百分比(0-100)" + }, + { + "name": "message", + "type": "string", + "required": false, + "description": "任务状态说明" + }, + { + "name": "update_time", + "type": "string", + "required": false, + "description": "任务最近更新时间(ISO 8601)" + } + ] + } + ], + "errors": [ + { + "code": "401", + "message": "未登录,请先登录" + }, + { + "code": "405", + "message": "参数校验失败:{具体原因}" + }, + { + "code": "500", + "message": "服务器内部错误:运单导出任务创建失败" + } + ] + }, + { + "method": "waybill.warehouse.exportTaskProgress", + "description": "运单导出进度查询-仓库侧:按 task_id 或 taskId 查询异步导出任务的执行进度。任务进度通过 Redis 缓存存储,任务 ID 前缀 waybill_export_。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token,从中解析 warehouseId(仓库上下文,ctx.user.store_id)" + } + ], + "params": [ + { + "name": "task_id", + "type": "string", + "required": false, + "source": "body", + "description": "异步导出任务ID(前缀 waybill_export_)。与 taskId 二选一,taskId 优先" + }, + { + "name": "taskId", + "type": "string", + "required": false, + "source": "body", + "description": "异步导出任务ID(别名,优先使用)。至少传入 taskId 或 task_id 之一" + } + ], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "业务状态码,200 表示成功" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "业务提示信息" + }, + { + "name": "data", + "type": "object", + "required": true, + "description": "成功时返回的导出任务进度信息", + "children": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务ID" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "任务状态:submitted(已提交)/ running(执行中)/ success(成功)/ failed(失败)" + }, + { + "name": "progress", + "type": "number", + "required": false, + "description": "任务进度百分比(0-100)" + }, + { + "name": "current_count", + "type": "number", + "required": false, + "description": "当前已处理的运单记录数" + }, + { + "name": "total_count", + "type": "number", + "required": false, + "description": "需要导出的总运单记录数" + }, + { + "name": "message", + "type": "string", + "required": false, + "description": "任务状态说明或错误信息" + }, + { + "name": "result", + "type": "object", + "required": false, + "description": "任务执行结果(status=success 时返回)", + "children": [ + { + "name": "total_exported", + "type": "number", + "required": false, + "description": "实际导出的记录数" + }, + { + "name": "file_size", + "type": "number", + "required": false, + "description": "导出文件大小(字节)" + } + ] + }, + { + "name": "error", + "type": "string", + "required": false, + "description": "错误信息(status=failed 时返回)" + }, + { + "name": "download_url", + "type": "string", + "required": false, + "description": "导出文件下载地址(COS 临时签名 URL,status=success 时返回)" + }, + { + "name": "update_time", + "type": "string", + "required": false, + "description": "任务最近更新时间(ISO 8601)" + } + ] + } + ], + "errors": [ + { + "code": "401", + "message": "未登录,请先登录" + }, + { + "code": "404", + "message": "任务不存在或已过期" + }, + { + "code": "405", + "message": "参数校验失败:请提供 taskId 或 task_id" + }, + { + "code": "500", + "message": "服务器内部错误:导出进度查询失败" + } + ] + } + ] + }, + { + "groupName": "API应用管理模块", + "module": "apiApp", + "list": [ + { + "method": "apiApp.list", + "description": "查询当前仓库的 API 应用列表(分页),返回脱敏后的 AppSecret", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "page", + "type": "number", + "required": false, + "source": "body", + "description": "页码,默认 1" + }, + { + "name": "pageSize", + "type": "number", + "required": false, + "source": "body", + "description": "每页数量,默认 20,最大 100" + }, + { + "name": "app_name", + "type": "string", + "required": false, + "source": "body", + "description": "应用名称(模糊搜索)" + }, + { + "name": "is_enabled", + "type": "number", + "required": false, + "source": "body", + "description": "启用状态:1-启用,0-停用" + } + ], + "response": { + "type": "object", + "properties": [ + { + "name": "list", + "type": "array", + "description": "应用列表", + "children": [ + { + "name": "id", + "type": "number", + "description": "应用 ID" + }, + { + "name": "app_name", + "type": "string", + "description": "应用名称" + }, + { + "name": "warehouse_id", + "type": "number", + "description": "仓库 ID" + }, + { + "name": "interface_type_id", + "type": "number", + "description": "接口类型 ID" + }, + { + "name": "self_app_key", + "type": "string", + "description": "自身 AppKey(对外提供)" + }, + { + "name": "self_app_secret", + "type": "string", + "description": "自身 AppSecret(脱敏,仅显示前8位+****)" + }, + { + "name": "self_ip_whitelist", + "type": "array", + "description": "IP 白名单", + "children": [ + { + "name": "ip", + "type": "string", + "description": "IP 地址或 CIDR" + } + ] + }, + { + "name": "callback_url", + "type": "string", + "description": "回调通知 URL" + }, + { + "name": "rate_limit", + "type": "number", + "description": "速率限制(次/秒)" + }, + { + "name": "sign_method", + "type": "string", + "description": "签名方法:md5/hmac/sha256" + }, + { + "name": "is_enabled", + "type": "number", + "description": "启用状态:1-启用,0-停用" + }, + { + "name": "created_at", + "type": "string", + "description": "创建时间" + }, + { + "name": "updated_at", + "type": "string", + "description": "更新时间" + } + ] + }, + { + "name": "pagination", + "type": "object", + "description": "分页信息", + "children": [ + { + "name": "page", + "type": "number", + "description": "当前页" + }, + { + "name": "pageSize", + "type": "number", + "description": "每页数量" + }, + { + "name": "total", + "type": "number", + "description": "总记录数" + }, + { + "name": "totalPages", + "type": "number", + "description": "总页数" + }, + { + "name": "hasNext", + "type": "boolean", + "description": "是否有下一页" + }, + { + "name": "hasPrevious", + "type": "boolean", + "description": "是否有上一页" + } + ] + } + ] + }, + "errors": [ + { + "code": "401", + "message": "未登录,请先登录" + }, + { + "code": "500", + "message": "服务器内部错误:查询 API 应用列表失败" + } + ] + }, + { + "method": "apiApp.detail", + "description": "查询单个 API 应用详情", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "应用 ID" + } + ], + "response": { + "type": "object", + "properties": [ + { + "name": "id", + "type": "number", + "description": "应用 ID" + }, + { + "name": "app_name", + "type": "string", + "description": "应用名称" + }, + { + "name": "warehouse_id", + "type": "number", + "description": "仓库 ID" + }, + { + "name": "interface_type_id", + "type": "number", + "description": "接口类型 ID" + }, + { + "name": "self_app_key", + "type": "string", + "description": "自身 AppKey" + }, + { + "name": "self_app_secret", + "type": "string", + "description": "自身 AppSecret(脱敏)" + }, + { + "name": "self_ip_whitelist", + "type": "array", + "description": "IP 白名单" + }, + { + "name": "callback_url", + "type": "string", + "description": "回调通知 URL" + }, + { + "name": "rate_limit", + "type": "number", + "description": "速率限制" + }, + { + "name": "sign_method", + "type": "string", + "description": "签名方法" + }, + { + "name": "is_enabled", + "type": "number", + "description": "启用状态" + }, + { + "name": "created_at", + "type": "string", + "description": "创建时间" + }, + { + "name": "updated_at", + "type": "string", + "description": "更新时间" + } + ] + }, + "errors": [ + { + "code": "400", + "message": "ID不能为空" + }, + { + "code": "401", + "message": "未登录,请先登录" + }, + { + "code": "404", + "message": "API应用不存在" + }, + { + "code": "500", + "message": "服务器内部错误:查询 API 应用详情失败" + } + ] + }, + { + "method": "apiApp.create", + "description": "创建 API 应用,自动生成 AppKey(AK{时间戳}{随机8位hex})和 AppSecret(64位hex)。仅创建时返回完整 Secret", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "app_name", + "type": "string", + "required": true, + "source": "body", + "description": "应用名称,最大 200 字符" + }, + { + "name": "interface_type_id", + "type": "number", + "required": false, + "source": "body", + "description": "接口类型 ID,不传则默认取 WH_CHANNEL 类型" + }, + { + "name": "self_ip_whitelist", + "type": "array", + "required": false, + "source": "body", + "description": "IP 白名单,如 [\"192.168.1.1\", \"10.0.0.0/24\"]", + "children": [ + { + "name": "ip", + "type": "string", + "description": "IP 地址或 CIDR" + } + ] + }, + { + "name": "callback_url", + "type": "string", + "required": false, + "source": "body", + "description": "API 回调通知 URL" + }, + { + "name": "rate_limit", + "type": "number", + "required": false, + "source": "body", + "description": "速率限制(次/秒),默认 1000,范围 1-100000" + }, + { + "name": "sign_method", + "type": "string", + "required": false, + "source": "body", + "description": "签名方法:md5/hmac/sha256,默认 md5" + } + ], + "response": { + "type": "object", + "properties": [ + { + "name": "id", + "type": "number", + "description": "应用 ID" + }, + { + "name": "app_name", + "type": "string", + "description": "应用名称" + }, + { + "name": "self_app_key", + "type": "string", + "description": "自动生成的 AppKey" + }, + { + "name": "self_app_secret", + "type": "string", + "description": "自动生成的 AppSecret(仅创建和重新生成时返回完整值,请妥善保存)" + }, + { + "name": "warehouse_id", + "type": "number", + "description": "所属仓库 ID" + }, + { + "name": "interface_type_id", + "type": "number", + "description": "接口类型 ID" + }, + { + "name": "rate_limit", + "type": "number", + "description": "速率限制" + }, + { + "name": "sign_method", + "type": "string", + "description": "签名方法" + }, + { + "name": "is_enabled", + "type": "number", + "description": "启用状态,创建后默认 1" + }, + { + "name": "created_at", + "type": "string", + "description": "创建时间" + } + ] + }, + "errors": [ + { + "code": "400", + "message": "应用名称不能为空" + }, + { + "code": "400", + "message": "应用名称不能超过200个字符" + }, + { + "code": "401", + "message": "未登录,请先登录" + }, + { + "code": "403", + "message": "无法获取当前仓库ID" + }, + { + "code": "500", + "message": "服务器内部错误:创建 API 应用失败" + } + ] + }, + { + "method": "apiApp.update", + "description": "更新 API 应用(名称、白名单、回调地址、限流、签名方法、启用状态),不可变字段:app_key、interface_type_id", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "应用 ID" + }, + { + "name": "app_name", + "type": "string", + "required": false, + "source": "body", + "description": "应用名称,最大 200 字符" + }, + { + "name": "self_ip_whitelist", + "type": "array", + "required": false, + "source": "body", + "description": "IP 白名单" + }, + { + "name": "callback_url", + "type": "string", + "required": false, + "source": "body", + "description": "回调通知 URL" + }, + { + "name": "rate_limit", + "type": "number", + "required": false, + "source": "body", + "description": "速率限制,范围 1-100000" + }, + { + "name": "sign_method", + "type": "string", + "required": false, + "source": "body", + "description": "签名方法:md5/hmac/sha256" + }, + { + "name": "is_enabled", + "type": "number", + "required": false, + "source": "body", + "description": "启用状态:1-启用,0-停用" + } + ], + "response": { + "type": "object", + "properties": [ + { + "name": "id", + "type": "number", + "description": "应用 ID" + }, + { + "name": "app_name", + "type": "string", + "description": "应用名称" + }, + { + "name": "self_app_key", + "type": "string", + "description": "AppKey(不可变)" + }, + { + "name": "self_app_secret", + "type": "string", + "description": "AppSecret(脱敏)" + }, + { + "name": "is_enabled", + "type": "number", + "description": "启用状态" + }, + { + "name": "updated_at", + "type": "string", + "description": "更新时间" + } + ] + }, + "errors": [ + { + "code": "400", + "message": "ID不能为空" + }, + { + "code": "400", + "message": "应用名称不能为空/不能超过200个字符" + }, + { + "code": "400", + "message": "签名方法仅支持 md5/hmac/sha256" + }, + { + "code": "401", + "message": "未登录,请先登录" + }, + { + "code": "404", + "message": "API应用不存在或不属于当前仓库" + }, + { + "code": "500", + "message": "服务器内部错误:更新 API 应用失败" + } + ] + }, + { + "method": "apiApp.delete", + "description": "停用 API 应用(软删除,设置 is_enabled=0,不物理删除数据)", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "应用 ID" + } + ], + "response": { + "type": "object", + "properties": [] + }, + "errors": [ + { + "code": "400", + "message": "ID不能为空" + }, + { + "code": "401", + "message": "未登录,请先登录" + }, + { + "code": "404", + "message": "API应用不存在或不属于当前仓库" + }, + { + "code": "500", + "message": "服务器内部错误:停用 API 应用失败" + } + ] + }, + { + "method": "apiApp.regenerateSecret", + "description": "重新生成 AppSecret,旧 Secret 立即失效。仅此次返回完整 Secret,请妥善保存", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "应用 ID" + } + ], + "response": { + "type": "object", + "properties": [ + { + "name": "id", + "type": "number", + "description": "应用 ID" + }, + { + "name": "app_name", + "type": "string", + "description": "应用名称" + }, + { + "name": "self_app_key", + "type": "string", + "description": "AppKey(不变)" + }, + { + "name": "self_app_secret", + "type": "string", + "description": "新生成的 AppSecret,64位十六进制(仅此次返回完整值,请妥善保存)" + } + ] + }, + "errors": [ + { + "code": "400", + "message": "ID不能为空" + }, + { + "code": "401", + "message": "未登录,请先登录" + }, + { + "code": "404", + "message": "API应用不存在或不属于当前仓库" + }, + { + "code": "500", + "message": "服务器内部错误:重新生成 AppSecret 失败" + } + ] + } + ] } ] } From edc164298d17ea9d6ce67347aeaf83e4a7b24ca7 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sat, 1 Aug 2026 03:43:47 +0800 Subject: [PATCH 138/550] =?UTF-8?q?feat(waybill):=20=E6=96=B0=E5=A2=9E?= =?UTF-8?q?=E9=9D=A2=E5=8D=95/=E8=BF=90=E5=8D=95=E7=AE=A1=E7=90=86?= =?UTF-8?q?=E6=A8=A1=E5=9D=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 systems/waybill.js 业务层:运单列表查询/详情/导出 - 新增 systemMethods/waybill/warehouse.js 入口层 - 新增 6 个迁移脚本:面单列表索引、store_id 列、物流编码/名称回填、发货单号列、货主ID回填、发货字段回填 - 更新 waybill-module-design.md 设计文档 --- .../systemMethods/waybill/warehouse.js | 307 ++++++ app/service/systems/waybill.js | 894 ++++++++++++++++++ database/designs/waybill-module-design.md | 107 ++- ...20260729140000-add-waybill-list-indexes.js | 84 ++ ...00000-add-store-id-to-wms-order-express.js | 49 + ...kfill-order-express-logistics-code-name.js | 83 ++ ...elivery-order-code-to-wms-order-express.js | 30 + ...000-backfill-wms-order-express-store-id.js | 72 ++ ...-backfill-order-express-delivery-fields.js | 60 ++ 9 files changed, 1661 insertions(+), 25 deletions(-) create mode 100644 app/service/systemMethods/waybill/warehouse.js create mode 100644 database/migrations/20260729140000-add-waybill-list-indexes.js create mode 100644 database/migrations/20260730000000-add-store-id-to-wms-order-express.js create mode 100644 database/migrations/20260730160000-backfill-order-express-logistics-code-name.js create mode 100644 database/migrations/20260730170000-add-delivery-order-code-to-wms-order-express.js create mode 100644 database/migrations/20260730200000-backfill-wms-order-express-store-id.js create mode 100644 database/migrations/20260730210000-backfill-order-express-delivery-fields.js diff --git a/app/service/systemMethods/waybill/warehouse.js b/app/service/systemMethods/waybill/warehouse.js new file mode 100644 index 0000000..9050313 --- /dev/null +++ b/app/service/systemMethods/waybill/warehouse.js @@ -0,0 +1,307 @@ +'use strict'; + +const MainService = require('../../main'); + +const WAYBILL_EXPORT_TASK_CACHE_KEY_PREFIX = 'waybill_export_task_'; + +/** + * 运单号仓库侧入口层。 + * 负责鉴权声明、参数校验,委托 systems/waybill.js 执行业务逻辑。 + * + * 所有方法均需登录但无需细粒度鉴权(与订单列表保持一致)。 + */ +class WaybillWarehouseService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list,detail,export,exportTaskProgress'; + const _noNeedLog = ''; + const _noNeedAuth = 'list,detail,export,exportTaskProgress'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 运单列表查询(仓库侧)。 + * 支持分页、多条件筛选、排序。 + * + * @param {Object} data 请求参数。 + * @param {Object} [data.where] 筛选条件。 + * @param {Object} [data.pagination] 分页参数 { page, pageSize }。 + * @param {Object} [data.sort] 排序参数 { field, order }。 + * @return {Promise} 运单列表与分页信息。 + */ + async list(data) { + try { + const { where, pagination, sort } = data || {}; + const result = await this.service.systems.waybill.list({ + where: where || {}, + pagination: pagination || {}, + sort: sort || {}, + }); + return this.success('获取成功', result); + } catch (e) { + return this.fail(e.message); + } + } + + /** + * 运单详情查询(仓库侧)。 + * 支持按运单ID或运单号查询。 + * + * @param {Object} data 请求参数。 + * @param {number} [data.id] 运单记录ID。 + * @param {string} [data.waybillCode] 运单号(与 id 二选一,waybillCode 优先)。 + * @return {Promise} 运单详情(含订单/打印/打包信息)。 + */ + async detail(data) { + try { + const { id, waybillCode } = data || {}; + if (!id && !waybillCode) { + return this.fail('运单ID或运单号不能为空'); + } + const result = await this.service.systems.waybill.detail({ + id, + waybillCode, + }); + return this.success('获取成功', result); + } catch (e) { + return this.fail(e.message); + } + } + + /** + * 运单导出(仓库侧)。异步任务模式,提交后通过 exportTaskProgress 查询进度。 + * + * @param {Object} data 请求参数。 + * @param {Object} [data.where] 筛选条件(同 list)。 + * @param {Object} [data.sort] 排序参数(同 list)。 + * @param {string[]} [data.exportFields] 需要导出的字段列表。 + * @return {Promise} 任务提交结果,含 task_id。 + */ + async export(data) { + try { + const { where, sort, exportFields } = data || {}; + const taskId = this.generateExportTaskId(); + + const taskPayload = { + task_id: taskId, + status: 'submitted', + progress: 0, + current_count: 0, + total_count: 0, + message: '导出任务已提交', + result: null, + error: '', + }; + await this.setExportTaskProgress(taskId, taskPayload); + + setImmediate(async () => { + try { + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'running', + progress: 5, + current_count: 0, + total_count: 0, + message: '导出任务执行中', + result: null, + error: '', + }); + + const result = await this.service.systems.waybill.export({ + where: where || {}, + sort: sort || {}, + exportFields, + onProgress: async progress => { + const safeProgress = this.isPlainObject(progress) ? progress : {}; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: safeProgress.status || 'running', + progress: safeProgress.progress || 0, + current_count: safeProgress.currentCount || safeProgress.current_count || 0, + total_count: safeProgress.totalCount || safeProgress.total_count || 0, + message: safeProgress.message || '导出任务执行中', + result: safeProgress.result || null, + error: '', + }); + }, + }); + + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'success', + progress: 100, + current_count: result.current_count || 0, + total_count: result.total_count || 0, + message: '导出任务完成', + result, + error: '', + }); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'failed', + progress: 100, + message: '导出任务失败', + result: null, + error: errorMessage, + }); + } + }); + + return this.success('ok', { + ...taskPayload, + update_time: Date.now(), + }); + } catch (e) { + return this.fail(e.message); + } + } + + /** + * 查询运单导出任务进度。 + * + * @param {Object} data 请求参数。 + * @param {string} [data.task_id] 任务ID(下划线写法)。 + * @param {string} [data.taskId] 任务ID(驼峰写法)。 + * @return {Promise} 任务进度信息。 + */ + async exportTaskProgress(data = {}) { + try { + const taskId = this.normalizeExportTaskId(data); + if (!taskId) { + return this.success('ok', { + task_id: '', + status: 'not_found', + progress: 0, + current_count: 0, + total_count: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const cachedTask = await this.getExportTaskProgress(taskId); + if (!cachedTask) { + return this.success('ok', { + task_id: taskId, + status: 'not_found', + progress: 0, + current_count: 0, + total_count: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {}; + const downloadUrl = String( + safeResult.url + || safeResult.cndUrl + || safeResult.cdnUrl + || safeResult.cosUrl + || safeResult.fileKey + || '' + ); + + return this.success('ok', { + task_id: taskId, + ...cachedTask, + download_url: downloadUrl, + }); + } catch (e) { + return this.fail(e.message); + } + } + + // ==================== 导出任务辅助方法 ==================== + + /** + * 生成运单导出任务ID。 + * @return {string} 任务ID。 + */ + generateExportTaskId() { + const warehouseId = this.ctx?.user?.store_id || 'unknown'; + const timestamp = Date.now(); + const randomToken = Math.random().toString(36).slice(2, 10); + return `waybill_export_${warehouseId}_${timestamp}_${randomToken}`; + } + + /** + * 规范导出任务ID。 + * @param {Object} data 请求体。 + * @return {string} 规范后的任务ID。 + */ + normalizeExportTaskId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.task_id || normalizedData.taskId || '').trim(); + } + + /** + * 获取运单导出任务缓存键。 + * @param {string} taskId 任务ID。 + * @return {string} 缓存键。 + */ + getExportTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + return `${WAYBILL_EXPORT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 写入运单导出任务进度缓存。 + * @param {string} taskId 任务ID。 + * @param {Object} payload 任务状态。 + * @return {Promise} 无返回值。 + */ + async setExportTaskProgress(taskId = '', payload = {}) { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.setCacheAsync !== 'function') { + return; + } + + const safePayload = this.isPlainObject(payload) ? payload : {}; + const normalizeCount = value => { + const numericValue = Number(value); + return Number.isFinite(numericValue) && numericValue >= 0 ? Math.round(numericValue) : 0; + }; + const progressPayload = { + task_id: String(taskId || '').trim(), + status: String(safePayload.status || 'submitted').trim() || 'submitted', + progress: Number.isFinite(Number(safePayload.progress)) + ? Math.min(100, Math.max(0, Math.round(Number(safePayload.progress)))) + : 0, + current_count: normalizeCount(safePayload.current_count), + total_count: normalizeCount(safePayload.total_count), + message: String(safePayload.message || ''), + result: safePayload.result ?? null, + error: String(safePayload.error || ''), + }; + + await this.app.setCacheAsync(cacheKey, progressPayload); + } + + /** + * 读取运单导出任务进度缓存。 + * @param {string} taskId 任务ID。 + * @return {Promise} 任务状态对象或 null。 + */ + async getExportTaskProgress(taskId = '') { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.getCacheAsync !== 'function') { + return null; + } + return await this.app.getCacheAsync(cacheKey); + } +} + +module.exports = WaybillWarehouseService; diff --git a/app/service/systems/waybill.js b/app/service/systems/waybill.js index 94f40ff..83a80f5 100644 --- a/app/service/systems/waybill.js +++ b/app/service/systems/waybill.js @@ -1,6 +1,11 @@ 'use strict'; const MainService = require('../main'); +const ExcelJS = require('exceljs'); +const fs = require('fs'); +const fsp = require('fs').promises; +const path = require('path'); +const os = require('os'); /** * 业务逻辑层:waybill(运单号快速查询)。 @@ -131,6 +136,895 @@ class WaybillService extends MainService { ], }; } + + /** + * 运单列表查询(仓库侧)。 + * 按仓库维度查询运单号列表,支持分页、多条件筛选、排序。 + * 核心查询仅使用 wms_order_express 单表(利用快照字段), + * 主单号通过 SELF JOIN 同 order_id 下 business_key=1 的记录获取。 + * + * @param {Object} [options={}] 查询参数。 + * @param {Object} [options.where] 筛选条件,支持 waybillCode / mainWaybillCode / orderId / orderNo / logisticsCode / logisticsInterfaceId / platformCode / status / isBack / isIntercept / isGalaxyReceive / packageMaterialId / hasWeighingWeight / keyword / createdAtStart / createdAtEnd。 + * @param {Object} [options.pagination] 分页参数 { page, pageSize },默认 page=1, pageSize=20。 + * @param {Object} [options.sort] 排序参数 { field, order },默认 create_at desc。 + * @return {Promise} 运单列表与分页信息 { list, pagination }。 + */ + async list({ where = {}, pagination = {}, sort = {} } = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + // 仓库隔离 + const warehouseId = Number(ctx.user && ctx.user.store_id); + if (!warehouseId) { + this.throwError('用户未绑定仓库,无法查询运单'); + } + + // 分页参数 + const page = Math.max(Number(pagination.page) || 1, 1); + const pageSize = Math.min(Math.max(Number(pagination.pageSize) || 20, 1), 500); + + // 排序参数 + const allowedSortFields = [ 'create_at', 'weighing_weight', 'id' ]; + const sortField = allowedSortFields.includes(sort.field) ? sort.field : 'create_at'; + const sortOrder = sort.order === 'asc' ? 'ASC' : 'DESC'; + + // 构建查询条件 + const queryWhere = { warehouse_id: warehouseId }; + + // 主单号查询:先通过主单号定位 order_id,再查该 order 下所有运单 + if (where.mainWaybillCode && String(where.mainWaybillCode).trim()) { + const mainCode = String(where.mainWaybillCode).trim(); + const mainRecord = await ctx.model.OrderExpress.findOne({ + where: { + waybill_code: mainCode, + business_key: 1, + warehouse_id: warehouseId, + }, + attributes: [ 'order_id' ], + raw: true, + }); + if (mainRecord) { + queryWhere.order_id = mainRecord.order_id; + } else { + // 主单号不存在,直接返回空结果 + return { + list: [], + pagination: { page, pageSize, total: 0, totalPages: 0 }, + }; + } + } + + // 运单号模糊搜索 + if (where.waybillCode && String(where.waybillCode).trim()) { + queryWhere.waybill_code = { [Op.like]: `%${String(where.waybillCode).trim()}%` }; + } + + // 订单ID等值 + if (where.orderId !== undefined && where.orderId !== null && String(where.orderId).trim() !== '') { + queryWhere.order_id = Number(where.orderId); + } + + // 订单号模糊搜索 + // TODO: 快照字段 delivery_order_code 未落库,暂跳过订单号筛选;快照列就绪后取消注释 + // if (where.orderNo && String(where.orderNo).trim()) { + // queryWhere.delivery_order_code = { [Op.like]: `%${String(where.orderNo).trim()}%` }; + // } + + // 物流公司编码等值 + if (where.logisticsCode && String(where.logisticsCode).trim()) { + queryWhere.logistics_code = String(where.logisticsCode).trim(); + } + + // 物流接口ID等值 + if (where.logisticsInterfaceId !== undefined && where.logisticsInterfaceId !== null && String(where.logisticsInterfaceId).trim() !== '') { + queryWhere.logistics_interface_id = Number(where.logisticsInterfaceId); + } + + // 平台编码等值 + if (where.platformCode && String(where.platformCode).trim()) { + queryWhere.platform_code = String(where.platformCode).trim(); + } + + // 运单状态等值 + if (where.status !== undefined && where.status !== null && String(where.status).trim() !== '') { + queryWhere.status = Number(where.status); + } + + // 是否退回 + if (where.isBack && String(where.isBack).trim()) { + queryWhere.is_back = String(where.isBack).trim(); + } + + // 是否拦截 + if (where.isIntercept && String(where.isIntercept).trim()) { + queryWhere.is_intercept = String(where.isIntercept).trim(); + } + + // 是否揽收 + if (where.isGalaxyReceive && String(where.isGalaxyReceive).trim()) { + queryWhere.is_galaxy_receive = String(where.isGalaxyReceive).trim(); + } + + // 运单类型:主单号 / 子单号 + if (where.waybillType && String(where.waybillType).trim()) { + const type = String(where.waybillType).trim(); + if (type === 'main' || type === '1') { + queryWhere.business_key = 1; + } else if (type === 'child' || type === '2') { + queryWhere.business_key = { [Op.gt]: 1 }; + } + } + + // 货主ID等值 + if (where.storeId !== undefined && where.storeId !== null && String(where.storeId).trim() !== '') { + queryWhere.store_id = Number(where.storeId); + } + + // 包材ID等值 + if (where.packageMaterialId !== undefined && where.packageMaterialId !== null && String(where.packageMaterialId).trim() !== '') { + queryWhere.package_material_id = Number(where.packageMaterialId); + } + + // 是否已称重 + if (where.hasWeighingWeight !== undefined && where.hasWeighingWeight !== null && String(where.hasWeighingWeight).trim() !== '') { + const hasWeight = String(where.hasWeighingWeight).trim(); + if (hasWeight === 'true') { + queryWhere.weighing_weight = { [Op.gt]: 0 }; + } else if (hasWeight === 'false') { + queryWhere.weighing_weight = { [Op.eq]: 0 }; + } + } + + // 关键词模糊搜索 + if (where.keyword && String(where.keyword).trim()) { + queryWhere.waybill_code = { [Op.like]: `%${String(where.keyword).trim()}%` }; + } + + // 创建时间范围 + if (where.createdAtStart && String(where.createdAtStart).trim()) { + const startDate = this.normalizeDate(String(where.createdAtStart).trim(), false); + if (startDate) { + queryWhere.create_at = { ...(queryWhere.create_at || {}), [Op.gte]: startDate }; + } + } + if (where.createdAtEnd && String(where.createdAtEnd).trim()) { + const endDate = this.normalizeDate(String(where.createdAtEnd).trim(), true); + if (endDate) { + queryWhere.create_at = { ...(queryWhere.create_at || {}), [Op.lte]: endDate }; + } + } + + // 核心查询:仅查 wms_order_express 单表 + // TODO: warehouse_name_snapshot / store_id_snapshot / store_name_snapshot / delivery_order_code + // 快照列未落库,暂时只查已有字段;快照列就绪后替换为快照直读 + const { count, rows } = await ctx.model.OrderExpress.findAndCountAll({ + where: queryWhere, + attributes: [ + 'id', 'waybill_code', 'order_id', 'business_key', 'status', + 'warehouse_id', 'store_id', + 'logistics_code', 'logistics_name', + 'logistics_interface_id', 'logistics_interface_name', + 'platform_code', + 'is_back', 'is_intercept', 'is_galaxy_receive', + 'weighing_weight', + 'package_material_id', 'package_material_name_snapshot', + 'create_at', + ], + order: [[ sortField, sortOrder ]], + limit: pageSize, + offset: (page - 1) * pageSize, + raw: true, + }); + + if (rows.length === 0) { + return { + list: [], + pagination: { page, pageSize, total: count, totalPages: Math.ceil(count / pageSize) }, + }; + } + + // 提取所有唯一的 order_id + const orderIds = [ ...new Set(rows.map(r => r.order_id).filter(Boolean)) ]; + + // SELF JOIN:查询同 order_id 下 business_key=1 的主单号 + const mainWaybillMap = new Map(); + if (orderIds.length > 0) { + const mainRecords = await ctx.model.OrderExpress.findAll({ + where: { + order_id: { [Op.in]: orderIds }, + business_key: 1, + }, + attributes: [ 'order_id', 'waybill_code' ], + raw: true, + }); + for (const rec of mainRecords) { + if (!mainWaybillMap.has(rec.order_id)) { + mainWaybillMap.set(rec.order_id, rec.waybill_code); + } + } + } + + // 提取运单号列表,用于查询打印信息 + const waybillCodes = rows.map(r => r.waybill_code).filter(Boolean); + + // 查询货主备注名称(store_warehouse.store_remask) + const storeRemarkMap = new Map(); + const storeWarehouseKeys = rows + .filter(r => r.store_id && r.warehouse_id) + .map(r => `${r.store_id}:${r.warehouse_id}`); + const uniqueKeys = [ ...new Set(storeWarehouseKeys) ]; + if (uniqueKeys.length > 0 && ctx.model.StoreWarehouse) { + const swConditions = uniqueKeys.map(key => { + const [ storeId, whId ] = key.split(':'); + return { store_id: Number(storeId), warehouse_id: Number(whId) }; + }); + const swRows = await ctx.model.StoreWarehouse.findAll({ + where: { [Op.or]: swConditions }, + attributes: [ 'store_id', 'warehouse_id', 'store_remask' ], + raw: true, + }); + for (const sw of swRows) { + storeRemarkMap.set(`${sw.store_id}:${sw.warehouse_id}`, sw.store_remask || ''); + } + } + + // 查询打印记录(次数和最近打印时间) + const printInfoMap = new Map(); + if (waybillCodes.length > 0) { + const printRecords = await ctx.model.ExpressPrintRecord.findAll({ + where: { express_no: { [Op.in]: waybillCodes } }, + attributes: [ + 'express_no', + [ app.Sequelize.fn('COUNT', app.Sequelize.col('id')), 'print_count' ], + [ app.Sequelize.fn('MAX', app.Sequelize.col('print_time')), 'last_print_at' ], + ], + group: [ 'express_no' ], + raw: true, + }); + for (const pr of printRecords) { + printInfoMap.set(pr.express_no, { + print_count: Number(pr.print_count) || 0, + last_print_at: pr.last_print_at || null, + }); + } + } + + // 组装响应列表 + const list = rows.map(row => { + const wbCode = row.waybill_code || ''; + const mainCode = mainWaybillMap.get(row.order_id) || wbCode; + const printInfo = printInfoMap.get(wbCode) || { print_count: 0, last_print_at: null }; + + return { + id: row.id, + waybill_code: wbCode, + main_waybill_code: mainCode, + waybill_type: Number(row.business_key) === 1 ? '主单号' : '子单号', + order_id: row.order_id, + // TODO: 快照列未落库,暂时填空;快照就绪后替换为 row.delivery_order_code + order_no: '', + warehouse_id: row.warehouse_id, + // TODO: 快照列未落库,暂时填空;快照就绪后替换为 row.warehouse_name_snapshot + warehouse_name: '', + store_id: row.store_id || 0, + // TODO: 快照列未落库,暂时填空;快照就绪后替换为 row.store_name_snapshot + store_name: '', + store_remark_name: storeRemarkMap.get(`${row.store_id}:${row.warehouse_id}`) || '', + business_key: row.business_key, + status: row.status, + status_text: row.status === 1 ? '已分配' : '未分配', + logistics_code: row.logistics_code || '', + logistics_name: row.logistics_name || '', + logistics_interface_id: row.logistics_interface_id || 0, + logistics_interface_name: row.logistics_interface_name || '', + platform_code: row.platform_code || '', + is_back: row.is_back || 'N', + is_intercept: row.is_intercept || 'N', + is_galaxy_receive: row.is_galaxy_receive || 'N', + weighing_weight: row.weighing_weight || 0, + weighing_weight_display: row.weighing_weight > 0 ? `${(row.weighing_weight / 1000).toFixed(2)} kg` : '0 kg', + package_material_id: row.package_material_id || 0, + package_material_name: row.package_material_name_snapshot || '', + print_count: printInfo.print_count, + last_print_at: printInfo.last_print_at ? this.app.formatDate(printInfo.last_print_at) : null, + create_at: row.create_at ? this.app.formatDate(row.create_at) : null, + }; + }); + + return { + list, + pagination: { + page, + pageSize, + total: count, + totalPages: Math.ceil(count / pageSize), + }, + }; + } + + /** + * 运单详情查询(仓库侧)。 + * 查询单个运单的完整信息,包含关联订单、兄弟运单、打印记录、打包信息。 + * + * @param {Object} options 查询参数。 + * @param {number} [options.id] 运单记录ID。 + * @param {string} [options.waybillCode] 运单号(与 id 二选一,waybillCode 优先)。 + * @return {Promise} 运单详情。 + * @throws {Error} 当运单不存在或参数无效时抛出业务错误。 + */ + async detail({ id, waybillCode } = {}) { + const { ctx } = this; + + // 仓库隔离 + const warehouseId = Number(ctx.user && ctx.user.store_id); + if (!warehouseId) { + this.throwError('用户未绑定仓库,无法查询运单'); + } + + // 构建查询条件 + const expressWhere = { warehouse_id: warehouseId }; + if (waybillCode && String(waybillCode).trim()) { + expressWhere.waybill_code = String(waybillCode).trim(); + } else if (id !== undefined && id !== null && String(id).trim() !== '') { + expressWhere.id = Number(id); + } else { + this.throwError('运单ID或运单号不能为空'); + } + + // 查询运单主记录 + const record = await ctx.model.OrderExpress.findOne({ + where: expressWhere, + raw: true, + }); + + if (!record) { + this.throwError('未找到该运单'); + } + + const orderId = record.order_id; + + // 查询同订单下所有运单(兄弟运单) + const siblingWaybills = await ctx.model.OrderExpress.findAll({ + where: { order_id: orderId, warehouse_id: warehouseId }, + attributes: [ 'id', 'waybill_code', 'business_key' ], + order: [[ 'business_key', 'ASC' ]], + raw: true, + }); + + const mainWaybillRecord = siblingWaybills.find(s => Number(s.business_key) === 1); + const mainWaybillCode = mainWaybillRecord ? mainWaybillRecord.waybill_code : (record.waybill_code || ''); + + const siblingList = siblingWaybills.map(s => ({ + waybill_code: s.waybill_code || '', + business_key: s.business_key, + waybill_type: Number(s.business_key) === 1 ? '主单号' : '子单号', + })); + + // 通过 OrderDeliveryFactory 多表遍历查询订单信息 + const orderDeliveryFactory = ctx.model && ctx.model.OrderDeliveryFactory; + let orderInfo = null; + if (orderDeliveryFactory && typeof orderDeliveryFactory.getCurrentModel === 'function') { + const tableOrders = [ + { label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) }, + { label: 'history', getModel: () => orderDeliveryFactory.getHistoryModel(warehouseId) }, + { label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) }, + ]; + + for (const entry of tableOrders) { + try { + const model = await entry.getModel(); + if (!model || typeof model.findOne !== 'function') { + continue; + } + const row = await model.findOne({ + where: { id: orderId, warehouse_id: warehouseId }, + attributes: [ + 'id', 'delivery_order_code', 'warehouse_id', 'store_id', + 'wave_id', 'wave_no', 'order_type', 'store_name', + ], + raw: true, + }); + if (row) { + orderInfo = { + order_id: row.id, + order_no: row.delivery_order_code || '', + warehouse_id: row.warehouse_id, + // TODO: 快照列未落库,暂时填空;快照就绪后替换为 record.warehouse_name_snapshot + warehouse_name: '', + store_id: row.store_id || 0, + store_name: row.store_name || '', + wave_id: row.wave_id || 0, + wave_no: row.wave_no || '', + order_type: row.order_type || 'delivery', + }; + break; + } + } catch (_err) { + continue; + } + } + } + + // 若遍历失败,用已有信息兜底 + // TODO: 快照列未落库,暂用空值兜底;快照就绪后替换为 record.xxx_snapshot + if (!orderInfo) { + orderInfo = { + order_id: orderId, + order_no: '', + warehouse_id: record.warehouse_id, + warehouse_name: '', + store_id: 0, + store_name: '', + wave_id: 0, + wave_no: '', + order_type: 'delivery', + }; + } + + // 查询打印记录 + let printRecords = []; + if (record.waybill_code) { + printRecords = await ctx.model.ExpressPrintRecord.findAll({ + where: { express_no: record.waybill_code }, + attributes: [ + 'id', 'printer_name', 'template_id', 'platform', + 'print_time', + ], + order: [[ 'print_time', 'DESC' ]], + raw: true, + }); + } + + // 组装详情响应 + return { + id: record.id, + waybill_code: record.waybill_code || '', + main_waybill_code: mainWaybillCode, + waybill_type: Number(record.business_key) === 1 ? '主单号' : '子单号', + business_key: record.business_key, + sibling_waybills: siblingList, + order: orderInfo, + logistics: { + logistics_code: record.logistics_code || '', + logistics_name: record.logistics_name || '', + logistics_interface_id: record.logistics_interface_id || 0, + logistics_interface_name: record.logistics_interface_name || '', + platform_code: record.platform_code || '', + }, + status_info: { + status: record.status, + status_text: record.status === 1 ? '已分配' : '未分配', + is_back: record.is_back || 'N', + is_intercept: record.is_intercept || 'N', + is_galaxy_receive: record.is_galaxy_receive || 'N', + }, + weight: { + weighing_weight: record.weighing_weight || 0, + weighing_weight_display: record.weighing_weight > 0 + ? `${(record.weighing_weight / 1000).toFixed(2)} kg` + : '0 kg', + }, + package: { + package_material_id: record.package_material_id || 0, + package_material_name: record.package_material_name_snapshot || '', + }, + print_records: printRecords.map(pr => ({ + id: pr.id, + printer_name: pr.printer_name || '', + template_id: pr.template_id || 0, + template_name: '', + platform: pr.platform || '', + printed_at: pr.print_time ? this.app.formatDate(pr.print_time) : null, + })), + print_count: printRecords.length, + printinfo: record.printinfo || null, + ver: record.ver || '', + retry_count: record.retry_count || 0, + create_at: record.create_at ? this.app.formatDate(record.create_at) : null, + delete_at: record.delete_at ? this.app.formatDate(record.delete_at) : null, + }; + } + + /** + * 运单导出(仓库侧)。 + * 复用 list 的筛选逻辑,分批查询,支持进度回调。 + * + * @param {Object} options 导出参数。 + * @param {Object} [options.where={}] 筛选条件(同 list)。 + * @param {Object} [options.sort={}] 排序参数(同 list)。 + * @param {string[]} [options.exportFields] 需要导出的字段列表,不传则导出全部字段。 + * @param {Function} [options.onProgress] 进度回调,接收 `{ status, progress, currentCount, totalCount, message, result }`。 + * @return {Promise} 导出结果 { list, current_count, total_count, url }。 + */ + async export({ where = {}, sort = {}, exportFields, onProgress } = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + // 仓库隔离 + const warehouseId = Number(ctx.user && ctx.user.store_id); + if (!warehouseId) { + this.throwError('用户未绑定仓库,无法导出运单'); + } + + // 排序参数 + const allowedSortFields = [ 'create_at', 'weighing_weight', 'id' ]; + const sortField = allowedSortFields.includes(sort.field) ? sort.field : 'create_at'; + const sortOrder = sort.order === 'asc' ? 'ASC' : 'DESC'; + + // 构建查询条件(同 list) + const queryWhere = { warehouse_id: warehouseId }; + + // 主单号查询 + if (where.mainWaybillCode && String(where.mainWaybillCode).trim()) { + const mainCode = String(where.mainWaybillCode).trim(); + const mainRecord = await ctx.model.OrderExpress.findOne({ + where: { + waybill_code: mainCode, + business_key: 1, + warehouse_id: warehouseId, + }, + attributes: [ 'order_id' ], + raw: true, + }); + if (mainRecord) { + queryWhere.order_id = mainRecord.order_id; + } else { + if (typeof onProgress === 'function') { + await onProgress({ status: 'success', progress: 100, currentCount: 0, totalCount: 0, message: '导出完成', result: { list: [], url: '' } }); + } + return { list: [], current_count: 0, total_count: 0, url: '' }; + } + } + + if (where.waybillCode && String(where.waybillCode).trim()) { + queryWhere.waybill_code = { [Op.like]: `%${String(where.waybillCode).trim()}%` }; + } + if (where.orderId !== undefined && where.orderId !== null && String(where.orderId).trim() !== '') { + queryWhere.order_id = Number(where.orderId); + } + // TODO: 快照字段 delivery_order_code 未落库,暂跳过订单号筛选;快照列就绪后取消注释 + if (where.logisticsCode && String(where.logisticsCode).trim()) { + queryWhere.logistics_code = String(where.logisticsCode).trim(); + } + if (where.logisticsInterfaceId !== undefined && where.logisticsInterfaceId !== null && String(where.logisticsInterfaceId).trim() !== '') { + queryWhere.logistics_interface_id = Number(where.logisticsInterfaceId); + } + if (where.platformCode && String(where.platformCode).trim()) { + queryWhere.platform_code = String(where.platformCode).trim(); + } + if (where.status !== undefined && where.status !== null && String(where.status).trim() !== '') { + queryWhere.status = Number(where.status); + } + if (where.isBack && String(where.isBack).trim()) { + queryWhere.is_back = String(where.isBack).trim(); + } + if (where.isIntercept && String(where.isIntercept).trim()) { + queryWhere.is_intercept = String(where.isIntercept).trim(); + } + if (where.isGalaxyReceive && String(where.isGalaxyReceive).trim()) { + queryWhere.is_galaxy_receive = String(where.isGalaxyReceive).trim(); + } + if (where.waybillType && String(where.waybillType).trim()) { + const type = String(where.waybillType).trim(); + if (type === 'main' || type === '1') { + queryWhere.business_key = 1; + } else if (type === 'child' || type === '2') { + queryWhere.business_key = { [Op.gt]: 1 }; + } + } + // 货主ID等值 + if (where.storeId !== undefined && where.storeId !== null && String(where.storeId).trim() !== '') { + queryWhere.store_id = Number(where.storeId); + } + if (where.packageMaterialId !== undefined && where.packageMaterialId !== null && String(where.packageMaterialId).trim() !== '') { + queryWhere.package_material_id = Number(where.packageMaterialId); + } + if (where.hasWeighingWeight !== undefined && where.hasWeighingWeight !== null && String(where.hasWeighingWeight).trim() !== '') { + const hasWeight = String(where.hasWeighingWeight).trim(); + if (hasWeight === 'true') { + queryWhere.weighing_weight = { [Op.gt]: 0 }; + } else if (hasWeight === 'false') { + queryWhere.weighing_weight = { [Op.eq]: 0 }; + } + } + if (where.keyword && String(where.keyword).trim()) { + queryWhere.waybill_code = { [Op.like]: `%${String(where.keyword).trim()}%` }; + } + if (where.createdAtStart && String(where.createdAtStart).trim()) { + const startDate = this.normalizeDate(String(where.createdAtStart).trim(), false); + if (startDate) { + queryWhere.create_at = { ...(queryWhere.create_at || {}), [Op.gte]: startDate }; + } + } + if (where.createdAtEnd && String(where.createdAtEnd).trim()) { + const endDate = this.normalizeDate(String(where.createdAtEnd).trim(), true); + if (endDate) { + queryWhere.create_at = { ...(queryWhere.create_at || {}), [Op.lte]: endDate }; + } + } + + // 先统计总数 + if (typeof onProgress === 'function') { + await onProgress({ status: 'running', progress: 10, currentCount: 0, totalCount: 0, message: '正在统计数据…' }); + } + const totalCount = await ctx.model.OrderExpress.count({ where: queryWhere }); + + if (totalCount === 0) { + if (typeof onProgress === 'function') { + await onProgress({ status: 'success', progress: 100, currentCount: 0, totalCount: 0, message: '导出完成', result: { list: [], url: '' } }); + } + return { list: [], current_count: 0, total_count: 0, url: '' }; + } + + if (typeof onProgress === 'function') { + await onProgress({ status: 'running', progress: 15, currentCount: 0, totalCount, message: `共 ${totalCount} 条,正在导出…` }); + } + + // 分批查询(避免大数据量内存溢出) + const EXPORT_PAGE_SIZE = 500; + const allRows = []; + const totalPages = Math.ceil(totalCount / EXPORT_PAGE_SIZE); + + for (let page = 0; page < totalPages; page++) { + const pageRows = await ctx.model.OrderExpress.findAll({ + where: queryWhere, + // TODO: 快照列未落库,暂时只查已有字段;快照就绪后补充 + attributes: [ + 'id', 'waybill_code', 'order_id', 'business_key', 'status', + 'warehouse_id', 'store_id', + 'logistics_code', 'logistics_name', + 'logistics_interface_id', 'logistics_interface_name', + 'platform_code', + 'is_back', 'is_intercept', 'is_galaxy_receive', + 'weighing_weight', + 'package_material_id', 'package_material_name_snapshot', + 'create_at', + ], + order: [[ sortField, sortOrder ]], + limit: EXPORT_PAGE_SIZE, + offset: page * EXPORT_PAGE_SIZE, + raw: true, + }); + allRows.push(...pageRows); + + // 进度回调(15% ~ 90%) + if (typeof onProgress === 'function') { + const progress = 15 + Math.round(75 * (page + 1) / totalPages); + await onProgress({ + status: 'running', + progress, + currentCount: allRows.length, + totalCount, + message: `已导出 ${allRows.length} / ${totalCount} 条`, + }); + } + } + + // 提取所有唯一的 order_id,SELF JOIN 主单号 + const orderIds = [ ...new Set(allRows.map(r => r.order_id).filter(Boolean)) ]; + const mainWaybillMap = new Map(); + if (orderIds.length > 0) { + const mainRecords = await ctx.model.OrderExpress.findAll({ + where: { + order_id: { [Op.in]: orderIds }, + business_key: 1, + }, + attributes: [ 'order_id', 'waybill_code' ], + raw: true, + }); + for (const rec of mainRecords) { + if (!mainWaybillMap.has(rec.order_id)) { + mainWaybillMap.set(rec.order_id, rec.waybill_code); + } + } + } + + // 预定义全部导出字段映射 + const allFieldMap = { + id: r => r.id, + waybill_code: r => r.waybill_code || '', + main_waybill_code: r => mainWaybillMap.get(r.order_id) || r.waybill_code || '', + waybill_type: r => (Number(r.business_key) === 1 ? '主单号' : '子单号'), + order_id: r => r.order_id, + // TODO: 快照列未落库,暂时填空;快照就绪后替换 + order_no: () => '', + warehouse_id: r => r.warehouse_id, + warehouse_name: () => '', + store_id: r => r.store_id || 0, + store_name: () => '', + business_key: r => r.business_key, + status: r => r.status, + status_text: r => (r.status === 1 ? '已分配' : '未分配'), + logistics_code: r => r.logistics_code || '', + logistics_name: r => r.logistics_name || '', + logistics_interface_id: r => r.logistics_interface_id || 0, + logistics_interface_name: r => r.logistics_interface_name || '', + platform_code: r => r.platform_code || '', + is_back: r => r.is_back || 'N', + is_intercept: r => r.is_intercept || 'N', + is_galaxy_receive: r => r.is_galaxy_receive || 'N', + weighing_weight: r => r.weighing_weight || 0, + weighing_weight_display: r => (r.weighing_weight > 0 ? `${(r.weighing_weight / 1000).toFixed(2)} kg` : '0 kg'), + package_material_id: r => r.package_material_id || 0, + package_material_name: r => r.package_material_name_snapshot || '', + create_at: r => (r.create_at ? this.app.formatDate(r.create_at) : null), + }; + + // 确定导出字段集 + const fields = Array.isArray(exportFields) && exportFields.length > 0 + ? exportFields.filter(f => allFieldMap[f]) + : Object.keys(allFieldMap); + + const list = allRows.map(row => { + const item = {}; + for (const field of fields) { + item[field] = allFieldMap[field](row); + } + return item; + }); + + if (typeof onProgress === 'function') { + await onProgress({ + status: 'running', + progress: 95, + currentCount: allRows.length, + totalCount, + message: '正在生成导出文件…', + }); + } + + // 生成 Excel 文件并上传 + const result = await this.buildWaybillExportFile({ + list, + fields, + warehouseId, + totalCount: allRows.length, + }); + + if (typeof onProgress === 'function') { + await onProgress({ + status: 'success', + progress: 100, + currentCount: allRows.length, + totalCount, + message: '导出完成', + result, + }); + } + + return result; + } + + /** + * 生成运单导出 Excel 文件并上传,返回下载链接。 + * @param {Object} options 导出选项。 + * @param {Array} options.list 导出数据列表。 + * @param {string[]} options.fields 导出字段列表。 + * @param {number} options.warehouseId 仓库ID。 + * @param {number} options.totalCount 总条数。 + * @return {Promise} { current_count, total_count, url }。 + */ + async buildWaybillExportFile({ list, fields, warehouseId, totalCount } = {}) { + const { ctx } = this; + + // 列名中文映射 + const COLUMN_LABELS = { + id: 'ID', + waybill_code: '运单号', + main_waybill_code: '主单号', + waybill_type: '运单类型', + order_id: '订单ID', + order_no: '订单号', + warehouse_id: '仓库ID', + warehouse_name: '仓库名称', + store_id: '货主ID', + store_name: '货主名称', + business_key: '拆单序号', + status: '状态', + status_text: '状态', + logistics_code: '物流编码', + logistics_name: '物流名称', + logistics_interface_id: '物流接口ID', + logistics_interface_name: '物流接口名称', + platform_code: '平台编码', + is_back: '是否退回', + is_intercept: '是否拦截', + is_galaxy_receive: '是否揽收', + weighing_weight: '称重重量(g)', + weighing_weight_display: '称重重量', + package_material_id: '包材ID', + package_material_name: '包材名称', + create_at: '创建时间', + }; + + // 生成 Excel + const workbook = new ExcelJS.Workbook(); + const worksheet = workbook.addWorksheet('运单导出'); + + // 写表头 + const headerRow = worksheet.addRow(fields.map(f => COLUMN_LABELS[f] || f)); + headerRow.font = { bold: true }; + headerRow.alignment = { horizontal: 'center' }; + + // 写数据 + for (const row of list) { + worksheet.addRow(fields.map(f => (row[f] !== undefined && row[f] !== null ? row[f] : ''))); + } + + // 保存到临时文件 + const now = new Date(); + const dateStr = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}`; + const filename = `运单导出_${dateStr}.xlsx`; + const tmpDir = os.tmpdir(); + const filePath = path.join(tmpDir, `waybill_export_${Date.now()}_${Math.random().toString(36).slice(2, 8)}.xlsx`); + + await workbook.xlsx.writeFile(filePath); + + // 上传文件 + const uploadService = ctx?.service?.systems?.upload; + let url = ''; + let fileKey = ''; + + if (uploadService && typeof uploadService.uploadFile === 'function') { + try { + const stat = await fsp.stat(filePath); + const safeWarehouseId = String(warehouseId || 'unknown'); + const randomToken = Math.random().toString(36).slice(2, 8); + const uploadKey = `exports/waybill/${safeWarehouseId}/${Date.now()}_${randomToken}.xlsx`; + + const uploadStream = fs.createReadStream(filePath); + uploadStream.filename = filename; + uploadStream.mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; + uploadStream.fileSize = stat.size; + + const uploadResult = await uploadService.uploadFile(uploadStream, { + key: uploadKey, + category: 'document', + mimetype: 'xls,xlsx,csv', + }); + + url = uploadResult.url || uploadResult.cdnUrl || uploadResult.cosUrl || ''; + fileKey = uploadResult.fileName || ''; + + // 记录上传文件 + if (typeof uploadService.uploadSuccessNotify === 'function') { + await uploadService.uploadSuccessNotify({ + url: uploadResult.fileName, + fileKey: uploadResult.fileName, + fileName: filename, + fileType: 'document', + mimeType: uploadStream.mimeType, + fileSize: stat.size, + category: 'document', + businessType: 'waybillExport', + businessId: `${warehouseId}`, + uploaderType: ctx?.user?.role || 'system_api', + uploaderDept: ctx?.user?.department || '', + }); + } + } catch (uploadError) { + ctx.logger.error('[WaybillService.buildWaybillExportFile] 文件上传失败', { + error: uploadError.message, + filename, + }); + } + } + + // 清理临时文件 + try { + await fsp.unlink(filePath); + } catch (_e) { + // 忽略清理错误 + } + + return { + current_count: totalCount, + total_count: totalCount, + url, + fileKey, + filename, + }; + } } module.exports = WaybillService; diff --git a/database/designs/waybill-module-design.md b/database/designs/waybill-module-design.md index a963fe6..af311a6 100644 --- a/database/designs/waybill-module-design.md +++ b/database/designs/waybill-module-design.md @@ -1,6 +1,6 @@ # 运单号模块设计方案(仓库侧) -> **状态**: ⏳ 等待审阅 +> **状态**: 🔧 开发中(索引已就绪,快照字段待 dev 实现写入逻辑后执行) > **设计日期**: 2026-07-29 > **设计人**: wms-db-agent > **说明**: 本文档仅输出设计方案,不执行代码实现。审阅通过后再进入开发。 @@ -34,6 +34,7 @@ | `waybill_code` | `VARCHAR(50)` | **运单号** | | `order_id` | `BIGINT(20)` | 订单ID | | `warehouse_id` | `BIGINT(20) UNSIGNED` | 仓库ID | +| `store_id` | `BIGINT(20) UNSIGNED` | 🆕 货主ID | | `business_key` | `INTEGER(3)` | 拆单序号(1=主单号,>1=子单号) | | `status` | `TINYINT(1)` DEFAULT 0 | 状态(1=已分配,0=未分配) | | `logistics_interface_id` | `BIGINT(20) UNSIGNED` | 物流接口ID | @@ -42,7 +43,7 @@ | `logistics_interface_id` | `BIGINT(20) UNSIGNED` | 物流接口ID | | `logistics_interface_name` | `VARCHAR(50)` | 物流接口名称 | | `platform_code` | `VARCHAR(50)` | 平台编码 | -| `is_galaxy_receive` | `ENUM('Y','N')` | 是否星河签收 | +| `is_galaxy_receive` | `ENUM('Y','N')` | 是否揽收 | | `is_back` | `ENUM('Y','N')` | 是否退回 | | `is_intercept` | `ENUM('Y','N')` | 是否拦截 | | `weighing_weight` | `INT(11)` DEFAULT 0 | 称重重量(g) | @@ -86,7 +87,7 @@ | `idx_warehouse_id_create_at` | 仓库+时间范围排序分页 | | `idx_order_id_business_key` | 已有 `uk_order_id_business_key` 唯一索引,可同时覆盖主单号 SELF JOIN 查询 | -> **索引迁移**:以下索引将通过迁移文件 `YYYYMMDDHHmmss-add-waybill-list-indexes.js` 正式创建,见 §五 文件变更清单。 +> **索引迁移**:以下索引已通过迁移文件 `20260729140000-add-waybill-list-indexes.js` 正式创建,见 §五 文件变更清单。 ### 2.4 主单号/子单号关联关系 @@ -105,6 +106,29 @@ - 大部分运单 `business_key = 1`(未拆单),此时主单号 = 运单号本身 - 仅拆单场景下存在 `business_key > 1` 的子单号 +### 2.5 快照字段评估(待开发实现) + +> **状态**:字段和迁移已准备就绪,但**创建运单号时写入快照值的逻辑尚未实现**(属于 dev 任务范围)。当前快照列为空,列表仍需 JOIN 订单表。 + +**原则**:运单列表应尽量避免 JOIN `wms_order_delivery`(current/history/dispatch 多表)和 `store` 表,通过快照字段冗余订单关键信息到 `wms_order_express`。 + +**现有快照字段**: + +| 字段 | 快照内容 | 覆盖场景 | +|------|---------|---------| +| `package_material_name_snapshot` | 包材名称 | ✅ 避 JOIN `package_material` | + +**待新增快照字段**(需配合 dev 改造创建运单号逻辑): + +| 快照列 | 类型 | 替代的 JOIN | 写入时机 | +|--------|------|-----------|---------| +| `delivery_order_code` | `VARCHAR(50)` | `order_delivery.delivery_order_code` | 运单号分配成功时(express.js) | +| `store_id_snapshot` | `BIGINT(20) UNSIGNED` | `order_delivery.store_id` | 同上 | +| `store_name_snapshot` | `VARCHAR(128)` | `store.name`(货主表) | 同上 | +| `warehouse_name_snapshot` | `VARCHAR(128)` | `store.name`(仓库表) | 同上 | + +> **迁移文件**:`20260729130000-add-waybill-order-snapshots.js` 已创建但**已回滚**,待 dev 实现写入逻辑后再执行。 + --- ## 三、接口设计 @@ -116,7 +140,7 @@ | 模块名 | `waybill.warehouse` | | 接口路径 | `POST /system`,body 中 `method` 字段为 `waybill.warehouse.{方法名}` | | 请求方式 | 全部 `POST`,参数放在 `body` 内 | -| 鉴权 | 查询类接口需登录但无需鉴权;导出需登录 | +| 鉴权 | 全部接口需登录,暂不做细粒度鉴权 | | 数据隔离 | 按 `warehouse_id` 隔离(仓库侧视角,见 §3.1.1 仓库隔离策略) | | 后续扩展 | 预留 `waybill.store.*`(货主侧,按 `store_id` 隔离),本期不实现 | @@ -207,7 +231,10 @@ POST /system { method: "waybill.warehouse.list", ... } "where": { "waybillCode": "", "mainWaybillCode": "", + "waybillType": "", "orderId": null, + "orderNo": "", + "storeId": null, "logisticsCode": "", "logisticsInterfaceId": null, "platformCode": "", @@ -236,15 +263,17 @@ POST /system { method: "waybill.warehouse.list", ... } | `where` | `object` | ✗ | 筛选条件,所有字段均为可选 | | `where.waybillCode` | `string` | ✗ | 运单号(模糊搜索) | | `where.mainWaybillCode` | `string` | ✗ | **主单号**(精确匹配)。先通过主单号定位 `order_id`,再返回该订单下所有运单(主+子)。与 `waybillCode` 互斥,同时传入时 `mainWaybillCode` 优先 | +| `where.waybillType` | `string` | ✗ | 🆕 **运单类型**:`"main"`/`"1"`=主单号(`business_key=1`),`"child"`/`"2"`=子单号(`business_key>1`) | | `where.orderId` | `number` | ✗ | 订单ID(等值) | -| `where.orderNo` | `string` | ✗ | 订单号(需要 JOIN 订单表后模糊匹配) | +| `where.orderNo` | `string` | ✗ | ⛔ **暂不可用**:订单号(待快照字段 `delivery_order_code` 落库后启用 LIKE 模糊搜索) | +| `where.storeId` | `number` | ✗ | 货主ID(等值,直读 `store_id` 列) | | `where.logisticsCode` | `string` | ✗ | 物流公司编码(等值) | | `where.logisticsInterfaceId` | `number` | ✗ | **物流接口ID**(等值),对应 `wms_order_express.logistics_interface_id`,用于按快递接口筛选运单列表 | | `where.platformCode` | `string` | ✗ | 平台编码(等值),如 PDD/DY/KS/JD/CAINIAO/SPH/XHS | | `where.status` | `number` | ✗ | 运单状态:`0`=未分配,`1`=已分配 | | `where.isBack` | `string` | ✗ | 是否退回:`Y`/`N` | | `where.isIntercept` | `string` | ✗ | 是否拦截:`Y`/`N` | -| `where.isGalaxyReceive` | `string` | ✗ | 是否星河签收:`Y`/`N` | +| `where.isGalaxyReceive` | `string` | ✗ | 是否揽收:`Y`/`N` | | `where.packageMaterialId` | `number` | ✗ | 包材ID(等值) | | `where.hasWeighingWeight` | `boolean` | ✗ | 是否已称重:`true`=weighing_weight>0,`false`=weighing_weight=0 | | `where.keyword` | `string` | ✗ | 关键词:匹配运单号(`waybill_code`)、主单号(`main_waybill_code`)、订单号(需 JOIN) | @@ -286,7 +315,6 @@ POST /system { method: "waybill.warehouse.list", ... } "weighing_weight_display": "1.25 kg", "package_material_id": 5, "package_material_name": "3号纸箱", - "pack_status": "已打包", "print_count": 2, "last_print_at": "2026-07-29 10:30:00", "create_at": "2026-07-29 08:00:00" @@ -310,11 +338,11 @@ POST /system { method: "waybill.warehouse.list", ... } | `main_waybill_code` | `string` | SELF JOIN 同 order 下 `business_key=1` | **主单号**。当 `business_key=1` 时等于 `waybill_code` 本身;当 `business_key>1` 时通过 SELF JOIN 查找同 `order_id` 下 `business_key=1` 的运单号 | | `waybill_type` | `string` | 计算字段 | 运单类型:`business_key=1` → `"主单号"`,`business_key>1` → `"子单号"` | | `order_id` | `number` | `wms_order_express.order_id` | 订单ID | -| `order_no` | `string` | JOIN 订单表 | 订单号(`delivery_order_code`) | +| `order_no` | `string` | JOIN 订单表 | 订单号(`delivery_order_code`)。待快照字段 + 写入逻辑实现后可改为直读 | | `warehouse_id` | `number` | `wms_order_express.warehouse_id` | 仓库ID | -| `warehouse_name` | `string` | JOIN `store` 表 | 仓库名称 | -| `store_id` | `number` | JOIN 订单表 | 货主ID | -| `store_name` | `string` | JOIN `store` 表 | 货主名称 | +| `warehouse_name` | `string` | JOIN `store` 表 | 仓库名称。待快照字段 + 写入逻辑实现后可改为直读 | +| `store_id` | `number` | JOIN 订单表 | 货主ID。待快照字段 + 写入逻辑实现后可改为直读 | +| `store_name` | `string` | JOIN `store` 表 | 货主名称。待快照字段 + 写入逻辑实现后可改为直读 | | `business_key` | `number` | `wms_order_express.business_key` | 拆单序号 | | `status` | `number` | `wms_order_express.status` | 状态:0/1 | | `status_text` | `string` | 前端映射 | 状态文本 | @@ -326,12 +354,11 @@ POST /system { method: "waybill.warehouse.list", ... } | `platform_name` | `string` | 前端映射 | 平台名称 | | `is_back` | `string` | `wms_order_express.is_back` | 是否退回 | | `is_intercept` | `string` | `wms_order_express.is_intercept` | 是否拦截 | -| `is_galaxy_receive` | `string` | `wms_order_express.is_galaxy_receive` | 是否星河签收 | +| `is_galaxy_receive` | `string` | `wms_order_express.is_galaxy_receive` | 是否揽收 | | `weighing_weight` | `number` | `wms_order_express.weighing_weight` | 称重重量(g) | | `weighing_weight_display` | `string` | 格式化 | 称重重量可读展示 | | `package_material_id` | `number` | `wms_order_express.package_material_id` | 包材ID | | `package_material_name` | `string` | `wms_order_express.package_material_name_snapshot` | 包材名称 | -| `pack_status` | `string` | LEFT JOIN `pack_task` | 打包状态("未打包"/"已打包") | | `print_count` | `number` | COUNT `express_print_record` | 打印次数 | | `last_print_at` | `string` | MAX `express_print_record.created_at` | 最近打印时间 | | `create_at` | `string` | `wms_order_express.create_at` | 运单创建时间 | @@ -344,12 +371,13 @@ POST /system { method: "waybill.warehouse.list", ... } 4. **按物流接口ID查询**:直接 `WHERE logistics_interface_id = ?`,等值匹配 5. **订单号模糊搜索**:当 `where.orderNo` 或 `where.keyword` 匹配到非纯数字运单号时,需要 JOIN 订单表(current/history/dispatch)进行 `delivery_order_code LIKE` 匹配 6. **打印次数**:通过子查询或 LEFT JOIN + GROUP BY `express_print_record.express_no = waybill_code` 聚合 -7. **打包状态**:LEFT JOIN `pack_task` ON `waybill_code` -8. **性能注意**:打印次数和打包状态的聚合查询在数据量大时可能成为瓶颈,建议先不做 JOIN,改为按需异步加载(在 detail 接口中返回),list 只返回 `wms_order_express` 原生字段 + 主单号 SELF JOIN +7. **性能注意**:打印次数聚合查询在数据量大时可能成为瓶颈,建议仅在 detail 接口返回 > **性能优化策略**(建议): -> - **方案 A(推荐)**:列表仅查 `wms_order_express` 原生字段,不 JOIN 订单/打印/打包表。`pack_status` 和 `print_count` 通过批量异步查询补充,或仅在 detail 接口返回。 +> - **方案 A(推荐)**:列表仅查 `wms_order_express` 原生字段,不 JOIN 订单/打印/打包表。`print_count` 通过批量异步查询补充,或仅在 detail 接口返回。 > - **方案 B**:列表即 JOIN,但需确保索引覆盖良好。 +> +> **快照字段优化(待实现)**:新增快照列 + 创建运单号时写入快照值后,可彻底去掉订单表和 store 表的 JOIN。迁移文件 `20260729130000-add-waybill-order-snapshots.js` 已就绪,待 dev 实现写入逻辑后执行。 --- @@ -415,11 +443,7 @@ POST /system { method: "waybill.warehouse.list", ... } }, "package": { "package_material_id": 5, - "package_material_name": "3号纸箱", - "pack_status": "已打包", - "pack_quantity": 3, - "pack_at": "2026-07-29 09:15:00", - "packer_name": "张三" + "package_material_name": "3号纸箱" }, "print_records": [ { @@ -528,7 +552,8 @@ POST /system { method: "waybill.warehouse.list", ... } | **预留** | `app/service/systemMethods/waybill/store.js` | 入口层(货主侧):本期不创建,后续按需新增 | | **修改** | `app/service/systems/waybill.js` | 业务层:在现有 `toOrder()` 方法基础上新增 `list()`、`detail()`、`export()` 方法 | | **修改** | `methods/system.json` | 新增 `waybill.warehouse` group,注册 3 个 method 定义 | -| **新增** | `database/migrations/YYYYMMDDHHmmss-add-waybill-list-indexes.js` | 迁移文件:新增 `idx_warehouse_id_status`、`idx_logistics_code`、`idx_logistics_interface_id`、`idx_warehouse_id_create_at` 索引 | +| **新增** | `database/migrations/20260729140000-add-waybill-list-indexes.js` | 迁移文件:新增 4 个索引(✅ 已执行) | +| **新增** | `database/migrations/20260730000000-add-store-id-to-wms-order-express.js` | 迁移文件:新增 `store_id` 货主ID列(✅ 已执行) | --- @@ -538,7 +563,7 @@ POST /system { method: "waybill.warehouse.list", ... } |------|------| | 仓库隔离 | 所有查询自动注入 `warehouse_id = ctx.user.store_id`(系统统一约定),仅返回当前用户所属仓库数据,不可由入参覆盖 | | 只读 | 本模块一期仅提供只读查询,不涉及运单创建/修改/删除 | -| 鉴权 | 查询接口仅需登录,不做细粒度权限校验(与订单列表保持一致) | +| 鉴权 | 全部接口仅需登录,暂不做细粒度权限校验(与订单列表保持一致) | --- @@ -574,6 +599,38 @@ POST /system { method: "waybill.warehouse.list", ... } - [ ] 接口设计是否满足业务需求(运单号独立列表 + 详情) - [x] ~~仓库隔离策略是否正确~~ → 已核实:全系统统一使用 `ctx.user.store_id` 作为 warehouse_id,与现有模式一致 - [ ] 列表字段是否完整(是否需要增减字段) -- [ ] 是否需要 JOIN 订单/打印/打包表(性能 vs 信息完整性权衡) -- [ ] 是否需要新增数据库索引 +- [ ] 快照字段写入逻辑:需在创建运单号(express.js)时同步写入快照列值(dev 任务) +- [ ] 是否需要新增数据库索引(已明确需要,`20260729140000` 已执行) - [ ] 与现有 `index.toOrder`、`order.*` 接口的边界是否清晰 + +### 当前筛选条件(共 18 项,16 可用 + 2 待快照) + +| # | 参数 | 类型 | 匹配 | 状态 | +|---|------|------|------|------| +| — | `warehouse_id` | — | = | ✅ 自动注入 | +| 1 | `waybillCode` | string | LIKE | ✅ | +| 2 | `mainWaybillCode` | string | 精确→order_id | ✅ | +| 3 | `waybillType` | string | `main/1`→bk=1, `child/2`→bk>1 | ✅ 🆕 | +| 4 | `orderId` | number | = | ✅ | +| 5 | `orderNo` | string | LIKE | ⛔ 待快照 | +| 6 | `storeId` | number | = | ✅ 直读 `store_id` | +| 7 | `logisticsCode` | string | = | ✅ | +| 8 | `logisticsInterfaceId` | number | = | ✅ | +| 9 | `platformCode` | string | = | ✅ | +| 10 | `status` | number | = | ✅ | +| 11 | `isBack` | string | = | ✅ | +| 12 | `isIntercept` | string | = | ✅ | +| 13 | `isGalaxyReceive` | string | = | ✅ | +| 14 | `packageMaterialId` | number | = | ✅ | +| 15 | `hasWeighingWeight` | boolean | true→>0, false→=0 | ✅ | +| 16 | `keyword` | string | LIKE waybill_code | ✅ | +| 17 | `createdAtStart` | string YYYY-MM-DD | >= | ✅ | +| 18 | `createdAtEnd` | string YYYY-MM-DD | <= | ✅ | + +### 排序 + +| field | order | 默认 | +|-------|-------|------| +| `create_at` | asc/desc | desc | +| `weighing_weight` | asc/desc | — | +| `id` | asc/desc | — | diff --git a/database/migrations/20260729140000-add-waybill-list-indexes.js b/database/migrations/20260729140000-add-waybill-list-indexes.js new file mode 100644 index 0000000..c5bdef9 --- /dev/null +++ b/database/migrations/20260729140000-add-waybill-list-indexes.js @@ -0,0 +1,84 @@ +'use strict'; + +const TABLE_NAME = 'wms_order_express'; + +/** + * 获取指定表的索引名集合。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @return {Promise>} 索引名集合。 + */ +const getIndexNameSet = async (queryInterface, tableName) => { + const indexes = await queryInterface.showIndex(tableName); + return new Set(indexes.map(index => String(index && index.name ? index.name : '').trim()).filter(Boolean)); +}; + +module.exports = { + /** + * 执行迁移:为运单表新增运单列表高频查询索引(幂等)。 + * + * 新增索引: + * - idx_warehouse_id_status:仓库+状态筛选(最常见查询组合) + * - idx_logistics_code:物流公司筛选 + * - idx_logistics_interface_id:快递接口ID筛选 + * - idx_warehouse_id_create_at:仓库+时间范围排序分页 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface, Sequelize) { + const indexNameSet = await getIndexNameSet(queryInterface, TABLE_NAME); + + if (!indexNameSet.has('idx_warehouse_id_status')) { + await queryInterface.addIndex(TABLE_NAME, { + name: 'idx_warehouse_id_status', + fields: ['warehouse_id', 'status'], + }); + } + + if (!indexNameSet.has('idx_logistics_code')) { + await queryInterface.addIndex(TABLE_NAME, { + name: 'idx_logistics_code', + fields: ['logistics_code'], + }); + } + + if (!indexNameSet.has('idx_logistics_interface_id')) { + await queryInterface.addIndex(TABLE_NAME, { + name: 'idx_logistics_interface_id', + fields: ['logistics_interface_id'], + }); + } + + if (!indexNameSet.has('idx_warehouse_id_create_at')) { + await queryInterface.addIndex(TABLE_NAME, { + name: 'idx_warehouse_id_create_at', + fields: ['warehouse_id', 'create_at'], + }); + } + }, + + /** + * 回滚迁移:移除运单列表查询索引。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface, Sequelize) { + const indexNameSet = await getIndexNameSet(queryInterface, TABLE_NAME); + + if (indexNameSet.has('idx_warehouse_id_status')) { + await queryInterface.removeIndex(TABLE_NAME, 'idx_warehouse_id_status'); + } + if (indexNameSet.has('idx_logistics_code')) { + await queryInterface.removeIndex(TABLE_NAME, 'idx_logistics_code'); + } + if (indexNameSet.has('idx_logistics_interface_id')) { + await queryInterface.removeIndex(TABLE_NAME, 'idx_logistics_interface_id'); + } + if (indexNameSet.has('idx_warehouse_id_create_at')) { + await queryInterface.removeIndex(TABLE_NAME, 'idx_warehouse_id_create_at'); + } + }, +}; diff --git a/database/migrations/20260730000000-add-store-id-to-wms-order-express.js b/database/migrations/20260730000000-add-store-id-to-wms-order-express.js new file mode 100644 index 0000000..b2cab63 --- /dev/null +++ b/database/migrations/20260730000000-add-store-id-to-wms-order-express.js @@ -0,0 +1,49 @@ +'use strict'; + +const TABLE_NAME = 'wms_order_express'; +const COLUMN_NAME = 'store_id'; + +/** + * 获取指定表的列名集合。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @return {Promise>} 列名集合。 + */ +const getColumnNameSet = async (queryInterface, tableName) => { + const columns = await queryInterface.describeTable(tableName); + return new Set(Object.keys(columns)); +}; + +module.exports = { + /** + * 执行迁移:为运单表新增货主ID字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface, Sequelize) { + const existingColumns = await getColumnNameSet(queryInterface, TABLE_NAME); + + if (!existingColumns.has(COLUMN_NAME)) { + await queryInterface.addColumn(TABLE_NAME, COLUMN_NAME, { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '货主ID', + }); + } + }, + + /** + * 回滚迁移:移除运单表的货主ID字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface, Sequelize) { + const existingColumns = await getColumnNameSet(queryInterface, TABLE_NAME); + + if (existingColumns.has(COLUMN_NAME)) { + await queryInterface.removeColumn(TABLE_NAME, COLUMN_NAME); + } + }, +}; diff --git a/database/migrations/20260730160000-backfill-order-express-logistics-code-name.js b/database/migrations/20260730160000-backfill-order-express-logistics-code-name.js new file mode 100644 index 0000000..9d6ccdd --- /dev/null +++ b/database/migrations/20260730160000-backfill-order-express-logistics-code-name.js @@ -0,0 +1,83 @@ +'use strict'; + +/** + * 回填 wms_order_express 表的 logistics_code 和 logistics_name。 + * + * 背景:取号成功后写入 wms_order_express 时引用了不存在的字段 + * listByWarehousePlatformCode.logistics_code / logistics_name, + * 导致 6w+ 条记录该两字段为空。 + * + * 本迁移通过 logistics_interface_id 关联 wms_express_interface.sys_express_code, + * 再通过 wms_express.name 获取快递名称,完成数据回填。 + */ +module.exports = { + async up(queryInterface) { + const [ results ] = await queryInterface.sequelize.query(` + SELECT COUNT(*) AS cnt + FROM wms_order_express oe + JOIN wms_express_interface ei ON oe.logistics_interface_id = ei.id + WHERE (oe.logistics_code IS NULL OR oe.logistics_code = '') + AND ei.sys_express_code IS NOT NULL + AND ei.sys_express_code != '' + `); + + const affectedCount = (results && results[0] && results[0].cnt) || 0; + console.log(`[backfill-order-express-logistics] 预计回填 ${affectedCount} 条记录`); + + if (affectedCount === 0) { + console.log('[backfill-order-express-logistics] 无需回填,跳过'); + return; + } + + await queryInterface.sequelize.query(` + UPDATE wms_order_express oe + JOIN wms_express_interface ei ON oe.logistics_interface_id = ei.id + LEFT JOIN wms_express e ON e.code = ei.sys_express_code + SET + oe.logistics_code = ei.sys_express_code, + oe.logistics_name = COALESCE(e.name, ei.sys_express_code) + WHERE (oe.logistics_code IS NULL OR oe.logistics_code = '') + AND ei.sys_express_code IS NOT NULL + AND ei.sys_express_code != '' + `); + + console.log(`[backfill-order-express-logistics] 成功回填 ${affectedCount} 条记录`); + }, + + async down(queryInterface) { + // 回滚:仅清空通过本迁移回填的记录(条件:logistics_code 等于对应 sys_express_code) + const [ results ] = await queryInterface.sequelize.query(` + SELECT COUNT(*) AS cnt + FROM wms_order_express oe + JOIN wms_express_interface ei ON oe.logistics_interface_id = ei.id + WHERE oe.logistics_code = ei.sys_express_code + AND oe.logistics_code IS NOT NULL + AND oe.logistics_code != '' + AND ei.sys_express_code IS NOT NULL + AND ei.sys_express_code != '' + `); + + const rollbackCount = (results && results[0] && results[0].cnt) || 0; + console.log(`[backfill-order-express-logistics] 预计回滚 ${rollbackCount} 条记录`); + + if (rollbackCount === 0) { + console.log('[backfill-order-express-logistics] 无需回滚,跳过'); + return; + } + + await queryInterface.sequelize.query(` + UPDATE wms_order_express oe + JOIN wms_express_interface ei ON oe.logistics_interface_id = ei.id + SET + oe.logistics_code = '', + oe.logistics_name = '' + WHERE oe.logistics_code = ei.sys_express_code + AND oe.logistics_code IS NOT NULL + AND oe.logistics_code != '' + AND ei.sys_express_code IS NOT NULL + AND ei.sys_express_code != '' + `); + + console.log(`[backfill-order-express-logistics] 成功回滚 ${rollbackCount} 条记录`); + }, +}; diff --git a/database/migrations/20260730170000-add-delivery-order-code-to-wms-order-express.js b/database/migrations/20260730170000-add-delivery-order-code-to-wms-order-express.js new file mode 100644 index 0000000..8514419 --- /dev/null +++ b/database/migrations/20260730170000-add-delivery-order-code-to-wms-order-express.js @@ -0,0 +1,30 @@ +'use strict'; + +/** + * 为 wms_order_express 表新增 delivery_order_code 和 source_order_codes 字段。 + * + * 用途:运单记录需要关联对应的发货单号和原始订单号,便于运单追溯和导出。 + * 字段格式参考 wms_order_delivery 表的同名字段。 + */ +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.addColumn('wms_order_express', 'delivery_order_code', { + type: Sequelize.STRING(50), + allowNull: true, + comment: '发货单号', + after: 'warehouse_id', + }); + + await queryInterface.addColumn('wms_order_express', 'source_order_codes', { + type: Sequelize.TEXT, + allowNull: true, + comment: '来源订单号集合', + after: 'delivery_order_code', + }); + }, + + async down(queryInterface) { + await queryInterface.removeColumn('wms_order_express', 'delivery_order_code'); + await queryInterface.removeColumn('wms_order_express', 'source_order_codes'); + }, +}; diff --git a/database/migrations/20260730200000-backfill-wms-order-express-store-id.js b/database/migrations/20260730200000-backfill-wms-order-express-store-id.js new file mode 100644 index 0000000..401be9e --- /dev/null +++ b/database/migrations/20260730200000-backfill-wms-order-express-store-id.js @@ -0,0 +1,72 @@ +'use strict'; + +const TABLE_NAME = 'wms_order_express'; + +/** + * 回填 wms_order_express.store_id。 + * 从对应的仓库分表(current → history → dispatch)中获取 store_id。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ +async function backfill(queryInterface) { + // 获取所有不同的 warehouse_id + const [warehouses] = await queryInterface.sequelize.query( + `SELECT DISTINCT warehouse_id FROM ${TABLE_NAME} WHERE store_id IS NULL AND warehouse_id IS NOT NULL` + ); + + if (!warehouses || warehouses.length === 0) { + return; + } + + for (const row of warehouses) { + const warehouseId = row.warehouse_id; + const tableTypes = [ + `wms_order_delivery_${warehouseId}`, // current(配送表 / 待处理表) + `wms_order_delivery_${warehouseId}_history`, // history + `wms_order_delivery_${warehouseId}_dispatch`, // dispatch + ]; + + for (const deliveryTable of tableTypes) { + try { + const [result] = await queryInterface.sequelize.query(` + UPDATE ${TABLE_NAME} e + INNER JOIN ${deliveryTable} d ON e.order_id = d.id AND e.warehouse_id = d.warehouse_id + SET e.store_id = d.store_id + WHERE e.store_id IS NULL AND d.store_id IS NOT NULL + `); + console.log(` warehouse=${warehouseId} table=${deliveryTable} rows=${result.info || result}`); + } catch (err) { + // 表可能不存在,跳过 + if (err && err.parent && err.parent.code === 'ER_NO_SUCH_TABLE') { + continue; + } + console.warn(` warehouse=${warehouseId} table=${deliveryTable} error=${err.message}`); + } + } + } +} + +module.exports = { + /** + * 执行迁移:回填 store_id。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface, Sequelize) { + await backfill(queryInterface); + }, + + /** + * 回滚迁移:将 store_id 置为 NULL。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface, Sequelize) { + await queryInterface.sequelize.query( + `UPDATE ${TABLE_NAME} SET store_id = NULL` + ); + }, +}; diff --git a/database/migrations/20260730210000-backfill-order-express-delivery-fields.js b/database/migrations/20260730210000-backfill-order-express-delivery-fields.js new file mode 100644 index 0000000..8736c81 --- /dev/null +++ b/database/migrations/20260730210000-backfill-order-express-delivery-fields.js @@ -0,0 +1,60 @@ +'use strict'; + +const TABLE_NAME = 'wms_order_express'; + +/** + * 回填 wms_order_express 的 delivery_order_code 和 source_order_codes。 + * 从对应的仓库分表(current → history → dispatch)中获取。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ +async function backfill(queryInterface) { + const [warehouses] = await queryInterface.sequelize.query( + `SELECT DISTINCT warehouse_id FROM ${TABLE_NAME} WHERE delivery_order_code IS NULL AND warehouse_id IS NOT NULL` + ); + + if (!warehouses || warehouses.length === 0) { + return; + } + + for (const row of warehouses) { + const warehouseId = row.warehouse_id; + const tableTypes = [ + `wms_order_delivery_${warehouseId}`, + `wms_order_delivery_${warehouseId}_history`, + `wms_order_delivery_${warehouseId}_dispatch`, + ]; + + for (const deliveryTable of tableTypes) { + try { + const [result] = await queryInterface.sequelize.query(` + UPDATE ${TABLE_NAME} e + INNER JOIN ${deliveryTable} d ON e.order_id = d.id AND e.warehouse_id = d.warehouse_id + SET e.delivery_order_code = COALESCE(e.delivery_order_code, d.delivery_order_code), + e.source_order_codes = COALESCE(e.source_order_codes, d.source_order_codes) + WHERE (e.delivery_order_code IS NULL OR e.source_order_codes IS NULL) + AND (d.delivery_order_code IS NOT NULL OR d.source_order_codes IS NOT NULL) + `); + console.log(` warehouse=${warehouseId} table=${deliveryTable} rows=${result.info || result}`); + } catch (err) { + if (err && err.parent && err.parent.code === 'ER_NO_SUCH_TABLE') { + continue; + } + console.warn(` warehouse=${warehouseId} table=${deliveryTable} error=${err.message}`); + } + } + } +} + +module.exports = { + async up(queryInterface, Sequelize) { + await backfill(queryInterface); + }, + + async down(queryInterface, Sequelize) { + await queryInterface.sequelize.query( + `UPDATE ${TABLE_NAME} SET delivery_order_code = NULL, source_order_codes = NULL` + ); + }, +}; From 45b59ea35c29dda3c777f96d02527ead0f48d66d Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sat, 1 Aug 2026 03:44:02 +0800 Subject: [PATCH 139/550] =?UTF-8?q?feat(camera):=20=E6=96=B0=E5=A2=9E?= =?UTF-8?q?=E6=91=84=E5=83=8F=E5=A4=B4=20OSD=20=E5=8F=A0=E5=8A=A0=E5=8A=9F?= =?UTF-8?q?=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 camera model username/password 字段 - 新增 osd_client.js OSD 客户端库 - 工作台打包时自动叠加 OSD 信息到摄像头(带 Redis 缓存去重) - 新增迁移脚本:摄像头用户名密码字段 --- app/lib/osd_client.js | 102 ++++++++++++++++++ app/model/camera.js | 10 ++ app/service/systemMethods/camera.js | 10 +- app/service/systems/camera.js | 71 +++++++++++- app/service/systems/workbench.js | 77 ++++++++++++- ...0730000000-add-camera-username-password.js | 43 ++++++++ 6 files changed, 306 insertions(+), 7 deletions(-) create mode 100644 app/lib/osd_client.js create mode 100644 database/migrations/20260730000000-add-camera-username-password.js diff --git a/app/lib/osd_client.js b/app/lib/osd_client.js new file mode 100644 index 0000000..ac78c33 --- /dev/null +++ b/app/lib/osd_client.js @@ -0,0 +1,102 @@ +'use strict'; + +/** + * OSD(屏幕菜单叠加)客户端模块。 + * 负责组装 RTSP URL 并调用打印服务设置摄像头 OSD 文字叠加。 + * + * 使用方式: + * const osdClient = new (require('../lib/osd_client'))(ctx); + * await osdClient.setOsd({ camera, warehouseId, text, x, y }); + */ +class OsdClient { + constructor(ctx) { + this.ctx = ctx; + this.logger = ctx.logger || console; + } + + /** + * 组装摄像头 RTSP 地址 + * 格式: rtsp://{username}:{password}@{ip}:554/stream{channelId} + * + * @param {Object} camera - 摄像头记录(含 ip/username/password/channel_id) + * @return {string} RTSP URL + */ + buildRtspUrl(camera) { + const ip = camera.ip; + if (!ip) { + throw new Error('摄像头未配置IP地址,无法组装RTSP地址'); + } + + const username = camera.username || 'admin'; + const password = camera.password || ''; + const channelId = camera.channel_id; + const rtspPort = 554; + + return `rtsp://${username}:${password}@${ip}:${rtspPort}/stream${channelId}`; + } + + /** + * 发送 OSD 叠加指令到打印服务 + * + * @param {Object} options - 配置选项 + * @param {Object} options.camera - 摄像头记录 + * @param {Object} [options.server] - 关联的录像服务器(fallback 认证信息) + * @param {number} options.warehouseId - 仓库ID + * @param {string} options.text - OSD 叠加文字 + * @param {number} [options.x] - X 坐标(-1 到 1,默认 -0.9) + * @param {number} [options.y] - Y 坐标(-1 到 1,默认 0.8) + * @return {Promise} 打印服务响应 { status, data, error } + */ + async setOsd(options = {}) { + const { ctx } = this; + const { camera, warehouseId, text, x, y } = options; + + if (!camera) throw new Error('摄像头信息不能为空'); + if (!text) throw new Error('OSD文字不能为空'); + if (warehouseId === undefined || warehouseId === null) throw new Error('仓库ID不能为空'); + + const rtspUrl = this.buildRtspUrl(camera); + const printServiceUrl = ctx.app.config.printService.url; + + const requestData = { + warehouse_id: String(warehouseId), + rtspUrl, + text, + x: x !== undefined ? x : -0.9, + y: y !== undefined ? y : 0.8, + }; + + const targetUrl = `${printServiceUrl}/camera/setOSD`; + ctx.logger.info('[OSD] 发送设置请求', { url: targetUrl, body: requestData }); + + let response = null; + let error = null; + try { + const res = await ctx.curl(targetUrl, { + method: 'POST', + contentType: 'json', + data: requestData, + dataType: 'json', + timeout: 10000, + }); + response = { + status: res.status, + headers: res.headers, + data: res.data, + }; + ctx.logger.info('[OSD] 打印服务回信', { status: res.status, data: res.data }); + } catch (err) { + error = err.message; + ctx.logger.warn('[OSD] 打印服务请求失败', { camera_id: camera.id, error: err.message }); + } + + return { + success: !error && response && response.status >= 200 && response.status < 300, + error, + response, + request: requestData, + }; + } +} + +module.exports = OsdClient; diff --git a/app/model/camera.js b/app/model/camera.js index 755d013..90a7858 100644 --- a/app/model/camera.js +++ b/app/model/camera.js @@ -55,6 +55,16 @@ module.exports = app => { allowNull: true, comment: '码流类型(auto/main/sub)', }, + username: { + type: STRING(100), + allowNull: true, + comment: '摄像头登录用户名', + }, + password: { + type: STRING(100), + allowNull: true, + comment: '摄像头登录密码', + }, custom_name: { type: STRING(100), allowNull: true, diff --git a/app/service/systemMethods/camera.js b/app/service/systemMethods/camera.js index 050c059..bd0aded 100644 --- a/app/service/systemMethods/camera.js +++ b/app/service/systemMethods/camera.js @@ -6,9 +6,9 @@ class CameraService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'list,detail'; + const _noNeedRight = 'list,detail,setOsd'; const _noNeedLog = '*'; - const _noNeedAuth = 'list,detail'; + const _noNeedAuth = 'list,detail,setOsd'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -41,6 +41,12 @@ class CameraService extends MainService { } catch (e) { return this.fail(e.message); } } + async setOsd(data) { + try { + return this.success('设置成功', await this.service.systems.camera.setOsd(data)); + } catch (e) { return this.fail(e.message); } + } + async delete(data) { try { const { id } = data || {}; diff --git a/app/service/systems/camera.js b/app/service/systems/camera.js index 94658ba..dbd9ce9 100644 --- a/app/service/systems/camera.js +++ b/app/service/systems/camera.js @@ -24,10 +24,10 @@ class CameraService extends Service { include: [{ model: ctx.model.CameraServer, as: 'server', - attributes: ['id', 'name', 'brand', 'public_ip', 'internal_ip', 'public_port', 'internal_port', 'status'], + attributes: [ 'id', 'name', 'brand', 'public_ip', 'internal_ip', 'public_port', 'internal_port', 'status' ], required: false, }], - order: [['created_at', 'DESC']], + order: [[ 'created_at', 'DESC' ]], offset: (page - 1) * pageSize, limit: pageSize, }); @@ -42,7 +42,7 @@ class CameraService extends Service { include: [{ model: ctx.model.CameraServer, as: 'server', - attributes: ['id', 'name', 'brand', 'public_ip', 'internal_ip', 'public_port', 'internal_port', 'status'], + attributes: [ 'id', 'name', 'brand', 'public_ip', 'internal_ip', 'public_port', 'internal_port', 'status' ], required: false, }], }); @@ -67,6 +67,8 @@ class CameraService extends Service { model: data.model || null, serial_number: data.serial_number || null, stream_type: data.stream_type || null, + username: data.username || null, + password: data.password || null, custom_name: data.custom_name || null, status: data.status !== undefined ? parseInt(data.status) : 1, remark: data.remark || null, @@ -87,6 +89,8 @@ class CameraService extends Service { if (data.model !== undefined) fields.model = data.model; if (data.serial_number !== undefined) fields.serial_number = data.serial_number; if (data.stream_type !== undefined) fields.stream_type = data.stream_type; + if (data.username !== undefined) fields.username = data.username; + if (data.password !== undefined) fields.password = data.password; if (data.custom_name !== undefined) { if (data.custom_name !== null && String(data.custom_name).trim() === '') { throw new Error('自定义名称不能为空'); @@ -101,6 +105,65 @@ class CameraService extends Service { return record; } + /** + * 设置摄像头 OSD 文字叠加 + * @param {Object} data - 配置选项 + * @param {number} data.id - 摄像头ID + * @param {string} data.text - OSD 叠加文字 + * @param {number} [data.x] - X 坐标(-1 到 1,默认 -0.9) + * @param {number} [data.y] - Y 坐标(-1 到 1,默认 0.8) + * @return {Promise} 打印服务响应 + */ + async setOsd(data) { + const { ctx } = this; + const { id, text, x, y } = data || {}; + const warehouseId = ctx.user.store_id; + + if (!id) throw new Error('摄像头ID不能为空'); + if (!text) throw new Error('OSD叠加文字不能为空'); + + // 查询摄像头及关联服务器 + const camera = await ctx.model.Camera.findOne({ + where: { id: parseInt(id), warehouse_id: warehouseId }, + include: [{ + model: ctx.model.CameraServer, + as: 'server', + attributes: [ 'id', 'name', 'username', 'password', 'public_ip', 'internal_ip' ], + required: false, + }], + }); + if (!camera) throw new Error('摄像头不存在或无权操作'); + + const OsdClient = require('../../lib/osd_client'); + const osdClient = new OsdClient(ctx); + + const result = await osdClient.setOsd({ + camera, + warehouseId, + text, + x, + y, + }); + + if (result.error) { + throw new Error(`打印服务请求失败: ${result.error}`); + } + if (!result.response || result.response.status !== 200) { + const status = result.response ? result.response.status : '无响应'; + const resData = result.response && result.response.data; + const msg = (resData && resData.message) || (resData && typeof resData === 'string' ? resData : '') || '未知错误'; + throw new Error(`打印服务返回异常(${status}): ${msg}`); + } + + return { + camera_id: camera.id, + rtsp_url: result.request.rtspUrl, + osd_text: text, + position: { x: result.request.x, y: result.request.y }, + print_service_response: result.response, + }; + } + async delete(id) { const { ctx } = this; const warehouseId = ctx.user.store_id; @@ -110,7 +173,7 @@ class CameraService extends Service { // 检查是否被工作台绑定 const boundWorkbenches = await ctx.model.Workbench.findAll({ where: { warehouse_id: warehouseId }, - attributes: ['id', 'name'], + attributes: [ 'id', 'name' ], }); for (const wb of boundWorkbenches) { const deviceIds = Array.isArray(wb.device_ids) ? wb.device_ids : []; diff --git a/app/service/systems/workbench.js b/app/service/systems/workbench.js index 1290e90..0b7e3db 100644 --- a/app/service/systems/workbench.js +++ b/app/service/systems/workbench.js @@ -438,7 +438,7 @@ class WorkbenchService extends Service { items_count: itemsCount, items_total: itemsTotal, users: usersParam } = params; - + if (!deliveryOrderCode) throw new Error('发货单号不能为空'); if (!inputWarehouseId) throw new Error('仓库ID不能为空'); @@ -649,6 +649,64 @@ class WorkbenchService extends Service { ctx.logger.info('[Workbench._packOrder] 写入 %d 个打包人员 operatorText=%s', users.length, operatorText); } + // 步骤7.5:下发 OSD 叠加到工作台绑定的摄像头(带 Redis 缓存去重) + const cameraIds = Array.isArray(deviceIds) ? deviceIds : []; + if (cameraIds.length > 0) { + let osdText = ''; + if (isSandan === 1) { + // 散单:用运单号 + const expressRecord = await ctx.model.OrderExpress.findOne({ + where: { order_id: orderId, warehouse_id: warehouseId }, + attributes: ['waybill_code'], + raw: true, + }); + osdText = (expressRecord && expressRecord.waybill_code) || deliveryOrderCode; + } else { + // 团购:波次号+总量 + osdText = `波次${actualWaveNo} 共${totalOrders}单`; + } + + // 写入 OSD 缓存 + try { + const osdCacheKey = `osd_${validWorkbenchId}`; + await this.app.setCacheAsync(osdCacheKey, osdText, 3600); + ctx.logger.info('[Workbench._packOrder] OSD缓存已写入 workbenchId=%d text=%s', + validWorkbenchId, osdText); + } catch (cacheErr) { + ctx.logger.warn('[Workbench._packOrder] OSD缓存写入失败 workbenchId=%d err=%s', + validWorkbenchId, cacheErr.message); + } + + const OsdClient = require('../../lib/osd_client'); + const osdClient = new OsdClient(ctx); + + // 异步下发,不阻塞打包主流程 + Promise.all(cameraIds.map(async cameraId => { + try { + const camera = await ctx.model.Camera.findOne({ + where: { id: cameraId, warehouse_id: warehouseId }, + raw: true, + }); + if (!camera || !camera.ip) return; + + const result = await osdClient.setOsd({ + camera, + warehouseId, + text: osdText, + }); + + if (!result.success) { + ctx.logger.warn('[Workbench._packOrder] OSD下发失败 cameraId=%d error=%s', + cameraId, result.error || '打印服务返回异常'); + } + } catch (err) { + ctx.logger.warn('[Workbench._packOrder] OSD下发异常 cameraId=%d err=%s', cameraId, err.message); + } + })).catch(err => { + ctx.logger.warn('[Workbench._packOrder] OSD批量下发异常 err=%s', err.message); + }); + } + // 步骤8:写入操作日志(散单写单个订单,团购批量写波次所有订单) await this._writePackOperationLog({ warehouseId, @@ -1188,10 +1246,27 @@ class WorkbenchService extends Service { ctx.logger.warn('[Workbench._queryOrder] 查询订单商品失败: %s', itemsErr.message); } + // 步骤5:查询货主备注(从合约表 store_warehouse.store_remask) + let storeRemark = ''; + const storeId = Number(orderRow.store_id || 0); + if (storeId > 0) { + try { + const swRow = await ctx.model.StoreWarehouse.findOne({ + where: { store_id: storeId, warehouse_id: warehouseId }, + attributes: ['store_remask'], + raw: true, + }); + storeRemark = (swRow && swRow.store_remask) ? String(swRow.store_remask).trim() : ''; + } catch (swErr) { + ctx.logger.warn('[Workbench._queryOrder] 查询货主备注失败 storeId=%d: %s', storeId, swErr.message); + } + } + const result = { barcode: normalizedBarcode, waybill_code: waybillCode, isSandan, + store_remark: storeRemark, express: { logistics_name: expressRecord.logistics_name, weighing_weight: expressRecord.weighing_weight, diff --git a/database/migrations/20260730000000-add-camera-username-password.js b/database/migrations/20260730000000-add-camera-username-password.js new file mode 100644 index 0000000..bf89be1 --- /dev/null +++ b/database/migrations/20260730000000-add-camera-username-password.js @@ -0,0 +1,43 @@ +'use strict'; + +const TABLE_NAME = 'wms_camera'; + +/** + * 新增摄像头认证字段:username(用户名)、password(密码)。 + * 用于保存摄像头登录认证信息。 + */ +module.exports = { + up: async (queryInterface, Sequelize) => { + const columns = [ + { + name: 'username', + def: { type: Sequelize.STRING(100), allowNull: true, comment: '摄像头登录用户名', after: 'stream_type' }, + }, + { + name: 'password', + def: { type: Sequelize.STRING(100), allowNull: true, comment: '摄像头登录密码', after: 'username' }, + }, + ]; + + for (const col of columns) { + const tableInfo = await queryInterface.describeTable(TABLE_NAME); + if (!tableInfo[col.name]) { + await queryInterface.addColumn(TABLE_NAME, col.name, col.def); + console.log(`[Migration] wms_camera.${col.name} 已添加`); + } else { + console.log(`[Migration] wms_camera.${col.name} 已存在,跳过`); + } + } + }, + + down: async queryInterface => { + const columns = ['password', 'username']; + for (const col of columns) { + const tableInfo = await queryInterface.describeTable(TABLE_NAME); + if (tableInfo[col]) { + await queryInterface.removeColumn(TABLE_NAME, col); + console.log(`[Migration] wms_camera.${col} 已回滚删除`); + } + } + }, +}; From 3736d306bd8164b29600dba80d416452393e5663 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sat, 1 Aug 2026 03:44:14 +0800 Subject: [PATCH 140/550] =?UTF-8?q?feat(express):=20=E5=BF=AB=E9=80=92?= =?UTF-8?q?=E8=BF=90=E5=8D=95=E5=88=9B=E5=BB=BA=E9=93=BE=E8=B7=AF=E6=94=B9?= =?UTF-8?q?=E9=80=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - order_express model 新增 logistics_code/name/delivery_order_code/source_order_codes/store_id 字段 - express.js 业务层改造:创建运单号时写入快照字段 - express_platform.js 适配新字段 - pendingOrder.js 运单分配+拆子单号改造:支持 dispatch 表查询、已取消订单校验、主单号前置检查、step 4 配送中拆单 --- app/model/order_express.js | 17 +- .../systemMethods/order/pendingOrder.js | 233 ++++++++++++++- app/service/systems/express.js | 267 ++++++++++++++++-- app/service/systems/express_platform.js | 98 +++++-- 4 files changed, 557 insertions(+), 58 deletions(-) diff --git a/app/model/order_express.js b/app/model/order_express.js index 383fed1..6a440d8 100644 --- a/app/model/order_express.js +++ b/app/model/order_express.js @@ -39,7 +39,7 @@ module.exports = app => { is_galaxy_receive: { type: ENUM('Y', 'N'), allowNull: true, - comment: '是否星河签收', + comment: '是否揽收', }, is_back: { type: ENUM('Y', 'N'), @@ -122,6 +122,21 @@ module.exports = app => { allowNull: true, comment: '仓库ID', }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '货主ID', + }, + delivery_order_code: { + type: STRING(50), + allowNull: true, + comment: '发货单号', + }, + source_order_codes: { + type: TEXT, + allowNull: true, + comment: '来源订单号集合', + }, package_material_id: { type: BIGINT(20).UNSIGNED, allowNull: true, diff --git a/app/service/systemMethods/order/pendingOrder.js b/app/service/systemMethods/order/pendingOrder.js index c8cb73a..3e02550 100644 --- a/app/service/systemMethods/order/pendingOrder.js +++ b/app/service/systemMethods/order/pendingOrder.js @@ -2015,6 +2015,12 @@ class PendingOrderService extends OrderBaseService { }; await this.setAllocateExpressTaskProgress(taskId, taskPayload); + // 捕获 warehouseId 供 setImmediate 异步回调使用, + // 避免 Qimen 等链路中 withPatchedCtxUser 补丁已撤销导致 getCurrentWarehouseId() 返回 0。 + const capturedWarehouseId = Number( + this.ctx && this.ctx.user && this.ctx.user.store_id || 0 + ); + // 后台异步执行 setImmediate(async () => { try { @@ -2026,6 +2032,7 @@ class PendingOrderService extends OrderBaseService { const result = await service.systems.express.createWaybillCodePipeline(orders, { awaitTasks: true, + warehouseId: capturedWarehouseId, }); await this.setAllocateExpressTaskProgress(taskId, { @@ -5703,7 +5710,7 @@ class PendingOrderService extends OrderBaseService { const where = this.buildOrderWhere([ orderId ], warehouseId); const order = await model.findOne({ where, - attributes: [ 'id', 'step', 'outbound_status', 'warehouse_id', 'store_id' ], + attributes: [ 'id', 'step', 'outbound_status', 'warehouse_id', 'store_id', 'sys_logistics_code', 'sys_logistics_name', 'delivery_order_code', 'source_order_codes' ], raw: true, }); @@ -5758,7 +5765,12 @@ class PendingOrderService extends OrderBaseService { order_id: orderId, waybill_code: waybillCode, logistics_interface_name: logisticsInterfaceName, + logistics_code: String(order.sys_logistics_code || '').trim() || null, + logistics_name: String(order.sys_logistics_name || '').trim() || null, + delivery_order_code: String(order.delivery_order_code || '').trim() || null, + source_order_codes: String(order.source_order_codes || '').trim() || null, warehouse_id: Number(order.warehouse_id) || warehouseId, + store_id: order.store_id != null ? Number(order.store_id) : null, business_key: nextBusinessKey, status: 1, create_at: new Date(), @@ -5959,25 +5971,40 @@ class PendingOrderService extends OrderBaseService { throw new Error('sub_order_count 必须为正整数且 >= 1'); } - // 2. 查询订单并校验状态(待处理:step in [1,2,3] 且 outbound_status != 'padding') - const model = await this.getOrderModel('order', warehouseId); + // 2. 查询订单并校验状态 + // 先查 current 表;若不存在再查 dispatch 表(配送中订单可能已被定时任务迁移到 dispatch) + let model = await this.getOrderModel('order', warehouseId); const where = this.buildOrderWhere([ orderId ], warehouseId); - const order = await model.findOne({ + let order = await model.findOne({ where, - attributes: [ 'id', 'step', 'outbound_status', 'warehouse_id', 'store_id', 'sys_platform_code', 'logistics_code', 'sys_platform_name', 'logistics_name' ], + attributes: [ 'id', 'step', 'outbound_status', 'warehouse_id', 'store_id', 'sys_platform_code', 'logistics_code', 'sys_platform_name', 'logistics_name', 'status' ], raw: true, }); + if (!order) { + model = await this.getOrderModelByTableType('dispatch', warehouseId); + order = await model.findOne({ + where, + attributes: [ 'id', 'step', 'outbound_status', 'warehouse_id', 'store_id', 'sys_platform_code', 'logistics_code', 'sys_platform_name', 'logistics_name', 'status' ], + raw: true, + }); + } + if (!order) { throw new Error(`订单 ${orderId} 不存在或不属于当前仓库`); } - const allowedSteps = new Set([ 1, 2, 3 ]); - if (!allowedSteps.has(order.step)) { - throw new Error(`订单 ${orderId} 当前步骤为 ${order.step},仅允许待处理状态(step 1/2/3)的订单分配子单号`); + if (order.status === PENDING_CANCEL_STATUS) { + throw new Error(`订单 ${orderId} 已取消,不允许分配子单号`); } - if (order.outbound_status === PENDING_OUTBOUND_STATUS) { + const allowedSteps = new Set([ 1, 2, 3, 4 ]); + if (!allowedSteps.has(order.step)) { + throw new Error(`订单 ${orderId} 当前步骤为 ${order.step},仅允许待处理(step 1/2/3)或配送中(step 4)的订单分配子单号`); + } + + // 仅待处理阶段(step 1/2/3)校验 outbound_status;配送中(step 4)不校验 + if (order.step !== 4 && order.outbound_status === PENDING_OUTBOUND_STATUS) { throw new Error(`订单 ${orderId} 已标记待出库,不允许分配子单号`); } @@ -5987,13 +6014,28 @@ class PendingOrderService extends OrderBaseService { throw new Error('OrderExpress 模型未加载'); } + // 3.1 校验主单号:必须已有 business_key=1 且 status=1 的主单号,才能拆子单号 + const { Op } = this.app.Sequelize; + const mainWaybill = await orderExpressModel.findOne({ + where: { + order_id: orderId, + warehouse_id: Number(order.warehouse_id) || warehouseId, + business_key: 1, + status: 1, + }, + attributes: [ 'id' ], + raw: true, + }); + if (!mainWaybill) { + throw new Error(`订单 ${orderId} 尚未分配主单号,请先分配主单号后再拆子单号`); + } + const businessKeys = []; for (let i = 0; i < subOrderCount; i++) { businessKeys.push(2 + i); } // 4. 预查已有的已分配运单号(status=1),仅用于初始 details 展示与全部跳过优化 - const { Op } = this.app.Sequelize; const existingCompleted = await orderExpressModel.findAll({ where: { order_id: orderId, @@ -6074,6 +6116,7 @@ class PendingOrderService extends OrderBaseService { sys_platform_name: order.sys_platform_name, logistics_name: order.logistics_name, store_id: order.store_id, + warehouse_id: Number(order.warehouse_id) || warehouseId, })); const pipelineResult = await this.service.systems.express.createWaybillCodePipeline( @@ -6100,6 +6143,19 @@ class PendingOrderService extends OrderBaseService { details: updatedDetails, }, }); + + // 写入操作日志(成功) + try { + await this.writeAllocateSubOrderLog(orderId, orderWarehouseId, { + action: isPartial ? 'SUCCESS_PARTIAL' : 'SUCCESS', + subOrderCount: businessKeys.length, + successCount, + details: updatedDetails, + }); + } catch (logErr) { + this.ctx.logger.warn('[pendingOrder.allocateSubOrderNumber] 写入成功操作日志失败: %s', + logErr && logErr.message ? logErr.message : logErr); + } } catch (error) { const errorMessage = error && error.message ? error.message : String(error); @@ -6110,6 +6166,25 @@ class PendingOrderService extends OrderBaseService { message: '子单号分配失败', error: errorMessage, }); + + // 写错误信息到 order_flag(尝试 current 和 dispatch 两张表) + try { + await this.writeAllocateSubOrderErrorFlag(orderId, orderWarehouseId, errorMessage); + } catch (flagErr) { + this.ctx.logger.warn('[pendingOrder.allocateSubOrderNumber] 写入 order_flag 失败: %s', + flagErr && flagErr.message ? flagErr.message : flagErr); + } + + // 写入操作日志(失败) + try { + await this.writeAllocateSubOrderLog(orderId, orderWarehouseId, { + action: 'FAILED', + errorMessage, + }); + } catch (logErr) { + this.ctx.logger.warn('[pendingOrder.allocateSubOrderNumber] 写入失败操作日志失败: %s', + logErr && logErr.message ? logErr.message : logErr); + } } }); @@ -6119,6 +6194,106 @@ class PendingOrderService extends OrderBaseService { }); } + /** + * 写入子单号分配的 order_flag 错误信息。 + * 尝试更新 current 和 dispatch 两张表,任一成功即返回。 + * + * @param {number} orderId 订单ID。 + * @param {number} warehouseId 仓库ID。 + * @param {string} errorMessage 错误信息。 + * @return {Promise} 无返回值。 + */ + async writeAllocateSubOrderErrorFlag(orderId, warehouseId, errorMessage) { + const flag = `[子单号分配失败] ${errorMessage}`.substring(0, 500); + const where = this.buildOrderWhere([ orderId ], warehouseId); + const updatePayload = { order_flag: flag, updated_at: new Date() }; + + // 尝试 current 表 + try { + const currentModel = await this.getOrderModel('order', warehouseId); + if (currentModel && typeof currentModel.update === 'function') { + const [ affected ] = await currentModel.update(updatePayload, { where }); + if (Number(affected) > 0) return; + } + } catch (err) { + this.ctx.logger.warn('[pendingOrder.allocateSubOrderNumber] current 表写入 order_flag 失败: %s', + err && err.message ? err.message : err); + } + + // 尝试 dispatch 表 + try { + const dispatchModel = await this.getOrderModelByTableType('dispatch', warehouseId); + if (dispatchModel && typeof dispatchModel.update === 'function') { + await dispatchModel.update(updatePayload, { where }); + } + } catch (err) { + this.ctx.logger.warn('[pendingOrder.allocateSubOrderNumber] dispatch 表写入 order_flag 失败: %s', + err && err.message ? err.message : err); + } + } + + /** + * 写入子单号分配的操作日志。 + * + * @param {number} orderId 订单ID。 + * @param {number} warehouseId 仓库ID。 + * @param {Object} opts 日志详情。 + * @param {string} opts.action 操作动作(SUCCESS/SUCCESS_PARTIAL/FAILED)。 + * @param {number} [opts.subOrderCount] 子单总数。 + * @param {number} [opts.successCount] 成功数。 + * @param {string} [opts.errorMessage] 错误信息。 + * @param {Array} [opts.details] 分配详情。 + * @return {Promise} 无返回值。 + */ + async writeAllocateSubOrderLog(orderId, warehouseId, opts = {}) { + const operator = this.getOrderLogOperator(); + const logWarehouseId = this.getOrderLogWarehouseId(warehouseId); + const now = new Date(); + + // 状态中文映射 + const STATUS_CN = { allocated: '成功', failed: '失败', skipped: '跳过', pending: '处理中' }; + const detailSummary = Array.isArray(opts.details) + ? opts.details.slice(0, 10).map(d => { + const cn = STATUS_CN[d.status] || d.status; + let seg = `子单${d.business_key}:${cn}`; + if (d.status === 'failed' && d.note) { + seg += `(${d.note})`; + } + return seg; + }).join(', ') + : ''; + + let message = `子单号分配${opts.action === 'FAILED' ? '失败' : '完成'}`; + if (opts.action === 'SUCCESS_PARTIAL') { + message = `子单号分配部分完成(${opts.successCount}/${opts.subOrderCount})`; + } + if (opts.errorMessage) { + message += ` - ${opts.errorMessage}`; + } + if (detailSummary) { + message += ` | ${detailSummary}`; + } + + const logRow = { + business_type: 'order', + business_id: String(orderId), + operation_code: '子单号分配', + operator_id: operator.id, + operator_name: operator.name, + external_log_type: 'NONE', + warehouse_id: logWarehouseId || null, + platform_code: 'SYSTEM', + message: message.substring(0, 1000), + created_at: now, + }; + + if (this.ctx.model && this.ctx.model.OperationLog) { + await this.ctx.model.OperationLog.create(logRow); + } else if (this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.operationLog) { + await this.ctx.service.systems.operationLog.createOperationLog(logRow); + } + } + /** * 查询子单号分配任务进度。 * @@ -6299,6 +6474,37 @@ class PendingOrderService extends OrderBaseService { } } + // 兜底:如果 order_express 中一条记录都没有,尝试从订单表的 order_flag 获取异常信息 + let orderFlagNote = ''; + if (recordMap.size === 0) { + try { + const orderWhere = this.buildOrderWhere([ orderId ], warehouseId); + // 查 current 表 + let orderModel = await this.getOrderModel('order', warehouseId); + let orderRow = await orderModel.findOne({ + where: orderWhere, + attributes: [ 'order_flag' ], + raw: true, + }); + // 查 dispatch 表兜底 + if (!orderRow) { + orderModel = await this.getOrderModelByTableType('dispatch', warehouseId); + orderRow = await orderModel.findOne({ + where: orderWhere, + attributes: [ 'order_flag' ], + raw: true, + }); + } + if (orderRow && orderRow.order_flag) { + orderFlagNote = `(订单异常: ${String(orderRow.order_flag).trim()})`; + } + } catch (err) { + // 查 order_flag 失败不影响主流程 + this.ctx.logger.warn('[pendingOrder.buildSubOrderDetails] 查询 order_flag 失败: %s', + err && err.message ? err.message : err); + } + } + return businessKeys.map(bk => { const record = recordMap.get(bk); if (record && Number(record.status) === 1 && String(record.waybill_code || '').trim()) { @@ -6319,11 +6525,12 @@ class PendingOrderService extends OrderBaseService { }; } + const baseNote = '未找到分配的运单记录'; return { business_key: bk, status: 'failed', waybill_code: null, - note: '未找到分配的运单记录', + note: orderFlagNote ? `${baseNote}${orderFlagNote}` : baseNote, }; }); } @@ -6364,7 +6571,7 @@ class PendingOrderService extends OrderBaseService { const now = new Date(); const buildWhere = () => ({ - step: { [Op.in]: [1, 2, 3] }, + step: { [Op.in]: [ 1, 2, 3 ] }, status: { [Op.ne]: 'cancel' }, print_status: { [Op.ne]: 'fin' }, }); @@ -6384,7 +6591,7 @@ class PendingOrderService extends OrderBaseService { // 2. 查询 current 表中已存在的订单 ID,计算出未命中的 ID const currentFoundRows = await currentModel.findAll({ - attributes: ['id'], + attributes: [ 'id' ], where: this.buildOrderWhere(orderIds, warehouseId), raw: true, }); diff --git a/app/service/systems/express.js b/app/service/systems/express.js index 02d2439..63d6f81 100644 --- a/app/service/systems/express.js +++ b/app/service/systems/express.js @@ -635,6 +635,10 @@ class ExpressService extends Service { status: { [Op.ne]: 'cancel', }, + // 保护配送中(step=4)订单不被回退为异常状态 + step: { + [Op.ne]: 4, + }, }, transaction, }); @@ -658,6 +662,76 @@ class ExpressService extends Service { } } + /** + * 补写 dispatch 表订单的 order_flag 异常信息。 + * dispatch 表中的配送中订单(step=4)不应回退 step,仅记录异常标记。 + * + * @param {Array} dispatchOrderDeliveryRows dispatch 表中的订单行。 + * @param {Map>} failedOrdersByReason 失败原因与订单 ID 映射。 + * @param {Object} transaction 数据库事务。 + * @return {Promise} 无返回值。 + */ + async writeDispatchOrderFlags(dispatchOrderDeliveryRows = [], failedOrdersByReason = new Map(), transaction) { + if (!failedOrdersByReason || typeof failedOrdersByReason.forEach !== 'function') { + return; + } + + const { Op } = this.app.Sequelize; + const dispatchOrderIdSet = new Set( + (Array.isArray(dispatchOrderDeliveryRows) ? dispatchOrderDeliveryRows : []) + .map(row => Number(row && row.id)) + .filter(id => Number.isFinite(id) && id > 0) + ); + + if (dispatchOrderIdSet.size === 0) { + return; + } + + this.ctx.logger.info('[ExpressService.writeDispatchOrderFlags] 入口 dispatchOrderIds=%s failedReasons=%d', + Array.from(dispatchOrderIdSet).join(','), failedOrdersByReason.size); + + // 找到同时属于 dispatch 表且失败的订单 + const dispatchFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; + if (!dispatchFactory || typeof dispatchFactory.getDispatchModel !== 'function') { + this.ctx.logger.warn('[ExpressService.writeDispatchOrderFlags] dispatchFactory 不可用'); + return; + } + + const currentWarehouseId = this.getCurrentWarehouseId(); + if (!currentWarehouseId) return; + + for (const [ exceptionText, orderIds ] of failedOrdersByReason.entries()) { + const failedDispatchIds = (Array.isArray(orderIds) ? orderIds : []) + .map(id => Number(id)) + .filter(id => dispatchOrderIdSet.has(id)); + + if (failedDispatchIds.length === 0) continue; + + this.ctx.logger.info('[ExpressService.writeDispatchOrderFlags] 准备写入 order_flag: ids=%s reason=%s', + failedDispatchIds.join(','), exceptionText); + + try { + const dispatchModel = await dispatchFactory.getDispatchModel(currentWarehouseId); + if (dispatchModel && typeof dispatchModel.update === 'function') { + await dispatchModel.update({ + order_flag: exceptionText, + updated_at: new Date(), + }, { + where: { + id: { [Op.in]: failedDispatchIds }, + status: { [Op.ne]: 'cancel' }, + }, + transaction, + }); + this.ctx.logger.info('[ExpressService.writeDispatchOrderFlags] 写入成功 ids=%s', failedDispatchIds.join(',')); + } + } catch (err) { + this.ctx.logger.warn('[ExpressService.writeDispatchOrderFlags] 写入 dispatch order_flag 失败: %s', + err && err.message ? err.message : err); + } + } + } + /** * 将运单异步后处理失败订单批量回写为错误状态。 * @@ -703,6 +777,10 @@ class ExpressService extends Service { status: { [Op.ne]: 'cancel', }, + // 保护配送中(step=4)订单不被回退为异常状态 + step: { + [Op.ne]: 4, + }, }, }); } @@ -2342,6 +2420,7 @@ class ExpressService extends Service { * @param {Object} [options] 可选配置。 * @param {boolean} [options.awaitTasks=false] 是否等待所有异步任务完成后再返回。 * @param {Function} [options.onBatchComplete] 单批完成回调 ({ processed, total })。 + * @param {number} [options.warehouseId] 仓库ID覆盖值,用于 setImmediate 等异步上下文中 ctx.user 不可用的场景。 * @return {Promise} 处理结果,包含 orders、waybill_codes 和 skippedOrders。 */ async createWaybillCodePipeline(orders = [], options = {}) { @@ -2358,7 +2437,7 @@ class ExpressService extends Service { waveIds: orderList.slice(0, 50).map(order => Number(order && order.wave_id)).filter(waveId => Number.isFinite(waveId) && waveId > 0), }); - const warehouseId = this.getCurrentWarehouseId(); + const warehouseId = Number(options.warehouseId) > 0 ? Number(options.warehouseId) : this.getCurrentWarehouseId(); const orderDeliveryModel = await this.getWaybillAsyncOrderDeliveryModel(warehouseId); @@ -2370,23 +2449,52 @@ class ExpressService extends Service { throw new Error('订单主表模型未初始化'); } - // 【step1】先按订单ID和业务键筛选 wms_order_express,找出已存在的快递记录,避免重复创建。 - const orders_arr = await orderDeliveryModel.findAll({ + // 【step1】先按订单ID和业务键筛选,找出已存在的快递记录,避免重复创建。 + // 先从 current 表查;若存在未覆盖的 order_id,再从 dispatch 表补查(配送中订单可能已迁移) + const inputOrderIds = orderList.map(order => Number(order && order.order_id)).filter(orderId => Number.isFinite(orderId) && orderId > 0); + const currentOrders = await orderDeliveryModel.findAll({ where: { - id: orderList.map(order => Number(order && order.order_id)).filter(orderId => Number.isFinite(orderId) && orderId > 0), + id: inputOrderIds, warehouse_id: warehouseId, step: { - [Op.in]: [ 1, 2, 3 ], + [Op.in]: [ 1, 2, 3, 4 ], }, }, attributes: [ 'id', 'sys_platform_code', 'logistics_code', 'sys_platform_name', 'logistics_name', 'store_id' ], raw: true, }); + + // 补查 dispatch 表:获取 current 表未覆盖的 order_id + const currentCoveredIds = new Set((Array.isArray(currentOrders) ? currentOrders : []).map(o => Number(o.id))); + const uncoveredIds = inputOrderIds.filter(id => !currentCoveredIds.has(id)); + let dispatchOrders = []; + if (uncoveredIds.length > 0) { + const dispatchModel = this.ctx.model && this.ctx.model.OrderDeliveryFactory + ? await this.ctx.model.OrderDeliveryFactory.getDispatchModel(warehouseId) + : null; + if (dispatchModel && typeof dispatchModel.findAll === 'function') { + dispatchOrders = await dispatchModel.findAll({ + where: { + id: uncoveredIds, + warehouse_id: warehouseId, + step: { + [Op.in]: [ 4 ], + }, + }, + attributes: [ 'id', 'sys_platform_code', 'logistics_code', 'sys_platform_name', 'logistics_name', 'store_id' ], + raw: true, + }); + } + } + + const orders_arr = [ ...(Array.isArray(currentOrders) ? currentOrders : []), ...dispatchOrders ]; this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 订单筛选结果', { traceId, warehouseId, inputOrderCount: orderList.length, - matchedOrderCount: Array.isArray(orders_arr) ? orders_arr.length : 0, + currentCount: (Array.isArray(currentOrders) ? currentOrders : []).length, + dispatchCount: dispatchOrders.length, + matchedOrderCount: orders_arr.length, }); // 【step1.5】过滤已分配运单号(status=1)且传入 business_key=1 的订单,避免重复分配。 @@ -2438,14 +2546,26 @@ class ExpressService extends Service { return { message: '所有订单均已分配运单号,无需处理' }; } - // orders_arr和orderList合并 - const ordersWithExpress = filteredOrdersArr.map(order => { - const matchedExpress = orderList.find(express => Number(order.id) === Number(express.order_id)); - return { - ...order, - business_key: matchedExpress ? matchedExpress.business_key : 1, - }; - }); + // orders_arr和orderList合并:同一 order_id 在 orderList 中可能有多条(不同 business_key), + // 需要展开为多条 ordersWithExpress,不能用 find() 只取第一条 + const ordersWithExpress = []; + for (const order of filteredOrdersArr) { + const matchingExpresses = orderList.filter(express => Number(order.id) === Number(express.order_id)); + if (matchingExpresses.length > 0) { + for (const express of matchingExpresses) { + ordersWithExpress.push({ + ...order, + business_key: express.business_key || 1, + }); + } + } else { + // 兜底:orderList 中无对应记录,business_key 默认为 1 + ordersWithExpress.push({ + ...order, + business_key: 1, + }); + } + } const platformList = await this.service.systems.platform.getPlatformList(true, true); const printPlatformCodeMap = await this.loadWaybillPrintPlatformCodeMap(platformList); const requestPlatformCodeMap = await this.loadWaybillAsyncRequestPlatformCodeMap(platformList); @@ -2750,7 +2870,69 @@ class ExpressService extends Service { include: orderDeliveryInclude, transaction, }); - const orderDeliveryMap = this.buildWaybillOrderDeliveryMap(orderDeliveryRows); + + // 补查 dispatch 表:配送中订单可能已迁移,current 表未覆盖的从 dispatch 补齐 + const currentCoveredOrderIds = new Set( + (Array.isArray(orderDeliveryRows) ? orderDeliveryRows : []).map(row => Number(row && row.id)) + ); + const uncoveredOrderIds = normalizedOrders + .map(o => o.order_id) + .filter(id => !currentCoveredOrderIds.has(id)); + let dispatchOrderDeliveryRows = []; + if (uncoveredOrderIds.length > 0) { + ctx.logger.info('[ExpressService.createWaybillCode] dispatch 补查 uncoveredOrderIds=%s', + [ ...new Set(uncoveredOrderIds) ].join(',')); + const dispatchModel = orderDeliveryFactory && typeof orderDeliveryFactory.getDispatchModel === 'function' + ? await orderDeliveryFactory.getDispatchModel(currentWarehouseId) + : null; + if (dispatchModel && typeof dispatchModel.findAll === 'function') { + // dispatch 表 items 关联可能不同,去掉 include 避免关联查询报错 + dispatchOrderDeliveryRows = await dispatchModel.findAll({ + attributes: WAYBILL_ORDER_DELIVERY_MIN_ATTRIBUTES, + where: { + id: { [Op.in]: uncoveredOrderIds }, + }, + transaction, + }); + ctx.logger.info('[ExpressService.createWaybillCode] dispatch 补查结果 count=%d', + dispatchOrderDeliveryRows.length); + + // 补查 dispatch 表的商品明细(物流 API 需要 items 信息) + if (dispatchOrderDeliveryRows.length > 0) { + const dispatchItemsFactory = ctx.model && ctx.model.OrderItemsFactory; + const dispatchItemsModel = dispatchItemsFactory && typeof dispatchItemsFactory.getDispatchModel === 'function' + ? await dispatchItemsFactory.getDispatchModel(currentWarehouseId) + : null; + if (dispatchItemsModel && typeof dispatchItemsModel.findAll === 'function') { + const dispatchOrderIds = dispatchOrderDeliveryRows.map(row => Number(row.id)).filter(id => id > 0); + const dispatchItems = await dispatchItemsModel.findAll({ + where: { order_id: { [Op.in]: dispatchOrderIds } }, + attributes: [ 'id', 'order_id', 'item_code', 'item_name', 'plan_qty', 'source_order_code' ], + raw: true, + transaction, + }); + // 将 items 以 Sequelize include 格式附加到 dispatch 行上 + if (Array.isArray(dispatchItems) && dispatchItems.length > 0) { + const itemsByOrderId = new Map(); + for (const item of dispatchItems) { + const oid = Number(item.order_id); + if (!itemsByOrderId.has(oid)) itemsByOrderId.set(oid, []); + itemsByOrderId.get(oid).push(item); + } + for (const row of dispatchOrderDeliveryRows) { + const oid = Number(row.id); + row.orderItems = itemsByOrderId.get(oid) || []; + } + } + } + } + } else { + ctx.logger.warn('[ExpressService.createWaybillCode] dispatch 模型不可用'); + } + } + + const allOrderDeliveryRows = [ ...(Array.isArray(orderDeliveryRows) ? orderDeliveryRows : []), ...dispatchOrderDeliveryRows ]; + const orderDeliveryMap = this.buildWaybillOrderDeliveryMap(allOrderDeliveryRows); const existingCompletedRows = await orderExpressModel.findAll({ where: { @@ -2787,7 +2969,7 @@ class ExpressService extends Service { const { relationGroupMap, missingOrderIds, - } = this.buildWaybillCreateRelationGroups(pendingOrders, orderDeliveryRows, currentWarehouseId); + } = this.buildWaybillCreateRelationGroups(pendingOrders, allOrderDeliveryRows, currentWarehouseId); const relationWhereList = Array.from(relationGroupMap.values()).map(group => ({ store_id: group.store_id, @@ -2828,6 +3010,16 @@ class ExpressService extends Service { // 【step5】事务内统一回写失败订单异常,避免成功与失败状态分离。 await this.writeWaybillOrderExceptions(orderDeliveryModel, failedOrdersByReason, transaction); + // 补写 dispatch 表 order_flag:dispatch 订单的异常信息需单独写(current 表写不到) + if (dispatchOrderDeliveryRows.length > 0 && failedOrdersByReason.size > 0) { + try { + await this.writeDispatchOrderFlags(dispatchOrderDeliveryRows, failedOrdersByReason, transaction); + } catch (dispatchFlagErr) { + ctx.logger.warn('[ExpressService.createWaybillCode] 补写 dispatch order_flag 失败: %s', + dispatchFlagErr && dispatchFlagErr.message ? dispatchFlagErr.message : dispatchFlagErr); + } + } + if (balanceWarnings.length > 0) { ctx.logger.warn('[ExpressService.createWaybillCode] 余额不足但允许超额分配: %s', balanceWarnings.join(';')); } @@ -2896,17 +3088,28 @@ class ExpressService extends Service { .filter(orderId => Number.isFinite(orderId) && orderId > 0))); if (successOrderIds.length > 0) { - await orderDeliveryModel.update({ - step: 2, - updated_at: new Date(), - }, { - where: { - id: { - [Op.in]: successOrderIds, + // 仅对非配送中(step != 4)的订单更新 step 为 2;配送中订单保持 step 不变 + const step4OrderIdSet = new Set(); + for (const orderId of successOrderIds) { + const orderRow = orderDeliveryMap.get(orderId); + if (orderRow && Number(orderRow.step) === 4) { + step4OrderIdSet.add(orderId); + } + } + const stepUpdatableIds = successOrderIds.filter(id => !step4OrderIdSet.has(id)); + if (stepUpdatableIds.length > 0) { + await orderDeliveryModel.update({ + step: 2, + updated_at: new Date(), + }, { + where: { + id: { + [Op.in]: stepUpdatableIds, + }, }, - }, - transaction, - }); + transaction, + }); + } } } @@ -2931,12 +3134,24 @@ class ExpressService extends Service { continue; } + ctx.logger.info('[DEBUG] rowsToCreate order', JSON.stringify({ + order_id: order.order_id, + store_id: order.store_id, + has_delivery: !!order.order_delivery, + delivery_store_id: order.order_delivery && order.order_delivery.store_id, + delivery_doc: order.order_delivery && order.order_delivery.delivery_order_code, + })); + rowsToCreate.push({ order_id: order.order_id, business_key: order.business_key, status: 0, retry_count: 0, warehouse_id: this.getCurrentWarehouseId(), + store_id: order.store_id || null, + logistics_code: (listByWarehousePlatformCode && listByWarehousePlatformCode.sys_express_code) || '', + delivery_order_code: (orderDeliveryMap.get(order.order_id) && orderDeliveryMap.get(order.order_id).delivery_order_code) || null, + source_order_codes: (orderDeliveryMap.get(order.order_id) && orderDeliveryMap.get(order.order_id).source_order_codes) || null, }); } diff --git a/app/service/systems/express_platform.js b/app/service/systems/express_platform.js index 72c3eea..bc5871f 100644 --- a/app/service/systems/express_platform.js +++ b/app/service/systems/express_platform.js @@ -614,6 +614,17 @@ class ExpressPlatformService extends MainService { }, }); const ExpressList = await this.service.systems.express.loadExpressList(); + const sysExpressName = (ExpressList.find(item => item.code === listByWarehousePlatformCode.sys_express_code) || {}).name || ''; + const orderDataMap = new Map(); + for (const order_tmp of normalizedOrders) { + const od = order_tmp && order_tmp.order_delivery; + if (!od) continue; + orderDataMap.set(`${od.id}_${order_tmp.business_key}`, { + delivery_order_code: od.delivery_order_code || '', + source_order_codes: od.source_order_codes || '', + store_id: od.store_id || 0, + }); + } const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; const allocatedWaybillMap = new Map(); if (orderExpressModel && typeof orderExpressModel.findAll === 'function') { @@ -943,9 +954,12 @@ class ExpressPlatformService extends MainService { encryptprintinfo: item.encryptprintinfo, ...this.buildOrderExpressVerPatch([ item.ver ]), create_at: new Date(), - logistics_code: listByWarehousePlatformCode.logistics_code || '', + delivery_order_code: orderDataMap.get(`${order_id}_${business_key}`)?.delivery_order_code || null, + source_order_codes: orderDataMap.get(`${order_id}_${business_key}`)?.source_order_codes || null, + store_id: orderDataMap.get(`${order_id}_${business_key}`)?.store_id || null, + logistics_code: listByWarehousePlatformCode.sys_express_code || '', logistics_interface_id: listByWarehousePlatformCode.id || null, - logistics_name: listByWarehousePlatformCode.logistics_name || '', + logistics_name: sysExpressName || '', logistics_interface_name: listByWarehousePlatformCode.name || '', platform_code: listByWarehousePlatformCode.platform_code || '', status: 1, @@ -975,9 +989,12 @@ class ExpressPlatformService extends MainService { encryptprintinfo: item.encryptprintinfo, ...this.buildOrderExpressVerPatch([ item.ver ]), create_at: new Date(), - logistics_code: listByWarehousePlatformCode.logistics_code || '', + delivery_order_code: orderDataMap.get(`${order_id}_${business_key}`)?.delivery_order_code || null, + source_order_codes: orderDataMap.get(`${order_id}_${business_key}`)?.source_order_codes || null, + store_id: orderDataMap.get(`${order_id}_${business_key}`)?.store_id || null, + logistics_code: listByWarehousePlatformCode.sys_express_code || '', logistics_interface_id: listByWarehousePlatformCode.id || null, - logistics_name: listByWarehousePlatformCode.logistics_name || '', + logistics_name: sysExpressName || '', logistics_interface_name: listByWarehousePlatformCode.name || '', platform_code: listByWarehousePlatformCode.platform_code || '', status: 1, @@ -1088,9 +1105,12 @@ class ExpressPlatformService extends MainService { encryptedtoken, ...this.buildOrderExpressVerPatch([ item && item.ver ]), create_at: new Date(), - logistics_code: listByWarehousePlatformCode.logistics_code || '', + delivery_order_code: orderDataMap.get(`${order_id}_${business_key}`)?.delivery_order_code || null, + source_order_codes: orderDataMap.get(`${order_id}_${business_key}`)?.source_order_codes || null, + store_id: orderDataMap.get(`${order_id}_${business_key}`)?.store_id || null, + logistics_code: listByWarehousePlatformCode.sys_express_code || '', logistics_interface_id: listByWarehousePlatformCode.id || null, - logistics_name: listByWarehousePlatformCode.logistics_name || '', + logistics_name: sysExpressName || '', logistics_interface_name: listByWarehousePlatformCode.name || '', platform_code: listByWarehousePlatformCode.platform_code || '', status: 1, @@ -1122,9 +1142,12 @@ class ExpressPlatformService extends MainService { encryptprintinfo: item.encryptprintinfo, ...this.buildOrderExpressVerPatch([ item.ver ]), create_at: new Date(), - logistics_code: listByWarehousePlatformCode.logistics_code || '', + delivery_order_code: orderDataMap.get(`${order_id}_${business_key}`)?.delivery_order_code || null, + source_order_codes: orderDataMap.get(`${order_id}_${business_key}`)?.source_order_codes || null, + store_id: orderDataMap.get(`${order_id}_${business_key}`)?.store_id || null, + logistics_code: listByWarehousePlatformCode.sys_express_code || '', logistics_interface_id: listByWarehousePlatformCode.id || null, - logistics_name: listByWarehousePlatformCode.logistics_name || '', + logistics_name: sysExpressName || '', logistics_interface_name: listByWarehousePlatformCode.name || '', platform_code: listByWarehousePlatformCode.platform_code || '', status: 1, @@ -1186,9 +1209,12 @@ class ExpressPlatformService extends MainService { encryptedtoken, ...this.buildOrderExpressVerPatch([ ver ]), create_at: new Date(), - logistics_code: listByWarehousePlatformCode.logistics_code || '', + delivery_order_code: orderDataMap.get(`${order_id}_${business_key}`)?.delivery_order_code || null, + source_order_codes: orderDataMap.get(`${order_id}_${business_key}`)?.source_order_codes || null, + store_id: orderDataMap.get(`${order_id}_${business_key}`)?.store_id || null, + logistics_code: listByWarehousePlatformCode.sys_express_code || '', logistics_interface_id: listByWarehousePlatformCode.id || null, - logistics_name: listByWarehousePlatformCode.logistics_name || '', + logistics_name: sysExpressName || '', logistics_interface_name: listByWarehousePlatformCode.name || '', platform_code: listByWarehousePlatformCode.platform_code || '', status: 1, @@ -1218,9 +1244,12 @@ class ExpressPlatformService extends MainService { encryptprintinfo: item.encryptprintinfo, ...this.buildOrderExpressVerPatch([ item.ver ]), create_at: new Date(), - logistics_code: listByWarehousePlatformCode.logistics_code || '', + delivery_order_code: orderDataMap.get(`${order_id}_${business_key}`)?.delivery_order_code || null, + source_order_codes: orderDataMap.get(`${order_id}_${business_key}`)?.source_order_codes || null, + store_id: orderDataMap.get(`${order_id}_${business_key}`)?.store_id || null, + logistics_code: listByWarehousePlatformCode.sys_express_code || '', logistics_interface_id: listByWarehousePlatformCode.id || null, - logistics_name: listByWarehousePlatformCode.logistics_name || '', + logistics_name: sysExpressName || '', logistics_interface_name: listByWarehousePlatformCode.name || '', platform_code: listByWarehousePlatformCode.platform_code || '', status: 1, @@ -1251,9 +1280,12 @@ class ExpressPlatformService extends MainService { encryptedtoken: item.encryptedtoken, ...this.buildOrderExpressVerPatch([ item.ver ]), create_at: new Date(), - logistics_code: listByWarehousePlatformCode.logistics_code || '', + delivery_order_code: orderDataMap.get(`${order_id}_${business_key}`)?.delivery_order_code || null, + source_order_codes: orderDataMap.get(`${order_id}_${business_key}`)?.source_order_codes || null, + store_id: orderDataMap.get(`${order_id}_${business_key}`)?.store_id || null, + logistics_code: listByWarehousePlatformCode.sys_express_code || '', logistics_interface_id: listByWarehousePlatformCode.id || null, - logistics_name: listByWarehousePlatformCode.logistics_name || '', + logistics_name: sysExpressName || '', logistics_interface_name: listByWarehousePlatformCode.name || '', platform_code: listByWarehousePlatformCode.platform_code || '', status: 1, @@ -1626,6 +1658,18 @@ class ExpressPlatformService extends MainService { const normalizedTemplateUrl = isValidCainiaoTemplateUrl(listByWarehousePlatformCode.template_url) ? String(listByWarehousePlatformCode.template_url).trim() : DEFAULT_CAINIAO_TEMPLATE_URL; + const ExpressList = await this.service.systems.express.loadExpressList(); + const sysExpressName = (ExpressList.find(item => item.code === listByWarehousePlatformCode.sys_express_code) || {}).name || ''; + const orderDataMap = new Map(); + for (const order_tmp of normalizedOrders) { + const od = order_tmp && order_tmp.order_delivery; + if (!od) continue; + orderDataMap.set(`${od.id}_${order_tmp.business_key}`, { + delivery_order_code: od.delivery_order_code || '', + source_order_codes: od.source_order_codes || '', + store_id: od.store_id || 0, + }); + } if (!appKey || !appSecret) { throw new Error('淘宝接口配置缺失'); } @@ -1851,9 +1895,12 @@ class ExpressPlatformService extends MainService { encryptprintinfo: encryptPrintInfo, ...orderExpressVerPatch, create_at: new Date(), - logistics_code: listByWarehousePlatformCode.logistics_code || '', + delivery_order_code: orderDataMap.get(`${orderId}_${businessKey}`)?.delivery_order_code || null, + source_order_codes: orderDataMap.get(`${orderId}_${businessKey}`)?.source_order_codes || null, + store_id: orderDataMap.get(`${orderId}_${businessKey}`)?.store_id || null, + logistics_code: listByWarehousePlatformCode.sys_express_code || '', logistics_interface_id: listByWarehousePlatformCode.id || null, - logistics_name: listByWarehousePlatformCode.logistics_name || '', + logistics_name: sysExpressName || '', logistics_interface_name: listByWarehousePlatformCode.name || '', platform_code: listByWarehousePlatformCode.platform_code || '', status: 1, @@ -2213,6 +2260,18 @@ class ExpressPlatformService extends MainService { } = data && typeof data === 'object' ? data : {}; const normalizedOrders = Array.isArray(orders) ? orders : []; const normalizedExtData = this.normalizePddExtData(listByWarehousePlatformCode.ext_data); + const ExpressList = await this.service.systems.express.loadExpressList(); + const sysExpressName = (ExpressList.find(item => item.code === listByWarehousePlatformCode.sys_express_code) || {}).name || ''; + const orderDataMap = new Map(); + for (const order_tmp of normalizedOrders) { + const od = order_tmp && order_tmp.order_delivery; + if (!od) continue; + orderDataMap.set(`${od.id}_${order_tmp.business_key}`, { + delivery_order_code: od.delivery_order_code || '', + source_order_codes: od.source_order_codes || '', + store_id: od.store_id || 0, + }); + } console.log('拼多多平台接口入参', data); @@ -2386,9 +2445,12 @@ class ExpressPlatformService extends MainService { parsedPrintData && parsedPrintData.data && parsedPrintData.data.ver, ]), create_at: new Date(), - logistics_code: listByWarehousePlatformCode.logistics_code || '', + delivery_order_code: orderDataMap.get(`${orderId}_${businessKey}`)?.delivery_order_code || null, + source_order_codes: orderDataMap.get(`${orderId}_${businessKey}`)?.source_order_codes || null, + store_id: orderDataMap.get(`${orderId}_${businessKey}`)?.store_id || null, + logistics_code: listByWarehousePlatformCode.sys_express_code || '', logistics_interface_id: listByWarehousePlatformCode.id || null, - logistics_name: listByWarehousePlatformCode.logistics_name || '', + logistics_name: sysExpressName || '', logistics_interface_name: listByWarehousePlatformCode.name || '', platform_code: listByWarehousePlatformCode.platform_code || '', status: 1, From 5378fcd137d920a8cbeab41bd40aa4e8f9ab6ecd Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sat, 1 Aug 2026 03:44:53 +0800 Subject: [PATCH 141/550] =?UTF-8?q?refactor(print):=20=E6=89=93=E5=8D=B0?= =?UTF-8?q?=E6=A8=A1=E5=9D=97=E9=87=8D=E6=9E=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 systems/order_print.js 订单打印业务层(getPrintDataByWaybillCodes 等) - print.js 删除 retry 补偿相关代码(normalizeRetrySendPayload/getRetryEligibility) - order/print.js 新增 getPrintDataByWaybillCodes 方法 - printer_data_builder.js 新增 appendExtraCustomLines + extraCustomLines 参数支持 - polo_api_client.js 添加调试缓存 - 删除 print_retry_compensation 定时任务测试 --- app/lib/polo_api_client.js | 3 + app/lib/printer_data_builder.js | 127 ++++-- app/service/systemMethods/order/print.js | 36 +- app/service/systemMethods/print.js | 408 +++++++----------- app/service/systems/order_print.js | 348 +++++++++++++++ .../schedule/print_retry_compensation.test.js | 255 ----------- .../service/systemMethods/print.send.test.js | 197 --------- 7 files changed, 628 insertions(+), 746 deletions(-) delete mode 100644 test/app/schedule/print_retry_compensation.test.js diff --git a/app/lib/polo_api_client.js b/app/lib/polo_api_client.js index 8a03b90..9379403 100644 --- a/app/lib/polo_api_client.js +++ b/app/lib/polo_api_client.js @@ -49,6 +49,9 @@ class PoloApiClient { .map(key => `${key}=${encodeURIComponent(signMap[key])}`) .join('&'); console.log('查询菠萝派平台数据,接口URL:', config.interface_url, '入参bizcontent:', JSON.stringify(bizcontent)); + + await this.ctx.app.setCacheAsync('PoloApiquery', '查询菠萝派平台数据,接口URL:' + config.interface_url + ',入参bizcontent:' + formBody, 3600); + const response = await this.ctx.curl(String(config.interface_url || ''), { method: 'POST', headers: { diff --git a/app/lib/printer_data_builder.js b/app/lib/printer_data_builder.js index 38ed2b9..c389d8e 100644 --- a/app/lib/printer_data_builder.js +++ b/app/lib/printer_data_builder.js @@ -556,6 +556,23 @@ function buildWaybillCustomProductInfoLines(items, policyConfig = {}, options = return [ headerLine, ...detailLines ]; } +/** + * 向已有的自定义区文本追加额外行。 + * @param {string} customText 已有的自定义区文本。 + * @param {Array} extraLines 额外文本行数组。 + * @param {string} [lineBreak='\n'] 换行符。 + * @return {string} 追加后的文本。 + */ +function appendExtraCustomLines(customText, extraLines, lineBreak = '\n') { + const safeLines = Array.isArray(extraLines) ? extraLines.filter(line => String(line || '').trim() !== '') : []; + if (safeLines.length === 0) { + return customText; + } + const prefix = safeLines.join(lineBreak); + const base = String(customText || '').trim(); + return base ? `${prefix}${lineBreak}${base}` : prefix; +} + /** * 将自定义文本行按平台换行符合并为字符串。 * @param {Array} lines 文本行数组。 @@ -1237,7 +1254,7 @@ function sanitizeTemplatePrivateFields(value, warnings, currentKey = '') { * @param {Object} policyConfig 策略配置对象。 * @param {string} customDataTemplateURL 自定义区模板地址默认值。 */ -function applyKuaishouExpressFieldMapping(platform, skeleton, orderExpress, orderDelivery, warnings, policyConfig, customDataTemplateURL) { +function applyKuaishouExpressFieldMapping(platform, skeleton, orderExpress, orderDelivery, warnings, policyConfig, customDataTemplateURL, extraCustomLines = []) { if (platform !== 'kuaishou') { return; } @@ -1278,9 +1295,13 @@ function applyKuaishouExpressFieldMapping(platform, skeleton, orderExpress, orde fallbackTotalQty: Number(safeOrderDelivery.items_count || safeOrderDelivery.items_total || 0), } ); - const customProductInfo = mergeWaybillCustomLines(customProductInfoLines, { - lineBreak: LINE_BREAK_MAP.LF, - }); + const customProductInfo = appendExtraCustomLines( + mergeWaybillCustomLines(customProductInfoLines, { + lineBreak: LINE_BREAK_MAP.LF, + }), + extraCustomLines, + LINE_BREAK_MAP.LF + ); for (const document of documents) { if (!isPlainObject(document)) { @@ -1382,7 +1403,7 @@ function applyKuaishouExpressFieldMapping(platform, skeleton, orderExpress, orde * @param {Object} orderDelivery 订单对象。 * @param {Object} policyConfig 策略配置对象。 */ -function applyPddExpressFieldMapping(platform, skeleton, orderExpress, orderDelivery, policyConfig) { +function applyPddExpressFieldMapping(platform, skeleton, orderExpress, orderDelivery, policyConfig, extraCustomLines = []) { if (platform !== 'pdd') { return; } @@ -1423,10 +1444,14 @@ function applyPddExpressFieldMapping(platform, skeleton, orderExpress, orderDeli fallbackTotalQty: Number(safeOrderDelivery.items_count || safeOrderDelivery.items_total || 0), } ); - const customProductInfo = mergeWaybillCustomLines(customProductInfoLines, { - lineBreak: LINE_BREAK_MAP.CR, - trailingLineBreak: true, - }); + const customProductInfo = appendExtraCustomLines( + mergeWaybillCustomLines(customProductInfoLines, { + lineBreak: LINE_BREAK_MAP.CR, + trailingLineBreak: true, + }), + extraCustomLines, + LINE_BREAK_MAP.CR + ); /** * 判断内容对象是否属于拼多多自定义区。 @@ -1560,7 +1585,7 @@ function resolveDouyinParams(orderExpress) { * @param {Object} orderDelivery 订单对象。 * @param {Object} policyConfig 策略配置对象。 */ -function applyDouyinExpressFieldMapping(platform, skeleton, orderExpress, orderDelivery, policyConfig) { +function applyDouyinExpressFieldMapping(platform, skeleton, orderExpress, orderDelivery, policyConfig, extraCustomLines = []) { if (platform !== 'douyin') { return; } @@ -1610,7 +1635,11 @@ function applyDouyinExpressFieldMapping(platform, skeleton, orderExpress, orderD fallbackTotalQty: Number(safeOrderDelivery.items_count || safeOrderDelivery.items_total || 0), } ); - const customProductInfo = mergeWaybillCustomLines(customProductInfoLines, { lineBreak: '\n' }); + const customProductInfo = appendExtraCustomLines( + mergeWaybillCustomLines(customProductInfoLines, { lineBreak: '\n' }), + extraCustomLines, + '\n' + ); for (const document of documents) { if (!isPlainObject(document)) { @@ -1700,7 +1729,8 @@ function applyCainiaoExpressFieldMapping( orderDelivery, policyConfig, customControlTemplateURL, - warnings + warnings, + extraCustomLines = [] ) { if (platform !== 'cainiao') { return; @@ -1743,9 +1773,13 @@ function applyCainiaoExpressFieldMapping( fallbackTotalQty: Number(safeOrderDelivery.items_count || safeOrderDelivery.items_total || 0), } ); - const customControlText = mergeWaybillCustomLines(customProductInfoLines, { - lineBreak: LINE_BREAK_MAP.CR, - }); + const customControlText = appendExtraCustomLines( + mergeWaybillCustomLines(customProductInfoLines, { + lineBreak: LINE_BREAK_MAP.CR, + }), + extraCustomLines, + LINE_BREAK_MAP.CR + ); for (const document of documents) { if (!isPlainObject(document)) { @@ -1904,7 +1938,8 @@ function applyXhsExpressFieldMapping( orderExpress, orderDelivery, policyConfig, - warnings + warnings, + extraCustomLines = [] ) { if (platform !== 'xhs') { return; @@ -1944,9 +1979,13 @@ function applyXhsExpressFieldMapping( fallbackTotalQty: Number(safeOrderDelivery.items_count || safeOrderDelivery.items_total || 0), } ); - const customProductInfo = mergeWaybillCustomLines(customProductInfoLines, { - lineBreak: LINE_BREAK_MAP.LF, - }); + const customProductInfo = appendExtraCustomLines( + mergeWaybillCustomLines(customProductInfoLines, { + lineBreak: LINE_BREAK_MAP.LF, + }), + extraCustomLines, + LINE_BREAK_MAP.LF + ); for (const document of documents) { if (!isPlainObject(document)) { @@ -2000,7 +2039,8 @@ function applySphExpressFieldMapping( skeleton, orderExpress, orderDelivery, - policyConfig + policyConfig, + extraCustomLines = [] ) { if (platform !== 'sph') { return; @@ -2054,9 +2094,13 @@ function applySphExpressFieldMapping( fallbackTotalQty: Number(safeOrderDelivery.items_count || safeOrderDelivery.items_total || 0), } ); - const customProductInfo = mergeWaybillCustomLines(customProductInfoLines, { - lineBreak: LINE_BREAK_MAP.LF, - }).replace(/\n/g, '
    '); + const customProductInfo = appendExtraCustomLines( + mergeWaybillCustomLines(customProductInfoLines, { + lineBreak: LINE_BREAK_MAP.LF, + }).replace(/\n/g, '
    '), + extraCustomLines, + '
    ' + ); task.customInfo = isPlainObject(task.customInfo) ? task.customInfo : {}; task.customInfo.data = isPlainObject(task.customInfo.data) ? task.customInfo.data : {}; @@ -2137,7 +2181,8 @@ function applyJdExpressFieldMapping( orderDelivery, policyConfig, templateSample, - warnings + warnings, + extraCustomLines = [] ) { if (platform !== 'jd') { return; @@ -2220,10 +2265,14 @@ function applyJdExpressFieldMapping( fallbackTotalQty: Number(safeOrderDelivery.items_count || safeOrderDelivery.items_total || 0), } ); - const customProductInfo = mergeWaybillCustomLines(customProductInfoLines, { - lineBreak: LINE_BREAK_MAP.LF, - trailingLineBreak: true, - }); + const customProductInfo = appendExtraCustomLines( + mergeWaybillCustomLines(customProductInfoLines, { + lineBreak: LINE_BREAK_MAP.LF, + trailingLineBreak: true, + }), + extraCustomLines, + LINE_BREAK_MAP.LF + ); content.customData = isPlainObject(content.customData) ? content.customData : {}; content.customData.GoodsInfo = customProductInfo; @@ -2243,6 +2292,7 @@ function buildPlatformRequestSkeleton(input = {}) { const baseResult = buildBaseData(input, normalized.platform, normalized.meta); const options = isPlainObject(input.options) ? input.options : {}; + const extraCustomLines = Array.isArray(options.extraCustomLines) ? options.extraCustomLines : []; const policyConfig = resolvePolicyConfig(input); const orderExpressForCompose = isPlainObject(input.order_express) ? { ...input.order_express } @@ -2335,7 +2385,8 @@ function buildPlatformRequestSkeleton(input = {}) { orderDeliveryForCompose, policyConfig, cainiaoCustomControlTemplateURL, - warnings + warnings, + extraCustomLines ); applyKuaishouExpressFieldMapping( @@ -2345,7 +2396,8 @@ function buildPlatformRequestSkeleton(input = {}) { orderDeliveryForCompose, warnings, policyConfig, - customDataTemplateURL + customDataTemplateURL, + extraCustomLines ); applyPddExpressFieldMapping( @@ -2353,7 +2405,8 @@ function buildPlatformRequestSkeleton(input = {}) { skeleton, orderExpressForCompose, orderDeliveryForCompose, - policyConfig + policyConfig, + extraCustomLines ); applyDouyinExpressFieldMapping( @@ -2361,7 +2414,8 @@ function buildPlatformRequestSkeleton(input = {}) { skeleton, orderExpressForCompose, orderDeliveryForCompose, - policyConfig + policyConfig, + extraCustomLines ); applyJdExpressFieldMapping( @@ -2371,7 +2425,8 @@ function buildPlatformRequestSkeleton(input = {}) { orderDeliveryForCompose, policyConfig, templateSample, - warnings + warnings, + extraCustomLines ); applyXhsExpressFieldMapping( @@ -2380,7 +2435,8 @@ function buildPlatformRequestSkeleton(input = {}) { orderExpressForCompose, orderDeliveryForCompose, policyConfig, - warnings + warnings, + extraCustomLines ); applySphExpressFieldMapping( @@ -2388,7 +2444,8 @@ function buildPlatformRequestSkeleton(input = {}) { skeleton, orderExpressForCompose, orderDeliveryForCompose, - policyConfig + policyConfig, + extraCustomLines ); return { diff --git a/app/service/systemMethods/order/print.js b/app/service/systemMethods/order/print.js index 8db847b..952ff73 100644 --- a/app/service/systemMethods/order/print.js +++ b/app/service/systemMethods/order/print.js @@ -11,9 +11,9 @@ class OrderPrintService extends OrderBaseService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'getWavePrintData,getWavePlatformPrintData,unlockWavePlatformPrintDataByGroup,getOrderPrintData'; - const _noNeedLog = 'getWavePrintData,unlockWavePlatformPrintDataByGroup,getOrderPrintData'; - const _noNeedAuth = 'getWavePrintData,getWavePlatformPrintData,unlockWavePlatformPrintDataByGroup,getOrderPrintData'; + const _noNeedRight = 'getWavePrintData,getWavePlatformPrintData,unlockWavePlatformPrintDataByGroup,getOrderPrintData,getPrintDataByWaybillCodes'; + const _noNeedLog = 'getWavePrintData,unlockWavePlatformPrintDataByGroup,getOrderPrintData,getPrintDataByWaybillCodes'; + const _noNeedAuth = 'getWavePrintData,getWavePlatformPrintData,unlockWavePlatformPrintDataByGroup,getOrderPrintData,getPrintDataByWaybillCodes'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -120,6 +120,36 @@ class OrderPrintService extends OrderBaseService { }); } + /** + * 按运单号数组拉取平台打印中间态数据。 + * + * method 层仅负责参数解构与边界校验,具体业务查询与打印数据组装由 systems 层实现。 + * 仓库ID统一从当前上下文获取,无需调用方传入。 + * + * @param {Object} data 请求体。 + * @param {Array} data.waybill_codes 运单号数组。 + * @return {Promise} 统一 success 包装的平台打印中间态结果。 + */ + async getPrintDataByWaybillCodes(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const { + waybill_codes: waybillCodes, + } = requestData; + + if (!Array.isArray(waybillCodes) || waybillCodes.length === 0) { + throw new Error('waybill_codes 必填,且必须为非空数组'); + } + + const result = await this.service.systems.orderPrint.getPrintDataByWaybillCodes({ + waybillCodes, + }); + + return this.success('ok', { + data: result, + code: 200, + }); + } + /** * 按分组解锁波次平台打印锁。 * diff --git a/app/service/systemMethods/print.js b/app/service/systemMethods/print.js index a1e7fd1..7cdc50a 100644 --- a/app/service/systemMethods/print.js +++ b/app/service/systemMethods/print.js @@ -138,7 +138,7 @@ class PrintService extends MainService { return { status: 'sent', send_status: 'sent', - print_status: 'printed', + print_status: 'unknown', sent_time: sentTime, print_time: sentTime, fail_code: null, @@ -170,55 +170,6 @@ class PrintService extends MainService { }; } - /** - * 规范化补打所需的已落库发送数据。 - * @param {Object|string} recordData 打印记录 data 字段。 - * @return {{success:boolean,data?:Object,error?:string}} 解析结果。 - */ - normalizeRetrySendPayload(recordData) { - let normalizedRecordData = recordData; - if (typeof normalizedRecordData === 'string') { - try { - normalizedRecordData = JSON.parse(normalizedRecordData); - } catch (error) { - return { - success: false, - error: '打印记录 data 不是有效 JSON', - }; - } - } - - if (!normalizedRecordData || typeof normalizedRecordData !== 'object' || Array.isArray(normalizedRecordData)) { - return { - success: false, - error: '打印记录 data 结构不合法', - }; - } - - const printer = String(normalizedRecordData.printer || '').trim(); - const component = String(normalizedRecordData.component || '').trim(); - const type = String(normalizedRecordData.type || '').trim(); - const payloadData = normalizedRecordData.data; - const orderIds = this.normalizeOrderIds(normalizedRecordData.order_ids); - if (!printer || !type || !payloadData || typeof payloadData !== 'object' || Array.isArray(payloadData)) { - return { - success: false, - error: '打印记录 data 缺少 printer/type/data', - }; - } - - return { - success: true, - data: { - printer, - component, - type, - order_ids: orderIds, - data: JSON.parse(JSON.stringify(payloadData)), - }, - }; - } - /** * 规范化订单ID数组,过滤非法值并去重。 * @param {Array} orderIds 原始订单ID数组。 @@ -421,39 +372,6 @@ class PrintService extends MainService { } } - /** - * 判断记录是否满足失败补打条件。 - * @param {Object} record 打印记录。 - * @param {boolean} force 是否强制补打(最小实现默认不放宽规则)。 - * @return {{canRetry:boolean,reason:string}} 判断结果。 - */ - getRetryEligibility(record = {}, force = false) { - const normalizedRecord = record && typeof record === 'object' ? record : {}; - const status = String(normalizedRecord.status || '').trim(); - const printStatus = String(normalizedRecord.print_status || '').trim(); - - if (status === 'sent' && [ 'unknown', 'printed' ].includes(printStatus)) { - return { - canRetry: false, - reason: `状态为 sent/${printStatus},按规则跳过`, - }; - } - - const canRetry = status === 'failed' || [ 'print_failed', 'timeout' ].includes(printStatus); - if (canRetry) { - return { - canRetry: true, - reason: '', - }; - } - - const forceTip = force ? '(force 已开启,当前最小实现仍不放宽状态限制)' : ''; - return { - canRetry: false, - reason: `状态不允许补打:status=${status || 'unknown'},print_status=${printStatus || 'unknown'}${forceTip}`, - }; - } - /** * 获取打印任务编码冲突重试配置。 * @return {{maxRetries:number,baseDelayMs:number,jitterMs:number}} 归一化后的重试配置。 @@ -1082,6 +1000,7 @@ class PrintService extends MainService { timestamp, count, printId: printRecord.id, + ...(customizeOrderIds.length > 0 ? { order_ids: customizeOrderIds } : {}), }; const sendStartAt = Date.now(); const res = await this.service.systems.print.index.sendToComputer({ warehouse: warehouseId, computerId, data: printData }); @@ -1142,175 +1061,6 @@ class PrintService extends MainService { return this.fail(res.error, { code: 504, printId: printRecord.id }); } - /** - * 失败项补打:仅重试失败记录,原记录保持不变。 - * @param {Object} data 补打参数。 - * @param {Array} data.print_ids 需要补打的打印记录 ID 列表。 - * @param {boolean} [data.force=false] 是否强制补打(最小实现默认不放宽状态规则)。 - * @param {number|string} [data.warehouse_id] 显式指定仓库 ID(用于定时任务等无登录上下文场景)。 - * @return {Promise} 统一返回结构。 - */ - async retryFailed(data = {}) { - const { ctx } = this; - const requestData = data && typeof data === 'object' ? data : {}; - const { - print_ids: rawPrintIds, - force = false, - warehouse_id: rawWarehouseId, - } = requestData; - - const normalizedWarehouseId = Number(rawWarehouseId); - const userWarehouseId = Number(ctx.user && ctx.user.store_id); - const warehouseId = Number.isInteger(normalizedWarehouseId) && normalizedWarehouseId > 0 - ? normalizedWarehouseId - : (Number.isInteger(userWarehouseId) && userWarehouseId > 0 ? userWarehouseId : 0); - - if (!warehouseId) { - return this.fail('warehouse_id 参数缺失,且当前上下文无可用仓库信息', { code: 400 }); - } - - if (!Array.isArray(rawPrintIds) || rawPrintIds.length === 0) { - return this.fail('print_ids 参数不能为空数组', { code: 400 }); - } - - const printIds = Array.from(new Set(rawPrintIds - .map(item => Number(item)) - .filter(item => Number.isInteger(item) && item > 0))); - if (printIds.length === 0) { - return this.fail('print_ids 参数不合法,必须包含正整数 ID', { code: 400 }); - } - - const sourceRecords = await ctx.model.PrintRecord.findAll({ - where: { - id: printIds, - warehouse_id: warehouseId, - }, - raw: true, - }); - const sourceRecordMap = new Map(sourceRecords.map(item => [ Number(item.id), item ])); - - const retried = []; - const skipped = []; - let successCount = 0; - let failedCount = 0; - - for (const printId of printIds) { - const sourceRecord = sourceRecordMap.get(printId); - if (!sourceRecord) { - skipped.push({ - print_id: printId, - reason: '记录不存在或不属于当前仓库', - }); - continue; - } - - const eligibility = this.getRetryEligibility(sourceRecord, Boolean(force)); - if (!eligibility.canRetry) { - skipped.push({ - print_id: printId, - reason: eligibility.reason, - }); - continue; - } - - const payloadResult = this.normalizeRetrySendPayload(sourceRecord.data); - if (!payloadResult.success) { - skipped.push({ - print_id: printId, - reason: payloadResult.error, - }); - continue; - } - - const sendPayload = payloadResult.data; - const taskCode = await this.reserveUniquePrintTaskCode(); - if (sendPayload.data.task && typeof sendPayload.data.task === 'object' && !Array.isArray(sendPayload.data.task)) { - sendPayload.data.task.taskID = taskCode; - } - - const newPrintRecord = await ctx.model.PrintRecord.create(this.buildPendingPrintRecordPayload({ - warehouse_id: sourceRecord.warehouse_id, - computer_id: sourceRecord.computer_id, - printer: sourceRecord.printer, - type: sourceRecord.type, - request_code: sourceRecord.request_code, - wave_id: sourceRecord.wave_id, - wave_no: sourceRecord.wave_no, - platform_code: sourceRecord.platform_code, - platform_name: sourceRecord.platform_name, - sys_logistics_code: sourceRecord.sys_logistics_code, - sys_logistics_name: sourceRecord.sys_logistics_name, - retry_of_print_id: sourceRecord.id, - data: sendPayload, - })); - - try { - const sendResult = await this.service.systems.print.index.sendToComputer({ - warehouse: warehouseId, - computerId: sourceRecord.computer_id, - data: { - ...sendPayload, - printId: newPrintRecord.id, - }, - }); - if (sendResult.status !== 'success') { - const failedMessage = sendResult.error || '打印服务返回失败'; - await newPrintRecord.update(this.buildSendFailedPrintRecordUpdatePayload({ - errorMessage: failedMessage, - failCode: 'SEND_FAILED', - })); - retried.push({ - source_print_id: sourceRecord.id, - new_print_id: newPrintRecord.id, - task_code: taskCode, - status: 'failed', - }); - failedCount += 1; - continue; - } - - const providerTaskId = String( - sendResult && (sendResult.taskId || sendResult.task_id || sendResult.providerTaskId || sendResult.id) - ? (sendResult.taskId || sendResult.task_id || sendResult.providerTaskId || sendResult.id) - : '' - ).trim(); - await this.bindTaskCodeToPrintRecordWithRetry({ - printRecordId: newPrintRecord.id, - taskCode, - provider: providerTaskId, - }); - retried.push({ - source_print_id: sourceRecord.id, - new_print_id: newPrintRecord.id, - task_code: taskCode, - status: 'sent', - }); - successCount += 1; - } catch (error) { - await newPrintRecord.update(this.buildSendFailedPrintRecordUpdatePayload({ - errorMessage: error && error.message ? error.message : `${error}`, - failCode: 'SEND_FAILED', - })); - retried.push({ - source_print_id: sourceRecord.id, - new_print_id: newPrintRecord.id, - task_code: taskCode, - status: 'failed', - }); - failedCount += 1; - } - } - - return this.success('失败项补打处理完成', { - code: 200, - success_count: successCount, - failed_count: failedCount, - skipped_count: skipped.length, - retried, - skipped, - }); - } - /** * 校验快递打印请求的必要参数。 * @param {Object} payload 校验参数。 @@ -1797,6 +1547,142 @@ class PrintService extends MainService { return this.notifyLock(data); } + /** + * 当 batchOrderIds 为空时,尝试通过 wave_id 从数据库反查订单 ID 列表作为兜底。 + * + * 适用于前端未回传 order_ids 的场景(如团购打印),确保打印成功后仍能标记订单为已打印。 + * + * @param {Object} payload 查询参数。 + * @param {number|string} payload.warehouseId 仓库ID。 + * @param {number|null} payload.waveId 波次ID。 + * @return {Promise>} 订单ID列表;查询失败或参数无效时返回空数组。 + */ + async resolveBatchOrderIdsByWaveFallback(payload = {}) { + const normalizedPayload = payload && typeof payload === 'object' ? payload : {}; + const warehouseId = Number(normalizedPayload.warehouseId || 0); + const waveId = Number(normalizedPayload.waveId || 0); + + if (!Number.isInteger(warehouseId) || warehouseId <= 0 || !Number.isInteger(waveId) || waveId <= 0) { + return []; + } + + try { + const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; + if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') { + this.ctx.logger.warn('[print.markWavePrintStatus] OrderDeliveryFactory 不可用'); + return []; + } + + const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(warehouseId); + if (!orderDeliveryModel || typeof orderDeliveryModel.findAll !== 'function') { + this.ctx.logger.warn('[print.markWavePrintStatus] orderDeliveryModel 不可用'); + return []; + } + + const rows = await orderDeliveryModel.findAll({ + attributes: [ 'id' ], + where: { + wave_id: waveId, + warehouse_id: warehouseId, + status: { [this.app.Sequelize.Op.ne]: 'cancel' }, + }, + raw: true, + }); + + const orderIds = (Array.isArray(rows) ? rows : []) + .map(row => Number(row && row.id)) + .filter(id => Number.isInteger(id) && id > 0); + + if (orderIds.length > 0) { + this.ctx.logger.info('[print.markWavePrintStatus] wave_id=%d 查询到 %d 个订单', waveId, orderIds.length); + } + + return orderIds; + } catch (error) { + this.ctx.logger.warn('[print.markWavePrintStatus] 查询失败 wave_id=%d reason=%s', + waveId, error && error.message ? error.message : `${error}`); + return []; + } + } + + /** + * 标记/取消标记整个波次的订单打印状态。 + * + * 仅操作当前仓库下、状态非取消的订单。 + * 仓库隔离:从 ctx.user.store_id 获取仓库 ID。 + * + * @param {Object} data 入参。 + * @param {number|string} data.wave_id 波次ID(必填)。 + * @param {string} [data.status='printed'] 目标状态:'printed' 标记已打印,'unprinted' 取消已打印标记。 + * @return {Promise} 统一返回结构。 + */ + async markWavePrintStatus(data = {}) { + const { ctx } = this; + const requestData = data && typeof data === 'object' ? data : {}; + const waveId = Number(requestData.wave_id || 0); + const targetStatus = String(requestData.status || 'printed').trim().toLowerCase(); + + if (!Number.isInteger(waveId) || waveId <= 0) { + return this.fail('wave_id 参数必填,且必须为正整数', { code: 400 }); + } + + if (![ 'printed', 'unprinted' ].includes(targetStatus)) { + return this.fail('status 参数不合法,仅支持 printed / unprinted', { code: 400 }); + } + + const warehouseId = Number(ctx.user && ctx.user.store_id || 0); + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + return this.fail('无法获取当前仓库ID,请确认已登录', { code: 400 }); + } + + const orderIds = await this.resolveBatchOrderIdsByWaveFallback({ warehouseId, waveId }); + if (orderIds.length === 0) { + return this.fail(`波次 ${waveId} 在当前仓库下没有可操作的订单`, { code: 404 }); + } + + const printStatus = targetStatus === 'printed' ? 'fin' : 'none'; + try { + const orderDeliveryFactory = ctx.model && ctx.model.OrderDeliveryFactory; + if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') { + return this.fail('OrderDeliveryFactory 不可用', { code: 500 }); + } + + const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(warehouseId); + if (!orderDeliveryModel || typeof orderDeliveryModel.update !== 'function') { + return this.fail('OrderDeliveryModel 不可用', { code: 500 }); + } + + const updateResult = await orderDeliveryModel.update({ + print_status: printStatus, + updated_at: new Date(), + }, { + where: { + id: { [this.app.Sequelize.Op.in]: orderIds }, + warehouse_id: warehouseId, + status: { [this.app.Sequelize.Op.ne]: 'cancel' }, + }, + }); + + const affectedRows = Number(Array.isArray(updateResult) ? updateResult[0] : updateResult) || 0; + this.ctx.logger.info('[print.markWavePrintStatus] 波次打印状态标记完成 wave_id=%d target=%s affected=%d/%d', + waveId, targetStatus, affectedRows, orderIds.length); + + return this.success('ok', { + code: 0, + wave_id: waveId, + status: targetStatus, + print_status: printStatus, + total_orders: orderIds.length, + affected_orders: affectedRows, + order_ids: orderIds, + }); + } catch (error) { + this.ctx.logger.error('[print.markWavePrintStatus] 更新失败 wave_id=%d reason=%s', + waveId, error && error.message ? error.message : `${error}`); + return this.fail(`波次打印状态更新失败:${error && error.message ? error.message : '未知错误'}`, { code: 500 }); + } + } + /** * 在打印发送成功后批量锁定订单。 * @@ -2129,6 +2015,16 @@ class PrintService extends MainService { for (let batchIndex = 0; batchIndex < orderBatches.length; batchIndex++) { const batchOrders = orderBatches[batchIndex]; const batchOrderIds = this.collectOrderIdsFromPlatformGroup(platformGroup, batchOrders); + // 兜底:前端未回传 order_ids 时,通过 wave_id 反查当前波次全部订单ID + if (batchOrderIds.length === 0 && waveId) { + const fallbackIds = await this.resolveBatchOrderIdsByWaveFallback({ + warehouseId: normalizedPayload.warehouseId, + waveId, + }); + if (fallbackIds.length > 0) { + batchOrderIds.push(...fallbackIds); + } + } const currentPrinterName = printerNameResult.data; const batchSummary = { ...groupSummary, @@ -2487,7 +2383,7 @@ class PrintService extends MainService { result: 'idempotent', print_task_code: normalizedPrintTaskCode, print_record_id: printRecordId, - print_status: 'printed', + print_status: 'unknown', }); } @@ -2497,7 +2393,7 @@ class PrintService extends MainService { result: 'ignored', print_task_code: normalizedPrintTaskCode, print_record_id: printRecordId, - print_status: 'printed', + print_status: 'unknown', }); } @@ -2507,7 +2403,7 @@ class PrintService extends MainService { const updatePayload = normalizedResult === 'success' ? { status: 'sent', - print_status: 'printed', + print_status: 'unknown', error_message: null, fail_code: null, print_time: normalizedPrintTime, @@ -2550,7 +2446,7 @@ class PrintService extends MainService { result: 'updated', print_task_code: normalizedPrintTaskCode, print_record_id: printRecordId, - print_status: updatePayload.print_status, + print_status: 'unknown', }); } diff --git a/app/service/systems/order_print.js b/app/service/systems/order_print.js index 02399b1..3db9e1a 100644 --- a/app/service/systems/order_print.js +++ b/app/service/systems/order_print.js @@ -890,6 +890,344 @@ class OrderPrintSystemService extends OrderBaseService { * @param {Array} payload.validWaveIds 有效波次ID列表。 * @return {Array} 规范化后的分组规则列表。 */ + /** + * 按运单号数组拉取平台打印中间态数据。 + * + * 与 getOrderPrintData 输出相同的 waveGroups 结构,但入参改为运单号数组。 + * 支持子单号(business_key > 1): + * - 主面单:与现有逻辑一致 + * - 子面单:使用主订单的订单数据构建打印数据,但在自定义区追加 "子单号【{business_key}】-{主单号}" 行 + * + * 仓库ID统一从当前上下文获取。 + * + * @param {Object} params 请求参数。 + * @param {Array} params.waybillCodes 运单号数组。 + * @return {Promise} 平台打印中间态结果。 + */ + async getPrintDataByWaybillCodes(params = {}) { + const requestParams = this.isPlainObject(params) ? params : {}; + const { waybillCodes } = requestParams; + + if (!Array.isArray(waybillCodes) || waybillCodes.length === 0) { + throw new Error('waybill_codes 必填,且必须为非空数组'); + } + + const normalizedWaybillCodes = Array.from(new Set( + waybillCodes.map(code => String(code || '').trim()).filter(Boolean) + )); + if (normalizedWaybillCodes.length === 0) { + throw new Error('waybill_codes 必填,且必须为非空数组'); + } + + const normalizedWarehouseId = this.getContextWarehouseId(); + + // 1. 按运单号查询运单记录(不限制 business_key,支持子单号) + const waybillRows = await this.queryWaybillsByCodes(normalizedWaybillCodes, normalizedWarehouseId); + if (waybillRows.length === 0) { + return { + summary: { total_waves: 0, total_orders: 0, total_platforms: 0 }, + waveGroups: [], + wave_ids: [], + ext: { + missing_waybill_codes: normalizedWaybillCodes, + filtered_waybill_codes: [], + }, + }; + } + + const foundWaybillCodeSet = new Set(waybillRows.map(r => String(r.waybill_code || '').trim())); + const missingWaybillCodes = normalizedWaybillCodes.filter(code => !foundWaybillCodeSet.has(code)); + + // 2. 提取所有涉及的订单ID,查询订单 + const orderIdSet = new Set(waybillRows.map(r => Number(r.order_id)).filter(id => id > 0)); + const orderIds = Array.from(orderIdSet); + const orderRows = await this.queryOrdersByIds(orderIds, normalizedWarehouseId); + const orderRowMap = new Map(orderRows.map(row => [ Number(row.id), row ])); + + // 过滤未找到订单的运单 + const validWaybillRows = waybillRows.filter(row => orderRowMap.has(Number(row.order_id))); + const invalidWaybillCodes = waybillRows + .filter(row => !orderRowMap.has(Number(row.order_id))) + .map(row => ({ + waybill_code: String(row.waybill_code || '').trim(), + reason: '关联订单未找到或不属于当前仓库', + })); + + if (validWaybillRows.length === 0) { + return { + summary: { total_waves: 0, total_orders: 0, total_platforms: 0 }, + waveGroups: [], + wave_ids: [], + ext: { + missing_waybill_codes: missingWaybillCodes, + filtered_waybill_codes: invalidWaybillCodes, + }, + }; + } + + // 3. 过滤 post_status !== 'fin' 的订单 + const validOrderIdSet = new Set( + orderRows + .filter(row => String(row.post_status || '').trim() === 'fin') + .map(row => Number(row.id)) + ); + const finalWaybillRows = validWaybillRows.filter(row => validOrderIdSet.has(Number(row.order_id))); + const filteredWaybillCodes = validWaybillRows + .filter(row => !validOrderIdSet.has(Number(row.order_id))) + .map(row => ({ + waybill_code: String(row.waybill_code || '').trim(), + reason: '关联订单快递未完全分配', + })); + + if (finalWaybillRows.length === 0) { + return { + summary: { total_waves: 0, total_orders: 0, total_platforms: 0 }, + waveGroups: [], + wave_ids: [], + ext: { + missing_waybill_codes: missingWaybillCodes, + filtered_waybill_codes: [ ...invalidWaybillCodes, ...filteredWaybillCodes ], + }, + }; + } + + // 4. 收集有效订单行 + const validOrderRows = Array.from( + new Map(orderRows.filter(row => validOrderIdSet.has(Number(row.id))).map(row => [ Number(row.id), row ])).values() + ); + + // 4b. 对命中的所有运单行做平台增强(主单和子单各自走自己的增强,密文/签名/参数按运单独立) + const waybillRowsForEnrich = finalWaybillRows.map(row => ({ ...row })); + const cainiaoEnrichedWaybillRows = await this.enrichCainiaoOrderExpressRows( + validOrderRows, waybillRowsForEnrich, normalizedWarehouseId + ); + const jdEnrichedWaybillRows = await this.enrichJdOrderExpressRows( + validOrderRows, cainiaoEnrichedWaybillRows, normalizedWarehouseId + ); + const enrichedWaybillRows = await this.enrichPddDyOrderExpressRows( + validOrderRows, jdEnrichedWaybillRows, normalizedWarehouseId + ); + // 构建 order_id → 增强后运单列表的映射(同一订单可能有多个运单) + const enrichedWaybillMap = new Map(); + for (const row of enrichedWaybillRows) { + const oid = Number(row.order_id); + if (!enrichedWaybillMap.has(oid)) { + enrichedWaybillMap.set(oid, []); + } + enrichedWaybillMap.get(oid).push(row); + } + + // 4c. 获取每个订单的主运单(business_key=1),用于子面单自定义区追加主运单号 + const mainWaybillMap = await this.getMainWaybillMapByOrderIds(orderIds, normalizedWarehouseId); + + // 5. 获取策略配置 + const policyConfigMap = await this.getPolicyConfigMapByStore(validOrderRows, normalizedWarehouseId); + + // 6. 拣货明细、波次序号等辅助数据 + const pickingCandidateRows = validOrderRows.filter(orderRow => { + const storeId = Number(orderRow.store_id || 0); + const policyConfig = policyConfigMap.get(storeId) || {}; + return this.shouldLoadPickingDetails(policyConfig); + }); + const printOrderRowMap = await this.buildPrintOrderRowMapWithPicking(pickingCandidateRows, normalizedWarehouseId); + + const validOrderWaveIds = Array.from(new Set(validOrderRows + .map(row => Number(row.wave_id || 0)) + .filter(waveId => Number.isInteger(waveId) && waveId > 0))); + const waveRows = await this.queryWavesByIds(normalizedWarehouseId, validOrderWaveIds); + + const orderIdsForIndex = validOrderRows.map(row => Number(row.id)).filter(id => id > 0); + const waveOrderIndexMap = await this.queryWaveOrderIndexMapByOrderIds( + orderIdsForIndex, normalizedWarehouseId, validOrderWaveIds + ); + const waveTotalOrderCountMap = await this.queryWaveTotalOrderCountMap(validOrderWaveIds, normalizedWarehouseId); + const templateSampleCache = new Map(); + + // 7. 为每个运单构建打印数据 + const orderPrintList = []; + for (const enrichedRow of enrichedWaybillRows) { + const orderId = Number(enrichedRow.order_id); + const orderRow = orderRowMap.get(orderId); + if (!orderRow) continue; + + const effectiveOrderRow = printOrderRowMap.get(orderId) || orderRow; + const waveOrderIndexInfo = waveOrderIndexMap.get(orderId) || {}; + const waveIdForCount = Number(effectiveOrderRow.wave_id || orderRow.wave_id || waveOrderIndexInfo.wave_id || 0); + const waveTotalOrders = Number(waveTotalOrderCountMap.get(waveIdForCount) || 0); + const waveIndex = Number(waveOrderIndexInfo.wave_index || 0); + const platformsIndex = Number(waveOrderIndexInfo.platforms_index || 0); + const effectiveOrderRowWithWaveIndex = { + ...effectiveOrderRow, + wave_total_orders: waveTotalOrders > 0 ? waveTotalOrders : 0, + wave_index: waveIndex > 0 ? waveIndex : 0, + platforms_index: platformsIndex > 0 ? platformsIndex : 0, + }; + + const storeId = Number(orderRow.store_id || 0); + const policyConfig = policyConfigMap.get(storeId) || {}; + const platformCode = this.resolvePrintPlatformCode(effectiveOrderRow, enrichedRow); + const templateSample = this.loadTemplateSampleByPlatform(platformCode, templateSampleCache); + + // 子面单:自定义区首行追加子单号标识 + const businessKey = Number(enrichedRow.business_key || 1); + const mainWaybill = mainWaybillMap.get(orderId); + const mainWaybillCode = mainWaybill ? String(mainWaybill.waybill_code || '').trim() : ''; + const isChildWaybill = businessKey > 1 && mainWaybillCode; + + const extraCustomLines = isChildWaybill + ? [ `子单号【${businessKey}】-${mainWaybillCode}` ] + : []; + + orderPrintList.push(await this.buildOrderPlatformPrintItem({ + orderRow: effectiveOrderRowWithWaveIndex, + orderExpress: enrichedRow, + policyConfig, + platformCode, + templateSample, + extraCustomLines, + })); + } + + // 8. 分组输出 + // 分离有波次和无波次的打印条目 + const wavedItems = orderPrintList.filter(item => Number(item && item.wave_id || 0) > 0); + const noWaveItems = orderPrintList.filter(item => Number(item && item.wave_id || 0) === 0); + + const waveGroups = this.groupOrderPrintItemsByWaveAndPlatform({ + waveRows, + hitWaveIds: validOrderWaveIds, + orderPrintList: wavedItems, + }); + + // 无波次条目按平台直接分组 + if (noWaveItems.length > 0) { + const noWavePlatforms = this.groupOrderPrintItemsByPlatform(noWaveItems); + waveGroups.push({ + wave_id: 0, + wave_no: '', + order_count: noWaveItems.length, + platforms: noWavePlatforms, + }); + // 将 0 加入 wave_ids 表示有无波次条目 + if (!validOrderWaveIds.includes(0)) { + validOrderWaveIds.push(0); + } + } + + const totalPlatforms = waveGroups.reduce((sum, waveGroup) => { + return sum + Number(waveGroup && waveGroup.platforms && waveGroup.platforms.length || 0); + }, 0); + + return { + summary: { + total_waves: waveGroups.length, + total_orders: orderPrintList.length, + total_platforms: totalPlatforms, + }, + waveGroups, + wave_ids: validOrderWaveIds, + ext: { + missing_waybill_codes: missingWaybillCodes, + filtered_waybill_codes: [ ...invalidWaybillCodes, ...filteredWaybillCodes ], + }, + }; + } + + /** + * 按运单号数组查询运单记录(不限制 business_key,支持子单号)。 + * + * @param {string[]} waybillCodes 运单号数组。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise>} 运单记录数组。 + */ + async queryWaybillsByCodes(waybillCodes = [], warehouseId) { + if (!Array.isArray(waybillCodes) || waybillCodes.length === 0) { + return []; + } + + const normalizedCodes = Array.from(new Set( + waybillCodes.map(code => String(code || '').trim()).filter(Boolean) + )); + if (normalizedCodes.length === 0) { + return []; + } + + const rows = await this.ctx.model.OrderExpress.findAll({ + attributes: [ + 'id', + 'order_id', + 'business_key', + 'waybill_code', + 'logistics_code', + 'logistics_name', + 'logistics_interface_id', + 'logistics_interface_name', + 'platform_code', + 'warehouse_id', + 'printinfo', + 'signature', + 'encryptprintinfo', + 'ver', + ], + where: { + waybill_code: { + [Op.in]: normalizedCodes, + }, + warehouse_id: warehouseId, + }, + order: [[ 'order_id', 'ASC' ], [ 'business_key', 'ASC' ], [ 'id', 'ASC' ]], + raw: true, + }); + + return Array.isArray(rows) ? rows : []; + } + + /** + * 按订单ID列表获取主运单映射(business_key=1)。 + * + * @param {number[]} orderIds 订单ID数组。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise>} order_id → 主运单记录。 + */ + async getMainWaybillMapByOrderIds(orderIds = [], warehouseId) { + const map = new Map(); + if (!Array.isArray(orderIds) || orderIds.length === 0) { + return map; + } + + const normalizedOrderIds = Array.from(new Set( + orderIds.map(id => Number(id)).filter(id => Number.isInteger(id) && id > 0) + )); + if (normalizedOrderIds.length === 0) { + return map; + } + + const rows = await this.ctx.model.OrderExpress.findAll({ + attributes: [ 'id', 'order_id', 'business_key', 'waybill_code' ], + where: { + order_id: { [Op.in]: normalizedOrderIds }, + warehouse_id: warehouseId, + business_key: 1, + }, + raw: true, + }); + + for (const row of rows) { + map.set(Number(row.order_id), row); + } + return map; + } + + /** + * 规范化"按分组解锁"规则。 + * + * @param {Object} payload 规则入参。 + * @param {Array} payload.groups 分组条件原始列表。 + * @param {string} payload.groupType 分组类型。 + * @param {string} payload.unlockScope 解锁范围。 + * @param {Array} payload.validWaveIds 有效波次ID列表。 + * @return {Array} 规范化后的分组规则列表。 + */ normalizeUnlockGroupRules(payload = {}) { const requestPayload = this.isPlainObject(payload) ? payload : {}; const groups = Array.isArray(requestPayload.groups) ? requestPayload.groups : []; @@ -1527,6 +1865,7 @@ class OrderPrintSystemService extends OrderBaseService { * 返回 business_key=1 的主运单,按 order_id、business_key、id 升序排列。 * * @param {number[]} orderIds 订单 ID 列表。 + * @param warehouseId * @return {Promise>} 匹配的运单记录数组,字段包含 id、order_id、business_key、waybill_code、 * logistics_code、logistics_name、logistics_interface_id、logistics_interface_name、platform_code、 * warehouse_id、printinfo、signature、encryptprintinfo、ver。 @@ -2648,6 +2987,7 @@ ${waveFilterSql} const policyConfig = this.isPlainObject(requestPayload.policyConfig) ? requestPayload.policyConfig : {}; const templateSample = this.isPlainObject(requestPayload.templateSample) ? requestPayload.templateSample : {}; const platformCode = String(requestPayload.platformCode || '').trim(); + const extraCustomLines = Array.isArray(requestPayload.extraCustomLines) ? requestPayload.extraCustomLines : []; // 查最匹配的包材名称(基于 items_hash) let suggestedPackageMaterialName = ''; @@ -2714,9 +3054,17 @@ ${waveFilterSql} taskId: requestId, documentId, packageMaterialName: suggestedPackageMaterialName, + extraCustomLines, }, }); const printData = this.extractSinglePlatformPrintData(printPayload); + // 子面单场景:同一运单号可能对应多个 business_key,注入 business_key 到返回文档中供调用方区分 + if (printData && typeof printData === 'object' && !Array.isArray(printData)) { + const expressBusinessKey = Number(orderExpress.business_key || 1); + if (expressBusinessKey > 1) { + printData.business_key = expressBusinessKey; + } + } return { wave_id: waveId, wave_no: String(orderRow.wave_no || '').trim(), diff --git a/test/app/schedule/print_retry_compensation.test.js b/test/app/schedule/print_retry_compensation.test.js deleted file mode 100644 index 7f8f99a..0000000 --- a/test/app/schedule/print_retry_compensation.test.js +++ /dev/null @@ -1,255 +0,0 @@ -'use strict'; - -const assert = require('node:assert/strict'); -const schedule = require('../../../app/schedule/print_retry_compensation'); - -describe('test/app/schedule/print_retry_compensation.test.js', () => { - it('should scan retryable records and invoke retryFailed grouped by warehouse', async () => { - assert.equal(schedule.schedule.interval, '30s'); - assert.equal(schedule.schedule.type, 'worker'); - assert.equal(schedule.schedule.immediate, false); - - const Op = { - and: Symbol('and'), - or: Symbol('or'), - in: Symbol('in'), - lte: Symbol('lte'), - lt: Symbol('lt'), - }; - - const retryCalls = []; - const ctx = { - app: { - _printRetryCompensationRunning: false, - _printRetryCompensationLastRunAt: 0, - config: { - printRetryCompensation: { - enable: true, - intervalMs: 0, - batchSize: 50, - force: false, - }, - }, - Sequelize: { - Op, - col(fieldName) { - return `col:${fieldName}`; - }, - }, - }, - logger: { - info() {}, - warn() {}, - error() {}, - }, - model: { - PrintRecord: { - async findAll(options) { - assert.equal(options.limit, 50); - assert.equal(options.raw, true); - return [ - { id: 101, warehouse_id: 1 }, - { id: 102, warehouse_id: 1 }, - { id: 201, warehouse_id: 2 }, - ]; - }, - }, - }, - service: { - systemMethods: { - print: { - async retryFailed(data) { - retryCalls.push(data); - return { - flag: 'success', - success_count: data.print_ids.length, - failed_count: 0, - skipped_count: 0, - }; - }, - }, - }, - }, - }; - - await schedule.task(ctx); - assert.equal(retryCalls.length, 2); - - const firstCall = retryCalls[0]; - const secondCall = retryCalls[1]; - assert.deepEqual(firstCall, { - print_ids: [ 101, 102 ], - warehouse_id: 1, - force: false, - }); - assert.deepEqual(secondCall, { - print_ids: [ 201 ], - warehouse_id: 2, - force: false, - }); - assert.equal(ctx.app._printRetryCompensationRunning, false); - }); - - it('should skip when disabled or already running', async () => { - let findAllCount = 0; - const ctx = { - app: { - _printRetryCompensationRunning: false, - _printRetryCompensationLastRunAt: 0, - config: { - printRetryCompensation: { - enable: false, - intervalMs: 60000, - batchSize: 10, - }, - }, - Sequelize: { - Op: {}, - col(fieldName) { - return `col:${fieldName}`; - }, - }, - }, - logger: { - info() {}, - warn() {}, - error() {}, - }, - model: { - PrintRecord: { - async findAll() { - findAllCount += 1; - return []; - }, - }, - }, - service: { - systemMethods: { - print: { - async retryFailed() { - throw new Error('should not reach'); - }, - }, - }, - }, - }; - - await schedule.task(ctx); - assert.equal(findAllCount, 0); - - ctx.app.config.printRetryCompensation.enable = true; - ctx.app._printRetryCompensationRunning = true; - await schedule.task(ctx); - assert.equal(findAllCount, 0); - }); - - it('should include retry_count < max_retry_count in where clause', async () => { - const Op = { - and: Symbol('and'), - or: Symbol('or'), - in: Symbol('in'), - lte: Symbol('lte'), - lt: Symbol('lt'), - }; - let whereClause; - const ctx = { - app: { - _printRetryCompensationRunning: false, - _printRetryCompensationLastRunAt: 0, - config: { printRetryCompensation: { enable: true, intervalMs: 0, batchSize: 50 } }, - Sequelize: { Op, col: fieldName => `col:${fieldName}` }, - }, - logger: { info() {}, warn() {}, error() {} }, - model: { - PrintRecord: { - async findAll(options) { - whereClause = options.where; - return []; - }, - }, - }, - service: { systemMethods: { print: { async retryFailed() {} } } }, - }; - - await schedule.task(ctx); - const andConditions = whereClause[Op.and]; - assert(Array.isArray(andConditions), 'where[Op.and] should be an array'); - const retryCountCondition = andConditions.find(condition => condition && condition.retry_count); - assert(retryCountCondition, 'retry_count condition should exist in where[Op.and]'); - assert.deepStrictEqual(retryCountCondition.retry_count, { [Op.lt]: 'col:max_retry_count' }); - }); - - it('should include next_retry_at <= now in where clause', async () => { - const Op = { - and: Symbol('and'), - or: Symbol('or'), - in: Symbol('in'), - lte: Symbol('lte'), - lt: Symbol('lt'), - }; - let whereClause; - const ctx = { - app: { - _printRetryCompensationRunning: false, - _printRetryCompensationLastRunAt: 0, - config: { printRetryCompensation: { enable: true, intervalMs: 0, batchSize: 50 } }, - Sequelize: { Op, col: () => {} }, - }, - logger: { info() {}, warn() {}, error() {} }, - model: { - PrintRecord: { - async findAll(options) { - whereClause = options.where; - return []; - }, - }, - }, - service: { systemMethods: { print: { async retryFailed() {} } } }, - }; - - await schedule.task(ctx); - const andConditions = whereClause[Op.and]; - assert(Array.isArray(andConditions), 'where[Op.and] should be an array'); - const nextRetryAtCondition = andConditions.find(condition => condition && condition.next_retry_at); - assert(nextRetryAtCondition, 'next_retry_at condition should exist in where[Op.and]'); - assert(nextRetryAtCondition.next_retry_at[Op.lte], 'should use lte operator'); - assert(nextRetryAtCondition.next_retry_at[Op.lte] instanceof Date, 'should compare with a Date object'); - }); - - it('should skip invalid records and not trigger retryFailed', async () => { - let retryFailedCalled = false; - const ctx = { - app: { - _printRetryCompensationRunning: false, - _printRetryCompensationLastRunAt: 0, - config: { printRetryCompensation: { enable: true, intervalMs: 0, batchSize: 50 } }, - Sequelize: { Op: {}, col: () => {} }, - }, - logger: { info() {}, warn() {}, error() {} }, - model: { - PrintRecord: { - async findAll() { - return [ - { id: 0, warehouse_id: 1 }, - { id: 1, warehouse_id: 0 }, - { id: -1, warehouse_id: 1 }, - { id: 1, warehouse_id: -1 }, - ]; - }, - }, - }, - service: { - systemMethods: { - print: { - async retryFailed() { - retryFailedCalled = true; - }, - }, - }, - }, - }; - - await schedule.task(ctx); - assert.equal(retryFailedCalled, false, 'retryFailed should not be called for invalid records'); - }); -}); diff --git a/test/app/service/systemMethods/print.send.test.js b/test/app/service/systemMethods/print.send.test.js index 831a06a..b219e74 100644 --- a/test/app/service/systemMethods/print.send.test.js +++ b/test/app/service/systemMethods/print.send.test.js @@ -1187,203 +1187,6 @@ describe('test/app/service/systemMethods/print.send.test.js', () => { assert.equal(calls.sendToComputerPayloads.length, 0); }); - it('retryFailed 应补打 failed 记录并创建新记录', async () => { - const sourceRecordId = 12001; - const { ctx, calls, state } = createContext({ - initialPrintRecords: [ - { - id: sourceRecordId, - warehouse_id: 100000, - computer_id: 'PC-STATION-001', - printer: 'PRN-STO', - type: 'express', - status: 'failed', - send_status: 'send_failed', - print_status: 'unknown', - data: { - printer: 'PRN-STO', - component: '菜鸟', - type: 'express', - data: { - task: { - taskID: 'OLD_TASK_ID', - documents: [], - }, - }, - }, - request_code: 'REQ-RETRY-001', - wave_id: 11, - wave_no: 'WAVE-11', - platform_code: 'cainiao', - platform_name: '菜鸟平台', - sys_logistics_code: 'STO', - sys_logistics_name: '申通', - }, - ], - sendToComputer: async payload => { - calls.sendToComputerPayloads.push(payload); - return { status: 'success' }; - }, - }); - const service = new PrintService(ctx); - - const result = await service.retryFailed({ - print_ids: [ sourceRecordId ], - }); - - assert.equal(result.flag, 'success'); - assert.equal(result.success_count, 1); - assert.equal(result.failed_count, 0); - assert.equal(result.skipped_count, 0); - assert.equal(result.retried.length, 1); - assert.equal(result.retried[0].source_print_id, sourceRecordId); - assert.equal(result.retried[0].status, 'sent'); - assert.equal(calls.printRecordCreatePayloads.length, 1); - assert.equal(calls.sendToComputerPayloads.length, 1); - assert.equal(calls.printRecordCreatePayloads[0].retry_of_print_id, sourceRecordId); - - const newRecordId = result.retried[0].new_print_id; - const newRecord = state.printRecordsById[newRecordId]; - assert.ok(newRecord); - assert.equal(newRecord.retry_of_print_id, sourceRecordId); - assert.equal(newRecord.status, 'sent'); - assert.equal(newRecord.send_status, 'sent'); - assert.equal(newRecord.print_status, 'printed'); - assert.notEqual(newRecord.data.data.task.taskID, 'OLD_TASK_ID'); - assert.equal(newRecord.data.data.task.taskID, result.retried[0].task_code); - assert.equal(state.printRecordsById[sourceRecordId].status, 'failed'); - }); - - it('retryFailed 应跳过 sent/printed 记录', async () => { - const sourceRecordId = 12002; - const { ctx, calls } = createContext({ - initialPrintRecords: [ - { - id: sourceRecordId, - warehouse_id: 100000, - computer_id: 'PC-STATION-001', - printer: 'PRN-STO', - type: 'express', - status: 'sent', - send_status: 'sent', - print_status: 'printed', - data: { - printer: 'PRN-STO', - component: '菜鸟', - type: 'express', - data: { - task: { - taskID: 'TASK-SENT-001', - documents: [], - }, - }, - }, - }, - ], - }); - const service = new PrintService(ctx); - - const result = await service.retryFailed({ - print_ids: [ sourceRecordId ], - }); - - assert.equal(result.flag, 'success'); - assert.equal(result.success_count, 0); - assert.equal(result.failed_count, 0); - assert.equal(result.skipped_count, 1); - assert.equal(result.skipped[0].print_id, sourceRecordId); - assert.match(result.skipped[0].reason, /跳过|不允许补打/); - assert.equal(calls.printRecordCreatePayloads.length, 0); - assert.equal(calls.sendToComputerPayloads.length, 0); - }); - - it('retryFailed 部分成功时应返回正确统计', async () => { - const sourceSuccessId = 12003; - const sourceFailId = 12004; - const sourceSkipId = 12005; - const { ctx, calls, state } = createContext({ - initialPrintRecords: [ - { - id: sourceSuccessId, - warehouse_id: 100000, - computer_id: 'PC-STATION-001', - printer: 'PRN-STO', - type: 'express', - status: 'failed', - send_status: 'send_failed', - print_status: 'unknown', - data: { - printer: 'PRN-STO', - component: '菜鸟', - type: 'express', - data: { task: { taskID: 'TASK-OLD-SUCCESS', documents: [] } }, - }, - }, - { - id: sourceFailId, - warehouse_id: 100000, - computer_id: 'PC-STATION-001', - printer: 'PRN-YTO', - type: 'express', - status: 'failed', - send_status: 'send_failed', - print_status: 'unknown', - data: { - printer: 'PRN-YTO', - component: '拼多多', - type: 'express', - data: { task: { taskID: 'TASK-OLD-FAIL', documents: [] } }, - }, - }, - { - id: sourceSkipId, - warehouse_id: 100000, - computer_id: 'PC-STATION-001', - printer: 'PRN-STO', - type: 'express', - status: 'sent', - send_status: 'sent', - print_status: 'unknown', - data: { - printer: 'PRN-STO', - component: '菜鸟', - type: 'express', - data: { task: { taskID: 'TASK-SKIP', documents: [] } }, - }, - }, - ], - sendToComputer: async payload => { - calls.sendToComputerPayloads.push(payload); - if (calls.sendToComputerPayloads.length === 2) { - return { - status: 'failure', - error: '发送失败-模拟', - }; - } - return { status: 'success' }; - }, - }); - const service = new PrintService(ctx); - - const result = await service.retryFailed({ - print_ids: [ sourceSuccessId, sourceFailId, sourceSkipId ], - }); - - assert.equal(result.flag, 'success'); - assert.equal(result.success_count, 1); - assert.equal(result.failed_count, 1); - assert.equal(result.skipped_count, 1); - assert.equal(result.retried.length, 2); - assert.equal(calls.printRecordCreatePayloads.length, 2); - assert.equal(calls.sendToComputerPayloads.length, 2); - assert.equal(state.printRecordsById[sourceSuccessId].status, 'failed'); - assert.equal(state.printRecordsById[sourceFailId].status, 'failed'); - assert.equal(state.printRecordsById[sourceSkipId].status, 'sent'); - const failedRetryItem = result.retried.find(item => item.source_print_id === sourceFailId); - assert.ok(failedRetryItem); - assert.equal(failedRetryItem.status, 'failed'); - }); - it('handlePrintCallback success 回调应更新为 printed', async () => { const { ctx, state, calls } = createContext(); const service = new PrintService(ctx); From bd6013d7b863e90f12cc0a9c20821ff2a3a7e034 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sat, 1 Aug 2026 03:45:06 +0800 Subject: [PATCH 142/550] =?UTF-8?q?fix(order):=20=E6=8B=A3=E8=B4=A7/?= =?UTF-8?q?=E6=B3=A2=E6=AC=A1/=E5=A4=8D=E6=A0=B8/=E6=89=93=E5=8C=85/?= =?UTF-8?q?=E8=87=AA=E5=8A=A8=E5=87=BA=E5=BA=93=E4=BF=AE=E5=A4=8D=E4=B8=8E?= =?UTF-8?q?=E5=A2=9E=E5=BC=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - pick.js: 修复拣货车绑定逻辑,禁止已绑定任务直接换车 - wave.js: 修复波次拣货车查询(移除 current_task_id) - recheckOrder.js: 新增 batchQuickRecheckByWave 按波次批量快速复核 - order_packing.js: 时间字段统一格式化输出 - order_auto_outbound.js: 修复仓库去重逻辑 --- .../systemMethods/order/recheckOrder.js | 361 +++++++++++++----- app/service/systemMethods/order/wave.js | 68 ++-- app/service/systems/order_auto_outbound.js | 33 +- app/service/systems/order_packing.js | 14 +- app/service/systems/pick.js | 146 +++---- 5 files changed, 389 insertions(+), 233 deletions(-) diff --git a/app/service/systemMethods/order/recheckOrder.js b/app/service/systemMethods/order/recheckOrder.js index 4373342..0fd95fd 100644 --- a/app/service/systemMethods/order/recheckOrder.js +++ b/app/service/systemMethods/order/recheckOrder.js @@ -10,9 +10,9 @@ class RecheckOrderService extends OrderBaseService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'scanOrder,scanTask,scanWaybill,confirmRecheck,recheckOrderList,confirmIntercept,batchQuickRecheck,queryRecheckOrderSingleList'; - const _noNeedLog = 'scanOrder,scanTask,scanWaybill,confirmRecheck,recheckOrderList,confirmIntercept,batchQuickRecheck'; - const _noNeedAuth = 'scanOrder,scanTask,scanWaybill,confirmRecheck,recheckOrderList,confirmIntercept,batchQuickRecheck,queryRecheckOrderSingleList'; + const _noNeedRight = 'scanOrder,scanTask,scanWaybill,confirmRecheck,recheckOrderList,confirmIntercept,batchQuickRecheck,batchQuickRecheckByWave,queryRecheckOrderSingleList'; + const _noNeedLog = 'scanOrder,scanTask,scanWaybill,confirmRecheck,recheckOrderList,confirmIntercept,batchQuickRecheck,batchQuickRecheckByWave'; + const _noNeedAuth = 'scanOrder,scanTask,scanWaybill,confirmRecheck,recheckOrderList,confirmIntercept,batchQuickRecheck,batchQuickRecheckByWave,queryRecheckOrderSingleList'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -79,6 +79,7 @@ class RecheckOrderService extends OrderBaseService { match_type: matchType, list_type: 'group', waybill_no: keyword, + wave_id: orderWaveId, picker_id: pickerInfo.picker_id, picker_name: pickerInfo.picker_name, task_id: groupTaskId, @@ -2293,21 +2294,7 @@ class RecheckOrderService extends OrderBaseService { async unbindCartForTask(taskId, warehouseId, operatorUserId) { const { ctx } = this; - // 1. 清空波次拣货任务的车绑定信息 - await ctx.model.query( - `UPDATE wms_wave_pick_task - SET current_cart_id = NULL, - current_cart_code_snapshot = NULL, - update_time = NOW() - WHERE id = :taskId - AND warehouse_id = :warehouseId`, - { - replacements: { taskId, warehouseId }, - type: ctx.model.QueryTypes.UPDATE, - } - ); - - // 2. 停用拣货车绑定记录 + // 停用拣货车绑定记录 await ctx.model.query( `UPDATE wms_pick_task_cart_binding SET is_active = 0, @@ -2322,21 +2309,6 @@ class RecheckOrderService extends OrderBaseService { type: ctx.model.QueryTypes.UPDATE, } ); - - // 3. 释放拣货车(清空当前任务和绑定用户) - await ctx.model.query( - `UPDATE wms_pick_cart - SET current_task_id = NULL, - bind_user_id = NULL, - last_seen_time = NOW(), - update_time = NOW() - WHERE warehouse_id = :warehouseId - AND current_task_id = :taskId`, - { - replacements: { taskId, warehouseId }, - type: ctx.model.QueryTypes.UPDATE, - } - ); } /** @@ -2596,16 +2568,44 @@ class RecheckOrderService extends OrderBaseService { /** * 通过车号查找匹配的拣货任务行。 * 匹配优先级: - * 1. wms_wave_pick_task.current_cart_code_snapshot(任务主表车号快照) - * 2. wms_wave_pick_task_order.cart_code_snapshot(任务订单行车号快照,仅散单模式有数据) - * 3. wms_pick_task_cart_binding(车任务绑定表,所有模式均有记录,回退兜底) + * 1. wms_pick_task_cart_binding(车任务绑定表,unbind_time IS NULL,权威数据源) + * 2. wms_wave_pick_task.current_cart_code_snapshot / wms_wave_pick_task_order.cart_code_snapshot(快照回退兜底) * @param {string} cartCode 车号。 * @param {number} warehouseId 仓库ID。 * @return {Promise} 任务行,未找到返回 null。 */ const findTaskByCartCode = async (cartCode, warehouseId) => { - // 第一优先级:任务主表车号快照 + 任务订单行车号快照 - const primaryRows = await ctx.model.query( + // 第一优先级:车任务绑定表(权威活跃绑定数据源,unbind_time IS NULL 表示未解绑) + const bindingRows = await ctx.model.query( + ` + SELECT + t.id AS task_id, + t.task_no, + t.pick_mode, + t.status, + t.review_status, + t.current_cart_code_snapshot + FROM wms_pick_task_cart_binding b + INNER JOIN wms_wave_pick_task t + ON t.id = b.task_id + WHERE b.cart_code_snapshot = :cartCode + AND b.warehouse_id = :warehouseId + AND b.unbind_time IS NULL + ORDER BY b.create_time DESC, b.id DESC + LIMIT 1 + `, + { + replacements: { warehouseId, cartCode }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + if (Array.isArray(bindingRows) && bindingRows.length > 0) { + return bindingRows[0]; + } + + // 第二优先级(回退兜底):任务主表 + 任务订单行快照 + const snapshotRows = await ctx.model.query( ` SELECT t.id AS task_id, @@ -2634,36 +2634,7 @@ class RecheckOrderService extends OrderBaseService { } ); - if (Array.isArray(primaryRows) && primaryRows.length > 0) { - return primaryRows[0]; - } - - // 第二优先级(回退):车任务绑定表(覆盖小团购等无 wms_wave_pick_task_order 记录的场景) - const bindingRows = await ctx.model.query( - ` - SELECT - t.id AS task_id, - t.task_no, - t.pick_mode, - t.status, - t.review_status, - t.current_cart_code_snapshot - FROM wms_pick_task_cart_binding b - INNER JOIN wms_wave_pick_task t - ON t.id = b.task_id - WHERE b.cart_code_snapshot = :cartCode - AND b.warehouse_id = :warehouseId - AND b.is_active = 1 - ORDER BY b.create_time DESC, b.id DESC - LIMIT 1 - `, - { - replacements: { warehouseId, cartCode }, - type: ctx.model.QueryTypes.SELECT, - } - ); - - return (Array.isArray(bindingRows) && bindingRows.length > 0) ? bindingRows[0] : null; + return (Array.isArray(snapshotRows) && snapshotRows.length > 0) ? snapshotRows[0] : null; }; const taskRow = await findTaskByCartCode(cartCode, warehouseId); @@ -3661,6 +3632,200 @@ class RecheckOrderService extends OrderBaseService { }; } + /** + * 规范波次 ID 入参,兼容 wave_ids、waveIds、wave_id 等写法。 + * @param {Object} data 请求体。 + * @return {number[]} 波次 ID 列表。 + */ + normalizeWaveIds(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const rawIds = requestData.wave_ids; + const sourceIds = []; + + if (Array.isArray(rawIds)) { + sourceIds.push(...rawIds); + } else if (typeof rawIds === 'string') { + sourceIds.push(...rawIds.split(',')); + } else if (rawIds !== undefined && rawIds !== null && rawIds !== '') { + sourceIds.push(rawIds); + } else if (requestData.waveIds !== undefined && requestData.waveIds !== null && requestData.waveIds !== '') { + const val = requestData.waveIds; + if (Array.isArray(val)) sourceIds.push(...val); + else if (typeof val === 'string') sourceIds.push(...val.split(',')); + else sourceIds.push(val); + } else if (requestData.wave_id !== undefined && requestData.wave_id !== null && requestData.wave_id !== '') { + sourceIds.push(requestData.wave_id); + } + + const normalizedIds = []; + for (const value of sourceIds) { + const normalizedId = Number(String(value).trim()); + if (Number.isFinite(normalizedId) && normalizedId > 0) { + normalizedIds.push(normalizedId); + } + } + + return Array.from(new Set(normalizedIds)); + } + + /** + * 按波次批量快捷复核:传入波次 IDs 列表,对每个波次下所有有效订单执行前置检查 + * (已分配储位、已分配快递、已同步且未被拦截),必要时自动完成拣货(含库存锁定校验与扣减、 + * 库存流水写入、拣货任务状态同步)后标记复核(含复核任务记录、任务复核状态更新、车任务解绑、 + * 操作日志)。每个订单在独立事务中执行,支持部分失败,不满足条件的订单跳过并返回原因。 + * + * @param {Object} data 请求体。 + * @param {number[]|string} [data.wave_ids] 波次 ID 列表,支持数组或以逗号分隔的字符串。 + * @param {number[]|string} [data.waveIds] 波次 ID 列表别名(驼峰写法)。 + * @param {number} [data.wave_id] 单个波次 ID。 + * @return {Promise} 处理结果,包含 success/failed 列表及计数。 + */ + async batchQuickRecheckByWave(data = {}) { + const { ctx } = this; + const warehouseId = this.getWarehouseId(); + const waveIds = this.normalizeWaveIds(data); + + if (waveIds.length === 0) { + this.ctx.throw(400, '波次ID列表不能为空'); + } + + // ── 1. 批量查询所有波次下的订单 ── + const orderModel = await this.getOrderModel('order', warehouseId); + const orderRows = await orderModel.findAll({ + where: { + wave_id: { [this.app.Sequelize.Op.in]: waveIds }, + warehouse_id: warehouseId, + }, + attributes: [ + 'id', 'delivery_order_code', 'pre_delivery_order_code', + 'storage_status', 'post_status', 'sync_status', 'status', 'intercept_status', + 'pick_status', 'recheck_status', 'wave_id', 'wave_no', + ], + raw: true, + }); + + // 按 wave_id 分组 + const waveOrderMap = new Map(); + for (const row of orderRows) { + const wid = Number(row.wave_id); + if (!waveOrderMap.has(wid)) { + waveOrderMap.set(wid, []); + } + waveOrderMap.get(wid).push(row); + } + + // ── 2. 前置条件检查:逐波次、逐订单校验 ── + const allSuccessOrders = []; + const allFailedOrders = []; + + for (const waveId of waveIds) { + const waveOrders = waveOrderMap.get(waveId) || []; + + if (waveOrders.length === 0) { + allFailedOrders.push({ + wave_id: waveId, + reason: '波次下无订单', + }); + continue; + } + + const validOrders = []; + + for (const order of waveOrders) { + const orderId = Number(order.id); + + const interceptStatus = String(order.intercept_status || '').trim(); + if (interceptStatus === 'intercepted' || interceptStatus === 'intercepted_at_warehouse') { + allFailedOrders.push({ + order_id: orderId, + wave_id: waveId, + delivery_order_code: String(order.delivery_order_code || order.pre_delivery_order_code || '').trim(), + reason: '已拦截', + }); + continue; + } + + const storageStatus = String(order.storage_status || '').trim(); + if (storageStatus !== 'fin') { + allFailedOrders.push({ + order_id: orderId, + wave_id: waveId, + delivery_order_code: String(order.delivery_order_code || order.pre_delivery_order_code || '').trim(), + reason: '未分配储位', + }); + continue; + } + + const postStatus = String(order.post_status || '').trim(); + if (postStatus !== 'fin') { + allFailedOrders.push({ + order_id: orderId, + wave_id: waveId, + delivery_order_code: String(order.delivery_order_code || order.pre_delivery_order_code || '').trim(), + reason: '没有分配快递', + }); + continue; + } + + const syncStatus = String(order.sync_status || '').trim(); + if (syncStatus !== 'fin') { + allFailedOrders.push({ + order_id: orderId, + wave_id: waveId, + delivery_order_code: String(order.delivery_order_code || order.pre_delivery_order_code || '').trim(), + reason: '没有同步', + }); + continue; + } + + validOrders.push(order); + } + + // ── 3. 逐订单在独立事务中执行拣货完成 + 复核标记 ── + for (const order of validOrders) { + const orderId = Number(order.id); + + try { + await ctx.model.transaction(async transaction => { + // 3a. 若未完成拣货,先执行拣货完成流程 + const pickStatus = String(order.pick_status || '').trim(); + if (pickStatus !== 'fin') { + await this._completePickForOrder(orderId, warehouseId, transaction); + // 更新内存中的 pick_status,避免后续 _markRecheckForOrder 因旧值误判 + order.pick_status = 'fin'; + } + + // 3b. 标记复核 + await this._markRecheckForOrder(order, warehouseId, transaction); + }); + + allSuccessOrders.push({ + order_id: orderId, + wave_id: Number(order.wave_id) || waveId, + delivery_order_code: String(order.delivery_order_code || order.pre_delivery_order_code || '').trim(), + }); + } catch (error) { + ctx.logger.warn( + `[batchQuickRecheckByWave] 订单复核失败, orderId=${orderId}, waveId=${waveId}, error=${error.message}` + ); + allFailedOrders.push({ + order_id: orderId, + wave_id: waveId, + delivery_order_code: String(order.delivery_order_code || order.pre_delivery_order_code || '').trim(), + reason: `复核失败: ${error.message}`, + }); + } + } + } + + return { + success: allSuccessOrders, + failed: allFailedOrders, + success_count: allSuccessOrders.length, + failed_count: allFailedOrders.length, + }; + } + /** * 完成单个订单的拣货流程(内部方法,在事务中执行)。 * 包含:更新拣货任务订单状态、订单拣货状态、拣货记录状态、扣减库存锁定数量与可用数量、写库存流水。 @@ -4294,6 +4459,31 @@ class RecheckOrderService extends OrderBaseService { `[batchQuickRecheck] 解绑车任务失败(复核已成功), taskId=${taskId}, orderId=${orderId}, error=${unbindError.message}` ); } + + // 更新 wms_wave_pick_task 任务状态:status=3(已完成),review_status=3(复核通过) + const operatorName = String(operator.name || '').trim(); + const taskStatusSetClauses = [ + 'status = 3', + 'review_status = 3', + 'review_finish_time = :now', + 'review_time = :now', + 'update_time = NOW()', + ]; + if (operatorUserId > 0) { + taskStatusSetClauses.push('review_user_id = :operatorUserId'); + taskStatusSetClauses.push('review_user_name = :operatorName'); + } + await ctx.model.query( + `UPDATE wms_wave_pick_task + SET ${taskStatusSetClauses.join(',\n ')} + WHERE id = :taskId + AND warehouse_id = :warehouseId`, + { + replacements: { taskId, warehouseId, operatorUserId, operatorName, now }, + type: ctx.model.QueryTypes.UPDATE, + transaction, + } + ); } /** @@ -4308,21 +4498,6 @@ class RecheckOrderService extends OrderBaseService { async _unbindCartForTaskInTransaction(taskId, warehouseId, operatorUserId, transaction) { const { ctx } = this; - // 清空波次拣货任务的车绑定信息 - await ctx.model.query( - `UPDATE wms_wave_pick_task - SET current_cart_id = NULL, - current_cart_code_snapshot = NULL, - update_time = NOW() - WHERE id = :taskId - AND warehouse_id = :warehouseId`, - { - replacements: { taskId, warehouseId }, - type: ctx.model.QueryTypes.UPDATE, - transaction, - } - ); - // 停用拣货车绑定记录 await ctx.model.query( `UPDATE wms_pick_task_cart_binding @@ -4339,26 +4514,6 @@ class RecheckOrderService extends OrderBaseService { transaction, } ); - - // 释放拣货车 - await ctx.model.query( - `UPDATE wms_pick_cart - SET status = 'idle', - current_task_id = NULL, - update_time = NOW() - WHERE id IN ( - SELECT cart_id - FROM wms_pick_task_cart_binding - WHERE task_id = :taskId - AND warehouse_id = :warehouseId - ) - AND warehouse_id = :warehouseId`, - { - replacements: { taskId, warehouseId }, - type: ctx.model.QueryTypes.UPDATE, - transaction, - } - ); } /** diff --git a/app/service/systemMethods/order/wave.js b/app/service/systemMethods/order/wave.js index 34b5014..e42038d 100644 --- a/app/service/systemMethods/order/wave.js +++ b/app/service/systemMethods/order/wave.js @@ -11347,7 +11347,7 @@ class WaveService extends OrderBaseService { : 0; const cartRows = await this.ctx.model.query(` - SELECT id, cart_code, current_task_id + SELECT id, cart_code FROM wms_pick_cart WHERE id = :cartId AND warehouse_id = :warehouseId @@ -11367,9 +11367,31 @@ class WaveService extends OrderBaseService { throw new Error(`拣货车不存在或已停用: ${cartId}`); } - const activeTaskId = Number(cartRow.current_task_id || 0); - if (activeTaskId > 0 && activeTaskId !== taskId) { - throw new Error(`拣货车已被任务占用: ${cartId}`); + // 通过绑定表判断车是否被其他活跃任务占用(不依赖 wms_pick_cart.current_task_id) + const bindingRows = await this.ctx.model.query(` + SELECT b.task_id + FROM wms_pick_task_cart_binding b + INNER JOIN wms_wave_pick_task t ON t.id = b.task_id + WHERE b.cart_id = :cartId + AND b.warehouse_id = :warehouseId + AND b.is_active = 1 + AND t.status IN (0, 1) + LIMIT 1 + FOR UPDATE + `, { + replacements: { + cartId, + warehouseId, + }, + type: this.ctx.model.QueryTypes.SELECT, + transaction, + }); + + const activeBindingTaskId = Number( + (Array.isArray(bindingRows) && bindingRows.length > 0 ? bindingRows[0]?.task_id : 0) + ); + if (activeBindingTaskId > 0 && activeBindingTaskId !== taskId) { + throw new Error(`拣货车已被活动任务占用: ${cartId}`); } await this.bulkInsertRows('wms_pick_task_cart_binding', [{ @@ -11385,25 +11407,6 @@ class WaveService extends OrderBaseService { unbind_time: null, }], transaction); - await this.ctx.model.query(` - UPDATE wms_pick_cart - SET - current_task_id = :taskId, - bind_user_id = :operatorId, - last_bind_time = NOW(), - last_seen_time = NOW() - WHERE id = :cartId - AND warehouse_id = :warehouseId - `, { - replacements: { - taskId, - operatorId, - cartId, - warehouseId, - }, - transaction, - }); - await this.ctx.model.query(` UPDATE wms_wave_pick_task SET @@ -12171,8 +12174,6 @@ class WaveService extends OrderBaseService { SET status = 9, wave_count = 0, - current_cart_id = NULL, - current_cart_code_snapshot = NULL, ${hasCancelledAtColumn ? 'cancelled_at = NOW(),' : ''} update_time = NOW() WHERE id = :taskId @@ -12204,23 +12205,6 @@ class WaveService extends OrderBaseService { transaction, }); - await this.ctx.model.query(` - UPDATE wms_pick_cart - SET - current_task_id = NULL, - bind_user_id = NULL, - last_seen_time = NOW(), - update_time = NOW() - WHERE warehouse_id = :warehouseId - AND current_task_id = :taskId - `, { - replacements: { - taskId, - warehouseId, - }, - transaction, - }); - await this.bulkInsertRows('wms_wave_pick_action_log', [{ task_id: taskId, warehouse_id: warehouseId, diff --git a/app/service/systems/order_auto_outbound.js b/app/service/systems/order_auto_outbound.js index 0b1dd68..6647379 100644 --- a/app/service/systems/order_auto_outbound.js +++ b/app/service/systems/order_auto_outbound.js @@ -55,21 +55,26 @@ class OrderAutoOutboundService extends MainService { raw: true, }); - for (const contract of contracts) { - result.push({ - storeId: store.id, - warehouseId: contract.warehouse_id, - rules: autoOutboundRules, - }); - } + // 始终将 store.id 自身的仓库加入扫描(store.id 即 warehouse_id) + const scannedWarehouseIds = new Set(); + result.push({ + storeId: store.id, + warehouseId: store.id, + rules: autoOutboundRules, + }); + scannedWarehouseIds.add(store.id); - // 兜底:仓库自身没有 StoreWarehouse 合同关系时,直接用 store.id 作为 warehouseId - if (contracts.length === 0) { - result.push({ - storeId: store.id, - warehouseId: store.id, - rules: autoOutboundRules, - }); + // 追加外部合同中的仓库(去重) + for (const contract of contracts) { + const contractWarehouseId = contract.warehouse_id; + if (!scannedWarehouseIds.has(contractWarehouseId)) { + result.push({ + storeId: store.id, + warehouseId: contractWarehouseId, + rules: autoOutboundRules, + }); + scannedWarehouseIds.add(contractWarehouseId); + } } } diff --git a/app/service/systems/order_packing.js b/app/service/systems/order_packing.js index 61cc6df..1bc2220 100644 --- a/app/service/systems/order_packing.js +++ b/app/service/systems/order_packing.js @@ -360,8 +360,14 @@ class OrderPackingService extends Service { const list = rows.map(row => { const plain = row.get({ plain: true }); const rawVideos = plain.videos || []; + const { app: appCtx } = this; return { ...plain, + start_time: plain.start_time ? appCtx.formatDate(plain.start_time) : null, + end_time: plain.end_time ? appCtx.formatDate(plain.end_time) : null, + create_time: plain.create_time ? appCtx.formatDate(plain.create_time) : null, + update_time: plain.update_time ? appCtx.formatDate(plain.update_time) : null, + deleted_at: plain.deleted_at ? appCtx.formatDate(plain.deleted_at) : null, workbench_name: plain.workbench?.name || null, workbench_type: plain.workbench?.type || null, workbench_barcode: plain.workbench?.barcode || null, @@ -465,8 +471,14 @@ class OrderPackingService extends Service { const plain = record.get({ plain: true }); const recordingComputerId = await this._getRecordingComputerId(warehouseId); const rawVideos = plain.videos || []; + const { app: appCtx } = this; const data = { ...plain, + start_time: plain.start_time ? appCtx.formatDate(plain.start_time) : null, + end_time: plain.end_time ? appCtx.formatDate(plain.end_time) : null, + create_time: plain.create_time ? appCtx.formatDate(plain.create_time) : null, + update_time: plain.update_time ? appCtx.formatDate(plain.update_time) : null, + deleted_at: plain.deleted_at ? appCtx.formatDate(plain.deleted_at) : null, workbench_name: plain.workbench?.name || null, workbench_type: plain.workbench?.type || null, workbench_barcode: plain.workbench?.barcode || null, @@ -549,7 +561,7 @@ class OrderPackingService extends Service { message: '结束时间设置成功', data: { id: record.id, - end_time: updates.end_time, + end_time: this.app.formatDate(updates.end_time), status: updates.status, }, }; diff --git a/app/service/systems/pick.js b/app/service/systems/pick.js index b87d322..832f995 100644 --- a/app/service/systems/pick.js +++ b/app/service/systems/pick.js @@ -2376,11 +2376,44 @@ class PickSystemService extends Service { const targetCartId = Number(targetCartRow.cart_id || 0); const targetCartCode = String(targetCartRow.cart_code || '').trim(); - const previousCartId = Number(taskRow && taskRow.current_cart_id || 0); - const bindType = previousCartId > 0 && previousCartId !== targetCartId ? 2 : 1; const transaction = await ctx.model.transaction(); try { + // 检查任务是否已有活跃的车绑定(正常绑定流程,不支持换车,需先解绑) + const taskActiveBindingRows = await ctx.model.query(` + SELECT + b.id, + b.cart_id, + t.current_cart_code_snapshot AS cart_code + FROM wms_pick_task_cart_binding b + INNER JOIN wms_wave_pick_task t + ON t.id = b.task_id + WHERE b.task_id = :taskId + AND b.warehouse_id = :warehouseId + AND b.is_active = 1 + ORDER BY b.id DESC + LIMIT 1 + `, { + replacements: { + taskId, + warehouseId, + }, + type: ctx.model.QueryTypes.SELECT, + transaction, + }); + + const taskActiveBinding = Array.isArray(taskActiveBindingRows) && taskActiveBindingRows.length > 0 + ? taskActiveBindingRows[0] + : null; + if (taskActiveBinding) { + throw this.createBusinessError('任务已绑定拣货车,请先解绑后再重新绑定', 409, { + task_id: taskId, + cart_id: Number(taskActiveBinding.cart_id || 0), + cart_code: String(taskActiveBinding.cart_code || '').trim() || null, + }); + } + + // 检查车是否已有活跃的任务绑定 const cartActiveBindingRows = await ctx.model.query(` SELECT b.id, @@ -2404,58 +2437,29 @@ class PickSystemService extends Service { transaction, }); - const activeBinding = Array.isArray(cartActiveBindingRows) && cartActiveBindingRows.length > 0 + const cartActiveBinding = Array.isArray(cartActiveBindingRows) && cartActiveBindingRows.length > 0 ? cartActiveBindingRows[0] : null; - const bindingTaskId = Number(activeBinding && activeBinding.task_id || 0); - const bindingTaskStatus = Number(activeBinding && activeBinding.task_status || 0); - if (bindingTaskId > 0 && bindingTaskId !== taskId && [ 0, 1 ].includes(bindingTaskStatus)) { - throw this.createBusinessError('该拣货车已绑定其他活动任务,无法重复绑定', 409, { - task_id: bindingTaskId, - task_no: String(activeBinding && activeBinding.task_no || '').trim() || null, - cart_id: targetCartId, - cart_code: targetCartCode, - }); + if (cartActiveBinding) { + const boundTaskId = Number(cartActiveBinding.task_id || 0); + const boundTaskStatus = Number(cartActiveBinding.task_status || 0); + if (boundTaskId === taskId) { + throw this.createBusinessError('该任务已绑定此拣货车,无需重复绑定', 409, { + task_id: taskId, + cart_id: targetCartId, + cart_code: targetCartCode, + }); + } + if ([ 0, 1 ].includes(boundTaskStatus)) { + throw this.createBusinessError('该拣货车已绑定其他活动任务,请先解绑后再重新绑定', 409, { + task_id: boundTaskId, + task_no: String(cartActiveBinding.task_no || '').trim() || null, + cart_id: targetCartId, + cart_code: targetCartCode, + }); + } } - if (previousCartId > 0 && previousCartId !== targetCartId) { - await ctx.model.query(` - UPDATE wms_pick_cart - SET current_task_id = NULL, - bind_user_id = NULL, - update_time = NOW() - WHERE id = :previousCartId - AND warehouse_id = :warehouseId - AND current_task_id = :taskId - `, { - replacements: { - previousCartId, - warehouseId, - taskId, - }, - transaction, - }); - } - - await ctx.model.query(` - UPDATE wms_pick_task_cart_binding - SET is_active = 0, - unbind_user_id = :operatorId, - unbind_time = NOW(), - update_time = NOW() - WHERE warehouse_id = :warehouseId - AND is_active = 1 - AND (task_id = :taskId OR cart_id = :cartId) - `, { - replacements: { - operatorId, - warehouseId, - taskId, - cartId: targetCartId, - }, - transaction, - }); - await ctx.model.query(` INSERT INTO wms_pick_task_cart_binding ( task_id, @@ -2474,7 +2478,7 @@ class PickSystemService extends Service { :cartCode, :warehouseId, :operatorId, - :bindType, + 1, 1, NOW(), NOW(), @@ -2487,7 +2491,6 @@ class PickSystemService extends Service { cartCode: targetCartCode, warehouseId, operatorId, - bindType, }, transaction, }); @@ -2509,25 +2512,6 @@ class PickSystemService extends Service { transaction, }); - await ctx.model.query(` - UPDATE wms_pick_cart - SET current_task_id = :taskId, - bind_user_id = :operatorId, - last_bind_time = NOW(), - last_seen_time = NOW(), - update_time = NOW() - WHERE id = :cartId - AND warehouse_id = :warehouseId - `, { - replacements: { - taskId, - operatorId, - cartId: targetCartId, - warehouseId, - }, - transaction, - }); - await transaction.commit(); const latestCartRow = await this.getPickCartById(targetCartId, warehouseId); @@ -2654,8 +2638,24 @@ class PickSystemService extends Service { throw this.createBusinessError('cart_code 必填', 400); } await this.assertPickCartCodeUnique(nextCartCode, warehouseId, cartId); - if (nextStatus === 0 && Number(cartRow.current_task_id || 0) > 0) { - throw this.createBusinessError('拣货车已绑定任务,无法停用', 400); + if (nextStatus === 0) { + // 通过绑定表检查车是否被活动任务占用 + const activeBindingRows = await ctx.model.query(` + SELECT b.id + FROM wms_pick_task_cart_binding b + INNER JOIN wms_wave_pick_task t ON t.id = b.task_id + WHERE b.cart_id = :cartId + AND b.warehouse_id = :warehouseId + AND b.is_active = 1 + AND t.status IN (0, 1) + LIMIT 1 + `, { + replacements: { cartId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + }); + if (Array.isArray(activeBindingRows) && activeBindingRows.length > 0) { + throw this.createBusinessError('拣货车已绑定活动任务,无法停用', 400); + } } await ctx.model.query(` From 315e366c4c34a97c56e1bcdee04f6c0a515026d8 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sat, 1 Aug 2026 03:45:16 +0800 Subject: [PATCH 143/550] =?UTF-8?q?feat(inventory):=20=E6=96=B0=E5=A2=9E?= =?UTF-8?q?=E5=BA=93=E5=AD=98=E5=BC=82=E6=AD=A5=E5=AF=BC=E5=87=BA=E5=8A=9F?= =?UTF-8?q?=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - systemMethods 层:export 提交异步任务 + exportTaskProgress 查询进度 - systems 层:exportInventoryList 导出实现(支持按 stock_id 聚合/按 storage_id 明细) - 导出任务通过 Redis 缓存管理进度状态(TTL 30min) --- .../systemMethods/storage/inventory.js | 231 +++++++++++++- app/service/systems/storage/inventory.js | 287 ++++++++++++++++++ 2 files changed, 515 insertions(+), 3 deletions(-) diff --git a/app/service/systemMethods/storage/inventory.js b/app/service/systemMethods/storage/inventory.js index f860d40..c4d3253 100644 --- a/app/service/systemMethods/storage/inventory.js +++ b/app/service/systemMethods/storage/inventory.js @@ -2,6 +2,9 @@ const MainService = require('../../main'); +const STORAGE_INVENTORY_EXPORT_TASK_CACHE_KEY_PREFIX = 'storage_inventory_export_task_'; +const STORAGE_INVENTORY_EXPORT_TASK_CACHE_TTL_SECONDS = 1800; + /** * 系统方法层:storage.inventory(库存操作接口包装层)。 * 职责:统一包装库存操作接口,调用底层 systems/storage/inventory service。 @@ -10,9 +13,9 @@ class InventoryMethodService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'list'; - const _noNeedLog = 'list'; - const _noNeedAuth = 'list,quickPutaway'; + const _noNeedRight = 'list,export,exportTaskProgress'; + const _noNeedLog = 'list,export,exportTaskProgress'; + const _noNeedAuth = 'list,quickPutaway,export,exportTaskProgress'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -75,6 +78,228 @@ class InventoryMethodService extends MainService { const result = await service.systems.storage.inventory.quickPutaway({ receiving_id }); return this.success('ok', result); } + /** + * 提交库存导出异步任务(入参与 list 一致,复用相同的 where/sort/group_by_batch 语义)。 + * + * @param {Object} data 请求体 + * @param {Object} [data.where] 查询条件(与 list 完全一致) + * @param {Object} [data.sort] 排序参数 { sortField, sortOrder }(与 list 完全一致) + * @param {boolean} [data.group_by_batch=false] 是否按批次导出,默认 false + * - false:按 stock_id + 库位聚合导出库存汇总 + * - true:按 storage_id 逐条导出库存明细 + * @return {Promise} 统一 success 包装,data 为导出任务信息 + */ + async export(data = {}) { + const { service } = this; + const groupByBatch = data.group_by_batch === true || data.group_by_batch === 'true'; + + // 与 list 一致:prepareWhereContext 会设置 ctx.whereParsed,systems 层从中读取条件 + this.prepareWhereContext(data); + + const { sort = {} } = data; + const sortField = sort.sortField || sort.sort_field; + const sortOrder = sort.sortOrder || sort.sort_order; + const sortParams = { + ...(sortField ? { sortField } : {}), + ...(sortOrder ? { sortOrder } : {}), + }; + + const taskId = this.generateExportTaskId(); + const taskPayload = { + task_id: taskId, + status: 'submitted', + progress: 0, + message: '导出任务已提交', + result: null, + error: '', + }; + + await this.setExportTaskProgress(taskId, taskPayload); + + setImmediate(async () => { + try { + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'running', + progress: 10, + message: '导出任务执行中', + result: null, + error: '', + }); + + const result = await service.systems.storage.inventory.exportInventoryList(sortParams, groupByBatch); + + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'success', + progress: 100, + message: '导出任务完成', + result, + error: '', + }); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'failed', + progress: 100, + message: '导出任务失败', + result: null, + error: errorMessage, + }); + } + }); + + return this.success('ok', { + ...taskPayload, + update_time: Date.now(), + }); + } + + /** + * 查询库存导出任务进度。 + * @param {Object} data 请求体 + * @param {string} [data.task_id] 任务ID(下划线写法) + * @param {string} [data.taskId] 任务ID(驼峰写法) + * @return {Promise} 统一 success 包装 + */ + async exportTaskProgress(data = {}) { + const taskId = this.normalizeExportTaskId(data); + if (!taskId) { + return this.success('ok', { + task_id: '', + status: 'not_found', + progress: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const cachedTask = await this.getExportTaskProgress(taskId); + if (!cachedTask) { + return this.success('ok', { + task_id: taskId, + status: 'not_found', + progress: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {}; + const downloadUrl = String( + safeResult.url + || safeResult.cndUrl + || safeResult.cosUrl + || safeResult.fileKey + || '' + ); + + return this.success('ok', { + task_id: taskId, + ...cachedTask, + download_url: downloadUrl, + }); + } + + // ==================== 导出任务辅助方法 ==================== + + /** + * 生成库存导出任务ID。 + * @return {string} 导出任务ID + */ + generateExportTaskId() { + const warehouseId = this.ctx?.user?.store_id || 'unknown'; + const timestamp = Date.now(); + const randomToken = Math.random().toString(36).slice(2, 10); + return `storage_inventory_export_${warehouseId}_${timestamp}_${randomToken}`; + } + + /** + * 归一化导出任务ID。 + * @param {Object} data 请求体 + * @param {string} [data.task_id] 任务ID(下划线写法) + * @param {string} [data.taskId] 任务ID(驼峰写法) + * @return {string} 归一化后的任务ID + */ + normalizeExportTaskId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.task_id || normalizedData.taskId || '').trim(); + } + + /** + * 获取导出任务缓存键。 + * @param {string} taskId 任务ID + * @return {string} 缓存键 + */ + getExportTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + return `${STORAGE_INVENTORY_EXPORT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 写入导出任务进度缓存。 + * @param {string} taskId 任务ID + * @param {Object} payload 任务状态载荷 + * @return {Promise} 无返回值 + */ + async setExportTaskProgress(taskId = '', payload = {}) { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.setCacheAsync !== 'function') { + return; + } + + const safePayload = this.isPlainObject(payload) ? payload : {}; + const progressPayload = { + task_id: String(taskId || '').trim(), + status: String(safePayload.status || 'submitted').trim() || 'submitted', + progress: Number.isFinite(Number(safePayload.progress)) ? Math.min(100, Math.max(0, Math.round(Number(safePayload.progress)))) : 0, + message: String(safePayload.message || ''), + result: safePayload.result ?? null, + error: String(safePayload.error || ''), + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync(cacheKey, progressPayload, STORAGE_INVENTORY_EXPORT_TASK_CACHE_TTL_SECONDS); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + this.ctx.logger.warn(`[storage.inventory.export] 写入导出任务缓存失败: ${errorMessage}`); + } + } + + /** + * 读取导出任务进度缓存。 + * @param {string} taskId 任务ID + * @return {Promise} 任务缓存 + */ + async getExportTaskProgress(taskId = '') { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.getCacheAsync !== 'function') { + return null; + } + + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (!this.isPlainObject(cached)) { + return null; + } + return cached; + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + this.ctx.logger.warn(`[storage.inventory.export] 读取导出任务缓存失败: ${errorMessage}`); + return null; + } + } } module.exports = InventoryMethodService; diff --git a/app/service/systems/storage/inventory.js b/app/service/systems/storage/inventory.js index 9fb6931..77c2fe8 100644 --- a/app/service/systems/storage/inventory.js +++ b/app/service/systems/storage/inventory.js @@ -1686,6 +1686,293 @@ class InventoryService extends Service { } } + /** + * 导出库存列表(异步任务内部调用,生成 Excel 并上传)。 + * + * where 条件通过 ctx.whereParsed 读取(与 getInventoryList 完全一致), + * 调用方需先执行 prepareWhereContext 设置 ctx.whereParsed。 + * + * 支持两种导出模式: + * - stock_location:按 stock_id + space_id(库位)聚合,汇总数量 + * - storage:按 storage_id 逐条导出明细 + * + * @param {Object} sortParams 排序参数 { sortField, sortOrder } + * @param {boolean} groupByBatch 是否按批次导出(false=聚合,true=逐条明细) + * @return {Promise} 导出上传结果(含 url/fileKey 等) + */ + async exportInventoryList(sortParams = {}, groupByBatch = false) { + const { ctx, app } = this; + const { Op, fn, col, literal } = app.Sequelize; + const warehouseId = ctx.user.store_id; + const { sortField = 'id', sortOrder = 'DESC' } = sortParams; + const pageSize = 500; + let page = 1; + let hasNext = true; + const rows = []; + + // 构建基础 where 条件(与 getInventoryList 完全一致) + const baseWhere = { + [Op.and]: [ + { warehouse_id: warehouseId }, + { is_enabled: 1 }, + { delete_at: null }, + ], + }; + + // 动态 where 条件(与 getInventoryList 一致:从 ctx.whereParsed 读取) + const parsed = ctx.whereParsed; + if (parsed && parsed.dynamicConditions && parsed.dynamicConditions.length > 0) { + baseWhere[Op.and].push(...parsed.dynamicConditions); + } + + if (groupByBatch) { + // ────── group_by_batch=true:按 storage_id 逐条导出明细 ────── + while (hasNext) { + const { rows: pageRows } = await ctx.model.Storage.findAndCountAll({ + where: baseWhere, + attributes: [ + 'id', 'stock_id', 'space_id', 'batch_no', 'inventory_type', + 'quantity', 'locked_quantity', 'available_quantity', + 'production_date', 'expiry_date', 'inbound_time', 'inbound_order_no', + 'supplier_batch_no', 'store_id', 'warehouse_id', + 'created_at', 'updated_at', + ], + order: [[ sortField, sortOrder ]], + offset: (page - 1) * pageSize, + limit: pageSize, + include: [ + { + model: ctx.model.StockWarehouse, + as: 'stock', + attributes: [ 'id', 'item_code', 'item_name', 'sku_property', 'stock_unit' ], + required: false, + }, + { + model: ctx.model.LocationSpace, + as: 'space', + attributes: [ 'id', 'space_code', 'custom_name' ], + required: false, + }, + ], + raw: true, + nest: true, + }); + + if (pageRows.length === 0) { + hasNext = false; + break; + } + + // 收集 store_id 批量查询货主名称 + const storeIds = [ ...new Set(pageRows.map(r => Number(r.store_id)).filter(Boolean)) ]; + const storeMap = new Map(); + if (storeIds.length > 0) { + try { + const storeRows = await ctx.model.StoreWarehouse.findAll({ + attributes: [ 'store_id', 'store_remask' ], + where: { store_id: { [Op.in]: storeIds }, warehouse_id: warehouseId }, + raw: true, + }); + for (const sr of storeRows) { + storeMap.set(Number(sr.store_id), sr.store_remask || ''); + } + } catch (_e) { /* ignore */ } + } + + for (const row of pageRows) { + rows.push({ + storage_id: row.id, + stock_id: row.stock_id, + item_code: row.stock?.item_code || '', + item_name: row.stock?.item_name || '', + sku_property: row.stock?.sku_property || '', + stock_unit: row.stock?.stock_unit || '', + store_name: storeMap.get(Number(row.store_id)) || '', + space_code: row.space?.space_code || '', + space_name: row.space?.custom_name || '', + batch_no: row.batch_no || '', + inventory_type: row.inventory_type || '', + quantity: row.quantity, + locked_quantity: row.locked_quantity, + available_quantity: row.available_quantity, + production_date: row.production_date ? app.formatDate(row.production_date) : '', + expiry_date: row.expiry_date ? app.formatDate(row.expiry_date) : '', + inbound_time: row.inbound_time ? app.formatDate(row.inbound_time) : '', + inbound_order_no: row.inbound_order_no || '', + supplier_batch_no: row.supplier_batch_no || '', + created_at: row.created_at ? app.formatDate(row.created_at) : '', + updated_at: row.updated_at ? app.formatDate(row.updated_at) : '', + }); + } + + hasNext = pageRows.length >= pageSize; + page += 1; + } + } else { + // ────── group_by_batch=false(默认):按 stock_id + space_id 聚合 ────── + const groupFields = [ 'stock_id', 'space_id' ]; + + while (hasNext) { + const pageRows = await ctx.model.Storage.findAll({ + where: baseWhere, + attributes: [ + 'stock_id', + 'space_id', + [ fn('MIN', col('wms_storage.store_id')), 'store_id' ], + [ fn('SUM', col('wms_storage.quantity')), 'quantity' ], + [ fn('SUM', col('wms_storage.locked_quantity')), 'locked_quantity' ], + [ fn('SUM', col('wms_storage.available_quantity')), 'available_quantity' ], + [ fn('COUNT', col('wms_storage.id')), 'batch_count' ], + [ fn('MAX', col('wms_storage.inbound_time')), 'last_inbound_time' ], + [ fn('MIN', col('wms_storage.created_at')), 'first_created_at' ], + [ fn('MAX', col('wms_storage.updated_at')), 'last_updated_at' ], + ], + group: groupFields, + order: [[ literal('last_inbound_time'), sortOrder ]], + offset: (page - 1) * pageSize, + limit: pageSize, + include: [ + { + model: ctx.model.StockWarehouse, + as: 'stock', + attributes: [ 'id', 'item_code', 'item_name', 'sku_property', 'stock_unit' ], + required: false, + }, + { + model: ctx.model.LocationSpace, + as: 'space', + attributes: [ 'id', 'space_code', 'custom_name' ], + required: false, + }, + ], + raw: true, + nest: true, + }); + + if (pageRows.length === 0) { + hasNext = false; + break; + } + + // 收集 store_id 批量查询货主名称 + const storeIds = [ ...new Set(pageRows.map(r => Number(r.store_id)).filter(Boolean)) ]; + const storeMap = new Map(); + if (storeIds.length > 0) { + try { + const storeRows = await ctx.model.StoreWarehouse.findAll({ + attributes: [ 'store_id', 'store_remask' ], + where: { store_id: { [Op.in]: storeIds }, warehouse_id: warehouseId }, + raw: true, + }); + for (const sr of storeRows) { + storeMap.set(Number(sr.store_id), sr.store_remask || ''); + } + } catch (_e) { /* ignore */ } + } + + for (const row of pageRows) { + rows.push({ + stock_id: row.stock_id, + space_id: row.space_id, + item_code: row.stock?.item_code || '', + item_name: row.stock?.item_name || '', + sku_property: row.stock?.sku_property || '', + stock_unit: row.stock?.stock_unit || '', + store_name: storeMap.get(Number(row.store_id)) || '', + space_code: row.space?.space_code || '', + space_name: row.space?.custom_name || '', + quantity: row.quantity, + locked_quantity: row.locked_quantity, + available_quantity: row.available_quantity, + batch_count: row.batch_count, + last_inbound_time: row.last_inbound_time ? app.formatDate(row.last_inbound_time) : '', + created_at: row.first_created_at ? app.formatDate(row.first_created_at) : '', + updated_at: row.last_updated_at ? app.formatDate(row.last_updated_at) : '', + }); + } + + hasNext = pageRows.length >= pageSize; + page += 1; + } + } + + // ── 批量填充商品条码和图片(复用 loadStockAttachments 缓存查询)── + if (rows.length > 0) { + const stockIds = [ ...new Set( + rows.map(r => Number(r.stock_id || 0)).filter(Boolean) + ) ]; + const { barcodesByStockId, imagesByStockId } = await loadStockAttachments(ctx, stockIds); + + for (const row of rows) { + const sid = Number(row.stock_id || 0); + row.barcodes = sid ? (barcodesByStockId.get(sid) || []).join(', ') : ''; + row.image_url = sid ? ((imagesByStockId.get(sid) || [])[0] || '') : ''; + } + } + + // 生成 Excel + const now = new Date(); + const dateToken = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}${String(now.getMilliseconds()).padStart(3, '0')}`; + + const modeLabel = groupByBatch ? '库存明细' : '库存汇总'; + const sheetName = groupByBatch ? '库存明细' : '库存汇总(按商品+库位)'; + + const columns = groupByBatch + ? [ + { header: '库存记录ID', key: 'storage_id' }, + { header: '商品编码', key: 'item_code' }, + { header: '商品名称', key: 'item_name' }, + { header: '规格', key: 'sku_property' }, + { header: '库存单位', key: 'stock_unit' }, + { header: '货主', key: 'store_name' }, + { header: '库位编码', key: 'space_code' }, + { header: '库位名称', key: 'space_name' }, + { header: '条码', key: 'barcodes' }, + { header: '图片', key: 'image_url' }, + { header: '批次号', key: 'batch_no' }, + { header: '库存类型', key: 'inventory_type' }, + { header: '数量', key: 'quantity' }, + { header: '锁定数量', key: 'locked_quantity' }, + { header: '可用数量', key: 'available_quantity' }, + { header: '生产日期', key: 'production_date' }, + { header: '过期日期', key: 'expiry_date' }, + { header: '入库时间', key: 'inbound_time' }, + { header: '入库单号', key: 'inbound_order_no' }, + { header: '供应商批次号', key: 'supplier_batch_no' }, + { header: '创建时间', key: 'created_at' }, + { header: '更新时间', key: 'updated_at' }, + ] + : [ + { header: '商品编码', key: 'item_code' }, + { header: '商品名称', key: 'item_name' }, + { header: '规格', key: 'sku_property' }, + { header: '库存单位', key: 'stock_unit' }, + { header: '货主', key: 'store_name' }, + { header: '条码', key: 'barcodes' }, + { header: '图片', key: 'image_url' }, + { header: '库位编码', key: 'space_code' }, + { header: '库位名称', key: 'space_name' }, + { header: '总库存', key: 'quantity' }, + { header: '锁定库存', key: 'locked_quantity' }, + { header: '可用库存', key: 'available_quantity' }, + { header: '批次数', key: 'batch_count' }, + { header: '最近入库时间', key: 'last_inbound_time' }, + { header: '创建时间', key: 'created_at' }, + { header: '更新时间', key: 'updated_at' }, + ]; + + return await ctx.service.systems.excel.generateAndUpload({ + filename: `${modeLabel}导出_${dateToken}.xlsx`, + dir: `exports/storage/inventory/${warehouseId}`, + category: 'document', + sheets: [{ + name: sheetName, + columns, + rows, + }], + }); + } + /** * 生成入库单号。 * 格式:SCRK + 年月日 + 4位流水号 From da56253d4ac5497485dbce9fabcd7c3aa9d667c3 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sat, 1 Aug 2026 03:45:26 +0800 Subject: [PATCH 144/550] =?UTF-8?q?feat(shops):=20=E5=BA=97=E9=93=BA?= =?UTF-8?q?=E8=A7=86=E9=A2=91=E5=8F=B7=E6=8E=88=E6=9D=83=E6=94=AF=E6=8C=81?= =?UTF-8?q?=20+=20=E9=83=A8=E7=BD=B2=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - shops.js: 视频号授权需传 appId/toUserName,新增授权请求/响应调试缓存 - index.js: SPH 运单查询添加调试缓存 - deploy-remote.cjs: 健康检查优化(30次→5次/10s),失败自动回滚 current.md - config.default.js: 数据库连接池 20→225 --- app/service/systemMethods/index.js | 10 ++++- app/service/systems/shops.js | 13 +++++++ config/config.default.js | 2 +- script/deploy-remote.cjs | 59 ++++++++++++++++++++++++++---- 4 files changed, 75 insertions(+), 9 deletions(-) diff --git a/app/service/systemMethods/index.js b/app/service/systemMethods/index.js index a8fae05..080f03b 100644 --- a/app/service/systemMethods/index.js +++ b/app/service/systemMethods/index.js @@ -2288,6 +2288,14 @@ class indexService extends MainService { const accessToken = String(shopPlain.access_token || '').trim(); const expressList = await this.service.systems.express.getExpressList(true); const expressNameMap = buildExpressNameMap(expressList, 'SPH'); + await this.app.setCacheAsync('SPHquery', JSON.stringify({ + interface_url: 'https://api.polyapi.com/OpenAPI/do', + appkey: this.app.config.poloApi.appKey, + app_secret: this.app.config.poloApi.appSecret, + platid, + version: '1.5', + token: accessToken, + }), 3600); const responseData = await service.systems.poloApi.request('Differ.JH.Logistics.GetWayBillCondition', { }, { interface_url: 'https://api.polyapi.com/OpenAPI/do', @@ -2297,7 +2305,7 @@ class indexService extends MainService { version: '1.5', token: accessToken, }); - console.log('请求的店铺的platformCode', platformCode, '接口响应', JSON.stringify(responseData)); + await this.app.setCacheAsync('SPHrequest', JSON.stringify(responseData), 3600); const parsed = formatDyWaybillSearchResponse(responseData, expressNameMap); list = parsed.list; break; diff --git a/app/service/systems/shops.js b/app/service/systems/shops.js index 521e633..8e792b7 100644 --- a/app/service/systems/shops.js +++ b/app/service/systems/shops.js @@ -696,6 +696,8 @@ class ShopsService extends Service { 'callbackurl', { required: true, maxLength: 500 } ); + const appId = data.appId || ''; + const toUserName = data.toUserName || ''; const shop = await this.findShopById(shopId, { allowDeleted: false }); const shopPlain = typeof shop.get === 'function' ? shop.get({ plain: true }) : shop; const platformCode = await this.ensureShopPrintPlatformExists(shopPlain.platform_code); @@ -719,6 +721,16 @@ class ShopsService extends Service { if (platName === '电商京东') { requestData.VenderID = shopPlain.id; } + if (platName === '视频号') { + if(!appId || !toUserName) { + throw this.createError('视频号授权需要提供 appId 和 toUserName', 400); + } + requestData.appId = appId; + requestData.toUserName = toUserName; + delete requestData.RedirectCodeUrl; + } + // 缓存最后一次授权查询请求数据,便于排查问题 + await this.app.setCacheAsync('last_query_auth_polo', JSON.stringify(requestData), 3600); const respone = await ctx.curl(authUrl, { method: 'POST', @@ -726,6 +738,7 @@ class ShopsService extends Service { timeout: 5000, data: requestData, }); + await this.app.setCacheAsync('last_respone_auth_polo', JSON.stringify(respone), 3600); if (respone.data && respone.data.code === 0) { const sessionKey = respone.data.data || null; if (sessionKey) { diff --git a/config/config.default.js b/config/config.default.js index 0e4a199..79dc675 100644 --- a/config/config.default.js +++ b/config/config.default.js @@ -171,7 +171,7 @@ module.exports = appInfo => { deletedAt: 'deleted_at', // 软删除字段名 }, pool: { - max: 20, + max: 225, min: 1, idle: 10000, acquire: 30000, diff --git a/script/deploy-remote.cjs b/script/deploy-remote.cjs index 13fc2fd..c89dde2 100644 --- a/script/deploy-remote.cjs +++ b/script/deploy-remote.cjs @@ -162,17 +162,17 @@ function main() { const switchOutput = runSsh(config, switchAndStartScript, { stdio: 'pipe' }); console.log(String(switchOutput || '').trim()); - // 6.5. 健康检查新实例(curl 循环等待,最多 60 秒) + // 6.5. 健康检查新实例(curl 循环等待,最多 10 秒) const oldDir = `${config.deployRoot}/${currentVersion}`; const healthCheckScript = [ 'set -euo pipefail', `TARGET_PORT=${targetPort}`, - 'for attempt in $(seq 1 30); do', - ' if curl -fsS --connect-timeout 2 --max-time 4 "http://127.0.0.1:$TARGET_PORT/" >/dev/null 2>&1; then', + 'for attempt in $(seq 1 5); do', + ' if curl -fsS --connect-timeout 2 --max-time 3 "http://127.0.0.1:$TARGET_PORT/" >/dev/null 2>&1; then', ` echo "新实例 (${targetVersion}) 健康检查通过 (端口 $TARGET_PORT)"`, ' break', ' fi', - ' if [ "$attempt" -eq 30 ]; then', + ' if [ "$attempt" -eq 5 ]; then', ` echo "新实例 (${targetVersion}) 健康检查超时 (端口 $TARGET_PORT)" >&2`, ' exit 1', ' fi', @@ -184,11 +184,56 @@ function main() { const healthOutput = runSsh(config, healthCheckScript, { stdio: 'pipe' }); console.log(String(healthOutput || '').trim()); } catch (err) { - console.warn(`[WARN] 新实例健康检查失败: ${err.message}`); - console.warn(`[WARN] 新实例 (${targetVersion}) 可能未完全就绪,请人工确认 127.0.0.1:${targetPort} 状态`); + // 健康检查失败 → 不做切换,回滚 current.md 并清理失败的新实例 + console.error(`[ERROR] 新实例健康检查失败 (10s 超时): ${err.message}`); + console.error(`[ERROR] 发布中止:不切换 Nginx upstream,不停旧实例`); + + // 回滚:将 current.md 恢复为旧版本 + const revertCurrentMdScript = [ + 'set -euo pipefail', + `printf '%s\\n' ${quoteForBash(currentVersion)} > ${quoteForBash(currentMdPath)}`, + `echo "已回滚 current.md -> ${currentVersion}"`, + ].join('\n'); + try { + const revertOutput = runSsh(config, revertCurrentMdScript, { stdio: 'pipe' }); + console.log(String(revertOutput || '').trim()); + } catch (revertErr) { + console.error(`[ERROR] 回滚 current.md 失败: ${revertErr.message}`); + } + + // 清理:杀死启动失败的新实例进程 + const killNewScript = [ + 'set -euo pipefail', + `NEW_DIR=${quoteForBash(targetDir)}`, + `NEW_VERSION=${quoteForBash(targetVersion)}`, + 'NEW_PIDS=$(ps -eo pid=,args= | awk -v root="$NEW_DIR" \'index($0, root) && $2 ~ /node$/ { print $1 }\')', + 'if [ -n "$NEW_PIDS" ]; then', + ' echo "正在清理失败的新实例 ($NEW_VERSION): $NEW_PIDS"', + ' kill $NEW_PIDS || true', + ' sleep 2', + ' NEW_PIDS_REMAIN=$(ps -eo pid=,args= | awk -v root="$NEW_DIR" \'index($0, root) && $2 ~ /node$/ { print $1 }\')', + ' if [ -n "$NEW_PIDS_REMAIN" ]; then', + ' echo "新实例仍有残留进程,强制停止: $NEW_PIDS_REMAIN"', + ' kill -9 $NEW_PIDS_REMAIN || true', + ' fi', + ' echo "失败的新实例 ($NEW_VERSION) 已清理"', + 'else', + ' echo "未找到新实例 ($NEW_VERSION) 进程,无需清理"', + 'fi', + ].join('\n'); + try { + const killOutput = runSsh(config, killNewScript, { stdio: 'pipe' }); + console.log(String(killOutput || '').trim()); + } catch (killErr) { + console.error(`[ERROR] 清理失败新实例进程出错: ${killErr.message}`); + } + + console.error(`[ERROR] 发布失败: ${envName} -> ${config.username}@${config.host}:${targetDir}`); + console.error(`[ERROR] 旧实例 (${currentVersion}) 仍在运行,线上服务不受影响`); + process.exit(1); } - // 6.55. 切换 Nginx upstream 端口并 reload + // 6.55. 切换 Nginx upstream 端口并 reload(仅在健康检查通过后执行) const nginxUpstreamPath = `${config.deployRoot}/nginx-upstream.conf`; const switchNginxScript = [ 'set -euo pipefail', From fbb12cf205cc129d2e0e44554abd243a77ffc6b1 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sat, 1 Aug 2026 13:56:21 +0800 Subject: [PATCH 145/550] =?UTF-8?q?fix(deliveryOrder):=20resolveExpressSna?= =?UTF-8?q?pshot=20=E5=85=9C=E5=BA=95=E8=AF=BB=E5=8F=96=20policy=5Fconfig.?= =?UTF-8?q?default=5Fexpress=5Fcode?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 修复前只读 store.subject_config.default_express_code,导致 subject_config 为 NULL 时始终命中默认 STO - 修复后货主 subject_config 优先,未配置时兜底读仓库 policy_config.default_express_code - 解决广州趣电贸易等 subject_config 为空的货主无法使用仓库级 ZTO 配置的问题 - 新增 resolveExpressSnapshot 单测 14 个用例全覆盖两大分支 --- app/service/systems/delivery_order.js | 29 ++++++++++++++++++--------- 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/app/service/systems/delivery_order.js b/app/service/systems/delivery_order.js index 2c87614..e672941 100644 --- a/app/service/systems/delivery_order.js +++ b/app/service/systems/delivery_order.js @@ -484,21 +484,35 @@ class DeliveryOrderService extends Service { /** * 解析订单快递快照。 * - * 优先级: - * 1. 先读取是否启用外部快递编码开关; - * 2. 开关关闭时,直接使用货主默认快递回填四个快递字段; - * 3. 开关开启时,先匹配 wms_express_setting,再匹配 wms_express,最后回退货主默认快递。 + * 默认快递编码优先级: + * 1. storeSubjectConfig.default_express_code(货主级,个性化配置) + * 2. policyConfig.default_express_code(仓库级,通用配置) + * + * 分支路由: + * 1. 先读取是否启用外部快递编码开关; + * 2. 开关关闭时,直接使用上述优先级的默认快递回填四个快递字段; + * 3. 开关开启时,先匹配 wms_express_setting,再匹配 wms_express,最后回退默认快递。 * * @param {string} logisticsCode 外部快递编码。 * @param {Object} storeSubjectConfig 货主签约配置。 - * @param {Object} [info={}] 上下文信息。 + * @param {Object} [info={}] 上下文信息,可含 policyConfig / enableExternalExpressCode / warehouseId。 * @param {Array} [operationLogs=[]] 待写入的操作日志数组。 * @return {Promise} 快递快照。 */ async resolveExpressSnapshot(logisticsCode, storeSubjectConfig, info = {}, operationLogs = []) { const expressList = await this.ctx.service.systems.express.getExpressList(); const externalCode = String(logisticsCode || '').trim(); - const defaultCode = String(storeSubjectConfig && storeSubjectConfig.default_express_code || '').trim(); + + // 货主 subject_config 优先于仓库 policy_config(货主个性配置高于仓库通用配置) + const policyConfig = info && info.policyConfig && typeof info.policyConfig === 'object' + ? info.policyConfig + : {}; + const defaultCode = String( + (storeSubjectConfig && storeSubjectConfig.default_express_code) + || policyConfig.default_express_code + || '' + ).trim(); + const fallbackExpress = this.findCodeOption(expressList, defaultCode); const fallbackLogisticsCode = String( fallbackExpress && (fallbackExpress.code || fallbackExpress.value || fallbackExpress.express_code || defaultCode) @@ -509,9 +523,6 @@ class DeliveryOrderService extends Service { const explicitEnableExternalExpressCode = info && Object.prototype.hasOwnProperty.call(info, 'enableExternalExpressCode') ? info.enableExternalExpressCode : undefined; - const policyConfig = info && info.policyConfig && typeof info.policyConfig === 'object' - ? info.policyConfig - : {}; const isEnableExternalExpressCode = this.resolveEnableExternalExpressCode( storeSubjectConfig, policyConfig, From 5759c1fb1998f0bb94baa57a07590773aa83b20d Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sat, 1 Aug 2026 15:31:00 +0800 Subject: [PATCH 146/550] =?UTF-8?q?feat(deploy):=20=E9=83=A8=E7=BD=B2?= =?UTF-8?q?=E8=84=9A=E6=9C=AC=E5=A2=9E=E5=8A=A0=E7=AB=AF=E5=8F=A3=E5=BC=BA?= =?UTF-8?q?=E5=88=B6=E6=B8=85=E7=90=86=20+=20=E5=81=A5=E5=BA=B7=E6=A3=80?= =?UTF-8?q?=E6=9F=A5=E8=B6=85=E6=97=B6=E5=BB=B6=E9=95=BF=E8=87=B3=2020s?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增步骤 5.5:启动前通过 ss + fuser -k 强制释放目标端口残留进程 - 健康检查重试次数从 5 次增加到 10 次,最长等待从 10s 延长至 20s - 健康检查失败日志增加启动日志路径提示 --- app/controller/warehouse.js | 56 +++++ app/router.js | 3 + app/service/systems/api_sign.js | 35 +-- app/service/systems/express_platform.js | 2 +- app/service/warehouse.js | 274 ++++++++++++++++++++++++ app/service/warehouseMethods/index.js | 22 ++ app/service/warehouseMethods/store.js | 88 ++++++++ methods/changes/warehouse.json | 22 ++ methods/warehouse.json | 203 ++++++++++++++++++ script/deploy-remote.cjs | 37 +++- 10 files changed, 723 insertions(+), 19 deletions(-) create mode 100644 app/controller/warehouse.js create mode 100644 app/service/warehouse.js create mode 100644 app/service/warehouseMethods/index.js create mode 100644 app/service/warehouseMethods/store.js create mode 100644 methods/changes/warehouse.json create mode 100644 methods/warehouse.json diff --git a/app/controller/warehouse.js b/app/controller/warehouse.js new file mode 100644 index 0000000..4e79e32 --- /dev/null +++ b/app/controller/warehouse.js @@ -0,0 +1,56 @@ +'use strict'; + +const { Controller } = require('egg'); +const { toSuccess, toFailure } = require('../lib/api_response'); + +class WarehouseController extends Controller { + /** + * 输出仓库 API 统一失败响应。 + * @param {number} httpStatus HTTP 状态码。 + * @param {string} message 错误消息。 + * @param {number} [code=httpStatus] 业务错误码。 + * @return {void} 无返回值。 + */ + writeFailureResponse(httpStatus, message, code = httpStatus) { + const { ctx } = this; + ctx.status = httpStatus; + ctx.body = toFailure({ + message, + httpStatus, + code, + }); + ctx.type = 'application/json'; + } + + /** + * 仓库 API 统一入口,仅负责转发到 warehouse service 并输出标准响应。 + * @return {Promise} 无返回值,结果写入 ctx.body。 + */ + async index() { + const { ctx } = this; + + try { + const result = await ctx.service.warehouse.processRequest(); + if (result.ok) { + ctx.status = Number(result.httpStatus) || 200; + ctx.body = toSuccess(result.data, result.message || 'ok'); + ctx.type = 'application/json'; + return; + } + + this.writeFailureResponse( + Number(result.httpStatus) || 500, + String(result.message || '请求失败'), + Number(result.code) || Number(result.httpStatus) || 500 + ); + ctx.type = 'application/json'; + return; + } catch (error) { + const message = String(error && error.message || '请求失败'); + this.writeFailureResponse(500, `接口错误: ${message}`, 500); + ctx.type = 'application/json'; + } + } +} + +module.exports = WarehouseController; diff --git a/app/router.js b/app/router.js index a557b37..c583b96 100644 --- a/app/router.js +++ b/app/router.js @@ -44,6 +44,9 @@ module.exports = app => { // OpenAPI 入口 router.post('/openapi', controller.openapi.index); + // 仓库 OpenAPI 入口 + router.post('/warehouse', controller.warehouse.index); + // 打印模板 router.get('/template/xml/:id', controller.template.xml); diff --git a/app/service/systems/api_sign.js b/app/service/systems/api_sign.js index f9fad9f..21d7662 100644 --- a/app/service/systems/api_sign.js +++ b/app/service/systems/api_sign.js @@ -6,29 +6,35 @@ const apiSignLib = require('../../lib/api_sign'); const API_APP_CACHE_PREFIX = 'openapi:api-app'; const API_APP_CACHE_TTL_SECONDS = 300; const OPENAPI_INTERFACE_TYPE_ID = 2; +const WAREHOUSE_INTERFACE_TYPE_ID = 3; class ApiSignService extends Service { /** * 构建 API 应用配置缓存键。 * @param {string} appKey 开放接口 app_key。 + * @param {number} [interfaceTypeId] 接口类型 ID,用于区分不同入口的缓存。 * @return {string} 缓存键。 */ - getApiAppCacheKey(appKey) { - return `${API_APP_CACHE_PREFIX}:${String(appKey || '').trim()}`; + getApiAppCacheKey(appKey, interfaceTypeId = OPENAPI_INTERFACE_TYPE_ID) { + const prefix = interfaceTypeId === WAREHOUSE_INTERFACE_TYPE_ID + ? 'warehouse:api-app' + : API_APP_CACHE_PREFIX; + return `${prefix}:${String(appKey || '').trim()}`; } /** * 根据 app_key 查询 API 应用可用配置(带缓存)。 * @param {string} appKey 开放接口 app_key。 + * @param {number} [interfaceTypeId=2] 接口类型 ID,2=货主级 / 3=仓库级。 * @return {Promise} 查询结果,包含应用主键与密钥。 */ - async getApiAppConfigByAppKey(appKey) { + async getApiAppConfigByAppKey(appKey, interfaceTypeId = OPENAPI_INTERFACE_TYPE_ID) { const normalizedAppKey = String(appKey || '').trim(); if (!normalizedAppKey) { throw new Error('appKey 不能为空'); } - const cacheKey = this.getApiAppCacheKey(normalizedAppKey); + const cacheKey = this.getApiAppCacheKey(normalizedAppKey, interfaceTypeId); if (this.app && typeof this.app.getCacheAsync === 'function') { try { const cached = await this.app.getCacheAsync(cacheKey); @@ -41,9 +47,10 @@ class ApiSignService extends Service { } const row = await this.ctx.model.ApiApp.findOne({ - attributes: [ 'id', 'self_app_key', 'self_app_secret', 'is_enabled', 'interface_type_id' ], + attributes: [ 'id', 'self_app_key', 'self_app_secret', 'is_enabled', 'interface_type_id', 'warehouse_id' ], where: { self_app_key: normalizedAppKey, + interface_type_id: interfaceTypeId, }, raw: true, }); @@ -56,10 +63,6 @@ class ApiSignService extends Service { throw new Error('API 应用已禁用'); } - if (Number(row.interface_type_id) !== OPENAPI_INTERFACE_TYPE_ID) { - throw new Error('app_key 无效或不可用'); - } - if (!row.self_app_secret) { throw new Error('API 应用缺少 self_app_secret 配置'); } @@ -68,6 +71,8 @@ class ApiSignService extends Service { id: row.id, appKey: row.self_app_key, selfAppSecret: row.self_app_secret, + interfaceTypeId: Number(row.interface_type_id), + warehouseId: row.warehouse_id ? Number(row.warehouse_id) : null, }; if (this.app && typeof this.app.setCacheAsync === 'function') { @@ -83,10 +88,11 @@ class ApiSignService extends Service { /** * 根据 app_key 查询 API 应用密钥信息。 * @param {string} appKey 开放接口 app_key。 + * @param {number} [interfaceTypeId=2] 接口类型 ID。 * @return {Promise} 查询结果,包含应用主键与密钥。 */ - async getApiAppSecretByAppKey(appKey) { - return await this.getApiAppConfigByAppKey(appKey); + async getApiAppSecretByAppKey(appKey, interfaceTypeId = OPENAPI_INTERFACE_TYPE_ID) { + return await this.getApiAppConfigByAppKey(appKey, interfaceTypeId); } /** @@ -97,12 +103,13 @@ class ApiSignService extends Service { * @param {*} [options.body] 请求体。 * @param {string} options.providedSign 请求中携带的 sign。 * @param {string[]} [options.ignoreKeys] 额外忽略的 query 字段。 + * @param {number} [options.interfaceTypeId=2] 接口类型 ID。 * @return {Promise} 验签结果。 */ - async verifyRequestSignByAppKey({ appKey, query = {}, body, providedSign, ignoreKeys } = {}) { + async verifyRequestSignByAppKey({ appKey, query = {}, body, providedSign, ignoreKeys, interfaceTypeId = OPENAPI_INTERFACE_TYPE_ID } = {}) { let appConfig; try { - appConfig = await this.getApiAppSecretByAppKey(appKey); + appConfig = await this.getApiAppSecretByAppKey(appKey, interfaceTypeId); } catch (error) { return { ok: false, @@ -137,6 +144,8 @@ class ApiSignService extends Service { sign: verifyResult.expectedSign, appId: appConfig.id, appKey: appConfig.appKey, + interfaceTypeId: appConfig.interfaceTypeId, + warehouseId: appConfig.warehouseId, }; } } diff --git a/app/service/systems/express_platform.js b/app/service/systems/express_platform.js index bc5871f..23861a1 100644 --- a/app/service/systems/express_platform.js +++ b/app/service/systems/express_platform.js @@ -706,7 +706,7 @@ class ExpressPlatformService extends MainService { let playload = { object_Id: `${order.warehouse_id}_${order.id}_${order_tmp.business_key}`, // 菠萝派平台要求订单唯一标识必须为字符串 orderno: `${order.warehouse_id}_${order.id}_${order_tmp.business_key}`, // 菠萝派平台要求订单号必须为字符串 - plattradeno: order.source_order_codes || order.delivery_order_code || '', + plattradeno: order.sys_platform_code === 'DY'? order.source_order_codes.split(",")[0] : order.source_order_codes || order.delivery_order_code || '', ismultiplepieces: order.package_count > 1 ? 1 : 0, logisticno: allocatedWaybillMap.get(`${Number(order.id) || 0}:${Number(order_tmp.business_key) || 0}`) || '', logistictype: order.logistics_code || '', diff --git a/app/service/warehouse.js b/app/service/warehouse.js new file mode 100644 index 0000000..701d20e --- /dev/null +++ b/app/service/warehouse.js @@ -0,0 +1,274 @@ +'use strict'; + +const Service = require('egg').Service; + +const WAREHOUSE_INTERFACE_TYPE_ID = 3; + +class WarehouseService extends Service { + /** + * 解析 warehouse method,拆分为服务路径与动作名。 + * @param {string} methodName method 名称。 + * @return {{ servicePath: string, actionName: string }} 解析结果。 + */ + resolveWarehouseMethod(methodName = '') { + const method = String(methodName || '').trim(); + const parts = method.split('.').filter(Boolean); + const actionName = parts.pop() || ''; + const servicePath = parts.join('.'); + + return { + servicePath, + actionName, + }; + } + + /** + * 根据服务路径查找 warehouseMethods 下的目标服务。 + * @param {string} servicePath 服务路径。 + * @return {Object|null} 目标服务实例。 + */ + getWarehouseMethodService(servicePath = '') { + const { ctx } = this; + const pathSegments = String(servicePath || '').split('.').filter(Boolean); + let methodService = ctx.service.warehouseMethods; + + if (pathSegments.length === 0) { + return methodService; + } + + for (const segment of pathSegments) { + methodService = methodService && methodService[segment]; + } + + return methodService || null; + } + + /** + * 分发 warehouse method 到 warehouseMethods 目录。 + * 分发前统一注入仓库上下文(warehouseId/appKey)。 + * @param {string} methodName method 名称。 + * @param {Object} body 请求体。 + * @param {Object} query 请求 query。 + * @param {Object} warehouseInfo 仓库上下文信息。 + * @return {Promise} method 执行结果。 + */ + async dispatchWarehouseMethod(methodName, body, query, warehouseInfo) { + const { servicePath, actionName } = this.resolveWarehouseMethod(methodName); + const methodService = this.getWarehouseMethodService(servicePath); + + if (!methodService || typeof methodService[actionName] !== 'function') { + return { + ok: false, + httpStatus: 400, + code: 400, + message: `warehouse method 不存在: ${methodName}`, + data: null, + }; + } + + // 统一注入仓库上下文到方法服务实例 + if (warehouseInfo && typeof methodService.setInfo === 'function') { + methodService.setInfo( + null, // storeId + warehouseInfo.warehouseId, + warehouseInfo.appKey, + null, // customerId + null // warehouseCode + ); + } + + const methodResult = await methodService[actionName]({ + body, + query, + }); + + return { + ok: true, + httpStatus: 200, + code: 1, + message: 'ok', + data: methodResult, + }; + } + + /** + * 校验 warehouse 基础 query 参数。 + * @param {Object} query 请求 query 参数。 + * @return {boolean} 是否通过基础参数校验。 + */ + validateWarehouseParams(query) { + const requiredFields = [ 'method', 'v', 'timestamp' ]; + for (const field of requiredFields) { + if (!query || !query[field]) { + return false; + } + } + + if (typeof query.method !== 'string' || !query.method.includes('.')) { + return false; + } + + return true; + } + + /** + * 读取并解析 JSON 请求体。 + * @return {Promise} 解析后的 JSON 对象。 + */ + async parseJsonBody() { + const { ctx } = this; + let jsonData = ''; + + if (ctx.request.rawBody) { + jsonData = ctx.request.rawBody; + } else if (ctx.request.body !== undefined) { + jsonData = typeof ctx.request.body === 'string' + ? ctx.request.body + : JSON.stringify(ctx.request.body); + } else { + jsonData = await new Promise((resolve, reject) => { + let data = ''; + ctx.req.on('data', chunk => { + data += chunk; + }); + ctx.req.on('end', () => { + resolve(data); + }); + ctx.req.on('error', reject); + }); + } + + jsonData = jsonData ? String(jsonData) : ''; + if (!jsonData || jsonData.trim() === '') { + return { + ok: false, + httpStatus: 400, + code: 400, + message: 'json数据为空', + data: null, + }; + } + + try { + return JSON.parse(jsonData); + } catch (error) { + return { + ok: false, + httpStatus: 400, + code: 400, + message: 'json数据解析错误', + data: null, + }; + } + } + + /** + * 提取并归一化 warehouse 所需的 appKey 与 sign。 + * @param {Object} query 请求 query 参数。 + * @return {{ appKey: string, providedSign: string }} 归一化后的关键信息。 + */ + normalizeSignFields(query = {}) { + const appKey = String(query.app_key || query.appkey || query.self_app_key || '').trim(); + const providedSign = String(query.sign || query.signature || '').trim(); + + return { + appKey, + providedSign, + }; + } + + /** + * 处理 warehouse 请求并返回统一结果。 + * 核心差异:使用 interface_type_id=3(仓库级),无需合约关联,直接取 warehouse_id。 + * @return {Promise} 统一结果对象。 + */ + async processRequest() { + const { ctx } = this; + const query = ctx.query || {}; + + if (!this.validateWarehouseParams(query)) { + return { + ok: false, + httpStatus: 400, + code: 400, + message: '参数缺失或错误: method/v/timestamp', + data: null, + }; + } + + // 时间戳时效校验(±10分钟) + const nowTs = Math.floor(Date.now() / 1000); + const reqTs = Number(query.timestamp); + if (!Number.isFinite(reqTs) || Math.abs(nowTs - reqTs) > 600) { + return { + ok: false, + httpStatus: 400, + code: 400, + message: `时间戳已过期或无效,服务器时间: ${nowTs}`, + data: null, + }; + } + + const body = await this.parseJsonBody(); + if (body && body.ok === false) { + return body; + } + + const { appKey, providedSign } = this.normalizeSignFields(query); + if (!appKey) { + return { + ok: false, + httpStatus: 400, + code: 400, + message: '参数缺失或错误: app_key', + data: null, + }; + } + + const { systems: systemsService } = ctx.service; + const apiSignService = systemsService.apiSign; + + // 仓库级验签:interface_type_id = 3 + const verifyResult = await apiSignService.verifyRequestSignByAppKey({ + appKey, + query, + body, + providedSign, + interfaceTypeId: WAREHOUSE_INTERFACE_TYPE_ID, + }); + + if (!verifyResult.ok) { + return { + ok: false, + httpStatus: 401, + code: 401, + message: `签名校验失败: ${verifyResult.message}`, + data: null, + }; + } + + // 仓库级无需合约关联,直接使用 api_app.warehouse_id + const warehouseId = verifyResult.warehouseId; + if (!warehouseId) { + return { + ok: false, + httpStatus: 403, + code: 403, + message: 'API 应用未绑定仓库', + data: null, + }; + } + + const queryWithAppKey = { + ...query, + app_key: verifyResult.appKey, + }; + + return await this.dispatchWarehouseMethod(query.method, body, queryWithAppKey, { + warehouseId, + appKey: verifyResult.appKey, + }); + } +} + +module.exports = WarehouseService; diff --git a/app/service/warehouseMethods/index.js b/app/service/warehouseMethods/index.js new file mode 100644 index 0000000..78da1d1 --- /dev/null +++ b/app/service/warehouseMethods/index.js @@ -0,0 +1,22 @@ +'use strict'; + +const MainService = require('../main'); + +class WarehouseIndexService extends MainService { + /** + * 心跳接口,返回服务可用性与仓库上下文信息。 + * @return {Promise} 心跳响应。 + */ + async ping() { + const { warehouseId, appKey } = this.getInfo(); + + return { + warehouse_id: warehouseId, + app_key: appKey, + server_time: Math.floor(Date.now() / 1000), + status: 'ok', + }; + } +} + +module.exports = WarehouseIndexService; diff --git a/app/service/warehouseMethods/store.js b/app/service/warehouseMethods/store.js new file mode 100644 index 0000000..a4c8d68 --- /dev/null +++ b/app/service/warehouseMethods/store.js @@ -0,0 +1,88 @@ +'use strict'; + +const MainService = require('../main'); + +class WarehouseStoreService extends MainService { + /** + * 查询当前仓库下已授权的货主列表。 + * 返回货主基本信息(id、公司名、联系人、联系电话、授权状态)。 + * @param {Object} options 请求参数。 + * @param {Object} options.body 请求体。 + * @return {Promise} 货主列表。 + */ + async list({ body = {} } = {}) { + const { ctx } = this; + const { warehouseId } = this.getInfo(); + + const page = Math.max(1, Number(body.page) || 1); + const pageSize = Math.min(100, Math.max(1, Number(body.pageSize) || 20)); + + // 通过 store_warehouse 关联查询已授权的货主 + const { StoreWarehouse, Store } = ctx.model; + + const where = { + warehouse_id: warehouseId, + auth_status: 2, // 已通过 + warehouse_use_status: 1, // 仓库侧可用 + }; + + const { count: total, rows } = await StoreWarehouse.findAndCountAll({ + attributes: [ + 'id', + 'store_id', + 'auth_status', + 'auth_start', + 'auth_end', + 'store_remask', + 'warehouse_remask', + ], + where, + include: [ + { + model: Store, + as: 'store', + attributes: [ + 'id', + 'company_name', + 'contact_person', + 'contact_phone', + 'status', + ], + required: true, + where: { + status: 1, // 启用 + }, + }, + ], + offset: (page - 1) * pageSize, + limit: pageSize, + order: [[ 'id', 'DESC' ]], + raw: true, + }); + + const list = rows.map(row => ({ + store_id: row['store.id'], + company_name: row['store.company_name'], + contact_person: row['store.contact_person'], + contact_phone: row['store.contact_phone'], + contract_id: row.id, + auth_status: row.auth_status, + auth_start: row.auth_start, + auth_end: row.auth_end, + store_remask: row.store_remask, + warehouse_remask: row.warehouse_remask, + })); + + return { + list, + pagination: { + page, + pageSize, + total, + totalPages: Math.ceil(total / pageSize), + }, + }; + } +} + +module.exports = WarehouseStoreService; diff --git a/methods/changes/warehouse.json b/methods/changes/warehouse.json new file mode 100644 index 0000000..120a920 --- /dev/null +++ b/methods/changes/warehouse.json @@ -0,0 +1,22 @@ +[ + { + "version": "2026.08.01-warehouse-01", + "date": "2026-08-01", + "type": "added", + "summary": "新增 /warehouse 仓库开放 API 入口,支持仓库级外部适配器 HMAC-SHA256 签名鉴权调用,首批上线 index.ping 心跳 + store.list 货主列表", + "methods": [ + "index.ping", + "store.list" + ], + "notes": [ + "POST /warehouse 为新增入口,独立于 /openapi(货主级),鉴权使用 interface_type_id=3 的仓库 API 应用(由 apiApp 模块管理)。", + "签名算法与 /openapi 完全一致:query 参数字典序 + body 拼接 → HMAC-SHA256 → hex。", + "时间戳 ±10 分钟有效期,Redis 缓存 API 应用配置 300 秒(缓存前缀 warehouse:api-app)。", + "无需 StoreWarehouse 合约关联,直接通过 api_app.warehouse_id 确定仓库上下文。", + "index.ping:无需 body 参数,返回 warehouse_id / app_key / server_time / status。", + "store.list:分页查询当前仓库下已授权的货主,通过 wms_store_warehouse 关联 wms_store,仅返回 auth_status=2 + store.status=1 + warehouse_use_status=1 的记录。", + "api_sign.js 改造:getApiAppConfigByAppKey 新增 interfaceTypeId 参数(默认 2 保持向后兼容),warehouse 入口传 3,查询增加 interface_type_id 条件并返回 warehouse_id。" + ], + "module": "warehouse" + } +] diff --git a/methods/warehouse.json b/methods/warehouse.json new file mode 100644 index 0000000..4c24677 --- /dev/null +++ b/methods/warehouse.json @@ -0,0 +1,203 @@ +{ + "module": "warehouse", + "description": "仓库开放 API 统一入口,供仓库级外部适配器(企微/钉钉/飞书/IM 等)调用,HTTP POST /warehouse,使用 HMAC-SHA256 签名鉴权(interface_type_id=3)", + "version": "1.0.0", + "updatedAt": "2026-08-01", + "http": { + "path": "/warehouse", + "method": "POST" + }, + "headers": [], + "methods": { + "groups": [ + { + "groupName": "基础模块", + "module": "index", + "list": [ + { + "method": "index.ping", + "description": "心跳接口,验证仓库 API 应用连通性,返回仓库上下文与应用信息", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [], + "response": [ + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "当前仓库 ID" + }, + { + "name": "app_key", + "type": "string", + "required": true, + "description": "当前请求的 AppKey" + }, + { + "name": "server_time", + "type": "number", + "required": true, + "description": "服务器 Unix 时间戳(秒)" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "服务状态,正常时返回 ok" + } + ], + "errors": [], + "notes": [ + "模块:基础模块", + "方法部署位置:warehouseMethods/index.ping", + "无需 body 参数,GET query 参数满足 method/v/timestamp/app_key/sign 即可", + "timestamp 时间戳时效校验:与服务器时间差不得超过 ±10 分钟(600 秒),否则返回 400" + ] + } + ] + }, + { + "groupName": "货主模块", + "module": "store", + "list": [ + { + "method": "store.list", + "description": "查询当前仓库下已授权的货主列表,返回货主基本信息与授权状态(需 auth_status=2 已通过 + store.status=1 启用 + warehouse_use_status=1 可用)", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "page", + "type": "number", + "required": false, + "source": "body", + "description": "页码,默认 1", + "defaultValue": 1 + }, + { + "name": "pageSize", + "type": "number", + "required": false, + "source": "body", + "description": "每页数量,默认 20,最大 100", + "defaultValue": 20 + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "货主列表", + "children": [ + { + "name": "store_id", + "type": "number", + "required": true, + "description": "货主 ID(wms_store.id)" + }, + { + "name": "company_name", + "type": "string", + "required": true, + "description": "公司全称" + }, + { + "name": "contact_person", + "type": "string", + "required": true, + "description": "联系人" + }, + { + "name": "contact_phone", + "type": "string", + "required": true, + "description": "联系电话" + }, + { + "name": "contract_id", + "type": "number", + "required": true, + "description": "授权关系 ID(wms_store_warehouse.id)" + }, + { + "name": "auth_status", + "type": "number", + "required": true, + "description": "授权状态:2=已通过" + }, + { + "name": "auth_start", + "type": "string", + "required": false, + "description": "授权开始日期" + }, + { + "name": "auth_end", + "type": "string", + "required": false, + "description": "授权结束日期" + }, + { + "name": "store_remask", + "type": "string", + "required": false, + "description": "商家备注" + }, + { + "name": "warehouse_remask", + "type": "string", + "required": false, + "description": "仓库备注" + } + ] + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息", + "children": [ + { + "name": "page", + "type": "number", + "required": true, + "description": "当前页码" + }, + { + "name": "pageSize", + "type": "number", + "required": true, + "description": "每页数量" + }, + { + "name": "total", + "type": "number", + "required": true, + "description": "总记录数" + }, + { + "name": "totalPages", + "type": "number", + "required": true, + "description": "总页数" + } + ] + } + ], + "errors": [], + "notes": [ + "模块:货主模块", + "方法部署位置:warehouseMethods/store.list", + "仓库隔离:自动使用当前 API 应用绑定的 warehouse_id", + "仅返回已通过授权(auth_status=2)、仓库侧可用(warehouse_use_status=1)、货主启用(store.status=1)的记录", + "分页查询:默认 20 条/页,最大 100 条/页" + ] + } + ] + } + ] + } +} diff --git a/script/deploy-remote.cjs b/script/deploy-remote.cjs index c89dde2..177f04d 100644 --- a/script/deploy-remote.cjs +++ b/script/deploy-remote.cjs @@ -148,6 +148,33 @@ function main() { const startLogPath = `/tmp/wms-${targetVersion}-start.log`; const currentMdPath = `${config.deployRoot}/current.md`; + // 5.5. 强制清理目标端口残留进程,防止端口占用导致启动失败 + const killPortScript = [ + 'set -euo pipefail', + `TARGET_PORT=${targetPort}`, + 'PORT_PID=$(ss -tlnp 2>/dev/null | awk -v p=":$TARGET_PORT " \'index($0, p) { print $0 }\' | grep -oP \'pid=\\K[0-9]+\' | head -1 || true)', + 'if [ -n "$PORT_PID" ]; then', + ` echo "检测到端口 $TARGET_PORT 被进程 $PORT_PID 占用,强制停止..."`, + ' kill -9 "$PORT_PID" 2>/dev/null || true', + ' sleep 1', + ' PORT_PID_CHECK=$(ss -tlnp 2>/dev/null | awk -v p=":$TARGET_PORT " \'index($0, p) { print $0 }\' | grep -oP \'pid=\\K[0-9]+\' | head -1 || true)', + ' if [ -n "$PORT_PID_CHECK" ]; then', + ` echo "[WARN] 端口 $TARGET_PORT 仍有残留进程 $PORT_PID_CHECK,尝试再次强制停止..."`, + ' fuser -k "$TARGET_PORT/tcp" 2>/dev/null || true', + ' fi', + ` echo "端口 $TARGET_PORT 已释放"`, + 'else', + ` echo "端口 $TARGET_PORT 空闲,无需清理"`, + 'fi', + ].join('\n'); + + try { + const killPortOutput = runSsh(config, killPortScript, { stdio: 'pipe' }); + console.log(String(killPortOutput || '').trim()); + } catch (err) { + console.warn(`[WARN] 端口 ${targetPort} 清理失败: ${err.message}`); + } + // 6. 更新远端 current.md 并启动新实例 const switchAndStartScript = [ 'set -euo pipefail', @@ -162,17 +189,17 @@ function main() { const switchOutput = runSsh(config, switchAndStartScript, { stdio: 'pipe' }); console.log(String(switchOutput || '').trim()); - // 6.5. 健康检查新实例(curl 循环等待,最多 10 秒) + // 6.5. 健康检查新实例(curl 循环等待,最多 20 秒) const oldDir = `${config.deployRoot}/${currentVersion}`; const healthCheckScript = [ 'set -euo pipefail', `TARGET_PORT=${targetPort}`, - 'for attempt in $(seq 1 5); do', + 'for attempt in $(seq 1 10); do', ' if curl -fsS --connect-timeout 2 --max-time 3 "http://127.0.0.1:$TARGET_PORT/" >/dev/null 2>&1; then', ` echo "新实例 (${targetVersion}) 健康检查通过 (端口 $TARGET_PORT)"`, ' break', ' fi', - ' if [ "$attempt" -eq 5 ]; then', + ' if [ "$attempt" -eq 10 ]; then', ` echo "新实例 (${targetVersion}) 健康检查超时 (端口 $TARGET_PORT)" >&2`, ' exit 1', ' fi', @@ -185,8 +212,8 @@ function main() { console.log(String(healthOutput || '').trim()); } catch (err) { // 健康检查失败 → 不做切换,回滚 current.md 并清理失败的新实例 - console.error(`[ERROR] 新实例健康检查失败 (10s 超时): ${err.message}`); - console.error(`[ERROR] 发布中止:不切换 Nginx upstream,不停旧实例`); + console.error(`[ERROR] 新实例健康检查失败 (20s 超时): ${err.message}`); + console.error(`[ERROR] 发布中止:不切换 Nginx upstream,不停旧实例。可检查启动日志 ${startLogPath}`); // 回滚:将 current.md 恢复为旧版本 const revertCurrentMdScript = [ From f747e73aea58d97620bbc71a73fb2186434d85b7 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sat, 1 Aug 2026 15:59:22 +0800 Subject: [PATCH 147/550] =?UTF-8?q?fix(deliveryOrder):=20=E8=B4=A7?= =?UTF-8?q?=E4=B8=BB=E9=BB=98=E8=AE=A4=E9=85=8D=E7=BD=AE=E7=BB=9F=E4=B8=80?= =?UTF-8?q?=E8=AF=BB=E5=8F=96=E5=90=88=E7=BA=A6=20policy=5Fconfig=EF=BC=8C?= =?UTF-8?q?=E7=A7=BB=E9=99=A4=E5=AF=B9=20wms=5Fstore.subject=5Fconfig=20?= =?UTF-8?q?=E7=9A=84=E9=94=99=E8=AF=AF=E4=BE=9D=E8=B5=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - prepareOrderData 不再调用 getStoreSubjectConfig(storeId) 读取死数据 - resolveExpressSnapshot: 默认快递编码统一从合约 policy_config 读取 - resolvePlatformSnapshot: 兜底平台编码只走合约 policy_config - resolveEnableExternalExpressCode: 移除 storeSubjectConfig 死数据兜底 - 仓库级 getStoreSubjectConfig(warehouseId) 保留(有 warehouse setting 更新入口) --- app/service/systems/delivery_order.js | 36 +++++++++++++-------------- 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/app/service/systems/delivery_order.js b/app/service/systems/delivery_order.js index e672941..9cbc534 100644 --- a/app/service/systems/delivery_order.js +++ b/app/service/systems/delivery_order.js @@ -318,11 +318,11 @@ class DeliveryOrderService extends Service { * 优先级: * 1. 先匹配平台列表里的基础平台项; * 2. 再匹配平台列表里的系统设置项; - * 3. 兜底:签约策略 default_platform_code(货主-仓库级)→ 货主 subject_config.default_platform_code。 + * 3. 兜底:合约 policy_config.default_platform_code。 * * @param {string} sourcePlatformCode 外部平台编码。 - * @param {Object} storeSubjectConfig 货主签约配置。 - * @param {Object} [policyConfig={}] 货主-仓库签约策略配置。 + * @param {Object} storeSubjectConfig 合约 policy_config。 + * @param {Object} [policyConfig={}] 合约策略配置。 * @param {Object} [info={}] 上下文信息。 * @param {Array} [operationLogs=[]] 待写入的操作日志数组。 * @return {Promise} 平台快照。 @@ -350,7 +350,7 @@ class DeliveryOrderService extends Service { sourcePlatformCode: externalCode, }); - // 兜底优先级:签约策略(货主-仓库级)→ 货主 subject_config + // 兜底优先级:合约 policy_config const policyDefaultCode = String(policyConfig && policyConfig.default_platform_code || '').trim(); const ownerDefaultCode = String(storeSubjectConfig && storeSubjectConfig.default_platform_code || '').trim(); const defaultCode = policyDefaultCode || ownerDefaultCode; @@ -458,10 +458,10 @@ class DeliveryOrderService extends Service { /** * 解析是否启用外部快递编码。 * - * 优先级:显式值 -> policy_config -> storeSubjectConfig,均未提供时默认关闭。 + * 优先级:显式值 -> policy_config,均未提供时默认关闭。 * - * @param {Object} storeSubjectConfig 货主签约配置。 - * @param {Object} policyConfig 仓库策略配置。 + * @param {Object} storeSubjectConfig 合约 policy_config(与 policyConfig 同源)。 + * @param {Object} policyConfig 合约策略配置。 * @param {any} explicitValue 显式指定值。 * @return {boolean} 是否启用外部快递编码。 */ @@ -484,17 +484,15 @@ class DeliveryOrderService extends Service { /** * 解析订单快递快照。 * - * 默认快递编码优先级: - * 1. storeSubjectConfig.default_express_code(货主级,个性化配置) - * 2. policyConfig.default_express_code(仓库级,通用配置) + * 默认快递编码统一从合约 policy_config 读取。 * * 分支路由: * 1. 先读取是否启用外部快递编码开关; - * 2. 开关关闭时,直接使用上述优先级的默认快递回填四个快递字段; + * 2. 开关关闭时,直接使用合约默认快递回填四个快递字段; * 3. 开关开启时,先匹配 wms_express_setting,再匹配 wms_express,最后回退默认快递。 * * @param {string} logisticsCode 外部快递编码。 - * @param {Object} storeSubjectConfig 货主签约配置。 + * @param {Object} storeSubjectConfig 合约 policy_config。 * @param {Object} [info={}] 上下文信息,可含 policyConfig / enableExternalExpressCode / warehouseId。 * @param {Array} [operationLogs=[]] 待写入的操作日志数组。 * @return {Promise} 快递快照。 @@ -503,12 +501,15 @@ class DeliveryOrderService extends Service { const expressList = await this.ctx.service.systems.express.getExpressList(); const externalCode = String(logisticsCode || '').trim(); - // 货主 subject_config 优先于仓库 policy_config(货主个性配置高于仓库通用配置) + // 默认快递编码统一从合约 policy_config 读取 const policyConfig = info && info.policyConfig && typeof info.policyConfig === 'object' ? info.policyConfig : {}; + const contractConfig = storeSubjectConfig && typeof storeSubjectConfig === 'object' + ? storeSubjectConfig + : {}; const defaultCode = String( - (storeSubjectConfig && storeSubjectConfig.default_express_code) + contractConfig.default_express_code || policyConfig.default_express_code || '' ).trim(); @@ -1051,15 +1052,14 @@ class DeliveryOrderService extends Service { receiverInfo, } = deliveryOrder; - const storeSubjectConfig = await this.getStoreSubjectConfig(info.storeId); const policyConfig = await this.getStoreWarehousePolicyConfig(info.storeId, info.warehouseId); - const enableExternalExpressCode = this.resolveEnableExternalExpressCode(storeSubjectConfig, policyConfig); - const platformSnapshot = await this.resolvePlatformSnapshot(sourcePlatformCode, storeSubjectConfig, policyConfig, { + const enableExternalExpressCode = this.resolveEnableExternalExpressCode(policyConfig, policyConfig); + const platformSnapshot = await this.resolvePlatformSnapshot(sourcePlatformCode, policyConfig, policyConfig, { deliveryOrderCode, warehouseId: info.warehouseId, storeId: info.storeId, }, operationLogs); - const expressSnapshot = await this.resolveExpressSnapshot(logisticsCode, storeSubjectConfig, { + const expressSnapshot = await this.resolveExpressSnapshot(logisticsCode, policyConfig, { deliveryOrderCode, warehouseId: info.warehouseId, storeId: info.storeId, From 8ee12374b314396054e12af554f5060b3b973e14 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sun, 2 Aug 2026 00:34:32 +0800 Subject: [PATCH 148/550] =?UTF-8?q?fix(storage.entry.get):=20=E7=A7=BB?= =?UTF-8?q?=E9=99=A4=20items[].stock=20=E4=B8=AD=E5=A4=9A=E4=BD=99?= =?UTF-8?q?=E7=9A=84=20quantity/locked=5Fquantity=20=E5=AD=97=E6=AE=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/systems/storage/entry.js | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/app/service/systems/storage/entry.js b/app/service/systems/storage/entry.js index 466187c..c138a2f 100644 --- a/app/service/systems/storage/entry.js +++ b/app/service/systems/storage/entry.js @@ -690,12 +690,17 @@ class EntryService extends Service { const receivedQty = Number(item.received_quantity) || 0; const completed = receivedQty > 0 ? receivedQty : directInQty; + const stockDetail = stockMap.get(Number(item.stock_id)); + const stock = stockDetail + ? (s => { delete s.quantity; delete s.locked_quantity; return s; })({ ...stockDetail }) + : null; + return { id: item.id, stock_id: item.stock_id, planned: planQty, completed, - stock: stockMap.get(Number(item.stock_id)) || null, + stock, }; }); From 05b71b2f31efbd94d23b446d754e6f8d3c3f0431 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sun, 2 Aug 2026 00:35:08 +0800 Subject: [PATCH 149/550] =?UTF-8?q?feat:=20=E6=8A=96=E9=9F=B3=E9=9D=A2?= =?UTF-8?q?=E5=8D=95=E8=87=AA=E5=AE=9A=E4=B9=89=E5=8C=BA=E6=A8=A1=E6=9D=BF?= =?UTF-8?q?=E5=87=BA=E5=8F=A3=E5=9F=9F=E5=90=8D=E6=94=B9=E4=B8=BA=E5=8F=AF?= =?UTF-8?q?=E9=85=8D=E7=BD=AE=E8=B7=AF=E7=94=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - config.default.js: 新增 customAreaBaseUrl 出口域名配置 - router.js: 新增 GET /mb/douyin1.xml 路由 - controller/template.js: 新增 douyinCustomArea() 方法输出静态 XML - printer_data_builder.js: applyDouyinExpressFieldMapping 支持 customAreaBaseUrl 参数 - order_print.js: 将 app.config.customAreaBaseUrl 传入 buildPlatformRequestSkeleton - douyin.json: 移除硬编码 templateURL,由运行时代码动态拼装 --- app/controller/template.js | 14 ++++++++++++++ app/lib/printer_data_builder.js | 10 +++++++--- app/router.js | 3 +++ app/service/systems/order_print.js | 1 + config/config.default.js | 2 ++ printer_data_template/douyin.json | 3 +-- 6 files changed, 28 insertions(+), 5 deletions(-) diff --git a/app/controller/template.js b/app/controller/template.js index 33c5868..21cf12e 100644 --- a/app/controller/template.js +++ b/app/controller/template.js @@ -8,5 +8,19 @@ class TemplateController extends Controller { const result = await service.systems.setting.printTemplate.getXmlByTemplate(ctx.params.id); ctx.body = result; } + + /** + * 输出抖音面单自定义区模板 XML(douyin1.xml) + */ + async douyinCustomArea() { + const { ctx } = this; + ctx.type = 'application/xml'; + ctx.body = ` + + + ]]> + +`; + } } module.exports = TemplateController; diff --git a/app/lib/printer_data_builder.js b/app/lib/printer_data_builder.js index c389d8e..8f4cfa7 100644 --- a/app/lib/printer_data_builder.js +++ b/app/lib/printer_data_builder.js @@ -1584,8 +1584,10 @@ function resolveDouyinParams(orderExpress) { * @param {Object} orderExpress 快递单对象。 * @param {Object} orderDelivery 订单对象。 * @param {Object} policyConfig 策略配置对象。 + * @param {string[]} extraCustomLines 额外的自定义文本行。 + * @param {string} customAreaBaseUrl 自定义区模板出口域名。 */ -function applyDouyinExpressFieldMapping(platform, skeleton, orderExpress, orderDelivery, policyConfig, extraCustomLines = []) { +function applyDouyinExpressFieldMapping(platform, skeleton, orderExpress, orderDelivery, policyConfig, extraCustomLines = [], customAreaBaseUrl = '') { if (platform !== 'douyin') { return; } @@ -1697,7 +1699,8 @@ function applyDouyinExpressFieldMapping(platform, skeleton, orderExpress, orderD } const customContent = contents[1]; if (!toTrimmedString(customContent.templateURL)) { - customContent.templateURL = 'http://www.ye4s.com/mb/douyin1.xml'; + const baseUrl = toTrimmedString(customAreaBaseUrl) || 'http://www.ye4s.com'; + customContent.templateURL = baseUrl + '/mb/douyin1.xml'; } customContent.data = isPlainObject(customContent.data) ? customContent.data : {}; customContent.data.productInfo = customProductInfo || '无拣货信息'; @@ -2415,7 +2418,8 @@ function buildPlatformRequestSkeleton(input = {}) { orderExpressForCompose, orderDeliveryForCompose, policyConfig, - extraCustomLines + extraCustomLines, + options.customAreaBaseUrl ); applyJdExpressFieldMapping( diff --git a/app/router.js b/app/router.js index c583b96..fb4cd42 100644 --- a/app/router.js +++ b/app/router.js @@ -50,6 +50,9 @@ module.exports = app => { // 打印模板 router.get('/template/xml/:id', controller.template.xml); + // 打印自定义区模板(抖音面单等) + router.get('/mb/douyin1.xml', controller.template.douyinCustomArea); + // 打印台设置 router.get('/auth/printSetting/:code', controller.auth.printerSetting); router.post('/auth/printSetting/', controller.auth.printerSetting); diff --git a/app/service/systems/order_print.js b/app/service/systems/order_print.js index 3db9e1a..86d833a 100644 --- a/app/service/systems/order_print.js +++ b/app/service/systems/order_print.js @@ -3055,6 +3055,7 @@ ${waveFilterSql} documentId, packageMaterialName: suggestedPackageMaterialName, extraCustomLines, + customAreaBaseUrl: this.ctx.app.config.customAreaBaseUrl || '', }, }); const printData = this.extractSinglePlatformPrintData(printPayload); diff --git a/config/config.default.js b/config/config.default.js index 79dc675..7e1a222 100644 --- a/config/config.default.js +++ b/config/config.default.js @@ -210,6 +210,8 @@ module.exports = appInfo => { batchSize: 50, force: false, }; + // 打印自定义区模板出口域名 + config.customAreaBaseUrl = 'https://api.ye4s.com'; return { ...config, diff --git a/printer_data_template/douyin.json b/printer_data_template/douyin.json index be5d3f9..fe21b24 100644 --- a/printer_data_template/douyin.json +++ b/printer_data_template/douyin.json @@ -47,8 +47,7 @@ { "data": { "productInfo": "#0 B1340646-1-1 商品总数 【2】\nE1区06-11-01 6949517008816;6949517008342;6949517008229 【1】 0\nE1区06-08-01 69000007 【1】 0\n\n验视员:" - }, - "templateURL": "http://www.ye4s.com/mb/douyin1.xml" + } } ] } From d6e4de6edc9490529af4fec61bfdb8333448bc6d Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sun, 2 Aug 2026 00:35:56 +0800 Subject: [PATCH 150/550] =?UTF-8?q?fix(wave):=20=E6=B3=A2=E6=AC=A1?= =?UTF-8?q?=E8=AE=A2=E5=8D=95=E7=A7=BB=E5=87=BA/=E5=8F=96=E6=B6=88?= =?UTF-8?q?=E5=90=8E=20wms=5Forder=5Fwave=5Findex=20=E6=9C=AA=E9=87=8D?= =?UTF-8?q?=E6=96=B0=E6=8E=92=E5=BA=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - batchRemoveOrders: 用 replaceOrderWaveIndexByWaveIds 替换手动 COUNT,移出后自动重排 wave_index - cancelWavePickTasksInternal: PDA拣货任务取消释放波次时清理 wms_order_wave_index - batchFinishAutoGrouping: 关闭自动加团前重建波次索引,确保 wave_index 连续 - cancelOrder(pendingOrder): 取消待处理订单后重建受影响波次索引 - cloneOrder: 克隆取消原订单时清理波次关联并重建索引 - Qimen取消: 奇门取消订单后重建波次索引 - OpenAPI取消: 新增完整波次清理逻辑(清除wave_id+删索引+重建+更新WaveBatch) - 新增 resortWaveIndex 内部方法用于强制重排历史数据 --- app/service/openapiMethods/order.js | 54 ++++- app/service/qimenMethods/order.js | 14 +- .../systemMethods/order/pendingOrder.js | 58 ++++- app/service/systemMethods/order/wave.js | 224 +++++++++++++++--- methods/system.json | 10 +- 5 files changed, 310 insertions(+), 50 deletions(-) diff --git a/app/service/openapiMethods/order.js b/app/service/openapiMethods/order.js index 5365ab9..85cc3f6 100644 --- a/app/service/openapiMethods/order.js +++ b/app/service/openapiMethods/order.js @@ -65,15 +65,65 @@ class OpenapiOrderService extends MainService { return this.fail('取消失败,已通知拦截执行'); } - await existingOrder.update({ + // 检查是否在波次中,若在波次中需清除波次关联 + const existingWaveId = Number(existingOrder.wave_id || 0); + + const updateValues = { status: 'cancel', outbound_status: 'fin', step: 4, updated_at: new Date(), - }, { + }; + if (existingWaveId > 0) { + updateValues.wave_id = 0; + updateValues.wave_no = ''; + } + + await existingOrder.update(updateValues, { transaction, }); + // 波次清理:删除波次索引、重建波次索引、更新波次统计 + if (existingWaveId > 0) { + try { + await ctx.service.systemMethods.order.wave.deleteOrderWaveIndexByOrderIds({ + warehouseId, + orderIds: [ existingOrder.id ], + transaction, + }); + + await ctx.service.systemMethods.order.wave.replaceOrderWaveIndexByWaveIds({ + warehouseId, + waveIds: [ existingWaveId ], + orderModel: DeliveryModel, + transaction, + }); + + const WaveBatch = ctx.model.WaveBatch; + if (WaveBatch) { + const wave = await WaveBatch.findOne({ + where: { wave_id: existingWaveId, warehouse_id: warehouseId }, + attributes: [ 'wave_id', 'total_orders', 'wave_status' ], + raw: true, + transaction, + }); + + if (wave) { + 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: new Date() }, + { where: { wave_id: existingWaveId, warehouse_id: warehouseId }, transaction } + ); + } + } + } + } catch (waveErr) { + ctx.logger.warn('[OpenapiOrderCancel] 清理波次关联失败,不影响订单取消', waveErr); + } + } + // 释放储位分配锁定库存 await this.releaseStockLockForCancel({ orderId: existingOrder.id, diff --git a/app/service/qimenMethods/order.js b/app/service/qimenMethods/order.js index 400217b..4110b00 100644 --- a/app/service/qimenMethods/order.js +++ b/app/service/qimenMethods/order.js @@ -243,7 +243,15 @@ class orderServer extends MainService { try { await ctx.service.systemMethods.order.wave.deleteOrderWaveIndexByOrderIds({ warehouseId: info.warehouseId, - orderIds: [existingOrder.id], + orderIds: [ existingOrder.id ], + transaction, + }); + + // 重建受影响波次的订单索引(wave_index 重新排序) + await ctx.service.systemMethods.order.wave.replaceOrderWaveIndexByWaveIds({ + warehouseId: info.warehouseId, + waveIds: [ existingWaveId ], + orderModel: DeliveryModel, transaction, }); @@ -262,7 +270,7 @@ class orderServer extends MainService { const wave = await WaveBatch.findOne({ where: { wave_id: existingWaveId, warehouse_id: info.warehouseId }, - attributes: ['wave_id', 'total_orders', 'wave_status'], + attributes: [ 'wave_id', 'total_orders', 'wave_status' ], raw: true, transaction, }); @@ -297,7 +305,7 @@ class orderServer extends MainService { try { ctx.service.systemMethods.order.wave.enqueueWaveStrategyQuickScanPostOrderChange( info.warehouseId, - [existingOrder.id], + [ existingOrder.id ], { triggerScan: true, source: 'qimenCancel' } ); } catch (scanErr) { diff --git a/app/service/systemMethods/order/pendingOrder.js b/app/service/systemMethods/order/pendingOrder.js index 3e02550..6f6bb79 100644 --- a/app/service/systemMethods/order/pendingOrder.js +++ b/app/service/systemMethods/order/pendingOrder.js @@ -1992,13 +1992,22 @@ class PendingOrderService extends OrderBaseService { * 批量分配待处理订单的快递号,并复用现有运单创建核心链路。 * * @param {Object} data 请求体。 - * @param {Array} data.orders 订单对象数组。 + * @param {Array} data.ids 订单 ID 数组(推荐)。 + * @param {Array} [data.orders] 订单对象数组(兼容旧格式,新调用方请使用 ids)。 * @return {Promise} 统一 success 包装,立即返回 task_id。 */ async allocateExpressCode(data) { - const { orders } = data || {}; - if (!Array.isArray(orders)) { - throw new Error('分配快递号接口仅支持订单对象数组入参'); + const { ids, orders: legacyOrders } = data || {}; + + // 新格式:ids,直接转为管线所需格式(business_key 固定为 1) + let orders; + if (Array.isArray(ids) && ids.length > 0) { + orders = ids.map(id => ({ order_id: Number(id), business_key: 1 })); + } else if (Array.isArray(legacyOrders)) { + // 兼容旧格式:orders 对象数组 + orders = legacyOrders; + } else { + throw new Error('分配快递号接口需要传入 ids(订单ID数组)或 orders(订单对象数组)'); } const { service } = this; @@ -2345,6 +2354,18 @@ class PendingOrderService extends OrderBaseService { orderIds: waveOrderIds, transaction: undefined, }); + + // 重建受影响波次的订单索引(wave_index 重新排序) + const affectedWaveIds = [ ...new Set(ordersWithWave + .map(order => Number(order.wave_id)) + .filter(waveId => Number.isInteger(waveId) && waveId > 0)) ]; + if (affectedWaveIds.length > 0) { + await this.ctx.service.systemMethods.order.wave.replaceOrderWaveIndexByWaveIds({ + warehouseId, + waveIds: affectedWaveIds, + orderModel: model, + }); + } } if (WaveBatch) { @@ -3014,14 +3035,37 @@ class PendingOrderService extends OrderBaseService { } const now = new Date(); + const originalWaveId = Number(original.wave_id || 0); - // 3. 取消原订单 - await model.update({ + // 3. 取消原订单(若在波次中需清除波次关联) + const cancelUpdateValues = { status: 'cancel', step: 9, outbound_status: 'padding', updated_at: now, - }, { where }); + }; + if (originalWaveId > 0) { + cancelUpdateValues.wave_id = 0; + cancelUpdateValues.wave_no = ''; + } + await model.update(cancelUpdateValues, { where }); + + // 克隆时清理波次索引(不影响主流程) + if (originalWaveId > 0) { + try { + await this.ctx.service.systemMethods.order.wave.deleteOrderWaveIndexByOrderIds({ + warehouseId, + orderIds: [ orderId ], + }); + await this.ctx.service.systemMethods.order.wave.replaceOrderWaveIndexByWaveIds({ + warehouseId, + waveIds: [ originalWaveId ], + orderModel: model, + }); + } catch (waveErr) { + this.ctx.logger.warn('[PendingOrderService.cloneOrder] 清理波次关联失败,不影响克隆', waveErr); + } + } // 记录原订单"克隆"日志 try { diff --git a/app/service/systemMethods/order/wave.js b/app/service/systemMethods/order/wave.js index e42038d..6456763 100644 --- a/app/service/systemMethods/order/wave.js +++ b/app/service/systemMethods/order/wave.js @@ -3012,7 +3012,7 @@ class WaveService extends OrderBaseService { AND o.lock_status = 'none' INNER JOIN ( SELECT - COALESCE(NULLIF(TRIM(COALESCE(src.items_hash, '')), ''), TRIM(COALESCE(src.items, ''))) AS structure_key, + src.items_hash AS structure_key, COUNT(1) AS same_structure_count FROM ${orderTableName} src WHERE src.warehouse_id = :warehouseId @@ -3025,9 +3025,9 @@ class WaveService extends OrderBaseService { AND src.outbound_status != 'padding' AND src.intercept_status = 'none' AND src.lock_status = 'none' - GROUP BY COALESCE(NULLIF(TRIM(COALESCE(src.items_hash, '')), ''), TRIM(COALESCE(src.items, ''))) + GROUP BY src.items_hash ) same_structure - ON same_structure.structure_key = COALESCE(NULLIF(TRIM(COALESCE(o.items_hash, '')), ''), TRIM(COALESCE(o.items, ''))) + ON same_structure.structure_key = o.items_hash INNER JOIN wms_wave_strategy s ON s.id = m.strategy_id AND s.warehouse_id = :warehouseId @@ -7061,39 +7061,14 @@ class WaveService extends OrderBaseService { const updatedOrderCount = Number(Array.isArray(orderUpdateResult) ? orderUpdateResult[0] : orderUpdateResult || 0); - await this.deleteOrderWaveIndexByOrderIds({ + // 重建受影响波次的订单索引(wave_index 重新排序),并获取各波次剩余订单数量 + const remainingCountMap = await this.replaceOrderWaveIndexByWaveIds({ warehouseId, - orderIds: removedOrderIds, + waveIds: affectedWaveIds, + orderModel, transaction, }); - const remainingRows = await orderModel.findAll({ - attributes: [ - 'wave_id', - [ this.ctx.model.fn('COUNT', this.ctx.model.col('id')), 'remaining_count' ], - ], - where: { - wave_id: { - [Op.in]: affectedWaveIds, - [Op.gt]: 0, - }, - }, - group: [ 'wave_id' ], - raw: true, - transaction, - }); - - const remainingCountMap = new Map(); - for (const row of (Array.isArray(remainingRows) ? remainingRows : [])) { - const waveId = Number(row && row.wave_id || 0); - const remainingCount = Number(row && row.remaining_count || 0); - if (!Number.isInteger(waveId) || waveId <= 0) { - continue; - } - - remainingCountMap.set(waveId, Number.isInteger(remainingCount) && remainingCount > 0 ? remainingCount : 0); - } - const updatedWaveIds = []; const emptiedWaveIds = []; @@ -7171,6 +7146,173 @@ class WaveService extends OrderBaseService { } } + /** + * 强制重排指定波次的订单索引(wave_index)。 + * + * 用于修正历史数据中因各种原因导致的 wave_index 不连续问题。 + * 内部调用 replaceOrderWaveIndexByWaveIds 完成索引重建,并同步更新 wms_wave_batch.total_orders。 + * + * @param {Object} data 请求参数。 + * @param {Array|number|string} [data.wave_ids] 波次ID集合。 + * @param {Array|number|string} [data.waveIds] 波次ID集合(驼峰写法)。 + * @return {Promise} 重排结果,含各波次重排前后的订单数量。 + */ + async resortWaveIndex(data = {}) { + const contextWarehouseId = Number(this.getWarehouseId() || 0); + if (!Number.isInteger(contextWarehouseId) || contextWarehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + + const warehouseId = contextWarehouseId; + const rawWaveIds = data && ( + data.wave_ids !== undefined ? data.wave_ids + : data.waveIds !== undefined ? data.waveIds + : data.wave_id !== undefined ? data.wave_id + : data.waveId !== undefined ? data.waveId + : null + ); + const normalizedWaveIds = this.normalizeIdsInput(rawWaveIds); + if (normalizedWaveIds.length === 0) { + throw new Error('wave_ids 参数不能为空或格式错误'); + } + + const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + const transaction = await this.ctx.model.transaction(); + + try { + // 重排前记录各波次每单的 wave_index,用于对比是否实际发生重排 + const beforeRows = await this.ctx.model.query(` + SELECT wave_id, order_id, wave_index + FROM wms_order_wave_index + WHERE warehouse_id = :warehouseId + AND wave_id IN (:waveIds) + ORDER BY wave_id, order_id + `, { + replacements: { warehouseId, waveIds: normalizedWaveIds }, + type: this.ctx.model.QueryTypes.SELECT, + transaction, + }); + + const beforeIndexMap = new Map(); // waveId -> Map(orderId -> wave_index) + const beforeCountMap = new Map(); + for (const row of (Array.isArray(beforeRows) ? beforeRows : [])) { + const waveId = Number(row && row.wave_id || 0); + const orderId = Number(row && row.order_id || 0); + const waveIndex = Number(row && row.wave_index || 0); + if (!Number.isInteger(waveId) || waveId <= 0) continue; + if (!beforeIndexMap.has(waveId)) beforeIndexMap.set(waveId, new Map()); + if (Number.isInteger(orderId) && orderId > 0) { + beforeIndexMap.get(waveId).set(orderId, Number.isInteger(waveIndex) ? waveIndex : 0); + } + beforeCountMap.set(waveId, (beforeCountMap.get(waveId) || 0) + 1); + } + + // 重建波次索引(内部先删后插,wave_index 从 1 开始连续编号) + const remainingCountMap = await this.replaceOrderWaveIndexByWaveIds({ + warehouseId, + waveIds: normalizedWaveIds, + orderModel, + transaction, + }); + + // 重排后查询各波次每单的 wave_index,用于对比是否实际发生变化 + const afterRows = await this.ctx.model.query(` + SELECT wave_id, order_id, wave_index + FROM wms_order_wave_index + WHERE warehouse_id = :warehouseId + AND wave_id IN (:waveIds) + ORDER BY wave_id, order_id + `, { + replacements: { warehouseId, waveIds: normalizedWaveIds }, + type: this.ctx.model.QueryTypes.SELECT, + transaction, + }); + + const afterIndexMap = new Map(); // waveId -> Map(orderId -> wave_index) + for (const row of (Array.isArray(afterRows) ? afterRows : [])) { + const waveId = Number(row && row.wave_id || 0); + const orderId = Number(row && row.order_id || 0); + const waveIndex = Number(row && row.wave_index || 0); + if (!Number.isInteger(waveId) || waveId <= 0) continue; + if (!afterIndexMap.has(waveId)) afterIndexMap.set(waveId, new Map()); + if (Number.isInteger(orderId) && orderId > 0) { + afterIndexMap.get(waveId).set(orderId, Number.isInteger(waveIndex) ? waveIndex : 0); + } + } + + // 同步更新 wms_wave_batch.total_orders + const waveDetails = []; + for (const waveId of normalizedWaveIds) { + const remainingCount = Number(remainingCountMap.get(waveId) || 0); + const beforeCount = Number(beforeCountMap.get(waveId) || 0); + + if (remainingCount > 0) { + await this.ctx.model.query(` + UPDATE wms_wave_batch + SET total_orders = :remainingCount, + processed_orders = LEAST(processed_orders, :remainingCount), + update_time = NOW() + WHERE warehouse_id = :warehouseId + AND wave_id = :waveId + `, { + replacements: { warehouseId, waveId, remainingCount }, + transaction, + }); + } else { + await this.ctx.model.query(` + UPDATE wms_wave_batch + SET total_orders = 0, + processed_orders = 0, + wave_status = -1, + update_time = NOW() + WHERE warehouse_id = :warehouseId + AND wave_id = :waveId + `, { + replacements: { warehouseId, waveId }, + transaction, + }); + } + + // 对比每单重排前后的 wave_index,判断是否实际发生变化 + const beforeOrderMap = beforeIndexMap.get(waveId) || new Map(); + const afterOrderMap = afterIndexMap.get(waveId) || new Map(); + const allOrderIds = new Set([ ...beforeOrderMap.keys(), ...afterOrderMap.keys() ]); + let hasChanged = beforeCount !== remainingCount; + if (!hasChanged) { + for (const oid of allOrderIds) { + if (beforeOrderMap.get(oid) !== afterOrderMap.get(oid)) { + hasChanged = true; + break; + } + } + } + + waveDetails.push({ + wave_id: waveId, + before_index_count: beforeCount, + after_index_count: remainingCount, + reordered: hasChanged, + }); + } + + await transaction.commit(); + + const totalBefore = waveDetails.reduce((sum, w) => sum + w.before_index_count, 0); + const totalAfter = waveDetails.reduce((sum, w) => sum + w.after_index_count, 0); + + return this.success('ok', { + warehouse_id: warehouseId, + wave_count: normalizedWaveIds.length, + total_before_index_count: totalBefore, + total_after_index_count: totalAfter, + waves: waveDetails, + }); + } catch (error) { + await transaction.rollback(); + throw error; + } + } + /** * 批量移除异常订单任务提交接口。 * @@ -9203,6 +9345,15 @@ class WaveService extends OrderBaseService { }); } + // 关闭自动加团前,重建波次订单索引(wave_index 重新排序),确保序号连续 + const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + await this.replaceOrderWaveIndexByWaveIds({ + warehouseId, + waveIds: updatedWaveIds, + orderModel, + transaction, + }); + const updateSql = ` UPDATE wms_wave_batch SET wave_status = 1, @@ -9969,7 +10120,7 @@ class WaveService extends OrderBaseService { const orderModel = await this.getOrderModel('pendingOrder', warehouseId); const orderTableName = this.getModelTableSqlName(orderModel); - const structureExpr = alias => `COALESCE(NULLIF(TRIM(COALESCE(${alias}.items_hash, '')), ''), TRIM(COALESCE(${alias}.items, '')))`; + const structureExpr = alias => `${alias}.items_hash`; const expressExpr = alias => `COALESCE(NULLIF(TRIM(COALESCE(${alias}.sys_logistics_code, '')), ''), NULLIF(TRIM(COALESCE(${alias}.logistics_code, '')), ''), TRIM(COALESCE(${alias}.logistics_name, '')))`; const groupKeyExtra = requireSameExpress ? `, ${expressExpr('src')}` : ''; const joinKeyExtra = requireSameExpress ? ` AND same_structure.express_key = ${expressExpr('o')}` : ''; @@ -12110,6 +12261,13 @@ class WaveService extends OrderBaseService { transaction, }); + // 清理波次订单索引 + await this.deleteOrderWaveIndexByWaveIds({ + warehouseId, + waveIds, + transaction, + }); + if (Array.isArray(releasedWaveRows) && releasedWaveRows.length > 0) { hasReleasedWaves = true; } diff --git a/methods/system.json b/methods/system.json index 08870ca..78e4c99 100644 --- a/methods/system.json +++ b/methods/system.json @@ -3227,7 +3227,7 @@ }, { "method": "order.pendingOrder.allocateExpressCode", - "description": "批量分配待处理订单的快递号,接收订单对象数组,复用 express.createWaybillCodePipeline。", + "description": "批量分配待处理订单的首单快递号(异步接口)。调用后立即返回 task_id,后台异步执行运单创建;可通过 order.pendingOrder.allocateExpressCodeTaskProgress 查询进度。拆单场景请使用 order.pendingOrder.allocateSubOrderNumber。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -3240,11 +3240,11 @@ ], "params": [ { - "name": "orders", - "type": "array", + "name": "ids", + "type": "array", "required": true, "source": "body", - "description": "订单对象数组;每个对象应为待处理订单列表或详情中获取的原始订单对象。每个订单对象必须包含 order_id 与 business_key;sys_platform_code 与 logistics_code 为订单对象自带字段,前端无需额外拼装或从外部构造,直接原样回传订单对象即可。其余字段会原样透传给运单创建链路。business_key 说明:business_key 是运单创建的序号键数组(例如:新分配 1 个运单号时传 [1];订单拆单时可能传 [2,3]),该字段会在 createWaybillCodePipeline 的返回 data 中原样返回,便于前端关联订单与运单创建结果。" + "description": "订单 ID 数组,例如 [123456, 789012]。sys_platform_code、logistics_code 等字段由后端直接从数据库读取,前端无需传参。" } ], "response": [ @@ -3270,7 +3270,7 @@ "name": "data", "type": "object", "required": false, - "description": "createWaybillCodePipeline 返回的运单创建结果,包含 success/failed 列表与 summary 等字段" + "description": "异步受理结果。包含 task_id(任务 ID,用于查询进度)、status(submitted)、message、update_time 等字段。实际运单分配结果需通过 allocateExpressCodeTaskProgress 接口查询。" } ], "errors": [ From 02b3a5e813832f0fe53032d44fd9c0b1673a5198 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sun, 2 Aug 2026 00:38:34 +0800 Subject: [PATCH 151/550] =?UTF-8?q?fix(order):=20=E8=AE=A2=E5=8D=95?= =?UTF-8?q?=E5=90=8C=E6=AD=A5/=E8=BF=90=E5=8D=95/=E5=BA=93=E4=BD=8D?= =?UTF-8?q?=E5=88=86=E9=85=8D=E9=98=B2=E5=BE=A1=E6=80=A7=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - express: 运单查询补充 pay_no/from_key 字段;step 更新增加 status!=cancel 过滤 - order_async: 同步分发前过滤 sync_status=fin 的已完成订单;修复 Op.ne 引用缺失;强制 SELECT FOR UPDATE 重读;多处更新增加 status!=cancel 守卫 - order_storage_allocation: SN/快递分配失败回写增加 status!=cancel 守卫 - methods: allocateExpressCode 文档更新为异步接口说明 --- app/service/systems/delivery_order.js | 9 +--- app/service/systems/express.js | 9 +++- app/service/systems/express_platform.js | 2 +- app/service/systems/order_async.js | 42 +++++++++++++++++-- .../systems/order_storage_allocation.js | 15 ++++++- methods/changes/system.json | 8 ++-- 6 files changed, 65 insertions(+), 20 deletions(-) diff --git a/app/service/systems/delivery_order.js b/app/service/systems/delivery_order.js index 9cbc534..fb96894 100644 --- a/app/service/systems/delivery_order.js +++ b/app/service/systems/delivery_order.js @@ -1543,14 +1543,7 @@ class DeliveryOrderService extends Service { buildExpressAllocateRequest(context) { const order = context && context.order ? context.order : {}; return { - orders: [{ - order_id: Number(order.id || context.orderId || 0), - business_key: 1, - sys_platform_code: String(order.sys_platform_code || '').trim(), - logistics_code: String(order.logistics_code || '').trim(), - store_id: Number(order.store_id || context.storeId || 0), - warehouse_id: Number(order.warehouse_id || context.warehouseId || 0), - }], + ids: [ Number(order.id || context.orderId || 0) ], }; } diff --git a/app/service/systems/express.js b/app/service/systems/express.js index 63d6f81..e9cdebc 100644 --- a/app/service/systems/express.js +++ b/app/service/systems/express.js @@ -58,6 +58,8 @@ const WAYBILL_ORDER_DELIVERY_MIN_ATTRIBUTES = Object.freeze([ 'logistics_code', 'extend_props', 'buyer_nick', + 'pay_no', + 'from_key' ]); class ExpressService extends Service { @@ -2460,7 +2462,7 @@ class ExpressService extends Service { [Op.in]: [ 1, 2, 3, 4 ], }, }, - attributes: [ 'id', 'sys_platform_code', 'logistics_code', 'sys_platform_name', 'logistics_name', 'store_id' ], + attributes: [ 'id', 'sys_platform_code', 'logistics_code', 'sys_platform_name', 'logistics_name', 'store_id','pay_no','from_key' ], raw: true, }); @@ -2481,7 +2483,7 @@ class ExpressService extends Service { [Op.in]: [ 4 ], }, }, - attributes: [ 'id', 'sys_platform_code', 'logistics_code', 'sys_platform_name', 'logistics_name', 'store_id' ], + attributes: [ 'id', 'sys_platform_code', 'logistics_code', 'sys_platform_name', 'logistics_name', 'store_id','pay_no','from_key' ], raw: true, }); } @@ -3106,6 +3108,9 @@ class ExpressService extends Service { id: { [Op.in]: stepUpdatableIds, }, + status: { + [Op.ne]: 'cancel', + }, }, transaction, }); diff --git a/app/service/systems/express_platform.js b/app/service/systems/express_platform.js index 23861a1..d7b1ee3 100644 --- a/app/service/systems/express_platform.js +++ b/app/service/systems/express_platform.js @@ -706,7 +706,7 @@ class ExpressPlatformService extends MainService { let playload = { object_Id: `${order.warehouse_id}_${order.id}_${order_tmp.business_key}`, // 菠萝派平台要求订单唯一标识必须为字符串 orderno: `${order.warehouse_id}_${order.id}_${order_tmp.business_key}`, // 菠萝派平台要求订单号必须为字符串 - plattradeno: order.sys_platform_code === 'DY'? order.source_order_codes.split(",")[0] : order.source_order_codes || order.delivery_order_code || '', + plattradeno: listByWarehousePlatformCode.platform_code === 'DY' && order.from_key == 23060081? order.pay_no : order.source_order_codes || order.delivery_order_code || '', ismultiplepieces: order.package_count > 1 ? 1 : 0, logisticno: allocatedWaybillMap.get(`${Number(order.id) || 0}:${Number(order_tmp.business_key) || 0}`) || '', logistictype: order.logistics_code || '', diff --git a/app/service/systems/order_async.js b/app/service/systems/order_async.js index 3a4643f..19a6d20 100644 --- a/app/service/systems/order_async.js +++ b/app/service/systems/order_async.js @@ -402,6 +402,11 @@ async function syncManualOrdersInternal(service, groupedOrder = {}, context = {} const orderMap = new Map(); for (const orderRow of Array.isArray(orderRows) ? orderRows : []) { if (orderRow && Number(orderRow.id) > 0) { + // 分发前过滤:已同步完成的订单不再派发 + if (String(orderRow.sync_status || '').trim() === 'fin') { + service.ctx.logger.info(`[syncManualOrders] 订单已完成同步,跳过派发 orderId=${orderRow.id}`); + continue; + } orderMap.set(Number(orderRow.id), orderRow); } } @@ -413,6 +418,10 @@ async function syncManualOrdersInternal(service, groupedOrder = {}, context = {} for (let i = 0; i < orderIds.length; i += DISPATCH_BATCH_SIZE) { const batch = orderIds.slice(i, i + DISPATCH_BATCH_SIZE); const batchResults = await Promise.all(batch.map(orderId => { + const dispathedOrderRow = orderMap.get(orderId); + if (!dispathedOrderRow) { + return { order_id: orderId, status: 'skipped', message: '订单已完成同步,跳过' }; + } return processManualOrderInternal( service, orderModel, @@ -484,7 +493,7 @@ async function markPendingExceptionInternal(service, orderModel, orderId, wareho id: orderId, warehouse_id: warehouseId, status: { - [Op.ne]: 'cancel', + [service.app.Sequelize.Op.ne]: 'cancel', }, }, }); @@ -509,7 +518,8 @@ async function finalizeSuccessfulQimenSyncInternal(service, orderModel, orderIte await runTransactionWithLockRetryInternal(service, 'finalizeSuccessfulQimenSync', async transaction => { let resolvedOrderRow = orderRow; - if (!resolvedOrderRow && orderModel && typeof orderModel.findOne === 'function') { + // 最小修复:始终执行 SELECT ... FOR UPDATE,不再因 orderRow 已传入而跳过 + if (orderModel && typeof orderModel.findOne === 'function') { resolvedOrderRow = await orderModel.findOne({ where: { id: orderId, @@ -569,6 +579,9 @@ async function finalizeSuccessfulQimenSyncInternal(service, orderModel, orderIte where: { id: orderId, warehouse_id: warehouseId, + status: { + [service.app.Sequelize.Op.ne]: 'cancel', + }, }, transaction, }); @@ -642,6 +655,9 @@ async function processLocalChannelOrderInternal(service, createChannel, orderMod where: { id: orderId, warehouse_id: warehouseId, + status: { + [service.app.Sequelize.Op.ne]: 'cancel', + }, }, transaction, }); @@ -815,6 +831,11 @@ async function finalizeLocalChannelOrdersInternal(service, createChannel, groupe const orderMap = new Map(); for (const orderRow of Array.isArray(orderRows) ? orderRows : []) { if (orderRow && Number(orderRow.id) > 0) { + // 分发前过滤:已同步完成的订单不再派发 + if (String(orderRow.sync_status || '').trim() === 'fin') { + service.ctx.logger.info(`[syncApiOrders] 订单已完成同步,跳过派发 orderId=${orderRow.id}`); + continue; + } orderMap.set(Number(orderRow.id), orderRow); } } @@ -826,6 +847,10 @@ async function finalizeLocalChannelOrdersInternal(service, createChannel, groupe for (let i = 0; i < orderIds.length; i += DISPATCH_BATCH_SIZE) { const batch = orderIds.slice(i, i + DISPATCH_BATCH_SIZE); const batchResults = await Promise.all(batch.map(orderId => { + const dispathedOrderRow = orderMap.get(orderId); + if (!dispathedOrderRow) { + return { order_id: orderId, status: 'skipped', message: '订单已完成同步,跳过' }; + } return processLocalChannelOrderInternal( service, createChannel, @@ -1156,6 +1181,11 @@ async function syncQmOrdersInternal(service, groupedOrder = {}, context = {}) { const orderMap = new Map(); for (const orderRow of Array.isArray(orderRows) ? orderRows : []) { if (orderRow && Number(orderRow.id) > 0) { + // 分发前过滤:已同步完成的订单不再派发,避免重复同步覆盖 error 等异常状态 + if (String(orderRow.sync_status || '').trim() === 'fin') { + service.ctx.logger.info(`[syncQmOrders] 订单已完成同步,跳过派发 orderId=${orderRow.id}`); + continue; + } orderMap.set(Number(orderRow.id), orderRow); } } @@ -1182,6 +1212,12 @@ async function syncQmOrdersInternal(service, groupedOrder = {}, context = {}) { for (let i = 0; i < orderIds.length; i += DISPATCH_BATCH_SIZE) { const batch = orderIds.slice(i, i + DISPATCH_BATCH_SIZE); const batchResults = await Promise.all(batch.map(orderId => { + // 分发时二次检查:orderRow 不在 map 中则跳过 + const dispathedOrderRow = orderMap.get(orderId); + if (!dispathedOrderRow) { + service.ctx.logger.info(`[syncQmOrders] 订单已过滤,跳过 orderId=${orderId}`); + return { order_id: orderId, status: 'skipped', message: '订单已完成同步,跳过' }; + } return processQmOrderInternal( service, orderModel, @@ -1189,7 +1225,7 @@ async function syncQmOrdersInternal(service, groupedOrder = {}, context = {}) { qimenClient, orderId, warehouseId, - orderMap.get(orderId), + dispathedOrderRow, itemsByOrderId.get(orderId) || [], context, waybillCodeMap.get(orderId) diff --git a/app/service/systems/order_storage_allocation.js b/app/service/systems/order_storage_allocation.js index b5e8e2e..b3baf4e 100644 --- a/app/service/systems/order_storage_allocation.js +++ b/app/service/systems/order_storage_allocation.js @@ -1328,6 +1328,9 @@ class OrderStorageAllocationService extends MainService { where: { id: orderId, warehouse_id: warehouseId, + status: { + [ctx.app.Sequelize.Op.ne]: 'cancel', + }, }, transaction, }); @@ -1831,7 +1834,11 @@ class OrderStorageAllocationService extends MainService { order_flag: snBatchForbiddenReason, updated_at: now, }, { - where: { id: { [ctx.app.Sequelize.Op.in]: snFailIds }, warehouse_id: warehouseId }, + where: { + id: { [ctx.app.Sequelize.Op.in]: snFailIds }, + warehouse_id: warehouseId, + status: { [ctx.app.Sequelize.Op.ne]: 'cancel' }, + }, transaction, }); } @@ -1845,7 +1852,11 @@ class OrderStorageAllocationService extends MainService { order_flag: fastFailReason, updated_at: now, }, { - where: { id: { [ctx.app.Sequelize.Op.in]: expressFailIds }, warehouse_id: warehouseId }, + where: { + id: { [ctx.app.Sequelize.Op.in]: expressFailIds }, + warehouse_id: warehouseId, + status: { [ctx.app.Sequelize.Op.ne]: 'cancel' }, + }, transaction, }); } diff --git a/methods/changes/system.json b/methods/changes/system.json index 49f9658..495587d 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1907,14 +1907,14 @@ { "version": "2026.04.18-system-02", "date": "2026-04-18", - "summary": "新增 order.pendingOrder.allocateExpressCode:待处理订单模块的批量分配快递号入口,复用 express.createWaybillCodePipeline。", + "summary": "新增 order.pendingOrder.allocateExpressCode:待处理订单模块的批量分配首单快递号(异步接口),复用 express.createWaybillCodePipeline。", "methods": [ "order.pendingOrder.allocateExpressCode" ], "notes": [ - "该接口直接接收订单对象数组入参;订单对象应为来自待处理订单列表或详情的原始订单对象。每个订单对象必须包含 order_id 与 business_key;sys_platform_code、logistics_code 为订单对象自带字段,前端无需额外拼装或单独构造,直接原样回传订单对象即可。", - "实际的运单创建、归一化与跳过逻辑由 express.createWaybillCodePipeline 处理。", - "接口返回值与现有分配链路一致,已用统一 success 包装返回。" + "异步接口:调用后立即返回 task_id,后台执行运单创建,通过 allocateExpressCodeTaskProgress 查询进度。", + "入参为 ids(订单 ID 数组),sys_platform_code/logistics_code 等由后端从数据库读取。", + "拆单场景请使用 order.pendingOrder.allocateSubOrderNumber。" ], "type": "added" }, From 02596feb3d768b4dfe85a1840076e616bb07ef36 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sun, 2 Aug 2026 00:52:11 +0800 Subject: [PATCH 152/550] =?UTF-8?q?fix(wave):=20=E4=BF=AE=E5=A4=8D?= =?UTF-8?q?=E5=B9=B6=E5=8F=91=E5=8F=96=E6=B6=88=E8=AE=A2=E5=8D=95=E6=97=B6?= =?UTF-8?q?=E4=BA=8B=E5=8A=A1=E6=AD=BB=E9=94=81=E5=AF=BC=E8=87=B4=20rollba?= =?UTF-8?q?ck=20=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit replaceOrderWaveIndexByWaveIds 内部 DELETE WHERE wave_id IN(...) 在并发取消同一波次时可能死锁,MySQL 自动回滚事务后,内层 try-catch 吞掉错误继续使用已死事务导致报错。去掉内层 try-catch,让错误传播到外层统一处理 rollback。 --- app/service/openapiMethods/order.js | 58 ++++++++++----------- app/service/qimenMethods/order.js | 78 ++++++++++++++--------------- 2 files changed, 64 insertions(+), 72 deletions(-) diff --git a/app/service/openapiMethods/order.js b/app/service/openapiMethods/order.js index 85cc3f6..6c6764b 100644 --- a/app/service/openapiMethods/order.js +++ b/app/service/openapiMethods/order.js @@ -85,42 +85,38 @@ class OpenapiOrderService extends MainService { // 波次清理:删除波次索引、重建波次索引、更新波次统计 if (existingWaveId > 0) { - try { - await ctx.service.systemMethods.order.wave.deleteOrderWaveIndexByOrderIds({ - warehouseId, - orderIds: [ existingOrder.id ], + await ctx.service.systemMethods.order.wave.deleteOrderWaveIndexByOrderIds({ + warehouseId, + orderIds: [ existingOrder.id ], + transaction, + }); + + await ctx.service.systemMethods.order.wave.replaceOrderWaveIndexByWaveIds({ + warehouseId, + waveIds: [ existingWaveId ], + orderModel: DeliveryModel, + transaction, + }); + + const WaveBatch = ctx.model.WaveBatch; + if (WaveBatch) { + const wave = await WaveBatch.findOne({ + where: { wave_id: existingWaveId, warehouse_id: warehouseId }, + attributes: [ 'wave_id', 'total_orders', 'wave_status' ], + raw: true, transaction, }); - await ctx.service.systemMethods.order.wave.replaceOrderWaveIndexByWaveIds({ - warehouseId, - waveIds: [ existingWaveId ], - orderModel: DeliveryModel, - transaction, - }); - - const WaveBatch = ctx.model.WaveBatch; - if (WaveBatch) { - const wave = await WaveBatch.findOne({ - where: { wave_id: existingWaveId, warehouse_id: warehouseId }, - attributes: [ 'wave_id', 'total_orders', 'wave_status' ], - raw: true, - transaction, - }); - - if (wave) { - 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: new Date() }, - { where: { wave_id: existingWaveId, warehouse_id: warehouseId }, transaction } - ); - } + if (wave) { + 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: new Date() }, + { where: { wave_id: existingWaveId, warehouse_id: warehouseId }, transaction } + ); } } - } catch (waveErr) { - ctx.logger.warn('[OpenapiOrderCancel] 清理波次关联失败,不影响订单取消', waveErr); } } diff --git a/app/service/qimenMethods/order.js b/app/service/qimenMethods/order.js index 4110b00..a949a49 100644 --- a/app/service/qimenMethods/order.js +++ b/app/service/qimenMethods/order.js @@ -238,56 +238,52 @@ class orderServer extends MainService { await existingOrder.update(updateValues, { transaction }); - // 波次清理:删除波次索引、更新波次统计 + // 波次清理:删除波次索引、重建波次索引、更新波次统计 if (existingWaveId > 0) { - try { - await ctx.service.systemMethods.order.wave.deleteOrderWaveIndexByOrderIds({ - warehouseId: info.warehouseId, - orderIds: [ existingOrder.id ], + await ctx.service.systemMethods.order.wave.deleteOrderWaveIndexByOrderIds({ + warehouseId: info.warehouseId, + orderIds: [ existingOrder.id ], + transaction, + }); + + // 重建受影响波次的订单索引(wave_index 重新排序) + await ctx.service.systemMethods.order.wave.replaceOrderWaveIndexByWaveIds({ + warehouseId: info.warehouseId, + waveIds: [ existingWaveId ], + orderModel: DeliveryModel, + transaction, + }); + + const { Op } = this.app.Sequelize; + const WaveBatch = ctx.model.WaveBatch; + if (WaveBatch) { + await WaveBatch.decrement('total_orders', { + by: 1, + where: { + wave_id: existingWaveId, + warehouse_id: info.warehouseId, + total_orders: { [Op.gt]: 0 }, + }, transaction, }); - // 重建受影响波次的订单索引(wave_index 重新排序) - await ctx.service.systemMethods.order.wave.replaceOrderWaveIndexByWaveIds({ - warehouseId: info.warehouseId, - waveIds: [ existingWaveId ], - orderModel: DeliveryModel, + const wave = await WaveBatch.findOne({ + where: { wave_id: existingWaveId, warehouse_id: info.warehouseId }, + attributes: [ 'wave_id', 'total_orders', 'wave_status' ], + raw: true, transaction, }); - const { Op } = this.app.Sequelize; - const WaveBatch = ctx.model.WaveBatch; - if (WaveBatch) { - await WaveBatch.decrement('total_orders', { - by: 1, - where: { - wave_id: existingWaveId, - warehouse_id: info.warehouseId, - total_orders: { [Op.gt]: 0 }, - }, - transaction, - }); - - const wave = await WaveBatch.findOne({ - where: { wave_id: existingWaveId, warehouse_id: info.warehouseId }, - attributes: [ 'wave_id', 'total_orders', 'wave_status' ], - raw: true, - transaction, - }); - - if (wave) { - 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: new Date() }, - { where: { wave_id: existingWaveId, warehouse_id: info.warehouseId }, transaction } - ); - } + if (wave) { + 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: new Date() }, + { where: { wave_id: existingWaveId, warehouse_id: info.warehouseId }, transaction } + ); } } - } catch (waveErr) { - ctx.logger.warn('[QimenOrderCancel] 清理波次关联失败,不影响订单取消', waveErr); } } From 59bd1128931bd690e13e66d85675e465449fbe8d Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sun, 2 Aug 2026 17:15:12 +0800 Subject: [PATCH 153/550] =?UTF-8?q?refactor:=20=E7=A7=BB=E9=99=A4=20order.?= =?UTF-8?q?print.getWavePrintData=20=E6=8E=A5=E5=8F=A3=EF=BC=88=E5=B7=B2?= =?UTF-8?q?=E8=A2=AB=20getWavePlatformPrintData=20=E6=9B=BF=E4=BB=A3?= =?UTF-8?q?=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/systemMethods/order/print.js | 43 +--- app/service/systems/order_print.js | 176 ---------------- methods/changes/system.json | 12 -- methods/system.json | 245 ----------------------- 4 files changed, 3 insertions(+), 473 deletions(-) diff --git a/app/service/systemMethods/order/print.js b/app/service/systemMethods/order/print.js index 952ff73..4c34b93 100644 --- a/app/service/systemMethods/order/print.js +++ b/app/service/systemMethods/order/print.js @@ -11,49 +11,12 @@ class OrderPrintService extends OrderBaseService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'getWavePrintData,getWavePlatformPrintData,unlockWavePlatformPrintDataByGroup,getOrderPrintData,getPrintDataByWaybillCodes'; - const _noNeedLog = 'getWavePrintData,unlockWavePlatformPrintDataByGroup,getOrderPrintData,getPrintDataByWaybillCodes'; - const _noNeedAuth = 'getWavePrintData,getWavePlatformPrintData,unlockWavePlatformPrintDataByGroup,getOrderPrintData,getPrintDataByWaybillCodes'; + const _noNeedRight = 'getWavePlatformPrintData,unlockWavePlatformPrintDataByGroup,getOrderPrintData,getPrintDataByWaybillCodes'; + const _noNeedLog = 'unlockWavePlatformPrintDataByGroup,getOrderPrintData,getPrintDataByWaybillCodes'; + const _noNeedAuth = 'getWavePlatformPrintData,unlockWavePlatformPrintDataByGroup,getOrderPrintData,getPrintDataByWaybillCodes'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } - /** - * 获取波次打印数据。 - * - * method 层仅负责参数解构与边界校验,具体业务查询由 systems 层实现。 - * 返回结果中的 ext 会同时包含 missing_wave_ids 与 filtered_wave_ids。 - * - * @param {Object} data 请求体。 - * @param {Array} data.wave_ids 波次ID数组。 - * @param {number|string} data.warehouse_id 仓库ID。 - * @return {Promise} 统一 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, - }); - } - /** * 获取波次平台打印中间态数据。 * diff --git a/app/service/systems/order_print.js b/app/service/systems/order_print.js index 86d833a..4ae1b69 100644 --- a/app/service/systems/order_print.js +++ b/app/service/systems/order_print.js @@ -456,50 +456,6 @@ class OrderPrintSystemService extends OrderBaseService { return {}; } - /** - * 获取波次打印数据。 - * - * @param {Object} params 请求参数。 - * @param {Array} params.waveIds 波次ID数组。 - * @param {number|string} params.warehouseId 仓库ID。 - * @return {Promise} 通用打印数据结构。 - */ - 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, - }); - } - /** * 获取波次平台打印数据中间态。 * @@ -3324,138 +3280,6 @@ ${waveFilterSql} }; } - /** - * 生成空结果结构。 - * - * @param {Array} 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} payload.waveRows 波次列表。 - * @param {Array} payload.orderRows 订单列表。 - * @param {Array} payload.hitWaveIds 命中的波次ID数组。 - * @param {Array} payload.missingWaveIds 未命中的波次ID数组。 - * @param {Array} 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; diff --git a/methods/changes/system.json b/methods/changes/system.json index 495587d..e2f76a4 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -970,18 +970,6 @@ ], "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", diff --git a/methods/system.json b/methods/system.json index 78e4c99..62dc192 100644 --- a/methods/system.json +++ b/methods/system.json @@ -11055,251 +11055,6 @@ "groupName": "打印模块", "module": "order.print", "list": [ - { - "method": "order.print.getWavePrintData", - "description": "按波次 IDs 获取订单打印数据,自动过滤快递未完全分配的波次,返回通过过滤的波次订单明细,按波次号分组", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "warehouse_id", - "type": "number", - "required": true, - "source": "body", - "description": "仓库ID" - }, - { - "name": "wave_ids", - "type": "array", - "required": true, - "source": "body", - "description": "波次ID列表(支持数字或字符串,内部自动去重与归一化)" - } - ], - "response": [ - { - "name": "summary", - "type": "object", - "description": "汇总信息", - "children": [ - { - "name": "total_waves", - "type": "number", - "description": "通过过滤的波次总数" - }, - { - "name": "total_orders", - "type": "number", - "description": "通过过滤的波次下订单总数" - } - ] - }, - { - "name": "wave_list", - "type": "array", - "description": "波次列表(按 wave_no 排序)", - "children": [ - { - "name": "wave_id", - "type": "number", - "description": "波次ID" - }, - { - "name": "wave_no", - "type": "string", - "description": "波次号" - }, - { - "name": "order_count", - "type": "number", - "description": "该波次订单数" - }, - { - "name": "orders", - "type": "array", - "description": "订单明细列表(含 order_id、order_no、收件信息等字段)", - "children": [ - { - "name": "order_id", - "type": "number", - "description": "订单ID" - }, - { - "name": "order_no", - "type": "string", - "description": "订单号(delivery_order_code 或 source_order_codes)" - }, - { - "name": "receiver", - "type": "object", - "description": "收件信息", - "children": [ - { - "name": "name", - "type": "string", - "description": "收件人姓名" - }, - { - "name": "mobile", - "type": "string", - "description": "手机号" - }, - { - "name": "tel", - "type": "string", - "description": "电话" - }, - { - "name": "province", - "type": "string", - "description": "省" - }, - { - "name": "city", - "type": "string", - "description": "市" - }, - { - "name": "area", - "type": "string", - "description": "区/县" - }, - { - "name": "town", - "type": "string", - "description": "镇/街道" - }, - { - "name": "detail_address", - "type": "string", - "description": "详细地址" - } - ] - }, - { - "name": "channel", - "type": "object", - "description": "渠道信息", - "children": [ - { - "name": "sys_platform_code", - "type": "string", - "description": "平台编码" - }, - { - "name": "sys_platform_name", - "type": "string", - "description": "平台名称" - }, - { - "name": "logistics_name", - "type": "string", - "description": "快递名称" - } - ] - }, - { - "name": "status", - "type": "object", - "description": "订单状态简要", - "children": [ - { - "name": "order_status", - "type": "string", - "description": "订单状态" - }, - { - "name": "outbound_status", - "type": "string", - "description": "出库状态" - }, - { - "name": "print_status", - "type": "string", - "description": "打印状态" - } - ] - }, - { - "name": "metrics", - "type": "object", - "description": "数量度量", - "children": [ - { - "name": "items_count", - "type": "number", - "description": "商品种类数" - }, - { - "name": "items_total", - "type": "number", - "description": "商品总件数" - }, - { - "name": "items_weight", - "type": "number", - "description": "重量(单位 g)" - } - ] - }, - { - "name": "times", - "type": "object", - "description": "时间字段", - "children": [ - { - "name": "create_at", - "type": "string", - "description": "创建时间" - }, - { - "name": "pay_time", - "type": "string", - "description": "支付时间" - } - ] - } - ] - } - ] - }, - { - "name": "ext", - "type": "object", - "description": "扩展字段", - "children": [ - { - "name": "missing_wave_ids", - "type": "array", - "description": "传入但不存在的 wave_id 列表" - }, - { - "name": "filtered_wave_ids", - "type": "array", - "description": "被过滤掉的波次(快递未完全分配),每项含 wave_id、wave_no、reason" - } - ] - } - ], - "errors": [ - { - "code": "400", - "description": "warehouse_id 或 wave_ids 缺失或格式错误" - }, - { - "code": "500", - "description": "查询失败" - } - ] - }, { "method": "order.print.getWavePlatformPrintData", "description": "按波次 IDs 获取平台打印中间态数据,自动过滤快递未完全分配的波次,返回 waveGroups(波次 -> 平台 -> 订单)结构", From de9eb2b657f50ed8c3ea21bdf0c5aeacd2a35afd Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sun, 2 Aug 2026 22:37:48 +0800 Subject: [PATCH 154/550] =?UTF-8?q?fix:=20wms=5Forder=5Fwave=5Findex=20?= =?UTF-8?q?=E5=86=99=E5=85=A5=E6=97=B6=E6=8C=89=E5=B9=B3=E5=8F=B0+?= =?UTF-8?q?=E5=BF=AB=E9=80=92=E6=8E=92=E5=BA=8F=20wave=5Findex?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit replaceOrderWaveIndexByWaveIds 中 wave_index 原按 id 顺序分配, 导致同一波次内不同平台订单交叉排列。 修复为按 sys_platform_code → sys_logistics_code → id 三级排序, 确保同平台同快递订单获得连续的 wave_index。 --- app/service/systemMethods/order/wave.js | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/app/service/systemMethods/order/wave.js b/app/service/systemMethods/order/wave.js index 6456763..a655200 100644 --- a/app/service/systemMethods/order/wave.js +++ b/app/service/systemMethods/order/wave.js @@ -11519,14 +11519,13 @@ class WaveService extends OrderBaseService { } // 通过绑定表判断车是否被其他活跃任务占用(不依赖 wms_pick_cart.current_task_id) + // 仅以 wms_pick_task_cart_binding.is_active = 1 为准,不关联任务状态做二次过滤 const bindingRows = await this.ctx.model.query(` SELECT b.task_id FROM wms_pick_task_cart_binding b - INNER JOIN wms_wave_pick_task t ON t.id = b.task_id WHERE b.cart_id = :cartId AND b.warehouse_id = :warehouseId AND b.is_active = 1 - AND t.status IN (0, 1) LIMIT 1 FOR UPDATE `, { @@ -12808,7 +12807,7 @@ class WaveService extends OrderBaseService { } const orderRows = await currentOrderModel.findAll({ - attributes: [ 'id', 'wave_id', 'sys_platform_code', 'source_platform_code' ], + attributes: [ 'id', 'wave_id', 'sys_platform_code', 'source_platform_code', 'sys_logistics_code' ], where: { wave_id: { [Op.in]: normalizedWaveIds, @@ -12836,6 +12835,7 @@ class WaveService extends OrderBaseService { id: orderId, sys_platform_code: String(row && row.sys_platform_code || ''), source_platform_code: String(row && row.source_platform_code || ''), + sys_logistics_code: String(row && row.sys_logistics_code || ''), }); } @@ -12863,7 +12863,21 @@ class WaveService extends OrderBaseService { let rowIndex = 0; for (const waveId of normalizedWaveIds) { - const orderRowsByWave = waveOrderRowsMap.get(waveId) || []; + const rawOrderRows = waveOrderRowsMap.get(waveId) || []; + // 按平台+快递排序:同平台、同快递订单聚合在一起,确保 wave_index 连续分配 + const orderRowsByWave = [ ...rawOrderRows ].sort((a, b) => { + const platformA = String( + (a && a.sys_platform_code) || (a && a.source_platform_code) || '' + ).trim().toLowerCase(); + const platformB = String( + (b && b.sys_platform_code) || (b && b.source_platform_code) || '' + ).trim().toLowerCase(); + if (platformA !== platformB) return platformA.localeCompare(platformB); + const logisticsA = String((a && a.sys_logistics_code) || '').trim().toLowerCase(); + const logisticsB = String((b && b.sys_logistics_code) || '').trim().toLowerCase(); + if (logisticsA !== logisticsB) return logisticsA.localeCompare(logisticsB); + return (Number(a && a.id) || 0) - (Number(b && b.id) || 0); + }); const platformsIndexMap = new Map(); const platformSequenceMap = new Map(); for (const orderRow of orderRowsByWave) { From 0b77a1c63eb613cb52629c5ebbba70955761cd79 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sun, 2 Aug 2026 22:40:03 +0800 Subject: [PATCH 155/550] =?UTF-8?q?fix(pick):=20wavePickTaskBindCart=20?= =?UTF-8?q?=E9=98=B2=E9=87=8D=E6=A3=80=E6=9F=A5=E4=B8=8D=E5=86=8D=E6=8C=89?= =?UTF-8?q?=E4=BB=BB=E5=8A=A1=E7=8A=B6=E6=80=81=E6=94=BE=E8=BF=87=E2=80=94?= =?UTF-8?q?=E2=80=94=E4=BB=85=E4=BB=A5=20is=5Factive=3D1=20=E4=B8=BA?= =?UTF-8?q?=E5=87=86=EF=BC=8C=E9=98=BB=E6=AD=A2=E4=B8=80=E8=BD=A6=E5=A4=9A?= =?UTF-8?q?=E7=BB=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/systems/pick.js | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/app/service/systems/pick.js b/app/service/systems/pick.js index 832f995..3937e23 100644 --- a/app/service/systems/pick.js +++ b/app/service/systems/pick.js @@ -2418,8 +2418,7 @@ class PickSystemService extends Service { SELECT b.id, b.task_id, - t.task_no, - t.status AS task_status + t.task_no FROM wms_pick_task_cart_binding b INNER JOIN wms_wave_pick_task t ON t.id = b.task_id @@ -2442,7 +2441,6 @@ class PickSystemService extends Service { : null; if (cartActiveBinding) { const boundTaskId = Number(cartActiveBinding.task_id || 0); - const boundTaskStatus = Number(cartActiveBinding.task_status || 0); if (boundTaskId === taskId) { throw this.createBusinessError('该任务已绑定此拣货车,无需重复绑定', 409, { task_id: taskId, @@ -2450,14 +2448,13 @@ class PickSystemService extends Service { cart_code: targetCartCode, }); } - if ([ 0, 1 ].includes(boundTaskStatus)) { - throw this.createBusinessError('该拣货车已绑定其他活动任务,请先解绑后再重新绑定', 409, { - task_id: boundTaskId, - task_no: String(cartActiveBinding.task_no || '').trim() || null, - cart_id: targetCartId, - cart_code: targetCartCode, - }); - } + // 车已有其他活跃绑定,无论旧任务状态如何均应阻止 + throw this.createBusinessError('该拣货车已绑定其他任务,请先解绑后再重新绑定', 409, { + task_id: boundTaskId, + task_no: String(cartActiveBinding.task_no || '').trim() || null, + cart_id: targetCartId, + cart_code: targetCartCode, + }); } await ctx.model.query(` From da4208707d0b0f1079c3b577b5c93745e6abe06b Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sun, 2 Aug 2026 22:40:58 +0800 Subject: [PATCH 156/550] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=E8=87=AA?= =?UTF-8?q?=E5=8A=A8=E5=88=86=E9=85=8D=E5=BF=AB=E9=80=92=E6=97=B6=20wareho?= =?UTF-8?q?use=5Fid=20=E4=B8=8A=E4=B8=8B=E6=96=87=E4=B8=A2=E5=A4=B1?= =?UTF-8?q?=E5=AF=BC=E8=87=B4=20FK=20=E7=BA=A6=E6=9D=9F=E5=A4=B1=E8=B4=A5?= =?UTF-8?q?=E5=8F=8A=E5=B9=B3=E5=8F=B0=E8=A7=A3=E6=9E=90=E5=BC=82=E5=B8=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - express.js: createWaybillCode 优先使用传入的 warehouse_id,修复 setImmediate 后 ctx.user 丢失导致 wms_order_express.warehouse_id 外键约束失败 - delivery_order.js: asyncProcessOrderCreated 中平台/快递解析逻辑修正 - recheckOrder.js: 复核单快递分配状态判断优化 - express_platform.js: 快递平台自动同步回传链路修正 - order_async.js: 奇门异步下单上下文增强 - polo_api_client.js: PolyAPI 客户端微调 --- app/lib/polo_api_client.js | 2 + .../systemMethods/order/recheckOrder.js | 194 ++++++++++++++---- app/service/systems/delivery_order.js | 3 +- app/service/systems/express.js | 68 ++++-- app/service/systems/express_platform.js | 96 +++++++-- app/service/systems/order_async.js | 18 +- printer_data_template/pdd.json | 1 - 7 files changed, 295 insertions(+), 87 deletions(-) diff --git a/app/lib/polo_api_client.js b/app/lib/polo_api_client.js index 9379403..e61d05d 100644 --- a/app/lib/polo_api_client.js +++ b/app/lib/polo_api_client.js @@ -60,6 +60,7 @@ class PoloApiClient { }, content: formBody, }); + console.log('formBody', formBody); let result; if (Buffer.isBuffer(response.data)) { @@ -71,6 +72,7 @@ class PoloApiClient { } else { result = response.data; } + await this.ctx.app.setCacheAsync('PoloApiresult', JSON.stringify(result), 3600); return result; } diff --git a/app/service/systemMethods/order/recheckOrder.js b/app/service/systemMethods/order/recheckOrder.js index 0fd95fd..1df67c6 100644 --- a/app/service/systemMethods/order/recheckOrder.js +++ b/app/service/systemMethods/order/recheckOrder.js @@ -2095,44 +2095,36 @@ class RecheckOrderService extends OrderBaseService { } ); - const taskId = Number( + let resolvedTaskId = Number( (Array.isArray(taskRows) && taskRows.length > 0 ? taskRows[0]?.task_id : 0) ); - if (taskId <= 0) { + // 团购模式(pick_mode=1/5)回退:wms_wave_pick_task_order 无记录时, + // 通过订单所属波次查找关联的拣货任务 + if (resolvedTaskId <= 0) { + resolvedTaskId = await this._resolveTaskIdByWaveFallback(orderId, warehouseId); + } + + if (resolvedTaskId <= 0) { return; } // 检查该任务下是否所有订单都已复核完成 - const unreviewedRows = await ctx.model.query( - `SELECT COUNT(*) AS cnt - FROM wms_wave_pick_task_order - WHERE task_id = :taskId - AND warehouse_id = :warehouseId - AND review_status != 1`, - { - replacements: { taskId, warehouseId }, - type: ctx.model.QueryTypes.SELECT, - } - ); + const allReviewed = await this._checkTaskOrdersAllReviewed(resolvedTaskId, warehouseId); - const unreviewedCount = Number( - (Array.isArray(unreviewedRows) && unreviewedRows.length > 0 ? unreviewedRows[0]?.cnt : 0) - ); - - if (unreviewedCount > 0) { + if (!allReviewed) { return; } // 任务下所有订单均已复核完成,更新任务状态为复核通过,并解绑车任务(失败不影响主流程) try { - await this.unbindCartForTask(taskId, warehouseId, operatorUserId); + await this.unbindCartForTask(resolvedTaskId, warehouseId, operatorUserId); ctx.logger.info( - `[confirmRecheck] 车任务解绑成功, taskId=${taskId}, orderId=${orderId}, operatorUserId=${operatorUserId}` + `[confirmRecheck] 车任务解绑成功, taskId=${resolvedTaskId}, orderId=${orderId}, operatorUserId=${operatorUserId}` ); } catch (unbindError) { ctx.logger.warn( - `[confirmRecheck] 解绑车任务失败(复核已成功), taskId=${taskId}, orderId=${orderId}, error=${unbindError.message}` + `[confirmRecheck] 解绑车任务失败(复核已成功), taskId=${resolvedTaskId}, orderId=${orderId}, error=${unbindError.message}` ); } @@ -2155,12 +2147,122 @@ class RecheckOrderService extends OrderBaseService { WHERE id = :taskId AND warehouse_id = :warehouseId`, { - replacements: { taskId, warehouseId, operatorUserId, operatorName, now }, + replacements: { taskId: resolvedTaskId, warehouseId, operatorUserId, operatorName, now }, type: ctx.model.QueryTypes.UPDATE, } ); } + /** + * 团购模式(pick_mode=1/5)回退:通过订单的波次 ID 查找关联的拣货任务 ID。 + * wms_wave_pick_task_order 在团购模式下无记录,需要绕道 wave 关联表。 + * + * @param {number} orderId 订单ID。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 任务ID,未找到返回 0。 + */ + async _resolveTaskIdByWaveFallback(orderId, warehouseId) { + const { ctx } = this; + + // 查订单所属 wave_id + const orderModel = await this.getOrderModelByTableType('current', warehouseId); + const order = await orderModel.findOne({ + where: { id: orderId, warehouse_id: warehouseId }, + attributes: [ 'id', 'wave_id' ], + raw: true, + }); + const orderWaveId = Number(order?.wave_id || 0); + if (orderWaveId <= 0) { + return 0; + } + + // 通过 wave_id 查拣货任务(仅限团购模式 pick_mode=1/5) + const taskWaveRows = await ctx.model.query( + `SELECT DISTINCT t.id AS task_id, t.pick_mode + FROM wms_wave_pick_task_wave tw + INNER JOIN wms_wave_pick_task t + ON t.id = tw.task_id AND t.warehouse_id = :warehouseId + WHERE tw.wave_id = :waveId + AND tw.warehouse_id = :warehouseId + AND t.pick_mode IN (1, 5) + LIMIT 1`, + { + replacements: { waveId: orderWaveId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + const fallbackTaskId = Number( + (Array.isArray(taskWaveRows) && taskWaveRows.length > 0 ? taskWaveRows[0]?.task_id : 0) + ); + + if (fallbackTaskId <= 0) { + return 0; + } + + // 检查波次下所有订单是否均已复核完成(团购模式以订单表 recheck_status 为准) + const unreviewedInWave = await orderModel.count({ + where: { + wave_id: orderWaveId, + warehouse_id: warehouseId, + recheck_status: { [ctx.app.Sequelize.Op.ne]: 'fin' }, + }, + }); + + return unreviewedInWave === 0 ? fallbackTaskId : 0; + } + + /** + * 检查拣货任务下是否所有订单均已复核完成。 + * - 散单模式:检查 wms_wave_pick_task_order.review_status + * - 团购模式:已由 _resolveTaskIdByWaveFallback 预先校验,此处直接返回 true + * + * @param {number} taskId 拣货任务ID。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 全部已复核返回 true。 + */ + async _checkTaskOrdersAllReviewed(taskId, warehouseId) { + const { ctx } = this; + + // 先确认 wms_wave_pick_task_order 中是否有记录 + const totalRows = await ctx.model.query( + `SELECT COUNT(*) AS cnt + FROM wms_wave_pick_task_order + WHERE task_id = :taskId + AND warehouse_id = :warehouseId`, + { + replacements: { taskId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + const totalCount = Number( + (Array.isArray(totalRows) && totalRows.length > 0 ? totalRows[0]?.cnt : 0) + ); + + if (totalCount > 0) { + // 散单模式:检查是否有未复核的订单 + const unreviewedRows = await ctx.model.query( + `SELECT COUNT(*) AS cnt + FROM wms_wave_pick_task_order + WHERE task_id = :taskId + AND warehouse_id = :warehouseId + AND review_status != 1`, + { + replacements: { taskId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + const unreviewedCount = Number( + (Array.isArray(unreviewedRows) && unreviewedRows.length > 0 ? unreviewedRows[0]?.cnt : 0) + ); + return unreviewedCount === 0; + } + + // 团购模式(wms_wave_pick_task_order 无记录): + // 已在 _resolveTaskIdByWaveFallback 中通过订单表的 recheck_status 校验通过 + return true; + } + /** * 批量更新波次拣货任务订单的复核状态,并按任务维度检查是否需要解绑车任务。 * 与单订单版本不同,本方法一次性更新所有相关任务订单的 review_status, @@ -2220,10 +2322,20 @@ class RecheckOrderService extends OrderBaseService { } ); - const taskIds = (Array.isArray(taskRows) ? taskRows : []) + let taskIds = (Array.isArray(taskRows) ? taskRows : []) .map(r => Number(r.task_id || 0)) .filter(id => id > 0); + // 团购模式(pick_mode=1/5)回退:wms_wave_pick_task_order 无记录时, + // 通过订单的波次 ID 查找关联的拣货任务 + if (taskIds.length === 0 && orderIds.length > 0) { + const firstOrderId = orderIds[0]; + const fallbackTaskId = await this._resolveTaskIdByWaveFallback(firstOrderId, warehouseId); + if (fallbackTaskId > 0) { + taskIds = [ fallbackTaskId ]; + } + } + // 逐任务判断是否所有订单均已复核完成 for (const taskId of taskIds) { const unreviewedRows = await ctx.model.query( @@ -4422,41 +4534,33 @@ class RecheckOrderService extends OrderBaseService { (Array.isArray(taskRows) && taskRows.length > 0 ? taskRows[0]?.task_id : 0) ); - if (taskId <= 0) { + // 团购模式(pick_mode=1/5)回退:wms_wave_pick_task_order 无记录时, + // 通过订单所属波次查找关联的拣货任务(回退查询使用独立连接,不参与当前事务) + let resolvedTaskId = taskId; + if (resolvedTaskId <= 0) { + resolvedTaskId = await this._resolveTaskIdByWaveFallback(orderId, warehouseId); + } + + if (resolvedTaskId <= 0) { return; } // 检查该任务下是否所有订单都已复核完成 - const unreviewedRows = await ctx.model.query( - `SELECT COUNT(*) AS cnt - FROM wms_wave_pick_task_order - WHERE task_id = :taskId - AND warehouse_id = :warehouseId - AND review_status != 1`, - { - replacements: { taskId, warehouseId }, - type: ctx.model.QueryTypes.SELECT, - transaction, - } - ); + const allReviewed = await this._checkTaskOrdersAllReviewed(resolvedTaskId, warehouseId); - const unreviewedCount = Number( - (Array.isArray(unreviewedRows) && unreviewedRows.length > 0 ? unreviewedRows[0]?.cnt : 0) - ); - - if (unreviewedCount > 0) { + if (!allReviewed) { return; } // 任务下所有订单均已复核完成,解绑车任务 try { - await this._unbindCartForTaskInTransaction(taskId, warehouseId, operatorUserId, transaction); + await this._unbindCartForTaskInTransaction(resolvedTaskId, warehouseId, operatorUserId, transaction); ctx.logger.info( - `[batchQuickRecheck] 车任务解绑成功, taskId=${taskId}, orderId=${orderId}, operatorUserId=${operatorUserId}` + `[batchQuickRecheck] 车任务解绑成功, taskId=${resolvedTaskId}, orderId=${orderId}, operatorUserId=${operatorUserId}` ); } catch (unbindError) { ctx.logger.warn( - `[batchQuickRecheck] 解绑车任务失败(复核已成功), taskId=${taskId}, orderId=${orderId}, error=${unbindError.message}` + `[batchQuickRecheck] 解绑车任务失败(复核已成功), taskId=${resolvedTaskId}, orderId=${orderId}, error=${unbindError.message}` ); } @@ -4479,7 +4583,7 @@ class RecheckOrderService extends OrderBaseService { WHERE id = :taskId AND warehouse_id = :warehouseId`, { - replacements: { taskId, warehouseId, operatorUserId, operatorName, now }, + replacements: { taskId: resolvedTaskId, warehouseId, operatorUserId, operatorName, now }, type: ctx.model.QueryTypes.UPDATE, transaction, } diff --git a/app/service/systems/delivery_order.js b/app/service/systems/delivery_order.js index fb96894..b545307 100644 --- a/app/service/systems/delivery_order.js +++ b/app/service/systems/delivery_order.js @@ -1050,6 +1050,7 @@ class DeliveryOrderService extends Service { isUrgency, invoiceFlag, receiverInfo, + sourceOrderCode } = deliveryOrder; const policyConfig = await this.getStoreWarehousePolicyConfig(info.storeId, info.warehouseId); @@ -1083,7 +1084,7 @@ class DeliveryOrderService extends Service { create_at: createTime ? new Date(createTime) : new Date(), place_order_time: placeOrderTime ? new Date(placeOrderTime) : null, pay_time: payTime ? new Date(payTime) : null, - pay_no: payNo || '', + pay_no: payNo || sourceOrderCode || '', shop_nick: shopNick, seller_nick: sellerNick, buyer_nick: buyerNick, diff --git a/app/service/systems/express.js b/app/service/systems/express.js index e9cdebc..075893a 100644 --- a/app/service/systems/express.js +++ b/app/service/systems/express.js @@ -59,7 +59,7 @@ const WAYBILL_ORDER_DELIVERY_MIN_ATTRIBUTES = Object.freeze([ 'extend_props', 'buyer_nick', 'pay_no', - 'from_key' + 'from_key', ]); class ExpressService extends Service { @@ -2273,18 +2273,42 @@ class ExpressService extends Service { const normalizedOrders = Array.isArray(bizcontent && bizcontent.orders) ? bizcontent.orders : []; - const dispatchPayloads = this.shouldDispatchWaybillAsyncPerOrder(normalizedPlatformCode) && normalizedOrders.length > 1 - ? normalizedOrders.map(order => ({ + + // 需要逐单调用的平台(cainiao/pdd):拆分为逐单 payload,并发调用 + if (this.shouldDispatchWaybillAsyncPerOrder(normalizedPlatformCode) && normalizedOrders.length > 1) { + const perOrderPayloads = normalizedOrders.map(order => ({ ...bizcontent, orders: [ order ], - })) - : [ bizcontent ]; + })); - for (const payload of dispatchPayloads) { - const dispatchResult = await dispatchMethod.call(expressPlatformService, payload); - if (dispatchResult && typeof dispatchResult === 'object' && dispatchResult.flag === 'failure') { - throw new Error(dispatchResult.message || normalizedPlatformCode + '接口调用失败'); + const perOrderResults = await Promise.all( + perOrderPayloads.map(payload => + dispatchMethod.call(expressPlatformService, payload).then( + dispatchResult => ({ payload, dispatchResult, error: null }), + error => ({ payload, dispatchResult: null, error }) + ) + ) + ); + + // 检查是否有失败结果;取第一个失败原因作为异常抛出 + const firstFailure = perOrderResults.find( + item => item.error + || (item.dispatchResult && typeof item.dispatchResult === 'object' && item.dispatchResult.flag === 'failure') + ); + if (firstFailure) { + const failureMessage = firstFailure.error + ? (firstFailure.error.message || String(firstFailure.error)) + : (firstFailure.dispatchResult && firstFailure.dispatchResult.message); + throw new Error(failureMessage || normalizedPlatformCode + '接口调用失败'); } + + return; + } + + // 非逐单平台:保持原有单次批量调用 + const dispatchResult = await dispatchMethod.call(expressPlatformService, bizcontent); + if (dispatchResult && typeof dispatchResult === 'object' && dispatchResult.flag === 'failure') { + throw new Error(dispatchResult.message || normalizedPlatformCode + '接口调用失败'); } } @@ -2462,7 +2486,7 @@ class ExpressService extends Service { [Op.in]: [ 1, 2, 3, 4 ], }, }, - attributes: [ 'id', 'sys_platform_code', 'logistics_code', 'sys_platform_name', 'logistics_name', 'store_id','pay_no','from_key' ], + attributes: [ 'id', 'sys_platform_code', 'logistics_code', 'sys_platform_name', 'logistics_name', 'store_id', 'pay_no', 'from_key' ], raw: true, }); @@ -2483,7 +2507,7 @@ class ExpressService extends Service { [Op.in]: [ 4 ], }, }, - attributes: [ 'id', 'sys_platform_code', 'logistics_code', 'sys_platform_name', 'logistics_name', 'store_id','pay_no','from_key' ], + attributes: [ 'id', 'sys_platform_code', 'logistics_code', 'sys_platform_name', 'logistics_name', 'store_id', 'pay_no', 'from_key' ], raw: true, }); } @@ -2621,15 +2645,18 @@ class ExpressService extends Service { ...expressInterface, } : null; - for (const batch of batches) { - // 异步不阻塞调用 createWaybillCode,快速返回结果给前端,后续的订单处理和异常回写都在 createWaybillCode 内部完成。 - if (pipelineOptions.awaitTasks) { - await this.asyncTask(batch, { + // 各批次并发执行:同组内不同批次的订单相互独立,无重叠,可安全并发 + if (pipelineOptions.awaitTasks) { + await Promise.all(batches.map(batch => + this.asyncTask(batch, { ...groupedOrder.options, trace_id: traceId, warehouse_id: warehouseId, - }, matchedPlatformWithRequestCode, expressInterfaceConfig); - } else { + }, matchedPlatformWithRequestCode, expressInterfaceConfig) + )); + } else { + // 非等待模式:fire-and-forget,所有批次同时触发 + for (const batch of batches) { this.asyncTask(batch, { ...groupedOrder.options, trace_id: traceId, @@ -2799,7 +2826,10 @@ class ExpressService extends Service { const { app, ctx } = this; const { Op } = app.Sequelize; const orderExpressModel = ctx.model && ctx.model.OrderExpress; - const currentWarehouseId = this.getCurrentWarehouseId(); + const currentWarehouseId = Number( + (listByWarehousePlatformCode && listByWarehousePlatformCode.warehouse_id) + || this.getCurrentWarehouseId() + ); if (!orderExpressModel || typeof orderExpressModel.findAll !== 'function' || typeof orderExpressModel.update !== 'function' @@ -3152,7 +3182,7 @@ class ExpressService extends Service { business_key: order.business_key, status: 0, retry_count: 0, - warehouse_id: this.getCurrentWarehouseId(), + warehouse_id: currentWarehouseId, store_id: order.store_id || null, logistics_code: (listByWarehousePlatformCode && listByWarehousePlatformCode.sys_express_code) || '', delivery_order_code: (orderDeliveryMap.get(order.order_id) && orderDeliveryMap.get(order.order_id).delivery_order_code) || null, diff --git a/app/service/systems/express_platform.js b/app/service/systems/express_platform.js index d7b1ee3..c6d0caf 100644 --- a/app/service/systems/express_platform.js +++ b/app/service/systems/express_platform.js @@ -920,21 +920,87 @@ class ExpressPlatformService extends MainService { }); console.log("分配运单号结果",result); - if (result && result.code !== '10000') { - const postOrderErrorMessage = String( - result.submessage || result.message || '菠萝派平台接口调用失败' - ).trim(); - this.ctx.logger.error('[expressPlatform.polyapi] PolyAPI 返回业务失败', { - traceId, - code: result.code, - message: postOrderErrorMessage, - response: result, - }); - // 清洗本批次全部订单资源,然后抛出 - const allFailedOrders = this.buildFailedOrderCleanupList(orders); - await this.cleanupFailedWaybillOrders(allFailedOrders, `PostOrder业务失败: ${postOrderErrorMessage}`); - throw new Error(`菠萝派平台接口返回错误信息:${postOrderErrorMessage},原始错误信息: \`\`\`${JSON.stringify(result)}\`\`\``); - } else if (result && result.code === '10000') { + // 统一处理:不再依赖顶层 code,直接从 results 逐条提取 issuccess 和 submessage + { + // 逐条检查 issuccess,将平台返回的业务失败项单独提取,避免因 logisticno 为空被误判为"运单号为空" + const allResults = Array.isArray(result.results) ? result.results : []; + const itemFailedList = []; + const itemSuccessList = []; + for (const item of allResults) { + const isSuccess = String(item.issuccess || '') === '1'; + if (isSuccess) { + itemSuccessList.push(item); + } else { + itemFailedList.push(item); + } + } + + // 逐条失败项:按 submessage 分组,每组使用各自的失败原因 + if (itemFailedList.length > 0) { + // 按 submessage 分组 + const reasonGroups = new Map(); + for (const failedItem of itemFailedList) { + const itemReason = String( + failedItem.submessage || failedItem.message || failedItem.subcode || '平台返回逐条业务失败' + ).trim(); + if (!reasonGroups.has(itemReason)) { + reasonGroups.set(itemReason, []); + } + reasonGroups.get(itemReason).push(failedItem); + } + + this.ctx.logger.error('[expressPlatform.polyapi] results 中存在逐条业务失败项', { + traceId, + totalCount: allResults.length, + failedCount: itemFailedList.length, + successCount: itemSuccessList.length, + reasonGroups: Array.from(reasonGroups.keys()), + sampleFailItem: JSON.stringify(itemFailedList.slice(0, 3)), + }); + + // 逐组清理 + for (const [ groupReason, groupItems ] of reasonGroups) { + const itemFailedOrders = []; + for (const failedItem of groupItems) { + const [ , order_id, business_key ] = String(failedItem.orderno || '').split('_'); + const orderId = Number(order_id) || 0; + const businessKey = Number(business_key) || 0; + if (!orderId || !businessKey) continue; + + let storeId = 0; + let warehouseId = 0; + for (const order of Array.isArray(orders) ? orders : []) { + const orderDelivery = order && order.order_delivery; + const oId = Number(orderDelivery && orderDelivery.id) || 0; + const bk = Number(order && order.business_key) || 0; + if (oId === orderId && bk === businessKey) { + storeId = Number(orderDelivery && orderDelivery.store_id) || 0; + warehouseId = Number(orderDelivery && orderDelivery.warehouse_id) || 0; + break; + } + } + itemFailedOrders.push({ + order_id: orderId, + business_key: businessKey, + warehouse_id: warehouseId, + store_id: storeId, + }); + } + if (itemFailedOrders.length > 0) { + await this.cleanupFailedWaybillOrders(itemFailedOrders, groupReason); + } + } + + // 全部订单都失败则抛出 + if (itemSuccessList.length === 0) { + const firstReason = Array.from(reasonGroups.keys())[0] || '平台返回逐条业务失败'; + throw new Error(firstReason); + } + } + + // 仅用成功的 items 继续处理 + result.results = itemSuccessList; + const resolveWaybillCode = item => String(item && (item.waybill_code || item.logisticno) || '').trim(); let successUpdates = []; switch (listByWarehousePlatformCode.platform_code) { diff --git a/app/service/systems/order_async.js b/app/service/systems/order_async.js index 19a6d20..3c4be2b 100644 --- a/app/service/systems/order_async.js +++ b/app/service/systems/order_async.js @@ -413,10 +413,12 @@ async function syncManualOrdersInternal(service, groupedOrder = {}, context = {} const waybillCodeMap = await buildOrderWaybillCodeMapInternal(service, orderIds); + // dispatch前最终去重,防止同一orderId在列表中重复导致并发双扣 + const uniqueOrderIds = [ ...new Set(orderIds) ]; const progressCacheKey = getSyncOrderIdsProgressCacheKey(context.request_id); const syncResults = []; - for (let i = 0; i < orderIds.length; i += DISPATCH_BATCH_SIZE) { - const batch = orderIds.slice(i, i + DISPATCH_BATCH_SIZE); + for (let i = 0; i < uniqueOrderIds.length; i += DISPATCH_BATCH_SIZE) { + const batch = uniqueOrderIds.slice(i, i + DISPATCH_BATCH_SIZE); const batchResults = await Promise.all(batch.map(orderId => { const dispathedOrderRow = orderMap.get(orderId); if (!dispathedOrderRow) { @@ -842,10 +844,12 @@ async function finalizeLocalChannelOrdersInternal(service, createChannel, groupe void orderItemRows; + // dispatch前最终去重,防止同一orderId在列表中重复导致并发双扣 + const uniqueOrderIds = [ ...new Set(orderIds) ]; const progressCacheKey = getSyncOrderIdsProgressCacheKey(context.request_id); const syncResults = []; - for (let i = 0; i < orderIds.length; i += DISPATCH_BATCH_SIZE) { - const batch = orderIds.slice(i, i + DISPATCH_BATCH_SIZE); + for (let i = 0; i < uniqueOrderIds.length; i += DISPATCH_BATCH_SIZE) { + const batch = uniqueOrderIds.slice(i, i + DISPATCH_BATCH_SIZE); const batchResults = await Promise.all(batch.map(orderId => { const dispathedOrderRow = orderMap.get(orderId); if (!dispathedOrderRow) { @@ -1208,9 +1212,11 @@ async function syncQmOrdersInternal(service, groupedOrder = {}, context = {}) { const qimenClient = service.app.qimenClient; const progressCacheKey = getSyncOrderIdsProgressCacheKey(context.request_id); + // dispatch前最终去重,防止同一orderId在列表中重复导致并发双扣 + const uniqueOrderIds = [ ...new Set(orderIds) ]; const qimenResults = []; - for (let i = 0; i < orderIds.length; i += DISPATCH_BATCH_SIZE) { - const batch = orderIds.slice(i, i + DISPATCH_BATCH_SIZE); + for (let i = 0; i < uniqueOrderIds.length; i += DISPATCH_BATCH_SIZE) { + const batch = uniqueOrderIds.slice(i, i + DISPATCH_BATCH_SIZE); const batchResults = await Promise.all(batch.map(orderId => { // 分发时二次检查:orderRow 不在 map 中则跳过 const dispathedOrderRow = orderMap.get(orderId); diff --git a/printer_data_template/pdd.json b/printer_data_template/pdd.json index 4543976..563b619 100644 --- a/printer_data_template/pdd.json +++ b/printer_data_template/pdd.json @@ -24,7 +24,6 @@ }, "encryptedData": "nCGXTLX57Gy747SrsozPkx1eh8H2E5WU7MGcj3KxacD3TzcoaNPPiAFxtUZBU+YZrVW69kK/T6rXC2lzapP6qnT3vTYQJ8p4OBiUIKkzktG0HAnglg2im8lxFex1sYacjUrMJej4k9BCPgHkgcwmMna+LQ6jBL5Q4Fyr8v/37jSUOeDWKSwQC9vF0t1YKDqRakOT3PFuLsY/XOqeVdEJTFKcloISdvN+XIp3Sj1imV3fXK85In9lIGSndtpQzxWUQEoc8+NDiHxD41xmp1vCUKnRnXwaf6LJP3X+r9QAJ00v/CX+r7WTmZgbjV02UNzxov+xbIcBisI+9AdQhbaPSft9SxyUFzJDAYwh22iQUAB0d9HPmKs+KAMCA7A/Ot0btFzvIVLFp3l2U32aEfCpsaSL9MSPeYmMJp0tS5l0y36MhV8i2P09HnqwLGwd1X9tDmMkzUuOE0/BmigmCKDb2vt3JDsfqC7XEwSDjjuT22mbaf7uJ34hoDGOSdcUJtW16Tr44dblvRdReA8FF8fL0uveNiYsa8eWqFIQMkHa+gDyVGEafqSED/ojUt83ex+iOess9UaA3wSfqU3l/c2kcFduCPjLd5upPY+Q40ac4MTITuaID2ZJ6GY4IBMIRVQ2s4OGG3Wd9ZJWCsYEUnaZN8RIUjwCnIyqsOPcKlD6jsxe6dHYNdiP11TxSkjp0pj6i7qtvSFoQpKQBCmK+GtTR62ipecViZeiBqFEbuDxstnPqkj8bcYibvKNOp+5iWHVXQv5vDSMQflhXP0z+qbcTKtDJtkIMjV1zY1Or5+By3kOQTEzE2x9km1GzGgp7QqWoztA8P8yCDj99RtzMDLccQDJoYaOgBzb47Z1262OiofNDO8LbPrIqdrji6VZBFUiwJE28nw7wlyib/bAFqM4+HgeNiL21yadIOSrXWW4YvK1AtpeOjDso9Nl4d06ncwC3P1ITSl8si9/k2kWuPW9goZvfFXLxmswLPyRSLD1PusgcI0pu4o4MVXjjYOro+Ax0MphhLCmoWuM0/C2tE2Pgcr/Ye3GZdWQS2pDGKszJhgSR/tP3lc0yvRbOeLWU+MEpF2h+nL+JHWT3VysohVaL+ZR71lufRj2OJJxwNv/FsUzmhzSlGZMagKvm0F4e6wj7cwixsGXJoeRJszP/DLqPbMViVpbLvBe6zqiAevr8zSHaH0+UARzQ+Jdp1Yj8fc2iXzwJQEpSJUqTlv4CXsuCFdfpX/5Lz5veeBFqTwfeimhbhwuqjgUY00DJrQb7uCFoWIapA1DQ3qqpbPoqInrD/StMvD0oR+/wP3E7pkyirA6T2Rm5gqZcDygmJyuaHPOrRecbfzYJp1M9GVm1co63R7sSahnX/PfJH7HKNf3vqajT0YJ7mOcJwzsqz9sbQUMWuk/2oS9hWC+NXaRrs20kLhnP+hKg+tnrFR40E4SydhtVHOT1IBuS2GNxP6NpKSXWutRLOHhSMTx6TSci+aWvV3W4Cr31pCxX1ZIr38AvV8RDJbTMDxCFSmfza4Qw8EnIn25Z90qM/knDuHju3ixtD5vz5RqbUmnNbsjGbt7/YVg5MSLPaeG1fHE6VgP0npQTduCvz/unN+bkhNkYUD8lhsg7/Kbv4FJByrftMJVVhZ6ZDc/3acZ2IHTEQfOY6PwYGNRl8q9rPPSnoG3iWrgS33Nh7Zp/0xk9brdbDDoAA2NoOxiQvak/OTT5/qGxHTIHxz5SiBmltlpA5Zw+bcEHB9OwItdA1rywZrVrCpRY0zK8iGw+qUFqTEUN5ybT7557NHdJueiq6Wxw4czjNj8V7lTscxknUlw8zdwXfQsMAqDs8ogT8IyqjkaoIpDatE4qGB1TYR7JEBfrEXcCdMqqqlqj4tDo7oiNBAUka5SNKJ9z8WRjBQpEZgnMzaXE8aZmLCn6tbdo7XmHWGX+VkJCTZJvBDVi7ubM8+tdkynMLRPK6+uoMlPDGYDeKYfA9hGduFG/P6TiY+dpIrrKB2/HwQZCD0XwZv8D7bA0xnQSBlXcJDBVOshJA1gHppdqt0jdEOjMXyp9RwfP49lU90O6AuDI+imkYhGLh5WJXnsaQrw+cqvOb7dcpDS6sPQbzxaPp/9brK85x4z/yWw1UJbfjRybEoyTE2KXXKHqqN/MLJDlhSH1EI6uf+Jnq40Qh9+Zp72bLV+gNbovmFgNtJAlnDFji8wyW0H9iGWuKmlU7CNgxRozMZ7J+y+NbTDx5AjX4a0EiATpZsw8OKNtEN2K7RmVf5AusTcgN4uwgs95yDENyMomxU4hFB9f0AuvHla6XCBiMcsLMUGZiiBbeqASLtGH2/Oq7MxptOtDE3Mdy2MelmQdMwKaDUZ8+PF2WjqKcy5yw56jOlHlbCru4aomuf//Ck3LOXugvCzHscdVePxvTFeSFJsIYr4idUUuseOVGwaG3ftLW0YqLvh300rwEkQf5Wtj9EMXzGhD0FPLk+q5nD3vzi/puxuNILN1S/36krYjJBLfRfh2eaRY2st9Q==?v=11&pv=1", "signature": "MQktCwU3fF9H2C3PkcGm+eAtTIO/qOHVCUTfvbkxSVrM8VuyvYbq/Xkun4qItxUJuDsbl0oa1l8p1Wb2ZtMpQHgsOCMEQfeQrFZtzubYU1xayPv8+o4GYQ+GdPXueOJQ4hCyyrnGVjJSf/qV/LKWoUGsFrXN8jC1PapMdI93XEI=", - "templateUrl": "https://file-link.pinduoduo.com/sto_one", "userid": "", "ver": "11" From b5b631f20d88231458eb528a3b5b8b222e700803 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 3 Aug 2026 01:08:36 +0800 Subject: [PATCH 157/550] =?UTF-8?q?fix(docs):=20warehouse=20=E6=96=87?= =?UTF-8?q?=E6=A1=A3=E4=BD=9C=E4=B8=BA=E5=A4=96=E9=83=A8=20API=20=E9=9A=94?= =?UTF-8?q?=E7=A6=BB=EF=BC=8C=E4=B8=8D=E6=9A=B4=E9=9C=B2=E5=86=85=E9=83=A8?= =?UTF-8?q?=E6=96=87=E6=A1=A3=E5=AF=BC=E8=88=AA=EF=BC=9B=E4=BF=AE=E6=AD=A3?= =?UTF-8?q?=E7=AD=BE=E5=90=8D=E7=AE=97=E6=B3=95=E6=8F=8F=E8=BF=B0=E4=B8=BA?= =?UTF-8?q?=20MD5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/controller/docs.js | 49 ++++++++++++++++++++++++++---------------- app/router.js | 3 +++ methods/warehouse.json | 2 +- 3 files changed, 35 insertions(+), 19 deletions(-) diff --git a/app/controller/docs.js b/app/controller/docs.js index 9996374..319c4b9 100644 --- a/app/controller/docs.js +++ b/app/controller/docs.js @@ -535,13 +535,15 @@ function renderMethodCard(item, entryPath, moduleName) { const description = item.description || ''; const isQimen = moduleName === 'qimen'; const isOpenapi = moduleName === 'openapi'; + const isWarehouse = moduleName === 'warehouse'; + const isExternalApi = isOpenapi || isWarehouse; const queryHint = isQimen ? 'app_key=xxx&method=...&v=2.0&format=json&sign_method=md5&sign=xxx×tamp=1700000000' - : isOpenapi + : isExternalApi ? `app_key=&method=${methodName}&v=1.0×tamp=1700000000` : `method=${methodName}&v=1.0×tamp=1700000000`; - const queryLabel = isOpenapi ? 'Query 参数(自动生成)' : 'Query 参数'; - const queryReadonlyAttr = isOpenapi ? ' readonly data-auto-generated="true" aria-label="自动生成"' : ''; + const queryLabel = isExternalApi ? 'Query 参数(自动生成)' : 'Query 参数'; + const queryReadonlyAttr = isExternalApi ? ' readonly data-auto-generated="true" aria-label="自动生成"' : ''; return `
    @@ -614,7 +616,7 @@ function renderMethodCard(item, entryPath, moduleName) { - ${isOpenapi ? ` + ${isExternalApi ? ` ` : ''} @@ -646,12 +648,14 @@ function renderHtmlPage({ entryPath, }) { const isOpenapi = docData.module === 'openapi'; + const isWarehouse = docData.module === 'warehouse'; + const isExternalApi = isOpenapi || isWarehouse; const methodsCount = groups.reduce((sum, group) => sum + toArray(group.list).length, 0); const globalHeaders = toArray(docData.headers); const globalHeadersControls = renderGlobalHeadersControls(globalHeaders); const rawUrl = `/api/docs/${encodeURIComponent(docName)}/raw`; const changesUrl = `/api/docs/${encodeURIComponent(docName)}/changes`; - const navHtml = isOpenapi ? '' : docs.filter(name => name !== 'openapi').map(name => { + const navHtml = isExternalApi ? '' : docs.filter(name => name !== 'openapi' && name !== 'warehouse').map(name => { const activeClass = name === docName ? 'active' : ''; return `${escapeHtml(name)}`; }).join(''); @@ -1076,7 +1080,7 @@ function renderHtmlPage({ 查看变更记录 查看 JSON
    - ${isOpenapi ? '' : `
    + ${isExternalApi ? '' : `

    全局 Authorization

    @@ -1087,7 +1091,7 @@ function renderHtmlPage({ ${globalHeadersControls}

    来自 JSON 的 headers 定义;带 * 的字段为必填,支持下拉 list 选择。

    `} - ${isOpenapi ? '' : `
    + ${isExternalApi ? '' : `

    文档资源

    ${renderWindowElement('打开变更记录', changesUrl, 'doc-resource-link')} @@ -1097,9 +1101,9 @@ function renderHtmlPage({
    点击上方按钮后,可直接预览当前文档的变更记录或原文 JSON。
    `} - ${isOpenapi ? `
    + ${isExternalApi ? `

    请求方式

    -
    POST /openapi?method={方法名}&v=1.0×tamp={时间戳}&app_key={app_key}&sign={签名}
    +        
    POST ${isOpenapi ? '/openapi' : '/warehouse'}?method={方法名}&v=1.0×tamp={时间戳}&app_key={app_key}&sign={签名}
     Content-Type: application/json
     
     {请求体 JSON}
    @@ -1138,10 +1142,10 @@ Content-Type: application/json
  • 时间戳 timestamp 时效校验:与服务器时间差不得超过 ±10 分钟(600 秒),超时返回 400
  • 签名结果为 32 位小写十六进制字符串
  • -

    + ${isOpenapi ? `

    → 回调测试工具 (模拟接收回调通知,验证回调链路) -

    +

    ` : ''}
    ` : ''}
    @@ -1167,9 +1171,10 @@ Content-Type: application/json (function() { var DOC_NAME = ${JSON.stringify(docName)}; var IS_OPENAPI_DOC = DOC_NAME === 'openapi'; + var IS_EXTERNAL_API_DOC = DOC_NAME === 'openapi' || DOC_NAME === 'warehouse'; var AUTH_KEY = 'wms_docs_global_auth'; var HEADER_STORE_KEY = 'wms_docs_global_headers_' + ${JSON.stringify(docName)}; - var OPENAPI_APP_KEY_STORE_KEY = 'wms_docs_openapi_app_key'; + var OPENAPI_APP_KEY_STORE_KEY = 'wms_docs_' + DOC_NAME + '_app_key'; var authInput = document.getElementById('globalAuth'); var clearBtn = document.getElementById('clearAuthBtn'); var searchInput = document.getElementById('methodSearch'); @@ -1547,7 +1552,7 @@ Content-Type: application/json return 'app_key=&method=' + encodeURIComponent(methodName) + '&v=2.0&format=json&sign_method=md5&sign=×tamp=' + nowTimestamp(); } - if (moduleName === 'openapi') { + if (moduleName === 'openapi' || moduleName === 'warehouse') { return buildOpenapiQuery(card, ''); } return 'method=' + encodeURIComponent(methodName) + '&v=1.0×tamp=' + nowTimestamp(); @@ -1573,7 +1578,7 @@ Content-Type: application/json var bodyInput = card.querySelector('.req-body'); var moduleName = card.getAttribute('data-module') || ''; if (queryInput) { - if (moduleName === 'openapi') { + if (moduleName === 'openapi' || moduleName === 'warehouse') { var appKeyInput = card.querySelector('.req-app-key'); var openapiAppKey = (appKeyInput && appKeyInput.value.trim()) || ''; queryInput.value = buildOpenapiQuery(card, openapiAppKey); @@ -1593,11 +1598,11 @@ Content-Type: application/json * @return {void} */ function refreshOpenapiQueryDisplays(appKey) { - if (!IS_OPENAPI_DOC) { + if (!IS_EXTERNAL_API_DOC) { return; } - var cards = document.querySelectorAll('.method-card[data-module="openapi"]'); + var cards = document.querySelectorAll('.method-card[data-module="openapi"], .method-card[data-module="warehouse"]'); cards.forEach(function(card) { var queryInput = card.querySelector('.req-query'); if (!queryInput) { @@ -1613,7 +1618,7 @@ Content-Type: application/json * @return {void} */ function initOpenapiAppKeyInputs() { - if (!IS_OPENAPI_DOC) { + if (!IS_EXTERNAL_API_DOC) { return; } @@ -1856,7 +1861,7 @@ Content-Type: application/json return; } - if (moduleName === 'openapi') { + if (moduleName === 'openapi' || moduleName === 'warehouse') { var appKeyInput = card.querySelector('.req-app-key'); var openapiAppKey = (appKeyInput && appKeyInput.value.trim()) || ''; query = buildOpenapiQuery(card, openapiAppKey); @@ -2040,6 +2045,14 @@ class DocsController extends Controller { await this.renderDoc('openapi'); } + /** + * 渲染仓库开放 API 文档独立页面。 + * @return {Promise} 无返回值。 + */ + async warehouse() { + await this.renderDoc('warehouse'); + } + async detail() { const { ctx } = this; const docName = ctx.params.docName; diff --git a/app/router.js b/app/router.js index fb4cd42..b437fe3 100644 --- a/app/router.js +++ b/app/router.js @@ -33,6 +33,9 @@ module.exports = app => { // OpenAPI 文档 — 所有环境均可访问,必须在通配路由之前注册 router.get('/docs/api/openapi', controller.docs.openapi); + // Warehouse 开放 API 文档 — 所有环境均可访问 + router.get('/docs/api/warehouse', controller.docs.warehouse); + // OpenAPI 回调测试 — 所有环境均可访问的独立调试页面 router.get('/docs/api/openapi/callback-test', controller.openapiCallback.testPage); diff --git a/methods/warehouse.json b/methods/warehouse.json index 4c24677..c344f36 100644 --- a/methods/warehouse.json +++ b/methods/warehouse.json @@ -1,6 +1,6 @@ { "module": "warehouse", - "description": "仓库开放 API 统一入口,供仓库级外部适配器(企微/钉钉/飞书/IM 等)调用,HTTP POST /warehouse,使用 HMAC-SHA256 签名鉴权(interface_type_id=3)", + "description": "仓库开放 API 统一入口,供仓库级外部适配器(企微/钉钉/飞书/IM 等)调用,HTTP POST /warehouse,使用 MD5 签名鉴权(interface_type_id=3)", "version": "1.0.0", "updatedAt": "2026-08-01", "http": { From 4374ad01e322c61112feb49a617e45d5d3d904a5 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 3 Aug 2026 01:36:16 +0800 Subject: [PATCH 158/550] =?UTF-8?q?feat(inbox):=20=E7=AB=99=E5=86=85?= =?UTF-8?q?=E4=BF=A1=E6=A8=A1=E5=9D=97=E5=AE=8C=E6=95=B4=E5=AE=9E=E7=8E=B0?= =?UTF-8?q?=20=E2=80=94=20=E7=BB=9F=E4=B8=80=E6=B6=88=E6=81=AF=E6=94=B6?= =?UTF-8?q?=E4=BB=B6=E7=AE=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/controller/inbox.js | 127 + app/model/inbox_message.js | 190 + app/router.js | 3 + app/service/inbox/dispatch/base.js | 118 + app/service/inbox/dispatch/dingtalk.js | 35 + app/service/inbox/dispatch/feishu.js | 60 + app/service/inbox/dispatch/webhook.js | 44 + app/service/inbox/dispatch/wecom.js | 33 + app/service/inbox/index.js | 354 + app/service/inbox/receiver.js | 370 + app/service/warehouseMethods/inbox.js | 64 + .../designs/inbox-message-module-design.md | 441 + .../20260803120000-create-inbox-message.js | 182 + methods/changes/system.json | 10244 ++++++++-------- methods/changes/warehouse.json | 59 +- methods/system.json | 603 +- methods/warehouse.json | 144 +- 17 files changed, 7940 insertions(+), 5131 deletions(-) create mode 100644 app/controller/inbox.js create mode 100644 app/model/inbox_message.js create mode 100644 app/service/inbox/dispatch/base.js create mode 100644 app/service/inbox/dispatch/dingtalk.js create mode 100644 app/service/inbox/dispatch/feishu.js create mode 100644 app/service/inbox/dispatch/webhook.js create mode 100644 app/service/inbox/dispatch/wecom.js create mode 100644 app/service/inbox/index.js create mode 100644 app/service/inbox/receiver.js create mode 100644 app/service/warehouseMethods/inbox.js create mode 100644 database/designs/inbox-message-module-design.md create mode 100644 database/migrations/20260803120000-create-inbox-message.js diff --git a/app/controller/inbox.js b/app/controller/inbox.js new file mode 100644 index 0000000..239cdc8 --- /dev/null +++ b/app/controller/inbox.js @@ -0,0 +1,127 @@ +'use strict'; + +const { Controller } = require('egg'); +const { toSuccess, toFailure } = require('../lib/api_response'); + +/** + * 站内信内部管理接口控制器。 + * 提供消息列表、详情、对话链、回信、重推、统计等管理功能。 + */ +class InboxController extends Controller { + /** + * 获取当前仓库上下文。 + * @return {{ warehouseId: number }} 仓库上下文。 + */ + getWarehouseContext() { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id); + + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + throw new Error('缺少仓库信息'); + } + + return { warehouseId }; + } + + /** + * 内部管理统一入口,分发到对应 service 方法。 + * @return {Promise} 无返回值,结果写入 ctx.body。 + */ + async index() { + const { ctx } = this; + + try { + const method = String(ctx.request.body && ctx.request.body.method || '').trim(); + if (!method || !method.startsWith('inbox.')) { + ctx.status = 400; + ctx.body = toFailure({ message: 'method 参数无效' }); + ctx.type = 'application/json'; + return; + } + + const action = method.replace('inbox.', ''); + const data = (ctx.request.body && ctx.request.body.data) || {}; + + let result; + + switch (action) { + case 'list': { + const { warehouseId } = this.getWarehouseContext(); + result = await ctx.service.inbox.index.list({ + warehouseId, + ...data, + }); + break; + } + + case 'detail': { + const { warehouseId } = this.getWarehouseContext(); + result = await ctx.service.inbox.index.detail({ + warehouseId, + id: data.id, + }); + break; + } + + case 'thread': { + const { warehouseId } = this.getWarehouseContext(); + result = await ctx.service.inbox.index.thread({ + warehouseId, + id: data.id, + }); + break; + } + + case 'reply': { + const { warehouseId } = this.getWarehouseContext(); + result = await ctx.service.inbox.index.reply({ + warehouseId, + parentId: data.parentId, + targetChannel: data.targetChannel, + targetUrl: data.targetUrl, + targetType: data.targetType, + refCode: data.refCode, + extData: data.extData, + flags: data.flags, + }); + break; + } + + case 'retry': { + const { warehouseId } = this.getWarehouseContext(); + result = await ctx.service.inbox.index.retry({ + warehouseId, + id: data.id, + }); + break; + } + + case 'stats': { + const { warehouseId } = this.getWarehouseContext(); + result = await ctx.service.inbox.index.stats({ + warehouseId, + direction: data.direction, + }); + break; + } + + default: + ctx.status = 400; + ctx.body = toFailure({ message: `不支持的 inbox 方法: ${action}` }); + ctx.type = 'application/json'; + return; + } + + ctx.status = 200; + ctx.body = toSuccess(result, 'ok'); + ctx.type = 'application/json'; + } catch (error) { + const message = String(error && error.message || '请求失败'); + ctx.status = 500; + ctx.body = toFailure({ message: `站内信错误: ${message}` }); + ctx.type = 'application/json'; + } + } +} + +module.exports = InboxController; diff --git a/app/model/inbox_message.js b/app/model/inbox_message.js new file mode 100644 index 0000000..6a43ce1 --- /dev/null +++ b/app/model/inbox_message.js @@ -0,0 +1,190 @@ +'use strict'; + +/** + * 站内信消息 Model。 + * 统一管理消息推送状态追踪:谁发来的、要推到哪、推送状态。 + * inbound(外部→WMS)与 outbound(WMS→外部)共表,direction + parent_id 形成对话链。 + * @param {Object} app Egg.js Application 实例。 + * @return {Object} Sequelize Model 定义。 + */ +module.exports = app => { + const { BIGINT, STRING, TINYINT, DATE, INTEGER, JSON: JSON_TYPE } = app.Sequelize; + + const InboxMessage = app.model.define('inbox_message', { + id: { + type: BIGINT.UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + ext_id: { + type: STRING(128), + allowNull: false, + comment: '外部唯一消息主键(IM msgId / API requestId 等),用于幂等去重', + }, + warehouse_id: { + type: BIGINT.UNSIGNED, + allowNull: false, + comment: '所属仓库ID', + }, + store_id: { + type: BIGINT.UNSIGNED, + allowNull: true, + comment: '关联货主ID', + }, + direction: { + type: STRING(10), + allowNull: false, + defaultValue: 'inbound', + validate: { + isIn: { + args: [[ 'inbound', 'outbound' ]], + msg: 'direction 必须是 inbound 或 outbound', + }, + }, + comment: '消息方向:inbound=外部→WMS收件 / outbound=WMS→外部回信', + }, + parent_id: { + type: BIGINT.UNSIGNED, + allowNull: true, + comment: '关联消息ID(回信时指向原消息,形成对话链)', + }, + source_type: { + type: STRING(20), + allowNull: false, + validate: { + isIn: { + args: [[ 'im', 'api', 'system' ]], + msg: 'source_type 必须是 im、api 或 system', + }, + }, + comment: '来源类型:im / api / system', + }, + source_extra: { + type: STRING(100), + allowNull: true, + comment: '来源附加信息(IM 平台 / API app_id)', + }, + target_type: { + type: STRING(20), + allowNull: false, + validate: { + isIn: { + args: [[ 'im', 'api', 'webhook' ]], + msg: 'target_type 必须是 im、api 或 webhook', + }, + }, + comment: '目标类型:im / api / webhook', + }, + target_channel: { + type: STRING(50), + allowNull: false, + validate: { + notEmpty: { + msg: 'target_channel 不能为空', + }, + }, + comment: '目标渠道:wecom / dingtalk / feishu / warehouse_api / webhook', + }, + target_url: { + type: STRING(500), + allowNull: false, + validate: { + notEmpty: { + msg: 'target_url 不能为空', + }, + len: { + args: [ 1, 500 ], + msg: 'target_url 长度应在1-500个字符之间', + }, + }, + comment: '推送目标URL(IM Bot webhook 地址 / API 回调地址)', + }, + ref_code: { + type: STRING(100), + allowNull: true, + comment: '外部引用编码,推送/回执时原样携带', + }, + ext_data: { + type: JSON_TYPE, + allowNull: true, + comment: '外部透传数据,外部传入任意JSON,WMS不解析,回信时原样返回', + }, + flags: { + type: JSON_TYPE, + allowNull: true, + comment: '处理标记,外部传入控制WMS处理行为', + }, + push_status: { + type: TINYINT(4), + allowNull: false, + defaultValue: 0, + validate: { + isIn: { + args: [[ 0, 1, 2, 3 ]], + msg: 'push_status 必须是 0(待推送)、1(推送中)、2(已送达)、3(失败)', + }, + }, + comment: '推送状态:0=待推送 1=推送中 2=已送达 3=失败', + }, + push_started_at: { + type: DATE, + allowNull: true, + comment: '开始推送时间(僵尸检测:超5分钟仍为1则重置为0)', + }, + retry_count: { + type: INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '已重试次数', + }, + push_response: { + type: JSON_TYPE, + allowNull: true, + comment: '目标响应(http_status, body, error)', + }, + pushed_at: { + type: DATE, + allowNull: true, + comment: '推送完成时间', + }, + work_order_id: { + type: BIGINT.UNSIGNED, + allowNull: true, + comment: '关联工单ID(预留)', + }, + work_order_no: { + type: STRING(50), + allowNull: true, + comment: '工单号(预留)', + }, + created_at: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + tableName: 'wms_inbox_message', + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + deletedAt: 'deleted_at', + paranoid: true, + comment: '站内信消息推送状态追踪表', + }); + + return InboxMessage; +}; diff --git a/app/router.js b/app/router.js index b437fe3..cf6fb6b 100644 --- a/app/router.js +++ b/app/router.js @@ -67,4 +67,7 @@ module.exports = app => { router.get('/testSendData', controller.home.testSendData); // IM交互入口 router.post('/im', controller.im.index); + + // 站内信内部管理接口 + router.post('/inbox', controller.inbox.index); }; diff --git a/app/service/inbox/dispatch/base.js b/app/service/inbox/dispatch/base.js new file mode 100644 index 0000000..eb6ff61 --- /dev/null +++ b/app/service/inbox/dispatch/base.js @@ -0,0 +1,118 @@ +'use strict'; + +const Service = require('egg').Service; +const apiSignLib = require('../../../lib/api_sign'); + +const WAREHOUSE_INTERFACE_TYPE_ID = 3; +const DISPATCH_TIMEOUT_MS = 10000; // 10s 超时 + +/** + * 统一出站基类,所有渠道 dispatch 继承此类。 + * 统一处理:查密钥、签名、发 HTTP。 + * 子类只需实现 push(record) 方法,关注消息格式转换。 + */ +class OutboundBase extends Service { + /** + * 获取仓库 ApiApp 密钥配置(IM 渠道无需签名,返回 null)。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} ApiApp 配置对象,含 appKey / selfAppSecret / warehouseId。 + */ + async getApiApp(warehouseId) { + const { ctx } = this; + try { + // 通过仓库ID查找该仓库的 warehouse 类型 ApiApp + const apiApp = await ctx.model.ApiApp.findOne({ + attributes: [ 'id', 'self_app_key', 'self_app_secret', 'is_enabled', 'interface_type_id', 'warehouse_id' ], + where: { + warehouse_id: warehouseId, + interface_type_id: WAREHOUSE_INTERFACE_TYPE_ID, + is_enabled: 1, + }, + raw: true, + }); + + if (!apiApp || !apiApp.self_app_secret) { + return null; + } + + return { + appKey: apiApp.self_app_key, + selfAppSecret: apiApp.self_app_secret, + warehouseId: Number(apiApp.warehouse_id), + }; + } catch (error) { + ctx.logger.warn(`[inbox dispatch] 获取仓库 ApiApp 失败: ${error.message}`); + return null; + } + } + + /** + * 生成 MD5 签名,返回带签名后的完整 URL。 + * @param {string} url 原始目标URL。 + * @param {*} body 请求体。 + * @param {Object} secret ApiApp 密钥对象,含 appKey / selfAppSecret。 + * @return {string} 带签名的完整URL。 + */ + signRequest(url, body, secret) { + const timestamp = Math.floor(Date.now() / 1000); + const query = { + app_key: secret.appKey, + timestamp, + }; + + const { sign } = apiSignLib.signRequest({ + query, + body, + selfAppSecret: secret.selfAppSecret, + }); + + const separator = url.includes('?') ? '&' : '?'; + return `${url}${separator}app_key=${encodeURIComponent(query.app_key)}×tamp=${timestamp}&sign=${encodeURIComponent(sign)}`; + } + + /** + * 统一 HTTP POST 发送。 + * @param {string} url 目标URL。 + * @param {*} body 请求体。 + * @param {Object} [options] 额外选项。 + * @param {Object} [options.headers] 自定义请求头。 + * @return {Promise<{status: number, data: *}>} 响应结果。 + */ + async post(url, body, options = {}) { + const { ctx } = this; + const headers = { + 'Content-Type': 'application/json', + ...(options.headers || {}), + }; + + try { + const response = await ctx.curl(url, { + method: 'POST', + dataType: 'json', + contentType: 'json', + data: body, + headers, + timeout: DISPATCH_TIMEOUT_MS, + }); + + return { + status: response.status, + data: response.data, + }; + } catch (error) { + throw new Error(`HTTP 推送失败: ${error.message}`); + } + } + + /** + * 子类必须实现的推送方法。 + * @param {Object} record 消息记录(Sequelize Model 实例),子类按需使用。 + * @throws {Error} 子类未实现时抛出。 + */ + async push(record) { + const id = record && record.id; + throw new Error(`子类必须实现 push(record) 方法,当前消息ID: ${id || '未知'}`); + } +} + +module.exports = OutboundBase; diff --git a/app/service/inbox/dispatch/dingtalk.js b/app/service/inbox/dispatch/dingtalk.js new file mode 100644 index 0000000..aab3df4 --- /dev/null +++ b/app/service/inbox/dispatch/dingtalk.js @@ -0,0 +1,35 @@ +'use strict'; + +const OutboundBase = require('./base'); + +/** + * 钉钉 Bot 渠道出站实现。 + * 推送 Markdown 消息到钉钉机器人 webhook。 + */ +class DingtalkDispatch extends OutboundBase { + /** + * 通过钉钉 Bot 推送消息。 + * @param {Object} record 消息记录(Sequelize Model 实例)。 + * @return {Promise<{status: number, data: *}>} 推送响应。 + */ + async push(record) { + const { ctx } = this; + + const extData = record.ext_data || {}; + const title = extData.title || '新消息通知'; + const text = extData.content || extData.text || `消息:${record.ref_code || record.ext_id}`; + + const body = { + msgtype: 'markdown', + markdown: { + title, + text: typeof text === 'string' ? text : JSON.stringify(text), + }, + }; + + ctx.logger.info(`[inbox dingtalk] 推送消息 ext_id=${record.ext_id} url=${record.target_url}`); + return await this.post(record.target_url, body); + } +} + +module.exports = DingtalkDispatch; diff --git a/app/service/inbox/dispatch/feishu.js b/app/service/inbox/dispatch/feishu.js new file mode 100644 index 0000000..26b5358 --- /dev/null +++ b/app/service/inbox/dispatch/feishu.js @@ -0,0 +1,60 @@ +'use strict'; + +const OutboundBase = require('./base'); + +/** + * 飞书 Bot 渠道出站实现。 + * 推送交互式卡片消息到飞书机器人 webhook。 + */ +class FeishuDispatch extends OutboundBase { + /** + * 通过飞书 Bot 推送消息。 + * @param {Object} record 消息记录(Sequelize Model 实例)。 + * @return {Promise<{status: number, data: *}>} 推送响应。 + */ + async push(record) { + const { ctx } = this; + + const extData = record.ext_data || {}; + const title = extData.title || '新消息通知'; + const content = extData.content || extData.text || `消息:${record.ref_code || record.ext_id}`; + + const body = { + msg_type: 'interactive', + card: { + header: { + title: { + tag: 'plain_text', + content: title, + }, + }, + elements: [ + { + tag: 'div', + text: { + tag: 'lark_md', + content: typeof content === 'string' ? content : JSON.stringify(content), + }, + }, + { + tag: 'hr', + }, + { + tag: 'note', + elements: [ + { + tag: 'plain_text', + content: `编号: ${record.ref_code || record.ext_id}`, + }, + ], + }, + ], + }, + }; + + ctx.logger.info(`[inbox feishu] 推送消息 ext_id=${record.ext_id} url=${record.target_url}`); + return await this.post(record.target_url, body); + } +} + +module.exports = FeishuDispatch; diff --git a/app/service/inbox/dispatch/webhook.js b/app/service/inbox/dispatch/webhook.js new file mode 100644 index 0000000..4df3812 --- /dev/null +++ b/app/service/inbox/dispatch/webhook.js @@ -0,0 +1,44 @@ +'use strict'; + +const OutboundBase = require('./base'); + +/** + * Webhook 渠道出站实现。 + * 直接 HTTP POST 推送 JSON 到目标 webhook URL。 + */ +class WebhookDispatch extends OutboundBase { + /** + * 通过 webhook 渠道推送消息。 + * @param {Object} record 消息记录(Sequelize Model 实例)。 + * @return {Promise<{status: number, data: *}>} 推送响应。 + */ + async push(record) { + const { ctx } = this; + + const body = { + ref_code: record.ref_code, + ext_data: record.ext_data, + message_id: record.ext_id, + direction: record.direction, + source_type: record.source_type, + created_at: record.created_at, + }; + + let targetUrl = record.target_url; + + // API 类型需要签名 + if (record.target_type === 'api') { + const apiApp = await this.getApiApp(record.warehouse_id); + if (apiApp) { + targetUrl = this.signRequest(targetUrl, body, apiApp); + } else { + ctx.logger.warn(`[inbox webhook] 仓库 ${record.warehouse_id} 没有可用 ApiApp,跳过签名`); + } + } + + ctx.logger.info(`[inbox webhook] 推送消息 ext_id=${record.ext_id} url=${targetUrl}`); + return await this.post(targetUrl, body); + } +} + +module.exports = WebhookDispatch; diff --git a/app/service/inbox/dispatch/wecom.js b/app/service/inbox/dispatch/wecom.js new file mode 100644 index 0000000..09ff283 --- /dev/null +++ b/app/service/inbox/dispatch/wecom.js @@ -0,0 +1,33 @@ +'use strict'; + +const OutboundBase = require('./base'); + +/** + * 企微 Bot 渠道出站实现。 + * 推送 Markdown 消息到企业微信机器人 webhook。 + */ +class WecomDispatch extends OutboundBase { + /** + * 通过企微 Bot 推送消息。 + * @param {Object} record 消息记录(Sequelize Model 实例)。 + * @return {Promise<{status: number, data: *}>} 推送响应。 + */ + async push(record) { + const { ctx } = this; + + const extData = record.ext_data || {}; + const content = extData.content || extData.text || `新消息通知:${record.ref_code || record.ext_id}`; + + const body = { + msgtype: 'markdown', + markdown: { + content: typeof content === 'string' ? content : JSON.stringify(content), + }, + }; + + ctx.logger.info(`[inbox wecom] 推送消息 ext_id=${record.ext_id} url=${record.target_url}`); + return await this.post(record.target_url, body); + } +} + +module.exports = WecomDispatch; diff --git a/app/service/inbox/index.js b/app/service/inbox/index.js new file mode 100644 index 0000000..6a68f32 --- /dev/null +++ b/app/service/inbox/index.js @@ -0,0 +1,354 @@ +'use strict'; + +const Service = require('egg').Service; +const crypto = require('crypto'); + +/** + * 站内信查询/管理服务。 + * 提供消息列表、详情、对话链、回复、重推、统计等管理功能。 + */ +class InboxService extends Service { + /** + * 消息列表(按仓库/状态/方向筛选,分页)。 + * @param {Object} params 查询参数。 + * @param {number} params.warehouseId 仓库ID(必填,服务端上下文注入)。 + * @param {string} [params.direction] 消息方向筛选:inbound / outbound。 + * @param {number} [params.pushStatus] 推送状态筛选:0/1/2/3。 + * @param {string} [params.targetChannel] 目标渠道筛选。 + * @param {string} [params.keyword] 关键词搜索(ext_id / ref_code)。 + * @param {number} [params.page=1] 页码。 + * @param {number} [params.pageSize=20] 每页数量。 + * @return {Promise<{list: Array, pagination: Object}>} 分页结果。 + */ + async list(params = {}) { + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + const { InboxMessage } = ctx.model; + + const warehouseId = Number(params.warehouseId); + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + throw new Error('warehouseId 无效'); + } + + const page = Math.max(1, Number(params.page) || 1); + const pageSize = Math.min(200, Math.max(1, Number(params.pageSize) || 20)); + + const where = { + warehouse_id: warehouseId, + }; + + if (params.direction && [ 'inbound', 'outbound' ].includes(params.direction)) { + where.direction = params.direction; + } + + if (params.pushStatus !== undefined && params.pushStatus !== null && params.pushStatus !== '') { + const status = Number(params.pushStatus); + if ([ 0, 1, 2, 3 ].includes(status)) { + where.push_status = status; + } + } + + if (params.targetChannel && typeof params.targetChannel === 'string') { + where.target_channel = params.targetChannel.trim(); + } + + if (params.keyword && typeof params.keyword === 'string') { + const keyword = `%${params.keyword.trim()}%`; + where[Op.or] = [ + { ext_id: { [Op.like]: keyword } }, + { ref_code: { [Op.like]: keyword } }, + ]; + } + + const { count: total, rows } = await InboxMessage.findAndCountAll({ + attributes: { + exclude: [ 'ext_data', 'push_response' ], + }, + where, + order: [[ 'created_at', 'DESC' ]], + offset: (page - 1) * pageSize, + limit: pageSize, + }); + + return { + list: rows, + pagination: { + page, + pageSize, + total, + totalPages: Math.ceil(total / pageSize), + hasPrevious: page > 1, + hasNext: page * pageSize < total, + }, + }; + } + + /** + * 消息详情(含 push_response)。 + * @param {Object} params 查询参数。 + * @param {number} params.warehouseId 仓库ID(必填)。 + * @param {number} params.id 消息ID。 + * @return {Promise} 消息详情。 + */ + async detail(params = {}) { + const { ctx } = this; + const { InboxMessage } = ctx.model; + + const warehouseId = Number(params.warehouseId); + const id = Number(params.id); + + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + throw new Error('warehouseId 无效'); + } + if (!Number.isFinite(id) || id <= 0) { + throw new Error('消息ID无效'); + } + + const record = await InboxMessage.findOne({ + where: { id, warehouse_id: warehouseId }, + }); + + if (!record) { + throw new Error('消息不存在或无权访问'); + } + + return record; + } + + /** + * 对话链查询(原消息 + 所有回信),按 parent_id 递归。 + * @param {Object} params 查询参数。 + * @param {number} params.warehouseId 仓库ID(必填)。 + * @param {number} params.id 消息ID。 + * @return {Promise} 对话链列表。 + */ + async thread(params = {}) { + const { ctx } = this; + const { InboxMessage } = ctx.model; + + const warehouseId = Number(params.warehouseId); + const id = Number(params.id); + + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + throw new Error('warehouseId 无效'); + } + if (!Number.isFinite(id) || id <= 0) { + throw new Error('消息ID无效'); + } + + // 查找根消息 + const root = await InboxMessage.findOne({ + where: { id, warehouse_id: warehouseId }, + }); + + if (!root) { + throw new Error('消息不存在或无权访问'); + } + + // 收集对话链:从根到叶 + const thread = [ root ]; + + // 查找所有回信(以 root.id 为 parent_id) + const replies = await InboxMessage.findAll({ + where: { + warehouse_id: warehouseId, + parent_id: root.id, + }, + order: [[ 'created_at', 'ASC' ]], + }); + + thread.push(...replies); + + // 如果当前消息不是根(有 parent_id),也向上查找原消息 + if (root.parent_id) { + const parent = await InboxMessage.findOne({ + where: { + id: root.parent_id, + warehouse_id: warehouseId, + }, + }); + + if (parent) { + thread.unshift(parent); + } + } + + return thread; + } + + /** + * 系统回信:写入 outbound 记录 + 异步推送。 + * @param {Object} data 回信数据。 + * @param {number} data.warehouseId 仓库ID(必填,服务端上下文注入)。 + * @param {number} data.parentId 原消息ID。 + * @param {string} data.targetChannel 目标渠道。 + * @param {string} data.targetUrl 推送目标URL。 + * @param {string} [data.refCode] 引用编码。 + * @param {Object} [data.extData] 透传数据。 + * @param {Object} [data.flags] 处理标记。 + * @return {Promise} 回信结果。 + */ + async reply(data = {}) { + const { ctx } = this; + const { InboxMessage } = ctx.model; + + const warehouseId = Number(data.warehouseId); + const parentId = Number(data.parentId); + + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + throw new Error('warehouseId 无效'); + } + if (!Number.isFinite(parentId) || parentId <= 0) { + throw new Error('parentId 无效'); + } + + // 查找原消息 + const parent = await InboxMessage.findOne({ + where: { id: parentId, warehouse_id: warehouseId }, + }); + + if (!parent) { + throw new Error('原消息不存在或无权访问'); + } + + const extId = `sys:${crypto.randomUUID()}`; + + const result = await ctx.service.inbox.receiver.receive({ + ext_id: extId, + warehouse_id: warehouseId, + store_id: parent.store_id, + direction: 'outbound', + parent_id: parentId, + source_type: 'system', + source_extra: null, + target_type: data.targetType || parent.target_type, + target_channel: data.targetChannel, + target_url: data.targetUrl, + ref_code: data.refCode || parent.ref_code, + ext_data: data.extData || parent.ext_data, + flags: data.flags || {}, + }); + + return result; + } + + /** + * 手动重推。 + * @param {Object} params 重推参数。 + * @param {number} params.warehouseId 仓库ID(必填)。 + * @param {number} params.id 消息ID。 + * @return {Promise} 重推结果。 + */ + async retry(params = {}) { + const { ctx } = this; + const { InboxMessage } = ctx.model; + + const warehouseId = Number(params.warehouseId); + const id = Number(params.id); + + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + throw new Error('warehouseId 无效'); + } + if (!Number.isFinite(id) || id <= 0) { + throw new Error('消息ID无效'); + } + + const record = await InboxMessage.findOne({ + where: { id, warehouse_id: warehouseId }, + }); + + if (!record) { + throw new Error('消息不存在或无权访问'); + } + + if (![ 3 ].includes(record.push_status)) { + throw new Error('仅失败状态的消息可以手动重推'); + } + + // 重置为待推送状态,由异步推送接管 + await record.update({ + push_status: 0, + push_started_at: null, + }); + + // 触发异步推送 + setImmediate(() => { + ctx.service.inbox.receiver.asyncPush(record, 0).catch(err => { + ctx.logger.error(`[inbox] 手动重推异常 ext_id=${record.ext_id}: ${err.message}`); + }); + }); + + return { + ok: true, + id: record.id, + ext_id: record.ext_id, + message: '已触发重推', + }; + } + + /** + * 推送统计(按仓库 + 状态汇总)。 + * @param {Object} params 统计参数。 + * @param {number} params.warehouseId 仓库ID(必填)。 + * @param {string} [params.direction] 消息方向筛选。 + * @return {Promise} 统计结果。 + */ + async stats(params = {}) { + const { ctx } = this; + const { InboxMessage } = ctx.model; + const { Op } = ctx.app.Sequelize; + + const warehouseId = Number(params.warehouseId); + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + throw new Error('warehouseId 无效'); + } + + const where = { + warehouse_id: warehouseId, + }; + + if (params.direction && [ 'inbound', 'outbound' ].includes(params.direction)) { + where.direction = params.direction; + } + + // 按方向统计 + const directionStats = await InboxMessage.findAll({ + attributes: [ + 'direction', + [ ctx.app.Sequelize.fn('COUNT', ctx.app.Sequelize.col('id')), 'count' ], + ], + where, + group: [ 'direction' ], + raw: true, + }); + + // 按推送状态统计 + const statusStats = await InboxMessage.findAll({ + attributes: [ + 'push_status', + [ ctx.app.Sequelize.fn('COUNT', ctx.app.Sequelize.col('id')), 'count' ], + ], + where, + group: [ 'push_status' ], + raw: true, + }); + + // 最近24小时统计 + const recentWhere = { + ...where, + created_at: { + [Op.gte]: new Date(Date.now() - 24 * 60 * 60 * 1000), + }, + }; + + const recentCount = await InboxMessage.count({ where: recentWhere }); + + return { + total_by_direction: directionStats, + total_by_status: statusStats, + recent_24h_count: recentCount, + }; + } +} + +module.exports = InboxService; diff --git a/app/service/inbox/receiver.js b/app/service/inbox/receiver.js new file mode 100644 index 0000000..fd9433a --- /dev/null +++ b/app/service/inbox/receiver.js @@ -0,0 +1,370 @@ +'use strict'; + +const Service = require('egg').Service; + +const { URL } = require('url'); +const { networkInterfaces } = require('os'); + +/** 推送 body 大小上限:64KB */ +const MAX_PUSH_BODY_SIZE = 64 * 1024; +/** 最大重试次数 */ +const MAX_RETRY_COUNT = 3; +/** 僵尸恢复阈值:5分钟 */ +const ZOMBIE_RECOVERY_MINUTES = 5; + +/** + * 收集本机所有内网 IPv4 地址。 + * @return {string[]} 内网IP地址列表。 + */ +function getLocalInternalIps() { + const ips = new Set(); + const nets = networkInterfaces(); + for (const interfaces of Object.values(nets)) { + for (const iface of interfaces) { + if (iface.family === 'IPv4' && !iface.internal) { + ips.add(iface.address); + } + } + } + return Array.from(ips); +} + +/** 内网 IP 前缀集合 */ +const INTERNAL_IP_PREFIXES = [ + '127.', + '10.', + '192.168.', + '0.', +]; + +/** + * 判断给定 IP 是否属于本机内网IP。 + * @param {string} ip IP地址。 + * @return {boolean} 是否为内网IP。 + */ +function isInternalIp(ip) { + if (!ip || ip === 'localhost') return true; + + // 检查已知内网前缀 + for (const prefix of INTERNAL_IP_PREFIXES) { + if (ip.startsWith(prefix)) return true; + } + + // 检查 172.16.0.0 ~ 172.31.255.255 + const parts = ip.split('.').map(Number); + if (parts.length === 4 && parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) { + return true; + } + + // 检查本机实际内网IP + const localIps = getLocalInternalIps(); + if (localIps.includes(ip)) return true; + + return false; +} + +/** + * 校验 target_url 安全性:仅允许 https://,禁止内网IP。 + * @param {string} urlStr 目标URL。 + * @throws {Error} URL 不合法时抛出。 + */ +function validateTargetUrl(urlStr) { + if (!urlStr || typeof urlStr !== 'string') { + throw new Error('target_url 不能为空'); + } + + let parsed; + try { + parsed = new URL(urlStr); + } catch (e) { + throw new Error(`target_url 格式不合法: ${urlStr}`); + } + + if (parsed.protocol !== 'https:') { + throw new Error('target_url 仅允许 https:// 协议'); + } + + const hostname = parsed.hostname || ''; + if (isInternalIp(hostname)) { + throw new Error('target_url 不允许指向内网地址'); + } +} + +/** + * 站内信接收服务。 + * 统一处理消息入站:幂等去重、写库、异步推送、指数退避重试、僵尸恢复。 + */ +class InboxReceiverService extends Service { + /** + * 获取支持的目标渠道集合。 + * @return {Set} 支持的目标渠道。 + */ + static get SUPPORTED_CHANNELS() { + return new Set([ + 'webhook', + 'wecom', + 'dingtalk', + 'feishu', + 'warehouse_api', + ]); + } + + /** + * 初始化时执行僵尸恢复。 + * @param {Object} ctx Egg.js 上下文。 + */ + constructor(ctx) { + super(ctx); + // 异步执行僵尸恢复,不阻塞服务启动 + setImmediate(() => { + this.recoverZombieMessages().catch(err => { + ctx.logger.error(`[inbox] 僵尸恢复失败: ${err.message}`); + }); + }); + } + + /** + * 统一接收入口:幂等去重、写库、异步推送。 + * @param {Object} data 消息数据。 + * @param {string} data.ext_id 外部唯一消息主键。 + * @param {number} data.warehouse_id 所属仓库ID(服务端上下文注入,禁止外部传入)。 + * @param {number} [data.store_id] 关联货主ID。 + * @param {string} [data.direction='inbound'] 消息方向。 + * @param {number} [data.parent_id] 关联消息ID(回信时指向原消息)。 + * @param {string} data.source_type 来源类型:im / api / system。 + * @param {string} [data.source_extra] 来源附加信息。 + * @param {string} data.target_type 目标类型:im / api / webhook。 + * @param {string} data.target_channel 目标渠道。 + * @param {string} data.target_url 推送目标URL。 + * @param {string} [data.ref_code] 引用编码。 + * @param {Object} [data.ext_data] 透传数据。 + * @param {Object} [data.flags] 处理标记。 + * @return {Promise<{ok: boolean, id: number, ext_id: string}>} 接收结果。 + */ + async receive(data = {}) { + const { ctx } = this; + const { InboxMessage } = ctx.model; + + // 安全边界:校验 ext_id 不能为空 + const extId = String(data.ext_id || '').trim(); + if (!extId) { + throw new Error('ext_id 不能为空'); + } + + // 安全边界:warehouse_id 必须由服务端上下文提供 + const warehouseId = Number(data.warehouse_id); + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + throw new Error('warehouse_id 无效'); + } + + // 校验 target_channel 是否存在 + const targetChannel = String(data.target_channel || '').trim(); + if (!targetChannel || !InboxReceiverService.SUPPORTED_CHANNELS.has(targetChannel)) { + throw new Error(`不支持的目标渠道: ${targetChannel},支持的渠道: ${Array.from(InboxReceiverService.SUPPORTED_CHANNELS).join(', ')}`); + } + + // 安全边界:校验 target_url + validateTargetUrl(data.target_url); + + // 幂等检查:ext_id 已存在则直接返回 + const exist = await InboxMessage.findOne({ + where: { ext_id: extId }, + attributes: [ 'id', 'ext_id', 'push_status' ], + paranoid: false, + }); + + if (exist) { + ctx.logger.info(`[inbox] 消息已存在,跳过入库 ext_id=${extId} id=${exist.id}`); + return { + ok: true, + id: exist.id, + ext_id: extId, + }; + } + + // 推送 body 大小限制(序列化后检查) + const pushBody = { + ref_code: data.ref_code || null, + ext_data: data.ext_data || null, + }; + const bodySize = Buffer.byteLength(JSON.stringify(pushBody), 'utf8'); + if (bodySize > MAX_PUSH_BODY_SIZE) { + throw new Error(`推送 body 超过 64KB 限制(当前 ${Math.round(bodySize / 1024)}KB)`); + } + + // 写库 + const record = await InboxMessage.create({ + ext_id: extId, + warehouse_id: warehouseId, + store_id: data.store_id || null, + direction: data.direction || 'inbound', + parent_id: data.parent_id || null, + source_type: data.source_type || 'api', + source_extra: data.source_extra || null, + target_type: data.target_type, + target_channel: targetChannel, + target_url: data.target_url, + ref_code: data.ref_code || null, + ext_data: data.ext_data || null, + flags: data.flags || {}, + push_status: 0, + }); + + ctx.logger.info(`[inbox] 消息入库成功 ext_id=${extId} id=${record.id}`); + + // 异步后台推送(不阻塞响应) + setImmediate(() => { + this.asyncPush(record).catch(err => { + ctx.logger.error(`[inbox] setImmediate 异步推送异常 ext_id=${extId}: ${err.message}`); + // 异常已由 asyncPush 内部 try/catch,这里作为兜底 + try { + InboxMessage.update( + { + push_status: 3, + push_response: { error: `setImmediate 异常: ${err.message}` }, + pushed_at: new Date(), + }, + { where: { id: record.id, push_status: { [this.ctx.app.Sequelize.Op.in]: [ 0, 1 ] } } } + ); + } catch (updateErr) { + ctx.logger.error(`[inbox] 兜底更新推送状态失败 ext_id=${extId}: ${updateErr.message}`); + } + }); + }); + + return { + ok: true, + id: record.id, + ext_id: extId, + }; + } + + /** + * 异步推送 + 指数退避重试。 + * @param {Object} record 消息记录(Sequelize Model 实例)。 + * @param {number} [attempt=0] 当前重试次数。 + * @return {Promise} 推送结果。 + */ + async asyncPush(record, attempt = 0) { + const { ctx } = this; + const { InboxMessage } = ctx.model; + const { Op } = ctx.app.Sequelize; + + try { + // 乐观锁:仅 push_status=0 或(重试时 push_status=3)时可取走 + const allowedStatuses = attempt === 0 ? [ 0 ] : [ 3 ]; + const [ updatedCount ] = await InboxMessage.update( + { + push_status: 1, + push_started_at: new Date(), + }, + { + where: { + id: record.id, + push_status: { [Op.in]: allowedStatuses }, + }, + } + ); + + if (updatedCount === 0) { + ctx.logger.info(`[inbox] 消息已被其他进程取走,跳过推送 ext_id=${record.ext_id} id=${record.id}`); + return; + } + + // 获取 dispatch 服务 + const channel = record.target_channel; + if (!InboxReceiverService.SUPPORTED_CHANNELS.has(channel)) { + throw new Error(`不支持的目标渠道: ${channel}`); + } + + // 统一渠道映射:warehouse_api → webhook + const dispatchChannel = channel === 'warehouse_api' ? 'webhook' : channel; + const dispatchService = ctx.service.inbox.dispatch[dispatchChannel]; + + if (!dispatchService || typeof dispatchService.push !== 'function') { + throw new Error(`dispatch 渠道 ${dispatchChannel} 未实现`); + } + + // 执行推送 + const response = await dispatchService.push(record); + + // 推送成功 + await InboxMessage.update( + { + push_status: 2, + push_response: { + http_status: response.status, + body: response.data, + }, + pushed_at: new Date(), + }, + { where: { id: record.id, push_status: 1 } } + ); + + ctx.logger.info(`[inbox] 推送成功 ext_id=${record.ext_id} channel=${channel}`); + } catch (error) { + const next = attempt + 1; + ctx.logger.warn(`[inbox] 推送失败 ext_id=${record.ext_id} attempt=${next} error=${error.message}`); + + // 更新失败状态 + await InboxMessage.update( + { + push_status: next >= MAX_RETRY_COUNT ? 3 : 3, + retry_count: next, + push_response: { error: error.message }, + ...(next >= MAX_RETRY_COUNT ? { pushed_at: new Date() } : {}), + }, + { where: { id: record.id, push_status: 1 } } + ); + + // 指数退避重试:30s → 60s → 120s + if (next < MAX_RETRY_COUNT) { + const delay = 30000 * Math.pow(2, attempt); + ctx.logger.info(`[inbox] 将在 ${delay / 1000}s 后重试 ext_id=${record.ext_id} attempt=${next}`); + setTimeout(() => { + this.asyncPush(record, next).catch(err => { + ctx.logger.error(`[inbox] 重试推送异常 ext_id=${record.ext_id}: ${err.message}`); + }); + }, delay); + } else { + ctx.logger.error(`[inbox] 推送达到最大重试次数,标记为终态失败 ext_id=${record.ext_id}`); + } + } + } + + /** + * 僵尸恢复:重置卡在"推送中"超过5分钟的消息为"待推送"。 + * 在服务启动时及定时任务中调用。 + * @return {Promise} 恢复的消息数量。 + */ + async recoverZombieMessages() { + const { ctx } = this; + const { InboxMessage } = ctx.model; + const { Op } = ctx.app.Sequelize; + + const threshold = new Date(Date.now() - ZOMBIE_RECOVERY_MINUTES * 60 * 1000); + + const [ updatedCount ] = await InboxMessage.update( + { + push_status: 0, + push_started_at: null, + }, + { + where: { + push_status: 1, + push_started_at: { + [Op.lt]: threshold, + }, + }, + } + ); + + if (updatedCount > 0) { + ctx.logger.info(`[inbox] 僵尸恢复完成,重置 ${updatedCount} 条消息为待推送`); + } + + return updatedCount; + } +} + +module.exports = InboxReceiverService; diff --git a/app/service/warehouseMethods/inbox.js b/app/service/warehouseMethods/inbox.js new file mode 100644 index 0000000..847f579 --- /dev/null +++ b/app/service/warehouseMethods/inbox.js @@ -0,0 +1,64 @@ +'use strict'; + +const MainService = require('../main'); + +/** + * 仓库开放 API — 站内信模块处理器。 + * 接收仓库级外部适配器推送的 inbox.push 请求, + * 统一委托 app/service/inbox/receiver.receive 处理写库与异步推送。 + */ +class WarehouseInboxService extends MainService { + /** + * 仓库 API 消息入站入口。 + * warehouse_id 从验签后上下文注入,禁止外部传入。 + * @param {Object} options 请求参数。 + * @param {Object} options.body 请求体。 + * @return {Promise} 入站结果。 + */ + async push({ body = {} } = {}) { + const { ctx } = this; + const { warehouseId, appKey } = this.getInfo(); + + // 安全边界:warehouse_id 一律从验签后上下文获取 + if (!warehouseId) { + throw new Error('缺少仓库信息'); + } + + // 安全边界:校验必填参数 + if (!body.requestId || !String(body.requestId).trim()) { + throw new Error('requestId 不能为空'); + } + + if (!body.targetChannel || !String(body.targetChannel).trim()) { + throw new Error('targetChannel 不能为空'); + } + + if (!body.targetUrl || !String(body.targetUrl).trim()) { + throw new Error('targetUrl 不能为空'); + } + + // 构造 ext_id + const extId = `api:${String(appKey || 'unknown')}:${String(body.requestId).trim()}`; + + // 构造入站数据并委托给 inbox receiver + const result = await ctx.service.inbox.receiver.receive({ + ext_id: extId, + warehouse_id: warehouseId, + store_id: body.storeId || null, + direction: 'inbound', + parent_id: body.parentId || null, + source_type: body.sourceType || 'api', + source_extra: String(appKey || ''), + target_type: body.targetType || 'im', + target_channel: body.targetChannel, + target_url: body.targetUrl, + ref_code: body.refCode || null, + ext_data: body.extData || null, + flags: body.flags || {}, + }); + + return result; + } +} + +module.exports = WarehouseInboxService; diff --git a/database/designs/inbox-message-module-design.md b/database/designs/inbox-message-module-design.md new file mode 100644 index 0000000..14e4651 --- /dev/null +++ b/database/designs/inbox-message-module-design.md @@ -0,0 +1,441 @@ +# 站内信(Inbox)模块设计方案 + +> **状态**: 📋 设计中 +> **设计日期**: 2026-08-03 +> **设计人**: wms-test-agent +> **模块**: `app/service/inbox/`,独立文件模块 +> **表**: 1 张 — `wms_inbox_message` + +--- + +## 一、概念 + +消息推送状态追踪表。不重复存储消息内容(消息体由 IM 回调 / API 请求各自管理),只记录**谁发来的、要推到哪、推送状态**。收件(inbound)和回信(outbound)共表,`direction` + `parent_id` 形成对话链。 + +``` + inbound(外部 → WMS) outbound(WMS → 外部) + ┌──────────────────────┐ ┌──────────────────────┐ + │ IM 回调 / API push │ │ 系统回信 / 工单通知 │ + └──────────┬───────────┘ └──────────┬───────────┘ + │ │ + ▼ ▼ + ┌─────────────────────────────────────────┐ + │ wms_inbox_message(同一张表) │ + │ │ + │ direction: inbound │ outbound │ + │ parent_id: NULL │ parent_id: 原消息ID │ + │ │ + │ "IM msg_001 → API app_10 → success" │ + │ "WMS 回复 → 企微 Bot → success" │ + └─────────────────────────────────────────┘ + │ + ▼ setImmediate async push + dispatch → HTTP POST / Bot API +``` + +--- + +## 二、数据库表 + +### `wms_inbox_message` + +| 字段 | 类型 | 必填 | 默认值 | 说明 | +|------|------|------|--------|------| +| `id` | `BIGINT UNSIGNED` | ✅ | AUTO | 主键 | +| `ext_id` | `VARCHAR(128)` | ✅ | — | **外部唯一消息主键**(IM msgId / API requestId 等),唯一索引,幂等去重 | +| `warehouse_id` | `BIGINT UNSIGNED` | ✅ | — | 所属仓库 | +| `store_id` | `BIGINT UNSIGNED` | — | NULL | 关联货主 | +| `direction` | `VARCHAR(10)` | ✅ | `inbound` | `inbound`=外部→WMS 收件 / `outbound`=WMS→外部 回信 | +| `parent_id` | `BIGINT UNSIGNED` | — | NULL | 关联消息 ID(回信时指向原消息,形成对话链) | + +#### 来源 / 目标 + +| 字段 | 类型 | 必填 | 说明 | +|------|------|------|------| +| `source_type` | `VARCHAR(20)` | ✅ | `im` / `api` | +| `source_extra` | `VARCHAR(100)` | — | 附加信息(IM 平台 / API app_id) | +| `target_type` | `VARCHAR(20)` | ✅ | `im` / `api` | +| `target_channel` | `VARCHAR(50)` | ✅ | 目标渠道:`wecom` / `dingtalk` / `feishu` / `warehouse_api` / `webhook` | +| `target_url` | `VARCHAR(500)` | ✅ | 推送目标 URL(IM Bot webhook 地址 / API 回调地址) | + +> **安全设计**: +> - `target_url` 不含 secret。IM Bot URL 中 token 已内嵌,API 推送时 secret 从 `ApiApp.self_app_secret` 查。 +> - **出站签名**:推送到仓库开放 API 时,使用与该仓库 ApiApp 相同的 MD5 签名算法(`canonicalQuery + self_app_secret + bodySign`),接收方用同一 `app_key` 验证。IM 通道则使用各自 Bot 的原生鉴权。 + +> **inbound vs outbound 的 source/target 语义**: +> ``` +> inbound(外部→WMS):source=外部来源 target=WMS 内部要转发到的渠道 +> outbound(WMS→外部):source=WMS 内部 target=要推送到的外部渠道 +> ``` +| `ref_code` | `VARCHAR(100)` | — | 外部引用编码,推送/回执时原样携带 | +| `ext_data` | `JSON` | — | **外部透传数据**,外部传入任意 JSON,WMS 不解析,回信时原样返回 | +| `flags` | `JSON` | — | **处理标记**,外部传入控制 WMS 处理行为,见下表 | + +> **`flags` 支持的标记**: +> ```json +> { +> "skip_ai_parse": true, // 跳过智能解析(内部员工发信时设为 true) +> "skip_auto_reply": true, // 跳过自动回复 +> "skip_forward": true // 仅存档,不转发 +> } +> ``` +> 外部不传 → 默认全部开启(智能解析 + 自动回复 + 转发)。内部系统调用 `inbox.push` 时按需关闭特定行为。 + +#### 推送状态 + +| 字段 | 类型 | 必填 | 默认值 | 说明 | +|------|------|------|--------|------| +| `push_status` | `TINYINT(4)` | ✅ | 0 | 0=待推送 1=推送中 2=已送达 3=失败 | +| `push_started_at` | `DATETIME` | — | NULL | 开始推送时间(僵尸检测:超 5 分钟仍为 1 → 重置为 0) | +| `retry_count` | `INT(11)` | ✅ | 0 | 已重试次数 | +| `push_response` | `JSON` | — | NULL | 目标响应(http_status, body, error) | +| `pushed_at` | `DATETIME` | — | NULL | 推送完成时间 | + +> **防重机制**:`push_status` 字段本身即状态流转,不需要额外流转表。使用乐观锁 `UPDATE SET push_status=1 WHERE push_status=0` 保证单条消息不会被重复取走。`push_started_at` 用于进程崩溃后的僵尸恢复。 + +#### 关联(后续) + +| 字段 | 类型 | 必填 | 说明 | +|------|------|------|------| +| `work_order_id` | `BIGINT UNSIGNED` | — | 🔮 关联工单 | +| `work_order_no` | `VARCHAR(50)` | — | 🔮 工单号 | + +#### 时间 + +| 字段 | 类型 | 必填 | 默认值 | 说明 | +|------|------|------|--------|------| +| `created_at` | `DATETIME` | ✅ | CURRENT_TIMESTAMP | | +| `updated_at` | `DATETIME` | ✅ | CURRENT_TIMESTAMP ON UPDATE | | +| `deleted_at` | `DATETIME` | — | NULL | 软删除 | + +### 索引 + +| 索引名 | 字段 | 用途 | +|--------|------|------| +| `PRIMARY` | `id` | — | +| `uk_ext_id` | `ext_id` UNIQUE | 外部幂等去重 | +| `idx_warehouse_status` | `warehouse_id, push_status` | 按仓库+状态查询 | +| `idx_warehouse_direction` | `warehouse_id, direction, created_at` | 收件/回信列表 | +| `idx_parent` | `parent_id` | 对话链查询 | +| `idx_created_at` | `created_at` | 时间范围 | + +> **`ext_id` 唯一键防碰撞**:不同来源的消息 ID 可能重复(IM msgId 与 API requestId 撞车)。入库时按来源加前缀: +> ``` +> IM 消息: ext_id = `im:wecom:${msg.msgId}` +> API 消息: ext_id = `api:${apiAppId}:${body.requestId}` +> 系统回信: ext_id = `sys:${uuid}` +> ``` +> 前缀保证不同来源的消息不会因 ID 相同而误判为重复。 + +> **容量规划**:`BIGINT UNSIGNED` 主键容量无限。单表 InnoDB 建议 ≤ 5000 万行。以 100 仓 × 日均 5000 条 = 日 50 万条计,达到上限需 ~100 天。届时加 `PARTITION BY HASH(warehouse_id) PARTITIONS 16` 即可水平扩展,无需分库分表,代码零改动。 + +### 安全边界(强制) + +| 边界 | 规则 | +|------|------| +| **warehouse_id 归属** | 禁止外部传入。IM 路径从回调解析获取,API 路径从验签后 `ctx.warehouseId` 获取 | +| **ext_id 前缀** | `im:{platform}:{msgId}` / `api:{appId}:{requestId}` / `sys:{uuid}`,receiver 入站时统一格式 | +| **target_url SSRF** | 仅允许 `https://`,禁止内网 IP(127.0.0.1/10.x/172.16-31.x/192.168.x) | +| **dispatch 超时** | HTTP 请求超时 10s,超时视为失败进入重试 | +| **setImmediate 异常** | `try/catch` 包裹,异常写入 `push_response.error`,`push_status=3` | +| **target_channel 校验** | `dispatch[channel]` 不存在时返回明确错误,不静默丢弃 | +| **僵尸恢复** | 启动时 + 每 5 分钟定时执行 `UPDATE push_status=0 WHERE push_status=1 AND push_started_at < NOW()-5MIN` | +| **推送 body 大小** | 限制 64KB,超限拒绝写入 | + +--- + +## 三、推送流程 + +``` +receiver.receive() + │ + ├─ 1. 幂等检查(ext_id 已存在 → 直接返回) + ├─ 2. INSERT(push_status=0) + └─ 3. setImmediate(() => asyncPush(record)) + │ + ├─ UPDATE push_status=1(推送中) + ├─ dispatch(target_channel, target_url) + │ ├─ 成功 → UPDATE push_status=2, pushed_at=NOW() + │ └─ 失败 → retry_count++ + │ ├─ < 3 次 → setTimeout(delay, asyncPush) 指数退避重试 + │ └─ ≥ 3 次 → UPDATE push_status=3(终态) + └─ 返回 +``` + +**指数退避**:30s → 60s → 120s,最多重试 3 次。 + +**关键**:不依赖定时任务轮询,利用 Node.js 事件循环的 `setImmediate` + `setTimeout` 在同一个进程内异步完成推送与重试。 + +--- + +## 四、两个接收入口 + +### IM 消息入站 + +``` +企微/钉钉/飞书 Bot 回调 → receiver.receive({ + // warehouse_id 由 IM 回调解析 / 签名验证后从上下文获取,不外部传入 + source_type: 'im', + ext_id: `im:wecom:${msg.msgId}`, + source_extra: 'wecom', + + target_type: 'api', + target_channel: 'warehouse_api', + target_url: 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxx', + ref_code: msg.userId, + ext_data: { conversation_id: msg.conversationId }, + flags: {}, + + warehouse_id: ctx.warehouseId, // ← 来自鉴权上下文,非外部传入 +}) +``` + +### 仓库 API 消息入站 + +``` +POST /warehouse?method=inbox.push → receiver.receive({ + // warehouse_id 由仓库 API 验签后从 ApiApp 解析,不外部传入 + source_type: 'api', + ext_id: `api:${ctx.apiAppId}:${body.requestId}`, + source_extra: String(ctx.apiAppId), + + target_type: 'im', + target_channel: body.targetChannel || 'wecom', + target_url: body.targetUrl, + ref_code: body.refCode, + ext_data: body.extData, + flags: body.flags || {}, + + warehouse_id: ctx.warehouseId, // ← 来自鉴权上下文,非外部传入 +}) +``` + +### 系统回信(outbound) + +``` +WMS 内部(工单通知/状态更新)→ receiver.reply({ + parent_id: 1, // 原消息 ID + target_type: 'im', + target_channel: 'wecom', + target_url: 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxx', + ref_code: 'TICKET-001', + ext_data: { ... }, // 继承原消息 ext_data + + warehouse_id: ctx.warehouseId, // ← WMS 内部上下文 +}) +// 自动写入 direction=outbound, parent_id=1 +// 推送成功后,可通过 inbox.thread 查完整对话链 +``` + +--- + +## 五、API + +### 5.1 内部管理 (`inbox.*`) + +| method | 说明 | +|--------|------| +| `inbox.list` | 消息列表(`direction` 区分收件/回信) | +| `inbox.detail` | 消息详情(含 push_response) | +| `inbox.thread` | 对话链(原消息 + 所有回信) | +| `inbox.reply` | 系统回信(写入 outbound 记录 + 异步推送) | +| `inbox.retry` | 手动重推 | +| `inbox.stats` | 推送统计 | + +### 5.2 仓库 API (`inbox.push`) + +`POST /warehouse?method=inbox.push` + +| 参数 | 类型 | 必填 | 说明 | +|------|------|------|------| +| `body.sourceType` | `string` | ✅ | 来源类型:`im` / `api` | +| `body.sourceChannel` | `string` | — | 来源渠道(IM 平台 / API 标识) | +| `body.requestId` | `string` | ✅ | 来源请求 ID(组成 ext_id) | +| `body.targetChannel` | `string` | ✅ | 目标渠道 | +| `body.targetUrl` | `string` | ✅ | 推送目标 URL | +| `body.refCode` | `string` | — | 引用编码 | +| `body.extData` | `object` | — | 透传数据 | +| `body.flags` | `object` | — | 处理标记 `{ skip_ai_parse, skip_auto_reply, skip_forward }` | +| `body.storeId` | `number` | — | 关联货主 | + +--- + +## 六、异步推送实现 + +不启动独立 consumer,利用 Egg.js / Node.js 原生异步能力: + +```javascript +// receiver.js +async receive(data) { + // 1. 幂等检查 + const exist = await this.ctx.model.InboxMessage.findOne({ + where: { ext_id: data.ext_id }, + }); + if (exist) return { ok: true, id: exist.id, ext_id: data.ext_id }; + + // 2. 写入记录 + const record = await this.ctx.model.InboxMessage.create({ + ext_id: data.ext_id, + warehouse_id: data.warehouse_id, + source_type: data.source_type, + source_extra: data.source_extra, + target_type: data.target_type, + target_channel: data.target_channel, + target_url: data.target_url, + ref_code: data.ref_code, + ext_data: data.ext_data, + flags: data.flags || {}, + push_status: 0, + }); + + // 3. 异步后台推送(不阻塞响应) + setImmediate(() => this.asyncPush(record)); + + return { ok: true, id: record.id, ext_id: data.ext_id }; +} + +async asyncPush(record, attempt = 0) { + // 乐观锁:仅 push_status=0 时可取走,防重 + const [ updated ] = await InboxMessage.update( + { push_status: 1, push_started_at: new Date() }, + { where: { id: record.id, push_status: attempt === 0 ? 0 : 3 } } + ); + if (!updated) return; // 已被其他进程取走 + + try { + // API 渠道:用仓库 ApiApp 生成 MD5 签名,接收方同密钥验证 + const payload = { ref_code: record.ref_code, ext_data: record.ext_data }; + const signedUrl = record.target_type === 'api' + ? await this.signRequest(record, payload) + : record.target_url; + + const res = await this.ctx.service.inbox.dispatch[record.target_channel].push( + signedUrl, payload + ); + await record.update({ + push_status: 2, + push_response: { http_status: res.status, body: res.data }, + pushed_at: new Date(), + }); + } catch (err) { + const next = attempt + 1; + await record.update({ push_status: 3, retry_count: next, push_response: { error: err.message } }); + + if (next < 3) { + const delay = 30000 * Math.pow(2, attempt); // 30s → 60s → 120s + setTimeout(() => this.asyncPush(record, next), delay); + } + } +} +``` + +**不需要**:定时任务、消息队列、独立 worker 进程。 + +> **僵尸恢复**:进程崩溃导致 `push_status=1` 的记录卡死时,启动时执行 `UPDATE SET push_status=0 WHERE push_status=1 AND push_started_at < NOW() - INTERVAL 5 MINUTE` 即可复活。 + +> **出站签名**:推送到 `target_type=api` 时,使用仓库 ApiApp 的 `self_app_secret` 生成 MD5 签名附加到 URL query: +> ``` +> signedUrl = target_url +> + '?app_key=' + apiApp.self_app_key +> + '×tamp=' + now +> + '&sign=' + md5(queryString + self_app_secret + md5(body)) +> ``` +> 接收方(仓库开放侧)可用同一 `app_key` 调用 `apiSignLib.verifyRequestSign()` 验证。IM 通道(wecom/dingtalk/feishu)使用各自 Bot 原生鉴权,不走此签名。 + +--- + +## 七、模块结构 + +**分层原则**:API 入口只做校验与签名,统一委托 `app/service/inbox/` 处理写库与推送逻辑。`methods/` 仅放接口定义,不放业务代码。 + +``` +入口层(校验 + 签名) 统一处理层(写库 + 推送) 数据层 +────────────────────────── ────────────────────────── ────── +app/controller/ app/service/inbox/ app/model/ + im.js ─────────────┐ ┌─ receiver.js inbox_message.js + warehouse.js ──────┤ │ 统一接收(幂等去重) ↑ + ├──调用──→ │ 写库(INSERT) │ + app/service/im.js ─┘ │ 异步推送(setImmediate) │ + │ │ 重试(setTimeout 指数退避) │ + │ │ │ + │ ├─ index.js │ + │ │ 列表/详情/重推/统计 │ + │ │ │ + │ └─ dispatch/ │ + │ base.js ← 统一出站:查 ApiApp、取密钥、签名、发 HTTP │ + │ webhook.js ← 继承 base,HTTP POST │ + │ wecom.js ← 继承 base,企微 Bot │ + │ dingtalk.js ← 继承 base,钉钉 Bot │ + │ feishu.js ← 继承 base,飞书 Bot │ + │ │ +methods/ (仅接口定义,不放逻辑) │ + warehouse.json ← inbox.push 参数声明 │ + system.json ← inbox.* 参数声明 │ +``` + +> **关键**:`app/service/inbox/` 是独立的统一处理目录,所有写库、推送、重试逻辑集中在此。后续新增渠道只需在 `dispatch/` 下加一个文件,不影响其他层。 + +### 统一出站基类 `dispatch/base.js` + +所有渠道 dispatch 继承此基类,统一处理查密钥、签名、发 HTTP: + +```javascript +// dispatch/base.js +class OutboundBase { + constructor(ctx) { this.ctx = ctx; } + + // 获取仓库 ApiApp 密钥(IM 渠道无需签名,返回 null) + async getApiApp(warehouseId) { + return await this.ctx.service.systems.apiSign.getApiAppConfigByAppKey( + /* appKey from warehouse */, WAREHOUSE_INTERFACE_TYPE_ID + ); + } + + // 生成 MD5 签名(复用 apiSignLib) + signRequest(url, body, secret) { + const query = { app_key: secret.appKey, timestamp: Math.floor(Date.now() / 1000) }; + const { sign } = apiSignLib.signRequest({ query, body, selfAppSecret: secret.selfAppSecret }); + return `${url}?app_key=${query.app_key}×tamp=${query.timestamp}&sign=${sign}`; + } + + // 统一发送(子类可覆盖签名逻辑) + async post(url, body) { /* axios/post */ } + + // 子类必须实现 + async push(record) { throw new Error('子类实现'); } +} +``` + +> **调用链**:`receiver.asyncPush()` → `dispatch[channel].push(record)` → 基类 `signRequest()` + `post()` → 外部。各渠道只关注消息格式转换,签名和 HTTP 由基类统一处理。 + +### 与现有系统集成 + +``` +app/controller/im.js(已有) + → IM 回调签名校验后 → ctx.service.inbox.receiver.receive({ source_type: 'im', ... }) + +app/controller/warehouse.js(已有) + → method=inbox.push → ctx.service.inbox.receiver.receive({ source_type: 'api', ... }) + +methods/warehouse.json(修改) + → 新增 inbox.push 方法定义,注册到 warehouse 开放接口方法列表 +``` + +--- + +## 八、文件变更清单 + +| 文件 | 操作 | +|------|------| +| `database/migrations/{ts}-create-inbox-message.js` | 新增 DDL | +| `app/model/inbox_message.js` | 新增 | +| `app/service/inbox/index.js` | 新增 | +| `app/service/inbox/receiver.js` | 新增(统一接收 + 写库 + 异步推送入口) | +| `app/service/inbox/dispatch/base.js` | 新增(统一出站:查密钥 + 签名 + HTTP) | +| `app/service/inbox/dispatch/webhook.js` | 新增(HTTP POST 推送) | +| `app/service/inbox/dispatch/wecom.js` | 新增(企微 Bot) | +| `app/service/inbox/dispatch/dingtalk.js` | 新增(钉钉 Bot) | +| `app/service/inbox/dispatch/feishu.js` | 新增(飞书 Bot) | +| `app/controller/inbox.js` | 新增 | +| `methods/warehouse.json` | 新增 `inbox.push` | +| `methods/system.json` | 新增 `inbox.*` | diff --git a/database/migrations/20260803120000-create-inbox-message.js b/database/migrations/20260803120000-create-inbox-message.js new file mode 100644 index 0000000..d31b668 --- /dev/null +++ b/database/migrations/20260803120000-create-inbox-message.js @@ -0,0 +1,182 @@ +'use strict'; + +const TABLE_NAME = 'wms_inbox_message'; + +module.exports = { + /** + * 创建站内信消息表。 + * @param {Object} queryInterface Sequelize QueryInterface 实例。 + * @param {Object} Sequelize Sequelize 类。 + * @return {Promise} 迁移执行结果。 + */ + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME); + if (exists) return; + + await queryInterface.createTable(TABLE_NAME, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + ext_id: { + type: Sequelize.STRING(128), + allowNull: false, + comment: '外部唯一消息主键(IM msgId / API requestId 等),用于幂等去重', + }, + warehouse_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '所属仓库ID', + }, + store_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '关联货主ID', + }, + direction: { + type: Sequelize.STRING(10), + allowNull: false, + defaultValue: 'inbound', + comment: '消息方向:inbound=外部→WMS收件 / outbound=WMS→外部回信', + }, + parent_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '关联消息ID(回信时指向原消息,形成对话链)', + }, + source_type: { + type: Sequelize.STRING(20), + allowNull: false, + comment: '来源类型:im / api', + }, + source_extra: { + type: Sequelize.STRING(100), + allowNull: true, + comment: '来源附加信息(IM 平台 / API app_id)', + }, + target_type: { + type: Sequelize.STRING(20), + allowNull: false, + comment: '目标类型:im / api', + }, + target_channel: { + type: Sequelize.STRING(50), + allowNull: false, + comment: '目标渠道:wecom / dingtalk / feishu / warehouse_api / webhook', + }, + target_url: { + type: Sequelize.STRING(500), + allowNull: false, + comment: '推送目标URL(IM Bot webhook 地址 / API 回调地址)', + }, + ref_code: { + type: Sequelize.STRING(100), + allowNull: true, + comment: '外部引用编码,推送/回执时原样携带', + }, + ext_data: { + type: Sequelize.JSON, + allowNull: true, + comment: '外部透传数据,外部传入任意JSON,WMS不解析,回信时原样返回', + }, + flags: { + type: Sequelize.JSON, + allowNull: true, + comment: '处理标记,外部传入控制WMS处理行为', + }, + push_status: { + type: Sequelize.TINYINT(4), + allowNull: false, + defaultValue: 0, + comment: '推送状态:0=待推送 1=推送中 2=已送达 3=失败', + }, + push_started_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '开始推送时间(僵尸检测:超5分钟仍为1则重置为0)', + }, + retry_count: { + type: Sequelize.INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '已重试次数', + }, + push_response: { + type: Sequelize.JSON, + allowNull: true, + comment: '目标响应(http_status, body, error)', + }, + pushed_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '推送完成时间', + }, + work_order_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '关联工单ID(预留)', + }, + work_order_no: { + type: Sequelize.STRING(50), + allowNull: true, + comment: '工单号(预留)', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '软删除时间', + }, + }); + + // 唯一索引 — 外部幂等去重 + await queryInterface.addIndex(TABLE_NAME, [ 'ext_id' ], { + unique: true, + name: 'uk_ext_id', + }); + + // 仓库+状态查询 + await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'push_status' ], { + name: 'idx_warehouse_status', + }); + + // 仓库+方向+时间 + await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'direction', 'created_at' ], { + name: 'idx_warehouse_direction', + }); + + // 对话链查询 + await queryInterface.addIndex(TABLE_NAME, [ 'parent_id' ], { + name: 'idx_parent', + }); + + // 时间范围查询 + await queryInterface.addIndex(TABLE_NAME, [ 'created_at' ], { + name: 'idx_created_at', + }); + }, + + /** + * 回滚站内信消息表。 + * @param {Object} queryInterface Sequelize QueryInterface 实例。 + * @return {Promise} 迁移回滚结果。 + */ + down: async queryInterface => { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/methods/changes/system.json b/methods/changes/system.json index e2f76a4..8539d6e 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,5111 +1,5137 @@ [ - { - "version": "2026.08.01-system-01", - "date": "2026-08-01", - "type": "added", - "summary": "新增 apiApp 仓库 API 应用管理模块,支持当前仓库维度的 API 应用 CRUD、AppKey/Secret 自动生成与重新生成、IP 白名单、回调地址、限流等配置", - "methods": [ - "apiApp.list", - "apiApp.detail", - "apiApp.create", - "apiApp.update", - "apiApp.delete", - "apiApp.regenerateSecret" - ], - "notes": [ - "apiApp.list:分页查询当前仓库 API 应用列表,支持按 app_name(模糊)、is_enabled 筛选,Secret 自动脱敏(前8位+****)。", - "apiApp.detail:按 ID 查询单个应用详情,需同时匹配 warehouse_id(自动注入 ctx.user.store_id),Secret 脱敏。", - "apiApp.create:创建应用时自动生成 AppKey(AK{yyyyMMddHHmmss}{random8hex})和 AppSecret(64位hex)。默认 interface_type_id 取 WH_CHANNEL。仅创建时返回完整 Secret。", - "apiApp.update:更新可编辑字段(app_name、self_ip_whitelist、callback_url、rate_limit、sign_method、is_enabled),不可变字段为 self_app_key 和 interface_type_id。", - "apiApp.delete:软删除(is_enabled=0),不物理删除。", - "apiApp.regenerateSecret:重新生成 64位hex AppSecret,旧 Secret 立即失效。仅此次返回完整 Secret。", - "仓库隔离:所有操作按 ctx.user.store_id → warehouse_id 自动过滤。", - "Secret 安全策略:list/detail/update 返回脱敏值,仅 create/regenerateSecret 返回完整 Secret。" - ], - "module": "apiApp" - }, - { - "version": "2026.07.31-system-02", - "date": "2026-07-31", - "type": "added", - "summary": "新增 storage.inventory.export 库存导出与 storage.inventory.exportTaskProgress 导出进度查询,入参复用 list 的 where/sort/group_by_batch 语义,支持两种导出模式(聚合汇总 / 逐条明细),库位信息一并导出", - "methods": [ - "storage.inventory.export", - "storage.inventory.exportTaskProgress" - ], - "notes": [ - "storage.inventory.export:异步提交导出任务,返回 task_id 与受理信息,后端异步生成 Excel 并上传。入参 where/sort/group_by_batch 与 storage.inventory.list 完全一致,无需额外学习成本。", - "group_by_batch=false(默认):按 stock_id + space_id(库位)聚合导出库存汇总,含商品编码/名称/规格/单位/货主/库位编码/名称/总库存/锁定/可用/批次数/最近入库时间。", - "group_by_batch=true:按 storage_id 逐条导出库存明细,含库存记录ID/商品信息/库位信息/批次号/库存类型/数量/生产日期/过期日期/入库时间/入库单号/供应商批次号。", - "新增 storage.inventory.exportTaskProgress:按 task_id/taskId 查询导出任务进度与状态(submitted/running/success/failed/not_found),status=success 时返回 download_url 供客户端下载。", - "导出文件目录:exports/storage/inventory/{warehouseId}/,缓存 TTL 1800 秒。" - ], - "module": "storage.inventory" - }, - { - "version": "2026.07.31-system-01", - "date": "2026-07-31", - "type": "added", - "summary": "新增按波次批量快捷复核接口 batchQuickRecheckByWave,支持批量波次 IDs 的前置条件检查(储位、快递、同步、拦截),自动完成拣货并标记复核,支持部分失败", - "methods": [ - "order.recheckOrder.batchQuickRecheckByWave" - ], - "notes": [ - "新增 order.recheckOrder.batchQuickRecheckByWave 方法,复用 batchQuickRecheck 的 _completePickForOrder / _markRecheckForOrder / _tryCompleteWaveInTransaction 等内部事务方法", - "入参 wave_ids 支持数组或逗号分隔字符串,兼容 waveIds(驼峰)、wave_id(单值)", - "按波次维度批量查询订单后逐波次、逐订单执行前置校验与复核,每个订单独立事务,部分失败不影响其他订单", - "响应包含 success/failed 列表及计数,failed 项含 order_id、wave_id、delivery_order_code、reason 说明;波次下无订单时仅返回 wave_id + reason" - ], - "module": "order.recheckOrder" - }, - { - "version": "2026.07.29-system-01", - "date": "2026-07-29", - "type": "added", - "summary": "补全 waybill.warehouse group API 文档参数定义:完善 list/detail/export 的 params 与 response,新增 exportTaskProgress 异步进度查询接口", - "methods": [ - "waybill.warehouse.list", - "waybill.warehouse.detail", - "waybill.warehouse.export", - "waybill.warehouse.exportTaskProgress" - ], - "notes": [ - "waybill.warehouse.list:params 含 pagination/where/sort 完整字段定义,where 支持 15 个筛选维度(运单号、主单号、订单ID、订单号、物流编码、物流接口ID、平台编码、状态、退回/拦截/星河签收、包材ID、已称重、关键词、创建时间范围),sort 白名单 create_at/weighing_weight/id。response 含 list(28 个字段)+ pagination。", - "waybill.warehouse.detail:修正 id 参数为可选(required: false),与 waybillCode 二选一,waybillCode 优先。response 含 id/waybill_code/main_waybill_code/waybill_type/business_key/sibling_waybills/order/logistics/status_info/weight/package/print_records/print_count 等完整详情。", - "waybill.warehouse.export:response 补充 progress/message/update_time 字段,完整覆盖异步任务返回信息。", - "新增 waybill.warehouse.exportTaskProgress:按 task_id/taskId 查询导出进度,response 含 task_id/status/progress/current_count/total_count/message/result/error/download_url/update_time。", - "所有接口 isNeedAuth: false, isNeedLogin: true,仓库隔离通过 ctx.user.store_id 自动注入。" - ], - "module": "waybill.warehouse" - }, - { - "version": "2026.07.28-system-01", - "date": "2026-07-28", - "type": "added", - "summary": "新增 order.pendingOrder.batchMarkPrinted:批量设置订单为已打印状态,将 print_status 更新为 'fin'", - "methods": [ - "order.pendingOrder.batchMarkPrinted" - ], - "notes": [ - "同步批量更新接口,传入订单ID数组,直接将符合条件的订单 print_status 设为 'fin'。", - "双表查询:先查 current 表(wms_order_delivery_{warehouseId}),未命中的 ID 再兜底查 dispatch 表(wms_order_delivery_{warehouseId}_dispatch)。", - "dispatch 表查询失败仅记录 warn 日志,不影响 current 表已更新的结果。", - "仅允许 step 在 [1,2,3] 且 status 不为 'cancel' 的订单操作,已打印(print_status='fin')的订单会被静默跳过。", - "仓库上下文强制从 ctx.user.store_id 获取,禁止传入外部仓库ID。", - "入参支持 order_ids / orderIds / ids 三种别名,优先级 order_ids > orderIds > ids。", - "返回 updated_count 表示实际更新条数(current + dispatch 合计),ids 原样回传请求的订单ID列表。", - "写入操作日志 operation_code: ORDER_BATCH_MARK_PRINTED。" - ], - "module": "order.pendingOrder" - }, - { - "version": "2026.07.27-system-03", - "date": "2026-07-27", - "type": "changed", - "summary": "storage.receiving 导出接口拆分:export 改为按仓库维度,新增 storeExport 按货主维度导出", - "methods": [ - "storage.receiving.export", - "storage.receiving.exportTaskProgress", - "storage.receiving.storeExport", - "storage.receiving.storeExportTaskProgress" - ], - "notes": [ - "export 改为仓库维度:过滤条件从 store_id(平台激活货主)改为 warehouse_id(ctx.user.store_id),与 getReceivingList 保持一致。", - "exportTaskProgress 同步更新为仓库维度进度查询,任务 ID 前缀 receiving_export_。", - "新增 storeExport:货主维度导出,通过平台激活上下文获取 store_id,过滤逻辑与 getStoreReceivingList 一致。", - "新增 storeExportTaskProgress:货主维度进度查询,复用 exportTaskProgress 的缓存逻辑,任务 ID 前缀 receiving_store_export_。", - "导出格式:双 Sheet Excel(Sheet1=收货单列表 21 列,Sheet2=收货单明细 17 列),通过 ExcelJS stream + uploadService 上传 COS。", - "仓库导出上传路径 exports/receiving/{warehouseId}/,货主导出上传路径 exports/receiving/store/{storeId}/。", - "修复 exportReceivingList 中 where 条件二次解析问题:增加 ctx.whereParsed 复用(与 getStoreReceivingList 一致),避免 prepareWhereContext 已解析后再重复 parseWhereConditions 导致边界条件丢失。", - "命名对齐 entry 侧:storeExport / storeExportTaskProgress 方法名、任务 ID 前缀、上传路径均与 storage.entry.storeExport 模式一致。" - ], - "module": "storage.receiving" - }, - { - "version": "2026.07.27-system-02", - "date": "2026-07-27", - "type": "added", - "summary": "新增 order.pendingOrder.allocateSubOrderNumber:待处理订单分配子单号(异步任务),business_key 从 2 开始递增,跳过已分配运单号;新增 allocateSubOrderNumberProgress 按 task_id/business_key 查询进度", - "methods": [ - "order.pendingOrder.allocateSubOrderNumber", - "order.pendingOrder.allocateSubOrderNumberProgress" - ], - "notes": [ - "新增 allocateSubOrderNumber:入参 order_id + sub_order_count,按 business_key 2..(2+count-1) 全量传入 createWaybillCodePipeline。", - "并发安全:全量传入 pipeline,由其内部事务 + UNIQUE(order_id,business_key,status,warehouse_id) 索引保证并发去重。", - "pipeline 内部 createWaybillCode 事务:status=1 已分配→跳过;status=0 占位中→复用;无记录→INSERT status=0 占位。", - "异步任务模式:请求立即返回 task_id(sub_ 前缀),后台 setImmediate 执行,进度通过 Redis 缓存追踪。", - "新增 allocateSubOrderNumberProgress:支持 task_id 查整体进度,business_key 可选参数过滤单个业务ID的详情。", - "进度状态 submitted→running→success/partial/failed,progress 对应 5/50/80/100。", - "result.details 数组记录每个 business_key 的 status(skipped/allocated/failed/pending)与 waybill_code。", - "buildSubOrderDetails 回查最终状态:status=1+waybill→allocated,status=0→failed,无记录→failed。" - ], - "module": "order.pendingOrder" - }, - { - "version": "2026.07.27-system-01", - "date": "2026-07-27", - "type": "added", - "summary": "新增 order.packing 打包任务模块:list/get 查询 + setEndTime 设置结束时间,含视频 CDN URL 拼接与状态回写", - "methods": [ - "order.packing.list", - "order.packing.get", - "order.packing.setEndTime", - "order.packing.forceRecord" - ], - "notes": [ - "新增 order.packing.list:按仓库维度查询打包任务列表,支持分页/筛选/排序,关联工作台、视频和运单信息。", - "新增 order.packing.get:按 id + warehouse_id 查询单条打包任务详情。", - "新增 order.packing.setEndTime:设置打包任务结束时间,入参 id + end_time;若任务状态不是已完成(2)则同步更新为已完成。", - "新增 order.packing.forceRecord:强制重新录制打包任务视频,入参 id;校验录制电脑在线后重置视频状态并推送打印服务。", - "前端默认值逻辑:若任务已有 end_time 则打开时默认为当前时间,否则默认为 start_time + 5分钟。", - "视频 URL 自动拼接 CDN 域名前缀:http://w{warehouseId}-c{recordingComputerId}.o.gztbyc.com{videoPath};录制电脑从 wms_print_computer 按 is_recording=true 获取。", - "视频响应新增 status 字段(created/recording/completed/failed),与数据库 ENUM 保持一致。", - "pack_task_video Model 的 status 字段从 TINYINT 改为 STRING(20) 以匹配 DB ENUM 迁移。", - "forceRecord 通过打印服务 /record/force 推送录制任务,传入 pack_task_id、warehouse_id、computer_id、camera_ids。" - ], - "module": "order.packing" - }, - { - "version": "2026.07.10-system-01", - "date": "2026-07-10", - "type": "added", - "summary": "新增 storage.report.searchStore 货主侧库存报表,以 store_id 为主维度查询库存流水", - "methods": [ - "storage.report.searchStore", - "storage.report.exportStore" - ], - "notes": [ - "新增 searchStore 方法:与 search 共享核心逻辑,通过 searchMode='store' 切换主维度从 warehouse_id → store_id。", - "新增 exportStore 方法:与 export 共享核心逻辑,支持货主侧导出 Excel(含汇总 + 变更记录两个 sheet)。", - "systems 层 search/export 方法新增 searchMode 参数(默认 'warehouse'),不影响现有 warehouse 侧行为。", - "货主侧使用 ctx.user.store_id 作为主维度 store_id,辅助维度支持 warehouse_ids 过滤特定仓库。", - "systemMethods 层 searchStore 从 where.warehouse_ids 取值传给 search 的 storeIds(承载 warehouse 过滤)。", - "输出新增 warehouse_id / warehouse_name 字段,货主侧可区分不同仓库的库存。search 方法也同步输出这两个字段(向后兼容)。", - "修复 getStockDetails 的 warehouseId 判断:从 != null 改为 !== undefined,使显式传 null 可跳过 warehouse 过滤。", - "修复 loadReportReferenceMaps 未传递 warehouseId 给 getStockDetails 的问题。" - ], - "module": "storage.report" - }, - { - "version": "2026.07.09-system-01", - "date": "2026-07-09", - "type": "updated", - "summary": "签约 sign 方法改造:统一当前主体→store_id,解除角色校验,仓库可签仓库", - "methods": [ - "storeWarehouse.store.sign", - "storeWarehouse.warehouse.sign" - ], - "notes": [ - "resolvePairIds:统一当前主体始终在 store_id(货主方/消费方),对方在 warehouse_id(仓库方/提供方)。不再根据 isWarehouse 分支。", - "getCounterparty:移除 expectedRole 角色校验(仓库不再只能签货主,可签仓库)。", - "findScopedRelation:改为 OR 查询 store_id/warehouse_id 两边,兼容新旧签约数据。", - "sign preview:counterparty.role 改为根据对方 project 真实返回(warehouse/store),不再硬编码反推。", - "签仓库:仓库发起签约时对方 ID 传 counterparty_id,系统自动将当前仓库放 store_id。" - ], - "module": "storeWarehouse" - }, - { - "version": "2026.07.08-system-01", - "date": "2026-07-08", - "type": "updated", - "summary": "storeWarehouse.store.list 与 storeWarehouse.warehouse.list 拆分实现,不再共用;仓库侧支持查询外部合作仓库", - "methods": [ - "storeWarehouse.store.list", - "storeWarehouse.warehouse.list" - ], - "notes": [ - "拆分:store.list 调用 listForStore,warehouse.list 调用 listForWarehouse,不再共用同一个 list 方法。", - "新规则:两个方法均按 store_id = 当前主体ID 过滤(主体在 store_id 为货主方/消费方,对方在 warehouse_id 为仓库方/提供方)。", - "warehouse.list 新增支持查询外部合作仓库:当对方主体的 project='warehouse' 时为仓库-仓库合作,counterparty_role='warehouse'。", - "响应新增 counterparty_role 字段(store/warehouse),标识对方主体的真实角色。", - "warehouse.list 响应 use_status 改为 store_use_status(仓库在 store_id 方时,己方启用状态应为 store_use_status)。", - "旧 list 方法保留标记为 @deprecated,保持向后兼容。", - "新增 buildListWhereByStoreId 统一按 store_id 维度构建查询条件。" - ], - "module": "storeWarehouse" - }, - { - "version": "2026.07.06-system-01", - "date": "2026-07-06", - "type": "updated", - "summary": "order.wave.batchList:响应新增 pick_assignment_status(拣货分配状态),按订单 pick_status 聚合判定", - "methods": [ - "order.wave.batchList" - ], - "notes": [ - "响应 list 每项新增字段 pick_assignment_status (string):拣货分配状态,按波次下订单的 pick_status 聚合判定。", - "取值语义与 resolveAssignmentStatus 一致,自定义标签:未拣货(全 none)、部分拣货(混合且无 error)、已拣货(全 fin)、拣货异常(含 error)。", - "SQL 子查询新增 pick_none_count / pick_fin_count / pick_error_count 聚合列。" - ], - "module": "order.wave" - }, - { - "version": "2026.07.05-system-01", - "date": "2026-07-05", - "type": "added", - "summary": "新增 pick.wavePickComplete:传入 wave_id 一键完成整个波次拣货,内部复用 query 去重与任务创建逻辑后自动调用 wavePickTaskComplete(mode=1)", - "methods": [ - "pick.wavePickComplete" - ], - "notes": [ - "新增方法:pick.wavePickComplete,入参 wave_id(number,必填)。", - "内部流程:按 wave_id 查波次 → 活动任务去重(同用户复用 / 他人409冲突)→ 完成任务去重 → 无任务则创建(source=2 后台抓取)→ 调用 pick.wavePickTaskComplete mode=1 全部确认。", - "创建任务 remark 格式:pick.wavePickComplete wave_id={waveId},用于与 pick.query 区分。", - "响应:task_id、status(completed / already_completed)、tip、confirmed_order_ids、is_completed、progress。", - "错误码:400(参数/波次无订单)、401(缺少操作人)、404(波次不存在)、409(他人活动任务冲突)、500(创建/完成失败)。" - ], - "module": "pick" - }, - { - "version": "2026.07.03-system-02", - "date": "2026-07-03", - "type": "added", - "summary": "新增 order.pendingOrder.updateRemark:批量修改待处理订单备注(remark),不受 post_status 限制", - "methods": [ - "order.pendingOrder.updateRemark" - ], - "notes": [ - "新增方法:order.pendingOrder.updateRemark,用于批量修改待处理订单的备注(remark)字段。", - "入参:ids(number[],必填,正整数数组,不能为空)、remark(string,必填,最大500字符)。", - "特性:不受 post_status 限制,可对所有状态的订单生效;纯批量不支持单ID。", - "更新成功后写入操作日志。", - "响应:updated_count(number,实际更新行数)、ids(number[],原样返回请求的ID数组)。", - "错误码:400(ids 不能为空 / ids 仅支持正整数数组 / remark 不能为空)。" - ], - "module": "order.pendingOrder" - }, - { - "version": "2026.07.03-system-01", - "date": "2026-07-03", - "type": "updated", - "summary": "将 quick.waybill.toOrder 迁移为 index.toOrder 并移入基础模块,新增 waves 返回字段", - "methods": [ - "quick.waybill.toOrder", - "index.toOrder" - ], - "notes": [ - "移除快捷操作(quick)模块分组,原 quick.waybill.toOrder 方法从 methods/system.json 删除。", - "在基础模块(index)新增 index.toOrder 方法:入参仍为 waybill_code,响应从单一 order_id 扩展为 order_id + waves 结构。", - "waves 为数组,每项含 wave_id(波次ID)、wave_no(波次号)、order_ids(波次下所有订单ID列表),无波次时为空数组。", - "查询路径:运单号 → wms_order_express(status=1)→ order_id + warehouse_id → 遍历 current/history/dispatch 表获取波次信息 → 再遍历多表获取同波次所有订单ID。" - ] - }, - { - "date": "2026-06-24", - "type": "addition", - "summary": "新增批量绑定入库单明细与收货单明细接口,支持明细级数量分配与部分成功", - "version": "2026-06-24-add-bind-receiving-details", - "methods": [ - "storage.entry.bindReceivingDetails" - ], - "notes": [] - }, - { - "date": "2026-06-24", - "type": "deprecation", - "summary": "废弃手动匹配入库单收货单接口,由 storage.entry.bindReceivingDetails 替代", - "version": "2026-06-24-deprecate-manual-match-entry-order", - "methods": [ - "storage.receiving.manualMatchEntryOrder" - ], - "notes": [] - }, - { - "version": "2026.06.16-system-03", - "date": "2026-06-16", - "summary": "order.wave.waveStrategyFallbackOrderList 响应新增 items_weight(总重量g)和 weight_type(重量类型)字段", - "methods": [ - "order.wave.waveStrategyFallbackOrderList" - ], - "notes": [ - "响应 list 每项新增字段 items_weight (number|null):订单总重量(g),来自 wms_order.items_weight,为 null 时返回 null。", - "响应 list 每项新增字段 weight_type (string):重量类型中文标签,来自 wms_order.weight_type 经 formatWeightTypeLabel 转换;取值:常规/轻货/重货/冷链(对应 DB 值 0/1/2/3)。" - ], - "type": "updated", - "module": "order.wave" - }, - { - "version": "2026.06.16-system-04", - "date": "2026-06-16", - "summary": "order.wave.singleOrderFetchList 响应新增 items_weight(总重量g)字段", - "methods": [ - "order.wave.singleOrderFetchList" - ], - "notes": [ - "响应 list 每项新增字段 items_weight (number|null):订单总重量(g),取组内首单 items_weight;组内订单 items_hash 相同重量一致。", - "为 null 时返回 null。" - ], - "type": "updated", - "module": "order.wave" - }, - { - "version": "2026.05.20-system-03", - "date": "2026-05-20", - "summary": "新增 storeWarehouse.store.queryPrintQuantityLogs:按 store_id 分页查询面单余额变更日志", - "methods": [ - "storeWarehouse.store.queryPrintQuantityLogs" - ], - "notes": [ - "新增方法:storeWarehouse.store.queryPrintQuantityLogs,用于按货主(store_id)分页查询面单余额变更日志。", - "入参:store_id(必填)、page(可选)、page_size / pageSize(可选,兼容别名)。", - "仅同步 methods/system.json 与本变更记录,不修改业务代码或测试。", - "返回:使用默认分页格式,响应在 `data` 下包含 `list`(变更日志数组)和 `pagination` 对象,`pagination` 字段:`page`、`pageSize`、`total`、`totalPages`、`hasPrevious`、`hasNext`。" - ], - "type": "added", - "module": "storeWarehouse" - }, - { - "version": "2026.05.13-system-01", - "date": "2026-05-13", - "summary": "完善 print.send 的 API 文档与返回说明", - "methods": [ - "print.send" - ], - "notes": [ - "补充请求参数说明:computerId、printer、template、data、type 标为必填,count、timestamp 保持可选。", - "补充 template 的子字段说明:page_width、page_height、template_content。", - "补充响应结构:flag、code、message、printId;其中成功时 code=200。", - "补充错误码说明:1001 对应不支持的打印类型,504 对应打印任务发送失败(包含打印机不存在、脱机、通讯失败等场景)。" - ], - "type": "updated" - }, - { - "version": "2026.05.08-system-06", - "date": "2026-05-08", - "summary": "新增取消拣货任务接口:order.wave.wavePickTaskCancel", - "methods": [ - "order.wave.wavePickTaskCancel" - ], - "notes": [ - "接口功能:取消拣货任务,同时释放关联波次(物理删除波次记录,订单回池)、解绑拣货车、写操作日志。", - "限制:仅允许在任务状态为 0(待开始)、1(拣货中)、2(待复核)时取消;状态为 3(已完成)或 9(已取消)时禁止取消,返回 400。", - "事务内操作:将任务状态更新为 9(已取消)、删除关联波次、清空订单 wave_id(回池)、解绑拣货车、写入 action_log 与 order_pick_trace;若有任一步骤失败则回滚并返回 500。" - ], - "type": "added" - }, - { - "version": "2026.07.01-system-01", - "date": "2026-07-01", - "summary": "storage.directInbound.addItem 参数名修正:entry_order_code → entry_order_id,类型 string → number", - "methods": [ - "storage.directInbound.addItem" - ], - "notes": [ - "文档 params 中 entry_order_code(string)改为 entry_order_id(number),与代码 app/service/systems/inbound_direct_log.js 第 544 行实际校验保持一致", - "同步修正 app/service/systemMethods/storage/direct_inbound.js JSDoc:@param {string} data.entry_order_code → @param {number} data.entry_order_id" - ], - "type": "fixed", - "module": "storage.directInbound" - }, - { - "version": "2026.07.01-system-02", - "date": "2026-07-01", - "summary": "新增 storage.entry.queryEntryLogs 接口文档定义", - "methods": [ - "storage.entry.queryEntryLogs" - ], - "notes": [ - "代码 method 层(systemMethods/storage/entry.js L284)和 systems 层(systems/operation_log.js L318)均已实现,补充文档定义", - "参数:id(number, required)、page(number, optional, 默认1)、pageSize(number, optional, 默认20)" - ], - "type": "added", - "module": "storage.entry" - }, - { - "version": "2026.06.18-system-01", - "date": "2026-06-18", - "summary": "order.pendingOrder.downloadCreateTemplate:模板列顺序调整,店铺名称(shop_nick)从末尾移至第2列B列,紧接*订单号之后", - "methods": [ - "order.pendingOrder.downloadCreateTemplate" - ], - "notes": [ - "调整 Excel 导入模板列顺序:店铺名称(shop_nick)从原第25列(Y列/末尾)移动至第2列(B列),紧跟在*订单号(delivery_order_code)之后。", - "同步更新 description 中的列顺序描述,明确 25 列(A-Y)的完整排列。", - "响应结构中移除冗余的 shop_nick 字段(模板列不属于 API 响应字段)。" - ], - "type": "updated", - "module": "order.pendingOrder" - }, - { - "version": "2026.05.17-system-09", - "date": "2026-05-17", - "summary": "为 storage.receiving.deleteDetail 文档补充约束:收货单已完成/已取消时禁止删除明细", - "methods": [ - "storage.receiving.deleteDetail" - ], - "notes": [ - "在 storage.receiving.deleteDetail 的 description 中补充:若关联收货单状态为 completed(已完成)或 cancelled(已取消),接口会返回删除失败(400),不允许删除明细。", - "在 errors 中补充或合并 400 描述以明确禁止删除已完成/已取消的收货单明细。" - ], - "type": "updated", - "module": "storage" - }, - { - "version": "2026.05.17-system-08", - "date": "2026-05-17", - "summary": "完善 storage.receiving.deleteDetail 文档:补充入参/返回/错误说明,明确用户上下文来源及删除约束", - "methods": [ - "storage.receiving.deleteDetail" - ], - "notes": [ - "补充 storage.receiving.deleteDetail 的参数说明:detail_id(来自请求体,必填);说明 creator_id 与 warehouse_id 来源于当前登录用户(ctx.user.employees_id / ctx.user.store_id)。", - "补充返回结构:成功时返回 code/message/data,data 包含 details(删除后剩余明细)和 selectId(建议选中ID);product_snapshot 若存在将被解析为对象或 null。", - "补充常见错误码:404(明细不存在或无权访问),400(收货单状态/已入库/删除失败),500(服务器异常)。", - "仅文档更新,不修改任何业务实现。" - ], - "type": "updated", - "module": "storage" - }, - { - "version": "2026.05.17-system-05", - "date": "2026-05-17", - "summary": "移除 storage.receiving.addItem(方法已下线/实现不存在)", - "methods": [ - "storage.receiving.addItem" - ], - "notes": [ - "仅同步文档:从 methods/system.json 中移除 storage.receiving.addItem,未修改任何业务代码或实现。", - "该方法已下线或实现不存在;请以当前 methods/system.json 的 SSOT 为准。" - ], - "type": "removed" - }, - { - "version": "2026.05.17-system-04", - "date": "2026-05-17", - "summary": "新增 stock.warehouse.import:仓库商品批量 JSON 导入(数组导入),SKU 为空创建/非空更新,支持 goods_code/货物编码 导入,更新写操作日志", - "methods": [ - "stock.warehouse.import" - ], - "notes": [ - "支持直接传入商品数组 JSON(主方式为数组,兼容 rows/items/list/data 包装)。", - "每项仅需传商品相关字段;SKU 为空时创建新商品,SKU 非空时为更新操作。", - "更新操作会写入操作日志以便审计。", - "支持导入 goods_code(货物编码)字段别名。", - "仅同步文档,不修改业务代码或实现。" - ], - "type": "added" - }, - { - "version": "2026.05.17-system-03", - "date": "2026-05-17", - "summary": "完善 stock.warehouse.handleBatchChange 文档:补充入参/出参/错误示例", - "methods": [ - "stock.warehouse.handleBatchChange" - ], - "notes": [ - "补充方法入参说明:ids/method/value 的字段类型、是否必填、来源与示例;完善响应结构示例与常见错误码说明。", - "仅文档更新,不改业务实现或语义。" - ], - "type": "updated" - }, - { - "version": "2026.05.17-system-02", - "date": "2026-05-17", - "summary": "stock.warehouse.export 由同步改为异步任务并新增进度查询 exportTaskProgress", - "methods": [ - "stock.warehouse.export", - "stock.warehouse.exportTaskProgress" - ], - "notes": [ - "stock.warehouse.export 改为异步提交导出任务:接口返回 task_id 与受理信息,后端异步生成导出文件。", - "新增 stock.warehouse.exportTaskProgress:按 task_id 查询任务状态与进度;当 status=success 时返回 download_url 供客户端下载;未找到时 status=not_found。", - "调用方式:先调用 stock.warehouse.export 获取 task_id,然后轮询 stock.warehouse.exportTaskProgress 直到 status=success 并获取 download_url。" - ], - "type": "updated" - }, - { - "version": "2026.05.17-system-01", - "date": "2026-05-17", - "summary": "新增 stock.warehouse.export:仓库商品导出(支持 where/sort),返回文件下载信息", - "methods": [ - "stock.warehouse.export" - ], - "notes": [ - "新增方法:stock.warehouse.export。复用 stock.warehouse.list 的 where/sort 过滤语义(支持 operator/value/type 标准 where 结构与历史简写)。", - "响应返回导出结果(示例字段:file_key、url),表示生成的 Excel 已上传并可下载/查询。" - ], - "type": "added" - }, - { - "version": "2026.05.16-system-01", - "date": "2026-05-16", - "summary": "同步 setting.expressInterface.create 文档入参:移除未使用的 express_platform_id,标注必填字段", - "methods": [ - "setting.expressInterface.create" - ], - "notes": [ - "移除文档中 express_platform_id(服务端实现未使用);确认必填字段 name/express_code/platform_code;仓库由系统自动填充,禁止传入 warehouse_id/warehouseId。" - ], - "type": "updated" - }, - { - "version": "2026.05.12-system-01", - "date": "2026-05-12", - "summary": "调整订单打印中间态返回结构为 waveGroups(波次 -> 平台 -> 订单)", - "methods": [ - "order.print.getWavePlatformPrintData" - ], - "notes": [ - "主要变更:将方法的主返回结构改为 waveGroups,按波次分组,波次内按平台分组,平台内为订单列表(波次 -> 平台 -> 订单)。", - "兼容性:保留旧字段 platform_groups 与 order_list 作为向后兼容字段,但文档主结构与推荐使用为 waveGroups。", - "返回结构说明:summary(total_waves/total_orders/total_platforms)、wave_ids(通过过滤的波次ID数组)、waveGroups(数组,项含 wave_id、wave_no、order_count、platforms[...],platforms项含 platform、platform_name、order_count、orders[...])、ext(missing_wave_ids、filtered_wave_ids)。", - "errors:保留 400 / 500 不变。" - ], - "type": "modified" - }, - { - "version": "2026.05.11-system-05", - "date": "2026-05-11", - "summary": "order.wave.batchList:支持 express/print 分配状态筛选,入参改为英文枚举(express/print)", - "methods": [ - "order.wave.batchList" - ], - "notes": [ - "修复 where.express_assignment_status 可按快递分配状态筛选。", - "新增 where.print_assignment_status 筛选(按打印分配聚合判断)。", - "express_assignment_status / print_assignment_status 要求使用英文枚举值:express=unassigned/partially_assigned/assigned,print=unprinted/partially_printed/printed;storage_assignment_status 继续兼容中文枚举(未分配/部分分配/已分配)。", - "若传入非法枚举值,接口返回 400(参数校验失败),message 中会说明允许取值。" - ], - "type": "updated" - }, - { - "version": "2026.05.11-system-04", - "date": "2026-05-11", - "summary": "调整 order.wave.waveStrategyFetchAdmin:由创建任务改为直接创建波次(不创建拣货任务)", - "methods": [ - "order.wave.waveStrategyFetchAdmin" - ], - "notes": [ - "接口行为变更:按策略直接抓取命中订单并创建波次,不再创建拣货任务(不返回 task_id/task_no 等任务字段)。", - "响应调整为建波结果:fetch_state(1=成功/2=失败)、wave_ids、wave_nos、created_wave_count、created_order_count、order_ids、(可选)wave_prefix、wave_prefix_source、tip/message。", - "错误调整:策略校验失败返回 400(并可能返回 validation_errors),缺少仓库上下文返回 400,建波失败返回 500 并在 message 中说明。" - ], - "type": "updated" - }, - { - "version": "2026.05.11-system-03", - "date": "2026-05-11", - "summary": "更新 pick.query:由查询拣货明细调整为按 keyword 获取/创建拣货任务", - "methods": [ - "pick.query" - ], - "notes": [ - "入参由 waybill_code/full_display 调整为 keyword(支持运单号或波次号)。", - "接口语义调整为任务化返回:命中活动任务则返回 existing 任务ID;无活动任务则创建并返回 created 任务ID。", - "新增任务归属冲突错误:当活动任务创建人非当前用户时返回冲突提示,并附带创建人及任务ID信息。" - ], - "type": "updated" - }, - { - "version": "2026.05.11-system-02", - "date": "2026-05-11", - "summary": "新增 pick.wavePickTaskCurrent:PDA 无参查询当前进行中拣货任务", - "methods": [ - "pick.wavePickTaskCurrent" - ], - "notes": [ - "新增 PDA 专用无参接口 pick.wavePickTaskCurrent。", - "按当前登录用户上下文(pick_user_id + warehouse_id)查询状态在 0/1/2 的最新任务。", - "命中返回 task_id,未命中返回 task_id=null。" - ], - "type": "added" - }, - { - "version": "2026.05.10-system-04", - "date": "2026-05-10", - "summary": "pick.wavePickTaskDetail 新增按任务类型区分的 picking_view 形态输出", - "methods": [ - "pick.wavePickTaskDetail" - ], - "notes": [ - "新增响应字段:picking_view(object),按 task.pick_mode 区分 5 种形态输出。", - "picking_view 字段说明:mode_code, mode_name, require_box_allocations, group_by, sort_by, items[](每项含 space_id、space_name、location_space、item_code、item_name、stock_id、total_qty、box_allocations[])。", - "当 pick_mode=1/3/4 时 require_box_allocations=true;当 pick_mode=2/5 时 require_box_allocations=false。" - ], - "type": "updated" - }, - { - "version": "2026.05.10-system-02", - "date": "2026-05-10", - "summary": "order.wave.waveStrategyFetchPda/Admin 返回新增 fetch_state 三态与简短 tip", - "methods": [ - "order.wave.waveStrategyFetchPda", - "order.wave.waveStrategyFetchAdmin" - ], - "notes": [ - "新增返回字段:fetch_state(number)、tip(string)、can_enter_pick_flow(boolean)", - "fetch_state 含义:1=创建成功(返回 task_id/task_no),2=普通失败(task_id=null),3=存在未完成任务(返回 existing task_id/task_no,前端可直接进入拣货流程)", - "当 fetch_state=3 时,字段 can_enter_pick_flow=true,表示前端可直接进入拣货流程;tip 为简短提示文本" - ], - "type": "updated" - }, - { - "version": "2026.05.10-system-03", - "date": "2026-05-10", - "summary": "裁剪 pick.wavePickTaskDetail 返回:移除 waves/orders,精简 task 并补充 boxes 拣货统计字段", - "methods": [ - "pick.wavePickTaskDetail" - ], - "notes": [ - "移除响应中的 waves 与 orders 子表,接口仅返回精简的 task、boxes、picking_details 与 picking_summary。", - "task 子字段裁剪为:task_id, task_no, status, pick_mode, start_at, finish_at, batch_no。", - "boxes 补充并明确返回:ref_label(箱参考标签)、required_qty(箱内需拣总数)、picked_qty(已拣数量)。", - "本次变更为文档层面的返回裁剪,前端应以新字段集合为准,旧字段可能不再返回。" - ], - "type": "updated" - }, - { - "version": "2026.05.10-system-01", - "date": "2026-05-10", - "summary": "order.wave.waveStrategyList 新增 strategy_type 最小过滤(散单/团购)", - "methods": [ - "order.wave.waveStrategyList" - ], - "notes": [ - "新增 strategy_type 过滤,仅 1/2", - "支持顶层 strategy_type 和 where.strategy_type,顶层优先", - "当前不引入其他 where 字段" - ], - "type": "updated" - }, - { - "version": "2026.05.09-system-02", - "date": "2026-05-09", - "summary": "新增 pick.wavePickTaskDetail:按任务ID解析拣货任务详情", - "methods": [ - "pick.wavePickTaskDetail" - ], - "notes": [ - "新增 pick.wavePickTaskDetail:传入 task_id 获取拣货任务完整信息,包含主表字段(task/pick_mode/status/wave_count/order_count/box_count 等)及三张子表数据(waves/orders/boxes)。", - "安全限制:接口会校验当前登录用户(operator_id/employees_id)与任务的 pick_user_id 是否一致;不一致时直接返回 403,不返回任何拣货信息。", - "鉴权配置:noNeedRight=true,noNeedAuth=true,isNeedLogin=true。" - ], - "type": "added" - }, - { - "version": "2026.05.08-system-05", - "date": "2026-05-08", - "summary": "order.wave.batchList:新增 source 字段并支持 where.source 过滤,返回 list item 中新增 source 字段", - "methods": [ - "order.wave.batchList" - ], - "notes": [ - "新增 where.source(可选,number)用于按来源过滤:0=普通波次(正常后台操作),1=管理后台策略任务,2=PDA策略任务;不传则不过滤。", - "响应 list 每条记录新增字段 source(number),用于区分波次来源。", - "仅更新文档,业务代码不在此变更范围。" - ], - "type": "updated" - }, - { - "version": "2026.05.08-system-04", - "date": "2026-05-08", - "summary": "完善 order.wave.wavePickTaskList 文档:补充入参、分页与返回字段兼容说明", - "methods": [ - "order.wave.wavePickTaskList", - "order.wave.wavePickTaskCancel" - ], - "notes": [ - "入参补充:warehouse_id(必填)、status(支持单值或数组,建议传数组)、source、keyword、page_no、page_size;保留 pagination 对象以兼容旧客户端。", - "兼容说明:接口同时支持历史 where 结构与顶层参数;当存在同名顶层参数时以顶层参数优先;pagination 支持 page/current 与 pageSize/size 别名。", - "返回格式:响应包含 total 与 list;list 每项包含字段:task_id、task_no、status、source、pick_mode、wave_count、order_count、box_count、operator_id、operator_name、start_at、finish_at、created_at。为兼容旧客户端,响应同时保留旧字段:pick_user_id、pick_user_name、start_time、finish_time、create_time。", - "入参 strategy_id 当前主表未存,接口会忽略该过滤,不建议使用。", - "默认排序:create_time desc.", - "文档变更:移除 order.wave.wavePickTaskCancel 的入参 operator_id 与 warehouse_id;入参改为仅支持 task_ids(数组,必填),不再兼容单个 task_id;操作人与仓库由请求上下文(例如当前登录用户上下文)自动获取;若上下文缺失接口将返回错误。响应补充批量结果字段:cancelled_count、task_ids、task_nos(若后端返回)。仅更新文档,未修改业务实现。" - ], - "type": "updated" - }, - { - "version": "2026.05.08-system-03", - "date": "2026-05-08", - "summary": "升级按策略抓取接口为创建任务主流程:order.wave.waveStrategyFetchPda / order.wave.waveStrategyFetchAdmin", - "methods": [ - "order.wave.waveStrategyFetchPda", - "order.wave.waveStrategyFetchAdmin" - ], - "notes": [ - "将 PDA/Admin 场景的按策略抓取接口由受理壳方法升级为 '创建任务主流程':接口会执行参数校验并在同步响应中创建任务记录(state=created),返回 task_id、task_no、plan 与 plan_summary 供前端展示与后续查询。", - "入参新增/扩展与创建流程相关字段:至少包含 cart_id(关联拣货车/作业车ID)、source(操作来源语义)并保留并透传 strategy_id 与 strategy_params(策略参数),以支持在创建阶段对策略进行局部覆盖或透传。", - "成功返回示例字段:state=created、task_id、task_no、plan(对象)和 plan_summary(字符串);失败场景会返回 validation_errors(数组,每项含 field/message)或 message 描述创建失败原因。", - "边界说明:当前为最小主流程(创建与计划预览),后续扫描/任务执行阶段(如实际抓取订单、写入 wave 等)将在后续版本中追加与完善。" - ], - "type": "updated" - }, - { - "version": "2026.05.08-system-02", - "date": "2026-05-08", - "summary": "调整按策略抓取壳方法:order.wave.waveStrategyFetch 更名为 order.wave.waveStrategyFetchPda,并新增 order.wave.waveStrategyFetchAdmin", - "methods": [ - "order.wave.waveStrategyFetch", - "order.wave.waveStrategyFetchPda", - "order.wave.waveStrategyFetchAdmin" - ], - "notes": [ - "waveStrategyFetchPda 仅用于 PDA 场景", - "waveStrategyFetchAdmin 仅用于后台管理场景", - "两者当前均为壳子受理方法,不执行真实抓取" - ], - "type": "updated" - }, - { - "version": "2026.05.08-system-01", - "date": "2026-05-08", - "summary": "新增 order.wave.waveStrategyFetch:按策略提交抓取任务(壳子方法)", - "methods": [ - "order.wave.waveStrategyFetch" - ], - "notes": [ - "当前方法为壳子方法:仅受理并返回任务受理信息,不执行真实抓取逻辑,后续补齐执行链路。" - ], - "type": "added" - }, - { - "version": "2026.05.07-system-05", - "date": "2026-05-07", - "summary": "新增 order.wave.waveStrategyCreate 与 order.wave.waveStrategyUpdate:波次策略创建与更新接口(含参数校验与版本推进)", - "methods": [ - "order.wave.waveStrategyCreate", - "order.wave.waveStrategyUpdate" - ], - "notes": [ - "仓库 ID 与创建人(creator_name)由当前登录仓库/操作者上下文获取,接口不接受外部覆盖。", - "入参 allowed_owners 与 allowed_expresses 会校验是否在系统可用范围内(基于仓库签约货主或系统快递列表),若存在非法值接口会直接报错(400)。", - "max_same_structure 受仓库配置 min_group_order_fetch_quantity 限制:若传入值 >= min_group_order_fetch_quantity,则自动下调为 min_group_order_fetch_quantity - 1(最小值为 1)。", - "新建/更新成功后会触发仓库的 wave_strategy_version 自增(+1)并失效相关仓库配置缓存,调用方可通过策略版本推进或缓存变化感知策略已生效。" - ], - "type": "added" - }, - { - "version": "2026.05.07-system-06", - "date": "2026-05-07", - "summary": "收敛 order.wave.waveStrategyFallbackOrderList 返回字段,限定 where 白名单,补充 order.wave.singleFetchByIds 别名与返回语义", - "methods": [ - "order.wave.waveStrategyFallbackOrderList", - "order.wave.singleFetchByIds" - ], - "notes": [ - "收敛 order.wave.waveStrategyFallbackOrderList response.list 字段为 id, delivery_no, tracking_no, items_count, items_total, sys_logistics_name, store_name, province, sys_platform_name, item_snapshot;item_snapshot 格式示例:商品名称*数量|...。", - "限制 order.wave.waveStrategyFallbackOrderList.where 白名单,禁止传入 warehouse_id / warehouseId;传入未列出字段或别名冲突将返回 400。", - "补充 order.wave.singleFetchByIds:明确支持 ids / order_ids / orderIds 三个别名(优先顺序 ids -> order_ids -> orderIds)并说明返回字段 fetched_order_ids、excluded_existing_wave_order_ids、skipped_order_ids、not_found_order_ids 的语义与兼容性。" - ], - "type": "updated" - }, - { - "version": "2026.05.07-system-04", - "date": "2026-05-07", - "summary": "更新 order.wave.waveStrategyFallbackOrderList,新增商品快照字段 item_snapshot", - "methods": [ - "order.wave.waveStrategyFallbackOrderList" - ], - "notes": [ - "item_snapshot 返回格式为 商品名称1*数量|商品名称2*数量" - ], - "type": "updated" - }, - { - "version": "2026.05.07-system-03", - "date": "2026-05-07", - "summary": "新增 order.wave.waveStrategyQuickScan 与进度查询接口", - "methods": [ - "order.wave.waveStrategyQuickScan", - "order.wave.waveStrategyQuickScanTaskProgress" - ], - "notes": [ - "同仓只允许一个扫描任务并使用缓存锁;扫描范围为当前表非待审核、未分配波次且订单策略版本与仓库当前版本不一致的订单;命中策略标记 wave_scan_result=1,否则=2" - ], - "type": "added" - }, - { - "version": "2026.05.07-system-02", - "date": "2026-05-07", - "summary": "新增 order.wave.waveStrategyList:查询当前仓库波次策略列表", - "methods": [ - "order.wave.waveStrategyList" - ], - "notes": [ - "从 wms_wave_strategy 拉取当前仓库的波次策略列表,分页返回" - ], - "type": "added" - }, - { - "version": "2026.05.07-system-01", - "date": "2026-05-07", - "summary": "移除 order.wave.singleOrderFetchDetailList,新增 order.wave.waveStrategyFallbackOrderList(内置固定筛选条件)", - "methods": [ - "order.wave.singleOrderFetchDetailList", - "order.wave.waveStrategyFallbackOrderList" - ], - "notes": [ - "移除 order.wave.singleOrderFetchDetailList。", - "新增 order.wave.waveStrategyFallbackOrderList。", - "新接口基于订单通用查询口径,固定内置筛选条件:step != 0、wave_id = 0、wave_scan_result = 2。" - ], - "type": "updated" - }, - { - "version": "2026.05.06-system-06", - "date": "2026-05-06", - "summary": "新增 order.wave.singleOrderFetchDetailList:订单级散单候选明细视图", - "methods": [ - "order.wave.singleOrderFetchDetailList" - ], - "notes": [ - "新增 order.wave.singleOrderFetchDetailList:提供订单级的散单候选明细列表,返回按订单聚合的明细(非分组级)。", - "返回订单级而非分组级;响应每项包含订单 id、group_count、item_detail_machine、item_detail_machine_snapshot、item_detail、item_snapshot、logistics_name、store_id、distinguish_express、create_at 与 status_summary 等关键字段。", - "仍沿用 same_order_quantity 阈值来排除团购命中分组(仅保留 group_count < same_order_quantity 的候选项)。", - "singleOrderFetchList 暂保留以兼容现有前端,前端可在切换到订单级视图后迁移到本接口。" - ], - "type": "added" - }, - { - "version": "2026.05.06-system-05", - "date": "2026-05-06", - "summary": "storage.receiving.get 返回扩展:data.details[*] 新增 box_remainder、box_weight", - "methods": [ - "storage.receiving.get" - ], - "notes": [ - "storage.receiving.get 的响应在 data.details[*] 中新增可选字段:box_remainder(箱内剩余数量/零散数量,number,默认 0)与 box_weight(实测箱重,number,默认 0)。", - "兼容性:新增字段为可选,旧客户端无需修改;建议前端在需要展示箱内余量/箱重时使用这些字段。" - ], - "type": "updated" - }, - { - "version": "2026.05.06-system-04", - "date": "2026-05-06", - "summary": "storage.receiving.getReceivingDetail 返回扩展:明细增加 box_remainder、box_weight;storage.receiving.completeReceiving 通知包含这两个字段", - "methods": [ - "storage.receiving.getReceivingDetail", - "storage.receiving.completeReceiving" - ], - "notes": [ - "为支持箱规统计与通知回传,getReceivingDetail 的明细项(receiving.details 或 data.details)在响应中新增可选字段:box_remainder(箱内剩余数量/零散数量,number)与 box_weight(实测箱重,number,单位同系统重量)。", - "completeReceiving 在完成收货后会发送通知(或回调),通知 payload/metadata 中将包含每条明细的 box_remainder 与 box_weight 字段,供下游系统/前端展示或审计使用。", - "兼容性:新增字段为可选,旧客户端在未使用这些字段时无需变更。" - ], - "type": "updated" - }, - { - "version": "2026.05.06-system-03", - "date": "2026-05-06", - "summary": "storage.receiving.detailChange:新增入参/出参字段 box_remainder、box_weight", - "methods": [ - "storage.receiving.detailChange" - ], - "notes": [ - "为支持箱规细化与回写,detailChange 新增可选入参 box_remainder(箱内余量/零散数量)和 box_weight(实测箱重,单位同系统重量),写入后会回写至明细并在响应 data 中返回对应字段。", - "兼容性:新增字段为可选,不传入则不影响现有调用;建议前端在需要回写箱余与箱重时一并传入。" - ], - "type": "updated" - }, - { - "version": "2026.05.06-system-02", - "date": "2026-05-06", - "summary": "新增 order.wave.singleFetchByIds:按订单ID抓取到一个散单波次", - "methods": [ - "order.wave.singleFetchByIds" - ], - "notes": [ - "新增 order.wave.singleFetchByIds:按入参 ids(兼容 order_ids/orderIds)去重后筛选当前仓库内待处理且不在波次中的订单,若存在可抓取订单则创建单个散单波次并把这些订单写入该波次(不区分快递);成功后批量写入订单操作日志;若无可抓取订单返回 wave_id=0。", - "接口行为严格对齐实现:过滤条件包含 step in [1,2,3]、status != 'cancel'、outbound_status != 'padding';已在波次的订单会被排除并返回 excluded_existing_wave_order_ids;响应包含 ids、wave_id、wave_no、fetched_order_ids、fetched_order_count、excluded_existing_wave_order_ids、skipped_order_ids、not_found_order_ids。" - ], - "type": "added" - }, - { - "version": "2026.05.06-system-01", - "date": "2026-05-06", - "summary": "新增 order.wave.groupFetch 与 order.wave.singleFetch;order.wave.fetch 保留兼容别名;抓取进度补充上限字段", - "methods": [ - "order.wave.groupFetch", - "order.wave.singleFetch", - "order.wave.fetch", - "order.wave.fetchTaskProgress" - ], - "notes": [ - "新增 order.wave.groupFetch:抓取团购接口(异步任务提交),参数 structure_list 与原 fetch 一致。", - "新增 order.wave.singleFetch:抓取散单接口(异步任务提交),在 structure_list 每项新增必填字段 max_fetch_quantity(最大抓取上限,订单数,正整数)。", - "order.wave.fetch 保留为兼容别名(等同 groupFetch),避免误导客户端。", - "groupFetch/singleFetch/fetch 的响应新增可选字段 fetch_mode;singleFetch 响应额外返回 max_fetch_quantity。", - "order.wave.fetchTaskProgress 的响应增加单模式相关字段:fetch_mode、max_fetch_quantity、limit_reached、stop_reason,用于描述散单抓取的上限与停止原因。" - ], - "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-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": "updated" - }, - { - "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 查询全字段列表并支持缓存", - "methods": [ - "setting.expressInterface.listByWarehousePlatformCode" - ], - "notes": [ - "新增 setting.expressInterface.listByWarehousePlatformCode:按 warehouse_id + platform_code 返回快递接口的全字段数组(不分页),每条记录包含 express 关联对象(id/code/name/platform 等)。", - "支持缓存,缓存键由 warehouse_id + platform_code 组成;缓存命中将直接返回缓存结果以提升查询性能。", - "在创建/更新/删除操作(setting.expressInterface.create/update/delete)后,会主动清理对应 warehouse_id + platform_code 的缓存以确保数据一致性。" - ], - "type": "added" - }, - { - "version": "2026.04.17-system-08", - "date": "2026-04-17", - "summary": "新增快递编码管理模块批量软删除接口 setting.express.delete", - "methods": [ - "setting.express.delete" - ], - "notes": [ - "新增批量软删除接口 setting.express.delete:接受 ids(数组、逗号字符串或单值),对属于当前仓库且未被删除的记录执行软删除(设置 deleted_at),并清理 express 列表缓存。", - "当任一目标记录的 code 被 wms_express_interface.express_code 引用时,接口会拒绝删除并返回 409,错误信息中包含被引用的编码列表。", - "响应包含 ids、deleted_ids、already_deleted_ids 与 status,已删除与未删除的 id 会明确分类。仅记录已实现行为。" - ], - "type": "added" - }, - { - "version": "2026.04.17-system-05", - "date": "2026-04-17", - "summary": "新增文档分组:平台编码管理模块(收口 index.getPlatformList 与 setting.platform.*)", - "methods": [ - "index.getPlatformList", - "setting.platform.list", - "setting.platform.create", - "setting.platform.update", - "setting.platform.delete" - ], - "notes": [ - "新增独立文档分组 '平台编码管理模块',将平台基础列表(index.getPlatformList)与平台设置管理接口(setting.platform.*)归并为单一分组以便维护;仅文档变更,不修改实现。", - "文档中仅包含已实现的方法与字段,未新增或推断不存在的参数/返回字段。" - ], - "type": "added" - }, - { - "version": "2026.04.17-system-04", - "date": "2026-04-17", - "summary": "新增独立平台设置模块 setting.platform(wms_platfrom_setting)及其 CRUD 接口:list/create/update/delete。", - "methods": [ - "setting.platform.list", - "setting.platform.create", - "setting.platform.update", - "setting.platform.delete" - ], - "notes": [ - "新增独立模块 setting.platform,映射数据表 wms_platfrom_setting;list 支持 where(id/code/name/platform_code/quickWhere)与 pagination(兼容 page/pageSize/page_size);create/update 要求 platform_code 必须存在于系统平台表(wms_platform),且禁止越权写入 warehouse_id;delete 需传入 id 并校验当前仓库范围。" - ], - "type": "added" - }, - { - "version": "2026.04.15-system-07", - "date": "2026-04-15", - "summary": "将 docs/order-workbench-list-api.md 引用统一为 window 链接格式", - "methods": [ - "order.list", - "order.reviewOrder.list", - "order.pendingOrder.list", - "order.outboundOrder.list", - "order.expectionOrder.list", - "order.entrustOrder.list", - "order.deliveryOrder.list", - "order.deliveryExpectionOrder.list" - ], - "notes": [ - "将所有 methods/system.json 中指向 docs/order-workbench-list-api.md 的说明统一替换为 docs/order-workbench-list-api.md 格式,以便 HTML 渲染识别为 window 链接。", - "仅修改 methods/system.json 的文档字段,不涉及任何业务代码或接口契约变化。" - ], - "type": "updated" - }, - { - "version": "2026.04.15-system-06", - "date": "2026-04-15", - "summary": "订单工作台列表文档补全 raw 字段字典与中文语义说明", - "methods": [ - "order.list", - "order.reviewOrder.list", - "order.pendingOrder.list", - "order.outboundOrder.list", - "order.expectionOrder.list", - "order.entrustOrder.list", - "order.deliveryOrder.list", - "order.deliveryExpectionOrder.list", - "order.archiveOrder.list" - ], - "notes": [ - "在 docs/order-workbench-list-api.md 中补充所有订单列表通用 raw 字段字典,明确每个字段的中文语义与 enum 取值。", - "补充 express_numbers / waybill_codes 两个服务层派生字段说明,便于前端直接渲染多个快递号。", - "methods/system.json 中所有订单 list 的 response.list 描述已指向该字段字典章节。" - ], - "type": "updated" - }, - { - "version": "2026.04.15-system-05", - "date": "2026-04-15", - "summary": "基础模块新增快递/平台列表查询接口并设置为不鉴权,复用缓存 service", - "methods": [ - "index.getExpressList", - "index.getPlatformList" - ], - "notes": [ - "新增 index.getExpressList,归属基础模块(module=index),对应 app/service/systems/express.js 中的 getExpressList。", - "index.getExpressList 设置为不鉴权,不需要 Authorization 头。", - "新增 index.getPlatformList,归属基础模块(module=index),对应 app/service/systems/platform.js 中的 getPlatformList。", - "index.getPlatformList 设置为不鉴权,不需要 Authorization 头。", - "快递列表与平台列表都支持缓存优先,缓存未命中时回源数据库并写入缓存。", - "平台列表支持缓存优先,缓存未命中时回源 wms_platform 并写入缓存。" - ], - "type": "added" - }, - { - "version": "2026.04.15-system-02", - "date": "2026-04-15", - "summary": "签约策略字段元信息新增 default_express_code / default_platform_code list 选项", - "methods": [ - "storeWarehouse.store.getPolicyConfigFields" - ], - "notes": [ - "getPolicyConfigFields 现在返回 default_express_code 与 default_platform_code 两个 list 字段,并从 wms_express / wms_platform 读取选项列表。", - "默认值仍保留为 default_express_code=STO、default_platform_code=TB。" - ], - "type": "updated" - }, - { - "version": "2026.04.15-system-03", - "date": "2026-04-15", - "summary": "签约策略字段移除 sku_visibility,receive_mode options 改为 value/label 结构", - "methods": [ - "storeWarehouse.store.savePolicyConfig", - "storeWarehouse.store.getPolicyConfigFields" - ], - "notes": [ - "策略字段定义不再包含 sku_visibility,历史值读取时仍会被归一化忽略。", - "receive_mode 的 options 改为 [{ value, label }] 格式,便于前端直接渲染。" - ], - "type": "updated" - }, - { - "version": "2026.04.15-system-04", - "date": "2026-04-15", - "summary": "按文件模块拆分 order 目录系统文档分组,覆盖订单工作台入口及各子模块方法", - "methods": [ - "order.list", - "order.manualOutboundOrder", - "order.badgeCount", - "order.outboundOrder.manualOutboundOrder", - "order.reviewOrder.list", - "order.reviewOrder.reviewOrder", - "order.pendingOrder.list", - "order.pendingOrder.reverseReviewOrder", - "order.pendingOrder.markPendingOutboundOrder", - "order.pendingOrder.cancelOrder", - "order.outboundOrder.list", - "order.expectionOrder.list", - "order.entrustOrder.list", - "order.deliveryOrder.list", - "order.deliveryExpectionOrder.list", - "order.archiveOrder.list" - ], - "notes": [ - "按 app/service/systemMethods/order 下的实际对外方法补全 methods/system.json 文档,只覆盖 system,不处理 qimen。", - "order 文档已按 index / reviewOrder / pendingOrder / outboundOrder / expectionOrder / entrustOrder / deliveryOrder / deliveryExpectionOrder / archiveOrder 拆成多个模块分组。", - "同步根据当前代码意图补充 params / response / errors,且不再把 index.js 已移除的兼容接口写回文档。" - ], - "type": "updated" - }, - { - "version": "2026.04.15-system-01", - "date": "2026-04-15", - "summary": "货主主体配置默认补齐 default_express_code / default_platform_code", - "methods": [ - "store.createStore", - "store.createWarehouse" - ], - "notes": [ - "当 subject_config 未传或缺少字段时,自动补齐 default_express_code=STO、default_platform_code=TB,并保留现有的 max_notice_webhook_count 默认值。", - "同步更新 methods/system.json 中 store.createStore 与 store.createWarehouse 的参数说明。" - ], - "type": "updated" - }, - { - "version": "2026.04.14-system-01", - "date": "2026-04-14", - "summary": "库存列表新增货主名称字段 stock.store_name", - "methods": [ - "storage.inventory.list" - ], - "notes": [ - "在 methods/system.json 的 storage.inventory.list response 中补充 stock.store_name:来源于签约表 store_remask,若无签约关系则为 null。", - "只同步文档,不修改业务代码。" - ], - "type": "updated" - }, - { - "version": "2026.04.13-system-01", - "date": "2026-04-13", - "summary": "补全 storage.receiving.detailChange 的入参/出参契约与错误码说明", - "methods": [ - "storage.receiving.detailChange" - ], - "notes": [ - "在 methods/system.json 中补充 storage.receiving.detailChange 的 params/response/errors,明确 id 与 receiving_id 必填。", - "说明 expiry_date 小于当前日期时返回 400 且 message 为 \"到期日期已过期,不能录入收货\"。", - "说明当传入 system_product_id 时会回填条码、重量、箱规、商品名称与 product_snapshot;未传时 barcode/product_name 也可单独更新。", - "同步补充文档:docs/storage-receiving-api.md 中新增 detailChange 段落。" - ], - "type": "updated" - }, - { - "version": "2026.04.07-system-01", - "date": "2026-04-07", - "summary": "修正 warehouse.getAreaRacks 的鉴权/权限链路文档,明确该接口需要 登录并走权限校验。", - "methods": [ - "warehouse.getAreaRacks" - ], - "notes": [ - "对齐当前 system 文档中的 isNeedAuth=true、isNeedLogin=true。", - "用于补充该接口权限链路修正文档的历史上下文,不改变 methods/system.json 的 SSOT 角色。" - ] - }, - { - "version": "2026.04.07-system-02", - "date": "2026-04-07", - "summary": "补充签约配置相关接口文档,覆盖策略字段元信息查询与面单数量人工调整。", - "methods": [ - "storeWarehouse.store.getPolicyConfigFields", - "storeWarehouse.store.adjustPrintQuantity" - ], - "notes": [ - "getPolicyConfigFields 说明为获取签约策略可配置字段元信息列表。", - "adjustPrintQuantity 说明为人工调整签约关系下的面单余额并记录变更日志,并 明确 id、change_quantity、reason 等关键入参。" - ] - }, - { - "version": "2026.04.07-system-03", - "date": "2026-04-07", - "summary": "对外命名从 qimenConfig 收口为 apiConfig,并在接口配置文档中强调 interface_type_id 校验。", - "methods": [ - "storeWarehouse.store.listApiConfig", - "storeWarehouse.store.saveApiConfig", - "storeWarehouse.store.deleteQimenConfig" - ], - "notes": [ - "文档对外统一使用 apiConfig / api_config 命名,减少 qimenConfig 历史别名歧义。", - "saveApiConfig 要求 interface_type_id 为必填且必须指向已存在的 wms_interface_type 记录。", - "listApiConfig / deleteQimenConfig 同步补充 interface_type_id 字段说明。" - ] - }, - { - "version": "2026.04.07-system-04", - "date": "2026-04-07", - "summary": "补充 /api/docs 文档体验增强说明,新增查看变更记录与查看原文 JSON 的入口说明。", - "methods": [ - "/api/docs", - "/api/docs/:docName", - "/api/docs/:docName/raw", - "/api/docs/:docName/changes" - ], - "notes": [ - "sidecar 变更数组用于承载文档历史说明,不替代 methods/system.json 作为 SSOT。", - "原文 JSON 入口继续用于直接查看当前生效文档。" - ] - }, - { - "version": "2026.04.07-system-05", - "date": "2026-04-07", - "summary": "修正 storeWarehouse.store.adjustPrintQuantity 的面单余额调整语义:由增减/累加改为覆盖设置目标余额。", - "methods": [ - "storeWarehouse.store.adjustPrintQuantity" - ], - "notes": [ - "adjustPrintQuantity 当前兼容 print_quantity、target_quantity、change_quantity、adjust_quantity 作为目标面单余额输入,不再按增减量解释。", - "变更日志中的 change_quantity 由 before/after 自动计算差值,以兼容历史审计与展示。" - ] - }, - { - "version": "2026.04.07-system-06", - "date": "2026-04-07", - "summary": "按接口类型分类限制必填字段,OPEN_API 创建时自动生成 self_app_key/self_app_secret", - "methods": [ - "storeWarehouse.store.saveApiConfig" - ], - "notes": [ - "QM_WMS 类型须填写 qimen_app_key/qimen_customer_id/qimen_warehouse_code;OPEN_API 类型三个奇门字段非必填,创建时自动生成 self_app_key(WMS+32位HEX)和 self_app_secret(64位HEX),更新时保留已有密钥。" - ], - "type": "changed" - }, - { - "version": "2026.04.07-system-07", - "date": "2026-04-07", - "summary": "新增接口类型列表查询接口,归属基础模块,无需权限", - "methods": [ - "index.listInterfaceTypes" - ], - "notes": [ - "返回所有已启用的接口类型(wms_interface_type),包含 id、interface_code、interface_name、interface_category、description 字段。设置 isNeedAuth: false, isNeedLogin: true。" - ], - "type": "added" - }, - { - "version": "2026.04.07-system-08", - "date": "2026-04-07", - "summary": "app_name 改为必传参数", - "methods": [ - "storeWarehouse.store.saveApiConfig" - ], - "notes": [ - "app_name 不再有默认值自动生成逻辑,调用方必须传入非空的 app_name,否则返 回 400 错误。" - ], - "type": "changed" - }, - { - "version": "2026.04.07-system-09", - "date": "2026-04-07", - "summary": "新增收货单快捷入库上架接口", - "methods": [ - "storage.inventory.quickPutaway" - ], - "notes": [ - "新建 storage.inventory 库存操作模块。quickPutaway 从收货单直接生成入库单 (SCRK)并写入 wms_storage 库存表,同时更新 wms_stock_warehouse 库存数量(悲观行锁),回填收货明细入库状态。要求收货单已完成且所有明细已匹配系统商品。" - ], - "type": "added" - }, - { - "version": "2026.04.08-system-01", - "date": "2026-04-08", - "summary": "新增收货单与入库单匹配入库接口", - "methods": [ - "storage.inventory.matchPutaway" - ], - "notes": [ - "接收多个收货单和入库单,按商品(stock_warehouse_id)进行数量匹配入库,完 成后根据入库单来源(QM/API)自动触发回传。入参为 receiving_ids(数组)和 entry_order_ids(数组),返回匹配汇总、各收货单入库状态、各入库单状态及回传结果。isNeedAuth=true, isNeedLogin=true, isNeedRight=false。" - ], - "type": "added" - }, - { - "version": "2026.04.08-system-02", - "date": "2026-04-08", - "summary": "saveApiConfig 新增 callback_url 可选参数", - "methods": [ - "storeWarehouse.store.saveApiConfig" - ], - "notes": [ - "新增 callback_url 参数(VARCHAR(500),可选),用于 OPEN_API 类型入库单的 回调地址配置。" - ], - "type": "changed" - }, - { - "version": "2026.04.08-system-03", - "date": "2026-04-08", - "summary": "serializeQimenConfig 新增返回 callback_url 字段,影响 list 和 listApiConfig 两个接口", - "methods": [ - "storeWarehouse.store.list", - "storeWarehouse.store.listApiConfig" - ], - "notes": [ - "serializeQimenConfig() 序列化方法新增 callback_url(string)字段。storeWarehouse.store.list 返回的每条记录 api_config 对象中包含 callback_url;storeWarehouse.store.listApiConfig 返回的 list 数组中每条配置包含 callback_url。" - ], - "type": "changed" - }, - { - "version": "2026.04.08-system-04", - "date": "2026-04-08", - "summary": "新增库存移库(库位转移)接口", - "methods": [ - "storage.inventory.transferLocation" - ], - "notes": [ - "新增 storage.inventory.transferLocation 接口,支持批量多商品多库位移库, 包含部分数量移库与全量移库。入参为 warehouse_id(仓库ID)和 transfers 数组(storage_id、target_space_id、quantity),触发 storage_transfer_completed 通知事件, 每条移库记录独立操作日志。isNeedAuth=true, isNeedLogin=true。" - ], - "type": "added" - }, - { - "version": "2026.04.08-system-05", - "date": "2026-04-08", - "summary": "简化移库接口入参,从批量 transfers 数组改为单条移库", - "methods": [ - "storage.inventory.transferLocation" - ], - "notes": [ - "移除 warehouse_id 和 transfers 数组入参,改为扁平的 storage_id + target_space_id + quantity 三个顶层参数。warehouse_id 从库存记录自动获取,接口从批量移库简化为单商品单库位移库。响应结构同步简化为单条结果对象。" - ], - "type": "modified" - }, - { - "version": "2026.04.08-system-06", - "date": "2026-04-08", - "summary": "新增商品库存明细查询接口", - "methods": [ - "stock.warehouse.getStockDetail" - ], - "notes": [ - "新增 stock.warehouse.getStockDetail 接口,按库位/批次维度查询商品库存分布。入参为 stock_id(必填,商品库存ID)和 pagination(可选,含 page/pageSize)。返回 stockItem(商品概要)、storageList(wms_storage 明细数组,含批次号、库位、数 量、锁定数量、生产日期、过期日期等,关联 location_space 库位信息)、pagination 分页信息。isNeedAuth=false, isNeedLogin=true。底层调用 stockStore.getStockDetail,自动校验商品归属当前仓库。" - ], - "type": "added" - }, - { - "version": "2026.04.08-system-07", - "date": "2026-04-08", - "summary": "新增入参 group_by_batch,支持按批次维度切换库存明细聚合方式", - "methods": [ - "stock.warehouse.getStockDetail" - ], - "notes": [ - "新增可选布尔参数 group_by_batch(默认 false)。false 时按库位合并数量,批次相关字段(batch_no, production_date, expiry_date, inbound_time, inbound_order_no, supplier_batch_no)置 null;true 时保持原逻辑返回每条明细。出参结构不变,但 storageList 中批次字段在合并模式下为 null。" - ], - "type": "modified" - }, - { - "version": "2026.04.08-system-08", - "date": "2026-04-08", - "summary": "新增按商品维度移库接口", - "methods": [ - "storage.inventory.transferByProduct" - ], - "notes": [ - "新增 storage.inventory.transferByProduct 接口,按库位+商品查找所有库存记 录合并移动。入参为 space_id(原库位ID)、stock_id(商品SKU ID,即 wms_stock_warehouse.id)、target_space_id(目标库位ID)、quantity(移库数量)。开启批次管理(is_batch_mgmt=Y)的商品会被拒绝,需使用 transferLocation 按库存记录精确移库。复用 storage_transfer_completed 通知事件,操作日志编码 STORAGE_TRANSFER_BY_PRODUCT。isNeedAuth=true, isNeedLogin=true。" - ], - "type": "added" - }, - { - "version": "2026.04.08-system-09", - "date": "2026-04-08", - "summary": "补充 storeWarehouse.store.list 完整 response 输出字段说明,移除 api_config / apiConfig", - "methods": [ - "storeWarehouse.store.list" - ], - "notes": [ - "从返回结果中移除 api_config 和 apiConfig 字段(代码中 delete serialized.api_config / delete serialized.apiConfig),文档 response 补充完整输出字段列表:id, store_id, store_name, warehouse_id, warehouse_name, counterparty_id, counterparty_name, current_subject_role, auth_status, auth_status_label, apply_reason, review_comment, apply_time, review_time, auth_start, auth_end, actual_end, print_quantity, applied_by, reviewed_by, ended_by, remask, use_status, policy_config, is_auth_valid, remaining_days 以及分页和 current_subject 信息。" - ], - "type": "updated" - }, - { - "version": "2026.04.08-system-10", - "date": "2026-04-08", - "summary": "货主列表返回新增 has_qimen_config 布尔字段", - "methods": [ - "storeWarehouse.store.list" - ], - "notes": [ - "storeWarehouse.store.list 返回的 data.list[] 中新增 has_qimen_config(boolean),表示该货主是否已配置奇门。" - ], - "type": "changed" - }, - { - "version": "2026.04.08-system-11", - "date": "2026-04-08", - "summary": "补全 stock.warehouse.search 接口文档,新增 params / response / errors 完整说明", - "methods": [ - "stock.warehouse.search" - ], - "notes": [ - "入参补充 keyword(string,模糊匹配 item_code / item_name / goods_code / barcode)和 store_id(number,按货主筛选)。响应补充 data 数组各字段(id, item_code, goods_code, item_name, sku_property, stock_unit, quantity, locked_quantity, brand_name, item_type, barcodes, store_stock)以及 total。errors 补充 code=0 搜 索失败场景。" - ], - "type": "updated" - }, - { - "version": "2026.04.08-system-12", - "date": "2026-04-08", - "summary": "新增 with_stock / is_batch 参数,支持返回关联库存明细(按库位分 组或按批次逐条)", - "methods": [ - "stock.warehouse.search" - ], - "notes": [ - "入参新增 with_stock(boolean,默认 false,是否返回关联库存数据)和 is_batch(boolean,默认 false,仅 with_stock=true 时生效,按批次明细返回)。响应 data[] 新增 storage[] 字段:is_batch=false 时按库位分组汇总(含 space_id、space、inventory_type、quantity、locked_quantity、available_quantity);is_batch=true 时逐 条返回批次明细(含 id、stock_id、space_id、batch_no、inventory_type、quantity、locked_quantity、available_quantity、production_date、expiry_date、inbound_time、inbound_order_no、supplier_batch_no、created_at、space)。" - ], - "type": "updated" - }, - { - "version": "2026.04.08-system-13", - "date": "2026-04-08", - "summary": "新增 wms_stock_transaction 表和模型", - "methods": [ - "wms_stock_transaction" - ], - "notes": [ - "新增出入库流水记录表 wms_stock_transaction,含 transaction_type(INBOUND/OUTBOUND)、warehouse_id、store_id、stock_id、storage_id、space_id、quantity、batch_no、inventory_type、order_type、order_no、order_id、receiving_id、entry_order_id、operator_id、operator_name、remark 等字段,关联 StockWarehouse 和 Storage 模型。" - ], - "type": "added" - }, - { - "version": "2026.04.08-system-14", - "date": "2026-04-08", - "summary": "quickPutaway 和 matchPutaway 入库时自动写入出入库记录", - "methods": [ - "storage.inventory.quickPutaway", - "storage.inventory.matchPutaway" - ], - "notes": [ - "入库操作完成后自动写入 wms_stock_transaction 记录。quickPutaway 写入 order_type='SCRK'(收货入库),matchPutaway 写入 order_type='MATCH'(匹配入库),均 自动填充 warehouse_id、store_id、stock_id、storage_id、space_id、quantity、batch_no、inventory_type 等字段。" - ], - "type": "updated" - }, - { - "version": "2026.04.08-system-15", - "date": "2026-04-08", - "summary": "新增 storage.inventory.list 出入库记录列表查询接口", - "methods": [ - "storage.inventory.list" - ], - "notes": [ - "出入库记录列表查询,支持 where 条件(transaction_type、stock_id、space_id、store_id、order_type、order_no、inventory_type、operator_name、created_at)、 分页(pagination)、排序(sort)和 group_by_batch 参数。默认合并模式按库位+商品 聚合返回合计数量与记录条数,group_by_batch=true 时返回每条明细含 batch_no、order_no、operator_name 等完整信息。响应均关联 stockItem(item_code、item_name、sku_property、stock_unit)。" - ], - "type": "added" - }, - { - "version": "2026.04.08-system-16", - "date": "2026-04-08", - "summary": "出入库流水记录查询接口从 storage.inventory.list 改名为 storage.transaction.list", - "methods": [ - "storage.transaction.list" - ], - "notes": [ - "将出入库流水记录查询从 storage.inventory.list 迁移到 storage.transaction.list,避免与库存列表概念混淆。功能和参数不变。isNeedAuth=false, isNeedLogin=true, isNeedRight=false。" - ], - "type": "rename", - "module": "storage" - }, - { - "version": "2026.04.08-system-17", - "date": "2026-04-08", - "summary": "新增 storage.inventory.list 库存列表查询接口", - "methods": [ - "storage.inventory.list" - ], - "notes": [ - "新增库存列表查询接口,查询 wms_storage 表。支持 where 条件(stock_id/space_id/store_id/inventory_type/batch_no/inbound_order_no/available_quantity/inbound_time/created_at)、分页、排序。支持 group_by_batch 参数:默认 false 按库位+商 品合并(SUM quantity/locked_quantity/available_quantity),true 返回每条明细含 batch_no/production_date/expiry_date 等。关联 stockItem(商品信息)和 space(库位信息)。isNeedAuth=false, isNeedLogin=true, isNeedRight=false。" - ], - "type": "add", - "module": "storage" - }, - { - "version": "2026.04.08-system-18", - "date": "2026-04-08", - "summary": "移除 storage.entry.create 创建入库单接口", - "methods": [ - "storage.entry.create" - ], - "notes": [ - "不再允许通过 API 创建入库单。入库单仅由快捷入库(quickPutaway)和匹配入库(matchPutaway)等内部流程自动创建。底层 service 实现保留但不再通过 systemMethods 对外暴露。" - ], - "type": "remove", - "module": "storage" - }, - { - "version": "2026.04.08-system-19", - "date": "2026-04-08", - "summary": "移除 storage.entry.addDetail / deleteDetail / detailChange 对外 接口", - "methods": [ - "storage.entry.addDetail", - "storage.entry.deleteDetail", - "storage.entry.detailChange" - ], - "notes": [ - "入库单明细编辑能力不再通过 systemMethods 对外暴露,入库单模块仅保留 list/get/cancel/completeEntry。" - ], - "type": "remove", - "module": "storage" - }, - { - "version": "2026.04.08-system-20", - "date": "2026-04-08", - "summary": "新增 storage.stockout 出库单模块(非订单出库单能力)", - "methods": [ - "storage.stockout.list", - "storage.stockout.toOrder", - "storage.stockout.listItems" - ], - "notes": [ - "新增 storage.stockout.list / toOrder / listItems 接口,作为非订单出库单的主出口(对应奇门 stockout.create)。storage.delivery.* 仅作为兼容转发保留;底层 部分能力仍复用 order 模块。" - ], - "type": "add", - "module": "storage" - }, - { - "version": "2026.04.08-system-21", - "date": "2026-04-08", - "summary": "将 storage.stockout.toOrder 标记为占位接口", - "methods": [ - "storage.stockout.toOrder" - ], - "notes": [ - "storage.stockout.toOrder 当前仅保留方法名用于后续扩展,暂不开放实际逻辑。调用时返回 code=405、message=占位接口,暂未开放。" - ], - "type": "change" - }, - { - "version": "2026.04.09-system-01", - "date": "2026-04-09", - "summary": "storage.entry.cancel 支持批量作废,新增 ids 入参并兼容单条 id", - "methods": [ - "storage.entry.cancel" - ], - "notes": [ - "新增入参 `ids`(number[])以支持批量作废,兼容旧入参 `id`;当同时传入 `ids` 与 `id` 时以 `ids` 为准。", - "参数校验:`ids` 必须为非空数组;非法 ID 或空数组返回 400。", - "业务约束:已完成/已作废/处于不可作废状态的单据不允许作废;批量场景下任一 单据不存在或状态不允许时整体返回 404/400,未执行部分更新。", - "响应说明:单条作废返回字段 `id`(number);批量作废返回字段 `ids`(number[])。", - "已同步更新 methods/system.json(storage.entry.cancel)为 SSOT。" - ] - }, - { - "version": "2026.04.09-system-02", - "date": "2026-04-09", - "summary": "新增基础模块车牌识别接口 index.recognizeLicensePlate", - "methods": [ - "index.recognizeLicensePlate" - ], - "notes": [ - "入参:base64(string,必填)或 imageBase64/image_base64(兼容)", - "响应:返回归一化后的识别对象,包含 licensePlate、plateNumber、color、confidence、requestId、imageSize、rawData", - "错误:400(参数或图片格式/尺寸问题),500(第三方 OCR 调用失败或云密钥未 配置)", - "文档中不包含任何敏感配置;实际腾讯云密钥保留在配置文件中,勿在文档中暴露 。" - ], - "type": "added" - }, - { - "version": "2026.04.09-system-03", - "date": "2026-04-09", - "summary": "收紧基础模块车牌识别接口响应,仅返回 licensePlate 字段", - "methods": [ - "index.recognizeLicensePlate" - ], - "notes": [ - "出参由 {licensePlate, plateNumber, color, confidence, requestId, imageSize, rawData} 调整为 {licensePlate}", - "调用方请仅依赖 licensePlate 字段以适配新版本;历史字段已裁剪且不再保证存 在。", - "文档中未包含任何云密钥或敏感配置信息。" - ], - "type": "changed" - }, - { - "version": "2026.04.10-system-01", - "date": "2026-04-10", - "summary": "订单审核字段由 audit_status 替换为整数字段 step,并添加数据库迁移", - "methods": [ - "order.getreviewOrderlist", - "order.reviewOrder.getreviewOrderlist", - "order.reviewOrder.reviewOrder", - "order.deliveryOrder.getdeliveryOrderlist", - "order.list", - "order.stats" - ], - "notes": [ - "字段变更:order 相关审核字段从字符串/枚举 audit_status 替换为整数 step。", - "step 映射:0=未审核,1=已审核,2=处理中,3=驳回/异常,4=配送中,5=已完成,9=已关闭。", - "reviewOrder 接口在更新 inspection_status 的同时会写入 step 字段。", - "必须执行迁移脚本:20260410150000-replace-audit-status-with-step-on-order-delivery-tables.js" - ], - "type": "changed" - }, - { - "version": "2026.04.13-system-02", - "date": "2026-04-13", - "summary": "stock.warehouse.search 返回新增效期管理字段并保留 is_shelf_life_mgmt", - "methods": [ - "stock.warehouse.search" - ], - "notes": [ - "响应 data[] 中新增字段:inbound_min_days、outbound_min_days、shelf_life_days、remaining_threshold_days(均为 number,单位:天)。", - "保留并说明 is_shelf_life_mgmt 布尔字段(boolean),表示是否启用效期管理(true=启用)。", - "仅更新文档(methods/system.json 与变更记录),代码行为不变。" - ], - "type": "updated" - }, - { - "version": "2026.04.13-system-02", - "date": "2026-04-13", - "summary": "新增 storage.expiry.list 库存有效期列表查询接口", - "methods": [ - "storage.expiry.list" - ], - "notes": [ - "该接口查询 wms_storage,关联 stockWarehouse 和 locationSpace,并按当前仓库与 remaining_threshold_days / expiry_date 过滤。" - ], - "type": "added" - }, - { - "version": "2026.04.13-system-03", - "date": "2026-04-13", - "summary": "新增 storage.inventory.list 库存列表返回效期字段与预警标记", - "methods": [ - "storage.inventory.list" - ], - "notes": [ - "库存列表响应增加生产日期、过期日期、效期预警是否触发字段", - "预警标记仅在商品启用保质期管理且到期日满足阈值条件时为 true" - ], - "type": "updated" - }, - { - "version": "2026.04.14-system-01", - "date": "2026-04-14", - "summary": "更新 index.searchSpace 文档", - "methods": [ - "index.searchSpace" - ], - "notes": [ - "补充 index.searchSpace 的 params/response,按 ctx.user.store_id 作为仓库上下文;keyword 为可选字符串,对 space_code 与 custom_barcode 做 %keyword% 模糊匹配;返回字段 id、space_code、custom_barcode、custom_name,最多 50 条;仅文档同步,无代码变更。" - ], - "type": "updated" - }, - { - "version": "2026.04.16-system-01", - "date": "2026-04-16", - "summary": "基础模块新增快递产品类型查询接口", - "methods": [ - "index.getExpressProductTypeList" - ], - "notes": [ - "新增 index.getExpressProductTypeList,归属基础模块(module=index),用于查询指定快递公司的产品类型列表。", - "对应服务实现:app/service/systems/express.js 中的 getExpressProductTypeList,支持传入 express_code 作为可选筛选参数(source=body)。", - "接口设置为免鉴权(isNeedAuth=false)但需登录(isNeedLogin=true),与 index.getExpressList / index.getPlatformList 一致,优先从缓存读取。" - ], - "type": "added" - }, - { - "version": "2026.04.17-system-01", - "date": "2026-04-17", - "summary": "新增快递管理模块(setting.express)及 5 个接口文档", - "methods": [ - "setting.express.list", - "setting.express.listBase", - "setting.express.create", - "setting.express.checkCodeUnique", - "setting.express.update" - ], - "notes": [ - "新增独立模块组:快递管理模块(module=setting.express),将快递映射管理相关接口独立为一组以便维护。", - "接口实现参考:app/service/systems/setting/express.js(返回结构)与 app/service/systemMethods/setting/express.js(对外方法包装)。", - "接口鉴权与上下文:isNeedAuth=false, isNeedLogin=true;需在请求中传入 Authorization 以携带登录上下文(用于获取当前仓库/货主上下文)。", - "已同步更新 methods/system.json,补充 params/response/errors,保持文档与实现一致。" - ], - "type": "added" - }, - { - "version": "2026.04.17-system-02", - "date": "2026-04-17", - "summary": "setting.express.list 分页入参统一为 pagination", - "methods": [ - "setting.express.list" - ], - "notes": [ - "将 setting.express.list 的分页入参文档从顶层 page/page_size/pageSize 迁移为 pagination 对象,主形态为 pagination;兼容 snake_case 的 page_size 与 camelCase 的 pageSize。", - "文档与当前实现一致:顶层 page/page_size/pageSize 会被归一化到 data.pagination 并转发到系统服务。" - ], - "type": "updated" - }, - { - "version": "2026.04.17-system-03", - "date": "2026-04-17", - "summary": "新增快递接口管理模块(setting.expressInterface)及 4 个接口文档", - "methods": [ - "setting.expressInterface.list", - "setting.expressInterface.create", - "setting.expressInterface.update", - "setting.expressInterface.delete" - ], - "notes": [ - "新增独立模块组:快递接口管理模块(module=setting.expressInterface),对应实现:app/service/systems/setting/expressInterface.js 与对外包装 app/service/systemMethods/setting/expressInterface.js。", - "接口为当前仓库范围(基于 ctx.user.store_id),仓库边界由系统服务强制校验;禁止通过接口指定 warehouse_id/warehouseId。操作需登录(isNeedLogin=true),无需额外鉴权(isNeedAuth=false)。", - "已在 methods/system.json 新增对应接口的 params/response/errors 文档,保持与实现一致。" - ], - "type": "added" - }, - { - "version": "2026.04.18-system-01", - "date": "2026-04-18", - "summary": "补充订单储位分配接口文档:order.storageAllocation.allocateStorage", - "methods": [ - "order.storageAllocation.allocateStorage" - ], - "notes": [ - "新增 order.storageAllocation.allocateStorage:按订单批量分配储位,支持多种入参别名(order_ids/ids/orderId 等)与仓库上下文优先级。", - "响应包含 requested_order_ids, pending_order_ids, allocated_order_ids, shortage_order_ids, skipped_orders, picking_count, stock_lock_summary, storage_lock_summary 等字段,用于前端展示分配结果与不足提示。" - ], - "type": "added" - }, - { - "version": "2026.04.18-system-02", - "date": "2026-04-18", - "summary": "新增 order.pendingOrder.allocateExpressCode:待处理订单模块的批量分配首单快递号(异步接口),复用 express.createWaybillCodePipeline。", - "methods": [ - "order.pendingOrder.allocateExpressCode" - ], - "notes": [ - "异步接口:调用后立即返回 task_id,后台执行运单创建,通过 allocateExpressCodeTaskProgress 查询进度。", - "入参为 ids(订单 ID 数组),sys_platform_code/logistics_code 等由后端从数据库读取。", - "拆单场景请使用 order.pendingOrder.allocateSubOrderNumber。" - ], - "type": "added" - }, - { - "version": "2026.04.18-system-03", - "date": "2026-04-18", - "summary": "将 order.storageAllocation.allocateStorage 迁移到 order.pendingOrder.allocateStorage,并移除原有公开分组。", - "methods": [ - "order.pendingOrder.allocateStorage" - ], - "notes": [ - "将对外入口从 order.storageAllocation.allocateStorage 迁移到 order.pendingOrder.allocateStorage,旧的 order.storageAllocation 分组已从 methods/system.json 中移除。", - "新的对外接口不接受 warehouse_id / warehouseId,仓库上下文由当前登录用户(ctx.user.store_id)提供。", - "本次变更仅同步文档位置与对外方法名,底层实现保留且通过新的 system 方法暴露。" - ], - "type": "changed" - }, - { - "version": "2026.04.19-system-02", - "date": "2026-04-19", - "summary": "新增待处理模块取消分配储位接口 order.pendingOrder.cancelAllocateStorage", - "methods": [ - "order.pendingOrder.cancelAllocateStorage" - ], - "notes": [ - "新增待处理模块取消分配储位接口 `order.pendingOrder.cancelAllocateStorage`,直接对接 `service.systems.orderStorageAllocation.cancelAllocateStorage` 实现。", - "接口现在仅接受订单ID(order_ids),不再接受 allow_storage_location;禁止传入 `warehouse_id/warehouseId`,仓库上下文由当前登录用户的 `store_id` 提供。", - "响应返回标准 { flag, code, message, data } 结构,data 包含取消分配的汇总结果(warehouse_id, requested_order_ids, cancellable_order_ids, skipped_orders, orders, picking_count, storage_unlock_summary, stock_unlock_summary)。" - ], - "type": "added" - }, - { - "version": "2026.04.21-system-01", - "date": "2026-04-21", - "summary": "新增 order.pendingOrder.updateOrderPlatform 方法:批量修改待处理订单平台信息", - "methods": [ - "order.pendingOrder.updateOrderPlatform" - ], - "notes": [ - "通过 code 查找 wms_platform,平台不存在时返回 404 错误。", - "仅操作当前仓库的当前订单表。", - "noNeedRight=true,noNeedAuth=true(isNeedAuth: true 在 spec 中对应权限配置 noNeedAuth=true)。" - ], - "type": "added" - }, - { - "version": "2026.04.21-system-02", - "date": "2026-04-21", - "summary": "新增方法 order.pendingOrder.updateOrderExpress:批量修改待处理订单的快递信息", - "methods": [ - "order.pendingOrder.updateOrderExpress" - ], - "notes": [ - "新增 order.pendingOrder.updateOrderExpress:批量修改待处理订单的快递信息,按 express_code 从仓库快递列表(带缓存)匹配快递项。", - "自定义映射(is_system_setting=true)时,sys_logistics_code/name 写入系统快递编码和名称,logistics_code/name 写入自定义编码和名称;系统快递(is_system_setting=false)时四个字段均写系统快递的 code/name。", - "只操作当前仓库的当前订单表,不处理其他订单表;操作后写入操作日志(ORDER_UPDATE_EXPRESS)。" - ], - "type": "added" - }, - { - "version": "2026.04.21-system-03", - "date": "2026-04-21", - "summary": "新增 order.expectionOrder.resolveException:将待处理异常订单转回正常待处理状态", - "methods": [ - "order.expectionOrder.resolveException" - ], - "notes": [ - "新增 order.expectionOrder.resolveException:批量将 step=3 的异常订单恢复为 step=2 正常待处理状态。", - "入参 ids 为订单ID 正整数数组,不能为空;仅操作当前仓库当前订单表。", - "返回 updated_count(实际更新行数)与 ids(本次操作ID列表)。", - "权限配置:noNeedLogin=false、noNeedRight=true、noNeedLog=false、noNeedAuth=true" - ], - "type": "added" - }, - { - "version": "2026.04.21-system-04", - "date": "2026-04-21", - "summary": "新增 order.pendingOrder.cloneOrder 方法:克隆待处理订单", - "methods": [ - "order.pendingOrder.cloneOrder" - ], - "notes": [ - "支持对 step 0/1/2/3 的待处理订单进行克隆操作。", - "若原订单已分配储位(storage_status=fin),克隆前自动清除已分配库存。", - "原订单取消后(step→9, status→cancel),以原订单业务数据创建新订单,流程状态字段全部重置为初始落库状态。", - "克隆订单明细含 stock_id,新订单 ID 重新绑定。", - "noNeedAuth=true,noNeedRight=true,noNeedLogin=false。" - ], - "type": "added" - }, - { - "version": "2026.04.21-system-06", - "date": "2026-04-21", - "summary": "新增 order.pendingOrder.createOrder:手动创建待处理/待审核订单", - "methods": [ - "order.pendingOrder.createOrder" - ], - "notes": [ - "新增 order.pendingOrder.createOrder:手动创建订单,step 由货主策略 need_order_approval 决定(1→待审核 step=0,0→待处理 step=1)。", - "必填字段:store_id、name、mobile/tel 至少一项、detail_address、items[](含 item_code 和 plan_qty)。", - "delivery_order_code 不传则自动生成(SYS+时间戳+随机4位);logistics_code/sys_platform_code 不传则读货主合约策略 default_express_code/default_platform_code。", - "不做库存锁定,储位分配为独立步骤。操作日志写入 ORDER_CREATE。", - "noNeedRight=true,noNeedAuth=true,noNeedLogin=false。" - ], - "type": "added" - }, - { - "version": "2026.04.21-system-07", - "date": "2026-04-21", - "summary": "新增 Excel 模板下载与批量导入创建订单接口:order.pendingOrder.downloadCreateTemplate 和 order.pendingOrder.importOrdersFromExcel", - "methods": [ - "order.pendingOrder.downloadCreateTemplate", - "order.pendingOrder.importOrdersFromExcel" - ], - "notes": [ - "新增 order.pendingOrder.downloadCreateTemplate:生成 Excel 导入模板,返回 base64 编码的 xlsx 文件,表头中带 * 的列为必填项(橙色背景),可选列为灰色背景,含示例数据行和填写说明工作表。", - "新增 order.pendingOrder.importOrdersFromExcel:接受 base64 编码的 xlsx 文件,按订单号分组,每组调用 createOrder 逻辑创建订单;不中断执行,逐条记录成功/失败结果返回。", - "多行相同订单号的行组成一个完整订单,每行代表一条商品明细;订单头信息(收件人、地址等)取每组第一行。", - "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" - }, - { - "version": "2026.05.08-system-05", - "date": "2026-05-08", - "summary": "order.wave.batchList:新增 source 字段并支持 where.source 过滤,返回 list item 中新增 source 字段", - "methods": [ - "order.wave.batchList" - ], - "notes": [ - "新增 where.source(可选,number)用于按来源过滤:0=普通波次(正常后台操作),1=管理后台策略任务,2=PDA策略任务;不传则不过滤。", - "响应 list 每条记录新增字段 source(number),用于区分波次来源。", - "仅更新文档,业务代码不在此变更范围。" - ], - "type": "updated" - }, - { - "version": "2026.05.09-system-01", - "date": "2026-05-09", - "summary": "新增 order.wave.wavePickTaskCancelSelf;order.wave.waveStrategyList 新增预演计数字段/参数", - "methods": [ - "order.wave.wavePickTaskCancelSelf", - "order.wave.waveStrategyList" - ], - "notes": [ - "新增接口 `order.wave.wavePickTaskCancelSelf`:仅支持单个 `task_id`(number,必填),明确不支持 `task_ids` 批量参数。", - "业务约束:仅允许取消当前登录用户本人创建的拣货任务;若尝试取消非本人创建任务,接口应返回 400 错误(仅允许取消本人创建任务)。", - "返回建议:与现有取消接口风格一致,包含 `cancelled_count`(0/1)、`task_id`、`task_no`(若后端返回)或相应的取消结果汇总。", - "错误码建议:400 参数不合法(task_id 缺失或传了 task_ids);400 仅允许取消本人创建任务;500 取消失败。", - "新增参数:calculate_next_fetch_order_count(number,可选),含别名 calculateNextFetchOrderCount;取值 0=不计算(默认),1=计算并返回每条策略的 next_fetch_order_count,用于前端在策略列表中预览抓取量。", - "新增响应字段:list[*].next_fetch_order_count(number),含义:按当前策略口径预演一次自动抓取时,预计会选中的订单数量;当未开启计算时返回 0。" - ], - "type": "added" - }, - { - "version": "2026.05.11-system-01", - "date": "2026-05-11", - "summary": "新增字段 wave_prefix(策略层波次前缀),并补充 PDA 抓取波次号生成行为说明", - "methods": [ - "order.wave.waveStrategyList", - "order.wave.waveStrategyCreate", - "order.wave.waveStrategyUpdate", - "order.wave.waveStrategyFetchPda" - ], - "notes": [ - "在 wave strategy 对象中新增可选字段 wave_prefix:策略波次前缀,优先于仓库前缀。", - "校验规则:长度 1-5,仅允许 A-Z0-9;保存时会转为大写;为空时回退仓库前缀:团购使用 group_wave_prefix,散单使用 delete_order_wave_prefix。", - "在 order.wave.waveStrategyList 的返回 list[*] 中新增字段 wave_prefix(string)。", - "在 order.wave.waveStrategyCreate / waveStrategyUpdate 的入参中新增可选字段 wave_prefix(string),创建/更新成功后保存为大写且触发策略版本推进。", - "在 order.wave.waveStrategyFetchPda 的行为说明中补充:生成波次号(wave_no)时优先使用策略层 wave_prefix,否则按策略类型回退到仓库前缀;前缀校验同上。" - ], - "type": "updated" - }, - { - "version": "2026.05.15-system-01", - "date": "2026-05-15", - "summary": "仅更新文档:将 setting.express.create 入参与实现对齐(新增 express_code,移除 platform)", - "methods": [ - "setting.express.create" - ], - "notes": [ - "仅同步文档,与实现对齐,未修改任何业务代码或行为" - ], - "type": "updated" - }, - { - "version": "2026.05.15-system-02", - "date": "2026-05-15", - "summary": "新增 storage.report.search:库存流水统计报表,支持按时间闭区间过滤与按库位/按商品聚合", - "methods": [ - "storage.report.search" - ], - "notes": [ - "方法新增:storage.report.search", - "时间过滤为闭区间:created_at >= start_time 且 created_at <= end_time", - "当 where.by_space 为 false(默认)时,按商品+货主聚合(多个库位汇总);当为 true 时按商品+库位返回", - "不返回无流水的商品/键(仅返回在查询区间内出现过流水的数据)" - ], - "type": "added" - }, - { - "version": "2026.05.15-system-03", - "date": "2026-05-15", - "summary": "库存报表模块主入口迁移到 stock.report.search,storage.report.search 保持兼容别名", - "methods": [ - "stock.report.search", - "storage.report.search" - ], - "notes": [ - "新增主入口方法 stock.report.search,沿用既有报表统计口径(时间闭区间、by_space/store_ids、返回字段保持一致)。", - "保留 storage.report.search 作为兼容别名,并在描述中明确建议迁移到 stock.report.search。", - "仅更新 methods 文档配置,不修改业务代码。" - ], - "type": "updated" - }, - { - "version": "2026.05.15-system-04", - "date": "2026-05-15", - "summary": "文档主入口统一为 stock.report.search,storage.report.search 调整为兼容别名简述", - "methods": [ - "stock.report.search", - "storage.report.search" - ], - "notes": [ - "保留 stock.report.search 作为库存报表唯一完整文档入口。", - "storage.report.search 不再维护完整重复字段,仅保留迁移与兼容说明。", - "仅更新 methods 文档配置,不修改业务代码。" - ], - "type": "updated" - }, - { - "version": "2026.05.15-system-05", - "date": "2026-05-15", - "summary": "拆分 storage.report 模块并移除错误 stock.report.search 文档入口", - "methods": [ - "storage.report.search", - "stock.report.search" - ], - "notes": [ - "将库存报表从 storage.inventory 中拆分为独立模块 storage.report,storage.report.search 文档改为主入口语义(不再作为兼容别名)。", - "从 storage.inventory 分组中移除错误的 stock.report.search 文档入口以及兼容别名条目 storage.report.search。", - "最终归属:storage.report.search 属于模块 storage.report;stock.report.search 的文档入口已移除以避免混淆(代码实现保留于 app/service/systemMethods/storage/report.js 的 storage.report.search)。", - "仅修改文档,不修改应用代码实现。" - ], - "type": "updated" - }, - { - "version": "2026.05.15-system-06", - "date": "2026-05-15", - "summary": "storage.report.search 新增排序能力文档说明", - "methods": [ - "storage.report.search" - ], - "notes": [ - "补充 sort 参数:支持 sortField/sort_field、sortOrder/sort_order。", - "补充排序白名单:begin_total、inbound_total、outbound_total、end_total。", - "补充非法排序字段/顺序回退默认排序说明。", - "响应说明补充:已按 sort 规则排序返回。" - ], - "type": "updated" - }, - { - "version": "2026.05.16-system-01", - "date": "2026-05-16", - "summary": "新增 storage.report.export:按与 storage.report.search 相同条件导出库存报表 Excel", - "methods": [ - "storage.report.export" - ], - "notes": [ - "新增方法:storage.report.export,复用 storage.report.search 的 where/sort 查询条件。", - "导出文件包含两个 sheet:汇总、变更记录。", - "用于在统计结果基础上回溯明细流水,提升库存变动追溯效率。" - ], - "type": "added" - }, - { - "version": "2026.05.16-system-02", - "date": "2026-05-16", - "summary": "storage.report.export 改为异步任务 + 新增 exportTaskProgress", - "methods": [ - "storage.report.export", - "storage.report.exportTaskProgress" - ], - "notes": [ - "调用方式调整为两步:先调用 storage.report.export 提交任务并获取 task_id,再调用 storage.report.exportTaskProgress 轮询任务进度。", - "下载链接获取方式:当 status=success 时,从 exportTaskProgress 响应的 download_url 字段获取导出文件地址。", - "任务状态值补充:submitted/running/success/failed/not_found。" - ], - "type": "updated" - }, - { - "version": "2026.05.16-system-03", - "date": "2026.05.16", - "summary": "同步 setting.expressInterface.create/update 入参与系统快递编码映射规则", - "methods": [ - "setting.expressInterface.create", - "setting.expressInterface.update" - ], - "notes": [ - "补充入参:sys_express_code、weight_type、address、town_name、ispickup、shipperno,并保留既有字段。", - "在参数说明补充 camelCase 别名支持:sysExpressCode、weightType、townName、isPickup、shipperNo 等。", - "同步约束变化:不再因同仓快递编码重复或平台重复直接返回 409;当 express_code 无法匹配系统快递编码时返回 400,文案为 express_code 未匹配到系统快递编码。" - ], - "type": "updated" - }, - { - "version": "2026.05.17-system-05", - "date": "2026-05-17", - "summary": "同步 storage.receiving.addDetail 的参数与返回值(从实现提取)", - "methods": [ - "storage.receiving.addDetail" - ], - "notes": [ - "补充 receiving_id 入参说明", - "补充返回的 details 数组与 selectId 字段", - "补充可能的错误码:404/400/500" - ], - "type": "updated" - }, - { - "version": "2026.05.17-system-06", - "date": "2026-05-17", - "summary": "重新同步 addDetail 文档", - "methods": [ - "storage.receiving.addDetail" - ], - "notes": [ - "再次从实现代码核对并补充参数/返回值/错误码,确保文档与实现一致", - "仅同步文档,不修改业务代码" - ], - "type": "updated" - }, - { - "version": "2026.05.17-system-07", - "date": "2026-05-17", - "summary": "addDetail 新增可选 item 入参并兼容空白创建链路", - "methods": [ - "storage.receiving.addDetail" - ], - "notes": [ - "item 有值时按传入字段创建(服务端覆盖 receiving_id 与 creator_id)", - "兼容不传 item 的空白创建链路;item.children 需覆盖关键字段(有则写、无则补齐)。" - ], - "type": "updated" - }, - { - "version": "2026.05.17-system-10", - "date": "2026-05-17", - "summary": "调整 storage.receiving.getReceivingDetail 库位字段输出语义:space_id 改为展示名称并补充兼容字段", - "methods": [ - "storage.receiving.getReceivingDetail" - ], - "notes": [ - "将 receiving.details.*.space_id 定义为展示名称(string|null),优先 custom_space_name,其次 space_name,不再作为原始数值ID文档语义。", - "新增并明确 receiving.details.*.space_id_raw(number|null)用于保留原始库位ID,兼容旧调用方。", - "补充 receiving.details.*.space_name(库位名称/编码)与 receiving.details.*.custom_space_name(自定义名称,可空)字段说明。" - ], - "type": "updated" - }, - { - "version": "2026.05.17-system-11", - "date": "2026-05-17", - "summary": "补充 subject_config.enable_external_express_code 字段文档与默认值语义", - "methods": [ - "store.createStore", - "store.createWarehouse", - "setting.warehouse.getSettings", - "setting.warehouse.saveSettings" - ], - "notes": [ - "在 store.createStore 与 store.createWarehouse 的 subject_config 入参中新增字段:enable_external_express_code(boolean),默认 false;开启后允许按外部系统传入的快递编码进行处理(如无匹配仍以业务校验为准)。", - "此 change 同时用于说明将在 setting.warehouse.getSettings / saveSettings 中补充该字段的文档说明(后续 doc-only 写入)。" - ], - "type": "updated", - "module": "store" - }, - { - "version": "2026.05.17-system-12", - "date": "2026-05-17", - "summary": "storeWarehouse.store 策略配置文档新增 enable_external_express_code 字段说明(向后兼容)", - "methods": [ - "storeWarehouse.store.getPolicyConfig", - "storeWarehouse.store.savePolicyConfig" - ], - "notes": [ - "在 getPolicyConfig / savePolicyConfig 的出参说明中补充 data.policy_config.enable_external_express_code 字段,明确为 flag(0=关闭,1=开启),默认 0。", - "在 savePolicyConfig 的入参说明中补充 policy_config.enable_external_express_code 字段定义。", - "本次为向后兼容的文档增强:新增可选策略字段说明,不影响现有调用。" - ], - "type": "updated" - }, - { - "version": "2026.05.19-system-01", - "date": "2026-05-19", - "summary": "补充 storage.entry.list 的 expense_record 筛选语义与未迁移环境错误提示", - "methods": [ - "storage.entry.list" - ], - "notes": [ - "在 where 参数说明中补充 expense_record 字段语义(费用是否记录)及 eq/in 支持。", - "明确 true/false、1/0、y/n、yes/no 的归一化规则与等价写法示例。", - "补充未完成表结构迁移时可能返回 400 及错误提示文案。" - ], - "type": "updated" - }, - { - "version": "2026.05.20-system-01", - "date": "2026-05-20", - "summary": "同步 order.recheckOrder.scanOrder 返回结构,补充 cart_match_view 语义化视图说明", - "methods": [ - "order.recheckOrder.scanOrder" - ], - "notes": [ - "新增返回字段:match_type(waybill/cart)与 cart_match_view(仅 cart 命中返回)。", - "cart_match_view 包含通用子字段:mode_code / mode_name / view_type / task;当车号命中时按 pick_mode 返回语义化结构:mode 1/5 返回 groups,mode 2 返回 orders,mode 3 返回 pick_groups,mode 4 返回 box_groups。" - ], - "type": "updated" - }, - { - "version": "2026.05.22-system-01", - "date": "2026-05-22", - "summary": "新增 index.getPlatformOauthLink 文档,补充平台授权链接接口说明", - "methods": [ - "index.getPlatformOauthLink" - ], - "notes": [ - "入参支持 code、platform_code、platformCode 三种平台编码字段别名。", - "当前仅支持 PDD;成功返回 data.platform_code、data.oauth_link 和 code=200,其他平台返回 code=400。", - "仅通过文档脚本同步 methods/system.json 与 methods/changes/system.json,不修改业务代码。" - ], - "type": "added", - "module": "index" - }, - { - "version": "2026.05.22-system-02", - "date": "2026-05-22", - "summary": "更新 index.getPlatformOauthLink 文档,补充仓库上下文、预占记录与错误说明", - "methods": [ - "index.getPlatformOauthLink" - ], - "notes": [ - "补充真实行为:从 ctx.user.store_id 读取当前仓库 ID,从 wms_platform.auth_base_url 读取授权基础地址,并在 wms_shops 创建平台授权预占记录。", - "补充 oauth_link 细节:追加 client_id、redirect_uri(配置非空时)以及长查询参数 wms_authorization_reservation_code,对应唯一 auth_random_code。", - "补充常见错误:平台编码为空、仓库上下文缺失、平台不存在、授权基础地址缺失/格式错误、不支持的平台,以及预占记录创建失败。" - ], - "type": "updated", - "module": "index" - }, - { - "version": "2026.05.22-system-03", - "date": "2026-05-22", - "summary": "同步 index.getPlatformOauthLink 当前实现:裸码入库与 state 拼接规则", - "methods": [ - "index.getPlatformOauthLink" - ], - "notes": [ - "补充真实行为:从 ctx.user.store_id 读取当前仓库,从 wms_platform.auth_base_url 读取基础授权链接,并优先复用 wms_shops 中 status=0 的未授权记录。", - "明确 auth_random_code 当前以裸码保存;若复用到历史带前缀记录,会先去掉 platformOauthReservationCodePrefix 后再回写。", - "更新 oauth_link 说明:state 由“前缀 + 平台编码 + '_' + 裸码”组成并整体 URL 编码后直接拼接到基础授权链接后,例如 xxxxx_PDD_;同时移除已不存在的基础地址格式错误/不支持平台错误描述。" - ], - "type": "updated", - "module": "index" - }, - { - "version": "2026.05.22-system-04", - "date": "2026-05-22", - "summary": "修正 index.getPlatformOauthLink 文档中的残留平台限制描述", - "methods": [ - "index.getPlatformOauthLink" - ], - "notes": [ - "移除 index.getPlatformOauthLink 参数与返回字段中残留的“当前仅支持 PDD”描述,避免与当前实现不一致。", - "保留授权链接仅依赖平台已配置基础授权链接模式的说明,不再把示例平台编码误写成实现限制。" - ], - "type": "updated", - "module": "index" - }, - { - "version": "2026.05.22-system-05", - "date": "2026-05-22", - "summary": "新增 index.getShopList 文档,并同步 custom_name 与店铺列表脱敏返回规则", - "methods": [ - "index.getShopList" - ], - "notes": [ - "新增 index.getShopList:接口依赖当前登录仓库上下文 ctx.user.store_id,不接受额外业务入参,缺少仓库时返回 400:未识别到当前仓库。", - "补充真实返回结构:data.list 为数组,包含 id、warehouse_id、platform_code、shop_name、custom_name、status、auth_expire_at、token_expires_at、refresh_token_expires_at、scope、created_at、updated_at 以及脱敏后的 owner_id、access_token、refresh_token、auth_random_code。", - "同步脱敏规则:owner_id 非空且长度大于 5 时返回前 3 位 + *** + 后 2 位,长度小于等于 5 时返回 ***;access_token、refresh_token、auth_random_code 非空时固定返回 ***,空值返回 null。", - "仅通过文档脚本同步 methods/system.json 与 methods/changes/system.json,不修改任何业务代码。" - ], - "type": "added", - "module": "index" - }, - { - "version": "2026.05.22-system-06", - "date": "2026-05-22", - "summary": "新增 index.getShopExpressList 文档,补充店铺快递列表统一返回结构", - "methods": [ - "index.getShopExpressList" - ], - "notes": [ - "按 ctx.user.store_id 校验店铺归属,仅允许查询当前登录仓库下的店铺。", - "服务端按店铺所属平台拉取并收敛快递签约/电子面单可用列表,统一返回前端消费结构。", - "未接入平台当前返回空列表;若店铺缺少授权 access_token,则返回 400:店铺未授权。", - "仅文档同步,不改业务代码。" - ], - "type": "added", - "module": "index" - }, - { - "version": "2026.05.22-system-07", - "date": "2026-05-22", - "summary": "同步快递接口文档:is_share 仅展示不可编辑", - "methods": [ - "setting.expressInterface.list", - "setting.expressInterface.create", - "setting.expressInterface.update" - ], - "notes": [ - "create/update 不再接受 is_share", - "list 仍可返回 is_share 作为展示信息", - "仅文档同步,不改业务代码" - ], - "type": "updated", - "module": "setting.expressInterface" - }, - { - "version": "2026.05.22-system-08", - "date": "2026-05-22", - "summary": "同步快递接口列表文档,移除未返回字段说明", - "methods": [ - "setting.expressInterface.list" - ], - "notes": [ - "根据 app/service/systems/setting/expressInterface.js 的 list() 查询字段与 normalizeInterfaceRow() 返回结构,同步 setting.expressInterface.list 不返回 token。", - "按当前实现清理 response.children 中未返回的 share_id、can_use_count 字段说明。", - "保留 is_share,并明确其仅用于展示,不作为编辑入参。" - ], - "type": "updated", - "module": "setting.expressInterface" - }, - { - "version": "2026.05.22-system-09", - "date": "2026-05-22", - "summary": "index.getShopList 支持按平台编码筛选店铺", - "methods": [ - "index.getShopList" - ], - "notes": [ - "index.getShopList 兼容 platform_code 与 platformCode 两种传参方式,服务端按 platform_code、platformCode 顺序读取首个 trim 后非空值作为平台筛选条件。", - "未传平台参数时返回当前登录仓库下全部已授权店铺;传入非空平台编码时仅返回该平台的已授权店铺。", - "本次仅补充筛选条件文档,不影响返回结构、排序规则与 owner_id/access_token/refresh_token/auth_random_code 的脱敏规则。", - "仅通过文档脚本同步 methods/system.json 与 methods/changes/system.json,不修改任何业务代码。" - ], - "type": "updated", - "module": "index" - }, - { - "version": "2026.05.22-system-10", - "date": "2026-05-22", - "summary": "快递接口配置新增 shop_id 字段", - "methods": [ - "setting.expressInterface.create", - "setting.expressInterface.update", - "setting.expressInterface.list" - ], - "notes": [ - "create/update 支持 shop_id/shopId(兼容 snake_case 与 camelCase),为店铺 ID,未传或空值按 null 处理。", - "list 返回 shop_id 字段,列表 where 支持按 shop_id 过滤。" - ], - "type": "updated" - }, - { - "version": "2026.05.22-system-11", - "date": "2026-05-22", - "summary": "调整快递接口列表排序规则", - "methods": [ - "setting.expressInterface.list" - ], - "notes": [ - "setting.expressInterface.list 改为按 weight ASC, id DESC 排序;优先按权重排序,权重相同再按 id 倒序。", - "本次仅同步该接口排序说明,不影响返回结构。" - ], - "type": "updated", - "module": "setting.expressInterface" - }, - { - "version": "2026.05.22-system-12", - "date": "2026-05-22", - "summary": "index.getShopExpressList 返回新增系统快递编码", - "methods": [ - "index.getShopExpressList" - ], - "notes": [ - "data.list[*] 新增 sys_express_code 字段,由平台快递编码 wp_code 映射系统快递编码,未匹配时返回空字符串。", - "补充 data.list[*].wp_name 说明:由系统快递基础表根据平台快递编码映射得到名称,未匹配时返回空字符串。", - "原有请求参数、鉴权方式与返回主结构保持不变。", - "仅文档同步,不改业务代码。" - ], - "type": "updated", - "module": "index" - }, - { - "version": "2026.05.23-system-01", - "date": "2026-05-23", - "summary": "补充快递接口列表 is_system_express_code 返回字段说明", - "methods": [ - "setting.expressInterface.list" - ], - "notes": [ - "在 setting.expressInterface.list 的 response.children 中补充 is_system_express_code 字段说明。", - "该字段表示当前行 express_code 是否为系统快递编码;不是系统快递编码返回 0,否则返回 1。", - "仅文档同步,不改业务代码。" - ], - "type": "updated", - "module": "setting.expressInterface" - }, - { - "version": "2026.05.23-system-02", - "date": "2026-05-23", - "summary": "完善 index.getExpressList 文档:补充过滤规则、返回字段与仓库维度行为", - "methods": [ - "index.getExpressList" - ], - "notes": [ - "补充 `systemOnly`、`express_code`、`expressCode` 的真实入参语义,明确真值识别规则与字段优先级。", - "补充默认模式、系统模式、按快递编码过滤模式下的返回差异,说明当前登录仓库维度来自 `ctx.user.store_id`。", - "补充 `data[*]` 各字段含义,明确系统基础快递与仓库自定义快递编码的差异字段。", - "仅文档同步,不修改业务代码。" - ], - "type": "updated", - "module": "index" - }, - { - "version": "2026.05.24-system-01", - "date": "2026-05-24", - "summary": "同步 index.getExpressList 文档:移除 expressCode 别名并明确 express_code 筛选语义", - "methods": [ - "index.getExpressList" - ], - "notes": [ - "移除 index.getExpressList 文档中的 expressCode 驼峰别名参数,仅保留 express_code。", - "明确当 systemOnly=false 且传入 express_code 时,接口按自定义映射记录中的系统快递编码字段 express_code 过滤,而不是按自定义 code 过滤。", - "保留 systemOnly=true 按系统快递编码过滤系统基础快递列表,以及默认合并逻辑、缓存优先、仓库维度来源不变的说明。" - ], - "type": "updated" - }, - { - "version": "2026.05.24-system-02", - "date": "2026-05-24", - "summary": "新增 index.getCainiaoStfTemplates 接口文档并明确模板返回语义", - "methods": [ - "index.getCainiaoStfTemplates" - ], - "notes": [ - "新增无参接口 index.getCainiaoStfTemplates:从当前仓库首个已授权 TB 店铺发起 cainiao.waybill.ii.search 查询菜鸟 STF 模板。", - "补充返回结构说明:data.platform_code 固定为 TB;data.list 返回模板数组并包含 template_id/template_name/template_url/cp_code/wp_code 字段。", - "明确模板列表为宽松结构解析并按 template_id/template_name/template_url 核心语义去重。", - "补充错误码说明:未识别仓库返回 400;当前仓库无已授权 TB 店铺返回 404。" - ], - "type": "added" - }, - { - "version": "2026.05.24-system-03", - "date": "2026-05-24", - "summary": "调整 index.getCainiaoStfTemplates 为免登录/免鉴权接口", - "methods": [ - "index.getCainiaoStfTemplates" - ], - "notes": [ - "将 index.getCainiaoStfTemplates 的 isNeedLogin 调整为 false,接口改为免登录访问。", - "保持 isNeedAuth=false,并同步免权限拦截配置,避免登录态与鉴权拦截。", - "该接口仍为无请求参数,headers 调整为空数组。" - ], - "type": "updated", - "module": "index" - }, - { - "version": "2026.05.24-system-04", - "date": "2026-05-24", - "summary": "调整 index.getCainiaoStfTemplates 为公共无参模板查询接口", - "methods": [ - "index.getCainiaoStfTemplates" - ], - "notes": [ - "index.getCainiaoStfTemplates 改为公共无参查询,不再依赖当前仓库、登录态或店铺授权。", - "接口直接调用 requestTbWaybillSearch({ cpCode: '' }) 查询公共模板,返回 data.platform_code='TB' 与模板数组。", - "requestTbWaybillSearch 支持 accessToken 缺失时不下发 session,因此该接口不再依赖 session。" - ], - "type": "updated" - }, - { - "version": "2026.05.24-system-05", - "date": "2026-05-24", - "summary": "同步 index.getCainiaoStfTemplates 改用淘宝标准模板公共接口", - "methods": [ - "index.getCainiaoStfTemplates" - ], - "notes": [ - "index.getCainiaoStfTemplates 改为调用淘宝开放平台 cainiao.cloudprint.stdtemplates.get,不再复用 cainiao.waybill.ii.search。", - "接口不需要用户授权,不下发 session,继续使用 https://eco.taobao.com/router/rest 与 TOP 公共签名参数。", - "模板列表改为从 cainiao_cloudprint_stdtemplates_get_response.result.datas[*].standard_templates[*] 做宽松兼容解析,统一返回 template_id/template_name/template_url/cp_code/wp_code。" - ], - "type": "updated" - }, - { - "version": "2026.05.24-system-06", - "date": "2026-05-24", - "summary": "新增 index.getPrintPlatformList 接口文档并明确打印平台下拉返回结构", - "methods": [ - "index.getPrintPlatformList" - ], - "notes": [ - "新增 index.getPrintPlatformList 文档,说明该接口供快递接口新增/编辑页下拉选择使用。", - "补充接口行为:仅返回未删除且状态为 ACTIVE 的打印平台,不分页,按 platform_name 与 id 升序返回。", - "补充 data[*] 返回字段说明,明确 code/name/value/label/platform_code/platform_name/status/remark 的含义。", - "仅文档同步,不修改业务代码。" - ], - "type": "added", - "module": "index" - }, - { - "version": "2026.05.24-system-07", - "date": "2026-05-24", - "summary": "新增 index.getPrintPlatformTemplateList 文档,明确 express_code 必填与模板过滤语义", - "methods": [ - "index.getPrintPlatformTemplateList" - ], - "notes": [ - "新增 index.getPrintPlatformTemplateList 方法文档,补充 platform_code 与 express_code 入参,其中 express_code 标记为必填。", - "明确业务语义:接口按 platform_code(默认 CAINIAO)定位 wms_express 中对应打印平台字段,并使用 express_code 过滤模板结果后返回。", - "补充返回结构 data.platform_code / data.express_code / data.responseData,说明未实现平台返回空对象。", - "仅文档同步,不修改业务代码。" - ], - "type": "added", - "module": "index" - }, - { - "version": "2026.05.25-system-01", - "date": "2026-05-25", - "summary": "新增 index.polyapiAuthorizeUrl 接口文档并标注免登录免鉴权特征", - "methods": [ - "index.polyapiAuthorizeUrl" - ], - "notes": [ - "新增基础模块方法 index.polyapiAuthorizeUrl,说明其为公共无参接口。", - "明确接口固定调用菠萝派 Differ.JH.BuildeAuthorizeUrl,返回体中以 data.respone 原样包裹上游响应。", - "同步标注 isNeedLogin=false、isNeedAuth=false,headers 为空数组。" - ], - "type": "added" - }, - { - "version": "2026.05.25-system-02", - "date": "2026-05-25", - "summary": "新增店铺模块相关接口文档(shops.list/add/del/edit)及授权会话接口 shops.GetAuthorizeSessionKey", - "methods": [ - "shops.list", - "shops.add", - "shops.del", - "shops.edit", - "shops.GetAuthorizeSessionKey" - ], - "notes": [ - "同步实现:shops.list 支持 where 分页与 quickWhere 快速搜索;shops.add/edit 校验 platform_code 存在且为 ACTIVE,custom_name 必填且长度限制;shops.del 为软删除,会返回 deleted=true 并清空敏感字段,若存在快递接口引用返回 409;shops.GetAuthorizeSessionKey 对 PDD/CAINIAO 平台生成预占码并返回 authorize_url,其他平台返回 501。", - "字段命名兼容说明:接口实现兼容 snake_case 与 camelCase 入参,文档以 snake_case 为主并注明兼容性。" - ], - "type": "added" - }, - { - "version": "2026.05.25-system-03", - "date": "2026-05-25", - "summary": "同步 shops.add 去入参化:移除 shop_name 入参并明确由授权后获取店铺名称", - "methods": [ - "shops.add" - ], - "notes": [ - "shops.add 入参移除 shop_name(及同义传参语义),仅保留 custom_name 与 platform_code 为关键请求字段。", - "补充说明:新增时 shop_name 由服务端生成 PENDING_* 占位名,后续以授权回调同步真实店铺名称。", - "仅文档同步,不修改任何业务代码。" - ], - "type": "updated", - "module": "shops" - }, - { - "version": "2026.05.28-system-02", - "date": "2026-05-28", - "summary": "新增 method: order.print.unlockWavePlatformPrintDataByGroup,按分组解锁波次平台打印锁", - "methods": [ - "order.print.unlockWavePlatformPrintDataByGroup" - ], - "notes": [ - "新增方法:order.print.unlockWavePlatformPrintDataByGroup,用于按分组规则批量解锁波次内被锁定的订单(将 print_lock_status 设为 'none')。", - "入参说明:group_type 默认为 platform_express(支持 platform、platform_express、order),unlock_scope 默认为 group(支持 group、wave);groups 为必须项,元素对象可包含 wave_id、platform、sys_logistics_code、order_ids 等字段。", - "返回说明:返回 summary(解锁统计)、unlocked_order_ids、unlocked_orders、ext.missing_wave_ids、ext.filtered_wave_ids 等字段。", - "实现参考:app/service/systemMethods/order/print.js 与 app/service/systems/order_print.js 的 unlockWavePlatformPrintDataByGroup 实现,相关单元测试位于 test/app/controller/system.order.print.unlockByGroup.test.js 与 test/app/service/systems/order_print.unlockWavePlatformPrintDataByGroup.test.js。" - ], - "type": "updated" - }, - { - "version": "2026.05.28-system-03", - "date": "2026-05-28", - "summary": "新增 order.updateExpressWeighingWeight 方法文档并补充单/多运单称重写入规则", - "methods": [ - "order.updateExpressWeighingWeight" - ], - "notes": [ - "新增 order.updateExpressWeighingWeight 入参说明:order_id、waybill_code、weighing_weight。", - "明确规则:单运单订单忽略 waybill_code 并直接更新唯一运单;多运单订单必须传 waybill_code 且需匹配订单下运单。", - "补充成功返回字段:order_id、waybill_code、weighing_weight。", - "补充错误码:400(参数校验与多运单缺失运单号)、404(运单记录不存在或未匹配)、500(模型未初始化或更新失败)。", - "仅通过文档脚本同步 methods/system.json 与 methods/changes/system.json,不修改业务代码。" - ], - "type": "added", - "module": "order.index" - }, - { - "version": "2026.05.28-system-01", - "date": "2026-05-28", - "summary": "新增包材相关 methods(create/update/delete/get),并提供 list 兼容说明", - "methods": [ - "setting.packageMaterial.create", - "setting.packageMaterial.update", - "setting.packageMaterial.delete", - "setting.packageMaterial.get", - "setting.packageMaterial.list" - ], - "notes": [ - "实现参考:app/service/systems/setting/packageMaterial.js", - "list 为兼容别名,内部转发至 get,建议新接入方改用 get" - ], - "type": "updated" - }, - { - "version": "2026.05.28-system-04", - "date": "2026-05-28", - "summary": "Add packageSupplier methods (create/update/delete/get) with list alias note", - "methods": [ - "setting.packageSupplier.create", - "setting.packageSupplier.update", - "setting.packageSupplier.delete", - "setting.packageSupplier.get", - "setting.packageSupplier.list" - ], - "notes": [ - "Reference implementation: app/service/systems/setting/packageSupplier.js", - "list is a compatibility alias; prefer get" - ], - "type": "updated" - }, - { - "version": "2026.05.28-system-05", - "date": "2026-05-28", - "summary": "新增 order.bindExpressPackageMaterial 方法文档,支持按订单运单绑定包材", - "methods": [ - "order.bindExpressPackageMaterial" - ], - "notes": [ - "新增 order.bindExpressPackageMaterial 入参说明:order_id、waybill_code、package_material_code(均必填)。", - "补充行为说明:按订单ID+运单号匹配 wms_order_express,按包材编码匹配包材并绑定 package_material_id 与 package_material_name_snapshot。", - "补充成功返回字段:order_id、waybill_code、package_material_id、package_material_name_snapshot、package_material_code。", - "补充错误码:400 参数错误、404 包材编码不存在、404 订单运单记录不存在、500 绑定包材失败。", - "仅通过文档脚本同步 methods/system.json 与 methods/changes/system.json,不修改业务代码。" - ], - "type": "added", - "module": "order.index" - }, - { - "version": "2026.05.29-system-01", - "date": "2026-05-29", - "summary": "新增 order.export 与 order.exportTaskProgress:订单导出异步任务与进度查询", - "methods": [ - "order.export", - "order.exportTaskProgress" - ], - "notes": [ - "order.export:提交导出任务,入参支持 table_type/tableType(枚举 current/history/dispatch/outsourced,兼容订单模块别名)与 module/module_name,where/sort 语义与 order.list 一致。接口提交后立即返回 task_id,后台异步执行导出,导出进度与结果通过 order.exportTaskProgress 查询。", - "order.exportTaskProgress:按 task_id 查询任务进度,返回 task_id、status、progress、current_count、total_count、message、error、download_url、update_time;任务上传完成后 download_url 返回可下载链接,未找到时 status=not_found。" - ], - "type": "added", - "module": "order.index" - }, - { - "version": "2026.05.30-system-01", - "date": "2026-05-30", - "summary": "新增 print.notifyLock(及 notify_lock 兼容别名),并补充 print.send 写入订单操作日志的行为说明", - "methods": [ - "print.notifyLock", - "print.notify_lock", - "print.send" - ], - "notes": [ - "新增 print.notifyLock:入参支持 order_ids/orderIds、waveGroups、data.waveGroups(至少一类提供订单 ID);仅执行订单锁定流程,不发送打印任务;写打印任务日志 + 订单操作日志;返回 locked_count、order_ids_count、order_ids、source;错误:无有效订单ID(400)、锁定失败(500)。", - "补充 print.send 文档:说明接口在执行打印任务记录的同时会写入订单操作日志(记录打印相关操作)。", - "新增兼容别名 print.notify_lock:文档说明等价转调到 print.notifyLock。" - ], - "type": "updated", - "module": "print" - }, - { - "version": "2026.06.03-system-01", - "date": "2026-06-03", - "summary": "同步 pick.query 文档为 keyword 任务化语义并补充冲突错误码", - "methods": [ - "pick.query" - ], - "notes": [ - "入参由 waybill_code/full_display 统一为 keyword(支持运单号或波次号)。", - "成功返回调整为 task_id/status/tip,status 取值 existing 或 created。", - "补充 409 冲突语义:波次已有他人活动任务时返回任务归属信息。" - ], - "type": "updated" - }, - { - "version": "2026.06.03-system-02", - "date": "2026-06-03", - "summary": "更新 pick.wavePickTaskDetail:增加快递号/储位分配前置校验并返回 action+order_ids", - "methods": [ - "pick.wavePickTaskDetail" - ], - "notes": [ - "新增前置校验:任务内若存在未分配快递号订单,返回 400,data.action=assign_express,data.order_ids 为未分配订单ID列表。", - "新增前置校验:任务内若存在未分配储位订单,返回 400,data.action=assign_storage,data.order_ids 为未分配订单ID列表。", - "保留原有权限校验与详情结构,仅补充分配校验失败分支的返回约定。" - ], - "type": "updated" - }, - { - "version": "2026.06.03-system-03", - "date": "2026-06-03", - "summary": "更新 order.wave.batchList:新增同步状态输出与筛选 sync_assignment_status", - "methods": [ - "order.wave.batchList" - ], - "notes": [ - "新增返回字段语义:list[].sync_assignment_status,取值为未同步/部分同步/已同步/同步异常。", - "新增筛选入参 where.sync_assignment_status,支持 unsynced/partially_synced/synced 英文枚举。", - "同步状态筛选规则与分配状态一致:error 并入 unsynced 过滤集合。" - ], - "type": "updated" - }, - { - "version": "2026.06.03-system-04", - "date": "2026-06-03", - "summary": "更新拣货中间态流程文档:wavePickTaskDetail 增加完成标记,并新增中间态/完全提交接口", - "methods": [ - "pick.wavePickTaskDetail", - "pick.wavePickTaskSubmit", - "pick.wavePickTaskComplete" - ], - "notes": [ - "更新 pick.wavePickTaskDetail 返回:新增 task.is_completed、task.progress(total_orders/picked_orders/pending_orders)以及顶层 is_completed。", - "新增 pick.wavePickTaskSubmit:支持保存中间态 payload 到任务 ext_json.pick_intermediate,并返回当前完成状态与进度。", - "新增 pick.wavePickTaskComplete:支持 mode=1 全部确认与 mode=2 部分确认(order_ids),返回 confirmed_order_ids 与最新进度。" - ], - "type": "updated" - }, - { - "version": "2026.06.03-system-05", - "date": "2026-06-03", - "summary": "拣货车能力拆分为一级模块 pickCart:扫码查询、任务绑车、CRUD、编码查重", - "methods": [ - "pickCart.scan", - "pickCart.bindTaskCart", - "pickCart.create", - "pickCart.update", - "pickCart.delete", - "pickCart.detail", - "pickCart.list", - "pickCart.codeDuplicateCheck" - ], - "notes": [ - "拣货车能力独立为一级模块 pickCart,不再挂在 pick 模块下。", - "新增 pickCart.scan:PDA 按 cart_code 扫码查询拣货车信息,用于进入任务绑定流程。", - "新增 pickCart.bindTaskCart:支持按 cart_id/cart_code 将拣货车绑定到指定拣货任务,若车已绑定其他活动任务则返回冲突。", - "新增 pickCart.create/pickCart.update/pickCart.delete/pickCart.detail/pickCart.list:补齐拣货车增删查改与分页查询能力。", - "新增 pickCart.codeDuplicateCheck:支持 exclude_cart_id 排除自身,供编辑场景做非自身重复校验;拣货车编码在当前仓库内不可重复。" - ], - "type": "updated" - }, - { - "version": "2026.06.03-system-06", - "date": "2026-06-03", - "summary": "更新 order.wave.batchList:新增 only_todo、复核状态聚合与复核筛选", - "methods": [ - "order.wave.batchList" - ], - "notes": [ - "新增入参 only_todo(默认 0):传 1/true 时仅返回仍有未复核订单的波次(unreviewed_order_count > 0)。", - "新增返回字段:list[].unreviewed_order_count(未复核订单数)与 list[].review_assignment_status(未复核/部分复核/已复核)。", - "新增 where.review_assignment_status 筛选,支持 unreviewed/partially_reviewed/reviewed 英文枚举。" - ], - "type": "updated", - "module": "order.wave" - }, - { - "version": "2026.06.04-system-01", - "date": "2026-06-04", - "summary": "裁剪 pick.wavePickTaskDetail 返回:团购小波次(pick_mode=1)不返回 picking_details 字段以减少带宽", - "methods": [ - "pick.wavePickTaskDetail" - ], - "notes": [ - "在 picking_details 字段 description 中补充:当 pick_mode=1(团购小波次)时该字段不返回,减少带宽浪费;其他 pick_mode(2/3/4/5)正常返回 picking_details。", - "在接口 description 中补充该裁剪行为的说明。", - "picking_summary、picking_view、boxes 等字段不受影响,pick_mode=1 时仍正常返回。" - ], - "type": "updated" - }, - { - "version": "2026.06.04-system-02", - "date": "2026-06-04", - "summary": "完善 index.getPlatformList 文档:补充入参 systemOnly/full、响应字段及错误码 500", - "methods": [ - "index.getPlatformList" - ], - "notes": [ - "补充入参说明:systemOnly(可选,支持 is_system 别名,真值识别 true/1/'1'/'true')、full(可选,真值识别同上,为 true 时返回全量表字段与 route_platform_code/platid 等扩展信息)", - "补充响应 data 数组每项字段:code、name、value、label、platform_code、platform_name、default_express_interface、is_system_setting、id(仅仓库自定义项)、alias(仅仓库自定义项)、full 模式扩展字段说明", - "说明合并逻辑:系统平台在前,仓库自定义在后,同 code 仅保留首条(系统优先);systemOnly=true 仅返回系统平台", - "补充缓存策略:优先读缓存,key 格式为 platform:list:{warehouseId}[:full] 或 platform:list:system[:full]", - "补充错误码 500:数据库或缓存访问异常", - "仅文档更新,不修改任何业务实现" - ], - "type": "updated", - "module": "index" - }, - { - "version": "2026.06.04-system-03", - "date": "2026-06-04", - "summary": "作废 order.pendingOrder.downloadCreateTemplate 和 order.pendingOrder.importOrdersFromExcel", - "methods": [ - "order.pendingOrder.downloadCreateTemplate", - "order.pendingOrder.importOrdersFromExcel" - ], - "notes": [ - "order.pendingOrder.downloadCreateTemplate:下载订单导入模板方法已从代码中移除,标记为 deprecated。", - "order.pendingOrder.importOrdersFromExcel:从 Excel 导入订单方法已从代码中移除,标记为 deprecated。", - "两个方法的文档条目保留在 methods/system.json 中,仅追加 status: 'deprecated' 与 description 中的'(已作废)'标记,未删除。" - ], - "type": "deprecated" - }, - { - "version": "2026.06.05-system-01", - "date": "2026-06-05", - "summary": "新增 storeWarehouse.store.openAccount 接口:仓库代货主一键开户(合并注册账号+创建货主+签约)", - "methods": [ - "storeWarehouse.store.openAccount" - ], - "notes": [ - "新增 storeWarehouse.store.openAccount 方法,归属货主-仓库签约模块(storeWarehouse.store)。", - "接口同时完成账号注册、货主创建和仓库-货主签约,一步完成开户全流程。", - "当前主体必须为仓库角色(Authorization header 中携带的 token 对应仓库用户)。", - "必填参数:username(登录账号)、password(初始密码)、company_name(公司全称)、business_license(营业执照号)、contact_person(联系人)、contact_phone(联系电话)。", - "响应返回新创建的 store_id、account_id、contract_id、company_name、username、role_id。" - ], - "type": "added", - "module": "storeWarehouse" - }, - { - "version": "2026.06.05-system-02", - "date": "2026-06-05", - "summary": "优化 storeWarehouse.store.openAccount 必填参数:password 改为随机生成、business_license 和 contact_phone 改为可选,必填仅剩 username/company_name/contact_person 三个", - "methods": [ - "storeWarehouse.store.openAccount" - ], - "notes": [ - "password:由必填改为可选,不传时自动随机生成 12 位密码", - "business_license:由必填改为可选", - "contact_phone:由必填改为可选" - ], - "type": "updated" - }, - { - "version": "2026.06.05-system-03", - "date": "2026-06-05", - "summary": "saveApiConfig 增加 callback_url 参数,支持配置 API 回调通知地址", - "methods": [ - "storeWarehouse.store.saveApiConfig" - ], - "notes": [ - "新增 callback_url 参数:OpenAPI 类型接口支持配置回调通知 URL", - "兼容别名 callbackUrl,最大 500 字符", - "存入 wms_api_app.callback_url 字段" - ], - "type": "modified" - }, - { - "version": "2026.06.05-system-04", - "date": "2026-06-05", - "summary": "createOrder 入参 item_code 改为 item_id,province/city/area 改为必填", - "methods": [ - "order.pendingOrder.createOrder" - ], - "notes": [ - "items[].item_code → items[].item_id:改用商品主键直接匹配,不依赖外部系统商品推送", - "province/city/area 新增必填校验,空值返回 400", - "item_name 优先外部传入,其次从 StockStore 缓存获取,最后兜底'商品'" - ], - "type": "modified" - }, - { - "version": "2026.06.05-system-05", - "date": "2026-06-05", - "summary": "新增 order.pendingOrder.parseAddress 智能地址解析方法", - "methods": [ - "order.pendingOrder.parseAddress" - ], - "notes": [ - "使用 DeepSeek AI 模型将非结构化地址字符串解析为省/市/区/详细地址/收件人/手机号", - "解析结果可直接用于 createOrder 的 receiverInfo 字段", - "DeepSeek API Key 通过 DEEPSEEK_API_KEY 环境变量配置" - ], - "type": "added" - }, - { - "version": "2026.06.05-system-06", - "date": "2026-06-05", - "summary": "waveStrategyUpdate/waveStrategyCreate 新增 wave_prefix 参数", - "methods": [ - "order.wave.waveStrategyUpdate", - "order.wave.waveStrategyCreate" - ], - "notes": [ - "新增 wave_prefix 波次编号前缀字段,最多 5 个字符,为空存 null" - ], - "type": "modified" - }, - { - "version": "2026.06.05-system-07", - "date": "2026-06-05", - "summary": "parseAddress 响应新增 town 字段(乡镇/街道)", - "methods": [ - "order.pendingOrder.parseAddress" - ], - "notes": [ - "响应 data 中新增 town 字段,返回 AI 解析出的乡镇/街道名称" - ], - "type": "modified" - }, - { - "version": "2026.06.05-system-08", - "date": "2026-06-05", - "summary": "为 order.list 响应新增 recheck_status 字段(复核状态:none=未复核,fin=已复核)", - "methods": [ - "order.list" - ], - "notes": [ - "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" - ], - "type": "updated" - }, - { - "version": "2026.06.05-system-09", - "date": "2026-06-05", - "summary": "为 order.reviewOrder.list 响应新增 recheck_status 字段(复核状态:none=未复核,fin=已复核)", - "methods": [ - "order.reviewOrder.list" - ], - "notes": [ - "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" - ], - "type": "updated" - }, - { - "version": "2026.06.05-system-10", - "date": "2026-06-05", - "summary": "为 order.pendingOrder.list 响应新增 recheck_status 字段(复核状态:none=未复核,fin=已复核)", - "methods": [ - "order.pendingOrder.list" - ], - "notes": [ - "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" - ], - "type": "updated" - }, - { - "version": "2026.06.05-system-11", - "date": "2026-06-05", - "summary": "为 order.outboundOrder.list 响应新增 recheck_status 字段(复核状态:none=未复核,fin=已复核)", - "methods": [ - "order.outboundOrder.list" - ], - "notes": [ - "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" - ], - "type": "updated" - }, - { - "version": "2026.06.05-system-12", - "date": "2026-06-05", - "summary": "为 order.expectionOrder.list 响应新增 recheck_status 字段(复核状态:none=未复核,fin=已复核)", - "methods": [ - "order.expectionOrder.list" - ], - "notes": [ - "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" - ], - "type": "updated" - }, - { - "version": "2026.06.05-system-13", - "date": "2026-06-05", - "summary": "为 order.entrustOrder.list 响应新增 recheck_status 字段(复核状态:none=未复核,fin=已复核)", - "methods": [ - "order.entrustOrder.list" - ], - "notes": [ - "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" - ], - "type": "updated" - }, - { - "version": "2026.06.05-system-14", - "date": "2026-06-05", - "summary": "为 order.deliveryOrder.list 响应新增 recheck_status 字段(复核状态:none=未复核,fin=已复核)", - "methods": [ - "order.deliveryOrder.list" - ], - "notes": [ - "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" - ], - "type": "updated" - }, - { - "version": "2026.06.05-system-15", - "date": "2026-06-05", - "summary": "为 order.deliveryExpectionOrder.list 响应新增 recheck_status 字段(复核状态:none=未复核,fin=已复核)", - "methods": [ - "order.deliveryExpectionOrder.list" - ], - "notes": [ - "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" - ], - "type": "updated" - }, - { - "version": "2026.06.05-system-16", - "date": "2026-06-05", - "summary": "为 order.archiveOrder.list 响应新增 recheck_status 字段(复核状态:none=未复核,fin=已复核)", - "methods": [ - "order.archiveOrder.list" - ], - "notes": [ - "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" - ], - "type": "updated" - }, - { - "version": "2026.06.06-system-01", - "date": "2026-06-06", - "summary": "恢复 order.pendingOrder.downloadCreateTemplate:方法仍存在于代码中,取消 deprecated 标记,完善文档描述", - "methods": [ - "order.pendingOrder.downloadCreateTemplate" - ], - "notes": [ - "order.pendingOrder.downloadCreateTemplate 方法在 pendingOrder.js 中仍存在(line 2099),此前被误标记为 deprecated。", - "取消 status: 'deprecated' 标记,恢复为 active 状态。", - "移除 description 中的'(已作废)'后缀。", - "完善 description:说明模板包含必填列(橙色背景)、可选列(灰色背景)、示例数据行和填写说明工作表。", - "补充 response 字段说明:filename 和 mime 为固定值。" - ], - "type": "updated" - }, - { - "version": "2026.06.07-system-01", - "date": "2026-06-07", - "summary": "order.pendingOrder.createOrder 文档新增 shop_nick 入参(店铺名称,可选,最大长度200)", - "methods": [ - "order.pendingOrder.createOrder" - ], - "notes": [ - "在 order.pendingOrder.createOrder 的 request params 中新增 shop_nick 字段(string,非必填),对应代码实现中 shopNick: String(requestData.shop_nick || requestData.shopNick || '').trim()。", - "shop_nick 已在 COPY_FIELDS 白名单中(pendingOrder.js L1738),仅文档缺失,本次为补齐。" - ], - "type": "updated" - }, - { - "version": "2026.06.07-system-02", - "date": "2026-06-07", - "summary": "order.pendingOrder.downloadCreateTemplate:模板新增 shop_nick 列(店铺名称),store_id/province/city/area 标注为非必填", - "methods": [ - "order.pendingOrder.downloadCreateTemplate" - ], - "notes": [ - "模板新增 shop_nick(店铺名称)列,非必填。", - "明确标注 store_id(货主ID)、province(省份)、city(城市)、area(区/县)为非必填列。", - "响应文档中新增 shop_nick 字段说明。" - ], - "type": "updated" - }, - { - "version": "2026.06.07-system-03", - "date": "2026-06-07", - "summary": "新增 order.pendingOrder.updateAddress:批量修改待处理订单收件地址,限制未分配快递时可用", - "methods": [ - "order.pendingOrder.updateAddress" - ], - "notes": [ - "新增 method:order.pendingOrder.updateAddress,免权限(isNeedAuth=false),需登录", - "功能:批量修改待处理订单收件地址(name/mobile/tel/zip_code/province/city/area/town/detail_address)", - "约束:仅 post_status='none'(未分配快递)的订单可修改;至少提供一个有效地址字段", - "响应:返回 updated_count(实际更新行数)和 ids(请求订单ID数组)" - ], - "type": "added" - }, - { - "version": "2026.06.07-system-04", - "date": "2026-06-07", - "summary": "order.wave.wavePickTaskCancel 扩展可取消状态至 status=3,并新增拣货状态回退", - "methods": [ - "order.wave.wavePickTaskCancel" - ], - "notes": [ - "可取消状态从 [0,1,2] 扩展为 [0,1,2,3](status=3 已完成现在也可取消)", - "取消 status=2(待复核)或 status=3(已完成)任务时,自动回退 wms_wave_pick_task_order.pick_status(1→0)和 order_delivery.pick_status(fin→padding)", - "错误码 400 描述同步更新,补充 403 错误码说明" - ], - "type": "updated" - }, - { - "version": "2026.06.07-system-05", - "date": "2026-06-07", - "summary": "order.wave.wavePickTaskList 响应新增 cart_name 字段(拣货车名称)", - "methods": [ - "order.wave.wavePickTaskList" - ], - "notes": [ - "响应 list 子项新增 cart_name(string):通过 current_cart_id LEFT JOIN wms_pick_cart 表获取,未绑定拣货车时为空字符串。" - ], - "type": "updated" - }, - { - "version": "2026.06.07-system-06", - "date": "2026-06-07", - "summary": "pick.wavePickTaskComplete 新增后台抓取任务(source=2)拣货车绑定校验,未绑定拣货车时拒绝提交", - "methods": [ - "pick.wavePickTaskComplete" - ], - "notes": [ - "description 补充说明:后台抓取创建的任务(source=2)必须先绑定拣货车才能提交,否则返回 400。", - "errors 中 400 错误补充:后台抓取任务(source=2)未绑定拣货车时拒绝提交,错误消息为\"后台抓取任务必须先绑定拣货车才能提交\"。" - ], - "type": "updated" - }, - { - "version": "2026.06.07-system-07", - "date": "2026-06-07", - "summary": "order.wave.batchList 文档修正:移除代码中不存在的 sync_assignment_status 引用", - "methods": [ - "order.wave.batchList" - ], - "notes": [ - "从 where 描述中移除 sync_assignment_status(代码 buildBatchListWhereClause allowedFields 中不存在该字段,BATCH_LIST_ASSIGNMENT_FILTER_SCHEMAS 中也无 review 之外的同步类型)。", - "从 response list 描述中移除 sync_assignment_status(代码响应映射中仅返回 storage/express/print/review 四种 assignment_status,无 sync_assignment_status)。", - "v2026.06.03-system-03 变更记录中声称新增的 sync_assignment_status 实际从未在代码中实现,本次仅为文档修正,不涉及代码变更。" - ], - "type": "updated", - "module": "order.wave" - }, - { - "version": "2026.06.07-system-08", - "date": "2026-06-07", - "summary": "order.recheckOrder.confirmRecheck 补充后置行为说明:波次任务全部复核完成后自动解绑车任务", - "methods": [ - "order.recheckOrder.confirmRecheck" - ], - "notes": [ - "在 description 中补充:确认复核后,若该订单所属波次拣货任务下所有订单均已复核完成,则自动解绑车任务。解绑操作包括:清空 wms_wave_pick_task 的 current_cart_id/current_cart_code_snapshot、停用 wms_pick_task_cart_binding(is_active=0 并记录解绑人和时间)、释放 wms_pick_cart(清空 current_task_id/bind_user_id)。", - "解绑失败仅记录 warn 日志,不影响复核主流程。", - "入参和返回结构未变,仅补充行为说明。" - ], - "type": "updated" - }, - { - "version": "2026.06.07-system-10", - "date": "2026-06-07", - "summary": "移除 order.wave.groupFetch / singleFetch / fetch 响应中已废弃的 auto_fetch_disabled_marker 字段", - "methods": [ - "order.wave.groupFetch", - "order.wave.singleFetch", - "order.wave.fetch" - ], - "notes": [ - "auto_fetch_disabled_marker 字段已从代码 submitFetchTask 响应中移除,文档同步删除该字段的描述。", - "auto_fetch_disabled 字段同样已从代码中移除,且原文档中不存在此字段(仅有 auto_fetch_disabled_marker),无需额外处理。", - "涉及 method:order.wave.groupFetch、order.wave.singleFetch、order.wave.fetch,均移除 response 中的 auto_fetch_disabled_marker 字段。" - ], - "type": "updated", - "module": "order.wave" - }, - { - "version": "2026.06.08-system-01", - "date": "2026-06-08", - "summary": "order.recheckOrder 模块 scanOrder 返回值重构为统一 list 输出,新增 confirmIntercept 与 recheckOrderList 接口", - "methods": [ - "order.recheckOrder.scanOrder", - "order.recheckOrder.confirmIntercept", - "order.recheckOrder.recheckOrderList" - ], - "notes": [ - "scanOrder 返回值重构:统一使用 list 字段输出,新增 list_type 字段区分散单/团购模式。散单模式顶层新增 picker_id、picker_name、wave_id、wave_no、wave_type、pick_mode、strategy_id、strategy_name、total_orders、reviewed_count、unreviewed_count 等汇总字段。list 中每项新增 waybill_no、is_printed、is_reviewed、wave_index、intercept_status、store_remark、stock[](含 stock_id、item_code、item_name、sku_property、packing_requirements、barcodes[]、images[]、plan_qty、has_shared_barcode)。移除旧字段 logs、order、order_id(顶层)、waybill_no(顶层旧位置)、wave_match_view、items、expresses、cart_match_view。", - "scanOrder 入参新增 wave_no / waveNo 支持波次号直接扫描匹配。", - "新增 order.recheckOrder.confirmIntercept:确认拦截接口,将订单 intercept_status 更新为 intercepted_at_warehouse,返回 order_id、order_no、intercept_status、updated_at。", - "新增 order.recheckOrder.recheckOrderList:复核订单列表查询,支持 list_type=single(散单)与 list_type=group(团购),均返回统一 list + pagination 结构。" - ], - "type": "updated" - }, - { - "version": "2026.06.08-system-02", - "date": "2026-06-08", - "summary": "order.recheckOrder 模块新增 batchIntercept/batchInterceptTaskProgress,更新 scanOrder 团购模式响应结构,完善 confirmIntercept/recheckOrderList 文档", - "methods": [ - "order.recheckOrder.batchIntercept", - "order.recheckOrder.batchInterceptTaskProgress", - "order.recheckOrder.scanOrder", - "order.recheckOrder.confirmIntercept", - "order.recheckOrder.recheckOrderList" - ], - "notes": [ - "新增 order.recheckOrder.batchIntercept:批量提交订单拦截(异步任务模式),入参支持 order_ids/orderIds/ids(订单ID数组,不再使用 wave_ids),将 intercept_status 设为 'requested',返回 task_id/warehouse_id/message/accepted_at。支持幂等提交与 warehouse_id 校验。", - "新增 order.recheckOrder.batchInterceptTaskProgress:按 task_id 查询批量拦截任务进度,返回 state(submitted/running/success/failed/not_found)及对应的进度/计数/结果/错误字段。", - "更新 order.recheckOrder.scanOrder 响应文档:团购模式(cart 命中)list 项新增 wave_id/wave_no/wave_type/wave_status/total_orders/processed_orders/creator/create_time/update_time/order_count/pick_mode/box_no/orders[] 等波次级别字段;补充散单无波次信息时的回退详情模式说明(detail/items/expresses/logs)。", - "完善 order.recheckOrder.confirmIntercept:补充操作日志写入说明(ORDER_INTERCEPT_CONFIRM)及失败不影响主流程的容错描述。", - "完善 order.recheckOrder.recheckOrderList:补充散单模式默认排除 pick_status='none' 和 recheck_status='fin' 的说明;团购模式 where 支持 wave_no(模糊搜索)的说明。" - ], - "type": "updated" - }, - { - "version": "2026.06.08-system-03", - "date": "2026-06-08", - "summary": "移除 order.recheckOrder.batchIntercept 的 warehouse_id/warehouseId 入参,仓库ID统一使用当前上下文", - "methods": [ - "order.recheckOrder.batchIntercept" - ], - "notes": [ - "移除入参 warehouse_id / warehouseId:仓库ID统一从当前上下文(ctx.user.store_id)获取,不再由调用方传入。", - "移除对应错误码:warehouse_id 参数不合法(400)、warehouse_id 与当前仓库上下文不一致(400)。", - "description 中补充说明仓库ID来源为当前上下文。", - "response 中 warehouse_id 字段描述改为「取自当前上下文」。" - ], - "type": "updated" - }, - { - "version": "2026.06.08-system-10", - "date": "2026-06-08", - "summary": "batchIntercept / batchInterceptTaskProgress 从 order.recheckOrder 迁移至 order.pendingOrder", - "methods": [ - "order.pendingOrder.batchIntercept", - "order.pendingOrder.batchInterceptTaskProgress" - ], - "notes": [ - "method 从 order.recheckOrder.batchIntercept 重命名为 order.pendingOrder.batchIntercept,分组从订单复核模块迁移至订单待处理模块", - "method 从 order.recheckOrder.batchInterceptTaskProgress 重命名为 order.pendingOrder.batchInterceptTaskProgress,分组从订单复核模块迁移至订单待处理模块", - "接口入参、响应、错误码均保持不变,仅变更 method 名称与所属分组" - ], - "type": "updated" - }, - { - "version": "2026.06.08-system-04", - "date": "2026-06-08", - "summary": "新增 order.print.getOrderPrintData:按订单ID拉取打印数据,返回结构与 getWavePlatformPrintData 一致,不限制锁定状态", - "methods": [ - "order.print.getOrderPrintData" - ], - "notes": [ - "新增 order.print.getOrderPrintData 接口文档,入参为 warehouse_id + order_ids(非空数组),返回与 getWavePlatformPrintData 结构一致的 waveGroups / summary / wave_ids / ext", - "与 getWavePlatformPrintData 的区别:入参为 order_ids(非 wave_ids),ext 中返回 missing_order_ids / filtered_order_ids(非 missing_wave_ids / filtered_wave_ids)", - "不限制打印锁定状态,所有订单(无论是否被锁定)统一返回打印数据", - "自动过滤 post_status !== 'fin' 的订单(快递未完全分配),被过滤订单出现在 ext.filtered_order_ids" - ], - "type": "added", - "module": "order.print" - }, - { - "version": "2026.06.08-system-11", - "date": "2026-06-08", - "summary": "新增 order.pendingOrder 批量锁定/解锁/解除拦截及对应进度查询共 6 个异步任务接口文档", - "methods": [ - "order.pendingOrder.batchLock", - "order.pendingOrder.batchLockTaskProgress", - "order.pendingOrder.batchUnlock", - "order.pendingOrder.batchUnlockTaskProgress", - "order.pendingOrder.batchUnintercept", - "order.pendingOrder.batchUninterceptTaskProgress" - ], - "notes": [ - "新增 batchLock:批量锁定订单,lock_status → 'warehouse',操作日志 ORDER_LOCK,task_id 格式 order_lock_{warehouseId}_{timestamp}_{rand}。", - "新增 batchLockTaskProgress:查询批量锁定进度,返回 locked_order_count / locked_order_ids 等。", - "新增 batchUnlock:批量解锁订单,lock_status → 'none',操作日志 ORDER_UNLOCK,task_id 格式 order_unlock_{warehouseId}_{timestamp}_{rand}。", - "新增 batchUnlockTaskProgress:查询批量解锁进度,返回 unlocked_order_count / unlocked_order_ids 等。", - "新增 batchUnintercept:批量解除拦截订单,intercept_status → 'none',操作日志 ORDER_INTERCEPT_CANCEL,task_id 格式 order_unintercept_{warehouseId}_{timestamp}_{rand}。", - "新增 batchUninterceptTaskProgress:查询批量解除拦截进度,返回 unintercepted_order_count / unintercepted_order_ids 等。", - "以上 6 个接口均采用与已有 batchIntercept/batchInterceptTaskProgress 一致的异步任务模式:提交返回 task_id,进度查询返回 state + 进度字段。", - "仅同步文档,不修改业务代码或实现。" - ], - "type": "added", - "module": "order" - }, - { - "version": "2026.06.08-system-12", - "date": "2026-06-08", - "summary": "更新 order.print.getOrderPrintData:移除锁定限制,所有订单统一返回打印数据,不再区分锁定/未锁定", - "methods": [ - "order.print.getOrderPrintData" - ], - "notes": [ - "移除打印锁定限制:所有订单(包括已锁定)统一返回打印数据,不再区分锁定/未锁定状态", - "移除 locked_count、locked_orders、locked_wave_groups 等锁定相关字段", - "返回结构与 getWavePlatformPrintData 完全一致:summary / waveGroups / wave_ids / ext", - "ext 中使用 missing_order_ids / filtered_order_ids(替代锁定相关字段),与代码实现完全对齐" - ], - "type": "updated", - "module": "order.print" - }, - { - "version": "2026.06.08-system-13", - "date": "2026-06-08", - "summary": "更新 order.print.getOrderPrintData:移除 warehouse_id 入参,仓库ID统一从当前上下文获取", - "methods": [ - "order.print.getOrderPrintData" - ], - "notes": [ - "移除 warehouse_id / warehouseId 入参,仓库ID统一从 this.getContextWarehouseId() 获取", - "同步移除 errors 中 warehouse_id 必填 相关错误码", - "description 补充说明仓库ID从上下文获取,无需调用方传入", - "params 仅保留 order_ids(非空数组),与代码 method 层 getOrderPrintData(data) 解构一致" - ], - "type": "updated", - "module": "order.print" - }, - { - "version": "2026.06.08-system-14", - "date": "2026-06-08", - "summary": "新增 order.recheckOrder.scanTask 接口文档,并为 scanOrder 响应补充 task_id 字段", - "methods": [ - "order.recheckOrder.scanTask", - "order.recheckOrder.scanOrder" - ], - "notes": [ - "新增 order.recheckOrder.scanTask:按拣货任务 ID 拉取复核数据,数据结构与 scanOrder 完全一致,用于前端刷新。入参为 task_id(必填,number),返回 match_type='task',散单模式(pick_mode 2/3/4)返回扁平订单列表,团购模式(pick_mode 1/5)返回分组波次列表。", - "更新 order.recheckOrder.scanOrder 响应定义:补充 task_id 字段说明(散单有波次时由 buildSingleWaveScanView 返回,团单车号命中时由 cartMatchContext 返回)。", - "仅同步文档,不修改任何业务代码或实现。" - ], - "type": "updated" - }, - { - "version": "2026.06.08-system-15", - "date": "2026-06-08", - "summary": "新增 order.pendingOrder.manualWaybill 接口(手工录入运单号)", - "methods": [ - "order.pendingOrder.manualWaybill" - ], - "notes": [ - "为待处理订单手动录入运单号,写入 wms_order_express 表", - "仅允许 step 在 [1,2,3] 且 outbound_status 不为 'padding' 的订单操作", - "免权限(isNeedAuth: false),需登录", - "成功返回运单记录的 id、order_id、waybill_code、create_at" - ], - "type": "added" - }, - { - "version": "2026.06.09-system-01", - "date": "2026-06-09", - "summary": "order.pendingOrder.updateAddress 新增 remark 字段:订单留言/备注批量覆盖,不受 post_status 限制", - "methods": [ - "order.pendingOrder.updateAddress" - ], - "notes": [ - "在 params 中新增 remark 字段(string,可选,最大500字符),支持批量覆盖所选订单的 remark", - "remark 更新不受 post_status 限制,可对所有订单生效(地址字段仍仅允许 post_status='none')", - "更新 description 明确 remark 与地址字段的独立性", - "更新 response 中 updated_count 说明:取地址更新行数与备注更新行数的最大值", - "更新 errors 中缺少字段的错误描述,改为「至少需要提供一个地址字段或备注进行修改」", - "业务代码已同步实现,本次仅同步文档" - ], - "type": "updated" - }, - { - "version": "2026.06.09-system-02", - "date": "2026-06-09", - "summary": "order.updateExpressWeighingWeight 新增运单号模式文档:order_id=0 时从运单号反查,支持散单与团购批量两种返回结构", - "methods": [ - "order.updateExpressWeighingWeight" - ], - "notes": [ - "order_id 参数说明补充:设为0时切换为运单号模式,需配合 waybill_code 使用。", - "waybill_code 参数说明补充:运单号模式(order_id=0)下必填。", - "description 更新:明确订单模式与运单号模式两种路径及团购波次批量行为。", - "response 新增运单号散单场景字段(order_id、waybill_code、weighing_weight)与运单号团购批量场景字段(wave_no、business_key、weighing_weight、success_count)。", - "errors 新增运单号模式相关错误码:运单号不存在(404)、运单号对应的订单不存在(404)、波次下未找到订单(404)、批量更新失败(500)。", - "仅文档同步,不修改业务代码。" - ], - "type": "updated" - }, - { - "version": "2026.06.09-system-03", - "date": "2026-06-09", - "summary": "order.updateExpressWeighingWeight 团购返回新增拆单汇总字段,移除 success_count/total_count", - "methods": [ - "order.updateExpressWeighingWeight" - ], - "notes": [ - "团购批量模式 response 新增 total_weight(所有拆单重量累加)、split_count(waybill_code 非空的 business_key 数量)、splits(按 business_key 分组的拆单明细数组,每项含 business_key/weighing_weight/waybill_code)、store_name(货主名称)和 sys_logistics_name(系统快递名称)。", - "移除 response 中的 success_count 与 total_count 字段,改为由 total_weight 和 split_count 提供汇总信息。", - "更新 description 以反映团购模式返回拆单汇总结构。" - ], - "type": "updated" - }, - { - "version": "2026.06.10-system-01", - "date": "2026-06-10", - "summary": "order.detail 接口文档:expresses 数组新增字段 weighing_weight、sys_logistics_code、sys_logistics_name、business_key、created_at", - "methods": [ - "order.detail" - ], - "notes": [ - "expresses 数组新增字段:weighing_weight(称重重量,number|null)、sys_logistics_code(系统物流公司编码,string)、sys_logistics_name(系统物流公司名称,string)、business_key(业务标识,string)、created_at(创建时间戳毫秒,number|null)", - "字段来源:getOrderExpressesByOrderId 方法中 sys_logistics_code/sys_logistics_name 取自订单表 sys_logistics_code/sys_logistics_name,其余字段取自 OrderExpress 表" - ], - "type": "updated" - }, - { - "version": "2026.06.10-system-02", - "date": "2026-06-10", - "summary": "dashboard.order_trend 从 mock 数据改为查询真实数据库,按小时统计当日订单数与发货数,补充完整返回结构与错误说明", - "methods": [ - "dashboard.order_trend" - ], - "notes": [ - "接口实现从 mock 静态数据改为查询真实数据库(wms_order_delivery 与 dispatch 表),数据实时反映仓库当日运营情况。", - "订单筛选条件:step in [1,2,3],排除 outbound_status='padding' 和 status='cancel',统计 create_at 在今日 00:00 到当前时刻的订单,按 HOUR(create_at) 分组。", - "发货筛选条件:dispatch_lane='m4',统计 delivery_time 在今日 00:00 到当前时刻的发货记录,按 HOUR(delivery_time) 分组。", - "时段范围:从 08:00 到当前小时(最晚 23:00),若当前时间早于 08:00 则从 08:00 开始。", - "返回新增 summary 汇总对象:total_orders(订单总数)、total_shipments(发货总数)、shipment_rate(发货率百分比)、peak_hour(峰值时段)、peak_orders(峰值订单数)。", - "categories/orders/shipments 三个数组一一对应,提供按时段的订单与发货趋势数据,可直接用于前端折线图/柱状图渲染。", - "需要登录(Authorization header),从 token 中获取 warehouseId;若缺少仓库上下文则返回 flag='fail'。" - ], - "type": "updated", - "module": "dashboard" - }, - { - "version": "2026.06.10-system-03", - "date": "2026-06-10", - "summary": "order.pendingOrder.manualWaybill 新增可选参数 logistics_interface_name 与响应字段 business_key/logistics_interface_name,补充行为说明", - "methods": [ - "order.pendingOrder.manualWaybill" - ], - "notes": [ - "新增可选参数 logistics_interface_name(string,选填,trim 后为空则传 null)", - "响应新增字段 business_key(number):同一订单下从已有最大值 +1 递增,无记录时从 1 开始", - "响应新增字段 logistics_interface_name(string/null):写入的物流接口名称", - "补充 description 行为说明:完成后自动更新 wms_order_delivery_* 表的 print_status 和 post_status 为 'fin'", - "wms_order_express 表写入时 status 固定为 1,warehouse_id 从订单记录取" - ], - "type": "updated" - }, - { - "version": "2026.06.10-system-04", - "date": "2026-06-10", - "summary": "stock.warehouse.import 新增 barcode(条码)字段支持", - "methods": [ - "stock.warehouse.import" - ], - "notes": [ - "新增 barcode(条码)字段支持,支持别名:条码、bar_code、barCode、barcodeList、barcode_list、barcode。", - "条码字段支持数组格式(如 [\"6901234567890\"])和分号分隔字符串格式(如 \"6901234567890;6901234567891\")。", - "新建和更新路径均已支持条码导入,条码写入 wms_stock_barcodes 表。", - "仅同步文档,不修改业务代码或实现。" - ], - "type": "updated" - }, - { - "version": "2026.06.10-system-05", - "date": "2026-06-10", - "summary": "stock.warehouse.import 的 barcode 字段分隔符改为逗号,对齐 stock.warehouse.export 导出格式;仅接收字符串格式,不再支持数组", - "methods": [ - "stock.warehouse.import" - ], - "notes": [ - "barcode 字段分隔符从分号 ; 改为逗号 ,", - "barcode 字段仅接收字符串格式,不再支持数组格式", - "格式示例:\"6901234567890,6901234567891\",与 stock.warehouse.export 导出格式一致" - ], - "type": "modified" - }, - { - "version": "2026.06.13-system-01", - "date": "2026-06-13", - "summary": "setting.warehouse 的 auto_outbound_rules 新增 require_print 和 require_pick 两个可选条件字段(同步代码实现)", - "methods": [ - "setting.warehouse.getSettings", - "setting.warehouse.saveSettings" - ], - "notes": [ - "在 getSettings 响应和 saveSettings 入参中补充 subject_config.auto_outbound_rules 对象的完整字段文档(enabled、require_recheck、require_pack、require_weigh、require_sync、require_print、require_pick)。", - "require_print:是否要求已打印(print_status=fin),默认 true。", - "require_pick:是否要求已拣货(pick_status=fin),默认 true。", - "该规则由自动出库定时任务 order_auto_outbound 消费,全部开启的条件均满足时自动标记待出库。" - ], - "type": "updated" - }, - { - "version": "2026.06.13-system-02", - "date": "2026-06-13", - "summary": "order.recheckOrder.scanOrder 团购模式响应新增 orders_detail 字段,暴露非拦截订单的详细列表(含 is_printed、is_reviewed 等状态字段)", - "methods": [ - "order.recheckOrder.scanOrder" - ], - "notes": [ - "团购模式(list_type='group')波次视图项新增 orders_detail 字段:非拦截订单详细列表,每项含 order_id、delivery_order_code、waybill_no、pick_status、is_printed(print_status === 'fin')、is_reviewed(recheck_status === 'fin')、recheck_status、shop_nick、items_count、wave_index、intercept_status", - "orders_detail 与现有 order_ids(纯数字 ID 数组)并存,均在团购模式的波次视图项中返回", - "orders_detail 仅在 list_type='group' 时返回,散单模式不受影响", - "同步更新 list 字段 description 以反映 group 模式新增的 order_ids、orders_detail、stocks 字段" - ], - "type": "updated" - }, - { - "version": "2026.06.13-system-03", - "date": "2026-06-13", - "summary": "新增批量快捷复核接口 batchQuickRecheck,支持批量订单 IDs 的前置条件检查(储位、快递、同步、拦截),自动完成拣货并标记复核,支持部分失败。拣货完成后同步更新 wms_wave_pick_task 状态", - "methods": [ - "order.recheckOrder.batchQuickRecheck" - ], - "notes": [ - "新增 order.recheckOrder.batchQuickRecheck 方法", - "入参 ids 支持数组或逗号分隔字符串", - "响应包含 success/failed 列表及计数,failed 项含 reason 说明" - ], - "details": { - "description": "包含拣货任务状态同步:全部拣完→任务状态=2(已完成),未全拣完→任务状态推进为1(拣货中)" - }, - "type": "added" - }, - { - "version": "2026.06.14-system-01", - "date": "2026-06-14", - "summary": "新增 order.bindExpressPackageMaterialByWaybill 方法:支持仅凭运单号绑定包材,无需传入订单ID", - "methods": [ - "order.bindExpressPackageMaterialByWaybill" - ], - "notes": [ - "新增 order.bindExpressPackageMaterialByWaybill 入参说明:waybill_code(运单号,必填)、package_material_code(包材编码,必填)。无需传入 order_id。", - "成功返回字段:order_id、waybill_code、package_material_id、package_material_name_snapshot、package_material_code。", - "错误码定义:400(参数错误)、404(运单号不存在 / 包材编码不存在)、500(绑定包材失败)。" - ], - "type": "added" - }, - { - "version": "2026.06.15-system-01", - "date": "2026-06-15", - "summary": "order.detail / order.deliveryOrder.detail 的 expresses 数组新增包材字段", - "methods": [ - "order.detail", - "order.deliveryOrder.detail" - ], - "notes": [ - "expresses 数组每个元素新增 package_material_id(包材ID,number|null)和 package_material_name_snapshot(包材名称快照,string|null)字段。" - ], - "type": "updated" - }, - { - "version": "2026.06.15-system-02", - "date": "2026-06-15", - "summary": "order.deliveryOrder.detail 的 expresses 数组新增包材字段", - "methods": [ - "order.deliveryOrder.detail" - ], - "notes": [ - "expresses 数组每个元素新增 package_material_id(包材ID,number|null)和 package_material_name_snapshot(包材名称快照,string|null)字段。" - ], - "type": "updated" - }, - { - "version": "2026.06.15-system-03", - "date": "2026-06-15", - "summary": "新增 setting.packageMaterial.search 方法:支持按关键字模糊搜索包材编码和名称", - "methods": [ - "setting.packageMaterial.search" - ], - "notes": [ - "新增 setting.packageMaterial.search 入参 keyword(可选),为空返回前 50 条启用中包材,有值时对 material_code 和 material_name 做模糊匹配。", - "返回包材数组,字段:id、material_code、material_name、material_type、spec、status。" - ], - "type": "added" - }, - { - "version": "2026.06.16-system-01", - "date": "2026-06-16", - "summary": "新增 order.recheckOrder.queryRecheckOrderSingleList:散单复核列表接口,响应新增 items_weight(总重量g)和 weight_type(重量类型)字段", - "methods": [ - "order.recheckOrder.queryRecheckOrderSingleList" - ], - "notes": [ - "新增方法 order.recheckOrder.queryRecheckOrderSingleList,为 recheckOrderList 散单模式的独立入口。", - "响应 list 每项新增字段 items_weight (DECIMAL(10,2)):订单总重量(g),来自 wms_order.items_weight,为 null 时返回 null。", - "响应 list 每项新增字段 weight_type (string):重量类型中文标签,来自 wms_order.weight_type 经 formatWeightTypeLabel 转换;取值:常规/轻货/重货/冷链(对应 DB 值 0/1/2/3)。" - ], - "type": "added", - "module": "order.recheckOrder" - }, - { - "version": "2026.06.16-system-02", - "date": "2026-06-16", - "summary": "为 order.wave.groupOrderFetchList / waveStrategyFallbackOrderList / singleOrderFetchList 响应新增 items_weight(总重量g)和 weight_type(重量类型)字段", - "methods": [ - "order.wave.groupOrderFetchList", - "order.wave.waveStrategyFallbackOrderList", - "order.wave.singleOrderFetchList" - ], - "notes": [ - "order.wave.groupOrderFetchList:响应 list 每项新增 items_weight (number|null):订单总重量(g),取组内首单 items_weight;组内订单 items_hash 相同重量一致。", - "order.wave.waveStrategyFallbackOrderList:响应 list 每项新增 items_weight (number|null):订单总重量(g),来自 wms_order.items_weight;新增 weight_type (string):重量类型中文标签,取值:常规/轻货/重货/冷链(对应 DB 值 0/1/2/3)。", - "order.wave.singleOrderFetchList:响应 list 每项新增 items_weight (number|null):订单总重量(g),取组内首单 items_weight;组内订单 items_hash 相同重量一致。", - "所有新增字段均为可选(required=false),为 null 时返回 null。" - ], - "type": "updated", - "module": "order.wave" - }, - { - "version": "2026.06.17-system-01", - "date": "2026-06-17", - "summary": "新增 order.pendingOrder.replenishmentDemand 分拣缺货补货需求计算接口文档", - "methods": [ - "order.pendingOrder.replenishmentDemand" - ], - "notes": [ - "新增分拣缺货补货需求计算方法,用于计算待处理订单的SKU在分拣区与存货区的库存分布及补货缺口", - "入参 order_ids/warehouse_id 均为可选;不传 order_ids 时自动查询当前仓库所有未完成储位分配的订单", - "纯只读查询接口,不修改任何数据", - "响应包含 list(明细)与 summary(汇总),其中 shortage = max(0, total_demand - pick_zone_quantity),replenishment_needed = min(shortage, storage_zone_quantity)" - ], - "type": "add", - "module": "order.pendingOrder" - }, - { - "version": "2026.06.17-system-02", - "date": "2026-06-17", - "type": "update", - "module": "order.pendingOrder", - "method": "order.pendingOrder.replenishmentDemand", - "description": "移除 order_ids 参数,改为纯仓库级别计算,自动查询当前仓库所有未完成储位分配的订单" - }, - { - "version": "2026.06.17-system-03", - "date": "2026-06-17", - "type": "update", - "module": "order.pendingOrder", - "method": "order.pendingOrder.replenishmentDemand", - "description": "新增 is_true_shortage 字段标识真正缺货(两区均无库存),summary 新增 total_true_shortage_skus 统计" - }, - { - "version": "2026.06.17-system-04", - "date": "2026-06-17", - "type": "migrate", - "module": "storage.management", - "summary": "从 order.pendingOrder.replenishmentDemand 迁移至 storage.management.replenishmentDemand(库存管理模块),原路径已删除,开发阶段无需兼容", - "methods": [ - "storage.management.replenishmentDemand" - ], - "notes": [ - "将 replenishmentDemand 接口从 order.pendingOrder 模块迁移到新建的 storage.management 库存管理模块。", - "旧条目 order.pendingOrder.replenishmentDemand 已从 order.pendingOrder 组中移除。", - "开发阶段无需兼容旧路径。" - ] - }, - { - "version": "2026.06.17-system-05", - "date": "2026-06-17", - "type": "update", - "module": "storage.management", - "summary": "storage.management.replenishmentDemand 移除 warehouse_id 入参,仓库ID改为纯从用户上下文(ctx.user)获取,接口无需入参", - "methods": [ - "storage.management.replenishmentDemand" - ], - "notes": [ - "移除 warehouse_id 入参,仓库ID改为纯从用户上下文(ctx.user)获取,接口无需入参" - ] - }, - { - "version": "2026.06.17-system-06", - "date": "2026-06-17", - "type": "update", - "module": "storage.management", - "method": "storage.management.replenishmentDemand", - "description": "新增分页入参(pagination)、排序入参(sort,默认按 shortage DESC)、响应新增 replenishment_locations(存货区可补货库位,最多5条)、响应新增 pagination 分页信息" - }, - { - "version": "2026.06.17-system-07", - "date": "2026-06-17", - "type": "update", - "module": "storage.management", - "summary": "replenishment_locations 新增 space_name 字段,优先取自定义名称(custom_name),无则回退库位编码(space_code)", - "methods": [ - "storage.management.replenishmentDemand" - ], - "notes": [ - "在 replenishment_locations.children 中新增 space_name 字段(string, required),放在 space_code 之后、available_quantity 之前。", - "space_name 取值逻辑:优先使用库位自定义名称 custom_name,若无自定义名称则回退为库位编码 space_code。" - ] - }, - { - "version": "2026.06.17-system-08", - "date": "2026-06-17", - "type": "update", - "module": "storage.management", - "summary": "合并 is_sufficient 和 is_true_shortage 为 replenishment_status 枚举字段(replenishable/true_shortage)", - "methods": [ - "storage.management.replenishmentDemand" - ], - "notes": [ - "删除 is_sufficient(boolean)和 is_true_shortage(boolean)两个字段。", - "新增 replenishment_status(string)枚举字段:replenishable=存货区足够覆盖缺口,移库可解决;true_shortage=存货区不足以覆盖缺口或两区均无库存,需采购。" - ] - }, - { - "version": "2026.06.18-system-01", - "date": "2026-06-18", - "summary": "入库单完成后异步匹配收货单并回传:completeEntry / entryorderConfirm 入库完成时自动匹配收货单,明细一致则按来源回传(奇门/OpenAPI),覆盖场景标记收货单部分入库;completeReceiving 完成后清除收货单缓存", - "methods": [ - "storage.entry.completeEntry", - "storage.receiving.completeReceiving" - ], - "notes": [ - "新增 app/service/systems/receiving_entry_match.js:入库单完成后异步匹配收货单并回传的核心服务,含 Redis 缓存收货单列表(TTL 300s)、remark 匹配收货单号、明细对比、奇门回传、OpenAPI 回调、部分入库标记等能力。", - "storage.entry.completeEntry 完成后通过 setImmediate 异步触发 matchAfterEntryCompleted,不阻塞主流程。", - "entry_order.js entryorderConfirm() 事务提交后(isFin 最终完成)同样异步触发匹配。", - "storage.receiving.completeReceiving 完成后清除收货单 Redis 缓存(cache:receiving_orders:warehouse:{warehouseId}),确保下次匹配获取最新收货单列表。", - "匹配规则:入库单 remark 包含收货单号 → 对比 SKU+数量 → 完全一致回传 / 收货单覆盖标记部分入库 / 其他不处理。", - "回传路径:source_type=QM → 奇门 taobao.qimen.entryorder.confirm;source_type=API → OpenAPI 回调(entry_order_receiving_matched 事件)。" - ], - "type": "updated" - }, - { - "version": "2026.06.18-system-02", - "date": "2026-06-18", - "summary": "新增 storage.receiving.manualMatchEntryOrder 接口", - "methods": [ - "storage.receiving.manualMatchEntryOrder" - ], - "notes": [ - "新增 storage.receiving.manualMatchEntryOrder:手动匹配入库单与收货单,传入 receivingId 和 entryOrderId,复用异步匹配服务的明细对比和回传逻辑,同步返回匹配结果", - "参数:receivingId (number, 必填)、entryOrderId (number, 必填)", - "校验:入库单存在性、收货单存在性、同仓库校验", - "返回 matchType (full_match/receiving_covers_entry/entry_exceeds_receiving/no_match)、comparisonResult、callbackSent、callbackResult、partialStorageMarked、entryOrder、receivingOrder" - ], - "type": "added", - "module": "storage" - }, - { - "version": "2026.06.18-system-03", - "date": "2026-06-18", - "summary": "新增 storage.receiving.getAvailableInboundQuantity 接口:按 stock_id 查询已审核收货单的可入库数量(actual_quantity - stored_quantity),排除未审核和已取消的收货单", - "methods": [ - "storage.receiving.getAvailableInboundQuantity" - ], - "notes": [ - "新增 system method:storage.receiving.getAvailableInboundQuantity,按 stock_id 查询已审核收货单中各明细的可入库数量(actual_quantity - stored_quantity),仅返回尚有可入库余量的明细。", - "实现文件:app/service/systemMethods/storage/receiving.js(包装层)、app/service/systems/storage/receiving.js(业务层)。", - "接口无需鉴权(isNeedAuth=false),但需要登录(isNeedLogin=true)。", - "入参 stock_id 为必填,对应 stock_warehouse.id;服务端从 ctx.user.store_id 获取仓库上下文。" - ], - "type": "added", - "module": "storage" - }, - { - "version": "2026.06.18-system-04", - "date": "2026-06-18", - "summary": "新增 storage.entry.bindReceivingDetails 接口和 wms_entry_receiving_binding 中间表:入库单明细可显式绑定收货明细(pending状态),提交入库时事务内完成双向扣减(stored_quantity/received_quantity),通过唯一约束和行锁防止超分和重复绑定。同时重构 completeEntry 调用链为 commitEntryWithBindings,无绑定时向后兼容。", - "methods": [ - "storage.entry.bindReceivingDetails", - "storage.entry.completeEntry" - ], - "notes": [ - "新增 storage.entry.bindReceivingDetails 方法:入库单明细绑定收货明细,pending 状态软绑定,每次调用清除旧 pending 绑定后创建新绑定。", - "新增 wms_entry_receiving_binding 中间表(migration: 20260618150000-create-wms-entry-receiving-binding.js),用于记录入库明细与收货明细的绑定关系。", - "重构 completeEntry 调用链:systemMethods 层 completeEntry 改为调用 commitEntryWithBindings,有绑定则事务内完成双向扣减(stored_quantity/received_quantity),无绑定时向后兼容仅变更入库单状态。", - "通过数据库唯一约束和行锁(SELECT ... FOR UPDATE)防止超分和重复绑定。", - "涉及文件: app/model/entry_receiving_binding.js, app/service/systems/storage/entry.js, app/service/systemMethods/storage/entry.js, database/migrations/20260618150000-create-wms-entry-receiving-binding.js" - ], - "type": "added", - "module": "storage.entry" - }, - { - "version": "2026.06.18-system-05", - "date": "2026-06-18", - "summary": "storage.entry.get 响应追加 pending_total/total_planned/bindings 字段,storage.receiving.getAvailableInboundQuantity 响应追加 pending_allocated_quantity 字段:前端可通过 get 查看入库明细的绑定状态,getAvailableInboundQuantity 的可用量已扣除全局 pending 绑定总量", - "methods": [ - "storage.entry.get", - "storage.receiving.getAvailableInboundQuantity" - ], - "notes": [ - "storage.entry.get:items 数组每项新增 pending_total(该入库明细当前 pending 绑定的总预分配数量)、total_planned(计划入库数量=count)、bindings(pending 绑定列表,每项含 id/entry_item_id/receiving_detail_id/allocated_quantity/status/receivingDetail 子对象)", - "storage.receiving.getAvailableInboundQuantity:list 每项新增 pending_allocated_quantity(该收货明细在当前 stock_id 所有入库单中的 pending 绑定总量),available_quantity 计算已扣除该值" - ], - "type": "updated" - }, - { - "version": "2026.06.18-system-06", - "date": "2026-06-18", - "summary": "bindReceivingDetails 重构为\"绑定即实收\"(received_quantity 在绑定时更新,不再等到 completeEntry),新增 unbindReceivingDetails 解绑接口(删除 pending 绑定并回退 received_quantity),commitEntryWithBindings 移除 received_quantity 更新逻辑", - "methods": [ - "storage.entry.bindReceivingDetails", - "storage.entry.unbindReceivingDetails", - "storage.entry.completeEntry" - ], - "notes": [ - "storage.entry.bindReceivingDetails:改为绑定即实收,绑定成功后立即更新入库明细 received_quantity;重复调用时先回退旧绑定量再创建新绑定,避免重复累加。", - "storage.entry.unbindReceivingDetails:新增解绑接口,删除该入库明细的所有 pending 绑定记录,并将 received_quantity 回退到绑定前的值;收货明细可用数量随绑定记录删除自动恢复。", - "storage.entry.completeEntry:commitEntryWithBindings 中移除 received_quantity 更新逻辑(received_quantity 已在绑定时更新,completeEntry 仅完成收货单侧入库数量扣减和库存上架)。" - ], - "type": "updated" - }, - { - "version": "2026.06.19-system-01", - "date": "2026-06-19", - "summary": "order.recheckOrder.scanOrder 响应 list[] 新增 items_weight(订单商品总重量g)和 suggested_package_material(推荐包材)字段", - "methods": [ - "order.recheckOrder.scanOrder" - ], - "notes": [ - "响应 list 每项新增 items_weight (number|null):订单商品总重量(g),来源于 wms_order_delivery.items_weight。散单模式每个订单对象包含,团购模式每个波次对象包含(取波次内首个正常订单的重量,为 null 时返回 0)。", - "响应 list 每项新增 suggested_package_material (object|null):推荐包材信息,根据订单商品结构(items_hash + items_crc)匹配 wms_package_material_item_relation 历史绑定记录,按 bind_count 降序取最优匹配。若 items_hash 为空或无匹配记录则为 null。包含子字段:id、code、name、spec、type、weight、length、width、height、bind_count。", - "同步更新 method description 和 list 字段 description,补充新增字段的说明。" - ], - "type": "updated", - "module": "order.recheckOrder" - }, - { - "version": "2026.06.21-system-01", - "date": "2026-06-21", - "summary": "order.bindExpressPackageMaterialByWaybill:入参 package_material_code 改为 package_material_id,类型由 string 改为 number|string", - "methods": [ - "order.bindExpressPackageMaterialByWaybill" - ], - "notes": [ - "入参字段名从 package_material_code 改为 package_material_id。", - "入参类型从 string 改为 number|string,与代码 normalizePackageMaterialId 的实现一致。", - "同步更新该方法 description 中'包材编码'为'包材ID'。" - ], - "type": "updated", - "module": "order" - }, - { - "version": "2026.06.21-system-comboGoods-01", - "date": "2026-06-21", - "summary": "新增 comboGoods 组合商品模块 5 个接口文档:list/create/update/delete/search", - "methods": [ - "comboGoods.list", - "comboGoods.create", - "comboGoods.update", - "comboGoods.delete", - "comboGoods.search" - ], - "notes": [ - "comboGoods.list:组合商品列表查询(分页),支持按 combo_code/combo_name/status/warehouse_id 筛选,返回含 simpleNotation 和 nameNotation 简记字段", - "comboGoods.create:创建组合商品(含明细一次性提交),校验 combo_code 唯一性、子商品有效性和货主一致性,事务保证原子写入", - "comboGoods.update:编辑组合商品(含明细替换),支持部分字段更新,传入 items 则先删旧明细再插入新明细", - "comboGoods.delete:软删除组合商品(status 置为 0)", - "comboGoods.search:关键字搜索组合商品,模糊匹配 combo_code 或 combo_name,仅返回启用状态记录,上限100条", - "数据表:wms_combo_goods(主表)+ wms_combo_goods_item(明细表);子商品校验依赖 wms_stock_warehouse 表", - "代码文件:app/service/systems/comboGoods.js(业务逻辑层)+ app/service/systemMethods/comboGoods.js(接口包装层)", - "isNeedAuth:list/search 无需鉴权,create/update/delete 需要鉴权" - ], - "type": "added", - "module": "comboGoods" - }, - { - "version": "2026.06.21-system-comboGoods-02", - "date": "2026-06-21", - "summary": "comboGoods 模块新增 custom_code(自定义编码)功能:create/update 支持传入 custom_code 并校验按货主唯一,list/search 返回新增 custom_code 字段,search 搜索范围扩展至 custom_code 且优先排列匹配项", - "methods": [ - "comboGoods.list", - "comboGoods.create", - "comboGoods.update", - "comboGoods.search" - ], - "notes": [ - "新增字段 custom_code(VARCHAR(64) NULL),仅做按货主唯一性校验(排除已删除记录),非全局唯一。", - "wms_combo_goods 表新增索引 uk_store_custom_code(warehouse_id, custom_code)。", - "comboGoods.create:新增可选入参 custom_code,如果非空则校验同货主非删除记录中 unique;返回新增 custom_code 字段。", - "comboGoods.update:新增可选入参 custom_code,如果非空则校验同货主非删除记录中 unique(排除自身 id)。", - "comboGoods.list:返回每条记录新增 custom_code 字段。", - "comboGoods.search:搜索条件扩大为 custom_code LIKE / combo_code LIKE / combo_name LIKE,custom_code 匹配项按 ORDER BY CASE 排在前面;返回新增 custom_code 字段。" - ], - "type": "updated" - }, - { - "version": "2026.06.21-system-comboGoods-03", - "date": "2026-06-21", - "summary": "stock.warehouse.search 新增 mode=\"combo\" 组合商品查询模式,新增 id/custom_code 参数,补充组合商品响应结构", - "methods": [ - "stock.warehouse.search" - ], - "notes": [ - "新增入参 mode(查询模式,传 \"combo\" 时搜索组合商品),id(mode=combo 时按组合商品ID精确查询),custom_code(mode=combo 时按自定义编码模糊查询)", - "原有 keyword 参数在 mode=combo 时模糊匹配 combo_code / combo_name / custom_code", - "mode=combo 响应结构新增 combo_code、combo_name、custom_code、items(子商品数组含 item_goods_sku_id/item_quantity)、simpleNotation(stock_id|数量格式)、nameNotation(【数量】商品名称格式)", - "mode=combo 时不返回 stock 模式特有的字段(item_code/goods_code/item_name/sku_property/stock_unit/quantity/locked_quantity/brand_name/item_type/barcodes/store_stock/效期字段/storage)", - "with_stock 和 is_batch 参数在 mode=combo 时不生效" - ], - "type": "updated" - }, - { - "version": "2026.06.22-system-wavePickTaskList-01", - "date": "2026-06-22", - "summary": "order.wave.wavePickTaskList 响应新增 wave_list 数组:每个拣货任务返回关联波次列表", - "methods": [ - "order.wave.wavePickTaskList" - ], - "notes": [ - "wavePickTaskList 响应 list 每项新增 wave_list 数组字段,通过批量查询 wms_wave_pick_task_wave 表获取关联波次详情。", - "wave_list 每项包含:wave_id(波次ID)、wave_no(波次号)、box_no(框号)、status(波次关联状态)、bind_time(绑定时间)、pick_time(拣货完成时间)。", - "无需额外入参,默认对所有拣货任务返回 wave_list;查询为空时返回空数组 []。", - "同步更新 methods/system.json 响应文档。" - ], - "type": "updated", - "module": "order.wave" - }, - { - "version": "2026.06.22-system-order-export-mode-01", - "date": "2026-06-22", - "summary": "order.export 新增 export_mode 参数:支持 waybill(默认,按运单展开)与 item(按商品明细展开)两种导出模式", - "methods": [ - "order.export" - ], - "notes": [ - "新增入参 export_mode/exportMode,枚举值:waybill(默认)— 按运单号展开,每运单一组,items_detail 列汇总商品;item — 按商品明细展开,每商品一行,运单信息汇总填充。", - "方法层(OrderIndexService.export)新增 export_mode/exportMode 解构并透传到 systems.orderExport.exportOrders。", - "同步更新 methods/system.json 文档:description 补充 export_mode 说明,params 新增 export_mode/exportMode 条目。", - "order.export 导出的列新增:业务类型、运单接口、包材ID、包材编码、包材名称。" - ], - "type": "updated", - "module": "order.index" - }, - { - "version": "2026.06.22-system-directInbound-01", - "date": "2026-06-22", - "summary": "新增 storage.directInbound 导入/PDA直接入库模块:getItems(获取入库信息)、addItem(增量添加商品)、commit(提交完成入库并回传)", - "methods": [ - "storage.directInbound.getItems", - "storage.directInbound.addItem", - "storage.directInbound.commit" - ], - "notes": [ - "新增 storage.directInbound 模块,用于非收货单途径的导入/PDA 直接入库场景。", - "storage.directInbound.getItems:根据入库单号获取入库明细及已有的导入/PDA 入库记录,返回每项的可入库余量。", - "storage.directInbound.addItem:按 stock_id 增量添加导入/PDA 入库记录,累加超过该 stock_id 在入库单中的计划总量时拒绝。支持 import(导入)和 pda(PDA)两种方式。", - "storage.directInbound.commit:提交确认完成入库,按实收数量写入 wms_storage 库存和 wms_storage_transaction 流水,同 stock_id 多条明细只写一次库存,更新入库单状态为 COMPLETED 并同步 sync_status=SUCCESS,异步触发奇门/API 回传(按实收数量回传)。不足量提交时未入库商品跳过。", - "新增数据表 wms_inbound_direct_log(migration: 20260622100000-create-wms-inbound-direct-log.js):记录非收货单途径入库操作,含 warehouse_id、stock_id、quantity、inbound_type(import/pda)、entry_order_id、operator 等字段。模型文件:app/model/inbound_direct_log.js。", - "新增操作日志:addItem 记录 DIRECT_INBOUND_ADD(异步),commit 记录 DIRECT_INBOUND_COMMIT(事务内)。commit 响应返回 order_status=COMPLETED 和 sync_status=SUCCESS。", - "涉及文件:app/service/systems/inbound_direct_log.js(业务层)、app/service/systemMethods/storage/direct_inbound.js(包装层)、app/model/inbound_direct_log.js、database/migrations/20260622100000-create-wms-inbound-direct-log.js、methods/system.json(新增导入/PDA入库模块)。", - "E2E 测试:test/e2e_direct_inbound.test.js(53项断言全覆盖)。" - ], - "type": "added", - "module": "storage.directInbound" - }, - { - "version": "2026.06.22-system-directInbound-02", - "date": "2026-06-22", - "summary": "storage.directInbound.addItem 新增批量模式(items 数组),getItems 响应 summary 新增 total_import/total_pda 分类型汇总", - "methods": [ - "storage.directInbound.addItem", - "storage.directInbound.getItems" - ], - "notes": [ - "addItem 新增批量模式:支持传入 items 数组一次添加多条商品,每项含 stock_id/quantity/inbound_type/remark。单条模式(stock_id/quantity/inbound_type 顶层字段)保持向后兼容。批量模式下所有商品共享同一个入库单状态校验,任一商品校验失败整批拒绝。", - "addItem 批量模式响应结构:{ count, total_quantity, items: [...] },items 每项含 id/stock_id/quantity/inbound_type/plan_quantity/existing_before/existing_after/remaining。", - "getItems 响应 summary 新增 total_import(导入入库总数)和 total_pda(PDA入库总数)字段。", - "同步更新 methods/system.json 文档。" - ], - "type": "updated", - "module": "storage.directInbound" - }, - { - "version": "2026.06.22-system-directInbound-03", - "date": "2026-06-22", - "summary": "storage.directInbound 新增 space_id 库位支持:addItem 支持传入 space_id(单条和批量),commit 从入库记录取 space_id 写入 wms_storage 替代硬编码 1", - "methods": [ - "storage.directInbound.addItem", - "storage.directInbound.commit", - "storage.directInbound.getItems" - ], - "notes": [ - "addItem 新增可选入参 space_id(单条模式顶层字段 / 批量模式 items[].space_id),指定存放库位ID,关联 wms_location_space.id。", - "wms_inbound_direct_log 表新增 space_id 字段(migration: 20260622110000-add-space-id-to-wms-inbound-direct-log.js)。", - "commit 从入库记录中取第一个非空 space_id 写入 wms_storage,无记录时兜底使用库位 1。", - "getItems 响应中 direct_logs 每条记录包含 space_id 字段。", - "同步更新 methods/system.json 文档及模型文件。" - ], - "type": "updated", - "module": "storage.directInbound" - }, - { - "version": "2026.06.23-system-01", - "date": "2026-06-23", - "summary": "入库单(wms_entry_order)新增 CREATED 状态:order_status ENUM 从 CREATING/PENDING/CONFIRMED/PARTIAL_RECEIVED/COMPLETED/CANCELLED 扩展为 CREATING/CREATED/PENDING/CONFIRMED/PARTIAL_RECEIVED/COMPLETED/CANCELLED;默认值从 PENDING 变更为 CREATED;validTransitions 增加 CREATED 节点(CREATED→PENDING/CANCELLED,CREATING→CREATED/CANCELLED)", - "methods": [ - "storage.entry.list", - "storage.entry.get", - "storage.entry.cancel", - "storage.entry.completeEntry", - "storage.entry.bindReceivingDetails" - ], - "notes": [ - "Model 层:app/model/entry_order.js order_status ENUM 新增 CREATED,默认值从 PENDING 变更为 CREATED", - "Service 层:app/service/systems/entry_order.js addOrder 创建后状态从 CREATING→CREATED,validTransitions 增加 CREATED 节点", - "Service 层:app/service/systems/storage/entry.js createEntry 默认状态 PENDING→CREATED", - "Service 层:app/service/systems/storage/inventory.js 快捷入库默认 CREATED", - "文档同步:storage.entry.list where.order_status 枚举补充 CREATED;storage.entry.get description 补充 order_status 枚举含 CREATED;storage.entry.cancel 补充 CREATED 可作废说明;storage.entry.completeEntry/bindReceivingDetails 补充可操作状态含 CREATED" - ], - "type": "updated", - "module": "storage.entry" - }, - { - "version": "2026.06.23-system-02", - "date": "2026-06-23", - "summary": "入库单 CREATED 状态限制:CREATED 状态不允许绑定货物和完成入库,仅 PENDING/CONFIRMED/PARTIAL_RECEIVED 状态可操作", - "methods": [ - "storage.entry.cancel", - "storage.entry.completeEntry", - "storage.entry.bindReceivingDetails", - "storage.entry.unbindReceivingDetails" - ], - "notes": [ - "completeEntry / bindReceivingDetails / unbindReceivingDetails / commitEntryWithBindings 的可操作状态从原来的白名单(包含 CREATED)改为 PENDING / CONFIRMED / PARTIAL_RECEIVED,排除 CREATED。", - "CREATED 状态仅允许确认入库(→PENDING)或作废(→CANCELLED)。", - "storage.entry.cancel 补充明确 COMPLETED 状态不可作废,CREATED 可作废。", - "同步更新对应 method 的 description、errors 描述。" - ], - "type": "updated", - "module": "storage.entry" - }, - { - "version": "2026.06.23-system-03", - "date": "2026-06-23", - "summary": "storage.entry.cancel:CONFIRMED(已确认)状态不再允许作废,仅 CREATED 和 PENDING 可作废", - "methods": [ - "storage.entry.cancel" - ], - "notes": [ - "canCancel() 白名单移除 CONFIRMED,仅保留 CREATED 和 PENDING", - "validTransitions 中 CONFIRMED 不再可转为 CANCELLED", - "cancel() 方法新增 CONFIRMED 状态拦截,返回 400:已确认入库单不允许作废,请先完成收货", - "PARTIAL_RECEIVED 仍可作废,COMPLETED 不允许作废(行为不变)", - "更新 description 明确各状态可作废规则,errors 中补充 CONFIRMED 不可作废的说明" - ], - "type": "updated", - "module": "storage.entry" - }, - { - "version": "2026.06.23-system-04", - "date": "2026-06-23", - "summary": "入库单状态从 7 个简化为 5 个:移除 CONFIRMED 和 PARTIAL_RECEIVED,最终状态为 CREATING/CREATED/PENDING/COMPLETED/CANCELLED;同步更新 storage.entry 所有 method 的状态枚举和错误信息描述", - "methods": [ - "storage.entry.list", - "storage.entry.get", - "storage.entry.cancel", - "storage.entry.completeEntry", - "storage.entry.bindReceivingDetails", - "storage.entry.unbindReceivingDetails" - ], - "notes": [ - "wms_entry_order.order_status ENUM 从 CREATING/CREATED/PENDING/CONFIRMED/PARTIAL_RECEIVED/COMPLETED/CANCELLED 简化为 CREATING/CREATED/PENDING/COMPLETED/CANCELLED", - "storage.entry.list: where.order_status 描述和 where 参数描述中的状态枚举同步更新", - "storage.entry.get: entryOrder.order_status 描述同步更新", - "storage.entry.cancel: 移除 PARTIAL_RECEIVED 可作废和 CONFIRMED 不可作废的描述,仅保留 CREATED 和 PENDING 可作废,COMPLETED 不可作废", - "storage.entry.completeEntry: 可完成状态从 PENDING/CONFIRMED/PARTIAL_RECEIVED 改为仅 PENDING", - "storage.entry.bindReceivingDetails: 可操作状态从 PENDING/CONFIRMED/PARTIAL_RECEIVED 改为仅 PENDING", - "storage.entry.unbindReceivingDetails: 可操作状态从 PENDING/CONFIRMED/PARTIAL_RECEIVED 改为仅 PENDING", - "cancel() 取消 CONFIRMED 状态拦截(状态已不存在),COMPLETED 拦截保持不变" - ], - "type": "updated" - }, - { - "version": "2026.06.23-system-05", - "date": "2026-06-23", - "summary": "入库单状态语义调整:CREATED=已创建待审核,PENDING=已审核;同步更新 storage.entry 所有 method 的 description 中状态说明", - "methods": [ - "storage.entry.list", - "storage.entry.get", - "storage.entry.cancel", - "storage.entry.completeEntry", - "storage.entry.bindReceivingDetails", - "storage.entry.unbindReceivingDetails" - ], - "notes": [ - "CREATED 含义从\"已创建\"改为\"已创建待审核\"(需审核后才能绑定和完成入库)", - "PENDING 含义从\"待收货/收货中\"改为\"已审核\"(审核通过,可绑定和完成入库)", - "CREATED→PENDING 步骤语义:绑定审核", - "addOrder() 新增可选参数 autoReview(boolean,默认 false),false 创建后状态 CREATED(需审核),true 创建后状态 PENDING(自动审核通过)", - "快捷入库 quickPutaway 内部流程改为调用 addOrder({autoReview:true}) → bindReceivingDetails → commitEntryWithBindings,不再直接写库存,对外返回格式不变", - "storage.entry.list / storage.entry.get description 中补充 CREATED/PENDING 语义说明", - "storage.entry.cancel description 中补充可作废状态说明", - "storage.entry.completeEntry description 中补充可完成状态说明", - "storage.entry.bindReceivingDetails / storage.entry.unbindReceivingDetails description 中补充可绑定/解绑状态说明" - ], - "type": "updated" - }, - { - "version": "2026.06.23-system-06", - "date": "2026-06-23", - "summary": "storage.inventory.quickPutaway description 更新:补充内部已改为走 addOrder→bind→commit 链路,不再直接写库存", - "methods": [ - "storage.inventory.quickPutaway" - ], - "notes": [ - "快捷入库 quickPutaway 内部流程改为调用 addOrder({autoReview:true}) → bindReceivingDetails → commitEntryWithBindings,不再直接写库存,外部返回格式不变", - "description 中补充内部调用链路说明" - ], - "type": "updated" - }, - { - "version": "2026.06.23-system-07", - "date": "2026-06-23", - "summary": "storage.entry 大范围清理:删除 bindReceivingDetails/unbindReceivingDetails(明细级绑定已弃用),更新 completeEntry 为纯状态变更(不再做库存写入/异步匹配)", - "methods": [ - "storage.entry.bindReceivingDetails", - "storage.entry.unbindReceivingDetails", - "storage.entry.completeEntry" - ], - "notes": [ - "storage.entry.bindReceivingDetails:已从代码中删除,明细级绑定收货单功能下线。库存写入统一由 storage.inventory.matchPutaway 完成。", - "storage.entry.unbindReceivingDetails:已从代码中删除,明细级解绑功能下线。", - "storage.entry.completeEntry:改为纯状态变更(PENDING → COMPLETED),不再做库存写入和异步匹配回调。库存写入统一由 storage.inventory.matchPutaway 完成。" - ], - "type": "updated" - }, - { - "version": "2026.06.23-system-08", - "date": "2026-06-23", - "summary": "storage.inventory 清理:删除 quickPutaway(快捷入库已下线,统一由 matchPutaway 完成匹配入库)", - "methods": [ - "storage.inventory.quickPutaway" - ], - "notes": [ - "storage.inventory.quickPutaway:已从代码中删除,快捷入库功能下线。请使用 storage.inventory.matchPutaway 替代。" - ], - "type": "removed" - }, - { - "version": "2026.06.23-system-09", - "date": "2026-06-23", - "summary": "入库流程弃用清理:bindReceivingDetails/unbindReceivingDetails 标记为已删除并补充弃用原因,completeEntry 明确不涉及库存写入", - "methods": [ - "storage.entry.bindReceivingDetails", - "storage.entry.unbindReceivingDetails", - "storage.entry.completeEntry" - ], - "notes": [ - "storage.entry.bindReceivingDetails 与 storage.entry.unbindReceivingDetails 已从代码中移除,入库单与收货单关系改为 wms_entry_order_receiving 主表级关联,不再需要逐明细绑定/解绑。", - "wms_entry_receiving_binding 表不再写入新数据。", - "storage.entry.completeEntry 仅做状态变更(PENDING→COMPLETED),库存写入统一由 storage.inventory.matchPutaway 完成。", - "commitEntryWithBindings(内部方法)不再使用,库存写入统一走 matchPutaway 链路。" - ], - "type": "updated" - }, - { - "version": "2026.06.23-system-10", - "date": "2026-06-23", - "summary": "quickPutaway 弃用说明完善:明确替代方案为 matchPutaway;matchPutaway 标明为目前唯一库存写入入库链路", - "methods": [ - "storage.inventory.quickPutaway", - "storage.inventory.matchPutaway" - ], - "notes": [ - "storage.inventory.quickPutaway 已从代码中移除,替代方案为 storage.inventory.matchPutaway(支持多收货单+多入库单批量匹配入库)。", - "storage.inventory.matchPutaway 是目前唯一的库存写入入库链路,入库单状态变更由 storage.entry.completeEntry 单独处理。", - "本次为文档补充说明,不涉及代码变更。" - ], - "type": "updated" - }, - { - "version": "2026.06.23-system-11", - "date": "2026-06-23", - "summary": "删除 storage.receiving.getAvailableInboundQuantity:该方法依赖已弃用的 wms_entry_receiving_binding 明细绑定表,已从代码中移除", - "methods": [ - "storage.receiving.getAvailableInboundQuantity" - ], - "notes": [ - "该方法原用于按 stock_id 查询已审核收货单中各明细的可入库数量(actual_quantity - stored_quantity - pending_allocated_quantity)。", - "由于 wms_entry_receiving_binding 明细绑定表已弃用,入库单与收货单的关联改为通过 wms_entry_order_receiving 主表级关联,该查询方法不再适用。", - "替代方案:使用 storage.entry.get 查询入库单详情,通过顶层 receivingBindings 获取关联的收货单信息。" - ], - "type": "removed" - }, - { - "version": "2026.06.23-system-12", - "date": "2026-06-23", - "summary": "storage.entry.get 响应结构变更:不再返回 items[].bindings(明细级绑定),改为返回顶层 receivingBindings(主表级关联收货单信息)", - "methods": [ - "storage.entry.get" - ], - "notes": [ - "移除 items[].bindings(明细级绑定,原基于 wms_entry_receiving_binding 表),该绑定表已弃用。", - "新增顶层 receivingBindings(wms_entry_order_receiving 主表级关联),每项含 id/receiving_id/receiving(含 id/receiving_number/status/storage_status/created_at)。", - "items 中保留 external_item_code/external_item_id/warehouse_item_code/warehouse_item_name/warehouse_item_spec 等扁平化字段。", - "响应结构变更与 storage.directInbound.getItems 的返回结构对齐,后者同样使用顶层 receivingBindings。" - ], - "type": "modified" - }, - { - "version": "2026.06.23-system-13", - "date": "2026-06-23", - "summary": "新增 storage.entry.* 下 4 个 DirectInbound 方法:getDirectInboundItems、addItem、commit、removeItem,原 storage.directInbound.* 方法保留向后兼容并标记 deprecated", - "methods": [ - "storage.entry.getDirectInboundItems", - "storage.entry.addItem", - "storage.entry.commit", - "storage.entry.removeItem" - ], - "notes": [ - "storage.entry.getDirectInboundItems:获取入库单的导入/PDA 入库信息,参数与响应格式同原 storage.directInbound.getItems", - "storage.entry.addItem:按商品增量添加导入/PDA 入库记录(支持单条和批量),参数与响应格式同原 storage.directInbound.addItem", - "storage.entry.commit:提交确认完成导入/PDA 入库,按实收数量写入库存并异步回传奇门/API,参数与响应格式同原 storage.directInbound.commit", - "storage.entry.removeItem:移除一条导入/PDA 入库记录,参数与响应格式同原 storage.directInbound.removeItem", - "底层 inbound_direct_log.js 实现不变,仅入口从 storage.directInbound 模块迁入 storage.entry 模块" - ], - "type": "added" - }, - { - "version": "2026.06.23-system-14", - "date": "2026-06-23", - "summary": "storage.directInbound.* 下 4 个方法标记 deprecated,指向 storage.entry.* 下对应新方法", - "methods": [ - "storage.directInbound.getItems", - "storage.directInbound.addItem", - "storage.directInbound.commit", - "storage.directInbound.removeItem" - ], - "notes": [ - "storage.directInbound.getItems → 替代方法 storage.entry.getDirectInboundItems", - "storage.directInbound.addItem → 替代方法 storage.entry.addItem", - "storage.directInbound.commit → 替代方法 storage.entry.commit", - "storage.directInbound.removeItem → 替代方法 storage.entry.removeItem", - "旧方法保留向后兼容,参数与响应格式不变,仅入口模块变更" - ], - "type": "deprecated" - }, - { - "version": "2026.06.23-system-15", - "date": "2026-06-23", - "summary": "storage.inventory.matchPutaway 标记 deprecated,替代方案为 storage.entry.commit", - "methods": [ - "storage.inventory.matchPutaway" - ], - "notes": [ - "storage.inventory.matchPutaway 已弃用,请迁移至 storage.entry.commit", - "commit 提供导入/PDA 入库完成确认功能,按实收数量写入库存并异步回传" - ], - "type": "deprecated" - }, - { - "version": "2026.06.23-system-16", - "date": "2026-06-23", - "summary": "清理已弃用 method 条目:从 system.json 删除 storage.entry.bindReceivingDetails、storage.entry.unbindReceivingDetails、storage.inventory.matchPutaway 三个已从代码中移除的 method 文档条目", - "methods": [ - "storage.entry.bindReceivingDetails", - "storage.entry.unbindReceivingDetails", - "storage.inventory.matchPutaway" - ], - "notes": [ - "storage.entry.bindReceivingDetails:已从代码中删除,明细级绑定收货单功能下线。入库单与收货单关系改为 wms_entry_order_receiving 主表级关联。", - "storage.entry.unbindReceivingDetails:已从代码中删除,明细级解绑功能下线。", - "storage.inventory.matchPutaway:已从代码中删除,匹配入库功能下线。替代方案为 storage.entry.commit。", - "storage.inventory.quickPutaway:之前已标记 [已删除],本次确认条目保留(与 matchPutaway 同一 group,保留作为历史参考)。", - "storage.entry.create / addDetail / deleteDetail / detailChange:systems 层方法已删除,但从未在 system.json 中暴露为 API method,无需文档变更。" - ], - "type": "removed" - }, - { - "version": "2026.06.23-system-17", - "date": "2026-06-23", - "summary": "storage.entry.get 响应新增仓库库存、条码、入库进度字段", - "methods": [ - "storage.entry.get" - ], - "notes": [ - "items 每项新增 warehouse_quantity(仓库库存总量)、warehouse_locked_quantity(锁定数量)、warehouse_is_batch_mgmt(是否批次管理)、warehouse_is_shelf_life_mgmt(是否效期管理)、warehouse_image_url(商品图片URL)、warehouse_is_images(是否有图片)", - "items 每项新增 barcodes(条码列表,每项含 id/barcode/sku_property)", - "items 每项新增 direct_inbound_quantity(导入/PDA已入库数量)、remaining_quantity(剩余可入库数量)", - "同步更新 response 字段定义,将原有概要描述展开为逐字段说明", - "仅文档同步,不改业务代码" - ], - "type": "updated", - "module": "storage.entry" - }, - { - "version": "2026.06.24-system-01", - "date": "2026-06-24", - "summary": "新增批量绑定入库单明细与收货单明细接口 storage.entry.bindReceivingDetails,支持明细级数量分配与部分成功", - "methods": [ - "storage.entry.bindReceivingDetails" - ], - "notes": [ - "新增 storage.entry.bindReceivingDetails:批量绑定入库单明细与收货单明细,支持明细级数量分配与部分成功", - "storage.entry.get 追加 available_receiving_details 字段加载可匹配的收货单明细" - ], - "type": "addition" - }, - { - "version": "2026.06.24-system-02", - "date": "2026-06-24", - "summary": "storage.entry.bindReceivingDetails:response.failed 字段从简单 reason 描述升级为结构化错误返回(含 error_code、message、detail);同步更新 400 错误说明", - "methods": [ - "storage.entry.bindReceivingDetails" - ], - "notes": [ - "response.failed 新增 items 定义,每项含 entry_item_id、receiving_detail_id、allocated_quantity、error_code、message、detail", - "error_code 枚举:ENTRY_ITEM_NOT_FOUND、STOCK_NOT_FOUND、RECEIVING_DETAIL_MISMATCH、RECEIVING_DETAIL_NOT_FOUND、INSUFFICIENT_AVAILABLE_QUANTITY、ENTRY_ORDER_STATUS_INVALID", - "400 错误说明更新:入库单状态不允许绑定时,所有 bindings 均返回 failed 且 error_code 为 ENTRY_ORDER_STATUS_INVALID" - ], - "type": "updated" - }, - { - "version": "2026.06.24-system-03", - "date": "2026-06-24", - "summary": "新增 storage.entry.quickInbound 快捷直入/虚拟入库接口", - "methods": [ - "storage.entry.quickInbound" - ], - "notes": [ - "新增 quickInbound 方法:入库单所有商品按明细数量一键直入虚拟库位(space_id=2),跳过收货/质检流程", - "支持状态:CREATED、PENDING 状态的入库单可执行", - "拒绝状态:CANCELLED(已作废)、COMPLETED(已完成)", - "事务内操作:更新入库明细收货量、累加库存总量、写入库存流水、写入虚拟库位库存、变更入库单状态为 COMPLETED", - "事务外异步回传奇门/API" - ], - "type": "addition" - }, - { - "version": "2026.06.24-system-04", - "date": "2026-06-24", - "summary": "收窄 storage.entry.quickInbound 状态约束:仅允许 CREATED 状态执行快捷直入", - "methods": [ - "storage.entry.quickInbound" - ], - "notes": [ - "收窄状态约束:仅允许 CREATED 状态执行快捷直入,PENDING 状态不再允许" - ], - "type": "updated" - }, - { - "version": "2026.06.24-system-05", - "date": "2026-06-24", - "summary": "修正 storage.entry.quickInbound errors[4] message 以匹配代码实现:改为动态状态描述", - "methods": [ - "storage.entry.quickInbound" - ], - "notes": [ - "errors[4].message 从「入库单状态不允许快捷直入(仅支持CREATED状态)」改为「入库单状态不允许快捷直入,当前状态:非CREATED(如PENDING等)」,反映代码中 `${entryOrder.order_status}` 动态模板特性" - ], - "type": "updated" - }, - { - "version": "2026.06.24-system-06", - "date": "2026-06-24", - "summary": "新增入库单与收货单商品对照预览接口", - "methods": [ - "storage.entry.receivingCompare" - ], - "notes": [ - "新增 storage.entry.receivingCompare 方法:给定入库单ID和收货单ID,返回入库商品与收货商品的逐行对照视图。", - "comparison 列表中每项含 match_status(matched/entry_only),以及入库侧和收货侧的商品与数量信息。", - "receiving_only 列表包含仅存在于收货单中的商品明细。", - "summary 提供 total_entry_items、matched_items、entry_only_items、receiving_only_items 汇总统计。", - "纯只读接口,不产生任何数据写入或状态变更。" - ], - "type": "addition" - }, - { - "version": "2026.06.24-system-07", - "date": "2026-06-24", - "summary": "setting.warehouse 模块新增 7 个发件人信息字段到 subject_config", - "methods": [ - "setting.warehouse.getSettings", - "setting.warehouse.saveSettings" - ], - "notes": [ - "在 getSettings 的 response 中新增 subject_config.sender_name(发件人姓名)、sender_tel(发件人电话)、province_name(省份)、city_name(城市)、district_name(区/县)、town_name(镇/街道)、address(详细地址)共 7 个字段,均为可选字符串,默认空。", - "在 saveSettings 的 params 中新增对应的 7 个入参字段,source 为 body.subject_config,均为可选字符串,默认空,并标注 maxLength。", - "字段 key 与 store_warehouse.policy_config 中发件人字段命名完全一致,统一仓库级发件人默认值配置。", - "getFieldMeta 接口无需修改文档——其返回的字段元信息由 WAREHOUSE_SETTING_FIELDS 定义在运行时自动生成,新增字段会随代码自动纳入返回列表。" - ], - "type": "updated", - "module": "setting.warehouse" - }, - { - "version": "2026.06.25-system-01", - "date": "2026-06-25", - "summary": "新增 storage.entry.bindReceiving 接口:将收货单绑定到入库单(主表级关联,不做明细数量分配)", - "methods": [ - "storage.entry.bindReceiving" - ], - "notes": [ - "新增入库单与收货单的主表绑定接口,与已有的 storage.entry.bindReceivingDetails(明细级绑定)区分:bindReceiving 仅建立 wms_entry_order_receiving 主表关联,不做明细数量分配。", - "入库单需为 CREATED 或 PENDING 状态;收货单需存在、同仓库且未取消。", - "支持部分成功模式:逐条校验收货单,校验通过的建立绑定,不通过的返回 error_code 和 message。", - "响应包含 success(成功列表)、failed(失败列表)、success_count、failed_count。" - ], - "type": "addition" - }, - { - "version": "2026.06.25-system-02", - "date": "2026-06-25", - "summary": "storage.entry.bindReceiving:新增 OWNER_MISMATCH 错误码,用于收货单与入库单货主不一致校验", - "methods": [ - "storage.entry.bindReceiving" - ], - "notes": [ - "在 storage.entry.bindReceiving 的 errors 数组中新增 OWNER_MISMATCH(收货单与入库单货主不一致)错误码。", - "同步更新 response.failed.error_code 的枚举描述,补充 OWNER_MISMATCH。" - ], - "type": "updated", - "module": "storage.entry" - }, - { - "version": "2026.06.25-system-03", - "date": "2026-06-25", - "summary": "storage.entry.bindReceiving:新增收货单未审核错误码 RECEIVING_NOT_REVIEWED", - "methods": [ - "storage.entry.bindReceiving" - ], - "notes": [ - "在 errors 数组中新增错误码 RECEIVING_NOT_REVIEWED(收货单未审核),用于标识绑定前收货单尚未完成审核的场景。", - "同步更新 response.failed.items.properties.error_code.description,在可能值列表中补充 RECEIVING_NOT_REVIEWED。" - ], - "type": "updated" - }, - { - "version": "2026.06.25-system-04", - "date": "2026-06-25", - "summary": "storage.entry.list 响应新增 receivingBindings 和 hasReceiving 字段,where 新增 hasReceiving 虚拟筛选条件", - "methods": [ - "storage.entry.list" - ], - "notes": [ - "响应 list 数组每项新增 receivingBindings(收货单绑定列表,主表级关联)和 hasReceiving(是否存在收货单绑定,boolean)字段。", - "入参 where 新增 hasReceiving 虚拟筛选字段,传 true/false 筛选已绑定/未绑定收货单的入库单,内部通过 wms_entry_order_receiving 表查询实现。", - "同步更新 description 以说明 hasReceiving 虚拟筛选的使用方式。" - ], - "type": "updated" - }, - { - "version": "2026.06.26-system-01", - "date": "2026-06-26", - "summary": "storage.entry.receivingCompare 支持多收货单对照预览", - "methods": [ - "storage.entry.receivingCompare" - ], - "notes": [ - "支持多个收货单ID对照预览(新增 receiving_ids 数组入参,优先于 receiving_id 使用)", - "入参 receiving_id 从 required 改为 optional,与 receiving_ids 二选一", - "出参结构调整为 comparisons[] 数组(多收货单),新增 errors[] 和 total_summary", - "向后兼容原 receiving_id 单值传参(底层自动转为单元素数组)", - "新增 400 错误码:receiving_ids 或 receiving_id 必填", - "移除 404 错误码:收货单不存在(已改为在 comparisons[]/errors[] 中以 status=error 形式返回)" - ], - "type": "enhancement" - }, - { - "version": "2026.06.26-system-02", - "date": "2026-06-26", - "summary": "storage.receiving.getReceivingList 新增 filterDepleted 可选参数;storage.entry.receivingCompare 返回值 receiving_only 字段新增 receiving_allocated 和 receiving_available 说明", - "methods": [ - "storage.receiving.getReceivingList", - "storage.entry.receivingCompare" - ], - "notes": [ - "storage.receiving.getReceivingList:params 新增 filterDepleted(boolean, 默认 false),用于过滤掉无可再用量的收货单(所有明细已被其他入库单 committed 绑定占满)。", - "storage.entry.receivingCompare:response 中 receiving_only 字段的 description 补充 receiving_allocated(已分配数量)和 receiving_available(可再用量)两个子字段说明。" - ], - "type": "updated" - }, - { - "version": "2026.06.26-system-03", - "date": "2026-06-26", - "summary": "storage.receiving.getReceivingList:新增可选参数 entry_order_id,按入库单商品交集过滤收货单列表", - "methods": [ - "storage.receiving.getReceivingList" - ], - "notes": [ - "新增可选参数 entry_order_id(number),传入入库单 ID 后只返回至少有一条明细的 system_product_id 在入库单明细中存在的收货单。", - "与现有 filterDepleted 参数可组合使用,二者取交集。", - "不传则不过滤,保持原有行为不变。" - ], - "type": "updated" - }, - { - "version": "2026.06.27-system-01", - "date": "2026-06-27", - "summary": "新增 storage.entry.reviewEntry 接口:审核入库单(CREATED→PENDING),需绑定收货单", - "methods": [ - "storage.entry.reviewEntry" - ], - "notes": [ - "新增入库单审核接口,支持 CREATED→PENDING 状态流转。", - "审核前置条件:入库单必须已绑定收货单(EntryOrderReceiving 存在关联记录)。", - "审核通过后写入操作日志(ENTRY_ORDER_REVIEW)。" - ], - "type": "added" - }, - { - "version": "2026.06.29-system-01", - "date": "2026-06-29", - "summary": "storage.inventory.quickPutaway 重新实现:收货单快捷转入库单", - "methods": [ - "storage.inventory.quickPutaway" - ], - "notes": [ - "此前已从代码中删除(2026.06.23-system-08),现由 wms-dev-agent 重新实现。", - "核心流程:参数校验 → 加载收货单及明细 → 检查货主配置 policy_config.allow_receiving_quick_putaway → 按 stock_id(system_product_id)分组合并数量 → 创建入库单 SCRK(自动审批到 PENDING)→ 写入 wms_entry_order_receiving 主表级绑定 → 更新收货单 storage_status 为 partial → 更新收货单明细 storage_status/stored_quantity → 提交事务。", - "前置条件:收货单状态为 completed 且 is_review=true(已审核),货主仓库签约配置 allow_receiving_quick_putaway=1。", - "与旧实现的区别:不涉及 wms_entry_receiving_binding 明细级绑定,使用 wms_entry_order_receiving 主表级关联;直接创建入库单并写入绑定,不再走 matchPutaway 匹配链路。", - "返回:entry_order_id、entry_order_code(SCRK 格式)、order_status(PENDING)、receiving_id、total_lines、total_quantity。" - ], - "type": "addition" - }, - { - "version": "2026.06.29-system-02", - "date": "2026-06-29", - "summary": "storage.entry.list:quickWhere 搜索范围扩展,新增收货单 ID(receiving_id)支持 PDA 扫描托盘唛头搜索绑定的入库单", - "methods": [ - "storage.entry.list" - ], - "notes": [ - "quickWhere 搜索字段新增 receiving_id(收货单 ID / 托盘唛头),通过 wms_entry_order_receiving 绑定表关联搜索。", - "同步更新 description 和 where 参数的 description,明确 quickWhere 完整搜索字段列表:entry_order_code、purchase_order_code、supplier_name、store_name、warehouse_name、receiving_id。" - ], - "type": "updated", - "module": "storage" - }, - { - "version": "2026.06.29-system-03", - "date": "2026-06-29", - "summary": "新增 storage.receiving.scanDetail 接口:PDA 上架扫码定位收货明细", - "methods": [ - "storage.receiving.scanDetail" - ], - "notes": [ - "新增 storage.receiving.scanDetail(PDA专用):通过 entry_order_id + barcode 扫码快速定位收货明细。", - "搜索逻辑:纯数字 barcode 优先按明细 ID 精确匹配(托盘唛头),未命中则模糊匹配商品条码;非纯数字仅模糊匹配商品条码。", - "入参:entry_order_id(必填 number)、barcode(必填 string)。", - "出参:detail_id、receiving_id、barcode、product_name、actual_quantity、receiving_status。", - "错误码:入库单不存在或无权访问、该入库单尚未关联收货单、未找到匹配的收货明细。" - ], - "type": "added" - }, - { - "version": "2026.06.29-system-04", - "date": "2026-06-29", - "summary": "storage.receiving.scanDetail 响应结构从单条改为列表:返回 { list, total } 支持同一条码匹配多条明细", - "methods": [ - "storage.receiving.scanDetail" - ], - "notes": [ - "响应结构变更:原返回 data.detail_id/data.receiving_id 等单条字段,现改为顶层 list 数组 + total 计数。", - "同一条码可能匹配到多条收货明细(不同收货单的同一商品),以列表形式返回所有匹配结果。", - "list 中每条明细包含 detail_id/receiving_id/barcode/product_name/actual_quantity/receiving_status。", - "补充错误码:用户未绑定仓库、入库单ID/条码为空、未找到可用的收货明细、500服务器错误。", - "PDA专用接口,description 更新说明匹配逻辑。" - ], - "type": "updated", - "module": "storage.receiving" - }, - { - "version": "2026.06.30-system-01", - "date": "2026-06-30", - "summary": "新增 storage.entry.containerList:PDA 上架时拉取入库单绑定收货单中指定商品的可用容器列表", - "methods": [ - "storage.entry.containerList" - ], - "notes": [ - "新增接口 storage.entry.containerList,用于 PDA 上架场景拉取入库单已绑定收货单中指定 stock_id 的可用收货明细(容器)列表。", - "入参:entry_order_id(入库单ID,必填)、stock_id(商品 stock_id,必填)。", - "出参:data.list 返回可用明细列表,每项含 detail_id、receiving_id、barcode、product_name、actual_quantity、receiving_status;data.total 为总数。", - "已绑定占用的收货明细(wms_entry_receiving_binding 中已有记录且未软删除)会被排除。", - "PDA 专用接口,无需额外鉴权(isNeedAuth=false)。" - ], - "type": "added" - }, - { - "version": "2026.06.30-system-02", - "date": "2026-06-30", - "summary": "storage.entry.addItem 入参变更:entry_order_code → entry_order_id(number);quantity 改为可选(传入 receiving_detail_id 时自动计算);新增 receiving_detail_id/allocated_quantity 参数支持 PDA 上架收货明细绑定模式;space_id 绑定模式下必填", - "methods": [ - "storage.entry.addItem" - ], - "notes": [ - "入参 entry_order_code(string) → entry_order_id(number),与底层 inboundDirectLog.addItem 实现对齐", - "quantity 改为可选:传入 receiving_detail_id 时自动从收货明细计算可用数量(actual_quantity - 已绑定数量)", - "新增 receiving_detail_id 参数:PDA 上架绑定收货明细时传入,触发预占绑定(wms_entry_receiving_binding status=pending)", - "新增 allocated_quantity 参数:预分配数量,默认等于 quantity", - "space_id 在绑定模式下必填;非绑定模式可选(commit 时兜底为 1)", - "PENDING 状态入库单必须传 receiving_detail_id 且已绑定收货单方可操作", - "CREATED + 已绑定收货单的入库单需先审核(reviewEntry)后才能上架", - "批量模式 items 数组同步支持 receiving_detail_id/allocated_quantity 字段", - "补充完整错误码列表:超量、可用数量不足、状态校验等" - ], - "type": "updated" - }, - { - "version": "2026.06.30-system-03", - "date": "2026-06-30", - "summary": "storage.entry.commit 入参变更:entry_order_code → entry_order_id(number),与底层 inboundDirectLog.commit 实现对齐", - "methods": [ - "storage.entry.commit" - ], - "notes": [ - "入参 entry_order_code(string) → entry_order_id(number),与底层 inboundDirectLog.commit(entryOrderId) 实现对齐", - "补充 description 说明先同步后写库两段式流程:① 奇门/API 回传 → ② onSuccess 内事务写库存", - "补充 commit 后 EntryReceivingBinding 状态从 pending 更新为 committed 的说明" - ], - "type": "updated" - }, - { - "version": "2026.06.30-system-04", - "date": "2026-06-30", - "summary": "storage.directInbound.commit 入参变更:entry_order_code → entry_order_id(number),与底层 inboundDirectLog.commit 实现对齐", - "methods": [ - "storage.directInbound.commit" - ], - "notes": [ - "入参 entry_order_code(string) → entry_order_id(number),与底层 inboundDirectLog.commit(entryOrderId) 实现对齐", - "该方法已标记 deprecated,推荐使用 storage.entry.commit" - ], - "type": "updated" - }, - { - "version": "2026.06.30-system-05", - "date": "2026-06-30", - "summary": "storage.entry.getDirectInboundItems 响应结构重构:entryOrder 精简字段,items[].count→planned、direct_inbound_quantity→completed,items[].bindings 新增,移除 direct_logs/summary 等冗余字段", - "methods": [ - "storage.entry.getDirectInboundItems" - ], - "notes": [ - "entryOrder 精简为 id / entry_order_code / order_status / store_remask 四个字段", - "items[].count → planned(计划数量),items[].direct_inbound_quantity → completed(已完成数量)", - "items[].bindings 新增,结构为 { detail_id, binding_id, allocated_quantity, space_id, space_name }", - "items[].stock 新增,返回 getStockDetails 缓存的商品详情(item_code、item_name、barcodes 等)", - "移除 direct_logs(现有响应中已不存在该顶层字段)", - "移除 summary(现有响应中已不存在该字段)", - "移除 items[].received_quantity、items[].remaining_quantity、items[].pending_binding_total 等旧字段", - "新增 receivingBindings 字段说明:入库单层级收货单绑定关系" - ], - "type": "updated" - }, - { - "version": "2026.06.30-system-06", - "date": "2026-06-30", - "summary": "storage.directInbound.getItems 响应结构重构:entryOrder 精简字段,items[].count→planned、direct_inbound_quantity→completed,items[].bindings 新增,移除 direct_logs/summary 等冗余字段", - "methods": [ - "storage.directInbound.getItems" - ], - "notes": [ - "响应结构与 storage.entry.getDirectInboundItems 对齐(两者共用同一个底层实现 inboundDirectLog.getItems)", - "entryOrder 精简为 id / entry_order_code / order_status / store_remask", - "items[].count → planned,items[].direct_inbound_quantity → completed", - "items[].bindings 新增 { detail_id, binding_id, allocated_quantity, space_id, space_name }", - "items[].stock 新增", - "移除 direct_logs、summary、items[].received_quantity、items[].remaining_quantity 等旧字段", - "新增 receivingBindings 字段" - ], - "type": "updated" - }, - { - "version": "2026.06.30-system-07", - "date": "2026-06-30", - "summary": "storage.entry.containerList 响应结构补充 stock 字段:返回商品详情(item_code、item_name、barcodes 等)", - "methods": [ - "storage.entry.containerList" - ], - "notes": [ - "响应 list[].stock 字段补充为必返回:通过 getStockDetails 批量获取商品详情缓存", - "stock 对象包含 item_code、item_name、sku_property、barcodes 等字段" - ], - "type": "updated" - }, - { - "version": "2026.06.30-system-08", - "date": "2026-06-30", - "summary": "storage.receiving.scanDetail 响应结构补充 stock 字段:返回商品详情(item_code、item_name、barcodes 等)", - "methods": [ - "storage.receiving.scanDetail" - ], - "notes": [ - "响应 list[].stock 字段补充为必返回:通过 getStockDetails 批量获取商品详情缓存", - "stock 对象包含 item_code、item_name、sku_property、barcodes 等字段", - "完善 error 列表:补充 未找到可用的收货明细、未找到匹配的收货明细、入库单ID不能为空、扫描条码不能为空 等错误" - ], - "type": "updated" - }, - { - "version": "2026.06.30-system-09", - "date": "2026-06-30", - "summary": "订单列表 list 响应新增 store_remark(货主备注)字段", - "methods": [ - "order.list", - "order.reviewOrder.list", - "order.pendingOrder.list", - "order.expectionOrder.list", - "order.entrustOrder.list", - "order.deliveryOrder.list", - "order.deliveryExpectionOrder.list", - "order.archiveOrder.list" - ], - "notes": [ - "数据库字段 store_remask,返回给前端的字段名为 store_remark。", - "服务层从 wms_store_warehouse.store_remask 按 store_id+warehouse_id 聚合批量填充。", - "货主备注值可能为空字符串(当货主未设置备注时)。", - "该字段对订单列表的所有 method 均适用(current/dispatch/outsourced/history 模型均返回)。" - ], - "type": "updated" - }, - { - "version": "2026.07.02-system-02", - "date": "2026-07-02", - "summary": "新增 quick.waybill.toOrder 接口:根据运单号快速查询订单ID", - "methods": [ - "quick.waybill.toOrder" - ], - "notes": [ - "新增 quick 模块组(快捷查询)", - "查询 wms_order_express 表中 status=1 的有效记录", - "无需登录和鉴权(免登录/免鉴权)" - ], - "type": "added" - }, - { - "version": "2026.07.02-system-01", - "date": "2026-07-02", - "summary": "修正 quick.waybill.toOrder 的 isNeedLogin 为 true,与代码实现保持一致", - "methods": [ - "quick.waybill.toOrder" - ], - "notes": [ - "文档中 isNeedLogin 为 false,但代码 systemMethods/quick/waybill.js 中 _noNeedLogin 为空字符串,未将 toOrder 加入免登录列表,实际需要登录验证,修正文档以与代码一致。" - ], - "type": "fixed" - }, - { - "version": "2026.07.03-system-01", - "date": "2026-07-03", - "summary": "binding 表弃用文档同步:wms_entry_receiving_binding 已弃用,功能迁移到 wms_inbound_direct_log 表;bindings 描述中表引用更新为 InboundDirectLog", - "methods": [ - "storage.entry.getDirectInboundItems" - ], - "notes": [ - "bindings 数组 description 中 wms_entry_receiving_binding 引用更新为 InboundDirectLog,明确旧表已弃用", - "binding_id description 中 wms_entry_receiving_binding.id 更新为 InboundDirectLog.id", - "allocated_quantity description 中补充来源 InboundDirectLog.quantity", - "wms_inbound_direct_log 表新增字段:entry_item_id、receiving_detail_id、status(ENUM: pending/committed/released)、updated_at、deleted_at" - ], - "type": "updated" - }, - { - "version": "2026.07.03-system-02", - "date": "2026-07-03", - "summary": "binding 表弃用文档同步:wms_entry_receiving_binding 已弃用,功能迁移到 wms_inbound_direct_log 表;bindings 描述中表引用更新为 InboundDirectLog", - "methods": [ - "storage.directInbound.getItems" - ], - "notes": [ - "bindings 数组 description 中更新为来自 InboundDirectLog,明确旧表已弃用", - "binding_id description 更新为 InboundDirectLog.id", - "allocated_quantity description 中补充来源 InboundDirectLog.quantity", - "wms_inbound_direct_log 表新增字段:entry_item_id、receiving_detail_id、status(ENUM: pending/committed/released)、updated_at、deleted_at" - ], - "type": "updated" - }, - { - "version": "2026.07.03-system-03", - "date": "2026-07-03", - "summary": "binding 表弃用文档同步:commit 描述中 EntryReceivingBinding 更新为 InboundDirectLog", - "methods": [ - "storage.entry.commit" - ], - "notes": [ - "commit description 中将 pending 状态的 EntryReceivingBinding 更新为 pending 状态的 InboundDirectLog,与代码实现一致" - ], - "type": "updated" - }, - { - "version": "2026-07-03-entry-get-params-fix", - "date": "2026-07-03", - "type": "updated", - "summary": "修正 storage.entry.get 文档:id 改为必填;移除未实现的 entry_order_code 参数;修正错误码与实际返回一致;补充 available_receiving_details 响应字段;修正 remaining_quantity 计算公式及 warehouse_image_url 实际行为", - "methods": [ - "storage.entry.get" - ], - "notes": [ - "params: 移除 entry_order_code(代码中从未使用该参数),id 从 required=false 改为 required=true", - "params: id 描述从'二选一'改为'必填'", - "errors: 400 的 message 从'参数错误:id 与 entry_order_code 至少提供一个'改为'id 参数不能为空'", - "errors: 移除不存在的 404 error,入库单不存在时实际返回 code=0, message='入库单不存在或无权访问'", - "errors: 删除不存在的 500 error", - "response: 新增 entryOrder.items[].available_receiving_details 字段及其描述", - "response: remaining_quantity 描述从 'count - received_quantity - direct_inbound_quantity' 修正为 'max(0, count - received_quantity)'", - "response: warehouse_image_url 描述从 StockWarehouse.image_url 改为'当前固定返回空字符串'", - "response: warehouse_is_images 类型从 number(0/1) 改为 string(Y/N),与 StockWarehouse.is_images 实际存储一致", - "response: warehouse_quantity/warehouse_locked_quantity/warehouse_is_batch_mgmt/warehouse_is_shelf_life_mgmt 补充无匹配时为 null 的说明", - "description: 更新描述以反映实际逻辑流程" - ] - }, - { - "version": "2026.07.03-system-04", - "date": "2026-07-03", - "type": "modified", - "summary": "order.pendingOrder.updateAddress 移除 remark(备注)修改功能,现在仅支持地址字段批量修改;备注修改已独立为 order.pendingOrder.updateRemark", - "methods": [ - "order.pendingOrder.updateAddress" - ], - "notes": [ - "移除入参 remark 参数定义项。", - "移除 remark 更新逻辑及相关描述,updateAddress 现在仅处理地址字段(name/mobile/tel/zip_code/province/city/area/town/detail_address)。", - "description 更新:去掉 remark 相关描述,仅描述地址字段修改规则。", - "response updated_count 描述更新:从「取地址更新行数与备注更新行数的最大值」改为单纯描述地址更新行数。", - "errors 更新:移除 remark 相关错误说明('remark 字段不受此限制' 等),修改 '至少需要提供一个地址字段或备注进行修改' 为 '至少需要提供一个地址字段进行修改'。", - "备注修改功能已独立为 order.pendingOrder.updateRemark 方法。" - ], - "module": "order.pendingOrder" - }, - { - "version": "2026-07-16", - "date": "2026-07-16", - "summary": "新增 workbench.bindCamera 接口,支持工作台绑定/解绑摄像头", - "methods": [ - "workbench.bindCamera" - ], - "notes": [ - "通过 device_ids JSON 字段存储绑定关系", - "传空数组可解绑" - ] - }, - { - "version": "2026.07.17-stock-report-migration-01", - "date": "2026-07-17", - "type": "updated", - "summary": "storage.report 模块迁移至 stock.report:修正语义错误,库存报表属于 stock 域而非 storage 域", - "methods": [ - "stock.report.search", - "stock.report.searchStore", - "stock.report.export", - "stock.report.exportStore", - "stock.report.exportTaskProgress" - ], - "notes": [ - "将 systemMethods/storage/report.js 移动到 systemMethods/stock/report.js", - "内部引用同步更新:类名 StorageReportMethodService→StockReportMethodService,缓存键 storage_report→stock_report,日志前缀 [storage.report]→[stock.report]", - "旧文件直接删除,不保留兼容(storage.report 为语义错误,调用方需同步更新 method 名)", - "更新 systems/storage/entry.js L273 注释引用", - "文档:methods/system.json module storage.report→stock.report,5个 method 名同步更新" - ] - }, - { - "version": "2026.07.17-stock-transaction-export-01", - "date": "2026-07-17", - "type": "added", - "summary": "新增 stock.transaction 商品流水导出(仓库侧+货主侧),异步任务模式,支持与列表查询一致的条件筛选", - "methods": [ - "stock.transaction.export", - "stock.transaction.exportStore", - "stock.transaction.exportTaskProgress" - ], - "notes": [ - "systems/stock_transaction.js 新增 exportList(),复用 queryList 的查询逻辑,不分页导出 Excel(上限 50000 条)", - "systemMethods/stock/transaction.js 新增 export/exportStore/exportTaskProgress,采用异步任务模式(setImmediate + 缓存)", - "仓库侧导出自动限定 warehouse_id=ctx.user.store_id,货主侧需传 store_id", - "导出 Excel 列:序号/创建时间/流水类型/仓库ID/货主ID/商品ID/变动数量/变更前库存/变更后库存/变更前锁定/变更后锁定/批次号/单据类型/单据号/收货单ID/入库单ID/发货单ID/操作人/备注" - ] - }, - { - "version": "2026.07.29-system-01", - "date": "2026-07-29", - "type": "added", - "summary": "新增 waybill.warehouse 运单模块(仓库侧):list(列表)、detail(详情)、export(导出)3 个接口,支持运单号独立查询与管理", - "methods": [ - "waybill.warehouse.list", - "waybill.warehouse.detail", - "waybill.warehouse.export" - ], - "notes": [ - "新增 waybill.warehouse.list:仓库侧运单列表查询,支持分页与多条件筛选(运单号/主单号/订单ID/订单号/物流公司/物流接口/平台/状态/退回/拦截/星河签收/包材/称重/关键词/时间范围),默认按 create_at desc 排序。", - "新增 waybill.warehouse.detail:仓库侧运单详情查询,含关联订单信息、兄弟运单(sibling_waybills)、物流信息、状态信息、称重信息、打包信息(打包状态/打包人/打包时间)、打印记录列表。", - "新增 waybill.warehouse.export:仓库侧运单导出,复用 list 筛选逻辑,异步任务模式,支持自定义导出字段。", - "仓库隔离策略:所有接口自动注入 warehouse_id = ctx.user.store_id(全系统统一约定),不可由前端入参覆盖。", - "快照字段方案:wms_order_express 表新增 delivery_order_code、store_id_snapshot、store_name_snapshot、warehouse_name_snapshot 四个快照列,列表查询无需 JOIN 订单表或货主表,仅单表查询 + SELF JOIN(主单号)。", - "主单号/子单号规则:同一 order_id 下 business_key=1 为主单号,business_key>1 为子单号,沿用系统已有约定。", - "命名空间规划:waybill.warehouse.* 本期实现(仓库侧),后续预留 waybill.store.*(货主侧)。", - "本模块一期仅提供只读查询,不涉及运单创建/修改/删除,不修改任何现有接口。" - ], - "module": "waybill.warehouse" - }, - { - "version": "2026.07.30-system-01", - "date": "2026-07-30", - "type": "changed", - "summary": "更新 waybill.warehouse group API 文档:list 新增 waybillType/storeId 筛选、移除 pack_status 响应字段;detail 精简 package 对象;export 响应改为纯异步任务模式(仅含 task_id/status/progress/message/update_time)", - "methods": [ - "waybill.warehouse.list", - "waybill.warehouse.detail", - "waybill.warehouse.export", - "waybill.warehouse.exportTaskProgress" - ], - "notes": [ - "waybill.warehouse.list:新增 where.waybillType 筛选(\"main\"/\"1\"=主单号,\"child\"/\"2\"=子单号),新增 where.storeId 货主ID等值筛选。where.orderNo 标注暂不可用(待快照字段就绪)。response 移除 pack_status 字段(两表无关联,不再返回),list 字段数从 28 减至 27。", - "waybill.warehouse.detail:package 对象移除 pack_status/pack_quantity/pack_at/packer_name 四个字段,仅保留 package_material_id 和 package_material_name。description 同步去掉\"打包状态\"相关描述。", - "waybill.warehouse.export:响应简化为纯异步任务模式,data 仅含 task_id/status/progress/message/update_time,不含 total_count/current_count/result/error/download_url 等执行期字段(这些信息由 exportTaskProgress 接口返回)。export 的 where 参数同步新增 waybillType 和 storeId。", - "waybill.warehouse.exportTaskProgress:无变更,保持不变。" - ], - "module": "waybill.warehouse" - } + { + "version": "2026.08.01-system-01", + "date": "2026-08-01", + "type": "added", + "summary": "新增 apiApp 仓库 API 应用管理模块,支持当前仓库维度的 API 应用 CRUD、AppKey/Secret 自动生成与重新生成、IP 白名单、回调地址、限流等配置", + "methods": [ + "apiApp.list", + "apiApp.detail", + "apiApp.create", + "apiApp.update", + "apiApp.delete", + "apiApp.regenerateSecret" + ], + "notes": [ + "apiApp.list:分页查询当前仓库 API 应用列表,支持按 app_name(模糊)、is_enabled 筛选,Secret 自动脱敏(前8位+****)。", + "apiApp.detail:按 ID 查询单个应用详情,需同时匹配 warehouse_id(自动注入 ctx.user.store_id),Secret 脱敏。", + "apiApp.create:创建应用时自动生成 AppKey(AK{yyyyMMddHHmmss}{random8hex})和 AppSecret(64位hex)。默认 interface_type_id 取 WH_CHANNEL。仅创建时返回完整 Secret。", + "apiApp.update:更新可编辑字段(app_name、self_ip_whitelist、callback_url、rate_limit、sign_method、is_enabled),不可变字段为 self_app_key 和 interface_type_id。", + "apiApp.delete:软删除(is_enabled=0),不物理删除。", + "apiApp.regenerateSecret:重新生成 64位hex AppSecret,旧 Secret 立即失效。仅此次返回完整 Secret。", + "仓库隔离:所有操作按 ctx.user.store_id → warehouse_id 自动过滤。", + "Secret 安全策略:list/detail/update 返回脱敏值,仅 create/regenerateSecret 返回完整 Secret。" + ], + "module": "apiApp" + }, + { + "version": "2026.07.31-system-02", + "date": "2026-07-31", + "type": "added", + "summary": "新增 storage.inventory.export 库存导出与 storage.inventory.exportTaskProgress 导出进度查询,入参复用 list 的 where/sort/group_by_batch 语义,支持两种导出模式(聚合汇总 / 逐条明细),库位信息一并导出", + "methods": [ + "storage.inventory.export", + "storage.inventory.exportTaskProgress" + ], + "notes": [ + "storage.inventory.export:异步提交导出任务,返回 task_id 与受理信息,后端异步生成 Excel 并上传。入参 where/sort/group_by_batch 与 storage.inventory.list 完全一致,无需额外学习成本。", + "group_by_batch=false(默认):按 stock_id + space_id(库位)聚合导出库存汇总,含商品编码/名称/规格/单位/货主/库位编码/名称/总库存/锁定/可用/批次数/最近入库时间。", + "group_by_batch=true:按 storage_id 逐条导出库存明细,含库存记录ID/商品信息/库位信息/批次号/库存类型/数量/生产日期/过期日期/入库时间/入库单号/供应商批次号。", + "新增 storage.inventory.exportTaskProgress:按 task_id/taskId 查询导出任务进度与状态(submitted/running/success/failed/not_found),status=success 时返回 download_url 供客户端下载。", + "导出文件目录:exports/storage/inventory/{warehouseId}/,缓存 TTL 1800 秒。" + ], + "module": "storage.inventory" + }, + { + "version": "2026.07.31-system-01", + "date": "2026-07-31", + "type": "added", + "summary": "新增按波次批量快捷复核接口 batchQuickRecheckByWave,支持批量波次 IDs 的前置条件检查(储位、快递、同步、拦截),自动完成拣货并标记复核,支持部分失败", + "methods": [ + "order.recheckOrder.batchQuickRecheckByWave" + ], + "notes": [ + "新增 order.recheckOrder.batchQuickRecheckByWave 方法,复用 batchQuickRecheck 的 _completePickForOrder / _markRecheckForOrder / _tryCompleteWaveInTransaction 等内部事务方法", + "入参 wave_ids 支持数组或逗号分隔字符串,兼容 waveIds(驼峰)、wave_id(单值)", + "按波次维度批量查询订单后逐波次、逐订单执行前置校验与复核,每个订单独立事务,部分失败不影响其他订单", + "响应包含 success/failed 列表及计数,failed 项含 order_id、wave_id、delivery_order_code、reason 说明;波次下无订单时仅返回 wave_id + reason" + ], + "module": "order.recheckOrder" + }, + { + "version": "2026.07.29-system-01", + "date": "2026-07-29", + "type": "added", + "summary": "补全 waybill.warehouse group API 文档参数定义:完善 list/detail/export 的 params 与 response,新增 exportTaskProgress 异步进度查询接口", + "methods": [ + "waybill.warehouse.list", + "waybill.warehouse.detail", + "waybill.warehouse.export", + "waybill.warehouse.exportTaskProgress" + ], + "notes": [ + "waybill.warehouse.list:params 含 pagination/where/sort 完整字段定义,where 支持 15 个筛选维度(运单号、主单号、订单ID、订单号、物流编码、物流接口ID、平台编码、状态、退回/拦截/星河签收、包材ID、已称重、关键词、创建时间范围),sort 白名单 create_at/weighing_weight/id。response 含 list(28 个字段)+ pagination。", + "waybill.warehouse.detail:修正 id 参数为可选(required: false),与 waybillCode 二选一,waybillCode 优先。response 含 id/waybill_code/main_waybill_code/waybill_type/business_key/sibling_waybills/order/logistics/status_info/weight/package/print_records/print_count 等完整详情。", + "waybill.warehouse.export:response 补充 progress/message/update_time 字段,完整覆盖异步任务返回信息。", + "新增 waybill.warehouse.exportTaskProgress:按 task_id/taskId 查询导出进度,response 含 task_id/status/progress/current_count/total_count/message/result/error/download_url/update_time。", + "所有接口 isNeedAuth: false, isNeedLogin: true,仓库隔离通过 ctx.user.store_id 自动注入。" + ], + "module": "waybill.warehouse" + }, + { + "version": "2026.07.28-system-01", + "date": "2026-07-28", + "type": "added", + "summary": "新增 order.pendingOrder.batchMarkPrinted:批量设置订单为已打印状态,将 print_status 更新为 'fin'", + "methods": [ + "order.pendingOrder.batchMarkPrinted" + ], + "notes": [ + "同步批量更新接口,传入订单ID数组,直接将符合条件的订单 print_status 设为 'fin'。", + "双表查询:先查 current 表(wms_order_delivery_{warehouseId}),未命中的 ID 再兜底查 dispatch 表(wms_order_delivery_{warehouseId}_dispatch)。", + "dispatch 表查询失败仅记录 warn 日志,不影响 current 表已更新的结果。", + "仅允许 step 在 [1,2,3] 且 status 不为 'cancel' 的订单操作,已打印(print_status='fin')的订单会被静默跳过。", + "仓库上下文强制从 ctx.user.store_id 获取,禁止传入外部仓库ID。", + "入参支持 order_ids / orderIds / ids 三种别名,优先级 order_ids > orderIds > ids。", + "返回 updated_count 表示实际更新条数(current + dispatch 合计),ids 原样回传请求的订单ID列表。", + "写入操作日志 operation_code: ORDER_BATCH_MARK_PRINTED。" + ], + "module": "order.pendingOrder" + }, + { + "version": "2026.07.27-system-03", + "date": "2026-07-27", + "type": "changed", + "summary": "storage.receiving 导出接口拆分:export 改为按仓库维度,新增 storeExport 按货主维度导出", + "methods": [ + "storage.receiving.export", + "storage.receiving.exportTaskProgress", + "storage.receiving.storeExport", + "storage.receiving.storeExportTaskProgress" + ], + "notes": [ + "export 改为仓库维度:过滤条件从 store_id(平台激活货主)改为 warehouse_id(ctx.user.store_id),与 getReceivingList 保持一致。", + "exportTaskProgress 同步更新为仓库维度进度查询,任务 ID 前缀 receiving_export_。", + "新增 storeExport:货主维度导出,通过平台激活上下文获取 store_id,过滤逻辑与 getStoreReceivingList 一致。", + "新增 storeExportTaskProgress:货主维度进度查询,复用 exportTaskProgress 的缓存逻辑,任务 ID 前缀 receiving_store_export_。", + "导出格式:双 Sheet Excel(Sheet1=收货单列表 21 列,Sheet2=收货单明细 17 列),通过 ExcelJS stream + uploadService 上传 COS。", + "仓库导出上传路径 exports/receiving/{warehouseId}/,货主导出上传路径 exports/receiving/store/{storeId}/。", + "修复 exportReceivingList 中 where 条件二次解析问题:增加 ctx.whereParsed 复用(与 getStoreReceivingList 一致),避免 prepareWhereContext 已解析后再重复 parseWhereConditions 导致边界条件丢失。", + "命名对齐 entry 侧:storeExport / storeExportTaskProgress 方法名、任务 ID 前缀、上传路径均与 storage.entry.storeExport 模式一致。" + ], + "module": "storage.receiving" + }, + { + "version": "2026.07.27-system-02", + "date": "2026-07-27", + "type": "added", + "summary": "新增 order.pendingOrder.allocateSubOrderNumber:待处理订单分配子单号(异步任务),business_key 从 2 开始递增,跳过已分配运单号;新增 allocateSubOrderNumberProgress 按 task_id/business_key 查询进度", + "methods": [ + "order.pendingOrder.allocateSubOrderNumber", + "order.pendingOrder.allocateSubOrderNumberProgress" + ], + "notes": [ + "新增 allocateSubOrderNumber:入参 order_id + sub_order_count,按 business_key 2..(2+count-1) 全量传入 createWaybillCodePipeline。", + "并发安全:全量传入 pipeline,由其内部事务 + UNIQUE(order_id,business_key,status,warehouse_id) 索引保证并发去重。", + "pipeline 内部 createWaybillCode 事务:status=1 已分配→跳过;status=0 占位中→复用;无记录→INSERT status=0 占位。", + "异步任务模式:请求立即返回 task_id(sub_ 前缀),后台 setImmediate 执行,进度通过 Redis 缓存追踪。", + "新增 allocateSubOrderNumberProgress:支持 task_id 查整体进度,business_key 可选参数过滤单个业务ID的详情。", + "进度状态 submitted→running→success/partial/failed,progress 对应 5/50/80/100。", + "result.details 数组记录每个 business_key 的 status(skipped/allocated/failed/pending)与 waybill_code。", + "buildSubOrderDetails 回查最终状态:status=1+waybill→allocated,status=0→failed,无记录→failed。" + ], + "module": "order.pendingOrder" + }, + { + "version": "2026.07.27-system-01", + "date": "2026-07-27", + "type": "added", + "summary": "新增 order.packing 打包任务模块:list/get 查询 + setEndTime 设置结束时间,含视频 CDN URL 拼接与状态回写", + "methods": [ + "order.packing.list", + "order.packing.get", + "order.packing.setEndTime", + "order.packing.forceRecord" + ], + "notes": [ + "新增 order.packing.list:按仓库维度查询打包任务列表,支持分页/筛选/排序,关联工作台、视频和运单信息。", + "新增 order.packing.get:按 id + warehouse_id 查询单条打包任务详情。", + "新增 order.packing.setEndTime:设置打包任务结束时间,入参 id + end_time;若任务状态不是已完成(2)则同步更新为已完成。", + "新增 order.packing.forceRecord:强制重新录制打包任务视频,入参 id;校验录制电脑在线后重置视频状态并推送打印服务。", + "前端默认值逻辑:若任务已有 end_time 则打开时默认为当前时间,否则默认为 start_time + 5分钟。", + "视频 URL 自动拼接 CDN 域名前缀:http://w{warehouseId}-c{recordingComputerId}.o.gztbyc.com{videoPath};录制电脑从 wms_print_computer 按 is_recording=true 获取。", + "视频响应新增 status 字段(created/recording/completed/failed),与数据库 ENUM 保持一致。", + "pack_task_video Model 的 status 字段从 TINYINT 改为 STRING(20) 以匹配 DB ENUM 迁移。", + "forceRecord 通过打印服务 /record/force 推送录制任务,传入 pack_task_id、warehouse_id、computer_id、camera_ids。" + ], + "module": "order.packing" + }, + { + "version": "2026.07.10-system-01", + "date": "2026-07-10", + "type": "added", + "summary": "新增 storage.report.searchStore 货主侧库存报表,以 store_id 为主维度查询库存流水", + "methods": [ + "storage.report.searchStore", + "storage.report.exportStore" + ], + "notes": [ + "新增 searchStore 方法:与 search 共享核心逻辑,通过 searchMode='store' 切换主维度从 warehouse_id → store_id。", + "新增 exportStore 方法:与 export 共享核心逻辑,支持货主侧导出 Excel(含汇总 + 变更记录两个 sheet)。", + "systems 层 search/export 方法新增 searchMode 参数(默认 'warehouse'),不影响现有 warehouse 侧行为。", + "货主侧使用 ctx.user.store_id 作为主维度 store_id,辅助维度支持 warehouse_ids 过滤特定仓库。", + "systemMethods 层 searchStore 从 where.warehouse_ids 取值传给 search 的 storeIds(承载 warehouse 过滤)。", + "输出新增 warehouse_id / warehouse_name 字段,货主侧可区分不同仓库的库存。search 方法也同步输出这两个字段(向后兼容)。", + "修复 getStockDetails 的 warehouseId 判断:从 != null 改为 !== undefined,使显式传 null 可跳过 warehouse 过滤。", + "修复 loadReportReferenceMaps 未传递 warehouseId 给 getStockDetails 的问题。" + ], + "module": "storage.report" + }, + { + "version": "2026.07.09-system-01", + "date": "2026-07-09", + "type": "updated", + "summary": "签约 sign 方法改造:统一当前主体→store_id,解除角色校验,仓库可签仓库", + "methods": [ + "storeWarehouse.store.sign", + "storeWarehouse.warehouse.sign" + ], + "notes": [ + "resolvePairIds:统一当前主体始终在 store_id(货主方/消费方),对方在 warehouse_id(仓库方/提供方)。不再根据 isWarehouse 分支。", + "getCounterparty:移除 expectedRole 角色校验(仓库不再只能签货主,可签仓库)。", + "findScopedRelation:改为 OR 查询 store_id/warehouse_id 两边,兼容新旧签约数据。", + "sign preview:counterparty.role 改为根据对方 project 真实返回(warehouse/store),不再硬编码反推。", + "签仓库:仓库发起签约时对方 ID 传 counterparty_id,系统自动将当前仓库放 store_id。" + ], + "module": "storeWarehouse" + }, + { + "version": "2026.07.08-system-01", + "date": "2026-07-08", + "type": "updated", + "summary": "storeWarehouse.store.list 与 storeWarehouse.warehouse.list 拆分实现,不再共用;仓库侧支持查询外部合作仓库", + "methods": [ + "storeWarehouse.store.list", + "storeWarehouse.warehouse.list" + ], + "notes": [ + "拆分:store.list 调用 listForStore,warehouse.list 调用 listForWarehouse,不再共用同一个 list 方法。", + "新规则:两个方法均按 store_id = 当前主体ID 过滤(主体在 store_id 为货主方/消费方,对方在 warehouse_id 为仓库方/提供方)。", + "warehouse.list 新增支持查询外部合作仓库:当对方主体的 project='warehouse' 时为仓库-仓库合作,counterparty_role='warehouse'。", + "响应新增 counterparty_role 字段(store/warehouse),标识对方主体的真实角色。", + "warehouse.list 响应 use_status 改为 store_use_status(仓库在 store_id 方时,己方启用状态应为 store_use_status)。", + "旧 list 方法保留标记为 @deprecated,保持向后兼容。", + "新增 buildListWhereByStoreId 统一按 store_id 维度构建查询条件。" + ], + "module": "storeWarehouse" + }, + { + "version": "2026.07.06-system-01", + "date": "2026-07-06", + "type": "updated", + "summary": "order.wave.batchList:响应新增 pick_assignment_status(拣货分配状态),按订单 pick_status 聚合判定", + "methods": [ + "order.wave.batchList" + ], + "notes": [ + "响应 list 每项新增字段 pick_assignment_status (string):拣货分配状态,按波次下订单的 pick_status 聚合判定。", + "取值语义与 resolveAssignmentStatus 一致,自定义标签:未拣货(全 none)、部分拣货(混合且无 error)、已拣货(全 fin)、拣货异常(含 error)。", + "SQL 子查询新增 pick_none_count / pick_fin_count / pick_error_count 聚合列。" + ], + "module": "order.wave" + }, + { + "version": "2026.07.05-system-01", + "date": "2026-07-05", + "type": "added", + "summary": "新增 pick.wavePickComplete:传入 wave_id 一键完成整个波次拣货,内部复用 query 去重与任务创建逻辑后自动调用 wavePickTaskComplete(mode=1)", + "methods": [ + "pick.wavePickComplete" + ], + "notes": [ + "新增方法:pick.wavePickComplete,入参 wave_id(number,必填)。", + "内部流程:按 wave_id 查波次 → 活动任务去重(同用户复用 / 他人409冲突)→ 完成任务去重 → 无任务则创建(source=2 后台抓取)→ 调用 pick.wavePickTaskComplete mode=1 全部确认。", + "创建任务 remark 格式:pick.wavePickComplete wave_id={waveId},用于与 pick.query 区分。", + "响应:task_id、status(completed / already_completed)、tip、confirmed_order_ids、is_completed、progress。", + "错误码:400(参数/波次无订单)、401(缺少操作人)、404(波次不存在)、409(他人活动任务冲突)、500(创建/完成失败)。" + ], + "module": "pick" + }, + { + "version": "2026.07.03-system-02", + "date": "2026-07-03", + "type": "added", + "summary": "新增 order.pendingOrder.updateRemark:批量修改待处理订单备注(remark),不受 post_status 限制", + "methods": [ + "order.pendingOrder.updateRemark" + ], + "notes": [ + "新增方法:order.pendingOrder.updateRemark,用于批量修改待处理订单的备注(remark)字段。", + "入参:ids(number[],必填,正整数数组,不能为空)、remark(string,必填,最大500字符)。", + "特性:不受 post_status 限制,可对所有状态的订单生效;纯批量不支持单ID。", + "更新成功后写入操作日志。", + "响应:updated_count(number,实际更新行数)、ids(number[],原样返回请求的ID数组)。", + "错误码:400(ids 不能为空 / ids 仅支持正整数数组 / remark 不能为空)。" + ], + "module": "order.pendingOrder" + }, + { + "version": "2026.07.03-system-01", + "date": "2026-07-03", + "type": "updated", + "summary": "将 quick.waybill.toOrder 迁移为 index.toOrder 并移入基础模块,新增 waves 返回字段", + "methods": [ + "quick.waybill.toOrder", + "index.toOrder" + ], + "notes": [ + "移除快捷操作(quick)模块分组,原 quick.waybill.toOrder 方法从 methods/system.json 删除。", + "在基础模块(index)新增 index.toOrder 方法:入参仍为 waybill_code,响应从单一 order_id 扩展为 order_id + waves 结构。", + "waves 为数组,每项含 wave_id(波次ID)、wave_no(波次号)、order_ids(波次下所有订单ID列表),无波次时为空数组。", + "查询路径:运单号 → wms_order_express(status=1)→ order_id + warehouse_id → 遍历 current/history/dispatch 表获取波次信息 → 再遍历多表获取同波次所有订单ID。" + ] + }, + { + "date": "2026-06-24", + "type": "addition", + "summary": "新增批量绑定入库单明细与收货单明细接口,支持明细级数量分配与部分成功", + "version": "2026-06-24-add-bind-receiving-details", + "methods": [ + "storage.entry.bindReceivingDetails" + ], + "notes": [] + }, + { + "date": "2026-06-24", + "type": "deprecation", + "summary": "废弃手动匹配入库单收货单接口,由 storage.entry.bindReceivingDetails 替代", + "version": "2026-06-24-deprecate-manual-match-entry-order", + "methods": [ + "storage.receiving.manualMatchEntryOrder" + ], + "notes": [] + }, + { + "version": "2026.06.16-system-03", + "date": "2026-06-16", + "summary": "order.wave.waveStrategyFallbackOrderList 响应新增 items_weight(总重量g)和 weight_type(重量类型)字段", + "methods": [ + "order.wave.waveStrategyFallbackOrderList" + ], + "notes": [ + "响应 list 每项新增字段 items_weight (number|null):订单总重量(g),来自 wms_order.items_weight,为 null 时返回 null。", + "响应 list 每项新增字段 weight_type (string):重量类型中文标签,来自 wms_order.weight_type 经 formatWeightTypeLabel 转换;取值:常规/轻货/重货/冷链(对应 DB 值 0/1/2/3)。" + ], + "type": "updated", + "module": "order.wave" + }, + { + "version": "2026.06.16-system-04", + "date": "2026-06-16", + "summary": "order.wave.singleOrderFetchList 响应新增 items_weight(总重量g)字段", + "methods": [ + "order.wave.singleOrderFetchList" + ], + "notes": [ + "响应 list 每项新增字段 items_weight (number|null):订单总重量(g),取组内首单 items_weight;组内订单 items_hash 相同重量一致。", + "为 null 时返回 null。" + ], + "type": "updated", + "module": "order.wave" + }, + { + "version": "2026.05.20-system-03", + "date": "2026-05-20", + "summary": "新增 storeWarehouse.store.queryPrintQuantityLogs:按 store_id 分页查询面单余额变更日志", + "methods": [ + "storeWarehouse.store.queryPrintQuantityLogs" + ], + "notes": [ + "新增方法:storeWarehouse.store.queryPrintQuantityLogs,用于按货主(store_id)分页查询面单余额变更日志。", + "入参:store_id(必填)、page(可选)、page_size / pageSize(可选,兼容别名)。", + "仅同步 methods/system.json 与本变更记录,不修改业务代码或测试。", + "返回:使用默认分页格式,响应在 `data` 下包含 `list`(变更日志数组)和 `pagination` 对象,`pagination` 字段:`page`、`pageSize`、`total`、`totalPages`、`hasPrevious`、`hasNext`。" + ], + "type": "added", + "module": "storeWarehouse" + }, + { + "version": "2026.05.13-system-01", + "date": "2026-05-13", + "summary": "完善 print.send 的 API 文档与返回说明", + "methods": [ + "print.send" + ], + "notes": [ + "补充请求参数说明:computerId、printer、template、data、type 标为必填,count、timestamp 保持可选。", + "补充 template 的子字段说明:page_width、page_height、template_content。", + "补充响应结构:flag、code、message、printId;其中成功时 code=200。", + "补充错误码说明:1001 对应不支持的打印类型,504 对应打印任务发送失败(包含打印机不存在、脱机、通讯失败等场景)。" + ], + "type": "updated" + }, + { + "version": "2026.05.08-system-06", + "date": "2026-05-08", + "summary": "新增取消拣货任务接口:order.wave.wavePickTaskCancel", + "methods": [ + "order.wave.wavePickTaskCancel" + ], + "notes": [ + "接口功能:取消拣货任务,同时释放关联波次(物理删除波次记录,订单回池)、解绑拣货车、写操作日志。", + "限制:仅允许在任务状态为 0(待开始)、1(拣货中)、2(待复核)时取消;状态为 3(已完成)或 9(已取消)时禁止取消,返回 400。", + "事务内操作:将任务状态更新为 9(已取消)、删除关联波次、清空订单 wave_id(回池)、解绑拣货车、写入 action_log 与 order_pick_trace;若有任一步骤失败则回滚并返回 500。" + ], + "type": "added" + }, + { + "version": "2026.07.01-system-01", + "date": "2026-07-01", + "summary": "storage.directInbound.addItem 参数名修正:entry_order_code → entry_order_id,类型 string → number", + "methods": [ + "storage.directInbound.addItem" + ], + "notes": [ + "文档 params 中 entry_order_code(string)改为 entry_order_id(number),与代码 app/service/systems/inbound_direct_log.js 第 544 行实际校验保持一致", + "同步修正 app/service/systemMethods/storage/direct_inbound.js JSDoc:@param {string} data.entry_order_code → @param {number} data.entry_order_id" + ], + "type": "fixed", + "module": "storage.directInbound" + }, + { + "version": "2026.07.01-system-02", + "date": "2026-07-01", + "summary": "新增 storage.entry.queryEntryLogs 接口文档定义", + "methods": [ + "storage.entry.queryEntryLogs" + ], + "notes": [ + "代码 method 层(systemMethods/storage/entry.js L284)和 systems 层(systems/operation_log.js L318)均已实现,补充文档定义", + "参数:id(number, required)、page(number, optional, 默认1)、pageSize(number, optional, 默认20)" + ], + "type": "added", + "module": "storage.entry" + }, + { + "version": "2026.06.18-system-01", + "date": "2026-06-18", + "summary": "order.pendingOrder.downloadCreateTemplate:模板列顺序调整,店铺名称(shop_nick)从末尾移至第2列B列,紧接*订单号之后", + "methods": [ + "order.pendingOrder.downloadCreateTemplate" + ], + "notes": [ + "调整 Excel 导入模板列顺序:店铺名称(shop_nick)从原第25列(Y列/末尾)移动至第2列(B列),紧跟在*订单号(delivery_order_code)之后。", + "同步更新 description 中的列顺序描述,明确 25 列(A-Y)的完整排列。", + "响应结构中移除冗余的 shop_nick 字段(模板列不属于 API 响应字段)。" + ], + "type": "updated", + "module": "order.pendingOrder" + }, + { + "version": "2026.05.17-system-09", + "date": "2026-05-17", + "summary": "为 storage.receiving.deleteDetail 文档补充约束:收货单已完成/已取消时禁止删除明细", + "methods": [ + "storage.receiving.deleteDetail" + ], + "notes": [ + "在 storage.receiving.deleteDetail 的 description 中补充:若关联收货单状态为 completed(已完成)或 cancelled(已取消),接口会返回删除失败(400),不允许删除明细。", + "在 errors 中补充或合并 400 描述以明确禁止删除已完成/已取消的收货单明细。" + ], + "type": "updated", + "module": "storage" + }, + { + "version": "2026.05.17-system-08", + "date": "2026-05-17", + "summary": "完善 storage.receiving.deleteDetail 文档:补充入参/返回/错误说明,明确用户上下文来源及删除约束", + "methods": [ + "storage.receiving.deleteDetail" + ], + "notes": [ + "补充 storage.receiving.deleteDetail 的参数说明:detail_id(来自请求体,必填);说明 creator_id 与 warehouse_id 来源于当前登录用户(ctx.user.employees_id / ctx.user.store_id)。", + "补充返回结构:成功时返回 code/message/data,data 包含 details(删除后剩余明细)和 selectId(建议选中ID);product_snapshot 若存在将被解析为对象或 null。", + "补充常见错误码:404(明细不存在或无权访问),400(收货单状态/已入库/删除失败),500(服务器异常)。", + "仅文档更新,不修改任何业务实现。" + ], + "type": "updated", + "module": "storage" + }, + { + "version": "2026.05.17-system-05", + "date": "2026-05-17", + "summary": "移除 storage.receiving.addItem(方法已下线/实现不存在)", + "methods": [ + "storage.receiving.addItem" + ], + "notes": [ + "仅同步文档:从 methods/system.json 中移除 storage.receiving.addItem,未修改任何业务代码或实现。", + "该方法已下线或实现不存在;请以当前 methods/system.json 的 SSOT 为准。" + ], + "type": "removed" + }, + { + "version": "2026.05.17-system-04", + "date": "2026-05-17", + "summary": "新增 stock.warehouse.import:仓库商品批量 JSON 导入(数组导入),SKU 为空创建/非空更新,支持 goods_code/货物编码 导入,更新写操作日志", + "methods": [ + "stock.warehouse.import" + ], + "notes": [ + "支持直接传入商品数组 JSON(主方式为数组,兼容 rows/items/list/data 包装)。", + "每项仅需传商品相关字段;SKU 为空时创建新商品,SKU 非空时为更新操作。", + "更新操作会写入操作日志以便审计。", + "支持导入 goods_code(货物编码)字段别名。", + "仅同步文档,不修改业务代码或实现。" + ], + "type": "added" + }, + { + "version": "2026.05.17-system-03", + "date": "2026-05-17", + "summary": "完善 stock.warehouse.handleBatchChange 文档:补充入参/出参/错误示例", + "methods": [ + "stock.warehouse.handleBatchChange" + ], + "notes": [ + "补充方法入参说明:ids/method/value 的字段类型、是否必填、来源与示例;完善响应结构示例与常见错误码说明。", + "仅文档更新,不改业务实现或语义。" + ], + "type": "updated" + }, + { + "version": "2026.05.17-system-02", + "date": "2026-05-17", + "summary": "stock.warehouse.export 由同步改为异步任务并新增进度查询 exportTaskProgress", + "methods": [ + "stock.warehouse.export", + "stock.warehouse.exportTaskProgress" + ], + "notes": [ + "stock.warehouse.export 改为异步提交导出任务:接口返回 task_id 与受理信息,后端异步生成导出文件。", + "新增 stock.warehouse.exportTaskProgress:按 task_id 查询任务状态与进度;当 status=success 时返回 download_url 供客户端下载;未找到时 status=not_found。", + "调用方式:先调用 stock.warehouse.export 获取 task_id,然后轮询 stock.warehouse.exportTaskProgress 直到 status=success 并获取 download_url。" + ], + "type": "updated" + }, + { + "version": "2026.05.17-system-01", + "date": "2026-05-17", + "summary": "新增 stock.warehouse.export:仓库商品导出(支持 where/sort),返回文件下载信息", + "methods": [ + "stock.warehouse.export" + ], + "notes": [ + "新增方法:stock.warehouse.export。复用 stock.warehouse.list 的 where/sort 过滤语义(支持 operator/value/type 标准 where 结构与历史简写)。", + "响应返回导出结果(示例字段:file_key、url),表示生成的 Excel 已上传并可下载/查询。" + ], + "type": "added" + }, + { + "version": "2026.05.16-system-01", + "date": "2026-05-16", + "summary": "同步 setting.expressInterface.create 文档入参:移除未使用的 express_platform_id,标注必填字段", + "methods": [ + "setting.expressInterface.create" + ], + "notes": [ + "移除文档中 express_platform_id(服务端实现未使用);确认必填字段 name/express_code/platform_code;仓库由系统自动填充,禁止传入 warehouse_id/warehouseId。" + ], + "type": "updated" + }, + { + "version": "2026.05.12-system-01", + "date": "2026-05-12", + "summary": "调整订单打印中间态返回结构为 waveGroups(波次 -> 平台 -> 订单)", + "methods": [ + "order.print.getWavePlatformPrintData" + ], + "notes": [ + "主要变更:将方法的主返回结构改为 waveGroups,按波次分组,波次内按平台分组,平台内为订单列表(波次 -> 平台 -> 订单)。", + "兼容性:保留旧字段 platform_groups 与 order_list 作为向后兼容字段,但文档主结构与推荐使用为 waveGroups。", + "返回结构说明:summary(total_waves/total_orders/total_platforms)、wave_ids(通过过滤的波次ID数组)、waveGroups(数组,项含 wave_id、wave_no、order_count、platforms[...],platforms项含 platform、platform_name、order_count、orders[...])、ext(missing_wave_ids、filtered_wave_ids)。", + "errors:保留 400 / 500 不变。" + ], + "type": "modified" + }, + { + "version": "2026.05.11-system-05", + "date": "2026-05-11", + "summary": "order.wave.batchList:支持 express/print 分配状态筛选,入参改为英文枚举(express/print)", + "methods": [ + "order.wave.batchList" + ], + "notes": [ + "修复 where.express_assignment_status 可按快递分配状态筛选。", + "新增 where.print_assignment_status 筛选(按打印分配聚合判断)。", + "express_assignment_status / print_assignment_status 要求使用英文枚举值:express=unassigned/partially_assigned/assigned,print=unprinted/partially_printed/printed;storage_assignment_status 继续兼容中文枚举(未分配/部分分配/已分配)。", + "若传入非法枚举值,接口返回 400(参数校验失败),message 中会说明允许取值。" + ], + "type": "updated" + }, + { + "version": "2026.05.11-system-04", + "date": "2026-05-11", + "summary": "调整 order.wave.waveStrategyFetchAdmin:由创建任务改为直接创建波次(不创建拣货任务)", + "methods": [ + "order.wave.waveStrategyFetchAdmin" + ], + "notes": [ + "接口行为变更:按策略直接抓取命中订单并创建波次,不再创建拣货任务(不返回 task_id/task_no 等任务字段)。", + "响应调整为建波结果:fetch_state(1=成功/2=失败)、wave_ids、wave_nos、created_wave_count、created_order_count、order_ids、(可选)wave_prefix、wave_prefix_source、tip/message。", + "错误调整:策略校验失败返回 400(并可能返回 validation_errors),缺少仓库上下文返回 400,建波失败返回 500 并在 message 中说明。" + ], + "type": "updated" + }, + { + "version": "2026.05.11-system-03", + "date": "2026-05-11", + "summary": "更新 pick.query:由查询拣货明细调整为按 keyword 获取/创建拣货任务", + "methods": [ + "pick.query" + ], + "notes": [ + "入参由 waybill_code/full_display 调整为 keyword(支持运单号或波次号)。", + "接口语义调整为任务化返回:命中活动任务则返回 existing 任务ID;无活动任务则创建并返回 created 任务ID。", + "新增任务归属冲突错误:当活动任务创建人非当前用户时返回冲突提示,并附带创建人及任务ID信息。" + ], + "type": "updated" + }, + { + "version": "2026.05.11-system-02", + "date": "2026-05-11", + "summary": "新增 pick.wavePickTaskCurrent:PDA 无参查询当前进行中拣货任务", + "methods": [ + "pick.wavePickTaskCurrent" + ], + "notes": [ + "新增 PDA 专用无参接口 pick.wavePickTaskCurrent。", + "按当前登录用户上下文(pick_user_id + warehouse_id)查询状态在 0/1/2 的最新任务。", + "命中返回 task_id,未命中返回 task_id=null。" + ], + "type": "added" + }, + { + "version": "2026.05.10-system-04", + "date": "2026-05-10", + "summary": "pick.wavePickTaskDetail 新增按任务类型区分的 picking_view 形态输出", + "methods": [ + "pick.wavePickTaskDetail" + ], + "notes": [ + "新增响应字段:picking_view(object),按 task.pick_mode 区分 5 种形态输出。", + "picking_view 字段说明:mode_code, mode_name, require_box_allocations, group_by, sort_by, items[](每项含 space_id、space_name、location_space、item_code、item_name、stock_id、total_qty、box_allocations[])。", + "当 pick_mode=1/3/4 时 require_box_allocations=true;当 pick_mode=2/5 时 require_box_allocations=false。" + ], + "type": "updated" + }, + { + "version": "2026.05.10-system-02", + "date": "2026-05-10", + "summary": "order.wave.waveStrategyFetchPda/Admin 返回新增 fetch_state 三态与简短 tip", + "methods": [ + "order.wave.waveStrategyFetchPda", + "order.wave.waveStrategyFetchAdmin" + ], + "notes": [ + "新增返回字段:fetch_state(number)、tip(string)、can_enter_pick_flow(boolean)", + "fetch_state 含义:1=创建成功(返回 task_id/task_no),2=普通失败(task_id=null),3=存在未完成任务(返回 existing task_id/task_no,前端可直接进入拣货流程)", + "当 fetch_state=3 时,字段 can_enter_pick_flow=true,表示前端可直接进入拣货流程;tip 为简短提示文本" + ], + "type": "updated" + }, + { + "version": "2026.05.10-system-03", + "date": "2026-05-10", + "summary": "裁剪 pick.wavePickTaskDetail 返回:移除 waves/orders,精简 task 并补充 boxes 拣货统计字段", + "methods": [ + "pick.wavePickTaskDetail" + ], + "notes": [ + "移除响应中的 waves 与 orders 子表,接口仅返回精简的 task、boxes、picking_details 与 picking_summary。", + "task 子字段裁剪为:task_id, task_no, status, pick_mode, start_at, finish_at, batch_no。", + "boxes 补充并明确返回:ref_label(箱参考标签)、required_qty(箱内需拣总数)、picked_qty(已拣数量)。", + "本次变更为文档层面的返回裁剪,前端应以新字段集合为准,旧字段可能不再返回。" + ], + "type": "updated" + }, + { + "version": "2026.05.10-system-01", + "date": "2026-05-10", + "summary": "order.wave.waveStrategyList 新增 strategy_type 最小过滤(散单/团购)", + "methods": [ + "order.wave.waveStrategyList" + ], + "notes": [ + "新增 strategy_type 过滤,仅 1/2", + "支持顶层 strategy_type 和 where.strategy_type,顶层优先", + "当前不引入其他 where 字段" + ], + "type": "updated" + }, + { + "version": "2026.05.09-system-02", + "date": "2026-05-09", + "summary": "新增 pick.wavePickTaskDetail:按任务ID解析拣货任务详情", + "methods": [ + "pick.wavePickTaskDetail" + ], + "notes": [ + "新增 pick.wavePickTaskDetail:传入 task_id 获取拣货任务完整信息,包含主表字段(task/pick_mode/status/wave_count/order_count/box_count 等)及三张子表数据(waves/orders/boxes)。", + "安全限制:接口会校验当前登录用户(operator_id/employees_id)与任务的 pick_user_id 是否一致;不一致时直接返回 403,不返回任何拣货信息。", + "鉴权配置:noNeedRight=true,noNeedAuth=true,isNeedLogin=true。" + ], + "type": "added" + }, + { + "version": "2026.05.08-system-05", + "date": "2026-05-08", + "summary": "order.wave.batchList:新增 source 字段并支持 where.source 过滤,返回 list item 中新增 source 字段", + "methods": [ + "order.wave.batchList" + ], + "notes": [ + "新增 where.source(可选,number)用于按来源过滤:0=普通波次(正常后台操作),1=管理后台策略任务,2=PDA策略任务;不传则不过滤。", + "响应 list 每条记录新增字段 source(number),用于区分波次来源。", + "仅更新文档,业务代码不在此变更范围。" + ], + "type": "updated" + }, + { + "version": "2026.05.08-system-04", + "date": "2026-05-08", + "summary": "完善 order.wave.wavePickTaskList 文档:补充入参、分页与返回字段兼容说明", + "methods": [ + "order.wave.wavePickTaskList", + "order.wave.wavePickTaskCancel" + ], + "notes": [ + "入参补充:warehouse_id(必填)、status(支持单值或数组,建议传数组)、source、keyword、page_no、page_size;保留 pagination 对象以兼容旧客户端。", + "兼容说明:接口同时支持历史 where 结构与顶层参数;当存在同名顶层参数时以顶层参数优先;pagination 支持 page/current 与 pageSize/size 别名。", + "返回格式:响应包含 total 与 list;list 每项包含字段:task_id、task_no、status、source、pick_mode、wave_count、order_count、box_count、operator_id、operator_name、start_at、finish_at、created_at。为兼容旧客户端,响应同时保留旧字段:pick_user_id、pick_user_name、start_time、finish_time、create_time。", + "入参 strategy_id 当前主表未存,接口会忽略该过滤,不建议使用。", + "默认排序:create_time desc.", + "文档变更:移除 order.wave.wavePickTaskCancel 的入参 operator_id 与 warehouse_id;入参改为仅支持 task_ids(数组,必填),不再兼容单个 task_id;操作人与仓库由请求上下文(例如当前登录用户上下文)自动获取;若上下文缺失接口将返回错误。响应补充批量结果字段:cancelled_count、task_ids、task_nos(若后端返回)。仅更新文档,未修改业务实现。" + ], + "type": "updated" + }, + { + "version": "2026.05.08-system-03", + "date": "2026-05-08", + "summary": "升级按策略抓取接口为创建任务主流程:order.wave.waveStrategyFetchPda / order.wave.waveStrategyFetchAdmin", + "methods": [ + "order.wave.waveStrategyFetchPda", + "order.wave.waveStrategyFetchAdmin" + ], + "notes": [ + "将 PDA/Admin 场景的按策略抓取接口由受理壳方法升级为 '创建任务主流程':接口会执行参数校验并在同步响应中创建任务记录(state=created),返回 task_id、task_no、plan 与 plan_summary 供前端展示与后续查询。", + "入参新增/扩展与创建流程相关字段:至少包含 cart_id(关联拣货车/作业车ID)、source(操作来源语义)并保留并透传 strategy_id 与 strategy_params(策略参数),以支持在创建阶段对策略进行局部覆盖或透传。", + "成功返回示例字段:state=created、task_id、task_no、plan(对象)和 plan_summary(字符串);失败场景会返回 validation_errors(数组,每项含 field/message)或 message 描述创建失败原因。", + "边界说明:当前为最小主流程(创建与计划预览),后续扫描/任务执行阶段(如实际抓取订单、写入 wave 等)将在后续版本中追加与完善。" + ], + "type": "updated" + }, + { + "version": "2026.05.08-system-02", + "date": "2026-05-08", + "summary": "调整按策略抓取壳方法:order.wave.waveStrategyFetch 更名为 order.wave.waveStrategyFetchPda,并新增 order.wave.waveStrategyFetchAdmin", + "methods": [ + "order.wave.waveStrategyFetch", + "order.wave.waveStrategyFetchPda", + "order.wave.waveStrategyFetchAdmin" + ], + "notes": [ + "waveStrategyFetchPda 仅用于 PDA 场景", + "waveStrategyFetchAdmin 仅用于后台管理场景", + "两者当前均为壳子受理方法,不执行真实抓取" + ], + "type": "updated" + }, + { + "version": "2026.05.08-system-01", + "date": "2026-05-08", + "summary": "新增 order.wave.waveStrategyFetch:按策略提交抓取任务(壳子方法)", + "methods": [ + "order.wave.waveStrategyFetch" + ], + "notes": [ + "当前方法为壳子方法:仅受理并返回任务受理信息,不执行真实抓取逻辑,后续补齐执行链路。" + ], + "type": "added" + }, + { + "version": "2026.05.07-system-05", + "date": "2026-05-07", + "summary": "新增 order.wave.waveStrategyCreate 与 order.wave.waveStrategyUpdate:波次策略创建与更新接口(含参数校验与版本推进)", + "methods": [ + "order.wave.waveStrategyCreate", + "order.wave.waveStrategyUpdate" + ], + "notes": [ + "仓库 ID 与创建人(creator_name)由当前登录仓库/操作者上下文获取,接口不接受外部覆盖。", + "入参 allowed_owners 与 allowed_expresses 会校验是否在系统可用范围内(基于仓库签约货主或系统快递列表),若存在非法值接口会直接报错(400)。", + "max_same_structure 受仓库配置 min_group_order_fetch_quantity 限制:若传入值 >= min_group_order_fetch_quantity,则自动下调为 min_group_order_fetch_quantity - 1(最小值为 1)。", + "新建/更新成功后会触发仓库的 wave_strategy_version 自增(+1)并失效相关仓库配置缓存,调用方可通过策略版本推进或缓存变化感知策略已生效。" + ], + "type": "added" + }, + { + "version": "2026.05.07-system-06", + "date": "2026-05-07", + "summary": "收敛 order.wave.waveStrategyFallbackOrderList 返回字段,限定 where 白名单,补充 order.wave.singleFetchByIds 别名与返回语义", + "methods": [ + "order.wave.waveStrategyFallbackOrderList", + "order.wave.singleFetchByIds" + ], + "notes": [ + "收敛 order.wave.waveStrategyFallbackOrderList response.list 字段为 id, delivery_no, tracking_no, items_count, items_total, sys_logistics_name, store_name, province, sys_platform_name, item_snapshot;item_snapshot 格式示例:商品名称*数量|...。", + "限制 order.wave.waveStrategyFallbackOrderList.where 白名单,禁止传入 warehouse_id / warehouseId;传入未列出字段或别名冲突将返回 400。", + "补充 order.wave.singleFetchByIds:明确支持 ids / order_ids / orderIds 三个别名(优先顺序 ids -> order_ids -> orderIds)并说明返回字段 fetched_order_ids、excluded_existing_wave_order_ids、skipped_order_ids、not_found_order_ids 的语义与兼容性。" + ], + "type": "updated" + }, + { + "version": "2026.05.07-system-04", + "date": "2026-05-07", + "summary": "更新 order.wave.waveStrategyFallbackOrderList,新增商品快照字段 item_snapshot", + "methods": [ + "order.wave.waveStrategyFallbackOrderList" + ], + "notes": [ + "item_snapshot 返回格式为 商品名称1*数量|商品名称2*数量" + ], + "type": "updated" + }, + { + "version": "2026.05.07-system-03", + "date": "2026-05-07", + "summary": "新增 order.wave.waveStrategyQuickScan 与进度查询接口", + "methods": [ + "order.wave.waveStrategyQuickScan", + "order.wave.waveStrategyQuickScanTaskProgress" + ], + "notes": [ + "同仓只允许一个扫描任务并使用缓存锁;扫描范围为当前表非待审核、未分配波次且订单策略版本与仓库当前版本不一致的订单;命中策略标记 wave_scan_result=1,否则=2" + ], + "type": "added" + }, + { + "version": "2026.05.07-system-02", + "date": "2026-05-07", + "summary": "新增 order.wave.waveStrategyList:查询当前仓库波次策略列表", + "methods": [ + "order.wave.waveStrategyList" + ], + "notes": [ + "从 wms_wave_strategy 拉取当前仓库的波次策略列表,分页返回" + ], + "type": "added" + }, + { + "version": "2026.05.07-system-01", + "date": "2026-05-07", + "summary": "移除 order.wave.singleOrderFetchDetailList,新增 order.wave.waveStrategyFallbackOrderList(内置固定筛选条件)", + "methods": [ + "order.wave.singleOrderFetchDetailList", + "order.wave.waveStrategyFallbackOrderList" + ], + "notes": [ + "移除 order.wave.singleOrderFetchDetailList。", + "新增 order.wave.waveStrategyFallbackOrderList。", + "新接口基于订单通用查询口径,固定内置筛选条件:step != 0、wave_id = 0、wave_scan_result = 2。" + ], + "type": "updated" + }, + { + "version": "2026.05.06-system-06", + "date": "2026-05-06", + "summary": "新增 order.wave.singleOrderFetchDetailList:订单级散单候选明细视图", + "methods": [ + "order.wave.singleOrderFetchDetailList" + ], + "notes": [ + "新增 order.wave.singleOrderFetchDetailList:提供订单级的散单候选明细列表,返回按订单聚合的明细(非分组级)。", + "返回订单级而非分组级;响应每项包含订单 id、group_count、item_detail_machine、item_detail_machine_snapshot、item_detail、item_snapshot、logistics_name、store_id、distinguish_express、create_at 与 status_summary 等关键字段。", + "仍沿用 same_order_quantity 阈值来排除团购命中分组(仅保留 group_count < same_order_quantity 的候选项)。", + "singleOrderFetchList 暂保留以兼容现有前端,前端可在切换到订单级视图后迁移到本接口。" + ], + "type": "added" + }, + { + "version": "2026.05.06-system-05", + "date": "2026-05-06", + "summary": "storage.receiving.get 返回扩展:data.details[*] 新增 box_remainder、box_weight", + "methods": [ + "storage.receiving.get" + ], + "notes": [ + "storage.receiving.get 的响应在 data.details[*] 中新增可选字段:box_remainder(箱内剩余数量/零散数量,number,默认 0)与 box_weight(实测箱重,number,默认 0)。", + "兼容性:新增字段为可选,旧客户端无需修改;建议前端在需要展示箱内余量/箱重时使用这些字段。" + ], + "type": "updated" + }, + { + "version": "2026.05.06-system-04", + "date": "2026-05-06", + "summary": "storage.receiving.getReceivingDetail 返回扩展:明细增加 box_remainder、box_weight;storage.receiving.completeReceiving 通知包含这两个字段", + "methods": [ + "storage.receiving.getReceivingDetail", + "storage.receiving.completeReceiving" + ], + "notes": [ + "为支持箱规统计与通知回传,getReceivingDetail 的明细项(receiving.details 或 data.details)在响应中新增可选字段:box_remainder(箱内剩余数量/零散数量,number)与 box_weight(实测箱重,number,单位同系统重量)。", + "completeReceiving 在完成收货后会发送通知(或回调),通知 payload/metadata 中将包含每条明细的 box_remainder 与 box_weight 字段,供下游系统/前端展示或审计使用。", + "兼容性:新增字段为可选,旧客户端在未使用这些字段时无需变更。" + ], + "type": "updated" + }, + { + "version": "2026.05.06-system-03", + "date": "2026-05-06", + "summary": "storage.receiving.detailChange:新增入参/出参字段 box_remainder、box_weight", + "methods": [ + "storage.receiving.detailChange" + ], + "notes": [ + "为支持箱规细化与回写,detailChange 新增可选入参 box_remainder(箱内余量/零散数量)和 box_weight(实测箱重,单位同系统重量),写入后会回写至明细并在响应 data 中返回对应字段。", + "兼容性:新增字段为可选,不传入则不影响现有调用;建议前端在需要回写箱余与箱重时一并传入。" + ], + "type": "updated" + }, + { + "version": "2026.05.06-system-02", + "date": "2026-05-06", + "summary": "新增 order.wave.singleFetchByIds:按订单ID抓取到一个散单波次", + "methods": [ + "order.wave.singleFetchByIds" + ], + "notes": [ + "新增 order.wave.singleFetchByIds:按入参 ids(兼容 order_ids/orderIds)去重后筛选当前仓库内待处理且不在波次中的订单,若存在可抓取订单则创建单个散单波次并把这些订单写入该波次(不区分快递);成功后批量写入订单操作日志;若无可抓取订单返回 wave_id=0。", + "接口行为严格对齐实现:过滤条件包含 step in [1,2,3]、status != 'cancel'、outbound_status != 'padding';已在波次的订单会被排除并返回 excluded_existing_wave_order_ids;响应包含 ids、wave_id、wave_no、fetched_order_ids、fetched_order_count、excluded_existing_wave_order_ids、skipped_order_ids、not_found_order_ids。" + ], + "type": "added" + }, + { + "version": "2026.05.06-system-01", + "date": "2026-05-06", + "summary": "新增 order.wave.groupFetch 与 order.wave.singleFetch;order.wave.fetch 保留兼容别名;抓取进度补充上限字段", + "methods": [ + "order.wave.groupFetch", + "order.wave.singleFetch", + "order.wave.fetch", + "order.wave.fetchTaskProgress" + ], + "notes": [ + "新增 order.wave.groupFetch:抓取团购接口(异步任务提交),参数 structure_list 与原 fetch 一致。", + "新增 order.wave.singleFetch:抓取散单接口(异步任务提交),在 structure_list 每项新增必填字段 max_fetch_quantity(最大抓取上限,订单数,正整数)。", + "order.wave.fetch 保留为兼容别名(等同 groupFetch),避免误导客户端。", + "groupFetch/singleFetch/fetch 的响应新增可选字段 fetch_mode;singleFetch 响应额外返回 max_fetch_quantity。", + "order.wave.fetchTaskProgress 的响应增加单模式相关字段:fetch_mode、max_fetch_quantity、limit_reached、stop_reason,用于描述散单抓取的上限与停止原因。" + ], + "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-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": "updated" + }, + { + "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 查询全字段列表并支持缓存", + "methods": [ + "setting.expressInterface.listByWarehousePlatformCode" + ], + "notes": [ + "新增 setting.expressInterface.listByWarehousePlatformCode:按 warehouse_id + platform_code 返回快递接口的全字段数组(不分页),每条记录包含 express 关联对象(id/code/name/platform 等)。", + "支持缓存,缓存键由 warehouse_id + platform_code 组成;缓存命中将直接返回缓存结果以提升查询性能。", + "在创建/更新/删除操作(setting.expressInterface.create/update/delete)后,会主动清理对应 warehouse_id + platform_code 的缓存以确保数据一致性。" + ], + "type": "added" + }, + { + "version": "2026.04.17-system-08", + "date": "2026-04-17", + "summary": "新增快递编码管理模块批量软删除接口 setting.express.delete", + "methods": [ + "setting.express.delete" + ], + "notes": [ + "新增批量软删除接口 setting.express.delete:接受 ids(数组、逗号字符串或单值),对属于当前仓库且未被删除的记录执行软删除(设置 deleted_at),并清理 express 列表缓存。", + "当任一目标记录的 code 被 wms_express_interface.express_code 引用时,接口会拒绝删除并返回 409,错误信息中包含被引用的编码列表。", + "响应包含 ids、deleted_ids、already_deleted_ids 与 status,已删除与未删除的 id 会明确分类。仅记录已实现行为。" + ], + "type": "added" + }, + { + "version": "2026.04.17-system-05", + "date": "2026-04-17", + "summary": "新增文档分组:平台编码管理模块(收口 index.getPlatformList 与 setting.platform.*)", + "methods": [ + "index.getPlatformList", + "setting.platform.list", + "setting.platform.create", + "setting.platform.update", + "setting.platform.delete" + ], + "notes": [ + "新增独立文档分组 '平台编码管理模块',将平台基础列表(index.getPlatformList)与平台设置管理接口(setting.platform.*)归并为单一分组以便维护;仅文档变更,不修改实现。", + "文档中仅包含已实现的方法与字段,未新增或推断不存在的参数/返回字段。" + ], + "type": "added" + }, + { + "version": "2026.04.17-system-04", + "date": "2026-04-17", + "summary": "新增独立平台设置模块 setting.platform(wms_platfrom_setting)及其 CRUD 接口:list/create/update/delete。", + "methods": [ + "setting.platform.list", + "setting.platform.create", + "setting.platform.update", + "setting.platform.delete" + ], + "notes": [ + "新增独立模块 setting.platform,映射数据表 wms_platfrom_setting;list 支持 where(id/code/name/platform_code/quickWhere)与 pagination(兼容 page/pageSize/page_size);create/update 要求 platform_code 必须存在于系统平台表(wms_platform),且禁止越权写入 warehouse_id;delete 需传入 id 并校验当前仓库范围。" + ], + "type": "added" + }, + { + "version": "2026.04.15-system-07", + "date": "2026-04-15", + "summary": "将 docs/order-workbench-list-api.md 引用统一为 window 链接格式", + "methods": [ + "order.list", + "order.reviewOrder.list", + "order.pendingOrder.list", + "order.outboundOrder.list", + "order.expectionOrder.list", + "order.entrustOrder.list", + "order.deliveryOrder.list", + "order.deliveryExpectionOrder.list" + ], + "notes": [ + "将所有 methods/system.json 中指向 docs/order-workbench-list-api.md 的说明统一替换为 docs/order-workbench-list-api.md 格式,以便 HTML 渲染识别为 window 链接。", + "仅修改 methods/system.json 的文档字段,不涉及任何业务代码或接口契约变化。" + ], + "type": "updated" + }, + { + "version": "2026.04.15-system-06", + "date": "2026-04-15", + "summary": "订单工作台列表文档补全 raw 字段字典与中文语义说明", + "methods": [ + "order.list", + "order.reviewOrder.list", + "order.pendingOrder.list", + "order.outboundOrder.list", + "order.expectionOrder.list", + "order.entrustOrder.list", + "order.deliveryOrder.list", + "order.deliveryExpectionOrder.list", + "order.archiveOrder.list" + ], + "notes": [ + "在 docs/order-workbench-list-api.md 中补充所有订单列表通用 raw 字段字典,明确每个字段的中文语义与 enum 取值。", + "补充 express_numbers / waybill_codes 两个服务层派生字段说明,便于前端直接渲染多个快递号。", + "methods/system.json 中所有订单 list 的 response.list 描述已指向该字段字典章节。" + ], + "type": "updated" + }, + { + "version": "2026.04.15-system-05", + "date": "2026-04-15", + "summary": "基础模块新增快递/平台列表查询接口并设置为不鉴权,复用缓存 service", + "methods": [ + "index.getExpressList", + "index.getPlatformList" + ], + "notes": [ + "新增 index.getExpressList,归属基础模块(module=index),对应 app/service/systems/express.js 中的 getExpressList。", + "index.getExpressList 设置为不鉴权,不需要 Authorization 头。", + "新增 index.getPlatformList,归属基础模块(module=index),对应 app/service/systems/platform.js 中的 getPlatformList。", + "index.getPlatformList 设置为不鉴权,不需要 Authorization 头。", + "快递列表与平台列表都支持缓存优先,缓存未命中时回源数据库并写入缓存。", + "平台列表支持缓存优先,缓存未命中时回源 wms_platform 并写入缓存。" + ], + "type": "added" + }, + { + "version": "2026.04.15-system-02", + "date": "2026-04-15", + "summary": "签约策略字段元信息新增 default_express_code / default_platform_code list 选项", + "methods": [ + "storeWarehouse.store.getPolicyConfigFields" + ], + "notes": [ + "getPolicyConfigFields 现在返回 default_express_code 与 default_platform_code 两个 list 字段,并从 wms_express / wms_platform 读取选项列表。", + "默认值仍保留为 default_express_code=STO、default_platform_code=TB。" + ], + "type": "updated" + }, + { + "version": "2026.04.15-system-03", + "date": "2026-04-15", + "summary": "签约策略字段移除 sku_visibility,receive_mode options 改为 value/label 结构", + "methods": [ + "storeWarehouse.store.savePolicyConfig", + "storeWarehouse.store.getPolicyConfigFields" + ], + "notes": [ + "策略字段定义不再包含 sku_visibility,历史值读取时仍会被归一化忽略。", + "receive_mode 的 options 改为 [{ value, label }] 格式,便于前端直接渲染。" + ], + "type": "updated" + }, + { + "version": "2026.04.15-system-04", + "date": "2026-04-15", + "summary": "按文件模块拆分 order 目录系统文档分组,覆盖订单工作台入口及各子模块方法", + "methods": [ + "order.list", + "order.manualOutboundOrder", + "order.badgeCount", + "order.outboundOrder.manualOutboundOrder", + "order.reviewOrder.list", + "order.reviewOrder.reviewOrder", + "order.pendingOrder.list", + "order.pendingOrder.reverseReviewOrder", + "order.pendingOrder.markPendingOutboundOrder", + "order.pendingOrder.cancelOrder", + "order.outboundOrder.list", + "order.expectionOrder.list", + "order.entrustOrder.list", + "order.deliveryOrder.list", + "order.deliveryExpectionOrder.list", + "order.archiveOrder.list" + ], + "notes": [ + "按 app/service/systemMethods/order 下的实际对外方法补全 methods/system.json 文档,只覆盖 system,不处理 qimen。", + "order 文档已按 index / reviewOrder / pendingOrder / outboundOrder / expectionOrder / entrustOrder / deliveryOrder / deliveryExpectionOrder / archiveOrder 拆成多个模块分组。", + "同步根据当前代码意图补充 params / response / errors,且不再把 index.js 已移除的兼容接口写回文档。" + ], + "type": "updated" + }, + { + "version": "2026.04.15-system-01", + "date": "2026-04-15", + "summary": "货主主体配置默认补齐 default_express_code / default_platform_code", + "methods": [ + "store.createStore", + "store.createWarehouse" + ], + "notes": [ + "当 subject_config 未传或缺少字段时,自动补齐 default_express_code=STO、default_platform_code=TB,并保留现有的 max_notice_webhook_count 默认值。", + "同步更新 methods/system.json 中 store.createStore 与 store.createWarehouse 的参数说明。" + ], + "type": "updated" + }, + { + "version": "2026.04.14-system-01", + "date": "2026-04-14", + "summary": "库存列表新增货主名称字段 stock.store_name", + "methods": [ + "storage.inventory.list" + ], + "notes": [ + "在 methods/system.json 的 storage.inventory.list response 中补充 stock.store_name:来源于签约表 store_remask,若无签约关系则为 null。", + "只同步文档,不修改业务代码。" + ], + "type": "updated" + }, + { + "version": "2026.04.13-system-01", + "date": "2026-04-13", + "summary": "补全 storage.receiving.detailChange 的入参/出参契约与错误码说明", + "methods": [ + "storage.receiving.detailChange" + ], + "notes": [ + "在 methods/system.json 中补充 storage.receiving.detailChange 的 params/response/errors,明确 id 与 receiving_id 必填。", + "说明 expiry_date 小于当前日期时返回 400 且 message 为 \"到期日期已过期,不能录入收货\"。", + "说明当传入 system_product_id 时会回填条码、重量、箱规、商品名称与 product_snapshot;未传时 barcode/product_name 也可单独更新。", + "同步补充文档:docs/storage-receiving-api.md 中新增 detailChange 段落。" + ], + "type": "updated" + }, + { + "version": "2026.04.07-system-01", + "date": "2026-04-07", + "summary": "修正 warehouse.getAreaRacks 的鉴权/权限链路文档,明确该接口需要 登录并走权限校验。", + "methods": [ + "warehouse.getAreaRacks" + ], + "notes": [ + "对齐当前 system 文档中的 isNeedAuth=true、isNeedLogin=true。", + "用于补充该接口权限链路修正文档的历史上下文,不改变 methods/system.json 的 SSOT 角色。" + ] + }, + { + "version": "2026.04.07-system-02", + "date": "2026-04-07", + "summary": "补充签约配置相关接口文档,覆盖策略字段元信息查询与面单数量人工调整。", + "methods": [ + "storeWarehouse.store.getPolicyConfigFields", + "storeWarehouse.store.adjustPrintQuantity" + ], + "notes": [ + "getPolicyConfigFields 说明为获取签约策略可配置字段元信息列表。", + "adjustPrintQuantity 说明为人工调整签约关系下的面单余额并记录变更日志,并 明确 id、change_quantity、reason 等关键入参。" + ] + }, + { + "version": "2026.04.07-system-03", + "date": "2026-04-07", + "summary": "对外命名从 qimenConfig 收口为 apiConfig,并在接口配置文档中强调 interface_type_id 校验。", + "methods": [ + "storeWarehouse.store.listApiConfig", + "storeWarehouse.store.saveApiConfig", + "storeWarehouse.store.deleteQimenConfig" + ], + "notes": [ + "文档对外统一使用 apiConfig / api_config 命名,减少 qimenConfig 历史别名歧义。", + "saveApiConfig 要求 interface_type_id 为必填且必须指向已存在的 wms_interface_type 记录。", + "listApiConfig / deleteQimenConfig 同步补充 interface_type_id 字段说明。" + ] + }, + { + "version": "2026.04.07-system-04", + "date": "2026-04-07", + "summary": "补充 /api/docs 文档体验增强说明,新增查看变更记录与查看原文 JSON 的入口说明。", + "methods": [ + "/api/docs", + "/api/docs/:docName", + "/api/docs/:docName/raw", + "/api/docs/:docName/changes" + ], + "notes": [ + "sidecar 变更数组用于承载文档历史说明,不替代 methods/system.json 作为 SSOT。", + "原文 JSON 入口继续用于直接查看当前生效文档。" + ] + }, + { + "version": "2026.04.07-system-05", + "date": "2026-04-07", + "summary": "修正 storeWarehouse.store.adjustPrintQuantity 的面单余额调整语义:由增减/累加改为覆盖设置目标余额。", + "methods": [ + "storeWarehouse.store.adjustPrintQuantity" + ], + "notes": [ + "adjustPrintQuantity 当前兼容 print_quantity、target_quantity、change_quantity、adjust_quantity 作为目标面单余额输入,不再按增减量解释。", + "变更日志中的 change_quantity 由 before/after 自动计算差值,以兼容历史审计与展示。" + ] + }, + { + "version": "2026.04.07-system-06", + "date": "2026-04-07", + "summary": "按接口类型分类限制必填字段,OPEN_API 创建时自动生成 self_app_key/self_app_secret", + "methods": [ + "storeWarehouse.store.saveApiConfig" + ], + "notes": [ + "QM_WMS 类型须填写 qimen_app_key/qimen_customer_id/qimen_warehouse_code;OPEN_API 类型三个奇门字段非必填,创建时自动生成 self_app_key(WMS+32位HEX)和 self_app_secret(64位HEX),更新时保留已有密钥。" + ], + "type": "changed" + }, + { + "version": "2026.04.07-system-07", + "date": "2026-04-07", + "summary": "新增接口类型列表查询接口,归属基础模块,无需权限", + "methods": [ + "index.listInterfaceTypes" + ], + "notes": [ + "返回所有已启用的接口类型(wms_interface_type),包含 id、interface_code、interface_name、interface_category、description 字段。设置 isNeedAuth: false, isNeedLogin: true。" + ], + "type": "added" + }, + { + "version": "2026.04.07-system-08", + "date": "2026-04-07", + "summary": "app_name 改为必传参数", + "methods": [ + "storeWarehouse.store.saveApiConfig" + ], + "notes": [ + "app_name 不再有默认值自动生成逻辑,调用方必须传入非空的 app_name,否则返 回 400 错误。" + ], + "type": "changed" + }, + { + "version": "2026.04.07-system-09", + "date": "2026-04-07", + "summary": "新增收货单快捷入库上架接口", + "methods": [ + "storage.inventory.quickPutaway" + ], + "notes": [ + "新建 storage.inventory 库存操作模块。quickPutaway 从收货单直接生成入库单 (SCRK)并写入 wms_storage 库存表,同时更新 wms_stock_warehouse 库存数量(悲观行锁),回填收货明细入库状态。要求收货单已完成且所有明细已匹配系统商品。" + ], + "type": "added" + }, + { + "version": "2026.04.08-system-01", + "date": "2026-04-08", + "summary": "新增收货单与入库单匹配入库接口", + "methods": [ + "storage.inventory.matchPutaway" + ], + "notes": [ + "接收多个收货单和入库单,按商品(stock_warehouse_id)进行数量匹配入库,完 成后根据入库单来源(QM/API)自动触发回传。入参为 receiving_ids(数组)和 entry_order_ids(数组),返回匹配汇总、各收货单入库状态、各入库单状态及回传结果。isNeedAuth=true, isNeedLogin=true, isNeedRight=false。" + ], + "type": "added" + }, + { + "version": "2026.04.08-system-02", + "date": "2026-04-08", + "summary": "saveApiConfig 新增 callback_url 可选参数", + "methods": [ + "storeWarehouse.store.saveApiConfig" + ], + "notes": [ + "新增 callback_url 参数(VARCHAR(500),可选),用于 OPEN_API 类型入库单的 回调地址配置。" + ], + "type": "changed" + }, + { + "version": "2026.04.08-system-03", + "date": "2026-04-08", + "summary": "serializeQimenConfig 新增返回 callback_url 字段,影响 list 和 listApiConfig 两个接口", + "methods": [ + "storeWarehouse.store.list", + "storeWarehouse.store.listApiConfig" + ], + "notes": [ + "serializeQimenConfig() 序列化方法新增 callback_url(string)字段。storeWarehouse.store.list 返回的每条记录 api_config 对象中包含 callback_url;storeWarehouse.store.listApiConfig 返回的 list 数组中每条配置包含 callback_url。" + ], + "type": "changed" + }, + { + "version": "2026.04.08-system-04", + "date": "2026-04-08", + "summary": "新增库存移库(库位转移)接口", + "methods": [ + "storage.inventory.transferLocation" + ], + "notes": [ + "新增 storage.inventory.transferLocation 接口,支持批量多商品多库位移库, 包含部分数量移库与全量移库。入参为 warehouse_id(仓库ID)和 transfers 数组(storage_id、target_space_id、quantity),触发 storage_transfer_completed 通知事件, 每条移库记录独立操作日志。isNeedAuth=true, isNeedLogin=true。" + ], + "type": "added" + }, + { + "version": "2026.04.08-system-05", + "date": "2026-04-08", + "summary": "简化移库接口入参,从批量 transfers 数组改为单条移库", + "methods": [ + "storage.inventory.transferLocation" + ], + "notes": [ + "移除 warehouse_id 和 transfers 数组入参,改为扁平的 storage_id + target_space_id + quantity 三个顶层参数。warehouse_id 从库存记录自动获取,接口从批量移库简化为单商品单库位移库。响应结构同步简化为单条结果对象。" + ], + "type": "modified" + }, + { + "version": "2026.04.08-system-06", + "date": "2026-04-08", + "summary": "新增商品库存明细查询接口", + "methods": [ + "stock.warehouse.getStockDetail" + ], + "notes": [ + "新增 stock.warehouse.getStockDetail 接口,按库位/批次维度查询商品库存分布。入参为 stock_id(必填,商品库存ID)和 pagination(可选,含 page/pageSize)。返回 stockItem(商品概要)、storageList(wms_storage 明细数组,含批次号、库位、数 量、锁定数量、生产日期、过期日期等,关联 location_space 库位信息)、pagination 分页信息。isNeedAuth=false, isNeedLogin=true。底层调用 stockStore.getStockDetail,自动校验商品归属当前仓库。" + ], + "type": "added" + }, + { + "version": "2026.04.08-system-07", + "date": "2026-04-08", + "summary": "新增入参 group_by_batch,支持按批次维度切换库存明细聚合方式", + "methods": [ + "stock.warehouse.getStockDetail" + ], + "notes": [ + "新增可选布尔参数 group_by_batch(默认 false)。false 时按库位合并数量,批次相关字段(batch_no, production_date, expiry_date, inbound_time, inbound_order_no, supplier_batch_no)置 null;true 时保持原逻辑返回每条明细。出参结构不变,但 storageList 中批次字段在合并模式下为 null。" + ], + "type": "modified" + }, + { + "version": "2026.04.08-system-08", + "date": "2026-04-08", + "summary": "新增按商品维度移库接口", + "methods": [ + "storage.inventory.transferByProduct" + ], + "notes": [ + "新增 storage.inventory.transferByProduct 接口,按库位+商品查找所有库存记 录合并移动。入参为 space_id(原库位ID)、stock_id(商品SKU ID,即 wms_stock_warehouse.id)、target_space_id(目标库位ID)、quantity(移库数量)。开启批次管理(is_batch_mgmt=Y)的商品会被拒绝,需使用 transferLocation 按库存记录精确移库。复用 storage_transfer_completed 通知事件,操作日志编码 STORAGE_TRANSFER_BY_PRODUCT。isNeedAuth=true, isNeedLogin=true。" + ], + "type": "added" + }, + { + "version": "2026.04.08-system-09", + "date": "2026-04-08", + "summary": "补充 storeWarehouse.store.list 完整 response 输出字段说明,移除 api_config / apiConfig", + "methods": [ + "storeWarehouse.store.list" + ], + "notes": [ + "从返回结果中移除 api_config 和 apiConfig 字段(代码中 delete serialized.api_config / delete serialized.apiConfig),文档 response 补充完整输出字段列表:id, store_id, store_name, warehouse_id, warehouse_name, counterparty_id, counterparty_name, current_subject_role, auth_status, auth_status_label, apply_reason, review_comment, apply_time, review_time, auth_start, auth_end, actual_end, print_quantity, applied_by, reviewed_by, ended_by, remask, use_status, policy_config, is_auth_valid, remaining_days 以及分页和 current_subject 信息。" + ], + "type": "updated" + }, + { + "version": "2026.04.08-system-10", + "date": "2026-04-08", + "summary": "货主列表返回新增 has_qimen_config 布尔字段", + "methods": [ + "storeWarehouse.store.list" + ], + "notes": [ + "storeWarehouse.store.list 返回的 data.list[] 中新增 has_qimen_config(boolean),表示该货主是否已配置奇门。" + ], + "type": "changed" + }, + { + "version": "2026.04.08-system-11", + "date": "2026-04-08", + "summary": "补全 stock.warehouse.search 接口文档,新增 params / response / errors 完整说明", + "methods": [ + "stock.warehouse.search" + ], + "notes": [ + "入参补充 keyword(string,模糊匹配 item_code / item_name / goods_code / barcode)和 store_id(number,按货主筛选)。响应补充 data 数组各字段(id, item_code, goods_code, item_name, sku_property, stock_unit, quantity, locked_quantity, brand_name, item_type, barcodes, store_stock)以及 total。errors 补充 code=0 搜 索失败场景。" + ], + "type": "updated" + }, + { + "version": "2026.04.08-system-12", + "date": "2026-04-08", + "summary": "新增 with_stock / is_batch 参数,支持返回关联库存明细(按库位分 组或按批次逐条)", + "methods": [ + "stock.warehouse.search" + ], + "notes": [ + "入参新增 with_stock(boolean,默认 false,是否返回关联库存数据)和 is_batch(boolean,默认 false,仅 with_stock=true 时生效,按批次明细返回)。响应 data[] 新增 storage[] 字段:is_batch=false 时按库位分组汇总(含 space_id、space、inventory_type、quantity、locked_quantity、available_quantity);is_batch=true 时逐 条返回批次明细(含 id、stock_id、space_id、batch_no、inventory_type、quantity、locked_quantity、available_quantity、production_date、expiry_date、inbound_time、inbound_order_no、supplier_batch_no、created_at、space)。" + ], + "type": "updated" + }, + { + "version": "2026.04.08-system-13", + "date": "2026-04-08", + "summary": "新增 wms_stock_transaction 表和模型", + "methods": [ + "wms_stock_transaction" + ], + "notes": [ + "新增出入库流水记录表 wms_stock_transaction,含 transaction_type(INBOUND/OUTBOUND)、warehouse_id、store_id、stock_id、storage_id、space_id、quantity、batch_no、inventory_type、order_type、order_no、order_id、receiving_id、entry_order_id、operator_id、operator_name、remark 等字段,关联 StockWarehouse 和 Storage 模型。" + ], + "type": "added" + }, + { + "version": "2026.04.08-system-14", + "date": "2026-04-08", + "summary": "quickPutaway 和 matchPutaway 入库时自动写入出入库记录", + "methods": [ + "storage.inventory.quickPutaway", + "storage.inventory.matchPutaway" + ], + "notes": [ + "入库操作完成后自动写入 wms_stock_transaction 记录。quickPutaway 写入 order_type='SCRK'(收货入库),matchPutaway 写入 order_type='MATCH'(匹配入库),均 自动填充 warehouse_id、store_id、stock_id、storage_id、space_id、quantity、batch_no、inventory_type 等字段。" + ], + "type": "updated" + }, + { + "version": "2026.04.08-system-15", + "date": "2026-04-08", + "summary": "新增 storage.inventory.list 出入库记录列表查询接口", + "methods": [ + "storage.inventory.list" + ], + "notes": [ + "出入库记录列表查询,支持 where 条件(transaction_type、stock_id、space_id、store_id、order_type、order_no、inventory_type、operator_name、created_at)、 分页(pagination)、排序(sort)和 group_by_batch 参数。默认合并模式按库位+商品 聚合返回合计数量与记录条数,group_by_batch=true 时返回每条明细含 batch_no、order_no、operator_name 等完整信息。响应均关联 stockItem(item_code、item_name、sku_property、stock_unit)。" + ], + "type": "added" + }, + { + "version": "2026.04.08-system-16", + "date": "2026-04-08", + "summary": "出入库流水记录查询接口从 storage.inventory.list 改名为 storage.transaction.list", + "methods": [ + "storage.transaction.list" + ], + "notes": [ + "将出入库流水记录查询从 storage.inventory.list 迁移到 storage.transaction.list,避免与库存列表概念混淆。功能和参数不变。isNeedAuth=false, isNeedLogin=true, isNeedRight=false。" + ], + "type": "rename", + "module": "storage" + }, + { + "version": "2026.04.08-system-17", + "date": "2026-04-08", + "summary": "新增 storage.inventory.list 库存列表查询接口", + "methods": [ + "storage.inventory.list" + ], + "notes": [ + "新增库存列表查询接口,查询 wms_storage 表。支持 where 条件(stock_id/space_id/store_id/inventory_type/batch_no/inbound_order_no/available_quantity/inbound_time/created_at)、分页、排序。支持 group_by_batch 参数:默认 false 按库位+商 品合并(SUM quantity/locked_quantity/available_quantity),true 返回每条明细含 batch_no/production_date/expiry_date 等。关联 stockItem(商品信息)和 space(库位信息)。isNeedAuth=false, isNeedLogin=true, isNeedRight=false。" + ], + "type": "add", + "module": "storage" + }, + { + "version": "2026.04.08-system-18", + "date": "2026-04-08", + "summary": "移除 storage.entry.create 创建入库单接口", + "methods": [ + "storage.entry.create" + ], + "notes": [ + "不再允许通过 API 创建入库单。入库单仅由快捷入库(quickPutaway)和匹配入库(matchPutaway)等内部流程自动创建。底层 service 实现保留但不再通过 systemMethods 对外暴露。" + ], + "type": "remove", + "module": "storage" + }, + { + "version": "2026.04.08-system-19", + "date": "2026-04-08", + "summary": "移除 storage.entry.addDetail / deleteDetail / detailChange 对外 接口", + "methods": [ + "storage.entry.addDetail", + "storage.entry.deleteDetail", + "storage.entry.detailChange" + ], + "notes": [ + "入库单明细编辑能力不再通过 systemMethods 对外暴露,入库单模块仅保留 list/get/cancel/completeEntry。" + ], + "type": "remove", + "module": "storage" + }, + { + "version": "2026.04.08-system-20", + "date": "2026-04-08", + "summary": "新增 storage.stockout 出库单模块(非订单出库单能力)", + "methods": [ + "storage.stockout.list", + "storage.stockout.toOrder", + "storage.stockout.listItems" + ], + "notes": [ + "新增 storage.stockout.list / toOrder / listItems 接口,作为非订单出库单的主出口(对应奇门 stockout.create)。storage.delivery.* 仅作为兼容转发保留;底层 部分能力仍复用 order 模块。" + ], + "type": "add", + "module": "storage" + }, + { + "version": "2026.04.08-system-21", + "date": "2026-04-08", + "summary": "将 storage.stockout.toOrder 标记为占位接口", + "methods": [ + "storage.stockout.toOrder" + ], + "notes": [ + "storage.stockout.toOrder 当前仅保留方法名用于后续扩展,暂不开放实际逻辑。调用时返回 code=405、message=占位接口,暂未开放。" + ], + "type": "change" + }, + { + "version": "2026.04.09-system-01", + "date": "2026-04-09", + "summary": "storage.entry.cancel 支持批量作废,新增 ids 入参并兼容单条 id", + "methods": [ + "storage.entry.cancel" + ], + "notes": [ + "新增入参 `ids`(number[])以支持批量作废,兼容旧入参 `id`;当同时传入 `ids` 与 `id` 时以 `ids` 为准。", + "参数校验:`ids` 必须为非空数组;非法 ID 或空数组返回 400。", + "业务约束:已完成/已作废/处于不可作废状态的单据不允许作废;批量场景下任一 单据不存在或状态不允许时整体返回 404/400,未执行部分更新。", + "响应说明:单条作废返回字段 `id`(number);批量作废返回字段 `ids`(number[])。", + "已同步更新 methods/system.json(storage.entry.cancel)为 SSOT。" + ] + }, + { + "version": "2026.04.09-system-02", + "date": "2026-04-09", + "summary": "新增基础模块车牌识别接口 index.recognizeLicensePlate", + "methods": [ + "index.recognizeLicensePlate" + ], + "notes": [ + "入参:base64(string,必填)或 imageBase64/image_base64(兼容)", + "响应:返回归一化后的识别对象,包含 licensePlate、plateNumber、color、confidence、requestId、imageSize、rawData", + "错误:400(参数或图片格式/尺寸问题),500(第三方 OCR 调用失败或云密钥未 配置)", + "文档中不包含任何敏感配置;实际腾讯云密钥保留在配置文件中,勿在文档中暴露 。" + ], + "type": "added" + }, + { + "version": "2026.04.09-system-03", + "date": "2026-04-09", + "summary": "收紧基础模块车牌识别接口响应,仅返回 licensePlate 字段", + "methods": [ + "index.recognizeLicensePlate" + ], + "notes": [ + "出参由 {licensePlate, plateNumber, color, confidence, requestId, imageSize, rawData} 调整为 {licensePlate}", + "调用方请仅依赖 licensePlate 字段以适配新版本;历史字段已裁剪且不再保证存 在。", + "文档中未包含任何云密钥或敏感配置信息。" + ], + "type": "changed" + }, + { + "version": "2026.04.10-system-01", + "date": "2026-04-10", + "summary": "订单审核字段由 audit_status 替换为整数字段 step,并添加数据库迁移", + "methods": [ + "order.getreviewOrderlist", + "order.reviewOrder.getreviewOrderlist", + "order.reviewOrder.reviewOrder", + "order.deliveryOrder.getdeliveryOrderlist", + "order.list", + "order.stats" + ], + "notes": [ + "字段变更:order 相关审核字段从字符串/枚举 audit_status 替换为整数 step。", + "step 映射:0=未审核,1=已审核,2=处理中,3=驳回/异常,4=配送中,5=已完成,9=已关闭。", + "reviewOrder 接口在更新 inspection_status 的同时会写入 step 字段。", + "必须执行迁移脚本:20260410150000-replace-audit-status-with-step-on-order-delivery-tables.js" + ], + "type": "changed" + }, + { + "version": "2026.04.13-system-02", + "date": "2026-04-13", + "summary": "stock.warehouse.search 返回新增效期管理字段并保留 is_shelf_life_mgmt", + "methods": [ + "stock.warehouse.search" + ], + "notes": [ + "响应 data[] 中新增字段:inbound_min_days、outbound_min_days、shelf_life_days、remaining_threshold_days(均为 number,单位:天)。", + "保留并说明 is_shelf_life_mgmt 布尔字段(boolean),表示是否启用效期管理(true=启用)。", + "仅更新文档(methods/system.json 与变更记录),代码行为不变。" + ], + "type": "updated" + }, + { + "version": "2026.04.13-system-02", + "date": "2026-04-13", + "summary": "新增 storage.expiry.list 库存有效期列表查询接口", + "methods": [ + "storage.expiry.list" + ], + "notes": [ + "该接口查询 wms_storage,关联 stockWarehouse 和 locationSpace,并按当前仓库与 remaining_threshold_days / expiry_date 过滤。" + ], + "type": "added" + }, + { + "version": "2026.04.13-system-03", + "date": "2026-04-13", + "summary": "新增 storage.inventory.list 库存列表返回效期字段与预警标记", + "methods": [ + "storage.inventory.list" + ], + "notes": [ + "库存列表响应增加生产日期、过期日期、效期预警是否触发字段", + "预警标记仅在商品启用保质期管理且到期日满足阈值条件时为 true" + ], + "type": "updated" + }, + { + "version": "2026.04.14-system-01", + "date": "2026-04-14", + "summary": "更新 index.searchSpace 文档", + "methods": [ + "index.searchSpace" + ], + "notes": [ + "补充 index.searchSpace 的 params/response,按 ctx.user.store_id 作为仓库上下文;keyword 为可选字符串,对 space_code 与 custom_barcode 做 %keyword% 模糊匹配;返回字段 id、space_code、custom_barcode、custom_name,最多 50 条;仅文档同步,无代码变更。" + ], + "type": "updated" + }, + { + "version": "2026.04.16-system-01", + "date": "2026-04-16", + "summary": "基础模块新增快递产品类型查询接口", + "methods": [ + "index.getExpressProductTypeList" + ], + "notes": [ + "新增 index.getExpressProductTypeList,归属基础模块(module=index),用于查询指定快递公司的产品类型列表。", + "对应服务实现:app/service/systems/express.js 中的 getExpressProductTypeList,支持传入 express_code 作为可选筛选参数(source=body)。", + "接口设置为免鉴权(isNeedAuth=false)但需登录(isNeedLogin=true),与 index.getExpressList / index.getPlatformList 一致,优先从缓存读取。" + ], + "type": "added" + }, + { + "version": "2026.04.17-system-01", + "date": "2026-04-17", + "summary": "新增快递管理模块(setting.express)及 5 个接口文档", + "methods": [ + "setting.express.list", + "setting.express.listBase", + "setting.express.create", + "setting.express.checkCodeUnique", + "setting.express.update" + ], + "notes": [ + "新增独立模块组:快递管理模块(module=setting.express),将快递映射管理相关接口独立为一组以便维护。", + "接口实现参考:app/service/systems/setting/express.js(返回结构)与 app/service/systemMethods/setting/express.js(对外方法包装)。", + "接口鉴权与上下文:isNeedAuth=false, isNeedLogin=true;需在请求中传入 Authorization 以携带登录上下文(用于获取当前仓库/货主上下文)。", + "已同步更新 methods/system.json,补充 params/response/errors,保持文档与实现一致。" + ], + "type": "added" + }, + { + "version": "2026.04.17-system-02", + "date": "2026-04-17", + "summary": "setting.express.list 分页入参统一为 pagination", + "methods": [ + "setting.express.list" + ], + "notes": [ + "将 setting.express.list 的分页入参文档从顶层 page/page_size/pageSize 迁移为 pagination 对象,主形态为 pagination;兼容 snake_case 的 page_size 与 camelCase 的 pageSize。", + "文档与当前实现一致:顶层 page/page_size/pageSize 会被归一化到 data.pagination 并转发到系统服务。" + ], + "type": "updated" + }, + { + "version": "2026.04.17-system-03", + "date": "2026-04-17", + "summary": "新增快递接口管理模块(setting.expressInterface)及 4 个接口文档", + "methods": [ + "setting.expressInterface.list", + "setting.expressInterface.create", + "setting.expressInterface.update", + "setting.expressInterface.delete" + ], + "notes": [ + "新增独立模块组:快递接口管理模块(module=setting.expressInterface),对应实现:app/service/systems/setting/expressInterface.js 与对外包装 app/service/systemMethods/setting/expressInterface.js。", + "接口为当前仓库范围(基于 ctx.user.store_id),仓库边界由系统服务强制校验;禁止通过接口指定 warehouse_id/warehouseId。操作需登录(isNeedLogin=true),无需额外鉴权(isNeedAuth=false)。", + "已在 methods/system.json 新增对应接口的 params/response/errors 文档,保持与实现一致。" + ], + "type": "added" + }, + { + "version": "2026.04.18-system-01", + "date": "2026-04-18", + "summary": "补充订单储位分配接口文档:order.storageAllocation.allocateStorage", + "methods": [ + "order.storageAllocation.allocateStorage" + ], + "notes": [ + "新增 order.storageAllocation.allocateStorage:按订单批量分配储位,支持多种入参别名(order_ids/ids/orderId 等)与仓库上下文优先级。", + "响应包含 requested_order_ids, pending_order_ids, allocated_order_ids, shortage_order_ids, skipped_orders, picking_count, stock_lock_summary, storage_lock_summary 等字段,用于前端展示分配结果与不足提示。" + ], + "type": "added" + }, + { + "version": "2026.04.18-system-02", + "date": "2026-04-18", + "summary": "新增 order.pendingOrder.allocateExpressCode:待处理订单模块的批量分配首单快递号(异步接口),复用 express.createWaybillCodePipeline。", + "methods": [ + "order.pendingOrder.allocateExpressCode" + ], + "notes": [ + "异步接口:调用后立即返回 task_id,后台执行运单创建,通过 allocateExpressCodeTaskProgress 查询进度。", + "入参为 ids(订单 ID 数组),sys_platform_code/logistics_code 等由后端从数据库读取。", + "拆单场景请使用 order.pendingOrder.allocateSubOrderNumber。" + ], + "type": "added" + }, + { + "version": "2026.04.18-system-03", + "date": "2026-04-18", + "summary": "将 order.storageAllocation.allocateStorage 迁移到 order.pendingOrder.allocateStorage,并移除原有公开分组。", + "methods": [ + "order.pendingOrder.allocateStorage" + ], + "notes": [ + "将对外入口从 order.storageAllocation.allocateStorage 迁移到 order.pendingOrder.allocateStorage,旧的 order.storageAllocation 分组已从 methods/system.json 中移除。", + "新的对外接口不接受 warehouse_id / warehouseId,仓库上下文由当前登录用户(ctx.user.store_id)提供。", + "本次变更仅同步文档位置与对外方法名,底层实现保留且通过新的 system 方法暴露。" + ], + "type": "changed" + }, + { + "version": "2026.04.19-system-02", + "date": "2026-04-19", + "summary": "新增待处理模块取消分配储位接口 order.pendingOrder.cancelAllocateStorage", + "methods": [ + "order.pendingOrder.cancelAllocateStorage" + ], + "notes": [ + "新增待处理模块取消分配储位接口 `order.pendingOrder.cancelAllocateStorage`,直接对接 `service.systems.orderStorageAllocation.cancelAllocateStorage` 实现。", + "接口现在仅接受订单ID(order_ids),不再接受 allow_storage_location;禁止传入 `warehouse_id/warehouseId`,仓库上下文由当前登录用户的 `store_id` 提供。", + "响应返回标准 { flag, code, message, data } 结构,data 包含取消分配的汇总结果(warehouse_id, requested_order_ids, cancellable_order_ids, skipped_orders, orders, picking_count, storage_unlock_summary, stock_unlock_summary)。" + ], + "type": "added" + }, + { + "version": "2026.04.21-system-01", + "date": "2026-04-21", + "summary": "新增 order.pendingOrder.updateOrderPlatform 方法:批量修改待处理订单平台信息", + "methods": [ + "order.pendingOrder.updateOrderPlatform" + ], + "notes": [ + "通过 code 查找 wms_platform,平台不存在时返回 404 错误。", + "仅操作当前仓库的当前订单表。", + "noNeedRight=true,noNeedAuth=true(isNeedAuth: true 在 spec 中对应权限配置 noNeedAuth=true)。" + ], + "type": "added" + }, + { + "version": "2026.04.21-system-02", + "date": "2026-04-21", + "summary": "新增方法 order.pendingOrder.updateOrderExpress:批量修改待处理订单的快递信息", + "methods": [ + "order.pendingOrder.updateOrderExpress" + ], + "notes": [ + "新增 order.pendingOrder.updateOrderExpress:批量修改待处理订单的快递信息,按 express_code 从仓库快递列表(带缓存)匹配快递项。", + "自定义映射(is_system_setting=true)时,sys_logistics_code/name 写入系统快递编码和名称,logistics_code/name 写入自定义编码和名称;系统快递(is_system_setting=false)时四个字段均写系统快递的 code/name。", + "只操作当前仓库的当前订单表,不处理其他订单表;操作后写入操作日志(ORDER_UPDATE_EXPRESS)。" + ], + "type": "added" + }, + { + "version": "2026.04.21-system-03", + "date": "2026-04-21", + "summary": "新增 order.expectionOrder.resolveException:将待处理异常订单转回正常待处理状态", + "methods": [ + "order.expectionOrder.resolveException" + ], + "notes": [ + "新增 order.expectionOrder.resolveException:批量将 step=3 的异常订单恢复为 step=2 正常待处理状态。", + "入参 ids 为订单ID 正整数数组,不能为空;仅操作当前仓库当前订单表。", + "返回 updated_count(实际更新行数)与 ids(本次操作ID列表)。", + "权限配置:noNeedLogin=false、noNeedRight=true、noNeedLog=false、noNeedAuth=true" + ], + "type": "added" + }, + { + "version": "2026.04.21-system-04", + "date": "2026-04-21", + "summary": "新增 order.pendingOrder.cloneOrder 方法:克隆待处理订单", + "methods": [ + "order.pendingOrder.cloneOrder" + ], + "notes": [ + "支持对 step 0/1/2/3 的待处理订单进行克隆操作。", + "若原订单已分配储位(storage_status=fin),克隆前自动清除已分配库存。", + "原订单取消后(step→9, status→cancel),以原订单业务数据创建新订单,流程状态字段全部重置为初始落库状态。", + "克隆订单明细含 stock_id,新订单 ID 重新绑定。", + "noNeedAuth=true,noNeedRight=true,noNeedLogin=false。" + ], + "type": "added" + }, + { + "version": "2026.04.21-system-06", + "date": "2026-04-21", + "summary": "新增 order.pendingOrder.createOrder:手动创建待处理/待审核订单", + "methods": [ + "order.pendingOrder.createOrder" + ], + "notes": [ + "新增 order.pendingOrder.createOrder:手动创建订单,step 由货主策略 need_order_approval 决定(1→待审核 step=0,0→待处理 step=1)。", + "必填字段:store_id、name、mobile/tel 至少一项、detail_address、items[](含 item_code 和 plan_qty)。", + "delivery_order_code 不传则自动生成(SYS+时间戳+随机4位);logistics_code/sys_platform_code 不传则读货主合约策略 default_express_code/default_platform_code。", + "不做库存锁定,储位分配为独立步骤。操作日志写入 ORDER_CREATE。", + "noNeedRight=true,noNeedAuth=true,noNeedLogin=false。" + ], + "type": "added" + }, + { + "version": "2026.04.21-system-07", + "date": "2026-04-21", + "summary": "新增 Excel 模板下载与批量导入创建订单接口:order.pendingOrder.downloadCreateTemplate 和 order.pendingOrder.importOrdersFromExcel", + "methods": [ + "order.pendingOrder.downloadCreateTemplate", + "order.pendingOrder.importOrdersFromExcel" + ], + "notes": [ + "新增 order.pendingOrder.downloadCreateTemplate:生成 Excel 导入模板,返回 base64 编码的 xlsx 文件,表头中带 * 的列为必填项(橙色背景),可选列为灰色背景,含示例数据行和填写说明工作表。", + "新增 order.pendingOrder.importOrdersFromExcel:接受 base64 编码的 xlsx 文件,按订单号分组,每组调用 createOrder 逻辑创建订单;不中断执行,逐条记录成功/失败结果返回。", + "多行相同订单号的行组成一个完整订单,每行代表一条商品明细;订单头信息(收件人、地址等)取每组第一行。", + "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" + }, + { + "version": "2026.05.08-system-05", + "date": "2026-05-08", + "summary": "order.wave.batchList:新增 source 字段并支持 where.source 过滤,返回 list item 中新增 source 字段", + "methods": [ + "order.wave.batchList" + ], + "notes": [ + "新增 where.source(可选,number)用于按来源过滤:0=普通波次(正常后台操作),1=管理后台策略任务,2=PDA策略任务;不传则不过滤。", + "响应 list 每条记录新增字段 source(number),用于区分波次来源。", + "仅更新文档,业务代码不在此变更范围。" + ], + "type": "updated" + }, + { + "version": "2026.05.09-system-01", + "date": "2026-05-09", + "summary": "新增 order.wave.wavePickTaskCancelSelf;order.wave.waveStrategyList 新增预演计数字段/参数", + "methods": [ + "order.wave.wavePickTaskCancelSelf", + "order.wave.waveStrategyList" + ], + "notes": [ + "新增接口 `order.wave.wavePickTaskCancelSelf`:仅支持单个 `task_id`(number,必填),明确不支持 `task_ids` 批量参数。", + "业务约束:仅允许取消当前登录用户本人创建的拣货任务;若尝试取消非本人创建任务,接口应返回 400 错误(仅允许取消本人创建任务)。", + "返回建议:与现有取消接口风格一致,包含 `cancelled_count`(0/1)、`task_id`、`task_no`(若后端返回)或相应的取消结果汇总。", + "错误码建议:400 参数不合法(task_id 缺失或传了 task_ids);400 仅允许取消本人创建任务;500 取消失败。", + "新增参数:calculate_next_fetch_order_count(number,可选),含别名 calculateNextFetchOrderCount;取值 0=不计算(默认),1=计算并返回每条策略的 next_fetch_order_count,用于前端在策略列表中预览抓取量。", + "新增响应字段:list[*].next_fetch_order_count(number),含义:按当前策略口径预演一次自动抓取时,预计会选中的订单数量;当未开启计算时返回 0。" + ], + "type": "added" + }, + { + "version": "2026.05.11-system-01", + "date": "2026-05-11", + "summary": "新增字段 wave_prefix(策略层波次前缀),并补充 PDA 抓取波次号生成行为说明", + "methods": [ + "order.wave.waveStrategyList", + "order.wave.waveStrategyCreate", + "order.wave.waveStrategyUpdate", + "order.wave.waveStrategyFetchPda" + ], + "notes": [ + "在 wave strategy 对象中新增可选字段 wave_prefix:策略波次前缀,优先于仓库前缀。", + "校验规则:长度 1-5,仅允许 A-Z0-9;保存时会转为大写;为空时回退仓库前缀:团购使用 group_wave_prefix,散单使用 delete_order_wave_prefix。", + "在 order.wave.waveStrategyList 的返回 list[*] 中新增字段 wave_prefix(string)。", + "在 order.wave.waveStrategyCreate / waveStrategyUpdate 的入参中新增可选字段 wave_prefix(string),创建/更新成功后保存为大写且触发策略版本推进。", + "在 order.wave.waveStrategyFetchPda 的行为说明中补充:生成波次号(wave_no)时优先使用策略层 wave_prefix,否则按策略类型回退到仓库前缀;前缀校验同上。" + ], + "type": "updated" + }, + { + "version": "2026.05.15-system-01", + "date": "2026-05-15", + "summary": "仅更新文档:将 setting.express.create 入参与实现对齐(新增 express_code,移除 platform)", + "methods": [ + "setting.express.create" + ], + "notes": [ + "仅同步文档,与实现对齐,未修改任何业务代码或行为" + ], + "type": "updated" + }, + { + "version": "2026.05.15-system-02", + "date": "2026-05-15", + "summary": "新增 storage.report.search:库存流水统计报表,支持按时间闭区间过滤与按库位/按商品聚合", + "methods": [ + "storage.report.search" + ], + "notes": [ + "方法新增:storage.report.search", + "时间过滤为闭区间:created_at >= start_time 且 created_at <= end_time", + "当 where.by_space 为 false(默认)时,按商品+货主聚合(多个库位汇总);当为 true 时按商品+库位返回", + "不返回无流水的商品/键(仅返回在查询区间内出现过流水的数据)" + ], + "type": "added" + }, + { + "version": "2026.05.15-system-03", + "date": "2026-05-15", + "summary": "库存报表模块主入口迁移到 stock.report.search,storage.report.search 保持兼容别名", + "methods": [ + "stock.report.search", + "storage.report.search" + ], + "notes": [ + "新增主入口方法 stock.report.search,沿用既有报表统计口径(时间闭区间、by_space/store_ids、返回字段保持一致)。", + "保留 storage.report.search 作为兼容别名,并在描述中明确建议迁移到 stock.report.search。", + "仅更新 methods 文档配置,不修改业务代码。" + ], + "type": "updated" + }, + { + "version": "2026.05.15-system-04", + "date": "2026-05-15", + "summary": "文档主入口统一为 stock.report.search,storage.report.search 调整为兼容别名简述", + "methods": [ + "stock.report.search", + "storage.report.search" + ], + "notes": [ + "保留 stock.report.search 作为库存报表唯一完整文档入口。", + "storage.report.search 不再维护完整重复字段,仅保留迁移与兼容说明。", + "仅更新 methods 文档配置,不修改业务代码。" + ], + "type": "updated" + }, + { + "version": "2026.05.15-system-05", + "date": "2026-05-15", + "summary": "拆分 storage.report 模块并移除错误 stock.report.search 文档入口", + "methods": [ + "storage.report.search", + "stock.report.search" + ], + "notes": [ + "将库存报表从 storage.inventory 中拆分为独立模块 storage.report,storage.report.search 文档改为主入口语义(不再作为兼容别名)。", + "从 storage.inventory 分组中移除错误的 stock.report.search 文档入口以及兼容别名条目 storage.report.search。", + "最终归属:storage.report.search 属于模块 storage.report;stock.report.search 的文档入口已移除以避免混淆(代码实现保留于 app/service/systemMethods/storage/report.js 的 storage.report.search)。", + "仅修改文档,不修改应用代码实现。" + ], + "type": "updated" + }, + { + "version": "2026.05.15-system-06", + "date": "2026-05-15", + "summary": "storage.report.search 新增排序能力文档说明", + "methods": [ + "storage.report.search" + ], + "notes": [ + "补充 sort 参数:支持 sortField/sort_field、sortOrder/sort_order。", + "补充排序白名单:begin_total、inbound_total、outbound_total、end_total。", + "补充非法排序字段/顺序回退默认排序说明。", + "响应说明补充:已按 sort 规则排序返回。" + ], + "type": "updated" + }, + { + "version": "2026.05.16-system-01", + "date": "2026-05-16", + "summary": "新增 storage.report.export:按与 storage.report.search 相同条件导出库存报表 Excel", + "methods": [ + "storage.report.export" + ], + "notes": [ + "新增方法:storage.report.export,复用 storage.report.search 的 where/sort 查询条件。", + "导出文件包含两个 sheet:汇总、变更记录。", + "用于在统计结果基础上回溯明细流水,提升库存变动追溯效率。" + ], + "type": "added" + }, + { + "version": "2026.05.16-system-02", + "date": "2026-05-16", + "summary": "storage.report.export 改为异步任务 + 新增 exportTaskProgress", + "methods": [ + "storage.report.export", + "storage.report.exportTaskProgress" + ], + "notes": [ + "调用方式调整为两步:先调用 storage.report.export 提交任务并获取 task_id,再调用 storage.report.exportTaskProgress 轮询任务进度。", + "下载链接获取方式:当 status=success 时,从 exportTaskProgress 响应的 download_url 字段获取导出文件地址。", + "任务状态值补充:submitted/running/success/failed/not_found。" + ], + "type": "updated" + }, + { + "version": "2026.05.16-system-03", + "date": "2026.05.16", + "summary": "同步 setting.expressInterface.create/update 入参与系统快递编码映射规则", + "methods": [ + "setting.expressInterface.create", + "setting.expressInterface.update" + ], + "notes": [ + "补充入参:sys_express_code、weight_type、address、town_name、ispickup、shipperno,并保留既有字段。", + "在参数说明补充 camelCase 别名支持:sysExpressCode、weightType、townName、isPickup、shipperNo 等。", + "同步约束变化:不再因同仓快递编码重复或平台重复直接返回 409;当 express_code 无法匹配系统快递编码时返回 400,文案为 express_code 未匹配到系统快递编码。" + ], + "type": "updated" + }, + { + "version": "2026.05.17-system-05", + "date": "2026-05-17", + "summary": "同步 storage.receiving.addDetail 的参数与返回值(从实现提取)", + "methods": [ + "storage.receiving.addDetail" + ], + "notes": [ + "补充 receiving_id 入参说明", + "补充返回的 details 数组与 selectId 字段", + "补充可能的错误码:404/400/500" + ], + "type": "updated" + }, + { + "version": "2026.05.17-system-06", + "date": "2026-05-17", + "summary": "重新同步 addDetail 文档", + "methods": [ + "storage.receiving.addDetail" + ], + "notes": [ + "再次从实现代码核对并补充参数/返回值/错误码,确保文档与实现一致", + "仅同步文档,不修改业务代码" + ], + "type": "updated" + }, + { + "version": "2026.05.17-system-07", + "date": "2026-05-17", + "summary": "addDetail 新增可选 item 入参并兼容空白创建链路", + "methods": [ + "storage.receiving.addDetail" + ], + "notes": [ + "item 有值时按传入字段创建(服务端覆盖 receiving_id 与 creator_id)", + "兼容不传 item 的空白创建链路;item.children 需覆盖关键字段(有则写、无则补齐)。" + ], + "type": "updated" + }, + { + "version": "2026.05.17-system-10", + "date": "2026-05-17", + "summary": "调整 storage.receiving.getReceivingDetail 库位字段输出语义:space_id 改为展示名称并补充兼容字段", + "methods": [ + "storage.receiving.getReceivingDetail" + ], + "notes": [ + "将 receiving.details.*.space_id 定义为展示名称(string|null),优先 custom_space_name,其次 space_name,不再作为原始数值ID文档语义。", + "新增并明确 receiving.details.*.space_id_raw(number|null)用于保留原始库位ID,兼容旧调用方。", + "补充 receiving.details.*.space_name(库位名称/编码)与 receiving.details.*.custom_space_name(自定义名称,可空)字段说明。" + ], + "type": "updated" + }, + { + "version": "2026.05.17-system-11", + "date": "2026-05-17", + "summary": "补充 subject_config.enable_external_express_code 字段文档与默认值语义", + "methods": [ + "store.createStore", + "store.createWarehouse", + "setting.warehouse.getSettings", + "setting.warehouse.saveSettings" + ], + "notes": [ + "在 store.createStore 与 store.createWarehouse 的 subject_config 入参中新增字段:enable_external_express_code(boolean),默认 false;开启后允许按外部系统传入的快递编码进行处理(如无匹配仍以业务校验为准)。", + "此 change 同时用于说明将在 setting.warehouse.getSettings / saveSettings 中补充该字段的文档说明(后续 doc-only 写入)。" + ], + "type": "updated", + "module": "store" + }, + { + "version": "2026.05.17-system-12", + "date": "2026-05-17", + "summary": "storeWarehouse.store 策略配置文档新增 enable_external_express_code 字段说明(向后兼容)", + "methods": [ + "storeWarehouse.store.getPolicyConfig", + "storeWarehouse.store.savePolicyConfig" + ], + "notes": [ + "在 getPolicyConfig / savePolicyConfig 的出参说明中补充 data.policy_config.enable_external_express_code 字段,明确为 flag(0=关闭,1=开启),默认 0。", + "在 savePolicyConfig 的入参说明中补充 policy_config.enable_external_express_code 字段定义。", + "本次为向后兼容的文档增强:新增可选策略字段说明,不影响现有调用。" + ], + "type": "updated" + }, + { + "version": "2026.05.19-system-01", + "date": "2026-05-19", + "summary": "补充 storage.entry.list 的 expense_record 筛选语义与未迁移环境错误提示", + "methods": [ + "storage.entry.list" + ], + "notes": [ + "在 where 参数说明中补充 expense_record 字段语义(费用是否记录)及 eq/in 支持。", + "明确 true/false、1/0、y/n、yes/no 的归一化规则与等价写法示例。", + "补充未完成表结构迁移时可能返回 400 及错误提示文案。" + ], + "type": "updated" + }, + { + "version": "2026.05.20-system-01", + "date": "2026-05-20", + "summary": "同步 order.recheckOrder.scanOrder 返回结构,补充 cart_match_view 语义化视图说明", + "methods": [ + "order.recheckOrder.scanOrder" + ], + "notes": [ + "新增返回字段:match_type(waybill/cart)与 cart_match_view(仅 cart 命中返回)。", + "cart_match_view 包含通用子字段:mode_code / mode_name / view_type / task;当车号命中时按 pick_mode 返回语义化结构:mode 1/5 返回 groups,mode 2 返回 orders,mode 3 返回 pick_groups,mode 4 返回 box_groups。" + ], + "type": "updated" + }, + { + "version": "2026.05.22-system-01", + "date": "2026-05-22", + "summary": "新增 index.getPlatformOauthLink 文档,补充平台授权链接接口说明", + "methods": [ + "index.getPlatformOauthLink" + ], + "notes": [ + "入参支持 code、platform_code、platformCode 三种平台编码字段别名。", + "当前仅支持 PDD;成功返回 data.platform_code、data.oauth_link 和 code=200,其他平台返回 code=400。", + "仅通过文档脚本同步 methods/system.json 与 methods/changes/system.json,不修改业务代码。" + ], + "type": "added", + "module": "index" + }, + { + "version": "2026.05.22-system-02", + "date": "2026-05-22", + "summary": "更新 index.getPlatformOauthLink 文档,补充仓库上下文、预占记录与错误说明", + "methods": [ + "index.getPlatformOauthLink" + ], + "notes": [ + "补充真实行为:从 ctx.user.store_id 读取当前仓库 ID,从 wms_platform.auth_base_url 读取授权基础地址,并在 wms_shops 创建平台授权预占记录。", + "补充 oauth_link 细节:追加 client_id、redirect_uri(配置非空时)以及长查询参数 wms_authorization_reservation_code,对应唯一 auth_random_code。", + "补充常见错误:平台编码为空、仓库上下文缺失、平台不存在、授权基础地址缺失/格式错误、不支持的平台,以及预占记录创建失败。" + ], + "type": "updated", + "module": "index" + }, + { + "version": "2026.05.22-system-03", + "date": "2026-05-22", + "summary": "同步 index.getPlatformOauthLink 当前实现:裸码入库与 state 拼接规则", + "methods": [ + "index.getPlatformOauthLink" + ], + "notes": [ + "补充真实行为:从 ctx.user.store_id 读取当前仓库,从 wms_platform.auth_base_url 读取基础授权链接,并优先复用 wms_shops 中 status=0 的未授权记录。", + "明确 auth_random_code 当前以裸码保存;若复用到历史带前缀记录,会先去掉 platformOauthReservationCodePrefix 后再回写。", + "更新 oauth_link 说明:state 由“前缀 + 平台编码 + '_' + 裸码”组成并整体 URL 编码后直接拼接到基础授权链接后,例如 xxxxx_PDD_;同时移除已不存在的基础地址格式错误/不支持平台错误描述。" + ], + "type": "updated", + "module": "index" + }, + { + "version": "2026.05.22-system-04", + "date": "2026-05-22", + "summary": "修正 index.getPlatformOauthLink 文档中的残留平台限制描述", + "methods": [ + "index.getPlatformOauthLink" + ], + "notes": [ + "移除 index.getPlatformOauthLink 参数与返回字段中残留的“当前仅支持 PDD”描述,避免与当前实现不一致。", + "保留授权链接仅依赖平台已配置基础授权链接模式的说明,不再把示例平台编码误写成实现限制。" + ], + "type": "updated", + "module": "index" + }, + { + "version": "2026.05.22-system-05", + "date": "2026-05-22", + "summary": "新增 index.getShopList 文档,并同步 custom_name 与店铺列表脱敏返回规则", + "methods": [ + "index.getShopList" + ], + "notes": [ + "新增 index.getShopList:接口依赖当前登录仓库上下文 ctx.user.store_id,不接受额外业务入参,缺少仓库时返回 400:未识别到当前仓库。", + "补充真实返回结构:data.list 为数组,包含 id、warehouse_id、platform_code、shop_name、custom_name、status、auth_expire_at、token_expires_at、refresh_token_expires_at、scope、created_at、updated_at 以及脱敏后的 owner_id、access_token、refresh_token、auth_random_code。", + "同步脱敏规则:owner_id 非空且长度大于 5 时返回前 3 位 + *** + 后 2 位,长度小于等于 5 时返回 ***;access_token、refresh_token、auth_random_code 非空时固定返回 ***,空值返回 null。", + "仅通过文档脚本同步 methods/system.json 与 methods/changes/system.json,不修改任何业务代码。" + ], + "type": "added", + "module": "index" + }, + { + "version": "2026.05.22-system-06", + "date": "2026-05-22", + "summary": "新增 index.getShopExpressList 文档,补充店铺快递列表统一返回结构", + "methods": [ + "index.getShopExpressList" + ], + "notes": [ + "按 ctx.user.store_id 校验店铺归属,仅允许查询当前登录仓库下的店铺。", + "服务端按店铺所属平台拉取并收敛快递签约/电子面单可用列表,统一返回前端消费结构。", + "未接入平台当前返回空列表;若店铺缺少授权 access_token,则返回 400:店铺未授权。", + "仅文档同步,不改业务代码。" + ], + "type": "added", + "module": "index" + }, + { + "version": "2026.05.22-system-07", + "date": "2026-05-22", + "summary": "同步快递接口文档:is_share 仅展示不可编辑", + "methods": [ + "setting.expressInterface.list", + "setting.expressInterface.create", + "setting.expressInterface.update" + ], + "notes": [ + "create/update 不再接受 is_share", + "list 仍可返回 is_share 作为展示信息", + "仅文档同步,不改业务代码" + ], + "type": "updated", + "module": "setting.expressInterface" + }, + { + "version": "2026.05.22-system-08", + "date": "2026-05-22", + "summary": "同步快递接口列表文档,移除未返回字段说明", + "methods": [ + "setting.expressInterface.list" + ], + "notes": [ + "根据 app/service/systems/setting/expressInterface.js 的 list() 查询字段与 normalizeInterfaceRow() 返回结构,同步 setting.expressInterface.list 不返回 token。", + "按当前实现清理 response.children 中未返回的 share_id、can_use_count 字段说明。", + "保留 is_share,并明确其仅用于展示,不作为编辑入参。" + ], + "type": "updated", + "module": "setting.expressInterface" + }, + { + "version": "2026.05.22-system-09", + "date": "2026-05-22", + "summary": "index.getShopList 支持按平台编码筛选店铺", + "methods": [ + "index.getShopList" + ], + "notes": [ + "index.getShopList 兼容 platform_code 与 platformCode 两种传参方式,服务端按 platform_code、platformCode 顺序读取首个 trim 后非空值作为平台筛选条件。", + "未传平台参数时返回当前登录仓库下全部已授权店铺;传入非空平台编码时仅返回该平台的已授权店铺。", + "本次仅补充筛选条件文档,不影响返回结构、排序规则与 owner_id/access_token/refresh_token/auth_random_code 的脱敏规则。", + "仅通过文档脚本同步 methods/system.json 与 methods/changes/system.json,不修改任何业务代码。" + ], + "type": "updated", + "module": "index" + }, + { + "version": "2026.05.22-system-10", + "date": "2026-05-22", + "summary": "快递接口配置新增 shop_id 字段", + "methods": [ + "setting.expressInterface.create", + "setting.expressInterface.update", + "setting.expressInterface.list" + ], + "notes": [ + "create/update 支持 shop_id/shopId(兼容 snake_case 与 camelCase),为店铺 ID,未传或空值按 null 处理。", + "list 返回 shop_id 字段,列表 where 支持按 shop_id 过滤。" + ], + "type": "updated" + }, + { + "version": "2026.05.22-system-11", + "date": "2026-05-22", + "summary": "调整快递接口列表排序规则", + "methods": [ + "setting.expressInterface.list" + ], + "notes": [ + "setting.expressInterface.list 改为按 weight ASC, id DESC 排序;优先按权重排序,权重相同再按 id 倒序。", + "本次仅同步该接口排序说明,不影响返回结构。" + ], + "type": "updated", + "module": "setting.expressInterface" + }, + { + "version": "2026.05.22-system-12", + "date": "2026-05-22", + "summary": "index.getShopExpressList 返回新增系统快递编码", + "methods": [ + "index.getShopExpressList" + ], + "notes": [ + "data.list[*] 新增 sys_express_code 字段,由平台快递编码 wp_code 映射系统快递编码,未匹配时返回空字符串。", + "补充 data.list[*].wp_name 说明:由系统快递基础表根据平台快递编码映射得到名称,未匹配时返回空字符串。", + "原有请求参数、鉴权方式与返回主结构保持不变。", + "仅文档同步,不改业务代码。" + ], + "type": "updated", + "module": "index" + }, + { + "version": "2026.05.23-system-01", + "date": "2026-05-23", + "summary": "补充快递接口列表 is_system_express_code 返回字段说明", + "methods": [ + "setting.expressInterface.list" + ], + "notes": [ + "在 setting.expressInterface.list 的 response.children 中补充 is_system_express_code 字段说明。", + "该字段表示当前行 express_code 是否为系统快递编码;不是系统快递编码返回 0,否则返回 1。", + "仅文档同步,不改业务代码。" + ], + "type": "updated", + "module": "setting.expressInterface" + }, + { + "version": "2026.05.23-system-02", + "date": "2026-05-23", + "summary": "完善 index.getExpressList 文档:补充过滤规则、返回字段与仓库维度行为", + "methods": [ + "index.getExpressList" + ], + "notes": [ + "补充 `systemOnly`、`express_code`、`expressCode` 的真实入参语义,明确真值识别规则与字段优先级。", + "补充默认模式、系统模式、按快递编码过滤模式下的返回差异,说明当前登录仓库维度来自 `ctx.user.store_id`。", + "补充 `data[*]` 各字段含义,明确系统基础快递与仓库自定义快递编码的差异字段。", + "仅文档同步,不修改业务代码。" + ], + "type": "updated", + "module": "index" + }, + { + "version": "2026.05.24-system-01", + "date": "2026-05-24", + "summary": "同步 index.getExpressList 文档:移除 expressCode 别名并明确 express_code 筛选语义", + "methods": [ + "index.getExpressList" + ], + "notes": [ + "移除 index.getExpressList 文档中的 expressCode 驼峰别名参数,仅保留 express_code。", + "明确当 systemOnly=false 且传入 express_code 时,接口按自定义映射记录中的系统快递编码字段 express_code 过滤,而不是按自定义 code 过滤。", + "保留 systemOnly=true 按系统快递编码过滤系统基础快递列表,以及默认合并逻辑、缓存优先、仓库维度来源不变的说明。" + ], + "type": "updated" + }, + { + "version": "2026.05.24-system-02", + "date": "2026-05-24", + "summary": "新增 index.getCainiaoStfTemplates 接口文档并明确模板返回语义", + "methods": [ + "index.getCainiaoStfTemplates" + ], + "notes": [ + "新增无参接口 index.getCainiaoStfTemplates:从当前仓库首个已授权 TB 店铺发起 cainiao.waybill.ii.search 查询菜鸟 STF 模板。", + "补充返回结构说明:data.platform_code 固定为 TB;data.list 返回模板数组并包含 template_id/template_name/template_url/cp_code/wp_code 字段。", + "明确模板列表为宽松结构解析并按 template_id/template_name/template_url 核心语义去重。", + "补充错误码说明:未识别仓库返回 400;当前仓库无已授权 TB 店铺返回 404。" + ], + "type": "added" + }, + { + "version": "2026.05.24-system-03", + "date": "2026-05-24", + "summary": "调整 index.getCainiaoStfTemplates 为免登录/免鉴权接口", + "methods": [ + "index.getCainiaoStfTemplates" + ], + "notes": [ + "将 index.getCainiaoStfTemplates 的 isNeedLogin 调整为 false,接口改为免登录访问。", + "保持 isNeedAuth=false,并同步免权限拦截配置,避免登录态与鉴权拦截。", + "该接口仍为无请求参数,headers 调整为空数组。" + ], + "type": "updated", + "module": "index" + }, + { + "version": "2026.05.24-system-04", + "date": "2026-05-24", + "summary": "调整 index.getCainiaoStfTemplates 为公共无参模板查询接口", + "methods": [ + "index.getCainiaoStfTemplates" + ], + "notes": [ + "index.getCainiaoStfTemplates 改为公共无参查询,不再依赖当前仓库、登录态或店铺授权。", + "接口直接调用 requestTbWaybillSearch({ cpCode: '' }) 查询公共模板,返回 data.platform_code='TB' 与模板数组。", + "requestTbWaybillSearch 支持 accessToken 缺失时不下发 session,因此该接口不再依赖 session。" + ], + "type": "updated" + }, + { + "version": "2026.05.24-system-05", + "date": "2026-05-24", + "summary": "同步 index.getCainiaoStfTemplates 改用淘宝标准模板公共接口", + "methods": [ + "index.getCainiaoStfTemplates" + ], + "notes": [ + "index.getCainiaoStfTemplates 改为调用淘宝开放平台 cainiao.cloudprint.stdtemplates.get,不再复用 cainiao.waybill.ii.search。", + "接口不需要用户授权,不下发 session,继续使用 https://eco.taobao.com/router/rest 与 TOP 公共签名参数。", + "模板列表改为从 cainiao_cloudprint_stdtemplates_get_response.result.datas[*].standard_templates[*] 做宽松兼容解析,统一返回 template_id/template_name/template_url/cp_code/wp_code。" + ], + "type": "updated" + }, + { + "version": "2026.05.24-system-06", + "date": "2026-05-24", + "summary": "新增 index.getPrintPlatformList 接口文档并明确打印平台下拉返回结构", + "methods": [ + "index.getPrintPlatformList" + ], + "notes": [ + "新增 index.getPrintPlatformList 文档,说明该接口供快递接口新增/编辑页下拉选择使用。", + "补充接口行为:仅返回未删除且状态为 ACTIVE 的打印平台,不分页,按 platform_name 与 id 升序返回。", + "补充 data[*] 返回字段说明,明确 code/name/value/label/platform_code/platform_name/status/remark 的含义。", + "仅文档同步,不修改业务代码。" + ], + "type": "added", + "module": "index" + }, + { + "version": "2026.05.24-system-07", + "date": "2026-05-24", + "summary": "新增 index.getPrintPlatformTemplateList 文档,明确 express_code 必填与模板过滤语义", + "methods": [ + "index.getPrintPlatformTemplateList" + ], + "notes": [ + "新增 index.getPrintPlatformTemplateList 方法文档,补充 platform_code 与 express_code 入参,其中 express_code 标记为必填。", + "明确业务语义:接口按 platform_code(默认 CAINIAO)定位 wms_express 中对应打印平台字段,并使用 express_code 过滤模板结果后返回。", + "补充返回结构 data.platform_code / data.express_code / data.responseData,说明未实现平台返回空对象。", + "仅文档同步,不修改业务代码。" + ], + "type": "added", + "module": "index" + }, + { + "version": "2026.05.25-system-01", + "date": "2026-05-25", + "summary": "新增 index.polyapiAuthorizeUrl 接口文档并标注免登录免鉴权特征", + "methods": [ + "index.polyapiAuthorizeUrl" + ], + "notes": [ + "新增基础模块方法 index.polyapiAuthorizeUrl,说明其为公共无参接口。", + "明确接口固定调用菠萝派 Differ.JH.BuildeAuthorizeUrl,返回体中以 data.respone 原样包裹上游响应。", + "同步标注 isNeedLogin=false、isNeedAuth=false,headers 为空数组。" + ], + "type": "added" + }, + { + "version": "2026.05.25-system-02", + "date": "2026-05-25", + "summary": "新增店铺模块相关接口文档(shops.list/add/del/edit)及授权会话接口 shops.GetAuthorizeSessionKey", + "methods": [ + "shops.list", + "shops.add", + "shops.del", + "shops.edit", + "shops.GetAuthorizeSessionKey" + ], + "notes": [ + "同步实现:shops.list 支持 where 分页与 quickWhere 快速搜索;shops.add/edit 校验 platform_code 存在且为 ACTIVE,custom_name 必填且长度限制;shops.del 为软删除,会返回 deleted=true 并清空敏感字段,若存在快递接口引用返回 409;shops.GetAuthorizeSessionKey 对 PDD/CAINIAO 平台生成预占码并返回 authorize_url,其他平台返回 501。", + "字段命名兼容说明:接口实现兼容 snake_case 与 camelCase 入参,文档以 snake_case 为主并注明兼容性。" + ], + "type": "added" + }, + { + "version": "2026.05.25-system-03", + "date": "2026-05-25", + "summary": "同步 shops.add 去入参化:移除 shop_name 入参并明确由授权后获取店铺名称", + "methods": [ + "shops.add" + ], + "notes": [ + "shops.add 入参移除 shop_name(及同义传参语义),仅保留 custom_name 与 platform_code 为关键请求字段。", + "补充说明:新增时 shop_name 由服务端生成 PENDING_* 占位名,后续以授权回调同步真实店铺名称。", + "仅文档同步,不修改任何业务代码。" + ], + "type": "updated", + "module": "shops" + }, + { + "version": "2026.05.28-system-02", + "date": "2026-05-28", + "summary": "新增 method: order.print.unlockWavePlatformPrintDataByGroup,按分组解锁波次平台打印锁", + "methods": [ + "order.print.unlockWavePlatformPrintDataByGroup" + ], + "notes": [ + "新增方法:order.print.unlockWavePlatformPrintDataByGroup,用于按分组规则批量解锁波次内被锁定的订单(将 print_lock_status 设为 'none')。", + "入参说明:group_type 默认为 platform_express(支持 platform、platform_express、order),unlock_scope 默认为 group(支持 group、wave);groups 为必须项,元素对象可包含 wave_id、platform、sys_logistics_code、order_ids 等字段。", + "返回说明:返回 summary(解锁统计)、unlocked_order_ids、unlocked_orders、ext.missing_wave_ids、ext.filtered_wave_ids 等字段。", + "实现参考:app/service/systemMethods/order/print.js 与 app/service/systems/order_print.js 的 unlockWavePlatformPrintDataByGroup 实现,相关单元测试位于 test/app/controller/system.order.print.unlockByGroup.test.js 与 test/app/service/systems/order_print.unlockWavePlatformPrintDataByGroup.test.js。" + ], + "type": "updated" + }, + { + "version": "2026.05.28-system-03", + "date": "2026-05-28", + "summary": "新增 order.updateExpressWeighingWeight 方法文档并补充单/多运单称重写入规则", + "methods": [ + "order.updateExpressWeighingWeight" + ], + "notes": [ + "新增 order.updateExpressWeighingWeight 入参说明:order_id、waybill_code、weighing_weight。", + "明确规则:单运单订单忽略 waybill_code 并直接更新唯一运单;多运单订单必须传 waybill_code 且需匹配订单下运单。", + "补充成功返回字段:order_id、waybill_code、weighing_weight。", + "补充错误码:400(参数校验与多运单缺失运单号)、404(运单记录不存在或未匹配)、500(模型未初始化或更新失败)。", + "仅通过文档脚本同步 methods/system.json 与 methods/changes/system.json,不修改业务代码。" + ], + "type": "added", + "module": "order.index" + }, + { + "version": "2026.05.28-system-01", + "date": "2026-05-28", + "summary": "新增包材相关 methods(create/update/delete/get),并提供 list 兼容说明", + "methods": [ + "setting.packageMaterial.create", + "setting.packageMaterial.update", + "setting.packageMaterial.delete", + "setting.packageMaterial.get", + "setting.packageMaterial.list" + ], + "notes": [ + "实现参考:app/service/systems/setting/packageMaterial.js", + "list 为兼容别名,内部转发至 get,建议新接入方改用 get" + ], + "type": "updated" + }, + { + "version": "2026.05.28-system-04", + "date": "2026-05-28", + "summary": "Add packageSupplier methods (create/update/delete/get) with list alias note", + "methods": [ + "setting.packageSupplier.create", + "setting.packageSupplier.update", + "setting.packageSupplier.delete", + "setting.packageSupplier.get", + "setting.packageSupplier.list" + ], + "notes": [ + "Reference implementation: app/service/systems/setting/packageSupplier.js", + "list is a compatibility alias; prefer get" + ], + "type": "updated" + }, + { + "version": "2026.05.28-system-05", + "date": "2026-05-28", + "summary": "新增 order.bindExpressPackageMaterial 方法文档,支持按订单运单绑定包材", + "methods": [ + "order.bindExpressPackageMaterial" + ], + "notes": [ + "新增 order.bindExpressPackageMaterial 入参说明:order_id、waybill_code、package_material_code(均必填)。", + "补充行为说明:按订单ID+运单号匹配 wms_order_express,按包材编码匹配包材并绑定 package_material_id 与 package_material_name_snapshot。", + "补充成功返回字段:order_id、waybill_code、package_material_id、package_material_name_snapshot、package_material_code。", + "补充错误码:400 参数错误、404 包材编码不存在、404 订单运单记录不存在、500 绑定包材失败。", + "仅通过文档脚本同步 methods/system.json 与 methods/changes/system.json,不修改业务代码。" + ], + "type": "added", + "module": "order.index" + }, + { + "version": "2026.05.29-system-01", + "date": "2026-05-29", + "summary": "新增 order.export 与 order.exportTaskProgress:订单导出异步任务与进度查询", + "methods": [ + "order.export", + "order.exportTaskProgress" + ], + "notes": [ + "order.export:提交导出任务,入参支持 table_type/tableType(枚举 current/history/dispatch/outsourced,兼容订单模块别名)与 module/module_name,where/sort 语义与 order.list 一致。接口提交后立即返回 task_id,后台异步执行导出,导出进度与结果通过 order.exportTaskProgress 查询。", + "order.exportTaskProgress:按 task_id 查询任务进度,返回 task_id、status、progress、current_count、total_count、message、error、download_url、update_time;任务上传完成后 download_url 返回可下载链接,未找到时 status=not_found。" + ], + "type": "added", + "module": "order.index" + }, + { + "version": "2026.05.30-system-01", + "date": "2026-05-30", + "summary": "新增 print.notifyLock(及 notify_lock 兼容别名),并补充 print.send 写入订单操作日志的行为说明", + "methods": [ + "print.notifyLock", + "print.notify_lock", + "print.send" + ], + "notes": [ + "新增 print.notifyLock:入参支持 order_ids/orderIds、waveGroups、data.waveGroups(至少一类提供订单 ID);仅执行订单锁定流程,不发送打印任务;写打印任务日志 + 订单操作日志;返回 locked_count、order_ids_count、order_ids、source;错误:无有效订单ID(400)、锁定失败(500)。", + "补充 print.send 文档:说明接口在执行打印任务记录的同时会写入订单操作日志(记录打印相关操作)。", + "新增兼容别名 print.notify_lock:文档说明等价转调到 print.notifyLock。" + ], + "type": "updated", + "module": "print" + }, + { + "version": "2026.06.03-system-01", + "date": "2026-06-03", + "summary": "同步 pick.query 文档为 keyword 任务化语义并补充冲突错误码", + "methods": [ + "pick.query" + ], + "notes": [ + "入参由 waybill_code/full_display 统一为 keyword(支持运单号或波次号)。", + "成功返回调整为 task_id/status/tip,status 取值 existing 或 created。", + "补充 409 冲突语义:波次已有他人活动任务时返回任务归属信息。" + ], + "type": "updated" + }, + { + "version": "2026.06.03-system-02", + "date": "2026-06-03", + "summary": "更新 pick.wavePickTaskDetail:增加快递号/储位分配前置校验并返回 action+order_ids", + "methods": [ + "pick.wavePickTaskDetail" + ], + "notes": [ + "新增前置校验:任务内若存在未分配快递号订单,返回 400,data.action=assign_express,data.order_ids 为未分配订单ID列表。", + "新增前置校验:任务内若存在未分配储位订单,返回 400,data.action=assign_storage,data.order_ids 为未分配订单ID列表。", + "保留原有权限校验与详情结构,仅补充分配校验失败分支的返回约定。" + ], + "type": "updated" + }, + { + "version": "2026.06.03-system-03", + "date": "2026-06-03", + "summary": "更新 order.wave.batchList:新增同步状态输出与筛选 sync_assignment_status", + "methods": [ + "order.wave.batchList" + ], + "notes": [ + "新增返回字段语义:list[].sync_assignment_status,取值为未同步/部分同步/已同步/同步异常。", + "新增筛选入参 where.sync_assignment_status,支持 unsynced/partially_synced/synced 英文枚举。", + "同步状态筛选规则与分配状态一致:error 并入 unsynced 过滤集合。" + ], + "type": "updated" + }, + { + "version": "2026.06.03-system-04", + "date": "2026-06-03", + "summary": "更新拣货中间态流程文档:wavePickTaskDetail 增加完成标记,并新增中间态/完全提交接口", + "methods": [ + "pick.wavePickTaskDetail", + "pick.wavePickTaskSubmit", + "pick.wavePickTaskComplete" + ], + "notes": [ + "更新 pick.wavePickTaskDetail 返回:新增 task.is_completed、task.progress(total_orders/picked_orders/pending_orders)以及顶层 is_completed。", + "新增 pick.wavePickTaskSubmit:支持保存中间态 payload 到任务 ext_json.pick_intermediate,并返回当前完成状态与进度。", + "新增 pick.wavePickTaskComplete:支持 mode=1 全部确认与 mode=2 部分确认(order_ids),返回 confirmed_order_ids 与最新进度。" + ], + "type": "updated" + }, + { + "version": "2026.06.03-system-05", + "date": "2026-06-03", + "summary": "拣货车能力拆分为一级模块 pickCart:扫码查询、任务绑车、CRUD、编码查重", + "methods": [ + "pickCart.scan", + "pickCart.bindTaskCart", + "pickCart.create", + "pickCart.update", + "pickCart.delete", + "pickCart.detail", + "pickCart.list", + "pickCart.codeDuplicateCheck" + ], + "notes": [ + "拣货车能力独立为一级模块 pickCart,不再挂在 pick 模块下。", + "新增 pickCart.scan:PDA 按 cart_code 扫码查询拣货车信息,用于进入任务绑定流程。", + "新增 pickCart.bindTaskCart:支持按 cart_id/cart_code 将拣货车绑定到指定拣货任务,若车已绑定其他活动任务则返回冲突。", + "新增 pickCart.create/pickCart.update/pickCart.delete/pickCart.detail/pickCart.list:补齐拣货车增删查改与分页查询能力。", + "新增 pickCart.codeDuplicateCheck:支持 exclude_cart_id 排除自身,供编辑场景做非自身重复校验;拣货车编码在当前仓库内不可重复。" + ], + "type": "updated" + }, + { + "version": "2026.06.03-system-06", + "date": "2026-06-03", + "summary": "更新 order.wave.batchList:新增 only_todo、复核状态聚合与复核筛选", + "methods": [ + "order.wave.batchList" + ], + "notes": [ + "新增入参 only_todo(默认 0):传 1/true 时仅返回仍有未复核订单的波次(unreviewed_order_count > 0)。", + "新增返回字段:list[].unreviewed_order_count(未复核订单数)与 list[].review_assignment_status(未复核/部分复核/已复核)。", + "新增 where.review_assignment_status 筛选,支持 unreviewed/partially_reviewed/reviewed 英文枚举。" + ], + "type": "updated", + "module": "order.wave" + }, + { + "version": "2026.06.04-system-01", + "date": "2026-06-04", + "summary": "裁剪 pick.wavePickTaskDetail 返回:团购小波次(pick_mode=1)不返回 picking_details 字段以减少带宽", + "methods": [ + "pick.wavePickTaskDetail" + ], + "notes": [ + "在 picking_details 字段 description 中补充:当 pick_mode=1(团购小波次)时该字段不返回,减少带宽浪费;其他 pick_mode(2/3/4/5)正常返回 picking_details。", + "在接口 description 中补充该裁剪行为的说明。", + "picking_summary、picking_view、boxes 等字段不受影响,pick_mode=1 时仍正常返回。" + ], + "type": "updated" + }, + { + "version": "2026.06.04-system-02", + "date": "2026-06-04", + "summary": "完善 index.getPlatformList 文档:补充入参 systemOnly/full、响应字段及错误码 500", + "methods": [ + "index.getPlatformList" + ], + "notes": [ + "补充入参说明:systemOnly(可选,支持 is_system 别名,真值识别 true/1/'1'/'true')、full(可选,真值识别同上,为 true 时返回全量表字段与 route_platform_code/platid 等扩展信息)", + "补充响应 data 数组每项字段:code、name、value、label、platform_code、platform_name、default_express_interface、is_system_setting、id(仅仓库自定义项)、alias(仅仓库自定义项)、full 模式扩展字段说明", + "说明合并逻辑:系统平台在前,仓库自定义在后,同 code 仅保留首条(系统优先);systemOnly=true 仅返回系统平台", + "补充缓存策略:优先读缓存,key 格式为 platform:list:{warehouseId}[:full] 或 platform:list:system[:full]", + "补充错误码 500:数据库或缓存访问异常", + "仅文档更新,不修改任何业务实现" + ], + "type": "updated", + "module": "index" + }, + { + "version": "2026.06.04-system-03", + "date": "2026-06-04", + "summary": "作废 order.pendingOrder.downloadCreateTemplate 和 order.pendingOrder.importOrdersFromExcel", + "methods": [ + "order.pendingOrder.downloadCreateTemplate", + "order.pendingOrder.importOrdersFromExcel" + ], + "notes": [ + "order.pendingOrder.downloadCreateTemplate:下载订单导入模板方法已从代码中移除,标记为 deprecated。", + "order.pendingOrder.importOrdersFromExcel:从 Excel 导入订单方法已从代码中移除,标记为 deprecated。", + "两个方法的文档条目保留在 methods/system.json 中,仅追加 status: 'deprecated' 与 description 中的'(已作废)'标记,未删除。" + ], + "type": "deprecated" + }, + { + "version": "2026.06.05-system-01", + "date": "2026-06-05", + "summary": "新增 storeWarehouse.store.openAccount 接口:仓库代货主一键开户(合并注册账号+创建货主+签约)", + "methods": [ + "storeWarehouse.store.openAccount" + ], + "notes": [ + "新增 storeWarehouse.store.openAccount 方法,归属货主-仓库签约模块(storeWarehouse.store)。", + "接口同时完成账号注册、货主创建和仓库-货主签约,一步完成开户全流程。", + "当前主体必须为仓库角色(Authorization header 中携带的 token 对应仓库用户)。", + "必填参数:username(登录账号)、password(初始密码)、company_name(公司全称)、business_license(营业执照号)、contact_person(联系人)、contact_phone(联系电话)。", + "响应返回新创建的 store_id、account_id、contract_id、company_name、username、role_id。" + ], + "type": "added", + "module": "storeWarehouse" + }, + { + "version": "2026.06.05-system-02", + "date": "2026-06-05", + "summary": "优化 storeWarehouse.store.openAccount 必填参数:password 改为随机生成、business_license 和 contact_phone 改为可选,必填仅剩 username/company_name/contact_person 三个", + "methods": [ + "storeWarehouse.store.openAccount" + ], + "notes": [ + "password:由必填改为可选,不传时自动随机生成 12 位密码", + "business_license:由必填改为可选", + "contact_phone:由必填改为可选" + ], + "type": "updated" + }, + { + "version": "2026.06.05-system-03", + "date": "2026-06-05", + "summary": "saveApiConfig 增加 callback_url 参数,支持配置 API 回调通知地址", + "methods": [ + "storeWarehouse.store.saveApiConfig" + ], + "notes": [ + "新增 callback_url 参数:OpenAPI 类型接口支持配置回调通知 URL", + "兼容别名 callbackUrl,最大 500 字符", + "存入 wms_api_app.callback_url 字段" + ], + "type": "modified" + }, + { + "version": "2026.06.05-system-04", + "date": "2026-06-05", + "summary": "createOrder 入参 item_code 改为 item_id,province/city/area 改为必填", + "methods": [ + "order.pendingOrder.createOrder" + ], + "notes": [ + "items[].item_code → items[].item_id:改用商品主键直接匹配,不依赖外部系统商品推送", + "province/city/area 新增必填校验,空值返回 400", + "item_name 优先外部传入,其次从 StockStore 缓存获取,最后兜底'商品'" + ], + "type": "modified" + }, + { + "version": "2026.06.05-system-05", + "date": "2026-06-05", + "summary": "新增 order.pendingOrder.parseAddress 智能地址解析方法", + "methods": [ + "order.pendingOrder.parseAddress" + ], + "notes": [ + "使用 DeepSeek AI 模型将非结构化地址字符串解析为省/市/区/详细地址/收件人/手机号", + "解析结果可直接用于 createOrder 的 receiverInfo 字段", + "DeepSeek API Key 通过 DEEPSEEK_API_KEY 环境变量配置" + ], + "type": "added" + }, + { + "version": "2026.06.05-system-06", + "date": "2026-06-05", + "summary": "waveStrategyUpdate/waveStrategyCreate 新增 wave_prefix 参数", + "methods": [ + "order.wave.waveStrategyUpdate", + "order.wave.waveStrategyCreate" + ], + "notes": [ + "新增 wave_prefix 波次编号前缀字段,最多 5 个字符,为空存 null" + ], + "type": "modified" + }, + { + "version": "2026.06.05-system-07", + "date": "2026-06-05", + "summary": "parseAddress 响应新增 town 字段(乡镇/街道)", + "methods": [ + "order.pendingOrder.parseAddress" + ], + "notes": [ + "响应 data 中新增 town 字段,返回 AI 解析出的乡镇/街道名称" + ], + "type": "modified" + }, + { + "version": "2026.06.05-system-08", + "date": "2026-06-05", + "summary": "为 order.list 响应新增 recheck_status 字段(复核状态:none=未复核,fin=已复核)", + "methods": [ + "order.list" + ], + "notes": [ + "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" + ], + "type": "updated" + }, + { + "version": "2026.06.05-system-09", + "date": "2026-06-05", + "summary": "为 order.reviewOrder.list 响应新增 recheck_status 字段(复核状态:none=未复核,fin=已复核)", + "methods": [ + "order.reviewOrder.list" + ], + "notes": [ + "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" + ], + "type": "updated" + }, + { + "version": "2026.06.05-system-10", + "date": "2026-06-05", + "summary": "为 order.pendingOrder.list 响应新增 recheck_status 字段(复核状态:none=未复核,fin=已复核)", + "methods": [ + "order.pendingOrder.list" + ], + "notes": [ + "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" + ], + "type": "updated" + }, + { + "version": "2026.06.05-system-11", + "date": "2026-06-05", + "summary": "为 order.outboundOrder.list 响应新增 recheck_status 字段(复核状态:none=未复核,fin=已复核)", + "methods": [ + "order.outboundOrder.list" + ], + "notes": [ + "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" + ], + "type": "updated" + }, + { + "version": "2026.06.05-system-12", + "date": "2026-06-05", + "summary": "为 order.expectionOrder.list 响应新增 recheck_status 字段(复核状态:none=未复核,fin=已复核)", + "methods": [ + "order.expectionOrder.list" + ], + "notes": [ + "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" + ], + "type": "updated" + }, + { + "version": "2026.06.05-system-13", + "date": "2026-06-05", + "summary": "为 order.entrustOrder.list 响应新增 recheck_status 字段(复核状态:none=未复核,fin=已复核)", + "methods": [ + "order.entrustOrder.list" + ], + "notes": [ + "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" + ], + "type": "updated" + }, + { + "version": "2026.06.05-system-14", + "date": "2026-06-05", + "summary": "为 order.deliveryOrder.list 响应新增 recheck_status 字段(复核状态:none=未复核,fin=已复核)", + "methods": [ + "order.deliveryOrder.list" + ], + "notes": [ + "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" + ], + "type": "updated" + }, + { + "version": "2026.06.05-system-15", + "date": "2026-06-05", + "summary": "为 order.deliveryExpectionOrder.list 响应新增 recheck_status 字段(复核状态:none=未复核,fin=已复核)", + "methods": [ + "order.deliveryExpectionOrder.list" + ], + "notes": [ + "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" + ], + "type": "updated" + }, + { + "version": "2026.06.05-system-16", + "date": "2026-06-05", + "summary": "为 order.archiveOrder.list 响应新增 recheck_status 字段(复核状态:none=未复核,fin=已复核)", + "methods": [ + "order.archiveOrder.list" + ], + "notes": [ + "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" + ], + "type": "updated" + }, + { + "version": "2026.06.06-system-01", + "date": "2026-06-06", + "summary": "恢复 order.pendingOrder.downloadCreateTemplate:方法仍存在于代码中,取消 deprecated 标记,完善文档描述", + "methods": [ + "order.pendingOrder.downloadCreateTemplate" + ], + "notes": [ + "order.pendingOrder.downloadCreateTemplate 方法在 pendingOrder.js 中仍存在(line 2099),此前被误标记为 deprecated。", + "取消 status: 'deprecated' 标记,恢复为 active 状态。", + "移除 description 中的'(已作废)'后缀。", + "完善 description:说明模板包含必填列(橙色背景)、可选列(灰色背景)、示例数据行和填写说明工作表。", + "补充 response 字段说明:filename 和 mime 为固定值。" + ], + "type": "updated" + }, + { + "version": "2026.06.07-system-01", + "date": "2026-06-07", + "summary": "order.pendingOrder.createOrder 文档新增 shop_nick 入参(店铺名称,可选,最大长度200)", + "methods": [ + "order.pendingOrder.createOrder" + ], + "notes": [ + "在 order.pendingOrder.createOrder 的 request params 中新增 shop_nick 字段(string,非必填),对应代码实现中 shopNick: String(requestData.shop_nick || requestData.shopNick || '').trim()。", + "shop_nick 已在 COPY_FIELDS 白名单中(pendingOrder.js L1738),仅文档缺失,本次为补齐。" + ], + "type": "updated" + }, + { + "version": "2026.06.07-system-02", + "date": "2026-06-07", + "summary": "order.pendingOrder.downloadCreateTemplate:模板新增 shop_nick 列(店铺名称),store_id/province/city/area 标注为非必填", + "methods": [ + "order.pendingOrder.downloadCreateTemplate" + ], + "notes": [ + "模板新增 shop_nick(店铺名称)列,非必填。", + "明确标注 store_id(货主ID)、province(省份)、city(城市)、area(区/县)为非必填列。", + "响应文档中新增 shop_nick 字段说明。" + ], + "type": "updated" + }, + { + "version": "2026.06.07-system-03", + "date": "2026-06-07", + "summary": "新增 order.pendingOrder.updateAddress:批量修改待处理订单收件地址,限制未分配快递时可用", + "methods": [ + "order.pendingOrder.updateAddress" + ], + "notes": [ + "新增 method:order.pendingOrder.updateAddress,免权限(isNeedAuth=false),需登录", + "功能:批量修改待处理订单收件地址(name/mobile/tel/zip_code/province/city/area/town/detail_address)", + "约束:仅 post_status='none'(未分配快递)的订单可修改;至少提供一个有效地址字段", + "响应:返回 updated_count(实际更新行数)和 ids(请求订单ID数组)" + ], + "type": "added" + }, + { + "version": "2026.06.07-system-04", + "date": "2026-06-07", + "summary": "order.wave.wavePickTaskCancel 扩展可取消状态至 status=3,并新增拣货状态回退", + "methods": [ + "order.wave.wavePickTaskCancel" + ], + "notes": [ + "可取消状态从 [0,1,2] 扩展为 [0,1,2,3](status=3 已完成现在也可取消)", + "取消 status=2(待复核)或 status=3(已完成)任务时,自动回退 wms_wave_pick_task_order.pick_status(1→0)和 order_delivery.pick_status(fin→padding)", + "错误码 400 描述同步更新,补充 403 错误码说明" + ], + "type": "updated" + }, + { + "version": "2026.06.07-system-05", + "date": "2026-06-07", + "summary": "order.wave.wavePickTaskList 响应新增 cart_name 字段(拣货车名称)", + "methods": [ + "order.wave.wavePickTaskList" + ], + "notes": [ + "响应 list 子项新增 cart_name(string):通过 current_cart_id LEFT JOIN wms_pick_cart 表获取,未绑定拣货车时为空字符串。" + ], + "type": "updated" + }, + { + "version": "2026.06.07-system-06", + "date": "2026-06-07", + "summary": "pick.wavePickTaskComplete 新增后台抓取任务(source=2)拣货车绑定校验,未绑定拣货车时拒绝提交", + "methods": [ + "pick.wavePickTaskComplete" + ], + "notes": [ + "description 补充说明:后台抓取创建的任务(source=2)必须先绑定拣货车才能提交,否则返回 400。", + "errors 中 400 错误补充:后台抓取任务(source=2)未绑定拣货车时拒绝提交,错误消息为\"后台抓取任务必须先绑定拣货车才能提交\"。" + ], + "type": "updated" + }, + { + "version": "2026.06.07-system-07", + "date": "2026-06-07", + "summary": "order.wave.batchList 文档修正:移除代码中不存在的 sync_assignment_status 引用", + "methods": [ + "order.wave.batchList" + ], + "notes": [ + "从 where 描述中移除 sync_assignment_status(代码 buildBatchListWhereClause allowedFields 中不存在该字段,BATCH_LIST_ASSIGNMENT_FILTER_SCHEMAS 中也无 review 之外的同步类型)。", + "从 response list 描述中移除 sync_assignment_status(代码响应映射中仅返回 storage/express/print/review 四种 assignment_status,无 sync_assignment_status)。", + "v2026.06.03-system-03 变更记录中声称新增的 sync_assignment_status 实际从未在代码中实现,本次仅为文档修正,不涉及代码变更。" + ], + "type": "updated", + "module": "order.wave" + }, + { + "version": "2026.06.07-system-08", + "date": "2026-06-07", + "summary": "order.recheckOrder.confirmRecheck 补充后置行为说明:波次任务全部复核完成后自动解绑车任务", + "methods": [ + "order.recheckOrder.confirmRecheck" + ], + "notes": [ + "在 description 中补充:确认复核后,若该订单所属波次拣货任务下所有订单均已复核完成,则自动解绑车任务。解绑操作包括:清空 wms_wave_pick_task 的 current_cart_id/current_cart_code_snapshot、停用 wms_pick_task_cart_binding(is_active=0 并记录解绑人和时间)、释放 wms_pick_cart(清空 current_task_id/bind_user_id)。", + "解绑失败仅记录 warn 日志,不影响复核主流程。", + "入参和返回结构未变,仅补充行为说明。" + ], + "type": "updated" + }, + { + "version": "2026.06.07-system-10", + "date": "2026-06-07", + "summary": "移除 order.wave.groupFetch / singleFetch / fetch 响应中已废弃的 auto_fetch_disabled_marker 字段", + "methods": [ + "order.wave.groupFetch", + "order.wave.singleFetch", + "order.wave.fetch" + ], + "notes": [ + "auto_fetch_disabled_marker 字段已从代码 submitFetchTask 响应中移除,文档同步删除该字段的描述。", + "auto_fetch_disabled 字段同样已从代码中移除,且原文档中不存在此字段(仅有 auto_fetch_disabled_marker),无需额外处理。", + "涉及 method:order.wave.groupFetch、order.wave.singleFetch、order.wave.fetch,均移除 response 中的 auto_fetch_disabled_marker 字段。" + ], + "type": "updated", + "module": "order.wave" + }, + { + "version": "2026.06.08-system-01", + "date": "2026-06-08", + "summary": "order.recheckOrder 模块 scanOrder 返回值重构为统一 list 输出,新增 confirmIntercept 与 recheckOrderList 接口", + "methods": [ + "order.recheckOrder.scanOrder", + "order.recheckOrder.confirmIntercept", + "order.recheckOrder.recheckOrderList" + ], + "notes": [ + "scanOrder 返回值重构:统一使用 list 字段输出,新增 list_type 字段区分散单/团购模式。散单模式顶层新增 picker_id、picker_name、wave_id、wave_no、wave_type、pick_mode、strategy_id、strategy_name、total_orders、reviewed_count、unreviewed_count 等汇总字段。list 中每项新增 waybill_no、is_printed、is_reviewed、wave_index、intercept_status、store_remark、stock[](含 stock_id、item_code、item_name、sku_property、packing_requirements、barcodes[]、images[]、plan_qty、has_shared_barcode)。移除旧字段 logs、order、order_id(顶层)、waybill_no(顶层旧位置)、wave_match_view、items、expresses、cart_match_view。", + "scanOrder 入参新增 wave_no / waveNo 支持波次号直接扫描匹配。", + "新增 order.recheckOrder.confirmIntercept:确认拦截接口,将订单 intercept_status 更新为 intercepted_at_warehouse,返回 order_id、order_no、intercept_status、updated_at。", + "新增 order.recheckOrder.recheckOrderList:复核订单列表查询,支持 list_type=single(散单)与 list_type=group(团购),均返回统一 list + pagination 结构。" + ], + "type": "updated" + }, + { + "version": "2026.06.08-system-02", + "date": "2026-06-08", + "summary": "order.recheckOrder 模块新增 batchIntercept/batchInterceptTaskProgress,更新 scanOrder 团购模式响应结构,完善 confirmIntercept/recheckOrderList 文档", + "methods": [ + "order.recheckOrder.batchIntercept", + "order.recheckOrder.batchInterceptTaskProgress", + "order.recheckOrder.scanOrder", + "order.recheckOrder.confirmIntercept", + "order.recheckOrder.recheckOrderList" + ], + "notes": [ + "新增 order.recheckOrder.batchIntercept:批量提交订单拦截(异步任务模式),入参支持 order_ids/orderIds/ids(订单ID数组,不再使用 wave_ids),将 intercept_status 设为 'requested',返回 task_id/warehouse_id/message/accepted_at。支持幂等提交与 warehouse_id 校验。", + "新增 order.recheckOrder.batchInterceptTaskProgress:按 task_id 查询批量拦截任务进度,返回 state(submitted/running/success/failed/not_found)及对应的进度/计数/结果/错误字段。", + "更新 order.recheckOrder.scanOrder 响应文档:团购模式(cart 命中)list 项新增 wave_id/wave_no/wave_type/wave_status/total_orders/processed_orders/creator/create_time/update_time/order_count/pick_mode/box_no/orders[] 等波次级别字段;补充散单无波次信息时的回退详情模式说明(detail/items/expresses/logs)。", + "完善 order.recheckOrder.confirmIntercept:补充操作日志写入说明(ORDER_INTERCEPT_CONFIRM)及失败不影响主流程的容错描述。", + "完善 order.recheckOrder.recheckOrderList:补充散单模式默认排除 pick_status='none' 和 recheck_status='fin' 的说明;团购模式 where 支持 wave_no(模糊搜索)的说明。" + ], + "type": "updated" + }, + { + "version": "2026.06.08-system-03", + "date": "2026-06-08", + "summary": "移除 order.recheckOrder.batchIntercept 的 warehouse_id/warehouseId 入参,仓库ID统一使用当前上下文", + "methods": [ + "order.recheckOrder.batchIntercept" + ], + "notes": [ + "移除入参 warehouse_id / warehouseId:仓库ID统一从当前上下文(ctx.user.store_id)获取,不再由调用方传入。", + "移除对应错误码:warehouse_id 参数不合法(400)、warehouse_id 与当前仓库上下文不一致(400)。", + "description 中补充说明仓库ID来源为当前上下文。", + "response 中 warehouse_id 字段描述改为「取自当前上下文」。" + ], + "type": "updated" + }, + { + "version": "2026.06.08-system-10", + "date": "2026-06-08", + "summary": "batchIntercept / batchInterceptTaskProgress 从 order.recheckOrder 迁移至 order.pendingOrder", + "methods": [ + "order.pendingOrder.batchIntercept", + "order.pendingOrder.batchInterceptTaskProgress" + ], + "notes": [ + "method 从 order.recheckOrder.batchIntercept 重命名为 order.pendingOrder.batchIntercept,分组从订单复核模块迁移至订单待处理模块", + "method 从 order.recheckOrder.batchInterceptTaskProgress 重命名为 order.pendingOrder.batchInterceptTaskProgress,分组从订单复核模块迁移至订单待处理模块", + "接口入参、响应、错误码均保持不变,仅变更 method 名称与所属分组" + ], + "type": "updated" + }, + { + "version": "2026.06.08-system-04", + "date": "2026-06-08", + "summary": "新增 order.print.getOrderPrintData:按订单ID拉取打印数据,返回结构与 getWavePlatformPrintData 一致,不限制锁定状态", + "methods": [ + "order.print.getOrderPrintData" + ], + "notes": [ + "新增 order.print.getOrderPrintData 接口文档,入参为 warehouse_id + order_ids(非空数组),返回与 getWavePlatformPrintData 结构一致的 waveGroups / summary / wave_ids / ext", + "与 getWavePlatformPrintData 的区别:入参为 order_ids(非 wave_ids),ext 中返回 missing_order_ids / filtered_order_ids(非 missing_wave_ids / filtered_wave_ids)", + "不限制打印锁定状态,所有订单(无论是否被锁定)统一返回打印数据", + "自动过滤 post_status !== 'fin' 的订单(快递未完全分配),被过滤订单出现在 ext.filtered_order_ids" + ], + "type": "added", + "module": "order.print" + }, + { + "version": "2026.06.08-system-11", + "date": "2026-06-08", + "summary": "新增 order.pendingOrder 批量锁定/解锁/解除拦截及对应进度查询共 6 个异步任务接口文档", + "methods": [ + "order.pendingOrder.batchLock", + "order.pendingOrder.batchLockTaskProgress", + "order.pendingOrder.batchUnlock", + "order.pendingOrder.batchUnlockTaskProgress", + "order.pendingOrder.batchUnintercept", + "order.pendingOrder.batchUninterceptTaskProgress" + ], + "notes": [ + "新增 batchLock:批量锁定订单,lock_status → 'warehouse',操作日志 ORDER_LOCK,task_id 格式 order_lock_{warehouseId}_{timestamp}_{rand}。", + "新增 batchLockTaskProgress:查询批量锁定进度,返回 locked_order_count / locked_order_ids 等。", + "新增 batchUnlock:批量解锁订单,lock_status → 'none',操作日志 ORDER_UNLOCK,task_id 格式 order_unlock_{warehouseId}_{timestamp}_{rand}。", + "新增 batchUnlockTaskProgress:查询批量解锁进度,返回 unlocked_order_count / unlocked_order_ids 等。", + "新增 batchUnintercept:批量解除拦截订单,intercept_status → 'none',操作日志 ORDER_INTERCEPT_CANCEL,task_id 格式 order_unintercept_{warehouseId}_{timestamp}_{rand}。", + "新增 batchUninterceptTaskProgress:查询批量解除拦截进度,返回 unintercepted_order_count / unintercepted_order_ids 等。", + "以上 6 个接口均采用与已有 batchIntercept/batchInterceptTaskProgress 一致的异步任务模式:提交返回 task_id,进度查询返回 state + 进度字段。", + "仅同步文档,不修改业务代码或实现。" + ], + "type": "added", + "module": "order" + }, + { + "version": "2026.06.08-system-12", + "date": "2026-06-08", + "summary": "更新 order.print.getOrderPrintData:移除锁定限制,所有订单统一返回打印数据,不再区分锁定/未锁定", + "methods": [ + "order.print.getOrderPrintData" + ], + "notes": [ + "移除打印锁定限制:所有订单(包括已锁定)统一返回打印数据,不再区分锁定/未锁定状态", + "移除 locked_count、locked_orders、locked_wave_groups 等锁定相关字段", + "返回结构与 getWavePlatformPrintData 完全一致:summary / waveGroups / wave_ids / ext", + "ext 中使用 missing_order_ids / filtered_order_ids(替代锁定相关字段),与代码实现完全对齐" + ], + "type": "updated", + "module": "order.print" + }, + { + "version": "2026.06.08-system-13", + "date": "2026-06-08", + "summary": "更新 order.print.getOrderPrintData:移除 warehouse_id 入参,仓库ID统一从当前上下文获取", + "methods": [ + "order.print.getOrderPrintData" + ], + "notes": [ + "移除 warehouse_id / warehouseId 入参,仓库ID统一从 this.getContextWarehouseId() 获取", + "同步移除 errors 中 warehouse_id 必填 相关错误码", + "description 补充说明仓库ID从上下文获取,无需调用方传入", + "params 仅保留 order_ids(非空数组),与代码 method 层 getOrderPrintData(data) 解构一致" + ], + "type": "updated", + "module": "order.print" + }, + { + "version": "2026.06.08-system-14", + "date": "2026-06-08", + "summary": "新增 order.recheckOrder.scanTask 接口文档,并为 scanOrder 响应补充 task_id 字段", + "methods": [ + "order.recheckOrder.scanTask", + "order.recheckOrder.scanOrder" + ], + "notes": [ + "新增 order.recheckOrder.scanTask:按拣货任务 ID 拉取复核数据,数据结构与 scanOrder 完全一致,用于前端刷新。入参为 task_id(必填,number),返回 match_type='task',散单模式(pick_mode 2/3/4)返回扁平订单列表,团购模式(pick_mode 1/5)返回分组波次列表。", + "更新 order.recheckOrder.scanOrder 响应定义:补充 task_id 字段说明(散单有波次时由 buildSingleWaveScanView 返回,团单车号命中时由 cartMatchContext 返回)。", + "仅同步文档,不修改任何业务代码或实现。" + ], + "type": "updated" + }, + { + "version": "2026.06.08-system-15", + "date": "2026-06-08", + "summary": "新增 order.pendingOrder.manualWaybill 接口(手工录入运单号)", + "methods": [ + "order.pendingOrder.manualWaybill" + ], + "notes": [ + "为待处理订单手动录入运单号,写入 wms_order_express 表", + "仅允许 step 在 [1,2,3] 且 outbound_status 不为 'padding' 的订单操作", + "免权限(isNeedAuth: false),需登录", + "成功返回运单记录的 id、order_id、waybill_code、create_at" + ], + "type": "added" + }, + { + "version": "2026.06.09-system-01", + "date": "2026-06-09", + "summary": "order.pendingOrder.updateAddress 新增 remark 字段:订单留言/备注批量覆盖,不受 post_status 限制", + "methods": [ + "order.pendingOrder.updateAddress" + ], + "notes": [ + "在 params 中新增 remark 字段(string,可选,最大500字符),支持批量覆盖所选订单的 remark", + "remark 更新不受 post_status 限制,可对所有订单生效(地址字段仍仅允许 post_status='none')", + "更新 description 明确 remark 与地址字段的独立性", + "更新 response 中 updated_count 说明:取地址更新行数与备注更新行数的最大值", + "更新 errors 中缺少字段的错误描述,改为「至少需要提供一个地址字段或备注进行修改」", + "业务代码已同步实现,本次仅同步文档" + ], + "type": "updated" + }, + { + "version": "2026.06.09-system-02", + "date": "2026-06-09", + "summary": "order.updateExpressWeighingWeight 新增运单号模式文档:order_id=0 时从运单号反查,支持散单与团购批量两种返回结构", + "methods": [ + "order.updateExpressWeighingWeight" + ], + "notes": [ + "order_id 参数说明补充:设为0时切换为运单号模式,需配合 waybill_code 使用。", + "waybill_code 参数说明补充:运单号模式(order_id=0)下必填。", + "description 更新:明确订单模式与运单号模式两种路径及团购波次批量行为。", + "response 新增运单号散单场景字段(order_id、waybill_code、weighing_weight)与运单号团购批量场景字段(wave_no、business_key、weighing_weight、success_count)。", + "errors 新增运单号模式相关错误码:运单号不存在(404)、运单号对应的订单不存在(404)、波次下未找到订单(404)、批量更新失败(500)。", + "仅文档同步,不修改业务代码。" + ], + "type": "updated" + }, + { + "version": "2026.06.09-system-03", + "date": "2026-06-09", + "summary": "order.updateExpressWeighingWeight 团购返回新增拆单汇总字段,移除 success_count/total_count", + "methods": [ + "order.updateExpressWeighingWeight" + ], + "notes": [ + "团购批量模式 response 新增 total_weight(所有拆单重量累加)、split_count(waybill_code 非空的 business_key 数量)、splits(按 business_key 分组的拆单明细数组,每项含 business_key/weighing_weight/waybill_code)、store_name(货主名称)和 sys_logistics_name(系统快递名称)。", + "移除 response 中的 success_count 与 total_count 字段,改为由 total_weight 和 split_count 提供汇总信息。", + "更新 description 以反映团购模式返回拆单汇总结构。" + ], + "type": "updated" + }, + { + "version": "2026.06.10-system-01", + "date": "2026-06-10", + "summary": "order.detail 接口文档:expresses 数组新增字段 weighing_weight、sys_logistics_code、sys_logistics_name、business_key、created_at", + "methods": [ + "order.detail" + ], + "notes": [ + "expresses 数组新增字段:weighing_weight(称重重量,number|null)、sys_logistics_code(系统物流公司编码,string)、sys_logistics_name(系统物流公司名称,string)、business_key(业务标识,string)、created_at(创建时间戳毫秒,number|null)", + "字段来源:getOrderExpressesByOrderId 方法中 sys_logistics_code/sys_logistics_name 取自订单表 sys_logistics_code/sys_logistics_name,其余字段取自 OrderExpress 表" + ], + "type": "updated" + }, + { + "version": "2026.06.10-system-02", + "date": "2026-06-10", + "summary": "dashboard.order_trend 从 mock 数据改为查询真实数据库,按小时统计当日订单数与发货数,补充完整返回结构与错误说明", + "methods": [ + "dashboard.order_trend" + ], + "notes": [ + "接口实现从 mock 静态数据改为查询真实数据库(wms_order_delivery 与 dispatch 表),数据实时反映仓库当日运营情况。", + "订单筛选条件:step in [1,2,3],排除 outbound_status='padding' 和 status='cancel',统计 create_at 在今日 00:00 到当前时刻的订单,按 HOUR(create_at) 分组。", + "发货筛选条件:dispatch_lane='m4',统计 delivery_time 在今日 00:00 到当前时刻的发货记录,按 HOUR(delivery_time) 分组。", + "时段范围:从 08:00 到当前小时(最晚 23:00),若当前时间早于 08:00 则从 08:00 开始。", + "返回新增 summary 汇总对象:total_orders(订单总数)、total_shipments(发货总数)、shipment_rate(发货率百分比)、peak_hour(峰值时段)、peak_orders(峰值订单数)。", + "categories/orders/shipments 三个数组一一对应,提供按时段的订单与发货趋势数据,可直接用于前端折线图/柱状图渲染。", + "需要登录(Authorization header),从 token 中获取 warehouseId;若缺少仓库上下文则返回 flag='fail'。" + ], + "type": "updated", + "module": "dashboard" + }, + { + "version": "2026.06.10-system-03", + "date": "2026-06-10", + "summary": "order.pendingOrder.manualWaybill 新增可选参数 logistics_interface_name 与响应字段 business_key/logistics_interface_name,补充行为说明", + "methods": [ + "order.pendingOrder.manualWaybill" + ], + "notes": [ + "新增可选参数 logistics_interface_name(string,选填,trim 后为空则传 null)", + "响应新增字段 business_key(number):同一订单下从已有最大值 +1 递增,无记录时从 1 开始", + "响应新增字段 logistics_interface_name(string/null):写入的物流接口名称", + "补充 description 行为说明:完成后自动更新 wms_order_delivery_* 表的 print_status 和 post_status 为 'fin'", + "wms_order_express 表写入时 status 固定为 1,warehouse_id 从订单记录取" + ], + "type": "updated" + }, + { + "version": "2026.06.10-system-04", + "date": "2026-06-10", + "summary": "stock.warehouse.import 新增 barcode(条码)字段支持", + "methods": [ + "stock.warehouse.import" + ], + "notes": [ + "新增 barcode(条码)字段支持,支持别名:条码、bar_code、barCode、barcodeList、barcode_list、barcode。", + "条码字段支持数组格式(如 [\"6901234567890\"])和分号分隔字符串格式(如 \"6901234567890;6901234567891\")。", + "新建和更新路径均已支持条码导入,条码写入 wms_stock_barcodes 表。", + "仅同步文档,不修改业务代码或实现。" + ], + "type": "updated" + }, + { + "version": "2026.06.10-system-05", + "date": "2026-06-10", + "summary": "stock.warehouse.import 的 barcode 字段分隔符改为逗号,对齐 stock.warehouse.export 导出格式;仅接收字符串格式,不再支持数组", + "methods": [ + "stock.warehouse.import" + ], + "notes": [ + "barcode 字段分隔符从分号 ; 改为逗号 ,", + "barcode 字段仅接收字符串格式,不再支持数组格式", + "格式示例:\"6901234567890,6901234567891\",与 stock.warehouse.export 导出格式一致" + ], + "type": "modified" + }, + { + "version": "2026.06.13-system-01", + "date": "2026-06-13", + "summary": "setting.warehouse 的 auto_outbound_rules 新增 require_print 和 require_pick 两个可选条件字段(同步代码实现)", + "methods": [ + "setting.warehouse.getSettings", + "setting.warehouse.saveSettings" + ], + "notes": [ + "在 getSettings 响应和 saveSettings 入参中补充 subject_config.auto_outbound_rules 对象的完整字段文档(enabled、require_recheck、require_pack、require_weigh、require_sync、require_print、require_pick)。", + "require_print:是否要求已打印(print_status=fin),默认 true。", + "require_pick:是否要求已拣货(pick_status=fin),默认 true。", + "该规则由自动出库定时任务 order_auto_outbound 消费,全部开启的条件均满足时自动标记待出库。" + ], + "type": "updated" + }, + { + "version": "2026.06.13-system-02", + "date": "2026-06-13", + "summary": "order.recheckOrder.scanOrder 团购模式响应新增 orders_detail 字段,暴露非拦截订单的详细列表(含 is_printed、is_reviewed 等状态字段)", + "methods": [ + "order.recheckOrder.scanOrder" + ], + "notes": [ + "团购模式(list_type='group')波次视图项新增 orders_detail 字段:非拦截订单详细列表,每项含 order_id、delivery_order_code、waybill_no、pick_status、is_printed(print_status === 'fin')、is_reviewed(recheck_status === 'fin')、recheck_status、shop_nick、items_count、wave_index、intercept_status", + "orders_detail 与现有 order_ids(纯数字 ID 数组)并存,均在团购模式的波次视图项中返回", + "orders_detail 仅在 list_type='group' 时返回,散单模式不受影响", + "同步更新 list 字段 description 以反映 group 模式新增的 order_ids、orders_detail、stocks 字段" + ], + "type": "updated" + }, + { + "version": "2026.06.13-system-03", + "date": "2026-06-13", + "summary": "新增批量快捷复核接口 batchQuickRecheck,支持批量订单 IDs 的前置条件检查(储位、快递、同步、拦截),自动完成拣货并标记复核,支持部分失败。拣货完成后同步更新 wms_wave_pick_task 状态", + "methods": [ + "order.recheckOrder.batchQuickRecheck" + ], + "notes": [ + "新增 order.recheckOrder.batchQuickRecheck 方法", + "入参 ids 支持数组或逗号分隔字符串", + "响应包含 success/failed 列表及计数,failed 项含 reason 说明" + ], + "details": { + "description": "包含拣货任务状态同步:全部拣完→任务状态=2(已完成),未全拣完→任务状态推进为1(拣货中)" + }, + "type": "added" + }, + { + "version": "2026.06.14-system-01", + "date": "2026-06-14", + "summary": "新增 order.bindExpressPackageMaterialByWaybill 方法:支持仅凭运单号绑定包材,无需传入订单ID", + "methods": [ + "order.bindExpressPackageMaterialByWaybill" + ], + "notes": [ + "新增 order.bindExpressPackageMaterialByWaybill 入参说明:waybill_code(运单号,必填)、package_material_code(包材编码,必填)。无需传入 order_id。", + "成功返回字段:order_id、waybill_code、package_material_id、package_material_name_snapshot、package_material_code。", + "错误码定义:400(参数错误)、404(运单号不存在 / 包材编码不存在)、500(绑定包材失败)。" + ], + "type": "added" + }, + { + "version": "2026.06.15-system-01", + "date": "2026-06-15", + "summary": "order.detail / order.deliveryOrder.detail 的 expresses 数组新增包材字段", + "methods": [ + "order.detail", + "order.deliveryOrder.detail" + ], + "notes": [ + "expresses 数组每个元素新增 package_material_id(包材ID,number|null)和 package_material_name_snapshot(包材名称快照,string|null)字段。" + ], + "type": "updated" + }, + { + "version": "2026.06.15-system-02", + "date": "2026-06-15", + "summary": "order.deliveryOrder.detail 的 expresses 数组新增包材字段", + "methods": [ + "order.deliveryOrder.detail" + ], + "notes": [ + "expresses 数组每个元素新增 package_material_id(包材ID,number|null)和 package_material_name_snapshot(包材名称快照,string|null)字段。" + ], + "type": "updated" + }, + { + "version": "2026.06.15-system-03", + "date": "2026-06-15", + "summary": "新增 setting.packageMaterial.search 方法:支持按关键字模糊搜索包材编码和名称", + "methods": [ + "setting.packageMaterial.search" + ], + "notes": [ + "新增 setting.packageMaterial.search 入参 keyword(可选),为空返回前 50 条启用中包材,有值时对 material_code 和 material_name 做模糊匹配。", + "返回包材数组,字段:id、material_code、material_name、material_type、spec、status。" + ], + "type": "added" + }, + { + "version": "2026.06.16-system-01", + "date": "2026-06-16", + "summary": "新增 order.recheckOrder.queryRecheckOrderSingleList:散单复核列表接口,响应新增 items_weight(总重量g)和 weight_type(重量类型)字段", + "methods": [ + "order.recheckOrder.queryRecheckOrderSingleList" + ], + "notes": [ + "新增方法 order.recheckOrder.queryRecheckOrderSingleList,为 recheckOrderList 散单模式的独立入口。", + "响应 list 每项新增字段 items_weight (DECIMAL(10,2)):订单总重量(g),来自 wms_order.items_weight,为 null 时返回 null。", + "响应 list 每项新增字段 weight_type (string):重量类型中文标签,来自 wms_order.weight_type 经 formatWeightTypeLabel 转换;取值:常规/轻货/重货/冷链(对应 DB 值 0/1/2/3)。" + ], + "type": "added", + "module": "order.recheckOrder" + }, + { + "version": "2026.06.16-system-02", + "date": "2026-06-16", + "summary": "为 order.wave.groupOrderFetchList / waveStrategyFallbackOrderList / singleOrderFetchList 响应新增 items_weight(总重量g)和 weight_type(重量类型)字段", + "methods": [ + "order.wave.groupOrderFetchList", + "order.wave.waveStrategyFallbackOrderList", + "order.wave.singleOrderFetchList" + ], + "notes": [ + "order.wave.groupOrderFetchList:响应 list 每项新增 items_weight (number|null):订单总重量(g),取组内首单 items_weight;组内订单 items_hash 相同重量一致。", + "order.wave.waveStrategyFallbackOrderList:响应 list 每项新增 items_weight (number|null):订单总重量(g),来自 wms_order.items_weight;新增 weight_type (string):重量类型中文标签,取值:常规/轻货/重货/冷链(对应 DB 值 0/1/2/3)。", + "order.wave.singleOrderFetchList:响应 list 每项新增 items_weight (number|null):订单总重量(g),取组内首单 items_weight;组内订单 items_hash 相同重量一致。", + "所有新增字段均为可选(required=false),为 null 时返回 null。" + ], + "type": "updated", + "module": "order.wave" + }, + { + "version": "2026.06.17-system-01", + "date": "2026-06-17", + "summary": "新增 order.pendingOrder.replenishmentDemand 分拣缺货补货需求计算接口文档", + "methods": [ + "order.pendingOrder.replenishmentDemand" + ], + "notes": [ + "新增分拣缺货补货需求计算方法,用于计算待处理订单的SKU在分拣区与存货区的库存分布及补货缺口", + "入参 order_ids/warehouse_id 均为可选;不传 order_ids 时自动查询当前仓库所有未完成储位分配的订单", + "纯只读查询接口,不修改任何数据", + "响应包含 list(明细)与 summary(汇总),其中 shortage = max(0, total_demand - pick_zone_quantity),replenishment_needed = min(shortage, storage_zone_quantity)" + ], + "type": "add", + "module": "order.pendingOrder" + }, + { + "version": "2026.06.17-system-02", + "date": "2026-06-17", + "type": "update", + "module": "order.pendingOrder", + "method": "order.pendingOrder.replenishmentDemand", + "description": "移除 order_ids 参数,改为纯仓库级别计算,自动查询当前仓库所有未完成储位分配的订单" + }, + { + "version": "2026.06.17-system-03", + "date": "2026-06-17", + "type": "update", + "module": "order.pendingOrder", + "method": "order.pendingOrder.replenishmentDemand", + "description": "新增 is_true_shortage 字段标识真正缺货(两区均无库存),summary 新增 total_true_shortage_skus 统计" + }, + { + "version": "2026.06.17-system-04", + "date": "2026-06-17", + "type": "migrate", + "module": "storage.management", + "summary": "从 order.pendingOrder.replenishmentDemand 迁移至 storage.management.replenishmentDemand(库存管理模块),原路径已删除,开发阶段无需兼容", + "methods": [ + "storage.management.replenishmentDemand" + ], + "notes": [ + "将 replenishmentDemand 接口从 order.pendingOrder 模块迁移到新建的 storage.management 库存管理模块。", + "旧条目 order.pendingOrder.replenishmentDemand 已从 order.pendingOrder 组中移除。", + "开发阶段无需兼容旧路径。" + ] + }, + { + "version": "2026.06.17-system-05", + "date": "2026-06-17", + "type": "update", + "module": "storage.management", + "summary": "storage.management.replenishmentDemand 移除 warehouse_id 入参,仓库ID改为纯从用户上下文(ctx.user)获取,接口无需入参", + "methods": [ + "storage.management.replenishmentDemand" + ], + "notes": [ + "移除 warehouse_id 入参,仓库ID改为纯从用户上下文(ctx.user)获取,接口无需入参" + ] + }, + { + "version": "2026.06.17-system-06", + "date": "2026-06-17", + "type": "update", + "module": "storage.management", + "method": "storage.management.replenishmentDemand", + "description": "新增分页入参(pagination)、排序入参(sort,默认按 shortage DESC)、响应新增 replenishment_locations(存货区可补货库位,最多5条)、响应新增 pagination 分页信息" + }, + { + "version": "2026.06.17-system-07", + "date": "2026-06-17", + "type": "update", + "module": "storage.management", + "summary": "replenishment_locations 新增 space_name 字段,优先取自定义名称(custom_name),无则回退库位编码(space_code)", + "methods": [ + "storage.management.replenishmentDemand" + ], + "notes": [ + "在 replenishment_locations.children 中新增 space_name 字段(string, required),放在 space_code 之后、available_quantity 之前。", + "space_name 取值逻辑:优先使用库位自定义名称 custom_name,若无自定义名称则回退为库位编码 space_code。" + ] + }, + { + "version": "2026.06.17-system-08", + "date": "2026-06-17", + "type": "update", + "module": "storage.management", + "summary": "合并 is_sufficient 和 is_true_shortage 为 replenishment_status 枚举字段(replenishable/true_shortage)", + "methods": [ + "storage.management.replenishmentDemand" + ], + "notes": [ + "删除 is_sufficient(boolean)和 is_true_shortage(boolean)两个字段。", + "新增 replenishment_status(string)枚举字段:replenishable=存货区足够覆盖缺口,移库可解决;true_shortage=存货区不足以覆盖缺口或两区均无库存,需采购。" + ] + }, + { + "version": "2026.06.18-system-01", + "date": "2026-06-18", + "summary": "入库单完成后异步匹配收货单并回传:completeEntry / entryorderConfirm 入库完成时自动匹配收货单,明细一致则按来源回传(奇门/OpenAPI),覆盖场景标记收货单部分入库;completeReceiving 完成后清除收货单缓存", + "methods": [ + "storage.entry.completeEntry", + "storage.receiving.completeReceiving" + ], + "notes": [ + "新增 app/service/systems/receiving_entry_match.js:入库单完成后异步匹配收货单并回传的核心服务,含 Redis 缓存收货单列表(TTL 300s)、remark 匹配收货单号、明细对比、奇门回传、OpenAPI 回调、部分入库标记等能力。", + "storage.entry.completeEntry 完成后通过 setImmediate 异步触发 matchAfterEntryCompleted,不阻塞主流程。", + "entry_order.js entryorderConfirm() 事务提交后(isFin 最终完成)同样异步触发匹配。", + "storage.receiving.completeReceiving 完成后清除收货单 Redis 缓存(cache:receiving_orders:warehouse:{warehouseId}),确保下次匹配获取最新收货单列表。", + "匹配规则:入库单 remark 包含收货单号 → 对比 SKU+数量 → 完全一致回传 / 收货单覆盖标记部分入库 / 其他不处理。", + "回传路径:source_type=QM → 奇门 taobao.qimen.entryorder.confirm;source_type=API → OpenAPI 回调(entry_order_receiving_matched 事件)。" + ], + "type": "updated" + }, + { + "version": "2026.06.18-system-02", + "date": "2026-06-18", + "summary": "新增 storage.receiving.manualMatchEntryOrder 接口", + "methods": [ + "storage.receiving.manualMatchEntryOrder" + ], + "notes": [ + "新增 storage.receiving.manualMatchEntryOrder:手动匹配入库单与收货单,传入 receivingId 和 entryOrderId,复用异步匹配服务的明细对比和回传逻辑,同步返回匹配结果", + "参数:receivingId (number, 必填)、entryOrderId (number, 必填)", + "校验:入库单存在性、收货单存在性、同仓库校验", + "返回 matchType (full_match/receiving_covers_entry/entry_exceeds_receiving/no_match)、comparisonResult、callbackSent、callbackResult、partialStorageMarked、entryOrder、receivingOrder" + ], + "type": "added", + "module": "storage" + }, + { + "version": "2026.06.18-system-03", + "date": "2026-06-18", + "summary": "新增 storage.receiving.getAvailableInboundQuantity 接口:按 stock_id 查询已审核收货单的可入库数量(actual_quantity - stored_quantity),排除未审核和已取消的收货单", + "methods": [ + "storage.receiving.getAvailableInboundQuantity" + ], + "notes": [ + "新增 system method:storage.receiving.getAvailableInboundQuantity,按 stock_id 查询已审核收货单中各明细的可入库数量(actual_quantity - stored_quantity),仅返回尚有可入库余量的明细。", + "实现文件:app/service/systemMethods/storage/receiving.js(包装层)、app/service/systems/storage/receiving.js(业务层)。", + "接口无需鉴权(isNeedAuth=false),但需要登录(isNeedLogin=true)。", + "入参 stock_id 为必填,对应 stock_warehouse.id;服务端从 ctx.user.store_id 获取仓库上下文。" + ], + "type": "added", + "module": "storage" + }, + { + "version": "2026.06.18-system-04", + "date": "2026-06-18", + "summary": "新增 storage.entry.bindReceivingDetails 接口和 wms_entry_receiving_binding 中间表:入库单明细可显式绑定收货明细(pending状态),提交入库时事务内完成双向扣减(stored_quantity/received_quantity),通过唯一约束和行锁防止超分和重复绑定。同时重构 completeEntry 调用链为 commitEntryWithBindings,无绑定时向后兼容。", + "methods": [ + "storage.entry.bindReceivingDetails", + "storage.entry.completeEntry" + ], + "notes": [ + "新增 storage.entry.bindReceivingDetails 方法:入库单明细绑定收货明细,pending 状态软绑定,每次调用清除旧 pending 绑定后创建新绑定。", + "新增 wms_entry_receiving_binding 中间表(migration: 20260618150000-create-wms-entry-receiving-binding.js),用于记录入库明细与收货明细的绑定关系。", + "重构 completeEntry 调用链:systemMethods 层 completeEntry 改为调用 commitEntryWithBindings,有绑定则事务内完成双向扣减(stored_quantity/received_quantity),无绑定时向后兼容仅变更入库单状态。", + "通过数据库唯一约束和行锁(SELECT ... FOR UPDATE)防止超分和重复绑定。", + "涉及文件: app/model/entry_receiving_binding.js, app/service/systems/storage/entry.js, app/service/systemMethods/storage/entry.js, database/migrations/20260618150000-create-wms-entry-receiving-binding.js" + ], + "type": "added", + "module": "storage.entry" + }, + { + "version": "2026.06.18-system-05", + "date": "2026-06-18", + "summary": "storage.entry.get 响应追加 pending_total/total_planned/bindings 字段,storage.receiving.getAvailableInboundQuantity 响应追加 pending_allocated_quantity 字段:前端可通过 get 查看入库明细的绑定状态,getAvailableInboundQuantity 的可用量已扣除全局 pending 绑定总量", + "methods": [ + "storage.entry.get", + "storage.receiving.getAvailableInboundQuantity" + ], + "notes": [ + "storage.entry.get:items 数组每项新增 pending_total(该入库明细当前 pending 绑定的总预分配数量)、total_planned(计划入库数量=count)、bindings(pending 绑定列表,每项含 id/entry_item_id/receiving_detail_id/allocated_quantity/status/receivingDetail 子对象)", + "storage.receiving.getAvailableInboundQuantity:list 每项新增 pending_allocated_quantity(该收货明细在当前 stock_id 所有入库单中的 pending 绑定总量),available_quantity 计算已扣除该值" + ], + "type": "updated" + }, + { + "version": "2026.06.18-system-06", + "date": "2026-06-18", + "summary": "bindReceivingDetails 重构为\"绑定即实收\"(received_quantity 在绑定时更新,不再等到 completeEntry),新增 unbindReceivingDetails 解绑接口(删除 pending 绑定并回退 received_quantity),commitEntryWithBindings 移除 received_quantity 更新逻辑", + "methods": [ + "storage.entry.bindReceivingDetails", + "storage.entry.unbindReceivingDetails", + "storage.entry.completeEntry" + ], + "notes": [ + "storage.entry.bindReceivingDetails:改为绑定即实收,绑定成功后立即更新入库明细 received_quantity;重复调用时先回退旧绑定量再创建新绑定,避免重复累加。", + "storage.entry.unbindReceivingDetails:新增解绑接口,删除该入库明细的所有 pending 绑定记录,并将 received_quantity 回退到绑定前的值;收货明细可用数量随绑定记录删除自动恢复。", + "storage.entry.completeEntry:commitEntryWithBindings 中移除 received_quantity 更新逻辑(received_quantity 已在绑定时更新,completeEntry 仅完成收货单侧入库数量扣减和库存上架)。" + ], + "type": "updated" + }, + { + "version": "2026.06.19-system-01", + "date": "2026-06-19", + "summary": "order.recheckOrder.scanOrder 响应 list[] 新增 items_weight(订单商品总重量g)和 suggested_package_material(推荐包材)字段", + "methods": [ + "order.recheckOrder.scanOrder" + ], + "notes": [ + "响应 list 每项新增 items_weight (number|null):订单商品总重量(g),来源于 wms_order_delivery.items_weight。散单模式每个订单对象包含,团购模式每个波次对象包含(取波次内首个正常订单的重量,为 null 时返回 0)。", + "响应 list 每项新增 suggested_package_material (object|null):推荐包材信息,根据订单商品结构(items_hash + items_crc)匹配 wms_package_material_item_relation 历史绑定记录,按 bind_count 降序取最优匹配。若 items_hash 为空或无匹配记录则为 null。包含子字段:id、code、name、spec、type、weight、length、width、height、bind_count。", + "同步更新 method description 和 list 字段 description,补充新增字段的说明。" + ], + "type": "updated", + "module": "order.recheckOrder" + }, + { + "version": "2026.06.21-system-01", + "date": "2026-06-21", + "summary": "order.bindExpressPackageMaterialByWaybill:入参 package_material_code 改为 package_material_id,类型由 string 改为 number|string", + "methods": [ + "order.bindExpressPackageMaterialByWaybill" + ], + "notes": [ + "入参字段名从 package_material_code 改为 package_material_id。", + "入参类型从 string 改为 number|string,与代码 normalizePackageMaterialId 的实现一致。", + "同步更新该方法 description 中'包材编码'为'包材ID'。" + ], + "type": "updated", + "module": "order" + }, + { + "version": "2026.06.21-system-comboGoods-01", + "date": "2026-06-21", + "summary": "新增 comboGoods 组合商品模块 5 个接口文档:list/create/update/delete/search", + "methods": [ + "comboGoods.list", + "comboGoods.create", + "comboGoods.update", + "comboGoods.delete", + "comboGoods.search" + ], + "notes": [ + "comboGoods.list:组合商品列表查询(分页),支持按 combo_code/combo_name/status/warehouse_id 筛选,返回含 simpleNotation 和 nameNotation 简记字段", + "comboGoods.create:创建组合商品(含明细一次性提交),校验 combo_code 唯一性、子商品有效性和货主一致性,事务保证原子写入", + "comboGoods.update:编辑组合商品(含明细替换),支持部分字段更新,传入 items 则先删旧明细再插入新明细", + "comboGoods.delete:软删除组合商品(status 置为 0)", + "comboGoods.search:关键字搜索组合商品,模糊匹配 combo_code 或 combo_name,仅返回启用状态记录,上限100条", + "数据表:wms_combo_goods(主表)+ wms_combo_goods_item(明细表);子商品校验依赖 wms_stock_warehouse 表", + "代码文件:app/service/systems/comboGoods.js(业务逻辑层)+ app/service/systemMethods/comboGoods.js(接口包装层)", + "isNeedAuth:list/search 无需鉴权,create/update/delete 需要鉴权" + ], + "type": "added", + "module": "comboGoods" + }, + { + "version": "2026.06.21-system-comboGoods-02", + "date": "2026-06-21", + "summary": "comboGoods 模块新增 custom_code(自定义编码)功能:create/update 支持传入 custom_code 并校验按货主唯一,list/search 返回新增 custom_code 字段,search 搜索范围扩展至 custom_code 且优先排列匹配项", + "methods": [ + "comboGoods.list", + "comboGoods.create", + "comboGoods.update", + "comboGoods.search" + ], + "notes": [ + "新增字段 custom_code(VARCHAR(64) NULL),仅做按货主唯一性校验(排除已删除记录),非全局唯一。", + "wms_combo_goods 表新增索引 uk_store_custom_code(warehouse_id, custom_code)。", + "comboGoods.create:新增可选入参 custom_code,如果非空则校验同货主非删除记录中 unique;返回新增 custom_code 字段。", + "comboGoods.update:新增可选入参 custom_code,如果非空则校验同货主非删除记录中 unique(排除自身 id)。", + "comboGoods.list:返回每条记录新增 custom_code 字段。", + "comboGoods.search:搜索条件扩大为 custom_code LIKE / combo_code LIKE / combo_name LIKE,custom_code 匹配项按 ORDER BY CASE 排在前面;返回新增 custom_code 字段。" + ], + "type": "updated" + }, + { + "version": "2026.06.21-system-comboGoods-03", + "date": "2026-06-21", + "summary": "stock.warehouse.search 新增 mode=\"combo\" 组合商品查询模式,新增 id/custom_code 参数,补充组合商品响应结构", + "methods": [ + "stock.warehouse.search" + ], + "notes": [ + "新增入参 mode(查询模式,传 \"combo\" 时搜索组合商品),id(mode=combo 时按组合商品ID精确查询),custom_code(mode=combo 时按自定义编码模糊查询)", + "原有 keyword 参数在 mode=combo 时模糊匹配 combo_code / combo_name / custom_code", + "mode=combo 响应结构新增 combo_code、combo_name、custom_code、items(子商品数组含 item_goods_sku_id/item_quantity)、simpleNotation(stock_id|数量格式)、nameNotation(【数量】商品名称格式)", + "mode=combo 时不返回 stock 模式特有的字段(item_code/goods_code/item_name/sku_property/stock_unit/quantity/locked_quantity/brand_name/item_type/barcodes/store_stock/效期字段/storage)", + "with_stock 和 is_batch 参数在 mode=combo 时不生效" + ], + "type": "updated" + }, + { + "version": "2026.06.22-system-wavePickTaskList-01", + "date": "2026-06-22", + "summary": "order.wave.wavePickTaskList 响应新增 wave_list 数组:每个拣货任务返回关联波次列表", + "methods": [ + "order.wave.wavePickTaskList" + ], + "notes": [ + "wavePickTaskList 响应 list 每项新增 wave_list 数组字段,通过批量查询 wms_wave_pick_task_wave 表获取关联波次详情。", + "wave_list 每项包含:wave_id(波次ID)、wave_no(波次号)、box_no(框号)、status(波次关联状态)、bind_time(绑定时间)、pick_time(拣货完成时间)。", + "无需额外入参,默认对所有拣货任务返回 wave_list;查询为空时返回空数组 []。", + "同步更新 methods/system.json 响应文档。" + ], + "type": "updated", + "module": "order.wave" + }, + { + "version": "2026.06.22-system-order-export-mode-01", + "date": "2026-06-22", + "summary": "order.export 新增 export_mode 参数:支持 waybill(默认,按运单展开)与 item(按商品明细展开)两种导出模式", + "methods": [ + "order.export" + ], + "notes": [ + "新增入参 export_mode/exportMode,枚举值:waybill(默认)— 按运单号展开,每运单一组,items_detail 列汇总商品;item — 按商品明细展开,每商品一行,运单信息汇总填充。", + "方法层(OrderIndexService.export)新增 export_mode/exportMode 解构并透传到 systems.orderExport.exportOrders。", + "同步更新 methods/system.json 文档:description 补充 export_mode 说明,params 新增 export_mode/exportMode 条目。", + "order.export 导出的列新增:业务类型、运单接口、包材ID、包材编码、包材名称。" + ], + "type": "updated", + "module": "order.index" + }, + { + "version": "2026.06.22-system-directInbound-01", + "date": "2026-06-22", + "summary": "新增 storage.directInbound 导入/PDA直接入库模块:getItems(获取入库信息)、addItem(增量添加商品)、commit(提交完成入库并回传)", + "methods": [ + "storage.directInbound.getItems", + "storage.directInbound.addItem", + "storage.directInbound.commit" + ], + "notes": [ + "新增 storage.directInbound 模块,用于非收货单途径的导入/PDA 直接入库场景。", + "storage.directInbound.getItems:根据入库单号获取入库明细及已有的导入/PDA 入库记录,返回每项的可入库余量。", + "storage.directInbound.addItem:按 stock_id 增量添加导入/PDA 入库记录,累加超过该 stock_id 在入库单中的计划总量时拒绝。支持 import(导入)和 pda(PDA)两种方式。", + "storage.directInbound.commit:提交确认完成入库,按实收数量写入 wms_storage 库存和 wms_storage_transaction 流水,同 stock_id 多条明细只写一次库存,更新入库单状态为 COMPLETED 并同步 sync_status=SUCCESS,异步触发奇门/API 回传(按实收数量回传)。不足量提交时未入库商品跳过。", + "新增数据表 wms_inbound_direct_log(migration: 20260622100000-create-wms-inbound-direct-log.js):记录非收货单途径入库操作,含 warehouse_id、stock_id、quantity、inbound_type(import/pda)、entry_order_id、operator 等字段。模型文件:app/model/inbound_direct_log.js。", + "新增操作日志:addItem 记录 DIRECT_INBOUND_ADD(异步),commit 记录 DIRECT_INBOUND_COMMIT(事务内)。commit 响应返回 order_status=COMPLETED 和 sync_status=SUCCESS。", + "涉及文件:app/service/systems/inbound_direct_log.js(业务层)、app/service/systemMethods/storage/direct_inbound.js(包装层)、app/model/inbound_direct_log.js、database/migrations/20260622100000-create-wms-inbound-direct-log.js、methods/system.json(新增导入/PDA入库模块)。", + "E2E 测试:test/e2e_direct_inbound.test.js(53项断言全覆盖)。" + ], + "type": "added", + "module": "storage.directInbound" + }, + { + "version": "2026.06.22-system-directInbound-02", + "date": "2026-06-22", + "summary": "storage.directInbound.addItem 新增批量模式(items 数组),getItems 响应 summary 新增 total_import/total_pda 分类型汇总", + "methods": [ + "storage.directInbound.addItem", + "storage.directInbound.getItems" + ], + "notes": [ + "addItem 新增批量模式:支持传入 items 数组一次添加多条商品,每项含 stock_id/quantity/inbound_type/remark。单条模式(stock_id/quantity/inbound_type 顶层字段)保持向后兼容。批量模式下所有商品共享同一个入库单状态校验,任一商品校验失败整批拒绝。", + "addItem 批量模式响应结构:{ count, total_quantity, items: [...] },items 每项含 id/stock_id/quantity/inbound_type/plan_quantity/existing_before/existing_after/remaining。", + "getItems 响应 summary 新增 total_import(导入入库总数)和 total_pda(PDA入库总数)字段。", + "同步更新 methods/system.json 文档。" + ], + "type": "updated", + "module": "storage.directInbound" + }, + { + "version": "2026.06.22-system-directInbound-03", + "date": "2026-06-22", + "summary": "storage.directInbound 新增 space_id 库位支持:addItem 支持传入 space_id(单条和批量),commit 从入库记录取 space_id 写入 wms_storage 替代硬编码 1", + "methods": [ + "storage.directInbound.addItem", + "storage.directInbound.commit", + "storage.directInbound.getItems" + ], + "notes": [ + "addItem 新增可选入参 space_id(单条模式顶层字段 / 批量模式 items[].space_id),指定存放库位ID,关联 wms_location_space.id。", + "wms_inbound_direct_log 表新增 space_id 字段(migration: 20260622110000-add-space-id-to-wms-inbound-direct-log.js)。", + "commit 从入库记录中取第一个非空 space_id 写入 wms_storage,无记录时兜底使用库位 1。", + "getItems 响应中 direct_logs 每条记录包含 space_id 字段。", + "同步更新 methods/system.json 文档及模型文件。" + ], + "type": "updated", + "module": "storage.directInbound" + }, + { + "version": "2026.06.23-system-01", + "date": "2026-06-23", + "summary": "入库单(wms_entry_order)新增 CREATED 状态:order_status ENUM 从 CREATING/PENDING/CONFIRMED/PARTIAL_RECEIVED/COMPLETED/CANCELLED 扩展为 CREATING/CREATED/PENDING/CONFIRMED/PARTIAL_RECEIVED/COMPLETED/CANCELLED;默认值从 PENDING 变更为 CREATED;validTransitions 增加 CREATED 节点(CREATED→PENDING/CANCELLED,CREATING→CREATED/CANCELLED)", + "methods": [ + "storage.entry.list", + "storage.entry.get", + "storage.entry.cancel", + "storage.entry.completeEntry", + "storage.entry.bindReceivingDetails" + ], + "notes": [ + "Model 层:app/model/entry_order.js order_status ENUM 新增 CREATED,默认值从 PENDING 变更为 CREATED", + "Service 层:app/service/systems/entry_order.js addOrder 创建后状态从 CREATING→CREATED,validTransitions 增加 CREATED 节点", + "Service 层:app/service/systems/storage/entry.js createEntry 默认状态 PENDING→CREATED", + "Service 层:app/service/systems/storage/inventory.js 快捷入库默认 CREATED", + "文档同步:storage.entry.list where.order_status 枚举补充 CREATED;storage.entry.get description 补充 order_status 枚举含 CREATED;storage.entry.cancel 补充 CREATED 可作废说明;storage.entry.completeEntry/bindReceivingDetails 补充可操作状态含 CREATED" + ], + "type": "updated", + "module": "storage.entry" + }, + { + "version": "2026.06.23-system-02", + "date": "2026-06-23", + "summary": "入库单 CREATED 状态限制:CREATED 状态不允许绑定货物和完成入库,仅 PENDING/CONFIRMED/PARTIAL_RECEIVED 状态可操作", + "methods": [ + "storage.entry.cancel", + "storage.entry.completeEntry", + "storage.entry.bindReceivingDetails", + "storage.entry.unbindReceivingDetails" + ], + "notes": [ + "completeEntry / bindReceivingDetails / unbindReceivingDetails / commitEntryWithBindings 的可操作状态从原来的白名单(包含 CREATED)改为 PENDING / CONFIRMED / PARTIAL_RECEIVED,排除 CREATED。", + "CREATED 状态仅允许确认入库(→PENDING)或作废(→CANCELLED)。", + "storage.entry.cancel 补充明确 COMPLETED 状态不可作废,CREATED 可作废。", + "同步更新对应 method 的 description、errors 描述。" + ], + "type": "updated", + "module": "storage.entry" + }, + { + "version": "2026.06.23-system-03", + "date": "2026-06-23", + "summary": "storage.entry.cancel:CONFIRMED(已确认)状态不再允许作废,仅 CREATED 和 PENDING 可作废", + "methods": [ + "storage.entry.cancel" + ], + "notes": [ + "canCancel() 白名单移除 CONFIRMED,仅保留 CREATED 和 PENDING", + "validTransitions 中 CONFIRMED 不再可转为 CANCELLED", + "cancel() 方法新增 CONFIRMED 状态拦截,返回 400:已确认入库单不允许作废,请先完成收货", + "PARTIAL_RECEIVED 仍可作废,COMPLETED 不允许作废(行为不变)", + "更新 description 明确各状态可作废规则,errors 中补充 CONFIRMED 不可作废的说明" + ], + "type": "updated", + "module": "storage.entry" + }, + { + "version": "2026.06.23-system-04", + "date": "2026-06-23", + "summary": "入库单状态从 7 个简化为 5 个:移除 CONFIRMED 和 PARTIAL_RECEIVED,最终状态为 CREATING/CREATED/PENDING/COMPLETED/CANCELLED;同步更新 storage.entry 所有 method 的状态枚举和错误信息描述", + "methods": [ + "storage.entry.list", + "storage.entry.get", + "storage.entry.cancel", + "storage.entry.completeEntry", + "storage.entry.bindReceivingDetails", + "storage.entry.unbindReceivingDetails" + ], + "notes": [ + "wms_entry_order.order_status ENUM 从 CREATING/CREATED/PENDING/CONFIRMED/PARTIAL_RECEIVED/COMPLETED/CANCELLED 简化为 CREATING/CREATED/PENDING/COMPLETED/CANCELLED", + "storage.entry.list: where.order_status 描述和 where 参数描述中的状态枚举同步更新", + "storage.entry.get: entryOrder.order_status 描述同步更新", + "storage.entry.cancel: 移除 PARTIAL_RECEIVED 可作废和 CONFIRMED 不可作废的描述,仅保留 CREATED 和 PENDING 可作废,COMPLETED 不可作废", + "storage.entry.completeEntry: 可完成状态从 PENDING/CONFIRMED/PARTIAL_RECEIVED 改为仅 PENDING", + "storage.entry.bindReceivingDetails: 可操作状态从 PENDING/CONFIRMED/PARTIAL_RECEIVED 改为仅 PENDING", + "storage.entry.unbindReceivingDetails: 可操作状态从 PENDING/CONFIRMED/PARTIAL_RECEIVED 改为仅 PENDING", + "cancel() 取消 CONFIRMED 状态拦截(状态已不存在),COMPLETED 拦截保持不变" + ], + "type": "updated" + }, + { + "version": "2026.06.23-system-05", + "date": "2026-06-23", + "summary": "入库单状态语义调整:CREATED=已创建待审核,PENDING=已审核;同步更新 storage.entry 所有 method 的 description 中状态说明", + "methods": [ + "storage.entry.list", + "storage.entry.get", + "storage.entry.cancel", + "storage.entry.completeEntry", + "storage.entry.bindReceivingDetails", + "storage.entry.unbindReceivingDetails" + ], + "notes": [ + "CREATED 含义从\"已创建\"改为\"已创建待审核\"(需审核后才能绑定和完成入库)", + "PENDING 含义从\"待收货/收货中\"改为\"已审核\"(审核通过,可绑定和完成入库)", + "CREATED→PENDING 步骤语义:绑定审核", + "addOrder() 新增可选参数 autoReview(boolean,默认 false),false 创建后状态 CREATED(需审核),true 创建后状态 PENDING(自动审核通过)", + "快捷入库 quickPutaway 内部流程改为调用 addOrder({autoReview:true}) → bindReceivingDetails → commitEntryWithBindings,不再直接写库存,对外返回格式不变", + "storage.entry.list / storage.entry.get description 中补充 CREATED/PENDING 语义说明", + "storage.entry.cancel description 中补充可作废状态说明", + "storage.entry.completeEntry description 中补充可完成状态说明", + "storage.entry.bindReceivingDetails / storage.entry.unbindReceivingDetails description 中补充可绑定/解绑状态说明" + ], + "type": "updated" + }, + { + "version": "2026.06.23-system-06", + "date": "2026-06-23", + "summary": "storage.inventory.quickPutaway description 更新:补充内部已改为走 addOrder→bind→commit 链路,不再直接写库存", + "methods": [ + "storage.inventory.quickPutaway" + ], + "notes": [ + "快捷入库 quickPutaway 内部流程改为调用 addOrder({autoReview:true}) → bindReceivingDetails → commitEntryWithBindings,不再直接写库存,外部返回格式不变", + "description 中补充内部调用链路说明" + ], + "type": "updated" + }, + { + "version": "2026.06.23-system-07", + "date": "2026-06-23", + "summary": "storage.entry 大范围清理:删除 bindReceivingDetails/unbindReceivingDetails(明细级绑定已弃用),更新 completeEntry 为纯状态变更(不再做库存写入/异步匹配)", + "methods": [ + "storage.entry.bindReceivingDetails", + "storage.entry.unbindReceivingDetails", + "storage.entry.completeEntry" + ], + "notes": [ + "storage.entry.bindReceivingDetails:已从代码中删除,明细级绑定收货单功能下线。库存写入统一由 storage.inventory.matchPutaway 完成。", + "storage.entry.unbindReceivingDetails:已从代码中删除,明细级解绑功能下线。", + "storage.entry.completeEntry:改为纯状态变更(PENDING → COMPLETED),不再做库存写入和异步匹配回调。库存写入统一由 storage.inventory.matchPutaway 完成。" + ], + "type": "updated" + }, + { + "version": "2026.06.23-system-08", + "date": "2026-06-23", + "summary": "storage.inventory 清理:删除 quickPutaway(快捷入库已下线,统一由 matchPutaway 完成匹配入库)", + "methods": [ + "storage.inventory.quickPutaway" + ], + "notes": [ + "storage.inventory.quickPutaway:已从代码中删除,快捷入库功能下线。请使用 storage.inventory.matchPutaway 替代。" + ], + "type": "removed" + }, + { + "version": "2026.06.23-system-09", + "date": "2026-06-23", + "summary": "入库流程弃用清理:bindReceivingDetails/unbindReceivingDetails 标记为已删除并补充弃用原因,completeEntry 明确不涉及库存写入", + "methods": [ + "storage.entry.bindReceivingDetails", + "storage.entry.unbindReceivingDetails", + "storage.entry.completeEntry" + ], + "notes": [ + "storage.entry.bindReceivingDetails 与 storage.entry.unbindReceivingDetails 已从代码中移除,入库单与收货单关系改为 wms_entry_order_receiving 主表级关联,不再需要逐明细绑定/解绑。", + "wms_entry_receiving_binding 表不再写入新数据。", + "storage.entry.completeEntry 仅做状态变更(PENDING→COMPLETED),库存写入统一由 storage.inventory.matchPutaway 完成。", + "commitEntryWithBindings(内部方法)不再使用,库存写入统一走 matchPutaway 链路。" + ], + "type": "updated" + }, + { + "version": "2026.06.23-system-10", + "date": "2026-06-23", + "summary": "quickPutaway 弃用说明完善:明确替代方案为 matchPutaway;matchPutaway 标明为目前唯一库存写入入库链路", + "methods": [ + "storage.inventory.quickPutaway", + "storage.inventory.matchPutaway" + ], + "notes": [ + "storage.inventory.quickPutaway 已从代码中移除,替代方案为 storage.inventory.matchPutaway(支持多收货单+多入库单批量匹配入库)。", + "storage.inventory.matchPutaway 是目前唯一的库存写入入库链路,入库单状态变更由 storage.entry.completeEntry 单独处理。", + "本次为文档补充说明,不涉及代码变更。" + ], + "type": "updated" + }, + { + "version": "2026.06.23-system-11", + "date": "2026-06-23", + "summary": "删除 storage.receiving.getAvailableInboundQuantity:该方法依赖已弃用的 wms_entry_receiving_binding 明细绑定表,已从代码中移除", + "methods": [ + "storage.receiving.getAvailableInboundQuantity" + ], + "notes": [ + "该方法原用于按 stock_id 查询已审核收货单中各明细的可入库数量(actual_quantity - stored_quantity - pending_allocated_quantity)。", + "由于 wms_entry_receiving_binding 明细绑定表已弃用,入库单与收货单的关联改为通过 wms_entry_order_receiving 主表级关联,该查询方法不再适用。", + "替代方案:使用 storage.entry.get 查询入库单详情,通过顶层 receivingBindings 获取关联的收货单信息。" + ], + "type": "removed" + }, + { + "version": "2026.06.23-system-12", + "date": "2026-06-23", + "summary": "storage.entry.get 响应结构变更:不再返回 items[].bindings(明细级绑定),改为返回顶层 receivingBindings(主表级关联收货单信息)", + "methods": [ + "storage.entry.get" + ], + "notes": [ + "移除 items[].bindings(明细级绑定,原基于 wms_entry_receiving_binding 表),该绑定表已弃用。", + "新增顶层 receivingBindings(wms_entry_order_receiving 主表级关联),每项含 id/receiving_id/receiving(含 id/receiving_number/status/storage_status/created_at)。", + "items 中保留 external_item_code/external_item_id/warehouse_item_code/warehouse_item_name/warehouse_item_spec 等扁平化字段。", + "响应结构变更与 storage.directInbound.getItems 的返回结构对齐,后者同样使用顶层 receivingBindings。" + ], + "type": "modified" + }, + { + "version": "2026.06.23-system-13", + "date": "2026-06-23", + "summary": "新增 storage.entry.* 下 4 个 DirectInbound 方法:getDirectInboundItems、addItem、commit、removeItem,原 storage.directInbound.* 方法保留向后兼容并标记 deprecated", + "methods": [ + "storage.entry.getDirectInboundItems", + "storage.entry.addItem", + "storage.entry.commit", + "storage.entry.removeItem" + ], + "notes": [ + "storage.entry.getDirectInboundItems:获取入库单的导入/PDA 入库信息,参数与响应格式同原 storage.directInbound.getItems", + "storage.entry.addItem:按商品增量添加导入/PDA 入库记录(支持单条和批量),参数与响应格式同原 storage.directInbound.addItem", + "storage.entry.commit:提交确认完成导入/PDA 入库,按实收数量写入库存并异步回传奇门/API,参数与响应格式同原 storage.directInbound.commit", + "storage.entry.removeItem:移除一条导入/PDA 入库记录,参数与响应格式同原 storage.directInbound.removeItem", + "底层 inbound_direct_log.js 实现不变,仅入口从 storage.directInbound 模块迁入 storage.entry 模块" + ], + "type": "added" + }, + { + "version": "2026.06.23-system-14", + "date": "2026-06-23", + "summary": "storage.directInbound.* 下 4 个方法标记 deprecated,指向 storage.entry.* 下对应新方法", + "methods": [ + "storage.directInbound.getItems", + "storage.directInbound.addItem", + "storage.directInbound.commit", + "storage.directInbound.removeItem" + ], + "notes": [ + "storage.directInbound.getItems → 替代方法 storage.entry.getDirectInboundItems", + "storage.directInbound.addItem → 替代方法 storage.entry.addItem", + "storage.directInbound.commit → 替代方法 storage.entry.commit", + "storage.directInbound.removeItem → 替代方法 storage.entry.removeItem", + "旧方法保留向后兼容,参数与响应格式不变,仅入口模块变更" + ], + "type": "deprecated" + }, + { + "version": "2026.06.23-system-15", + "date": "2026-06-23", + "summary": "storage.inventory.matchPutaway 标记 deprecated,替代方案为 storage.entry.commit", + "methods": [ + "storage.inventory.matchPutaway" + ], + "notes": [ + "storage.inventory.matchPutaway 已弃用,请迁移至 storage.entry.commit", + "commit 提供导入/PDA 入库完成确认功能,按实收数量写入库存并异步回传" + ], + "type": "deprecated" + }, + { + "version": "2026.06.23-system-16", + "date": "2026-06-23", + "summary": "清理已弃用 method 条目:从 system.json 删除 storage.entry.bindReceivingDetails、storage.entry.unbindReceivingDetails、storage.inventory.matchPutaway 三个已从代码中移除的 method 文档条目", + "methods": [ + "storage.entry.bindReceivingDetails", + "storage.entry.unbindReceivingDetails", + "storage.inventory.matchPutaway" + ], + "notes": [ + "storage.entry.bindReceivingDetails:已从代码中删除,明细级绑定收货单功能下线。入库单与收货单关系改为 wms_entry_order_receiving 主表级关联。", + "storage.entry.unbindReceivingDetails:已从代码中删除,明细级解绑功能下线。", + "storage.inventory.matchPutaway:已从代码中删除,匹配入库功能下线。替代方案为 storage.entry.commit。", + "storage.inventory.quickPutaway:之前已标记 [已删除],本次确认条目保留(与 matchPutaway 同一 group,保留作为历史参考)。", + "storage.entry.create / addDetail / deleteDetail / detailChange:systems 层方法已删除,但从未在 system.json 中暴露为 API method,无需文档变更。" + ], + "type": "removed" + }, + { + "version": "2026.06.23-system-17", + "date": "2026-06-23", + "summary": "storage.entry.get 响应新增仓库库存、条码、入库进度字段", + "methods": [ + "storage.entry.get" + ], + "notes": [ + "items 每项新增 warehouse_quantity(仓库库存总量)、warehouse_locked_quantity(锁定数量)、warehouse_is_batch_mgmt(是否批次管理)、warehouse_is_shelf_life_mgmt(是否效期管理)、warehouse_image_url(商品图片URL)、warehouse_is_images(是否有图片)", + "items 每项新增 barcodes(条码列表,每项含 id/barcode/sku_property)", + "items 每项新增 direct_inbound_quantity(导入/PDA已入库数量)、remaining_quantity(剩余可入库数量)", + "同步更新 response 字段定义,将原有概要描述展开为逐字段说明", + "仅文档同步,不改业务代码" + ], + "type": "updated", + "module": "storage.entry" + }, + { + "version": "2026.06.24-system-01", + "date": "2026-06-24", + "summary": "新增批量绑定入库单明细与收货单明细接口 storage.entry.bindReceivingDetails,支持明细级数量分配与部分成功", + "methods": [ + "storage.entry.bindReceivingDetails" + ], + "notes": [ + "新增 storage.entry.bindReceivingDetails:批量绑定入库单明细与收货单明细,支持明细级数量分配与部分成功", + "storage.entry.get 追加 available_receiving_details 字段加载可匹配的收货单明细" + ], + "type": "addition" + }, + { + "version": "2026.06.24-system-02", + "date": "2026-06-24", + "summary": "storage.entry.bindReceivingDetails:response.failed 字段从简单 reason 描述升级为结构化错误返回(含 error_code、message、detail);同步更新 400 错误说明", + "methods": [ + "storage.entry.bindReceivingDetails" + ], + "notes": [ + "response.failed 新增 items 定义,每项含 entry_item_id、receiving_detail_id、allocated_quantity、error_code、message、detail", + "error_code 枚举:ENTRY_ITEM_NOT_FOUND、STOCK_NOT_FOUND、RECEIVING_DETAIL_MISMATCH、RECEIVING_DETAIL_NOT_FOUND、INSUFFICIENT_AVAILABLE_QUANTITY、ENTRY_ORDER_STATUS_INVALID", + "400 错误说明更新:入库单状态不允许绑定时,所有 bindings 均返回 failed 且 error_code 为 ENTRY_ORDER_STATUS_INVALID" + ], + "type": "updated" + }, + { + "version": "2026.06.24-system-03", + "date": "2026-06-24", + "summary": "新增 storage.entry.quickInbound 快捷直入/虚拟入库接口", + "methods": [ + "storage.entry.quickInbound" + ], + "notes": [ + "新增 quickInbound 方法:入库单所有商品按明细数量一键直入虚拟库位(space_id=2),跳过收货/质检流程", + "支持状态:CREATED、PENDING 状态的入库单可执行", + "拒绝状态:CANCELLED(已作废)、COMPLETED(已完成)", + "事务内操作:更新入库明细收货量、累加库存总量、写入库存流水、写入虚拟库位库存、变更入库单状态为 COMPLETED", + "事务外异步回传奇门/API" + ], + "type": "addition" + }, + { + "version": "2026.06.24-system-04", + "date": "2026-06-24", + "summary": "收窄 storage.entry.quickInbound 状态约束:仅允许 CREATED 状态执行快捷直入", + "methods": [ + "storage.entry.quickInbound" + ], + "notes": [ + "收窄状态约束:仅允许 CREATED 状态执行快捷直入,PENDING 状态不再允许" + ], + "type": "updated" + }, + { + "version": "2026.06.24-system-05", + "date": "2026-06-24", + "summary": "修正 storage.entry.quickInbound errors[4] message 以匹配代码实现:改为动态状态描述", + "methods": [ + "storage.entry.quickInbound" + ], + "notes": [ + "errors[4].message 从「入库单状态不允许快捷直入(仅支持CREATED状态)」改为「入库单状态不允许快捷直入,当前状态:非CREATED(如PENDING等)」,反映代码中 `${entryOrder.order_status}` 动态模板特性" + ], + "type": "updated" + }, + { + "version": "2026.06.24-system-06", + "date": "2026-06-24", + "summary": "新增入库单与收货单商品对照预览接口", + "methods": [ + "storage.entry.receivingCompare" + ], + "notes": [ + "新增 storage.entry.receivingCompare 方法:给定入库单ID和收货单ID,返回入库商品与收货商品的逐行对照视图。", + "comparison 列表中每项含 match_status(matched/entry_only),以及入库侧和收货侧的商品与数量信息。", + "receiving_only 列表包含仅存在于收货单中的商品明细。", + "summary 提供 total_entry_items、matched_items、entry_only_items、receiving_only_items 汇总统计。", + "纯只读接口,不产生任何数据写入或状态变更。" + ], + "type": "addition" + }, + { + "version": "2026.06.24-system-07", + "date": "2026-06-24", + "summary": "setting.warehouse 模块新增 7 个发件人信息字段到 subject_config", + "methods": [ + "setting.warehouse.getSettings", + "setting.warehouse.saveSettings" + ], + "notes": [ + "在 getSettings 的 response 中新增 subject_config.sender_name(发件人姓名)、sender_tel(发件人电话)、province_name(省份)、city_name(城市)、district_name(区/县)、town_name(镇/街道)、address(详细地址)共 7 个字段,均为可选字符串,默认空。", + "在 saveSettings 的 params 中新增对应的 7 个入参字段,source 为 body.subject_config,均为可选字符串,默认空,并标注 maxLength。", + "字段 key 与 store_warehouse.policy_config 中发件人字段命名完全一致,统一仓库级发件人默认值配置。", + "getFieldMeta 接口无需修改文档——其返回的字段元信息由 WAREHOUSE_SETTING_FIELDS 定义在运行时自动生成,新增字段会随代码自动纳入返回列表。" + ], + "type": "updated", + "module": "setting.warehouse" + }, + { + "version": "2026.06.25-system-01", + "date": "2026-06-25", + "summary": "新增 storage.entry.bindReceiving 接口:将收货单绑定到入库单(主表级关联,不做明细数量分配)", + "methods": [ + "storage.entry.bindReceiving" + ], + "notes": [ + "新增入库单与收货单的主表绑定接口,与已有的 storage.entry.bindReceivingDetails(明细级绑定)区分:bindReceiving 仅建立 wms_entry_order_receiving 主表关联,不做明细数量分配。", + "入库单需为 CREATED 或 PENDING 状态;收货单需存在、同仓库且未取消。", + "支持部分成功模式:逐条校验收货单,校验通过的建立绑定,不通过的返回 error_code 和 message。", + "响应包含 success(成功列表)、failed(失败列表)、success_count、failed_count。" + ], + "type": "addition" + }, + { + "version": "2026.06.25-system-02", + "date": "2026-06-25", + "summary": "storage.entry.bindReceiving:新增 OWNER_MISMATCH 错误码,用于收货单与入库单货主不一致校验", + "methods": [ + "storage.entry.bindReceiving" + ], + "notes": [ + "在 storage.entry.bindReceiving 的 errors 数组中新增 OWNER_MISMATCH(收货单与入库单货主不一致)错误码。", + "同步更新 response.failed.error_code 的枚举描述,补充 OWNER_MISMATCH。" + ], + "type": "updated", + "module": "storage.entry" + }, + { + "version": "2026.06.25-system-03", + "date": "2026-06-25", + "summary": "storage.entry.bindReceiving:新增收货单未审核错误码 RECEIVING_NOT_REVIEWED", + "methods": [ + "storage.entry.bindReceiving" + ], + "notes": [ + "在 errors 数组中新增错误码 RECEIVING_NOT_REVIEWED(收货单未审核),用于标识绑定前收货单尚未完成审核的场景。", + "同步更新 response.failed.items.properties.error_code.description,在可能值列表中补充 RECEIVING_NOT_REVIEWED。" + ], + "type": "updated" + }, + { + "version": "2026.06.25-system-04", + "date": "2026-06-25", + "summary": "storage.entry.list 响应新增 receivingBindings 和 hasReceiving 字段,where 新增 hasReceiving 虚拟筛选条件", + "methods": [ + "storage.entry.list" + ], + "notes": [ + "响应 list 数组每项新增 receivingBindings(收货单绑定列表,主表级关联)和 hasReceiving(是否存在收货单绑定,boolean)字段。", + "入参 where 新增 hasReceiving 虚拟筛选字段,传 true/false 筛选已绑定/未绑定收货单的入库单,内部通过 wms_entry_order_receiving 表查询实现。", + "同步更新 description 以说明 hasReceiving 虚拟筛选的使用方式。" + ], + "type": "updated" + }, + { + "version": "2026.06.26-system-01", + "date": "2026-06-26", + "summary": "storage.entry.receivingCompare 支持多收货单对照预览", + "methods": [ + "storage.entry.receivingCompare" + ], + "notes": [ + "支持多个收货单ID对照预览(新增 receiving_ids 数组入参,优先于 receiving_id 使用)", + "入参 receiving_id 从 required 改为 optional,与 receiving_ids 二选一", + "出参结构调整为 comparisons[] 数组(多收货单),新增 errors[] 和 total_summary", + "向后兼容原 receiving_id 单值传参(底层自动转为单元素数组)", + "新增 400 错误码:receiving_ids 或 receiving_id 必填", + "移除 404 错误码:收货单不存在(已改为在 comparisons[]/errors[] 中以 status=error 形式返回)" + ], + "type": "enhancement" + }, + { + "version": "2026.06.26-system-02", + "date": "2026-06-26", + "summary": "storage.receiving.getReceivingList 新增 filterDepleted 可选参数;storage.entry.receivingCompare 返回值 receiving_only 字段新增 receiving_allocated 和 receiving_available 说明", + "methods": [ + "storage.receiving.getReceivingList", + "storage.entry.receivingCompare" + ], + "notes": [ + "storage.receiving.getReceivingList:params 新增 filterDepleted(boolean, 默认 false),用于过滤掉无可再用量的收货单(所有明细已被其他入库单 committed 绑定占满)。", + "storage.entry.receivingCompare:response 中 receiving_only 字段的 description 补充 receiving_allocated(已分配数量)和 receiving_available(可再用量)两个子字段说明。" + ], + "type": "updated" + }, + { + "version": "2026.06.26-system-03", + "date": "2026-06-26", + "summary": "storage.receiving.getReceivingList:新增可选参数 entry_order_id,按入库单商品交集过滤收货单列表", + "methods": [ + "storage.receiving.getReceivingList" + ], + "notes": [ + "新增可选参数 entry_order_id(number),传入入库单 ID 后只返回至少有一条明细的 system_product_id 在入库单明细中存在的收货单。", + "与现有 filterDepleted 参数可组合使用,二者取交集。", + "不传则不过滤,保持原有行为不变。" + ], + "type": "updated" + }, + { + "version": "2026.06.27-system-01", + "date": "2026-06-27", + "summary": "新增 storage.entry.reviewEntry 接口:审核入库单(CREATED→PENDING),需绑定收货单", + "methods": [ + "storage.entry.reviewEntry" + ], + "notes": [ + "新增入库单审核接口,支持 CREATED→PENDING 状态流转。", + "审核前置条件:入库单必须已绑定收货单(EntryOrderReceiving 存在关联记录)。", + "审核通过后写入操作日志(ENTRY_ORDER_REVIEW)。" + ], + "type": "added" + }, + { + "version": "2026.06.29-system-01", + "date": "2026-06-29", + "summary": "storage.inventory.quickPutaway 重新实现:收货单快捷转入库单", + "methods": [ + "storage.inventory.quickPutaway" + ], + "notes": [ + "此前已从代码中删除(2026.06.23-system-08),现由 wms-dev-agent 重新实现。", + "核心流程:参数校验 → 加载收货单及明细 → 检查货主配置 policy_config.allow_receiving_quick_putaway → 按 stock_id(system_product_id)分组合并数量 → 创建入库单 SCRK(自动审批到 PENDING)→ 写入 wms_entry_order_receiving 主表级绑定 → 更新收货单 storage_status 为 partial → 更新收货单明细 storage_status/stored_quantity → 提交事务。", + "前置条件:收货单状态为 completed 且 is_review=true(已审核),货主仓库签约配置 allow_receiving_quick_putaway=1。", + "与旧实现的区别:不涉及 wms_entry_receiving_binding 明细级绑定,使用 wms_entry_order_receiving 主表级关联;直接创建入库单并写入绑定,不再走 matchPutaway 匹配链路。", + "返回:entry_order_id、entry_order_code(SCRK 格式)、order_status(PENDING)、receiving_id、total_lines、total_quantity。" + ], + "type": "addition" + }, + { + "version": "2026.06.29-system-02", + "date": "2026-06-29", + "summary": "storage.entry.list:quickWhere 搜索范围扩展,新增收货单 ID(receiving_id)支持 PDA 扫描托盘唛头搜索绑定的入库单", + "methods": [ + "storage.entry.list" + ], + "notes": [ + "quickWhere 搜索字段新增 receiving_id(收货单 ID / 托盘唛头),通过 wms_entry_order_receiving 绑定表关联搜索。", + "同步更新 description 和 where 参数的 description,明确 quickWhere 完整搜索字段列表:entry_order_code、purchase_order_code、supplier_name、store_name、warehouse_name、receiving_id。" + ], + "type": "updated", + "module": "storage" + }, + { + "version": "2026.06.29-system-03", + "date": "2026-06-29", + "summary": "新增 storage.receiving.scanDetail 接口:PDA 上架扫码定位收货明细", + "methods": [ + "storage.receiving.scanDetail" + ], + "notes": [ + "新增 storage.receiving.scanDetail(PDA专用):通过 entry_order_id + barcode 扫码快速定位收货明细。", + "搜索逻辑:纯数字 barcode 优先按明细 ID 精确匹配(托盘唛头),未命中则模糊匹配商品条码;非纯数字仅模糊匹配商品条码。", + "入参:entry_order_id(必填 number)、barcode(必填 string)。", + "出参:detail_id、receiving_id、barcode、product_name、actual_quantity、receiving_status。", + "错误码:入库单不存在或无权访问、该入库单尚未关联收货单、未找到匹配的收货明细。" + ], + "type": "added" + }, + { + "version": "2026.06.29-system-04", + "date": "2026-06-29", + "summary": "storage.receiving.scanDetail 响应结构从单条改为列表:返回 { list, total } 支持同一条码匹配多条明细", + "methods": [ + "storage.receiving.scanDetail" + ], + "notes": [ + "响应结构变更:原返回 data.detail_id/data.receiving_id 等单条字段,现改为顶层 list 数组 + total 计数。", + "同一条码可能匹配到多条收货明细(不同收货单的同一商品),以列表形式返回所有匹配结果。", + "list 中每条明细包含 detail_id/receiving_id/barcode/product_name/actual_quantity/receiving_status。", + "补充错误码:用户未绑定仓库、入库单ID/条码为空、未找到可用的收货明细、500服务器错误。", + "PDA专用接口,description 更新说明匹配逻辑。" + ], + "type": "updated", + "module": "storage.receiving" + }, + { + "version": "2026.06.30-system-01", + "date": "2026-06-30", + "summary": "新增 storage.entry.containerList:PDA 上架时拉取入库单绑定收货单中指定商品的可用容器列表", + "methods": [ + "storage.entry.containerList" + ], + "notes": [ + "新增接口 storage.entry.containerList,用于 PDA 上架场景拉取入库单已绑定收货单中指定 stock_id 的可用收货明细(容器)列表。", + "入参:entry_order_id(入库单ID,必填)、stock_id(商品 stock_id,必填)。", + "出参:data.list 返回可用明细列表,每项含 detail_id、receiving_id、barcode、product_name、actual_quantity、receiving_status;data.total 为总数。", + "已绑定占用的收货明细(wms_entry_receiving_binding 中已有记录且未软删除)会被排除。", + "PDA 专用接口,无需额外鉴权(isNeedAuth=false)。" + ], + "type": "added" + }, + { + "version": "2026.06.30-system-02", + "date": "2026-06-30", + "summary": "storage.entry.addItem 入参变更:entry_order_code → entry_order_id(number);quantity 改为可选(传入 receiving_detail_id 时自动计算);新增 receiving_detail_id/allocated_quantity 参数支持 PDA 上架收货明细绑定模式;space_id 绑定模式下必填", + "methods": [ + "storage.entry.addItem" + ], + "notes": [ + "入参 entry_order_code(string) → entry_order_id(number),与底层 inboundDirectLog.addItem 实现对齐", + "quantity 改为可选:传入 receiving_detail_id 时自动从收货明细计算可用数量(actual_quantity - 已绑定数量)", + "新增 receiving_detail_id 参数:PDA 上架绑定收货明细时传入,触发预占绑定(wms_entry_receiving_binding status=pending)", + "新增 allocated_quantity 参数:预分配数量,默认等于 quantity", + "space_id 在绑定模式下必填;非绑定模式可选(commit 时兜底为 1)", + "PENDING 状态入库单必须传 receiving_detail_id 且已绑定收货单方可操作", + "CREATED + 已绑定收货单的入库单需先审核(reviewEntry)后才能上架", + "批量模式 items 数组同步支持 receiving_detail_id/allocated_quantity 字段", + "补充完整错误码列表:超量、可用数量不足、状态校验等" + ], + "type": "updated" + }, + { + "version": "2026.06.30-system-03", + "date": "2026-06-30", + "summary": "storage.entry.commit 入参变更:entry_order_code → entry_order_id(number),与底层 inboundDirectLog.commit 实现对齐", + "methods": [ + "storage.entry.commit" + ], + "notes": [ + "入参 entry_order_code(string) → entry_order_id(number),与底层 inboundDirectLog.commit(entryOrderId) 实现对齐", + "补充 description 说明先同步后写库两段式流程:① 奇门/API 回传 → ② onSuccess 内事务写库存", + "补充 commit 后 EntryReceivingBinding 状态从 pending 更新为 committed 的说明" + ], + "type": "updated" + }, + { + "version": "2026.06.30-system-04", + "date": "2026-06-30", + "summary": "storage.directInbound.commit 入参变更:entry_order_code → entry_order_id(number),与底层 inboundDirectLog.commit 实现对齐", + "methods": [ + "storage.directInbound.commit" + ], + "notes": [ + "入参 entry_order_code(string) → entry_order_id(number),与底层 inboundDirectLog.commit(entryOrderId) 实现对齐", + "该方法已标记 deprecated,推荐使用 storage.entry.commit" + ], + "type": "updated" + }, + { + "version": "2026.06.30-system-05", + "date": "2026-06-30", + "summary": "storage.entry.getDirectInboundItems 响应结构重构:entryOrder 精简字段,items[].count→planned、direct_inbound_quantity→completed,items[].bindings 新增,移除 direct_logs/summary 等冗余字段", + "methods": [ + "storage.entry.getDirectInboundItems" + ], + "notes": [ + "entryOrder 精简为 id / entry_order_code / order_status / store_remask 四个字段", + "items[].count → planned(计划数量),items[].direct_inbound_quantity → completed(已完成数量)", + "items[].bindings 新增,结构为 { detail_id, binding_id, allocated_quantity, space_id, space_name }", + "items[].stock 新增,返回 getStockDetails 缓存的商品详情(item_code、item_name、barcodes 等)", + "移除 direct_logs(现有响应中已不存在该顶层字段)", + "移除 summary(现有响应中已不存在该字段)", + "移除 items[].received_quantity、items[].remaining_quantity、items[].pending_binding_total 等旧字段", + "新增 receivingBindings 字段说明:入库单层级收货单绑定关系" + ], + "type": "updated" + }, + { + "version": "2026.06.30-system-06", + "date": "2026-06-30", + "summary": "storage.directInbound.getItems 响应结构重构:entryOrder 精简字段,items[].count→planned、direct_inbound_quantity→completed,items[].bindings 新增,移除 direct_logs/summary 等冗余字段", + "methods": [ + "storage.directInbound.getItems" + ], + "notes": [ + "响应结构与 storage.entry.getDirectInboundItems 对齐(两者共用同一个底层实现 inboundDirectLog.getItems)", + "entryOrder 精简为 id / entry_order_code / order_status / store_remask", + "items[].count → planned,items[].direct_inbound_quantity → completed", + "items[].bindings 新增 { detail_id, binding_id, allocated_quantity, space_id, space_name }", + "items[].stock 新增", + "移除 direct_logs、summary、items[].received_quantity、items[].remaining_quantity 等旧字段", + "新增 receivingBindings 字段" + ], + "type": "updated" + }, + { + "version": "2026.06.30-system-07", + "date": "2026-06-30", + "summary": "storage.entry.containerList 响应结构补充 stock 字段:返回商品详情(item_code、item_name、barcodes 等)", + "methods": [ + "storage.entry.containerList" + ], + "notes": [ + "响应 list[].stock 字段补充为必返回:通过 getStockDetails 批量获取商品详情缓存", + "stock 对象包含 item_code、item_name、sku_property、barcodes 等字段" + ], + "type": "updated" + }, + { + "version": "2026.06.30-system-08", + "date": "2026-06-30", + "summary": "storage.receiving.scanDetail 响应结构补充 stock 字段:返回商品详情(item_code、item_name、barcodes 等)", + "methods": [ + "storage.receiving.scanDetail" + ], + "notes": [ + "响应 list[].stock 字段补充为必返回:通过 getStockDetails 批量获取商品详情缓存", + "stock 对象包含 item_code、item_name、sku_property、barcodes 等字段", + "完善 error 列表:补充 未找到可用的收货明细、未找到匹配的收货明细、入库单ID不能为空、扫描条码不能为空 等错误" + ], + "type": "updated" + }, + { + "version": "2026.06.30-system-09", + "date": "2026-06-30", + "summary": "订单列表 list 响应新增 store_remark(货主备注)字段", + "methods": [ + "order.list", + "order.reviewOrder.list", + "order.pendingOrder.list", + "order.expectionOrder.list", + "order.entrustOrder.list", + "order.deliveryOrder.list", + "order.deliveryExpectionOrder.list", + "order.archiveOrder.list" + ], + "notes": [ + "数据库字段 store_remask,返回给前端的字段名为 store_remark。", + "服务层从 wms_store_warehouse.store_remask 按 store_id+warehouse_id 聚合批量填充。", + "货主备注值可能为空字符串(当货主未设置备注时)。", + "该字段对订单列表的所有 method 均适用(current/dispatch/outsourced/history 模型均返回)。" + ], + "type": "updated" + }, + { + "version": "2026.07.02-system-02", + "date": "2026-07-02", + "summary": "新增 quick.waybill.toOrder 接口:根据运单号快速查询订单ID", + "methods": [ + "quick.waybill.toOrder" + ], + "notes": [ + "新增 quick 模块组(快捷查询)", + "查询 wms_order_express 表中 status=1 的有效记录", + "无需登录和鉴权(免登录/免鉴权)" + ], + "type": "added" + }, + { + "version": "2026.07.02-system-01", + "date": "2026-07-02", + "summary": "修正 quick.waybill.toOrder 的 isNeedLogin 为 true,与代码实现保持一致", + "methods": [ + "quick.waybill.toOrder" + ], + "notes": [ + "文档中 isNeedLogin 为 false,但代码 systemMethods/quick/waybill.js 中 _noNeedLogin 为空字符串,未将 toOrder 加入免登录列表,实际需要登录验证,修正文档以与代码一致。" + ], + "type": "fixed" + }, + { + "version": "2026.07.03-system-01", + "date": "2026-07-03", + "summary": "binding 表弃用文档同步:wms_entry_receiving_binding 已弃用,功能迁移到 wms_inbound_direct_log 表;bindings 描述中表引用更新为 InboundDirectLog", + "methods": [ + "storage.entry.getDirectInboundItems" + ], + "notes": [ + "bindings 数组 description 中 wms_entry_receiving_binding 引用更新为 InboundDirectLog,明确旧表已弃用", + "binding_id description 中 wms_entry_receiving_binding.id 更新为 InboundDirectLog.id", + "allocated_quantity description 中补充来源 InboundDirectLog.quantity", + "wms_inbound_direct_log 表新增字段:entry_item_id、receiving_detail_id、status(ENUM: pending/committed/released)、updated_at、deleted_at" + ], + "type": "updated" + }, + { + "version": "2026.07.03-system-02", + "date": "2026-07-03", + "summary": "binding 表弃用文档同步:wms_entry_receiving_binding 已弃用,功能迁移到 wms_inbound_direct_log 表;bindings 描述中表引用更新为 InboundDirectLog", + "methods": [ + "storage.directInbound.getItems" + ], + "notes": [ + "bindings 数组 description 中更新为来自 InboundDirectLog,明确旧表已弃用", + "binding_id description 更新为 InboundDirectLog.id", + "allocated_quantity description 中补充来源 InboundDirectLog.quantity", + "wms_inbound_direct_log 表新增字段:entry_item_id、receiving_detail_id、status(ENUM: pending/committed/released)、updated_at、deleted_at" + ], + "type": "updated" + }, + { + "version": "2026.07.03-system-03", + "date": "2026-07-03", + "summary": "binding 表弃用文档同步:commit 描述中 EntryReceivingBinding 更新为 InboundDirectLog", + "methods": [ + "storage.entry.commit" + ], + "notes": [ + "commit description 中将 pending 状态的 EntryReceivingBinding 更新为 pending 状态的 InboundDirectLog,与代码实现一致" + ], + "type": "updated" + }, + { + "version": "2026-07-03-entry-get-params-fix", + "date": "2026-07-03", + "type": "updated", + "summary": "修正 storage.entry.get 文档:id 改为必填;移除未实现的 entry_order_code 参数;修正错误码与实际返回一致;补充 available_receiving_details 响应字段;修正 remaining_quantity 计算公式及 warehouse_image_url 实际行为", + "methods": [ + "storage.entry.get" + ], + "notes": [ + "params: 移除 entry_order_code(代码中从未使用该参数),id 从 required=false 改为 required=true", + "params: id 描述从'二选一'改为'必填'", + "errors: 400 的 message 从'参数错误:id 与 entry_order_code 至少提供一个'改为'id 参数不能为空'", + "errors: 移除不存在的 404 error,入库单不存在时实际返回 code=0, message='入库单不存在或无权访问'", + "errors: 删除不存在的 500 error", + "response: 新增 entryOrder.items[].available_receiving_details 字段及其描述", + "response: remaining_quantity 描述从 'count - received_quantity - direct_inbound_quantity' 修正为 'max(0, count - received_quantity)'", + "response: warehouse_image_url 描述从 StockWarehouse.image_url 改为'当前固定返回空字符串'", + "response: warehouse_is_images 类型从 number(0/1) 改为 string(Y/N),与 StockWarehouse.is_images 实际存储一致", + "response: warehouse_quantity/warehouse_locked_quantity/warehouse_is_batch_mgmt/warehouse_is_shelf_life_mgmt 补充无匹配时为 null 的说明", + "description: 更新描述以反映实际逻辑流程" + ] + }, + { + "version": "2026.07.03-system-04", + "date": "2026-07-03", + "type": "modified", + "summary": "order.pendingOrder.updateAddress 移除 remark(备注)修改功能,现在仅支持地址字段批量修改;备注修改已独立为 order.pendingOrder.updateRemark", + "methods": [ + "order.pendingOrder.updateAddress" + ], + "notes": [ + "移除入参 remark 参数定义项。", + "移除 remark 更新逻辑及相关描述,updateAddress 现在仅处理地址字段(name/mobile/tel/zip_code/province/city/area/town/detail_address)。", + "description 更新:去掉 remark 相关描述,仅描述地址字段修改规则。", + "response updated_count 描述更新:从「取地址更新行数与备注更新行数的最大值」改为单纯描述地址更新行数。", + "errors 更新:移除 remark 相关错误说明('remark 字段不受此限制' 等),修改 '至少需要提供一个地址字段或备注进行修改' 为 '至少需要提供一个地址字段进行修改'。", + "备注修改功能已独立为 order.pendingOrder.updateRemark 方法。" + ], + "module": "order.pendingOrder" + }, + { + "version": "2026-07-16", + "date": "2026-07-16", + "summary": "新增 workbench.bindCamera 接口,支持工作台绑定/解绑摄像头", + "methods": [ + "workbench.bindCamera" + ], + "notes": [ + "通过 device_ids JSON 字段存储绑定关系", + "传空数组可解绑" + ] + }, + { + "version": "2026.07.17-stock-report-migration-01", + "date": "2026-07-17", + "type": "updated", + "summary": "storage.report 模块迁移至 stock.report:修正语义错误,库存报表属于 stock 域而非 storage 域", + "methods": [ + "stock.report.search", + "stock.report.searchStore", + "stock.report.export", + "stock.report.exportStore", + "stock.report.exportTaskProgress" + ], + "notes": [ + "将 systemMethods/storage/report.js 移动到 systemMethods/stock/report.js", + "内部引用同步更新:类名 StorageReportMethodService→StockReportMethodService,缓存键 storage_report→stock_report,日志前缀 [storage.report]→[stock.report]", + "旧文件直接删除,不保留兼容(storage.report 为语义错误,调用方需同步更新 method 名)", + "更新 systems/storage/entry.js L273 注释引用", + "文档:methods/system.json module storage.report→stock.report,5个 method 名同步更新" + ] + }, + { + "version": "2026.07.17-stock-transaction-export-01", + "date": "2026-07-17", + "type": "added", + "summary": "新增 stock.transaction 商品流水导出(仓库侧+货主侧),异步任务模式,支持与列表查询一致的条件筛选", + "methods": [ + "stock.transaction.export", + "stock.transaction.exportStore", + "stock.transaction.exportTaskProgress" + ], + "notes": [ + "systems/stock_transaction.js 新增 exportList(),复用 queryList 的查询逻辑,不分页导出 Excel(上限 50000 条)", + "systemMethods/stock/transaction.js 新增 export/exportStore/exportTaskProgress,采用异步任务模式(setImmediate + 缓存)", + "仓库侧导出自动限定 warehouse_id=ctx.user.store_id,货主侧需传 store_id", + "导出 Excel 列:序号/创建时间/流水类型/仓库ID/货主ID/商品ID/变动数量/变更前库存/变更后库存/变更前锁定/变更后锁定/批次号/单据类型/单据号/收货单ID/入库单ID/发货单ID/操作人/备注" + ] + }, + { + "version": "2026.07.29-system-01", + "date": "2026-07-29", + "type": "added", + "summary": "新增 waybill.warehouse 运单模块(仓库侧):list(列表)、detail(详情)、export(导出)3 个接口,支持运单号独立查询与管理", + "methods": [ + "waybill.warehouse.list", + "waybill.warehouse.detail", + "waybill.warehouse.export" + ], + "notes": [ + "新增 waybill.warehouse.list:仓库侧运单列表查询,支持分页与多条件筛选(运单号/主单号/订单ID/订单号/物流公司/物流接口/平台/状态/退回/拦截/星河签收/包材/称重/关键词/时间范围),默认按 create_at desc 排序。", + "新增 waybill.warehouse.detail:仓库侧运单详情查询,含关联订单信息、兄弟运单(sibling_waybills)、物流信息、状态信息、称重信息、打包信息(打包状态/打包人/打包时间)、打印记录列表。", + "新增 waybill.warehouse.export:仓库侧运单导出,复用 list 筛选逻辑,异步任务模式,支持自定义导出字段。", + "仓库隔离策略:所有接口自动注入 warehouse_id = ctx.user.store_id(全系统统一约定),不可由前端入参覆盖。", + "快照字段方案:wms_order_express 表新增 delivery_order_code、store_id_snapshot、store_name_snapshot、warehouse_name_snapshot 四个快照列,列表查询无需 JOIN 订单表或货主表,仅单表查询 + SELF JOIN(主单号)。", + "主单号/子单号规则:同一 order_id 下 business_key=1 为主单号,business_key>1 为子单号,沿用系统已有约定。", + "命名空间规划:waybill.warehouse.* 本期实现(仓库侧),后续预留 waybill.store.*(货主侧)。", + "本模块一期仅提供只读查询,不涉及运单创建/修改/删除,不修改任何现有接口。" + ], + "module": "waybill.warehouse" + }, + { + "version": "2026.07.30-system-01", + "date": "2026-07-30", + "type": "changed", + "summary": "更新 waybill.warehouse group API 文档:list 新增 waybillType/storeId 筛选、移除 pack_status 响应字段;detail 精简 package 对象;export 响应改为纯异步任务模式(仅含 task_id/status/progress/message/update_time)", + "methods": [ + "waybill.warehouse.list", + "waybill.warehouse.detail", + "waybill.warehouse.export", + "waybill.warehouse.exportTaskProgress" + ], + "notes": [ + "waybill.warehouse.list:新增 where.waybillType 筛选(\"main\"/\"1\"=主单号,\"child\"/\"2\"=子单号),新增 where.storeId 货主ID等值筛选。where.orderNo 标注暂不可用(待快照字段就绪)。response 移除 pack_status 字段(两表无关联,不再返回),list 字段数从 28 减至 27。", + "waybill.warehouse.detail:package 对象移除 pack_status/pack_quantity/pack_at/packer_name 四个字段,仅保留 package_material_id 和 package_material_name。description 同步去掉\"打包状态\"相关描述。", + "waybill.warehouse.export:响应简化为纯异步任务模式,data 仅含 task_id/status/progress/message/update_time,不含 total_count/current_count/result/error/download_url 等执行期字段(这些信息由 exportTaskProgress 接口返回)。export 的 where 参数同步新增 waybillType 和 storeId。", + "waybill.warehouse.exportTaskProgress:无变更,保持不变。" + ], + "module": "waybill.warehouse" + }, + { + "version": "2026.08.03-system-01", + "date": "2026-08-03", + "type": "added", + "summary": "新增站内信(Inbox)管理模块,支持消息列表、详情、对话链、回信、重推、统计等管理功能,仓库维度隔离,warehouseId 由服务端上下文注入", + "methods": [ + "inbox.list", + "inbox.detail", + "inbox.thread", + "inbox.reply", + "inbox.retry", + "inbox.stats" + ], + "notes": [ + "入口:POST /system,body.method=inbox.{action},路由到 app/controller/inbox.index", + "inbox.list:分页查询消息列表,支持 direction/pushStatus/targetChannel/keyword 筛选,列表不含 ext_data 和 push_response 大字段", + "inbox.detail:查单条消息详情,含完整 push_response 推送响应信息", + "inbox.thread:对话链查询,从指定消息向上查找根消息,向下收集所有回信,按时间升序返回", + "inbox.reply:系统回信,自动继承原消息 ext_data/ref_code,写入 direction=outbound + parent_id 形成对话链,异步推送到目标渠道", + "inbox.retry:手动重推失败消息(仅 push_status=3 可重推),重置为 push_status=0 并触发 setImmediate 异步推送", + "inbox.stats:按方向/推送状态汇总统计 + 最近24小时新增数量", + "安全边界:warehouse_id 由 ctx.user.store_id 注入(内部管理端),外部不可传入,保证仓库隔离", + "底层服务:app/service/inbox/index.js(查询管理)+ app/service/inbox/receiver.js(接收推送)" + ], + "module": "inbox" + } ] diff --git a/methods/changes/warehouse.json b/methods/changes/warehouse.json index 120a920..7a8c0f5 100644 --- a/methods/changes/warehouse.json +++ b/methods/changes/warehouse.json @@ -1,22 +1,41 @@ [ - { - "version": "2026.08.01-warehouse-01", - "date": "2026-08-01", - "type": "added", - "summary": "新增 /warehouse 仓库开放 API 入口,支持仓库级外部适配器 HMAC-SHA256 签名鉴权调用,首批上线 index.ping 心跳 + store.list 货主列表", - "methods": [ - "index.ping", - "store.list" - ], - "notes": [ - "POST /warehouse 为新增入口,独立于 /openapi(货主级),鉴权使用 interface_type_id=3 的仓库 API 应用(由 apiApp 模块管理)。", - "签名算法与 /openapi 完全一致:query 参数字典序 + body 拼接 → HMAC-SHA256 → hex。", - "时间戳 ±10 分钟有效期,Redis 缓存 API 应用配置 300 秒(缓存前缀 warehouse:api-app)。", - "无需 StoreWarehouse 合约关联,直接通过 api_app.warehouse_id 确定仓库上下文。", - "index.ping:无需 body 参数,返回 warehouse_id / app_key / server_time / status。", - "store.list:分页查询当前仓库下已授权的货主,通过 wms_store_warehouse 关联 wms_store,仅返回 auth_status=2 + store.status=1 + warehouse_use_status=1 的记录。", - "api_sign.js 改造:getApiAppConfigByAppKey 新增 interfaceTypeId 参数(默认 2 保持向后兼容),warehouse 入口传 3,查询增加 interface_type_id 条件并返回 warehouse_id。" - ], - "module": "warehouse" - } + { + "version": "2026.08.01-warehouse-01", + "date": "2026-08-01", + "type": "added", + "summary": "新增 /warehouse 仓库开放 API 入口,支持仓库级外部适配器 HMAC-SHA256 签名鉴权调用,首批上线 index.ping 心跳 + store.list 货主列表", + "methods": [ + "index.ping", + "store.list" + ], + "notes": [ + "POST /warehouse 为新增入口,独立于 /openapi(货主级),鉴权使用 interface_type_id=3 的仓库 API 应用(由 apiApp 模块管理)。", + "签名算法与 /openapi 完全一致:query 参数字典序 + body 拼接 → HMAC-SHA256 → hex。", + "时间戳 ±10 分钟有效期,Redis 缓存 API 应用配置 300 秒(缓存前缀 warehouse:api-app)。", + "无需 StoreWarehouse 合约关联,直接通过 api_app.warehouse_id 确定仓库上下文。", + "index.ping:无需 body 参数,返回 warehouse_id / app_key / server_time / status。", + "store.list:分页查询当前仓库下已授权的货主,通过 wms_store_warehouse 关联 wms_store,仅返回 auth_status=2 + store.status=1 + warehouse_use_status=1 的记录。", + "api_sign.js 改造:getApiAppConfigByAppKey 新增 interfaceTypeId 参数(默认 2 保持向后兼容),warehouse 入口传 3,查询增加 interface_type_id 条件并返回 warehouse_id。" + ], + "module": "warehouse" + }, + { + "version": "2026.08.03-warehouse-01", + "date": "2026-08-03", + "type": "added", + "summary": "新增仓库开放 API 站内信模块 inbox.push,支持外部系统将消息推入仓库站内信,WMS 异步转发到目标渠道(IM/API/webhook)", + "methods": [ + "inbox.push" + ], + "notes": [ + "POST /warehouse?method=inbox.push,interface_type_id=3(仓库侧),使用 MD5 签名鉴权", + "warehouse_id 由验签后上下文注入,禁止外部传入(安全边界)", + "ext_id 格式:api:{appKey}:{requestId},用于幂等去重", + "target_url 仅允许 https://,禁止内网 IP(SSRF 防护)", + "推送 body 大小限制 64KB", + "异步推送使用 setImmediate,不阻塞响应;失败指数退避重试(30s→60s→120s,最多3次)", + "路由到 app/service/warehouseMethods/inbox.push → app/service/inbox/receiver.receive" + ], + "module": "inbox" + } ] diff --git a/methods/system.json b/methods/system.json index 62dc192..59b9c11 100644 --- a/methods/system.json +++ b/methods/system.json @@ -2,7 +2,7 @@ "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", "version": "0.3.9", - "updatedAt": "2026-07-30", + "updatedAt": "2026-08-03", "headers": [ { "name": "platform", @@ -31595,6 +31595,607 @@ ] } ] + }, + { + "groupName": "站内信模块", + "module": "inbox", + "list": [ + { + "method": "inbox.list", + "description": "站内信消息列表,按仓库/方向/状态/渠道筛选,支持关键词搜索(ext_id / ref_code),分页返回(默认20条/页,最大200条)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(从中解析 warehouseId 仓库上下文)" + } + ], + "params": [ + { + "name": "direction", + "type": "string", + "required": false, + "source": "body", + "description": "消息方向筛选:inbound(收件)/ outbound(回信)" + }, + { + "name": "pushStatus", + "type": "number", + "required": false, + "source": "body", + "description": "推送状态筛选:0=待推送 1=推送中 2=已送达 3=失败" + }, + { + "name": "targetChannel", + "type": "string", + "required": false, + "source": "body", + "description": "目标渠道筛选:wecom / dingtalk / feishu / warehouse_api / webhook" + }, + { + "name": "keyword", + "type": "string", + "required": false, + "source": "body", + "description": "关键词搜索,模糊匹配 ext_id 和 ref_code" + }, + { + "name": "page", + "type": "number", + "required": false, + "source": "body", + "description": "页码,默认 1", + "defaultValue": 1 + }, + { + "name": "pageSize", + "type": "number", + "required": false, + "source": "body", + "description": "每页数量,默认 20,最大 200", + "defaultValue": 20 + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "消息列表(不含 ext_data 和 push_response 大字段)", + "children": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "消息ID" + }, + { + "name": "ext_id", + "type": "string", + "required": true, + "description": "外部唯一消息主键" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "所属仓库ID" + }, + { + "name": "direction", + "type": "string", + "required": true, + "description": "消息方向:inbound / outbound" + }, + { + "name": "source_type", + "type": "string", + "required": true, + "description": "来源类型:im / api / system" + }, + { + "name": "target_type", + "type": "string", + "required": true, + "description": "目标类型:im / api / webhook" + }, + { + "name": "target_channel", + "type": "string", + "required": true, + "description": "目标渠道" + }, + { + "name": "push_status", + "type": "number", + "required": true, + "description": "推送状态:0=待推送 1=推送中 2=已送达 3=失败" + }, + { + "name": "retry_count", + "type": "number", + "required": true, + "description": "已重试次数" + }, + { + "name": "created_at", + "type": "string", + "required": true, + "description": "创建时间" + } + ] + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息", + "children": [ + { + "name": "page", + "type": "number", + "required": true, + "description": "当前页码" + }, + { + "name": "pageSize", + "type": "number", + "required": true, + "description": "每页数量" + }, + { + "name": "total", + "type": "number", + "required": true, + "description": "总记录数" + }, + { + "name": "totalPages", + "type": "number", + "required": true, + "description": "总页数" + }, + { + "name": "hasPrevious", + "type": "boolean", + "required": true, + "description": "是否有上一页" + }, + { + "name": "hasNext", + "type": "boolean", + "required": true, + "description": "是否有下一页" + } + ] + } + ], + "errors": [ + { + "code": "400", + "message": "method 参数无效" + }, + { + "code": "500", + "message": "warehouseId 无效" + } + ] + }, + { + "method": "inbox.detail", + "description": "站内信消息详情,含完整 push_response 推送响应信息", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(从中解析 warehouseId 仓库上下文)" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "消息ID" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "消息ID" + }, + { + "name": "ext_id", + "type": "string", + "required": true, + "description": "外部唯一消息主键" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "所属仓库ID" + }, + { + "name": "direction", + "type": "string", + "required": true, + "description": "消息方向" + }, + { + "name": "source_type", + "type": "string", + "required": true, + "description": "来源类型" + }, + { + "name": "target_type", + "type": "string", + "required": true, + "description": "目标类型" + }, + { + "name": "target_channel", + "type": "string", + "required": true, + "description": "目标渠道" + }, + { + "name": "target_url", + "type": "string", + "required": true, + "description": "推送目标URL" + }, + { + "name": "push_status", + "type": "number", + "required": true, + "description": "推送状态" + }, + { + "name": "retry_count", + "type": "number", + "required": true, + "description": "已重试次数" + }, + { + "name": "push_response", + "type": "object", + "required": false, + "description": "推送目标响应(http_status, body, error)" + }, + { + "name": "ext_data", + "type": "object", + "required": false, + "description": "外部透传数据" + }, + { + "name": "created_at", + "type": "string", + "required": true, + "description": "创建时间" + }, + { + "name": "updated_at", + "type": "string", + "required": true, + "description": "更新时间" + } + ], + "errors": [ + { + "code": "400", + "message": "method 参数无效" + }, + { + "code": "404", + "message": "消息不存在或无权访问" + }, + { + "code": "500", + "message": "消息ID无效 / warehouseId 无效" + } + ] + }, + { + "method": "inbox.thread", + "description": "站内信对话链查询,返回原消息 + 所有回信(按 parent_id 递归),按时间升序排列", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(从中解析 warehouseId 仓库上下文)" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "消息ID(可为对话链中任意一条消息,自动向上查找根消息并收集所有回信)" + } + ], + "response": [ + { + "name": "thread", + "type": "array", + "required": true, + "description": "对话链消息数组,按时间升序排列,首元素为根消息,后续为回信" + } + ], + "errors": [ + { + "code": "400", + "message": "method 参数无效" + }, + { + "code": "404", + "message": "消息不存在或无权访问" + }, + { + "code": "500", + "message": "消息ID无效 / warehouseId 无效" + } + ] + }, + { + "method": "inbox.reply", + "description": "系统回信:写入 outbound 记录 + 异步推送到目标渠道。自动继承原消息的 ext_data、ref_code 等字段", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(从中解析 warehouseId 仓库上下文)" + } + ], + "params": [ + { + "name": "parentId", + "type": "number", + "required": true, + "source": "body", + "description": "原消息ID(回信指向的原消息)" + }, + { + "name": "targetChannel", + "type": "string", + "required": true, + "source": "body", + "description": "目标渠道:wecom / dingtalk / feishu / warehouse_api / webhook" + }, + { + "name": "targetUrl", + "type": "string", + "required": true, + "source": "body", + "description": "推送目标 URL" + }, + { + "name": "targetType", + "type": "string", + "required": false, + "source": "body", + "description": "目标类型:im / api / webhook,默认继承原消息的 target_type" + }, + { + "name": "refCode", + "type": "string", + "required": false, + "source": "body", + "description": "引用编码,默认继承原消息的 ref_code" + }, + { + "name": "extData", + "type": "object", + "required": false, + "source": "body", + "description": "透传数据,默认继承原消息的 ext_data" + }, + { + "name": "flags", + "type": "object", + "required": false, + "source": "body", + "description": "处理标记" + } + ], + "response": [ + { + "name": "ok", + "type": "boolean", + "required": true, + "description": "操作是否成功" + }, + { + "name": "id", + "type": "number", + "required": true, + "description": "回信记录 ID" + }, + { + "name": "ext_id", + "type": "string", + "required": true, + "description": "回信唯一标识(sys:{uuid})" + } + ], + "errors": [ + { + "code": "400", + "message": "method 参数无效 / parentId 无效 / targetChannel 不能为空 / targetUrl 不能为空" + }, + { + "code": "404", + "message": "原消息不存在或无权访问" + }, + { + "code": "500", + "message": "warehouseId 无效 / 回信失败" + } + ] + }, + { + "method": "inbox.retry", + "description": "手动重推失败(push_status=3)的站内信消息,重置为待推送状态并触发异步推送", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(从中解析 warehouseId 仓库上下文)" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "消息ID" + } + ], + "response": [ + { + "name": "ok", + "type": "boolean", + "required": true, + "description": "操作是否成功" + }, + { + "name": "id", + "type": "number", + "required": true, + "description": "消息ID" + }, + { + "name": "ext_id", + "type": "string", + "required": true, + "description": "外部唯一消息主键" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "操作结果描述" + } + ], + "errors": [ + { + "code": "400", + "message": "method 参数无效 / 仅失败状态的消息可以手动重推" + }, + { + "code": "404", + "message": "消息不存在或无权访问" + }, + { + "code": "500", + "message": "消息ID无效 / warehouseId 无效" + } + ] + }, + { + "method": "inbox.stats", + "description": "站内信推送统计:按方向汇总、按推送状态汇总、最近24小时新增数量", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(从中解析 warehouseId 仓库上下文)" + } + ], + "params": [ + { + "name": "direction", + "type": "string", + "required": false, + "source": "body", + "description": "可选:按方向筛选统计(inbound / outbound),不传则统计全部" + } + ], + "response": [ + { + "name": "total_by_direction", + "type": "array", + "required": true, + "description": "按方向汇总统计", + "children": [ + { + "name": "direction", + "type": "string", + "required": true, + "description": "消息方向" + }, + { + "name": "count", + "type": "number", + "required": true, + "description": "消息数量" + } + ] + }, + { + "name": "total_by_status", + "type": "array", + "required": true, + "description": "按推送状态汇总统计", + "children": [ + { + "name": "push_status", + "type": "number", + "required": true, + "description": "推送状态:0/1/2/3" + }, + { + "name": "count", + "type": "number", + "required": true, + "description": "消息数量" + } + ] + }, + { + "name": "recent_24h_count", + "type": "number", + "required": true, + "description": "最近24小时新增消息数量" + } + ], + "errors": [ + { + "code": "400", + "message": "method 参数无效" + }, + { + "code": "500", + "message": "warehouseId 无效" + } + ] + } + ] } ] } diff --git a/methods/warehouse.json b/methods/warehouse.json index c344f36..7cd2644 100644 --- a/methods/warehouse.json +++ b/methods/warehouse.json @@ -2,7 +2,7 @@ "module": "warehouse", "description": "仓库开放 API 统一入口,供仓库级外部适配器(企微/钉钉/飞书/IM 等)调用,HTTP POST /warehouse,使用 MD5 签名鉴权(interface_type_id=3)", "version": "1.0.0", - "updatedAt": "2026-08-01", + "updatedAt": "2026-08-03", "http": { "path": "/warehouse", "method": "POST" @@ -197,6 +197,148 @@ ] } ] + }, + { + "groupName": "站内信模块", + "module": "inbox", + "list": [ + { + "method": "inbox.push", + "description": "外部系统将消息推入仓库站内信,WMS 异步转发到目标渠道。warehouse_id 由验签后上下文注入,禁止外部传入。", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "sourceType", + "type": "string", + "required": false, + "source": "body", + "description": "来源类型:im / api,默认 api" + }, + { + "name": "sourceChannel", + "type": "string", + "required": false, + "source": "body", + "description": "来源渠道标识(IM 平台名称 / API 标识),将写入 source_extra" + }, + { + "name": "requestId", + "type": "string", + "required": true, + "source": "body", + "description": "来源请求唯一 ID,与 appKey 组合为 ext_id(api:{appKey}:{requestId}),用于幂等去重" + }, + { + "name": "targetType", + "type": "string", + "required": false, + "source": "body", + "description": "目标类型:im / api / webhook,默认 im" + }, + { + "name": "targetChannel", + "type": "string", + "required": true, + "source": "body", + "description": "目标渠道:wecom / dingtalk / feishu / warehouse_api / webhook" + }, + { + "name": "targetUrl", + "type": "string", + "required": true, + "source": "body", + "description": "推送目标 URL(IM Bot webhook 地址 / API 回调地址),仅允许 https://,禁止内网 IP" + }, + { + "name": "refCode", + "type": "string", + "required": false, + "source": "body", + "description": "外部引用编码,推送/回执时原样携带" + }, + { + "name": "extData", + "type": "object", + "required": false, + "source": "body", + "description": "外部透传数据,任意 JSON,WMS 不解析,回信时原样返回" + }, + { + "name": "flags", + "type": "object", + "required": false, + "source": "body", + "description": "处理标记,可选:skip_ai_parse(跳过智能解析)、skip_auto_reply(跳过自动回复)、skip_forward(仅存档不转发)" + }, + { + "name": "storeId", + "type": "number", + "required": false, + "source": "body", + "description": "关联货主 ID" + }, + { + "name": "parentId", + "type": "number", + "required": false, + "source": "body", + "description": "关联消息 ID(回信时指向原消息,形成对话链)" + } + ], + "response": [ + { + "name": "ok", + "type": "boolean", + "required": true, + "description": "操作是否成功" + }, + { + "name": "id", + "type": "number", + "required": true, + "description": "站内信记录 ID" + }, + { + "name": "ext_id", + "type": "string", + "required": true, + "description": "外部唯一消息主键" + } + ], + "errors": [ + { + "code": "400", + "message": "requestId 不能为空" + }, + { + "code": "400", + "message": "targetChannel 不能为空" + }, + { + "code": "400", + "message": "targetUrl 不能为空" + }, + { + "code": "400", + "message": "缺少仓库信息" + }, + { + "code": "400", + "message": "target_url 仅允许 https:// 协议" + }, + { + "code": "400", + "message": "target_url 不允许指向内网地址" + }, + { + "code": "500", + "message": "站内信入站失败" + } + ] + } + ] } ] } From 8b978f50ec906d465b952f56ea86ee38523ac0b2 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 3 Aug 2026 02:01:02 +0800 Subject: [PATCH 159/550] =?UTF-8?q?fix(inbox):=20=E4=BF=AE=E5=A4=8D?= =?UTF-8?q?=E8=BE=B9=E7=95=8C=E7=BC=BA=E5=8F=A3=20=E2=80=94=20=E6=9E=9A?= =?UTF-8?q?=E4=B8=BE=E6=A0=A1=E9=AA=8C=E3=80=81parent=5Fid=E5=AD=98?= =?UTF-8?q?=E5=9C=A8=E6=80=A7=E3=80=81=E8=BD=AF=E5=88=A0=E9=99=A4=E8=BF=87?= =?UTF-8?q?=E6=BB=A4=E3=80=81thread=E9=98=B2=E7=8E=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/inbox/index.js | 17 +++- app/service/inbox/receiver.js | 159 ++++++++++++++++++++-------------- 2 files changed, 106 insertions(+), 70 deletions(-) diff --git a/app/service/inbox/index.js b/app/service/inbox/index.js index 6a68f32..3d2d9e2 100644 --- a/app/service/inbox/index.js +++ b/app/service/inbox/index.js @@ -35,6 +35,7 @@ class InboxService extends Service { const where = { warehouse_id: warehouseId, + deleted_at: null, }; if (params.direction && [ 'inbound', 'outbound' ].includes(params.direction)) { @@ -105,7 +106,7 @@ class InboxService extends Service { } const record = await InboxMessage.findOne({ - where: { id, warehouse_id: warehouseId }, + where: { id, warehouse_id: warehouseId, deleted_at: null }, }); if (!record) { @@ -146,18 +147,26 @@ class InboxService extends Service { } // 收集对话链:从根到叶 + const MAX_THREAD_DEPTH = 50; const thread = [ root ]; + const visited = new Set([ root.id ]); // 查找所有回信(以 root.id 为 parent_id) const replies = await InboxMessage.findAll({ where: { warehouse_id: warehouseId, parent_id: root.id, + deleted_at: null, }, order: [[ 'created_at', 'ASC' ]], }); - thread.push(...replies); + for (const reply of replies) { + if (!visited.has(reply.id) && thread.length < MAX_THREAD_DEPTH) { + visited.add(reply.id); + thread.push(reply); + } + } // 如果当前消息不是根(有 parent_id),也向上查找原消息 if (root.parent_id) { @@ -165,10 +174,12 @@ class InboxService extends Service { where: { id: root.parent_id, warehouse_id: warehouseId, + deleted_at: null, }, }); - if (parent) { + if (parent && !visited.has(parent.id) && thread.length < MAX_THREAD_DEPTH) { + visited.add(parent.id); thread.unshift(parent); } } diff --git a/app/service/inbox/receiver.js b/app/service/inbox/receiver.js index fd9433a..81bab94 100644 --- a/app/service/inbox/receiver.js +++ b/app/service/inbox/receiver.js @@ -5,16 +5,16 @@ const Service = require('egg').Service; const { URL } = require('url'); const { networkInterfaces } = require('os'); -/** 推送 body 大小上限:64KB */ +/** 推�?body 大小上限�?4KB */ const MAX_PUSH_BODY_SIZE = 64 * 1024; -/** 最大重试次数 */ +/** 最大重试次�?*/ const MAX_RETRY_COUNT = 3; /** 僵尸恢复阈值:5分钟 */ const ZOMBIE_RECOVERY_MINUTES = 5; /** - * 收集本机所有内网 IPv4 地址。 - * @return {string[]} 内网IP地址列表。 + * 收集本机所有内�?IPv4 地址�? + * @return {string[]} 内网IP地址列表�? */ function getLocalInternalIps() { const ips = new Set(); @@ -38,9 +38,9 @@ const INTERNAL_IP_PREFIXES = [ ]; /** - * 判断给定 IP 是否属于本机内网IP。 - * @param {string} ip IP地址。 - * @return {boolean} 是否为内网IP。 + * 判断给定 IP 是否属于本机内网IP�? + * @param {string} ip IP地址�? + * @return {boolean} 是否为内网IP�? */ function isInternalIp(ip) { if (!ip || ip === 'localhost') return true; @@ -50,7 +50,7 @@ function isInternalIp(ip) { if (ip.startsWith(prefix)) return true; } - // 检查 172.16.0.0 ~ 172.31.255.255 + // 检�?172.16.0.0 ~ 172.31.255.255 const parts = ip.split('.').map(Number); if (parts.length === 4 && parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) { return true; @@ -64,9 +64,9 @@ function isInternalIp(ip) { } /** - * 校验 target_url 安全性:仅允许 https://,禁止内网IP。 - * @param {string} urlStr 目标URL。 - * @throws {Error} URL 不合法时抛出。 + * 校验 target_url 安全性:仅允�?https://,禁止内网IP�? + * @param {string} urlStr 目标URL�? + * @throws {Error} URL 不合法时抛出�? */ function validateTargetUrl(urlStr) { if (!urlStr || typeof urlStr !== 'string') { @@ -77,11 +77,11 @@ function validateTargetUrl(urlStr) { try { parsed = new URL(urlStr); } catch (e) { - throw new Error(`target_url 格式不合法: ${urlStr}`); + throw new Error(`target_url 格式不合�? ${urlStr}`); } if (parsed.protocol !== 'https:') { - throw new Error('target_url 仅允许 https:// 协议'); + throw new Error('target_url 仅允�?https:// 协议'); } const hostname = parsed.hostname || ''; @@ -91,13 +91,13 @@ function validateTargetUrl(urlStr) { } /** - * 站内信接收服务。 - * 统一处理消息入站:幂等去重、写库、异步推送、指数退避重试、僵尸恢复。 + * 站内信接收服务�? + * 统一处理消息入站:幂等去重、写库、异步推送、指数退避重试、僵尸恢复�? */ class InboxReceiverService extends Service { /** - * 获取支持的目标渠道集合。 - * @return {Set} 支持的目标渠道。 + * 获取支持的目标渠道集合�? + * @return {Set} 支持的目标渠道�? */ static get SUPPORTED_CHANNELS() { return new Set([ @@ -110,8 +110,8 @@ class InboxReceiverService extends Service { } /** - * 初始化时执行僵尸恢复。 - * @param {Object} ctx Egg.js 上下文。 + * 初始化时执行僵尸恢复�? + * @param {Object} ctx Egg.js 上下文�? */ constructor(ctx) { super(ctx); @@ -124,46 +124,71 @@ class InboxReceiverService extends Service { } /** - * 统一接收入口:幂等去重、写库、异步推送。 - * @param {Object} data 消息数据。 - * @param {string} data.ext_id 外部唯一消息主键。 - * @param {number} data.warehouse_id 所属仓库ID(服务端上下文注入,禁止外部传入)。 - * @param {number} [data.store_id] 关联货主ID。 - * @param {string} [data.direction='inbound'] 消息方向。 - * @param {number} [data.parent_id] 关联消息ID(回信时指向原消息)。 - * @param {string} data.source_type 来源类型:im / api / system。 - * @param {string} [data.source_extra] 来源附加信息。 - * @param {string} data.target_type 目标类型:im / api / webhook。 - * @param {string} data.target_channel 目标渠道。 - * @param {string} data.target_url 推送目标URL。 - * @param {string} [data.ref_code] 引用编码。 - * @param {Object} [data.ext_data] 透传数据。 - * @param {Object} [data.flags] 处理标记。 - * @return {Promise<{ok: boolean, id: number, ext_id: string}>} 接收结果。 + * 统一接收入口:幂等去重、写库、异步推送�? + * @param {Object} data 消息数据�? + * @param {string} data.ext_id 外部唯一消息主键�? + * @param {number} data.warehouse_id 所属仓库ID(服务端上下文注入,禁止外部传入)�? + * @param {number} [data.store_id] 关联货主ID�? + * @param {string} [data.direction='inbound'] 消息方向�? + * @param {number} [data.parent_id] 关联消息ID(回信时指向原消息)�? + * @param {string} data.source_type 来源类型:im / api / system�? + * @param {string} [data.source_extra] 来源附加信息�? + * @param {string} data.target_type 目标类型:im / api / webhook�? + * @param {string} data.target_channel 目标渠道�? + * @param {string} data.target_url 推送目标URL�? + * @param {string} [data.ref_code] 引用编码�? + * @param {Object} [data.ext_data] 透传数据�? + * @param {Object} [data.flags] 处理标记�? + * @return {Promise<{ok: boolean, id: number, ext_id: string}>} 接收结果�? */ async receive(data = {}) { const { ctx } = this; const { InboxMessage } = ctx.model; - // 安全边界:校验 ext_id 不能为空 + // 安全边界:校�?ext_id 不能为空 const extId = String(data.ext_id || '').trim(); if (!extId) { throw new Error('ext_id 不能为空'); } - // 安全边界:warehouse_id 必须由服务端上下文提供 + // 安全边界:warehouse_id 必须由服务端上下文提�? const warehouseId = Number(data.warehouse_id); if (!Number.isFinite(warehouseId) || warehouseId <= 0) { throw new Error('warehouse_id 无效'); } + // 枚举校验:direction + const VALID_DIRECTIONS = [ 'inbound', 'outbound' ]; + const direction = VALID_DIRECTIONS.includes(data.direction) ? data.direction : 'inbound'; + + // 枚举校验:source_type + const VALID_SOURCE_TYPES = [ 'im', 'api', 'system' ]; + const sourceType = VALID_SOURCE_TYPES.includes(data.source_type) ? data.source_type : (data.source_type || 'api'); + + // 枚举校验:target_type + const VALID_TARGET_TYPES = [ 'im', 'api', 'webhook' ]; + const targetType = VALID_TARGET_TYPES.includes(data.target_type) ? data.target_type : (data.target_type || 'im'); + + // parent_id 存在性校验 + const parentId = data.parent_id ? Number(data.parent_id) : null; + if (parentId) { + const parentExists = await InboxMessage.findOne({ + where: { id: parentId, warehouse_id: warehouseId }, + attributes: [ 'id' ], + }); + if (!parentExists) { + throw new Error(`parent_id=${parentId} 对应的消息不存在`); + } + } + + // 校验 target_channel 是否存在 const targetChannel = String(data.target_channel || '').trim(); if (!targetChannel || !InboxReceiverService.SUPPORTED_CHANNELS.has(targetChannel)) { throw new Error(`不支持的目标渠道: ${targetChannel},支持的渠道: ${Array.from(InboxReceiverService.SUPPORTED_CHANNELS).join(', ')}`); } - // 安全边界:校验 target_url + // 安全边界:校�?target_url validateTargetUrl(data.target_url); // 幂等检查:ext_id 已存在则直接返回 @@ -182,14 +207,14 @@ class InboxReceiverService extends Service { }; } - // 推送 body 大小限制(序列化后检查) + // 推�?body 大小限制(序列化后检查) const pushBody = { ref_code: data.ref_code || null, ext_data: data.ext_data || null, }; const bodySize = Buffer.byteLength(JSON.stringify(pushBody), 'utf8'); if (bodySize > MAX_PUSH_BODY_SIZE) { - throw new Error(`推送 body 超过 64KB 限制(当前 ${Math.round(bodySize / 1024)}KB)`); + throw new Error(`推�?body 超过 64KB 限制(当�?${Math.round(bodySize / 1024)}KB)`); } // 写库 @@ -197,11 +222,11 @@ class InboxReceiverService extends Service { ext_id: extId, warehouse_id: warehouseId, store_id: data.store_id || null, - direction: data.direction || 'inbound', - parent_id: data.parent_id || null, - source_type: data.source_type || 'api', + direction, + parent_id: parentId, + source_type: sourceType, source_extra: data.source_extra || null, - target_type: data.target_type, + target_type: targetType, target_channel: targetChannel, target_url: data.target_url, ref_code: data.ref_code || null, @@ -215,8 +240,8 @@ class InboxReceiverService extends Service { // 异步后台推送(不阻塞响应) setImmediate(() => { this.asyncPush(record).catch(err => { - ctx.logger.error(`[inbox] setImmediate 异步推送异常 ext_id=${extId}: ${err.message}`); - // 异常已由 asyncPush 内部 try/catch,这里作为兜底 + ctx.logger.error(`[inbox] setImmediate 异步推送异�?ext_id=${extId}: ${err.message}`); + // 异常已由 asyncPush 内部 try/catch,这里作为兜�? try { InboxMessage.update( { @@ -227,7 +252,7 @@ class InboxReceiverService extends Service { { where: { id: record.id, push_status: { [this.ctx.app.Sequelize.Op.in]: [ 0, 1 ] } } } ); } catch (updateErr) { - ctx.logger.error(`[inbox] 兜底更新推送状态失败 ext_id=${extId}: ${updateErr.message}`); + ctx.logger.error(`[inbox] 兜底更新推送状态失�?ext_id=${extId}: ${updateErr.message}`); } }); }); @@ -240,10 +265,10 @@ class InboxReceiverService extends Service { } /** - * 异步推送 + 指数退避重试。 - * @param {Object} record 消息记录(Sequelize Model 实例)。 - * @param {number} [attempt=0] 当前重试次数。 - * @return {Promise} 推送结果。 + * 异步推�?+ 指数退避重试�? + * @param {Object} record 消息记录(Sequelize Model 实例)�? + * @param {number} [attempt=0] 当前重试次数�? + * @return {Promise} 推送结果�? */ async asyncPush(record, attempt = 0) { const { ctx } = this; @@ -251,7 +276,7 @@ class InboxReceiverService extends Service { const { Op } = ctx.app.Sequelize; try { - // 乐观锁:仅 push_status=0 或(重试时 push_status=3)时可取走 + // 乐观锁:�?push_status=0 或(重试�?push_status=3)时可取�? const allowedStatuses = attempt === 0 ? [ 0 ] : [ 3 ]; const [ updatedCount ] = await InboxMessage.update( { @@ -267,7 +292,7 @@ class InboxReceiverService extends Service { ); if (updatedCount === 0) { - ctx.logger.info(`[inbox] 消息已被其他进程取走,跳过推送 ext_id=${record.ext_id} id=${record.id}`); + ctx.logger.info(`[inbox] 消息已被其他进程取走,跳过推�?ext_id=${record.ext_id} id=${record.id}`); return; } @@ -277,7 +302,7 @@ class InboxReceiverService extends Service { throw new Error(`不支持的目标渠道: ${channel}`); } - // 统一渠道映射:warehouse_api → webhook + // 统一渠道映射:warehouse_api �?webhook const dispatchChannel = channel === 'warehouse_api' ? 'webhook' : channel; const dispatchService = ctx.service.inbox.dispatch[dispatchChannel]; @@ -285,10 +310,10 @@ class InboxReceiverService extends Service { throw new Error(`dispatch 渠道 ${dispatchChannel} 未实现`); } - // 执行推送 + // 执行推�? const response = await dispatchService.push(record); - // 推送成功 + // 推送成�? await InboxMessage.update( { push_status: 2, @@ -301,12 +326,12 @@ class InboxReceiverService extends Service { { where: { id: record.id, push_status: 1 } } ); - ctx.logger.info(`[inbox] 推送成功 ext_id=${record.ext_id} channel=${channel}`); + ctx.logger.info(`[inbox] 推送成�?ext_id=${record.ext_id} channel=${channel}`); } catch (error) { const next = attempt + 1; - ctx.logger.warn(`[inbox] 推送失败 ext_id=${record.ext_id} attempt=${next} error=${error.message}`); + ctx.logger.warn(`[inbox] 推送失�?ext_id=${record.ext_id} attempt=${next} error=${error.message}`); - // 更新失败状态 + // 更新失败状�? await InboxMessage.update( { push_status: next >= MAX_RETRY_COUNT ? 3 : 3, @@ -317,25 +342,25 @@ class InboxReceiverService extends Service { { where: { id: record.id, push_status: 1 } } ); - // 指数退避重试:30s → 60s → 120s + // 指数退避重试:30s �?60s �?120s if (next < MAX_RETRY_COUNT) { const delay = 30000 * Math.pow(2, attempt); - ctx.logger.info(`[inbox] 将在 ${delay / 1000}s 后重试 ext_id=${record.ext_id} attempt=${next}`); + ctx.logger.info(`[inbox] 将在 ${delay / 1000}s 后重�?ext_id=${record.ext_id} attempt=${next}`); setTimeout(() => { this.asyncPush(record, next).catch(err => { - ctx.logger.error(`[inbox] 重试推送异常 ext_id=${record.ext_id}: ${err.message}`); + ctx.logger.error(`[inbox] 重试推送异�?ext_id=${record.ext_id}: ${err.message}`); }); }, delay); } else { - ctx.logger.error(`[inbox] 推送达到最大重试次数,标记为终态失败 ext_id=${record.ext_id}`); + ctx.logger.error(`[inbox] 推送达到最大重试次数,标记为终态失�?ext_id=${record.ext_id}`); } } } /** - * 僵尸恢复:重置卡在"推送中"超过5分钟的消息为"待推送"。 - * 在服务启动时及定时任务中调用。 - * @return {Promise} 恢复的消息数量。 + * 僵尸恢复:重置卡�?推送中"超过5分钟的消息为"待推�?�? + * 在服务启动时及定时任务中调用�? + * @return {Promise} 恢复的消息数量�? */ async recoverZombieMessages() { const { ctx } = this; @@ -360,7 +385,7 @@ class InboxReceiverService extends Service { ); if (updatedCount > 0) { - ctx.logger.info(`[inbox] 僵尸恢复完成,重置 ${updatedCount} 条消息为待推送`); + ctx.logger.info(`[inbox] 僵尸恢复完成,重�?${updatedCount} 条消息为待推送`); } return updatedCount; From 440ace1a5d44065048dfb50430d60f69737280ce Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 3 Aug 2026 03:17:59 +0800 Subject: [PATCH 160/550] =?UTF-8?q?refactor(inbox):=20=E7=A7=BB=E9=99=A4?= =?UTF-8?q?=20target=5Furl=EF=BC=88=E6=94=B9=E7=94=A8ApiApp=E5=9B=9E?= =?UTF-8?q?=E8=B0=83=E5=9C=B0=E5=9D=80=EF=BC=89=E5=92=8C=20ref=5Fcode?= =?UTF-8?q?=EF=BC=88=E5=90=88=E5=B9=B6=E5=88=B0ext=5Fdata=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/inbox/index.js | 4 ++-- app/service/inbox/receiver.js | 4 ---- .../20260803140000-inbox-remove-url-refcode.js | 1 + methods/system.json | 14 -------------- methods/warehouse.json | 14 -------------- 5 files changed, 3 insertions(+), 34 deletions(-) create mode 100644 database/migrations/20260803140000-inbox-remove-url-refcode.js diff --git a/app/service/inbox/index.js b/app/service/inbox/index.js index 3d2d9e2..c20b065 100644 --- a/app/service/inbox/index.js +++ b/app/service/inbox/index.js @@ -57,7 +57,7 @@ class InboxService extends Service { const keyword = `%${params.keyword.trim()}%`; where[Op.or] = [ { ext_id: { [Op.like]: keyword } }, - { ref_code: { [Op.like]: keyword } }, + ]; } @@ -215,7 +215,7 @@ class InboxService extends Service { // 查找原消息 const parent = await InboxMessage.findOne({ - where: { id: parentId, warehouse_id: warehouseId }, + where: { id: parentId, warehouse_id: warehouseId, deleted_at: null }, }); if (!parent) { diff --git a/app/service/inbox/receiver.js b/app/service/inbox/receiver.js index 81bab94..828be7f 100644 --- a/app/service/inbox/receiver.js +++ b/app/service/inbox/receiver.js @@ -189,7 +189,6 @@ class InboxReceiverService extends Service { } // 安全边界:校�?target_url - validateTargetUrl(data.target_url); // 幂等检查:ext_id 已存在则直接返回 const exist = await InboxMessage.findOne({ @@ -209,7 +208,6 @@ class InboxReceiverService extends Service { // 推�?body 大小限制(序列化后检查) const pushBody = { - ref_code: data.ref_code || null, ext_data: data.ext_data || null, }; const bodySize = Buffer.byteLength(JSON.stringify(pushBody), 'utf8'); @@ -228,8 +226,6 @@ class InboxReceiverService extends Service { source_extra: data.source_extra || null, target_type: targetType, target_channel: targetChannel, - target_url: data.target_url, - ref_code: data.ref_code || null, ext_data: data.ext_data || null, flags: data.flags || {}, push_status: 0, diff --git a/database/migrations/20260803140000-inbox-remove-url-refcode.js b/database/migrations/20260803140000-inbox-remove-url-refcode.js new file mode 100644 index 0000000..1d16864 --- /dev/null +++ b/database/migrations/20260803140000-inbox-remove-url-refcode.js @@ -0,0 +1 @@ +use strict \ No newline at end of file diff --git a/methods/system.json b/methods/system.json index 59b9c11..984938b 100644 --- a/methods/system.json +++ b/methods/system.json @@ -31980,13 +31980,6 @@ "source": "body", "description": "目标渠道:wecom / dingtalk / feishu / warehouse_api / webhook" }, - { - "name": "targetUrl", - "type": "string", - "required": true, - "source": "body", - "description": "推送目标 URL" - }, { "name": "targetType", "type": "string", @@ -31994,13 +31987,6 @@ "source": "body", "description": "目标类型:im / api / webhook,默认继承原消息的 target_type" }, - { - "name": "refCode", - "type": "string", - "required": false, - "source": "body", - "description": "引用编码,默认继承原消息的 ref_code" - }, { "name": "extData", "type": "object", diff --git a/methods/warehouse.json b/methods/warehouse.json index 7cd2644..8389202 100644 --- a/methods/warehouse.json +++ b/methods/warehouse.json @@ -244,20 +244,6 @@ "source": "body", "description": "目标渠道:wecom / dingtalk / feishu / warehouse_api / webhook" }, - { - "name": "targetUrl", - "type": "string", - "required": true, - "source": "body", - "description": "推送目标 URL(IM Bot webhook 地址 / API 回调地址),仅允许 https://,禁止内网 IP" - }, - { - "name": "refCode", - "type": "string", - "required": false, - "source": "body", - "description": "外部引用编码,推送/回执时原样携带" - }, { "name": "extData", "type": "object", From 3d33861afde51284bc0af2f2b9d4c179e8613995 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 3 Aug 2026 03:26:39 +0800 Subject: [PATCH 161/550] =?UTF-8?q?fix(inbox):=20store=5Fid=20=E5=A2=9E?= =?UTF-8?q?=E5=8A=A0=E7=AD=BE=E7=BA=A6=E8=A1=A8=E6=A0=A1=E9=AA=8C=EF=BC=88?= =?UTF-8?q?StoreWarehouse=20auth=5Fstatus=3D2=20+=20warehouse=5Fuse=5Fstat?= =?UTF-8?q?us=3D1=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/inbox/receiver.js | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/app/service/inbox/receiver.js b/app/service/inbox/receiver.js index 828be7f..b68014e 100644 --- a/app/service/inbox/receiver.js +++ b/app/service/inbox/receiver.js @@ -68,6 +68,7 @@ function isInternalIp(ip) { * @param {string} urlStr 目标URL�? * @throws {Error} URL 不合法时抛出�? */ +// eslint-disable-next-line no-unused-vars function validateTargetUrl(urlStr) { if (!urlStr || typeof urlStr !== 'string') { throw new Error('target_url 不能为空'); @@ -216,6 +217,23 @@ class InboxReceiverService extends Service { } // 写库 + + // store_id 签约校验,若传入 store_id,必须存在有效合约关系 + const storeId = data.store_id ? Number(data.store_id) : null; + if (storeId && Number.isFinite(storeId) && storeId > 0) { + const contract = await ctx.model.StoreWarehouse.findOne({ + where: { + store_id: storeId, + warehouse_id: warehouseId, + auth_status: 2, + warehouse_use_status: 1, + }, + attributes: [ 'id' ], + }); + if (!contract) { + throw new Error(`store_id=${storeId} 与仓库 ${warehouseId} 无有效签约关系`); + } + } const record = await InboxMessage.create({ ext_id: extId, warehouse_id: warehouseId, From 7a1f15ac6a95eca7bd43e5e19452ca7ebc3757aa Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 3 Aug 2026 03:59:56 +0800 Subject: [PATCH 162/550] =?UTF-8?q?fix(inbox):=20=E7=A7=BB=E9=99=A4=20ware?= =?UTF-8?q?houseMethods=20=E4=B8=AD=20targetUrl/refCode=20=E6=AE=8B?= =?UTF-8?q?=E7=95=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/warehouseMethods/inbox.js | 6 ------ .../migrations/20260803140000-inbox-remove-url-refcode.js | 1 - 2 files changed, 7 deletions(-) delete mode 100644 database/migrations/20260803140000-inbox-remove-url-refcode.js diff --git a/app/service/warehouseMethods/inbox.js b/app/service/warehouseMethods/inbox.js index 847f579..7232976 100644 --- a/app/service/warehouseMethods/inbox.js +++ b/app/service/warehouseMethods/inbox.js @@ -33,10 +33,6 @@ class WarehouseInboxService extends MainService { throw new Error('targetChannel 不能为空'); } - if (!body.targetUrl || !String(body.targetUrl).trim()) { - throw new Error('targetUrl 不能为空'); - } - // 构造 ext_id const extId = `api:${String(appKey || 'unknown')}:${String(body.requestId).trim()}`; @@ -51,8 +47,6 @@ class WarehouseInboxService extends MainService { source_extra: String(appKey || ''), target_type: body.targetType || 'im', target_channel: body.targetChannel, - target_url: body.targetUrl, - ref_code: body.refCode || null, ext_data: body.extData || null, flags: body.flags || {}, }); diff --git a/database/migrations/20260803140000-inbox-remove-url-refcode.js b/database/migrations/20260803140000-inbox-remove-url-refcode.js deleted file mode 100644 index 1d16864..0000000 --- a/database/migrations/20260803140000-inbox-remove-url-refcode.js +++ /dev/null @@ -1 +0,0 @@ -use strict \ No newline at end of file From 11e8bedfaffe1dc1e1d119a201facdb3fcadf03a Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 3 Aug 2026 21:01:42 +0800 Subject: [PATCH 163/550] =?UTF-8?q?fix:=20wms=5Fwave=5Fpick=5Ftask=5Forder?= =?UTF-8?q?.box=5Fno=20=E6=94=B9=E4=B8=BA=E4=B8=8E=20wms=5Forder=5Fwave=5F?= =?UTF-8?q?index.wave=5Findex=20=E4=B8=80=E8=87=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - wave.js buildTaskOrderRows: box_no 优先取 wave_index,无记录时退化为 index+1 - wave.js 任务创建流程: 调用前查询 wms_order_wave_index 获取 wave_index - pick.js createWavePickTask: INSERT 补齐 box_no 列,值取自 wave_index - 所有路径均含 try-catch 降级,查询失败不阻塞任务创建 --- app/service/systemMethods/order/wave.js | 92 ++++++++++++++++++++----- app/service/systemMethods/pick.js | 38 ++++++++++ 2 files changed, 111 insertions(+), 19 deletions(-) diff --git a/app/service/systemMethods/order/wave.js b/app/service/systemMethods/order/wave.js index a655200..451a2ec 100644 --- a/app/service/systemMethods/order/wave.js +++ b/app/service/systemMethods/order/wave.js @@ -3999,8 +3999,9 @@ class WaveService extends OrderBaseService { { specialFieldMap: { quickWhere: { bucket: 'quick' } } } ); const { where: sanitizedWhere, expressNumbers } = this.extractOrderListExpressVirtualFilter(ctxWhere); + const { where: whereAfterBuyerMessage, buyerMessageHas } = this.extractBuyerMessageHasVirtualFilter(sanitizedWhere); const defaultWhere = this.getDefaultWhere('waveStrategyFallbackOrder'); - const mergedWhere = this.mergeWhereObjects(defaultWhere, sanitizedWhere); + const mergedWhere = this.mergeWhereObjects(defaultWhere, whereAfterBuyerMessage); let queryWhere = this.buildWhere(mergedWhere, contextWarehouseId, { specialFieldMap: { quickWhere: { bucket: 'quick' } }, }); @@ -4011,6 +4012,11 @@ class WaveService extends OrderBaseService { queryWhere = this.appendOrderIdsFilterToWhere(queryWhere, orderIds); } + if (buyerMessageHas !== null) { + const buyerMessageCondition = this.buildBuyerMessageHasCondition(buyerMessageHas); + queryWhere = this.appendConditionToWhere(queryWhere, buyerMessageCondition); + } + // 追加 OR 条件:未匹配策略(wave_scan_result=2) 或 已完全打印被排除(print_status='fin') const { Sequelize } = this.app; queryWhere = { @@ -11066,12 +11072,48 @@ class WaveService extends OrderBaseService { selectedWaveIds, waveNoMap, }); + // 查询波次索引(wave_index),使 box_no 与 wms_order_wave_index.wave_index 一致 + const waveIndexMap = new Map(); + if (selectedOrderIds.length > 0 && selectedWaveIds.length > 0) { + try { + const waveIndexRows = await this.ctx.model.query( + `SELECT order_id, wave_index + FROM wms_order_wave_index + WHERE warehouse_id = :warehouseId + AND wave_id IN (:waveIds) + AND order_id IN (:orderIds)`, + { + replacements: { + warehouseId, + waveIds: selectedWaveIds, + orderIds: selectedOrderIds, + }, + type: this.ctx.model.QueryTypes.SELECT, + transaction, + } + ); + for (const wr of (Array.isArray(waveIndexRows) ? waveIndexRows : [])) { + const wrOrderId = Number(wr && wr.order_id || 0); + if (wrOrderId > 0) { + waveIndexMap.set(wrOrderId, Number(wr.wave_index || 0)); + } + } + } catch (e) { + this.ctx.logger.warn('[wave.createTask] 查询波次索引失败,box_no 将退化为任务内序号', { + error: e && e.message, + warehouseId, + waveIds: selectedWaveIds, + }); + } + } + const taskOrderRows = this.buildTaskOrderRows({ taskId, plan: effectivePlan, selectedWaveIds, selectedOrderIds, cartId: normalizedCartId, + waveIndexMap, }); const taskSkuRows = await this.buildTaskSkuRows({ plan: effectivePlan, @@ -11265,12 +11307,16 @@ class WaveService extends OrderBaseService { /** * 构建任务订单明细写入行。 * + * box_no 与 wms_order_wave_index.wave_index 保持一致(波次内全局顺序)。 + * 若 waveIndexMap 中无对应记录,则退化为当前订单在 selectedOrderIds 中的 index + 1。 + * * @param {Object} options 构建参数。 * @param {number} options.taskId 任务ID。 * @param {Object} options.plan 预处理计划。 * @param {Array} options.selectedWaveIds 已选波次ID。 * @param {Array} options.selectedOrderIds 已选订单ID。 * @param {number} options.cartId 绑定车ID。 + * @param {Map} [options.waveIndexMap] orderId → wave_index 映射。 * @return {Array} 任务订单行。 */ buildTaskOrderRows(options = {}) { @@ -11285,30 +11331,38 @@ class WaveService extends OrderBaseService { ? options.selectedOrderIds : []; const cartId = Number(options && options.cartId || 0); + const waveIndexMap = options && options.waveIndexMap instanceof Map + ? options.waveIndexMap + : new Map(); if (![ 2, 3, 4 ].includes(pickMode)) { return []; } const defaultWaveId = selectedWaveIds.length > 0 ? selectedWaveIds[0] : null; - return selectedOrderIds.map((orderId, index) => ({ - task_id: taskId, - wave_id: defaultWaveId, - order_id: orderId, - order_no: null, - box_no: index + 1, - cart_id: cartId > 0 ? cartId : null, - cart_code_snapshot: null, - warehouse_id: warehouseId, - pick_status: 0, - review_status: 0, - review_user_id: null, - review_result: null, - review_remark: null, - exception_reason: null, - picked_time: null, - review_time: null, - })); + return selectedOrderIds.map((orderId, index) => { + const waveIndex = waveIndexMap.has(orderId) + ? Number(waveIndexMap.get(orderId) || 0) + : 0; + return { + task_id: taskId, + wave_id: defaultWaveId, + order_id: orderId, + order_no: null, + box_no: waveIndex > 0 ? waveIndex : (index + 1), + cart_id: cartId > 0 ? cartId : null, + cart_code_snapshot: null, + warehouse_id: warehouseId, + pick_status: 0, + review_status: 0, + review_user_id: null, + review_result: null, + review_remark: null, + exception_reason: null, + picked_time: null, + review_time: null, + }; + }); } /** diff --git a/app/service/systemMethods/pick.js b/app/service/systemMethods/pick.js index 3fae376..5d33c75 100644 --- a/app/service/systemMethods/pick.js +++ b/app/service/systemMethods/pick.js @@ -258,16 +258,52 @@ class PickService extends MainService { ); if (normalizedOrderIds.length > 0) { + // 查询波次索引(wave_index),使 box_no 与 wms_order_wave_index.wave_index 一致 + const waveIndexMap = new Map(); + try { + const waveIndexRows = await ctx.model.query( + `SELECT order_id, wave_index + FROM wms_order_wave_index + WHERE warehouse_id = :warehouseId + AND wave_id = :waveId + AND order_id IN (:orderIds)`, + { + replacements: { + warehouseId, + waveId, + orderIds: normalizedOrderIds, + }, + type: ctx.model.QueryTypes.SELECT, + transaction, + } + ); + for (const wr of (Array.isArray(waveIndexRows) ? waveIndexRows : [])) { + const wrOrderId = Number(wr && wr.order_id || 0); + if (wrOrderId > 0) { + waveIndexMap.set(wrOrderId, Number(wr.wave_index || 0)); + } + } + } catch (e) { + ctx.logger.warn('[pick.createWavePickTask] 查询波次索引失败,box_no 将退化为任务内序号', { + error: e && e.message, + warehouseId, + waveId, + }); + } + const orderValuesSql = []; const orderReplacements = {}; normalizedOrderIds.forEach((orderId, index) => { const orderIdKey = `orderId${index}`; const orderNoKey = `orderNo${index}`; + const boxNoKey = `boxNo${index}`; + const waveIndex = waveIndexMap.get(orderId); orderValuesSql.push(`( :taskId, :waveId, :${orderIdKey}, :${orderNoKey}, + :${boxNoKey}, :warehouseId, 0, 0, @@ -276,6 +312,7 @@ class PickService extends MainService { )`); orderReplacements[orderIdKey] = orderId; orderReplacements[orderNoKey] = orderNoMap.get(orderId) || ''; + orderReplacements[boxNoKey] = Number.isFinite(waveIndex) && waveIndex > 0 ? waveIndex : (index + 1); }); await ctx.model.query( @@ -285,6 +322,7 @@ class PickService extends MainService { wave_id, order_id, order_no, + box_no, warehouse_id, pick_status, review_status, From 7e39159f0bcda005d475513669b90e647734e4ee Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 3 Aug 2026 21:02:31 +0800 Subject: [PATCH 164/550] =?UTF-8?q?feat(setting.expressInterface.list):=20?= =?UTF-8?q?=E6=96=B0=E5=A2=9E=20quantity/recycled=5Fquantity/cancel=5Fquan?= =?UTF-8?q?tity/allocated=5Fquantity=20=E6=89=81=E5=B9=B3=E5=AD=97?= =?UTF-8?q?=E6=AE=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Promise.all 并行调用 index.getShopExpressList 获取店铺快递签约数据 - 三层匹配: sys_express_code → site_code/branch_code → shipperno/customer_code_list - 无店铺或无数据时四字段均为 0 - 补全 response 全部 42 个子字段文档 --- .../systemMethods/setting/expressInterface.js | 120 +- methods/changes/system.json | 10297 ++++++++-------- methods/system.json | 312 +- 3 files changed, 5573 insertions(+), 5156 deletions(-) diff --git a/app/service/systemMethods/setting/expressInterface.js b/app/service/systemMethods/setting/expressInterface.js index 83313d8..e10f187 100644 --- a/app/service/systemMethods/setting/expressInterface.js +++ b/app/service/systemMethods/setting/expressInterface.js @@ -119,7 +119,125 @@ class expressInterfaceService extends MainService { }, }); - return await this.callSystemExpressInterface('list', payload, '获取快递接口列表失败'); + const result = await this.callSystemExpressInterface('list', payload, '获取快递接口列表失败'); + if (result.flag !== 'success') { + return result; + } + + const list = result.data?.list || result.list || []; + if (list.length === 0) { + return result; + } + + // 收集唯一 shop_id(去重) + const shopIds = [...new Set( + list + .map(item => item.shop_id) + .filter(id => id !== null && id !== undefined && Number(id) !== 0) + )]; + + if (shopIds.length === 0) { + const defaultList = list.map(item => ({ ...item, quantity: 0, recycled_quantity: 0, cancel_quantity: 0, allocated_quantity: 0 })); + if (result.data) { + result.data.list = defaultList; + } else { + result.list = defaultList; + } + return result; + } + + const { ctx } = this; + + // 并行调用 getShopExpressList,构建 Map + const shopExpressMap = new Map(); + const shopResults = await Promise.all( + shopIds.map(async (shopId) => { + try { + const shopExpressResult = await ctx.service.systemMethods.index.getShopExpressList({ + shop_id: shopId, + }); + return { shopId: Number(shopId), result: shopExpressResult }; + } catch (err) { + ctx.logger.warn( + `[expressInterface.list] 获取店铺 ${shopId} 快递签约数据异常: ${err.message}` + ); + return { shopId: Number(shopId), result: null }; + } + }) + ); + + for (const { shopId, result: shopResult } of shopResults) { + ctx.logger.info('[expressInterface.list] shopId=' + shopId + ' flag=' + (shopResult ? shopResult.flag : 'null') + ' msg=' + (shopResult ? shopResult.message : 'null')); + if (shopResult && shopResult.flag === 'success') { + const shopExpressList = shopResult.data?.list || shopResult.list || []; + if (shopExpressList.length > 0) { + shopExpressMap.set(shopId, shopExpressList); + } + } + } + + // 为每条记录匹配并汇总 quantity + const enrichedList = list.map(item => { + const shopId = item.shop_id; + if (shopId === null || shopId === undefined) { + return { ...item, quantity: 0, recycled_quantity: 0, cancel_quantity: 0, allocated_quantity: 0 }; + } + + const shopExpressList = shopExpressMap.get(Number(shopId)); + if (!shopExpressList || shopExpressList.length === 0) { + return { ...item, quantity: 0, recycled_quantity: 0, cancel_quantity: 0, allocated_quantity: 0 }; + } + + const sysExpressCode = (item.sys_express_code || '').trim().toUpperCase(); + const expressCode = (item.express_code || '').trim().toUpperCase(); + + // 按 sys_express_code 或 express_code(wp_code) 匹配 + const matchedExpress = shopExpressList.find(expressItem => { + const itemSysCode = (expressItem.sys_express_code || '').trim().toUpperCase(); + const itemWpCode = (expressItem.wp_code || '').trim().toUpperCase(); + return itemSysCode === sysExpressCode + || itemWpCode === expressCode + || itemSysCode === expressCode; + }); + + if (!matchedExpress) { + return { ...item, quantity: 0, recycled_quantity: 0, cancel_quantity: 0, allocated_quantity: 0 }; + } + + let accounts = Array.isArray(matchedExpress.accounts) ? matchedExpress.accounts : []; + + // 若有 site_code,进一步按 branch_code 筛选匹配的网点账号 + const siteCode = (item.site_code || '').trim().toUpperCase(); + if (siteCode) { + const branchMatched = accounts.filter(acc => + (acc.branch_code || '').trim().toUpperCase() === siteCode + ); + if (branchMatched.length > 0) { + accounts = branchMatched; + } + } + + // 若有 shipperno,进一步按 customer_code_list 筛选匹配的账号 + const shipperNo = (item.shipperno || '').trim(); + if (shipperNo && accounts.length > 0) { + const shipperMatched = accounts.filter(acc => + Array.isArray(acc.customer_code_list) && acc.customer_code_list.includes(shipperNo) + ); + if (shipperMatched.length > 0) { + accounts = shipperMatched; + } + } + + return { ...item, quantity: accounts.reduce((sum, acc) => sum + (Number(acc.quantity) || 0), 0), recycled_quantity: accounts.reduce((sum, acc) => sum + (Number(acc.recycled_quantity) || 0), 0), cancel_quantity: accounts.reduce((sum, acc) => sum + (Number(acc.cancel_quantity) || 0), 0), allocated_quantity: accounts.reduce((sum, acc) => sum + (Number(acc.allocated_quantity) || 0), 0) }; + }); + + if (result.data) { + result.data.list = enrichedList; + } else { + result.list = enrichedList; + } + + return result; } /** diff --git a/methods/changes/system.json b/methods/changes/system.json index 8539d6e..31505a0 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,5137 +1,5164 @@ [ - { - "version": "2026.08.01-system-01", - "date": "2026-08-01", - "type": "added", - "summary": "新增 apiApp 仓库 API 应用管理模块,支持当前仓库维度的 API 应用 CRUD、AppKey/Secret 自动生成与重新生成、IP 白名单、回调地址、限流等配置", - "methods": [ - "apiApp.list", - "apiApp.detail", - "apiApp.create", - "apiApp.update", - "apiApp.delete", - "apiApp.regenerateSecret" - ], - "notes": [ - "apiApp.list:分页查询当前仓库 API 应用列表,支持按 app_name(模糊)、is_enabled 筛选,Secret 自动脱敏(前8位+****)。", - "apiApp.detail:按 ID 查询单个应用详情,需同时匹配 warehouse_id(自动注入 ctx.user.store_id),Secret 脱敏。", - "apiApp.create:创建应用时自动生成 AppKey(AK{yyyyMMddHHmmss}{random8hex})和 AppSecret(64位hex)。默认 interface_type_id 取 WH_CHANNEL。仅创建时返回完整 Secret。", - "apiApp.update:更新可编辑字段(app_name、self_ip_whitelist、callback_url、rate_limit、sign_method、is_enabled),不可变字段为 self_app_key 和 interface_type_id。", - "apiApp.delete:软删除(is_enabled=0),不物理删除。", - "apiApp.regenerateSecret:重新生成 64位hex AppSecret,旧 Secret 立即失效。仅此次返回完整 Secret。", - "仓库隔离:所有操作按 ctx.user.store_id → warehouse_id 自动过滤。", - "Secret 安全策略:list/detail/update 返回脱敏值,仅 create/regenerateSecret 返回完整 Secret。" - ], - "module": "apiApp" - }, - { - "version": "2026.07.31-system-02", - "date": "2026-07-31", - "type": "added", - "summary": "新增 storage.inventory.export 库存导出与 storage.inventory.exportTaskProgress 导出进度查询,入参复用 list 的 where/sort/group_by_batch 语义,支持两种导出模式(聚合汇总 / 逐条明细),库位信息一并导出", - "methods": [ - "storage.inventory.export", - "storage.inventory.exportTaskProgress" - ], - "notes": [ - "storage.inventory.export:异步提交导出任务,返回 task_id 与受理信息,后端异步生成 Excel 并上传。入参 where/sort/group_by_batch 与 storage.inventory.list 完全一致,无需额外学习成本。", - "group_by_batch=false(默认):按 stock_id + space_id(库位)聚合导出库存汇总,含商品编码/名称/规格/单位/货主/库位编码/名称/总库存/锁定/可用/批次数/最近入库时间。", - "group_by_batch=true:按 storage_id 逐条导出库存明细,含库存记录ID/商品信息/库位信息/批次号/库存类型/数量/生产日期/过期日期/入库时间/入库单号/供应商批次号。", - "新增 storage.inventory.exportTaskProgress:按 task_id/taskId 查询导出任务进度与状态(submitted/running/success/failed/not_found),status=success 时返回 download_url 供客户端下载。", - "导出文件目录:exports/storage/inventory/{warehouseId}/,缓存 TTL 1800 秒。" - ], - "module": "storage.inventory" - }, - { - "version": "2026.07.31-system-01", - "date": "2026-07-31", - "type": "added", - "summary": "新增按波次批量快捷复核接口 batchQuickRecheckByWave,支持批量波次 IDs 的前置条件检查(储位、快递、同步、拦截),自动完成拣货并标记复核,支持部分失败", - "methods": [ - "order.recheckOrder.batchQuickRecheckByWave" - ], - "notes": [ - "新增 order.recheckOrder.batchQuickRecheckByWave 方法,复用 batchQuickRecheck 的 _completePickForOrder / _markRecheckForOrder / _tryCompleteWaveInTransaction 等内部事务方法", - "入参 wave_ids 支持数组或逗号分隔字符串,兼容 waveIds(驼峰)、wave_id(单值)", - "按波次维度批量查询订单后逐波次、逐订单执行前置校验与复核,每个订单独立事务,部分失败不影响其他订单", - "响应包含 success/failed 列表及计数,failed 项含 order_id、wave_id、delivery_order_code、reason 说明;波次下无订单时仅返回 wave_id + reason" - ], - "module": "order.recheckOrder" - }, - { - "version": "2026.07.29-system-01", - "date": "2026-07-29", - "type": "added", - "summary": "补全 waybill.warehouse group API 文档参数定义:完善 list/detail/export 的 params 与 response,新增 exportTaskProgress 异步进度查询接口", - "methods": [ - "waybill.warehouse.list", - "waybill.warehouse.detail", - "waybill.warehouse.export", - "waybill.warehouse.exportTaskProgress" - ], - "notes": [ - "waybill.warehouse.list:params 含 pagination/where/sort 完整字段定义,where 支持 15 个筛选维度(运单号、主单号、订单ID、订单号、物流编码、物流接口ID、平台编码、状态、退回/拦截/星河签收、包材ID、已称重、关键词、创建时间范围),sort 白名单 create_at/weighing_weight/id。response 含 list(28 个字段)+ pagination。", - "waybill.warehouse.detail:修正 id 参数为可选(required: false),与 waybillCode 二选一,waybillCode 优先。response 含 id/waybill_code/main_waybill_code/waybill_type/business_key/sibling_waybills/order/logistics/status_info/weight/package/print_records/print_count 等完整详情。", - "waybill.warehouse.export:response 补充 progress/message/update_time 字段,完整覆盖异步任务返回信息。", - "新增 waybill.warehouse.exportTaskProgress:按 task_id/taskId 查询导出进度,response 含 task_id/status/progress/current_count/total_count/message/result/error/download_url/update_time。", - "所有接口 isNeedAuth: false, isNeedLogin: true,仓库隔离通过 ctx.user.store_id 自动注入。" - ], - "module": "waybill.warehouse" - }, - { - "version": "2026.07.28-system-01", - "date": "2026-07-28", - "type": "added", - "summary": "新增 order.pendingOrder.batchMarkPrinted:批量设置订单为已打印状态,将 print_status 更新为 'fin'", - "methods": [ - "order.pendingOrder.batchMarkPrinted" - ], - "notes": [ - "同步批量更新接口,传入订单ID数组,直接将符合条件的订单 print_status 设为 'fin'。", - "双表查询:先查 current 表(wms_order_delivery_{warehouseId}),未命中的 ID 再兜底查 dispatch 表(wms_order_delivery_{warehouseId}_dispatch)。", - "dispatch 表查询失败仅记录 warn 日志,不影响 current 表已更新的结果。", - "仅允许 step 在 [1,2,3] 且 status 不为 'cancel' 的订单操作,已打印(print_status='fin')的订单会被静默跳过。", - "仓库上下文强制从 ctx.user.store_id 获取,禁止传入外部仓库ID。", - "入参支持 order_ids / orderIds / ids 三种别名,优先级 order_ids > orderIds > ids。", - "返回 updated_count 表示实际更新条数(current + dispatch 合计),ids 原样回传请求的订单ID列表。", - "写入操作日志 operation_code: ORDER_BATCH_MARK_PRINTED。" - ], - "module": "order.pendingOrder" - }, - { - "version": "2026.07.27-system-03", - "date": "2026-07-27", - "type": "changed", - "summary": "storage.receiving 导出接口拆分:export 改为按仓库维度,新增 storeExport 按货主维度导出", - "methods": [ - "storage.receiving.export", - "storage.receiving.exportTaskProgress", - "storage.receiving.storeExport", - "storage.receiving.storeExportTaskProgress" - ], - "notes": [ - "export 改为仓库维度:过滤条件从 store_id(平台激活货主)改为 warehouse_id(ctx.user.store_id),与 getReceivingList 保持一致。", - "exportTaskProgress 同步更新为仓库维度进度查询,任务 ID 前缀 receiving_export_。", - "新增 storeExport:货主维度导出,通过平台激活上下文获取 store_id,过滤逻辑与 getStoreReceivingList 一致。", - "新增 storeExportTaskProgress:货主维度进度查询,复用 exportTaskProgress 的缓存逻辑,任务 ID 前缀 receiving_store_export_。", - "导出格式:双 Sheet Excel(Sheet1=收货单列表 21 列,Sheet2=收货单明细 17 列),通过 ExcelJS stream + uploadService 上传 COS。", - "仓库导出上传路径 exports/receiving/{warehouseId}/,货主导出上传路径 exports/receiving/store/{storeId}/。", - "修复 exportReceivingList 中 where 条件二次解析问题:增加 ctx.whereParsed 复用(与 getStoreReceivingList 一致),避免 prepareWhereContext 已解析后再重复 parseWhereConditions 导致边界条件丢失。", - "命名对齐 entry 侧:storeExport / storeExportTaskProgress 方法名、任务 ID 前缀、上传路径均与 storage.entry.storeExport 模式一致。" - ], - "module": "storage.receiving" - }, - { - "version": "2026.07.27-system-02", - "date": "2026-07-27", - "type": "added", - "summary": "新增 order.pendingOrder.allocateSubOrderNumber:待处理订单分配子单号(异步任务),business_key 从 2 开始递增,跳过已分配运单号;新增 allocateSubOrderNumberProgress 按 task_id/business_key 查询进度", - "methods": [ - "order.pendingOrder.allocateSubOrderNumber", - "order.pendingOrder.allocateSubOrderNumberProgress" - ], - "notes": [ - "新增 allocateSubOrderNumber:入参 order_id + sub_order_count,按 business_key 2..(2+count-1) 全量传入 createWaybillCodePipeline。", - "并发安全:全量传入 pipeline,由其内部事务 + UNIQUE(order_id,business_key,status,warehouse_id) 索引保证并发去重。", - "pipeline 内部 createWaybillCode 事务:status=1 已分配→跳过;status=0 占位中→复用;无记录→INSERT status=0 占位。", - "异步任务模式:请求立即返回 task_id(sub_ 前缀),后台 setImmediate 执行,进度通过 Redis 缓存追踪。", - "新增 allocateSubOrderNumberProgress:支持 task_id 查整体进度,business_key 可选参数过滤单个业务ID的详情。", - "进度状态 submitted→running→success/partial/failed,progress 对应 5/50/80/100。", - "result.details 数组记录每个 business_key 的 status(skipped/allocated/failed/pending)与 waybill_code。", - "buildSubOrderDetails 回查最终状态:status=1+waybill→allocated,status=0→failed,无记录→failed。" - ], - "module": "order.pendingOrder" - }, - { - "version": "2026.07.27-system-01", - "date": "2026-07-27", - "type": "added", - "summary": "新增 order.packing 打包任务模块:list/get 查询 + setEndTime 设置结束时间,含视频 CDN URL 拼接与状态回写", - "methods": [ - "order.packing.list", - "order.packing.get", - "order.packing.setEndTime", - "order.packing.forceRecord" - ], - "notes": [ - "新增 order.packing.list:按仓库维度查询打包任务列表,支持分页/筛选/排序,关联工作台、视频和运单信息。", - "新增 order.packing.get:按 id + warehouse_id 查询单条打包任务详情。", - "新增 order.packing.setEndTime:设置打包任务结束时间,入参 id + end_time;若任务状态不是已完成(2)则同步更新为已完成。", - "新增 order.packing.forceRecord:强制重新录制打包任务视频,入参 id;校验录制电脑在线后重置视频状态并推送打印服务。", - "前端默认值逻辑:若任务已有 end_time 则打开时默认为当前时间,否则默认为 start_time + 5分钟。", - "视频 URL 自动拼接 CDN 域名前缀:http://w{warehouseId}-c{recordingComputerId}.o.gztbyc.com{videoPath};录制电脑从 wms_print_computer 按 is_recording=true 获取。", - "视频响应新增 status 字段(created/recording/completed/failed),与数据库 ENUM 保持一致。", - "pack_task_video Model 的 status 字段从 TINYINT 改为 STRING(20) 以匹配 DB ENUM 迁移。", - "forceRecord 通过打印服务 /record/force 推送录制任务,传入 pack_task_id、warehouse_id、computer_id、camera_ids。" - ], - "module": "order.packing" - }, - { - "version": "2026.07.10-system-01", - "date": "2026-07-10", - "type": "added", - "summary": "新增 storage.report.searchStore 货主侧库存报表,以 store_id 为主维度查询库存流水", - "methods": [ - "storage.report.searchStore", - "storage.report.exportStore" - ], - "notes": [ - "新增 searchStore 方法:与 search 共享核心逻辑,通过 searchMode='store' 切换主维度从 warehouse_id → store_id。", - "新增 exportStore 方法:与 export 共享核心逻辑,支持货主侧导出 Excel(含汇总 + 变更记录两个 sheet)。", - "systems 层 search/export 方法新增 searchMode 参数(默认 'warehouse'),不影响现有 warehouse 侧行为。", - "货主侧使用 ctx.user.store_id 作为主维度 store_id,辅助维度支持 warehouse_ids 过滤特定仓库。", - "systemMethods 层 searchStore 从 where.warehouse_ids 取值传给 search 的 storeIds(承载 warehouse 过滤)。", - "输出新增 warehouse_id / warehouse_name 字段,货主侧可区分不同仓库的库存。search 方法也同步输出这两个字段(向后兼容)。", - "修复 getStockDetails 的 warehouseId 判断:从 != null 改为 !== undefined,使显式传 null 可跳过 warehouse 过滤。", - "修复 loadReportReferenceMaps 未传递 warehouseId 给 getStockDetails 的问题。" - ], - "module": "storage.report" - }, - { - "version": "2026.07.09-system-01", - "date": "2026-07-09", - "type": "updated", - "summary": "签约 sign 方法改造:统一当前主体→store_id,解除角色校验,仓库可签仓库", - "methods": [ - "storeWarehouse.store.sign", - "storeWarehouse.warehouse.sign" - ], - "notes": [ - "resolvePairIds:统一当前主体始终在 store_id(货主方/消费方),对方在 warehouse_id(仓库方/提供方)。不再根据 isWarehouse 分支。", - "getCounterparty:移除 expectedRole 角色校验(仓库不再只能签货主,可签仓库)。", - "findScopedRelation:改为 OR 查询 store_id/warehouse_id 两边,兼容新旧签约数据。", - "sign preview:counterparty.role 改为根据对方 project 真实返回(warehouse/store),不再硬编码反推。", - "签仓库:仓库发起签约时对方 ID 传 counterparty_id,系统自动将当前仓库放 store_id。" - ], - "module": "storeWarehouse" - }, - { - "version": "2026.07.08-system-01", - "date": "2026-07-08", - "type": "updated", - "summary": "storeWarehouse.store.list 与 storeWarehouse.warehouse.list 拆分实现,不再共用;仓库侧支持查询外部合作仓库", - "methods": [ - "storeWarehouse.store.list", - "storeWarehouse.warehouse.list" - ], - "notes": [ - "拆分:store.list 调用 listForStore,warehouse.list 调用 listForWarehouse,不再共用同一个 list 方法。", - "新规则:两个方法均按 store_id = 当前主体ID 过滤(主体在 store_id 为货主方/消费方,对方在 warehouse_id 为仓库方/提供方)。", - "warehouse.list 新增支持查询外部合作仓库:当对方主体的 project='warehouse' 时为仓库-仓库合作,counterparty_role='warehouse'。", - "响应新增 counterparty_role 字段(store/warehouse),标识对方主体的真实角色。", - "warehouse.list 响应 use_status 改为 store_use_status(仓库在 store_id 方时,己方启用状态应为 store_use_status)。", - "旧 list 方法保留标记为 @deprecated,保持向后兼容。", - "新增 buildListWhereByStoreId 统一按 store_id 维度构建查询条件。" - ], - "module": "storeWarehouse" - }, - { - "version": "2026.07.06-system-01", - "date": "2026-07-06", - "type": "updated", - "summary": "order.wave.batchList:响应新增 pick_assignment_status(拣货分配状态),按订单 pick_status 聚合判定", - "methods": [ - "order.wave.batchList" - ], - "notes": [ - "响应 list 每项新增字段 pick_assignment_status (string):拣货分配状态,按波次下订单的 pick_status 聚合判定。", - "取值语义与 resolveAssignmentStatus 一致,自定义标签:未拣货(全 none)、部分拣货(混合且无 error)、已拣货(全 fin)、拣货异常(含 error)。", - "SQL 子查询新增 pick_none_count / pick_fin_count / pick_error_count 聚合列。" - ], - "module": "order.wave" - }, - { - "version": "2026.07.05-system-01", - "date": "2026-07-05", - "type": "added", - "summary": "新增 pick.wavePickComplete:传入 wave_id 一键完成整个波次拣货,内部复用 query 去重与任务创建逻辑后自动调用 wavePickTaskComplete(mode=1)", - "methods": [ - "pick.wavePickComplete" - ], - "notes": [ - "新增方法:pick.wavePickComplete,入参 wave_id(number,必填)。", - "内部流程:按 wave_id 查波次 → 活动任务去重(同用户复用 / 他人409冲突)→ 完成任务去重 → 无任务则创建(source=2 后台抓取)→ 调用 pick.wavePickTaskComplete mode=1 全部确认。", - "创建任务 remark 格式:pick.wavePickComplete wave_id={waveId},用于与 pick.query 区分。", - "响应:task_id、status(completed / already_completed)、tip、confirmed_order_ids、is_completed、progress。", - "错误码:400(参数/波次无订单)、401(缺少操作人)、404(波次不存在)、409(他人活动任务冲突)、500(创建/完成失败)。" - ], - "module": "pick" - }, - { - "version": "2026.07.03-system-02", - "date": "2026-07-03", - "type": "added", - "summary": "新增 order.pendingOrder.updateRemark:批量修改待处理订单备注(remark),不受 post_status 限制", - "methods": [ - "order.pendingOrder.updateRemark" - ], - "notes": [ - "新增方法:order.pendingOrder.updateRemark,用于批量修改待处理订单的备注(remark)字段。", - "入参:ids(number[],必填,正整数数组,不能为空)、remark(string,必填,最大500字符)。", - "特性:不受 post_status 限制,可对所有状态的订单生效;纯批量不支持单ID。", - "更新成功后写入操作日志。", - "响应:updated_count(number,实际更新行数)、ids(number[],原样返回请求的ID数组)。", - "错误码:400(ids 不能为空 / ids 仅支持正整数数组 / remark 不能为空)。" - ], - "module": "order.pendingOrder" - }, - { - "version": "2026.07.03-system-01", - "date": "2026-07-03", - "type": "updated", - "summary": "将 quick.waybill.toOrder 迁移为 index.toOrder 并移入基础模块,新增 waves 返回字段", - "methods": [ - "quick.waybill.toOrder", - "index.toOrder" - ], - "notes": [ - "移除快捷操作(quick)模块分组,原 quick.waybill.toOrder 方法从 methods/system.json 删除。", - "在基础模块(index)新增 index.toOrder 方法:入参仍为 waybill_code,响应从单一 order_id 扩展为 order_id + waves 结构。", - "waves 为数组,每项含 wave_id(波次ID)、wave_no(波次号)、order_ids(波次下所有订单ID列表),无波次时为空数组。", - "查询路径:运单号 → wms_order_express(status=1)→ order_id + warehouse_id → 遍历 current/history/dispatch 表获取波次信息 → 再遍历多表获取同波次所有订单ID。" - ] - }, - { - "date": "2026-06-24", - "type": "addition", - "summary": "新增批量绑定入库单明细与收货单明细接口,支持明细级数量分配与部分成功", - "version": "2026-06-24-add-bind-receiving-details", - "methods": [ - "storage.entry.bindReceivingDetails" - ], - "notes": [] - }, - { - "date": "2026-06-24", - "type": "deprecation", - "summary": "废弃手动匹配入库单收货单接口,由 storage.entry.bindReceivingDetails 替代", - "version": "2026-06-24-deprecate-manual-match-entry-order", - "methods": [ - "storage.receiving.manualMatchEntryOrder" - ], - "notes": [] - }, - { - "version": "2026.06.16-system-03", - "date": "2026-06-16", - "summary": "order.wave.waveStrategyFallbackOrderList 响应新增 items_weight(总重量g)和 weight_type(重量类型)字段", - "methods": [ - "order.wave.waveStrategyFallbackOrderList" - ], - "notes": [ - "响应 list 每项新增字段 items_weight (number|null):订单总重量(g),来自 wms_order.items_weight,为 null 时返回 null。", - "响应 list 每项新增字段 weight_type (string):重量类型中文标签,来自 wms_order.weight_type 经 formatWeightTypeLabel 转换;取值:常规/轻货/重货/冷链(对应 DB 值 0/1/2/3)。" - ], - "type": "updated", - "module": "order.wave" - }, - { - "version": "2026.06.16-system-04", - "date": "2026-06-16", - "summary": "order.wave.singleOrderFetchList 响应新增 items_weight(总重量g)字段", - "methods": [ - "order.wave.singleOrderFetchList" - ], - "notes": [ - "响应 list 每项新增字段 items_weight (number|null):订单总重量(g),取组内首单 items_weight;组内订单 items_hash 相同重量一致。", - "为 null 时返回 null。" - ], - "type": "updated", - "module": "order.wave" - }, - { - "version": "2026.05.20-system-03", - "date": "2026-05-20", - "summary": "新增 storeWarehouse.store.queryPrintQuantityLogs:按 store_id 分页查询面单余额变更日志", - "methods": [ - "storeWarehouse.store.queryPrintQuantityLogs" - ], - "notes": [ - "新增方法:storeWarehouse.store.queryPrintQuantityLogs,用于按货主(store_id)分页查询面单余额变更日志。", - "入参:store_id(必填)、page(可选)、page_size / pageSize(可选,兼容别名)。", - "仅同步 methods/system.json 与本变更记录,不修改业务代码或测试。", - "返回:使用默认分页格式,响应在 `data` 下包含 `list`(变更日志数组)和 `pagination` 对象,`pagination` 字段:`page`、`pageSize`、`total`、`totalPages`、`hasPrevious`、`hasNext`。" - ], - "type": "added", - "module": "storeWarehouse" - }, - { - "version": "2026.05.13-system-01", - "date": "2026-05-13", - "summary": "完善 print.send 的 API 文档与返回说明", - "methods": [ - "print.send" - ], - "notes": [ - "补充请求参数说明:computerId、printer、template、data、type 标为必填,count、timestamp 保持可选。", - "补充 template 的子字段说明:page_width、page_height、template_content。", - "补充响应结构:flag、code、message、printId;其中成功时 code=200。", - "补充错误码说明:1001 对应不支持的打印类型,504 对应打印任务发送失败(包含打印机不存在、脱机、通讯失败等场景)。" - ], - "type": "updated" - }, - { - "version": "2026.05.08-system-06", - "date": "2026-05-08", - "summary": "新增取消拣货任务接口:order.wave.wavePickTaskCancel", - "methods": [ - "order.wave.wavePickTaskCancel" - ], - "notes": [ - "接口功能:取消拣货任务,同时释放关联波次(物理删除波次记录,订单回池)、解绑拣货车、写操作日志。", - "限制:仅允许在任务状态为 0(待开始)、1(拣货中)、2(待复核)时取消;状态为 3(已完成)或 9(已取消)时禁止取消,返回 400。", - "事务内操作:将任务状态更新为 9(已取消)、删除关联波次、清空订单 wave_id(回池)、解绑拣货车、写入 action_log 与 order_pick_trace;若有任一步骤失败则回滚并返回 500。" - ], - "type": "added" - }, - { - "version": "2026.07.01-system-01", - "date": "2026-07-01", - "summary": "storage.directInbound.addItem 参数名修正:entry_order_code → entry_order_id,类型 string → number", - "methods": [ - "storage.directInbound.addItem" - ], - "notes": [ - "文档 params 中 entry_order_code(string)改为 entry_order_id(number),与代码 app/service/systems/inbound_direct_log.js 第 544 行实际校验保持一致", - "同步修正 app/service/systemMethods/storage/direct_inbound.js JSDoc:@param {string} data.entry_order_code → @param {number} data.entry_order_id" - ], - "type": "fixed", - "module": "storage.directInbound" - }, - { - "version": "2026.07.01-system-02", - "date": "2026-07-01", - "summary": "新增 storage.entry.queryEntryLogs 接口文档定义", - "methods": [ - "storage.entry.queryEntryLogs" - ], - "notes": [ - "代码 method 层(systemMethods/storage/entry.js L284)和 systems 层(systems/operation_log.js L318)均已实现,补充文档定义", - "参数:id(number, required)、page(number, optional, 默认1)、pageSize(number, optional, 默认20)" - ], - "type": "added", - "module": "storage.entry" - }, - { - "version": "2026.06.18-system-01", - "date": "2026-06-18", - "summary": "order.pendingOrder.downloadCreateTemplate:模板列顺序调整,店铺名称(shop_nick)从末尾移至第2列B列,紧接*订单号之后", - "methods": [ - "order.pendingOrder.downloadCreateTemplate" - ], - "notes": [ - "调整 Excel 导入模板列顺序:店铺名称(shop_nick)从原第25列(Y列/末尾)移动至第2列(B列),紧跟在*订单号(delivery_order_code)之后。", - "同步更新 description 中的列顺序描述,明确 25 列(A-Y)的完整排列。", - "响应结构中移除冗余的 shop_nick 字段(模板列不属于 API 响应字段)。" - ], - "type": "updated", - "module": "order.pendingOrder" - }, - { - "version": "2026.05.17-system-09", - "date": "2026-05-17", - "summary": "为 storage.receiving.deleteDetail 文档补充约束:收货单已完成/已取消时禁止删除明细", - "methods": [ - "storage.receiving.deleteDetail" - ], - "notes": [ - "在 storage.receiving.deleteDetail 的 description 中补充:若关联收货单状态为 completed(已完成)或 cancelled(已取消),接口会返回删除失败(400),不允许删除明细。", - "在 errors 中补充或合并 400 描述以明确禁止删除已完成/已取消的收货单明细。" - ], - "type": "updated", - "module": "storage" - }, - { - "version": "2026.05.17-system-08", - "date": "2026-05-17", - "summary": "完善 storage.receiving.deleteDetail 文档:补充入参/返回/错误说明,明确用户上下文来源及删除约束", - "methods": [ - "storage.receiving.deleteDetail" - ], - "notes": [ - "补充 storage.receiving.deleteDetail 的参数说明:detail_id(来自请求体,必填);说明 creator_id 与 warehouse_id 来源于当前登录用户(ctx.user.employees_id / ctx.user.store_id)。", - "补充返回结构:成功时返回 code/message/data,data 包含 details(删除后剩余明细)和 selectId(建议选中ID);product_snapshot 若存在将被解析为对象或 null。", - "补充常见错误码:404(明细不存在或无权访问),400(收货单状态/已入库/删除失败),500(服务器异常)。", - "仅文档更新,不修改任何业务实现。" - ], - "type": "updated", - "module": "storage" - }, - { - "version": "2026.05.17-system-05", - "date": "2026-05-17", - "summary": "移除 storage.receiving.addItem(方法已下线/实现不存在)", - "methods": [ - "storage.receiving.addItem" - ], - "notes": [ - "仅同步文档:从 methods/system.json 中移除 storage.receiving.addItem,未修改任何业务代码或实现。", - "该方法已下线或实现不存在;请以当前 methods/system.json 的 SSOT 为准。" - ], - "type": "removed" - }, - { - "version": "2026.05.17-system-04", - "date": "2026-05-17", - "summary": "新增 stock.warehouse.import:仓库商品批量 JSON 导入(数组导入),SKU 为空创建/非空更新,支持 goods_code/货物编码 导入,更新写操作日志", - "methods": [ - "stock.warehouse.import" - ], - "notes": [ - "支持直接传入商品数组 JSON(主方式为数组,兼容 rows/items/list/data 包装)。", - "每项仅需传商品相关字段;SKU 为空时创建新商品,SKU 非空时为更新操作。", - "更新操作会写入操作日志以便审计。", - "支持导入 goods_code(货物编码)字段别名。", - "仅同步文档,不修改业务代码或实现。" - ], - "type": "added" - }, - { - "version": "2026.05.17-system-03", - "date": "2026-05-17", - "summary": "完善 stock.warehouse.handleBatchChange 文档:补充入参/出参/错误示例", - "methods": [ - "stock.warehouse.handleBatchChange" - ], - "notes": [ - "补充方法入参说明:ids/method/value 的字段类型、是否必填、来源与示例;完善响应结构示例与常见错误码说明。", - "仅文档更新,不改业务实现或语义。" - ], - "type": "updated" - }, - { - "version": "2026.05.17-system-02", - "date": "2026-05-17", - "summary": "stock.warehouse.export 由同步改为异步任务并新增进度查询 exportTaskProgress", - "methods": [ - "stock.warehouse.export", - "stock.warehouse.exportTaskProgress" - ], - "notes": [ - "stock.warehouse.export 改为异步提交导出任务:接口返回 task_id 与受理信息,后端异步生成导出文件。", - "新增 stock.warehouse.exportTaskProgress:按 task_id 查询任务状态与进度;当 status=success 时返回 download_url 供客户端下载;未找到时 status=not_found。", - "调用方式:先调用 stock.warehouse.export 获取 task_id,然后轮询 stock.warehouse.exportTaskProgress 直到 status=success 并获取 download_url。" - ], - "type": "updated" - }, - { - "version": "2026.05.17-system-01", - "date": "2026-05-17", - "summary": "新增 stock.warehouse.export:仓库商品导出(支持 where/sort),返回文件下载信息", - "methods": [ - "stock.warehouse.export" - ], - "notes": [ - "新增方法:stock.warehouse.export。复用 stock.warehouse.list 的 where/sort 过滤语义(支持 operator/value/type 标准 where 结构与历史简写)。", - "响应返回导出结果(示例字段:file_key、url),表示生成的 Excel 已上传并可下载/查询。" - ], - "type": "added" - }, - { - "version": "2026.05.16-system-01", - "date": "2026-05-16", - "summary": "同步 setting.expressInterface.create 文档入参:移除未使用的 express_platform_id,标注必填字段", - "methods": [ - "setting.expressInterface.create" - ], - "notes": [ - "移除文档中 express_platform_id(服务端实现未使用);确认必填字段 name/express_code/platform_code;仓库由系统自动填充,禁止传入 warehouse_id/warehouseId。" - ], - "type": "updated" - }, - { - "version": "2026.05.12-system-01", - "date": "2026-05-12", - "summary": "调整订单打印中间态返回结构为 waveGroups(波次 -> 平台 -> 订单)", - "methods": [ - "order.print.getWavePlatformPrintData" - ], - "notes": [ - "主要变更:将方法的主返回结构改为 waveGroups,按波次分组,波次内按平台分组,平台内为订单列表(波次 -> 平台 -> 订单)。", - "兼容性:保留旧字段 platform_groups 与 order_list 作为向后兼容字段,但文档主结构与推荐使用为 waveGroups。", - "返回结构说明:summary(total_waves/total_orders/total_platforms)、wave_ids(通过过滤的波次ID数组)、waveGroups(数组,项含 wave_id、wave_no、order_count、platforms[...],platforms项含 platform、platform_name、order_count、orders[...])、ext(missing_wave_ids、filtered_wave_ids)。", - "errors:保留 400 / 500 不变。" - ], - "type": "modified" - }, - { - "version": "2026.05.11-system-05", - "date": "2026-05-11", - "summary": "order.wave.batchList:支持 express/print 分配状态筛选,入参改为英文枚举(express/print)", - "methods": [ - "order.wave.batchList" - ], - "notes": [ - "修复 where.express_assignment_status 可按快递分配状态筛选。", - "新增 where.print_assignment_status 筛选(按打印分配聚合判断)。", - "express_assignment_status / print_assignment_status 要求使用英文枚举值:express=unassigned/partially_assigned/assigned,print=unprinted/partially_printed/printed;storage_assignment_status 继续兼容中文枚举(未分配/部分分配/已分配)。", - "若传入非法枚举值,接口返回 400(参数校验失败),message 中会说明允许取值。" - ], - "type": "updated" - }, - { - "version": "2026.05.11-system-04", - "date": "2026-05-11", - "summary": "调整 order.wave.waveStrategyFetchAdmin:由创建任务改为直接创建波次(不创建拣货任务)", - "methods": [ - "order.wave.waveStrategyFetchAdmin" - ], - "notes": [ - "接口行为变更:按策略直接抓取命中订单并创建波次,不再创建拣货任务(不返回 task_id/task_no 等任务字段)。", - "响应调整为建波结果:fetch_state(1=成功/2=失败)、wave_ids、wave_nos、created_wave_count、created_order_count、order_ids、(可选)wave_prefix、wave_prefix_source、tip/message。", - "错误调整:策略校验失败返回 400(并可能返回 validation_errors),缺少仓库上下文返回 400,建波失败返回 500 并在 message 中说明。" - ], - "type": "updated" - }, - { - "version": "2026.05.11-system-03", - "date": "2026-05-11", - "summary": "更新 pick.query:由查询拣货明细调整为按 keyword 获取/创建拣货任务", - "methods": [ - "pick.query" - ], - "notes": [ - "入参由 waybill_code/full_display 调整为 keyword(支持运单号或波次号)。", - "接口语义调整为任务化返回:命中活动任务则返回 existing 任务ID;无活动任务则创建并返回 created 任务ID。", - "新增任务归属冲突错误:当活动任务创建人非当前用户时返回冲突提示,并附带创建人及任务ID信息。" - ], - "type": "updated" - }, - { - "version": "2026.05.11-system-02", - "date": "2026-05-11", - "summary": "新增 pick.wavePickTaskCurrent:PDA 无参查询当前进行中拣货任务", - "methods": [ - "pick.wavePickTaskCurrent" - ], - "notes": [ - "新增 PDA 专用无参接口 pick.wavePickTaskCurrent。", - "按当前登录用户上下文(pick_user_id + warehouse_id)查询状态在 0/1/2 的最新任务。", - "命中返回 task_id,未命中返回 task_id=null。" - ], - "type": "added" - }, - { - "version": "2026.05.10-system-04", - "date": "2026-05-10", - "summary": "pick.wavePickTaskDetail 新增按任务类型区分的 picking_view 形态输出", - "methods": [ - "pick.wavePickTaskDetail" - ], - "notes": [ - "新增响应字段:picking_view(object),按 task.pick_mode 区分 5 种形态输出。", - "picking_view 字段说明:mode_code, mode_name, require_box_allocations, group_by, sort_by, items[](每项含 space_id、space_name、location_space、item_code、item_name、stock_id、total_qty、box_allocations[])。", - "当 pick_mode=1/3/4 时 require_box_allocations=true;当 pick_mode=2/5 时 require_box_allocations=false。" - ], - "type": "updated" - }, - { - "version": "2026.05.10-system-02", - "date": "2026-05-10", - "summary": "order.wave.waveStrategyFetchPda/Admin 返回新增 fetch_state 三态与简短 tip", - "methods": [ - "order.wave.waveStrategyFetchPda", - "order.wave.waveStrategyFetchAdmin" - ], - "notes": [ - "新增返回字段:fetch_state(number)、tip(string)、can_enter_pick_flow(boolean)", - "fetch_state 含义:1=创建成功(返回 task_id/task_no),2=普通失败(task_id=null),3=存在未完成任务(返回 existing task_id/task_no,前端可直接进入拣货流程)", - "当 fetch_state=3 时,字段 can_enter_pick_flow=true,表示前端可直接进入拣货流程;tip 为简短提示文本" - ], - "type": "updated" - }, - { - "version": "2026.05.10-system-03", - "date": "2026-05-10", - "summary": "裁剪 pick.wavePickTaskDetail 返回:移除 waves/orders,精简 task 并补充 boxes 拣货统计字段", - "methods": [ - "pick.wavePickTaskDetail" - ], - "notes": [ - "移除响应中的 waves 与 orders 子表,接口仅返回精简的 task、boxes、picking_details 与 picking_summary。", - "task 子字段裁剪为:task_id, task_no, status, pick_mode, start_at, finish_at, batch_no。", - "boxes 补充并明确返回:ref_label(箱参考标签)、required_qty(箱内需拣总数)、picked_qty(已拣数量)。", - "本次变更为文档层面的返回裁剪,前端应以新字段集合为准,旧字段可能不再返回。" - ], - "type": "updated" - }, - { - "version": "2026.05.10-system-01", - "date": "2026-05-10", - "summary": "order.wave.waveStrategyList 新增 strategy_type 最小过滤(散单/团购)", - "methods": [ - "order.wave.waveStrategyList" - ], - "notes": [ - "新增 strategy_type 过滤,仅 1/2", - "支持顶层 strategy_type 和 where.strategy_type,顶层优先", - "当前不引入其他 where 字段" - ], - "type": "updated" - }, - { - "version": "2026.05.09-system-02", - "date": "2026-05-09", - "summary": "新增 pick.wavePickTaskDetail:按任务ID解析拣货任务详情", - "methods": [ - "pick.wavePickTaskDetail" - ], - "notes": [ - "新增 pick.wavePickTaskDetail:传入 task_id 获取拣货任务完整信息,包含主表字段(task/pick_mode/status/wave_count/order_count/box_count 等)及三张子表数据(waves/orders/boxes)。", - "安全限制:接口会校验当前登录用户(operator_id/employees_id)与任务的 pick_user_id 是否一致;不一致时直接返回 403,不返回任何拣货信息。", - "鉴权配置:noNeedRight=true,noNeedAuth=true,isNeedLogin=true。" - ], - "type": "added" - }, - { - "version": "2026.05.08-system-05", - "date": "2026-05-08", - "summary": "order.wave.batchList:新增 source 字段并支持 where.source 过滤,返回 list item 中新增 source 字段", - "methods": [ - "order.wave.batchList" - ], - "notes": [ - "新增 where.source(可选,number)用于按来源过滤:0=普通波次(正常后台操作),1=管理后台策略任务,2=PDA策略任务;不传则不过滤。", - "响应 list 每条记录新增字段 source(number),用于区分波次来源。", - "仅更新文档,业务代码不在此变更范围。" - ], - "type": "updated" - }, - { - "version": "2026.05.08-system-04", - "date": "2026-05-08", - "summary": "完善 order.wave.wavePickTaskList 文档:补充入参、分页与返回字段兼容说明", - "methods": [ - "order.wave.wavePickTaskList", - "order.wave.wavePickTaskCancel" - ], - "notes": [ - "入参补充:warehouse_id(必填)、status(支持单值或数组,建议传数组)、source、keyword、page_no、page_size;保留 pagination 对象以兼容旧客户端。", - "兼容说明:接口同时支持历史 where 结构与顶层参数;当存在同名顶层参数时以顶层参数优先;pagination 支持 page/current 与 pageSize/size 别名。", - "返回格式:响应包含 total 与 list;list 每项包含字段:task_id、task_no、status、source、pick_mode、wave_count、order_count、box_count、operator_id、operator_name、start_at、finish_at、created_at。为兼容旧客户端,响应同时保留旧字段:pick_user_id、pick_user_name、start_time、finish_time、create_time。", - "入参 strategy_id 当前主表未存,接口会忽略该过滤,不建议使用。", - "默认排序:create_time desc.", - "文档变更:移除 order.wave.wavePickTaskCancel 的入参 operator_id 与 warehouse_id;入参改为仅支持 task_ids(数组,必填),不再兼容单个 task_id;操作人与仓库由请求上下文(例如当前登录用户上下文)自动获取;若上下文缺失接口将返回错误。响应补充批量结果字段:cancelled_count、task_ids、task_nos(若后端返回)。仅更新文档,未修改业务实现。" - ], - "type": "updated" - }, - { - "version": "2026.05.08-system-03", - "date": "2026-05-08", - "summary": "升级按策略抓取接口为创建任务主流程:order.wave.waveStrategyFetchPda / order.wave.waveStrategyFetchAdmin", - "methods": [ - "order.wave.waveStrategyFetchPda", - "order.wave.waveStrategyFetchAdmin" - ], - "notes": [ - "将 PDA/Admin 场景的按策略抓取接口由受理壳方法升级为 '创建任务主流程':接口会执行参数校验并在同步响应中创建任务记录(state=created),返回 task_id、task_no、plan 与 plan_summary 供前端展示与后续查询。", - "入参新增/扩展与创建流程相关字段:至少包含 cart_id(关联拣货车/作业车ID)、source(操作来源语义)并保留并透传 strategy_id 与 strategy_params(策略参数),以支持在创建阶段对策略进行局部覆盖或透传。", - "成功返回示例字段:state=created、task_id、task_no、plan(对象)和 plan_summary(字符串);失败场景会返回 validation_errors(数组,每项含 field/message)或 message 描述创建失败原因。", - "边界说明:当前为最小主流程(创建与计划预览),后续扫描/任务执行阶段(如实际抓取订单、写入 wave 等)将在后续版本中追加与完善。" - ], - "type": "updated" - }, - { - "version": "2026.05.08-system-02", - "date": "2026-05-08", - "summary": "调整按策略抓取壳方法:order.wave.waveStrategyFetch 更名为 order.wave.waveStrategyFetchPda,并新增 order.wave.waveStrategyFetchAdmin", - "methods": [ - "order.wave.waveStrategyFetch", - "order.wave.waveStrategyFetchPda", - "order.wave.waveStrategyFetchAdmin" - ], - "notes": [ - "waveStrategyFetchPda 仅用于 PDA 场景", - "waveStrategyFetchAdmin 仅用于后台管理场景", - "两者当前均为壳子受理方法,不执行真实抓取" - ], - "type": "updated" - }, - { - "version": "2026.05.08-system-01", - "date": "2026-05-08", - "summary": "新增 order.wave.waveStrategyFetch:按策略提交抓取任务(壳子方法)", - "methods": [ - "order.wave.waveStrategyFetch" - ], - "notes": [ - "当前方法为壳子方法:仅受理并返回任务受理信息,不执行真实抓取逻辑,后续补齐执行链路。" - ], - "type": "added" - }, - { - "version": "2026.05.07-system-05", - "date": "2026-05-07", - "summary": "新增 order.wave.waveStrategyCreate 与 order.wave.waveStrategyUpdate:波次策略创建与更新接口(含参数校验与版本推进)", - "methods": [ - "order.wave.waveStrategyCreate", - "order.wave.waveStrategyUpdate" - ], - "notes": [ - "仓库 ID 与创建人(creator_name)由当前登录仓库/操作者上下文获取,接口不接受外部覆盖。", - "入参 allowed_owners 与 allowed_expresses 会校验是否在系统可用范围内(基于仓库签约货主或系统快递列表),若存在非法值接口会直接报错(400)。", - "max_same_structure 受仓库配置 min_group_order_fetch_quantity 限制:若传入值 >= min_group_order_fetch_quantity,则自动下调为 min_group_order_fetch_quantity - 1(最小值为 1)。", - "新建/更新成功后会触发仓库的 wave_strategy_version 自增(+1)并失效相关仓库配置缓存,调用方可通过策略版本推进或缓存变化感知策略已生效。" - ], - "type": "added" - }, - { - "version": "2026.05.07-system-06", - "date": "2026-05-07", - "summary": "收敛 order.wave.waveStrategyFallbackOrderList 返回字段,限定 where 白名单,补充 order.wave.singleFetchByIds 别名与返回语义", - "methods": [ - "order.wave.waveStrategyFallbackOrderList", - "order.wave.singleFetchByIds" - ], - "notes": [ - "收敛 order.wave.waveStrategyFallbackOrderList response.list 字段为 id, delivery_no, tracking_no, items_count, items_total, sys_logistics_name, store_name, province, sys_platform_name, item_snapshot;item_snapshot 格式示例:商品名称*数量|...。", - "限制 order.wave.waveStrategyFallbackOrderList.where 白名单,禁止传入 warehouse_id / warehouseId;传入未列出字段或别名冲突将返回 400。", - "补充 order.wave.singleFetchByIds:明确支持 ids / order_ids / orderIds 三个别名(优先顺序 ids -> order_ids -> orderIds)并说明返回字段 fetched_order_ids、excluded_existing_wave_order_ids、skipped_order_ids、not_found_order_ids 的语义与兼容性。" - ], - "type": "updated" - }, - { - "version": "2026.05.07-system-04", - "date": "2026-05-07", - "summary": "更新 order.wave.waveStrategyFallbackOrderList,新增商品快照字段 item_snapshot", - "methods": [ - "order.wave.waveStrategyFallbackOrderList" - ], - "notes": [ - "item_snapshot 返回格式为 商品名称1*数量|商品名称2*数量" - ], - "type": "updated" - }, - { - "version": "2026.05.07-system-03", - "date": "2026-05-07", - "summary": "新增 order.wave.waveStrategyQuickScan 与进度查询接口", - "methods": [ - "order.wave.waveStrategyQuickScan", - "order.wave.waveStrategyQuickScanTaskProgress" - ], - "notes": [ - "同仓只允许一个扫描任务并使用缓存锁;扫描范围为当前表非待审核、未分配波次且订单策略版本与仓库当前版本不一致的订单;命中策略标记 wave_scan_result=1,否则=2" - ], - "type": "added" - }, - { - "version": "2026.05.07-system-02", - "date": "2026-05-07", - "summary": "新增 order.wave.waveStrategyList:查询当前仓库波次策略列表", - "methods": [ - "order.wave.waveStrategyList" - ], - "notes": [ - "从 wms_wave_strategy 拉取当前仓库的波次策略列表,分页返回" - ], - "type": "added" - }, - { - "version": "2026.05.07-system-01", - "date": "2026-05-07", - "summary": "移除 order.wave.singleOrderFetchDetailList,新增 order.wave.waveStrategyFallbackOrderList(内置固定筛选条件)", - "methods": [ - "order.wave.singleOrderFetchDetailList", - "order.wave.waveStrategyFallbackOrderList" - ], - "notes": [ - "移除 order.wave.singleOrderFetchDetailList。", - "新增 order.wave.waveStrategyFallbackOrderList。", - "新接口基于订单通用查询口径,固定内置筛选条件:step != 0、wave_id = 0、wave_scan_result = 2。" - ], - "type": "updated" - }, - { - "version": "2026.05.06-system-06", - "date": "2026-05-06", - "summary": "新增 order.wave.singleOrderFetchDetailList:订单级散单候选明细视图", - "methods": [ - "order.wave.singleOrderFetchDetailList" - ], - "notes": [ - "新增 order.wave.singleOrderFetchDetailList:提供订单级的散单候选明细列表,返回按订单聚合的明细(非分组级)。", - "返回订单级而非分组级;响应每项包含订单 id、group_count、item_detail_machine、item_detail_machine_snapshot、item_detail、item_snapshot、logistics_name、store_id、distinguish_express、create_at 与 status_summary 等关键字段。", - "仍沿用 same_order_quantity 阈值来排除团购命中分组(仅保留 group_count < same_order_quantity 的候选项)。", - "singleOrderFetchList 暂保留以兼容现有前端,前端可在切换到订单级视图后迁移到本接口。" - ], - "type": "added" - }, - { - "version": "2026.05.06-system-05", - "date": "2026-05-06", - "summary": "storage.receiving.get 返回扩展:data.details[*] 新增 box_remainder、box_weight", - "methods": [ - "storage.receiving.get" - ], - "notes": [ - "storage.receiving.get 的响应在 data.details[*] 中新增可选字段:box_remainder(箱内剩余数量/零散数量,number,默认 0)与 box_weight(实测箱重,number,默认 0)。", - "兼容性:新增字段为可选,旧客户端无需修改;建议前端在需要展示箱内余量/箱重时使用这些字段。" - ], - "type": "updated" - }, - { - "version": "2026.05.06-system-04", - "date": "2026-05-06", - "summary": "storage.receiving.getReceivingDetail 返回扩展:明细增加 box_remainder、box_weight;storage.receiving.completeReceiving 通知包含这两个字段", - "methods": [ - "storage.receiving.getReceivingDetail", - "storage.receiving.completeReceiving" - ], - "notes": [ - "为支持箱规统计与通知回传,getReceivingDetail 的明细项(receiving.details 或 data.details)在响应中新增可选字段:box_remainder(箱内剩余数量/零散数量,number)与 box_weight(实测箱重,number,单位同系统重量)。", - "completeReceiving 在完成收货后会发送通知(或回调),通知 payload/metadata 中将包含每条明细的 box_remainder 与 box_weight 字段,供下游系统/前端展示或审计使用。", - "兼容性:新增字段为可选,旧客户端在未使用这些字段时无需变更。" - ], - "type": "updated" - }, - { - "version": "2026.05.06-system-03", - "date": "2026-05-06", - "summary": "storage.receiving.detailChange:新增入参/出参字段 box_remainder、box_weight", - "methods": [ - "storage.receiving.detailChange" - ], - "notes": [ - "为支持箱规细化与回写,detailChange 新增可选入参 box_remainder(箱内余量/零散数量)和 box_weight(实测箱重,单位同系统重量),写入后会回写至明细并在响应 data 中返回对应字段。", - "兼容性:新增字段为可选,不传入则不影响现有调用;建议前端在需要回写箱余与箱重时一并传入。" - ], - "type": "updated" - }, - { - "version": "2026.05.06-system-02", - "date": "2026-05-06", - "summary": "新增 order.wave.singleFetchByIds:按订单ID抓取到一个散单波次", - "methods": [ - "order.wave.singleFetchByIds" - ], - "notes": [ - "新增 order.wave.singleFetchByIds:按入参 ids(兼容 order_ids/orderIds)去重后筛选当前仓库内待处理且不在波次中的订单,若存在可抓取订单则创建单个散单波次并把这些订单写入该波次(不区分快递);成功后批量写入订单操作日志;若无可抓取订单返回 wave_id=0。", - "接口行为严格对齐实现:过滤条件包含 step in [1,2,3]、status != 'cancel'、outbound_status != 'padding';已在波次的订单会被排除并返回 excluded_existing_wave_order_ids;响应包含 ids、wave_id、wave_no、fetched_order_ids、fetched_order_count、excluded_existing_wave_order_ids、skipped_order_ids、not_found_order_ids。" - ], - "type": "added" - }, - { - "version": "2026.05.06-system-01", - "date": "2026-05-06", - "summary": "新增 order.wave.groupFetch 与 order.wave.singleFetch;order.wave.fetch 保留兼容别名;抓取进度补充上限字段", - "methods": [ - "order.wave.groupFetch", - "order.wave.singleFetch", - "order.wave.fetch", - "order.wave.fetchTaskProgress" - ], - "notes": [ - "新增 order.wave.groupFetch:抓取团购接口(异步任务提交),参数 structure_list 与原 fetch 一致。", - "新增 order.wave.singleFetch:抓取散单接口(异步任务提交),在 structure_list 每项新增必填字段 max_fetch_quantity(最大抓取上限,订单数,正整数)。", - "order.wave.fetch 保留为兼容别名(等同 groupFetch),避免误导客户端。", - "groupFetch/singleFetch/fetch 的响应新增可选字段 fetch_mode;singleFetch 响应额外返回 max_fetch_quantity。", - "order.wave.fetchTaskProgress 的响应增加单模式相关字段:fetch_mode、max_fetch_quantity、limit_reached、stop_reason,用于描述散单抓取的上限与停止原因。" - ], - "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-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": "updated" - }, - { - "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 查询全字段列表并支持缓存", - "methods": [ - "setting.expressInterface.listByWarehousePlatformCode" - ], - "notes": [ - "新增 setting.expressInterface.listByWarehousePlatformCode:按 warehouse_id + platform_code 返回快递接口的全字段数组(不分页),每条记录包含 express 关联对象(id/code/name/platform 等)。", - "支持缓存,缓存键由 warehouse_id + platform_code 组成;缓存命中将直接返回缓存结果以提升查询性能。", - "在创建/更新/删除操作(setting.expressInterface.create/update/delete)后,会主动清理对应 warehouse_id + platform_code 的缓存以确保数据一致性。" - ], - "type": "added" - }, - { - "version": "2026.04.17-system-08", - "date": "2026-04-17", - "summary": "新增快递编码管理模块批量软删除接口 setting.express.delete", - "methods": [ - "setting.express.delete" - ], - "notes": [ - "新增批量软删除接口 setting.express.delete:接受 ids(数组、逗号字符串或单值),对属于当前仓库且未被删除的记录执行软删除(设置 deleted_at),并清理 express 列表缓存。", - "当任一目标记录的 code 被 wms_express_interface.express_code 引用时,接口会拒绝删除并返回 409,错误信息中包含被引用的编码列表。", - "响应包含 ids、deleted_ids、already_deleted_ids 与 status,已删除与未删除的 id 会明确分类。仅记录已实现行为。" - ], - "type": "added" - }, - { - "version": "2026.04.17-system-05", - "date": "2026-04-17", - "summary": "新增文档分组:平台编码管理模块(收口 index.getPlatformList 与 setting.platform.*)", - "methods": [ - "index.getPlatformList", - "setting.platform.list", - "setting.platform.create", - "setting.platform.update", - "setting.platform.delete" - ], - "notes": [ - "新增独立文档分组 '平台编码管理模块',将平台基础列表(index.getPlatformList)与平台设置管理接口(setting.platform.*)归并为单一分组以便维护;仅文档变更,不修改实现。", - "文档中仅包含已实现的方法与字段,未新增或推断不存在的参数/返回字段。" - ], - "type": "added" - }, - { - "version": "2026.04.17-system-04", - "date": "2026-04-17", - "summary": "新增独立平台设置模块 setting.platform(wms_platfrom_setting)及其 CRUD 接口:list/create/update/delete。", - "methods": [ - "setting.platform.list", - "setting.platform.create", - "setting.platform.update", - "setting.platform.delete" - ], - "notes": [ - "新增独立模块 setting.platform,映射数据表 wms_platfrom_setting;list 支持 where(id/code/name/platform_code/quickWhere)与 pagination(兼容 page/pageSize/page_size);create/update 要求 platform_code 必须存在于系统平台表(wms_platform),且禁止越权写入 warehouse_id;delete 需传入 id 并校验当前仓库范围。" - ], - "type": "added" - }, - { - "version": "2026.04.15-system-07", - "date": "2026-04-15", - "summary": "将 docs/order-workbench-list-api.md 引用统一为 window 链接格式", - "methods": [ - "order.list", - "order.reviewOrder.list", - "order.pendingOrder.list", - "order.outboundOrder.list", - "order.expectionOrder.list", - "order.entrustOrder.list", - "order.deliveryOrder.list", - "order.deliveryExpectionOrder.list" - ], - "notes": [ - "将所有 methods/system.json 中指向 docs/order-workbench-list-api.md 的说明统一替换为 docs/order-workbench-list-api.md 格式,以便 HTML 渲染识别为 window 链接。", - "仅修改 methods/system.json 的文档字段,不涉及任何业务代码或接口契约变化。" - ], - "type": "updated" - }, - { - "version": "2026.04.15-system-06", - "date": "2026-04-15", - "summary": "订单工作台列表文档补全 raw 字段字典与中文语义说明", - "methods": [ - "order.list", - "order.reviewOrder.list", - "order.pendingOrder.list", - "order.outboundOrder.list", - "order.expectionOrder.list", - "order.entrustOrder.list", - "order.deliveryOrder.list", - "order.deliveryExpectionOrder.list", - "order.archiveOrder.list" - ], - "notes": [ - "在 docs/order-workbench-list-api.md 中补充所有订单列表通用 raw 字段字典,明确每个字段的中文语义与 enum 取值。", - "补充 express_numbers / waybill_codes 两个服务层派生字段说明,便于前端直接渲染多个快递号。", - "methods/system.json 中所有订单 list 的 response.list 描述已指向该字段字典章节。" - ], - "type": "updated" - }, - { - "version": "2026.04.15-system-05", - "date": "2026-04-15", - "summary": "基础模块新增快递/平台列表查询接口并设置为不鉴权,复用缓存 service", - "methods": [ - "index.getExpressList", - "index.getPlatformList" - ], - "notes": [ - "新增 index.getExpressList,归属基础模块(module=index),对应 app/service/systems/express.js 中的 getExpressList。", - "index.getExpressList 设置为不鉴权,不需要 Authorization 头。", - "新增 index.getPlatformList,归属基础模块(module=index),对应 app/service/systems/platform.js 中的 getPlatformList。", - "index.getPlatformList 设置为不鉴权,不需要 Authorization 头。", - "快递列表与平台列表都支持缓存优先,缓存未命中时回源数据库并写入缓存。", - "平台列表支持缓存优先,缓存未命中时回源 wms_platform 并写入缓存。" - ], - "type": "added" - }, - { - "version": "2026.04.15-system-02", - "date": "2026-04-15", - "summary": "签约策略字段元信息新增 default_express_code / default_platform_code list 选项", - "methods": [ - "storeWarehouse.store.getPolicyConfigFields" - ], - "notes": [ - "getPolicyConfigFields 现在返回 default_express_code 与 default_platform_code 两个 list 字段,并从 wms_express / wms_platform 读取选项列表。", - "默认值仍保留为 default_express_code=STO、default_platform_code=TB。" - ], - "type": "updated" - }, - { - "version": "2026.04.15-system-03", - "date": "2026-04-15", - "summary": "签约策略字段移除 sku_visibility,receive_mode options 改为 value/label 结构", - "methods": [ - "storeWarehouse.store.savePolicyConfig", - "storeWarehouse.store.getPolicyConfigFields" - ], - "notes": [ - "策略字段定义不再包含 sku_visibility,历史值读取时仍会被归一化忽略。", - "receive_mode 的 options 改为 [{ value, label }] 格式,便于前端直接渲染。" - ], - "type": "updated" - }, - { - "version": "2026.04.15-system-04", - "date": "2026-04-15", - "summary": "按文件模块拆分 order 目录系统文档分组,覆盖订单工作台入口及各子模块方法", - "methods": [ - "order.list", - "order.manualOutboundOrder", - "order.badgeCount", - "order.outboundOrder.manualOutboundOrder", - "order.reviewOrder.list", - "order.reviewOrder.reviewOrder", - "order.pendingOrder.list", - "order.pendingOrder.reverseReviewOrder", - "order.pendingOrder.markPendingOutboundOrder", - "order.pendingOrder.cancelOrder", - "order.outboundOrder.list", - "order.expectionOrder.list", - "order.entrustOrder.list", - "order.deliveryOrder.list", - "order.deliveryExpectionOrder.list", - "order.archiveOrder.list" - ], - "notes": [ - "按 app/service/systemMethods/order 下的实际对外方法补全 methods/system.json 文档,只覆盖 system,不处理 qimen。", - "order 文档已按 index / reviewOrder / pendingOrder / outboundOrder / expectionOrder / entrustOrder / deliveryOrder / deliveryExpectionOrder / archiveOrder 拆成多个模块分组。", - "同步根据当前代码意图补充 params / response / errors,且不再把 index.js 已移除的兼容接口写回文档。" - ], - "type": "updated" - }, - { - "version": "2026.04.15-system-01", - "date": "2026-04-15", - "summary": "货主主体配置默认补齐 default_express_code / default_platform_code", - "methods": [ - "store.createStore", - "store.createWarehouse" - ], - "notes": [ - "当 subject_config 未传或缺少字段时,自动补齐 default_express_code=STO、default_platform_code=TB,并保留现有的 max_notice_webhook_count 默认值。", - "同步更新 methods/system.json 中 store.createStore 与 store.createWarehouse 的参数说明。" - ], - "type": "updated" - }, - { - "version": "2026.04.14-system-01", - "date": "2026-04-14", - "summary": "库存列表新增货主名称字段 stock.store_name", - "methods": [ - "storage.inventory.list" - ], - "notes": [ - "在 methods/system.json 的 storage.inventory.list response 中补充 stock.store_name:来源于签约表 store_remask,若无签约关系则为 null。", - "只同步文档,不修改业务代码。" - ], - "type": "updated" - }, - { - "version": "2026.04.13-system-01", - "date": "2026-04-13", - "summary": "补全 storage.receiving.detailChange 的入参/出参契约与错误码说明", - "methods": [ - "storage.receiving.detailChange" - ], - "notes": [ - "在 methods/system.json 中补充 storage.receiving.detailChange 的 params/response/errors,明确 id 与 receiving_id 必填。", - "说明 expiry_date 小于当前日期时返回 400 且 message 为 \"到期日期已过期,不能录入收货\"。", - "说明当传入 system_product_id 时会回填条码、重量、箱规、商品名称与 product_snapshot;未传时 barcode/product_name 也可单独更新。", - "同步补充文档:docs/storage-receiving-api.md 中新增 detailChange 段落。" - ], - "type": "updated" - }, - { - "version": "2026.04.07-system-01", - "date": "2026-04-07", - "summary": "修正 warehouse.getAreaRacks 的鉴权/权限链路文档,明确该接口需要 登录并走权限校验。", - "methods": [ - "warehouse.getAreaRacks" - ], - "notes": [ - "对齐当前 system 文档中的 isNeedAuth=true、isNeedLogin=true。", - "用于补充该接口权限链路修正文档的历史上下文,不改变 methods/system.json 的 SSOT 角色。" - ] - }, - { - "version": "2026.04.07-system-02", - "date": "2026-04-07", - "summary": "补充签约配置相关接口文档,覆盖策略字段元信息查询与面单数量人工调整。", - "methods": [ - "storeWarehouse.store.getPolicyConfigFields", - "storeWarehouse.store.adjustPrintQuantity" - ], - "notes": [ - "getPolicyConfigFields 说明为获取签约策略可配置字段元信息列表。", - "adjustPrintQuantity 说明为人工调整签约关系下的面单余额并记录变更日志,并 明确 id、change_quantity、reason 等关键入参。" - ] - }, - { - "version": "2026.04.07-system-03", - "date": "2026-04-07", - "summary": "对外命名从 qimenConfig 收口为 apiConfig,并在接口配置文档中强调 interface_type_id 校验。", - "methods": [ - "storeWarehouse.store.listApiConfig", - "storeWarehouse.store.saveApiConfig", - "storeWarehouse.store.deleteQimenConfig" - ], - "notes": [ - "文档对外统一使用 apiConfig / api_config 命名,减少 qimenConfig 历史别名歧义。", - "saveApiConfig 要求 interface_type_id 为必填且必须指向已存在的 wms_interface_type 记录。", - "listApiConfig / deleteQimenConfig 同步补充 interface_type_id 字段说明。" - ] - }, - { - "version": "2026.04.07-system-04", - "date": "2026-04-07", - "summary": "补充 /api/docs 文档体验增强说明,新增查看变更记录与查看原文 JSON 的入口说明。", - "methods": [ - "/api/docs", - "/api/docs/:docName", - "/api/docs/:docName/raw", - "/api/docs/:docName/changes" - ], - "notes": [ - "sidecar 变更数组用于承载文档历史说明,不替代 methods/system.json 作为 SSOT。", - "原文 JSON 入口继续用于直接查看当前生效文档。" - ] - }, - { - "version": "2026.04.07-system-05", - "date": "2026-04-07", - "summary": "修正 storeWarehouse.store.adjustPrintQuantity 的面单余额调整语义:由增减/累加改为覆盖设置目标余额。", - "methods": [ - "storeWarehouse.store.adjustPrintQuantity" - ], - "notes": [ - "adjustPrintQuantity 当前兼容 print_quantity、target_quantity、change_quantity、adjust_quantity 作为目标面单余额输入,不再按增减量解释。", - "变更日志中的 change_quantity 由 before/after 自动计算差值,以兼容历史审计与展示。" - ] - }, - { - "version": "2026.04.07-system-06", - "date": "2026-04-07", - "summary": "按接口类型分类限制必填字段,OPEN_API 创建时自动生成 self_app_key/self_app_secret", - "methods": [ - "storeWarehouse.store.saveApiConfig" - ], - "notes": [ - "QM_WMS 类型须填写 qimen_app_key/qimen_customer_id/qimen_warehouse_code;OPEN_API 类型三个奇门字段非必填,创建时自动生成 self_app_key(WMS+32位HEX)和 self_app_secret(64位HEX),更新时保留已有密钥。" - ], - "type": "changed" - }, - { - "version": "2026.04.07-system-07", - "date": "2026-04-07", - "summary": "新增接口类型列表查询接口,归属基础模块,无需权限", - "methods": [ - "index.listInterfaceTypes" - ], - "notes": [ - "返回所有已启用的接口类型(wms_interface_type),包含 id、interface_code、interface_name、interface_category、description 字段。设置 isNeedAuth: false, isNeedLogin: true。" - ], - "type": "added" - }, - { - "version": "2026.04.07-system-08", - "date": "2026-04-07", - "summary": "app_name 改为必传参数", - "methods": [ - "storeWarehouse.store.saveApiConfig" - ], - "notes": [ - "app_name 不再有默认值自动生成逻辑,调用方必须传入非空的 app_name,否则返 回 400 错误。" - ], - "type": "changed" - }, - { - "version": "2026.04.07-system-09", - "date": "2026-04-07", - "summary": "新增收货单快捷入库上架接口", - "methods": [ - "storage.inventory.quickPutaway" - ], - "notes": [ - "新建 storage.inventory 库存操作模块。quickPutaway 从收货单直接生成入库单 (SCRK)并写入 wms_storage 库存表,同时更新 wms_stock_warehouse 库存数量(悲观行锁),回填收货明细入库状态。要求收货单已完成且所有明细已匹配系统商品。" - ], - "type": "added" - }, - { - "version": "2026.04.08-system-01", - "date": "2026-04-08", - "summary": "新增收货单与入库单匹配入库接口", - "methods": [ - "storage.inventory.matchPutaway" - ], - "notes": [ - "接收多个收货单和入库单,按商品(stock_warehouse_id)进行数量匹配入库,完 成后根据入库单来源(QM/API)自动触发回传。入参为 receiving_ids(数组)和 entry_order_ids(数组),返回匹配汇总、各收货单入库状态、各入库单状态及回传结果。isNeedAuth=true, isNeedLogin=true, isNeedRight=false。" - ], - "type": "added" - }, - { - "version": "2026.04.08-system-02", - "date": "2026-04-08", - "summary": "saveApiConfig 新增 callback_url 可选参数", - "methods": [ - "storeWarehouse.store.saveApiConfig" - ], - "notes": [ - "新增 callback_url 参数(VARCHAR(500),可选),用于 OPEN_API 类型入库单的 回调地址配置。" - ], - "type": "changed" - }, - { - "version": "2026.04.08-system-03", - "date": "2026-04-08", - "summary": "serializeQimenConfig 新增返回 callback_url 字段,影响 list 和 listApiConfig 两个接口", - "methods": [ - "storeWarehouse.store.list", - "storeWarehouse.store.listApiConfig" - ], - "notes": [ - "serializeQimenConfig() 序列化方法新增 callback_url(string)字段。storeWarehouse.store.list 返回的每条记录 api_config 对象中包含 callback_url;storeWarehouse.store.listApiConfig 返回的 list 数组中每条配置包含 callback_url。" - ], - "type": "changed" - }, - { - "version": "2026.04.08-system-04", - "date": "2026-04-08", - "summary": "新增库存移库(库位转移)接口", - "methods": [ - "storage.inventory.transferLocation" - ], - "notes": [ - "新增 storage.inventory.transferLocation 接口,支持批量多商品多库位移库, 包含部分数量移库与全量移库。入参为 warehouse_id(仓库ID)和 transfers 数组(storage_id、target_space_id、quantity),触发 storage_transfer_completed 通知事件, 每条移库记录独立操作日志。isNeedAuth=true, isNeedLogin=true。" - ], - "type": "added" - }, - { - "version": "2026.04.08-system-05", - "date": "2026-04-08", - "summary": "简化移库接口入参,从批量 transfers 数组改为单条移库", - "methods": [ - "storage.inventory.transferLocation" - ], - "notes": [ - "移除 warehouse_id 和 transfers 数组入参,改为扁平的 storage_id + target_space_id + quantity 三个顶层参数。warehouse_id 从库存记录自动获取,接口从批量移库简化为单商品单库位移库。响应结构同步简化为单条结果对象。" - ], - "type": "modified" - }, - { - "version": "2026.04.08-system-06", - "date": "2026-04-08", - "summary": "新增商品库存明细查询接口", - "methods": [ - "stock.warehouse.getStockDetail" - ], - "notes": [ - "新增 stock.warehouse.getStockDetail 接口,按库位/批次维度查询商品库存分布。入参为 stock_id(必填,商品库存ID)和 pagination(可选,含 page/pageSize)。返回 stockItem(商品概要)、storageList(wms_storage 明细数组,含批次号、库位、数 量、锁定数量、生产日期、过期日期等,关联 location_space 库位信息)、pagination 分页信息。isNeedAuth=false, isNeedLogin=true。底层调用 stockStore.getStockDetail,自动校验商品归属当前仓库。" - ], - "type": "added" - }, - { - "version": "2026.04.08-system-07", - "date": "2026-04-08", - "summary": "新增入参 group_by_batch,支持按批次维度切换库存明细聚合方式", - "methods": [ - "stock.warehouse.getStockDetail" - ], - "notes": [ - "新增可选布尔参数 group_by_batch(默认 false)。false 时按库位合并数量,批次相关字段(batch_no, production_date, expiry_date, inbound_time, inbound_order_no, supplier_batch_no)置 null;true 时保持原逻辑返回每条明细。出参结构不变,但 storageList 中批次字段在合并模式下为 null。" - ], - "type": "modified" - }, - { - "version": "2026.04.08-system-08", - "date": "2026-04-08", - "summary": "新增按商品维度移库接口", - "methods": [ - "storage.inventory.transferByProduct" - ], - "notes": [ - "新增 storage.inventory.transferByProduct 接口,按库位+商品查找所有库存记 录合并移动。入参为 space_id(原库位ID)、stock_id(商品SKU ID,即 wms_stock_warehouse.id)、target_space_id(目标库位ID)、quantity(移库数量)。开启批次管理(is_batch_mgmt=Y)的商品会被拒绝,需使用 transferLocation 按库存记录精确移库。复用 storage_transfer_completed 通知事件,操作日志编码 STORAGE_TRANSFER_BY_PRODUCT。isNeedAuth=true, isNeedLogin=true。" - ], - "type": "added" - }, - { - "version": "2026.04.08-system-09", - "date": "2026-04-08", - "summary": "补充 storeWarehouse.store.list 完整 response 输出字段说明,移除 api_config / apiConfig", - "methods": [ - "storeWarehouse.store.list" - ], - "notes": [ - "从返回结果中移除 api_config 和 apiConfig 字段(代码中 delete serialized.api_config / delete serialized.apiConfig),文档 response 补充完整输出字段列表:id, store_id, store_name, warehouse_id, warehouse_name, counterparty_id, counterparty_name, current_subject_role, auth_status, auth_status_label, apply_reason, review_comment, apply_time, review_time, auth_start, auth_end, actual_end, print_quantity, applied_by, reviewed_by, ended_by, remask, use_status, policy_config, is_auth_valid, remaining_days 以及分页和 current_subject 信息。" - ], - "type": "updated" - }, - { - "version": "2026.04.08-system-10", - "date": "2026-04-08", - "summary": "货主列表返回新增 has_qimen_config 布尔字段", - "methods": [ - "storeWarehouse.store.list" - ], - "notes": [ - "storeWarehouse.store.list 返回的 data.list[] 中新增 has_qimen_config(boolean),表示该货主是否已配置奇门。" - ], - "type": "changed" - }, - { - "version": "2026.04.08-system-11", - "date": "2026-04-08", - "summary": "补全 stock.warehouse.search 接口文档,新增 params / response / errors 完整说明", - "methods": [ - "stock.warehouse.search" - ], - "notes": [ - "入参补充 keyword(string,模糊匹配 item_code / item_name / goods_code / barcode)和 store_id(number,按货主筛选)。响应补充 data 数组各字段(id, item_code, goods_code, item_name, sku_property, stock_unit, quantity, locked_quantity, brand_name, item_type, barcodes, store_stock)以及 total。errors 补充 code=0 搜 索失败场景。" - ], - "type": "updated" - }, - { - "version": "2026.04.08-system-12", - "date": "2026-04-08", - "summary": "新增 with_stock / is_batch 参数,支持返回关联库存明细(按库位分 组或按批次逐条)", - "methods": [ - "stock.warehouse.search" - ], - "notes": [ - "入参新增 with_stock(boolean,默认 false,是否返回关联库存数据)和 is_batch(boolean,默认 false,仅 with_stock=true 时生效,按批次明细返回)。响应 data[] 新增 storage[] 字段:is_batch=false 时按库位分组汇总(含 space_id、space、inventory_type、quantity、locked_quantity、available_quantity);is_batch=true 时逐 条返回批次明细(含 id、stock_id、space_id、batch_no、inventory_type、quantity、locked_quantity、available_quantity、production_date、expiry_date、inbound_time、inbound_order_no、supplier_batch_no、created_at、space)。" - ], - "type": "updated" - }, - { - "version": "2026.04.08-system-13", - "date": "2026-04-08", - "summary": "新增 wms_stock_transaction 表和模型", - "methods": [ - "wms_stock_transaction" - ], - "notes": [ - "新增出入库流水记录表 wms_stock_transaction,含 transaction_type(INBOUND/OUTBOUND)、warehouse_id、store_id、stock_id、storage_id、space_id、quantity、batch_no、inventory_type、order_type、order_no、order_id、receiving_id、entry_order_id、operator_id、operator_name、remark 等字段,关联 StockWarehouse 和 Storage 模型。" - ], - "type": "added" - }, - { - "version": "2026.04.08-system-14", - "date": "2026-04-08", - "summary": "quickPutaway 和 matchPutaway 入库时自动写入出入库记录", - "methods": [ - "storage.inventory.quickPutaway", - "storage.inventory.matchPutaway" - ], - "notes": [ - "入库操作完成后自动写入 wms_stock_transaction 记录。quickPutaway 写入 order_type='SCRK'(收货入库),matchPutaway 写入 order_type='MATCH'(匹配入库),均 自动填充 warehouse_id、store_id、stock_id、storage_id、space_id、quantity、batch_no、inventory_type 等字段。" - ], - "type": "updated" - }, - { - "version": "2026.04.08-system-15", - "date": "2026-04-08", - "summary": "新增 storage.inventory.list 出入库记录列表查询接口", - "methods": [ - "storage.inventory.list" - ], - "notes": [ - "出入库记录列表查询,支持 where 条件(transaction_type、stock_id、space_id、store_id、order_type、order_no、inventory_type、operator_name、created_at)、 分页(pagination)、排序(sort)和 group_by_batch 参数。默认合并模式按库位+商品 聚合返回合计数量与记录条数,group_by_batch=true 时返回每条明细含 batch_no、order_no、operator_name 等完整信息。响应均关联 stockItem(item_code、item_name、sku_property、stock_unit)。" - ], - "type": "added" - }, - { - "version": "2026.04.08-system-16", - "date": "2026-04-08", - "summary": "出入库流水记录查询接口从 storage.inventory.list 改名为 storage.transaction.list", - "methods": [ - "storage.transaction.list" - ], - "notes": [ - "将出入库流水记录查询从 storage.inventory.list 迁移到 storage.transaction.list,避免与库存列表概念混淆。功能和参数不变。isNeedAuth=false, isNeedLogin=true, isNeedRight=false。" - ], - "type": "rename", - "module": "storage" - }, - { - "version": "2026.04.08-system-17", - "date": "2026-04-08", - "summary": "新增 storage.inventory.list 库存列表查询接口", - "methods": [ - "storage.inventory.list" - ], - "notes": [ - "新增库存列表查询接口,查询 wms_storage 表。支持 where 条件(stock_id/space_id/store_id/inventory_type/batch_no/inbound_order_no/available_quantity/inbound_time/created_at)、分页、排序。支持 group_by_batch 参数:默认 false 按库位+商 品合并(SUM quantity/locked_quantity/available_quantity),true 返回每条明细含 batch_no/production_date/expiry_date 等。关联 stockItem(商品信息)和 space(库位信息)。isNeedAuth=false, isNeedLogin=true, isNeedRight=false。" - ], - "type": "add", - "module": "storage" - }, - { - "version": "2026.04.08-system-18", - "date": "2026-04-08", - "summary": "移除 storage.entry.create 创建入库单接口", - "methods": [ - "storage.entry.create" - ], - "notes": [ - "不再允许通过 API 创建入库单。入库单仅由快捷入库(quickPutaway)和匹配入库(matchPutaway)等内部流程自动创建。底层 service 实现保留但不再通过 systemMethods 对外暴露。" - ], - "type": "remove", - "module": "storage" - }, - { - "version": "2026.04.08-system-19", - "date": "2026-04-08", - "summary": "移除 storage.entry.addDetail / deleteDetail / detailChange 对外 接口", - "methods": [ - "storage.entry.addDetail", - "storage.entry.deleteDetail", - "storage.entry.detailChange" - ], - "notes": [ - "入库单明细编辑能力不再通过 systemMethods 对外暴露,入库单模块仅保留 list/get/cancel/completeEntry。" - ], - "type": "remove", - "module": "storage" - }, - { - "version": "2026.04.08-system-20", - "date": "2026-04-08", - "summary": "新增 storage.stockout 出库单模块(非订单出库单能力)", - "methods": [ - "storage.stockout.list", - "storage.stockout.toOrder", - "storage.stockout.listItems" - ], - "notes": [ - "新增 storage.stockout.list / toOrder / listItems 接口,作为非订单出库单的主出口(对应奇门 stockout.create)。storage.delivery.* 仅作为兼容转发保留;底层 部分能力仍复用 order 模块。" - ], - "type": "add", - "module": "storage" - }, - { - "version": "2026.04.08-system-21", - "date": "2026-04-08", - "summary": "将 storage.stockout.toOrder 标记为占位接口", - "methods": [ - "storage.stockout.toOrder" - ], - "notes": [ - "storage.stockout.toOrder 当前仅保留方法名用于后续扩展,暂不开放实际逻辑。调用时返回 code=405、message=占位接口,暂未开放。" - ], - "type": "change" - }, - { - "version": "2026.04.09-system-01", - "date": "2026-04-09", - "summary": "storage.entry.cancel 支持批量作废,新增 ids 入参并兼容单条 id", - "methods": [ - "storage.entry.cancel" - ], - "notes": [ - "新增入参 `ids`(number[])以支持批量作废,兼容旧入参 `id`;当同时传入 `ids` 与 `id` 时以 `ids` 为准。", - "参数校验:`ids` 必须为非空数组;非法 ID 或空数组返回 400。", - "业务约束:已完成/已作废/处于不可作废状态的单据不允许作废;批量场景下任一 单据不存在或状态不允许时整体返回 404/400,未执行部分更新。", - "响应说明:单条作废返回字段 `id`(number);批量作废返回字段 `ids`(number[])。", - "已同步更新 methods/system.json(storage.entry.cancel)为 SSOT。" - ] - }, - { - "version": "2026.04.09-system-02", - "date": "2026-04-09", - "summary": "新增基础模块车牌识别接口 index.recognizeLicensePlate", - "methods": [ - "index.recognizeLicensePlate" - ], - "notes": [ - "入参:base64(string,必填)或 imageBase64/image_base64(兼容)", - "响应:返回归一化后的识别对象,包含 licensePlate、plateNumber、color、confidence、requestId、imageSize、rawData", - "错误:400(参数或图片格式/尺寸问题),500(第三方 OCR 调用失败或云密钥未 配置)", - "文档中不包含任何敏感配置;实际腾讯云密钥保留在配置文件中,勿在文档中暴露 。" - ], - "type": "added" - }, - { - "version": "2026.04.09-system-03", - "date": "2026-04-09", - "summary": "收紧基础模块车牌识别接口响应,仅返回 licensePlate 字段", - "methods": [ - "index.recognizeLicensePlate" - ], - "notes": [ - "出参由 {licensePlate, plateNumber, color, confidence, requestId, imageSize, rawData} 调整为 {licensePlate}", - "调用方请仅依赖 licensePlate 字段以适配新版本;历史字段已裁剪且不再保证存 在。", - "文档中未包含任何云密钥或敏感配置信息。" - ], - "type": "changed" - }, - { - "version": "2026.04.10-system-01", - "date": "2026-04-10", - "summary": "订单审核字段由 audit_status 替换为整数字段 step,并添加数据库迁移", - "methods": [ - "order.getreviewOrderlist", - "order.reviewOrder.getreviewOrderlist", - "order.reviewOrder.reviewOrder", - "order.deliveryOrder.getdeliveryOrderlist", - "order.list", - "order.stats" - ], - "notes": [ - "字段变更:order 相关审核字段从字符串/枚举 audit_status 替换为整数 step。", - "step 映射:0=未审核,1=已审核,2=处理中,3=驳回/异常,4=配送中,5=已完成,9=已关闭。", - "reviewOrder 接口在更新 inspection_status 的同时会写入 step 字段。", - "必须执行迁移脚本:20260410150000-replace-audit-status-with-step-on-order-delivery-tables.js" - ], - "type": "changed" - }, - { - "version": "2026.04.13-system-02", - "date": "2026-04-13", - "summary": "stock.warehouse.search 返回新增效期管理字段并保留 is_shelf_life_mgmt", - "methods": [ - "stock.warehouse.search" - ], - "notes": [ - "响应 data[] 中新增字段:inbound_min_days、outbound_min_days、shelf_life_days、remaining_threshold_days(均为 number,单位:天)。", - "保留并说明 is_shelf_life_mgmt 布尔字段(boolean),表示是否启用效期管理(true=启用)。", - "仅更新文档(methods/system.json 与变更记录),代码行为不变。" - ], - "type": "updated" - }, - { - "version": "2026.04.13-system-02", - "date": "2026-04-13", - "summary": "新增 storage.expiry.list 库存有效期列表查询接口", - "methods": [ - "storage.expiry.list" - ], - "notes": [ - "该接口查询 wms_storage,关联 stockWarehouse 和 locationSpace,并按当前仓库与 remaining_threshold_days / expiry_date 过滤。" - ], - "type": "added" - }, - { - "version": "2026.04.13-system-03", - "date": "2026-04-13", - "summary": "新增 storage.inventory.list 库存列表返回效期字段与预警标记", - "methods": [ - "storage.inventory.list" - ], - "notes": [ - "库存列表响应增加生产日期、过期日期、效期预警是否触发字段", - "预警标记仅在商品启用保质期管理且到期日满足阈值条件时为 true" - ], - "type": "updated" - }, - { - "version": "2026.04.14-system-01", - "date": "2026-04-14", - "summary": "更新 index.searchSpace 文档", - "methods": [ - "index.searchSpace" - ], - "notes": [ - "补充 index.searchSpace 的 params/response,按 ctx.user.store_id 作为仓库上下文;keyword 为可选字符串,对 space_code 与 custom_barcode 做 %keyword% 模糊匹配;返回字段 id、space_code、custom_barcode、custom_name,最多 50 条;仅文档同步,无代码变更。" - ], - "type": "updated" - }, - { - "version": "2026.04.16-system-01", - "date": "2026-04-16", - "summary": "基础模块新增快递产品类型查询接口", - "methods": [ - "index.getExpressProductTypeList" - ], - "notes": [ - "新增 index.getExpressProductTypeList,归属基础模块(module=index),用于查询指定快递公司的产品类型列表。", - "对应服务实现:app/service/systems/express.js 中的 getExpressProductTypeList,支持传入 express_code 作为可选筛选参数(source=body)。", - "接口设置为免鉴权(isNeedAuth=false)但需登录(isNeedLogin=true),与 index.getExpressList / index.getPlatformList 一致,优先从缓存读取。" - ], - "type": "added" - }, - { - "version": "2026.04.17-system-01", - "date": "2026-04-17", - "summary": "新增快递管理模块(setting.express)及 5 个接口文档", - "methods": [ - "setting.express.list", - "setting.express.listBase", - "setting.express.create", - "setting.express.checkCodeUnique", - "setting.express.update" - ], - "notes": [ - "新增独立模块组:快递管理模块(module=setting.express),将快递映射管理相关接口独立为一组以便维护。", - "接口实现参考:app/service/systems/setting/express.js(返回结构)与 app/service/systemMethods/setting/express.js(对外方法包装)。", - "接口鉴权与上下文:isNeedAuth=false, isNeedLogin=true;需在请求中传入 Authorization 以携带登录上下文(用于获取当前仓库/货主上下文)。", - "已同步更新 methods/system.json,补充 params/response/errors,保持文档与实现一致。" - ], - "type": "added" - }, - { - "version": "2026.04.17-system-02", - "date": "2026-04-17", - "summary": "setting.express.list 分页入参统一为 pagination", - "methods": [ - "setting.express.list" - ], - "notes": [ - "将 setting.express.list 的分页入参文档从顶层 page/page_size/pageSize 迁移为 pagination 对象,主形态为 pagination;兼容 snake_case 的 page_size 与 camelCase 的 pageSize。", - "文档与当前实现一致:顶层 page/page_size/pageSize 会被归一化到 data.pagination 并转发到系统服务。" - ], - "type": "updated" - }, - { - "version": "2026.04.17-system-03", - "date": "2026-04-17", - "summary": "新增快递接口管理模块(setting.expressInterface)及 4 个接口文档", - "methods": [ - "setting.expressInterface.list", - "setting.expressInterface.create", - "setting.expressInterface.update", - "setting.expressInterface.delete" - ], - "notes": [ - "新增独立模块组:快递接口管理模块(module=setting.expressInterface),对应实现:app/service/systems/setting/expressInterface.js 与对外包装 app/service/systemMethods/setting/expressInterface.js。", - "接口为当前仓库范围(基于 ctx.user.store_id),仓库边界由系统服务强制校验;禁止通过接口指定 warehouse_id/warehouseId。操作需登录(isNeedLogin=true),无需额外鉴权(isNeedAuth=false)。", - "已在 methods/system.json 新增对应接口的 params/response/errors 文档,保持与实现一致。" - ], - "type": "added" - }, - { - "version": "2026.04.18-system-01", - "date": "2026-04-18", - "summary": "补充订单储位分配接口文档:order.storageAllocation.allocateStorage", - "methods": [ - "order.storageAllocation.allocateStorage" - ], - "notes": [ - "新增 order.storageAllocation.allocateStorage:按订单批量分配储位,支持多种入参别名(order_ids/ids/orderId 等)与仓库上下文优先级。", - "响应包含 requested_order_ids, pending_order_ids, allocated_order_ids, shortage_order_ids, skipped_orders, picking_count, stock_lock_summary, storage_lock_summary 等字段,用于前端展示分配结果与不足提示。" - ], - "type": "added" - }, - { - "version": "2026.04.18-system-02", - "date": "2026-04-18", - "summary": "新增 order.pendingOrder.allocateExpressCode:待处理订单模块的批量分配首单快递号(异步接口),复用 express.createWaybillCodePipeline。", - "methods": [ - "order.pendingOrder.allocateExpressCode" - ], - "notes": [ - "异步接口:调用后立即返回 task_id,后台执行运单创建,通过 allocateExpressCodeTaskProgress 查询进度。", - "入参为 ids(订单 ID 数组),sys_platform_code/logistics_code 等由后端从数据库读取。", - "拆单场景请使用 order.pendingOrder.allocateSubOrderNumber。" - ], - "type": "added" - }, - { - "version": "2026.04.18-system-03", - "date": "2026-04-18", - "summary": "将 order.storageAllocation.allocateStorage 迁移到 order.pendingOrder.allocateStorage,并移除原有公开分组。", - "methods": [ - "order.pendingOrder.allocateStorage" - ], - "notes": [ - "将对外入口从 order.storageAllocation.allocateStorage 迁移到 order.pendingOrder.allocateStorage,旧的 order.storageAllocation 分组已从 methods/system.json 中移除。", - "新的对外接口不接受 warehouse_id / warehouseId,仓库上下文由当前登录用户(ctx.user.store_id)提供。", - "本次变更仅同步文档位置与对外方法名,底层实现保留且通过新的 system 方法暴露。" - ], - "type": "changed" - }, - { - "version": "2026.04.19-system-02", - "date": "2026-04-19", - "summary": "新增待处理模块取消分配储位接口 order.pendingOrder.cancelAllocateStorage", - "methods": [ - "order.pendingOrder.cancelAllocateStorage" - ], - "notes": [ - "新增待处理模块取消分配储位接口 `order.pendingOrder.cancelAllocateStorage`,直接对接 `service.systems.orderStorageAllocation.cancelAllocateStorage` 实现。", - "接口现在仅接受订单ID(order_ids),不再接受 allow_storage_location;禁止传入 `warehouse_id/warehouseId`,仓库上下文由当前登录用户的 `store_id` 提供。", - "响应返回标准 { flag, code, message, data } 结构,data 包含取消分配的汇总结果(warehouse_id, requested_order_ids, cancellable_order_ids, skipped_orders, orders, picking_count, storage_unlock_summary, stock_unlock_summary)。" - ], - "type": "added" - }, - { - "version": "2026.04.21-system-01", - "date": "2026-04-21", - "summary": "新增 order.pendingOrder.updateOrderPlatform 方法:批量修改待处理订单平台信息", - "methods": [ - "order.pendingOrder.updateOrderPlatform" - ], - "notes": [ - "通过 code 查找 wms_platform,平台不存在时返回 404 错误。", - "仅操作当前仓库的当前订单表。", - "noNeedRight=true,noNeedAuth=true(isNeedAuth: true 在 spec 中对应权限配置 noNeedAuth=true)。" - ], - "type": "added" - }, - { - "version": "2026.04.21-system-02", - "date": "2026-04-21", - "summary": "新增方法 order.pendingOrder.updateOrderExpress:批量修改待处理订单的快递信息", - "methods": [ - "order.pendingOrder.updateOrderExpress" - ], - "notes": [ - "新增 order.pendingOrder.updateOrderExpress:批量修改待处理订单的快递信息,按 express_code 从仓库快递列表(带缓存)匹配快递项。", - "自定义映射(is_system_setting=true)时,sys_logistics_code/name 写入系统快递编码和名称,logistics_code/name 写入自定义编码和名称;系统快递(is_system_setting=false)时四个字段均写系统快递的 code/name。", - "只操作当前仓库的当前订单表,不处理其他订单表;操作后写入操作日志(ORDER_UPDATE_EXPRESS)。" - ], - "type": "added" - }, - { - "version": "2026.04.21-system-03", - "date": "2026-04-21", - "summary": "新增 order.expectionOrder.resolveException:将待处理异常订单转回正常待处理状态", - "methods": [ - "order.expectionOrder.resolveException" - ], - "notes": [ - "新增 order.expectionOrder.resolveException:批量将 step=3 的异常订单恢复为 step=2 正常待处理状态。", - "入参 ids 为订单ID 正整数数组,不能为空;仅操作当前仓库当前订单表。", - "返回 updated_count(实际更新行数)与 ids(本次操作ID列表)。", - "权限配置:noNeedLogin=false、noNeedRight=true、noNeedLog=false、noNeedAuth=true" - ], - "type": "added" - }, - { - "version": "2026.04.21-system-04", - "date": "2026-04-21", - "summary": "新增 order.pendingOrder.cloneOrder 方法:克隆待处理订单", - "methods": [ - "order.pendingOrder.cloneOrder" - ], - "notes": [ - "支持对 step 0/1/2/3 的待处理订单进行克隆操作。", - "若原订单已分配储位(storage_status=fin),克隆前自动清除已分配库存。", - "原订单取消后(step→9, status→cancel),以原订单业务数据创建新订单,流程状态字段全部重置为初始落库状态。", - "克隆订单明细含 stock_id,新订单 ID 重新绑定。", - "noNeedAuth=true,noNeedRight=true,noNeedLogin=false。" - ], - "type": "added" - }, - { - "version": "2026.04.21-system-06", - "date": "2026-04-21", - "summary": "新增 order.pendingOrder.createOrder:手动创建待处理/待审核订单", - "methods": [ - "order.pendingOrder.createOrder" - ], - "notes": [ - "新增 order.pendingOrder.createOrder:手动创建订单,step 由货主策略 need_order_approval 决定(1→待审核 step=0,0→待处理 step=1)。", - "必填字段:store_id、name、mobile/tel 至少一项、detail_address、items[](含 item_code 和 plan_qty)。", - "delivery_order_code 不传则自动生成(SYS+时间戳+随机4位);logistics_code/sys_platform_code 不传则读货主合约策略 default_express_code/default_platform_code。", - "不做库存锁定,储位分配为独立步骤。操作日志写入 ORDER_CREATE。", - "noNeedRight=true,noNeedAuth=true,noNeedLogin=false。" - ], - "type": "added" - }, - { - "version": "2026.04.21-system-07", - "date": "2026-04-21", - "summary": "新增 Excel 模板下载与批量导入创建订单接口:order.pendingOrder.downloadCreateTemplate 和 order.pendingOrder.importOrdersFromExcel", - "methods": [ - "order.pendingOrder.downloadCreateTemplate", - "order.pendingOrder.importOrdersFromExcel" - ], - "notes": [ - "新增 order.pendingOrder.downloadCreateTemplate:生成 Excel 导入模板,返回 base64 编码的 xlsx 文件,表头中带 * 的列为必填项(橙色背景),可选列为灰色背景,含示例数据行和填写说明工作表。", - "新增 order.pendingOrder.importOrdersFromExcel:接受 base64 编码的 xlsx 文件,按订单号分组,每组调用 createOrder 逻辑创建订单;不中断执行,逐条记录成功/失败结果返回。", - "多行相同订单号的行组成一个完整订单,每行代表一条商品明细;订单头信息(收件人、地址等)取每组第一行。", - "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" - }, - { - "version": "2026.05.08-system-05", - "date": "2026-05-08", - "summary": "order.wave.batchList:新增 source 字段并支持 where.source 过滤,返回 list item 中新增 source 字段", - "methods": [ - "order.wave.batchList" - ], - "notes": [ - "新增 where.source(可选,number)用于按来源过滤:0=普通波次(正常后台操作),1=管理后台策略任务,2=PDA策略任务;不传则不过滤。", - "响应 list 每条记录新增字段 source(number),用于区分波次来源。", - "仅更新文档,业务代码不在此变更范围。" - ], - "type": "updated" - }, - { - "version": "2026.05.09-system-01", - "date": "2026-05-09", - "summary": "新增 order.wave.wavePickTaskCancelSelf;order.wave.waveStrategyList 新增预演计数字段/参数", - "methods": [ - "order.wave.wavePickTaskCancelSelf", - "order.wave.waveStrategyList" - ], - "notes": [ - "新增接口 `order.wave.wavePickTaskCancelSelf`:仅支持单个 `task_id`(number,必填),明确不支持 `task_ids` 批量参数。", - "业务约束:仅允许取消当前登录用户本人创建的拣货任务;若尝试取消非本人创建任务,接口应返回 400 错误(仅允许取消本人创建任务)。", - "返回建议:与现有取消接口风格一致,包含 `cancelled_count`(0/1)、`task_id`、`task_no`(若后端返回)或相应的取消结果汇总。", - "错误码建议:400 参数不合法(task_id 缺失或传了 task_ids);400 仅允许取消本人创建任务;500 取消失败。", - "新增参数:calculate_next_fetch_order_count(number,可选),含别名 calculateNextFetchOrderCount;取值 0=不计算(默认),1=计算并返回每条策略的 next_fetch_order_count,用于前端在策略列表中预览抓取量。", - "新增响应字段:list[*].next_fetch_order_count(number),含义:按当前策略口径预演一次自动抓取时,预计会选中的订单数量;当未开启计算时返回 0。" - ], - "type": "added" - }, - { - "version": "2026.05.11-system-01", - "date": "2026-05-11", - "summary": "新增字段 wave_prefix(策略层波次前缀),并补充 PDA 抓取波次号生成行为说明", - "methods": [ - "order.wave.waveStrategyList", - "order.wave.waveStrategyCreate", - "order.wave.waveStrategyUpdate", - "order.wave.waveStrategyFetchPda" - ], - "notes": [ - "在 wave strategy 对象中新增可选字段 wave_prefix:策略波次前缀,优先于仓库前缀。", - "校验规则:长度 1-5,仅允许 A-Z0-9;保存时会转为大写;为空时回退仓库前缀:团购使用 group_wave_prefix,散单使用 delete_order_wave_prefix。", - "在 order.wave.waveStrategyList 的返回 list[*] 中新增字段 wave_prefix(string)。", - "在 order.wave.waveStrategyCreate / waveStrategyUpdate 的入参中新增可选字段 wave_prefix(string),创建/更新成功后保存为大写且触发策略版本推进。", - "在 order.wave.waveStrategyFetchPda 的行为说明中补充:生成波次号(wave_no)时优先使用策略层 wave_prefix,否则按策略类型回退到仓库前缀;前缀校验同上。" - ], - "type": "updated" - }, - { - "version": "2026.05.15-system-01", - "date": "2026-05-15", - "summary": "仅更新文档:将 setting.express.create 入参与实现对齐(新增 express_code,移除 platform)", - "methods": [ - "setting.express.create" - ], - "notes": [ - "仅同步文档,与实现对齐,未修改任何业务代码或行为" - ], - "type": "updated" - }, - { - "version": "2026.05.15-system-02", - "date": "2026-05-15", - "summary": "新增 storage.report.search:库存流水统计报表,支持按时间闭区间过滤与按库位/按商品聚合", - "methods": [ - "storage.report.search" - ], - "notes": [ - "方法新增:storage.report.search", - "时间过滤为闭区间:created_at >= start_time 且 created_at <= end_time", - "当 where.by_space 为 false(默认)时,按商品+货主聚合(多个库位汇总);当为 true 时按商品+库位返回", - "不返回无流水的商品/键(仅返回在查询区间内出现过流水的数据)" - ], - "type": "added" - }, - { - "version": "2026.05.15-system-03", - "date": "2026-05-15", - "summary": "库存报表模块主入口迁移到 stock.report.search,storage.report.search 保持兼容别名", - "methods": [ - "stock.report.search", - "storage.report.search" - ], - "notes": [ - "新增主入口方法 stock.report.search,沿用既有报表统计口径(时间闭区间、by_space/store_ids、返回字段保持一致)。", - "保留 storage.report.search 作为兼容别名,并在描述中明确建议迁移到 stock.report.search。", - "仅更新 methods 文档配置,不修改业务代码。" - ], - "type": "updated" - }, - { - "version": "2026.05.15-system-04", - "date": "2026-05-15", - "summary": "文档主入口统一为 stock.report.search,storage.report.search 调整为兼容别名简述", - "methods": [ - "stock.report.search", - "storage.report.search" - ], - "notes": [ - "保留 stock.report.search 作为库存报表唯一完整文档入口。", - "storage.report.search 不再维护完整重复字段,仅保留迁移与兼容说明。", - "仅更新 methods 文档配置,不修改业务代码。" - ], - "type": "updated" - }, - { - "version": "2026.05.15-system-05", - "date": "2026-05-15", - "summary": "拆分 storage.report 模块并移除错误 stock.report.search 文档入口", - "methods": [ - "storage.report.search", - "stock.report.search" - ], - "notes": [ - "将库存报表从 storage.inventory 中拆分为独立模块 storage.report,storage.report.search 文档改为主入口语义(不再作为兼容别名)。", - "从 storage.inventory 分组中移除错误的 stock.report.search 文档入口以及兼容别名条目 storage.report.search。", - "最终归属:storage.report.search 属于模块 storage.report;stock.report.search 的文档入口已移除以避免混淆(代码实现保留于 app/service/systemMethods/storage/report.js 的 storage.report.search)。", - "仅修改文档,不修改应用代码实现。" - ], - "type": "updated" - }, - { - "version": "2026.05.15-system-06", - "date": "2026-05-15", - "summary": "storage.report.search 新增排序能力文档说明", - "methods": [ - "storage.report.search" - ], - "notes": [ - "补充 sort 参数:支持 sortField/sort_field、sortOrder/sort_order。", - "补充排序白名单:begin_total、inbound_total、outbound_total、end_total。", - "补充非法排序字段/顺序回退默认排序说明。", - "响应说明补充:已按 sort 规则排序返回。" - ], - "type": "updated" - }, - { - "version": "2026.05.16-system-01", - "date": "2026-05-16", - "summary": "新增 storage.report.export:按与 storage.report.search 相同条件导出库存报表 Excel", - "methods": [ - "storage.report.export" - ], - "notes": [ - "新增方法:storage.report.export,复用 storage.report.search 的 where/sort 查询条件。", - "导出文件包含两个 sheet:汇总、变更记录。", - "用于在统计结果基础上回溯明细流水,提升库存变动追溯效率。" - ], - "type": "added" - }, - { - "version": "2026.05.16-system-02", - "date": "2026-05-16", - "summary": "storage.report.export 改为异步任务 + 新增 exportTaskProgress", - "methods": [ - "storage.report.export", - "storage.report.exportTaskProgress" - ], - "notes": [ - "调用方式调整为两步:先调用 storage.report.export 提交任务并获取 task_id,再调用 storage.report.exportTaskProgress 轮询任务进度。", - "下载链接获取方式:当 status=success 时,从 exportTaskProgress 响应的 download_url 字段获取导出文件地址。", - "任务状态值补充:submitted/running/success/failed/not_found。" - ], - "type": "updated" - }, - { - "version": "2026.05.16-system-03", - "date": "2026.05.16", - "summary": "同步 setting.expressInterface.create/update 入参与系统快递编码映射规则", - "methods": [ - "setting.expressInterface.create", - "setting.expressInterface.update" - ], - "notes": [ - "补充入参:sys_express_code、weight_type、address、town_name、ispickup、shipperno,并保留既有字段。", - "在参数说明补充 camelCase 别名支持:sysExpressCode、weightType、townName、isPickup、shipperNo 等。", - "同步约束变化:不再因同仓快递编码重复或平台重复直接返回 409;当 express_code 无法匹配系统快递编码时返回 400,文案为 express_code 未匹配到系统快递编码。" - ], - "type": "updated" - }, - { - "version": "2026.05.17-system-05", - "date": "2026-05-17", - "summary": "同步 storage.receiving.addDetail 的参数与返回值(从实现提取)", - "methods": [ - "storage.receiving.addDetail" - ], - "notes": [ - "补充 receiving_id 入参说明", - "补充返回的 details 数组与 selectId 字段", - "补充可能的错误码:404/400/500" - ], - "type": "updated" - }, - { - "version": "2026.05.17-system-06", - "date": "2026-05-17", - "summary": "重新同步 addDetail 文档", - "methods": [ - "storage.receiving.addDetail" - ], - "notes": [ - "再次从实现代码核对并补充参数/返回值/错误码,确保文档与实现一致", - "仅同步文档,不修改业务代码" - ], - "type": "updated" - }, - { - "version": "2026.05.17-system-07", - "date": "2026-05-17", - "summary": "addDetail 新增可选 item 入参并兼容空白创建链路", - "methods": [ - "storage.receiving.addDetail" - ], - "notes": [ - "item 有值时按传入字段创建(服务端覆盖 receiving_id 与 creator_id)", - "兼容不传 item 的空白创建链路;item.children 需覆盖关键字段(有则写、无则补齐)。" - ], - "type": "updated" - }, - { - "version": "2026.05.17-system-10", - "date": "2026-05-17", - "summary": "调整 storage.receiving.getReceivingDetail 库位字段输出语义:space_id 改为展示名称并补充兼容字段", - "methods": [ - "storage.receiving.getReceivingDetail" - ], - "notes": [ - "将 receiving.details.*.space_id 定义为展示名称(string|null),优先 custom_space_name,其次 space_name,不再作为原始数值ID文档语义。", - "新增并明确 receiving.details.*.space_id_raw(number|null)用于保留原始库位ID,兼容旧调用方。", - "补充 receiving.details.*.space_name(库位名称/编码)与 receiving.details.*.custom_space_name(自定义名称,可空)字段说明。" - ], - "type": "updated" - }, - { - "version": "2026.05.17-system-11", - "date": "2026-05-17", - "summary": "补充 subject_config.enable_external_express_code 字段文档与默认值语义", - "methods": [ - "store.createStore", - "store.createWarehouse", - "setting.warehouse.getSettings", - "setting.warehouse.saveSettings" - ], - "notes": [ - "在 store.createStore 与 store.createWarehouse 的 subject_config 入参中新增字段:enable_external_express_code(boolean),默认 false;开启后允许按外部系统传入的快递编码进行处理(如无匹配仍以业务校验为准)。", - "此 change 同时用于说明将在 setting.warehouse.getSettings / saveSettings 中补充该字段的文档说明(后续 doc-only 写入)。" - ], - "type": "updated", - "module": "store" - }, - { - "version": "2026.05.17-system-12", - "date": "2026-05-17", - "summary": "storeWarehouse.store 策略配置文档新增 enable_external_express_code 字段说明(向后兼容)", - "methods": [ - "storeWarehouse.store.getPolicyConfig", - "storeWarehouse.store.savePolicyConfig" - ], - "notes": [ - "在 getPolicyConfig / savePolicyConfig 的出参说明中补充 data.policy_config.enable_external_express_code 字段,明确为 flag(0=关闭,1=开启),默认 0。", - "在 savePolicyConfig 的入参说明中补充 policy_config.enable_external_express_code 字段定义。", - "本次为向后兼容的文档增强:新增可选策略字段说明,不影响现有调用。" - ], - "type": "updated" - }, - { - "version": "2026.05.19-system-01", - "date": "2026-05-19", - "summary": "补充 storage.entry.list 的 expense_record 筛选语义与未迁移环境错误提示", - "methods": [ - "storage.entry.list" - ], - "notes": [ - "在 where 参数说明中补充 expense_record 字段语义(费用是否记录)及 eq/in 支持。", - "明确 true/false、1/0、y/n、yes/no 的归一化规则与等价写法示例。", - "补充未完成表结构迁移时可能返回 400 及错误提示文案。" - ], - "type": "updated" - }, - { - "version": "2026.05.20-system-01", - "date": "2026-05-20", - "summary": "同步 order.recheckOrder.scanOrder 返回结构,补充 cart_match_view 语义化视图说明", - "methods": [ - "order.recheckOrder.scanOrder" - ], - "notes": [ - "新增返回字段:match_type(waybill/cart)与 cart_match_view(仅 cart 命中返回)。", - "cart_match_view 包含通用子字段:mode_code / mode_name / view_type / task;当车号命中时按 pick_mode 返回语义化结构:mode 1/5 返回 groups,mode 2 返回 orders,mode 3 返回 pick_groups,mode 4 返回 box_groups。" - ], - "type": "updated" - }, - { - "version": "2026.05.22-system-01", - "date": "2026-05-22", - "summary": "新增 index.getPlatformOauthLink 文档,补充平台授权链接接口说明", - "methods": [ - "index.getPlatformOauthLink" - ], - "notes": [ - "入参支持 code、platform_code、platformCode 三种平台编码字段别名。", - "当前仅支持 PDD;成功返回 data.platform_code、data.oauth_link 和 code=200,其他平台返回 code=400。", - "仅通过文档脚本同步 methods/system.json 与 methods/changes/system.json,不修改业务代码。" - ], - "type": "added", - "module": "index" - }, - { - "version": "2026.05.22-system-02", - "date": "2026-05-22", - "summary": "更新 index.getPlatformOauthLink 文档,补充仓库上下文、预占记录与错误说明", - "methods": [ - "index.getPlatformOauthLink" - ], - "notes": [ - "补充真实行为:从 ctx.user.store_id 读取当前仓库 ID,从 wms_platform.auth_base_url 读取授权基础地址,并在 wms_shops 创建平台授权预占记录。", - "补充 oauth_link 细节:追加 client_id、redirect_uri(配置非空时)以及长查询参数 wms_authorization_reservation_code,对应唯一 auth_random_code。", - "补充常见错误:平台编码为空、仓库上下文缺失、平台不存在、授权基础地址缺失/格式错误、不支持的平台,以及预占记录创建失败。" - ], - "type": "updated", - "module": "index" - }, - { - "version": "2026.05.22-system-03", - "date": "2026-05-22", - "summary": "同步 index.getPlatformOauthLink 当前实现:裸码入库与 state 拼接规则", - "methods": [ - "index.getPlatformOauthLink" - ], - "notes": [ - "补充真实行为:从 ctx.user.store_id 读取当前仓库,从 wms_platform.auth_base_url 读取基础授权链接,并优先复用 wms_shops 中 status=0 的未授权记录。", - "明确 auth_random_code 当前以裸码保存;若复用到历史带前缀记录,会先去掉 platformOauthReservationCodePrefix 后再回写。", - "更新 oauth_link 说明:state 由“前缀 + 平台编码 + '_' + 裸码”组成并整体 URL 编码后直接拼接到基础授权链接后,例如 xxxxx_PDD_;同时移除已不存在的基础地址格式错误/不支持平台错误描述。" - ], - "type": "updated", - "module": "index" - }, - { - "version": "2026.05.22-system-04", - "date": "2026-05-22", - "summary": "修正 index.getPlatformOauthLink 文档中的残留平台限制描述", - "methods": [ - "index.getPlatformOauthLink" - ], - "notes": [ - "移除 index.getPlatformOauthLink 参数与返回字段中残留的“当前仅支持 PDD”描述,避免与当前实现不一致。", - "保留授权链接仅依赖平台已配置基础授权链接模式的说明,不再把示例平台编码误写成实现限制。" - ], - "type": "updated", - "module": "index" - }, - { - "version": "2026.05.22-system-05", - "date": "2026-05-22", - "summary": "新增 index.getShopList 文档,并同步 custom_name 与店铺列表脱敏返回规则", - "methods": [ - "index.getShopList" - ], - "notes": [ - "新增 index.getShopList:接口依赖当前登录仓库上下文 ctx.user.store_id,不接受额外业务入参,缺少仓库时返回 400:未识别到当前仓库。", - "补充真实返回结构:data.list 为数组,包含 id、warehouse_id、platform_code、shop_name、custom_name、status、auth_expire_at、token_expires_at、refresh_token_expires_at、scope、created_at、updated_at 以及脱敏后的 owner_id、access_token、refresh_token、auth_random_code。", - "同步脱敏规则:owner_id 非空且长度大于 5 时返回前 3 位 + *** + 后 2 位,长度小于等于 5 时返回 ***;access_token、refresh_token、auth_random_code 非空时固定返回 ***,空值返回 null。", - "仅通过文档脚本同步 methods/system.json 与 methods/changes/system.json,不修改任何业务代码。" - ], - "type": "added", - "module": "index" - }, - { - "version": "2026.05.22-system-06", - "date": "2026-05-22", - "summary": "新增 index.getShopExpressList 文档,补充店铺快递列表统一返回结构", - "methods": [ - "index.getShopExpressList" - ], - "notes": [ - "按 ctx.user.store_id 校验店铺归属,仅允许查询当前登录仓库下的店铺。", - "服务端按店铺所属平台拉取并收敛快递签约/电子面单可用列表,统一返回前端消费结构。", - "未接入平台当前返回空列表;若店铺缺少授权 access_token,则返回 400:店铺未授权。", - "仅文档同步,不改业务代码。" - ], - "type": "added", - "module": "index" - }, - { - "version": "2026.05.22-system-07", - "date": "2026-05-22", - "summary": "同步快递接口文档:is_share 仅展示不可编辑", - "methods": [ - "setting.expressInterface.list", - "setting.expressInterface.create", - "setting.expressInterface.update" - ], - "notes": [ - "create/update 不再接受 is_share", - "list 仍可返回 is_share 作为展示信息", - "仅文档同步,不改业务代码" - ], - "type": "updated", - "module": "setting.expressInterface" - }, - { - "version": "2026.05.22-system-08", - "date": "2026-05-22", - "summary": "同步快递接口列表文档,移除未返回字段说明", - "methods": [ - "setting.expressInterface.list" - ], - "notes": [ - "根据 app/service/systems/setting/expressInterface.js 的 list() 查询字段与 normalizeInterfaceRow() 返回结构,同步 setting.expressInterface.list 不返回 token。", - "按当前实现清理 response.children 中未返回的 share_id、can_use_count 字段说明。", - "保留 is_share,并明确其仅用于展示,不作为编辑入参。" - ], - "type": "updated", - "module": "setting.expressInterface" - }, - { - "version": "2026.05.22-system-09", - "date": "2026-05-22", - "summary": "index.getShopList 支持按平台编码筛选店铺", - "methods": [ - "index.getShopList" - ], - "notes": [ - "index.getShopList 兼容 platform_code 与 platformCode 两种传参方式,服务端按 platform_code、platformCode 顺序读取首个 trim 后非空值作为平台筛选条件。", - "未传平台参数时返回当前登录仓库下全部已授权店铺;传入非空平台编码时仅返回该平台的已授权店铺。", - "本次仅补充筛选条件文档,不影响返回结构、排序规则与 owner_id/access_token/refresh_token/auth_random_code 的脱敏规则。", - "仅通过文档脚本同步 methods/system.json 与 methods/changes/system.json,不修改任何业务代码。" - ], - "type": "updated", - "module": "index" - }, - { - "version": "2026.05.22-system-10", - "date": "2026-05-22", - "summary": "快递接口配置新增 shop_id 字段", - "methods": [ - "setting.expressInterface.create", - "setting.expressInterface.update", - "setting.expressInterface.list" - ], - "notes": [ - "create/update 支持 shop_id/shopId(兼容 snake_case 与 camelCase),为店铺 ID,未传或空值按 null 处理。", - "list 返回 shop_id 字段,列表 where 支持按 shop_id 过滤。" - ], - "type": "updated" - }, - { - "version": "2026.05.22-system-11", - "date": "2026-05-22", - "summary": "调整快递接口列表排序规则", - "methods": [ - "setting.expressInterface.list" - ], - "notes": [ - "setting.expressInterface.list 改为按 weight ASC, id DESC 排序;优先按权重排序,权重相同再按 id 倒序。", - "本次仅同步该接口排序说明,不影响返回结构。" - ], - "type": "updated", - "module": "setting.expressInterface" - }, - { - "version": "2026.05.22-system-12", - "date": "2026-05-22", - "summary": "index.getShopExpressList 返回新增系统快递编码", - "methods": [ - "index.getShopExpressList" - ], - "notes": [ - "data.list[*] 新增 sys_express_code 字段,由平台快递编码 wp_code 映射系统快递编码,未匹配时返回空字符串。", - "补充 data.list[*].wp_name 说明:由系统快递基础表根据平台快递编码映射得到名称,未匹配时返回空字符串。", - "原有请求参数、鉴权方式与返回主结构保持不变。", - "仅文档同步,不改业务代码。" - ], - "type": "updated", - "module": "index" - }, - { - "version": "2026.05.23-system-01", - "date": "2026-05-23", - "summary": "补充快递接口列表 is_system_express_code 返回字段说明", - "methods": [ - "setting.expressInterface.list" - ], - "notes": [ - "在 setting.expressInterface.list 的 response.children 中补充 is_system_express_code 字段说明。", - "该字段表示当前行 express_code 是否为系统快递编码;不是系统快递编码返回 0,否则返回 1。", - "仅文档同步,不改业务代码。" - ], - "type": "updated", - "module": "setting.expressInterface" - }, - { - "version": "2026.05.23-system-02", - "date": "2026-05-23", - "summary": "完善 index.getExpressList 文档:补充过滤规则、返回字段与仓库维度行为", - "methods": [ - "index.getExpressList" - ], - "notes": [ - "补充 `systemOnly`、`express_code`、`expressCode` 的真实入参语义,明确真值识别规则与字段优先级。", - "补充默认模式、系统模式、按快递编码过滤模式下的返回差异,说明当前登录仓库维度来自 `ctx.user.store_id`。", - "补充 `data[*]` 各字段含义,明确系统基础快递与仓库自定义快递编码的差异字段。", - "仅文档同步,不修改业务代码。" - ], - "type": "updated", - "module": "index" - }, - { - "version": "2026.05.24-system-01", - "date": "2026-05-24", - "summary": "同步 index.getExpressList 文档:移除 expressCode 别名并明确 express_code 筛选语义", - "methods": [ - "index.getExpressList" - ], - "notes": [ - "移除 index.getExpressList 文档中的 expressCode 驼峰别名参数,仅保留 express_code。", - "明确当 systemOnly=false 且传入 express_code 时,接口按自定义映射记录中的系统快递编码字段 express_code 过滤,而不是按自定义 code 过滤。", - "保留 systemOnly=true 按系统快递编码过滤系统基础快递列表,以及默认合并逻辑、缓存优先、仓库维度来源不变的说明。" - ], - "type": "updated" - }, - { - "version": "2026.05.24-system-02", - "date": "2026-05-24", - "summary": "新增 index.getCainiaoStfTemplates 接口文档并明确模板返回语义", - "methods": [ - "index.getCainiaoStfTemplates" - ], - "notes": [ - "新增无参接口 index.getCainiaoStfTemplates:从当前仓库首个已授权 TB 店铺发起 cainiao.waybill.ii.search 查询菜鸟 STF 模板。", - "补充返回结构说明:data.platform_code 固定为 TB;data.list 返回模板数组并包含 template_id/template_name/template_url/cp_code/wp_code 字段。", - "明确模板列表为宽松结构解析并按 template_id/template_name/template_url 核心语义去重。", - "补充错误码说明:未识别仓库返回 400;当前仓库无已授权 TB 店铺返回 404。" - ], - "type": "added" - }, - { - "version": "2026.05.24-system-03", - "date": "2026-05-24", - "summary": "调整 index.getCainiaoStfTemplates 为免登录/免鉴权接口", - "methods": [ - "index.getCainiaoStfTemplates" - ], - "notes": [ - "将 index.getCainiaoStfTemplates 的 isNeedLogin 调整为 false,接口改为免登录访问。", - "保持 isNeedAuth=false,并同步免权限拦截配置,避免登录态与鉴权拦截。", - "该接口仍为无请求参数,headers 调整为空数组。" - ], - "type": "updated", - "module": "index" - }, - { - "version": "2026.05.24-system-04", - "date": "2026-05-24", - "summary": "调整 index.getCainiaoStfTemplates 为公共无参模板查询接口", - "methods": [ - "index.getCainiaoStfTemplates" - ], - "notes": [ - "index.getCainiaoStfTemplates 改为公共无参查询,不再依赖当前仓库、登录态或店铺授权。", - "接口直接调用 requestTbWaybillSearch({ cpCode: '' }) 查询公共模板,返回 data.platform_code='TB' 与模板数组。", - "requestTbWaybillSearch 支持 accessToken 缺失时不下发 session,因此该接口不再依赖 session。" - ], - "type": "updated" - }, - { - "version": "2026.05.24-system-05", - "date": "2026-05-24", - "summary": "同步 index.getCainiaoStfTemplates 改用淘宝标准模板公共接口", - "methods": [ - "index.getCainiaoStfTemplates" - ], - "notes": [ - "index.getCainiaoStfTemplates 改为调用淘宝开放平台 cainiao.cloudprint.stdtemplates.get,不再复用 cainiao.waybill.ii.search。", - "接口不需要用户授权,不下发 session,继续使用 https://eco.taobao.com/router/rest 与 TOP 公共签名参数。", - "模板列表改为从 cainiao_cloudprint_stdtemplates_get_response.result.datas[*].standard_templates[*] 做宽松兼容解析,统一返回 template_id/template_name/template_url/cp_code/wp_code。" - ], - "type": "updated" - }, - { - "version": "2026.05.24-system-06", - "date": "2026-05-24", - "summary": "新增 index.getPrintPlatformList 接口文档并明确打印平台下拉返回结构", - "methods": [ - "index.getPrintPlatformList" - ], - "notes": [ - "新增 index.getPrintPlatformList 文档,说明该接口供快递接口新增/编辑页下拉选择使用。", - "补充接口行为:仅返回未删除且状态为 ACTIVE 的打印平台,不分页,按 platform_name 与 id 升序返回。", - "补充 data[*] 返回字段说明,明确 code/name/value/label/platform_code/platform_name/status/remark 的含义。", - "仅文档同步,不修改业务代码。" - ], - "type": "added", - "module": "index" - }, - { - "version": "2026.05.24-system-07", - "date": "2026-05-24", - "summary": "新增 index.getPrintPlatformTemplateList 文档,明确 express_code 必填与模板过滤语义", - "methods": [ - "index.getPrintPlatformTemplateList" - ], - "notes": [ - "新增 index.getPrintPlatformTemplateList 方法文档,补充 platform_code 与 express_code 入参,其中 express_code 标记为必填。", - "明确业务语义:接口按 platform_code(默认 CAINIAO)定位 wms_express 中对应打印平台字段,并使用 express_code 过滤模板结果后返回。", - "补充返回结构 data.platform_code / data.express_code / data.responseData,说明未实现平台返回空对象。", - "仅文档同步,不修改业务代码。" - ], - "type": "added", - "module": "index" - }, - { - "version": "2026.05.25-system-01", - "date": "2026-05-25", - "summary": "新增 index.polyapiAuthorizeUrl 接口文档并标注免登录免鉴权特征", - "methods": [ - "index.polyapiAuthorizeUrl" - ], - "notes": [ - "新增基础模块方法 index.polyapiAuthorizeUrl,说明其为公共无参接口。", - "明确接口固定调用菠萝派 Differ.JH.BuildeAuthorizeUrl,返回体中以 data.respone 原样包裹上游响应。", - "同步标注 isNeedLogin=false、isNeedAuth=false,headers 为空数组。" - ], - "type": "added" - }, - { - "version": "2026.05.25-system-02", - "date": "2026-05-25", - "summary": "新增店铺模块相关接口文档(shops.list/add/del/edit)及授权会话接口 shops.GetAuthorizeSessionKey", - "methods": [ - "shops.list", - "shops.add", - "shops.del", - "shops.edit", - "shops.GetAuthorizeSessionKey" - ], - "notes": [ - "同步实现:shops.list 支持 where 分页与 quickWhere 快速搜索;shops.add/edit 校验 platform_code 存在且为 ACTIVE,custom_name 必填且长度限制;shops.del 为软删除,会返回 deleted=true 并清空敏感字段,若存在快递接口引用返回 409;shops.GetAuthorizeSessionKey 对 PDD/CAINIAO 平台生成预占码并返回 authorize_url,其他平台返回 501。", - "字段命名兼容说明:接口实现兼容 snake_case 与 camelCase 入参,文档以 snake_case 为主并注明兼容性。" - ], - "type": "added" - }, - { - "version": "2026.05.25-system-03", - "date": "2026-05-25", - "summary": "同步 shops.add 去入参化:移除 shop_name 入参并明确由授权后获取店铺名称", - "methods": [ - "shops.add" - ], - "notes": [ - "shops.add 入参移除 shop_name(及同义传参语义),仅保留 custom_name 与 platform_code 为关键请求字段。", - "补充说明:新增时 shop_name 由服务端生成 PENDING_* 占位名,后续以授权回调同步真实店铺名称。", - "仅文档同步,不修改任何业务代码。" - ], - "type": "updated", - "module": "shops" - }, - { - "version": "2026.05.28-system-02", - "date": "2026-05-28", - "summary": "新增 method: order.print.unlockWavePlatformPrintDataByGroup,按分组解锁波次平台打印锁", - "methods": [ - "order.print.unlockWavePlatformPrintDataByGroup" - ], - "notes": [ - "新增方法:order.print.unlockWavePlatformPrintDataByGroup,用于按分组规则批量解锁波次内被锁定的订单(将 print_lock_status 设为 'none')。", - "入参说明:group_type 默认为 platform_express(支持 platform、platform_express、order),unlock_scope 默认为 group(支持 group、wave);groups 为必须项,元素对象可包含 wave_id、platform、sys_logistics_code、order_ids 等字段。", - "返回说明:返回 summary(解锁统计)、unlocked_order_ids、unlocked_orders、ext.missing_wave_ids、ext.filtered_wave_ids 等字段。", - "实现参考:app/service/systemMethods/order/print.js 与 app/service/systems/order_print.js 的 unlockWavePlatformPrintDataByGroup 实现,相关单元测试位于 test/app/controller/system.order.print.unlockByGroup.test.js 与 test/app/service/systems/order_print.unlockWavePlatformPrintDataByGroup.test.js。" - ], - "type": "updated" - }, - { - "version": "2026.05.28-system-03", - "date": "2026-05-28", - "summary": "新增 order.updateExpressWeighingWeight 方法文档并补充单/多运单称重写入规则", - "methods": [ - "order.updateExpressWeighingWeight" - ], - "notes": [ - "新增 order.updateExpressWeighingWeight 入参说明:order_id、waybill_code、weighing_weight。", - "明确规则:单运单订单忽略 waybill_code 并直接更新唯一运单;多运单订单必须传 waybill_code 且需匹配订单下运单。", - "补充成功返回字段:order_id、waybill_code、weighing_weight。", - "补充错误码:400(参数校验与多运单缺失运单号)、404(运单记录不存在或未匹配)、500(模型未初始化或更新失败)。", - "仅通过文档脚本同步 methods/system.json 与 methods/changes/system.json,不修改业务代码。" - ], - "type": "added", - "module": "order.index" - }, - { - "version": "2026.05.28-system-01", - "date": "2026-05-28", - "summary": "新增包材相关 methods(create/update/delete/get),并提供 list 兼容说明", - "methods": [ - "setting.packageMaterial.create", - "setting.packageMaterial.update", - "setting.packageMaterial.delete", - "setting.packageMaterial.get", - "setting.packageMaterial.list" - ], - "notes": [ - "实现参考:app/service/systems/setting/packageMaterial.js", - "list 为兼容别名,内部转发至 get,建议新接入方改用 get" - ], - "type": "updated" - }, - { - "version": "2026.05.28-system-04", - "date": "2026-05-28", - "summary": "Add packageSupplier methods (create/update/delete/get) with list alias note", - "methods": [ - "setting.packageSupplier.create", - "setting.packageSupplier.update", - "setting.packageSupplier.delete", - "setting.packageSupplier.get", - "setting.packageSupplier.list" - ], - "notes": [ - "Reference implementation: app/service/systems/setting/packageSupplier.js", - "list is a compatibility alias; prefer get" - ], - "type": "updated" - }, - { - "version": "2026.05.28-system-05", - "date": "2026-05-28", - "summary": "新增 order.bindExpressPackageMaterial 方法文档,支持按订单运单绑定包材", - "methods": [ - "order.bindExpressPackageMaterial" - ], - "notes": [ - "新增 order.bindExpressPackageMaterial 入参说明:order_id、waybill_code、package_material_code(均必填)。", - "补充行为说明:按订单ID+运单号匹配 wms_order_express,按包材编码匹配包材并绑定 package_material_id 与 package_material_name_snapshot。", - "补充成功返回字段:order_id、waybill_code、package_material_id、package_material_name_snapshot、package_material_code。", - "补充错误码:400 参数错误、404 包材编码不存在、404 订单运单记录不存在、500 绑定包材失败。", - "仅通过文档脚本同步 methods/system.json 与 methods/changes/system.json,不修改业务代码。" - ], - "type": "added", - "module": "order.index" - }, - { - "version": "2026.05.29-system-01", - "date": "2026-05-29", - "summary": "新增 order.export 与 order.exportTaskProgress:订单导出异步任务与进度查询", - "methods": [ - "order.export", - "order.exportTaskProgress" - ], - "notes": [ - "order.export:提交导出任务,入参支持 table_type/tableType(枚举 current/history/dispatch/outsourced,兼容订单模块别名)与 module/module_name,where/sort 语义与 order.list 一致。接口提交后立即返回 task_id,后台异步执行导出,导出进度与结果通过 order.exportTaskProgress 查询。", - "order.exportTaskProgress:按 task_id 查询任务进度,返回 task_id、status、progress、current_count、total_count、message、error、download_url、update_time;任务上传完成后 download_url 返回可下载链接,未找到时 status=not_found。" - ], - "type": "added", - "module": "order.index" - }, - { - "version": "2026.05.30-system-01", - "date": "2026-05-30", - "summary": "新增 print.notifyLock(及 notify_lock 兼容别名),并补充 print.send 写入订单操作日志的行为说明", - "methods": [ - "print.notifyLock", - "print.notify_lock", - "print.send" - ], - "notes": [ - "新增 print.notifyLock:入参支持 order_ids/orderIds、waveGroups、data.waveGroups(至少一类提供订单 ID);仅执行订单锁定流程,不发送打印任务;写打印任务日志 + 订单操作日志;返回 locked_count、order_ids_count、order_ids、source;错误:无有效订单ID(400)、锁定失败(500)。", - "补充 print.send 文档:说明接口在执行打印任务记录的同时会写入订单操作日志(记录打印相关操作)。", - "新增兼容别名 print.notify_lock:文档说明等价转调到 print.notifyLock。" - ], - "type": "updated", - "module": "print" - }, - { - "version": "2026.06.03-system-01", - "date": "2026-06-03", - "summary": "同步 pick.query 文档为 keyword 任务化语义并补充冲突错误码", - "methods": [ - "pick.query" - ], - "notes": [ - "入参由 waybill_code/full_display 统一为 keyword(支持运单号或波次号)。", - "成功返回调整为 task_id/status/tip,status 取值 existing 或 created。", - "补充 409 冲突语义:波次已有他人活动任务时返回任务归属信息。" - ], - "type": "updated" - }, - { - "version": "2026.06.03-system-02", - "date": "2026-06-03", - "summary": "更新 pick.wavePickTaskDetail:增加快递号/储位分配前置校验并返回 action+order_ids", - "methods": [ - "pick.wavePickTaskDetail" - ], - "notes": [ - "新增前置校验:任务内若存在未分配快递号订单,返回 400,data.action=assign_express,data.order_ids 为未分配订单ID列表。", - "新增前置校验:任务内若存在未分配储位订单,返回 400,data.action=assign_storage,data.order_ids 为未分配订单ID列表。", - "保留原有权限校验与详情结构,仅补充分配校验失败分支的返回约定。" - ], - "type": "updated" - }, - { - "version": "2026.06.03-system-03", - "date": "2026-06-03", - "summary": "更新 order.wave.batchList:新增同步状态输出与筛选 sync_assignment_status", - "methods": [ - "order.wave.batchList" - ], - "notes": [ - "新增返回字段语义:list[].sync_assignment_status,取值为未同步/部分同步/已同步/同步异常。", - "新增筛选入参 where.sync_assignment_status,支持 unsynced/partially_synced/synced 英文枚举。", - "同步状态筛选规则与分配状态一致:error 并入 unsynced 过滤集合。" - ], - "type": "updated" - }, - { - "version": "2026.06.03-system-04", - "date": "2026-06-03", - "summary": "更新拣货中间态流程文档:wavePickTaskDetail 增加完成标记,并新增中间态/完全提交接口", - "methods": [ - "pick.wavePickTaskDetail", - "pick.wavePickTaskSubmit", - "pick.wavePickTaskComplete" - ], - "notes": [ - "更新 pick.wavePickTaskDetail 返回:新增 task.is_completed、task.progress(total_orders/picked_orders/pending_orders)以及顶层 is_completed。", - "新增 pick.wavePickTaskSubmit:支持保存中间态 payload 到任务 ext_json.pick_intermediate,并返回当前完成状态与进度。", - "新增 pick.wavePickTaskComplete:支持 mode=1 全部确认与 mode=2 部分确认(order_ids),返回 confirmed_order_ids 与最新进度。" - ], - "type": "updated" - }, - { - "version": "2026.06.03-system-05", - "date": "2026-06-03", - "summary": "拣货车能力拆分为一级模块 pickCart:扫码查询、任务绑车、CRUD、编码查重", - "methods": [ - "pickCart.scan", - "pickCart.bindTaskCart", - "pickCart.create", - "pickCart.update", - "pickCart.delete", - "pickCart.detail", - "pickCart.list", - "pickCart.codeDuplicateCheck" - ], - "notes": [ - "拣货车能力独立为一级模块 pickCart,不再挂在 pick 模块下。", - "新增 pickCart.scan:PDA 按 cart_code 扫码查询拣货车信息,用于进入任务绑定流程。", - "新增 pickCart.bindTaskCart:支持按 cart_id/cart_code 将拣货车绑定到指定拣货任务,若车已绑定其他活动任务则返回冲突。", - "新增 pickCart.create/pickCart.update/pickCart.delete/pickCart.detail/pickCart.list:补齐拣货车增删查改与分页查询能力。", - "新增 pickCart.codeDuplicateCheck:支持 exclude_cart_id 排除自身,供编辑场景做非自身重复校验;拣货车编码在当前仓库内不可重复。" - ], - "type": "updated" - }, - { - "version": "2026.06.03-system-06", - "date": "2026-06-03", - "summary": "更新 order.wave.batchList:新增 only_todo、复核状态聚合与复核筛选", - "methods": [ - "order.wave.batchList" - ], - "notes": [ - "新增入参 only_todo(默认 0):传 1/true 时仅返回仍有未复核订单的波次(unreviewed_order_count > 0)。", - "新增返回字段:list[].unreviewed_order_count(未复核订单数)与 list[].review_assignment_status(未复核/部分复核/已复核)。", - "新增 where.review_assignment_status 筛选,支持 unreviewed/partially_reviewed/reviewed 英文枚举。" - ], - "type": "updated", - "module": "order.wave" - }, - { - "version": "2026.06.04-system-01", - "date": "2026-06-04", - "summary": "裁剪 pick.wavePickTaskDetail 返回:团购小波次(pick_mode=1)不返回 picking_details 字段以减少带宽", - "methods": [ - "pick.wavePickTaskDetail" - ], - "notes": [ - "在 picking_details 字段 description 中补充:当 pick_mode=1(团购小波次)时该字段不返回,减少带宽浪费;其他 pick_mode(2/3/4/5)正常返回 picking_details。", - "在接口 description 中补充该裁剪行为的说明。", - "picking_summary、picking_view、boxes 等字段不受影响,pick_mode=1 时仍正常返回。" - ], - "type": "updated" - }, - { - "version": "2026.06.04-system-02", - "date": "2026-06-04", - "summary": "完善 index.getPlatformList 文档:补充入参 systemOnly/full、响应字段及错误码 500", - "methods": [ - "index.getPlatformList" - ], - "notes": [ - "补充入参说明:systemOnly(可选,支持 is_system 别名,真值识别 true/1/'1'/'true')、full(可选,真值识别同上,为 true 时返回全量表字段与 route_platform_code/platid 等扩展信息)", - "补充响应 data 数组每项字段:code、name、value、label、platform_code、platform_name、default_express_interface、is_system_setting、id(仅仓库自定义项)、alias(仅仓库自定义项)、full 模式扩展字段说明", - "说明合并逻辑:系统平台在前,仓库自定义在后,同 code 仅保留首条(系统优先);systemOnly=true 仅返回系统平台", - "补充缓存策略:优先读缓存,key 格式为 platform:list:{warehouseId}[:full] 或 platform:list:system[:full]", - "补充错误码 500:数据库或缓存访问异常", - "仅文档更新,不修改任何业务实现" - ], - "type": "updated", - "module": "index" - }, - { - "version": "2026.06.04-system-03", - "date": "2026-06-04", - "summary": "作废 order.pendingOrder.downloadCreateTemplate 和 order.pendingOrder.importOrdersFromExcel", - "methods": [ - "order.pendingOrder.downloadCreateTemplate", - "order.pendingOrder.importOrdersFromExcel" - ], - "notes": [ - "order.pendingOrder.downloadCreateTemplate:下载订单导入模板方法已从代码中移除,标记为 deprecated。", - "order.pendingOrder.importOrdersFromExcel:从 Excel 导入订单方法已从代码中移除,标记为 deprecated。", - "两个方法的文档条目保留在 methods/system.json 中,仅追加 status: 'deprecated' 与 description 中的'(已作废)'标记,未删除。" - ], - "type": "deprecated" - }, - { - "version": "2026.06.05-system-01", - "date": "2026-06-05", - "summary": "新增 storeWarehouse.store.openAccount 接口:仓库代货主一键开户(合并注册账号+创建货主+签约)", - "methods": [ - "storeWarehouse.store.openAccount" - ], - "notes": [ - "新增 storeWarehouse.store.openAccount 方法,归属货主-仓库签约模块(storeWarehouse.store)。", - "接口同时完成账号注册、货主创建和仓库-货主签约,一步完成开户全流程。", - "当前主体必须为仓库角色(Authorization header 中携带的 token 对应仓库用户)。", - "必填参数:username(登录账号)、password(初始密码)、company_name(公司全称)、business_license(营业执照号)、contact_person(联系人)、contact_phone(联系电话)。", - "响应返回新创建的 store_id、account_id、contract_id、company_name、username、role_id。" - ], - "type": "added", - "module": "storeWarehouse" - }, - { - "version": "2026.06.05-system-02", - "date": "2026-06-05", - "summary": "优化 storeWarehouse.store.openAccount 必填参数:password 改为随机生成、business_license 和 contact_phone 改为可选,必填仅剩 username/company_name/contact_person 三个", - "methods": [ - "storeWarehouse.store.openAccount" - ], - "notes": [ - "password:由必填改为可选,不传时自动随机生成 12 位密码", - "business_license:由必填改为可选", - "contact_phone:由必填改为可选" - ], - "type": "updated" - }, - { - "version": "2026.06.05-system-03", - "date": "2026-06-05", - "summary": "saveApiConfig 增加 callback_url 参数,支持配置 API 回调通知地址", - "methods": [ - "storeWarehouse.store.saveApiConfig" - ], - "notes": [ - "新增 callback_url 参数:OpenAPI 类型接口支持配置回调通知 URL", - "兼容别名 callbackUrl,最大 500 字符", - "存入 wms_api_app.callback_url 字段" - ], - "type": "modified" - }, - { - "version": "2026.06.05-system-04", - "date": "2026-06-05", - "summary": "createOrder 入参 item_code 改为 item_id,province/city/area 改为必填", - "methods": [ - "order.pendingOrder.createOrder" - ], - "notes": [ - "items[].item_code → items[].item_id:改用商品主键直接匹配,不依赖外部系统商品推送", - "province/city/area 新增必填校验,空值返回 400", - "item_name 优先外部传入,其次从 StockStore 缓存获取,最后兜底'商品'" - ], - "type": "modified" - }, - { - "version": "2026.06.05-system-05", - "date": "2026-06-05", - "summary": "新增 order.pendingOrder.parseAddress 智能地址解析方法", - "methods": [ - "order.pendingOrder.parseAddress" - ], - "notes": [ - "使用 DeepSeek AI 模型将非结构化地址字符串解析为省/市/区/详细地址/收件人/手机号", - "解析结果可直接用于 createOrder 的 receiverInfo 字段", - "DeepSeek API Key 通过 DEEPSEEK_API_KEY 环境变量配置" - ], - "type": "added" - }, - { - "version": "2026.06.05-system-06", - "date": "2026-06-05", - "summary": "waveStrategyUpdate/waveStrategyCreate 新增 wave_prefix 参数", - "methods": [ - "order.wave.waveStrategyUpdate", - "order.wave.waveStrategyCreate" - ], - "notes": [ - "新增 wave_prefix 波次编号前缀字段,最多 5 个字符,为空存 null" - ], - "type": "modified" - }, - { - "version": "2026.06.05-system-07", - "date": "2026-06-05", - "summary": "parseAddress 响应新增 town 字段(乡镇/街道)", - "methods": [ - "order.pendingOrder.parseAddress" - ], - "notes": [ - "响应 data 中新增 town 字段,返回 AI 解析出的乡镇/街道名称" - ], - "type": "modified" - }, - { - "version": "2026.06.05-system-08", - "date": "2026-06-05", - "summary": "为 order.list 响应新增 recheck_status 字段(复核状态:none=未复核,fin=已复核)", - "methods": [ - "order.list" - ], - "notes": [ - "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" - ], - "type": "updated" - }, - { - "version": "2026.06.05-system-09", - "date": "2026-06-05", - "summary": "为 order.reviewOrder.list 响应新增 recheck_status 字段(复核状态:none=未复核,fin=已复核)", - "methods": [ - "order.reviewOrder.list" - ], - "notes": [ - "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" - ], - "type": "updated" - }, - { - "version": "2026.06.05-system-10", - "date": "2026-06-05", - "summary": "为 order.pendingOrder.list 响应新增 recheck_status 字段(复核状态:none=未复核,fin=已复核)", - "methods": [ - "order.pendingOrder.list" - ], - "notes": [ - "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" - ], - "type": "updated" - }, - { - "version": "2026.06.05-system-11", - "date": "2026-06-05", - "summary": "为 order.outboundOrder.list 响应新增 recheck_status 字段(复核状态:none=未复核,fin=已复核)", - "methods": [ - "order.outboundOrder.list" - ], - "notes": [ - "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" - ], - "type": "updated" - }, - { - "version": "2026.06.05-system-12", - "date": "2026-06-05", - "summary": "为 order.expectionOrder.list 响应新增 recheck_status 字段(复核状态:none=未复核,fin=已复核)", - "methods": [ - "order.expectionOrder.list" - ], - "notes": [ - "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" - ], - "type": "updated" - }, - { - "version": "2026.06.05-system-13", - "date": "2026-06-05", - "summary": "为 order.entrustOrder.list 响应新增 recheck_status 字段(复核状态:none=未复核,fin=已复核)", - "methods": [ - "order.entrustOrder.list" - ], - "notes": [ - "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" - ], - "type": "updated" - }, - { - "version": "2026.06.05-system-14", - "date": "2026-06-05", - "summary": "为 order.deliveryOrder.list 响应新增 recheck_status 字段(复核状态:none=未复核,fin=已复核)", - "methods": [ - "order.deliveryOrder.list" - ], - "notes": [ - "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" - ], - "type": "updated" - }, - { - "version": "2026.06.05-system-15", - "date": "2026-06-05", - "summary": "为 order.deliveryExpectionOrder.list 响应新增 recheck_status 字段(复核状态:none=未复核,fin=已复核)", - "methods": [ - "order.deliveryExpectionOrder.list" - ], - "notes": [ - "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" - ], - "type": "updated" - }, - { - "version": "2026.06.05-system-16", - "date": "2026-06-05", - "summary": "为 order.archiveOrder.list 响应新增 recheck_status 字段(复核状态:none=未复核,fin=已复核)", - "methods": [ - "order.archiveOrder.list" - ], - "notes": [ - "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" - ], - "type": "updated" - }, - { - "version": "2026.06.06-system-01", - "date": "2026-06-06", - "summary": "恢复 order.pendingOrder.downloadCreateTemplate:方法仍存在于代码中,取消 deprecated 标记,完善文档描述", - "methods": [ - "order.pendingOrder.downloadCreateTemplate" - ], - "notes": [ - "order.pendingOrder.downloadCreateTemplate 方法在 pendingOrder.js 中仍存在(line 2099),此前被误标记为 deprecated。", - "取消 status: 'deprecated' 标记,恢复为 active 状态。", - "移除 description 中的'(已作废)'后缀。", - "完善 description:说明模板包含必填列(橙色背景)、可选列(灰色背景)、示例数据行和填写说明工作表。", - "补充 response 字段说明:filename 和 mime 为固定值。" - ], - "type": "updated" - }, - { - "version": "2026.06.07-system-01", - "date": "2026-06-07", - "summary": "order.pendingOrder.createOrder 文档新增 shop_nick 入参(店铺名称,可选,最大长度200)", - "methods": [ - "order.pendingOrder.createOrder" - ], - "notes": [ - "在 order.pendingOrder.createOrder 的 request params 中新增 shop_nick 字段(string,非必填),对应代码实现中 shopNick: String(requestData.shop_nick || requestData.shopNick || '').trim()。", - "shop_nick 已在 COPY_FIELDS 白名单中(pendingOrder.js L1738),仅文档缺失,本次为补齐。" - ], - "type": "updated" - }, - { - "version": "2026.06.07-system-02", - "date": "2026-06-07", - "summary": "order.pendingOrder.downloadCreateTemplate:模板新增 shop_nick 列(店铺名称),store_id/province/city/area 标注为非必填", - "methods": [ - "order.pendingOrder.downloadCreateTemplate" - ], - "notes": [ - "模板新增 shop_nick(店铺名称)列,非必填。", - "明确标注 store_id(货主ID)、province(省份)、city(城市)、area(区/县)为非必填列。", - "响应文档中新增 shop_nick 字段说明。" - ], - "type": "updated" - }, - { - "version": "2026.06.07-system-03", - "date": "2026-06-07", - "summary": "新增 order.pendingOrder.updateAddress:批量修改待处理订单收件地址,限制未分配快递时可用", - "methods": [ - "order.pendingOrder.updateAddress" - ], - "notes": [ - "新增 method:order.pendingOrder.updateAddress,免权限(isNeedAuth=false),需登录", - "功能:批量修改待处理订单收件地址(name/mobile/tel/zip_code/province/city/area/town/detail_address)", - "约束:仅 post_status='none'(未分配快递)的订单可修改;至少提供一个有效地址字段", - "响应:返回 updated_count(实际更新行数)和 ids(请求订单ID数组)" - ], - "type": "added" - }, - { - "version": "2026.06.07-system-04", - "date": "2026-06-07", - "summary": "order.wave.wavePickTaskCancel 扩展可取消状态至 status=3,并新增拣货状态回退", - "methods": [ - "order.wave.wavePickTaskCancel" - ], - "notes": [ - "可取消状态从 [0,1,2] 扩展为 [0,1,2,3](status=3 已完成现在也可取消)", - "取消 status=2(待复核)或 status=3(已完成)任务时,自动回退 wms_wave_pick_task_order.pick_status(1→0)和 order_delivery.pick_status(fin→padding)", - "错误码 400 描述同步更新,补充 403 错误码说明" - ], - "type": "updated" - }, - { - "version": "2026.06.07-system-05", - "date": "2026-06-07", - "summary": "order.wave.wavePickTaskList 响应新增 cart_name 字段(拣货车名称)", - "methods": [ - "order.wave.wavePickTaskList" - ], - "notes": [ - "响应 list 子项新增 cart_name(string):通过 current_cart_id LEFT JOIN wms_pick_cart 表获取,未绑定拣货车时为空字符串。" - ], - "type": "updated" - }, - { - "version": "2026.06.07-system-06", - "date": "2026-06-07", - "summary": "pick.wavePickTaskComplete 新增后台抓取任务(source=2)拣货车绑定校验,未绑定拣货车时拒绝提交", - "methods": [ - "pick.wavePickTaskComplete" - ], - "notes": [ - "description 补充说明:后台抓取创建的任务(source=2)必须先绑定拣货车才能提交,否则返回 400。", - "errors 中 400 错误补充:后台抓取任务(source=2)未绑定拣货车时拒绝提交,错误消息为\"后台抓取任务必须先绑定拣货车才能提交\"。" - ], - "type": "updated" - }, - { - "version": "2026.06.07-system-07", - "date": "2026-06-07", - "summary": "order.wave.batchList 文档修正:移除代码中不存在的 sync_assignment_status 引用", - "methods": [ - "order.wave.batchList" - ], - "notes": [ - "从 where 描述中移除 sync_assignment_status(代码 buildBatchListWhereClause allowedFields 中不存在该字段,BATCH_LIST_ASSIGNMENT_FILTER_SCHEMAS 中也无 review 之外的同步类型)。", - "从 response list 描述中移除 sync_assignment_status(代码响应映射中仅返回 storage/express/print/review 四种 assignment_status,无 sync_assignment_status)。", - "v2026.06.03-system-03 变更记录中声称新增的 sync_assignment_status 实际从未在代码中实现,本次仅为文档修正,不涉及代码变更。" - ], - "type": "updated", - "module": "order.wave" - }, - { - "version": "2026.06.07-system-08", - "date": "2026-06-07", - "summary": "order.recheckOrder.confirmRecheck 补充后置行为说明:波次任务全部复核完成后自动解绑车任务", - "methods": [ - "order.recheckOrder.confirmRecheck" - ], - "notes": [ - "在 description 中补充:确认复核后,若该订单所属波次拣货任务下所有订单均已复核完成,则自动解绑车任务。解绑操作包括:清空 wms_wave_pick_task 的 current_cart_id/current_cart_code_snapshot、停用 wms_pick_task_cart_binding(is_active=0 并记录解绑人和时间)、释放 wms_pick_cart(清空 current_task_id/bind_user_id)。", - "解绑失败仅记录 warn 日志,不影响复核主流程。", - "入参和返回结构未变,仅补充行为说明。" - ], - "type": "updated" - }, - { - "version": "2026.06.07-system-10", - "date": "2026-06-07", - "summary": "移除 order.wave.groupFetch / singleFetch / fetch 响应中已废弃的 auto_fetch_disabled_marker 字段", - "methods": [ - "order.wave.groupFetch", - "order.wave.singleFetch", - "order.wave.fetch" - ], - "notes": [ - "auto_fetch_disabled_marker 字段已从代码 submitFetchTask 响应中移除,文档同步删除该字段的描述。", - "auto_fetch_disabled 字段同样已从代码中移除,且原文档中不存在此字段(仅有 auto_fetch_disabled_marker),无需额外处理。", - "涉及 method:order.wave.groupFetch、order.wave.singleFetch、order.wave.fetch,均移除 response 中的 auto_fetch_disabled_marker 字段。" - ], - "type": "updated", - "module": "order.wave" - }, - { - "version": "2026.06.08-system-01", - "date": "2026-06-08", - "summary": "order.recheckOrder 模块 scanOrder 返回值重构为统一 list 输出,新增 confirmIntercept 与 recheckOrderList 接口", - "methods": [ - "order.recheckOrder.scanOrder", - "order.recheckOrder.confirmIntercept", - "order.recheckOrder.recheckOrderList" - ], - "notes": [ - "scanOrder 返回值重构:统一使用 list 字段输出,新增 list_type 字段区分散单/团购模式。散单模式顶层新增 picker_id、picker_name、wave_id、wave_no、wave_type、pick_mode、strategy_id、strategy_name、total_orders、reviewed_count、unreviewed_count 等汇总字段。list 中每项新增 waybill_no、is_printed、is_reviewed、wave_index、intercept_status、store_remark、stock[](含 stock_id、item_code、item_name、sku_property、packing_requirements、barcodes[]、images[]、plan_qty、has_shared_barcode)。移除旧字段 logs、order、order_id(顶层)、waybill_no(顶层旧位置)、wave_match_view、items、expresses、cart_match_view。", - "scanOrder 入参新增 wave_no / waveNo 支持波次号直接扫描匹配。", - "新增 order.recheckOrder.confirmIntercept:确认拦截接口,将订单 intercept_status 更新为 intercepted_at_warehouse,返回 order_id、order_no、intercept_status、updated_at。", - "新增 order.recheckOrder.recheckOrderList:复核订单列表查询,支持 list_type=single(散单)与 list_type=group(团购),均返回统一 list + pagination 结构。" - ], - "type": "updated" - }, - { - "version": "2026.06.08-system-02", - "date": "2026-06-08", - "summary": "order.recheckOrder 模块新增 batchIntercept/batchInterceptTaskProgress,更新 scanOrder 团购模式响应结构,完善 confirmIntercept/recheckOrderList 文档", - "methods": [ - "order.recheckOrder.batchIntercept", - "order.recheckOrder.batchInterceptTaskProgress", - "order.recheckOrder.scanOrder", - "order.recheckOrder.confirmIntercept", - "order.recheckOrder.recheckOrderList" - ], - "notes": [ - "新增 order.recheckOrder.batchIntercept:批量提交订单拦截(异步任务模式),入参支持 order_ids/orderIds/ids(订单ID数组,不再使用 wave_ids),将 intercept_status 设为 'requested',返回 task_id/warehouse_id/message/accepted_at。支持幂等提交与 warehouse_id 校验。", - "新增 order.recheckOrder.batchInterceptTaskProgress:按 task_id 查询批量拦截任务进度,返回 state(submitted/running/success/failed/not_found)及对应的进度/计数/结果/错误字段。", - "更新 order.recheckOrder.scanOrder 响应文档:团购模式(cart 命中)list 项新增 wave_id/wave_no/wave_type/wave_status/total_orders/processed_orders/creator/create_time/update_time/order_count/pick_mode/box_no/orders[] 等波次级别字段;补充散单无波次信息时的回退详情模式说明(detail/items/expresses/logs)。", - "完善 order.recheckOrder.confirmIntercept:补充操作日志写入说明(ORDER_INTERCEPT_CONFIRM)及失败不影响主流程的容错描述。", - "完善 order.recheckOrder.recheckOrderList:补充散单模式默认排除 pick_status='none' 和 recheck_status='fin' 的说明;团购模式 where 支持 wave_no(模糊搜索)的说明。" - ], - "type": "updated" - }, - { - "version": "2026.06.08-system-03", - "date": "2026-06-08", - "summary": "移除 order.recheckOrder.batchIntercept 的 warehouse_id/warehouseId 入参,仓库ID统一使用当前上下文", - "methods": [ - "order.recheckOrder.batchIntercept" - ], - "notes": [ - "移除入参 warehouse_id / warehouseId:仓库ID统一从当前上下文(ctx.user.store_id)获取,不再由调用方传入。", - "移除对应错误码:warehouse_id 参数不合法(400)、warehouse_id 与当前仓库上下文不一致(400)。", - "description 中补充说明仓库ID来源为当前上下文。", - "response 中 warehouse_id 字段描述改为「取自当前上下文」。" - ], - "type": "updated" - }, - { - "version": "2026.06.08-system-10", - "date": "2026-06-08", - "summary": "batchIntercept / batchInterceptTaskProgress 从 order.recheckOrder 迁移至 order.pendingOrder", - "methods": [ - "order.pendingOrder.batchIntercept", - "order.pendingOrder.batchInterceptTaskProgress" - ], - "notes": [ - "method 从 order.recheckOrder.batchIntercept 重命名为 order.pendingOrder.batchIntercept,分组从订单复核模块迁移至订单待处理模块", - "method 从 order.recheckOrder.batchInterceptTaskProgress 重命名为 order.pendingOrder.batchInterceptTaskProgress,分组从订单复核模块迁移至订单待处理模块", - "接口入参、响应、错误码均保持不变,仅变更 method 名称与所属分组" - ], - "type": "updated" - }, - { - "version": "2026.06.08-system-04", - "date": "2026-06-08", - "summary": "新增 order.print.getOrderPrintData:按订单ID拉取打印数据,返回结构与 getWavePlatformPrintData 一致,不限制锁定状态", - "methods": [ - "order.print.getOrderPrintData" - ], - "notes": [ - "新增 order.print.getOrderPrintData 接口文档,入参为 warehouse_id + order_ids(非空数组),返回与 getWavePlatformPrintData 结构一致的 waveGroups / summary / wave_ids / ext", - "与 getWavePlatformPrintData 的区别:入参为 order_ids(非 wave_ids),ext 中返回 missing_order_ids / filtered_order_ids(非 missing_wave_ids / filtered_wave_ids)", - "不限制打印锁定状态,所有订单(无论是否被锁定)统一返回打印数据", - "自动过滤 post_status !== 'fin' 的订单(快递未完全分配),被过滤订单出现在 ext.filtered_order_ids" - ], - "type": "added", - "module": "order.print" - }, - { - "version": "2026.06.08-system-11", - "date": "2026-06-08", - "summary": "新增 order.pendingOrder 批量锁定/解锁/解除拦截及对应进度查询共 6 个异步任务接口文档", - "methods": [ - "order.pendingOrder.batchLock", - "order.pendingOrder.batchLockTaskProgress", - "order.pendingOrder.batchUnlock", - "order.pendingOrder.batchUnlockTaskProgress", - "order.pendingOrder.batchUnintercept", - "order.pendingOrder.batchUninterceptTaskProgress" - ], - "notes": [ - "新增 batchLock:批量锁定订单,lock_status → 'warehouse',操作日志 ORDER_LOCK,task_id 格式 order_lock_{warehouseId}_{timestamp}_{rand}。", - "新增 batchLockTaskProgress:查询批量锁定进度,返回 locked_order_count / locked_order_ids 等。", - "新增 batchUnlock:批量解锁订单,lock_status → 'none',操作日志 ORDER_UNLOCK,task_id 格式 order_unlock_{warehouseId}_{timestamp}_{rand}。", - "新增 batchUnlockTaskProgress:查询批量解锁进度,返回 unlocked_order_count / unlocked_order_ids 等。", - "新增 batchUnintercept:批量解除拦截订单,intercept_status → 'none',操作日志 ORDER_INTERCEPT_CANCEL,task_id 格式 order_unintercept_{warehouseId}_{timestamp}_{rand}。", - "新增 batchUninterceptTaskProgress:查询批量解除拦截进度,返回 unintercepted_order_count / unintercepted_order_ids 等。", - "以上 6 个接口均采用与已有 batchIntercept/batchInterceptTaskProgress 一致的异步任务模式:提交返回 task_id,进度查询返回 state + 进度字段。", - "仅同步文档,不修改业务代码或实现。" - ], - "type": "added", - "module": "order" - }, - { - "version": "2026.06.08-system-12", - "date": "2026-06-08", - "summary": "更新 order.print.getOrderPrintData:移除锁定限制,所有订单统一返回打印数据,不再区分锁定/未锁定", - "methods": [ - "order.print.getOrderPrintData" - ], - "notes": [ - "移除打印锁定限制:所有订单(包括已锁定)统一返回打印数据,不再区分锁定/未锁定状态", - "移除 locked_count、locked_orders、locked_wave_groups 等锁定相关字段", - "返回结构与 getWavePlatformPrintData 完全一致:summary / waveGroups / wave_ids / ext", - "ext 中使用 missing_order_ids / filtered_order_ids(替代锁定相关字段),与代码实现完全对齐" - ], - "type": "updated", - "module": "order.print" - }, - { - "version": "2026.06.08-system-13", - "date": "2026-06-08", - "summary": "更新 order.print.getOrderPrintData:移除 warehouse_id 入参,仓库ID统一从当前上下文获取", - "methods": [ - "order.print.getOrderPrintData" - ], - "notes": [ - "移除 warehouse_id / warehouseId 入参,仓库ID统一从 this.getContextWarehouseId() 获取", - "同步移除 errors 中 warehouse_id 必填 相关错误码", - "description 补充说明仓库ID从上下文获取,无需调用方传入", - "params 仅保留 order_ids(非空数组),与代码 method 层 getOrderPrintData(data) 解构一致" - ], - "type": "updated", - "module": "order.print" - }, - { - "version": "2026.06.08-system-14", - "date": "2026-06-08", - "summary": "新增 order.recheckOrder.scanTask 接口文档,并为 scanOrder 响应补充 task_id 字段", - "methods": [ - "order.recheckOrder.scanTask", - "order.recheckOrder.scanOrder" - ], - "notes": [ - "新增 order.recheckOrder.scanTask:按拣货任务 ID 拉取复核数据,数据结构与 scanOrder 完全一致,用于前端刷新。入参为 task_id(必填,number),返回 match_type='task',散单模式(pick_mode 2/3/4)返回扁平订单列表,团购模式(pick_mode 1/5)返回分组波次列表。", - "更新 order.recheckOrder.scanOrder 响应定义:补充 task_id 字段说明(散单有波次时由 buildSingleWaveScanView 返回,团单车号命中时由 cartMatchContext 返回)。", - "仅同步文档,不修改任何业务代码或实现。" - ], - "type": "updated" - }, - { - "version": "2026.06.08-system-15", - "date": "2026-06-08", - "summary": "新增 order.pendingOrder.manualWaybill 接口(手工录入运单号)", - "methods": [ - "order.pendingOrder.manualWaybill" - ], - "notes": [ - "为待处理订单手动录入运单号,写入 wms_order_express 表", - "仅允许 step 在 [1,2,3] 且 outbound_status 不为 'padding' 的订单操作", - "免权限(isNeedAuth: false),需登录", - "成功返回运单记录的 id、order_id、waybill_code、create_at" - ], - "type": "added" - }, - { - "version": "2026.06.09-system-01", - "date": "2026-06-09", - "summary": "order.pendingOrder.updateAddress 新增 remark 字段:订单留言/备注批量覆盖,不受 post_status 限制", - "methods": [ - "order.pendingOrder.updateAddress" - ], - "notes": [ - "在 params 中新增 remark 字段(string,可选,最大500字符),支持批量覆盖所选订单的 remark", - "remark 更新不受 post_status 限制,可对所有订单生效(地址字段仍仅允许 post_status='none')", - "更新 description 明确 remark 与地址字段的独立性", - "更新 response 中 updated_count 说明:取地址更新行数与备注更新行数的最大值", - "更新 errors 中缺少字段的错误描述,改为「至少需要提供一个地址字段或备注进行修改」", - "业务代码已同步实现,本次仅同步文档" - ], - "type": "updated" - }, - { - "version": "2026.06.09-system-02", - "date": "2026-06-09", - "summary": "order.updateExpressWeighingWeight 新增运单号模式文档:order_id=0 时从运单号反查,支持散单与团购批量两种返回结构", - "methods": [ - "order.updateExpressWeighingWeight" - ], - "notes": [ - "order_id 参数说明补充:设为0时切换为运单号模式,需配合 waybill_code 使用。", - "waybill_code 参数说明补充:运单号模式(order_id=0)下必填。", - "description 更新:明确订单模式与运单号模式两种路径及团购波次批量行为。", - "response 新增运单号散单场景字段(order_id、waybill_code、weighing_weight)与运单号团购批量场景字段(wave_no、business_key、weighing_weight、success_count)。", - "errors 新增运单号模式相关错误码:运单号不存在(404)、运单号对应的订单不存在(404)、波次下未找到订单(404)、批量更新失败(500)。", - "仅文档同步,不修改业务代码。" - ], - "type": "updated" - }, - { - "version": "2026.06.09-system-03", - "date": "2026-06-09", - "summary": "order.updateExpressWeighingWeight 团购返回新增拆单汇总字段,移除 success_count/total_count", - "methods": [ - "order.updateExpressWeighingWeight" - ], - "notes": [ - "团购批量模式 response 新增 total_weight(所有拆单重量累加)、split_count(waybill_code 非空的 business_key 数量)、splits(按 business_key 分组的拆单明细数组,每项含 business_key/weighing_weight/waybill_code)、store_name(货主名称)和 sys_logistics_name(系统快递名称)。", - "移除 response 中的 success_count 与 total_count 字段,改为由 total_weight 和 split_count 提供汇总信息。", - "更新 description 以反映团购模式返回拆单汇总结构。" - ], - "type": "updated" - }, - { - "version": "2026.06.10-system-01", - "date": "2026-06-10", - "summary": "order.detail 接口文档:expresses 数组新增字段 weighing_weight、sys_logistics_code、sys_logistics_name、business_key、created_at", - "methods": [ - "order.detail" - ], - "notes": [ - "expresses 数组新增字段:weighing_weight(称重重量,number|null)、sys_logistics_code(系统物流公司编码,string)、sys_logistics_name(系统物流公司名称,string)、business_key(业务标识,string)、created_at(创建时间戳毫秒,number|null)", - "字段来源:getOrderExpressesByOrderId 方法中 sys_logistics_code/sys_logistics_name 取自订单表 sys_logistics_code/sys_logistics_name,其余字段取自 OrderExpress 表" - ], - "type": "updated" - }, - { - "version": "2026.06.10-system-02", - "date": "2026-06-10", - "summary": "dashboard.order_trend 从 mock 数据改为查询真实数据库,按小时统计当日订单数与发货数,补充完整返回结构与错误说明", - "methods": [ - "dashboard.order_trend" - ], - "notes": [ - "接口实现从 mock 静态数据改为查询真实数据库(wms_order_delivery 与 dispatch 表),数据实时反映仓库当日运营情况。", - "订单筛选条件:step in [1,2,3],排除 outbound_status='padding' 和 status='cancel',统计 create_at 在今日 00:00 到当前时刻的订单,按 HOUR(create_at) 分组。", - "发货筛选条件:dispatch_lane='m4',统计 delivery_time 在今日 00:00 到当前时刻的发货记录,按 HOUR(delivery_time) 分组。", - "时段范围:从 08:00 到当前小时(最晚 23:00),若当前时间早于 08:00 则从 08:00 开始。", - "返回新增 summary 汇总对象:total_orders(订单总数)、total_shipments(发货总数)、shipment_rate(发货率百分比)、peak_hour(峰值时段)、peak_orders(峰值订单数)。", - "categories/orders/shipments 三个数组一一对应,提供按时段的订单与发货趋势数据,可直接用于前端折线图/柱状图渲染。", - "需要登录(Authorization header),从 token 中获取 warehouseId;若缺少仓库上下文则返回 flag='fail'。" - ], - "type": "updated", - "module": "dashboard" - }, - { - "version": "2026.06.10-system-03", - "date": "2026-06-10", - "summary": "order.pendingOrder.manualWaybill 新增可选参数 logistics_interface_name 与响应字段 business_key/logistics_interface_name,补充行为说明", - "methods": [ - "order.pendingOrder.manualWaybill" - ], - "notes": [ - "新增可选参数 logistics_interface_name(string,选填,trim 后为空则传 null)", - "响应新增字段 business_key(number):同一订单下从已有最大值 +1 递增,无记录时从 1 开始", - "响应新增字段 logistics_interface_name(string/null):写入的物流接口名称", - "补充 description 行为说明:完成后自动更新 wms_order_delivery_* 表的 print_status 和 post_status 为 'fin'", - "wms_order_express 表写入时 status 固定为 1,warehouse_id 从订单记录取" - ], - "type": "updated" - }, - { - "version": "2026.06.10-system-04", - "date": "2026-06-10", - "summary": "stock.warehouse.import 新增 barcode(条码)字段支持", - "methods": [ - "stock.warehouse.import" - ], - "notes": [ - "新增 barcode(条码)字段支持,支持别名:条码、bar_code、barCode、barcodeList、barcode_list、barcode。", - "条码字段支持数组格式(如 [\"6901234567890\"])和分号分隔字符串格式(如 \"6901234567890;6901234567891\")。", - "新建和更新路径均已支持条码导入,条码写入 wms_stock_barcodes 表。", - "仅同步文档,不修改业务代码或实现。" - ], - "type": "updated" - }, - { - "version": "2026.06.10-system-05", - "date": "2026-06-10", - "summary": "stock.warehouse.import 的 barcode 字段分隔符改为逗号,对齐 stock.warehouse.export 导出格式;仅接收字符串格式,不再支持数组", - "methods": [ - "stock.warehouse.import" - ], - "notes": [ - "barcode 字段分隔符从分号 ; 改为逗号 ,", - "barcode 字段仅接收字符串格式,不再支持数组格式", - "格式示例:\"6901234567890,6901234567891\",与 stock.warehouse.export 导出格式一致" - ], - "type": "modified" - }, - { - "version": "2026.06.13-system-01", - "date": "2026-06-13", - "summary": "setting.warehouse 的 auto_outbound_rules 新增 require_print 和 require_pick 两个可选条件字段(同步代码实现)", - "methods": [ - "setting.warehouse.getSettings", - "setting.warehouse.saveSettings" - ], - "notes": [ - "在 getSettings 响应和 saveSettings 入参中补充 subject_config.auto_outbound_rules 对象的完整字段文档(enabled、require_recheck、require_pack、require_weigh、require_sync、require_print、require_pick)。", - "require_print:是否要求已打印(print_status=fin),默认 true。", - "require_pick:是否要求已拣货(pick_status=fin),默认 true。", - "该规则由自动出库定时任务 order_auto_outbound 消费,全部开启的条件均满足时自动标记待出库。" - ], - "type": "updated" - }, - { - "version": "2026.06.13-system-02", - "date": "2026-06-13", - "summary": "order.recheckOrder.scanOrder 团购模式响应新增 orders_detail 字段,暴露非拦截订单的详细列表(含 is_printed、is_reviewed 等状态字段)", - "methods": [ - "order.recheckOrder.scanOrder" - ], - "notes": [ - "团购模式(list_type='group')波次视图项新增 orders_detail 字段:非拦截订单详细列表,每项含 order_id、delivery_order_code、waybill_no、pick_status、is_printed(print_status === 'fin')、is_reviewed(recheck_status === 'fin')、recheck_status、shop_nick、items_count、wave_index、intercept_status", - "orders_detail 与现有 order_ids(纯数字 ID 数组)并存,均在团购模式的波次视图项中返回", - "orders_detail 仅在 list_type='group' 时返回,散单模式不受影响", - "同步更新 list 字段 description 以反映 group 模式新增的 order_ids、orders_detail、stocks 字段" - ], - "type": "updated" - }, - { - "version": "2026.06.13-system-03", - "date": "2026-06-13", - "summary": "新增批量快捷复核接口 batchQuickRecheck,支持批量订单 IDs 的前置条件检查(储位、快递、同步、拦截),自动完成拣货并标记复核,支持部分失败。拣货完成后同步更新 wms_wave_pick_task 状态", - "methods": [ - "order.recheckOrder.batchQuickRecheck" - ], - "notes": [ - "新增 order.recheckOrder.batchQuickRecheck 方法", - "入参 ids 支持数组或逗号分隔字符串", - "响应包含 success/failed 列表及计数,failed 项含 reason 说明" - ], - "details": { - "description": "包含拣货任务状态同步:全部拣完→任务状态=2(已完成),未全拣完→任务状态推进为1(拣货中)" - }, - "type": "added" - }, - { - "version": "2026.06.14-system-01", - "date": "2026-06-14", - "summary": "新增 order.bindExpressPackageMaterialByWaybill 方法:支持仅凭运单号绑定包材,无需传入订单ID", - "methods": [ - "order.bindExpressPackageMaterialByWaybill" - ], - "notes": [ - "新增 order.bindExpressPackageMaterialByWaybill 入参说明:waybill_code(运单号,必填)、package_material_code(包材编码,必填)。无需传入 order_id。", - "成功返回字段:order_id、waybill_code、package_material_id、package_material_name_snapshot、package_material_code。", - "错误码定义:400(参数错误)、404(运单号不存在 / 包材编码不存在)、500(绑定包材失败)。" - ], - "type": "added" - }, - { - "version": "2026.06.15-system-01", - "date": "2026-06-15", - "summary": "order.detail / order.deliveryOrder.detail 的 expresses 数组新增包材字段", - "methods": [ - "order.detail", - "order.deliveryOrder.detail" - ], - "notes": [ - "expresses 数组每个元素新增 package_material_id(包材ID,number|null)和 package_material_name_snapshot(包材名称快照,string|null)字段。" - ], - "type": "updated" - }, - { - "version": "2026.06.15-system-02", - "date": "2026-06-15", - "summary": "order.deliveryOrder.detail 的 expresses 数组新增包材字段", - "methods": [ - "order.deliveryOrder.detail" - ], - "notes": [ - "expresses 数组每个元素新增 package_material_id(包材ID,number|null)和 package_material_name_snapshot(包材名称快照,string|null)字段。" - ], - "type": "updated" - }, - { - "version": "2026.06.15-system-03", - "date": "2026-06-15", - "summary": "新增 setting.packageMaterial.search 方法:支持按关键字模糊搜索包材编码和名称", - "methods": [ - "setting.packageMaterial.search" - ], - "notes": [ - "新增 setting.packageMaterial.search 入参 keyword(可选),为空返回前 50 条启用中包材,有值时对 material_code 和 material_name 做模糊匹配。", - "返回包材数组,字段:id、material_code、material_name、material_type、spec、status。" - ], - "type": "added" - }, - { - "version": "2026.06.16-system-01", - "date": "2026-06-16", - "summary": "新增 order.recheckOrder.queryRecheckOrderSingleList:散单复核列表接口,响应新增 items_weight(总重量g)和 weight_type(重量类型)字段", - "methods": [ - "order.recheckOrder.queryRecheckOrderSingleList" - ], - "notes": [ - "新增方法 order.recheckOrder.queryRecheckOrderSingleList,为 recheckOrderList 散单模式的独立入口。", - "响应 list 每项新增字段 items_weight (DECIMAL(10,2)):订单总重量(g),来自 wms_order.items_weight,为 null 时返回 null。", - "响应 list 每项新增字段 weight_type (string):重量类型中文标签,来自 wms_order.weight_type 经 formatWeightTypeLabel 转换;取值:常规/轻货/重货/冷链(对应 DB 值 0/1/2/3)。" - ], - "type": "added", - "module": "order.recheckOrder" - }, - { - "version": "2026.06.16-system-02", - "date": "2026-06-16", - "summary": "为 order.wave.groupOrderFetchList / waveStrategyFallbackOrderList / singleOrderFetchList 响应新增 items_weight(总重量g)和 weight_type(重量类型)字段", - "methods": [ - "order.wave.groupOrderFetchList", - "order.wave.waveStrategyFallbackOrderList", - "order.wave.singleOrderFetchList" - ], - "notes": [ - "order.wave.groupOrderFetchList:响应 list 每项新增 items_weight (number|null):订单总重量(g),取组内首单 items_weight;组内订单 items_hash 相同重量一致。", - "order.wave.waveStrategyFallbackOrderList:响应 list 每项新增 items_weight (number|null):订单总重量(g),来自 wms_order.items_weight;新增 weight_type (string):重量类型中文标签,取值:常规/轻货/重货/冷链(对应 DB 值 0/1/2/3)。", - "order.wave.singleOrderFetchList:响应 list 每项新增 items_weight (number|null):订单总重量(g),取组内首单 items_weight;组内订单 items_hash 相同重量一致。", - "所有新增字段均为可选(required=false),为 null 时返回 null。" - ], - "type": "updated", - "module": "order.wave" - }, - { - "version": "2026.06.17-system-01", - "date": "2026-06-17", - "summary": "新增 order.pendingOrder.replenishmentDemand 分拣缺货补货需求计算接口文档", - "methods": [ - "order.pendingOrder.replenishmentDemand" - ], - "notes": [ - "新增分拣缺货补货需求计算方法,用于计算待处理订单的SKU在分拣区与存货区的库存分布及补货缺口", - "入参 order_ids/warehouse_id 均为可选;不传 order_ids 时自动查询当前仓库所有未完成储位分配的订单", - "纯只读查询接口,不修改任何数据", - "响应包含 list(明细)与 summary(汇总),其中 shortage = max(0, total_demand - pick_zone_quantity),replenishment_needed = min(shortage, storage_zone_quantity)" - ], - "type": "add", - "module": "order.pendingOrder" - }, - { - "version": "2026.06.17-system-02", - "date": "2026-06-17", - "type": "update", - "module": "order.pendingOrder", - "method": "order.pendingOrder.replenishmentDemand", - "description": "移除 order_ids 参数,改为纯仓库级别计算,自动查询当前仓库所有未完成储位分配的订单" - }, - { - "version": "2026.06.17-system-03", - "date": "2026-06-17", - "type": "update", - "module": "order.pendingOrder", - "method": "order.pendingOrder.replenishmentDemand", - "description": "新增 is_true_shortage 字段标识真正缺货(两区均无库存),summary 新增 total_true_shortage_skus 统计" - }, - { - "version": "2026.06.17-system-04", - "date": "2026-06-17", - "type": "migrate", - "module": "storage.management", - "summary": "从 order.pendingOrder.replenishmentDemand 迁移至 storage.management.replenishmentDemand(库存管理模块),原路径已删除,开发阶段无需兼容", - "methods": [ - "storage.management.replenishmentDemand" - ], - "notes": [ - "将 replenishmentDemand 接口从 order.pendingOrder 模块迁移到新建的 storage.management 库存管理模块。", - "旧条目 order.pendingOrder.replenishmentDemand 已从 order.pendingOrder 组中移除。", - "开发阶段无需兼容旧路径。" - ] - }, - { - "version": "2026.06.17-system-05", - "date": "2026-06-17", - "type": "update", - "module": "storage.management", - "summary": "storage.management.replenishmentDemand 移除 warehouse_id 入参,仓库ID改为纯从用户上下文(ctx.user)获取,接口无需入参", - "methods": [ - "storage.management.replenishmentDemand" - ], - "notes": [ - "移除 warehouse_id 入参,仓库ID改为纯从用户上下文(ctx.user)获取,接口无需入参" - ] - }, - { - "version": "2026.06.17-system-06", - "date": "2026-06-17", - "type": "update", - "module": "storage.management", - "method": "storage.management.replenishmentDemand", - "description": "新增分页入参(pagination)、排序入参(sort,默认按 shortage DESC)、响应新增 replenishment_locations(存货区可补货库位,最多5条)、响应新增 pagination 分页信息" - }, - { - "version": "2026.06.17-system-07", - "date": "2026-06-17", - "type": "update", - "module": "storage.management", - "summary": "replenishment_locations 新增 space_name 字段,优先取自定义名称(custom_name),无则回退库位编码(space_code)", - "methods": [ - "storage.management.replenishmentDemand" - ], - "notes": [ - "在 replenishment_locations.children 中新增 space_name 字段(string, required),放在 space_code 之后、available_quantity 之前。", - "space_name 取值逻辑:优先使用库位自定义名称 custom_name,若无自定义名称则回退为库位编码 space_code。" - ] - }, - { - "version": "2026.06.17-system-08", - "date": "2026-06-17", - "type": "update", - "module": "storage.management", - "summary": "合并 is_sufficient 和 is_true_shortage 为 replenishment_status 枚举字段(replenishable/true_shortage)", - "methods": [ - "storage.management.replenishmentDemand" - ], - "notes": [ - "删除 is_sufficient(boolean)和 is_true_shortage(boolean)两个字段。", - "新增 replenishment_status(string)枚举字段:replenishable=存货区足够覆盖缺口,移库可解决;true_shortage=存货区不足以覆盖缺口或两区均无库存,需采购。" - ] - }, - { - "version": "2026.06.18-system-01", - "date": "2026-06-18", - "summary": "入库单完成后异步匹配收货单并回传:completeEntry / entryorderConfirm 入库完成时自动匹配收货单,明细一致则按来源回传(奇门/OpenAPI),覆盖场景标记收货单部分入库;completeReceiving 完成后清除收货单缓存", - "methods": [ - "storage.entry.completeEntry", - "storage.receiving.completeReceiving" - ], - "notes": [ - "新增 app/service/systems/receiving_entry_match.js:入库单完成后异步匹配收货单并回传的核心服务,含 Redis 缓存收货单列表(TTL 300s)、remark 匹配收货单号、明细对比、奇门回传、OpenAPI 回调、部分入库标记等能力。", - "storage.entry.completeEntry 完成后通过 setImmediate 异步触发 matchAfterEntryCompleted,不阻塞主流程。", - "entry_order.js entryorderConfirm() 事务提交后(isFin 最终完成)同样异步触发匹配。", - "storage.receiving.completeReceiving 完成后清除收货单 Redis 缓存(cache:receiving_orders:warehouse:{warehouseId}),确保下次匹配获取最新收货单列表。", - "匹配规则:入库单 remark 包含收货单号 → 对比 SKU+数量 → 完全一致回传 / 收货单覆盖标记部分入库 / 其他不处理。", - "回传路径:source_type=QM → 奇门 taobao.qimen.entryorder.confirm;source_type=API → OpenAPI 回调(entry_order_receiving_matched 事件)。" - ], - "type": "updated" - }, - { - "version": "2026.06.18-system-02", - "date": "2026-06-18", - "summary": "新增 storage.receiving.manualMatchEntryOrder 接口", - "methods": [ - "storage.receiving.manualMatchEntryOrder" - ], - "notes": [ - "新增 storage.receiving.manualMatchEntryOrder:手动匹配入库单与收货单,传入 receivingId 和 entryOrderId,复用异步匹配服务的明细对比和回传逻辑,同步返回匹配结果", - "参数:receivingId (number, 必填)、entryOrderId (number, 必填)", - "校验:入库单存在性、收货单存在性、同仓库校验", - "返回 matchType (full_match/receiving_covers_entry/entry_exceeds_receiving/no_match)、comparisonResult、callbackSent、callbackResult、partialStorageMarked、entryOrder、receivingOrder" - ], - "type": "added", - "module": "storage" - }, - { - "version": "2026.06.18-system-03", - "date": "2026-06-18", - "summary": "新增 storage.receiving.getAvailableInboundQuantity 接口:按 stock_id 查询已审核收货单的可入库数量(actual_quantity - stored_quantity),排除未审核和已取消的收货单", - "methods": [ - "storage.receiving.getAvailableInboundQuantity" - ], - "notes": [ - "新增 system method:storage.receiving.getAvailableInboundQuantity,按 stock_id 查询已审核收货单中各明细的可入库数量(actual_quantity - stored_quantity),仅返回尚有可入库余量的明细。", - "实现文件:app/service/systemMethods/storage/receiving.js(包装层)、app/service/systems/storage/receiving.js(业务层)。", - "接口无需鉴权(isNeedAuth=false),但需要登录(isNeedLogin=true)。", - "入参 stock_id 为必填,对应 stock_warehouse.id;服务端从 ctx.user.store_id 获取仓库上下文。" - ], - "type": "added", - "module": "storage" - }, - { - "version": "2026.06.18-system-04", - "date": "2026-06-18", - "summary": "新增 storage.entry.bindReceivingDetails 接口和 wms_entry_receiving_binding 中间表:入库单明细可显式绑定收货明细(pending状态),提交入库时事务内完成双向扣减(stored_quantity/received_quantity),通过唯一约束和行锁防止超分和重复绑定。同时重构 completeEntry 调用链为 commitEntryWithBindings,无绑定时向后兼容。", - "methods": [ - "storage.entry.bindReceivingDetails", - "storage.entry.completeEntry" - ], - "notes": [ - "新增 storage.entry.bindReceivingDetails 方法:入库单明细绑定收货明细,pending 状态软绑定,每次调用清除旧 pending 绑定后创建新绑定。", - "新增 wms_entry_receiving_binding 中间表(migration: 20260618150000-create-wms-entry-receiving-binding.js),用于记录入库明细与收货明细的绑定关系。", - "重构 completeEntry 调用链:systemMethods 层 completeEntry 改为调用 commitEntryWithBindings,有绑定则事务内完成双向扣减(stored_quantity/received_quantity),无绑定时向后兼容仅变更入库单状态。", - "通过数据库唯一约束和行锁(SELECT ... FOR UPDATE)防止超分和重复绑定。", - "涉及文件: app/model/entry_receiving_binding.js, app/service/systems/storage/entry.js, app/service/systemMethods/storage/entry.js, database/migrations/20260618150000-create-wms-entry-receiving-binding.js" - ], - "type": "added", - "module": "storage.entry" - }, - { - "version": "2026.06.18-system-05", - "date": "2026-06-18", - "summary": "storage.entry.get 响应追加 pending_total/total_planned/bindings 字段,storage.receiving.getAvailableInboundQuantity 响应追加 pending_allocated_quantity 字段:前端可通过 get 查看入库明细的绑定状态,getAvailableInboundQuantity 的可用量已扣除全局 pending 绑定总量", - "methods": [ - "storage.entry.get", - "storage.receiving.getAvailableInboundQuantity" - ], - "notes": [ - "storage.entry.get:items 数组每项新增 pending_total(该入库明细当前 pending 绑定的总预分配数量)、total_planned(计划入库数量=count)、bindings(pending 绑定列表,每项含 id/entry_item_id/receiving_detail_id/allocated_quantity/status/receivingDetail 子对象)", - "storage.receiving.getAvailableInboundQuantity:list 每项新增 pending_allocated_quantity(该收货明细在当前 stock_id 所有入库单中的 pending 绑定总量),available_quantity 计算已扣除该值" - ], - "type": "updated" - }, - { - "version": "2026.06.18-system-06", - "date": "2026-06-18", - "summary": "bindReceivingDetails 重构为\"绑定即实收\"(received_quantity 在绑定时更新,不再等到 completeEntry),新增 unbindReceivingDetails 解绑接口(删除 pending 绑定并回退 received_quantity),commitEntryWithBindings 移除 received_quantity 更新逻辑", - "methods": [ - "storage.entry.bindReceivingDetails", - "storage.entry.unbindReceivingDetails", - "storage.entry.completeEntry" - ], - "notes": [ - "storage.entry.bindReceivingDetails:改为绑定即实收,绑定成功后立即更新入库明细 received_quantity;重复调用时先回退旧绑定量再创建新绑定,避免重复累加。", - "storage.entry.unbindReceivingDetails:新增解绑接口,删除该入库明细的所有 pending 绑定记录,并将 received_quantity 回退到绑定前的值;收货明细可用数量随绑定记录删除自动恢复。", - "storage.entry.completeEntry:commitEntryWithBindings 中移除 received_quantity 更新逻辑(received_quantity 已在绑定时更新,completeEntry 仅完成收货单侧入库数量扣减和库存上架)。" - ], - "type": "updated" - }, - { - "version": "2026.06.19-system-01", - "date": "2026-06-19", - "summary": "order.recheckOrder.scanOrder 响应 list[] 新增 items_weight(订单商品总重量g)和 suggested_package_material(推荐包材)字段", - "methods": [ - "order.recheckOrder.scanOrder" - ], - "notes": [ - "响应 list 每项新增 items_weight (number|null):订单商品总重量(g),来源于 wms_order_delivery.items_weight。散单模式每个订单对象包含,团购模式每个波次对象包含(取波次内首个正常订单的重量,为 null 时返回 0)。", - "响应 list 每项新增 suggested_package_material (object|null):推荐包材信息,根据订单商品结构(items_hash + items_crc)匹配 wms_package_material_item_relation 历史绑定记录,按 bind_count 降序取最优匹配。若 items_hash 为空或无匹配记录则为 null。包含子字段:id、code、name、spec、type、weight、length、width、height、bind_count。", - "同步更新 method description 和 list 字段 description,补充新增字段的说明。" - ], - "type": "updated", - "module": "order.recheckOrder" - }, - { - "version": "2026.06.21-system-01", - "date": "2026-06-21", - "summary": "order.bindExpressPackageMaterialByWaybill:入参 package_material_code 改为 package_material_id,类型由 string 改为 number|string", - "methods": [ - "order.bindExpressPackageMaterialByWaybill" - ], - "notes": [ - "入参字段名从 package_material_code 改为 package_material_id。", - "入参类型从 string 改为 number|string,与代码 normalizePackageMaterialId 的实现一致。", - "同步更新该方法 description 中'包材编码'为'包材ID'。" - ], - "type": "updated", - "module": "order" - }, - { - "version": "2026.06.21-system-comboGoods-01", - "date": "2026-06-21", - "summary": "新增 comboGoods 组合商品模块 5 个接口文档:list/create/update/delete/search", - "methods": [ - "comboGoods.list", - "comboGoods.create", - "comboGoods.update", - "comboGoods.delete", - "comboGoods.search" - ], - "notes": [ - "comboGoods.list:组合商品列表查询(分页),支持按 combo_code/combo_name/status/warehouse_id 筛选,返回含 simpleNotation 和 nameNotation 简记字段", - "comboGoods.create:创建组合商品(含明细一次性提交),校验 combo_code 唯一性、子商品有效性和货主一致性,事务保证原子写入", - "comboGoods.update:编辑组合商品(含明细替换),支持部分字段更新,传入 items 则先删旧明细再插入新明细", - "comboGoods.delete:软删除组合商品(status 置为 0)", - "comboGoods.search:关键字搜索组合商品,模糊匹配 combo_code 或 combo_name,仅返回启用状态记录,上限100条", - "数据表:wms_combo_goods(主表)+ wms_combo_goods_item(明细表);子商品校验依赖 wms_stock_warehouse 表", - "代码文件:app/service/systems/comboGoods.js(业务逻辑层)+ app/service/systemMethods/comboGoods.js(接口包装层)", - "isNeedAuth:list/search 无需鉴权,create/update/delete 需要鉴权" - ], - "type": "added", - "module": "comboGoods" - }, - { - "version": "2026.06.21-system-comboGoods-02", - "date": "2026-06-21", - "summary": "comboGoods 模块新增 custom_code(自定义编码)功能:create/update 支持传入 custom_code 并校验按货主唯一,list/search 返回新增 custom_code 字段,search 搜索范围扩展至 custom_code 且优先排列匹配项", - "methods": [ - "comboGoods.list", - "comboGoods.create", - "comboGoods.update", - "comboGoods.search" - ], - "notes": [ - "新增字段 custom_code(VARCHAR(64) NULL),仅做按货主唯一性校验(排除已删除记录),非全局唯一。", - "wms_combo_goods 表新增索引 uk_store_custom_code(warehouse_id, custom_code)。", - "comboGoods.create:新增可选入参 custom_code,如果非空则校验同货主非删除记录中 unique;返回新增 custom_code 字段。", - "comboGoods.update:新增可选入参 custom_code,如果非空则校验同货主非删除记录中 unique(排除自身 id)。", - "comboGoods.list:返回每条记录新增 custom_code 字段。", - "comboGoods.search:搜索条件扩大为 custom_code LIKE / combo_code LIKE / combo_name LIKE,custom_code 匹配项按 ORDER BY CASE 排在前面;返回新增 custom_code 字段。" - ], - "type": "updated" - }, - { - "version": "2026.06.21-system-comboGoods-03", - "date": "2026-06-21", - "summary": "stock.warehouse.search 新增 mode=\"combo\" 组合商品查询模式,新增 id/custom_code 参数,补充组合商品响应结构", - "methods": [ - "stock.warehouse.search" - ], - "notes": [ - "新增入参 mode(查询模式,传 \"combo\" 时搜索组合商品),id(mode=combo 时按组合商品ID精确查询),custom_code(mode=combo 时按自定义编码模糊查询)", - "原有 keyword 参数在 mode=combo 时模糊匹配 combo_code / combo_name / custom_code", - "mode=combo 响应结构新增 combo_code、combo_name、custom_code、items(子商品数组含 item_goods_sku_id/item_quantity)、simpleNotation(stock_id|数量格式)、nameNotation(【数量】商品名称格式)", - "mode=combo 时不返回 stock 模式特有的字段(item_code/goods_code/item_name/sku_property/stock_unit/quantity/locked_quantity/brand_name/item_type/barcodes/store_stock/效期字段/storage)", - "with_stock 和 is_batch 参数在 mode=combo 时不生效" - ], - "type": "updated" - }, - { - "version": "2026.06.22-system-wavePickTaskList-01", - "date": "2026-06-22", - "summary": "order.wave.wavePickTaskList 响应新增 wave_list 数组:每个拣货任务返回关联波次列表", - "methods": [ - "order.wave.wavePickTaskList" - ], - "notes": [ - "wavePickTaskList 响应 list 每项新增 wave_list 数组字段,通过批量查询 wms_wave_pick_task_wave 表获取关联波次详情。", - "wave_list 每项包含:wave_id(波次ID)、wave_no(波次号)、box_no(框号)、status(波次关联状态)、bind_time(绑定时间)、pick_time(拣货完成时间)。", - "无需额外入参,默认对所有拣货任务返回 wave_list;查询为空时返回空数组 []。", - "同步更新 methods/system.json 响应文档。" - ], - "type": "updated", - "module": "order.wave" - }, - { - "version": "2026.06.22-system-order-export-mode-01", - "date": "2026-06-22", - "summary": "order.export 新增 export_mode 参数:支持 waybill(默认,按运单展开)与 item(按商品明细展开)两种导出模式", - "methods": [ - "order.export" - ], - "notes": [ - "新增入参 export_mode/exportMode,枚举值:waybill(默认)— 按运单号展开,每运单一组,items_detail 列汇总商品;item — 按商品明细展开,每商品一行,运单信息汇总填充。", - "方法层(OrderIndexService.export)新增 export_mode/exportMode 解构并透传到 systems.orderExport.exportOrders。", - "同步更新 methods/system.json 文档:description 补充 export_mode 说明,params 新增 export_mode/exportMode 条目。", - "order.export 导出的列新增:业务类型、运单接口、包材ID、包材编码、包材名称。" - ], - "type": "updated", - "module": "order.index" - }, - { - "version": "2026.06.22-system-directInbound-01", - "date": "2026-06-22", - "summary": "新增 storage.directInbound 导入/PDA直接入库模块:getItems(获取入库信息)、addItem(增量添加商品)、commit(提交完成入库并回传)", - "methods": [ - "storage.directInbound.getItems", - "storage.directInbound.addItem", - "storage.directInbound.commit" - ], - "notes": [ - "新增 storage.directInbound 模块,用于非收货单途径的导入/PDA 直接入库场景。", - "storage.directInbound.getItems:根据入库单号获取入库明细及已有的导入/PDA 入库记录,返回每项的可入库余量。", - "storage.directInbound.addItem:按 stock_id 增量添加导入/PDA 入库记录,累加超过该 stock_id 在入库单中的计划总量时拒绝。支持 import(导入)和 pda(PDA)两种方式。", - "storage.directInbound.commit:提交确认完成入库,按实收数量写入 wms_storage 库存和 wms_storage_transaction 流水,同 stock_id 多条明细只写一次库存,更新入库单状态为 COMPLETED 并同步 sync_status=SUCCESS,异步触发奇门/API 回传(按实收数量回传)。不足量提交时未入库商品跳过。", - "新增数据表 wms_inbound_direct_log(migration: 20260622100000-create-wms-inbound-direct-log.js):记录非收货单途径入库操作,含 warehouse_id、stock_id、quantity、inbound_type(import/pda)、entry_order_id、operator 等字段。模型文件:app/model/inbound_direct_log.js。", - "新增操作日志:addItem 记录 DIRECT_INBOUND_ADD(异步),commit 记录 DIRECT_INBOUND_COMMIT(事务内)。commit 响应返回 order_status=COMPLETED 和 sync_status=SUCCESS。", - "涉及文件:app/service/systems/inbound_direct_log.js(业务层)、app/service/systemMethods/storage/direct_inbound.js(包装层)、app/model/inbound_direct_log.js、database/migrations/20260622100000-create-wms-inbound-direct-log.js、methods/system.json(新增导入/PDA入库模块)。", - "E2E 测试:test/e2e_direct_inbound.test.js(53项断言全覆盖)。" - ], - "type": "added", - "module": "storage.directInbound" - }, - { - "version": "2026.06.22-system-directInbound-02", - "date": "2026-06-22", - "summary": "storage.directInbound.addItem 新增批量模式(items 数组),getItems 响应 summary 新增 total_import/total_pda 分类型汇总", - "methods": [ - "storage.directInbound.addItem", - "storage.directInbound.getItems" - ], - "notes": [ - "addItem 新增批量模式:支持传入 items 数组一次添加多条商品,每项含 stock_id/quantity/inbound_type/remark。单条模式(stock_id/quantity/inbound_type 顶层字段)保持向后兼容。批量模式下所有商品共享同一个入库单状态校验,任一商品校验失败整批拒绝。", - "addItem 批量模式响应结构:{ count, total_quantity, items: [...] },items 每项含 id/stock_id/quantity/inbound_type/plan_quantity/existing_before/existing_after/remaining。", - "getItems 响应 summary 新增 total_import(导入入库总数)和 total_pda(PDA入库总数)字段。", - "同步更新 methods/system.json 文档。" - ], - "type": "updated", - "module": "storage.directInbound" - }, - { - "version": "2026.06.22-system-directInbound-03", - "date": "2026-06-22", - "summary": "storage.directInbound 新增 space_id 库位支持:addItem 支持传入 space_id(单条和批量),commit 从入库记录取 space_id 写入 wms_storage 替代硬编码 1", - "methods": [ - "storage.directInbound.addItem", - "storage.directInbound.commit", - "storage.directInbound.getItems" - ], - "notes": [ - "addItem 新增可选入参 space_id(单条模式顶层字段 / 批量模式 items[].space_id),指定存放库位ID,关联 wms_location_space.id。", - "wms_inbound_direct_log 表新增 space_id 字段(migration: 20260622110000-add-space-id-to-wms-inbound-direct-log.js)。", - "commit 从入库记录中取第一个非空 space_id 写入 wms_storage,无记录时兜底使用库位 1。", - "getItems 响应中 direct_logs 每条记录包含 space_id 字段。", - "同步更新 methods/system.json 文档及模型文件。" - ], - "type": "updated", - "module": "storage.directInbound" - }, - { - "version": "2026.06.23-system-01", - "date": "2026-06-23", - "summary": "入库单(wms_entry_order)新增 CREATED 状态:order_status ENUM 从 CREATING/PENDING/CONFIRMED/PARTIAL_RECEIVED/COMPLETED/CANCELLED 扩展为 CREATING/CREATED/PENDING/CONFIRMED/PARTIAL_RECEIVED/COMPLETED/CANCELLED;默认值从 PENDING 变更为 CREATED;validTransitions 增加 CREATED 节点(CREATED→PENDING/CANCELLED,CREATING→CREATED/CANCELLED)", - "methods": [ - "storage.entry.list", - "storage.entry.get", - "storage.entry.cancel", - "storage.entry.completeEntry", - "storage.entry.bindReceivingDetails" - ], - "notes": [ - "Model 层:app/model/entry_order.js order_status ENUM 新增 CREATED,默认值从 PENDING 变更为 CREATED", - "Service 层:app/service/systems/entry_order.js addOrder 创建后状态从 CREATING→CREATED,validTransitions 增加 CREATED 节点", - "Service 层:app/service/systems/storage/entry.js createEntry 默认状态 PENDING→CREATED", - "Service 层:app/service/systems/storage/inventory.js 快捷入库默认 CREATED", - "文档同步:storage.entry.list where.order_status 枚举补充 CREATED;storage.entry.get description 补充 order_status 枚举含 CREATED;storage.entry.cancel 补充 CREATED 可作废说明;storage.entry.completeEntry/bindReceivingDetails 补充可操作状态含 CREATED" - ], - "type": "updated", - "module": "storage.entry" - }, - { - "version": "2026.06.23-system-02", - "date": "2026-06-23", - "summary": "入库单 CREATED 状态限制:CREATED 状态不允许绑定货物和完成入库,仅 PENDING/CONFIRMED/PARTIAL_RECEIVED 状态可操作", - "methods": [ - "storage.entry.cancel", - "storage.entry.completeEntry", - "storage.entry.bindReceivingDetails", - "storage.entry.unbindReceivingDetails" - ], - "notes": [ - "completeEntry / bindReceivingDetails / unbindReceivingDetails / commitEntryWithBindings 的可操作状态从原来的白名单(包含 CREATED)改为 PENDING / CONFIRMED / PARTIAL_RECEIVED,排除 CREATED。", - "CREATED 状态仅允许确认入库(→PENDING)或作废(→CANCELLED)。", - "storage.entry.cancel 补充明确 COMPLETED 状态不可作废,CREATED 可作废。", - "同步更新对应 method 的 description、errors 描述。" - ], - "type": "updated", - "module": "storage.entry" - }, - { - "version": "2026.06.23-system-03", - "date": "2026-06-23", - "summary": "storage.entry.cancel:CONFIRMED(已确认)状态不再允许作废,仅 CREATED 和 PENDING 可作废", - "methods": [ - "storage.entry.cancel" - ], - "notes": [ - "canCancel() 白名单移除 CONFIRMED,仅保留 CREATED 和 PENDING", - "validTransitions 中 CONFIRMED 不再可转为 CANCELLED", - "cancel() 方法新增 CONFIRMED 状态拦截,返回 400:已确认入库单不允许作废,请先完成收货", - "PARTIAL_RECEIVED 仍可作废,COMPLETED 不允许作废(行为不变)", - "更新 description 明确各状态可作废规则,errors 中补充 CONFIRMED 不可作废的说明" - ], - "type": "updated", - "module": "storage.entry" - }, - { - "version": "2026.06.23-system-04", - "date": "2026-06-23", - "summary": "入库单状态从 7 个简化为 5 个:移除 CONFIRMED 和 PARTIAL_RECEIVED,最终状态为 CREATING/CREATED/PENDING/COMPLETED/CANCELLED;同步更新 storage.entry 所有 method 的状态枚举和错误信息描述", - "methods": [ - "storage.entry.list", - "storage.entry.get", - "storage.entry.cancel", - "storage.entry.completeEntry", - "storage.entry.bindReceivingDetails", - "storage.entry.unbindReceivingDetails" - ], - "notes": [ - "wms_entry_order.order_status ENUM 从 CREATING/CREATED/PENDING/CONFIRMED/PARTIAL_RECEIVED/COMPLETED/CANCELLED 简化为 CREATING/CREATED/PENDING/COMPLETED/CANCELLED", - "storage.entry.list: where.order_status 描述和 where 参数描述中的状态枚举同步更新", - "storage.entry.get: entryOrder.order_status 描述同步更新", - "storage.entry.cancel: 移除 PARTIAL_RECEIVED 可作废和 CONFIRMED 不可作废的描述,仅保留 CREATED 和 PENDING 可作废,COMPLETED 不可作废", - "storage.entry.completeEntry: 可完成状态从 PENDING/CONFIRMED/PARTIAL_RECEIVED 改为仅 PENDING", - "storage.entry.bindReceivingDetails: 可操作状态从 PENDING/CONFIRMED/PARTIAL_RECEIVED 改为仅 PENDING", - "storage.entry.unbindReceivingDetails: 可操作状态从 PENDING/CONFIRMED/PARTIAL_RECEIVED 改为仅 PENDING", - "cancel() 取消 CONFIRMED 状态拦截(状态已不存在),COMPLETED 拦截保持不变" - ], - "type": "updated" - }, - { - "version": "2026.06.23-system-05", - "date": "2026-06-23", - "summary": "入库单状态语义调整:CREATED=已创建待审核,PENDING=已审核;同步更新 storage.entry 所有 method 的 description 中状态说明", - "methods": [ - "storage.entry.list", - "storage.entry.get", - "storage.entry.cancel", - "storage.entry.completeEntry", - "storage.entry.bindReceivingDetails", - "storage.entry.unbindReceivingDetails" - ], - "notes": [ - "CREATED 含义从\"已创建\"改为\"已创建待审核\"(需审核后才能绑定和完成入库)", - "PENDING 含义从\"待收货/收货中\"改为\"已审核\"(审核通过,可绑定和完成入库)", - "CREATED→PENDING 步骤语义:绑定审核", - "addOrder() 新增可选参数 autoReview(boolean,默认 false),false 创建后状态 CREATED(需审核),true 创建后状态 PENDING(自动审核通过)", - "快捷入库 quickPutaway 内部流程改为调用 addOrder({autoReview:true}) → bindReceivingDetails → commitEntryWithBindings,不再直接写库存,对外返回格式不变", - "storage.entry.list / storage.entry.get description 中补充 CREATED/PENDING 语义说明", - "storage.entry.cancel description 中补充可作废状态说明", - "storage.entry.completeEntry description 中补充可完成状态说明", - "storage.entry.bindReceivingDetails / storage.entry.unbindReceivingDetails description 中补充可绑定/解绑状态说明" - ], - "type": "updated" - }, - { - "version": "2026.06.23-system-06", - "date": "2026-06-23", - "summary": "storage.inventory.quickPutaway description 更新:补充内部已改为走 addOrder→bind→commit 链路,不再直接写库存", - "methods": [ - "storage.inventory.quickPutaway" - ], - "notes": [ - "快捷入库 quickPutaway 内部流程改为调用 addOrder({autoReview:true}) → bindReceivingDetails → commitEntryWithBindings,不再直接写库存,外部返回格式不变", - "description 中补充内部调用链路说明" - ], - "type": "updated" - }, - { - "version": "2026.06.23-system-07", - "date": "2026-06-23", - "summary": "storage.entry 大范围清理:删除 bindReceivingDetails/unbindReceivingDetails(明细级绑定已弃用),更新 completeEntry 为纯状态变更(不再做库存写入/异步匹配)", - "methods": [ - "storage.entry.bindReceivingDetails", - "storage.entry.unbindReceivingDetails", - "storage.entry.completeEntry" - ], - "notes": [ - "storage.entry.bindReceivingDetails:已从代码中删除,明细级绑定收货单功能下线。库存写入统一由 storage.inventory.matchPutaway 完成。", - "storage.entry.unbindReceivingDetails:已从代码中删除,明细级解绑功能下线。", - "storage.entry.completeEntry:改为纯状态变更(PENDING → COMPLETED),不再做库存写入和异步匹配回调。库存写入统一由 storage.inventory.matchPutaway 完成。" - ], - "type": "updated" - }, - { - "version": "2026.06.23-system-08", - "date": "2026-06-23", - "summary": "storage.inventory 清理:删除 quickPutaway(快捷入库已下线,统一由 matchPutaway 完成匹配入库)", - "methods": [ - "storage.inventory.quickPutaway" - ], - "notes": [ - "storage.inventory.quickPutaway:已从代码中删除,快捷入库功能下线。请使用 storage.inventory.matchPutaway 替代。" - ], - "type": "removed" - }, - { - "version": "2026.06.23-system-09", - "date": "2026-06-23", - "summary": "入库流程弃用清理:bindReceivingDetails/unbindReceivingDetails 标记为已删除并补充弃用原因,completeEntry 明确不涉及库存写入", - "methods": [ - "storage.entry.bindReceivingDetails", - "storage.entry.unbindReceivingDetails", - "storage.entry.completeEntry" - ], - "notes": [ - "storage.entry.bindReceivingDetails 与 storage.entry.unbindReceivingDetails 已从代码中移除,入库单与收货单关系改为 wms_entry_order_receiving 主表级关联,不再需要逐明细绑定/解绑。", - "wms_entry_receiving_binding 表不再写入新数据。", - "storage.entry.completeEntry 仅做状态变更(PENDING→COMPLETED),库存写入统一由 storage.inventory.matchPutaway 完成。", - "commitEntryWithBindings(内部方法)不再使用,库存写入统一走 matchPutaway 链路。" - ], - "type": "updated" - }, - { - "version": "2026.06.23-system-10", - "date": "2026-06-23", - "summary": "quickPutaway 弃用说明完善:明确替代方案为 matchPutaway;matchPutaway 标明为目前唯一库存写入入库链路", - "methods": [ - "storage.inventory.quickPutaway", - "storage.inventory.matchPutaway" - ], - "notes": [ - "storage.inventory.quickPutaway 已从代码中移除,替代方案为 storage.inventory.matchPutaway(支持多收货单+多入库单批量匹配入库)。", - "storage.inventory.matchPutaway 是目前唯一的库存写入入库链路,入库单状态变更由 storage.entry.completeEntry 单独处理。", - "本次为文档补充说明,不涉及代码变更。" - ], - "type": "updated" - }, - { - "version": "2026.06.23-system-11", - "date": "2026-06-23", - "summary": "删除 storage.receiving.getAvailableInboundQuantity:该方法依赖已弃用的 wms_entry_receiving_binding 明细绑定表,已从代码中移除", - "methods": [ - "storage.receiving.getAvailableInboundQuantity" - ], - "notes": [ - "该方法原用于按 stock_id 查询已审核收货单中各明细的可入库数量(actual_quantity - stored_quantity - pending_allocated_quantity)。", - "由于 wms_entry_receiving_binding 明细绑定表已弃用,入库单与收货单的关联改为通过 wms_entry_order_receiving 主表级关联,该查询方法不再适用。", - "替代方案:使用 storage.entry.get 查询入库单详情,通过顶层 receivingBindings 获取关联的收货单信息。" - ], - "type": "removed" - }, - { - "version": "2026.06.23-system-12", - "date": "2026-06-23", - "summary": "storage.entry.get 响应结构变更:不再返回 items[].bindings(明细级绑定),改为返回顶层 receivingBindings(主表级关联收货单信息)", - "methods": [ - "storage.entry.get" - ], - "notes": [ - "移除 items[].bindings(明细级绑定,原基于 wms_entry_receiving_binding 表),该绑定表已弃用。", - "新增顶层 receivingBindings(wms_entry_order_receiving 主表级关联),每项含 id/receiving_id/receiving(含 id/receiving_number/status/storage_status/created_at)。", - "items 中保留 external_item_code/external_item_id/warehouse_item_code/warehouse_item_name/warehouse_item_spec 等扁平化字段。", - "响应结构变更与 storage.directInbound.getItems 的返回结构对齐,后者同样使用顶层 receivingBindings。" - ], - "type": "modified" - }, - { - "version": "2026.06.23-system-13", - "date": "2026-06-23", - "summary": "新增 storage.entry.* 下 4 个 DirectInbound 方法:getDirectInboundItems、addItem、commit、removeItem,原 storage.directInbound.* 方法保留向后兼容并标记 deprecated", - "methods": [ - "storage.entry.getDirectInboundItems", - "storage.entry.addItem", - "storage.entry.commit", - "storage.entry.removeItem" - ], - "notes": [ - "storage.entry.getDirectInboundItems:获取入库单的导入/PDA 入库信息,参数与响应格式同原 storage.directInbound.getItems", - "storage.entry.addItem:按商品增量添加导入/PDA 入库记录(支持单条和批量),参数与响应格式同原 storage.directInbound.addItem", - "storage.entry.commit:提交确认完成导入/PDA 入库,按实收数量写入库存并异步回传奇门/API,参数与响应格式同原 storage.directInbound.commit", - "storage.entry.removeItem:移除一条导入/PDA 入库记录,参数与响应格式同原 storage.directInbound.removeItem", - "底层 inbound_direct_log.js 实现不变,仅入口从 storage.directInbound 模块迁入 storage.entry 模块" - ], - "type": "added" - }, - { - "version": "2026.06.23-system-14", - "date": "2026-06-23", - "summary": "storage.directInbound.* 下 4 个方法标记 deprecated,指向 storage.entry.* 下对应新方法", - "methods": [ - "storage.directInbound.getItems", - "storage.directInbound.addItem", - "storage.directInbound.commit", - "storage.directInbound.removeItem" - ], - "notes": [ - "storage.directInbound.getItems → 替代方法 storage.entry.getDirectInboundItems", - "storage.directInbound.addItem → 替代方法 storage.entry.addItem", - "storage.directInbound.commit → 替代方法 storage.entry.commit", - "storage.directInbound.removeItem → 替代方法 storage.entry.removeItem", - "旧方法保留向后兼容,参数与响应格式不变,仅入口模块变更" - ], - "type": "deprecated" - }, - { - "version": "2026.06.23-system-15", - "date": "2026-06-23", - "summary": "storage.inventory.matchPutaway 标记 deprecated,替代方案为 storage.entry.commit", - "methods": [ - "storage.inventory.matchPutaway" - ], - "notes": [ - "storage.inventory.matchPutaway 已弃用,请迁移至 storage.entry.commit", - "commit 提供导入/PDA 入库完成确认功能,按实收数量写入库存并异步回传" - ], - "type": "deprecated" - }, - { - "version": "2026.06.23-system-16", - "date": "2026-06-23", - "summary": "清理已弃用 method 条目:从 system.json 删除 storage.entry.bindReceivingDetails、storage.entry.unbindReceivingDetails、storage.inventory.matchPutaway 三个已从代码中移除的 method 文档条目", - "methods": [ - "storage.entry.bindReceivingDetails", - "storage.entry.unbindReceivingDetails", - "storage.inventory.matchPutaway" - ], - "notes": [ - "storage.entry.bindReceivingDetails:已从代码中删除,明细级绑定收货单功能下线。入库单与收货单关系改为 wms_entry_order_receiving 主表级关联。", - "storage.entry.unbindReceivingDetails:已从代码中删除,明细级解绑功能下线。", - "storage.inventory.matchPutaway:已从代码中删除,匹配入库功能下线。替代方案为 storage.entry.commit。", - "storage.inventory.quickPutaway:之前已标记 [已删除],本次确认条目保留(与 matchPutaway 同一 group,保留作为历史参考)。", - "storage.entry.create / addDetail / deleteDetail / detailChange:systems 层方法已删除,但从未在 system.json 中暴露为 API method,无需文档变更。" - ], - "type": "removed" - }, - { - "version": "2026.06.23-system-17", - "date": "2026-06-23", - "summary": "storage.entry.get 响应新增仓库库存、条码、入库进度字段", - "methods": [ - "storage.entry.get" - ], - "notes": [ - "items 每项新增 warehouse_quantity(仓库库存总量)、warehouse_locked_quantity(锁定数量)、warehouse_is_batch_mgmt(是否批次管理)、warehouse_is_shelf_life_mgmt(是否效期管理)、warehouse_image_url(商品图片URL)、warehouse_is_images(是否有图片)", - "items 每项新增 barcodes(条码列表,每项含 id/barcode/sku_property)", - "items 每项新增 direct_inbound_quantity(导入/PDA已入库数量)、remaining_quantity(剩余可入库数量)", - "同步更新 response 字段定义,将原有概要描述展开为逐字段说明", - "仅文档同步,不改业务代码" - ], - "type": "updated", - "module": "storage.entry" - }, - { - "version": "2026.06.24-system-01", - "date": "2026-06-24", - "summary": "新增批量绑定入库单明细与收货单明细接口 storage.entry.bindReceivingDetails,支持明细级数量分配与部分成功", - "methods": [ - "storage.entry.bindReceivingDetails" - ], - "notes": [ - "新增 storage.entry.bindReceivingDetails:批量绑定入库单明细与收货单明细,支持明细级数量分配与部分成功", - "storage.entry.get 追加 available_receiving_details 字段加载可匹配的收货单明细" - ], - "type": "addition" - }, - { - "version": "2026.06.24-system-02", - "date": "2026-06-24", - "summary": "storage.entry.bindReceivingDetails:response.failed 字段从简单 reason 描述升级为结构化错误返回(含 error_code、message、detail);同步更新 400 错误说明", - "methods": [ - "storage.entry.bindReceivingDetails" - ], - "notes": [ - "response.failed 新增 items 定义,每项含 entry_item_id、receiving_detail_id、allocated_quantity、error_code、message、detail", - "error_code 枚举:ENTRY_ITEM_NOT_FOUND、STOCK_NOT_FOUND、RECEIVING_DETAIL_MISMATCH、RECEIVING_DETAIL_NOT_FOUND、INSUFFICIENT_AVAILABLE_QUANTITY、ENTRY_ORDER_STATUS_INVALID", - "400 错误说明更新:入库单状态不允许绑定时,所有 bindings 均返回 failed 且 error_code 为 ENTRY_ORDER_STATUS_INVALID" - ], - "type": "updated" - }, - { - "version": "2026.06.24-system-03", - "date": "2026-06-24", - "summary": "新增 storage.entry.quickInbound 快捷直入/虚拟入库接口", - "methods": [ - "storage.entry.quickInbound" - ], - "notes": [ - "新增 quickInbound 方法:入库单所有商品按明细数量一键直入虚拟库位(space_id=2),跳过收货/质检流程", - "支持状态:CREATED、PENDING 状态的入库单可执行", - "拒绝状态:CANCELLED(已作废)、COMPLETED(已完成)", - "事务内操作:更新入库明细收货量、累加库存总量、写入库存流水、写入虚拟库位库存、变更入库单状态为 COMPLETED", - "事务外异步回传奇门/API" - ], - "type": "addition" - }, - { - "version": "2026.06.24-system-04", - "date": "2026-06-24", - "summary": "收窄 storage.entry.quickInbound 状态约束:仅允许 CREATED 状态执行快捷直入", - "methods": [ - "storage.entry.quickInbound" - ], - "notes": [ - "收窄状态约束:仅允许 CREATED 状态执行快捷直入,PENDING 状态不再允许" - ], - "type": "updated" - }, - { - "version": "2026.06.24-system-05", - "date": "2026-06-24", - "summary": "修正 storage.entry.quickInbound errors[4] message 以匹配代码实现:改为动态状态描述", - "methods": [ - "storage.entry.quickInbound" - ], - "notes": [ - "errors[4].message 从「入库单状态不允许快捷直入(仅支持CREATED状态)」改为「入库单状态不允许快捷直入,当前状态:非CREATED(如PENDING等)」,反映代码中 `${entryOrder.order_status}` 动态模板特性" - ], - "type": "updated" - }, - { - "version": "2026.06.24-system-06", - "date": "2026-06-24", - "summary": "新增入库单与收货单商品对照预览接口", - "methods": [ - "storage.entry.receivingCompare" - ], - "notes": [ - "新增 storage.entry.receivingCompare 方法:给定入库单ID和收货单ID,返回入库商品与收货商品的逐行对照视图。", - "comparison 列表中每项含 match_status(matched/entry_only),以及入库侧和收货侧的商品与数量信息。", - "receiving_only 列表包含仅存在于收货单中的商品明细。", - "summary 提供 total_entry_items、matched_items、entry_only_items、receiving_only_items 汇总统计。", - "纯只读接口,不产生任何数据写入或状态变更。" - ], - "type": "addition" - }, - { - "version": "2026.06.24-system-07", - "date": "2026-06-24", - "summary": "setting.warehouse 模块新增 7 个发件人信息字段到 subject_config", - "methods": [ - "setting.warehouse.getSettings", - "setting.warehouse.saveSettings" - ], - "notes": [ - "在 getSettings 的 response 中新增 subject_config.sender_name(发件人姓名)、sender_tel(发件人电话)、province_name(省份)、city_name(城市)、district_name(区/县)、town_name(镇/街道)、address(详细地址)共 7 个字段,均为可选字符串,默认空。", - "在 saveSettings 的 params 中新增对应的 7 个入参字段,source 为 body.subject_config,均为可选字符串,默认空,并标注 maxLength。", - "字段 key 与 store_warehouse.policy_config 中发件人字段命名完全一致,统一仓库级发件人默认值配置。", - "getFieldMeta 接口无需修改文档——其返回的字段元信息由 WAREHOUSE_SETTING_FIELDS 定义在运行时自动生成,新增字段会随代码自动纳入返回列表。" - ], - "type": "updated", - "module": "setting.warehouse" - }, - { - "version": "2026.06.25-system-01", - "date": "2026-06-25", - "summary": "新增 storage.entry.bindReceiving 接口:将收货单绑定到入库单(主表级关联,不做明细数量分配)", - "methods": [ - "storage.entry.bindReceiving" - ], - "notes": [ - "新增入库单与收货单的主表绑定接口,与已有的 storage.entry.bindReceivingDetails(明细级绑定)区分:bindReceiving 仅建立 wms_entry_order_receiving 主表关联,不做明细数量分配。", - "入库单需为 CREATED 或 PENDING 状态;收货单需存在、同仓库且未取消。", - "支持部分成功模式:逐条校验收货单,校验通过的建立绑定,不通过的返回 error_code 和 message。", - "响应包含 success(成功列表)、failed(失败列表)、success_count、failed_count。" - ], - "type": "addition" - }, - { - "version": "2026.06.25-system-02", - "date": "2026-06-25", - "summary": "storage.entry.bindReceiving:新增 OWNER_MISMATCH 错误码,用于收货单与入库单货主不一致校验", - "methods": [ - "storage.entry.bindReceiving" - ], - "notes": [ - "在 storage.entry.bindReceiving 的 errors 数组中新增 OWNER_MISMATCH(收货单与入库单货主不一致)错误码。", - "同步更新 response.failed.error_code 的枚举描述,补充 OWNER_MISMATCH。" - ], - "type": "updated", - "module": "storage.entry" - }, - { - "version": "2026.06.25-system-03", - "date": "2026-06-25", - "summary": "storage.entry.bindReceiving:新增收货单未审核错误码 RECEIVING_NOT_REVIEWED", - "methods": [ - "storage.entry.bindReceiving" - ], - "notes": [ - "在 errors 数组中新增错误码 RECEIVING_NOT_REVIEWED(收货单未审核),用于标识绑定前收货单尚未完成审核的场景。", - "同步更新 response.failed.items.properties.error_code.description,在可能值列表中补充 RECEIVING_NOT_REVIEWED。" - ], - "type": "updated" - }, - { - "version": "2026.06.25-system-04", - "date": "2026-06-25", - "summary": "storage.entry.list 响应新增 receivingBindings 和 hasReceiving 字段,where 新增 hasReceiving 虚拟筛选条件", - "methods": [ - "storage.entry.list" - ], - "notes": [ - "响应 list 数组每项新增 receivingBindings(收货单绑定列表,主表级关联)和 hasReceiving(是否存在收货单绑定,boolean)字段。", - "入参 where 新增 hasReceiving 虚拟筛选字段,传 true/false 筛选已绑定/未绑定收货单的入库单,内部通过 wms_entry_order_receiving 表查询实现。", - "同步更新 description 以说明 hasReceiving 虚拟筛选的使用方式。" - ], - "type": "updated" - }, - { - "version": "2026.06.26-system-01", - "date": "2026-06-26", - "summary": "storage.entry.receivingCompare 支持多收货单对照预览", - "methods": [ - "storage.entry.receivingCompare" - ], - "notes": [ - "支持多个收货单ID对照预览(新增 receiving_ids 数组入参,优先于 receiving_id 使用)", - "入参 receiving_id 从 required 改为 optional,与 receiving_ids 二选一", - "出参结构调整为 comparisons[] 数组(多收货单),新增 errors[] 和 total_summary", - "向后兼容原 receiving_id 单值传参(底层自动转为单元素数组)", - "新增 400 错误码:receiving_ids 或 receiving_id 必填", - "移除 404 错误码:收货单不存在(已改为在 comparisons[]/errors[] 中以 status=error 形式返回)" - ], - "type": "enhancement" - }, - { - "version": "2026.06.26-system-02", - "date": "2026-06-26", - "summary": "storage.receiving.getReceivingList 新增 filterDepleted 可选参数;storage.entry.receivingCompare 返回值 receiving_only 字段新增 receiving_allocated 和 receiving_available 说明", - "methods": [ - "storage.receiving.getReceivingList", - "storage.entry.receivingCompare" - ], - "notes": [ - "storage.receiving.getReceivingList:params 新增 filterDepleted(boolean, 默认 false),用于过滤掉无可再用量的收货单(所有明细已被其他入库单 committed 绑定占满)。", - "storage.entry.receivingCompare:response 中 receiving_only 字段的 description 补充 receiving_allocated(已分配数量)和 receiving_available(可再用量)两个子字段说明。" - ], - "type": "updated" - }, - { - "version": "2026.06.26-system-03", - "date": "2026-06-26", - "summary": "storage.receiving.getReceivingList:新增可选参数 entry_order_id,按入库单商品交集过滤收货单列表", - "methods": [ - "storage.receiving.getReceivingList" - ], - "notes": [ - "新增可选参数 entry_order_id(number),传入入库单 ID 后只返回至少有一条明细的 system_product_id 在入库单明细中存在的收货单。", - "与现有 filterDepleted 参数可组合使用,二者取交集。", - "不传则不过滤,保持原有行为不变。" - ], - "type": "updated" - }, - { - "version": "2026.06.27-system-01", - "date": "2026-06-27", - "summary": "新增 storage.entry.reviewEntry 接口:审核入库单(CREATED→PENDING),需绑定收货单", - "methods": [ - "storage.entry.reviewEntry" - ], - "notes": [ - "新增入库单审核接口,支持 CREATED→PENDING 状态流转。", - "审核前置条件:入库单必须已绑定收货单(EntryOrderReceiving 存在关联记录)。", - "审核通过后写入操作日志(ENTRY_ORDER_REVIEW)。" - ], - "type": "added" - }, - { - "version": "2026.06.29-system-01", - "date": "2026-06-29", - "summary": "storage.inventory.quickPutaway 重新实现:收货单快捷转入库单", - "methods": [ - "storage.inventory.quickPutaway" - ], - "notes": [ - "此前已从代码中删除(2026.06.23-system-08),现由 wms-dev-agent 重新实现。", - "核心流程:参数校验 → 加载收货单及明细 → 检查货主配置 policy_config.allow_receiving_quick_putaway → 按 stock_id(system_product_id)分组合并数量 → 创建入库单 SCRK(自动审批到 PENDING)→ 写入 wms_entry_order_receiving 主表级绑定 → 更新收货单 storage_status 为 partial → 更新收货单明细 storage_status/stored_quantity → 提交事务。", - "前置条件:收货单状态为 completed 且 is_review=true(已审核),货主仓库签约配置 allow_receiving_quick_putaway=1。", - "与旧实现的区别:不涉及 wms_entry_receiving_binding 明细级绑定,使用 wms_entry_order_receiving 主表级关联;直接创建入库单并写入绑定,不再走 matchPutaway 匹配链路。", - "返回:entry_order_id、entry_order_code(SCRK 格式)、order_status(PENDING)、receiving_id、total_lines、total_quantity。" - ], - "type": "addition" - }, - { - "version": "2026.06.29-system-02", - "date": "2026-06-29", - "summary": "storage.entry.list:quickWhere 搜索范围扩展,新增收货单 ID(receiving_id)支持 PDA 扫描托盘唛头搜索绑定的入库单", - "methods": [ - "storage.entry.list" - ], - "notes": [ - "quickWhere 搜索字段新增 receiving_id(收货单 ID / 托盘唛头),通过 wms_entry_order_receiving 绑定表关联搜索。", - "同步更新 description 和 where 参数的 description,明确 quickWhere 完整搜索字段列表:entry_order_code、purchase_order_code、supplier_name、store_name、warehouse_name、receiving_id。" - ], - "type": "updated", - "module": "storage" - }, - { - "version": "2026.06.29-system-03", - "date": "2026-06-29", - "summary": "新增 storage.receiving.scanDetail 接口:PDA 上架扫码定位收货明细", - "methods": [ - "storage.receiving.scanDetail" - ], - "notes": [ - "新增 storage.receiving.scanDetail(PDA专用):通过 entry_order_id + barcode 扫码快速定位收货明细。", - "搜索逻辑:纯数字 barcode 优先按明细 ID 精确匹配(托盘唛头),未命中则模糊匹配商品条码;非纯数字仅模糊匹配商品条码。", - "入参:entry_order_id(必填 number)、barcode(必填 string)。", - "出参:detail_id、receiving_id、barcode、product_name、actual_quantity、receiving_status。", - "错误码:入库单不存在或无权访问、该入库单尚未关联收货单、未找到匹配的收货明细。" - ], - "type": "added" - }, - { - "version": "2026.06.29-system-04", - "date": "2026-06-29", - "summary": "storage.receiving.scanDetail 响应结构从单条改为列表:返回 { list, total } 支持同一条码匹配多条明细", - "methods": [ - "storage.receiving.scanDetail" - ], - "notes": [ - "响应结构变更:原返回 data.detail_id/data.receiving_id 等单条字段,现改为顶层 list 数组 + total 计数。", - "同一条码可能匹配到多条收货明细(不同收货单的同一商品),以列表形式返回所有匹配结果。", - "list 中每条明细包含 detail_id/receiving_id/barcode/product_name/actual_quantity/receiving_status。", - "补充错误码:用户未绑定仓库、入库单ID/条码为空、未找到可用的收货明细、500服务器错误。", - "PDA专用接口,description 更新说明匹配逻辑。" - ], - "type": "updated", - "module": "storage.receiving" - }, - { - "version": "2026.06.30-system-01", - "date": "2026-06-30", - "summary": "新增 storage.entry.containerList:PDA 上架时拉取入库单绑定收货单中指定商品的可用容器列表", - "methods": [ - "storage.entry.containerList" - ], - "notes": [ - "新增接口 storage.entry.containerList,用于 PDA 上架场景拉取入库单已绑定收货单中指定 stock_id 的可用收货明细(容器)列表。", - "入参:entry_order_id(入库单ID,必填)、stock_id(商品 stock_id,必填)。", - "出参:data.list 返回可用明细列表,每项含 detail_id、receiving_id、barcode、product_name、actual_quantity、receiving_status;data.total 为总数。", - "已绑定占用的收货明细(wms_entry_receiving_binding 中已有记录且未软删除)会被排除。", - "PDA 专用接口,无需额外鉴权(isNeedAuth=false)。" - ], - "type": "added" - }, - { - "version": "2026.06.30-system-02", - "date": "2026-06-30", - "summary": "storage.entry.addItem 入参变更:entry_order_code → entry_order_id(number);quantity 改为可选(传入 receiving_detail_id 时自动计算);新增 receiving_detail_id/allocated_quantity 参数支持 PDA 上架收货明细绑定模式;space_id 绑定模式下必填", - "methods": [ - "storage.entry.addItem" - ], - "notes": [ - "入参 entry_order_code(string) → entry_order_id(number),与底层 inboundDirectLog.addItem 实现对齐", - "quantity 改为可选:传入 receiving_detail_id 时自动从收货明细计算可用数量(actual_quantity - 已绑定数量)", - "新增 receiving_detail_id 参数:PDA 上架绑定收货明细时传入,触发预占绑定(wms_entry_receiving_binding status=pending)", - "新增 allocated_quantity 参数:预分配数量,默认等于 quantity", - "space_id 在绑定模式下必填;非绑定模式可选(commit 时兜底为 1)", - "PENDING 状态入库单必须传 receiving_detail_id 且已绑定收货单方可操作", - "CREATED + 已绑定收货单的入库单需先审核(reviewEntry)后才能上架", - "批量模式 items 数组同步支持 receiving_detail_id/allocated_quantity 字段", - "补充完整错误码列表:超量、可用数量不足、状态校验等" - ], - "type": "updated" - }, - { - "version": "2026.06.30-system-03", - "date": "2026-06-30", - "summary": "storage.entry.commit 入参变更:entry_order_code → entry_order_id(number),与底层 inboundDirectLog.commit 实现对齐", - "methods": [ - "storage.entry.commit" - ], - "notes": [ - "入参 entry_order_code(string) → entry_order_id(number),与底层 inboundDirectLog.commit(entryOrderId) 实现对齐", - "补充 description 说明先同步后写库两段式流程:① 奇门/API 回传 → ② onSuccess 内事务写库存", - "补充 commit 后 EntryReceivingBinding 状态从 pending 更新为 committed 的说明" - ], - "type": "updated" - }, - { - "version": "2026.06.30-system-04", - "date": "2026-06-30", - "summary": "storage.directInbound.commit 入参变更:entry_order_code → entry_order_id(number),与底层 inboundDirectLog.commit 实现对齐", - "methods": [ - "storage.directInbound.commit" - ], - "notes": [ - "入参 entry_order_code(string) → entry_order_id(number),与底层 inboundDirectLog.commit(entryOrderId) 实现对齐", - "该方法已标记 deprecated,推荐使用 storage.entry.commit" - ], - "type": "updated" - }, - { - "version": "2026.06.30-system-05", - "date": "2026-06-30", - "summary": "storage.entry.getDirectInboundItems 响应结构重构:entryOrder 精简字段,items[].count→planned、direct_inbound_quantity→completed,items[].bindings 新增,移除 direct_logs/summary 等冗余字段", - "methods": [ - "storage.entry.getDirectInboundItems" - ], - "notes": [ - "entryOrder 精简为 id / entry_order_code / order_status / store_remask 四个字段", - "items[].count → planned(计划数量),items[].direct_inbound_quantity → completed(已完成数量)", - "items[].bindings 新增,结构为 { detail_id, binding_id, allocated_quantity, space_id, space_name }", - "items[].stock 新增,返回 getStockDetails 缓存的商品详情(item_code、item_name、barcodes 等)", - "移除 direct_logs(现有响应中已不存在该顶层字段)", - "移除 summary(现有响应中已不存在该字段)", - "移除 items[].received_quantity、items[].remaining_quantity、items[].pending_binding_total 等旧字段", - "新增 receivingBindings 字段说明:入库单层级收货单绑定关系" - ], - "type": "updated" - }, - { - "version": "2026.06.30-system-06", - "date": "2026-06-30", - "summary": "storage.directInbound.getItems 响应结构重构:entryOrder 精简字段,items[].count→planned、direct_inbound_quantity→completed,items[].bindings 新增,移除 direct_logs/summary 等冗余字段", - "methods": [ - "storage.directInbound.getItems" - ], - "notes": [ - "响应结构与 storage.entry.getDirectInboundItems 对齐(两者共用同一个底层实现 inboundDirectLog.getItems)", - "entryOrder 精简为 id / entry_order_code / order_status / store_remask", - "items[].count → planned,items[].direct_inbound_quantity → completed", - "items[].bindings 新增 { detail_id, binding_id, allocated_quantity, space_id, space_name }", - "items[].stock 新增", - "移除 direct_logs、summary、items[].received_quantity、items[].remaining_quantity 等旧字段", - "新增 receivingBindings 字段" - ], - "type": "updated" - }, - { - "version": "2026.06.30-system-07", - "date": "2026-06-30", - "summary": "storage.entry.containerList 响应结构补充 stock 字段:返回商品详情(item_code、item_name、barcodes 等)", - "methods": [ - "storage.entry.containerList" - ], - "notes": [ - "响应 list[].stock 字段补充为必返回:通过 getStockDetails 批量获取商品详情缓存", - "stock 对象包含 item_code、item_name、sku_property、barcodes 等字段" - ], - "type": "updated" - }, - { - "version": "2026.06.30-system-08", - "date": "2026-06-30", - "summary": "storage.receiving.scanDetail 响应结构补充 stock 字段:返回商品详情(item_code、item_name、barcodes 等)", - "methods": [ - "storage.receiving.scanDetail" - ], - "notes": [ - "响应 list[].stock 字段补充为必返回:通过 getStockDetails 批量获取商品详情缓存", - "stock 对象包含 item_code、item_name、sku_property、barcodes 等字段", - "完善 error 列表:补充 未找到可用的收货明细、未找到匹配的收货明细、入库单ID不能为空、扫描条码不能为空 等错误" - ], - "type": "updated" - }, - { - "version": "2026.06.30-system-09", - "date": "2026-06-30", - "summary": "订单列表 list 响应新增 store_remark(货主备注)字段", - "methods": [ - "order.list", - "order.reviewOrder.list", - "order.pendingOrder.list", - "order.expectionOrder.list", - "order.entrustOrder.list", - "order.deliveryOrder.list", - "order.deliveryExpectionOrder.list", - "order.archiveOrder.list" - ], - "notes": [ - "数据库字段 store_remask,返回给前端的字段名为 store_remark。", - "服务层从 wms_store_warehouse.store_remask 按 store_id+warehouse_id 聚合批量填充。", - "货主备注值可能为空字符串(当货主未设置备注时)。", - "该字段对订单列表的所有 method 均适用(current/dispatch/outsourced/history 模型均返回)。" - ], - "type": "updated" - }, - { - "version": "2026.07.02-system-02", - "date": "2026-07-02", - "summary": "新增 quick.waybill.toOrder 接口:根据运单号快速查询订单ID", - "methods": [ - "quick.waybill.toOrder" - ], - "notes": [ - "新增 quick 模块组(快捷查询)", - "查询 wms_order_express 表中 status=1 的有效记录", - "无需登录和鉴权(免登录/免鉴权)" - ], - "type": "added" - }, - { - "version": "2026.07.02-system-01", - "date": "2026-07-02", - "summary": "修正 quick.waybill.toOrder 的 isNeedLogin 为 true,与代码实现保持一致", - "methods": [ - "quick.waybill.toOrder" - ], - "notes": [ - "文档中 isNeedLogin 为 false,但代码 systemMethods/quick/waybill.js 中 _noNeedLogin 为空字符串,未将 toOrder 加入免登录列表,实际需要登录验证,修正文档以与代码一致。" - ], - "type": "fixed" - }, - { - "version": "2026.07.03-system-01", - "date": "2026-07-03", - "summary": "binding 表弃用文档同步:wms_entry_receiving_binding 已弃用,功能迁移到 wms_inbound_direct_log 表;bindings 描述中表引用更新为 InboundDirectLog", - "methods": [ - "storage.entry.getDirectInboundItems" - ], - "notes": [ - "bindings 数组 description 中 wms_entry_receiving_binding 引用更新为 InboundDirectLog,明确旧表已弃用", - "binding_id description 中 wms_entry_receiving_binding.id 更新为 InboundDirectLog.id", - "allocated_quantity description 中补充来源 InboundDirectLog.quantity", - "wms_inbound_direct_log 表新增字段:entry_item_id、receiving_detail_id、status(ENUM: pending/committed/released)、updated_at、deleted_at" - ], - "type": "updated" - }, - { - "version": "2026.07.03-system-02", - "date": "2026-07-03", - "summary": "binding 表弃用文档同步:wms_entry_receiving_binding 已弃用,功能迁移到 wms_inbound_direct_log 表;bindings 描述中表引用更新为 InboundDirectLog", - "methods": [ - "storage.directInbound.getItems" - ], - "notes": [ - "bindings 数组 description 中更新为来自 InboundDirectLog,明确旧表已弃用", - "binding_id description 更新为 InboundDirectLog.id", - "allocated_quantity description 中补充来源 InboundDirectLog.quantity", - "wms_inbound_direct_log 表新增字段:entry_item_id、receiving_detail_id、status(ENUM: pending/committed/released)、updated_at、deleted_at" - ], - "type": "updated" - }, - { - "version": "2026.07.03-system-03", - "date": "2026-07-03", - "summary": "binding 表弃用文档同步:commit 描述中 EntryReceivingBinding 更新为 InboundDirectLog", - "methods": [ - "storage.entry.commit" - ], - "notes": [ - "commit description 中将 pending 状态的 EntryReceivingBinding 更新为 pending 状态的 InboundDirectLog,与代码实现一致" - ], - "type": "updated" - }, - { - "version": "2026-07-03-entry-get-params-fix", - "date": "2026-07-03", - "type": "updated", - "summary": "修正 storage.entry.get 文档:id 改为必填;移除未实现的 entry_order_code 参数;修正错误码与实际返回一致;补充 available_receiving_details 响应字段;修正 remaining_quantity 计算公式及 warehouse_image_url 实际行为", - "methods": [ - "storage.entry.get" - ], - "notes": [ - "params: 移除 entry_order_code(代码中从未使用该参数),id 从 required=false 改为 required=true", - "params: id 描述从'二选一'改为'必填'", - "errors: 400 的 message 从'参数错误:id 与 entry_order_code 至少提供一个'改为'id 参数不能为空'", - "errors: 移除不存在的 404 error,入库单不存在时实际返回 code=0, message='入库单不存在或无权访问'", - "errors: 删除不存在的 500 error", - "response: 新增 entryOrder.items[].available_receiving_details 字段及其描述", - "response: remaining_quantity 描述从 'count - received_quantity - direct_inbound_quantity' 修正为 'max(0, count - received_quantity)'", - "response: warehouse_image_url 描述从 StockWarehouse.image_url 改为'当前固定返回空字符串'", - "response: warehouse_is_images 类型从 number(0/1) 改为 string(Y/N),与 StockWarehouse.is_images 实际存储一致", - "response: warehouse_quantity/warehouse_locked_quantity/warehouse_is_batch_mgmt/warehouse_is_shelf_life_mgmt 补充无匹配时为 null 的说明", - "description: 更新描述以反映实际逻辑流程" - ] - }, - { - "version": "2026.07.03-system-04", - "date": "2026-07-03", - "type": "modified", - "summary": "order.pendingOrder.updateAddress 移除 remark(备注)修改功能,现在仅支持地址字段批量修改;备注修改已独立为 order.pendingOrder.updateRemark", - "methods": [ - "order.pendingOrder.updateAddress" - ], - "notes": [ - "移除入参 remark 参数定义项。", - "移除 remark 更新逻辑及相关描述,updateAddress 现在仅处理地址字段(name/mobile/tel/zip_code/province/city/area/town/detail_address)。", - "description 更新:去掉 remark 相关描述,仅描述地址字段修改规则。", - "response updated_count 描述更新:从「取地址更新行数与备注更新行数的最大值」改为单纯描述地址更新行数。", - "errors 更新:移除 remark 相关错误说明('remark 字段不受此限制' 等),修改 '至少需要提供一个地址字段或备注进行修改' 为 '至少需要提供一个地址字段进行修改'。", - "备注修改功能已独立为 order.pendingOrder.updateRemark 方法。" - ], - "module": "order.pendingOrder" - }, - { - "version": "2026-07-16", - "date": "2026-07-16", - "summary": "新增 workbench.bindCamera 接口,支持工作台绑定/解绑摄像头", - "methods": [ - "workbench.bindCamera" - ], - "notes": [ - "通过 device_ids JSON 字段存储绑定关系", - "传空数组可解绑" - ] - }, - { - "version": "2026.07.17-stock-report-migration-01", - "date": "2026-07-17", - "type": "updated", - "summary": "storage.report 模块迁移至 stock.report:修正语义错误,库存报表属于 stock 域而非 storage 域", - "methods": [ - "stock.report.search", - "stock.report.searchStore", - "stock.report.export", - "stock.report.exportStore", - "stock.report.exportTaskProgress" - ], - "notes": [ - "将 systemMethods/storage/report.js 移动到 systemMethods/stock/report.js", - "内部引用同步更新:类名 StorageReportMethodService→StockReportMethodService,缓存键 storage_report→stock_report,日志前缀 [storage.report]→[stock.report]", - "旧文件直接删除,不保留兼容(storage.report 为语义错误,调用方需同步更新 method 名)", - "更新 systems/storage/entry.js L273 注释引用", - "文档:methods/system.json module storage.report→stock.report,5个 method 名同步更新" - ] - }, - { - "version": "2026.07.17-stock-transaction-export-01", - "date": "2026-07-17", - "type": "added", - "summary": "新增 stock.transaction 商品流水导出(仓库侧+货主侧),异步任务模式,支持与列表查询一致的条件筛选", - "methods": [ - "stock.transaction.export", - "stock.transaction.exportStore", - "stock.transaction.exportTaskProgress" - ], - "notes": [ - "systems/stock_transaction.js 新增 exportList(),复用 queryList 的查询逻辑,不分页导出 Excel(上限 50000 条)", - "systemMethods/stock/transaction.js 新增 export/exportStore/exportTaskProgress,采用异步任务模式(setImmediate + 缓存)", - "仓库侧导出自动限定 warehouse_id=ctx.user.store_id,货主侧需传 store_id", - "导出 Excel 列:序号/创建时间/流水类型/仓库ID/货主ID/商品ID/变动数量/变更前库存/变更后库存/变更前锁定/变更后锁定/批次号/单据类型/单据号/收货单ID/入库单ID/发货单ID/操作人/备注" - ] - }, - { - "version": "2026.07.29-system-01", - "date": "2026-07-29", - "type": "added", - "summary": "新增 waybill.warehouse 运单模块(仓库侧):list(列表)、detail(详情)、export(导出)3 个接口,支持运单号独立查询与管理", - "methods": [ - "waybill.warehouse.list", - "waybill.warehouse.detail", - "waybill.warehouse.export" - ], - "notes": [ - "新增 waybill.warehouse.list:仓库侧运单列表查询,支持分页与多条件筛选(运单号/主单号/订单ID/订单号/物流公司/物流接口/平台/状态/退回/拦截/星河签收/包材/称重/关键词/时间范围),默认按 create_at desc 排序。", - "新增 waybill.warehouse.detail:仓库侧运单详情查询,含关联订单信息、兄弟运单(sibling_waybills)、物流信息、状态信息、称重信息、打包信息(打包状态/打包人/打包时间)、打印记录列表。", - "新增 waybill.warehouse.export:仓库侧运单导出,复用 list 筛选逻辑,异步任务模式,支持自定义导出字段。", - "仓库隔离策略:所有接口自动注入 warehouse_id = ctx.user.store_id(全系统统一约定),不可由前端入参覆盖。", - "快照字段方案:wms_order_express 表新增 delivery_order_code、store_id_snapshot、store_name_snapshot、warehouse_name_snapshot 四个快照列,列表查询无需 JOIN 订单表或货主表,仅单表查询 + SELF JOIN(主单号)。", - "主单号/子单号规则:同一 order_id 下 business_key=1 为主单号,business_key>1 为子单号,沿用系统已有约定。", - "命名空间规划:waybill.warehouse.* 本期实现(仓库侧),后续预留 waybill.store.*(货主侧)。", - "本模块一期仅提供只读查询,不涉及运单创建/修改/删除,不修改任何现有接口。" - ], - "module": "waybill.warehouse" - }, - { - "version": "2026.07.30-system-01", - "date": "2026-07-30", - "type": "changed", - "summary": "更新 waybill.warehouse group API 文档:list 新增 waybillType/storeId 筛选、移除 pack_status 响应字段;detail 精简 package 对象;export 响应改为纯异步任务模式(仅含 task_id/status/progress/message/update_time)", - "methods": [ - "waybill.warehouse.list", - "waybill.warehouse.detail", - "waybill.warehouse.export", - "waybill.warehouse.exportTaskProgress" - ], - "notes": [ - "waybill.warehouse.list:新增 where.waybillType 筛选(\"main\"/\"1\"=主单号,\"child\"/\"2\"=子单号),新增 where.storeId 货主ID等值筛选。where.orderNo 标注暂不可用(待快照字段就绪)。response 移除 pack_status 字段(两表无关联,不再返回),list 字段数从 28 减至 27。", - "waybill.warehouse.detail:package 对象移除 pack_status/pack_quantity/pack_at/packer_name 四个字段,仅保留 package_material_id 和 package_material_name。description 同步去掉\"打包状态\"相关描述。", - "waybill.warehouse.export:响应简化为纯异步任务模式,data 仅含 task_id/status/progress/message/update_time,不含 total_count/current_count/result/error/download_url 等执行期字段(这些信息由 exportTaskProgress 接口返回)。export 的 where 参数同步新增 waybillType 和 storeId。", - "waybill.warehouse.exportTaskProgress:无变更,保持不变。" - ], - "module": "waybill.warehouse" - }, - { - "version": "2026.08.03-system-01", - "date": "2026-08-03", - "type": "added", - "summary": "新增站内信(Inbox)管理模块,支持消息列表、详情、对话链、回信、重推、统计等管理功能,仓库维度隔离,warehouseId 由服务端上下文注入", - "methods": [ - "inbox.list", - "inbox.detail", - "inbox.thread", - "inbox.reply", - "inbox.retry", - "inbox.stats" - ], - "notes": [ - "入口:POST /system,body.method=inbox.{action},路由到 app/controller/inbox.index", - "inbox.list:分页查询消息列表,支持 direction/pushStatus/targetChannel/keyword 筛选,列表不含 ext_data 和 push_response 大字段", - "inbox.detail:查单条消息详情,含完整 push_response 推送响应信息", - "inbox.thread:对话链查询,从指定消息向上查找根消息,向下收集所有回信,按时间升序返回", - "inbox.reply:系统回信,自动继承原消息 ext_data/ref_code,写入 direction=outbound + parent_id 形成对话链,异步推送到目标渠道", - "inbox.retry:手动重推失败消息(仅 push_status=3 可重推),重置为 push_status=0 并触发 setImmediate 异步推送", - "inbox.stats:按方向/推送状态汇总统计 + 最近24小时新增数量", - "安全边界:warehouse_id 由 ctx.user.store_id 注入(内部管理端),外部不可传入,保证仓库隔离", - "底层服务:app/service/inbox/index.js(查询管理)+ app/service/inbox/receiver.js(接收推送)" - ], - "module": "inbox" - } + { + "version": "2026.08.01-system-01", + "date": "2026-08-01", + "type": "added", + "summary": "新增 apiApp 仓库 API 应用管理模块,支持当前仓库维度的 API 应用 CRUD、AppKey/Secret 自动生成与重新生成、IP 白名单、回调地址、限流等配置", + "methods": [ + "apiApp.list", + "apiApp.detail", + "apiApp.create", + "apiApp.update", + "apiApp.delete", + "apiApp.regenerateSecret" + ], + "notes": [ + "apiApp.list:分页查询当前仓库 API 应用列表,支持按 app_name(模糊)、is_enabled 筛选,Secret 自动脱敏(前8位+****)。", + "apiApp.detail:按 ID 查询单个应用详情,需同时匹配 warehouse_id(自动注入 ctx.user.store_id),Secret 脱敏。", + "apiApp.create:创建应用时自动生成 AppKey(AK{yyyyMMddHHmmss}{random8hex})和 AppSecret(64位hex)。默认 interface_type_id 取 WH_CHANNEL。仅创建时返回完整 Secret。", + "apiApp.update:更新可编辑字段(app_name、self_ip_whitelist、callback_url、rate_limit、sign_method、is_enabled),不可变字段为 self_app_key 和 interface_type_id。", + "apiApp.delete:软删除(is_enabled=0),不物理删除。", + "apiApp.regenerateSecret:重新生成 64位hex AppSecret,旧 Secret 立即失效。仅此次返回完整 Secret。", + "仓库隔离:所有操作按 ctx.user.store_id → warehouse_id 自动过滤。", + "Secret 安全策略:list/detail/update 返回脱敏值,仅 create/regenerateSecret 返回完整 Secret。" + ], + "module": "apiApp" + }, + { + "version": "2026.07.31-system-02", + "date": "2026-07-31", + "type": "added", + "summary": "新增 storage.inventory.export 库存导出与 storage.inventory.exportTaskProgress 导出进度查询,入参复用 list 的 where/sort/group_by_batch 语义,支持两种导出模式(聚合汇总 / 逐条明细),库位信息一并导出", + "methods": [ + "storage.inventory.export", + "storage.inventory.exportTaskProgress" + ], + "notes": [ + "storage.inventory.export:异步提交导出任务,返回 task_id 与受理信息,后端异步生成 Excel 并上传。入参 where/sort/group_by_batch 与 storage.inventory.list 完全一致,无需额外学习成本。", + "group_by_batch=false(默认):按 stock_id + space_id(库位)聚合导出库存汇总,含商品编码/名称/规格/单位/货主/库位编码/名称/总库存/锁定/可用/批次数/最近入库时间。", + "group_by_batch=true:按 storage_id 逐条导出库存明细,含库存记录ID/商品信息/库位信息/批次号/库存类型/数量/生产日期/过期日期/入库时间/入库单号/供应商批次号。", + "新增 storage.inventory.exportTaskProgress:按 task_id/taskId 查询导出任务进度与状态(submitted/running/success/failed/not_found),status=success 时返回 download_url 供客户端下载。", + "导出文件目录:exports/storage/inventory/{warehouseId}/,缓存 TTL 1800 秒。" + ], + "module": "storage.inventory" + }, + { + "version": "2026.07.31-system-01", + "date": "2026-07-31", + "type": "added", + "summary": "新增按波次批量快捷复核接口 batchQuickRecheckByWave,支持批量波次 IDs 的前置条件检查(储位、快递、同步、拦截),自动完成拣货并标记复核,支持部分失败", + "methods": [ + "order.recheckOrder.batchQuickRecheckByWave" + ], + "notes": [ + "新增 order.recheckOrder.batchQuickRecheckByWave 方法,复用 batchQuickRecheck 的 _completePickForOrder / _markRecheckForOrder / _tryCompleteWaveInTransaction 等内部事务方法", + "入参 wave_ids 支持数组或逗号分隔字符串,兼容 waveIds(驼峰)、wave_id(单值)", + "按波次维度批量查询订单后逐波次、逐订单执行前置校验与复核,每个订单独立事务,部分失败不影响其他订单", + "响应包含 success/failed 列表及计数,failed 项含 order_id、wave_id、delivery_order_code、reason 说明;波次下无订单时仅返回 wave_id + reason" + ], + "module": "order.recheckOrder" + }, + { + "version": "2026.07.29-system-01", + "date": "2026-07-29", + "type": "added", + "summary": "补全 waybill.warehouse group API 文档参数定义:完善 list/detail/export 的 params 与 response,新增 exportTaskProgress 异步进度查询接口", + "methods": [ + "waybill.warehouse.list", + "waybill.warehouse.detail", + "waybill.warehouse.export", + "waybill.warehouse.exportTaskProgress" + ], + "notes": [ + "waybill.warehouse.list:params 含 pagination/where/sort 完整字段定义,where 支持 15 个筛选维度(运单号、主单号、订单ID、订单号、物流编码、物流接口ID、平台编码、状态、退回/拦截/星河签收、包材ID、已称重、关键词、创建时间范围),sort 白名单 create_at/weighing_weight/id。response 含 list(28 个字段)+ pagination。", + "waybill.warehouse.detail:修正 id 参数为可选(required: false),与 waybillCode 二选一,waybillCode 优先。response 含 id/waybill_code/main_waybill_code/waybill_type/business_key/sibling_waybills/order/logistics/status_info/weight/package/print_records/print_count 等完整详情。", + "waybill.warehouse.export:response 补充 progress/message/update_time 字段,完整覆盖异步任务返回信息。", + "新增 waybill.warehouse.exportTaskProgress:按 task_id/taskId 查询导出进度,response 含 task_id/status/progress/current_count/total_count/message/result/error/download_url/update_time。", + "所有接口 isNeedAuth: false, isNeedLogin: true,仓库隔离通过 ctx.user.store_id 自动注入。" + ], + "module": "waybill.warehouse" + }, + { + "version": "2026.07.28-system-01", + "date": "2026-07-28", + "type": "added", + "summary": "新增 order.pendingOrder.batchMarkPrinted:批量设置订单为已打印状态,将 print_status 更新为 'fin'", + "methods": [ + "order.pendingOrder.batchMarkPrinted" + ], + "notes": [ + "同步批量更新接口,传入订单ID数组,直接将符合条件的订单 print_status 设为 'fin'。", + "双表查询:先查 current 表(wms_order_delivery_{warehouseId}),未命中的 ID 再兜底查 dispatch 表(wms_order_delivery_{warehouseId}_dispatch)。", + "dispatch 表查询失败仅记录 warn 日志,不影响 current 表已更新的结果。", + "仅允许 step 在 [1,2,3] 且 status 不为 'cancel' 的订单操作,已打印(print_status='fin')的订单会被静默跳过。", + "仓库上下文强制从 ctx.user.store_id 获取,禁止传入外部仓库ID。", + "入参支持 order_ids / orderIds / ids 三种别名,优先级 order_ids > orderIds > ids。", + "返回 updated_count 表示实际更新条数(current + dispatch 合计),ids 原样回传请求的订单ID列表。", + "写入操作日志 operation_code: ORDER_BATCH_MARK_PRINTED。" + ], + "module": "order.pendingOrder" + }, + { + "version": "2026.07.27-system-03", + "date": "2026-07-27", + "type": "changed", + "summary": "storage.receiving 导出接口拆分:export 改为按仓库维度,新增 storeExport 按货主维度导出", + "methods": [ + "storage.receiving.export", + "storage.receiving.exportTaskProgress", + "storage.receiving.storeExport", + "storage.receiving.storeExportTaskProgress" + ], + "notes": [ + "export 改为仓库维度:过滤条件从 store_id(平台激活货主)改为 warehouse_id(ctx.user.store_id),与 getReceivingList 保持一致。", + "exportTaskProgress 同步更新为仓库维度进度查询,任务 ID 前缀 receiving_export_。", + "新增 storeExport:货主维度导出,通过平台激活上下文获取 store_id,过滤逻辑与 getStoreReceivingList 一致。", + "新增 storeExportTaskProgress:货主维度进度查询,复用 exportTaskProgress 的缓存逻辑,任务 ID 前缀 receiving_store_export_。", + "导出格式:双 Sheet Excel(Sheet1=收货单列表 21 列,Sheet2=收货单明细 17 列),通过 ExcelJS stream + uploadService 上传 COS。", + "仓库导出上传路径 exports/receiving/{warehouseId}/,货主导出上传路径 exports/receiving/store/{storeId}/。", + "修复 exportReceivingList 中 where 条件二次解析问题:增加 ctx.whereParsed 复用(与 getStoreReceivingList 一致),避免 prepareWhereContext 已解析后再重复 parseWhereConditions 导致边界条件丢失。", + "命名对齐 entry 侧:storeExport / storeExportTaskProgress 方法名、任务 ID 前缀、上传路径均与 storage.entry.storeExport 模式一致。" + ], + "module": "storage.receiving" + }, + { + "version": "2026.07.27-system-02", + "date": "2026-07-27", + "type": "added", + "summary": "新增 order.pendingOrder.allocateSubOrderNumber:待处理订单分配子单号(异步任务),business_key 从 2 开始递增,跳过已分配运单号;新增 allocateSubOrderNumberProgress 按 task_id/business_key 查询进度", + "methods": [ + "order.pendingOrder.allocateSubOrderNumber", + "order.pendingOrder.allocateSubOrderNumberProgress" + ], + "notes": [ + "新增 allocateSubOrderNumber:入参 order_id + sub_order_count,按 business_key 2..(2+count-1) 全量传入 createWaybillCodePipeline。", + "并发安全:全量传入 pipeline,由其内部事务 + UNIQUE(order_id,business_key,status,warehouse_id) 索引保证并发去重。", + "pipeline 内部 createWaybillCode 事务:status=1 已分配→跳过;status=0 占位中→复用;无记录→INSERT status=0 占位。", + "异步任务模式:请求立即返回 task_id(sub_ 前缀),后台 setImmediate 执行,进度通过 Redis 缓存追踪。", + "新增 allocateSubOrderNumberProgress:支持 task_id 查整体进度,business_key 可选参数过滤单个业务ID的详情。", + "进度状态 submitted→running→success/partial/failed,progress 对应 5/50/80/100。", + "result.details 数组记录每个 business_key 的 status(skipped/allocated/failed/pending)与 waybill_code。", + "buildSubOrderDetails 回查最终状态:status=1+waybill→allocated,status=0→failed,无记录→failed。" + ], + "module": "order.pendingOrder" + }, + { + "version": "2026.07.27-system-01", + "date": "2026-07-27", + "type": "added", + "summary": "新增 order.packing 打包任务模块:list/get 查询 + setEndTime 设置结束时间,含视频 CDN URL 拼接与状态回写", + "methods": [ + "order.packing.list", + "order.packing.get", + "order.packing.setEndTime", + "order.packing.forceRecord" + ], + "notes": [ + "新增 order.packing.list:按仓库维度查询打包任务列表,支持分页/筛选/排序,关联工作台、视频和运单信息。", + "新增 order.packing.get:按 id + warehouse_id 查询单条打包任务详情。", + "新增 order.packing.setEndTime:设置打包任务结束时间,入参 id + end_time;若任务状态不是已完成(2)则同步更新为已完成。", + "新增 order.packing.forceRecord:强制重新录制打包任务视频,入参 id;校验录制电脑在线后重置视频状态并推送打印服务。", + "前端默认值逻辑:若任务已有 end_time 则打开时默认为当前时间,否则默认为 start_time + 5分钟。", + "视频 URL 自动拼接 CDN 域名前缀:http://w{warehouseId}-c{recordingComputerId}.o.gztbyc.com{videoPath};录制电脑从 wms_print_computer 按 is_recording=true 获取。", + "视频响应新增 status 字段(created/recording/completed/failed),与数据库 ENUM 保持一致。", + "pack_task_video Model 的 status 字段从 TINYINT 改为 STRING(20) 以匹配 DB ENUM 迁移。", + "forceRecord 通过打印服务 /record/force 推送录制任务,传入 pack_task_id、warehouse_id、computer_id、camera_ids。" + ], + "module": "order.packing" + }, + { + "version": "2026.07.10-system-01", + "date": "2026-07-10", + "type": "added", + "summary": "新增 storage.report.searchStore 货主侧库存报表,以 store_id 为主维度查询库存流水", + "methods": [ + "storage.report.searchStore", + "storage.report.exportStore" + ], + "notes": [ + "新增 searchStore 方法:与 search 共享核心逻辑,通过 searchMode='store' 切换主维度从 warehouse_id → store_id。", + "新增 exportStore 方法:与 export 共享核心逻辑,支持货主侧导出 Excel(含汇总 + 变更记录两个 sheet)。", + "systems 层 search/export 方法新增 searchMode 参数(默认 'warehouse'),不影响现有 warehouse 侧行为。", + "货主侧使用 ctx.user.store_id 作为主维度 store_id,辅助维度支持 warehouse_ids 过滤特定仓库。", + "systemMethods 层 searchStore 从 where.warehouse_ids 取值传给 search 的 storeIds(承载 warehouse 过滤)。", + "输出新增 warehouse_id / warehouse_name 字段,货主侧可区分不同仓库的库存。search 方法也同步输出这两个字段(向后兼容)。", + "修复 getStockDetails 的 warehouseId 判断:从 != null 改为 !== undefined,使显式传 null 可跳过 warehouse 过滤。", + "修复 loadReportReferenceMaps 未传递 warehouseId 给 getStockDetails 的问题。" + ], + "module": "storage.report" + }, + { + "version": "2026.07.09-system-01", + "date": "2026-07-09", + "type": "updated", + "summary": "签约 sign 方法改造:统一当前主体→store_id,解除角色校验,仓库可签仓库", + "methods": [ + "storeWarehouse.store.sign", + "storeWarehouse.warehouse.sign" + ], + "notes": [ + "resolvePairIds:统一当前主体始终在 store_id(货主方/消费方),对方在 warehouse_id(仓库方/提供方)。不再根据 isWarehouse 分支。", + "getCounterparty:移除 expectedRole 角色校验(仓库不再只能签货主,可签仓库)。", + "findScopedRelation:改为 OR 查询 store_id/warehouse_id 两边,兼容新旧签约数据。", + "sign preview:counterparty.role 改为根据对方 project 真实返回(warehouse/store),不再硬编码反推。", + "签仓库:仓库发起签约时对方 ID 传 counterparty_id,系统自动将当前仓库放 store_id。" + ], + "module": "storeWarehouse" + }, + { + "version": "2026.07.08-system-01", + "date": "2026-07-08", + "type": "updated", + "summary": "storeWarehouse.store.list 与 storeWarehouse.warehouse.list 拆分实现,不再共用;仓库侧支持查询外部合作仓库", + "methods": [ + "storeWarehouse.store.list", + "storeWarehouse.warehouse.list" + ], + "notes": [ + "拆分:store.list 调用 listForStore,warehouse.list 调用 listForWarehouse,不再共用同一个 list 方法。", + "新规则:两个方法均按 store_id = 当前主体ID 过滤(主体在 store_id 为货主方/消费方,对方在 warehouse_id 为仓库方/提供方)。", + "warehouse.list 新增支持查询外部合作仓库:当对方主体的 project='warehouse' 时为仓库-仓库合作,counterparty_role='warehouse'。", + "响应新增 counterparty_role 字段(store/warehouse),标识对方主体的真实角色。", + "warehouse.list 响应 use_status 改为 store_use_status(仓库在 store_id 方时,己方启用状态应为 store_use_status)。", + "旧 list 方法保留标记为 @deprecated,保持向后兼容。", + "新增 buildListWhereByStoreId 统一按 store_id 维度构建查询条件。" + ], + "module": "storeWarehouse" + }, + { + "version": "2026.07.06-system-01", + "date": "2026-07-06", + "type": "updated", + "summary": "order.wave.batchList:响应新增 pick_assignment_status(拣货分配状态),按订单 pick_status 聚合判定", + "methods": [ + "order.wave.batchList" + ], + "notes": [ + "响应 list 每项新增字段 pick_assignment_status (string):拣货分配状态,按波次下订单的 pick_status 聚合判定。", + "取值语义与 resolveAssignmentStatus 一致,自定义标签:未拣货(全 none)、部分拣货(混合且无 error)、已拣货(全 fin)、拣货异常(含 error)。", + "SQL 子查询新增 pick_none_count / pick_fin_count / pick_error_count 聚合列。" + ], + "module": "order.wave" + }, + { + "version": "2026.07.05-system-01", + "date": "2026-07-05", + "type": "added", + "summary": "新增 pick.wavePickComplete:传入 wave_id 一键完成整个波次拣货,内部复用 query 去重与任务创建逻辑后自动调用 wavePickTaskComplete(mode=1)", + "methods": [ + "pick.wavePickComplete" + ], + "notes": [ + "新增方法:pick.wavePickComplete,入参 wave_id(number,必填)。", + "内部流程:按 wave_id 查波次 → 活动任务去重(同用户复用 / 他人409冲突)→ 完成任务去重 → 无任务则创建(source=2 后台抓取)→ 调用 pick.wavePickTaskComplete mode=1 全部确认。", + "创建任务 remark 格式:pick.wavePickComplete wave_id={waveId},用于与 pick.query 区分。", + "响应:task_id、status(completed / already_completed)、tip、confirmed_order_ids、is_completed、progress。", + "错误码:400(参数/波次无订单)、401(缺少操作人)、404(波次不存在)、409(他人活动任务冲突)、500(创建/完成失败)。" + ], + "module": "pick" + }, + { + "version": "2026.07.03-system-02", + "date": "2026-07-03", + "type": "added", + "summary": "新增 order.pendingOrder.updateRemark:批量修改待处理订单备注(remark),不受 post_status 限制", + "methods": [ + "order.pendingOrder.updateRemark" + ], + "notes": [ + "新增方法:order.pendingOrder.updateRemark,用于批量修改待处理订单的备注(remark)字段。", + "入参:ids(number[],必填,正整数数组,不能为空)、remark(string,必填,最大500字符)。", + "特性:不受 post_status 限制,可对所有状态的订单生效;纯批量不支持单ID。", + "更新成功后写入操作日志。", + "响应:updated_count(number,实际更新行数)、ids(number[],原样返回请求的ID数组)。", + "错误码:400(ids 不能为空 / ids 仅支持正整数数组 / remark 不能为空)。" + ], + "module": "order.pendingOrder" + }, + { + "version": "2026.07.03-system-01", + "date": "2026-07-03", + "type": "updated", + "summary": "将 quick.waybill.toOrder 迁移为 index.toOrder 并移入基础模块,新增 waves 返回字段", + "methods": [ + "quick.waybill.toOrder", + "index.toOrder" + ], + "notes": [ + "移除快捷操作(quick)模块分组,原 quick.waybill.toOrder 方法从 methods/system.json 删除。", + "在基础模块(index)新增 index.toOrder 方法:入参仍为 waybill_code,响应从单一 order_id 扩展为 order_id + waves 结构。", + "waves 为数组,每项含 wave_id(波次ID)、wave_no(波次号)、order_ids(波次下所有订单ID列表),无波次时为空数组。", + "查询路径:运单号 → wms_order_express(status=1)→ order_id + warehouse_id → 遍历 current/history/dispatch 表获取波次信息 → 再遍历多表获取同波次所有订单ID。" + ] + }, + { + "date": "2026-06-24", + "type": "addition", + "summary": "新增批量绑定入库单明细与收货单明细接口,支持明细级数量分配与部分成功", + "version": "2026-06-24-add-bind-receiving-details", + "methods": [ + "storage.entry.bindReceivingDetails" + ], + "notes": [] + }, + { + "date": "2026-06-24", + "type": "deprecation", + "summary": "废弃手动匹配入库单收货单接口,由 storage.entry.bindReceivingDetails 替代", + "version": "2026-06-24-deprecate-manual-match-entry-order", + "methods": [ + "storage.receiving.manualMatchEntryOrder" + ], + "notes": [] + }, + { + "version": "2026.06.16-system-03", + "date": "2026-06-16", + "summary": "order.wave.waveStrategyFallbackOrderList 响应新增 items_weight(总重量g)和 weight_type(重量类型)字段", + "methods": [ + "order.wave.waveStrategyFallbackOrderList" + ], + "notes": [ + "响应 list 每项新增字段 items_weight (number|null):订单总重量(g),来自 wms_order.items_weight,为 null 时返回 null。", + "响应 list 每项新增字段 weight_type (string):重量类型中文标签,来自 wms_order.weight_type 经 formatWeightTypeLabel 转换;取值:常规/轻货/重货/冷链(对应 DB 值 0/1/2/3)。" + ], + "type": "updated", + "module": "order.wave" + }, + { + "version": "2026.06.16-system-04", + "date": "2026-06-16", + "summary": "order.wave.singleOrderFetchList 响应新增 items_weight(总重量g)字段", + "methods": [ + "order.wave.singleOrderFetchList" + ], + "notes": [ + "响应 list 每项新增字段 items_weight (number|null):订单总重量(g),取组内首单 items_weight;组内订单 items_hash 相同重量一致。", + "为 null 时返回 null。" + ], + "type": "updated", + "module": "order.wave" + }, + { + "version": "2026.05.20-system-03", + "date": "2026-05-20", + "summary": "新增 storeWarehouse.store.queryPrintQuantityLogs:按 store_id 分页查询面单余额变更日志", + "methods": [ + "storeWarehouse.store.queryPrintQuantityLogs" + ], + "notes": [ + "新增方法:storeWarehouse.store.queryPrintQuantityLogs,用于按货主(store_id)分页查询面单余额变更日志。", + "入参:store_id(必填)、page(可选)、page_size / pageSize(可选,兼容别名)。", + "仅同步 methods/system.json 与本变更记录,不修改业务代码或测试。", + "返回:使用默认分页格式,响应在 `data` 下包含 `list`(变更日志数组)和 `pagination` 对象,`pagination` 字段:`page`、`pageSize`、`total`、`totalPages`、`hasPrevious`、`hasNext`。" + ], + "type": "added", + "module": "storeWarehouse" + }, + { + "version": "2026.05.13-system-01", + "date": "2026-05-13", + "summary": "完善 print.send 的 API 文档与返回说明", + "methods": [ + "print.send" + ], + "notes": [ + "补充请求参数说明:computerId、printer、template、data、type 标为必填,count、timestamp 保持可选。", + "补充 template 的子字段说明:page_width、page_height、template_content。", + "补充响应结构:flag、code、message、printId;其中成功时 code=200。", + "补充错误码说明:1001 对应不支持的打印类型,504 对应打印任务发送失败(包含打印机不存在、脱机、通讯失败等场景)。" + ], + "type": "updated" + }, + { + "version": "2026.05.08-system-06", + "date": "2026-05-08", + "summary": "新增取消拣货任务接口:order.wave.wavePickTaskCancel", + "methods": [ + "order.wave.wavePickTaskCancel" + ], + "notes": [ + "接口功能:取消拣货任务,同时释放关联波次(物理删除波次记录,订单回池)、解绑拣货车、写操作日志。", + "限制:仅允许在任务状态为 0(待开始)、1(拣货中)、2(待复核)时取消;状态为 3(已完成)或 9(已取消)时禁止取消,返回 400。", + "事务内操作:将任务状态更新为 9(已取消)、删除关联波次、清空订单 wave_id(回池)、解绑拣货车、写入 action_log 与 order_pick_trace;若有任一步骤失败则回滚并返回 500。" + ], + "type": "added" + }, + { + "version": "2026.07.01-system-01", + "date": "2026-07-01", + "summary": "storage.directInbound.addItem 参数名修正:entry_order_code → entry_order_id,类型 string → number", + "methods": [ + "storage.directInbound.addItem" + ], + "notes": [ + "文档 params 中 entry_order_code(string)改为 entry_order_id(number),与代码 app/service/systems/inbound_direct_log.js 第 544 行实际校验保持一致", + "同步修正 app/service/systemMethods/storage/direct_inbound.js JSDoc:@param {string} data.entry_order_code → @param {number} data.entry_order_id" + ], + "type": "fixed", + "module": "storage.directInbound" + }, + { + "version": "2026.07.01-system-02", + "date": "2026-07-01", + "summary": "新增 storage.entry.queryEntryLogs 接口文档定义", + "methods": [ + "storage.entry.queryEntryLogs" + ], + "notes": [ + "代码 method 层(systemMethods/storage/entry.js L284)和 systems 层(systems/operation_log.js L318)均已实现,补充文档定义", + "参数:id(number, required)、page(number, optional, 默认1)、pageSize(number, optional, 默认20)" + ], + "type": "added", + "module": "storage.entry" + }, + { + "version": "2026.06.18-system-01", + "date": "2026-06-18", + "summary": "order.pendingOrder.downloadCreateTemplate:模板列顺序调整,店铺名称(shop_nick)从末尾移至第2列B列,紧接*订单号之后", + "methods": [ + "order.pendingOrder.downloadCreateTemplate" + ], + "notes": [ + "调整 Excel 导入模板列顺序:店铺名称(shop_nick)从原第25列(Y列/末尾)移动至第2列(B列),紧跟在*订单号(delivery_order_code)之后。", + "同步更新 description 中的列顺序描述,明确 25 列(A-Y)的完整排列。", + "响应结构中移除冗余的 shop_nick 字段(模板列不属于 API 响应字段)。" + ], + "type": "updated", + "module": "order.pendingOrder" + }, + { + "version": "2026.05.17-system-09", + "date": "2026-05-17", + "summary": "为 storage.receiving.deleteDetail 文档补充约束:收货单已完成/已取消时禁止删除明细", + "methods": [ + "storage.receiving.deleteDetail" + ], + "notes": [ + "在 storage.receiving.deleteDetail 的 description 中补充:若关联收货单状态为 completed(已完成)或 cancelled(已取消),接口会返回删除失败(400),不允许删除明细。", + "在 errors 中补充或合并 400 描述以明确禁止删除已完成/已取消的收货单明细。" + ], + "type": "updated", + "module": "storage" + }, + { + "version": "2026.05.17-system-08", + "date": "2026-05-17", + "summary": "完善 storage.receiving.deleteDetail 文档:补充入参/返回/错误说明,明确用户上下文来源及删除约束", + "methods": [ + "storage.receiving.deleteDetail" + ], + "notes": [ + "补充 storage.receiving.deleteDetail 的参数说明:detail_id(来自请求体,必填);说明 creator_id 与 warehouse_id 来源于当前登录用户(ctx.user.employees_id / ctx.user.store_id)。", + "补充返回结构:成功时返回 code/message/data,data 包含 details(删除后剩余明细)和 selectId(建议选中ID);product_snapshot 若存在将被解析为对象或 null。", + "补充常见错误码:404(明细不存在或无权访问),400(收货单状态/已入库/删除失败),500(服务器异常)。", + "仅文档更新,不修改任何业务实现。" + ], + "type": "updated", + "module": "storage" + }, + { + "version": "2026.05.17-system-05", + "date": "2026-05-17", + "summary": "移除 storage.receiving.addItem(方法已下线/实现不存在)", + "methods": [ + "storage.receiving.addItem" + ], + "notes": [ + "仅同步文档:从 methods/system.json 中移除 storage.receiving.addItem,未修改任何业务代码或实现。", + "该方法已下线或实现不存在;请以当前 methods/system.json 的 SSOT 为准。" + ], + "type": "removed" + }, + { + "version": "2026.05.17-system-04", + "date": "2026-05-17", + "summary": "新增 stock.warehouse.import:仓库商品批量 JSON 导入(数组导入),SKU 为空创建/非空更新,支持 goods_code/货物编码 导入,更新写操作日志", + "methods": [ + "stock.warehouse.import" + ], + "notes": [ + "支持直接传入商品数组 JSON(主方式为数组,兼容 rows/items/list/data 包装)。", + "每项仅需传商品相关字段;SKU 为空时创建新商品,SKU 非空时为更新操作。", + "更新操作会写入操作日志以便审计。", + "支持导入 goods_code(货物编码)字段别名。", + "仅同步文档,不修改业务代码或实现。" + ], + "type": "added" + }, + { + "version": "2026.05.17-system-03", + "date": "2026-05-17", + "summary": "完善 stock.warehouse.handleBatchChange 文档:补充入参/出参/错误示例", + "methods": [ + "stock.warehouse.handleBatchChange" + ], + "notes": [ + "补充方法入参说明:ids/method/value 的字段类型、是否必填、来源与示例;完善响应结构示例与常见错误码说明。", + "仅文档更新,不改业务实现或语义。" + ], + "type": "updated" + }, + { + "version": "2026.05.17-system-02", + "date": "2026-05-17", + "summary": "stock.warehouse.export 由同步改为异步任务并新增进度查询 exportTaskProgress", + "methods": [ + "stock.warehouse.export", + "stock.warehouse.exportTaskProgress" + ], + "notes": [ + "stock.warehouse.export 改为异步提交导出任务:接口返回 task_id 与受理信息,后端异步生成导出文件。", + "新增 stock.warehouse.exportTaskProgress:按 task_id 查询任务状态与进度;当 status=success 时返回 download_url 供客户端下载;未找到时 status=not_found。", + "调用方式:先调用 stock.warehouse.export 获取 task_id,然后轮询 stock.warehouse.exportTaskProgress 直到 status=success 并获取 download_url。" + ], + "type": "updated" + }, + { + "version": "2026.05.17-system-01", + "date": "2026-05-17", + "summary": "新增 stock.warehouse.export:仓库商品导出(支持 where/sort),返回文件下载信息", + "methods": [ + "stock.warehouse.export" + ], + "notes": [ + "新增方法:stock.warehouse.export。复用 stock.warehouse.list 的 where/sort 过滤语义(支持 operator/value/type 标准 where 结构与历史简写)。", + "响应返回导出结果(示例字段:file_key、url),表示生成的 Excel 已上传并可下载/查询。" + ], + "type": "added" + }, + { + "version": "2026.05.16-system-01", + "date": "2026-05-16", + "summary": "同步 setting.expressInterface.create 文档入参:移除未使用的 express_platform_id,标注必填字段", + "methods": [ + "setting.expressInterface.create" + ], + "notes": [ + "移除文档中 express_platform_id(服务端实现未使用);确认必填字段 name/express_code/platform_code;仓库由系统自动填充,禁止传入 warehouse_id/warehouseId。" + ], + "type": "updated" + }, + { + "version": "2026.05.12-system-01", + "date": "2026-05-12", + "summary": "调整订单打印中间态返回结构为 waveGroups(波次 -> 平台 -> 订单)", + "methods": [ + "order.print.getWavePlatformPrintData" + ], + "notes": [ + "主要变更:将方法的主返回结构改为 waveGroups,按波次分组,波次内按平台分组,平台内为订单列表(波次 -> 平台 -> 订单)。", + "兼容性:保留旧字段 platform_groups 与 order_list 作为向后兼容字段,但文档主结构与推荐使用为 waveGroups。", + "返回结构说明:summary(total_waves/total_orders/total_platforms)、wave_ids(通过过滤的波次ID数组)、waveGroups(数组,项含 wave_id、wave_no、order_count、platforms[...],platforms项含 platform、platform_name、order_count、orders[...])、ext(missing_wave_ids、filtered_wave_ids)。", + "errors:保留 400 / 500 不变。" + ], + "type": "modified" + }, + { + "version": "2026.05.11-system-05", + "date": "2026-05-11", + "summary": "order.wave.batchList:支持 express/print 分配状态筛选,入参改为英文枚举(express/print)", + "methods": [ + "order.wave.batchList" + ], + "notes": [ + "修复 where.express_assignment_status 可按快递分配状态筛选。", + "新增 where.print_assignment_status 筛选(按打印分配聚合判断)。", + "express_assignment_status / print_assignment_status 要求使用英文枚举值:express=unassigned/partially_assigned/assigned,print=unprinted/partially_printed/printed;storage_assignment_status 继续兼容中文枚举(未分配/部分分配/已分配)。", + "若传入非法枚举值,接口返回 400(参数校验失败),message 中会说明允许取值。" + ], + "type": "updated" + }, + { + "version": "2026.05.11-system-04", + "date": "2026-05-11", + "summary": "调整 order.wave.waveStrategyFetchAdmin:由创建任务改为直接创建波次(不创建拣货任务)", + "methods": [ + "order.wave.waveStrategyFetchAdmin" + ], + "notes": [ + "接口行为变更:按策略直接抓取命中订单并创建波次,不再创建拣货任务(不返回 task_id/task_no 等任务字段)。", + "响应调整为建波结果:fetch_state(1=成功/2=失败)、wave_ids、wave_nos、created_wave_count、created_order_count、order_ids、(可选)wave_prefix、wave_prefix_source、tip/message。", + "错误调整:策略校验失败返回 400(并可能返回 validation_errors),缺少仓库上下文返回 400,建波失败返回 500 并在 message 中说明。" + ], + "type": "updated" + }, + { + "version": "2026.05.11-system-03", + "date": "2026-05-11", + "summary": "更新 pick.query:由查询拣货明细调整为按 keyword 获取/创建拣货任务", + "methods": [ + "pick.query" + ], + "notes": [ + "入参由 waybill_code/full_display 调整为 keyword(支持运单号或波次号)。", + "接口语义调整为任务化返回:命中活动任务则返回 existing 任务ID;无活动任务则创建并返回 created 任务ID。", + "新增任务归属冲突错误:当活动任务创建人非当前用户时返回冲突提示,并附带创建人及任务ID信息。" + ], + "type": "updated" + }, + { + "version": "2026.05.11-system-02", + "date": "2026-05-11", + "summary": "新增 pick.wavePickTaskCurrent:PDA 无参查询当前进行中拣货任务", + "methods": [ + "pick.wavePickTaskCurrent" + ], + "notes": [ + "新增 PDA 专用无参接口 pick.wavePickTaskCurrent。", + "按当前登录用户上下文(pick_user_id + warehouse_id)查询状态在 0/1/2 的最新任务。", + "命中返回 task_id,未命中返回 task_id=null。" + ], + "type": "added" + }, + { + "version": "2026.05.10-system-04", + "date": "2026-05-10", + "summary": "pick.wavePickTaskDetail 新增按任务类型区分的 picking_view 形态输出", + "methods": [ + "pick.wavePickTaskDetail" + ], + "notes": [ + "新增响应字段:picking_view(object),按 task.pick_mode 区分 5 种形态输出。", + "picking_view 字段说明:mode_code, mode_name, require_box_allocations, group_by, sort_by, items[](每项含 space_id、space_name、location_space、item_code、item_name、stock_id、total_qty、box_allocations[])。", + "当 pick_mode=1/3/4 时 require_box_allocations=true;当 pick_mode=2/5 时 require_box_allocations=false。" + ], + "type": "updated" + }, + { + "version": "2026.05.10-system-02", + "date": "2026-05-10", + "summary": "order.wave.waveStrategyFetchPda/Admin 返回新增 fetch_state 三态与简短 tip", + "methods": [ + "order.wave.waveStrategyFetchPda", + "order.wave.waveStrategyFetchAdmin" + ], + "notes": [ + "新增返回字段:fetch_state(number)、tip(string)、can_enter_pick_flow(boolean)", + "fetch_state 含义:1=创建成功(返回 task_id/task_no),2=普通失败(task_id=null),3=存在未完成任务(返回 existing task_id/task_no,前端可直接进入拣货流程)", + "当 fetch_state=3 时,字段 can_enter_pick_flow=true,表示前端可直接进入拣货流程;tip 为简短提示文本" + ], + "type": "updated" + }, + { + "version": "2026.05.10-system-03", + "date": "2026-05-10", + "summary": "裁剪 pick.wavePickTaskDetail 返回:移除 waves/orders,精简 task 并补充 boxes 拣货统计字段", + "methods": [ + "pick.wavePickTaskDetail" + ], + "notes": [ + "移除响应中的 waves 与 orders 子表,接口仅返回精简的 task、boxes、picking_details 与 picking_summary。", + "task 子字段裁剪为:task_id, task_no, status, pick_mode, start_at, finish_at, batch_no。", + "boxes 补充并明确返回:ref_label(箱参考标签)、required_qty(箱内需拣总数)、picked_qty(已拣数量)。", + "本次变更为文档层面的返回裁剪,前端应以新字段集合为准,旧字段可能不再返回。" + ], + "type": "updated" + }, + { + "version": "2026.05.10-system-01", + "date": "2026-05-10", + "summary": "order.wave.waveStrategyList 新增 strategy_type 最小过滤(散单/团购)", + "methods": [ + "order.wave.waveStrategyList" + ], + "notes": [ + "新增 strategy_type 过滤,仅 1/2", + "支持顶层 strategy_type 和 where.strategy_type,顶层优先", + "当前不引入其他 where 字段" + ], + "type": "updated" + }, + { + "version": "2026.05.09-system-02", + "date": "2026-05-09", + "summary": "新增 pick.wavePickTaskDetail:按任务ID解析拣货任务详情", + "methods": [ + "pick.wavePickTaskDetail" + ], + "notes": [ + "新增 pick.wavePickTaskDetail:传入 task_id 获取拣货任务完整信息,包含主表字段(task/pick_mode/status/wave_count/order_count/box_count 等)及三张子表数据(waves/orders/boxes)。", + "安全限制:接口会校验当前登录用户(operator_id/employees_id)与任务的 pick_user_id 是否一致;不一致时直接返回 403,不返回任何拣货信息。", + "鉴权配置:noNeedRight=true,noNeedAuth=true,isNeedLogin=true。" + ], + "type": "added" + }, + { + "version": "2026.05.08-system-05", + "date": "2026-05-08", + "summary": "order.wave.batchList:新增 source 字段并支持 where.source 过滤,返回 list item 中新增 source 字段", + "methods": [ + "order.wave.batchList" + ], + "notes": [ + "新增 where.source(可选,number)用于按来源过滤:0=普通波次(正常后台操作),1=管理后台策略任务,2=PDA策略任务;不传则不过滤。", + "响应 list 每条记录新增字段 source(number),用于区分波次来源。", + "仅更新文档,业务代码不在此变更范围。" + ], + "type": "updated" + }, + { + "version": "2026.05.08-system-04", + "date": "2026-05-08", + "summary": "完善 order.wave.wavePickTaskList 文档:补充入参、分页与返回字段兼容说明", + "methods": [ + "order.wave.wavePickTaskList", + "order.wave.wavePickTaskCancel" + ], + "notes": [ + "入参补充:warehouse_id(必填)、status(支持单值或数组,建议传数组)、source、keyword、page_no、page_size;保留 pagination 对象以兼容旧客户端。", + "兼容说明:接口同时支持历史 where 结构与顶层参数;当存在同名顶层参数时以顶层参数优先;pagination 支持 page/current 与 pageSize/size 别名。", + "返回格式:响应包含 total 与 list;list 每项包含字段:task_id、task_no、status、source、pick_mode、wave_count、order_count、box_count、operator_id、operator_name、start_at、finish_at、created_at。为兼容旧客户端,响应同时保留旧字段:pick_user_id、pick_user_name、start_time、finish_time、create_time。", + "入参 strategy_id 当前主表未存,接口会忽略该过滤,不建议使用。", + "默认排序:create_time desc.", + "文档变更:移除 order.wave.wavePickTaskCancel 的入参 operator_id 与 warehouse_id;入参改为仅支持 task_ids(数组,必填),不再兼容单个 task_id;操作人与仓库由请求上下文(例如当前登录用户上下文)自动获取;若上下文缺失接口将返回错误。响应补充批量结果字段:cancelled_count、task_ids、task_nos(若后端返回)。仅更新文档,未修改业务实现。" + ], + "type": "updated" + }, + { + "version": "2026.05.08-system-03", + "date": "2026-05-08", + "summary": "升级按策略抓取接口为创建任务主流程:order.wave.waveStrategyFetchPda / order.wave.waveStrategyFetchAdmin", + "methods": [ + "order.wave.waveStrategyFetchPda", + "order.wave.waveStrategyFetchAdmin" + ], + "notes": [ + "将 PDA/Admin 场景的按策略抓取接口由受理壳方法升级为 '创建任务主流程':接口会执行参数校验并在同步响应中创建任务记录(state=created),返回 task_id、task_no、plan 与 plan_summary 供前端展示与后续查询。", + "入参新增/扩展与创建流程相关字段:至少包含 cart_id(关联拣货车/作业车ID)、source(操作来源语义)并保留并透传 strategy_id 与 strategy_params(策略参数),以支持在创建阶段对策略进行局部覆盖或透传。", + "成功返回示例字段:state=created、task_id、task_no、plan(对象)和 plan_summary(字符串);失败场景会返回 validation_errors(数组,每项含 field/message)或 message 描述创建失败原因。", + "边界说明:当前为最小主流程(创建与计划预览),后续扫描/任务执行阶段(如实际抓取订单、写入 wave 等)将在后续版本中追加与完善。" + ], + "type": "updated" + }, + { + "version": "2026.05.08-system-02", + "date": "2026-05-08", + "summary": "调整按策略抓取壳方法:order.wave.waveStrategyFetch 更名为 order.wave.waveStrategyFetchPda,并新增 order.wave.waveStrategyFetchAdmin", + "methods": [ + "order.wave.waveStrategyFetch", + "order.wave.waveStrategyFetchPda", + "order.wave.waveStrategyFetchAdmin" + ], + "notes": [ + "waveStrategyFetchPda 仅用于 PDA 场景", + "waveStrategyFetchAdmin 仅用于后台管理场景", + "两者当前均为壳子受理方法,不执行真实抓取" + ], + "type": "updated" + }, + { + "version": "2026.05.08-system-01", + "date": "2026-05-08", + "summary": "新增 order.wave.waveStrategyFetch:按策略提交抓取任务(壳子方法)", + "methods": [ + "order.wave.waveStrategyFetch" + ], + "notes": [ + "当前方法为壳子方法:仅受理并返回任务受理信息,不执行真实抓取逻辑,后续补齐执行链路。" + ], + "type": "added" + }, + { + "version": "2026.05.07-system-05", + "date": "2026-05-07", + "summary": "新增 order.wave.waveStrategyCreate 与 order.wave.waveStrategyUpdate:波次策略创建与更新接口(含参数校验与版本推进)", + "methods": [ + "order.wave.waveStrategyCreate", + "order.wave.waveStrategyUpdate" + ], + "notes": [ + "仓库 ID 与创建人(creator_name)由当前登录仓库/操作者上下文获取,接口不接受外部覆盖。", + "入参 allowed_owners 与 allowed_expresses 会校验是否在系统可用范围内(基于仓库签约货主或系统快递列表),若存在非法值接口会直接报错(400)。", + "max_same_structure 受仓库配置 min_group_order_fetch_quantity 限制:若传入值 >= min_group_order_fetch_quantity,则自动下调为 min_group_order_fetch_quantity - 1(最小值为 1)。", + "新建/更新成功后会触发仓库的 wave_strategy_version 自增(+1)并失效相关仓库配置缓存,调用方可通过策略版本推进或缓存变化感知策略已生效。" + ], + "type": "added" + }, + { + "version": "2026.05.07-system-06", + "date": "2026-05-07", + "summary": "收敛 order.wave.waveStrategyFallbackOrderList 返回字段,限定 where 白名单,补充 order.wave.singleFetchByIds 别名与返回语义", + "methods": [ + "order.wave.waveStrategyFallbackOrderList", + "order.wave.singleFetchByIds" + ], + "notes": [ + "收敛 order.wave.waveStrategyFallbackOrderList response.list 字段为 id, delivery_no, tracking_no, items_count, items_total, sys_logistics_name, store_name, province, sys_platform_name, item_snapshot;item_snapshot 格式示例:商品名称*数量|...。", + "限制 order.wave.waveStrategyFallbackOrderList.where 白名单,禁止传入 warehouse_id / warehouseId;传入未列出字段或别名冲突将返回 400。", + "补充 order.wave.singleFetchByIds:明确支持 ids / order_ids / orderIds 三个别名(优先顺序 ids -> order_ids -> orderIds)并说明返回字段 fetched_order_ids、excluded_existing_wave_order_ids、skipped_order_ids、not_found_order_ids 的语义与兼容性。" + ], + "type": "updated" + }, + { + "version": "2026.05.07-system-04", + "date": "2026-05-07", + "summary": "更新 order.wave.waveStrategyFallbackOrderList,新增商品快照字段 item_snapshot", + "methods": [ + "order.wave.waveStrategyFallbackOrderList" + ], + "notes": [ + "item_snapshot 返回格式为 商品名称1*数量|商品名称2*数量" + ], + "type": "updated" + }, + { + "version": "2026.05.07-system-03", + "date": "2026-05-07", + "summary": "新增 order.wave.waveStrategyQuickScan 与进度查询接口", + "methods": [ + "order.wave.waveStrategyQuickScan", + "order.wave.waveStrategyQuickScanTaskProgress" + ], + "notes": [ + "同仓只允许一个扫描任务并使用缓存锁;扫描范围为当前表非待审核、未分配波次且订单策略版本与仓库当前版本不一致的订单;命中策略标记 wave_scan_result=1,否则=2" + ], + "type": "added" + }, + { + "version": "2026.05.07-system-02", + "date": "2026-05-07", + "summary": "新增 order.wave.waveStrategyList:查询当前仓库波次策略列表", + "methods": [ + "order.wave.waveStrategyList" + ], + "notes": [ + "从 wms_wave_strategy 拉取当前仓库的波次策略列表,分页返回" + ], + "type": "added" + }, + { + "version": "2026.05.07-system-01", + "date": "2026-05-07", + "summary": "移除 order.wave.singleOrderFetchDetailList,新增 order.wave.waveStrategyFallbackOrderList(内置固定筛选条件)", + "methods": [ + "order.wave.singleOrderFetchDetailList", + "order.wave.waveStrategyFallbackOrderList" + ], + "notes": [ + "移除 order.wave.singleOrderFetchDetailList。", + "新增 order.wave.waveStrategyFallbackOrderList。", + "新接口基于订单通用查询口径,固定内置筛选条件:step != 0、wave_id = 0、wave_scan_result = 2。" + ], + "type": "updated" + }, + { + "version": "2026.05.06-system-06", + "date": "2026-05-06", + "summary": "新增 order.wave.singleOrderFetchDetailList:订单级散单候选明细视图", + "methods": [ + "order.wave.singleOrderFetchDetailList" + ], + "notes": [ + "新增 order.wave.singleOrderFetchDetailList:提供订单级的散单候选明细列表,返回按订单聚合的明细(非分组级)。", + "返回订单级而非分组级;响应每项包含订单 id、group_count、item_detail_machine、item_detail_machine_snapshot、item_detail、item_snapshot、logistics_name、store_id、distinguish_express、create_at 与 status_summary 等关键字段。", + "仍沿用 same_order_quantity 阈值来排除团购命中分组(仅保留 group_count < same_order_quantity 的候选项)。", + "singleOrderFetchList 暂保留以兼容现有前端,前端可在切换到订单级视图后迁移到本接口。" + ], + "type": "added" + }, + { + "version": "2026.05.06-system-05", + "date": "2026-05-06", + "summary": "storage.receiving.get 返回扩展:data.details[*] 新增 box_remainder、box_weight", + "methods": [ + "storage.receiving.get" + ], + "notes": [ + "storage.receiving.get 的响应在 data.details[*] 中新增可选字段:box_remainder(箱内剩余数量/零散数量,number,默认 0)与 box_weight(实测箱重,number,默认 0)。", + "兼容性:新增字段为可选,旧客户端无需修改;建议前端在需要展示箱内余量/箱重时使用这些字段。" + ], + "type": "updated" + }, + { + "version": "2026.05.06-system-04", + "date": "2026-05-06", + "summary": "storage.receiving.getReceivingDetail 返回扩展:明细增加 box_remainder、box_weight;storage.receiving.completeReceiving 通知包含这两个字段", + "methods": [ + "storage.receiving.getReceivingDetail", + "storage.receiving.completeReceiving" + ], + "notes": [ + "为支持箱规统计与通知回传,getReceivingDetail 的明细项(receiving.details 或 data.details)在响应中新增可选字段:box_remainder(箱内剩余数量/零散数量,number)与 box_weight(实测箱重,number,单位同系统重量)。", + "completeReceiving 在完成收货后会发送通知(或回调),通知 payload/metadata 中将包含每条明细的 box_remainder 与 box_weight 字段,供下游系统/前端展示或审计使用。", + "兼容性:新增字段为可选,旧客户端在未使用这些字段时无需变更。" + ], + "type": "updated" + }, + { + "version": "2026.05.06-system-03", + "date": "2026-05-06", + "summary": "storage.receiving.detailChange:新增入参/出参字段 box_remainder、box_weight", + "methods": [ + "storage.receiving.detailChange" + ], + "notes": [ + "为支持箱规细化与回写,detailChange 新增可选入参 box_remainder(箱内余量/零散数量)和 box_weight(实测箱重,单位同系统重量),写入后会回写至明细并在响应 data 中返回对应字段。", + "兼容性:新增字段为可选,不传入则不影响现有调用;建议前端在需要回写箱余与箱重时一并传入。" + ], + "type": "updated" + }, + { + "version": "2026.05.06-system-02", + "date": "2026-05-06", + "summary": "新增 order.wave.singleFetchByIds:按订单ID抓取到一个散单波次", + "methods": [ + "order.wave.singleFetchByIds" + ], + "notes": [ + "新增 order.wave.singleFetchByIds:按入参 ids(兼容 order_ids/orderIds)去重后筛选当前仓库内待处理且不在波次中的订单,若存在可抓取订单则创建单个散单波次并把这些订单写入该波次(不区分快递);成功后批量写入订单操作日志;若无可抓取订单返回 wave_id=0。", + "接口行为严格对齐实现:过滤条件包含 step in [1,2,3]、status != 'cancel'、outbound_status != 'padding';已在波次的订单会被排除并返回 excluded_existing_wave_order_ids;响应包含 ids、wave_id、wave_no、fetched_order_ids、fetched_order_count、excluded_existing_wave_order_ids、skipped_order_ids、not_found_order_ids。" + ], + "type": "added" + }, + { + "version": "2026.05.06-system-01", + "date": "2026-05-06", + "summary": "新增 order.wave.groupFetch 与 order.wave.singleFetch;order.wave.fetch 保留兼容别名;抓取进度补充上限字段", + "methods": [ + "order.wave.groupFetch", + "order.wave.singleFetch", + "order.wave.fetch", + "order.wave.fetchTaskProgress" + ], + "notes": [ + "新增 order.wave.groupFetch:抓取团购接口(异步任务提交),参数 structure_list 与原 fetch 一致。", + "新增 order.wave.singleFetch:抓取散单接口(异步任务提交),在 structure_list 每项新增必填字段 max_fetch_quantity(最大抓取上限,订单数,正整数)。", + "order.wave.fetch 保留为兼容别名(等同 groupFetch),避免误导客户端。", + "groupFetch/singleFetch/fetch 的响应新增可选字段 fetch_mode;singleFetch 响应额外返回 max_fetch_quantity。", + "order.wave.fetchTaskProgress 的响应增加单模式相关字段:fetch_mode、max_fetch_quantity、limit_reached、stop_reason,用于描述散单抓取的上限与停止原因。" + ], + "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-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": "updated" + }, + { + "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 查询全字段列表并支持缓存", + "methods": [ + "setting.expressInterface.listByWarehousePlatformCode" + ], + "notes": [ + "新增 setting.expressInterface.listByWarehousePlatformCode:按 warehouse_id + platform_code 返回快递接口的全字段数组(不分页),每条记录包含 express 关联对象(id/code/name/platform 等)。", + "支持缓存,缓存键由 warehouse_id + platform_code 组成;缓存命中将直接返回缓存结果以提升查询性能。", + "在创建/更新/删除操作(setting.expressInterface.create/update/delete)后,会主动清理对应 warehouse_id + platform_code 的缓存以确保数据一致性。" + ], + "type": "added" + }, + { + "version": "2026.04.17-system-08", + "date": "2026-04-17", + "summary": "新增快递编码管理模块批量软删除接口 setting.express.delete", + "methods": [ + "setting.express.delete" + ], + "notes": [ + "新增批量软删除接口 setting.express.delete:接受 ids(数组、逗号字符串或单值),对属于当前仓库且未被删除的记录执行软删除(设置 deleted_at),并清理 express 列表缓存。", + "当任一目标记录的 code 被 wms_express_interface.express_code 引用时,接口会拒绝删除并返回 409,错误信息中包含被引用的编码列表。", + "响应包含 ids、deleted_ids、already_deleted_ids 与 status,已删除与未删除的 id 会明确分类。仅记录已实现行为。" + ], + "type": "added" + }, + { + "version": "2026.04.17-system-05", + "date": "2026-04-17", + "summary": "新增文档分组:平台编码管理模块(收口 index.getPlatformList 与 setting.platform.*)", + "methods": [ + "index.getPlatformList", + "setting.platform.list", + "setting.platform.create", + "setting.platform.update", + "setting.platform.delete" + ], + "notes": [ + "新增独立文档分组 '平台编码管理模块',将平台基础列表(index.getPlatformList)与平台设置管理接口(setting.platform.*)归并为单一分组以便维护;仅文档变更,不修改实现。", + "文档中仅包含已实现的方法与字段,未新增或推断不存在的参数/返回字段。" + ], + "type": "added" + }, + { + "version": "2026.04.17-system-04", + "date": "2026-04-17", + "summary": "新增独立平台设置模块 setting.platform(wms_platfrom_setting)及其 CRUD 接口:list/create/update/delete。", + "methods": [ + "setting.platform.list", + "setting.platform.create", + "setting.platform.update", + "setting.platform.delete" + ], + "notes": [ + "新增独立模块 setting.platform,映射数据表 wms_platfrom_setting;list 支持 where(id/code/name/platform_code/quickWhere)与 pagination(兼容 page/pageSize/page_size);create/update 要求 platform_code 必须存在于系统平台表(wms_platform),且禁止越权写入 warehouse_id;delete 需传入 id 并校验当前仓库范围。" + ], + "type": "added" + }, + { + "version": "2026.04.15-system-07", + "date": "2026-04-15", + "summary": "将 docs/order-workbench-list-api.md 引用统一为 window 链接格式", + "methods": [ + "order.list", + "order.reviewOrder.list", + "order.pendingOrder.list", + "order.outboundOrder.list", + "order.expectionOrder.list", + "order.entrustOrder.list", + "order.deliveryOrder.list", + "order.deliveryExpectionOrder.list" + ], + "notes": [ + "将所有 methods/system.json 中指向 docs/order-workbench-list-api.md 的说明统一替换为 docs/order-workbench-list-api.md 格式,以便 HTML 渲染识别为 window 链接。", + "仅修改 methods/system.json 的文档字段,不涉及任何业务代码或接口契约变化。" + ], + "type": "updated" + }, + { + "version": "2026.04.15-system-06", + "date": "2026-04-15", + "summary": "订单工作台列表文档补全 raw 字段字典与中文语义说明", + "methods": [ + "order.list", + "order.reviewOrder.list", + "order.pendingOrder.list", + "order.outboundOrder.list", + "order.expectionOrder.list", + "order.entrustOrder.list", + "order.deliveryOrder.list", + "order.deliveryExpectionOrder.list", + "order.archiveOrder.list" + ], + "notes": [ + "在 docs/order-workbench-list-api.md 中补充所有订单列表通用 raw 字段字典,明确每个字段的中文语义与 enum 取值。", + "补充 express_numbers / waybill_codes 两个服务层派生字段说明,便于前端直接渲染多个快递号。", + "methods/system.json 中所有订单 list 的 response.list 描述已指向该字段字典章节。" + ], + "type": "updated" + }, + { + "version": "2026.04.15-system-05", + "date": "2026-04-15", + "summary": "基础模块新增快递/平台列表查询接口并设置为不鉴权,复用缓存 service", + "methods": [ + "index.getExpressList", + "index.getPlatformList" + ], + "notes": [ + "新增 index.getExpressList,归属基础模块(module=index),对应 app/service/systems/express.js 中的 getExpressList。", + "index.getExpressList 设置为不鉴权,不需要 Authorization 头。", + "新增 index.getPlatformList,归属基础模块(module=index),对应 app/service/systems/platform.js 中的 getPlatformList。", + "index.getPlatformList 设置为不鉴权,不需要 Authorization 头。", + "快递列表与平台列表都支持缓存优先,缓存未命中时回源数据库并写入缓存。", + "平台列表支持缓存优先,缓存未命中时回源 wms_platform 并写入缓存。" + ], + "type": "added" + }, + { + "version": "2026.04.15-system-02", + "date": "2026-04-15", + "summary": "签约策略字段元信息新增 default_express_code / default_platform_code list 选项", + "methods": [ + "storeWarehouse.store.getPolicyConfigFields" + ], + "notes": [ + "getPolicyConfigFields 现在返回 default_express_code 与 default_platform_code 两个 list 字段,并从 wms_express / wms_platform 读取选项列表。", + "默认值仍保留为 default_express_code=STO、default_platform_code=TB。" + ], + "type": "updated" + }, + { + "version": "2026.04.15-system-03", + "date": "2026-04-15", + "summary": "签约策略字段移除 sku_visibility,receive_mode options 改为 value/label 结构", + "methods": [ + "storeWarehouse.store.savePolicyConfig", + "storeWarehouse.store.getPolicyConfigFields" + ], + "notes": [ + "策略字段定义不再包含 sku_visibility,历史值读取时仍会被归一化忽略。", + "receive_mode 的 options 改为 [{ value, label }] 格式,便于前端直接渲染。" + ], + "type": "updated" + }, + { + "version": "2026.04.15-system-04", + "date": "2026-04-15", + "summary": "按文件模块拆分 order 目录系统文档分组,覆盖订单工作台入口及各子模块方法", + "methods": [ + "order.list", + "order.manualOutboundOrder", + "order.badgeCount", + "order.outboundOrder.manualOutboundOrder", + "order.reviewOrder.list", + "order.reviewOrder.reviewOrder", + "order.pendingOrder.list", + "order.pendingOrder.reverseReviewOrder", + "order.pendingOrder.markPendingOutboundOrder", + "order.pendingOrder.cancelOrder", + "order.outboundOrder.list", + "order.expectionOrder.list", + "order.entrustOrder.list", + "order.deliveryOrder.list", + "order.deliveryExpectionOrder.list", + "order.archiveOrder.list" + ], + "notes": [ + "按 app/service/systemMethods/order 下的实际对外方法补全 methods/system.json 文档,只覆盖 system,不处理 qimen。", + "order 文档已按 index / reviewOrder / pendingOrder / outboundOrder / expectionOrder / entrustOrder / deliveryOrder / deliveryExpectionOrder / archiveOrder 拆成多个模块分组。", + "同步根据当前代码意图补充 params / response / errors,且不再把 index.js 已移除的兼容接口写回文档。" + ], + "type": "updated" + }, + { + "version": "2026.04.15-system-01", + "date": "2026-04-15", + "summary": "货主主体配置默认补齐 default_express_code / default_platform_code", + "methods": [ + "store.createStore", + "store.createWarehouse" + ], + "notes": [ + "当 subject_config 未传或缺少字段时,自动补齐 default_express_code=STO、default_platform_code=TB,并保留现有的 max_notice_webhook_count 默认值。", + "同步更新 methods/system.json 中 store.createStore 与 store.createWarehouse 的参数说明。" + ], + "type": "updated" + }, + { + "version": "2026.04.14-system-01", + "date": "2026-04-14", + "summary": "库存列表新增货主名称字段 stock.store_name", + "methods": [ + "storage.inventory.list" + ], + "notes": [ + "在 methods/system.json 的 storage.inventory.list response 中补充 stock.store_name:来源于签约表 store_remask,若无签约关系则为 null。", + "只同步文档,不修改业务代码。" + ], + "type": "updated" + }, + { + "version": "2026.04.13-system-01", + "date": "2026-04-13", + "summary": "补全 storage.receiving.detailChange 的入参/出参契约与错误码说明", + "methods": [ + "storage.receiving.detailChange" + ], + "notes": [ + "在 methods/system.json 中补充 storage.receiving.detailChange 的 params/response/errors,明确 id 与 receiving_id 必填。", + "说明 expiry_date 小于当前日期时返回 400 且 message 为 \"到期日期已过期,不能录入收货\"。", + "说明当传入 system_product_id 时会回填条码、重量、箱规、商品名称与 product_snapshot;未传时 barcode/product_name 也可单独更新。", + "同步补充文档:docs/storage-receiving-api.md 中新增 detailChange 段落。" + ], + "type": "updated" + }, + { + "version": "2026.04.07-system-01", + "date": "2026-04-07", + "summary": "修正 warehouse.getAreaRacks 的鉴权/权限链路文档,明确该接口需要 登录并走权限校验。", + "methods": [ + "warehouse.getAreaRacks" + ], + "notes": [ + "对齐当前 system 文档中的 isNeedAuth=true、isNeedLogin=true。", + "用于补充该接口权限链路修正文档的历史上下文,不改变 methods/system.json 的 SSOT 角色。" + ] + }, + { + "version": "2026.04.07-system-02", + "date": "2026-04-07", + "summary": "补充签约配置相关接口文档,覆盖策略字段元信息查询与面单数量人工调整。", + "methods": [ + "storeWarehouse.store.getPolicyConfigFields", + "storeWarehouse.store.adjustPrintQuantity" + ], + "notes": [ + "getPolicyConfigFields 说明为获取签约策略可配置字段元信息列表。", + "adjustPrintQuantity 说明为人工调整签约关系下的面单余额并记录变更日志,并 明确 id、change_quantity、reason 等关键入参。" + ] + }, + { + "version": "2026.04.07-system-03", + "date": "2026-04-07", + "summary": "对外命名从 qimenConfig 收口为 apiConfig,并在接口配置文档中强调 interface_type_id 校验。", + "methods": [ + "storeWarehouse.store.listApiConfig", + "storeWarehouse.store.saveApiConfig", + "storeWarehouse.store.deleteQimenConfig" + ], + "notes": [ + "文档对外统一使用 apiConfig / api_config 命名,减少 qimenConfig 历史别名歧义。", + "saveApiConfig 要求 interface_type_id 为必填且必须指向已存在的 wms_interface_type 记录。", + "listApiConfig / deleteQimenConfig 同步补充 interface_type_id 字段说明。" + ] + }, + { + "version": "2026.04.07-system-04", + "date": "2026-04-07", + "summary": "补充 /api/docs 文档体验增强说明,新增查看变更记录与查看原文 JSON 的入口说明。", + "methods": [ + "/api/docs", + "/api/docs/:docName", + "/api/docs/:docName/raw", + "/api/docs/:docName/changes" + ], + "notes": [ + "sidecar 变更数组用于承载文档历史说明,不替代 methods/system.json 作为 SSOT。", + "原文 JSON 入口继续用于直接查看当前生效文档。" + ] + }, + { + "version": "2026.04.07-system-05", + "date": "2026-04-07", + "summary": "修正 storeWarehouse.store.adjustPrintQuantity 的面单余额调整语义:由增减/累加改为覆盖设置目标余额。", + "methods": [ + "storeWarehouse.store.adjustPrintQuantity" + ], + "notes": [ + "adjustPrintQuantity 当前兼容 print_quantity、target_quantity、change_quantity、adjust_quantity 作为目标面单余额输入,不再按增减量解释。", + "变更日志中的 change_quantity 由 before/after 自动计算差值,以兼容历史审计与展示。" + ] + }, + { + "version": "2026.04.07-system-06", + "date": "2026-04-07", + "summary": "按接口类型分类限制必填字段,OPEN_API 创建时自动生成 self_app_key/self_app_secret", + "methods": [ + "storeWarehouse.store.saveApiConfig" + ], + "notes": [ + "QM_WMS 类型须填写 qimen_app_key/qimen_customer_id/qimen_warehouse_code;OPEN_API 类型三个奇门字段非必填,创建时自动生成 self_app_key(WMS+32位HEX)和 self_app_secret(64位HEX),更新时保留已有密钥。" + ], + "type": "changed" + }, + { + "version": "2026.04.07-system-07", + "date": "2026-04-07", + "summary": "新增接口类型列表查询接口,归属基础模块,无需权限", + "methods": [ + "index.listInterfaceTypes" + ], + "notes": [ + "返回所有已启用的接口类型(wms_interface_type),包含 id、interface_code、interface_name、interface_category、description 字段。设置 isNeedAuth: false, isNeedLogin: true。" + ], + "type": "added" + }, + { + "version": "2026.04.07-system-08", + "date": "2026-04-07", + "summary": "app_name 改为必传参数", + "methods": [ + "storeWarehouse.store.saveApiConfig" + ], + "notes": [ + "app_name 不再有默认值自动生成逻辑,调用方必须传入非空的 app_name,否则返 回 400 错误。" + ], + "type": "changed" + }, + { + "version": "2026.04.07-system-09", + "date": "2026-04-07", + "summary": "新增收货单快捷入库上架接口", + "methods": [ + "storage.inventory.quickPutaway" + ], + "notes": [ + "新建 storage.inventory 库存操作模块。quickPutaway 从收货单直接生成入库单 (SCRK)并写入 wms_storage 库存表,同时更新 wms_stock_warehouse 库存数量(悲观行锁),回填收货明细入库状态。要求收货单已完成且所有明细已匹配系统商品。" + ], + "type": "added" + }, + { + "version": "2026.04.08-system-01", + "date": "2026-04-08", + "summary": "新增收货单与入库单匹配入库接口", + "methods": [ + "storage.inventory.matchPutaway" + ], + "notes": [ + "接收多个收货单和入库单,按商品(stock_warehouse_id)进行数量匹配入库,完 成后根据入库单来源(QM/API)自动触发回传。入参为 receiving_ids(数组)和 entry_order_ids(数组),返回匹配汇总、各收货单入库状态、各入库单状态及回传结果。isNeedAuth=true, isNeedLogin=true, isNeedRight=false。" + ], + "type": "added" + }, + { + "version": "2026.04.08-system-02", + "date": "2026-04-08", + "summary": "saveApiConfig 新增 callback_url 可选参数", + "methods": [ + "storeWarehouse.store.saveApiConfig" + ], + "notes": [ + "新增 callback_url 参数(VARCHAR(500),可选),用于 OPEN_API 类型入库单的 回调地址配置。" + ], + "type": "changed" + }, + { + "version": "2026.04.08-system-03", + "date": "2026-04-08", + "summary": "serializeQimenConfig 新增返回 callback_url 字段,影响 list 和 listApiConfig 两个接口", + "methods": [ + "storeWarehouse.store.list", + "storeWarehouse.store.listApiConfig" + ], + "notes": [ + "serializeQimenConfig() 序列化方法新增 callback_url(string)字段。storeWarehouse.store.list 返回的每条记录 api_config 对象中包含 callback_url;storeWarehouse.store.listApiConfig 返回的 list 数组中每条配置包含 callback_url。" + ], + "type": "changed" + }, + { + "version": "2026.04.08-system-04", + "date": "2026-04-08", + "summary": "新增库存移库(库位转移)接口", + "methods": [ + "storage.inventory.transferLocation" + ], + "notes": [ + "新增 storage.inventory.transferLocation 接口,支持批量多商品多库位移库, 包含部分数量移库与全量移库。入参为 warehouse_id(仓库ID)和 transfers 数组(storage_id、target_space_id、quantity),触发 storage_transfer_completed 通知事件, 每条移库记录独立操作日志。isNeedAuth=true, isNeedLogin=true。" + ], + "type": "added" + }, + { + "version": "2026.04.08-system-05", + "date": "2026-04-08", + "summary": "简化移库接口入参,从批量 transfers 数组改为单条移库", + "methods": [ + "storage.inventory.transferLocation" + ], + "notes": [ + "移除 warehouse_id 和 transfers 数组入参,改为扁平的 storage_id + target_space_id + quantity 三个顶层参数。warehouse_id 从库存记录自动获取,接口从批量移库简化为单商品单库位移库。响应结构同步简化为单条结果对象。" + ], + "type": "modified" + }, + { + "version": "2026.04.08-system-06", + "date": "2026-04-08", + "summary": "新增商品库存明细查询接口", + "methods": [ + "stock.warehouse.getStockDetail" + ], + "notes": [ + "新增 stock.warehouse.getStockDetail 接口,按库位/批次维度查询商品库存分布。入参为 stock_id(必填,商品库存ID)和 pagination(可选,含 page/pageSize)。返回 stockItem(商品概要)、storageList(wms_storage 明细数组,含批次号、库位、数 量、锁定数量、生产日期、过期日期等,关联 location_space 库位信息)、pagination 分页信息。isNeedAuth=false, isNeedLogin=true。底层调用 stockStore.getStockDetail,自动校验商品归属当前仓库。" + ], + "type": "added" + }, + { + "version": "2026.04.08-system-07", + "date": "2026-04-08", + "summary": "新增入参 group_by_batch,支持按批次维度切换库存明细聚合方式", + "methods": [ + "stock.warehouse.getStockDetail" + ], + "notes": [ + "新增可选布尔参数 group_by_batch(默认 false)。false 时按库位合并数量,批次相关字段(batch_no, production_date, expiry_date, inbound_time, inbound_order_no, supplier_batch_no)置 null;true 时保持原逻辑返回每条明细。出参结构不变,但 storageList 中批次字段在合并模式下为 null。" + ], + "type": "modified" + }, + { + "version": "2026.04.08-system-08", + "date": "2026-04-08", + "summary": "新增按商品维度移库接口", + "methods": [ + "storage.inventory.transferByProduct" + ], + "notes": [ + "新增 storage.inventory.transferByProduct 接口,按库位+商品查找所有库存记 录合并移动。入参为 space_id(原库位ID)、stock_id(商品SKU ID,即 wms_stock_warehouse.id)、target_space_id(目标库位ID)、quantity(移库数量)。开启批次管理(is_batch_mgmt=Y)的商品会被拒绝,需使用 transferLocation 按库存记录精确移库。复用 storage_transfer_completed 通知事件,操作日志编码 STORAGE_TRANSFER_BY_PRODUCT。isNeedAuth=true, isNeedLogin=true。" + ], + "type": "added" + }, + { + "version": "2026.04.08-system-09", + "date": "2026-04-08", + "summary": "补充 storeWarehouse.store.list 完整 response 输出字段说明,移除 api_config / apiConfig", + "methods": [ + "storeWarehouse.store.list" + ], + "notes": [ + "从返回结果中移除 api_config 和 apiConfig 字段(代码中 delete serialized.api_config / delete serialized.apiConfig),文档 response 补充完整输出字段列表:id, store_id, store_name, warehouse_id, warehouse_name, counterparty_id, counterparty_name, current_subject_role, auth_status, auth_status_label, apply_reason, review_comment, apply_time, review_time, auth_start, auth_end, actual_end, print_quantity, applied_by, reviewed_by, ended_by, remask, use_status, policy_config, is_auth_valid, remaining_days 以及分页和 current_subject 信息。" + ], + "type": "updated" + }, + { + "version": "2026.04.08-system-10", + "date": "2026-04-08", + "summary": "货主列表返回新增 has_qimen_config 布尔字段", + "methods": [ + "storeWarehouse.store.list" + ], + "notes": [ + "storeWarehouse.store.list 返回的 data.list[] 中新增 has_qimen_config(boolean),表示该货主是否已配置奇门。" + ], + "type": "changed" + }, + { + "version": "2026.04.08-system-11", + "date": "2026-04-08", + "summary": "补全 stock.warehouse.search 接口文档,新增 params / response / errors 完整说明", + "methods": [ + "stock.warehouse.search" + ], + "notes": [ + "入参补充 keyword(string,模糊匹配 item_code / item_name / goods_code / barcode)和 store_id(number,按货主筛选)。响应补充 data 数组各字段(id, item_code, goods_code, item_name, sku_property, stock_unit, quantity, locked_quantity, brand_name, item_type, barcodes, store_stock)以及 total。errors 补充 code=0 搜 索失败场景。" + ], + "type": "updated" + }, + { + "version": "2026.04.08-system-12", + "date": "2026-04-08", + "summary": "新增 with_stock / is_batch 参数,支持返回关联库存明细(按库位分 组或按批次逐条)", + "methods": [ + "stock.warehouse.search" + ], + "notes": [ + "入参新增 with_stock(boolean,默认 false,是否返回关联库存数据)和 is_batch(boolean,默认 false,仅 with_stock=true 时生效,按批次明细返回)。响应 data[] 新增 storage[] 字段:is_batch=false 时按库位分组汇总(含 space_id、space、inventory_type、quantity、locked_quantity、available_quantity);is_batch=true 时逐 条返回批次明细(含 id、stock_id、space_id、batch_no、inventory_type、quantity、locked_quantity、available_quantity、production_date、expiry_date、inbound_time、inbound_order_no、supplier_batch_no、created_at、space)。" + ], + "type": "updated" + }, + { + "version": "2026.04.08-system-13", + "date": "2026-04-08", + "summary": "新增 wms_stock_transaction 表和模型", + "methods": [ + "wms_stock_transaction" + ], + "notes": [ + "新增出入库流水记录表 wms_stock_transaction,含 transaction_type(INBOUND/OUTBOUND)、warehouse_id、store_id、stock_id、storage_id、space_id、quantity、batch_no、inventory_type、order_type、order_no、order_id、receiving_id、entry_order_id、operator_id、operator_name、remark 等字段,关联 StockWarehouse 和 Storage 模型。" + ], + "type": "added" + }, + { + "version": "2026.04.08-system-14", + "date": "2026-04-08", + "summary": "quickPutaway 和 matchPutaway 入库时自动写入出入库记录", + "methods": [ + "storage.inventory.quickPutaway", + "storage.inventory.matchPutaway" + ], + "notes": [ + "入库操作完成后自动写入 wms_stock_transaction 记录。quickPutaway 写入 order_type='SCRK'(收货入库),matchPutaway 写入 order_type='MATCH'(匹配入库),均 自动填充 warehouse_id、store_id、stock_id、storage_id、space_id、quantity、batch_no、inventory_type 等字段。" + ], + "type": "updated" + }, + { + "version": "2026.04.08-system-15", + "date": "2026-04-08", + "summary": "新增 storage.inventory.list 出入库记录列表查询接口", + "methods": [ + "storage.inventory.list" + ], + "notes": [ + "出入库记录列表查询,支持 where 条件(transaction_type、stock_id、space_id、store_id、order_type、order_no、inventory_type、operator_name、created_at)、 分页(pagination)、排序(sort)和 group_by_batch 参数。默认合并模式按库位+商品 聚合返回合计数量与记录条数,group_by_batch=true 时返回每条明细含 batch_no、order_no、operator_name 等完整信息。响应均关联 stockItem(item_code、item_name、sku_property、stock_unit)。" + ], + "type": "added" + }, + { + "version": "2026.04.08-system-16", + "date": "2026-04-08", + "summary": "出入库流水记录查询接口从 storage.inventory.list 改名为 storage.transaction.list", + "methods": [ + "storage.transaction.list" + ], + "notes": [ + "将出入库流水记录查询从 storage.inventory.list 迁移到 storage.transaction.list,避免与库存列表概念混淆。功能和参数不变。isNeedAuth=false, isNeedLogin=true, isNeedRight=false。" + ], + "type": "rename", + "module": "storage" + }, + { + "version": "2026.04.08-system-17", + "date": "2026-04-08", + "summary": "新增 storage.inventory.list 库存列表查询接口", + "methods": [ + "storage.inventory.list" + ], + "notes": [ + "新增库存列表查询接口,查询 wms_storage 表。支持 where 条件(stock_id/space_id/store_id/inventory_type/batch_no/inbound_order_no/available_quantity/inbound_time/created_at)、分页、排序。支持 group_by_batch 参数:默认 false 按库位+商 品合并(SUM quantity/locked_quantity/available_quantity),true 返回每条明细含 batch_no/production_date/expiry_date 等。关联 stockItem(商品信息)和 space(库位信息)。isNeedAuth=false, isNeedLogin=true, isNeedRight=false。" + ], + "type": "add", + "module": "storage" + }, + { + "version": "2026.04.08-system-18", + "date": "2026-04-08", + "summary": "移除 storage.entry.create 创建入库单接口", + "methods": [ + "storage.entry.create" + ], + "notes": [ + "不再允许通过 API 创建入库单。入库单仅由快捷入库(quickPutaway)和匹配入库(matchPutaway)等内部流程自动创建。底层 service 实现保留但不再通过 systemMethods 对外暴露。" + ], + "type": "remove", + "module": "storage" + }, + { + "version": "2026.04.08-system-19", + "date": "2026-04-08", + "summary": "移除 storage.entry.addDetail / deleteDetail / detailChange 对外 接口", + "methods": [ + "storage.entry.addDetail", + "storage.entry.deleteDetail", + "storage.entry.detailChange" + ], + "notes": [ + "入库单明细编辑能力不再通过 systemMethods 对外暴露,入库单模块仅保留 list/get/cancel/completeEntry。" + ], + "type": "remove", + "module": "storage" + }, + { + "version": "2026.04.08-system-20", + "date": "2026-04-08", + "summary": "新增 storage.stockout 出库单模块(非订单出库单能力)", + "methods": [ + "storage.stockout.list", + "storage.stockout.toOrder", + "storage.stockout.listItems" + ], + "notes": [ + "新增 storage.stockout.list / toOrder / listItems 接口,作为非订单出库单的主出口(对应奇门 stockout.create)。storage.delivery.* 仅作为兼容转发保留;底层 部分能力仍复用 order 模块。" + ], + "type": "add", + "module": "storage" + }, + { + "version": "2026.04.08-system-21", + "date": "2026-04-08", + "summary": "将 storage.stockout.toOrder 标记为占位接口", + "methods": [ + "storage.stockout.toOrder" + ], + "notes": [ + "storage.stockout.toOrder 当前仅保留方法名用于后续扩展,暂不开放实际逻辑。调用时返回 code=405、message=占位接口,暂未开放。" + ], + "type": "change" + }, + { + "version": "2026.04.09-system-01", + "date": "2026-04-09", + "summary": "storage.entry.cancel 支持批量作废,新增 ids 入参并兼容单条 id", + "methods": [ + "storage.entry.cancel" + ], + "notes": [ + "新增入参 `ids`(number[])以支持批量作废,兼容旧入参 `id`;当同时传入 `ids` 与 `id` 时以 `ids` 为准。", + "参数校验:`ids` 必须为非空数组;非法 ID 或空数组返回 400。", + "业务约束:已完成/已作废/处于不可作废状态的单据不允许作废;批量场景下任一 单据不存在或状态不允许时整体返回 404/400,未执行部分更新。", + "响应说明:单条作废返回字段 `id`(number);批量作废返回字段 `ids`(number[])。", + "已同步更新 methods/system.json(storage.entry.cancel)为 SSOT。" + ] + }, + { + "version": "2026.04.09-system-02", + "date": "2026-04-09", + "summary": "新增基础模块车牌识别接口 index.recognizeLicensePlate", + "methods": [ + "index.recognizeLicensePlate" + ], + "notes": [ + "入参:base64(string,必填)或 imageBase64/image_base64(兼容)", + "响应:返回归一化后的识别对象,包含 licensePlate、plateNumber、color、confidence、requestId、imageSize、rawData", + "错误:400(参数或图片格式/尺寸问题),500(第三方 OCR 调用失败或云密钥未 配置)", + "文档中不包含任何敏感配置;实际腾讯云密钥保留在配置文件中,勿在文档中暴露 。" + ], + "type": "added" + }, + { + "version": "2026.04.09-system-03", + "date": "2026-04-09", + "summary": "收紧基础模块车牌识别接口响应,仅返回 licensePlate 字段", + "methods": [ + "index.recognizeLicensePlate" + ], + "notes": [ + "出参由 {licensePlate, plateNumber, color, confidence, requestId, imageSize, rawData} 调整为 {licensePlate}", + "调用方请仅依赖 licensePlate 字段以适配新版本;历史字段已裁剪且不再保证存 在。", + "文档中未包含任何云密钥或敏感配置信息。" + ], + "type": "changed" + }, + { + "version": "2026.04.10-system-01", + "date": "2026-04-10", + "summary": "订单审核字段由 audit_status 替换为整数字段 step,并添加数据库迁移", + "methods": [ + "order.getreviewOrderlist", + "order.reviewOrder.getreviewOrderlist", + "order.reviewOrder.reviewOrder", + "order.deliveryOrder.getdeliveryOrderlist", + "order.list", + "order.stats" + ], + "notes": [ + "字段变更:order 相关审核字段从字符串/枚举 audit_status 替换为整数 step。", + "step 映射:0=未审核,1=已审核,2=处理中,3=驳回/异常,4=配送中,5=已完成,9=已关闭。", + "reviewOrder 接口在更新 inspection_status 的同时会写入 step 字段。", + "必须执行迁移脚本:20260410150000-replace-audit-status-with-step-on-order-delivery-tables.js" + ], + "type": "changed" + }, + { + "version": "2026.04.13-system-02", + "date": "2026-04-13", + "summary": "stock.warehouse.search 返回新增效期管理字段并保留 is_shelf_life_mgmt", + "methods": [ + "stock.warehouse.search" + ], + "notes": [ + "响应 data[] 中新增字段:inbound_min_days、outbound_min_days、shelf_life_days、remaining_threshold_days(均为 number,单位:天)。", + "保留并说明 is_shelf_life_mgmt 布尔字段(boolean),表示是否启用效期管理(true=启用)。", + "仅更新文档(methods/system.json 与变更记录),代码行为不变。" + ], + "type": "updated" + }, + { + "version": "2026.04.13-system-02", + "date": "2026-04-13", + "summary": "新增 storage.expiry.list 库存有效期列表查询接口", + "methods": [ + "storage.expiry.list" + ], + "notes": [ + "该接口查询 wms_storage,关联 stockWarehouse 和 locationSpace,并按当前仓库与 remaining_threshold_days / expiry_date 过滤。" + ], + "type": "added" + }, + { + "version": "2026.04.13-system-03", + "date": "2026-04-13", + "summary": "新增 storage.inventory.list 库存列表返回效期字段与预警标记", + "methods": [ + "storage.inventory.list" + ], + "notes": [ + "库存列表响应增加生产日期、过期日期、效期预警是否触发字段", + "预警标记仅在商品启用保质期管理且到期日满足阈值条件时为 true" + ], + "type": "updated" + }, + { + "version": "2026.04.14-system-01", + "date": "2026-04-14", + "summary": "更新 index.searchSpace 文档", + "methods": [ + "index.searchSpace" + ], + "notes": [ + "补充 index.searchSpace 的 params/response,按 ctx.user.store_id 作为仓库上下文;keyword 为可选字符串,对 space_code 与 custom_barcode 做 %keyword% 模糊匹配;返回字段 id、space_code、custom_barcode、custom_name,最多 50 条;仅文档同步,无代码变更。" + ], + "type": "updated" + }, + { + "version": "2026.04.16-system-01", + "date": "2026-04-16", + "summary": "基础模块新增快递产品类型查询接口", + "methods": [ + "index.getExpressProductTypeList" + ], + "notes": [ + "新增 index.getExpressProductTypeList,归属基础模块(module=index),用于查询指定快递公司的产品类型列表。", + "对应服务实现:app/service/systems/express.js 中的 getExpressProductTypeList,支持传入 express_code 作为可选筛选参数(source=body)。", + "接口设置为免鉴权(isNeedAuth=false)但需登录(isNeedLogin=true),与 index.getExpressList / index.getPlatformList 一致,优先从缓存读取。" + ], + "type": "added" + }, + { + "version": "2026.04.17-system-01", + "date": "2026-04-17", + "summary": "新增快递管理模块(setting.express)及 5 个接口文档", + "methods": [ + "setting.express.list", + "setting.express.listBase", + "setting.express.create", + "setting.express.checkCodeUnique", + "setting.express.update" + ], + "notes": [ + "新增独立模块组:快递管理模块(module=setting.express),将快递映射管理相关接口独立为一组以便维护。", + "接口实现参考:app/service/systems/setting/express.js(返回结构)与 app/service/systemMethods/setting/express.js(对外方法包装)。", + "接口鉴权与上下文:isNeedAuth=false, isNeedLogin=true;需在请求中传入 Authorization 以携带登录上下文(用于获取当前仓库/货主上下文)。", + "已同步更新 methods/system.json,补充 params/response/errors,保持文档与实现一致。" + ], + "type": "added" + }, + { + "version": "2026.04.17-system-02", + "date": "2026-04-17", + "summary": "setting.express.list 分页入参统一为 pagination", + "methods": [ + "setting.express.list" + ], + "notes": [ + "将 setting.express.list 的分页入参文档从顶层 page/page_size/pageSize 迁移为 pagination 对象,主形态为 pagination;兼容 snake_case 的 page_size 与 camelCase 的 pageSize。", + "文档与当前实现一致:顶层 page/page_size/pageSize 会被归一化到 data.pagination 并转发到系统服务。" + ], + "type": "updated" + }, + { + "version": "2026.04.17-system-03", + "date": "2026-04-17", + "summary": "新增快递接口管理模块(setting.expressInterface)及 4 个接口文档", + "methods": [ + "setting.expressInterface.list", + "setting.expressInterface.create", + "setting.expressInterface.update", + "setting.expressInterface.delete" + ], + "notes": [ + "新增独立模块组:快递接口管理模块(module=setting.expressInterface),对应实现:app/service/systems/setting/expressInterface.js 与对外包装 app/service/systemMethods/setting/expressInterface.js。", + "接口为当前仓库范围(基于 ctx.user.store_id),仓库边界由系统服务强制校验;禁止通过接口指定 warehouse_id/warehouseId。操作需登录(isNeedLogin=true),无需额外鉴权(isNeedAuth=false)。", + "已在 methods/system.json 新增对应接口的 params/response/errors 文档,保持与实现一致。" + ], + "type": "added" + }, + { + "version": "2026.04.18-system-01", + "date": "2026-04-18", + "summary": "补充订单储位分配接口文档:order.storageAllocation.allocateStorage", + "methods": [ + "order.storageAllocation.allocateStorage" + ], + "notes": [ + "新增 order.storageAllocation.allocateStorage:按订单批量分配储位,支持多种入参别名(order_ids/ids/orderId 等)与仓库上下文优先级。", + "响应包含 requested_order_ids, pending_order_ids, allocated_order_ids, shortage_order_ids, skipped_orders, picking_count, stock_lock_summary, storage_lock_summary 等字段,用于前端展示分配结果与不足提示。" + ], + "type": "added" + }, + { + "version": "2026.04.18-system-02", + "date": "2026-04-18", + "summary": "新增 order.pendingOrder.allocateExpressCode:待处理订单模块的批量分配首单快递号(异步接口),复用 express.createWaybillCodePipeline。", + "methods": [ + "order.pendingOrder.allocateExpressCode" + ], + "notes": [ + "异步接口:调用后立即返回 task_id,后台执行运单创建,通过 allocateExpressCodeTaskProgress 查询进度。", + "入参为 ids(订单 ID 数组),sys_platform_code/logistics_code 等由后端从数据库读取。", + "拆单场景请使用 order.pendingOrder.allocateSubOrderNumber。" + ], + "type": "added" + }, + { + "version": "2026.04.18-system-03", + "date": "2026-04-18", + "summary": "将 order.storageAllocation.allocateStorage 迁移到 order.pendingOrder.allocateStorage,并移除原有公开分组。", + "methods": [ + "order.pendingOrder.allocateStorage" + ], + "notes": [ + "将对外入口从 order.storageAllocation.allocateStorage 迁移到 order.pendingOrder.allocateStorage,旧的 order.storageAllocation 分组已从 methods/system.json 中移除。", + "新的对外接口不接受 warehouse_id / warehouseId,仓库上下文由当前登录用户(ctx.user.store_id)提供。", + "本次变更仅同步文档位置与对外方法名,底层实现保留且通过新的 system 方法暴露。" + ], + "type": "changed" + }, + { + "version": "2026.04.19-system-02", + "date": "2026-04-19", + "summary": "新增待处理模块取消分配储位接口 order.pendingOrder.cancelAllocateStorage", + "methods": [ + "order.pendingOrder.cancelAllocateStorage" + ], + "notes": [ + "新增待处理模块取消分配储位接口 `order.pendingOrder.cancelAllocateStorage`,直接对接 `service.systems.orderStorageAllocation.cancelAllocateStorage` 实现。", + "接口现在仅接受订单ID(order_ids),不再接受 allow_storage_location;禁止传入 `warehouse_id/warehouseId`,仓库上下文由当前登录用户的 `store_id` 提供。", + "响应返回标准 { flag, code, message, data } 结构,data 包含取消分配的汇总结果(warehouse_id, requested_order_ids, cancellable_order_ids, skipped_orders, orders, picking_count, storage_unlock_summary, stock_unlock_summary)。" + ], + "type": "added" + }, + { + "version": "2026.04.21-system-01", + "date": "2026-04-21", + "summary": "新增 order.pendingOrder.updateOrderPlatform 方法:批量修改待处理订单平台信息", + "methods": [ + "order.pendingOrder.updateOrderPlatform" + ], + "notes": [ + "通过 code 查找 wms_platform,平台不存在时返回 404 错误。", + "仅操作当前仓库的当前订单表。", + "noNeedRight=true,noNeedAuth=true(isNeedAuth: true 在 spec 中对应权限配置 noNeedAuth=true)。" + ], + "type": "added" + }, + { + "version": "2026.04.21-system-02", + "date": "2026-04-21", + "summary": "新增方法 order.pendingOrder.updateOrderExpress:批量修改待处理订单的快递信息", + "methods": [ + "order.pendingOrder.updateOrderExpress" + ], + "notes": [ + "新增 order.pendingOrder.updateOrderExpress:批量修改待处理订单的快递信息,按 express_code 从仓库快递列表(带缓存)匹配快递项。", + "自定义映射(is_system_setting=true)时,sys_logistics_code/name 写入系统快递编码和名称,logistics_code/name 写入自定义编码和名称;系统快递(is_system_setting=false)时四个字段均写系统快递的 code/name。", + "只操作当前仓库的当前订单表,不处理其他订单表;操作后写入操作日志(ORDER_UPDATE_EXPRESS)。" + ], + "type": "added" + }, + { + "version": "2026.04.21-system-03", + "date": "2026-04-21", + "summary": "新增 order.expectionOrder.resolveException:将待处理异常订单转回正常待处理状态", + "methods": [ + "order.expectionOrder.resolveException" + ], + "notes": [ + "新增 order.expectionOrder.resolveException:批量将 step=3 的异常订单恢复为 step=2 正常待处理状态。", + "入参 ids 为订单ID 正整数数组,不能为空;仅操作当前仓库当前订单表。", + "返回 updated_count(实际更新行数)与 ids(本次操作ID列表)。", + "权限配置:noNeedLogin=false、noNeedRight=true、noNeedLog=false、noNeedAuth=true" + ], + "type": "added" + }, + { + "version": "2026.04.21-system-04", + "date": "2026-04-21", + "summary": "新增 order.pendingOrder.cloneOrder 方法:克隆待处理订单", + "methods": [ + "order.pendingOrder.cloneOrder" + ], + "notes": [ + "支持对 step 0/1/2/3 的待处理订单进行克隆操作。", + "若原订单已分配储位(storage_status=fin),克隆前自动清除已分配库存。", + "原订单取消后(step→9, status→cancel),以原订单业务数据创建新订单,流程状态字段全部重置为初始落库状态。", + "克隆订单明细含 stock_id,新订单 ID 重新绑定。", + "noNeedAuth=true,noNeedRight=true,noNeedLogin=false。" + ], + "type": "added" + }, + { + "version": "2026.04.21-system-06", + "date": "2026-04-21", + "summary": "新增 order.pendingOrder.createOrder:手动创建待处理/待审核订单", + "methods": [ + "order.pendingOrder.createOrder" + ], + "notes": [ + "新增 order.pendingOrder.createOrder:手动创建订单,step 由货主策略 need_order_approval 决定(1→待审核 step=0,0→待处理 step=1)。", + "必填字段:store_id、name、mobile/tel 至少一项、detail_address、items[](含 item_code 和 plan_qty)。", + "delivery_order_code 不传则自动生成(SYS+时间戳+随机4位);logistics_code/sys_platform_code 不传则读货主合约策略 default_express_code/default_platform_code。", + "不做库存锁定,储位分配为独立步骤。操作日志写入 ORDER_CREATE。", + "noNeedRight=true,noNeedAuth=true,noNeedLogin=false。" + ], + "type": "added" + }, + { + "version": "2026.04.21-system-07", + "date": "2026-04-21", + "summary": "新增 Excel 模板下载与批量导入创建订单接口:order.pendingOrder.downloadCreateTemplate 和 order.pendingOrder.importOrdersFromExcel", + "methods": [ + "order.pendingOrder.downloadCreateTemplate", + "order.pendingOrder.importOrdersFromExcel" + ], + "notes": [ + "新增 order.pendingOrder.downloadCreateTemplate:生成 Excel 导入模板,返回 base64 编码的 xlsx 文件,表头中带 * 的列为必填项(橙色背景),可选列为灰色背景,含示例数据行和填写说明工作表。", + "新增 order.pendingOrder.importOrdersFromExcel:接受 base64 编码的 xlsx 文件,按订单号分组,每组调用 createOrder 逻辑创建订单;不中断执行,逐条记录成功/失败结果返回。", + "多行相同订单号的行组成一个完整订单,每行代表一条商品明细;订单头信息(收件人、地址等)取每组第一行。", + "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" + }, + { + "version": "2026.05.08-system-05", + "date": "2026-05-08", + "summary": "order.wave.batchList:新增 source 字段并支持 where.source 过滤,返回 list item 中新增 source 字段", + "methods": [ + "order.wave.batchList" + ], + "notes": [ + "新增 where.source(可选,number)用于按来源过滤:0=普通波次(正常后台操作),1=管理后台策略任务,2=PDA策略任务;不传则不过滤。", + "响应 list 每条记录新增字段 source(number),用于区分波次来源。", + "仅更新文档,业务代码不在此变更范围。" + ], + "type": "updated" + }, + { + "version": "2026.05.09-system-01", + "date": "2026-05-09", + "summary": "新增 order.wave.wavePickTaskCancelSelf;order.wave.waveStrategyList 新增预演计数字段/参数", + "methods": [ + "order.wave.wavePickTaskCancelSelf", + "order.wave.waveStrategyList" + ], + "notes": [ + "新增接口 `order.wave.wavePickTaskCancelSelf`:仅支持单个 `task_id`(number,必填),明确不支持 `task_ids` 批量参数。", + "业务约束:仅允许取消当前登录用户本人创建的拣货任务;若尝试取消非本人创建任务,接口应返回 400 错误(仅允许取消本人创建任务)。", + "返回建议:与现有取消接口风格一致,包含 `cancelled_count`(0/1)、`task_id`、`task_no`(若后端返回)或相应的取消结果汇总。", + "错误码建议:400 参数不合法(task_id 缺失或传了 task_ids);400 仅允许取消本人创建任务;500 取消失败。", + "新增参数:calculate_next_fetch_order_count(number,可选),含别名 calculateNextFetchOrderCount;取值 0=不计算(默认),1=计算并返回每条策略的 next_fetch_order_count,用于前端在策略列表中预览抓取量。", + "新增响应字段:list[*].next_fetch_order_count(number),含义:按当前策略口径预演一次自动抓取时,预计会选中的订单数量;当未开启计算时返回 0。" + ], + "type": "added" + }, + { + "version": "2026.05.11-system-01", + "date": "2026-05-11", + "summary": "新增字段 wave_prefix(策略层波次前缀),并补充 PDA 抓取波次号生成行为说明", + "methods": [ + "order.wave.waveStrategyList", + "order.wave.waveStrategyCreate", + "order.wave.waveStrategyUpdate", + "order.wave.waveStrategyFetchPda" + ], + "notes": [ + "在 wave strategy 对象中新增可选字段 wave_prefix:策略波次前缀,优先于仓库前缀。", + "校验规则:长度 1-5,仅允许 A-Z0-9;保存时会转为大写;为空时回退仓库前缀:团购使用 group_wave_prefix,散单使用 delete_order_wave_prefix。", + "在 order.wave.waveStrategyList 的返回 list[*] 中新增字段 wave_prefix(string)。", + "在 order.wave.waveStrategyCreate / waveStrategyUpdate 的入参中新增可选字段 wave_prefix(string),创建/更新成功后保存为大写且触发策略版本推进。", + "在 order.wave.waveStrategyFetchPda 的行为说明中补充:生成波次号(wave_no)时优先使用策略层 wave_prefix,否则按策略类型回退到仓库前缀;前缀校验同上。" + ], + "type": "updated" + }, + { + "version": "2026.05.15-system-01", + "date": "2026-05-15", + "summary": "仅更新文档:将 setting.express.create 入参与实现对齐(新增 express_code,移除 platform)", + "methods": [ + "setting.express.create" + ], + "notes": [ + "仅同步文档,与实现对齐,未修改任何业务代码或行为" + ], + "type": "updated" + }, + { + "version": "2026.05.15-system-02", + "date": "2026-05-15", + "summary": "新增 storage.report.search:库存流水统计报表,支持按时间闭区间过滤与按库位/按商品聚合", + "methods": [ + "storage.report.search" + ], + "notes": [ + "方法新增:storage.report.search", + "时间过滤为闭区间:created_at >= start_time 且 created_at <= end_time", + "当 where.by_space 为 false(默认)时,按商品+货主聚合(多个库位汇总);当为 true 时按商品+库位返回", + "不返回无流水的商品/键(仅返回在查询区间内出现过流水的数据)" + ], + "type": "added" + }, + { + "version": "2026.05.15-system-03", + "date": "2026-05-15", + "summary": "库存报表模块主入口迁移到 stock.report.search,storage.report.search 保持兼容别名", + "methods": [ + "stock.report.search", + "storage.report.search" + ], + "notes": [ + "新增主入口方法 stock.report.search,沿用既有报表统计口径(时间闭区间、by_space/store_ids、返回字段保持一致)。", + "保留 storage.report.search 作为兼容别名,并在描述中明确建议迁移到 stock.report.search。", + "仅更新 methods 文档配置,不修改业务代码。" + ], + "type": "updated" + }, + { + "version": "2026.05.15-system-04", + "date": "2026-05-15", + "summary": "文档主入口统一为 stock.report.search,storage.report.search 调整为兼容别名简述", + "methods": [ + "stock.report.search", + "storage.report.search" + ], + "notes": [ + "保留 stock.report.search 作为库存报表唯一完整文档入口。", + "storage.report.search 不再维护完整重复字段,仅保留迁移与兼容说明。", + "仅更新 methods 文档配置,不修改业务代码。" + ], + "type": "updated" + }, + { + "version": "2026.05.15-system-05", + "date": "2026-05-15", + "summary": "拆分 storage.report 模块并移除错误 stock.report.search 文档入口", + "methods": [ + "storage.report.search", + "stock.report.search" + ], + "notes": [ + "将库存报表从 storage.inventory 中拆分为独立模块 storage.report,storage.report.search 文档改为主入口语义(不再作为兼容别名)。", + "从 storage.inventory 分组中移除错误的 stock.report.search 文档入口以及兼容别名条目 storage.report.search。", + "最终归属:storage.report.search 属于模块 storage.report;stock.report.search 的文档入口已移除以避免混淆(代码实现保留于 app/service/systemMethods/storage/report.js 的 storage.report.search)。", + "仅修改文档,不修改应用代码实现。" + ], + "type": "updated" + }, + { + "version": "2026.05.15-system-06", + "date": "2026-05-15", + "summary": "storage.report.search 新增排序能力文档说明", + "methods": [ + "storage.report.search" + ], + "notes": [ + "补充 sort 参数:支持 sortField/sort_field、sortOrder/sort_order。", + "补充排序白名单:begin_total、inbound_total、outbound_total、end_total。", + "补充非法排序字段/顺序回退默认排序说明。", + "响应说明补充:已按 sort 规则排序返回。" + ], + "type": "updated" + }, + { + "version": "2026.05.16-system-01", + "date": "2026-05-16", + "summary": "新增 storage.report.export:按与 storage.report.search 相同条件导出库存报表 Excel", + "methods": [ + "storage.report.export" + ], + "notes": [ + "新增方法:storage.report.export,复用 storage.report.search 的 where/sort 查询条件。", + "导出文件包含两个 sheet:汇总、变更记录。", + "用于在统计结果基础上回溯明细流水,提升库存变动追溯效率。" + ], + "type": "added" + }, + { + "version": "2026.05.16-system-02", + "date": "2026-05-16", + "summary": "storage.report.export 改为异步任务 + 新增 exportTaskProgress", + "methods": [ + "storage.report.export", + "storage.report.exportTaskProgress" + ], + "notes": [ + "调用方式调整为两步:先调用 storage.report.export 提交任务并获取 task_id,再调用 storage.report.exportTaskProgress 轮询任务进度。", + "下载链接获取方式:当 status=success 时,从 exportTaskProgress 响应的 download_url 字段获取导出文件地址。", + "任务状态值补充:submitted/running/success/failed/not_found。" + ], + "type": "updated" + }, + { + "version": "2026.05.16-system-03", + "date": "2026.05.16", + "summary": "同步 setting.expressInterface.create/update 入参与系统快递编码映射规则", + "methods": [ + "setting.expressInterface.create", + "setting.expressInterface.update" + ], + "notes": [ + "补充入参:sys_express_code、weight_type、address、town_name、ispickup、shipperno,并保留既有字段。", + "在参数说明补充 camelCase 别名支持:sysExpressCode、weightType、townName、isPickup、shipperNo 等。", + "同步约束变化:不再因同仓快递编码重复或平台重复直接返回 409;当 express_code 无法匹配系统快递编码时返回 400,文案为 express_code 未匹配到系统快递编码。" + ], + "type": "updated" + }, + { + "version": "2026.05.17-system-05", + "date": "2026-05-17", + "summary": "同步 storage.receiving.addDetail 的参数与返回值(从实现提取)", + "methods": [ + "storage.receiving.addDetail" + ], + "notes": [ + "补充 receiving_id 入参说明", + "补充返回的 details 数组与 selectId 字段", + "补充可能的错误码:404/400/500" + ], + "type": "updated" + }, + { + "version": "2026.05.17-system-06", + "date": "2026-05-17", + "summary": "重新同步 addDetail 文档", + "methods": [ + "storage.receiving.addDetail" + ], + "notes": [ + "再次从实现代码核对并补充参数/返回值/错误码,确保文档与实现一致", + "仅同步文档,不修改业务代码" + ], + "type": "updated" + }, + { + "version": "2026.05.17-system-07", + "date": "2026-05-17", + "summary": "addDetail 新增可选 item 入参并兼容空白创建链路", + "methods": [ + "storage.receiving.addDetail" + ], + "notes": [ + "item 有值时按传入字段创建(服务端覆盖 receiving_id 与 creator_id)", + "兼容不传 item 的空白创建链路;item.children 需覆盖关键字段(有则写、无则补齐)。" + ], + "type": "updated" + }, + { + "version": "2026.05.17-system-10", + "date": "2026-05-17", + "summary": "调整 storage.receiving.getReceivingDetail 库位字段输出语义:space_id 改为展示名称并补充兼容字段", + "methods": [ + "storage.receiving.getReceivingDetail" + ], + "notes": [ + "将 receiving.details.*.space_id 定义为展示名称(string|null),优先 custom_space_name,其次 space_name,不再作为原始数值ID文档语义。", + "新增并明确 receiving.details.*.space_id_raw(number|null)用于保留原始库位ID,兼容旧调用方。", + "补充 receiving.details.*.space_name(库位名称/编码)与 receiving.details.*.custom_space_name(自定义名称,可空)字段说明。" + ], + "type": "updated" + }, + { + "version": "2026.05.17-system-11", + "date": "2026-05-17", + "summary": "补充 subject_config.enable_external_express_code 字段文档与默认值语义", + "methods": [ + "store.createStore", + "store.createWarehouse", + "setting.warehouse.getSettings", + "setting.warehouse.saveSettings" + ], + "notes": [ + "在 store.createStore 与 store.createWarehouse 的 subject_config 入参中新增字段:enable_external_express_code(boolean),默认 false;开启后允许按外部系统传入的快递编码进行处理(如无匹配仍以业务校验为准)。", + "此 change 同时用于说明将在 setting.warehouse.getSettings / saveSettings 中补充该字段的文档说明(后续 doc-only 写入)。" + ], + "type": "updated", + "module": "store" + }, + { + "version": "2026.05.17-system-12", + "date": "2026-05-17", + "summary": "storeWarehouse.store 策略配置文档新增 enable_external_express_code 字段说明(向后兼容)", + "methods": [ + "storeWarehouse.store.getPolicyConfig", + "storeWarehouse.store.savePolicyConfig" + ], + "notes": [ + "在 getPolicyConfig / savePolicyConfig 的出参说明中补充 data.policy_config.enable_external_express_code 字段,明确为 flag(0=关闭,1=开启),默认 0。", + "在 savePolicyConfig 的入参说明中补充 policy_config.enable_external_express_code 字段定义。", + "本次为向后兼容的文档增强:新增可选策略字段说明,不影响现有调用。" + ], + "type": "updated" + }, + { + "version": "2026.05.19-system-01", + "date": "2026-05-19", + "summary": "补充 storage.entry.list 的 expense_record 筛选语义与未迁移环境错误提示", + "methods": [ + "storage.entry.list" + ], + "notes": [ + "在 where 参数说明中补充 expense_record 字段语义(费用是否记录)及 eq/in 支持。", + "明确 true/false、1/0、y/n、yes/no 的归一化规则与等价写法示例。", + "补充未完成表结构迁移时可能返回 400 及错误提示文案。" + ], + "type": "updated" + }, + { + "version": "2026.05.20-system-01", + "date": "2026-05-20", + "summary": "同步 order.recheckOrder.scanOrder 返回结构,补充 cart_match_view 语义化视图说明", + "methods": [ + "order.recheckOrder.scanOrder" + ], + "notes": [ + "新增返回字段:match_type(waybill/cart)与 cart_match_view(仅 cart 命中返回)。", + "cart_match_view 包含通用子字段:mode_code / mode_name / view_type / task;当车号命中时按 pick_mode 返回语义化结构:mode 1/5 返回 groups,mode 2 返回 orders,mode 3 返回 pick_groups,mode 4 返回 box_groups。" + ], + "type": "updated" + }, + { + "version": "2026.05.22-system-01", + "date": "2026-05-22", + "summary": "新增 index.getPlatformOauthLink 文档,补充平台授权链接接口说明", + "methods": [ + "index.getPlatformOauthLink" + ], + "notes": [ + "入参支持 code、platform_code、platformCode 三种平台编码字段别名。", + "当前仅支持 PDD;成功返回 data.platform_code、data.oauth_link 和 code=200,其他平台返回 code=400。", + "仅通过文档脚本同步 methods/system.json 与 methods/changes/system.json,不修改业务代码。" + ], + "type": "added", + "module": "index" + }, + { + "version": "2026.05.22-system-02", + "date": "2026-05-22", + "summary": "更新 index.getPlatformOauthLink 文档,补充仓库上下文、预占记录与错误说明", + "methods": [ + "index.getPlatformOauthLink" + ], + "notes": [ + "补充真实行为:从 ctx.user.store_id 读取当前仓库 ID,从 wms_platform.auth_base_url 读取授权基础地址,并在 wms_shops 创建平台授权预占记录。", + "补充 oauth_link 细节:追加 client_id、redirect_uri(配置非空时)以及长查询参数 wms_authorization_reservation_code,对应唯一 auth_random_code。", + "补充常见错误:平台编码为空、仓库上下文缺失、平台不存在、授权基础地址缺失/格式错误、不支持的平台,以及预占记录创建失败。" + ], + "type": "updated", + "module": "index" + }, + { + "version": "2026.05.22-system-03", + "date": "2026-05-22", + "summary": "同步 index.getPlatformOauthLink 当前实现:裸码入库与 state 拼接规则", + "methods": [ + "index.getPlatformOauthLink" + ], + "notes": [ + "补充真实行为:从 ctx.user.store_id 读取当前仓库,从 wms_platform.auth_base_url 读取基础授权链接,并优先复用 wms_shops 中 status=0 的未授权记录。", + "明确 auth_random_code 当前以裸码保存;若复用到历史带前缀记录,会先去掉 platformOauthReservationCodePrefix 后再回写。", + "更新 oauth_link 说明:state 由“前缀 + 平台编码 + '_' + 裸码”组成并整体 URL 编码后直接拼接到基础授权链接后,例如 xxxxx_PDD_;同时移除已不存在的基础地址格式错误/不支持平台错误描述。" + ], + "type": "updated", + "module": "index" + }, + { + "version": "2026.05.22-system-04", + "date": "2026-05-22", + "summary": "修正 index.getPlatformOauthLink 文档中的残留平台限制描述", + "methods": [ + "index.getPlatformOauthLink" + ], + "notes": [ + "移除 index.getPlatformOauthLink 参数与返回字段中残留的“当前仅支持 PDD”描述,避免与当前实现不一致。", + "保留授权链接仅依赖平台已配置基础授权链接模式的说明,不再把示例平台编码误写成实现限制。" + ], + "type": "updated", + "module": "index" + }, + { + "version": "2026.05.22-system-05", + "date": "2026-05-22", + "summary": "新增 index.getShopList 文档,并同步 custom_name 与店铺列表脱敏返回规则", + "methods": [ + "index.getShopList" + ], + "notes": [ + "新增 index.getShopList:接口依赖当前登录仓库上下文 ctx.user.store_id,不接受额外业务入参,缺少仓库时返回 400:未识别到当前仓库。", + "补充真实返回结构:data.list 为数组,包含 id、warehouse_id、platform_code、shop_name、custom_name、status、auth_expire_at、token_expires_at、refresh_token_expires_at、scope、created_at、updated_at 以及脱敏后的 owner_id、access_token、refresh_token、auth_random_code。", + "同步脱敏规则:owner_id 非空且长度大于 5 时返回前 3 位 + *** + 后 2 位,长度小于等于 5 时返回 ***;access_token、refresh_token、auth_random_code 非空时固定返回 ***,空值返回 null。", + "仅通过文档脚本同步 methods/system.json 与 methods/changes/system.json,不修改任何业务代码。" + ], + "type": "added", + "module": "index" + }, + { + "version": "2026.05.22-system-06", + "date": "2026-05-22", + "summary": "新增 index.getShopExpressList 文档,补充店铺快递列表统一返回结构", + "methods": [ + "index.getShopExpressList" + ], + "notes": [ + "按 ctx.user.store_id 校验店铺归属,仅允许查询当前登录仓库下的店铺。", + "服务端按店铺所属平台拉取并收敛快递签约/电子面单可用列表,统一返回前端消费结构。", + "未接入平台当前返回空列表;若店铺缺少授权 access_token,则返回 400:店铺未授权。", + "仅文档同步,不改业务代码。" + ], + "type": "added", + "module": "index" + }, + { + "version": "2026.05.22-system-07", + "date": "2026-05-22", + "summary": "同步快递接口文档:is_share 仅展示不可编辑", + "methods": [ + "setting.expressInterface.list", + "setting.expressInterface.create", + "setting.expressInterface.update" + ], + "notes": [ + "create/update 不再接受 is_share", + "list 仍可返回 is_share 作为展示信息", + "仅文档同步,不改业务代码" + ], + "type": "updated", + "module": "setting.expressInterface" + }, + { + "version": "2026.05.22-system-08", + "date": "2026-05-22", + "summary": "同步快递接口列表文档,移除未返回字段说明", + "methods": [ + "setting.expressInterface.list" + ], + "notes": [ + "根据 app/service/systems/setting/expressInterface.js 的 list() 查询字段与 normalizeInterfaceRow() 返回结构,同步 setting.expressInterface.list 不返回 token。", + "按当前实现清理 response.children 中未返回的 share_id、can_use_count 字段说明。", + "保留 is_share,并明确其仅用于展示,不作为编辑入参。" + ], + "type": "updated", + "module": "setting.expressInterface" + }, + { + "version": "2026.05.22-system-09", + "date": "2026-05-22", + "summary": "index.getShopList 支持按平台编码筛选店铺", + "methods": [ + "index.getShopList" + ], + "notes": [ + "index.getShopList 兼容 platform_code 与 platformCode 两种传参方式,服务端按 platform_code、platformCode 顺序读取首个 trim 后非空值作为平台筛选条件。", + "未传平台参数时返回当前登录仓库下全部已授权店铺;传入非空平台编码时仅返回该平台的已授权店铺。", + "本次仅补充筛选条件文档,不影响返回结构、排序规则与 owner_id/access_token/refresh_token/auth_random_code 的脱敏规则。", + "仅通过文档脚本同步 methods/system.json 与 methods/changes/system.json,不修改任何业务代码。" + ], + "type": "updated", + "module": "index" + }, + { + "version": "2026.05.22-system-10", + "date": "2026-05-22", + "summary": "快递接口配置新增 shop_id 字段", + "methods": [ + "setting.expressInterface.create", + "setting.expressInterface.update", + "setting.expressInterface.list" + ], + "notes": [ + "create/update 支持 shop_id/shopId(兼容 snake_case 与 camelCase),为店铺 ID,未传或空值按 null 处理。", + "list 返回 shop_id 字段,列表 where 支持按 shop_id 过滤。" + ], + "type": "updated" + }, + { + "version": "2026.05.22-system-11", + "date": "2026-05-22", + "summary": "调整快递接口列表排序规则", + "methods": [ + "setting.expressInterface.list" + ], + "notes": [ + "setting.expressInterface.list 改为按 weight ASC, id DESC 排序;优先按权重排序,权重相同再按 id 倒序。", + "本次仅同步该接口排序说明,不影响返回结构。" + ], + "type": "updated", + "module": "setting.expressInterface" + }, + { + "version": "2026.05.22-system-12", + "date": "2026-05-22", + "summary": "index.getShopExpressList 返回新增系统快递编码", + "methods": [ + "index.getShopExpressList" + ], + "notes": [ + "data.list[*] 新增 sys_express_code 字段,由平台快递编码 wp_code 映射系统快递编码,未匹配时返回空字符串。", + "补充 data.list[*].wp_name 说明:由系统快递基础表根据平台快递编码映射得到名称,未匹配时返回空字符串。", + "原有请求参数、鉴权方式与返回主结构保持不变。", + "仅文档同步,不改业务代码。" + ], + "type": "updated", + "module": "index" + }, + { + "version": "2026.05.23-system-01", + "date": "2026-05-23", + "summary": "补充快递接口列表 is_system_express_code 返回字段说明", + "methods": [ + "setting.expressInterface.list" + ], + "notes": [ + "在 setting.expressInterface.list 的 response.children 中补充 is_system_express_code 字段说明。", + "该字段表示当前行 express_code 是否为系统快递编码;不是系统快递编码返回 0,否则返回 1。", + "仅文档同步,不改业务代码。" + ], + "type": "updated", + "module": "setting.expressInterface" + }, + { + "version": "2026.05.23-system-02", + "date": "2026-05-23", + "summary": "完善 index.getExpressList 文档:补充过滤规则、返回字段与仓库维度行为", + "methods": [ + "index.getExpressList" + ], + "notes": [ + "补充 `systemOnly`、`express_code`、`expressCode` 的真实入参语义,明确真值识别规则与字段优先级。", + "补充默认模式、系统模式、按快递编码过滤模式下的返回差异,说明当前登录仓库维度来自 `ctx.user.store_id`。", + "补充 `data[*]` 各字段含义,明确系统基础快递与仓库自定义快递编码的差异字段。", + "仅文档同步,不修改业务代码。" + ], + "type": "updated", + "module": "index" + }, + { + "version": "2026.05.24-system-01", + "date": "2026-05-24", + "summary": "同步 index.getExpressList 文档:移除 expressCode 别名并明确 express_code 筛选语义", + "methods": [ + "index.getExpressList" + ], + "notes": [ + "移除 index.getExpressList 文档中的 expressCode 驼峰别名参数,仅保留 express_code。", + "明确当 systemOnly=false 且传入 express_code 时,接口按自定义映射记录中的系统快递编码字段 express_code 过滤,而不是按自定义 code 过滤。", + "保留 systemOnly=true 按系统快递编码过滤系统基础快递列表,以及默认合并逻辑、缓存优先、仓库维度来源不变的说明。" + ], + "type": "updated" + }, + { + "version": "2026.05.24-system-02", + "date": "2026-05-24", + "summary": "新增 index.getCainiaoStfTemplates 接口文档并明确模板返回语义", + "methods": [ + "index.getCainiaoStfTemplates" + ], + "notes": [ + "新增无参接口 index.getCainiaoStfTemplates:从当前仓库首个已授权 TB 店铺发起 cainiao.waybill.ii.search 查询菜鸟 STF 模板。", + "补充返回结构说明:data.platform_code 固定为 TB;data.list 返回模板数组并包含 template_id/template_name/template_url/cp_code/wp_code 字段。", + "明确模板列表为宽松结构解析并按 template_id/template_name/template_url 核心语义去重。", + "补充错误码说明:未识别仓库返回 400;当前仓库无已授权 TB 店铺返回 404。" + ], + "type": "added" + }, + { + "version": "2026.05.24-system-03", + "date": "2026-05-24", + "summary": "调整 index.getCainiaoStfTemplates 为免登录/免鉴权接口", + "methods": [ + "index.getCainiaoStfTemplates" + ], + "notes": [ + "将 index.getCainiaoStfTemplates 的 isNeedLogin 调整为 false,接口改为免登录访问。", + "保持 isNeedAuth=false,并同步免权限拦截配置,避免登录态与鉴权拦截。", + "该接口仍为无请求参数,headers 调整为空数组。" + ], + "type": "updated", + "module": "index" + }, + { + "version": "2026.05.24-system-04", + "date": "2026-05-24", + "summary": "调整 index.getCainiaoStfTemplates 为公共无参模板查询接口", + "methods": [ + "index.getCainiaoStfTemplates" + ], + "notes": [ + "index.getCainiaoStfTemplates 改为公共无参查询,不再依赖当前仓库、登录态或店铺授权。", + "接口直接调用 requestTbWaybillSearch({ cpCode: '' }) 查询公共模板,返回 data.platform_code='TB' 与模板数组。", + "requestTbWaybillSearch 支持 accessToken 缺失时不下发 session,因此该接口不再依赖 session。" + ], + "type": "updated" + }, + { + "version": "2026.05.24-system-05", + "date": "2026-05-24", + "summary": "同步 index.getCainiaoStfTemplates 改用淘宝标准模板公共接口", + "methods": [ + "index.getCainiaoStfTemplates" + ], + "notes": [ + "index.getCainiaoStfTemplates 改为调用淘宝开放平台 cainiao.cloudprint.stdtemplates.get,不再复用 cainiao.waybill.ii.search。", + "接口不需要用户授权,不下发 session,继续使用 https://eco.taobao.com/router/rest 与 TOP 公共签名参数。", + "模板列表改为从 cainiao_cloudprint_stdtemplates_get_response.result.datas[*].standard_templates[*] 做宽松兼容解析,统一返回 template_id/template_name/template_url/cp_code/wp_code。" + ], + "type": "updated" + }, + { + "version": "2026.05.24-system-06", + "date": "2026-05-24", + "summary": "新增 index.getPrintPlatformList 接口文档并明确打印平台下拉返回结构", + "methods": [ + "index.getPrintPlatformList" + ], + "notes": [ + "新增 index.getPrintPlatformList 文档,说明该接口供快递接口新增/编辑页下拉选择使用。", + "补充接口行为:仅返回未删除且状态为 ACTIVE 的打印平台,不分页,按 platform_name 与 id 升序返回。", + "补充 data[*] 返回字段说明,明确 code/name/value/label/platform_code/platform_name/status/remark 的含义。", + "仅文档同步,不修改业务代码。" + ], + "type": "added", + "module": "index" + }, + { + "version": "2026.05.24-system-07", + "date": "2026-05-24", + "summary": "新增 index.getPrintPlatformTemplateList 文档,明确 express_code 必填与模板过滤语义", + "methods": [ + "index.getPrintPlatformTemplateList" + ], + "notes": [ + "新增 index.getPrintPlatformTemplateList 方法文档,补充 platform_code 与 express_code 入参,其中 express_code 标记为必填。", + "明确业务语义:接口按 platform_code(默认 CAINIAO)定位 wms_express 中对应打印平台字段,并使用 express_code 过滤模板结果后返回。", + "补充返回结构 data.platform_code / data.express_code / data.responseData,说明未实现平台返回空对象。", + "仅文档同步,不修改业务代码。" + ], + "type": "added", + "module": "index" + }, + { + "version": "2026.05.25-system-01", + "date": "2026-05-25", + "summary": "新增 index.polyapiAuthorizeUrl 接口文档并标注免登录免鉴权特征", + "methods": [ + "index.polyapiAuthorizeUrl" + ], + "notes": [ + "新增基础模块方法 index.polyapiAuthorizeUrl,说明其为公共无参接口。", + "明确接口固定调用菠萝派 Differ.JH.BuildeAuthorizeUrl,返回体中以 data.respone 原样包裹上游响应。", + "同步标注 isNeedLogin=false、isNeedAuth=false,headers 为空数组。" + ], + "type": "added" + }, + { + "version": "2026.05.25-system-02", + "date": "2026-05-25", + "summary": "新增店铺模块相关接口文档(shops.list/add/del/edit)及授权会话接口 shops.GetAuthorizeSessionKey", + "methods": [ + "shops.list", + "shops.add", + "shops.del", + "shops.edit", + "shops.GetAuthorizeSessionKey" + ], + "notes": [ + "同步实现:shops.list 支持 where 分页与 quickWhere 快速搜索;shops.add/edit 校验 platform_code 存在且为 ACTIVE,custom_name 必填且长度限制;shops.del 为软删除,会返回 deleted=true 并清空敏感字段,若存在快递接口引用返回 409;shops.GetAuthorizeSessionKey 对 PDD/CAINIAO 平台生成预占码并返回 authorize_url,其他平台返回 501。", + "字段命名兼容说明:接口实现兼容 snake_case 与 camelCase 入参,文档以 snake_case 为主并注明兼容性。" + ], + "type": "added" + }, + { + "version": "2026.05.25-system-03", + "date": "2026-05-25", + "summary": "同步 shops.add 去入参化:移除 shop_name 入参并明确由授权后获取店铺名称", + "methods": [ + "shops.add" + ], + "notes": [ + "shops.add 入参移除 shop_name(及同义传参语义),仅保留 custom_name 与 platform_code 为关键请求字段。", + "补充说明:新增时 shop_name 由服务端生成 PENDING_* 占位名,后续以授权回调同步真实店铺名称。", + "仅文档同步,不修改任何业务代码。" + ], + "type": "updated", + "module": "shops" + }, + { + "version": "2026.05.28-system-02", + "date": "2026-05-28", + "summary": "新增 method: order.print.unlockWavePlatformPrintDataByGroup,按分组解锁波次平台打印锁", + "methods": [ + "order.print.unlockWavePlatformPrintDataByGroup" + ], + "notes": [ + "新增方法:order.print.unlockWavePlatformPrintDataByGroup,用于按分组规则批量解锁波次内被锁定的订单(将 print_lock_status 设为 'none')。", + "入参说明:group_type 默认为 platform_express(支持 platform、platform_express、order),unlock_scope 默认为 group(支持 group、wave);groups 为必须项,元素对象可包含 wave_id、platform、sys_logistics_code、order_ids 等字段。", + "返回说明:返回 summary(解锁统计)、unlocked_order_ids、unlocked_orders、ext.missing_wave_ids、ext.filtered_wave_ids 等字段。", + "实现参考:app/service/systemMethods/order/print.js 与 app/service/systems/order_print.js 的 unlockWavePlatformPrintDataByGroup 实现,相关单元测试位于 test/app/controller/system.order.print.unlockByGroup.test.js 与 test/app/service/systems/order_print.unlockWavePlatformPrintDataByGroup.test.js。" + ], + "type": "updated" + }, + { + "version": "2026.05.28-system-03", + "date": "2026-05-28", + "summary": "新增 order.updateExpressWeighingWeight 方法文档并补充单/多运单称重写入规则", + "methods": [ + "order.updateExpressWeighingWeight" + ], + "notes": [ + "新增 order.updateExpressWeighingWeight 入参说明:order_id、waybill_code、weighing_weight。", + "明确规则:单运单订单忽略 waybill_code 并直接更新唯一运单;多运单订单必须传 waybill_code 且需匹配订单下运单。", + "补充成功返回字段:order_id、waybill_code、weighing_weight。", + "补充错误码:400(参数校验与多运单缺失运单号)、404(运单记录不存在或未匹配)、500(模型未初始化或更新失败)。", + "仅通过文档脚本同步 methods/system.json 与 methods/changes/system.json,不修改业务代码。" + ], + "type": "added", + "module": "order.index" + }, + { + "version": "2026.05.28-system-01", + "date": "2026-05-28", + "summary": "新增包材相关 methods(create/update/delete/get),并提供 list 兼容说明", + "methods": [ + "setting.packageMaterial.create", + "setting.packageMaterial.update", + "setting.packageMaterial.delete", + "setting.packageMaterial.get", + "setting.packageMaterial.list" + ], + "notes": [ + "实现参考:app/service/systems/setting/packageMaterial.js", + "list 为兼容别名,内部转发至 get,建议新接入方改用 get" + ], + "type": "updated" + }, + { + "version": "2026.05.28-system-04", + "date": "2026-05-28", + "summary": "Add packageSupplier methods (create/update/delete/get) with list alias note", + "methods": [ + "setting.packageSupplier.create", + "setting.packageSupplier.update", + "setting.packageSupplier.delete", + "setting.packageSupplier.get", + "setting.packageSupplier.list" + ], + "notes": [ + "Reference implementation: app/service/systems/setting/packageSupplier.js", + "list is a compatibility alias; prefer get" + ], + "type": "updated" + }, + { + "version": "2026.05.28-system-05", + "date": "2026-05-28", + "summary": "新增 order.bindExpressPackageMaterial 方法文档,支持按订单运单绑定包材", + "methods": [ + "order.bindExpressPackageMaterial" + ], + "notes": [ + "新增 order.bindExpressPackageMaterial 入参说明:order_id、waybill_code、package_material_code(均必填)。", + "补充行为说明:按订单ID+运单号匹配 wms_order_express,按包材编码匹配包材并绑定 package_material_id 与 package_material_name_snapshot。", + "补充成功返回字段:order_id、waybill_code、package_material_id、package_material_name_snapshot、package_material_code。", + "补充错误码:400 参数错误、404 包材编码不存在、404 订单运单记录不存在、500 绑定包材失败。", + "仅通过文档脚本同步 methods/system.json 与 methods/changes/system.json,不修改业务代码。" + ], + "type": "added", + "module": "order.index" + }, + { + "version": "2026.05.29-system-01", + "date": "2026-05-29", + "summary": "新增 order.export 与 order.exportTaskProgress:订单导出异步任务与进度查询", + "methods": [ + "order.export", + "order.exportTaskProgress" + ], + "notes": [ + "order.export:提交导出任务,入参支持 table_type/tableType(枚举 current/history/dispatch/outsourced,兼容订单模块别名)与 module/module_name,where/sort 语义与 order.list 一致。接口提交后立即返回 task_id,后台异步执行导出,导出进度与结果通过 order.exportTaskProgress 查询。", + "order.exportTaskProgress:按 task_id 查询任务进度,返回 task_id、status、progress、current_count、total_count、message、error、download_url、update_time;任务上传完成后 download_url 返回可下载链接,未找到时 status=not_found。" + ], + "type": "added", + "module": "order.index" + }, + { + "version": "2026.05.30-system-01", + "date": "2026-05-30", + "summary": "新增 print.notifyLock(及 notify_lock 兼容别名),并补充 print.send 写入订单操作日志的行为说明", + "methods": [ + "print.notifyLock", + "print.notify_lock", + "print.send" + ], + "notes": [ + "新增 print.notifyLock:入参支持 order_ids/orderIds、waveGroups、data.waveGroups(至少一类提供订单 ID);仅执行订单锁定流程,不发送打印任务;写打印任务日志 + 订单操作日志;返回 locked_count、order_ids_count、order_ids、source;错误:无有效订单ID(400)、锁定失败(500)。", + "补充 print.send 文档:说明接口在执行打印任务记录的同时会写入订单操作日志(记录打印相关操作)。", + "新增兼容别名 print.notify_lock:文档说明等价转调到 print.notifyLock。" + ], + "type": "updated", + "module": "print" + }, + { + "version": "2026.06.03-system-01", + "date": "2026-06-03", + "summary": "同步 pick.query 文档为 keyword 任务化语义并补充冲突错误码", + "methods": [ + "pick.query" + ], + "notes": [ + "入参由 waybill_code/full_display 统一为 keyword(支持运单号或波次号)。", + "成功返回调整为 task_id/status/tip,status 取值 existing 或 created。", + "补充 409 冲突语义:波次已有他人活动任务时返回任务归属信息。" + ], + "type": "updated" + }, + { + "version": "2026.06.03-system-02", + "date": "2026-06-03", + "summary": "更新 pick.wavePickTaskDetail:增加快递号/储位分配前置校验并返回 action+order_ids", + "methods": [ + "pick.wavePickTaskDetail" + ], + "notes": [ + "新增前置校验:任务内若存在未分配快递号订单,返回 400,data.action=assign_express,data.order_ids 为未分配订单ID列表。", + "新增前置校验:任务内若存在未分配储位订单,返回 400,data.action=assign_storage,data.order_ids 为未分配订单ID列表。", + "保留原有权限校验与详情结构,仅补充分配校验失败分支的返回约定。" + ], + "type": "updated" + }, + { + "version": "2026.06.03-system-03", + "date": "2026-06-03", + "summary": "更新 order.wave.batchList:新增同步状态输出与筛选 sync_assignment_status", + "methods": [ + "order.wave.batchList" + ], + "notes": [ + "新增返回字段语义:list[].sync_assignment_status,取值为未同步/部分同步/已同步/同步异常。", + "新增筛选入参 where.sync_assignment_status,支持 unsynced/partially_synced/synced 英文枚举。", + "同步状态筛选规则与分配状态一致:error 并入 unsynced 过滤集合。" + ], + "type": "updated" + }, + { + "version": "2026.06.03-system-04", + "date": "2026-06-03", + "summary": "更新拣货中间态流程文档:wavePickTaskDetail 增加完成标记,并新增中间态/完全提交接口", + "methods": [ + "pick.wavePickTaskDetail", + "pick.wavePickTaskSubmit", + "pick.wavePickTaskComplete" + ], + "notes": [ + "更新 pick.wavePickTaskDetail 返回:新增 task.is_completed、task.progress(total_orders/picked_orders/pending_orders)以及顶层 is_completed。", + "新增 pick.wavePickTaskSubmit:支持保存中间态 payload 到任务 ext_json.pick_intermediate,并返回当前完成状态与进度。", + "新增 pick.wavePickTaskComplete:支持 mode=1 全部确认与 mode=2 部分确认(order_ids),返回 confirmed_order_ids 与最新进度。" + ], + "type": "updated" + }, + { + "version": "2026.06.03-system-05", + "date": "2026-06-03", + "summary": "拣货车能力拆分为一级模块 pickCart:扫码查询、任务绑车、CRUD、编码查重", + "methods": [ + "pickCart.scan", + "pickCart.bindTaskCart", + "pickCart.create", + "pickCart.update", + "pickCart.delete", + "pickCart.detail", + "pickCart.list", + "pickCart.codeDuplicateCheck" + ], + "notes": [ + "拣货车能力独立为一级模块 pickCart,不再挂在 pick 模块下。", + "新增 pickCart.scan:PDA 按 cart_code 扫码查询拣货车信息,用于进入任务绑定流程。", + "新增 pickCart.bindTaskCart:支持按 cart_id/cart_code 将拣货车绑定到指定拣货任务,若车已绑定其他活动任务则返回冲突。", + "新增 pickCart.create/pickCart.update/pickCart.delete/pickCart.detail/pickCart.list:补齐拣货车增删查改与分页查询能力。", + "新增 pickCart.codeDuplicateCheck:支持 exclude_cart_id 排除自身,供编辑场景做非自身重复校验;拣货车编码在当前仓库内不可重复。" + ], + "type": "updated" + }, + { + "version": "2026.06.03-system-06", + "date": "2026-06-03", + "summary": "更新 order.wave.batchList:新增 only_todo、复核状态聚合与复核筛选", + "methods": [ + "order.wave.batchList" + ], + "notes": [ + "新增入参 only_todo(默认 0):传 1/true 时仅返回仍有未复核订单的波次(unreviewed_order_count > 0)。", + "新增返回字段:list[].unreviewed_order_count(未复核订单数)与 list[].review_assignment_status(未复核/部分复核/已复核)。", + "新增 where.review_assignment_status 筛选,支持 unreviewed/partially_reviewed/reviewed 英文枚举。" + ], + "type": "updated", + "module": "order.wave" + }, + { + "version": "2026.06.04-system-01", + "date": "2026-06-04", + "summary": "裁剪 pick.wavePickTaskDetail 返回:团购小波次(pick_mode=1)不返回 picking_details 字段以减少带宽", + "methods": [ + "pick.wavePickTaskDetail" + ], + "notes": [ + "在 picking_details 字段 description 中补充:当 pick_mode=1(团购小波次)时该字段不返回,减少带宽浪费;其他 pick_mode(2/3/4/5)正常返回 picking_details。", + "在接口 description 中补充该裁剪行为的说明。", + "picking_summary、picking_view、boxes 等字段不受影响,pick_mode=1 时仍正常返回。" + ], + "type": "updated" + }, + { + "version": "2026.06.04-system-02", + "date": "2026-06-04", + "summary": "完善 index.getPlatformList 文档:补充入参 systemOnly/full、响应字段及错误码 500", + "methods": [ + "index.getPlatformList" + ], + "notes": [ + "补充入参说明:systemOnly(可选,支持 is_system 别名,真值识别 true/1/'1'/'true')、full(可选,真值识别同上,为 true 时返回全量表字段与 route_platform_code/platid 等扩展信息)", + "补充响应 data 数组每项字段:code、name、value、label、platform_code、platform_name、default_express_interface、is_system_setting、id(仅仓库自定义项)、alias(仅仓库自定义项)、full 模式扩展字段说明", + "说明合并逻辑:系统平台在前,仓库自定义在后,同 code 仅保留首条(系统优先);systemOnly=true 仅返回系统平台", + "补充缓存策略:优先读缓存,key 格式为 platform:list:{warehouseId}[:full] 或 platform:list:system[:full]", + "补充错误码 500:数据库或缓存访问异常", + "仅文档更新,不修改任何业务实现" + ], + "type": "updated", + "module": "index" + }, + { + "version": "2026.06.04-system-03", + "date": "2026-06-04", + "summary": "作废 order.pendingOrder.downloadCreateTemplate 和 order.pendingOrder.importOrdersFromExcel", + "methods": [ + "order.pendingOrder.downloadCreateTemplate", + "order.pendingOrder.importOrdersFromExcel" + ], + "notes": [ + "order.pendingOrder.downloadCreateTemplate:下载订单导入模板方法已从代码中移除,标记为 deprecated。", + "order.pendingOrder.importOrdersFromExcel:从 Excel 导入订单方法已从代码中移除,标记为 deprecated。", + "两个方法的文档条目保留在 methods/system.json 中,仅追加 status: 'deprecated' 与 description 中的'(已作废)'标记,未删除。" + ], + "type": "deprecated" + }, + { + "version": "2026.06.05-system-01", + "date": "2026-06-05", + "summary": "新增 storeWarehouse.store.openAccount 接口:仓库代货主一键开户(合并注册账号+创建货主+签约)", + "methods": [ + "storeWarehouse.store.openAccount" + ], + "notes": [ + "新增 storeWarehouse.store.openAccount 方法,归属货主-仓库签约模块(storeWarehouse.store)。", + "接口同时完成账号注册、货主创建和仓库-货主签约,一步完成开户全流程。", + "当前主体必须为仓库角色(Authorization header 中携带的 token 对应仓库用户)。", + "必填参数:username(登录账号)、password(初始密码)、company_name(公司全称)、business_license(营业执照号)、contact_person(联系人)、contact_phone(联系电话)。", + "响应返回新创建的 store_id、account_id、contract_id、company_name、username、role_id。" + ], + "type": "added", + "module": "storeWarehouse" + }, + { + "version": "2026.06.05-system-02", + "date": "2026-06-05", + "summary": "优化 storeWarehouse.store.openAccount 必填参数:password 改为随机生成、business_license 和 contact_phone 改为可选,必填仅剩 username/company_name/contact_person 三个", + "methods": [ + "storeWarehouse.store.openAccount" + ], + "notes": [ + "password:由必填改为可选,不传时自动随机生成 12 位密码", + "business_license:由必填改为可选", + "contact_phone:由必填改为可选" + ], + "type": "updated" + }, + { + "version": "2026.06.05-system-03", + "date": "2026-06-05", + "summary": "saveApiConfig 增加 callback_url 参数,支持配置 API 回调通知地址", + "methods": [ + "storeWarehouse.store.saveApiConfig" + ], + "notes": [ + "新增 callback_url 参数:OpenAPI 类型接口支持配置回调通知 URL", + "兼容别名 callbackUrl,最大 500 字符", + "存入 wms_api_app.callback_url 字段" + ], + "type": "modified" + }, + { + "version": "2026.06.05-system-04", + "date": "2026-06-05", + "summary": "createOrder 入参 item_code 改为 item_id,province/city/area 改为必填", + "methods": [ + "order.pendingOrder.createOrder" + ], + "notes": [ + "items[].item_code → items[].item_id:改用商品主键直接匹配,不依赖外部系统商品推送", + "province/city/area 新增必填校验,空值返回 400", + "item_name 优先外部传入,其次从 StockStore 缓存获取,最后兜底'商品'" + ], + "type": "modified" + }, + { + "version": "2026.06.05-system-05", + "date": "2026-06-05", + "summary": "新增 order.pendingOrder.parseAddress 智能地址解析方法", + "methods": [ + "order.pendingOrder.parseAddress" + ], + "notes": [ + "使用 DeepSeek AI 模型将非结构化地址字符串解析为省/市/区/详细地址/收件人/手机号", + "解析结果可直接用于 createOrder 的 receiverInfo 字段", + "DeepSeek API Key 通过 DEEPSEEK_API_KEY 环境变量配置" + ], + "type": "added" + }, + { + "version": "2026.06.05-system-06", + "date": "2026-06-05", + "summary": "waveStrategyUpdate/waveStrategyCreate 新增 wave_prefix 参数", + "methods": [ + "order.wave.waveStrategyUpdate", + "order.wave.waveStrategyCreate" + ], + "notes": [ + "新增 wave_prefix 波次编号前缀字段,最多 5 个字符,为空存 null" + ], + "type": "modified" + }, + { + "version": "2026.06.05-system-07", + "date": "2026-06-05", + "summary": "parseAddress 响应新增 town 字段(乡镇/街道)", + "methods": [ + "order.pendingOrder.parseAddress" + ], + "notes": [ + "响应 data 中新增 town 字段,返回 AI 解析出的乡镇/街道名称" + ], + "type": "modified" + }, + { + "version": "2026.06.05-system-08", + "date": "2026-06-05", + "summary": "为 order.list 响应新增 recheck_status 字段(复核状态:none=未复核,fin=已复核)", + "methods": [ + "order.list" + ], + "notes": [ + "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" + ], + "type": "updated" + }, + { + "version": "2026.06.05-system-09", + "date": "2026-06-05", + "summary": "为 order.reviewOrder.list 响应新增 recheck_status 字段(复核状态:none=未复核,fin=已复核)", + "methods": [ + "order.reviewOrder.list" + ], + "notes": [ + "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" + ], + "type": "updated" + }, + { + "version": "2026.06.05-system-10", + "date": "2026-06-05", + "summary": "为 order.pendingOrder.list 响应新增 recheck_status 字段(复核状态:none=未复核,fin=已复核)", + "methods": [ + "order.pendingOrder.list" + ], + "notes": [ + "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" + ], + "type": "updated" + }, + { + "version": "2026.06.05-system-11", + "date": "2026-06-05", + "summary": "为 order.outboundOrder.list 响应新增 recheck_status 字段(复核状态:none=未复核,fin=已复核)", + "methods": [ + "order.outboundOrder.list" + ], + "notes": [ + "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" + ], + "type": "updated" + }, + { + "version": "2026.06.05-system-12", + "date": "2026-06-05", + "summary": "为 order.expectionOrder.list 响应新增 recheck_status 字段(复核状态:none=未复核,fin=已复核)", + "methods": [ + "order.expectionOrder.list" + ], + "notes": [ + "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" + ], + "type": "updated" + }, + { + "version": "2026.06.05-system-13", + "date": "2026-06-05", + "summary": "为 order.entrustOrder.list 响应新增 recheck_status 字段(复核状态:none=未复核,fin=已复核)", + "methods": [ + "order.entrustOrder.list" + ], + "notes": [ + "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" + ], + "type": "updated" + }, + { + "version": "2026.06.05-system-14", + "date": "2026-06-05", + "summary": "为 order.deliveryOrder.list 响应新增 recheck_status 字段(复核状态:none=未复核,fin=已复核)", + "methods": [ + "order.deliveryOrder.list" + ], + "notes": [ + "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" + ], + "type": "updated" + }, + { + "version": "2026.06.05-system-15", + "date": "2026-06-05", + "summary": "为 order.deliveryExpectionOrder.list 响应新增 recheck_status 字段(复核状态:none=未复核,fin=已复核)", + "methods": [ + "order.deliveryExpectionOrder.list" + ], + "notes": [ + "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" + ], + "type": "updated" + }, + { + "version": "2026.06.05-system-16", + "date": "2026-06-05", + "summary": "为 order.archiveOrder.list 响应新增 recheck_status 字段(复核状态:none=未复核,fin=已复核)", + "methods": [ + "order.archiveOrder.list" + ], + "notes": [ + "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" + ], + "type": "updated" + }, + { + "version": "2026.06.06-system-01", + "date": "2026-06-06", + "summary": "恢复 order.pendingOrder.downloadCreateTemplate:方法仍存在于代码中,取消 deprecated 标记,完善文档描述", + "methods": [ + "order.pendingOrder.downloadCreateTemplate" + ], + "notes": [ + "order.pendingOrder.downloadCreateTemplate 方法在 pendingOrder.js 中仍存在(line 2099),此前被误标记为 deprecated。", + "取消 status: 'deprecated' 标记,恢复为 active 状态。", + "移除 description 中的'(已作废)'后缀。", + "完善 description:说明模板包含必填列(橙色背景)、可选列(灰色背景)、示例数据行和填写说明工作表。", + "补充 response 字段说明:filename 和 mime 为固定值。" + ], + "type": "updated" + }, + { + "version": "2026.06.07-system-01", + "date": "2026-06-07", + "summary": "order.pendingOrder.createOrder 文档新增 shop_nick 入参(店铺名称,可选,最大长度200)", + "methods": [ + "order.pendingOrder.createOrder" + ], + "notes": [ + "在 order.pendingOrder.createOrder 的 request params 中新增 shop_nick 字段(string,非必填),对应代码实现中 shopNick: String(requestData.shop_nick || requestData.shopNick || '').trim()。", + "shop_nick 已在 COPY_FIELDS 白名单中(pendingOrder.js L1738),仅文档缺失,本次为补齐。" + ], + "type": "updated" + }, + { + "version": "2026.06.07-system-02", + "date": "2026-06-07", + "summary": "order.pendingOrder.downloadCreateTemplate:模板新增 shop_nick 列(店铺名称),store_id/province/city/area 标注为非必填", + "methods": [ + "order.pendingOrder.downloadCreateTemplate" + ], + "notes": [ + "模板新增 shop_nick(店铺名称)列,非必填。", + "明确标注 store_id(货主ID)、province(省份)、city(城市)、area(区/县)为非必填列。", + "响应文档中新增 shop_nick 字段说明。" + ], + "type": "updated" + }, + { + "version": "2026.06.07-system-03", + "date": "2026-06-07", + "summary": "新增 order.pendingOrder.updateAddress:批量修改待处理订单收件地址,限制未分配快递时可用", + "methods": [ + "order.pendingOrder.updateAddress" + ], + "notes": [ + "新增 method:order.pendingOrder.updateAddress,免权限(isNeedAuth=false),需登录", + "功能:批量修改待处理订单收件地址(name/mobile/tel/zip_code/province/city/area/town/detail_address)", + "约束:仅 post_status='none'(未分配快递)的订单可修改;至少提供一个有效地址字段", + "响应:返回 updated_count(实际更新行数)和 ids(请求订单ID数组)" + ], + "type": "added" + }, + { + "version": "2026.06.07-system-04", + "date": "2026-06-07", + "summary": "order.wave.wavePickTaskCancel 扩展可取消状态至 status=3,并新增拣货状态回退", + "methods": [ + "order.wave.wavePickTaskCancel" + ], + "notes": [ + "可取消状态从 [0,1,2] 扩展为 [0,1,2,3](status=3 已完成现在也可取消)", + "取消 status=2(待复核)或 status=3(已完成)任务时,自动回退 wms_wave_pick_task_order.pick_status(1→0)和 order_delivery.pick_status(fin→padding)", + "错误码 400 描述同步更新,补充 403 错误码说明" + ], + "type": "updated" + }, + { + "version": "2026.06.07-system-05", + "date": "2026-06-07", + "summary": "order.wave.wavePickTaskList 响应新增 cart_name 字段(拣货车名称)", + "methods": [ + "order.wave.wavePickTaskList" + ], + "notes": [ + "响应 list 子项新增 cart_name(string):通过 current_cart_id LEFT JOIN wms_pick_cart 表获取,未绑定拣货车时为空字符串。" + ], + "type": "updated" + }, + { + "version": "2026.06.07-system-06", + "date": "2026-06-07", + "summary": "pick.wavePickTaskComplete 新增后台抓取任务(source=2)拣货车绑定校验,未绑定拣货车时拒绝提交", + "methods": [ + "pick.wavePickTaskComplete" + ], + "notes": [ + "description 补充说明:后台抓取创建的任务(source=2)必须先绑定拣货车才能提交,否则返回 400。", + "errors 中 400 错误补充:后台抓取任务(source=2)未绑定拣货车时拒绝提交,错误消息为\"后台抓取任务必须先绑定拣货车才能提交\"。" + ], + "type": "updated" + }, + { + "version": "2026.06.07-system-07", + "date": "2026-06-07", + "summary": "order.wave.batchList 文档修正:移除代码中不存在的 sync_assignment_status 引用", + "methods": [ + "order.wave.batchList" + ], + "notes": [ + "从 where 描述中移除 sync_assignment_status(代码 buildBatchListWhereClause allowedFields 中不存在该字段,BATCH_LIST_ASSIGNMENT_FILTER_SCHEMAS 中也无 review 之外的同步类型)。", + "从 response list 描述中移除 sync_assignment_status(代码响应映射中仅返回 storage/express/print/review 四种 assignment_status,无 sync_assignment_status)。", + "v2026.06.03-system-03 变更记录中声称新增的 sync_assignment_status 实际从未在代码中实现,本次仅为文档修正,不涉及代码变更。" + ], + "type": "updated", + "module": "order.wave" + }, + { + "version": "2026.06.07-system-08", + "date": "2026-06-07", + "summary": "order.recheckOrder.confirmRecheck 补充后置行为说明:波次任务全部复核完成后自动解绑车任务", + "methods": [ + "order.recheckOrder.confirmRecheck" + ], + "notes": [ + "在 description 中补充:确认复核后,若该订单所属波次拣货任务下所有订单均已复核完成,则自动解绑车任务。解绑操作包括:清空 wms_wave_pick_task 的 current_cart_id/current_cart_code_snapshot、停用 wms_pick_task_cart_binding(is_active=0 并记录解绑人和时间)、释放 wms_pick_cart(清空 current_task_id/bind_user_id)。", + "解绑失败仅记录 warn 日志,不影响复核主流程。", + "入参和返回结构未变,仅补充行为说明。" + ], + "type": "updated" + }, + { + "version": "2026.06.07-system-10", + "date": "2026-06-07", + "summary": "移除 order.wave.groupFetch / singleFetch / fetch 响应中已废弃的 auto_fetch_disabled_marker 字段", + "methods": [ + "order.wave.groupFetch", + "order.wave.singleFetch", + "order.wave.fetch" + ], + "notes": [ + "auto_fetch_disabled_marker 字段已从代码 submitFetchTask 响应中移除,文档同步删除该字段的描述。", + "auto_fetch_disabled 字段同样已从代码中移除,且原文档中不存在此字段(仅有 auto_fetch_disabled_marker),无需额外处理。", + "涉及 method:order.wave.groupFetch、order.wave.singleFetch、order.wave.fetch,均移除 response 中的 auto_fetch_disabled_marker 字段。" + ], + "type": "updated", + "module": "order.wave" + }, + { + "version": "2026.06.08-system-01", + "date": "2026-06-08", + "summary": "order.recheckOrder 模块 scanOrder 返回值重构为统一 list 输出,新增 confirmIntercept 与 recheckOrderList 接口", + "methods": [ + "order.recheckOrder.scanOrder", + "order.recheckOrder.confirmIntercept", + "order.recheckOrder.recheckOrderList" + ], + "notes": [ + "scanOrder 返回值重构:统一使用 list 字段输出,新增 list_type 字段区分散单/团购模式。散单模式顶层新增 picker_id、picker_name、wave_id、wave_no、wave_type、pick_mode、strategy_id、strategy_name、total_orders、reviewed_count、unreviewed_count 等汇总字段。list 中每项新增 waybill_no、is_printed、is_reviewed、wave_index、intercept_status、store_remark、stock[](含 stock_id、item_code、item_name、sku_property、packing_requirements、barcodes[]、images[]、plan_qty、has_shared_barcode)。移除旧字段 logs、order、order_id(顶层)、waybill_no(顶层旧位置)、wave_match_view、items、expresses、cart_match_view。", + "scanOrder 入参新增 wave_no / waveNo 支持波次号直接扫描匹配。", + "新增 order.recheckOrder.confirmIntercept:确认拦截接口,将订单 intercept_status 更新为 intercepted_at_warehouse,返回 order_id、order_no、intercept_status、updated_at。", + "新增 order.recheckOrder.recheckOrderList:复核订单列表查询,支持 list_type=single(散单)与 list_type=group(团购),均返回统一 list + pagination 结构。" + ], + "type": "updated" + }, + { + "version": "2026.06.08-system-02", + "date": "2026-06-08", + "summary": "order.recheckOrder 模块新增 batchIntercept/batchInterceptTaskProgress,更新 scanOrder 团购模式响应结构,完善 confirmIntercept/recheckOrderList 文档", + "methods": [ + "order.recheckOrder.batchIntercept", + "order.recheckOrder.batchInterceptTaskProgress", + "order.recheckOrder.scanOrder", + "order.recheckOrder.confirmIntercept", + "order.recheckOrder.recheckOrderList" + ], + "notes": [ + "新增 order.recheckOrder.batchIntercept:批量提交订单拦截(异步任务模式),入参支持 order_ids/orderIds/ids(订单ID数组,不再使用 wave_ids),将 intercept_status 设为 'requested',返回 task_id/warehouse_id/message/accepted_at。支持幂等提交与 warehouse_id 校验。", + "新增 order.recheckOrder.batchInterceptTaskProgress:按 task_id 查询批量拦截任务进度,返回 state(submitted/running/success/failed/not_found)及对应的进度/计数/结果/错误字段。", + "更新 order.recheckOrder.scanOrder 响应文档:团购模式(cart 命中)list 项新增 wave_id/wave_no/wave_type/wave_status/total_orders/processed_orders/creator/create_time/update_time/order_count/pick_mode/box_no/orders[] 等波次级别字段;补充散单无波次信息时的回退详情模式说明(detail/items/expresses/logs)。", + "完善 order.recheckOrder.confirmIntercept:补充操作日志写入说明(ORDER_INTERCEPT_CONFIRM)及失败不影响主流程的容错描述。", + "完善 order.recheckOrder.recheckOrderList:补充散单模式默认排除 pick_status='none' 和 recheck_status='fin' 的说明;团购模式 where 支持 wave_no(模糊搜索)的说明。" + ], + "type": "updated" + }, + { + "version": "2026.06.08-system-03", + "date": "2026-06-08", + "summary": "移除 order.recheckOrder.batchIntercept 的 warehouse_id/warehouseId 入参,仓库ID统一使用当前上下文", + "methods": [ + "order.recheckOrder.batchIntercept" + ], + "notes": [ + "移除入参 warehouse_id / warehouseId:仓库ID统一从当前上下文(ctx.user.store_id)获取,不再由调用方传入。", + "移除对应错误码:warehouse_id 参数不合法(400)、warehouse_id 与当前仓库上下文不一致(400)。", + "description 中补充说明仓库ID来源为当前上下文。", + "response 中 warehouse_id 字段描述改为「取自当前上下文」。" + ], + "type": "updated" + }, + { + "version": "2026.06.08-system-10", + "date": "2026-06-08", + "summary": "batchIntercept / batchInterceptTaskProgress 从 order.recheckOrder 迁移至 order.pendingOrder", + "methods": [ + "order.pendingOrder.batchIntercept", + "order.pendingOrder.batchInterceptTaskProgress" + ], + "notes": [ + "method 从 order.recheckOrder.batchIntercept 重命名为 order.pendingOrder.batchIntercept,分组从订单复核模块迁移至订单待处理模块", + "method 从 order.recheckOrder.batchInterceptTaskProgress 重命名为 order.pendingOrder.batchInterceptTaskProgress,分组从订单复核模块迁移至订单待处理模块", + "接口入参、响应、错误码均保持不变,仅变更 method 名称与所属分组" + ], + "type": "updated" + }, + { + "version": "2026.06.08-system-04", + "date": "2026-06-08", + "summary": "新增 order.print.getOrderPrintData:按订单ID拉取打印数据,返回结构与 getWavePlatformPrintData 一致,不限制锁定状态", + "methods": [ + "order.print.getOrderPrintData" + ], + "notes": [ + "新增 order.print.getOrderPrintData 接口文档,入参为 warehouse_id + order_ids(非空数组),返回与 getWavePlatformPrintData 结构一致的 waveGroups / summary / wave_ids / ext", + "与 getWavePlatformPrintData 的区别:入参为 order_ids(非 wave_ids),ext 中返回 missing_order_ids / filtered_order_ids(非 missing_wave_ids / filtered_wave_ids)", + "不限制打印锁定状态,所有订单(无论是否被锁定)统一返回打印数据", + "自动过滤 post_status !== 'fin' 的订单(快递未完全分配),被过滤订单出现在 ext.filtered_order_ids" + ], + "type": "added", + "module": "order.print" + }, + { + "version": "2026.06.08-system-11", + "date": "2026-06-08", + "summary": "新增 order.pendingOrder 批量锁定/解锁/解除拦截及对应进度查询共 6 个异步任务接口文档", + "methods": [ + "order.pendingOrder.batchLock", + "order.pendingOrder.batchLockTaskProgress", + "order.pendingOrder.batchUnlock", + "order.pendingOrder.batchUnlockTaskProgress", + "order.pendingOrder.batchUnintercept", + "order.pendingOrder.batchUninterceptTaskProgress" + ], + "notes": [ + "新增 batchLock:批量锁定订单,lock_status → 'warehouse',操作日志 ORDER_LOCK,task_id 格式 order_lock_{warehouseId}_{timestamp}_{rand}。", + "新增 batchLockTaskProgress:查询批量锁定进度,返回 locked_order_count / locked_order_ids 等。", + "新增 batchUnlock:批量解锁订单,lock_status → 'none',操作日志 ORDER_UNLOCK,task_id 格式 order_unlock_{warehouseId}_{timestamp}_{rand}。", + "新增 batchUnlockTaskProgress:查询批量解锁进度,返回 unlocked_order_count / unlocked_order_ids 等。", + "新增 batchUnintercept:批量解除拦截订单,intercept_status → 'none',操作日志 ORDER_INTERCEPT_CANCEL,task_id 格式 order_unintercept_{warehouseId}_{timestamp}_{rand}。", + "新增 batchUninterceptTaskProgress:查询批量解除拦截进度,返回 unintercepted_order_count / unintercepted_order_ids 等。", + "以上 6 个接口均采用与已有 batchIntercept/batchInterceptTaskProgress 一致的异步任务模式:提交返回 task_id,进度查询返回 state + 进度字段。", + "仅同步文档,不修改业务代码或实现。" + ], + "type": "added", + "module": "order" + }, + { + "version": "2026.06.08-system-12", + "date": "2026-06-08", + "summary": "更新 order.print.getOrderPrintData:移除锁定限制,所有订单统一返回打印数据,不再区分锁定/未锁定", + "methods": [ + "order.print.getOrderPrintData" + ], + "notes": [ + "移除打印锁定限制:所有订单(包括已锁定)统一返回打印数据,不再区分锁定/未锁定状态", + "移除 locked_count、locked_orders、locked_wave_groups 等锁定相关字段", + "返回结构与 getWavePlatformPrintData 完全一致:summary / waveGroups / wave_ids / ext", + "ext 中使用 missing_order_ids / filtered_order_ids(替代锁定相关字段),与代码实现完全对齐" + ], + "type": "updated", + "module": "order.print" + }, + { + "version": "2026.06.08-system-13", + "date": "2026-06-08", + "summary": "更新 order.print.getOrderPrintData:移除 warehouse_id 入参,仓库ID统一从当前上下文获取", + "methods": [ + "order.print.getOrderPrintData" + ], + "notes": [ + "移除 warehouse_id / warehouseId 入参,仓库ID统一从 this.getContextWarehouseId() 获取", + "同步移除 errors 中 warehouse_id 必填 相关错误码", + "description 补充说明仓库ID从上下文获取,无需调用方传入", + "params 仅保留 order_ids(非空数组),与代码 method 层 getOrderPrintData(data) 解构一致" + ], + "type": "updated", + "module": "order.print" + }, + { + "version": "2026.06.08-system-14", + "date": "2026-06-08", + "summary": "新增 order.recheckOrder.scanTask 接口文档,并为 scanOrder 响应补充 task_id 字段", + "methods": [ + "order.recheckOrder.scanTask", + "order.recheckOrder.scanOrder" + ], + "notes": [ + "新增 order.recheckOrder.scanTask:按拣货任务 ID 拉取复核数据,数据结构与 scanOrder 完全一致,用于前端刷新。入参为 task_id(必填,number),返回 match_type='task',散单模式(pick_mode 2/3/4)返回扁平订单列表,团购模式(pick_mode 1/5)返回分组波次列表。", + "更新 order.recheckOrder.scanOrder 响应定义:补充 task_id 字段说明(散单有波次时由 buildSingleWaveScanView 返回,团单车号命中时由 cartMatchContext 返回)。", + "仅同步文档,不修改任何业务代码或实现。" + ], + "type": "updated" + }, + { + "version": "2026.06.08-system-15", + "date": "2026-06-08", + "summary": "新增 order.pendingOrder.manualWaybill 接口(手工录入运单号)", + "methods": [ + "order.pendingOrder.manualWaybill" + ], + "notes": [ + "为待处理订单手动录入运单号,写入 wms_order_express 表", + "仅允许 step 在 [1,2,3] 且 outbound_status 不为 'padding' 的订单操作", + "免权限(isNeedAuth: false),需登录", + "成功返回运单记录的 id、order_id、waybill_code、create_at" + ], + "type": "added" + }, + { + "version": "2026.06.09-system-01", + "date": "2026-06-09", + "summary": "order.pendingOrder.updateAddress 新增 remark 字段:订单留言/备注批量覆盖,不受 post_status 限制", + "methods": [ + "order.pendingOrder.updateAddress" + ], + "notes": [ + "在 params 中新增 remark 字段(string,可选,最大500字符),支持批量覆盖所选订单的 remark", + "remark 更新不受 post_status 限制,可对所有订单生效(地址字段仍仅允许 post_status='none')", + "更新 description 明确 remark 与地址字段的独立性", + "更新 response 中 updated_count 说明:取地址更新行数与备注更新行数的最大值", + "更新 errors 中缺少字段的错误描述,改为「至少需要提供一个地址字段或备注进行修改」", + "业务代码已同步实现,本次仅同步文档" + ], + "type": "updated" + }, + { + "version": "2026.06.09-system-02", + "date": "2026-06-09", + "summary": "order.updateExpressWeighingWeight 新增运单号模式文档:order_id=0 时从运单号反查,支持散单与团购批量两种返回结构", + "methods": [ + "order.updateExpressWeighingWeight" + ], + "notes": [ + "order_id 参数说明补充:设为0时切换为运单号模式,需配合 waybill_code 使用。", + "waybill_code 参数说明补充:运单号模式(order_id=0)下必填。", + "description 更新:明确订单模式与运单号模式两种路径及团购波次批量行为。", + "response 新增运单号散单场景字段(order_id、waybill_code、weighing_weight)与运单号团购批量场景字段(wave_no、business_key、weighing_weight、success_count)。", + "errors 新增运单号模式相关错误码:运单号不存在(404)、运单号对应的订单不存在(404)、波次下未找到订单(404)、批量更新失败(500)。", + "仅文档同步,不修改业务代码。" + ], + "type": "updated" + }, + { + "version": "2026.06.09-system-03", + "date": "2026-06-09", + "summary": "order.updateExpressWeighingWeight 团购返回新增拆单汇总字段,移除 success_count/total_count", + "methods": [ + "order.updateExpressWeighingWeight" + ], + "notes": [ + "团购批量模式 response 新增 total_weight(所有拆单重量累加)、split_count(waybill_code 非空的 business_key 数量)、splits(按 business_key 分组的拆单明细数组,每项含 business_key/weighing_weight/waybill_code)、store_name(货主名称)和 sys_logistics_name(系统快递名称)。", + "移除 response 中的 success_count 与 total_count 字段,改为由 total_weight 和 split_count 提供汇总信息。", + "更新 description 以反映团购模式返回拆单汇总结构。" + ], + "type": "updated" + }, + { + "version": "2026.06.10-system-01", + "date": "2026-06-10", + "summary": "order.detail 接口文档:expresses 数组新增字段 weighing_weight、sys_logistics_code、sys_logistics_name、business_key、created_at", + "methods": [ + "order.detail" + ], + "notes": [ + "expresses 数组新增字段:weighing_weight(称重重量,number|null)、sys_logistics_code(系统物流公司编码,string)、sys_logistics_name(系统物流公司名称,string)、business_key(业务标识,string)、created_at(创建时间戳毫秒,number|null)", + "字段来源:getOrderExpressesByOrderId 方法中 sys_logistics_code/sys_logistics_name 取自订单表 sys_logistics_code/sys_logistics_name,其余字段取自 OrderExpress 表" + ], + "type": "updated" + }, + { + "version": "2026.06.10-system-02", + "date": "2026-06-10", + "summary": "dashboard.order_trend 从 mock 数据改为查询真实数据库,按小时统计当日订单数与发货数,补充完整返回结构与错误说明", + "methods": [ + "dashboard.order_trend" + ], + "notes": [ + "接口实现从 mock 静态数据改为查询真实数据库(wms_order_delivery 与 dispatch 表),数据实时反映仓库当日运营情况。", + "订单筛选条件:step in [1,2,3],排除 outbound_status='padding' 和 status='cancel',统计 create_at 在今日 00:00 到当前时刻的订单,按 HOUR(create_at) 分组。", + "发货筛选条件:dispatch_lane='m4',统计 delivery_time 在今日 00:00 到当前时刻的发货记录,按 HOUR(delivery_time) 分组。", + "时段范围:从 08:00 到当前小时(最晚 23:00),若当前时间早于 08:00 则从 08:00 开始。", + "返回新增 summary 汇总对象:total_orders(订单总数)、total_shipments(发货总数)、shipment_rate(发货率百分比)、peak_hour(峰值时段)、peak_orders(峰值订单数)。", + "categories/orders/shipments 三个数组一一对应,提供按时段的订单与发货趋势数据,可直接用于前端折线图/柱状图渲染。", + "需要登录(Authorization header),从 token 中获取 warehouseId;若缺少仓库上下文则返回 flag='fail'。" + ], + "type": "updated", + "module": "dashboard" + }, + { + "version": "2026.06.10-system-03", + "date": "2026-06-10", + "summary": "order.pendingOrder.manualWaybill 新增可选参数 logistics_interface_name 与响应字段 business_key/logistics_interface_name,补充行为说明", + "methods": [ + "order.pendingOrder.manualWaybill" + ], + "notes": [ + "新增可选参数 logistics_interface_name(string,选填,trim 后为空则传 null)", + "响应新增字段 business_key(number):同一订单下从已有最大值 +1 递增,无记录时从 1 开始", + "响应新增字段 logistics_interface_name(string/null):写入的物流接口名称", + "补充 description 行为说明:完成后自动更新 wms_order_delivery_* 表的 print_status 和 post_status 为 'fin'", + "wms_order_express 表写入时 status 固定为 1,warehouse_id 从订单记录取" + ], + "type": "updated" + }, + { + "version": "2026.06.10-system-04", + "date": "2026-06-10", + "summary": "stock.warehouse.import 新增 barcode(条码)字段支持", + "methods": [ + "stock.warehouse.import" + ], + "notes": [ + "新增 barcode(条码)字段支持,支持别名:条码、bar_code、barCode、barcodeList、barcode_list、barcode。", + "条码字段支持数组格式(如 [\"6901234567890\"])和分号分隔字符串格式(如 \"6901234567890;6901234567891\")。", + "新建和更新路径均已支持条码导入,条码写入 wms_stock_barcodes 表。", + "仅同步文档,不修改业务代码或实现。" + ], + "type": "updated" + }, + { + "version": "2026.06.10-system-05", + "date": "2026-06-10", + "summary": "stock.warehouse.import 的 barcode 字段分隔符改为逗号,对齐 stock.warehouse.export 导出格式;仅接收字符串格式,不再支持数组", + "methods": [ + "stock.warehouse.import" + ], + "notes": [ + "barcode 字段分隔符从分号 ; 改为逗号 ,", + "barcode 字段仅接收字符串格式,不再支持数组格式", + "格式示例:\"6901234567890,6901234567891\",与 stock.warehouse.export 导出格式一致" + ], + "type": "modified" + }, + { + "version": "2026.06.13-system-01", + "date": "2026-06-13", + "summary": "setting.warehouse 的 auto_outbound_rules 新增 require_print 和 require_pick 两个可选条件字段(同步代码实现)", + "methods": [ + "setting.warehouse.getSettings", + "setting.warehouse.saveSettings" + ], + "notes": [ + "在 getSettings 响应和 saveSettings 入参中补充 subject_config.auto_outbound_rules 对象的完整字段文档(enabled、require_recheck、require_pack、require_weigh、require_sync、require_print、require_pick)。", + "require_print:是否要求已打印(print_status=fin),默认 true。", + "require_pick:是否要求已拣货(pick_status=fin),默认 true。", + "该规则由自动出库定时任务 order_auto_outbound 消费,全部开启的条件均满足时自动标记待出库。" + ], + "type": "updated" + }, + { + "version": "2026.06.13-system-02", + "date": "2026-06-13", + "summary": "order.recheckOrder.scanOrder 团购模式响应新增 orders_detail 字段,暴露非拦截订单的详细列表(含 is_printed、is_reviewed 等状态字段)", + "methods": [ + "order.recheckOrder.scanOrder" + ], + "notes": [ + "团购模式(list_type='group')波次视图项新增 orders_detail 字段:非拦截订单详细列表,每项含 order_id、delivery_order_code、waybill_no、pick_status、is_printed(print_status === 'fin')、is_reviewed(recheck_status === 'fin')、recheck_status、shop_nick、items_count、wave_index、intercept_status", + "orders_detail 与现有 order_ids(纯数字 ID 数组)并存,均在团购模式的波次视图项中返回", + "orders_detail 仅在 list_type='group' 时返回,散单模式不受影响", + "同步更新 list 字段 description 以反映 group 模式新增的 order_ids、orders_detail、stocks 字段" + ], + "type": "updated" + }, + { + "version": "2026.06.13-system-03", + "date": "2026-06-13", + "summary": "新增批量快捷复核接口 batchQuickRecheck,支持批量订单 IDs 的前置条件检查(储位、快递、同步、拦截),自动完成拣货并标记复核,支持部分失败。拣货完成后同步更新 wms_wave_pick_task 状态", + "methods": [ + "order.recheckOrder.batchQuickRecheck" + ], + "notes": [ + "新增 order.recheckOrder.batchQuickRecheck 方法", + "入参 ids 支持数组或逗号分隔字符串", + "响应包含 success/failed 列表及计数,failed 项含 reason 说明" + ], + "details": { + "description": "包含拣货任务状态同步:全部拣完→任务状态=2(已完成),未全拣完→任务状态推进为1(拣货中)" + }, + "type": "added" + }, + { + "version": "2026.06.14-system-01", + "date": "2026-06-14", + "summary": "新增 order.bindExpressPackageMaterialByWaybill 方法:支持仅凭运单号绑定包材,无需传入订单ID", + "methods": [ + "order.bindExpressPackageMaterialByWaybill" + ], + "notes": [ + "新增 order.bindExpressPackageMaterialByWaybill 入参说明:waybill_code(运单号,必填)、package_material_code(包材编码,必填)。无需传入 order_id。", + "成功返回字段:order_id、waybill_code、package_material_id、package_material_name_snapshot、package_material_code。", + "错误码定义:400(参数错误)、404(运单号不存在 / 包材编码不存在)、500(绑定包材失败)。" + ], + "type": "added" + }, + { + "version": "2026.06.15-system-01", + "date": "2026-06-15", + "summary": "order.detail / order.deliveryOrder.detail 的 expresses 数组新增包材字段", + "methods": [ + "order.detail", + "order.deliveryOrder.detail" + ], + "notes": [ + "expresses 数组每个元素新增 package_material_id(包材ID,number|null)和 package_material_name_snapshot(包材名称快照,string|null)字段。" + ], + "type": "updated" + }, + { + "version": "2026.06.15-system-02", + "date": "2026-06-15", + "summary": "order.deliveryOrder.detail 的 expresses 数组新增包材字段", + "methods": [ + "order.deliveryOrder.detail" + ], + "notes": [ + "expresses 数组每个元素新增 package_material_id(包材ID,number|null)和 package_material_name_snapshot(包材名称快照,string|null)字段。" + ], + "type": "updated" + }, + { + "version": "2026.06.15-system-03", + "date": "2026-06-15", + "summary": "新增 setting.packageMaterial.search 方法:支持按关键字模糊搜索包材编码和名称", + "methods": [ + "setting.packageMaterial.search" + ], + "notes": [ + "新增 setting.packageMaterial.search 入参 keyword(可选),为空返回前 50 条启用中包材,有值时对 material_code 和 material_name 做模糊匹配。", + "返回包材数组,字段:id、material_code、material_name、material_type、spec、status。" + ], + "type": "added" + }, + { + "version": "2026.06.16-system-01", + "date": "2026-06-16", + "summary": "新增 order.recheckOrder.queryRecheckOrderSingleList:散单复核列表接口,响应新增 items_weight(总重量g)和 weight_type(重量类型)字段", + "methods": [ + "order.recheckOrder.queryRecheckOrderSingleList" + ], + "notes": [ + "新增方法 order.recheckOrder.queryRecheckOrderSingleList,为 recheckOrderList 散单模式的独立入口。", + "响应 list 每项新增字段 items_weight (DECIMAL(10,2)):订单总重量(g),来自 wms_order.items_weight,为 null 时返回 null。", + "响应 list 每项新增字段 weight_type (string):重量类型中文标签,来自 wms_order.weight_type 经 formatWeightTypeLabel 转换;取值:常规/轻货/重货/冷链(对应 DB 值 0/1/2/3)。" + ], + "type": "added", + "module": "order.recheckOrder" + }, + { + "version": "2026.06.16-system-02", + "date": "2026-06-16", + "summary": "为 order.wave.groupOrderFetchList / waveStrategyFallbackOrderList / singleOrderFetchList 响应新增 items_weight(总重量g)和 weight_type(重量类型)字段", + "methods": [ + "order.wave.groupOrderFetchList", + "order.wave.waveStrategyFallbackOrderList", + "order.wave.singleOrderFetchList" + ], + "notes": [ + "order.wave.groupOrderFetchList:响应 list 每项新增 items_weight (number|null):订单总重量(g),取组内首单 items_weight;组内订单 items_hash 相同重量一致。", + "order.wave.waveStrategyFallbackOrderList:响应 list 每项新增 items_weight (number|null):订单总重量(g),来自 wms_order.items_weight;新增 weight_type (string):重量类型中文标签,取值:常规/轻货/重货/冷链(对应 DB 值 0/1/2/3)。", + "order.wave.singleOrderFetchList:响应 list 每项新增 items_weight (number|null):订单总重量(g),取组内首单 items_weight;组内订单 items_hash 相同重量一致。", + "所有新增字段均为可选(required=false),为 null 时返回 null。" + ], + "type": "updated", + "module": "order.wave" + }, + { + "version": "2026.06.17-system-01", + "date": "2026-06-17", + "summary": "新增 order.pendingOrder.replenishmentDemand 分拣缺货补货需求计算接口文档", + "methods": [ + "order.pendingOrder.replenishmentDemand" + ], + "notes": [ + "新增分拣缺货补货需求计算方法,用于计算待处理订单的SKU在分拣区与存货区的库存分布及补货缺口", + "入参 order_ids/warehouse_id 均为可选;不传 order_ids 时自动查询当前仓库所有未完成储位分配的订单", + "纯只读查询接口,不修改任何数据", + "响应包含 list(明细)与 summary(汇总),其中 shortage = max(0, total_demand - pick_zone_quantity),replenishment_needed = min(shortage, storage_zone_quantity)" + ], + "type": "add", + "module": "order.pendingOrder" + }, + { + "version": "2026.06.17-system-02", + "date": "2026-06-17", + "type": "update", + "module": "order.pendingOrder", + "method": "order.pendingOrder.replenishmentDemand", + "description": "移除 order_ids 参数,改为纯仓库级别计算,自动查询当前仓库所有未完成储位分配的订单" + }, + { + "version": "2026.06.17-system-03", + "date": "2026-06-17", + "type": "update", + "module": "order.pendingOrder", + "method": "order.pendingOrder.replenishmentDemand", + "description": "新增 is_true_shortage 字段标识真正缺货(两区均无库存),summary 新增 total_true_shortage_skus 统计" + }, + { + "version": "2026.06.17-system-04", + "date": "2026-06-17", + "type": "migrate", + "module": "storage.management", + "summary": "从 order.pendingOrder.replenishmentDemand 迁移至 storage.management.replenishmentDemand(库存管理模块),原路径已删除,开发阶段无需兼容", + "methods": [ + "storage.management.replenishmentDemand" + ], + "notes": [ + "将 replenishmentDemand 接口从 order.pendingOrder 模块迁移到新建的 storage.management 库存管理模块。", + "旧条目 order.pendingOrder.replenishmentDemand 已从 order.pendingOrder 组中移除。", + "开发阶段无需兼容旧路径。" + ] + }, + { + "version": "2026.06.17-system-05", + "date": "2026-06-17", + "type": "update", + "module": "storage.management", + "summary": "storage.management.replenishmentDemand 移除 warehouse_id 入参,仓库ID改为纯从用户上下文(ctx.user)获取,接口无需入参", + "methods": [ + "storage.management.replenishmentDemand" + ], + "notes": [ + "移除 warehouse_id 入参,仓库ID改为纯从用户上下文(ctx.user)获取,接口无需入参" + ] + }, + { + "version": "2026.06.17-system-06", + "date": "2026-06-17", + "type": "update", + "module": "storage.management", + "method": "storage.management.replenishmentDemand", + "description": "新增分页入参(pagination)、排序入参(sort,默认按 shortage DESC)、响应新增 replenishment_locations(存货区可补货库位,最多5条)、响应新增 pagination 分页信息" + }, + { + "version": "2026.06.17-system-07", + "date": "2026-06-17", + "type": "update", + "module": "storage.management", + "summary": "replenishment_locations 新增 space_name 字段,优先取自定义名称(custom_name),无则回退库位编码(space_code)", + "methods": [ + "storage.management.replenishmentDemand" + ], + "notes": [ + "在 replenishment_locations.children 中新增 space_name 字段(string, required),放在 space_code 之后、available_quantity 之前。", + "space_name 取值逻辑:优先使用库位自定义名称 custom_name,若无自定义名称则回退为库位编码 space_code。" + ] + }, + { + "version": "2026.06.17-system-08", + "date": "2026-06-17", + "type": "update", + "module": "storage.management", + "summary": "合并 is_sufficient 和 is_true_shortage 为 replenishment_status 枚举字段(replenishable/true_shortage)", + "methods": [ + "storage.management.replenishmentDemand" + ], + "notes": [ + "删除 is_sufficient(boolean)和 is_true_shortage(boolean)两个字段。", + "新增 replenishment_status(string)枚举字段:replenishable=存货区足够覆盖缺口,移库可解决;true_shortage=存货区不足以覆盖缺口或两区均无库存,需采购。" + ] + }, + { + "version": "2026.06.18-system-01", + "date": "2026-06-18", + "summary": "入库单完成后异步匹配收货单并回传:completeEntry / entryorderConfirm 入库完成时自动匹配收货单,明细一致则按来源回传(奇门/OpenAPI),覆盖场景标记收货单部分入库;completeReceiving 完成后清除收货单缓存", + "methods": [ + "storage.entry.completeEntry", + "storage.receiving.completeReceiving" + ], + "notes": [ + "新增 app/service/systems/receiving_entry_match.js:入库单完成后异步匹配收货单并回传的核心服务,含 Redis 缓存收货单列表(TTL 300s)、remark 匹配收货单号、明细对比、奇门回传、OpenAPI 回调、部分入库标记等能力。", + "storage.entry.completeEntry 完成后通过 setImmediate 异步触发 matchAfterEntryCompleted,不阻塞主流程。", + "entry_order.js entryorderConfirm() 事务提交后(isFin 最终完成)同样异步触发匹配。", + "storage.receiving.completeReceiving 完成后清除收货单 Redis 缓存(cache:receiving_orders:warehouse:{warehouseId}),确保下次匹配获取最新收货单列表。", + "匹配规则:入库单 remark 包含收货单号 → 对比 SKU+数量 → 完全一致回传 / 收货单覆盖标记部分入库 / 其他不处理。", + "回传路径:source_type=QM → 奇门 taobao.qimen.entryorder.confirm;source_type=API → OpenAPI 回调(entry_order_receiving_matched 事件)。" + ], + "type": "updated" + }, + { + "version": "2026.06.18-system-02", + "date": "2026-06-18", + "summary": "新增 storage.receiving.manualMatchEntryOrder 接口", + "methods": [ + "storage.receiving.manualMatchEntryOrder" + ], + "notes": [ + "新增 storage.receiving.manualMatchEntryOrder:手动匹配入库单与收货单,传入 receivingId 和 entryOrderId,复用异步匹配服务的明细对比和回传逻辑,同步返回匹配结果", + "参数:receivingId (number, 必填)、entryOrderId (number, 必填)", + "校验:入库单存在性、收货单存在性、同仓库校验", + "返回 matchType (full_match/receiving_covers_entry/entry_exceeds_receiving/no_match)、comparisonResult、callbackSent、callbackResult、partialStorageMarked、entryOrder、receivingOrder" + ], + "type": "added", + "module": "storage" + }, + { + "version": "2026.06.18-system-03", + "date": "2026-06-18", + "summary": "新增 storage.receiving.getAvailableInboundQuantity 接口:按 stock_id 查询已审核收货单的可入库数量(actual_quantity - stored_quantity),排除未审核和已取消的收货单", + "methods": [ + "storage.receiving.getAvailableInboundQuantity" + ], + "notes": [ + "新增 system method:storage.receiving.getAvailableInboundQuantity,按 stock_id 查询已审核收货单中各明细的可入库数量(actual_quantity - stored_quantity),仅返回尚有可入库余量的明细。", + "实现文件:app/service/systemMethods/storage/receiving.js(包装层)、app/service/systems/storage/receiving.js(业务层)。", + "接口无需鉴权(isNeedAuth=false),但需要登录(isNeedLogin=true)。", + "入参 stock_id 为必填,对应 stock_warehouse.id;服务端从 ctx.user.store_id 获取仓库上下文。" + ], + "type": "added", + "module": "storage" + }, + { + "version": "2026.06.18-system-04", + "date": "2026-06-18", + "summary": "新增 storage.entry.bindReceivingDetails 接口和 wms_entry_receiving_binding 中间表:入库单明细可显式绑定收货明细(pending状态),提交入库时事务内完成双向扣减(stored_quantity/received_quantity),通过唯一约束和行锁防止超分和重复绑定。同时重构 completeEntry 调用链为 commitEntryWithBindings,无绑定时向后兼容。", + "methods": [ + "storage.entry.bindReceivingDetails", + "storage.entry.completeEntry" + ], + "notes": [ + "新增 storage.entry.bindReceivingDetails 方法:入库单明细绑定收货明细,pending 状态软绑定,每次调用清除旧 pending 绑定后创建新绑定。", + "新增 wms_entry_receiving_binding 中间表(migration: 20260618150000-create-wms-entry-receiving-binding.js),用于记录入库明细与收货明细的绑定关系。", + "重构 completeEntry 调用链:systemMethods 层 completeEntry 改为调用 commitEntryWithBindings,有绑定则事务内完成双向扣减(stored_quantity/received_quantity),无绑定时向后兼容仅变更入库单状态。", + "通过数据库唯一约束和行锁(SELECT ... FOR UPDATE)防止超分和重复绑定。", + "涉及文件: app/model/entry_receiving_binding.js, app/service/systems/storage/entry.js, app/service/systemMethods/storage/entry.js, database/migrations/20260618150000-create-wms-entry-receiving-binding.js" + ], + "type": "added", + "module": "storage.entry" + }, + { + "version": "2026.06.18-system-05", + "date": "2026-06-18", + "summary": "storage.entry.get 响应追加 pending_total/total_planned/bindings 字段,storage.receiving.getAvailableInboundQuantity 响应追加 pending_allocated_quantity 字段:前端可通过 get 查看入库明细的绑定状态,getAvailableInboundQuantity 的可用量已扣除全局 pending 绑定总量", + "methods": [ + "storage.entry.get", + "storage.receiving.getAvailableInboundQuantity" + ], + "notes": [ + "storage.entry.get:items 数组每项新增 pending_total(该入库明细当前 pending 绑定的总预分配数量)、total_planned(计划入库数量=count)、bindings(pending 绑定列表,每项含 id/entry_item_id/receiving_detail_id/allocated_quantity/status/receivingDetail 子对象)", + "storage.receiving.getAvailableInboundQuantity:list 每项新增 pending_allocated_quantity(该收货明细在当前 stock_id 所有入库单中的 pending 绑定总量),available_quantity 计算已扣除该值" + ], + "type": "updated" + }, + { + "version": "2026.06.18-system-06", + "date": "2026-06-18", + "summary": "bindReceivingDetails 重构为\"绑定即实收\"(received_quantity 在绑定时更新,不再等到 completeEntry),新增 unbindReceivingDetails 解绑接口(删除 pending 绑定并回退 received_quantity),commitEntryWithBindings 移除 received_quantity 更新逻辑", + "methods": [ + "storage.entry.bindReceivingDetails", + "storage.entry.unbindReceivingDetails", + "storage.entry.completeEntry" + ], + "notes": [ + "storage.entry.bindReceivingDetails:改为绑定即实收,绑定成功后立即更新入库明细 received_quantity;重复调用时先回退旧绑定量再创建新绑定,避免重复累加。", + "storage.entry.unbindReceivingDetails:新增解绑接口,删除该入库明细的所有 pending 绑定记录,并将 received_quantity 回退到绑定前的值;收货明细可用数量随绑定记录删除自动恢复。", + "storage.entry.completeEntry:commitEntryWithBindings 中移除 received_quantity 更新逻辑(received_quantity 已在绑定时更新,completeEntry 仅完成收货单侧入库数量扣减和库存上架)。" + ], + "type": "updated" + }, + { + "version": "2026.06.19-system-01", + "date": "2026-06-19", + "summary": "order.recheckOrder.scanOrder 响应 list[] 新增 items_weight(订单商品总重量g)和 suggested_package_material(推荐包材)字段", + "methods": [ + "order.recheckOrder.scanOrder" + ], + "notes": [ + "响应 list 每项新增 items_weight (number|null):订单商品总重量(g),来源于 wms_order_delivery.items_weight。散单模式每个订单对象包含,团购模式每个波次对象包含(取波次内首个正常订单的重量,为 null 时返回 0)。", + "响应 list 每项新增 suggested_package_material (object|null):推荐包材信息,根据订单商品结构(items_hash + items_crc)匹配 wms_package_material_item_relation 历史绑定记录,按 bind_count 降序取最优匹配。若 items_hash 为空或无匹配记录则为 null。包含子字段:id、code、name、spec、type、weight、length、width、height、bind_count。", + "同步更新 method description 和 list 字段 description,补充新增字段的说明。" + ], + "type": "updated", + "module": "order.recheckOrder" + }, + { + "version": "2026.06.21-system-01", + "date": "2026-06-21", + "summary": "order.bindExpressPackageMaterialByWaybill:入参 package_material_code 改为 package_material_id,类型由 string 改为 number|string", + "methods": [ + "order.bindExpressPackageMaterialByWaybill" + ], + "notes": [ + "入参字段名从 package_material_code 改为 package_material_id。", + "入参类型从 string 改为 number|string,与代码 normalizePackageMaterialId 的实现一致。", + "同步更新该方法 description 中'包材编码'为'包材ID'。" + ], + "type": "updated", + "module": "order" + }, + { + "version": "2026.06.21-system-comboGoods-01", + "date": "2026-06-21", + "summary": "新增 comboGoods 组合商品模块 5 个接口文档:list/create/update/delete/search", + "methods": [ + "comboGoods.list", + "comboGoods.create", + "comboGoods.update", + "comboGoods.delete", + "comboGoods.search" + ], + "notes": [ + "comboGoods.list:组合商品列表查询(分页),支持按 combo_code/combo_name/status/warehouse_id 筛选,返回含 simpleNotation 和 nameNotation 简记字段", + "comboGoods.create:创建组合商品(含明细一次性提交),校验 combo_code 唯一性、子商品有效性和货主一致性,事务保证原子写入", + "comboGoods.update:编辑组合商品(含明细替换),支持部分字段更新,传入 items 则先删旧明细再插入新明细", + "comboGoods.delete:软删除组合商品(status 置为 0)", + "comboGoods.search:关键字搜索组合商品,模糊匹配 combo_code 或 combo_name,仅返回启用状态记录,上限100条", + "数据表:wms_combo_goods(主表)+ wms_combo_goods_item(明细表);子商品校验依赖 wms_stock_warehouse 表", + "代码文件:app/service/systems/comboGoods.js(业务逻辑层)+ app/service/systemMethods/comboGoods.js(接口包装层)", + "isNeedAuth:list/search 无需鉴权,create/update/delete 需要鉴权" + ], + "type": "added", + "module": "comboGoods" + }, + { + "version": "2026.06.21-system-comboGoods-02", + "date": "2026-06-21", + "summary": "comboGoods 模块新增 custom_code(自定义编码)功能:create/update 支持传入 custom_code 并校验按货主唯一,list/search 返回新增 custom_code 字段,search 搜索范围扩展至 custom_code 且优先排列匹配项", + "methods": [ + "comboGoods.list", + "comboGoods.create", + "comboGoods.update", + "comboGoods.search" + ], + "notes": [ + "新增字段 custom_code(VARCHAR(64) NULL),仅做按货主唯一性校验(排除已删除记录),非全局唯一。", + "wms_combo_goods 表新增索引 uk_store_custom_code(warehouse_id, custom_code)。", + "comboGoods.create:新增可选入参 custom_code,如果非空则校验同货主非删除记录中 unique;返回新增 custom_code 字段。", + "comboGoods.update:新增可选入参 custom_code,如果非空则校验同货主非删除记录中 unique(排除自身 id)。", + "comboGoods.list:返回每条记录新增 custom_code 字段。", + "comboGoods.search:搜索条件扩大为 custom_code LIKE / combo_code LIKE / combo_name LIKE,custom_code 匹配项按 ORDER BY CASE 排在前面;返回新增 custom_code 字段。" + ], + "type": "updated" + }, + { + "version": "2026.06.21-system-comboGoods-03", + "date": "2026-06-21", + "summary": "stock.warehouse.search 新增 mode=\"combo\" 组合商品查询模式,新增 id/custom_code 参数,补充组合商品响应结构", + "methods": [ + "stock.warehouse.search" + ], + "notes": [ + "新增入参 mode(查询模式,传 \"combo\" 时搜索组合商品),id(mode=combo 时按组合商品ID精确查询),custom_code(mode=combo 时按自定义编码模糊查询)", + "原有 keyword 参数在 mode=combo 时模糊匹配 combo_code / combo_name / custom_code", + "mode=combo 响应结构新增 combo_code、combo_name、custom_code、items(子商品数组含 item_goods_sku_id/item_quantity)、simpleNotation(stock_id|数量格式)、nameNotation(【数量】商品名称格式)", + "mode=combo 时不返回 stock 模式特有的字段(item_code/goods_code/item_name/sku_property/stock_unit/quantity/locked_quantity/brand_name/item_type/barcodes/store_stock/效期字段/storage)", + "with_stock 和 is_batch 参数在 mode=combo 时不生效" + ], + "type": "updated" + }, + { + "version": "2026.06.22-system-wavePickTaskList-01", + "date": "2026-06-22", + "summary": "order.wave.wavePickTaskList 响应新增 wave_list 数组:每个拣货任务返回关联波次列表", + "methods": [ + "order.wave.wavePickTaskList" + ], + "notes": [ + "wavePickTaskList 响应 list 每项新增 wave_list 数组字段,通过批量查询 wms_wave_pick_task_wave 表获取关联波次详情。", + "wave_list 每项包含:wave_id(波次ID)、wave_no(波次号)、box_no(框号)、status(波次关联状态)、bind_time(绑定时间)、pick_time(拣货完成时间)。", + "无需额外入参,默认对所有拣货任务返回 wave_list;查询为空时返回空数组 []。", + "同步更新 methods/system.json 响应文档。" + ], + "type": "updated", + "module": "order.wave" + }, + { + "version": "2026.06.22-system-order-export-mode-01", + "date": "2026-06-22", + "summary": "order.export 新增 export_mode 参数:支持 waybill(默认,按运单展开)与 item(按商品明细展开)两种导出模式", + "methods": [ + "order.export" + ], + "notes": [ + "新增入参 export_mode/exportMode,枚举值:waybill(默认)— 按运单号展开,每运单一组,items_detail 列汇总商品;item — 按商品明细展开,每商品一行,运单信息汇总填充。", + "方法层(OrderIndexService.export)新增 export_mode/exportMode 解构并透传到 systems.orderExport.exportOrders。", + "同步更新 methods/system.json 文档:description 补充 export_mode 说明,params 新增 export_mode/exportMode 条目。", + "order.export 导出的列新增:业务类型、运单接口、包材ID、包材编码、包材名称。" + ], + "type": "updated", + "module": "order.index" + }, + { + "version": "2026.06.22-system-directInbound-01", + "date": "2026-06-22", + "summary": "新增 storage.directInbound 导入/PDA直接入库模块:getItems(获取入库信息)、addItem(增量添加商品)、commit(提交完成入库并回传)", + "methods": [ + "storage.directInbound.getItems", + "storage.directInbound.addItem", + "storage.directInbound.commit" + ], + "notes": [ + "新增 storage.directInbound 模块,用于非收货单途径的导入/PDA 直接入库场景。", + "storage.directInbound.getItems:根据入库单号获取入库明细及已有的导入/PDA 入库记录,返回每项的可入库余量。", + "storage.directInbound.addItem:按 stock_id 增量添加导入/PDA 入库记录,累加超过该 stock_id 在入库单中的计划总量时拒绝。支持 import(导入)和 pda(PDA)两种方式。", + "storage.directInbound.commit:提交确认完成入库,按实收数量写入 wms_storage 库存和 wms_storage_transaction 流水,同 stock_id 多条明细只写一次库存,更新入库单状态为 COMPLETED 并同步 sync_status=SUCCESS,异步触发奇门/API 回传(按实收数量回传)。不足量提交时未入库商品跳过。", + "新增数据表 wms_inbound_direct_log(migration: 20260622100000-create-wms-inbound-direct-log.js):记录非收货单途径入库操作,含 warehouse_id、stock_id、quantity、inbound_type(import/pda)、entry_order_id、operator 等字段。模型文件:app/model/inbound_direct_log.js。", + "新增操作日志:addItem 记录 DIRECT_INBOUND_ADD(异步),commit 记录 DIRECT_INBOUND_COMMIT(事务内)。commit 响应返回 order_status=COMPLETED 和 sync_status=SUCCESS。", + "涉及文件:app/service/systems/inbound_direct_log.js(业务层)、app/service/systemMethods/storage/direct_inbound.js(包装层)、app/model/inbound_direct_log.js、database/migrations/20260622100000-create-wms-inbound-direct-log.js、methods/system.json(新增导入/PDA入库模块)。", + "E2E 测试:test/e2e_direct_inbound.test.js(53项断言全覆盖)。" + ], + "type": "added", + "module": "storage.directInbound" + }, + { + "version": "2026.06.22-system-directInbound-02", + "date": "2026-06-22", + "summary": "storage.directInbound.addItem 新增批量模式(items 数组),getItems 响应 summary 新增 total_import/total_pda 分类型汇总", + "methods": [ + "storage.directInbound.addItem", + "storage.directInbound.getItems" + ], + "notes": [ + "addItem 新增批量模式:支持传入 items 数组一次添加多条商品,每项含 stock_id/quantity/inbound_type/remark。单条模式(stock_id/quantity/inbound_type 顶层字段)保持向后兼容。批量模式下所有商品共享同一个入库单状态校验,任一商品校验失败整批拒绝。", + "addItem 批量模式响应结构:{ count, total_quantity, items: [...] },items 每项含 id/stock_id/quantity/inbound_type/plan_quantity/existing_before/existing_after/remaining。", + "getItems 响应 summary 新增 total_import(导入入库总数)和 total_pda(PDA入库总数)字段。", + "同步更新 methods/system.json 文档。" + ], + "type": "updated", + "module": "storage.directInbound" + }, + { + "version": "2026.06.22-system-directInbound-03", + "date": "2026-06-22", + "summary": "storage.directInbound 新增 space_id 库位支持:addItem 支持传入 space_id(单条和批量),commit 从入库记录取 space_id 写入 wms_storage 替代硬编码 1", + "methods": [ + "storage.directInbound.addItem", + "storage.directInbound.commit", + "storage.directInbound.getItems" + ], + "notes": [ + "addItem 新增可选入参 space_id(单条模式顶层字段 / 批量模式 items[].space_id),指定存放库位ID,关联 wms_location_space.id。", + "wms_inbound_direct_log 表新增 space_id 字段(migration: 20260622110000-add-space-id-to-wms-inbound-direct-log.js)。", + "commit 从入库记录中取第一个非空 space_id 写入 wms_storage,无记录时兜底使用库位 1。", + "getItems 响应中 direct_logs 每条记录包含 space_id 字段。", + "同步更新 methods/system.json 文档及模型文件。" + ], + "type": "updated", + "module": "storage.directInbound" + }, + { + "version": "2026.06.23-system-01", + "date": "2026-06-23", + "summary": "入库单(wms_entry_order)新增 CREATED 状态:order_status ENUM 从 CREATING/PENDING/CONFIRMED/PARTIAL_RECEIVED/COMPLETED/CANCELLED 扩展为 CREATING/CREATED/PENDING/CONFIRMED/PARTIAL_RECEIVED/COMPLETED/CANCELLED;默认值从 PENDING 变更为 CREATED;validTransitions 增加 CREATED 节点(CREATED→PENDING/CANCELLED,CREATING→CREATED/CANCELLED)", + "methods": [ + "storage.entry.list", + "storage.entry.get", + "storage.entry.cancel", + "storage.entry.completeEntry", + "storage.entry.bindReceivingDetails" + ], + "notes": [ + "Model 层:app/model/entry_order.js order_status ENUM 新增 CREATED,默认值从 PENDING 变更为 CREATED", + "Service 层:app/service/systems/entry_order.js addOrder 创建后状态从 CREATING→CREATED,validTransitions 增加 CREATED 节点", + "Service 层:app/service/systems/storage/entry.js createEntry 默认状态 PENDING→CREATED", + "Service 层:app/service/systems/storage/inventory.js 快捷入库默认 CREATED", + "文档同步:storage.entry.list where.order_status 枚举补充 CREATED;storage.entry.get description 补充 order_status 枚举含 CREATED;storage.entry.cancel 补充 CREATED 可作废说明;storage.entry.completeEntry/bindReceivingDetails 补充可操作状态含 CREATED" + ], + "type": "updated", + "module": "storage.entry" + }, + { + "version": "2026.06.23-system-02", + "date": "2026-06-23", + "summary": "入库单 CREATED 状态限制:CREATED 状态不允许绑定货物和完成入库,仅 PENDING/CONFIRMED/PARTIAL_RECEIVED 状态可操作", + "methods": [ + "storage.entry.cancel", + "storage.entry.completeEntry", + "storage.entry.bindReceivingDetails", + "storage.entry.unbindReceivingDetails" + ], + "notes": [ + "completeEntry / bindReceivingDetails / unbindReceivingDetails / commitEntryWithBindings 的可操作状态从原来的白名单(包含 CREATED)改为 PENDING / CONFIRMED / PARTIAL_RECEIVED,排除 CREATED。", + "CREATED 状态仅允许确认入库(→PENDING)或作废(→CANCELLED)。", + "storage.entry.cancel 补充明确 COMPLETED 状态不可作废,CREATED 可作废。", + "同步更新对应 method 的 description、errors 描述。" + ], + "type": "updated", + "module": "storage.entry" + }, + { + "version": "2026.06.23-system-03", + "date": "2026-06-23", + "summary": "storage.entry.cancel:CONFIRMED(已确认)状态不再允许作废,仅 CREATED 和 PENDING 可作废", + "methods": [ + "storage.entry.cancel" + ], + "notes": [ + "canCancel() 白名单移除 CONFIRMED,仅保留 CREATED 和 PENDING", + "validTransitions 中 CONFIRMED 不再可转为 CANCELLED", + "cancel() 方法新增 CONFIRMED 状态拦截,返回 400:已确认入库单不允许作废,请先完成收货", + "PARTIAL_RECEIVED 仍可作废,COMPLETED 不允许作废(行为不变)", + "更新 description 明确各状态可作废规则,errors 中补充 CONFIRMED 不可作废的说明" + ], + "type": "updated", + "module": "storage.entry" + }, + { + "version": "2026.06.23-system-04", + "date": "2026-06-23", + "summary": "入库单状态从 7 个简化为 5 个:移除 CONFIRMED 和 PARTIAL_RECEIVED,最终状态为 CREATING/CREATED/PENDING/COMPLETED/CANCELLED;同步更新 storage.entry 所有 method 的状态枚举和错误信息描述", + "methods": [ + "storage.entry.list", + "storage.entry.get", + "storage.entry.cancel", + "storage.entry.completeEntry", + "storage.entry.bindReceivingDetails", + "storage.entry.unbindReceivingDetails" + ], + "notes": [ + "wms_entry_order.order_status ENUM 从 CREATING/CREATED/PENDING/CONFIRMED/PARTIAL_RECEIVED/COMPLETED/CANCELLED 简化为 CREATING/CREATED/PENDING/COMPLETED/CANCELLED", + "storage.entry.list: where.order_status 描述和 where 参数描述中的状态枚举同步更新", + "storage.entry.get: entryOrder.order_status 描述同步更新", + "storage.entry.cancel: 移除 PARTIAL_RECEIVED 可作废和 CONFIRMED 不可作废的描述,仅保留 CREATED 和 PENDING 可作废,COMPLETED 不可作废", + "storage.entry.completeEntry: 可完成状态从 PENDING/CONFIRMED/PARTIAL_RECEIVED 改为仅 PENDING", + "storage.entry.bindReceivingDetails: 可操作状态从 PENDING/CONFIRMED/PARTIAL_RECEIVED 改为仅 PENDING", + "storage.entry.unbindReceivingDetails: 可操作状态从 PENDING/CONFIRMED/PARTIAL_RECEIVED 改为仅 PENDING", + "cancel() 取消 CONFIRMED 状态拦截(状态已不存在),COMPLETED 拦截保持不变" + ], + "type": "updated" + }, + { + "version": "2026.06.23-system-05", + "date": "2026-06-23", + "summary": "入库单状态语义调整:CREATED=已创建待审核,PENDING=已审核;同步更新 storage.entry 所有 method 的 description 中状态说明", + "methods": [ + "storage.entry.list", + "storage.entry.get", + "storage.entry.cancel", + "storage.entry.completeEntry", + "storage.entry.bindReceivingDetails", + "storage.entry.unbindReceivingDetails" + ], + "notes": [ + "CREATED 含义从\"已创建\"改为\"已创建待审核\"(需审核后才能绑定和完成入库)", + "PENDING 含义从\"待收货/收货中\"改为\"已审核\"(审核通过,可绑定和完成入库)", + "CREATED→PENDING 步骤语义:绑定审核", + "addOrder() 新增可选参数 autoReview(boolean,默认 false),false 创建后状态 CREATED(需审核),true 创建后状态 PENDING(自动审核通过)", + "快捷入库 quickPutaway 内部流程改为调用 addOrder({autoReview:true}) → bindReceivingDetails → commitEntryWithBindings,不再直接写库存,对外返回格式不变", + "storage.entry.list / storage.entry.get description 中补充 CREATED/PENDING 语义说明", + "storage.entry.cancel description 中补充可作废状态说明", + "storage.entry.completeEntry description 中补充可完成状态说明", + "storage.entry.bindReceivingDetails / storage.entry.unbindReceivingDetails description 中补充可绑定/解绑状态说明" + ], + "type": "updated" + }, + { + "version": "2026.06.23-system-06", + "date": "2026-06-23", + "summary": "storage.inventory.quickPutaway description 更新:补充内部已改为走 addOrder→bind→commit 链路,不再直接写库存", + "methods": [ + "storage.inventory.quickPutaway" + ], + "notes": [ + "快捷入库 quickPutaway 内部流程改为调用 addOrder({autoReview:true}) → bindReceivingDetails → commitEntryWithBindings,不再直接写库存,外部返回格式不变", + "description 中补充内部调用链路说明" + ], + "type": "updated" + }, + { + "version": "2026.06.23-system-07", + "date": "2026-06-23", + "summary": "storage.entry 大范围清理:删除 bindReceivingDetails/unbindReceivingDetails(明细级绑定已弃用),更新 completeEntry 为纯状态变更(不再做库存写入/异步匹配)", + "methods": [ + "storage.entry.bindReceivingDetails", + "storage.entry.unbindReceivingDetails", + "storage.entry.completeEntry" + ], + "notes": [ + "storage.entry.bindReceivingDetails:已从代码中删除,明细级绑定收货单功能下线。库存写入统一由 storage.inventory.matchPutaway 完成。", + "storage.entry.unbindReceivingDetails:已从代码中删除,明细级解绑功能下线。", + "storage.entry.completeEntry:改为纯状态变更(PENDING → COMPLETED),不再做库存写入和异步匹配回调。库存写入统一由 storage.inventory.matchPutaway 完成。" + ], + "type": "updated" + }, + { + "version": "2026.06.23-system-08", + "date": "2026-06-23", + "summary": "storage.inventory 清理:删除 quickPutaway(快捷入库已下线,统一由 matchPutaway 完成匹配入库)", + "methods": [ + "storage.inventory.quickPutaway" + ], + "notes": [ + "storage.inventory.quickPutaway:已从代码中删除,快捷入库功能下线。请使用 storage.inventory.matchPutaway 替代。" + ], + "type": "removed" + }, + { + "version": "2026.06.23-system-09", + "date": "2026-06-23", + "summary": "入库流程弃用清理:bindReceivingDetails/unbindReceivingDetails 标记为已删除并补充弃用原因,completeEntry 明确不涉及库存写入", + "methods": [ + "storage.entry.bindReceivingDetails", + "storage.entry.unbindReceivingDetails", + "storage.entry.completeEntry" + ], + "notes": [ + "storage.entry.bindReceivingDetails 与 storage.entry.unbindReceivingDetails 已从代码中移除,入库单与收货单关系改为 wms_entry_order_receiving 主表级关联,不再需要逐明细绑定/解绑。", + "wms_entry_receiving_binding 表不再写入新数据。", + "storage.entry.completeEntry 仅做状态变更(PENDING→COMPLETED),库存写入统一由 storage.inventory.matchPutaway 完成。", + "commitEntryWithBindings(内部方法)不再使用,库存写入统一走 matchPutaway 链路。" + ], + "type": "updated" + }, + { + "version": "2026.06.23-system-10", + "date": "2026-06-23", + "summary": "quickPutaway 弃用说明完善:明确替代方案为 matchPutaway;matchPutaway 标明为目前唯一库存写入入库链路", + "methods": [ + "storage.inventory.quickPutaway", + "storage.inventory.matchPutaway" + ], + "notes": [ + "storage.inventory.quickPutaway 已从代码中移除,替代方案为 storage.inventory.matchPutaway(支持多收货单+多入库单批量匹配入库)。", + "storage.inventory.matchPutaway 是目前唯一的库存写入入库链路,入库单状态变更由 storage.entry.completeEntry 单独处理。", + "本次为文档补充说明,不涉及代码变更。" + ], + "type": "updated" + }, + { + "version": "2026.06.23-system-11", + "date": "2026-06-23", + "summary": "删除 storage.receiving.getAvailableInboundQuantity:该方法依赖已弃用的 wms_entry_receiving_binding 明细绑定表,已从代码中移除", + "methods": [ + "storage.receiving.getAvailableInboundQuantity" + ], + "notes": [ + "该方法原用于按 stock_id 查询已审核收货单中各明细的可入库数量(actual_quantity - stored_quantity - pending_allocated_quantity)。", + "由于 wms_entry_receiving_binding 明细绑定表已弃用,入库单与收货单的关联改为通过 wms_entry_order_receiving 主表级关联,该查询方法不再适用。", + "替代方案:使用 storage.entry.get 查询入库单详情,通过顶层 receivingBindings 获取关联的收货单信息。" + ], + "type": "removed" + }, + { + "version": "2026.06.23-system-12", + "date": "2026-06-23", + "summary": "storage.entry.get 响应结构变更:不再返回 items[].bindings(明细级绑定),改为返回顶层 receivingBindings(主表级关联收货单信息)", + "methods": [ + "storage.entry.get" + ], + "notes": [ + "移除 items[].bindings(明细级绑定,原基于 wms_entry_receiving_binding 表),该绑定表已弃用。", + "新增顶层 receivingBindings(wms_entry_order_receiving 主表级关联),每项含 id/receiving_id/receiving(含 id/receiving_number/status/storage_status/created_at)。", + "items 中保留 external_item_code/external_item_id/warehouse_item_code/warehouse_item_name/warehouse_item_spec 等扁平化字段。", + "响应结构变更与 storage.directInbound.getItems 的返回结构对齐,后者同样使用顶层 receivingBindings。" + ], + "type": "modified" + }, + { + "version": "2026.06.23-system-13", + "date": "2026-06-23", + "summary": "新增 storage.entry.* 下 4 个 DirectInbound 方法:getDirectInboundItems、addItem、commit、removeItem,原 storage.directInbound.* 方法保留向后兼容并标记 deprecated", + "methods": [ + "storage.entry.getDirectInboundItems", + "storage.entry.addItem", + "storage.entry.commit", + "storage.entry.removeItem" + ], + "notes": [ + "storage.entry.getDirectInboundItems:获取入库单的导入/PDA 入库信息,参数与响应格式同原 storage.directInbound.getItems", + "storage.entry.addItem:按商品增量添加导入/PDA 入库记录(支持单条和批量),参数与响应格式同原 storage.directInbound.addItem", + "storage.entry.commit:提交确认完成导入/PDA 入库,按实收数量写入库存并异步回传奇门/API,参数与响应格式同原 storage.directInbound.commit", + "storage.entry.removeItem:移除一条导入/PDA 入库记录,参数与响应格式同原 storage.directInbound.removeItem", + "底层 inbound_direct_log.js 实现不变,仅入口从 storage.directInbound 模块迁入 storage.entry 模块" + ], + "type": "added" + }, + { + "version": "2026.06.23-system-14", + "date": "2026-06-23", + "summary": "storage.directInbound.* 下 4 个方法标记 deprecated,指向 storage.entry.* 下对应新方法", + "methods": [ + "storage.directInbound.getItems", + "storage.directInbound.addItem", + "storage.directInbound.commit", + "storage.directInbound.removeItem" + ], + "notes": [ + "storage.directInbound.getItems → 替代方法 storage.entry.getDirectInboundItems", + "storage.directInbound.addItem → 替代方法 storage.entry.addItem", + "storage.directInbound.commit → 替代方法 storage.entry.commit", + "storage.directInbound.removeItem → 替代方法 storage.entry.removeItem", + "旧方法保留向后兼容,参数与响应格式不变,仅入口模块变更" + ], + "type": "deprecated" + }, + { + "version": "2026.06.23-system-15", + "date": "2026-06-23", + "summary": "storage.inventory.matchPutaway 标记 deprecated,替代方案为 storage.entry.commit", + "methods": [ + "storage.inventory.matchPutaway" + ], + "notes": [ + "storage.inventory.matchPutaway 已弃用,请迁移至 storage.entry.commit", + "commit 提供导入/PDA 入库完成确认功能,按实收数量写入库存并异步回传" + ], + "type": "deprecated" + }, + { + "version": "2026.06.23-system-16", + "date": "2026-06-23", + "summary": "清理已弃用 method 条目:从 system.json 删除 storage.entry.bindReceivingDetails、storage.entry.unbindReceivingDetails、storage.inventory.matchPutaway 三个已从代码中移除的 method 文档条目", + "methods": [ + "storage.entry.bindReceivingDetails", + "storage.entry.unbindReceivingDetails", + "storage.inventory.matchPutaway" + ], + "notes": [ + "storage.entry.bindReceivingDetails:已从代码中删除,明细级绑定收货单功能下线。入库单与收货单关系改为 wms_entry_order_receiving 主表级关联。", + "storage.entry.unbindReceivingDetails:已从代码中删除,明细级解绑功能下线。", + "storage.inventory.matchPutaway:已从代码中删除,匹配入库功能下线。替代方案为 storage.entry.commit。", + "storage.inventory.quickPutaway:之前已标记 [已删除],本次确认条目保留(与 matchPutaway 同一 group,保留作为历史参考)。", + "storage.entry.create / addDetail / deleteDetail / detailChange:systems 层方法已删除,但从未在 system.json 中暴露为 API method,无需文档变更。" + ], + "type": "removed" + }, + { + "version": "2026.06.23-system-17", + "date": "2026-06-23", + "summary": "storage.entry.get 响应新增仓库库存、条码、入库进度字段", + "methods": [ + "storage.entry.get" + ], + "notes": [ + "items 每项新增 warehouse_quantity(仓库库存总量)、warehouse_locked_quantity(锁定数量)、warehouse_is_batch_mgmt(是否批次管理)、warehouse_is_shelf_life_mgmt(是否效期管理)、warehouse_image_url(商品图片URL)、warehouse_is_images(是否有图片)", + "items 每项新增 barcodes(条码列表,每项含 id/barcode/sku_property)", + "items 每项新增 direct_inbound_quantity(导入/PDA已入库数量)、remaining_quantity(剩余可入库数量)", + "同步更新 response 字段定义,将原有概要描述展开为逐字段说明", + "仅文档同步,不改业务代码" + ], + "type": "updated", + "module": "storage.entry" + }, + { + "version": "2026.06.24-system-01", + "date": "2026-06-24", + "summary": "新增批量绑定入库单明细与收货单明细接口 storage.entry.bindReceivingDetails,支持明细级数量分配与部分成功", + "methods": [ + "storage.entry.bindReceivingDetails" + ], + "notes": [ + "新增 storage.entry.bindReceivingDetails:批量绑定入库单明细与收货单明细,支持明细级数量分配与部分成功", + "storage.entry.get 追加 available_receiving_details 字段加载可匹配的收货单明细" + ], + "type": "addition" + }, + { + "version": "2026.06.24-system-02", + "date": "2026-06-24", + "summary": "storage.entry.bindReceivingDetails:response.failed 字段从简单 reason 描述升级为结构化错误返回(含 error_code、message、detail);同步更新 400 错误说明", + "methods": [ + "storage.entry.bindReceivingDetails" + ], + "notes": [ + "response.failed 新增 items 定义,每项含 entry_item_id、receiving_detail_id、allocated_quantity、error_code、message、detail", + "error_code 枚举:ENTRY_ITEM_NOT_FOUND、STOCK_NOT_FOUND、RECEIVING_DETAIL_MISMATCH、RECEIVING_DETAIL_NOT_FOUND、INSUFFICIENT_AVAILABLE_QUANTITY、ENTRY_ORDER_STATUS_INVALID", + "400 错误说明更新:入库单状态不允许绑定时,所有 bindings 均返回 failed 且 error_code 为 ENTRY_ORDER_STATUS_INVALID" + ], + "type": "updated" + }, + { + "version": "2026.06.24-system-03", + "date": "2026-06-24", + "summary": "新增 storage.entry.quickInbound 快捷直入/虚拟入库接口", + "methods": [ + "storage.entry.quickInbound" + ], + "notes": [ + "新增 quickInbound 方法:入库单所有商品按明细数量一键直入虚拟库位(space_id=2),跳过收货/质检流程", + "支持状态:CREATED、PENDING 状态的入库单可执行", + "拒绝状态:CANCELLED(已作废)、COMPLETED(已完成)", + "事务内操作:更新入库明细收货量、累加库存总量、写入库存流水、写入虚拟库位库存、变更入库单状态为 COMPLETED", + "事务外异步回传奇门/API" + ], + "type": "addition" + }, + { + "version": "2026.06.24-system-04", + "date": "2026-06-24", + "summary": "收窄 storage.entry.quickInbound 状态约束:仅允许 CREATED 状态执行快捷直入", + "methods": [ + "storage.entry.quickInbound" + ], + "notes": [ + "收窄状态约束:仅允许 CREATED 状态执行快捷直入,PENDING 状态不再允许" + ], + "type": "updated" + }, + { + "version": "2026.06.24-system-05", + "date": "2026-06-24", + "summary": "修正 storage.entry.quickInbound errors[4] message 以匹配代码实现:改为动态状态描述", + "methods": [ + "storage.entry.quickInbound" + ], + "notes": [ + "errors[4].message 从「入库单状态不允许快捷直入(仅支持CREATED状态)」改为「入库单状态不允许快捷直入,当前状态:非CREATED(如PENDING等)」,反映代码中 `${entryOrder.order_status}` 动态模板特性" + ], + "type": "updated" + }, + { + "version": "2026.06.24-system-06", + "date": "2026-06-24", + "summary": "新增入库单与收货单商品对照预览接口", + "methods": [ + "storage.entry.receivingCompare" + ], + "notes": [ + "新增 storage.entry.receivingCompare 方法:给定入库单ID和收货单ID,返回入库商品与收货商品的逐行对照视图。", + "comparison 列表中每项含 match_status(matched/entry_only),以及入库侧和收货侧的商品与数量信息。", + "receiving_only 列表包含仅存在于收货单中的商品明细。", + "summary 提供 total_entry_items、matched_items、entry_only_items、receiving_only_items 汇总统计。", + "纯只读接口,不产生任何数据写入或状态变更。" + ], + "type": "addition" + }, + { + "version": "2026.06.24-system-07", + "date": "2026-06-24", + "summary": "setting.warehouse 模块新增 7 个发件人信息字段到 subject_config", + "methods": [ + "setting.warehouse.getSettings", + "setting.warehouse.saveSettings" + ], + "notes": [ + "在 getSettings 的 response 中新增 subject_config.sender_name(发件人姓名)、sender_tel(发件人电话)、province_name(省份)、city_name(城市)、district_name(区/县)、town_name(镇/街道)、address(详细地址)共 7 个字段,均为可选字符串,默认空。", + "在 saveSettings 的 params 中新增对应的 7 个入参字段,source 为 body.subject_config,均为可选字符串,默认空,并标注 maxLength。", + "字段 key 与 store_warehouse.policy_config 中发件人字段命名完全一致,统一仓库级发件人默认值配置。", + "getFieldMeta 接口无需修改文档——其返回的字段元信息由 WAREHOUSE_SETTING_FIELDS 定义在运行时自动生成,新增字段会随代码自动纳入返回列表。" + ], + "type": "updated", + "module": "setting.warehouse" + }, + { + "version": "2026.06.25-system-01", + "date": "2026-06-25", + "summary": "新增 storage.entry.bindReceiving 接口:将收货单绑定到入库单(主表级关联,不做明细数量分配)", + "methods": [ + "storage.entry.bindReceiving" + ], + "notes": [ + "新增入库单与收货单的主表绑定接口,与已有的 storage.entry.bindReceivingDetails(明细级绑定)区分:bindReceiving 仅建立 wms_entry_order_receiving 主表关联,不做明细数量分配。", + "入库单需为 CREATED 或 PENDING 状态;收货单需存在、同仓库且未取消。", + "支持部分成功模式:逐条校验收货单,校验通过的建立绑定,不通过的返回 error_code 和 message。", + "响应包含 success(成功列表)、failed(失败列表)、success_count、failed_count。" + ], + "type": "addition" + }, + { + "version": "2026.06.25-system-02", + "date": "2026-06-25", + "summary": "storage.entry.bindReceiving:新增 OWNER_MISMATCH 错误码,用于收货单与入库单货主不一致校验", + "methods": [ + "storage.entry.bindReceiving" + ], + "notes": [ + "在 storage.entry.bindReceiving 的 errors 数组中新增 OWNER_MISMATCH(收货单与入库单货主不一致)错误码。", + "同步更新 response.failed.error_code 的枚举描述,补充 OWNER_MISMATCH。" + ], + "type": "updated", + "module": "storage.entry" + }, + { + "version": "2026.06.25-system-03", + "date": "2026-06-25", + "summary": "storage.entry.bindReceiving:新增收货单未审核错误码 RECEIVING_NOT_REVIEWED", + "methods": [ + "storage.entry.bindReceiving" + ], + "notes": [ + "在 errors 数组中新增错误码 RECEIVING_NOT_REVIEWED(收货单未审核),用于标识绑定前收货单尚未完成审核的场景。", + "同步更新 response.failed.items.properties.error_code.description,在可能值列表中补充 RECEIVING_NOT_REVIEWED。" + ], + "type": "updated" + }, + { + "version": "2026.06.25-system-04", + "date": "2026-06-25", + "summary": "storage.entry.list 响应新增 receivingBindings 和 hasReceiving 字段,where 新增 hasReceiving 虚拟筛选条件", + "methods": [ + "storage.entry.list" + ], + "notes": [ + "响应 list 数组每项新增 receivingBindings(收货单绑定列表,主表级关联)和 hasReceiving(是否存在收货单绑定,boolean)字段。", + "入参 where 新增 hasReceiving 虚拟筛选字段,传 true/false 筛选已绑定/未绑定收货单的入库单,内部通过 wms_entry_order_receiving 表查询实现。", + "同步更新 description 以说明 hasReceiving 虚拟筛选的使用方式。" + ], + "type": "updated" + }, + { + "version": "2026.06.26-system-01", + "date": "2026-06-26", + "summary": "storage.entry.receivingCompare 支持多收货单对照预览", + "methods": [ + "storage.entry.receivingCompare" + ], + "notes": [ + "支持多个收货单ID对照预览(新增 receiving_ids 数组入参,优先于 receiving_id 使用)", + "入参 receiving_id 从 required 改为 optional,与 receiving_ids 二选一", + "出参结构调整为 comparisons[] 数组(多收货单),新增 errors[] 和 total_summary", + "向后兼容原 receiving_id 单值传参(底层自动转为单元素数组)", + "新增 400 错误码:receiving_ids 或 receiving_id 必填", + "移除 404 错误码:收货单不存在(已改为在 comparisons[]/errors[] 中以 status=error 形式返回)" + ], + "type": "enhancement" + }, + { + "version": "2026.06.26-system-02", + "date": "2026-06-26", + "summary": "storage.receiving.getReceivingList 新增 filterDepleted 可选参数;storage.entry.receivingCompare 返回值 receiving_only 字段新增 receiving_allocated 和 receiving_available 说明", + "methods": [ + "storage.receiving.getReceivingList", + "storage.entry.receivingCompare" + ], + "notes": [ + "storage.receiving.getReceivingList:params 新增 filterDepleted(boolean, 默认 false),用于过滤掉无可再用量的收货单(所有明细已被其他入库单 committed 绑定占满)。", + "storage.entry.receivingCompare:response 中 receiving_only 字段的 description 补充 receiving_allocated(已分配数量)和 receiving_available(可再用量)两个子字段说明。" + ], + "type": "updated" + }, + { + "version": "2026.06.26-system-03", + "date": "2026-06-26", + "summary": "storage.receiving.getReceivingList:新增可选参数 entry_order_id,按入库单商品交集过滤收货单列表", + "methods": [ + "storage.receiving.getReceivingList" + ], + "notes": [ + "新增可选参数 entry_order_id(number),传入入库单 ID 后只返回至少有一条明细的 system_product_id 在入库单明细中存在的收货单。", + "与现有 filterDepleted 参数可组合使用,二者取交集。", + "不传则不过滤,保持原有行为不变。" + ], + "type": "updated" + }, + { + "version": "2026.06.27-system-01", + "date": "2026-06-27", + "summary": "新增 storage.entry.reviewEntry 接口:审核入库单(CREATED→PENDING),需绑定收货单", + "methods": [ + "storage.entry.reviewEntry" + ], + "notes": [ + "新增入库单审核接口,支持 CREATED→PENDING 状态流转。", + "审核前置条件:入库单必须已绑定收货单(EntryOrderReceiving 存在关联记录)。", + "审核通过后写入操作日志(ENTRY_ORDER_REVIEW)。" + ], + "type": "added" + }, + { + "version": "2026.06.29-system-01", + "date": "2026-06-29", + "summary": "storage.inventory.quickPutaway 重新实现:收货单快捷转入库单", + "methods": [ + "storage.inventory.quickPutaway" + ], + "notes": [ + "此前已从代码中删除(2026.06.23-system-08),现由 wms-dev-agent 重新实现。", + "核心流程:参数校验 → 加载收货单及明细 → 检查货主配置 policy_config.allow_receiving_quick_putaway → 按 stock_id(system_product_id)分组合并数量 → 创建入库单 SCRK(自动审批到 PENDING)→ 写入 wms_entry_order_receiving 主表级绑定 → 更新收货单 storage_status 为 partial → 更新收货单明细 storage_status/stored_quantity → 提交事务。", + "前置条件:收货单状态为 completed 且 is_review=true(已审核),货主仓库签约配置 allow_receiving_quick_putaway=1。", + "与旧实现的区别:不涉及 wms_entry_receiving_binding 明细级绑定,使用 wms_entry_order_receiving 主表级关联;直接创建入库单并写入绑定,不再走 matchPutaway 匹配链路。", + "返回:entry_order_id、entry_order_code(SCRK 格式)、order_status(PENDING)、receiving_id、total_lines、total_quantity。" + ], + "type": "addition" + }, + { + "version": "2026.06.29-system-02", + "date": "2026-06-29", + "summary": "storage.entry.list:quickWhere 搜索范围扩展,新增收货单 ID(receiving_id)支持 PDA 扫描托盘唛头搜索绑定的入库单", + "methods": [ + "storage.entry.list" + ], + "notes": [ + "quickWhere 搜索字段新增 receiving_id(收货单 ID / 托盘唛头),通过 wms_entry_order_receiving 绑定表关联搜索。", + "同步更新 description 和 where 参数的 description,明确 quickWhere 完整搜索字段列表:entry_order_code、purchase_order_code、supplier_name、store_name、warehouse_name、receiving_id。" + ], + "type": "updated", + "module": "storage" + }, + { + "version": "2026.06.29-system-03", + "date": "2026-06-29", + "summary": "新增 storage.receiving.scanDetail 接口:PDA 上架扫码定位收货明细", + "methods": [ + "storage.receiving.scanDetail" + ], + "notes": [ + "新增 storage.receiving.scanDetail(PDA专用):通过 entry_order_id + barcode 扫码快速定位收货明细。", + "搜索逻辑:纯数字 barcode 优先按明细 ID 精确匹配(托盘唛头),未命中则模糊匹配商品条码;非纯数字仅模糊匹配商品条码。", + "入参:entry_order_id(必填 number)、barcode(必填 string)。", + "出参:detail_id、receiving_id、barcode、product_name、actual_quantity、receiving_status。", + "错误码:入库单不存在或无权访问、该入库单尚未关联收货单、未找到匹配的收货明细。" + ], + "type": "added" + }, + { + "version": "2026.06.29-system-04", + "date": "2026-06-29", + "summary": "storage.receiving.scanDetail 响应结构从单条改为列表:返回 { list, total } 支持同一条码匹配多条明细", + "methods": [ + "storage.receiving.scanDetail" + ], + "notes": [ + "响应结构变更:原返回 data.detail_id/data.receiving_id 等单条字段,现改为顶层 list 数组 + total 计数。", + "同一条码可能匹配到多条收货明细(不同收货单的同一商品),以列表形式返回所有匹配结果。", + "list 中每条明细包含 detail_id/receiving_id/barcode/product_name/actual_quantity/receiving_status。", + "补充错误码:用户未绑定仓库、入库单ID/条码为空、未找到可用的收货明细、500服务器错误。", + "PDA专用接口,description 更新说明匹配逻辑。" + ], + "type": "updated", + "module": "storage.receiving" + }, + { + "version": "2026.06.30-system-01", + "date": "2026-06-30", + "summary": "新增 storage.entry.containerList:PDA 上架时拉取入库单绑定收货单中指定商品的可用容器列表", + "methods": [ + "storage.entry.containerList" + ], + "notes": [ + "新增接口 storage.entry.containerList,用于 PDA 上架场景拉取入库单已绑定收货单中指定 stock_id 的可用收货明细(容器)列表。", + "入参:entry_order_id(入库单ID,必填)、stock_id(商品 stock_id,必填)。", + "出参:data.list 返回可用明细列表,每项含 detail_id、receiving_id、barcode、product_name、actual_quantity、receiving_status;data.total 为总数。", + "已绑定占用的收货明细(wms_entry_receiving_binding 中已有记录且未软删除)会被排除。", + "PDA 专用接口,无需额外鉴权(isNeedAuth=false)。" + ], + "type": "added" + }, + { + "version": "2026.06.30-system-02", + "date": "2026-06-30", + "summary": "storage.entry.addItem 入参变更:entry_order_code → entry_order_id(number);quantity 改为可选(传入 receiving_detail_id 时自动计算);新增 receiving_detail_id/allocated_quantity 参数支持 PDA 上架收货明细绑定模式;space_id 绑定模式下必填", + "methods": [ + "storage.entry.addItem" + ], + "notes": [ + "入参 entry_order_code(string) → entry_order_id(number),与底层 inboundDirectLog.addItem 实现对齐", + "quantity 改为可选:传入 receiving_detail_id 时自动从收货明细计算可用数量(actual_quantity - 已绑定数量)", + "新增 receiving_detail_id 参数:PDA 上架绑定收货明细时传入,触发预占绑定(wms_entry_receiving_binding status=pending)", + "新增 allocated_quantity 参数:预分配数量,默认等于 quantity", + "space_id 在绑定模式下必填;非绑定模式可选(commit 时兜底为 1)", + "PENDING 状态入库单必须传 receiving_detail_id 且已绑定收货单方可操作", + "CREATED + 已绑定收货单的入库单需先审核(reviewEntry)后才能上架", + "批量模式 items 数组同步支持 receiving_detail_id/allocated_quantity 字段", + "补充完整错误码列表:超量、可用数量不足、状态校验等" + ], + "type": "updated" + }, + { + "version": "2026.06.30-system-03", + "date": "2026-06-30", + "summary": "storage.entry.commit 入参变更:entry_order_code → entry_order_id(number),与底层 inboundDirectLog.commit 实现对齐", + "methods": [ + "storage.entry.commit" + ], + "notes": [ + "入参 entry_order_code(string) → entry_order_id(number),与底层 inboundDirectLog.commit(entryOrderId) 实现对齐", + "补充 description 说明先同步后写库两段式流程:① 奇门/API 回传 → ② onSuccess 内事务写库存", + "补充 commit 后 EntryReceivingBinding 状态从 pending 更新为 committed 的说明" + ], + "type": "updated" + }, + { + "version": "2026.06.30-system-04", + "date": "2026-06-30", + "summary": "storage.directInbound.commit 入参变更:entry_order_code → entry_order_id(number),与底层 inboundDirectLog.commit 实现对齐", + "methods": [ + "storage.directInbound.commit" + ], + "notes": [ + "入参 entry_order_code(string) → entry_order_id(number),与底层 inboundDirectLog.commit(entryOrderId) 实现对齐", + "该方法已标记 deprecated,推荐使用 storage.entry.commit" + ], + "type": "updated" + }, + { + "version": "2026.06.30-system-05", + "date": "2026-06-30", + "summary": "storage.entry.getDirectInboundItems 响应结构重构:entryOrder 精简字段,items[].count→planned、direct_inbound_quantity→completed,items[].bindings 新增,移除 direct_logs/summary 等冗余字段", + "methods": [ + "storage.entry.getDirectInboundItems" + ], + "notes": [ + "entryOrder 精简为 id / entry_order_code / order_status / store_remask 四个字段", + "items[].count → planned(计划数量),items[].direct_inbound_quantity → completed(已完成数量)", + "items[].bindings 新增,结构为 { detail_id, binding_id, allocated_quantity, space_id, space_name }", + "items[].stock 新增,返回 getStockDetails 缓存的商品详情(item_code、item_name、barcodes 等)", + "移除 direct_logs(现有响应中已不存在该顶层字段)", + "移除 summary(现有响应中已不存在该字段)", + "移除 items[].received_quantity、items[].remaining_quantity、items[].pending_binding_total 等旧字段", + "新增 receivingBindings 字段说明:入库单层级收货单绑定关系" + ], + "type": "updated" + }, + { + "version": "2026.06.30-system-06", + "date": "2026-06-30", + "summary": "storage.directInbound.getItems 响应结构重构:entryOrder 精简字段,items[].count→planned、direct_inbound_quantity→completed,items[].bindings 新增,移除 direct_logs/summary 等冗余字段", + "methods": [ + "storage.directInbound.getItems" + ], + "notes": [ + "响应结构与 storage.entry.getDirectInboundItems 对齐(两者共用同一个底层实现 inboundDirectLog.getItems)", + "entryOrder 精简为 id / entry_order_code / order_status / store_remask", + "items[].count → planned,items[].direct_inbound_quantity → completed", + "items[].bindings 新增 { detail_id, binding_id, allocated_quantity, space_id, space_name }", + "items[].stock 新增", + "移除 direct_logs、summary、items[].received_quantity、items[].remaining_quantity 等旧字段", + "新增 receivingBindings 字段" + ], + "type": "updated" + }, + { + "version": "2026.06.30-system-07", + "date": "2026-06-30", + "summary": "storage.entry.containerList 响应结构补充 stock 字段:返回商品详情(item_code、item_name、barcodes 等)", + "methods": [ + "storage.entry.containerList" + ], + "notes": [ + "响应 list[].stock 字段补充为必返回:通过 getStockDetails 批量获取商品详情缓存", + "stock 对象包含 item_code、item_name、sku_property、barcodes 等字段" + ], + "type": "updated" + }, + { + "version": "2026.06.30-system-08", + "date": "2026-06-30", + "summary": "storage.receiving.scanDetail 响应结构补充 stock 字段:返回商品详情(item_code、item_name、barcodes 等)", + "methods": [ + "storage.receiving.scanDetail" + ], + "notes": [ + "响应 list[].stock 字段补充为必返回:通过 getStockDetails 批量获取商品详情缓存", + "stock 对象包含 item_code、item_name、sku_property、barcodes 等字段", + "完善 error 列表:补充 未找到可用的收货明细、未找到匹配的收货明细、入库单ID不能为空、扫描条码不能为空 等错误" + ], + "type": "updated" + }, + { + "version": "2026.06.30-system-09", + "date": "2026-06-30", + "summary": "订单列表 list 响应新增 store_remark(货主备注)字段", + "methods": [ + "order.list", + "order.reviewOrder.list", + "order.pendingOrder.list", + "order.expectionOrder.list", + "order.entrustOrder.list", + "order.deliveryOrder.list", + "order.deliveryExpectionOrder.list", + "order.archiveOrder.list" + ], + "notes": [ + "数据库字段 store_remask,返回给前端的字段名为 store_remark。", + "服务层从 wms_store_warehouse.store_remask 按 store_id+warehouse_id 聚合批量填充。", + "货主备注值可能为空字符串(当货主未设置备注时)。", + "该字段对订单列表的所有 method 均适用(current/dispatch/outsourced/history 模型均返回)。" + ], + "type": "updated" + }, + { + "version": "2026.07.02-system-02", + "date": "2026-07-02", + "summary": "新增 quick.waybill.toOrder 接口:根据运单号快速查询订单ID", + "methods": [ + "quick.waybill.toOrder" + ], + "notes": [ + "新增 quick 模块组(快捷查询)", + "查询 wms_order_express 表中 status=1 的有效记录", + "无需登录和鉴权(免登录/免鉴权)" + ], + "type": "added" + }, + { + "version": "2026.07.02-system-01", + "date": "2026-07-02", + "summary": "修正 quick.waybill.toOrder 的 isNeedLogin 为 true,与代码实现保持一致", + "methods": [ + "quick.waybill.toOrder" + ], + "notes": [ + "文档中 isNeedLogin 为 false,但代码 systemMethods/quick/waybill.js 中 _noNeedLogin 为空字符串,未将 toOrder 加入免登录列表,实际需要登录验证,修正文档以与代码一致。" + ], + "type": "fixed" + }, + { + "version": "2026.07.03-system-01", + "date": "2026-07-03", + "summary": "binding 表弃用文档同步:wms_entry_receiving_binding 已弃用,功能迁移到 wms_inbound_direct_log 表;bindings 描述中表引用更新为 InboundDirectLog", + "methods": [ + "storage.entry.getDirectInboundItems" + ], + "notes": [ + "bindings 数组 description 中 wms_entry_receiving_binding 引用更新为 InboundDirectLog,明确旧表已弃用", + "binding_id description 中 wms_entry_receiving_binding.id 更新为 InboundDirectLog.id", + "allocated_quantity description 中补充来源 InboundDirectLog.quantity", + "wms_inbound_direct_log 表新增字段:entry_item_id、receiving_detail_id、status(ENUM: pending/committed/released)、updated_at、deleted_at" + ], + "type": "updated" + }, + { + "version": "2026.07.03-system-02", + "date": "2026-07-03", + "summary": "binding 表弃用文档同步:wms_entry_receiving_binding 已弃用,功能迁移到 wms_inbound_direct_log 表;bindings 描述中表引用更新为 InboundDirectLog", + "methods": [ + "storage.directInbound.getItems" + ], + "notes": [ + "bindings 数组 description 中更新为来自 InboundDirectLog,明确旧表已弃用", + "binding_id description 更新为 InboundDirectLog.id", + "allocated_quantity description 中补充来源 InboundDirectLog.quantity", + "wms_inbound_direct_log 表新增字段:entry_item_id、receiving_detail_id、status(ENUM: pending/committed/released)、updated_at、deleted_at" + ], + "type": "updated" + }, + { + "version": "2026.07.03-system-03", + "date": "2026-07-03", + "summary": "binding 表弃用文档同步:commit 描述中 EntryReceivingBinding 更新为 InboundDirectLog", + "methods": [ + "storage.entry.commit" + ], + "notes": [ + "commit description 中将 pending 状态的 EntryReceivingBinding 更新为 pending 状态的 InboundDirectLog,与代码实现一致" + ], + "type": "updated" + }, + { + "version": "2026-07-03-entry-get-params-fix", + "date": "2026-07-03", + "type": "updated", + "summary": "修正 storage.entry.get 文档:id 改为必填;移除未实现的 entry_order_code 参数;修正错误码与实际返回一致;补充 available_receiving_details 响应字段;修正 remaining_quantity 计算公式及 warehouse_image_url 实际行为", + "methods": [ + "storage.entry.get" + ], + "notes": [ + "params: 移除 entry_order_code(代码中从未使用该参数),id 从 required=false 改为 required=true", + "params: id 描述从'二选一'改为'必填'", + "errors: 400 的 message 从'参数错误:id 与 entry_order_code 至少提供一个'改为'id 参数不能为空'", + "errors: 移除不存在的 404 error,入库单不存在时实际返回 code=0, message='入库单不存在或无权访问'", + "errors: 删除不存在的 500 error", + "response: 新增 entryOrder.items[].available_receiving_details 字段及其描述", + "response: remaining_quantity 描述从 'count - received_quantity - direct_inbound_quantity' 修正为 'max(0, count - received_quantity)'", + "response: warehouse_image_url 描述从 StockWarehouse.image_url 改为'当前固定返回空字符串'", + "response: warehouse_is_images 类型从 number(0/1) 改为 string(Y/N),与 StockWarehouse.is_images 实际存储一致", + "response: warehouse_quantity/warehouse_locked_quantity/warehouse_is_batch_mgmt/warehouse_is_shelf_life_mgmt 补充无匹配时为 null 的说明", + "description: 更新描述以反映实际逻辑流程" + ] + }, + { + "version": "2026.07.03-system-04", + "date": "2026-07-03", + "type": "modified", + "summary": "order.pendingOrder.updateAddress 移除 remark(备注)修改功能,现在仅支持地址字段批量修改;备注修改已独立为 order.pendingOrder.updateRemark", + "methods": [ + "order.pendingOrder.updateAddress" + ], + "notes": [ + "移除入参 remark 参数定义项。", + "移除 remark 更新逻辑及相关描述,updateAddress 现在仅处理地址字段(name/mobile/tel/zip_code/province/city/area/town/detail_address)。", + "description 更新:去掉 remark 相关描述,仅描述地址字段修改规则。", + "response updated_count 描述更新:从「取地址更新行数与备注更新行数的最大值」改为单纯描述地址更新行数。", + "errors 更新:移除 remark 相关错误说明('remark 字段不受此限制' 等),修改 '至少需要提供一个地址字段或备注进行修改' 为 '至少需要提供一个地址字段进行修改'。", + "备注修改功能已独立为 order.pendingOrder.updateRemark 方法。" + ], + "module": "order.pendingOrder" + }, + { + "version": "2026-07-16", + "date": "2026-07-16", + "summary": "新增 workbench.bindCamera 接口,支持工作台绑定/解绑摄像头", + "methods": [ + "workbench.bindCamera" + ], + "notes": [ + "通过 device_ids JSON 字段存储绑定关系", + "传空数组可解绑" + ] + }, + { + "version": "2026.07.17-stock-report-migration-01", + "date": "2026-07-17", + "type": "updated", + "summary": "storage.report 模块迁移至 stock.report:修正语义错误,库存报表属于 stock 域而非 storage 域", + "methods": [ + "stock.report.search", + "stock.report.searchStore", + "stock.report.export", + "stock.report.exportStore", + "stock.report.exportTaskProgress" + ], + "notes": [ + "将 systemMethods/storage/report.js 移动到 systemMethods/stock/report.js", + "内部引用同步更新:类名 StorageReportMethodService→StockReportMethodService,缓存键 storage_report→stock_report,日志前缀 [storage.report]→[stock.report]", + "旧文件直接删除,不保留兼容(storage.report 为语义错误,调用方需同步更新 method 名)", + "更新 systems/storage/entry.js L273 注释引用", + "文档:methods/system.json module storage.report→stock.report,5个 method 名同步更新" + ] + }, + { + "version": "2026.07.17-stock-transaction-export-01", + "date": "2026-07-17", + "type": "added", + "summary": "新增 stock.transaction 商品流水导出(仓库侧+货主侧),异步任务模式,支持与列表查询一致的条件筛选", + "methods": [ + "stock.transaction.export", + "stock.transaction.exportStore", + "stock.transaction.exportTaskProgress" + ], + "notes": [ + "systems/stock_transaction.js 新增 exportList(),复用 queryList 的查询逻辑,不分页导出 Excel(上限 50000 条)", + "systemMethods/stock/transaction.js 新增 export/exportStore/exportTaskProgress,采用异步任务模式(setImmediate + 缓存)", + "仓库侧导出自动限定 warehouse_id=ctx.user.store_id,货主侧需传 store_id", + "导出 Excel 列:序号/创建时间/流水类型/仓库ID/货主ID/商品ID/变动数量/变更前库存/变更后库存/变更前锁定/变更后锁定/批次号/单据类型/单据号/收货单ID/入库单ID/发货单ID/操作人/备注" + ] + }, + { + "version": "2026.07.29-system-01", + "date": "2026-07-29", + "type": "added", + "summary": "新增 waybill.warehouse 运单模块(仓库侧):list(列表)、detail(详情)、export(导出)3 个接口,支持运单号独立查询与管理", + "methods": [ + "waybill.warehouse.list", + "waybill.warehouse.detail", + "waybill.warehouse.export" + ], + "notes": [ + "新增 waybill.warehouse.list:仓库侧运单列表查询,支持分页与多条件筛选(运单号/主单号/订单ID/订单号/物流公司/物流接口/平台/状态/退回/拦截/星河签收/包材/称重/关键词/时间范围),默认按 create_at desc 排序。", + "新增 waybill.warehouse.detail:仓库侧运单详情查询,含关联订单信息、兄弟运单(sibling_waybills)、物流信息、状态信息、称重信息、打包信息(打包状态/打包人/打包时间)、打印记录列表。", + "新增 waybill.warehouse.export:仓库侧运单导出,复用 list 筛选逻辑,异步任务模式,支持自定义导出字段。", + "仓库隔离策略:所有接口自动注入 warehouse_id = ctx.user.store_id(全系统统一约定),不可由前端入参覆盖。", + "快照字段方案:wms_order_express 表新增 delivery_order_code、store_id_snapshot、store_name_snapshot、warehouse_name_snapshot 四个快照列,列表查询无需 JOIN 订单表或货主表,仅单表查询 + SELF JOIN(主单号)。", + "主单号/子单号规则:同一 order_id 下 business_key=1 为主单号,business_key>1 为子单号,沿用系统已有约定。", + "命名空间规划:waybill.warehouse.* 本期实现(仓库侧),后续预留 waybill.store.*(货主侧)。", + "本模块一期仅提供只读查询,不涉及运单创建/修改/删除,不修改任何现有接口。" + ], + "module": "waybill.warehouse" + }, + { + "version": "2026.07.30-system-01", + "date": "2026-07-30", + "type": "changed", + "summary": "更新 waybill.warehouse group API 文档:list 新增 waybillType/storeId 筛选、移除 pack_status 响应字段;detail 精简 package 对象;export 响应改为纯异步任务模式(仅含 task_id/status/progress/message/update_time)", + "methods": [ + "waybill.warehouse.list", + "waybill.warehouse.detail", + "waybill.warehouse.export", + "waybill.warehouse.exportTaskProgress" + ], + "notes": [ + "waybill.warehouse.list:新增 where.waybillType 筛选(\"main\"/\"1\"=主单号,\"child\"/\"2\"=子单号),新增 where.storeId 货主ID等值筛选。where.orderNo 标注暂不可用(待快照字段就绪)。response 移除 pack_status 字段(两表无关联,不再返回),list 字段数从 28 减至 27。", + "waybill.warehouse.detail:package 对象移除 pack_status/pack_quantity/pack_at/packer_name 四个字段,仅保留 package_material_id 和 package_material_name。description 同步去掉\"打包状态\"相关描述。", + "waybill.warehouse.export:响应简化为纯异步任务模式,data 仅含 task_id/status/progress/message/update_time,不含 total_count/current_count/result/error/download_url 等执行期字段(这些信息由 exportTaskProgress 接口返回)。export 的 where 参数同步新增 waybillType 和 storeId。", + "waybill.warehouse.exportTaskProgress:无变更,保持不变。" + ], + "module": "waybill.warehouse" + }, + { + "version": "2026.08.03-system-01", + "date": "2026-08-03", + "type": "added", + "summary": "新增站内信(Inbox)管理模块,支持消息列表、详情、对话链、回信、重推、统计等管理功能,仓库维度隔离,warehouseId 由服务端上下文注入", + "methods": [ + "inbox.list", + "inbox.detail", + "inbox.thread", + "inbox.reply", + "inbox.retry", + "inbox.stats" + ], + "notes": [ + "入口:POST /system,body.method=inbox.{action},路由到 app/controller/inbox.index", + "inbox.list:分页查询消息列表,支持 direction/pushStatus/targetChannel/keyword 筛选,列表不含 ext_data 和 push_response 大字段", + "inbox.detail:查单条消息详情,含完整 push_response 推送响应信息", + "inbox.thread:对话链查询,从指定消息向上查找根消息,向下收集所有回信,按时间升序返回", + "inbox.reply:系统回信,自动继承原消息 ext_data/ref_code,写入 direction=outbound + parent_id 形成对话链,异步推送到目标渠道", + "inbox.retry:手动重推失败消息(仅 push_status=3 可重推),重置为 push_status=0 并触发 setImmediate 异步推送", + "inbox.stats:按方向/推送状态汇总统计 + 最近24小时新增数量", + "安全边界:warehouse_id 由 ctx.user.store_id 注入(内部管理端),外部不可传入,保证仓库隔离", + "底层服务:app/service/inbox/index.js(查询管理)+ app/service/inbox/receiver.js(接收推送)" + ], + "module": "inbox" + }, + { + "version": "2026.08.03-system-02", + "date": "2026-08-03", + "summary": "setting.expressInterface.list 返回新增 quantity/recycled_quantity/cancel_quantity/allocated_quantity 扁平字段,数据源为 index.getShopExpressList", + "methods": [ + "setting.expressInterface.list" + ], + "notes": [ + "每条记录新增四个扁平字段:quantity(可用面单数)、recycled_quantity(已回收)、cancel_quantity(已取消)、allocated_quantity(已分配)", + "数据通过 Promise.all 并行调用 index.getShopExpressList 获取各店铺快递签约数据", + "匹配逻辑分三层:sys_express_code 匹配快递 → site_code/branch_code 匹配网点 → shipperno/customer_code_list 匹配账号", + "无店铺或无数据时四个字段均为 0" + ] + }, + { + "version": "2026.08.03-system-03", + "date": "2026-08-03", + "summary": "补全 setting.expressInterface.list response 所有返回字段文档,包含 express 子对象、quantity 四字段等", + "methods": [ + "setting.expressInterface.list" + ], + "notes": [ + "补全所有 response list children 字段:从原有的 4 个扩展为 42 个完整字段", + "新增 express 子对象文档(code/name/polyapi_code/polyapi_extra_info/pdd_code/ks_code/dyxd_code)", + "保留 quantity/recycled_quantity/cancel_quantity/allocated_quantity 四个扁平面单数量字段" + ] + } ] diff --git a/methods/system.json b/methods/system.json index 984938b..720d335 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1715,7 +1715,7 @@ "type": "object", "required": false, "source": "body", - "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会自动标准化;禁止传入 warehouse_id / warehouseId。" + "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会自动标准化;禁止传入 warehouse_id / warehouseId。支持虚拟字段:buyer_message_has(覆盖 buyer_message/seller_message/remark 三个字段,任一有值即为有留言,value=true/false),express_numbers / waybill_codes(运单号筛选)。" }, { "name": "sort", @@ -8161,7 +8161,7 @@ "type": "object", "required": false, "source": "body", - "description": "筛选白名单字段(object)。仅支持下列字段,且禁止传入 warehouse_id / warehouseId:\n- id(等值)\n- delivery_no / deliveryNo(模糊)\n- tracking_no / trackingNo(模糊)\n- items_count_min / items_count_max(范围)\n- items_total_min / items_total_max(范围)\n- sys_logistics_name(模糊)\n- store_name(模糊)\n- owner_name(等值)\n- province(模糊)\n- sys_platform_name(模糊)\n说明:若传入未列出的字段或禁止字段(如 warehouse_id)接口会返回 400。" + "description": "筛选白名单字段(object)。仅支持下列字段,且禁止传入 warehouse_id / warehouseId:\n- id(等值)\n- delivery_no / deliveryNo(模糊)\n- tracking_no / trackingNo(模糊)\n- items_count_min / items_count_max(范围)\n- items_total_min / items_total_max(范围)\n- sys_logistics_name(模糊)\n- store_name(模糊)\n- owner_name(等值)\n- province(模糊)\n- sys_platform_name(模糊)\n- buyer_message_has(虚拟字段,覆盖 buyer_message/seller_message/remark 三个字段,任一有值即为有留言,value=true/false)\n说明:若传入未列出的字段或禁止字段(如 warehouse_id)接口会返回 400。" } ], "response": [ @@ -14167,12 +14167,12 @@ ] }, { - "groupName": "快递接口管理模块", + "groupName": "快递接口管理", "module": "setting.expressInterface", "list": [ { "method": "setting.expressInterface.list", - "description": "查询当前仓库范围的快递接口列表,支持 where + pagination;返回 data:{ list, total, page, page_size }。按 weight 升序、id 降序排序,优先按权重排序。", + "description": "查询当前仓库范围的快递接口列表,支持 where + pagination;返回 data:{ list, total, page, page_size }。按 weight 升序、id 降序排序,优先按权重排序。每条记录新增 quantity/recycled_quantity/cancel_quantity/allocated_quantity 扁平字段,数据源为 index.getShopExpressList,按 sys_express_code/site_code/shipperno 三层匹配汇总。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -14189,14 +14189,14 @@ "type": "object", "required": false, "source": "body", - "description": "pagination" + "description": "分页参数,含 page、pageSize" }, { "name": "where", "type": "object", "required": false, "source": "body", - "description": "支持按 shop_id 过滤" + "description": "筛选条件,支持 id/name/express_code/platform_code/sender_name/sender_tel/viewer/client_id/share_id/site_code/product_type/shop_name/is_enabled/quickWhere" } ], "response": [ @@ -14208,26 +14208,298 @@ { "name": "id", "type": "number", - "description": "id", - "required": true + "required": true, + "description": "主键ID" }, { "name": "name", "type": "string", - "description": "name", - "required": true + "required": true, + "description": "接口名称" + }, + { + "name": "express_code", + "type": "string", + "required": true, + "description": "快递编码" + }, + { + "name": "sys_express_code", + "type": "string", + "required": true, + "description": "系统快递编码" + }, + { + "name": "warehouse_id", + "type": "number", + "required": false, + "description": "仓库ID" }, { "name": "shop_id", "type": "number", - "description": "店铺 ID,未绑定时返回 null", - "required": false + "required": false, + "description": "店铺ID,未绑定时为 null" + }, + { + "name": "platform_shop_id", + "type": "number", + "required": false, + "description": "平台店铺ID" + }, + { + "name": "template_id", + "type": "string", + "required": false, + "description": "模板ID" + }, + { + "name": "paymode", + "type": "number", + "required": false, + "description": "付款方式" + }, + { + "name": "brandno", + "type": "string", + "required": false, + "description": "品牌编码" + }, + { + "name": "providertype", + "type": "string", + "required": false, + "description": "服务商类型编码" + }, + { + "name": "providerid", + "type": "number", + "required": false, + "description": "服务商ID" + }, + { + "name": "platform_code", + "type": "string", + "required": true, + "description": "平台编码(PDD/CAINIAO/DY/KS/SPH/XHS/JD/QT)" + }, + { + "name": "sender_name", + "type": "string", + "required": false, + "description": "寄件人" + }, + { + "name": "sender_tel", + "type": "string", + "required": false, + "description": "寄件电话" + }, + { + "name": "weight", + "type": "number", + "required": false, + "description": "排序权重" + }, + { + "name": "weight_type", + "type": "number", + "required": false, + "description": "重量类型" + }, + { + "name": "viewer", + "type": "string", + "required": false, + "description": "查看者/备注" + }, + { + "name": "client_id", + "type": "string", + "required": false, + "description": "客户ID" + }, + { + "name": "is_enabled", + "type": "number", + "required": false, + "description": "是否启用(1启用 0禁用)" + }, + { + "name": "is_share", + "type": "number", + "required": false, + "description": "是否共享" + }, + { + "name": "ispickup", + "type": "number", + "required": false, + "description": "是否上门取件" + }, + { + "name": "shipperno", + "type": "string", + "required": false, + "description": "发货编号/客户代码" + }, + { + "name": "template_url", + "type": "string", + "required": false, + "description": "模板URL" + }, + { + "name": "ext_data", + "type": "object", + "required": false, + "description": "扩展数据(JSON对象)" + }, + { + "name": "province_name", + "type": "string", + "required": false, + "description": "省份" + }, + { + "name": "city_name", + "type": "string", + "required": false, + "description": "城市" + }, + { + "name": "district_name", + "type": "string", + "required": false, + "description": "区县" + }, + { + "name": "address", + "type": "string", + "required": false, + "description": "详细地址" + }, + { + "name": "town_name", + "type": "string", + "required": false, + "description": "镇/街道" + }, + { + "name": "site_code", + "type": "string", + "required": false, + "description": "网点编码" + }, + { + "name": "product_type", + "type": "string", + "required": false, + "description": "产品类型" + }, + { + "name": "shop_name", + "type": "string", + "required": false, + "description": "店铺名称" + }, + { + "name": "express", + "type": "object", + "required": false, + "description": "关联的系统快递对象", + "children": [ + { + "name": "code", + "type": "string", + "required": false, + "description": "系统快递编码" + }, + { + "name": "name", + "type": "string", + "required": false, + "description": "快递名称" + }, + { + "name": "polyapi_code", + "type": "string", + "required": false, + "description": "PolyAPI编码" + }, + { + "name": "polyapi_extra_info", + "type": "string", + "required": false, + "description": "PolyAPI扩展信息" + }, + { + "name": "pdd_code", + "type": "string", + "required": false, + "description": "拼多多快递编码" + }, + { + "name": "ks_code", + "type": "string", + "required": false, + "description": "快手快递编码" + }, + { + "name": "dyxd_code", + "type": "string", + "required": false, + "description": "抖音快递编码" + } + ] + }, + { + "name": "express_name", + "type": "string", + "required": false, + "description": "快递名称(扁平字段)" + }, + { + "name": "express_polyapi_extra_info", + "type": "string", + "required": false, + "description": "PolyAPI扩展信息(扁平字段)" + }, + { + "name": "express_pdd_code", + "type": "string", + "required": false, + "description": "拼多多快递编码(扁平字段)" }, { "name": "is_system_express_code", "type": "number", - "description": "该行 express_code 是否为系统快递编码;若不是系统快递编码返回 0,否则返回 1", - "required": true + "required": true, + "description": "是否为系统快递编码(1是 0否)" + }, + { + "name": "quantity", + "type": "number", + "required": true, + "description": "可用面单数量(从店铺快递签约数据汇总),无店铺或无数据时为 0" + }, + { + "name": "recycled_quantity", + "type": "number", + "required": true, + "description": "已回收面单数量" + }, + { + "name": "cancel_quantity", + "type": "number", + "required": true, + "description": "已取消面单数量" + }, + { + "name": "allocated_quantity", + "type": "number", + "required": true, + "description": "已分配面单数量" } ], "description": "list,按 weight 升序、id 降序排序;优先按权重排序,权重相同再按 id 倒序" @@ -14235,20 +14507,20 @@ { "name": "total", "type": "number", - "description": "total", - "required": true + "required": true, + "description": "总记录数" }, { "name": "page", "type": "number", - "description": "page", - "required": true + "required": true, + "description": "当前页码" }, { "name": "page_size", "type": "number", - "description": "page_size", - "required": true + "required": true, + "description": "每页条数" } ], "errors": [] From a9a015117fe16d3ed95200462ad28735b4f737d7 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 3 Aug 2026 21:03:21 +0800 Subject: [PATCH 165/550] =?UTF-8?q?feat(print):=20=E6=96=B0=E5=A2=9E?= =?UTF-8?q?=E6=89=93=E5=8D=B0=E5=AE=8C=E6=88=90=E5=90=8E=E5=BC=82=E6=AD=A5?= =?UTF-8?q?=E8=A7=A3=E7=BB=91=E6=8B=A3=E8=B4=A7=E8=BD=A6=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - tryUnbindCartAfterPrintComplete: 接收 waveId,按团购/散单检测任务下所有订单 print_status - 团购仅小团购(pick_mode=1)触发,统一用订单 print_status != 'none' 判断 - send() express 成功分支异步 fire-and-forget 调用,不阻塞返回 - 解绑时写入 unbind_user_id,从 ctx 上下文提取操作人 - 含 extractUniqueWaveIds 去重 + 18 项单元测试全部通过 --- app/service/systemMethods/order/base.js | 104 +++++++++++++++++++++++- app/service/systemMethods/print.js | 91 +++++++++++++++++++++ app/service/systems/order_export.js | 8 +- 3 files changed, 201 insertions(+), 2 deletions(-) diff --git a/app/service/systemMethods/order/base.js b/app/service/systemMethods/order/base.js index 7f7c006..9b6354f 100644 --- a/app/service/systemMethods/order/base.js +++ b/app/service/systemMethods/order/base.js @@ -910,6 +910,102 @@ class OrderBaseService extends MainService { }; } + /** + * 提取买家留言虚拟筛选条件 buyer_message_has。 + * 覆盖 buyer_message / seller_message / remark 三个字段,任一有值即为"有留言"。 + * 将其从 where 中移除并解析为布尔值,后续在 buildWhere 之后注入 Sequelize 条件。 + * @param {Object} whereInput 标准化后的 where 条件。 + * @return {{ where: Object, buyerMessageHas: boolean|null }} 清洗后的 where 与买家留言标记。 + */ + extractBuyerMessageHasVirtualFilter(whereInput = {}) { + const normalizedWhere = this.isPlainObject(whereInput) + ? { ...whereInput } + : {}; + const buyerMessageHasCondition = normalizedWhere.buyer_message_has; + + delete normalizedWhere.buyer_message_has; + + if (!buyerMessageHasCondition) { + return { where: normalizedWhere, buyerMessageHas: null }; + } + + const rawValue = this.isPlainObject(buyerMessageHasCondition) + && Object.prototype.hasOwnProperty.call(buyerMessageHasCondition, 'value') + ? buyerMessageHasCondition.value + : buyerMessageHasCondition; + + // 兼容布尔值、字符串 'true'/'false'、'Y'/'N'、数字 1/0、以及前端 select 组件值 'has'/'empty'/'none' + const normalizedRawValue = typeof rawValue === 'string' ? rawValue.trim().toLowerCase() : rawValue; + if (rawValue === true || normalizedRawValue === 'true' || normalizedRawValue === 'y' || normalizedRawValue === 'has' || rawValue === 1) { + return { where: normalizedWhere, buyerMessageHas: true }; + } + if (rawValue === false || normalizedRawValue === 'false' || normalizedRawValue === 'n' || normalizedRawValue === 'empty' || normalizedRawValue === 'none' || rawValue === 0) { + return { where: normalizedWhere, buyerMessageHas: false }; + } + + return { where: normalizedWhere, buyerMessageHas: null }; + } + + /** + * 构建 buyer_message_has 虚拟字段的 Sequelize where 条件。 + * 覆盖三个留言/备注字段:buyer_message、seller_message、remark。 + * @param {boolean} hasMessage true=任一字段有留言,false=三个字段全部为空。 + * @return {Object|null} Sequelize where 条件,无效时返回 null。 + */ + buildBuyerMessageHasCondition(hasMessage) { + if (typeof hasMessage !== 'boolean') { + return null; + } + const { Op } = this.app.Sequelize; + const hasContent = col => ({ + [Op.and]: [ + { [col]: { [Op.not]: null } }, + { [col]: { [Op.ne]: '' } }, + ], + }); + const isEmpty = col => ({ + [Op.or]: [ + { [col]: { [Op.is]: null } }, + { [col]: { [Op.eq]: '' } }, + ], + }); + const fields = [ 'buyer_message', 'seller_message', 'remark' ]; + if (hasMessage) { + return { [Op.or]: fields.map(col => hasContent(col)) }; + } + return { [Op.and]: fields.map(col => isEmpty(col)) }; + } + + /** + * 将附加条件并入 queryWhere,兼容 flat 对象与 { [Op.and]: [...] } 结构。 + * @param {Object} queryWhere 现有 Sequelize where 条件。 + * @param {Object} extraCondition 待并入的条件。 + * @return {Object} 合并后的 where 条件。 + */ + appendConditionToWhere(queryWhere = {}, extraCondition = null) { + if (!extraCondition || !this.isPlainObject(extraCondition) + || (Object.keys(extraCondition).length === 0 && Object.getOwnPropertySymbols(extraCondition).length === 0)) { + return queryWhere; + } + const { Op } = this.app.Sequelize; + + if (!this.isPlainObject(queryWhere) + || (Object.keys(queryWhere).length === 0 && Object.getOwnPropertySymbols(queryWhere).length === 0)) { + return extraCondition; + } + + if (Array.isArray(queryWhere[Op.and])) { + return { + ...queryWhere, + [Op.and]: [ ...queryWhere[Op.and], extraCondition ], + }; + } + + return { + [Op.and]: [ queryWhere, extraCondition ], + }; + } + /** * 规范化运单号筛选输入,兼容字符串、数组与 { value } 结构。 * @param {*} condition 运单号筛选条件。 @@ -1150,7 +1246,8 @@ class OrderBaseService extends MainService { }, }); const { where: sanitizedWhere, expressNumbers } = this.extractOrderListExpressVirtualFilter(where); - const mergedWhere = this.mergeWhereObjects(this.getDefaultWhere(moduleName), sanitizedWhere); + const { where: whereAfterBuyerMessage, buyerMessageHas } = this.extractBuyerMessageHasVirtualFilter(sanitizedWhere); + const mergedWhere = this.mergeWhereObjects(this.getDefaultWhere(moduleName), whereAfterBuyerMessage); let queryWhere = this.buildWhere(mergedWhere, contextWarehouseId, { specialFieldMap: { quickWhere: { @@ -1164,6 +1261,11 @@ class OrderBaseService extends MainService { queryWhere = this.appendOrderIdsFilterToWhere(queryWhere, orderIds); } + if (buyerMessageHas !== null) { + const buyerMessageCondition = this.buildBuyerMessageHasCondition(buyerMessageHas); + queryWhere = this.appendConditionToWhere(queryWhere, buyerMessageCondition); + } + const model = await this.getOrderModel(moduleName, contextWarehouseId); const order = this.buildListOrder(requestData.sort, moduleName); const offset = (page - 1) * pageSize; diff --git a/app/service/systemMethods/print.js b/app/service/systemMethods/print.js index 7cdc50a..e0135f6 100644 --- a/app/service/systemMethods/print.js +++ b/app/service/systemMethods/print.js @@ -971,6 +971,18 @@ class PrintService extends MainService { printIds: Array.isArray(expressSendResult.printIds) ? expressSendResult.printIds : [], }); } + // 异步检查是否需要解绑拣货车(不阻塞返回) + const expressWaveIds = this.extractUniqueWaveIds(data.waveGroups); + for (const wid of expressWaveIds) { + this.tryUnbindCartAfterPrintComplete(wid).catch(err => { + this.ctx.logger.error('[print.send] 异步解绑车标异常', { + waveId: wid, + warehouseId, + error: err && err.message ? err.message : `${err}`, + }); + }); + } + this.ctx.logger.info('[print.send] 最终返回 success', { warehouseId, type, @@ -1194,6 +1206,23 @@ class PrintService extends MainService { return Array.from(platformCodeSet); } + /** + * 从 waveGroups 中提取去重后的 wave_id 列表。 + * @param {Array} waveGroups 波次分组数据。 + * @return {Array} 去重后的波次ID列表。 + */ + extractUniqueWaveIds(waveGroups = []) { + const normalizedWaveGroups = Array.isArray(waveGroups) ? waveGroups : []; + const waveIdSet = new Set(); + for (const waveGroup of normalizedWaveGroups) { + const waveId = Number(waveGroup && waveGroup.wave_id || 0); + if (Number.isInteger(waveId) && waveId > 0) { + waveIdSet.add(waveId); + } + } + return Array.from(waveIdSet); + } + /** * 从波次平台数据中提取订单ID列表。 * @@ -2750,6 +2779,68 @@ class PrintService extends MainService { return this.success('success', { data: null, code: 0 }); } + + async tryUnbindCartAfterPrintComplete(waveId, warehouseId) { + const { ctx } = this; + const resolvedWarehouseId = Number(warehouseId || ctx.user && ctx.user.store_id || 0); + let taskId = 0; + let waveType = 0; + try { + const waveBatch = await ctx.model.WaveBatch.findOne({ where: { wave_id: waveId }, attributes: [ 'wave_type' ], raw: true }); + if (!waveBatch) return; + waveType = Number(waveBatch.wave_type); + if (![ 1, 2 ].includes(waveType)) return; + const taskWaveRows = await ctx.model.query( + 'SELECT task_id FROM wms_wave_pick_task_wave WHERE wave_id = :waveId AND warehouse_id = :warehouseId LIMIT 1', + { replacements: { waveId, warehouseId: resolvedWarehouseId }, type: ctx.model.QueryTypes.SELECT } + ); + const taskWave = Array.isArray(taskWaveRows) && taskWaveRows.length > 0 ? taskWaveRows[0] : null; + if (!taskWave || !taskWave.task_id) return; + taskId = Number(taskWave.task_id); + if (!taskId) return; + + if (waveType === 1) { + const taskRows = await ctx.model.query( + 'SELECT pick_mode FROM wms_wave_pick_task WHERE id = :taskId LIMIT 1', + { replacements: { taskId }, type: ctx.model.QueryTypes.SELECT } + ); + const task = Array.isArray(taskRows) && taskRows.length > 0 ? taskRows[0] : null; + const pickMode = task ? Number(task.pick_mode) : 0; + if (pickMode !== 1) return; + } + + // 团购 / 散单统一按订单维度检查:所有订单均已打印时才解绑 + const taskOrders = await ctx.model.query( + 'SELECT DISTINCT order_id FROM wms_wave_pick_task_order WHERE task_id = :taskId', + { replacements: { taskId }, type: ctx.model.QueryTypes.SELECT } + ); + const orderIds = (Array.isArray(taskOrders) ? taskOrders : []).map(r => Number(r && r.order_id)).filter(id => id > 0); + if (orderIds.length === 0) return; + const orderDeliveryFactory = ctx.model && ctx.model.OrderDeliveryFactory; + if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') { + this.ctx.logger.warn('[print.unbindCart] OrderDeliveryFactory 不可用,跳过检查'); + return; + } + const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(resolvedWarehouseId); + const unprintedCount = await orderDeliveryModel.count({ + where: { id: { [ctx.model.Sequelize.Op.in]: orderIds }, print_status: 'none' }, + }); + if (unprintedCount > 0) { + this.ctx.logger.info('[print.unbindCart] 尚有未打印订单,跳过解绑', { waveId, warehouseId, taskId, waveType, waveTypeLabel: waveType === 1 ? '团购' : '散单', totalOrders: orderIds.length, unprintedCount }); + return; + } + + const operator = this.getPrintOrderOperationOperator(); + const unbindUserId = operator.id || null; + await ctx.model.query( + 'UPDATE wms_pick_task_cart_binding SET is_active = 0, unbind_user_id = :unbindUserId, unbind_time = NOW(), update_time = NOW() WHERE task_id = :taskId AND is_active = 1', + { replacements: { taskId, unbindUserId } } + ); + this.ctx.logger.info('[print.unbindCart] 车标解绑成功', { waveId, warehouseId: resolvedWarehouseId, taskId, waveType, waveTypeLabel: waveType === 1 ? '团购' : '散单', unbindUserId }); + } catch (error) { + this.ctx.logger.error('[print.unbindCart] 解绑车标检查异常', { waveId, warehouseId: resolvedWarehouseId, taskId, waveType, error: error && error.message ? error.message : String(error) }); + } + } } module.exports = PrintService; diff --git a/app/service/systems/order_export.js b/app/service/systems/order_export.js index 2c24b8c..4c66a92 100644 --- a/app/service/systems/order_export.js +++ b/app/service/systems/order_export.js @@ -615,9 +615,10 @@ class OrderExportService extends OrderBaseService { }, }); const { where: sanitizedWhere, expressNumbers } = this.extractOrderListExpressVirtualFilter(where); + const { where: whereAfterBuyerMessage, buyerMessageHas } = this.extractBuyerMessageHasVirtualFilter(sanitizedWhere); const mergedWhere = this.mergeWhereObjects( target.defaultWhereModuleName ? this.getDefaultWhere(target.defaultWhereModuleName) : {}, - sanitizedWhere + whereAfterBuyerMessage ); let queryWhere = this.buildWhere(mergedWhere, warehouseId, { specialFieldMap: { @@ -632,6 +633,11 @@ class OrderExportService extends OrderBaseService { queryWhere = this.appendOrderIdsFilterToWhere(queryWhere, orderIds); } + if (buyerMessageHas !== null) { + const buyerMessageCondition = this.buildBuyerMessageHasCondition(buyerMessageHas); + queryWhere = this.appendConditionToWhere(queryWhere, buyerMessageCondition); + } + const orderModel = await this.getOrderModelByTableType(target.tableType, warehouseId); const pageSize = this.getExportPageSize(); const order = this.buildListOrder(requestData.sort, target.sortModuleName); From 0b781a7e7097cd8ea147e52f011412657778a1fc Mon Sep 17 00:00:00 2001 From: liufumingren Date: Tue, 4 Aug 2026 08:18:43 +0800 Subject: [PATCH 166/550] =?UTF-8?q?feat:=20=E5=BA=97=E9=93=BA=E5=BF=AB?= =?UTF-8?q?=E9=80=92=E7=BB=91=E5=AE=9A=E7=AD=96=E7=95=A5=E6=A8=A1=E5=9D=97?= =?UTF-8?q?=20+=20=E8=AE=A2=E5=8D=95=E5=88=9B=E5=BB=BA=E9=93=BE=E8=B7=AF?= =?UTF-8?q?=E9=9B=86=E6=88=90=20+=20=E8=BF=90=E5=8D=95=E5=8F=B7=E5=88=86?= =?UTF-8?q?=E9=85=8D=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 【新增模块】 - app/model/store_express_binding_policy.js: 策略数据模型(17字段,JSON数组) - app/service/systems/store_express_binding_policy.js: CRUD+列表(含名称批量解析) - app/service/systems/express_policy.js: 缓存优先策略查询 + 6维漏斗匹配引擎 - app/service/systemMethods/store_express_binding_policy.js: method路由层 - database/designs/store-express-binding-policy-design.md: 设计文档 【策略漏斗匹配逻辑】 - 按priority DESC逐条匹配: store_ids→shop_name→prohibited→regions→exclude→weight - NULL/空数组=不限, 未命中自动continue到下一条 - 地区/店铺匹配使用子串包含(省/市/区/详细地址均生效) - 违禁品匹配使用数组交集 - 输出快递编码+重量类型, 未命中返回null 【订单创建链路集成】 - addOrder→addOrderLines后触发matchPolicy(weight可用) - 命中: 写入logistics/sys_logistics 4字段+weight_type+操作日志 - 未命中: 降级到resolveExpressSnapshot默认值+兜底DEFAULT_STORE_SUBJECT_CONFIG(STO) - 系统快递4字段一致, 自定义映射(express_setting)分流写入 【运单号分配优化】 - pickWaybillExpressInterface两步兜底: Step1: logistics_code仅匹配express_code(自定义编码精确) Step2: sys_logistics_code匹配全候选码(系统编码兜底) - 新增weight_type过滤器(接口NULL=通配, 设限须精确匹配) - groupedOrder.options新增sys_logistics_code/weight_type传递 【操作码翻译】 - ORDER_EXPRESS_POLICY_MATCH: '策略命中' - ORDER_EXPRESS_FALLBACK: '快递降级' - 无策略命中时写入快递降级日志 【API文档】 - methods/system.json: 策略模块4接口+响应字段(express_name/数组类型等) 【数据库迁移】 - 13个migration: 建表→字段迭代→TEXT改JSON→prohibited改数组(dev+prod均执行) --- app/dict/businessDict.js | 1 + app/model/store_express_binding_policy.js | 144 ++++ .../store_express_binding_policy.js | 210 ++++++ app/service/systems/delivery_order.js | 118 ++- app/service/systems/express.js | 63 +- app/service/systems/express_policy.js | 275 +++++++ .../systems/store_express_binding_policy.js | 696 ++++++++++++++++++ .../store-express-binding-policy-design.md | 138 ++++ ...create-wms-store-express-binding-policy.js | 129 ++++ ...emove-store-shop-id-from-binding-policy.js | 40 + ...dd-prohibited-type-id-to-binding-policy.js | 18 + ...e-match-condition-with-provinces-cities.js | 31 + ...0000-add-weight-range-to-binding-policy.js | 25 + ...70500-add-weight-type-to-binding-policy.js | 18 + ...0260803171000-make-weight-type-required.js | 23 + ...90000-merge-provinces-cities-to-regions.js | 30 + .../20260804091000-add-exclude-regions.js | 18 + .../20260804100000-add-shop-name.js | 18 + .../20260804101000-add-store-ids.js | 18 + .../20260804110000-change-text-to-json.js | 19 + ...0260804120000-change-prohibited-to-json.js | 21 + methods/system.json | 489 +++++++++++- 22 files changed, 2519 insertions(+), 23 deletions(-) create mode 100644 app/model/store_express_binding_policy.js create mode 100644 app/service/systemMethods/store_express_binding_policy.js create mode 100644 app/service/systems/express_policy.js create mode 100644 app/service/systems/store_express_binding_policy.js create mode 100644 database/designs/store-express-binding-policy-design.md create mode 100644 database/migrations/20260803150000-create-wms-store-express-binding-policy.js create mode 100644 database/migrations/20260803160000-remove-store-shop-id-from-binding-policy.js create mode 100644 database/migrations/20260803163000-add-prohibited-type-id-to-binding-policy.js create mode 100644 database/migrations/20260803164500-replace-match-condition-with-provinces-cities.js create mode 100644 database/migrations/20260803170000-add-weight-range-to-binding-policy.js create mode 100644 database/migrations/20260803170500-add-weight-type-to-binding-policy.js create mode 100644 database/migrations/20260803171000-make-weight-type-required.js create mode 100644 database/migrations/20260804090000-merge-provinces-cities-to-regions.js create mode 100644 database/migrations/20260804091000-add-exclude-regions.js create mode 100644 database/migrations/20260804100000-add-shop-name.js create mode 100644 database/migrations/20260804101000-add-store-ids.js create mode 100644 database/migrations/20260804110000-change-text-to-json.js create mode 100644 database/migrations/20260804120000-change-prohibited-to-json.js diff --git a/app/dict/businessDict.js b/app/dict/businessDict.js index c6c363f..a9004a9 100644 --- a/app/dict/businessDict.js +++ b/app/dict/businessDict.js @@ -68,6 +68,7 @@ module.exports = { ORDER_INTERCEPT_CONFIRM: '确认拦截', ORDER_PLATFORM_FALLBACK: '平台降级', ORDER_EXPRESS_FALLBACK: '快递降级', + ORDER_EXPRESS_POLICY_MATCH: '策略命中', ORDER_WAVE_UPDATE: '更新波次', ORDER_WAVE_ASSIGN: '分配波次', ORDER_WAVE_REMOVE: '移出波次', diff --git a/app/model/store_express_binding_policy.js b/app/model/store_express_binding_policy.js new file mode 100644 index 0000000..0f53969 --- /dev/null +++ b/app/model/store_express_binding_policy.js @@ -0,0 +1,144 @@ +'use strict'; + +/** + * 订单自定义店铺-快递绑定策略模型。 + * + * 支持在仓库维度下,为用户自定义店铺标签配置快递绑定策略, + * 按优先级匹配,可附加商品、地区、重量等条件。 + * + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} Sequelize 模型。 + */ +module.exports = app => { + const { BIGINT, STRING, INTEGER, TINYINT, DATE, TEXT, JSON: JSON_TYPE } = app.Sequelize; + + const StoreExpressBindingPolicy = app.model.define('store_express_binding_policy', { + id: { + type: BIGINT.UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: BIGINT.UNSIGNED, + allowNull: false, + comment: '仓库ID,策略所属仓库', + }, + custom_name: { + type: STRING(100), + allowNull: false, + comment: '策略名称,便于人工识别', + }, + shop_name: { + type: JSON_TYPE, + allowNull: true, + comment: '包含店铺名称,字符串数组,如["旗舰店","奥莱店"],NULL=不限制', + }, + store_ids: { + type: JSON_TYPE, + allowNull: true, + comment: '限定货主ID,数字数组,如[1000000,1000001],NULL=不限制', + }, + express_code: { + type: STRING(50), + allowNull: false, + comment: '绑定的快递编码(wms_express.code)', + }, + priority: { + type: INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '优先级,数值越大越优先匹配', + }, + is_enabled: { + type: TINYINT(1), + allowNull: false, + defaultValue: 1, + validate: { + isIn: { + args: [[ 0, 1 ]], + msg: '启用状态不合法,0=停用,1=启用', + }, + }, + comment: '是否启用:0=停用,1=启用', + }, + regions: { + type: JSON_TYPE, + allowNull: true, + comment: '限定地区,字符串数组,如["广东省","广州市"],NULL=不限制', + }, + exclude_regions: { + type: JSON_TYPE, + allowNull: true, + comment: '排除地区,字符串数组,如["新疆维吾尔自治区"],NULL=不排除', + }, + min_weight_g: { + type: INTEGER, + allowNull: true, + comment: '最小重量(克),NULL=不限制', + }, + max_weight_g: { + type: INTEGER, + allowNull: true, + comment: '最大重量(克),NULL=不限制', + }, + weight_type: { + type: TINYINT(1), + allowNull: false, + defaultValue: 0, + validate: { isIn: { args: [[ 0, 1, 2, 3 ]], msg: '重量类型不合法,0=常规/1=轻货/2=重货/3=冷链' } }, + comment: '重量段类型:0=常规/1=轻货/2=重货/3=冷链', + }, + prohibited_type_id: { + type: JSON_TYPE, + allowNull: true, + comment: '违禁品类型ID数组(关联 wms_prohibited_type.id),如[1,2],NULL=不限制违禁品', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注说明', + }, + creator_id: { + type: BIGINT.UNSIGNED, + allowNull: true, + comment: '创建人账户ID(accounts.id)', + }, + created_at: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + tableName: 'wms_store_express_binding_policy', + freezeTableName: true, + underscored: true, + timestamps: false, + comment: '订单自定义店铺-快递绑定策略表', + indexes: [ + { + name: 'idx_warehouse_enabled', + fields: [ 'warehouse_id', 'is_enabled', 'deleted_at' ], + }, + { + name: 'idx_warehouse_express', + fields: [ 'warehouse_id', 'express_code', 'deleted_at' ], + }, + ], + }); + + return StoreExpressBindingPolicy; +}; diff --git a/app/service/systemMethods/store_express_binding_policy.js b/app/service/systemMethods/store_express_binding_policy.js new file mode 100644 index 0000000..b97258e --- /dev/null +++ b/app/service/systemMethods/store_express_binding_policy.js @@ -0,0 +1,210 @@ +'use strict'; + +const MainService = require('../main'); + +/** + * 店铺-快递绑定策略 methods 出口。 + * + * 支持以下 method 调用(通过 /system?method=storeExpressBindingPolicy.xxx): + * - storeExpressBindingPolicy.list 分页查询策略列表 + * - storeExpressBindingPolicy.add 新增策略 + * - storeExpressBindingPolicy.edit 编辑策略 + * - storeExpressBindingPolicy.del 软删除策略 + */ +class StoreExpressBindingPolicyMethodService extends MainService { + /** + * 初始化鉴权配置。 + * @param {Egg.Context} ctx 上下文对象 + */ + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = ''; + const _noNeedLog = '*'; + const _noNeedAuth = ''; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 统一调用业务服务。 + * @param {string} methodName 业务方法名 + * @param {Object} data 请求参数 + * @param {string} fallbackMessage 默认错误文案 + * @return {Promise} methods 标准返回 + */ + async callSystem(methodName, data, fallbackMessage) { + const { service } = this; + + try { + const result = await service.systems.storeExpressBindingPolicy[methodName](data); + return this.success('ok', { data: result, code: 200 }); + } catch (error) { + return this.fail(error.message || fallbackMessage, { + code: Number(error.code) || 500, + }); + } + } + + /** + * storeExpressBindingPolicy.list:分页查询策略列表。 + * @param {Object} [data={}] 请求参数 + * @return {Promise} 查询结果 + */ + async list(data = {}) { + const payload = { + ...(data && typeof data === 'object' ? data : {}), + }; + + this.prepareWhereContext(payload, { + specialFieldMap: this.service.systems.storeExpressBindingPolicy.getListWhereSpecialFieldMap(), + }); + + return await this.callSystem('list', payload, '查询策略列表失败'); + } + + /** + * storeExpressBindingPolicy.add:新增策略。 + * @param {Object} [data={}] 请求参数 + * @return {Promise} 新增结果 + */ + async add(data = {}) { + const { + custom_name: customName, + customName: customNameCamel, + express_code: expressCode, + expressCode: expressCodeCamel, + priority, + is_enabled: isEnabled, + isEnabled: isEnabledCamel, + regions, + shop_name: shopName, + store_ids: storeIds, + exclude_regions: excludeRegions, + min_weight_g: minWeightG, + max_weight_g: maxWeightG, + weight_type: weightType, + prohibited_type_id: prohibitedTypeId, + prohibitedTypeId: prohibitedTypeIdCamel, + remark, + creator_id: creatorId, + creatorId: creatorIdCamel, + } = data || {}; + + return await this.callSystem('add', { + custom_name: customName !== undefined ? customName : customNameCamel, + express_code: expressCode !== undefined ? expressCode : expressCodeCamel, + priority, + is_enabled: isEnabled !== undefined ? isEnabled : isEnabledCamel, + regions, + shop_name: shopName, + store_ids: storeIds, + exclude_regions: excludeRegions, + min_weight_g: minWeightG, + max_weight_g: maxWeightG, + weight_type: weightType, + prohibited_type_id: prohibitedTypeId !== undefined ? prohibitedTypeId : prohibitedTypeIdCamel, + remark, + creator_id: creatorId !== undefined ? creatorId : creatorIdCamel, + }, '新增策略失败'); + } + + /** + * storeExpressBindingPolicy.edit:编辑策略。 + * @param {Object} [data={}] 请求参数 + * @return {Promise} 编辑结果 + */ + async edit(data = {}) { + const { + id, + policy_id: policyId, + policyId: policyIdCamel, + custom_name: customName, + customName: customNameCamel, + express_code: expressCode, + expressCode: expressCodeCamel, + priority, + is_enabled: isEnabled, + isEnabled: isEnabledCamel, + regions, + shop_name: shopName, + store_ids: storeIds, + exclude_regions: excludeRegions, + min_weight_g: minWeightG, + max_weight_g: maxWeightG, + weight_type: weightType, + prohibited_type_id: prohibitedTypeId, + prohibitedTypeId: prohibitedTypeIdCamel, + remark, + creator_id: creatorId, + creatorId: creatorIdCamel, + } = data || {}; + + const payload = { + id: id !== undefined ? id : (policyId !== undefined ? policyId : policyIdCamel), + }; + + if (customName !== undefined || customNameCamel !== undefined) { + payload.custom_name = customName !== undefined ? customName : customNameCamel; + } + if (expressCode !== undefined || expressCodeCamel !== undefined) { + payload.express_code = expressCode !== undefined ? expressCode : expressCodeCamel; + } + if (priority !== undefined) { + payload.priority = priority; + } + if (isEnabled !== undefined || isEnabledCamel !== undefined) { + payload.is_enabled = isEnabled !== undefined ? isEnabled : isEnabledCamel; + } + if (regions !== undefined) { + payload.regions = regions; + } + if (shopName !== undefined) { + payload.shop_name = shopName; + } + if (storeIds !== undefined) { + payload.store_ids = storeIds; + } + if (excludeRegions !== undefined) { + payload.exclude_regions = excludeRegions; + } + if (minWeightG !== undefined) { + payload.min_weight_g = minWeightG; + } + if (maxWeightG !== undefined) { + payload.max_weight_g = maxWeightG; + } + if (weightType !== undefined) { + payload.weight_type = weightType; + } + if (prohibitedTypeId !== undefined || prohibitedTypeIdCamel !== undefined) { + payload.prohibited_type_id = prohibitedTypeId !== undefined ? prohibitedTypeId : prohibitedTypeIdCamel; + } + if (remark !== undefined) { + payload.remark = remark; + } + if (creatorId !== undefined || creatorIdCamel !== undefined) { + payload.creator_id = creatorId !== undefined ? creatorId : creatorIdCamel; + } + + return await this.callSystem('edit', payload, '编辑策略失败'); + } + + /** + * storeExpressBindingPolicy.del:软删除策略。 + * @param {Object} [data={}] 请求参数 + * @return {Promise} 删除结果 + */ + async del(data = {}) { + const { + id, + policy_id: policyId, + policyId: policyIdCamel, + } = data || {}; + + return await this.callSystem('del', { + id: id !== undefined ? id : (policyId !== undefined ? policyId : policyIdCamel), + }, '删除策略失败'); + } +} + +module.exports = StoreExpressBindingPolicyMethodService; diff --git a/app/service/systems/delivery_order.js b/app/service/systems/delivery_order.js index b545307..45f954d 100644 --- a/app/service/systems/delivery_order.js +++ b/app/service/systems/delivery_order.js @@ -22,6 +22,7 @@ const ORDER_OPERATION_CODES = Object.freeze({ CREATE: 'ORDER_CREATE', PLATFORM_FALLBACK: 'ORDER_PLATFORM_FALLBACK', EXPRESS_FALLBACK: 'ORDER_EXPRESS_FALLBACK', + EXPRESS_POLICY_MATCH: 'ORDER_EXPRESS_POLICY_MATCH', }); const STORE_SUBJECT_CONFIG_CACHE_TTL_SECONDS = 600; @@ -514,11 +515,12 @@ class DeliveryOrderService extends Service { || '' ).trim(); - const fallbackExpress = this.findCodeOption(expressList, defaultCode); + const fallbackExpress = this.findCodeOption(expressList, defaultCode) + || this.findCodeOption(expressList, DEFAULT_STORE_SUBJECT_CONFIG.default_express_code); const fallbackLogisticsCode = String( - fallbackExpress && (fallbackExpress.code || fallbackExpress.value || fallbackExpress.express_code || defaultCode) + fallbackExpress && (fallbackExpress.code || fallbackExpress.value || fallbackExpress.express_code || defaultCode || DEFAULT_STORE_SUBJECT_CONFIG.default_express_code) || defaultCode - || '' + || DEFAULT_STORE_SUBJECT_CONFIG.default_express_code ).trim(); const fallbackLogisticsName = this.getOptionName(fallbackExpress); const explicitEnableExternalExpressCode = info && Object.prototype.hasOwnProperty.call(info, 'enableExternalExpressCode') @@ -536,6 +538,7 @@ class DeliveryOrderService extends Service { logisticsName: fallbackLogisticsName, sysLogisticsCode: fallbackLogisticsCode, sysLogisticsName: fallbackLogisticsName, + weightType: 0, }; } @@ -554,6 +557,7 @@ class DeliveryOrderService extends Service { logisticsName: String(expressSetting.name || '').trim(), sysLogisticsCode: matchedSysLogisticsCode, sysLogisticsName: matchedSysLogisticsName, + weightType: 0, }; } @@ -570,6 +574,7 @@ class DeliveryOrderService extends Service { logisticsName: matchedLogisticsName, sysLogisticsCode: matchedLogisticsCode, sysLogisticsName: matchedLogisticsName, + weightType: 0, }; } if (fallbackExpress) { @@ -592,6 +597,7 @@ class DeliveryOrderService extends Service { logisticsName: fallbackLogisticsName, sysLogisticsCode: fallbackLogisticsCode, sysLogisticsName: fallbackLogisticsName, + weightType: 0, }; } @@ -608,6 +614,7 @@ class DeliveryOrderService extends Service { logisticsName: fallbackLogisticsName, sysLogisticsCode: fallbackLogisticsCode, sysLogisticsName: fallbackLogisticsName, + weightType: 0, }; } @@ -728,6 +735,110 @@ class DeliveryOrderService extends Service { updated_at: new Date(), }; + // ===== 快递绑定策略漏斗匹配(items 处理后 weight 可用) ===== + try { + const receiverInfo = deliveryOrder.receiverInfo; + const shopNick = deliveryOrder.shopNick; + const hasEnoughData = shopNick || (receiverInfo && (receiverInfo.province || receiverInfo.city)); + + if (hasEnoughData) { + const address = [ + receiverInfo?.province || '', + receiverInfo?.city || '', + receiverInfo?.area || '', + receiverInfo?.town || '', + receiverInfo?.detail_address || '', + ].join('').trim(); + + const matchResult = await ctx.service.systems.expressPolicy.matchPolicy( + info.warehouseId, + { + storeId: info.storeId, + customShopName: shopNick || '', + address: address || '', + weight: itemsInfo.total_weight || null, + prohibitedTypeIds: null, // TODO: 后续从商品 StockWarehouse.prohibited_id 聚合 + } + ); + + if (matchResult && matchResult.expressCode) { + const expressList = await ctx.service.systems.express.getExpressList(); + const matchedExpress = expressList.find( + item => item && String(item.code || item.value || '').trim() === String(matchResult.expressCode).trim() + ); + + let logisticsCode; + let logisticsName; + let sysLogisticsCode; + let sysLogisticsName; + + if (matchedExpress) { + if (matchedExpress.is_system_setting) { + // 自定义映射:sys 写映射的系统快递,logistics 写自定义编码 + sysLogisticsCode = String(matchedExpress.express_code || '').trim(); + const sysItem = expressList.find( + item => item && !item.is_system_setting && String(item.code || item.value || '').trim() === sysLogisticsCode + ); + sysLogisticsName = sysItem ? String(sysItem.name || sysItem.label || sysLogisticsCode).trim() : sysLogisticsCode; + logisticsCode = String(matchedExpress.code || matchedExpress.value || matchResult.expressCode).trim(); + logisticsName = String(matchedExpress.alias || matchedExpress.name || logisticsCode).trim(); + } else { + // 系统快递:4 字段一致 + logisticsCode = String(matchedExpress.code || matchedExpress.value || matchResult.expressCode).trim(); + logisticsName = String(matchedExpress.name || matchedExpress.label || logisticsCode).trim(); + sysLogisticsCode = logisticsCode; + sysLogisticsName = logisticsName; + } + } else { + // 未在列表中,fallback + logisticsCode = String(matchResult.expressCode).trim(); + logisticsName = logisticsCode; + sysLogisticsCode = logisticsCode; + sysLogisticsName = logisticsCode; + } + + stats.logistics_code = logisticsCode; + stats.logistics_name = logisticsName; + stats.sys_logistics_code = sysLogisticsCode; + stats.sys_logistics_name = sysLogisticsName; + stats.weight_type = matchResult.weightType; + stats.updated_at = new Date(); + + // 写入操作日志:命中了哪条策略 + this.appendOrderOperationLog( + operationLogs, + ORDER_OPERATION_CODES.EXPRESS_POLICY_MATCH, + `快递策略命中: ${matchResult.policyName || '未知'}(${matchResult.policyId || '?'}) → ${sysLogisticsName || sysLogisticsCode}` + ); + + ctx.logger.info('[ExpressPolicyMatch] 策略命中(延迟匹配)', { + orderId, + orderCode: deliveryOrder.deliveryOrderCode, + logisticsCode, + sysLogisticsCode, + weightType: matchResult.weightType, + policyName: matchResult.policyName, + policyId: matchResult.policyId, + totalWeight: itemsInfo.total_weight, + }); + } else if (hasEnoughData) { + // 策略未命中:记快递降级日志(取已落库的初始快递值) + const fallbackCode = orderData.sys_logistics_code || orderData.logistics_code; + const fallbackName = orderData.sys_logistics_name || orderData.logistics_name; + this.appendOrderOperationLog( + operationLogs, + ORDER_OPERATION_CODES.EXPRESS_FALLBACK, + `未命中快递策略,使用默认快递: ${fallbackName || fallbackCode}` + ); + } + } + } catch (policyErr) { + ctx.logger.warn('[ExpressPolicyMatch] 策略匹配异常,跳过', { + orderId, + error: policyErr.message, + }); + } + await DeliveryModel.update( stats, { @@ -1104,6 +1215,7 @@ class DeliveryOrderService extends Service { sys_logistics_code: expressSnapshot.sysLogisticsCode, sys_logistics_name: expressSnapshot.sysLogisticsName, express_code: expressCode || '', + weight_type: expressSnapshot.weightType ?? 0, logistics_area_code: logisticsAreaCode || '', is_urgency: isUrgency || 'N', invoice_flag: invoiceFlag || 'N', diff --git a/app/service/systems/express.js b/app/service/systems/express.js index 075893a..b167287 100644 --- a/app/service/systems/express.js +++ b/app/service/systems/express.js @@ -1797,6 +1797,8 @@ class ExpressService extends Service { sys_platform_code: sysPlatformCode, print_platform_code: printPlatformCode, logistics_code: logisticsCode, + sys_logistics_code: String(order.sys_logistics_code || '').trim(), + weight_type: order.weight_type !== undefined ? Number(order.weight_type) : 0, sys_platform_name: order.sys_platform_name || '', logistics_name: order.logistics_name || '', store_id: order.store_id || 0, @@ -1854,10 +1856,16 @@ class ExpressService extends Service { && groupedOrder.options && groupedOrder.options.logistics_code ); - - if (!logisticsCode) { - return null; - } + const sysLogisticsCode = normalizeCode( + groupedOrder + && groupedOrder.options + && groupedOrder.options.sys_logistics_code + ); + const orderWeightType = Number( + groupedOrder + && groupedOrder.options + && groupedOrder.options.weight_type + ) || 0; const platformCode = normalizeCode( groupedOrder @@ -1871,27 +1879,44 @@ class ExpressService extends Service { && matchedPlatform.print_platform_code ); - for (const item of Array.isArray(interfaceList) ? interfaceList : []) { - if (!item || typeof item !== 'object') { - continue; - } + const enabledList = (Array.isArray(interfaceList) ? interfaceList : []) + .filter(item => item && typeof item === 'object' && Number(item.is_enabled) === 1); - // 停用的快递接口不允许分配运单号 - if (Number(item.is_enabled) !== 1) { - continue; + // 通用匹配函数 + const matchByCode = (item, targetCode, useSysCode = true) => { + if (!targetCode) return false; + const candidateCodes = [ normalizeCode(item.express_code) ]; + if (useSysCode) { + candidateCodes.push(normalizeCode(item.sys_express_code)); } - - const candidateCodes = [ - normalizeCode(item.sys_express_code), - normalizeCode(item.express_code), - ]; const expressMap = item.express && typeof item.express === 'object' ? item.express : null; if (expressMap && platformCode) { candidateCodes.push(normalizeCode(expressMap[platformCode])); } + if (!candidateCodes.some(code => code && code === targetCode)) return false; - if (candidateCodes.some(code => code && code === logisticsCode)) { - return item; + const itemWeightType = item.weight_type !== null && item.weight_type !== undefined + ? Number(item.weight_type) : null; + if (itemWeightType !== null && itemWeightType !== orderWeightType) return false; + + return true; + }; + + // 第一步:logistics_code 仅匹配 express_code + 平台码(不用 sys_express_code) + if (logisticsCode) { + for (const item of enabledList) { + if (matchByCode(item, logisticsCode, false)) { + return item; + } + } + } + + // 第二步:sys_logistics_code 匹配 sys_express_code + express_code(全放开) + if (sysLogisticsCode) { + for (const item of enabledList) { + if (matchByCode(item, sysLogisticsCode, true)) { + return item; + } } } @@ -2635,6 +2660,8 @@ class ExpressService extends Service { printPlatformCode: groupedOrder.options.print_platform_code, expressInterfacePlatformCode, logisticsCode: groupedOrder.options.logistics_code, + sysLogisticsCode: groupedOrder.options.sys_logistics_code, + weightType: groupedOrder.options.weight_type, matchedPlatformCode: matchedPlatformWithRequestCode && matchedPlatformWithRequestCode.code, requestPlatformCode: matchedPlatformWithRequestCode && matchedPlatformWithRequestCode.request_platform_code, hasExpressInterface: Boolean(expressInterface), diff --git a/app/service/systems/express_policy.js b/app/service/systems/express_policy.js new file mode 100644 index 0000000..0df2b1f --- /dev/null +++ b/app/service/systems/express_policy.js @@ -0,0 +1,275 @@ +'use strict'; + +const Service = require('egg').Service; + +/** + * 快递策略内部服务。 + * + * 为快递匹配链路提供策略查询能力,内置缓存加速。 + * 不对外暴露 method 路由,仅供其他 service 内部调用。 + */ +class ExpressPolicyService extends Service { + // -------------------- 缓存键 -------------------- + + /** + * 仓库维度策略列表缓存键。 + * @param {number} warehouseId 仓库 ID + * @return {string} 缓存键 + */ + getWarehousePolicyCacheKey(warehouseId) { + return `express_policy:warehouse:${warehouseId}`; + } + + /** + * 仓库维度策略缓存过期秒数(默认 300s)。 + * @return {number} 过期秒数 + */ + getWarehousePolicyCacheTTL() { + return 300; + } + + // -------------------- 缓存清理 -------------------- + + /** + * 清理指定仓库的策略缓存。 + * @param {number} warehouseId 仓库 ID + * @return {Promise} + */ + async clearWarehousePolicyCache(warehouseId) { + const cacheKey = this.getWarehousePolicyCacheKey(warehouseId); + if (this.app && typeof this.app.delCacheAsync === 'function') { + await this.app.delCacheAsync(cacheKey); + } + } + + // -------------------- 数据查询 -------------------- + + /** + * 从数据库查询仓库下所有启用的策略,按优先级降序排列。 + * @param {number} warehouseId 仓库 ID + * @return {Promise>} 策略列表(plain object) + */ + async fetchWarehousePoliciesFromDB(warehouseId) { + const { ctx } = this; + + try { + const rows = await ctx.model.StoreExpressBindingPolicy.findAll({ + where: { + warehouse_id: warehouseId, + is_enabled: 1, + deleted_at: null, + }, + order: [[ 'priority', 'DESC' ], [ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]], + raw: true, + }); + return rows; + } catch (error) { + if (ctx.logger && typeof ctx.logger.warn === 'function') { + ctx.logger.warn('[ExpressPolicyDBError]', error.message, { warehouseId }); + } + return []; + } + } + + // -------------------- 对外方法 -------------------- + + /** + * 获取仓库策略目录(缓存优先)。 + * + * 查询链路:缓存命中 → 直接返回;缓存未命中 → 查库 → 写缓存 → 返回。 + * + * @param {number} warehouseId 仓库 ID + * @param {Object} [options] 选项 + * @param {boolean} [options.forceRefresh=false] 是否强制刷新缓存 + * @return {Promise>} 策略列表(按 priority DESC 排序) + */ + async getWarehousePolicies(warehouseId, options = {}) { + const { app } = this; + const { forceRefresh = false } = options; + + if (!Number.isFinite(Number(warehouseId)) || Number(warehouseId) <= 0) { + return []; + } + + const cacheKey = this.getWarehousePolicyCacheKey(warehouseId); + const ttl = this.getWarehousePolicyCacheTTL(); + + // 1) 读缓存(非强制刷新时) + if (!forceRefresh && app && typeof app.getCacheAsync === 'function') { + try { + const cached = await app.getCacheAsync(cacheKey); + if (cached && Array.isArray(cached) && cached.length > 0) { + return cached; + } + } catch (error) { + if (app.logger && typeof app.logger.warn === 'function') { + app.logger.warn('[ExpressPolicyCacheReadError]', error.message, { warehouseId }); + } + } + } + + // 2) 查库 + const policies = await this.fetchWarehousePoliciesFromDB(warehouseId); + + // 3) 写缓存 + if (app && typeof app.setCacheAsync === 'function') { + try { + await app.setCacheAsync(cacheKey, policies, ttl); + } catch (error) { + if (app.logger && typeof app.logger.warn === 'function') { + app.logger.warn('[ExpressPolicyCacheWriteError]', error.message, { warehouseId }); + } + } + } + + return policies; + } + + // -------------------- 策略匹配 -------------------- + + /** + * 检查 policy 中数组字段的任意值是否命中目标字符串(子串包含匹配)。 + * @param {Array|null} policyArray 策略中的数组字段 + * @param {string} target 目标字符串(如地址、店铺名称) + * @return {boolean} 是否命中 + */ + _matchAnyToken(policyArray, target) { + if (!Array.isArray(policyArray) || policyArray.length === 0) { + return true; // 未限定 = 不限制 + } + const normalizedTarget = String(target || '').trim(); + if (!normalizedTarget) { + return false; + } + return policyArray.some(token => { + const t = String(token || '').trim(); + return t && normalizedTarget.includes(t); + }); + } + + /** + * 检查两个数组是否有交集。 + * @param {Array<*>|null} policyArray 策略中的数组字段 + * @param {Array<*>|null} inputArray 传入的数组 + * @return {boolean} 是否有交集 + */ + _matchAnyIntersect(policyArray, inputArray) { + if (!Array.isArray(policyArray) || policyArray.length === 0) { + return true; // 未限定 = 不限制 + } + if (!Array.isArray(inputArray) || inputArray.length === 0) { + return false; + } + const policySet = new Set(policyArray.map(v => Number(v))); + return inputArray.some(v => policySet.has(Number(v))); + } + + /** + * 检查传入值是否在策略数组范围内。 + * @param {Array<*>|null} policyArray 策略中的数组字段 + * @param {number} value 传入值 + * @return {boolean} 是否命中 + */ + _matchValueInArray(policyArray, value) { + if (!Array.isArray(policyArray) || policyArray.length === 0) { + return true; // 未限定 = 不限制 + } + return policyArray.some(v => Number(v) === Number(value)); + } + + /** + * 按策略优先级漏斗筛选,返回命中策略的快递编码与重量段类型。 + * + * 筛选顺序(按 priority DESC,同 priority 按 updated_at DESC): + * 1. store_ids —— 传入货主ID是否在策略限定范围内(NULL=不限) + * 2. shop_name —— 自定义店铺名称子串匹配(任意一个命中即通过) + * 3. prohibited_type_id —— 违禁品类型ID数组交集(有交集即命中) + * 4. regions —— 地址包含任意限定地区即命中 + * 5. exclude_regions —— 地址包含任意排除地区则跳过该策略 + * 6. min_weight_g / max_weight_g —— 重量区间 + * + * @param {number} warehouseId 仓库 ID + * @param {Object} params 匹配参数 + * @param {number} [params.storeId] 货主 ID + * @param {string} [params.customShopName] 自定义店铺名称 + * @param {Array} [params.prohibitedTypeIds] 商品违禁品类型 ID 数组 + * @param {string} [params.address] 省市区详细地址(单个字符串) + * @param {number} [params.weight] 重量(克) + * @return {Promise<{expressCode: string|null, weightType: number|null}>} + */ + async matchPolicy(warehouseId, params = {}) { + const { + storeId, + customShopName, + prohibitedTypeIds, + address, + weight, + } = params; + + const policies = await this.getWarehousePolicies(warehouseId); + if (!Array.isArray(policies) || policies.length === 0) { + return { expressCode: null, weightType: null }; + } + + for (const policy of policies) { + // 1) store_ids — 未限定(NULL)视为不限;否则传入 storeId 必须在范围内 + if (!this._matchValueInArray(policy.store_ids, storeId)) { + continue; + } + + // 2) shop_name — 子串包含匹配 + if (!this._matchAnyToken(policy.shop_name, customShopName)) { + continue; + } + + // 3) prohibited_type_id — 数组交集 + if (!this._matchAnyIntersect(policy.prohibited_type_id, prohibitedTypeIds)) { + continue; + } + + // 4) regions — 地址包含任意限定地区 + if (!this._matchAnyToken(policy.regions, address)) { + continue; + } + + // 5) exclude_regions — 地址包含任意排除地区则跳过 + if (Array.isArray(policy.exclude_regions) && policy.exclude_regions.length > 0) { + const excluded = policy.exclude_regions.some(token => { + const t = String(token || '').trim(); + return t && String(address || '').includes(t); + }); + if (excluded) { + continue; + } + } + + // 6) 重量区间 + const weightNum = Number(weight); + if (Number.isFinite(weightNum)) { + if (policy.min_weight_g !== null && policy.min_weight_g !== undefined) { + if (weightNum < Number(policy.min_weight_g)) { + continue; + } + } + if (policy.max_weight_g !== null && policy.max_weight_g !== undefined) { + if (weightNum > Number(policy.max_weight_g)) { + continue; + } + } + } + + // 全部通过 → 命中 + return { + expressCode: policy.express_code || null, + weightType: policy.weight_type !== undefined ? policy.weight_type : 0, + policyName: policy.custom_name || null, + policyId: policy.id || null, + }; + } + + // 无命中 + return { expressCode: null, weightType: null }; + } +} + +module.exports = ExpressPolicyService; diff --git a/app/service/systems/store_express_binding_policy.js b/app/service/systems/store_express_binding_policy.js new file mode 100644 index 0000000..49e5104 --- /dev/null +++ b/app/service/systems/store_express_binding_policy.js @@ -0,0 +1,696 @@ +'use strict'; + +const Service = require('egg').Service; + +/** + * 订单自定义店铺-快递绑定策略业务服务。 + */ +class StoreExpressBindingPolicyService extends Service { + /** + * 获取当前仓库 ID。 + * @return {number} 仓库 ID + */ + getCurrentWarehouseId() { + const warehouseId = Number(this.ctx.user && this.ctx.user.store_id); + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw this.createError('未识别到当前仓库', 400); + } + return warehouseId; + } + + /** + * 创建业务错误。 + * @param {string} message 错误信息 + * @param {number} [code=500] 错误码 + * @return {Error} 业务错误对象 + */ + createError(message, code = 500) { + const error = new Error(message); + error.code = code; + return error; + } + + /** + * 规范化字符串参数。 + * @param {*} value 原始值 + * @param {string} fieldName 字段名 + * @param {Object} [options={}] 选项 + * @return {string|null} 规范化结果 + */ + normalizeText(value, fieldName, options = {}) { + const { required = false, maxLength = 255 } = options; + if (value === undefined || value === null) { + if (required) throw this.createError(`${fieldName} 不能为空`, 400); + return null; + } + const normalized = String(value).trim(); + if (!normalized) { + if (required) throw this.createError(`${fieldName} 不能为空`, 400); + return null; + } + if (normalized.length > maxLength) { + throw this.createError(`${fieldName} 长度不能超过 ${maxLength}`, 400); + } + return normalized; + } + + /** + * 规范化整数参数。 + * @param {*} value 原始值 + * @param {string} fieldName 字段名 + * @param {Object} [options={}] 选项 + * @return {number|null} 规范化结果 + */ + normalizeInteger(value, fieldName, options = {}) { + const { required = false, min = null } = options; + if (value === undefined || value === null || value === '') { + if (required) throw this.createError(`${fieldName} 不能为空`, 400); + return null; + } + const normalized = Number(value); + if (!Number.isInteger(normalized)) { + throw this.createError(`${fieldName} 参数不合法`, 400); + } + if (min !== null && normalized < min) { + throw this.createError(`${fieldName} 参数不合法`, 400); + } + return normalized; + } + + /** + * 规范化重量段类型。 + * @param {*} value 原始值 + * @return {number|null} NULL 或 0/1/2/3 + */ + normalizeWeightType(value) { + if (value === undefined || value === null || value === '') return 0; + const v = Number(value); + if (![ 0, 1, 2, 3 ].includes(v)) throw this.createError('weight_type 不合法,仅支持 0/1/2/3(常规/轻货/重货/冷链)', 400); + return v; + } + + /** + * 校验快递编码是否存在。 + * @param {string} expressCode 快递编码 + * @return {Promise} 标准化快递编码 + */ + normalizeJsonArray(value, fieldName) { + if (value === undefined || value === null || value === '') return null; + if (Array.isArray(value)) return value.length > 0 ? value : null; + if (typeof value === 'string') { + try { const parsed = JSON.parse(value); if (Array.isArray(parsed)) return parsed.length > 0 ? parsed : null; } catch (e) {} + } + throw this.createError(fieldName + ' 必须是字符串数组', 400); + } + + async ensureExpressExists(expressCode) { + const { ctx } = this; + const normalizedCode = this.normalizeText(expressCode, 'express_code', { + required: true, + maxLength: 50, + }); + + // 使用合并后的快递列表(含系统快递 + 仓库自定义映射) + const expressList = await ctx.service.systems.express.getExpressList(); + const found = Array.isArray(expressList) + ? expressList.find(item => item && String(item.code || item.value || '').trim() === normalizedCode) + : null; + + if (!found) { + throw this.createError(`快递编码 "${normalizedCode}" 不存在`, 400); + } + + return normalizedCode; + } + + /** + * 获取列表字段过滤映射。 + * @return {Object} specialFieldMap + */ + getListWhereSpecialFieldMap() { + return { + id: { field: 'id' }, + custom_name: { field: 'custom_name' }, + shop_name: { field: 'shop_name' }, + store_ids: { field: 'store_ids' }, + express_code: { field: 'express_code' }, + priority: { field: 'priority' }, + is_enabled: { field: 'is_enabled' }, + prohibited_type_id: { field: 'prohibited_type_id' }, + regions: { field: 'regions' }, + exclude_regions: { field: 'exclude_regions' }, + min_weight_g: { field: 'min_weight_g' }, + max_weight_g: { field: 'max_weight_g' }, + weight_type: { field: 'weight_type' }, + creator_id: { field: 'creator_id' }, + quickWhere: { bucket: 'quick' }, + }; + } + + /** + * 构建列表查询条件。 + * @param {Object} [data={}] 请求参数 + * @return {Object} where 条件 + */ + buildListWhere(data = {}) { + const { app, ctx } = this; + const { Op } = app.Sequelize; + const parsedResult = ctx.whereParsed || { + dynamicConditions: [], + rawConditionsByField: {}, + }; + const whereAndConditions = [ + { warehouse_id: this.getCurrentWarehouseId() }, + { deleted_at: null }, + ]; + + const dynamicConditions = Array.isArray(parsedResult.dynamicConditions) + ? parsedResult.dynamicConditions + : []; + + if (dynamicConditions.length > 0) { + whereAndConditions.push({ [Op.and]: dynamicConditions }); + } + + // 快速搜索:按 custom_name 模糊匹配 + const quickWhereCondition = parsedResult.rawConditionsByField + ? parsedResult.rawConditionsByField.quickWhere + : null; + const quickWhereValue = quickWhereCondition && typeof quickWhereCondition === 'object' + ? quickWhereCondition.value + : null; + const keyword = String(quickWhereValue || '').trim(); + + if (keyword) { + whereAndConditions.push({ + [Op.or]: [ + { custom_name: { [Op.like]: `%${keyword}%` } }, + { express_code: { [Op.like]: `%${keyword}%` } }, + ], + }); + } + + return { [Op.and]: whereAndConditions }; + } + + /** + * 规范化分页参数。 + * @param {Object} [data={}] 请求参数 + * @return {{ page: number, pageSize: number, offset: number }} + */ + normalizePagination(data = {}) { + const pagination = data && typeof data.pagination === 'object' ? data.pagination : {}; + const pageSource = pagination.page !== undefined + ? pagination.page + : (data.page !== undefined ? data.page : data.currentPage); + const pageSizeSource = pagination.pageSize !== undefined + ? pagination.pageSize + : (pagination.page_size !== undefined ? pagination.page_size : (data.pageSize !== undefined ? data.pageSize : data.page_size)); + + const page = Math.max(Number.parseInt(pageSource, 10) || 1, 1); + const pageSize = Math.min(Math.max(Number.parseInt(pageSizeSource, 10) || 20, 1), 200); + + return { page, pageSize, offset: (page - 1) * pageSize }; + } + + /** + * 规范化策略记录输出。 + * @param {Object} row 策略记录 + * @return {Object} 输出结构 + */ + formatPolicyRow(row) { + return { + id: row.id, + warehouse_id: row.warehouse_id, + custom_name: row.custom_name, + shop_name: row.shop_name, + store_ids: row.store_ids, + store_names: row._store_names || null, + express_code: row.express_code, + express_name: row._express_name || row.express_code || null, + priority: row.priority, + is_enabled: row.is_enabled, + prohibited_type_id: row.prohibited_type_id, + prohibited_type_names: row._prohibited_type_names || null, + regions: row.regions, + exclude_regions: row.exclude_regions, + min_weight_g: row.min_weight_g, + max_weight_g: row.max_weight_g, + weight_type: row.weight_type, + remark: row.remark, + creator_id: row.creator_id, + created_at: row.created_at, + updated_at: row.updated_at, + }; + } + + /** + * 查询策略分页列表。 + * @param {Object} [data={}] 请求参数 + * @return {Promise} 列表结果 + */ + async list(data = {}) { + const { ctx } = this; + const { page, pageSize, offset } = this.normalizePagination(data); + const where = this.buildListWhere(data); + + const result = await ctx.model.StoreExpressBindingPolicy.findAndCountAll({ + where, + order: [[ 'priority', 'DESC' ], [ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]], + offset, + limit: pageSize, + }); + + const rows = Array.isArray(result && result.rows) ? result.rows : []; + const plainRows = rows.map(row => (row && typeof row.get === 'function' ? row.get({ plain: true }) : row)); + + // 批量解析货主名称 & 违禁品名称 + const allStoreIds = new Set(); + const allProhibitedIds = new Set(); + for (const row of plainRows) { + if (Array.isArray(row.store_ids)) { + row.store_ids.forEach(id => allStoreIds.add(id)); + } + if (Array.isArray(row.prohibited_type_id)) { + row.prohibited_type_id.forEach(id => allProhibitedIds.add(id)); + } + } + + const storeNameMap = new Map(); + if (allStoreIds.size > 0) { + const stores = await ctx.model.Store.findAll({ + where: { id: [ ...allStoreIds ] }, + attributes: [ 'id', 'company_name' ], + }); + for (const s of stores) { + storeNameMap.set(s.id, s.company_name); + } + } + + const prohibitedNameMap = new Map(); + if (allProhibitedIds.size > 0) { + const types = await ctx.model.ProhibitedType.findAll({ + where: { id: [ ...allProhibitedIds ] }, + attributes: [ 'id', 'type_name' ], + }); + for (const t of types) { + prohibitedNameMap.set(t.id, t.type_name); + } + } + + // 批量解析快递名称(含系统快递 + 自定义映射) + const allExpressCodes = new Set(); + for (const row of plainRows) { + if (row.express_code) allExpressCodes.add(row.express_code); + } + const expressNameMap = new Map(); + if (allExpressCodes.size > 0) { + try { + const expressList = await ctx.service.systems.express.getExpressList(); + for (const item of (Array.isArray(expressList) ? expressList : [])) { + const code = String(item && (item.code || item.value) || '').trim(); + if (code && allExpressCodes.has(code)) { + expressNameMap.set(code, String(item.name || item.label || code).trim()); + } + } + } catch (_) { /* 快递列表查询失败不影响列表 */ } + } + + // 将名称数组挂到临时属性上 + for (const row of plainRows) { + if (Array.isArray(row.store_ids)) { + row._store_names = row.store_ids.map(id => storeNameMap.get(id) || String(id)); + } + if (Array.isArray(row.prohibited_type_id)) { + row._prohibited_type_names = row.prohibited_type_id.map(id => prohibitedNameMap.get(id) || String(id)); + } + if (row.express_code) { + row._express_name = expressNameMap.get(row.express_code) || row.express_code; + } + } + + const list = plainRows.map(row => this.formatPolicyRow(row)); + const total = Number(result && result.count ? result.count : 0); + + return { + list, + pagination: { + page, + pageSize, + total, + totalPages: pageSize > 0 ? Math.ceil(total / pageSize) : 0, + hasNext: page * pageSize < total, + hasPrevious: page > 1, + }, + }; + } + + /** + * 校验自定义名称在同仓库下唯一(排除自身)。 + * @param {Object} payload 入参 + * @return {Promise} + */ + async ensureCustomNameUnique(payload) { + const { ctx } = this; + const { Op } = this.app.Sequelize; + const { warehouseId, customName, excludeId = null } = payload; + + const where = { + warehouse_id: warehouseId, + custom_name: customName, + deleted_at: null, + }; + + if (excludeId !== null) { + where.id = { [Op.ne]: excludeId }; + } + + const existed = await ctx.model.StoreExpressBindingPolicy.findOne({ + where, + attributes: [ 'id' ], + }); + + if (existed) { + throw this.createError('同仓库下策略名称已存在', 409); + } + } + + /** + * 新增策略。 + * @param {Object} [data={}] 请求参数 + * @return {Promise} 新增结果 + */ + async add(data = {}) { + const { ctx } = this; + const warehouseId = this.getCurrentWarehouseId(); + + const customName = this.normalizeText( + data.custom_name !== undefined ? data.custom_name : data.customName, + 'custom_name', + { required: true, maxLength: 100 } + ); + + const expressCode = await this.ensureExpressExists( + data.express_code !== undefined ? data.express_code : data.expressCode + ); + + const priority = this.normalizeInteger( + data.priority !== undefined ? data.priority : 0, + 'priority', + { required: false } + ); + + const isEnabled = data.is_enabled !== undefined + ? Number(data.is_enabled) + : (data.isEnabled !== undefined ? Number(data.isEnabled) : 1); + if (![ 0, 1 ].includes(isEnabled)) { + throw this.createError('is_enabled 参数不合法,仅支持 0 或 1', 400); + } + + const regions = this.normalizeJsonArray( + data.regions !== undefined ? data.regions : null, + 'regions' + ); + + const shopName = this.normalizeJsonArray( + data.shop_name !== undefined ? data.shop_name : data.shopName, + 'shop_name' + ); + + const storeIds = this.normalizeJsonArray( + data.store_ids !== undefined ? data.store_ids : data.storeIds, + 'store_ids' + ); + + const excludeRegions = this.normalizeJsonArray( + data.exclude_regions !== undefined ? data.exclude_regions : data.excludeRegions, + 'exclude_regions' + ); + + const minWeightG = this.normalizeInteger( + data.min_weight_g !== undefined ? data.min_weight_g : data.minWeightG, + 'min_weight_g' + ); + + const maxWeightG = this.normalizeInteger( + data.max_weight_g !== undefined ? data.max_weight_g : data.maxWeightG, + 'max_weight_g' + ); + + const weightType = this.normalizeWeightType( + data.weight_type !== undefined ? data.weight_type : data.weightType + ); + + const prohibitedTypeIds = this.normalizeJsonArray( + data.prohibited_type_id !== undefined ? data.prohibited_type_id : data.prohibitedTypeId, + 'prohibited_type_id' + ); + + const remark = this.normalizeText( + data.remark !== undefined ? data.remark : null, + 'remark', + { maxLength: 500 } + ); + + const creatorId = this.normalizeInteger( + data.creator_id !== undefined ? data.creator_id : data.creatorId, + 'creator_id' + ); + + // 校验名称唯一性 + await this.ensureCustomNameUnique({ warehouseId, customName }); + + const created = await ctx.model.StoreExpressBindingPolicy.create({ + warehouse_id: warehouseId, + custom_name: customName, + express_code: expressCode, + priority: priority ?? 0, + is_enabled: isEnabled, + regions, + shop_name: shopName, + store_ids: storeIds, + exclude_regions: excludeRegions, + min_weight_g: minWeightG, + max_weight_g: maxWeightG, + weight_type: weightType, + prohibited_type_id: prohibitedTypeIds, + remark, + creator_id: creatorId, + }); + + // 清理当前仓库策略缓存 + try { + await ctx.service.systems.expressPolicy.clearWarehousePolicyCache(warehouseId); + } catch (_) { + // 缓存清理失败不影响主流程 + } + + const plainRow = created && typeof created.get === 'function' + ? created.get({ plain: true }) + : created; + + return { id: plainRow.id }; + } + + /** + * 读取策略并校验仓库归属。 + * @param {*} policyId 策略 ID + * @return {Promise} 策略模型实例 + */ + async findPolicyById(policyId) { + const { ctx } = this; + const id = this.normalizeInteger(policyId, 'id', { required: true, min: 1 }); + + const policy = await ctx.model.StoreExpressBindingPolicy.findOne({ + where: { + id, + warehouse_id: this.getCurrentWarehouseId(), + deleted_at: null, + }, + }); + + if (!policy) { + throw this.createError('策略不存在', 404); + } + + return policy; + } + + /** + * 编辑策略。 + * @param {Object} [data={}] 请求参数 + * @return {Promise} 编辑结果 + */ + async edit(data = {}) { + const id = data.id !== undefined ? data.id : data.policy_id; + + const policy = await this.findPolicyById(id); + const warehouseId = this.getCurrentWarehouseId(); + const updateFields = {}; + + // custom_name + const customName = data.custom_name !== undefined + ? data.custom_name + : (data.customName !== undefined ? data.customName : undefined); + if (customName !== undefined) { + const normalized = this.normalizeText(customName, 'custom_name', { maxLength: 100 }); + if (normalized && normalized !== policy.custom_name) { + await this.ensureCustomNameUnique({ + warehouseId, + customName: normalized, + excludeId: Number(policy.id), + }); + } + updateFields.custom_name = normalized; + } + + // express_code + const expressCode = data.express_code !== undefined + ? data.express_code + : (data.expressCode !== undefined ? data.expressCode : undefined); + if (expressCode !== undefined) { + updateFields.express_code = await this.ensureExpressExists(expressCode); + } + + // priority + const priority = data.priority !== undefined ? data.priority : undefined; + if (priority !== undefined) { + updateFields.priority = this.normalizeInteger(priority, 'priority'); + } + + // is_enabled + const isEnabled = data.is_enabled !== undefined + ? data.is_enabled + : (data.isEnabled !== undefined ? data.isEnabled : undefined); + if (isEnabled !== undefined) { + const val = Number(isEnabled); + if (![ 0, 1 ].includes(val)) { + throw this.createError('is_enabled 参数不合法,仅支持 0 或 1', 400); + } + updateFields.is_enabled = val; + } + + // regions + const regions = data.regions !== undefined ? data.regions : undefined; + if (regions !== undefined) { + updateFields.regions = this.normalizeJsonArray(regions, 'regions'); + } + + // shop_name + const shopName = data.shop_name !== undefined + ? data.shop_name + : (data.shopName !== undefined ? data.shopName : undefined); + if (shopName !== undefined) { + updateFields.shop_name = this.normalizeJsonArray(shopName, 'shop_name'); + } + + // store_ids + const storeIds = data.store_ids !== undefined + ? data.store_ids + : (data.storeIds !== undefined ? data.storeIds : undefined); + if (storeIds !== undefined) { + updateFields.store_ids = this.normalizeJsonArray(storeIds, 'store_ids'); + } + + // exclude_regions + const excludeRegions = data.exclude_regions !== undefined + ? data.exclude_regions + : (data.excludeRegions !== undefined ? data.excludeRegions : undefined); + if (excludeRegions !== undefined) { + updateFields.exclude_regions = this.normalizeJsonArray(excludeRegions, 'exclude_regions'); + } + + // min_weight_g + const minWeightG = data.min_weight_g !== undefined + ? data.min_weight_g + : (data.minWeightG !== undefined ? data.minWeightG : undefined); + if (minWeightG !== undefined) { + updateFields.min_weight_g = this.normalizeInteger(minWeightG, 'min_weight_g'); + } + + // max_weight_g + const maxWeightG = data.max_weight_g !== undefined + ? data.max_weight_g + : (data.maxWeightG !== undefined ? data.maxWeightG : undefined); + if (maxWeightG !== undefined) { + updateFields.max_weight_g = this.normalizeInteger(maxWeightG, 'max_weight_g'); + } + + // weight_type + const weightType = data.weight_type !== undefined + ? data.weight_type + : (data.weightType !== undefined ? data.weightType : undefined); + if (weightType !== undefined) { + updateFields.weight_type = this.normalizeWeightType(weightType); + } + + // prohibited_type_id + const prohibitedTypeIds = data.prohibited_type_id !== undefined + ? data.prohibited_type_id + : (data.prohibitedTypeId !== undefined ? data.prohibitedTypeId : undefined); + if (prohibitedTypeIds !== undefined) { + updateFields.prohibited_type_id = this.normalizeJsonArray(prohibitedTypeIds, 'prohibited_type_id'); + } + + // remark + const remark = data.remark !== undefined ? data.remark : undefined; + if (remark !== undefined) { + updateFields.remark = this.normalizeText(remark, 'remark', { maxLength: 500 }); + } + + // creator_id + const creatorId = data.creator_id !== undefined + ? data.creator_id + : (data.creatorId !== undefined ? data.creatorId : undefined); + if (creatorId !== undefined) { + updateFields.creator_id = this.normalizeInteger(creatorId, 'creator_id'); + } + + if (Object.keys(updateFields).length === 0) { + throw this.createError('没有需要更新的字段', 400); + } + + await policy.update(updateFields); + + // 清理当前仓库策略缓存 + try { + await this.ctx.service.systems.expressPolicy.clearWarehousePolicyCache(warehouseId); + } catch (_) { + // 缓存清理失败不影响主流程 + } + + const updated = policy && typeof policy.get === 'function' + ? policy.get({ plain: true }) + : policy; + + return { id: updated.id }; + } + + /** + * 软删除策略。 + * @param {Object} [data={}] 请求参数 + * @return {Promise} 删除结果 + */ + async del(data = {}) { + const id = data.id !== undefined ? data.id : data.policy_id; + + const policy = await this.findPolicyById(id); + const now = new Date(); + + await policy.update({ deleted_at: now, is_enabled: 0 }); + + // 清理当前仓库策略缓存 + try { + const warehouseId = Number(policy.warehouse_id); + if (warehouseId > 0) { + await this.ctx.service.systems.expressPolicy.clearWarehousePolicyCache(warehouseId); + } + } catch (_) { + // 缓存清理失败不影响主流程 + } + + return { id: Number(policy.id) }; + } +} + +module.exports = StoreExpressBindingPolicyService; diff --git a/database/designs/store-express-binding-policy-design.md b/database/designs/store-express-binding-policy-design.md new file mode 100644 index 0000000..4c48653 --- /dev/null +++ b/database/designs/store-express-binding-policy-design.md @@ -0,0 +1,138 @@ +# 订单自定义店铺-快递绑定策略 设计方案 + +> **状态**: 📋 设计中 +> **设计日期**: 2026-08-03 +> **模块**: 订单快递分配策略 +> **表**: 1 张 — `wms_store_express_binding_policy` + +--- + +## 一、背景与目的 + +在 WMS 系统中,订单的快递分配目前依赖以下路径: + +1. `store_warehouse.policy_config.auto_allocate_express` 控制是否自动分配 +2. `express_interface` 表提供「仓库 + 店铺 + 平台 + 快递」的接口配置映射 +3. 货主 `subject_config.default_express_code` 提供默认快递 + +**痛点**:无法根据业务场景灵活配置"某个仓库下,某店铺(或某货主)强制使用/优先使用某快递"的策略。例如: + +- 仓库 A 的拼多多店铺「旗舰店」必须走中通(ZTO),而「奥莱店」走圆通(YTO) +- 同一店铺在不同条件下(如收件省份、商品类型)使用不同快递 +- 多人同时管理时需要记录创建人、创建时间,方便追溯 + +**解决方案**:新增 `wms_store_express_binding_policy` 表,支持自定义店铺-快递绑定策略,按优先级匹配。 + +--- + +## 二、数据库表 + +### `wms_store_express_binding_policy` + +| 字段 | 类型 | 必填 | 默认值 | 说明 | +|------|------|------|--------|------| +| `id` | `BIGINT UNSIGNED` | ✅ | AUTO | 主键 | +| `warehouse_id` | `BIGINT UNSIGNED` | ✅ | — | 仓库ID,策略所属仓库 | +| `custom_name` | `VARCHAR(100)` | ✅ | — | 自定义店铺标签名称(自由文本,与系统店铺无关) | +| `express_code` | `VARCHAR(50)` | ✅ | — | 绑定的快递编码(关联 wms_express.code) | +| `priority` | `INT(11)` | ✅ | 0 | 优先级,数值越大越优先匹配 | +| `is_enabled` | `TINYINT(1)` | ✅ | 1 | 是否启用:0=停用,1=启用 | +| `match_condition` | `JSON` | — | NULL | 附加匹配条件(见下方说明) | +| `remark` | `VARCHAR(500)` | — | NULL | 备注说明 | +| `creator_id` | `BIGINT UNSIGNED` | — | NULL | 创建人账户ID(关联 accounts 表) | +| `created_at` | `DATETIME` | ✅ | CURRENT_TIMESTAMP | 创建时间 | +| `updated_at` | `DATETIME` | ✅ | CURRENT_TIMESTAMP ON UPDATE | 更新时间 | +| `deleted_at` | `DATETIME` | — | NULL | 软删除时间 | + +### 索引设计 + +| 索引名 | 字段 | 说明 | +|--------|------|------| +| `PRIMARY` | `id` | 主键 | +| `idx_warehouse_enabled` | `warehouse_id`, `is_enabled`, `deleted_at` | 按仓库查询启用策略 | +| `idx_warehouse_express` | `warehouse_id`, `express_code`, `deleted_at` | 按仓库+快递反查绑定 | + +### `match_condition` 字段说明(JSON,可选) + +用于扩展匹配条件,可进一步按以下维度过滤: + +```jsonc +{ + "platform_codes": ["PDD", "TB"], // 限定平台编码 + "provinces": ["广东省", "浙江省"], // 限定收件省份 + "cities": ["广州市", "杭州市"], // 限定收件城市 + "item_codes": ["SKU001", "SKU002"], // 限定商品编码 + "min_weight_g": 0, // 最小重量(g),NULL=不限制 + "max_weight_g": 5000, // 最大重量(g),NULL=不限制 + "min_amount": 0, // 最小金额(元),NULL=不限制 + "max_amount": 1000 // 最大金额(元),NULL=不限制 +} +``` + +## 三、匹配逻辑(伪代码) + +``` +1. 查询 wms_store_express_binding_policy + WHERE warehouse_id = :warehouseId + AND is_enabled = 1 + AND deleted_at IS NULL + ORDER BY priority DESC, id ASC + +2. 遍历结果集,对每条策略: + a. 若 match_condition 为空 → 命中,返回 express_code + b. 若 match_condition 不为空 → 逐条件判断: + - platform_codes:订单平台编码是否在列表中 + - provinces / cities:收件地址省/市是否在列表中 + - item_codes:订单商品编码是否命中 + - min/max_weight_g:订单总重量是否在范围内 + - min/max_amount:订单总金额是否在范围内 + c. 所有条件 AND 全部满足 → 命中,返回 express_code + +3. 若未命中任何策略 → 回退到原有默认逻辑 + (express_interface 匹配 → subject_config.default_express_code) +``` + +## 四、与现有表的关系 + +``` +wms_store_express_binding_policy + ├─ warehouse_id → stores.id(逻辑关联,不做物理外键) + ├─ express_code → wms_express.code(逻辑关联) + └─ creator_id → accounts.id(逻辑关联) +``` + +## 五、典型使用场景 + +### 场景1:按自定义店铺标签绑定快递 + +```sql +INSERT INTO wms_store_express_binding_policy + (warehouse_id, custom_name, express_code, priority, creator_id) +VALUES + (1000000, '旗舰店-中通', 'ZTO', 10, 10001); +``` + +### 场景2:按自定义店铺标签+省份绑定快递(偏远地区走邮政) + +```sql +INSERT INTO wms_store_express_binding_policy + (warehouse_id, custom_name, express_code, priority, match_condition, creator_id) +VALUES + (1000000, '偏远地区邮政', 'EMS', 20, + '{"provinces":["新疆维吾尔自治区","西藏自治区","青海省"]}', 10001); +``` + +### 场景3:全局默认快递 + +```sql +INSERT INTO wms_store_express_binding_policy + (warehouse_id, custom_name, express_code, priority, creator_id) +VALUES + (1000000, '全局顺丰', 'SF', 5, 10001); +``` + +## 六、后续扩展 + +- 策略命中日志:记录每次快递分配命中了哪条策略,便于分析调整 +- 策略生效时间段:增加 `start_time` / `end_time` 支持定时策略(如大促期间切换快递) +- 策略复制:支持跨仓库复制策略配置 diff --git a/database/migrations/20260803150000-create-wms-store-express-binding-policy.js b/database/migrations/20260803150000-create-wms-store-express-binding-policy.js new file mode 100644 index 0000000..0fe917b --- /dev/null +++ b/database/migrations/20260803150000-create-wms-store-express-binding-policy.js @@ -0,0 +1,129 @@ +'use strict'; + +const TABLE_NAME = 'wms_store_express_binding_policy'; + +module.exports = { + /** + * 创建订单自定义店铺-快递绑定策略表。 + * @param {Object} queryInterface Sequelize QueryInterface 实例。 + * @param {Object} Sequelize Sequelize 类。 + * @return {Promise} 迁移执行结果。 + */ + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME); + if (exists) return; + + await queryInterface.createTable(TABLE_NAME, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID,策略所属仓库', + }, + custom_name: { + type: Sequelize.STRING(100), + allowNull: false, + comment: '自定义策略名称,便于人工识别', + }, + store_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '货主ID(stores.id),NULL=适用所有货主', + }, + shop_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '店铺ID(shops.id),NULL=适用所有店铺', + }, + express_code: { + type: Sequelize.STRING(50), + allowNull: false, + comment: '绑定的快递编码(wms_express.code)', + }, + priority: { + type: Sequelize.INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '优先级,数值越大越优先匹配', + }, + is_enabled: { + type: Sequelize.TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '是否启用:0=停用,1=启用', + }, + match_condition: { + type: Sequelize.JSON, + allowNull: true, + comment: '附加匹配条件(JSON):platform_codes/provinces/cities/item_codes/min_weight_g/max_weight_g/min_amount/max_amount', + }, + remark: { + type: Sequelize.STRING(500), + allowNull: true, + comment: '备注说明', + }, + creator_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '创建人账户ID(accounts.id)', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + comment: '订单自定义店铺-快递绑定策略表', + engine: 'InnoDB', + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + }); + + // 索引:按仓库查询启用策略 + await queryInterface.addIndex(TABLE_NAME, { + name: 'idx_warehouse_enabled', + fields: [ 'warehouse_id', 'is_enabled', 'deleted_at' ], + }); + + // 索引:按仓库+货主+店铺精确匹配 + await queryInterface.addIndex(TABLE_NAME, { + name: 'idx_warehouse_store_shop', + fields: [ 'warehouse_id', 'store_id', 'shop_id', 'deleted_at' ], + }); + + // 索引:按仓库+快递反查绑定店铺 + await queryInterface.addIndex(TABLE_NAME, { + name: 'idx_warehouse_express', + fields: [ 'warehouse_id', 'express_code', 'deleted_at' ], + }); + }, + + /** + * 回滚:删除表。 + * @param {Object} queryInterface Sequelize QueryInterface 实例。 + * @param {Object} Sequelize Sequelize 类。 + * @return {Promise} 迁移执行结果。 + */ + down: async (queryInterface, Sequelize) => { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260803160000-remove-store-shop-id-from-binding-policy.js b/database/migrations/20260803160000-remove-store-shop-id-from-binding-policy.js new file mode 100644 index 0000000..dc79c57 --- /dev/null +++ b/database/migrations/20260803160000-remove-store-shop-id-from-binding-policy.js @@ -0,0 +1,40 @@ +'use strict'; + +const TABLE_NAME = 'wms_store_express_binding_policy'; + +module.exports = { + /** + * 移除冗余字段 store_id / shop_id 及其索引。 + * @param {Object} queryInterface Sequelize QueryInterface 实例。 + * @param {Object} Sequelize Sequelize 类。 + * @return {Promise} 迁移执行结果。 + */ + up: async (queryInterface, Sequelize) => { + await queryInterface.removeIndex(TABLE_NAME, 'idx_warehouse_store_shop'); + await queryInterface.removeColumn(TABLE_NAME, 'store_id'); + await queryInterface.removeColumn(TABLE_NAME, 'shop_id'); + }, + + /** + * 回滚:恢复 store_id / shop_id 列及索引。 + * @param {Object} queryInterface Sequelize QueryInterface 实例。 + * @param {Object} Sequelize Sequelize 类。 + * @return {Promise} 迁移执行结果。 + */ + down: async (queryInterface, Sequelize) => { + await queryInterface.addColumn(TABLE_NAME, 'store_id', { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '货主ID(stores.id),NULL=适用所有货主', + }); + await queryInterface.addColumn(TABLE_NAME, 'shop_id', { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '店铺ID(shops.id),NULL=适用所有店铺', + }); + await queryInterface.addIndex(TABLE_NAME, { + name: 'idx_warehouse_store_shop', + fields: [ 'warehouse_id', 'store_id', 'shop_id', 'deleted_at' ], + }); + }, +}; diff --git a/database/migrations/20260803163000-add-prohibited-type-id-to-binding-policy.js b/database/migrations/20260803163000-add-prohibited-type-id-to-binding-policy.js new file mode 100644 index 0000000..dd485a9 --- /dev/null +++ b/database/migrations/20260803163000-add-prohibited-type-id-to-binding-policy.js @@ -0,0 +1,18 @@ +'use strict'; + +const TABLE_NAME = 'wms_store_express_binding_policy'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + await queryInterface.addColumn(TABLE_NAME, 'prohibited_type_id', { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: true, + comment: '违禁品类型ID(关联 wms_prohibited_type.id),NULL=不限制违禁品', + after: 'match_condition', + }); + }, + + down: async (queryInterface, Sequelize) => { + await queryInterface.removeColumn(TABLE_NAME, 'prohibited_type_id'); + }, +}; diff --git a/database/migrations/20260803164500-replace-match-condition-with-provinces-cities.js b/database/migrations/20260803164500-replace-match-condition-with-provinces-cities.js new file mode 100644 index 0000000..9453a0a --- /dev/null +++ b/database/migrations/20260803164500-replace-match-condition-with-provinces-cities.js @@ -0,0 +1,31 @@ +'use strict'; + +const TABLE_NAME = 'wms_store_express_binding_policy'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + await queryInterface.removeColumn(TABLE_NAME, 'match_condition'); + await queryInterface.addColumn(TABLE_NAME, 'provinces', { + type: Sequelize.TEXT, + allowNull: true, + comment: '限定省份,逗号分隔,如"广东省,浙江省",NULL=不限制', + after: 'is_enabled', + }); + await queryInterface.addColumn(TABLE_NAME, 'cities', { + type: Sequelize.TEXT, + allowNull: true, + comment: '限定城市,逗号分隔,如"广州市,杭州市",NULL=不限制', + after: 'provinces', + }); + }, + + down: async (queryInterface, Sequelize) => { + await queryInterface.removeColumn(TABLE_NAME, 'cities'); + await queryInterface.removeColumn(TABLE_NAME, 'provinces'); + await queryInterface.addColumn(TABLE_NAME, 'match_condition', { + type: Sequelize.JSON, + allowNull: true, + comment: '附加匹配条件(JSON)', + }); + }, +}; diff --git a/database/migrations/20260803170000-add-weight-range-to-binding-policy.js b/database/migrations/20260803170000-add-weight-range-to-binding-policy.js new file mode 100644 index 0000000..5c2073d --- /dev/null +++ b/database/migrations/20260803170000-add-weight-range-to-binding-policy.js @@ -0,0 +1,25 @@ +'use strict'; + +const TABLE_NAME = 'wms_store_express_binding_policy'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + await queryInterface.addColumn(TABLE_NAME, 'min_weight_g', { + type: Sequelize.INTEGER, + allowNull: true, + comment: '最小重量(克),NULL=不限制', + after: 'cities', + }); + await queryInterface.addColumn(TABLE_NAME, 'max_weight_g', { + type: Sequelize.INTEGER, + allowNull: true, + comment: '最大重量(克),NULL=不限制', + after: 'min_weight_g', + }); + }, + + down: async (queryInterface, Sequelize) => { + await queryInterface.removeColumn(TABLE_NAME, 'max_weight_g'); + await queryInterface.removeColumn(TABLE_NAME, 'min_weight_g'); + }, +}; diff --git a/database/migrations/20260803170500-add-weight-type-to-binding-policy.js b/database/migrations/20260803170500-add-weight-type-to-binding-policy.js new file mode 100644 index 0000000..4dd20d5 --- /dev/null +++ b/database/migrations/20260803170500-add-weight-type-to-binding-policy.js @@ -0,0 +1,18 @@ +'use strict'; + +const TABLE_NAME = 'wms_store_express_binding_policy'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + await queryInterface.addColumn(TABLE_NAME, 'weight_type', { + type: Sequelize.TINYINT(1), + allowNull: true, + comment: '重量段类型:NULL=不限制/0=常规/1=轻货/2=重货/3=冷链', + after: 'max_weight_g', + }); + }, + + down: async (queryInterface, Sequelize) => { + await queryInterface.removeColumn(TABLE_NAME, 'weight_type'); + }, +}; diff --git a/database/migrations/20260803171000-make-weight-type-required.js b/database/migrations/20260803171000-make-weight-type-required.js new file mode 100644 index 0000000..7e6f6e7 --- /dev/null +++ b/database/migrations/20260803171000-make-weight-type-required.js @@ -0,0 +1,23 @@ +'use strict'; + +const TABLE_NAME = 'wms_store_express_binding_policy'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + await queryInterface.changeColumn(TABLE_NAME, 'weight_type', { + type: Sequelize.TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '重量段类型:0=常规/1=轻货/2=重货/3=冷链', + }); + }, + + down: async (queryInterface, Sequelize) => { + await queryInterface.changeColumn(TABLE_NAME, 'weight_type', { + type: Sequelize.TINYINT(1), + allowNull: true, + defaultValue: null, + comment: '重量段类型:NULL=不限制/0=常规/1=轻货/2=重货/3=冷链', + }); + }, +}; diff --git a/database/migrations/20260804090000-merge-provinces-cities-to-regions.js b/database/migrations/20260804090000-merge-provinces-cities-to-regions.js new file mode 100644 index 0000000..b7d5945 --- /dev/null +++ b/database/migrations/20260804090000-merge-provinces-cities-to-regions.js @@ -0,0 +1,30 @@ +'use strict'; + +const TABLE_NAME = 'wms_store_express_binding_policy'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + await queryInterface.removeColumn(TABLE_NAME, 'cities'); + await queryInterface.removeColumn(TABLE_NAME, 'provinces'); + await queryInterface.addColumn(TABLE_NAME, 'regions', { + type: Sequelize.TEXT, + allowNull: true, + comment: '限定地区,逗号分隔,如"广东省,广州市,深圳市",NULL=不限制', + after: 'is_enabled', + }); + }, + + down: async (queryInterface, Sequelize) => { + await queryInterface.removeColumn(TABLE_NAME, 'regions'); + await queryInterface.addColumn(TABLE_NAME, 'provinces', { + type: Sequelize.TEXT, + allowNull: true, + comment: '限定省份', + }); + await queryInterface.addColumn(TABLE_NAME, 'cities', { + type: Sequelize.TEXT, + allowNull: true, + comment: '限定城市', + }); + }, +}; diff --git a/database/migrations/20260804091000-add-exclude-regions.js b/database/migrations/20260804091000-add-exclude-regions.js new file mode 100644 index 0000000..77285cf --- /dev/null +++ b/database/migrations/20260804091000-add-exclude-regions.js @@ -0,0 +1,18 @@ +'use strict'; + +const TABLE_NAME = 'wms_store_express_binding_policy'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + await queryInterface.addColumn(TABLE_NAME, 'exclude_regions', { + type: Sequelize.TEXT, + allowNull: true, + comment: '排除地区,逗号分隔,如"新疆维吾尔自治区,西藏自治区",NULL=不排除', + after: 'regions', + }); + }, + + down: async (queryInterface, Sequelize) => { + await queryInterface.removeColumn(TABLE_NAME, 'exclude_regions'); + }, +}; diff --git a/database/migrations/20260804100000-add-shop-name.js b/database/migrations/20260804100000-add-shop-name.js new file mode 100644 index 0000000..c1dbe5b --- /dev/null +++ b/database/migrations/20260804100000-add-shop-name.js @@ -0,0 +1,18 @@ +'use strict'; + +const TABLE_NAME = 'wms_store_express_binding_policy'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + await queryInterface.addColumn(TABLE_NAME, 'shop_name', { + type: Sequelize.TEXT, + allowNull: true, + comment: '包含店铺名称,逗号分隔,NULL=不限制', + after: 'custom_name', + }); + }, + + down: async (queryInterface, Sequelize) => { + await queryInterface.removeColumn(TABLE_NAME, 'shop_name'); + }, +}; diff --git a/database/migrations/20260804101000-add-store-ids.js b/database/migrations/20260804101000-add-store-ids.js new file mode 100644 index 0000000..2e9aabb --- /dev/null +++ b/database/migrations/20260804101000-add-store-ids.js @@ -0,0 +1,18 @@ +'use strict'; + +const TABLE_NAME = 'wms_store_express_binding_policy'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + await queryInterface.addColumn(TABLE_NAME, 'store_ids', { + type: Sequelize.TEXT, + allowNull: true, + comment: '限定货主ID,逗号分隔,NULL=不限制', + after: 'shop_name', + }); + }, + + down: async (queryInterface, Sequelize) => { + await queryInterface.removeColumn(TABLE_NAME, 'store_ids'); + }, +}; diff --git a/database/migrations/20260804110000-change-text-to-json.js b/database/migrations/20260804110000-change-text-to-json.js new file mode 100644 index 0000000..95722c1 --- /dev/null +++ b/database/migrations/20260804110000-change-text-to-json.js @@ -0,0 +1,19 @@ +'use strict'; + +const TABLE_NAME = 'wms_store_express_binding_policy'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + await queryInterface.changeColumn(TABLE_NAME, 'regions', { type: Sequelize.JSON, allowNull: true, comment: '限定地区,字符串数组' }); + await queryInterface.changeColumn(TABLE_NAME, 'exclude_regions', { type: Sequelize.JSON, allowNull: true, comment: '排除地区,字符串数组' }); + await queryInterface.changeColumn(TABLE_NAME, 'shop_name', { type: Sequelize.JSON, allowNull: true, comment: '包含店铺名称,字符串数组' }); + await queryInterface.changeColumn(TABLE_NAME, 'store_ids', { type: Sequelize.JSON, allowNull: true, comment: '限定货主ID,数字数组' }); + }, + + down: async (queryInterface, Sequelize) => { + await queryInterface.changeColumn(TABLE_NAME, 'regions', { type: Sequelize.TEXT, allowNull: true, comment: '限定地区,逗号分隔' }); + await queryInterface.changeColumn(TABLE_NAME, 'exclude_regions', { type: Sequelize.TEXT, allowNull: true, comment: '排除地区,逗号分隔' }); + await queryInterface.changeColumn(TABLE_NAME, 'shop_name', { type: Sequelize.TEXT, allowNull: true, comment: '包含店铺名称,逗号分隔' }); + await queryInterface.changeColumn(TABLE_NAME, 'store_ids', { type: Sequelize.TEXT, allowNull: true, comment: '限定货主ID,逗号分隔' }); + }, +}; diff --git a/database/migrations/20260804120000-change-prohibited-to-json.js b/database/migrations/20260804120000-change-prohibited-to-json.js new file mode 100644 index 0000000..f2b1f9b --- /dev/null +++ b/database/migrations/20260804120000-change-prohibited-to-json.js @@ -0,0 +1,21 @@ +'use strict'; + +const TABLE_NAME = 'wms_store_express_binding_policy'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + await queryInterface.changeColumn(TABLE_NAME, 'prohibited_type_id', { + type: Sequelize.JSON, + allowNull: true, + comment: '违禁品类型ID数组(关联 wms_prohibited_type.id),如[1,2],NULL=不限制违禁品', + }); + }, + + down: async (queryInterface, Sequelize) => { + await queryInterface.changeColumn(TABLE_NAME, 'prohibited_type_id', { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: true, + comment: '违禁品类型ID(关联 wms_prohibited_type.id),NULL=不限制违禁品', + }); + }, +}; diff --git a/methods/system.json b/methods/system.json index 720d335..679e87a 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1,8 +1,8 @@ { "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", - "version": "0.3.9", - "updatedAt": "2026-08-03", + "version": "0.3.17", + "updatedAt": "2026-08-04", "headers": [ { "name": "platform", @@ -32454,6 +32454,491 @@ ] } ] + }, + { + "groupName": "店铺快递绑定策略模块", + "module": "storeExpressBindingPolicy", + "list": [ + { + "method": "storeExpressBindingPolicy.list", + "description": "分页查询策略列表,按priority DESC updated_at DESC排序", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "page", + "type": "number", + "required": false, + "source": "body", + "description": "页码,兼容pagination.page/currentPage" + }, + { + "name": "pageSize", + "type": "number", + "required": false, + "source": "body", + "description": "每页大小,兼容page_size/pagination.page_size,最大200" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "字段兼容id/custom_name/shop_name(数组)/store_ids(数组)/express_code/priority/is_enabled/regions(数组)/exclude_regions(数组)/prohibited_type_id(数组)/weight_type/min_weight_g/max_weight_g/creator_id/quickWhere" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "调用成功为success" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务状态码" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息" + }, + { + "name": "data.list", + "type": "array", + "required": true, + "description": "策略数组shop_name/store_ids/regions/exclude_regions/prohibited_type_id均为JSON数组,附带store_names/prohibited_type_names文本数组,express_name为快递名称" + }, + { + "name": "data.list[].store_names", + "type": "array", + "required": false, + "description": "货主名称文本数组,与store_ids一一对应" + }, + { + "name": "data.list[].prohibited_type_names", + "type": "array", + "required": false, + "description": "违禁品类型名称文本数组,与prohibited_type_id一一对应" + }, + { + "name": "data.list[].express_name", + "type": "string", + "required": false, + "description": "快递名称(含系统快递和自定义映射)" + }, + { + "name": "data.pagination", + "type": "object", + "required": true, + "description": "业务状态码" + } + ], + "errors": [ + { + "code": 400, + "message": "参数错误" + }, + { + "code": 401, + "message": "未认证" + } + ] + }, + { + "method": "storeExpressBindingPolicy.add", + "description": "新增策略。必填custom_name+express_code。weight_type默认0。同仓库custom_name唯一", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "custom_name", + "type": "string", + "required": true, + "source": "body", + "description": "策略名称同仓库唯一兼容customName" + }, + { + "name": "shop_name", + "type": "array", + "required": false, + "source": "body", + "description": "包含店铺名称字符串数组兼容shopName" + }, + { + "name": "store_ids", + "type": "array", + "required": false, + "source": "body", + "description": "限定货主ID数字数组兼容storeIds" + }, + { + "name": "express_code", + "type": "string", + "required": true, + "source": "body", + "description": "快递编码兼容expressCode" + }, + { + "name": "priority", + "type": "number", + "required": false, + "source": "body", + "description": "优先级默认0" + }, + { + "name": "is_enabled", + "type": "number", + "required": false, + "source": "body", + "description": "0停用1启用默认1兼容isEnabled" + }, + { + "name": "regions", + "type": "array", + "required": false, + "source": "body", + "description": "限定地区字符串数组" + }, + { + "name": "exclude_regions", + "type": "array", + "required": false, + "source": "body", + "description": "排除地区字符串数组兼容excludeRegions" + }, + { + "name": "min_weight_g", + "type": "number", + "required": false, + "source": "body", + "description": "最小重量克兼容minWeightG" + }, + { + "name": "max_weight_g", + "type": "number", + "required": false, + "source": "body", + "description": "最大重量克兼容maxWeightG" + }, + { + "name": "weight_type", + "type": "number", + "required": false, + "source": "body", + "description": "0常规1轻货2重货3冷链默认0兼容weightType" + }, + { + "name": "prohibited_type_id", + "type": "array", + "required": false, + "source": "body", + "description": "违禁品类型ID数字数组兼容prohibitedTypeId" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注最大500字符" + }, + { + "name": "creator_id", + "type": "number", + "required": false, + "source": "body", + "description": "创建人账户ID兼容creatorId" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "调用成功为success" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务状态码" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息" + }, + { + "name": "data.id", + "type": "number", + "required": true, + "description": "策略ID" + } + ], + "errors": [ + { + "code": 400, + "message": "参数错误" + }, + { + "code": 401, + "message": "未认证" + }, + { + "code": 409, + "message": "同仓库策略名已存在" + } + ] + }, + { + "method": "storeExpressBindingPolicy.edit", + "description": "编辑策略必填id仅更新传入字段", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "策略ID兼容policy_id/policyId" + }, + { + "name": "custom_name", + "type": "string", + "required": false, + "source": "body", + "description": "兼容customName" + }, + { + "name": "shop_name", + "type": "array", + "required": false, + "source": "body", + "description": "包含店铺名称字符串数组兼容shopName" + }, + { + "name": "store_ids", + "type": "array", + "required": false, + "source": "body", + "description": "限定货主ID数字数组兼容storeIds" + }, + { + "name": "express_code", + "type": "string", + "required": false, + "source": "body", + "description": "兼容expressCode" + }, + { + "name": "priority", + "type": "number", + "required": false, + "source": "body", + "description": "优先级" + }, + { + "name": "is_enabled", + "type": "number", + "required": false, + "source": "body", + "description": "兼容isEnabled" + }, + { + "name": "regions", + "type": "array", + "required": false, + "source": "body", + "description": "限定地区字符串数组" + }, + { + "name": "exclude_regions", + "type": "array", + "required": false, + "source": "body", + "description": "排除地区字符串数组兼容excludeRegions" + }, + { + "name": "min_weight_g", + "type": "number", + "required": false, + "source": "body", + "description": "兼容minWeightG" + }, + { + "name": "max_weight_g", + "type": "number", + "required": false, + "source": "body", + "description": "兼容maxWeightG" + }, + { + "name": "weight_type", + "type": "number", + "required": false, + "source": "body", + "description": "兼容weightType" + }, + { + "name": "prohibited_type_id", + "type": "array", + "required": false, + "source": "body", + "description": "违禁品类型ID数字数组兼容prohibitedTypeId" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注" + }, + { + "name": "creator_id", + "type": "number", + "required": false, + "source": "body", + "description": "兼容creatorId" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "调用成功为success" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务状态码" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息" + }, + { + "name": "data.id", + "type": "number", + "required": true, + "description": "策略ID" + } + ], + "errors": [ + { + "code": 400, + "message": "参数错误" + }, + { + "code": 401, + "message": "未认证" + }, + { + "code": 404, + "message": "策略不存在" + }, + { + "code": 409, + "message": "同仓库策略名已存在" + } + ] + }, + { + "method": "storeExpressBindingPolicy.del", + "description": "软删除策略", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "策略ID兼容policy_id/policyId" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "调用成功为success" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务状态码" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息" + }, + { + "name": "data.id", + "type": "number", + "required": true, + "description": "策略ID" + } + ], + "errors": [ + { + "code": 400, + "message": "id为空" + }, + { + "code": 401, + "message": "未认证" + }, + { + "code": 404, + "message": "策略不存在" + } + ] + } + ] } ] } From 9b1a6034af214ba28c5936a8a2aab18ae7200648 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Tue, 4 Aug 2026 08:22:54 +0800 Subject: [PATCH 167/550] =?UTF-8?q?=E6=96=87=E6=A1=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- methods/changes/system.json | 139 ++++++++++++++++++++++++++++++++++++ 1 file changed, 139 insertions(+) diff --git a/methods/changes/system.json b/methods/changes/system.json index 31505a0..44abf26 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -5160,5 +5160,144 @@ "新增 express 子对象文档(code/name/polyapi_code/polyapi_extra_info/pdd_code/ks_code/dyxd_code)", "保留 quantity/recycled_quantity/cancel_quantity/allocated_quantity 四个扁平面单数量字段" ] + }, + { + "version": "2026.08.03-system-04", + "date": "2026-08-03", + "type": "added", + "summary": "新增店铺-快递绑定策略模块 storeExpressBindingPolicy,支持仓库维度的货主/店铺->快递绑定策略 CRUD,按优先级匹配,可附加商品/地区/重量/金额等条件", + "methods": [ + "storeExpressBindingPolicy.list", + "storeExpressBindingPolicy.add", + "storeExpressBindingPolicy.edit", + "storeExpressBindingPolicy.del" + ], + "notes": [ + "storeExpressBindingPolicy.list:分页查询策略列表,支持 where 条件筛选(id/custom_name/store_id/shop_id/express_code/priority/is_enabled/creator_id/quickWhere),按 priority DESC、updated_at DESC 排序。", + "storeExpressBindingPolicy.add:新增策略,必填 custom_name 和 express_code。express_code 须存在于 wms_express。同仓库下 custom_name 唯一。可选 store_id/shop_id/priority/is_enabled/match_condition/remark/creator_id。", + "storeExpressBindingPolicy.edit:编辑策略,必填 id。仅更新传入的非 undefined 字段。修改 custom_name 时校验同仓库唯一性。", + "storeExpressBindingPolicy.del:软删除策略(deleted_at + is_enabled=0),不物理删除。", + "仓库隔离:所有操作按 ctx.user.store_id → warehouse_id 自动过滤。", + "匹配条件 match_condition(JSON):支持 platform_codes/provinces/cities/item_codes/min_weight_g/max_weight_g/min_amount/max_amount。" + ], + "module": "storeExpressBindingPolicy" + }, + { + "version": "2026.08.03-system-05", + "date": "2026-08-03", + "type": "changed", + "summary": "精简 storeExpressBindingPolicy:移除 store_id/shop_id 冗余字段,custom_name 明确为纯自由文本标签(与系统 shops 无关)", + "methods": [ + "storeExpressBindingPolicy.list", + "storeExpressBindingPolicy.add", + "storeExpressBindingPolicy.edit", + "storeExpressBindingPolicy.del" + ], + "notes": [ + "移除 add/edit 入参中的 store_id/shop_id(含 camelCase 兼容)", + "list 响应不再返回 store_id/shop_id", + "custom_name 为纯自由文本标签,与系统 shops 表无关" + ], + "module": "storeExpressBindingPolicy" + }, + { + "version": "2026.08.04-system-01", + "date": "2026-08-04", + "type": "changed", + "summary": "storeExpressBindingPolicy 字段重构: match_condition JSON 拆分为独立字段 provinces/cities/min_weight_g/max_weight_g/weight_type,新增 prohibited_type_id", + "methods": [ + "storeExpressBindingPolicy.list", + "storeExpressBindingPolicy.add", + "storeExpressBindingPolicy.edit", + "storeExpressBindingPolicy.del" + ], + "notes": [ + "移除 match_condition JSON,拆分 provinces TEXT逗号分隔 + cities TEXT逗号分隔 + min_weight_g INT + max_weight_g INT + weight_type TINYINT 默认0", + "weight_type 枚举 0=常规 1=轻货 2=重货 3=冷链 必填默认0", + "新增 prohibited_type_id 关联 wms_prohibited_type.id" + ], + "module": "storeExpressBindingPolicy" + }, + { + "version": "2026.08.04-system-02", + "date": "2026-08-04", + "type": "changed", + "summary": "合并 provinces/cities 为单一 regions 字段 TEXT逗号分隔", + "methods": [ + "storeExpressBindingPolicy.list", + "storeExpressBindingPolicy.add", + "storeExpressBindingPolicy.edit", + "storeExpressBindingPolicy.del" + ], + "notes": [ + "移除 provinces/cities 两个字段,合并为 regions TEXT 逗号分隔" + ], + "module": "storeExpressBindingPolicy" + }, + { + "version": "2026.08.04-system-03", + "date": "2026-08-04", + "type": "added", + "summary": "新增 exclude_regions 排除地区字段", + "methods": [ + "storeExpressBindingPolicy.list", + "storeExpressBindingPolicy.add", + "storeExpressBindingPolicy.edit", + "storeExpressBindingPolicy.del" + ], + "notes": [ + "新增 exclude_regions 排除地区字段 TEXT逗号分隔" + ], + "module": "storeExpressBindingPolicy" + }, + { + "version": "2026.08.04-system-04", + "date": "2026-08-04", + "type": "changed", + "summary": "修正 API 文档风格,对齐项目 shops.list 等模块规范", + "methods": [ + "storeExpressBindingPolicy.list", + "storeExpressBindingPolicy.add", + "storeExpressBindingPolicy.edit", + "storeExpressBindingPolicy.del" + ], + "notes": [ + "list page/pageSize 描述对齐 shops.list 风格", + "add/edit 参数描述补充兼容性说明和详细格式" + ], + "module": "storeExpressBindingPolicy" + }, + { + "version": "2026.08.04-system-05", + "date": "2026-08-04", + "type": "added", + "summary": "新增 shop_name 字段,用于包含店铺名称匹配", + "methods": [ + "storeExpressBindingPolicy.list", + "storeExpressBindingPolicy.add", + "storeExpressBindingPolicy.edit", + "storeExpressBindingPolicy.del" + ], + "notes": [ + "新增 shop_name TEXT逗号分隔,与 custom_name区分:custom_name=策略名称,shop_name=包含店铺名称" + ], + "module": "storeExpressBindingPolicy" + }, + { + "version": "2026.08.04-system-06", + "date": "2026-08-04", + "type": "added", + "summary": "新增shop_name和store_ids字段", + "methods": [ + "storeExpressBindingPolicy.list", + "storeExpressBindingPolicy.add", + "storeExpressBindingPolicy.edit", + "storeExpressBindingPolicy.del" + ], + "notes": [ + "新增shop_name包含店铺名称", + "新增store_ids限定货主ID" + ], + "module": "storeExpressBindingPolicy" } ] From b9fe9e774ce0a34456f50fbc6f0893f6e8ea5f9c Mon Sep 17 00:00:00 2001 From: liufumingren Date: Tue, 4 Aug 2026 16:02:27 +0800 Subject: [PATCH 168/550] =?UTF-8?q?fix:=20=E6=8B=A3=E8=B4=A7=E5=AE=8C?= =?UTF-8?q?=E6=88=90=E6=89=A3=E5=87=8F=E5=BA=93=E5=AD=98=E4=BA=8B=E5=8A=A1?= =?UTF-8?q?=E6=BC=8F=E6=B4=9E=20-=20picking=E6=9F=A5=E8=AF=A2=E6=B7=BB?= =?UTF-8?q?=E5=8A=A0FOR=20UPDATE=E8=A1=8C=E9=94=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - recheckOrder._completePickForOrder: picking查询添加FOR UPDATE,防止并发重复扣减 - pick_compensation.compensateInTransaction: 同上 - pick_compensation.releaseCancelledInTransaction: 同上 与主路径 wavePickTaskComplete 保持一致的双重行锁防护(picking FOR UPDATE + storage LOCK.UPDATE) --- app/service/systemMethods/order/recheckOrder.js | 4 +++- app/service/systems/pick_compensation.js | 4 ++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/app/service/systemMethods/order/recheckOrder.js b/app/service/systemMethods/order/recheckOrder.js index 1df67c6..dd34ba5 100644 --- a/app/service/systemMethods/order/recheckOrder.js +++ b/app/service/systemMethods/order/recheckOrder.js @@ -3995,13 +3995,15 @@ class RecheckOrderService extends OrderBaseService { ); // 步骤3:检查是否存在 wms_picking 记录(仅统计 pending 且未删除的记录) + // 使用 FOR UPDATE 行锁,防止并发事务读取到相同的 picking 记录导致重复扣减库存 const pickingRows = await ctx.model.query( `SELECT id, storage_id, quantity, space_id FROM wms_picking WHERE order_id = :orderId AND warehouse_id = :warehouseId AND status = 'pending' - AND deleted_at IS NULL`, + AND deleted_at IS NULL + FOR UPDATE`, { replacements: { orderId, warehouseId }, type: ctx.model.QueryTypes.SELECT, diff --git a/app/service/systems/pick_compensation.js b/app/service/systems/pick_compensation.js index cd5ba78..a6ce4a7 100644 --- a/app/service/systems/pick_compensation.js +++ b/app/service/systems/pick_compensation.js @@ -335,6 +335,7 @@ class PickCompensationService extends MainService { try { // Step 1: 重新查询 wms_picking,确保只处理仍然 status='pending' 的记录 + // 使用 FOR UPDATE 行锁,防止并发事务读取到相同的 picking 记录导致重复释放锁定库存 const confirmedRows = await ctx.model.query(` SELECT p.id, @@ -348,6 +349,7 @@ class PickCompensationService extends MainService { AND p.storage_id IS NOT NULL AND p.storage_id > 0 AND p.deleted_at IS NULL -- 排除软删除记录 + FOR UPDATE `, { replacements: { pickingIds, warehouseId }, type: ctx.model.QueryTypes.SELECT, @@ -474,6 +476,7 @@ class PickCompensationService extends MainService { try { // Step 1: 重新查询 wms_picking,确保只处理仍然 status='pending' 的记录 + // 使用 FOR UPDATE 行锁,防止并发事务读取到相同的 picking 记录导致重复扣减库存 const confirmedRows = await ctx.model.query(` SELECT p.id, @@ -487,6 +490,7 @@ class PickCompensationService extends MainService { AND p.storage_id IS NOT NULL AND p.storage_id > 0 AND p.deleted_at IS NULL -- 排除软删除记录 + FOR UPDATE `, { replacements: { pickingIds, warehouseId }, type: ctx.model.QueryTypes.SELECT, From 095679c38e7d5d70c1963272c468139769700917 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Tue, 4 Aug 2026 16:11:39 +0800 Subject: [PATCH 169/550] =?UTF-8?q?fix:=E4=BF=AE=E6=AD=A3=E5=88=86?= =?UTF-8?q?=E9=85=8D=E5=BF=AB=E9=80=92=E5=8F=B7=E5=85=A5=E5=8F=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/systems/express_platform.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/service/systems/express_platform.js b/app/service/systems/express_platform.js index c6d0caf..c4923d1 100644 --- a/app/service/systems/express_platform.js +++ b/app/service/systems/express_platform.js @@ -706,7 +706,7 @@ class ExpressPlatformService extends MainService { let playload = { object_Id: `${order.warehouse_id}_${order.id}_${order_tmp.business_key}`, // 菠萝派平台要求订单唯一标识必须为字符串 orderno: `${order.warehouse_id}_${order.id}_${order_tmp.business_key}`, // 菠萝派平台要求订单号必须为字符串 - plattradeno: listByWarehousePlatformCode.platform_code === 'DY' && order.from_key == 23060081? order.pay_no : order.source_order_codes || order.delivery_order_code || '', + plattradeno: listByWarehousePlatformCode.platform_code === 'DY' && order.from_key === 23060081 && !!order.pay_no ? order.pay_no : order.source_order_codes || order.delivery_order_code || '', ismultiplepieces: order.package_count > 1 ? 1 : 0, logisticno: allocatedWaybillMap.get(`${Number(order.id) || 0}:${Number(order_tmp.business_key) || 0}`) || '', logistictype: order.logistics_code || '', From 61b82512f28232fe06e87638b6cc9ac84773cfd8 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Tue, 4 Aug 2026 18:08:46 +0800 Subject: [PATCH 170/550] =?UTF-8?q?feat(auth):=20=E6=96=B0=E5=A2=9E?= =?UTF-8?q?=E5=AE=A2=E6=9C=8D=E7=BB=84=E6=9D=83=E9=99=90=E6=8E=88=E6=9D=83?= =?UTF-8?q?/=E5=8F=96=E6=B6=88=E8=84=9A=E6=9C=AC=EF=BC=8C=E6=9B=B4?= =?UTF-8?q?=E6=96=B0=20dev-agent=20=E9=85=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - scripts/auth/grant-cs-up.js: 客服组及以上角色批量授权(dev+prod) - scripts/auth/revoke-cs-up.js: 客服组及以上角色批量取消授权(dev+prod) - .github/agents/开发.agent.md: 新增关键定位地图第5项-客服组权限授权脚本 - .cursor/agents/wms-dev-agent.md: 同步 dev-agent 配置 --- .cursor/agents/wms-dev-agent.md | 15 ++ .github/agents/开发.agent.md | 15 ++ app/service/systems/inbound_direct_log.js | 64 +++---- app/service/systems/pick_compensation.js | 45 ++++- app/service/systems/stock_store.js | 14 +- app/service/systems/storage/entry.js | 60 +++---- scripts/auth/grant-cs-up.js | 200 ++++++++++++++++++++++ scripts/auth/revoke-cs-up.js | 191 +++++++++++++++++++++ 8 files changed, 542 insertions(+), 62 deletions(-) create mode 100644 scripts/auth/grant-cs-up.js create mode 100644 scripts/auth/revoke-cs-up.js diff --git a/.cursor/agents/wms-dev-agent.md b/.cursor/agents/wms-dev-agent.md index 40b56e2..0fdd890 100644 --- a/.cursor/agents/wms-dev-agent.md +++ b/.cursor/agents/wms-dev-agent.md @@ -71,6 +71,21 @@ is_background: false - `test/app/controller/system.user.info.web.test.js` - `test/app/controller/system.user.changeRole.test.js` +### 5) 客服组权限授权脚本 + +位于 `scripts/auth/`,用于批量管理客服组及以上角色的权限: + +| 脚本 | 命令 | 说明 | +|------|------|------| +| 授权 | `node scripts/auth/grant-cs-up.js <权限ID>` | 添加权限到 客服组-员工(30) → 客服组-主管(28) → 经理(8) | +| 取消 | `node scripts/auth/revoke-cs-up.js <权限ID>` | 从上述角色移除权限 | + +**特性**: +- 自动跳过通配符角色(`超级管理员(7)` 和 `仓库管理员(2)` 已有 `*`) +- 幂等安全:已存在/不存在时自动跳过 +- 双环境同步:开发 → 生产 顺序执行 +- 权限校验:自动查询 `wms_permission` 确认权限存在 + ## 推荐工作流 ### 代码修改 / 修 bug diff --git a/.github/agents/开发.agent.md b/.github/agents/开发.agent.md index 2b11c3c..e779179 100644 --- a/.github/agents/开发.agent.md +++ b/.github/agents/开发.agent.md @@ -71,6 +71,21 @@ model: DeepSeek V4 Pro (deepseek) - `test/app/controller/system.user.info.web.test.js` - `test/app/controller/system.user.changeRole.test.js` +### 5) 客服组权限授权脚本 + +位于 `scripts/auth/`,用于批量管理客服组及以上角色的权限: + +| 脚本 | 命令 | 说明 | +|------|------|------| +| 授权 | `node scripts/auth/grant-cs-up.js <权限ID>` | 添加权限到 客服组-员工(30) → 客服组-主管(28) → 经理(8) | +| 取消 | `node scripts/auth/revoke-cs-up.js <权限ID>` | 从上述角色移除权限 | + +**特性**: +- 自动跳过通配符角色(`超级管理员(7)` 和 `仓库管理员(2)` 已有 `*`) +- 幂等安全:已存在/不存在时自动跳过 +- 双环境同步:开发 → 生产 顺序执行 +- 权限校验:自动查询 `wms_permission` 确认权限存在 + ## 推荐工作流 ### 代码修改 / 修 bug diff --git a/app/service/systems/inbound_direct_log.js b/app/service/systems/inbound_direct_log.js index db37198..9062369 100644 --- a/app/service/systems/inbound_direct_log.js +++ b/app/service/systems/inbound_direct_log.js @@ -991,38 +991,40 @@ class InboundDirectLogService extends Service { transaction, }); - if (stockRecord) { - const beforeQuantity = Number(stockRecord.quantity) || 0; - const beforeLockedQuantity = Number(stockRecord.locked_quantity) || 0; - - await stockRecord.increment('quantity', { by: inboundQty, transaction, silent: true }); - await stockRecord.reload({ transaction }); - - const afterQuantity = Number(stockRecord.quantity) || 0; - const afterLockedQuantity = Number(stockRecord.locked_quantity) || 0; - - // 写入库存流水(聚合维度) - await ctx.service.systems.stockTransaction.create({ - transaction_type: 'INBOUND', - warehouse_id: warehouseId, - store_id: storeId, - stock_id: stockId, - quantity: inboundQty, - batch_no: batchNo, - inventory_type: inventoryType, - order_type: eo.order_type, - order_no: eo.entry_order_code, - entry_order_id: eo.id, - operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), - operator_name: ctx.user?.employees_name || '', - remark: '导入/PDA直接入库提交', - before_quantity: beforeQuantity, - after_quantity: afterQuantity, - before_locked_quantity: beforeLockedQuantity, - after_locked_quantity: afterLockedQuantity, - created_at: new Date(), - }, { transaction }); + if (!stockRecord) { + throw new Error(`商品库存记录不存在或已失效,无法入库: stock_id=${stockId}`); } + + const beforeQuantity = Number(stockRecord.quantity) || 0; + const beforeLockedQuantity = Number(stockRecord.locked_quantity) || 0; + + await stockRecord.increment('quantity', { by: inboundQty, transaction, silent: true }); + await stockRecord.reload({ transaction }); + + const afterQuantity = Number(stockRecord.quantity) || 0; + const afterLockedQuantity = Number(stockRecord.locked_quantity) || 0; + + // 写入库存流水(聚合维度) + await ctx.service.systems.stockTransaction.create({ + transaction_type: 'INBOUND', + warehouse_id: warehouseId, + store_id: storeId, + stock_id: stockId, + quantity: inboundQty, + batch_no: batchNo, + inventory_type: inventoryType, + order_type: eo.order_type, + order_no: eo.entry_order_code, + entry_order_id: eo.id, + operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), + operator_name: ctx.user?.employees_name || '', + remark: '导入/PDA直接入库提交', + before_quantity: beforeQuantity, + after_quantity: afterQuantity, + before_locked_quantity: beforeLockedQuantity, + after_locked_quantity: afterLockedQuantity, + created_at: new Date(), + }, { transaction }); } /** diff --git a/app/service/systems/pick_compensation.js b/app/service/systems/pick_compensation.js index a6ce4a7..1190437 100644 --- a/app/service/systems/pick_compensation.js +++ b/app/service/systems/pick_compensation.js @@ -378,7 +378,10 @@ class PickCompensationService extends MainService { id: { [app.Sequelize.Op.in]: storageIds }, warehouse_id: warehouseId, }, - attributes: [ 'id', 'locked_quantity', 'quantity', 'store_id', 'stock_id' ], + attributes: [ + 'id', 'locked_quantity', 'quantity', + 'store_id', 'stock_id', 'batch_no', 'inventory_type', 'space_id', + ], lock: transaction.LOCK.UPDATE, raw: true, transaction, @@ -420,6 +423,46 @@ class PickCompensationService extends MainService { transaction, }); + // Step 4.5: 写入 wms_storage_transaction 解锁流水 + const unlockTransactionRows = []; + for (const sRow of storageRows) { + const sid = Number(sRow.id); + const deduction = storageQtyMap.get(sid) || 0; + if (deduction <= 0) continue; + const beforeQty = Number(sRow.quantity) || 0; + const beforeLocked = Number(sRow.locked_quantity) || 0; + unlockTransactionRows.push({ + transaction_type: 'UNLOCK', + warehouse_id: warehouseId, + store_id: Number(sRow.store_id) || 0, + stock_id: Number(sRow.stock_id) || 0, + storage_id: sid, + space_id: Number(sRow.space_id) || null, + quantity: deduction, + before_quantity: beforeQty, + after_quantity: beforeQty, + before_locked_quantity: beforeLocked, + after_locked_quantity: Math.max(0, beforeLocked - deduction), + batch_no: sRow.batch_no || null, + inventory_type: sRow.inventory_type || 'ZP', + order_type: 'PICKING_CANCEL_UNLOCK', + order_no: normalizedConfirmedRows + .filter(r => Number(r.storage_id) === sid) + .map(r => String(r.order_id)) + .join(',') + .slice(0, 255), + order_id: 0, + operator_id: '', + operator_name: 'pick_compensation', + remark: '拣货补偿-释放已取消订单库存锁定', + created_at: new Date(), + }); + } + + if (unlockTransactionRows.length > 0) { + await ctx.model.StorageTransaction.bulkCreate(unlockTransactionRows, { transaction }); + } + // Step 5: UPDATE wms_picking SET status='cancelled_released' const compensatedPickingIds = normalizedConfirmedRows.map(r => Number(r.id)); await ctx.model.query(` diff --git a/app/service/systems/stock_store.js b/app/service/systems/stock_store.js index e5da1a7..c7c5f0d 100644 --- a/app/service/systems/stock_store.js +++ b/app/service/systems/stock_store.js @@ -884,7 +884,7 @@ class stockStoreService extends Service { const beforeLockedQuantity = Number(storage.lockedQuantity) || 0; // 非首次入库:更新现有记录(只增加quantity) - await ctx.model.StockWarehouse.increment('quantity', { + const [ affectedRows ] = await ctx.model.StockWarehouse.increment('quantity', { by: inboundQty, where: { id: storage.id, @@ -894,6 +894,18 @@ class stockStoreService extends Service { transaction: currentTransaction, }); + if (!affectedRows || affectedRows === 0) { + const failureResult = { + success: false, + error: '商品库存记录不存在或已失效,入库失败', + data: null, + }; + if (hasExternalTransaction) { + throw new Error(failureResult.error); + } + return failureResult; + } + const updatedRecord = await ctx.model.StockWarehouse.findByPk(storage.id, { transaction: currentTransaction, raw: true, diff --git a/app/service/systems/storage/entry.js b/app/service/systems/storage/entry.js index c138a2f..add9722 100644 --- a/app/service/systems/storage/entry.js +++ b/app/service/systems/storage/entry.js @@ -1504,37 +1504,39 @@ class EntryService extends Service { transaction, }); - if (stockRecord) { - const beforeQuantity = Number(stockRecord.quantity) || 0; - const beforeLockedQuantity = Number(stockRecord.locked_quantity) || 0; - - await stockRecord.increment('quantity', { by: planQty, transaction, silent: true }); - await stockRecord.reload({ transaction }); - - const afterQuantity = Number(stockRecord.quantity) || 0; - const afterLockedQuantity = Number(stockRecord.locked_quantity) || 0; - - await ctx.service.systems.stockTransaction.create({ - transaction_type: 'INBOUND', - warehouse_id: warehouseId, - store_id: storeId, - stock_id: stockId, - quantity: planQty, - batch_no: batchNo, - order_type: eo.order_type, - order_no: eo.entry_order_code, - entry_order_id: eo.id, - operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), - operator_name: ctx.user?.employees_name || '', - remark: '快捷直入/虚拟入库', - before_quantity: beforeQuantity, - after_quantity: afterQuantity, - before_locked_quantity: beforeLockedQuantity, - after_locked_quantity: afterLockedQuantity, - created_at: new Date(), - }, { transaction }); + if (!stockRecord) { + throw new Error(`商品库存记录不存在或已失效,无法入库: stock_id=${stockId}`); } + const beforeQuantity = Number(stockRecord.quantity) || 0; + const beforeLockedQuantity = Number(stockRecord.locked_quantity) || 0; + + await stockRecord.increment('quantity', { by: planQty, transaction, silent: true }); + await stockRecord.reload({ transaction }); + + const afterQuantity = Number(stockRecord.quantity) || 0; + const afterLockedQuantity = Number(stockRecord.locked_quantity) || 0; + + await ctx.service.systems.stockTransaction.create({ + transaction_type: 'INBOUND', + warehouse_id: warehouseId, + store_id: storeId, + stock_id: stockId, + quantity: planQty, + batch_no: batchNo, + order_type: eo.order_type, + order_no: eo.entry_order_code, + entry_order_id: eo.id, + operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), + operator_name: ctx.user?.employees_name || '', + remark: '快捷直入/虚拟入库', + before_quantity: beforeQuantity, + after_quantity: afterQuantity, + before_locked_quantity: beforeLockedQuantity, + after_locked_quantity: afterLockedQuantity, + created_at: new Date(), + }, { transaction }); + const storageRecord = await ctx.model.Storage.findOne({ where: { space_id: hardcodedSpaceId, diff --git a/scripts/auth/grant-cs-up.js b/scripts/auth/grant-cs-up.js new file mode 100644 index 0000000..fd4fbef --- /dev/null +++ b/scripts/auth/grant-cs-up.js @@ -0,0 +1,200 @@ +/** + * 客服组及以上角色授权脚本 + * + * 用法: node scripts/auth/grant-cs-up.js <权限ID> + * 示例: node scripts/auth/grant-cs-up.js 365 + * + * 授权链路: 客服组-员工(30) → 客服组-主管(28) → 经理(8) + * 仓库管理员(2)和超级管理员(7)已有通配符 *,自动拥有所有权限,无需处理 + */ + +const path = require('path'); +const { createRequire } = require('module'); + +const PROJECT_ROOT = path.join(__dirname, '..', '..'); +const projectRequire = createRequire(path.join(PROJECT_ROOT, 'package.json')); +const mysql = projectRequire('mysql2/promise'); + +// ── 客服链路角色(从低到高) ── +const CS_CHAIN_ROLES = [ + { id: 30, code: '04', name: '客服组-员工' }, + { id: 28, code: '05', name: '客服组-主管' }, + { id: 8, code: '2', name: '经理' }, +]; + +// 已有通配符 * 的角色,自动拥有所有权限,跳过 +const WILDCARD_ROLES = [7, 2]; + +// ── 数据库连接 ── + +function loadDbConfig(env) { + const configFile = env === 'production' + ? path.join(PROJECT_ROOT, 'config', 'config.default.js') + : path.join(PROJECT_ROOT, 'config', 'config.local.js'); + + const factory = require(configFile); + const cfg = typeof factory === 'function' + ? factory({ name: 'wms', baseDir: PROJECT_ROOT }) + : factory; + + if (env === 'production') { + return cfg.sequelize; + } + return cfg.mysql && cfg.mysql.clients && cfg.mysql.clients.wms; +} + +async function createConnection(env) { + const cfg = loadDbConfig(env); + if (!cfg) throw new Error(`无法加载 ${env} 数据库配置`); + return mysql.createConnection({ + host: cfg.host, + port: cfg.port || 3306, + user: cfg.username || cfg.user, + password: cfg.password, + database: cfg.database, + }); +} + +// ── 权限校验 ── + +async function getPermission(conn, permId) { + const [rows] = await conn.query( + 'SELECT id, name, meta_title, type, path FROM wms_permission WHERE id = ?', + [permId] + ); + return rows[0] || null; +} + +// ── 授权逻辑 ── + +async function grantPermission(conn, permId, envLabel) { + const results = []; + + for (const role of CS_CHAIN_ROLES) { + const [rows] = await conn.query( + 'SELECT id, role_code, role_name, permissions FROM wms_role WHERE id = ? AND deleted_at IS NULL', + [role.id] + ); + + if (rows.length === 0) { + results.push({ role, status: 'not_found', msg: '角色不存在或已删除' }); + continue; + } + + const record = rows[0]; + + // 通配符角色跳过 + if (record.permissions === '*') { + results.push({ role, status: 'wildcard', msg: '已有通配符 *,跳过' }); + continue; + } + + // 解析权限数组 + let perms; + try { + perms = JSON.parse(record.permissions); + } catch { + results.push({ role, status: 'error', msg: `permissions JSON 解析失败` }); + continue; + } + + if (!Array.isArray(perms)) { + results.push({ role, status: 'error', msg: 'permissions 不是数组' }); + continue; + } + + if (perms.includes(Number(permId))) { + results.push({ role, status: 'skip', msg: `已包含权限 ${permId}` }); + continue; + } + + // 添加权限并排序 + perms.push(Number(permId)); + perms.sort((a, b) => a - b); + + await conn.query('UPDATE wms_role SET permissions = ? WHERE id = ?', [ + JSON.stringify(perms), + role.id, + ]); + results.push({ role, status: 'ok', msg: '已添加', count: perms.length }); + } + + return results; +} + +// ── 主流程 ── + +async function main() { + const permId = process.argv[2]; + + if (!permId || isNaN(Number(permId))) { + console.error('用法: node scripts/auth/grant-cs-up.js <权限ID>'); + console.error('示例: node scripts/auth/grant-cs-up.js 365'); + process.exit(1); + } + + const permIdNum = Number(permId); + + console.log('═══════════════════════════════════════'); + console.log(' 客服组及以上角色授权脚本'); + console.log('═══════════════════════════════════════'); + console.log(` 权限 ID: ${permIdNum}`); + console.log(` 目标角色: ${CS_CHAIN_ROLES.map(r => `${r.name}(${r.id})`).join(' → ')}`); + console.log(` 通配符角色(跳过): id=${WILDCARD_ROLES.join(',')} (已有 *)`); + console.log('═══════════════════════════════════════\n'); + + // ── 开发环境:查询权限信息 ── + let devConn; + try { + devConn = await createConnection('dev'); + } catch (e) { + console.error(`[DEV] 开发环境连接失败: ${e.message}`); + process.exit(1); + } + + const perm = await getPermission(devConn, permIdNum); + if (!perm) { + console.error(`[DEV] 权限 ${permIdNum} 在数据库中不存在!`); + await devConn.end(); + process.exit(1); + } + + console.log(`权限信息: ${perm.meta_title || '(无名称)'} [${perm.type}] ${perm.path || ''}\n`); + + // ── 开发环境授权 ── + console.log('[DEV] 开发环境 ======'); + const devResults = await grantPermission(devConn, permIdNum, '[DEV]'); + for (const r of devResults) { + const icon = r.status === 'ok' ? '✅' : r.status === 'skip' ? '⏭️' : r.status === 'wildcard' ? '🔹' : '❌'; + const extra = r.status === 'ok' ? ` (共${r.count}个权限)` : ''; + console.log(` ${icon} ${r.role.name}(${r.role.id}): ${r.msg}${extra}`); + } + await devConn.end(); + + // ── 生产环境授权 ── + console.log('\n[PROD] 生产环境 ======'); + let prodConn; + try { + prodConn = await createConnection('production'); + } catch (e) { + console.error(` 生产环境连接失败: ${e.message}`); + process.exit(1); + } + + const prodResults = await grantPermission(prodConn, permIdNum, '[PROD]'); + for (const r of prodResults) { + const icon = r.status === 'ok' ? '✅' : r.status === 'skip' ? '⏭️' : r.status === 'wildcard' ? '🔹' : '❌'; + const extra = r.status === 'ok' ? ` (共${r.count}个权限)` : ''; + console.log(` ${icon} ${r.role.name}(${r.role.id}): ${r.msg}${extra}`); + } + await prodConn.end(); + + console.log('\n═══════════════════════════════════════'); + console.log(' 授权完成'); + console.log('═══════════════════════════════════════'); +} + +main().catch(e => { + console.error('执行失败:', e.message); + process.exit(1); +}); diff --git a/scripts/auth/revoke-cs-up.js b/scripts/auth/revoke-cs-up.js new file mode 100644 index 0000000..d9bf651 --- /dev/null +++ b/scripts/auth/revoke-cs-up.js @@ -0,0 +1,191 @@ +/** + * 客服组及以上角色取消授权脚本 + * + * 用法: node scripts/auth/revoke-cs-up.js <权限ID> + * 示例: node scripts/auth/revoke-cs-up.js 365 + * + * 取消链路: 客服组-员工(30) → 客服组-主管(28) → 经理(8) + * 仓库管理员(2)和超级管理员(7)已有通配符 *,无需处理 + */ + +const path = require('path'); +const { createRequire } = require('module'); + +const PROJECT_ROOT = path.join(__dirname, '..', '..'); +const projectRequire = createRequire(path.join(PROJECT_ROOT, 'package.json')); +const mysql = projectRequire('mysql2/promise'); + +// ── 客服链路角色(从低到高) ── +const CS_CHAIN_ROLES = [ + { id: 30, code: '04', name: '客服组-员工' }, + { id: 28, code: '05', name: '客服组-主管' }, + { id: 8, code: '2', name: '经理' }, +]; + +// ── 数据库连接 ── + +function loadDbConfig(env) { + const configFile = env === 'production' + ? path.join(PROJECT_ROOT, 'config', 'config.default.js') + : path.join(PROJECT_ROOT, 'config', 'config.local.js'); + + const factory = require(configFile); + const cfg = typeof factory === 'function' + ? factory({ name: 'wms', baseDir: PROJECT_ROOT }) + : factory; + + if (env === 'production') { + return cfg.sequelize; + } + return cfg.mysql && cfg.mysql.clients && cfg.mysql.clients.wms; +} + +async function createConnection(env) { + const cfg = loadDbConfig(env); + if (!cfg) throw new Error(`无法加载 ${env} 数据库配置`); + return mysql.createConnection({ + host: cfg.host, + port: cfg.port || 3306, + user: cfg.username || cfg.user, + password: cfg.password, + database: cfg.database, + }); +} + +// ── 取消授权逻辑 ── + +async function revokePermission(conn, permId, envLabel) { + const results = []; + + for (const role of CS_CHAIN_ROLES) { + const [rows] = await conn.query( + 'SELECT id, role_code, role_name, permissions FROM wms_role WHERE id = ? AND deleted_at IS NULL', + [role.id] + ); + + if (rows.length === 0) { + results.push({ role, status: 'not_found', msg: '角色不存在或已删除' }); + continue; + } + + const record = rows[0]; + + // 通配符角色跳过 + if (record.permissions === '*') { + results.push({ role, status: 'wildcard', msg: '已有通配符 *,跳过' }); + continue; + } + + // 解析权限数组 + let perms; + try { + perms = JSON.parse(record.permissions); + } catch { + results.push({ role, status: 'error', msg: 'permissions JSON 解析失败' }); + continue; + } + + if (!Array.isArray(perms)) { + results.push({ role, status: 'error', msg: 'permissions 不是数组' }); + continue; + } + + const idx = perms.indexOf(Number(permId)); + if (idx === -1) { + results.push({ role, status: 'skip', msg: `不包含权限 ${permId},跳过` }); + continue; + } + + // 移除权限 + perms.splice(idx, 1); + + await conn.query('UPDATE wms_role SET permissions = ? WHERE id = ?', [ + JSON.stringify(perms), + role.id, + ]); + results.push({ role, status: 'ok', msg: '已移除', count: perms.length }); + } + + return results; +} + +// ── 主流程 ── + +async function main() { + const permId = process.argv[2]; + + if (!permId || isNaN(Number(permId))) { + console.error('用法: node scripts/auth/revoke-cs-up.js <权限ID>'); + console.error('示例: node scripts/auth/revoke-cs-up.js 365'); + process.exit(1); + } + + const permIdNum = Number(permId); + + console.log('═══════════════════════════════════════'); + console.log(' 客服组及以上角色取消授权脚本'); + console.log('═══════════════════════════════════════'); + console.log(` 权限 ID: ${permIdNum}`); + console.log(` 目标角色: ${CS_CHAIN_ROLES.map(r => `${r.name}(${r.id})`).join(' → ')}`); + console.log(` 通配符角色(跳过): id=7,2 (已有 *)`); + console.log('═══════════════════════════════════════\n'); + + // ── 开发环境:查询权限信息 ── + let devConn; + try { + devConn = await createConnection('dev'); + } catch (e) { + console.error(`[DEV] 开发环境连接失败: ${e.message}`); + process.exit(1); + } + + const [permRows] = await devConn.query( + 'SELECT id, name, meta_title, type, path FROM wms_permission WHERE id = ?', + [permIdNum] + ); + + if (permRows.length > 0) { + const perm = permRows[0]; + console.log(`权限信息: ${perm.meta_title || '(无名称)'} [${perm.type}] ${perm.path || ''}`); + console.log('⚠️ 该权限在数据库中仍存在,确定要取消授权?\n'); + } else { + console.log('该权限已在数据库中物理删除\n'); + } + + // ── 开发环境取消 ── + console.log('[DEV] 开发环境 ======'); + const devResults = await revokePermission(devConn, permIdNum, '[DEV]'); + for (const r of devResults) { + const icon = r.status === 'ok' ? '✅' : r.status === 'skip' ? '⏭️' : r.status === 'wildcard' ? '🔹' : '❌'; + const extra = r.status === 'ok' ? ` (剩余${r.count}个权限)` : ''; + console.log(` ${icon} ${r.role.name}(${r.role.id}): ${r.msg}${extra}`); + } + await devConn.end(); + + // ── 生产环境取消 ── + console.log('\n[PROD] 生产环境 ======'); + let prodConn; + try { + prodConn = await createConnection('production'); + } catch (e) { + console.error(` 生产环境连接失败: ${e.message}`); + process.exit(1); + } + + const prodResults = await revokePermission(prodConn, permIdNum, '[PROD]'); + for (const r of prodResults) { + const icon = r.status === 'ok' ? '✅' : r.status === 'skip' ? '⏭️' : r.status === 'wildcard' ? '🔹' : '❌'; + const extra = r.status === 'ok' ? ` (剩余${r.count}个权限)` : ''; + console.log(` ${icon} ${r.role.name}(${r.role.id}): ${r.msg}${extra}`); + } + await prodConn.end(); + + console.log('\n═══════════════════════════════════════'); + console.log(' 取消授权完成'); + console.log('═══════════════════════════════════════'); +} + +main().catch(e => { + console.error('执行失败:', e.message); + process.exit(1); +}); From 807fddccc55f394e8aaf18896454ee9163d8677a Mon Sep 17 00:00:00 2001 From: liufumingren Date: Tue, 4 Aug 2026 21:28:26 +0800 Subject: [PATCH 171/550] =?UTF-8?q?fix(express=5Fplatform):=20package=5Fin?= =?UTF-8?q?fo=20=E5=A2=9E=E5=8A=A0=20id=20=E4=BD=9C=E4=B8=BA=E5=94=AF?= =?UTF-8?q?=E4=B8=80=E4=B8=9A=E5=8A=A1=E9=94=AE=E6=94=AF=E6=8C=81=E6=8B=86?= =?UTF-8?q?=E5=8D=95=20--=20story=3Dsym:package=5Finfo?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/systems/express_platform.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/app/service/systems/express_platform.js b/app/service/systems/express_platform.js index c4923d1..b3c40e9 100644 --- a/app/service/systems/express_platform.js +++ b/app/service/systems/express_platform.js @@ -1776,6 +1776,7 @@ class ExpressPlatformService extends MainService { count: item.plan_qty, })) || [], goods_description: '物品', + id:`${orderDelivery.warehouse_id}_${orderDelivery.id}_${order_tmp.business_key}`, }, recipient: { address: { @@ -2355,6 +2356,7 @@ class ExpressPlatformService extends MainService { name: item.item_name || '商品', count: item.plan_qty, })) || [], + id:`${order_tmp.order_delivery.warehouse_id}_${order_tmp.order_delivery.id}_${order_tmp.business_key}`, }, recipient: { address: { From f00b4be1fbea56820f9b7429903cdd7f576e03b8 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Wed, 5 Aug 2026 14:55:29 +0800 Subject: [PATCH 172/550] =?UTF-8?q?=E5=B0=8F=E7=BA=A2=E4=B9=A6=E5=BF=AB?= =?UTF-8?q?=E9=80=92=E5=8F=96=E5=8F=B7=E6=B8=A0=E9=81=93=E8=A1=A5=E5=85=85?= =?UTF-8?q?mobile=E5=AD=97=E6=AE=B5=E5=85=A5=E5=8F=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/systems/express_platform.js | 1 + 1 file changed, 1 insertion(+) diff --git a/app/service/systems/express_platform.js b/app/service/systems/express_platform.js index b3c40e9..a2d3907 100644 --- a/app/service/systems/express_platform.js +++ b/app/service/systems/express_platform.js @@ -746,6 +746,7 @@ class ExpressPlatformService extends MainService { company: listByWarehousePlatformCode.shop_name || '', name: listByWarehousePlatformCode.sender_name || '', phone: listByWarehousePlatformCode.sender_tel || '', + mobile: order.sys_platform_code === 'XHS' ? listByWarehousePlatformCode.sender_tel : undefined, country: 'CN', city: listByWarehousePlatformCode.city_name || '', province: listByWarehousePlatformCode.province_name || '', From b00e320262bed4750ba6de364454602344594d3e Mon Sep 17 00:00:00 2001 From: liufumingren Date: Wed, 5 Aug 2026 22:46:22 +0800 Subject: [PATCH 173/550] fix(db): expand item_snapshot_key to VARCHAR(1024) to prevent Data too long error - wave_batch.item_snapshot_key: 255 -> 1024, full index -> prefix index(191) - inbox-menu-permissions: INSERT -> INSERT IGNORE for idempotent production rerun --- app/model/wave_batch.js | 6 +- ...260805130000-add-inbox-menu-permissions.js | 73 +++++++++++++++ ...20260805160000-expand-item-snapshot-key.js | 90 +++++++++++++++++++ 3 files changed, 166 insertions(+), 3 deletions(-) create mode 100644 database/migrations/20260805130000-add-inbox-menu-permissions.js create mode 100644 database/migrations/20260805160000-expand-item-snapshot-key.js diff --git a/app/model/wave_batch.js b/app/model/wave_batch.js index 38d4c5f..af3f43a 100644 --- a/app/model/wave_batch.js +++ b/app/model/wave_batch.js @@ -141,9 +141,9 @@ module.exports = app => { comment: '快递名称(区分快递时参与匹配)', }, item_snapshot_key: { - type: STRING(255), + type: STRING(1024), allowNull: true, - comment: '结构快照键', + comment: '结构快照键(与 item_detail_machine 一致,1024 长度以容纳多商品订单的快照)', }, }, { tableName: 'wms_wave_batch', @@ -172,7 +172,7 @@ module.exports = app => { }, { name: 'idx_wave_snapshot_key', - fields: [ 'item_snapshot_key' ], + fields: [{ name: 'item_snapshot_key', length: 191 }], }, { name: 'idx_wave_item_machine_prefix', diff --git a/database/migrations/20260805130000-add-inbox-menu-permissions.js b/database/migrations/20260805130000-add-inbox-menu-permissions.js new file mode 100644 index 0000000..6306340 --- /dev/null +++ b/database/migrations/20260805130000-add-inbox-menu-permissions.js @@ -0,0 +1,73 @@ +'use strict'; + +/** + * 新增「消息和自动回复」根菜单及「群列表」「消息记录」子页面。 + * + * 固定 ID(开发库 & 生产库 wms_permission 当前 max_id 均为 491): + * 492 — 父级菜单 "消息和自动回复" + * 493 — inbox.groups(群列表) + * 494 — inbox.messages(消息记录) + * + * 授权角色(permissions 不为 "*" 的 主管/经理 级角色): + * 8 — 经理 + * 26 — 仓库组-主管 + * 28 — 客服组-主管 + * 29 — 生产组-主管 + */ +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + // ── 1. 插入父级权限 (type=web_pages, sort=13) ── + // 使用 INSERT IGNORE 兼容生产环境已有数据(路径相同但名称可能略有差异) + await queryInterface.sequelize.query(` + INSERT IGNORE INTO wms_permission (id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at) + VALUES (492, '/inbox', NULL, '消息和自动回复', NULL, '消息和自动回复', NULL, 0, 0, NULL, 'web_pages', 13, 1, NOW(), NOW()) + `); + + // ── 2. 插入子页面权限 ── + // 群列表 + await queryInterface.sequelize.query(` + INSERT IGNORE INTO wms_permission (id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at) + VALUES (493, '/inbox/groups', NULL, 'inbox.groups', NULL, '群列表', NULL, 0, 0, 492, 'web_pages', 0, 1, NOW(), NOW()) + `); + + // 消息记录 + await queryInterface.sequelize.query(` + INSERT IGNORE INTO wms_permission (id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at) + VALUES (494, '/inbox/messages', NULL, 'inbox.messages', NULL, '消息记录', NULL, 0, 0, 492, 'web_pages', 1, 1, NOW(), NOW()) + `); + + // ── 3. 给 客服组-主管及以上角色 追加权限 ID(幂等:已包含则跳过)── + const newIdSuffix = ', 492, 493, 494'; + + await queryInterface.sequelize.query(` + UPDATE wms_role + SET permissions = CONCAT(LEFT(permissions, LENGTH(permissions) - 1), '${newIdSuffix}]') + WHERE id IN (8, 26, 28, 29) + AND permissions != '*' + AND permissions IS NOT NULL + AND LENGTH(permissions) > 2 + AND permissions NOT LIKE '% 492,%' + `); + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + // ── 1. 从角色权限中移除新增的 ID ── + await queryInterface.sequelize.query(` + UPDATE wms_role + SET permissions = REPLACE(permissions, ', 492, 493, 494', '') + WHERE id IN (8, 26, 28, 29) + `); + + // ── 2. 删除子页面权限 ── + await queryInterface.sequelize.query( + 'DELETE FROM wms_permission WHERE id IN (493, 494)' + ); + + // ── 3. 删除父级权限 ── + await queryInterface.sequelize.query( + 'DELETE FROM wms_permission WHERE id = 492' + ); + }, +}; diff --git a/database/migrations/20260805160000-expand-item-snapshot-key.js b/database/migrations/20260805160000-expand-item-snapshot-key.js new file mode 100644 index 0000000..d7914cb --- /dev/null +++ b/database/migrations/20260805160000-expand-item-snapshot-key.js @@ -0,0 +1,90 @@ +'use strict'; + +/** + * 扩大 wms_wave_batch.item_snapshot_key 列容量以容纳多商品订单的快照键。 + * + * 背景: + * buildItemSnapshotKey 将订单中每个商品的 stock_id、item_code、 + * item_name、barcode、quantity 用 :: 拼接,多个商品再用 | 连接。 + * 当订单包含较多商品或商品名较长时,快照键极易超过原 VARCHAR(255) 上限, + * 导致 INSERT 时报 "Data too long for column 'item_snapshot_key'"。 + * + * 变更: + * 1. item_snapshot_key: VARCHAR(255) → VARCHAR(1024) + * (与 item_detail_machine 容量保持一致) + * 2. 索引 idx_wave_snapshot_key: 全列索引 → 前缀索引(191) + * (与 idx_wave_item_machine_prefix 前缀长度一致, + * 兼容 utf8mb4 下的 InnoDB 索引键长度限制) + */ +module.exports = { + // eslint-disable-next-line no-unused-vars + up: async (queryInterface, Sequelize) => { + // ── 1. 先删旧全列索引(否则 changeColumn 1024 会触发 3072 字节限制)── + try { + await queryInterface.removeIndex('wms_wave_batch', 'idx_wave_snapshot_key'); + console.log('[migrate] 已移除旧全列索引 idx_wave_snapshot_key'); + } catch (e) { + // 索引可能不存在(如全新库或已执行过),忽略 + const msg = String(e.message || ''); + if (!msg.includes('check that it exists') && !msg.includes('exist')) { + console.warn('[migrate] 移除索引 idx_wave_snapshot_key 时出现非预期错误:', msg); + } + } + + // ── 2. 修改列容量 ── + await queryInterface.changeColumn('wms_wave_batch', 'item_snapshot_key', { + type: Sequelize.STRING(1024), + allowNull: true, + comment: '结构快照键(与 item_detail_machine 一致,1024 长度以容纳多商品订单的快照)', + }); + console.log('[migrate] wms_wave_batch.item_snapshot_key VARCHAR(255) → VARCHAR(1024)'); + + // ── 3. 创建前缀索引 ── + try { + await queryInterface.sequelize.query( + 'ALTER TABLE wms_wave_batch ADD INDEX idx_wave_snapshot_key (item_snapshot_key(191))' + ); + console.log('[migrate] 已创建前缀索引 idx_wave_snapshot_key(item_snapshot_key(191))'); + } catch (e) { + if (e.message && e.message.includes('Duplicate')) { + console.log('[migrate] 前缀索引 idx_wave_snapshot_key 已存在,跳过'); + } else { + throw e; + } + } + }, + + // eslint-disable-next-line no-unused-vars + down: async (queryInterface, Sequelize) => { + // ── 还原索引为全列索引 ── + try { + await queryInterface.removeIndex('wms_wave_batch', 'idx_wave_snapshot_key'); + console.log('[migrate:down] 已移除前缀索引 idx_wave_snapshot_key'); + } catch (e) { + if (!(e.message && e.message.includes('check that it exists'))) { + console.warn('[migrate:down] 移除索引时出现非预期错误:', e.message); + } + } + + try { + await queryInterface.sequelize.query( + 'ALTER TABLE wms_wave_batch ADD INDEX idx_wave_snapshot_key (item_snapshot_key)' + ); + console.log('[migrate:down] 已还原全列索引 idx_wave_snapshot_key'); + } catch (e) { + if (e.message && e.message.includes('Duplicate')) { + console.log('[migrate:down] 全列索引 idx_wave_snapshot_key 已存在,跳过'); + } else { + throw e; + } + } + + // ── 还原列容量 ── + await queryInterface.changeColumn('wms_wave_batch', 'item_snapshot_key', { + type: Sequelize.STRING(255), + allowNull: true, + comment: '结构快照键', + }); + console.log('[migrate:down] wms_wave_batch.item_snapshot_key VARCHAR(1024) → VARCHAR(255)'); + }, +}; From 7ab67b239acb1bbd2de34887d236f77107ca52f4 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Wed, 5 Aug 2026 22:46:58 +0800 Subject: [PATCH 174/550] =?UTF-8?q?feat:=20=E8=AE=A2=E5=8D=95=E5=88=97?= =?UTF-8?q?=E8=A1=A8=E6=96=B0=E5=A2=9E=20stock=5Fquery=20=E5=95=86?= =?UTF-8?q?=E5=93=81=E6=A8=A1=E7=B3=8A=E6=9F=A5=E8=AF=A2=E6=9D=A1=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 所有订单列表接口支持通过 where.stock_query 进行商品维度的模糊筛选: - 模糊匹配 stock_warehouse 的 item_code(商品编码)、item_name(商品名称)、id(主键) - 模糊匹配 stock_barcodes 的 barcode(条码) - 通过 order_items 关联查找匹配的订单 ID 并过滤订单列表 涉及方法: - base.js: listByModule(覆盖 9 个订单列表入口) - wave.js: groupOrderFetchList / singleOrderFetchList / waveStrategyFallbackOrderList - recheckOrder.js: queryRecheckOrderSingleList / queryRecheckOrderGroupList --- app/service/systemMethods/order/base.js | 135 +++++++++++++++++- .../systemMethods/order/recheckOrder.js | 46 ++++++ app/service/systemMethods/order/wave.js | 39 ++++- 3 files changed, 218 insertions(+), 2 deletions(-) diff --git a/app/service/systemMethods/order/base.js b/app/service/systemMethods/order/base.js index 9b6354f..047bc41 100644 --- a/app/service/systemMethods/order/base.js +++ b/app/service/systemMethods/order/base.js @@ -946,6 +946,34 @@ class OrderBaseService extends MainService { return { where: normalizedWhere, buyerMessageHas: null }; } + /** + * 提取 stock_query 虚拟筛选条件。 + * 将其从 where 中移除并返回清洗后的 where 与 stock_query 关键字。 + * @param {Object} whereInput 标准化后的 where 条件。 + * @return {{ where: Object, stockQuery: string }} 清洗后的 where 与 stock_query 值。 + */ + extractStockQueryVirtualFilter(whereInput = {}) { + const normalizedWhere = this.isPlainObject(whereInput) + ? { ...whereInput } + : {}; + const stockQueryCondition = normalizedWhere.stock_query; + + delete normalizedWhere.stock_query; + + if (!stockQueryCondition) { + return { where: normalizedWhere, stockQuery: '' }; + } + + const rawValue = this.isPlainObject(stockQueryCondition) + && Object.prototype.hasOwnProperty.call(stockQueryCondition, 'value') + ? stockQueryCondition.value + : stockQueryCondition; + + const stockQuery = typeof rawValue === 'string' ? rawValue.trim() : ''; + + return { where: normalizedWhere, stockQuery }; + } + /** * 构建 buyer_message_has 虚拟字段的 Sequelize where 条件。 * 覆盖三个留言/备注字段:buyer_message、seller_message、remark。 @@ -1080,6 +1108,105 @@ class OrderBaseService extends MainService { .filter(orderId => Number.isFinite(orderId) && orderId > 0))); } + /** + * 根据 stock_query 模糊查询 stock_warehouse(商品编码、商品名称、主键ID)和 stock_barcodes(条码), + * 找到匹配的 stock_id,再通过 order_items 查找关联的订单 ID。 + * 若未匹配到任何 stock 则返回空数组,下游会将订单列表结果置空。 + * @param {string} stockQuery 模糊查询关键词。 + * @param {string} moduleName 模块名称(用于确定 order_items 表类型)。 + * @param {number|string} [warehouseId] 仓库ID。 + * @return {Promise} 命中的订单ID列表。 + */ + async findOrderIdsByStockQuery(stockQuery = '', moduleName = 'order', warehouseId = null) { + const contextWarehouseId = this.getWarehouseId(); + + if (contextWarehouseId === null || contextWarehouseId === undefined || contextWarehouseId === '') { + throw new Error('缺少当前用户仓库上下文 store_id'); + } + + if (warehouseId !== null && warehouseId !== undefined && warehouseId !== '' + && String(warehouseId) !== String(contextWarehouseId)) { + throw new Error('订单工作台仓库ID必须来自当前用户上下文 store_id,禁止传入外部仓库ID。'); + } + + if (!stockQuery || typeof stockQuery !== 'string') { + return []; + } + + const trimmedQuery = stockQuery.trim(); + if (!trimmedQuery) { + return []; + } + + const { Op } = this.app.Sequelize; + const likePattern = `%${trimmedQuery}%`; + + // 第一步:从 stock_warehouse 模糊查询 item_code、item_name 和 id + const stockWarehouseModel = this.ctx.model && this.ctx.model.StockWarehouse; + const stockIdsFromWarehouse = []; + if (stockWarehouseModel) { + const stockRows = await stockWarehouseModel.findAll({ + where: { + warehouse_id: contextWarehouseId, + is_valid: 'Y', + [Op.or]: [ + { item_code: { [Op.like]: likePattern } }, + { item_name: { [Op.like]: likePattern } }, + { id: { [Op.like]: likePattern } }, + ], + }, + attributes: [ 'id' ], + raw: true, + }); + for (const row of stockRows) { + stockIdsFromWarehouse.push(Number(row.id)); + } + } + + // 第二步:从 stock_barcodes 模糊查询 barcode + const stockBarcodeModel = this.ctx.model && this.ctx.model.StockBarcode; + const stockIdsFromBarcodes = []; + if (stockBarcodeModel) { + const barcodeRows = await stockBarcodeModel.findAll({ + where: { + warehouse_id: contextWarehouseId, + barcode: { [Op.like]: likePattern }, + }, + attributes: [ 'stock_id' ], + raw: true, + }); + for (const row of barcodeRows) { + stockIdsFromBarcodes.push(Number(row.stock_id)); + } + } + + // 第三步:合并去重所有匹配的 stock_id + const allStockIds = Array.from(new Set([ ...stockIdsFromWarehouse, ...stockIdsFromBarcodes ])) + .filter(id => Number.isFinite(id) && id > 0); + + if (allStockIds.length === 0) { + return []; + } + + // 第四步:通过 order_items 查找关联的 order_id + const moduleConfig = this.getModuleConfig(moduleName); + const tableType = moduleConfig.modelType || 'current'; + const orderItemsModel = await this.getOrderItemsModelByTableType(tableType, contextWarehouseId); + const orderItemRows = await orderItemsModel.findAll({ + where: { + stock_id: { [Op.in]: allStockIds }, + }, + attributes: [ 'order_id' ], + raw: true, + }); + + return Array.from(new Set( + (Array.isArray(orderItemRows) ? orderItemRows : []) + .map(row => Number(row && row.order_id)) + .filter(orderId => Number.isFinite(orderId) && orderId > 0) + )); + } + /** * 将命中的订单ID并入 Sequelize where 条件。 * @param {Object} queryWhere 原始 where 条件。 @@ -1247,7 +1374,8 @@ class OrderBaseService extends MainService { }); const { where: sanitizedWhere, expressNumbers } = this.extractOrderListExpressVirtualFilter(where); const { where: whereAfterBuyerMessage, buyerMessageHas } = this.extractBuyerMessageHasVirtualFilter(sanitizedWhere); - const mergedWhere = this.mergeWhereObjects(this.getDefaultWhere(moduleName), whereAfterBuyerMessage); + const { where: whereAfterStockQuery, stockQuery } = this.extractStockQueryVirtualFilter(whereAfterBuyerMessage); + const mergedWhere = this.mergeWhereObjects(this.getDefaultWhere(moduleName), whereAfterStockQuery); let queryWhere = this.buildWhere(mergedWhere, contextWarehouseId, { specialFieldMap: { quickWhere: { @@ -1266,6 +1394,11 @@ class OrderBaseService extends MainService { queryWhere = this.appendConditionToWhere(queryWhere, buyerMessageCondition); } + if (stockQuery) { + const stockOrderIds = await this.findOrderIdsByStockQuery(stockQuery, moduleName, contextWarehouseId); + queryWhere = this.appendOrderIdsFilterToWhere(queryWhere, stockOrderIds); + } + const model = await this.getOrderModel(moduleName, contextWarehouseId); const order = this.buildListOrder(requestData.sort, moduleName); const offset = (page - 1) * pageSize; diff --git a/app/service/systemMethods/order/recheckOrder.js b/app/service/systemMethods/order/recheckOrder.js index dd34ba5..ccde821 100644 --- a/app/service/systemMethods/order/recheckOrder.js +++ b/app/service/systemMethods/order/recheckOrder.js @@ -3237,6 +3237,29 @@ class RecheckOrderService extends OrderBaseService { replacements.pickStatus = pickStatus; } + // stock_query 商品模糊筛选:通过 stock_warehouse / stock_barcodes → order_items → order_id + const stockQuery = String(where.stock_query || '').trim(); + if (stockQuery) { + const stockOrderIds = await this.findOrderIdsByStockQuery(stockQuery, 'order', warehouseId); + if (stockOrderIds.length > 0) { + conditions.push('o.id IN (:stockOrderIds)'); + replacements.stockOrderIds = stockOrderIds; + } else { + // 未匹配到任何商品,直接返回空列表 + return this.success('ok', { + list: [], + pagination: { + page, + pageSize, + total: 0, + totalPages: 0, + hasPrevious: false, + hasNext: false, + }, + }); + } + } + const whereClause = conditions.length > 0 ? `WHERE ${conditions.join('\n AND ')}` : ''; @@ -3365,6 +3388,29 @@ class RecheckOrderService extends OrderBaseService { replacements.waveStatus = waveStatus; } + // stock_query 商品模糊筛选:通过 stock_warehouse / stock_barcodes → order_items → order_id 过滤波次 + const stockQuery = String(where.stock_query || '').trim(); + if (stockQuery) { + const stockOrderIds = await this.findOrderIdsByStockQuery(stockQuery, 'order', warehouseId); + if (stockOrderIds.length > 0) { + conditions.push('o.id IN (:stockOrderIds)'); + replacements.stockOrderIds = stockOrderIds; + } else { + // 未匹配到任何商品,直接返回空列表 + return this.success('ok', { + list: [], + pagination: { + page, + pageSize, + total: 0, + totalPages: 0, + hasPrevious: false, + hasNext: false, + }, + }); + } + } + const whereClause = conditions.length > 0 ? `WHERE ${conditions.join('\n AND ')}` : ''; diff --git a/app/service/systemMethods/order/wave.js b/app/service/systemMethods/order/wave.js index 451a2ec..db41349 100644 --- a/app/service/systemMethods/order/wave.js +++ b/app/service/systemMethods/order/wave.js @@ -2145,6 +2145,7 @@ class WaveService extends OrderBaseService { const shopName = this.normalizeShopName(requestData.shop_name); const includeSku = this.normalizeSkuText(requestData.include_sku); const returnOrderIds = this.normalizeBoolean(requestData.return_order_ids, false); + const stockQuery = String(requestData.stock_query || '').trim(); const { page, pageSize } = this.normalizePagination(requestData); const where = { @@ -2164,6 +2165,20 @@ class WaveService extends OrderBaseService { where.shop_nick = { [Op.like]: `%${shopName}%` }; } + // stock_query 商品模糊筛选:通过 stock_warehouse / stock_barcodes → order_items → 限定候选订单范围 + if (stockQuery) { + const stockOrderIds = await this.findOrderIdsByStockQuery(stockQuery, 'order', warehouseId); + if (stockOrderIds.length > 0) { + where.id = { [Op.in]: stockOrderIds }; + } else { + // 未匹配到任何商品,直接返回空列表 + return { + list: [], + pagination: { page, pageSize, total: 0, totalPages: 0, hasPrevious: false, hasNext: false }, + }; + } + } + // Phase 1: 主表全量查询,用 items_hash 做分组基准 const rawOrders = await model.findAll({ where, @@ -2383,6 +2398,7 @@ class WaveService extends OrderBaseService { const shopName = this.normalizeShopName(requestData.shop_name); const includeSku = this.normalizeSkuText(requestData.include_sku); const returnOrderIds = this.normalizeBoolean(requestData.return_order_ids, false); + const stockQuery = String(requestData.stock_query || '').trim(); const { page, pageSize } = this.normalizePagination(requestData); const where = { @@ -2402,6 +2418,20 @@ class WaveService extends OrderBaseService { where.shop_nick = { [Op.like]: `%${shopName}%` }; } + // stock_query 商品模糊筛选:通过 stock_warehouse / stock_barcodes → order_items → 限定候选订单范围 + if (stockQuery) { + const stockOrderIds = await this.findOrderIdsByStockQuery(stockQuery, 'order', warehouseId); + if (stockOrderIds.length > 0) { + where.id = { [Op.in]: stockOrderIds }; + } else { + // 未匹配到任何商品,直接返回空列表 + return { + list: [], + pagination: { page, pageSize, total: 0, totalPages: 0, hasPrevious: false, hasNext: false }, + }; + } + } + // Phase 1: 主表全量查询,用 items_hash 做分组基准 const rawOrders = await model.findAll({ where, @@ -4000,8 +4030,9 @@ class WaveService extends OrderBaseService { ); const { where: sanitizedWhere, expressNumbers } = this.extractOrderListExpressVirtualFilter(ctxWhere); const { where: whereAfterBuyerMessage, buyerMessageHas } = this.extractBuyerMessageHasVirtualFilter(sanitizedWhere); + const { where: whereAfterStockQuery, stockQuery } = this.extractStockQueryVirtualFilter(whereAfterBuyerMessage); const defaultWhere = this.getDefaultWhere('waveStrategyFallbackOrder'); - const mergedWhere = this.mergeWhereObjects(defaultWhere, whereAfterBuyerMessage); + const mergedWhere = this.mergeWhereObjects(defaultWhere, whereAfterStockQuery); let queryWhere = this.buildWhere(mergedWhere, contextWarehouseId, { specialFieldMap: { quickWhere: { bucket: 'quick' } }, }); @@ -4017,6 +4048,12 @@ class WaveService extends OrderBaseService { queryWhere = this.appendConditionToWhere(queryWhere, buyerMessageCondition); } + // 处理 stock_query 虚拟筛选 + if (stockQuery) { + const stockOrderIds = await this.findOrderIdsByStockQuery(stockQuery, 'waveStrategyFallbackOrder', contextWarehouseId); + queryWhere = this.appendOrderIdsFilterToWhere(queryWhere, stockOrderIds); + } + // 追加 OR 条件:未匹配策略(wave_scan_result=2) 或 已完全打印被排除(print_status='fin') const { Sequelize } = this.app; queryWhere = { From 4f41e735a96a61f0ceca43366a9bfb750bb6b6d4 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Wed, 5 Aug 2026 22:52:53 +0800 Subject: [PATCH 175/550] =?UTF-8?q?feat(pick):=20wavePickTaskDetail=20?= =?UTF-8?q?=E5=93=8D=E5=BA=94=20task=20=E5=AF=B9=E8=B1=A1=E6=96=B0?= =?UTF-8?q?=E5=A2=9E=20wave=5Fno=20=E5=AD=97=E6=AE=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 从 wms_wave_pick_task_wave JOIN wms_wave_batch 查询波次号,查询失败时降级为空字符串。同步更新 methods/system.json 文档与 changes 记录。 --- app/service/systems/pick.js | 24 +++ methods/changes/system.json | 32 ++++ methods/system.json | 317 +++++++++++++++++++++++++++++++++++- 3 files changed, 371 insertions(+), 2 deletions(-) diff --git a/app/service/systems/pick.js b/app/service/systems/pick.js index 3937e23..de8bc96 100644 --- a/app/service/systems/pick.js +++ b/app/service/systems/pick.js @@ -973,6 +973,29 @@ class PickSystemService extends Service { const warehouseId = Number(taskRow.warehouse_id || 0); const pickMode = Number(taskRow.pick_mode || 0); + + // 查询任务关联的波次号 + let taskWaveNo = ''; + try { + const taskWaveNoRows = await ctx.model.query(` + SELECT + wb.wave_no + FROM wms_wave_pick_task_wave ptw + INNER JOIN wms_wave_batch wb ON wb.wave_id = ptw.wave_id + WHERE ptw.task_id = :taskId + ORDER BY ptw.id ASC + LIMIT 1 + `, { + replacements: { taskId }, + type: ctx.model.QueryTypes.SELECT, + }); + taskWaveNo = Array.isArray(taskWaveNoRows) && taskWaveNoRows.length > 0 + ? String(taskWaveNoRows[0].wave_no || '').trim() + : ''; + } catch (error) { + ctx.logger.warn(`[pick.wavePickTaskDetail] 查询波次号失败,将降级为空: ${error.message}`); + } + const taskOrderColumnSet = await this.getTableColumnSet('wms_wave_pick_task_order'); const taskWaveColumnSet = await this.getTableColumnSet('wms_wave_pick_task_wave'); const boxColumnSet = await this.getTableColumnSet('wms_wave_pick_task_box'); @@ -1312,6 +1335,7 @@ class PickSystemService extends Service { task: { task_id: Number(taskRow.task_id || 0), task_no: String(taskRow.task_no || '').trim(), + wave_no: taskWaveNo, status: Number(taskRow.status || 0), pick_mode: pickMode, start_at: taskRow.start_at || null, diff --git a/methods/changes/system.json b/methods/changes/system.json index 44abf26..bc780e4 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,24 @@ [ + { + "version": "2026.08.05-inbox-group", + "date": "2026-08-05", + "type": "added", + "summary": "站内信模块新增群管理接口:群列表拉取、群禁用/解禁、群信息修改(支持群类型/子类型/货主/快递接口/系统快递编码)、按群查询消息列表。仓库ID由服务端自动注入。express_interfaces输出为数组,systemExpressCode在express类型时必填校验。", + "methods": [ + "inbox.group.list", + "inbox.group.disable", + "inbox.group.update", + "inbox.group.messages" + ], + "notes": [ + "inbox.group.list:按群类型/关键词筛选,分页返回。express_interfaces 存储逗号分隔输出数组。", + "inbox.group.disable:通过群主键ID禁用/解禁(isBlocked=1禁用/0启用)。", + "inbox.group.update:支持修改groupType/subType/storeId/expressInterfaces/systemExpressCode。切换为express类型时systemExpressCode必填且需校验wms_express.code存在,expressInterfaces需校验wms_express_interface.id存在。非express类型忽略express相关字段。", + "inbox.group.messages:按groupId拉取消息列表,支持direction/keyword筛选,仓库隔离,查询命中idx_warehouse_group_created索引。", + "公共:所有方法warehouseId均从ctx.user.store_id自动注入,前端无需传递。" + ], + "module": "inbox" + }, { "version": "2026.08.01-system-01", "date": "2026-08-01", @@ -5299,5 +5319,17 @@ "新增store_ids限定货主ID" ], "module": "storeExpressBindingPolicy" + }, + { + "version": "2026-08-05-wavePickTaskDetail-waveNo", + "date": "2026-08-05", + "summary": "pick.wavePickTaskDetail 响应 task 对象新增 wave_no 字段,从 wms_wave_pick_task_wave 关联 wms_wave_batch 获取波次号", + "methods": [ + "pick.wavePickTaskDetail" + ], + "notes": [ + "task 对象新增 wave_no(string)字段,位于 task_no 之后;查询失败时降级为空字符串。", + "数据来源:wms_wave_pick_task_wave INNER JOIN wms_wave_batch ON wave_id。" + ] } ] diff --git a/methods/system.json b/methods/system.json index 679e87a..00db843 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1,8 +1,8 @@ { "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", - "version": "0.3.17", - "updatedAt": "2026-08-04", + "version": "0.3.18", + "updatedAt": "2026-08-05", "headers": [ { "name": "platform", @@ -17757,6 +17757,12 @@ "description": "任务编号", "required": false }, + { + "name": "wave_no", + "type": "string", + "description": "波次号,从 wms_wave_pick_task_wave 关联 wms_wave_batch 获取;无关联波次时为空字符串", + "required": false + }, { "name": "status", "type": "number", @@ -32452,6 +32458,313 @@ "message": "warehouseId 无效" } ] + }, + { + "method": "inbox.bindCode", + "description": "生成货主绑群码。传入货主ID和子类型,生成5分钟有效12位随机码存入缓存", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(从中解析 warehouseId 仓库上下文)" + } + ], + "params": [ + { + "name": "storeId", + "type": "number", + "required": true, + "source": "body", + "description": "货主ID" + }, + { + "name": "subType", + "type": "string", + "required": false, + "source": "body", + "description": "群子类型编码:after_sales(售后) / finance(财务) / receiving(收货)" + } + ], + "response": [ + { + "name": "code", + "type": "string", + "required": true, + "description": "12位绑群随机码,5分钟有效" + } + ], + "errors": [ + { + "code": "400", + "message": "storeId 无效 / 缺少仓库信息" + }, + { + "code": "500", + "message": "货主在仓库无有效合约" + } + ] + }, + { + "method": "inbox.group.list", + "description": "拉取当前仓库的群列表,支持按群类型筛选和关键词搜索,express_interfaces 逗号分隔存储输出为数组", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(从中解析 warehouseId 仓库上下文)" + } + ], + "params": [ + { + "name": "groupType", + "type": "string", + "required": false, + "source": "body", + "description": "群类型筛选:store(货主) / warehouse(仓库) / express(快递)" + }, + { + "name": "keyword", + "type": "string", + "required": false, + "source": "body", + "description": "群名称模糊搜索" + }, + { + "name": "page", + "type": "number", + "required": false, + "source": "body", + "description": "页码,默认1" + }, + { + "name": "pageSize", + "type": "number", + "required": false, + "source": "body", + "description": "每页条数,默认20,最大100" + } + ], + "response": [ + { + "name": "total", + "type": "number", + "required": true, + "description": "总记录数" + }, + { + "name": "list", + "type": "array", + "required": true, + "description": "群记录列表,含id/group_name/group_id/store_id/group_type/sub_type/is_blocked/express_interfaces(数组)/system_express_code/created_at" + } + ], + "errors": [ + { + "code": "400", + "message": "warehouseId 无效" + } + ] + }, + { + "method": "inbox.group.disable", + "description": "禁用或解禁群,通过群主键ID操作", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(从中解析 warehouseId 仓库上下文)" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "群记录主键ID" + }, + { + "name": "isBlocked", + "type": "number", + "required": false, + "source": "body", + "description": "是否禁用:1=禁用 0=启用,默认1" + } + ], + "response": [ + { + "name": "message", + "type": "string", + "required": true, + "description": "操作结果提示:群已禁用 / 群已启用" + } + ], + "errors": [ + { + "code": "400", + "message": "群ID无效 / warehouseId 无效" + }, + { + "code": "500", + "message": "群不存在或无权限操作" + } + ] + }, + { + "method": "inbox.group.update", + "description": "修改群信息:群类型/子类型/货主/快递接口/系统快递编码。切换为express类型时systemExpressCode必填,expressInterfaces仅express类型生效", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(从中解析 warehouseId 仓库上下文)" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "群记录主键ID" + }, + { + "name": "groupType", + "type": "string", + "required": false, + "source": "body", + "description": "群类型:store(货主) / warehouse(仓库) / express(快递)" + }, + { + "name": "subType", + "type": "string", + "required": false, + "source": "body", + "description": "群子类型:after_sales(售后) / finance(财务) / receiving(收货)" + }, + { + "name": "storeId", + "type": "number", + "required": false, + "source": "body", + "description": "关联货主ID" + }, + { + "name": "expressInterfaces", + "type": "array", + "required": false, + "source": "body", + "description": "快递接口ID数组,仅groupType=express时生效。空数组表示全部快递类型。需校验wms_express_interface.id存在" + }, + { + "name": "systemExpressCode", + "type": "string", + "required": false, + "source": "body", + "description": "系统快递编码,groupType=express时必填。需校验wms_express.code存在" + } + ], + "response": [ + { + "name": "message", + "type": "string", + "required": true, + "description": "操作结果提示:群信息修改成功" + } + ], + "errors": [ + { + "code": "400", + "message": "群ID无效 / 系统快递编码不能为空(express类型时)" + }, + { + "code": "500", + "message": "群不存在 / 系统快递编码不存在 / 快递接口ID无效" + } + ] + }, + { + "method": "inbox.group.messages", + "description": "按群拉取消息列表,支持方向/关键词筛选,分页返回。warehouseId服务端自动注入,查询命中idx_warehouse_group_created索引", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(从中解析 warehouseId 仓库上下文)" + } + ], + "params": [ + { + "name": "groupId", + "type": "string", + "required": true, + "source": "body", + "description": "群ID(必填)" + }, + { + "name": "direction", + "type": "string", + "required": false, + "source": "body", + "description": "消息方向筛选:inbound(入站) / outbound(出站)" + }, + { + "name": "keyword", + "type": "string", + "required": false, + "source": "body", + "description": "关键词搜索(ext_id / content)" + }, + { + "name": "page", + "type": "number", + "required": false, + "source": "body", + "description": "页码,默认1" + }, + { + "name": "pageSize", + "type": "number", + "required": false, + "source": "body", + "description": "每页条数,默认20,最大200" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "消息记录列表" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息:page/pageSize/total/totalPages/hasPrevious/hasNext" + } + ], + "errors": [ + { + "code": "400", + "message": "groupId 不能为空 / warehouseId 无效" + } + ] } ] }, From 11167434acb36313752d2ec2d3739d7034326d2b Mon Sep 17 00:00:00 2001 From: liufumingren Date: Wed, 5 Aug 2026 22:54:25 +0800 Subject: [PATCH 176/550] =?UTF-8?q?feat:=20=E4=BB=93=E5=BA=93=E8=AE=BE?= =?UTF-8?q?=E7=BD=AE=E6=96=B0=E5=A2=9E=20string=5Farray=20=E7=B1=BB?= =?UTF-8?q?=E5=9E=8B=E5=8F=8A=E8=87=AA=E5=8A=A8=E5=88=86=E9=85=8D=E5=BF=AB?= =?UTF-8?q?=E9=80=92=E6=8E=92=E9=99=A4=E5=A4=87=E6=B3=A8=E9=85=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增字段 auto_allocate_express_exclude_remarks,类型 string_array,默认 [],用于控制订单备注命中关键字时跳过自动分配快递。 修改文件: WAREHOUSE_SETTING_FIELDS 新增元数据定义; Store model DEFAULT_SUBJECT_CONFIG 补默认值 + normalizeSubjectConfig 补校验。 --- app/model/store.js | 22 ++++++++++++++++++++++ app/service/systems/setting/warehouse.js | 8 ++++++++ 2 files changed, 30 insertions(+) diff --git a/app/model/store.js b/app/model/store.js index 4708ea4..d31fb6a 100644 --- a/app/model/store.js +++ b/app/model/store.js @@ -46,6 +46,7 @@ module.exports = app => { max_notice_webhook_count: DEFAULT_MAX_NOTICE_WEBHOOK_COUNT, max_wave_quantity: DEFAULT_MAX_WAVE_QUANTITY, min_group_order_fetch_quantity: 13, + auto_allocate_express_exclude_remarks: [], default_express_code: 'STO', default_platform_code: 'TB', sender_name: '', @@ -240,6 +241,27 @@ module.exports = app => { normalized.min_group_order_fetch_quantity = minGroupOrderFetchQuantity; } + const rawExcludeRemarks = parsed.auto_allocate_express_exclude_remarks; + if (rawExcludeRemarks === undefined || rawExcludeRemarks === null || rawExcludeRemarks === '') { + normalized.auto_allocate_express_exclude_remarks = []; + } else { + if (!Array.isArray(rawExcludeRemarks)) { + throw new Error('subject_config.auto_allocate_express_exclude_remarks 必须是字符串数组'); + } + normalized.auto_allocate_express_exclude_remarks = rawExcludeRemarks + .map((item, index) => { + if (item === undefined || item === null || item === '') { + return null; + } + const trimmed = String(item).trim(); + if (trimmed === '') { + throw new Error(`subject_config.auto_allocate_express_exclude_remarks[${index}] 不能为空字符串`); + } + return trimmed; + }) + .filter(Boolean); + } + normalized.default_express_code = normalizeSubjectConfigText( parsed.default_express_code, DEFAULT_SUBJECT_CONFIG.default_express_code diff --git a/app/service/systems/setting/warehouse.js b/app/service/systems/setting/warehouse.js index 8dd1bfa..5cf0ca6 100644 --- a/app/service/systems/setting/warehouse.js +++ b/app/service/systems/setting/warehouse.js @@ -51,6 +51,14 @@ const WAREHOUSE_SETTING_FIELDS = Object.freeze([ required: false, description: '是否启用订单创建后自动加入团购波次,默认 false(关闭)', }), + Object.freeze({ + key: 'auto_allocate_express_exclude_remarks', + name: '自动分配快递排除备注', + type: 'string_array', + default: [], + required: false, + description: '订单备注命中任一关键字时,跳过自动分配快递,默认 [](不排除任何订单)', + }), Object.freeze({ key: 'default_express_code', name: '默认快递编码', From c25dffe8844e69a80cf93edf05ddb1637a77dd30 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Thu, 6 Aug 2026 17:38:49 +0800 Subject: [PATCH 177/550] =?UTF-8?q?feat(pick):=20=E5=85=88=E6=8B=A3?= =?UTF-8?q?=E5=90=8E=E5=88=86=E6=95=A3=E5=8D=95=E6=8B=A3=E8=B4=A7=E6=A8=A1?= =?UTF-8?q?=E5=BC=8F=E6=94=AF=E6=8C=81=20-=20box=5Fno=E6=8C=89=E5=BA=93?= =?UTF-8?q?=E4=BD=8D=E6=8E=92=E5=BA=8F=E5=B9=B6=E6=8C=89stock=5Fid?= =?UTF-8?q?=E5=88=86=E7=BB=84=E5=88=9B=E5=BB=BA=E6=A1=86=20-=20picking=5Fd?= =?UTF-8?q?etails=E5=92=8CscanOrder=E6=8C=89stock=5Fid=E6=98=A0=E5=B0=84bo?= =?UTF-8?q?x=5Fno=20-=20singleFetchByIds=E6=B3=A2=E6=AC=A1=E9=BB=98?= =?UTF-8?q?=E8=AE=A4=E5=85=88=E6=8B=A3=E5=90=8E=E5=88=86=E6=A8=A1=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../systemMethods/order/recheckOrder.js | 32 +- app/service/systemMethods/pick.js | 305 ++++++++++++++++-- app/service/systems/pick.js | 22 ++ 3 files changed, 326 insertions(+), 33 deletions(-) diff --git a/app/service/systemMethods/order/recheckOrder.js b/app/service/systemMethods/order/recheckOrder.js index ccde821..5790498 100644 --- a/app/service/systemMethods/order/recheckOrder.js +++ b/app/service/systemMethods/order/recheckOrder.js @@ -517,11 +517,41 @@ class RecheckOrderService extends OrderBaseService { // 批量查询包材推荐 const packageMaterialMap = await this.batchQueryPackageMaterialRecommendation(orders, warehouseId); - // 为每个订单附加 items_weight 和包材推荐 + // 查询任务框的 stock_id → box_no 映射(用于先拣后分等散单模式) + const taskId = pickerInfo.task_id; + const boxNoByStockId = new Map(); + if (taskId > 0) { + const { ctx } = this; + const boxRows = await ctx.model.query( + `SELECT ref_id, box_no + FROM wms_wave_pick_task_box + WHERE task_id = :taskId`, + { + replacements: { taskId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + for (const row of (Array.isArray(boxRows) ? boxRows : [])) { + const sid = Number(row.ref_id || 0); + const bno = Number(row.box_no || 0); + if (sid > 0 && bno > 0 && !boxNoByStockId.has(sid)) { + boxNoByStockId.set(sid, bno); + } + } + } + + // 为每个订单附加 items_weight、包材推荐和 stock 中的 box_no const enrichedOrders = orders.map(order => { const itemsHash = String(order.items_hash || '').trim(); + const enrichedStock = Array.isArray(order.stock) + ? order.stock.map(stockItem => ({ + ...stockItem, + box_no: boxNoByStockId.get(Number(stockItem.stock_id || 0)) || 0, + })) + : []; return { ...order, + stock: enrichedStock, items_weight: order.items_weight != null ? Number(order.items_weight) : 0, suggested_package_material: itemsHash ? (packageMaterialMap.get(itemsHash) || null) : null, }; diff --git a/app/service/systemMethods/pick.js b/app/service/systemMethods/pick.js index 5d33c75..762cc4f 100644 --- a/app/service/systemMethods/pick.js +++ b/app/service/systemMethods/pick.js @@ -258,46 +258,112 @@ class PickService extends MainService { ); if (normalizedOrderIds.length > 0) { - // 查询波次索引(wave_index),使 box_no 与 wms_order_wave_index.wave_index 一致 - const waveIndexMap = new Map(); - try { - const waveIndexRows = await ctx.model.query( - `SELECT order_id, wave_index - FROM wms_order_wave_index - WHERE warehouse_id = :warehouseId - AND wave_id = :waveId - AND order_id IN (:orderIds)`, + // 按库位排序并按 stock_id 分组,同 stock_id 的订单共享同一篮号 + const stockGroups = await this.resolveLocationSortedOrderIds( + normalizedOrderIds, + warehouseId, + transaction + ); + + // 写入 wms_wave_pick_task_box:每个 stock_id 一个框,记录 stock_id → box_no 映射 + const boxValuesSql = []; + const boxReplacements = {}; + let boxNo = 0; + let boxIndex = 0; + for (const group of stockGroups) { + boxNo += 1; + const stockId = group.stock_id > 0 ? group.stock_id : 0; + const boxNoKey = `boxNo${boxIndex}`; + const stockIdKey = `stockId${boxIndex}`; + const boxCodeKey = `boxCode${boxIndex}`; + boxValuesSql.push(`( + :taskId, + NULL, + :${boxCodeKey}, + :${boxNoKey}, + 1, + :${stockIdKey}, + NULL, + 0, + 0, + 0, + NULL, + NULL, + NULL, + :warehouseId, + NOW(), + NOW() + )`); + boxReplacements[boxNoKey] = boxNo; + boxReplacements[stockIdKey] = stockId; + boxReplacements[boxCodeKey] = `${taskNo}-S${boxNo}`; + boxIndex += 1; + } + + if (boxValuesSql.length > 0) { + await ctx.model.query( + ` + INSERT INTO wms_wave_pick_task_box ( + task_id, + order_id, + box_code, + box_no, + box_type, + ref_id, + ref_label, + required_qty, + picked_qty, + box_status, + review_result, + review_user_id, + review_time, + warehouse_id, + create_time, + update_time + ) VALUES ${boxValuesSql.join(',\n')} + `, { replacements: { + taskId, warehouseId, - waveId, - orderIds: normalizedOrderIds, + ...boxReplacements, }, - type: ctx.model.QueryTypes.SELECT, transaction, } ); - for (const wr of (Array.isArray(waveIndexRows) ? waveIndexRows : [])) { - const wrOrderId = Number(wr && wr.order_id || 0); - if (wrOrderId > 0) { - waveIndexMap.set(wrOrderId, Number(wr.wave_index || 0)); + + // 更新任务主表的 box_count + await ctx.model.query( + `UPDATE wms_wave_pick_task + SET box_count = :boxCount, + update_time = NOW() + WHERE id = :taskId`, + { + replacements: { taskId, boxCount: boxValuesSql.length }, + transaction, + } + ); + } + + // 写入 wms_wave_pick_task_order:每个订单写入一次(取该订单所属的最小 box_no) + const orderBoxMap = new Map(); + boxNo = 0; + for (const group of stockGroups) { + boxNo += 1; + for (const orderId of group.order_ids) { + if (!orderBoxMap.has(orderId) || orderBoxMap.get(orderId) > boxNo) { + orderBoxMap.set(orderId, boxNo); } } - } catch (e) { - ctx.logger.warn('[pick.createWavePickTask] 查询波次索引失败,box_no 将退化为任务内序号', { - error: e && e.message, - warehouseId, - waveId, - }); } const orderValuesSql = []; const orderReplacements = {}; - normalizedOrderIds.forEach((orderId, index) => { - const orderIdKey = `orderId${index}`; - const orderNoKey = `orderNo${index}`; - const boxNoKey = `boxNo${index}`; - const waveIndex = waveIndexMap.get(orderId); + let paramIndex = 0; + for (const [ orderId, orderBoxNo ] of orderBoxMap) { + const orderIdKey = `orderId${paramIndex}`; + const orderNoKey = `orderNo${paramIndex}`; + const boxNoKey = `oBoxNo${paramIndex}`; orderValuesSql.push(`( :taskId, :waveId, @@ -312,8 +378,9 @@ class PickService extends MainService { )`); orderReplacements[orderIdKey] = orderId; orderReplacements[orderNoKey] = orderNoMap.get(orderId) || ''; - orderReplacements[boxNoKey] = Number.isFinite(waveIndex) && waveIndex > 0 ? waveIndex : (index + 1); - }); + orderReplacements[boxNoKey] = orderBoxNo; + paramIndex += 1; + } await ctx.model.query( ` @@ -362,7 +429,7 @@ class PickService extends MainService { extras: { message: `订单${orderId}抓取波次成功`, warehouseId, - externalLogType: 'PDA', + externalLogType: 'API', }, })); await operationLogService.createOperationLogs(logPayloads); @@ -384,6 +451,144 @@ class PickService extends MainService { } } + /** + * 按库位排序并按 stock_id 分组订单,使 box_no 按拣货路径顺序分配。 + * + * 同 stock_id 的订单归入同一组(同一篮号),组间按 pick_sequence ASC 排序。 + * 若某订单无拣货数据(未分配储位),排到末尾保持原顺序。 + * + * @param {Array} orderIds 订单ID列表。 + * @param {number} warehouseId 仓库ID。 + * @param {Object} [transaction] Sequelize 事务。 + * @return {Promise>} 按库位排序后的分组列表。 + */ + async resolveLocationSortedOrderIds(orderIds, warehouseId, transaction) { + const { ctx } = this; + const normalizedOrderIds = [ ...new Set((Array.isArray(orderIds) ? orderIds : []) + .map(id => Number(id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ]; + + if (normalizedOrderIds.length === 0) { + return []; + } + + if (normalizedOrderIds.length === 1) { + return [{ stock_id: 0, order_ids: normalizedOrderIds }]; + } + + try { + // 查询拣货明细获取 order_item_id 和 space_id + const pickingRows = await ctx.model.Picking.findAll({ + where: { + order_id: { [this.app.Sequelize.Op.in]: normalizedOrderIds }, + warehouse_id: warehouseId, + }, + attributes: [ 'order_id', 'order_item_id', 'space_id' ], + raw: true, + transaction, + }); + + const normalizedPickingRows = Array.isArray(pickingRows) ? pickingRows : []; + const orderSpaceMap = new Map(); + const orderItemIds = []; + for (const row of normalizedPickingRows) { + const oid = Number(row && row.order_id || 0); + const sid = Number(row && row.space_id || 0); + const oiid = Number(row && row.order_item_id || 0); + if (oid > 0 && !orderSpaceMap.has(oid)) { + orderSpaceMap.set(oid, sid); + } + if (oiid > 0) { + orderItemIds.push(oiid); + } + } + + // 查询订单商品明细获取 stock_id,收集每个订单的所有 stock_id + const orderStockIdSet = new Map(); + if (orderItemIds.length > 0) { + const factory = ctx.model && ctx.model.OrderItemsFactory; + if (factory && typeof factory.getCurrentModel === 'function') { + const orderItemModel = await factory.getCurrentModel(warehouseId); + if (orderItemModel && typeof orderItemModel.findAll === 'function') { + const itemRows = await orderItemModel.findAll({ + where: { + id: { [this.app.Sequelize.Op.in]: [ ...new Set(orderItemIds) ] }, + }, + attributes: [ 'id', 'order_id', 'stock_id' ], + raw: true, + transaction, + }); + for (const row of (Array.isArray(itemRows) ? itemRows : [])) { + const oid = Number(row && row.order_id || 0); + const stockId = Number(row && row.stock_id || 0); + if (oid > 0 && stockId > 0) { + if (!orderStockIdSet.has(oid)) { + orderStockIdSet.set(oid, new Set()); + } + orderStockIdSet.get(oid).add(stockId); + } + } + } + } + } + + // 按 stock_id 分组:每个 stock_id 一个组,订单可出现在多个组(多商品订单) + const groupMap = new Map(); + for (const oid of normalizedOrderIds) { + const stockIds = orderStockIdSet.get(oid); + if (stockIds && stockIds.size > 0) { + for (const stockId of stockIds) { + if (!groupMap.has(stockId)) { + groupMap.set(stockId, { stock_id: stockId, order_ids: [] }); + } + groupMap.get(stockId).order_ids.push(oid); + } + } else { + const key = -oid; // 无 stock_id 的订单各自成组 + if (!groupMap.has(key)) { + groupMap.set(key, { stock_id: 0, order_ids: [] }); + } + groupMap.get(key).order_ids.push(oid); + } + } + + const spaceIds = [ ...new Set([ ...orderSpaceMap.values() ].filter(sid => sid > 0)) ]; + const sequenceMap = new Map(); + if (spaceIds.length > 0) { + const locationRows = await ctx.model.LocationSpace.findAll({ + where: { id: { [this.app.Sequelize.Op.in]: spaceIds } }, + attributes: [ 'id', 'pick_sequence' ], + raw: true, + transaction, + }); + for (const row of (Array.isArray(locationRows) ? locationRows : [])) { + const lid = Number(row && row.id || 0); + if (lid > 0 && !sequenceMap.has(lid)) { + sequenceMap.set(lid, Number(row.pick_sequence || 0)); + } + } + } + + // 每组取最小 pick_sequence 排序 + const groups = [ ...groupMap.values() ]; + groups.sort((a, b) => { + const seqA = Math.min(...a.order_ids.map(oid => sequenceMap.get(orderSpaceMap.get(oid)) ?? Number.MAX_SAFE_INTEGER)); + const seqB = Math.min(...b.order_ids.map(oid => sequenceMap.get(orderSpaceMap.get(oid)) ?? Number.MAX_SAFE_INTEGER)); + if (seqA !== seqB) return seqA - seqB; + return a.order_ids[0] - b.order_ids[0]; + }); + + return groups; + } catch (error) { + ctx.logger.warn('[pick.resolveLocationSortedOrderIds] 按库位排序失败,退回原顺序', { + error: error && error.message, + warehouseId, + orderCount: normalizedOrderIds.length, + }); + return [{ stock_id: 0, order_ids: normalizedOrderIds }]; + } + } + /** * 按关键字获取或创建波次拣货任务。 * @@ -709,7 +914,25 @@ class PickService extends MainService { const normalizedWaveType = Number(targetWaveType || 2); const isGroupWave = normalizedWaveType === 1; - const pickMode = isGroupWave ? 1 : 2; + // 检查是否为 singleFetchByIds 创建的波次(item_part_type='manual_ids'),使用先拣后分模式 + let isManualIdsWave = false; + try { + const waveInfoRows = await ctx.model.query( + `SELECT item_part_type + FROM wms_wave_batch + WHERE wave_id = :waveId + LIMIT 1`, + { + replacements: { waveId: targetWaveId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + const waveInfo = Array.isArray(waveInfoRows) && waveInfoRows.length > 0 ? waveInfoRows[0] : null; + isManualIdsWave = String(waveInfo && waveInfo.item_part_type || '').trim() === 'manual_ids'; + } catch (e) { + // 查询失败不影响主流程,退回默认拣货模式 + } + const pickMode = isGroupWave ? 1 : (isManualIdsWave ? 3 : 2); if (selectedOrderIds.length === 0) { let orderModel = null; @@ -1080,7 +1303,25 @@ class PickService extends MainService { const normalizedWaveType = Number(targetWaveType || 2); const isGroupWave = normalizedWaveType === 1; - const pickMode = isGroupWave ? 1 : 2; + // 检查是否为 singleFetchByIds 创建的波次(item_part_type='manual_ids'),使用先拣后分模式 + let isManualIdsWaveWP = false; + try { + const waveInfoRowsWP = await ctx.model.query( + `SELECT item_part_type + FROM wms_wave_batch + WHERE wave_id = :waveId + LIMIT 1`, + { + replacements: { waveId: targetWaveId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + const waveInfoWP = Array.isArray(waveInfoRowsWP) && waveInfoRowsWP.length > 0 ? waveInfoRowsWP[0] : null; + isManualIdsWaveWP = String(waveInfoWP && waveInfoWP.item_part_type || '').trim() === 'manual_ids'; + } catch (e) { + // 查询失败不影响主流程,退回默认拣货模式 + } + const pickMode = isGroupWave ? 1 : (isManualIdsWaveWP ? 3 : 2); try { const createdTask = await this.createWavePickTask({ diff --git a/app/service/systems/pick.js b/app/service/systems/pick.js index de8bc96..d40c11c 100644 --- a/app/service/systems/pick.js +++ b/app/service/systems/pick.js @@ -1261,6 +1261,16 @@ class PickSystemService extends Service { .map(row => [ Number(row && row.box_no || 0), row ]) .filter(([ boxNo ]) => boxNo > 0)); + // 构建 stock_id → box_no 映射(从 wms_wave_pick_task_box.ref_id),用于给每个拣货明细行标注篮号 + const boxNoByStockId = new Map(); + for (const row of normalizedBoxRows) { + const sid = Number(row && row.ref_id || 0); + const bno = Number(row && row.box_no || 0); + if (sid > 0 && bno > 0 && !boxNoByStockId.has(sid)) { + boxNoByStockId.set(sid, bno); + } + } + const pickingDetails = (Array.isArray(pickingRows) ? pickingRows : []).map(row => { const orderItemId = Number(row && row.order_item_id || 0); const currentSpaceId = Number(row && row.space_id || 0); @@ -1295,6 +1305,7 @@ class PickSystemService extends Service { return { order_id: Number(row && row.order_id || 0), + box_no: boxNoByStockId.get(stockId) || 0, order_item_id: orderItemId, quantity: Number(row && row.quantity || 0), storage_id: Number(row && row.storage_id || 0), @@ -1320,6 +1331,17 @@ class PickSystemService extends Service { }; }); + // 排序 picking_details:box_no 已按库位顺序生成,直接按 box_no 升序即可 + pickingDetails.sort((a, b) => { + const boxA = Number(a && a.box_no || 0); + const boxB = Number(b && b.box_no || 0); + if (boxA !== boxB) return boxA - boxB; + + const codeA = String(a && a.item_code || '').trim(); + const codeB = String(b && b.item_code || '').trim(); + return codeA.localeCompare(codeB); + }); + const pickingSummary = this.buildPickingSummary(pickingDetails); const pickingView = await this.buildPickingView({ pickMode, From e61efbb66af7f08b9f9ab14664378de485c3d108 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Thu, 6 Aug 2026 17:40:36 +0800 Subject: [PATCH 178/550] =?UTF-8?q?feat(inbox):=20=E7=AB=99=E5=86=85?= =?UTF-8?q?=E4=BF=A1=E6=A8=A1=E5=9D=97=E5=AE=8C=E6=95=B4=E5=AE=9E=E7=8E=B0?= =?UTF-8?q?=20-=20AI=E6=99=BA=E8=83=BD=E5=8A=A9=E6=89=8B=E3=80=81=E7=BE=A4?= =?UTF-8?q?=E7=AE=A1=E7=90=86=E3=80=81=E6=B6=88=E6=81=AF=E5=88=97=E8=A1=A8?= =?UTF-8?q?=E5=A2=9E=E5=BC=BA=E3=80=81=E7=81=B0=E5=BA=A6=E5=BC=80=E5=85=B3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增功能: - AI智能助手: DeepSeek多轮推理、函数调用(searchStock/createOrder等) - silent动作: AI识别无需回复的消息(好的/谢谢/再见)自动跳过回执 - ai_enabled灰度开关: 群级别控制AI启停,支持逐群放量 - 消息列表增强: storeId/groupId/groupName/userName/content/sourceType多条件筛选,时间格式化 代码优化: - processWithAI: 多轮推理循环(MAX_ROUNDS=5)、对话历史不含[#N]前缀防AI污染 - 回执记录补齐group_id/user_id/group_name/user_name上下文 - 移除未使用的target_channel字段及迁移 - bindCode文档修正: store_warehouse → store 接口文档: - system.json v0.3.18→0.3.19: 新增aiEnabled参数、消息列表响应扩充 - changes/system.json: 新增bindCode变更记录 杂项: - store_warehouse.js JSDoc补全 - wave.js waveBatchSource修复 --- app/controller/inbox.js | 127 -- app/model/inbox_block.js | 45 + app/model/inbox_group.js | 106 ++ app/model/inbox_message.js | 53 +- app/model/store_warehouse.js | 20 +- app/router.js | 3 - app/service/inbox/dispatch/base.js | 118 -- app/service/inbox/dispatch/dingtalk.js | 35 - app/service/inbox/dispatch/feishu.js | 60 - app/service/inbox/dispatch/webhook.js | 44 - app/service/inbox/dispatch/wecom.js | 33 - app/service/inbox/functions.js | 1060 +++++++++++++++++ app/service/inbox/index.js | 84 +- app/service/inbox/message.js | 335 ++++++ app/service/inbox/processor.js | 570 +++++++++ app/service/inbox/receiver.js | 405 ++----- app/service/systemMethods/inbox.js | 189 +++ app/service/systemMethods/order/wave.js | 2 +- app/service/systems/inbox/group.js | 250 ++++ app/service/systems/store.js | 67 ++ app/service/warehouseMethods/inbox.js | 11 +- .../20260803120000-create-inbox-message.js | 33 +- ...0804120000-add-content-to-inbox-message.js | 33 + .../20260804130000-create-inbox-block.js | 57 + .../20260804140000-create-inbox-group.js | 92 ++ ...20000-add-express-fields-to-inbox-group.js | 42 + .../20260805140000-add-inbox-indexes.js | 73 ++ ...0260805150000-add-group-api-permissions.js | 53 + ...120000-add-ai-thoughts-to-inbox-message.js | 27 + ...806150000-add-ai-enabled-to-inbox-group.js | 21 + ...-drop-target-channel-from-inbox-message.js | 20 + methods/changes/system.json | 17 + methods/system.json | 151 ++- script/tmp-check-pending-migrations.cjs | 87 ++ 34 files changed, 3440 insertions(+), 883 deletions(-) delete mode 100644 app/controller/inbox.js create mode 100644 app/model/inbox_block.js create mode 100644 app/model/inbox_group.js delete mode 100644 app/service/inbox/dispatch/base.js delete mode 100644 app/service/inbox/dispatch/dingtalk.js delete mode 100644 app/service/inbox/dispatch/feishu.js delete mode 100644 app/service/inbox/dispatch/webhook.js delete mode 100644 app/service/inbox/dispatch/wecom.js create mode 100644 app/service/inbox/functions.js create mode 100644 app/service/inbox/message.js create mode 100644 app/service/inbox/processor.js create mode 100644 app/service/systemMethods/inbox.js create mode 100644 app/service/systems/inbox/group.js create mode 100644 database/migrations/20260804120000-add-content-to-inbox-message.js create mode 100644 database/migrations/20260804130000-create-inbox-block.js create mode 100644 database/migrations/20260804140000-create-inbox-group.js create mode 100644 database/migrations/20260805120000-add-express-fields-to-inbox-group.js create mode 100644 database/migrations/20260805140000-add-inbox-indexes.js create mode 100644 database/migrations/20260805150000-add-group-api-permissions.js create mode 100644 database/migrations/20260806120000-add-ai-thoughts-to-inbox-message.js create mode 100644 database/migrations/20260806150000-add-ai-enabled-to-inbox-group.js create mode 100644 database/migrations/20260806160000-drop-target-channel-from-inbox-message.js create mode 100644 script/tmp-check-pending-migrations.cjs diff --git a/app/controller/inbox.js b/app/controller/inbox.js deleted file mode 100644 index 239cdc8..0000000 --- a/app/controller/inbox.js +++ /dev/null @@ -1,127 +0,0 @@ -'use strict'; - -const { Controller } = require('egg'); -const { toSuccess, toFailure } = require('../lib/api_response'); - -/** - * 站内信内部管理接口控制器。 - * 提供消息列表、详情、对话链、回信、重推、统计等管理功能。 - */ -class InboxController extends Controller { - /** - * 获取当前仓库上下文。 - * @return {{ warehouseId: number }} 仓库上下文。 - */ - getWarehouseContext() { - const { ctx } = this; - const warehouseId = Number(ctx.user && ctx.user.store_id); - - if (!Number.isFinite(warehouseId) || warehouseId <= 0) { - throw new Error('缺少仓库信息'); - } - - return { warehouseId }; - } - - /** - * 内部管理统一入口,分发到对应 service 方法。 - * @return {Promise} 无返回值,结果写入 ctx.body。 - */ - async index() { - const { ctx } = this; - - try { - const method = String(ctx.request.body && ctx.request.body.method || '').trim(); - if (!method || !method.startsWith('inbox.')) { - ctx.status = 400; - ctx.body = toFailure({ message: 'method 参数无效' }); - ctx.type = 'application/json'; - return; - } - - const action = method.replace('inbox.', ''); - const data = (ctx.request.body && ctx.request.body.data) || {}; - - let result; - - switch (action) { - case 'list': { - const { warehouseId } = this.getWarehouseContext(); - result = await ctx.service.inbox.index.list({ - warehouseId, - ...data, - }); - break; - } - - case 'detail': { - const { warehouseId } = this.getWarehouseContext(); - result = await ctx.service.inbox.index.detail({ - warehouseId, - id: data.id, - }); - break; - } - - case 'thread': { - const { warehouseId } = this.getWarehouseContext(); - result = await ctx.service.inbox.index.thread({ - warehouseId, - id: data.id, - }); - break; - } - - case 'reply': { - const { warehouseId } = this.getWarehouseContext(); - result = await ctx.service.inbox.index.reply({ - warehouseId, - parentId: data.parentId, - targetChannel: data.targetChannel, - targetUrl: data.targetUrl, - targetType: data.targetType, - refCode: data.refCode, - extData: data.extData, - flags: data.flags, - }); - break; - } - - case 'retry': { - const { warehouseId } = this.getWarehouseContext(); - result = await ctx.service.inbox.index.retry({ - warehouseId, - id: data.id, - }); - break; - } - - case 'stats': { - const { warehouseId } = this.getWarehouseContext(); - result = await ctx.service.inbox.index.stats({ - warehouseId, - direction: data.direction, - }); - break; - } - - default: - ctx.status = 400; - ctx.body = toFailure({ message: `不支持的 inbox 方法: ${action}` }); - ctx.type = 'application/json'; - return; - } - - ctx.status = 200; - ctx.body = toSuccess(result, 'ok'); - ctx.type = 'application/json'; - } catch (error) { - const message = String(error && error.message || '请求失败'); - ctx.status = 500; - ctx.body = toFailure({ message: `站内信错误: ${message}` }); - ctx.type = 'application/json'; - } - } -} - -module.exports = InboxController; diff --git a/app/model/inbox_block.js b/app/model/inbox_block.js new file mode 100644 index 0000000..4baa2dd --- /dev/null +++ b/app/model/inbox_block.js @@ -0,0 +1,45 @@ +'use strict'; + +/** + * 站内信屏蔽表 Model。 + * 记录被屏蔽的群/用户,后续来自该群+用户的消息不再触发 AI 回信。 + * group_name 和 user_name 均为 NULL 时表示全局屏蔽(预留)。 + * + * @param {Object} app Egg.js Application 实例。 + * @return {Object} Sequelize Model 定义。 + */ +module.exports = app => { + const { BIGINT, STRING, DATE } = app.Sequelize; + + const InboxBlock = app.model.define('inbox_block', { + id: { + type: BIGINT.UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + group_name: { + type: STRING(100), + allowNull: true, + comment: '群名称', + }, + user_name: { + type: STRING(100), + allowNull: true, + comment: '用户名称', + }, + created_at: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + }, { + tableName: 'wms_inbox_block', + timestamps: false, + comment: '站内信屏蔽表', + }); + + return InboxBlock; +}; diff --git a/app/model/inbox_group.js b/app/model/inbox_group.js new file mode 100644 index 0000000..3b5dc47 --- /dev/null +++ b/app/model/inbox_group.js @@ -0,0 +1,106 @@ +'use strict'; + +/** + * 站内信群表 Model。 + * 记录与 WMS 交互的群信息,支持按仓库屏蔽。 + * + * @param {Object} app Egg.js Application 实例。 + * @return {Object} Sequelize Model 定义。 + */ +module.exports = app => { + const { BIGINT, STRING, TINYINT, DATE } = app.Sequelize; + + const InboxGroup = app.model.define('inbox_group', { + id: { + type: BIGINT.UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + group_name: { + type: STRING(100), + allowNull: false, + comment: '群名称', + }, + group_id: { + type: STRING(100), + allowNull: true, + comment: '外部群ID', + }, + warehouse_id: { + type: BIGINT.UNSIGNED, + allowNull: false, + comment: '所属仓库ID', + }, + store_id: { + type: BIGINT.UNSIGNED, + allowNull: true, + comment: '关联货主ID', + }, + group_type: { + type: app.Sequelize.ENUM('store', 'warehouse', 'express'), + allowNull: true, + comment: '群类型: store=货主 warehouse=仓库 express=快递', + }, + sub_type: { + type: STRING(20), + allowNull: true, + comment: '群子类型: 货主(售后/财务/收货) 仓库(收货/普通/生产) 快递(揽收/售后)', + }, + source_type: { + type: STRING(20), + allowNull: true, + comment: '来源类型:im / api / system', + }, + source_extra: { + type: STRING(100), + allowNull: true, + comment: '来源附加信息', + }, + is_blocked: { + type: TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '是否屏蔽 0=否 1=是', + }, + ai_enabled: { + type: TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '是否启用AI自动回复: 0=关闭 1=开启', + }, + express_interfaces: { + type: STRING(500), + allowNull: true, + comment: '快递接口ID列表,逗号分隔(仅群类型为 express 时生效)', + }, + system_express_code: { + type: STRING(50), + allowNull: true, + comment: '系统快递编码(仅群类型为 express 时必填)', + }, + created_at: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + }, { + tableName: 'wms_inbox_group', + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + deletedAt: 'deleted_at', + paranoid: true, + comment: '站内信群表', + }); + + return InboxGroup; +}; diff --git a/app/model/inbox_message.js b/app/model/inbox_message.js index 6a43ce1..73873b5 100644 --- a/app/model/inbox_message.js +++ b/app/model/inbox_message.js @@ -77,34 +77,30 @@ module.exports = app => { }, comment: '目标类型:im / api / webhook', }, - target_channel: { - type: STRING(50), - allowNull: false, - validate: { - notEmpty: { - msg: 'target_channel 不能为空', - }, - }, - comment: '目标渠道:wecom / dingtalk / feishu / warehouse_api / webhook', - }, - target_url: { - type: STRING(500), - allowNull: false, - validate: { - notEmpty: { - msg: 'target_url 不能为空', - }, - len: { - args: [ 1, 500 ], - msg: 'target_url 长度应在1-500个字符之间', - }, - }, - comment: '推送目标URL(IM Bot webhook 地址 / API 回调地址)', - }, - ref_code: { + group_name: { type: STRING(100), allowNull: true, - comment: '外部引用编码,推送/回执时原样携带', + comment: '群名称(外部传入)', + }, + user_name: { + type: STRING(100), + allowNull: true, + comment: '用户名称(外部传入)', + }, + group_id: { + type: STRING(100), + allowNull: true, + comment: '外部群ID', + }, + user_id: { + type: STRING(100), + allowNull: true, + comment: '外部用户ID', + }, + content: { + type: app.Sequelize.TEXT, + allowNull: true, + comment: '消息正文/摘要,用于列表展示和关键词搜索', }, ext_data: { type: JSON_TYPE, @@ -116,6 +112,11 @@ module.exports = app => { allowNull: true, comment: '处理标记,外部传入控制WMS处理行为', }, + ai_thoughts: { + type: JSON_TYPE, + allowNull: true, + comment: 'AI 多轮推理思考过程 [{round,action,function,params,reason,functionResult}]', + }, push_status: { type: TINYINT(4), allowNull: false, diff --git a/app/model/store_warehouse.js b/app/model/store_warehouse.js index 52136f9..5e7a40c 100644 --- a/app/model/store_warehouse.js +++ b/app/model/store_warehouse.js @@ -734,7 +734,14 @@ module.exports = app => { return normalizePolicyConfig(value, options); }; - // 统一构造复合键语义的 where 条件,避免 service 侧重复散落。 + /** + * 统一构造复合键语义的 where 条件,避免 service 侧重复散落。 + * @param {Object} options 配置项 + * @param {number} [options.warehouseId] 仓库ID + * @param {number} [options.storeId] 货主ID + * @param {number} [options.warehouseUseStatus=1] 仓库侧使用状态过滤,默认仅查可用合约 + * @return {Object} 组装后的 where 条件对象 + */ StoreWarehouse.buildScopedWhere = function(options = {}) { const { warehouseId, @@ -757,7 +764,16 @@ module.exports = app => { return where; }; - // 统一构造 StockWarehouse -> StoreWarehouse(include as=store_stock) 的 include。 + /** + * 统一构造 StockWarehouse -> StoreWarehouse(include as=store_stock) 的 include。 + * @param {Object} options 配置项 + * @param {number} [options.warehouseId] 仓库ID + * @param {number} [options.storeId] 货主ID + * @param {boolean} [options.required=false] 是否使用 INNER JOIN + * @param {number} [options.warehouseUseStatus=1] 仓库侧使用状态过滤,默认仅查可用合约 + * @param {Array} [options.attributes] 需要查询的字段 + * @return {Object} Sequelize include 对象 + */ StoreWarehouse.buildStoreStockInclude = function(options = {}) { const { warehouseId, diff --git a/app/router.js b/app/router.js index cf6fb6b..b437fe3 100644 --- a/app/router.js +++ b/app/router.js @@ -67,7 +67,4 @@ module.exports = app => { router.get('/testSendData', controller.home.testSendData); // IM交互入口 router.post('/im', controller.im.index); - - // 站内信内部管理接口 - router.post('/inbox', controller.inbox.index); }; diff --git a/app/service/inbox/dispatch/base.js b/app/service/inbox/dispatch/base.js deleted file mode 100644 index eb6ff61..0000000 --- a/app/service/inbox/dispatch/base.js +++ /dev/null @@ -1,118 +0,0 @@ -'use strict'; - -const Service = require('egg').Service; -const apiSignLib = require('../../../lib/api_sign'); - -const WAREHOUSE_INTERFACE_TYPE_ID = 3; -const DISPATCH_TIMEOUT_MS = 10000; // 10s 超时 - -/** - * 统一出站基类,所有渠道 dispatch 继承此类。 - * 统一处理:查密钥、签名、发 HTTP。 - * 子类只需实现 push(record) 方法,关注消息格式转换。 - */ -class OutboundBase extends Service { - /** - * 获取仓库 ApiApp 密钥配置(IM 渠道无需签名,返回 null)。 - * @param {number} warehouseId 仓库ID。 - * @return {Promise} ApiApp 配置对象,含 appKey / selfAppSecret / warehouseId。 - */ - async getApiApp(warehouseId) { - const { ctx } = this; - try { - // 通过仓库ID查找该仓库的 warehouse 类型 ApiApp - const apiApp = await ctx.model.ApiApp.findOne({ - attributes: [ 'id', 'self_app_key', 'self_app_secret', 'is_enabled', 'interface_type_id', 'warehouse_id' ], - where: { - warehouse_id: warehouseId, - interface_type_id: WAREHOUSE_INTERFACE_TYPE_ID, - is_enabled: 1, - }, - raw: true, - }); - - if (!apiApp || !apiApp.self_app_secret) { - return null; - } - - return { - appKey: apiApp.self_app_key, - selfAppSecret: apiApp.self_app_secret, - warehouseId: Number(apiApp.warehouse_id), - }; - } catch (error) { - ctx.logger.warn(`[inbox dispatch] 获取仓库 ApiApp 失败: ${error.message}`); - return null; - } - } - - /** - * 生成 MD5 签名,返回带签名后的完整 URL。 - * @param {string} url 原始目标URL。 - * @param {*} body 请求体。 - * @param {Object} secret ApiApp 密钥对象,含 appKey / selfAppSecret。 - * @return {string} 带签名的完整URL。 - */ - signRequest(url, body, secret) { - const timestamp = Math.floor(Date.now() / 1000); - const query = { - app_key: secret.appKey, - timestamp, - }; - - const { sign } = apiSignLib.signRequest({ - query, - body, - selfAppSecret: secret.selfAppSecret, - }); - - const separator = url.includes('?') ? '&' : '?'; - return `${url}${separator}app_key=${encodeURIComponent(query.app_key)}×tamp=${timestamp}&sign=${encodeURIComponent(sign)}`; - } - - /** - * 统一 HTTP POST 发送。 - * @param {string} url 目标URL。 - * @param {*} body 请求体。 - * @param {Object} [options] 额外选项。 - * @param {Object} [options.headers] 自定义请求头。 - * @return {Promise<{status: number, data: *}>} 响应结果。 - */ - async post(url, body, options = {}) { - const { ctx } = this; - const headers = { - 'Content-Type': 'application/json', - ...(options.headers || {}), - }; - - try { - const response = await ctx.curl(url, { - method: 'POST', - dataType: 'json', - contentType: 'json', - data: body, - headers, - timeout: DISPATCH_TIMEOUT_MS, - }); - - return { - status: response.status, - data: response.data, - }; - } catch (error) { - throw new Error(`HTTP 推送失败: ${error.message}`); - } - } - - /** - * 子类必须实现的推送方法。 - * @param {Object} record 消息记录(Sequelize Model 实例),子类按需使用。 - * @throws {Error} 子类未实现时抛出。 - */ - async push(record) { - const id = record && record.id; - throw new Error(`子类必须实现 push(record) 方法,当前消息ID: ${id || '未知'}`); - } -} - -module.exports = OutboundBase; diff --git a/app/service/inbox/dispatch/dingtalk.js b/app/service/inbox/dispatch/dingtalk.js deleted file mode 100644 index aab3df4..0000000 --- a/app/service/inbox/dispatch/dingtalk.js +++ /dev/null @@ -1,35 +0,0 @@ -'use strict'; - -const OutboundBase = require('./base'); - -/** - * 钉钉 Bot 渠道出站实现。 - * 推送 Markdown 消息到钉钉机器人 webhook。 - */ -class DingtalkDispatch extends OutboundBase { - /** - * 通过钉钉 Bot 推送消息。 - * @param {Object} record 消息记录(Sequelize Model 实例)。 - * @return {Promise<{status: number, data: *}>} 推送响应。 - */ - async push(record) { - const { ctx } = this; - - const extData = record.ext_data || {}; - const title = extData.title || '新消息通知'; - const text = extData.content || extData.text || `消息:${record.ref_code || record.ext_id}`; - - const body = { - msgtype: 'markdown', - markdown: { - title, - text: typeof text === 'string' ? text : JSON.stringify(text), - }, - }; - - ctx.logger.info(`[inbox dingtalk] 推送消息 ext_id=${record.ext_id} url=${record.target_url}`); - return await this.post(record.target_url, body); - } -} - -module.exports = DingtalkDispatch; diff --git a/app/service/inbox/dispatch/feishu.js b/app/service/inbox/dispatch/feishu.js deleted file mode 100644 index 26b5358..0000000 --- a/app/service/inbox/dispatch/feishu.js +++ /dev/null @@ -1,60 +0,0 @@ -'use strict'; - -const OutboundBase = require('./base'); - -/** - * 飞书 Bot 渠道出站实现。 - * 推送交互式卡片消息到飞书机器人 webhook。 - */ -class FeishuDispatch extends OutboundBase { - /** - * 通过飞书 Bot 推送消息。 - * @param {Object} record 消息记录(Sequelize Model 实例)。 - * @return {Promise<{status: number, data: *}>} 推送响应。 - */ - async push(record) { - const { ctx } = this; - - const extData = record.ext_data || {}; - const title = extData.title || '新消息通知'; - const content = extData.content || extData.text || `消息:${record.ref_code || record.ext_id}`; - - const body = { - msg_type: 'interactive', - card: { - header: { - title: { - tag: 'plain_text', - content: title, - }, - }, - elements: [ - { - tag: 'div', - text: { - tag: 'lark_md', - content: typeof content === 'string' ? content : JSON.stringify(content), - }, - }, - { - tag: 'hr', - }, - { - tag: 'note', - elements: [ - { - tag: 'plain_text', - content: `编号: ${record.ref_code || record.ext_id}`, - }, - ], - }, - ], - }, - }; - - ctx.logger.info(`[inbox feishu] 推送消息 ext_id=${record.ext_id} url=${record.target_url}`); - return await this.post(record.target_url, body); - } -} - -module.exports = FeishuDispatch; diff --git a/app/service/inbox/dispatch/webhook.js b/app/service/inbox/dispatch/webhook.js deleted file mode 100644 index 4df3812..0000000 --- a/app/service/inbox/dispatch/webhook.js +++ /dev/null @@ -1,44 +0,0 @@ -'use strict'; - -const OutboundBase = require('./base'); - -/** - * Webhook 渠道出站实现。 - * 直接 HTTP POST 推送 JSON 到目标 webhook URL。 - */ -class WebhookDispatch extends OutboundBase { - /** - * 通过 webhook 渠道推送消息。 - * @param {Object} record 消息记录(Sequelize Model 实例)。 - * @return {Promise<{status: number, data: *}>} 推送响应。 - */ - async push(record) { - const { ctx } = this; - - const body = { - ref_code: record.ref_code, - ext_data: record.ext_data, - message_id: record.ext_id, - direction: record.direction, - source_type: record.source_type, - created_at: record.created_at, - }; - - let targetUrl = record.target_url; - - // API 类型需要签名 - if (record.target_type === 'api') { - const apiApp = await this.getApiApp(record.warehouse_id); - if (apiApp) { - targetUrl = this.signRequest(targetUrl, body, apiApp); - } else { - ctx.logger.warn(`[inbox webhook] 仓库 ${record.warehouse_id} 没有可用 ApiApp,跳过签名`); - } - } - - ctx.logger.info(`[inbox webhook] 推送消息 ext_id=${record.ext_id} url=${targetUrl}`); - return await this.post(targetUrl, body); - } -} - -module.exports = WebhookDispatch; diff --git a/app/service/inbox/dispatch/wecom.js b/app/service/inbox/dispatch/wecom.js deleted file mode 100644 index 09ff283..0000000 --- a/app/service/inbox/dispatch/wecom.js +++ /dev/null @@ -1,33 +0,0 @@ -'use strict'; - -const OutboundBase = require('./base'); - -/** - * 企微 Bot 渠道出站实现。 - * 推送 Markdown 消息到企业微信机器人 webhook。 - */ -class WecomDispatch extends OutboundBase { - /** - * 通过企微 Bot 推送消息。 - * @param {Object} record 消息记录(Sequelize Model 实例)。 - * @return {Promise<{status: number, data: *}>} 推送响应。 - */ - async push(record) { - const { ctx } = this; - - const extData = record.ext_data || {}; - const content = extData.content || extData.text || `新消息通知:${record.ref_code || record.ext_id}`; - - const body = { - msgtype: 'markdown', - markdown: { - content: typeof content === 'string' ? content : JSON.stringify(content), - }, - }; - - ctx.logger.info(`[inbox wecom] 推送消息 ext_id=${record.ext_id} url=${record.target_url}`); - return await this.post(record.target_url, body); - } -} - -module.exports = WecomDispatch; diff --git a/app/service/inbox/functions.js b/app/service/inbox/functions.js new file mode 100644 index 0000000..650d65a --- /dev/null +++ b/app/service/inbox/functions.js @@ -0,0 +1,1060 @@ +'use strict'; + +const Service = require('egg').Service; + +/** + * ## 函数分组常量 + * + * 层级格式:`{主分组}` 或 `{主分组}:{子分组}` + * + * ### 分组匹配规则(注册 / 查询) + * + * 1. **精确匹配**:`['common']` 只匹配当前活跃分组包含 `common` 的上下文。 + * 2. **主分组通配**:`['bound:store:*']` 匹配 `bound:store` 及其所有子分组 + * (`bound:store:after_sales` / `bound:store:finance` / `bound:store:receiving`), + * 适用于同一主分组下所有子分组都需要的函数。 + * 3. **显式子分组**:`['bound:store:after_sales']` 只在该子分组活跃时可用, + * 适用于某子分组专属的函数。 + * 4. **组合使用**:`['common', 'bound:store:*']` 表示通用 + 所有货主子分组均可用。 + * + * ### 如何注册新函数 + * + * ```js + * // 仅通用分组 + * this.register('myFunc', { groups: [GROUP.COMMON], ... }); + * + * // 所有货主子分组(推荐) + * this.register('myFunc', { groups: [GROUP.BOUND_STORE_WILDCARD], ... }); + * + * // 仅售后子分组 + * this.register('myFunc', { groups: [GROUP.BOUND_STORE_AFTER_SALES], ... }); + * + * // 售后 + 财务(但非收货) + * this.register('myFunc', { + * groups: [GROUP.BOUND_STORE_AFTER_SALES, GROUP.BOUND_STORE_FINANCE], + * ... + * }); + * ``` + * + * @constant + */ +const GROUP = { + /** 通用分组 — 所有上下文均可用 */ + COMMON: 'common', + /** 已绑定货主群主分组 */ + BOUND_STORE: 'bound:store', + /** 货主群通配 — 匹配 bound:store 及其全部子分组 */ + BOUND_STORE_WILDCARD: 'bound:store:*', + /** 货主-售后子分组 */ + BOUND_STORE_AFTER_SALES: 'bound:store:after_sales', + /** 货主-财务子分组 */ + BOUND_STORE_FINANCE: 'bound:store:finance', + /** 货主-收货子分组 */ + BOUND_STORE_RECEIVING: 'bound:store:receiving', + /** 已绑定仓库群(预留) */ + BOUND_WAREHOUSE: 'bound:warehouse', + /** 已绑定快递群(预留) */ + BOUND_EXPRESS: 'bound:express', +}; + +/** + * 子分组 → 主分组映射,用于 `resolveActiveGroups` 展开。 + * 新增子分组时必须同步追加。 + * @constant {Record} + */ +const SUB_TO_MAIN = { + [GROUP.BOUND_STORE_AFTER_SALES]: GROUP.BOUND_STORE, + [GROUP.BOUND_STORE_FINANCE]: GROUP.BOUND_STORE, + [GROUP.BOUND_STORE_RECEIVING]: GROUP.BOUND_STORE, +}; + +/** + * 注册时声明的主分组通配 → 所有已知子分组展开列表。 + * 用于 `isFunctionAvailable` 中展开 `bound:store:*` → 实际子分组集合。 + * @constant {Record} + */ +const WILDCARD_EXPAND = { + [GROUP.BOUND_STORE_WILDCARD]: [ + GROUP.BOUND_STORE, + GROUP.BOUND_STORE_AFTER_SALES, + GROUP.BOUND_STORE_FINANCE, + GROUP.BOUND_STORE_RECEIVING, + ], +}; + +/** + * 站内信函数库。 + * 注册可被 AI 调用的内部方法,支持按分组筛选, + * 根据当前上下文(群类型、绑定状态)自动选择可用函数集合。 + */ +class InboxFunctionsService extends Service { + /** + * 初始化函数注册表。 + * @param {Object} ctx Egg.js 上下文。 + */ + constructor(ctx) { + super(ctx); + /** @type {Map} */ + this.registry = new Map(); + this.registerBuiltinFunctions(); + } + + /** + * 注册内置函数。 + */ + registerBuiltinFunctions() { + this.register('hello', { + description: '问候接口,返回欢迎信息。传入 name 参数可个性化问候', + params: { + name: { type: 'string', required: false, description: '用户名称' }, + }, + groups: [ GROUP.COMMON ], + handler: async (params = {}) => { + const name = String(params.name || '').trim(); + const greeting = name ? `你好,${name}!欢迎使用 WMS 站内信服务` : '你好!欢迎使用 WMS 站内信服务'; + return { + success: true, + data: { greeting }, + }; + }, + }); + + this.register('queryPrintBalance', { + description: '查询当前货主的面单余额。根据上下文中的货主ID和仓库ID查询合约中的面单剩余量和锁定量', + params: {}, + groups: [ GROUP.BOUND_STORE_WILDCARD ], + handler: async (params = {}) => { + const { ctx } = this; + void params; + const storeId = Number( + ctx.inboxContext?.store_id + || ctx.user?.store_id + || 0 + ); + const warehouseId = Number( + ctx.inboxContext?.warehouse_id + || ctx.user?.store_id + || 0 + ); + + if (!Number.isFinite(storeId) || storeId <= 0) { + return { + success: false, + error: '无法获取货主信息,请确认已在已签约的货主上下文中操作', + }; + } + + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + return { + success: false, + error: '无法获取仓库信息,请确认上下文已正确设置', + }; + } + + try { + const contract = await ctx.model.StoreWarehouse.findOne({ + attributes: [ + 'id', 'store_id', 'warehouse_id', + 'print_quantity', 'print_quantity_locked', + ], + where: { + store_id: storeId, + warehouse_id: warehouseId, + auth_status: 2, + warehouse_use_status: 1, + }, + raw: true, + }); + + if (!contract) { + return { + success: false, + error: `货主 ${storeId} 在仓库 ${warehouseId} 中无有效合约,请检查货主ID是否正确`, + }; + } + + const available = Math.max(0, contract.print_quantity - contract.print_quantity_locked); + + return { + success: true, + data: { + store_id: contract.store_id, + warehouse_id: contract.warehouse_id, + print_quantity: contract.print_quantity, + print_quantity_locked: contract.print_quantity_locked, + available, + }, + }; + } catch (error) { + return { + success: false, + error: `查询面单余额失败: ${error.message}`, + }; + } + }, + }); + this.register('createWaybill', { + description: '为指定平台单号创建快递单号。根据平台订单号查找发货单并分配快递单号', + params: { + order_code: { type: 'string', required: true, description: '平台订单号' }, + }, + groups: [ GROUP.BOUND_STORE_WILDCARD ], + handler: async (params = {}) => { + const { ctx } = this; + const orderCode = String(params.order_code || '').trim(); + const storeId = Number(ctx.inboxContext?.store_id || 0); + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + + if (!orderCode) { + return { + success: false, + error: '未提供有效的平台单号,请提供订单编号', + }; + } + + if (!warehouseId || !storeId) { + return { + success: false, + error: '无法获取仓库或货主信息,请确认上下文已正确设置', + }; + } + + try { + const OrderDelivery = await ctx.service.systems.express.getWaybillAsyncOrderDeliveryModel(warehouseId); + if (!OrderDelivery) { + return { success: false, error: `仓库 ${warehouseId} 的发货单表不可用` }; + } + + const orderDelivery = await OrderDelivery.findOne({ + attributes: [ 'id', 'delivery_order_code', 'source_order_codes', 'store_id', 'warehouse_id', 'post_status' ], + where: { + source_order_codes: { [ctx.app.Sequelize.Op.like]: `%${orderCode}%` }, + warehouse_id: warehouseId, + store_id: storeId, + }, + raw: true, + }); + + if (!orderDelivery) { + return { + success: false, + error: `未找到平台单号 ${orderCode} 对应的发货单,请核实单号是否正确`, + }; + } + + // 查已有快递单号 + const existingExpress = await ctx.model.OrderExpress.findOne({ + attributes: [ 'waybill_code', 'logistics_name', 'status' ], + where: { order_id: orderDelivery.id, business_key: 1 }, + raw: true, + }); + + if (existingExpress && existingExpress.waybill_code) { + return { + success: true, + data: { + order_id: orderDelivery.id, + delivery_order_code: orderDelivery.delivery_order_code, + waybill_code: existingExpress.waybill_code, + logistics_name: existingExpress.logistics_name, + existed: true, + }, + }; + } + + // 触发取号 + await ctx.service.systemMethods.order.pendingOrder.allocateExpressCode({ + ids: [ orderDelivery.id ], + }); + + return { + success: true, + data: { + order_id: orderDelivery.id, + delivery_order_code: orderDelivery.delivery_order_code, + message: `已为订单 ${orderCode} 提交快递取号任务,请稍后查询`, + }, + }; + } catch (error) { + return { + success: false, + error: `创建快递单号失败: ${error.message}`, + }; + } + }, + }); + + this.register('searchStock', { + description: '搜索仓库商品。按关键词查询当前仓库+货主的商品,返回 stock_store.id、编码、名称、条码、库存总量/锁定/可用 供建单参考', + params: { + keyword: { type: 'string', required: true, description: '搜索关键词:商品编码(item_code)、条码(barcode)、商品名称(item_name)' }, + }, + groups: [ GROUP.BOUND_STORE_WILDCARD ], + handler: async (params = {}) => { + const { ctx } = this; + const storeId = Number(ctx.inboxContext?.store_id || 0); + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + const keyword = String(params.keyword || '').trim(); + const { Op } = ctx.app.Sequelize; + + if (!keyword) return { success: false, error: '请提供搜索关键词' }; + if (!warehouseId || !storeId) return { success: false, error: '无法获取仓库或货主信息' }; + + try { + const items = await ctx.model.StockStore.findAll({ + attributes: [ 'id', 'stock_id', 'item_code', 'item_name', 'barcode', 'brand_name', 'stock_unit' ], + where: { + warehouse_id: warehouseId, + store_id: storeId, + [Op.or]: [ + { item_code: { [Op.like]: `%${keyword}%` } }, + { item_name: { [Op.like]: `%${keyword}%` } }, + { barcode: { [Op.like]: `%${keyword}%` } }, + ], + }, + limit: 10, + raw: true, + }); + + if (items.length === 0) { + return { success: true, data: { total: 0, items: [], hint: '未找到匹配商品,请尝试其他关键词' } }; + } + + // 批量查库存数量 + const stockIds = [ ...new Set(items.map(i => i.stock_id).filter(Boolean)) ]; + const stockQtyMap = {}; + if (stockIds.length > 0) { + const stocks = await ctx.model.StockWarehouse.findAll({ + attributes: [ 'id', 'quantity', 'locked_quantity' ], + where: { id: { [Op.in]: stockIds } }, + raw: true, + }); + for (const s of stocks) { + stockQtyMap[s.id] = { + quantity: s.quantity || 0, + locked_quantity: s.locked_quantity || 0, + available: Math.max(0, (s.quantity || 0) - (s.locked_quantity || 0)), + }; + } + } + + return { + success: true, + data: { + total: items.length, + items: items.map(i => ({ + id: i.id, + item_code: i.item_code, + item_name: i.item_name, + barcode: i.barcode, + brand_name: i.brand_name || '', + unit: i.stock_unit || '', + stock_qty: stockQtyMap[i.stock_id]?.quantity || 0, + stock_locked: stockQtyMap[i.stock_id]?.locked_quantity || 0, + stock_available: stockQtyMap[i.stock_id]?.available || 0, + })), + }, + }; + } catch (error) { + return { success: false, error: `商品搜索失败: ${error.message}` }; + } + }, + }); + + this.register('recallHistory', { + description: '回顾当前群+用户的最近对话历史。当需要上下文但信息不足时调用,获取最近N条消息记录(含AI回复),每条带序号', + params: { + limit: { type: 'number', required: false, description: '获取最近几条,默认5,最大10' }, + }, + groups: [ GROUP.COMMON ], + handler: async (params = {}) => { + const limit = Math.min(10, Math.max(1, Number(params.limit) || 5)); + const history = await this.getConversationHistory({ maxMessages: limit }); + if (history.length === 0) { + return { success: true, data: { total: 0, messages: [], hint: '暂无对话历史' } }; + } + return { + success: true, + data: { + total: history.length, + messages: history.map(h => ({ + seq: h.seq, + role: h.role === 'user' ? '用户' : 'AI', + content: h.content || '', + })), + }, + }; + }, + }); + + this.register('createOrder', { + description: '创建发货订单。传入商品 stock_id(来自 searchStock)及数量、收件人信息,使用手工建单流程创建发货单', + params: { + items: { type: 'array', required: true, description: '商品列表 [{item_id: stock_id, plan_qty: 数量}]' }, + receiverName: { type: 'string', required: true, description: '收件人姓名' }, + receiverPhone: { type: 'string', required: true, description: '收件人电话' }, + receiverProvince: { type: 'string', required: false, description: '省份' }, + receiverCity: { type: 'string', required: false, description: '城市' }, + receiverDistrict: { type: 'string', required: false, description: '区县' }, + receiverAddress: { type: 'string', required: true, description: '详细地址' }, + }, + groups: [ GROUP.BOUND_STORE_AFTER_SALES ], + handler: async (params = {}) => { + const { ctx } = this; + const storeId = Number(ctx.inboxContext?.store_id || 0); + const items = Array.isArray(params.items) ? params.items : []; + const name = String(params.receiverName || '').trim(); + const mobile = String(params.receiverPhone || '').trim(); + const province = String(params.receiverProvince || '').trim(); + const city = String(params.receiverCity || '').trim(); + const area = String(params.receiverDistrict || '').trim(); + const detailAddress = String(params.receiverAddress || '').trim(); + + if (!storeId) return { success: false, error: '无法获取货主信息' }; + if (!name) return { success: false, error: '收件人姓名不能为空' }; + if (!mobile) return { success: false, error: '收件人电话不能为空' }; + if (!detailAddress) return { success: false, error: '详细地址不能为空' }; + if (!province) return { success: false, error: '省份不能为空' }; + if (items.length === 0) return { success: false, error: '请提供至少一个商品' }; + + try { + // 适配手工建单格式 + const orderItems = items.map((item, i) => ({ + item_id: Number(item.item_id), + plan_qty: Number(item.plan_qty) || 1, + item_code: String(item.item_code || '').trim(), + item_name: String(item.item_name || '').trim(), + order_line_no: String(i + 1), + })); + + const invalidItems = orderItems.filter(i => !i.item_id || i.item_id <= 0); + if (invalidItems.length > 0) { + return { success: false, error: '商品 item_id 必须为正整数(请先使用 searchStock 获取正确的商品ID)' }; + } + + const result = await ctx.service.systemMethods.order.pendingOrder.createOrder({ + store_id: storeId, + name, + mobile, + tel: '', + province, + city, + area, + detail_address: detailAddress, + items: orderItems, + }); + + return { + success: true, + data: { + deliveryOrderCode: result?.delivery_order_code || result?.deliveryOrderCode || '', + message: result?.message || '发货单创建成功', + }, + }; + } catch (error) { + return { success: false, error: `建单失败: ${error.message}` }; + } + }, + }); + + this.register('blockUser', { + description: '屏蔽用户消息。将当前群和用户加入屏蔽列表,后续不再回复', + params: {}, + groups: [ GROUP.COMMON ], + handler: async (params = {}) => { + const { ctx } = this; + void params; + const groupName = String(ctx.inboxContext?.group_name || '').trim(); + const userName = String(ctx.inboxContext?.user_name || '').trim(); + + if (!groupName && !userName) { + return { + success: false, + error: '无法获取群名称或用户名称,屏蔽操作需要明确的群或用户身份', + }; + } + + try { + const { InboxBlock } = ctx.model; + await InboxBlock.create({ + group_name: groupName || null, + user_name: userName || null, + }); + + // 失效屏蔽缓存 + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + await ctx.service.inbox.processor.invalidateBlockCache(warehouseId); + + const scope = []; + if (groupName) scope.push(`群「${groupName}」`); + if (userName) scope.push(`用户「${userName}」`); + + return { + success: true, + data: { + blocked: groupName || userName, + message: `已屏蔽${scope.join('的')},后续将不再处理你的消息。如需解除屏蔽,请联系客服到WMS解除。`, + }, + }; + } catch (error) { + // 唯一键冲突 = 已屏蔽 + if (error.name === 'SequelizeUniqueConstraintError') { + return { + success: true, + data: { + message: '该群或用户已在屏蔽列表中,无需重复操作。如需解除屏蔽,请联系客服到WMS解除。', + }, + }; + } + return { + success: false, + error: `屏蔽操作失败: ${error.message}`, + }; + } + }, + }); + + this.register('listGroups', { + description: '查询当前仓库的群列表,包含屏蔽状态', + params: {}, + groups: [ GROUP.COMMON ], + handler: async (params = {}) => { + const { ctx } = this; + void params; + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + + if (!warehouseId) { + return { success: false, error: '无法获取仓库信息' }; + } + + try { + const groups = await ctx.model.InboxGroup.findAll({ + attributes: [ 'id', 'group_name', 'is_blocked', 'created_at' ], + where: { warehouse_id: warehouseId }, + order: [[ 'created_at', 'DESC' ]], + limit: 20, + raw: true, + }); + + return { + success: true, + data: { + warehouse_id: warehouseId, + total: groups.length, + groups: groups.map(g => ({ + name: g.group_name, + blocked: g.is_blocked === 1, + created_at: g.created_at, + })), + }, + }; + } catch (error) { + return { success: false, error: `查询群列表失败: ${error.message}` }; + } + }, + }); + } + + /** + * 注册一个函数。 + * + * @param {string} name 函数名称。 + * @param {Object} def 函数定义。 + * @param {string} def.description 函数描述(供 AI 理解用途)。 + * @param {Object} def.params 参数定义。 + * @param {string[]} def.groups 所属分组列表,按 {主分组}:{子分组} 格式。 + * 例如 ['common'] 或 ['bound:store', 'bound:store:after_sales']。 + * @param {Function} def.handler 函数实现,接收 params 对象,返回结果。 + */ + register(name, def) { + if (!name || typeof name !== 'string') { + throw new Error('函数名称必须是非空字符串'); + } + if (!def || typeof def.handler !== 'function') { + throw new Error(`函数 ${name} 必须提供 handler 实现`); + } + this.registry.set(name, { + name, + description: String(def.description || ''), + params: def.params || {}, + groups: Array.isArray(def.groups) && def.groups.length > 0 + ? def.groups + : [ GROUP.COMMON ], + handler: def.handler, + }); + this.ctx.logger.info(`[inbox functions] 注册函数: ${name} groups=${this.registry.get(name).groups.join(',')}`); + } + + /** + * 根据当前上下文解析可用分组集合。 + * + * ### 分组解析逻辑 + * + * - 始终包含 `common`(通用分组)。 + * - 若群已绑定货主(`store_id > 0` 且 `groupType === 'store'`): + * - 追加 `bound:store`(主分组)。 + * - 若有 `subType`(如 `after_sales`),追加 `bound:store:{subType}`。 + * - 若群已绑定仓库(`groupType === 'warehouse'`):追加 `bound:warehouse`。 + * - 若群已绑定快递(`groupType === 'express'`):追加 `bound:express`。 + * + * ### 使用方式 + * + * - AI 处理消息时自动调用,无需手动传参。 + * - 也可显式传入 `opts.groupType` / `opts.subType` 覆盖上下文。 + * + * @param {Object} [opts] 可选覆盖参数。 + * @param {string} [opts.groupType] 群类型(store / warehouse / express)。 + * @param {string} [opts.subType] 子类型(after_sales / finance / receiving)。 + * @return {string[]} 当前上下文中可用的分组列表。 + */ + resolveActiveGroups(opts = {}) { + const { ctx } = this; + const groups = [ GROUP.COMMON ]; + + const groupType = String( + opts.groupType || ctx.inboxContext?.group_type || '' + ).trim(); + const subType = String( + opts.subType || ctx.inboxContext?.sub_type || '' + ).trim(); + const storeId = Number(ctx.inboxContext?.store_id || 0); + + // 已绑定货主 → 加入 bound:store 及相关子分组 + if (storeId > 0 && groupType === 'store') { + groups.push(GROUP.BOUND_STORE); + const subGroup = `bound:store:${subType}`; + if (SUB_TO_MAIN[subGroup]) { + groups.push(subGroup); + } + } + + // 其他绑定类型预留 + if (storeId > 0 && groupType === 'warehouse') { + groups.push(GROUP.BOUND_WAREHOUSE); + } + if (storeId > 0 && groupType === 'express') { + groups.push(GROUP.BOUND_EXPRESS); + } + + return groups; + } + + /** + * 判断某个函数在当前活跃分组集合中是否可用。 + * + * ### 匹配规则 + * + * 1. 函数未声明 `groups` 或为空数组 → 视为 `['common']`,始终可用。 + * 2. 函数 `groups` 中包含 `common` → 始终可用。 + * 3. 函数 `groups` 中包含 `{主分组}:*` 通配(如 `bound:store:*`) → + * 展开为 `WILDCARD_EXPAND` 中定义的所有子分组,逐一与活跃分组求交集。 + * 4. 精确匹配:函数 `groups` 中的每一个精确分组名与活跃分组集合取交集。 + * + * @param {Object} def 函数定义对象(含 `groups` 字段)。 + * @param {string[]} activeGroups 当前上下文的活跃分组列表。 + * @return {boolean} 该函数在当前分组中是否可用。 + */ + isFunctionAvailable(def, activeGroups) { + if (!Array.isArray(def.groups) || def.groups.length === 0) return true; + + const expanded = []; + for (const g of def.groups) { + // 通配展开:bound:store:* → [bound:store, bound:store:after_sales, ...] + if (WILDCARD_EXPAND[g]) { + expanded.push(...WILDCARD_EXPAND[g]); + } else { + expanded.push(g); + } + } + + // common 分组或任一展开后的分组命中活跃集合即视为可用 + return expanded.some(g => g === GROUP.COMMON || activeGroups.includes(g)); + } + + /** + * 获取指定分组下的函数列表。 + * + * @param {string[]} [activeGroups] 活跃分组列表,不传则返回全部已注册函数。 + * @return {Array<{name: string, description: string, params: Object}>} 函数列表。 + */ + getFunctionList(activeGroups) { + const list = []; + for (const [ name, def ] of this.registry) { + if (activeGroups && !this.isFunctionAvailable(def, activeGroups)) continue; + list.push({ + name, + description: def.description, + params: def.params, + }); + } + return list; + } + + /** + * 构建函数列表的文本描述,供 AI prompt 使用。 + * + * @param {string[]} [activeGroups] 活跃分组列表,不传则返回全部。 + * @return {string} 函数列表文本。 + */ + buildFunctionListText(activeGroups) { + const lines = []; + for (const [ name, def ] of this.registry) { + if (activeGroups && !this.isFunctionAvailable(def, activeGroups)) continue; + const paramEntries = Object.entries(def.params); + const paramStr = paramEntries.length > 0 + ? paramEntries.map(([ k, v ]) => `${k}(${v.type || 'string'}, ${v.required ? '必填' : '可选'}): ${v.description}`).join(', ') + : '无参数'; + lines.push(`- ${name}: ${def.description}。参数: ${paramStr}`); + } + return lines.join('\n'); + } + + /** + * 执行已注册的函数。 + * + * @param {string} name 函数名称。 + * @param {Object} [params={}] 函数参数。 + * @return {Promise} 函数执行结果。 + */ + async callFunction(name, params = {}) { + const def = this.registry.get(name); + if (!def) { + return { + success: false, + error: `未注册的函数: ${name},可用函数: ${Array.from(this.registry.keys()).join(', ')}`, + }; + } + + try { + const result = await def.handler(params); + return result && typeof result === 'object' ? result : { success: true, data: result }; + } catch (error) { + return { + success: false, + error: `函数 ${name} 执行异常: ${error.message}`, + }; + } + } + + /** + * 调用 DeepSeek API。 + * + * @param {Array<{role: string, content: string}>} messages 消息列表。 + * @param {Object} [options] 额外选项。 + * @return {Promise} AI 返回的文本内容。 + */ + async callDeepSeek(messages, options = {}) { + const { ctx } = this; + const apiKey = ctx.app.config.deepseek.apiKey; + const baseUrl = ctx.app.config.deepseek.baseUrl || 'https://api.deepseek.com'; + + if (!apiKey) { + throw new Error('DeepSeek API Key 未配置'); + } + + const result = await ctx.curl(`${baseUrl}/v1/chat/completions`, { + method: 'POST', + contentType: 'json', + dataType: 'json', + headers: { Authorization: `Bearer ${apiKey}` }, + data: { + model: 'deepseek-v4-pro', + messages, + temperature: options.temperature ?? 0, + max_tokens: options.maxTokens ?? 1000, + }, + timeout: options.timeout || 30000, + }); + + if (result.status !== 200 || !result.data) { + throw new Error(`DeepSeek 请求失败, HTTP ${result.status}`); + } + + let content = result.data.choices?.[0]?.message?.content || ''; + // 清理 markdown 代码块 + content = content.replace(/^```json\s*/i, '').replace(/\s*```$/i, ''); + content = content.replace(/^```\s*/i, '').replace(/\s*```$/i, ''); + return content.trim(); + } + + /** + * 获取智能对话历史上下文。 + * 同一群 + 同一用户 → 最近 N 条消息(含 AI 回复),用于多轮对话短期记忆。 + * 按创建时间升序排列,并为每条消息附加序号供 AI 追踪。 + * + * @param {Object} opts 查询选项。 + * @param {number} [opts.parentId] 当前消息的 parent_id(兼容旧参数)。 + * @param {number} [opts.maxMessages=5] 最大历史消息数。 + * @return {Promise>} 历史消息列表。 + */ + async getConversationHistory(opts = {}) { + const parentId = Number(opts.parentId) || 0; + const maxMessages = Math.min(10, Math.max(1, Number(opts.maxMessages) || 5)); + + const { ctx } = this; + const { InboxMessage } = ctx.model; + const { Op } = ctx.app.Sequelize; + + const groupId = String(ctx.inboxContext?.group_id || '').trim(); + const userId = String(ctx.inboxContext?.user_id || '').trim(); + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + + // 无群/用户上下文时,退回旧逻辑:沿 parent_id 追溯 + if (!groupId || !userId || !warehouseId) { + if (!parentId) return []; + try { + const history = []; + let currentId = parentId; + const visited = new Set(); + while (currentId && history.length < maxMessages) { + if (visited.has(currentId)) break; + visited.add(currentId); + const msg = await InboxMessage.findOne({ + attributes: [ 'id', 'parent_id', 'direction', 'content' ], + where: { id: currentId }, + raw: true, + }); + if (!msg) break; + history.unshift({ role: msg.direction === 'inbound' ? 'user' : 'assistant', content: msg.content || '' }); + currentId = msg.parent_id; + } + return history; + } catch (error) { + ctx.logger.warn(`[inbox functions] 对话历史回退查询失败: ${error.message}`); + return []; + } + } + + // 智能查询:同一群+用户,最近 maxMessages 条(入站+出站混合) + try { + const messages = await InboxMessage.findAll({ + attributes: [ 'id', 'parent_id', 'direction', 'content', 'created_at' ], + where: { + warehouse_id: warehouseId, + group_id: groupId, + user_id: userId, + direction: { [Op.in]: [ 'inbound', 'outbound' ] }, + }, + order: [[ 'created_at', 'DESC' ]], + limit: maxMessages, + raw: true, + }); + + if (messages.length === 0) return []; + + // 升序排列(不再附加序号前缀,防止 AI 输出污染) + return messages.reverse().map(msg => ({ + role: msg.direction === 'inbound' ? 'user' : 'assistant', + content: msg.content || '', + })); + } catch (error) { + ctx.logger.warn(`[inbox functions] 智能对话历史查询失败: ${error.message}`); + return []; + } + } + + /** + * DeepSeek 多轮推理:思考→调函数→评估→(重复或输出)。 + * + * 每轮 AI 返回 JSON,通过 action 字段决定行为: + * { "action": "call", "function": "函数名", "params": {...}, "reason": "..." } + * { "action": "reply", "reply": "最终回复内容" } + * + * 最多 MAX_ROUNDS 轮,防止无限循环。 + * + * @param {Object} data 消息数据。 + * @param {string} data.content 消息正文。 + * @param {Object} [data.ext_data] 透传数据。 + * @param {number} [data.parentId] 父消息ID。 + * @return {Promise<{reply: string, functionName: string|null, functionResult: Object|null}>} AI 回复。 + */ + async processWithAI(data = {}) { + const { ctx } = this; + const content = String(data.content || '').trim(); + if (!content) { + return { reply: '消息正文为空,无法处理', functionName: null, functionResult: null }; + } + + const activeGroups = this.resolveActiveGroups(); + ctx.logger.info(`[inbox functions] 当前活跃分组: ${activeGroups.join(', ')}`); + + const functionListText = this.buildFunctionListText(activeGroups); + if (!functionListText) { + ctx.logger.info('[inbox functions] 当前上下文无可用的 AI 函数'); + return { reply: null, functionName: null, functionResult: null }; + } + + const history = await this.getConversationHistory({ + parentId: data.parentId, + maxMessages: 5, + }); + + const MAX_ROUNDS = 5; + const executedFunctions = []; + const thoughts = []; + let finalReply = null; + let lastFunctionName = null; + let lastFunctionResult = null; + + const systemPrompt = `你是一个 WMS 仓库管理系统的智能助手,支持多步推理。 +已注册函数:\n${functionListText}\n +你需要通过多轮调用来完成用户的复杂请求。每轮返回纯 JSON: + +如果还需要调用函数获取信息: +{ + "action": "call", + "function": "函数名", + "params": { "参数名": "参数值" }, + "reason": "为什么需要这个函数" +} + +如果信息充足可以回复用户了: +{ + "action": "reply", + "reply": "最终回复(中文纯文本,禁止Markdown,200字以内,可适当使用\\n换行分隔信息)" +} + +如果消息无需回复(用户只是确认、道谢、告别或表示自己处理): +{ + "action": "silent" +} + +约束: +- 最多 ${MAX_ROUNDS} 轮函数调用,第 ${MAX_ROUNDS} 轮必须给出最终回复 +- 同一函数不要重复调用(除非参数不同) +- 如果函数执行失败,换其他方式或直接告知用户 +- 回复使用中文纯文本,禁止 Markdown 语法,可用 \\n 换行提升可读性 +- silent 仅用于以下纯社交/确认性语句(用户无提问、无请求):"好的""收到""OK""谢谢""再见""等会再说""手工处理""知道了" +- 以下情况严禁 silent,必须 reply:用户提出疑问、请求查询/建单/操作、函数执行完毕需告知结果、库存为0需说明原因 +- 已调用函数获取了用户请求的数据后,必须 reply 告知结果,绝对不能 silent +- 无法判断是否需要回复时,宁可回复也不要 silent +- searchStock 返回多条结果时,必须列举让用户选择(告知 id/编码/名称/可用库存),不要擅自决定 +- createOrder 失败时告知失败原因(库存不足/商品不存在等),不要重试同一商品 +- searchStock 返回的 stock_available 为 0 时,提醒用户该商品无库存,建议选择其他商品 +- 用户说"第1个""第2个"时,按 searchStock 返回的顺序对应选择 +- 需要上下文但记忆不足时,主动调用 recallHistory 回顾对话历史`; + + // 多轮推理循环 + for (let round = 1; round <= MAX_ROUNDS; round++) { + const contextLines = []; + if (executedFunctions.length > 0) { + contextLines.push('已执行的函数及结果:'); + executedFunctions.forEach((f, i) => { + contextLines.push( + ` ${i + 1}. ${f.name}(${JSON.stringify(f.params)}) → ${JSON.stringify(f.result)}` + ); + }); + } + + const messages = [ + { role: 'system', content: systemPrompt }, + ...history, + ...(contextLines.length > 0 ? [{ role: 'system', content: contextLines.join('\n') }] : []), + { role: 'user', content: round === 1 + ? content + : (executedFunctions.length > 0 + ? `已获取到函数执行结果,请根据结果 reply 告知用户(禁止 silent)。第 ${round}/${MAX_ROUNDS} 轮` + : `请根据已获取的信息,决定下一步:继续调用函数还是给出最终回复。第 ${round}/${MAX_ROUNDS} 轮`), + }, + ]; + + let raw = ''; + try { + raw = await this.callDeepSeek(messages, { maxTokens: 600 }); + ctx.logger.info(`[inbox functions] 第 ${round}/${MAX_ROUNDS} 轮: ${raw}`); + + const result = JSON.parse(raw); + + // 记录思考过程 + thoughts.push({ + round, + action: result.action || 'unknown', + function: result.function || null, + params: result.params || null, + reason: result.reason || null, + }); + + if (result.action === 'reply') { + finalReply = String(result.reply || '').trim(); + if (!finalReply) finalReply = '已处理完成'; + break; + } + + if (result.action === 'silent') { + // 已调用过函数 → 必须回复结果,不能 silent + if (executedFunctions.length > 0) { + ctx.logger.info('[inbox functions] 已有函数调用,忽略 silent 继续要求回复'); + continue; + } + ctx.logger.info('[inbox functions] AI 判定无需回复,跳过回执'); + return { reply: null, functionName: null, functionResult: null, thoughts, skip: true }; + } + + if (result.action === 'call' && result.function) { + const fnName = String(result.function).trim(); + const params = result.params || {}; + + if (fnName === 'none' || fnName === 'stop') { + finalReply = result.reply || '已处理完成'; + break; + } + + lastFunctionName = fnName; + lastFunctionResult = await this.callFunction(fnName, params); + executedFunctions.push({ name: fnName, params, result: lastFunctionResult }); + + // 补充函数执行结果到思考记录 + const lastThought = thoughts[thoughts.length - 1]; + if (lastThought) lastThought.functionResult = lastFunctionResult; + ctx.logger.info(`[inbox functions] 执行 ${fnName}: ${JSON.stringify(lastFunctionResult)}`); + + // 最后一轮强制输出 + if (round === MAX_ROUNDS) { + finalReply = lastFunctionResult?.data?.message + || lastFunctionResult?.data?.greeting + || JSON.stringify(lastFunctionResult?.data || lastFunctionResult); + } + continue; + } + + // 无法解析 → 尝试提取 reply + finalReply = result.reply || result.message || '抱歉,暂时无法处理您的请求'; + break; + } catch (error) { + ctx.logger.warn(`[inbox functions] 第 ${round} 轮异常: ${error.message}, raw: ${raw}`); + + // 不是 JSON → 当作文本回复 + if (error instanceof SyntaxError && raw) { + finalReply = raw; + break; + } + + // 最后一轮兜底 + if (round === MAX_ROUNDS) { + finalReply = '抱歉,暂时无法处理您的请求,请稍后重试'; + } + continue; + } + } + + // 无回复的兜底 + if (!finalReply && lastFunctionResult) { + finalReply = lastFunctionResult?.data?.message + || lastFunctionResult?.data?.greeting + || (lastFunctionResult?.success !== false ? '操作已完成' : lastFunctionResult?.error || '处理完成'); + } + if (!finalReply) { + finalReply = '抱歉,暂时无法处理您的请求'; + } + + ctx.logger.info(`[inbox functions] 最终回复: ${finalReply}`); + return { + reply: finalReply, + functionName: lastFunctionName, + functionResult: lastFunctionResult, + thoughts, + }; + } +} + +module.exports = InboxFunctionsService; diff --git a/app/service/inbox/index.js b/app/service/inbox/index.js index c20b065..e2cfd53 100644 --- a/app/service/inbox/index.js +++ b/app/service/inbox/index.js @@ -9,13 +9,14 @@ const crypto = require('crypto'); */ class InboxService extends Service { /** - * 消息列表(按仓库/状态/方向筛选,分页)。 + * 消息列表(按仓库/状态/方向/群筛选,分页)。 * @param {Object} params 查询参数。 * @param {number} params.warehouseId 仓库ID(必填,服务端上下文注入)。 + * @param {string} [params.groupId] 按群ID筛选(精确匹配,用于群消息列表)。 * @param {string} [params.direction] 消息方向筛选:inbound / outbound。 * @param {number} [params.pushStatus] 推送状态筛选:0/1/2/3。 * @param {string} [params.targetChannel] 目标渠道筛选。 - * @param {string} [params.keyword] 关键词搜索(ext_id / ref_code)。 + * @param {string} [params.keyword] 关键词搜索(ext_id / content)。 * @param {number} [params.page=1] 页码。 * @param {number} [params.pageSize=20] 每页数量。 * @return {Promise<{list: Array, pagination: Object}>} 分页结果。 @@ -38,6 +39,12 @@ class InboxService extends Service { deleted_at: null, }; + // 按群ID筛选 + if (params.groupId && typeof params.groupId === 'string') { + const gid = params.groupId.trim(); + if (gid) where.group_id = gid; + } + if (params.direction && [ 'inbound', 'outbound' ].includes(params.direction)) { where.direction = params.direction; } @@ -49,15 +56,11 @@ class InboxService extends Service { } } - if (params.targetChannel && typeof params.targetChannel === 'string') { - where.target_channel = params.targetChannel.trim(); - } - if (params.keyword && typeof params.keyword === 'string') { const keyword = `%${params.keyword.trim()}%`; where[Op.or] = [ { ext_id: { [Op.like]: keyword } }, - + { content: { [Op.like]: keyword } }, ]; } @@ -188,13 +191,11 @@ class InboxService extends Service { } /** - * 系统回信:写入 outbound 记录 + 异步推送。 + * 系统回信:写入 outbound 记录。 * @param {Object} data 回信数据。 * @param {number} data.warehouseId 仓库ID(必填,服务端上下文注入)。 * @param {number} data.parentId 原消息ID。 - * @param {string} data.targetChannel 目标渠道。 - * @param {string} data.targetUrl 推送目标URL。 - * @param {string} [data.refCode] 引用编码。 + * @param {string} [data.content] 消息正文。 * @param {Object} [data.extData] 透传数据。 * @param {Object} [data.flags] 处理标记。 * @return {Promise} 回信结果。 @@ -232,10 +233,7 @@ class InboxService extends Service { parent_id: parentId, source_type: 'system', source_extra: null, - target_type: data.targetType || parent.target_type, - target_channel: data.targetChannel, - target_url: data.targetUrl, - ref_code: data.refCode || parent.ref_code, + content: data.content || null, ext_data: data.extData || parent.ext_data, flags: data.flags || {}, }); @@ -244,61 +242,7 @@ class InboxService extends Service { } /** - * 手动重推。 - * @param {Object} params 重推参数。 - * @param {number} params.warehouseId 仓库ID(必填)。 - * @param {number} params.id 消息ID。 - * @return {Promise} 重推结果。 - */ - async retry(params = {}) { - const { ctx } = this; - const { InboxMessage } = ctx.model; - - const warehouseId = Number(params.warehouseId); - const id = Number(params.id); - - if (!Number.isFinite(warehouseId) || warehouseId <= 0) { - throw new Error('warehouseId 无效'); - } - if (!Number.isFinite(id) || id <= 0) { - throw new Error('消息ID无效'); - } - - const record = await InboxMessage.findOne({ - where: { id, warehouse_id: warehouseId }, - }); - - if (!record) { - throw new Error('消息不存在或无权访问'); - } - - if (![ 3 ].includes(record.push_status)) { - throw new Error('仅失败状态的消息可以手动重推'); - } - - // 重置为待推送状态,由异步推送接管 - await record.update({ - push_status: 0, - push_started_at: null, - }); - - // 触发异步推送 - setImmediate(() => { - ctx.service.inbox.receiver.asyncPush(record, 0).catch(err => { - ctx.logger.error(`[inbox] 手动重推异常 ext_id=${record.ext_id}: ${err.message}`); - }); - }); - - return { - ok: true, - id: record.id, - ext_id: record.ext_id, - message: '已触发重推', - }; - } - - /** - * 推送统计(按仓库 + 状态汇总)。 + * 推送统计(按仓库 + 方向汇总)。 * @param {Object} params 统计参数。 * @param {number} params.warehouseId 仓库ID(必填)。 * @param {string} [params.direction] 消息方向筛选。 diff --git a/app/service/inbox/message.js b/app/service/inbox/message.js new file mode 100644 index 0000000..f572f26 --- /dev/null +++ b/app/service/inbox/message.js @@ -0,0 +1,335 @@ +'use strict'; + +const Service = require('egg').Service; + +/** + * 站内信消息查询/管理服务。 + * 提供消息列表、详情、对话链、回复、统计等管理功能。 + */ +class InboxMessageService extends Service { + /** + * 消息列表(多条件筛选,分页)。 + * 时间字段使用 app.formatDate 统一格式化输出。 + * + * @param {Object} params 查询参数。 + * @param {number} params.warehouseId 仓库ID(必填,服务端上下文注入)。 + * @param {string|string[]} [params.storeId] 货主ID筛选,支持逗号分隔字符串或数组。 + * @param {string|string[]} [params.groupId] 群ID筛选,支持逗号分隔字符串或数组。 + * @param {string} [params.groupName] 群名称模糊搜索。 + * @param {string} [params.userName] 用户名模糊搜索。 + * @param {string} [params.content] 正文模糊搜索。 + * @param {string} [params.sourceType] 来源类型:im / api / system。 + * @param {string} [params.direction] 消息方向筛选:inbound / outbound。 + * @param {number} [params.pushStatus] 推送状态筛选:0/1/2/3。 + * @param {number} [params.page=1] 页码。 + * @param {number} [params.pageSize=20] 每页数量。 + * @return {Promise<{list: Array, pagination: Object}>} 分页结果。 + */ + async list(params = {}) { + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + const { InboxMessage } = ctx.model; + + const warehouseId = Number(params.warehouseId); + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + throw new Error('warehouseId 无效'); + } + + const page = Math.max(1, Number(params.page) || 1); + const pageSize = Math.min(200, Math.max(1, Number(params.pageSize) || 20)); + + const where = { + warehouse_id: warehouseId, + deleted_at: null, + }; + + // 货主ID:支持多选(逗号分隔字符串或数组) + const storeIds = this._normalizeIds(params.storeId); + if (storeIds.length > 0) { + where.store_id = { [Op.in]: storeIds }; + } + + // 群ID:支持多选(逗号分隔字符串或数组) + const groupIds = this._normalizeStrings(params.groupId); + if (groupIds.length > 0) { + where.group_id = { [Op.in]: groupIds }; + } + + // 群名称模糊搜索 + const groupName = String(params.groupName || '').trim(); + if (groupName) { + where.group_name = { [Op.like]: `%${groupName}%` }; + } + + // 用户名模糊搜索 + const userName = String(params.userName || '').trim(); + if (userName) { + where.user_name = { [Op.like]: `%${userName}%` }; + } + + // 正文模糊搜索 + const content = String(params.content || '').trim(); + if (content) { + where.content = { [Op.like]: `%${content}%` }; + } + + // 来源类型筛选 + const VALID_SOURCE_TYPES = [ 'im', 'api', 'system' ]; + const sourceType = String(params.sourceType || '').trim(); + if (sourceType && VALID_SOURCE_TYPES.includes(sourceType)) { + where.source_type = sourceType; + } + + // 方向筛选 + if (params.direction && [ 'inbound', 'outbound' ].includes(params.direction)) { + where.direction = params.direction; + } + + // 推送状态筛选 + if (params.pushStatus !== undefined && params.pushStatus !== null && params.pushStatus !== '') { + const status = Number(params.pushStatus); + if ([ 0, 1, 2, 3 ].includes(status)) { + where.push_status = status; + } + } + + const { count: total, rows } = await InboxMessage.findAndCountAll({ + attributes: { + exclude: [ 'ext_data', 'push_response', 'target_channel' ], + }, + where, + order: [[ 'created_at', 'DESC' ]], + offset: (page - 1) * pageSize, + limit: pageSize, + }); + + // 批量查货主名称 + const storeIdsInResult = [ ...new Set(rows.map(r => r.store_id).filter(Boolean)) ]; + const storeNameMap = {}; + if (storeIdsInResult.length > 0) { + const stores = await ctx.model.Store.findAll({ + attributes: [ 'id', 'company_name' ], + where: { id: { [Op.in]: storeIdsInResult } }, + raw: true, + }); + for (const s of stores) { + storeNameMap[s.id] = s.company_name || ''; + } + } + + const formatDate = ctx.app.formatDate; + const list = rows.map(row => { + const obj = row && typeof row.toJSON === 'function' ? row.toJSON() : row; + return { + ...obj, + store_name: storeNameMap[obj.store_id] || '', + created_at: obj.created_at ? formatDate(obj.created_at) : '', + updated_at: obj.updated_at ? formatDate(obj.updated_at) : '', + pushed_at: obj.pushed_at ? formatDate(obj.pushed_at) : '', + }; + }); + + return { + list, + pagination: { + page, + pageSize, + total, + totalPages: Math.ceil(total / pageSize), + hasPrevious: page > 1, + hasNext: page * pageSize < total, + }, + }; + } + + /** + * 将入参统一为数字ID数组。 + * 支持逗号分隔字符串 "1,2,3" 或数组 [1,2,3]。 + * @param {string|string[]|number[]|undefined} val 入参。 + * @return {number[]} 去重后的数字数组。 + */ + _normalizeIds(val) { + if (val === undefined || val === null) return []; + const arr = Array.isArray(val) ? val : String(val).split(','); + return [ ...new Set(arr.map(Number).filter(v => Number.isFinite(v) && v > 0)) ]; + } + + /** + * 将入参统一为字符串数组(去重去空)。 + * @param {string|string[]|undefined} val 入参。 + * @return {string[]} 去重后的非空字符串数组。 + */ + _normalizeStrings(val) { + if (val === undefined || val === null) return []; + const arr = Array.isArray(val) ? val : String(val).split(','); + return [ ...new Set(arr.map(String).map(s => s.trim()).filter(Boolean)) ]; + } + + /** + * 消息详情(含 push_response)。 + * @param {Object} params 查询参数。 + * @param {number} params.warehouseId 仓库ID(必填)。 + * @param {number} params.id 消息ID。 + * @return {Promise} 消息详情。 + */ + async detail(params = {}) { + const { ctx } = this; + const { InboxMessage } = ctx.model; + + const warehouseId = Number(params.warehouseId); + const id = Number(params.id); + + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + throw new Error('warehouseId 无效'); + } + if (!Number.isFinite(id) || id <= 0) { + throw new Error('消息ID无效'); + } + + const record = await InboxMessage.findOne({ + where: { id, warehouse_id: warehouseId, deleted_at: null }, + }); + + if (!record) { + throw new Error('消息不存在或无权访问'); + } + + return record; + } + + /** + * 对话链查询(原消息 + 所有回信),按 parent_id 递归。 + * @param {Object} params 查询参数。 + * @param {number} params.warehouseId 仓库ID(必填)。 + * @param {number} params.id 消息ID。 + * @return {Promise} 对话链列表。 + */ + async thread(params = {}) { + const { ctx } = this; + const { InboxMessage } = ctx.model; + + const warehouseId = Number(params.warehouseId); + const id = Number(params.id); + + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + throw new Error('warehouseId 无效'); + } + if (!Number.isFinite(id) || id <= 0) { + throw new Error('消息ID无效'); + } + + // 查找根消息 + const root = await InboxMessage.findOne({ + where: { id, warehouse_id: warehouseId }, + }); + + if (!root) { + throw new Error('消息不存在或无权访问'); + } + + // 收集对话链:从根到叶 + const MAX_THREAD_DEPTH = 50; + const thread = [ root ]; + const visited = new Set([ root.id ]); + + // 查找所有回信(以 root.id 为 parent_id) + const replies = await InboxMessage.findAll({ + where: { + warehouse_id: warehouseId, + parent_id: root.id, + deleted_at: null, + }, + order: [[ 'created_at', 'ASC' ]], + }); + + for (const reply of replies) { + if (!visited.has(reply.id) && thread.length < MAX_THREAD_DEPTH) { + visited.add(reply.id); + thread.push(reply); + } + } + + // 如果当前消息不是根(有 parent_id),也向上查找原消息 + if (root.parent_id) { + const parent = await InboxMessage.findOne({ + where: { + id: root.parent_id, + warehouse_id: warehouseId, + deleted_at: null, + }, + }); + + if (parent && !visited.has(parent.id) && thread.length < MAX_THREAD_DEPTH) { + visited.add(parent.id); + thread.unshift(parent); + } + } + + return thread; + } + + /** + * 推送统计(按仓库 + 方向汇总)。 + * @param {Object} params 统计参数。 + * @param {number} params.warehouseId 仓库ID(必填)。 + * @return {Promise} 统计结果。 + */ + async stats(params = {}) { + const { ctx } = this; + const { InboxMessage } = ctx.model; + const { Op } = ctx.app.Sequelize; + + const warehouseId = Number(params.warehouseId); + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + throw new Error('warehouseId 无效'); + } + + const where = { + warehouse_id: warehouseId, + }; + + if (params.direction && [ 'inbound', 'outbound' ].includes(params.direction)) { + where.direction = params.direction; + } + + // 按方向统计 + const directionStats = await InboxMessage.findAll({ + attributes: [ + 'direction', + [ ctx.app.Sequelize.fn('COUNT', ctx.app.Sequelize.col('id')), 'count' ], + ], + where, + group: [ 'direction' ], + raw: true, + }); + + // 按推送状态统计 + const statusStats = await InboxMessage.findAll({ + attributes: [ + 'push_status', + [ ctx.app.Sequelize.fn('COUNT', ctx.app.Sequelize.col('id')), 'count' ], + ], + where, + group: [ 'push_status' ], + raw: true, + }); + + // 最近24小时统计 + const recentWhere = { + ...where, + created_at: { + [Op.gte]: new Date(Date.now() - 24 * 60 * 60 * 1000), + }, + }; + + const recentCount = await InboxMessage.count({ where: recentWhere }); + + return { + total_by_direction: directionStats, + total_by_status: statusStats, + recent_24h_count: recentCount, + }; + } +} + +module.exports = InboxMessageService; diff --git a/app/service/inbox/processor.js b/app/service/inbox/processor.js new file mode 100644 index 0000000..c256ea6 --- /dev/null +++ b/app/service/inbox/processor.js @@ -0,0 +1,570 @@ +'use strict'; + +const Service = require('egg').Service; + +const WAREHOUSE_INTERFACE_TYPE_ID = 3; +const CALLBACK_TIMEOUT_MS = 10000; // 回执超时 10s + +/** + * 站内信内容处理器。 + * 负责解析入站消息正文,按 source_type 分流处理, + * 将 warehouse_id 和 store_id 挂载到 ctx 上下文供下游使用。 + */ +class InboxProcessorService extends Service { + /** + * 处理入站消息内容。 + * 解析 content 后将 warehouse_id 和 store_id 写入 ctx 上下文。 + * + * @param {Object} data 入站消息数据。 + * @param {string} data.content 消息正文。 + * @param {number} [data.warehouse_id] 仓库ID(优先使用显式传入值)。 + * @param {number} [data.store_id] 货主ID(优先使用显式传入值)。 + * @return {Promise<{warehouse_id: number|null, store_id: number|null, content: string}>} 处理结果。 + */ + async process(data = {}) { + const { ctx } = this; + + const content = String(data.content || '').trim(); + if (!content) { + throw new Error('消息正文 content 不能为空'); + } + + // warehouse_id:优先取显式传入,否则尝试从 content 中解析 + let warehouseId = data.warehouse_id != null ? Number(data.warehouse_id) : null; + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + warehouseId = this.extractWarehouseId(content) || this.getWarehouseIdFromContext(); + } + + // store_id:优先取显式传入,否则尝试从 content 中解析 + let storeId = data.store_id != null ? Number(data.store_id) : null; + if (!Number.isFinite(storeId) || storeId <= 0) { + storeId = this.extractStoreId(content) || this.getStoreIdFromContext(); + } + + // 写入 ctx 上下文,供下游使用 + if (!ctx.inboxContext) { + ctx.inboxContext = {}; + } + ctx.inboxContext.warehouse_id = warehouseId || null; + ctx.inboxContext.store_id = storeId || null; + ctx.inboxContext.group_name = data.group_name || null; + ctx.inboxContext.user_name = data.user_name || null; + ctx.inboxContext.group_id = data.group_id || null; + ctx.inboxContext.user_id = data.user_id || null; + + ctx.logger.info( + '[inbox processor] 内容处理完成 ' + + `warehouse_id=${ctx.inboxContext.warehouse_id} ` + + `store_id=${ctx.inboxContext.store_id} ` + + `content_length=${content.length}` + ); + + return { + warehouse_id: ctx.inboxContext.warehouse_id, + store_id: ctx.inboxContext.store_id, + content, + }; + } + + /** + * API 来源消息异步回执。 + * 处理消息正文后,向仓库 ApiApp 回调地址 POST 确认回执。 + * 回执内容为"收到",ext_data 原路带回。 + * 异步执行,不阻塞入站响应。 + * + * @param {Object} data 入站消息数据。 + * @param {number} data.warehouse_id 仓库ID。 + * @param {number} [data.store_id] 货主ID。 + * @param {number} [data.parent_id] 入站消息记录ID(回执的 parent_id)。 + * @param {Object} [data.ext_data] 原始透传数据。 + * @param {string} [data.ext_id] 外部消息ID。 + * @param {string} [data.content] 消息正文。 + * @return {Promise} 无返回值,异常仅记日志不抛出。 + */ + async handleApiMessage(data = {}) { + const { ctx } = this; + const { InboxMessage } = ctx.model; + + const warehouseId = Number(data.warehouse_id) || 0; + const extId = String(data.ext_id || ''); + const parentId = Number(data.parent_id) || null; + + try { + // 1. 处理消息正文,挂载上下文 + await this.process(data); + + // 2. 屏蔽检查 + const isBlocked = await this.isBlocked(); + if (isBlocked) { + ctx.logger.info(`[inbox processor] 已屏蔽,跳过回执 ext_id=${extId}`); + return; + } + + // 3. 绑群码识别:消息匹配"授权:CODE"时执行绑群 + const bindHandled = await this.tryBindGroup(data); + if (bindHandled) return; + + // 4. 群未绑定货主则跳过 AI 解析 + const storeId = Number(ctx.inboxContext?.store_id || 0); + if (!storeId) { + ctx.logger.info(`[inbox processor] 群未绑定货主,跳过 AI ext_id=${extId}`); + return; + } + + // 4.1 注入群的 group_type / sub_type / ai_enabled 到上下文 + if (!ctx.inboxContext.group_type || !ctx.inboxContext.sub_type || ctx.inboxContext.ai_enabled === undefined) { + try { + const groupId = String(ctx.inboxContext.group_id || '').trim(); + if (groupId) { + const group = await ctx.model.InboxGroup.findOne({ + attributes: [ 'group_type', 'sub_type', 'ai_enabled' ], + where: { group_id: groupId, warehouse_id: warehouseId }, + raw: true, + }); + if (group) { + ctx.inboxContext.group_type = group.group_type || ''; + ctx.inboxContext.sub_type = group.sub_type || ''; + ctx.inboxContext.ai_enabled = group.ai_enabled; + ctx.logger.info( + `[inbox processor] 注入群分组信息 group_type=${ctx.inboxContext.group_type} sub_type=${ctx.inboxContext.sub_type} ai_enabled=${ctx.inboxContext.ai_enabled}` + ); + } + } + } catch (e) { + ctx.logger.warn(`[inbox processor] 查询群分组信息失败: ${e.message}`); + } + } + + // 4.2 群未启用AI → 跳过 AI 解析(灰度开关) + if (ctx.inboxContext.ai_enabled === 0) { + ctx.logger.info(`[inbox processor] 群未启用AI自动回复,跳过 AI ext_id=${extId}`); + return; + } + + // 5. DeepSeek 两步交互 + const aiResult = await ctx.service.inbox.functions.processWithAI({ + content: data.content || '', + ext_data: data.ext_data || null, + parentId: data.parent_id || null, + }); + + // 无回复且无函数调用 → 跳过,节约资源 + // AI 显式指示跳过(silent 动作)→ 同上 + if (aiResult.skip || (!aiResult.reply && (!aiResult.functionName || aiResult.functionName === 'none'))) { + ctx.logger.info(`[inbox processor] 无回复且未匹配函数,跳过回执 ext_id=${extId}`); + return; + } + + const replyContent = aiResult.reply || '已处理完成'; + ctx.logger.info( + `[inbox processor] AI 处理完成 ext_id=${extId} ` + + `function=${aiResult.functionName || 'direct'} reply_length=${replyContent.length}` + ); + + // 6. 写入 outbound 回执记录 + const ackExtId = `sys:ack:${extId}`; + + try { + const existAck = await InboxMessage.findOne({ + where: { ext_id: ackExtId }, + attributes: [ 'id' ], + paranoid: false, + }); + + if (!existAck) { + await InboxMessage.create({ + ext_id: ackExtId, + warehouse_id: warehouseId, + store_id: data.store_id || null, + direction: 'outbound', + parent_id: parentId, + source_type: 'system', + source_extra: null, + target_type: 'api', + group_id: ctx.inboxContext?.group_id || data.group_id || null, + user_id: ctx.inboxContext?.user_id || data.user_id || null, + group_name: ctx.inboxContext?.group_name || data.group_name || null, + user_name: ctx.inboxContext?.user_name || data.user_name || null, + content: replyContent, + ext_data: data.ext_data || null, + ai_thoughts: aiResult.thoughts || null, + flags: {}, + }); + + ctx.logger.info(`[inbox processor] 回执记录写入成功 parent_id=${parentId}`); + } + } catch (writeError) { + ctx.logger.warn(`[inbox processor] 回执记录写入失败: ${writeError.message}`); + } + + // 7. 查回调地址并发送 + const callbackUrl = await this.getApiAppCallbackUrl(warehouseId); + if (!callbackUrl) { + ctx.logger.info(`[inbox processor] 仓库 ${warehouseId} 未配置回调地址,跳过回执 ext_id=${extId}`); + return; + } + + const ackBody = { + content: replyContent, + ext_data: data.ext_data || null, + ext_id: extId || null, + }; + + ctx.logger.info(`[inbox processor] 发送 API 回执 ext_id=${extId} url=${callbackUrl}`); + + const response = await ctx.curl(callbackUrl, { + method: 'POST', + dataType: 'json', + contentType: 'json', + data: ackBody, + headers: { 'Content-Type': 'application/json' }, + timeout: CALLBACK_TIMEOUT_MS, + }); + + ctx.logger.info( + `[inbox processor] API 回执完成 ext_id=${extId} ` + + `http_status=${response.status}` + ); + } catch (error) { + ctx.logger.error( + `[inbox processor] API 回执失败 ext_id=${extId}: ${error.message}` + ); + } + } + + /** + * 尝试识别并执行绑群操作。 + * 匹配"授权:CODE",从缓存读取绑群信息并绑定货主到群。 + * + * @param {Object} data 消息数据。 + * @return {Promise} 是否已处理绑群。 + */ + async tryBindGroup(data = {}) { + const { ctx } = this; + const content = String(data.content || '').trim(); + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + const groupId = String(ctx.inboxContext?.group_id || '').trim(); + + const bindMatch = content.match(/授权[::]\s*([A-Z0-9]{6,20})/i); + if (!bindMatch || !groupId || !warehouseId) return false; + + const code = bindMatch[1].toUpperCase(); + + // 查群是否已绑定(直接查 DB,避免 ctx 上下文被仓库ID污染) + try { + const existingGroup = await ctx.model.InboxGroup.findOne({ + attributes: [ 'store_id' ], + where: { group_id: groupId, warehouse_id: warehouseId }, + raw: true, + }); + if (existingGroup && existingGroup.store_id) { + await this.writeOutboundReply(data, '已在绑定状态,无需重复操作'); + return true; + } + } catch (e) { + ctx.logger.warn(`[inbox processor] 查群绑定状态异常: ${e.message}`); + } + + const cacheKey = `chat:bind:${warehouseId}:${code}`; + + try { + const cacheValue = await ctx.app.getCacheAsync(cacheKey); + if (!cacheValue || !cacheValue.store_id) { + await this.writeOutboundReply(data, '绑群码无效或已过期,请重新生成'); + return true; + } + + let storeName = `货主${cacheValue.store_id}`; + try { + const store = await ctx.model.Store.findOne({ + attributes: [ 'store_name' ], + where: { id: cacheValue.store_id }, + raw: true, + }); + if (store && store.store_name) storeName = store.store_name; + } catch (e) { /* ignore */ } + + await ctx.model.InboxGroup.update( + { + store_id: cacheValue.store_id, + group_type: cacheValue.group_type || 'store', + sub_type: cacheValue.sub_type || null, + }, + { where: { group_id: groupId, warehouse_id: warehouseId } } + ); + + ctx.inboxContext.store_id = cacheValue.store_id; + ctx.inboxContext.group_type = cacheValue.group_type || 'store'; + ctx.inboxContext.sub_type = cacheValue.sub_type || null; + await ctx.app.setCacheAsync(cacheKey, null, 0); + + ctx.logger.info( + `[inbox processor] 绑群成功 group_id=${groupId} store=${storeName}` + ); + + await this.writeOutboundReply(data, `绑定「${storeName}」成功`); + + // 绑定成功后自动查询面单余额 + try { + const balanceResult = await ctx.service.inbox.functions.callFunction('queryPrintBalance', {}); + const balanceMsg = balanceResult?.success + ? `面单余额:总量 ${balanceResult.data.print_quantity},已锁定 ${balanceResult.data.print_quantity_locked},可用 ${balanceResult.data.available}` + : `面单余额查询失败:${balanceResult?.error || '未知错误'}`; + // 使用独立 ext_id 避免与绑定成功回执冲突 + await this.writeOutboundReply({ ...data, ext_id: `${data.ext_id}:balance` }, balanceMsg); + } catch (balanceErr) { + ctx.logger.warn(`[inbox processor] 绑群后面单余额查询异常: ${balanceErr.message}`); + } + + return true; + } catch (error) { + ctx.logger.error(`[inbox processor] 绑群异常: ${error.message}`); + return false; + } + } + + /** + * 写入 outbound 回执并发送 HTTP 回调。 + * group_id / user_id / group_name / user_name 为强制入参, + * 缺失任一将抛出异常。 + * + * @param {Object} data 消息数据。 + * @param {string} data.group_id 群ID(必填)。 + * @param {string} data.user_id 用户ID(必填)。 + * @param {string} data.group_name 群名称(必填)。 + * @param {string} data.user_name 用户名称(必填)。 + * @param {string} replyContent 回复内容。 + * @return {Promise} + */ + async writeOutboundReply(data, replyContent) { + const { ctx } = this; + const { InboxMessage } = ctx.model; + + const warehouseId = Number(data.warehouse_id || 0); + const extId = String(data.ext_id || ''); + const parentId = Number(data.parent_id || 0); + + // 强制入参校验 + const groupId = String(data.group_id || ctx.inboxContext?.group_id || '').trim(); + const userId = String(data.user_id || ctx.inboxContext?.user_id || '').trim(); + const groupName = String(data.group_name || ctx.inboxContext?.group_name || '').trim(); + const userName = String(data.user_name || ctx.inboxContext?.user_name || '').trim(); + + if (!groupId || !userId || !groupName || !userName) { + throw new Error( + `回执缺少必填字段: group_id=${groupId || '?'}, user_id=${userId || '?'}, ` + + `group_name=${groupName || '?'}, user_name=${userName || '?'}` + ); + } + + try { + const ackExtId = `sys:ack:${extId}`; + const existAck = await InboxMessage.findOne({ + where: { ext_id: ackExtId }, attributes: [ 'id' ], paranoid: false, + }); + if (!existAck) { + await InboxMessage.create({ + ext_id: ackExtId, warehouse_id: warehouseId, + store_id: ctx.inboxContext?.store_id || null, + direction: 'outbound', parent_id: parentId || null, + source_type: 'system', source_extra: null, + target_type: 'api', + group_id: groupId, + user_id: userId, + group_name: groupName, + user_name: userName, + content: replyContent, + ext_data: data.ext_data || null, flags: {}, + }); + } + + const callbackUrl = await this.getApiAppCallbackUrl(warehouseId); + if (callbackUrl) { + const curlResult = await ctx.curl(callbackUrl, { + method: 'POST', dataType: 'json', contentType: 'json', + data: { + content: replyContent, + ext_data: data.ext_data || null, + ext_id: extId, + group_id: groupId, + user_id: userId, + group_name: groupName, + user_name: userName, + }, + headers: { 'Content-Type': 'application/json' }, timeout: 10000, + }); + + // HTTP 200 → 更新回执消息推送状态为已送达 + if (curlResult && curlResult.status === 200) { + await InboxMessage.update( + { + push_status: 2, + push_response: { http_status: curlResult.status, body: curlResult.data || null }, + pushed_at: ctx.app.Sequelize.literal('CURRENT_TIMESTAMP'), + }, + { where: { ext_id: ackExtId } } + ); + + // 同步更新原入站消息的推送状态 + if (parentId) { + await InboxMessage.update( + { + push_status: 2, + pushed_at: ctx.app.Sequelize.literal('CURRENT_TIMESTAMP'), + }, + { where: { id: parentId } } + ); + } + } + } + } catch (error) { + ctx.logger.warn(`[inbox processor] 回执写入失败: ${error.message}`); + } + } + + /** + * 检查当前消息的群/用户是否在屏蔽列表中。 + * + * @return {Promise} 是否已屏蔽。 + */ + async isBlocked() { + const { ctx } = this; + const app = ctx.app; + const groupName = String(ctx.inboxContext?.group_name || '').trim(); + const userName = String(ctx.inboxContext?.user_name || '').trim(); + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + + if (!groupName && !userName) return false; + + try { + // 1. 尝试从缓存读取屏蔽列表 + const cacheKey = `inbox:block:${warehouseId}`; + let blockedSet = await app.getCacheAsync(cacheKey); + + if (!blockedSet || !(blockedSet instanceof Set)) { + // 2. 缓存未命中,查库并填入缓存 + const { InboxBlock } = ctx.model; + const rows = await InboxBlock.findAll({ attributes: [ 'group_name', 'user_name' ], raw: true }); + + blockedSet = new Set(); + for (const row of rows) { + const g = String(row.group_name || '').trim(); + const u = String(row.user_name || '').trim(); + if (g && u) blockedSet.add(`${g}:${u}`); + if (g) blockedSet.add(`${g}:*`); + if (u) blockedSet.add(`*:${u}`); + } + + // TTL 5 分钟 + await app.setCacheAsync(cacheKey, blockedSet, 300); + } + + // 3. 检查当前消息是否命中屏蔽规则 + if (groupName && userName && blockedSet.has(`${groupName}:${userName}`)) return true; + if (groupName && blockedSet.has(`${groupName}:*`)) return true; + if (userName && blockedSet.has(`*:${userName}`)) return true; + + return false; + } catch (error) { + ctx.logger.warn(`[inbox processor] 屏蔽检查异常: ${error.message}`); + return false; + } + } + + /** + * 失效屏蔽缓存,在新增屏蔽记录后调用。 + * + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 无返回值。 + */ + async invalidateBlockCache(warehouseId) { + const { ctx } = this; + try { + await ctx.app.setCacheAsync(`inbox:block:${warehouseId}`, null, 0); + } catch (error) { + ctx.logger.warn(`[inbox processor] 失效屏蔽缓存失败: ${error.message}`); + } + } + + /** + * 获取仓库 ApiApp 回调地址。 + * + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 回调 URL,未配置时返回 null。 + */ + async getApiAppCallbackUrl(warehouseId) { + const { ctx } = this; + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + return null; + } + + try { + const apiApp = await ctx.model.ApiApp.findOne({ + attributes: [ 'callback_url' ], + where: { + warehouse_id: warehouseId, + interface_type_id: WAREHOUSE_INTERFACE_TYPE_ID, + is_enabled: 1, + }, + raw: true, + }); + + return (apiApp && apiApp.callback_url) || null; + } catch (error) { + ctx.logger.warn(`[inbox processor] 查询回调地址失败: ${error.message}`); + return null; + } + } + + /** + * 尝试从消息正文中提取仓库ID。 + * 子类或业务方可覆盖此方法以实现自定义解析逻辑。 + * + * @param {string} content 消息正文。 + * @return {number|null} 仓库ID,无法解析时返回 null。 + */ + extractWarehouseId(content) { + // 默认不解析,由业务方覆盖 + void content; + return null; + } + + /** + * 尝试从消息正文中提取货主ID。 + * 子类或业务方可覆盖此方法以实现自定义解析逻辑。 + * + * @param {string} content 消息正文。 + * @return {number|null} 货主ID,无法解析时返回 null。 + */ + extractStoreId(content) { + // 默认不解析,由业务方覆盖 + void content; + return null; + } + + /** + * 从 Egg.js 请求上下文中获取仓库ID。 + * + * @return {number|null} 仓库ID。 + */ + getWarehouseIdFromContext() { + const { ctx } = this; + const user = ctx.user || ctx.state?.user || {}; + const warehouseId = Number(user.store_id || user.warehouse_id) || null; + return Number.isFinite(warehouseId) && warehouseId > 0 ? warehouseId : null; + } + + /** + * 从 Egg.js 请求上下文中获取货主ID。 + * + * @return {number|null} 货主ID。 + */ + getStoreIdFromContext() { + const { ctx } = this; + const user = ctx.user || ctx.state?.user || {}; + const storeId = Number(user.store_id) || null; + return Number.isFinite(storeId) && storeId > 0 ? storeId : null; + } +} + +module.exports = InboxProcessorService; diff --git a/app/service/inbox/receiver.js b/app/service/inbox/receiver.js index b68014e..b54acc1 100644 --- a/app/service/inbox/receiver.js +++ b/app/service/inbox/receiver.js @@ -2,157 +2,45 @@ const Service = require('egg').Service; -const { URL } = require('url'); -const { networkInterfaces } = require('os'); - -/** 推�?body 大小上限�?4KB */ -const MAX_PUSH_BODY_SIZE = 64 * 1024; -/** 最大重试次�?*/ -const MAX_RETRY_COUNT = 3; -/** 僵尸恢复阈值:5分钟 */ -const ZOMBIE_RECOVERY_MINUTES = 5; +/** 消息体大小上限 64KB */ +const MAX_BODY_SIZE = 64 * 1024; /** - * 收集本机所有内�?IPv4 地址�? - * @return {string[]} 内网IP地址列表�? - */ -function getLocalInternalIps() { - const ips = new Set(); - const nets = networkInterfaces(); - for (const interfaces of Object.values(nets)) { - for (const iface of interfaces) { - if (iface.family === 'IPv4' && !iface.internal) { - ips.add(iface.address); - } - } - } - return Array.from(ips); -} - -/** 内网 IP 前缀集合 */ -const INTERNAL_IP_PREFIXES = [ - '127.', - '10.', - '192.168.', - '0.', -]; - -/** - * 判断给定 IP 是否属于本机内网IP�? - * @param {string} ip IP地址�? - * @return {boolean} 是否为内网IP�? - */ -function isInternalIp(ip) { - if (!ip || ip === 'localhost') return true; - - // 检查已知内网前缀 - for (const prefix of INTERNAL_IP_PREFIXES) { - if (ip.startsWith(prefix)) return true; - } - - // 检�?172.16.0.0 ~ 172.31.255.255 - const parts = ip.split('.').map(Number); - if (parts.length === 4 && parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) { - return true; - } - - // 检查本机实际内网IP - const localIps = getLocalInternalIps(); - if (localIps.includes(ip)) return true; - - return false; -} - -/** - * 校验 target_url 安全性:仅允�?https://,禁止内网IP�? - * @param {string} urlStr 目标URL�? - * @throws {Error} URL 不合法时抛出�? - */ -// eslint-disable-next-line no-unused-vars -function validateTargetUrl(urlStr) { - if (!urlStr || typeof urlStr !== 'string') { - throw new Error('target_url 不能为空'); - } - - let parsed; - try { - parsed = new URL(urlStr); - } catch (e) { - throw new Error(`target_url 格式不合�? ${urlStr}`); - } - - if (parsed.protocol !== 'https:') { - throw new Error('target_url 仅允�?https:// 协议'); - } - - const hostname = parsed.hostname || ''; - if (isInternalIp(hostname)) { - throw new Error('target_url 不允许指向内网地址'); - } -} - -/** - * 站内信接收服务�? - * 统一处理消息入站:幂等去重、写库、异步推送、指数退避重试、僵尸恢复�? + * 站内信接收服务。 + * 统一处理消息入站:幂等去重、写库。 + * 暂不包含出站转发逻辑,纯入库管理。 */ class InboxReceiverService extends Service { /** - * 获取支持的目标渠道集合�? - * @return {Set} 支持的目标渠道�? - */ - static get SUPPORTED_CHANNELS() { - return new Set([ - 'webhook', - 'wecom', - 'dingtalk', - 'feishu', - 'warehouse_api', - ]); - } - - /** - * 初始化时执行僵尸恢复�? - * @param {Object} ctx Egg.js 上下文�? - */ - constructor(ctx) { - super(ctx); - // 异步执行僵尸恢复,不阻塞服务启动 - setImmediate(() => { - this.recoverZombieMessages().catch(err => { - ctx.logger.error(`[inbox] 僵尸恢复失败: ${err.message}`); - }); - }); - } - - /** - * 统一接收入口:幂等去重、写库、异步推送�? - * @param {Object} data 消息数据�? - * @param {string} data.ext_id 外部唯一消息主键�? - * @param {number} data.warehouse_id 所属仓库ID(服务端上下文注入,禁止外部传入)�? - * @param {number} [data.store_id] 关联货主ID�? - * @param {string} [data.direction='inbound'] 消息方向�? - * @param {number} [data.parent_id] 关联消息ID(回信时指向原消息)�? - * @param {string} data.source_type 来源类型:im / api / system�? - * @param {string} [data.source_extra] 来源附加信息�? - * @param {string} data.target_type 目标类型:im / api / webhook�? - * @param {string} data.target_channel 目标渠道�? - * @param {string} data.target_url 推送目标URL�? - * @param {string} [data.ref_code] 引用编码�? - * @param {Object} [data.ext_data] 透传数据�? - * @param {Object} [data.flags] 处理标记�? - * @return {Promise<{ok: boolean, id: number, ext_id: string}>} 接收结果�? + * 统一接收入口:幂等去重、写库。 + * @param {Object} data 消息数据。 + * @param {string} data.ext_id 外部唯一消息主键。 + * @param {number} data.warehouse_id 所属仓库ID(服务端上下文注入,禁止外部传入)。 + * @param {string} [data.direction='inbound'] 消息方向。 + * @param {number} [data.parent_id] 关联消息ID(回信时指向原消息)。 + * @param {string} data.source_type 来源类型:im / api / system。 + * @param {string} [data.source_extra] 来源附加信息。 + * @param {string} data.target_type 目标类型:im / api / webhook。 + * @param {string} [data.group_name] 群名称(外部传入)。 + * @param {string} [data.user_name] 用户名称(外部传入)。 + * @param {string} [data.group_id] 外部群ID。 + * @param {string} [data.user_id] 外部用户ID。 + * @param {string} [data.content] 消息正文/摘要。 + * @param {Object} [data.ext_data] 透传数据。 + * @param {Object} [data.flags] 处理标记。 + * @return {Promise<{ok: boolean, id: number, ext_id: string}>} 接收结果。 */ async receive(data = {}) { const { ctx } = this; const { InboxMessage } = ctx.model; - // 安全边界:校�?ext_id 不能为空 + // 安全边界:校验 ext_id 不能为空 const extId = String(data.ext_id || '').trim(); if (!extId) { throw new Error('ext_id 不能为空'); } - // 安全边界:warehouse_id 必须由服务端上下文提�? + // 安全边界:warehouse_id 必须由服务端上下文提供 const warehouseId = Number(data.warehouse_id); if (!Number.isFinite(warehouseId) || warehouseId <= 0) { throw new Error('warehouse_id 无效'); @@ -182,19 +70,10 @@ class InboxReceiverService extends Service { } } - - // 校验 target_channel 是否存在 - const targetChannel = String(data.target_channel || '').trim(); - if (!targetChannel || !InboxReceiverService.SUPPORTED_CHANNELS.has(targetChannel)) { - throw new Error(`不支持的目标渠道: ${targetChannel},支持的渠道: ${Array.from(InboxReceiverService.SUPPORTED_CHANNELS).join(', ')}`); - } - - // 安全边界:校�?target_url - // 幂等检查:ext_id 已存在则直接返回 const exist = await InboxMessage.findOne({ where: { ext_id: extId }, - attributes: [ 'id', 'ext_id', 'push_status' ], + attributes: [ 'id', 'ext_id' ], paranoid: false, }); @@ -207,69 +86,92 @@ class InboxReceiverService extends Service { }; } - // 推�?body 大小限制(序列化后检查) - const pushBody = { + // 消息体大小限制 + const checkBody = { + content: data.content || null, ext_data: data.ext_data || null, }; - const bodySize = Buffer.byteLength(JSON.stringify(pushBody), 'utf8'); - if (bodySize > MAX_PUSH_BODY_SIZE) { - throw new Error(`推�?body 超过 64KB 限制(当�?${Math.round(bodySize / 1024)}KB)`); + const bodySize = Buffer.byteLength(JSON.stringify(checkBody), 'utf8'); + if (bodySize > MAX_BODY_SIZE) { + throw new Error(`消息体超过 64KB 限制(当前 ${Math.round(bodySize / 1024)}KB)`); } - // 写库 - - // store_id 签约校验,若传入 store_id,必须存在有效合约关系 - const storeId = data.store_id ? Number(data.store_id) : null; - if (storeId && Number.isFinite(storeId) && storeId > 0) { - const contract = await ctx.model.StoreWarehouse.findOne({ - where: { - store_id: storeId, - warehouse_id: warehouseId, - auth_status: 2, - warehouse_use_status: 1, - }, - attributes: [ 'id' ], - }); - if (!contract) { - throw new Error(`store_id=${storeId} 与仓库 ${warehouseId} 无有效签约关系`); + // 从群绑定查询货主ID(外部不再直接传入 store_id) + let storeId = null; + const extGroupId = String(data.group_id || '').trim(); + if (extGroupId && warehouseId) { + try { + const group = await ctx.model.InboxGroup.findOne({ + attributes: [ 'store_id' ], + where: { group_id: extGroupId, warehouse_id: warehouseId }, + raw: true, + }); + if (group && group.store_id) { + storeId = Number(group.store_id); + } + } catch (groupErr) { + ctx.logger.warn(`[inbox] 查找群货主失败: ${groupErr.message}`); } } + + // 写库(暂不触发异步转发) const record = await InboxMessage.create({ ext_id: extId, warehouse_id: warehouseId, - store_id: data.store_id || null, + store_id: storeId || null, direction, parent_id: parentId, source_type: sourceType, source_extra: data.source_extra || null, target_type: targetType, - target_channel: targetChannel, + group_name: data.group_name || null, + user_name: data.user_name || null, + group_id: data.group_id || null, + user_id: data.user_id || null, + content: data.content || null, ext_data: data.ext_data || null, flags: data.flags || {}, - push_status: 0, }); ctx.logger.info(`[inbox] 消息入库成功 ext_id=${extId} id=${record.id}`); - // 异步后台推送(不阻塞响应) - setImmediate(() => { - this.asyncPush(record).catch(err => { - ctx.logger.error(`[inbox] setImmediate 异步推送异�?ext_id=${extId}: ${err.message}`); - // 异常已由 asyncPush 内部 try/catch,这里作为兜�? - try { - InboxMessage.update( - { - push_status: 3, - push_response: { error: `setImmediate 异常: ${err.message}` }, - pushed_at: new Date(), - }, - { where: { id: record.id, push_status: { [this.ctx.app.Sequelize.Op.in]: [ 0, 1 ] } } } - ); - } catch (updateErr) { - ctx.logger.error(`[inbox] 兜底更新推送状态失�?ext_id=${extId}: ${updateErr.message}`); - } + // 自动登记群(幂等 upsert) + const groupName = String(data.group_name || '').trim(); + if (groupName) { + try { + await ctx.model.InboxGroup.findOrCreate({ + where: { group_name: groupName, warehouse_id: warehouseId }, + defaults: { + group_id: extGroupId, + store_id: storeId || null, + source_type: sourceType, + source_extra: data.source_extra || null, + }, + }); + } catch (groupErr) { + ctx.logger.warn(`[inbox] 群登记失败: ${groupErr.message}`); + } + } + + // source_type 分流:API 来源异步回执 + if (sourceType === 'api') { + setImmediate(() => { + ctx.service.inbox.processor.handleApiMessage({ + warehouse_id: warehouseId, + store_id: storeId, + parent_id: record.id, + ext_data: data.ext_data || null, + ext_id: extId, + content: data.content || '', + group_name: data.group_name || null, + user_name: data.user_name || null, + group_id: data.group_id || null, + user_id: data.user_id || null, + }).catch(err => { + ctx.logger.error(`[inbox] API 异步回执异常 ext_id=${extId}: ${err.message}`); + }); }); - }); + } return { ok: true, @@ -277,133 +179,6 @@ class InboxReceiverService extends Service { ext_id: extId, }; } - - /** - * 异步推�?+ 指数退避重试�? - * @param {Object} record 消息记录(Sequelize Model 实例)�? - * @param {number} [attempt=0] 当前重试次数�? - * @return {Promise} 推送结果�? - */ - async asyncPush(record, attempt = 0) { - const { ctx } = this; - const { InboxMessage } = ctx.model; - const { Op } = ctx.app.Sequelize; - - try { - // 乐观锁:�?push_status=0 或(重试�?push_status=3)时可取�? - const allowedStatuses = attempt === 0 ? [ 0 ] : [ 3 ]; - const [ updatedCount ] = await InboxMessage.update( - { - push_status: 1, - push_started_at: new Date(), - }, - { - where: { - id: record.id, - push_status: { [Op.in]: allowedStatuses }, - }, - } - ); - - if (updatedCount === 0) { - ctx.logger.info(`[inbox] 消息已被其他进程取走,跳过推�?ext_id=${record.ext_id} id=${record.id}`); - return; - } - - // 获取 dispatch 服务 - const channel = record.target_channel; - if (!InboxReceiverService.SUPPORTED_CHANNELS.has(channel)) { - throw new Error(`不支持的目标渠道: ${channel}`); - } - - // 统一渠道映射:warehouse_api �?webhook - const dispatchChannel = channel === 'warehouse_api' ? 'webhook' : channel; - const dispatchService = ctx.service.inbox.dispatch[dispatchChannel]; - - if (!dispatchService || typeof dispatchService.push !== 'function') { - throw new Error(`dispatch 渠道 ${dispatchChannel} 未实现`); - } - - // 执行推�? - const response = await dispatchService.push(record); - - // 推送成�? - await InboxMessage.update( - { - push_status: 2, - push_response: { - http_status: response.status, - body: response.data, - }, - pushed_at: new Date(), - }, - { where: { id: record.id, push_status: 1 } } - ); - - ctx.logger.info(`[inbox] 推送成�?ext_id=${record.ext_id} channel=${channel}`); - } catch (error) { - const next = attempt + 1; - ctx.logger.warn(`[inbox] 推送失�?ext_id=${record.ext_id} attempt=${next} error=${error.message}`); - - // 更新失败状�? - await InboxMessage.update( - { - push_status: next >= MAX_RETRY_COUNT ? 3 : 3, - retry_count: next, - push_response: { error: error.message }, - ...(next >= MAX_RETRY_COUNT ? { pushed_at: new Date() } : {}), - }, - { where: { id: record.id, push_status: 1 } } - ); - - // 指数退避重试:30s �?60s �?120s - if (next < MAX_RETRY_COUNT) { - const delay = 30000 * Math.pow(2, attempt); - ctx.logger.info(`[inbox] 将在 ${delay / 1000}s 后重�?ext_id=${record.ext_id} attempt=${next}`); - setTimeout(() => { - this.asyncPush(record, next).catch(err => { - ctx.logger.error(`[inbox] 重试推送异�?ext_id=${record.ext_id}: ${err.message}`); - }); - }, delay); - } else { - ctx.logger.error(`[inbox] 推送达到最大重试次数,标记为终态失�?ext_id=${record.ext_id}`); - } - } - } - - /** - * 僵尸恢复:重置卡�?推送中"超过5分钟的消息为"待推�?�? - * 在服务启动时及定时任务中调用�? - * @return {Promise} 恢复的消息数量�? - */ - async recoverZombieMessages() { - const { ctx } = this; - const { InboxMessage } = ctx.model; - const { Op } = ctx.app.Sequelize; - - const threshold = new Date(Date.now() - ZOMBIE_RECOVERY_MINUTES * 60 * 1000); - - const [ updatedCount ] = await InboxMessage.update( - { - push_status: 0, - push_started_at: null, - }, - { - where: { - push_status: 1, - push_started_at: { - [Op.lt]: threshold, - }, - }, - } - ); - - if (updatedCount > 0) { - ctx.logger.info(`[inbox] 僵尸恢复完成,重�?${updatedCount} 条消息为待推送`); - } - - return updatedCount; - } } module.exports = InboxReceiverService; diff --git a/app/service/systemMethods/inbox.js b/app/service/systemMethods/inbox.js new file mode 100644 index 0000000..f3314f5 --- /dev/null +++ b/app/service/systemMethods/inbox.js @@ -0,0 +1,189 @@ +'use strict'; + +const MainService = require('../main'); + +/** + * 站内信系统方法层。 + * 提供需要用户权限的内部管理接口。 + */ +class InboxSystemService extends MainService { + /** + * 群管理子入口,供 /system dispatcher 按 inbox.group.* 路径访问。 + * @return {{list: Function, disable: Function, update: Function, messages: Function, checkAuth: Function}} + */ + get group() { + return { + list: data => this.groupList(data), + disable: data => this.groupDisable(data), + update: data => this.groupUpdate(data), + messages: data => this.groupMessages(data), + checkAuth: (...args) => this.checkAuth(...args), + }; + } + + /** + * 消息管理子入口,供 /system dispatcher 按 inbox.message.* 路径访问。 + * @return {{list: Function, detail: Function, thread: Function, reply: Function, stats: Function, checkAuth: Function}} + */ + get message() { + const { ctx } = this; + return { + list: data => { + const warehouseId = Number(ctx.user?.store_id || 0); + return ctx.service.inbox.message.list({ warehouseId, ...data }); + }, + detail: data => { + const warehouseId = Number(ctx.user?.store_id || 0); + return ctx.service.inbox.message.detail({ warehouseId, id: data.id }); + }, + thread: data => { + const warehouseId = Number(ctx.user?.store_id || 0); + return ctx.service.inbox.message.thread({ warehouseId, id: data.id }); + }, + stats: data => { + const warehouseId = Number(ctx.user?.store_id || 0); + return ctx.service.inbox.message.stats({ warehouseId, direction: data.direction }); + }, + checkAuth: (...args) => this.checkAuth(...args), + }; + } + + /** + * 生成货主绑群码。 + * 委托给 systems.store.bindCode 执行:校验 StoreWarehouse 合约 → 生成12位随机码 → 缓存300秒。 + * warehouseId 从 ctx.user.store_id 自动注入,绑群码缓存 key 为 chat:bind:{warehouseId}:{code}。 + * + * @param {Object} data 请求数据。 + * @param {number} data.storeId 货主ID。 + * @param {string} [data.subType] 群子类型编码:after_sales(售后) / finance(财务) / receiving(收货)。 + * @return {Promise} { code: 绑群码 }。 + */ + async bindCode(data = {}) { + const { ctx } = this; + const { storeId, subType } = data; + const warehouseId = Number(ctx.user?.store_id || 0); + + return await ctx.service.systems.store.bindCode({ + storeId, + warehouseId, + subType, + }); + } + + /** + * 拉取当前仓库的群列表。 + * warehouseId 从 ctx.user.store_id 自动注入。 + * + * @param {Object} data 请求数据。 + * @param {string} [data.groupType] 按群类型筛选:store / warehouse / express。 + * @param {string} [data.keyword] 群名称模糊搜索。 + * @param {number} [data.page] 页码。 + * @param {number} [data.pageSize] 每页条数。 + * @return {Promise} { total, list }。 + */ + async groupList(data = {}) { + const { ctx } = this; + const { groupType, keyword, page, pageSize } = data; + const warehouseId = Number(ctx.user?.store_id || 0); + + return await ctx.service.systems.inbox.group.list({ + warehouseId, + groupType, + keyword, + page, + pageSize, + }); + } + + /** + * 禁用 / 解禁群。 + * warehouseId 从 ctx.user.store_id 自动注入。 + * + * @param {Object} data 请求数据。 + * @param {number} data.id 群记录主键ID(必填)。 + * @param {number} [data.isBlocked=1] 是否禁用 1=是 0=否。 + * @return {Promise} { message: 操作结果 }。 + */ + async groupDisable(data = {}) { + const { ctx } = this; + const { id, isBlocked } = data; + const warehouseId = Number(ctx.user?.store_id || 0); + + await ctx.service.systems.inbox.group.disable({ + id, + warehouseId, + isBlocked: isBlocked === 0 ? 0 : 1, + }); + + return { message: isBlocked === 0 ? '群已启用' : '群已禁用' }; + } + + /** + * 修改群信息。 + * 支持修改 group_type / sub_type / store_id / express_interfaces / system_express_code。 + * warehouseId 从 ctx.user.store_id 自动注入。 + * + * @param {Object} data 请求数据。 + * @param {number} data.id 群记录主键ID(必填)。 + * @param {string} [data.groupType] 群类型:store / warehouse / express。 + * @param {string} [data.subType] 群子类型。 + * @param {number} [data.storeId] 关联货主ID。 + * @param {number[]} [data.expressInterfaces] 快递接口ID数组(仅 express 生效)。 + * @param {string} [data.systemExpressCode] 系统快递编码(express 时必填)。 + * @return {Promise} { message: 操作结果 }。 + */ + async groupUpdate(data = {}) { + const { ctx } = this; + const { + id, groupType, subType, storeId, + expressInterfaces, systemExpressCode, aiEnabled, + } = data; + const warehouseId = Number(ctx.user?.store_id || 0); + + await ctx.service.systems.inbox.group.update({ + id, + warehouseId, + groupType, + subType, + storeId, + expressInterfaces, + systemExpressCode, + aiEnabled, + }); + + return { message: '群信息修改成功' }; + } + + /** + * 拉取指定群的消息列表。 + * warehouseId 从 ctx.user.store_id 自动注入。 + * + * @param {Object} data 请求数据。 + * @param {string} data.groupId 群ID(必填)。 + * @param {string} [data.direction] 消息方向筛选:inbound / outbound。 + * @param {string} [data.keyword] 关键词搜索(ext_id / content)。 + * @param {number} [data.page] 页码。 + * @param {number} [data.pageSize] 每页条数。 + * @return {Promise} { list, pagination }。 + */ + async groupMessages(data = {}) { + const { ctx } = this; + const { groupId, direction, keyword, page, pageSize } = data; + const warehouseId = Number(ctx.user?.store_id || 0); + + if (!groupId || typeof groupId !== 'string' || !groupId.trim()) { + throw new Error('groupId 不能为空'); + } + + return await ctx.service.inbox.message.list({ + warehouseId, + groupId: groupId.trim(), + direction, + keyword, + page, + pageSize, + }); + } +} + +module.exports = InboxSystemService; diff --git a/app/service/systemMethods/order/wave.js b/app/service/systemMethods/order/wave.js index db41349..fa27eb0 100644 --- a/app/service/systemMethods/order/wave.js +++ b/app/service/systemMethods/order/wave.js @@ -12732,7 +12732,7 @@ class WaveService extends OrderBaseService { try { const directFetchResult = await this.executeWaveStrategyDirectFetch({ plan, - waveBatchSource: 1, + waveBatchSource: 0, }); this.ctx.logger.info('[wave.waveStrategyFetchAdmin] 建波成功', { diff --git a/app/service/systems/inbox/group.js b/app/service/systems/inbox/group.js new file mode 100644 index 0000000..876daf3 --- /dev/null +++ b/app/service/systems/inbox/group.js @@ -0,0 +1,250 @@ +'use strict'; + +const Service = require('egg').Service; + +/** + * 站内信群管理业务逻辑层。 + * 提供群列表查询、禁用、修改等核心能力。 + */ +class InboxGroupService extends Service { + /** + * 拉取当前仓库的群列表。 + * + * @param {Object} data 请求数据。 + * @param {number} data.warehouseId 仓库ID(必填,由 controller 注入)。 + * @param {string} [data.groupType] 按群类型筛选:store / warehouse / express。 + * @param {string} [data.keyword] 按群名称模糊搜索。 + * @param {number} [data.page=1] 页码。 + * @param {number} [data.pageSize=20] 每页条数。 + * @return {Promise} { total, list }。 + */ + async list(data = {}) { + const { ctx } = this; + const { InboxGroup } = ctx.model; + const { Op } = ctx.app.Sequelize; + + const warehouseId = Number(data.warehouseId); + const groupType = String(data.groupType || '').trim(); + const keyword = String(data.keyword || '').trim(); + const page = Math.max(1, Number(data.page) || 1); + const pageSize = Math.min(100, Math.max(1, Number(data.pageSize) || 20)); + const offset = (page - 1) * pageSize; + + if (!warehouseId) throw new Error('warehouseId 无效'); + + const where = { warehouse_id: warehouseId }; + if (groupType) where.group_type = groupType; + if (keyword) where.group_name = { [Op.like]: `%${keyword}%` }; + + const { count, rows } = await InboxGroup.findAndCountAll({ + attributes: [ + 'id', 'group_name', 'group_id', 'warehouse_id', 'store_id', + 'group_type', 'sub_type', 'source_type', 'source_extra', + 'is_blocked', 'ai_enabled', 'express_interfaces', 'system_express_code', + 'created_at', 'updated_at', + ], + where, + order: [[ 'created_at', 'DESC' ]], + limit: pageSize, + offset, + raw: true, + }); + + // express_interfaces 输出为数组 + const list = rows.map(row => ({ + ...row, + express_interfaces: row.express_interfaces + ? row.express_interfaces.split(',').map(Number).filter(Boolean) + : [], + })); + + return { total: count, list }; + } + + /** + * 禁用 / 解禁群。 + * + * @param {Object} data 请求数据。 + * @param {number} data.id 群记录主键ID(必填)。 + * @param {number} data.warehouseId 仓库ID(必填,由 controller 注入)。 + * @param {number} data.isBlocked 是否屏蔽 1=禁用 0=启用。 + * @return {Promise} + */ + async disable(data = {}) { + const { ctx } = this; + const { InboxGroup } = ctx.model; + + const id = Number(data.id); + const warehouseId = Number(data.warehouseId); + const isBlocked = data.isBlocked === 1 ? 1 : 0; + + if (!id) throw new Error('群ID无效'); + if (!warehouseId) throw new Error('warehouseId 无效'); + + const [ affected ] = await InboxGroup.update( + { is_blocked: isBlocked }, + { where: { id, warehouse_id: warehouseId } } + ); + + if (!affected) { + throw new Error('群不存在或无权限操作'); + } + + ctx.logger.info( + `[inbox group] ${isBlocked ? '禁用' : '启用'}群 id=${id} warehouse_id=${warehouseId}` + ); + } + + /** + * 修改群信息。 + * 支持修改 group_type / sub_type / store_id / express_interfaces / system_express_code。 + * 群类型切为 express 时 system_express_code 必填, + * express_interfaces 仅在群类型为 express 时生效(非 express 类型忽略)。 + * + * @param {Object} data 请求数据。 + * @param {number} data.id 群记录主键ID(必填)。 + * @param {number} data.warehouseId 仓库ID(必填,由 controller 注入)。 + * @param {string} [data.groupType] 群类型:store / warehouse / express。 + * @param {string} [data.subType] 群子类型。 + * @param {number} [data.storeId] 关联货主ID。 + * @param {number[]} [data.expressInterfaces] 快递接口ID数组。 + * @param {string} [data.systemExpressCode] 系统快递编码。 + * @return {Promise} + */ + async update(data = {}) { + const { ctx } = this; + const { InboxGroup } = ctx.model; + + const id = Number(data.id); + const warehouseId = Number(data.warehouseId); + + if (!id) throw new Error('群ID无效'); + if (!warehouseId) throw new Error('warehouseId 无效'); + + // 查群是否存在 + const group = await InboxGroup.findOne({ + attributes: [ 'id', 'group_type', 'group_id', 'warehouse_id' ], + where: { id, warehouse_id: warehouseId }, + raw: true, + }); + if (!group) throw new Error('群不存在或无权限操作'); + + // 目标群类型(优先新值,否则保留原值) + const targetGroupType = data.groupType !== undefined + ? String(data.groupType).trim() + : group.group_type || ''; + const isExpress = targetGroupType === 'express'; + + // express_interfaces 处理 + let expressInterfaces = null; + if (data.expressInterfaces !== undefined) { + if (Array.isArray(data.expressInterfaces) && data.expressInterfaces.length > 0) { + // 校验快递接口ID有效性 + await this.validateExpressInterfaces(data.expressInterfaces); + expressInterfaces = data.expressInterfaces.join(','); + } else if (Array.isArray(data.expressInterfaces) && data.expressInterfaces.length === 0) { + // 空数组 = 清空 = 表示全部快递类型 + expressInterfaces = ''; + } else { + expressInterfaces = null; // 未传入 = 不修改 + } + } + + // system_express_code 校验 + let systemExpressCode; + if (data.systemExpressCode !== undefined) { + const code = String(data.systemExpressCode).trim(); + if (code) { + await this.validateSystemExpressCode(code); + systemExpressCode = code; + } else { + systemExpressCode = null; + } + } + + // 切换为 express 类型时 system_express_code 不能为空 + if (isExpress && data.groupType !== undefined) { + const finalCode = systemExpressCode !== undefined ? systemExpressCode : group.system_express_code; + if (!finalCode) { + throw new Error('群类型为快递群时,系统快递编码不能为空'); + } + } + + // 构建更新字段 + const updateData = {}; + if (data.groupType !== undefined) updateData.group_type = targetGroupType || null; + if (data.subType !== undefined) updateData.sub_type = String(data.subType || '').trim() || null; + if (data.storeId !== undefined) { + updateData.store_id = Number.isFinite(Number(data.storeId)) && Number(data.storeId) > 0 + ? Number(data.storeId) : null; + } + // 非 express 群类型时忽略 express 相关字段 + if (isExpress && expressInterfaces !== null) { + updateData.express_interfaces = expressInterfaces || null; + } + if (isExpress && systemExpressCode !== undefined) { + updateData.system_express_code = systemExpressCode || null; + } + // AI 开关(所有群类型均支持) + if (data.aiEnabled !== undefined) { + updateData.ai_enabled = data.aiEnabled === 1 ? 1 : 0; + } + + if (Object.keys(updateData).length === 0) { + throw new Error('未提供任何需要修改的字段'); + } + + await InboxGroup.update(updateData, { where: { id, warehouse_id: warehouseId } }); + ctx.logger.info( + `[inbox group] 修改群 id=${id} fields=${Object.keys(updateData).join(',')}` + ); + } + + /** + * 校验快递接口ID数组的有效性。 + * 所有ID必须在 wms_express_interface 表中存在。 + * + * @param {number[]} ids 快递接口ID数组。 + * @return {Promise} 无效时抛出异常。 + */ + async validateExpressInterfaces(ids) { + const { ctx } = this; + if (!Array.isArray(ids) || ids.length === 0) return; + + const numericIds = ids.map(Number).filter(id => Number.isFinite(id) && id > 0); + if (numericIds.length !== ids.length) { + throw new Error('快递接口ID包含无效值'); + } + + const count = await ctx.model.ExpressInterface.count({ + where: { id: { [ctx.app.Sequelize.Op.in]: numericIds } }, + }); + + if (count !== numericIds.length) { + throw new Error('部分快递接口ID不存在'); + } + } + + /** + * 校验系统快递编码有效性。 + * 必须在 wms_express 表中存在对应的 code。 + * + * @param {string} code 系统快递编码。 + * @return {Promise} 无效时抛出异常。 + */ + async validateSystemExpressCode(code) { + const { ctx } = this; + const trimmed = String(code).trim(); + if (!trimmed) throw new Error('系统快递编码不能为空'); + + const exists = await ctx.model.Express.count({ + where: { code: trimmed }, + }); + + if (!exists) { + throw new Error(`系统快递编码 "${trimmed}" 不存在`); + } + } +} + +module.exports = InboxGroupService; diff --git a/app/service/systems/store.js b/app/service/systems/store.js index 5358472..d43daf9 100644 --- a/app/service/systems/store.js +++ b/app/service/systems/store.js @@ -1004,6 +1004,73 @@ class StoreService extends Service { throw error; } } + + /** + * 生成货主绑群码。 + * 查询货主与仓库的有效合约,生成 12 位随机码并存入缓存(5分钟有效)。 + * + * @param {Object} data 请求数据。 + * @param {number} data.storeId 货主ID(必填)。 + * @param {number} data.warehouseId 仓库ID(必填,由 systemMethods 层注入)。 + * @param {string} [data.subType] 群子类型:after_sales / finance / receiving。 + * @return {Promise} { code: 绑群码 }。 + */ + async bindCode(data = {}) { + const { ctx } = this; + const storeId = Number(data.storeId); + const warehouseId = Number(data.warehouseId); + + if (!Number.isFinite(storeId) || storeId <= 0) { + throw new Error('storeId 无效'); + } + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + throw new Error('缺少仓库信息,请确认已登录并选择了仓库'); + } + + const contract = await ctx.model.StoreWarehouse.findOne({ + attributes: [ 'id', 'store_id', 'warehouse_id', 'initiator_subject_id' ], + where: { + store_id: storeId, + warehouse_id: warehouseId, + auth_status: 2, + warehouse_use_status: 1, + }, + raw: true, + }); + + if (!contract) { + throw new Error(`货主 ${storeId} 在仓库 ${warehouseId} 无有效合约`); + } + + const subType = String(data.subType || '').trim(); + const VALID_SUB_TYPES = [ 'after_sales', 'finance', 'receiving' ]; + if (subType && !VALID_SUB_TYPES.includes(subType)) { + throw new Error(`无效的子类型: ${subType},可选值: ${VALID_SUB_TYPES.join(' / ')}`); + } + + const code = Math.random().toString(36).slice(2, 8) + .toUpperCase() + + Math.random().toString(36).slice(2, 8) + .toUpperCase(); + const cacheKey = `chat:bind:${warehouseId}:${code}`; + + const cacheValue = { + store_id: contract.store_id, + initiator_subject_id: contract.initiator_subject_id || null, + warehouse_id: contract.warehouse_id, + group_type: 'store', + sub_type: subType || null, + }; + + await ctx.app.setCacheAsync(cacheKey, cacheValue, 300); + + ctx.logger.info( + `[store bindCode] 生成绑群码 code=${code} ` + + `store_id=${contract.store_id} warehouse_id=${warehouseId}` + ); + + return { code }; + } } module.exports = StoreService; diff --git a/app/service/warehouseMethods/inbox.js b/app/service/warehouseMethods/inbox.js index 7232976..23c7fa9 100644 --- a/app/service/warehouseMethods/inbox.js +++ b/app/service/warehouseMethods/inbox.js @@ -29,10 +29,6 @@ class WarehouseInboxService extends MainService { throw new Error('requestId 不能为空'); } - if (!body.targetChannel || !String(body.targetChannel).trim()) { - throw new Error('targetChannel 不能为空'); - } - // 构造 ext_id const extId = `api:${String(appKey || 'unknown')}:${String(body.requestId).trim()}`; @@ -40,13 +36,16 @@ class WarehouseInboxService extends MainService { const result = await ctx.service.inbox.receiver.receive({ ext_id: extId, warehouse_id: warehouseId, - store_id: body.storeId || null, direction: 'inbound', parent_id: body.parentId || null, source_type: body.sourceType || 'api', source_extra: String(appKey || ''), target_type: body.targetType || 'im', - target_channel: body.targetChannel, + group_name: body.groupName || null, + user_name: body.userName || null, + group_id: body.groupId || null, + user_id: body.userId || null, + content: body.content || null, ext_data: body.extData || null, flags: body.flags || {}, }); diff --git a/database/migrations/20260803120000-create-inbox-message.js b/database/migrations/20260803120000-create-inbox-message.js index d31b668..1e6a8d3 100644 --- a/database/migrations/20260803120000-create-inbox-message.js +++ b/database/migrations/20260803120000-create-inbox-message.js @@ -65,18 +65,33 @@ module.exports = { }, target_channel: { type: Sequelize.STRING(50), - allowNull: false, - comment: '目标渠道:wecom / dingtalk / feishu / warehouse_api / webhook', + allowNull: true, + comment: '目标渠道(仅供参考,出站路由由外部系统负责)', }, - target_url: { - type: Sequelize.STRING(500), - allowNull: false, - comment: '推送目标URL(IM Bot webhook 地址 / API 回调地址)', - }, - ref_code: { + group_name: { type: Sequelize.STRING(100), allowNull: true, - comment: '外部引用编码,推送/回执时原样携带', + comment: '群名称(外部传入)', + }, + user_name: { + type: Sequelize.STRING(100), + allowNull: true, + comment: '用户名称(外部传入)', + }, + group_id: { + type: Sequelize.STRING(100), + allowNull: true, + comment: '外部群ID', + }, + user_id: { + type: Sequelize.STRING(100), + allowNull: true, + comment: '外部用户ID', + }, + content: { + type: Sequelize.TEXT, + allowNull: true, + comment: '消息正文/摘要,用于列表展示和关键词搜索', }, ext_data: { type: Sequelize.JSON, diff --git a/database/migrations/20260804120000-add-content-to-inbox-message.js b/database/migrations/20260804120000-add-content-to-inbox-message.js new file mode 100644 index 0000000..4cd1c9b --- /dev/null +++ b/database/migrations/20260804120000-add-content-to-inbox-message.js @@ -0,0 +1,33 @@ +'use strict'; + +const TABLE_NAME = 'wms_inbox_message'; +const COLUMN_NAME = 'content'; + +module.exports = { + /** + * 为站内信消息表添加消息正文字段。 + * @param {Object} queryInterface Sequelize QueryInterface 实例。 + * @param {Object} Sequelize Sequelize 类。 + * @return {Promise} 迁移执行结果。 + */ + up: async (queryInterface, Sequelize) => { + const columns = await queryInterface.describeTable(TABLE_NAME); + if (columns[COLUMN_NAME]) return; + + await queryInterface.addColumn(TABLE_NAME, COLUMN_NAME, { + type: Sequelize.TEXT, + allowNull: true, + comment: '消息正文/摘要,用于列表展示和关键词搜索', + after: 'target_channel', + }); + }, + + /** + * 回滚:移除消息正文字段。 + * @param {Object} queryInterface Sequelize QueryInterface 实例。 + * @return {Promise} 迁移回滚结果。 + */ + down: async queryInterface => { + await queryInterface.removeColumn(TABLE_NAME, COLUMN_NAME); + }, +}; diff --git a/database/migrations/20260804130000-create-inbox-block.js b/database/migrations/20260804130000-create-inbox-block.js new file mode 100644 index 0000000..2e22c45 --- /dev/null +++ b/database/migrations/20260804130000-create-inbox-block.js @@ -0,0 +1,57 @@ +'use strict'; + +const TABLE_NAME = 'wms_inbox_block'; + +module.exports = { + /** + * 创建站内信屏蔽表。 + * @param {Object} queryInterface Sequelize QueryInterface 实例。 + * @param {Object} Sequelize Sequelize 类。 + * @return {Promise} 迁移执行结果。 + */ + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME); + if (exists) return; + + await queryInterface.createTable(TABLE_NAME, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + group_name: { + type: Sequelize.STRING(100), + allowNull: true, + comment: '群名称', + }, + user_name: { + type: Sequelize.STRING(100), + allowNull: true, + comment: '用户名称', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'group_name', 'user_name' ], { + unique: true, + name: 'uk_group_user', + }); + }, + + /** + * 回滚:删除站内信屏蔽表。 + * @param {Object} queryInterface Sequelize QueryInterface 实例。 + * @return {Promise} 迁移回滚结果。 + */ + down: async queryInterface => { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260804140000-create-inbox-group.js b/database/migrations/20260804140000-create-inbox-group.js new file mode 100644 index 0000000..875af02 --- /dev/null +++ b/database/migrations/20260804140000-create-inbox-group.js @@ -0,0 +1,92 @@ +'use strict'; + +const TABLE_NAME = 'wms_inbox_group'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + if (tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME)) return; + + await queryInterface.createTable(TABLE_NAME, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + group_name: { + type: Sequelize.STRING(100), + allowNull: false, + comment: '群名称', + }, + group_id: { + type: Sequelize.STRING(100), + allowNull: true, + comment: '外部群ID', + }, + warehouse_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '所属仓库ID', + }, + store_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '关联货主ID', + }, + group_type: { + type: Sequelize.ENUM('store', 'warehouse', 'express'), + allowNull: true, + comment: '群类型: store=货主 warehouse=仓库 express=快递', + }, + sub_type: { + type: Sequelize.STRING(20), + allowNull: true, + comment: '群子类型', + }, + source_type: { + type: Sequelize.STRING(20), + allowNull: true, + comment: '来源类型:im / api / system', + }, + source_extra: { + type: Sequelize.STRING(100), + allowNull: true, + comment: '来源附加信息', + }, + is_blocked: { + type: Sequelize.TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '是否屏蔽 0=否 1=是', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '软删除时间', + }, + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'group_name', 'warehouse_id' ], { + unique: true, + name: 'uk_group_warehouse', + }); + }, + + down: async queryInterface => { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260805120000-add-express-fields-to-inbox-group.js b/database/migrations/20260805120000-add-express-fields-to-inbox-group.js new file mode 100644 index 0000000..c2ae5ec --- /dev/null +++ b/database/migrations/20260805120000-add-express-fields-to-inbox-group.js @@ -0,0 +1,42 @@ +'use strict'; + +/** + * 为 wms_inbox_group 添加快递相关字段: + * - express_interfaces:快递接口ID列表(逗号分隔) + * - system_express_code:系统快递编码 + */ +module.exports = { + up: async (queryInterface, Sequelize) => { + const { STRING } = Sequelize; + + // 检查列是否已存在 + const tableInfo = await queryInterface.describeTable('wms_inbox_group'); + + if (!tableInfo.express_interfaces) { + await queryInterface.addColumn('wms_inbox_group', 'express_interfaces', { + type: STRING(500), + allowNull: true, + comment: '快递接口ID列表,逗号分隔(仅群类型为 express 时生效)', + }); + } + + if (!tableInfo.system_express_code) { + await queryInterface.addColumn('wms_inbox_group', 'system_express_code', { + type: STRING(50), + allowNull: true, + comment: '系统快递编码(仅群类型为 express 时必填)', + }); + } + }, + + down: async (queryInterface) => { + const tableInfo = await queryInterface.describeTable('wms_inbox_group'); + + if (tableInfo.express_interfaces) { + await queryInterface.removeColumn('wms_inbox_group', 'express_interfaces'); + } + if (tableInfo.system_express_code) { + await queryInterface.removeColumn('wms_inbox_group', 'system_express_code'); + } + }, +}; diff --git a/database/migrations/20260805140000-add-inbox-indexes.js b/database/migrations/20260805140000-add-inbox-indexes.js new file mode 100644 index 0000000..558a0dc --- /dev/null +++ b/database/migrations/20260805140000-add-inbox-indexes.js @@ -0,0 +1,73 @@ +'use strict'; + +/** + * 为站内信消息表和群表补充查询索引。 + * + * wms_inbox_message: + * - idx_warehouse_group_created: (warehouse_id, group_id, created_at) + * 用于按群拉取消息列表(最常用查询)。 + * + * wms_inbox_group: + * - idx_group_id: (group_id) + * 用于 receiver/processor 中按 group_id 查找群。 + * - idx_warehouse_group_id: (warehouse_id, group_id) + * 用于按仓库+群ID定位群。 + */ +module.exports = { + // eslint-disable-next-line no-unused-vars + up: async (queryInterface, Sequelize) => { + // ── wms_inbox_message 索引 ── + const msgTableInfo = await queryInterface.describeTable('wms_inbox_message'); + + // 检查已有索引(通过尝试添加,重复则忽略) + try { + await queryInterface.addIndex('wms_inbox_message', { + fields: ['warehouse_id', 'group_id', 'created_at'], + name: 'idx_warehouse_group_created', + }); + console.log('[idx] wms_inbox_message.idx_warehouse_group_created 已创建'); + } catch (e) { + if (e.message && e.message.includes('Duplicate')) { + console.log('[idx] wms_inbox_message.idx_warehouse_group_created 已存在,跳过'); + } else { + throw e; + } + } + + // ── wms_inbox_group 索引 ── + try { + await queryInterface.addIndex('wms_inbox_group', { + fields: ['group_id'], + name: 'idx_group_id', + }); + console.log('[idx] wms_inbox_group.idx_group_id 已创建'); + } catch (e) { + if (e.message && e.message.includes('Duplicate')) { + console.log('[idx] wms_inbox_group.idx_group_id 已存在,跳过'); + } else { + throw e; + } + } + + try { + await queryInterface.addIndex('wms_inbox_group', { + fields: ['warehouse_id', 'group_id'], + name: 'idx_warehouse_group_id', + }); + console.log('[idx] wms_inbox_group.idx_warehouse_group_id 已创建'); + } catch (e) { + if (e.message && e.message.includes('Duplicate')) { + console.log('[idx] wms_inbox_group.idx_warehouse_group_id 已存在,跳过'); + } else { + throw e; + } + } + }, + + // eslint-disable-next-line no-unused-vars + down: async (queryInterface, Sequelize) => { + await queryInterface.removeIndex('wms_inbox_message', 'idx_warehouse_group_created'); + await queryInterface.removeIndex('wms_inbox_group', 'idx_group_id'); + await queryInterface.removeIndex('wms_inbox_group', 'idx_warehouse_group_id'); + }, +}; diff --git a/database/migrations/20260805150000-add-group-api-permissions.js b/database/migrations/20260805150000-add-group-api-permissions.js new file mode 100644 index 0000000..95cc4e6 --- /dev/null +++ b/database/migrations/20260805150000-add-group-api-permissions.js @@ -0,0 +1,53 @@ +'use strict'; + +/** + * 为 inbox.group.* 方法创建 API 权限记录。 + * + * 固定 ID(当前 max_id=494): + * 495 — inbox.group.list + * 496 — inbox.group.disable + * 497 — inbox.group.update + * 498 — inbox.group.messages + */ +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + const methods = [ + [495, 'inbox.group.list'], + [496, 'inbox.group.disable'], + [497, 'inbox.group.update'], + [498, 'inbox.group.messages'], + ]; + + for (const [id, method] of methods) { + await queryInterface.sequelize.query(` + INSERT INTO wms_permission (id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at) + VALUES (${id}, '${method}', NULL, '${method}', NULL, 'API:${method}', NULL, 0, 0, NULL, 'api', 0, 1, NOW(), NOW()) + ON DUPLICATE KEY UPDATE path='${method}', meta_title='API:${method}', type='api' + `); + } + + // 授权给客服组-主管及以上角色 + const newIdSuffix = ', 495, 496, 497, 498'; + await queryInterface.sequelize.query(` + UPDATE wms_role + SET permissions = CONCAT(LEFT(permissions, LENGTH(permissions) - 1), '${newIdSuffix}]') + WHERE id IN (8, 26, 28, 29) + AND permissions != '*' + AND permissions IS NOT NULL + AND LENGTH(permissions) > 2 + `); + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + await queryInterface.sequelize.query( + 'DELETE FROM wms_permission WHERE id IN (495, 496, 497, 498)' + ); + await queryInterface.sequelize.query(` + UPDATE wms_role + SET permissions = REPLACE(permissions, ', 495, 496, 497, 498', '') + WHERE id IN (8, 26, 28, 29) + `); + }, +}; diff --git a/database/migrations/20260806120000-add-ai-thoughts-to-inbox-message.js b/database/migrations/20260806120000-add-ai-thoughts-to-inbox-message.js new file mode 100644 index 0000000..fe6095d --- /dev/null +++ b/database/migrations/20260806120000-add-ai-thoughts-to-inbox-message.js @@ -0,0 +1,27 @@ +'use strict'; + +/** + * 为 wms_inbox_message 新增 ai_thoughts 字段。 + * 存储 AI 多轮推理的思考过程数组。 + */ +module.exports = { + // eslint-disable-next-line no-unused-vars + up: async (queryInterface, Sequelize) => { + const tableInfo = await queryInterface.describeTable('wms_inbox_message'); + if (!tableInfo.ai_thoughts) { + await queryInterface.addColumn('wms_inbox_message', 'ai_thoughts', { + type: Sequelize.JSON, + allowNull: true, + comment: 'AI 多轮推理思考过程 [{round,action,function,params,reason,functionResult}]', + }); + } + }, + + // eslint-disable-next-line no-unused-vars + down: async (queryInterface) => { + const tableInfo = await queryInterface.describeTable('wms_inbox_message'); + if (tableInfo.ai_thoughts) { + await queryInterface.removeColumn('wms_inbox_message', 'ai_thoughts'); + } + }, +}; diff --git a/database/migrations/20260806150000-add-ai-enabled-to-inbox-group.js b/database/migrations/20260806150000-add-ai-enabled-to-inbox-group.js new file mode 100644 index 0000000..c7efcc3 --- /dev/null +++ b/database/migrations/20260806150000-add-ai-enabled-to-inbox-group.js @@ -0,0 +1,21 @@ +'use strict'; + +const TABLE_NAME = 'wms_inbox_group'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const columns = await queryInterface.describeTable(TABLE_NAME); + if (columns.ai_enabled) return; + + await queryInterface.addColumn(TABLE_NAME, 'ai_enabled', { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 1, + comment: '是否启用AI自动回复: 0=关闭 1=开启', + }); + }, + + down: async queryInterface => { + await queryInterface.removeColumn(TABLE_NAME, 'ai_enabled'); + }, +}; diff --git a/database/migrations/20260806160000-drop-target-channel-from-inbox-message.js b/database/migrations/20260806160000-drop-target-channel-from-inbox-message.js new file mode 100644 index 0000000..aea30e1 --- /dev/null +++ b/database/migrations/20260806160000-drop-target-channel-from-inbox-message.js @@ -0,0 +1,20 @@ +'use strict'; + +const TABLE_NAME = 'wms_inbox_message'; + +module.exports = { + up: async queryInterface => { + const columns = await queryInterface.describeTable(TABLE_NAME); + if (!columns.target_channel) return; + + await queryInterface.removeColumn(TABLE_NAME, 'target_channel'); + }, + + down: async (queryInterface, Sequelize) => { + await queryInterface.addColumn(TABLE_NAME, 'target_channel', { + type: Sequelize.STRING(50), + allowNull: true, + comment: '目标渠道:wecom / dingtalk / feishu / warehouse_api / webhook', + }); + }, +}; diff --git a/methods/changes/system.json b/methods/changes/system.json index bc780e4..11f208f 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,21 @@ [ + { + "version": "2026.08.06-inbox-bindCode", + "date": "2026-08-06", + "type": "added", + "summary": "新增货主绑群码生成接口。校验 StoreWarehouse 合约有效性后生成12位随机码(大写字母+数字),缓存 key 为 chat:bind:{warehouseId}:{code},TTL 300秒。实现位于 systems/store.js → bindCode(),由 systemMethods/inbox.js → bindCode() 委托调用。", + "methods": [ + "inbox.bindCode" + ], + "notes": [ + "调用链:/system → systemMethods/inbox.bindCode → systems/store.bindCode。", + "前置校验:StoreWarehouse 合约 auth_status=2 AND warehouse_use_status=1,不满足则返回500。", + "缓存策略:app.setCacheAsync('chat:bind:{warehouseId}:{code}', { store_id, initiator_subject_id, warehouse_id, group_type, sub_type }, 300)。", + "绑定时消费:processor.tryBindGroup 匹配 '授权:CODE' 模式,读取缓存执行绑定,成功即清缓存。", + "warehouseId:从 ctx.user.store_id 自动注入,前端无需传递。" + ], + "module": "inbox" + }, { "version": "2026.08.05-inbox-group", "date": "2026-08-05", diff --git a/methods/system.json b/methods/system.json index 00db843..54c497f 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1,7 +1,7 @@ { "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", - "version": "0.3.18", + "version": "0.3.19", "updatedAt": "2026-08-05", "headers": [ { @@ -31879,8 +31879,8 @@ "module": "inbox", "list": [ { - "method": "inbox.list", - "description": "站内信消息列表,按仓库/方向/状态/渠道筛选,支持关键词搜索(ext_id / ref_code),分页返回(默认20条/页,最大200条)", + "method": "inbox.message.list", + "description": "站内信消息列表,支持货主/群/用户名/正文/来源等多条件筛选,时间字段使用统一格式化输出,分页返回(默认20条/页,最大200条)", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -31892,6 +31892,48 @@ } ], "params": [ + { + "name": "storeId", + "type": "string", + "required": false, + "source": "body", + "description": "货主ID筛选,支持逗号分隔多选,如 \"1000000,1000001\"" + }, + { + "name": "groupId", + "type": "string", + "required": false, + "source": "body", + "description": "群ID筛选,支持逗号分隔多选" + }, + { + "name": "groupName", + "type": "string", + "required": false, + "source": "body", + "description": "群名称模糊搜索" + }, + { + "name": "userName", + "type": "string", + "required": false, + "source": "body", + "description": "用户名模糊搜索" + }, + { + "name": "content", + "type": "string", + "required": false, + "source": "body", + "description": "正文模糊搜索" + }, + { + "name": "sourceType", + "type": "string", + "required": false, + "source": "body", + "description": "来源类型筛选:im / api / system" + }, { "name": "direction", "type": "string", @@ -31906,20 +31948,6 @@ "source": "body", "description": "推送状态筛选:0=待推送 1=推送中 2=已送达 3=失败" }, - { - "name": "targetChannel", - "type": "string", - "required": false, - "source": "body", - "description": "目标渠道筛选:wecom / dingtalk / feishu / warehouse_api / webhook" - }, - { - "name": "keyword", - "type": "string", - "required": false, - "source": "body", - "description": "关键词搜索,模糊匹配 ext_id 和 ref_code" - }, { "name": "page", "type": "number", @@ -31942,7 +31970,7 @@ "name": "list", "type": "array", "required": true, - "description": "消息列表(不含 ext_data 和 push_response 大字段)", + "description": "消息列表(不含 ext_data、push_response、target_channel 字段,时间已格式化)", "children": [ { "name": "id", @@ -31962,6 +31990,18 @@ "required": true, "description": "所属仓库ID" }, + { + "name": "store_id", + "type": "number", + "required": false, + "description": "关联货主ID" + }, + { + "name": "store_name", + "type": "string", + "required": false, + "description": "货主名称(批量回填)" + }, { "name": "direction", "type": "string", @@ -31981,10 +32021,34 @@ "description": "目标类型:im / api / webhook" }, { - "name": "target_channel", + "name": "group_id", "type": "string", - "required": true, - "description": "目标渠道" + "required": false, + "description": "外部群ID" + }, + { + "name": "group_name", + "type": "string", + "required": false, + "description": "群名称" + }, + { + "name": "user_id", + "type": "string", + "required": false, + "description": "外部用户ID" + }, + { + "name": "user_name", + "type": "string", + "required": false, + "description": "用户名称" + }, + { + "name": "content", + "type": "string", + "required": false, + "description": "消息正文/摘要" }, { "name": "push_status", @@ -32002,7 +32066,19 @@ "name": "created_at", "type": "string", "required": true, - "description": "创建时间" + "description": "创建时间(YYYY-MM-DD HH:mm:ss 格式化)" + }, + { + "name": "updated_at", + "type": "string", + "required": true, + "description": "更新时间(YYYY-MM-DD HH:mm:ss 格式化)" + }, + { + "name": "pushed_at", + "type": "string", + "required": false, + "description": "推送完成时间(YYYY-MM-DD HH:mm:ss 格式化)" } ] }, @@ -32063,7 +32139,7 @@ ] }, { - "method": "inbox.detail", + "method": "inbox.message.detail", "description": "站内信消息详情,含完整 push_response 推送响应信息", "isNeedAuth": false, "isNeedLogin": true, @@ -32186,7 +32262,7 @@ ] }, { - "method": "inbox.thread", + "method": "inbox.message.thread", "description": "站内信对话链查询,返回原消息 + 所有回信(按 parent_id 递归),按时间升序排列", "isNeedAuth": false, "isNeedLogin": true, @@ -32231,7 +32307,7 @@ ] }, { - "method": "inbox.reply", + "method": "inbox.message.reply", "description": "系统回信:写入 outbound 记录 + 异步推送到目标渠道。自动继承原消息的 ext_data、ref_code 等字段", "isNeedAuth": false, "isNeedLogin": true, @@ -32316,7 +32392,7 @@ ] }, { - "method": "inbox.retry", + "method": "inbox.message.retry", "description": "手动重推失败(push_status=3)的站内信消息,重置为待推送状态并触发异步推送", "isNeedAuth": false, "isNeedLogin": true, @@ -32379,7 +32455,7 @@ ] }, { - "method": "inbox.stats", + "method": "inbox.message.stats", "description": "站内信推送统计:按方向汇总、按推送状态汇总、最近24小时新增数量", "isNeedAuth": false, "isNeedLogin": true, @@ -32461,7 +32537,7 @@ }, { "method": "inbox.bindCode", - "description": "生成货主绑群码。传入货主ID和子类型,生成5分钟有效12位随机码存入缓存", + "description": "生成货主绑群码。校验 StoreWarehouse 合约有效后,生成12位随机码(大写字母+数字),缓存 key 为 chat:bind:{warehouseId}:{code},TTL 300秒。warehouseId 从 token 自动注入", "isNeedAuth": true, "isNeedLogin": true, "headers": [ @@ -32478,14 +32554,14 @@ "type": "number", "required": true, "source": "body", - "description": "货主ID" + "description": "货主ID(需在目标仓库有有效合约 auth_status=2 warehouse_use_status=1)" }, { "name": "subType", "type": "string", "required": false, "source": "body", - "description": "群子类型编码:after_sales(售后) / finance(财务) / receiving(收货)" + "description": "群子类型:after_sales(售后) / finance(财务) / receiving(收货)" } ], "response": [ @@ -32493,13 +32569,13 @@ "name": "code", "type": "string", "required": true, - "description": "12位绑群随机码,5分钟有效" + "description": "12位绑群随机码(大写字母+数字),5分钟有效" } ], "errors": [ { "code": "400", - "message": "storeId 无效 / 缺少仓库信息" + "message": "storeId 无效 / 缺少仓库信息 / 子类型无效" }, { "code": "500", @@ -32561,7 +32637,7 @@ "name": "list", "type": "array", "required": true, - "description": "群记录列表,含id/group_name/group_id/store_id/group_type/sub_type/is_blocked/express_interfaces(数组)/system_express_code/created_at" + "description": "群记录列表,含id/group_name/group_id/store_id/group_type/sub_type/is_blocked/ai_enabled/express_interfaces(数组)/system_express_code/created_at" } ], "errors": [ @@ -32621,7 +32697,7 @@ }, { "method": "inbox.group.update", - "description": "修改群信息:群类型/子类型/货主/快递接口/系统快递编码。切换为express类型时systemExpressCode必填,expressInterfaces仅express类型生效", + "description": "修改群信息:群类型/子类型/货主/快递接口/系统快递编码/AI开关。aiEnabled支持灰度控制,切换为express类型时systemExpressCode必填", "isNeedAuth": true, "isNeedLogin": true, "headers": [ @@ -32674,6 +32750,13 @@ "required": false, "source": "body", "description": "系统快递编码,groupType=express时必填。需校验wms_express.code存在" + }, + { + "name": "aiEnabled", + "type": "number", + "required": false, + "source": "body", + "description": "是否启用AI自动回复: 0=关闭 1=开启,默认1(所有群类型均支持,用于灰度测试)" } ], "response": [ diff --git a/script/tmp-check-pending-migrations.cjs b/script/tmp-check-pending-migrations.cjs new file mode 100644 index 0000000..240e40f --- /dev/null +++ b/script/tmp-check-pending-migrations.cjs @@ -0,0 +1,87 @@ +'use strict'; + +const fs = require('node:fs'); +const path = require('node:path'); +const Sequelize = require('sequelize'); + +const ROOT = path.resolve(__dirname, '..'); +const MIGRATIONS_DIR = path.join(ROOT, 'database', 'migrations'); + +async function main() { + // 1. 收集本地所有迁移文件 + const allFiles = fs.readdirSync(MIGRATIONS_DIR).filter(f => f.endsWith('.js')).sort(); + console.log(`[本地] 迁移文件总数: ${allFiles.length}`); + + // 2. 连接生产数据库 + const dbConfig = { + host: '112.124.21.102', + port: 3306, + user: 'wms', + password: 'P6j3YTHTpirepYWz', + database: 'wms', + }; + + const sequelize = new Sequelize(dbConfig.database, dbConfig.user, dbConfig.password, { + host: dbConfig.host, + port: dbConfig.port, + dialect: 'mysql', + logging: false, + }); + + try { + await sequelize.authenticate(); + console.log('[DB] 生产数据库连接成功'); + } catch (e) { + console.error('[DB] 生产数据库连接失败:', e.message); + process.exit(2); + } + + // 3. 检查 SequelizeMeta 表是否存在 + let appliedNames = []; + try { + const [rows] = await sequelize.query('SELECT name FROM SequelizeMeta ORDER BY name'); + appliedNames = rows.map(r => (typeof r === 'string' ? r : r.name)).filter(Boolean); + } catch (e) { + console.error('[DB] 读取 SequelizeMeta 失败:', e.message); + await sequelize.close(); + process.exit(2); + } + + console.log(`[DB] SequelizeMeta 已记录迁移数: ${appliedNames.length}`); + + // 4. 找出未执行的迁移 + const appliedSet = new Set(appliedNames); + const pending = allFiles.filter(f => !appliedSet.has(f)); + const archived = allFiles.filter(f => f.startsWith('archive/')); + + console.log(`\n========== 结果汇总 ==========`); + console.log(`本地迁移文件总数: ${allFiles.length}`); + console.log(`已执行 (SequelizeMeta): ${appliedNames.length}`); + console.log(`未执行 (pending): ${pending.length}`); + console.log(`===============================\n`); + + if (pending.length === 0) { + console.log('✅ 所有迁移脚本均已执行,无 pending migration。'); + } else { + console.log(`❌ 发现 ${pending.length} 个未执行的迁移脚本:\n`); + pending.forEach((f, i) => { + console.log(` ${String(i + 1).padStart(3, ' ')}. ${f}`); + }); + + // 额外检查:有没有本地没有但 DB 已记录的(可能被删除了) + const localSet = new Set(allFiles); + const orphanInDb = appliedNames.filter(n => !localSet.has(n)); + if (orphanInDb.length > 0) { + console.log(`\n⚠️ DB 中记录了 ${orphanInDb.length} 个本地已不存在的迁移(可能已被删除):`); + orphanInDb.forEach(n => console.log(` - ${n}`)); + } + } + + await sequelize.close(); + console.log('\n[DONE] 检查完成'); +} + +main().catch(err => { + console.error('脚本执行异常:', err); + process.exit(1); +}); From 2cd53c7e0f1b745befdbff0062be72dd65b6d2a3 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Fri, 7 Aug 2026 13:15:15 +0800 Subject: [PATCH 179/550] =?UTF-8?q?fix(pick):=20=E4=BF=AE=E5=A4=8D?= =?UTF-8?q?=E6=8B=A3=E8=B4=A7=E5=AE=8C=E6=88=90=E2=86=92=E5=8F=96=E6=B6=88?= =?UTF-8?q?=E2=86=92=E9=87=8D=E5=85=A5=E7=9A=84=E6=B5=81=E7=A8=8B=E6=BC=8F?= =?UTF-8?q?=E6=B4=9E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. pick.query 增加跨波次订单级去重:已拣货完成的订单不再创建新任务,直接返回原有任务 2. cancelWavePickTasksInternal 禁止取消 status 2(待复核)/3(已完成) 的任务,防止库存与订单状态不一致 --- app/service/systemMethods/order/wave.js | 7 +++-- app/service/systemMethods/pick.js | 39 +++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 2 deletions(-) diff --git a/app/service/systemMethods/order/wave.js b/app/service/systemMethods/order/wave.js index fa27eb0..2387d81 100644 --- a/app/service/systemMethods/order/wave.js +++ b/app/service/systemMethods/order/wave.js @@ -12247,8 +12247,11 @@ class WaveService extends OrderBaseService { } const taskStatus = Number(taskRow.status || 0); - if (![ 0, 1, 2, 3 ].includes(taskStatus)) { - const error = new Error('当前任务状态不允许取消'); + // status 2(待复核)、3(已完成)不允许取消,此时库存已扣减且订单已标记拣货完成 + if (![ 0, 1 ].includes(taskStatus)) { + const statusMessages = { 2: '待复核', 3: '已完成', 9: '已取消' }; + const statusText = statusMessages[taskStatus] || `状态${taskStatus}`; + const error = new Error(`当前任务已${statusText},不允许取消`); error.statusCode = 400; error.data = { task_id: taskId, diff --git a/app/service/systemMethods/pick.js b/app/service/systemMethods/pick.js index 762cc4f..8f402ef 100644 --- a/app/service/systemMethods/pick.js +++ b/app/service/systemMethods/pick.js @@ -973,6 +973,45 @@ class PickService extends MainService { } } + // 跨波次订单级去重:检查这批订单是否已有已完成(status 2/3)的拣货任务 + if (selectedOrderIds.length > 0) { + const crossWaveDedupRows = await ctx.model.query( + ` + SELECT t.id AS task_id, t.task_no, t.status, t.pick_user_id, t.pick_user_name + FROM wms_wave_pick_task t + INNER JOIN wms_wave_pick_task_order pto + ON pto.task_id = t.id + AND pto.warehouse_id = t.warehouse_id + WHERE t.warehouse_id = :warehouseId + AND t.status IN (2, 3) + AND pto.order_id IN (:orderIds) + AND pto.pick_status = 1 + ORDER BY t.id DESC + LIMIT 1 + `, + { + replacements: { + warehouseId: normalizedWarehouseId, + orderIds: selectedOrderIds, + }, + type: ctx.model.QueryTypes.SELECT, + } + ); + const crossWaveDedupTask = Array.isArray(crossWaveDedupRows) && crossWaveDedupRows.length > 0 + ? crossWaveDedupRows[0] + : null; + if (crossWaveDedupTask) { + return this.success('ok', { + data: { + task_id: Number(crossWaveDedupTask.task_id), + status: 'existing_completed', + tip: '该批订单已有完成拣货任务,无需重复创建', + }, + code: 200, + }); + } + } + try { const createdTask = await this.createWavePickTask({ warehouseId: normalizedWarehouseId, From 948f60068961ff8f1228ec9260f40aab7f172a91 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sat, 8 Aug 2026 00:17:38 +0800 Subject: [PATCH 180/550] =?UTF-8?q?feat(inbox):=20=E5=9B=9E=E8=B0=83?= =?UTF-8?q?=E6=8E=A8=E9=80=81=E3=80=81=E5=87=BA=E7=AB=99=E6=96=87=E6=A1=A3?= =?UTF-8?q?=E3=80=81=E6=90=9C=E7=B4=A2=E5=A2=9E=E5=BC=BA=E3=80=81=E6=97=A5?= =?UTF-8?q?=E5=BF=97=E4=B8=8E=E6=8E=A8=E9=80=81=E7=8A=B6=E6=80=81=E5=AE=8C?= =?UTF-8?q?=E5=96=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 出站回调: - 新增 warehouse_notify.json 文档(notify.ping/notify.reply),与 warehouse.json 互跳 - 回调体统一 { method, code, data },method 放 query,body 为业务数据 - MD5 签名: sign=MD5(appSecret+timestamp+bodyJson) - 回调响应: {code:200} 成功,非200/非code:200 视为失败 - docs 页面支持模拟推送调试 搜索增强(searchStock/searchWarehouseStock): - 直接查 stock_warehouse,不再依赖 stock_store - 新增字段: gross_weight/box_spec/packing_requirements/prohibited_type - 管理标识: is_sn_mgmt/is_shelf_life_mgmt/is_batch_mgmt - 条码关联: wms_stock_barcodes - 图片: wms_file_reference(business_type=stock)+wms_file,返回数组 - id 修正为 stock_warehouse.id 推送状态完善: - handleApiMessage 增加 push_status 更新(2成功/3失败) - 未配回调地址 → push_status=3 + error 原因 - 回调异常 catch 也更新 push_status=3 + 写日志 - 出站日志写入 wms_warehouse_log 表(WN-前缀) 消息列表: - keyword 兼容 content/keyword,支持数组 - keyword 搜索 content/group_name/user_name 三列 - 支持 where+operator 结构化查询(parseWhereConditions) - storeId=-1 查询无货主消息; storeId=0→IS NULL - 日期范围: startDate/endDate 其他: - silent 动作: AI 识别无需回复时跳过回执 - ai_enabled 灰度开关(群级) - bindCode 文档修正 - store_name 改用 StoreWarehouse.store_remask --- app/controller/docs.js | 128 ++- app/controller/warehouse.js | 59 +- app/lib/qimen_client.js | 2 +- app/model/api_app.js | 4 +- app/model/inbox_block.js | 30 +- app/model/inbox_group.js | 2 +- app/model/order_stockout.js | 25 + app/model/warehouse_log.js | 111 +++ app/schedule/consume_warehouse_logs.js | 56 ++ app/service/inbox/functions.js | 336 +++++-- app/service/inbox/message.js | 123 ++- app/service/inbox/processor.js | 374 ++++++-- app/service/inbox/receiver.js | 1 + app/service/qimenMethods/stockout.js | 4 +- app/service/systemMethods/storage/stockout.js | 272 +++++- app/service/systems/apiApp.js | 10 +- app/service/systems/express_platform.js | 20 +- app/service/systems/upload.js | 6 +- app/service/warehouse.js | 24 +- app/service/warehouseMethods/inbox.js | 2 +- config/config.default.js | 16 +- ...20260806200000-create-wms-warehouse-log.js | 108 +++ ...07100000-change-ai-enabled-default-to-0.js | 27 + ...0260807110000-switch-inbox-block-to-ids.js | 83 ++ ...-add-express-code-to-wms-order-stockout.js | 44 + ...0807130000-add-stockout-api-permissions.js | 84 ++ ...ress-name-waybill-to-wms-order-stockout.js | 56 ++ methods/changes/qimen.json | 16 + methods/changes/system.json | 67 ++ methods/changes/warehouse.json | 105 ++- methods/inbox-callback.json | 261 ++++++ methods/system.json | 837 +++++++++++------- methods/warehouse.json | 101 ++- methods/warehouse_notify.json | 181 ++++ 34 files changed, 2951 insertions(+), 624 deletions(-) create mode 100644 app/model/warehouse_log.js create mode 100644 app/schedule/consume_warehouse_logs.js create mode 100644 database/migrations/20260806200000-create-wms-warehouse-log.js create mode 100644 database/migrations/20260807100000-change-ai-enabled-default-to-0.js create mode 100644 database/migrations/20260807110000-switch-inbox-block-to-ids.js create mode 100644 database/migrations/20260807120000-add-express-code-to-wms-order-stockout.js create mode 100644 database/migrations/20260807130000-add-stockout-api-permissions.js create mode 100644 database/migrations/20260807140000-add-express-name-waybill-to-wms-order-stockout.js create mode 100644 methods/inbox-callback.json create mode 100644 methods/warehouse_notify.json diff --git a/app/controller/docs.js b/app/controller/docs.js index 319c4b9..9fcc600 100644 --- a/app/controller/docs.js +++ b/app/controller/docs.js @@ -465,6 +465,20 @@ function resolveDocEntryPath(docData) { return '/system'; } +/** + * 渲染 seeAlso 交叉引用链接。 + * @param {Array<{name: string, path: string, description: string}>|undefined} seeAlso 交叉引用列表。 + * @return {string} HTML 片段。 + */ +function renderSeeAlsoLinks(seeAlso) { + if (!Array.isArray(seeAlso) || seeAlso.length === 0) return ''; + const links = seeAlso.map(item => { + const href = `/api/docs/${(item.path || '').replace(/^\/?methods\//, '').replace(/\.json$/, '')}`; + return `${escapeHtml(item.name)}`; + }).join(''); + return `
    关联文档:${links}
    `; +} + /** * 渲染键值表格。 * @param {Array} items 数据项列表。 @@ -535,7 +549,7 @@ function renderMethodCard(item, entryPath, moduleName) { const description = item.description || ''; const isQimen = moduleName === 'qimen'; const isOpenapi = moduleName === 'openapi'; - const isWarehouse = moduleName === 'warehouse'; + const isWarehouse = moduleName === 'warehouse' || moduleName === 'warehouse_notify'; const isExternalApi = isOpenapi || isWarehouse; const queryHint = isQimen ? 'app_key=xxx&method=...&v=2.0&format=json&sign_method=md5&sign=xxx×tamp=1700000000' @@ -610,7 +624,24 @@ function renderMethodCard(item, entryPath, moduleName) { -
    + ${moduleName === 'warehouse_notify' ? `
    + 模拟推送 +
    + + + + + + + + +
    + + 模拟 WMS 向 notify_url 推送通知,sign 在浏览器端 MD5 计算 +
    +
    点击发送后显示响应
    +
    +
    ` : `
    在线调试
    @@ -631,7 +662,7 @@ function renderMethodCard(item, entryPath, moduleName) {
    点击发送后显示响应
    -
    +
    `} `; } @@ -648,14 +679,14 @@ function renderHtmlPage({ entryPath, }) { const isOpenapi = docData.module === 'openapi'; - const isWarehouse = docData.module === 'warehouse'; + const isWarehouse = docData.module === 'warehouse' || docData.module === 'warehouse_notify'; const isExternalApi = isOpenapi || isWarehouse; const methodsCount = groups.reduce((sum, group) => sum + toArray(group.list).length, 0); const globalHeaders = toArray(docData.headers); const globalHeadersControls = renderGlobalHeadersControls(globalHeaders); const rawUrl = `/api/docs/${encodeURIComponent(docName)}/raw`; const changesUrl = `/api/docs/${encodeURIComponent(docName)}/changes`; - const navHtml = isExternalApi ? '' : docs.filter(name => name !== 'openapi' && name !== 'warehouse').map(name => { + const navHtml = isExternalApi ? '' : docs.filter(name => name !== 'openapi' && name !== 'warehouse' && name !== 'warehouse_notify').map(name => { const activeClass = name === docName ? 'active' : ''; return `${escapeHtml(name)}`; }).join(''); @@ -1074,6 +1105,7 @@ function renderHtmlPage({ 更新: ${escapeHtml(docData.updatedAt || 'N/A')} 方法数: ${methodsCount} 统一入口: ${escapeHtml(entryPath)} + ${renderSeeAlsoLinks(docData.seeAlso)}
    ${navHtml} @@ -1101,7 +1133,42 @@ function renderHtmlPage({
    点击上方按钮后,可直接预览当前文档的变更记录或原文 JSON。
    `} - ${isExternalApi ? `
    + ${isExternalApi ? (docData.module === 'warehouse_notify' ? `
    +

    请求方式

    +
    POST {notify_url}?app_key={app_key}&method={方法名}&timestamp={时间戳}&sign={签名}
    +Content-Type: application/json
    +
    +{
    +  "code": 200,
    +  "data": { ... }
    +}
    + +

    签名算法(MD5)

    +
    sign = MD5(self_app_secret + timestamp + bodyJson).toLowerCase()
    +
    +其中:
    +  self_app_secret = 平台分配的密钥
    +  timestamp = Unix 秒级时间戳
    +  bodyJson = JSON.stringify(请求体)
    +
    +示例(假设 self_app_secret=abc123,请求体={"code":200,"data":{...}}):
    +  bodyJson = {"code":200,"data":{...}}
    +  timestamp = 1700000000
    +  signText = abc1231700000000{"code":200,"data":{...}}
    +  sign = md5(signText).toLowerCase() = ...
    + +

    注意事项(外部系统接收方)

    +
      +
    • 通知由 WMS 主动推送到您配置的 notify_url,外部系统接收并返回 HTTP 200即可
    • +
    • 根据 query 中的 method 字段路由到不同处理逻辑(notify.ping / notify.reply)
    • +
    • 根据 data.type 区分消息类别(ai / bind / balance / error)
    • +
    • 验签时从 query 取 sign,本地计算 MD5(self_app_secret + timestamp + bodyJson) 比对
    • +
    • 时间戳 timestamp 为 Unix 秒级时间戳,校验 ±10 分钟时效
    • +
    • 签名结果为 32 位小写十六进制字符串
    • +
    • 接收成功返回 {"code":200},非 200 或 HTTP 状态码非 200 视为推送失败
    • +
    • WMS 推送超时 10 秒,失败不重试,仅记录日志
    • +
    +
    ` : `

    请求方式

    POST ${isOpenapi ? '/openapi' : '/warehouse'}?method={方法名}&v=1.0×tamp={时间戳}&app_key={app_key}&sign={签名}
     Content-Type: application/json
    @@ -1146,7 +1213,7 @@ Content-Type: application/json
               → 回调测试工具
               (模拟接收回调通知,验证回调链路)
             

    ` : ''} -
    ` : ''} +
    `) : ''}
    @@ -1171,7 +1238,7 @@ Content-Type: application/json (function() { var DOC_NAME = ${JSON.stringify(docName)}; var IS_OPENAPI_DOC = DOC_NAME === 'openapi'; - var IS_EXTERNAL_API_DOC = DOC_NAME === 'openapi' || DOC_NAME === 'warehouse'; + var IS_EXTERNAL_API_DOC = DOC_NAME === 'openapi' || DOC_NAME === 'warehouse' || DOC_NAME === 'warehouse_notify'; var AUTH_KEY = 'wms_docs_global_auth'; var HEADER_STORE_KEY = 'wms_docs_global_headers_' + ${JSON.stringify(docName)}; var OPENAPI_APP_KEY_STORE_KEY = 'wms_docs_' + DOC_NAME + '_app_key'; @@ -1939,6 +2006,51 @@ Content-Type: application/json initDefaultQueries(); applySearch(''); + + // ── warehouse_notify 模拟推送(每个方法卡上的按钮)── + document.querySelectorAll('.notify-send-btn').forEach(function(btn) { + btn.addEventListener('click', function() { + var card = btn.closest('.method-card'); + var methodName = btn.getAttribute('data-method'); + var notifyUrlInput = card.querySelector('.notify-url-input'); + var appKeyInput = card.querySelector('.req-app-key'); + var appSecretInput = card.querySelector('.req-self-app-secret'); + var bodyTextarea = card.querySelector('.req-body'); + var resultEl = card.querySelector('.req-result'); + + var url = (notifyUrlInput && notifyUrlInput.value || '').trim(); + var appKey = (appKeyInput && appKeyInput.value || '').trim(); + var appSecret = (appSecretInput && appSecretInput.value || '').trim(); + var bodyStr = (bodyTextarea && bodyTextarea.value || '{}').trim(); + + if (!url) { resultEl.textContent = '请填写 notify_url'; resultEl.className = 'req-result error'; return; } + if (!appKey) { resultEl.textContent = '请填写 app_key'; resultEl.className = 'req-result error'; return; } + if (!appSecret) { resultEl.textContent = '请填写 self_app_secret'; resultEl.className = 'req-result error'; return; } + + var bodyJson; + try { bodyJson = JSON.stringify(JSON.parse(bodyStr)); } catch (e) { resultEl.textContent = 'Body JSON 格式错误'; resultEl.className = 'req-result error'; return; } + + var ts = Math.floor(Date.now() / 1000); + var sign = md5(appSecret + ts + bodyJson); + + resultEl.textContent = '发送中...'; + resultEl.className = 'req-result'; + + fetch(url + '?app_key=' + encodeURIComponent(appKey) + '&method=' + encodeURIComponent(methodName) + '×tamp=' + ts + '&sign=' + sign, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: bodyJson, + }).then(function(res) { + return res.text().then(function(txt) { return { status: res.status, body: txt }; }); + }).then(function(r) { + resultEl.textContent = 'HTTP ' + r.status + '\n' + r.body; + resultEl.className = r.status === 200 ? 'req-result success' : 'req-result error'; + }).catch(function(err) { + resultEl.textContent = '推送失败: ' + err.message; + resultEl.className = 'req-result error'; + }); + }); + }); })(); diff --git a/app/controller/warehouse.js b/app/controller/warehouse.js index 4e79e32..d34a440 100644 --- a/app/controller/warehouse.js +++ b/app/controller/warehouse.js @@ -1,8 +1,12 @@ 'use strict'; const { Controller } = require('egg'); +const crypto = require('crypto'); const { toSuccess, toFailure } = require('../lib/api_response'); +/** 日志内容长度上限 */ +const LOG_BODY_MAX = 65535; + class WarehouseController extends Controller { /** * 输出仓库 API 统一失败响应。 @@ -23,14 +27,33 @@ class WarehouseController extends Controller { } /** - * 仓库 API 统一入口,仅负责转发到 warehouse service 并输出标准响应。 + * 截断日志内容到上限长度。 + * @param {string} value 原始字符串。 + * @return {string} 截断后的字符串。 + */ + truncateLogBody(value) { + const str = typeof value === 'string' ? value : JSON.stringify(value); + if (str.length > LOG_BODY_MAX) { + return str.substring(0, LOG_BODY_MAX); + } + return str; + } + + /** + * 仓库 API 统一入口,记录请求日志并转发到 warehouse service。 * @return {Promise} 无返回值,结果写入 ctx.body。 */ async index() { - const { ctx } = this; + const { ctx, app } = this; + const startTime = Date.now(); + const logId = 'WL-' + Date.now() + '-' + crypto.randomBytes(3).toString('hex'); + + const query = ctx.query || {}; + let result; try { - const result = await ctx.service.warehouse.processRequest(); + result = await ctx.service.warehouse.processRequest(); + if (result.ok) { ctx.status = Number(result.httpStatus) || 200; ctx.body = toSuccess(result.data, result.message || 'ok'); @@ -49,6 +72,36 @@ class WarehouseController extends Controller { const message = String(error && error.message || '请求失败'); this.writeFailureResponse(500, `接口错误: ${message}`, 500); ctx.type = 'application/json'; + // 异常情况下 result 为 undefined,构造一个 fallback + result = { + ok: false, + httpStatus: 500, + message: error.message || '未知错误', + warehouseId: null, + appKey: String(query.app_key || '').trim() || null, + }; + } finally { + // 异步写日志,不阻塞响应 + try { + const logData = { + log_id: logId, + app_key: (result && result.appKey) || String(query.app_key || '').trim() || null, + method: String(query.method || '').trim() || null, + warehouse_id: (result && result.warehouseId) || null, + url: ctx.request.href || null, + http_status: ctx.status || (result && result.httpStatus) || null, + body: this.truncateLogBody(ctx.request.rawBody || JSON.stringify(ctx.request.body || {})), + result: this.truncateLogBody(typeof ctx.body === 'string' ? ctx.body : JSON.stringify(ctx.body || {})), + use_time: Date.now() - startTime, + created_at: new Date(), + }; + + app.fileWriter.writeRecord('warehouse-logs', logData).catch(writeErr => { + ctx.logger.error('[warehouse-log-sink] 写入文件失败: ' + writeErr.message); + }); + } catch (logErr) { + ctx.logger.error('[warehouse-log] 日志记录异常: ' + logErr.message); + } } } } diff --git a/app/lib/qimen_client.js b/app/lib/qimen_client.js index 09ff933..d50fa0c 100644 --- a/app/lib/qimen_client.js +++ b/app/lib/qimen_client.js @@ -153,7 +153,7 @@ class QimenClient { const baseUrl = 'http://qimen.api.taobao.com/router/qimen/service'; const requestPayload = this.normalizeRequestPayload(data); const xmlData = await helpers.toXml(requestPayload); - const queryData = method === 'taobao.qimen.deliveryorder.confirm' + const queryData = method === 'taobao.qimen.deliveryorder.confirm' || method === 'taobao.qimen.stockout.confirm' ? this.replaceDeliveryConfirmPayloadTags(xmlData) : this.replaceXmlTagsWithString(xmlData, 'item', 'orderLine'); const sign = await helpers.signTopRequest(baseQueryParams, queryData, this.app.config.qimen.security, 'md5'); diff --git a/app/model/api_app.js b/app/model/api_app.js index b81db1b..4d19535 100644 --- a/app/model/api_app.js +++ b/app/model/api_app.js @@ -108,10 +108,10 @@ module.exports = app => { allowNull: true, defaultValue: 'md5', validate: { - isIn: [[ 'md5', 'hmac', 'sha256' ]], + isIn: [[ 'md5' ]], len: [ 0, 50 ], }, - comment: '签名方法', + comment: '签名方法(当前仅支持 md5)', }, rate_limit: { type: INTEGER(11), diff --git a/app/model/inbox_block.js b/app/model/inbox_block.js index 4baa2dd..e2fefba 100644 --- a/app/model/inbox_block.js +++ b/app/model/inbox_block.js @@ -2,14 +2,14 @@ /** * 站内信屏蔽表 Model。 - * 记录被屏蔽的群/用户,后续来自该群+用户的消息不再触发 AI 回信。 - * group_name 和 user_name 均为 NULL 时表示全局屏蔽(预留)。 + * 按群ID+用户ID维度屏蔽,后续来自该群+用户的消息不再触发 AI 回信。 + * group_id 和 user_id 均为 NULL 时表示全局屏蔽(预留)。 * * @param {Object} app Egg.js Application 实例。 * @return {Object} Sequelize Model 定义。 */ module.exports = app => { - const { BIGINT, STRING, DATE } = app.Sequelize; + const { BIGINT, STRING, INTEGER, DATE } = app.Sequelize; const InboxBlock = app.model.define('inbox_block', { id: { @@ -19,15 +19,20 @@ module.exports = app => { allowNull: false, comment: '主键', }, - group_name: { - type: STRING(100), - allowNull: true, - comment: '群名称', + warehouse_id: { + type: INTEGER(10), + allowNull: false, + comment: '仓库ID', }, - user_name: { + group_id: { type: STRING(100), allowNull: true, - comment: '用户名称', + comment: '群ID', + }, + user_id: { + type: STRING(100), + allowNull: true, + comment: '用户ID', }, created_at: { type: DATE, @@ -39,6 +44,13 @@ module.exports = app => { tableName: 'wms_inbox_block', timestamps: false, comment: '站内信屏蔽表', + indexes: [ + { + name: 'uk_warehouse_group_user', + unique: true, + fields: [ 'warehouse_id', 'group_id', 'user_id' ], + }, + ], }); return InboxBlock; diff --git a/app/model/inbox_group.js b/app/model/inbox_group.js index 3b5dc47..6a02825 100644 --- a/app/model/inbox_group.js +++ b/app/model/inbox_group.js @@ -67,7 +67,7 @@ module.exports = app => { ai_enabled: { type: TINYINT(1), allowNull: false, - defaultValue: 1, + defaultValue: 0, comment: '是否启用AI自动回复: 0=关闭 1=开启', }, express_interfaces: { diff --git a/app/model/order_stockout.js b/app/model/order_stockout.js index 601f832..4b56eab 100644 --- a/app/model/order_stockout.js +++ b/app/model/order_stockout.js @@ -107,6 +107,31 @@ module.exports = app => { allowNull: true, comment: '备注', }, + express_code: { + type: STRING(50), + allowNull: true, + comment: '快递公司编码(如 SF、STO,用于出站回传 logisticsCode)', + }, + express_name: { + type: STRING(200), + allowNull: true, + comment: '快递公司名称(由 express_code 自动解析,如 顺丰、申通)', + }, + waybill_code: { + type: STRING(50), + allowNull: true, + comment: '运单号', + }, + waybill_codes: { + type: JSON_TYPE, + allowNull: true, + comment: '运单号列表(JSON 数组,支持多包裹场景)', + }, + express_codes: { + type: JSON_TYPE, + allowNull: true, + comment: '@deprecated 运单号列表,请使用 waybill_codes', + }, extend_props: { type: JSON_TYPE, allowNull: true, diff --git a/app/model/warehouse_log.js b/app/model/warehouse_log.js new file mode 100644 index 0000000..7eb67b4 --- /dev/null +++ b/app/model/warehouse_log.js @@ -0,0 +1,111 @@ +// app/model/warehouse_log.js + +'use strict'; + +module.exports = app => { + const { STRING, INTEGER, BIGINT, TEXT, DATE } = app.Sequelize; + + const WarehouseLog = app.model.define('warehouse_log', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + }, + log_id: { + type: STRING(32), + allowNull: false, + unique: true, + field: 'log_id', + comment: '日志唯一ID(WL-{timestamp}-{random})', + }, + app_key: { + type: STRING(64), + allowNull: true, + field: 'app_key', + comment: 'API 应用 AppKey', + }, + method: { + type: STRING(100), + allowNull: true, + comment: '请求方法名(如 inbox.push)', + }, + warehouse_id: { + type: INTEGER(10), + allowNull: true, + field: 'warehouse_id', + comment: '仓库 ID', + }, + url: { + type: TEXT, + allowNull: true, + comment: '请求 URL', + }, + http_status: { + type: INTEGER(5), + allowNull: true, + field: 'http_status', + comment: 'HTTP 状态码', + }, + body: { + type: TEXT('long'), + allowNull: true, + comment: '请求体(最大 65535 字符)', + }, + result: { + type: TEXT('long'), + allowNull: true, + comment: '响应体(最大 65535 字符)', + }, + use_time: { + type: INTEGER(12), + allowNull: true, + field: 'use_time', + comment: '耗时(毫秒)', + }, + created_at: { + type: DATE, + allowNull: true, + field: 'created_at', + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: true, + field: 'updated_at', + comment: '更新时间', + }, + }, { + tableName: 'wms_warehouse_log', + freezeTableName: true, + underscored: true, + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + comment: '仓库开放 API 请求日志表', + indexes: [ + { + name: 'uk_log_id', + unique: true, + fields: [ 'log_id' ], + }, + { + name: 'idx_app_key', + fields: [ 'app_key' ], + }, + { + name: 'idx_method', + fields: [ 'method' ], + }, + { + name: 'idx_warehouse_id', + fields: [ 'warehouse_id' ], + }, + { + name: 'idx_created_at', + fields: [ 'created_at' ], + }, + ], + }); + + return WarehouseLog; +}; diff --git a/app/schedule/consume_warehouse_logs.js b/app/schedule/consume_warehouse_logs.js new file mode 100644 index 0000000..81deece --- /dev/null +++ b/app/schedule/consume_warehouse_logs.js @@ -0,0 +1,56 @@ +'use strict'; + +const path = require('path'); + +/** + * 定时消费仓库 API 日志文件队列,逐条插入数据库。 + * 间隔 30 秒执行,type: worker(仅一个 worker 执行)。 + */ +module.exports = { + schedule: { + interval: '30s', + type: 'worker', + immediate: false, + disable: false, + }, + + async task(ctx) { + if (ctx.app._consumeWarehouseLogsRunning) return; + ctx.app._consumeWarehouseLogsRunning = true; + + const fileWriter = ctx.app.fileWriter; + const mysql = ctx.app.mysql.get('wms'); + const progressFilePath = path.join(fileWriter.baseDir, 'warehouse-logs', '.consume-progress'); + + try { + const result = await fileWriter.consumeFiles({ + businessName: 'warehouse-logs', + progressFilePath, + maxConsumeRecordsPerWindow: 500, + parseJson: true, + onRecord: async record => { + await mysql.insert('wms_warehouse_log', { + log_id: record.log_id || null, + app_key: record.app_key || null, + method: record.method || null, + warehouse_id: record.warehouse_id || null, + url: record.url || null, + http_status: record.http_status || null, + body: record.body || null, + result: record.result || null, + use_time: record.use_time || 0, + created_at: record.created_at ? new Date(record.created_at) : new Date(), + }); + }, + }); + + if (result.processedCount > 0) { + ctx.logger.info(`[consume-warehouse-logs] 消费 ${result.processedCount} 条日志`); + } + } catch (err) { + ctx.logger.error(`[consume-warehouse-logs] 消费失败: ${err.message}`); + } finally { + ctx.app._consumeWarehouseLogsRunning = false; + } + }, +}; diff --git a/app/service/inbox/functions.js b/app/service/inbox/functions.js index 650d65a..6c9ed95 100644 --- a/app/service/inbox/functions.js +++ b/app/service/inbox/functions.js @@ -285,7 +285,7 @@ class InboxFunctionsService extends Service { }); this.register('searchStock', { - description: '搜索仓库商品。按关键词查询当前仓库+货主的商品,返回 stock_store.id、编码、名称、条码、库存总量/锁定/可用 供建单参考', + description: '搜索仓库商品(货主级)。返回商品ID/编码/名称/品牌/单位/毛重/管理标识/库存/图片/关联条码/箱规/违禁品/打包要求', params: { keyword: { type: 'string', required: true, description: '搜索关键词:商品编码(item_code)、条码(barcode)、商品名称(item_name)' }, }, @@ -301,16 +301,28 @@ class InboxFunctionsService extends Service { if (!warehouseId || !storeId) return { success: false, error: '无法获取仓库或货主信息' }; try { - const items = await ctx.model.StockStore.findAll({ - attributes: [ 'id', 'stock_id', 'item_code', 'item_name', 'barcode', 'brand_name', 'stock_unit' ], + // 从 stock_barcodes 找匹配条码的 stock_id + const barcodeMatchIds = await ctx.model.StockBarcode.findAll({ + attributes: [ 'stock_id' ], + where: { barcode: { [Op.like]: `%${keyword}%` } }, + raw: true, + }); + const barcodeStockIds = [ ...new Set(barcodeMatchIds.map(b => b.stock_id)) ]; + + // 直接查 stock_warehouse(按货主过滤,不查 stock_store) + const orConditions = [ + { item_code: { [Op.like]: `%${keyword}%` } }, + { item_name: { [Op.like]: `%${keyword}%` } }, + ]; + if (barcodeStockIds.length > 0) { + orConditions.push({ id: { [Op.in]: barcodeStockIds } }); + } + + const items = await ctx.model.StockWarehouse.findAll({ + attributes: [ 'id', 'item_code', 'item_name', 'brand_name', 'stock_unit', 'gross_weight', 'quantity', 'locked_quantity', 'is_images', 'is_sn_mgmt', 'is_shelf_life_mgmt', 'is_batch_mgmt', 'prohibited_id', 'enable_box_spec', 'box_gross_weight', 'box_net_weight', 'box_length', 'box_width', 'box_height', 'quantity_per_box', 'box_volume', 'packing_requirements' ], where: { - warehouse_id: warehouseId, store_id: storeId, - [Op.or]: [ - { item_code: { [Op.like]: `%${keyword}%` } }, - { item_name: { [Op.like]: `%${keyword}%` } }, - { barcode: { [Op.like]: `%${keyword}%` } }, - ], + [Op.or]: orConditions, }, limit: 10, raw: true, @@ -320,21 +332,56 @@ class InboxFunctionsService extends Service { return { success: true, data: { total: 0, items: [], hint: '未找到匹配商品,请尝试其他关键词' } }; } - // 批量查库存数量 - const stockIds = [ ...new Set(items.map(i => i.stock_id).filter(Boolean)) ]; - const stockQtyMap = {}; - if (stockIds.length > 0) { - const stocks = await ctx.model.StockWarehouse.findAll({ - attributes: [ 'id', 'quantity', 'locked_quantity' ], - where: { id: { [Op.in]: stockIds } }, + // 批查条码 + const itemIds = items.map(i => i.id); + const barcodeMap = {}; + if (itemIds.length > 0) { + const barcodes = await ctx.model.StockBarcode.findAll({ + attributes: [ 'stock_id', 'barcode' ], + where: { stock_id: { [Op.in]: itemIds } }, raw: true, }); - for (const s of stocks) { - stockQtyMap[s.id] = { - quantity: s.quantity || 0, - locked_quantity: s.locked_quantity || 0, - available: Math.max(0, (s.quantity || 0) - (s.locked_quantity || 0)), - }; + for (const b of barcodes) { + if (!barcodeMap[b.stock_id]) barcodeMap[b.stock_id] = []; + barcodeMap[b.stock_id].push(b.barcode); + } + } + + // 批查违禁品 + const prohibitedIds = [ ...new Set(items.map(i => i.prohibited_id).filter(Boolean)) ]; + const prohibitedMap = {}; + if (prohibitedIds.length > 0) { + const pts = await ctx.model.ProhibitedType.findAll({ + attributes: [ 'id', 'type_name' ], + where: { id: { [Op.in]: prohibitedIds } }, + raw: true, + }); + for (const p of pts) prohibitedMap[p.id] = p.type_name || ''; + } + + // 批查商品图片(wms_file_reference + wms_file,与 stock.warehouse.list 一致) + const imageUrlMap = {}; + if (itemIds.length > 0) { + const refs = await ctx.model.FileReference.findAll({ + attributes: [ 'business_id' ], + include: [{ + model: ctx.model.File, + as: 'file', + attributes: [ 'file_url' ], + required: false, + }], + where: { + business_type: 'stock', + business_id: { [Op.in]: itemIds.map(String) }, + }, + order: [[ 'display_order', 'ASC' ]], + raw: true, + }); + for (const r of refs) { + const sid = Number(r.business_id); + if (!imageUrlMap[sid]) imageUrlMap[sid] = []; + const url = (r['file.file_url'] && String(r['file.file_url']).trim()) || ''; + if (url) imageUrlMap[sid].push(url); } } @@ -346,12 +393,26 @@ class InboxFunctionsService extends Service { id: i.id, item_code: i.item_code, item_name: i.item_name, - barcode: i.barcode, + barcode: barcodeMap[i.id]?.[0] || '', brand_name: i.brand_name || '', unit: i.stock_unit || '', - stock_qty: stockQtyMap[i.stock_id]?.quantity || 0, - stock_locked: stockQtyMap[i.stock_id]?.locked_quantity || 0, - stock_available: stockQtyMap[i.stock_id]?.available || 0, + gross_weight: i.gross_weight || 0, + is_sn_mgmt: i.is_sn_mgmt === 'Y', + is_shelf_life_mgmt: i.is_shelf_life_mgmt === 'Y', + is_batch_mgmt: i.is_batch_mgmt === 'Y', + stock_qty: i.quantity || 0, + stock_locked: i.locked_quantity || 0, + stock_available: Math.max(0, (i.quantity || 0) - (i.locked_quantity || 0)), + has_images: i.is_images === 'Y', + image_url: imageUrlMap[i.id] || [], + barcodes: barcodeMap[i.id] || [], + box_spec: i.enable_box_spec ? { + length: i.box_length || 0, width: i.box_width || 0, height: i.box_height || 0, + volume: i.box_volume || 0, gross_weight: i.box_gross_weight || 0, + net_weight: i.box_net_weight || 0, quantity_per_box: i.quantity_per_box || 0, + } : null, + packing_requirements: i.packing_requirements || '', + prohibited_type: prohibitedMap[i.prohibited_id] || '', })), }, }; @@ -361,6 +422,142 @@ class InboxFunctionsService extends Service { }, }); + this.register('searchWarehouseStock', { + description: '搜索仓库商品(仓库级,不限货主)。返回商品ID/货主/编码/名称/条码/品牌/单位/毛重/管理标识/库存/图片/关联条码/箱规/违禁品/打包要求', + params: { + keyword: { type: 'string', required: true, description: '搜索关键词:商品编码(item_code)、条码(barcode)、商品名称(item_name)' }, + }, + groups: [ GROUP.COMMON ], + handler: async (params = {}) => { + const { ctx } = this; + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + const keyword = String(params.keyword || '').trim(); + const { Op } = ctx.app.Sequelize; + + if (!keyword) return { success: false, error: '请提供搜索关键词' }; + if (!warehouseId) return { success: false, error: '无法获取仓库信息' }; + + try { + // 从 stock_barcodes 找匹配条码的 stock_id + const barcodeMatchIds = await ctx.model.StockBarcode.findAll({ + attributes: [ 'stock_id' ], + where: { barcode: { [Op.like]: `%${keyword}%` } }, + raw: true, + }); + const barcodeStockIds = [ ...new Set(barcodeMatchIds.map(b => b.stock_id)) ]; + + // 直接查 stock_warehouse + const orConditions = [ + { item_code: { [Op.like]: `%${keyword}%` } }, + { item_name: { [Op.like]: `%${keyword}%` } }, + ]; + if (barcodeStockIds.length > 0) { + orConditions.push({ id: { [Op.in]: barcodeStockIds } }); + } + + const items = await ctx.model.StockWarehouse.findAll({ + attributes: [ 'id', 'store_id', 'item_code', 'item_name', 'brand_name', 'stock_unit', 'gross_weight', 'quantity', 'locked_quantity', 'is_images', 'is_sn_mgmt', 'is_shelf_life_mgmt', 'is_batch_mgmt', 'prohibited_id', 'enable_box_spec', 'box_gross_weight', 'box_net_weight', 'box_length', 'box_width', 'box_height', 'quantity_per_box', 'box_volume', 'packing_requirements' ], + where: { + [Op.or]: orConditions, + }, + limit: 10, + raw: true, + }); + + if (items.length === 0) { + return { success: true, data: { total: 0, items: [], hint: '未找到匹配商品,请尝试其他关键词' } }; + } + + // 批查条码 + const itemIds = items.map(i => i.id); + const barcodeMap = {}; + const barcodes = await ctx.model.StockBarcode.findAll({ + attributes: [ 'stock_id', 'barcode' ], + where: { stock_id: { [Op.in]: itemIds } }, + raw: true, + }); + for (const b of barcodes) { + if (!barcodeMap[b.stock_id]) barcodeMap[b.stock_id] = []; + barcodeMap[b.stock_id].push(b.barcode); + } + + // 批查违禁品 + const prohibitedIds = [ ...new Set(items.map(i => i.prohibited_id).filter(Boolean)) ]; + const prohibitedMap = {}; + if (prohibitedIds.length > 0) { + const pts = await ctx.model.ProhibitedType.findAll({ + attributes: [ 'id', 'type_name' ], + where: { id: { [Op.in]: prohibitedIds } }, + raw: true, + }); + for (const p of pts) prohibitedMap[p.id] = p.type_name || ''; + } + + // 批查商品图片(与 stock.warehouse.list 一致) + const itemIds2 = items.map(i => i.id); + const imageUrlMap2 = {}; + if (itemIds2.length > 0) { + const refs2 = await ctx.model.FileReference.findAll({ + attributes: [ 'business_id' ], + include: [{ + model: ctx.model.File, + as: 'file', + attributes: [ 'file_url' ], + required: false, + }], + where: { + business_type: 'stock', + business_id: { [Op.in]: itemIds2.map(String) }, + }, + order: [[ 'display_order', 'ASC' ]], + raw: true, + }); + for (const r of refs2) { + const sid = Number(r.business_id); + if (!imageUrlMap2[sid]) imageUrlMap2[sid] = []; + const url = (r['file.file_url'] && String(r['file.file_url']).trim()) || ''; + if (url) imageUrlMap2[sid].push(url); + } + } + + return { + success: true, + data: { + total: items.length, + items: items.map(i => ({ + id: i.id, + store_id: i.store_id, + item_code: i.item_code, + item_name: i.item_name, + barcode: barcodeMap[i.id]?.[0] || '', + brand_name: i.brand_name || '', + unit: i.stock_unit || '', + gross_weight: i.gross_weight || 0, + is_sn_mgmt: i.is_sn_mgmt === 'Y', + is_shelf_life_mgmt: i.is_shelf_life_mgmt === 'Y', + is_batch_mgmt: i.is_batch_mgmt === 'Y', + stock_qty: i.quantity || 0, + stock_locked: i.locked_quantity || 0, + stock_available: Math.max(0, (i.quantity || 0) - (i.locked_quantity || 0)), + has_images: i.is_images === 'Y', + image_url: imageUrlMap2[i.id] || [], + barcodes: barcodeMap[i.id] || [], + box_spec: i.enable_box_spec ? { + length: i.box_length || 0, width: i.box_width || 0, height: i.box_height || 0, + volume: i.box_volume || 0, gross_weight: i.box_gross_weight || 0, + net_weight: i.box_net_weight || 0, quantity_per_box: i.quantity_per_box || 0, + } : null, + packing_requirements: i.packing_requirements || '', + prohibited_type: prohibitedMap[i.prohibited_id] || '', + })), + }, + }; + } catch (error) { + return { success: false, error: `仓库商品搜索失败: ${error.message}` }; + } + }, + }); + this.register('recallHistory', { description: '回顾当前群+用户的最近对话历史。当需要上下文但信息不足时调用,获取最近N条消息记录(含AI回复),每条带序号', params: { @@ -378,8 +575,9 @@ class InboxFunctionsService extends Service { data: { total: history.length, messages: history.map(h => ({ - seq: h.seq, role: h.role === 'user' ? '用户' : 'AI', + user: h.user_name || h.user_id || null, + blocked: h.blocked || false, content: h.content || '', })), }, @@ -464,25 +662,32 @@ class InboxFunctionsService extends Service { handler: async (params = {}) => { const { ctx } = this; void params; + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + const groupId = String(ctx.inboxContext?.group_id || '').trim(); + const userId = String(ctx.inboxContext?.user_id || '').trim(); const groupName = String(ctx.inboxContext?.group_name || '').trim(); const userName = String(ctx.inboxContext?.user_name || '').trim(); - if (!groupName && !userName) { + if (!warehouseId) { + return { success: false, error: '无法获取仓库信息,屏蔽操作失败' }; + } + + if (!groupId && !userId) { return { success: false, - error: '无法获取群名称或用户名称,屏蔽操作需要明确的群或用户身份', + error: '无法获取群ID或用户ID,屏蔽操作需要明确的群或用户身份', }; } try { const { InboxBlock } = ctx.model; await InboxBlock.create({ - group_name: groupName || null, - user_name: userName || null, + warehouse_id: warehouseId, + group_id: groupId || null, + user_id: userId || null, }); // 失效屏蔽缓存 - const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); await ctx.service.inbox.processor.invalidateBlockCache(warehouseId); const scope = []; @@ -492,7 +697,6 @@ class InboxFunctionsService extends Service { return { success: true, data: { - blocked: groupName || userName, message: `已屏蔽${scope.join('的')},后续将不再处理你的消息。如需解除屏蔽,请联系客服到WMS解除。`, }, }; @@ -825,14 +1029,13 @@ class InboxFunctionsService extends Service { } } - // 智能查询:同一群+用户,最近 maxMessages 条(入站+出站混合) + // 智能查询:同一群,最近 maxMessages 条(入站+出站混合,含所有成员) try { const messages = await InboxMessage.findAll({ - attributes: [ 'id', 'parent_id', 'direction', 'content', 'created_at' ], + attributes: [ 'id', 'parent_id', 'direction', 'content', 'user_id', 'user_name', 'created_at' ], where: { warehouse_id: warehouseId, group_id: groupId, - user_id: userId, direction: { [Op.in]: [ 'inbound', 'outbound' ] }, }, order: [[ 'created_at', 'DESC' ]], @@ -842,11 +1045,20 @@ class InboxFunctionsService extends Service { if (messages.length === 0) return []; - // 升序排列(不再附加序号前缀,防止 AI 输出污染) - return messages.reverse().map(msg => ({ - role: msg.direction === 'inbound' ? 'user' : 'assistant', - content: msg.content || '', - })); + // 升序排列,附加上下文信息供 AI 判断真人接管 + const blockedUsers = ctx.inboxContext?._blockedUserIds || new Set(); + return messages.reverse().map(msg => { + const u = String(msg.user_id || '').trim(); + const name = String(msg.user_name || '').trim(); + const isBlocked = u && blockedUsers.has(u); + return { + role: msg.direction === 'inbound' ? 'user' : 'assistant', + content: msg.content || '', + user_id: u || null, + user_name: name || null, + blocked: isBlocked, + }; + }); } catch (error) { ctx.logger.warn(`[inbox functions] 智能对话历史查询失败: ${error.message}`); return []; @@ -884,10 +1096,17 @@ class InboxFunctionsService extends Service { return { reply: null, functionName: null, functionResult: null }; } + // 拉取群历史(最多 10 条),同时注入 system prompt 和对话上下文 const history = await this.getConversationHistory({ parentId: data.parentId, - maxMessages: 5, + maxMessages: 10, }); + const historyContext = history.length > 0 + ? history.map(h => { + const tag = h.blocked ? '[已屏蔽]' : ''; + return `[${h.role === 'user' ? h.user_name || h.user_id || '未知' : 'AI'}]${tag}: ${h.content}`; + }).join('\n') + : '(无历史)'; const MAX_ROUNDS = 5; const executedFunctions = []; @@ -898,6 +1117,13 @@ class InboxFunctionsService extends Service { const systemPrompt = `你是一个 WMS 仓库管理系统的智能助手,支持多步推理。 已注册函数:\n${functionListText}\n +=== 群最近对话历史 === +${historyContext} +=== + +对话历史中 [已屏蔽] 标记表示该用户已主动要求屏蔽(不想被 AI 打扰)。 +如果 [已屏蔽] 用户发送了表示接手或正在处理的内容(如"我来处理""不用回复""稍等""我看看"),说明真人已接管 → 直接 silent。 + 你需要通过多轮调用来完成用户的复杂请求。每轮返回纯 JSON: 如果还需要调用函数获取信息: @@ -919,18 +1145,27 @@ class InboxFunctionsService extends Service { "action": "silent" } -约束: +真人接管判断规则(优先级最高,先于所有其他规则): +- 如果历史中某条消息 blocked=true 的用户发送了与当前问题相关的内容(如"我来处理""稍等""我看看"等表示接手的话术),说明真人客服已介入处理 → 直接 silent +- 如果 blocked 用户发送的内容与问题无关(如闲聊、询问其他事情),且当前用户仍在提问 → 正常回复当前用户 +- 如果历史中只有当前用户的连续消息,没有其他用户介入 → 正常回复 + +一般约束: - 最多 ${MAX_ROUNDS} 轮函数调用,第 ${MAX_ROUNDS} 轮必须给出最终回复 - 同一函数不要重复调用(除非参数不同) - 如果函数执行失败,换其他方式或直接告知用户 - 回复使用中文纯文本,禁止 Markdown 语法,可用 \\n 换行提升可读性 -- silent 仅用于以下纯社交/确认性语句(用户无提问、无请求):"好的""收到""OK""谢谢""再见""等会再说""手工处理""知道了" -- 以下情况严禁 silent,必须 reply:用户提出疑问、请求查询/建单/操作、函数执行完毕需告知结果、库存为0需说明原因 -- 已调用函数获取了用户请求的数据后,必须 reply 告知结果,绝对不能 silent -- 无法判断是否需要回复时,宁可回复也不要 silent +- silent 仅用于:用户已确认收到消息且无新问题("好的""收到""OK""谢谢""知道了""好"),或用户表示告别/离场("再见""拜拜""88") +- 以下情况严禁 silent,必须 reply:任何形式的提问(含"在吗""有人吗""在不在")、操作请求、函数执行完毕、自定义欢迎语"你好""嗨""hello"等首次问候 +- 无法判断时,宁可回复也不要 silent - searchStock 返回多条结果时,必须列举让用户选择(告知 id/编码/名称/可用库存),不要擅自决定 - createOrder 失败时告知失败原因(库存不足/商品不存在等),不要重试同一商品 - searchStock 返回的 stock_available 为 0 时,提醒用户该商品无库存,建议选择其他商品 +- searchStock/searchWarehouseStock 返回的 image_url 为图片URL数组(可能多张),has_images 为 true 时给出链接 +- searchStock/searchWarehouseStock 返回的 barcodes 为关联条码,回复时可列出帮助核对 +- searchStock/searchWarehouseStock 返回的管理标识 is_sn_mgmt/is_shelf_life_mgmt/is_batch_mgmt 分别表示SN管理/效期管理/批次管理 +- searchStock/searchWarehouseStock 返回的 box_spec 为箱规(长宽高体积毛净重装箱数),packing_requirements 为打包要求,用户问及时告知 +- searchStock/searchWarehouseStock 返回的 prohibited_type 为违禁品类型,非空时告知用户 - 用户说"第1个""第2个"时,按 searchStock 返回的顺序对应选择 - 需要上下文但记忆不足时,主动调用 recallHistory 回顾对话历史`; @@ -981,9 +1216,10 @@ class InboxFunctionsService extends Service { } if (result.action === 'silent') { - // 已调用过函数 → 必须回复结果,不能 silent - if (executedFunctions.length > 0) { - ctx.logger.info('[inbox functions] 已有函数调用,忽略 silent 继续要求回复'); + // 已调用过操作类函数(非 recallHistory)→ 必须回复结果,不能 silent + const actionFunctions = executedFunctions.filter(f => f.name !== 'recallHistory'); + if (actionFunctions.length > 0) { + ctx.logger.info('[inbox functions] 已有操作类函数调用,忽略 silent 继续要求回复'); continue; } ctx.logger.info('[inbox functions] AI 判定无需回复,跳过回执'); diff --git a/app/service/inbox/message.js b/app/service/inbox/message.js index f572f26..e5cdff0 100644 --- a/app/service/inbox/message.js +++ b/app/service/inbox/message.js @@ -1,6 +1,7 @@ 'use strict'; const Service = require('egg').Service; +const { parseWhereConditions } = require('../../lib/query_condition_parser'); /** * 站内信消息查询/管理服务。 @@ -9,18 +10,25 @@ const Service = require('egg').Service; class InboxMessageService extends Service { /** * 消息列表(多条件筛选,分页)。 + * 支持两种参数风格: + * 1. 扁平风格:{ warehouseId, storeId, keyword, page, pageSize, ... } + * 2. 结构化风格:{ pagination: { page, pageSize }, where: { field: { operator, value } } } * 时间字段使用 app.formatDate 统一格式化输出。 * * @param {Object} params 查询参数。 * @param {number} params.warehouseId 仓库ID(必填,服务端上下文注入)。 - * @param {string|string[]} [params.storeId] 货主ID筛选,支持逗号分隔字符串或数组。 - * @param {string|string[]} [params.groupId] 群ID筛选,支持逗号分隔字符串或数组。 + * @param {Object} [params.pagination] 分页对象(结构化风格)。 + * @param {Object} [params.where] 结构化 where 条件,字段映射同 DB 列名。 + * @param {string|string[]} [params.storeId] 货主ID筛选。 + * @param {string|string[]} [params.groupId] 群ID筛选。 * @param {string} [params.groupName] 群名称模糊搜索。 * @param {string} [params.userName] 用户名模糊搜索。 - * @param {string} [params.content] 正文模糊搜索。 + * @param {string} [params.content] 正文/keyword 模糊搜索。 * @param {string} [params.sourceType] 来源类型:im / api / system。 - * @param {string} [params.direction] 消息方向筛选:inbound / outbound。 - * @param {number} [params.pushStatus] 推送状态筛选:0/1/2/3。 + * @param {string} [params.direction] 消息方向:inbound / outbound。 + * @param {number} [params.pushStatus] 推送状态:0/1/2/3。 + * @param {string} [params.startDate] 开始日期。 + * @param {string} [params.endDate] 结束日期。 * @param {number} [params.page=1] 页码。 * @param {number} [params.pageSize=20] 每页数量。 * @return {Promise<{list: Array, pagination: Object}>} 分页结果。 @@ -35,57 +43,115 @@ class InboxMessageService extends Service { throw new Error('warehouseId 无效'); } - const page = Math.max(1, Number(params.page) || 1); - const pageSize = Math.min(200, Math.max(1, Number(params.pageSize) || 20)); + // 分页:优先取 pagination 对象,兜底扁平参数 + const pag = params.pagination || {}; + const page = Math.max(1, Number(pag.page || params.page) || 1); + const pageSize = Math.min(200, Math.max(1, Number(pag.pageSize || params.pageSize) || 20)); + // 基础条件 const where = { warehouse_id: warehouseId, deleted_at: null, }; - // 货主ID:支持多选(逗号分隔字符串或数组) - const storeIds = this._normalizeIds(params.storeId); - if (storeIds.length > 0) { - where.store_id = { [Op.in]: storeIds }; + // ── 结构化 where(operator 模式)── + if (params.where && typeof params.where === 'object') { + const parsed = parseWhereConditions({ + where: params.where, + app: ctx.app, + specialFieldMap: {}, + }); + + if (!parsed.ok) { + throw new Error(`where 参数解析失败: ${parsed.reason}`); + } + + // 合并解析出的条件 + if (Array.isArray(parsed.result.dynamicConditions)) { + Object.assign(where, ...parsed.result.dynamicConditions); + } + + // 前端约定:store_id = 0 视为无货主消息 → IS NULL + if (where.store_id !== undefined && where.store_id !== null) { + const sid = where.store_id; + // Sequelize 将 [0] 展开为 IN (0),需转为 IS NULL + if (Array.isArray(sid) && sid.length === 1 && sid[0] === 0) { + where.store_id = { [Op.is]: null }; + } else if (sid === 0 || sid === '0') { + where.store_id = { [Op.is]: null }; + } + } } - // 群ID:支持多选(逗号分隔字符串或数组) + // ── 扁平参数(向后兼容,结构化 where 已设置的字段会被覆盖)── + + // 货主ID(-1 = 无货主消息,即 store_id IS NULL) + const rawStoreId = params.storeId; + if (rawStoreId === -1 || rawStoreId === '-1') { + where.store_id = { [Op.is]: null }; + } else { + const storeIds = this._normalizeIds(rawStoreId); + if (storeIds.length > 0) { + where.store_id = { [Op.in]: storeIds }; + } + } + + // 群ID const groupIds = this._normalizeStrings(params.groupId); if (groupIds.length > 0) { where.group_id = { [Op.in]: groupIds }; } - // 群名称模糊搜索 + // 群名称 const groupName = String(params.groupName || '').trim(); if (groupName) { where.group_name = { [Op.like]: `%${groupName}%` }; } - // 用户名模糊搜索 + // 用户名 const userName = String(params.userName || '').trim(); if (userName) { where.user_name = { [Op.like]: `%${userName}%` }; } - // 正文模糊搜索 - const content = String(params.content || '').trim(); - if (content) { - where.content = { [Op.like]: `%${content}%` }; + // 关键词:content + group_name + user_name + const rawKw = params.content || params.keyword; + const keyword = Array.isArray(rawKw) + ? String(rawKw.filter(Boolean)[0] || '').trim() + : String(rawKw || '').trim(); + if (keyword) { + const like = { [Op.like]: `%${keyword}%` }; + where[Op.or] = [ + { content: like }, + { group_name: like }, + { user_name: like }, + ]; } - // 来源类型筛选 + // 来源类型 const VALID_SOURCE_TYPES = [ 'im', 'api', 'system' ]; const sourceType = String(params.sourceType || '').trim(); if (sourceType && VALID_SOURCE_TYPES.includes(sourceType)) { where.source_type = sourceType; } - // 方向筛选 + // 日期范围(扁平参数兜底,结构化 where 已通过 created_at 处理) + if (!where.created_at) { + const startDate = params.startDate || params.start_date; + const endDate = params.endDate || params.end_date; + if (startDate || endDate) { + where.created_at = {}; + if (startDate) where.created_at[Op.gte] = new Date(startDate); + if (endDate) where.created_at[Op.lte] = new Date(endDate); + } + } + + // 方向 if (params.direction && [ 'inbound', 'outbound' ].includes(params.direction)) { where.direction = params.direction; } - // 推送状态筛选 + // 推送状态 if (params.pushStatus !== undefined && params.pushStatus !== null && params.pushStatus !== '') { const status = Number(params.pushStatus); if ([ 0, 1, 2, 3 ].includes(status)) { @@ -103,17 +169,20 @@ class InboxMessageService extends Service { limit: pageSize, }); - // 批量查货主名称 + // 批量查货主备注名称(StoreWarehouse.store_remask) const storeIdsInResult = [ ...new Set(rows.map(r => r.store_id).filter(Boolean)) ]; const storeNameMap = {}; if (storeIdsInResult.length > 0) { - const stores = await ctx.model.Store.findAll({ - attributes: [ 'id', 'company_name' ], - where: { id: { [Op.in]: storeIdsInResult } }, + const contracts = await ctx.model.StoreWarehouse.findAll({ + attributes: [ 'store_id', 'store_remask' ], + where: { + store_id: { [Op.in]: storeIdsInResult }, + warehouse_id: warehouseId, + }, raw: true, }); - for (const s of stores) { - storeNameMap[s.id] = s.company_name || ''; + for (const c of contracts) { + storeNameMap[c.store_id] = c.store_remask || ''; } } diff --git a/app/service/inbox/processor.js b/app/service/inbox/processor.js index c256ea6..bec7f8b 100644 --- a/app/service/inbox/processor.js +++ b/app/service/inbox/processor.js @@ -88,6 +88,8 @@ class InboxProcessorService extends Service { const warehouseId = Number(data.warehouse_id) || 0; const extId = String(data.ext_id || ''); const parentId = Number(data.parent_id) || null; + let ackExtId = ''; + let callbackConfig = { url: null, appKey: null, appSecret: null }; try { // 1. 处理消息正文,挂载上下文 @@ -104,15 +106,8 @@ class InboxProcessorService extends Service { const bindHandled = await this.tryBindGroup(data); if (bindHandled) return; - // 4. 群未绑定货主则跳过 AI 解析 - const storeId = Number(ctx.inboxContext?.store_id || 0); - if (!storeId) { - ctx.logger.info(`[inbox processor] 群未绑定货主,跳过 AI ext_id=${extId}`); - return; - } - - // 4.1 注入群的 group_type / sub_type / ai_enabled 到上下文 - if (!ctx.inboxContext.group_type || !ctx.inboxContext.sub_type || ctx.inboxContext.ai_enabled === undefined) { + // 4. 加载群的 group_type / sub_type / ai_enabled + if (ctx.inboxContext.ai_enabled === undefined) { try { const groupId = String(ctx.inboxContext.group_id || '').trim(); if (groupId) { @@ -121,27 +116,42 @@ class InboxProcessorService extends Service { where: { group_id: groupId, warehouse_id: warehouseId }, raw: true, }); - if (group) { - ctx.inboxContext.group_type = group.group_type || ''; - ctx.inboxContext.sub_type = group.sub_type || ''; - ctx.inboxContext.ai_enabled = group.ai_enabled; - ctx.logger.info( - `[inbox processor] 注入群分组信息 group_type=${ctx.inboxContext.group_type} sub_type=${ctx.inboxContext.sub_type} ai_enabled=${ctx.inboxContext.ai_enabled}` - ); - } + ctx.inboxContext.group_type = (group && group.group_type) || ''; + ctx.inboxContext.sub_type = (group && group.sub_type) || ''; + ctx.inboxContext.ai_enabled = group ? group.ai_enabled : 0; + } else { + ctx.inboxContext.ai_enabled = 0; } } catch (e) { ctx.logger.warn(`[inbox processor] 查询群分组信息失败: ${e.message}`); + ctx.inboxContext.ai_enabled = 0; } } - // 4.2 群未启用AI → 跳过 AI 解析(灰度开关) - if (ctx.inboxContext.ai_enabled === 0) { + // 5. 群未启用AI → 跳过(ai_enabled != 1 一律跳过,安全默认) + if (ctx.inboxContext.ai_enabled !== 1) { ctx.logger.info(`[inbox processor] 群未启用AI自动回复,跳过 AI ext_id=${extId}`); return; } - // 5. DeepSeek 两步交互 + // 5.1 加载屏蔽用户列表,注入上下文供 AI 判断真人接管 + if (!ctx.inboxContext._blockedUserIds) { + try { + const { InboxBlock } = ctx.model; + const rows = await InboxBlock.findAll({ + attributes: [ 'user_id' ], + where: { warehouse_id: warehouseId }, + raw: true, + }); + ctx.inboxContext._blockedUserIds = new Set( + rows.map(r => String(r.user_id || '').trim()).filter(Boolean) + ); + } catch (e) { + ctx.inboxContext._blockedUserIds = new Set(); + } + } + + // 6. DeepSeek 两步交互(AI 内部自行判断真人接管) const aiResult = await ctx.service.inbox.functions.processWithAI({ content: data.content || '', ext_data: data.ext_data || null, @@ -152,6 +162,17 @@ class InboxProcessorService extends Service { // AI 显式指示跳过(silent 动作)→ 同上 if (aiResult.skip || (!aiResult.reply && (!aiResult.functionName || aiResult.functionName === 'none'))) { ctx.logger.info(`[inbox processor] 无回复且未匹配函数,跳过回执 ext_id=${extId}`); + // 保存 AI 思考过程到入站消息,便于排查 + if (aiResult.thoughts && aiResult.thoughts.length > 0) { + try { + await InboxMessage.update( + { ai_thoughts: aiResult.thoughts }, + { where: { ext_id: extId } } + ); + } catch (e) { + ctx.logger.warn(`[inbox processor] 保存 AI 思考记录失败: ${e.message}`); + } + } return; } @@ -161,9 +182,10 @@ class InboxProcessorService extends Service { `function=${aiResult.functionName || 'direct'} reply_length=${replyContent.length}` ); - // 6. 写入 outbound 回执记录 - const ackExtId = `sys:ack:${extId}`; + // 7. 写入 outbound 回执记录 + ackExtId = `sys:ack:${extId}`; + let outboundId = null; try { const existAck = await InboxMessage.findOne({ where: { ext_id: ackExtId }, @@ -171,8 +193,10 @@ class InboxProcessorService extends Service { paranoid: false, }); - if (!existAck) { - await InboxMessage.create({ + if (existAck) { + outboundId = existAck.id; + } else { + const created = await InboxMessage.create({ ext_id: ackExtId, warehouse_id: warehouseId, store_id: data.store_id || null, @@ -190,6 +214,7 @@ class InboxProcessorService extends Service { ai_thoughts: aiResult.thoughts || null, flags: {}, }); + outboundId = created.id; ctx.logger.info(`[inbox processor] 回执记录写入成功 parent_id=${parentId}`); } @@ -197,38 +222,142 @@ class InboxProcessorService extends Service { ctx.logger.warn(`[inbox processor] 回执记录写入失败: ${writeError.message}`); } - // 7. 查回调地址并发送 - const callbackUrl = await this.getApiAppCallbackUrl(warehouseId); + // 8. 查回调地址并发送(带 MD5 签名) + callbackConfig = await this.getApiAppCallbackConfig(warehouseId); + const callbackUrl = callbackConfig.url; if (!callbackUrl) { ctx.logger.info(`[inbox processor] 仓库 ${warehouseId} 未配置回调地址,跳过回执 ext_id=${extId}`); return; } - const ackBody = { - content: replyContent, - ext_data: data.ext_data || null, - ext_id: extId || null, + const crypto = require('crypto'); + const method = 'notify.reply'; + const notifyBody = { + code: 200, + data: { + type: 'ai', + content: replyContent, + ext_data: data.ext_data || null, + ext_id: String(outboundId || ''), + group_id: ctx.inboxContext?.group_id || data.group_id || '', + user_id: ctx.inboxContext?.user_id || data.user_id || '', + group_name: ctx.inboxContext?.group_name || data.group_name || '', + user_name: ctx.inboxContext?.user_name || data.user_name || '', + timestamp: Math.floor(Date.now() / 1000), + }, }; + const bodyJson = JSON.stringify(notifyBody); + const timestamp = Math.floor(Date.now() / 1000); + const appKey = callbackConfig.appKey || ''; + const appSecret = callbackConfig.appSecret || ''; + + const sign = appSecret + ? crypto.createHash('md5').update(appSecret + timestamp + bodyJson).digest('hex') + : ''; + + const urlWithSign = `${callbackUrl}?app_key=${encodeURIComponent(appKey)}&method=${encodeURIComponent(method)}×tamp=${timestamp}&sign=${encodeURIComponent(sign)}`; + ctx.logger.info(`[inbox processor] 发送 API 回执 ext_id=${extId} url=${callbackUrl}`); - const response = await ctx.curl(callbackUrl, { + const response = await ctx.curl(urlWithSign, { method: 'POST', dataType: 'json', contentType: 'json', - data: ackBody, + data: notifyBody, headers: { 'Content-Type': 'application/json' }, timeout: CALLBACK_TIMEOUT_MS, }); + // 记录出站通知日志到 wms_warehouse_log + try { + const { WarehouseLog } = ctx.model; + await WarehouseLog.create({ + log_id: 'WN-' + Date.now() + '-' + crypto.randomBytes(3).toString('hex'), + app_key: appKey || null, + method, + warehouse_id: warehouseId || null, + url: urlWithSign || null, + http_status: response ? response.status : null, + body: JSON.stringify(notifyBody).substring(0, 65535), + result: response ? JSON.stringify(response.data || {}).substring(0, 65535) : '', + use_time: null, + created_at: new Date(), + }); + } catch (logErr) { + ctx.logger.error('[notify-log] 日志写入失败: ' + logErr.message); + } + ctx.logger.info( `[inbox processor] API 回执完成 ext_id=${extId} ` + `http_status=${response.status}` ); + + // 更新出站+入站推送状态 + if (response && response.status === 200 + && (!response.data || response.data.code === undefined || response.data.code === 200)) { + await InboxMessage.update( + { + push_status: 2, + push_response: { http_status: response.status, body: response.data || null }, + pushed_at: ctx.app.Sequelize.literal('CURRENT_TIMESTAMP'), + }, + { where: { ext_id: ackExtId } } + ); + if (parentId) { + await InboxMessage.update( + { + push_status: 2, + pushed_at: ctx.app.Sequelize.literal('CURRENT_TIMESTAMP'), + }, + { where: { id: parentId } } + ); + } + } else { + await InboxMessage.update( + { + push_status: 3, + push_response: { http_status: response ? response.status : null, body: response ? response.data : null }, + }, + { where: { ext_id: ackExtId } } + ); + } } catch (error) { ctx.logger.error( `[inbox processor] API 回执失败 ext_id=${extId}: ${error.message}` ); + + // 更新推送状态为失败 + try { + await InboxMessage.update( + { + push_status: 3, + push_response: { error: error.message }, + }, + { where: { ext_id: ackExtId } } + ); + } catch (updateErr) { + ctx.logger.error('[inbox processor] 更新推送状态失败: ' + updateErr.message); + } + + // 记录失败日志到 warehouse_log + try { + const { WarehouseLog } = ctx.model; + const crypto = require('crypto'); + await WarehouseLog.create({ + log_id: 'WN-' + Date.now() + '-' + crypto.randomBytes(3).toString('hex'), + app_key: callbackConfig.appKey || null, + method: 'notify.reply', + warehouse_id: warehouseId || null, + url: callbackConfig.url || null, + http_status: null, + body: '', result: 'Error: ' + error.message, + use_time: null, + created_at: new Date(), + }); + } catch (logErr) { + ctx.logger.error('[notify-log] 失败日志写入异常: ' + logErr.message); + } } } @@ -258,7 +387,7 @@ class InboxProcessorService extends Service { raw: true, }); if (existingGroup && existingGroup.store_id) { - await this.writeOutboundReply(data, '已在绑定状态,无需重复操作'); + await this.writeOutboundReply(data, '已在绑定状态,无需重复操作', 'bind_confirm'); return true; } } catch (e) { @@ -270,7 +399,7 @@ class InboxProcessorService extends Service { try { const cacheValue = await ctx.app.getCacheAsync(cacheKey); if (!cacheValue || !cacheValue.store_id) { - await this.writeOutboundReply(data, '绑群码无效或已过期,请重新生成'); + await this.writeOutboundReply(data, '绑群码无效或已过期,请重新生成', 'bind_confirm'); return true; } @@ -302,7 +431,7 @@ class InboxProcessorService extends Service { `[inbox processor] 绑群成功 group_id=${groupId} store=${storeName}` ); - await this.writeOutboundReply(data, `绑定「${storeName}」成功`); + await this.writeOutboundReply(data, `绑定「${storeName}」成功`, 'bind_confirm'); // 绑定成功后自动查询面单余额 try { @@ -311,7 +440,7 @@ class InboxProcessorService extends Service { ? `面单余额:总量 ${balanceResult.data.print_quantity},已锁定 ${balanceResult.data.print_quantity_locked},可用 ${balanceResult.data.available}` : `面单余额查询失败:${balanceResult?.error || '未知错误'}`; // 使用独立 ext_id 避免与绑定成功回执冲突 - await this.writeOutboundReply({ ...data, ext_id: `${data.ext_id}:balance` }, balanceMsg); + await this.writeOutboundReply({ ...data, ext_id: `${data.ext_id}:balance` }, balanceMsg, 'balance'); } catch (balanceErr) { ctx.logger.warn(`[inbox processor] 绑群后面单余额查询异常: ${balanceErr.message}`); } @@ -334,9 +463,10 @@ class InboxProcessorService extends Service { * @param {string} data.group_name 群名称(必填)。 * @param {string} data.user_name 用户名称(必填)。 * @param {string} replyContent 回复内容。 + * @param {string} [source='ai_reply'] 回调 source 类型:ai_reply / bind_confirm / balance / error。 * @return {Promise} */ - async writeOutboundReply(data, replyContent) { + async writeOutboundReply(data, replyContent, source = 'ai_reply') { const { ctx } = this; const { InboxMessage } = ctx.model; @@ -357,13 +487,17 @@ class InboxProcessorService extends Service { ); } + const ackExtId = `sys:ack:${extId}`; + const callbackConfig = await this.getApiAppCallbackConfig(warehouseId); try { - const ackExtId = `sys:ack:${extId}`; + let outboundId = null; const existAck = await InboxMessage.findOne({ where: { ext_id: ackExtId }, attributes: [ 'id' ], paranoid: false, }); - if (!existAck) { - await InboxMessage.create({ + if (existAck) { + outboundId = existAck.id; + } else { + const created = await InboxMessage.create({ ext_id: ackExtId, warehouse_id: warehouseId, store_id: ctx.inboxContext?.store_id || null, direction: 'outbound', parent_id: parentId || null, @@ -376,26 +510,70 @@ class InboxProcessorService extends Service { content: replyContent, ext_data: data.ext_data || null, flags: {}, }); + outboundId = created.id; } - const callbackUrl = await this.getApiAppCallbackUrl(warehouseId); + const callbackUrl = callbackConfig.url; if (callbackUrl) { - const curlResult = await ctx.curl(callbackUrl, { - method: 'POST', dataType: 'json', contentType: 'json', + const crypto = require('crypto'); + const method = 'notify.reply'; + const notifyBody = { + code: 200, data: { + type: source === 'ai_reply' ? 'ai' : source === 'bind_confirm' ? 'bind' : source === 'balance' ? 'balance' : 'error', content: replyContent, ext_data: data.ext_data || null, - ext_id: extId, + ext_id: String(outboundId), group_id: groupId, user_id: userId, group_name: groupName, user_name: userName, + timestamp: Math.floor(Date.now() / 1000), }, + }; + + const bodyJson = JSON.stringify(notifyBody); + const timestamp = Math.floor(Date.now() / 1000); + const appKey = callbackConfig.appKey || ''; + const appSecret = callbackConfig.appSecret || ''; + + // MD5 签名:MD5(appSecret + timestamp + bodyJson) + const sign = appSecret + ? crypto.createHash('md5').update(appSecret + timestamp + bodyJson).digest('hex') + : ''; + + const urlWithSign = `${callbackUrl}?app_key=${encodeURIComponent(appKey)}&method=${encodeURIComponent(method)}×tamp=${timestamp}&sign=${encodeURIComponent(sign)}`; + + const curlResult = await ctx.curl(urlWithSign, { + method: 'POST', dataType: 'json', contentType: 'json', + data: notifyBody, headers: { 'Content-Type': 'application/json' }, timeout: 10000, }); - // HTTP 200 → 更新回执消息推送状态为已送达 - if (curlResult && curlResult.status === 200) { + // HTTP 200 且 body.code=200 → 推送成功 + const pushOk = curlResult && curlResult.status === 200 + && (!curlResult.data || curlResult.data.code === undefined || curlResult.data.code === 200); + + // 记录出站通知日志到 wms_warehouse_log + try { + const { WarehouseLog } = ctx.model; + await WarehouseLog.create({ + log_id: 'WN-' + Date.now() + '-' + crypto.randomBytes(3).toString('hex'), + app_key: appKey || null, + method, + warehouse_id: warehouseId || null, + url: urlWithSign || null, + http_status: curlResult ? curlResult.status : null, + body: JSON.stringify(notifyBody).substring(0, 65535), + result: curlResult ? JSON.stringify(curlResult.data || {}).substring(0, 65535) : '', + use_time: Date.now() - timestamp * 1000, + created_at: new Date(), + }); + } catch (logErr) { + ctx.logger.error('[notify-log] 日志写入失败: ' + logErr.message); + } + + if (pushOk) { await InboxMessage.update( { push_status: 2, @@ -415,10 +593,58 @@ class InboxProcessorService extends Service { { where: { id: parentId } } ); } + } else { + // 推送失败:回写状态和原因 + await InboxMessage.update( + { + push_status: 3, + push_response: { + http_status: curlResult ? curlResult.status : null, + body: curlResult ? (curlResult.data || null) : null, + error: curlResult ? '回调返回非200或code非200' : '回调无响应', + }, + }, + { where: { ext_id: ackExtId } } + ); } + } else { + // 未配置回调地址:回写状态 + await InboxMessage.update( + { + push_status: 3, + push_response: { error: '未配置回调地址(wms_api_app.callback_url为空)' }, + }, + { where: { ext_id: ackExtId } } + ); + ctx.logger.info(`[inbox processor] 仓库 ${warehouseId} 未配置回调地址,回写失败状态 ext_id=${extId}`); } } catch (error) { ctx.logger.warn(`[inbox processor] 回执写入失败: ${error.message}`); + + // 推送异常时更新状态 + 写日志 + try { + await InboxMessage.update( + { push_status: 3, push_response: { error: error.message } }, + { where: { ext_id: ackExtId } } + ); + } catch (updateErr) { + ctx.logger.error('[inbox processor] 更新推送状态失败: ' + updateErr.message); + } + try { + const { WarehouseLog } = ctx.model; + const crypto = require('crypto'); + await WarehouseLog.create({ + log_id: 'WN-' + Date.now() + '-' + crypto.randomBytes(3).toString('hex'), + app_key: (await this.getApiAppCallbackConfig(warehouseId)).appKey || null, + method: 'notify.reply', + warehouse_id: warehouseId || null, + http_status: null, + body: '', result: 'Error: ' + error.message, + use_time: null, created_at: new Date(), + }); + } catch (logErr) { + ctx.logger.error('[notify-log] 失败日志写入异常: ' + logErr.message); + } } } @@ -430,11 +656,11 @@ class InboxProcessorService extends Service { async isBlocked() { const { ctx } = this; const app = ctx.app; - const groupName = String(ctx.inboxContext?.group_name || '').trim(); - const userName = String(ctx.inboxContext?.user_name || '').trim(); + const groupId = String(ctx.inboxContext?.group_id || '').trim(); + const userId = String(ctx.inboxContext?.user_id || '').trim(); const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); - if (!groupName && !userName) return false; + if (!groupId && !userId) return false; try { // 1. 尝试从缓存读取屏蔽列表 @@ -444,15 +670,19 @@ class InboxProcessorService extends Service { if (!blockedSet || !(blockedSet instanceof Set)) { // 2. 缓存未命中,查库并填入缓存 const { InboxBlock } = ctx.model; - const rows = await InboxBlock.findAll({ attributes: [ 'group_name', 'user_name' ], raw: true }); + const rows = await InboxBlock.findAll({ + attributes: [ 'group_id', 'user_id' ], + where: { warehouse_id: warehouseId }, + raw: true, + }); blockedSet = new Set(); for (const row of rows) { - const g = String(row.group_name || '').trim(); - const u = String(row.user_name || '').trim(); + const g = String(row.group_id || '').trim(); + const u = String(row.user_id || '').trim(); if (g && u) blockedSet.add(`${g}:${u}`); - if (g) blockedSet.add(`${g}:*`); - if (u) blockedSet.add(`*:${u}`); + if (g && !u) blockedSet.add(`${g}:*`); + if (!g && u) blockedSet.add(`*:${u}`); } // TTL 5 分钟 @@ -460,9 +690,9 @@ class InboxProcessorService extends Service { } // 3. 检查当前消息是否命中屏蔽规则 - if (groupName && userName && blockedSet.has(`${groupName}:${userName}`)) return true; - if (groupName && blockedSet.has(`${groupName}:*`)) return true; - if (userName && blockedSet.has(`*:${userName}`)) return true; + if (groupId && userId && blockedSet.has(`${groupId}:${userId}`)) return true; + if (groupId && blockedSet.has(`${groupId}:*`)) return true; + if (userId && blockedSet.has(`*:${userId}`)) return true; return false; } catch (error) { @@ -487,20 +717,20 @@ class InboxProcessorService extends Service { } /** - * 获取仓库 ApiApp 回调地址。 + * 获取仓库 ApiApp 回调配置(URL + 签名凭证)。 * * @param {number} warehouseId 仓库ID。 - * @return {Promise} 回调 URL,未配置时返回 null。 + * @return {Promise<{url: string|null, appKey: string|null, appSecret: string|null}>} */ - async getApiAppCallbackUrl(warehouseId) { + async getApiAppCallbackConfig(warehouseId) { const { ctx } = this; if (!Number.isFinite(warehouseId) || warehouseId <= 0) { - return null; + return { url: null, appKey: null, appSecret: null }; } try { const apiApp = await ctx.model.ApiApp.findOne({ - attributes: [ 'callback_url' ], + attributes: [ 'callback_url', 'self_app_key', 'self_app_secret' ], where: { warehouse_id: warehouseId, interface_type_id: WAREHOUSE_INTERFACE_TYPE_ID, @@ -509,13 +739,27 @@ class InboxProcessorService extends Service { raw: true, }); - return (apiApp && apiApp.callback_url) || null; + return { + url: (apiApp && apiApp.callback_url) || null, + appKey: (apiApp && apiApp.self_app_key) || null, + appSecret: (apiApp && apiApp.self_app_secret) || null, + }; } catch (error) { - ctx.logger.warn(`[inbox processor] 查询回调地址失败: ${error.message}`); - return null; + ctx.logger.warn(`[inbox processor] 查询回调配置失败: ${error.message}`); + return { url: null, appKey: null, appSecret: null }; } } + /** + * 获取仓库 ApiApp 回调地址(兼容旧调用)。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 回调 URL。 + */ + async getApiAppCallbackUrl(warehouseId) { + const config = await this.getApiAppCallbackConfig(warehouseId); + return config.url; + } + /** * 尝试从消息正文中提取仓库ID。 * 子类或业务方可覆盖此方法以实现自定义解析逻辑。 diff --git a/app/service/inbox/receiver.js b/app/service/inbox/receiver.js index b54acc1..4a7e279 100644 --- a/app/service/inbox/receiver.js +++ b/app/service/inbox/receiver.js @@ -146,6 +146,7 @@ class InboxReceiverService extends Service { store_id: storeId || null, source_type: sourceType, source_extra: data.source_extra || null, + ai_enabled: 0, }, }); } catch (groupErr) { diff --git a/app/service/qimenMethods/stockout.js b/app/service/qimenMethods/stockout.js index d7fa424..ff2875a 100644 --- a/app/service/qimenMethods/stockout.js +++ b/app/service/qimenMethods/stockout.js @@ -25,7 +25,7 @@ class stockoutServer extends MainService { * @return {Promise} 返回 success / fail 结果 */ async create(data) { - const { app, ctx, appKey, storeId, warehouseId, warehouseCode } = this; + const { app, ctx, storeId, warehouseId, warehouseCode } = this; const { deliveryOrder, orderLines } = data.request; // 单条 orderLine 转为数组 @@ -106,7 +106,7 @@ class stockoutServer extends MainService { remark: deliveryOrder.remark || null, warehouse_id: warehouseId, store_id: storeId, - qimen_owner_code: appKey, + qimen_owner_code: items[0].ownerCode, qimen_warehouse_code: warehouseCode, source_type: 'QM', created_at: new Date(), diff --git a/app/service/systemMethods/storage/stockout.js b/app/service/systemMethods/storage/stockout.js index c0d4f80..d91bd6f 100644 --- a/app/service/systemMethods/storage/stockout.js +++ b/app/service/systemMethods/storage/stockout.js @@ -4,7 +4,7 @@ const MainService = require('../../main'); /** * 系统方法层:storage.stockout(非订单出库单)。 - * 说明:该实现为最小可用能力,复用订单分表模型读取当前仓库的出库单与明细。 + * 说明:直接读写 wms_order_stockout + wms_order_stockout_items 表。 */ class StorageStockoutService extends MainService { constructor(ctx) { @@ -40,11 +40,11 @@ class StorageStockoutService extends MainService { const page = Math.max(Number(pagination.page) || 1, 1); const pageSize = Math.max(Number(pagination.pageSize) || 20, 1); const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; - const OrderDeliveryModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); + const OrderStockoutModel = ctx.model.OrderStockout; const andConditions = [ { warehouse_id: warehouseId }, - { delete_at: null }, + { deleted_at: null }, ]; const dynamicConditions = Array.isArray(parsed && parsed.dynamicConditions) ? parsed.dynamicConditions : []; @@ -60,23 +60,20 @@ class StorageStockoutService extends MainService { const keyword = String(quickValue).trim(); andConditions.push({ [Op.or]: [ - { delivery_order_code: { [Op.like]: `%${keyword}%` } }, - { source_order_codes: { [Op.like]: `%${keyword}%` } }, - { buyer_nick: { [Op.like]: `%${keyword}%` } }, - { mobile: { [Op.like]: `%${keyword}%` } }, - { name: { [Op.like]: `%${keyword}%` } }, + { stockout_order_code: { [Op.like]: `%${keyword}%` } }, + { remark: { [Op.like]: `%${keyword}%` } }, ], }); } const validSortFields = [ 'id', - 'delivery_order_code', - 'status', - 'outbound_status', + 'stockout_order_code', + 'order_status', + 'order_type', 'updated_at', - 'create_at', - 'delivery_time', + 'created_at', + 'order_create_time', ]; const sortField = validSortFields.includes(String(sort.sortField || '').trim()) ? String(sort.sortField).trim() @@ -84,7 +81,7 @@ class StorageStockoutService extends MainService { const sortOrder = String(sort.sortOrder || 'DESC').toUpperCase() === 'ASC' ? 'ASC' : 'DESC'; const finalWhere = { [Op.and]: andConditions }; - const { count, rows } = await OrderDeliveryModel.findAndCountAll({ + const { count, rows } = await OrderStockoutModel.findAndCountAll({ where: finalWhere, order: [[ sortField, sortOrder ], [ 'id', 'DESC' ]], limit: pageSize, @@ -117,33 +114,34 @@ class StorageStockoutService extends MainService { * 出库单明细查询。 * @param {Object} data 请求体 * @param {number} [data.id] 出库单ID - * @param {string} [data.delivery_order_code] 出库单号 + * @param {string} [data.stockout_order_code] 出库单号 * @return {Promise} 统一成功包装响应 */ async listItems(data = {}) { const { ctx } = this; const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; const id = Number(data.id || 0); - const deliveryOrderCode = String(data.delivery_order_code || '').trim(); + // 兼容 delivery_order_code 旧参数名 + const stockoutOrderCode = String(data.stockout_order_code || data.delivery_order_code || '').trim(); - if (!id && !deliveryOrderCode) { - return this.fail('id 或 delivery_order_code 至少传一个'); + if (!id && !stockoutOrderCode) { + return this.fail('id 或 stockout_order_code 至少传一个'); } - const OrderDeliveryModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); - const OrderItemsModel = await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId); + const OrderStockoutModel = ctx.model.OrderStockout; + const OrderStockoutItemsModel = ctx.model.OrderStockoutItems; const where = { warehouse_id: warehouseId, - delete_at: null, + deleted_at: null, }; if (id > 0) { where.id = id; } else { - where.delivery_order_code = deliveryOrderCode; + where.stockout_order_code = stockoutOrderCode; } - const order = await OrderDeliveryModel.findOne({ + const order = await OrderStockoutModel.findOne({ where, raw: true, }); @@ -155,7 +153,7 @@ class StorageStockoutService extends MainService { }); } - const list = await OrderItemsModel.findAll({ + const list = await OrderStockoutItemsModel.findAll({ where: { order_id: order.id, }, @@ -168,6 +166,232 @@ class StorageStockoutService extends MainService { list, }); } + + /** + * 出库单确认(直出)。 + * 不改变内部库存,直接按出库单明细的计划数量确认。 + * 出站同步 taobao.qimen.stockout.confirm 成功后,状态才推进到 COMPLETED。 + * 要求 express_code 已填写,否则拒绝确认。 + * @param {Object} data 请求体 + * @param {number} data.id 出库单ID(必填) + * @return {Promise} 统一成功/失败包装响应 + */ + async confirm(data = {}) { + const { ctx } = this; + const id = Number(data.id || 0); + + if (!id) { + return this.fail('缺少出库单ID'); + } + + const order = await ctx.model.OrderStockout.findByPk(id); + if (!order) { + return this.fail('出库单不存在'); + } + + if (!order.canConfirm || !order.canConfirm()) { + return this.fail(`出库单当前状态(${order.order_status})不允许确认`); + } + + // 校验运单号是否已填写 + if (!order.waybill_code) { + return this.fail('出库单未填写运单号(waybill_code),请先更新运单号后再确认'); + } + + // 第一步:事务内写入明细 actual_qty(暂不改变 order_status) + const transaction = await ctx.model.transaction(); + let items; + try { + items = await ctx.model.OrderStockoutItems.findAll({ + where: { order_id: id }, + transaction, + }); + + for (const item of items) { + await item.update({ + actual_qty: item.plan_qty, + updated_at: new Date(), + }, { transaction }); + } + + await transaction.commit(); + } catch (err) { + await transaction.rollback(); + ctx.logger.error('[stockout.confirm] 明细更新失败:', err); + return this.fail(`确认失败:${err.message}`); + } + + // 第二步:出站通知 ERP(taobao.qimen.stockout.confirm) + const { app } = this; + let qimenSuccess = false; + let qimenMessage = ''; + + if (app.qimenClient && order.qimen_owner_code && order.qimen_warehouse_code) { + try { + const now = app.formatDate(new Date()); + const waybillCodes = Array.isArray(order.waybill_codes) && order.waybill_codes.length > 0 + ? order.waybill_codes + : [ order.waybill_code ].filter(Boolean); + + const outboundData = { + deliveryOrder: { + totalOrderLines: order.total_order_lines, + deliveryOrderCode: order.stockout_order_code, + deliveryOrderId: order.id, + warehouseCode: order.qimen_warehouse_code, + orderType: order.order_type, + status: 'DELIVERED', + outBizCode: order.stockout_order_code, + confirmType: 0, + orderConfirmTime: now, + operatorCode: '', + operatorName: '', + }, + packages: { + package: waybillCodes.map(code => ({ + logisticsCode: order.express_code || 'OTHER', + logisticsName: order.express_name || 'OTHER', + expressCode: code, + packageCode: order.stockout_order_code, + items: items.map(item => ({ + itemCode: item.item_code || '', + itemId: item.item_id || '', + quantity: item.plan_qty || 0, + })), + })), + }, + orderLines: items.map(item => ({ + orderLineNo: item.order_line_no || '', + ownerCode: item.owner_code || order.qimen_owner_code, + itemCode: item.item_code || '', + itemId: item.item_id || '', + itemName: item.item_name || '', + planQty: item.plan_qty || 0, + actualQty: item.plan_qty || 0, + inventoryType: item.inventory_type || 'ZP', + })), + }; + + const sendResult = await app.qimenClient.send( + 'taobao.qimen.stockout.confirm', + order.qimen_owner_code, + outboundData, + { ctx } + ); + + // 解析奇门响应 + const response = (sendResult && sendResult.xmlArray && sendResult.xmlArray.response) + ? (Array.isArray(sendResult.xmlArray.response) ? sendResult.xmlArray.response[0] : sendResult.xmlArray.response) + : {}; + qimenSuccess = String(response.flag || '').trim() === 'success'; + qimenMessage = qimenSuccess ? '' : `${response.code || ''} ${response.message || '未知错误'}`.trim(); + } catch (outboundErr) { + qimenMessage = outboundErr.message || '出站通知异常'; + ctx.logger.error(`[stockout.confirm] 出站通知异常: ${qimenMessage}`); + } + } else { + ctx.logger.warn(`[stockout.confirm] 跳过出站通知: qimenClient=${!!app.qimenClient}, ownerCode=${order.qimen_owner_code}, warehouseCode=${order.qimen_warehouse_code}`); + } + + // 第三步:根据出站结果更新状态 + if (qimenSuccess) { + await ctx.model.OrderStockout.update( + { order_status: 'COMPLETED', sync_status: 'SUCCESS', sync_message: '', updated_at: new Date() }, + { where: { id: order.id } } + ); + ctx.logger.info(`[stockout.confirm] 确认完成: ${order.stockout_order_code}`); + + return this.success('确认成功', { + id: order.id, + stockout_order_code: order.stockout_order_code, + order_status: 'COMPLETED', + logisticsName: 'OTHER', + expressCode: order.express_code, + expressCodes: order.express_codes, + qimenSync: 'success', + }); + } + + // 出站失败:更新 sync_status,order_status 不变 + await ctx.model.OrderStockout.update( + { sync_status: 'FAILED', sync_message: qimenMessage, updated_at: new Date() }, + { where: { id: order.id } } + ); + ctx.logger.error(`[stockout.confirm] 出站同步失败: ${order.stockout_order_code} - ${qimenMessage}`); + + return this.fail(`出站同步失败: ${qimenMessage || '未发起出站通知'}`); + } + + /** + * 更新出库单快递和运单号。 + * 用于在确认前填写 express_code / waybill_code / waybill_codes。 + * express_code 传入后自动从系统快递表解析 express_name。 + * @param {Object} data 请求体 + * @param {number} data.id 出库单ID(必填) + * @param {string} [data.express_code] 快递公司编码(如 SF、STO),传入后自动解析 express_name + * @param {string} [data.waybill_code] 运单号 + * @param {string[]} [data.waybill_codes] 运单号列表 + * @return {Promise} 统一成功/失败包装响应 + */ + async updateExpress(data = {}) { + const { ctx } = this; + const id = Number(data.id || 0); + + if (!id) { + return this.fail('缺少出库单ID'); + } + + const order = await ctx.model.OrderStockout.findByPk(id); + if (!order) { + return this.fail('出库单不存在'); + } + + const updateData = { updated_at: new Date() }; + + // express_code:自动解析 express_name + if (data.express_code !== undefined) { + updateData.express_code = data.express_code || null; + if (data.express_code) { + try { + const expressMap = await ctx.service.systems.setting.express.getSystemExpressMap(); + const info = expressMap.get(String(data.express_code).trim().toUpperCase()); + updateData.express_name = info ? info.name : ''; + } catch (e) { + ctx.logger.warn('[updateExpress] 解析快递名称失败: ' + e.message); + updateData.express_name = ''; + } + } else { + updateData.express_name = null; + } + } + + if (data.waybill_code !== undefined) { + updateData.waybill_code = data.waybill_code || null; + } + if (data.waybill_codes !== undefined) { + const codes = data.waybill_codes; + if (codes !== null && !Array.isArray(codes)) { + return this.fail('waybill_codes 必须是数组或 null'); + } + updateData.waybill_codes = codes; + } + + if (Object.keys(updateData).length <= 1) { + return this.fail('没有需要更新的字段'); + } + + await order.update(updateData); + await order.reload(); + + return this.success('更新成功', { + id: order.id, + stockout_order_code: order.stockout_order_code, + express_code: order.express_code, + express_name: order.express_name, + waybill_code: order.waybill_code, + waybill_codes: order.waybill_codes, + }); + } } module.exports = StorageStockoutService; diff --git a/app/service/systems/apiApp.js b/app/service/systems/apiApp.js index c5b7042..1613a90 100644 --- a/app/service/systems/apiApp.js +++ b/app/service/systems/apiApp.js @@ -149,9 +149,7 @@ class ApiAppService extends Service { self_ip_whitelist: Array.isArray(data.self_ip_whitelist) ? data.self_ip_whitelist : null, callback_url: String(data.callback_url || '').trim() || null, rate_limit: Number(data.rate_limit) || 1000, - sign_method: [ 'md5', 'hmac', 'sha256' ].includes(String(data.sign_method || '').trim()) - ? String(data.sign_method).trim() - : 'md5', + sign_method: 'md5', is_enabled: 1, }; @@ -209,11 +207,7 @@ class ApiAppService extends Service { for (const field of updatableFields) { if (data[field] !== undefined && data[field] !== null) { if (field === 'sign_method') { - const val = String(data[field]).trim(); - if (![ 'md5', 'hmac', 'sha256' ].includes(val)) { - throw new Error('签名方法仅支持 md5/hmac/sha256'); - } - record[field] = val; + throw new Error('签名方法当前仅支持 md5,不允许修改'); } else if (field === 'is_enabled') { record[field] = Number(data[field]); } else if (field === 'rate_limit') { diff --git a/app/service/systems/express_platform.js b/app/service/systems/express_platform.js index a2d3907..cb382d0 100644 --- a/app/service/systems/express_platform.js +++ b/app/service/systems/express_platform.js @@ -704,8 +704,8 @@ class ExpressPlatformService extends MainService { console.log('order', order); const expressListItem = ExpressList.find(item => item.code === listByWarehousePlatformCode.sys_express_code) || {}; let playload = { - object_Id: `${order.warehouse_id}_${order.id}_${order_tmp.business_key}`, // 菠萝派平台要求订单唯一标识必须为字符串 - orderno: `${order.warehouse_id}_${order.id}_${order_tmp.business_key}`, // 菠萝派平台要求订单号必须为字符串 + object_Id: `${order.warehouse_id.toString(16)}_${order.id}_${order_tmp.business_key}`, // 菠萝派平台要求订单唯一标识必须为字符串 + orderno: `${order.warehouse_id.toString(16)}_${order.id}_${order_tmp.business_key}`, // 菠萝派平台要求订单号必须为字符串 plattradeno: listByWarehousePlatformCode.platform_code === 'DY' && order.from_key === 23060081 && !!order.pay_no ? order.pay_no : order.source_order_codes || order.delivery_order_code || '', ismultiplepieces: order.package_count > 1 ? 1 : 0, logisticno: allocatedWaybillMap.get(`${Number(order.id) || 0}:${Number(order_tmp.business_key) || 0}`) || '', @@ -1007,7 +1007,8 @@ class ExpressPlatformService extends MainService { switch (listByWarehousePlatformCode.platform_code) { case 'KS': successUpdates = (result.results || []).map(item => { - const [ warehouse_id, order_id, business_key ] = String(item.orderno || '').split('_'); + const [ warehouse_id_hex, order_id, business_key ] = String(item.orderno || '').split('_'); + const warehouse_id = parseInt(warehouse_id_hex, 16); const waybillCode = resolveWaybillCode(item); return { warehouse_id, @@ -1042,7 +1043,9 @@ class ExpressPlatformService extends MainService { break; case 'DY': successUpdates = (result.results || []).map(item => { - const [ warehouse_id, order_id, business_key ] = String(item.orderno || '').split('_'); + const [ warehouse_id_hex, order_id, business_key ] = String(item.orderno || '').split('_'); + const warehouse_id = parseInt(warehouse_id_hex, 16); + const waybillCode = resolveWaybillCode(item); return { warehouse_id, @@ -1142,7 +1145,8 @@ class ExpressPlatformService extends MainService { successUpdates = (batchPrintResult && batchPrintResult.results || []).map(item => { const objectId = String(item && item.orderno || '').trim(); - const [ warehouse_id, order_id, business_key ] = objectId.split('_'); + const [ warehouse_id_hex, order_id, business_key ] = objectId.split('_'); + const warehouse_id = parseInt(warehouse_id_hex, 16); const waybillCode = String(item && (item.logisticno || item.waybill_code) || '').trim(); const rawPrintData = item && Object.prototype.hasOwnProperty.call(item, 'printdata') ? item.printdata @@ -1193,7 +1197,8 @@ class ExpressPlatformService extends MainService { } case 'XHS':{ successUpdates = (result.results || []).map(item => { - const [ warehouse_id, order_id, business_key ] = String(item.orderno || '').split('_'); + const [ warehouse_id_hex, order_id, business_key ] = String(item.orderno || '').split('_'); + const warehouse_id = parseInt(warehouse_id_hex, 16); const waybillCode = resolveWaybillCode(item); const printInfo = item.print_info ?? item.printinfo; return { @@ -1235,7 +1240,8 @@ class ExpressPlatformService extends MainService { if (!objectId || objectIdParts.length < 3) { throw new Error(`视频号取号返回 object_id 无法解析: ${objectId || JSON.stringify(item)}`); } - const [ warehouse_id, order_id, business_key ] = objectIdParts; + const [ warehouse_id_hex, order_id, business_key ] = objectIdParts; + const warehouse_id = parseInt(warehouse_id_hex, 16); const waybillCode = resolveWaybillCode(item); const rawPrintData = item && Object.prototype.hasOwnProperty.call(item, 'raw') ? item.raw diff --git a/app/service/systems/upload.js b/app/service/systems/upload.js index 0dbf547..ba971f6 100644 --- a/app/service/systems/upload.js +++ b/app/service/systems/upload.js @@ -282,8 +282,8 @@ class UploadService extends Service { .replace('{filemd5}', md5) .replace('{.suffix}', ext); - // 添加目录前缀并规范化路径 - const fullPath = path.posix.join(result).replace(/\/\//g, '/'); + // 添加目录前缀并规范化路径,去除前导 / 防止与 CDN 域名拼接时产生 // + const fullPath = path.posix.join(result).replace(/\/\//g, '/').replace(/^\/+/, ''); return fullPath; } @@ -439,7 +439,7 @@ class UploadService extends Service { this.ctx.logger.warn('上传成功通知缺少用户信息,使用默认值'); } - const resolvedFileKey = String(data.url || data.fileKey || ''); + const resolvedFileKey = String(data.url || data.fileKey || '').replace(/^\/+/, ''); const resolvedFileName = String(data.fileName || data.name || path.basename(resolvedFileKey || 'file')); const resolvedFileSize = Number(data.fileSize || data.size || 0); diff --git a/app/service/warehouse.js b/app/service/warehouse.js index 701d20e..0b21fbe 100644 --- a/app/service/warehouse.js +++ b/app/service/warehouse.js @@ -193,6 +193,8 @@ class WarehouseService extends Service { code: 400, message: '参数缺失或错误: method/v/timestamp', data: null, + warehouseId: null, + appKey: String(query.app_key || '').trim() || null, }; } @@ -206,12 +208,18 @@ class WarehouseService extends Service { code: 400, message: `时间戳已过期或无效,服务器时间: ${nowTs}`, data: null, + warehouseId: null, + appKey: String(query.app_key || '').trim() || null, }; } const body = await this.parseJsonBody(); if (body && body.ok === false) { - return body; + return { + ...body, + warehouseId: null, + appKey: String(query.app_key || '').trim() || null, + }; } const { appKey, providedSign } = this.normalizeSignFields(query); @@ -222,6 +230,8 @@ class WarehouseService extends Service { code: 400, message: '参数缺失或错误: app_key', data: null, + warehouseId: null, + appKey: null, }; } @@ -244,6 +254,8 @@ class WarehouseService extends Service { code: 401, message: `签名校验失败: ${verifyResult.message}`, data: null, + warehouseId: null, + appKey, }; } @@ -256,6 +268,8 @@ class WarehouseService extends Service { code: 403, message: 'API 应用未绑定仓库', data: null, + warehouseId: null, + appKey: verifyResult.appKey, }; } @@ -264,10 +278,16 @@ class WarehouseService extends Service { app_key: verifyResult.appKey, }; - return await this.dispatchWarehouseMethod(query.method, body, queryWithAppKey, { + const dispatchResult = await this.dispatchWarehouseMethod(query.method, body, queryWithAppKey, { warehouseId, appKey: verifyResult.appKey, }); + + return { + ...dispatchResult, + warehouseId, + appKey: verifyResult.appKey, + }; } } diff --git a/app/service/warehouseMethods/inbox.js b/app/service/warehouseMethods/inbox.js index 23c7fa9..5de365b 100644 --- a/app/service/warehouseMethods/inbox.js +++ b/app/service/warehouseMethods/inbox.js @@ -38,7 +38,7 @@ class WarehouseInboxService extends MainService { warehouse_id: warehouseId, direction: 'inbound', parent_id: body.parentId || null, - source_type: body.sourceType || 'api', + source_type: 'api', source_extra: String(appKey || ''), target_type: body.targetType || 'im', group_name: body.groupName || null, diff --git a/config/config.default.js b/config/config.default.js index 7e1a222..9561698 100644 --- a/config/config.default.js +++ b/config/config.default.js @@ -52,6 +52,12 @@ module.exports = appInfo => { apiKey: process.env.DEEPSEEK_API_KEY || '', baseUrl: 'https://api.deepseek.com', }; + + // 站内信模块配置 + config.inbox = { + imageBaseUrl: '', // 商品图片域名,为空时用请求 ctx.host + }; + config.tencentCloud = { ...tencentCloudConfig, }; @@ -61,16 +67,16 @@ module.exports = appInfo => { region: 'ap-guangzhou', uploadurl: 'https://ye4s-1255377868.cos.ap-guangzhou.myqcloud.com', cdnurl: 'https://ye4s.file.gzxunren.com', - savekey: '/{warehouseId}/{dir}/{year}{mon}{day}/{filemd5}{.suffix}', + savekey: '{warehouseId}/{dir}/{year}{mon}{day}/{filemd5}{.suffix}', expire: 600, maxsize: '100M', mimetype: 'jpg,png,bmp,jpeg,gif,zip,rar,xls,xlsx,apk', apiupload: 1, dirs: { - image: '/images/', - document: '/documents/', - apk: '/apks/', - temp: '/temp/', // 临时文件目录 + image: 'images/', + document: 'documents/', + apk: 'apks/', + temp: 'temp/', // 临时文件目录 }, }; config.fileWriter = { diff --git a/database/migrations/20260806200000-create-wms-warehouse-log.js b/database/migrations/20260806200000-create-wms-warehouse-log.js new file mode 100644 index 0000000..3d9573e --- /dev/null +++ b/database/migrations/20260806200000-create-wms-warehouse-log.js @@ -0,0 +1,108 @@ +'use strict'; + +/** + * 创建仓库开放 API 请求日志表。 + * 记录 /warehouse 入口的每次请求:app_key、method、warehouse_id、 + * 请求体、响应体、HTTP 状态码、耗时等。 + */ +module.exports = { + up: async (queryInterface, Sequelize) => { + const { STRING, INTEGER, BIGINT, TEXT, DATE } = Sequelize; + + await queryInterface.createTable('wms_warehouse_log', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '自增主键', + }, + log_id: { + type: STRING(32), + allowNull: false, + unique: true, + comment: '日志唯一ID(WL-{timestamp}-{random})', + }, + app_key: { + type: STRING(64), + allowNull: true, + comment: 'API 应用 AppKey', + }, + method: { + type: STRING(100), + allowNull: true, + comment: '请求方法名(如 inbox.push)', + }, + warehouse_id: { + type: INTEGER(10), + allowNull: true, + comment: '仓库 ID', + }, + url: { + type: TEXT, + allowNull: true, + comment: '请求 URL', + }, + http_status: { + type: INTEGER(5), + allowNull: true, + comment: 'HTTP 状态码', + }, + body: { + type: TEXT('long'), + allowNull: true, + comment: '请求体(最大 65535 字符)', + }, + result: { + type: TEXT('long'), + allowNull: true, + comment: '响应体(最大 65535 字符)', + }, + use_time: { + type: INTEGER(12), + allowNull: true, + comment: '耗时(毫秒)', + }, + created_at: { + type: DATE, + allowNull: true, + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: true, + comment: '更新时间', + }, + }); + + // 索引 + await queryInterface.addIndex('wms_warehouse_log', { + name: 'uk_log_id', + unique: true, + fields: [ 'log_id' ], + }); + + await queryInterface.addIndex('wms_warehouse_log', { + name: 'idx_app_key', + fields: [ 'app_key' ], + }); + + await queryInterface.addIndex('wms_warehouse_log', { + name: 'idx_method', + fields: [ 'method' ], + }); + + await queryInterface.addIndex('wms_warehouse_log', { + name: 'idx_warehouse_id', + fields: [ 'warehouse_id' ], + }); + + await queryInterface.addIndex('wms_warehouse_log', { + name: 'idx_created_at', + fields: [ 'created_at' ], + }); + }, + + down: async queryInterface => { + await queryInterface.dropTable('wms_warehouse_log'); + }, +}; diff --git a/database/migrations/20260807100000-change-ai-enabled-default-to-0.js b/database/migrations/20260807100000-change-ai-enabled-default-to-0.js new file mode 100644 index 0000000..c5ebcf7 --- /dev/null +++ b/database/migrations/20260807100000-change-ai-enabled-default-to-0.js @@ -0,0 +1,27 @@ +'use strict'; + +const TABLE_NAME = 'wms_inbox_group'; + +/** + * 修改 ai_enabled 默认值从 1 改为 0。 + * 新创建的群默认关闭 AI 自动回复,需管理员手动开启。 + */ +module.exports = { + up: async (queryInterface, Sequelize) => { + await queryInterface.changeColumn(TABLE_NAME, 'ai_enabled', { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 0, + comment: '是否启用AI自动回复: 0=关闭 1=开启', + }); + }, + + down: async (queryInterface, Sequelize) => { + await queryInterface.changeColumn(TABLE_NAME, 'ai_enabled', { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 1, + comment: '是否启用AI自动回复: 0=关闭 1=开启', + }); + }, +}; diff --git a/database/migrations/20260807110000-switch-inbox-block-to-ids.js b/database/migrations/20260807110000-switch-inbox-block-to-ids.js new file mode 100644 index 0000000..2033b23 --- /dev/null +++ b/database/migrations/20260807110000-switch-inbox-block-to-ids.js @@ -0,0 +1,83 @@ +'use strict'; + +const TABLE_NAME = 'wms_inbox_block'; + +/** + * 将屏蔽表从 group_name/user_name 切换为 group_id/user_id + warehouse_id。 + * 群名称和用户名可能变更或含特殊字符,改用稳定ID。 + */ +module.exports = { + up: async (queryInterface, Sequelize) => { + // 1. 新增 warehouse_id(不允许为空,给历史数据默认值 0) + const cols = await queryInterface.describeTable(TABLE_NAME); + if (!cols.warehouse_id) { + await queryInterface.addColumn(TABLE_NAME, 'warehouse_id', { + type: Sequelize.INTEGER(10), + allowNull: false, + defaultValue: 0, + comment: '仓库ID', + }); + } + + // 2. 新增 group_id + if (!cols.group_id) { + await queryInterface.addColumn(TABLE_NAME, 'group_id', { + type: Sequelize.STRING(100), + allowNull: true, + comment: '群ID', + }); + } + + // 3. 新增 user_id + if (!cols.user_id) { + await queryInterface.addColumn(TABLE_NAME, 'user_id', { + type: Sequelize.STRING(100), + allowNull: true, + comment: '用户ID', + }); + } + + // 4. 检查是否已有旧列,有则删除 + const colsAfter = await queryInterface.describeTable(TABLE_NAME); + if (colsAfter.group_name) { + await queryInterface.removeColumn(TABLE_NAME, 'group_name'); + } + if (colsAfter.user_name) { + await queryInterface.removeColumn(TABLE_NAME, 'user_name'); + } + + // 5. 添加唯一索引 + await queryInterface.addIndex(TABLE_NAME, { + name: 'uk_warehouse_group_user', + unique: true, + fields: [ 'warehouse_id', 'group_id', 'user_id' ], + }); + }, + + down: async (queryInterface, Sequelize) => { + // 回滚:恢复旧列 + const cols = await queryInterface.describeTable(TABLE_NAME); + if (!cols.group_name) { + await queryInterface.addColumn(TABLE_NAME, 'group_name', { + type: Sequelize.STRING(100), + allowNull: true, + comment: '群名称', + }); + } + if (!cols.user_name) { + await queryInterface.addColumn(TABLE_NAME, 'user_name', { + type: Sequelize.STRING(100), + allowNull: true, + comment: '用户名称', + }); + } + + // 删除新列 + if (cols.group_id) await queryInterface.removeColumn(TABLE_NAME, 'group_id'); + if (cols.user_id) await queryInterface.removeColumn(TABLE_NAME, 'user_id'); + if (cols.warehouse_id) await queryInterface.removeColumn(TABLE_NAME, 'warehouse_id'); + + // 删除唯一索引 + await queryInterface.removeIndex(TABLE_NAME, 'uk_warehouse_group_user'); + }, +}; diff --git a/database/migrations/20260807120000-add-express-code-to-wms-order-stockout.js b/database/migrations/20260807120000-add-express-code-to-wms-order-stockout.js new file mode 100644 index 0000000..bace1e7 --- /dev/null +++ b/database/migrations/20260807120000-add-express-code-to-wms-order-stockout.js @@ -0,0 +1,44 @@ +'use strict'; + +const TABLE = 'wms_order_stockout'; + +/** + * 为出库单主表添加运单号字段。 + * + * - express_code:回传运单号(单个),奇门 stockout.confirm 回传时使用,为空则拒绝确认 + * - express_codes:运单号列表(JSON 数组),支持多包裹场景 + */ +module.exports = { + up: async (queryInterface, Sequelize) => { + const columns = await queryInterface.describeTable(TABLE); + + if (!columns.express_code) { + await queryInterface.addColumn(TABLE, 'express_code', { + type: Sequelize.STRING(50), + allowNull: true, + comment: '回传运单号(奇门 stockout.confirm 回传使用,为空则拒绝确认)', + }); + } + + if (!columns.express_codes) { + await queryInterface.addColumn(TABLE, 'express_codes', { + type: Sequelize.JSON, + allowNull: true, + comment: '运单号列表(JSON 数组,支持多包裹场景)', + }); + } + }, + + down: async (queryInterface) => { + const columns = await queryInterface.describeTable(TABLE); + + if (columns.express_code) { + await queryInterface.removeColumn(TABLE, 'express_code'); + } + + if (columns.express_codes) { + await queryInterface.removeColumn(TABLE, 'express_codes'); + } + }, +}; + diff --git a/database/migrations/20260807130000-add-stockout-api-permissions.js b/database/migrations/20260807130000-add-stockout-api-permissions.js new file mode 100644 index 0000000..1dcb27c --- /dev/null +++ b/database/migrations/20260807130000-add-stockout-api-permissions.js @@ -0,0 +1,84 @@ +'use strict'; + +/** + * 为 storage.stockout.* 添加 API 权限并授权。 + * + * 权限 ID(固定): + * 504 — storage.stockout.list 出库单列表 + * 505 — storage.stockout.listItems 出库单明细 + * 506 — storage.stockout.confirm 出库单确认 + * 507 — storage.stockout.updateExpress 更新运单号 + * + * 授权角色:经理(8)、仓库组-主管(26)、客服组-主管(28)、生产组-主管(29)、客服组-员工(30) + */ +module.exports = { + up: async (queryInterface) => { + // ===== 第一步:写入权限行 ===== + const perms = [ + [504, 'storage.stockout.list', '出库单列表'], + [505, 'storage.stockout.listItems', '出库单明细'], + [506, 'storage.stockout.confirm', '出库单确认'], + [507, 'storage.stockout.updateExpress', '更新运单号'], + ]; + + for (const [id, method, desc] of perms) { + await queryInterface.sequelize.query(` + INSERT INTO wms_permission (id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at) + VALUES (${id}, '${method}', NULL, '${method}', NULL, 'API:${desc}', NULL, 0, 0, NULL, 'api', 0, 1, NOW(), NOW()) + ON DUPLICATE KEY UPDATE path='${method}', meta_title='API:${desc}', type='api' + `); + } + + // ===== 第二步:授权给客服组员工及以上角色 ===== + const roleIds = [8, 26, 28, 29, 30]; // 经理 + 各主管 + 客服组-员工 + const newPermIds = [504, 505, 506, 507]; + + for (const roleId of roleIds) { + for (const permId of newPermIds) { + await queryInterface.sequelize.query(` + UPDATE wms_role + SET permissions = JSON_ARRAY_APPEND(permissions, '$', CAST(${permId} AS UNSIGNED)), + updated_at = NOW() + WHERE id = ${roleId} + AND permissions IS NOT NULL + AND permissions != '*' + AND permissions != '[]' + AND JSON_VALID(permissions) = 1 + AND JSON_CONTAINS(permissions, '${permId}', '$') = 0 + `); + } + } + }, + + down: async (queryInterface) => { + // 移除授权 + const roleIds = [8, 26, 28, 29, 30]; + const permIdStr = '504, 505, 506, 507'; + + for (const roleId of roleIds) { + await queryInterface.sequelize.query(` + UPDATE wms_role + SET permissions = JSON_REMOVE( + JSON_REMOVE( + JSON_REMOVE( + JSON_REMOVE(permissions, JSON_UNQUOTE(JSON_SEARCH(permissions, 'one', '504'))), + JSON_UNQUOTE(JSON_SEARCH(permissions, 'one', '505')) + ), + JSON_UNQUOTE(JSON_SEARCH(permissions, 'one', '506')) + ), + JSON_UNQUOTE(JSON_SEARCH(permissions, 'one', '507')) + ), + updated_at = NOW() + WHERE id = ${roleId} + AND permissions IS NOT NULL + AND permissions != '*' + AND permissions != '[]' + `); + } + + // 删除权限行 + await queryInterface.sequelize.query(` + DELETE FROM wms_permission WHERE id IN (504, 505, 506, 507) + `); + }, +}; diff --git a/database/migrations/20260807140000-add-express-name-waybill-to-wms-order-stockout.js b/database/migrations/20260807140000-add-express-name-waybill-to-wms-order-stockout.js new file mode 100644 index 0000000..b9c4912 --- /dev/null +++ b/database/migrations/20260807140000-add-express-name-waybill-to-wms-order-stockout.js @@ -0,0 +1,56 @@ +'use strict'; + +const TABLE = 'wms_order_stockout'; + +/** + * 拆分运单号字段: + * - express_code 保持为快递公司编码(如 SF、STO) + * - 新增 express_name:快递公司名称(如 顺丰、申通) + * - 新增 waybill_code:单个运单号 + * - 新增 waybill_codes:运单号列表(JSON 数组) + */ +module.exports = { + up: async (queryInterface, Sequelize) => { + const columns = await queryInterface.describeTable(TABLE); + + if (!columns.express_name) { + await queryInterface.addColumn(TABLE, 'express_name', { + type: Sequelize.STRING(200), + allowNull: true, + comment: '快递公司名称(由 express_code 自动解析)', + }); + } + + if (!columns.waybill_code) { + await queryInterface.addColumn(TABLE, 'waybill_code', { + type: Sequelize.STRING(50), + allowNull: true, + comment: '运单号', + }); + } + + if (!columns.waybill_codes) { + await queryInterface.addColumn(TABLE, 'waybill_codes', { + type: Sequelize.JSON, + allowNull: true, + comment: '运单号列表(JSON 数组,支持多包裹场景)', + }); + } + }, + + down: async (queryInterface) => { + const columns = await queryInterface.describeTable(TABLE); + + if (columns.express_name) { + await queryInterface.removeColumn(TABLE, 'express_name'); + } + + if (columns.waybill_code) { + await queryInterface.removeColumn(TABLE, 'waybill_code'); + } + + if (columns.waybill_codes) { + await queryInterface.removeColumn(TABLE, 'waybill_codes'); + } + }, +}; diff --git a/methods/changes/qimen.json b/methods/changes/qimen.json index c744a7b..11cfe45 100644 --- a/methods/changes/qimen.json +++ b/methods/changes/qimen.json @@ -53,5 +53,21 @@ "文档与代码实现(qimenMethods/stockout.js query 方法)对齐" ], "type": "updated" + }, + { + "version": "2026.08.07-stockout-confirm-01", + "date": "2026-08-07", + "summary": "stockout.confirm 从入站改为出站:确认后由 WMS 出站调用 taobao.qimen.stockout.confirm 通知 ERP", + "methods": [ + "stockout.confirm" + ], + "notes": [ + "移除 qimenMethods/stockout.js 中错误的入站 confirm 方法(stockout.confirm 是出站而非入站)", + "storage.stockout.confirm 确认后通过 qimenClient.send() 出站调用 taobao.qimen.stockout.confirm", + "出站 payload 包含 deliveryOrder/packages/orderLines,logisticsCode=OTHER", + "qimen.json 移除 stockout.confirm 入站条目" + ], + "type": "changed", + "module": "stockout" } ] diff --git a/methods/changes/system.json b/methods/changes/system.json index 11f208f..6879912 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,54 @@ [ + { + "version": "2026.08.07-stockout-express", + "date": "2026-08-07", + "type": "changed", + "summary": "wms_order_stockout 表新增 express_code / express_codes 字段;storage.stockout.confirm 改为读表字段回传,不再随机生成;新增 storage.stockout.updateExpress 接口。", + "methods": [ + "storage.stockout.confirm", + "storage.stockout.updateExpress" + ], + "notes": [ + "DB 迁移:20260807120000-add-express-code-to-wms-order-stockout.js 添加 express_code VARCHAR(50) 和 express_codes JSON 字段。", + "Model:order_stockout.js 新增 express_code / express_codes 字段定义。", + "storage.stockout.confirm:回传时不再随机生成 expressCode,改为读取表中 express_code / express_codes;express_code 为空则拒绝确认(400)。", + "storage.stockout.updateExpress:新增接口,用于在确认前更新运单号,支持 express_code(单个)和 express_codes(列表)两个字段。", + "qimenMethods/stockout.js confirm 同步调整,透传 expressCodes。" + ], + "module": "storage" + }, + { + "version": "2026.08.07-stockout-confirm", + "date": "2026-08-07", + "type": "added", + "summary": "新增 storage.stockout.confirm 直出确认接口:不改变内部库存,按出库单明细计划数量直接确认,状态推进到 COMPLETED。", + "methods": [ + "storage.stockout.confirm" + ], + "notes": [ + "入参:id(出库单ID,必填)。", + "逻辑:校验 canConfirm (CREATED/PENDING) → 事务内更新 order_status=COMPLETED、actual_qty=plan_qty。", + "返回:id、stockout_order_code、order_status、logisticsName(固定OTHER)、expressCode(随机生成)。", + "对应奇门 stockout.confirm 接口,由 qimenMethods/stockout.js confirm 方法调用。" + ], + "module": "storage" + }, + { + "version": "2026.08.07-stockout-list-fix", + "date": "2026-08-07", + "type": "changed", + "summary": "修复 storage.stockout.list / listItems 读错表:从 OrderDeliveryFactory/OrderItemsFactory 改为直接读取 OrderStockout/OrderStockoutItems 模型(wms_order_stockout 表)。", + "methods": [ + "storage.stockout.list", + "storage.stockout.listItems" + ], + "notes": [ + "list:数据源 OrderDeliveryFactory → OrderStockout;软删字段 delete_at → deleted_at;快速搜索字段适配 stockout_order_code/remark;排序字段适配 order_status/order_type/created_at/order_create_time。", + "listItems:数据源 OrderDeliveryFactory+OrderItemsFactory → OrderStockout+OrderStockoutItems;参数 delivery_order_code → stockout_order_code(兼容旧参数名)。", + "response 字段 items → list,与实际返回一致。" + ], + "module": "storage" + }, { "version": "2026.08.06-inbox-bindCode", "date": "2026-08-06", @@ -5348,5 +5398,22 @@ "task 对象新增 wave_no(string)字段,位于 task_no 之后;查询失败时降级为空字符串。", "数据来源:wms_wave_pick_task_wave INNER JOIN wms_wave_batch ON wave_id。" ] + }, + { + "version": "2026-08-06", + "date": "2026-08-06", + "summary": "sign_method 收紧为仅支持 md5:create 固定为 md5 不可选,update 不允许修改 sign_method,list/detail 响应描述同步更新", + "methods": [ + "apiApp.list", + "apiApp.detail", + "apiApp.create", + "apiApp.update" + ], + "notes": [ + "验证确认 /openapi 和 /warehouse 实际只使用 MD5 签名算法", + "apiApp.create: 删除 sign_method 入参,硬编码为 md5", + "apiApp.update: sign_method 字段改为不可修改,传入即报错", + "apiApp.list / apiApp.detail: sign_method 响应描述更新为「当前仅支持 md5」" + ] } ] diff --git a/methods/changes/warehouse.json b/methods/changes/warehouse.json index 7a8c0f5..59ca781 100644 --- a/methods/changes/warehouse.json +++ b/methods/changes/warehouse.json @@ -1,41 +1,68 @@ [ - { - "version": "2026.08.01-warehouse-01", - "date": "2026-08-01", - "type": "added", - "summary": "新增 /warehouse 仓库开放 API 入口,支持仓库级外部适配器 HMAC-SHA256 签名鉴权调用,首批上线 index.ping 心跳 + store.list 货主列表", - "methods": [ - "index.ping", - "store.list" - ], - "notes": [ - "POST /warehouse 为新增入口,独立于 /openapi(货主级),鉴权使用 interface_type_id=3 的仓库 API 应用(由 apiApp 模块管理)。", - "签名算法与 /openapi 完全一致:query 参数字典序 + body 拼接 → HMAC-SHA256 → hex。", - "时间戳 ±10 分钟有效期,Redis 缓存 API 应用配置 300 秒(缓存前缀 warehouse:api-app)。", - "无需 StoreWarehouse 合约关联,直接通过 api_app.warehouse_id 确定仓库上下文。", - "index.ping:无需 body 参数,返回 warehouse_id / app_key / server_time / status。", - "store.list:分页查询当前仓库下已授权的货主,通过 wms_store_warehouse 关联 wms_store,仅返回 auth_status=2 + store.status=1 + warehouse_use_status=1 的记录。", - "api_sign.js 改造:getApiAppConfigByAppKey 新增 interfaceTypeId 参数(默认 2 保持向后兼容),warehouse 入口传 3,查询增加 interface_type_id 条件并返回 warehouse_id。" - ], - "module": "warehouse" - }, - { - "version": "2026.08.03-warehouse-01", - "date": "2026-08-03", - "type": "added", - "summary": "新增仓库开放 API 站内信模块 inbox.push,支持外部系统将消息推入仓库站内信,WMS 异步转发到目标渠道(IM/API/webhook)", - "methods": [ - "inbox.push" - ], - "notes": [ - "POST /warehouse?method=inbox.push,interface_type_id=3(仓库侧),使用 MD5 签名鉴权", - "warehouse_id 由验签后上下文注入,禁止外部传入(安全边界)", - "ext_id 格式:api:{appKey}:{requestId},用于幂等去重", - "target_url 仅允许 https://,禁止内网 IP(SSRF 防护)", - "推送 body 大小限制 64KB", - "异步推送使用 setImmediate,不阻塞响应;失败指数退避重试(30s→60s→120s,最多3次)", - "路由到 app/service/warehouseMethods/inbox.push → app/service/inbox/receiver.receive" - ], - "module": "inbox" - } + { + "version": "2026.08.01-warehouse-01", + "date": "2026-08-01", + "type": "added", + "summary": "新增 /warehouse 仓库开放 API 入口,支持仓库级外部适配器 HMAC-SHA256 签名鉴权调用,首批上线 index.ping 心跳 + store.list 货主列表", + "methods": [ + "index.ping", + "store.list" + ], + "notes": [ + "POST /warehouse 为新增入口,独立于 /openapi(货主级),鉴权使用 interface_type_id=3 的仓库 API 应用(由 apiApp 模块管理)。", + "签名算法与 /openapi 完全一致:query 参数字典序 + body 拼接 → HMAC-SHA256 → hex。", + "时间戳 ±10 分钟有效期,Redis 缓存 API 应用配置 300 秒(缓存前缀 warehouse:api-app)。", + "无需 StoreWarehouse 合约关联,直接通过 api_app.warehouse_id 确定仓库上下文。", + "index.ping:无需 body 参数,返回 warehouse_id / app_key / server_time / status。", + "store.list:分页查询当前仓库下已授权的货主,通过 wms_store_warehouse 关联 wms_store,仅返回 auth_status=2 + store.status=1 + warehouse_use_status=1 的记录。", + "api_sign.js 改造:getApiAppConfigByAppKey 新增 interfaceTypeId 参数(默认 2 保持向后兼容),warehouse 入口传 3,查询增加 interface_type_id 条件并返回 warehouse_id。" + ], + "module": "warehouse" + }, + { + "version": "2026.08.03-warehouse-01", + "date": "2026-08-03", + "type": "added", + "summary": "新增仓库开放 API 站内信模块 inbox.push,支持外部系统将消息推入仓库站内信,WMS 异步转发到目标渠道(IM/API/webhook)", + "methods": [ + "inbox.push" + ], + "notes": [ + "POST /warehouse?method=inbox.push,interface_type_id=3(仓库侧),使用 MD5 签名鉴权", + "warehouse_id 由验签后上下文注入,禁止外部传入(安全边界)", + "ext_id 格式:api:{appKey}:{requestId},用于幂等去重", + "target_url 仅允许 https://,禁止内网 IP(SSRF 防护)", + "推送 body 大小限制 64KB", + "异步推送使用 setImmediate,不阻塞响应;失败指数退避重试(30s→60s→120s,最多3次)", + "路由到 app/service/warehouseMethods/inbox.push → app/service/inbox/receiver.receive" + ], + "module": "inbox" + }, + { + "version": "2026-08-06", + "date": "2026-08-06", + "summary": "inbox.push 文档同步代码现状:移除废弃参数 sourceChannel/targetChannel/storeId,补齐缺失参数 groupId/groupName/userId/userName/content,更新错误码与描述", + "methods": [ + "inbox.push" + ], + "notes": [ + "移除 sourceChannel / targetChannel / storeId 参数(代码中不存在)", + "补齐 groupId / groupName / userId / userName / content 参数", + "移除 targetChannel/targetUrl 相关错误码", + "新增 parent_id 校验、消息体 64KB 限制错误码", + "ext_id 自动组合为 api:{appKey}:{requestId}" + ] + }, + { + "version": "2026-08-07", + "date": "2026-08-07", + "summary": "inbox.push: source_type 硬编码为 api,移除 sourceType 入参(仓库 API 入站来源固定为 api,无需外部传入)", + "methods": [ + "inbox.push" + ], + "notes": [ + "source_type 从 body.sourceType || 'api' 改为硬编码 'api'", + "文档移除 sourceType 参数,description 补注 source_type 固定为 api" + ] + } ] diff --git a/methods/inbox-callback.json b/methods/inbox-callback.json new file mode 100644 index 0000000..dd745ac --- /dev/null +++ b/methods/inbox-callback.json @@ -0,0 +1,261 @@ +{ + "module": "inbox-callback", + "description": "站内信模块出站回调定义。WMS 处理入站消息后,通过 HTTP POST 将回复推送到仓库 ApiApp 配置的 callback_url(interface_type_id=3),供外部适配器消费并投递到实际聊天通道。回调体统一包裹:{ method, code, data }。", + "version": "1.1.0", + "updatedAt": "2026-08-07", + "http": { + "path": "{ApiApp.callback_url}", + "method": "POST" + }, + "headers": [ + { + "name": "Content-Type", + "type": "string", + "required": true, + "description": "application/json" + } + ], + "methods": { + "groups": [ + { + "groupName": "AI 自动回复", + "module": "ai_reply", + "list": [ + { + "method": "inbox.callback.ai_reply", + "description": "AI 自动回复回调。用户发送消息后,DeepSeek 推理给出回复内容,WMS 推送到外部聊天通道。", + "params": [], + "response": [], + "errors": [], + "notes": [ + "content 为 AI 生成的纯文本(含 \\n 换行,禁止 Markdown)", + "ext_id 与入站消息相同,外部系统可据此关联对话", + "若 AI 判定无需回复(silent),不会触发此回调", + "ai_thoughts 字段记录整个推理链(仅限出站记录查询,不入回调)" + ], + "example": { + "method": "inbox.callback.ai_reply", + "code": 200, + "data": { + "source": "ai_reply", + "content": "条码6900000000016查到2款商品:\n1. 披肩-消退 可用0\n2. 披肩 可用0(总量95已锁定)\n均无可用库存,建议更换商品。", + "ext_id": "api:AK001:req-123", + "ext_data": { + "request_id": "req-123" + }, + "group_id": "wrchat-xxx", + "user_id": "user-001", + "group_name": "售后沟通群", + "user_name": "张三", + "timestamp": 1786100000 + } + } + } + ] + }, + { + "groupName": "绑群确认", + "module": "bind_confirm", + "list": [ + { + "method": "inbox.callback.bind_confirm", + "description": "绑群确认回调。用户发送「授权:CODE」后,WMS 校验成功/失败/已绑定,推送绑群结果。", + "params": [], + "response": [], + "errors": [], + "notes": [ + "成功 content:绑定「{货主备注名}」成功", + "失败 content:绑群码无效或已过期,请重新生成", + "已绑定 content:已在绑定状态,无需重复操作", + "绑定成功后自动追加 inbox.callback.balance 返回面单余额" + ], + "example": { + "method": "inbox.callback.bind_confirm", + "code": 200, + "data": { + "source": "bind_confirm", + "content": "绑定「测试货主1111」成功", + "ext_id": "api:AK001:req-456", + "ext_data": null, + "group_id": "wrchat-xxx", + "user_id": "user-001", + "group_name": "售后沟通群", + "user_name": "张三", + "timestamp": 1786100000 + } + } + } + ] + }, + { + "groupName": "面单余额", + "module": "balance", + "list": [ + { + "method": "inbox.callback.balance", + "description": "面单余额回调。绑群成功后自动查询,或用户主动查询时推送面单余额。", + "params": [], + "response": [], + "errors": [], + "notes": [ + "content 格式:面单余额:总量 {print_quantity},已锁定 {print_quantity_locked},可用 {available}", + "ext_id 为 {原ext_id}:balance 后缀,避免与绑群确认回执冲突", + "余额查询失败时 content:面单余额查询失败:{错误原因}" + ], + "example": { + "method": "inbox.callback.balance", + "code": 200, + "data": { + "source": "balance", + "content": "面单余额:总量 5000,已锁定 200,可用 4800", + "ext_id": "api:AK001:req-456:balance", + "ext_data": null, + "group_id": "wrchat-xxx", + "user_id": "user-001", + "group_name": "售后沟通群", + "user_name": "张三", + "timestamp": 1786100000 + } + } + } + ] + }, + { + "groupName": "异常兜底", + "module": "error", + "list": [ + { + "method": "inbox.callback.error", + "description": "异常兜底回调。AI 5轮推理均失败或系统异常时的兜底回复。", + "params": [], + "response": [], + "errors": [], + "notes": [ + "content 为固定兜底文案:抱歉,暂时无法处理您的请求,请稍后重试", + "出站前仍写入 wms_inbox_message.outbound 记录" + ], + "example": { + "method": "inbox.callback.error", + "code": 200, + "data": { + "source": "error", + "content": "抱歉,暂时无法处理您的请求,请稍后重试", + "ext_id": "api:AK001:req-789", + "ext_data": null, + "group_id": "wrchat-xxx", + "user_id": "user-001", + "group_name": "售后沟通群", + "user_name": "张三", + "timestamp": 1786100000 + } + } + } + ] + }, + { + "groupName": "通用说明", + "module": "common", + "list": [ + { + "method": "inbox.callback.common", + "description": "所有回调类型共有字段说明及路由指引。外部适配器根据 method 字段路由到不同处理逻辑。", + "params": [ + { + "name": "method", + "type": "string", + "required": true, + "source": "body", + "description": "回调方法名,固定格式 inbox.callback.{source},外部适配器据此路由" + }, + { + "name": "code", + "type": "number", + "required": true, + "source": "body", + "description": "状态码,正常回调固定 200" + }, + { + "name": "data.source", + "type": "string", + "required": true, + "source": "body", + "description": "消息来源:ai_reply / bind_confirm / balance / error" + }, + { + "name": "data.content", + "type": "string", + "required": true, + "source": "body", + "description": "回复正文(纯文本,含 \\n 换行)" + }, + { + "name": "data.ext_id", + "type": "string", + "required": true, + "source": "body", + "description": "原始入站消息ID,关联对话链" + }, + { + "name": "data.ext_data", + "type": "object", + "required": false, + "source": "body", + "description": "入站透传数据,原路带回" + }, + { + "name": "data.group_id", + "type": "string", + "required": true, + "source": "body", + "description": "外部群ID" + }, + { + "name": "data.user_id", + "type": "string", + "required": true, + "source": "body", + "description": "外部用户ID" + }, + { + "name": "data.group_name", + "type": "string", + "required": true, + "source": "body", + "description": "群名称" + }, + { + "name": "data.user_name", + "type": "string", + "required": true, + "source": "body", + "description": "用户名称" + }, + { + "name": "data.timestamp", + "type": "number", + "required": true, + "source": "body", + "description": "出站 Unix 时间戳(秒)" + } + ], + "response": [ + { + "name": "http_status", + "type": "number", + "required": true, + "description": "HTTP 200 表示回调成功,WMS 更新 push_status=2" + } + ], + "errors": [], + "notes": [ + "回调由 app/service/inbox/processor.js → writeOutboundReply() / handleApiMessage 发起", + "callback_url 配置:wms_api_app.interface_type_id=3 AND is_enabled=1", + "超时 10 秒,失败不影响消息记录写入", + "HTTP 200 → 更新出站+入站 push_status=2(已送达)" + ] + } + ] + } + ] + } +} \ No newline at end of file diff --git a/methods/system.json b/methods/system.json index 54c497f..4c069d1 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1,8 +1,8 @@ { "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", - "version": "0.3.19", - "updatedAt": "2026-08-05", + "version": "0.3.21", + "updatedAt": "2026-08-06", "headers": [ { "name": "platform", @@ -21792,8 +21792,8 @@ { "method": "storage.stockout.list", "name": "出库单列表", - "description": "非订单出库单能力(对应奇门 stockout.create):用于处理由奇门创建的非订单出库单;主出口为 storage.stockout.*,不再推荐通过 storage.delivery.* 命名使用。storage.delivery.* 仅保留兼容转发。", - "isNeedAuth": false, + "description": "非订单出库单能力(对应奇门 stockout.create):直接读取 wms_order_stockout 表;主出口为 storage.stockout.*,不再推荐通过 storage.delivery.* 命名使用。storage.delivery.* 仅保留兼容转发。", + "isNeedAuth": true, "isNeedLogin": true, "isNeedRight": false, "headers": [ @@ -21817,14 +21817,14 @@ "type": "object", "required": false, "source": "body", - "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会在 main 中自动标准化;常用字段包括 delivery_order_code、status、outbound_status、buyer_nick、mobile 与日期区间字段。" + "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会在 main 中自动标准化;常用字段包括 stockout_order_code、order_status、order_type、source_type、remark 与日期区间字段。" }, { "name": "sort", "type": "object", "required": false, "source": "body", - "description": "排序参数,支持 sortField/sortOrder,默认按 updated_at DESC、id DESC" + "description": "排序参数,支持 sortField/sortOrder,可选字段:id、stockout_order_code、order_status、order_type、updated_at、created_at、order_create_time,默认按 updated_at DESC、id DESC" } ], "response": [ @@ -21832,7 +21832,7 @@ "name": "list", "type": "array", "required": true, - "description": "出库单列表" + "description": "出库单列表(wms_order_stockout 表记录,含 sync_status/sync_message 出站同步状态字段)" }, { "name": "pagination", @@ -21901,8 +21901,8 @@ { "method": "storage.stockout.listItems", "name": "出库单拉取明细", - "description": "按出库单查询商品明细(用于非订单出库单),底层复用 order.listItems。", - "isNeedAuth": false, + "description": "按出库单查询商品明细(用于非订单出库单),直接读取 wms_order_stockout + wms_order_stockout_items 表。", + "isNeedAuth": true, "isNeedLogin": true, "isNeedRight": false, "headers": [ @@ -21915,25 +21915,18 @@ ], "params": [ { - "name": "delivery_order_code", + "name": "stockout_order_code", "type": "string", "required": false, "source": "body", - "description": "出库单号,可用于定位订单" - }, - { - "name": "order_id", - "type": "number", - "required": false, - "source": "body", - "description": "订单ID,可与 id 兼容用于定位订单" + "description": "出库单号(推荐);兼容 delivery_order_code 旧参数名" }, { "name": "id", "type": "number", "required": false, "source": "body", - "description": "订单ID,可选;与 delivery_order_code / order_id 至少传一个" + "description": "出库单ID,可选;与 stockout_order_code 至少传一个" } ], "response": [ @@ -21941,25 +21934,197 @@ "name": "order", "type": "object", "required": true, - "description": "订单基础信息(含 id、delivery_order_code)" + "description": "出库单基础信息(wms_order_stockout 表记录,含 id、stockout_order_code)" }, { - "name": "items", + "name": "list", "type": "array", "required": true, - "description": "出库单商品明细" + "description": "出库单商品明细(wms_order_stockout_items 表记录)" } ], "errors": [ { "code": "404", - "description": "订单不存在" + "description": "出库单不存在" }, { "code": "500", "description": "缺少定位参数或查询失败" } ] + }, + { + "method": "storage.stockout.confirm", + "name": "出库单确认(直出)", + "description": "直出确认出库单:不改变内部库存,按出库单明细计划数量(plan_qty)直接确认。出站同步 taobao.qimen.stockout.confirm 成功后才将状态推进到 COMPLETED;同步失败则返回错误,order_status 不变,sync_status 标记为 FAILED。要求 express_code 已填写,否则拒绝确认。", + "isNeedAuth": true, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "出库单ID(必填)" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "出库单ID" + }, + { + "name": "stockout_order_code", + "type": "string", + "required": true, + "description": "出库单号" + }, + { + "name": "order_status", + "type": "string", + "required": true, + "description": "确认后状态(COMPLETED)" + }, + { + "name": "logisticsName", + "type": "string", + "required": true, + "description": "物流公司名称(固定为 OTHER)" + }, + { + "name": "expressCode", + "type": "string", + "required": true, + "description": "运单号(取自表中 express_code 字段)" + }, + { + "name": "expressCodes", + "type": "array", + "required": false, + "description": "运单号列表(取自表中 express_codes 字段)" + }, + { + "name": "qimenSync", + "type": "string", + "required": true, + "description": "奇门出站同步结果:success=通知成功,failure=通知失败(确认本身不受影响)" + }, + { + "name": "qimenSyncMessage", + "type": "string", + "required": false, + "description": "奇门出站失败时的错误信息" + } + ], + "errors": [ + { + "code": "400", + "description": "缺少出库单ID" + }, + { + "code": "400", + "description": "出库单不存在" + }, + { + "code": "400", + "description": "出库单当前状态不允许确认(非 CREATED/PENDING)" + }, + { + "code": "400", + "description": "出库单未填写运单号(express_code),请先更新运单号后再确认" + } + ] + }, + { + "method": "storage.stockout.updateExpress", + "name": "更新出库单运单号", + "description": "更新出库单的运单号字段(express_code / express_codes),用于在确认前填写运单信息。", + "isNeedAuth": true, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "出库单ID(必填)" + }, + { + "name": "express_code", + "type": "string", + "required": false, + "source": "body", + "description": "运单号" + }, + { + "name": "express_codes", + "type": "array", + "required": false, + "source": "body", + "description": "运单号列表(JSON 数组)" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "出库单ID" + }, + { + "name": "stockout_order_code", + "type": "string", + "required": true, + "description": "出库单号" + }, + { + "name": "express_code", + "type": "string", + "required": false, + "description": "更新后的运单号" + }, + { + "name": "express_codes", + "type": "array", + "required": false, + "description": "更新后的运单号列表" + } + ], + "errors": [ + { + "code": "400", + "description": "缺少出库单ID" + }, + { + "code": "400", + "description": "出库单不存在" + }, + { + "code": "400", + "description": "express_codes 必须是数组或 null" + } + ] } ] }, @@ -31250,127 +31415,146 @@ "description": "启用状态:1-启用,0-停用" } ], - "response": { - "type": "object", - "properties": [ - { - "name": "list", - "type": "array", - "description": "应用列表", - "children": [ - { - "name": "id", - "type": "number", - "description": "应用 ID" - }, - { - "name": "app_name", - "type": "string", - "description": "应用名称" - }, - { - "name": "warehouse_id", - "type": "number", - "description": "仓库 ID" - }, - { - "name": "interface_type_id", - "type": "number", - "description": "接口类型 ID" - }, - { - "name": "self_app_key", - "type": "string", - "description": "自身 AppKey(对外提供)" - }, - { - "name": "self_app_secret", - "type": "string", - "description": "自身 AppSecret(脱敏,仅显示前8位+****)" - }, - { - "name": "self_ip_whitelist", - "type": "array", - "description": "IP 白名单", - "children": [ - { - "name": "ip", - "type": "string", - "description": "IP 地址或 CIDR" - } - ] - }, - { - "name": "callback_url", - "type": "string", - "description": "回调通知 URL" - }, - { - "name": "rate_limit", - "type": "number", - "description": "速率限制(次/秒)" - }, - { - "name": "sign_method", - "type": "string", - "description": "签名方法:md5/hmac/sha256" - }, - { - "name": "is_enabled", - "type": "number", - "description": "启用状态:1-启用,0-停用" - }, - { - "name": "created_at", - "type": "string", - "description": "创建时间" - }, - { - "name": "updated_at", - "type": "string", - "description": "更新时间" - } - ] - }, - { - "name": "pagination", - "type": "object", - "description": "分页信息", - "children": [ - { - "name": "page", - "type": "number", - "description": "当前页" - }, - { - "name": "pageSize", - "type": "number", - "description": "每页数量" - }, - { - "name": "total", - "type": "number", - "description": "总记录数" - }, - { - "name": "totalPages", - "type": "number", - "description": "总页数" - }, - { - "name": "hasNext", - "type": "boolean", - "description": "是否有下一页" - }, - { - "name": "hasPrevious", - "type": "boolean", - "description": "是否有上一页" - } - ] - } - ] - }, + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "应用列表", + "children": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "应用 ID" + }, + { + "name": "app_name", + "type": "string", + "required": true, + "description": "应用名称" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "仓库 ID" + }, + { + "name": "interface_type_id", + "type": "number", + "required": true, + "description": "接口类型 ID" + }, + { + "name": "self_app_key", + "type": "string", + "required": true, + "description": "自身 AppKey(对外提供)" + }, + { + "name": "self_app_secret", + "type": "string", + "required": true, + "description": "自身 AppSecret(脱敏,仅显示前8位+****)" + }, + { + "name": "self_ip_whitelist", + "type": "array", + "required": false, + "description": "IP 白名单", + "children": [ + { + "name": "ip", + "type": "string", + "required": false, + "description": "IP 地址或 CIDR" + } + ] + }, + { + "name": "callback_url", + "type": "string", + "required": false, + "description": "回调通知 URL" + }, + { + "name": "rate_limit", + "type": "number", + "required": false, + "description": "速率限制(次/秒)" + }, + { + "name": "sign_method", + "type": "string", + "required": false, + "description": "签名方法(当前仅支持 md5)" + }, + { + "name": "is_enabled", + "type": "number", + "required": false, + "description": "启用状态:1-启用,0-停用" + }, + { + "name": "created_at", + "type": "string", + "required": false, + "description": "创建时间" + }, + { + "name": "updated_at", + "type": "string", + "required": false, + "description": "更新时间" + } + ] + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息", + "children": [ + { + "name": "page", + "type": "number", + "required": true, + "description": "当前页" + }, + { + "name": "pageSize", + "type": "number", + "required": true, + "description": "每页数量" + }, + { + "name": "total", + "type": "number", + "required": true, + "description": "总记录数" + }, + { + "name": "totalPages", + "type": "number", + "required": true, + "description": "总页数" + }, + { + "name": "hasNext", + "type": "boolean", + "required": true, + "description": "是否有下一页" + }, + { + "name": "hasPrevious", + "type": "boolean", + "required": true, + "description": "是否有上一页" + } + ] + } + ], "errors": [ { "code": "401", @@ -31404,76 +31588,86 @@ "description": "应用 ID" } ], - "response": { - "type": "object", - "properties": [ - { - "name": "id", - "type": "number", - "description": "应用 ID" - }, - { - "name": "app_name", - "type": "string", - "description": "应用名称" - }, - { - "name": "warehouse_id", - "type": "number", - "description": "仓库 ID" - }, - { - "name": "interface_type_id", - "type": "number", - "description": "接口类型 ID" - }, - { - "name": "self_app_key", - "type": "string", - "description": "自身 AppKey" - }, - { - "name": "self_app_secret", - "type": "string", - "description": "自身 AppSecret(脱敏)" - }, - { - "name": "self_ip_whitelist", - "type": "array", - "description": "IP 白名单" - }, - { - "name": "callback_url", - "type": "string", - "description": "回调通知 URL" - }, - { - "name": "rate_limit", - "type": "number", - "description": "速率限制" - }, - { - "name": "sign_method", - "type": "string", - "description": "签名方法" - }, - { - "name": "is_enabled", - "type": "number", - "description": "启用状态" - }, - { - "name": "created_at", - "type": "string", - "description": "创建时间" - }, - { - "name": "updated_at", - "type": "string", - "description": "更新时间" - } - ] - }, + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "应用 ID" + }, + { + "name": "app_name", + "type": "string", + "required": true, + "description": "应用名称" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "仓库 ID" + }, + { + "name": "interface_type_id", + "type": "number", + "required": true, + "description": "接口类型 ID" + }, + { + "name": "self_app_key", + "type": "string", + "required": true, + "description": "自身 AppKey" + }, + { + "name": "self_app_secret", + "type": "string", + "required": true, + "description": "自身 AppSecret(脱敏)" + }, + { + "name": "self_ip_whitelist", + "type": "array", + "required": false, + "description": "IP 白名单" + }, + { + "name": "callback_url", + "type": "string", + "required": false, + "description": "回调通知 URL" + }, + { + "name": "rate_limit", + "type": "number", + "required": false, + "description": "速率限制" + }, + { + "name": "sign_method", + "type": "string", + "required": false, + "description": "签名方法(当前仅支持 md5)" + }, + { + "name": "is_enabled", + "type": "number", + "required": false, + "description": "启用状态" + }, + { + "name": "created_at", + "type": "string", + "required": false, + "description": "创建时间" + }, + { + "name": "updated_at", + "type": "string", + "required": false, + "description": "更新时间" + } + ], "errors": [ { "code": "400", @@ -31495,7 +31689,7 @@ }, { "method": "apiApp.create", - "description": "创建 API 应用,自动生成 AppKey(AK{时间戳}{随机8位hex})和 AppSecret(64位hex)。仅创建时返回完整 Secret", + "description": "创建 API 应用,自动生成 AppKey(AK{时间戳}{随机8位hex})和 AppSecret(64位hex)。仅创建时返回完整 Secret。签名方法固定为 md5", "isNeedAuth": true, "isNeedLogin": true, "headers": [ @@ -31531,6 +31725,7 @@ { "name": "ip", "type": "string", + "required": false, "description": "IP 地址或 CIDR" } ] @@ -31548,70 +31743,70 @@ "required": false, "source": "body", "description": "速率限制(次/秒),默认 1000,范围 1-100000" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "应用 ID" + }, + { + "name": "app_name", + "type": "string", + "required": true, + "description": "应用名称" + }, + { + "name": "self_app_key", + "type": "string", + "required": true, + "description": "自动生成的 AppKey" + }, + { + "name": "self_app_secret", + "type": "string", + "required": true, + "description": "自动生成的 AppSecret(仅创建和重新生成时返回完整值,请妥善保存)" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "所属仓库 ID" + }, + { + "name": "interface_type_id", + "type": "number", + "required": true, + "description": "接口类型 ID" + }, + { + "name": "rate_limit", + "type": "number", + "required": false, + "description": "速率限制" }, { "name": "sign_method", "type": "string", "required": false, - "source": "body", - "description": "签名方法:md5/hmac/sha256,默认 md5" + "description": "签名方法(固定为 md5)" + }, + { + "name": "is_enabled", + "type": "number", + "required": false, + "description": "启用状态,创建后默认 1" + }, + { + "name": "created_at", + "type": "string", + "required": false, + "description": "创建时间" } ], - "response": { - "type": "object", - "properties": [ - { - "name": "id", - "type": "number", - "description": "应用 ID" - }, - { - "name": "app_name", - "type": "string", - "description": "应用名称" - }, - { - "name": "self_app_key", - "type": "string", - "description": "自动生成的 AppKey" - }, - { - "name": "self_app_secret", - "type": "string", - "description": "自动生成的 AppSecret(仅创建和重新生成时返回完整值,请妥善保存)" - }, - { - "name": "warehouse_id", - "type": "number", - "description": "所属仓库 ID" - }, - { - "name": "interface_type_id", - "type": "number", - "description": "接口类型 ID" - }, - { - "name": "rate_limit", - "type": "number", - "description": "速率限制" - }, - { - "name": "sign_method", - "type": "string", - "description": "签名方法" - }, - { - "name": "is_enabled", - "type": "number", - "description": "启用状态,创建后默认 1" - }, - { - "name": "created_at", - "type": "string", - "description": "创建时间" - } - ] - }, "errors": [ { "code": "400", @@ -31637,7 +31832,7 @@ }, { "method": "apiApp.update", - "description": "更新 API 应用(名称、白名单、回调地址、限流、签名方法、启用状态),不可变字段:app_key、interface_type_id", + "description": "更新 API 应用(名称、白名单、回调地址、限流、启用状态),不可变字段:app_key、interface_type_id、sign_method(固定为 md5,不允许修改)", "isNeedAuth": true, "isNeedLogin": true, "headers": [ @@ -31684,13 +31879,6 @@ "source": "body", "description": "速率限制,范围 1-100000" }, - { - "name": "sign_method", - "type": "string", - "required": false, - "source": "body", - "description": "签名方法:md5/hmac/sha256" - }, { "name": "is_enabled", "type": "number", @@ -31699,41 +31887,44 @@ "description": "启用状态:1-启用,0-停用" } ], - "response": { - "type": "object", - "properties": [ - { - "name": "id", - "type": "number", - "description": "应用 ID" - }, - { - "name": "app_name", - "type": "string", - "description": "应用名称" - }, - { - "name": "self_app_key", - "type": "string", - "description": "AppKey(不可变)" - }, - { - "name": "self_app_secret", - "type": "string", - "description": "AppSecret(脱敏)" - }, - { - "name": "is_enabled", - "type": "number", - "description": "启用状态" - }, - { - "name": "updated_at", - "type": "string", - "description": "更新时间" - } - ] - }, + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "应用 ID" + }, + { + "name": "app_name", + "type": "string", + "required": true, + "description": "应用名称" + }, + { + "name": "self_app_key", + "type": "string", + "required": true, + "description": "AppKey(不可变)" + }, + { + "name": "self_app_secret", + "type": "string", + "required": true, + "description": "AppSecret(脱敏)" + }, + { + "name": "is_enabled", + "type": "number", + "required": false, + "description": "启用状态" + }, + { + "name": "updated_at", + "type": "string", + "required": false, + "description": "更新时间" + } + ], "errors": [ { "code": "400", @@ -31745,7 +31936,7 @@ }, { "code": "400", - "message": "签名方法仅支持 md5/hmac/sha256" + "message": "签名方法当前仅支持 md5,不允许修改" }, { "code": "401", @@ -31948,6 +32139,20 @@ "source": "body", "description": "推送状态筛选:0=待推送 1=推送中 2=已送达 3=失败" }, + { + "name": "startDate", + "type": "string", + "required": false, + "source": "body", + "description": "开始日期(created_at >=),格式 YYYY-MM-DD 或 YYYY-MM-DD HH:mm:ss" + }, + { + "name": "endDate", + "type": "string", + "required": false, + "source": "body", + "description": "结束日期(created_at <=),格式 YYYY-MM-DD 或 YYYY-MM-DD HH:mm:ss" + }, { "name": "page", "type": "number", diff --git a/methods/warehouse.json b/methods/warehouse.json index 8389202..f94bd06 100644 --- a/methods/warehouse.json +++ b/methods/warehouse.json @@ -1,8 +1,8 @@ { "module": "warehouse", - "description": "仓库开放 API 统一入口,供仓库级外部适配器(企微/钉钉/飞书/IM 等)调用,HTTP POST /warehouse,使用 MD5 签名鉴权(interface_type_id=3)", - "version": "1.0.0", - "updatedAt": "2026-08-03", + "description": "仓库开放 API 统一入口(入站方向:外部 → WMS),供仓库级外部适配器(企微/钉钉/飞书/IM 等)调用,HTTP POST /warehouse,使用 MD5 签名鉴权(interface_type_id=3)。出站通知请参阅 warehouse_notify.json。", + "version": "1.2.0", + "updatedAt": "2026-08-07", "http": { "path": "/warehouse", "method": "POST" @@ -204,25 +204,11 @@ "list": [ { "method": "inbox.push", - "description": "外部系统将消息推入仓库站内信,WMS 异步转发到目标渠道。warehouse_id 由验签后上下文注入,禁止外部传入。", + "description": "外部系统将消息推入仓库站内信。warehouse_id 由验签后上下文注入,禁止外部传入。ext_id 由 appKey + requestId 自动组合,幂等去重。source_type 固定为 api,禁止外部传入。", "isNeedAuth": false, "isNeedLogin": false, "headers": [], "params": [ - { - "name": "sourceType", - "type": "string", - "required": false, - "source": "body", - "description": "来源类型:im / api,默认 api" - }, - { - "name": "sourceChannel", - "type": "string", - "required": false, - "source": "body", - "description": "来源渠道标识(IM 平台名称 / API 标识),将写入 source_extra" - }, { "name": "requestId", "type": "string", @@ -230,6 +216,48 @@ "source": "body", "description": "来源请求唯一 ID,与 appKey 组合为 ext_id(api:{appKey}:{requestId}),用于幂等去重" }, + { + "name": "content", + "type": "string", + "required": false, + "source": "body", + "description": "消息正文/摘要" + }, + { + "name": "groupId", + "type": "string", + "required": false, + "source": "body", + "description": "外部群 ID,用于关联群及自动查询货主路由" + }, + { + "name": "groupName", + "type": "string", + "required": false, + "source": "body", + "description": "群名称(展示用)" + }, + { + "name": "userId", + "type": "string", + "required": false, + "source": "body", + "description": "外部用户 ID" + }, + { + "name": "userName", + "type": "string", + "required": false, + "source": "body", + "description": "用户名称(展示用)" + }, + { + "name": "parentId", + "type": "number", + "required": false, + "source": "body", + "description": "关联消息 ID(回信时指向原消息,形成对话链)" + }, { "name": "targetType", "type": "string", @@ -237,13 +265,6 @@ "source": "body", "description": "目标类型:im / api / webhook,默认 im" }, - { - "name": "targetChannel", - "type": "string", - "required": true, - "source": "body", - "description": "目标渠道:wecom / dingtalk / feishu / warehouse_api / webhook" - }, { "name": "extData", "type": "object", @@ -256,21 +277,7 @@ "type": "object", "required": false, "source": "body", - "description": "处理标记,可选:skip_ai_parse(跳过智能解析)、skip_auto_reply(跳过自动回复)、skip_forward(仅存档不转发)" - }, - { - "name": "storeId", - "type": "number", - "required": false, - "source": "body", - "description": "关联货主 ID" - }, - { - "name": "parentId", - "type": "number", - "required": false, - "source": "body", - "description": "关联消息 ID(回信时指向原消息,形成对话链)" + "description": "处理标记(预留,当前未消费)" } ], "response": [ @@ -290,7 +297,7 @@ "name": "ext_id", "type": "string", "required": true, - "description": "外部唯一消息主键" + "description": "外部唯一消息主键(api:{appKey}:{requestId})" } ], "errors": [ @@ -298,25 +305,17 @@ "code": "400", "message": "requestId 不能为空" }, - { - "code": "400", - "message": "targetChannel 不能为空" - }, - { - "code": "400", - "message": "targetUrl 不能为空" - }, { "code": "400", "message": "缺少仓库信息" }, { "code": "400", - "message": "target_url 仅允许 https:// 协议" + "message": "parent_id=XX 对应的消息不存在" }, { "code": "400", - "message": "target_url 不允许指向内网地址" + "message": "消息体超过 64KB 限制" }, { "code": "500", diff --git a/methods/warehouse_notify.json b/methods/warehouse_notify.json new file mode 100644 index 0000000..0b29b96 --- /dev/null +++ b/methods/warehouse_notify.json @@ -0,0 +1,181 @@ +{ + "module": "warehouse_notify", + "description": "仓库开放通知 API 定义(出站方向:WMS → 外部系统)。WMS 处理消息后,通过 HTTP POST 主动推送到外部系统配置的 notify_url,使用 MD5 签名鉴权。method 通过 query 参数传递,body 为 { code, data }。外部系统返回 {\"code\":200} 或 HTTP 非 200 视为推送失败。", + "version": "1.0.0", + "updatedAt": "2026-08-07", + "http": { + "path": "{wms_api_app.callback_url}", + "method": "POST" + }, + "auth": { + "type": "MD5", + "description": "签名算法:sign = MD5(app_secret + timestamp + body_json)。外部系统用预先分配的 AppSecret 验证。method / app_key / timestamp / sign 通过 query 参数传递。", + "params": [ + { + "name": "app_key", + "type": "string", + "required": true, + "source": "query", + "description": "WMS 的 AppKey" + }, + { + "name": "method", + "type": "string", + "required": true, + "source": "query", + "description": "notify.ping / notify.reply" + }, + { + "name": "timestamp", + "type": "number", + "required": true, + "source": "query", + "description": "Unix 时间戳(秒),±10分钟有效" + }, + { + "name": "sign", + "type": "string", + "required": true, + "source": "query", + "description": "MD5(appSecret + timestamp + bodyJson)" + } + ] + }, + "headers": [ + { + "name": "Content-Type", + "type": "string", + "required": true, + "description": "application/json" + } + ], + "methods": { + "groups": [ + { + "groupName": "心跳", + "module": "ping", + "list": [ + { + "method": "notify.ping", + "description": "连通性测试。WMS 配置 notify_url 后可发送 ping 通知验证外部系统可达。", + "isNeedAuth": true, + "isNeedLogin": false, + "example": { + "query": "?app_key=AK20260807001×tamp=1786100000&sign=abc123", + "method": "notify.ping", + "code": 200, + "data": { + "content": "ping", + "timestamp": 1786100000 + } + } + } + ] + }, + { + "groupName": "消息回复", + "module": "reply", + "list": [ + { + "method": "notify.reply", + "description": "消息回复通知。WMS 处理入站消息后,将 AI 回复/绑群结果/面单余额等内容推送到外部系统。外部系统根据 data.type 区分消息类别。", + "isNeedAuth": true, + "isNeedLogin": false, + "params": [ + { + "name": "data.type", + "type": "string", + "required": true, + "source": "body", + "description": "ai=AI回复 / bind=绑群结果 / balance=面单余额 / error=异常兜底" + }, + { + "name": "data.content", + "type": "string", + "required": true, + "source": "body", + "description": "回复正文(纯文本)" + }, + { + "name": "data.ext_id", + "type": "string", + "required": true, + "source": "body", + "description": "通知唯一 ID(wms_inbox_message.id 主键),用于幂等判断。网络波动时可能重推,接收方应据此去重" + }, + { + "name": "data.ext_data", + "type": "object", + "required": false, + "source": "body", + "description": "入站透传数据,原路带回" + }, + { + "name": "data.group_id", + "type": "string", + "required": true, + "source": "body", + "description": "群ID" + }, + { + "name": "data.user_id", + "type": "string", + "required": true, + "source": "body", + "description": "用户ID" + }, + { + "name": "data.group_name", + "type": "string", + "required": true, + "source": "body", + "description": "群名称" + }, + { + "name": "data.user_name", + "type": "string", + "required": true, + "source": "body", + "description": "用户名称" + }, + { + "name": "data.timestamp", + "type": "number", + "required": true, + "source": "body", + "description": "Unix 秒" + } + ], + "notes": [ + "对应入站:/warehouse inbox.push", + "type=ai:用户消息触发 AI 推理回复", + "type=bind:用户发送「授权:CODE」绑群", + "type=balance:绑群成功后自动推送面单余额", + "type=error:AI 无法处理时的兜底回复", + "AI silent(无需回复)时不推送", + "ext_id 为 wms_inbox_message.id 主键,接收方应以 ext_id 做幂等去重,网络波动可能重推" + ], + "example": { + "query": "?app_key=AK001×tamp=1786100000&sign=abc", + "method": "notify.reply", + "code": 200, + "data": { + "type": "ai", + "content": "条码6900000000016查到2款商品:\n1. 披肩-消退 可用0\n2. 披肩 可用0(总量95已锁定)", + "ext_id": "188", + "ext_data": { + "request_id": "req-123" + }, + "group_id": "wrchat-xxx", + "user_id": "user-001", + "group_name": "售后沟通群", + "user_name": "张三", + "timestamp": 1786100000 + } + } + } + ] + } + ] + } +} \ No newline at end of file From 35c71e13c4a38384e939e9405f34d0d5a98c5175 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sat, 8 Aug 2026 01:58:06 +0800 Subject: [PATCH 181/550] =?UTF-8?q?feat(inbox):=20=E7=BE=A4=E5=88=97?= =?UTF-8?q?=E8=A1=A8=E5=AD=97=E6=AE=B5=E4=BC=98=E5=8C=96=E3=80=81where?= =?UTF-8?q?=E6=9F=A5=E8=AF=A2=E6=94=AF=E6=8C=81=E3=80=81=E5=BF=AB=E9=80=92?= =?UTF-8?q?=E6=8E=A5=E5=8F=A3=E5=8A=A0=E8=BD=BD=E5=8F=8A=E6=97=B6=E9=97=B4?= =?UTF-8?q?=E6=A0=BC=E5=BC=8F=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit inbox.group.list 优化: - 移除 warehouse_id 返回字段 - 新增 store_name(StoreWarehouse.store_remask) - express_interfaces 改为 {id,name} 对象数组 - 新增 system_express_name(wms_express.name) - created_at/updated_at 使用 app.formatDate 格式化 - 支持 pagination 对象 + where 结构化查询(parseWhereConditions) - keyword 虚拟字段映射为 group_name LIKE - groupType 驼峰映射为 group_type - 增加 specialFieldMap 声明合法字段 新增 index.loadExpressInterfaces: - 参考 loadStores 模式,拉取仓库下快递接口下拉列表 - 支持 systemExpressCode 入参过滤 - systemMethods/index.js 注册 + methods/system.json 文档 其他: - delivery_order_code + store_id 联合索引迁移 --- app/service/inbox/functions.js | 157 ++++++++++++++++-- app/service/inbox/processor.js | 7 + app/service/systemMethods/inbox.js | 4 +- app/service/systemMethods/index.js | 10 +- app/service/systems/inbox/group.js | 143 +++++++++++++++- .../systems/setting/expressInterface.js | 31 ++++ ...808100000-add-delivery-code-store-index.js | 14 ++ methods/system.json | 53 ++++++ 8 files changed, 399 insertions(+), 20 deletions(-) create mode 100644 database/migrations/20260808100000-add-delivery-code-store-index.js diff --git a/app/service/inbox/functions.js b/app/service/inbox/functions.js index 6c9ed95..aeb389b 100644 --- a/app/service/inbox/functions.js +++ b/app/service/inbox/functions.js @@ -126,16 +126,8 @@ class InboxFunctionsService extends Service { handler: async (params = {}) => { const { ctx } = this; void params; - const storeId = Number( - ctx.inboxContext?.store_id - || ctx.user?.store_id - || 0 - ); - const warehouseId = Number( - ctx.inboxContext?.warehouse_id - || ctx.user?.store_id - || 0 - ); + const storeId = Number(ctx.inboxContext?.store_id || 0); + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); if (!Number.isFinite(storeId) || storeId <= 0) { return { @@ -558,6 +550,151 @@ class InboxFunctionsService extends Service { }, }); + this.register('queryOrder', { + description: '查询订单。先精确匹配运单号,未命中则模糊搜索发货单号/平台单号。自动定位订单在待处理表/配送表/历史表中的位置,返回订单关键信息和重量。重量字段说明:items_weight 为订单商品总重量(g),waybills[].weighing_weight 为快递实际称重重量(g),仅已分配运单号时才有称重值', + params: { + keyword: { type: 'string', required: true, description: '搜索关键词:运单号(waybill_code,精确匹配)、发货单号(delivery_order_code,模糊)、平台单号(source_platform_code,模糊)' }, + }, + groups: [ GROUP.BOUND_STORE_AFTER_SALES ], + handler: async (params = {}) => { + const { ctx } = this; + const storeId = Number(ctx.inboxContext?.store_id || 0); + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + const keyword = String(params.keyword || '').trim(); + const { Op } = ctx.app.Sequelize; + + if (!keyword) return { success: false, error: '请提供搜索关键词' }; + if (!warehouseId || !storeId) return { success: false, error: '无法获取仓库或货主信息' }; + + // 公共:三张订单表配置 + const attributes = [ + 'id', 'delivery_order_code', 'source_platform_code', 'source_order_codes', + 'store_id', 'warehouse_id', 'status', 'step', + 'name', 'mobile', 'province', 'city', 'area', 'detail_address', + 'items_count', 'items_total', 'items_weight', + 'express_code', 'logistics_name', 'logistics_code', + 'total_amount', 'freight', + 'create_at', 'updated_at', 'delivery_time', + ]; + const tableConfigs = [ + { key: 'current', label: '待处理表', getModel: (f, wid) => f.getCurrentModel(wid) }, + { key: 'dispatch', label: '配送表', getModel: (f, wid) => f.getDispatchModel(wid) }, + { key: 'history', label: '历史表', getModel: (f, wid) => f.getHistoryModel(wid) }, + ]; + const factory = ctx.model.OrderDeliveryFactory; + + /** + * 在三张订单表中查找匹配行 + * @param {Object} where WHERE 条件 + * @return {Object|null} 找到的行(含 table/key),或 null + */ + const findInDeliveryTables = async where => { + for (const cfg of tableConfigs) { + const model = await cfg.getModel(factory, warehouseId); + if (!model) continue; + const row = await model.findOne({ attributes, where, raw: true }); + if (row) return { table: cfg.key, table_label: cfg.label, ...row }; + } + return null; + }; + + try { + let found = null; + + // ========== 第一步:运单号精确匹配 ========== + const exactExpress = await ctx.model.OrderExpress.findOne({ + attributes: [ 'delivery_order_code' ], + where: { + waybill_code: keyword, + store_id: storeId, + warehouse_id: warehouseId, + }, + raw: true, + }); + + if (exactExpress && exactExpress.delivery_order_code) { + // 用运单关联的发货单号精确查找订单 + found = await findInDeliveryTables({ + store_id: storeId, + delivery_order_code: exactExpress.delivery_order_code, + }); + } + + // ========== 第二步:运单未命中 → 模糊搜索发货单号 / 平台单号 ========== + if (!found) { + found = await findInDeliveryTables({ + store_id: storeId, + [Op.or]: [ + { delivery_order_code: { [Op.like]: `%${keyword}%` } }, + { source_platform_code: { [Op.like]: `%${keyword}%` } }, + ], + }); + } + + if (!found) { + return { + success: false, + error: `未找到与「${keyword}」匹配的订单,请核实单号后重试(支持运单号精确匹配 / 发货单号模糊 / 平台单号模糊查询)`, + }; + } + + // ========== 第三步:查关联运单信息 ========== + const linkedExpress = await ctx.model.OrderExpress.findAll({ + attributes: [ 'waybill_code', 'logistics_name', 'weighing_weight', 'status', 'is_galaxy_receive' ], + where: { + delivery_order_code: found.delivery_order_code, + store_id: storeId, + }, + raw: true, + }); + + const hasWaybill = linkedExpress.length > 0; + + return { + success: true, + data: { + table: found.table, + table_label: found.table_label, + order_id: found.id, + delivery_order_code: found.delivery_order_code || '', + source_platform_code: found.source_platform_code || '', + source_order_codes: found.source_order_codes || '', + status: found.status, + step: found.step, + receiver_name: found.name || '', + receiver_mobile: found.mobile || '', + receiver_address: [ found.province, found.city, found.area, found.detail_address ] + .filter(Boolean).join(''), + items_count: found.items_count || 0, + items_total: found.items_total || 0, + // 重量信息(必须区分说明) + items_weight: found.items_weight || 0, + items_weight_note: '商品总重量(克),订单中所有商品SKU的合计重量', + has_waybill: hasWaybill, + has_waybill_note: hasWaybill ? '' : '该订单尚未分配运单号,无实际称重重量', + waybills: linkedExpress.map(e => ({ + waybill_code: e.waybill_code || '', + logistics_name: e.logistics_name || '', + weighing_weight: e.weighing_weight || 0, + weighing_weight_note: '快递实际称重重量(克),仅已分配运单号并完成称重时才有值', + status: e.status, + is_received: e.is_galaxy_receive === 'Y', + })), + express_code: found.express_code || '', + logistics_name: found.logistics_name || '', + total_amount: found.total_amount, + freight: found.freight, + created_at: found.create_at, + updated_at: found.updated_at, + delivery_time: found.delivery_time || null, + }, + }; + } catch (error) { + return { success: false, error: `订单查询失败: ${error.message}` }; + } + }, + }); + this.register('recallHistory', { description: '回顾当前群+用户的最近对话历史。当需要上下文但信息不足时调用,获取最近N条消息记录(含AI回复),每条带序号', params: { diff --git a/app/service/inbox/processor.js b/app/service/inbox/processor.js index bec7f8b..6b6fd0d 100644 --- a/app/service/inbox/processor.js +++ b/app/service/inbox/processor.js @@ -128,6 +128,13 @@ class InboxProcessorService extends Service { } } + // 4.5 群未绑定任务类型 → 跳过 AI 处理 + const groupType = String(ctx.inboxContext.group_type || '').trim(); + if (!groupType) { + ctx.logger.info(`[inbox processor] 群未绑定任务类型,跳过 AI ext_id=${extId}`); + return; + } + // 5. 群未启用AI → 跳过(ai_enabled != 1 一律跳过,安全默认) if (ctx.inboxContext.ai_enabled !== 1) { ctx.logger.info(`[inbox processor] 群未启用AI自动回复,跳过 AI ext_id=${extId}`); diff --git a/app/service/systemMethods/inbox.js b/app/service/systemMethods/inbox.js index f3314f5..c0dccee 100644 --- a/app/service/systemMethods/inbox.js +++ b/app/service/systemMethods/inbox.js @@ -83,7 +83,7 @@ class InboxSystemService extends MainService { */ async groupList(data = {}) { const { ctx } = this; - const { groupType, keyword, page, pageSize } = data; + const { groupType, keyword, page, pageSize, pagination, where } = data; const warehouseId = Number(ctx.user?.store_id || 0); return await ctx.service.systems.inbox.group.list({ @@ -92,6 +92,8 @@ class InboxSystemService extends MainService { keyword, page, pageSize, + pagination, + where, }); } diff --git a/app/service/systemMethods/index.js b/app/service/systemMethods/index.js index 080f03b..19f4bd7 100644 --- a/app/service/systemMethods/index.js +++ b/app/service/systemMethods/index.js @@ -1053,9 +1053,9 @@ class indexService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = 'getI18nMessage,putI18nCollect,test,getCainiaoStfTemplates,polyapiAuthorizeUrl'; - const _noNeedRight = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,loadWarehouses,getImages,getCOSUploadConfig,uploadSuccessNotify,getMessageDetail,searchSpace,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,getPlatformOauthLink,listenPlatformOauthBind,recognizeLicensePlate,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl,toOrder'; + const _noNeedRight = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,loadWarehouses,loadExpressInterfaces,getImages,getCOSUploadConfig,uploadSuccessNotify,getMessageDetail,searchSpace,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,getPlatformOauthLink,listenPlatformOauthBind,recognizeLicensePlate,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl,toOrder'; const _noNeedLog = '*'; - const _noNeedAuth = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,loadWarehouses,getImages,getMessageDetail,searchSpace,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,getPlatformOauthLink,listenPlatformOauthBind,recognizeLicensePlate,test,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl,toOrder'; + const _noNeedAuth = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,loadWarehouses,loadExpressInterfaces,getImages,getMessageDetail,searchSpace,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,getPlatformOauthLink,listenPlatformOauthBind,recognizeLicensePlate,test,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl,toOrder'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } async fastWhereTree(data) { @@ -1074,6 +1074,12 @@ class indexService extends MainService { const result = await service.systems.store.loadWarehouses(); return this.success('ok', { warehouses: result, code: 200 }); } + async loadExpressInterfaces(data = {}) { + const { service } = this; + const { systemExpressCode } = data; + const result = await service.systems.setting.expressInterface.loadExpressInterfaces({ systemExpressCode }); + return this.success('ok', { expressInterfaces: result, code: 200 }); + } async getCOSUploadConfig(datas) { const { service } = this; const { data } = datas; diff --git a/app/service/systems/inbox/group.js b/app/service/systems/inbox/group.js index 876daf3..7f4abf4 100644 --- a/app/service/systems/inbox/group.js +++ b/app/service/systems/inbox/group.js @@ -1,6 +1,7 @@ 'use strict'; const Service = require('egg').Service; +const { parseWhereConditions } = require('../../../lib/query_condition_parser'); /** * 站内信群管理业务逻辑层。 @@ -20,25 +21,84 @@ class InboxGroupService extends Service { */ async list(data = {}) { const { ctx } = this; - const { InboxGroup } = ctx.model; + const { InboxGroup, StoreWarehouse, ExpressInterface, Express } = ctx.model; const { Op } = ctx.app.Sequelize; const warehouseId = Number(data.warehouseId); - const groupType = String(data.groupType || '').trim(); - const keyword = String(data.keyword || '').trim(); - const page = Math.max(1, Number(data.page) || 1); - const pageSize = Math.min(100, Math.max(1, Number(data.pageSize) || 20)); + + // 分页:优先取 pagination 对象,兜底扁平参数 + const pag = data.pagination || {}; + const page = Math.max(1, Number(pag.page || data.page) || 1); + const pageSize = Math.min(100, Math.max(1, Number(pag.pageSize || data.pageSize) || 20)); const offset = (page - 1) * pageSize; if (!warehouseId) throw new Error('warehouseId 无效'); const where = { warehouse_id: warehouseId }; + + // ── 扁平参数(向后兼容)── + const groupType = String(data.groupType || '').trim(); + const keyword = String(data.keyword || '').trim(); if (groupType) where.group_type = groupType; if (keyword) where.group_name = { [Op.like]: `%${keyword}%` }; + // ── 结构化 where(operator 模式)── + if (data.where && typeof data.where === 'object') { + // 从 where 中提取虚拟字段(不允许直接作为列名查询) + const whereInput = { ...data.where }; + + // keyword:虚拟字段 → 模糊搜索 group_name + if (whereInput.keyword !== undefined) { + const kw = whereInput.keyword; + delete whereInput.keyword; + const kwValue = kw && typeof kw === 'object' && kw.value !== undefined ? kw.value : kw; + const kwArr = Array.isArray(kwValue) ? kwValue : [ kwValue ]; + const kwStr = kwArr.filter(Boolean).join('').trim(); + if (kwStr && !keyword) { + where.group_name = { [Op.like]: `%${kwStr}%` }; + } + } + + // groupType: camelCase → group_type(优先已从扁平参数设置的 group_type) + if (whereInput.groupType !== undefined) { + const gt = whereInput.groupType; + delete whereInput.groupType; + const gtValue = gt && typeof gt === 'object' && gt.value !== undefined ? gt.value : gt; + const gtStr = String(gtValue || '').trim(); + if (gtStr && !groupType) { + where.group_type = gtStr; + } + } + + if (Object.keys(whereInput).length > 0) { + const parsed = parseWhereConditions({ + where: whereInput, + app: ctx.app, + specialFieldMap: { + store_id: { field: 'store_id' }, + group_id: { field: 'group_id' }, + group_name: { field: 'group_name' }, + sub_type: { field: 'sub_type' }, + source_type: { field: 'source_type' }, + is_blocked: { field: 'is_blocked' }, + ai_enabled: { field: 'ai_enabled' }, + system_express_code: { field: 'system_express_code' }, + }, + }); + + if (!parsed.ok) { + throw new Error(`where 参数解析失败: ${parsed.reason}`); + } + + if (Array.isArray(parsed.result.dynamicConditions)) { + Object.assign(where, ...parsed.result.dynamicConditions); + } + } + } + const { count, rows } = await InboxGroup.findAndCountAll({ attributes: [ - 'id', 'group_name', 'group_id', 'warehouse_id', 'store_id', + 'id', 'group_name', 'group_id', 'store_id', 'group_type', 'sub_type', 'source_type', 'source_extra', 'is_blocked', 'ai_enabled', 'express_interfaces', 'system_express_code', 'created_at', 'updated_at', @@ -50,12 +110,81 @@ class InboxGroupService extends Service { raw: true, }); - // express_interfaces 输出为数组 + // 收集需要批量查询的 ID + const storeIds = [ ...new Set(rows.map(r => r.store_id).filter(Boolean)) ]; + const allExpressInterfaceIds = []; + const expressCodes = [ ...new Set(rows.map(r => r.system_express_code).filter(Boolean)) ]; + + rows.forEach(row => { + if (row.express_interfaces) { + const ids = row.express_interfaces.split(',').map(Number).filter(Boolean); + ids.forEach(id => allExpressInterfaceIds.push(id)); + } + }); + const uniqueExpressInterfaceIds = [ ...new Set(allExpressInterfaceIds) ]; + + // 批量查询货主仓库合约备注 + let storeWarehouseMap = {}; + if (storeIds.length > 0) { + const swRows = await StoreWarehouse.findAll({ + attributes: [ 'store_id', 'store_remask' ], + where: { + store_id: { [Op.in]: storeIds }, + warehouse_id: warehouseId, + }, + raw: true, + }); + storeWarehouseMap = swRows.reduce((acc, sw) => { + acc[sw.store_id] = sw.store_remask || ''; + return acc; + }, {}); + } + + // 批量查询快递接口名称 + let expressInterfaceMap = {}; + if (uniqueExpressInterfaceIds.length > 0) { + const eiRows = await ExpressInterface.findAll({ + attributes: [ 'id', 'name' ], + where: { id: { [Op.in]: uniqueExpressInterfaceIds } }, + raw: true, + }); + expressInterfaceMap = eiRows.reduce((acc, ei) => { + acc[ei.id] = ei.name || ''; + return acc; + }, {}); + } + + // 批量查询系统快递名称 + let expressNameMap = {}; + if (expressCodes.length > 0) { + const expressRows = await Express.findAll({ + attributes: [ 'code', 'name' ], + where: { code: { [Op.in]: expressCodes } }, + raw: true, + }); + expressNameMap = expressRows.reduce((acc, e) => { + acc[e.code] = e.name || ''; + return acc; + }, {}); + } + + // 组装返回数据 + const formatDate = ctx.app.formatDate; const list = rows.map(row => ({ ...row, + store_name: row.store_id ? (storeWarehouseMap[row.store_id] || '') : '', express_interfaces: row.express_interfaces ? row.express_interfaces.split(',').map(Number).filter(Boolean) + .map(id => ({ + id, + name: expressInterfaceMap[id] || '', + })) : [], + system_express_name: row.system_express_code + ? (expressNameMap[row.system_express_code] || '') + : '', + created_at: row.created_at ? formatDate(row.created_at) : '', + updated_at: row.updated_at ? formatDate(row.updated_at) : '', })); return { total: count, list }; diff --git a/app/service/systems/setting/expressInterface.js b/app/service/systems/setting/expressInterface.js index 0d95bf0..9fa73fc 100644 --- a/app/service/systems/setting/expressInterface.js +++ b/app/service/systems/setting/expressInterface.js @@ -1643,6 +1643,37 @@ class SettingExpressInterfaceService extends Service { }, }; } + + /** + * 加载当前仓库下所有快递接口的下拉选项(id + name)。 + * 供 index.loadExpressInterfaces 调用,用于前端下拉框。 + * + * @param {Object} [data={}] 请求参数 + * @param {string} [data.systemExpressCode] 系统快递编码,传入时按 sys_express_code 过滤 + * @return {Promise>} 快递接口下拉列表 + */ + async loadExpressInterfaces(data = {}) { + const { ctx } = this; + const warehouseId = this.getCurrentStoreId(); + const systemExpressCode = String(data.systemExpressCode || '').trim().toUpperCase(); + + const where = { warehouse_id: warehouseId }; + if (systemExpressCode) { + where.sys_express_code = systemExpressCode; + } + + const rows = await ctx.model.ExpressInterface.findAll({ + where, + attributes: [ 'id', 'name' ], + order: [[ 'weight', 'ASC' ], [ 'id', 'ASC' ]], + raw: true, + }); + + return rows.map(row => ({ + value: row.id, + label: row.name || '', + })); + } } module.exports = SettingExpressInterfaceService; diff --git a/database/migrations/20260808100000-add-delivery-code-store-index.js b/database/migrations/20260808100000-add-delivery-code-store-index.js new file mode 100644 index 0000000..6537aaf --- /dev/null +++ b/database/migrations/20260808100000-add-delivery-code-store-index.js @@ -0,0 +1,14 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + // Query 3 关联查询:delivery_order_code + store_id 联合索引(最高频缺失索引) + await queryInterface.addIndex('wms_order_express', ['delivery_order_code', 'store_id'], { + name: 'idx_delivery_code_store', + }); + }, + + async down(queryInterface, Sequelize) { + await queryInterface.removeIndex('wms_order_express', 'idx_delivery_code_store'); + }, +}; diff --git a/methods/system.json b/methods/system.json index 4c069d1..def17fe 100644 --- a/methods/system.json +++ b/methods/system.json @@ -468,6 +468,59 @@ "response": [], "errors": [] }, + { + "method": "index.loadExpressInterfaces", + "description": "index.loadExpressInterfaces 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "systemExpressCode", + "type": "string", + "required": false, + "source": "body", + "description": "系统快递编码(wms_express.code),传入时仅返回该编码对应的快递接口" + } + ], + "response": [ + { + "name": "code", + "type": "number", + "description": "业务状态码,200 表示成功" + }, + { + "name": "message", + "type": "string", + "description": "业务提示信息" + }, + { + "name": "expressInterfaces", + "type": "array", + "description": "当前仓库下的快递接口下拉列表", + "children": [ + { + "name": "value", + "type": "number", + "description": "快递接口ID(wms_express_interface.id)" + }, + { + "name": "label", + "type": "string", + "description": "快递接口名称(wms_express_interface.name)" + } + ] + } + ], + "errors": [] + }, { "method": "index.getCOSUploadConfig", "description": "index.getCOSUploadConfig 接口", From 358fef0f7196786d34560286aa6b1e63b8134415 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sat, 8 Aug 2026 20:28:18 +0800 Subject: [PATCH 182/550] =?UTF-8?q?chore:=20apply=20ESLint=20auto-fixes,?= =?UTF-8?q?=20JSDoc=20additions,=20and=20CRLF=E2=86=92LF=20normalization?= =?UTF-8?q?=20(no=20logic=20changes)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/lib/polo_api_client.js | 2 +- app/lib/printer_data_builder.js | 6 +++++ app/model/after_sale_work_order.js | 4 ++-- app/model/camera.js | 10 ++++----- app/model/camera_server.js | 6 ++--- app/model/workbench.js | 8 +++---- app/service/systemMethods/dashboard.js | 2 +- .../systemMethods/setting/expressInterface.js | 6 ++--- .../systemMethods/storeWarehouse/warehouse.js | 2 ++ app/service/systemMethods/workbench.js | 7 ++++++ app/service/systems/cameraServer.js | 2 +- app/service/systems/delivery_order.js | 6 ++--- app/service/systems/express_platform.js | 16 +++++++------- app/service/systems/shops.js | 2 +- app/service/systems/stock_store.js | 4 +++- app/service/systems/storage/report.js | 3 +++ .../systems/store_express_binding_policy.js | 2 ++ app/service/systems/store_warehouse.js | 3 ++- ...-custom-barcode-unique-to-per-warehouse.js | 4 ++-- ...to-increment-wms-order-delivery-1000028.js | 2 +- .../20260715160000-create-wms-workbench.js | 8 +++---- ...0260715170000-add-type-to-wms-workbench.js | 2 +- .../20260715180000-extend-wms-pack-task.js | 12 +++++----- ...20260715220000-create-wms-camera-server.js | 6 ++--- .../20260715220001-create-wms-camera.js | 10 ++++----- ...260715230000-create-wms-pack-task-video.js | 6 ++--- ...20260717150000-add-camera-device-fields.js | 2 +- ...718170000-fix-supervisor-cs-permissions.js | 4 ++-- ...00-add-print-qty-log-export-permissions.js | 4 ++-- ...25150000-add-print-computer-permissions.js | 12 +++++----- ...0260725170000-add-recording-permissions.js | 12 +++++----- ...120000-create-wms-after-sale-work-order.js | 22 +++++++++---------- ...0-create-wms-after-sale-work-order-step.js | 8 +++---- ...20260729140000-add-waybill-list-indexes.js | 8 +++---- ...0730000000-add-camera-username-password.js | 2 +- ...000-backfill-wms-order-express-store-id.js | 10 ++++----- ...-backfill-order-express-delivery-fields.js | 4 ++-- ...20000-add-express-fields-to-inbox-group.js | 2 +- .../20260805140000-add-inbox-indexes.js | 6 ++--- ...0260805150000-add-group-api-permissions.js | 10 ++++----- ...120000-add-ai-thoughts-to-inbox-message.js | 2 +- ...-add-express-code-to-wms-order-stockout.js | 2 +- ...0807130000-add-stockout-api-permissions.js | 20 ++++++++--------- ...ress-name-waybill-to-wms-order-stockout.js | 2 +- ...808100000-add-delivery-code-store-index.js | 2 +- scripts/auth/grant-cs-up.js | 14 ++++++------ scripts/auth/revoke-cs-up.js | 12 +++++----- .../pendingOrder.manualWaybill.log.test.js | 5 +++-- 48 files changed, 165 insertions(+), 141 deletions(-) diff --git a/app/lib/polo_api_client.js b/app/lib/polo_api_client.js index e61d05d..f400c75 100644 --- a/app/lib/polo_api_client.js +++ b/app/lib/polo_api_client.js @@ -60,7 +60,7 @@ class PoloApiClient { }, content: formBody, }); - + console.log('formBody', formBody); let result; if (Buffer.isBuffer(response.data)) { diff --git a/app/lib/printer_data_builder.js b/app/lib/printer_data_builder.js index 8f4cfa7..727b8fd 100644 --- a/app/lib/printer_data_builder.js +++ b/app/lib/printer_data_builder.js @@ -1253,6 +1253,7 @@ function sanitizeTemplatePrivateFields(value, warnings, currentKey = '') { * @param {string[]} warnings 风险提示列表。 * @param {Object} policyConfig 策略配置对象。 * @param {string} customDataTemplateURL 自定义区模板地址默认值。 + * @param extraCustomLines */ function applyKuaishouExpressFieldMapping(platform, skeleton, orderExpress, orderDelivery, warnings, policyConfig, customDataTemplateURL, extraCustomLines = []) { if (platform !== 'kuaishou') { @@ -1402,6 +1403,7 @@ function applyKuaishouExpressFieldMapping(platform, skeleton, orderExpress, orde * @param {Object} orderExpress 快递单对象。 * @param {Object} orderDelivery 订单对象。 * @param {Object} policyConfig 策略配置对象。 + * @param extraCustomLines */ function applyPddExpressFieldMapping(platform, skeleton, orderExpress, orderDelivery, policyConfig, extraCustomLines = []) { if (platform !== 'pdd') { @@ -1724,6 +1726,7 @@ function applyDouyinExpressFieldMapping(platform, skeleton, orderExpress, orderD * @param {Object} policyConfig 策略配置对象。 * @param {string} customControlTemplateURL 菜鸟自定义区模板地址。 * @param {string[]} warnings 风险提示列表。 + * @param extraCustomLines */ function applyCainiaoExpressFieldMapping( platform, @@ -1934,6 +1937,7 @@ function resolveXhsMainContentFromPrintinfo(printinfo, warnings = []) { * @param {Object} orderDelivery 订单对象。 * @param {Object} policyConfig 策略配置对象。 * @param {string[]} warnings 风险提示列表。 + * @param extraCustomLines */ function applyXhsExpressFieldMapping( platform, @@ -2036,6 +2040,7 @@ function applyXhsExpressFieldMapping( * @param {Object} orderExpress 快递单对象。 * @param {Object} orderDelivery 订单对象。 * @param {Object} policyConfig 策略配置对象。 + * @param extraCustomLines */ function applySphExpressFieldMapping( platform, @@ -2176,6 +2181,7 @@ function resolveJdTemplateUrlFromOrderExpress(orderExpress) { * @param {Object} policyConfig 策略配置对象。 * @param {Object} templateSample 模板样例对象。 * @param {string[]} warnings 风险提示列表。 + * @param extraCustomLines */ function applyJdExpressFieldMapping( platform, diff --git a/app/model/after_sale_work_order.js b/app/model/after_sale_work_order.js index 0d7e9dd..90e0c89 100644 --- a/app/model/after_sale_work_order.js +++ b/app/model/after_sale_work_order.js @@ -71,7 +71,7 @@ module.exports = app => { /** * 根据 business_type 获取关联表名 * @param {string} businessType 业务类型 - * @returns {string|null} 关联表名 + * @return {string|null} 关联表名 */ function getBusinessTable(businessType) { return BUSINESS_TYPES[businessType]?.table || null; @@ -81,7 +81,7 @@ module.exports = app => { * 校验 business_type + business_sub_type 组合是否合法 * @param {string} businessType 业务类型 * @param {string} businessSubType 业务子类型 - * @returns {boolean} 是否合法 + * @return {boolean} 是否合法 */ function isValidSubType(businessType, businessSubType) { const def = BUSINESS_TYPES[businessType]; diff --git a/app/model/camera.js b/app/model/camera.js index 90a7858..04fa30e 100644 --- a/app/model/camera.js +++ b/app/model/camera.js @@ -105,11 +105,11 @@ module.exports = app => { deletedAt: 'deleted_at', comment: '摄像头表', indexes: [ - { name: 'idx_warehouse_id', fields: ['warehouse_id'] }, - { name: 'idx_server_id', fields: ['server_id'] }, - { name: 'uk_server_channel', unique: true, fields: ['server_id', 'channel_id', 'deleted_at'] }, - { name: 'idx_status', fields: ['status'] }, - { name: 'idx_deleted_at', fields: ['deleted_at'] }, + { name: 'idx_warehouse_id', fields: [ 'warehouse_id' ] }, + { name: 'idx_server_id', fields: [ 'server_id' ] }, + { name: 'uk_server_channel', unique: true, fields: [ 'server_id', 'channel_id', 'deleted_at' ] }, + { name: 'idx_status', fields: [ 'status' ] }, + { name: 'idx_deleted_at', fields: [ 'deleted_at' ] }, ], }); diff --git a/app/model/camera_server.js b/app/model/camera_server.js index 7b4712c..900a202 100644 --- a/app/model/camera_server.js +++ b/app/model/camera_server.js @@ -90,9 +90,9 @@ module.exports = app => { deletedAt: 'deleted_at', comment: '录像服务器表', indexes: [ - { name: 'idx_warehouse_id', fields: ['warehouse_id'] }, - { name: 'idx_status', fields: ['status'] }, - { name: 'idx_deleted_at', fields: ['deleted_at'] }, + { name: 'idx_warehouse_id', fields: [ 'warehouse_id' ] }, + { name: 'idx_status', fields: [ 'status' ] }, + { name: 'idx_deleted_at', fields: [ 'deleted_at' ] }, ], }); diff --git a/app/model/workbench.js b/app/model/workbench.js index ee65b8a..d8d08e0 100644 --- a/app/model/workbench.js +++ b/app/model/workbench.js @@ -71,10 +71,10 @@ module.exports = app => { deletedAt: 'deleted_at', comment: '工作台表', indexes: [ - { name: 'idx_warehouse_id', fields: ['warehouse_id'] }, - { name: 'idx_barcode', fields: ['barcode'] }, - { name: 'uk_warehouse_barcode', unique: true, fields: ['warehouse_id', 'barcode', 'deleted_at'] }, - { name: 'idx_deleted_at', fields: ['deleted_at'] }, + { name: 'idx_warehouse_id', fields: [ 'warehouse_id' ] }, + { name: 'idx_barcode', fields: [ 'barcode' ] }, + { name: 'uk_warehouse_barcode', unique: true, fields: [ 'warehouse_id', 'barcode', 'deleted_at' ] }, + { name: 'idx_deleted_at', fields: [ 'deleted_at' ] }, ], }); diff --git a/app/service/systemMethods/dashboard.js b/app/service/systemMethods/dashboard.js index 5b630c7..eeb246e 100644 --- a/app/service/systemMethods/dashboard.js +++ b/app/service/systemMethods/dashboard.js @@ -25,7 +25,7 @@ class dashboardService extends MainService { return this.fail('缺少仓库上下文'); } const stats = await this.queryWarehouseStats(warehouseId); - return this.success('ok', this.mergeStoreStats([stats])); + return this.success('ok', this.mergeStoreStats([ stats ])); } async storeSideStoreStats() { diff --git a/app/service/systemMethods/setting/expressInterface.js b/app/service/systemMethods/setting/expressInterface.js index e10f187..1d2d007 100644 --- a/app/service/systemMethods/setting/expressInterface.js +++ b/app/service/systemMethods/setting/expressInterface.js @@ -130,11 +130,11 @@ class expressInterfaceService extends MainService { } // 收集唯一 shop_id(去重) - const shopIds = [...new Set( + const shopIds = [ ...new Set( list .map(item => item.shop_id) .filter(id => id !== null && id !== undefined && Number(id) !== 0) - )]; + ) ]; if (shopIds.length === 0) { const defaultList = list.map(item => ({ ...item, quantity: 0, recycled_quantity: 0, cancel_quantity: 0, allocated_quantity: 0 })); @@ -151,7 +151,7 @@ class expressInterfaceService extends MainService { // 并行调用 getShopExpressList,构建 Map const shopExpressMap = new Map(); const shopResults = await Promise.all( - shopIds.map(async (shopId) => { + shopIds.map(async shopId => { try { const shopExpressResult = await ctx.service.systemMethods.index.getShopExpressList({ shop_id: shopId, diff --git a/app/service/systemMethods/storeWarehouse/warehouse.js b/app/service/systemMethods/storeWarehouse/warehouse.js index 0aa4ab4..5661b49 100644 --- a/app/service/systemMethods/storeWarehouse/warehouse.js +++ b/app/service/systemMethods/storeWarehouse/warehouse.js @@ -51,6 +51,7 @@ class StoreWarehouseWarehouseService extends MainService { /** * 仓库侧发起签约。 + * @param data */ async sign(data = {}) { const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse; @@ -68,6 +69,7 @@ class StoreWarehouseWarehouseService extends MainService { /** * 仓库侧确认签约。 + * @param data */ async confirmSign(data = {}) { const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse; diff --git a/app/service/systemMethods/workbench.js b/app/service/systemMethods/workbench.js index 1f7c3fe..c4a9282 100644 --- a/app/service/systemMethods/workbench.js +++ b/app/service/systemMethods/workbench.js @@ -14,6 +14,7 @@ class WorkbenchService extends MainService { /** * 工作台列表(分页 + 筛选) + * @param data */ async list(data) { const { service } = this; @@ -27,6 +28,7 @@ class WorkbenchService extends MainService { /** * 工作台详情 + * @param data */ async detail(data) { const { service } = this; @@ -42,6 +44,7 @@ class WorkbenchService extends MainService { /** * 创建工作台 + * @param data */ async create(data) { const { service } = this; @@ -55,6 +58,7 @@ class WorkbenchService extends MainService { /** * 更新工作台 + * @param data */ async update(data) { const { service } = this; @@ -70,6 +74,7 @@ class WorkbenchService extends MainService { /** * 删除工作台(软删除) + * @param data */ async delete(data) { const { service } = this; @@ -102,6 +107,7 @@ class WorkbenchService extends MainService { /** * 工作台绑定摄像头 + * @param data */ async bindCamera(data) { const { service } = this; @@ -117,6 +123,7 @@ class WorkbenchService extends MainService { /** * 检查条码是否已存在 + * @param data */ async checkBarcode(data) { const { service } = this; diff --git a/app/service/systems/cameraServer.js b/app/service/systems/cameraServer.js index 6437e65..0bdd0fe 100644 --- a/app/service/systems/cameraServer.js +++ b/app/service/systems/cameraServer.js @@ -20,7 +20,7 @@ class CameraServerService extends Service { const { count, rows } = await ctx.model.CameraServer.findAndCountAll({ where: queryWhere, - order: [['created_at', 'DESC']], + order: [[ 'created_at', 'DESC' ]], offset: (page - 1) * pageSize, limit: pageSize, }); diff --git a/app/service/systems/delivery_order.js b/app/service/systems/delivery_order.js index 45f954d..18c7df2 100644 --- a/app/service/systems/delivery_order.js +++ b/app/service/systems/delivery_order.js @@ -1161,7 +1161,7 @@ class DeliveryOrderService extends Service { isUrgency, invoiceFlag, receiverInfo, - sourceOrderCode + sourceOrderCode, } = deliveryOrder; const policyConfig = await this.getStoreWarehousePolicyConfig(info.storeId, info.warehouseId); @@ -1371,12 +1371,12 @@ class DeliveryOrderService extends Service { resolvedItems.sort((a, b) => a.stockId - b.stockId); // ===== 批量查询 wms_stock_warehouse 获取仓库侧称重毛重 ===== - const stockIds = [...new Set(resolvedItems.map(item => item.stockId).filter(Boolean))]; + const stockIds = [ ...new Set(resolvedItems.map(item => item.stockId).filter(Boolean)) ]; const warehouseWeightMap = new Map(); if (stockIds.length > 0) { const warehouseRecords = await app.model.StockWarehouse.findAll({ where: { id: stockIds }, - attributes: ['id', 'gross_weight'], + attributes: [ 'id', 'gross_weight' ], transaction, raw: true, }); diff --git a/app/service/systems/express_platform.js b/app/service/systems/express_platform.js index cb382d0..71cf8bb 100644 --- a/app/service/systems/express_platform.js +++ b/app/service/systems/express_platform.js @@ -780,8 +780,8 @@ class ExpressPlatformService extends MainService { labelformat: listByWarehousePlatformCode.labelformat || '', extraInfo: ExpressList.find(item => item.code === listByWarehousePlatformCode.sys_express_code)?.polyapi_extra_info || '', }; - console.log("matchedPlatform.platid",matchedPlatform.platid); - console.log("startPlayload",playload); + console.log('matchedPlatform.platid', matchedPlatform.platid); + console.log('startPlayload', playload); if (Number(matchedPlatform.platid) === 673) { playload.BizVersion = '2'; @@ -891,7 +891,7 @@ class ExpressPlatformService extends MainService { if (!order.extend_props.ewaybill_order_code) { throw new Error('订单数据错误,参数不全缺失extend_props.ewaybill_order_code,请复制次信息给ERP方反馈'); } - playload.oaid = order.extend_props.ewaybill_order_code||order.oaid||undefined; + playload.oaid = order.extend_props.ewaybill_order_code || order.oaid || undefined; playload.transtype = '0'; playload.Mallmaskid = order.buyer_nick; @@ -919,7 +919,7 @@ class ExpressPlatformService extends MainService { api: 'Differ.JH.Logistics.PostOrder', response: JSON.stringify(result), }); - console.log("分配运单号结果",result); + console.log('分配运单号结果', result); // 统一处理:不再依赖顶层 code,直接从 results 逐条提取 issuccess 和 submessage { @@ -1109,14 +1109,14 @@ class ExpressPlatformService extends MainService { eCustomerCode: '', remark: '', selleruserid: '', - printno: "", + printno: '', iscloudprint: 'false', needprintdetail: 'false', extenddata: '', providercode: String(item.procode || item.realcpcode || item.logisticcompanycode || ''), packageno: '', fontsize: '', - platorderno: "", + platorderno: '', sipshopid: 0, })); console.log('京东批量打印请求参数', JSON.stringify({ @@ -1783,7 +1783,7 @@ class ExpressPlatformService extends MainService { count: item.plan_qty, })) || [], goods_description: '物品', - id:`${orderDelivery.warehouse_id}_${orderDelivery.id}_${order_tmp.business_key}`, + id: `${orderDelivery.warehouse_id}_${orderDelivery.id}_${order_tmp.business_key}`, }, recipient: { address: { @@ -2363,7 +2363,7 @@ class ExpressPlatformService extends MainService { name: item.item_name || '商品', count: item.plan_qty, })) || [], - id:`${order_tmp.order_delivery.warehouse_id}_${order_tmp.order_delivery.id}_${order_tmp.business_key}`, + id: `${order_tmp.order_delivery.warehouse_id}_${order_tmp.order_delivery.id}_${order_tmp.business_key}`, }, recipient: { address: { diff --git a/app/service/systems/shops.js b/app/service/systems/shops.js index 8e792b7..ad9d8d2 100644 --- a/app/service/systems/shops.js +++ b/app/service/systems/shops.js @@ -722,7 +722,7 @@ class ShopsService extends Service { requestData.VenderID = shopPlain.id; } if (platName === '视频号') { - if(!appId || !toUserName) { + if (!appId || !toUserName) { throw this.createError('视频号授权需要提供 appId 和 toUserName', 400); } requestData.appId = appId; diff --git a/app/service/systems/stock_store.js b/app/service/systems/stock_store.js index c7c5f0d..9e377e4 100644 --- a/app/service/systems/stock_store.js +++ b/app/service/systems/stock_store.js @@ -1599,6 +1599,8 @@ class stockStoreService extends Service { * @param {Object} sortParams - 排序参数 * @param {string} sortParams.sortField - 排序字段,默认'create_at' * @param {string} sortParams.sortOrder - 排序方式,默认'DESC' + * @param externalWarehouseId + * @param externalStoreId * @return {Promise} 返回查询结果 */ async getWarehouseStock(where, pageParams = {}, sortParams = {}, externalWarehouseId = 0, externalStoreId = 0) { @@ -2842,7 +2844,7 @@ class stockStoreService extends Service { ]); } // 批量查询奇门应用名称 - const appKeys = [...new Set(barcodes.map(item => item.app_key).filter(Boolean))]; + const appKeys = [ ...new Set(barcodes.map(item => item.app_key).filter(Boolean)) ]; const qimenAppMap = new Map(); if (appKeys.length > 0) { const qimenApps = await ctx.model.QimenApp.findAll({ diff --git a/app/service/systems/storage/report.js b/app/service/systems/storage/report.js index 54e24a3..42a059a 100644 --- a/app/service/systems/storage/report.js +++ b/app/service/systems/storage/report.js @@ -328,6 +328,9 @@ class StorageReportService extends Service { * @param {number[]} [options.storeIds=[]] 货主ID列表 * @param {number[]} [options.spaceIds=[]] 库位ID列表 * @param {boolean} [options.includeBarcode=false] 是否加载条码映射 + * @param options.entryOrderIds + * @param options.orderIds + * @param options.warehouseId * @return {Promise} 映射对象 */ async loadReportReferenceMaps({ diff --git a/app/service/systems/store_express_binding_policy.js b/app/service/systems/store_express_binding_policy.js index 49e5104..c6f1732 100644 --- a/app/service/systems/store_express_binding_policy.js +++ b/app/service/systems/store_express_binding_policy.js @@ -92,6 +92,8 @@ class StoreExpressBindingPolicyService extends Service { /** * 校验快递编码是否存在。 * @param {string} expressCode 快递编码 + * @param value + * @param fieldName * @return {Promise} 标准化快递编码 */ normalizeJsonArray(value, fieldName) { diff --git a/app/service/systems/store_warehouse.js b/app/service/systems/store_warehouse.js index d4dae35..ea24806 100644 --- a/app/service/systems/store_warehouse.js +++ b/app/service/systems/store_warehouse.js @@ -1852,6 +1852,7 @@ class SettingStoreWarehouseService extends Service { /** * 精简签约对象,仅保留前端需要的字段。 + * @param serialized */ trimContract(serialized) { return { @@ -2198,7 +2199,7 @@ class SettingStoreWarehouseService extends Service { const accountIds = Array.from(accountIdSet).filter(id => Number.isFinite(id) && id > 0); // 批量查询账号姓名 - let accountNameMap = {}; + const accountNameMap = {}; if (accountIds.length > 0) { try { const accounts = await ctx.model.Account.findAll({ diff --git a/database/migrations/20260710000000-fix-custom-barcode-unique-to-per-warehouse.js b/database/migrations/20260710000000-fix-custom-barcode-unique-to-per-warehouse.js index 4f1004f..aa5e3c2 100644 --- a/database/migrations/20260710000000-fix-custom-barcode-unique-to-per-warehouse.js +++ b/database/migrations/20260710000000-fix-custom-barcode-unique-to-per-warehouse.js @@ -4,7 +4,7 @@ module.exports = { async up(queryInterface, Sequelize) { // 将 custom_barcode 唯一索引从全局改为仓库级别 await queryInterface.removeIndex('wms_location_space', 'uk_custom_barcode'); - await queryInterface.addIndex('wms_location_space', ['warehouse_id', 'custom_barcode', 'deleted_at'], { + await queryInterface.addIndex('wms_location_space', [ 'warehouse_id', 'custom_barcode', 'deleted_at' ], { name: 'uk_warehouse_custom_barcode', unique: true, }); @@ -12,7 +12,7 @@ module.exports = { async down(queryInterface, Sequelize) { await queryInterface.removeIndex('wms_location_space', 'uk_warehouse_custom_barcode'); - await queryInterface.addIndex('wms_location_space', ['custom_barcode'], { + await queryInterface.addIndex('wms_location_space', [ 'custom_barcode' ], { name: 'uk_custom_barcode', unique: true, }); diff --git a/database/migrations/20260713150000-set-auto-increment-wms-order-delivery-1000028.js b/database/migrations/20260713150000-set-auto-increment-wms-order-delivery-1000028.js index 14e8da6..93286cf 100644 --- a/database/migrations/20260713150000-set-auto-increment-wms-order-delivery-1000028.js +++ b/database/migrations/20260713150000-set-auto-increment-wms-order-delivery-1000028.js @@ -5,7 +5,7 @@ module.exports = { // 紧急修复:将 wms_order_delivery_1000028 自增值提升至 15000+ // 原因:表重建后 AUTO_INCREMENT 被重置为 151,与历史水位差距过大 await queryInterface.sequelize.query( - "ALTER TABLE wms_order_delivery_1000028 AUTO_INCREMENT = 15000" + 'ALTER TABLE wms_order_delivery_1000028 AUTO_INCREMENT = 15000' ); }, diff --git a/database/migrations/20260715160000-create-wms-workbench.js b/database/migrations/20260715160000-create-wms-workbench.js index 4912d91..53ca5f5 100644 --- a/database/migrations/20260715160000-create-wms-workbench.js +++ b/database/migrations/20260715160000-create-wms-workbench.js @@ -62,23 +62,23 @@ module.exports = { }); // 仓库隔离查询 - await queryInterface.addIndex(TABLE_NAME, ['warehouse_id'], { + await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id' ], { name: 'idx_warehouse_id', }); // 条码检索 - await queryInterface.addIndex(TABLE_NAME, ['barcode'], { + await queryInterface.addIndex(TABLE_NAME, [ 'barcode' ], { name: 'idx_barcode', }); // 仓库级别唯一条码(含软删除,遵循 location_space 同款模式) - await queryInterface.addIndex(TABLE_NAME, ['warehouse_id', 'barcode', 'deleted_at'], { + await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'barcode', 'deleted_at' ], { unique: true, name: 'uk_warehouse_barcode', }); // 软删除查询优化 - await queryInterface.addIndex(TABLE_NAME, ['deleted_at'], { + await queryInterface.addIndex(TABLE_NAME, [ 'deleted_at' ], { name: 'idx_deleted_at', }); }, diff --git a/database/migrations/20260715170000-add-type-to-wms-workbench.js b/database/migrations/20260715170000-add-type-to-wms-workbench.js index 5ce0cda..4e10f28 100644 --- a/database/migrations/20260715170000-add-type-to-wms-workbench.js +++ b/database/migrations/20260715170000-add-type-to-wms-workbench.js @@ -13,7 +13,7 @@ module.exports = { }); }, - down: async (queryInterface) => { + down: async queryInterface => { await queryInterface.removeColumn(TABLE_NAME, 'type'); }, }; diff --git a/database/migrations/20260715180000-extend-wms-pack-task.js b/database/migrations/20260715180000-extend-wms-pack-task.js index 365b690..54a3dbb 100644 --- a/database/migrations/20260715180000-extend-wms-pack-task.js +++ b/database/migrations/20260715180000-extend-wms-pack-task.js @@ -130,12 +130,12 @@ module.exports = { }); // ======== 索引 ======== - await queryInterface.addIndex(TABLE_NAME, ['warehouse_id'], { name: 'idx_warehouse_id' }); - await queryInterface.addIndex(TABLE_NAME, ['workbench_id'], { name: 'idx_workbench_id' }); - await queryInterface.addIndex(TABLE_NAME, ['wave_id'], { name: 'idx_wave_id' }); - await queryInterface.addIndex(TABLE_NAME, ['waybill_code'], { name: 'idx_waybill_code' }); - await queryInterface.addIndex(TABLE_NAME, ['start_time'], { name: 'idx_start_time' }); - await queryInterface.addIndex(TABLE_NAME, ['status'], { name: 'idx_status' }); + await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id' ], { name: 'idx_warehouse_id' }); + await queryInterface.addIndex(TABLE_NAME, [ 'workbench_id' ], { name: 'idx_workbench_id' }); + await queryInterface.addIndex(TABLE_NAME, [ 'wave_id' ], { name: 'idx_wave_id' }); + await queryInterface.addIndex(TABLE_NAME, [ 'waybill_code' ], { name: 'idx_waybill_code' }); + await queryInterface.addIndex(TABLE_NAME, [ 'start_time' ], { name: 'idx_start_time' }); + await queryInterface.addIndex(TABLE_NAME, [ 'status' ], { name: 'idx_status' }); }, down: async queryInterface => { diff --git a/database/migrations/20260715220000-create-wms-camera-server.js b/database/migrations/20260715220000-create-wms-camera-server.js index 5ad66f3..5e2dc93 100644 --- a/database/migrations/20260715220000-create-wms-camera-server.js +++ b/database/migrations/20260715220000-create-wms-camera-server.js @@ -87,9 +87,9 @@ module.exports = { }, }); - await queryInterface.addIndex(TABLE_NAME, ['warehouse_id'], { name: 'idx_warehouse_id' }); - await queryInterface.addIndex(TABLE_NAME, ['status'], { name: 'idx_status' }); - await queryInterface.addIndex(TABLE_NAME, ['deleted_at'], { name: 'idx_deleted_at' }); + await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id' ], { name: 'idx_warehouse_id' }); + await queryInterface.addIndex(TABLE_NAME, [ 'status' ], { name: 'idx_status' }); + await queryInterface.addIndex(TABLE_NAME, [ 'deleted_at' ], { name: 'idx_deleted_at' }); }, down: async queryInterface => { diff --git a/database/migrations/20260715220001-create-wms-camera.js b/database/migrations/20260715220001-create-wms-camera.js index 6a6e894..328ddc3 100644 --- a/database/migrations/20260715220001-create-wms-camera.js +++ b/database/migrations/20260715220001-create-wms-camera.js @@ -71,15 +71,15 @@ module.exports = { }, }); - await queryInterface.addIndex(TABLE_NAME, ['warehouse_id'], { name: 'idx_warehouse_id' }); - await queryInterface.addIndex(TABLE_NAME, ['server_id'], { name: 'idx_server_id' }); + await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id' ], { name: 'idx_warehouse_id' }); + await queryInterface.addIndex(TABLE_NAME, [ 'server_id' ], { name: 'idx_server_id' }); // 同一服务器下通道号唯一 - await queryInterface.addIndex(TABLE_NAME, ['server_id', 'channel_id', 'deleted_at'], { + await queryInterface.addIndex(TABLE_NAME, [ 'server_id', 'channel_id', 'deleted_at' ], { unique: true, name: 'uk_server_channel', }); - await queryInterface.addIndex(TABLE_NAME, ['status'], { name: 'idx_status' }); - await queryInterface.addIndex(TABLE_NAME, ['deleted_at'], { name: 'idx_deleted_at' }); + await queryInterface.addIndex(TABLE_NAME, [ 'status' ], { name: 'idx_status' }); + await queryInterface.addIndex(TABLE_NAME, [ 'deleted_at' ], { name: 'idx_deleted_at' }); }, down: async queryInterface => { diff --git a/database/migrations/20260715230000-create-wms-pack-task-video.js b/database/migrations/20260715230000-create-wms-pack-task-video.js index ceeeffa..32a871c 100644 --- a/database/migrations/20260715230000-create-wms-pack-task-video.js +++ b/database/migrations/20260715230000-create-wms-pack-task-video.js @@ -61,9 +61,9 @@ module.exports = { }, }); - await queryInterface.addIndex(TABLE_NAME, ['pack_task_id'], { name: 'idx_pack_task_id' }); - await queryInterface.addIndex(TABLE_NAME, ['camera_id'], { name: 'idx_camera_id' }); - await queryInterface.addIndex(TABLE_NAME, ['deleted_at'], { name: 'idx_deleted_at' }); + await queryInterface.addIndex(TABLE_NAME, [ 'pack_task_id' ], { name: 'idx_pack_task_id' }); + await queryInterface.addIndex(TABLE_NAME, [ 'camera_id' ], { name: 'idx_camera_id' }); + await queryInterface.addIndex(TABLE_NAME, [ 'deleted_at' ], { name: 'idx_deleted_at' }); }, down: async queryInterface => { diff --git a/database/migrations/20260717150000-add-camera-device-fields.js b/database/migrations/20260717150000-add-camera-device-fields.js index 6acfe27..46ce25e 100644 --- a/database/migrations/20260717150000-add-camera-device-fields.js +++ b/database/migrations/20260717150000-add-camera-device-fields.js @@ -43,7 +43,7 @@ module.exports = { }, down: async queryInterface => { - const columns = ['stream_type', 'serial_number', 'model', 'port', 'ip']; + const columns = [ 'stream_type', 'serial_number', 'model', 'port', 'ip' ]; for (const col of columns) { const tableInfo = await queryInterface.describeTable(TABLE_NAME); if (tableInfo[col]) { diff --git a/database/migrations/20260718170000-fix-supervisor-cs-permissions.js b/database/migrations/20260718170000-fix-supervisor-cs-permissions.js index 9f201d5..4a11bca 100644 --- a/database/migrations/20260718170000-fix-supervisor-cs-permissions.js +++ b/database/migrations/20260718170000-fix-supervisor-cs-permissions.js @@ -32,7 +32,7 @@ const OLD_PERMISSIONS = '[1,4,8,9,11,12,13,14,15,17,18,19,20,21,22,24,25,26,27,2 * @param {import('sequelize').QueryInterface} queryInterface */ module.exports.up = async queryInterface => { - const [result] = await queryInterface.sequelize.query( + const [ result ] = await queryInterface.sequelize.query( `UPDATE \`${TABLE}\` SET permissions = :permissions, updated_at = NOW() WHERE id = :id AND is_system = 1`, { replacements: { id: ROLE_ID, permissions: NEW_PERMISSIONS } } @@ -46,7 +46,7 @@ module.exports.up = async queryInterface => { * @param {import('sequelize').QueryInterface} queryInterface */ module.exports.down = async queryInterface => { - const [result] = await queryInterface.sequelize.query( + const [ result ] = await queryInterface.sequelize.query( `UPDATE \`${TABLE}\` SET permissions = :permissions, updated_at = NOW() WHERE id = :id AND is_system = 1`, { replacements: { id: ROLE_ID, permissions: OLD_PERMISSIONS } } diff --git a/database/migrations/20260720160000-add-print-qty-log-export-permissions.js b/database/migrations/20260720160000-add-print-qty-log-export-permissions.js index fdc0d75..b10acfe 100644 --- a/database/migrations/20260720160000-add-print-qty-log-export-permissions.js +++ b/database/migrations/20260720160000-add-print-qty-log-export-permissions.js @@ -21,7 +21,7 @@ const TABLE_PERMISSION = 'wms_permission'; const TABLE_ROLE = 'wms_role'; /** 需要授权的角色ID(财务以上:货主管理员 + 经理) */ -const TARGET_ROLE_IDS = [5, 8]; +const TARGET_ROLE_IDS = [ 5, 8 ]; /** @type {{path: string, name: string, meta_title: string, type: string}[]} */ const NEW_PERMISSIONS = [ @@ -149,7 +149,7 @@ module.exports.up = async queryInterface => { } console.log( - `[Migration] 面单余额导出权限迁移完成:` + + '[Migration] 面单余额导出权限迁移完成:' + `新增 ${NEW_PERMISSIONS.length} 条权限,授权 ${TARGET_ROLE_IDS.length} 个角色` ); }; diff --git a/database/migrations/20260725150000-add-print-computer-permissions.js b/database/migrations/20260725150000-add-print-computer-permissions.js index 0cdfe6f..3fb6c96 100644 --- a/database/migrations/20260725150000-add-print-computer-permissions.js +++ b/database/migrations/20260725150000-add-print-computer-permissions.js @@ -20,8 +20,8 @@ module.exports = { await queryInterface.bulkInsert('wms_permission', permissions); // 2. 查询刚插入的权限 ID - const [rows] = await queryInterface.sequelize.query( - `SELECT id FROM wms_permission WHERE path IN ('print_computer.list', 'print_computer.update', 'print_computer.delete') ORDER BY id` + const [ rows ] = await queryInterface.sequelize.query( + 'SELECT id FROM wms_permission WHERE path IN (\'print_computer.list\', \'print_computer.update\', \'print_computer.delete\') ORDER BY id' ); const ids = rows.map(r => r.id); if (ids.length !== 3) { @@ -29,7 +29,7 @@ module.exports = { } // 3. 授权客服主管及以上角色(排除 permissions='*' 的超级管理员角色) - const roleIds = [2, 5, 7, 8, 22, 26, 28, 29]; + const roleIds = [ 2, 5, 7, 8, 22, 26, 28, 29 ]; for (const permId of ids) { await queryInterface.sequelize.query(` UPDATE wms_role @@ -52,16 +52,16 @@ module.exports = { * @return {Promise} 无返回值 */ async down(queryInterface, Sequelize) { - const paths = ['print_computer.list', 'print_computer.update', 'print_computer.delete']; + const paths = [ 'print_computer.list', 'print_computer.update', 'print_computer.delete' ]; // 1. 查询权限 ID - const [rows] = await queryInterface.sequelize.query( + const [ rows ] = await queryInterface.sequelize.query( `SELECT id FROM wms_permission WHERE path IN ('${paths.join("','")}')` ); const ids = rows.map(r => r.id); // 2. 从角色权限中移除 - const roleIds = [2, 5, 7, 8, 22, 26, 28, 29]; + const roleIds = [ 2, 5, 7, 8, 22, 26, 28, 29 ]; for (const permId of ids) { await queryInterface.sequelize.query(` UPDATE wms_role diff --git a/database/migrations/20260725170000-add-recording-permissions.js b/database/migrations/20260725170000-add-recording-permissions.js index 4542c82..384bdad 100644 --- a/database/migrations/20260725170000-add-recording-permissions.js +++ b/database/migrations/20260725170000-add-recording-permissions.js @@ -19,8 +19,8 @@ module.exports = { await queryInterface.bulkInsert('wms_permission', permissions); // 2. 查询刚插入的权限 ID - const [rows] = await queryInterface.sequelize.query( - `SELECT id FROM wms_permission WHERE path IN ('print_computer.setRecording', 'print_computer.cancelRecording') ORDER BY id` + const [ rows ] = await queryInterface.sequelize.query( + 'SELECT id FROM wms_permission WHERE path IN (\'print_computer.setRecording\', \'print_computer.cancelRecording\') ORDER BY id' ); const ids = rows.map(r => r.id); if (ids.length !== 2) { @@ -28,7 +28,7 @@ module.exports = { } // 3. 授权客服主管及以上角色 - const roleIds = [2, 5, 7, 8, 22, 26, 28, 29]; + const roleIds = [ 2, 5, 7, 8, 22, 26, 28, 29 ]; for (const permId of ids) { await queryInterface.sequelize.query(` UPDATE wms_role @@ -51,14 +51,14 @@ module.exports = { * @return {Promise} 无返回值 */ async down(queryInterface, Sequelize) { - const paths = ['print_computer.setRecording', 'print_computer.cancelRecording']; + const paths = [ 'print_computer.setRecording', 'print_computer.cancelRecording' ]; - const [rows] = await queryInterface.sequelize.query( + const [ rows ] = await queryInterface.sequelize.query( `SELECT id FROM wms_permission WHERE path IN ('${paths.join("','")}')` ); const ids = rows.map(r => r.id); - const roleIds = [2, 5, 7, 8, 22, 26, 28, 29]; + const roleIds = [ 2, 5, 7, 8, 22, 26, 28, 29 ]; for (const permId of ids) { await queryInterface.sequelize.query(` UPDATE wms_role diff --git a/database/migrations/20260728120000-create-wms-after-sale-work-order.js b/database/migrations/20260728120000-create-wms-after-sale-work-order.js index 6854144..c6c6ab1 100644 --- a/database/migrations/20260728120000-create-wms-after-sale-work-order.js +++ b/database/migrations/20260728120000-create-wms-after-sale-work-order.js @@ -153,58 +153,58 @@ module.exports = { }); // 工单号唯一 - await queryInterface.addIndex(TABLE_NAME, ['work_order_no'], { + await queryInterface.addIndex(TABLE_NAME, [ 'work_order_no' ], { unique: true, name: 'uk_work_order_no', }); // 仓库隔离查询 - await queryInterface.addIndex(TABLE_NAME, ['warehouse_id'], { + await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id' ], { name: 'idx_warehouse_id', }); // 货主隔离查询 - await queryInterface.addIndex(TABLE_NAME, ['store_id'], { + await queryInterface.addIndex(TABLE_NAME, [ 'store_id' ], { name: 'idx_store_id', }); // 按业务类型+子类型+单据ID反查工单 - await queryInterface.addIndex(TABLE_NAME, ['business_type', 'business_sub_type', 'business_id'], { + await queryInterface.addIndex(TABLE_NAME, [ 'business_type', 'business_sub_type', 'business_id' ], { name: 'idx_business_type_subtype_id', }); // 按状态筛选 - await queryInterface.addIndex(TABLE_NAME, ['status'], { + await queryInterface.addIndex(TABLE_NAME, [ 'status' ], { name: 'idx_status', }); // 按处理人查询 - await queryInterface.addIndex(TABLE_NAME, ['assignee_id'], { + await queryInterface.addIndex(TABLE_NAME, [ 'assignee_id' ], { name: 'idx_assignee_id', }); // 按父工单查子工单 - await queryInterface.addIndex(TABLE_NAME, ['parent_work_order_id'], { + await queryInterface.addIndex(TABLE_NAME, [ 'parent_work_order_id' ], { name: 'idx_parent_work_order_id', }); // 按优先级排序 - await queryInterface.addIndex(TABLE_NAME, ['priority'], { + await queryInterface.addIndex(TABLE_NAME, [ 'priority' ], { name: 'idx_priority', }); // 按理赔状态筛选 - await queryInterface.addIndex(TABLE_NAME, ['claim_status'], { + await queryInterface.addIndex(TABLE_NAME, [ 'claim_status' ], { name: 'idx_claim_status', }); // 按时间排序 - await queryInterface.addIndex(TABLE_NAME, ['created_at'], { + await queryInterface.addIndex(TABLE_NAME, [ 'created_at' ], { name: 'idx_created_at', }); // 软删除查询优化 - await queryInterface.addIndex(TABLE_NAME, ['deleted_at'], { + await queryInterface.addIndex(TABLE_NAME, [ 'deleted_at' ], { name: 'idx_deleted_at', }); }, diff --git a/database/migrations/20260728130000-create-wms-after-sale-work-order-step.js b/database/migrations/20260728130000-create-wms-after-sale-work-order-step.js index 3564929..77e2b6f 100644 --- a/database/migrations/20260728130000-create-wms-after-sale-work-order-step.js +++ b/database/migrations/20260728130000-create-wms-after-sale-work-order-step.js @@ -88,22 +88,22 @@ module.exports = { }); // 按工单查所有步骤 - await queryInterface.addIndex(TABLE_NAME, ['work_order_id'], { + await queryInterface.addIndex(TABLE_NAME, [ 'work_order_id' ], { name: 'idx_work_order_id', }); // 按操作人反查 - await queryInterface.addIndex(TABLE_NAME, ['operator_id'], { + await queryInterface.addIndex(TABLE_NAME, [ 'operator_id' ], { name: 'idx_operator_id', }); // 软删除查询优化 - await queryInterface.addIndex(TABLE_NAME, ['deleted_at'], { + await queryInterface.addIndex(TABLE_NAME, [ 'deleted_at' ], { name: 'idx_deleted_at', }); // 同一工单下步骤序号唯一(含软删除) - await queryInterface.addIndex(TABLE_NAME, ['work_order_id', 'step_order', 'deleted_at'], { + await queryInterface.addIndex(TABLE_NAME, [ 'work_order_id', 'step_order', 'deleted_at' ], { unique: true, name: 'uk_work_order_step', }); diff --git a/database/migrations/20260729140000-add-waybill-list-indexes.js b/database/migrations/20260729140000-add-waybill-list-indexes.js index c5bdef9..049fad5 100644 --- a/database/migrations/20260729140000-add-waybill-list-indexes.js +++ b/database/migrations/20260729140000-add-waybill-list-indexes.js @@ -33,28 +33,28 @@ module.exports = { if (!indexNameSet.has('idx_warehouse_id_status')) { await queryInterface.addIndex(TABLE_NAME, { name: 'idx_warehouse_id_status', - fields: ['warehouse_id', 'status'], + fields: [ 'warehouse_id', 'status' ], }); } if (!indexNameSet.has('idx_logistics_code')) { await queryInterface.addIndex(TABLE_NAME, { name: 'idx_logistics_code', - fields: ['logistics_code'], + fields: [ 'logistics_code' ], }); } if (!indexNameSet.has('idx_logistics_interface_id')) { await queryInterface.addIndex(TABLE_NAME, { name: 'idx_logistics_interface_id', - fields: ['logistics_interface_id'], + fields: [ 'logistics_interface_id' ], }); } if (!indexNameSet.has('idx_warehouse_id_create_at')) { await queryInterface.addIndex(TABLE_NAME, { name: 'idx_warehouse_id_create_at', - fields: ['warehouse_id', 'create_at'], + fields: [ 'warehouse_id', 'create_at' ], }); } }, diff --git a/database/migrations/20260730000000-add-camera-username-password.js b/database/migrations/20260730000000-add-camera-username-password.js index bf89be1..2ba43b6 100644 --- a/database/migrations/20260730000000-add-camera-username-password.js +++ b/database/migrations/20260730000000-add-camera-username-password.js @@ -31,7 +31,7 @@ module.exports = { }, down: async queryInterface => { - const columns = ['password', 'username']; + const columns = [ 'password', 'username' ]; for (const col of columns) { const tableInfo = await queryInterface.describeTable(TABLE_NAME); if (tableInfo[col]) { diff --git a/database/migrations/20260730200000-backfill-wms-order-express-store-id.js b/database/migrations/20260730200000-backfill-wms-order-express-store-id.js index 401be9e..88df70b 100644 --- a/database/migrations/20260730200000-backfill-wms-order-express-store-id.js +++ b/database/migrations/20260730200000-backfill-wms-order-express-store-id.js @@ -11,7 +11,7 @@ const TABLE_NAME = 'wms_order_express'; */ async function backfill(queryInterface) { // 获取所有不同的 warehouse_id - const [warehouses] = await queryInterface.sequelize.query( + const [ warehouses ] = await queryInterface.sequelize.query( `SELECT DISTINCT warehouse_id FROM ${TABLE_NAME} WHERE store_id IS NULL AND warehouse_id IS NOT NULL` ); @@ -22,14 +22,14 @@ async function backfill(queryInterface) { for (const row of warehouses) { const warehouseId = row.warehouse_id; const tableTypes = [ - `wms_order_delivery_${warehouseId}`, // current(配送表 / 待处理表) - `wms_order_delivery_${warehouseId}_history`, // history - `wms_order_delivery_${warehouseId}_dispatch`, // dispatch + `wms_order_delivery_${warehouseId}`, // current(配送表 / 待处理表) + `wms_order_delivery_${warehouseId}_history`, // history + `wms_order_delivery_${warehouseId}_dispatch`, // dispatch ]; for (const deliveryTable of tableTypes) { try { - const [result] = await queryInterface.sequelize.query(` + const [ result ] = await queryInterface.sequelize.query(` UPDATE ${TABLE_NAME} e INNER JOIN ${deliveryTable} d ON e.order_id = d.id AND e.warehouse_id = d.warehouse_id SET e.store_id = d.store_id diff --git a/database/migrations/20260730210000-backfill-order-express-delivery-fields.js b/database/migrations/20260730210000-backfill-order-express-delivery-fields.js index 8736c81..46bff59 100644 --- a/database/migrations/20260730210000-backfill-order-express-delivery-fields.js +++ b/database/migrations/20260730210000-backfill-order-express-delivery-fields.js @@ -10,7 +10,7 @@ const TABLE_NAME = 'wms_order_express'; * @return {Promise} 无返回值。 */ async function backfill(queryInterface) { - const [warehouses] = await queryInterface.sequelize.query( + const [ warehouses ] = await queryInterface.sequelize.query( `SELECT DISTINCT warehouse_id FROM ${TABLE_NAME} WHERE delivery_order_code IS NULL AND warehouse_id IS NOT NULL` ); @@ -28,7 +28,7 @@ async function backfill(queryInterface) { for (const deliveryTable of tableTypes) { try { - const [result] = await queryInterface.sequelize.query(` + const [ result ] = await queryInterface.sequelize.query(` UPDATE ${TABLE_NAME} e INNER JOIN ${deliveryTable} d ON e.order_id = d.id AND e.warehouse_id = d.warehouse_id SET e.delivery_order_code = COALESCE(e.delivery_order_code, d.delivery_order_code), diff --git a/database/migrations/20260805120000-add-express-fields-to-inbox-group.js b/database/migrations/20260805120000-add-express-fields-to-inbox-group.js index c2ae5ec..926880e 100644 --- a/database/migrations/20260805120000-add-express-fields-to-inbox-group.js +++ b/database/migrations/20260805120000-add-express-fields-to-inbox-group.js @@ -29,7 +29,7 @@ module.exports = { } }, - down: async (queryInterface) => { + down: async queryInterface => { const tableInfo = await queryInterface.describeTable('wms_inbox_group'); if (tableInfo.express_interfaces) { diff --git a/database/migrations/20260805140000-add-inbox-indexes.js b/database/migrations/20260805140000-add-inbox-indexes.js index 558a0dc..974cf49 100644 --- a/database/migrations/20260805140000-add-inbox-indexes.js +++ b/database/migrations/20260805140000-add-inbox-indexes.js @@ -22,7 +22,7 @@ module.exports = { // 检查已有索引(通过尝试添加,重复则忽略) try { await queryInterface.addIndex('wms_inbox_message', { - fields: ['warehouse_id', 'group_id', 'created_at'], + fields: [ 'warehouse_id', 'group_id', 'created_at' ], name: 'idx_warehouse_group_created', }); console.log('[idx] wms_inbox_message.idx_warehouse_group_created 已创建'); @@ -37,7 +37,7 @@ module.exports = { // ── wms_inbox_group 索引 ── try { await queryInterface.addIndex('wms_inbox_group', { - fields: ['group_id'], + fields: [ 'group_id' ], name: 'idx_group_id', }); console.log('[idx] wms_inbox_group.idx_group_id 已创建'); @@ -51,7 +51,7 @@ module.exports = { try { await queryInterface.addIndex('wms_inbox_group', { - fields: ['warehouse_id', 'group_id'], + fields: [ 'warehouse_id', 'group_id' ], name: 'idx_warehouse_group_id', }); console.log('[idx] wms_inbox_group.idx_warehouse_group_id 已创建'); diff --git a/database/migrations/20260805150000-add-group-api-permissions.js b/database/migrations/20260805150000-add-group-api-permissions.js index 95cc4e6..0464573 100644 --- a/database/migrations/20260805150000-add-group-api-permissions.js +++ b/database/migrations/20260805150000-add-group-api-permissions.js @@ -13,13 +13,13 @@ module.exports = { // eslint-disable-next-line no-unused-vars async up(queryInterface, Sequelize) { const methods = [ - [495, 'inbox.group.list'], - [496, 'inbox.group.disable'], - [497, 'inbox.group.update'], - [498, 'inbox.group.messages'], + [ 495, 'inbox.group.list' ], + [ 496, 'inbox.group.disable' ], + [ 497, 'inbox.group.update' ], + [ 498, 'inbox.group.messages' ], ]; - for (const [id, method] of methods) { + for (const [ id, method ] of methods) { await queryInterface.sequelize.query(` INSERT INTO wms_permission (id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at) VALUES (${id}, '${method}', NULL, '${method}', NULL, 'API:${method}', NULL, 0, 0, NULL, 'api', 0, 1, NOW(), NOW()) diff --git a/database/migrations/20260806120000-add-ai-thoughts-to-inbox-message.js b/database/migrations/20260806120000-add-ai-thoughts-to-inbox-message.js index fe6095d..303c981 100644 --- a/database/migrations/20260806120000-add-ai-thoughts-to-inbox-message.js +++ b/database/migrations/20260806120000-add-ai-thoughts-to-inbox-message.js @@ -18,7 +18,7 @@ module.exports = { }, // eslint-disable-next-line no-unused-vars - down: async (queryInterface) => { + down: async queryInterface => { const tableInfo = await queryInterface.describeTable('wms_inbox_message'); if (tableInfo.ai_thoughts) { await queryInterface.removeColumn('wms_inbox_message', 'ai_thoughts'); diff --git a/database/migrations/20260807120000-add-express-code-to-wms-order-stockout.js b/database/migrations/20260807120000-add-express-code-to-wms-order-stockout.js index bace1e7..8c1386e 100644 --- a/database/migrations/20260807120000-add-express-code-to-wms-order-stockout.js +++ b/database/migrations/20260807120000-add-express-code-to-wms-order-stockout.js @@ -29,7 +29,7 @@ module.exports = { } }, - down: async (queryInterface) => { + down: async queryInterface => { const columns = await queryInterface.describeTable(TABLE); if (columns.express_code) { diff --git a/database/migrations/20260807130000-add-stockout-api-permissions.js b/database/migrations/20260807130000-add-stockout-api-permissions.js index 1dcb27c..f4b39d5 100644 --- a/database/migrations/20260807130000-add-stockout-api-permissions.js +++ b/database/migrations/20260807130000-add-stockout-api-permissions.js @@ -12,16 +12,16 @@ * 授权角色:经理(8)、仓库组-主管(26)、客服组-主管(28)、生产组-主管(29)、客服组-员工(30) */ module.exports = { - up: async (queryInterface) => { + up: async queryInterface => { // ===== 第一步:写入权限行 ===== const perms = [ - [504, 'storage.stockout.list', '出库单列表'], - [505, 'storage.stockout.listItems', '出库单明细'], - [506, 'storage.stockout.confirm', '出库单确认'], - [507, 'storage.stockout.updateExpress', '更新运单号'], + [ 504, 'storage.stockout.list', '出库单列表' ], + [ 505, 'storage.stockout.listItems', '出库单明细' ], + [ 506, 'storage.stockout.confirm', '出库单确认' ], + [ 507, 'storage.stockout.updateExpress', '更新运单号' ], ]; - for (const [id, method, desc] of perms) { + for (const [ id, method, desc ] of perms) { await queryInterface.sequelize.query(` INSERT INTO wms_permission (id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at) VALUES (${id}, '${method}', NULL, '${method}', NULL, 'API:${desc}', NULL, 0, 0, NULL, 'api', 0, 1, NOW(), NOW()) @@ -30,8 +30,8 @@ module.exports = { } // ===== 第二步:授权给客服组员工及以上角色 ===== - const roleIds = [8, 26, 28, 29, 30]; // 经理 + 各主管 + 客服组-员工 - const newPermIds = [504, 505, 506, 507]; + const roleIds = [ 8, 26, 28, 29, 30 ]; // 经理 + 各主管 + 客服组-员工 + const newPermIds = [ 504, 505, 506, 507 ]; for (const roleId of roleIds) { for (const permId of newPermIds) { @@ -50,9 +50,9 @@ module.exports = { } }, - down: async (queryInterface) => { + down: async queryInterface => { // 移除授权 - const roleIds = [8, 26, 28, 29, 30]; + const roleIds = [ 8, 26, 28, 29, 30 ]; const permIdStr = '504, 505, 506, 507'; for (const roleId of roleIds) { diff --git a/database/migrations/20260807140000-add-express-name-waybill-to-wms-order-stockout.js b/database/migrations/20260807140000-add-express-name-waybill-to-wms-order-stockout.js index b9c4912..158b5e0 100644 --- a/database/migrations/20260807140000-add-express-name-waybill-to-wms-order-stockout.js +++ b/database/migrations/20260807140000-add-express-name-waybill-to-wms-order-stockout.js @@ -38,7 +38,7 @@ module.exports = { } }, - down: async (queryInterface) => { + down: async queryInterface => { const columns = await queryInterface.describeTable(TABLE); if (columns.express_name) { diff --git a/database/migrations/20260808100000-add-delivery-code-store-index.js b/database/migrations/20260808100000-add-delivery-code-store-index.js index 6537aaf..8bcba00 100644 --- a/database/migrations/20260808100000-add-delivery-code-store-index.js +++ b/database/migrations/20260808100000-add-delivery-code-store-index.js @@ -3,7 +3,7 @@ module.exports = { async up(queryInterface, Sequelize) { // Query 3 关联查询:delivery_order_code + store_id 联合索引(最高频缺失索引) - await queryInterface.addIndex('wms_order_express', ['delivery_order_code', 'store_id'], { + await queryInterface.addIndex('wms_order_express', [ 'delivery_order_code', 'store_id' ], { name: 'idx_delivery_code_store', }); }, diff --git a/scripts/auth/grant-cs-up.js b/scripts/auth/grant-cs-up.js index fd4fbef..ff8e8ad 100644 --- a/scripts/auth/grant-cs-up.js +++ b/scripts/auth/grant-cs-up.js @@ -19,11 +19,11 @@ const mysql = projectRequire('mysql2/promise'); const CS_CHAIN_ROLES = [ { id: 30, code: '04', name: '客服组-员工' }, { id: 28, code: '05', name: '客服组-主管' }, - { id: 8, code: '2', name: '经理' }, + { id: 8, code: '2', name: '经理' }, ]; // 已有通配符 * 的角色,自动拥有所有权限,跳过 -const WILDCARD_ROLES = [7, 2]; +const WILDCARD_ROLES = [ 7, 2 ]; // ── 数据库连接 ── @@ -58,9 +58,9 @@ async function createConnection(env) { // ── 权限校验 ── async function getPermission(conn, permId) { - const [rows] = await conn.query( + const [ rows ] = await conn.query( 'SELECT id, name, meta_title, type, path FROM wms_permission WHERE id = ?', - [permId] + [ permId ] ); return rows[0] || null; } @@ -71,9 +71,9 @@ async function grantPermission(conn, permId, envLabel) { const results = []; for (const role of CS_CHAIN_ROLES) { - const [rows] = await conn.query( + const [ rows ] = await conn.query( 'SELECT id, role_code, role_name, permissions FROM wms_role WHERE id = ? AND deleted_at IS NULL', - [role.id] + [ role.id ] ); if (rows.length === 0) { @@ -94,7 +94,7 @@ async function grantPermission(conn, permId, envLabel) { try { perms = JSON.parse(record.permissions); } catch { - results.push({ role, status: 'error', msg: `permissions JSON 解析失败` }); + results.push({ role, status: 'error', msg: 'permissions JSON 解析失败' }); continue; } diff --git a/scripts/auth/revoke-cs-up.js b/scripts/auth/revoke-cs-up.js index d9bf651..e1431d3 100644 --- a/scripts/auth/revoke-cs-up.js +++ b/scripts/auth/revoke-cs-up.js @@ -19,7 +19,7 @@ const mysql = projectRequire('mysql2/promise'); const CS_CHAIN_ROLES = [ { id: 30, code: '04', name: '客服组-员工' }, { id: 28, code: '05', name: '客服组-主管' }, - { id: 8, code: '2', name: '经理' }, + { id: 8, code: '2', name: '经理' }, ]; // ── 数据库连接 ── @@ -58,9 +58,9 @@ async function revokePermission(conn, permId, envLabel) { const results = []; for (const role of CS_CHAIN_ROLES) { - const [rows] = await conn.query( + const [ rows ] = await conn.query( 'SELECT id, role_code, role_name, permissions FROM wms_role WHERE id = ? AND deleted_at IS NULL', - [role.id] + [ role.id ] ); if (rows.length === 0) { @@ -127,7 +127,7 @@ async function main() { console.log('═══════════════════════════════════════'); console.log(` 权限 ID: ${permIdNum}`); console.log(` 目标角色: ${CS_CHAIN_ROLES.map(r => `${r.name}(${r.id})`).join(' → ')}`); - console.log(` 通配符角色(跳过): id=7,2 (已有 *)`); + console.log(' 通配符角色(跳过): id=7,2 (已有 *)'); console.log('═══════════════════════════════════════\n'); // ── 开发环境:查询权限信息 ── @@ -139,9 +139,9 @@ async function main() { process.exit(1); } - const [permRows] = await devConn.query( + const [ permRows ] = await devConn.query( 'SELECT id, name, meta_title, type, path FROM wms_permission WHERE id = ?', - [permIdNum] + [ permIdNum ] ); if (permRows.length > 0) { diff --git a/test/app/service/systemMethods/order/pendingOrder.manualWaybill.log.test.js b/test/app/service/systemMethods/order/pendingOrder.manualWaybill.log.test.js index 31b806d..1cd7fc6 100644 --- a/test/app/service/systemMethods/order/pendingOrder.manualWaybill.log.test.js +++ b/test/app/service/systemMethods/order/pendingOrder.manualWaybill.log.test.js @@ -7,6 +7,7 @@ const PendingOrderService = require('../../../../../app/service/systemMethods/or * 创建 manualWaybill 操作日志回归测试上下文。 * * 仅覆盖 operationLog.createOperationLog 的 businessId 传入值。 + * @param options */ function createManualWaybillLogHarness(options = {}) { const calls = { @@ -103,14 +104,14 @@ function createManualWaybillLogHarness(options = {}) { }, }); - service.buildOrderWhere = (orderIds) => ({ + service.buildOrderWhere = orderIds => ({ id: { [ctx.app.Sequelize.Op.in]: orderIds }, warehouse_id: warehouseId, }); service.success = (msg, data) => ({ code: 0, msg, data }); - service.syncOrderIds = (payload) => { + service.syncOrderIds = payload => { calls.syncOrderIdsPayload = payload; return Promise.resolve(); }; From 3e7c9a7a10cc16f223c4a8dcd0b92f5ca4e7c2ae Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sun, 9 Aug 2026 00:23:42 +0800 Subject: [PATCH 183/550] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=20docs=20?= =?UTF-8?q?=E9=A1=B5=E9=9D=A2=20JS=20=E5=A4=B1=E6=95=88=20+=20=E5=85=A5?= =?UTF-8?q?=E5=BA=93=20locked=5Fquantity=20=E6=B5=81=E6=B0=B4=E8=A1=A5?= =?UTF-8?q?=E5=85=A8=20+=20stock=5Fstore=20=E6=9F=A5=E8=AF=A2=E6=9D=A1?= =?UTF-8?q?=E4=BB=B6=E8=A1=A5=E5=85=A8=20is=5Fvalid?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. docs.js: 修复模板字面量中 '\n' 被服务端解释为换行符导致客户端 JS SyntaxError,所有交互功能失效(搜索/发送按钮) 2. inbound_direct_log.js: batch_no 修正为 effectiveBatchNo;storage 表更新时补全 before_locked_quantity/after_locked_quantity;新增 stock_id 归属校验 3. stock_store.js: 多处查询/更新补全 is_valid='Y' 过滤条件,避免软删除/失效数据泄露或误操作 4. storage/entry.js: 入库完成时补全 storage 表 before_locked_quantity/after_locked_quantity 流水字段 --- app/controller/docs.js | 2 +- app/service/systems/inbound_direct_log.js | 16 +++++++++++++++- app/service/systems/stock_store.js | 14 +++++++++++++- app/service/systems/storage/entry.js | 8 ++++++++ 4 files changed, 37 insertions(+), 3 deletions(-) diff --git a/app/controller/docs.js b/app/controller/docs.js index 9fcc600..7967b14 100644 --- a/app/controller/docs.js +++ b/app/controller/docs.js @@ -2043,7 +2043,7 @@ Content-Type: application/json }).then(function(res) { return res.text().then(function(txt) { return { status: res.status, body: txt }; }); }).then(function(r) { - resultEl.textContent = 'HTTP ' + r.status + '\n' + r.body; + resultEl.textContent = 'HTTP ' + r.status + '\\n' + r.body; resultEl.className = r.status === 200 ? 'req-result success' : 'req-result error'; }).catch(function(err) { resultEl.textContent = '推送失败: ' + err.message; diff --git a/app/service/systems/inbound_direct_log.js b/app/service/systems/inbound_direct_log.js index 9062369..49556a1 100644 --- a/app/service/systems/inbound_direct_log.js +++ b/app/service/systems/inbound_direct_log.js @@ -1042,7 +1042,7 @@ class InboundDirectLogService extends Service { where: { space_id: spaceId, stock_id: stockId, - batch_no: batchNo, + batch_no: effectiveBatchNo, inventory_type: inventoryType, is_enabled: 1, delete_at: null, @@ -1054,10 +1054,20 @@ class InboundDirectLogService extends Service { let sId = null; let sBeforeQty = 0; let sAfterQty = 0; + let sBeforeLockedQty = 0; + let sAfterLockedQty = 0; if (sRecord) { + if (Number(sRecord.stock_id) !== Number(stockId)) { + throw new Error( + `入库库存归属冲突: storage_id=${sRecord.id} 当前 stock_id=${sRecord.stock_id}, ` + + `本次入库 stock_id=${stockId}, space_id=${spaceId}, batch_no=${effectiveBatchNo}` + ); + } sBeforeQty = Number(sRecord.quantity) || 0; sAfterQty = sBeforeQty + qty; + sBeforeLockedQty = Number(sRecord.locked_quantity) || 0; + sAfterLockedQty = sBeforeLockedQty; await ctx.model.Storage.update({ quantity: app.Sequelize.literal(`quantity + ${qty}`), @@ -1077,6 +1087,8 @@ class InboundDirectLogService extends Service { } else { sBeforeQty = 0; sAfterQty = qty; + sBeforeLockedQty = 0; + sAfterLockedQty = 0; const createdStorage = await ctx.model.Storage.create({ warehouse_id: warehouseId, @@ -1114,6 +1126,8 @@ class InboundDirectLogService extends Service { quantity: qty, before_quantity: sBeforeQty, after_quantity: sAfterQty, + before_locked_quantity: sBeforeLockedQty, + after_locked_quantity: sAfterLockedQty, batch_no: effectiveBatchNo, inventory_type: inventoryType, order_type: 'entry_order', diff --git a/app/service/systems/stock_store.js b/app/service/systems/stock_store.js index 9e377e4..aedcf07 100644 --- a/app/service/systems/stock_store.js +++ b/app/service/systems/stock_store.js @@ -1437,6 +1437,7 @@ class stockStoreService extends Service { warehouse_id: warehouseId, store_id: sourceData.store_id, deleted_at: null, + is_valid: 'Y', }, attributes: [ 'id' ], raw: true, @@ -1548,6 +1549,7 @@ class stockStoreService extends Service { goods_code: sourceData.goods_code, warehouse_id: warehouseId, is_valid: 'Y', + deleted_at: null, }, attributes: [ 'id' ], raw: true, @@ -2557,7 +2559,8 @@ class stockStoreService extends Service { where: { id: { [Op.in]: ids }, warehouse_id: warehouseId, - delete_at: null, + deleted_at: null, + is_valid: 'Y', }, attributes: [ 'id' ], }); @@ -2784,6 +2787,8 @@ class stockStoreService extends Service { } else { const StockWarehouseWhere = { warehouse_id: warehouseId, + deleted_at: null, + is_valid: 'Y', }; const StockStoreWhere = {}; if (store_id) { @@ -2905,6 +2910,7 @@ class stockStoreService extends Service { where: { warehouse_id: warehouseId, deleted_at: null, + is_valid: 'Y', id: warehouse_stock, }, attributes: [ @@ -2985,6 +2991,7 @@ class stockStoreService extends Service { where: { warehouse_id: warehouseId, deleted_at: null, + is_valid: 'Y', id, }, attributes: [ @@ -3078,6 +3085,7 @@ class stockStoreService extends Service { where: { id, deleted_at: null, + is_valid: 'Y', warehouse_id: ctx.user.store_id, }, transaction, @@ -3325,6 +3333,7 @@ class stockStoreService extends Service { store_id: owner_id, warehouse_id, deleted_at: null, + is_valid: 'Y', }; if (item_id) { @@ -3370,6 +3379,7 @@ class stockStoreService extends Service { [Op.and]: [ { id: { [Op.in]: ids } }, { deleted_at: null }, + { is_valid: 'Y' }, ], }; @@ -3678,6 +3688,7 @@ class stockStoreService extends Service { const whereCondition = { warehouse_id: warehouseId, deleted_at: null, + is_valid: 'Y', }; // 如果有传入store_id,则添加store_id条件 @@ -3923,6 +3934,7 @@ class stockStoreService extends Service { id: stock_id, warehouse_id: warehouseId, deleted_at: null, + is_valid: 'Y', }, attributes: [ 'id', 'item_code', 'item_name', 'sku_property', 'stock_unit', 'quantity', 'locked_quantity' ], raw: true, diff --git a/app/service/systems/storage/entry.js b/app/service/systems/storage/entry.js index add9722..260a70a 100644 --- a/app/service/systems/storage/entry.js +++ b/app/service/systems/storage/entry.js @@ -1553,10 +1553,14 @@ class EntryService extends Service { let storageId = null; let storageBeforeQty = 0; let storageAfterQty = 0; + let storageBeforeLockedQty = 0; + let storageAfterLockedQty = 0; if (storageRecord) { storageBeforeQty = Number(storageRecord.quantity) || 0; storageAfterQty = storageBeforeQty + planQty; + storageBeforeLockedQty = Number(storageRecord.locked_quantity) || 0; + storageAfterLockedQty = storageBeforeLockedQty; await ctx.model.Storage.update({ quantity: app.Sequelize.literal(`quantity + ${planQty}`), @@ -1573,6 +1577,8 @@ class EntryService extends Service { } else { storageBeforeQty = 0; storageAfterQty = planQty; + storageBeforeLockedQty = 0; + storageAfterLockedQty = 0; const createdStorage = await ctx.model.Storage.create({ warehouse_id: warehouseId, @@ -1608,6 +1614,8 @@ class EntryService extends Service { quantity: planQty, before_quantity: storageBeforeQty, after_quantity: storageAfterQty, + before_locked_quantity: storageBeforeLockedQty, + after_locked_quantity: storageAfterLockedQty, batch_no: batchNo, inventory_type: inventoryType, order_type: 'entry_order', From 0c2b0626582c7981ca57dd4b183092fd77f20daf Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sun, 9 Aug 2026 16:21:04 +0800 Subject: [PATCH 184/550] =?UTF-8?q?chore:=20=E7=A7=BB=E9=99=A4=E5=94=AE?= =?UTF-8?q?=E5=90=8E=E5=B7=A5=E5=8D=95=E6=A8=A1=E5=9D=97=20(after=5Fsale?= =?UTF-8?q?=5Fwork=5Forder)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 删除 model: after_sale_work_order.js, after_sale_work_order_step.js - 删除旧迁移: 20260728120000, 20260728130000 - 删除设计文档: after-sale-work-order-design.md, after-sale-api-design.md - 新增 DROP TABLE 迁移: 20260809120000 - 开发/生产环境均已执行 DROP 迁移,两表已删除 --- app/model/after_sale_work_order.js | 267 -------- app/model/after_sale_work_order_step.js | 99 --- database/designs/after-sale-api-design.md | 644 ------------------ .../designs/after-sale-work-order-design.md | 440 ------------ ...0-create-wms-after-sale-work-order-step.js | 115 ---- ...9120000-drop-wms-after-sale-work-order.js} | 167 +++-- 6 files changed, 104 insertions(+), 1628 deletions(-) delete mode 100644 app/model/after_sale_work_order.js delete mode 100644 app/model/after_sale_work_order_step.js delete mode 100644 database/designs/after-sale-api-design.md delete mode 100644 database/designs/after-sale-work-order-design.md delete mode 100644 database/migrations/20260728130000-create-wms-after-sale-work-order-step.js rename database/migrations/{20260728120000-create-wms-after-sale-work-order.js => 20260809120000-drop-wms-after-sale-work-order.js} (50%) diff --git a/app/model/after_sale_work_order.js b/app/model/after_sale_work_order.js deleted file mode 100644 index 90e0c89..0000000 --- a/app/model/after_sale_work_order.js +++ /dev/null @@ -1,267 +0,0 @@ -'use strict'; - -module.exports = app => { - const { STRING, BIGINT, INTEGER, TINYINT, TEXT, DATE, DECIMAL } = app.Sequelize; - - /** - * 售后工单业务类型定义 - * 外部可通过 require('./app/model/after_sale_work_order').BUSINESS_TYPES 访问 - * 增删业务类型或子类型只需修改此常量,无需 ALTER TABLE - */ - const BUSINESS_TYPES = { - waybill: { - label: '运单', - table: 'wms_order_express', - subtypes: { - intercept: '拦截', - urge: '催件', - damage: '破损', - lost: '丢件', - wrong_info: '信息错误', - }, - }, - order_delivery: { - label: '发货订单', - table: 'wms_order_delivery', - subtypes: { - mis_shipment: '错发', - missing_item: '少发', - wrong_sku: '错品', - quality_issue: '质量问题', - delivery_delay: '发货延迟', - }, - }, - entry_order: { - label: '入库单', - table: 'wms_entry_order', - subtypes: { - shortage: '少货', - damage: '破损', - wrong_sku: '错品', - quality_issue: '质量问题', - }, - }, - order_stockout: { - label: '出库单/退货出库单', - table: 'wms_order_stockout', - subtypes: { - return_issue: '退货异常', - wrong_outbound: '错发', - shortage: '少发', - }, - }, - receiving: { - label: '收货单', - table: 'wms_receiving', - subtypes: { - shortage: '少货', - damage: '破损', - quality_issue: '质量问题', - }, - }, - other: { - label: '其他', - table: null, - subtypes: { - general: '通用', - }, - }, - }; - - /** - * 根据 business_type 获取关联表名 - * @param {string} businessType 业务类型 - * @return {string|null} 关联表名 - */ - function getBusinessTable(businessType) { - return BUSINESS_TYPES[businessType]?.table || null; - } - - /** - * 校验 business_type + business_sub_type 组合是否合法 - * @param {string} businessType 业务类型 - * @param {string} businessSubType 业务子类型 - * @return {boolean} 是否合法 - */ - function isValidSubType(businessType, businessSubType) { - const def = BUSINESS_TYPES[businessType]; - return def && Object.prototype.hasOwnProperty.call(def.subtypes, businessSubType); - } - - const AfterSaleWorkOrder = app.model.define('after_sale_work_order', { - id: { - type: BIGINT(20).UNSIGNED, - primaryKey: true, - autoIncrement: true, - comment: '主键ID', - }, - warehouse_id: { - type: BIGINT(20).UNSIGNED, - allowNull: false, - comment: '仓库ID', - }, - store_id: { - type: BIGINT(20).UNSIGNED, - allowNull: false, - comment: '货主ID', - }, - work_order_no: { - type: STRING(50), - allowNull: false, - comment: '售后工单号,唯一', - }, - business_type: { - type: STRING(50), - allowNull: false, - comment: '关联业务类型', - }, - business_sub_type: { - type: STRING(50), - allowNull: false, - comment: '关联业务子类型', - }, - business_id: { - type: BIGINT(20).UNSIGNED, - allowNull: false, - comment: '关联业务单据主键ID(多态关联)', - }, - business_no: { - type: STRING(100), - allowNull: true, - comment: '关联业务单据号(冗余)', - }, - direction: { - type: TINYINT.UNSIGNED, - allowNull: false, - defaultValue: 0, - comment: '记账方向:0=未确定 1=入库 2=出库', - }, - status: { - type: TINYINT.UNSIGNED, - allowNull: false, - defaultValue: 0, - comment: '工单状态:0=待处理 1=处理中 2=已完成 3=已关闭 9=已取消', - }, - priority: { - type: TINYINT.UNSIGNED, - allowNull: false, - defaultValue: 50, - comment: '优先级:1~100,数字越大优先级越高', - }, - title: { - type: STRING(200), - allowNull: false, - comment: '工单标题/摘要', - }, - description: { - type: TEXT, - allowNull: true, - comment: '问题描述', - }, - creator_id: { - type: BIGINT(20).UNSIGNED, - allowNull: false, - comment: '创建人ID,关联 account.id;0 表示 AI 自动接待', - }, - creator_snapshot: { - type: TEXT, - allowNull: true, - comment: '创建人信息快照(JSON格式);AI创建时记录模型/会话信息', - }, - assignee_id: { - type: BIGINT(20).UNSIGNED, - allowNull: true, - comment: '当前处理人ID,关联 account.id', - }, - parent_work_order_id: { - type: BIGINT(20).UNSIGNED, - allowNull: true, - comment: '父工单ID,自关联本表;非空时表示子工单', - }, - current_step: { - type: TINYINT.UNSIGNED, - allowNull: false, - defaultValue: 1, - comment: '当前进度,值为当前正在处理的 step_order 序号', - }, - claim_needed: { - type: TINYINT.UNSIGNED, - allowNull: false, - defaultValue: 0, - comment: '是否需要理赔:0=不需要 1=需要', - }, - claim_amount: { - type: DECIMAL(12, 2), - allowNull: true, - defaultValue: 0.00, - comment: '理赔金额(元)', - }, - claim_status: { - type: TINYINT.UNSIGNED, - allowNull: false, - defaultValue: 0, - comment: '理赔状态:0=未理赔 1=已理赔(单笔结清) 2=月结', - }, - resolution: { - type: TEXT, - allowNull: true, - comment: '处理结果说明', - }, - resolved_at: { - type: DATE, - allowNull: true, - comment: '解决时间', - }, - created_at: { - type: DATE, - allowNull: false, - comment: '创建时间', - }, - updated_at: { - type: DATE, - allowNull: false, - comment: '更新时间', - }, - deleted_at: { - type: DATE, - allowNull: true, - comment: '软删除时间', - }, - }, { - tableName: 'wms_after_sale_work_order', - timestamps: true, - createdAt: 'created_at', - updatedAt: 'updated_at', - paranoid: true, - deletedAt: 'deleted_at', - comment: '售后工单主表', - }); - - AfterSaleWorkOrder.associate = () => { - // 自关联:父工单 → 子工单 - AfterSaleWorkOrder.hasMany(app.model.AfterSaleWorkOrder, { - foreignKey: 'parent_work_order_id', - sourceKey: 'id', - as: 'children', - }); - AfterSaleWorkOrder.belongsTo(app.model.AfterSaleWorkOrder, { - foreignKey: 'parent_work_order_id', - targetKey: 'id', - as: 'parent', - }); - - // 关联进度步骤表 - AfterSaleWorkOrder.hasMany(app.model.AfterSaleWorkOrderStep, { - foreignKey: 'work_order_id', - sourceKey: 'id', - as: 'steps', - }); - }; - - // 挂载业务类型常量及辅助函数到 Model - AfterSaleWorkOrder.BUSINESS_TYPES = BUSINESS_TYPES; - AfterSaleWorkOrder.getBusinessTable = getBusinessTable; - AfterSaleWorkOrder.isValidSubType = isValidSubType; - - return AfterSaleWorkOrder; -}; diff --git a/app/model/after_sale_work_order_step.js b/app/model/after_sale_work_order_step.js deleted file mode 100644 index dc66ba4..0000000 --- a/app/model/after_sale_work_order_step.js +++ /dev/null @@ -1,99 +0,0 @@ -'use strict'; - -module.exports = app => { - const { STRING, BIGINT, TINYINT, TEXT, DATE } = app.Sequelize; - - const AfterSaleWorkOrderStep = app.model.define('after_sale_work_order_step', { - id: { - type: BIGINT(20).UNSIGNED, - primaryKey: true, - autoIncrement: true, - comment: '主键ID', - }, - work_order_id: { - type: BIGINT(20).UNSIGNED, - allowNull: false, - comment: '工单ID,关联 wms_after_sale_work_order.id', - }, - step_order: { - type: TINYINT.UNSIGNED, - allowNull: false, - defaultValue: 1, - comment: '步骤序号(从1开始递增)', - }, - step_name: { - type: STRING(100), - allowNull: false, - comment: '步骤名称', - }, - step_status: { - type: TINYINT.UNSIGNED, - allowNull: false, - defaultValue: 0, - comment: '步骤状态:0=待开始 1=进行中 2=已完成 3=已跳过', - }, - operator_id: { - type: BIGINT(20).UNSIGNED, - allowNull: true, - comment: '操作员工ID,关联 account.id', - }, - operator_snapshot: { - type: TEXT, - allowNull: true, - comment: '操作人信息快照(JSON格式)', - }, - action: { - type: STRING(100), - allowNull: true, - comment: '操作动作描述', - }, - remark: { - type: TEXT, - allowNull: true, - comment: '处理备注', - }, - started_at: { - type: DATE, - allowNull: true, - comment: '步骤开始时间', - }, - completed_at: { - type: DATE, - allowNull: true, - comment: '步骤完成时间', - }, - created_at: { - type: DATE, - allowNull: false, - comment: '创建时间', - }, - updated_at: { - type: DATE, - allowNull: false, - comment: '更新时间', - }, - deleted_at: { - type: DATE, - allowNull: true, - comment: '软删除时间', - }, - }, { - tableName: 'wms_after_sale_work_order_step', - timestamps: true, - createdAt: 'created_at', - updatedAt: 'updated_at', - paranoid: true, - deletedAt: 'deleted_at', - comment: '售后工单进度步骤表', - }); - - AfterSaleWorkOrderStep.associate = () => { - AfterSaleWorkOrderStep.belongsTo(app.model.AfterSaleWorkOrder, { - foreignKey: 'work_order_id', - targetKey: 'id', - as: 'workOrder', - }); - }; - - return AfterSaleWorkOrderStep; -}; diff --git a/database/designs/after-sale-api-design.md b/database/designs/after-sale-api-design.md deleted file mode 100644 index b4a4bd3..0000000 --- a/database/designs/after-sale-api-design.md +++ /dev/null @@ -1,644 +0,0 @@ -# 售后工单 API 接口设计方案 - -> **状态**: ⏳ 等待人工审阅 -> **设计日期**: 2026-07-29 -> **设计人**: wms-db-agent -> **说明**: 本文档仅输出 API 接口设计方案,不直接修改程序代码。审阅通过后再执行实现。 - ---- - -## 一、模块概览 - -| 项目 | 说明 | -|------|------| -| 模块名 | `afterSale` | -| 接口路径 | `POST /system`,body 中 `method` 字段为 `afterSale.{方法名}` | -| 请求方式 | 全部 `POST`,参数放在 `body` 内 | -| 鉴权 | 除 `businessTypes` 外均需登录;写操作需鉴权 | - -### 文件规划 - -``` -app/service/systemMethods/afterSale.js ← 入口层(鉴权、参数校验、委托) -app/service/systems/afterSale.js ← 业务层(数据库操作、状态机) -methods/system.json ← API 文档(追加 afterSale group) -``` - -### 调用链路 - -``` -POST /system { method: "afterSale.list", ... } - → app/router.js - → app/service/system.js - → app/service/systemMethods/afterSale.js ← 鉴权 + 参数校验 - → app/service/systems/afterSale.js ← 业务逻辑 + DB操作 - → app/model/after_sale_work_order.js ← Sequelize Model - → app/model/after_sale_work_order_step.js -``` - ---- - -## 二、接口清单(共 13 个) - -| # | method | 描述 | 需登录 | 需鉴权 | -|---|--------|------|--------|--------| -| 1 | `afterSale.businessTypes` | 获取内置业务类型及子类型枚举 | ✗ | ✗ | -| 2 | `afterSale.list` | 工单列表(分页+筛选) | ✓ | ✗ | -| 3 | `afterSale.detail` | 工单详情(含步骤列表) | ✓ | ✗ | -| 4 | `afterSale.create` | 创建工单 | ✓ | ✓ | -| 5 | `afterSale.update` | 更新工单基本信息 | ✓ | ✓ | -| 6 | `afterSale.delete` | 删除工单(软删除) | ✓ | ✓ | -| 7 | `afterSale.assign` | 分配处理人 | ✓ | ✓ | -| 8 | `afterSale.complete` | 完成工单 | ✓ | ✓ | -| 9 | `afterSale.close` | 关闭工单 | ✓ | ✓ | -| 10 | `afterSale.cancel` | 取消工单 | ✓ | ✓ | -| 11 | `afterSale.stepStart` | 开始某个步骤 | ✓ | ✓ | -| 12 | `afterSale.stepComplete` | 完成某个步骤 | ✓ | ✓ | -| 13 | `afterSale.stepSkip` | 跳过某个步骤 | ✓ | ✓ | - ---- - -## 三、接口详细设计 - -### 3.1 `afterSale.businessTypes` — 获取业务类型枚举 - -```json -{ - "method": "afterSale.businessTypes", - "description": "获取售后工单内置业务类型及子类型枚举,供前端下拉选择使用。数据来源:app/model/after_sale_work_order.js 中的 BUSINESS_TYPES 常量。", - "isNeedAuth": false, - "isNeedLogin": false, - "params": [], - "response": [ - { - "name": "data", - "type": "object", - "description": "业务类型枚举,key 为 business_type,value 含 label、table、subtypes", - "example": { - "waybill": { - "label": "运单", - "table": "wms_order_express", - "subtypes": { - "intercept": "拦截", - "urge": "催件", - "damage": "破损", - "lost": "丢件", - "wrong_info": "信息错误" - } - }, - "order_delivery": { - "label": "发货订单", - "table": "wms_order_delivery", - "subtypes": { - "mis_shipment": "错发", - "missing_item": "少发", - "wrong_sku": "错品", - "quality_issue": "质量问题", - "delivery_delay": "发货延迟" - } - } - } - } - ] -} -``` - ---- - -### 3.2 `afterSale.list` — 工单列表 - -```json -{ - "method": "afterSale.list", - "description": "查询售后工单列表,支持分页与多条件筛选。仓库隔离(自动注入 warehouse_id)。", - "isNeedAuth": false, - "isNeedLogin": true, - "params": [ - { - "name": "pagination", - "type": "object", - "required": false, - "source": "body", - "description": "分页参数 { page, pageSize },默认 page=1 pageSize=20" - }, - { - "name": "where", - "type": "object", - "required": false, - "source": "body", - "description": "筛选条件,所有字段均为可选", - "children": [ - { "name": "workOrderNo", "type": "string", "description": "工单号(模糊搜索)" }, - { "name": "businessType", "type": "string", "description": "业务类型(等值),如 waybill" }, - { "name": "businessSubType","type": "string", "description": "业务子类型(等值),如 intercept" }, - { "name": "businessNo", "type": "string", "description": "关联业务单据号(模糊)" }, - { "name": "status", "type": "number", "description": "工单状态(等值):0/1/2/3/9" }, - { "name": "priorityMin", "type": "number", "description": "优先级下限(>=)" }, - { "name": "priorityMax", "type": "number", "description": "优先级上限(<=)" }, - { "name": "claimStatus", "type": "number", "description": "理赔状态(等值):0/1/2" }, - { "name": "assigneeId", "type": "number", "description": "处理人ID(等值)" }, - { "name": "creatorId", "type": "number", "description": "创建人ID(等值)" }, - { "name": "keyword", "type": "string", "description": "关键词:匹配工单号/标题/业务单据号" }, - { "name": "createdAtStart", "type": "string", "description": "创建时间起始(YYYY-MM-DD)" }, - { "name": "createdAtEnd", "type": "string", "description": "创建时间截止(YYYY-MM-DD)" } - ] - }, - { - "name": "sort", - "type": "object", - "required": false, - "source": "body", - "description": "排序 { field: 'priority'|'created_at'|'status', order: 'asc'|'desc' },默认 priority desc" - } - ], - "response": [ - { - "name": "list", - "type": "array", - "description": "工单列表(不含 description/resolution 长文本,减少传输量)", - "children": [ - { "name": "id", "type": "number", "description": "工单ID" }, - { "name": "work_order_no", "type": "string", "description": "工单号" }, - { "name": "warehouse_id", "type": "number", "description": "仓库ID" }, - { "name": "store_id", "type": "number", "description": "货主ID" }, - { "name": "business_type", "type": "string", "description": "业务类型" }, - { "name": "business_sub_type","type": "string", "description": "业务子类型" }, - { "name": "business_id", "type": "number", "description": "关联单据ID" }, - { "name": "business_no", "type": "string", "description": "关联单据号" }, - { "name": "direction", "type": "number", "description": "记账方向:0/1/2" }, - { "name": "status", "type": "number", "description": "工单状态:0/1/2/3/9" }, - { "name": "priority", "type": "number", "description": "优先级:1-100" }, - { "name": "title", "type": "string", "description": "工单标题" }, - { "name": "creator_id", "type": "number", "description": "创建人ID" }, - { "name": "creator_name", "type": "string", "description": "创建人姓名(JOIN account)" }, - { "name": "assignee_id", "type": "number", "description": "当前处理人ID" }, - { "name": "assignee_name", "type": "string", "description": "当前处理人姓名(JOIN account)" }, - { "name": "parent_work_order_id","type":"number","description": "父工单ID" }, - { "name": "current_step", "type": "number", "description": "当前进度步骤序号" }, - { "name": "claim_needed", "type": "number", "description": "是否理赔" }, - { "name": "claim_amount", "type": "number", "description": "理赔金额" }, - { "name": "claim_status", "type": "number", "description": "理赔状态" }, - { "name": "resolved_at", "type": "string", "description": "解决时间" }, - { "name": "created_at", "type": "string", "description": "创建时间" }, - { "name": "updated_at", "type": "string", "description": "更新时间" } - ] - }, - { "name": "pagination", "type": "object", "description": "分页信息 { page, pageSize, total, totalPages }" } - ] -} -``` - ---- - -### 3.3 `afterSale.detail` — 工单详情 - -```json -{ - "method": "afterSale.detail", - "description": "查询单个工单详情,含完整字段 + 步骤列表。仓库隔离。", - "isNeedAuth": false, - "isNeedLogin": true, - "params": [ - { - "name": "id", - "type": "number", - "required": true, - "source": "body", - "description": "工单ID(必填)" - } - ], - "response": [ - { - "name": "data", - "type": "object", - "description": "工单完整信息", - "children": [ - { "name": "id", "type": "number", "description": "工单ID" }, - { "name": "...", "type": "", "description": "同 list 接口所有字段" }, - { "name": "description", "type": "string", "description": "问题描述(详情接口返回)" }, - { "name": "resolution", "type": "string", "description": "处理结果说明(详情接口返回)" }, - { "name": "creator_snapshot", "type": "string", "description": "创建人信息快照" }, - { "name": "steps", "type": "array", "description": "步骤列表", - "children": [ - { "name": "id", "type": "number", "description": "步骤ID" }, - { "name": "step_order", "type": "number", "description": "步骤序号" }, - { "name": "step_name", "type": "string", "description": "步骤名称" }, - { "name": "step_status", "type": "number", "description": "步骤状态:0/1/2/3" }, - { "name": "operator_id", "type": "number", "description": "操作人ID" }, - { "name": "operator_name", "type": "string", "description": "操作人姓名" }, - { "name": "operator_snapshot","type": "string", "description": "操作人快照" }, - { "name": "action", "type": "string", "description": "操作动作" }, - { "name": "remark", "type": "string", "description": "处理备注" }, - { "name": "started_at", "type": "string", "description": "开始时间" }, - { "name": "completed_at", "type": "string", "description": "完成时间" }, - { "name": "created_at", "type": "string", "description": "创建时间" } - ] - }, - { "name": "children", "type": "array", "description": "子工单列表(如有)" }, - { "name": "parent", "type": "object", "description": "父工单简要信息(如有)" } - ] - } - ], - "errors": [ - { "code": "400", "description": "工单ID不能为空" }, - { "code": "404", "description": "工单不存在或无权访问" } - ] -} -``` - ---- - -### 3.4 `afterSale.create` — 创建工单 - -```json -{ - "method": "afterSale.create", - "description": "创建售后工单。自动生成工单号(AS+时间戳),自动设置 creator_id 和 warehouse_id。创建成功后返回工单详情。", - "isNeedAuth": true, - "isNeedLogin": true, - "params": [ - { - "name": "business_type", - "type": "string", - "required": true, - "source": "body", - "description": "业务类型(必填),如 waybill、order_delivery" - }, - { - "name": "business_sub_type", - "type": "string", - "required": true, - "source": "body", - "description": "业务子类型(必填),如 intercept、mis_shipment。需与 business_type 匹配(由 BUSINESS_TYPES 校验)" - }, - { - "name": "business_id", - "type": "number", - "required": true, - "source": "body", - "description": "关联业务单据主键ID(必填)" - }, - { - "name": "business_no", - "type": "string", - "required": false, - "source": "body", - "description": "关联业务单据号(可选,建议传入方便列表展示)" - }, - { - "name": "direction", - "type": "number", - "required": false, - "source": "body", - "description": "记账方向:1=入库 2=出库,默认 0(未确定)" - }, - { - "name": "priority", - "type": "number", - "required": false, - "source": "body", - "description": "优先级:1~100,默认 50。AI 创建时自动填入" - }, - { - "name": "title", - "type": "string", - "required": true, - "source": "body", - "description": "工单标题(必填)" - }, - { - "name": "description", - "type": "string", - "required": false, - "source": "body", - "description": "问题描述" - }, - { - "name": "claim_needed", - "type": "number", - "required": false, - "source": "body", - "description": "是否需要理赔:0=否 1=是,默认 0" - }, - { - "name": "claim_amount", - "type": "number", - "required": false, - "source": "body", - "description": "理赔金额,默认 0.00" - }, - { - "name": "parent_work_order_id", - "type": "number", - "required": false, - "source": "body", - "description": "父工单ID(子工单场景),不传则为根工单" - } - ], - "response": [ - { - "name": "data", - "type": "object", - "description": "创建成功的工单详情(同 detail 接口返回结构)" - } - ], - "errors": [ - { "code": "400", "description": "工单标题不能为空" }, - { "code": "400", "description": "业务类型或子类型不合法" }, - { "code": "400", "description": "父工单不存在" } - ] -} -``` - ---- - -### 3.5 `afterSale.update` — 更新工单基本信息 - -```json -{ - "method": "afterSale.update", - "description": "更新工单基本信息(标题、描述、优先级、记账方向、理赔信息)。不可修改 business_type/business_sub_type/business_id。仓库隔离。", - "isNeedAuth": true, - "isNeedLogin": true, - "params": [ - { "name": "id", "type": "number", "required": true, "source": "body", "description": "工单ID(必填)" }, - { "name": "title", "type": "string", "required": false, "source": "body", "description": "工单标题" }, - { "name": "description", "type": "string", "required": false, "source": "body", "description": "问题描述" }, - { "name": "priority", "type": "number", "required": false, "source": "body", "description": "优先级" }, - { "name": "direction", "type": "number", "required": false, "source": "body", "description": "记账方向" }, - { "name": "claim_needed", "type": "number", "required": false, "source": "body", "description": "是否需要理赔" }, - { "name": "claim_amount", "type": "number", "required": false, "source": "body", "description": "理赔金额" }, - { "name": "claim_status", "type": "number", "required": false, "source": "body", "description": "理赔状态" } - ], - "response": [ - { "name": "data", "type": "object", "description": "更新后的工单详情" } - ], - "errors": [ - { "code": "400", "description": "工单ID不能为空" }, - { "code": "404", "description": "工单不存在或无权操作" } - ] -} -``` - ---- - -### 3.6 `afterSale.delete` — 删除工单 - -```json -{ - "method": "afterSale.delete", - "description": "软删除工单及其所有步骤。仅待处理(0)和已取消(9)状态的工单可删除。仓库隔离。", - "isNeedAuth": true, - "isNeedLogin": true, - "params": [ - { "name": "id", "type": "number", "required": true, "source": "body", "description": "工单ID(必填)" } - ], - "response": [], - "errors": [ - { "code": "400", "description": "工单ID不能为空" }, - { "code": "400", "description": "处理中的工单不可删除" }, - { "code": "404", "description": "工单不存在或无权操作" } - ] -} -``` - ---- - -### 3.7 `afterSale.assign` — 分配处理人 - -```json -{ - "method": "afterSale.assign", - "description": "将工单分配给指定处理人。仅待处理(0)状态的工单可分配。分配后自动流转至处理中(1)。仓库隔离。", - "isNeedAuth": true, - "isNeedLogin": true, - "params": [ - { "name": "id", "type": "number", "required": true, "source": "body", "description": "工单ID(必填)" }, - { "name": "assignee_id", "type": "number", "required": true, "source": "body", "description": "处理人ID(必填)" }, - { "name": "remark", "type": "string", "required": false, "source": "body", "description": "分配备注" } - ], - "response": [ - { "name": "data", "type": "object", "description": "更新后的工单详情" } - ], - "errors": [ - { "code": "400", "description": "工单ID不能为空" }, - { "code": "400", "description": "处理人ID不能为空" }, - { "code": "400", "description": "当前状态不可分配(非待处理状态)" } - ] -} -``` - ---- - -### 3.8 `afterSale.complete` — 完成工单 - -```json -{ - "method": "afterSale.complete", - "description": "完成工单。仅处理中(1)状态且所有步骤已完成/跳过的工单可完成。完成后自动设置 resolved_at。仓库隔离。", - "isNeedAuth": true, - "isNeedLogin": true, - "params": [ - { "name": "id", "type": "number", "required": true, "source": "body", "description": "工单ID(必填)" }, - { "name": "resolution", "type": "string", "required": false, "source": "body", "description": "处理结果说明" } - ], - "response": [ - { "name": "data", "type": "object", "description": "更新后的工单详情" } - ], - "errors": [ - { "code": "400", "description": "工单ID不能为空" }, - { "code": "400", "description": "当前状态不可完成(非处理中状态)" }, - { "code": "400", "description": "仍有步骤未完成,请先完成所有步骤" } - ] -} -``` - ---- - -### 3.9 `afterSale.close` — 关闭工单 - -```json -{ - "method": "afterSale.close", - "description": "关闭工单。仅已完成(2)状态的工单可关闭。仓库隔离。", - "isNeedAuth": true, - "isNeedLogin": true, - "params": [ - { "name": "id", "type": "number", "required": true, "source": "body", "description": "工单ID(必填)" }, - { "name": "remark", "type": "string", "required": false, "source": "body", "description": "关闭备注" } - ], - "response": [ - { "name": "data", "type": "object", "description": "更新后的工单详情" } - ], - "errors": [ - { "code": "400", "description": "工单ID不能为空" }, - { "code": "400", "description": "当前状态不可关闭(非已完成状态)" } - ] -} -``` - ---- - -### 3.10 `afterSale.cancel` — 取消工单 - -```json -{ - "method": "afterSale.cancel", - "description": "取消工单。仅待处理(0)和处理中(1)状态的工单可取消。仓库隔离。", - "isNeedAuth": true, - "isNeedLogin": true, - "params": [ - { "name": "id", "type": "number", "required": true, "source": "body", "description": "工单ID(必填)" }, - { "name": "remark", "type": "string", "required": false, "source": "body", "description": "取消原因" } - ], - "response": [ - { "name": "data", "type": "object", "description": "更新后的工单详情" } - ], - "errors": [ - { "code": "400", "description": "工单ID不能为空" }, - { "code": "400", "description": "当前状态不可取消" } - ] -} -``` - ---- - -### 3.11 `afterSale.stepStart` — 开始步骤 - -```json -{ - "method": "afterSale.stepStart", - "description": "开始处理某个步骤。将步骤状态设为进行中(1),同时更新主表 current_step。同一时刻只允许一个步骤处于进行中。仓库隔离。", - "isNeedAuth": true, - "isNeedLogin": true, - "params": [ - { "name": "step_id", "type": "number", "required": true, "source": "body", "description": "步骤ID(必填,wms_after_sale_work_order_step.id)" }, - { "name": "remark", "type": "string", "required": false, "source": "body", "description": "备注" } - ], - "response": [ - { "name": "data", "type": "object", "description": "更新后的步骤信息" } - ], - "errors": [ - { "code": "400", "description": "步骤ID不能为空" }, - { "code": "400", "description": "已有其他步骤正在进行中" }, - { "code": "400", "description": "步骤当前状态不可开始" } - ] -} -``` - ---- - -### 3.12 `afterSale.stepComplete` — 完成步骤 - -```json -{ - "method": "afterSale.stepComplete", - "description": "完成某个步骤。将步骤状态设为已完成(2),记录操作人和完成时间。仓库隔离。", - "isNeedAuth": true, - "isNeedLogin": true, - "params": [ - { "name": "step_id", "type": "number", "required": true, "source": "body", "description": "步骤ID(必填)" }, - { "name": "action", "type": "string", "required": false, "source": "body", "description": "操作动作描述" }, - { "name": "remark", "type": "string", "required": false, "source": "body", "description": "处理备注" } - ], - "response": [ - { "name": "data", "type": "object", "description": "更新后的步骤信息" } - ], - "errors": [ - { "code": "400", "description": "步骤ID不能为空" }, - { "code": "400", "description": "步骤当前状态不可完成(非进行中状态)" } - ] -} -``` - ---- - -### 3.13 `afterSale.stepSkip` — 跳过步骤 - -```json -{ - "method": "afterSale.stepSkip", - "description": "跳过某个步骤。将步骤状态设为已跳过(3)。仓库隔离。", - "isNeedAuth": true, - "isNeedLogin": true, - "params": [ - { "name": "step_id", "type": "number", "required": true, "source": "body", "description": "步骤ID(必填)" }, - { "name": "remark", "type": "string", "required": false, "source": "body", "description": "跳过原因" } - ], - "response": [ - { "name": "data", "type": "object", "description": "更新后的步骤信息" } - ], - "errors": [ - { "code": "400", "description": "步骤ID不能为空" }, - { "code": "400", "description": "步骤当前状态不可跳过" } - ] -} -``` - ---- - -## 四、状态机约束(服务端校验规则) - -| 操作 | 允许的当前状态 | 目标状态 | -|------|-------------|---------| -| `create` | — | `status=0`, `current_step=1` | -| `assign` | `status=0` | `status=1` | -| `delete` | `status=0` 或 `status=9` | 软删除 | -| `complete` | `status=1` + 所有步骤已完成/跳过 | `status=2`, `resolved_at=NOW()` | -| `close` | `status=2` | `status=3` | -| `cancel` | `status=0` 或 `status=1` | `status=9` | -| `stepStart` | `step_status=0` + 无其他进行中步骤 | `step_status=1`, `current_step=该step_order` | -| `stepComplete` | `step_status=1` | `step_status=2` | -| `stepSkip` | `step_status=0` | `step_status=3` | - ---- - -## 五、methods/system.json 追加格式 - -在 `methods.system.json` 的 `methods.groups` 数组末尾追加: - -```json -{ - "groupName": "售后工单模块", - "module": "afterSale", - "list": [ - { "method": "afterSale.businessTypes", ... }, - { "method": "afterSale.list", ... }, - { "method": "afterSale.detail", ... }, - { "method": "afterSale.create", ... }, - { "method": "afterSale.update", ... }, - { "method": "afterSale.delete", ... }, - { "method": "afterSale.assign", ... }, - { "method": "afterSale.complete", ... }, - { "method": "afterSale.close", ... }, - { "method": "afterSale.cancel", ... }, - { "method": "afterSale.stepStart", ... }, - { "method": "afterSale.stepComplete", ... }, - { "method": "afterSale.stepSkip", ... } - ] -} -``` - -(完整 JSON 定义见第三节各接口) - ---- - -## 六、后续实现计划(审阅通过后执行) - -| 步骤 | 文件 | 说明 | -|------|------|------| -| 1 | `app/service/systems/afterSale.js` | 业务层:数据库操作、状态机、工单号生成 | -| 2 | `app/service/systemMethods/afterSale.js` | 入口层:鉴权配置、参数校验、委托调用 | -| 3 | `methods/system.json` | 追加 `afterSale` group 的 13 个 method 文档 | -| 4 | `methods/changes/afterSale-20260729.json` | 接口变更记录 | - ---- - -## 七、待确认事项 - -- [ ] **1. 模块名**:`afterSale` 是否合适?备选 `asWorkOrder`、`afterSaleWorkOrder` -- [ ] **2. 步骤操作是否需要独立接口**:`stepStart/stepComplete/stepSkip` 三个独立接口 vs 合并为一个 `stepUpdate`(传 status 参数) -- [ ] **3. `businessTypes` 接口免登录**:是否允许未登录用户获取业务类型枚举? -- [ ] **4. 步骤创建时机**:步骤是创建工单时自动初始化一组,还是由前端手动逐条添加? -- [ ] **5. 是否需要批量操作**:批量分配、批量关闭? -- [ ] **6. 是否需要操作日志**:是否复用 `operation_log` 记录关键状态变更? diff --git a/database/designs/after-sale-work-order-design.md b/database/designs/after-sale-work-order-design.md deleted file mode 100644 index 13d2914..0000000 --- a/database/designs/after-sale-work-order-design.md +++ /dev/null @@ -1,440 +0,0 @@ -# 售后工单表设计方案 - -> **状态**: ✅ 已落库(开发环境) -> **设计日期**: 2026-07-28(v4 定稿:新增 parent_work_order_id 支持主子工单) -> **设计人**: wms-db-agent -> **说明**: 本文档仅输出设计方案,不执行落库。审阅通过后再生成迁移文件。 - ---- - -## 一、需求概述 - -1. **主表**:售后工单单表,支持灵活绑定多种业务单据(运单、订单、入库单、退货单等),通过 `business_type` + `business_sub_type` + `business_id` 三级多态关联 -2. **副表**:进度步骤处理表,记录每一步的操作员工、动作、备注(步骤不预设模板,由业务逻辑动态创建) -3. **状态流转**:工单整体状态 + 主表 `current_step` 进度 + 步骤级状态三层次 -4. **简单记账**:记录是"进"还是"出" -5. **理赔追踪**:是否需要理赔、理赔金额、理赔结算状态 -6. **附件关联**:通过现有 `wms_file_reference` 表关联附件/图片 - ---- - -## 二、表结构设计 - -### 2.1 主表:`wms_after_sale_work_order`(售后工单主表) - -| # | 字段名 | 类型 | 必填 | 默认值 | 说明 | -|---|--------|------|------|--------|------| -| 1 | `id` | `BIGINT(20) UNSIGNED` | Y | AUTO | 主键ID | -| 2 | `warehouse_id` | `BIGINT(20) UNSIGNED` | Y | — | 仓库ID | -| 3 | `store_id` | `BIGINT(20) UNSIGNED` | Y | — | 货主ID | -| 4 | `work_order_no` | `VARCHAR(50)` | Y | — | 售后工单号,唯一,格式 `AS` + 时间戳(如 AS202607280001) | -| 5 | `business_type` | `VARCHAR(50)` | Y | — | 关联业务类型,见 §3.1 枚举及 §五 Model 内置定义 | -| 6 | `business_sub_type` | `VARCHAR(50)` | Y | — | 关联业务子类型,如运单下的 `intercept`(拦截)、订单下的 `mis_shipment`(错发),见 §五 | -| 7 | `business_id` | `BIGINT(20) UNSIGNED` | Y | — | 关联业务单据主键ID(多态关联) | -| 8 | `business_no` | `VARCHAR(100)` | N | — | 关联业务单据号(冗余,方便列表展示) | -| 9 | `direction` | `TINYINT UNSIGNED` | Y | 0 | 记账方向:`1`=入库(退货入库/换货入库),`2`=出库(补发/换货出库),`0`=未确定 | -| 10 | `status` | `TINYINT UNSIGNED` | Y | 0 | 工单状态,见 §3.4 状态机 | -| 11 | `priority` | `TINYINT UNSIGNED` | Y | 50 | 优先级:`1`~`100`,数字越大优先级越高,由客服接待或AI自动识别填入 | -| 12 | `title` | `VARCHAR(200)` | Y | — | 工单标题/摘要 | -| 13 | `description` | `TEXT` | N | — | 问题描述 | -| 14 | `creator_id` | `BIGINT(20) UNSIGNED` | Y | — | 创建人ID,关联 `account.id`;`0` 表示 AI 自动接待 | -| 15 | `creator_snapshot` | `TEXT` | N | — | 创建人信息快照(JSON格式);AI创建时记录模型/会话信息 | -| 16 | `assignee_id` | `BIGINT(20) UNSIGNED` | N | — | 当前处理人ID,关联 `account.id` | -| 17 | `parent_work_order_id` | `BIGINT(20) UNSIGNED` | N | — | 父工单ID,自关联 `wms_after_sale_work_order.id`;非空时表示当前工单为子工单 | -| 18 | `current_step` | `TINYINT UNSIGNED` | Y | 1 | **当前进度**(位于主表),值为当前正在处理的 `step_order` 序号 | -| 19 | `claim_needed` | `TINYINT UNSIGNED` | Y | 0 | 是否需要理赔:`0`=不需要,`1`=需要 | -| 20 | `claim_amount` | `DECIMAL(12,2)` | N | 0.00 | 理赔金额(元),精度2位小数 | -| 21 | `claim_status` | `TINYINT UNSIGNED` | Y | 0 | 理赔状态:`0`=未理赔,`1`=已理赔(单笔结清),`2`=月结 | -| 22 | `resolution` | `TEXT` | N | — | 处理结果说明 | -| 23 | `resolved_at` | `DATETIME` | N | — | 解决时间 | -| 24 | `created_at` | `DATETIME` | Y | `CURRENT_TIMESTAMP` | 创建时间 | -| 25 | `updated_at` | `DATETIME` | Y | `CURRENT_TIMESTAMP ON UPDATE` | 更新时间 | -| 26 | `deleted_at` | `DATETIME` | N | — | 软删除时间 | - -**索引设计**: - -| 索引名 | 字段 | 类型 | 说明 | -|--------|------|------|------| -| `PRIMARY` | `id` | 主键 | — | -| `uk_work_order_no` | `work_order_no` | 唯一 | 工单号唯一 | -| `idx_warehouse_id` | `warehouse_id` | 普通 | 按仓库查询 | -| `idx_store_id` | `store_id` | 普通 | 按货主查询 | -| `idx_business_type_subtype_id` | `business_type, business_sub_type, business_id` | 普通 | 按业务类型+子类型+单据ID反查工单 | -| `idx_status` | `status` | 普通 | 按状态筛选 | -| `idx_assignee_id` | `assignee_id` | 普通 | 按处理人查询 | -| `idx_parent_work_order_id` | `parent_work_order_id` | 普通 | 按父工单查所有子工单 | -| `idx_priority` | `priority` | 普通 | 按优先级排序 | -| `idx_claim_status` | `claim_status` | 普通 | 按理赔状态筛选 | -| `idx_created_at` | `created_at` | 普通 | 按时间排序 | -| `idx_deleted_at` | `deleted_at` | 普通 | 软删除查询 | - ---- - -### 2.2 副表:`wms_after_sale_work_order_step`(售后工单进度步骤表) - -| # | 字段名 | 类型 | 必填 | 默认值 | 说明 | -|---|--------|------|------|--------|------| -| 1 | `id` | `BIGINT(20) UNSIGNED` | Y | AUTO | 主键ID | -| 2 | `work_order_id` | `BIGINT(20) UNSIGNED` | Y | — | 工单ID,关联 `wms_after_sale_work_order.id` | -| 3 | `step_order` | `TINYINT UNSIGNED` | Y | 1 | 步骤序号(从1开始递增) | -| 4 | `step_name` | `VARCHAR(100)` | Y | — | 步骤名称 | -| 5 | `step_status` | `TINYINT UNSIGNED` | Y | 0 | 步骤状态:`0`=待开始,`1`=进行中,`2`=已完成,`3`=已跳过 | -| 6 | `operator_id` | `BIGINT(20) UNSIGNED` | N | — | 操作员工ID,关联 `account.id` | -| 7 | `operator_snapshot` | `TEXT` | N | — | 操作人信息快照(JSON格式) | -| 8 | `action` | `VARCHAR(100)` | N | — | 操作动作描述(如"核实问题属实,安排退货入库") | -| 9 | `remark` | `TEXT` | N | — | 处理备注 | -| 10 | `started_at` | `DATETIME` | N | — | 步骤开始时间 | -| 11 | `completed_at` | `DATETIME` | N | — | 步骤完成时间 | -| 12 | `created_at` | `DATETIME` | Y | `CURRENT_TIMESTAMP` | 创建时间 | -| 13 | `updated_at` | `DATETIME` | Y | `CURRENT_TIMESTAMP ON UPDATE` | 更新时间 | -| 14 | `deleted_at` | `DATETIME` | N | — | 软删除时间 | - -**索引设计**: - -| 索引名 | 字段 | 类型 | 说明 | -|--------|------|------|------| -| `PRIMARY` | `id` | 主键 | — | -| `idx_work_order_id` | `work_order_id` | 普通 | 按工单查所有步骤 | -| `idx_operator_id` | `operator_id` | 普通 | 按操作人反查 | -| `idx_deleted_at` | `deleted_at` | 普通 | 软删除查询 | -| `uk_work_order_step` | `work_order_id, step_order, deleted_at` | 唯一 | 同一工单下步骤序号唯一(含软删除) | - ---- - -## 三、枚举定义 - -### 3.1 `business_type` 与 `business_sub_type`(业务类型及子类型) - -业务类型和子类型由 Model 文件 `app/model/after_sale_work_order.js` 中的 `BUSINESS_TYPES` 常量统一定义。数据库层面使用 `VARCHAR(50)` 存储,方便扩展。 - -#### 内置业务类型总览 - -| business_type | 业务名称 | 关联表 | 子类型 (business_sub_type) | -|---------------|---------|--------|---------------------------| -| `waybill` | 运单 | `wms_order_express` | `intercept`(拦截)、`urge`(催件)、`damage`(破损)、`lost`(丢件)、`wrong_info`(信息错误) | -| `order_delivery` | 发货订单 | `wms_order_delivery` | `mis_shipment`(错发)、`missing_item`(少发)、`wrong_sku`(错品)、`quality_issue`(质量问题)、`delivery_delay`(发货延迟) | -| `entry_order` | 入库单 | `wms_entry_order` | `shortage`(少货)、`damage`(破损)、`wrong_sku`(错品)、`quality_issue`(质量问题) | -| `order_stockout` | 出库单/退货出库单 | `wms_order_stockout` | `return_issue`(退货异常)、`wrong_outbound`(错发)、`shortage`(少发) | -| `receiving` | 收货单 | `wms_receiving` | `shortage`(少货)、`damage`(破损)、`quality_issue`(质量问题) | -| `other` | 其他 | — | `general`(通用) | - -> **扩展方式**:在 Model 的 `BUSINESS_TYPES` 常量中增删条目即可,无需 ALTER TABLE。外部代码通过 `require` Model 文件读取。 - -### 3.2 `priority`(优先级) - -``` -1 ~ 100 的整数,数字越大优先级越高。 -由客服接待手动填入,或由 AI 根据问题描述自动识别并填入。 -默认值 50(中等优先级)。 -``` - -### 3.3 `direction`(记账方向) - -``` -0 — 未确定 -1 — 入库(IN):退货入库 / 换货入库 / 赔付补货入库 -2 — 出库(OUT):补发出库 / 换货出库 / 退款退货出库 -``` - -> 与 `stock_transaction.transaction_type`(`INBOUND`/`OUTBOUND`)语义对齐。 - -### 3.4 `status`(工单状态) - -``` -0 — 待处理 (工单刚创建,尚未分配) -1 — 处理中 (已分配处理人,正在推进) -2 — 已完成 (问题已解决,全部步骤完成) -3 — 已关闭 (问题关闭,不再跟进) -9 — 已取消 (工单作废) -``` - -### 3.5 `claim_status`(理赔状态) - -``` -0 — 未理赔 (不需要理赔,或尚未发起理赔) -1 — 已理赔 (单笔已结清,理赔款项已到账) -2 — 月结 (纳入月度结算,按月统一对账打款) -``` - -### 3.6 `step_status`(步骤状态) - -``` -0 — 待开始 (步骤尚未激活) -1 — 进行中 (当前正在处理的步骤) -2 — 已完成 (步骤已处理完毕) -3 — 已跳过 (该步骤被跳过,不适用) -``` - -### 3.7 `creator_id` 特殊值 - -``` -0 — AI 自动接待(非员工账号创建) -> 0 — 对应 account.id,人工客服/员工创建 -``` - -> 当 `creator_id = 0` 时,`creator_snapshot` 可记录 AI 模型标识及会话 ID 等元信息。 - ---- - -## 四、状态流转设计 - -### 4.1 工单级别状态机 - -``` - ┌──────────────────────────────────┐ - │ │ - ┌───┴──────┐ ┌───┴──────┐ - 创建工单 ───→ │ 待处理(0) │ ──── 分配处理人 ───→ │ 处理中(1) │ - └───┬──────┘ └───┬──────┘ - │ │ - │ 取消 │ 全部步骤完成 - ↓ ↓ - ┌───┴──────┐ ┌───┴──────┐ - │ 已取消(9) │ │ 已完成(2) │ - └──────────┘ └───┬──────┘ - │ - │ 关闭 - ↓ - ┌───┴──────┐ - │ 已关闭(3) │ - └──────────┘ -``` - -**流转规则**: - -| 当前状态 | 允许流转到 | 触发条件 | -|----------|-----------|----------| -| `0-待处理` | `1-处理中` | 分配处理人 | -| `0-待处理` | `9-已取消` | 主动取消 | -| `1-处理中` | `2-已完成` | 所有步骤均标记为已完成 | -| `1-处理中` | `9-已取消` | 主动取消 | -| `2-已完成` | `3-已关闭` | 确认关闭 | -| `3-已关闭` | — | 终态,不可流转 | - -### 4.2 步骤级别状态机 - -``` - ┌──────────────────────────────────┐ - │ │ - ┌───┴──────┐ ┌───┴──────┐ - 步骤创建 ───→ │ 待开始(0) │ ──── 开始处理 ───→ │ 进行中(1) │ - └───┬──────┘ └───┬──────┘ - │ │ - │ 跳过 │ 完成 - ↓ ↓ - ┌───┴──────┐ ┌───┴──────┐ - │ 已跳过(3) │ │ 已完成(2) │ - └──────────┘ └──────────┘ -``` - -**约束**: -- 同一工单下,同一时刻最多只有 1 个步骤处于 `进行中(1)` -- 步骤按 `step_order` 顺序流转,但允许跳过中间步骤 -- 工单进度由主表 `current_step` 字段追踪,指向当前正在处理的 `step_order` -- 所有步骤标记为 `已完成(2)` 或 `已跳过(3)` 后,`current_step` 置为最终步骤号,工单状态可流转至 `已完成(2)` - ---- - -## 五、Model 内置业务类型定义 - -> **步骤不预设模板**:`wms_after_sale_work_order_step` 表的步骤由业务逻辑在运行时动态创建,不在数据库或 Model 中硬编码步骤模板。 - -### 5.1 `BUSINESS_TYPES` 常量(定义在 `app/model/after_sale_work_order.js`) - -```javascript -/** - * 售后工单业务类型定义 - * 外部可通过 require('./app/model/after_sale_work_order').BUSINESS_TYPES 访问 - * 增删业务类型或子类型只需修改此常量,无需 ALTER TABLE - */ -const BUSINESS_TYPES = { - waybill: { - label: '运单', - table: 'wms_order_express', // 关联的数据库表名 - subtypes: { - intercept: '拦截', - urge: '催件', - damage: '破损', - lost: '丢件', - wrong_info: '信息错误', - }, - }, - order_delivery: { - label: '发货订单', - table: 'wms_order_delivery', - subtypes: { - mis_shipment: '错发', - missing_item: '少发', - wrong_sku: '错品', - quality_issue: '质量问题', - delivery_delay: '发货延迟', - }, - }, - entry_order: { - label: '入库单', - table: 'wms_entry_order', - subtypes: { - shortage: '少货', - damage: '破损', - wrong_sku: '错品', - quality_issue: '质量问题', - }, - }, - order_stockout: { - label: '出库单/退货出库单', - table: 'wms_order_stockout', - subtypes: { - return_issue: '退货异常', - wrong_outbound: '错发', - shortage: '少发', - }, - }, - receiving: { - label: '收货单', - table: 'wms_receiving', - subtypes: { - shortage: '少货', - damage: '破损', - quality_issue: '质量问题', - }, - }, - other: { - label: '其他', - table: null, - subtypes: { - general: '通用', - }, - }, -}; - -// 辅助函数:根据 business_type 获取关联表名 -function getBusinessTable(businessType) { - return BUSINESS_TYPES[businessType]?.table || null; -} - -// 辅助函数:校验 business_type + business_sub_type 组合是否合法 -function isValidSubType(businessType, businessSubType) { - const def = BUSINESS_TYPES[businessType]; - return def && Object.prototype.hasOwnProperty.call(def.subtypes, businessSubType); -} - -module.exports = { BUSINESS_TYPES, getBusinessTable, isValidSubType }; -``` - -### 5.2 使用示例 - -```javascript -// 外部读取 -const { BUSINESS_TYPES, getBusinessTable, isValidSubType } = require('./app/model/after_sale_work_order'); - -// 获取所有业务类型列表 -Object.keys(BUSINESS_TYPES); // ['waybill', 'order_delivery', 'entry_order', ...] - -// 获取运单下的子类型 -BUSINESS_TYPES.waybill.subtypes; // { intercept: '拦截', urge: '催件', ... } - -// 获取关联表 -const table = getBusinessTable('waybill'); // 'wms_order_express' - -// 校验合法性 -isValidSubType('waybill', 'intercept'); // true -isValidSubType('waybill', 'mis_shipment'); // false -``` - ---- - -## 六、与现有系统的关联 - -### 6.1 与业务单据的多态关联(三级定位) - -``` -wms_after_sale_work_order - .business_type = 'waybill' - .business_sub_type = 'intercept' ← 子类型(Model 常量定义) - .business_id = 12345 ← wms_order_express.id - .business_no = 'YD202607280001' ← 冗余单号 - -实际关联链路: - business_type → BUSINESS_TYPES[type].table → 确定关联表 - business_id → 关联表主键 - business_sub_type → 细分工单类别(如拦截/催件/破损) - -示例: - ├── 'waybill' / 'intercept' → wms_order_express.id - ├── 'waybill' / 'urge' → wms_order_express.id - ├── 'waybill' / 'damage' → wms_order_express.id - ├── 'order_delivery' / 'mis_shipment' → wms_order_delivery.id - ├── 'order_delivery' / 'missing_item' → wms_order_delivery.id - ├── 'entry_order' / 'shortage' → wms_entry_order.id - ├── 'order_stockout' / 'return_issue' → wms_order_stockout.id - ├── 'receiving' / 'damage' → wms_receiving.id - └── 'other' / 'general' → 自定义 -``` - -### 6.2 与库存交易的对账 - -``` -售后工单.direction = 1 (入库) - → stock_transaction.transaction_type = 'INBOUND' - → stock_transaction.order_type = 'AFTER_SALE' (需同步在 stock_transaction 中新增此类型) - -售后工单.direction = 2 (出库) - → stock_transaction.transaction_type = 'OUTBOUND' - → stock_transaction.order_type = 'AFTER_SALE' -``` - -### 6.4 与附件的关联 - -售后工单不新增附件字段,复用现有 `wms_file_reference` 表做多态附件关联: - -``` -wms_file_reference - .reference_type = 'after_sale_work_order' ← 固定标识 - .reference_id = 工单 id ← wms_after_sale_work_order.id - .file_id = 文件 id ← wms_file.id - -示例:一张工单可关联多张图片/多个附件(如破损照片、快递面单照片等)。 -``` - -> `file_reference` 表已支持多态关联(`reference_type` + `reference_id`),无需新建表或字段。 - -### 6.5 与员工的关联 - -``` -wms_after_sale_work_order.creator_id → account.id(创建人) -wms_after_sale_work_order.assignee_id → account.id(当前处理人) -wms_after_sale_work_order_step.operator_id → account.id(步骤操作人) -``` - ---- - -## 七、待确认事项(审阅清单) - -请审阅时重点关注以下设计决策: - -- [x] **1. `business_type` 枚举值**:`order_delivery` / `entry_order` / `order_stockout` / `waybill` / `receiving` / `other` — ✅ 已确认,暂不增加 `return_order` 独立类型(退货场景通过 `order_stockout` 覆盖) -- [x] **2. `direction` 记账方向**:`1`=入库 / `2`=出库 / `0`=未确定 — ✅ 已确认,细粒度区分由关联的实际出入库单承载 -- [x] **3. 工单状态值**:`0-待处理/1-处理中/2-已完成/3-已关闭/9-已取消` — ✅ 已确认,当前中间态足够,无需增加"驳回/退回" -- [x] **4. 预设步骤模板**:不再预设步骤模板,步骤由业务逻辑动态创建 ✅ -- [x] **5. `business_id` 多态关联**:采用 `business_type` + `business_sub_type` + `business_id` 三级多态关联,子类型由 Model 常量定义 ✅ -- [x] **6. 理赔信息**:已新增 `claim_needed` / `claim_amount` / `claim_status` 三个字段 ✅ -- [x] **7. 进度追踪**:进度由主表 `current_step` 字段承载(不再仅依赖副表步骤状态) ✅ -- [x] **8. 优先级**:改为 `TINYINT UNSIGNED` 取值范围 `1-100`,由客服或 AI 自动识别填入,默认值 `50` ✅ -- [x] **9. AI 创建支持**:`creator_id = 0` 表示 AI 自动接待,`creator_snapshot` 记录模型/会话信息 ✅ -- [x] **10. 附件/图片**:复用现有 `wms_file_reference` 表做多态关联,不新增字段 ✅ -- [x] **11. 预计完成时间**:暂不增加,后续通过 `created_at` + `priority` 做超时告警替代;SLA 配置表留待后续迭代 ✅ -- [x] **12. 关联工单**:已确认新增 `parent_work_order_id` 字段,支持主子工单拆分 ✅ -- [x] **13. 表名**:`wms_after_sale_work_order` 和 `wms_after_sale_work_order_step` — ✅ 已确认 -- [x] **14. 权限**:API 接口设计阶段再补录 `wms_permission` 记录,不阻塞表落库 ✅ - ---- - -## 八、后续落库计划(审阅通过后执行) - -1. 创建迁移文件 `database/migrations/20260728XXXXXX-create-wms-after-sale-work-order.js` -2. 创建迁移文件 `database/migrations/20260728XXXXXX-create-wms-after-sale-work-order-step.js` -3. 创建 Model 文件 `app/model/after_sale_work_order.js` -4. 创建 Model 文件 `app/model/after_sale_work_order_step.js` -5. 在 `methods/system.json` 中新增接口路由 -6. 如需,在 `stock_transaction.order_type` 中新增 `AFTER_SALE` 枚举值(独立迁移) -7. 如需,新增 `wms_permission` 权限记录 diff --git a/database/migrations/20260728130000-create-wms-after-sale-work-order-step.js b/database/migrations/20260728130000-create-wms-after-sale-work-order-step.js deleted file mode 100644 index 77e2b6f..0000000 --- a/database/migrations/20260728130000-create-wms-after-sale-work-order-step.js +++ /dev/null @@ -1,115 +0,0 @@ -'use strict'; - -const TABLE_NAME = 'wms_after_sale_work_order_step'; - -module.exports = { - up: async (queryInterface, Sequelize) => { - const tables = await queryInterface.showAllTables(); - const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME); - if (exists) return; - - await queryInterface.createTable(TABLE_NAME, { - id: { - type: Sequelize.BIGINT(20).UNSIGNED, - primaryKey: true, - autoIncrement: true, - allowNull: false, - comment: '主键ID', - }, - work_order_id: { - type: Sequelize.BIGINT(20).UNSIGNED, - allowNull: false, - comment: '工单ID,关联 wms_after_sale_work_order.id', - }, - step_order: { - type: Sequelize.TINYINT.UNSIGNED, - allowNull: false, - defaultValue: 1, - comment: '步骤序号(从1开始递增)', - }, - step_name: { - type: Sequelize.STRING(100), - allowNull: false, - comment: '步骤名称', - }, - step_status: { - type: Sequelize.TINYINT.UNSIGNED, - allowNull: false, - defaultValue: 0, - comment: '步骤状态:0=待开始 1=进行中 2=已完成 3=已跳过', - }, - operator_id: { - type: Sequelize.BIGINT(20).UNSIGNED, - allowNull: true, - comment: '操作员工ID,关联 account.id', - }, - operator_snapshot: { - type: Sequelize.TEXT, - allowNull: true, - comment: '操作人信息快照(JSON格式)', - }, - action: { - type: Sequelize.STRING(100), - allowNull: true, - comment: '操作动作描述', - }, - remark: { - type: Sequelize.TEXT, - allowNull: true, - comment: '处理备注', - }, - started_at: { - type: Sequelize.DATE, - allowNull: true, - comment: '步骤开始时间', - }, - completed_at: { - type: Sequelize.DATE, - allowNull: true, - comment: '步骤完成时间', - }, - created_at: { - type: Sequelize.DATE, - allowNull: false, - defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), - comment: '创建时间', - }, - updated_at: { - type: Sequelize.DATE, - allowNull: false, - defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), - comment: '更新时间', - }, - deleted_at: { - type: Sequelize.DATE, - allowNull: true, - comment: '软删除时间', - }, - }); - - // 按工单查所有步骤 - await queryInterface.addIndex(TABLE_NAME, [ 'work_order_id' ], { - name: 'idx_work_order_id', - }); - - // 按操作人反查 - await queryInterface.addIndex(TABLE_NAME, [ 'operator_id' ], { - name: 'idx_operator_id', - }); - - // 软删除查询优化 - await queryInterface.addIndex(TABLE_NAME, [ 'deleted_at' ], { - name: 'idx_deleted_at', - }); - - // 同一工单下步骤序号唯一(含软删除) - await queryInterface.addIndex(TABLE_NAME, [ 'work_order_id', 'step_order', 'deleted_at' ], { - unique: true, - name: 'uk_work_order_step', - }); - }, - - down: async queryInterface => { - await queryInterface.dropTable(TABLE_NAME); - }, -}; diff --git a/database/migrations/20260728120000-create-wms-after-sale-work-order.js b/database/migrations/20260809120000-drop-wms-after-sale-work-order.js similarity index 50% rename from database/migrations/20260728120000-create-wms-after-sale-work-order.js rename to database/migrations/20260809120000-drop-wms-after-sale-work-order.js index c6c6ab1..ec379c2 100644 --- a/database/migrations/20260728120000-create-wms-after-sale-work-order.js +++ b/database/migrations/20260809120000-drop-wms-after-sale-work-order.js @@ -1,14 +1,18 @@ -'use strict'; +'use strict'; -const TABLE_NAME = 'wms_after_sale_work_order'; +const TABLE_MAIN = 'wms_after_sale_work_order'; +const TABLE_STEP = 'wms_after_sale_work_order_step'; module.exports = { up: async (queryInterface, Sequelize) => { - const tables = await queryInterface.showAllTables(); - const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME); - if (exists) return; + // 先删子表(步骤表),再删主表(工单表) + await queryInterface.dropTable(TABLE_STEP); + await queryInterface.dropTable(TABLE_MAIN); + }, - await queryInterface.createTable(TABLE_NAME, { + down: async (queryInterface, Sequelize) => { + // ========== 1. 重建主表:wms_after_sale_work_order ========== + await queryInterface.createTable(TABLE_MAIN, { id: { type: Sequelize.BIGINT(20).UNSIGNED, primaryKey: true, @@ -152,64 +156,101 @@ module.exports = { }, }); - // 工单号唯一 - await queryInterface.addIndex(TABLE_NAME, [ 'work_order_no' ], { - unique: true, - name: 'uk_work_order_no', + await queryInterface.addIndex(TABLE_MAIN, ['work_order_no'], { unique: true, name: 'uk_work_order_no' }); + await queryInterface.addIndex(TABLE_MAIN, ['warehouse_id'], { name: 'idx_warehouse_id' }); + await queryInterface.addIndex(TABLE_MAIN, ['store_id'], { name: 'idx_store_id' }); + await queryInterface.addIndex(TABLE_MAIN, ['business_type', 'business_sub_type', 'business_id'], { name: 'idx_business_type_subtype_id' }); + await queryInterface.addIndex(TABLE_MAIN, ['status'], { name: 'idx_status' }); + await queryInterface.addIndex(TABLE_MAIN, ['assignee_id'], { name: 'idx_assignee_id' }); + await queryInterface.addIndex(TABLE_MAIN, ['parent_work_order_id'], { name: 'idx_parent_work_order_id' }); + await queryInterface.addIndex(TABLE_MAIN, ['priority'], { name: 'idx_priority' }); + await queryInterface.addIndex(TABLE_MAIN, ['claim_status'], { name: 'idx_claim_status' }); + await queryInterface.addIndex(TABLE_MAIN, ['created_at'], { name: 'idx_created_at' }); + await queryInterface.addIndex(TABLE_MAIN, ['deleted_at'], { name: 'idx_deleted_at' }); + + // ========== 2. 重建子表:wms_after_sale_work_order_step ========== + await queryInterface.createTable(TABLE_STEP, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + work_order_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '工单ID,关联 wms_after_sale_work_order.id', + }, + step_order: { + type: Sequelize.TINYINT.UNSIGNED, + allowNull: false, + defaultValue: 1, + comment: '步骤序号(从1开始递增)', + }, + step_name: { + type: Sequelize.STRING(100), + allowNull: false, + comment: '步骤名称', + }, + step_status: { + type: Sequelize.TINYINT.UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '步骤状态:0=待开始 1=进行中 2=已完成 3=已跳过', + }, + operator_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '操作员工ID,关联 account.id', + }, + operator_snapshot: { + type: Sequelize.TEXT, + allowNull: true, + comment: '操作人信息快照(JSON格式)', + }, + action: { + type: Sequelize.STRING(100), + allowNull: true, + comment: '操作动作描述', + }, + remark: { + type: Sequelize.TEXT, + allowNull: true, + comment: '处理备注', + }, + started_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '步骤开始时间', + }, + completed_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '步骤完成时间', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '软删除时间', + }, }); - // 仓库隔离查询 - await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id' ], { - name: 'idx_warehouse_id', - }); - - // 货主隔离查询 - await queryInterface.addIndex(TABLE_NAME, [ 'store_id' ], { - name: 'idx_store_id', - }); - - // 按业务类型+子类型+单据ID反查工单 - await queryInterface.addIndex(TABLE_NAME, [ 'business_type', 'business_sub_type', 'business_id' ], { - name: 'idx_business_type_subtype_id', - }); - - // 按状态筛选 - await queryInterface.addIndex(TABLE_NAME, [ 'status' ], { - name: 'idx_status', - }); - - // 按处理人查询 - await queryInterface.addIndex(TABLE_NAME, [ 'assignee_id' ], { - name: 'idx_assignee_id', - }); - - // 按父工单查子工单 - await queryInterface.addIndex(TABLE_NAME, [ 'parent_work_order_id' ], { - name: 'idx_parent_work_order_id', - }); - - // 按优先级排序 - await queryInterface.addIndex(TABLE_NAME, [ 'priority' ], { - name: 'idx_priority', - }); - - // 按理赔状态筛选 - await queryInterface.addIndex(TABLE_NAME, [ 'claim_status' ], { - name: 'idx_claim_status', - }); - - // 按时间排序 - await queryInterface.addIndex(TABLE_NAME, [ 'created_at' ], { - name: 'idx_created_at', - }); - - // 软删除查询优化 - await queryInterface.addIndex(TABLE_NAME, [ 'deleted_at' ], { - name: 'idx_deleted_at', - }); - }, - - down: async queryInterface => { - await queryInterface.dropTable(TABLE_NAME); + await queryInterface.addIndex(TABLE_STEP, ['work_order_id'], { name: 'idx_work_order_id' }); + await queryInterface.addIndex(TABLE_STEP, ['operator_id'], { name: 'idx_operator_id' }); + await queryInterface.addIndex(TABLE_STEP, ['deleted_at'], { name: 'idx_deleted_at' }); + await queryInterface.addIndex(TABLE_STEP, ['work_order_id', 'step_order', 'deleted_at'], { unique: true, name: 'uk_work_order_step' }); }, }; From 296536c83e03554e0be691faca87e4cdfe0072ee Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sun, 9 Aug 2026 21:17:34 +0800 Subject: [PATCH 185/550] =?UTF-8?q?feat:=20=E5=94=AE=E5=90=8E=E6=A8=A1?= =?UTF-8?q?=E5=9D=97V2=E5=85=A8=E9=9D=A2=E8=90=BD=E5=9C=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 数据库: - 创建 wms_after_sale 主表 (36字段/16索引) - 创建 wms_after_sale_detail 步骤表 (11字段/3索引) - 插入售后权限 16条 (ID 508-523) - 绑定6个角色权限 (客服/仓库/生产主管/拣货组长) 代码: - Model: after_sale.js + after_sale_detail.js (含常量枚举) - Service: systemMethods/afterSale.js + systems/afterSale.js (19方法) 文档: - API定义: methods/system.json (+9 methods) - 设计文档: database/designs/after-sale-v2-design.md - 开发/生产环境均已执行迁移,权限ID完全一致 --- app/model/after_sale.js | 421 +++++++++ app/model/after_sale_detail.js | 143 +++ app/service/systemMethods/afterSale.js | 843 +++++++++++++++++ app/service/systems/afterSale.js | 863 ++++++++++++++++++ database/designs/after-sale-v2-design.md | 845 +++++++++++++++++ .../20260809130000-create-wms-after-sale.js | 293 ++++++ ...0809130100-create-wms-after-sale-detail.js | 100 ++ ...260809130200-add-after-sale-permissions.js | 97 ++ methods/system.json | 160 +++- 9 files changed, 3764 insertions(+), 1 deletion(-) create mode 100644 app/model/after_sale.js create mode 100644 app/model/after_sale_detail.js create mode 100644 app/service/systemMethods/afterSale.js create mode 100644 app/service/systems/afterSale.js create mode 100644 database/designs/after-sale-v2-design.md create mode 100644 database/migrations/20260809130000-create-wms-after-sale.js create mode 100644 database/migrations/20260809130100-create-wms-after-sale-detail.js create mode 100644 database/migrations/20260809130200-add-after-sale-permissions.js diff --git a/app/model/after_sale.js b/app/model/after_sale.js new file mode 100644 index 0000000..2ec2f60 --- /dev/null +++ b/app/model/after_sale.js @@ -0,0 +1,421 @@ +'use strict'; + +/** + * 售后主表 Model,基于 `wms_after_sale` 表。 + * @param {import('egg').Application} app Egg 应用实例 + * @return {import('sequelize').ModelCtor} 售后 Model(含常量挂载) + */ +module.exports = app => { + const { STRING, BIGINT, INTEGER, DECIMAL, TEXT, TINYINT, DATE } = app.Sequelize; + + // ============================ + // 枚举常量定义 + // ============================ + + /** + * 售后类型 + 子类型枚举,按业务单据维度分类。 + * @type {Array<{name: string, type: string, subType: Array<{name: string, value: string}>}>} + */ + const AFTER_SALE_TYPES = [ + { + name: '订单', + type: 'order', + subType: [ + { name: '破损', value: 'damage' }, + { name: '少发', value: 'missing_item' }, + { name: '错发', value: 'mis_shipment' }, + { name: '错品', value: 'wrong_sku' }, + { name: '质量问题', value: 'quality_issue' }, + { name: '发货延迟', value: 'delivery_delay' }, + { name: '物流异常', value: 'logistics_issue' }, + { name: '客户拒收', value: 'rejected' }, + { name: '拦截', value: 'intercept' }, + { name: '核实签收', value: 'verify_delivery' }, + { name: '催件', value: 'urge' }, + { name: '多发', value: 'extra_item' }, + { name: '改地址', value: 'change_address' }, + { name: '换快递', value: 'change_carrier' }, + { name: '重量异常', value: 'weight_issue' }, + { name: '运费争议', value: 'freight_issue' }, + { name: '其他', value: 'other' }, + ], + }, + { + name: '收货单', + type: 'receiving', + subType: [ + { name: '少货', value: 'shortage' }, + { name: '破损', value: 'damage' }, + { name: '错品', value: 'wrong_sku' }, + { name: '质量问题', value: 'quality_issue' }, + { name: '其他', value: 'other' }, + ], + }, + { + name: '入库单', + type: 'entry', + subType: [ + { name: '少货', value: 'shortage' }, + { name: '破损', value: 'damage' }, + { name: '错品', value: 'wrong_sku' }, + { name: '质量问题', value: 'quality_issue' }, + { name: '其他', value: 'other' }, + ], + }, + { + name: '出库单', + type: 'stockout', + subType: [ + { name: '退货异常', value: 'return_issue' }, + { name: '错发', value: 'wrong_outbound' }, + { name: '少发', value: 'shortage' }, + { name: '其他', value: 'other' }, + ], + }, + ]; + + /** + * 售后处理角色组枚举。 + * @type {{customer_service: string, warehouse: string, finance: string}} + */ + const AFTER_SALE_ROLE_GROUPS = { + customer_service: '客服组', + warehouse: '仓库组', + finance: '财务组', + }; + + /** + * 售后单状态枚举。 + * @type {{pending: string, processing: string, completed: string, closed: string, cancelled: string}} + */ + const AFTER_SALE_STATUS = { + pending: '待处理', + processing: '处理中', + completed: '已完成', + closed: '已关闭', + cancelled: '已取消', + }; + + /** + * 理赔状态枚举(仓库理赔 & 运方理赔通用)。 + * @type {{pending: string, reviewing: string, approved: string, paid: string, monthly: string, rejected: string}} + */ + const CLAIM_STATUS = { + pending: '待理赔', + reviewing: '审核中', + approved: '已通过', + paid: '已打款', + monthly: '月结', + rejected: '已拒绝', + }; + + // ============================ + // Model 定义 + // ============================ + + const AfterSale = app.model.define('after_sale', { + /** 主键 */ + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键', + }, + /** 仓库ID */ + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + /** 货主ID */ + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '货主ID', + }, + /** 售后单号,唯一 */ + after_sale_no: { + type: STRING(50), + allowNull: false, + comment: '售后单号,唯一。生成规则:前缀AS + 日期YYYYMMDD + 6位序号', + }, + /** 售后类型 */ + type: { + type: STRING(20), + allowNull: false, + comment: '售后类型:order=订单, receiving=收货单, entry=入库单, stockout=出库单', + }, + /** 售后子类型 */ + sub_type: { + type: STRING(50), + allowNull: false, + comment: '售后子类型,与 type 组成二级分类', + }, + /** 售后状态 */ + status: { + type: STRING(20), + allowNull: false, + defaultValue: 'pending', + comment: '售后状态:pending=待处理, processing=处理中, completed=已完成, closed=已关闭, cancelled=已取消', + }, + /** 优先级 */ + priority: { + type: INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '优先级,数值越大越优先(0=普通,10=紧急)', + }, + /** 售后标题 */ + title: { + type: STRING(200), + allowNull: false, + comment: '售后标题(简要描述)', + }, + /** 售后详细描述 */ + description: { + type: TEXT, + allowNull: true, + comment: '售后详细描述', + }, + /** 创建人账户ID */ + creator_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '创建人账户ID(关联 accounts 表)', + }, + /** 关联站内信消息ID */ + inbox_message_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '关联 wms_inbox_message.id,为空表示无关联信息', + }, + /** 当前处理角色组 */ + role_group: { + type: STRING(50), + allowNull: true, + comment: '当前处理角色组:customer_service=客服组, warehouse=仓库组, finance=财务组。NULL 表示未分配', + }, + /** 最终处理结果说明 */ + resolution: { + type: TEXT, + allowNull: true, + comment: '最终处理结果说明', + }, + /** 完结时间 */ + resolved_at: { + type: DATE, + allowNull: true, + comment: '完结时间(状态变为 completed 时写入)', + }, + /** 仓库理赔标记 */ + claim_needed: { + type: TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '仓库理赔标记:0=不需要,1=需要', + }, + /** 仓库理赔金额(元) */ + claim_amount: { + type: DECIMAL(12, 2), + allowNull: true, + comment: '仓库理赔金额,单位:人民币(元),claim_needed=1 时可填写', + }, + /** 仓库理赔状态 */ + claim_status: { + type: STRING(20), + allowNull: true, + comment: '仓库理赔状态:pending=待理赔, reviewing=审核中, approved=已通过, paid=已打款, monthly=月结, rejected=已拒绝', + }, + /** 运方理赔标记 */ + carrier_claim_needed: { + type: TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '运方理赔标记:0=不需要,1=需要', + }, + /** 运方理赔金额(元) */ + carrier_claim_amount: { + type: DECIMAL(12, 2), + allowNull: true, + comment: '运方理赔金额,单位:人民币(元),carrier_claim_needed=1 时可填写', + }, + /** 运方理赔状态 */ + carrier_claim_status: { + type: STRING(20), + allowNull: true, + comment: '运方理赔状态:pending=待理赔, reviewing=审核中, approved=已通过, paid=已打款, monthly=月结, rejected=已拒绝', + }, + // ========== 单据关联字段(替代旧版多态关联) ========== + /** 运单ID */ + waybill_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '运单ID(关联 wms_order_express.id)', + }, + /** 运单号(冗余) */ + waybill_no: { + type: STRING(50), + allowNull: true, + comment: '运单号(冗余字段,方便查询展示)', + }, + /** 发货订单ID */ + order_delivery_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '发货订单ID(关联 wms_order_delivery.id)', + }, + /** 发货订单号(冗余) */ + order_delivery_no: { + type: STRING(50), + allowNull: true, + comment: '发货订单号(冗余字段)', + }, + /** 入库单ID */ + entry_order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '入库单ID(关联 wms_entry_order.id)', + }, + /** 入库单号(冗余) */ + entry_order_no: { + type: STRING(50), + allowNull: true, + comment: '入库单号(冗余字段)', + }, + /** 出库单/退货出库单ID */ + order_stockout_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '出库单/退货出库单ID(关联 wms_order_stockout.id)', + }, + /** 出库单号(冗余) */ + order_stockout_no: { + type: STRING(50), + allowNull: true, + comment: '出库单号(冗余字段)', + }, + /** 收货单ID */ + receiving_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '收货单ID(关联 wms_receiving.id)', + }, + /** 收货单号(冗余) */ + receiving_no: { + 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, + comment: '更新时间', + }, + /** 软删除时间 */ + deleted_at: { + type: DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + tableName: 'wms_after_sale', + comment: '售后主表', + timestamps: false, + indexes: [ + { + name: 'uk_after_sale_no', + unique: true, + fields: [ 'after_sale_no' ], + }, + { + name: 'idx_warehouse_status', + fields: [ 'warehouse_id', 'status', 'deleted_at' ], + }, + { + name: 'idx_warehouse_type', + fields: [ 'warehouse_id', 'type', 'deleted_at' ], + }, + { + name: 'idx_type_subtype', + fields: [ 'warehouse_id', 'type', 'sub_type', 'deleted_at' ], + }, + { + name: 'idx_store_id', + fields: [ 'store_id', 'deleted_at' ], + }, + { + name: 'idx_creator_id', + fields: [ 'creator_id', 'deleted_at' ], + }, + { + name: 'idx_role_group', + fields: [ 'role_group', 'status', 'deleted_at' ], + }, + { + name: 'idx_created_at', + fields: [ 'warehouse_id', 'created_at' ], + }, + { + name: 'idx_waybill_id', + fields: [ 'waybill_id' ], + }, + { + name: 'idx_order_delivery_id', + fields: [ 'order_delivery_id' ], + }, + { + name: 'idx_entry_order_id', + fields: [ 'entry_order_id' ], + }, + { + name: 'idx_order_stockout_id', + fields: [ 'order_stockout_id' ], + }, + { + name: 'idx_receiving_id', + fields: [ 'receiving_id' ], + }, + { + name: 'idx_carrier_claim_status', + fields: [ 'carrier_claim_status' ], + }, + { + name: 'idx_inbox_message_id', + fields: [ 'inbox_message_id' ], + }, + ], + }); + + // ============================ + // 关联关系 + // ============================ + + AfterSale.associate = function() { + const { AfterSale, AfterSaleDetail } = app.model; + + // 关联售后进度步骤(一对多) + AfterSale.hasMany(AfterSaleDetail, { + foreignKey: 'after_sale_id', + as: 'details', + }); + }; + + // ============================ + // 常量挂载到 Model + // ============================ + + AfterSale.AFTER_SALE_TYPES = AFTER_SALE_TYPES; + AfterSale.AFTER_SALE_ROLE_GROUPS = AFTER_SALE_ROLE_GROUPS; + AfterSale.AFTER_SALE_STATUS = AFTER_SALE_STATUS; + AfterSale.CLAIM_STATUS = CLAIM_STATUS; + + return AfterSale; +}; diff --git a/app/model/after_sale_detail.js b/app/model/after_sale_detail.js new file mode 100644 index 0000000..9a828e2 --- /dev/null +++ b/app/model/after_sale_detail.js @@ -0,0 +1,143 @@ +'use strict'; + +/** + * 售后进度步骤表 Model,基于 `wms_after_sale_detail` 表。 + * @param {import('egg').Application} app Egg 应用实例 + * @return {import('sequelize').ModelCtor} 售后进度步骤 Model(含常量挂载) + */ +module.exports = app => { + const { STRING, BIGINT, TEXT, TINYINT, DATE } = app.Sequelize; + + // ============================ + // 枚举常量定义 + // ============================ + + /** + * 步骤状态枚举。 + * @type {{0: string, 1: string, 2: string, 3: string}} + */ + const STEP_STATUS = { + 0: '待开始', + 1: '进行中', + 2: '已完成', + 3: '已跳过', + }; + + // ============================ + // Model 定义 + // ============================ + + const AfterSaleDetail = app.model.define('after_sale_detail', { + /** 主键 */ + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键', + }, + /** 关联售后主表ID */ + after_sale_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '关联售后主表ID(wms_after_sale.id)', + }, + /** 步骤状态 */ + step_status: { + type: TINYINT(3).UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '步骤状态:0=待开始,1=进行中,2=已完成,3=已跳过', + }, + /** 操作人账户ID */ + operator_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '操作人账户ID(关联 accounts 表);外部系统回调/自动触发的步骤可为空', + }, + /** 操作人信息快照 */ + operator_snapshot: { + type: TEXT, + allowNull: true, + comment: '操作人信息快照(JSON),如 {"name":"张三","role":"客服"},防止账户删除后历史丢失', + }, + /** 操作动作描述 */ + action: { + type: STRING(100), + allowNull: true, + comment: '操作动作描述,如"确认收货"、"审核驳回"、"发起退款"', + }, + /** 处理备注 */ + remark: { + type: TEXT, + allowNull: true, + comment: '处理备注', + }, + /** 步骤开始时间 */ + started_at: { + type: DATE, + allowNull: true, + comment: '步骤开始时间', + }, + /** 步骤完成时间 */ + completed_at: { + type: DATE, + allowNull: true, + comment: '步骤完成时间', + }, + /** 创建时间 */ + created_at: { + type: DATE, + allowNull: true, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + /** 更新时间 */ + updated_at: { + type: DATE, + allowNull: true, + comment: '更新时间', + }, + /** 软删除时间 */ + deleted_at: { + type: DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + tableName: 'wms_after_sale_detail', + comment: '售后进度步骤表', + timestamps: false, + indexes: [ + { + name: 'idx_after_sale_id', + fields: [ 'after_sale_id' ], + }, + { + name: 'idx_operator_id', + fields: [ 'operator_id' ], + }, + ], + }); + + // ============================ + // 关联关系 + // ============================ + + AfterSaleDetail.associate = function() { + const { AfterSale, AfterSaleDetail } = app.model; + + // 关联售后主表(多对一) + AfterSaleDetail.belongsTo(AfterSale, { + foreignKey: 'after_sale_id', + as: 'afterSale', + }); + }; + + // ============================ + // 常量挂载到 Model + // ============================ + + AfterSaleDetail.STEP_STATUS = STEP_STATUS; + + return AfterSaleDetail; +}; diff --git a/app/service/systemMethods/afterSale.js b/app/service/systemMethods/afterSale.js new file mode 100644 index 0000000..9263fad --- /dev/null +++ b/app/service/systemMethods/afterSale.js @@ -0,0 +1,843 @@ +'use strict'; + +const MainService = require('../main'); + +const AFTER_SALE_EXPORT_TASK_CACHE_KEY_PREFIX = 'after_sale_export_task_'; +const AFTER_SALE_EXPORT_TASK_CACHE_TTL_SECONDS = 1800; + +/** + * 售后 block 权限 ID → role_group 映射表。 + * 516=客服组, 517=仓库组, 518=财务组 + */ +const BLOCK_PERMISSION_ROLE_GROUP_MAP = Object.freeze({ + 516: 'customer_service', + 517: 'warehouse', + 518: 'finance', +}); + +/** + * 售后模块工作列表排除的状态(已完成/已取消)。 + */ +const WORK_LIST_EXCLUDED_STATUSES = Object.freeze([ 'completed', 'cancelled' ]); + +/** + * 系统方法层:afterSale(售后模块接口包装层)。 + * 主要职责:统一包装系统方法接口,处理权限、日志、where 解析等公共逻辑, + * 将具体业务逻辑下沉到 systems.afterSale 中。 + */ +class AfterSaleMethodService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'workList,auditList,detail,create,transfer,handleWorkOrder,registerClaim,export,exportTaskProgress'; + const _noNeedLog = 'workList,auditList,detail,export,exportTaskProgress'; + const _noNeedAuth = 'workList,auditList,detail,create,transfer,handleWorkOrder,registerClaim,export,exportTaskProgress'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + // =========================== + // 售后工作列表 + // =========================== + + /** + * 售后工作列表:按当前用户的 block 权限筛选可见的售后单。 + * 解析用户 wms_role.permissions 中 type=block 的售后权限 ID(516/517/518), + * 映射为 role_group,仅展示当前用户可处理的售后单。 + * + * @param {Object} data 请求体 + * @param {Object} [data.pagination] 分页参数 + * @param {Object} [data.where] 动态筛选条件 + * @param {Object} [data.sort] 排序参数 + * @return {Promise} 统一 success 包装 + */ + async workList(data = {}) { + const { service } = this; + const { pagination, sort } = data; + const { where } = this.prepareWhereContext(data, { + specialFieldMap: { + quickWhere: { + bucket: 'quick', + }, + }, + }); + + // 提取当前用户的售后 block 权限 → role_group 列表 + const allowedRoleGroups = this._resolveAfterSaleBlockRoleGroups(); + + // 强制过滤:仅展示当前用户可处理的 role_group,且排除已完成/已取消 + const enforcedWhere = { + ...where, + role_group: { + operator: 'in', + value: allowedRoleGroups, + }, + status: { + operator: 'notin', + value: WORK_LIST_EXCLUDED_STATUSES, + }, + }; + + const result = await service.systems.afterSale.list(enforcedWhere, pagination, sort); + return this.success('ok', result); + } + + /** + * 解析当前用户所拥有的售后 block 权限对应的 role_group 列表。 + * 从 ctx.user.role.permissions 中筛选 type=block 且 ID 为 516/517/518 的权限项。 + * + * @return {string[]} 当前用户可处理的 role_group 列表 + */ + _resolveAfterSaleBlockRoleGroups() { + const { ctx } = this; + const rolePermissions = ctx.user && ctx.user.role && Array.isArray(ctx.user.role.permissions) + ? ctx.user.role.permissions + : []; + + const allowedRoleGroups = []; + for (const perm of rolePermissions) { + const permId = Number(perm && (perm.id || perm.permission_id || 0)); + const permType = String(perm && (perm.type || '')).trim(); + if (permType === 'block' && BLOCK_PERMISSION_ROLE_GROUP_MAP[permId]) { + allowedRoleGroups.push(BLOCK_PERMISSION_ROLE_GROUP_MAP[permId]); + } + } + + // 如果未匹配到任何售后 block 权限,默认不给任何 role_group 可见范围 + if (allowedRoleGroups.length === 0) { + return [ '__none__' ]; + } + + return allowedRoleGroups; + } + + // =========================== + // 售后审计列表 + // =========================== + + /** + * 售后审计列表:不限 role_group 与 status(包含已完成/已取消)。 + * 用于管理员/审计角色查看全部售后单。 + * + * @param {Object} data 请求体 + * @param {Object} [data.pagination] 分页参数 + * @param {Object} [data.where] 动态筛选条件 + * @param {Object} [data.sort] 排序参数 + * @return {Promise} 统一 success 包装 + */ + async auditList(data = {}) { + const { service } = this; + const { pagination, sort } = data; + const { where } = this.prepareWhereContext(data, { + specialFieldMap: { + quickWhere: { + bucket: 'quick', + }, + }, + }); + + const result = await service.systems.afterSale.list(where, pagination, sort); + return this.success('ok', result); + } + + // =========================== + // 售后明细 + // =========================== + + /** + * 售后明细:查询主表、步骤列表及步骤附件。 + * + * @param {Object} data 请求体 + * @param {number} data.id 售后单主键ID + * @return {Promise} 统一 success 包装,包含主表、步骤列表及附件信息 + */ + async detail(data = {}) { + const { service } = this; + const { id } = data || {}; + + if (!id) { + return this.fail('缺少售后单ID'); + } + + const result = await service.systems.afterSale.getDetail(Number(id)); + return this.success('ok', result); + } + + // =========================== + // 创建售后单 + // =========================== + + /** + * 创建售后单:生成售后单号,写入主表记录。 + * warehouse_id 由服务端从当前上下文自动注入。 + * + * @param {Object} data 请求体 + * @param {string} data.type 售后类型(order/receiving/entry/stockout) + * @param {string} data.sub_type 售后子类型 + * @param {string} data.title 售后标题 + * @param {string} [data.description] 售后详细描述 + * @param {number} [data.priority=0] 优先级 + * @param {number} [data.waybill_id] 关联运单ID + * @param {number} [data.order_delivery_id] 关联发货订单ID + * @param {number} [data.entry_order_id] 关联入库单ID + * @param {number} [data.order_stockout_id] 关联出库单ID + * @param {number} [data.receiving_id] 关联收货单ID + * @param {number} [data.store_id] 关联货主ID + * @param {number} [data.inbox_message_id] 关联站内信ID + * @return {Promise} 统一 success 包装,返回新创建的售后单信息 + */ + async create(data = {}) { + const { ctx, service } = this; + const warehouseId = ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : 0; + const creatorId = ctx.user ? (ctx.user.id || ctx.user.user_id || 0) : 0; + + if (!warehouseId) { + return this.fail('无法获取当前仓库上下文'); + } + + const { + type, + sub_type: subType, + title, + description, + priority, + waybill_id: waybillId, + order_delivery_id: orderDeliveryId, + entry_order_id: entryOrderId, + order_stockout_id: orderStockoutId, + receiving_id: receivingId, + store_id: storeId, + inbox_message_id: inboxMessageId, + } = data || {}; + + // 生成售后单号 + const afterSaleNo = await this.generateAfterSaleNo(warehouseId); + + // 处理单据关联字段的冗余同步(waybill_no 等从对应表同步取数) + const redundantFields = await this._resolveRedundantFields({ + waybillId, + orderDeliveryId, + entryOrderId, + orderStockoutId, + receivingId, + }); + + const createData = { + warehouse_id: warehouseId, + after_sale_no: afterSaleNo, + type, + sub_type: subType, + title, + description: description || null, + priority: priority !== undefined ? Number(priority) : 0, + creator_id: creatorId, + role_group: 'customer_service', + status: 'pending', + waybill_id: waybillId || null, + waybill_no: redundantFields.waybill_no || null, + order_delivery_id: orderDeliveryId || null, + order_delivery_no: redundantFields.order_delivery_no || null, + entry_order_id: entryOrderId || null, + entry_order_no: redundantFields.entry_order_no || null, + order_stockout_id: orderStockoutId || null, + order_stockout_no: redundantFields.order_stockout_no || null, + receiving_id: receivingId || null, + receiving_no: redundantFields.receiving_no || null, + store_id: storeId || null, + inbox_message_id: inboxMessageId || null, + }; + + const result = await service.systems.afterSale.create(createData); + return this.success('售后单创建成功', result); + } + + /** + * 解析单据关联字段的冗余值(waybill_no、order_delivery_no 等), + * 从对应的关联表中同步取数。 + * + * @param {Object} params 关联ID集合 + * @param {number} [params.waybillId] 运单ID + * @param {number} [params.orderDeliveryId] 发货订单ID + * @param {number} [params.entryOrderId] 入库单ID + * @param {number} [params.orderStockoutId] 出库单ID + * @param {number} [params.receivingId] 收货单ID + * @return {Promise} 冗余字段键值对 + */ + async _resolveRedundantFields(params = {}) { + const { ctx } = this; + const redundant = {}; + + // 运单号 + if (params.waybillId) { + try { + const waybill = await ctx.model.OrderExpress.findOne({ + where: { id: params.waybillId }, + attributes: [ 'waybill_code' ], + raw: true, + }); + redundant.waybill_no = waybill ? waybill.waybill_code || null : null; + } catch (err) { + ctx.logger.warn(`[afterSale._resolveRedundantFields] 查询运单号失败: ${err.message}`); + } + } + + // 发货订单号 + if (params.orderDeliveryId) { + try { + const warehouseId = ctx.user && ctx.user.store_id; + const DeliveryModel = warehouseId + ? await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId) + : null; + if (DeliveryModel) { + const order = await DeliveryModel.findOne({ + where: { id: params.orderDeliveryId }, + attributes: [ 'delivery_order_code' ], + raw: true, + }); + redundant.order_delivery_no = order ? order.delivery_order_code || null : null; + } + } catch (err) { + ctx.logger.warn(`[afterSale._resolveRedundantFields] 查询发货订单号失败: ${err.message}`); + } + } + + // 入库单号 + if (params.entryOrderId) { + try { + const entry = await ctx.model.EntryOrder.findOne({ + where: { id: params.entryOrderId }, + attributes: [ 'entry_order_code' ], + raw: true, + }); + redundant.entry_order_no = entry ? entry.entry_order_code || null : null; + } catch (err) { + ctx.logger.warn(`[afterSale._resolveRedundantFields] 查询入库单号失败: ${err.message}`); + } + } + + // 出库单号 + if (params.orderStockoutId) { + try { + const stockout = await ctx.model.OrderStockout.findOne({ + where: { id: params.orderStockoutId }, + attributes: [ 'order_stockout_no' ], + raw: true, + }); + redundant.order_stockout_no = stockout ? stockout.order_stockout_no || null : null; + } catch (err) { + ctx.logger.warn(`[afterSale._resolveRedundantFields] 查询出库单号失败: ${err.message}`); + } + } + + // 收货单号 + if (params.receivingId) { + try { + const receiving = await ctx.model.Receiving.findOne({ + where: { id: params.receivingId }, + attributes: [ 'receiving_code' ], + raw: true, + }); + redundant.receiving_no = receiving ? receiving.receiving_code || null : null; + } catch (err) { + ctx.logger.warn(`[afterSale._resolveRedundantFields] 查询收货单号失败: ${err.message}`); + } + } + + return redundant; + } + + // =========================== + // 转单 + // =========================== + + /** + * 转单:将售后单的 role_group 更新为目标值,并写入一条 detail 步骤记录。 + * + * @param {Object} data 请求体 + * @param {number} data.id 售后单主键ID + * @param {string} data.target_role_group 目标角色组(customer_service/warehouse/finance) + * @param {string} [data.remark] 转单备注 + * @return {Promise} 统一 success 包装 + */ + async transfer(data = {}) { + const { ctx, service } = this; + const { + id, + target_role_group: targetRoleGroup, + remark, + } = data || {}; + + if (!id) { + return this.fail('缺少售后单ID'); + } + if (!targetRoleGroup) { + return this.fail('缺少目标角色组'); + } + + const operatorId = ctx.user ? (ctx.user.id || ctx.user.user_id || 0) : 0; + const operatorSnapshot = this._buildOperatorSnapshot(); + + const result = await service.systems.afterSale.transfer({ + id: Number(id), + targetRoleGroup, + remark: remark || '', + operatorId, + operatorSnapshot, + }); + + return this.success('转单成功', result); + } + + // =========================== + // 处理工单 + // =========================== + + /** + * 处理工单:校验权限后写入步骤记录,可选更新状态与附件。 + * 若处理完后当前 role_group 非客服组且状态未完结,自动回设为客服组。 + * + * @param {Object} data 请求体 + * @param {number} data.id 售后单主键ID + * @param {string} data.action 操作动作描述 + * @param {string} [data.remark] 处理备注 + * @param {string} [data.status] 目标售后状态 + * @param {string} [data.resolution] 完结处理结果(status=completed 时写入) + * @param {number[]} [data.attachment_ids] 附件文件ID列表 + * @return {Promise} 统一 success 包装 + */ + async handleWorkOrder(data = {}) { + const { ctx, service } = this; + const { + id, + action, + remark, + status: targetStatus, + resolution, + attachment_ids: attachmentIds, + } = data || {}; + + if (!id) { + return this.fail('缺少售后单ID'); + } + if (!action) { + return this.fail('缺少操作动作'); + } + + const operatorId = ctx.user ? (ctx.user.id || ctx.user.user_id || 0) : 0; + const operatorSnapshot = this._buildOperatorSnapshot(); + const warehouseId = ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : 0; + + const result = await service.systems.afterSale.handleWorkOrder({ + id: Number(id), + action, + remark: remark || null, + targetStatus: targetStatus || null, + resolution: resolution || null, + attachmentIds: Array.isArray(attachmentIds) ? attachmentIds : [], + operatorId, + operatorSnapshot, + warehouseId, + }); + + return this.success('处理成功', result); + } + + // =========================== + // 登记理赔 + // =========================== + + /** + * 登记理赔:更新售后单的理赔相关字段,写入步骤记录,绑定附件。 + * + * @param {Object} data 请求体 + * @param {number} data.id 售后单主键ID + * @param {number} [data.claim_needed] 仓库理赔标记(0/1) + * @param {number} [data.claim_amount] 仓库理赔金额 + * @param {string} [data.claim_status] 仓库理赔状态 + * @param {number} [data.carrier_claim_needed] 运方理赔标记(0/1) + * @param {number} [data.carrier_claim_amount] 运方理赔金额 + * @param {string} [data.carrier_claim_status] 运方理赔状态 + * @param {string} [data.remark] 理赔备注 + * @param {string} [data.action] 操作动作描述,默认"登记理赔" + * @param {number[]} [data.attachment_ids] 附件文件ID列表 + * @return {Promise} 统一 success 包装 + */ + async registerClaim(data = {}) { + const { ctx, service } = this; + const { + id, + claim_needed: claimNeeded, + claim_amount: claimAmount, + claim_status: claimStatus, + carrier_claim_needed: carrierClaimNeeded, + carrier_claim_amount: carrierClaimAmount, + carrier_claim_status: carrierClaimStatus, + remark, + action, + attachment_ids: attachmentIds, + } = data || {}; + + if (!id) { + return this.fail('缺少售后单ID'); + } + + const operatorId = ctx.user ? (ctx.user.id || ctx.user.user_id || 0) : 0; + const operatorSnapshot = this._buildOperatorSnapshot(); + const warehouseId = ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : 0; + + const result = await service.systems.afterSale.registerClaim({ + id: Number(id), + claimNeeded: claimNeeded !== undefined ? Number(claimNeeded) : undefined, + claimAmount: claimAmount !== undefined ? Number(claimAmount) : undefined, + claimStatus: claimStatus || undefined, + carrierClaimNeeded: carrierClaimNeeded !== undefined ? Number(carrierClaimNeeded) : undefined, + carrierClaimAmount: carrierClaimAmount !== undefined ? Number(carrierClaimAmount) : undefined, + carrierClaimStatus: carrierClaimStatus || undefined, + remark: remark || null, + action: action || '登记理赔', + attachmentIds: Array.isArray(attachmentIds) ? attachmentIds : [], + operatorId, + operatorSnapshot, + warehouseId, + }); + + return this.success('理赔登记成功', result); + } + + // =========================== + // 导出 + // =========================== + + /** + * 提交售后单导出任务。 + * 异步执行:分页查询 → ExcelJS 流式写入 → COS 上传。 + * 进度通过 Redis 缓存追踪。 + * + * @param {Object} data 请求体 + * @param {Object} [data.where] 筛选条件(与列表一致) + * @param {Object} [data.sort] 排序参数 + * @return {Promise} 统一 success 包装,返回任务ID + */ + async export(data = {}) { + const { service } = this; + const { where, sort } = data || {}; + + const taskId = this.generateExportTaskId(); + const taskPayload = { + task_id: taskId, + status: 'submitted', + progress: 0, + current_count: 0, + total_count: 0, + message: '导出任务已提交', + result: null, + error: '', + }; + + await this.setExportTaskProgress(taskId, taskPayload); + + setImmediate(async () => { + try { + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'running', + progress: 5, + current_count: 0, + total_count: 0, + message: '导出任务执行中', + result: null, + error: '', + }); + + const result = await service.systems.afterSale.exportAfterSales({ + where: this.isPlainObject(where) ? { ...where } : {}, + sort: this.isPlainObject(sort) ? { ...sort } : {}, + onProgress: async progress => { + const safeProgress = this.isPlainObject(progress) ? progress : {}; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: safeProgress.status || 'running', + progress: safeProgress.progress, + current_count: safeProgress.currentCount || 0, + total_count: safeProgress.totalCount || 0, + message: safeProgress.message || '导出任务执行中', + result: safeProgress.result || null, + error: '', + }); + }, + }); + + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'success', + progress: 100, + current_count: result.current_count || 0, + total_count: result.total_count || 0, + message: '导出任务完成', + result, + error: '', + }); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'failed', + progress: 100, + current_count: 0, + total_count: 0, + message: '导出任务失败', + result: null, + error: errorMessage, + }); + } + }); + + return this.success('ok', { + ...taskPayload, + update_time: Date.now(), + }); + } + + /** + * 查询售后单导出任务进度。 + * + * @param {Object} data 请求体 + * @param {string} [data.task_id] 任务ID(下划线写法) + * @param {string} [data.taskId] 任务ID(驼峰写法) + * @return {Promise} 统一 success 包装,包含进度与下载链接 + */ + async exportTaskProgress(data = {}) { + const taskId = this.normalizeExportTaskId(data); + if (!taskId) { + return this.success('ok', { + task_id: '', + status: 'not_found', + progress: 0, + current_count: 0, + total_count: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const cachedTask = await this.getExportTaskProgress(taskId); + if (!cachedTask) { + return this.success('ok', { + task_id: taskId, + status: 'not_found', + progress: 0, + current_count: 0, + total_count: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {}; + const downloadUrl = String( + safeResult.url + || safeResult.cdnUrl + || safeResult.cosUrl + || safeResult.fileKey + || '' + ); + + return this.success('ok', { + task_id: taskId, + ...cachedTask, + download_url: downloadUrl, + }); + } + + // =========================== + // 辅助方法 + // =========================== + + /** + * 生成售后单号。 + * 格式:AS + YYYYMMDD + 6位序号(如 AS20240809000001)。 + * + * @param {number} warehouseId 仓库ID + * @return {Promise} 售后单号 + */ + async generateAfterSaleNo(warehouseId) { + const { ctx } = this; + const datePart = this._getCurrentDatePart(); + const prefix = 'AS'; + + const sql = ` + SELECT after_sale_no + FROM wms_after_sale + WHERE warehouse_id = :warehouseId + AND after_sale_no LIKE :pattern + ORDER BY after_sale_no DESC + LIMIT 1 + `; + const pattern = `${prefix}${datePart}%`; + + const rows = await ctx.model.query(sql, { + replacements: { warehouseId, pattern }, + type: ctx.model.QueryTypes.SELECT, + }); + + const latestNo = String(rows && rows[0] && rows[0].after_sale_no || '').trim(); + let sequence = 1; + + if (latestNo) { + const match = latestNo.match(/(\d{6})$/); + const lastSequence = match ? Number(match[1]) : 0; + if (Number.isInteger(lastSequence) && lastSequence > 0) { + sequence = lastSequence + 1; + } + } + + return `${prefix}${datePart}${String(sequence).padStart(6, '0')}`; + } + + /** + * 获取当前日期片段(YYYYMMDD)。 + * + * @return {string} 当前日期片段 + */ + _getCurrentDatePart() { + const now = new Date(); + const year = now.getFullYear(); + const month = String(now.getMonth() + 1).padStart(2, '0'); + const day = String(now.getDate()).padStart(2, '0'); + return `${year}${month}${day}`; + } + + /** + * 构建操作人快照 JSON 字符串。 + * 从 ctx.user 中提取关键身份信息。 + * + * @return {string} 操作人快照 JSON + */ + _buildOperatorSnapshot() { + const { ctx } = this; + const user = ctx.user && typeof ctx.user === 'object' ? ctx.user : {}; + const snapshot = { + id: user.id || user.user_id || null, + name: user.employees_name || user.real_name || user.name || '', + role: user.role && user.role.name ? user.role.name : '', + }; + return JSON.stringify(snapshot); + } + + /** + * 生成导出任务ID。 + * + * @return {string} 导出任务ID + */ + generateExportTaskId() { + const warehouseId = this.ctx && this.ctx.user && this.ctx.user.store_id + ? this.ctx.user.store_id + : 'unknown'; + const timestamp = Date.now(); + const randomToken = Math.random().toString(36).slice(2, 10); + return `after_sale_export_${warehouseId}_${timestamp}_${randomToken}`; + } + + /** + * 归一化导出任务ID(兼容 task_id / taskId)。 + * + * @param {Object} data 请求体 + * @param {string} [data.task_id] 任务ID(下划线写法) + * @param {string} [data.taskId] 任务ID(驼峰写法) + * @return {string} 归一化后的任务ID + */ + normalizeExportTaskId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.task_id || normalizedData.taskId || '').trim(); + } + + /** + * 获取导出任务缓存键。 + * + * @param {string} taskId 任务ID + * @return {string} 缓存键 + */ + getExportTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + return `${AFTER_SALE_EXPORT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 写入导出任务进度缓存。 + * + * @param {string} taskId 任务ID + * @param {Object} payload 任务状态载荷 + * @return {Promise} 无返回值 + */ + async setExportTaskProgress(taskId = '', payload = {}) { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.setCacheAsync !== 'function') { + return; + } + + const safePayload = this.isPlainObject(payload) ? payload : {}; + const normalizeCount = value => { + const numericValue = Number(value); + return Number.isFinite(numericValue) && numericValue >= 0 ? Math.round(numericValue) : 0; + }; + const progressPayload = { + task_id: String(taskId || '').trim(), + status: String(safePayload.status || 'submitted').trim() || 'submitted', + progress: Number.isFinite(Number(safePayload.progress)) + ? Math.min(100, Math.max(0, Math.round(Number(safePayload.progress)))) + : 0, + current_count: normalizeCount(safePayload.current_count), + total_count: normalizeCount(safePayload.total_count), + message: String(safePayload.message || ''), + result: safePayload.result ?? null, + error: String(safePayload.error || ''), + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync( + cacheKey, + progressPayload, + AFTER_SALE_EXPORT_TASK_CACHE_TTL_SECONDS + ); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + this.ctx.logger.warn(`[afterSale.export] 写入导出任务缓存失败: ${errorMessage}`); + } + } + + /** + * 读取导出任务进度缓存。 + * + * @param {string} taskId 任务ID + * @return {Promise} 任务缓存,不存在则返回 null + */ + async getExportTaskProgress(taskId = '') { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.getCacheAsync !== 'function') { + return null; + } + + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (!this.isPlainObject(cached)) { + return null; + } + return cached; + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + this.ctx.logger.warn(`[afterSale.export] 读取导出任务缓存失败: ${errorMessage}`); + return null; + } + } +} + +module.exports = AfterSaleMethodService; diff --git a/app/service/systems/afterSale.js b/app/service/systems/afterSale.js new file mode 100644 index 0000000..e44e387 --- /dev/null +++ b/app/service/systems/afterSale.js @@ -0,0 +1,863 @@ +'use strict'; + +const Service = require('egg').Service; + +/** + * 售后模块业务逻辑层。 + * 负责 wms_after_sale / wms_after_sale_detail 的 CRUD、附件绑定等核心操作。 + * 所有数据库交互集中在此层,供 systemMethods/afterSale.js 调用。 + */ +class AfterSaleService extends Service { + // =========================== + // 列表查询 + // =========================== + + /** + * 售后单列表查询,支持 where 条件、分页、排序。 + * + * @param {Object} where 标准化 where 条件对象 + * @param {Object} [where.after_sale_no] 售后单号条件 + * @param {Object} [where.type] 售后类型条件 + * @param {Object} [where.sub_type] 售后子类型条件 + * @param {Object} [where.status] 售后状态条件 + * @param {Object} [where.priority] 优先级条件 + * @param {Object} [where.role_group] 角色组条件 + * @param {Object} [where.waybill_no] 运单号条件 + * @param {Object} [where.claim_status] 仓库理赔状态条件 + * @param {Object} [where.carrier_claim_status] 运方理赔状态条件 + * @param {Object} [where.quickWhere] 快捷搜索条件 + * @param {Object} [where.warehouse_id] 仓库ID(由方法层注入) + * @param {Object} [pagination] 分页参数 + * @param {number} [pagination.page=1] 页码 + * @param {number} [pagination.pageSize=20] 每页数量 + * @param {Object} [sort] 排序参数 + * @param {string} [sort.sortField] 排序字段 + * @param {string} [sort.sortOrder] 排序顺序(asc/desc) + * @return {Promise} { list: Array, pagination: Object } + */ + async list(where = {}, pagination = {}, sort = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + const page = Math.max(1, parseInt(pagination.page) || 1); + const pageSize = Math.min(500, Math.max(1, parseInt(pagination.pageSize) || 20)); + + // 构建 Sequelize where 条件 + const queryWhere = this._buildListWhere(where, Op); + + // 排序 + const order = this._buildListOrder(sort); + + const { count, rows } = await ctx.model.AfterSale.findAndCountAll({ + where: queryWhere, + order, + offset: (page - 1) * pageSize, + limit: pageSize, + raw: true, + }); + + const totalPages = Math.ceil(count / pageSize); + + return { + list: rows, + pagination: { + page, + pageSize, + total: count, + totalPages, + hasPrevious: page > 1, + hasNext: page * pageSize < count, + }, + }; + } + + /** + * 根据标准化 where 条件构建 Sequelize 查询条件。 + * + * @param {Object} where 标准化 where 条件对象 + * @param {Object} Op Sequelize Op 对象 + * @return {Object} Sequelize where 条件 + */ + _buildListWhere(where = {}, Op) { + const queryWhere = {}; + + // 软删除过滤 + queryWhere.deleted_at = null; + + // 直接映射字段 + const directFields = [ + 'type', 'sub_type', 'status', 'priority', 'role_group', + 'claim_status', 'carrier_claim_status', 'after_sale_no', + 'waybill_no', 'order_delivery_no', 'entry_order_no', + 'order_stockout_no', 'receiving_no', 'warehouse_id', + 'store_id', 'creator_id', + ]; + + for (const field of directFields) { + if (where[field] !== undefined && where[field] !== null) { + queryWhere[field] = this._resolveConditionValue(where[field], Op); + } + } + + // 快捷搜索:在 after_sale_no / title / waybill_no 等字段中模糊搜索 + if (where.quickWhere !== undefined && where.quickWhere !== null) { + const quickValue = this._extractConditionValue(where.quickWhere); + if (quickValue !== undefined && quickValue !== null && String(quickValue).trim() !== '') { + const likePattern = { [Op.like]: `%${String(quickValue).trim()}%` }; + queryWhere[Op.or] = [ + { after_sale_no: likePattern }, + { title: likePattern }, + { waybill_no: likePattern }, + { order_delivery_no: likePattern }, + { entry_order_no: likePattern }, + { order_stockout_no: likePattern }, + { receiving_no: likePattern }, + ]; + } + } + + return queryWhere; + } + + /** + * 解析标准化条件值为 Sequelize 可用的条件对象。 + * + * @param {*} condition 标准化条件(可能是 {operator, value} 或直接值) + * @param {Object} Op Sequelize Op 对象 + * @return {*} Sequelize 条件 + */ + _resolveConditionValue(condition, Op) { + if (condition && typeof condition === 'object' && !Array.isArray(condition)) { + const operator = condition.operator; + const value = condition.value; + + if (!operator) { + return value; + } + + switch (operator) { + case 'eq': + return value; + case 'ne': + return { [Op.ne]: value }; + case 'in': + return { [Op.in]: Array.isArray(value) ? value : [ value ] }; + case 'notin': + return { [Op.notIn]: Array.isArray(value) ? value : [ value ] }; + case 'like': + return { [Op.like]: `%${value}%` }; + case 'gt': + return { [Op.gt]: value }; + case 'gte': + return { [Op.gte]: value }; + case 'lt': + return { [Op.lt]: value }; + case 'lte': + return { [Op.lte]: value }; + case 'between': + return { [Op.between]: Array.isArray(value) ? value : [ value ] }; + default: + return value; + } + } + + return condition; + } + + /** + * 从条件对象中提取原始 value。 + * + * @param {*} condition 标准化条件 + * @return {*} 原始值 + */ + _extractConditionValue(condition) { + if (condition && typeof condition === 'object' && !Array.isArray(condition)) { + if ('value' in condition) { + return condition.value; + } + } + return condition; + } + + /** + * 根据 sort 参数构建 Sequelize 排序数组。 + * + * @param {Object} sort 排序参数 + * @param {string} [sort.sortField] 排序字段 + * @param {string} [sort.sort_order] 排序顺序 + * @param {string} [sort.sortOrder] 排序顺序(驼峰) + * @return {Array>} Sequelize order 数组 + */ + _buildListOrder(sort = {}) { + const sortField = sort.sortField || sort.sort_field || 'created_at'; + const sortOrderRaw = (sort.sortOrder || sort.sort_order || 'desc').toLowerCase(); + const sortOrder = sortOrderRaw === 'asc' ? 'ASC' : 'DESC'; + + // 允许排序的字段白名单 + const allowedSortFields = new Set([ + 'id', 'after_sale_no', 'type', 'sub_type', 'status', 'priority', + 'role_group', 'created_at', 'updated_at', 'resolved_at', + 'claim_status', 'carrier_claim_status', + ]); + + const safeSortField = allowedSortFields.has(sortField) ? sortField : 'created_at'; + + return [[ safeSortField, sortOrder ]]; + } + + // =========================== + // 明细查询 + // =========================== + + /** + * 售后单明细查询,包含主表信息、步骤列表及附件。 + * + * @param {number} id 售后单主键ID + * @return {Promise} 售后单明细,包含主表、步骤列表(含附件) + * @throws {Error} 售后单不存在时抛出 + */ + async getDetail(id) { + const { ctx } = this; + + // 查询主表 + const afterSale = await ctx.model.AfterSale.findOne({ + where: { id, deleted_at: null }, + raw: true, + }); + + if (!afterSale) { + throw new Error('售后单不存在'); + } + + // 查询步骤列表(按创建时间升序) + const steps = await ctx.model.AfterSaleDetail.findAll({ + where: { after_sale_id: id, deleted_at: null }, + order: [[ 'created_at', 'ASC' ]], + raw: true, + }); + + // 查询步骤附件 + const stepsWithAttachments = await this._enrichStepsWithAttachments(steps); + + return { + ...afterSale, + steps: stepsWithAttachments, + }; + } + + /** + * 为步骤列表补充附件信息。 + * + * @param {Array} steps 步骤列表 + * @return {Promise>} 含附件信息的步骤列表 + */ + async _enrichStepsWithAttachments(steps = []) { + const { ctx } = this; + + if (!steps || steps.length === 0) { + return []; + } + + const detailIds = steps.map(s => s.id).filter(Boolean); + if (detailIds.length === 0) { + return steps; + } + + // 查询所有步骤的附件引用 + const references = await ctx.model.FileReference.findAll({ + where: { + business_type: 'after_sale_detail', + business_id: { [ctx.app.Sequelize.Op.in]: detailIds.map(String) }, + }, + include: [ + { + model: ctx.model.File, + as: 'file', + attributes: [ 'id', 'file_key', 'file_url', 'file_name', 'file_size', 'mime_type' ], + required: false, + }, + ], + raw: false, + }); + + // 构建 detailId → files 映射 + const attachmentMap = new Map(); + for (const ref of references) { + const refJson = ref.toJSON ? ref.toJSON() : ref; + const detailId = Number(refJson.business_id); + const fileInfo = refJson.file || null; + + if (!detailId) continue; + + if (!attachmentMap.has(detailId)) { + attachmentMap.set(detailId, []); + } + + if (fileInfo) { + attachmentMap.get(detailId).push({ + id: fileInfo.id, + file_key: fileInfo.file_key, + file_url: fileInfo.file_url, + file_name: fileInfo.file_name, + file_size: fileInfo.file_size, + mime_type: fileInfo.mime_type, + }); + } + } + + // 为每个步骤挂载附件 + return steps.map(step => ({ + ...step, + attachments: attachmentMap.get(step.id) || [], + })); + } + + // =========================== + // 创建售后单 + // =========================== + + /** + * 创建售后单主表记录。 + * + * @param {Object} data 售后单数据 + * @param {number} data.warehouse_id 仓库ID + * @param {string} data.after_sale_no 售后单号 + * @param {string} data.type 售后类型 + * @param {string} data.sub_type 售后子类型 + * @param {string} data.title 售后标题 + * @param {string} [data.description] 售后描述 + * @param {number} [data.priority] 优先级 + * @param {number} data.creator_id 创建人ID + * @param {string} [data.role_group] 当前处理角色组 + * @param {string} [data.status] 售后状态 + * @param {Object} [transaction] Sequelize 事务对象 + * @return {Promise} 创建的售后单记录 + */ + async create(data, transaction = null) { + const { ctx } = this; + const record = await ctx.model.AfterSale.create(data, { transaction }); + return record && record.toJSON ? record.toJSON() : record; + } + + // =========================== + // 更新售后单 + // =========================== + + /** + * 更新售后单主表字段。 + * + * @param {number} id 售后单主键ID + * @param {Object} data 需要更新的字段键值对 + * @param {Object} [transaction] Sequelize 事务对象 + * @return {Promise} 更新后的售后单记录 + * @throws {Error} 售后单不存在时抛出 + */ + async update(id, data, transaction = null) { + const { ctx } = this; + + const record = await ctx.model.AfterSale.findOne({ + where: { id, deleted_at: null }, + transaction, + }); + + if (!record) { + throw new Error('售后单不存在'); + } + + await record.update(data, { transaction }); + return record && record.toJSON ? record.toJSON() : record; + } + + // =========================== + // 步骤记录 + // =========================== + + /** + * 写入一条售后进度步骤记录。 + * + * @param {number} afterSaleId 售后单主键ID + * @param {Object} stepData 步骤数据 + * @param {number} [stepData.step_status=2] 步骤状态(0=待开始,1=进行中,2=已完成,3=已跳过) + * @param {number} [stepData.operator_id] 操作人账户ID + * @param {string} [stepData.operator_snapshot] 操作人信息快照 JSON + * @param {string} [stepData.action] 操作动作描述 + * @param {string} [stepData.remark] 处理备注 + * @param {Date} [stepData.started_at] 步骤开始时间 + * @param {Date} [stepData.completed_at] 步骤完成时间 + * @param {Object} [transaction] Sequelize 事务对象 + * @return {Promise} 创建的步骤记录 + */ + async addStep(afterSaleId, stepData = {}, transaction = null) { + const { ctx } = this; + const now = new Date(); + + const record = await ctx.model.AfterSaleDetail.create({ + after_sale_id: afterSaleId, + step_status: stepData.step_status !== undefined ? stepData.step_status : 2, + operator_id: stepData.operator_id || null, + operator_snapshot: stepData.operator_snapshot || null, + action: stepData.action || null, + remark: stepData.remark || null, + started_at: stepData.started_at || now, + completed_at: stepData.completed_at || now, + created_at: now, + }, { transaction }); + + return record && record.toJSON ? record.toJSON() : record; + } + + // =========================== + // 附件绑定 + // =========================== + + /** + * 将文件绑定到售后步骤(批量)。 + * 通过 wms_file_reference 表建立关联。 + * + * @param {number} detailId 售后步骤ID + * @param {number[]} fileIds 文件ID列表 + * @param {Object} [transaction] Sequelize 事务对象 + * @return {Promise>} 创建的文件引用记录列表 + */ + async bindAttachments(detailId, fileIds = [], transaction = null) { + const { ctx } = this; + + if (!detailId || !Array.isArray(fileIds) || fileIds.length === 0) { + return []; + } + + const warehouseId = ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : 0; + const createdBy = ctx.user + ? String(ctx.user.employees_name || ctx.user.real_name || ctx.user.name || ctx.user.id || '') + : ''; + + const references = []; + for (const fileId of fileIds) { + // 检查是否已存在绑定,防止重复 + const existing = await ctx.model.FileReference.findOne({ + where: { + file_id: fileId, + warehouse_id: warehouseId, + business_type: 'after_sale_detail', + business_id: String(detailId), + }, + transaction, + }); + + if (existing) { + references.push(existing); + continue; + } + + const reference = await ctx.model.FileReference.create({ + file_id: fileId, + warehouse_id: warehouseId, + business_type: 'after_sale_detail', + business_id: String(detailId), + display_order: 0, + created_by: createdBy, + created_at: new Date(), + }, { transaction }); + + references.push(reference); + } + + return references.map(r => (r && r.toJSON ? r.toJSON() : r)); + } + + // =========================== + // 转单 + // =========================== + + /** + * 转单:更新售后单 role_group 并写入步骤记录。 + * + * @param {Object} params 转单参数 + * @param {number} params.id 售后单主键ID + * @param {string} params.targetRoleGroup 目标角色组 + * @param {string} params.remark 转单备注 + * @param {number} params.operatorId 操作人ID + * @param {string} params.operatorSnapshot 操作人快照 JSON + * @return {Promise} 更新后的售后单记录 + */ + async transfer(params = {}) { + const { id, targetRoleGroup, remark, operatorId, operatorSnapshot } = params; + + const transaction = await this.ctx.model.transaction(); + + try { + // 更新 role_group + const updated = await this.update(id, { + role_group: targetRoleGroup, + updated_at: new Date(), + }, transaction); + + // 写入步骤记录 + await this.addStep(id, { + step_status: 2, + operator_id: operatorId, + operator_snapshot: operatorSnapshot, + action: '转单', + remark: remark || `转至${targetRoleGroup}`, + started_at: new Date(), + completed_at: new Date(), + }, transaction); + + await transaction.commit(); + return updated; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + // =========================== + // 处理工单 + // =========================== + + /** + * 处理工单:校验权限 → 写步骤 → 可选更新状态 → 变量回设 → 绑附件。 + * + * @param {Object} params 处理参数 + * @param {number} params.id 售后单主键ID + * @param {string} params.action 操作动作描述 + * @param {string|null} params.remark 处理备注 + * @param {string|null} params.targetStatus 目标售后状态 + * @param {string|null} params.resolution 完结处理结果 + * @param {number[]} params.attachmentIds 附件文件ID列表 + * @param {number} params.operatorId 操作人ID + * @param {string} params.operatorSnapshot 操作人快照 JSON + * @param {number} params.warehouseId 仓库ID + * @return {Promise} 处理结果,包含更新后的售后单和步骤记录 + * @throws {Error} 售后单不存在或权限不足时抛出 + */ + async handleWorkOrder(params = {}) { + const { + id, action, remark, targetStatus, resolution, + attachmentIds, operatorId, operatorSnapshot, + warehouseId, + } = params; + + const { ctx } = this; + + // 1. 查询售后单并校验存在性(限定仓库范围) + const afterSale = await ctx.model.AfterSale.findOne({ + where: { id, warehouse_id: warehouseId, deleted_at: null }, + }); + + if (!afterSale) { + throw new Error('售后单不存在'); + } + + // 2. 校验 role_group 权限:操作人必须有对应 role_group 的处理权限。 + // 实际权限解析已在方法层(systemMethods/afterSale.js)通过 block 权限完成, + // 此处仅做兜底校验。 + const allowedRoleGroups = [ 'customer_service', 'warehouse', 'finance' ]; + const currentRoleGroup = afterSale.role_group; + + if (currentRoleGroup && !allowedRoleGroups.includes(currentRoleGroup)) { + throw new Error('无权限处理当前角色组的售后单'); + } + + // 3. 开启事务 + const transaction = await ctx.model.transaction(); + + try { + const now = new Date(); + + // 4. 写入步骤记录 + const step = await this.addStep(id, { + step_status: 2, + operator_id: operatorId, + operator_snapshot: operatorSnapshot, + action, + remark, + started_at: now, + completed_at: now, + }, transaction); + + // 5. 绑定附件 + if (Array.isArray(attachmentIds) && attachmentIds.length > 0) { + await this.bindAttachments(step.id, attachmentIds, transaction); + } + + // 6. 更新售后单状态 + const updateFields = { updated_at: now }; + + if (targetStatus) { + updateFields.status = targetStatus; + + // 若完结,写入 resolution 和 resolved_at + if (targetStatus === 'completed') { + updateFields.resolution = resolution || null; + updateFields.resolved_at = now; + } + } + + // 7. 若当前角色非客服组且状态非完结,自动回设为客服组 + if (currentRoleGroup && currentRoleGroup !== 'customer_service' && targetStatus !== 'completed') { + updateFields.role_group = 'customer_service'; + } + + await afterSale.update(updateFields, { transaction }); + + await transaction.commit(); + + const updatedAfterSale = afterSale.toJSON ? afterSale.toJSON() : afterSale; + + return { + after_sale: updatedAfterSale, + step, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + // =========================== + // 登记理赔 + // =========================== + + /** + * 登记理赔:更新售后单的理赔字段,写入步骤记录,绑定附件。 + * + * @param {Object} params 理赔参数 + * @param {number} params.id 售后单主键ID + * @param {number} [params.claimNeeded] 仓库理赔标记 + * @param {number} [params.claimAmount] 仓库理赔金额 + * @param {string} [params.claimStatus] 仓库理赔状态 + * @param {number} [params.carrierClaimNeeded] 运方理赔标记 + * @param {number} [params.carrierClaimAmount] 运方理赔金额 + * @param {string} [params.carrierClaimStatus] 运方理赔状态 + * @param {string|null} params.remark 理赔备注 + * @param {string} params.action 操作动作描述 + * @param {number[]} params.attachmentIds 附件文件ID列表 + * @param {number} params.operatorId 操作人ID + * @param {string} params.operatorSnapshot 操作人快照 JSON + * @param {number} params.warehouseId 仓库ID + * @return {Promise} 理赔处理结果 + * @throws {Error} 售后单不存在时抛出 + */ + async registerClaim(params = {}) { + const { + id, claimNeeded, claimAmount, claimStatus, + carrierClaimNeeded, carrierClaimAmount, carrierClaimStatus, + remark, action, attachmentIds, operatorId, operatorSnapshot, + } = params; + + const { ctx } = this; + + // 校验售后单存在 + const afterSale = await ctx.model.AfterSale.findOne({ + where: { id, deleted_at: null }, + }); + + if (!afterSale) { + throw new Error('售后单不存在'); + } + + const transaction = await ctx.model.transaction(); + + try { + const now = new Date(); + + // 构建更新字段(仅含非空传入值) + const updateFields = { updated_at: now }; + + if (claimNeeded !== undefined) updateFields.claim_needed = claimNeeded; + if (claimAmount !== undefined) updateFields.claim_amount = claimAmount; + if (claimStatus !== undefined) updateFields.claim_status = claimStatus; + if (carrierClaimNeeded !== undefined) updateFields.carrier_claim_needed = carrierClaimNeeded; + if (carrierClaimAmount !== undefined) updateFields.carrier_claim_amount = carrierClaimAmount; + if (carrierClaimStatus !== undefined) updateFields.carrier_claim_status = carrierClaimStatus; + + await afterSale.update(updateFields, { transaction }); + + // 写入步骤 + const step = await this.addStep(id, { + step_status: 2, + operator_id: operatorId, + operator_snapshot: operatorSnapshot, + action, + remark, + started_at: now, + completed_at: now, + }, transaction); + + // 绑定附件 + if (Array.isArray(attachmentIds) && attachmentIds.length > 0) { + await this.bindAttachments(step.id, attachmentIds, transaction); + } + + await transaction.commit(); + + const updatedAfterSale = afterSale.toJSON ? afterSale.toJSON() : afterSale; + + return { + after_sale: updatedAfterSale, + step, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + // =========================== + // 导出 + // =========================== + + /** + * 售后单导出:分页查询 → ExcelJS 流式写入 → COS 上传。 + * 通过 onProgress 回调实时推送进度。 + * + * @param {Object} options 导出选项 + * @param {Object} [options.where] 筛选条件 + * @param {Object} [options.sort] 排序参数 + * @param {Function} [options.onProgress] 进度回调 + * @return {Promise} 导出结果,包含文件下载信息 + */ + async exportAfterSales(options = {}) { + const { where = {}, sort = {}, onProgress } = options; + + const reportProgress = (status, progress, message, extra = {}) => { + if (typeof onProgress === 'function') { + onProgress({ status, progress, message, ...extra }); + } + }; + + reportProgress('running', 5, '正在准备导出数据...'); + + // 先统计总数 + const { count: totalCount } = await this.ctx.model.AfterSale.findAndCountAll({ + where: this._buildListWhere(where, this.ctx.app.Sequelize.Op), + raw: true, + }); + + reportProgress('running', 10, `共 ${totalCount} 条记录,开始导出...`, { totalCount, currentCount: 0 }); + + // 分页查询并导出 + const pageSize = 500; + const totalPages = Math.ceil(totalCount / pageSize); + const allRows = []; + + for (let page = 1; page <= totalPages; page++) { + const result = await this.list(where, { page, pageSize }, sort); + const rows = Array.isArray(result.list) ? result.list : []; + allRows.push(...rows); + + const progress = 10 + Math.floor(((page / totalPages) * 80)); + reportProgress('running', progress, `正在导出... (${allRows.length}/${totalCount})`, { + totalCount, + currentCount: allRows.length, + }); + + // 每页之间稍作让渡,避免长时间阻塞 + await new Promise(resolve => setImmediate(resolve)); + } + + reportProgress('running', 90, '正在上传文件...', { totalCount, currentCount: allRows.length }); + + // 生成 Excel 文件并上传 COS + const exportResult = await this._generateAndUploadExcel(allRows); + + reportProgress('success', 100, '导出完成', { + totalCount, + currentCount: allRows.length, + result: exportResult, + }); + + return { + ...exportResult, + total_count: totalCount, + current_count: allRows.length, + }; + } + + /** + * 生成 Excel 并上传 COS,返回下载信息。 + * + * @param {Array} rows 售后单数据行 + * @return {Promise} { url, fileKey, fileName } + */ + async _generateAndUploadExcel(rows = []) { + const { ctx } = this; + + try { + const ExcelJS = require('exceljs'); + const workbook = new ExcelJS.Workbook(); + const worksheet = workbook.addWorksheet('售后单列表'); + + // 定义列 + worksheet.columns = [ + { header: '售后单号', key: 'after_sale_no', width: 22 }, + { header: '售后类型', key: 'type', width: 12 }, + { header: '售后子类型', key: 'sub_type', width: 14 }, + { header: '售后状态', key: 'status', width: 12 }, + { header: '优先级', key: 'priority', width: 10 }, + { header: '标题', key: 'title', width: 30 }, + { header: '描述', key: 'description', width: 30 }, + { header: '当前处理角色', key: 'role_group', width: 16 }, + { header: '仓库理赔状态', key: 'claim_status', width: 14 }, + { header: '仓库理赔金额', key: 'claim_amount', width: 14 }, + { header: '运方理赔状态', key: 'carrier_claim_status', width: 14 }, + { header: '运方理赔金额', key: 'carrier_claim_amount', width: 14 }, + { header: '运单号', key: 'waybill_no', width: 20 }, + { header: '发货订单号', key: 'order_delivery_no', width: 20 }, + { header: '入库单号', key: 'entry_order_no', width: 20 }, + { header: '出库单号', key: 'order_stockout_no', width: 20 }, + { header: '收货单号', key: 'receiving_no', width: 20 }, + { header: '处理结果', key: 'resolution', width: 30 }, + { header: '创建时间', key: 'created_at', width: 20 }, + { header: '更新时间', key: 'updated_at', width: 20 }, + { header: '完结时间', key: 'resolved_at', width: 20 }, + ]; + + // 写入数据行 + for (const row of rows) { + worksheet.addRow(row); + } + + // 生成 buffer + const buffer = await workbook.xlsx.writeBuffer(); + + // 上传到 COS + const now = new Date(); + const dateStr = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}`; + const timestamp = Date.now(); + const fileName = `after_sale_export_${dateStr}_${timestamp}.xlsx`; + const fileKey = `export/after_sale/${fileName}`; + + let url = ''; + try { + if (ctx.service.systems && ctx.service.systems.upload && typeof ctx.service.systems.upload.uploadToCos === 'function') { + const uploadResult = await ctx.service.systems.upload.uploadToCos({ + buffer, + fileKey, + fileName, + mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + }); + url = uploadResult && uploadResult.url ? uploadResult.url : ''; + } + } catch (uploadError) { + ctx.logger.warn(`[afterSale.export] COS 上传失败: ${uploadError.message}`); + } + + return { + url, + fileKey, + fileName, + }; + } catch (error) { + ctx.logger.error(`[afterSale.export] 生成 Excel 失败: ${error.message}`); + return { + url: '', + fileKey: '', + fileName: '', + }; + } + } +} + +module.exports = AfterSaleService; diff --git a/database/designs/after-sale-v2-design.md b/database/designs/after-sale-v2-design.md new file mode 100644 index 0000000..1244763 --- /dev/null +++ b/database/designs/after-sale-v2-design.md @@ -0,0 +1,845 @@ +# 售后模块 V2 设计方案 + +> **状态**: 📋 v1 初稿,待评审 +> **设计日期**: 2026-08-09 +> **设计人**: wms-doc-agent +> **模块**: 售后管理(After-Sale) +> **表**: 2 张 — `wms_after_sale`(售后主表)、`wms_after_sale_detail`(售后进度步骤表) +> **说明**: 本文档为全新设计,替代已移除的旧版 `wms_after_sale_work_order` + `wms_after_sale_work_order_step` 体系。 + +--- + +## 一、设计背景 + +### 1.1 旧版问题 + +旧版售后工单(`after_sale_work_order` + `after_sale_work_order_step`)已于 2026-08-09 通过迁移 `20260809120000-drop-wms-after-sale-work-order.js` 正式移除。旧版存在以下核心问题: + +1. **多态关联难以维护**:使用 `business_type` + `business_sub_type` + `business_id` 三元组关联业务单据,导致: + - 查询需要动态拼接 JOIN 条件,性能差 + - 无法利用数据库外键约束保证数据完整性 + - 业务类型枚举膨胀,新增业务类型需改动多处代码 +2. **不支持多单据共存**:一个售后单只能关联一种业务单据,实际场景中退货退款往往同时涉及运单、发货订单、收货单等多张单据 +3. **覆盖场景不足**:旧版仅覆盖工单流转,未涵盖理赔、投诉等售后场景 +4. **缺少明细层级**:无法记录售后单中的商品明细(退什么货、换什么货、赔多少钱) + +### 1.2 V2 设计目标 + +| 目标 | 说明 | +|------|------| +| **废弃多态关联** | 每种业务单据使用独立字段,类型安全、查询高效 | +| **支持多单据共存** | 一个售后单可同时关联运单、发货订单、入库单、出库单、收货单等 | +| **覆盖全场景** | 按单据维度分类(订单/收货单/入库单/出库单),售后动作(退货/换货/理赔/投诉等)通过进度步骤体现 | +| **进度追溯** | `wms_after_sale_detail` 记录售后处理进度步骤,支持按步骤序号追踪操作人、操作动作、处理时间 | +| **可追溯** | 完整记录创建人、处理人、最终处理结果、完结时间 | + +### 1.3 与旧版核心差异 + +| 维度 | 旧版(已移除) | V2(本设计) | +|------|---------------|-------------| +| 主表 | `wms_after_sale_work_order` | `wms_after_sale` | +| 子表 | `wms_after_sale_work_order_step`(工单步骤流转) | `wms_after_sale_detail`(售后进度步骤) | +| 单据关联 | 多态三元组 `business_type + business_sub_type + business_id` | 每种单据独立字段组,可多个同时有值 | +| 多单据共存 | ❌ 不支持 | ✅ 支持 | +| 理赔 | ❌ 不支持 | ✅ 内建仓库理赔(`claim_needed / claim_amount / claim_status`)和运方理赔(`carrier_claim_needed / carrier_claim_amount / carrier_claim_status`) | +| 进度步骤 | ❌ `after_sale_work_order_step` | ✅ `wms_after_sale_detail` 记录步骤序号/操作人/操作动作/耗时 | +| 商品明细 | ❌ 无 | ❌ 不再独立建表,商品明细可存入 `remark` 或扩展 JSON 字段 | + +--- + +## 二、ER 图 + +```mermaid +erDiagram + wms_after_sale ||--o{ wms_after_sale_detail : "1:N" + + wms_after_sale { + BIGINT id PK "主键" + BIGINT warehouse_id "仓库ID" + BIGINT store_id "货主ID" + VARCHAR after_sale_no UK "售后单号,唯一" + VARCHAR type "售后类型" + VARCHAR sub_type "售后子类型" + VARCHAR status "状态" + INT priority "优先级" + VARCHAR title "标题" + TEXT description "描述" + BIGINT creator_id "创建人" + BIGINT inbox_message_id "关联消息ID" + VARCHAR role_group "角色组" + TEXT resolution "最终处理结果" + DATETIME resolved_at "完结时间" + TINYINT claim_needed "仓库理赔标记" + DECIMAL claim_amount "仓库理赔金额(元)" + VARCHAR claim_status "仓库理赔状态" + TINYINT carrier_claim_needed "运方理赔标记" + DECIMAL carrier_claim_amount "运方理赔金额(元)" + VARCHAR carrier_claim_status "运方理赔状态" + BIGINT waybill_id "运单ID" + VARCHAR waybill_no "运单号" + BIGINT order_delivery_id "发货订单ID" + VARCHAR order_delivery_no "发货订单号" + BIGINT entry_order_id "入库单ID" + VARCHAR entry_order_no "入库单号" + BIGINT order_stockout_id "出库单ID" + VARCHAR order_stockout_no "出库单号" + BIGINT receiving_id "收货单ID" + VARCHAR receiving_no "收货单号" + DATETIME created_at "创建时间" + DATETIME updated_at "更新时间" + DATETIME deleted_at "软删除" + } + + wms_after_sale_detail { + BIGINT id PK "主键" + BIGINT after_sale_id FK "关联售后主表" + TINYINT step_status "步骤状态" + BIGINT operator_id "操作人ID" + TEXT operator_snapshot "操作人信息快照" + VARCHAR action "操作动作" + TEXT remark "处理备注" + DATETIME started_at "步骤开始时间" + DATETIME completed_at "步骤完成时间" + DATETIME created_at "创建时间" + DATETIME updated_at "更新时间" + DATETIME deleted_at "软删除" + } +``` + +### 关联关系说明 + +``` +wms_after_sale + ├─ warehouse_id → stores.id(仓库,逻辑关联) + ├─ store_id → stores.id(货主,逻辑关联) + ├─ creator_id → accounts.id(创建人,逻辑关联) + ├─ inbox_message_id → wms_inbox_message.id(站内信消息,逻辑关联) + ├─ waybill_id → wms_order_express.id(运单,逻辑关联) + ├─ order_delivery_id → wms_order_delivery.id(发货订单,逻辑关联) + ├─ entry_order_id → wms_entry_order.id(入库单,逻辑关联) + ├─ order_stockout_id → wms_order_stockout.id(出库单,逻辑关联) + └─ receiving_id → wms_receiving.id(收货单,逻辑关联) + +wms_after_sale_detail + └─ after_sale_id → wms_after_sale.id(级联删除) +``` + +> **注意**:所有关联均为逻辑关联(不做物理外键),遵循项目现有惯例。 + +--- + +## 三、数据库表 + +### 3.1 表 A:售后主表 `wms_after_sale` + +#### 3.1.1 基础字段 + +| 字段 | 类型 | 必填 | 默认值 | 说明 | +|------|------|------|--------|------| +| `id` | `BIGINT UNSIGNED` | ✅ | AUTO | 主键 | +| `warehouse_id` | `BIGINT UNSIGNED` | ✅ | — | 仓库ID | +| `store_id` | `BIGINT UNSIGNED` | — | NULL | 货主ID | + +#### 3.1.2 售后信息 + +| 字段 | 类型 | 必填 | 默认值 | 说明 | +|------|------|------|--------|------| +| `after_sale_no` | `VARCHAR(50)` | ✅ | — | **售后单号**,唯一索引。生成规则:前缀 `AS` + 日期 `YYYYMMDD` + 6 位序号(当天同仓库自增),如 `AS20260809000001`。参考波次号 `wave_no` 生成逻辑。 | +| `type` | `VARCHAR(20)` | ✅ | — | 售后类型,枚举见 §3.1.6 | +| `sub_type` | `VARCHAR(50)` | ✅ | — | 售后子类型,枚举见 §3.1.6,与 type 组成二级分类 | +| `status` | `VARCHAR(20)` | ✅ | `pending` | 售后状态,枚举及流转见 §五 | +| `priority` | `INT(11)` | ✅ | 0 | 优先级,数值越大越优先(0=普通,10=紧急) | +| `title` | `VARCHAR(200)` | ✅ | — | 售后标题(简要描述) | +| `description` | `TEXT` | — | NULL | 售后详细描述 | + +#### 3.1.3 人员信息 + +| 字段 | 类型 | 必填 | 默认值 | 说明 | +|------|------|------|--------|------| +| `creator_id` | `BIGINT UNSIGNED` | ✅ | — | 创建人账户ID(关联 `accounts` 表) | +| `role_group` | `VARCHAR(50)` | — | NULL | 当前处理角色组,用于角色维度查询待处理工单和转单。枚举见 §3.1.6。NULL 表示未分配。 | +| `inbox_message_id` | `BIGINT UNSIGNED` | — | NULL | 关联 `wms_inbox_message.id`(站内信消息主键)。为空表示无关联信息,非空表示该售后单由对应站内信消息创建或关联。 | + +#### 3.1.4 处理结果 + +| 字段 | 类型 | 必填 | 默认值 | 说明 | +|------|------|------|--------|------| +| `resolution` | `TEXT` | — | NULL | 最终处理结果说明 | +| `resolved_at` | `DATETIME` | — | NULL | 完结时间(状态变为 `completed` 时写入) | + +#### 3.1.5 仓库理赔 & 运方理赔 + +**仓库理赔**: + +| 字段 | 类型 | 必填 | 默认值 | 说明 | +|------|------|------|--------|------| +| `claim_needed` | `TINYINT(1)` | ✅ | 0 | 仓库理赔标记:0=不需要,1=需要 | +| `claim_amount` | `DECIMAL(12,2)` | — | NULL | 仓库理赔金额,单位:人民币(元),claim_needed=1 时可填写 | +| `claim_status` | `VARCHAR(20)` | — | NULL | 仓库理赔状态,枚举见 §3.1.6,仅 `claim_needed=1` 时有意义 | + +**运方理赔**: + +| 字段 | 类型 | 必填 | 默认值 | 说明 | +|------|------|------|--------|------| +| `carrier_claim_needed` | `TINYINT(1)` | ✅ | 0 | 运方理赔标记:0=不需要,1=需要 | +| `carrier_claim_amount` | `DECIMAL(12,2)` | — | NULL | 运方理赔金额,单位:人民币(元),carrier_claim_needed=1 时可填写 | +| `carrier_claim_status` | `VARCHAR(20)` | — | NULL | 运方理赔状态,枚举见 §3.1.6,仅 `carrier_claim_needed=1` 时有意义 | + +#### 3.1.6 类型与状态枚举 + +**售后类型 `type` + 售后子类型 `sub_type`**: + +> 售后类型表示售后单主要关联的业务单据类型,售后子类型表示具体售后原因分类,两者组成二级分类。具体的售后动作(退货/换货/理赔/投诉等)通过进度步骤和最终处理结果体现。 + +| type | 说明 | sub_type | +|------|------|----------| +| `order` | 订单 | `damage` 破损, `missing_item` 少发, `mis_shipment` 错发, `wrong_sku` 错品, `quality_issue` 质量问题, `delivery_delay` 发货延迟, `logistics_issue` 物流异常, `rejected` 客户拒收, `intercept` 拦截, `verify_delivery` 核实签收, `urge` 催件, `extra_item` 多发, `change_address` 改地址, `change_carrier` 换快递, `weight_issue` 重量异常, `freight_issue` 运费争议, `other` 其他 | +| `receiving` | 收货单 | `shortage` 少货, `damage` 破损, `wrong_sku` 错品, `quality_issue` 质量问题, `other` 其他 | +| `entry` | 入库单 | `shortage` 少货, `damage` 破损, `wrong_sku` 错品, `quality_issue` 质量问题, `other` 其他 | +| `stockout` | 出库单 | `return_issue` 退货异常, `wrong_outbound` 错发, `shortage` 少发, `other` 其他 | + +**Model 层常量定义**(`app/model/after_sale.js`): + +```javascript +// app/model/after_sale.js 中的常量定义 +const AFTER_SALE_TYPES = [ + { + name: '订单', + type: 'order', + subType: [ + { name: '破损', value: 'damage' }, + { name: '少发', value: 'missing_item' }, + { name: '错发', value: 'mis_shipment' }, + { name: '错品', value: 'wrong_sku' }, + { name: '质量问题', value: 'quality_issue' }, + { name: '发货延迟', value: 'delivery_delay' }, + { name: '物流异常', value: 'logistics_issue' }, + { name: '客户拒收', value: 'rejected' }, + { name: '拦截', value: 'intercept' }, + { name: '核实签收', value: 'verify_delivery' }, + { name: '催件', value: 'urge' }, + { name: '多发', value: 'extra_item' }, + { name: '改地址', value: 'change_address' }, + { name: '换快递', value: 'change_carrier' }, + { name: '重量异常', value: 'weight_issue' }, + { name: '运费争议', value: 'freight_issue' }, + { name: '其他', value: 'other' }, + ], + }, + { + name: '收货单', + type: 'receiving', + subType: [ + { name: '少货', value: 'shortage' }, + { name: '破损', value: 'damage' }, + { name: '错品', value: 'wrong_sku' }, + { name: '质量问题', value: 'quality_issue' }, + { name: '其他', value: 'other' }, + ], + }, + { + name: '入库单', + type: 'entry', + subType: [ + { name: '少货', value: 'shortage' }, + { name: '破损', value: 'damage' }, + { name: '错品', value: 'wrong_sku' }, + { name: '质量问题', value: 'quality_issue' }, + { name: '其他', value: 'other' }, + ], + }, + { + name: '出库单', + type: 'stockout', + subType: [ + { name: '退货异常', value: 'return_issue' }, + { name: '错发', value: 'wrong_outbound' }, + { name: '少发', value: 'shortage' }, + { name: '其他', value: 'other' }, + ], + }, +]; +``` + +**角色组 `role_group`**: + +| 值 | 说明 | +|----|------| +| `customer_service` | 客服组 | +| `warehouse` | 仓库组 | +| `finance` | 财务组 | + +> 设计理由:运方(快递公司)是外部角色,不登录 WMS 系统,不纳入内部角色组。 + +**售后状态 `status`**: + +| 值 | 说明 | +|----|------| +| `pending` | 待处理 | +| `processing` | 处理中 | +| `completed` | 已完成 | +| `closed` | 已关闭 | +| `cancelled` | 已取消 | + +**理赔状态(仓库理赔 & 运方理赔通用枚举)**: + +| 值 | 说明 | +|----|------| +| `pending` | 待理赔 | +| `reviewing` | 审核中 | +| `approved` | 已通过 | +| `paid` | 已打款 | +| `monthly` | 月结 | +| `rejected` | 已拒绝 | + +#### 3.1.7 单据关联字段(核心设计) + +> **设计要点**:每种业务单据使用独立字段组(ID + 单号冗余),替代旧版多态关联。多个字段组可同时有值,实现"一个售后单关联多种单据"。 + +| 字段 | 类型 | 必填 | 默认值 | 说明 | +|------|------|------|--------|------| +| `waybill_id` | `BIGINT UNSIGNED` | — | NULL | 运单ID(关联 `wms_order_express.id`) | +| `waybill_no` | `VARCHAR(50)` | — | NULL | 运单号(冗余字段,方便查询展示) | +| `order_delivery_id` | `BIGINT UNSIGNED` | — | NULL | 发货订单ID(关联 `wms_order_delivery.id`) | +| `order_delivery_no` | `VARCHAR(50)` | — | NULL | 发货订单号(冗余字段) | +| `entry_order_id` | `BIGINT UNSIGNED` | — | NULL | 入库单ID(关联 `wms_entry_order.id`) | +| `entry_order_no` | `VARCHAR(50)` | — | NULL | 入库单号(冗余字段) | +| `order_stockout_id` | `BIGINT UNSIGNED` | — | NULL | 出库单/退货出库单ID(关联 `wms_order_stockout.id`) | +| `order_stockout_no` | `VARCHAR(50)` | — | NULL | 出库单号(冗余字段) | +| `receiving_id` | `BIGINT UNSIGNED` | — | NULL | 收货单ID(关联 `wms_receiving.id`) | +| `receiving_no` | `VARCHAR(50)` | — | NULL | 收货单号(冗余字段) | + +> **冗余字段说明**:`_no` 后缀字段为冗余存储,目的是在售后列表查询时避免 JOIN 各业务表。写入时从对应业务表同步取数,后续若业务表单号变更需同步更新(建议通过业务 hook 或定时任务保证最终一致)。 + +#### 3.1.8 时间戳 + +| 字段 | 类型 | 必填 | 默认值 | 说明 | +|------|------|------|--------|------| +| `created_at` | `DATETIME` | ✅ | `CURRENT_TIMESTAMP` | 创建时间 | +| `updated_at` | `DATETIME` | ✅ | `CURRENT_TIMESTAMP ON UPDATE` | 更新时间 | +| `deleted_at` | `DATETIME` | — | NULL | 软删除时间 | + +--- + +### 3.2 表 B:售后进度步骤表 `wms_after_sale_detail` + +用于记录售后单的处理进度步骤(谁在什么时间做了什么操作)。步骤按 `created_at` 自然时间排序,通过 `action` 描述步骤内容,可记录步骤开始/完成时间、操作人及操作快照。 + +#### 3.2.1 字段定义 + +| 字段 | 类型 | 必填 | 默认值 | 说明 | +|------|------|------|--------|------| +| `id` | `BIGINT UNSIGNED` | ✅ | AUTO | 主键 | +| `after_sale_id` | `BIGINT UNSIGNED` | ✅ | — | 关联售后主表ID(`wms_after_sale.id`) | +| `step_status` | `TINYINT UNSIGNED` | ✅ | 0 | 步骤状态:0=待开始,1=进行中,2=已完成,3=已跳过 | +| `operator_id` | `BIGINT UNSIGNED` | — | NULL | 操作人账户ID(关联 `accounts` 表);可为空,外部系统回调/自动触发的步骤无人操作 | +| `operator_snapshot` | `TEXT` | — | NULL | 操作人信息快照(JSON),如 `{"name":"张三","role":"客服"}`,防止账户删除后历史丢失 | +| `action` | `VARCHAR(100)` | — | NULL | 操作动作描述,如"确认收货"、"审核驳回"、"发起退款" | +| `remark` | `TEXT` | — | NULL | 处理备注 | +| `started_at` | `DATETIME` | — | NULL | 步骤开始时间 | +| `completed_at` | `DATETIME` | — | NULL | 步骤完成时间 | +| `created_at` | `DATETIME` | ✅ | `CURRENT_TIMESTAMP` | 创建时间 | +| `updated_at` | `DATETIME` | ✅ | `CURRENT_TIMESTAMP ON UPDATE` | 更新时间 | +| `deleted_at` | `DATETIME` | — | NULL | 软删除时间 | + +#### 3.2.2 步骤状态 `step_status` 枚举 + +| 值 | 说明 | 典型场景 | +|----|------|---------| +| `0` | 待开始 | 步骤尚未触发,等待前置步骤完成 | +| `1` | 进行中 | 步骤正在处理中 | +| `2` | 已完成 | 步骤处理完毕 | +| `3` | 已跳过 | 因条件不满足或审批豁免而跳过此步骤 | + +> **设计考量**:`step_status` 决定步骤的当前状态。步骤按 `created_at` 自然时间排序,通过 `action` 描述步骤内容。后续步骤在前置步骤全部 `completed` 或 `skipped` 后才能开始。步骤可在创建售后单时预置(如按 `type` 生成一套标准步骤),也可在处理过程中动态追加。 +> +> **外部系统触发说明**:当步骤由外部系统触发(如快递签收回调、支付平台退款回调、ERP 同步等)时,`operator_id` 为 NULL,`action` 记录触发来源(如"快递签收回调"、"支付宝退款通知")。这确保自动触发的步骤可追溯来源,同时与人工操作步骤明确区分。 + +### 3.2.3 附件关联 + +售后进度步骤可通过 `wms_file_reference` 表挂载附件(如破损照片、签收凭证、理赔单据等)。 + +**绑定方式:** + +| wms_file_reference 字段 | 值 | 说明 | +|--------------------------|-----|------| +| `business_type` | `after_sale_detail` | 售后进度步骤 | +| `business_id` | `{wms_after_sale_detail.id}` | 步骤主键ID | + +**典型场景:** +- 仓库验货步骤上传破损商品照片 +- 客服接单步骤上传客户提供的聊天截图 +- 运方理赔步骤上传快递破损证明 +- 退款步骤上传打款凭证截图 + +**查询示例:** +```sql +-- 查询某售后单所有步骤的附件 +SELECT f.*, fr.business_id AS step_id +FROM wms_file_reference fr +JOIN wms_file f ON f.id = fr.file_id +WHERE fr.business_type = 'after_sale_detail' + AND fr.business_id IN ( + SELECT id FROM wms_after_sale_detail WHERE after_sale_id = ? + ); +``` + +--- + +## 四、索引设计 + +### 4.1 `wms_after_sale` 索引 + +| 索引名 | 字段 | 类型 | 说明 | +|--------|------|------|------| +| `PRIMARY` | `id` | 主键 | — | +| `uk_after_sale_no` | `after_sale_no` | 唯一 | 售后单号唯一约束 | +| `idx_warehouse_status` | `warehouse_id`, `status`, `deleted_at` | 普通 | 按仓库+状态查询售后列表(最高频) | +| `idx_warehouse_type` | `warehouse_id`, `type`, `deleted_at` | 普通 | 按仓库+类型筛选 | +| `idx_type_subtype` | `warehouse_id`, `type`, `sub_type`, `deleted_at` | 普通 | 按仓库+类型+子类型筛选 | +| `idx_store_id` | `store_id`, `deleted_at` | 普通 | 按货主查询 | +| `idx_creator_id` | `creator_id`, `deleted_at` | 普通 | 按创建人查询 | +| `idx_role_group` | `role_group`, `status`, `deleted_at` | 普通 | 按角色组+状态查询待处理工单(角色维度) | +| `idx_created_at` | `warehouse_id`, `created_at` | 普通 | 按仓库+时间排序分页 | +| `idx_waybill_id` | `waybill_id` | 普通 | 按运单反查售后单 | +| `idx_order_delivery_id` | `order_delivery_id` | 普通 | 按发货订单反查售后单 | +| `idx_entry_order_id` | `entry_order_id` | 普通 | 按入库单反查售后单 | +| `idx_order_stockout_id` | `order_stockout_id` | 普通 | 按出库单反查售后单 | +| `idx_receiving_id` | `receiving_id` | 普通 | 按收货单反查售后单 | +| `idx_carrier_claim_status` | `carrier_claim_status` | 普通 | 按运方理赔状态筛选 | +| `idx_inbox_message_id` | `inbox_message_id` | 普通 | 按站内信消息反查售后单 | + +### 4.2 `wms_after_sale_detail` 索引 + +| 索引名 | 字段 | 类型 | 说明 | +|--------|------|------|------| +| `PRIMARY` | `id` | 主键 | — | +| `idx_after_sale_id` | `after_sale_id` | 普通 | 按售后单查询进度步骤(最高频) | +| `idx_operator_id` | `operator_id` | 普通 | 按操作人查询其处理的步骤 | + +--- + +## 五、状态流转 + +```mermaid +stateDiagram-v2 + [*] --> pending: 创建售后单 + pending --> processing: 指派处理人 / 开始处理 + pending --> cancelled: 取消 + processing --> completed: 处理完成 + processing --> closed: 强制关闭 + completed --> [*] + closed --> [*] + cancelled --> [*] +``` + +| 流转 | 触发条件 | 说明 | +|------|---------|------| +| `pending` → `processing` | 指派处理人 or 手动开始处理 | 通过 `wms_after_sale_detail` 记录的处理步骤追踪 | +| `pending` → `cancelled` | 创建人取消 | 仅待处理状态可取消 | +| `processing` → `completed` | 处理完毕 | 写入 `resolution` + `resolved_at` | +| `processing` → `closed` | 管理员强制关闭 | 如重复单、无效单等 | +| 转单(跨角色组) | 客服转仓库 / 仓库转财务等 | 更新 `role_group` 为目标角色组,如 `customer_service` → `warehouse`;同时可在 `wms_after_sale_detail` 记录转单步骤 | + +**理赔状态流转**(仓库理赔 & 运方理赔通用):`pending` → `reviewing` → `approved` → `paid`,任意阶段可 → `rejected`,或走 `monthly`(月结)通道。 + +> `wms_after_sale_detail` 即操作日志:每条进度步骤记录操作人、操作动作、处理备注、开始/完成时间,已完整覆盖状态变更追踪需求,无需额外日志表。 + +--- + +## 六、典型使用场景 + +### 场景1:订单售后(退货退款,关联运单 + 收货单) + +``` +售后单 type=order, sub_type=damage, role_group=customer_service +├─ inbox_message_id: 12345(关联站内信消息,客户发送"破损"指令触发) +├─ waybill_id / waybill_no: 客户寄回的快递单号 +├─ receiving_id / receiving_no: 仓库收货单 +└─ 进度步骤: + ├─ step_status=2(已完成), operator_id=1001, action=客服接单-受理退货申请 + ├─ step_status=2(已完成), operator_id=2001, action=仓库收货-确认收货入库 + └─ step_status=0(待开始), action=退款打款 +``` + +> **转单说明**:当客服接单后发现需要仓库核实实物时,可将 `role_group` 从 `customer_service` 更新为 `warehouse`,仓库组即可在自己的待办列表中看到该工单。 + +### 场景2:订单售后(换货,关联运单 + 发货订单) + +``` +售后单 type=order, sub_type=quality_issue +├─ waybill_id / waybill_no: 客户寄回的快递单号 +├─ order_delivery_id / order_delivery_no: 仓库补发的发货订单 +└─ 进度步骤: + ├─ step_status=2(已完成), action=客服接单-确认换货申请 + ├─ step_status=2(已完成), action=退回入库-客户退回商品已入库 + └─ step_status=1(进行中), action=补发换货-仓库补发新商品 +``` + +### 场景3:订单售后(仓库理赔) + +``` +售后单 type=order, sub_type=damage +├─ claim_needed=1, claim_amount=50.00, claim_status=pending +└─ 进度步骤: + ├─ step_status=2(已完成), action=客服接单-受理仓库理赔 + ├─ step_status=2(已完成), action=核实定损, remark=仓库出库破损, 核定赔偿50元 + └─ step_status=1(进行中), action=审批打款 +``` + +### 场景3b:订单售后(运方理赔) + +``` +售后单 type=order, sub_type=logistics_issue +├─ carrier_claim_needed=1, carrier_claim_amount=200.00, carrier_claim_status=pending +├─ waybill_id / waybill_no: 涉损运单 +└─ 进度步骤: + ├─ step_status=2(已完成), action=客服接单-受理运方理赔 + ├─ step_status=2(已完成), action=核实定损, remark=运输途中破损, 核定赔偿200元 + └─ step_status=1(进行中), action=快递审批 +``` + +> **说明**:仓库理赔与运方理赔可同时存在(如货物在仓库出库&运输途中均发生破损),分别使用 `claim_*` 和 `carrier_claim_*` 字段组记录。 + +### 场景4:订单售后(多单据共存:退货退款 + 运单 + 收货单 + 出库单) + +``` +售后单 type=order, sub_type=damage, role_group=warehouse +├─ waybill_id / waybill_no: 客户退货快递 +├─ receiving_id / receiving_no: 仓库收货单 +├─ order_stockout_id / order_stockout_no: 退货出库单 +└─ 进度步骤: + ├─ step_status=2(已完成), action=客服接单-批量退货受理 + ├─ step_status=2(已完成), operator_id=3001, action=验货签收, remark=SKU001×3, SKU002×1 均完好(可挂附件:破损照片 × 2) + ├─ step_status=2(已完成), action=退货入库 + └─ step_status=0(待开始), action=退款打款 +``` + +> **说明**:此场景中 `role_group=warehouse` 表示当前由仓库组负责验货入库环节;验货完成后如需财务退款,转单时将 `role_group` 更新为 `finance`。 + +--- + +## 七、迁移计划 + +### 7.1 迁移文件 + +``` +database/migrations/YYYYMMDDHHMMSS-create-wms-after-sale.js +database/migrations/YYYYMMDDHHMMSS-create-wms-after-sale-detail.js +``` + +### 7.2 Model 文件 + +``` +app/model/after_sale.js → wms_after_sale +app/model/after_sale_detail.js → wms_after_sale_detail +``` + +### 7.3 后续扩展(不纳入本期) + +| 扩展项 | 说明 | +|--------|------| +| 批量创建 | 按运单号/订单号批量生成售后单 | +| 自动创建规则 | 如收到退货快递自动创建售后单 | +| 售后统计看板 | 按仓库/类型/状态统计售后量、理赔金额等 | + +--- + +## 八、版本记录 + +| 版本 | 日期 | 变更内容 | 作者 | +|------|------|---------|------| +| v1 | 2026-08-09 | 初稿,待评审 | wms-doc-agent | + +--- + +## 九、权限设计 + +售后模块的角色组通过 `wms_permission` 表中 `type='block'` 的权限条目来承载,与主表 `role_group` 字段一一对应。 + +### 9.1 Block 权限(角色组区分) + +> ID 516-523 为售后模块固定 ID。 + +| ID | meta_title | type | 对应 role_group | +|----|-----------|------|-----------------| +| 516 | 售后-客服组 | `block` | `customer_service` | +| 517 | 售后-仓库组 | `block` | `warehouse` | +| 518 | 售后-财务组 | `block` | `finance` | + +> 生产组主管(role_code=03)和拣货组组长(role_code=021)使用仓库组 block(517),共享仓库组视角。 + +### 9.2 页面权限 + +| ID | path | meta_title | type | parent_id | +|----|------|-----------|------|-----------| +| 519 | `afterSale` | 售后管理 | `web_pages` | null | +| 520 | `afterSale.list` | 售后列表 | `web_pages` | 519 | +| 521 | `afterSale.detail` | 售后明细 | `web_pages` | 519 | + +### 9.3 API 权限 + +| ID | path | meta_title | type | +|----|------|-----------|------| +| 522 | `afterSale.workList` | API:售后工作列表查询 | `api` | +| 523 | `afterSale.auditList` | API:售后审计列表查询 | `api` | +| 508 | `afterSale.detail` | API:售后明细查询 | `api` | +| 509 | `afterSale.create` | API:创建售后单 | `api` | +| 510 | `afterSale.update` | API:更新售后单 | `api` | +| 511 | `afterSale.transfer` | API:售后转单 | `api` | +| 512 | `afterSale.handleWorkOrder` | API:处理工单 | `api` | +| 513 | `afterSale.registerClaim` | API:登记理赔 | `api` | +| 514 | `afterSale.export` | API:售后导出 | `api` | +| 515 | `afterSale.exportTaskProgress` | API:导出进度查询 | `api` | + +### 9.4 角色权限绑定 + +| 角色 | 角色组 block | 页面 | API | +|------|------------|------|-----| +| 客服 | 516 | 519, 520, 521 | 522, 523, 508, 509, 510, 511, 512, 513, 514, 515 | +| 仓库 | 517 | 519, 520, 521 | 522, 508, 510, 512 | +| 生产组-主管 | 517 | 519, 520, 521 | 522, 508, 510, 512 | +| 拣货组-组长 | 517 | 519, 520, 521 | 522, 508, 510, 512 | +| 财务 | 518 | 519, 520, 521 | 522, 508 | + +> - 客服:全部权限(创建、更新、转单、查理赔) +> - 仓库:只读查询 + 更新处理结果 +> - 生产组-主管 / 拣货组-组长:共享仓库组视角(同仓库组权限),处理退货验货入库等实物操作。普通生产组员工不授权任何售后权限。 +> - 财务:只读查询(理赔审核通过财务系统操作,不走 WMS) + +> **生产组其他角色**(普通员工、复核、其他普工)不授权任何售后权限。 + +--- + +## 十、Methods API 设计 + +### 10.1 概述 + +售后模块 API method 统一以 `afterSale.` 为前缀,使用 `/system` 网关接入。工作列表与审计列表分离,导出采用异步任务模式。 + +### 10.2 列表一:工作列表 `afterSale.workList` + +**定位**:仓库内员工看到自己角色组需要处理的工单。 + +**可见性规则:** +- 创建时 `role_group` 默认为 `customer_service`,仅客服组可见 +- 转单后(如 `customer_service` → `warehouse`),原角色组不再可见,目标角色组可见 +- 用户通过角色绑定的 block 权限(516/517/518)确定可见哪些 role_group +- **核心逻辑**:`WHERE role_group IN (用户拥有的售后block对应的role_group)` 且 `status != 'completed' AND status != 'cancelled'` + +**method 定义:** +```json +{ + "method": "afterSale.workList", + "description": "售后工作列表。仅返回当前用户角色组负责的待处理工单。创建时默认进入客服组,转单后原组不可见、目标组可见。", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [ + { "name": "pagination", "type": "object", "required": false, "source": "body", "description": "分页参数 page/pageSize" }, + { "name": "where", "type": "object", "required": false, "source": "body", "description": "筛选条件:支持 type/sub_type/status/priority/after_sale_no/waybill_no 等字段筛选,以及 quickWhere 快捷搜索" }, + { "name": "sort", "type": "object", "required": false, "source": "body", "description": "排序参数 sortField/sortOrder,默认按 priority DESC, created_at DESC" } + ], + "response": [ + { "name": "list", "type": "array", "required": true, "description": "售后工单列表" }, + { "name": "pagination", "type": "object", "required": true, "description": "分页信息" } + ] +} +``` + +### 10.3 列表二:审计列表 `afterSale.auditList` + +**定位**:所有售后单全局视图,不限角色组,用于审计和管理。 + +**可见性规则:** +- 所有 `status` 的工单均可见(包括 completed/cancelled) +- 不限 `role_group` +- 与工作列表共享 where/sort/pagination 参数格式 + +**method 定义:** +```json +{ + "method": "afterSale.auditList", + "description": "售后审计列表。全局售后单视图,不限角色组、不限状态,用于审计和统计分析。入参与 afterSale.workList 一致。", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [ + { "name": "pagination", "type": "object", "required": false, "source": "body" }, + { "name": "where", "type": "object", "required": false, "source": "body", "description": "同 workList,额外支持 claim_status/carrier_claim_status 筛选" }, + { "name": "sort", "type": "object", "required": false, "source": "body" } + ], + "response": [ + { "name": "list", "type": "array", "required": true }, + { "name": "pagination", "type": "object", "required": true } + ] +} +``` + +### 10.4 导出接口 `afterSale.export` + `afterSale.exportTaskProgress` + +参考项目现有导出模式(`order.export` / `order.exportTaskProgress`)。 + +**`afterSale.export`:** +```json +{ + "method": "afterSale.export", + "description": "提交售后审计列表导出任务(异步)。入参 where/sort 与 afterSale.auditList 完全一致。提交后立即返回 task_id,后台异步执行 Excel 生成并上传 COS。通过 afterSale.exportTaskProgress 查询进度和下载链接。", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [ + { "name": "where", "type": "object", "required": false, "source": "body", "description": "查询条件,与 afterSale.auditList 的 where 语义一致" }, + { "name": "sort", "type": "object", "required": false, "source": "body", "description": "排序参数,与 afterSale.auditList 的 sort 语义一致" } + ], + "response": [ + { "name": "task_id", "type": "string", "required": true, "description": "导出任务ID" }, + { "name": "status", "type": "string", "required": true, "description": "submitted/running/success/failed" }, + { "name": "progress", "type": "number", "required": true, "description": "0-100" }, + { "name": "message", "type": "string", "required": true } + ] +} +``` + +**`afterSale.exportTaskProgress`:** +```json +{ + "method": "afterSale.exportTaskProgress", + "description": "查询售后导出任务进度和下载链接。", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [ + { "name": "task_id", "type": "string", "required": true, "source": "body", "description": "导出任务ID" } + ], + "response": [ + { "name": "task_id", "type": "string", "required": true }, + { "name": "status", "type": "string", "required": true }, + { "name": "progress", "type": "number", "required": true }, + { "name": "download_url", "type": "string", "required": false, "description": "status=success 时返回 Excel 下载链接" }, + { "name": "error", "type": "string", "required": false, "description": "status=failed 时返回错误信息" } + ] +} +``` + +### 10.5 其他 methods + +| method | 说明 | 权限 | +|--------|------|------| +| `afterSale.create` | 创建售后单 | 客服 | +| `afterSale.detail` | 售后明细(主表+步骤列表) | 全部 | +| `afterSale.update` | 更新售后单 | 客服/仓库 | +| `afterSale.transfer` | 转单(更新 role_group) | 客服 | +| `afterSale.handleWorkOrder` | 处理工单(写步骤+绑附件) | 当前 role_group 匹配的用户 | +| `afterSale.registerClaim` | 登记售后理赔信息(仓库理赔+运方理赔) | 客服 | + +### 10.6 导出流程说明 + +导出流程参考项目现有异步导出模式(`order.export`): + +1. 客户端调用 `afterSale.export` 提交导出任务,服务端生成 `task_id`,在 Redis 中初始化任务状态为 `submitted` +2. 通过 `setImmediate` 启动异步执行,立即返回 `task_id` 给客户端 +3. 后台任务分页查询售后数据,使用 ExcelJS 流式写入 Excel 文件 +4. Excel 生成完成后上传至 COS,获取下载链接 +5. 更新 Redis 中任务状态为 `success`,并写入 `download_url` +6. 若任一步骤失败,更新任务状态为 `failed`,并写入错误信息 +7. 客户端轮询 `afterSale.exportTaskProgress` 获取进度和下载链接 + +**Redis 缓存规范:** +- Key 格式:`after_sale_export_task_{task_id}` +- TTL:30 分钟(任务完成后自动过期) + +### 10.7 处理工单 `afterSale.handleWorkOrder` + +```json +{ + "method": "afterSale.handleWorkOrder", + "description": "处理售后工单。员工在工作列表中对工单进行操作,写入进度步骤并绑定附件。操作人信息从登录上下文自动获取。非客服组处理完成后自动转回客服组继续跟进。", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [ + { "name": "id", "type": "integer", "required": true, "source": "body", "description": "售后工单主表ID(wms_after_sale.id)" }, + { "name": "status", "type": "string", "required": false, "source": "body", "description": "更新售后单状态(pending/processing/completed/closed),不传则保持当前状态" }, + { "name": "action", "type": "string", "required": true, "source": "body", "description": "操作动作描述,如"客服接单"、"仓库验货"、"确认收货入库"、"退款打款"" }, + { "name": "remark", "type": "string", "required": false, "source": "body", "description": "处理备注/消息主体" }, + { "name": "attachment_ids", "type": "array", "required": false, "source": "body", "description": "附件 file_id 数组,如 [123, 456]。处理时自动绑定到本次步骤。" } + ], + "response": [ + { "name": "detail_id", "type": "integer", "required": true, "description": "本次写入的 wms_after_sale_detail.id" }, + { "name": "after_sale_id", "type": "integer", "required": true } + ], + "errors": [ + { "code": 400, "message": "工单不存在或参数缺失" }, + { "code": 403, "message": "无权限处理该工单(role_group 不匹配)" }, + { "code": 500, "message": "处理失败" } + ] +} +``` + +**处理流程:** + +1. 校验工单 `id` 存在,且当前用户 `role_group` 与工单 `role_group` 匹配(否则 403) +2. 从登录上下文(JWT token)提取操作人 `operator_id` 和 `operator_snapshot` +3. 写入 `wms_after_sale_detail`: + - `step_status = 2`(已完成) + - `action` = 入参 `action` + - `remark` = 入参 `remark` + - `operator_id` / `operator_snapshot` = 当前用户 + - `started_at = now`, `completed_at = now` +4. 若传入了 `attachment_ids`,遍历写入 `wms_file_reference`: + - `business_type = 'after_sale_detail'` + - `business_id` = 刚写入的 `detail.id` + - `file_id = attachment_id` +5. 若传入了 `status`,更新 `wms_after_sale.status` +6. 若当前 `role_group` ≠ `'customer_service'` 且 `status` ≠ `'completed'`,自动将 `role_group` 回设为 `'customer_service'`(仓库/财务处理完本环节后自动退回客服组继续跟进) +7. 若 `status = 'completed'`,同时写入 `resolution` 和 `resolved_at` + +### 10.8 理赔登记 `afterSale.registerClaim` + +```json +{ + "method": "afterSale.registerClaim", + "description": "登记售后理赔信息。一次性填入仓库理赔和运方理赔的全部字段,同时写入进度步骤。两套理赔字段可同时填写(双赔场景)。", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [ + { "name": "id", "type": "integer", "required": true, "source": "body", "description": "售后工单主表ID" }, + { "name": "claim_needed", "type": "integer", "required": false, "source": "body", "description": "仓库理赔标记:0/1" }, + { "name": "claim_amount", "type": "number", "required": false, "source": "body", "description": "仓库理赔金额(元)" }, + { "name": "claim_status", "type": "string", "required": false, "source": "body", "description": "仓库理赔状态:pending/reviewing/approved/paid/monthly/rejected" }, + { "name": "carrier_claim_needed", "type": "integer", "required": false, "source": "body", "description": "运方理赔标记:0/1" }, + { "name": "carrier_claim_amount", "type": "number", "required": false, "source": "body", "description": "运方理赔金额(元)" }, + { "name": "carrier_claim_status", "type": "string", "required": false, "source": "body", "description": "运方理赔状态:pending/reviewing/approved/paid/monthly/rejected" }, + { "name": "action", "type": "string", "required": true, "source": "body", "description": "操作动作描述,如"登记仓库理赔"、"登记运方理赔"" }, + { "name": "remark", "type": "string", "required": false, "source": "body", "description": "处理备注,如"快递破损核定赔200元"" }, + { "name": "attachment_ids", "type": "array", "required": false, "source": "body", "description": "附件 file_id 数组(破损照片、理赔单据等)" } + ], + "response": [ + { "name": "detail_id", "type": "integer", "required": true, "description": "本次写入的步骤ID" }, + { "name": "after_sale_id", "type": "integer", "required": true } + ], + "errors": [ + { "code": 400, "message": "工单不存在或参数缺失" }, + { "code": 500, "message": "登记失败" } + ] +} +``` + +**处理流程:** + +1. 校验工单 `id` 存在 +2. 从登录上下文提取操作人信息 +3. 更新 `wms_after_sale` 中传入的非空理赔字段(`claim_needed/amount/status`、`carrier_claim_needed/amount/status`) +4. 写入 `wms_after_sale_detail`(step_status=2,action/remark/operator) +5. 若有 `attachment_ids`,绑定到本次步骤 + +**使用场景:** +- 单赔:只传仓库理赔字段组,运方字段不传 +- 单赔:只传运方理赔字段组,仓库字段不传 +- 双赔:同时传两套字段(仓库+运输途中均破损) + +--- + +## 十一、待评审事项 + +- [ ] 售后单号 `after_sale_no` 生成规则:格式已确定为 `AS + YYYYMMDD + 6位序号`(如 `AS20260809000001`),待确认序号从 1 起始还是从指定起始值起 +- [ ] 仓库理赔(`claim_status`)和运方理赔(`carrier_claim_status`)是否需要更细粒度的流转(如:待审核 → 审核通过 → 已打款 → 月结) +- [ ] 进度步骤表是否需要记录商品明细信息(如退货 SKU/数量),或通过 `remark` JSON 扩展存储 +- [ ] 单据关联字段是否需要扩展到更多类型(如质检单 `quality_check_id`) +- [ ] 是否需要支持售后单之间的关联(如换货单关联原退货单) diff --git a/database/migrations/20260809130000-create-wms-after-sale.js b/database/migrations/20260809130000-create-wms-after-sale.js new file mode 100644 index 0000000..68eae7b --- /dev/null +++ b/database/migrations/20260809130000-create-wms-after-sale.js @@ -0,0 +1,293 @@ +'use strict'; + +const TABLE_NAME = 'wms_after_sale'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME); + if (exists) return; + + await queryInterface.createTable(TABLE_NAME, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + warehouse_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + store_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '货主ID', + }, + after_sale_no: { + type: Sequelize.STRING(50), + allowNull: false, + comment: '售后单号,唯一,生成规则:AS+YYYYMMDD+6位序号', + }, + type: { + type: Sequelize.STRING(20), + allowNull: false, + comment: '售后类型:order/receiving/entry/stockout', + }, + sub_type: { + type: Sequelize.STRING(50), + allowNull: false, + comment: '售后子类型,与 type 组成二级分类', + }, + status: { + type: Sequelize.STRING(20), + allowNull: false, + defaultValue: 'pending', + comment: '售后状态:pending/processing/completed/closed/cancelled', + }, + priority: { + type: Sequelize.INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '优先级,数值越大越优先(0=普通,10=紧急)', + }, + title: { + type: Sequelize.STRING(200), + allowNull: false, + comment: '售后标题/简要描述', + }, + description: { + type: Sequelize.TEXT, + allowNull: true, + defaultValue: null, + comment: '售后详细描述', + }, + creator_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '创建人账户ID', + }, + role_group: { + type: Sequelize.STRING(50), + allowNull: true, + defaultValue: null, + comment: '当前处理角色组:customer_service/warehouse/finance', + }, + inbox_message_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '关联站内信消息ID(wms_inbox_message.id)', + }, + resolution: { + type: Sequelize.TEXT, + allowNull: true, + defaultValue: null, + comment: '最终处理结果说明', + }, + resolved_at: { + type: Sequelize.DATE, + allowNull: true, + defaultValue: null, + comment: '完结时间(状态变为 completed 时写入)', + }, + claim_needed: { + type: Sequelize.TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '仓库理赔标记:0=不需要,1=需要', + }, + claim_amount: { + type: Sequelize.DECIMAL(12, 2), + allowNull: true, + defaultValue: null, + comment: '仓库理赔金额,单位:元', + }, + claim_status: { + type: Sequelize.STRING(20), + allowNull: true, + defaultValue: null, + comment: '仓库理赔状态:pending/reviewing/approved/paid/monthly/rejected', + }, + carrier_claim_needed: { + type: Sequelize.TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '运方理赔标记:0=不需要,1=需要', + }, + carrier_claim_amount: { + type: Sequelize.DECIMAL(12, 2), + allowNull: true, + defaultValue: null, + comment: '运方理赔金额,单位:元', + }, + carrier_claim_status: { + type: Sequelize.STRING(20), + allowNull: true, + defaultValue: null, + comment: '运方理赔状态:pending/reviewing/approved/paid/monthly/rejected', + }, + waybill_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '运单ID(关联 wms_order_express.id)', + }, + waybill_no: { + type: Sequelize.STRING(50), + allowNull: true, + defaultValue: null, + comment: '运单号(冗余)', + }, + order_delivery_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '发货订单ID(关联 wms_order_delivery.id)', + }, + order_delivery_no: { + type: Sequelize.STRING(50), + allowNull: true, + defaultValue: null, + comment: '发货订单号(冗余)', + }, + entry_order_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '入库单ID(关联 wms_entry_order.id)', + }, + entry_order_no: { + type: Sequelize.STRING(50), + allowNull: true, + defaultValue: null, + comment: '入库单号(冗余)', + }, + order_stockout_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '出库单ID(关联 wms_order_stockout.id)', + }, + order_stockout_no: { + type: Sequelize.STRING(50), + allowNull: true, + defaultValue: null, + comment: '出库单号(冗余)', + }, + receiving_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '收货单ID(关联 wms_receiving.id)', + }, + receiving_no: { + type: Sequelize.STRING(50), + allowNull: true, + defaultValue: null, + comment: '收货单号(冗余)', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: Sequelize.DATE, + allowNull: true, + defaultValue: null, + comment: '软删除时间', + }, + }); + + // 唯一索引 — 售后单号 + await queryInterface.addIndex(TABLE_NAME, ['after_sale_no'], { + unique: true, + name: 'uk_after_sale_no', + }); + + // 仓库+状态查询(最高频) + await queryInterface.addIndex(TABLE_NAME, ['warehouse_id', 'status', 'deleted_at'], { + name: 'idx_warehouse_status', + }); + + // 仓库+类型筛选 + await queryInterface.addIndex(TABLE_NAME, ['warehouse_id', 'type', 'deleted_at'], { + name: 'idx_warehouse_type', + }); + + // 仓库+类型+子类型筛选 + await queryInterface.addIndex(TABLE_NAME, ['warehouse_id', 'type', 'sub_type', 'deleted_at'], { + name: 'idx_type_subtype', + }); + + // 货主查询 + await queryInterface.addIndex(TABLE_NAME, ['store_id', 'deleted_at'], { + name: 'idx_store_id', + }); + + // 创建人查询 + await queryInterface.addIndex(TABLE_NAME, ['creator_id', 'deleted_at'], { + name: 'idx_creator_id', + }); + + // 角色组+状态查询 + await queryInterface.addIndex(TABLE_NAME, ['role_group', 'status', 'deleted_at'], { + name: 'idx_role_group', + }); + + // 仓库+时间排序分页 + await queryInterface.addIndex(TABLE_NAME, ['warehouse_id', 'created_at'], { + name: 'idx_created_at', + }); + + // 运单反查 + await queryInterface.addIndex(TABLE_NAME, ['waybill_id'], { + name: 'idx_waybill_id', + }); + + // 发货订单反查 + await queryInterface.addIndex(TABLE_NAME, ['order_delivery_id'], { + name: 'idx_order_delivery_id', + }); + + // 入库单反查 + await queryInterface.addIndex(TABLE_NAME, ['entry_order_id'], { + name: 'idx_entry_order_id', + }); + + // 出库单反查 + await queryInterface.addIndex(TABLE_NAME, ['order_stockout_id'], { + name: 'idx_order_stockout_id', + }); + + // 收货单反查 + await queryInterface.addIndex(TABLE_NAME, ['receiving_id'], { + name: 'idx_receiving_id', + }); + + // 运方理赔状态筛选 + await queryInterface.addIndex(TABLE_NAME, ['carrier_claim_status'], { + name: 'idx_carrier_claim_status', + }); + + // 站内信消息反查 + await queryInterface.addIndex(TABLE_NAME, ['inbox_message_id'], { + name: 'idx_inbox_message_id', + }); + }, + + down: async queryInterface => { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260809130100-create-wms-after-sale-detail.js b/database/migrations/20260809130100-create-wms-after-sale-detail.js new file mode 100644 index 0000000..4a139ec --- /dev/null +++ b/database/migrations/20260809130100-create-wms-after-sale-detail.js @@ -0,0 +1,100 @@ +'use strict'; + +const TABLE_NAME = 'wms_after_sale_detail'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME); + if (exists) return; + + await queryInterface.createTable(TABLE_NAME, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + after_sale_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '关联售后主表ID(wms_after_sale.id)', + }, + step_status: { + type: Sequelize.TINYINT(3).UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '步骤状态:0=待开始,1=进行中,2=已完成,3=已跳过', + }, + operator_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '操作人账户ID(关联 accounts 表)', + }, + operator_snapshot: { + type: Sequelize.TEXT, + allowNull: true, + defaultValue: null, + comment: '操作人信息快照(JSON),防止账户删除后历史丢失', + }, + action: { + type: Sequelize.STRING(100), + allowNull: true, + defaultValue: null, + comment: '操作动作描述', + }, + remark: { + type: Sequelize.TEXT, + allowNull: true, + defaultValue: null, + comment: '处理备注', + }, + started_at: { + type: Sequelize.DATE, + allowNull: true, + defaultValue: null, + comment: '步骤开始时间', + }, + completed_at: { + type: Sequelize.DATE, + allowNull: true, + defaultValue: null, + comment: '步骤完成时间', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: Sequelize.DATE, + allowNull: true, + defaultValue: null, + comment: '软删除时间', + }, + }); + + // 按售后单查询进度步骤(最高频) + await queryInterface.addIndex(TABLE_NAME, ['after_sale_id'], { + name: 'idx_after_sale_id', + }); + + // 按操作人查询 + await queryInterface.addIndex(TABLE_NAME, ['operator_id'], { + name: 'idx_operator_id', + }); + }, + + down: async queryInterface => { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260809130200-add-after-sale-permissions.js b/database/migrations/20260809130200-add-after-sale-permissions.js new file mode 100644 index 0000000..d4f2901 --- /dev/null +++ b/database/migrations/20260809130200-add-after-sale-permissions.js @@ -0,0 +1,97 @@ +'use strict'; + +/** + * 新增售后模块权限记录(固定 ID 策略,确保开发/生产一致)。 + * + * 新增权限明细: + * Block(角色组维度): + * 516 — 售后-客服组 + * 517 — 售后-仓库组 + * 518 — 售后-财务组 + * + * Web Pages(菜单/页面): + * 519 — afterSale 售后管理(根菜单) + * 520 — afterSale.list 售后列表 + * 521 — afterSale.detail 售后明细 + * + * API: + * 522 — afterSale.workList API:售后工作列表查询 + * 523 — afterSale.auditList API:售后审计列表查询 + * 508 — afterSale.detail API:售后明细查询 + * 509 — afterSale.create API:创建售后单 + * 510 — afterSale.update API:更新售后单 + * 511 — afterSale.transfer API:售后转单 + * 512 — afterSale.handleWorkOrder API:处理工单 + * 513 — afterSale.registerClaim API:登记理赔 + * 514 — afterSale.export API:售后导出 + * 515 — afterSale.exportTaskProgress API:导出进度查询 + * + * 幂等设计:使用 INSERT IGNORE,已存在的 id 不会重复插入。 + */ + +const TABLE = 'wms_permission'; +const COLUMNS = 'id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at'; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + // ── 1. Block 权限(角色组维度,用于权限分配分组)── + const blocks = [ + [516, null, null, '售后-客服组', null, '售后-客服组', null, 0, 0, null, 'block', 0, 1], + [517, null, null, '售后-仓库组', null, '售后-仓库组', null, 0, 0, null, 'block', 0, 1], + [518, null, null, '售后-财务组', null, '售后-财务组', null, 0, 0, null, 'block', 0, 1], + ]; + + for (const [id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status] of blocks) { + await queryInterface.sequelize.query( + `INSERT IGNORE INTO \`${TABLE}\` (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`, + { replacements: [id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status] } + ); + } + + // ── 2. Web Pages 权限(菜单/页面)── + const pages = [ + [519, 'afterSale', null, 'afterSale', null, '售后管理', null, 0, 0, null, 'web_pages', 14, 1], + [520, 'afterSale.list', null, 'afterSale.list', null, '售后列表', null, 0, 0, 519, 'web_pages', 0, 1], + [521, 'afterSale.detail', null, 'afterSale.detail', null, '售后明细', null, 0, 0, 519, 'web_pages', 1, 1], + ]; + + for (const [id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status] of pages) { + await queryInterface.sequelize.query( + `INSERT IGNORE INTO \`${TABLE}\` (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`, + { replacements: [id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status] } + ); + } + + // ── 3. API 权限 ── + const apis = [ + [522, 'afterSale.workList', 'API:售后工作列表查询'], + [523, 'afterSale.auditList', 'API:售后审计列表查询'], + [508, 'afterSale.detail', 'API:售后明细查询'], + [509, 'afterSale.create', 'API:创建售后单'], + [510, 'afterSale.update', 'API:更新售后单'], + [511, 'afterSale.transfer', 'API:售后转单'], + [512, 'afterSale.handleWorkOrder', 'API:处理工单'], + [513, 'afterSale.registerClaim', 'API:登记理赔'], + [514, 'afterSale.export', 'API:售后导出'], + [515, 'afterSale.exportTaskProgress', 'API:导出进度查询'], + ]; + + for (const [id, path, meta_title] of apis) { + await queryInterface.sequelize.query( + `INSERT IGNORE INTO \`${TABLE}\` (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`, + { replacements: [id, path, null, path, null, meta_title, null, 0, 0, null, 'api', 0, 1] } + ); + } + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + const ids = [516, 517, 518, 519, 520, 521, 522, 523, 508, 509, 510, 511, 512, 513, 514, 515]; + const placeholders = ids.map(() => '?').join(', '); + await queryInterface.sequelize.query( + `DELETE FROM \`${TABLE}\` WHERE id IN (${placeholders})`, + { replacements: ids } + ); + }, +}; diff --git a/methods/system.json b/methods/system.json index def17fe..8145c8b 100644 --- a/methods/system.json +++ b/methods/system.json @@ -2,7 +2,7 @@ "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", "version": "0.3.21", - "updatedAt": "2026-08-06", + "updatedAt": "2026-08-09", "headers": [ { "name": "platform", @@ -33593,6 +33593,164 @@ ] } ] + }, + { + "groupName": "售后管理", + "module": "afterSale", + "list": [ + { + "method": "afterSale.workList", + "description": "售后工作列表。仅返回当前用户角色组负责的待处理工单。", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [ + { "name": "pagination", "type": "object", "required": false, "source": "body", "description": "分页参数 page/pageSize" }, + { "name": "where", "type": "object", "required": false, "source": "body", "description": "筛选条件:type/sub_type/status/priority/after_sale_no/waybill_no 等" }, + { "name": "sort", "type": "object", "required": false, "source": "body", "description": "排序参数 sortField/sortOrder" } + ], + "response": [ + { "name": "list", "type": "array", "required": true }, + { "name": "pagination", "type": "object", "required": true } + ] + }, + { + "method": "afterSale.auditList", + "description": "售后审计列表。全局售后单视图,不限角色组、不限状态。", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [ + { "name": "pagination", "type": "object", "required": false, "source": "body" }, + { "name": "where", "type": "object", "required": false, "source": "body", "description": "同 workList,额外支持 claim_status/carrier_claim_status" }, + { "name": "sort", "type": "object", "required": false, "source": "body" } + ], + "response": [ + { "name": "list", "type": "array", "required": true }, + { "name": "pagination", "type": "object", "required": true } + ] + }, + { + "method": "afterSale.detail", + "description": "售后明细(主表+步骤列表+附件)。", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [ + { "name": "id", "type": "integer", "required": true, "source": "body", "description": "售后工单主表ID" } + ], + "response": [ + { "name": "after_sale", "type": "object", "required": true, "description": "主表数据" }, + { "name": "steps", "type": "array", "required": true, "description": "步骤列表(含附件)" } + ] + }, + { + "method": "afterSale.create", + "description": "创建售后单。", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [ + { "name": "warehouse_id", "type": "integer", "required": true, "source": "body" }, + { "name": "store_id", "type": "integer", "required": false, "source": "body" }, + { "name": "type", "type": "string", "required": true, "source": "body", "description": "order/receiving/entry/stockout" }, + { "name": "sub_type", "type": "string", "required": true, "source": "body" }, + { "name": "priority", "type": "integer", "required": false, "source": "body" }, + { "name": "title", "type": "string", "required": true, "source": "body" }, + { "name": "description", "type": "string", "required": false, "source": "body" }, + { "name": "waybill_id", "type": "integer", "required": false, "source": "body" }, + { "name": "order_delivery_id", "type": "integer", "required": false, "source": "body" }, + { "name": "entry_order_id", "type": "integer", "required": false, "source": "body" }, + { "name": "order_stockout_id", "type": "integer", "required": false, "source": "body" }, + { "name": "receiving_id", "type": "integer", "required": false, "source": "body" }, + { "name": "inbox_message_id", "type": "integer", "required": false, "source": "body" } + ], + "response": [ + { "name": "id", "type": "integer", "required": true }, + { "name": "after_sale_no", "type": "string", "required": true } + ] + }, + { + "method": "afterSale.transfer", + "description": "转单(更新 role_group)。", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [ + { "name": "id", "type": "integer", "required": true, "source": "body" }, + { "name": "role_group", "type": "string", "required": true, "source": "body", "description": "customer_service/warehouse/finance" }, + { "name": "remark", "type": "string", "required": false, "source": "body" } + ], + "response": [ + { "name": "after_sale_id", "type": "integer", "required": true } + ] + }, + { + "method": "afterSale.handleWorkOrder", + "description": "处理售后工单(写步骤+绑附件+自动转回客服)。", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [ + { "name": "id", "type": "integer", "required": true, "source": "body" }, + { "name": "status", "type": "string", "required": false, "source": "body", "description": "更新状态" }, + { "name": "action", "type": "string", "required": true, "source": "body" }, + { "name": "remark", "type": "string", "required": false, "source": "body" }, + { "name": "attachment_ids", "type": "array", "required": false, "source": "body", "description": "附件 file_id 数组" } + ], + "response": [ + { "name": "detail_id", "type": "integer", "required": true }, + { "name": "after_sale_id", "type": "integer", "required": true } + ] + }, + { + "method": "afterSale.registerClaim", + "description": "登记售后理赔信息(仓库+运方一次性填入)。", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [ + { "name": "id", "type": "integer", "required": true, "source": "body" }, + { "name": "claim_needed", "type": "integer", "required": false, "source": "body" }, + { "name": "claim_amount", "type": "number", "required": false, "source": "body" }, + { "name": "claim_status", "type": "string", "required": false, "source": "body" }, + { "name": "carrier_claim_needed", "type": "integer", "required": false, "source": "body" }, + { "name": "carrier_claim_amount", "type": "number", "required": false, "source": "body" }, + { "name": "carrier_claim_status", "type": "string", "required": false, "source": "body" }, + { "name": "action", "type": "string", "required": true, "source": "body" }, + { "name": "remark", "type": "string", "required": false, "source": "body" }, + { "name": "attachment_ids", "type": "array", "required": false, "source": "body" } + ], + "response": [ + { "name": "detail_id", "type": "integer", "required": true }, + { "name": "after_sale_id", "type": "integer", "required": true } + ] + }, + { + "method": "afterSale.export", + "description": "提交售后审计列表导出任务(异步)。返回 task_id。", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [ + { "name": "where", "type": "object", "required": false, "source": "body" }, + { "name": "sort", "type": "object", "required": false, "source": "body" } + ], + "response": [ + { "name": "task_id", "type": "string", "required": true }, + { "name": "status", "type": "string", "required": true }, + { "name": "progress", "type": "number", "required": true }, + { "name": "message", "type": "string", "required": true } + ] + }, + { + "method": "afterSale.exportTaskProgress", + "description": "查询售后导出任务进度和下载链接。", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [ + { "name": "task_id", "type": "string", "required": true, "source": "body" } + ], + "response": [ + { "name": "task_id", "type": "string", "required": true }, + { "name": "status", "type": "string", "required": true }, + { "name": "progress", "type": "number", "required": true }, + { "name": "download_url", "type": "string", "required": false } + ] + } + ] } ] } From 4c5807dbbc2fc3e800f6b420ac939c25e69ae376 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sun, 9 Aug 2026 21:30:52 +0800 Subject: [PATCH 186/550] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8Ddetail?= =?UTF-8?q?=E8=BF=94=E5=9B=9E=E7=BB=93=E6=9E=84=E5=92=8Ctransfer=E5=8F=82?= =?UTF-8?q?=E6=95=B0=E5=90=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - detail返回{after_sale,steps}包装结构 - transfer入参名target_role_group改为role_group - 集成测试8/8全部通过 --- app/service/systemMethods/afterSale.js | 4 ++-- app/service/systems/afterSale.js | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/app/service/systemMethods/afterSale.js b/app/service/systemMethods/afterSale.js index 9263fad..78e9b43 100644 --- a/app/service/systemMethods/afterSale.js +++ b/app/service/systemMethods/afterSale.js @@ -354,7 +354,7 @@ class AfterSaleMethodService extends MainService { * * @param {Object} data 请求体 * @param {number} data.id 售后单主键ID - * @param {string} data.target_role_group 目标角色组(customer_service/warehouse/finance) + * @param {string} data.role_group 目标角色组(customer_service/warehouse/finance) * @param {string} [data.remark] 转单备注 * @return {Promise} 统一 success 包装 */ @@ -362,7 +362,7 @@ class AfterSaleMethodService extends MainService { const { ctx, service } = this; const { id, - target_role_group: targetRoleGroup, + role_group: targetRoleGroup, remark, } = data || {}; diff --git a/app/service/systems/afterSale.js b/app/service/systems/afterSale.js index e44e387..b62a4fc 100644 --- a/app/service/systems/afterSale.js +++ b/app/service/systems/afterSale.js @@ -240,7 +240,7 @@ class AfterSaleService extends Service { const stepsWithAttachments = await this._enrichStepsWithAttachments(steps); return { - ...afterSale, + after_sale: afterSale, steps: stepsWithAttachments, }; } From b436b6dd9e2bc850a2520691419316a2b8e6f4a4 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Wed, 12 Aug 2026 20:47:19 +0800 Subject: [PATCH 187/550] =?UTF-8?q?feat:=20=E6=8B=A6=E6=88=AA=E9=93=BE?= =?UTF-8?q?=E8=B7=AF=E5=85=A8=E6=B5=81=E7=A8=8B=E5=AE=8C=E5=96=84=20?= =?UTF-8?q?=E2=80=94=20=E6=96=B0=E5=A2=9EinterceptScan=20+=20=E8=BF=90?= =?UTF-8?q?=E5=8D=95=E8=A1=A8=E5=90=8C=E6=AD=A5=20+=20=E5=B7=A5=E5=8D=95?= =?UTF-8?q?=E9=80=9A=E7=9F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增: - order.recheckOrder.interceptScan: 拦截扫描接口,入参运单号,查express标记退回,处理工单,更新订单拦截状态 - afterSale.createInterceptWorkOrdersAndNotify: 共享方法,幂等创建工单+通知快递群 修复: - confirmIntercept: 补运单is_back同步(仅限is_intercept=Y),补工单创建+通知 - batchIntercept: 补运单is_intercept同步,补工单创建+通知 - batchUnintercept: 补运单is_intercept/is_back清除 - Qimen/OpenAPI cancel: 补运单is_intercept同步,补工单创建+通知 - interceptScan: 删除死查询,加空指针兜底 文档: - methods/system.json: interceptScan + confirmIntercept 完整API文档 - methods/changes/system.json: 变更记录 --- app/model/after_sale.js | 17 +- app/model/after_sale_detail.js | 23 +- app/model/inbox_group.js | 7 +- app/model/store_warehouse.js | 10 + app/service/inbox/ai.js | 370 ++++ app/service/inbox/functions.js | 1536 +++++++++++------ app/service/inbox/groups.js | 224 +++ app/service/inbox/processor.js | 355 ++-- app/service/openapiMethods/order.js | 34 + app/service/qimenMethods/order.js | 26 + app/service/systemMethods/afterSale.js | 239 ++- app/service/systemMethods/index.js | 7 +- .../systemMethods/order/deliveryOrder.js | 331 +++- .../systemMethods/order/pendingOrder.js | 38 + .../systemMethods/order/recheckOrder.js | 208 ++- app/service/systemMethods/pickCart.js | 39 +- .../systemMethods/storage/receiving.js | 2 +- .../systemMethods/storage/transaction.js | 4 +- app/service/systems/afterSale.js | 1120 +++++++++++- app/service/systems/inbox/group.js | 121 ++ app/service/systems/pick.js | 178 +- app/service/systems/pickCart.js | 11 + app/service/systems/setting/warehouse.js | 57 + app/service/systems/stock_transaction.js | 17 +- app/service/systems/storage/receiving.js | 61 +- app/service/systems/waybill.js | 219 ++- database/designs/after-sale-v2-design.md | 88 +- ...09140000-add-after-sale-workorder-pages.js | 42 + ...140100-grant-after-sale-workorder-pages.js | 103 ++ ...fter-sale-detail-step-status-to-varchar.js | 27 + ...00000-add-followup-at-to-wms-after-sale.js | 17 + ...60811120000-add-ext-data-to-inbox-group.js | 20 + ...260812120000-add-order-id-to-after-sale.js | 16 + methods/changes/system.json | 338 ++++ methods/system.json | 1157 ++++++++++++- 35 files changed, 5951 insertions(+), 1111 deletions(-) create mode 100644 app/service/inbox/ai.js create mode 100644 app/service/inbox/groups.js create mode 100644 database/migrations/20260809140000-add-after-sale-workorder-pages.js create mode 100644 database/migrations/20260809140100-grant-after-sale-workorder-pages.js create mode 100644 database/migrations/20260810140000-alter-wms-after-sale-detail-step-status-to-varchar.js create mode 100644 database/migrations/20260811100000-add-followup-at-to-wms-after-sale.js create mode 100644 database/migrations/20260811120000-add-ext-data-to-inbox-group.js create mode 100644 database/migrations/20260812120000-add-order-id-to-after-sale.js diff --git a/app/model/after_sale.js b/app/model/after_sale.js index 2ec2f60..05f3955 100644 --- a/app/model/after_sale.js +++ b/app/model/after_sale.js @@ -86,11 +86,12 @@ module.exports = app => { /** * 售后单状态枚举。 - * @type {{pending: string, processing: string, completed: string, closed: string, cancelled: string}} + * @type {{pending: string, processing: string, waiting: string, completed: string, closed: string, cancelled: string}} */ const AFTER_SALE_STATUS = { pending: '待处理', processing: '处理中', + pending_feedback: '等待外部反馈', completed: '已完成', closed: '已关闭', cancelled: '已取消', @@ -156,7 +157,7 @@ module.exports = app => { type: STRING(20), allowNull: false, defaultValue: 'pending', - comment: '售后状态:pending=待处理, processing=处理中, completed=已完成, closed=已关闭, cancelled=已取消', + comment: '售后状态:pending=待处理, processing=处理中, pending_feedback=等待外部反馈, completed=已完成, closed=已关闭, cancelled=已取消', }, /** 优先级 */ priority: { @@ -207,6 +208,12 @@ module.exports = app => { allowNull: true, comment: '完结时间(状态变为 completed 时写入)', }, + /** 下次跟进时间 */ + followup_at: { + type: DATE, + allowNull: true, + comment: '下次跟进时间:设为 pending_feedback 时可指定,超时后需二次跟进', + }, /** 仓库理赔标记 */ claim_needed: { type: TINYINT(1), @@ -258,6 +265,12 @@ module.exports = app => { allowNull: true, comment: '运单号(冗余字段,方便查询展示)', }, + /** 订单ID */ + order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '订单ID(关联 wms_order.id),快递反馈建单时从 wms_order_express.order_id 填入', + }, /** 发货订单ID */ order_delivery_id: { type: BIGINT(20).UNSIGNED, diff --git a/app/model/after_sale_detail.js b/app/model/after_sale_detail.js index 9a828e2..f623b96 100644 --- a/app/model/after_sale_detail.js +++ b/app/model/after_sale_detail.js @@ -6,21 +6,22 @@ * @return {import('sequelize').ModelCtor} 售后进度步骤 Model(含常量挂载) */ module.exports = app => { - const { STRING, BIGINT, TEXT, TINYINT, DATE } = app.Sequelize; + const { STRING, BIGINT, TEXT, DATE } = app.Sequelize; // ============================ // 枚举常量定义 // ============================ /** - * 步骤状态枚举。 - * @type {{0: string, 1: string, 2: string, 3: string}} + * 步骤状态枚举(与 wms_after_sale.status 一致)。 */ const STEP_STATUS = { - 0: '待开始', - 1: '进行中', - 2: '已完成', - 3: '已跳过', + pending: '待处理', + processing: '处理中', + pending_feedback: '等待外部反馈', + completed: '已完成', + closed: '已关闭', + cancelled: '已取消', }; // ============================ @@ -41,12 +42,12 @@ module.exports = app => { allowNull: false, comment: '关联售后主表ID(wms_after_sale.id)', }, - /** 步骤状态 */ + /** 步骤记录时售后主表的状态 */ step_status: { - type: TINYINT(3).UNSIGNED, + type: STRING(20), allowNull: false, - defaultValue: 0, - comment: '步骤状态:0=待开始,1=进行中,2=已完成,3=已跳过', + defaultValue: 'processing', + comment: '步骤记录时售后主表的状态,与 wms_after_sale.status 一致: pending | processing | pending_feedback | completed | closed | cancelled', }, /** 操作人账户ID */ operator_id: { diff --git a/app/model/inbox_group.js b/app/model/inbox_group.js index 6a02825..4a3039b 100644 --- a/app/model/inbox_group.js +++ b/app/model/inbox_group.js @@ -8,7 +8,7 @@ * @return {Object} Sequelize Model 定义。 */ module.exports = app => { - const { BIGINT, STRING, TINYINT, DATE } = app.Sequelize; + const { BIGINT, STRING, TINYINT, DATE, JSON: JSON_TYPE } = app.Sequelize; const InboxGroup = app.model.define('inbox_group', { id: { @@ -80,6 +80,11 @@ module.exports = app => { allowNull: true, comment: '系统快递编码(仅群类型为 express 时必填)', }, + ext_data: { + type: JSON_TYPE, + allowNull: true, + comment: '群扩展数据(IM平台信息等)', + }, created_at: { type: DATE, allowNull: false, diff --git a/app/model/store_warehouse.js b/app/model/store_warehouse.js index 5e7a40c..1e5b37f 100644 --- a/app/model/store_warehouse.js +++ b/app/model/store_warehouse.js @@ -216,6 +216,16 @@ module.exports = app => { max: '23:59', description: '截单时间,格式 HH:mm,如 16:00', }), + Object.freeze({ + key: 'after_sale_followup_hours', + name: '售后跟进时间(h)', + type: 'integer', + default: 24, + required: false, + min: 1, + max: 720, + description: '售后单设为等待外部反馈后,默认多少小时需二次跟进。具体类型可在代码枚举中覆盖', + }), ]); const POLICY_CONFIG_FIELD_MAP = Object.freeze(POLICY_CONFIG_FIELDS.reduce((result, field) => { result[field.key] = field; diff --git a/app/service/inbox/ai.js b/app/service/inbox/ai.js new file mode 100644 index 0000000..fc41d87 --- /dev/null +++ b/app/service/inbox/ai.js @@ -0,0 +1,370 @@ +'use strict'; + +const Service = require('egg').Service; + +/** + * AI 推理引擎。 + * 负责调用 DeepSeek API 进行多轮推理:思考→调函数→评估→(重复或输出)。 + * 函数注册、分组管理等纯工具箱逻辑在 inbox/functions.js 中。 + */ +class InboxAIService extends Service { + + /** + * 调用 DeepSeek API。 + * + * @param {Array<{role: string, content: string}>} messages 消息列表。 + * @param {Object} [options] 额外选项。 + * @return {Promise} AI 返回的文本内容。 + */ + async callDeepSeek(messages, options = {}) { + const { ctx } = this; + const apiKey = ctx.app.config.deepseek.apiKey; + const baseUrl = ctx.app.config.deepseek.baseUrl || 'https://api.deepseek.com'; + + if (!apiKey) { + throw new Error('DeepSeek API Key 未配置'); + } + + const result = await ctx.curl(`${baseUrl}/v1/chat/completions`, { + method: 'POST', + contentType: 'json', + dataType: 'json', + headers: { Authorization: `Bearer ${apiKey}` }, + data: { + model: 'deepseek-v4-pro', + messages, + temperature: options.temperature ?? 0, + max_tokens: options.maxTokens ?? 1000, + }, + timeout: options.timeout || 30000, + }); + + if (result.status !== 200 || !result.data) { + throw new Error(`DeepSeek 请求失败, HTTP ${result.status}`); + } + + let content = result.data.choices?.[0]?.message?.content || ''; + // 清理 markdown 代码块 + content = content.replace(/^```json\s*/i, '').replace(/\s*```$/i, ''); + content = content.replace(/^```\s*/i, '').replace(/\s*```$/i, ''); + return content.trim(); + } + + /** + * 获取智能对话历史上下文。 + * 同一群 + 同一用户 → 最近 N 条消息(含 AI 回复),用于多轮对话短期记忆。 + * 按创建时间升序排列,并为每条消息附加序号供 AI 追踪。 + * + * @param {Object} opts 查询选项。 + * @param {number} [opts.parentId] 当前消息的 parent_id(兼容旧参数)。 + * @param {number} [opts.maxMessages=5] 最大历史消息数。 + * @return {Promise>} 历史消息列表。 + */ + async getConversationHistory(opts = {}) { + const parentId = Number(opts.parentId) || 0; + const maxMessages = Math.min(10, Math.max(1, Number(opts.maxMessages) || 5)); + + const { ctx } = this; + const { InboxMessage } = ctx.model; + const { Op } = ctx.app.Sequelize; + + const groupId = String(ctx.inboxContext?.group_id || '').trim(); + const userId = String(ctx.inboxContext?.user_id || '').trim(); + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + + // 无群/用户上下文时,退回旧逻辑:沿 parent_id 追溯 + if (!groupId || !userId || !warehouseId) { + if (!parentId) return []; + try { + const history = []; + let currentId = parentId; + const visited = new Set(); + while (currentId && history.length < maxMessages) { + if (visited.has(currentId)) break; + visited.add(currentId); + const msg = await InboxMessage.findOne({ + attributes: [ 'id', 'parent_id', 'direction', 'content' ], + where: { id: currentId }, + raw: true, + }); + if (!msg) break; + history.unshift({ role: msg.direction === 'inbound' ? 'user' : 'assistant', content: msg.content || '' }); + currentId = msg.parent_id; + } + return history; + } catch (error) { + ctx.logger.warn(`[inbox ai] 对话历史回退查询失败: ${error.message}`); + return []; + } + } + + // 智能查询:同一群,最近 maxMessages 条(入站+出站混合,含所有成员) + try { + const messages = await InboxMessage.findAll({ + attributes: [ 'id', 'parent_id', 'direction', 'content', 'user_id', 'user_name', 'created_at' ], + where: { + warehouse_id: warehouseId, + group_id: groupId, + direction: { [Op.in]: [ 'inbound', 'outbound' ] }, + }, + order: [[ 'created_at', 'DESC' ]], + limit: maxMessages, + raw: true, + }); + + if (messages.length === 0) return []; + + // 升序排列,附加上下文信息供 AI 判断真人接管 + const blockedUsers = ctx.inboxContext?._blockedUserIds || new Set(); + return messages.reverse().map(msg => { + const u = String(msg.user_id || '').trim(); + const name = String(msg.user_name || '').trim(); + const isBlocked = u && blockedUsers.has(u); + return { + role: msg.direction === 'inbound' ? 'user' : 'assistant', + content: msg.content || '', + user_id: u || null, + user_name: name || null, + blocked: isBlocked, + }; + }); + } catch (error) { + ctx.logger.warn(`[inbox ai] 智能对话历史查询失败: ${error.message}`); + return []; + } + } + + /** + * DeepSeek 多轮推理:思考→调函数→评估→(重复或输出)。 + * + * 每轮 AI 返回 JSON,通过 action 字段决定行为: + * { "action": "call", "function": "函数名", "params": {...}, "reason": "..." } + * { "action": "reply", "reply": "最终回复内容" } + * + * 最多 MAX_ROUNDS 轮,防止无限循环。 + * + * @param {Object} data 消息数据。 + * @param {string} data.content 消息正文。 + * @param {Object} [data.ext_data] 透传数据。 + * @param {number} [data.parentId] 父消息ID。 + * @return {Promise<{reply: string, functionName: string|null, functionResult: Object|null}>} AI 回复。 + */ + async processWithAI(data = {}) { + const { ctx } = this; + const content = String(data.content || '').trim(); + if (!content) { + return { reply: '消息正文为空,无法处理', functionName: null, functionResult: null }; + } + + const funcSvc = ctx.service.inbox.functions; + const groupsSvc = ctx.service.inbox.groups; + const activeGroups = groupsSvc.resolveActiveGroups(); + ctx.logger.info(`[inbox ai] 当前活跃分组: ${activeGroups.join(', ')}`); + + const functionListText = groupsSvc.buildFunctionListText(activeGroups); + if (!functionListText) { + ctx.logger.info('[inbox ai] 当前上下文无可用的 AI 函数'); + return { reply: null, functionName: null, functionResult: null }; + } + + // 拉取群历史(最多 10 条),同时注入 system prompt 和对话上下文 + const history = await this.getConversationHistory({ + parentId: data.parentId, + maxMessages: 10, + }); + const historyContext = history.length > 0 + ? history.map(h => { + const tag = h.blocked ? '[已屏蔽]' : ''; + return `[${h.role === 'user' ? h.user_name || h.user_id || '未知' : 'AI'}]${tag}: ${h.content}`; + }).join('\n') + : '(无历史)'; + + const MAX_ROUNDS = 5; + const executedFunctions = []; + const thoughts = []; + let finalReply = null; + let lastFunctionName = null; + let lastFunctionResult = null; + + const systemPrompt = `你是一个 WMS 仓库管理系统的智能助手,支持多步推理。 +已注册函数:\n${functionListText}\n +=== 群最近对话历史 === +${historyContext} +=== + +对话历史中 [已屏蔽] 标记表示该用户已主动要求屏蔽(不想被 AI 打扰)。 +如果 [已屏蔽] 用户发送了表示接手或正在处理的内容(如"我来处理""不用回复""稍等""我看看"),说明真人已接管 → 直接 silent。 + +你需要通过多轮调用来完成用户的复杂请求。每轮返回纯 JSON: + +如果还需要调用函数获取信息: +{ + "action": "call", + "function": "函数名", + "params": { "参数名": "参数值" }, + "reason": "为什么需要这个函数" +} + +如果信息充足可以回复用户了: +{ + "action": "reply", + "reply": "最终回复(中文纯文本,禁止Markdown,200字以内,可适当使用\\n换行分隔信息)" +} + +如果消息无需回复(用户只是确认、道谢、告别或表示自己处理): +{ + "action": "silent" +} + +真人接管判断规则(优先级最高,先于所有其他规则): +- 如果历史中某条消息 blocked=true 的用户发送了与当前问题相关的内容(如"我来处理""稍等""我看看"等表示接手的话术),说明真人客服已介入处理 → 直接 silent +- 如果 blocked 用户发送的内容与问题无关(如闲聊、询问其他事情),且当前用户仍在提问 → 正常回复当前用户 +- 如果历史中只有当前用户的连续消息,没有其他用户介入 → 正常回复 + +一般约束: +- 最多 ${MAX_ROUNDS} 轮函数调用,第 ${MAX_ROUNDS} 轮必须给出最终回复 +- 同一函数不要重复调用(除非参数不同) +- 信息中如果携带了@标记,说明信息是针对某个特定用户的,请注意是否需要回复该用户 +- 如果函数执行失败,换其他方式或直接告知用户 +- 回复使用中文纯文本,禁止 Markdown 语法,可用 \\n 换行提升可读性 +- silent 仅用于:用户已确认收到消息且无新问题("好的""收到""OK""谢谢""知道了""好"),或用户表示告别/离场("再见""拜拜""88") +- 以下情况严禁 silent,必须 reply:任何形式的提问(含"在吗""有人吗""在不在")、操作请求、函数执行完毕、自定义欢迎语"你好""嗨""hello"等首次问候 +- 无法判断时,宁可回复也不要 silent +- searchStock 返回多条结果时,必须列举让用户选择(告知 id/编码/名称/可用库存),不要擅自决定 +- createOrder 失败时告知失败原因(库存不足/商品不存在等),不要重试同一商品 +- searchStock 返回的 stock_available 为 0 时,提醒用户该商品无库存,建议选择其他商品 +- searchStock/searchWarehouseStock 返回的 image_url 为图片URL数组(可能多张),has_images 为 true 时给出链接 +- searchStock/searchWarehouseStock 返回的 barcodes 为关联条码,回复时可列出帮助核对 +- searchStock/searchWarehouseStock 返回的管理标识 is_sn_mgmt/is_shelf_life_mgmt/is_batch_mgmt 分别表示SN管理/效期管理/批次管理 +- searchStock/searchWarehouseStock 返回的 box_spec 为箱规(长宽高体积毛净重装箱数),packing_requirements 为打包要求,用户问及时告知 +- searchStock/searchWarehouseStock 返回的 prohibited_type 为违禁品类型,非空时告知用户 +- 用户说"第1个""第2个"时,按 searchStock 返回的顺序对应选择 +- 需要上下文但记忆不足时,主动调用 recallHistory 回顾对话历史 +- 【防误判规则 - interceptWaybill】讨论已有售后工单(AS开头编号)、询问物流进度、问"快递到哪了"、转发售后截图等均不是拦截请求,严禁调用 interceptWaybill。只有用户明确说"拦截/退回/召回/追回/取消"运单时才可调用 +- 【措辞规则 - interceptWaybill】拦截结果回复严禁使用"已拦截""拦截成功"等确定口吻,必须使用"拦截信息已登记""已提交拦截申请"等措辞。因为快递拦截可能失败,实际结果以快递公司反馈为准。回复时需列出工单号供用户跟进`; + + // 多轮推理循环 + for (let round = 1; round <= MAX_ROUNDS; round++) { + const contextLines = []; + if (executedFunctions.length > 0) { + contextLines.push('已执行的函数及结果:'); + executedFunctions.forEach((f, i) => { + contextLines.push( + ` ${i + 1}. ${f.name}(${JSON.stringify(f.params)}) → ${JSON.stringify(f.result)}` + ); + }); + } + + const messages = [ + { role: 'system', content: systemPrompt }, + ...history, + ...(contextLines.length > 0 ? [{ role: 'system', content: contextLines.join('\n') }] : []), + { role: 'user', content: round === 1 + ? content + : (executedFunctions.length > 0 + ? `已获取到函数执行结果,请根据结果 reply 告知用户(禁止 silent)。第 ${round}/${MAX_ROUNDS} 轮` + : `请根据已获取的信息,决定下一步:继续调用函数还是给出最终回复。第 ${round}/${MAX_ROUNDS} 轮`), + }, + ]; + + let raw = ''; + try { + raw = await this.callDeepSeek(messages, { maxTokens: 600 }); + ctx.logger.info(`[inbox ai] 第 ${round}/${MAX_ROUNDS} 轮: ${raw}`); + + const result = JSON.parse(raw); + + // 记录思考过程 + thoughts.push({ + round, + action: result.action || 'unknown', + function: result.function || null, + params: result.params || null, + reason: result.reason || null, + }); + + if (result.action === 'reply') { + finalReply = String(result.reply || '').trim(); + if (!finalReply) finalReply = '已处理完成'; + break; + } + + if (result.action === 'silent') { + // 已调用过操作类函数(非 recallHistory)→ 必须回复结果,不能 silent + const actionFunctions = executedFunctions.filter(f => f.name !== 'recallHistory'); + if (actionFunctions.length > 0) { + ctx.logger.info('[inbox ai] 已有操作类函数调用,忽略 silent 继续要求回复'); + continue; + } + ctx.logger.info('[inbox ai] AI 判定无需回复,跳过回执'); + return { reply: null, functionName: null, functionResult: null, thoughts, skip: true }; + } + + if (result.action === 'call' && result.function) { + const fnName = String(result.function).trim(); + const params = result.params || {}; + + if (fnName === 'none' || fnName === 'stop') { + finalReply = result.reply || '已处理完成'; + break; + } + + lastFunctionName = fnName; + lastFunctionResult = await funcSvc.callFunction(fnName, params); + executedFunctions.push({ name: fnName, params, result: lastFunctionResult }); + + // 补充函数执行结果到思考记录 + const lastThought = thoughts[thoughts.length - 1]; + if (lastThought) lastThought.functionResult = lastFunctionResult; + ctx.logger.info(`[inbox ai] 执行 ${fnName}: ${JSON.stringify(lastFunctionResult)}`); + + // 最后一轮强制输出 + if (round === MAX_ROUNDS) { + finalReply = lastFunctionResult?.data?.message + || lastFunctionResult?.data?.greeting + || JSON.stringify(lastFunctionResult?.data || lastFunctionResult); + } + continue; + } + + // 无法解析 → 尝试提取 reply + finalReply = result.reply || result.message || '抱歉,暂时无法处理您的请求'; + break; + } catch (error) { + ctx.logger.warn(`[inbox ai] 第 ${round} 轮异常: ${error.message}, raw: ${raw}`); + + // 不是 JSON → 当作文本回复 + if (error instanceof SyntaxError && raw) { + finalReply = raw; + break; + } + + // 最后一轮兜底 + if (round === MAX_ROUNDS) { + finalReply = '抱歉,暂时无法处理您的请求,请稍后重试'; + } + continue; + } + } + + // 无回复的兜底 + if (!finalReply && lastFunctionResult) { + finalReply = lastFunctionResult?.data?.message + || lastFunctionResult?.data?.greeting + || (lastFunctionResult?.success !== false ? '操作已完成' : lastFunctionResult?.error || '处理完成'); + } + if (!finalReply) { + finalReply = '抱歉,暂时无法处理您的请求'; + } + + ctx.logger.info(`[inbox ai] 最终回复: ${finalReply}`); + return { + reply: finalReply, + functionName: lastFunctionName, + functionResult: lastFunctionResult, + thoughts, + }; + } +} + +module.exports = InboxAIService; diff --git a/app/service/inbox/functions.js b/app/service/inbox/functions.js index aeb389b..7bc7509 100644 --- a/app/service/inbox/functions.js +++ b/app/service/inbox/functions.js @@ -2,90 +2,13 @@ const Service = require('egg').Service; -/** - * ## 函数分组常量 - * - * 层级格式:`{主分组}` 或 `{主分组}:{子分组}` - * - * ### 分组匹配规则(注册 / 查询) - * - * 1. **精确匹配**:`['common']` 只匹配当前活跃分组包含 `common` 的上下文。 - * 2. **主分组通配**:`['bound:store:*']` 匹配 `bound:store` 及其所有子分组 - * (`bound:store:after_sales` / `bound:store:finance` / `bound:store:receiving`), - * 适用于同一主分组下所有子分组都需要的函数。 - * 3. **显式子分组**:`['bound:store:after_sales']` 只在该子分组活跃时可用, - * 适用于某子分组专属的函数。 - * 4. **组合使用**:`['common', 'bound:store:*']` 表示通用 + 所有货主子分组均可用。 - * - * ### 如何注册新函数 - * - * ```js - * // 仅通用分组 - * this.register('myFunc', { groups: [GROUP.COMMON], ... }); - * - * // 所有货主子分组(推荐) - * this.register('myFunc', { groups: [GROUP.BOUND_STORE_WILDCARD], ... }); - * - * // 仅售后子分组 - * this.register('myFunc', { groups: [GROUP.BOUND_STORE_AFTER_SALES], ... }); - * - * // 售后 + 财务(但非收货) - * this.register('myFunc', { - * groups: [GROUP.BOUND_STORE_AFTER_SALES, GROUP.BOUND_STORE_FINANCE], - * ... - * }); - * ``` - * - * @constant - */ -const GROUP = { - /** 通用分组 — 所有上下文均可用 */ - COMMON: 'common', - /** 已绑定货主群主分组 */ - BOUND_STORE: 'bound:store', - /** 货主群通配 — 匹配 bound:store 及其全部子分组 */ - BOUND_STORE_WILDCARD: 'bound:store:*', - /** 货主-售后子分组 */ - BOUND_STORE_AFTER_SALES: 'bound:store:after_sales', - /** 货主-财务子分组 */ - BOUND_STORE_FINANCE: 'bound:store:finance', - /** 货主-收货子分组 */ - BOUND_STORE_RECEIVING: 'bound:store:receiving', - /** 已绑定仓库群(预留) */ - BOUND_WAREHOUSE: 'bound:warehouse', - /** 已绑定快递群(预留) */ - BOUND_EXPRESS: 'bound:express', -}; +// 群类型常量定义统一收口到 inbox/groups.js +const { GROUP } = require('./groups'); /** - * 子分组 → 主分组映射,用于 `resolveActiveGroups` 展开。 - * 新增子分组时必须同步追加。 - * @constant {Record} - */ -const SUB_TO_MAIN = { - [GROUP.BOUND_STORE_AFTER_SALES]: GROUP.BOUND_STORE, - [GROUP.BOUND_STORE_FINANCE]: GROUP.BOUND_STORE, - [GROUP.BOUND_STORE_RECEIVING]: GROUP.BOUND_STORE, -}; - -/** - * 注册时声明的主分组通配 → 所有已知子分组展开列表。 - * 用于 `isFunctionAvailable` 中展开 `bound:store:*` → 实际子分组集合。 - * @constant {Record} - */ -const WILDCARD_EXPAND = { - [GROUP.BOUND_STORE_WILDCARD]: [ - GROUP.BOUND_STORE, - GROUP.BOUND_STORE_AFTER_SALES, - GROUP.BOUND_STORE_FINANCE, - GROUP.BOUND_STORE_RECEIVING, - ], -}; - -/** - * 站内信函数库。 - * 注册可被 AI 调用的内部方法,支持按分组筛选, - * 根据当前上下文(群类型、绑定状态)自动选择可用函数集合。 + * 站内信函数注册表。 + * 负责注册 AI 可调用的函数(含 handler),支持按分组声明可见性。 + * 分组匹配与筛选逻辑在 {@link InboxGroupsService} 中。 */ class InboxFunctionsService extends Service { /** @@ -109,6 +32,8 @@ class InboxFunctionsService extends Service { name: { type: 'string', required: false, description: '用户名称' }, }, groups: [ GROUP.COMMON ], + weight: 0, + keywords: [ '你好', 'hi', 'hello', '在吗' ], handler: async (params = {}) => { const name = String(params.name || '').trim(); const greeting = name ? `你好,${name}!欢迎使用 WMS 站内信服务` : '你好!欢迎使用 WMS 站内信服务'; @@ -123,6 +48,8 @@ class InboxFunctionsService extends Service { description: '查询当前货主的面单余额。根据上下文中的货主ID和仓库ID查询合约中的面单剩余量和锁定量', params: {}, groups: [ GROUP.BOUND_STORE_WILDCARD ], + weight: 80, + keywords: [ '面单余额', '打印余额', '快递单余额', '还剩多少单', '面单' ], handler: async (params = {}) => { const { ctx } = this; void params; @@ -191,6 +118,8 @@ class InboxFunctionsService extends Service { order_code: { type: 'string', required: true, description: '平台订单号' }, }, groups: [ GROUP.BOUND_STORE_WILDCARD ], + weight: 90, + keywords: [ '创建快递单', '取号', '分配快递', '生成运单', '快递单号' ], handler: async (params = {}) => { const { ctx } = this; const orderCode = String(params.order_code || '').trim(); @@ -282,6 +211,8 @@ class InboxFunctionsService extends Service { keyword: { type: 'string', required: true, description: '搜索关键词:商品编码(item_code)、条码(barcode)、商品名称(item_name)' }, }, groups: [ GROUP.BOUND_STORE_WILDCARD ], + weight: 70, + keywords: [ '查商品', '搜商品', '找商品', '商品信息', '库存', '商品' ], handler: async (params = {}) => { const { ctx } = this; const storeId = Number(ctx.inboxContext?.store_id || 0); @@ -420,6 +351,8 @@ class InboxFunctionsService extends Service { keyword: { type: 'string', required: true, description: '搜索关键词:商品编码(item_code)、条码(barcode)、商品名称(item_name)' }, }, groups: [ GROUP.COMMON ], + weight: 60, + keywords: [ '仓库商品', '所有商品' ], handler: async (params = {}) => { const { ctx } = this; const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); @@ -556,6 +489,8 @@ class InboxFunctionsService extends Service { keyword: { type: 'string', required: true, description: '搜索关键词:运单号(waybill_code,精确匹配)、发货单号(delivery_order_code,模糊)、平台单号(source_platform_code,模糊)' }, }, groups: [ GROUP.BOUND_STORE_AFTER_SALES ], + weight: 85, + keywords: [ '查订单', '搜订单', '订单详情', '运单号', '快递单号', '发货单' ], handler: async (params = {}) => { const { ctx } = this; const storeId = Number(ctx.inboxContext?.store_id || 0); @@ -701,9 +636,12 @@ class InboxFunctionsService extends Service { limit: { type: 'number', required: false, description: '获取最近几条,默认5,最大10' }, }, groups: [ GROUP.COMMON ], + weight: 0, + keywords: [], handler: async (params = {}) => { + const { ctx } = this; const limit = Math.min(10, Math.max(1, Number(params.limit) || 5)); - const history = await this.getConversationHistory({ maxMessages: limit }); + const history = await ctx.service.inbox.ai.getConversationHistory({ maxMessages: limit }); if (history.length === 0) { return { success: true, data: { total: 0, messages: [], hint: '暂无对话历史' } }; } @@ -724,6 +662,8 @@ class InboxFunctionsService extends Service { this.register('createOrder', { description: '创建发货订单。传入商品 stock_id(来自 searchStock)及数量、收件人信息,使用手工建单流程创建发货单', + weight: 90, + keywords: [ '建单', '创建订单', '下单', '发货', '新建订单' ], params: { items: { type: 'array', required: true, description: '商品列表 [{item_id: stock_id, plan_qty: 数量}]' }, receiverName: { type: 'string', required: true, description: '收件人姓名' }, @@ -796,6 +736,8 @@ class InboxFunctionsService extends Service { description: '屏蔽用户消息。将当前群和用户加入屏蔽列表,后续不再回复', params: {}, groups: [ GROUP.COMMON ], + weight: 0, + keywords: [ '屏蔽', '不回复', '拉黑' ], handler: async (params = {}) => { const { ctx } = this; void params; @@ -855,10 +797,954 @@ class InboxFunctionsService extends Service { }, }); + this.register('interceptWaybill', { + description: '拦截运单(支持批量)。仅当用户明确要求"拦截/退回/召回/追回"快递运单时才调用。传入运单号(如SF123456),校验权限后批量创建售后工单,并合并通知对应快递的售后群。货主群需验store_id,仓库群无需。严禁:讨论已有售后工单(AS开头)不是拦截请求、询问物流进度不是拦截请求', + weight: 95, + keywords: [ '拦截', '退回', '召回', '追回', '取消快递', '不要了' ], + params: { + keyword: { type: 'string', required: true, description: '运单号,多个用逗号或空格分隔,如 SF111,SF222' }, + reason: { type: 'string', required: false, description: '拦截原因' }, + }, + groups: [ GROUP.BOUND_WAREHOUSE_CUSTOMER_SERVICE, GROUP.BOUND_STORE_AFTER_SALES ], + handler: async (params = {}) => { + const { ctx } = this; + const raw = String(params.keyword || '').trim(); + const reason = String(params.reason || '').trim(); + const storeId = Number(ctx.inboxContext?.store_id || 0); + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + const groupType = String(ctx.inboxContext?.group_type || '').trim(); + const groupName = String(ctx.inboxContext?.group_name || '').trim(); + const userName = String(ctx.inboxContext?.user_name || '').trim(); + + if (!raw) return { success: false, error: '请提供运单号' }; + if (!warehouseId) return { success: false, error: '无法获取仓库信息' }; + + // 解析多个运单号(逗号/空格/换行分隔) + const keywords = raw.split(/[,,\s\n]+/).map(s => s.trim()).filter(Boolean); + if (keywords.length === 0) return { success: false, error: '未解析到有效运单号' }; + + // 前置拦截:拒绝看起来像售后单号(AS...)的输入,防止误把售后讨论当拦截 + const asLikeList = keywords.filter(k => /^AS/i.test(k)); + if (asLikeList.length > 0) { + return { + success: false, + error: `${asLikeList.join('、')} 看起来是售后工单号而非运单号,如需查询工单请用 queryOrder,如需拦截请提供运单号`, + }; + } + + try { + // 第一步:批量查询运单 + const expressList = await ctx.model.OrderExpress.findAll({ + attributes: [ + 'id', 'waybill_code', 'logistics_name', 'store_id', + 'logistics_interface_id', 'logistics_code', 'order_id', + ], + where: { + waybill_code: { [ctx.app.Sequelize.Op.in]: keywords }, + warehouse_id: warehouseId, + }, + raw: true, + }); + + if (expressList.length === 0) { + return { success: false, error: `未找到运单号「${raw}」,请核实单号后重试` }; + } + + // 第二步:鉴权 + 过滤 + const validList = []; + const skipped = []; + for (const e of expressList) { + if (groupType === 'store') { + if (!storeId || Number(e.store_id) !== storeId) { + skipped.push(e.waybill_code); + continue; + } + } + validList.push(e); + } + + if (validList.length === 0) { + return { + success: false, + error: `运单${skipped.join('、')}不属于当前货主,无法操作`, + }; + } + + // 第三步:幂等检查(批量查已有工单) + const validIds = validList.map(e => e.id); + const existingASList = await ctx.model.AfterSale.findAll({ + attributes: [ 'waybill_id', 'after_sale_no' ], + where: { + waybill_id: { [ctx.app.Sequelize.Op.in]: validIds }, + type: 'order', + sub_type: 'intercept', + status: { [ctx.app.Sequelize.Op.notIn]: [ 'completed', 'closed', 'cancelled' ] }, + }, + raw: true, + }); + const existingWaybillIds = new Set(existingASList.map(r => r.waybill_id)); + + // 过滤掉已存在工单的 + const toCreate = validList.filter(e => !existingWaybillIds.has(e.id)); + const alreadyExist = existingASList.map(r => r.after_sale_no); + + if (toCreate.length === 0) { + return { + success: true, + data: { + existed: true, + message: `运单已存在处理中的拦截工单: ${alreadyExist.join('、')}`, + after_sale_nos: alreadyExist, + }, + }; + } + + // 第四步:批量创建工单(初始状态 pending,后续根据通知结果升级) + const creatorLabel = [ groupName, userName ].filter(Boolean).join('-') || 'AI系统'; + const createdNos = []; + const waybillToAsNo = {}; // waybill_id → after_sale_no 映射 + for (const e of toCreate) { + const afterSaleNo = await ctx.service.systemMethods.afterSale.generateAfterSaleNo(warehouseId); + const descParts = [ + `发起人: ${creatorLabel}`, + `运单号: ${e.waybill_code}`, + `快递公司: ${e.logistics_name || '未知'}`, + reason ? `拦截原因: ${reason}` : '', + ].filter(Boolean).join('\n'); + + await ctx.service.systems.afterSale.create({ + warehouse_id: warehouseId, + after_sale_no: afterSaleNo, + type: 'order', + sub_type: 'intercept', + title: `[AI工单] 拦截请求 - ${e.waybill_code}`, + description: descParts, + priority: 10, + creator_id: 0, + inbox_message_id: ctx.inboxContext?.inbound_message_id || null, + role_group: 'customer_service', + status: 'pending', + waybill_id: e.id, + waybill_no: e.waybill_code, + store_id: e.store_id || storeId || null, + order_id: e.order_id || null, + }); + createdNos.push(afterSaleNo); + waybillToAsNo[e.id] = afterSaleNo; + } + + ctx.logger.info( + `[inbox functions] 批量拦截: total=${keywords.length} found=${expressList.length} ` + + `valid=${validList.length} created=${createdNos.length} skipped=${skipped.length}` + ); + + // 第4.5步:波次感知拦截处理(仅操作待处理表中的订单) + const orderIds = toCreate.map(e => e.order_id).filter(id => id); + if (orderIds.length > 0) { + try { + const orderModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); + if (orderModel) { + const orders = await orderModel.findAll({ + attributes: [ 'id', 'step', 'wave_id', 'inspection_status' ], + where: { + id: { [ctx.app.Sequelize.Op.in]: orderIds }, + step: { [ctx.app.Sequelize.Op.in]: [ 1, 2, 3 ] }, + }, + raw: true, + }); + + if (orders.length > 0) { + // 按 wave_id 分组查波次信息 + const waveIds = [ ...new Set(orders.map(o => o.wave_id).filter(id => id > 0)) ]; + let waveMap = {}; + if (waveIds.length > 0) { + const waves = await ctx.model.WaveBatch.findAll({ + attributes: [ 'wave_id', 'wave_type', 'wave_status', 'total_orders' ], + where: { wave_id: { [ctx.app.Sequelize.Op.in]: waveIds } }, + raw: true, + }); + waveMap = Object.fromEntries(waves.map(w => [ w.wave_id, w ])); + } + + const interceptOrderIds = []; + const kickOutOrderIds = []; + + for (const order of orders) { + const wave = waveMap[order.wave_id]; + const orderId = order.id; + + // 规则1:团购未复核 / 散单未称重 → 设置拦截 + let needIntercept = false; + if (order.wave_id > 0 && wave) { + if (wave.wave_type === 1) { + // 团购波次:未复核 → 拦截 + needIntercept = order.inspection_status !== 'fin'; + } else if (wave.wave_type === 2) { + // 散单波次:未称重视同可拦截(订单表无称重状态,默认拦截) + needIntercept = true; + } + } else { + // 无波次订单:直接拦截 + needIntercept = true; + } + + if (needIntercept) { + interceptOrderIds.push(orderId); + } + + // 规则2:有波次且未打印 + if (order.wave_id > 0 && wave && wave.wave_status < 2) { + const minGroupQty = 13; // 默认大团购阈值 + if (wave.wave_type === 1 && wave.total_orders >= minGroupQty) { + // 大团购:踢出波次 + kickOutOrderIds.push(orderId); + } + // 小团购/散单:仅拦截,不踢出(已在 interceptOrderIds 中处理) + } + } + + // 执行拦截状态设置(订单表 + 运单表) + if (interceptOrderIds.length > 0) { + await orderModel.update( + { intercept_status: 'requested' }, + { where: { id: { [ctx.app.Sequelize.Op.in]: interceptOrderIds } } } + ); + // 同步更新运单表拦截标记 + await ctx.model.OrderExpress.update( + { is_intercept: 'Y' }, + { where: { order_id: { [ctx.app.Sequelize.Op.in]: interceptOrderIds }, warehouse_id: warehouseId } } + ); + ctx.logger.info( + `[inbox functions] 设置拦截状态: ${interceptOrderIds.length} 个订单` + ); + } + + // 执行踢出波次 + if (kickOutOrderIds.length > 0) { + await ctx.service.systemMethods.order.wave.batchRemoveOrders({ + ids: kickOutOrderIds, + }); + ctx.logger.info( + `[inbox functions] 踢出大团购波次: ${kickOutOrderIds.length} 个订单` + ); + } + } + } + } catch (e) { + ctx.logger.warn(`[inbox functions] 波次感知拦截处理失败: ${e.message}`); + } + } + + // 第五步:合并通知对应快递的售后群(按快递分组,每条消息包含该快递的所有运单) + const expressByCode = {}; + for (const e of toCreate) { + const code = e.logistics_code || '__unknown__'; + if (!expressByCode[code]) { + expressByCode[code] = { interfaceId: e.logistics_interface_id, waybills: [] }; + } + expressByCode[code].waybills.push(e.waybill_code); + } + + let notifiedTotal = 0; + const notifiedWaybillIds = new Set(); // 记录哪些运单成功通知了至少一个群 + for (const [ code, info ] of Object.entries(expressByCode)) { + if (code === '__unknown__' || !info.interfaceId) continue; + try { + const { afterSalesGroups } = await ctx.service.systems.inbox.group.findGroupsByExpress({ + expressInterfaceId: info.interfaceId, + expressCode: code, + warehouseId, + }); + + if (afterSalesGroups.length === 0) { + ctx.logger.info(`[inbox functions] 快递 ${code} 未配置售后群,跳过通知`); + continue; + } + + const notifyMsg = info.waybills.join('\n') + '\n拦截'; + for (const g of afterSalesGroups) { + ctx.service.inbox.processor.pushSystemNotification({ + warehouse_id: warehouseId, + group_id: g.group_id, + group_name: g.group_name, + content: notifyMsg, + ext_data: g.ext_data || null, + }); + notifiedTotal += 1; + } + // 有售后群即标记为已通知(推送是异步的,不计成败) + const codeWaybills = toCreate.filter(e => (e.logistics_code || '__unknown__') === code); + codeWaybills.forEach(e => notifiedWaybillIds.add(e.id)); + } catch (e) { + ctx.logger.warn(`[inbox functions] 查售后群失败 code=${code}: ${e.message}`); + } + } + + // 第六步:有通知的工单升级为 pending_feedback + const notifiedAsNos = []; + const notNotifiedAsNos = []; + for (const e of toCreate) { + const asNo = waybillToAsNo[e.id]; + if (notifiedWaybillIds.has(e.id)) { + notifiedAsNos.push(asNo); + } else { + notNotifiedAsNos.push(asNo); + } + } + + if (notifiedAsNos.length > 0) { + // 与 handleWorkOrder 一致:设置追踪时间 + 分配客服组 + const hours = await ctx.service.systems.afterSale._resolveFollowupHours( + warehouseId, 'order', 'intercept' + ); + await ctx.model.AfterSale.update( + { + status: 'pending_feedback', + followup_at: ctx.app.Sequelize.literal(`DATE_ADD(NOW(), INTERVAL ${hours} HOUR)`), + role_group: 'customer_service', + }, + { where: { after_sale_no: { [ctx.app.Sequelize.Op.in]: notifiedAsNos } } } + ); + ctx.logger.info( + `[inbox functions] ${notifiedAsNos.length} 个工单已通知快递群,` + + `升级为 pending_feedback,${hours}h 后追踪` + ); + } + + // 构造返回消息 + const parts = []; + if (notifiedAsNos.length > 0) { + parts.push(`拦截信息已登记并通知快递群,工单: ${notifiedAsNos.join('、')}`); + } + if (notNotifiedAsNos.length > 0) { + parts.push(`拦截信息已登记(未配置快递群,需人工跟进),工单: ${notNotifiedAsNos.join('、')}`); + } + if (alreadyExist.length > 0) { + parts.push(`已登记过,工单: ${alreadyExist.join('、')}`); + } + if (skipped.length > 0) { + parts.push(`无权操作: ${skipped.join('、')}`); + } + + return { + success: true, + data: { + created: createdNos.length, + existed: alreadyExist.length, + skipped: skipped.length, + after_sale_nos: [ ...createdNos, ...alreadyExist ], + notified_as_nos: notifiedAsNos, + not_notified_as_nos: notNotifiedAsNos, + notified_groups: notifiedTotal, + waybills: validList.map(e => e.waybill_code), + message: parts.join(';'), + }, + }; + } catch (error) { + ctx.logger.error(`[inbox functions] 批量拦截失败: ${error.message}`); + return { success: false, error: `拦截操作失败: ${error.message}` }; + } + }, + }); + + this.register('cancelIntercept', { + description: '取消拦截运单(支持批量)。当用户要求"取消拦截/撤销拦截/不拦截了"时调用。先查已有售后工单,有则追加取消记录,无则按拦截规则创建工单。同时设置订单和运单拦截状态并通知快递群', + weight: 94, + keywords: [ '取消拦截', '撤销拦截', '解除拦截', '不拦截了', '不用拦截' ], + params: { + keyword: { type: 'string', required: true, description: '运单号,多个用逗号或空格分隔' }, + reason: { type: 'string', required: false, description: '取消拦截原因' }, + }, + groups: [ GROUP.BOUND_WAREHOUSE_CUSTOMER_SERVICE, GROUP.BOUND_STORE_AFTER_SALES ], + handler: async (params = {}) => { + const { ctx } = this; + const raw = String(params.keyword || '').trim(); + const reason = String(params.reason || '').trim(); + const storeId = Number(ctx.inboxContext?.store_id || 0); + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + const groupType = String(ctx.inboxContext?.group_type || '').trim(); + const groupName = String(ctx.inboxContext?.group_name || '').trim(); + const userName = String(ctx.inboxContext?.user_name || '').trim(); + + if (!raw) return { success: false, error: '请提供运单号' }; + if (!warehouseId) return { success: false, error: '无法获取仓库信息' }; + + const keywords = raw.split(/[,,\s\n]+/).map(s => s.trim()).filter(Boolean); + if (keywords.length === 0) return { success: false, error: '未解析到有效运单号' }; + + const asLikeList = keywords.filter(k => /^AS/i.test(k)); + if (asLikeList.length > 0) { + return { success: false, error: `${asLikeList.join('、')} 是售后工单号而非运单号,请提供运单号` }; + } + + try { + // 第一步:批量查询运单 + const expressList = await ctx.model.OrderExpress.findAll({ + attributes: [ 'id', 'waybill_code', 'logistics_name', 'store_id', + 'logistics_interface_id', 'logistics_code', 'order_id' ], + where: { waybill_code: { [ctx.app.Sequelize.Op.in]: keywords }, warehouse_id: warehouseId }, + raw: true, + }); + if (expressList.length === 0) { + return { success: false, error: `未找到运单号「${raw}」,请核实单号后重试` }; + } + + // 第二步:鉴权 + const validList = []; + const skipped = []; + for (const e of expressList) { + if (groupType === 'store') { + if (!storeId || Number(e.store_id) !== storeId) { skipped.push(e.waybill_code); continue; } + } + validList.push(e); + } + if (validList.length === 0) { + return { success: false, error: `运单${skipped.join('、')}不属于当前货主,无法操作` }; + } + + // 第三步:查已有工单(不限制状态,找到即追加取消记录) + const validIds = validList.map(e => e.id); + const existingASList = await ctx.model.AfterSale.findAll({ + attributes: [ 'id', 'waybill_id', 'waybill_no', 'after_sale_no', 'status', 'store_id' ], + where: { + waybill_id: { [ctx.app.Sequelize.Op.in]: validIds }, + type: 'order', + status: { [ctx.app.Sequelize.Op.notIn]: [ 'completed', 'closed', 'cancelled' ] }, + }, + raw: true, + }); + + const existingWaybillIds = new Set(existingASList.map(r => r.waybill_id)); + const toCreate = validList.filter(e => !existingWaybillIds.has(e.id)); + + // 获取原消息内容用于反馈记录 + let cancelMsgContent = ''; + try { + const cid = ctx.inboxContext?.inbound_message_id; + if (cid) { + const cm = await ctx.model.InboxMessage.findByPk(cid, { attributes: [ 'content' ], raw: true }); + if (cm && cm.content) cancelMsgContent = String(cm.content); + } + } catch (e) { /* ignore */ } + + let feedbackCount = 0; + const cancelGroup = ctx.inboxContext?.group_name || '未知群'; + const cancelUser = ctx.inboxContext?.user_name || '未知用户'; + const cancelTime = new Date().toISOString().slice(0, 19) + .replace('T', ' '); + + // 已有工单:追加取消拦截记录 + for (const as of existingASList) { + try { + const remarkLines = [ + `群: ${cancelGroup}`, `用户: ${cancelUser}`, `时间: ${cancelTime}`, + ]; + if (cancelMsgContent) remarkLines.push(`原消息: ${cancelMsgContent}`); + if (reason) remarkLines.push(`取消原因: ${reason}`); + await ctx.service.systems.afterSale.addStep(as.id, { + step_status: 'processing', + action: '取消拦截', + remark: remarkLines.join('\n'), + }); + feedbackCount += 1; + } catch (e) { + ctx.logger.warn(`[inbox functions] 取消拦截反馈失败 as_no=${as.after_sale_no}: ${e.message}`); + } + } + + const parts = []; + if (feedbackCount > 0) parts.push(`已有工单追加取消拦截: ${feedbackCount}个`); + + // 第四步:无工单的按拦截规则创建 + const createdNos = []; + if (toCreate.length > 0) { + const creatorLabel = [ groupName, userName ].filter(Boolean).join('-') || 'AI系统'; + for (const e of toCreate) { + const afterSaleNo = await ctx.service.systemMethods.afterSale.generateAfterSaleNo(warehouseId); + const descParts = [ + `发起人: ${creatorLabel}`, `运单号: ${e.waybill_code}`, + `快递公司: ${e.logistics_name || '未知'}`, + reason ? `取消原因: ${reason}` : '', + '来源: 取消拦截', + ].filter(Boolean).join('\n'); + + await ctx.service.systems.afterSale.create({ + warehouse_id: warehouseId, after_sale_no: afterSaleNo, + type: 'order', sub_type: 'intercept', + title: `[AI工单] 取消拦截 - ${e.waybill_code}`, + description: descParts, priority: 10, creator_id: 0, + inbox_message_id: ctx.inboxContext?.inbound_message_id || null, + role_group: 'customer_service', status: 'pending', + waybill_id: e.id, waybill_no: e.waybill_code, + store_id: e.store_id || storeId || null, + order_id: e.order_id || null, + }); + createdNos.push(afterSaleNo); + } + } + if (createdNos.length > 0) parts.push(`已创建取消拦截工单: ${createdNos.length}个`); + + ctx.logger.info( + `[inbox functions] 取消拦截: total=${keywords.length} ` + + `feedback=${feedbackCount} created=${createdNos.length} skipped=${skipped.length}` + ); + + // 第4.5步:波次感知拦截(与 interceptWaybill 相同) + const orderIds = toCreate.map(e => e.order_id).filter(id => id); + if (orderIds.length > 0) { + try { + const orderModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); + if (orderModel) { + const orders = await orderModel.findAll({ + attributes: [ 'id', 'step', 'wave_id', 'inspection_status' ], + where: { id: { [ctx.app.Sequelize.Op.in]: orderIds }, step: { [ctx.app.Sequelize.Op.in]: [ 1, 2, 3 ] } }, + raw: true, + }); + if (orders.length > 0) { + const waveIds = [ ...new Set(orders.map(o => o.wave_id).filter(id => id > 0)) ]; + let waveMap = {}; + if (waveIds.length > 0) { + const waves = await ctx.model.WaveBatch.findAll({ + attributes: [ 'wave_id', 'wave_type', 'wave_status', 'total_orders' ], + where: { wave_id: { [ctx.app.Sequelize.Op.in]: waveIds } }, raw: true, + }); + waveMap = Object.fromEntries(waves.map(w => [ w.wave_id, w ])); + } + const interceptOrderIds = []; + for (const order of orders) { + const wave = waveMap[order.wave_id]; + let needIntercept = false; + if (order.wave_id > 0 && wave) { + needIntercept = wave.wave_type === 1 ? order.inspection_status !== 'fin' : true; + } else { + needIntercept = true; + } + if (needIntercept) interceptOrderIds.push(order.id); + } + if (interceptOrderIds.length > 0) { + await orderModel.update( + { intercept_status: 'requested' }, + { where: { id: { [ctx.app.Sequelize.Op.in]: interceptOrderIds } } } + ); + await ctx.model.OrderExpress.update( + { is_intercept: 'Y' }, + { where: { order_id: { [ctx.app.Sequelize.Op.in]: interceptOrderIds }, warehouse_id: warehouseId } } + ); + ctx.logger.info(`[inbox functions] 取消拦截-设置拦截状态: ${interceptOrderIds.length} 个订单`); + } + } + } + } catch (e) { + ctx.logger.warn(`[inbox functions] 取消拦截-波次处理失败: ${e.message}`); + } + } + + // 第五步:通知快递群 + const expressByCode = {}; + for (const e of toCreate) { + const code = e.logistics_code || '__unknown__'; + if (!expressByCode[code]) expressByCode[code] = { interfaceId: e.logistics_interface_id, waybills: [] }; + expressByCode[code].waybills.push(e.waybill_code); + } + let notifiedTotal = 0; + const notifiedNos = []; + for (const [ code, info ] of Object.entries(expressByCode)) { + if (code === '__unknown__' || !info.interfaceId) continue; + try { + const { afterSalesGroups } = await ctx.service.systems.inbox.group.findGroupsByExpress({ + expressInterfaceId: info.interfaceId, expressCode: code, warehouseId, + }); + if (afterSalesGroups.length === 0) continue; + const notifyMsg = info.waybills.join('\n') + '\n取消拦截'; + for (const g of afterSalesGroups) { + ctx.service.inbox.processor.pushSystemNotification({ + warehouse_id: warehouseId, group_id: g.group_id, + group_name: g.group_name, content: notifyMsg, ext_data: g.ext_data || null, + }); + notifiedTotal += 1; + } + } catch (e) { + ctx.logger.warn(`[inbox functions] 取消拦截查快递群失败 code=${code}: ${e.message}`); + } + } + if (notifiedTotal > 0) parts.push(`已通知 ${notifiedTotal} 个快递群`); + + // 有通知的工单升级 pending_feedback + if (notifiedNos.length > 0) { + const hours = await ctx.service.systems.afterSale._resolveFollowupHours(warehouseId, 'order', 'intercept'); + await ctx.model.AfterSale.update( + { status: 'pending_feedback', followup_at: ctx.app.Sequelize.literal(`DATE_ADD(NOW(), INTERVAL ${hours} HOUR)`), role_group: 'customer_service' }, + { where: { after_sale_no: { [ctx.app.Sequelize.Op.in]: notifiedNos }, warehouse_id: warehouseId } } + ); + } + + return { success: true, data: { feedback: feedbackCount, created: createdNos.length, skipped: skipped.length, notified_groups: notifiedTotal, message: parts.join(';') || '处理完成' } }; + } catch (error) { + ctx.logger.error(`[inbox functions] 取消拦截失败: ${error.message}`); + return { success: false, error: `操作失败: ${error.message}` }; + } + }, + }); + + this.register('handleExpressFeedback', { + description: '快递群售后通用反馈。传入运单号,优先找已有售后工单追加记录,无工单则按运单查订单并自动创建售后工单。AI 可根据快递反馈内容传入售后类型和子类型', + weight: 90, + keywords: [ '已处理', '已联系', '已通知', '核实', '反馈' ], + params: { + keyword: { type: 'string', required: true, description: '运单号,多个用逗号或空格分隔' }, + as_type: { type: 'string', required: false, description: '新建工单时的售后类型(order/receiving),默认 order' }, + as_sub_type: { type: 'string', required: false, description: '新建工单时的售后子类型,默认 logistics_issue。可选: logistics_issue(物流异常)/damage(破损)/missing_item(少发)/delivery_delay(发货延迟)/urge(催件)/verify_delivery(核实签收)/change_carrier(换快递)/rejected(拒收)/other(其他)' }, + }, + groups: [ GROUP.BOUND_EXPRESS_AFTER_SALES ], + handler: async (params = {}) => { + const { ctx } = this; + const raw = String(params.keyword || '').trim(); + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + const asType = String(params.as_type || 'order').trim() || 'order'; + const asSubType = String(params.as_sub_type || 'logistics_issue').trim() || 'logistics_issue'; + + if (!raw) return { success: false, error: '请提供运单号' }; + if (!warehouseId) return { success: false, error: '无法获取仓库信息' }; + + const keywords = raw.split(/[,,\s\n]+/).map(s => s.trim()).filter(Boolean); + if (keywords.length === 0) return { success: false, error: '未解析到有效运单号' }; + + try { + // 第一步:查已有售后工单 + const existingAS = await ctx.model.AfterSale.findAll({ + attributes: [ 'id', 'after_sale_no', 'waybill_no', 'status', 'warehouse_id', 'inbox_message_id', 'store_id' ], + where: { + waybill_no: { [ctx.app.Sequelize.Op.in]: keywords }, + warehouse_id: warehouseId, + }, + raw: true, + }); + + const hasAS = new Set(existingAS.map(r => r.waybill_no)); + let feedbackCount = 0; + let createdCount = 0; + const parts = []; + + // 已有工单:追加反馈 + // 获取原始消息内容用于反馈记录 + let feedbackMsgContent = ''; + try { + const fbMsgId = ctx.inboxContext?.inbound_message_id; + if (fbMsgId) { + const fbMsg = await ctx.model.InboxMessage.findByPk(fbMsgId, { + attributes: [ 'content' ], + raw: true, + }); + if (fbMsg && fbMsg.content) feedbackMsgContent = String(fbMsg.content); + } + } catch (e) { + ctx.logger.warn(`[inbox functions] 获取原消息内容失败: ${e.message}`); + } + const feedbackGroup = ctx.inboxContext?.group_name || '未知群'; + const feedbackUser = ctx.inboxContext?.user_name || '未知用户'; + for (const as of existingAS) { + try { + const remarkLines = [ + `群: ${feedbackGroup}`, + `用户: ${feedbackUser}`, + `时间: ${new Date().toISOString().slice(0, 19) + .replace('T', ' ')}`, + ]; + if (feedbackMsgContent) { + remarkLines.push(`原消息: ${feedbackMsgContent}`); + } + await ctx.service.systems.afterSale.addStep(as.id, { + step_status: 'processing', + action: '快递反馈', + remark: remarkLines.join('\n'), + }); + feedbackCount += 1; + } catch (e) { + ctx.logger.warn(`[inbox functions] 快递反馈失败 as_no=${as.after_sale_no}: ${e.message}`); + } + } + if (feedbackCount > 0) { + parts.push(`已有工单追加反馈: ${feedbackCount}个`); + } + + // 第二步:无工单的运单,查订单并创建售后工单 + const needCreate = keywords.filter(k => !hasAS.has(k)); + let expressList = []; + const createdAsNos = []; + if (needCreate.length > 0) { + expressList = await ctx.model.OrderExpress.findAll({ + attributes: [ 'id', 'waybill_code', 'logistics_name', 'store_id', 'warehouse_id', 'order_id' ], + where: { + waybill_code: { [ctx.app.Sequelize.Op.in]: needCreate }, + warehouse_id: warehouseId, + }, + raw: true, + }); + + const foundCodes = new Set(expressList.map(e => e.waybill_code)); + const notFound = needCreate.filter(k => !foundCodes.has(k)); + + for (const e of expressList) { + try { + const afterSaleNo = await ctx.service.systemMethods.afterSale.generateAfterSaleNo(warehouseId); + const title = `[AI工单] 快递反馈 - ${e.waybill_code}`; + const description = [ + `运单号: ${e.waybill_code}`, + `快递公司: ${e.logistics_name || '未知'}`, + `售后类型: ${asType}.${asSubType}`, + '来源: 快递群反馈', + ].join('\n'); + + await ctx.service.systems.afterSale.create({ + warehouse_id: warehouseId, + after_sale_no: afterSaleNo, + type: asType, + sub_type: asSubType, + title, + description, + priority: 10, + creator_id: 0, + inbox_message_id: ctx.inboxContext?.inbound_message_id || null, + role_group: 'customer_service', + status: 'pending', + waybill_id: e.id, + waybill_no: e.waybill_code, + store_id: e.store_id || null, + order_id: e.order_id || null, + }); + createdAsNos.push(afterSaleNo); + createdCount += 1; + } catch (e) { + ctx.logger.warn(`[inbox functions] 快递反馈建单失败 wb=${e.waybill_code}: ${e.message}`); + } + } + if (createdCount > 0) { + parts.push(`已创建工单: ${createdCount}个`); + } + if (notFound.length > 0) { + parts.push(`未找到运单: ${notFound.join('、')}`); + } + } + + ctx.logger.info( + `[inbox functions] 快递反馈: total=${keywords.length} ` + + `feedback=${feedbackCount} created=${createdCount}` + ); + + // 第三步:排除回复检查(仓库配置 inbox_reply_exclude_keywords) + let skipReply = false; + try { + const inboundMsgId = ctx.inboxContext?.inbound_message_id; + if (inboundMsgId) { + const [ inboundMsg, store ] = await Promise.all([ + ctx.model.InboxMessage.findByPk(inboundMsgId, { + attributes: [ 'id', 'content' ], + raw: true, + }), + ctx.model.Store.findByPk(warehouseId, { + attributes: [ 'subject_config' ], + raw: true, + }), + ]); + + const excludeKeywords = (store && store.subject_config + && Array.isArray(store.subject_config.inbox_reply_exclude_keywords)) + ? store.subject_config.inbox_reply_exclude_keywords.filter(k => typeof k === 'string' && k.trim()) + : []; + + if (excludeKeywords.length > 0 && inboundMsg && inboundMsg.content) { + const msgContent = String(inboundMsg.content); + const matched = excludeKeywords.find(kw => msgContent.includes(kw)); + if (matched) { + skipReply = true; + ctx.logger.info( + `[inbox functions] 消息命中排除关键词「${matched}」,仅记录不通知` + ); + } + } + } + } catch (e) { + ctx.logger.warn(`[inbox functions] 排除回复检查失败: ${e.message}`); + } + + let replyTargets = new Map(); + if (!skipReply) { + // 第四步:回信路由 + // - 已有工单且带 inbox_message_id → 查原始消息获取群信息 → 回信到原群 + // - 无工单或无 inbox_message_id → 回信到货主售后群 + replyTargets = new Map(); // group_id → { group_id, group_name, user_id, ext_data } + const replyMsg = parts.join(';') || '处理完成'; + + // 4a. 已有工单带 inbox_message_id:回信到原消息所在群(排除快递群) + const asWithMsgId = existingAS.filter(as => as.inbox_message_id); + let expressGroupIds = new Set(); + if (asWithMsgId.length > 0) { + const msgIds = [ ...new Set(asWithMsgId.map(as => as.inbox_message_id)) ]; + try { + const messages = await ctx.model.InboxMessage.findAll({ + attributes: [ 'id', 'group_id', 'user_id', 'group_name', 'user_name' ], + where: { id: { [ctx.app.Sequelize.Op.in]: msgIds } }, + raw: true, + }); + // 过滤快递群:原消息来自快递群的,不回信到快递群,走 4b 货主售后群 + const candidateGroupIds = [ ...new Set(messages.map(m => m.group_id).filter(Boolean)) ]; + if (candidateGroupIds.length > 0) { + const expressGroups = await ctx.model.InboxGroup.findAll({ + attributes: [ 'group_id' ], + where: { + group_id: { [ctx.app.Sequelize.Op.in]: candidateGroupIds }, + warehouse_id: warehouseId, + group_type: 'express', + }, + raw: true, + }); + expressGroupIds = new Set(expressGroups.map(g => g.group_id)); + } + for (const msg of messages) { + if (msg.group_id && !replyTargets.has(msg.group_id) && !expressGroupIds.has(msg.group_id)) { + replyTargets.set(msg.group_id, { + group_id: msg.group_id, + group_name: msg.group_name || '', + user_id: msg.user_id || '', + user_name: msg.user_name || '', + ext_data: null, + }); + } + } + } catch (e) { + ctx.logger.warn(`[inbox functions] 查原消息群信息失败: ${e.message}`); + } + } + + // 4b. 已有工单无 inbox_message_id + 新建工单 + 原消息来自快递群:回信到货主售后群 + const storeIdsForReply = new Set(); + // 已有工单无 inbox_message_id 的 store_id + for (const as of existingAS) { + if (!as.inbox_message_id && as.store_id) { + storeIdsForReply.add(as.store_id); + } + } + // 已有工单 inbox_message_id 指向快递群的(4a 已排除),也走货主售后群 + if (expressGroupIds && expressGroupIds.size > 0) { + for (const as of asWithMsgId) { + if (as.store_id) storeIdsForReply.add(as.store_id); + } + } + // 新建工单的 store_id(来自 OrderExpress 记录) + for (const e of expressList) { + if (!hasAS.has(e.waybill_code) && e.store_id) { + storeIdsForReply.add(e.store_id); + } + } + + if (storeIdsForReply.size > 0) { + try { + const storeGroups = await ctx.service.systems.inbox.group.findStoreAfterSalesGroups({ + storeIds: [ ...storeIdsForReply ], + warehouseId, + }); + for (const g of storeGroups) { + if (g.group_id && !replyTargets.has(g.group_id)) { + replyTargets.set(g.group_id, { + group_id: g.group_id, + group_name: g.group_name || '', + user_id: '', + user_name: '', + ext_data: g.ext_data || null, + }); + } + } + } catch (e) { + ctx.logger.warn(`[inbox functions] 查货主售后群失败: ${e.message}`); + } + } + + // 3c. 发送回信 + for (const [ , target ] of replyTargets) { + ctx.service.inbox.processor.pushSystemNotification({ + warehouse_id: warehouseId, + group_id: target.group_id, + group_name: target.group_name, + content: `快递反馈: ${replyMsg}`, + ext_data: target.ext_data, + }); + } + + if (replyTargets.size > 0) { + parts.push(`已回信到 ${replyTargets.size} 个群`); + } + } // if (!skipReply) + + if (skipReply) { + parts.push('消息命中排除关键词,仅记录不通知'); + } + + // 第五步:更新新建工单状态 + // - 已回信 → pending_feedback(等待外部通知)+ 跟踪时间 + // - 未回信/排除关键词 → processing(处理中) + // 注意:已有工单仅追加反馈,不改变原有状态 + if (createdAsNos.length > 0) { + try { + if (!skipReply && replyTargets && replyTargets.size > 0) { + const hours = await ctx.service.systems.afterSale._resolveFollowupHours( + warehouseId, asType, asSubType + ); + await ctx.model.AfterSale.update( + { + status: 'pending_feedback', + followup_at: ctx.app.Sequelize.literal(`DATE_ADD(NOW(), INTERVAL ${hours} HOUR)`), + role_group: 'customer_service', + }, + { + where: { + after_sale_no: { [ctx.app.Sequelize.Op.in]: createdAsNos }, + warehouse_id: warehouseId, + }, + } + ); + ctx.logger.info( + `[inbox functions] ${createdAsNos.length} 个工单已通知客户群,升级 pending_feedback,${hours}h 后追踪` + ); + } else { + await ctx.model.AfterSale.update( + { status: 'processing', role_group: 'customer_service' }, + { + where: { + after_sale_no: { [ctx.app.Sequelize.Op.in]: createdAsNos }, + warehouse_id: warehouseId, + }, + } + ); + ctx.logger.info( + `[inbox functions] ${createdAsNos.length} 个工单未通知客户群,状态设为 processing` + ); + } + } catch (e) { + ctx.logger.warn(`[inbox functions] 更新工单状态失败: ${e.message}`); + } + } + + return { + success: true, + data: { + feedback: feedbackCount, + created: createdCount, + message: parts.join(';') || '处理完成', + }, + }; + } catch (error) { + ctx.logger.error(`[inbox functions] 快递反馈处理失败: ${error.message}`); + return { success: false, error: `操作失败: ${error.message}` }; + } + }, + }); + this.register('listGroups', { - description: '查询当前仓库的群列表,包含屏蔽状态', + description: '查询当前仓库的群列表,包含屏蔽状态(仅内部仓库群可用)', params: {}, - groups: [ GROUP.COMMON ], + groups: [ GROUP.BOUND_WAREHOUSE ], + weight: 0, + keywords: [ '群列表', '有哪些群', '群组' ], handler: async (params = {}) => { const { ctx } = this; void params; @@ -905,6 +1791,8 @@ class InboxFunctionsService extends Service { * @param {Object} def.params 参数定义。 * @param {string[]} def.groups 所属分组列表,按 {主分组}:{子分组} 格式。 * 例如 ['common'] 或 ['bound:store', 'bound:store:after_sales']。 + * @param {number} [def.weight=0] 权重,值越大优先级越高,用于 AI 多函数匹配时排序。 + * @param {string[]} [def.keywords] 触发关键词,用于 AI 快速匹配用户意图。 * @param {Function} def.handler 函数实现,接收 params 对象,返回结果。 */ register(name, def) { @@ -921,135 +1809,13 @@ class InboxFunctionsService extends Service { groups: Array.isArray(def.groups) && def.groups.length > 0 ? def.groups : [ GROUP.COMMON ], + weight: Number.isFinite(def.weight) ? def.weight : 0, + keywords: Array.isArray(def.keywords) ? def.keywords : [], handler: def.handler, }); this.ctx.logger.info(`[inbox functions] 注册函数: ${name} groups=${this.registry.get(name).groups.join(',')}`); } - /** - * 根据当前上下文解析可用分组集合。 - * - * ### 分组解析逻辑 - * - * - 始终包含 `common`(通用分组)。 - * - 若群已绑定货主(`store_id > 0` 且 `groupType === 'store'`): - * - 追加 `bound:store`(主分组)。 - * - 若有 `subType`(如 `after_sales`),追加 `bound:store:{subType}`。 - * - 若群已绑定仓库(`groupType === 'warehouse'`):追加 `bound:warehouse`。 - * - 若群已绑定快递(`groupType === 'express'`):追加 `bound:express`。 - * - * ### 使用方式 - * - * - AI 处理消息时自动调用,无需手动传参。 - * - 也可显式传入 `opts.groupType` / `opts.subType` 覆盖上下文。 - * - * @param {Object} [opts] 可选覆盖参数。 - * @param {string} [opts.groupType] 群类型(store / warehouse / express)。 - * @param {string} [opts.subType] 子类型(after_sales / finance / receiving)。 - * @return {string[]} 当前上下文中可用的分组列表。 - */ - resolveActiveGroups(opts = {}) { - const { ctx } = this; - const groups = [ GROUP.COMMON ]; - - const groupType = String( - opts.groupType || ctx.inboxContext?.group_type || '' - ).trim(); - const subType = String( - opts.subType || ctx.inboxContext?.sub_type || '' - ).trim(); - const storeId = Number(ctx.inboxContext?.store_id || 0); - - // 已绑定货主 → 加入 bound:store 及相关子分组 - if (storeId > 0 && groupType === 'store') { - groups.push(GROUP.BOUND_STORE); - const subGroup = `bound:store:${subType}`; - if (SUB_TO_MAIN[subGroup]) { - groups.push(subGroup); - } - } - - // 其他绑定类型预留 - if (storeId > 0 && groupType === 'warehouse') { - groups.push(GROUP.BOUND_WAREHOUSE); - } - if (storeId > 0 && groupType === 'express') { - groups.push(GROUP.BOUND_EXPRESS); - } - - return groups; - } - - /** - * 判断某个函数在当前活跃分组集合中是否可用。 - * - * ### 匹配规则 - * - * 1. 函数未声明 `groups` 或为空数组 → 视为 `['common']`,始终可用。 - * 2. 函数 `groups` 中包含 `common` → 始终可用。 - * 3. 函数 `groups` 中包含 `{主分组}:*` 通配(如 `bound:store:*`) → - * 展开为 `WILDCARD_EXPAND` 中定义的所有子分组,逐一与活跃分组求交集。 - * 4. 精确匹配:函数 `groups` 中的每一个精确分组名与活跃分组集合取交集。 - * - * @param {Object} def 函数定义对象(含 `groups` 字段)。 - * @param {string[]} activeGroups 当前上下文的活跃分组列表。 - * @return {boolean} 该函数在当前分组中是否可用。 - */ - isFunctionAvailable(def, activeGroups) { - if (!Array.isArray(def.groups) || def.groups.length === 0) return true; - - const expanded = []; - for (const g of def.groups) { - // 通配展开:bound:store:* → [bound:store, bound:store:after_sales, ...] - if (WILDCARD_EXPAND[g]) { - expanded.push(...WILDCARD_EXPAND[g]); - } else { - expanded.push(g); - } - } - - // common 分组或任一展开后的分组命中活跃集合即视为可用 - return expanded.some(g => g === GROUP.COMMON || activeGroups.includes(g)); - } - - /** - * 获取指定分组下的函数列表。 - * - * @param {string[]} [activeGroups] 活跃分组列表,不传则返回全部已注册函数。 - * @return {Array<{name: string, description: string, params: Object}>} 函数列表。 - */ - getFunctionList(activeGroups) { - const list = []; - for (const [ name, def ] of this.registry) { - if (activeGroups && !this.isFunctionAvailable(def, activeGroups)) continue; - list.push({ - name, - description: def.description, - params: def.params, - }); - } - return list; - } - - /** - * 构建函数列表的文本描述,供 AI prompt 使用。 - * - * @param {string[]} [activeGroups] 活跃分组列表,不传则返回全部。 - * @return {string} 函数列表文本。 - */ - buildFunctionListText(activeGroups) { - const lines = []; - for (const [ name, def ] of this.registry) { - if (activeGroups && !this.isFunctionAvailable(def, activeGroups)) continue; - const paramEntries = Object.entries(def.params); - const paramStr = paramEntries.length > 0 - ? paramEntries.map(([ k, v ]) => `${k}(${v.type || 'string'}, ${v.required ? '必填' : '可选'}): ${v.description}`).join(', ') - : '无参数'; - lines.push(`- ${name}: ${def.description}。参数: ${paramStr}`); - } - return lines.join('\n'); - } - /** * 执行已注册的函数。 * @@ -1076,358 +1842,6 @@ class InboxFunctionsService extends Service { }; } } - - /** - * 调用 DeepSeek API。 - * - * @param {Array<{role: string, content: string}>} messages 消息列表。 - * @param {Object} [options] 额外选项。 - * @return {Promise} AI 返回的文本内容。 - */ - async callDeepSeek(messages, options = {}) { - const { ctx } = this; - const apiKey = ctx.app.config.deepseek.apiKey; - const baseUrl = ctx.app.config.deepseek.baseUrl || 'https://api.deepseek.com'; - - if (!apiKey) { - throw new Error('DeepSeek API Key 未配置'); - } - - const result = await ctx.curl(`${baseUrl}/v1/chat/completions`, { - method: 'POST', - contentType: 'json', - dataType: 'json', - headers: { Authorization: `Bearer ${apiKey}` }, - data: { - model: 'deepseek-v4-pro', - messages, - temperature: options.temperature ?? 0, - max_tokens: options.maxTokens ?? 1000, - }, - timeout: options.timeout || 30000, - }); - - if (result.status !== 200 || !result.data) { - throw new Error(`DeepSeek 请求失败, HTTP ${result.status}`); - } - - let content = result.data.choices?.[0]?.message?.content || ''; - // 清理 markdown 代码块 - content = content.replace(/^```json\s*/i, '').replace(/\s*```$/i, ''); - content = content.replace(/^```\s*/i, '').replace(/\s*```$/i, ''); - return content.trim(); - } - - /** - * 获取智能对话历史上下文。 - * 同一群 + 同一用户 → 最近 N 条消息(含 AI 回复),用于多轮对话短期记忆。 - * 按创建时间升序排列,并为每条消息附加序号供 AI 追踪。 - * - * @param {Object} opts 查询选项。 - * @param {number} [opts.parentId] 当前消息的 parent_id(兼容旧参数)。 - * @param {number} [opts.maxMessages=5] 最大历史消息数。 - * @return {Promise>} 历史消息列表。 - */ - async getConversationHistory(opts = {}) { - const parentId = Number(opts.parentId) || 0; - const maxMessages = Math.min(10, Math.max(1, Number(opts.maxMessages) || 5)); - - const { ctx } = this; - const { InboxMessage } = ctx.model; - const { Op } = ctx.app.Sequelize; - - const groupId = String(ctx.inboxContext?.group_id || '').trim(); - const userId = String(ctx.inboxContext?.user_id || '').trim(); - const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); - - // 无群/用户上下文时,退回旧逻辑:沿 parent_id 追溯 - if (!groupId || !userId || !warehouseId) { - if (!parentId) return []; - try { - const history = []; - let currentId = parentId; - const visited = new Set(); - while (currentId && history.length < maxMessages) { - if (visited.has(currentId)) break; - visited.add(currentId); - const msg = await InboxMessage.findOne({ - attributes: [ 'id', 'parent_id', 'direction', 'content' ], - where: { id: currentId }, - raw: true, - }); - if (!msg) break; - history.unshift({ role: msg.direction === 'inbound' ? 'user' : 'assistant', content: msg.content || '' }); - currentId = msg.parent_id; - } - return history; - } catch (error) { - ctx.logger.warn(`[inbox functions] 对话历史回退查询失败: ${error.message}`); - return []; - } - } - - // 智能查询:同一群,最近 maxMessages 条(入站+出站混合,含所有成员) - try { - const messages = await InboxMessage.findAll({ - attributes: [ 'id', 'parent_id', 'direction', 'content', 'user_id', 'user_name', 'created_at' ], - where: { - warehouse_id: warehouseId, - group_id: groupId, - direction: { [Op.in]: [ 'inbound', 'outbound' ] }, - }, - order: [[ 'created_at', 'DESC' ]], - limit: maxMessages, - raw: true, - }); - - if (messages.length === 0) return []; - - // 升序排列,附加上下文信息供 AI 判断真人接管 - const blockedUsers = ctx.inboxContext?._blockedUserIds || new Set(); - return messages.reverse().map(msg => { - const u = String(msg.user_id || '').trim(); - const name = String(msg.user_name || '').trim(); - const isBlocked = u && blockedUsers.has(u); - return { - role: msg.direction === 'inbound' ? 'user' : 'assistant', - content: msg.content || '', - user_id: u || null, - user_name: name || null, - blocked: isBlocked, - }; - }); - } catch (error) { - ctx.logger.warn(`[inbox functions] 智能对话历史查询失败: ${error.message}`); - return []; - } - } - - /** - * DeepSeek 多轮推理:思考→调函数→评估→(重复或输出)。 - * - * 每轮 AI 返回 JSON,通过 action 字段决定行为: - * { "action": "call", "function": "函数名", "params": {...}, "reason": "..." } - * { "action": "reply", "reply": "最终回复内容" } - * - * 最多 MAX_ROUNDS 轮,防止无限循环。 - * - * @param {Object} data 消息数据。 - * @param {string} data.content 消息正文。 - * @param {Object} [data.ext_data] 透传数据。 - * @param {number} [data.parentId] 父消息ID。 - * @return {Promise<{reply: string, functionName: string|null, functionResult: Object|null}>} AI 回复。 - */ - async processWithAI(data = {}) { - const { ctx } = this; - const content = String(data.content || '').trim(); - if (!content) { - return { reply: '消息正文为空,无法处理', functionName: null, functionResult: null }; - } - - const activeGroups = this.resolveActiveGroups(); - ctx.logger.info(`[inbox functions] 当前活跃分组: ${activeGroups.join(', ')}`); - - const functionListText = this.buildFunctionListText(activeGroups); - if (!functionListText) { - ctx.logger.info('[inbox functions] 当前上下文无可用的 AI 函数'); - return { reply: null, functionName: null, functionResult: null }; - } - - // 拉取群历史(最多 10 条),同时注入 system prompt 和对话上下文 - const history = await this.getConversationHistory({ - parentId: data.parentId, - maxMessages: 10, - }); - const historyContext = history.length > 0 - ? history.map(h => { - const tag = h.blocked ? '[已屏蔽]' : ''; - return `[${h.role === 'user' ? h.user_name || h.user_id || '未知' : 'AI'}]${tag}: ${h.content}`; - }).join('\n') - : '(无历史)'; - - const MAX_ROUNDS = 5; - const executedFunctions = []; - const thoughts = []; - let finalReply = null; - let lastFunctionName = null; - let lastFunctionResult = null; - - const systemPrompt = `你是一个 WMS 仓库管理系统的智能助手,支持多步推理。 -已注册函数:\n${functionListText}\n -=== 群最近对话历史 === -${historyContext} -=== - -对话历史中 [已屏蔽] 标记表示该用户已主动要求屏蔽(不想被 AI 打扰)。 -如果 [已屏蔽] 用户发送了表示接手或正在处理的内容(如"我来处理""不用回复""稍等""我看看"),说明真人已接管 → 直接 silent。 - -你需要通过多轮调用来完成用户的复杂请求。每轮返回纯 JSON: - -如果还需要调用函数获取信息: -{ - "action": "call", - "function": "函数名", - "params": { "参数名": "参数值" }, - "reason": "为什么需要这个函数" -} - -如果信息充足可以回复用户了: -{ - "action": "reply", - "reply": "最终回复(中文纯文本,禁止Markdown,200字以内,可适当使用\\n换行分隔信息)" -} - -如果消息无需回复(用户只是确认、道谢、告别或表示自己处理): -{ - "action": "silent" -} - -真人接管判断规则(优先级最高,先于所有其他规则): -- 如果历史中某条消息 blocked=true 的用户发送了与当前问题相关的内容(如"我来处理""稍等""我看看"等表示接手的话术),说明真人客服已介入处理 → 直接 silent -- 如果 blocked 用户发送的内容与问题无关(如闲聊、询问其他事情),且当前用户仍在提问 → 正常回复当前用户 -- 如果历史中只有当前用户的连续消息,没有其他用户介入 → 正常回复 - -一般约束: -- 最多 ${MAX_ROUNDS} 轮函数调用,第 ${MAX_ROUNDS} 轮必须给出最终回复 -- 同一函数不要重复调用(除非参数不同) -- 如果函数执行失败,换其他方式或直接告知用户 -- 回复使用中文纯文本,禁止 Markdown 语法,可用 \\n 换行提升可读性 -- silent 仅用于:用户已确认收到消息且无新问题("好的""收到""OK""谢谢""知道了""好"),或用户表示告别/离场("再见""拜拜""88") -- 以下情况严禁 silent,必须 reply:任何形式的提问(含"在吗""有人吗""在不在")、操作请求、函数执行完毕、自定义欢迎语"你好""嗨""hello"等首次问候 -- 无法判断时,宁可回复也不要 silent -- searchStock 返回多条结果时,必须列举让用户选择(告知 id/编码/名称/可用库存),不要擅自决定 -- createOrder 失败时告知失败原因(库存不足/商品不存在等),不要重试同一商品 -- searchStock 返回的 stock_available 为 0 时,提醒用户该商品无库存,建议选择其他商品 -- searchStock/searchWarehouseStock 返回的 image_url 为图片URL数组(可能多张),has_images 为 true 时给出链接 -- searchStock/searchWarehouseStock 返回的 barcodes 为关联条码,回复时可列出帮助核对 -- searchStock/searchWarehouseStock 返回的管理标识 is_sn_mgmt/is_shelf_life_mgmt/is_batch_mgmt 分别表示SN管理/效期管理/批次管理 -- searchStock/searchWarehouseStock 返回的 box_spec 为箱规(长宽高体积毛净重装箱数),packing_requirements 为打包要求,用户问及时告知 -- searchStock/searchWarehouseStock 返回的 prohibited_type 为违禁品类型,非空时告知用户 -- 用户说"第1个""第2个"时,按 searchStock 返回的顺序对应选择 -- 需要上下文但记忆不足时,主动调用 recallHistory 回顾对话历史`; - - // 多轮推理循环 - for (let round = 1; round <= MAX_ROUNDS; round++) { - const contextLines = []; - if (executedFunctions.length > 0) { - contextLines.push('已执行的函数及结果:'); - executedFunctions.forEach((f, i) => { - contextLines.push( - ` ${i + 1}. ${f.name}(${JSON.stringify(f.params)}) → ${JSON.stringify(f.result)}` - ); - }); - } - - const messages = [ - { role: 'system', content: systemPrompt }, - ...history, - ...(contextLines.length > 0 ? [{ role: 'system', content: contextLines.join('\n') }] : []), - { role: 'user', content: round === 1 - ? content - : (executedFunctions.length > 0 - ? `已获取到函数执行结果,请根据结果 reply 告知用户(禁止 silent)。第 ${round}/${MAX_ROUNDS} 轮` - : `请根据已获取的信息,决定下一步:继续调用函数还是给出最终回复。第 ${round}/${MAX_ROUNDS} 轮`), - }, - ]; - - let raw = ''; - try { - raw = await this.callDeepSeek(messages, { maxTokens: 600 }); - ctx.logger.info(`[inbox functions] 第 ${round}/${MAX_ROUNDS} 轮: ${raw}`); - - const result = JSON.parse(raw); - - // 记录思考过程 - thoughts.push({ - round, - action: result.action || 'unknown', - function: result.function || null, - params: result.params || null, - reason: result.reason || null, - }); - - if (result.action === 'reply') { - finalReply = String(result.reply || '').trim(); - if (!finalReply) finalReply = '已处理完成'; - break; - } - - if (result.action === 'silent') { - // 已调用过操作类函数(非 recallHistory)→ 必须回复结果,不能 silent - const actionFunctions = executedFunctions.filter(f => f.name !== 'recallHistory'); - if (actionFunctions.length > 0) { - ctx.logger.info('[inbox functions] 已有操作类函数调用,忽略 silent 继续要求回复'); - continue; - } - ctx.logger.info('[inbox functions] AI 判定无需回复,跳过回执'); - return { reply: null, functionName: null, functionResult: null, thoughts, skip: true }; - } - - if (result.action === 'call' && result.function) { - const fnName = String(result.function).trim(); - const params = result.params || {}; - - if (fnName === 'none' || fnName === 'stop') { - finalReply = result.reply || '已处理完成'; - break; - } - - lastFunctionName = fnName; - lastFunctionResult = await this.callFunction(fnName, params); - executedFunctions.push({ name: fnName, params, result: lastFunctionResult }); - - // 补充函数执行结果到思考记录 - const lastThought = thoughts[thoughts.length - 1]; - if (lastThought) lastThought.functionResult = lastFunctionResult; - ctx.logger.info(`[inbox functions] 执行 ${fnName}: ${JSON.stringify(lastFunctionResult)}`); - - // 最后一轮强制输出 - if (round === MAX_ROUNDS) { - finalReply = lastFunctionResult?.data?.message - || lastFunctionResult?.data?.greeting - || JSON.stringify(lastFunctionResult?.data || lastFunctionResult); - } - continue; - } - - // 无法解析 → 尝试提取 reply - finalReply = result.reply || result.message || '抱歉,暂时无法处理您的请求'; - break; - } catch (error) { - ctx.logger.warn(`[inbox functions] 第 ${round} 轮异常: ${error.message}, raw: ${raw}`); - - // 不是 JSON → 当作文本回复 - if (error instanceof SyntaxError && raw) { - finalReply = raw; - break; - } - - // 最后一轮兜底 - if (round === MAX_ROUNDS) { - finalReply = '抱歉,暂时无法处理您的请求,请稍后重试'; - } - continue; - } - } - - // 无回复的兜底 - if (!finalReply && lastFunctionResult) { - finalReply = lastFunctionResult?.data?.message - || lastFunctionResult?.data?.greeting - || (lastFunctionResult?.success !== false ? '操作已完成' : lastFunctionResult?.error || '处理完成'); - } - if (!finalReply) { - finalReply = '抱歉,暂时无法处理您的请求'; - } - - ctx.logger.info(`[inbox functions] 最终回复: ${finalReply}`); - return { - reply: finalReply, - functionName: lastFunctionName, - functionResult: lastFunctionResult, - thoughts, - }; - } } module.exports = InboxFunctionsService; diff --git a/app/service/inbox/groups.js b/app/service/inbox/groups.js new file mode 100644 index 0000000..e6f7977 --- /dev/null +++ b/app/service/inbox/groups.js @@ -0,0 +1,224 @@ +'use strict'; + +const Service = require('egg').Service; + +/** + * ## 群类型统一定义(唯一数据源) + * + * 所有 AI 函数分组常量(GROUP)、合法子类型映射(VALID_SUB_TYPES)、 + * 通配展开(WILDCARD_EXPAND)均由此结构自动派生,修改群类型只需维护此处。 + * + * @constant {Array<{type: string, label: string, mainGroup: string, wildcardGroup: string|null, subTypes: Array<{key: string, label: string}>}>} + */ +const GROUP_TYPES = [ + { + type: 'store', + label: '货主群', + mainGroup: 'bound:store', + wildcardGroup: 'bound:store:*', + subTypes: [ + { key: 'after_sales', label: '售后' }, + { key: 'finance', label: '财务' }, + { key: 'receiving', label: '收货' }, + ], + }, + { + type: 'warehouse', + label: '仓库群', + mainGroup: 'bound:warehouse', + wildcardGroup: null, + subTypes: [ + { key: 'receiving', label: '收货' }, + { key: 'production', label: '生产' }, + { key: 'stockout', label: '出库' }, + { key: 'finance', label: '财务' }, + { key: 'all', label: '全体' }, + { key: 'customer_service', label: '客服' }, + { key: 'exception', label: '异常' }, + ], + }, + { + type: 'express', + label: '快递群', + mainGroup: 'bound:express', + wildcardGroup: null, + subTypes: [ + { key: 'pickup', label: '揽收' }, + { key: 'after_sales', label: '售后' }, + ], + }, +]; + +// ========== 以下均为 GROUP_TYPES 的派生值,禁止手动修改 ========== + +/** + * AI 函数分组常量,由 {@link GROUP_TYPES} 自动生成。 + * @constant {Record} + */ +const GROUP = (() => { + const map = { COMMON: 'common' }; + for (const gt of GROUP_TYPES) { + const prefix = gt.mainGroup.split(':').pop(); + const upper = prefix.toUpperCase(); + map[`BOUND_${upper}`] = gt.mainGroup; + if (gt.wildcardGroup) { + map[`BOUND_${upper}_WILDCARD`] = gt.wildcardGroup; + } + for (const st of gt.subTypes) { + map[`BOUND_${upper}_${st.key.toUpperCase()}`] = `${gt.mainGroup}:${st.key}`; + } + } + return Object.freeze(map); +})(); + +/** + * 各群类型下合法的子类型 key → GROUP 常量映射,由 {@link GROUP_TYPES} 自动生成。 + * @constant {Record>} + */ +const VALID_SUB_TYPES = (() => { + const map = {}; + for (const gt of GROUP_TYPES) { + if (gt.subTypes.length === 0) continue; + const sub = {}; + for (const st of gt.subTypes) { + const prefix = gt.mainGroup.split(':').pop().toUpperCase(); + sub[st.key] = GROUP[`BOUND_${prefix}_${st.key.toUpperCase()}`]; + } + map[gt.type] = sub; + } + return Object.freeze(map); +})(); + +/** + * 通配展开映射,由 {@link GROUP_TYPES} 自动生成。 + * @constant {Record} + */ +const WILDCARD_EXPAND = (() => { + const map = {}; + for (const gt of GROUP_TYPES) { + if (!gt.wildcardGroup) continue; + const prefix = gt.mainGroup.split(':').pop().toUpperCase(); + const list = [ GROUP[`BOUND_${prefix}`] ]; + for (const st of gt.subTypes) { + list.push(GROUP[`BOUND_${prefix}_${st.key.toUpperCase()}`]); + } + map[gt.wildcardGroup] = list; + } + return Object.freeze(map); +})(); + +/** + * 群分组匹配服务。 + * 负责根据当前上下文解析可用分组、判断函数可见性、构建函数列表。 + * 纯策略/匹配逻辑,不涉及函数注册与执行。 + */ +class InboxGroupsService extends Service { + + /** + * 根据当前上下文解析可用分组集合。 + * + * - 始终包含 `common`(通用分组)。 + * - 根据 `groupType` + `subType` 查询 VALID_SUB_TYPES 激活对应的子分组。 + * - 只有 VALID_SUB_TYPES 中声明的 subType 才会生效,防止越界激活。 + * + * @param {Object} [opts] 可选覆盖参数。 + * @param {string} [opts.groupType] 群类型(store / warehouse / express)。 + * @param {string} [opts.subType] 子类型。 + * @return {string[]} 当前上下文中可用的分组列表。 + */ + resolveActiveGroups(opts = {}) { + const { ctx } = this; + const groups = [ GROUP.COMMON ]; + + const groupType = String( + opts.groupType || ctx.inboxContext?.group_type || '' + ).trim(); + const subType = String( + opts.subType || ctx.inboxContext?.sub_type || '' + ).trim(); + const storeId = Number(ctx.inboxContext?.store_id || 0); + + const gtDef = GROUP_TYPES.find(gt => gt.type === groupType); + if (gtDef && (groupType === 'express' || storeId > 0)) { + groups.push(gtDef.mainGroup); + const subMap = VALID_SUB_TYPES[groupType]; + if (subMap && subMap[subType]) { + groups.push(subMap[subType]); + } + } + + return groups; + } + + /** + * 判断某个函数在当前活跃分组集合中是否可用。 + * + * @param {Object} def 函数定义对象(含 `groups` 字段)。 + * @param {string[]} activeGroups 当前上下文的活跃分组列表。 + * @return {boolean} 该函数在当前分组中是否可用。 + */ + isFunctionAvailable(def, activeGroups) { + if (!Array.isArray(def.groups) || def.groups.length === 0) return true; + + const expanded = []; + for (const g of def.groups) { + if (WILDCARD_EXPAND[g]) { + expanded.push(...WILDCARD_EXPAND[g]); + } else { + expanded.push(g); + } + } + + return expanded.some(g => g === GROUP.COMMON || activeGroups.includes(g)); + } + + /** + * 获取指定分组下的函数列表。 + * + * @param {string[]} [activeGroups] 活跃分组列表,不传则返回全部已注册函数。 + * @return {Array<{name: string, description: string, params: Object}>} 函数列表。 + */ + getFunctionList(activeGroups) { + const { ctx } = this; + const funcSvc = ctx.service.inbox.functions; + const list = []; + for (const [ name, def ] of funcSvc.registry) { + if (activeGroups && !this.isFunctionAvailable(def, activeGroups)) continue; + list.push({ + name, + description: def.description, + params: def.params, + }); + } + return list; + } + + /** + * 构建函数列表的文本描述,供 AI prompt 使用。 + * + * @param {string[]} [activeGroups] 活跃分组列表,不传则返回全部。 + * @return {string} 函数列表文本。 + */ + buildFunctionListText(activeGroups) { + const { ctx } = this; + const funcSvc = ctx.service.inbox.functions; + const lines = []; + for (const [ name, def ] of funcSvc.registry) { + if (activeGroups && !this.isFunctionAvailable(def, activeGroups)) continue; + const paramEntries = Object.entries(def.params); + const paramStr = paramEntries.length > 0 + ? paramEntries.map(([ k, v ]) => `${k}(${v.type || 'string'}, ${v.required ? '必填' : '可选'}): ${v.description}`).join(', ') + : '无参数'; + const weightStr = def.weight ? ` [权重:${def.weight}]` : ''; + const keywordStr = def.keywords && def.keywords.length > 0 + ? ` [触发词:${def.keywords.join(',')}]` + : ''; + lines.push(`- ${name}${weightStr}${keywordStr}: ${def.description}。参数: ${paramStr}`); + } + return lines.join('\n'); + } +} + +module.exports = InboxGroupsService; +module.exports.GROUP_TYPES = GROUP_TYPES; +module.exports.GROUP = GROUP; diff --git a/app/service/inbox/processor.js b/app/service/inbox/processor.js index 6b6fd0d..152d2b1 100644 --- a/app/service/inbox/processor.js +++ b/app/service/inbox/processor.js @@ -3,7 +3,6 @@ const Service = require('egg').Service; const WAREHOUSE_INTERFACE_TYPE_ID = 3; -const CALLBACK_TIMEOUT_MS = 10000; // 回执超时 10s /** * 站内信内容处理器。 @@ -11,6 +10,69 @@ const CALLBACK_TIMEOUT_MS = 10000; // 回执超时 10s * 将 warehouse_id 和 store_id 挂载到 ctx 上下文供下游使用。 */ class InboxProcessorService extends Service { + + constructor(ctx) { + super(ctx); + /** + * 群信息缓存(groupId:warehouseId → { group_type, sub_type, ai_enabled, ext_data })。 + * 生命周期跟随进程,写回 ext_data 时清除对应条目。 + */ + this._groupCache = new Map(); + } + + /** + * 从缓存或 DB 拉取群信息。若群 ext_data 为空且消息携带 ext_data,自动写回并清缓存。 + * @param {string} groupId 外部群ID + * @param {number} warehouseId 仓库ID + * @param {Object|null} msgExtData 入站消息的 ext_data + * @return {Promise<{group_type: string, sub_type: string, ai_enabled: number, ext_data: Object|null}>} + */ + async _loadGroupInfo(groupId, warehouseId, msgExtData) { + const { ctx } = this; + const cacheKey = `${groupId}:${warehouseId}`; + + // 命中缓存直接返回 + const cached = this._groupCache.get(cacheKey); + if (cached) return cached; + + let group = null; + try { + group = await ctx.model.InboxGroup.findOne({ + attributes: [ 'group_type', 'sub_type', 'ai_enabled', 'ext_data' ], + where: { group_id: groupId, warehouse_id: warehouseId }, + raw: true, + }); + } catch (e) { + ctx.logger.warn(`[inbox processor] 查询群分组信息失败: ${e.message}`); + } + + const info = { + group_type: (group && group.group_type) || '', + sub_type: (group && group.sub_type) || '', + ai_enabled: group ? group.ai_enabled : 0, + ext_data: (group && group.ext_data) || null, + }; + + // 群存在但 ext_data 为空,且入站消息带有 ext_data → 写回群配置 + if (group && !info.ext_data && msgExtData && typeof msgExtData === 'object' && Object.keys(msgExtData).length > 0) { + try { + await ctx.model.InboxGroup.update( + { ext_data: msgExtData }, + { where: { group_id: groupId, warehouse_id: warehouseId } } + ); + info.ext_data = msgExtData; + ctx.logger.info(`[inbox processor] 群 ext_data 写回成功: ${groupId}`); + } catch (e) { + ctx.logger.warn(`[inbox processor] 群 ext_data 写回失败: ${e.message}`); + // 写回失败不阻塞,直接返回 info(ext_data 仍为空) + return info; + } + } + + // 写入缓存 + this._groupCache.set(cacheKey, info); + return info; + } /** * 处理入站消息内容。 * 解析 content 后将 warehouse_id 和 store_id 写入 ctx 上下文。 @@ -88,8 +150,6 @@ class InboxProcessorService extends Service { const warehouseId = Number(data.warehouse_id) || 0; const extId = String(data.ext_id || ''); const parentId = Number(data.parent_id) || null; - let ackExtId = ''; - let callbackConfig = { url: null, appKey: null, appSecret: null }; try { // 1. 处理消息正文,挂载上下文 @@ -106,24 +166,16 @@ class InboxProcessorService extends Service { const bindHandled = await this.tryBindGroup(data); if (bindHandled) return; - // 4. 加载群的 group_type / sub_type / ai_enabled + // 4. 加载群的 group_type / sub_type / ai_enabled / ext_data(带缓存 + 自动写回) if (ctx.inboxContext.ai_enabled === undefined) { - try { - const groupId = String(ctx.inboxContext.group_id || '').trim(); - if (groupId) { - const group = await ctx.model.InboxGroup.findOne({ - attributes: [ 'group_type', 'sub_type', 'ai_enabled' ], - where: { group_id: groupId, warehouse_id: warehouseId }, - raw: true, - }); - ctx.inboxContext.group_type = (group && group.group_type) || ''; - ctx.inboxContext.sub_type = (group && group.sub_type) || ''; - ctx.inboxContext.ai_enabled = group ? group.ai_enabled : 0; - } else { - ctx.inboxContext.ai_enabled = 0; - } - } catch (e) { - ctx.logger.warn(`[inbox processor] 查询群分组信息失败: ${e.message}`); + const groupId = String(ctx.inboxContext.group_id || '').trim(); + if (groupId) { + const info = await this._loadGroupInfo(groupId, warehouseId, data.ext_data || null); + ctx.inboxContext.group_type = info.group_type; + ctx.inboxContext.sub_type = info.sub_type; + ctx.inboxContext.ai_enabled = info.ai_enabled; + ctx.inboxContext.group_ext_data = info.ext_data; + } else { ctx.inboxContext.ai_enabled = 0; } } @@ -136,6 +188,7 @@ class InboxProcessorService extends Service { } // 5. 群未启用AI → 跳过(ai_enabled != 1 一律跳过,安全默认) + // 快递群默认 ai_enabled=0,需手动开启后才会走 AI 处理 if (ctx.inboxContext.ai_enabled !== 1) { ctx.logger.info(`[inbox processor] 群未启用AI自动回复,跳过 AI ext_id=${extId}`); return; @@ -158,8 +211,11 @@ class InboxProcessorService extends Service { } } + // 5.2 注入入站消息ID,供下游函数(如 interceptWaybill)关联工单 + ctx.inboxContext.inbound_message_id = parentId || null; + // 6. DeepSeek 两步交互(AI 内部自行判断真人接管) - const aiResult = await ctx.service.inbox.functions.processWithAI({ + const aiResult = await ctx.service.inbox.ai.processWithAI({ content: data.content || '', ext_data: data.ext_data || null, parentId: data.parent_id || null, @@ -189,182 +245,37 @@ class InboxProcessorService extends Service { `function=${aiResult.functionName || 'direct'} reply_length=${replyContent.length}` ); - // 7. 写入 outbound 回执记录 - ackExtId = `sys:ack:${extId}`; - - let outboundId = null; - try { - const existAck = await InboxMessage.findOne({ - where: { ext_id: ackExtId }, - attributes: [ 'id' ], - paranoid: false, - }); - - if (existAck) { - outboundId = existAck.id; - } else { - const created = await InboxMessage.create({ - ext_id: ackExtId, - warehouse_id: warehouseId, - store_id: data.store_id || null, - direction: 'outbound', - parent_id: parentId, - source_type: 'system', - source_extra: null, - target_type: 'api', - group_id: ctx.inboxContext?.group_id || data.group_id || null, - user_id: ctx.inboxContext?.user_id || data.user_id || null, - group_name: ctx.inboxContext?.group_name || data.group_name || null, - user_name: ctx.inboxContext?.user_name || data.user_name || null, - content: replyContent, - ext_data: data.ext_data || null, - ai_thoughts: aiResult.thoughts || null, - flags: {}, - }); - outboundId = created.id; - - ctx.logger.info(`[inbox processor] 回执记录写入成功 parent_id=${parentId}`); + // 7. AI 推理写入入站消息(便于排查) + if (aiResult.thoughts && aiResult.thoughts.length > 0) { + try { + await InboxMessage.update( + { ai_thoughts: aiResult.thoughts }, + { where: { ext_id: extId } } + ); + } catch (e) { + ctx.logger.warn(`[inbox processor] 保存 AI 思考记录失败: ${e.message}`); } - } catch (writeError) { - ctx.logger.warn(`[inbox processor] 回执记录写入失败: ${writeError.message}`); } - // 8. 查回调地址并发送(带 MD5 签名) - callbackConfig = await this.getApiAppCallbackConfig(warehouseId); - const callbackUrl = callbackConfig.url; - if (!callbackUrl) { - ctx.logger.info(`[inbox processor] 仓库 ${warehouseId} 未配置回调地址,跳过回执 ext_id=${extId}`); + // 8. 快递群:仅执行函数,不回信 + if (groupType === 'express') { + ctx.logger.info(`[inbox processor] 快递群AI处理完成(不回信) ext_id=${extId}`); return; } - const crypto = require('crypto'); - const method = 'notify.reply'; - const notifyBody = { - code: 200, - data: { - type: 'ai', - content: replyContent, - ext_data: data.ext_data || null, - ext_id: String(outboundId || ''), - group_id: ctx.inboxContext?.group_id || data.group_id || '', - user_id: ctx.inboxContext?.user_id || data.user_id || '', - group_name: ctx.inboxContext?.group_name || data.group_name || '', - user_name: ctx.inboxContext?.user_name || data.user_name || '', - timestamp: Math.floor(Date.now() / 1000), - }, - }; - - const bodyJson = JSON.stringify(notifyBody); - const timestamp = Math.floor(Date.now() / 1000); - const appKey = callbackConfig.appKey || ''; - const appSecret = callbackConfig.appSecret || ''; - - const sign = appSecret - ? crypto.createHash('md5').update(appSecret + timestamp + bodyJson).digest('hex') - : ''; - - const urlWithSign = `${callbackUrl}?app_key=${encodeURIComponent(appKey)}&method=${encodeURIComponent(method)}×tamp=${timestamp}&sign=${encodeURIComponent(sign)}`; - - ctx.logger.info(`[inbox processor] 发送 API 回执 ext_id=${extId} url=${callbackUrl}`); - - const response = await ctx.curl(urlWithSign, { - method: 'POST', - dataType: 'json', - contentType: 'json', - data: notifyBody, - headers: { 'Content-Type': 'application/json' }, - timeout: CALLBACK_TIMEOUT_MS, - }); - - // 记录出站通知日志到 wms_warehouse_log - try { - const { WarehouseLog } = ctx.model; - await WarehouseLog.create({ - log_id: 'WN-' + Date.now() + '-' + crypto.randomBytes(3).toString('hex'), - app_key: appKey || null, - method, - warehouse_id: warehouseId || null, - url: urlWithSign || null, - http_status: response ? response.status : null, - body: JSON.stringify(notifyBody).substring(0, 65535), - result: response ? JSON.stringify(response.data || {}).substring(0, 65535) : '', - use_time: null, - created_at: new Date(), - }); - } catch (logErr) { - ctx.logger.error('[notify-log] 日志写入失败: ' + logErr.message); - } - - ctx.logger.info( - `[inbox processor] API 回执完成 ext_id=${extId} ` + - `http_status=${response.status}` - ); - - // 更新出站+入站推送状态 - if (response && response.status === 200 - && (!response.data || response.data.code === undefined || response.data.code === 200)) { - await InboxMessage.update( - { - push_status: 2, - push_response: { http_status: response.status, body: response.data || null }, - pushed_at: ctx.app.Sequelize.literal('CURRENT_TIMESTAMP'), - }, - { where: { ext_id: ackExtId } } - ); - if (parentId) { - await InboxMessage.update( - { - push_status: 2, - pushed_at: ctx.app.Sequelize.literal('CURRENT_TIMESTAMP'), - }, - { where: { id: parentId } } - ); - } - } else { - await InboxMessage.update( - { - push_status: 3, - push_response: { http_status: response ? response.status : null, body: response ? response.data : null }, - }, - { where: { ext_id: ackExtId } } - ); - } + // 9. 统一回信 + await this.writeOutboundReply({ + warehouse_id: warehouseId, + ext_id: extId, + parent_id: parentId, + ext_data: data.ext_data || null, + group_id: ctx.inboxContext?.group_id || data.group_id || null, + user_id: ctx.inboxContext?.user_id || data.user_id || null, + group_name: ctx.inboxContext?.group_name || data.group_name || null, + user_name: ctx.inboxContext?.user_name || data.user_name || null, + }, replyContent); } catch (error) { - ctx.logger.error( - `[inbox processor] API 回执失败 ext_id=${extId}: ${error.message}` - ); - - // 更新推送状态为失败 - try { - await InboxMessage.update( - { - push_status: 3, - push_response: { error: error.message }, - }, - { where: { ext_id: ackExtId } } - ); - } catch (updateErr) { - ctx.logger.error('[inbox processor] 更新推送状态失败: ' + updateErr.message); - } - - // 记录失败日志到 warehouse_log - try { - const { WarehouseLog } = ctx.model; - const crypto = require('crypto'); - await WarehouseLog.create({ - log_id: 'WN-' + Date.now() + '-' + crypto.randomBytes(3).toString('hex'), - app_key: callbackConfig.appKey || null, - method: 'notify.reply', - warehouse_id: warehouseId || null, - url: callbackConfig.url || null, - http_status: null, - body: '', result: 'Error: ' + error.message, - use_time: null, - created_at: new Date(), - }); - } catch (logErr) { - ctx.logger.error('[notify-log] 失败日志写入异常: ' + logErr.message); - } + ctx.logger.warn(`[inbox processor] API 回执失败 ext_id=${extId}: ${error.message}`); } } @@ -470,7 +381,8 @@ class InboxProcessorService extends Service { * @param {string} data.group_name 群名称(必填)。 * @param {string} data.user_name 用户名称(必填)。 * @param {string} replyContent 回复内容。 - * @param {string} [source='ai_reply'] 回调 source 类型:ai_reply / bind_confirm / balance / error。 + * @param {string} [source='ai_reply'] 回调 source 类型:ai_reply / bind_confirm / balance / error / system。 + * system 类型不要求 user_id/user_name。 * @return {Promise} */ async writeOutboundReply(data, replyContent, source = 'ai_reply') { @@ -480,18 +392,19 @@ class InboxProcessorService extends Service { const warehouseId = Number(data.warehouse_id || 0); const extId = String(data.ext_id || ''); const parentId = Number(data.parent_id || 0); + const isSystem = source === 'system'; - // 强制入参校验 + // 强制入参校验(system 类型不要求 user_id/user_name) const groupId = String(data.group_id || ctx.inboxContext?.group_id || '').trim(); const userId = String(data.user_id || ctx.inboxContext?.user_id || '').trim(); const groupName = String(data.group_name || ctx.inboxContext?.group_name || '').trim(); const userName = String(data.user_name || ctx.inboxContext?.user_name || '').trim(); - if (!groupId || !userId || !groupName || !userName) { - throw new Error( - `回执缺少必填字段: group_id=${groupId || '?'}, user_id=${userId || '?'}, ` + - `group_name=${groupName || '?'}, user_name=${userName || '?'}` - ); + if (!groupId || !groupName) { + throw new Error(`回执缺少必填字段: group_id=${groupId || '?'}, group_name=${groupName || '?'}`); + } + if (!isSystem && (!userId || !userName)) { + throw new Error(`回执缺少必填字段: user_id=${userId || '?'}, user_name=${userName || '?'}`); } const ackExtId = `sys:ack:${extId}`; @@ -511,9 +424,9 @@ class InboxProcessorService extends Service { source_type: 'system', source_extra: null, target_type: 'api', group_id: groupId, - user_id: userId, + user_id: isSystem ? null : userId, group_name: groupName, - user_name: userName, + user_name: isSystem ? null : userName, content: replyContent, ext_data: data.ext_data || null, flags: {}, }); @@ -527,14 +440,13 @@ class InboxProcessorService extends Service { const notifyBody = { code: 200, data: { - type: source === 'ai_reply' ? 'ai' : source === 'bind_confirm' ? 'bind' : source === 'balance' ? 'balance' : 'error', + type: isSystem ? 'system' : source === 'ai_reply' ? 'ai' : source === 'bind_confirm' ? 'bind' : source === 'balance' ? 'balance' : 'error', content: replyContent, ext_data: data.ext_data || null, ext_id: String(outboundId), group_id: groupId, - user_id: userId, + ...(isSystem ? {} : { user_id: userId, user_name: userName }), group_name: groupName, - user_name: userName, timestamp: Math.floor(Date.now() / 1000), }, }; @@ -767,6 +679,45 @@ class InboxProcessorService extends Service { return config.url; } + /** + * 系统通知异步推送:仅 POST 回调,不写 inbox_message。 + * @param {Object} data 通知数据。 + * @param {number} data.warehouse_id 仓库ID。 + * @param {string} data.group_id 目标群ID。 + * @param {string} data.group_name 目标群名称。 + * @param {string} data.content 通知内容。 + * @param {Object} [data.ext_data] 群扩展数据(渠道信息)。 + */ + pushSystemNotification(data = {}) { + const { ctx } = this; + const warehouseId = Number(data.warehouse_id); + const groupId = String(data.group_id || '').trim(); + const groupName = String(data.group_name || '').trim(); + const content = String(data.content || '').trim(); + const extData = data.ext_data || null; + + if (!warehouseId || !groupId || !content) return; + + // 构造 data 对象,复用 writeOutboundReply + const replyData = { + warehouse_id: warehouseId, + ext_id: `sys:notify:${warehouseId}:${groupId}:${Date.now()}:${Math.random().toString(36).slice(2, 8)}`, + parent_id: null, + ext_data: extData, + group_id: groupId, + user_id: '', + group_name: groupName, + user_name: '', + }; + + // 写库 + POST,异步不阻塞 + setImmediate(() => { + this.writeOutboundReply(replyData, content, 'system').catch(err => { + ctx.logger.warn(`[pushNotify] 推送异常 group=${groupName}: ${err.message}`); + }); + }); + } + /** * 尝试从消息正文中提取仓库ID。 * 子类或业务方可覆盖此方法以实现自定义解析逻辑。 diff --git a/app/service/openapiMethods/order.js b/app/service/openapiMethods/order.js index 6c6764b..50c55e4 100644 --- a/app/service/openapiMethods/order.js +++ b/app/service/openapiMethods/order.js @@ -61,7 +61,41 @@ class OpenapiOrderService extends MainService { transaction, }); + // 同步更新运单表拦截标记 + try { + const { ctx } = this; + const warehouseId = ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : 0; + if (warehouseId > 0) { + await ctx.model.OrderExpress.update( + { is_intercept: 'Y' }, + { where: { order_id: existingOrder.id, warehouse_id: warehouseId }, transaction } + ); + } + } catch (expressErr) { + this.ctx.logger.warn( + `[openapi order cancel] 更新运单拦截标记失败, orderId=${existingOrder.id}, error=${expressErr.message}` + ); + } + await transaction.commit(); + + // 创建售后工单 + 通知快递群(失败不影响主流程) + try { + const { ctx } = this; + const whId = ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : 0; + if (whId > 0) { + await ctx.service.systems.afterSale.createInterceptWorkOrdersAndNotify({ + orderIds: [ existingOrder.id ], + warehouseId: whId, + creatorLabel: ctx.user?.employees_name || 'OpenAPI系统', + }); + } + } catch (workOrderErr) { + this.ctx.logger.warn( + `[openapi order cancel] 创建工单/通知失败, orderId=${existingOrder.id}, error=${workOrderErr.message}` + ); + } + return this.fail('取消失败,已通知拦截执行'); } diff --git a/app/service/qimenMethods/order.js b/app/service/qimenMethods/order.js index a949a49..a390248 100644 --- a/app/service/qimenMethods/order.js +++ b/app/service/qimenMethods/order.js @@ -194,7 +194,33 @@ class orderServer extends MainService { transaction, }); + // 同步更新运单表拦截标记 + try { + await ctx.model.OrderExpress.update( + { is_intercept: 'Y' }, + { where: { order_id: existingOrder.id, warehouse_id: info.warehouseId }, transaction } + ); + } catch (expressErr) { + ctx.logger.warn( + `[qimen order cancel] 更新运单拦截标记失败, orderId=${existingOrder.id}, error=${expressErr.message}` + ); + } + await transaction.commit(); + + // 创建售后工单 + 通知快递群(失败不影响主流程) + try { + await ctx.service.systems.afterSale.createInterceptWorkOrdersAndNotify({ + orderIds: [ existingOrder.id ], + warehouseId: info.warehouseId, + creatorLabel: ctx.user?.employees_name || '奇门系统', + }); + } catch (workOrderErr) { + ctx.logger.warn( + `[qimen order cancel] 创建工单/通知失败, orderId=${existingOrder.id}, error=${workOrderErr.message}` + ); + } + await this.sendCancelInterceptNotice({ orderCode, existingOrder, diff --git a/app/service/systemMethods/afterSale.js b/app/service/systemMethods/afterSale.js index 78e9b43..a9ddb13 100644 --- a/app/service/systemMethods/afterSale.js +++ b/app/service/systemMethods/afterSale.js @@ -16,9 +16,10 @@ const BLOCK_PERMISSION_ROLE_GROUP_MAP = Object.freeze({ }); /** - * 售后模块工作列表排除的状态(已完成/已取消)。 + * 售后模块工作列表排除的终态(已完成/已关闭/已取消)。 + * pending_feedback 不在静态排除列表中,由 workList 根据 followup_at 动态判断。 */ -const WORK_LIST_EXCLUDED_STATUSES = Object.freeze([ 'completed', 'cancelled' ]); +const WORK_LIST_EXCLUDED_STATUSES = Object.freeze([ 'completed', 'closed', 'cancelled' ]); /** * 系统方法层:afterSale(售后模块接口包装层)。 @@ -29,9 +30,9 @@ class AfterSaleMethodService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'workList,auditList,detail,create,transfer,handleWorkOrder,registerClaim,export,exportTaskProgress'; - const _noNeedLog = 'workList,auditList,detail,export,exportTaskProgress'; - const _noNeedAuth = 'workList,auditList,detail,create,transfer,handleWorkOrder,registerClaim,export,exportTaskProgress'; + const _noNeedRight = 'workList,auditList,detail,create,transfer,handleWorkOrder,batchSetPendingFeedback,batchClose,registerClaim,export,exportTaskProgress,workCount'; + const _noNeedLog = 'workList,auditList,detail,export,exportTaskProgress,workCount'; + const _noNeedAuth = 'workList,auditList,detail,create,transfer,handleWorkOrder,batchSetPendingFeedback,batchClose,registerClaim,export,exportTaskProgress,workCount'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -62,7 +63,7 @@ class AfterSaleMethodService extends MainService { }); // 提取当前用户的售后 block 权限 → role_group 列表 - const allowedRoleGroups = this._resolveAfterSaleBlockRoleGroups(); + const allowedRoleGroups = await this._resolveAfterSaleBlockRoleGroups(); // 强制过滤:仅展示当前用户可处理的 role_group,且排除已完成/已取消 const enforcedWhere = { @@ -77,37 +78,112 @@ class AfterSaleMethodService extends MainService { }, }; - const result = await service.systems.afterSale.list(enforcedWhere, pagination, sort); + const result = await service.systems.afterSale.list(enforcedWhere, pagination, sort, { + order: [[ 'priority', 'DESC' ], [ 'updated_at', 'DESC' ]], + excludeFutureFollowup: true, + }); return this.success('ok', result); } /** * 解析当前用户所拥有的售后 block 权限对应的 role_group 列表。 - * 从 ctx.user.role.permissions 中筛选 type=block 且 ID 为 516/517/518 的权限项。 + * 从 wms_role.permissions 中查询当前激活角色的原始权限 ID, + * 若 permissions='*' 则返回全部 role_group,否则筛选 516/517/518。 * - * @return {string[]} 当前用户可处理的 role_group 列表 + * @return {Promise} 当前用户可处理的 role_group 列表 */ - _resolveAfterSaleBlockRoleGroups() { + async _resolveAfterSaleBlockRoleGroups() { const { ctx } = this; - const rolePermissions = ctx.user && ctx.user.role && Array.isArray(ctx.user.role.permissions) - ? ctx.user.role.permissions - : []; - - const allowedRoleGroups = []; - for (const perm of rolePermissions) { - const permId = Number(perm && (perm.id || perm.permission_id || 0)); - const permType = String(perm && (perm.type || '')).trim(); - if (permType === 'block' && BLOCK_PERMISSION_ROLE_GROUP_MAP[permId]) { - allowedRoleGroups.push(BLOCK_PERMISSION_ROLE_GROUP_MAP[permId]); - } - } - - // 如果未匹配到任何售后 block 权限,默认不给任何 role_group 可见范围 - if (allowedRoleGroups.length === 0) { + const employeeId = ctx.user && ctx.user.employees_id; + if (!employeeId) { return [ '__none__' ]; } - return allowedRoleGroups; + try { + // 1. 通过 EmployeeRole 找到 role_id + const employeeRole = await ctx.model.EmployeeRole.findOne({ + where: { employee_id: employeeId }, + attributes: [ 'role_id' ], + raw: true, + }); + if (!employeeRole || !employeeRole.role_id) { + return [ '__none__' ]; + } + + // 2. 读取 wms_role.permissions + const role = await ctx.model.Role.findOne({ + where: { id: employeeRole.role_id, status: 1 }, + attributes: [ 'permissions' ], + raw: true, + }); + if (!role) { + return [ '__none__' ]; + } + + // 3. 标准化解析 + const state = ctx.service.systems.auth.rolePermission.normalizePermissionSet(role.permissions); + + // 超级管理员 → 全部 role_group + if (state.allAccess) { + return [ 'customer_service', 'warehouse', 'finance' ]; + } + + // 匹配 block 权限 516/517/518 + const allowedRoleGroups = []; + for (const permId of state.permissionIds) { + if (BLOCK_PERMISSION_ROLE_GROUP_MAP[permId]) { + allowedRoleGroups.push(BLOCK_PERMISSION_ROLE_GROUP_MAP[permId]); + } + } + + if (allowedRoleGroups.length === 0) { + return [ '__none__' ]; + } + return allowedRoleGroups; + } catch (err) { + ctx.logger.warn(`[_resolveAfterSaleBlockRoleGroups] 权限查询失败: ${err.message}`); + return [ '__none__' ]; + } + } + + // =========================== + // 待处理工单计数(角标用) + // =========================== + + /** + * 快速查询当前用户待处理售后工单数量(用于角标显示)。 + * 过滤逻辑与 workList 一致:role_group 按 block 权限,排除已完成/已取消。 + * 返回 { count: number },前端自行判断 >99 显示 99+。 + * + * @param {Object} data 请求体(可选 where 条件) + * @return {Promise} { count: number } + */ + async workCount(data = {}) { + const { service } = this; + const { where } = this.prepareWhereContext(data, { + specialFieldMap: { + quickWhere: { + bucket: 'quick', + }, + }, + }); + + // 与 workList 一致的角色组 + 状态过滤 + const allowedRoleGroups = await this._resolveAfterSaleBlockRoleGroups(); + const enforcedWhere = { + ...where, + role_group: { + operator: 'in', + value: allowedRoleGroups, + }, + status: { + operator: 'notin', + value: WORK_LIST_EXCLUDED_STATUSES, + }, + }; + + const result = await service.systems.afterSale.countPending(enforcedWhere, { excludeFutureFollowup: true }); + return this.success('ok', { count: result.count }); } // =========================== @@ -177,7 +253,7 @@ class AfterSaleMethodService extends MainService { * @param {string} [data.description] 售后详细描述 * @param {number} [data.priority=0] 优先级 * @param {number} [data.waybill_id] 关联运单ID - * @param {number} [data.order_delivery_id] 关联发货订单ID + * @param {number} [data.order_delivery_id] 关联发货订单ID(兼容别名 order_id) * @param {number} [data.entry_order_id] 关联入库单ID * @param {number} [data.order_stockout_id] 关联出库单ID * @param {number} [data.receiving_id] 关联收货单ID @@ -201,7 +277,8 @@ class AfterSaleMethodService extends MainService { description, priority, waybill_id: waybillId, - order_delivery_id: orderDeliveryId, + order_delivery_id: orderDeliveryIdRaw, + order_id: orderIdRaw, entry_order_id: entryOrderId, order_stockout_id: orderStockoutId, receiving_id: receivingId, @@ -209,6 +286,9 @@ class AfterSaleMethodService extends MainService { inbox_message_id: inboxMessageId, } = data || {}; + // 兼容 order_id 别名(优先 order_delivery_id,为空时取 order_id) + const orderDeliveryId = orderDeliveryIdRaw || orderIdRaw || null; + // 生成售后单号 const afterSaleNo = await this.generateAfterSaleNo(warehouseId); @@ -397,7 +477,6 @@ class AfterSaleMethodService extends MainService { * * @param {Object} data 请求体 * @param {number} data.id 售后单主键ID - * @param {string} data.action 操作动作描述 * @param {string} [data.remark] 处理备注 * @param {string} [data.status] 目标售后状态 * @param {string} [data.resolution] 完结处理结果(status=completed 时写入) @@ -408,7 +487,6 @@ class AfterSaleMethodService extends MainService { const { ctx, service } = this; const { id, - action, remark, status: targetStatus, resolution, @@ -418,9 +496,10 @@ class AfterSaleMethodService extends MainService { if (!id) { return this.fail('缺少售后单ID'); } - if (!action) { - return this.fail('缺少操作动作'); - } + + // status 不填或填错默认 processing;pending 是创建默认值,不适用于处理操作 + const ALLOWED_STATUSES = Object.keys(ctx.model.AfterSale.AFTER_SALE_STATUS).filter(s => s !== 'pending'); + const safeStatus = (targetStatus && ALLOWED_STATUSES.includes(targetStatus)) ? targetStatus : 'processing'; const operatorId = ctx.user ? (ctx.user.id || ctx.user.user_id || 0) : 0; const operatorSnapshot = this._buildOperatorSnapshot(); @@ -428,9 +507,8 @@ class AfterSaleMethodService extends MainService { const result = await service.systems.afterSale.handleWorkOrder({ id: Number(id), - action, remark: remark || null, - targetStatus: targetStatus || null, + targetStatus: safeStatus, resolution: resolution || null, attachmentIds: Array.isArray(attachmentIds) ? attachmentIds : [], operatorId, @@ -441,6 +519,96 @@ class AfterSaleMethodService extends MainService { return this.success('处理成功', result); } + // =========================== + // 批量设为待反馈 + // =========================== + + /** + * 批量将售后工单设为"待反馈"状态,按仓库配置自动计算下次跟进时间。 + * 所有工单在同一事务中处理,任一失败则全部回滚。 + * + * @param {Object} data 请求体 + * @param {number[]} data.ids 售后单主键ID列表 + * @param {string} [data.remark] 统一处理备注(所有工单共用) + * @return {Promise} 统一 success 包装,包含 total/success/failed + */ + async batchSetPendingFeedback(data = {}) { + const { ctx, service } = this; + const { ids, remark } = data || {}; + + if (!Array.isArray(ids) || ids.length === 0) { + return this.fail('ids 不能为空且必须为数组'); + } + + const operatorId = ctx.user ? (ctx.user.id || ctx.user.user_id || 0) : 0; + const operatorSnapshot = this._buildOperatorSnapshot(); + const warehouseId = ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : 0; + + if (!warehouseId) { + return this.fail('无法获取当前仓库上下文'); + } + + const result = await service.systems.afterSale.batchSetPendingFeedback({ + ids, + remark: remark || null, + operatorId, + operatorSnapshot, + warehouseId, + }); + + return this.success('批量设为待反馈完成', result); + } + + // =========================== + // 批量完结/关闭 + // =========================== + + /** + * 批量将售后工单设为完结或关闭状态。 + * completed 时自动写入 resolved_at 并清除 followup_at。 + * 所有工单在同一事务中处理,任一失败则全部回滚。 + * + * @param {Object} data 请求体 + * @param {number[]} data.ids 售后单主键ID列表 + * @param {string} data.status 目标状态:completed | closed + * @param {string} [data.resolution] 完结处理结果(仅 status=completed 时写入) + * @param {string} [data.remark] 统一处理备注(所有工单共用) + * @return {Promise} 统一 success 包装,包含 total/success/failed + */ + async batchClose(data = {}) { + const { ctx, service } = this; + const { ids, status: targetStatus, resolution, remark } = data || {}; + + if (!Array.isArray(ids) || ids.length === 0) { + return this.fail('ids 不能为空且必须为数组'); + } + + const ALLOWED_TARGET_STATUSES = new Set([ 'completed', 'closed' ]); + if (!targetStatus || !ALLOWED_TARGET_STATUSES.has(targetStatus)) { + return this.fail('status 必须为 completed 或 closed'); + } + + const operatorId = ctx.user ? (ctx.user.id || ctx.user.user_id || 0) : 0; + const operatorSnapshot = this._buildOperatorSnapshot(); + const warehouseId = ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : 0; + + if (!warehouseId) { + return this.fail('无法获取当前仓库上下文'); + } + + const result = await service.systems.afterSale.batchClose({ + ids, + status: targetStatus, + resolution: resolution || null, + remark: remark || null, + operatorId, + operatorSnapshot, + warehouseId, + }); + + return this.success('批量操作完成', result); + } + // =========================== // 登记理赔 // =========================== @@ -838,6 +1006,7 @@ class AfterSaleMethodService extends MainService { return null; } } + } module.exports = AfterSaleMethodService; diff --git a/app/service/systemMethods/index.js b/app/service/systemMethods/index.js index 19f4bd7..de7eb76 100644 --- a/app/service/systemMethods/index.js +++ b/app/service/systemMethods/index.js @@ -1287,8 +1287,13 @@ class indexService extends MainService { // 构建嵌套路径 for (let i = 0; i < keys.length - 1; i++) { const key = keys[i]; - if (!current[key]) { + // 如果路径节点已存在但非对象(被其他叶子键占用),先保存旧值再转为对象 + if (!current[key] || typeof current[key] !== 'object') { + const oldValue = current[key]; current[key] = {}; + if (oldValue !== undefined) { + current[key]._self = oldValue; + } } current = current[key]; } diff --git a/app/service/systemMethods/order/deliveryOrder.js b/app/service/systemMethods/order/deliveryOrder.js index c0c59bc..8cc4f92 100644 --- a/app/service/systemMethods/order/deliveryOrder.js +++ b/app/service/systemMethods/order/deliveryOrder.js @@ -1,14 +1,24 @@ 'use strict'; const OrderBaseService = require('./base'); +const fs = require('fs'); +const path = require('path'); + +const DEBUG_LOG = path.join(__dirname, '..', '..', '..', '..', 'temp', 'quickSearch_debug.log'); + +function dbg(msg) { + const ts = new Date().toISOString(); + const line = `[${ts}] ${msg}\n`; + try { fs.appendFileSync(DEBUG_LOG, line, 'utf8'); } catch (_) { /* ignore */ } +} class DeliveryOrderService extends OrderBaseService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'list,deliveryOrder'; - const _noNeedLog = 'list'; - const _noNeedAuth = 'list,deliveryOrder'; + const _noNeedRight = 'list,deliveryOrder,quickSearch'; + const _noNeedLog = 'list,quickSearch'; + const _noNeedAuth = 'list,deliveryOrder,quickSearch'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -50,6 +60,321 @@ class DeliveryOrderService extends OrderBaseService { return await super.detail(detailParams); } + /** + * 订单快速搜索。 + * 跨表联合搜索:运单号(wms_order_express,精确)、发货单号/外部订单号/平台交易单号(dispatch 表,模糊)。 + * 返回匹配的订单列表(最多 20 条),包含订单关键信息及关联运单号。 + * + * @param {Object} data 请求体。 + * @param {string} data.keyword 搜索关键词(必填)。 + * @return {Promise} { list, keyword } + */ + async quickSearch(data = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const requestData = this.isPlainObject(data) ? data : {}; + const keyword = String(requestData.keyword || '').trim(); + const warehouseId = this.getWarehouseId(); + + dbg('========== quickSearch START =========='); + dbg(`keyword="${keyword}" warehouseId=${warehouseId}`); + + if (!keyword) { + dbg('keyword empty → return []'); + return { list: [], keyword: '' }; + } + + if (!warehouseId) { + dbg('warehouseId empty → throw'); + throw new Error('缺少仓库上下文'); + } + + const MAX_RESULTS = 20; + + // 收集匹配的订单 ID(去重) + const matchedOrderIds = new Set(); + + // ====== 第一步:express 表 OR 搜索 ====== + dbg('--- Step1: express OR query ---'); + const expressWhere = { + warehouse_id: warehouseId, + [Op.or]: [ + { waybill_code: keyword }, + { delivery_order_code: { [Op.like]: `%${keyword}%` } }, + { source_order_codes: { [Op.like]: `%${keyword}%` } }, + ], + }; + dbg(`expressWhere: ${JSON.stringify(expressWhere)}`); + + let expressRecords; + try { + expressRecords = await ctx.model.OrderExpress.findAll({ + attributes: [ + 'id', 'order_id', 'waybill_code', 'delivery_order_code', 'source_order_codes', 'store_id', + 'logistics_code', 'logistics_name', + 'logistics_interface_id', 'logistics_interface_name', + 'platform_code', 'status', 'is_back', 'is_intercept', 'is_galaxy_receive', + 'weighing_weight', + ], + where: expressWhere, + raw: true, + limit: MAX_RESULTS, + }); + dbg(`expressRecords count: ${expressRecords.length}`); + } catch (e) { + dbg(`expressRecords ERROR: ${e.message}`); + expressRecords = []; + } + + const waybillMap = new Map(); + for (const er of expressRecords) { + dbg(` er: id=${er.id} order_id=${er.order_id} waybill_code=${er.waybill_code} delivery_order_code=${er.delivery_order_code}`); + if (er.order_id) { + matchedOrderIds.add(er.order_id); + if (!waybillMap.has(er.order_id)) { + waybillMap.set(er.order_id, []); + } + waybillMap.get(er.order_id).push(this.buildWaybillItem(er)); + } + } + dbg(`matchedOrderIds: [${[ ...matchedOrderIds ].join(',')}]`); + dbg(`waybillMap keys: [${[ ...waybillMap.keys() ].join(',')}]`); + + if (matchedOrderIds.size === 0) { + dbg('matchedOrderIds empty → return []'); + return { list: [], keyword }; + } + + // ====== 第二步:订单表 IN 查详情 ====== + const orderIds = [ ...matchedOrderIds ].slice(0, MAX_RESULTS); + const orderMap = new Map(); + dbg(`--- Step2: order detail IN query, orderIds=[${orderIds.join(',')}] ---`); + + if (orderIds.length > 0) { + const factory = ctx.model && ctx.model.OrderDeliveryFactory; + dbg(`factory exists: ${!!factory}`); + dbg(`factory keys: ${factory ? Object.keys(factory).join(',') : 'N/A'}`); + dbg(`factory.getDispatchModel type: ${factory && typeof factory.getDispatchModel}`); + + // 直接尝试调用,不判断 typeof,看具体报什么错 + if (factory) { + const tableDefs = [ + { label: 'dispatch', getModel: () => factory.getDispatchModel(warehouseId) }, + { label: 'current', getModel: () => factory.getCurrentModel(warehouseId) }, + { label: 'history', getModel: () => factory.getHistoryModel(warehouseId) }, + ]; + const remainingIds = new Set(orderIds.map(String)); + for (const entry of tableDefs) { + if (remainingIds.size === 0) break; + dbg(` trying table: ${entry.label}, remainingIds=[${[ ...remainingIds ].join(',')}]`); + try { + const model = await entry.getModel(); + dbg(` ${entry.label} model: ${!!model}, typeof findAll=${model && typeof model.findAll}`); + if (!model || typeof model.findAll !== 'function') { + dbg(` ${entry.label} model invalid, skip`); + continue; + } + const whereClause = { id: [ ...remainingIds ].map(Number) }; + dbg(` ${entry.label} where: ${JSON.stringify(whereClause)}`); + const rows = await model.findAll({ + attributes: [ + 'id', 'delivery_order_code', 'source_order_codes', 'pay_no', + 'store_id', 'status', + 'name', 'mobile', 'province', 'city', 'area', 'detail_address', + 'buyer_nick', 'seller_nick', 'shop_nick', + 'total_amount', 'item_amount', 'freight', + 'items_count', 'items_weight', + 'wave_no', 'delivery_time', 'create_at', + ], + where: whereClause, + raw: true, + }); + dbg(` ${entry.label} rows count: ${rows.length}`); + for (const r of (rows || [])) { + dbg(` row: id=${r.id} delivery_order_code=${r.delivery_order_code} status=${r.status}`); + const rid = String(r.id); + if (!orderMap.has(rid)) { orderMap.set(rid, r); remainingIds.delete(rid); } + } + } catch (e) { + dbg(` ${entry.label} ERROR: ${e.message} | stack: ${(e.stack || '').split('\n').slice(0, 3).join(' | ')}`); + continue; + } + } + } + } + dbg(`orderMap.size: ${orderMap.size}, keys: [${[ ...orderMap.keys() ].join(',')}]`); + + // ====== 第三步:货主备注 ====== + dbg('--- Step3: store remark ---'); + const storeRemarkMap = new Map(); + const allStoreIds = new Set(); + for (const oid of orderIds) { + const wb = (waybillMap.get(oid) || [])[0]; + const sid = (wb && wb.store_id) || (orderMap.get(String(oid)) || {}).store_id || 0; + if (sid) allStoreIds.add(sid); + } + dbg(`allStoreIds: [${[ ...allStoreIds ].join(',')}]`); + if (allStoreIds.size > 0 && ctx.model.StoreWarehouse) { + try { + const swRows = await ctx.model.StoreWarehouse.findAll({ + where: { store_id: { [Op.in]: [ ...allStoreIds ] }, warehouse_id: warehouseId }, + attributes: [ 'store_id', 'store_remask' ], raw: true, + }); + dbg(`store_warehouse rows: ${swRows.length}`); + for (const sw of swRows) { + dbg(` sw: store_id=${sw.store_id} store_remask="${sw.store_remask}"`); + storeRemarkMap.set(sw.store_id, sw.store_remask || ''); + } + } catch (e) { dbg(`store_warehouse ERROR: ${e.message}`); } + } + + // ====== 合并输出 ====== + dbg('--- Merge output ---'); + const list = []; + for (const oid of orderIds) { + const order = orderMap.get(String(oid)) || {}; + const waybills = waybillMap.get(oid) || []; + dbg(` oid=${oid} orderKeys=[${Object.keys(order).join(',')}] waybills=${waybills.length}`); + if (waybills.length === 0) { + list.push({ + order_id: oid, waybill_id: 0, waybill_code: '', + logistics_code: '', logistics_name: '', logistics_interface_id: 0, logistics_interface_name: '', + platform_code: '', waybill_status: null, waybill_status_text: '', + is_back: 'N', is_intercept: 'N', is_galaxy_receive: 'N', + weighing_weight: 0, weighing_weight_display: '0 kg', + delivery_order_code: order.delivery_order_code || '', + source_order_codes: order.source_order_codes || '', + pay_no: order.pay_no || '', + store_id: order.store_id || 0, store_name: order.store_name || '', + store_remask: storeRemarkMap.get(order.store_id) || '', + status: order.status || '', name: order.name || '', mobile: order.mobile || '', + province: order.province || '', city: order.city || '', area: order.area || '', + detail_address: order.detail_address || '', + buyer_nick: order.buyer_nick || '', seller_nick: order.seller_nick || '', shop_nick: order.shop_nick || '', + total_amount: order.total_amount || 0, item_amount: order.item_amount || 0, freight: order.freight || 0, + items_count: order.items_count || 0, items_weight: order.items_weight || 0, + wave_no: order.wave_no || '', + delivery_time: order.delivery_time ? app.formatDate(order.delivery_time) : null, + create_at: order.create_at ? app.formatDate(order.create_at) : null, + }); + } else { + for (const wb of waybills) { + list.push({ + order_id: oid, waybill_id: wb.id, waybill_code: wb.waybill_code, + logistics_code: wb.logistics_code, logistics_name: wb.logistics_name, + logistics_interface_id: wb.logistics_interface_id, logistics_interface_name: wb.logistics_interface_name, + platform_code: wb.platform_code, + waybill_status: wb.status, waybill_status_text: wb.status_text, + is_back: wb.is_back, is_intercept: wb.is_intercept, is_galaxy_receive: wb.is_galaxy_receive, + weighing_weight: wb.weighing_weight, weighing_weight_display: wb.weighing_weight_display, + delivery_order_code: wb.delivery_order_code || order.delivery_order_code || '', + source_order_codes: wb.source_order_codes || order.source_order_codes || '', + pay_no: order.pay_no || '', + store_id: wb.store_id || order.store_id || 0, store_name: order.store_name || '', + store_remask: storeRemarkMap.get(wb.store_id || order.store_id) || '', + status: order.status || '', name: order.name || '', mobile: order.mobile || '', + province: order.province || '', city: order.city || '', area: order.area || '', + detail_address: order.detail_address || '', + buyer_nick: order.buyer_nick || '', seller_nick: order.seller_nick || '', shop_nick: order.shop_nick || '', + total_amount: order.total_amount || 0, item_amount: order.item_amount || 0, freight: order.freight || 0, + items_count: order.items_count || 0, items_weight: order.items_weight || 0, + wave_no: order.wave_no || '', + delivery_time: order.delivery_time ? app.formatDate(order.delivery_time) : null, + create_at: order.create_at ? app.formatDate(order.create_at) : null, + }); + } + } + } + + dbg(`list.length: ${list.length}`); + dbg('========== quickSearch END =========='); + return { list, keyword }; + } + + buildWaybillItem(er) { + return { + id: er.id, + waybill_code: er.waybill_code, + delivery_order_code: er.delivery_order_code || '', + source_order_codes: er.source_order_codes || '', + store_id: er.store_id || 0, + logistics_code: er.logistics_code || '', + logistics_name: er.logistics_name || '', + logistics_interface_id: er.logistics_interface_id || 0, + logistics_interface_name: er.logistics_interface_name || '', + platform_code: er.platform_code || '', + status: er.status, + status_text: er.status === 1 ? '已分配' : '未分配', + is_back: er.is_back || 'N', + is_intercept: er.is_intercept || 'N', + is_galaxy_receive: er.is_galaxy_receive || 'N', + weighing_weight: er.weighing_weight || 0, + weighing_weight_display: er.weighing_weight > 0 + ? `${(er.weighing_weight / 1000).toFixed(2)} kg` : '0 kg', + }; + } + + /** + * 按订单 ID 列表批量查询订单关键字段(遍历 dispatch → current → history)。 + * @param {number[]} orderIds 订单ID列表 + * @param {number} warehouseId 仓库ID + * @return {Promise>} orderId → 订单行 + */ + async fetchOrderMapByIds(orderIds, warehouseId) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const orderDeliveryFactory = ctx.model && ctx.model.OrderDeliveryFactory; + + if (!orderDeliveryFactory || typeof orderDeliveryFactory.getDispatchModel !== 'function') { + return []; + } + + const tableOrders = [ + { label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) }, + { label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) }, + { label: 'history', getModel: () => orderDeliveryFactory.getHistoryModel(warehouseId) }, + ]; + + const resultMap = new Map(); + const remainingIds = new Set(orderIds.map(id => String(id))); + + for (const entry of tableOrders) { + if (remainingIds.size === 0) break; + try { + const model = await entry.getModel(); + if (!model || typeof model.findAll !== 'function') continue; + + const rows = await model.findAll({ + attributes: [ + 'id', 'delivery_order_code', 'source_order_codes', 'pay_no', + 'store_id', 'status', + 'name', 'mobile', 'province', 'city', 'area', 'detail_address', + 'buyer_nick', 'seller_nick', 'shop_nick', + 'total_amount', 'item_amount', 'freight', + 'items_count', 'items_weight', + 'wave_no', 'delivery_time', 'create_at', + ], + where: { + id: { [Op.in]: [ ...remainingIds ].map(Number) }, + }, + raw: true, + }); + + for (const r of rows) { + const rid = String(r.id); + if (!resultMap.has(rid)) { + resultMap.set(rid, r); + remainingIds.delete(rid); + } + } + } catch (_err) { + continue; + } + } + + return resultMap; + } + } module.exports = DeliveryOrderService; diff --git a/app/service/systemMethods/order/pendingOrder.js b/app/service/systemMethods/order/pendingOrder.js index 6f6bb79..1c155f4 100644 --- a/app/service/systemMethods/order/pendingOrder.js +++ b/app/service/systemMethods/order/pendingOrder.js @@ -4105,6 +4105,32 @@ class PendingOrderService extends OrderBaseService { }, }); + // 同步更新运单表拦截标记 + try { + await ctx.model.OrderExpress.update( + { is_intercept: 'Y' }, + { where: { order_id: { [Op.in]: chunkOrderIds }, warehouse_id: warehouseId } } + ); + } catch (expressErr) { + ctx.logger.warn( + `[order.pendingOrder.batchIntercept] 更新运单拦截标记失败, count=${chunkOrderIds.length}, error=${expressErr.message}` + ); + } + + // 创建售后工单 + 通知快递群(失败不影响主流程) + try { + const op = this.getOrderLogOperator(); + await ctx.service.systems.afterSale.createInterceptWorkOrdersAndNotify({ + orderIds: chunkOrderIds, + warehouseId, + creatorLabel: op.name || '系统', + }); + } catch (workOrderErr) { + ctx.logger.warn( + `[order.pendingOrder.batchIntercept] 创建工单/通知失败, count=${chunkOrderIds.length}, error=${workOrderErr.message}` + ); + } + // 写入操作日志 const logPayloads = chunkRows.map(row => { const orderId = Number(row.id || 0); @@ -5635,6 +5661,18 @@ class PendingOrderService extends OrderBaseService { }, }); + // 同步清除运单表拦截+退回标记 + try { + await ctx.model.OrderExpress.update( + { is_intercept: 'N', is_back: 'N' }, + { where: { order_id: { [Op.in]: chunkOrderIds }, warehouse_id: warehouseId } } + ); + } catch (expressErr) { + ctx.logger.warn( + `[order.pendingOrder.batchUnintercept] 清除运单标记失败, count=${chunkOrderIds.length}, error=${expressErr.message}` + ); + } + // 写入操作日志 ORDER_INTERCEPT_CANCEL const logPayloads = chunkRows.map(row => { const orderId = Number(row.id || 0); diff --git a/app/service/systemMethods/order/recheckOrder.js b/app/service/systemMethods/order/recheckOrder.js index 5790498..1320033 100644 --- a/app/service/systemMethods/order/recheckOrder.js +++ b/app/service/systemMethods/order/recheckOrder.js @@ -10,9 +10,9 @@ class RecheckOrderService extends OrderBaseService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'scanOrder,scanTask,scanWaybill,confirmRecheck,recheckOrderList,confirmIntercept,batchQuickRecheck,batchQuickRecheckByWave,queryRecheckOrderSingleList'; - const _noNeedLog = 'scanOrder,scanTask,scanWaybill,confirmRecheck,recheckOrderList,confirmIntercept,batchQuickRecheck,batchQuickRecheckByWave'; - const _noNeedAuth = 'scanOrder,scanTask,scanWaybill,confirmRecheck,recheckOrderList,confirmIntercept,batchQuickRecheck,batchQuickRecheckByWave,queryRecheckOrderSingleList'; + const _noNeedRight = 'scanOrder,scanTask,scanWaybill,confirmRecheck,recheckOrderList,confirmIntercept,batchQuickRecheck,batchQuickRecheckByWave,queryRecheckOrderSingleList,interceptScan'; + const _noNeedLog = 'scanOrder,scanTask,scanWaybill,confirmRecheck,recheckOrderList,confirmIntercept,batchQuickRecheck,batchQuickRecheckByWave,interceptScan'; + const _noNeedAuth = 'scanOrder,scanTask,scanWaybill,confirmRecheck,recheckOrderList,confirmIntercept,batchQuickRecheck,batchQuickRecheckByWave,queryRecheckOrderSingleList,interceptScan'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -3611,6 +3611,18 @@ class RecheckOrderService extends OrderBaseService { throw new Error('拦截状态更新失败,请稍后重试'); } + // 同步更新运单表:仅对已标记拦截的运单设置退回标记 + try { + await ctx.model.OrderExpress.update( + { is_back: 'Y' }, + { where: { order_id: orderId, warehouse_id: warehouseId, is_intercept: 'Y' } } + ); + } catch (expressErr) { + ctx.logger.warn( + `[recheckOrder.confirmIntercept] 更新运单退回标记失败, orderId=${orderId}, error=${expressErr.message}` + ); + } + // 拦截成功后释放储位分配(归还库存) try { await this.service.systems.orderStorageAllocation.cancelAllocateStorage({ @@ -3634,6 +3646,20 @@ class RecheckOrderService extends OrderBaseService { ); } + // 创建售后工单 + 通知快递群(失败不影响主流程) + try { + const operator = this.getOrderLogOperator(); + await this.service.systems.afterSale.createInterceptWorkOrdersAndNotify({ + orderIds: [ orderId ], + warehouseId, + creatorLabel: operator.name || '系统', + }); + } catch (workOrderErr) { + ctx.logger.warn( + `[recheckOrder.confirmIntercept] 创建工单/通知失败, orderId=${orderId}, error=${workOrderErr.message}` + ); + } + const orderNo = String(order.delivery_order_code || order.pre_delivery_order_code || '').trim(); // 写入操作日志(失败不影响主流程) @@ -3668,6 +3694,182 @@ class RecheckOrderService extends OrderBaseService { }; } + /** + * 拦截扫描:通过运单号查找运单记录,标记退回并处理关联工单与订单拦截状态。 + * + * 处理流程: + * 1. 根据运单号查询 wms_order_express,找到则将 is_back 设为 'Y';未找到则创建新记录补充缺失快递 + * 2. 检查是否存在关联的未完结售后工单(wms_after_sale),若有则调用 handleWorkOrder 写入 + * "库内拦截成功"步骤并将工单置为 completed + * 3. 同步更新 wms_order_delivery 的 intercept_status 为 intercepted_at_warehouse, + * 并释放储位分配与订单锁(与 confirmIntercept 行为一致,订单级拦截覆盖所有面单含子面单) + * + * @param {Object} data 请求体。 + * @param {string} data.waybill_code 运单号。 + * @return {Promise} 拦截扫描结果,包含 waybill_code、is_back、after_sale(若有)、order。 + */ + async interceptScan(data = {}) { + const { ctx, service } = this; + const { waybill_code: waybillCode } = data || {}; + + if (!waybillCode || !String(waybillCode).trim()) { + throw new Error('运单号不能为空'); + } + + const normalizedWaybillCode = String(waybillCode).trim(); + const warehouseId = this.getWarehouseId(); + const now = new Date(); + + // 1. 查询运单记录 + let expressRecord = await ctx.model.OrderExpress.findOne({ + where: { waybill_code: normalizedWaybillCode, warehouse_id: warehouseId }, + raw: true, + }); + + // 1a. 缺失快递补充:运单记录不存在则创建新记录 + if (!expressRecord) { + const created = await ctx.model.OrderExpress.create({ + waybill_code: normalizedWaybillCode, + order_id: null, + warehouse_id: warehouseId, + is_back: 'Y', + is_intercept: 'Y', + create_at: now, + }); + + expressRecord = (created && created.toJSON ? created.toJSON() : created) || {}; + } else { + // 2. 标记退回 + await ctx.model.OrderExpress.update( + { is_back: 'Y', is_intercept: 'Y' }, + { where: { id: expressRecord.id } } + ); + } + + // 3. 检查关联的未完结售后工单 + const afterSale = await ctx.model.AfterSale.findOne({ + where: { + waybill_no: normalizedWaybillCode, + warehouse_id: warehouseId, + deleted_at: null, + status: { [ctx.app.Sequelize.Op.notIn]: [ 'completed', 'closed', 'cancelled' ] }, + }, + order: [[ 'id', 'DESC' ]], + raw: true, + }); + + let afterSaleResult = null; + if (afterSale) { + const operator = this.getOrderLogOperator(); + const operatorId = operator.id ? Number(operator.id) : 0; + const operatorSnapshot = JSON.stringify({ + id: String(operator.id || ''), + name: String(operator.name || ''), + }); + + try { + afterSaleResult = await service.systems.afterSale.handleWorkOrder({ + id: afterSale.id, + remark: '库内拦截成功', + targetStatus: 'completed', + resolution: '库内拦截成功', + attachmentIds: [], + operatorId, + operatorSnapshot, + warehouseId, + }); + } catch (workOrderErr) { + ctx.logger.warn( + `[recheckOrder.interceptScan] 处理工单失败, afterSaleId=${afterSale.id}, waybill=${normalizedWaybillCode}, error=${workOrderErr.message}` + ); + // 工单处理失败不阻断主流程 + } + } + + // 4. 更新订单拦截状态(与 confirmIntercept 一致:订单级拦截,覆盖所有面单含子面单) + const orderId = Number(expressRecord.order_id || 0); + let orderResult = null; + if (orderId > 0) { + const orderModel = await this.getOrderModelByTableType('current', warehouseId); + const orderWhere = this.buildOrderWhere([ orderId ], warehouseId); + const order = await orderModel.findOne({ + where: orderWhere, + attributes: [ 'id', 'delivery_order_code', 'pre_delivery_order_code', 'intercept_status' ], + raw: true, + }); + + if (order) { + await orderModel.update( + { intercept_status: 'intercepted_at_warehouse', updated_at: now }, + { where: orderWhere } + ); + + // 释放储位分配 + try { + await service.systems.orderStorageAllocation.cancelAllocateStorage({ + order_ids: [ orderId ], + }); + } catch (allocErr) { + ctx.logger.warn( + `[recheckOrder.interceptScan] 释放储位分配失败, orderId=${orderId}, error=${allocErr.message}` + ); + } + + // 释放订单锁 + try { + await orderModel.update( + { lock_status: 'none', updated_at: now }, + { where: orderWhere } + ); + } catch (lockErr) { + ctx.logger.warn( + `[recheckOrder.interceptScan] 释放锁失败, orderId=${orderId}, error=${lockErr.message}` + ); + } + + const orderNo = String(order.delivery_order_code || order.pre_delivery_order_code || '').trim(); + + // 写入操作日志 + try { + const operator = this.getOrderLogOperator(); + const logWarehouseId = this.getOrderLogWarehouseId(warehouseId); + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'order', + businessId: logWarehouseId, + operationCode: 'ORDER_INTERCEPT_CONFIRM', + operator, + extras: { + warehouseId: logWarehouseId, + orderId, + orderNo, + previousInterceptStatus: String(order.intercept_status || '').trim(), + newInterceptStatus: 'intercepted_at_warehouse', + }, + beforeChanges: null, + }); + } catch (logErr) { + ctx.logger.warn( + `[recheckOrder.interceptScan] 写入操作日志失败, orderId=${orderId}, error=${logErr.message}` + ); + } + + orderResult = { + order_id: orderId, + order_no: orderNo, + intercept_status: 'intercepted_at_warehouse', + }; + } + } + + return { + waybill_code: normalizedWaybillCode, + is_back: 'Y', + is_intercept: 'Y', + after_sale: afterSaleResult ? afterSaleResult.after_sale : null, + order: orderResult, + }; + } + /** * 批量快捷复核:对一批订单 IDs 依次执行前置条件检查与复核流程。 * 支持部分失败:不满足前置条件的订单直接跳过并记录失败原因,其余订单继续走完拣货完成 + 复核标记流程。 diff --git a/app/service/systemMethods/pickCart.js b/app/service/systemMethods/pickCart.js index 64479c6..4de4881 100644 --- a/app/service/systemMethods/pickCart.js +++ b/app/service/systemMethods/pickCart.js @@ -11,9 +11,9 @@ class PickCartService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'scan,bindTaskCart,create,update,delete,detail,list,codeDuplicateCheck'; + const _noNeedRight = 'scan,bindTaskCart,create,update,delete,batchDelete,detail,list,codeDuplicateCheck'; const _noNeedLog = ''; - const _noNeedAuth = 'scan,bindTaskCart,create,update,delete,detail,list,codeDuplicateCheck'; + const _noNeedAuth = 'scan,bindTaskCart,create,update,delete,batchDelete,detail,list,codeDuplicateCheck'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -208,6 +208,41 @@ class PickCartService extends MainService { } } + /** + * 批量删除拣货车。已绑定任务的将被跳过。 + * + * @param {Object} data 请求参数。 + * @param {Array} data.ids 拣货车ID列表。 + * @return {Promise} 统一 success/fail 包装结果。 + */ + async batchDelete(data = {}) { + const { service, ctx } = this; + const ids = Array.isArray(data && data.ids) ? data.ids : []; + + if (ids.length === 0) { + return this.fail('ids 必填且必须为非空数组', {}, 400); + } + + try { + const result = await service.systems.pickCart.batchDelete({ ids }); + return this.success('ok', { + data: result, + code: 200, + }); + } catch (error) { + const code = Number(error && error.code); + if (Number.isInteger(code) && code >= 400 && code < 600) { + const errorData = error && error.data && typeof error.data === 'object' && !Array.isArray(error.data) + ? error.data + : {}; + return this.fail(error.message || '批量删除失败', errorData, code); + } + + ctx.logger.error('[PickCartService.batchDelete] 批量删除拣货车失败: %s', error && error.message ? error.message : error); + return this.fail('批量删除失败', {}, 500); + } + } + /** * 查询拣货车详情。 * diff --git a/app/service/systemMethods/storage/receiving.js b/app/service/systemMethods/storage/receiving.js index ef2cc25..db61b3f 100644 --- a/app/service/systemMethods/storage/receiving.js +++ b/app/service/systemMethods/storage/receiving.js @@ -14,7 +14,7 @@ class configService extends MainService { super(ctx); const _noNeedLogin = ''; const _noNeedRight = 'getReceivingList,getStoreReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs,scanDetail,export,exportTaskProgress,storeExport,storeExportTaskProgress'; - const _noNeedLog = 'getReceivingList,getStoreReceivingList,get,addDetail,deleteDetail,detailChange,bindStore,bindDetailProduct,queryReceivingLogs,scanDetail,export,exportTaskProgress,storeExport,storeExportTaskProgress'; + const _noNeedLog = ''; const _noNeedAuth = 'getReceivingList,getStoreReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs,scanDetail,export,exportTaskProgress,storeExport,storeExportTaskProgress'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } diff --git a/app/service/systemMethods/storage/transaction.js b/app/service/systemMethods/storage/transaction.js index 8a031e5..48a6167 100644 --- a/app/service/systemMethods/storage/transaction.js +++ b/app/service/systemMethods/storage/transaction.js @@ -23,9 +23,9 @@ class StorageTransactionService extends MainService { */ async list(data = {}) { const { service } = this; - const { pagination, sort, group_by_batch } = data; + const { pagination, sort, group_by_batch, keyword } = data; this.prepareWhereContext(data); - const result = await service.systems.stockTransaction.list(pagination, sort, group_by_batch); + const result = await service.systems.stockTransaction.list(pagination, sort, group_by_batch, keyword); return this.success('ok', result); } } diff --git a/app/service/systems/afterSale.js b/app/service/systems/afterSale.js index b62a4fc..ceedfb6 100644 --- a/app/service/systems/afterSale.js +++ b/app/service/systems/afterSale.js @@ -33,9 +33,12 @@ class AfterSaleService extends Service { * @param {Object} [sort] 排序参数 * @param {string} [sort.sortField] 排序字段 * @param {string} [sort.sortOrder] 排序顺序(asc/desc) + * @param {Object} [opts] 额外选项 + * @param {Array} [opts.order] 自定义 Sequelize order(优先于 sort) + * @param {boolean} [opts.excludeFutureFollowup] 是否排除 followup_at 未到的 pending_feedback 工单 * @return {Promise} { list: Array, pagination: Object } */ - async list(where = {}, pagination = {}, sort = {}) { + async list(where = {}, pagination = {}, sort = {}, opts = {}) { const { ctx, app } = this; const { Op } = app.Sequelize; @@ -45,8 +48,32 @@ class AfterSaleService extends Service { // 构建 Sequelize where 条件 const queryWhere = this._buildListWhere(where, Op); - // 排序 - const order = this._buildListOrder(sort); + // 工作列表特殊逻辑:pending_feedback 状态的工单,若 followup_at 未到,暂不显示 + if (opts.excludeFutureFollowup) { + const pendingFeedbackWhere = { + [Op.or]: [ + { status: { [Op.ne]: 'pending_feedback' } }, + { + status: 'pending_feedback', + [Op.or]: [ + { followup_at: null }, + { followup_at: { [Op.lte]: app.Sequelize.literal('NOW()') } }, + ], + }, + ], + }; + // 合并到现有 where 中(AND 关系) + if (queryWhere[Op.and]) { + queryWhere[Op.and].push(pendingFeedbackWhere); + } else { + queryWhere[Op.and] = [ pendingFeedbackWhere ]; + } + } + + // 排序:opts.order 优先于 sort + const order = Array.isArray(opts.order) && opts.order.length > 0 + ? opts.order + : this._buildListOrder(sort); const { count, rows } = await ctx.model.AfterSale.findAndCountAll({ where: queryWhere, @@ -58,8 +85,10 @@ class AfterSaleService extends Service { const totalPages = Math.ceil(count / pageSize); + const list = rows.map(row => this._formatAfterSaleRow(row, app)); + return { - list: rows, + list, pagination: { page, pageSize, @@ -71,6 +100,49 @@ class AfterSaleService extends Service { }; } + /** + * 快速统计符合条件的售后单数量(用于角标显示,不做分页)。 + * 与 list() 共享相同的 where 构建逻辑,但只返回 count。 + * + * @param {Object} where 标准化 where 条件对象 + * @param {Object} [opts] 额外选项 + * @param {boolean} [opts.excludeFutureFollowup] 是否排除 followup_at 未到的 pending_feedback 工单 + * @return {Promise} { count: number } + */ + async countPending(where = {}, opts = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + const queryWhere = this._buildListWhere(where, Op); + + // 工作列表特殊逻辑:pending_feedback 状态的工单,若 followup_at 未到,暂不计数 + if (opts.excludeFutureFollowup) { + const pendingFeedbackWhere = { + [Op.or]: [ + { status: { [Op.ne]: 'pending_feedback' } }, + { + status: 'pending_feedback', + [Op.or]: [ + { followup_at: null }, + { followup_at: { [Op.lte]: app.Sequelize.literal('NOW()') } }, + ], + }, + ], + }; + if (queryWhere[Op.and]) { + queryWhere[Op.and].push(pendingFeedbackWhere); + } else { + queryWhere[Op.and] = [ pendingFeedbackWhere ]; + } + } + + const count = await ctx.model.AfterSale.count({ + where: queryWhere, + }); + + return { count }; + } + /** * 根据标准化 where 条件构建 Sequelize 查询条件。 * @@ -189,7 +261,7 @@ class AfterSaleService extends Service { * @return {Array>} Sequelize order 数组 */ _buildListOrder(sort = {}) { - const sortField = sort.sortField || sort.sort_field || 'created_at'; + const sortField = sort.sortField || sort.sort_field || 'updated_at'; const sortOrderRaw = (sort.sortOrder || sort.sort_order || 'desc').toLowerCase(); const sortOrder = sortOrderRaw === 'asc' ? 'ASC' : 'DESC'; @@ -204,20 +276,21 @@ class AfterSaleService extends Service { return [[ safeSortField, sortOrder ]]; } - // =========================== // 明细查询 // =========================== /** * 售后单明细查询,包含主表信息、步骤列表及附件。 + * 若关联了订单(order_delivery_id),自动补充收件人/发件人/订单明细/打包视频。 + * 若关联了货主(store_id),自动补充货主合约备注。 * * @param {number} id 售后单主键ID - * @return {Promise} 售后单明细,包含主表、步骤列表(含附件) + * @return {Promise} 售后单明细,包含主表、步骤列表(含附件)、关联单据详情 * @throws {Error} 售后单不存在时抛出 */ async getDetail(id) { - const { ctx } = this; + const { ctx, app } = this; // 查询主表 const afterSale = await ctx.model.AfterSale.findOne({ @@ -239,9 +312,373 @@ class AfterSaleService extends Service { // 查询步骤附件 const stepsWithAttachments = await this._enrichStepsWithAttachments(steps); + // 格式化时间字段 + const formatRow = row => this._formatAfterSaleRow(row, app); + + // 补充关联单据详情 + const related = await this._enrichAfterSaleDetail(afterSale); + + // 开始处理时间:取首条步骤记录的创建时间 + const firstStep = stepsWithAttachments[0]; + const startedAt = firstStep ? (firstStep.created_at ? app.formatDate(firstStep.created_at) : null) : null; + return { - after_sale: afterSale, - steps: stepsWithAttachments, + after_sale: { ...formatRow(afterSale), started_at: startedAt }, + steps: stepsWithAttachments.map(formatRow), + related, + }; + } + + /** + * 根据售后单关联的业务单据ID,补充关联详情。 + * 包括:订单信息(收件人/发件人/明细/打包视频)、货主合约备注。 + * + * @param {Object} afterSale 售后主表记录 + * @return {Promise} 关联详情对象 + */ + async _enrichAfterSaleDetail(afterSale) { + const { ctx } = this; + const related = {}; + + // ======= 1. 关联订单详情 ======= + if (afterSale.order_delivery_id) { + try { + related.order = await this._resolveOrderDetail( + afterSale.order_delivery_id, + afterSale.warehouse_id + ); + } catch (err) { + ctx.logger.warn(`[_enrichAfterSaleDetail] 解析订单详情失败 id=${afterSale.order_delivery_id}: ${err.message}`); + } + } + + // ======= 2. 关联运单详情(快递公司 + 接口) ======= + if (afterSale.waybill_id) { + try { + related.waybill = await this._resolveWaybillDetail(afterSale.waybill_id); + } catch (err) { + ctx.logger.warn(`[_enrichAfterSaleDetail] 解析运单详情失败 id=${afterSale.waybill_id}: ${err.message}`); + } + } + + // ======= 3. 货主合约备注 ======= + if (afterSale.store_id && afterSale.warehouse_id) { + try { + related.store_contract = await this._resolveStoreContractNote( + afterSale.store_id, + afterSale.warehouse_id + ); + } catch (err) { + ctx.logger.warn(`[_enrichAfterSaleDetail] 解析货主合约备注失败 store_id=${afterSale.store_id}: ${err.message}`); + } + } + + return related; + } + + /** + * 解析关联订单的详细信息:收件人、发件人、订单明细、打包视频。 + * + * @param {number} orderDeliveryId 发货订单ID + * @param {number} warehouseId 仓库ID + * @return {Promise} 订单详情,查询失败返回 null + */ + async _resolveOrderDetail(orderDeliveryId, warehouseId) { + const { ctx, app } = this; + + try { + // 1. 查询订单主记录(优先主表,再尝试工厂分表) + let order = null; + try { + order = await ctx.model.OrderDelivery.findOne({ + where: { id: orderDeliveryId }, + raw: true, + }); + } catch (err) { + ctx.logger.warn(`[_resolveOrderDetail] 主表查询失败: ${err.message}`); + } + + if (!order && ctx.model.OrderDeliveryFactory) { + try { + const factoryModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); + if (factoryModel) { + order = await factoryModel.findOne({ + where: { id: orderDeliveryId }, + raw: true, + }); + } + } catch (err) { + ctx.logger.warn(`[_resolveOrderDetail] 工厂模型查询失败: ${err.message}`); + } + } + + if (!order) { + ctx.logger.info(`[_resolveOrderDetail] 未找到订单 id=${orderDeliveryId} warehouseId=${warehouseId}`); + return null; + } + + ctx.logger.info(`[_resolveOrderDetail] 找到订单 id=${orderDeliveryId} code=${order.delivery_order_code} status=${order.status}`); + + // 2. 构建收件人信息 + const recipient = { + name: order.name || '', + tel: order.tel || '', + mobile: order.mobile || '', + email: order.email || '', + zip_code: order.zip_code || '', + country: order.country_code || '', + province: order.province || '', + city: order.city || '', + district: order.district || '', + town: order.town || '', + address: order.detail_address || '', + }; + + // 3. 构建发件人信息(从货主 subject_config 中取) + let sender = null; + if (order.store_id) { + try { + const store = await ctx.model.Store.findOne({ + where: { id: order.store_id }, + attributes: [ 'id', 'subject_config', 'name' ], + raw: true, + }); + if (store) { + let subjectConfig = store.subject_config; + if (typeof subjectConfig === 'string') { + try { subjectConfig = JSON.parse(subjectConfig); } catch { subjectConfig = {}; } + } + sender = { + name: (subjectConfig && subjectConfig.sender_name) || store.name || '', + tel: (subjectConfig && subjectConfig.sender_tel) || '', + province: (subjectConfig && subjectConfig.province_name) || '', + city: (subjectConfig && subjectConfig.city_name) || '', + district: (subjectConfig && subjectConfig.district_name) || '', + town: (subjectConfig && subjectConfig.town_name) || '', + address: (subjectConfig && subjectConfig.address) || '', + }; + } + } catch (err) { + ctx.logger.warn(`[_resolveOrderDetail] 查询发件人信息失败: ${err.message}`); + } + } + + // 4. 订单明细(优先 order.items JSON,为空时回退到分表查询) + let orderItems = []; + if (order.items) { + try { + const parsed = typeof order.items === 'string' ? JSON.parse(order.items) : order.items; + orderItems = Array.isArray(parsed) ? parsed : []; + } catch { + // items 解析失败,忽略 + } + } + + // 回退:若 items 为空且 OrderItemsFactory 可用,从分表查询 + if (orderItems.length === 0 && ctx.model.OrderItemsFactory) { + try { + const itemsModel = await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId); + if (itemsModel) { + const dbItems = await itemsModel.findAll({ + where: { order_id: orderDeliveryId }, + raw: true, + }); + if (dbItems && dbItems.length > 0) { + // 收集 stock_id 用于批量查库存详情 + const stockIds = dbItems + .map(item => Number(item.stock_id)) + .filter(id => Number.isInteger(id) && id > 0); + + // 批量获取库存详情(带缓存的并行查询:条码 + 图片 + 库存属性) + let stockDetailsMap = new Map(); + if (stockIds.length > 0) { + try { + const details = await ctx.service.systems.stockWarehouse.getStockDetails(stockIds, { + warehouseId, + cacheTTL: 300, + }); + for (const detail of details) { + stockDetailsMap.set(detail.id, detail); + } + } catch (err) { + ctx.logger.warn(`[_resolveOrderDetail] 批量获取库存详情失败: ${err.message}`); + } + } + + orderItems = dbItems.map(item => { + const stock = stockDetailsMap.get(Number(item.stock_id)) || {}; + return { + id: item.id, + order_line_no: item.order_line_no || '', + item_code: item.item_code || stock.item_code || '', + item_name: item.item_name || stock.item_name || '', + sku_property: stock.sku_property || '', + quantity: stock.quantity || 0, + locked_quantity: stock.locked_quantity || 0, + is_batch_mgmt: stock.is_batch_mgmt || 'N', + is_shelf_life_mgmt: stock.is_shelf_life_mgmt || 'N', + is_images: stock.is_images || 'N', + store_id: stock.store_id || null, + packing_requirements: stock.packing_requirements || '', + stock_unit: stock.stock_unit || '', + image_url: stock.image_url || [], + barcodes: stock.barcodes || [], + plan_qty: item.plan_qty || 0, + stock_id: item.stock_id || null, + order_item_id: item.id, + order_id: orderDeliveryId, + }; + }); + ctx.logger.info(`[_resolveOrderDetail] 从分表加载 ${orderItems.length} 条明细(含库存详情)`); + } + } + } catch (err) { + ctx.logger.warn(`[_resolveOrderDetail] 分表查询商品明细失败: ${err.message}`); + } + } + + // 5. 打包视频 + let packVideos = []; + try { + const packTasks = await ctx.model.PackTask.findAll({ + where: { order_id: orderDeliveryId, deleted_at: null }, + include: [ + { + model: ctx.model.PackTaskVideo, + as: 'videos', + where: { deleted_at: null }, + required: false, + }, + ], + order: [[ 'create_time', 'DESC' ]], + raw: false, + }); + + for (const task of packTasks) { + const taskJson = task.toJSON ? task.toJSON() : task; + const videos = (taskJson.videos || []).map(v => ({ + id: v.id, + video_url: v.video_url, + camera_id: v.camera_id, + status: v.status, + created_at: v.created_at ? app.formatDate(v.created_at) : null, + })); + packVideos.push({ + pack_task_id: taskJson.id, + status: taskJson.status, + pack_quantity: taskJson.pack_quantity, + start_time: taskJson.start_time ? app.formatDate(taskJson.start_time) : null, + end_time: taskJson.end_time ? app.formatDate(taskJson.end_time) : null, + operator_text: taskJson.operator_text || '', + videos, + }); + } + } catch (err) { + ctx.logger.warn(`[_resolveOrderDetail] 查询打包视频失败: ${err.message}`); + } + + // 6. 组装返回 + return { + id: order.id, + delivery_order_code: order.delivery_order_code || '', + warehouse_id: order.warehouse_id, + store_id: order.store_id, + // 重量(g) + items_weight: order.items_weight || 0, + // 波次 + wave_id: order.wave_id || 0, + wave_no: order.wave_no || '', + // 来源 + platform_name: order.source_platform_name || '', + source_order_codes: order.source_order_codes || '', + // 创建来源渠道 + create_channel: order.create_channel || '', + create_channel_label: this._getCreateChannelLabel(order.create_channel), + // 状态机 + sync_status: order.sync_status || 'padding', + inspection_status: order.inspection_status || 'none', + storage_status: order.storage_status || 'none', + post_status: order.post_status || 'none', + print_status: order.print_status || 'none', + pick_status: order.pick_status || 'none', + pack_status: order.pack_status || 'none', + intercept_status: order.intercept_status || 'none', + // 数量 + items_count: order.items_count, + items_total: order.items_total, + // 收件人 / 发件人 / 明细 / 打包视频 + recipient, + sender, + items: orderItems, + pack_videos: packVideos, + }; + } catch (err) { + ctx.logger.warn(`[_resolveOrderDetail] 整体异常 id=${orderDeliveryId}: ${err.message}`, err.stack); + return null; + } + } + + /** + * 解析货主在当前仓库下的合约备注。 + * + * @param {number} storeId 货主ID + * @param {number} warehouseId 仓库ID + * @return {Promise} 合约备注信息 + */ + async _resolveStoreContractNote(storeId, warehouseId) { + const { ctx } = this; + + const sw = await ctx.model.StoreWarehouse.findOne({ + where: { store_id: storeId, warehouse_id: warehouseId }, + attributes: [ 'id', 'store_remask', 'warehouse_remask', 'store_use_status', 'warehouse_use_status' ], + raw: true, + }); + + if (!sw) return null; + + return { + contract_id: sw.id, + store_remask: sw.store_remask || '', + warehouse_remask: sw.warehouse_remask || '', + store_use_status: sw.store_use_status, + warehouse_use_status: sw.warehouse_use_status, + }; + } + + /** + * 解析关联运单的快递公司名称与使用的物流接口。 + * + * @param {number} waybillId 运单ID(wms_order_express.id) + * @return {Promise} 运单详情,查询失败返回 null + */ + async _resolveWaybillDetail(waybillId) { + const { ctx } = this; + + const waybill = await ctx.model.OrderExpress.findOne({ + where: { id: waybillId }, + attributes: [ + 'id', 'waybill_code', 'order_id', 'logistics_code', + 'logistics_name', 'logistics_interface_id', 'logistics_interface_name', + 'status', 'is_back', 'is_intercept', 'warehouse_id', 'create_at', + ], + raw: true, + }); + + if (!waybill) return null; + + return { + id: waybill.id, + waybill_code: waybill.waybill_code || '', + order_id: waybill.order_id, + logistics_code: waybill.logistics_code || '', + logistics_name: waybill.logistics_name || '', + logistics_interface_id: waybill.logistics_interface_id, + logistics_interface_name: waybill.logistics_interface_name || '', + status: waybill.status, + is_back: waybill.is_back || 'N', + is_intercept: waybill.is_intercept || 'N', + warehouse_id: waybill.warehouse_id, + create_at: waybill.create_at ? ctx.app.formatDate(waybill.create_at) : null, }; } @@ -334,9 +771,10 @@ class AfterSaleService extends Service { * @return {Promise} 创建的售后单记录 */ async create(data, transaction = null) { - const { ctx } = this; + const { ctx, app } = this; const record = await ctx.model.AfterSale.create(data, { transaction }); - return record && record.toJSON ? record.toJSON() : record; + const json = record && record.toJSON ? record.toJSON() : record; + return this._formatAfterSaleRow(json, app); } // =========================== @@ -353,7 +791,7 @@ class AfterSaleService extends Service { * @throws {Error} 售后单不存在时抛出 */ async update(id, data, transaction = null) { - const { ctx } = this; + const { ctx, app } = this; const record = await ctx.model.AfterSale.findOne({ where: { id, deleted_at: null }, @@ -365,7 +803,27 @@ class AfterSaleService extends Service { } await record.update(data, { transaction }); - return record && record.toJSON ? record.toJSON() : record; + const json = record && record.toJSON ? record.toJSON() : record; + return this._formatAfterSaleRow(json, app); + } + + /** + * 格式化售后单记录的时间字段。 + * @param {Object} row 原始数据库行 + * @param {Object} app Egg app 实例 + * @return {Object} 格式化后的行 + */ + _formatAfterSaleRow(row, app) { + if (!row) return row; + return { + ...row, + created_at: row.created_at ? app.formatDate(row.created_at) : null, + updated_at: row.updated_at ? app.formatDate(row.updated_at) : null, + resolved_at: row.resolved_at ? app.formatDate(row.resolved_at) : null, + followup_at: row.followup_at ? app.formatDate(row.followup_at) : null, + started_at: row.started_at ? app.formatDate(row.started_at) : null, + completed_at: row.completed_at ? app.formatDate(row.completed_at) : null, + }; } // =========================== @@ -393,7 +851,7 @@ class AfterSaleService extends Service { const record = await ctx.model.AfterSaleDetail.create({ after_sale_id: afterSaleId, - step_status: stepData.step_status !== undefined ? stepData.step_status : 2, + step_status: stepData.step_status !== undefined ? stepData.step_status : 'processing', operator_id: stepData.operator_id || null, operator_snapshot: stepData.operator_snapshot || null, action: stepData.action || null, @@ -492,9 +950,9 @@ class AfterSaleService extends Service { updated_at: new Date(), }, transaction); - // 写入步骤记录 + // 写入步骤记录(step_status 与主表当前 status 一致) await this.addStep(id, { - step_status: 2, + step_status: updated.status || 'processing', operator_id: operatorId, operator_snapshot: operatorSnapshot, action: '转单', @@ -520,7 +978,6 @@ class AfterSaleService extends Service { * * @param {Object} params 处理参数 * @param {number} params.id 售后单主键ID - * @param {string} params.action 操作动作描述 * @param {string|null} params.remark 处理备注 * @param {string|null} params.targetStatus 目标售后状态 * @param {string|null} params.resolution 完结处理结果 @@ -533,7 +990,7 @@ class AfterSaleService extends Service { */ async handleWorkOrder(params = {}) { const { - id, action, remark, targetStatus, resolution, + id, remark, targetStatus, resolution, attachmentIds, operatorId, operatorSnapshot, warehouseId, } = params; @@ -549,7 +1006,11 @@ class AfterSaleService extends Service { throw new Error('售后单不存在'); } - // 2. 校验 role_group 权限:操作人必须有对应 role_group 的处理权限。 + // 2. status 不填或填错默认 processing;pending 是创建默认值,不适用于处理操作 + const ALLOWED_STATUSES = Object.keys(ctx.model.AfterSale.AFTER_SALE_STATUS).filter(s => s !== 'pending'); + const safeStatus = (targetStatus && ALLOWED_STATUSES.includes(targetStatus)) ? targetStatus : 'processing'; + + // 3. 校验 role_group 权限:操作人必须有对应 role_group 的处理权限。 // 实际权限解析已在方法层(systemMethods/afterSale.js)通过 block 权限完成, // 此处仅做兜底校验。 const allowedRoleGroups = [ 'customer_service', 'warehouse', 'finance' ]; @@ -559,43 +1020,53 @@ class AfterSaleService extends Service { throw new Error('无权限处理当前角色组的售后单'); } - // 3. 开启事务 + // 4. 开启事务 const transaction = await ctx.model.transaction(); try { const now = new Date(); - // 4. 写入步骤记录 + // 5. 写入步骤记录(action 由服务端固定为"处理工单",step_status 同步主表 status) const step = await this.addStep(id, { - step_status: 2, + step_status: safeStatus, operator_id: operatorId, operator_snapshot: operatorSnapshot, - action, + action: '处理工单', remark, started_at: now, completed_at: now, }, transaction); - // 5. 绑定附件 + // 6. 绑定附件 if (Array.isArray(attachmentIds) && attachmentIds.length > 0) { await this.bindAttachments(step.id, attachmentIds, transaction); } - // 6. 更新售后单状态 + // 7. 更新售后单状态 const updateFields = { updated_at: now }; - if (targetStatus) { - updateFields.status = targetStatus; + updateFields.status = safeStatus; - // 若完结,写入 resolution 和 resolved_at - if (targetStatus === 'completed') { - updateFields.resolution = resolution || null; - updateFields.resolved_at = now; - } + // 若完结,写入 resolution 和 resolved_at;清除 followup_at + if (safeStatus === 'completed') { + updateFields.resolution = resolution || null; + updateFields.resolved_at = now; + updateFields.followup_at = null; } - // 7. 若当前角色非客服组且状态非完结,自动回设为客服组 - if (currentRoleGroup && currentRoleGroup !== 'customer_service' && targetStatus !== 'completed') { + // 若设为 pending_feedback:按仓库配置自动计算下次跟进时间 + if (safeStatus === 'pending_feedback') { + const hours = await this._resolveFollowupHours(afterSale.warehouse_id, afterSale.type, afterSale.sub_type); + ctx.logger.info( + `[handleWorkOrder] id=%s warehouse=%s type=%s subType=%s hours=%d`, + id, afterSale.warehouse_id, afterSale.type, afterSale.sub_type, hours + ); + // 使用数据库 NOW() 确保与查询条件时区一致 + updateFields.followup_at = ctx.app.Sequelize.literal(`DATE_ADD(NOW(), INTERVAL ${hours} HOUR)`); + } + + // 8. 若当前角色非客服组且状态非完结,自动回设为客服组 + if (currentRoleGroup && currentRoleGroup !== 'customer_service' && safeStatus !== 'completed') { updateFields.role_group = 'customer_service'; } @@ -606,7 +1077,7 @@ class AfterSaleService extends Service { const updatedAfterSale = afterSale.toJSON ? afterSale.toJSON() : afterSale; return { - after_sale: updatedAfterSale, + after_sale: this._formatAfterSaleRow(updatedAfterSale, ctx.app), step, }; } catch (error) { @@ -615,6 +1086,559 @@ class AfterSaleService extends Service { } } + // =========================== + // 拦截链路:批量创建工单 + 通知快递群 + // =========================== + + /** + * 拦截链路共享方法:根据订单 ID 查找运单,幂等创建售后工单,并按快递分组通知售后群。 + * 用于 batchIntercept / confirmIntercept / Qimen cancel / OpenAPI cancel 等入口统一调用。 + * + * @param {Object} params 参数。 + * @param {number[]} params.orderIds 订单 ID 列表。 + * @param {number} params.warehouseId 仓库 ID。 + * @param {string} params.creatorLabel 创建人标签(如 "系统"、"王小明")。 + * @param {string} [params.reason] 拦截原因。 + * @return {Promise<{ createdCount: number, notifiedCount: number }>} 创建与通知统计。 + */ + async createInterceptWorkOrdersAndNotify(params = {}) { + const { ctx } = this; + const { orderIds, warehouseId, creatorLabel, reason } = params; + + if (!Array.isArray(orderIds) || orderIds.length === 0 || !warehouseId) { + return { createdCount: 0, notifiedCount: 0 }; + } + + try { + // 1. 查询运单信息 + const expressList = await ctx.model.OrderExpress.findAll({ + attributes: [ + 'id', 'waybill_code', 'logistics_name', 'store_id', + 'logistics_interface_id', 'logistics_code', 'order_id', + ], + where: { + order_id: { [ctx.app.Sequelize.Op.in]: orderIds }, + warehouse_id: warehouseId, + }, + raw: true, + }); + + if (expressList.length === 0) { + return { createdCount: 0, notifiedCount: 0 }; + } + + // 2. 幂等检查:已有未完结的拦截工单不再重复创建 + const expressIds = expressList.map(e => e.id); + const existingASList = await ctx.model.AfterSale.findAll({ + attributes: [ 'waybill_id' ], + where: { + waybill_id: { [ctx.app.Sequelize.Op.in]: expressIds }, + type: 'order', + sub_type: 'intercept', + status: { [ctx.app.Sequelize.Op.notIn]: [ 'completed', 'closed', 'cancelled' ] }, + }, + raw: true, + }); + const existingWaybillIds = new Set(existingASList.map(r => r.waybill_id)); + const toCreate = expressList.filter(e => !existingWaybillIds.has(e.id)); + + if (toCreate.length === 0) { + return { createdCount: 0, notifiedCount: 0 }; + } + + // 3. 批量创建工单 + const label = creatorLabel || '系统'; + let createdCount = 0; + const createdWaybillIds = []; + + for (const e of toCreate) { + try { + const afterSaleNo = await ctx.service.systemMethods.afterSale.generateAfterSaleNo(warehouseId); + const descParts = [ + `发起人: ${label}`, + `运单号: ${e.waybill_code}`, + `快递公司: ${e.logistics_name || '未知'}`, + reason ? `拦截原因: ${reason}` : '', + ].filter(Boolean).join('\n'); + + await this.create({ + warehouse_id: warehouseId, + after_sale_no: afterSaleNo, + type: 'order', + sub_type: 'intercept', + title: `[系统拦截] ${e.waybill_code}`, + description: descParts, + priority: 10, + creator_id: 0, + inbox_message_id: null, + role_group: 'warehouse', + status: 'pending', + waybill_id: e.id, + waybill_no: e.waybill_code, + store_id: e.store_id || null, + order_id: e.order_id || null, + }); + createdCount += 1; + createdWaybillIds.push(e.id); + } catch (createErr) { + ctx.logger.warn( + `[afterSale.createInterceptWorkOrdersAndNotify] 创建工单失败, waybill=${e.waybill_code}, error=${createErr.message}` + ); + } + } + + // 4. 按快递分组通知售后群 + const expressByCode = {}; + for (const e of toCreate) { + const code = e.logistics_code || '__unknown__'; + if (!expressByCode[code]) { + expressByCode[code] = { interfaceId: e.logistics_interface_id, waybills: [] }; + } + expressByCode[code].waybills.push(e.waybill_code); + } + + let notifiedCount = 0; + const notifiedWaybillIds = new Set(); + + for (const [ code, info ] of Object.entries(expressByCode)) { + if (code === '__unknown__' || !info.interfaceId) continue; + try { + const { afterSalesGroups } = await ctx.service.systems.inbox.group.findGroupsByExpress({ + expressInterfaceId: info.interfaceId, + expressCode: code, + warehouseId, + }); + + if (afterSalesGroups.length === 0) continue; + + const notifyMsg = info.waybills.join('\n') + '\n拦截'; + for (const g of afterSalesGroups) { + ctx.service.inbox.processor.pushSystemNotification({ + warehouse_id: warehouseId, + group_id: g.group_id, + group_name: g.group_name, + content: notifyMsg, + ext_data: g.ext_data || null, + }); + notifiedCount += 1; + } + // 标记该快递下所有运单已通知 + const codeWaybills = toCreate.filter(e => (e.logistics_code || '__unknown__') === code); + codeWaybills.forEach(e => notifiedWaybillIds.add(e.id)); + } catch (e) { + ctx.logger.warn(`[afterSale] 查售后群失败 code=${code}: ${e.message}`); + } + } + + // 5. 有通知的工单升级为 pending_feedback + if (notifiedWaybillIds.size > 0) { + const notifiedWaybillIdArr = [ ...notifiedWaybillIds ]; + const hours = await this._resolveFollowupHours(warehouseId, 'order', 'intercept'); + await ctx.model.AfterSale.update( + { + status: 'pending_feedback', + followup_at: ctx.app.Sequelize.literal(`DATE_ADD(NOW(), INTERVAL ${hours} HOUR)`), + role_group: 'customer_service', + }, + { + where: { + waybill_id: { [ctx.app.Sequelize.Op.in]: notifiedWaybillIdArr }, + warehouse_id: warehouseId, + type: 'order', + sub_type: 'intercept', + status: 'pending', + }, + } + ); + } + + return { createdCount, notifiedCount }; + } catch (error) { + ctx.logger.warn(`[afterSale.createInterceptWorkOrdersAndNotify] 整体失败: ${error.message}`); + return { createdCount: 0, notifiedCount: 0 }; + } + } + + // =========================== + // 跟进时间配置 + // =========================== + + /** + * 根据仓库配置解析跟进小时数。 + * 优先级:policy_config sub_type 精确匹配 → type._default → 整数兜底 → 24h。 + * + * @param {number} warehouseId 仓库ID + * @param {string} type 售后类型 + * @param {string} subType 售后子类型 + * @return {Promise} 跟进小时数 + */ + async _resolveFollowupHours(warehouseId, type, subType) { + const { ctx } = this; + + // 仓库配置值的最小有效阈值:≤1 视为未配置的占位值,回退到 DEFAULTS + // (实际业务最小合理值为 intercept/urge 的 4h,不存在 0/1h 的跟进场景) + const MIN_VALID_FOLLOWUP_HOURS = 2; + + // 1. 仓库已保存的配置 + const sw = await ctx.model.StoreWarehouse.findOne({ + where: { warehouse_id: warehouseId }, + attributes: [ 'policy_config' ], + order: [[ 'id', 'DESC' ]], + raw: true, + }); + + ctx.logger.info( + `[_resolveFollowupHours] warehouseId=%s type=%s subType=%s hasStoreWarehouse=%s`, + warehouseId, type, subType, !!(sw && sw.policy_config) + ); + + if (sw && sw.policy_config) { + let config = sw.policy_config; + if (typeof config === 'string') { + try { config = JSON.parse(config); } catch { config = {}; } + } + const whConfig = config && config.after_sale_followup_hours; + ctx.logger.info( + `[_resolveFollowupHours] whConfig type=%s value=%s`, + typeof whConfig, JSON.stringify(whConfig) + ); + + if (whConfig && typeof whConfig === 'object') { + const whTypeMap = whConfig[type]; + ctx.logger.info( + `[_resolveFollowupHours] whTypeMap for type=%s: %s`, + type, JSON.stringify(whTypeMap) + ); + + // 分支 A:嵌套对象格式 {"order": {"damage": 48, "_default": 24}} + if (whTypeMap && typeof whTypeMap === 'object') { + if (subType) { + const subVal = this._tryParseHours(whTypeMap[subType]); + if (typeof subVal === 'number' && subVal >= MIN_VALID_FOLLOWUP_HOURS) { + ctx.logger.info(`[_resolveFollowupHours] MATCH subType (nested): %s=%dh`, subType, subVal); + return subVal; + } + } + const defVal = this._tryParseHours(whTypeMap._default); + if (typeof defVal === 'number' && defVal >= MIN_VALID_FOLLOWUP_HOURS) { + ctx.logger.info(`[_resolveFollowupHours] MATCH type._default (nested): %s._default=%dh`, type, defVal); + return defVal; + } + } + + // 分支 B:扁平格式 {"order": "24"} 或 {"order": 24} + // 值为字符串或数字,直接作为该 type 下所有 subType 的统一时长 + const flatVal = this._tryParseHours(whTypeMap); + if (typeof flatVal === 'number' && flatVal >= MIN_VALID_FOLLOWUP_HOURS) { + ctx.logger.info(`[_resolveFollowupHours] MATCH type flat: %s=%dh`, type, flatVal); + return flatVal; + } + } + // 分支 C:全局数字 {"after_sale_followup_hours": 24} 或 {"after_sale_followup_hours": "24"} + { + const globalVal = this._tryParseHours(whConfig); + if (typeof globalVal === 'number' && globalVal >= MIN_VALID_FOLLOWUP_HOURS) { + ctx.logger.info(`[_resolveFollowupHours] MATCH whConfig global: %dh`, globalVal); + return globalVal; + } + } + ctx.logger.info(`[_resolveFollowupHours] whConfig found but no valid match (all < ${MIN_VALID_FOLLOWUP_HOURS}h or type mismatch), falling to DEFAULTS`); + } + + // 2. 仓库未配置时,使用字段默认值(与 setting.warehouse.getFieldMeta 返回一致) + const DEFAULTS = { + order: { _default: 24, intercept: 4, urge: 4, change_address: 8, change_carrier: 8, delivery_delay: 12, damage: 48, quality_issue: 48, missing_item: 24 }, + receiving: { _default: 24, shortage: 48, damage: 48 }, + entry: { _default: 24, shortage: 48, damage: 48 }, + stockout: { _default: 24, return_issue: 48, shortage: 48 }, + }; + const typeDefault = DEFAULTS[type]; + if (typeDefault) { + if (subType && typeof typeDefault[subType] === 'number') { + ctx.logger.info(`[_resolveFollowupHours] DEFAULTS subType match: %s=%dh`, subType, typeDefault[subType]); + return typeDefault[subType]; + } + if (typeof typeDefault._default === 'number') { + ctx.logger.info(`[_resolveFollowupHours] DEFAULTS type._default: %s=%dh`, type, typeDefault._default); + return typeDefault._default; + } + } + + // 3. 硬兜底 + ctx.logger.warn(`[_resolveFollowupHours] FALLBACK 24h for type=%s subType=%s`, type, subType); + return 24; + } + + /** + * 将配置值尝试转为有效的小时数。 + * 兼容数字 24 和字符串 "24" 两种格式;无法解析时返回 null。 + * + * @param {*} raw 原始配置值 + * @return {number|null} 有效小时数,或 null + */ + _tryParseHours(raw) { + if (raw === null || raw === undefined || raw === '') return null; + if (typeof raw === 'number' && Number.isFinite(raw)) return raw; + if (typeof raw === 'string') { + const parsed = Number(raw); + if (Number.isFinite(parsed)) return parsed; + } + return null; + } + + // =========================== + // 批量设为待反馈 + // =========================== + + /** + * 批量将售后工单设为"待反馈"状态,并按仓库配置自动计算 followup_at。 + * 对每个工单写入步骤记录,所有操作在同一事务中执行。 + * + * @param {Object} params 批量操作参数 + * @param {number[]} params.ids 售后单主键ID列表 + * @param {number} params.operatorId 操作人账户ID + * @param {string} params.operatorSnapshot 操作人快照 JSON + * @param {string} [params.remark] 统一处理备注(所有工单共用) + * @param {number} params.warehouseId 仓库ID(用于权限校验) + * @return {Promise} { total, success, failed: [{id, reason}] } + */ + async batchSetPendingFeedback(params = {}) { + const { ids, operatorId, operatorSnapshot, remark, warehouseId } = params; + const { ctx } = this; + + // 1. 入参校验 + if (!Array.isArray(ids) || ids.length === 0) { + return { total: 0, success: 0, failed: [] }; + } + + const numericIds = ids.map(id => Number(id)).filter(id => Number.isInteger(id) && id > 0); + if (numericIds.length === 0) { + return { total: 0, success: 0, failed: [] }; + } + + // 2. 查询所有目标工单 + const afterSales = await ctx.model.AfterSale.findAll({ + where: { + id: { [ctx.app.Sequelize.Op.in]: numericIds }, + deleted_at: null, + }, + }); + + const afterSaleMap = new Map(); + for (const record of afterSales) { + afterSaleMap.set(record.id, record); + } + + // 3. 预校验 & 分类 + const validRecords = []; + const failed = []; + + // 终态不可设为待反馈 + const TERMINAL_STATUSES = new Set([ 'completed', 'closed', 'cancelled' ]); + + for (const id of numericIds) { + const record = afterSaleMap.get(id); + if (!record) { + failed.push({ id, reason: '售后单不存在或已删除' }); + continue; + } + if (TERMINAL_STATUSES.has(record.status)) { + failed.push({ id, reason: `工单已完结(${record.status}),不可设为待反馈` }); + continue; + } + if (record.warehouse_id !== warehouseId) { + failed.push({ id, reason: '仓库不匹配,无权操作' }); + continue; + } + validRecords.push(record); + } + + // 4. 开启事务,逐条更新 + const transaction = await ctx.model.transaction(); + + try { + const now = new Date(); + let successCount = 0; + + for (const record of validRecords) { + // 4a. 解析该工单的跟进小时数 + const hours = await this._resolveFollowupHours( + record.warehouse_id, + record.type, + record.sub_type + ); + + ctx.logger.info( + `[batchSetPendingFeedback] id=%s type=%s subType=%s hours=%d`, + record.id, record.type, record.sub_type, hours + ); + + // 4b. 写入步骤记录 + await this.addStep(record.id, { + step_status: 'pending_feedback', + operator_id: operatorId, + operator_snapshot: operatorSnapshot, + action: '设为待反馈', + remark: remark || null, + started_at: now, + completed_at: now, + }, transaction); + + // 4c. 更新主表:status + followup_at + role_group 回客服组 + const updateFields = { + status: 'pending_feedback', + followup_at: ctx.app.Sequelize.literal(`DATE_ADD(NOW(), INTERVAL ${hours} HOUR)`), + updated_at: now, + }; + // 若非客服组,自动回设为客服组(与 handleWorkOrder 行为一致) + if (record.role_group && record.role_group !== 'customer_service') { + updateFields.role_group = 'customer_service'; + } + + await record.update(updateFields, { transaction }); + successCount++; + } + + await transaction.commit(); + + return { + total: numericIds.length, + success: successCount, + failed, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + // =========================== + // 批量完结/关闭 + // =========================== + + /** + * 批量将售后工单设为完结或关闭状态。 + * completed 时自动写入 resolved_at 并清除 followup_at;closed 仅更新状态。 + * 对每个工单写入步骤记录,所有操作在同一事务中执行。 + * + * @param {Object} params 批量操作参数 + * @param {number[]} params.ids 售后单主键ID列表 + * @param {string} params.status 目标状态:completed | closed + * @param {string} [params.resolution] 完结处理结果(仅 status=completed 时写入) + * @param {number} params.operatorId 操作人账户ID + * @param {string} params.operatorSnapshot 操作人快照 JSON + * @param {string} [params.remark] 统一处理备注(所有工单共用) + * @param {number} params.warehouseId 仓库ID(用于权限校验) + * @return {Promise} { total, success, failed: [{id, reason}] } + */ + async batchClose(params = {}) { + const { ids, status: targetStatus, resolution, operatorId, operatorSnapshot, remark, warehouseId } = params; + const { ctx } = this; + + // 1. 入参校验 + const ALLOWED_TARGET_STATUSES = new Set([ 'completed', 'closed' ]); + if (!targetStatus || !ALLOWED_TARGET_STATUSES.has(targetStatus)) { + return { total: 0, success: 0, failed: [{ id: 0, reason: 'status 必须为 completed 或 closed' }] }; + } + + if (!Array.isArray(ids) || ids.length === 0) { + return { total: 0, success: 0, failed: [] }; + } + + const numericIds = ids.map(id => Number(id)).filter(id => Number.isInteger(id) && id > 0); + if (numericIds.length === 0) { + return { total: 0, success: 0, failed: [] }; + } + + // 2. 查询所有目标工单 + const afterSales = await ctx.model.AfterSale.findAll({ + where: { + id: { [ctx.app.Sequelize.Op.in]: numericIds }, + deleted_at: null, + }, + }); + + const afterSaleMap = new Map(); + for (const record of afterSales) { + afterSaleMap.set(record.id, record); + } + + // 3. 预校验 & 分类 + const validRecords = []; + const failed = []; + + // 终态不可重复完结/关闭 + const TERMINAL_STATUSES = new Set([ 'completed', 'closed', 'cancelled' ]); + + for (const id of numericIds) { + const record = afterSaleMap.get(id); + if (!record) { + failed.push({ id, reason: '售后单不存在或已删除' }); + continue; + } + if (TERMINAL_STATUSES.has(record.status)) { + failed.push({ id, reason: `工单已是终态(${record.status}),不可重复${targetStatus === 'completed' ? '完结' : '关闭'}` }); + continue; + } + if (record.warehouse_id !== warehouseId) { + failed.push({ id, reason: '仓库不匹配,无权操作' }); + continue; + } + validRecords.push(record); + } + + // 4. 开启事务,逐条更新 + const transaction = await ctx.model.transaction(); + + try { + const now = new Date(); + let successCount = 0; + + // 操作动作名称 + const actionName = targetStatus === 'completed' ? '批量完结' : '批量关闭'; + + for (const record of validRecords) { + // 4a. 写入步骤记录 + await this.addStep(record.id, { + step_status: targetStatus, + operator_id: operatorId, + operator_snapshot: operatorSnapshot, + action: actionName, + remark: remark || null, + started_at: now, + completed_at: now, + }, transaction); + + // 4b. 更新主表 + const updateFields = { + status: targetStatus, + updated_at: now, + followup_at: null, + }; + + // completed:额外写入 resolution + resolved_at + if (targetStatus === 'completed') { + updateFields.resolution = resolution || null; + updateFields.resolved_at = now; + } + + await record.update(updateFields, { transaction }); + successCount++; + } + + await transaction.commit(); + + return { + total: numericIds.length, + success: successCount, + failed, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + // =========================== // 登记理赔 // =========================== @@ -674,9 +1698,9 @@ class AfterSaleService extends Service { await afterSale.update(updateFields, { transaction }); - // 写入步骤 + // 写入步骤(step_status 与主表当前 status 一致) const step = await this.addStep(id, { - step_status: 2, + step_status: afterSale.status || 'processing', operator_id: operatorId, operator_snapshot: operatorSnapshot, action, @@ -695,7 +1719,7 @@ class AfterSaleService extends Service { const updatedAfterSale = afterSale.toJSON ? afterSale.toJSON() : afterSale; return { - after_sale: updatedAfterSale, + after_sale: this._formatAfterSaleRow(updatedAfterSale, ctx.app), step, }; } catch (error) { @@ -858,6 +1882,24 @@ class AfterSaleService extends Service { }; } } + + // =========================== + // 工具方法 + // =========================== + + /** + * 获取创建来源渠道的中文标签。 + * @param {string} channel 创建渠道代码 + * @return {string} 中文标签 + */ + _getCreateChannelLabel(channel) { + const labels = { + MANUAL: '手工单', + API: '接口', + QM: '奇门', + }; + return labels[channel] || channel || ''; + } } module.exports = AfterSaleService; diff --git a/app/service/systems/inbox/group.js b/app/service/systems/inbox/group.js index 7f4abf4..0fb9a39 100644 --- a/app/service/systems/inbox/group.js +++ b/app/service/systems/inbox/group.js @@ -3,6 +3,9 @@ const Service = require('egg').Service; const { parseWhereConditions } = require('../../../lib/query_condition_parser'); +// 从分组服务导入群类型定义,用于两层类型校验 +const { GROUP_TYPES: INBOX_GROUP_TYPES } = require('../../inbox/groups'); + /** * 站内信群管理业务逻辑层。 * 提供群列表查询、禁用、修改等核心能力。 @@ -262,6 +265,25 @@ class InboxGroupService extends Service { const targetGroupType = data.groupType !== undefined ? String(data.groupType).trim() : group.group_type || ''; + + // 两层类型校验:subType 必须在对应 groupType 的合法子类型列表中 + if (data.subType !== undefined && targetGroupType) { + const gtDef = INBOX_GROUP_TYPES.find(gt => gt.type === targetGroupType); + if (!gtDef) { + throw new Error(`无效的群类型: ${targetGroupType}`); + } + const subType = String(data.subType || '').trim(); + if (subType) { + const validKeys = gtDef.subTypes.map(st => st.key); + if (!validKeys.includes(subType)) { + throw new Error( + `子类型 "${subType}" 不在群类型 "${targetGroupType}" 的合法范围内,` + + `可用值: ${validKeys.join(', ')}` + ); + } + } + } + const isExpress = targetGroupType === 'express'; // express_interfaces 处理 @@ -374,6 +396,105 @@ class InboxGroupService extends Service { throw new Error(`系统快递编码 "${trimmed}" 不存在`); } } + + /** + * 根据快递接口ID和快递编码,查询绑定的售后群和揽收群。 + * + * 匹配规则: + * 1. group_type = 'express' + * 2. system_express_code 精确匹配 expressCode + * 3. express_interfaces 为空(未设置)→ 视为匹配所有该快递的接口 + * 4. express_interfaces 不为空 → 必须包含传入的 expressInterfaceId + * + * @param {Object} params 查询参数。 + * @param {number} params.expressInterfaceId 快递接口ID(wms_express_interface.id)。 + * @param {string} params.expressCode 快递编码(wms_express.code)。 + * @param {number} [params.warehouseId] 仓库ID,不传则查所有仓库。 + * @return {Promise<{afterSalesGroups: Array, pickupGroups: Array}>} 售后群和揽收群列表。 + */ + async findGroupsByExpress({ expressInterfaceId, expressCode, warehouseId }) { + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + + const eid = Number(expressInterfaceId); + const code = String(expressCode || '').trim(); + if (!eid || !code) { + throw new Error('expressInterfaceId 和 expressCode 不能为空'); + } + + const where = { + group_type: 'express', + system_express_code: code, + [Op.or]: [ + { express_interfaces: { [Op.or]: [ null, '' ] } }, + { express_interfaces: { [Op.like]: `%${eid}%` } }, + ], + }; + + if (warehouseId) { + where.warehouse_id = Number(warehouseId); + } + + const rows = await ctx.model.InboxGroup.findAll({ + attributes: [ 'id', 'group_name', 'group_id', 'sub_type', 'express_interfaces', 'warehouse_id', 'ext_data' ], + where, + raw: true, + }); + + const afterSalesGroups = rows.filter(r => r.sub_type === 'after_sales'); + const pickupGroups = rows.filter(r => r.sub_type === 'pickup'); + + ctx.logger.info( + `[inbox group] 查快递绑定群 eid=${eid} code=${code} ` + + `after_sales=${afterSalesGroups.length} pickup=${pickupGroups.length}` + ); + + return { afterSalesGroups, pickupGroups }; + } + + /** + * 根据货主ID列表,查询绑定的货主售后群。 + * + * 匹配规则: + * 1. group_type = 'store' + * 2. sub_type = 'after_sales' + * 3. store_id 在传入列表中 + * + * @param {Object} params 查询参数。 + * @param {number[]} params.storeIds 货主ID列表。 + * @param {number} params.warehouseId 仓库ID。 + * @return {Promise} 货主售后群列表 [{group_id, group_name, store_id, ext_data}]。 + */ + async findStoreAfterSalesGroups({ storeIds, warehouseId }) { + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + + const ids = (Array.isArray(storeIds) ? storeIds : [ storeIds ]) + .map(id => Number(id)) + .filter(id => Number.isFinite(id) && id > 0); + + if (ids.length === 0) { + return []; + } + + const rows = await ctx.model.InboxGroup.findAll({ + attributes: [ 'id', 'group_name', 'group_id', 'store_id', 'ext_data' ], + where: { + warehouse_id: Number(warehouseId), + group_type: 'store', + sub_type: 'after_sales', + store_id: { [Op.in]: ids }, + }, + raw: true, + }); + + ctx.logger.info( + `[inbox group] 查货主售后群 warehouse=${warehouseId} ` + + `stores=[${ids.join(',')}] found=${rows.length}` + ); + + return rows; + } } module.exports = InboxGroupService; diff --git a/app/service/systems/pick.js b/app/service/systems/pick.js index d40c11c..9592a60 100644 --- a/app/service/systems/pick.js +++ b/app/service/systems/pick.js @@ -2592,42 +2592,54 @@ class PickSystemService extends Service { throw this.createBusinessError('缺少当前用户仓库上下文 store_id', 400); } - await this.assertPickCartCodeUnique(cartCode, warehouseId); + // 使用事务:唯一性检查 + INSERT + LAST_INSERT_ID() 在同一连接,避免竞态 + const transaction = await ctx.model.transaction(); + let cartId = 0; + try { + await this.assertPickCartCodeUnique(cartCode, warehouseId, 0, transaction); - const insertResult = await ctx.model.query(` - INSERT INTO wms_pick_cart ( - warehouse_id, - cart_code, - cart_name, - status, - create_time, - update_time - ) VALUES ( - :warehouseId, - :cartCode, - :cartName, - :status, - NOW(), - NOW() - ) - `, { - replacements: { - warehouseId, - cartCode, - cartName, - status, - }, - }); + await ctx.model.query(` + INSERT INTO wms_pick_cart ( + warehouse_id, + cart_code, + cart_name, + status, + create_time, + update_time + ) VALUES ( + :warehouseId, + :cartCode, + :cartName, + :status, + NOW(), + NOW() + ) + `, { + replacements: { + warehouseId, + cartCode, + cartName, + status, + }, + transaction, + }); - const insertHead = Array.isArray(insertResult) ? insertResult[0] : null; - const insertMeta = Array.isArray(insertResult) ? insertResult[1] : null; - const cartId = Number( - (insertMeta && (insertMeta.insertId || insertMeta.lastID || insertMeta.id)) - || (insertHead && (insertHead.insertId || insertHead.lastID || insertHead.id)) - || 0 - ); - if (!Number.isInteger(cartId) || cartId <= 0) { - throw this.createBusinessError('拣货车创建失败', 500); + const idRows = await ctx.model.query('SELECT LAST_INSERT_ID() AS cart_id', { + type: ctx.model.QueryTypes.SELECT, + transaction, + }); + cartId = Number(Array.isArray(idRows) && idRows.length > 0 ? (idRows[0].cart_id || 0) : 0); + if (!Number.isInteger(cartId) || cartId <= 0) { + throw new Error('cartId 无效'); + } + + await transaction.commit(); + } catch (error) { + await transaction.rollback(); + if (error.message === 'cartId 无效') { + throw this.createBusinessError('拣货车创建失败', 500); + } + throw error; } const cartRow = await this.getPickCartById(cartId, warehouseId); @@ -2823,6 +2835,104 @@ class PickSystemService extends Service { }; } + /** + * 批量删除拣货车。已绑定任务或存在有效绑定记录的将被跳过。 + * + * @param {Object} params 删除参数。 + * @param {Array} params.ids 拣货车ID列表。 + * @return {Promise} { deleted_ids, skipped_ids, deleted_count, skipped_count } + */ + async pickCartBatchDelete(params = {}) { + const { ctx } = this; + const rawIds = Array.isArray(params && params.ids) ? params.ids : []; + const { warehouseId } = this.resolveOperatorContext(); + + if (!Array.isArray(rawIds) || rawIds.length === 0) { + throw this.createBusinessError('ids 必填且必须为非空数组', 400); + } + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw this.createBusinessError('缺少当前用户仓库上下文 store_id', 400); + } + + // 去重并转为数字,过滤非法值 + const idSet = new Set(); + for (const id of rawIds) { + const num = Number(id); + if (Number.isInteger(num) && num > 0) { + idSet.add(num); + } + } + const ids = Array.from(idSet); + if (ids.length === 0) { + throw this.createBusinessError('ids 中没有合法的拣货车ID', 400); + } + + // 1) 查出当前仓库下这些拣货车的 current_task_id + const cartRows = await ctx.model.query(` + SELECT id, cart_code, current_task_id + FROM wms_pick_cart + WHERE id IN (:ids) + AND warehouse_id = :warehouseId + `, { + replacements: { ids, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + }); + + // 2) 查出有效绑定记录 + const bindingRows = await ctx.model.query(` + SELECT cart_id + FROM wms_pick_task_cart_binding + WHERE cart_id IN (:ids) + AND warehouse_id = :warehouseId + AND is_active = 1 + `, { + replacements: { ids, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + }); + + const bindingCartIds = new Set( + (Array.isArray(bindingRows) ? bindingRows : []).map(r => Number(r.cart_id || 0)).filter(id => id > 0) + ); + + // 3) 分类:已绑定任务 / 有效绑定记录 → skip;其余 → delete + const skipIds = []; + const deleteIds = []; + for (const row of (Array.isArray(cartRows) ? cartRows : [])) { + const cartId = Number(row.id || 0); + if (Number(row.current_task_id || 0) > 0 || bindingCartIds.has(cartId)) { + skipIds.push(cartId); + } else { + deleteIds.push(cartId); + } + } + + // ids 中存在但 cartRows 中不存在的(不属于该仓库或已不存在),也归入 skip + const foundIds = new Set((Array.isArray(cartRows) ? cartRows : []).map(r => Number(r.id || 0))); + for (const id of ids) { + if (!foundIds.has(id) && !skipIds.includes(id)) { + skipIds.push(id); + } + } + + // 4) 执行删除 + if (deleteIds.length > 0) { + await ctx.model.query(` + DELETE FROM wms_pick_cart + WHERE id IN (:deleteIds) + AND warehouse_id = :warehouseId + `, { + replacements: { deleteIds, warehouseId }, + }); + } + + return { + deleted_ids: deleteIds, + skipped_ids: skipIds, + deleted_count: deleteIds.length, + skipped_count: skipIds.length, + }; + } + /** * 查询拣货车详情。 * diff --git a/app/service/systems/pickCart.js b/app/service/systems/pickCart.js index cb449e0..4799b0f 100644 --- a/app/service/systems/pickCart.js +++ b/app/service/systems/pickCart.js @@ -54,6 +54,17 @@ class PickCartSystemService extends Service { return await this.service.systems.pick.pickCartDelete(params); } + /** + * 批量删除拣货车。已绑定任务的将被跳过。 + * + * @param {Object} params 删除参数。 + * @param {Array} params.ids 拣货车ID列表。 + * @return {Promise} 批量删除结果。 + */ + async batchDelete(params = {}) { + return await this.service.systems.pick.pickCartBatchDelete(params); + } + /** * 查询拣货车详情。 * diff --git a/app/service/systems/setting/warehouse.js b/app/service/systems/setting/warehouse.js index 5cf0ca6..58b0512 100644 --- a/app/service/systems/setting/warehouse.js +++ b/app/service/systems/setting/warehouse.js @@ -59,6 +59,14 @@ const WAREHOUSE_SETTING_FIELDS = Object.freeze([ required: false, description: '订单备注命中任一关键字时,跳过自动分配快递,默认 [](不排除任何订单)', }), + Object.freeze({ + key: 'inbox_reply_exclude_keywords', + name: '排除快递回复关键词', + type: 'string_array', + default: [], + required: false, + description: '消息命中任一关键词时仅记录工单不发送回信通知,默认 [](正常回信)', + }), Object.freeze({ key: 'default_express_code', name: '默认快递编码', @@ -228,6 +236,55 @@ const WAREHOUSE_SETTING_FIELDS = Object.freeze([ max: '23:59', description: '截单时间,格式 HH:mm,如 18:00', }), + Object.freeze({ + key: 'after_sale_followup_hours', + name: '售后跟进时间(h)', + type: 'object', + required: false, + description: '按售后类型+子类型设置跟进小时数。_default 为该类型默认值,具体子类型可覆盖', + item_keys: [ + Object.freeze({ key: 'order', name: '订单售后', type: 'object', required: false, description: '订单类型跟进配置', + item_keys: [ + Object.freeze({ key: '_default', name: '默认', type: 'integer', default: 24, min: 1, max: 720 }), + Object.freeze({ key: 'intercept', name: '拦截', type: 'integer', default: 4, min: 1, max: 720 }), + Object.freeze({ key: 'urge', name: '催件', type: 'integer', default: 4, min: 1, max: 720 }), + Object.freeze({ key: 'change_address', name: '改地址', type: 'integer', default: 8, min: 1, max: 720 }), + Object.freeze({ key: 'change_carrier', name: '换快递', type: 'integer', default: 8, min: 1, max: 720 }), + Object.freeze({ key: 'delivery_delay', name: '发货延迟', type: 'integer', default: 12, min: 1, max: 720 }), + Object.freeze({ key: 'damage', name: '破损', type: 'integer', default: 48, min: 1, max: 720 }), + Object.freeze({ key: 'quality_issue', name: '质量问题', type: 'integer', default: 48, min: 1, max: 720 }), + Object.freeze({ key: 'missing_item', name: '少发', type: 'integer', default: 24, min: 1, max: 720 }), + ], + }), + Object.freeze({ key: 'receiving', name: '收货单售后', type: 'object', required: false, description: '收货单类型跟进配置', + item_keys: [ + Object.freeze({ key: '_default', name: '默认', type: 'integer', default: 24, min: 1, max: 720 }), + Object.freeze({ key: 'shortage', name: '少货', type: 'integer', default: 48, min: 1, max: 720 }), + Object.freeze({ key: 'damage', name: '破损', type: 'integer', default: 48, min: 1, max: 720 }), + ], + }), + Object.freeze({ key: 'entry', name: '入库单售后', type: 'object', required: false, description: '入库单类型跟进配置', + item_keys: [ + Object.freeze({ key: '_default', name: '默认', type: 'integer', default: 24, min: 1, max: 720 }), + Object.freeze({ key: 'shortage', name: '少货', type: 'integer', default: 48, min: 1, max: 720 }), + Object.freeze({ key: 'damage', name: '破损', type: 'integer', default: 48, min: 1, max: 720 }), + ], + }), + Object.freeze({ key: 'stockout', name: '出库单售后', type: 'object', required: false, description: '出库单类型跟进配置', + item_keys: [ + Object.freeze({ key: '_default', name: '默认', type: 'integer', default: 24, min: 1, max: 720 }), + Object.freeze({ key: 'return_issue', name: '退货异常', type: 'integer', default: 48, min: 1, max: 720 }), + Object.freeze({ key: 'shortage', name: '少发', type: 'integer', default: 48, min: 1, max: 720 }), + ], + }), + ], + default: Object.freeze({ + order: Object.freeze({ _default: 24, intercept: 4, urge: 4, change_address: 8, change_carrier: 8, delivery_delay: 12, damage: 48, quality_issue: 48, missing_item: 24 }), + receiving: Object.freeze({ _default: 24, shortage: 48, damage: 48 }), + entry: Object.freeze({ _default: 24, shortage: 48, damage: 48 }), + stockout: Object.freeze({ _default: 24, return_issue: 48, shortage: 48 }), + }), + }), Object.freeze({ key: INTERNAL_WAVE_STRATEGY_VERSION_KEY, name: '仓库波次策略版本号', diff --git a/app/service/systems/stock_transaction.js b/app/service/systems/stock_transaction.js index ec4dd98..2e0f6e7 100644 --- a/app/service/systems/stock_transaction.js +++ b/app/service/systems/stock_transaction.js @@ -193,7 +193,7 @@ class StockTransactionService extends Service { return ctx.model.StockTransaction.create(payload, options); } - async list(pageParams = {}, sortParams = {}, groupByBatch = false) { + async list(pageParams = {}, sortParams = {}, groupByBatch = false, keyword = '') { const { ctx, app } = this; const { Op, fn, col, literal } = app.Sequelize; @@ -208,6 +208,21 @@ class StockTransactionService extends Service { ], }; + // keyword 快捷搜索:按 item_code + barcode 匹配,解析为 stock_id IN 条件 + const normalizedKeyword = String(keyword || '').trim(); + if (normalizedKeyword) { + const stockIds = await this._resolveKeywordToStockIds(normalizedKeyword, 'warehouse_id', warehouseId); + if (stockIds.length > 0) { + baseWhere[Op.and].push({ stock_id: { [Op.in]: stockIds } }); + } else { + // keyword 无匹配结果,直接返回空列表 + return { + list: [], + pagination: { page, pageSize, total: 0, totalPages: 0 }, + }; + } + } + // 动态 where 条件 const parsed = ctx.whereParsed; if (parsed && parsed.dynamicConditions && parsed.dynamicConditions.length > 0) { diff --git a/app/service/systems/storage/receiving.js b/app/service/systems/storage/receiving.js index 3529a15..127315b 100644 --- a/app/service/systems/storage/receiving.js +++ b/app/service/systems/storage/receiving.js @@ -2689,9 +2689,14 @@ class ReceivingService extends Service { }), }; + // 判断是否为改绑(明细之前已绑定过其他商品) + const isRebind = receivingDetail.system_product_id + && Number(receivingDetail.system_product_id) !== systemProductId; + // 如果收货明细有条码且商品尚未包含该条码,则自动为商品新增条码 + // 但改绑操作不写入条码(条码属于旧商品上下文,不应污染新商品) const detailBarcode = String(receivingDetail.barcode || '').trim(); - if (detailBarcode && !barcodes.includes(detailBarcode)) { + if (!isRebind && detailBarcode && !barcodes.includes(detailBarcode)) { try { await app.model.StockBarcode.create({ stock_id: systemProductId, @@ -4620,6 +4625,28 @@ class ReceivingService extends Service { return { code: 0, message: '该入库单尚未关联收货单', data: null }; } + // 校验所有 receiving 属于当前仓库 + const validReceivings = await ctx.model.Receiving.findAll({ + where: { id: { [Op.in]: receivingIds }, warehouse_id: warehouseId }, + attributes: [ 'id' ], + raw: true, + }); + const validReceivingIds = validReceivings.map(r => r.id); + if (validReceivingIds.length === 0) { + return { code: 1, message: '收货单不存在或不属于当前仓库', list: [], total: 0 }; + } + + // 2.5 获取入库单的所有合法 stock_id(用于校验收货明细的 system_product_id) + const entryItems = await ctx.model.EntryItems.findAll({ + where: { order_id: normalizedEntryOrderId }, + attributes: [ 'stock_id' ], + raw: true, + }); + const validStockIds = [ ...new Set(entryItems.map(ei => ei.stock_id).filter(Boolean)) ]; + if (validStockIds.length === 0) { + return { code: 0, message: '入库单无明细,无法匹配收货明细', data: null }; + } + // 排除已绑定的收货明细(wms_inbound_direct_log 中有记录且未软删除) const notBoundCondition = app.Sequelize.literal( 'NOT EXISTS (SELECT 1 FROM wms_inbound_direct_log erb WHERE erb.receiving_detail_id = wms_receiving_detail.id AND erb.deleted_at IS NULL)' @@ -4629,7 +4656,8 @@ class ReceivingService extends Service { const details = await ctx.model.ReceivingDetail.findAll({ where: { [Op.and]: [ - { receiving_id: { [Op.in]: receivingIds } }, + { receiving_id: { [Op.in]: validReceivingIds } }, + { system_product_id: { [Op.in]: validStockIds } }, notBoundCondition, ], }, @@ -4667,7 +4695,10 @@ class ReceivingService extends Service { for (const detail of details) { // 优先按明细 ID 精确匹配(托盘唛头场景) if (isNumericBarcode && detail.id === Number(normalizedBarcode)) { - matchedDetails.push(detail); + const sd = stockDetailMap.get(Number(detail.system_product_id)); + if (sd) { + matchedDetails.push(detail); + } continue; } @@ -4687,15 +4718,21 @@ class ReceivingService extends Service { return { code: 0, message: '未找到匹配的收货明细', data: null }; } - const list = matchedDetails.map(matchedDetail => ({ - detail_id: matchedDetail.id, - receiving_id: matchedDetail.receiving_id, - barcode: matchedDetail.barcode || '', - product_name: matchedDetail.product_name || '', - actual_quantity: matchedDetail.actual_quantity || 0, - receiving_status: matchedDetail.receiving_status || '', - stock: stockDetailMap.get(Number(matchedDetail.system_product_id)) || null, - })); + const list = matchedDetails.map(matchedDetail => { + const sd = stockDetailMap.get(Number(matchedDetail.system_product_id)); + const stockBarcode = (sd && Array.isArray(sd.barcodes) && sd.barcodes.length > 0) + ? (sd.barcodes[0].barcode || '') + : ''; + return { + detail_id: matchedDetail.id, + receiving_id: matchedDetail.receiving_id, + barcode: stockBarcode || matchedDetail.barcode || '', + product_name: matchedDetail.product_name || '', + actual_quantity: matchedDetail.actual_quantity || 0, + receiving_status: matchedDetail.receiving_status || '', + stock: sd || null, + }; + }); return { code: 200, diff --git a/app/service/systems/waybill.js b/app/service/systems/waybill.js index 83a80f5..7231985 100644 --- a/app/service/systems/waybill.js +++ b/app/service/systems/waybill.js @@ -149,10 +149,27 @@ class WaybillService extends MainService { * @param {Object} [options.sort] 排序参数 { field, order },默认 create_at desc。 * @return {Promise} 运单列表与分页信息 { list, pagination }。 */ - async list({ where = {}, pagination = {}, sort = {} } = {}) { + async list({ where: rawWhere = {}, pagination = {}, sort = {} } = {}) { const { ctx, app } = this; const { Op } = app.Sequelize; + // 标准化 where 条件:将前端 operator/value 格式(如 {operator:"contains", value:"YT..."})统一转为标准条件对象 + const where = this.normalizeWhereParams(rawWhere); + + /** + * 从 where 条件中提取实际值。 + * 标准化后的条件为 {operator, value} 对象,本函数提取 .value; + * 对于未标准化的原始值(string/number)直接返回。 + * @param {*} c 条件值 + * @param {*} defaultValue 默认值 + * @return {*} 提取后的实际值 + */ + const val = (c, defaultValue) => { + if (c === undefined || c === null) return defaultValue; + if (typeof c === 'object' && !Array.isArray(c) && 'value' in c) return c.value; + return c; + }; + // 仓库隔离 const warehouseId = Number(ctx.user && ctx.user.store_id); if (!warehouseId) { @@ -172,8 +189,9 @@ class WaybillService extends MainService { const queryWhere = { warehouse_id: warehouseId }; // 主单号查询:先通过主单号定位 order_id,再查该 order 下所有运单 - if (where.mainWaybillCode && String(where.mainWaybillCode).trim()) { - const mainCode = String(where.mainWaybillCode).trim(); + const mainWaybillCode = val(where.mainWaybillCode); + if (mainWaybillCode && String(mainWaybillCode).trim()) { + const mainCode = String(mainWaybillCode).trim(); const mainRecord = await ctx.model.OrderExpress.findOne({ where: { waybill_code: mainCode, @@ -195,13 +213,15 @@ class WaybillService extends MainService { } // 运单号模糊搜索 - if (where.waybillCode && String(where.waybillCode).trim()) { - queryWhere.waybill_code = { [Op.like]: `%${String(where.waybillCode).trim()}%` }; + const waybillCode = val(where.waybillCode); + if (waybillCode && String(waybillCode).trim()) { + queryWhere.waybill_code = { [Op.like]: `%${String(waybillCode).trim()}%` }; } // 订单ID等值 - if (where.orderId !== undefined && where.orderId !== null && String(where.orderId).trim() !== '') { - queryWhere.order_id = Number(where.orderId); + const orderId = val(where.orderId); + if (orderId !== undefined && orderId !== null && String(orderId).trim() !== '') { + queryWhere.order_id = Number(orderId); } // 订单号模糊搜索 @@ -211,43 +231,51 @@ class WaybillService extends MainService { // } // 物流公司编码等值 - if (where.logisticsCode && String(where.logisticsCode).trim()) { - queryWhere.logistics_code = String(where.logisticsCode).trim(); + const logisticsCode = val(where.logisticsCode); + if (logisticsCode && String(logisticsCode).trim()) { + queryWhere.logistics_code = String(logisticsCode).trim(); } // 物流接口ID等值 - if (where.logisticsInterfaceId !== undefined && where.logisticsInterfaceId !== null && String(where.logisticsInterfaceId).trim() !== '') { - queryWhere.logistics_interface_id = Number(where.logisticsInterfaceId); + const logisticsInterfaceId = val(where.logisticsInterfaceId); + if (logisticsInterfaceId !== undefined && logisticsInterfaceId !== null && String(logisticsInterfaceId).trim() !== '') { + queryWhere.logistics_interface_id = Number(logisticsInterfaceId); } // 平台编码等值 - if (where.platformCode && String(where.platformCode).trim()) { - queryWhere.platform_code = String(where.platformCode).trim(); + const platformCode = val(where.platformCode); + if (platformCode && String(platformCode).trim()) { + queryWhere.platform_code = String(platformCode).trim(); } // 运单状态等值 - if (where.status !== undefined && where.status !== null && String(where.status).trim() !== '') { - queryWhere.status = Number(where.status); + const statusVal = val(where.status); + if (statusVal !== undefined && statusVal !== null && String(statusVal).trim() !== '') { + queryWhere.status = Number(statusVal); } // 是否退回 - if (where.isBack && String(where.isBack).trim()) { - queryWhere.is_back = String(where.isBack).trim(); + const isBack = val(where.isBack); + if (isBack && String(isBack).trim()) { + queryWhere.is_back = String(isBack).trim(); } // 是否拦截 - if (where.isIntercept && String(where.isIntercept).trim()) { - queryWhere.is_intercept = String(where.isIntercept).trim(); + const isIntercept = val(where.isIntercept); + if (isIntercept && String(isIntercept).trim()) { + queryWhere.is_intercept = String(isIntercept).trim(); } // 是否揽收 - if (where.isGalaxyReceive && String(where.isGalaxyReceive).trim()) { - queryWhere.is_galaxy_receive = String(where.isGalaxyReceive).trim(); + const isGalaxyReceive = val(where.isGalaxyReceive); + if (isGalaxyReceive && String(isGalaxyReceive).trim()) { + queryWhere.is_galaxy_receive = String(isGalaxyReceive).trim(); } // 运单类型:主单号 / 子单号 - if (where.waybillType && String(where.waybillType).trim()) { - const type = String(where.waybillType).trim(); + const waybillType = val(where.waybillType); + if (waybillType && String(waybillType).trim()) { + const type = String(waybillType).trim(); if (type === 'main' || type === '1') { queryWhere.business_key = 1; } else if (type === 'child' || type === '2') { @@ -256,18 +284,21 @@ class WaybillService extends MainService { } // 货主ID等值 - if (where.storeId !== undefined && where.storeId !== null && String(where.storeId).trim() !== '') { - queryWhere.store_id = Number(where.storeId); + const storeId = val(where.storeId); + if (storeId !== undefined && storeId !== null && String(storeId).trim() !== '') { + queryWhere.store_id = Number(storeId); } // 包材ID等值 - if (where.packageMaterialId !== undefined && where.packageMaterialId !== null && String(where.packageMaterialId).trim() !== '') { - queryWhere.package_material_id = Number(where.packageMaterialId); + const packageMaterialId = val(where.packageMaterialId); + if (packageMaterialId !== undefined && packageMaterialId !== null && String(packageMaterialId).trim() !== '') { + queryWhere.package_material_id = Number(packageMaterialId); } // 是否已称重 - if (where.hasWeighingWeight !== undefined && where.hasWeighingWeight !== null && String(where.hasWeighingWeight).trim() !== '') { - const hasWeight = String(where.hasWeighingWeight).trim(); + const hasWeighingWeight = val(where.hasWeighingWeight); + if (hasWeighingWeight !== undefined && hasWeighingWeight !== null && String(hasWeighingWeight).trim() !== '') { + const hasWeight = String(hasWeighingWeight).trim(); if (hasWeight === 'true') { queryWhere.weighing_weight = { [Op.gt]: 0 }; } else if (hasWeight === 'false') { @@ -276,19 +307,22 @@ class WaybillService extends MainService { } // 关键词模糊搜索 - if (where.keyword && String(where.keyword).trim()) { - queryWhere.waybill_code = { [Op.like]: `%${String(where.keyword).trim()}%` }; + const keyword = val(where.keyword); + if (keyword && String(keyword).trim()) { + queryWhere.waybill_code = { [Op.like]: `%${String(keyword).trim()}%` }; } // 创建时间范围 - if (where.createdAtStart && String(where.createdAtStart).trim()) { - const startDate = this.normalizeDate(String(where.createdAtStart).trim(), false); + const createdAtStart = val(where.createdAtStart); + if (createdAtStart && String(createdAtStart).trim()) { + const startDate = this.normalizeDate(String(createdAtStart).trim(), false); if (startDate) { queryWhere.create_at = { ...(queryWhere.create_at || {}), [Op.gte]: startDate }; } } - if (where.createdAtEnd && String(where.createdAtEnd).trim()) { - const endDate = this.normalizeDate(String(where.createdAtEnd).trim(), true); + const createdAtEnd = val(where.createdAtEnd); + if (createdAtEnd && String(createdAtEnd).trim()) { + const endDate = this.normalizeDate(String(createdAtEnd).trim(), true); if (endDate) { queryWhere.create_at = { ...(queryWhere.create_at || {}), [Op.lte]: endDate }; } @@ -302,6 +336,7 @@ class WaybillService extends MainService { attributes: [ 'id', 'waybill_code', 'order_id', 'business_key', 'status', 'warehouse_id', 'store_id', + 'delivery_order_code', 'source_order_codes', 'logistics_code', 'logistics_name', 'logistics_interface_id', 'logistics_interface_name', 'platform_code', @@ -401,13 +436,11 @@ class WaybillService extends MainService { main_waybill_code: mainCode, waybill_type: Number(row.business_key) === 1 ? '主单号' : '子单号', order_id: row.order_id, - // TODO: 快照列未落库,暂时填空;快照就绪后替换为 row.delivery_order_code - order_no: '', + order_no: row.delivery_order_code || row.source_order_codes || '', + source_order_codes: row.source_order_codes || '', warehouse_id: row.warehouse_id, - // TODO: 快照列未落库,暂时填空;快照就绪后替换为 row.warehouse_name_snapshot warehouse_name: '', store_id: row.store_id || 0, - // TODO: 快照列未落库,暂时填空;快照就绪后替换为 row.store_name_snapshot store_name: '', store_remark_name: storeRemarkMap.get(`${row.store_id}:${row.warehouse_id}`) || '', business_key: row.business_key, @@ -636,10 +669,24 @@ class WaybillService extends MainService { * @param {Function} [options.onProgress] 进度回调,接收 `{ status, progress, currentCount, totalCount, message, result }`。 * @return {Promise} 导出结果 { list, current_count, total_count, url }。 */ - async export({ where = {}, sort = {}, exportFields, onProgress } = {}) { + async export({ where: rawWhere = {}, sort = {}, exportFields, onProgress } = {}) { const { ctx, app } = this; const { Op } = app.Sequelize; + // 标准化 where 条件 + const where = this.normalizeWhereParams(rawWhere); + /** + * 从标准化后的 where 条件中提取实际值。 + * @param {*} c 条件值 + * @param {*} defaultValue 默认值 + * @return {*} 提取后的实际值 + */ + const val = (c, defaultValue) => { + if (c === undefined || c === null) return defaultValue; + if (typeof c === 'object' && !Array.isArray(c) && 'value' in c) return c.value; + return c; + }; + // 仓库隔离 const warehouseId = Number(ctx.user && ctx.user.store_id); if (!warehouseId) { @@ -655,8 +702,9 @@ class WaybillService extends MainService { const queryWhere = { warehouse_id: warehouseId }; // 主单号查询 - if (where.mainWaybillCode && String(where.mainWaybillCode).trim()) { - const mainCode = String(where.mainWaybillCode).trim(); + const mainWaybillCodeExport = val(where.mainWaybillCode); + if (mainWaybillCodeExport && String(mainWaybillCodeExport).trim()) { + const mainCode = String(mainWaybillCodeExport).trim(); const mainRecord = await ctx.model.OrderExpress.findOne({ where: { waybill_code: mainCode, @@ -676,36 +724,46 @@ class WaybillService extends MainService { } } - if (where.waybillCode && String(where.waybillCode).trim()) { - queryWhere.waybill_code = { [Op.like]: `%${String(where.waybillCode).trim()}%` }; + const waybillCodeExport = val(where.waybillCode); + if (waybillCodeExport && String(waybillCodeExport).trim()) { + queryWhere.waybill_code = { [Op.like]: `%${String(waybillCodeExport).trim()}%` }; } - if (where.orderId !== undefined && where.orderId !== null && String(where.orderId).trim() !== '') { - queryWhere.order_id = Number(where.orderId); + const orderIdExport = val(where.orderId); + if (orderIdExport !== undefined && orderIdExport !== null && String(orderIdExport).trim() !== '') { + queryWhere.order_id = Number(orderIdExport); } // TODO: 快照字段 delivery_order_code 未落库,暂跳过订单号筛选;快照列就绪后取消注释 - if (where.logisticsCode && String(where.logisticsCode).trim()) { - queryWhere.logistics_code = String(where.logisticsCode).trim(); + const logisticsCodeExport = val(where.logisticsCode); + if (logisticsCodeExport && String(logisticsCodeExport).trim()) { + queryWhere.logistics_code = String(logisticsCodeExport).trim(); } - if (where.logisticsInterfaceId !== undefined && where.logisticsInterfaceId !== null && String(where.logisticsInterfaceId).trim() !== '') { - queryWhere.logistics_interface_id = Number(where.logisticsInterfaceId); + const logisticsInterfaceIdExport = val(where.logisticsInterfaceId); + if (logisticsInterfaceIdExport !== undefined && logisticsInterfaceIdExport !== null && String(logisticsInterfaceIdExport).trim() !== '') { + queryWhere.logistics_interface_id = Number(logisticsInterfaceIdExport); } - if (where.platformCode && String(where.platformCode).trim()) { - queryWhere.platform_code = String(where.platformCode).trim(); + const platformCodeExport = val(where.platformCode); + if (platformCodeExport && String(platformCodeExport).trim()) { + queryWhere.platform_code = String(platformCodeExport).trim(); } - if (where.status !== undefined && where.status !== null && String(where.status).trim() !== '') { - queryWhere.status = Number(where.status); + const statusExport = val(where.status); + if (statusExport !== undefined && statusExport !== null && String(statusExport).trim() !== '') { + queryWhere.status = Number(statusExport); } - if (where.isBack && String(where.isBack).trim()) { - queryWhere.is_back = String(where.isBack).trim(); + const isBackExport = val(where.isBack); + if (isBackExport && String(isBackExport).trim()) { + queryWhere.is_back = String(isBackExport).trim(); } - if (where.isIntercept && String(where.isIntercept).trim()) { - queryWhere.is_intercept = String(where.isIntercept).trim(); + const isInterceptExport = val(where.isIntercept); + if (isInterceptExport && String(isInterceptExport).trim()) { + queryWhere.is_intercept = String(isInterceptExport).trim(); } - if (where.isGalaxyReceive && String(where.isGalaxyReceive).trim()) { - queryWhere.is_galaxy_receive = String(where.isGalaxyReceive).trim(); + const isGalaxyReceiveExport = val(where.isGalaxyReceive); + if (isGalaxyReceiveExport && String(isGalaxyReceiveExport).trim()) { + queryWhere.is_galaxy_receive = String(isGalaxyReceiveExport).trim(); } - if (where.waybillType && String(where.waybillType).trim()) { - const type = String(where.waybillType).trim(); + const waybillTypeExport = val(where.waybillType); + if (waybillTypeExport && String(waybillTypeExport).trim()) { + const type = String(waybillTypeExport).trim(); if (type === 'main' || type === '1') { queryWhere.business_key = 1; } else if (type === 'child' || type === '2') { @@ -713,31 +771,37 @@ class WaybillService extends MainService { } } // 货主ID等值 - if (where.storeId !== undefined && where.storeId !== null && String(where.storeId).trim() !== '') { - queryWhere.store_id = Number(where.storeId); + const storeIdExport = val(where.storeId); + if (storeIdExport !== undefined && storeIdExport !== null && String(storeIdExport).trim() !== '') { + queryWhere.store_id = Number(storeIdExport); } - if (where.packageMaterialId !== undefined && where.packageMaterialId !== null && String(where.packageMaterialId).trim() !== '') { - queryWhere.package_material_id = Number(where.packageMaterialId); + const packageMaterialIdExport = val(where.packageMaterialId); + if (packageMaterialIdExport !== undefined && packageMaterialIdExport !== null && String(packageMaterialIdExport).trim() !== '') { + queryWhere.package_material_id = Number(packageMaterialIdExport); } - if (where.hasWeighingWeight !== undefined && where.hasWeighingWeight !== null && String(where.hasWeighingWeight).trim() !== '') { - const hasWeight = String(where.hasWeighingWeight).trim(); + const hasWeighingWeightExport = val(where.hasWeighingWeight); + if (hasWeighingWeightExport !== undefined && hasWeighingWeightExport !== null && String(hasWeighingWeightExport).trim() !== '') { + const hasWeight = String(hasWeighingWeightExport).trim(); if (hasWeight === 'true') { queryWhere.weighing_weight = { [Op.gt]: 0 }; } else if (hasWeight === 'false') { queryWhere.weighing_weight = { [Op.eq]: 0 }; } } - if (where.keyword && String(where.keyword).trim()) { - queryWhere.waybill_code = { [Op.like]: `%${String(where.keyword).trim()}%` }; + const keywordExport = val(where.keyword); + if (keywordExport && String(keywordExport).trim()) { + queryWhere.waybill_code = { [Op.like]: `%${String(keywordExport).trim()}%` }; } - if (where.createdAtStart && String(where.createdAtStart).trim()) { - const startDate = this.normalizeDate(String(where.createdAtStart).trim(), false); + const createdAtStartExport = val(where.createdAtStart); + if (createdAtStartExport && String(createdAtStartExport).trim()) { + const startDate = this.normalizeDate(String(createdAtStartExport).trim(), false); if (startDate) { queryWhere.create_at = { ...(queryWhere.create_at || {}), [Op.gte]: startDate }; } } - if (where.createdAtEnd && String(where.createdAtEnd).trim()) { - const endDate = this.normalizeDate(String(where.createdAtEnd).trim(), true); + const createdAtEndExport = val(where.createdAtEnd); + if (createdAtEndExport && String(createdAtEndExport).trim()) { + const endDate = this.normalizeDate(String(createdAtEndExport).trim(), true); if (endDate) { queryWhere.create_at = { ...(queryWhere.create_at || {}), [Op.lte]: endDate }; } @@ -768,10 +832,10 @@ class WaybillService extends MainService { for (let page = 0; page < totalPages; page++) { const pageRows = await ctx.model.OrderExpress.findAll({ where: queryWhere, - // TODO: 快照列未落库,暂时只查已有字段;快照就绪后补充 attributes: [ 'id', 'waybill_code', 'order_id', 'business_key', 'status', 'warehouse_id', 'store_id', + 'delivery_order_code', 'source_order_codes', 'logistics_code', 'logistics_name', 'logistics_interface_id', 'logistics_interface_name', 'platform_code', @@ -826,8 +890,8 @@ class WaybillService extends MainService { main_waybill_code: r => mainWaybillMap.get(r.order_id) || r.waybill_code || '', waybill_type: r => (Number(r.business_key) === 1 ? '主单号' : '子单号'), order_id: r => r.order_id, - // TODO: 快照列未落库,暂时填空;快照就绪后替换 - order_no: () => '', + order_no: r => r.delivery_order_code || r.source_order_codes || '', + source_order_codes: r => r.source_order_codes || '', warehouse_id: r => r.warehouse_id, warehouse_name: () => '', store_id: r => r.store_id || 0, @@ -915,6 +979,7 @@ class WaybillService extends MainService { waybill_type: '运单类型', order_id: '订单ID', order_no: '订单号', + source_order_codes: '原始订单号', warehouse_id: '仓库ID', warehouse_name: '仓库名称', store_id: '货主ID', diff --git a/database/designs/after-sale-v2-design.md b/database/designs/after-sale-v2-design.md index 1244763..a9f44f4 100644 --- a/database/designs/after-sale-v2-design.md +++ b/database/designs/after-sale-v2-design.md @@ -93,7 +93,7 @@ erDiagram wms_after_sale_detail { BIGINT id PK "主键" BIGINT after_sale_id FK "关联售后主表" - TINYINT step_status "步骤状态" + VARCHAR step_status "步骤记录时主表状态" BIGINT operator_id "操作人ID" TEXT operator_snapshot "操作人信息快照" VARCHAR action "操作动作" @@ -277,6 +277,7 @@ const AFTER_SALE_TYPES = [ |----|------| | `pending` | 待处理 | | `processing` | 处理中 | +| `pending_feedback` | 等待外部反馈(内部处理完成,等待外部反馈后再决定是否继续处理) | | `completed` | 已完成 | | `closed` | 已关闭 | | `cancelled` | 已取消 | @@ -331,7 +332,7 @@ const AFTER_SALE_TYPES = [ |------|------|------|--------|------| | `id` | `BIGINT UNSIGNED` | ✅ | AUTO | 主键 | | `after_sale_id` | `BIGINT UNSIGNED` | ✅ | — | 关联售后主表ID(`wms_after_sale.id`) | -| `step_status` | `TINYINT UNSIGNED` | ✅ | 0 | 步骤状态:0=待开始,1=进行中,2=已完成,3=已跳过 | +| `step_status` | `VARCHAR(20)` | ✅ | `processing` | 步骤记录时售后主表的状态,与 `wms_after_sale.status` 完全一致: pending / processing / completed / closed / cancelled。每次写入步骤时取主表当前 status 快照 | | `operator_id` | `BIGINT UNSIGNED` | — | NULL | 操作人账户ID(关联 `accounts` 表);可为空,外部系统回调/自动触发的步骤无人操作 | | `operator_snapshot` | `TEXT` | — | NULL | 操作人信息快照(JSON),如 `{"name":"张三","role":"客服"}`,防止账户删除后历史丢失 | | `action` | `VARCHAR(100)` | — | NULL | 操作动作描述,如"确认收货"、"审核驳回"、"发起退款" | @@ -342,18 +343,19 @@ const AFTER_SALE_TYPES = [ | `updated_at` | `DATETIME` | ✅ | `CURRENT_TIMESTAMP ON UPDATE` | 更新时间 | | `deleted_at` | `DATETIME` | — | NULL | 软删除时间 | -#### 3.2.2 步骤状态 `step_status` 枚举 +#### 3.2.2 步骤状态 `step_status` 说明 -| 值 | 说明 | 典型场景 | -|----|------|---------| -| `0` | 待开始 | 步骤尚未触发,等待前置步骤完成 | -| `1` | 进行中 | 步骤正在处理中 | -| `2` | 已完成 | 步骤处理完毕 | -| `3` | 已跳过 | 因条件不满足或审批豁免而跳过此步骤 | +`step_status` 与 `wms_after_sale.status` 完全一致(类型、枚举均相同),每次写入步骤时记录步骤发生时主表的当前状态快照。枚举值: -> **设计考量**:`step_status` 决定步骤的当前状态。步骤按 `created_at` 自然时间排序,通过 `action` 描述步骤内容。后续步骤在前置步骤全部 `completed` 或 `skipped` 后才能开始。步骤可在创建售后单时预置(如按 `type` 生成一套标准步骤),也可在处理过程中动态追加。 -> -> **外部系统触发说明**:当步骤由外部系统触发(如快递签收回调、支付平台退款回调、ERP 同步等)时,`operator_id` 为 NULL,`action` 记录触发来源(如"快递签收回调"、"支付宝退款通知")。这确保自动触发的步骤可追溯来源,同时与人工操作步骤明确区分。 +| 值 | 说明 | +|----|------| +| `pending` | 待处理 | +| `processing` | 处理中 | +| `completed` | 已完成 | +| `closed` | 已关闭 | +| `cancelled` | 已取消 | + +> **设计考量**:`step_status` 记录的是"该步骤发生时,售后主表处于什么状态",而非步骤本身的"进行中/已完成"标记。这使得每条步骤都能直接追溯到该步骤执行时的工单状态上下文,无需 JOIN 主表查阅历史状态。步骤按 `created_at` 自然时间排序。 ### 3.2.3 附件关联 @@ -426,8 +428,11 @@ stateDiagram-v2 [*] --> pending: 创建售后单 pending --> processing: 指派处理人 / 开始处理 pending --> cancelled: 取消 + processing --> pending_feedback: 内部处理完毕,等待外部反馈 processing --> completed: 处理完成 processing --> closed: 强制关闭 + pending_feedback --> processing: 收到外部反馈,继续处理 + pending_feedback --> completed: 外部反馈确认完成 completed --> [*] closed --> [*] cancelled --> [*] @@ -437,9 +442,11 @@ stateDiagram-v2 |------|---------|------| | `pending` → `processing` | 指派处理人 or 手动开始处理 | 通过 `wms_after_sale_detail` 记录的处理步骤追踪 | | `pending` → `cancelled` | 创建人取消 | 仅待处理状态可取消 | +| `processing` → `pending_feedback` | 内部处理完毕,等待外部反馈 | 如已将拦截信息发给运方,等待运方反馈拦截结果 | | `processing` → `completed` | 处理完毕 | 写入 `resolution` + `resolved_at` | | `processing` → `closed` | 管理员强制关闭 | 如重复单、无效单等 | -| 转单(跨角色组) | 客服转仓库 / 仓库转财务等 | 更新 `role_group` 为目标角色组,如 `customer_service` → `warehouse`;同时可在 `wms_after_sale_detail` 记录转单步骤 | +| `pending_feedback` → `processing` | 收到外部反馈,继续处理 | 如运方反馈已拦截/未拦截,回到内部通知客户 | +| `pending_feedback` → `completed` | 外部反馈确认完成 | 如平台退款回调确认到账 | **理赔状态流转**(仓库理赔 & 运方理赔通用):`pending` → `reviewing` → `approved` → `paid`,任意阶段可 → `rejected`,或走 `monthly`(月结)通道。 @@ -457,9 +464,9 @@ stateDiagram-v2 ├─ waybill_id / waybill_no: 客户寄回的快递单号 ├─ receiving_id / receiving_no: 仓库收货单 └─ 进度步骤: - ├─ step_status=2(已完成), operator_id=1001, action=客服接单-受理退货申请 - ├─ step_status=2(已完成), operator_id=2001, action=仓库收货-确认收货入库 - └─ step_status=0(待开始), action=退款打款 + ├─ step_status=processing, operator_id=1001, action=客服接单-受理退货申请 + ├─ step_status=processing, operator_id=2001, action=仓库收货-确认收货入库 + └─ step_status=processing, action=退款打款 ``` > **转单说明**:当客服接单后发现需要仓库核实实物时,可将 `role_group` 从 `customer_service` 更新为 `warehouse`,仓库组即可在自己的待办列表中看到该工单。 @@ -471,9 +478,9 @@ stateDiagram-v2 ├─ waybill_id / waybill_no: 客户寄回的快递单号 ├─ order_delivery_id / order_delivery_no: 仓库补发的发货订单 └─ 进度步骤: - ├─ step_status=2(已完成), action=客服接单-确认换货申请 - ├─ step_status=2(已完成), action=退回入库-客户退回商品已入库 - └─ step_status=1(进行中), action=补发换货-仓库补发新商品 + ├─ step_status=processing, action=客服接单-确认换货申请 + ├─ step_status=processing, action=退回入库-客户退回商品已入库 + └─ step_status=processing, action=补发换货-仓库补发新商品 ``` ### 场景3:订单售后(仓库理赔) @@ -482,9 +489,9 @@ stateDiagram-v2 售后单 type=order, sub_type=damage ├─ claim_needed=1, claim_amount=50.00, claim_status=pending └─ 进度步骤: - ├─ step_status=2(已完成), action=客服接单-受理仓库理赔 - ├─ step_status=2(已完成), action=核实定损, remark=仓库出库破损, 核定赔偿50元 - └─ step_status=1(进行中), action=审批打款 + ├─ step_status=processing, action=客服接单-受理仓库理赔 + ├─ step_status=processing, action=核实定损, remark=仓库出库破损, 核定赔偿50元 + └─ step_status=processing, action=审批打款 ``` ### 场景3b:订单售后(运方理赔) @@ -494,9 +501,9 @@ stateDiagram-v2 ├─ carrier_claim_needed=1, carrier_claim_amount=200.00, carrier_claim_status=pending ├─ waybill_id / waybill_no: 涉损运单 └─ 进度步骤: - ├─ step_status=2(已完成), action=客服接单-受理运方理赔 - ├─ step_status=2(已完成), action=核实定损, remark=运输途中破损, 核定赔偿200元 - └─ step_status=1(进行中), action=快递审批 + ├─ step_status=processing, action=客服接单-受理运方理赔 + ├─ step_status=processing, action=核实定损, remark=运输途中破损, 核定赔偿200元 + └─ step_status=processing, action=快递审批 ``` > **说明**:仓库理赔与运方理赔可同时存在(如货物在仓库出库&运输途中均发生破损),分别使用 `claim_*` 和 `carrier_claim_*` 字段组记录。 @@ -509,10 +516,10 @@ stateDiagram-v2 ├─ receiving_id / receiving_no: 仓库收货单 ├─ order_stockout_id / order_stockout_no: 退货出库单 └─ 进度步骤: - ├─ step_status=2(已完成), action=客服接单-批量退货受理 - ├─ step_status=2(已完成), operator_id=3001, action=验货签收, remark=SKU001×3, SKU002×1 均完好(可挂附件:破损照片 × 2) - ├─ step_status=2(已完成), action=退货入库 - └─ step_status=0(待开始), action=退款打款 + ├─ step_status=processing, action=客服接单-批量退货受理 + ├─ step_status=processing, operator_id=3001, action=验货签收, remark=SKU001×3, SKU002×1 均完好(可挂附件:破损照片 × 2) + ├─ step_status=processing, action=退货入库 + └─ step_status=processing, action=退款打款 ``` > **说明**:此场景中 `role_group=warehouse` 表示当前由仓库组负责验货入库环节;验货完成后如需财务退款,转单时将 `role_group` 更新为 `finance`。 @@ -601,13 +608,16 @@ app/model/after_sale_detail.js → wms_after_sale_detail | 生产组-主管 | 517 | 519, 520, 521 | 522, 508, 510, 512 | | 拣货组-组长 | 517 | 519, 520, 521 | 522, 508, 510, 512 | | 财务 | 518 | 519, 520, 521 | 522, 508 | +| 经理 | — | 519, 520, 521 | 522, 523, 508, 509, 510, 511, 512, 513, 514, 515 | > - 客服:全部权限(创建、更新、转单、查理赔) > - 仓库:只读查询 + 更新处理结果 > - 生产组-主管 / 拣货组-组长:共享仓库组视角(同仓库组权限),处理退货验货入库等实物操作。普通生产组员工不授权任何售后权限。 > - 财务:只读查询(理赔审核通过财务系统操作,不走 WMS) +> - 经理:全部售后权限 > **生产组其他角色**(普通员工、复核、其他普工)不授权任何售后权限。 +> **财务组角色**:role_code=`finance`,role_name=`财务组`,自动创建并授权。 --- @@ -750,14 +760,13 @@ app/model/after_sale_detail.js → wms_after_sale_detail ```json { "method": "afterSale.handleWorkOrder", - "description": "处理售后工单。员工在工作列表中对工单进行操作,写入进度步骤并绑定附件。操作人信息从登录上下文自动获取。非客服组处理完成后自动转回客服组继续跟进。", + "description": "处理售后工单。员工在工作列表中对工单进行操作,写入进度步骤并绑定附件。操作人信息从登录上下文自动获取。步骤 action 由服务端固定为\"处理工单\",前端无需传入。status 不填或填错默认 processing。非客服组处理完成后自动转回客服组继续跟进。", "isNeedAuth": false, "isNeedLogin": true, "params": [ { "name": "id", "type": "integer", "required": true, "source": "body", "description": "售后工单主表ID(wms_after_sale.id)" }, - { "name": "status", "type": "string", "required": false, "source": "body", "description": "更新售后单状态(pending/processing/completed/closed),不传则保持当前状态" }, - { "name": "action", "type": "string", "required": true, "source": "body", "description": "操作动作描述,如"客服接单"、"仓库验货"、"确认收货入库"、"退款打款"" }, - { "name": "remark", "type": "string", "required": false, "source": "body", "description": "处理备注/消息主体" }, + { "name": "status", "type": "string", "required": false, "source": "body", "description": "更新售后单状态: processing | completed | closed | cancelled。不填或填错默认 processing。注意:pending 不适用于处理操作" }, + { "name": "remark", "type": "string", "required": false, "source": "body", "description": "处理备注" }, { "name": "attachment_ids", "type": "array", "required": false, "source": "body", "description": "附件 file_id 数组,如 [123, 456]。处理时自动绑定到本次步骤。" } ], "response": [ @@ -766,7 +775,6 @@ app/model/after_sale_detail.js → wms_after_sale_detail ], "errors": [ { "code": 400, "message": "工单不存在或参数缺失" }, - { "code": 403, "message": "无权限处理该工单(role_group 不匹配)" }, { "code": 500, "message": "处理失败" } ] } @@ -777,8 +785,8 @@ app/model/after_sale_detail.js → wms_after_sale_detail 1. 校验工单 `id` 存在,且当前用户 `role_group` 与工单 `role_group` 匹配(否则 403) 2. 从登录上下文(JWT token)提取操作人 `operator_id` 和 `operator_snapshot` 3. 写入 `wms_after_sale_detail`: - - `step_status = 2`(已完成) - - `action` = 入参 `action` + - `step_status` = 主表当前 status(由 safeStatus 决定,不填或填错默认 processing) + - `action` = 服务端固定 `"处理工单"` - `remark` = 入参 `remark` - `operator_id` / `operator_snapshot` = 当前用户 - `started_at = now`, `completed_at = now` @@ -786,9 +794,9 @@ app/model/after_sale_detail.js → wms_after_sale_detail - `business_type = 'after_sale_detail'` - `business_id` = 刚写入的 `detail.id` - `file_id = attachment_id` -5. 若传入了 `status`,更新 `wms_after_sale.status` -6. 若当前 `role_group` ≠ `'customer_service'` 且 `status` ≠ `'completed'`,自动将 `role_group` 回设为 `'customer_service'`(仓库/财务处理完本环节后自动退回客服组继续跟进) -7. 若 `status = 'completed'`,同时写入 `resolution` 和 `resolved_at` +5. 更新 `wms_after_sale.status`:始终写入 safeStatus(默认 processing,白名单校验,不含 pending) +6. 若当前 `role_group` ≠ `'customer_service'` 且 status ≠ `'completed'`,自动将 `role_group` 回设为 `'customer_service'`(仓库/财务处理完本环节后自动退回客服组继续跟进) +7. 若 status = `'completed'`,同时写入 `resolution` 和 `resolved_at` ### 10.8 理赔登记 `afterSale.registerClaim` @@ -826,7 +834,7 @@ app/model/after_sale_detail.js → wms_after_sale_detail 1. 校验工单 `id` 存在 2. 从登录上下文提取操作人信息 3. 更新 `wms_after_sale` 中传入的非空理赔字段(`claim_needed/amount/status`、`carrier_claim_needed/amount/status`) -4. 写入 `wms_after_sale_detail`(step_status=2,action/remark/operator) +4. 写入 `wms_after_sale_detail`(step_status=主表当前 status,action/remark/operator) 5. 若有 `attachment_ids`,绑定到本次步骤 **使用场景:** diff --git a/database/migrations/20260809140000-add-after-sale-workorder-pages.js b/database/migrations/20260809140000-add-after-sale-workorder-pages.js new file mode 100644 index 0000000..370dd2f --- /dev/null +++ b/database/migrations/20260809140000-add-after-sale-workorder-pages.js @@ -0,0 +1,42 @@ +'use strict'; + +/** + * 新增售后模块页面权限(售后工单 + 工单列表)。 + * + * 新增: + * Web Pages: + * 524 — afterSale.workOrder 售后工单(根菜单) + * 525 — afterSale.workOrder.list 工单列表(子页面,parent_id=524) + * + * 幂等设计:使用 INSERT IGNORE,已存在的 id 不会重复插入。 + */ + +const TABLE = 'wms_permission'; +const COLUMNS = 'id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at'; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + const pages = [ + [524, 'afterSale.workOrder', null, 'afterSale.workOrder', null, '售后工单', null, 0, 0, null, 'web_pages', 15, 1], + [525, 'afterSale.workOrder.list', null, 'afterSale.workOrder.list', null, '工单列表', null, 0, 0, 524, 'web_pages', 0, 1], + ]; + + for (const [id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status] of pages) { + await queryInterface.sequelize.query( + `INSERT IGNORE INTO \`${TABLE}\` (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`, + { replacements: [id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status] } + ); + } + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + const ids = [524, 525]; + const placeholders = ids.map(() => '?').join(', '); + await queryInterface.sequelize.query( + `DELETE FROM \`${TABLE}\` WHERE id IN (${placeholders})`, + { replacements: ids } + ); + }, +}; diff --git a/database/migrations/20260809140100-grant-after-sale-workorder-pages.js b/database/migrations/20260809140100-grant-after-sale-workorder-pages.js new file mode 100644 index 0000000..1e4f238 --- /dev/null +++ b/database/migrations/20260809140100-grant-after-sale-workorder-pages.js @@ -0,0 +1,103 @@ +'use strict'; + +/** + * 为售后模块新增页面权限授权,并创建财务组角色。 + * + * 操作: + * 1. 新建财务组角色(role_code='finance') + * 2. 为以下角色追加页面权限 524 (afterSale.workOrder)、525 (afterSale.workOrder.list): + * - 经理 (role_code=2) + * - 客服组-主管 (role_code=05) + * - 客服组-员工 (role_code=04) + * - 仓库组-主管 (role_code=warehouse) + * - 仓库组-员工 (role_code=warehouse_role) + * - 生产组-主管 (role_code=03) + * - 生产组-拣货 (role_code=021) + * + * 幂等设计: + * - 财务组角色使用 INSERT IGNORE,已存在则跳过 + * - 权限追加使用 JSON_ARRAY_APPEND,不重复添加 + */ + +const NEW_PAGE_IDS = [524, 525]; + +// 财务组基础权限:block(518) + 所有web_pages(519,520,521,524,525) + 只读API(522,508) +const FINANCE_PERMISSIONS = [518, 519, 520, 521, 524, 525, 522, 508]; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + const { sequelize } = queryInterface; + + // ── 1. 创建财务组角色(如果不存在)── + await sequelize.query(` + INSERT IGNORE INTO wms_role (role_code, role_name, description, role_type, scope, is_system, status, pid, created_by, permissions, created_at, updated_at) + VALUES ('finance', '财务组', '售后模块财务审核角色', 1, 1, 1, 1, 8, 1, ?, NOW(), NOW()) + `, { + replacements: [JSON.stringify(FINANCE_PERMISSIONS)], + }); + + // ── 2. 为已有角色追加页面权限 ── + const targetRoleCodes = ['2', '05', '04', 'warehouse', 'warehouse_role', '03', '021']; + + for (const roleCode of targetRoleCodes) { + for (const permId of NEW_PAGE_IDS) { + // 仅当该角色的 permissions 数组中不包含此权限ID时才追加 + // JSON_CONTAINS 检查是否已存在 + // 注意:permissions 列为 LONGTEXT,JSON 函数需显式 CAST + // 安全守卫:permissions 必须是合法 JSON 数组(以 [ 开头且非 NULL), + // 避免在非法 JSON(如旧版范围格式 [4-121])或 NULL 上执行 JSON_ARRAY_APPEND 导致权限被清空。 + await sequelize.query( + `UPDATE wms_role + SET permissions = JSON_ARRAY_APPEND(CAST(permissions AS JSON), '$', CAST(? AS UNSIGNED)), + updated_at = NOW() + WHERE role_code = ? + AND permissions IS NOT NULL + AND permissions != '' + AND permissions != '*' + AND JSON_VALID(permissions) = 1 + AND LEFT(permissions, 1) = '[' + AND JSON_CONTAINS(CAST(permissions AS JSON), CAST(? AS JSON), '$') = 0`, + { replacements: [permId, roleCode, String(permId)] } + ); + } + } + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + const { sequelize } = queryInterface; + + // ── 1. 移除财务组角色 ── + await sequelize.query( + "DELETE FROM wms_role WHERE role_code = 'finance'" + ); + + // ── 2. 从各角色移除页面权限 ── + const targetRoleCodes = ['2', '05', '04', 'warehouse', 'warehouse_role', '03', '021']; + + for (const roleCode of targetRoleCodes) { + for (const permId of NEW_PAGE_IDS) { + // 从 JSON 数组中移除指定值(MySQL 5.7+ 无直接 JSON_REMOVE_BY_VALUE,用 JSON_SEARCH) + // 注意:permissions 列为 LONGTEXT,JSON 函数需显式 CAST + // 安全守卫:同 up(),防止在非法 JSON 上操作 + await sequelize.query( + `UPDATE wms_role + SET permissions = JSON_REMOVE( + CAST(permissions AS JSON), + REPLACE(JSON_UNQUOTE(JSON_SEARCH(CAST(permissions AS JSON), 'one', CAST(? AS CHAR), NULL, '$')), '', '') + ), + updated_at = NOW() + WHERE role_code = ? + AND permissions IS NOT NULL + AND permissions != '' + AND permissions != '*' + AND JSON_VALID(permissions) = 1 + AND LEFT(permissions, 1) = '[' + AND JSON_CONTAINS(CAST(permissions AS JSON), CAST(? AS JSON), '$') = 1`, + { replacements: [permId, roleCode, String(permId)] } + ); + } + } + }, +}; diff --git a/database/migrations/20260810140000-alter-wms-after-sale-detail-step-status-to-varchar.js b/database/migrations/20260810140000-alter-wms-after-sale-detail-step-status-to-varchar.js new file mode 100644 index 0000000..eeff6e7 --- /dev/null +++ b/database/migrations/20260810140000-alter-wms-after-sale-detail-step-status-to-varchar.js @@ -0,0 +1,27 @@ +'use strict'; + +const TABLE_NAME = 'wms_after_sale_detail'; + +module.exports = { + up: async queryInterface => { + // 将 step_status 从 TINYINT 改为 VARCHAR(20),与 wms_after_sale.status 枚举保持一致 + // 使用原生 SQL 一步完成:改类型 + 更新已有数据为 processing + await queryInterface.sequelize.query( + `ALTER TABLE \`${TABLE_NAME}\` MODIFY COLUMN step_status VARCHAR(20) NOT NULL DEFAULT 'processing' COMMENT '步骤记录时售后主表的状态,与 wms_after_sale.status 一致: pending | processing | pending_feedback | completed | closed | cancelled'` + ); + // 已有数据(原 TINYINT 值)统一回填为 processing + await queryInterface.sequelize.query( + `UPDATE \`${TABLE_NAME}\` SET step_status = 'processing'` + ); + }, + + down: async queryInterface => { + // 回退:先更新数据,再改回 TINYINT + await queryInterface.sequelize.query( + `UPDATE \`${TABLE_NAME}\` SET step_status = '2'` + ); + await queryInterface.sequelize.query( + `ALTER TABLE \`${TABLE_NAME}\` MODIFY COLUMN step_status TINYINT(3) UNSIGNED NOT NULL DEFAULT 2 COMMENT '步骤状态:0=待开始,1=进行中,2=已完成,3=已跳过'` + ); + }, +}; diff --git a/database/migrations/20260811100000-add-followup-at-to-wms-after-sale.js b/database/migrations/20260811100000-add-followup-at-to-wms-after-sale.js new file mode 100644 index 0000000..b90618d --- /dev/null +++ b/database/migrations/20260811100000-add-followup-at-to-wms-after-sale.js @@ -0,0 +1,17 @@ +'use strict'; + +const TABLE_NAME = 'wms_after_sale'; + +module.exports = { + up: async queryInterface => { + await queryInterface.sequelize.query( + `ALTER TABLE \`${TABLE_NAME}\` ADD COLUMN followup_at DATETIME NULL DEFAULT NULL COMMENT '下次跟进时间:设为 pending_feedback 时可指定,超时后需二次跟进' AFTER resolved_at` + ); + }, + + down: async queryInterface => { + await queryInterface.sequelize.query( + `ALTER TABLE \`${TABLE_NAME}\` DROP COLUMN followup_at` + ); + }, +}; diff --git a/database/migrations/20260811120000-add-ext-data-to-inbox-group.js b/database/migrations/20260811120000-add-ext-data-to-inbox-group.js new file mode 100644 index 0000000..402f25e --- /dev/null +++ b/database/migrations/20260811120000-add-ext-data-to-inbox-group.js @@ -0,0 +1,20 @@ +'use strict'; + +const TABLE_NAME = 'wms_inbox_group'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const columns = await queryInterface.describeTable(TABLE_NAME); + if (columns.ext_data) return; + + await queryInterface.addColumn(TABLE_NAME, 'ext_data', { + type: Sequelize.JSON, + allowNull: true, + comment: '群扩展数据(IM平台信息等)', + }); + }, + + down: async queryInterface => { + await queryInterface.removeColumn(TABLE_NAME, 'ext_data'); + }, +}; diff --git a/database/migrations/20260812120000-add-order-id-to-after-sale.js b/database/migrations/20260812120000-add-order-id-to-after-sale.js new file mode 100644 index 0000000..0b0c1f8 --- /dev/null +++ b/database/migrations/20260812120000-add-order-id-to-after-sale.js @@ -0,0 +1,16 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.addColumn('wms_after_sale', 'order_id', { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '订单ID(关联 wms_order.id),快递反馈建单时从 wms_order_express.order_id 填入', + after: 'waybill_no', + }); + }, + + async down(queryInterface) { + await queryInterface.removeColumn('wms_after_sale', 'order_id'); + }, +}; diff --git a/methods/changes/system.json b/methods/changes/system.json index 6879912..a22f3e1 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,99 @@ [ + { + "version": "2026.08.12-confirmIntercept-doc", + "date": "2026-08-12", + "type": "updated", + "summary": "order.recheckOrder.confirmIntercept 文档描述补全:补充释放储位分配、释放订单锁等副作用说明,明确各副作用失败不阻断主流程的容错语义", + "methods": [ + "order.recheckOrder.confirmIntercept" + ], + "notes": [ + "description 补充:拦截成功后会释放储位分配(cancelAllocateStorage)与订单锁(lock_status=none)", + "description 补充:储位释放、锁释放、日志写入失败均不影响主流程(try/catch 容错)", + "仅文档变更,不修改业务代码" + ], + "module": "order" + }, + { + "version": "2026.08.12-interceptScan", + "date": "2026-08-12", + "type": "added", + "summary": "order.recheckOrder.interceptScan 新增拦截扫描接口:通过运单号查找运单,标记退回+拦截(is_back='Y', is_intercept='Y');运单记录不存在时自动创建补充;处理关联售后工单(写入「库内拦截成功」并完结);订单级拦截覆盖所有面单含子面单(与 confirmIntercept 一致)", + "methods": [ + "order.recheckOrder.interceptScan" + ], + "notes": [ + "入参:waybill_code(string, required),运单号", + "运单记录不存在时自动创建(INSERT wms_order_express),而非抛 404,确保缺失快递被补充", + "同时设置 is_back='Y' 和 is_intercept='Y'", + "查 wms_after_sale 表(未完结工单),命中则调用 handleWorkOrder 写入「库内拦截成功」步骤并置 status=completed;工单处理失败不阻断主流程", + "订单拦截与 confirmIntercept 一致:只要有 order_id 即更新 wms_order_delivery.intercept_status = intercepted_at_warehouse,并释放储位分配与订单锁,写入 ORDER_INTERCEPT_CONFIRM 操作日志;不再区分 business_key,子面单同样会触发订单级拦截", + "免权限/免日志/免鉴权(与 confirmIntercept 同级)", + "代码变更:recheckOrder.js 构造函数 + interceptScan 方法(~180行);methods/system.json 新增 API 文档" + ], + "module": "order" + }, + { + "version": "2026.08.10-storageTransaction-keyword", + "date": "2026-08-10", + "type": "updated", + "summary": "storage.transaction.list 新增 keyword 快捷搜索参数,支持按 item_code(商品编码) 和 barcode(条码) 模糊匹配,内部解析为 stock_id 列表后以 IN 条件合并到查询中", + "methods": [ + "storage.transaction.list" + ], + "notes": [ + "新增 keyword 参数(string, optional),搜索范围为 stock_warehouse.item_code + stock_barcodes.barcode", + "keyword 解析复用已有 _resolveKeywordToStockIds 方法,与 stock.report.search 的 keyword 解析逻辑一致", + "keyword 可与 where 条件叠加使用(交集),无匹配结果时直接返回空列表", + "代码变更:stock_transaction.js list() 增加 keyword 参数并在 baseWhere 中注入 stock_id IN 条件;systemMethods/storage/transaction.js 透传 keyword" + ], + "module": "storage" + }, + { + "version": "2026.08.10-stockTransaction-keyword-doc", + "date": "2026-08-10", + "type": "updated", + "summary": "stock.transaction.list 补全 keyword 快捷搜索参数文档。代码层已支持 keyword(通过 queryList → _resolveKeywordToStockIds),本次仅补文档", + "methods": [ + "stock.transaction.list" + ], + "notes": [ + "新增 where.keyword 参数文档(string, optional),搜索范围为 stock_warehouse.item_code/item_name/goods_code + stock_barcodes.barcode + SKU ID", + "keyword 解析复用已有 _resolveKeywordToStockIds 方法,与 stock.report.search 逻辑一致", + "keyword 与 stock_ids 互斥(keyword 优先),无匹配结果时返回空列表", + "仅文档变更,不修改业务代码" + ], + "module": "stock" + }, + { + "version": "2026.08.09-afterSale-doc", + "date": "2026-08-09", + "type": "updated", + "summary": "补全 afterSale 组全部 11 个 method 的文档:workList/auditList/detail/create/transfer/handleWorkOrder/registerClaim/export/exportTaskProgress/workCount 的 params 与 response 补全 description,移除 create 中冗余 warehouse_id 参数(后端自动注入),明确各枚举值、关联表、业务语义。", + "methods": [ + "afterSale.workList", + "afterSale.auditList", + "afterSale.detail", + "afterSale.create", + "afterSale.transfer", + "afterSale.handleWorkOrder", + "afterSale.registerClaim", + "afterSale.export", + "afterSale.exportTaskProgress", + "afterSale.workCount" + ], + "notes": [ + "afterSale.create:移除 warehouse_id 参数(后端从 ctx.user.store_id 自动注入),补全所有 12 个参数的 description(含 type/sub_type 枚举值),response 新增 status 和 role_group 字段。", + "afterSale.transfer:补全 id/role_group/remark 的 description,response 新增 role_group 字段。", + "afterSale.handleWorkOrder:补全 action/status/attachment_ids 的 description,明确 action 示例和 status 枚举。", + "afterSale.registerClaim:补全 10 个参数的 description,明确 claim_status/carrier_claim_status 枚举值(pending/reviewing/approved/paid/monthly/rejected)。", + "afterSale.workList/auditList:补全 pagination/where/sort 与 response 的 description。", + "afterSale.export/exportTaskProgress:补全参数和响应的 description,明确 task_id 用途。", + "afterSale.workCount:已有完整 description,本次未修改。", + "仅文档变更,不修改任何业务代码或接口语义。" + ], + "module": "afterSale" + }, { "version": "2026.08.07-stockout-express", "date": "2026-08-07", @@ -5415,5 +5510,248 @@ "apiApp.update: sign_method 字段改为不可修改,传入即报错", "apiApp.list / apiApp.detail: sign_method 响应描述更新为「当前仅支持 md5」" ] + }, + { + "version": "2026.08.10-afterSale-handleWorkOrder-remove-action", + "date": "2026-08-10", + "type": "changed", + "summary": "afterSale.handleWorkOrder 移除 action 参数:action 不再由前端传入,改为服务端固定写入\"处理工单\";处理说明统一使用 remark 字段。", + "methods": [ + "afterSale.handleWorkOrder" + ], + "notes": [ + "移除 action 参数(原为必填 string,前端传入操作动作描述),前端不再需要也不接受此参数。", + "步骤记录的 action 字段由服务端在 systems/afterSale.js handleWorkOrder 中硬编码为\"处理工单\"。", + "处理说明统一使用 remark 字段承载。", + "代码变更:systemMethods/afterSale.js handleWorkOrder 移除 action 解构与必填校验;systems/afterSale.js handleWorkOrder 移除 message 参数,addStep action 固定为\"处理工单\"。" + ], + "module": "afterSale" + }, + { + "version": "2026.08.10-afterSale-handleWorkOrder-status-whitelist", + "date": "2026-08-10", + "type": "changed", + "summary": "afterSale.handleWorkOrder 新增 status 枚举白名单校验:status 必须与 wms_after_sale 主表 AFTER_SALE_STATUS 枚举一致(pending/processing/completed/closed/cancelled),补全 cancelled 枚举值文档。", + "methods": [ + "afterSale.handleWorkOrder" + ], + "notes": [ + "status 参数新增枚举白名单校验:从 AfterSale.AFTER_SALE_STATUS 取 key 列表,不在白名单内返回 400。", + "文档 status 枚举值补全 cancelled,与主表模型保持一致(pending | processing | completed | closed | cancelled)。", + "校验同时在 systemMethods/afterSale.js(方法层)和 systems/afterSale.js(业务层)两层生效。", + "仅代码校验增强 + 文档修正,不改变业务语义。" + ], + "module": "afterSale" + }, + { + "version": "2026.08.10-afterSale-handleWorkOrder-status-default-processing", + "date": "2026-08-10", + "type": "changed", + "summary": "afterSale.handleWorkOrder status 参数改为容错模式:不填或填错时默认 processing(处理中),不再返回 400 错误。status 始终写入主表。", + "methods": [ + "afterSale.handleWorkOrder" + ], + "notes": [ + "status 参数行为变更:原来不传时保持当前状态(有 if 判断),现在不填或填错默认 processing,始终写入主表。", + "校验方式从白名单拒绝改为容错兜底:safeStatus = (targetStatus 合法) ? targetStatus : 'processing'。", + "updateFields.status 从条件写入改为始终写入 safeStatus。", + "role_group 回退判断同步从 targetStatus 改为 safeStatus。", + "代码变更:systemMethods/afterSale.js + systems/afterSale.js 两层均改为容错逻辑。" + ], + "module": "afterSale" + }, + { + "version": "2026.08.10-afterSale-handleWorkOrder-exclude-pending", + "date": "2026-08-10", + "type": "changed", + "summary": "afterSale.handleWorkOrder status 白名单排除 pending:pending 是创建默认值(表示尚未处理),处理工单时不允许回退到此状态。", + "methods": [ + "afterSale.handleWorkOrder" + ], + "notes": [ + "handleWorkOrder 允许的 status 从全部 AFTER_SALE_STATUS 中排除 pending,剩余:processing | completed | closed | cancelled。", + "若前端传 status=pending 视为填错,容错兜底为 processing。", + "代码变更:两处 ALLOWED_STATUSES 增加 .filter(s => s !== 'pending')。" + ], + "module": "afterSale" + }, + { + "version": "2026.08.10-afterSale-step-status-align-main-table", + "date": "2026-08-10", + "type": "changed", + "summary": "wms_after_sale_detail.step_status 改为与 wms_after_sale.status 完全一致:字段类型从 TINYINT 改为 VARCHAR(20),每次写入步骤时记录主表当前 status 快照。", + "methods": [ + "afterSale.handleWorkOrder" + ], + "notes": [ + "DB 迁移:20260810140000-alter-wms-after-sale-detail-step-status-to-varchar.js — step_status 从 TINYINT UNSIGNED 改为 STRING(20),已有数据回填 processing。", + "Model:after_sale_detail.js 移除 TINYINT 引用,step_status 改为 STRING(20),STEP_STATUS 枚举对齐主表 AFTER_SALE_STATUS。", + "addStep 默认值从 2 改为 'processing'。", + "transfer:step_status 取 update() 返回的 updated.status。", + "handleWorkOrder:step_status 取 safeStatus(与写入主表的 status 完全一致)。", + "registerClaim:step_status 取 afterSale.status(主表当前状态)。" + ], + "module": "afterSale" + }, + { + "version": "2026.08.11-afterSale-add-waiting-status", + "date": "2026-08-11", + "type": "added", + "summary": "新增 waiting(等待外部处理)状态:用于内部处理完成后等待外部第三方(快递、客户、平台)响应的场景。", + "methods": [ + "afterSale.handleWorkOrder" + ], + "notes": [ + "Model:after_sale.js AFTER_SALE_STATUS 新增 waiting: '等待外部处理'。", + "Model:after_sale_detail.js STEP_STATUS 同步新增 waiting。", + "handleWorkOrder 白名单自动包含 waiting(从 AFTER_SALE_STATUS 派生,仅排除 pending)。", + "状态流转:processing → waiting → processing/completed。", + "设计文档同步更新 ER 图、状态流转图、枚举表。" + ], + "module": "afterSale" + }, + { + "version": "2026.08.11-afterSale-rename-pending-feedback", + "date": "2026-08-11", + "type": "changed", + "summary": "waiting 重命名为 pending_feedback(等待外部反馈):语义更精确——内部已处理完并将信息发给外部,等待反馈后再决定是否继续处理,等待期间不需要内部介入。", + "methods": [ + "afterSale.handleWorkOrder" + ], + "notes": [ + "Model/DB/文档中 waiting 全部替换为 pending_feedback", + "workList/workCount 排除列表新增 pending_feedback(等待反馈期间不需要内部处理)", + "典型场景:客服收到拦截工单 → 发信息给运方 → 设为 pending_feedback 等待运方反馈 → 收到反馈后回到 processing 通知客户" + ], + "module": "afterSale" + }, + { + "version": "2026.08.11-afterSale-batchSetPendingFeedback", + "date": "2026-08-11", + "type": "added", + "summary": "新增 afterSale.batchSetPendingFeedback 批量设为待反馈接口:传入 ids 列表,按仓库 policy_config.after_sale_followup_hours 配置自动计算 followup_at,事务内批量更新状态并写入步骤记录。", + "methods": [ + "afterSale.batchSetPendingFeedback" + ], + "notes": [ + "新增 method:afterSale.batchSetPendingFeedback,入参 ids(number[])和 remark(string, optional)", + "业务层 systems/afterSale.js 新增 batchSetPendingFeedback:预校验 ids 有效性/终态/跨仓库,事务内逐条更新 status=pending_feedback + followup_at=NOW()+INTERVAL hours HOUR + 步骤记录", + "方法层 systemMethods/afterSale.js 新增 batchSetPendingFeedback:从 ctx.user 提取 operator 信息和 warehouseId,委托 systems 层执行", + "followup_at 时长复用现有 _resolveFollowupHours 三级查找:仓库 policy_config → 内置 DEFAULTS 映射 → 兜底 24h", + "终态工单(completed/closed/cancelled)不可设为待反馈,跨仓库工单被拒绝,均返回在 failed 列表中", + "已在 _noNeedRight 和 _noNeedAuth 中注册,写入操作会记录日志" + ], + "module": "afterSale" + }, + { + "version": "2026.08.11-afterSale-batchClose", + "date": "2026-08-11", + "type": "added", + "summary": "新增 afterSale.batchClose 批量完结/关闭接口:传入 ids + status(completed|closed),事务内批量更新状态、写入步骤记录,completed 时自动写入 resolved_at 并清除 followup_at。", + "methods": [ + "afterSale.batchClose" + ], + "notes": [ + "新增 method:afterSale.batchClose,入参 ids(number[])、status(completed|closed)、resolution(string, optional)、remark(string, optional)", + "业务层 systems/afterSale.js 新增 batchClose:预校验 ids 有效性/终态/跨仓库,事务内逐条更新 status + resolved_at + followup_at 清除 + 步骤记录", + "方法层 systemMethods/afterSale.js 新增 batchClose:从 ctx.user 提取 operator 信息和 warehouseId,委托 systems 层执行", + "终态工单(completed/closed/cancelled)不可重复完结/关闭,跨仓库工单被拒绝,均返回在 failed 列表中", + "已在 _noNeedRight 和 _noNeedAuth 中注册,写入操作会记录日志" + ], + "module": "afterSale" + }, + { + "version": "2026.08.11-afterSale-detail-enrich", + "date": "2026-08-11", + "type": "enhanced", + "summary": "enhance: afterSale.detail 响应新增 related 字段,自动补充关联订单详情(收件人/发件人/商品明细/打包视频)和货主合约备注(store_remask)。", + "methods": [ + "afterSale.detail" + ], + "notes": [ + "响应新增 related 对象:含 related.order(订单详情)和 related.store_contract(货主合约备注),仅在售后单有关联单据时有值", + "related.order.recipient:从 wms_order_delivery 提取收件人姓名/电话/手机/邮箱/省市区/详细地址", + "related.order.sender:从货主 store.subject_config 提取发件人信息(sender_name/sender_tel/地址)", + "related.order.current_table:根据 dispatch_status/outbound_status/status 判断订单当前所在表(main/dispatch/history)", + "related.order.items:从 order_delivery.items JSON 字段解析商品明细数组", + "related.order.pack_videos:通过 PackTask → PackTaskVideo 关联查询打包视频列表(含 video_url/camera_id)", + "related.store_contract:从 wms_store_warehouse 查询 store_remask(商家备注)/warehouse_remask(仓库备注)/使用状态", + "所有关联查询使用 try-catch 兜底,查询失败时仅打 warn 日志,不影响主流程", + "systems/afterSale.js 新增 _enrichAfterSaleDetail / _resolveOrderDetail / _resolveStoreContractNote 三个私有方法" + ], + "module": "afterSale" + }, + { + "version": "2026.08.11-afterSale-detail-waybill", + "date": "2026-08-11", + "type": "enhanced", + "summary": "enhance: afterSale.detail 响应 related 新增 waybill 字段,自动补充运单详情(快递公司名称 + 使用的物流接口)。", + "methods": [ + "afterSale.detail" + ], + "notes": [ + "响应 related 新增 related.waybill 字段(waybill_id 不为空时自动返回)", + "related.waybill.logistics_name:快递公司名称(如 圆通/中通/顺丰),来源 wms_order_express.logistics_name", + "related.waybill.logistics_interface_name:使用的物流接口名称,来源 wms_order_express.logistics_interface_name", + "related.waybill.logistics_code:物流编码,来源 wms_order_express.logistics_code", + "related.waybill 同时返回 waybill_code/status/is_back/is_intercept/create_at 等基础字段", + "systems/afterSale.js 新增 _resolveWaybillDetail 私有方法,查询失败仅打 warn 日志不影响主流程", + "仅文档 + 代码变更,不涉及数据库变更" + ], + "module": "afterSale" + }, + { + "version": "2026.08.11-afterSale-create-order-id-alias", + "date": "2026-08-11", + "type": "enhanced", + "summary": "enhance: afterSale.create 入参新增 order_id 别名,与 order_delivery_id 等效,优先取 order_delivery_id,为空时回退到 order_id。", + "methods": [ + "afterSale.create" + ], + "notes": [ + "create 方法解构时新增 order_id 别名读取;优先使用 order_delivery_id,为空时取 order_id", + "仅方法层变更(systemMethods/afterSale.js),业务层无改动", + "同时更新 JSDoc 注释,标注 order_delivery_id 兼容别名 order_id" + ], + "module": "afterSale" + }, + { + "version": "2026.08.11-inbox-group-update-subtype-enum", + "date": "2026-08-11", + "summary": "enhance: inbox.group.update 子类型枚举补全三层约束。groupType=store 可用 after_sales/finance/receiving,groupType=warehouse 新增 production/stockout/all/exception,groupType=express 补全 pickup/after_sales。同步更新 subType description 和 400 错误码描述", + "type": "enhance", + "methods": [ + "inbox.group.update" + ], + "notes": [ + "subType 枚举由 GROUP_TYPES 统一定义,与 AI 函数分组同源", + "后端已新增两层类型校验:subType 必须在对应 groupType 的合法子类型列表中" + ] + }, + { + "version": "2026.08.11-inbox-group-update-subtype-enum-v2", + "date": "2026-08-11", + "summary": "enhance: inbox.group.update 子类型枚举补全三层约束。groupType=store 可用 after_sales/finance/receiving,groupType=warehouse 新增 production/stockout/all/exception,groupType=express 补全 pickup/after_sales。同步更新 subType description 和 400 错误码描述", + "type": "enhance", + "methods": [ + "inbox.group.update" + ], + "notes": [ + "subType 枚举由 GROUP_TYPES 统一定义,与 AI 函数分组同源", + "后端已新增两层类型校验:subType 必须在对应 groupType 的合法子类型列表中" + ] + }, + { + "version": "2026.08.11-inbox-group-update-subtype-enum-v3", + "date": "2026-08-11", + "summary": "enhance: inbox.group.update 子类型枚举补全三层约束。groupType=store 可用 after_sales/finance/receiving,groupType=warehouse 新增 production/stockout/all/exception,groupType=express 补全 pickup/after_sales。同步更新 subType description 和 400 错误码描述", + "type": "enhance", + "methods": [ + "inbox.group.update" + ], + "notes": [ + "subType 枚举由 GROUP_TYPES 统一定义,与 AI 函数分组同源", + "后端已新增两层类型校验:subType 必须在对应 groupType 的合法子类型列表中" + ] } ] diff --git a/methods/system.json b/methods/system.json index 8145c8b..5044a83 100644 --- a/methods/system.json +++ b/methods/system.json @@ -2,7 +2,7 @@ "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", "version": "0.3.21", - "updatedAt": "2026-08-09", + "updatedAt": "2026-08-11", "headers": [ { "name": "platform", @@ -5925,7 +5925,7 @@ }, { "method": "order.recheckOrder.confirmIntercept", - "description": "确认拦截:通过订单ID直接匹配订单,将其拦截状态更新为 intercepted_at_warehouse(仓库已拦截)。仅拦截当前指定订单,不波及波次内其他订单。操作成功后写入操作日志(ORDER_INTERCEPT_CONFIRM),日志写入失败不影响主流程。", + "description": "确认拦截:通过订单ID直接匹配订单,将其拦截状态更新为 intercepted_at_warehouse(仓库已拦截),同时释放储位分配(cancelAllocateStorage)与订单锁(lock_status=none)。仅拦截当前指定订单,不波及波次内其他订单。操作成功后写入操作日志(ORDER_INTERCEPT_CONFIRM)。储位释放、锁释放、日志写入失败均不影响主流程。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -5988,6 +5988,67 @@ } ] }, + { + "method": "order.recheckOrder.interceptScan", + "description": "拦截扫描:通过运单号查找运单记录,标记退回与拦截(is_back='Y', is_intercept='Y')。运单记录不存在时自动创建补充。处理关联的未完结售后工单(写入「库内拦截成功」步骤并置为 completed)。同步更新订单拦截状态为 intercepted_at_warehouse 并释放储位分配与订单锁(与 confirmIntercept 一致,订单级拦截覆盖所有面单含子面单)。工单处理失败不阻断主流程。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "waybill_code", + "type": "string", + "required": true, + "source": "body", + "description": "运单号" + } + ], + "response": [ + { + "name": "waybill_code", + "type": "string", + "required": true, + "description": "运单号" + }, + { + "name": "is_back", + "type": "string", + "required": true, + "description": "退回标记(固定为 'Y')" + }, + { + "name": "is_intercept", + "type": "string", + "required": true, + "description": "拦截标记(固定为 'Y')" + }, + { + "name": "after_sale", + "type": "object|null", + "required": false, + "description": "关联的售后工单处理结果(仅当存在未完结工单时返回);工单处理失败时为 null" + }, + { + "name": "order", + "type": "object|null", + "required": false, + "description": "订单拦截结果(仅当运单关联到订单时返回),包含 order_id、order_no、intercept_status;无法关联订单时为 null" + } + ], + "errors": [ + { + "code": 400, + "message": "运单号不能为空" + } + ] + }, { "method": "order.recheckOrder.recheckOrderList", "description": "复核订单列表查询,通过入参 list_type 区分散单模式与团购模式。散单模式(single,默认)返回待复核订单列表(每项为一个订单,排除 pick_status='none' 和 recheck_status='fin'),团购模式(group)返回波次维度的复核汇总列表(每项为一个波次及其订单复核统计,含 review_assignment_status 计算字段)。统一使用 list 字段名输出,均支持分页与筛选。", @@ -10813,6 +10874,251 @@ "message": "内部错误" } ] + }, + { + "method": "order.deliveryOrder.quickSearch", + "description": "订单快速搜索。跨表联合搜索:运单号(wms_order_express 精确匹配)、发货单号/外部订单号/平台交易单号(dispatch 表模糊匹配)。返回匹配的订单列表(最多20条),包含关键字段及关联运单号。", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [ + { + "name": "keyword", + "type": "string", + "required": true, + "source": "body", + "description": "搜索关键词。同时匹配运单号(精确)、发货单号 delivery_order_code(模糊)、外部订单号 source_order_codes(模糊)、平台交易单号 pay_no(模糊)" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "匹配的订单列表", + "children": [ + { + "name": "order_id", + "type": "number", + "required": true, + "description": "订单ID" + }, + { + "name": "waybill_id", + "type": "number", + "required": true, + "description": "运单记录ID(wms_order_express.id),0=无关联运单" + }, + { + "name": "waybill_code", + "type": "string", + "required": true, + "description": "运单号" + }, + { + "name": "logistics_code", + "type": "string", + "required": true, + "description": "快递公司编码" + }, + { + "name": "logistics_name", + "type": "string", + "required": true, + "description": "快递公司名称" + }, + { + "name": "logistics_interface_id", + "type": "number", + "required": true, + "description": "快递接口ID" + }, + { + "name": "logistics_interface_name", + "type": "string", + "required": true, + "description": "快递接口名称" + }, + { + "name": "platform_code", + "type": "string", + "required": true, + "description": "平台编码" + }, + { + "name": "waybill_status", + "type": "number", + "required": true, + "description": "运单状态 0/1" + }, + { + "name": "waybill_status_text", + "type": "string", + "required": true, + "description": "运单状态文本" + }, + { + "name": "weighing_weight", + "type": "number", + "required": true, + "description": "称重重量(g)" + }, + { + "name": "delivery_order_code", + "type": "string", + "required": true, + "description": "发货单号" + }, + { + "name": "source_order_codes", + "type": "string", + "required": true, + "description": "原始平台订单号" + }, + { + "name": "pay_no", + "type": "string", + "required": true, + "description": "平台交易单号" + }, + { + "name": "store_id", + "type": "number", + "required": true, + "description": "货主ID" + }, + { + "name": "store_name", + "type": "string", + "required": true, + "description": "货主名称" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "订单状态" + }, + { + "name": "name", + "type": "string", + "required": true, + "description": "收件人" + }, + { + "name": "mobile", + "type": "string", + "required": true, + "description": "手机号" + }, + { + "name": "province", + "type": "string", + "required": true, + "description": "省" + }, + { + "name": "city", + "type": "string", + "required": true, + "description": "市" + }, + { + "name": "area", + "type": "string", + "required": true, + "description": "区" + }, + { + "name": "detail_address", + "type": "string", + "required": true, + "description": "详细地址" + }, + { + "name": "buyer_nick", + "type": "string", + "required": true, + "description": "买家昵称" + }, + { + "name": "seller_nick", + "type": "string", + "required": true, + "description": "卖家昵称" + }, + { + "name": "shop_nick", + "type": "string", + "required": true, + "description": "店铺名称" + }, + { + "name": "total_amount", + "type": "number", + "required": true, + "description": "订单总金额" + }, + { + "name": "item_amount", + "type": "number", + "required": true, + "description": "商品金额" + }, + { + "name": "freight", + "type": "number", + "required": true, + "description": "运费" + }, + { + "name": "items_count", + "type": "number", + "required": true, + "description": "商品件数" + }, + { + "name": "items_weight", + "type": "number", + "required": true, + "description": "商品总重量(g)" + }, + { + "name": "wave_no", + "type": "string", + "required": true, + "description": "波次号" + }, + { + "name": "delivery_time", + "type": "string", + "required": true, + "description": "发货时间" + }, + { + "name": "create_at", + "type": "string", + "required": true, + "description": "创建时间" + } + ] + }, + { + "name": "keyword", + "type": "string", + "required": true, + "description": "回显搜索关键词" + } + ], + "errors": [ + { + "code": 400, + "message": "缺少 keyword 参数或仓库上下文" + }, + { + "code": 500, + "message": "搜索失败" + } + ] } ] }, @@ -17102,7 +17408,7 @@ }, { "method": "stock.transaction.list", - "description": "商品出入库流水列表查询(wms_stock_transaction),支持 where 条件筛选与分页", + "description": "商品出入库流水列表查询(wms_stock_transaction),支持 where 条件筛选与分页,支持 keyword 快捷搜索", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -17152,6 +17458,12 @@ "required": false, "description": "商品库存ID数组,为空或未传表示不筛选" }, + { + "name": "keyword", + "type": "string", + "required": false, + "description": "快捷搜索关键字,支持按商品编码(item_code)、商品名称(item_name)、货物编码(goods_code)、条码(barcode)、SKU ID 模糊匹配。内部解析为 stock_id 列表后以 IN 条件合并查询。与 stock_ids 互斥(keyword 优先)" + }, { "name": "transaction_type", "type": "string", @@ -18904,6 +19216,66 @@ } ] }, + { + "method": "pickCart.batchDelete", + "description": "批量删除拣货车。已绑定任务的拣货车将被跳过,不会删除。", + "isNeedAuth": false, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids", + "type": "array", + "required": true, + "source": "body", + "description": "拣货车ID列表,如 [1,2,3]" + } + ], + "response": [ + { + "name": "deleted_ids", + "type": "array", + "required": true, + "description": "成功删除的拣货车ID列表" + }, + { + "name": "skipped_ids", + "type": "array", + "required": true, + "description": "跳过的拣货车ID列表(已绑定任务或存在有效绑定记录)" + }, + { + "name": "deleted_count", + "type": "number", + "required": true, + "description": "成功删除数量" + }, + { + "name": "skipped_count", + "type": "number", + "required": true, + "description": "跳过数量" + } + ], + "errors": [ + { + "code": 400, + "message": "ids 参数不合法或缺少仓库上下文。" + }, + { + "code": 500, + "message": "批量删除失败。" + } + ] + }, { "method": "pickCart.detail", "description": "查询拣货车详情。", @@ -22791,7 +23163,7 @@ }, { "method": "storage.transaction.list", - "description": "出入库记录列表查询,支持 where 条件、分页、排序、批次分组切换。默认按库位合并数量(合并模式),group_by_batch=true 时返回每条明细(明细模式)", + "description": "出入库记录列表查询,支持 where 条件、keyword 快捷搜索、分页、排序、批次分组切换。默认按库位合并数量(合并模式),group_by_batch=true 时返回每条明细(明细模式)", "name": "出入库流水记录列表", "isNeedAuth": false, "isNeedLogin": true, @@ -22804,6 +23176,13 @@ "source": "body", "description": "统一 where 条件对象,可用字段:transaction_type(ENUM INBOUND/OUTBOUND)、stock_id、space_id、store_id、order_type(SCRK/MATCH)、order_no、inventory_type(ZP/CC/JS/XS/ZT/DJ/FP)、operator_name、created_at(支持 between)" }, + { + "name": "keyword", + "type": "string", + "required": false, + "source": "body", + "description": "快捷搜索关键字,支持按商品编码(item_code)、条码(barcode)模糊匹配。内部先解析为 stock_id 列表,再以 IN 条件合并到 where 中。与 where.stock_id/stock_ids 可叠加使用(交集)" + }, { "name": "pagination", "type": "object", @@ -30452,7 +30831,13 @@ "name": "order_no", "type": "string", "required": true, - "description": "订单号(来自 delivery_order_code 快照列)" + "description": "订单号。优先取 wms_order_express.delivery_order_code(快照列),为空时回退取 source_order_codes" + }, + { + "name": "source_order_codes", + "type": "string", + "required": true, + "description": "原始订单号(平台订单号),来自 wms_order_express.source_order_codes 快照列" }, { "name": "warehouse_id", @@ -30470,13 +30855,13 @@ "name": "store_id", "type": "number", "required": true, - "description": "货主ID(来自 store_id_snapshot 快照列)" + "description": "货主ID(来自 wms_order_express.store_id)" }, { "name": "store_name", "type": "string", "required": true, - "description": "货主名称(来自 store_name_snapshot 快照列)" + "description": "货主名称。通过订单ID批量关联订单发货表(current/history/dispatch)获取 store_name 字段" }, { "name": "business_key", @@ -32119,7 +32504,7 @@ ] }, { - "groupName": "站内信模块", + "groupName": "站内信", "module": "inbox", "list": [ { @@ -32955,7 +33340,7 @@ }, { "method": "inbox.group.update", - "description": "修改群信息:群类型/子类型/货主/快递接口/系统快递编码/AI开关。aiEnabled支持灰度控制,切换为express类型时systemExpressCode必填", + "description": "修改群信息:群类型/子类型/货主/快递接口/系统快递编码/AI开关。子类型受群类型约束,合法取值见 groupType.list[].subTypes。aiEnabled支持灰度控制,切换为express类型时systemExpressCode必填", "isNeedAuth": true, "isNeedLogin": true, "headers": [ @@ -32979,14 +33364,82 @@ "type": "string", "required": false, "source": "body", - "description": "群类型:store(货主) / warehouse(仓库) / express(快递)" + "description": "群类型:store(货主群) / warehouse(仓库群) / express(快递群)", + "list": [ + { + "value": "store", + "description": "货主群", + "subTypes": [ + { + "value": "after_sales", + "description": "售后" + }, + { + "value": "finance", + "description": "财务" + }, + { + "value": "receiving", + "description": "收货" + } + ] + }, + { + "value": "warehouse", + "description": "仓库群", + "subTypes": [ + { + "value": "receiving", + "description": "收货" + }, + { + "value": "production", + "description": "生产" + }, + { + "value": "stockout", + "description": "出库" + }, + { + "value": "finance", + "description": "财务" + }, + { + "value": "all", + "description": "全体" + }, + { + "value": "customer_service", + "description": "客服" + }, + { + "value": "exception", + "description": "异常" + } + ] + }, + { + "value": "express", + "description": "快递群", + "subTypes": [ + { + "value": "pickup", + "description": "揽收" + }, + { + "value": "after_sales", + "description": "售后" + } + ] + } + ] }, { "name": "subType", "type": "string", "required": false, "source": "body", - "description": "群子类型:after_sales(售后) / finance(财务) / receiving(收货)" + "description": "群子类型,值取决于groupType。store→after_sales(售后)/finance(财务)/receiving(收货)。warehouse→receiving(收货)/production(生产)/stockout(出库)/finance(财务)/all(全体)/customer_service(客服)/exception(异常)。express→pickup(揽收)/after_sales(售后)" }, { "name": "storeId", @@ -33028,11 +33481,11 @@ "errors": [ { "code": "400", - "message": "群ID无效 / 系统快递编码不能为空(express类型时)" + "message": "群ID无效 / 子类型不在对应群类型的合法范围内 / 系统快递编码不能为空(express类型时)" }, { "code": "500", - "message": "群不存在 / 系统快递编码不存在 / 快递接口ID无效" + "message": "群不存在或无权限操作 / 系统快递编码不存在 / 快递接口ID无效" } ] }, @@ -33595,7 +34048,7 @@ ] }, { - "groupName": "售后管理", + "groupName": "售后模块", "module": "afterSale", "list": [ { @@ -33604,13 +34057,41 @@ "isNeedAuth": false, "isNeedLogin": true, "params": [ - { "name": "pagination", "type": "object", "required": false, "source": "body", "description": "分页参数 page/pageSize" }, - { "name": "where", "type": "object", "required": false, "source": "body", "description": "筛选条件:type/sub_type/status/priority/after_sale_no/waybill_no 等" }, - { "name": "sort", "type": "object", "required": false, "source": "body", "description": "排序参数 sortField/sortOrder" } + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页 { page: 1, pageSize: 20 }" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "可选筛选字段: type/sub_type/status/priority/after_sale_no/waybill_no/store_id/claim_status/carrier_claim_status" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序 { sortField: 'id'|'priority'|'created_at', sortOrder: 'asc'|'desc' }" + } ], "response": [ - { "name": "list", "type": "array", "required": true }, - { "name": "pagination", "type": "object", "required": true } + { + "name": "list", + "type": "array", + "required": true, + "description": "售后单列表,每条含主表字段 + detail_count" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息 { page, pageSize, total, totalPages }" + } ] }, { @@ -33619,120 +34100,462 @@ "isNeedAuth": false, "isNeedLogin": true, "params": [ - { "name": "pagination", "type": "object", "required": false, "source": "body" }, - { "name": "where", "type": "object", "required": false, "source": "body", "description": "同 workList,额外支持 claim_status/carrier_claim_status" }, - { "name": "sort", "type": "object", "required": false, "source": "body" } + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页 { page: 1, pageSize: 20 }" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "可选筛选字段: type/sub_type/status/priority/after_sale_no/waybill_no/store_id/role_group/claim_status/carrier_claim_status。" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序 { sortField: 'id'|'priority'|'created_at', sortOrder: 'asc'|'desc' }" + } ], "response": [ - { "name": "list", "type": "array", "required": true }, - { "name": "pagination", "type": "object", "required": true } + { + "name": "list", + "type": "array", + "required": true, + "description": "全局售后单列表" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息 { page, pageSize, total, totalPages }" + } ] }, { "method": "afterSale.detail", - "description": "售后明细(主表+步骤列表+附件)。", + "description": "售后单明细查询:返回主表信息、步骤列表(含附件)、关联详情(订单/运单/货主合约)。关联数据按 afterSale 中的 order_delivery_id / waybill_id / store_id 自动解析,任一查询失败不影响主流程。", "isNeedAuth": false, "isNeedLogin": true, + "headers": [], "params": [ - { "name": "id", "type": "integer", "required": true, "source": "body", "description": "售后工单主表ID" } + { + "name": "id", + "type": "integer", + "required": true, + "source": "body", + "description": "售后单主键ID" + } ], "response": [ - { "name": "after_sale", "type": "object", "required": true, "description": "主表数据" }, - { "name": "steps", "type": "array", "required": true, "description": "步骤列表(含附件)" } + { + "name": "after_sale", + "type": "object", + "required": true, + "description": "售后主表完整记录(含格式化时间字段)" + }, + { + "name": "steps", + "type": "array", + "required": true, + "description": "售后进度步骤列表(含附件 attachments),按创建时间升序", + "list": [ + { + "value": "object", + "label": "{ id, after_sale_id, step_status, operator_id, action, remark, attachments: [{id,file_url,file_name}] }" + } + ] + }, + { + "name": "related", + "type": "object", + "required": true, + "description": "关联单据详情。仅在售后单关联了对应业务单据时有值,其他情况为空对象。" + }, + { + "name": "related.order", + "type": "object", + "required": false, + "description": "关联发货订单详情(order_delivery_id 不为空时)。含 delivery_order_code、status、current_table(main/dispatch/history)、recipient(收件人)、sender(发件人,从货主 subject_config 取)、items(订单商品明细数组)、pack_videos(打包视频列表)" + }, + { + "name": "related.waybill", + "type": "object", + "required": false, + "description": "关联运单详情(waybill_id 不为空时)。含 waybill_code、logistics_name(快递公司名称)、logistics_code(物流编码)、logistics_interface_name(使用的物流接口)、logistics_interface_id、status、is_back、is_intercept" + }, + { + "name": "related.store_contract", + "type": "object", + "required": false, + "description": "货主合约备注(store_id + warehouse_id 匹配时)。含 contract_id、store_remask(商家备注)、warehouse_remask(仓库备注)、store_use_status、warehouse_use_status" + } + ], + "errors": [ + { + "code": 404, + "message": "售后单不存在" + } ] }, { "method": "afterSale.create", - "description": "创建售后单。", + "description": "创建售后单:生成售后单号(AS+YYYYMMDD+6位序号),写入主表记录。warehouse_id 由服务端从 ctx.user.store_id 自动注入。关联单据ID可自动同步对应单号(如传 order_delivery_id 自动查 delivery_order_code)。role_group 默认 customer_service,status 默认 pending。", "isNeedAuth": false, "isNeedLogin": true, + "headers": [], "params": [ - { "name": "warehouse_id", "type": "integer", "required": true, "source": "body" }, - { "name": "store_id", "type": "integer", "required": false, "source": "body" }, - { "name": "type", "type": "string", "required": true, "source": "body", "description": "order/receiving/entry/stockout" }, - { "name": "sub_type", "type": "string", "required": true, "source": "body" }, - { "name": "priority", "type": "integer", "required": false, "source": "body" }, - { "name": "title", "type": "string", "required": true, "source": "body" }, - { "name": "description", "type": "string", "required": false, "source": "body" }, - { "name": "waybill_id", "type": "integer", "required": false, "source": "body" }, - { "name": "order_delivery_id", "type": "integer", "required": false, "source": "body" }, - { "name": "entry_order_id", "type": "integer", "required": false, "source": "body" }, - { "name": "order_stockout_id", "type": "integer", "required": false, "source": "body" }, - { "name": "receiving_id", "type": "integer", "required": false, "source": "body" }, - { "name": "inbox_message_id", "type": "integer", "required": false, "source": "body" } + { + "name": "type", + "type": "string", + "required": true, + "source": "body", + "description": "售后类型:order | receiving | entry | stockout" + }, + { + "name": "sub_type", + "type": "string", + "required": true, + "source": "body", + "description": "售后子类型,与 type 组成二级分类,详见模型枚举" + }, + { + "name": "title", + "type": "string", + "required": true, + "source": "body", + "description": "售后标题(简要描述)" + }, + { + "name": "description", + "type": "string", + "required": false, + "source": "body", + "description": "售后详细描述" + }, + { + "name": "priority", + "type": "integer", + "required": false, + "source": "body", + "description": "优先级,默认0(0=普通,10=紧急)" + }, + { + "name": "order_delivery_id", + "type": "integer", + "required": false, + "source": "body", + "description": "关联发货订单ID,兼容别名 order_id" + }, + { + "name": "waybill_id", + "type": "integer", + "required": false, + "source": "body", + "description": "关联运单ID(wms_order_express.id)" + }, + { + "name": "entry_order_id", + "type": "integer", + "required": false, + "source": "body", + "description": "关联入库单ID" + }, + { + "name": "order_stockout_id", + "type": "integer", + "required": false, + "source": "body", + "description": "关联出库单ID" + }, + { + "name": "receiving_id", + "type": "integer", + "required": false, + "source": "body", + "description": "关联收货单ID" + }, + { + "name": "store_id", + "type": "integer", + "required": false, + "source": "body", + "description": "关联货主ID" + }, + { + "name": "inbox_message_id", + "type": "integer", + "required": false, + "source": "body", + "description": "关联站内信ID" + } ], "response": [ - { "name": "id", "type": "integer", "required": true }, - { "name": "after_sale_no", "type": "string", "required": true } - ] + { + "name": "after_sale_no", + "type": "string", + "required": true, + "description": "售后单号" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "售后状态,创建默认 pending" + }, + { + "name": "role_group", + "type": "string", + "required": true, + "description": "角色组,创建默认 customer_service" + }, + { + "name": "id", + "type": "integer", + "required": true, + "description": "售后单主键ID" + } + ], + "errors": [] }, { "method": "afterSale.transfer", - "description": "转单(更新 role_group)。", + "description": "转单:将售后工单转给其他角色组处理。转单后原角色组不可见,目标角色组可见。", "isNeedAuth": false, "isNeedLogin": true, "params": [ - { "name": "id", "type": "integer", "required": true, "source": "body" }, - { "name": "role_group", "type": "string", "required": true, "source": "body", "description": "customer_service/warehouse/finance" }, - { "name": "remark", "type": "string", "required": false, "source": "body" } + { + "name": "id", + "type": "integer", + "required": true, + "source": "body", + "description": "售后工单主表ID" + }, + { + "name": "role_group", + "type": "string", + "required": true, + "source": "body", + "description": "目标角色组: customer_service(客服组) | warehouse(仓库组) | finance(财务组)" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "转单备注/原因" + } ], "response": [ - { "name": "after_sale_id", "type": "integer", "required": true } + { + "name": "after_sale_id", + "type": "integer", + "required": true, + "description": "售后工单ID" + }, + { + "name": "role_group", + "type": "string", + "required": true, + "description": "更新后的 role_group" + } ] }, { "method": "afterSale.handleWorkOrder", - "description": "处理售后工单(写步骤+绑附件+自动转回客服)。", + "description": "处理售后工单:写入进度步骤并绑定附件。操作人信息从登录上下文自动获取。非客服组处理完成后自动将 role_group 回退到 customer_service;status=completed 时自动写入 resolution + resolved_at。步骤 action 由服务端固定为\"处理工单\",step_status 与主表 status 完全一致。status 不填或填错时默认 processing。新增 pending_feedback 状态用于内部处理完成等待外部反馈(如已将拦截信息发给运方,等待运方反馈后再决定是否继续处理)。", "isNeedAuth": false, "isNeedLogin": true, + "headers": [], "params": [ - { "name": "id", "type": "integer", "required": true, "source": "body" }, - { "name": "status", "type": "string", "required": false, "source": "body", "description": "更新状态" }, - { "name": "action", "type": "string", "required": true, "source": "body" }, - { "name": "remark", "type": "string", "required": false, "source": "body" }, - { "name": "attachment_ids", "type": "array", "required": false, "source": "body", "description": "附件 file_id 数组" } + { + "name": "id", + "type": "integer", + "required": true, + "source": "body", + "description": "售后工单主表ID" + }, + { + "name": "status", + "type": "string", + "required": false, + "source": "body", + "description": "更新售后单状态: processing | pending_feedback | completed | closed | cancelled。不填或填错默认 processing。不含 pending(创建默认值)。pending_feedback=等待外部反馈" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "处理备注" + }, + { + "name": "attachment_ids", + "type": "array", + "required": false, + "source": "body", + "description": "附件 file_id 数组,如 [123, 456]。自动绑定到本次步骤" + } ], "response": [ - { "name": "detail_id", "type": "integer", "required": true }, - { "name": "after_sale_id", "type": "integer", "required": true } - ] + { + "name": "detail_id", + "type": "integer", + "required": true, + "description": "本次写入的步骤ID(wms_after_sale_detail.id)" + }, + { + "name": "after_sale_id", + "type": "integer", + "required": true, + "description": "售后工单ID" + } + ], + "errors": [] }, { "method": "afterSale.registerClaim", - "description": "登记售后理赔信息(仓库+运方一次性填入)。", + "description": "登记售后理赔信息:一次性填入仓库理赔和运方理赔字段,同时写入进度步骤。两套理赔可同时填写(双赔场景)。", "isNeedAuth": false, "isNeedLogin": true, "params": [ - { "name": "id", "type": "integer", "required": true, "source": "body" }, - { "name": "claim_needed", "type": "integer", "required": false, "source": "body" }, - { "name": "claim_amount", "type": "number", "required": false, "source": "body" }, - { "name": "claim_status", "type": "string", "required": false, "source": "body" }, - { "name": "carrier_claim_needed", "type": "integer", "required": false, "source": "body" }, - { "name": "carrier_claim_amount", "type": "number", "required": false, "source": "body" }, - { "name": "carrier_claim_status", "type": "string", "required": false, "source": "body" }, - { "name": "action", "type": "string", "required": true, "source": "body" }, - { "name": "remark", "type": "string", "required": false, "source": "body" }, - { "name": "attachment_ids", "type": "array", "required": false, "source": "body" } + { + "name": "id", + "type": "integer", + "required": true, + "source": "body", + "description": "售后工单主表ID" + }, + { + "name": "claim_needed", + "type": "integer", + "required": false, + "source": "body", + "description": "仓库理赔标记: 0=不需要, 1=需要" + }, + { + "name": "claim_amount", + "type": "number", + "required": false, + "source": "body", + "description": "仓库理赔金额(元)" + }, + { + "name": "claim_status", + "type": "string", + "required": false, + "source": "body", + "description": "仓库理赔状态: pending | reviewing | approved | paid | monthly | rejected" + }, + { + "name": "carrier_claim_needed", + "type": "integer", + "required": false, + "source": "body", + "description": "运方理赔标记: 0=不需要, 1=需要" + }, + { + "name": "carrier_claim_amount", + "type": "number", + "required": false, + "source": "body", + "description": "运方理赔金额(元)" + }, + { + "name": "carrier_claim_status", + "type": "string", + "required": false, + "source": "body", + "description": "运方理赔状态: pending | reviewing | approved | paid | monthly | rejected" + }, + { + "name": "action", + "type": "string", + "required": true, + "source": "body", + "description": "操作动作描述,如\"登记仓库理赔\"、\"登记运方理赔\"" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "处理备注,如\"快递破损核定赔200元\"" + }, + { + "name": "attachment_ids", + "type": "array", + "required": false, + "source": "body", + "description": "附件 file_id 数组(破损照片、理赔单据等)" + } ], "response": [ - { "name": "detail_id", "type": "integer", "required": true }, - { "name": "after_sale_id", "type": "integer", "required": true } + { + "name": "detail_id", + "type": "integer", + "required": true, + "description": "本次写入的步骤ID" + }, + { + "name": "after_sale_id", + "type": "integer", + "required": true, + "description": "售后工单ID" + } ] }, { "method": "afterSale.export", - "description": "提交售后审计列表导出任务(异步)。返回 task_id。", + "description": "提交售后审计列表导出任务(异步)。返回 task_id,通过 exportTaskProgress 查询进度。", "isNeedAuth": false, "isNeedLogin": true, "params": [ - { "name": "where", "type": "object", "required": false, "source": "body" }, - { "name": "sort", "type": "object", "required": false, "source": "body" } + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "筛选条件,同 auditList.where" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序,同 auditList.sort" + } ], "response": [ - { "name": "task_id", "type": "string", "required": true }, - { "name": "status", "type": "string", "required": true }, - { "name": "progress", "type": "number", "required": true }, - { "name": "message", "type": "string", "required": true } + { + "name": "task_id", + "type": "string", + "required": true, + "description": "导出任务ID,用于轮询进度" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "pending | processing | completed | failed" + }, + { + "name": "progress", + "type": "number", + "required": true, + "description": "进度百分比 0-100" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "状态说明" + } ] }, { @@ -33741,14 +34564,180 @@ "isNeedAuth": false, "isNeedLogin": true, "params": [ - { "name": "task_id", "type": "string", "required": true, "source": "body" } + { + "name": "task_id", + "type": "string", + "required": true, + "source": "body", + "description": "export 接口返回的 task_id" + } ], "response": [ - { "name": "task_id", "type": "string", "required": true }, - { "name": "status", "type": "string", "required": true }, - { "name": "progress", "type": "number", "required": true }, - { "name": "download_url", "type": "string", "required": false } + { + "name": "task_id", + "type": "string", + "required": true, + "description": "导出任务ID" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "pending | processing | completed | failed" + }, + { + "name": "progress", + "type": "number", + "required": true, + "description": "进度百分比 0-100" + }, + { + "name": "download_url", + "type": "string", + "required": false, + "description": "完成后的文件下载链接(仅 status=completed 时返回)" + } ] + }, + { + "method": "afterSale.workCount", + "description": "快速查询当前用户待处理售后工单数量(角标用),返回count字段,前端>99显示99+。", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [], + "response": [ + { + "name": "count", + "type": "integer", + "required": true + } + ] + }, + { + "method": "afterSale.batchSetPendingFeedback", + "description": "批量将售后工单设为“待反馈”状态,按仓库 policy_config.after_sale_followup_hours 配置自动计算每个工单的 followup_at(下次跟进时间)。所有工单在同一事务中处理,任一失败则全部回滚。终态工单(completed/closed/cancelled)不可回退、跨仓库工单会被拒绝并返回 failed 列表。非客服组工单自动将 role_group 回设为 customer_service。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "ids", + "type": "array", + "required": true, + "source": "body", + "description": "售后单主键ID列表,如 [1, 2, 3]。非正整数会被自动过滤。", + "list": [ + { + "value": "number", + "label": "售后单ID(正整数)" + } + ] + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "统一处理备注,所有工单共用同一备注内容" + } + ], + "response": [ + { + "name": "total", + "type": "integer", + "required": true, + "description": "传入的工单总数(过滤非正整数后)" + }, + { + "name": "success", + "type": "integer", + "required": true, + "description": "成功设为待反馈的工单数量" + }, + { + "name": "failed", + "type": "array", + "required": true, + "description": "失败的工单列表,每项包含 id 和 reason", + "list": [ + { + "value": "object", + "label": "{ id: number, reason: string }" + } + ] + } + ], + "errors": [] + }, + { + "method": "afterSale.batchClose", + "description": "批量将售后工单完结或关闭。status=completed 时自动写入 resolved_at 并清除 followup_at;status=closed 时仅更新状态。所有工单在同一事务中处理,任一失败则全部回滚。终态工单(completed/closed/cancelled)不可重复操作、跨仓库工单会被拒绝并返回 failed 列表。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "ids", + "type": "array", + "required": true, + "source": "body", + "description": "售后单主键ID列表,如 [1, 2, 3]。非正整数会被自动过滤。", + "list": [ + { + "value": "number", + "label": "售后单ID(正整数)" + } + ] + }, + { + "name": "status", + "type": "string", + "required": true, + "source": "body", + "description": "目标状态:completed=完结(写入 resolved_at + resolution),closed=关闭(仅更新状态,不写入完结信息)" + }, + { + "name": "resolution", + "type": "string", + "required": false, + "source": "body", + "description": "完结处理结果说明,仅 status=completed 时写入" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "统一处理备注,所有工单共用同一备注内容" + } + ], + "response": [ + { + "name": "total", + "type": "integer", + "required": true, + "description": "传入的工单总数(过滤非正整数后)" + }, + { + "name": "success", + "type": "integer", + "required": true, + "description": "成功操作的工单数量" + }, + { + "name": "failed", + "type": "array", + "required": true, + "description": "失败的工单列表,每项包含 id 和 reason", + "list": [ + { + "value": "object", + "label": "{ id: number, reason: string }" + } + ] + } + ], + "errors": [] } ] } From a024a20356f677e133321277608de5e8706f799e Mon Sep 17 00:00:00 2001 From: liufumingren Date: Wed, 12 Aug 2026 21:56:22 +0800 Subject: [PATCH 188/550] =?UTF-8?q?fix:=20=E6=95=A3=E5=8D=95=E6=B3=A2?= =?UTF-8?q?=E6=AC=A1=E6=8B=A6=E6=88=AA=E5=A2=9E=E5=8A=A0=E7=A7=B0=E9=87=8D?= =?UTF-8?q?=E5=88=A4=E6=96=AD=20=E2=80=94=20weighing=5Fweight>0=E6=97=B6?= =?UTF-8?q?=E4=B8=8D=E8=AE=BE=E7=BD=AE=E6=8B=A6=E6=88=AA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 修复: inbox AI 波次感知拦截(interceptWaybill + 取消拦截) - 散单(wave_type=2)不再无条件拦截,改为查 wms_order_express.weighing_weight - weighing_weight > 0(已称重) → 跳过拦截 - weighing_weight <= 0(未称重) → 设置拦截 - 团购(wave_type=1)逻辑不变: inspection_status !== 'fin' → 拦截 --- app/service/inbox/functions.js | 43 +++++++++++++++++++++++++++++++--- 1 file changed, 40 insertions(+), 3 deletions(-) diff --git a/app/service/inbox/functions.js b/app/service/inbox/functions.js index 7bc7509..64ee1cc 100644 --- a/app/service/inbox/functions.js +++ b/app/service/inbox/functions.js @@ -969,6 +969,23 @@ class InboxFunctionsService extends Service { const interceptOrderIds = []; const kickOutOrderIds = []; + // 批量查询散单的称重状态(wms_order_express.weighing_weight) + let weighingMap = {}; + const scatterOrderIds = orders + .filter(o => o.wave_id > 0 && waveMap[o.wave_id] && waveMap[o.wave_id].wave_type === 2) + .map(o => o.id); + if (scatterOrderIds.length > 0) { + const expressRows = await ctx.model.OrderExpress.findAll({ + attributes: [ 'order_id', 'weighing_weight' ], + where: { order_id: { [ctx.app.Sequelize.Op.in]: scatterOrderIds }, warehouse_id: warehouseId }, + raw: true, + }); + weighingMap = Object.fromEntries( + (Array.isArray(expressRows) ? expressRows : []) + .map(r => [ r.order_id, Number(r.weighing_weight || 0) ]) + ); + } + for (const order of orders) { const wave = waveMap[order.wave_id]; const orderId = order.id; @@ -980,8 +997,9 @@ class InboxFunctionsService extends Service { // 团购波次:未复核 → 拦截 needIntercept = order.inspection_status !== 'fin'; } else if (wave.wave_type === 2) { - // 散单波次:未称重视同可拦截(订单表无称重状态,默认拦截) - needIntercept = true; + // 散单波次:未称重 → 拦截(weighing_weight = 0 表示未称重) + const weight = weighingMap[orderId] ?? 0; + needIntercept = weight <= 0; } } else { // 无波次订单:直接拦截 @@ -1311,11 +1329,30 @@ class InboxFunctionsService extends Service { waveMap = Object.fromEntries(waves.map(w => [ w.wave_id, w ])); } const interceptOrderIds = []; + // 批量查询散单的称重状态 + const scatterIds = orders + .filter(o => o.wave_id > 0 && waveMap[o.wave_id] && waveMap[o.wave_id].wave_type === 2) + .map(o => o.id); + const wMap = {}; + if (scatterIds.length > 0) { + const er = await ctx.model.OrderExpress.findAll({ + attributes: [ 'order_id', 'weighing_weight' ], + where: { order_id: { [ctx.app.Sequelize.Op.in]: scatterIds }, warehouse_id: warehouseId }, + raw: true, + }); + for (const r of (Array.isArray(er) ? er : [])) { + wMap[r.order_id] = Number(r.weighing_weight || 0); + } + } for (const order of orders) { const wave = waveMap[order.wave_id]; let needIntercept = false; if (order.wave_id > 0 && wave) { - needIntercept = wave.wave_type === 1 ? order.inspection_status !== 'fin' : true; + if (wave.wave_type === 1) { + needIntercept = order.inspection_status !== 'fin'; + } else { + needIntercept = (wMap[order.id] ?? 0) <= 0; + } } else { needIntercept = true; } From 2795ae07580d49e7fc2350f0f8e397908e31f253 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Wed, 12 Aug 2026 22:13:20 +0800 Subject: [PATCH 189/550] =?UTF-8?q?fix:=20=E8=A1=A5=E5=85=A8=E6=8B=A6?= =?UTF-8?q?=E6=88=AA=E9=93=BE=E8=B7=AF=E6=93=8D=E4=BD=9C=E6=97=A5=E5=BF=97?= =?UTF-8?q?=20=E2=80=94=20Qimen/OpenAPI/inbox=20AI=20=E5=86=99=E5=85=A5=20?= =?UTF-8?q?ORDER=5FINTERCEPT=5FREQUEST?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 修复: 3处拦截入口缺失操作日志 - Qimen cancel: 拦截路径补 ORDER_INTERCEPT_REQUEST - OpenAPI cancel: 拦截路径补 ORDER_INTERCEPT_REQUEST - inbox AI interceptWaybill + 取消拦截: 补 ORDER_INTERCEPT_REQUEST --- app/service/inbox/functions.js | 34 +++++++++++++++++++++++++++++ app/service/openapiMethods/order.js | 21 ++++++++++++++++++ app/service/qimenMethods/order.js | 20 +++++++++++++++++ 3 files changed, 75 insertions(+) diff --git a/app/service/inbox/functions.js b/app/service/inbox/functions.js index 64ee1cc..5fac707 100644 --- a/app/service/inbox/functions.js +++ b/app/service/inbox/functions.js @@ -1032,6 +1032,23 @@ class InboxFunctionsService extends Service { { is_intercept: 'Y' }, { where: { order_id: { [ctx.app.Sequelize.Op.in]: interceptOrderIds }, warehouse_id: warehouseId } } ); + // 写入操作日志(失败不影响主流程) + try { + const logService = ctx.service?.systems?.operationLog; + if (logService && typeof logService.createOperationLogs === 'function') { + await logService.createOperationLogs( + interceptOrderIds.map(oid => ({ + businessType: 'order', + businessId: String(warehouseId), + operationCode: 'ORDER_INTERCEPT_REQUEST', + operator: { id: '0', name: groupName || 'AI系统' }, + extras: { warehouseId, orderId: oid, newInterceptStatus: 'requested' }, + })) + ); + } + } catch (logErr) { + ctx.logger.warn(`[inbox functions] 写入拦截操作日志失败: ${logErr.message}`); + } ctx.logger.info( `[inbox functions] 设置拦截状态: ${interceptOrderIds.length} 个订单` ); @@ -1367,6 +1384,23 @@ class InboxFunctionsService extends Service { { is_intercept: 'Y' }, { where: { order_id: { [ctx.app.Sequelize.Op.in]: interceptOrderIds }, warehouse_id: warehouseId } } ); + // 写入操作日志(失败不影响主流程) + try { + const logSvc = ctx.service?.systems?.operationLog; + if (logSvc && typeof logSvc.createOperationLogs === 'function') { + await logSvc.createOperationLogs( + interceptOrderIds.map(oid => ({ + businessType: 'order', + businessId: String(warehouseId), + operationCode: 'ORDER_INTERCEPT_REQUEST', + operator: { id: '0', name: groupName || 'AI系统' }, + extras: { warehouseId, orderId: oid, newInterceptStatus: 'requested' }, + })) + ); + } + } catch (logErr) { + ctx.logger.warn(`[inbox functions] 取消拦截-写入操作日志失败: ${logErr.message}`); + } ctx.logger.info(`[inbox functions] 取消拦截-设置拦截状态: ${interceptOrderIds.length} 个订单`); } } diff --git a/app/service/openapiMethods/order.js b/app/service/openapiMethods/order.js index 50c55e4..9fd9b6a 100644 --- a/app/service/openapiMethods/order.js +++ b/app/service/openapiMethods/order.js @@ -79,6 +79,27 @@ class OpenapiOrderService extends MainService { await transaction.commit(); + // 写入拦截操作日志(失败不影响主流程) + try { + const { ctx: ctx2 } = this; + if (ctx2.model && ctx2.model.OperationLog) { + const whId2 = ctx2.user && ctx2.user.store_id ? Number(ctx2.user.store_id) : 0; + await ctx2.model.OperationLog.create({ + business_type: 'order', + business_id: String(existingOrder.id), + operation_code: 'ORDER_INTERCEPT_REQUEST', + operator_id: ctx2.user?.employees_id || ctx2.user?.id || null, + operator_name: ctx2.user?.employees_name || 'OpenAPI', + external_log_type: 'NONE', + warehouse_id: whId2 || null, + platform_code: 'OPENAPI', + message: 'OpenAPI取消订单-触发拦截', + }); + } + } catch (logErr) { + this.ctx.logger.warn('[OpenAPIOrderCancel] 写入拦截操作日志失败,不影响主流程', logErr); + } + // 创建售后工单 + 通知快递群(失败不影响主流程) try { const { ctx } = this; diff --git a/app/service/qimenMethods/order.js b/app/service/qimenMethods/order.js index a390248..dc40180 100644 --- a/app/service/qimenMethods/order.js +++ b/app/service/qimenMethods/order.js @@ -208,6 +208,26 @@ class orderServer extends MainService { await transaction.commit(); + // 写入拦截操作日志(失败不影响主流程) + try { + if (ctx.model && ctx.model.OperationLog) { + const customerId2 = String(info.customerId || '').trim(); + await ctx.model.OperationLog.create({ + business_type: 'order', + business_id: String(existingOrder.id), + operation_code: 'ORDER_INTERCEPT_REQUEST', + operator_id: null, + operator_name: customerId2 ? `qimen:${customerId2}` : 'qimen', + external_log_type: 'NONE', + warehouse_id: info.warehouseId || null, + platform_code: customerId2 || 'SYSTEM', + message: '奇门取消订单-触发拦截', + }); + } + } catch (logErr) { + ctx.logger.warn('[QimenOrderCancel] 写入拦截操作日志失败,不影响主流程', logErr); + } + // 创建售后工单 + 通知快递群(失败不影响主流程) try { await ctx.service.systems.afterSale.createInterceptWorkOrdersAndNotify({ From 6c5e69c7d9f74ebf1dbb6a8fe1e2f37bde878e72 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Wed, 12 Aug 2026 22:26:00 +0800 Subject: [PATCH 190/550] =?UTF-8?q?fix:=20afterSale=20detail=20=E5=85=BC?= =?UTF-8?q?=E5=AE=B9=20order=5Fid=20=E5=9B=9E=E9=80=80=20=E2=80=94=20?= =?UTF-8?q?=E6=8B=A6=E6=88=AA=E5=B7=A5=E5=8D=95=E8=83=BD=E7=9C=8B=E5=88=B0?= =?UTF-8?q?=E8=AE=A2=E5=8D=95=E6=98=8E=E7=BB=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit after_sale 表中拦截工单使用 order_id 字段,_enrichAfterSaleDetail 仅判断 order_delivery_id,导致拦截工单的详情接口看不到订单明细。 改为 order_delivery_id || order_id 双字段兼容 --- app/service/systems/afterSale.js | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/app/service/systems/afterSale.js b/app/service/systems/afterSale.js index ceedfb6..24d4692 100644 --- a/app/service/systems/afterSale.js +++ b/app/service/systems/afterSale.js @@ -341,14 +341,15 @@ class AfterSaleService extends Service { const related = {}; // ======= 1. 关联订单详情 ======= - if (afterSale.order_delivery_id) { + const resolvedOrderId = afterSale.order_delivery_id || afterSale.order_id; + if (resolvedOrderId) { try { related.order = await this._resolveOrderDetail( - afterSale.order_delivery_id, + resolvedOrderId, afterSale.warehouse_id ); } catch (err) { - ctx.logger.warn(`[_enrichAfterSaleDetail] 解析订单详情失败 id=${afterSale.order_delivery_id}: ${err.message}`); + ctx.logger.warn(`[_enrichAfterSaleDetail] 解析订单详情失败 id=${resolvedOrderId}: ${err.message}`); } } From 61467756e231a8a3a57727fc4e72f0ab4ad6e067 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Wed, 12 Aug 2026 22:39:06 +0800 Subject: [PATCH 191/550] =?UTF-8?q?refactor:=20after=5Fsale=20=E7=BB=9F?= =?UTF-8?q?=E4=B8=80=E4=BD=BF=E7=94=A8=20order=5Fid=20=E2=80=94=20?= =?UTF-8?q?=E5=BC=83=E7=94=A8=20order=5Fdelivery=5Fid=20=E5=86=99=E5=85=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - systemMethods/afterSale create: order_delivery_id → order_id - systemMethods/afterSale _resolveRedundantFields: order_delivery_no → order_no - systems/afterSale _enrichAfterSaleDetail: 仅使用 order_id --- app/service/systemMethods/afterSale.js | 6 +++--- app/service/systems/afterSale.js | 3 ++- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/app/service/systemMethods/afterSale.js b/app/service/systemMethods/afterSale.js index a9ddb13..1340900 100644 --- a/app/service/systemMethods/afterSale.js +++ b/app/service/systemMethods/afterSale.js @@ -314,8 +314,8 @@ class AfterSaleMethodService extends MainService { status: 'pending', waybill_id: waybillId || null, waybill_no: redundantFields.waybill_no || null, - order_delivery_id: orderDeliveryId || null, - order_delivery_no: redundantFields.order_delivery_no || null, + order_id: orderDeliveryId || null, + order_no: redundantFields.order_no || null, entry_order_id: entryOrderId || null, entry_order_no: redundantFields.entry_order_no || null, order_stockout_id: orderStockoutId || null, @@ -373,7 +373,7 @@ class AfterSaleMethodService extends MainService { attributes: [ 'delivery_order_code' ], raw: true, }); - redundant.order_delivery_no = order ? order.delivery_order_code || null : null; + redundant.order_no = order ? order.delivery_order_code || null : null; } } catch (err) { ctx.logger.warn(`[afterSale._resolveRedundantFields] 查询发货订单号失败: ${err.message}`); diff --git a/app/service/systems/afterSale.js b/app/service/systems/afterSale.js index 24d4692..b6de78e 100644 --- a/app/service/systems/afterSale.js +++ b/app/service/systems/afterSale.js @@ -341,7 +341,8 @@ class AfterSaleService extends Service { const related = {}; // ======= 1. 关联订单详情 ======= - const resolvedOrderId = afterSale.order_delivery_id || afterSale.order_id; + // 统一使用 order_id + const resolvedOrderId = afterSale.order_id; if (resolvedOrderId) { try { related.order = await this._resolveOrderDetail( From 9974cfab892af47e5d5fe56225e2674d43b84697 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Wed, 12 Aug 2026 22:41:32 +0800 Subject: [PATCH 192/550] =?UTF-8?q?migrate:=20=E7=A7=BB=E9=99=A4=20wms=5Fa?= =?UTF-8?q?fter=5Fsale.order=5Fdelivery=5Fid/order=5Fdelivery=5Fno?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - migration: DROP order_delivery_id, order_delivery_no - model: 移除两字段定义 + idx_order_delivery_id 索引 - 全部流程已统一使用 order_id --- app/model/after_sale.js | 18 ++------- ...emove-order-delivery-id-from-after-sale.js | 40 +++++++++++++++++++ 2 files changed, 43 insertions(+), 15 deletions(-) create mode 100644 database/migrations/20260812150000-remove-order-delivery-id-from-after-sale.js diff --git a/app/model/after_sale.js b/app/model/after_sale.js index 05f3955..7e0f5bc 100644 --- a/app/model/after_sale.js +++ b/app/model/after_sale.js @@ -269,19 +269,7 @@ module.exports = app => { order_id: { type: BIGINT(20).UNSIGNED, allowNull: true, - comment: '订单ID(关联 wms_order.id),快递反馈建单时从 wms_order_express.order_id 填入', - }, - /** 发货订单ID */ - order_delivery_id: { - type: BIGINT(20).UNSIGNED, - allowNull: true, - comment: '发货订单ID(关联 wms_order_delivery.id)', - }, - /** 发货订单号(冗余) */ - order_delivery_no: { - type: STRING(50), - allowNull: true, - comment: '发货订单号(冗余字段)', + comment: '订单ID(关联 wms_order_delivery.id)', }, /** 入库单ID */ entry_order_id: { @@ -381,8 +369,8 @@ module.exports = app => { fields: [ 'waybill_id' ], }, { - name: 'idx_order_delivery_id', - fields: [ 'order_delivery_id' ], + name: 'idx_order_id', + fields: [ 'order_id' ], }, { name: 'idx_entry_order_id', diff --git a/database/migrations/20260812150000-remove-order-delivery-id-from-after-sale.js b/database/migrations/20260812150000-remove-order-delivery-id-from-after-sale.js new file mode 100644 index 0000000..84edcab --- /dev/null +++ b/database/migrations/20260812150000-remove-order-delivery-id-from-after-sale.js @@ -0,0 +1,40 @@ +'use strict'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const { STRING, BIGINT } = Sequelize; + const tableName = 'wms_after_sale'; + + // 检查列是否存在 + const [columns] = await queryInterface.sequelize.query( + `SHOW COLUMNS FROM \`${tableName}\` LIKE 'order_delivery_id'` + ); + if (Array.isArray(columns) && columns.length > 0) { + await queryInterface.removeColumn(tableName, 'order_delivery_id'); + } + + const [columns2] = await queryInterface.sequelize.query( + `SHOW COLUMNS FROM \`${tableName}\` LIKE 'order_delivery_no'` + ); + if (Array.isArray(columns2) && columns2.length > 0) { + await queryInterface.removeColumn(tableName, 'order_delivery_no'); + } + }, + + down: async (queryInterface, Sequelize) => { + const { STRING, BIGINT } = Sequelize; + const tableName = 'wms_after_sale'; + + await queryInterface.addColumn(tableName, 'order_delivery_id', { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '发货订单ID(关联 wms_order_delivery.id)', + }); + + await queryInterface.addColumn(tableName, 'order_delivery_no', { + type: STRING(50), + allowNull: true, + comment: '发货订单号(冗余字段)', + }); + }, +}; From 64c24f963ddf92a8dc19bb8291b596e7bb194b5d Mon Sep 17 00:00:00 2001 From: liufumingren Date: Wed, 12 Aug 2026 22:45:56 +0800 Subject: [PATCH 193/550] =?UTF-8?q?feat:=20afterSale=20detail=20=E8=AE=A2?= =?UTF-8?q?=E5=8D=95=E6=98=8E=E7=BB=86=E5=A2=9E=E5=8A=A0=20total=5Famount/?= =?UTF-8?q?item=5Famount?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/systems/afterSale.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/app/service/systems/afterSale.js b/app/service/systems/afterSale.js index b6de78e..048b311 100644 --- a/app/service/systems/afterSale.js +++ b/app/service/systems/afterSale.js @@ -608,6 +608,9 @@ class AfterSaleService extends Service { // 数量 items_count: order.items_count, items_total: order.items_total, + // 金额 + total_amount: order.total_amount, + item_amount: order.item_amount, // 收件人 / 发件人 / 明细 / 打包视频 recipient, sender, From 793dca837502ef6365b471c42bca1ba9aa71fa01 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Wed, 12 Aug 2026 22:52:37 +0800 Subject: [PATCH 194/550] =?UTF-8?q?fix:=20confirmIntercept=20=E5=90=8C?= =?UTF-8?q?=E6=AD=A5=E8=AE=BE=E7=BD=AE=20is=5Fintercept=3DY=20+=20is=5Fbac?= =?UTF-8?q?k=3DY=20=E5=88=B0=E6=89=80=E6=9C=89=E8=BF=90=E5=8D=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 之前 confirmIntercept 仅对 is_intercept=Y 的运单设 is_back=Y, 但 confirmIntercept 入口不经过 AI 波次感知,运单可能未被标记拦截, 导致确认拦截后运单表标记不生效。 改为订单级统一设置 is_intercept+is_back,覆盖所有运单。 --- app/service/systemMethods/order/recheckOrder.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/app/service/systemMethods/order/recheckOrder.js b/app/service/systemMethods/order/recheckOrder.js index 1320033..6f6e8af 100644 --- a/app/service/systemMethods/order/recheckOrder.js +++ b/app/service/systemMethods/order/recheckOrder.js @@ -3611,15 +3611,15 @@ class RecheckOrderService extends OrderBaseService { throw new Error('拦截状态更新失败,请稍后重试'); } - // 同步更新运单表:仅对已标记拦截的运单设置退回标记 + // 同步更新运单表:标记拦截 + 退回 try { await ctx.model.OrderExpress.update( - { is_back: 'Y' }, - { where: { order_id: orderId, warehouse_id: warehouseId, is_intercept: 'Y' } } + { is_intercept: 'Y', is_back: 'Y' }, + { where: { order_id: orderId, warehouse_id: warehouseId } } ); } catch (expressErr) { ctx.logger.warn( - `[recheckOrder.confirmIntercept] 更新运单退回标记失败, orderId=${orderId}, error=${expressErr.message}` + `[recheckOrder.confirmIntercept] 更新运单拦截/退回标记失败, orderId=${orderId}, error=${expressErr.message}` ); } From 1ea2bc48f7386a8f6bcf3d7fb0e5e8c7663734cc Mon Sep 17 00:00:00 2001 From: liufumingren Date: Wed, 12 Aug 2026 22:54:05 +0800 Subject: [PATCH 195/550] =?UTF-8?q?fix:=20Qimen=20sync=20cancel=20+=20pend?= =?UTF-8?q?ingOrder=20cancel=20=E8=A1=A5=E8=BF=90=E5=8D=95=20is=5Fintercep?= =?UTF-8?q?t=20=E6=A0=87=E8=AE=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Qimen cancel(syncStatus=fin): 补 is_intercept='Y' - pendingOrder.cancelOrder(synced): 补 is_intercept='Y' --- app/service/qimenMethods/order.js | 12 ++++++++++++ app/service/systemMethods/order/pendingOrder.js | 12 ++++++++++++ 2 files changed, 24 insertions(+) diff --git a/app/service/qimenMethods/order.js b/app/service/qimenMethods/order.js index dc40180..ab162cd 100644 --- a/app/service/qimenMethods/order.js +++ b/app/service/qimenMethods/order.js @@ -259,6 +259,18 @@ class orderServer extends MainService { transaction, }); + // 同步更新运单表拦截标记 + try { + await ctx.model.OrderExpress.update( + { is_intercept: 'Y' }, + { where: { order_id: existingOrder.id, warehouse_id: info.warehouseId }, transaction } + ); + } catch (expressErr) { + ctx.logger.warn( + `[qimen order cancel] 更新运单拦截标记失败(sync), orderId=${existingOrder.id}, error=${expressErr.message}` + ); + } + await transaction.commit(); await this.sendCancelInterceptNotice({ orderCode, diff --git a/app/service/systemMethods/order/pendingOrder.js b/app/service/systemMethods/order/pendingOrder.js index 1c155f4..1f6d911 100644 --- a/app/service/systemMethods/order/pendingOrder.js +++ b/app/service/systemMethods/order/pendingOrder.js @@ -2294,6 +2294,18 @@ class PendingOrderService extends OrderBaseService { }, } ); + // 同步更新运单表拦截标记 + try { + const { Op: cancelOp } = this.app.Sequelize; + await this.ctx.model.OrderExpress.update( + { is_intercept: 'Y' }, + { where: { order_id: { [cancelOp.in]: syncedOrderIds }, warehouse_id: warehouseId } } + ); + } catch (expressErr) { + this.ctx.logger.warn( + `[PendingOrderService.cancelOrder] 更新运单拦截标记失败, count=${syncedOrderIds.length}, error=${expressErr.message}` + ); + } this.ctx.logger.info( `[PendingOrderService.cancelOrder] 订单已同步,不可取消,已转为拦截处理,订单ID: ${syncedOrderIds.join(',')}` ); From 7a74130219af3a9fa0326fb2d263eb96a0093320 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Wed, 12 Aug 2026 23:09:28 +0800 Subject: [PATCH 196/550] 1 --- .github/agents/数据库.agent.md | 2 +- .github/agents/测试.agent.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/agents/数据库.agent.md b/.github/agents/数据库.agent.md index a050a04..271f873 100644 --- a/.github/agents/数据库.agent.md +++ b/.github/agents/数据库.agent.md @@ -14,7 +14,7 @@ model : DeepSeek V4 Pro (deepseek) - 默认数据库脚本:`script/db-query.ps1` - 默认 MySQL client:`wms` - 可切换 client:`wms`、`ye4s` - +- 禁止执行npm run deploy ## 何时必须使用本 Agent 出现以下任一诉求时,必须使用 `wms-db-agent`: diff --git a/.github/agents/测试.agent.md b/.github/agents/测试.agent.md index c238c3e..90ec35e 100644 --- a/.github/agents/测试.agent.md +++ b/.github/agents/测试.agent.md @@ -13,7 +13,7 @@ model: DeepSeek V4 Pro (deepseek) - 项目根目录:`D:\wms` - 主要目录:`test/`、`app/`、`methods/` - 适用于单元测试、集成测试、回归测试、接口验证与修复验证 - +- 禁止执行npm run deploy ## 测试环境固定参数 | 参数 | 值 | 说明 | From c84d5ac4ae200c12e2a332b8ecbd388bd3dcd11a Mon Sep 17 00:00:00 2001 From: liufumingren Date: Wed, 12 Aug 2026 23:35:38 +0800 Subject: [PATCH 197/550] =?UTF-8?q?feat:=20=E5=BA=93=E5=86=85=E6=8B=A6?= =?UTF-8?q?=E6=88=AA=E7=A1=AE=E8=AE=A4=E5=90=8C=E6=AD=A5=E6=8E=A8=E8=BF=9B?= =?UTF-8?q?=E8=AE=A2=E5=8D=95=20step=3D4=20+=20outbound=5Fstatus=3Dfin?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit confirmIntercept + interceptScan 确认拦截后: - step = 4(配送中) - outbound_status = 'fin'(出库完成) - intercept_status = intercepted_at_warehouse --- app/service/inbox/functions.js | 11 +++++++++++ app/service/systemMethods/order/recheckOrder.js | 9 ++++++++- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/app/service/inbox/functions.js b/app/service/inbox/functions.js index 5fac707..d10c39c 100644 --- a/app/service/inbox/functions.js +++ b/app/service/inbox/functions.js @@ -901,6 +901,16 @@ class InboxFunctionsService extends Service { // 第四步:批量创建工单(初始状态 pending,后续根据通知结果升级) const creatorLabel = [ groupName, userName ].filter(Boolean).join('-') || 'AI系统'; + // 获取原消息内容,写入工单明细 + let interceptMsgContent = ''; + try { + const iid = ctx.inboxContext?.inbound_message_id; + if (iid) { + const imsg = await ctx.model.InboxMessage.findByPk(iid, { attributes: [ 'content' ], raw: true }); + if (imsg && imsg.content) interceptMsgContent = String(imsg.content); + } + } catch (e) { /* ignore */ } + const createdNos = []; const waybillToAsNo = {}; // waybill_id → after_sale_no 映射 for (const e of toCreate) { @@ -910,6 +920,7 @@ class InboxFunctionsService extends Service { `运单号: ${e.waybill_code}`, `快递公司: ${e.logistics_name || '未知'}`, reason ? `拦截原因: ${reason}` : '', + interceptMsgContent ? `原消息: ${interceptMsgContent}` : '', ].filter(Boolean).join('\n'); await ctx.service.systems.afterSale.create({ diff --git a/app/service/systemMethods/order/recheckOrder.js b/app/service/systemMethods/order/recheckOrder.js index 6f6e8af..200a48d 100644 --- a/app/service/systemMethods/order/recheckOrder.js +++ b/app/service/systemMethods/order/recheckOrder.js @@ -3600,6 +3600,8 @@ class RecheckOrderService extends OrderBaseService { const now = new Date(); const updateValues = { intercept_status: 'intercepted_at_warehouse', + step: 4, + outbound_status: 'fin', updated_at: now, }; const updateResult = await orderModel.update(updateValues, { @@ -3800,7 +3802,12 @@ class RecheckOrderService extends OrderBaseService { if (order) { await orderModel.update( - { intercept_status: 'intercepted_at_warehouse', updated_at: now }, + { + intercept_status: 'intercepted_at_warehouse', + step: 4, + outbound_status: 'fin', + updated_at: now, + }, { where: orderWhere } ); From f4ed98555617dfbe6030e0a24f0efb08526098fa Mon Sep 17 00:00:00 2001 From: liufumingren Date: Thu, 13 Aug 2026 01:58:55 +0800 Subject: [PATCH 198/550] =?UTF-8?q?feat:=20=E6=96=B0=E5=A2=9E=E9=80=80?= =?UTF-8?q?=E5=9B=9E=E6=94=B6=E5=88=B0=E6=A8=A1=E5=9D=97=EF=BC=88returnRec?= =?UTF-8?q?eived=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增退回收到登记表 wms_return_received 及模型、建表迁移 - 新增扫码登记/列表/详情/删除接口(systemMethods + systems 分层) - 退回收到联动:标记运单 is_back、完结拦截工单、订单退回状态、操作记录 - 新增权限 527/528/529 + 菜单 530,授权仓库/客服角色 - 解除拦截不再清除 is_back(由退回收货流程单独管理) - 同步 API 文档、method 路由速查 --- AI_METHOD_ROUTING.md | 4 + app/dict/businessDict.js | 1 + app/model/return_received.js | 100 ++++ .../systemMethods/order/pendingOrder.js | 6 +- .../systemMethods/order/recheckOrder.js | 14 +- app/service/systemMethods/returnReceived.js | 107 ++++ app/service/systems/return_received.js | 551 ++++++++++++++++++ ...260812160000-create-wms-return-received.js | 87 +++ ...0000-create-return-received-permissions.js | 98 ++++ ...000-add-return-received-menu-permission.js | 82 +++ methods/changes/system.json | 22 + methods/system.json | 314 +++++++++- 12 files changed, 1375 insertions(+), 11 deletions(-) create mode 100644 app/model/return_received.js create mode 100644 app/service/systemMethods/returnReceived.js create mode 100644 app/service/systems/return_received.js create mode 100644 database/migrations/20260812160000-create-wms-return-received.js create mode 100644 database/migrations/20260813100000-create-return-received-permissions.js create mode 100644 database/migrations/20260813110000-add-return-received-menu-permission.js diff --git a/AI_METHOD_ROUTING.md b/AI_METHOD_ROUTING.md index 04de55b..afa7e3c 100644 --- a/AI_METHOD_ROUTING.md +++ b/AI_METHOD_ROUTING.md @@ -161,6 +161,8 @@ rg "class .*Service|module.exports" app/service/qimenMethods - send, sendToComputer, log - app/service/systemMethods/printer/station.js (1) - list +- app/service/systemMethods/returnReceived.js (4) + - create, list, detail, delete - app/service/systemMethods/setting/printTemplate.js (3) - list, save, listTemplatesByType - app/service/systemMethods/stock.js (21) @@ -207,6 +209,8 @@ rg "class .*Service|module.exports" app/service/qimenMethods - sendToComputer, test - app/service/systems/qimen_query.js (6) - send, replaceXmlTagsWithString, addSign, getQueryParams, generateUrlWithParams, sendRequest +- app/service/systems/return_received.js (12) + - create, list, detail, delete, createBusinessError, _findByIdChecked, _enrichReturn, _resolveStoreRemark, _buildListWhere, _resolveConditionValue, _extractConditionValue, _buildListOrder - app/service/systems/setting/print_template.js (14) - listTemplatesByType, getTree, getTemplatesByType, save, getBusinessTypesAndItem, getGroupedPrintItems, getTableConfigs, clearBusinessTypesCache, getXmlByTemplate, buildXmlFromElements, renderElement, computeItemStyle, computeTableItemStyle, renderTable - app/service/systems/sign.js (10) diff --git a/app/dict/businessDict.js b/app/dict/businessDict.js index a9004a9..dc73d16 100644 --- a/app/dict/businessDict.js +++ b/app/dict/businessDict.js @@ -90,6 +90,7 @@ module.exports = { ORDER_EXPRESS_ALLOCATE_FAILED: '分配快递失败', ORDER_INTERCEPT_REQUEST: '请求订单拦截', ORDER_INTERCEPT_CANCEL: '解除订单拦截', + ORDER_RETURN_RECEIVED: '退回收到', ORDER_LOCK: '订单锁定', ORDER_UNLOCK: '订单解锁', diff --git a/app/model/return_received.js b/app/model/return_received.js new file mode 100644 index 0000000..40cc62a --- /dev/null +++ b/app/model/return_received.js @@ -0,0 +1,100 @@ +'use strict'; + +/** + * 退回收到登记表模型。 + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} Sequelize 模型。 + */ +module.exports = app => { + const { BIGINT, STRING, DATE } = app.Sequelize; + + const ReturnReceived = app.model.define('wms_return_received', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键ID', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID(数据隔离维度)', + }, + waybill_code: { + type: STRING(50), + allowNull: false, + comment: '退回收件运单号(扫描到的退回包裹单号)', + }, + scan_date: { + type: DATE, + allowNull: false, + comment: '扫描收到日期', + }, + scanner_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '扫描人员工号ID,关联 wms_account_store_employee.id(employees_id)', + }, + scanner_name: { + type: STRING(50), + allowNull: false, + comment: '扫描人员工号名称快照(employees_name / real_name)', + }, + order_express_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '运单表关联字段,关联 wms_order_express.id;原单退回时回填,非原单退回/非本仓库件时为空', + }, + order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '订单ID,方便快速匹配;非原单退回时为空', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '货主ID,原单退回时回填,用于查货主备注 wms_store_warehouse.store_remask', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + }, { + tableName: 'wms_return_received', + comment: '退回收到登记表', + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: false, + indexes: [ + { name: 'idx_warehouse_waybill_scan_date', fields: [ 'warehouse_id', 'waybill_code', 'scan_date' ] }, + { name: 'idx_warehouse_scan_date', fields: [ 'warehouse_id', 'scan_date' ] }, + { name: 'idx_scanner_id', fields: [ 'scanner_id' ] }, + { name: 'idx_order_express_id', fields: [ 'order_express_id' ] }, + { name: 'idx_store_id', fields: [ 'store_id' ] }, + ], + }); + + // 关联定义 + ReturnReceived.associate = function() { + const { Store, AccountStoreEmployee, OrderExpress } = app.model; + // 关联仓库(wms_store 主体表) + ReturnReceived.belongsTo(Store, { + foreignKey: 'warehouse_id', + as: 'warehouse', + }); + // 关联扫描人员工号 + ReturnReceived.belongsTo(AccountStoreEmployee, { + foreignKey: 'scanner_id', + as: 'scanner', + }); + // 关联原运单 + ReturnReceived.belongsTo(OrderExpress, { + foreignKey: 'order_express_id', + as: 'orderExpress', + }); + }; + + return ReturnReceived; +}; diff --git a/app/service/systemMethods/order/pendingOrder.js b/app/service/systemMethods/order/pendingOrder.js index 1f6d911..fbbd7ab 100644 --- a/app/service/systemMethods/order/pendingOrder.js +++ b/app/service/systemMethods/order/pendingOrder.js @@ -5673,15 +5673,15 @@ class PendingOrderService extends OrderBaseService { }, }); - // 同步清除运单表拦截+退回标记 + // 同步清除运单表拦截标记(退回收到标记 is_back 保持不变,由退回收货流程单独管理) try { await ctx.model.OrderExpress.update( - { is_intercept: 'N', is_back: 'N' }, + { is_intercept: 'N' }, { where: { order_id: { [Op.in]: chunkOrderIds }, warehouse_id: warehouseId } } ); } catch (expressErr) { ctx.logger.warn( - `[order.pendingOrder.batchUnintercept] 清除运单标记失败, count=${chunkOrderIds.length}, error=${expressErr.message}` + `[order.pendingOrder.batchUnintercept] 清除运单拦截标记失败, count=${chunkOrderIds.length}, error=${expressErr.message}` ); } diff --git a/app/service/systemMethods/order/recheckOrder.js b/app/service/systemMethods/order/recheckOrder.js index 200a48d..5dec0ae 100644 --- a/app/service/systemMethods/order/recheckOrder.js +++ b/app/service/systemMethods/order/recheckOrder.js @@ -3613,7 +3613,7 @@ class RecheckOrderService extends OrderBaseService { throw new Error('拦截状态更新失败,请稍后重试'); } - // 同步更新运单表:标记拦截 + 退回 + // 同步更新运单表:标记拦截 + 退回(库内拦截确认,货物在库内需退回) try { await ctx.model.OrderExpress.update( { is_intercept: 'Y', is_back: 'Y' }, @@ -3697,18 +3697,20 @@ class RecheckOrderService extends OrderBaseService { } /** - * 拦截扫描:通过运单号查找运单记录,标记退回并处理关联工单与订单拦截状态。 + * 拦截扫描:通过运单号查找运单记录,标记退回与拦截并处理关联工单与订单拦截状态。 * * 处理流程: - * 1. 根据运单号查询 wms_order_express,找到则将 is_back 设为 'Y';未找到则创建新记录补充缺失快递 + * 1. 根据运单号查询 wms_order_express,找到则将 is_back、is_intercept 设为 'Y';未找到则创建新记录补充缺失快递 * 2. 检查是否存在关联的未完结售后工单(wms_after_sale),若有则调用 handleWorkOrder 写入 * "库内拦截成功"步骤并将工单置为 completed * 3. 同步更新 wms_order_delivery 的 intercept_status 为 intercepted_at_warehouse, * 并释放储位分配与订单锁(与 confirmIntercept 行为一致,订单级拦截覆盖所有面单含子面单) * + * 注:库内拦截确认需标记退回 is_back='Y';发起拦截链路仅写 is_intercept,不写 is_back。 + * * @param {Object} data 请求体。 * @param {string} data.waybill_code 运单号。 - * @return {Promise} 拦截扫描结果,包含 waybill_code、is_back、after_sale(若有)、order。 + * @return {Promise} 拦截扫描结果,包含 waybill_code、is_back、is_intercept、after_sale(若有)、order。 */ async interceptScan(data = {}) { const { ctx, service } = this; @@ -3728,7 +3730,7 @@ class RecheckOrderService extends OrderBaseService { raw: true, }); - // 1a. 缺失快递补充:运单记录不存在则创建新记录 + // 1a. 缺失快递补充:运单记录不存在则创建新记录(库内拦截确认需标记退回) if (!expressRecord) { const created = await ctx.model.OrderExpress.create({ waybill_code: normalizedWaybillCode, @@ -3741,7 +3743,7 @@ class RecheckOrderService extends OrderBaseService { expressRecord = (created && created.toJSON ? created.toJSON() : created) || {}; } else { - // 2. 标记退回 + // 2. 标记退回 + 拦截 await ctx.model.OrderExpress.update( { is_back: 'Y', is_intercept: 'Y' }, { where: { id: expressRecord.id } } diff --git a/app/service/systemMethods/returnReceived.js b/app/service/systemMethods/returnReceived.js new file mode 100644 index 0000000..5262b92 --- /dev/null +++ b/app/service/systemMethods/returnReceived.js @@ -0,0 +1,107 @@ +'use strict'; + +const MainService = require('../main'); + +/** + * 系统方法层:returnReceived(退回收到模块接口包装层)。 + * 主要职责:统一包装系统方法接口,处理权限、where 解析等公共逻辑, + * 将具体业务逻辑下沉到 systems.return_received 中。 + */ +class ReturnReceivedMethodService extends MainService { + constructor(ctx) { + super(ctx); + // 免登录方法列表:空(全部需要登录) + const _noNeedLogin = ''; + // 免权限方法列表:detail 复用列表权限(仅登录 + 仓库隔离校验),其余走 API 权限校验 + const _noNeedRight = 'detail'; + // 免日志方法列表:空(全部记录日志) + const _noNeedLog = ''; + // 免鉴权(仓库有效期检查)方法列表:空(全部检查有效期) + const _noNeedAuth = ''; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 统一调用退回收到业务服务,并捕获业务错误码。 + * + * @param {Function} fn 业务调用函数。 + * @param {string} fallbackMessage 兜底错误文案。 + * @return {Promise} 统一 success/fail 包装。 + */ + async _call(fn, fallbackMessage) { + try { + const result = await fn(); + return this.success('ok', result); + } catch (error) { + const code = Number(error && error.code); + if (Number.isInteger(code) && code >= 400 && code < 600) { + return this.fail(error.message || fallbackMessage, {}, code); + } + this.ctx.logger.error(`[returnReceived] ${fallbackMessage}: ${error && error.message ? error.message : error}`); + return this.fail('服务器内部错误', {}, 500); + } + } + + /** + * 扫码登记退回包裹(增)。 + * + * @param {Object} data 请求体。 + * @param {string} data.waybill_code 退回收件运单号。 + * @param {string} [data.remark] 备注。 + * @return {Promise} 统一 success 包装。 + */ + async create(data = {}) { + const { waybill_code, remark } = data; + return this._call(() => this.service.systems.returnReceived.create({ waybill_code, remark }), '扫码登记失败'); + } + + /** + * 分页查询退回收到登记列表(查,仓库隔离自动注入)。 + * + * @param {Object} data 请求体。 + * @param {Object} [data.pagination] 分页参数。 + * @param {Object} [data.where] 筛选条件。 + * @param {Object} [data.sort] 排序参数。 + * @return {Promise} 统一 success 包装。 + */ + async list(data = {}) { + const { service } = this; + const { pagination, sort } = data; + const { where } = this.prepareWhereContext(data, {}); + + // 仓库隔离:由服务端从当前上下文自动注入,禁止前端传入 + const warehouseId = Number(this.ctx.user && this.ctx.user.store_id || 0); + const enforcedWhere = { ...where }; + if (warehouseId > 0) { + enforcedWhere.warehouse_id = { operator: 'eq', value: warehouseId }; + } + + return this._call(() => service.systems.returnReceived.list(enforcedWhere, pagination, sort), '查询列表失败'); + } + + /** + * 查询单条退回收到登记详情(查)。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 登记记录主键ID。 + * @return {Promise} 统一 success 包装。 + */ + async detail(data = {}) { + const { id } = data; + return this._call(() => this.service.systems.returnReceived.detail(Number(id)), '查询详情失败'); + } + + /** + * 删除单条退回收到登记记录(删)。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 登记记录主键ID。 + * @return {Promise} 统一 success 包装。 + */ + async delete(data = {}) { + const { id } = data; + return this._call(() => this.service.systems.returnReceived.delete(Number(id)), '删除失败'); + } +} + +module.exports = ReturnReceivedMethodService; diff --git a/app/service/systems/return_received.js b/app/service/systems/return_received.js new file mode 100644 index 0000000..bf9c192 --- /dev/null +++ b/app/service/systems/return_received.js @@ -0,0 +1,551 @@ +'use strict'; + +const Service = require('egg').Service; + +/** + * 退回收到模块业务逻辑层。 + * 负责 wms_return_received 的增删查,以及原单反查、货主备注、30 日幂等等核心操作。 + * 所有数据库交互集中在此层,供 systemMethods/returnReceived.js 调用。 + */ +class ReturnReceivedService extends Service { + /** + * 创建带业务错误码的异常对象。 + * @param {string} message 错误信息。 + * @param {number} [code=400] 业务错误码。 + * @return {Error} 包含 code 的异常对象。 + */ + createBusinessError(message, code = 400) { + const error = new Error(`${message}`); + error.code = code; + return error; + } + + /** + * 扫码登记退回包裹(30 日内同仓库同单号只写一次,以第一次为准)。 + * 反查原运单判定是否原单退回,命中则回填关联字段并同步标记 is_back='Y'。 + * + * @param {Object} params 登记参数。 + * @param {string} params.waybill_code 退回收件运单号。 + * @param {string} [params.remark] 备注。 + * @return {Promise} 登记结果,含 record、is_original_return、store_remark、duplicated。 + */ + async create({ waybill_code, remark }) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + const waybillCode = String(waybill_code || '').trim(); + if (!waybillCode) { + throw this.createBusinessError('waybill_code 不能为空', 400); + } + + const warehouseId = Number(ctx.user && ctx.user.store_id || 0); + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + throw this.createBusinessError('缺少仓库上下文', 400); + } + + const scannerId = ctx.user && ctx.user.employees_id ? Number(ctx.user.employees_id) : 0; + const scannerName = String( + (ctx.user && ctx.user.employees_name) || (ctx.user && ctx.user.real_name) || '' + ).trim(); + + if (!Number.isFinite(scannerId) || scannerId <= 0) { + throw this.createBusinessError('缺少扫描人员工号上下文', 400); + } + + // 30 日幂等窗口:同仓库 + 同单号,扫描日期在最近 30 天内则视为重复 + const now = new Date(); + const thirtyDaysAgo = new Date(now.getTime()); + thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30); + const scanDate = app.formatDate(now, 'YYYY-MM-DD'); + const windowStart = app.formatDate(thirtyDaysAgo, 'YYYY-MM-DD'); + + const existing = await ctx.model.ReturnReceived.findOne({ + where: { + warehouse_id: warehouseId, + waybill_code: waybillCode, + scan_date: { [Op.gte]: windowStart }, + }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + if (existing) { + const enriched = await this._enrichReturn(existing); + return { ...enriched, duplicated: true }; + } + + // 反查原运单,判定是否原单退回 + let orderExpressId = null; + let orderId = null; + let storeId = null; + try { + const orderExpress = await ctx.model.OrderExpress.findOne({ + where: { waybill_code: waybillCode }, + attributes: [ 'id', 'order_id', 'store_id' ], + raw: true, + }); + if (orderExpress) { + orderExpressId = orderExpress.id; + orderId = orderExpress.order_id; + storeId = orderExpress.store_id; + } + } catch (err) { + ctx.logger.warn(`[returnReceived.create] 反查原运单失败: ${err.message}`); + } + + const created = await ctx.model.ReturnReceived.create({ + warehouse_id: warehouseId, + waybill_code: waybillCode, + scan_date: scanDate, + scanner_id: scannerId, + scanner_name: scannerName || '未命名', + order_express_id: orderExpressId, + order_id: orderId, + store_id: storeId, + remark: remark ? String(remark).slice(0, 500) : null, + }); + + // 原单退回:同步标记 wms_order_express.is_back = 'Y' + if (orderExpressId) { + try { + await ctx.model.OrderExpress.update( + { is_back: 'Y' }, + { where: { id: orderExpressId } } + ); + } catch (err) { + ctx.logger.warn(`[returnReceived.create] 更新运单退回标记失败: ${err.message}`); + } + } + + // 原单退回:处理关联拦截工单 + 更新订单拦截状态(参考库内拦截,不处理库存信息) + if (orderExpressId) { + await this._handleInterceptAfterSale(waybillCode, warehouseId, scannerId, scannerName); + if (orderId) { + await this._updateOrderInterceptStatus(orderId, warehouseId, scannerId, scannerName); + } + } + + const createdRow = created && typeof created.toJSON === 'function' ? created.toJSON() : created; + const enriched = await this._enrichReturn(createdRow); + return { ...enriched, duplicated: false }; + } + + /** + * 处理退回运单关联的未完结拦截工单(写入「退回包裹已收到」并完结)。 + * 仅更新工单状态,不处理库存信息(参考库内拦截 interceptScan 的工单处理部分)。 + * + * @param {string} waybillCode 退回收件运单号。 + * @param {number} warehouseId 仓库ID。 + * @param {number} operatorId 操作人工号ID。 + * @param {string} operatorName 操作人工号名称。 + * @return {Promise} 无返回值。 + */ + async _handleInterceptAfterSale(waybillCode, warehouseId, operatorId, operatorName) { + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + try { + const afterSale = await ctx.model.AfterSale.findOne({ + where: { + waybill_no: waybillCode, + warehouse_id: warehouseId, + type: 'order', + sub_type: 'intercept', + deleted_at: null, + status: { [Op.notIn]: [ 'completed', 'closed', 'cancelled' ] }, + }, + order: [[ 'id', 'DESC' ]], + raw: true, + }); + + if (!afterSale) { + return; + } + + const operatorSnapshot = JSON.stringify({ + id: String(operatorId || ''), + name: String(operatorName || ''), + }); + + await ctx.service.systems.afterSale.handleWorkOrder({ + id: afterSale.id, + remark: '退回包裹已收到', + targetStatus: 'completed', + resolution: '退回包裹已收到', + attachmentIds: [], + operatorId: Number(operatorId) || 0, + operatorSnapshot, + warehouseId, + }); + } catch (err) { + ctx.logger.warn(`[returnReceived._handleInterceptAfterSale] 处理拦截工单失败, waybill=${waybillCode}, error=${err.message}`); + } + } + + /** + * 更新退回运单关联订单的退回状态并写入操作记录(不处理库存信息)。 + * - current 表(待处理):设置 intercept_status='returned'、step=4、outbound_status='fin' 触发自动转配送表; + * - dispatch 表(配送中):仅更新 intercept_status='returned'; + * - 不释放储位分配、不释放订单锁。 + * 兼容 current/dispatch 分表:先查 current 表,不存在再查 dispatch 表。 + * + * @param {number} orderId 订单ID。 + * @param {number} warehouseId 仓库ID。 + * @param {number} operatorId 操作人工号ID。 + * @param {string} operatorName 操作人工号名称。 + * @return {Promise} 无返回值。 + */ + async _updateOrderInterceptStatus(orderId, warehouseId, operatorId, operatorName) { + const { ctx } = this; + try { + const factory = ctx.model && ctx.model.OrderDeliveryFactory; + if (!factory || typeof factory.getCurrentModel !== 'function') { + return; + } + + const where = { id: orderId, warehouse_id: warehouseId }; + const orderAttributes = [ 'id', 'delivery_order_code', 'pre_delivery_order_code', 'intercept_status' ]; + + // 先查 current 表;不存在再查 dispatch 表 + let orderModel = await factory.getCurrentModel(warehouseId); + let order = orderModel && typeof orderModel.findOne === 'function' + ? await orderModel.findOne({ where, attributes: orderAttributes, raw: true }) + : null; + + const isCurrentTable = Boolean(order); + + if (!order && typeof factory.getDispatchModel === 'function') { + orderModel = await factory.getDispatchModel(warehouseId); + order = orderModel && typeof orderModel.findOne === 'function' + ? await orderModel.findOne({ where, attributes: orderAttributes, raw: true }) + : null; + } + + if (!order || !orderModel || typeof orderModel.update !== 'function') { + return; + } + + const updateFields = { + intercept_status: 'returned', + updated_at: new Date(), + }; + + // 待处理表(current):设置 step=4 + outbound_status='fin' 触发自动转配送表 + if (isCurrentTable) { + updateFields.step = 4; + updateFields.outbound_status = 'fin'; + } + + await orderModel.update(updateFields, { where }); + + // 写入订单操作记录 + const orderNo = String(order.delivery_order_code || order.pre_delivery_order_code || '').trim(); + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'order', + businessId: warehouseId, + operationCode: 'ORDER_RETURN_RECEIVED', + operator: { id: String(operatorId || ''), name: String(operatorName || '') }, + extras: { + warehouseId, + orderId, + orderNo, + previousInterceptStatus: String(order.intercept_status || '').trim(), + newInterceptStatus: 'returned', + }, + beforeChanges: null, + }); + } catch (logErr) { + ctx.logger.warn(`[returnReceived._updateOrderInterceptStatus] 写入订单操作日志失败, orderId=${orderId}, error=${logErr.message}`); + } + } catch (err) { + ctx.logger.warn(`[returnReceived._updateOrderInterceptStatus] 更新订单退回状态失败, orderId=${orderId}, error=${err.message}`); + } + } + + /** + * 分页查询退回收到登记列表(仓库隔离由方法层注入 warehouse_id)。 + * + * @param {Object} where 标准化 where 条件对象。 + * @param {Object} [pagination] 分页参数。 + * @param {number} [pagination.page=1] 页码。 + * @param {number} [pagination.pageSize=20] 每页数量。 + * @param {Object} [sort] 排序参数。 + * @param {string} [sort.sortField] 排序字段。 + * @param {string} [sort.sortOrder] 排序顺序(asc/desc)。 + * @return {Promise} { list: Array, pagination: Object }。 + */ + async list(where = {}, pagination = {}, sort = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + const page = Math.max(1, parseInt(pagination.page) || 1); + const pageSize = Math.min(500, Math.max(1, parseInt(pagination.pageSize) || 20)); + + const queryWhere = this._buildListWhere(where, Op); + const order = this._buildListOrder(sort); + + const { count, rows } = await ctx.model.ReturnReceived.findAndCountAll({ + where: queryWhere, + order, + offset: (page - 1) * pageSize, + limit: pageSize, + raw: true, + }); + + const list = []; + for (const row of rows) { + list.push(await this._enrichReturn(row)); + } + + return { + list, + pagination: { + page, + pageSize, + total: count, + totalPages: Math.ceil(count / pageSize), + hasPrevious: page > 1, + hasNext: page * pageSize < count, + }, + }; + } + + /** + * 查询单条退回收到登记详情(含原运单与货主合约备注)。 + * + * @param {number} id 登记记录主键ID。 + * @return {Promise} { record, order_express, store_contract }。 + */ + async detail(id) { + const { ctx } = this; + const record = await this._findByIdChecked(id); + const enriched = await this._enrichReturn(record); + + const orderExpress = record.order_express_id + ? await ctx.model.OrderExpress.findOne({ + where: { id: record.order_express_id }, + attributes: [ + 'id', 'waybill_code', 'order_id', 'store_id', 'warehouse_id', + 'is_back', 'is_intercept', 'logistics_name', 'logistics_code', + ], + raw: true, + }) + : null; + + const storeContract = record.store_id + ? await ctx.model.StoreWarehouse.findOne({ + where: { store_id: record.store_id, warehouse_id: record.warehouse_id }, + attributes: [ + 'id', 'store_id', 'warehouse_id', 'store_remask', 'warehouse_remask', + 'store_use_status', 'warehouse_use_status', + ], + raw: true, + }) + : null; + + return { + record: enriched, + order_express: orderExpress, + store_contract: storeContract, + }; + } + + /** + * 删除单条退回收到登记记录(物理删除)。 + * + * @param {number} id 登记记录主键ID。 + * @return {Promise} 删除结果,含被删除记录 id。 + */ + async delete(id) { + const { ctx } = this; + const record = await this._findByIdChecked(id); + await ctx.model.ReturnReceived.destroy({ where: { id: record.id } }); + return { id: record.id }; + } + + /** + * 按主键查询登记记录,并校验仓库隔离。 + * + * @param {number} id 登记记录主键ID。 + * @return {Promise} 登记记录原始数据。 + */ + async _findByIdChecked(id) { + const { ctx } = this; + const normalizedId = Number(id || 0); + if (!Number.isFinite(normalizedId) || normalizedId <= 0) { + throw this.createBusinessError('id 必填且必须为正整数', 400); + } + + const record = await ctx.model.ReturnReceived.findOne({ + where: { id: normalizedId }, + raw: true, + }); + if (!record) { + throw this.createBusinessError('登记记录不存在', 404); + } + + const warehouseId = Number(ctx.user && ctx.user.store_id || 0); + if (warehouseId > 0 && Number(record.warehouse_id) !== warehouseId) { + throw this.createBusinessError('无权访问该登记记录', 403); + } + + return record; + } + + /** + * 组装登记记录展示字段(是否原单退回、货主备注、时间格式化)。 + * + * @param {Object} row 登记记录原始数据。 + * @return {Promise} 组装后的记录。 + */ + async _enrichReturn(row) { + const { app } = this; + const record = { ...row }; + record.is_original_return = Boolean(record.order_express_id); + record.store_remark = await this._resolveStoreRemark(record); + // 时间格式化(与 afterSale._formatAfterSaleRow 一致,直接覆盖为本地时间字符串) + record.scan_date = record.scan_date ? app.formatDate(record.scan_date, 'YYYY-MM-DD') : null; + record.created_at = record.created_at ? app.formatDate(record.created_at) : null; + record.updated_at = record.updated_at ? app.formatDate(record.updated_at) : null; + return record; + } + + /** + * 查询货主合约备注名称(wms_store_warehouse.store_remask)。 + * + * @param {Object} record 登记记录。 + * @return {Promise} 货主备注名称,无货主或未命中时返回空字符串。 + */ + async _resolveStoreRemark(record) { + const { ctx } = this; + const storeId = Number(record && record.store_id || 0); + const warehouseId = Number(record && record.warehouse_id || 0); + if (!storeId || !warehouseId) { + return ''; + } + try { + const sw = await ctx.model.StoreWarehouse.findOne({ + where: { store_id: storeId, warehouse_id: warehouseId }, + attributes: [ 'store_remask' ], + raw: true, + }); + return (sw && sw.store_remask) || ''; + } catch (err) { + ctx.logger.warn(`[returnReceived._resolveStoreRemark] 查询货主备注失败: ${err.message}`); + return ''; + } + } + + /** + * 根据标准化 where 条件构建 Sequelize 查询条件。 + * + * @param {Object} where 标准化 where 条件对象。 + * @param {Object} Op Sequelize Op 对象。 + * @return {Object} Sequelize where 条件。 + */ + _buildListWhere(where = {}, Op) { + const queryWhere = {}; + + const directFields = [ + 'warehouse_id', 'scanner_id', 'store_id', 'order_express_id', 'order_id', + 'waybill_code', 'scan_date', 'scanner_name', + ]; + + for (const field of directFields) { + if (where[field] !== undefined && where[field] !== null) { + queryWhere[field] = this._resolveConditionValue(where[field], Op); + } + } + + // 是否原单退回(派生字段):true=有关联运单,false=无关联 + if (where.is_original_return !== undefined && where.is_original_return !== null) { + const flag = this._extractConditionValue(where.is_original_return); + if (flag === true || flag === 1 || flag === '1' || flag === 'true') { + queryWhere.order_express_id = { [Op.ne]: null }; + } else { + queryWhere.order_express_id = null; + } + } + + return queryWhere; + } + + /** + * 解析标准化条件值为 Sequelize 可用的条件对象。 + * + * @param {*} condition 标准化条件(可能是 {operator, value} 或直接值)。 + * @param {Object} Op Sequelize Op 对象。 + * @return {*} Sequelize 条件。 + */ + _resolveConditionValue(condition, Op) { + if (condition && typeof condition === 'object' && !Array.isArray(condition)) { + const operator = condition.operator; + const value = condition.value; + + if (!operator) { + return value; + } + + switch (operator) { + case 'eq': + return value; + case 'ne': + return { [Op.ne]: value }; + case 'in': + return { [Op.in]: Array.isArray(value) ? value : [ value ] }; + case 'notin': + return { [Op.notIn]: Array.isArray(value) ? value : [ value ] }; + case 'like': + return { [Op.like]: `%${value}%` }; + case 'gt': + return { [Op.gt]: value }; + case 'gte': + return { [Op.gte]: value }; + case 'lt': + return { [Op.lt]: value }; + case 'lte': + return { [Op.lte]: value }; + case 'between': + return { [Op.between]: Array.isArray(value) ? value : [ value ] }; + default: + return value; + } + } + + return condition; + } + + /** + * 从条件对象中提取原始 value。 + * + * @param {*} condition 标准化条件。 + * @return {*} 原始值。 + */ + _extractConditionValue(condition) { + if (condition && typeof condition === 'object' && !Array.isArray(condition)) { + if ('value' in condition) { + return condition.value; + } + } + return condition; + } + + /** + * 根据 sort 参数构建 Sequelize 排序数组。 + * + * @param {Object} sort 排序参数。 + * @return {Array>} Sequelize order 数组。 + */ + _buildListOrder(sort = {}) { + const sortField = sort.sortField || sort.sort_field || 'created_at'; + const sortOrderRaw = (sort.sortOrder || sort.sort_order || 'desc').toLowerCase(); + const sortOrder = sortOrderRaw === 'asc' ? 'ASC' : 'DESC'; + + const allowedSortFields = new Set([ 'id', 'scan_date', 'created_at', 'updated_at', 'waybill_code' ]); + const safeSortField = allowedSortFields.has(sortField) ? sortField : 'created_at'; + + return [[ safeSortField, sortOrder ]]; + } +} + +module.exports = ReturnReceivedService; diff --git a/database/migrations/20260812160000-create-wms-return-received.js b/database/migrations/20260812160000-create-wms-return-received.js new file mode 100644 index 0000000..bd4c4a3 --- /dev/null +++ b/database/migrations/20260812160000-create-wms-return-received.js @@ -0,0 +1,87 @@ +'use strict'; + +/** + * 创建退回收到登记表 wms_return_received。 + * + * 字段:仓库隔离 warehouse_id、退回收件运单号 waybill_code、扫描日期 scan_date、 + * 扫描人员 scanner_id/scanner_name、运单关联 order_express_id/order_id/store_id(非必填)。 + * + * 索引: + * idx_warehouse_waybill_scan_date(30 日幂等查询) + * idx_warehouse_scan_date(仓库+日期隔离查询) + * idx_scanner_id / idx_order_express_id / idx_store_id + */ + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + const { BIGINT, STRING, DATE } = Sequelize; + await queryInterface.createTable('wms_return_received', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID(数据隔离维度)', + }, + waybill_code: { + type: STRING(50), + allowNull: false, + comment: '退回收件运单号(扫描到的退回包裹单号)', + }, + scan_date: { + type: DATE, + allowNull: false, + comment: '扫描收到日期', + }, + scanner_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '扫描人员工号ID(employees_id)', + }, + scanner_name: { + type: STRING(50), + allowNull: false, + comment: '扫描人员工号名称快照(employees_name / real_name)', + }, + order_express_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '运单表关联字段,关联 wms_order_express.id;非必填', + }, + order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '订单ID,方便快速匹配;非必填', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '货主ID,原单退回时回填,用于查货主备注', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + created_at: { type: DATE, allowNull: false }, + updated_at: { type: DATE, allowNull: false }, + }); + + await queryInterface.addIndex('wms_return_received', [ 'warehouse_id', 'waybill_code', 'scan_date' ], { name: 'idx_warehouse_waybill_scan_date' }); + await queryInterface.addIndex('wms_return_received', [ 'warehouse_id', 'scan_date' ], { name: 'idx_warehouse_scan_date' }); + await queryInterface.addIndex('wms_return_received', [ 'scanner_id' ], { name: 'idx_scanner_id' }); + await queryInterface.addIndex('wms_return_received', [ 'order_express_id' ], { name: 'idx_order_express_id' }); + await queryInterface.addIndex('wms_return_received', [ 'store_id' ], { name: 'idx_store_id' }); + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + await queryInterface.dropTable('wms_return_received'); + }, +}; diff --git a/database/migrations/20260813100000-create-return-received-permissions.js b/database/migrations/20260813100000-create-return-received-permissions.js new file mode 100644 index 0000000..bfc1ef0 --- /dev/null +++ b/database/migrations/20260813100000-create-return-received-permissions.js @@ -0,0 +1,98 @@ +'use strict'; + +/** + * 退回收到模块权限记录 + 角色授权迁移。 + * + * 权限明细(固定 ID): + * 527 — returnReceived.create API:退回收件扫码登记 + * 528 — returnReceived.list API:退回收件列表查询 + * 529 — returnReceived.delete API:退回收件删除 + * + * 角色授权(系统预设角色,不含通配符角色): + * 527(扫码登记)→ 仓库组-员工(27) → 仓库组-主管(26)(仓库员工及以上) + * 528(列表)、529(删除)→ 客服组-员工(30) → 客服组-主管(28)(客服员工及以上) + * 经理(8)/仓库管理员(2)/超级管理员(7) 已持有 * 通配符,自动拥有所有权限,无需处理 + * + * 幂等:INSERT IGNORE 创建权限记录;角色权限数组追加后去重排序,已存在跳过。 + */ + +const TABLE = 'wms_permission'; +const ROLE_TABLE = 'wms_role'; +const COLUMNS = 'id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at'; + +/** 权限ID → 授权角色ID列表(不含通配符角色) */ +const PERMISSION_ROLES = { + 527: [ 27, 26 ], + 528: [ 30, 28 ], + 529: [ 30, 28 ], +}; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + // ── 1. 创建 API 权限记录(固定 ID)── + const apis = [ + [ 527, 'returnReceived.create', 'API:退回收件扫码登记' ], + [ 528, 'returnReceived.list', 'API:退回收件列表查询' ], + [ 529, 'returnReceived.delete', 'API:退回收件删除' ], + ]; + + for (const [ id, path, metaTitle ] of apis) { + await queryInterface.sequelize.query( + `INSERT IGNORE INTO \`${TABLE}\` (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`, + { replacements: [ id, path, null, path, null, metaTitle, null, 0, 0, null, 'api', 0, 1 ] } + ); + } + + // ── 2. 角色授权注入 ── + for (const permId of Object.keys(PERMISSION_ROLES).map(Number)) { + for (const roleId of PERMISSION_ROLES[permId]) { + const rows = await queryInterface.sequelize.query( + `SELECT id, permissions FROM \`${ROLE_TABLE}\` WHERE id = ?`, + { replacements: [ roleId ], type: queryInterface.sequelize.QueryTypes.SELECT } + ); + const record = Array.isArray(rows) ? rows[0] : null; + if (!record) { + continue; + } + + // 通配符角色跳过 + if (record.permissions === '*') { + continue; + } + + let perms; + try { + perms = JSON.parse(record.permissions || '[]'); + } catch (err) { + continue; + } + if (!Array.isArray(perms)) { + continue; + } + + if (perms.includes(permId)) { + continue; + } + + perms.push(permId); + perms.sort((a, b) => a - b); + + await queryInterface.sequelize.query( + `UPDATE \`${ROLE_TABLE}\` SET permissions = ? WHERE id = ?`, + { replacements: [ JSON.stringify(perms), roleId ] } + ); + } + } + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + const ids = [ 527, 528, 529 ]; + const placeholders = ids.map(() => '?').join(', '); + await queryInterface.sequelize.query( + `DELETE FROM \`${TABLE}\` WHERE id IN (${placeholders})`, + { replacements: ids } + ); + }, +}; diff --git a/database/migrations/20260813110000-add-return-received-menu-permission.js b/database/migrations/20260813110000-add-return-received-menu-permission.js new file mode 100644 index 0000000..38823d6 --- /dev/null +++ b/database/migrations/20260813110000-add-return-received-menu-permission.js @@ -0,0 +1,82 @@ +'use strict'; + +/** + * 快递菜单下新增 web_pages 子菜单「快递收件」(id=530),并授权客服员工及以上角色。 + * + * 权限明细: + * 530 — returnReceived(web_pages 菜单,parent_id=19 快递/物流) + * + * 角色授权(系统预设角色,不含通配符角色): + * 530 → 客服组-员工(30) → 客服组-主管(28)(客服员工及以上) + * 经理(8)/仓库管理员(2)/超级管理员(7) 已持有 * 通配符,自动拥有所有权限,无需处理 + * + * 幂等:INSERT IGNORE 创建菜单权限;角色权限数组追加后去重排序,已存在跳过。 + */ + +const TABLE = 'wms_permission'; +const ROLE_TABLE = 'wms_role'; +const COLUMNS = 'id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at'; + +/** 权限ID → 授权角色ID列表(不含通配符角色) */ +const PERMISSION_ROLES = { + 530: [ 30, 28 ], +}; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + // ── 1. 创建 web_pages 菜单权限(固定 ID,parent_id=19 快递/物流)── + await queryInterface.sequelize.query( + `INSERT IGNORE INTO \`${TABLE}\` (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`, + { replacements: [ 530, 'returnReceived', '@/views/express/returnReceived/index', 'returnReceived', null, '快递收件', null, 0, 0, 19, 'web_pages', 1, 1 ] } + ); + + // ── 2. 角色授权注入 ── + for (const permId of Object.keys(PERMISSION_ROLES).map(Number)) { + for (const roleId of PERMISSION_ROLES[permId]) { + const rows = await queryInterface.sequelize.query( + `SELECT id, permissions FROM \`${ROLE_TABLE}\` WHERE id = ?`, + { replacements: [ roleId ], type: queryInterface.sequelize.QueryTypes.SELECT } + ); + const record = Array.isArray(rows) ? rows[0] : null; + if (!record) { + continue; + } + + // 通配符角色跳过 + if (record.permissions === '*') { + continue; + } + + let perms; + try { + perms = JSON.parse(record.permissions || '[]'); + } catch (err) { + continue; + } + if (!Array.isArray(perms)) { + continue; + } + + if (perms.includes(permId)) { + continue; + } + + perms.push(permId); + perms.sort((a, b) => a - b); + + await queryInterface.sequelize.query( + `UPDATE \`${ROLE_TABLE}\` SET permissions = ? WHERE id = ?`, + { replacements: [ JSON.stringify(perms), roleId ] } + ); + } + } + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + await queryInterface.sequelize.query( + `DELETE FROM \`${TABLE}\` WHERE id = 530` + ); + }, +}; diff --git a/methods/changes/system.json b/methods/changes/system.json index a22f3e1..239f8da 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -5753,5 +5753,27 @@ "subType 枚举由 GROUP_TYPES 统一定义,与 AI 函数分组同源", "后端已新增两层类型校验:subType 必须在对应 groupType 的合法子类型列表中" ] + }, + { + "version": "2026.08.13-returnReceived", + "date": "2026-08-13", + "type": "added", + "summary": "新增退回收到模块(returnReceived):退回包裹扫码登记、分页列表、详情、删除四个接口。扫码登记30日内同仓库同单号幂等(以第一次为准),反查原运单判定是否原单退回并同步标记 is_back='Y';列表/详情/删除仓库隔离。配套权限 527/528/529(扫码登记→仓库员工及以上,列表/删除→客服员工及以上)", + "methods": [ + "returnReceived.create", + "returnReceived.list", + "returnReceived.detail", + "returnReceived.delete" + ], + "notes": [ + "新增表 wms_return_received(仓库隔离 warehouse_id、退回收件单号 waybill_code、扫描日期 scan_date、扫描人员 scanner_id/scanner_name、运单关联 order_express_id/order_id/store_id 非必填)", + "returnReceived.create:30日幂等 + 反查 wms_order_express.waybill_code,命中回填关联字段并同步 is_back='Y',返回 is_original_return/store_remark/duplicated", + "returnReceived.list:分页列表,仓库隔离由服务端注入 warehouse_id,支持运单号/日期/扫描人员/货主/是否原单退回筛选", + "returnReceived.detail:详情含原运单与货主合约备注,免权限但需登录+仓库隔离", + "returnReceived.delete:物理删除,需权限+仓库隔离", + "权限:527 returnReceived.create(仓库员工及以上)、528 returnReceived.list、529 returnReceived.delete(客服员工及以上);detail 复用 list 权限", + "代码变更:app/model/return_received.js、app/service/systems/return_received.js、app/service/systemMethods/returnReceived.js、database/migrations/20260812160000-create-wms-return-received.js、20260813100000-create-return-received-permissions.js" + ], + "module": "returnReceived" } ] diff --git a/methods/system.json b/methods/system.json index 5044a83..55b7389 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1,8 +1,8 @@ { "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", - "version": "0.3.21", - "updatedAt": "2026-08-11", + "version": "0.3.22", + "updatedAt": "2026-08-13", "headers": [ { "name": "platform", @@ -34740,6 +34740,316 @@ "errors": [] } ] + }, + { + "groupName": "退回收到模块", + "module": "returnReceived", + "list": [ + { + "method": "returnReceived.create", + "description": "退回包裹扫码登记。30日内同仓库同单号只写一次(以第一次为准);反查 wms_order_express 判定是否原单退回,命中则回填 order_express_id/order_id/store_id 并同步标记 is_back='Y'。仓库隔离:warehouse_id 由服务端注入 ctx.user.store_id,禁止前端传入。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "waybill_code", + "type": "string", + "required": true, + "source": "body", + "description": "退回收件运单号(扫描到的退回包裹单号)" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注" + } + ], + "response": [ + { + "name": "id", + "type": "integer", + "required": true, + "description": "登记记录主键ID" + }, + { + "name": "waybill_code", + "type": "string", + "required": true, + "description": "退回收件运单号" + }, + { + "name": "scan_date", + "type": "string", + "required": true, + "description": "扫描收到日期" + }, + { + "name": "scanner_id", + "type": "integer", + "required": true, + "description": "扫描人员工号ID" + }, + { + "name": "scanner_name", + "type": "string", + "required": true, + "description": "扫描人员工号名称" + }, + { + "name": "order_express_id", + "type": "integer", + "required": false, + "description": "原运单ID(原单退回时回填,否则为 null)" + }, + { + "name": "order_id", + "type": "integer", + "required": false, + "description": "原订单ID(原单退回时回填,否则为 null)" + }, + { + "name": "store_id", + "type": "integer", + "required": false, + "description": "货主ID(原单退回时回填,否则为 null)" + }, + { + "name": "remark", + "type": "string", + "required": false, + "description": "备注" + }, + { + "name": "is_original_return", + "type": "boolean", + "required": true, + "description": "是否原单退回" + }, + { + "name": "store_remark", + "type": "string", + "required": true, + "description": "货主的合约货主备注名称(wms_store_warehouse.store_remask),非原单退回时为空字符串" + }, + { + "name": "duplicated", + "type": "boolean", + "required": true, + "description": "是否命中30日幂等、返回第一次记录" + } + ], + "errors": [ + { + "code": "400", + "message": "waybill_code 不能为空" + }, + { + "code": "400", + "message": "缺少仓库上下文" + }, + { + "code": "400", + "message": "缺少扫描人员工号上下文" + }, + { + "code": "401", + "message": "未提供有效的认证令牌" + }, + { + "code": "403", + "message": "无权访问该接口" + } + ] + }, + { + "method": "returnReceived.list", + "description": "退回收到登记分页列表。仓库隔离(服务端自动注入 warehouse_id = ctx.user.store_id,禁止前端传入)。支持按运单号模糊、扫描日期范围、扫描人员、货主、是否原单退回筛选。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页 { page: 1, pageSize: 20 }" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "筛选条件对象,所有字段均可选" + }, + { + "name": "where.waybill_code", + "type": "string", + "required": false, + "source": "body.where", + "description": "退回收件运单号(模糊搜索,传 {operator:'like',value} 或直接值)" + }, + { + "name": "where.scan_date", + "type": "object", + "required": false, + "source": "body.where", + "description": "扫描日期范围 { operator:'between'|'gte'|'lte', value:[start,end] 或单值 }" + }, + { + "name": "where.scanner_id", + "type": "number", + "required": false, + "source": "body.where", + "description": "扫描人员工号ID(等值)" + }, + { + "name": "where.store_id", + "type": "number", + "required": false, + "source": "body.where", + "description": "货主ID(等值)" + }, + { + "name": "where.is_original_return", + "type": "boolean", + "required": false, + "source": "body.where", + "description": "是否原单退回:true=有关联原运单,false=无关联" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序 { sortField: 'id'|'scan_date'|'created_at'|'updated_at'|'waybill_code', sortOrder: 'asc'|'desc' }" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "退回收到登记列表,每条含登记字段 + is_original_return + store_remark" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息 { page, pageSize, total, totalPages, hasPrevious, hasNext }" + } + ], + "errors": [ + { + "code": "401", + "message": "未提供有效的认证令牌" + }, + { + "code": "403", + "message": "无权访问该接口" + } + ] + }, + { + "method": "returnReceived.detail", + "description": "退回收到登记详情,含原运单(命中时)与货主合约备注(命中时)。免权限但需登录,仓库隔离校验(仅本仓库记录)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "id", + "type": "integer", + "required": true, + "source": "body", + "description": "登记记录主键ID" + } + ], + "response": [ + { + "name": "record", + "type": "object", + "required": true, + "description": "登记记录完整信息(含 is_original_return、store_remark、格式化时间字段)" + }, + { + "name": "order_express", + "type": "object", + "required": false, + "description": "原运单详情(order_express_id 不为空时)。含 waybill_code、order_id、store_id、warehouse_id、is_back、is_intercept、logistics_name、logistics_code" + }, + { + "name": "store_contract", + "type": "object", + "required": false, + "description": "货主合约备注(store_id 不为空时)。含 store_remask、warehouse_remask、store_use_status、warehouse_use_status" + } + ], + "errors": [ + { + "code": "400", + "message": "id 必填且必须为正整数" + }, + { + "code": "401", + "message": "未提供有效的认证令牌" + }, + { + "code": "403", + "message": "无权访问该登记记录" + }, + { + "code": "404", + "message": "登记记录不存在" + } + ] + }, + { + "method": "returnReceived.delete", + "description": "删除退回收到登记记录(物理删除)。仓库隔离校验(仅本仓库记录)。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "id", + "type": "integer", + "required": true, + "source": "body", + "description": "登记记录主键ID" + } + ], + "response": [ + { + "name": "id", + "type": "integer", + "required": true, + "description": "被删除登记记录ID" + } + ], + "errors": [ + { + "code": "400", + "message": "id 必填且必须为正整数" + }, + { + "code": "401", + "message": "未提供有效的认证令牌" + }, + { + "code": "403", + "message": "无权访问该登记记录" + }, + { + "code": "404", + "message": "登记记录不存在" + } + ] + } + ] } ] } From 38b29be7769a739041ee4ab3d54cc8a23cec5d25 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Thu, 13 Aug 2026 21:40:50 +0800 Subject: [PATCH 199/550] =?UTF-8?q?feat:=20=E6=96=B0=E5=A2=9E=E9=80=80?= =?UTF-8?q?=E5=9B=9E=E6=8B=86=E5=8C=85=E6=A8=A1=E5=9D=97=EF=BC=88returnUnp?= =?UTF-8?q?ack=EF=BC=89=E4=B8=8E=E5=BA=8F=E5=88=97=E8=A1=A8=E5=8E=9F?= =?UTF-8?q?=E5=AD=90=E5=8F=96=E5=8F=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 wms_return_unpack 主表/明细/视频 与 wms_return_query_log 表(model + 迁移) - 新增序列表 wms_number_sequence,单号取号改为 INSERT...ON DUPLICATE KEY 原子递增(含历史 seed 对齐) - 补齐 wms_order_delivery 基表缺失 25 列(修复 Unknown column) - 权限固定 ID 540-549 + 角色授权迁移 - 修复 returnReceived.create 出参 record 包装;修复 afterSale 发件人查询列名(name→company_name) - detail 接口按设计走 548 权限校验 --- app/model/number_sequence.js | 55 + app/model/return_query_log.js | 65 ++ app/model/return_unpack.js | 166 +++ app/model/return_unpack_detail.js | 111 ++ app/model/return_unpack_video.js | 89 ++ app/service/systemMethods/returnUnpack.js | 219 ++++ app/service/systems/afterSale.js | 398 +++---- app/service/systems/return_received.js | 14 +- app/service/systems/return_unpack.js | 1008 +++++++++++++++++ ...20260813120000-create-wms-return-unpack.js | 145 +++ ...3120100-create-wms-return-unpack-detail.js | 110 ++ ...13120200-create-wms-return-unpack-video.js | 66 ++ ...60813120300-create-wms-return-query-log.js | 75 ++ ...130000-create-return-unpack-permissions.js | 119 ++ ...der-delivery-base-table-missing-columns.js | 118 ++ ...260813150000-create-wms-number-sequence.js | 63 ++ 16 files changed, 2620 insertions(+), 201 deletions(-) create mode 100644 app/model/number_sequence.js create mode 100644 app/model/return_query_log.js create mode 100644 app/model/return_unpack.js create mode 100644 app/model/return_unpack_detail.js create mode 100644 app/model/return_unpack_video.js create mode 100644 app/service/systemMethods/returnUnpack.js create mode 100644 app/service/systems/return_unpack.js create mode 100644 database/migrations/20260813120000-create-wms-return-unpack.js create mode 100644 database/migrations/20260813120100-create-wms-return-unpack-detail.js create mode 100644 database/migrations/20260813120200-create-wms-return-unpack-video.js create mode 100644 database/migrations/20260813120300-create-wms-return-query-log.js create mode 100644 database/migrations/20260813130000-create-return-unpack-permissions.js create mode 100644 database/migrations/20260813140000-add-order-delivery-base-table-missing-columns.js create mode 100644 database/migrations/20260813150000-create-wms-number-sequence.js diff --git a/app/model/number_sequence.js b/app/model/number_sequence.js new file mode 100644 index 0000000..d6aab1e --- /dev/null +++ b/app/model/number_sequence.js @@ -0,0 +1,55 @@ +'use strict'; + +/** + * 业务单号序列表模型。 + * 按「仓库 + 业务类型 + 日期」维度原子分配序号, + * 取号使用 INSERT ... ON DUPLICATE KEY UPDATE current_seq = LAST_INSERT_ID(current_seq + 1), + * 避免「查当日最大序号+1」在并发下的撞号问题。 + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} Sequelize 模型。 + */ +module.exports = app => { + const { BIGINT, STRING, INTEGER, CHAR } = app.Sequelize; + + const NumberSequence = app.model.define('wms_number_sequence', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID(序号隔离维度)', + }, + biz_type: { + type: STRING(30), + allowNull: false, + comment: '业务类型,如 return_unpack(退回拆包单号)', + }, + date_part: { + type: CHAR(8), + allowNull: false, + comment: '日期片段 YYYYMMDD', + }, + current_seq: { + type: INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '当前已分配序号(原子递增)', + }, + }, { + tableName: 'wms_number_sequence', + comment: '业务单号序列表(原子取号)', + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: false, + indexes: [ + { name: 'uk_warehouse_biz_date', unique: true, fields: [ 'warehouse_id', 'biz_type', 'date_part' ] }, + ], + }); + + return NumberSequence; +}; diff --git a/app/model/return_query_log.js b/app/model/return_query_log.js new file mode 100644 index 0000000..ff693b9 --- /dev/null +++ b/app/model/return_query_log.js @@ -0,0 +1,65 @@ +'use strict'; + +/** + * 退回查询记录表模型(货主未退回、但做过查询退回的运单号)。 + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} Sequelize 模型。 + */ +module.exports = app => { + const { BIGINT, STRING, TINYINT } = app.Sequelize; + + const ReturnQueryLog = app.model.define('wms_return_query_log', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID(隔离维度)', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '货主ID(隔离维度)', + }, + waybill_code: { + type: STRING(50), + allowNull: false, + comment: '查询过的运单号', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + is_notified: { + type: TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '是否已通知:0=未通知,1=已通知', + }, + is_back: { + type: TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '是否退回:0=未退回,1=已退回', + }, + }, { + tableName: 'wms_return_query_log', + comment: '退回查询记录表(货主未退回但查询过的运单号)', + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: false, + indexes: [ + { name: 'idx_warehouse_store_waybill', fields: [ 'warehouse_id', 'store_id', 'waybill_code' ] }, + { name: 'idx_warehouse_store', fields: [ 'warehouse_id', 'store_id' ] }, + { name: 'idx_waybill_code', fields: [ 'waybill_code' ] }, + ], + }); + + return ReturnQueryLog; +}; diff --git a/app/model/return_unpack.js b/app/model/return_unpack.js new file mode 100644 index 0000000..60316b7 --- /dev/null +++ b/app/model/return_unpack.js @@ -0,0 +1,166 @@ +'use strict'; + +/** + * 退回拆包主表模型。 + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} Sequelize 模型。 + */ +module.exports = app => { + const { BIGINT, STRING, INTEGER, DATE, JSON: JSON_TYPE } = app.Sequelize; + + const ReturnUnpack = app.model.define('wms_return_unpack', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID(数据隔离维度)', + }, + unpack_no: { + type: STRING(50), + allowNull: false, + unique: true, + comment: '拆包单号,RP+YYYYMMDD+6位序号', + }, + return_received_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '关联退回收到表 wms_return_received.id;非必填', + }, + waybill_code: { + type: STRING(50), + allowNull: false, + comment: '拆包的运单号(退回包裹运单号)', + }, + unpack_date: { + type: DATE, + allowNull: false, + comment: '拆包日期', + }, + start_time: { + type: DATE, + allowNull: true, + comment: '拆包开始时间(参考打包表 start_time)', + }, + end_time: { + type: DATE, + allowNull: true, + comment: '拆包结束时间(参考打包表 end_time)', + }, + unpacker_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '拆包人员工号ID,关联 wms_account_store_employee.id(employees_id)', + }, + unpacker_name: { + type: STRING(50), + allowNull: false, + comment: '拆包人员工号名称快照(employees_name / real_name)', + }, + status: { + type: STRING(20), + allowNull: false, + defaultValue: 'unpacking', + comment: '拆包状态:unpacking/completed/cancelled', + }, + detail_status: { + type: STRING(30), + allowNull: false, + defaultValue: 'none_recognized', + comment: '明细识别状态:none_recognized/partial_recognized/all_recognized', + }, + total_items: { + type: INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '物品种类数(明细行数)', + }, + total_quantity: { + type: INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '物品总数量(明细数量合计)', + }, + order_express_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '原运单ID,关联 wms_order_express.id;原单退回时回填', + }, + order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '原订单ID,便于快速匹配;原单退回时回填', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '货主ID,原单退回/识别到系统商品时回填', + }, + camera_ids: { + type: JSON_TYPE, + allowNull: true, + comment: '摄像头ID列表,如 [1,2,3](参考 wms_pack_task.device_ids)', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + }, { + tableName: 'wms_return_unpack', + comment: '退回拆包主表', + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: false, + indexes: [ + { name: 'uk_unpack_no', unique: true, fields: [ 'unpack_no' ] }, + { name: 'idx_warehouse_unpack_date', fields: [ 'warehouse_id', 'unpack_date' ] }, + { name: 'idx_return_received_id', fields: [ 'return_received_id' ] }, + { name: 'idx_waybill_code', fields: [ 'waybill_code' ] }, + { name: 'idx_order_express_id', fields: [ 'order_express_id' ] }, + { name: 'idx_unpacker_id', fields: [ 'unpacker_id' ] }, + { name: 'idx_start_time', fields: [ 'start_time' ] }, + { name: 'idx_store_id', fields: [ 'store_id' ] }, + ], + }); + + ReturnUnpack.associate = function() { + const { Store, AccountStoreEmployee, ReturnReceived, ReturnUnpackDetail, ReturnUnpackVideo, OrderExpress } = app.model; + // 关联仓库(wms_store 主体表) + ReturnUnpack.belongsTo(Store, { + foreignKey: 'warehouse_id', + as: 'warehouse', + }); + // 关联拆包人员工号 + ReturnUnpack.belongsTo(AccountStoreEmployee, { + foreignKey: 'unpacker_id', + as: 'unpacker', + }); + // 关联退回收到单(非必填) + ReturnUnpack.belongsTo(ReturnReceived, { + foreignKey: 'return_received_id', + as: 'returnReceived', + }); + // 关联原运单 + ReturnUnpack.belongsTo(OrderExpress, { + foreignKey: 'order_express_id', + as: 'orderExpress', + }); + // 明细 / 视频 + ReturnUnpack.hasMany(ReturnUnpackDetail, { + foreignKey: 'unpack_id', + as: 'details', + }); + ReturnUnpack.hasMany(ReturnUnpackVideo, { + foreignKey: 'unpack_id', + as: 'videos', + }); + }; + + return ReturnUnpack; +}; diff --git a/app/model/return_unpack_detail.js b/app/model/return_unpack_detail.js new file mode 100644 index 0000000..91709e6 --- /dev/null +++ b/app/model/return_unpack_detail.js @@ -0,0 +1,111 @@ +'use strict'; + +/** + * 退回拆包明细表模型。 + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} Sequelize 模型。 + */ +module.exports = app => { + const { BIGINT, STRING, INTEGER, TEXT, TINYINT } = app.Sequelize; + + const ReturnUnpackDetail = app.model.define('wms_return_unpack_detail', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键', + }, + unpack_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '关联拆包主表 wms_return_unpack.id', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID(冗余,隔离查询)', + }, + barcode: { + type: STRING(100), + allowNull: true, + comment: '扫描条码(前端可选传入,仅作记录;后端不用于识别)', + }, + stock_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '关联 wms_stock_warehouse.id;识别到系统商品时回填,非识别为空', + }, + is_recognized: { + type: TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '是否识别:1=识别到系统商品,0=非识别物品', + }, + item_code: { + type: STRING(50), + allowNull: true, + comment: '商品编码快照(识别时回填)', + }, + item_name: { + type: STRING(255), + allowNull: true, + comment: '物品名称(识别时回填;非识别时可手工补录)', + }, + spec: { + type: STRING(100), + allowNull: true, + comment: '规格快照(sku_property)', + }, + quantity: { + type: INTEGER(11), + allowNull: false, + defaultValue: 1, + comment: '数量', + }, + product_status: { + type: STRING(20), + allowNull: false, + defaultValue: 'normal', + comment: '产品状态:normal-正常,damaged-破损', + }, + product_snapshot: { + type: TEXT, + allowNull: true, + comment: '商品信息快照(JSON),识别时回填,防止商品资料变更后历史丢失', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + }, { + tableName: 'wms_return_unpack_detail', + comment: '退回拆包明细表', + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: false, + indexes: [ + { name: 'idx_unpack_id', fields: [ 'unpack_id' ] }, + { name: 'idx_warehouse_barcode', fields: [ 'warehouse_id', 'barcode' ] }, + { name: 'idx_stock_id', fields: [ 'stock_id' ] }, + { name: 'idx_barcode', fields: [ 'barcode' ] }, + ], + }); + + ReturnUnpackDetail.associate = function() { + const { ReturnUnpack, StockWarehouse } = app.model; + // 关联拆包主表 + ReturnUnpackDetail.belongsTo(ReturnUnpack, { + foreignKey: 'unpack_id', + as: 'unpack', + }); + // 关联系统商品(识别到系统商品时命中) + ReturnUnpackDetail.belongsTo(StockWarehouse, { + foreignKey: 'stock_id', + as: 'stockWarehouse', + }); + }; + + return ReturnUnpackDetail; +}; diff --git a/app/model/return_unpack_video.js b/app/model/return_unpack_video.js new file mode 100644 index 0000000..4eb1219 --- /dev/null +++ b/app/model/return_unpack_video.js @@ -0,0 +1,89 @@ +'use strict'; + +/** + * 退回拆包视频记录表模型(参考 wms_pack_task_video)。 + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} Sequelize 模型。 + */ +module.exports = app => { + const { BIGINT, STRING, DATE } = app.Sequelize; + + const ReturnUnpackVideo = app.model.define('wms_return_unpack_video', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键ID', + }, + unpack_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '关联拆包主表 wms_return_unpack.id', + }, + camera_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '摄像头设备ID,关联 wms_camera.id', + }, + video_url: { + type: STRING(500), + allowNull: false, + comment: '视频地址(录像回放URL)', + }, + status: { + type: STRING(20), + allowNull: false, + defaultValue: 'created', + comment: '状态:created-已创建 recording-录制中 completed-已完成 failed-失败', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + created_at: { + type: DATE, + allowNull: false, + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + comment: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + tableName: 'wms_return_unpack_video', + comment: '退回拆包视频记录表', + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: true, + deletedAt: 'deleted_at', + indexes: [ + { name: 'idx_unpack_id', fields: [ 'unpack_id' ] }, + { name: 'idx_camera_id', fields: [ 'camera_id' ] }, + { name: 'idx_deleted_at', fields: [ 'deleted_at' ] }, + ], + }); + + ReturnUnpackVideo.associate = function() { + const { ReturnUnpack, Camera } = app.model; + // 关联拆包主表 + ReturnUnpackVideo.belongsTo(ReturnUnpack, { + foreignKey: 'unpack_id', + as: 'unpack', + }); + // 关联摄像头 + ReturnUnpackVideo.belongsTo(Camera, { + foreignKey: 'camera_id', + as: 'camera', + }); + }; + + return ReturnUnpackVideo; +}; diff --git a/app/service/systemMethods/returnUnpack.js b/app/service/systemMethods/returnUnpack.js new file mode 100644 index 0000000..39884be --- /dev/null +++ b/app/service/systemMethods/returnUnpack.js @@ -0,0 +1,219 @@ +'use strict'; + +const MainService = require('../main'); + +/** + * 系统方法层:returnUnpack(退回拆包模块接口包装层)。 + * 主要职责:统一包装系统方法接口,处理权限、where 解析等公共逻辑, + * 将具体业务逻辑下沉到 systems.return_unpack 中。 + */ +class ReturnUnpackMethodService extends MainService { + constructor(ctx) { + super(ctx); + // 免登录方法列表:空(全部需要登录) + const _noNeedLogin = ''; + // 免权限方法列表:空(全部走 API 权限校验;detail 走固定 ID 548 客服授权,与设计一致) + const _noNeedRight = ''; + // 免日志方法列表:空(全部记录日志) + const _noNeedLog = ''; + // 免鉴权(仓库有效期检查)方法列表:空(全部检查有效期) + const _noNeedAuth = ''; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 统一调用退回拆包业务服务,并捕获业务错误码。 + * + * @param {Function} fn 业务调用函数。 + * @param {string} fallbackMessage 兜底错误文案。 + * @return {Promise} 统一 success/fail 包装。 + */ + async _call(fn, fallbackMessage) { + try { + const result = await fn(); + return this.success('ok', result); + } catch (error) { + const code = Number(error && error.code); + if (Number.isInteger(code) && code >= 400 && code < 600) { + return this.fail(error.message || fallbackMessage, {}, code); + } + this.ctx.logger.error(`[returnUnpack] ${fallbackMessage}: ${error && error.message ? error.message : error}`); + return this.fail('服务器内部错误', {}, 500); + } + } + + /** + * 开拆包单(增)。 + * + * @param {Object} data 请求体。 + * @param {string} data.waybill_code 拆包的运单号。 + * @param {Array} [data.camera_ids] 摄像头ID列表。 + * @param {number} [data.return_received_id] 关联退回收到单ID。 + * @param {string} [data.remark] 备注。 + * @return {Promise} 统一 success 包装。 + */ + async create(data = {}) { + const { waybill_code, camera_ids, return_received_id, remark } = data; + return this._call( + () => this.service.systems.returnUnpack.create({ waybill_code, camera_ids, return_received_id, remark }), + '开拆包单失败' + ); + } + + /** + * 录明细(增)。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 拆包单ID。 + * @param {number} [data.stock_id] 系统商品ID(wms_stock_warehouse.id)。 + * @param {number} [data.quantity] 数量。 + * @param {string} [data.product_status] 产品状态 normal/damaged。 + * @param {string} [data.remark] 备注。 + * @return {Promise} 统一 success 包装。 + */ + async addDetail(data = {}) { + const { id, stock_id, quantity, product_status, remark } = data; + return this._call( + () => this.service.systems.returnUnpack.addDetail({ id, stock_id, quantity, product_status, remark }), + '录明细失败' + ); + } + + /** + * 更新明细(改,仅数量/备注)。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 拆包单ID。 + * @param {number} data.detail_id 明细ID。 + * @param {number} [data.quantity] 数量。 + * @param {string} [data.remark] 备注。 + * @return {Promise} 统一 success 包装。 + */ + async updateDetail(data = {}) { + const { id, detail_id, quantity, remark } = data; + return this._call( + () => this.service.systems.returnUnpack.updateDetail({ id, detail_id, quantity, remark }), + '更新明细失败' + ); + } + + /** + * 移除明细(删)。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 拆包单ID。 + * @param {number} data.detail_id 明细ID。 + * @return {Promise} 统一 success 包装。 + */ + async removeDetail(data = {}) { + const { id, detail_id } = data; + return this._call( + () => this.service.systems.returnUnpack.removeDetail({ id, detail_id }), + '移除明细失败' + ); + } + + /** + * 取消拆包单(删,仅未完成状态)。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 拆包单ID。 + * @return {Promise} 统一 success 包装。 + */ + async cancel(data = {}) { + const { id } = data; + return this._call(() => this.service.systems.returnUnpack.cancel({ id }), '取消拆包单失败'); + } + + /** + * 提交确认(改,转 completed 终态)。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 拆包单ID。 + * @return {Promise} 统一 success 包装。 + */ + async submit(data = {}) { + const { id } = data; + return this._call(() => this.service.systems.returnUnpack.submit({ id }), '提交确认失败'); + } + + /** + * 分页查询拆包单列表(查,仓库隔离自动注入)。 + * + * @param {Object} data 请求体。 + * @param {Object} [data.pagination] 分页参数。 + * @param {Object} [data.where] 筛选条件。 + * @param {Object} [data.sort] 排序参数。 + * @return {Promise} 统一 success 包装。 + */ + async list(data = {}) { + const { service } = this; + const { pagination, sort } = data; + const { where } = this.prepareWhereContext(data, {}); + + // 仓库隔离:由服务端从当前上下文自动注入,禁止前端传入 + const warehouseId = Number(this.ctx.user && this.ctx.user.store_id || 0); + const enforcedWhere = { ...where }; + if (warehouseId > 0) { + enforcedWhere.warehouse_id = { operator: 'eq', value: warehouseId }; + } + + return this._call( + () => service.systems.returnUnpack.list(enforcedWhere, pagination, sort), + '查询列表失败' + ); + } + + /** + * 分页查询拆包明细列表(查,仓库隔离自动注入)。 + * + * @param {Object} data 请求体。 + * @param {Object} [data.pagination] 分页参数。 + * @param {Object} [data.where] 筛选条件。 + * @param {Object} [data.sort] 排序参数。 + * @return {Promise} 统一 success 包装。 + */ + async detailList(data = {}) { + const { service } = this; + const { pagination, sort } = data; + const { where } = this.prepareWhereContext(data, {}); + + // 仓库隔离:由服务端从当前上下文自动注入,禁止前端传入 + const warehouseId = Number(this.ctx.user && this.ctx.user.store_id || 0); + const enforcedWhere = { ...where }; + if (warehouseId > 0) { + enforcedWhere.warehouse_id = { operator: 'eq', value: warehouseId }; + } + + return this._call( + () => service.systems.returnUnpack.detailList(enforcedWhere, pagination, sort), + '查询明细列表失败' + ); + } + + /** + * 查询拆包单详情(查)。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 拆包单ID。 + * @return {Promise} 统一 success 包装。 + */ + async detail(data = {}) { + const { id } = data; + return this._call(() => this.service.systems.returnUnpack.detail(Number(id)), '查询详情失败'); + } + + /** + * 删除拆包单(删,后台管理,不限制状态)。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 拆包单ID。 + * @return {Promise} 统一 success 包装。 + */ + async delete(data = {}) { + const { id } = data; + return this._call(() => this.service.systems.returnUnpack.delete(Number(id)), '删除失败'); + } +} + +module.exports = ReturnUnpackMethodService; diff --git a/app/service/systems/afterSale.js b/app/service/systems/afterSale.js index 048b311..3732ead 100644 --- a/app/service/systems/afterSale.js +++ b/app/service/systems/afterSale.js @@ -421,202 +421,202 @@ class AfterSaleService extends Service { ctx.logger.info(`[_resolveOrderDetail] 找到订单 id=${orderDeliveryId} code=${order.delivery_order_code} status=${order.status}`); - // 2. 构建收件人信息 - const recipient = { - name: order.name || '', - tel: order.tel || '', - mobile: order.mobile || '', - email: order.email || '', - zip_code: order.zip_code || '', - country: order.country_code || '', - province: order.province || '', - city: order.city || '', - district: order.district || '', - town: order.town || '', - address: order.detail_address || '', - }; + // 2. 构建收件人信息 + const recipient = { + name: order.name || '', + tel: order.tel || '', + mobile: order.mobile || '', + email: order.email || '', + zip_code: order.zip_code || '', + country: order.country_code || '', + province: order.province || '', + city: order.city || '', + district: order.district || '', + town: order.town || '', + address: order.detail_address || '', + }; - // 3. 构建发件人信息(从货主 subject_config 中取) - let sender = null; - if (order.store_id) { - try { - const store = await ctx.model.Store.findOne({ - where: { id: order.store_id }, - attributes: [ 'id', 'subject_config', 'name' ], - raw: true, - }); - if (store) { - let subjectConfig = store.subject_config; - if (typeof subjectConfig === 'string') { - try { subjectConfig = JSON.parse(subjectConfig); } catch { subjectConfig = {}; } - } - sender = { - name: (subjectConfig && subjectConfig.sender_name) || store.name || '', - tel: (subjectConfig && subjectConfig.sender_tel) || '', - province: (subjectConfig && subjectConfig.province_name) || '', - city: (subjectConfig && subjectConfig.city_name) || '', - district: (subjectConfig && subjectConfig.district_name) || '', - town: (subjectConfig && subjectConfig.town_name) || '', - address: (subjectConfig && subjectConfig.address) || '', - }; - } - } catch (err) { - ctx.logger.warn(`[_resolveOrderDetail] 查询发件人信息失败: ${err.message}`); - } - } - - // 4. 订单明细(优先 order.items JSON,为空时回退到分表查询) - let orderItems = []; - if (order.items) { - try { - const parsed = typeof order.items === 'string' ? JSON.parse(order.items) : order.items; - orderItems = Array.isArray(parsed) ? parsed : []; - } catch { - // items 解析失败,忽略 - } - } - - // 回退:若 items 为空且 OrderItemsFactory 可用,从分表查询 - if (orderItems.length === 0 && ctx.model.OrderItemsFactory) { - try { - const itemsModel = await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId); - if (itemsModel) { - const dbItems = await itemsModel.findAll({ - where: { order_id: orderDeliveryId }, + // 3. 构建发件人信息(从货主 subject_config 中取) + let sender = null; + if (order.store_id) { + try { + const store = await ctx.model.Store.findOne({ + where: { id: order.store_id }, + attributes: [ 'id', 'subject_config', 'company_name' ], raw: true, }); - if (dbItems && dbItems.length > 0) { - // 收集 stock_id 用于批量查库存详情 - const stockIds = dbItems - .map(item => Number(item.stock_id)) - .filter(id => Number.isInteger(id) && id > 0); - - // 批量获取库存详情(带缓存的并行查询:条码 + 图片 + 库存属性) - let stockDetailsMap = new Map(); - if (stockIds.length > 0) { - try { - const details = await ctx.service.systems.stockWarehouse.getStockDetails(stockIds, { - warehouseId, - cacheTTL: 300, - }); - for (const detail of details) { - stockDetailsMap.set(detail.id, detail); - } - } catch (err) { - ctx.logger.warn(`[_resolveOrderDetail] 批量获取库存详情失败: ${err.message}`); - } + if (store) { + let subjectConfig = store.subject_config; + if (typeof subjectConfig === 'string') { + try { subjectConfig = JSON.parse(subjectConfig); } catch { subjectConfig = {}; } } - - orderItems = dbItems.map(item => { - const stock = stockDetailsMap.get(Number(item.stock_id)) || {}; - return { - id: item.id, - order_line_no: item.order_line_no || '', - item_code: item.item_code || stock.item_code || '', - item_name: item.item_name || stock.item_name || '', - sku_property: stock.sku_property || '', - quantity: stock.quantity || 0, - locked_quantity: stock.locked_quantity || 0, - is_batch_mgmt: stock.is_batch_mgmt || 'N', - is_shelf_life_mgmt: stock.is_shelf_life_mgmt || 'N', - is_images: stock.is_images || 'N', - store_id: stock.store_id || null, - packing_requirements: stock.packing_requirements || '', - stock_unit: stock.stock_unit || '', - image_url: stock.image_url || [], - barcodes: stock.barcodes || [], - plan_qty: item.plan_qty || 0, - stock_id: item.stock_id || null, - order_item_id: item.id, - order_id: orderDeliveryId, - }; - }); - ctx.logger.info(`[_resolveOrderDetail] 从分表加载 ${orderItems.length} 条明细(含库存详情)`); + sender = { + name: (subjectConfig && subjectConfig.sender_name) || store.company_name || '', + tel: (subjectConfig && subjectConfig.sender_tel) || '', + province: (subjectConfig && subjectConfig.province_name) || '', + city: (subjectConfig && subjectConfig.city_name) || '', + district: (subjectConfig && subjectConfig.district_name) || '', + town: (subjectConfig && subjectConfig.town_name) || '', + address: (subjectConfig && subjectConfig.address) || '', + }; } + } catch (err) { + ctx.logger.warn(`[_resolveOrderDetail] 查询发件人信息失败: ${err.message}`); + } + } + + // 4. 订单明细(优先 order.items JSON,为空时回退到分表查询) + let orderItems = []; + if (order.items) { + try { + const parsed = typeof order.items === 'string' ? JSON.parse(order.items) : order.items; + orderItems = Array.isArray(parsed) ? parsed : []; + } catch { + // items 解析失败,忽略 + } + } + + // 回退:若 items 为空且 OrderItemsFactory 可用,从分表查询 + if (orderItems.length === 0 && ctx.model.OrderItemsFactory) { + try { + const itemsModel = await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId); + if (itemsModel) { + const dbItems = await itemsModel.findAll({ + where: { order_id: orderDeliveryId }, + raw: true, + }); + if (dbItems && dbItems.length > 0) { + // 收集 stock_id 用于批量查库存详情 + const stockIds = dbItems + .map(item => Number(item.stock_id)) + .filter(id => Number.isInteger(id) && id > 0); + + // 批量获取库存详情(带缓存的并行查询:条码 + 图片 + 库存属性) + const stockDetailsMap = new Map(); + if (stockIds.length > 0) { + try { + const details = await ctx.service.systems.stockWarehouse.getStockDetails(stockIds, { + warehouseId, + cacheTTL: 300, + }); + for (const detail of details) { + stockDetailsMap.set(detail.id, detail); + } + } catch (err) { + ctx.logger.warn(`[_resolveOrderDetail] 批量获取库存详情失败: ${err.message}`); + } + } + + orderItems = dbItems.map(item => { + const stock = stockDetailsMap.get(Number(item.stock_id)) || {}; + return { + id: item.id, + order_line_no: item.order_line_no || '', + item_code: item.item_code || stock.item_code || '', + item_name: item.item_name || stock.item_name || '', + sku_property: stock.sku_property || '', + quantity: stock.quantity || 0, + locked_quantity: stock.locked_quantity || 0, + is_batch_mgmt: stock.is_batch_mgmt || 'N', + is_shelf_life_mgmt: stock.is_shelf_life_mgmt || 'N', + is_images: stock.is_images || 'N', + store_id: stock.store_id || null, + packing_requirements: stock.packing_requirements || '', + stock_unit: stock.stock_unit || '', + image_url: stock.image_url || [], + barcodes: stock.barcodes || [], + plan_qty: item.plan_qty || 0, + stock_id: item.stock_id || null, + order_item_id: item.id, + order_id: orderDeliveryId, + }; + }); + ctx.logger.info(`[_resolveOrderDetail] 从分表加载 ${orderItems.length} 条明细(含库存详情)`); + } + } + } catch (err) { + ctx.logger.warn(`[_resolveOrderDetail] 分表查询商品明细失败: ${err.message}`); + } + } + + // 5. 打包视频 + const packVideos = []; + try { + const packTasks = await ctx.model.PackTask.findAll({ + where: { order_id: orderDeliveryId, deleted_at: null }, + include: [ + { + model: ctx.model.PackTaskVideo, + as: 'videos', + where: { deleted_at: null }, + required: false, + }, + ], + order: [[ 'create_time', 'DESC' ]], + raw: false, + }); + + for (const task of packTasks) { + const taskJson = task.toJSON ? task.toJSON() : task; + const videos = (taskJson.videos || []).map(v => ({ + id: v.id, + video_url: v.video_url, + camera_id: v.camera_id, + status: v.status, + created_at: v.created_at ? app.formatDate(v.created_at) : null, + })); + packVideos.push({ + pack_task_id: taskJson.id, + status: taskJson.status, + pack_quantity: taskJson.pack_quantity, + start_time: taskJson.start_time ? app.formatDate(taskJson.start_time) : null, + end_time: taskJson.end_time ? app.formatDate(taskJson.end_time) : null, + operator_text: taskJson.operator_text || '', + videos, + }); } } catch (err) { - ctx.logger.warn(`[_resolveOrderDetail] 分表查询商品明细失败: ${err.message}`); + ctx.logger.warn(`[_resolveOrderDetail] 查询打包视频失败: ${err.message}`); } - } - // 5. 打包视频 - let packVideos = []; - try { - const packTasks = await ctx.model.PackTask.findAll({ - where: { order_id: orderDeliveryId, deleted_at: null }, - include: [ - { - model: ctx.model.PackTaskVideo, - as: 'videos', - where: { deleted_at: null }, - required: false, - }, - ], - order: [[ 'create_time', 'DESC' ]], - raw: false, - }); - - for (const task of packTasks) { - const taskJson = task.toJSON ? task.toJSON() : task; - const videos = (taskJson.videos || []).map(v => ({ - id: v.id, - video_url: v.video_url, - camera_id: v.camera_id, - status: v.status, - created_at: v.created_at ? app.formatDate(v.created_at) : null, - })); - packVideos.push({ - pack_task_id: taskJson.id, - status: taskJson.status, - pack_quantity: taskJson.pack_quantity, - start_time: taskJson.start_time ? app.formatDate(taskJson.start_time) : null, - end_time: taskJson.end_time ? app.formatDate(taskJson.end_time) : null, - operator_text: taskJson.operator_text || '', - videos, - }); - } - } catch (err) { - ctx.logger.warn(`[_resolveOrderDetail] 查询打包视频失败: ${err.message}`); - } - - // 6. 组装返回 - return { - id: order.id, - delivery_order_code: order.delivery_order_code || '', - warehouse_id: order.warehouse_id, - store_id: order.store_id, - // 重量(g) - items_weight: order.items_weight || 0, - // 波次 - wave_id: order.wave_id || 0, - wave_no: order.wave_no || '', - // 来源 - platform_name: order.source_platform_name || '', - source_order_codes: order.source_order_codes || '', - // 创建来源渠道 - create_channel: order.create_channel || '', - create_channel_label: this._getCreateChannelLabel(order.create_channel), - // 状态机 - sync_status: order.sync_status || 'padding', - inspection_status: order.inspection_status || 'none', - storage_status: order.storage_status || 'none', - post_status: order.post_status || 'none', - print_status: order.print_status || 'none', - pick_status: order.pick_status || 'none', - pack_status: order.pack_status || 'none', - intercept_status: order.intercept_status || 'none', - // 数量 - items_count: order.items_count, - items_total: order.items_total, - // 金额 - total_amount: order.total_amount, - item_amount: order.item_amount, - // 收件人 / 发件人 / 明细 / 打包视频 - recipient, - sender, - items: orderItems, - pack_videos: packVideos, - }; + // 6. 组装返回 + return { + id: order.id, + delivery_order_code: order.delivery_order_code || '', + warehouse_id: order.warehouse_id, + store_id: order.store_id, + // 重量(g) + items_weight: order.items_weight || 0, + // 波次 + wave_id: order.wave_id || 0, + wave_no: order.wave_no || '', + // 来源 + platform_name: order.source_platform_name || '', + source_order_codes: order.source_order_codes || '', + // 创建来源渠道 + create_channel: order.create_channel || '', + create_channel_label: this._getCreateChannelLabel(order.create_channel), + // 状态机 + sync_status: order.sync_status || 'padding', + inspection_status: order.inspection_status || 'none', + storage_status: order.storage_status || 'none', + post_status: order.post_status || 'none', + print_status: order.print_status || 'none', + pick_status: order.pick_status || 'none', + pack_status: order.pack_status || 'none', + intercept_status: order.intercept_status || 'none', + // 数量 + items_count: order.items_count, + items_total: order.items_total, + // 金额 + total_amount: order.total_amount, + item_amount: order.item_amount, + // 收件人 / 发件人 / 明细 / 打包视频 + recipient, + sender, + items: orderItems, + pack_videos: packVideos, + }; } catch (err) { ctx.logger.warn(`[_resolveOrderDetail] 整体异常 id=${orderDeliveryId}: ${err.message}`, err.stack); return null; @@ -1063,7 +1063,7 @@ class AfterSaleService extends Service { if (safeStatus === 'pending_feedback') { const hours = await this._resolveFollowupHours(afterSale.warehouse_id, afterSale.type, afterSale.sub_type); ctx.logger.info( - `[handleWorkOrder] id=%s warehouse=%s type=%s subType=%s hours=%d`, + '[handleWorkOrder] id=%s warehouse=%s type=%s subType=%s hours=%d', id, afterSale.warehouse_id, afterSale.type, afterSale.sub_type, hours ); // 使用数据库 NOW() 确保与查询条件时区一致 @@ -1293,7 +1293,7 @@ class AfterSaleService extends Service { }); ctx.logger.info( - `[_resolveFollowupHours] warehouseId=%s type=%s subType=%s hasStoreWarehouse=%s`, + '[_resolveFollowupHours] warehouseId=%s type=%s subType=%s hasStoreWarehouse=%s', warehouseId, type, subType, !!(sw && sw.policy_config) ); @@ -1304,14 +1304,14 @@ class AfterSaleService extends Service { } const whConfig = config && config.after_sale_followup_hours; ctx.logger.info( - `[_resolveFollowupHours] whConfig type=%s value=%s`, + '[_resolveFollowupHours] whConfig type=%s value=%s', typeof whConfig, JSON.stringify(whConfig) ); if (whConfig && typeof whConfig === 'object') { const whTypeMap = whConfig[type]; ctx.logger.info( - `[_resolveFollowupHours] whTypeMap for type=%s: %s`, + '[_resolveFollowupHours] whTypeMap for type=%s: %s', type, JSON.stringify(whTypeMap) ); @@ -1320,13 +1320,13 @@ class AfterSaleService extends Service { if (subType) { const subVal = this._tryParseHours(whTypeMap[subType]); if (typeof subVal === 'number' && subVal >= MIN_VALID_FOLLOWUP_HOURS) { - ctx.logger.info(`[_resolveFollowupHours] MATCH subType (nested): %s=%dh`, subType, subVal); + ctx.logger.info('[_resolveFollowupHours] MATCH subType (nested): %s=%dh', subType, subVal); return subVal; } } const defVal = this._tryParseHours(whTypeMap._default); if (typeof defVal === 'number' && defVal >= MIN_VALID_FOLLOWUP_HOURS) { - ctx.logger.info(`[_resolveFollowupHours] MATCH type._default (nested): %s._default=%dh`, type, defVal); + ctx.logger.info('[_resolveFollowupHours] MATCH type._default (nested): %s._default=%dh', type, defVal); return defVal; } } @@ -1335,7 +1335,7 @@ class AfterSaleService extends Service { // 值为字符串或数字,直接作为该 type 下所有 subType 的统一时长 const flatVal = this._tryParseHours(whTypeMap); if (typeof flatVal === 'number' && flatVal >= MIN_VALID_FOLLOWUP_HOURS) { - ctx.logger.info(`[_resolveFollowupHours] MATCH type flat: %s=%dh`, type, flatVal); + ctx.logger.info('[_resolveFollowupHours] MATCH type flat: %s=%dh', type, flatVal); return flatVal; } } @@ -1343,7 +1343,7 @@ class AfterSaleService extends Service { { const globalVal = this._tryParseHours(whConfig); if (typeof globalVal === 'number' && globalVal >= MIN_VALID_FOLLOWUP_HOURS) { - ctx.logger.info(`[_resolveFollowupHours] MATCH whConfig global: %dh`, globalVal); + ctx.logger.info('[_resolveFollowupHours] MATCH whConfig global: %dh', globalVal); return globalVal; } } @@ -1360,17 +1360,17 @@ class AfterSaleService extends Service { const typeDefault = DEFAULTS[type]; if (typeDefault) { if (subType && typeof typeDefault[subType] === 'number') { - ctx.logger.info(`[_resolveFollowupHours] DEFAULTS subType match: %s=%dh`, subType, typeDefault[subType]); + ctx.logger.info('[_resolveFollowupHours] DEFAULTS subType match: %s=%dh', subType, typeDefault[subType]); return typeDefault[subType]; } if (typeof typeDefault._default === 'number') { - ctx.logger.info(`[_resolveFollowupHours] DEFAULTS type._default: %s=%dh`, type, typeDefault._default); + ctx.logger.info('[_resolveFollowupHours] DEFAULTS type._default: %s=%dh', type, typeDefault._default); return typeDefault._default; } } // 3. 硬兜底 - ctx.logger.warn(`[_resolveFollowupHours] FALLBACK 24h for type=%s subType=%s`, type, subType); + ctx.logger.warn('[_resolveFollowupHours] FALLBACK 24h for type=%s subType=%s', type, subType); return 24; } @@ -1474,7 +1474,7 @@ class AfterSaleService extends Service { ); ctx.logger.info( - `[batchSetPendingFeedback] id=%s type=%s subType=%s hours=%d`, + '[batchSetPendingFeedback] id=%s type=%s subType=%s hours=%d', record.id, record.type, record.sub_type, hours ); diff --git a/app/service/systems/return_received.js b/app/service/systems/return_received.js index bf9c192..d4f591d 100644 --- a/app/service/systems/return_received.js +++ b/app/service/systems/return_received.js @@ -71,7 +71,12 @@ class ReturnReceivedService extends Service { if (existing) { const enriched = await this._enrichReturn(existing); - return { ...enriched, duplicated: true }; + return { + record: enriched, + is_original_return: Boolean(enriched.order_express_id), + store_remark: enriched.store_remark || '', + duplicated: true, + }; } // 反查原运单,判定是否原单退回 @@ -127,7 +132,12 @@ class ReturnReceivedService extends Service { const createdRow = created && typeof created.toJSON === 'function' ? created.toJSON() : created; const enriched = await this._enrichReturn(createdRow); - return { ...enriched, duplicated: false }; + return { + record: enriched, + is_original_return: Boolean(enriched.order_express_id), + store_remark: enriched.store_remark || '', + duplicated: false, + }; } /** diff --git a/app/service/systems/return_unpack.js b/app/service/systems/return_unpack.js new file mode 100644 index 0000000..413046c --- /dev/null +++ b/app/service/systems/return_unpack.js @@ -0,0 +1,1008 @@ +'use strict'; + +const Service = require('egg').Service; + +/** + * 退回拆包模块业务逻辑层。 + * 负责 wms_return_unpack(主表)/ wms_return_unpack_detail(明细)/ wms_return_unpack_video(视频)/ + * wms_return_query_log(退回查询记录)的增删查,以及原单反查、货主校验、单号生成等核心操作。 + * 所有数据库交互集中在此层,供 systemMethods/returnUnpack.js 调用。 + */ +class ReturnUnpackService extends Service { + /** + * 创建带业务错误码的异常对象。 + * + * @param {string} message 错误信息。 + * @param {number} [code=400] 业务错误码。 + * @return {Error} 包含 code 的异常对象。 + */ + createBusinessError(message, code = 400) { + const error = new Error(`${message}`); + error.code = code; + return error; + } + + /** + * 开拆包单(明细不在此提交,由 addDetail 逐件录入)。 + * 用 waybill_code 反查原运单判定是否原单退回;未命中原单时再从退回查询记录表反查货主。 + * + * @param {Object} params 开单参数。 + * @param {string} params.waybill_code 拆包的运单号(必填)。 + * @param {Array} [params.camera_ids] 摄像头ID列表。 + * @param {number} [params.return_received_id] 关联退回收到单ID。 + * @param {string} [params.remark] 备注。 + * @return {Promise} 开单结果,含 id、record、is_original_return、store_remark、order。 + */ + async create({ waybill_code, camera_ids, return_received_id, remark }) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + const waybillCode = String(waybill_code || '').trim(); + if (!waybillCode) { + throw this.createBusinessError('waybill_code 不能为空', 400); + } + + const warehouseId = Number(ctx.user && ctx.user.store_id || 0); + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + throw this.createBusinessError('缺少仓库上下文', 400); + } + + const unpackerId = ctx.user && ctx.user.employees_id ? Number(ctx.user.employees_id) : 0; + const unpackerName = String( + (ctx.user && ctx.user.employees_name) || (ctx.user && ctx.user.real_name) || '' + ).trim(); + + if (!Number.isFinite(unpackerId) || unpackerId <= 0) { + throw this.createBusinessError('缺少拆包人员工号上下文', 400); + } + + // 摄像头ID列表归一化 + let normalizedCameraIds = null; + if (Array.isArray(camera_ids)) { + normalizedCameraIds = camera_ids + .map(item => Number(item)) + .filter(id => Number.isInteger(id) && id > 0); + } + + // 1. 原单反查:命中则回填原单关联字段 + let orderExpressId = null; + let orderId = null; + let storeId = null; + try { + const orderExpress = await ctx.model.OrderExpress.findOne({ + where: { waybill_code: waybillCode }, + attributes: [ 'id', 'order_id', 'store_id' ], + raw: true, + }); + if (orderExpress) { + orderExpressId = orderExpress.id; + orderId = orderExpress.order_id; + storeId = orderExpress.store_id; + } + } catch (err) { + ctx.logger.warn(`[returnUnpack.create] 反查原运单失败: ${err.message}`); + } + + // 2. 未命中原单:从退回查询记录表反查货主(限最近 3 个月内登记,运单号可能被复用) + if (!orderExpressId) { + try { + const threeMonthsAgo = new Date(); + threeMonthsAgo.setMonth(threeMonthsAgo.getMonth() - 3); + const queryLog = await ctx.model.ReturnQueryLog.findOne({ + where: { + warehouse_id: warehouseId, + waybill_code: waybillCode, + created_at: { [Op.gte]: threeMonthsAgo }, + }, + attributes: [ 'store_id' ], + order: [[ 'created_at', 'DESC' ]], + raw: true, + }); + if (queryLog && queryLog.store_id) { + storeId = queryLog.store_id; + } + } catch (err) { + ctx.logger.warn(`[returnUnpack.create] 反查退回查询记录失败: ${err.message}`); + } + } + + const isOriginalReturn = Boolean(orderExpressId); + + // 3. 货主备注(原单退回 / 反查命中货主时) + const storeRemark = await this._resolveStoreRemark(storeId, warehouseId); + + // 4. 拆包日期/开始时间(单号在下方重试循环内生成) + const now = new Date(); + const unpackDate = app.formatDate(now, 'YYYY-MM-DD'); + + // 5. 插入主表(并发下撞 uk_unpack_no 唯一索引时重新取号重试,最多 5 次,指数退避+随机抖动) + const baseFields = { + warehouse_id: warehouseId, + return_received_id: return_received_id ? Number(return_received_id) || null : null, + waybill_code: waybillCode, + unpack_date: unpackDate, + start_time: now, + end_time: null, + unpacker_id: unpackerId, + unpacker_name: unpackerName || '未命名', + status: 'unpacking', + detail_status: 'none_recognized', + total_items: 0, + total_quantity: 0, + order_express_id: orderExpressId, + order_id: orderId, + store_id: storeId, + camera_ids: normalizedCameraIds, + remark: remark ? String(remark).slice(0, 500) : null, + }; + + let created = null; + const maxAttempts = 5; + for (let attempt = 1; attempt <= maxAttempts && !created; attempt += 1) { + const unpackNo = await this._generateUnpackNo(warehouseId); + try { + created = await ctx.model.ReturnUnpack.create({ + ...baseFields, + unpack_no: unpackNo, + }); + } catch (err) { + const isUniqueConflict = err && ( + err.name === 'SequelizeUniqueConstraintError' + || (err.parent && err.parent.code === 'ER_DUP_ENTRY') + ); + if (isUniqueConflict && attempt < maxAttempts) { + // 并发撞号:指数退避 + 随机抖动后重新取号重试,降低同一序号再次碰撞概率 + const backoffMs = Math.min(500, attempt * 40) + Math.floor(Math.random() * 60); + ctx.logger.warn(`[returnUnpack.create] 拆包单号唯一冲突,第 ${attempt} 次重试(退避 ${backoffMs}ms): ${err.message}`); + await new Promise(resolve => setTimeout(resolve, backoffMs)); + continue; + } + throw err; + } + } + + const createdRow = created && typeof created.toJSON === 'function' ? created.toJSON() : created; + + // 6. 原订单详情(仅原单退回时拉取,参考 afterSale.detail._resolveOrderDetail) + let order = null; + if (isOriginalReturn && orderId) { + try { + order = await ctx.service.systems.afterSale._resolveOrderDetail(orderId, warehouseId); + } catch (err) { + ctx.logger.warn(`[returnUnpack.create] 拉取原订单详情失败: ${err.message}`); + } + } + + return { + id: createdRow.id, + record: await this._enrichRow(createdRow), + is_original_return: isOriginalReturn, + store_remark: storeRemark, + order, + }; + } + + /** + * 录明细:以拆包单ID为依据录入一条明细(识别到系统商品时回填快照)。 + * + * @param {Object} params 明细参数。 + * @param {number} params.id 拆包单ID。 + * @param {number} [params.stock_id] 系统商品ID(wms_stock_warehouse.id),为空即无关联货物。 + * @param {number} [params.quantity] 数量,默认 1。 + * @param {string} [params.product_status] 产品状态 normal/damaged,默认 normal。 + * @param {string} [params.remark] 备注。 + * @return {Promise} 明细ID + 明细行 + 主表最新汇总。 + */ + async addDetail({ id, stock_id, quantity, product_status, remark }) { + const { ctx } = this; + + const unpack = await this._findByIdChecked(id); + this._assertUnpacking(unpack); + + const normalizedStockId = stock_id ? Number(stock_id) : null; + const normalizedQuantity = Math.max(1, parseInt(quantity) || 1); + const normalizedStatus = product_status === 'damaged' ? 'damaged' : 'normal'; + + // 识别到系统商品:校验货主归属 + 回填快照 + let isRecognized = 0; + let itemCode = null; + let itemName = null; + let spec = null; + let productSnapshot = null; + + if (normalizedStockId) { + const stock = await ctx.model.StockWarehouse.findOne({ + where: { id: normalizedStockId }, + raw: true, + }); + if (!stock) { + throw this.createBusinessError('系统商品不存在', 404); + } + + // 货主校验:主表已有货主则必须一致;主表货主为空则以首个识别商品回填货主 + const currentStoreId = Number(unpack.store_id || 0); + const stockStoreId = Number(stock.store_id || 0); + if (currentStoreId > 0 && stockStoreId !== currentStoreId) { + throw this.createBusinessError('该商品不属于当前货主,无法录入', 403); + } + + isRecognized = 1; + itemCode = stock.item_code || null; + itemName = stock.item_name || null; + spec = stock.sku_property || null; + productSnapshot = JSON.stringify({ + item_code: stock.item_code || '', + goods_code: stock.goods_code || '', + item_name: stock.item_name || '', + sku_property: stock.sku_property || '', + stock_unit: stock.stock_unit || '', + item_type: stock.item_type || '', + }); + + // 主表货主为空时回填(首个识别商品确定货主) + if (currentStoreId === 0 && stockStoreId > 0) { + await ctx.model.ReturnUnpack.update( + { store_id: stockStoreId }, + { where: { id: unpack.id } } + ); + } + } + + const created = await ctx.model.ReturnUnpackDetail.create({ + unpack_id: unpack.id, + warehouse_id: unpack.warehouse_id, + barcode: null, + stock_id: normalizedStockId, + is_recognized: isRecognized, + item_code: itemCode, + item_name: itemName, + spec, + quantity: normalizedQuantity, + product_status: normalizedStatus, + product_snapshot: productSnapshot, + remark: remark ? String(remark).slice(0, 500) : null, + }); + + const summary = await this._recalcMain(unpack.id, unpack.warehouse_id); + + const createdRow = created && typeof created.toJSON === 'function' ? created.toJSON() : created; + return { + detail_id: createdRow.id, + detail: createdRow, + ...summary, + }; + } + + /** + * 更新明细:仅允许更新数量 / 备注(白名单)。 + * + * @param {Object} params 更新参数。 + * @param {number} params.id 拆包单ID。 + * @param {number} params.detail_id 明细ID。 + * @param {number} [params.quantity] 数量。 + * @param {string} [params.remark] 备注。 + * @return {Promise} 更新后的明细 + 主表最新汇总。 + */ + async updateDetail({ id, detail_id, quantity, remark }) { + const { ctx } = this; + + const unpack = await this._findByIdChecked(id); + this._assertUnpacking(unpack); + + const detail = await this._findDetailChecked(unpack.id, detail_id); + + const updateFields = {}; + let quantityChanged = false; + + if (quantity !== undefined && quantity !== null) { + const normalizedQuantity = Math.max(1, parseInt(quantity) || 1); + if (normalizedQuantity !== Number(detail.quantity)) { + updateFields.quantity = normalizedQuantity; + quantityChanged = true; + } + } + if (remark !== undefined && remark !== null) { + updateFields.remark = String(remark).slice(0, 500); + } + + if (Object.keys(updateFields).length === 0) { + return { + detail, + total_items: unpack.total_items, + total_quantity: unpack.total_quantity, + detail_status: unpack.detail_status, + }; + } + + await ctx.model.ReturnUnpackDetail.update(updateFields, { + where: { id: detail.id }, + }); + + const updated = await ctx.model.ReturnUnpackDetail.findOne({ + where: { id: detail.id }, + raw: true, + }); + + let summary = { + total_items: unpack.total_items, + total_quantity: unpack.total_quantity, + detail_status: unpack.detail_status, + }; + if (quantityChanged) { + summary = await this._recalcMain(unpack.id, unpack.warehouse_id); + } + + return { + detail: updated, + ...summary, + }; + } + + /** + * 移除明细:硬删除拆包单下的一条明细。 + * + * @param {Object} params 移除参数。 + * @param {number} params.id 拆包单ID。 + * @param {number} params.detail_id 明细ID。 + * @return {Promise} 删除结果 + 主表最新汇总。 + */ + async removeDetail({ id, detail_id }) { + const { ctx } = this; + + const unpack = await this._findByIdChecked(id); + this._assertUnpacking(unpack); + + const detail = await this._findDetailChecked(unpack.id, detail_id); + + await ctx.model.ReturnUnpackDetail.destroy({ + where: { id: detail.id }, + }); + + const summary = await this._recalcMain(unpack.id, unpack.warehouse_id); + return { + removed_detail_id: detail.id, + ...summary, + }; + } + + /** + * 取消拆包单:仅在未完成(unpacking)状态可删,事务内硬删除主表 + 所有明细。 + * + * @param {Object} params 取消参数。 + * @param {number} params.id 拆包单ID。 + * @return {Promise} 取消结果。 + */ + async cancel({ id }) { + const { ctx } = this; + + const unpack = await this._findByIdChecked(id); + this._assertUnpacking(unpack); + + await ctx.model.transaction(async transaction => { + await ctx.model.ReturnUnpackDetail.destroy({ + where: { unpack_id: unpack.id }, + transaction, + }); + await ctx.model.ReturnUnpackVideo.destroy({ + where: { unpack_id: unpack.id }, + transaction, + }); + await ctx.model.ReturnUnpack.destroy({ + where: { id: unpack.id }, + transaction, + }); + }); + + return { id: unpack.id }; + } + + /** + * 提交确认:未完成拆包单转 completed 终态,回写结束时间, + * 并同步更新退回查询记录 is_back=1(标记该运单号已退回)。 + * + * @param {Object} params 提交参数。 + * @param {number} params.id 拆包单ID。 + * @return {Promise} 更新后的主表记录。 + */ + async submit({ id }) { + const { ctx } = this; + + const unpack = await this._findByIdChecked(id); + this._assertUnpacking(unpack); + + const now = new Date(); + await ctx.model.ReturnUnpack.update( + { status: 'completed', end_time: now }, + { where: { id: unpack.id } } + ); + + // 同步更新退回查询记录:按 warehouse_id + waybill_code 反查命中则 is_back=1 + try { + await ctx.model.ReturnQueryLog.update( + { is_back: 1 }, + { where: { warehouse_id: unpack.warehouse_id, waybill_code: unpack.waybill_code } } + ); + } catch (err) { + ctx.logger.warn(`[returnUnpack.submit] 更新退回查询记录 is_back 失败: ${err.message}`); + } + + const updated = await ctx.model.ReturnUnpack.findOne({ + where: { id: unpack.id }, + raw: true, + }); + + return { + record: await this._enrichRow(updated), + }; + } + + /** + * 分页查询拆包单列表(仓库隔离由方法层注入 warehouse_id)。 + * + * @param {Object} where 标准化 where 条件对象。 + * @param {Object} [pagination] 分页参数。 + * @param {Object} [sort] 排序参数。 + * @return {Promise} { list, pagination }。 + */ + async list(where = {}, pagination = {}, sort = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + const page = Math.max(1, parseInt(pagination.page) || 1); + const pageSize = Math.min(500, Math.max(1, parseInt(pagination.pageSize) || 20)); + + const queryWhere = this._buildListWhere(where, Op); + const order = this._buildListOrder(sort, 'return_unpack'); + + const { count, rows } = await ctx.model.ReturnUnpack.findAndCountAll({ + where: queryWhere, + order, + offset: (page - 1) * pageSize, + limit: pageSize, + raw: true, + }); + + const list = []; + for (const row of rows) { + list.push(await this._enrichRow(row)); + } + + return { + list, + pagination: { + page, + pageSize, + total: count, + totalPages: Math.ceil(count / pageSize), + hasPrevious: page > 1, + hasNext: page * pageSize < count, + }, + }; + } + + /** + * 分页查询拆包明细列表(仓库隔离由方法层注入 warehouse_id)。 + * + * @param {Object} where 标准化 where 条件对象。 + * @param {Object} [pagination] 分页参数。 + * @param {Object} [sort] 排序参数。 + * @return {Promise} { list, pagination }。 + */ + async detailList(where = {}, pagination = {}, sort = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + const page = Math.max(1, parseInt(pagination.page) || 1); + const pageSize = Math.min(500, Math.max(1, parseInt(pagination.pageSize) || 20)); + + const queryWhere = this._buildDetailListWhere(where, Op); + const order = this._buildListOrder(sort, 'return_unpack_detail'); + + const { count, rows } = await ctx.model.ReturnUnpackDetail.findAndCountAll({ + where: queryWhere, + include: [ + { + model: ctx.model.StockWarehouse, + as: 'stockWarehouse', + required: false, + }, + ], + order, + offset: (page - 1) * pageSize, + limit: pageSize, + raw: false, + }); + + const list = rows.map(row => (row && typeof row.toJSON === 'function' ? row.toJSON() : row)); + + return { + list, + pagination: { + page, + pageSize, + total: count, + totalPages: Math.ceil(count / pageSize), + hasPrevious: page > 1, + hasNext: page * pageSize < count, + }, + }; + } + + /** + * 查询拆包单详情:主表 + 明细 + 视频 + 退回收到单 + 原订单详情(原单退回时)。 + * + * @param {number} id 拆包单ID。 + * @return {Promise} 详情对象。 + */ + async detail(id) { + const { ctx } = this; + + const unpack = await this._findByIdChecked(id); + + const record = await ctx.model.ReturnUnpack.findOne({ + where: { id: unpack.id }, + include: [ + { + model: ctx.model.ReturnUnpackDetail, + as: 'details', + required: false, + include: [ + { + model: ctx.model.StockWarehouse, + as: 'stockWarehouse', + required: false, + }, + ], + }, + { + model: ctx.model.ReturnUnpackVideo, + as: 'videos', + where: { deleted_at: null }, + required: false, + include: [ + { + model: ctx.model.Camera, + as: 'camera', + required: false, + }, + ], + }, + { + model: ctx.model.ReturnReceived, + as: 'returnReceived', + required: false, + }, + ], + raw: false, + }); + + const recordJson = record && typeof record.toJSON === 'function' ? record.toJSON() : record; + + // 原订单详情(仅原单退回时返回) + let relatedOrder = null; + if (recordJson && recordJson.order_id) { + try { + relatedOrder = await ctx.service.systems.afterSale._resolveOrderDetail( + recordJson.order_id, + recordJson.warehouse_id + ); + } catch (err) { + ctx.logger.warn(`[returnUnpack.detail] 拉取原订单详情失败: ${err.message}`); + } + } + + return { + record: await this._enrichRow(recordJson), + related: { + order: relatedOrder, + }, + }; + } + + /** + * 删除拆包单(后台管理,不限制状态):事务内物理删除主表 + 明细,同步软删视频。 + * + * @param {number} id 拆包单ID。 + * @return {Promise} 删除结果。 + */ + async delete(id) { + const { ctx } = this; + + const unpack = await this._findByIdChecked(id); + + await ctx.model.transaction(async transaction => { + await ctx.model.ReturnUnpackDetail.destroy({ + where: { unpack_id: unpack.id }, + transaction, + }); + await ctx.model.ReturnUnpackVideo.destroy({ + where: { unpack_id: unpack.id }, + transaction, + }); + await ctx.model.ReturnUnpack.destroy({ + where: { id: unpack.id }, + transaction, + }); + }); + + return { id: unpack.id }; + } + + // =========================== + // 辅助方法 + // =========================== + + /** + * 按主键查询拆包单,并校验仓库隔离。 + * + * @param {number} id 拆包单ID。 + * @return {Promise} 拆包单原始数据。 + */ + async _findByIdChecked(id) { + const { ctx } = this; + const normalizedId = Number(id || 0); + if (!Number.isFinite(normalizedId) || normalizedId <= 0) { + throw this.createBusinessError('id 必填且必须为正整数', 400); + } + + const record = await ctx.model.ReturnUnpack.findOne({ + where: { id: normalizedId }, + raw: true, + }); + if (!record) { + throw this.createBusinessError('拆包单不存在', 404); + } + + const warehouseId = Number(ctx.user && ctx.user.store_id || 0); + if (warehouseId > 0 && Number(record.warehouse_id) !== warehouseId) { + throw this.createBusinessError('无权访问该拆包单', 403); + } + + return record; + } + + /** + * 校验拆包单处于未完成(unpacking)状态。 + * + * @param {Object} unpack 拆包单记录。 + */ + _assertUnpacking(unpack) { + if (String(unpack.status) !== 'unpacking') { + throw this.createBusinessError('拆包单已提交或已取消,不可操作', 400); + } + } + + /** + * 查询明细并校验属于指定拆包单。 + * + * @param {number} unpackId 拆包单ID。 + * @param {number} detailId 明细ID。 + * @return {Promise} 明细原始数据。 + */ + async _findDetailChecked(unpackId, detailId) { + const { ctx } = this; + const normalizedDetailId = Number(detailId || 0); + if (!Number.isFinite(normalizedDetailId) || normalizedDetailId <= 0) { + throw this.createBusinessError('detail_id 必填且必须为正整数', 400); + } + + const detail = await ctx.model.ReturnUnpackDetail.findOne({ + where: { id: normalizedDetailId, unpack_id: unpackId }, + raw: true, + }); + if (!detail) { + throw this.createBusinessError('明细不存在或不属于该拆包单', 404); + } + + return detail; + } + + /** + * 重算主表汇总字段:total_items / total_quantity / detail_status。 + * + * @param {number} unpackId 拆包单ID。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 最新汇总对象。 + */ + async _recalcMain(unpackId, warehouseId) { + const { ctx } = this; + + const details = await ctx.model.ReturnUnpackDetail.findAll({ + where: { unpack_id: unpackId }, + attributes: [ 'id', 'quantity', 'is_recognized' ], + raw: true, + }); + + const totalItems = details.length; + const totalQuantity = details.reduce((sum, row) => sum + (Number(row.quantity) || 0), 0); + + let detailStatus = 'none_recognized'; + if (totalItems > 0) { + const recognizedCount = details.filter(row => Number(row.is_recognized) === 1).length; + if (recognizedCount === totalItems) { + detailStatus = 'all_recognized'; + } else if (recognizedCount > 0) { + detailStatus = 'partial_recognized'; + } + } + + await ctx.model.ReturnUnpack.update( + { + total_items: totalItems, + total_quantity: totalQuantity, + detail_status: detailStatus, + }, + { where: { id: unpackId, warehouse_id: warehouseId } } + ); + + return { + total_items: totalItems, + total_quantity: totalQuantity, + detail_status: detailStatus, + }; + } + + /** + * 组装主表展示字段(识别状态派生字段 + 时间格式化 + camera_ids 数组化)。 + * + * @param {Object} row 主表原始数据。 + * @return {Promise} 组装后的记录。 + */ + async _enrichRow(row) { + const { app } = this; + const record = { ...row }; + + record.is_original_return = Boolean(record.order_express_id); + + // camera_ids 归一化为数组(MySQL JSON 列可能返回字符串) + if (record.camera_ids !== undefined && record.camera_ids !== null) { + if (typeof record.camera_ids === 'string') { + try { + const parsed = JSON.parse(record.camera_ids); + record.camera_ids = Array.isArray(parsed) ? parsed : []; + } catch (err) { + record.camera_ids = []; + } + } else if (!Array.isArray(record.camera_ids)) { + record.camera_ids = []; + } + } else { + record.camera_ids = []; + } + + // 时间格式化 + record.unpack_date = record.unpack_date ? app.formatDate(record.unpack_date, 'YYYY-MM-DD') : null; + record.start_time = record.start_time ? app.formatDate(record.start_time) : null; + record.end_time = record.end_time ? app.formatDate(record.end_time) : null; + record.created_at = record.created_at ? app.formatDate(record.created_at) : null; + record.updated_at = record.updated_at ? app.formatDate(record.updated_at) : null; + + return record; + } + + /** + * 查询货主合约备注名称(wms_store_warehouse.store_remask)。 + * + * @param {number} storeId 货主ID。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 货主备注名称,未命中时返回空字符串。 + */ + async _resolveStoreRemark(storeId, warehouseId) { + const { ctx } = this; + const normalizedStoreId = Number(storeId || 0); + const normalizedWarehouseId = Number(warehouseId || 0); + if (!normalizedStoreId || !normalizedWarehouseId) { + return ''; + } + try { + const sw = await ctx.model.StoreWarehouse.findOne({ + where: { store_id: normalizedStoreId, warehouse_id: normalizedWarehouseId }, + attributes: [ 'store_remask' ], + raw: true, + }); + return (sw && sw.store_remask) || ''; + } catch (err) { + ctx.logger.warn(`[returnUnpack._resolveStoreRemark] 查询货主备注失败: ${err.message}`); + return ''; + } + } + + /** + * 生成拆包单号(原子取号)。 + * 格式:RP + YYYYMMDD + 6位序号(如 RP20260813000001)。 + * 取号基于序列表 wms_number_sequence 的单条 upsert 原子递增: + * INSERT ... VALUES (LAST_INSERT_ID(:seed + 1)) ON DUPLICATE KEY UPDATE + * current_seq = LAST_INSERT_ID(GREATEST(current_seq, :seed) + 1) + * 其中 :seed 为当日主表已有最大序号,保证历史数据对齐(首日启用不撞已有单号); + * 同事务(同连接)内回读 LAST_INSERT_ID() 取回本次分配序号,并发下无撞号。 + * + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 拆包单号。 + */ + async _generateUnpackNo(warehouseId) { + const { ctx } = this; + const now = new Date(); + const year = now.getFullYear(); + const month = String(now.getMonth() + 1).padStart(2, '0'); + const day = String(now.getDate()).padStart(2, '0'); + const datePart = `${year}${month}${day}`; + const prefix = 'RP'; + const bizType = 'return_unpack'; + + const sequence = await ctx.model.transaction(async transaction => { + // 历史对齐基准:当日主表已有最大序号(无则为 0) + const seedRows = await ctx.model.query( + `SELECT IFNULL(MAX(CAST(RIGHT(unpack_no, 6) AS UNSIGNED)), 0) AS max_seq + FROM wms_return_unpack + WHERE warehouse_id = :warehouseId AND unpack_no LIKE :pattern`, + { + replacements: { warehouseId, pattern: `${prefix}${datePart}%` }, + type: ctx.model.QueryTypes.SELECT, + transaction, + } + ); + const seed = Number(seedRows && seedRows[0] && seedRows[0].max_seq) || 0; + + // 原子取号:单条 upsert 内递增并设置连接级 LAST_INSERT_ID + await ctx.model.query( + `INSERT INTO wms_number_sequence (warehouse_id, biz_type, date_part, current_seq, created_at, updated_at) + VALUES (:warehouseId, :bizType, :datePart, LAST_INSERT_ID(:seed + 1), NOW(), NOW()) + ON DUPLICATE KEY UPDATE current_seq = LAST_INSERT_ID(GREATEST(current_seq, :seed) + 1), updated_at = NOW()`, + { + replacements: { warehouseId, bizType, datePart, seed }, + transaction, + } + ); + + const rows = await ctx.model.query( + 'SELECT LAST_INSERT_ID() AS seq', + { + type: ctx.model.QueryTypes.SELECT, + transaction, + } + ); + return Number(rows && rows[0] && rows[0].seq) || 1; + }); + + if (sequence > 999999) { + throw this.createBusinessError('当日拆包单号已用尽(序号超过 999999),请联系管理员', 500); + } + + return `${prefix}${datePart}${String(sequence).padStart(6, '0')}`; + } + + /** + * 根据标准化 where 条件构建主表 Sequelize 查询条件。 + * + * @param {Object} where 标准化 where 条件对象。 + * @param {Object} Op Sequelize Op 对象。 + * @return {Object} Sequelize where 条件。 + */ + _buildListWhere(where = {}, Op) { + const queryWhere = {}; + + const directFields = [ + 'warehouse_id', 'unpacker_id', 'return_received_id', 'store_id', + 'order_express_id', 'order_id', 'status', 'detail_status', + ]; + + for (const field of directFields) { + if (where[field] !== undefined && where[field] !== null) { + queryWhere[field] = this._resolveConditionValue(where[field], Op); + } + } + + // 日期/时间范围字段 + const rangeFields = [ 'unpack_date', 'start_time', 'end_time', 'created_at', 'updated_at' ]; + for (const field of rangeFields) { + if (where[field] !== undefined && where[field] !== null) { + queryWhere[field] = this._resolveConditionValue(where[field], Op); + } + } + + // 文本字段(支持模糊) + const textFields = [ 'unpack_no', 'waybill_code' ]; + for (const field of textFields) { + if (where[field] !== undefined && where[field] !== null) { + queryWhere[field] = this._resolveConditionValue(where[field], Op); + } + } + + return queryWhere; + } + + /** + * 根据标准化 where 条件构建明细表 Sequelize 查询条件。 + * + * @param {Object} where 标准化 where 条件对象。 + * @param {Object} Op Sequelize Op 对象。 + * @return {Object} Sequelize where 条件。 + */ + _buildDetailListWhere(where = {}, Op) { + const queryWhere = {}; + + const fields = [ + 'warehouse_id', 'unpack_id', 'stock_id', 'barcode', + 'is_recognized', 'product_status', + ]; + + for (const field of fields) { + if (where[field] !== undefined && where[field] !== null) { + queryWhere[field] = this._resolveConditionValue(where[field], Op); + } + } + + return queryWhere; + } + + /** + * 解析标准化条件值为 Sequelize 可用的条件对象。 + * + * @param {*} condition 标准化条件(可能是 {operator, value} 或直接值)。 + * @param {Object} Op Sequelize Op 对象。 + * @return {*} Sequelize 条件。 + */ + _resolveConditionValue(condition, Op) { + if (condition && typeof condition === 'object' && !Array.isArray(condition)) { + const operator = condition.operator; + const value = condition.value; + + if (!operator) { + return value; + } + + switch (operator) { + case 'eq': + return value; + case 'ne': + return { [Op.ne]: value }; + case 'in': + return { [Op.in]: Array.isArray(value) ? value : [ value ] }; + case 'notin': + return { [Op.notIn]: Array.isArray(value) ? value : [ value ] }; + case 'like': + return { [Op.like]: `%${value}%` }; + case 'gt': + return { [Op.gt]: value }; + case 'gte': + return { [Op.gte]: value }; + case 'lt': + return { [Op.lt]: value }; + case 'lte': + return { [Op.lte]: value }; + case 'between': + return { [Op.between]: Array.isArray(value) ? value : [ value ] }; + default: + return value; + } + } + + return condition; + } + + /** + * 根据 sort 参数构建 Sequelize 排序数组。 + * + * @param {Object} sort 排序参数。 + * @param {string} scene 场景标识(return_unpack / return_unpack_detail)。 + * @return {Array>} Sequelize order 数组。 + */ + _buildListOrder(sort = {}, scene = 'return_unpack') { + const sortField = sort.sortField || sort.sort_field || 'created_at'; + const sortOrderRaw = (sort.sortOrder || sort.sort_order || 'desc').toLowerCase(); + const sortOrder = sortOrderRaw === 'asc' ? 'ASC' : 'DESC'; + + const mainFields = new Set([ + 'id', 'created_at', 'updated_at', 'unpack_date', 'start_time', 'end_time', + 'unpack_no', 'waybill_code', + ]); + const detailFields = new Set([ 'id', 'created_at', 'updated_at', 'quantity' ]); + + const allowed = scene === 'return_unpack_detail' ? detailFields : mainFields; + const safeSortField = allowed.has(sortField) ? sortField : 'created_at'; + + return [[ safeSortField, sortOrder ]]; + } +} + +module.exports = ReturnUnpackService; diff --git a/database/migrations/20260813120000-create-wms-return-unpack.js b/database/migrations/20260813120000-create-wms-return-unpack.js new file mode 100644 index 0000000..582d33e --- /dev/null +++ b/database/migrations/20260813120000-create-wms-return-unpack.js @@ -0,0 +1,145 @@ +'use strict'; + +/** + * 创建退回拆包主表 wms_return_unpack。 + * + * 字段:仓库隔离 warehouse_id、拆包单号 unpack_no(RP+YYYYMMDD+6位序号)、 + * 关联退回收到单 return_received_id(非必填)、运单号 waybill_code、拆包日期 unpack_date、 + * 起止时间 start_time/end_time、拆包人 unpacker_id/unpacker_name、状态 status/detail_status、 + * 汇总 total_items/total_quantity、原单关联 order_express_id/order_id/store_id(非必填)、 + * 摄像头列表 camera_ids(JSON)、备注 remark。 + * + * 索引: + * uk_unpack_no(单号唯一) + * idx_warehouse_unpack_date(仓库+日期隔离查询) + * idx_return_received_id / idx_waybill_code / idx_order_express_id + * idx_unpacker_id / idx_start_time / idx_store_id + */ + +const TABLE_NAME = 'wms_return_unpack'; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + const { BIGINT, STRING, INTEGER, DATE } = Sequelize; + await queryInterface.createTable(TABLE_NAME, { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID(数据隔离维度)', + }, + unpack_no: { + type: STRING(50), + allowNull: false, + comment: '拆包单号,RP+YYYYMMDD+6位序号', + }, + return_received_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '关联退回收到表 wms_return_received.id;非必填', + }, + waybill_code: { + type: STRING(50), + allowNull: false, + comment: '拆包的运单号(退回包裹运单号)', + }, + unpack_date: { + type: DATE, + allowNull: false, + comment: '拆包日期', + }, + start_time: { + type: DATE, + allowNull: true, + comment: '拆包开始时间', + }, + end_time: { + type: DATE, + allowNull: true, + comment: '拆包结束时间', + }, + unpacker_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '拆包人员工号ID(employees_id)', + }, + unpacker_name: { + type: STRING(50), + allowNull: false, + comment: '拆包人员工号名称快照(employees_name / real_name)', + }, + status: { + type: STRING(20), + allowNull: false, + defaultValue: 'unpacking', + comment: '拆包状态:unpacking/completed/cancelled', + }, + detail_status: { + type: STRING(30), + allowNull: false, + defaultValue: 'none_recognized', + comment: '明细识别状态:none_recognized/partial_recognized/all_recognized', + }, + total_items: { + type: INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '物品种类数(明细行数)', + }, + total_quantity: { + type: INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '物品总数量(明细数量合计)', + }, + order_express_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '原运单ID,关联 wms_order_express.id;原单退回时回填', + }, + order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '原订单ID,便于快速匹配;原单退回时回填', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '货主ID,原单退回/识别到系统商品时回填', + }, + camera_ids: { + type: Sequelize.JSON, + allowNull: true, + comment: '摄像头ID列表,如 [1,2,3](参考 wms_pack_task.device_ids)', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + created_at: { type: DATE, allowNull: false }, + updated_at: { type: DATE, allowNull: false }, + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'unpack_no' ], { unique: true, name: 'uk_unpack_no' }); + await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'unpack_date' ], { name: 'idx_warehouse_unpack_date' }); + await queryInterface.addIndex(TABLE_NAME, [ 'return_received_id' ], { name: 'idx_return_received_id' }); + await queryInterface.addIndex(TABLE_NAME, [ 'waybill_code' ], { name: 'idx_waybill_code' }); + await queryInterface.addIndex(TABLE_NAME, [ 'order_express_id' ], { name: 'idx_order_express_id' }); + await queryInterface.addIndex(TABLE_NAME, [ 'unpacker_id' ], { name: 'idx_unpacker_id' }); + await queryInterface.addIndex(TABLE_NAME, [ 'start_time' ], { name: 'idx_start_time' }); + await queryInterface.addIndex(TABLE_NAME, [ 'store_id' ], { name: 'idx_store_id' }); + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260813120100-create-wms-return-unpack-detail.js b/database/migrations/20260813120100-create-wms-return-unpack-detail.js new file mode 100644 index 0000000..df251fe --- /dev/null +++ b/database/migrations/20260813120100-create-wms-return-unpack-detail.js @@ -0,0 +1,110 @@ +'use strict'; + +/** + * 创建退回拆包明细表 wms_return_unpack_detail。 + * + * 字段:关联主表 unpack_id、仓库冗余 warehouse_id、扫描条码 barcode(可空,仅记录)、 + * 系统商品 stock_id(可空,关联 wms_stock_warehouse.id)、识别标记 is_recognized、 + * 快照 item_code/item_name/spec/product_snapshot、数量 quantity、产品状态 product_status、备注 remark。 + * + * 索引: + * idx_unpack_id(按拆包单查明细,最高频) + * idx_warehouse_barcode(仓库+条码) + * idx_stock_id(按系统商品反查) + * idx_barcode(按条码查询) + * + * 说明:同一拆包单内可能多次扫描同一条码,明细不设 barcode 唯一约束。 + */ + +const TABLE_NAME = 'wms_return_unpack_detail'; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + const { BIGINT, STRING, INTEGER, DATE, TEXT, TINYINT } = Sequelize; + await queryInterface.createTable(TABLE_NAME, { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + unpack_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '关联拆包主表 wms_return_unpack.id', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID(冗余,隔离查询)', + }, + barcode: { + type: STRING(100), + allowNull: true, + comment: '扫描条码(前端可选传入,仅作记录;后端不用于识别)', + }, + stock_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '关联 wms_stock_warehouse.id;识别到系统商品时回填,非识别为空', + }, + is_recognized: { + type: TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '是否识别:1=识别到系统商品,0=非识别物品', + }, + item_code: { + type: STRING(50), + allowNull: true, + comment: '商品编码快照(识别时回填)', + }, + item_name: { + type: STRING(255), + allowNull: true, + comment: '物品名称(识别时回填;非识别时可手工补录)', + }, + spec: { + type: STRING(100), + allowNull: true, + comment: '规格快照(sku_property)', + }, + quantity: { + type: INTEGER(11), + allowNull: false, + defaultValue: 1, + comment: '数量', + }, + product_status: { + type: STRING(20), + allowNull: false, + defaultValue: 'normal', + comment: '产品状态:normal-正常,damaged-破损', + }, + product_snapshot: { + type: TEXT, + allowNull: true, + comment: '商品信息快照(JSON),识别时回填,防止商品资料变更后历史丢失', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + created_at: { type: DATE, allowNull: false }, + updated_at: { type: DATE, allowNull: false }, + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'unpack_id' ], { name: 'idx_unpack_id' }); + await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'barcode' ], { name: 'idx_warehouse_barcode' }); + await queryInterface.addIndex(TABLE_NAME, [ 'stock_id' ], { name: 'idx_stock_id' }); + await queryInterface.addIndex(TABLE_NAME, [ 'barcode' ], { name: 'idx_barcode' }); + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260813120200-create-wms-return-unpack-video.js b/database/migrations/20260813120200-create-wms-return-unpack-video.js new file mode 100644 index 0000000..268e531 --- /dev/null +++ b/database/migrations/20260813120200-create-wms-return-unpack-video.js @@ -0,0 +1,66 @@ +'use strict'; + +/** + * 创建退回拆包视频记录表 wms_return_unpack_video(参考 wms_pack_task_video)。 + * + * 字段:关联主表 unpack_id、摄像头 camera_id(非必填)、视频地址 video_url、状态 status、 + * 备注 remark、软删除 deleted_at(paranoid)。 + * + * 索引:idx_unpack_id(按拆包单查视频)、idx_camera_id(按摄像头反查)、idx_deleted_at(软删除优化)。 + */ + +const TABLE_NAME = 'wms_return_unpack_video'; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + const { BIGINT, STRING, DATE, ENUM } = Sequelize; + await queryInterface.createTable(TABLE_NAME, { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + unpack_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '关联拆包主表 wms_return_unpack.id', + }, + camera_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '摄像头设备ID,关联 wms_camera.id', + }, + video_url: { + type: STRING(500), + allowNull: false, + comment: '视频地址(录像回放URL)', + }, + status: { + type: ENUM('created', 'recording', 'completed', 'failed'), + allowNull: false, + defaultValue: 'created', + comment: '状态:created/recording/completed/failed', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + created_at: { type: DATE, allowNull: false }, + updated_at: { type: DATE, allowNull: false }, + deleted_at: { type: DATE, allowNull: true, comment: '软删除时间' }, + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'unpack_id' ], { name: 'idx_unpack_id' }); + await queryInterface.addIndex(TABLE_NAME, [ 'camera_id' ], { name: 'idx_camera_id' }); + await queryInterface.addIndex(TABLE_NAME, [ 'deleted_at' ], { name: 'idx_deleted_at' }); + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260813120300-create-wms-return-query-log.js b/database/migrations/20260813120300-create-wms-return-query-log.js new file mode 100644 index 0000000..80e46f3 --- /dev/null +++ b/database/migrations/20260813120300-create-wms-return-query-log.js @@ -0,0 +1,75 @@ +'use strict'; + +/** + * 创建退回查询记录表 wms_return_query_log。 + * + * 用途:登记「货主未退回、但做过查询退回」的运单号,仓库 + 货主隔离。 + * 创建拆包单未命中原单时,据此反查运单号对应的货主并回写 store_id(限最近 3 个月内登记)。 + * is_back / is_notified 供定时任务扫描拆包通知;拆包单提交确认时更新 is_back=1。 + * + * 索引: + * idx_warehouse_store_waybill(仓库+货主+运单号,核心) + * idx_warehouse_store(仓库+货主隔离查询) + * idx_waybill_code(按运单号查询) + */ + +const TABLE_NAME = 'wms_return_query_log'; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + const { BIGINT, STRING, DATE, TINYINT } = Sequelize; + await queryInterface.createTable(TABLE_NAME, { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID(隔离维度)', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '货主ID(隔离维度)', + }, + waybill_code: { + type: STRING(50), + allowNull: false, + comment: '查询过的运单号', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + is_notified: { + type: TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '是否已通知:0=未通知,1=已通知', + }, + is_back: { + type: TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '是否退回:0=未退回,1=已退回', + }, + created_at: { type: DATE, allowNull: false }, + updated_at: { type: DATE, allowNull: false }, + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'store_id', 'waybill_code' ], { name: 'idx_warehouse_store_waybill' }); + await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'store_id' ], { name: 'idx_warehouse_store' }); + await queryInterface.addIndex(TABLE_NAME, [ 'waybill_code' ], { name: 'idx_waybill_code' }); + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260813130000-create-return-unpack-permissions.js b/database/migrations/20260813130000-create-return-unpack-permissions.js new file mode 100644 index 0000000..7890329 --- /dev/null +++ b/database/migrations/20260813130000-create-return-unpack-permissions.js @@ -0,0 +1,119 @@ +'use strict'; + +/** + * 退回拆包模块权限记录 + 角色授权迁移。 + * + * 权限明细(固定 ID 540-549,550 预留): + * 540 — returnUnpack.create API:退回拆包开单 + * 541 — returnUnpack.addDetail API:退回拆包录明细 + * 542 — returnUnpack.updateDetail API:退回拆包更新明细 + * 543 — returnUnpack.removeDetail API:退回拆包移除明细 + * 544 — returnUnpack.cancel API:退回拆包取消 + * 545 — returnUnpack.submit API:退回拆包提交确认 + * 546 — returnUnpack.list API:退回拆包列表查询 + * 547 — returnUnpack.detailList API:退回拆包明细列表 + * 548 — returnUnpack.detail API:退回拆包详情 + * 549 — returnUnpack.delete API:退回拆包删除 + * + * 角色授权(系统预设角色,不含通配符角色): + * 作业类(540-545)→ 仓库组-员工(27) → 仓库组-主管(26)(仓库员工及以上) + * 查询/删除类(546-549)→ 客服组-员工(30) → 客服组-主管(28)(客服员工及以上) + * 经理(8)/仓库管理员(2)/超级管理员(7) 已持有 * 通配符,自动拥有所有权限,无需处理 + * + * 幂等:INSERT IGNORE 创建权限记录;角色权限数组追加后去重排序,已存在跳过。 + */ + +const TABLE = 'wms_permission'; +const ROLE_TABLE = 'wms_role'; +const COLUMNS = 'id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at'; + +/** 权限ID → 授权角色ID列表(不含通配符角色) */ +const PERMISSION_ROLES = { + 540: [ 27, 26 ], + 541: [ 27, 26 ], + 542: [ 27, 26 ], + 543: [ 27, 26 ], + 544: [ 27, 26 ], + 545: [ 27, 26 ], + 546: [ 30, 28 ], + 547: [ 30, 28 ], + 548: [ 30, 28 ], + 549: [ 30, 28 ], +}; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + // ── 1. 创建 API 权限记录(固定 ID)── + const apis = [ + [ 540, 'returnUnpack.create', 'API:退回拆包开单' ], + [ 541, 'returnUnpack.addDetail', 'API:退回拆包录明细' ], + [ 542, 'returnUnpack.updateDetail', 'API:退回拆包更新明细' ], + [ 543, 'returnUnpack.removeDetail', 'API:退回拆包移除明细' ], + [ 544, 'returnUnpack.cancel', 'API:退回拆包取消' ], + [ 545, 'returnUnpack.submit', 'API:退回拆包提交确认' ], + [ 546, 'returnUnpack.list', 'API:退回拆包列表查询' ], + [ 547, 'returnUnpack.detailList', 'API:退回拆包明细列表' ], + [ 548, 'returnUnpack.detail', 'API:退回拆包详情' ], + [ 549, 'returnUnpack.delete', 'API:退回拆包删除' ], + ]; + + for (const [ id, path, metaTitle ] of apis) { + await queryInterface.sequelize.query( + `INSERT IGNORE INTO \`${TABLE}\` (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`, + { replacements: [ id, path, null, path, null, metaTitle, null, 0, 0, null, 'api', 0, 1 ] } + ); + } + + // ── 2. 角色授权注入 ── + for (const permId of Object.keys(PERMISSION_ROLES).map(Number)) { + for (const roleId of PERMISSION_ROLES[permId]) { + const rows = await queryInterface.sequelize.query( + `SELECT id, permissions FROM \`${ROLE_TABLE}\` WHERE id = ?`, + { replacements: [ roleId ], type: queryInterface.sequelize.QueryTypes.SELECT } + ); + const record = Array.isArray(rows) ? rows[0] : null; + if (!record) { + continue; + } + + // 通配符角色跳过 + if (record.permissions === '*') { + continue; + } + + let perms; + try { + perms = JSON.parse(record.permissions || '[]'); + } catch (err) { + continue; + } + if (!Array.isArray(perms)) { + continue; + } + + if (perms.includes(permId)) { + continue; + } + + perms.push(permId); + perms.sort((a, b) => a - b); + + await queryInterface.sequelize.query( + `UPDATE \`${ROLE_TABLE}\` SET permissions = ? WHERE id = ?`, + { replacements: [ JSON.stringify(perms), roleId ] } + ); + } + } + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + const ids = [ 540, 541, 542, 543, 544, 545, 546, 547, 548, 549 ]; + const placeholders = ids.map(() => '?').join(', '); + await queryInterface.sequelize.query( + `DELETE FROM \`${TABLE}\` WHERE id IN (${placeholders})`, + { replacements: ids } + ); + }, +}; diff --git a/database/migrations/20260813140000-add-order-delivery-base-table-missing-columns.js b/database/migrations/20260813140000-add-order-delivery-base-table-missing-columns.js new file mode 100644 index 0000000..33c8646 --- /dev/null +++ b/database/migrations/20260813140000-add-order-delivery-base-table-missing-columns.js @@ -0,0 +1,118 @@ +'use strict'; + +/** + * 补齐 wms_order_delivery 基表相对模型缺失的 25 列。 + * + * 背景:app/model/order_delivery.js 声明 92 个字段,但基表只有 67 列, + * 缺列导致按模型全字段 SELECT(如 afterSale._resolveOrderDetail 先查基表)时 + * 报 Unknown column 'extend_props' 等错误。 + * 分表(wms_order_delivery_100000 等)均已有这些列,本迁移以分表结构为参照补齐基表。 + * + * 修复后 afterSale._resolveOrderDetail 查基表不再抛错(查无数据时回退工厂分表)。 + */ + +const TABLE_NAME = 'wms_order_delivery'; + +/** 缺失列定义(类型/是否可空/默认值/注释),与分表结构一致 */ +const MISSING_COLUMNS = [ + { name: 'extend_props', type: 'JSON', allowNull: true, defaultValue: null, comment: '订单扩展属性' }, + { name: 'create_channel', type: 'STRING(20)', allowNull: false, defaultValue: 'MANUAL', comment: '创建来源渠道' }, + { name: 'sys_platform_code', type: 'STRING(50)', allowNull: true, defaultValue: null, comment: '系统平台编码' }, + { name: 'sys_platform_name', type: 'STRING(200)', allowNull: true, defaultValue: null, comment: '系统平台名称' }, + { name: 'buyer_message', type: 'STRING(500)', allowNull: true, defaultValue: null, comment: '买家留言' }, + { name: 'seller_message', type: 'STRING(500)', allowNull: true, defaultValue: null, comment: '卖家留言' }, + { name: 'remark', type: 'STRING(500)', allowNull: true, defaultValue: null, comment: '备注' }, + { name: 'sys_logistics_code', type: 'STRING(50)', allowNull: true, defaultValue: null, comment: '系统物流公司编码' }, + { name: 'sys_logistics_name', type: 'STRING(200)', allowNull: true, defaultValue: null, comment: '系统物流公司名称' }, + { name: 'basket_number', type: 'STRING(50)', allowNull: true, defaultValue: null, comment: '筐号' }, + { name: 'from_key', type: 'INTEGER(11)', allowNull: true, defaultValue: null, comment: '来源键' }, + { name: 'items', type: 'TEXT', allowNull: true, defaultValue: null, comment: '商品JSON字符串' }, + { name: 'items_count', type: 'SMALLINT(5).UNSIGNED', allowNull: false, defaultValue: 0, comment: '商品种类数' }, + { name: 'items_total', type: 'INTEGER(10).UNSIGNED', allowNull: false, defaultValue: 0, comment: '商品总数' }, + { name: 'items_weight', type: 'INTEGER(11)', allowNull: false, defaultValue: 0, comment: '总重量(g)' }, + { name: 'items_hash', type: 'CHAR(32)', allowNull: false, defaultValue: '', comment: 'MD5哈希值(32位)' }, + { name: 'items_crc', type: 'INTEGER(10).UNSIGNED', allowNull: false, defaultValue: 0, comment: 'CRC32校验码' }, + { name: 'wave_id', type: 'BIGINT(20)', allowNull: false, defaultValue: 0, comment: '波次ID,0表示未分配' }, + { name: 'wave_no', type: 'STRING(50)', allowNull: false, defaultValue: '', comment: '波次号,空字符串表示未分配' }, + { name: 'wave_strategy_version', type: 'INTEGER(10)', allowNull: false, defaultValue: 0, comment: '波次策略版本号' }, + { name: 'wave_scan_result', type: 'INTEGER(10)', allowNull: false, defaultValue: 0, comment: '波次扫描结果,0未扫描' }, + { name: 'sended_status', type: 'ENUM', enumValues: [ 'none', 'padding', 'fin', 'error' ], allowNull: true, defaultValue: 'none', comment: '发货状态机' }, + { name: 'recheck_status', type: 'STRING(20)', allowNull: true, defaultValue: 'none', comment: '复核状态' }, + { name: 'recheck_time', type: 'DATE', allowNull: true, defaultValue: null, comment: '复核时间' }, + { name: 'print_lock_status', type: 'ENUM', enumValues: [ 'none', 'warehouse' ], allowNull: true, defaultValue: 'none', comment: '打印锁定状态机' }, +]; + +/** + * 将列定义转为 Sequelize 字段描述。 + * + * @param {Object} Sequelize Sequelize 构造器。 + * @param {Object} def 列定义(name/type/allowNull/defaultValue/comment)。 + * @return {Object} Sequelize addColumn 字段描述。 + */ +function toColumnDef(Sequelize, def) { + let type; + if (def.type === 'ENUM') { + type = Sequelize.ENUM(...def.enumValues); + } else if (def.type === 'JSON') { + type = Sequelize.JSON; + } else if (def.type === 'DATE') { + type = Sequelize.DATE; + } else if (def.type === 'TEXT') { + type = Sequelize.TEXT; + } else if (def.type === 'CHAR(32)') { + type = Sequelize.CHAR(32); + } else { + const match = def.type.match(/^([A-Z]+)(?:\(([^)]+)\))?(?:\.([A-Z]+))?$/); + if (!match) { + throw new Error(`无法解析列类型: ${def.type}`); + } + const base = match[1]; + const args = match[2] ? match[2].split(',').map(s => Number(s.trim())) : []; + const unsigned = Boolean(match[3] && match[3] === 'UNSIGNED'); + switch (base) { + case 'STRING': + type = Sequelize.STRING(args[0]); + break; + case 'INTEGER': + type = Sequelize.INTEGER(args[0]); + break; + case 'BIGINT': + type = Sequelize.BIGINT(args[0]); + break; + case 'SMALLINT': + type = Sequelize.SMALLINT(args[0]); + break; + default: + throw new Error(`无法解析列类型: ${def.type}`); + } + if (unsigned) { + type = type.UNSIGNED; + } + } + + const columnDef = { + type, + allowNull: def.allowNull, + comment: def.comment, + }; + if (def.defaultValue !== null && def.defaultValue !== undefined) { + columnDef.defaultValue = def.defaultValue; + } + return columnDef; +} + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + for (const def of MISSING_COLUMNS) { + await queryInterface.addColumn(TABLE_NAME, def.name, toColumnDef(Sequelize, def)); + } + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + for (const def of MISSING_COLUMNS) { + await queryInterface.removeColumn(TABLE_NAME, def.name); + } + }, +}; diff --git a/database/migrations/20260813150000-create-wms-number-sequence.js b/database/migrations/20260813150000-create-wms-number-sequence.js new file mode 100644 index 0000000..9763d05 --- /dev/null +++ b/database/migrations/20260813150000-create-wms-number-sequence.js @@ -0,0 +1,63 @@ +'use strict'; + +/** + * 创建业务单号序列表 wms_number_sequence。 + * + * 用途:按「仓库 + 业务类型 + 日期」维度原子分配单号序号, + * 取代「查当日最大序号+1」的并发撞号方案。 + * 取号 SQL:INSERT ... ON DUPLICATE KEY UPDATE current_seq = LAST_INSERT_ID(current_seq + 1) + * (同连接内再 SELECT LAST_INSERT_ID() 取回本次分配序号)。 + * + * 索引:uk_warehouse_biz_date(仓库+业务类型+日期 唯一,原子取号的幂等键)。 + */ + +const TABLE_NAME = 'wms_number_sequence'; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + const { BIGINT, STRING, INTEGER, CHAR, DATE } = Sequelize; + await queryInterface.createTable(TABLE_NAME, { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID(序号隔离维度)', + }, + biz_type: { + type: STRING(30), + allowNull: false, + comment: '业务类型,如 return_unpack(退回拆包单号)', + }, + date_part: { + type: CHAR(8), + allowNull: false, + comment: '日期片段 YYYYMMDD', + }, + current_seq: { + type: INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '当前已分配序号(原子递增)', + }, + created_at: { type: DATE, allowNull: false }, + updated_at: { type: DATE, allowNull: false }, + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'biz_type', 'date_part' ], { + unique: true, + name: 'uk_warehouse_biz_date', + }); + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + await queryInterface.dropTable(TABLE_NAME); + }, +}; From 2d1b9e98fad8a2dee1d976e421e8343a3645cc23 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Thu, 13 Aug 2026 21:40:57 +0800 Subject: [PATCH 200/550] =?UTF-8?q?feat:=20=E6=96=B0=E5=A2=9E=E8=BF=90?= =?UTF-8?q?=E5=8D=95=E9=80=80=E5=9B=9E=E7=99=BB=E8=AE=B0=E6=A8=A1=E5=9D=97?= =?UTF-8?q?=EF=BC=88returnWaybill=EF=BC=89=E5=B9=B6=E5=90=8C=E6=AD=A5?= =?UTF-8?q?=E6=8E=A5=E5=8F=A3=E6=96=87=E6=A1=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 复用 wms_return_query_log 表,提供货主+运单号退回登记增删查改(create/update/list/detail/delete) - create 幂等(同仓库+货主+运单号返回已有);货主合约校验;update 冲突 409 - 权限固定 ID 551-555 + 角色授权迁移 - 同步 methods/system.json 退回拆包/运单退回登记模块与 changes 变更记录 --- app/service/systemMethods/returnWaybill.js | 132 ++ app/service/systems/return_waybill.js | 371 +++++ ...60000-create-return-waybill-permissions.js | 104 ++ methods/changes/system.json | 141 ++ methods/system.json | 1368 +++++++++++++++-- 5 files changed, 2024 insertions(+), 92 deletions(-) create mode 100644 app/service/systemMethods/returnWaybill.js create mode 100644 app/service/systems/return_waybill.js create mode 100644 database/migrations/20260813160000-create-return-waybill-permissions.js diff --git a/app/service/systemMethods/returnWaybill.js b/app/service/systemMethods/returnWaybill.js new file mode 100644 index 0000000..74ec66a --- /dev/null +++ b/app/service/systemMethods/returnWaybill.js @@ -0,0 +1,132 @@ +'use strict'; + +const MainService = require('../main'); + +/** + * 系统方法层:returnWaybill(运单退回登记模块接口包装层)。 + * 主要职责:统一包装系统方法接口,处理权限、where 解析等公共逻辑, + * 将具体业务逻辑下沉到 systems.return_waybill 中。 + */ +class ReturnWaybillMethodService extends MainService { + constructor(ctx) { + super(ctx); + // 免登录方法列表:空(全部需要登录) + const _noNeedLogin = ''; + // 免权限方法列表:detail 复用列表权限(仅登录 + 仓库隔离校验),其余走 API 权限校验 + const _noNeedRight = 'detail'; + // 免日志方法列表:空(全部记录日志) + const _noNeedLog = ''; + // 免鉴权(仓库有效期检查)方法列表:空(全部检查有效期) + const _noNeedAuth = ''; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 统一调用运单退回登记业务服务,并捕获业务错误码。 + * + * @param {Function} fn 业务调用函数。 + * @param {string} fallbackMessage 兜底错误文案。 + * @return {Promise} 统一 success/fail 包装。 + */ + async _call(fn, fallbackMessage) { + try { + const result = await fn(); + return this.success('ok', result); + } catch (error) { + const code = Number(error && error.code); + if (Number.isInteger(code) && code >= 400 && code < 600) { + return this.fail(error.message || fallbackMessage, {}, code); + } + this.ctx.logger.error(`[returnWaybill] ${fallbackMessage}: ${error && error.message ? error.message : error}`); + return this.fail('服务器内部错误', {}, 500); + } + } + + /** + * 运单退回登记(增)。 + * + * @param {Object} data 请求体。 + * @param {string} data.waybill_code 运单号。 + * @param {number} data.store_id 货主ID。 + * @param {string} [data.remark] 备注。 + * @return {Promise} 统一 success 包装。 + */ + async create(data = {}) { + const { waybill_code, store_id, remark } = data; + return this._call( + () => this.service.systems.returnWaybill.create({ waybill_code, store_id, remark }), + '登记失败' + ); + } + + /** + * 修改登记(改)。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 登记记录ID。 + * @param {string} [data.waybill_code] 运单号。 + * @param {number} [data.store_id] 货主ID。 + * @param {string} [data.remark] 备注。 + * @return {Promise} 统一 success 包装。 + */ + async update(data = {}) { + const { id, waybill_code, store_id, remark } = data; + return this._call( + () => this.service.systems.returnWaybill.update({ id, waybill_code, store_id, remark }), + '修改登记失败' + ); + } + + /** + * 分页查询登记列表(查,仓库隔离自动注入)。 + * + * @param {Object} data 请求体。 + * @param {Object} [data.pagination] 分页参数。 + * @param {Object} [data.where] 筛选条件。 + * @param {Object} [data.sort] 排序参数。 + * @return {Promise} 统一 success 包装。 + */ + async list(data = {}) { + const { service } = this; + const { pagination, sort } = data; + const { where } = this.prepareWhereContext(data, {}); + + // 仓库隔离:由服务端从当前上下文自动注入,禁止前端传入 + const warehouseId = Number(this.ctx.user && this.ctx.user.store_id || 0); + const enforcedWhere = { ...where }; + if (warehouseId > 0) { + enforcedWhere.warehouse_id = { operator: 'eq', value: warehouseId }; + } + + return this._call( + () => service.systems.returnWaybill.list(enforcedWhere, pagination, sort), + '查询列表失败' + ); + } + + /** + * 查询单条登记详情(查)。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 登记记录ID。 + * @return {Promise} 统一 success 包装。 + */ + async detail(data = {}) { + const { id } = data; + return this._call(() => this.service.systems.returnWaybill.detail(Number(id)), '查询详情失败'); + } + + /** + * 删除单条登记(删)。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 登记记录ID。 + * @return {Promise} 统一 success 包装。 + */ + async delete(data = {}) { + const { id } = data; + return this._call(() => this.service.systems.returnWaybill.delete(Number(id)), '删除失败'); + } +} + +module.exports = ReturnWaybillMethodService; diff --git a/app/service/systems/return_waybill.js b/app/service/systems/return_waybill.js new file mode 100644 index 0000000..fafd8c4 --- /dev/null +++ b/app/service/systems/return_waybill.js @@ -0,0 +1,371 @@ +'use strict'; + +const Service = require('egg').Service; + +/** + * 运单退回登记模块业务逻辑层。 + * 复用 wms_return_query_log 表,提供「货主 + 运单号」退回登记的增删查改。 + * 所有数据库交互集中在此层,供 systemMethods/returnWaybill.js 调用。 + */ +class ReturnWaybillService extends Service { + /** + * 创建带业务错误码的异常对象。 + * + * @param {string} message 错误信息。 + * @param {number} [code=400] 业务错误码。 + * @return {Error} 包含 code 的异常对象。 + */ + createBusinessError(message, code = 400) { + const error = new Error(`${message}`); + error.code = code; + return error; + } + + /** + * 运单退回登记(增)。入参:运单号 + 货主ID。 + * 同 warehouse_id + store_id + waybill_code 已存在时返回已有记录(幂等)。 + * + * @param {Object} params 登记参数。 + * @param {string} params.waybill_code 运单号(必填)。 + * @param {number} params.store_id 货主ID(必填)。 + * @param {string} [params.remark] 备注。 + * @return {Promise} { record, duplicated }。 + */ + async create({ waybill_code, store_id, remark }) { + const { ctx } = this; + + const waybillCode = String(waybill_code || '').trim(); + if (!waybillCode) { + throw this.createBusinessError('waybill_code 不能为空', 400); + } + + const storeId = Number(store_id || 0); + if (!Number.isFinite(storeId) || storeId <= 0) { + throw this.createBusinessError('store_id 必填且必须为正整数', 400); + } + + const warehouseId = Number(ctx.user && ctx.user.store_id || 0); + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + throw this.createBusinessError('缺少仓库上下文', 400); + } + + // 货主合约校验:wms_store_warehouse 存在 store_id + warehouse_id 合约 + await this._assertStoreContract(storeId, warehouseId); + + // 幂等:同仓库+货主+运单号已存在 → 返回已有记录 + const existing = await ctx.model.ReturnQueryLog.findOne({ + where: { + warehouse_id: warehouseId, + store_id: storeId, + waybill_code: waybillCode, + }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + if (existing) { + return { record: this._formatRow(existing), duplicated: true }; + } + + const created = await ctx.model.ReturnQueryLog.create({ + warehouse_id: warehouseId, + store_id: storeId, + waybill_code: waybillCode, + remark: remark ? String(remark).slice(0, 500) : null, + is_notified: 0, + is_back: 0, + }); + + const createdRow = created && typeof created.toJSON === 'function' ? created.toJSON() : created; + return { record: this._formatRow(createdRow), duplicated: false }; + } + + /** + * 修改登记(改)。入参:id + 可改运单号/货主ID/备注。 + * + * @param {Object} params 修改参数。 + * @param {number} params.id 登记记录ID(必填)。 + * @param {string} [params.waybill_code] 运单号。 + * @param {number} [params.store_id] 货主ID。 + * @param {string} [params.remark] 备注。 + * @return {Promise} { record }。 + */ + async update({ id, waybill_code, store_id, remark }) { + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + + const record = await this._findByIdChecked(id); + + const updateFields = {}; + const nextWaybillCode = waybill_code !== undefined && waybill_code !== null + ? String(waybill_code).trim() + : record.waybill_code; + if (!nextWaybillCode) { + throw this.createBusinessError('waybill_code 不能为空', 400); + } + + const nextStoreId = store_id !== undefined && store_id !== null + ? Number(store_id) + : Number(record.store_id); + if (!Number.isFinite(nextStoreId) || nextStoreId <= 0) { + throw this.createBusinessError('store_id 必填且必须为正整数', 400); + } + + if (waybill_code !== undefined && waybill_code !== null) { + updateFields.waybill_code = nextWaybillCode; + } + if (store_id !== undefined && store_id !== null && Number(store_id) !== Number(record.store_id)) { + // 货主变更时校验新货主合约 + await this._assertStoreContract(nextStoreId, record.warehouse_id); + updateFields.store_id = nextStoreId; + } + if (remark !== undefined && remark !== null) { + updateFields.remark = String(remark).slice(0, 500); + } + + // 冲突防护:改后与另一条同仓库+货主+运单号冲突则拒绝 + const changed = Object.keys(updateFields).length > 0; + if (changed) { + const conflict = await ctx.model.ReturnQueryLog.findOne({ + where: { + warehouse_id: record.warehouse_id, + store_id: nextStoreId, + waybill_code: nextWaybillCode, + id: { [Op.ne]: record.id }, + }, + attributes: [ 'id' ], + raw: true, + }); + if (conflict) { + throw this.createBusinessError('已存在相同货主 + 运单号的登记记录', 409); + } + + await ctx.model.ReturnQueryLog.update(updateFields, { + where: { id: record.id }, + }); + } + + const updated = await ctx.model.ReturnQueryLog.findOne({ + where: { id: record.id }, + raw: true, + }); + + return { record: this._formatRow(updated) }; + } + + /** + * 分页查询登记列表(仓库隔离由方法层注入 warehouse_id)。 + * + * @param {Object} where 标准化 where 条件对象。 + * @param {Object} [pagination] 分页参数。 + * @param {Object} [sort] 排序参数。 + * @return {Promise} { list, pagination }。 + */ + async list(where = {}, pagination = {}, sort = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + const page = Math.max(1, parseInt(pagination.page) || 1); + const pageSize = Math.min(500, Math.max(1, parseInt(pagination.pageSize) || 20)); + + const queryWhere = this._buildListWhere(where, Op); + const order = this._buildListOrder(sort); + + const { count, rows } = await ctx.model.ReturnQueryLog.findAndCountAll({ + where: queryWhere, + order, + offset: (page - 1) * pageSize, + limit: pageSize, + raw: true, + }); + + return { + list: rows.map(row => this._formatRow(row)), + pagination: { + page, + pageSize, + total: count, + totalPages: Math.ceil(count / pageSize), + hasPrevious: page > 1, + hasNext: page * pageSize < count, + }, + }; + } + + /** + * 查询单条登记详情。 + * + * @param {number} id 登记记录ID。 + * @return {Promise} { record }。 + */ + async detail(id) { + const record = await this._findByIdChecked(id); + return { record: this._formatRow(record) }; + } + + /** + * 删除单条登记(物理删除)。 + * + * @param {number} id 登记记录ID。 + * @return {Promise} 删除结果,含被删除记录 id。 + */ + async delete(id) { + const { ctx } = this; + const record = await this._findByIdChecked(id); + await ctx.model.ReturnQueryLog.destroy({ where: { id: record.id } }); + return { id: record.id }; + } + + // =========================== + // 辅助方法 + // =========================== + + /** + * 按主键查询登记记录,并校验仓库隔离。 + * + * @param {number} id 登记记录ID。 + * @return {Promise} 登记记录原始数据。 + */ + async _findByIdChecked(id) { + const { ctx } = this; + const normalizedId = Number(id || 0); + if (!Number.isFinite(normalizedId) || normalizedId <= 0) { + throw this.createBusinessError('id 必填且必须为正整数', 400); + } + + const record = await ctx.model.ReturnQueryLog.findOne({ + where: { id: normalizedId }, + raw: true, + }); + if (!record) { + throw this.createBusinessError('登记记录不存在', 404); + } + + const warehouseId = Number(ctx.user && ctx.user.store_id || 0); + if (warehouseId > 0 && Number(record.warehouse_id) !== warehouseId) { + throw this.createBusinessError('无权访问该登记记录', 403); + } + + return record; + } + + /** + * 货主合约校验:wms_store_warehouse 必须存在 store_id + warehouse_id 合约。 + * + * @param {number} storeId 货主ID。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 校验失败抛业务异常。 + */ + async _assertStoreContract(storeId, warehouseId) { + const { ctx } = this; + const contract = await ctx.model.StoreWarehouse.findOne({ + where: { store_id: storeId, warehouse_id: warehouseId }, + attributes: [ 'id' ], + raw: true, + }); + if (!contract) { + throw this.createBusinessError('货主在当前仓库无合约关系,无法登记', 400); + } + } + + /** + * 格式化登记记录(时间字段本地化)。 + * + * @param {Object} row 登记记录原始数据。 + * @return {Object} 格式化后的记录。 + */ + _formatRow(row) { + const { app } = this; + const record = { ...row }; + record.created_at = record.created_at ? app.formatDate(record.created_at) : null; + record.updated_at = record.updated_at ? app.formatDate(record.updated_at) : null; + return record; + } + + /** + * 根据标准化 where 条件构建 Sequelize 查询条件。 + * + * @param {Object} where 标准化 where 条件对象。 + * @param {Object} Op Sequelize Op 对象。 + * @return {Object} Sequelize where 条件。 + */ + _buildListWhere(where = {}, Op) { + const queryWhere = {}; + + const fields = [ + 'warehouse_id', 'store_id', 'waybill_code', + 'is_notified', 'is_back', 'created_at', 'updated_at', + ]; + + for (const field of fields) { + if (where[field] !== undefined && where[field] !== null) { + queryWhere[field] = this._resolveConditionValue(where[field], Op); + } + } + + return queryWhere; + } + + /** + * 解析标准化条件值为 Sequelize 可用的条件对象。 + * + * @param {*} condition 标准化条件(可能是 {operator, value} 或直接值)。 + * @param {Object} Op Sequelize Op 对象。 + * @return {*} Sequelize 条件。 + */ + _resolveConditionValue(condition, Op) { + if (condition && typeof condition === 'object' && !Array.isArray(condition)) { + const operator = condition.operator; + const value = condition.value; + + if (!operator) { + return value; + } + + switch (operator) { + case 'eq': + return value; + case 'ne': + return { [Op.ne]: value }; + case 'in': + return { [Op.in]: Array.isArray(value) ? value : [ value ] }; + case 'notin': + return { [Op.notIn]: Array.isArray(value) ? value : [ value ] }; + case 'like': + return { [Op.like]: `%${value}%` }; + case 'gt': + return { [Op.gt]: value }; + case 'gte': + return { [Op.gte]: value }; + case 'lt': + return { [Op.lt]: value }; + case 'lte': + return { [Op.lte]: value }; + case 'between': + return { [Op.between]: Array.isArray(value) ? value : [ value ] }; + default: + return value; + } + } + + return condition; + } + + /** + * 根据 sort 参数构建 Sequelize 排序数组。 + * + * @param {Object} sort 排序参数。 + * @return {Array>} Sequelize order 数组。 + */ + _buildListOrder(sort = {}) { + const sortField = sort.sortField || sort.sort_field || 'created_at'; + const sortOrderRaw = (sort.sortOrder || sort.sort_order || 'desc').toLowerCase(); + const sortOrder = sortOrderRaw === 'asc' ? 'ASC' : 'DESC'; + + const allowedSortFields = new Set([ 'id', 'created_at', 'updated_at', 'waybill_code' ]); + const safeSortField = allowedSortFields.has(sortField) ? sortField : 'created_at'; + + return [[ safeSortField, sortOrder ]]; + } +} + +module.exports = ReturnWaybillService; diff --git a/database/migrations/20260813160000-create-return-waybill-permissions.js b/database/migrations/20260813160000-create-return-waybill-permissions.js new file mode 100644 index 0000000..8710091 --- /dev/null +++ b/database/migrations/20260813160000-create-return-waybill-permissions.js @@ -0,0 +1,104 @@ +'use strict'; + +/** + * 运单退回登记模块权限记录 + 角色授权迁移。 + * + * 权限明细(固定 ID 551-555,550 预留): + * 551 — returnWaybill.create API:运单退回登记 + * 552 — returnWaybill.update API:运单退回登记修改 + * 553 — returnWaybill.list API:运单退回登记列表 + * 554 — returnWaybill.detail API:运单退回登记详情 + * 555 — returnWaybill.delete API:运单退回登记删除 + * + * 角色授权(系统预设角色,不含通配符角色): + * 作业类(551-552)→ 仓库组-员工(27) → 仓库组-主管(26)(仓库员工及以上) + * 查询/删除类(553-555)→ 客服组-员工(30) → 客服组-主管(28)(客服员工及以上) + * 经理(8)/仓库管理员(2)/超级管理员(7) 已持有 * 通配符,自动拥有所有权限,无需处理 + * + * 幂等:INSERT IGNORE 创建权限记录;角色权限数组追加后去重排序,已存在跳过。 + */ + +const TABLE = 'wms_permission'; +const ROLE_TABLE = 'wms_role'; +const COLUMNS = 'id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at'; + +/** 权限ID → 授权角色ID列表(不含通配符角色) */ +const PERMISSION_ROLES = { + 551: [ 27, 26 ], + 552: [ 27, 26 ], + 553: [ 30, 28 ], + 554: [ 30, 28 ], + 555: [ 30, 28 ], +}; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + // ── 1. 创建 API 权限记录(固定 ID)── + const apis = [ + [ 551, 'returnWaybill.create', 'API:运单退回登记' ], + [ 552, 'returnWaybill.update', 'API:运单退回登记修改' ], + [ 553, 'returnWaybill.list', 'API:运单退回登记列表' ], + [ 554, 'returnWaybill.detail', 'API:运单退回登记详情' ], + [ 555, 'returnWaybill.delete', 'API:运单退回登记删除' ], + ]; + + for (const [ id, path, metaTitle ] of apis) { + await queryInterface.sequelize.query( + `INSERT IGNORE INTO \`${TABLE}\` (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`, + { replacements: [ id, path, null, path, null, metaTitle, null, 0, 0, null, 'api', 0, 1 ] } + ); + } + + // ── 2. 角色授权注入 ── + for (const permId of Object.keys(PERMISSION_ROLES).map(Number)) { + for (const roleId of PERMISSION_ROLES[permId]) { + const rows = await queryInterface.sequelize.query( + `SELECT id, permissions FROM \`${ROLE_TABLE}\` WHERE id = ?`, + { replacements: [ roleId ], type: queryInterface.sequelize.QueryTypes.SELECT } + ); + const record = Array.isArray(rows) ? rows[0] : null; + if (!record) { + continue; + } + + // 通配符角色跳过 + if (record.permissions === '*') { + continue; + } + + let perms; + try { + perms = JSON.parse(record.permissions || '[]'); + } catch (err) { + continue; + } + if (!Array.isArray(perms)) { + continue; + } + + if (perms.includes(permId)) { + continue; + } + + perms.push(permId); + perms.sort((a, b) => a - b); + + await queryInterface.sequelize.query( + `UPDATE \`${ROLE_TABLE}\` SET permissions = ? WHERE id = ?`, + { replacements: [ JSON.stringify(perms), roleId ] } + ); + } + } + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + const ids = [ 551, 552, 553, 554, 555 ]; + const placeholders = ids.map(() => '?').join(', '); + await queryInterface.sequelize.query( + `DELETE FROM \`${TABLE}\` WHERE id IN (${placeholders})`, + { replacements: ids } + ); + }, +}; diff --git a/methods/changes/system.json b/methods/changes/system.json index 239f8da..9ef0b36 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,21 @@ [ + { + "version": "2026.08.13-stockQueryWhere", + "date": "2026-08-13", + "type": "added", + "summary": "storage.receiving.getReceivingList / getStoreReceivingList 新增 stock_query_where 参数:按商品条码/商品编码/商品ID 搜索,经收货明细关联过滤收货单列表(仓库侧与货主侧同步支持)", + "methods": [ + "storage.receiving.getReceivingList", + "storage.receiving.getStoreReceivingList" + ], + "notes": [ + "新增 stock_query_where 入参(string|string[], optional, body,前端通常传数组),搜索范围:wms_stock_barcodes.barcode + wms_stock_warehouse.item_code + wms_stock_warehouse.id(纯数字时精确匹配)", + "解析链路:stock_query_where → wms_stock_warehouse.id 集合 → wms_receiving_detail.system_product_id IN 集合 → receiving_id 列表", + "与 filterDepleted、entry_order_id 可组合使用(多组过滤取交集,仓库侧),无匹配结果时返回空列表", + "代码变更:systems/storage/receiving.js 新增 _resolveStockQueryReceivingIds 并对两个列表方法注入过滤;systemMethods/storage/receiving.js 两个列表方法均透传 stock_query_where;methods/system.json 两个接口均新增参数文档" + ], + "module": "storage" + }, { "version": "2026.08.12-confirmIntercept-doc", "date": "2026-08-12", @@ -5775,5 +5792,129 @@ "代码变更:app/model/return_received.js、app/service/systems/return_received.js、app/service/systemMethods/returnReceived.js、database/migrations/20260812160000-create-wms-return-received.js、20260813100000-create-return-received-permissions.js" ], "module": "returnReceived" + }, + { + "version": "2026.08.13-shops-GetAuthorizeSessionKey-doc-sync", + "date": "2026-08-13", + "type": "updated", + "summary": "同步 shops.GetAuthorizeSessionKey 文档:实现已切换为调用授权服务 saveShop 换取授权会话,旧的 PDD/CAINIAO 预占码方案已下线。", + "methods": [ + "shops.GetAuthorizeSessionKey" + ], + "notes": [ + "实现:按店铺 platform_code 取 wms_print_platform.get_auth_platform_name 作为 platName,POST 授权服务 saveShop,携带 RedirectCodeUrl/shopName;京东平台附 VenderID,视频号平台改传 appId/toUserName 且不带 RedirectCodeUrl", + "成功后更新店铺 access_token=sessionKey、status=1,返回 data.message='获取授权成功';上游 code≠0 或未返回 sessionKey 时抛 500", + "文档更新:移除旧 data.session_key/authorize_url/state 返回结构与 501 未实现错误,补充 appId/toUserName 入参及 shop_id/callbackurl/platform_code 校验错误码", + "仅文档同步,不修改业务代码" + ], + "module": "shops" + }, + { + "version": "2026.08.13-interceptScan-non-intercept-guard", + "date": "2026-08-13", + "type": "updated", + "summary": "order.recheckOrder.interceptScan 增加非拦截订单前置校验:运单不存在或未发起系统拦截时直接拒绝并提示「非拦截订单」,移除原先自动创建运单补充记录的逻辑。", + "methods": [ + "order.recheckOrder.interceptScan" + ], + "notes": [ + "校验规则:运单记录不存在即拒绝;运单 is_intercept≠'Y' 时回查关联订单,intercept_status 不在 requested/intercepting 也拒绝,提示「非拦截订单」", + "校验通过后原逻辑不变:标记 is_back='Y'/is_intercept='Y'、处理未完结售后工单、订单级更新 intercepted_at_warehouse 并释放储位分配与订单锁", + "移除运单不存在时自动创建补充记录的分支(未发起拦截的运单不再被静默置为拦截)", + "同步更新 JSDoc 与 methods/system.json 文档,错误码新增 400 非拦截订单" + ], + "module": "order.recheckOrder" + }, + { + "version": "2026.08.13-returnUnpack", + "date": "2026-08-13", + "type": "added", + "summary": "新增退回拆包模块(returnUnpack):开拆包单、录明细、更新明细、移除明细、取消、提交确认、分页列表、明细列表、详情、删除十个接口。开单反查原运单判定原单退回并回填货主,未命中原单时按 warehouse_id+waybill_code 从退回查询记录反查货主;拆包单号 RP+YYYYMMDD+6位序号;状态机 unpacking/completed/cancelled;明细识别状态 none_recognized/partial_recognized/all_recognized;全接口仓库隔离(服务端注入 warehouse_id)。配套权限 540-549(作业类→仓库员工及以上,查询/删除类→客服员工及以上,detail 免权限复用列表权限)", + "methods": [ + "returnUnpack.create", + "returnUnpack.addDetail", + "returnUnpack.updateDetail", + "returnUnpack.removeDetail", + "returnUnpack.cancel", + "returnUnpack.submit", + "returnUnpack.list", + "returnUnpack.detailList", + "returnUnpack.detail", + "returnUnpack.delete" + ], + "notes": [ + "新增表 wms_return_unpack(主表)/ wms_return_unpack_detail(明细)/ wms_return_unpack_video(视频,paranoid 软删)/ wms_return_query_log(退回查询记录)", + "returnUnpack.create:waybill_code 必填;反查 wms_order_express.waybill_code 命中则回填 order_express_id/order_id/store_id 并返回原订单详情(复用 afterSale._resolveOrderDetail);未命中再从 wms_return_query_log 按 warehouse_id+waybill_code 反查货主(限最近 3 个月内登记);返回 id/record/is_original_return/store_remark/order", + "returnUnpack.addDetail:主单非终态校验;stock_id 有值 → 查 wms_stock_warehouse 校验货主归属(不一致 403)+ 回填 is_recognized=1 与快照;主表 store_id 为空时以首个识别商品回填货主;写明细后重算 total_items/total_quantity/detail_status", + "returnUnpack.updateDetail:白名单仅 quantity/remark;仅 quantity 变更时重算主表汇总", + "returnUnpack.removeDetail:明细表 paranoid:false 硬删除 + 重算主表汇总", + "returnUnpack.cancel:仅 unpacking 状态;事务内硬删主表+明细,软删视频", + "returnUnpack.submit:仅 unpacking;status=completed + 回写 end_time,并同步更新 wms_return_query_log.is_back=1(失败不阻断主流程)", + "returnUnpack.list:主表分页,仓库隔离服务端注入 warehouse_id;where 支持 unpack_no/waybill_code 模糊、unpack_date/start_time/end_time 范围、status/detail_status/unpacker_id/return_received_id/store_id/order_express_id/order_id 等值", + "returnUnpack.detailList:明细分页 + stockWarehouse 关联(命中时);where 支持 unpack_id/stock_id/barcode/is_recognized/product_status", + "returnUnpack.detail:主表 + details(stockWarehouse) + videos(camera) + returnReceived;原单退回时返回 related.order;免权限仅登录 + 仓库隔离", + "returnUnpack.delete:后台删除不限状态;事务物理删主表+明细,软删视频", + "仓库隔离:全部接口禁止前端传入 warehouse_id,由服务端注入 ctx.user.store_id;拆包单号规则 RP+YYYYMMDD+6位序号(仓库维度序号)", + "权限:540 returnUnpack.create、541 addDetail、542 updateDetail、543 removeDetail、544 cancel、545 submit(仓库员工及以上);546 list、547 detailList、548 detail、549 delete(客服员工及以上);detail 免权限(复用列表权限)", + "代码变更:app/model/return_unpack.js、return_unpack_detail.js、return_unpack_video.js、return_query_log.js;app/service/systems/return_unpack.js;app/service/systemMethods/returnUnpack.js;database/migrations/20260813120000-20260813120300 建表、20260813130000 权限" + ], + "module": "returnUnpack" + }, + { + "version": "2026.08.13-returnReceived.createResponse", + "date": "2026-08-13", + "type": "updated", + "summary": "returnReceived.create 出参结构调整:由平铺返回登记字段改为包装结构 { record, is_original_return, store_remark, duplicated },record 含登记记录完整字段与派生字段 is_original_return/store_remark,与代码实现(app/service/systems/return_received.js)及设计文档对齐", + "methods": [ + "returnReceived.create" + ], + "notes": [ + "原出参平铺 id/waybill_code/scan_date/scanner_id/scanner_name/order_express_id/order_id/store_id/remark/is_original_return/store_remark/duplicated,现改为四个顶层字段:record(object,必填)、is_original_return(boolean,必填)、store_remark(string,必填)、duplicated(boolean,必填)", + "record 内字段:id、waybill_code、scan_date、scanner_id、scanner_name、order_express_id、order_id、store_id、remark、created_at、updated_at(时间为格式化字符串)+ 派生字段 is_original_return、store_remark", + "顶层 is_original_return / store_remark / duplicated 为 record 之外独立返回字段,与 record 内同名字段取值一致", + "仅文档变更,代码实现已对齐(create 返回 { record, is_original_return, store_remark, duplicated },30日幂等命中与新建分支结构一致)" + ], + "module": "returnReceived" + }, + { + "version": "2026.08.13-returnWaybill", + "date": "2026-08-13", + "type": "added", + "summary": "新增运单退回登记模块(returnWaybill):复用 wms_return_query_log 表实现「货主 + 运单号」退回关系的增删查改五个接口(create/update/list/detail/delete)。create 校验货主合约并幂等返回已有记录;update 支持改运单号/货主/备注,改后冲突 409 拒绝;list 分页筛选(运单号模糊/货主/是否已通知/是否退回/登记时间范围);detail 免权限仅登录+仓库隔离;delete 物理删除。全接口仓库隔离(warehouse_id 服务端注入)。配套权限 551-555(作业类 create/update→仓库员工及以上,查询/删除类 list/detail/delete→客服员工及以上,detail 免权限复用列表权限)", + "methods": [ + "returnWaybill.create", + "returnWaybill.update", + "returnWaybill.list", + "returnWaybill.detail", + "returnWaybill.delete" + ], + "notes": [ + "复用表 wms_return_query_log(20260813120300 迁移已落地):warehouse_id/store_id/waybill_code/remark/is_notified/is_back/created_at/updated_at;登记接口不维护 is_notified/is_back(由定时任务与拆包联动维护)", + "returnWaybill.create:waybill_code/store_id 必填;货主合约校验(wms_store_warehouse 存在 store_id+warehouse_id,无合约 400 拒绝);同仓库+货主+运单号已存在时幂等返回已有记录 duplicated=true;写入 is_notified=0/is_back=0", + "returnWaybill.update:id 必填;仓库隔离校验;waybill_code/store_id/remark 可选更新;store_id 变更时校验新货主合约;改后与另一条同仓库+货主+运单号冲突则 409 拒绝", + "returnWaybill.list:pagination(pageSize 上限 500 默认 20)+ where(waybill_code 模糊、store_id、is_notified、is_back、created_at 起止)+ sort(id/created_at/updated_at/waybill_code,默认 created_at desc)", + "returnWaybill.detail:免权限(复用列表权限),仅登录 + 仓库隔离校验", + "returnWaybill.delete:物理删除(表 paranoid:false),返回被删除记录 id", + "仓库隔离:所有接口 warehouse_id 由服务端注入 ctx.user.store_id,禁止前端传入", + "权限:551 create、552 update(仓库员工及以上);553 list、554 detail、555 delete(客服员工及以上);detail 免权限复用 list 权限", + "代码变更:app/service/systems/return_waybill.js、app/service/systemMethods/returnWaybill.js、database/migrations/20260813160000-create-return-waybill-permissions.js" + ], + "module": "returnWaybill" + }, + { + "version": "2026.08.13-returnUnpack.detailAuth", + "date": "2026-08-13", + "type": "updated", + "summary": "returnUnpack.detail 鉴权配置变更:不再免权限(原 _noNeedRight='detail'),改为走 API 权限校验(固定权限 ID 548,客服员工及以上),与 app/service/systemMethods/returnUnpack.js 实现对齐。", + "methods": [ + "returnUnpack.detail" + ], + "notes": [ + "isNeedAuth:false → true;description 同步说明「需 548 权限(客服员工及以上)」", + "代码对齐:returnUnpack.js _noNeedRight 改为空字符串,detail 与其他接口一致走 API 权限校验", + "权限 548 为客服员工及以上(与原「查询类→客服员工及以上」设计一致)", + "仅文档同步,其余接口与模块不动" + ], + "module": "returnUnpack" } ] diff --git a/methods/system.json b/methods/system.json index 55b7389..36faa19 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1,7 +1,7 @@ { "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", - "version": "0.3.22", + "version": "0.3.27", "updatedAt": "2026-08-13", "headers": [ { @@ -5990,7 +5990,7 @@ }, { "method": "order.recheckOrder.interceptScan", - "description": "拦截扫描:通过运单号查找运单记录,标记退回与拦截(is_back='Y', is_intercept='Y')。运单记录不存在时自动创建补充。处理关联的未完结售后工单(写入「库内拦截成功」步骤并置为 completed)。同步更新订单拦截状态为 intercepted_at_warehouse 并释放储位分配与订单锁(与 confirmIntercept 一致,订单级拦截覆盖所有面单含子面单)。工单处理失败不阻断主流程。", + "description": "拦截扫描:通过运单号查找运单记录。非拦截订单会被拒绝并提示「非拦截订单」:运单记录不存在,或运单 is_intercept≠'Y' 且关联订单 intercept_status 不在 requested/intercepting。校验通过后标记退回与拦截(is_back='Y', is_intercept='Y'),处理关联的未完结售后工单(写入「库内拦截成功」步骤并置为 completed)。若运单关联到订单,则将订单拦截状态更新为 intercepted_at_warehouse(step=4、outbound_status=fin)并释放储位分配与订单锁(仅订单级状态更新,不标记订单下其他面单)。工单处理失败不阻断主流程。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -6046,6 +6046,10 @@ { "code": 400, "message": "运单号不能为空" + }, + { + "code": 400, + "message": "非拦截订单" } ] }, @@ -19494,7 +19498,7 @@ "list": [ { "method": "storage.receiving.getReceivingList", - "description": "查询收货单列表,支持分页和多条件筛选。支持 filterDepleted 参数过滤掉无可再用量的收货单(所有明细已被其他入库单 committed 绑定占满)。支持 entry_order_id 参数按入库单商品交集过滤。", + "description": "查询收货单列表,支持分页和多条件筛选。支持 filterDepleted 参数过滤掉无可再用量的收货单(所有明细已被其他入库单 committed 绑定占满)。支持 entry_order_id 参数按入库单商品交集过滤。支持 stock_query_where 参数按商品条码/编码/ID 过滤。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -19533,6 +19537,13 @@ "required": false, "source": "body", "description": "按入库单商品交集过滤。传入入库单 ID 后,只返回至少有一条收货明细的 system_product_id 在入库单明细中存在的收货单。与 filterDepleted 可组合使用。不传则不过滤。" + }, + { + "name": "stock_query_where", + "type": "string|string[]", + "required": false, + "source": "body", + "description": "按商品维度过滤。传入字符串或字符串数组后搜索商品条码(wms_stock_barcodes.barcode)、商品编码(wms_stock_warehouse.item_code)与商品ID(wms_stock_warehouse.id,纯数字时精确匹配),再经 wms_receiving_detail.system_product_id 关联,返回明细中含匹配商品的收货单;多个关键字取并集。与 filterDepleted、entry_order_id 可组合使用(组合时取交集)。不传则不过滤。" } ], "response": [ @@ -19596,6 +19607,13 @@ "required": false, "source": "body", "description": "排序参数,支持 sortField/sortOrder" + }, + { + "name": "stock_query_where", + "type": "string|string[]", + "required": false, + "source": "body", + "description": "按商品维度过滤。传入字符串或字符串数组后搜索商品条码(wms_stock_barcodes.barcode)、商品编码(wms_stock_warehouse.item_code)与商品ID(wms_stock_warehouse.id,纯数字时精确匹配),再经 wms_receiving_detail.system_product_id 关联,返回明细中含匹配商品的收货单;多个关键字取并集。不传则不过滤。" } ], "response": [ @@ -27627,7 +27645,7 @@ }, { "method": "shops.GetAuthorizeSessionKey", - "description": "按店铺所属平台生成授权会话。入参兼容 id/shop_id/shopId 与 callbackurl/callback_url,callbackurl 必填。对已实现的平台(PDD/CAINIAO)返回 session_key/authorize_url/state,其他平台返回 501 未实现。", + "description": "按店铺所属平台向授权服务换取授权会话(saveShop)。入参兼容 id/shop_id/shopId 与 callbackurl/callback_url,callbackurl 必填;视频号平台还需 appId 与 toUserName(此时不带 RedirectCodeUrl),京东平台附带 VenderID。成功后更新店铺 access_token 与 status=1,返回 data.message='获取授权成功'。", "isNeedAuth": true, "isNeedLogin": true, "headers": [ @@ -27651,7 +27669,21 @@ "type": "string", "required": true, "source": "body", - "description": "回调地址,兼容 callback_url" + "description": "授权回调地址,兼容 callback_url,最长 500 字符" + }, + { + "name": "appId", + "type": "string", + "required": false, + "source": "body", + "description": "视频号平台必填:授权服务应用 ID" + }, + { + "name": "toUserName", + "type": "string", + "required": false, + "source": "body", + "description": "视频号平台必填:授权服务用户名" } ], "response": [ @@ -27674,47 +27706,29 @@ "description": "提示信息" }, { - "name": "data.shop_id", - "type": "number", - "required": true, - "description": "店铺 ID" - }, - { - "name": "data.platform_code", + "name": "data.message", "type": "string", "required": true, - "description": "平台编码(大写)" - }, - { - "name": "data.callbackurl", - "type": "string", - "required": true, - "description": "回调地址" - }, - { - "name": "data.session_key", - "type": "string", - "required": true, - "description": "授权预占码(session)" - }, - { - "name": "data.authorize_url", - "type": "string", - "required": true, - "description": "平台授权跳转地址(含 state)" - }, - { - "name": "data.state", - "type": "string", - "required": true, - "description": "内部 state 值(platform + '_' + authRandomCode),用于回调解析" + "description": "成功时固定返回「获取授权成功」" } ], "errors": [ + { + "code": 400, + "message": "shop_id 不能为空" + }, + { + "code": 400, + "message": "shop_id 参数不合法" + }, { "code": 400, "message": "callbackurl 不能为空" }, + { + "code": 400, + "message": "callbackurl 长度不能超过 500" + }, { "code": 400, "message": "未识别到当前仓库" @@ -27725,15 +27739,23 @@ }, { "code": 400, - "message": "平台授权基础地址未配置" + "message": "platform_code 不能为空" }, { - "code": 501, - "message": "平台 %s 暂未实现授权会话换取能力" + "code": 400, + "message": "platform_code 未匹配到打印平台编码" + }, + { + "code": 400, + "message": "视频号授权需要提供 appId 和 toUserName" }, { "code": 500, - "message": "生成唯一授权码失败,请稍后重试" + "message": "获取授权失败,未返回 sessionKey" + }, + { + "code": 500, + "message": "获取授权失败:接口请求异常(上游返回非 0 时携带上游 msg)" } ] } @@ -34769,58 +34791,10 @@ ], "response": [ { - "name": "id", - "type": "integer", + "name": "record", + "type": "object", "required": true, - "description": "登记记录主键ID" - }, - { - "name": "waybill_code", - "type": "string", - "required": true, - "description": "退回收件运单号" - }, - { - "name": "scan_date", - "type": "string", - "required": true, - "description": "扫描收到日期" - }, - { - "name": "scanner_id", - "type": "integer", - "required": true, - "description": "扫描人员工号ID" - }, - { - "name": "scanner_name", - "type": "string", - "required": true, - "description": "扫描人员工号名称" - }, - { - "name": "order_express_id", - "type": "integer", - "required": false, - "description": "原运单ID(原单退回时回填,否则为 null)" - }, - { - "name": "order_id", - "type": "integer", - "required": false, - "description": "原订单ID(原单退回时回填,否则为 null)" - }, - { - "name": "store_id", - "type": "integer", - "required": false, - "description": "货主ID(原单退回时回填,否则为 null)" - }, - { - "name": "remark", - "type": "string", - "required": false, - "description": "备注" + "description": "登记记录包装对象,含登记记录完整字段(id、waybill_code、scan_date、scanner_id、scanner_name、order_express_id、order_id、store_id、remark、created_at、updated_at 等,时间字段为格式化字符串)及派生字段 is_original_return、store_remark" }, { "name": "is_original_return", @@ -35050,6 +35024,1216 @@ ] } ] + }, + { + "groupName": "退回拆包模块", + "module": "returnUnpack", + "list": [ + { + "method": "returnUnpack.create", + "description": "开拆包单(明细不在此提交,由 returnUnpack.addDetail 逐件录入)。用 waybill_code 反查 wms_order_express 判定是否原单退回,命中则回填 order_express_id/order_id/store_id 并返回原订单详情;未命中原单时按 warehouse_id+waybill_code 从 wms_return_query_log 反查货主(限最近 3 个月内登记)。拆包单号规则 RP+YYYYMMDD+6位序号。仓库隔离:warehouse_id 由服务端注入 ctx.user.store_id,禁止前端传入。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "waybill_code", + "type": "string", + "required": true, + "source": "body", + "description": "拆包的运单号(退回包裹运单号,必填,用于反查原单/货主信息)" + }, + { + "name": "camera_ids", + "type": "array", + "required": false, + "source": "body", + "description": "摄像头ID列表,如 [1,2,3],关联 wms_camera.id(非正整数会被过滤)" + }, + { + "name": "return_received_id", + "type": "integer", + "required": false, + "source": "body", + "description": "关联退回收到单ID(wms_return_received.id),非必填,允许独立拆包" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注(最长 500 字符,超出截断)" + } + ], + "response": [ + { + "name": "id", + "type": "integer", + "required": true, + "description": "拆包单主键ID(后续明细收录的依据,传给 returnUnpack.addDetail)" + }, + { + "name": "record", + "type": "object", + "required": true, + "description": "拆包单主表记录(含 unpack_no、waybill_code、unpack_date、start_time、unpacker_id/unpacker_name、status、detail_status、camera_ids 数组、回填的 order_express_id/order_id/store_id 及 is_original_return 派生字段)" + }, + { + "name": "is_original_return", + "type": "boolean", + "required": true, + "description": "是否原单退回(反查 wms_order_express.waybill_code 命中为 true)" + }, + { + "name": "store_remark", + "type": "string", + "required": true, + "description": "货主的合约货主备注名称(wms_store_warehouse.store_remask),未命中时为空字符串" + }, + { + "name": "order", + "type": "object", + "required": false, + "description": "原订单详情(含 items 明细,仅原单退回时返回,非原单为 null)" + } + ], + "errors": [ + { + "code": "400", + "message": "waybill_code 不能为空" + }, + { + "code": "400", + "message": "缺少仓库上下文" + }, + { + "code": "400", + "message": "缺少拆包人员工号上下文" + }, + { + "code": "401", + "message": "未提供有效的认证令牌" + }, + { + "code": "403", + "message": "无权访问该接口" + }, + { + "code": "500", + "message": "服务器内部错误" + } + ] + }, + { + "method": "returnUnpack.addDetail", + "description": "录明细:以拆包单ID为依据录入一条明细。主单非终态(unpacking)校验;stock_id 有值时校验货主归属并回填识别快照(is_recognized=1 + item_code/item_name/spec/product_snapshot),为空即无关联货物(is_recognized=0);主表 store_id 为空时以首个识别商品回填主表货主。写明细后重算主表 total_items/total_quantity/detail_status。仓库隔离校验(仅本仓库拆包单)。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "id", + "type": "integer", + "required": true, + "source": "body", + "description": "拆包单ID(returnUnpack.create 返回的依据)" + }, + { + "name": "stock_id", + "type": "integer", + "required": false, + "source": "body", + "description": "系统商品ID(wms_stock_warehouse.id),为空即无关联货物" + }, + { + "name": "quantity", + "type": "integer", + "required": false, + "source": "body", + "description": "数量,默认 1(小于 1 按 1 处理)" + }, + { + "name": "product_status", + "type": "string", + "required": false, + "source": "body", + "description": "产品状态:normal 正常(默认)/ damaged 破损" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注(最长 500 字符,超出截断)" + } + ], + "response": [ + { + "name": "detail_id", + "type": "integer", + "required": true, + "description": "新增明细ID(供 returnUnpack.updateDetail / returnUnpack.removeDetail 使用)" + }, + { + "name": "detail", + "type": "object", + "required": true, + "description": "新增的明细行(含 is_recognized/item_code/item_name/spec/product_snapshot 等识别结果快照)" + }, + { + "name": "total_items", + "type": "integer", + "required": true, + "description": "主表最新物品种类数(明细行数)" + }, + { + "name": "total_quantity", + "type": "integer", + "required": true, + "description": "主表最新物品总数量(明细数量合计)" + }, + { + "name": "detail_status", + "type": "string", + "required": true, + "description": "主表最新明细识别状态:none_recognized 全未识别 / partial_recognized 部分识别 / all_recognized 全部识别" + } + ], + "errors": [ + { + "code": "400", + "message": "id 必填且必须为正整数" + }, + { + "code": "400", + "message": "拆包单已提交或已取消,不可操作" + }, + { + "code": "401", + "message": "未提供有效的认证令牌" + }, + { + "code": "403", + "message": "该商品不属于当前货主,无法录入" + }, + { + "code": "403", + "message": "无权访问该拆包单" + }, + { + "code": "403", + "message": "无权访问该接口" + }, + { + "code": "404", + "message": "拆包单不存在" + }, + { + "code": "404", + "message": "系统商品不存在" + }, + { + "code": "500", + "message": "服务器内部错误" + } + ] + }, + { + "method": "returnUnpack.updateDetail", + "description": "更新明细:仅允许更新 quantity/remark(更新范围白名单,暂限这两个字段)。校验拆包单存在且非终态(unpacking)、明细属于该拆包单;仅 quantity 变更时重算主表 total_quantity(total_items/detail_status 不变)。仓库隔离校验(仅本仓库拆包单)。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "id", + "type": "integer", + "required": true, + "source": "body", + "description": "拆包单ID" + }, + { + "name": "detail_id", + "type": "integer", + "required": true, + "source": "body", + "description": "明细ID(returnUnpack.addDetail 返回)" + }, + { + "name": "quantity", + "type": "integer", + "required": false, + "source": "body", + "description": "数量(小于 1 按 1 处理,变更时才触发主表重算)" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注(最长 500 字符,超出截断)" + } + ], + "response": [ + { + "name": "detail", + "type": "object", + "required": true, + "description": "更新后的明细行" + }, + { + "name": "total_items", + "type": "integer", + "required": true, + "description": "主表最新物品种类数" + }, + { + "name": "total_quantity", + "type": "integer", + "required": true, + "description": "主表最新物品总数量(quantity 变更时重算)" + }, + { + "name": "detail_status", + "type": "string", + "required": true, + "description": "主表最新明细识别状态:none_recognized/partial_recognized/all_recognized" + } + ], + "errors": [ + { + "code": "400", + "message": "id 必填且必须为正整数" + }, + { + "code": "400", + "message": "detail_id 必填且必须为正整数" + }, + { + "code": "400", + "message": "拆包单已提交或已取消,不可操作" + }, + { + "code": "401", + "message": "未提供有效的认证令牌" + }, + { + "code": "403", + "message": "无权访问该拆包单" + }, + { + "code": "403", + "message": "无权访问该接口" + }, + { + "code": "404", + "message": "拆包单不存在" + }, + { + "code": "404", + "message": "明细不存在或不属于该拆包单" + }, + { + "code": "500", + "message": "服务器内部错误" + } + ] + }, + { + "method": "returnUnpack.removeDetail", + "description": "移除明细:删除拆包单下的一条明细(明细表 paranoid:false,硬删除/物理删除),并重算主表 total_items/total_quantity/detail_status。校验拆包单存在且非终态(unpacking)、明细属于该拆包单。仓库隔离校验(仅本仓库拆包单)。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "id", + "type": "integer", + "required": true, + "source": "body", + "description": "拆包单ID" + }, + { + "name": "detail_id", + "type": "integer", + "required": true, + "source": "body", + "description": "明细ID(returnUnpack.addDetail 返回)" + } + ], + "response": [ + { + "name": "removed_detail_id", + "type": "integer", + "required": true, + "description": "被移除明细ID" + }, + { + "name": "total_items", + "type": "integer", + "required": true, + "description": "主表最新物品种类数" + }, + { + "name": "total_quantity", + "type": "integer", + "required": true, + "description": "主表最新物品总数量" + }, + { + "name": "detail_status", + "type": "string", + "required": true, + "description": "主表最新明细识别状态:none_recognized/partial_recognized/all_recognized" + } + ], + "errors": [ + { + "code": "400", + "message": "id 必填且必须为正整数" + }, + { + "code": "400", + "message": "detail_id 必填且必须为正整数" + }, + { + "code": "400", + "message": "拆包单已提交或已取消,不可操作" + }, + { + "code": "401", + "message": "未提供有效的认证令牌" + }, + { + "code": "403", + "message": "无权访问该拆包单" + }, + { + "code": "403", + "message": "无权访问该接口" + }, + { + "code": "404", + "message": "拆包单不存在" + }, + { + "code": "404", + "message": "明细不存在或不属于该拆包单" + }, + { + "code": "500", + "message": "服务器内部错误" + } + ] + }, + { + "method": "returnUnpack.cancel", + "description": "取消拆包单:仅在未完成(unpacking)状态可取消,事务内硬删除主表 + 该单所有明细,并同步软删视频副表记录。与 returnUnpack.delete 区别:cancel 仅供未完成状态作业取消;delete 为后台管理删除,不限制状态。仓库隔离校验(仅本仓库拆包单)。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "id", + "type": "integer", + "required": true, + "source": "body", + "description": "拆包单ID" + } + ], + "response": [ + { + "name": "id", + "type": "integer", + "required": true, + "description": "被取消拆包单ID" + } + ], + "errors": [ + { + "code": "400", + "message": "id 必填且必须为正整数" + }, + { + "code": "400", + "message": "拆包单已提交或已取消,不可操作" + }, + { + "code": "401", + "message": "未提供有效的认证令牌" + }, + { + "code": "403", + "message": "无权访问该拆包单" + }, + { + "code": "403", + "message": "无权访问该接口" + }, + { + "code": "404", + "message": "拆包单不存在" + }, + { + "code": "500", + "message": "服务器内部错误" + } + ] + }, + { + "method": "returnUnpack.submit", + "description": "提交确认:未完成(unpacking)拆包单转 completed 终态并回写 end_time(拆包结束时间);同步按 warehouse_id+waybill_code 更新 wms_return_query_log.is_back=1(标记该运单号已退回,更新失败不阻断主流程)。提交后进入终态,不可再录/移除明细。仓库隔离校验(仅本仓库拆包单)。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "id", + "type": "integer", + "required": true, + "source": "body", + "description": "拆包单ID" + } + ], + "response": [ + { + "name": "record", + "type": "object", + "required": true, + "description": "更新后的主表记录(含 status=completed、end_time 及格式化时间字段)" + } + ], + "errors": [ + { + "code": "400", + "message": "id 必填且必须为正整数" + }, + { + "code": "400", + "message": "拆包单已提交或已取消,不可操作" + }, + { + "code": "401", + "message": "未提供有效的认证令牌" + }, + { + "code": "403", + "message": "无权访问该拆包单" + }, + { + "code": "403", + "message": "无权访问该接口" + }, + { + "code": "404", + "message": "拆包单不存在" + }, + { + "code": "500", + "message": "服务器内部错误" + } + ] + }, + { + "method": "returnUnpack.list", + "description": "拆包单分页列表(主表)。仓库隔离:warehouse_id 由服务端自动注入 ctx.user.store_id,禁止前端传入。支持拆包单号/运单号模糊、日期/时间范围、状态、拆包人员、退回收到单、货主、原运单/原订单等筛选。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页 { page: 1, pageSize: 20 }(pageSize 上限 500,默认 20)" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "筛选条件对象,所有字段均可选" + }, + { + "name": "where.unpack_no", + "type": "string", + "required": false, + "source": "body.where", + "description": "拆包单号(模糊搜索,传 {operator:'like',value} 或直接值)" + }, + { + "name": "where.waybill_code", + "type": "string", + "required": false, + "source": "body.where", + "description": "运单号(模糊搜索,传 {operator:'like',value} 或直接值)" + }, + { + "name": "where.unpack_date", + "type": "object", + "required": false, + "source": "body.where", + "description": "拆包日期范围 { operator:'between'|'gte'|'lte'|'gt'|'lt', value:[start,end] 或单值 }" + }, + { + "name": "where.start_time", + "type": "object", + "required": false, + "source": "body.where", + "description": "拆包开始时间范围 { operator:'between'|'gte'|'lte'|'gt'|'lt', value:[start,end] 或单值 }" + }, + { + "name": "where.end_time", + "type": "object", + "required": false, + "source": "body.where", + "description": "拆包结束时间范围 { operator:'between'|'gte'|'lte'|'gt'|'lt', value:[start,end] 或单值 }" + }, + { + "name": "where.status", + "type": "string", + "required": false, + "source": "body.where", + "description": "拆包状态(等值):unpacking 拆包中 / completed 完成 / cancelled 作废" + }, + { + "name": "where.detail_status", + "type": "string", + "required": false, + "source": "body.where", + "description": "明细识别状态(等值):none_recognized / partial_recognized / all_recognized" + }, + { + "name": "where.unpacker_id", + "type": "number", + "required": false, + "source": "body.where", + "description": "拆包人员工号ID(等值)" + }, + { + "name": "where.return_received_id", + "type": "number", + "required": false, + "source": "body.where", + "description": "关联退回收到单ID(等值)" + }, + { + "name": "where.store_id", + "type": "number", + "required": false, + "source": "body.where", + "description": "货主ID(等值)" + }, + { + "name": "where.order_express_id", + "type": "number", + "required": false, + "source": "body.where", + "description": "原运单ID(等值)" + }, + { + "name": "where.order_id", + "type": "number", + "required": false, + "source": "body.where", + "description": "原订单ID(等值)" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序 { sortField: 'id'|'created_at'|'updated_at'|'unpack_date'|'start_time'|'end_time'|'unpack_no'|'waybill_code', sortOrder: 'asc'|'desc' },默认 created_at desc" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "拆包单列表,每条含主表字段 + is_original_return 派生字段 + 格式化时间字段 + camera_ids 数组" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息 { page, pageSize, total, totalPages, hasPrevious, hasNext }" + } + ], + "errors": [ + { + "code": "401", + "message": "未提供有效的认证令牌" + }, + { + "code": "403", + "message": "无权访问该接口" + }, + { + "code": "500", + "message": "服务器内部错误" + } + ] + }, + { + "method": "returnUnpack.detailList", + "description": "拆包明细分页列表,命中识别商品时含 stockWarehouse 关联。仓库隔离:warehouse_id 由服务端自动注入 ctx.user.store_id,禁止前端传入。支持按拆包单ID、系统商品、条码、识别标记、产品状态筛选。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页 { page: 1, pageSize: 20 }(pageSize 上限 500,默认 20)" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "筛选条件对象,所有字段均可选" + }, + { + "name": "where.unpack_id", + "type": "number", + "required": false, + "source": "body.where", + "description": "拆包单ID(等值)" + }, + { + "name": "where.stock_id", + "type": "number", + "required": false, + "source": "body.where", + "description": "系统商品ID(wms_stock_warehouse.id,等值)" + }, + { + "name": "where.barcode", + "type": "string", + "required": false, + "source": "body.where", + "description": "扫描条码(模糊搜索,传 {operator:'like',value} 或直接值)" + }, + { + "name": "where.is_recognized", + "type": "number", + "required": false, + "source": "body.where", + "description": "是否识别(等值):1 识别到系统商品 / 0 非识别物品" + }, + { + "name": "where.product_status", + "type": "string", + "required": false, + "source": "body.where", + "description": "产品状态(等值):normal 正常 / damaged 破损" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序 { sortField: 'id'|'created_at'|'updated_at'|'quantity', sortOrder: 'asc'|'desc' },默认 created_at desc" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "明细行列表(含 is_recognized/item_code/item_name/spec/product_snapshot,识别命中时含 stockWarehouse 关联)" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息 { page, pageSize, total, totalPages, hasPrevious, hasNext }" + } + ], + "errors": [ + { + "code": "401", + "message": "未提供有效的认证令牌" + }, + { + "code": "403", + "message": "无权访问该接口" + }, + { + "code": "500", + "message": "服务器内部错误" + } + ] + }, + { + "method": "returnUnpack.detail", + "description": "拆包单详情:主表 + 明细(含 stockWarehouse 关联,命中时)+ 视频副表(含 camera 关联,命中时)+ 退回收到单(命中时);原单退回时(order_id 有值)返回 related.order 原订单详情。需 548 权限(客服员工及以上),仓库隔离校验(仅本仓库拆包单)。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "id", + "type": "integer", + "required": true, + "source": "body", + "description": "拆包单ID" + } + ], + "response": [ + { + "name": "record", + "type": "object", + "required": true, + "description": "主表完整记录(含 details 明细、videos 视频、returnReceived 退回收到单关联与格式化时间字段)" + }, + { + "name": "related", + "type": "object", + "required": true, + "description": "关联信息对象" + }, + { + "name": "related.order", + "type": "object", + "required": false, + "description": "原订单详情(含 items 明细,仅原单退回时返回,非原单为 null)" + } + ], + "errors": [ + { + "code": "400", + "message": "id 必填且必须为正整数" + }, + { + "code": "401", + "message": "未提供有效的认证令牌" + }, + { + "code": "403", + "message": "无权访问该拆包单" + }, + { + "code": "404", + "message": "拆包单不存在" + }, + { + "code": "500", + "message": "服务器内部错误" + } + ] + }, + { + "method": "returnUnpack.delete", + "description": "删除拆包单(后台管理,不限制状态):事务内物理删除主表 + 所有明细,并同步软删视频副表记录。作业层未完成状态取消请走 returnUnpack.cancel。仓库隔离校验(仅本仓库拆包单)。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "id", + "type": "integer", + "required": true, + "source": "body", + "description": "拆包单ID" + } + ], + "response": [ + { + "name": "id", + "type": "integer", + "required": true, + "description": "被删除拆包单ID" + } + ], + "errors": [ + { + "code": "400", + "message": "id 必填且必须为正整数" + }, + { + "code": "401", + "message": "未提供有效的认证令牌" + }, + { + "code": "403", + "message": "无权访问该拆包单" + }, + { + "code": "403", + "message": "无权访问该接口" + }, + { + "code": "404", + "message": "拆包单不存在" + }, + { + "code": "500", + "message": "服务器内部错误" + } + ] + } + ] + }, + { + "groupName": "运单退回登记模块", + "module": "returnWaybill", + "list": [ + { + "method": "returnWaybill.create", + "description": "运单退回登记(增):录入「货主 + 运单号」退回关系。waybill_code/store_id 必填;校验 wms_store_warehouse 存在 store_id + warehouse_id 货主合约,无合约拒绝写入;同仓库+货主+运单号已存在时幂等返回已有记录(duplicated=true,不重复插入)。写入 is_notified=0/is_back=0(由定时任务与拆包联动维护,登记接口不维护)。仓库隔离:warehouse_id 由服务端注入 ctx.user.store_id,禁止前端传入。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "waybill_code", + "type": "string", + "required": true, + "source": "body", + "description": "运单号(登记入参,必填,trim 后不能为空)" + }, + { + "name": "store_id", + "type": "integer", + "required": true, + "source": "body", + "description": "货主ID(必填,正整数,需存在 wms_store_warehouse 中 store_id + warehouse_id 合约记录)" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注(可选,最长 500 字符,超出截断)" + } + ], + "response": [ + { + "name": "record", + "type": "object", + "required": true, + "description": "登记记录包装对象,含登记记录完整字段(id、warehouse_id、store_id、waybill_code、remark、is_notified、is_back、created_at、updated_at,时间字段为格式化字符串)" + }, + { + "name": "duplicated", + "type": "boolean", + "required": true, + "description": "是否命中已有记录:同仓库+货主+运单号已存在时为 true(返回已有记录,不重复插入),否则 false" + } + ], + "errors": [ + { + "code": "400", + "message": "waybill_code 不能为空" + }, + { + "code": "400", + "message": "store_id 必填且必须为正整数" + }, + { + "code": "400", + "message": "缺少仓库上下文" + }, + { + "code": "400", + "message": "货主在当前仓库无合约关系,无法登记" + }, + { + "code": "401", + "message": "未提供有效的认证令牌" + }, + { + "code": "403", + "message": "无权访问该接口" + }, + { + "code": "500", + "message": "服务器内部错误" + } + ] + }, + { + "method": "returnWaybill.update", + "description": "修改登记(改):id 必填,可改 waybill_code/store_id/remark。校验记录存在且属于当前仓库;store_id 变更时重新校验新货主合约(wms_store_warehouse 存在 store_id + warehouse_id);改后与另一条同仓库+货主+运单号冲突则 409 拒绝(防重复登记)。仓库隔离校验(仅本仓库记录)。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "id", + "type": "integer", + "required": true, + "source": "body", + "description": "登记记录主键ID(必填,正整数)" + }, + { + "name": "waybill_code", + "type": "string", + "required": false, + "source": "body", + "description": "运单号(可选,改运单号,trim 后不能为空字符串)" + }, + { + "name": "store_id", + "type": "integer", + "required": false, + "source": "body", + "description": "货主ID(可选,改货主ID;变更时校验新货主在当前仓库的合约)" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注(可选,最长 500 字符,超出截断)" + } + ], + "response": [ + { + "name": "record", + "type": "object", + "required": true, + "description": "更新后的登记记录完整信息(含格式化时间字段)" + } + ], + "errors": [ + { + "code": "400", + "message": "id 必填且必须为正整数" + }, + { + "code": "400", + "message": "waybill_code 不能为空" + }, + { + "code": "400", + "message": "store_id 必填且必须为正整数" + }, + { + "code": "400", + "message": "货主在当前仓库无合约关系,无法登记" + }, + { + "code": "401", + "message": "未提供有效的认证令牌" + }, + { + "code": "403", + "message": "无权访问该登记记录" + }, + { + "code": "403", + "message": "无权访问该接口" + }, + { + "code": "404", + "message": "登记记录不存在" + }, + { + "code": "409", + "message": "已存在相同货主 + 运单号的登记记录" + }, + { + "code": "500", + "message": "服务器内部错误" + } + ] + }, + { + "method": "returnWaybill.list", + "description": "运单退回登记分页列表。仓库隔离:warehouse_id 由服务端注入 ctx.user.store_id,禁止前端传入。支持按运单号模糊、货主、是否已通知、是否退回、登记时间范围筛选。is_notified/is_back 由定时任务与拆包联动维护,登记接口不维护。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页 { page: 1, pageSize: 20 }(pageSize 上限 500,默认 20)" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "筛选条件对象,所有字段均可选" + }, + { + "name": "where.waybill_code", + "type": "string", + "required": false, + "source": "body.where", + "description": "运单号(模糊搜索,传 {operator:'like',value} 或直接值)" + }, + { + "name": "where.store_id", + "type": "number", + "required": false, + "source": "body.where", + "description": "货主ID(等值)" + }, + { + "name": "where.is_notified", + "type": "number", + "required": false, + "source": "body.where", + "description": "是否已通知(等值):1 已通知 / 0 未通知(由定时任务维护,登记接口不写入)" + }, + { + "name": "where.is_back", + "type": "number", + "required": false, + "source": "body.where", + "description": "是否退回(等值):1 已退回 / 0 未退回(由拆包单提交联动维护,登记接口不写入)" + }, + { + "name": "where.created_at", + "type": "object", + "required": false, + "source": "body.where", + "description": "登记日期范围 { operator:'between'|'gte'|'lte'|'gt'|'lt', value:[start,end] 或单值 }" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序 { sortField: 'id'|'created_at'|'updated_at'|'waybill_code', sortOrder: 'asc'|'desc' },默认 created_at desc" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "运单退回登记列表,每条含登记字段(id、warehouse_id、store_id、waybill_code、remark、is_notified、is_back)及格式化时间字段" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息 { page, pageSize, total, totalPages, hasPrevious, hasNext }" + } + ], + "errors": [ + { + "code": "401", + "message": "未提供有效的认证令牌" + }, + { + "code": "403", + "message": "无权访问该接口" + }, + { + "code": "500", + "message": "服务器内部错误" + } + ] + }, + { + "method": "returnWaybill.detail", + "description": "运单退回登记详情。免权限(复用列表权限),仅需登录 + 仓库隔离校验(仅本仓库记录)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "id", + "type": "integer", + "required": true, + "source": "body", + "description": "登记记录主键ID(必填,正整数)" + } + ], + "response": [ + { + "name": "record", + "type": "object", + "required": true, + "description": "登记记录完整信息(id、warehouse_id、store_id、waybill_code、remark、is_notified、is_back 及格式化时间字段)" + } + ], + "errors": [ + { + "code": "400", + "message": "id 必填且必须为正整数" + }, + { + "code": "401", + "message": "未提供有效的认证令牌" + }, + { + "code": "403", + "message": "无权访问该登记记录" + }, + { + "code": "404", + "message": "登记记录不存在" + }, + { + "code": "500", + "message": "服务器内部错误" + } + ] + }, + { + "method": "returnWaybill.delete", + "description": "删除运单退回登记(物理删除,表 paranoid:false)。仓库隔离校验(仅本仓库记录)。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "id", + "type": "integer", + "required": true, + "source": "body", + "description": "登记记录主键ID(必填,正整数)" + } + ], + "response": [ + { + "name": "id", + "type": "integer", + "required": true, + "description": "被删除登记记录ID" + } + ], + "errors": [ + { + "code": "400", + "message": "id 必填且必须为正整数" + }, + { + "code": "401", + "message": "未提供有效的认证令牌" + }, + { + "code": "403", + "message": "无权访问该登记记录" + }, + { + "code": "403", + "message": "无权访问该接口" + }, + { + "code": "404", + "message": "登记记录不存在" + }, + { + "code": "500", + "message": "服务器内部错误" + } + ] + } + ] } ] } From 59ef8117d70dd9037ad35bfc8cd1d1cbb034be41 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Thu, 13 Aug 2026 21:42:27 +0800 Subject: [PATCH 201/550] =?UTF-8?q?fix:=20inbox=20=E8=A1=A5=E5=85=A8=20mes?= =?UTF-8?q?sage.retry/reply=20=E6=96=B9=E6=B3=95=E5=85=A5=E5=8F=A3?= =?UTF-8?q?=EF=BC=8C=E4=BF=AE=E5=A4=8D=20retry=20=E6=96=B9=E6=B3=95?= =?UTF-8?q?=E4=B8=8D=E5=AD=98=E5=9C=A8=E6=8A=A5=E9=94=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/inbox/message.js | 82 ++++++++++++++++++++++++++++++ app/service/systemMethods/inbox.js | 35 +++++++++++++ 2 files changed, 117 insertions(+) diff --git a/app/service/inbox/message.js b/app/service/inbox/message.js index e5cdff0..d803526 100644 --- a/app/service/inbox/message.js +++ b/app/service/inbox/message.js @@ -399,6 +399,88 @@ class InboxMessageService extends Service { recent_24h_count: recentCount, }; } + + /** + * 手动重推失败(push_status=3)的站内信消息。 + * 重置为待推送状态(push_status=0)并触发异步推送。 + * @param {Object} params 重推参数。 + * @param {number} params.warehouseId 仓库ID(必填,服务端上下文注入)。 + * @param {number} params.id 消息ID。 + * @return {Promise} { ok, id, ext_id, message }。 + */ + async retry(params = {}) { + const { ctx } = this; + const { InboxMessage } = ctx.model; + + const warehouseId = Number(params.warehouseId); + const id = Number(params.id); + + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + throw new Error('warehouseId 无效'); + } + if (!Number.isFinite(id) || id <= 0) { + throw new Error('消息ID无效'); + } + + const record = await InboxMessage.findOne({ + where: { id, warehouse_id: warehouseId, deleted_at: null }, + }); + + if (!record) { + throw new Error('消息不存在或无权访问'); + } + if (record.push_status !== 3) { + throw new Error('仅失败状态的消息可以手动重推'); + } + + // 重置为待推送状态 + await InboxMessage.update( + { push_status: 0, push_response: null, push_started_at: null }, + { where: { id } } + ); + + // 回执记录 ext_id 形如 sys:ack:{原消息ext_id},反解出原消息 ext_id 以复用推送链路 + const extId = String(record.ext_id || ''); + const originalExtId = extId.startsWith('sys:ack:') ? extId.slice(8) : extId; + const hasUser = Boolean(record.user_id && record.user_name); + const pushData = { + warehouse_id: warehouseId, + ext_id: originalExtId, + parent_id: record.parent_id || null, + group_id: record.group_id || '', + group_name: record.group_name || '', + user_id: record.user_id || '', + user_name: record.user_name || '', + ext_data: record.ext_data || null, + }; + + // 触发异步推送 + setImmediate(() => { + ctx.service.inbox.processor.writeOutboundReply( + pushData, + record.content || '', + hasUser ? 'ai_reply' : 'system' + ).catch(async err => { + ctx.logger.error(`[inbox] 手动重推异步推送异常 id=${id}: ${err.message}`); + // 推送前校验失败时回写失败状态,避免消息卡在待推送 + try { + await InboxMessage.update( + { push_status: 3, push_response: { error: err.message } }, + { where: { id } } + ); + } catch (updateErr) { + ctx.logger.error(`[inbox] 重推失败状态回写异常 id=${id}: ${updateErr.message}`); + } + }); + }); + + return { + ok: true, + id: record.id, + ext_id: record.ext_id, + message: '已重置为待推送状态,正在异步重推', + }; + } } module.exports = InboxMessageService; diff --git a/app/service/systemMethods/inbox.js b/app/service/systemMethods/inbox.js index c0dccee..018de3c 100644 --- a/app/service/systemMethods/inbox.js +++ b/app/service/systemMethods/inbox.js @@ -44,6 +44,8 @@ class InboxSystemService extends MainService { const warehouseId = Number(ctx.user?.store_id || 0); return ctx.service.inbox.message.stats({ warehouseId, direction: data.direction }); }, + reply: data => this.reply(data), + retry: data => this.retry(data), checkAuth: (...args) => this.checkAuth(...args), }; } @@ -186,6 +188,39 @@ class InboxSystemService extends MainService { pageSize, }); } + + /** + * 手动重推失败(push_status=3)的站内信消息。 + * 兼容旧版 inbox.retry 路径,与 inbox.message.retry 等价。 + * warehouseId 从 ctx.user.store_id 自动注入。 + * + * @param {Object} data 请求数据。 + * @param {number} data.id 消息ID(必填)。 + * @return {Promise} { ok, id, ext_id, message }。 + */ + async retry(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user?.store_id || 0); + return await ctx.service.inbox.message.retry({ warehouseId, id: data.id }); + } + + /** + * 系统回信:写入 outbound 记录。 + * 兼容旧版 inbox.reply 路径,与 inbox.message.reply 等价。 + * warehouseId 从 ctx.user.store_id 自动注入。 + * + * @param {Object} data 请求数据。 + * @param {number} data.parentId 原消息ID(必填)。 + * @param {string} [data.content] 回信正文。 + * @param {Object} [data.extData] 透传数据。 + * @param {Object} [data.flags] 处理标记。 + * @return {Promise} 回信结果。 + */ + async reply(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user?.store_id || 0); + return await ctx.service.inbox.index.reply({ warehouseId, ...data }); + } } module.exports = InboxSystemService; From d25ea39e87c7dd6fc23fbdbfc10a39172e82b549 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Thu, 13 Aug 2026 21:42:58 +0800 Subject: [PATCH 202/550] =?UTF-8?q?fix:=20=E5=BA=93=E5=86=85=E6=8B=A6?= =?UTF-8?q?=E6=88=AA=E6=89=AB=E6=8F=8F=E4=B8=A5=E6=A0=BC=E6=A0=A1=E9=AA=8C?= =?UTF-8?q?=EF=BC=8C=E9=9D=9E=E6=8B=A6=E6=88=AA=E8=AE=A2=E5=8D=95=E7=9B=B4?= =?UTF-8?q?=E6=8E=A5=E6=8B=92=E7=BB=9D=E4=B8=94=E4=B8=8D=E5=86=8D=E8=A1=A5?= =?UTF-8?q?=E5=BB=BA=E7=BC=BA=E5=A4=B1=E8=BF=90=E5=8D=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../systemMethods/order/recheckOrder.js | 60 ++++++++++++------- 1 file changed, 38 insertions(+), 22 deletions(-) diff --git a/app/service/systemMethods/order/recheckOrder.js b/app/service/systemMethods/order/recheckOrder.js index 5dec0ae..0ff76a1 100644 --- a/app/service/systemMethods/order/recheckOrder.js +++ b/app/service/systemMethods/order/recheckOrder.js @@ -3700,11 +3700,13 @@ class RecheckOrderService extends OrderBaseService { * 拦截扫描:通过运单号查找运单记录,标记退回与拦截并处理关联工单与订单拦截状态。 * * 处理流程: - * 1. 根据运单号查询 wms_order_express,找到则将 is_back、is_intercept 设为 'Y';未找到则创建新记录补充缺失快递 - * 2. 检查是否存在关联的未完结售后工单(wms_after_sale),若有则调用 handleWorkOrder 写入 + * 1. 根据运单号查询 wms_order_express;运单不存在,或运单 is_intercept≠'Y' 且关联订单 + * intercept_status 不在 requested/intercepting 时,视为非拦截订单并拒绝 + * 2. 校验通过后将运单 is_back、is_intercept 设为 'Y' + * 3. 检查是否存在关联的未完结售后工单(wms_after_sale),若有则调用 handleWorkOrder 写入 * "库内拦截成功"步骤并将工单置为 completed - * 3. 同步更新 wms_order_delivery 的 intercept_status 为 intercepted_at_warehouse, - * 并释放储位分配与订单锁(与 confirmIntercept 行为一致,订单级拦截覆盖所有面单含子面单) + * 4. 同步更新 wms_order_delivery 的 intercept_status 为 intercepted_at_warehouse, + * 并释放储位分配与订单锁(仅订单级状态更新,不标记订单下其他面单) * * 注:库内拦截确认需标记退回 is_back='Y';发起拦截链路仅写 is_intercept,不写 is_back。 * @@ -3725,31 +3727,45 @@ class RecheckOrderService extends OrderBaseService { const now = new Date(); // 1. 查询运单记录 - let expressRecord = await ctx.model.OrderExpress.findOne({ + const expressRecord = await ctx.model.OrderExpress.findOne({ where: { waybill_code: normalizedWaybillCode, warehouse_id: warehouseId }, raw: true, }); - // 1a. 缺失快递补充:运单记录不存在则创建新记录(库内拦截确认需标记退回) + // 1a. 非拦截订单校验:运单不存在,或运单/关联订单均未发起系统拦截,则拒绝 if (!expressRecord) { - const created = await ctx.model.OrderExpress.create({ - waybill_code: normalizedWaybillCode, - order_id: null, - warehouse_id: warehouseId, - is_back: 'Y', - is_intercept: 'Y', - create_at: now, - }); - - expressRecord = (created && created.toJSON ? created.toJSON() : created) || {}; - } else { - // 2. 标记退回 + 拦截 - await ctx.model.OrderExpress.update( - { is_back: 'Y', is_intercept: 'Y' }, - { where: { id: expressRecord.id } } - ); + throw new Error('非拦截订单'); } + const expressIntercepted = String(expressRecord.is_intercept || '').trim() === 'Y'; + let orderIntercepted = false; + + if (!expressIntercepted) { + const linkedOrderId = Number(expressRecord.order_id || 0); + + if (linkedOrderId > 0) { + const checkOrderModel = await this.getOrderModelByTableType('current', warehouseId); + const linkedOrder = await checkOrderModel.findOne({ + where: this.buildOrderWhere([ linkedOrderId ], warehouseId), + attributes: [ 'id', 'intercept_status' ], + raw: true, + }); + orderIntercepted = linkedOrder + ? [ 'requested', 'intercepting' ].includes(String(linkedOrder.intercept_status || '').trim()) + : false; + } + } + + if (!expressIntercepted && !orderIntercepted) { + throw new Error('非拦截订单'); + } + + // 2. 标记退回 + 拦截 + await ctx.model.OrderExpress.update( + { is_back: 'Y', is_intercept: 'Y' }, + { where: { id: expressRecord.id } } + ); + // 3. 检查关联的未完结售后工单 const afterSale = await ctx.model.AfterSale.findOne({ where: { From 75a248fdf6d6048c189607298f290a508d98817b Mon Sep 17 00:00:00 2001 From: liufumingren Date: Thu, 13 Aug 2026 21:43:01 +0800 Subject: [PATCH 203/550] =?UTF-8?q?feat:=20=E6=94=B6=E8=B4=A7=E5=8D=95?= =?UTF-8?q?=E5=88=97=E8=A1=A8=E6=96=B0=E5=A2=9E=20stock=5Fquery=5Fwhere=20?= =?UTF-8?q?=E5=95=86=E5=93=81=E7=BB=B4=E5=BA=A6=E8=BF=87=E6=BB=A4=EF=BC=88?= =?UTF-8?q?=E6=9D=A1=E7=A0=81/=E7=BC=96=E7=A0=81/ID=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../systemMethods/storage/receiving.js | 11 +- app/service/systems/storage/receiving.js | 119 +++++++++++++++--- 2 files changed, 110 insertions(+), 20 deletions(-) diff --git a/app/service/systemMethods/storage/receiving.js b/app/service/systemMethods/storage/receiving.js index db61b3f..22771d0 100644 --- a/app/service/systemMethods/storage/receiving.js +++ b/app/service/systemMethods/storage/receiving.js @@ -26,11 +26,12 @@ class configService extends MainService { * @param {Object} [data.where] 筛选条件 * @param {boolean} [data.filterDepleted=false] 是否过滤掉无可再用量的收货单(所有明细已被其他入库单 committed 绑定占满) * @param {number} [data.entry_order_id] 可选,按入库单商品交集过滤:只返回"至少有一条明细的 system_product_id 在入库单明细中"的收货单 + * @param {string} [data.stock_query_where] 可选,按商品条码/商品编码/商品ID搜索,返回明细中含匹配商品的收货单 * @return {Promise} 统一成功包装响应 */ async getReceivingList(data) { const { service } = this; - const { pagination, sort, filterDepleted = false, entry_order_id: entryOrderId } = data; + const { pagination, sort, filterDepleted = false, entry_order_id: entryOrderId, stock_query_where: stockQueryWhere } = data; const { where } = this.prepareWhereContext(data, { specialFieldMap: { quickWhere: { @@ -38,7 +39,7 @@ class configService extends MainService { }, }, }); - const result = await service.systems.storage.receiving.getReceivingList(where, pagination, sort, { filterDepleted, entry_order_id: entryOrderId }); + const result = await service.systems.storage.receiving.getReceivingList(where, pagination, sort, { filterDepleted, entry_order_id: entryOrderId, stock_query_where: stockQueryWhere }); return this.success('ok', result); } @@ -49,11 +50,12 @@ class configService extends MainService { * @param {Object} [data.pagination] 分页参数 * @param {Object} [data.where] 筛选条件 * @param {Object} [data.sort] 排序参数 + * @param {string|string[]} [data.stock_query_where] 可选,按商品条码/商品编码/商品ID搜索,返回明细中含匹配商品的收货单 * @return {Promise} 统一成功包装响应 */ async getStoreReceivingList(data) { const { ctx, app } = this; - const { pagination, sort } = data; + const { pagination, sort, stock_query_where: stockQueryWhere } = data; // 从平台激活上下文获取 store_id(使用原生查询避免 AccountPlatformActive 无 id 列兼容问题) const platformRows = await app.model.query( @@ -85,7 +87,8 @@ class configService extends MainService { where, storeId, pagination, - sort + sort, + { stock_query_where: stockQueryWhere } ); return this.success('ok', result); diff --git a/app/service/systems/storage/receiving.js b/app/service/systems/storage/receiving.js index 127315b..b49b3f2 100644 --- a/app/service/systems/storage/receiving.js +++ b/app/service/systems/storage/receiving.js @@ -47,6 +47,7 @@ class ReceivingService extends Service { * @param {Object} [options] 额外选项 * @param {boolean} [options.filterDepleted=false] 是否过滤掉无可再用量的收货单 * @param {number} [options.entry_order_id] 可选,按入库单商品交集过滤:只返回"至少有一条明细的 system_product_id 在入库单明细中"的收货单 + * @param {string|string[]} [options.stock_query_where] 可选,按商品维度过滤:搜索条码/商品编码/商品ID,返回明细中含匹配商品的收货单(支持字符串或字符串数组,多个关键字取并集) * @return {Promise} 列表、分页与汇总信息 */ async getReceivingList(where, pageParams = {}, sortParams = {}, options = {}) { @@ -70,7 +71,7 @@ class ReceivingService extends Service { sortField = 'id', sortOrder = 'DESC', } = sortParams; - const { filterDepleted = false, entry_order_id: entryOrderId } = options; + const { filterDepleted = false, entry_order_id: entryOrderId, stock_query_where: stockQueryWhere } = options; const queryOptions = { where: { @@ -301,18 +302,23 @@ class ReceivingService extends Service { } } - // 合并 filterDepleted 和 entry_order_id 的过滤结果 + // 可选过滤:按 stock_query_where(商品条码/编码/ID)过滤,支持字符串或字符串数组 + let stockQueryFilteredIds = null; + const stockQueryKeywords = Array.isArray(stockQueryWhere) + ? stockQueryWhere.map(v => String(v).trim()).filter(Boolean) + : (typeof stockQueryWhere === 'string' && stockQueryWhere.trim() !== '' ? [ stockQueryWhere.trim() ] : []); + if (stockQueryKeywords.length > 0) { + stockQueryFilteredIds = await this._resolveStockQueryReceivingIds(stockQueryKeywords); + } + + // 合并 filterDepleted / entry_order_id / stock_query_where 的过滤结果(多组启用时取交集) let combinedFilteredIds = null; - if (filteredReceivingIds !== null || intersectionFilteredIds !== null) { - if (filteredReceivingIds !== null && intersectionFilteredIds !== null) { - // 两个过滤都启用 → 取交集 - const intersectionSet = new Set(intersectionFilteredIds); - combinedFilteredIds = filteredReceivingIds.filter(id => intersectionSet.has(id)); - } else if (filteredReceivingIds !== null) { - combinedFilteredIds = filteredReceivingIds; - } else { - combinedFilteredIds = intersectionFilteredIds; - } + const idFilterSets = [ filteredReceivingIds, intersectionFilteredIds, stockQueryFilteredIds ] + .filter(arr => arr !== null) + .map(arr => new Set(arr)); + if (idFilterSets.length > 0) { + const [ first, ...rest ] = idFilterSets; + combinedFilteredIds = [ ...first ].filter(id => rest.every(set => set.has(id))); } // 如果启用了过滤,用过滤后的 ID 做最终查询 @@ -404,7 +410,7 @@ class ReceivingService extends Service { conditions: normalizedWhere, sortField: actualSortField, sortOrder: actualSortOrder, - hasBarcodeSearch: false, + hasBarcodeSearch: stockQueryKeywords.length > 0, }, }, message: '查询成功', @@ -434,6 +440,70 @@ class ReceivingService extends Service { }; } } + + /** + * 按商品关键字解析收货单 ID 列表。 + * 搜索范围: + * 1) wms_stock_warehouse.item_code(商品编码)模糊匹配 + * 2) wms_stock_warehouse.id 精确匹配(关键字为纯数字时) + * 3) wms_stock_barcodes.barcode(条码)模糊匹配 + * 再通过 wms_receiving_detail.system_product_id 关联回收货单。 + * @param {string|string[]} keywords 搜索关键字(字符串或字符串数组,多个关键字取并集) + * @return {Promise} 收货单 ID 数组;关键字为空返回 null + */ + async _resolveStockQueryReceivingIds(keywords) { + const { ctx, app } = this; + const { Sequelize } = app; + const { Op } = Sequelize; + + const keywordList = (Array.isArray(keywords) ? keywords : [ keywords ]) + .map(v => String(v).trim()) + .filter(Boolean); + if (keywordList.length === 0) return null; + + const stockIds = new Set(); + + // 1. 商品编码 / 商品ID 匹配(wms_stock_warehouse) + const stockWhere = { + [Op.or]: keywordList.map(k => ({ item_code: { [Op.like]: `%${k}%` } })), + }; + keywordList.forEach(k => { + if (/^\d+$/.test(k)) { + stockWhere[Op.or].push({ id: Number(k) }); + } + }); + const stockRows = await ctx.model.StockWarehouse.findAll({ + attributes: [ 'id' ], + where: stockWhere, + raw: true, + }); + stockRows.forEach(row => stockIds.add(Number(row.id))); + + // 2. 条码匹配(wms_stock_barcodes → stock_id) + const barcodeRows = await ctx.model.StockBarcode.findAll({ + attributes: [ 'stock_id' ], + where: { + [Op.or]: keywordList.map(k => ({ barcode: { [Op.like]: `%${k}%` } })), + }, + raw: true, + }); + barcodeRows.forEach(row => stockIds.add(Number(row.stock_id))); + + if (stockIds.size === 0) return []; + + // 3. 通过明细表关联回收货单 + const detailRows = await ctx.model.ReceivingDetail.findAll({ + attributes: [ 'receiving_id' ], + where: { + system_product_id: { [Op.in]: [ ...stockIds ] }, + }, + group: [ 'receiving_id' ], + raw: true, + }); + + return [ ...new Set(detailRows.map(row => row.receiving_id)) ]; + } + /** * 货主侧收货单列表查询。 * 以 store_id 为维度查询收货单,支持分页、多条件筛选与排序。 @@ -445,14 +515,17 @@ class ReceivingService extends Service { * @param {Object} [sortParams] 排序参数 * @param {string} [sortParams.sortField='created_at'] 排序字段 * @param {string} [sortParams.sortOrder='DESC'] 排序方向 + * @param {Object} [options] 额外选项 + * @param {string|string[]} [options.stock_query_where] 可选,按商品维度过滤:搜索条码/商品编码/商品ID,返回明细中含匹配商品的收货单(支持字符串或字符串数组,多个关键字取并集) * @return {Promise} 列表、分页与汇总信息 */ - async getStoreReceivingList(where, storeId, pageParams = {}, sortParams = {}) { + async getStoreReceivingList(where, storeId, pageParams = {}, sortParams = {}, options = {}) { const { ctx, app } = this; const { Sequelize } = app; const { Op } = Sequelize; const { page = 1, pageSize = 20 } = pageParams; const { sortField = 'created_at', sortOrder = 'DESC' } = sortParams; + const { stock_query_where: stockQueryWhere } = options; try { const queryOptions = { @@ -522,13 +595,27 @@ class ReceivingService extends Service { const offset = (page - 1) * pageSize; + // 可选过滤:按 stock_query_where(商品条码/编码/ID)过滤,支持字符串或字符串数组 + let stockQueryFilteredIds = null; + const stockQueryKeywords = Array.isArray(stockQueryWhere) + ? stockQueryWhere.map(v => String(v).trim()).filter(Boolean) + : (typeof stockQueryWhere === 'string' && stockQueryWhere.trim() !== '' ? [ stockQueryWhere.trim() ] : []); + if (stockQueryKeywords.length > 0) { + stockQueryFilteredIds = await this._resolveStockQueryReceivingIds(stockQueryKeywords); + } + + const finalWhere = stockQueryFilteredIds !== null + ? { id: { [Op.in]: stockQueryFilteredIds } } + : queryOptions.where; + const [ total, data ] = await Promise.all([ ctx.model.Receiving.count({ - where: queryOptions.where, + where: finalWhere, distinct: true, }), ctx.model.Receiving.findAll({ ...queryOptions, + where: finalWhere, limit: Number(pageSize), offset: Number(offset), distinct: true, @@ -611,7 +698,7 @@ class ReceivingService extends Service { conditions: normalizedWhere, sortField: actualSortField, sortOrder: actualSortOrder, - hasBarcodeSearch: false, + hasBarcodeSearch: stockQueryKeywords.length > 0, }, }, message: '查询成功', From bcf6a5b38484b53be24e66f504c0411978827c63 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Thu, 13 Aug 2026 23:13:07 +0800 Subject: [PATCH 204/550] =?UTF-8?q?feat:=20=E6=9F=A5=E9=80=80=E5=9B=9E?= =?UTF-8?q?=E6=98=8E=E7=BB=86=EF=BC=88queryReturn=EF=BC=89+=20=E9=80=80?= =?UTF-8?q?=E5=9B=9E=E6=8B=86=E5=8C=85=E5=BD=95=E6=98=8E=E7=BB=86=E6=9D=A1?= =?UTF-8?q?=E7=A0=81=E4=B8=8E=E8=AE=A2=E5=8D=95=E4=BF=A1=E6=81=AF=E5=BF=AB?= =?UTF-8?q?=E7=85=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 站内信新增 queryReturn(查退回+运单号):跨退回相关表查询(拆包/退回收到/退回查询登记),未退回自动预登记,未收到时回填退回登记表货主 - 模板消息直发机制 direct_reply:函数返回模板原样回复,不经 AI 改写 - 退回拆包 addDetail 支持 barcode(仅作记录)、未指定 stock_id 标注未知商品、跨货主 stock_id 403 - wms_return_unpack 新增 source_order_codes/shop_name 快照(迁移 20260813170000),原单退回时回填 - ai.js 加固:DeepSeek 推理模型 max_tokens 提升、截断/空 JSON 重试、查询类请求强制调函数规则 - 新增调试脚本 script/debug-inbox-push.cjs;同步 methods 文档与变更记录 --- app/model/return_unpack.js | 10 + app/service/inbox/ai.js | 45 ++- app/service/inbox/functions.js | 94 +++++ app/service/systemMethods/returnUnpack.js | 5 +- app/service/systems/return_unpack.js | 364 +++++++++++++++++- ...0813170000-add-return-unpack-order-info.js | 36 ++ methods/changes/system.json | 48 +++ methods/system.json | 17 +- script/debug-inbox-push.cjs | 243 ++++++++++++ 9 files changed, 844 insertions(+), 18 deletions(-) create mode 100644 database/migrations/20260813170000-add-return-unpack-order-info.js create mode 100644 script/debug-inbox-push.cjs diff --git a/app/model/return_unpack.js b/app/model/return_unpack.js index 60316b7..6772771 100644 --- a/app/model/return_unpack.js +++ b/app/model/return_unpack.js @@ -100,6 +100,16 @@ module.exports = app => { allowNull: true, comment: '货主ID,原单退回/识别到系统商品时回填', }, + source_order_codes: { + type: STRING(500), + allowNull: true, + comment: '平台交易单号快照(原单退回时回填)', + }, + shop_name: { + type: STRING(50), + allowNull: true, + comment: '店铺名称快照(货主自定义店铺名称 store_remask)', + }, camera_ids: { type: JSON_TYPE, allowNull: true, diff --git a/app/service/inbox/ai.js b/app/service/inbox/ai.js index fc41d87..8d25d1f 100644 --- a/app/service/inbox/ai.js +++ b/app/service/inbox/ai.js @@ -44,6 +44,17 @@ class InboxAIService extends Service { } let content = result.data.choices?.[0]?.message?.content || ''; + const reasoning = result.data.choices?.[0]?.message?.reasoning_content || ''; + const finishReason = result.data.choices?.[0]?.finish_reason || ''; + + // 推理模型会把 max_tokens 消耗在 reasoning 上,导致 content 为空(finish_reason=length) + if (!content.trim() && finishReason === 'length') { + ctx.logger.warn( + `[inbox ai] DeepSeek 输出被截断: reasoning=${reasoning.length} 字符, content 为空, finish_reason=length` + ); + throw new Error('DeepSeek 输出被截断(max_tokens 被推理过程占满),请提高 max_tokens'); + } + // 清理 markdown 代码块 content = content.replace(/^```json\s*/i, '').replace(/\s*```$/i, ''); content = content.replace(/^```\s*/i, '').replace(/\s*```$/i, ''); @@ -185,6 +196,7 @@ class InboxAIService extends Service { let finalReply = null; let lastFunctionName = null; let lastFunctionResult = null; + let jsonRetryNote = ''; const systemPrompt = `你是一个 WMS 仓库管理系统的智能助手,支持多步推理。 已注册函数:\n${functionListText}\n @@ -241,7 +253,10 @@ ${historyContext} - 用户说"第1个""第2个"时,按 searchStock 返回的顺序对应选择 - 需要上下文但记忆不足时,主动调用 recallHistory 回顾对话历史 - 【防误判规则 - interceptWaybill】讨论已有售后工单(AS开头编号)、询问物流进度、问"快递到哪了"、转发售后截图等均不是拦截请求,严禁调用 interceptWaybill。只有用户明确说"拦截/退回/召回/追回/取消"运单时才可调用 -- 【措辞规则 - interceptWaybill】拦截结果回复严禁使用"已拦截""拦截成功"等确定口吻,必须使用"拦截信息已登记""已提交拦截申请"等措辞。因为快递拦截可能失败,实际结果以快递公司反馈为准。回复时需列出工单号供用户跟进`; +- 【措辞规则 - interceptWaybill】拦截结果回复严禁使用"已拦截""拦截成功"等确定口吻,必须使用"拦截信息已登记""已提交拦截申请"等措辞。因为快递拦截可能失败,实际结果以快递公司反馈为准。回复时需列出工单号供用户跟进 +- 【模板消息 - queryReturn】queryReturn 返回的 data.message 是已排版好的模板消息,必须原样作为最终回复输出,禁止改写、删减、增补内容,禁止添加 Markdown 或额外说明 +- 用户发送"查退回+运单号"时,调用 queryReturn 查询退回明细,不要误调 queryOrder 或 interceptWaybill +- 【查询类请求强制调函数】查订单/查退回/查库存等查询类请求必须实际调用对应函数获取结果后再回复,严禁仅凭历史对话或猜测臆测"服务不可用/无法处理"而跳过函数调用`; // 多轮推理循环 for (let round = 1; round <= MAX_ROUNDS; round++) { @@ -261,7 +276,7 @@ ${historyContext} ...(contextLines.length > 0 ? [{ role: 'system', content: contextLines.join('\n') }] : []), { role: 'user', content: round === 1 ? content - : (executedFunctions.length > 0 + : (jsonRetryNote ? `${jsonRetryNote}\n` : '') + (executedFunctions.length > 0 ? `已获取到函数执行结果,请根据结果 reply 告知用户(禁止 silent)。第 ${round}/${MAX_ROUNDS} 轮` : `请根据已获取的信息,决定下一步:继续调用函数还是给出最终回复。第 ${round}/${MAX_ROUNDS} 轮`), }, @@ -269,7 +284,8 @@ ${historyContext} let raw = ''; try { - raw = await this.callDeepSeek(messages, { maxTokens: 600 }); + // 推理模型(deepseek-v4-pro)需要充足 max_tokens:推理过程会先占用配额,过小会导致 content 被截断为空 + raw = await this.callDeepSeek(messages, { maxTokens: 4000 }); ctx.logger.info(`[inbox ai] 第 ${round}/${MAX_ROUNDS} 轮: ${raw}`); const result = JSON.parse(raw); @@ -318,6 +334,19 @@ ${historyContext} if (lastThought) lastThought.functionResult = lastFunctionResult; ctx.logger.info(`[inbox ai] 执行 ${fnName}: ${JSON.stringify(lastFunctionResult)}`); + // 函数携带模板消息(direct_reply=true)→ 直接作为最终回复,不再交由 AI 改写 + const directReply = lastFunctionResult + && lastFunctionResult.data + && lastFunctionResult.data.direct_reply === true + && lastFunctionResult.data.message + ? String(lastFunctionResult.data.message) + : ''; + if (directReply) { + ctx.logger.info(`[inbox ai] 函数 ${fnName} 返回模板消息,直接回复 (length=${directReply.length})`); + finalReply = directReply; + break; + } + // 最后一轮强制输出 if (round === MAX_ROUNDS) { finalReply = lastFunctionResult?.data?.message @@ -333,9 +362,15 @@ ${historyContext} } catch (error) { ctx.logger.warn(`[inbox ai] 第 ${round} 轮异常: ${error.message}, raw: ${raw}`); - // 不是 JSON → 当作文本回复 + // 模型输出疑似被截断的 JSON → 提醒后重试,避免把原始 JSON 当作回复发给用户 if (error instanceof SyntaxError && raw) { - finalReply = raw; + const trimmedRaw = String(raw).trim(); + if (trimmedRaw.startsWith('{') || trimmedRaw.startsWith('[')) { + jsonRetryNote = '上一轮模型输出不是合法 JSON(疑似截断),请重新输出完整合法的纯 JSON,不要包含任何额外文字'; + continue; + } + // 不是 JSON → 当作文本回复 + finalReply = trimmedRaw; break; } diff --git a/app/service/inbox/functions.js b/app/service/inbox/functions.js index d10c39c..a577cbd 100644 --- a/app/service/inbox/functions.js +++ b/app/service/inbox/functions.js @@ -1193,6 +1193,100 @@ class InboxFunctionsService extends Service { }, }); + this.register('queryReturn', { + description: '查询退回包裹明细(查退回)。用户发送"查退回+运单号"时调用。传入运单号,查询退回收到/退回拆包/未退回登记状态:已拆包返回拆包明细与录像地址模板消息,未退回则自动登记到退回查询表。注意:仅查询退回状态使用,与 interceptWaybill 拦截、queryOrder 订单查询不同', + weight: 90, + keywords: [ '查退回', '查退件', '退回查询', '退回明细', '查拆包', '退件查询', '退回进度' ], + params: { + waybill_code: { type: 'string', required: true, description: '退回包裹运单号,如"查退回 465570943491370"中的465570943491370' }, + }, + groups: [ GROUP.COMMON ], + handler: async (params = {}) => { + const { ctx } = this; + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + const storeId = Number(ctx.inboxContext?.store_id || 0); + + let raw = String(params.waybill_code || '').trim(); + if (!raw) return { success: false, error: '请提供退回包裹运单号' }; + + // 兼容把"查退回 123456"整体传入的情况 + const match = raw.match(/查退[回件]\s*[::]?\s*(.+)$/); + if (match) raw = String(match[1]).trim(); + // 去掉空白与常见中文标点,保留运单号本体(字母/数字/横线等) + const waybill = raw.replace(/[\s,,。;;]+/g, ''); + if (!waybill) return { success: false, error: '未解析到有效运单号' }; + if (!warehouseId) return { success: false, error: '无法获取仓库信息' }; + + try { + const result = await ctx.service.systems.returnUnpack.queryByWaybill({ + waybill_code: waybill, + warehouse_id: warehouseId, + store_id: storeId, + }); + + const warehouseLabel = result.warehouse_name || '仓库'; + let message = ''; + + if (result.status === 'unpacked') { + const unpack = result.unpack || {}; + const details = result.details || []; + const videos = result.videos || []; + const orderInfo = result.order_info || {}; + + const lines = []; + lines.push(`${waybill}已在已退件中登记,登记信息为:`); + lines.push(''); + lines.push(`运单号:${waybill}`); + lines.push(`是否原单:${unpack.order_express_id ? '是' : '否'}`); + lines.push(`交易单号:${orderInfo.trade_no || ''}`); + lines.push(`快递:${orderInfo.express || ''}`); + lines.push(`店铺名称:${orderInfo.shop_name || ''}`); + lines.push(`${warehouseLabel}收到且已拆包,拆包明细为:`); + if (details.length > 0) { + for (const detail of details) { + lines.push(`商品名称:${detail.item_name || ''}`); + lines.push(`条码:${detail.barcode || ''}`); + lines.push(`数量:${detail.quantity || 0}`); + lines.push(`是否破损:${detail.product_status === 'damaged' ? '是' : '否'}`); + } + } else { + lines.push('暂无拆包明细,拆包完成后可再次查询'); + } + lines.push(''); + lines.push('退件录像地址为:'); + if (videos.length > 0) { + for (const video of videos) { + if (video.video_url) lines.push(String(video.video_url)); + } + } else { + lines.push('暂无'); + } + lines.push('拆包视频保存会有延迟,可以在稍后发送:查退回+运单号,查询'); + message = lines.join('\n'); + } else if (result.status === 'received') { + message = `包裹${waybill}已收到未拆包,拆包登记后,将自动发送通知拆包信息`; + } else if (result.status === 'not_returned') { + message = `${waybill}尚未退回仓库,已在未退回表中登记成功,等待包裹退件登记后,将自动发送通知包裹信息`; + } else { + message = `未查询到运单号${waybill}的退回信息,请核实单号后重试`; + } + + return { + success: true, + data: { + status: result.status, + waybill_code: waybill, + message, + direct_reply: true, + }, + }; + } catch (error) { + ctx.logger.error(`[inbox functions] 退回查询失败: ${error.message}`); + return { success: false, error: `退回查询失败: ${error.message}` }; + } + }, + }); + this.register('cancelIntercept', { description: '取消拦截运单(支持批量)。当用户要求"取消拦截/撤销拦截/不拦截了"时调用。先查已有售后工单,有则追加取消记录,无则按拦截规则创建工单。同时设置订单和运单拦截状态并通知快递群', weight: 94, diff --git a/app/service/systemMethods/returnUnpack.js b/app/service/systemMethods/returnUnpack.js index 39884be..e8d6a0e 100644 --- a/app/service/systemMethods/returnUnpack.js +++ b/app/service/systemMethods/returnUnpack.js @@ -66,15 +66,16 @@ class ReturnUnpackMethodService extends MainService { * @param {Object} data 请求体。 * @param {number} data.id 拆包单ID。 * @param {number} [data.stock_id] 系统商品ID(wms_stock_warehouse.id)。 + * @param {string} [data.barcode] 扫描条码(stock_id 为空时按条码反查商品)。 * @param {number} [data.quantity] 数量。 * @param {string} [data.product_status] 产品状态 normal/damaged。 * @param {string} [data.remark] 备注。 * @return {Promise} 统一 success 包装。 */ async addDetail(data = {}) { - const { id, stock_id, quantity, product_status, remark } = data; + const { id, stock_id, barcode, quantity, product_status, remark } = data; return this._call( - () => this.service.systems.returnUnpack.addDetail({ id, stock_id, quantity, product_status, remark }), + () => this.service.systems.returnUnpack.addDetail({ id, stock_id, barcode, quantity, product_status, remark }), '录明细失败' ); } diff --git a/app/service/systems/return_unpack.js b/app/service/systems/return_unpack.js index 413046c..4a5bd96 100644 --- a/app/service/systems/return_unpack.js +++ b/app/service/systems/return_unpack.js @@ -68,16 +68,18 @@ class ReturnUnpackService extends Service { let orderExpressId = null; let orderId = null; let storeId = null; + let sourceOrderCodes = null; try { const orderExpress = await ctx.model.OrderExpress.findOne({ where: { waybill_code: waybillCode }, - attributes: [ 'id', 'order_id', 'store_id' ], + attributes: [ 'id', 'order_id', 'store_id', 'source_order_codes' ], raw: true, }); if (orderExpress) { orderExpressId = orderExpress.id; orderId = orderExpress.order_id; storeId = orderExpress.store_id; + sourceOrderCodes = orderExpress.source_order_codes || null; } } catch (err) { ctx.logger.warn(`[returnUnpack.create] 反查原运单失败: ${err.message}`); @@ -132,6 +134,8 @@ class ReturnUnpackService extends Service { order_express_id: orderExpressId, order_id: orderId, store_id: storeId, + source_order_codes: sourceOrderCodes, + shop_name: storeRemark || null, camera_ids: normalizedCameraIds, remark: remark ? String(remark).slice(0, 500) : null, }; @@ -184,22 +188,26 @@ class ReturnUnpackService extends Service { /** * 录明细:以拆包单ID为依据录入一条明细(识别到系统商品时回填快照)。 + * 仅以 stock_id 识别商品;不指定 stock_id 时一律标注未知商品, + * 不做条码自动匹配(同一商品可能存在多条条码记录/多个 stock_id,自动匹配易误配)。 * * @param {Object} params 明细参数。 * @param {number} params.id 拆包单ID。 - * @param {number} [params.stock_id] 系统商品ID(wms_stock_warehouse.id),为空即无关联货物。 + * @param {number} [params.stock_id] 系统商品ID(wms_stock_warehouse.id),为空即无关联货物(商品名称标注未知商品)。 + * @param {string} [params.barcode] 扫描条码(仅作记录,不参与商品匹配)。 * @param {number} [params.quantity] 数量,默认 1。 * @param {string} [params.product_status] 产品状态 normal/damaged,默认 normal。 * @param {string} [params.remark] 备注。 * @return {Promise} 明细ID + 明细行 + 主表最新汇总。 */ - async addDetail({ id, stock_id, quantity, product_status, remark }) { + async addDetail({ id, stock_id, barcode, quantity, product_status, remark }) { const { ctx } = this; const unpack = await this._findByIdChecked(id); this._assertUnpacking(unpack); const normalizedStockId = stock_id ? Number(stock_id) : null; + const normalizedBarcode = barcode ? String(barcode).trim().slice(0, 100) : null; const normalizedQuantity = Math.max(1, parseInt(quantity) || 1); const normalizedStatus = product_status === 'damaged' ? 'damaged' : 'normal'; @@ -239,19 +247,25 @@ class ReturnUnpackService extends Service { item_type: stock.item_type || '', }); - // 主表货主为空时回填(首个识别商品确定货主) + // 主表货主为空时回填(首个识别商品确定货主),并同步回填自定义店铺名称快照 if (currentStoreId === 0 && stockStoreId > 0) { + const backfillFields = { store_id: stockStoreId }; + const shopName = await this._resolveStoreRemark(stockStoreId, unpack.warehouse_id); + if (shopName) backfillFields.shop_name = shopName; await ctx.model.ReturnUnpack.update( - { store_id: stockStoreId }, + backfillFields, { where: { id: unpack.id } } ); } + } else { + // 未指定系统商品:一律标注未知商品,不做条码自动匹配(同条码可能对应多个 stock_id,易误配) + itemName = '未知商品'; } const created = await ctx.model.ReturnUnpackDetail.create({ unpack_id: unpack.id, warehouse_id: unpack.warehouse_id, - barcode: null, + barcode: normalizedBarcode, stock_id: normalizedStockId, is_recognized: isRecognized, item_code: itemCode, @@ -599,6 +613,344 @@ class ReturnUnpackService extends Service { }; } + /** + * 查询退回明细(按运单号,跨退回相关表汇总)。 + * 依次查询:拆包主表+明细+视频(已拆包)→ 退回收到表(已收到未拆包)→ 退回查询登记表(未退回)。 + * 未退回且无登记记录时自动登记到 wms_return_query_log,等待拆包后处理。 + * + * @param {Object} params 查询参数。 + * @param {string} params.waybill_code 退回包裹运单号(必填)。 + * @param {number} params.warehouse_id 仓库ID(必填)。 + * @param {number} [params.store_id] 货主ID(可选,用于货主隔离与未退回登记)。 + * @return {Promise} { status, waybill_code, warehouse_name, ... }。 + * status:unpacked(已拆包)/ received(已收到未拆包)/ not_returned(未退回)/ hidden(跨货主不可见)。 + */ + async queryByWaybill({ waybill_code, warehouse_id, store_id } = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + const waybillCode = String(waybill_code || '').trim(); + if (!waybillCode) { + throw this.createBusinessError('waybill_code 不能为空', 400); + } + + const warehouseId = Number(warehouse_id || 0); + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + throw this.createBusinessError('缺少仓库上下文', 400); + } + const storeId = Number(store_id || 0); + + const warehouseName = await this._resolveWarehouseName(warehouseId); + + // 1. 已拆包:同一运单号取最新一条有效拆包单(跳过已作废) + const unpack = await ctx.model.ReturnUnpack.findOne({ + where: { + warehouse_id: warehouseId, + waybill_code: waybillCode, + status: { [Op.ne]: 'cancelled' }, + }, + order: [[ 'created_at', 'DESC' ], [ 'id', 'DESC' ]], + raw: true, + }); + + if (unpack) { + // 货主隔离:限定货主查询且拆包单已归属其他货主 → 不暴露数据 + if (storeId > 0 && Number(unpack.store_id || 0) > 0 && Number(unpack.store_id) !== storeId) { + return { status: 'hidden', waybill_code: waybillCode, warehouse_name: warehouseName }; + } + + const details = await ctx.model.ReturnUnpackDetail.findAll({ + where: { unpack_id: unpack.id }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + const videos = await ctx.model.ReturnUnpackVideo.findAll({ + where: { unpack_id: unpack.id, deleted_at: null }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + let received = null; + if (unpack.return_received_id) { + received = await ctx.model.ReturnReceived.findOne({ + where: { id: unpack.return_received_id }, + raw: true, + }); + } + + const orderInfo = await this._resolveReturnOrderInfo({ + order_express_id: unpack.order_express_id, + order_id: unpack.order_id, + warehouse_id: warehouseId, + store_id: unpack.store_id, + source_order_codes: unpack.source_order_codes, + shop_name: unpack.shop_name, + }); + + return { + status: 'unpacked', + waybill_code: waybillCode, + warehouse_name: warehouseName, + unpack, + details, + videos, + received, + order_info: orderInfo, + }; + } + + // 2. 已收到未拆包:退回收到表登记过 + const received = await ctx.model.ReturnReceived.findOne({ + where: { warehouse_id: warehouseId, waybill_code: waybillCode }, + order: [[ 'created_at', 'DESC' ], [ 'id', 'DESC' ]], + raw: true, + }); + + if (received) { + if (storeId > 0 && Number(received.store_id || 0) > 0 && Number(received.store_id) !== storeId) { + return { status: 'hidden', waybill_code: waybillCode, warehouse_name: warehouseName }; + } + + // 货主确定优先级:入参 store_id > 退回登记表 store_id > 原运单反查 store_id > 0(未知) + let resolvedStoreId = storeId || Number(received.store_id || 0); + if (!resolvedStoreId) { + resolvedStoreId = await this._resolveStoreIdByWaybill(waybillCode, warehouseId); + } + + // 退回登记表货主为空 → 回填变更(后续拆包/通知依赖货主) + if (Number(received.store_id || 0) <= 0 && resolvedStoreId > 0) { + try { + await ctx.model.ReturnReceived.update( + { store_id: resolvedStoreId }, + { where: { id: received.id } } + ); + received.store_id = resolvedStoreId; + ctx.logger.info( + `[returnUnpack.queryByWaybill] 退回登记表回填货主: id=${received.id} store_id=${resolvedStoreId}` + ); + } catch (err) { + ctx.logger.warn(`[returnUnpack.queryByWaybill] 回填退回登记表货主失败: ${err.message}`); + } + } + + // 照常登记退回查询记录(幂等:已存在则不重复创建) + let queryLog = await ctx.model.ReturnQueryLog.findOne({ + where: { warehouse_id: warehouseId, waybill_code: waybillCode }, + order: [[ 'id', 'DESC' ]], + raw: true, + }); + if (!queryLog) { + try { + const created = await ctx.model.ReturnQueryLog.create({ + warehouse_id: warehouseId, + store_id: resolvedStoreId || 0, + waybill_code: waybillCode, + remark: '站内信查询退回自动登记(已收到未拆包)', + is_notified: 0, + is_back: 0, + }); + queryLog = created && typeof created.toJSON === 'function' ? created.toJSON() : created; + } catch (err) { + ctx.logger.warn(`[returnUnpack.queryByWaybill] 已收到未拆包登记退回查询记录失败: ${err.message}`); + } + } + + const orderInfo = await this._resolveReturnOrderInfo({ + order_express_id: received.order_express_id, + order_id: received.order_id, + warehouse_id: warehouseId, + store_id: resolvedStoreId || Number(received.store_id || 0), + }); + + return { + status: 'received', + waybill_code: waybillCode, + warehouse_name: warehouseName, + received, + query_log: queryLog, + order_info: orderInfo, + }; + } + + // 3. 未退回:查询退回查询登记表,无登记则自动登记(等待拆包后处理) + const queryLog = await ctx.model.ReturnQueryLog.findOne({ + where: { warehouse_id: warehouseId, waybill_code: waybillCode }, + order: [[ 'id', 'DESC' ]], + raw: true, + }); + + if (queryLog) { + return { + status: 'not_returned', + waybill_code: waybillCode, + warehouse_name: warehouseName, + query_log: queryLog, + registered_now: false, + }; + } + + // 货主确定优先级:入参 store_id > 原运单反查 store_id > 0(未知货主) + let regStoreId = storeId; + if (!regStoreId) { + regStoreId = await this._resolveStoreIdByWaybill(waybillCode, warehouseId); + } + + let createdRow = null; + try { + const created = await ctx.model.ReturnQueryLog.create({ + warehouse_id: warehouseId, + store_id: regStoreId || 0, + waybill_code: waybillCode, + remark: '站内信查询退回自动登记', + is_notified: 0, + is_back: 0, + }); + createdRow = created && typeof created.toJSON === 'function' ? created.toJSON() : created; + } catch (err) { + // 并发/异常兜底:登记失败不影响查询结论,回查已有登记 + ctx.logger.warn(`[returnUnpack.queryByWaybill] 自动登记退回查询记录失败: ${err.message}`); + try { + createdRow = await ctx.model.ReturnQueryLog.findOne({ + where: { warehouse_id: warehouseId, waybill_code: waybillCode }, + order: [[ 'id', 'DESC' ]], + raw: true, + }); + } catch (e) { + ctx.logger.warn(`[returnUnpack.queryByWaybill] 回查退回查询记录失败: ${e.message}`); + } + } + + return { + status: 'not_returned', + waybill_code: waybillCode, + warehouse_name: warehouseName, + query_log: createdRow, + registered_now: Boolean(createdRow), + }; + } + + /** + * 解析仓库名称(wms_store.company_name)。 + * + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 仓库名称,查询失败返回空字符串。 + */ + async _resolveWarehouseName(warehouseId) { + const { ctx } = this; + try { + const store = await ctx.model.Store.findOne({ + where: { id: warehouseId }, + attributes: [ 'company_name' ], + raw: true, + }); + return store && store.company_name ? String(store.company_name) : ''; + } catch (err) { + ctx.logger.warn(`[returnUnpack._resolveWarehouseName] 查询仓库名称失败: ${err.message}`); + return ''; + } + } + + /** + * 按运单号反查货主(wms_order_express)。 + * + * @param {string} waybillCode 运单号。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 货主ID,未命中返回 0。 + */ + async _resolveStoreIdByWaybill(waybillCode, warehouseId) { + const { ctx } = this; + try { + const express = await ctx.model.OrderExpress.findOne({ + where: { waybill_code: waybillCode, warehouse_id: warehouseId }, + attributes: [ 'store_id' ], + raw: true, + }); + return express && Number(express.store_id) > 0 ? Number(express.store_id) : 0; + } catch (err) { + ctx.logger.warn(`[returnUnpack._resolveStoreIdByWaybill] 反查货主失败: ${err.message}`); + return 0; + } + } + + /** + * 解析退回包裹关联的原单信息:平台交易单号 / 快递 / 自定义店铺名称。 + * 优先取主表快照(source_order_codes / shop_name),为空时实时兜底: + * 交易单号取原运单/原订单的 source_order_codes,店铺名称取货主合约 store_remask。 + * + * @param {Object} params 关联参数。 + * @param {number} [params.order_express_id] 原运单ID。 + * @param {number} [params.order_id] 原订单ID。 + * @param {number} [params.warehouse_id] 仓库ID(分表查询/合约查询用)。 + * @param {number} [params.store_id] 货主ID(自定义店铺名称查询用)。 + * @param {string} [params.source_order_codes] 平台交易单号快照。 + * @param {string} [params.shop_name] 店铺名称快照。 + * @return {Promise<{trade_no: string, express: string, shop_name: string}>} 原单信息。 + */ + async _resolveReturnOrderInfo({ order_express_id, order_id, warehouse_id, store_id, source_order_codes, shop_name } = {}) { + const { ctx } = this; + const info = { + trade_no: String(source_order_codes || '').trim(), + express: '', + shop_name: String(shop_name || '').trim(), + }; + + if (order_express_id) { + try { + const express = await ctx.model.OrderExpress.findOne({ + where: { id: order_express_id }, + attributes: [ 'logistics_name', 'source_order_codes' ], + raw: true, + }); + if (express) { + if (express.logistics_name) info.express = String(express.logistics_name); + if (!info.trade_no && express.source_order_codes) { + info.trade_no = String(express.source_order_codes); + } + } + } catch (err) { + ctx.logger.warn(`[returnUnpack._resolveReturnOrderInfo] 查询原运单失败: ${err.message}`); + } + } + + if (order_id && !info.trade_no) { + try { + let order = null; + try { + order = await ctx.model.OrderDelivery.findOne({ + where: { id: order_id }, + raw: true, + }); + } catch (err) { + // 主表查询失败,继续走工厂分表兜底 + } + if (!order && ctx.model.OrderDeliveryFactory) { + try { + const factoryModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouse_id); + if (factoryModel) { + order = await factoryModel.findOne({ where: { id: order_id }, raw: true }); + } + } catch (err) { + // 分表查询失败忽略 + } + } + if (order) { + info.trade_no = String(order.source_order_codes || order.source_platform_code || ''); + if (!info.express && order.logistics_name) info.express = String(order.logistics_name); + } + } catch (err) { + ctx.logger.warn(`[returnUnpack._resolveReturnOrderInfo] 查询原订单失败: ${err.message}`); + } + } + + // 自定义店铺名称兜底:货主合约 store_remask + if (!info.shop_name && store_id) { + info.shop_name = await this._resolveStoreRemark(store_id, warehouse_id); + } + + return info; + } + /** * 删除拆包单(后台管理,不限制状态):事务内物理删除主表 + 明细,同步软删视频。 * diff --git a/database/migrations/20260813170000-add-return-unpack-order-info.js b/database/migrations/20260813170000-add-return-unpack-order-info.js new file mode 100644 index 0000000..f0f5a9c --- /dev/null +++ b/database/migrations/20260813170000-add-return-unpack-order-info.js @@ -0,0 +1,36 @@ +'use strict'; + +/** + * wms_return_unpack 主表补充订单信息快照字段: + * - source_order_codes:平台交易单号(原单退回时回填,来源 wms_order_express.source_order_codes) + * - shop_name:店铺名称(货主自定义店铺名称快照,来源 wms_store_warehouse.store_remask) + * + * 用途:退回查询(查退回模板消息)直接取主表快照,避免依赖原运单/订单表实时关联。 + */ + +const TABLE_NAME = 'wms_return_unpack'; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + const { STRING } = Sequelize; + await queryInterface.addColumn(TABLE_NAME, 'source_order_codes', { + type: STRING(500), + allowNull: true, + comment: '平台交易单号快照(原单退回时回填)', + after: 'store_id', + }); + await queryInterface.addColumn(TABLE_NAME, 'shop_name', { + type: STRING(50), + allowNull: true, + comment: '店铺名称快照(货主自定义店铺名称 store_remask)', + after: 'source_order_codes', + }); + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + await queryInterface.removeColumn(TABLE_NAME, 'shop_name'); + await queryInterface.removeColumn(TABLE_NAME, 'source_order_codes'); + }, +}; diff --git a/methods/changes/system.json b/methods/changes/system.json index 9ef0b36..6adaad4 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -5916,5 +5916,53 @@ "仅文档同步,其余接口与模块不动" ], "module": "returnUnpack" + }, + { + "version": "2026.08.13-returnUnpack.addDetailBarcode", + "date": "2026-08-13", + "type": "updated", + "summary": "returnUnpack.addDetail 新增 barcode 入参(可选):stock_id 为空时按条码反查本仓库商品(wms_stock_barcodes)再走识别流程,反查不到按无关联货物处理;条码同步写入明细作记录(此前固定写 null)。复用基础模块条码索引,支持 PDA 扫描条码录明细。", + "methods": [ + "returnUnpack.addDetail" + ], + "notes": [ + "params 新增 barcode(string,可选,最长100,body)", + "识别优先级:stock_id > barcode 反查 > 无关联货物", + "明细 barcode 字段由固定 null 改为记录扫描条码", + "business 层按 warehouse_id+barcode 匹配 wms_stock_barcodes(uk_barcode 全局唯一,加仓库过滤防跨仓串货)" + ], + "module": "returnUnpack" + }, + { + "version": "2026.08.13-returnUnpack.addDetailBarcodeV2", + "date": "2026-08-13", + "type": "updated", + "summary": "returnUnpack.addDetail 识别策略调整:未指定 stock_id 时一律标注未知商品(item_name=未知商品),移除按条码自动反查 stock_id 的逻辑(同一条码可能对应多个 stock_id,自动匹配易误配);barcode 仍写入明细作记录。", + "methods": [ + "returnUnpack.addDetail" + ], + "notes": [ + "移除 barcode 反查 wms_stock_barcodes 自动识别逻辑(v1 新增,本次回退)", + "未指定 stock_id:is_recognized=0,item_name=未知商品(此前为 null)", + "barcode 参数保留:仅作记录写入明细,不参与商品匹配", + "docs 同步:addDetail description / stock_id / barcode 参数说明更新" + ], + "module": "returnUnpack" + }, + { + "version": "2026.08.13-returnUnpack.orderInfoSnapshot", + "date": "2026-08-13", + "type": "updated", + "summary": "wms_return_unpack 主表新增订单信息快照字段 source_order_codes(平台交易单号)/ shop_name(店铺名称=货主自定义店铺名称 store_remask),returnUnpack.create 原单退回时回填;退回查询(查退回)优先取主表快照返回交易单号与自定义店铺。", + "methods": [ + "returnUnpack.create" + ], + "notes": [ + "迁移 20260813170000-add-return-unpack-order-info.js:addColumn source_order_codes VARCHAR(500) + shop_name VARCHAR(50)", + "create 原单退回:source_order_codes 取 wms_order_express.source_order_codes,shop_name 取 store_remask", + "addDetail 首个识别商品回填主表 store_id 时同步回填 shop_name", + "退回查询 _resolveReturnOrderInfo 优先主表快照,空时实时兜底(交易单号→原运单/原订单,店铺→store_remask)" + ], + "module": "returnUnpack" } ] diff --git a/methods/system.json b/methods/system.json index 36faa19..e92a56a 100644 --- a/methods/system.json +++ b/methods/system.json @@ -35031,7 +35031,7 @@ "list": [ { "method": "returnUnpack.create", - "description": "开拆包单(明细不在此提交,由 returnUnpack.addDetail 逐件录入)。用 waybill_code 反查 wms_order_express 判定是否原单退回,命中则回填 order_express_id/order_id/store_id 并返回原订单详情;未命中原单时按 warehouse_id+waybill_code 从 wms_return_query_log 反查货主(限最近 3 个月内登记)。拆包单号规则 RP+YYYYMMDD+6位序号。仓库隔离:warehouse_id 由服务端注入 ctx.user.store_id,禁止前端传入。", + "description": "开拆包单(明细不在此提交,由 returnUnpack.addDetail 逐件录入)。用 waybill_code 反查 wms_order_express 判定是否原单退回,命中则回填 order_express_id/order_id/store_id 及订单信息快照(source_order_codes 平台交易单号 / shop_name 店铺名称=货主自定义店铺名称 store_remask)并返回原订单详情;未命中原单时按 warehouse_id+waybill_code 从 wms_return_query_log 反查货主(限最近 3 个月内登记)。拆包单号规则 RP+YYYYMMDD+6位序号。仓库隔离:warehouse_id 由服务端注入 ctx.user.store_id,禁止前端传入。", "isNeedAuth": true, "isNeedLogin": true, "headers": [], @@ -35076,7 +35076,7 @@ "name": "record", "type": "object", "required": true, - "description": "拆包单主表记录(含 unpack_no、waybill_code、unpack_date、start_time、unpacker_id/unpacker_name、status、detail_status、camera_ids 数组、回填的 order_express_id/order_id/store_id 及 is_original_return 派生字段)" + "description": "拆包单主表记录(含 unpack_no、waybill_code、unpack_date、start_time、unpacker_id/unpacker_name、status、detail_status、camera_ids 数组、回填的 order_express_id/order_id/store_id/source_order_codes/shop_name 快照及 is_original_return 派生字段)" }, { "name": "is_original_return", @@ -35126,7 +35126,7 @@ }, { "method": "returnUnpack.addDetail", - "description": "录明细:以拆包单ID为依据录入一条明细。主单非终态(unpacking)校验;stock_id 有值时校验货主归属并回填识别快照(is_recognized=1 + item_code/item_name/spec/product_snapshot),为空即无关联货物(is_recognized=0);主表 store_id 为空时以首个识别商品回填主表货主。写明细后重算主表 total_items/total_quantity/detail_status。仓库隔离校验(仅本仓库拆包单)。", + "description": "录明细:以拆包单ID为依据录入一条明细。主单非终态(unpacking)校验;stock_id 有值时校验货主归属并回填识别快照(is_recognized=1 + item_code/item_name/spec/product_snapshot),未指定 stock_id 时一律标注未知商品(is_recognized=0,item_name=未知商品),不做条码自动匹配(同一条码可能对应多个 stock_id,自动匹配易误配),barcode 仅作记录;主表 store_id 为空时以首个识别商品回填主表货主。写明细后重算主表 total_items/total_quantity/detail_status。仓库隔离校验(仅本仓库拆包单)。", "isNeedAuth": true, "isNeedLogin": true, "headers": [], @@ -35143,7 +35143,14 @@ "type": "integer", "required": false, "source": "body", - "description": "系统商品ID(wms_stock_warehouse.id),为空即无关联货物" + "description": "系统商品ID(wms_stock_warehouse.id),为空即无关联货物(商品名称标注未知商品)" + }, + { + "name": "barcode", + "type": "string", + "required": false, + "source": "body", + "description": "扫描条码(最长100字符,仅作记录,不参与商品匹配)" }, { "name": "quantity", @@ -35178,7 +35185,7 @@ "name": "detail", "type": "object", "required": true, - "description": "新增的明细行(含 is_recognized/item_code/item_name/spec/product_snapshot 等识别结果快照)" + "description": "新增的明细行(含 barcode/is_recognized/item_code/item_name(未知商品)/spec/product_snapshot 等)" }, { "name": "total_items", diff --git a/script/debug-inbox-push.cjs b/script/debug-inbox-push.cjs new file mode 100644 index 0000000..be486f9 --- /dev/null +++ b/script/debug-inbox-push.cjs @@ -0,0 +1,243 @@ +'use strict'; + +/** + * 站内信消息推送调试脚本(模拟 IM 桥向仓库推送入站消息,走真实验签链路)。 + * + * 用法: + * node script/debug-inbox-push.cjs + * 默认: 向 test-stock-group 推送「查退回 <随机不存在运单号>」 + * node script/debug-inbox-push.cjs --content "查退回 888888888888888" + * node script/debug-inbox-push.cjs --waybill 888888888888888 --groupId test-stock-group --userName 测试用户 + * + * 行为: + * 1. 按 app/lib/api_sign.js 规则签名,POST /warehouse?method=inbox.push + * 2. 等待 AI 异步处理(默认 15s) + * 3. 回查本地库: 入站消息 / AI 思考过程 / 回信内容 / wms_return_query_log 登记 + */ + +const crypto = require('crypto'); +const http = require('http'); +const mysql = require('mysql2/promise'); + +// ========================== 稳定序列化(与 app/lib/api_sign.js 一致) ========================== + +function isPlainObject(value) { + return Object.prototype.toString.call(value) === '[object Object]'; +} + +function stableStringify(value) { + if (value === undefined) return ''; + if (value === null || typeof value !== 'object') return JSON.stringify(value); + if (Array.isArray(value)) { + return `[${value.map(item => stableStringify(item)).join(',')}]`; + } + if (!isPlainObject(value)) return JSON.stringify(value); + const keys = Object.keys(value).sort(); + return `{${keys.map(key => `${JSON.stringify(key)}:${stableStringify(value[key])}`).join(',')}}`; +} + +function md5(str) { + return crypto.createHash('md5').update(str, 'utf8').digest('hex').toLowerCase(); +} + +function buildSign(query, body, secret) { + const ignoreSet = new Set([ 'sign', 'signature' ]); + const keys = Object.keys(query) + .filter(key => !ignoreSet.has(String(key).toLowerCase())) + .filter(key => query[key] !== undefined) + .sort(); + const canonicalQuery = keys.map(key => { + const v = query[key]; + if (v === undefined || v === null) return `${key}=`; + if (typeof v === 'object') return `${key}=${stableStringify(v)}`; + return `${key}=${String(v)}`; + }).join('&'); + const bodySign = md5(stableStringify(body)); + const signText = `${canonicalQuery}${secret}${bodySign}`; + return { canonicalQuery, bodySign, sign: md5(signText) }; +} + +// ========================== 参数解析 ========================== + +const ARGS = {}; +for (let i = 2; i < process.argv.length; i++) { + const arg = process.argv[i]; + const match = arg.match(/^--([^=]+)=(.*)$/); + if (match) { + ARGS[match[1]] = match[2]; + } else if (arg.startsWith('--')) { + ARGS[arg.slice(2)] = process.argv[i + 1]; + i++; + } +} + +const CONFIG = { + baseUrl: ARGS.baseUrl || 'http://127.0.0.1:6060', + appKey: ARGS.appKey || 'APP2025011514315678', + appSecret: ARGS.appSecret || 'sec_xyz789uvw012abc345def678ghi901jkl234mno567pqr890', + groupId: ARGS.groupId || 'test-stock-group', + groupName: ARGS.groupName || '库存查询测试群', + userName: ARGS.userName || '测试用户', + waitMs: Number(ARGS.waitMs || 15000), + waybill: ARGS.waybill || `${Date.now()}99`, +}; + +if (ARGS.content) { + CONFIG.content = ARGS.content; +} else { + CONFIG.content = `查退回 ${CONFIG.waybill}`; +} + +// ========================== HTTP 推送 ========================== + +function postWarehouse(method, body) { + const query = { + method, + v: '1.0', + timestamp: Math.floor(Date.now() / 1000), + app_key: CONFIG.appKey, + }; + const { sign } = buildSign(query, body, CONFIG.appSecret); + query.sign = sign; + + const qs = Object.entries(query) + .map(([ k, v ]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`) + .join('&'); + const bodyStr = JSON.stringify(body); + const url = `${CONFIG.baseUrl}/warehouse?${qs}`; + + return new Promise((resolve, reject) => { + const req = http.request(url, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Content-Length': Buffer.byteLength(bodyStr), + }, + timeout: 20000, + }, res => { + let data = ''; + res.on('data', chunk => (data += chunk)); + res.on('end', () => { + try { resolve({ status: res.statusCode, body: JSON.parse(data) }); } catch (e) { resolve({ status: res.statusCode, body: data }); } + }); + }); + req.on('error', reject); + req.on('timeout', () => { req.destroy(); reject(new Error('Request timeout')); }); + req.write(bodyStr); + req.end(); + }); +} + +function sleep(ms) { + return new Promise(resolve => setTimeout(resolve, ms)); +} + +// ========================== 本地库回查 ========================== + +async function queryDb(sql) { + const conn = await mysql.createConnection({ + host: '127.0.0.1', + port: 3307, + user: 'wms', + password: 'dspxmRwRdRbWtbm7', + database: 'wms', + }); + try { + const [ rows ] = await conn.query(sql); + return rows; + } finally { + await conn.end(); + } +} + +// ========================== 主流程 ========================== + +(async () => { + const requestId = `debug-return-${Date.now()}`; + console.log('========== 站内信模拟推送 =========='); + console.log(` 群: ${CONFIG.groupId} (${CONFIG.groupName})`); + console.log(` 用户: ${CONFIG.userName}`); + console.log(` 内容: ${CONFIG.content}`); + console.log(` requestId: ${requestId}`); + + const r = await postWarehouse('inbox.push', { + requestId, + content: CONFIG.content, + groupId: CONFIG.groupId, + groupName: CONFIG.groupName, + userId: 'debug_user', + userName: CONFIG.userName, + targetType: 'im', + }); + + console.log(` HTTP ${r.status}: ${JSON.stringify(r.body).slice(0, 300)}`); + if (r.status !== 200 || (r.body && r.body.ok === false)) { + console.error('推送失败,请检查签名与仓库应用配置'); + process.exit(1); + } + + console.log(`\n等待 AI 异步处理 ${CONFIG.waitMs / 1000}s ...`); + await sleep(CONFIG.waitMs); + + const extId = `api:${CONFIG.appKey}:${requestId}`; + + // 1. 入站消息 + AI 思考 + const inbound = await queryDb( + `SELECT id, direction, content, ai_thoughts, push_status, created_at + FROM wms_inbox_message WHERE ext_id='${extId}' ORDER BY id DESC LIMIT 1` + ); + console.log('\n[入站消息]'); + if (inbound.length === 0) { + console.log(' 未找到(消息可能尚未入库)'); + } else { + console.log(` id=${inbound[0].id} push_status=${inbound[0].push_status}`); + console.log(` content: ${inbound[0].content}`); + const thoughts = inbound[0].ai_thoughts; + if (thoughts && typeof thoughts === 'string') { + try { + const parsed = JSON.parse(thoughts); + console.log(` ai_thoughts: ${JSON.stringify(parsed).slice(0, 400)}`); + } catch (e) { + console.log(` ai_thoughts(raw): ${String(thoughts).slice(0, 400)}`); + } + } else { + console.log(' ai_thoughts: 无'); + } + } + + // 2. 回信内容 + const outbound = await queryDb( + `SELECT id, direction, content, created_at + FROM wms_inbox_message + WHERE direction='outbound' AND group_id='${CONFIG.groupId}' + ORDER BY id DESC LIMIT 1` + ); + console.log('\n[最新回信]'); + if (outbound.length === 0) { + console.log(' 无回信'); + } else { + console.log(` id=${outbound[0].id} created_at=${outbound[0].created_at}`); + console.log(` content:\n${outbound[0].content}`); + } + + // 3. 退回查询登记 + const waybill = CONFIG.waybill; + const queryLog = await queryDb( + `SELECT id, warehouse_id, store_id, waybill_code, remark, is_notified, is_back, created_at + FROM wms_return_query_log WHERE waybill_code='${waybill}' ORDER BY id DESC LIMIT 3` + ); + console.log('\n[wms_return_query_log 登记]'); + if (queryLog.length === 0) { + console.log(' 无登记'); + } else { + queryLog.forEach(row => { + console.log(` id=${row.id} store_id=${row.store_id} is_back=${row.is_back} is_notified=${row.is_notified} remark=${row.remark} ${row.created_at}`); + }); + } + + console.log('\n完成。测试记录按需保留,无需删除。'); + process.exit(0); +})().catch(e => { + console.error('异常:', e.message); + process.exit(1); +}); From 98bc0889292dff0b7e775f6836644461d8653056 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Fri, 14 Aug 2026 15:29:59 +0800 Subject: [PATCH 205/550] =?UTF-8?q?feat:=20=E4=BB=93=E5=BA=93=E9=85=8D?= =?UTF-8?q?=E7=BD=AE=E6=96=B0=E5=A2=9E=E6=94=B6=E8=B4=A7=E5=9C=B0=E5=9D=80?= =?UTF-8?q?=20receiver=5Faddress=EF=BC=8Cinbox=20=E5=94=AE=E5=90=8E?= =?UTF-8?q?=E7=BE=A4=E6=96=B0=E5=A2=9E=E5=B7=A5=E5=8D=95=E7=99=BB=E8=AE=B0?= =?UTF-8?q?/=E6=94=B9=E5=9C=B0=E5=9D=80/=E6=A0=B8=E5=AE=9E=E7=AD=BE?= =?UTF-8?q?=E6=94=B6/=E6=94=B9=E5=BF=AB=E9=80=92/=E6=9F=A5=E8=AF=A2?= =?UTF-8?q?=E4=BB=93=E5=BA=93=E5=9C=B0=E5=9D=80=E5=87=BD=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/model/store.js | 1 + app/service/inbox/ai.js | 9 +- app/service/inbox/functions.js | 969 ++++++++++++++++++ app/service/inbox/groups.js | 2 +- app/service/systems/setting/warehouse.js | 9 + methods/changes/system.json | 18 + methods/system.json | 13 + .../service/systems/setting/warehouse.test.js | 28 + 8 files changed, 1047 insertions(+), 2 deletions(-) diff --git a/app/model/store.js b/app/model/store.js index d31fb6a..4630ef4 100644 --- a/app/model/store.js +++ b/app/model/store.js @@ -56,6 +56,7 @@ module.exports = app => { district_name: '', town_name: '', address: '', + receiver_address: '', group_wave_prefix: 'B', delete_order_wave_prefix: 'A', inventory_warning_rules: DEFAULT_INVENTORY_WARNING_RULES, diff --git a/app/service/inbox/ai.js b/app/service/inbox/ai.js index 8d25d1f..79bfa63 100644 --- a/app/service/inbox/ai.js +++ b/app/service/inbox/ai.js @@ -254,9 +254,16 @@ ${historyContext} - 需要上下文但记忆不足时,主动调用 recallHistory 回顾对话历史 - 【防误判规则 - interceptWaybill】讨论已有售后工单(AS开头编号)、询问物流进度、问"快递到哪了"、转发售后截图等均不是拦截请求,严禁调用 interceptWaybill。只有用户明确说"拦截/退回/召回/追回/取消"运单时才可调用 - 【措辞规则 - interceptWaybill】拦截结果回复严禁使用"已拦截""拦截成功"等确定口吻,必须使用"拦截信息已登记""已提交拦截申请"等措辞。因为快递拦截可能失败,实际结果以快递公司反馈为准。回复时需列出工单号供用户跟进 +- 【规则 - handleStoreFeedback】货主售后群中客户反馈"错发/发错""破损/坏了""多发/发多""少发/漏发"且提供了运单号时,调用 handleStoreFeedback 创建售后工单(初始状态未开始处理,不通知快递群);若消息中无运单号,先向客户确认运单号再调用 +- 【规则 - changeAddr】货主售后群中客户消息含"改地址/改电话/改联系人/改收件人/地址更改/改手机/催退回/尽快安排派送/催促退回"等诉求且提供了运单号时,调用 changeAddr(issue_type:addr=改地址类诉求,return=催退回类诉求);函数会创建售后工单并把客户原文转发到对应快递群,返回的 data.message 是模板消息必须原样回复;若消息中无运单号,先向客户确认运单号再调用 +- 【规则 - weishoudao】货主售后群中客户消息含"核实签收/未收到/是否发出/是否已经发货/核实/没有找到快递"等诉求且提供了运单号时,调用 weishoudao 创建核实签收售后工单,并把"运单号+核实签收"转发到对应快递群;返回的 data.message 是模板消息必须原样回复;若消息中无运单号,先向客户确认运单号再调用 +- 【规则 - changeExpress】货主售后群中客户要求"改快递/换快递/改圆通/改中通/改顺丰"等且提供了订单号时,调用 changeExpress(keyword=订单号,express=目标快递名称或编码);仅待处理表中未分配快递的订单可以修改,已分配快递或不在待处理表的订单不能修改;返回的 data.message 是模板消息必须原样回复;若消息中缺订单号或目标快递,先向客户确认再调用 - 【模板消息 - queryReturn】queryReturn 返回的 data.message 是已排版好的模板消息,必须原样作为最终回复输出,禁止改写、删减、增补内容,禁止添加 Markdown 或额外说明 +- 【规则 - queryWarehouseAddress】用户询问"仓库地址/收货地址/退货地址/退件地址/寄回地址"时,调用 queryWarehouseAddress 查询仓库配置中的 receiver_address;返回的 data.message 是模板消息必须原样回复 +- 【模板消息 - handleStoreFeedback】handleStoreFeedback 返回的 data.message 是已排版好的模板消息(运单号+问题类型+工单号+"稍后客服将人工核实跟进"),必须原样作为最终回复输出,禁止改写、删减或增补内容 - 用户发送"查退回+运单号"时,调用 queryReturn 查询退回明细,不要误调 queryOrder 或 interceptWaybill -- 【查询类请求强制调函数】查订单/查退回/查库存等查询类请求必须实际调用对应函数获取结果后再回复,严禁仅凭历史对话或猜测臆测"服务不可用/无法处理"而跳过函数调用`; +- 【查询类请求强制调函数】查订单/查退回/查库存等查询类请求必须实际调用对应函数获取结果后再回复,严禁仅凭历史对话或猜测臆测"服务不可用/无法处理"而跳过函数调用 +- 【历史失败回复免疫】群历史中 AI 的历史回复(尤其含"失败""异常""无法处理"等字样的兜底回复)只是历史记录,不代表当前功能不可用;严禁模仿、引用这类历史回复,也严禁据此判断函数不可用而拒绝调用;登记/操作/查询类请求必须实际调用对应函数获取最新结果`; // 多轮推理循环 for (let round = 1; round <= MAX_ROUNDS; round++) { diff --git a/app/service/inbox/functions.js b/app/service/inbox/functions.js index a577cbd..be4282d 100644 --- a/app/service/inbox/functions.js +++ b/app/service/inbox/functions.js @@ -1562,6 +1562,901 @@ class InboxFunctionsService extends Service { }, }); + this.register('handleStoreFeedback', { + description: '货主售后群问题反馈建工单。客户反馈"错发/发错""破损/坏了""多发/发多""少发/漏发"等问题并提供了运单号时调用。校验货主权限后创建售后工单,初始状态为未开始处理(pending),不转发通知快递群', + weight: 88, + keywords: [ '错发', '发错', '破损', '坏了', '多发', '发多', '少发', '漏发', '发少' ], + params: { + keyword: { type: 'string', required: true, description: '运单号,多个用逗号或空格分隔,如 SF111,SF222' }, + issue_type: { type: 'string', required: true, description: '问题类型:wrong(错发)/damaged(破损)/multiple(多发)/missing(少发)' }, + }, + groups: [ GROUP.BOUND_STORE_AFTER_SALES ], + handler: async (params = {}) => { + const { ctx } = this; + const raw = String(params.keyword || '').trim(); + const issueTypeRaw = String(params.issue_type || '').trim(); + const storeId = Number(ctx.inboxContext?.store_id || 0); + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + const groupName = String(ctx.inboxContext?.group_name || '').trim(); + const userName = String(ctx.inboxContext?.user_name || '').trim(); + + if (!raw) return { success: false, error: '请提供运单号' }; + if (!warehouseId) return { success: false, error: '无法获取仓库信息' }; + if (!storeId) return { success: false, error: '无法获取货主信息,请确认已在货主售后群上下文中操作' }; + + // 问题类型 → 售后子类型映射(支持英文枚举与中文别名) + const ISSUE_TYPE_MAP = { + wrong: { sub_type: 'mis_shipment', label: '错发' }, + 错发: { sub_type: 'mis_shipment', label: '错发' }, + damaged: { sub_type: 'damage', label: '破损' }, + 破损: { sub_type: 'damage', label: '破损' }, + multiple: { sub_type: 'extra_item', label: '多发' }, + 多发: { sub_type: 'extra_item', label: '多发' }, + missing: { sub_type: 'missing_item', label: '少发' }, + 少发: { sub_type: 'missing_item', label: '少发' }, + }; + const issue = ISSUE_TYPE_MAP[issueTypeRaw]; + if (!issue) { + return { + success: false, + error: `不支持的问题类型「${issueTypeRaw || '空'}」,仅支持 wrong(错发)/damaged(破损)/multiple(多发)/missing(少发)`, + }; + } + + const keywords = raw.split(/[,,\s\n]+/).map(s => s.trim()).filter(Boolean); + if (keywords.length === 0) return { success: false, error: '未解析到有效运单号' }; + + // 前置拦截:拒绝看起来像售后单号(AS...)的输入 + const asLikeList = keywords.filter(k => /^AS/i.test(k)); + if (asLikeList.length > 0) { + return { success: false, error: `${asLikeList.join('、')} 是售后工单号而非运单号,请提供运单号` }; + } + + try { + // 第一步:批量查询运单(限当前仓库 + 当前货主) + const expressList = await ctx.model.OrderExpress.findAll({ + attributes: [ 'id', 'waybill_code', 'logistics_name', 'store_id', 'order_id' ], + where: { + waybill_code: { [ctx.app.Sequelize.Op.in]: keywords }, + warehouse_id: warehouseId, + store_id: storeId, + }, + raw: true, + }); + + const foundCodes = new Set(expressList.map(e => e.waybill_code)); + const notFound = keywords.filter(k => !foundCodes.has(k)); + + if (expressList.length === 0) { + return { success: false, error: `未找到当前货主在仓库中的运单「${raw}」,请核实单号后重试` }; + } + + // 第二步:幂等检查(同子类型未完结工单不重复建单) + const expressIds = expressList.map(e => e.id); + const existingASList = await ctx.model.AfterSale.findAll({ + attributes: [ 'waybill_id', 'after_sale_no' ], + where: { + waybill_id: { [ctx.app.Sequelize.Op.in]: expressIds }, + type: 'order', + sub_type: issue.sub_type, + status: { [ctx.app.Sequelize.Op.notIn]: [ 'completed', 'closed', 'cancelled' ] }, + }, + raw: true, + }); + const existingWaybillIds = new Set(existingASList.map(r => r.waybill_id)); + const toCreate = expressList.filter(e => !existingWaybillIds.has(e.id)); + const alreadyExist = existingASList.map(r => r.after_sale_no); + + /** + * 组装客户回信模板:单号 + 问题信息 + 工单号。 + * @param {Array<{waybill: string, as_no: string}>} pairs 运单号→工单号列表。 + * @return {string} 模板消息。 + */ + const buildReply = pairs => { + const lines = pairs.map(p => `运单${p.waybill} ${issue.label}问题已登记,工单:${p.as_no}`); + if (notFound.length > 0) { + lines.push(`未找到运单:${notFound.join('、')},请核实单号`); + } + return `${lines.join('\n')},稍后客服将人工核实跟进`; + }; + + if (toCreate.length === 0) { + const existedPairs = expressList + .filter(e => existingWaybillIds.has(e.id)) + .map(e => { + const row = existingASList.find(r => Number(r.waybill_id) === Number(e.id)); + return { waybill: e.waybill_code, as_no: (row && row.after_sale_no) || '' }; + }) + .filter(p => p.as_no); + return { + success: true, + data: { + existed: true, + message: buildReply(existedPairs), + direct_reply: true, + after_sale_nos: alreadyExist, + }, + }; + } + + // 第三步:创建工单(初始状态 pending=未开始处理,不转发通知快递群) + const creatorLabel = [ groupName, userName ].filter(Boolean).join('-') || 'AI系统'; + let msgContent = ''; + try { + const mid = ctx.inboxContext?.inbound_message_id; + if (mid) { + const m = await ctx.model.InboxMessage.findByPk(mid, { attributes: [ 'content' ], raw: true }); + if (m && m.content) msgContent = String(m.content); + } + } catch (e) { /* ignore */ } + + const createdNos = []; + const waybillToAsNo = {}; // waybill_id → after_sale_no 映射 + for (const e of toCreate) { + const afterSaleNo = await ctx.service.systemMethods.afterSale.generateAfterSaleNo(warehouseId); + const descParts = [ + `发起人: ${creatorLabel}`, + `运单号: ${e.waybill_code}`, + `快递公司: ${e.logistics_name || '未知'}`, + `问题类型: ${issue.label}`, + msgContent ? `原消息: ${msgContent}` : '', + ].filter(Boolean).join('\n'); + + await ctx.service.systems.afterSale.create({ + warehouse_id: warehouseId, + after_sale_no: afterSaleNo, + type: 'order', + sub_type: issue.sub_type, + title: `[AI工单] ${issue.label} - ${e.waybill_code}`, + description: descParts, + priority: 10, + creator_id: 0, + inbox_message_id: ctx.inboxContext?.inbound_message_id || null, + role_group: 'customer_service', + status: 'pending', + waybill_id: e.id, + waybill_no: e.waybill_code, + store_id: e.store_id || storeId, + order_id: e.order_id || null, + }); + createdNos.push(afterSaleNo); + waybillToAsNo[e.id] = afterSaleNo; + } + + ctx.logger.info( + `[inbox functions] 货主问题反馈建工单: sub_type=${issue.sub_type} ` + + `total=${keywords.length} found=${expressList.length} created=${createdNos.length} notFound=${notFound.length}` + ); + + // 构造返回数据(客户回信模板:单号+问题+工单,细节字段仅作内部记录) + const createdPairs = toCreate.map(e => ({ + waybill: e.waybill_code, + as_no: waybillToAsNo[e.id] || '', + })); + const existedPairs = expressList + .filter(e => existingWaybillIds.has(e.id)) + .map(e => { + const row = existingASList.find(r => Number(r.waybill_id) === Number(e.id)); + return { waybill: e.waybill_code, as_no: (row && row.after_sale_no) || '' }; + }) + .filter(p => p.as_no); + + return { + success: true, + data: { + created: createdNos.length, + existed: alreadyExist.length, + after_sale_nos: [ ...createdNos, ...alreadyExist ], + not_found: notFound, + message: buildReply([ ...createdPairs, ...existedPairs ]), + direct_reply: true, + }, + }; + } catch (error) { + ctx.logger.error(`[inbox functions] 货主问题反馈建工单失败: ${error.message}`); + return { success: false, error: `操作失败: ${error.message}` }; + } + }, + }); + + this.register('changeAddr', { + description: '货主售后群改地址/催退回处理。客户消息含"改地址/改电话/改联系人/改收件人/地址更改/改手机/催退回/尽快安排派送/催促退回"等诉求且提供了运单号时调用:创建售后工单(改地址/催退回),并将客户原文转发到对应快递的售后群通知快递处理', + weight: 89, + keywords: [ '改地址', '改电话', '改联系人', '改收件人', '地址更改', '改手机', '催退回', '尽快安排派送', '催促退回' ], + params: { + keyword: { type: 'string', required: true, description: '运单号,多个用逗号或空格分隔,如 SF111,SF222' }, + issue_type: { type: 'string', required: true, description: '诉求类型:addr(改地址类诉求)/return(催退回类诉求)' }, + }, + groups: [ GROUP.BOUND_STORE_AFTER_SALES ], + handler: async (params = {}) => { + const { ctx } = this; + const raw = String(params.keyword || '').trim(); + const issueTypeRaw = String(params.issue_type || '').trim(); + const storeId = Number(ctx.inboxContext?.store_id || 0); + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + const groupName = String(ctx.inboxContext?.group_name || '').trim(); + const userName = String(ctx.inboxContext?.user_name || '').trim(); + + if (!raw) return { success: false, error: '请提供运单号' }; + if (!warehouseId) return { success: false, error: '无法获取仓库信息' }; + if (!storeId) return { success: false, error: '无法获取货主信息,请确认已在货主售后群上下文中操作' }; + + // 诉求类型 → 售后子类型映射(支持英文枚举与中文别名) + const ISSUE_TYPE_MAP = { + addr: { sub_type: 'change_address', label: '改地址' }, + 改地址: { sub_type: 'change_address', label: '改地址' }, + return: { sub_type: 'rejected', label: '催退回' }, + 催退回: { sub_type: 'rejected', label: '催退回' }, + }; + const issue = ISSUE_TYPE_MAP[issueTypeRaw] || ISSUE_TYPE_MAP.addr; + + const keywords = raw.split(/[,,\s\n]+/).map(s => s.trim()).filter(Boolean); + if (keywords.length === 0) return { success: false, error: '未解析到有效运单号' }; + + const asLikeList = keywords.filter(k => /^AS/i.test(k)); + if (asLikeList.length > 0) { + return { success: false, error: `${asLikeList.join('、')} 是售后工单号而非运单号,请提供运单号` }; + } + + try { + // 原文(客户原始消息,用于转发快递群 + 工单明细) + let originalText = ''; + try { + const mid = ctx.inboxContext?.inbound_message_id; + if (mid) { + const m = await ctx.model.InboxMessage.findByPk(mid, { attributes: [ 'content' ], raw: true }); + if (m && m.content) originalText = String(m.content); + } + } catch (e) { /* ignore */ } + + // 第一步:批量查询运单(限当前仓库 + 当前货主) + const expressList = await ctx.model.OrderExpress.findAll({ + attributes: [ 'id', 'waybill_code', 'logistics_name', 'store_id', 'order_id', + 'logistics_interface_id', 'logistics_code' ], + where: { + waybill_code: { [ctx.app.Sequelize.Op.in]: keywords }, + warehouse_id: warehouseId, + store_id: storeId, + }, + raw: true, + }); + + const foundCodes = new Set(expressList.map(e => e.waybill_code)); + const notFound = keywords.filter(k => !foundCodes.has(k)); + + if (expressList.length === 0) { + return { success: false, error: `未找到当前货主在仓库中的运单「${raw}」,请核实单号后重试` }; + } + + // 第二步:幂等检查(同子类型未完结工单不重复建单) + const expressIds = expressList.map(e => e.id); + const existingASList = await ctx.model.AfterSale.findAll({ + attributes: [ 'waybill_id', 'after_sale_no' ], + where: { + waybill_id: { [ctx.app.Sequelize.Op.in]: expressIds }, + type: 'order', + sub_type: issue.sub_type, + status: { [ctx.app.Sequelize.Op.notIn]: [ 'completed', 'closed', 'cancelled' ] }, + }, + raw: true, + }); + const existingWaybillIds = new Set(existingASList.map(r => r.waybill_id)); + const toCreate = expressList.filter(e => !existingWaybillIds.has(e.id)); + const alreadyExist = existingASList.map(r => r.after_sale_no); + + const existedPairs = expressList + .filter(e => existingWaybillIds.has(e.id)) + .map(e => { + const row = existingASList.find(r => Number(r.waybill_id) === Number(e.id)); + return { waybill: e.waybill_code, as_no: (row && row.after_sale_no) || '' }; + }) + .filter(p => p.as_no); + + // 第三步:创建工单(含原文)并映射 waybill_id → 工单号 + const createdNos = []; + const waybillToAsNo = {}; // waybill_id → after_sale_no 映射 + if (toCreate.length > 0) { + const creatorLabel = [ groupName, userName ].filter(Boolean).join('-') || 'AI系统'; + for (const e of toCreate) { + const afterSaleNo = await ctx.service.systemMethods.afterSale.generateAfterSaleNo(warehouseId); + const descParts = [ + `发起人: ${creatorLabel}`, + `运单号: ${e.waybill_code}`, + `快递公司: ${e.logistics_name || '未知'}`, + `诉求类型: ${issue.label}`, + originalText ? `原文: ${originalText}` : '', + ].filter(Boolean).join('\n'); + + await ctx.service.systems.afterSale.create({ + warehouse_id: warehouseId, + after_sale_no: afterSaleNo, + type: 'order', + sub_type: issue.sub_type, + title: `[AI工单] ${issue.label} - ${e.waybill_code}`, + description: descParts, + priority: 10, + creator_id: 0, + inbox_message_id: ctx.inboxContext?.inbound_message_id || null, + role_group: 'customer_service', + status: 'pending', + waybill_id: e.id, + waybill_no: e.waybill_code, + store_id: e.store_id || storeId, + order_id: e.order_id || null, + }); + createdNos.push(afterSaleNo); + waybillToAsNo[e.id] = afterSaleNo; + } + } + + // 第四步:原文转发到对应快递的售后群(按快递分组) + const expressByCode = {}; + for (const e of toCreate) { + const code = e.logistics_code || '__unknown__'; + if (!expressByCode[code]) { + expressByCode[code] = { interfaceId: e.logistics_interface_id, waybills: [] }; + } + expressByCode[code].waybills.push(e.waybill_code); + } + + let notifiedTotal = 0; + const notifiedWaybillIds = new Set(); + for (const [ code, info ] of Object.entries(expressByCode)) { + if (code === '__unknown__' || !info.interfaceId) continue; + try { + const { afterSalesGroups } = await ctx.service.systems.inbox.group.findGroupsByExpress({ + expressInterfaceId: info.interfaceId, + expressCode: code, + warehouseId, + }); + if (afterSalesGroups.length === 0) { + ctx.logger.info(`[inbox functions] 快递 ${code} 未配置售后群,跳过转发`); + continue; + } + + // 原文转发:运单号 + 客户原始消息 + const forwardMsg = `运单: ${info.waybills.join('、')}\n原文: ${originalText || raw}`; + for (const g of afterSalesGroups) { + ctx.service.inbox.processor.pushSystemNotification({ + warehouse_id: warehouseId, + group_id: g.group_id, + group_name: g.group_name, + content: forwardMsg, + ext_data: g.ext_data || null, + }); + notifiedTotal += 1; + } + toCreate + .filter(e => (e.logistics_code || '__unknown__') === code) + .forEach(e => notifiedWaybillIds.add(e.id)); + } catch (e) { + ctx.logger.warn(`[inbox functions] 改地址/催退回查快递群失败 code=${code}: ${e.message}`); + } + } + + // 第五步:有转发通知的工单升级 pending_feedback + 跟踪时限 + const notifiedAsNos = createdNos.filter((asNo, idx) => notifiedWaybillIds.has(toCreate[idx].id)); + if (notifiedAsNos.length > 0) { + try { + const hours = await ctx.service.systems.afterSale._resolveFollowupHours( + warehouseId, 'order', issue.sub_type + ); + await ctx.model.AfterSale.update( + { + status: 'pending_feedback', + followup_at: ctx.app.Sequelize.literal(`DATE_ADD(NOW(), INTERVAL ${hours} HOUR)`), + role_group: 'customer_service', + }, + { where: { after_sale_no: { [ctx.app.Sequelize.Op.in]: notifiedAsNos } } } + ); + } catch (e) { + ctx.logger.warn(`[inbox functions] 改地址/催退回更新工单状态失败: ${e.message}`); + } + } + + // 第六步:客户回信模板(单号+诉求+工单) + const createdPairs = toCreate.map(e => ({ + waybill: e.waybill_code, + as_no: waybillToAsNo[e.id] || '', + })); + const lines = [ ...createdPairs, ...existedPairs ].map(p => `运单${p.waybill} ${issue.label}问题已登记,工单:${p.as_no}`); + if (notFound.length > 0) { + lines.push(`未找到运单:${notFound.join('、')},请核实单号`); + } + + ctx.logger.info( + `[inbox functions] 改地址/催退回: sub_type=${issue.sub_type} ` + + `total=${keywords.length} found=${expressList.length} created=${createdNos.length} notified=${notifiedTotal}` + ); + + return { + success: true, + data: { + created: createdNos.length, + existed: alreadyExist.length, + after_sale_nos: [ ...createdNos, ...alreadyExist ], + notified_groups: notifiedTotal, + not_found: notFound, + message: `${lines.join('\n')},稍后客服将人工核实跟进`, + direct_reply: true, + }, + }; + } catch (error) { + ctx.logger.error(`[inbox functions] 改地址/催退回处理失败: ${error.message}`); + return { success: false, error: `操作失败: ${error.message}` }; + } + }, + }); + + this.register('weishoudao', { + description: '货主售后群核实签收处理。客户消息含"核实签收/未收到/是否发出/是否已经发货/核实/没有找到快递"等诉求且提供了运单号时调用:创建核实签收售后工单(verify_delivery),并把"运单号+核实签收"转发到对应快递的售后群通知快递核实', + weight: 89, + keywords: [ '核实签收', '未收到', '是否发出', '是否已经发货', '没有找到快递' ], + params: { + keyword: { type: 'string', required: true, description: '运单号,多个用逗号或空格分隔,如 SF111,SF222' }, + }, + groups: [ GROUP.BOUND_STORE_AFTER_SALES ], + handler: async (params = {}) => { + const { ctx } = this; + const raw = String(params.keyword || '').trim(); + const storeId = Number(ctx.inboxContext?.store_id || 0); + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + const groupName = String(ctx.inboxContext?.group_name || '').trim(); + const userName = String(ctx.inboxContext?.user_name || '').trim(); + + const issue = { sub_type: 'verify_delivery', label: '核实签收' }; + + if (!raw) return { success: false, error: '请提供运单号' }; + if (!warehouseId) return { success: false, error: '无法获取仓库信息' }; + if (!storeId) return { success: false, error: '无法获取货主信息,请确认已在货主售后群上下文中操作' }; + + const keywords = raw.split(/[,,\s\n]+/).map(s => s.trim()).filter(Boolean); + if (keywords.length === 0) return { success: false, error: '未解析到有效运单号' }; + + const asLikeList = keywords.filter(k => /^AS/i.test(k)); + if (asLikeList.length > 0) { + return { success: false, error: `${asLikeList.join('、')} 是售后工单号而非运单号,请提供运单号` }; + } + + try { + // 原文(客户原始消息,写入工单明细) + let originalText = ''; + try { + const mid = ctx.inboxContext?.inbound_message_id; + if (mid) { + const m = await ctx.model.InboxMessage.findByPk(mid, { attributes: [ 'content' ], raw: true }); + if (m && m.content) originalText = String(m.content); + } + } catch (e) { /* ignore */ } + + // 第一步:批量查询运单(限当前仓库 + 当前货主) + const expressList = await ctx.model.OrderExpress.findAll({ + attributes: [ 'id', 'waybill_code', 'logistics_name', 'store_id', 'order_id', + 'logistics_interface_id', 'logistics_code' ], + where: { + waybill_code: { [ctx.app.Sequelize.Op.in]: keywords }, + warehouse_id: warehouseId, + store_id: storeId, + }, + raw: true, + }); + + const foundCodes = new Set(expressList.map(e => e.waybill_code)); + const notFound = keywords.filter(k => !foundCodes.has(k)); + + if (expressList.length === 0) { + return { success: false, error: `未找到当前货主在仓库中的运单「${raw}」,请核实单号后重试` }; + } + + // 第二步:幂等检查(同子类型未完结工单不重复建单) + const expressIds = expressList.map(e => e.id); + const existingASList = await ctx.model.AfterSale.findAll({ + attributes: [ 'waybill_id', 'after_sale_no' ], + where: { + waybill_id: { [ctx.app.Sequelize.Op.in]: expressIds }, + type: 'order', + sub_type: issue.sub_type, + status: { [ctx.app.Sequelize.Op.notIn]: [ 'completed', 'closed', 'cancelled' ] }, + }, + raw: true, + }); + const existingWaybillIds = new Set(existingASList.map(r => r.waybill_id)); + const toCreate = expressList.filter(e => !existingWaybillIds.has(e.id)); + const alreadyExist = existingASList.map(r => r.after_sale_no); + + const existedPairs = expressList + .filter(e => existingWaybillIds.has(e.id)) + .map(e => { + const row = existingASList.find(r => Number(r.waybill_id) === Number(e.id)); + return { waybill: e.waybill_code, as_no: (row && row.after_sale_no) || '' }; + }) + .filter(p => p.as_no); + + // 第三步:创建工单(含原文)并映射 waybill_id → 工单号 + const createdNos = []; + const waybillToAsNo = {}; + if (toCreate.length > 0) { + const creatorLabel = [ groupName, userName ].filter(Boolean).join('-') || 'AI系统'; + for (const e of toCreate) { + const afterSaleNo = await ctx.service.systemMethods.afterSale.generateAfterSaleNo(warehouseId); + const descParts = [ + `发起人: ${creatorLabel}`, + `运单号: ${e.waybill_code}`, + `快递公司: ${e.logistics_name || '未知'}`, + `诉求类型: ${issue.label}`, + originalText ? `原文: ${originalText}` : '', + ].filter(Boolean).join('\n'); + + await ctx.service.systems.afterSale.create({ + warehouse_id: warehouseId, + after_sale_no: afterSaleNo, + type: 'order', + sub_type: issue.sub_type, + title: `[AI工单] ${issue.label} - ${e.waybill_code}`, + description: descParts, + priority: 10, + creator_id: 0, + inbox_message_id: ctx.inboxContext?.inbound_message_id || null, + role_group: 'customer_service', + status: 'pending', + waybill_id: e.id, + waybill_no: e.waybill_code, + store_id: e.store_id || storeId, + order_id: e.order_id || null, + }); + createdNos.push(afterSaleNo); + waybillToAsNo[e.id] = afterSaleNo; + } + } + + // 第四步:转发快递群(格式:运单号 + \n + 核实签收) + const expressByCode = {}; + for (const e of toCreate) { + const code = e.logistics_code || '__unknown__'; + if (!expressByCode[code]) { + expressByCode[code] = { interfaceId: e.logistics_interface_id, waybills: [] }; + } + expressByCode[code].waybills.push(e.waybill_code); + } + + let notifiedTotal = 0; + const notifiedWaybillIds = new Set(); + for (const [ code, info ] of Object.entries(expressByCode)) { + if (code === '__unknown__' || !info.interfaceId) continue; + try { + const { afterSalesGroups } = await ctx.service.systems.inbox.group.findGroupsByExpress({ + expressInterfaceId: info.interfaceId, + expressCode: code, + warehouseId, + }); + if (afterSalesGroups.length === 0) { + ctx.logger.info(`[inbox functions] 快递 ${code} 未配置售后群,跳过转发`); + continue; + } + + const forwardMsg = `${info.waybills.join('\n')}\n核实签收`; + for (const g of afterSalesGroups) { + ctx.service.inbox.processor.pushSystemNotification({ + warehouse_id: warehouseId, + group_id: g.group_id, + group_name: g.group_name, + content: forwardMsg, + ext_data: g.ext_data || null, + }); + notifiedTotal += 1; + } + toCreate + .filter(e => (e.logistics_code || '__unknown__') === code) + .forEach(e => notifiedWaybillIds.add(e.id)); + } catch (e) { + ctx.logger.warn(`[inbox functions] 核实签收查快递群失败 code=${code}: ${e.message}`); + } + } + + // 第五步:有转发通知的工单升级 pending_feedback + 跟踪时限 + const notifiedAsNos = createdNos.filter((asNo, idx) => notifiedWaybillIds.has(toCreate[idx].id)); + if (notifiedAsNos.length > 0) { + try { + const hours = await ctx.service.systems.afterSale._resolveFollowupHours( + warehouseId, 'order', issue.sub_type + ); + await ctx.model.AfterSale.update( + { + status: 'pending_feedback', + followup_at: ctx.app.Sequelize.literal(`DATE_ADD(NOW(), INTERVAL ${hours} HOUR)`), + role_group: 'customer_service', + }, + { where: { after_sale_no: { [ctx.app.Sequelize.Op.in]: notifiedAsNos } } } + ); + } catch (e) { + ctx.logger.warn(`[inbox functions] 核实签收更新工单状态失败: ${e.message}`); + } + } + + // 第六步:客户回信模板(单号+诉求+工单) + const createdPairs = toCreate.map(e => ({ + waybill: e.waybill_code, + as_no: waybillToAsNo[e.id] || '', + })); + const lines = [ ...createdPairs, ...existedPairs ].map(p => `运单${p.waybill} ${issue.label}问题已登记,工单:${p.as_no}`); + if (notFound.length > 0) { + lines.push(`未找到运单:${notFound.join('、')},请核实单号`); + } + + ctx.logger.info( + `[inbox functions] 核实签收: total=${keywords.length} found=${expressList.length} created=${createdNos.length} notified=${notifiedTotal}` + ); + + return { + success: true, + data: { + created: createdNos.length, + existed: alreadyExist.length, + after_sale_nos: [ ...createdNos, ...alreadyExist ], + notified_groups: notifiedTotal, + not_found: notFound, + message: `${lines.join('\n')},稍后客服将人工核实跟进`, + direct_reply: true, + }, + }; + } catch (error) { + ctx.logger.error(`[inbox functions] 核实签收处理失败: ${error.message}`); + return { success: false, error: `操作失败: ${error.message}` }; + } + }, + }); + + this.register('changeExpress', { + description: '货主售后群改快递。客户要求"改快递/换快递/改圆通/改中通/改顺丰"等且提供了订单号时调用。仅待处理表中未分配快递(post_status=none)的订单可以修改快递;已分配快递或不在待处理表的订单不能修改', + weight: 87, + keywords: [ '改快递', '换快递', '改圆通', '改中通', '改申通', '改顺丰', '改极兔', '改韵达', '改京东', '改德邦' ], + params: { + keyword: { type: 'string', required: true, description: '订单号(发货单号或平台单号),多个用逗号或空格分隔' }, + express: { type: 'string', required: true, description: '目标快递名称或编码,如 圆通/中通/顺丰,或系统编码如 YTO/STO/SF' }, + }, + groups: [ GROUP.BOUND_STORE_AFTER_SALES ], + handler: async (params = {}) => { + const { ctx } = this; + const raw = String(params.keyword || '').trim(); + const expressRaw = String(params.express || '').trim(); + const storeId = Number(ctx.inboxContext?.store_id || 0); + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + const groupName = String(ctx.inboxContext?.group_name || '').trim(); + const userName = String(ctx.inboxContext?.user_name || '').trim(); + + if (!raw) return { success: false, error: '请提供订单号' }; + if (!expressRaw) return { success: false, error: '请提供目标快递(名称或编码),如 圆通/中通/顺丰' }; + if (!warehouseId) return { success: false, error: '无法获取仓库信息' }; + if (!storeId) return { success: false, error: '无法获取货主信息,请确认已在货主售后群上下文中操作' }; + + const keywords = raw.split(/[,,\s\n]+/).map(s => s.trim()).filter(Boolean); + if (keywords.length === 0) return { success: false, error: '未解析到有效订单号' }; + + // 前置拦截:AS 开头为售后工单号,不是订单号 + const asLikeList = keywords.filter(k => /^AS/i.test(k)); + if (asLikeList.length > 0) { + return { success: false, error: `${asLikeList.join('、')} 是售后工单号而非订单号,请提供发货单号或平台单号` }; + } + + try { + const { Op } = ctx.app.Sequelize; + const factory = ctx.model.OrderDeliveryFactory; + + // 第一步:解析目标快递(兼容名称/别名/编码)。 + // 快递列表服务依赖 ctx.user.store_id 作为仓库上下文,临时注入后恢复。 + const originalUser = ctx.user; + ctx.user = { + ...(originalUser || {}), + store_id: warehouseId, + employees_id: 0, + employees_name: [ groupName, userName ].filter(Boolean).join('-') || 'AI系统', + }; + let expressList = []; + try { + expressList = await ctx.service.systems.express.getExpressList(); + } finally { + ctx.user = originalUser; + } + + const expressKey = expressRaw.toUpperCase(); + const list = Array.isArray(expressList) ? expressList : []; + + // 第一轮:精确匹配(编码/名称/别名/系统编码) + let expressItem = list.find(item => { + const code = String(item.code || item.value || '').trim().toUpperCase(); + const name = String(item.name || '').trim().toUpperCase(); + const alias = String(item.alias || '').trim().toUpperCase(); + const sysCode = String(item.express_code || '').trim().toUpperCase(); + return code === expressKey || name === expressKey || alias === expressKey || sysCode === expressKey; + }); + + // 第二轮:模糊匹配(如客户说"圆通",列表名为"圆通快递") + if (!expressItem && expressKey.length >= 2) { + const fuzzy = list.filter(item => { + const code = String(item.code || item.value || '').trim().toUpperCase(); + const name = String(item.name || '').trim().toUpperCase(); + const alias = String(item.alias || '').trim().toUpperCase(); + const fields = [ name, alias, code ].filter(Boolean); + return fields.some(f => f.includes(expressKey) || expressKey.includes(f)); + }); + if (fuzzy.length === 1) { + expressItem = fuzzy[0]; + } else if (fuzzy.length > 1) { + const names = fuzzy.slice(0, 10) + .map(item => `${item.name || item.code || ''}(${item.code || item.value || ''})`) + .join('、'); + return { + success: false, + error: `快递「${expressRaw}」匹配到多个结果,请明确:${names}`, + }; + } + } + + if (!expressItem) { + const names = list.slice(0, 20) + .map(item => `${item.name || item.code || ''}(${item.code || item.value || ''})`) + .join('、'); + return { + success: false, + error: `未找到快递「${expressRaw}」${names ? `,当前仓库可选快递:${names}` : ''}`, + }; + } + + // 第二步:查待处理表(仅当前货主) + const currentModel = await factory.getCurrentModel(warehouseId); + if (!currentModel) { + return { success: false, error: `仓库 ${warehouseId} 的待处理表不可用` }; + } + + const foundOrders = await currentModel.findAll({ + attributes: [ + 'id', 'delivery_order_code', 'source_platform_code', 'source_order_codes', + 'post_status', 'logistics_name', + ], + where: { + store_id: storeId, + [Op.or]: [ + { delivery_order_code: { [Op.in]: keywords } }, + { source_platform_code: { [Op.in]: keywords } }, + ...keywords.map(k => ({ source_order_codes: { [Op.like]: `%${k}%` } })), + ], + }, + raw: true, + }); + + const foundCodes = new Set(); + for (const o of foundOrders) { + foundCodes.add(o.delivery_order_code); + foundCodes.add(o.source_platform_code); + for (const sc of String(o.source_order_codes || '').split(',')) { + if (sc.trim()) foundCodes.add(sc.trim()); + } + } + const missing = keywords.filter(k => !foundCodes.has(k)); + + // 第三步:未在待处理表找到的 → 查配送表/历史表,区分"不在待处理表"与"未找到" + const notInPending = []; + const notFound = []; + if (missing.length > 0) { + const tableConfigs = [ + { getModel: (f, wid) => f.getDispatchModel(wid) }, + { getModel: (f, wid) => f.getHistoryModel(wid) }, + ]; + const missingSet = new Set(missing); + for (const cfg of tableConfigs) { + if (missingSet.size === 0) break; + const model = await cfg.getModel(factory, warehouseId); + if (!model) continue; + const rows = await model.findAll({ + attributes: [ 'delivery_order_code', 'source_platform_code', 'source_order_codes' ], + where: { + store_id: storeId, + [Op.or]: [ + { delivery_order_code: { [Op.in]: [ ...missingSet ] } }, + { source_platform_code: { [Op.in]: [ ...missingSet ] } }, + ...[ ...missingSet ].map(k => ({ source_order_codes: { [Op.like]: `%${k}%` } })), + ], + }, + raw: true, + }); + for (const r of rows) { + const codes = [ + r.delivery_order_code, + r.source_platform_code, + ...String(r.source_order_codes || '').split(','), + ].map(s => String(s || '').trim()).filter(Boolean); + for (const k of [ ...missingSet ]) { + if (codes.includes(k)) { + missingSet.delete(k); + notInPending.push(k); + } + } + } + } + for (const k of missingSet) notFound.push(k); + } + + // 第四步:区分可改(post_status=none)与已分配快递 + const eligible = foundOrders.filter(o => String(o.post_status || '').trim() === 'none'); + const allocated = foundOrders.filter(o => String(o.post_status || '').trim() !== 'none'); + + // 第五步:逐个改快递(复用 updateOrderExpress,内部自带 post_status=none 保护) + const expressCode = String(expressItem.code || expressItem.value || '').trim(); + const changed = []; + const unchanged = []; + for (const o of eligible) { + try { + const originalUser2 = ctx.user; + ctx.user = { + ...(originalUser2 || {}), + store_id: warehouseId, + employees_id: 0, + employees_name: [ groupName, userName ].filter(Boolean).join('-') || 'AI系统', + }; + let updateResult = null; + try { + updateResult = await ctx.service.systemMethods.order.pendingOrder.updateOrderExpress({ + order_ids: [ o.id ], + express_code: expressCode, + }); + } finally { + ctx.user = originalUser2; + } + const updated = Number(updateResult && updateResult.updated_count) || 0; + if (updated > 0) { + changed.push(o.delivery_order_code); + } else { + unchanged.push(o.delivery_order_code); + } + } catch (e) { + ctx.logger.warn(`[inbox functions] 改快递失败 order=${o.delivery_order_code}: ${e.message}`); + unchanged.push(o.delivery_order_code); + } + } + + // 第六步:组装模板回复 + const expressName = String(expressItem.name || expressItem.code || expressRaw).trim(); + const lines = []; + if (changed.length > 0) { + lines.push(`已改快递为「${expressName}」:${changed.join('、')}`); + } + if (allocated.length > 0) { + lines.push(`已分配快递,不能修改:${allocated.map(o => `${o.delivery_order_code}(${o.logistics_name || '已取号'})`).join('、')}`); + } + if (unchanged.length > 0) { + lines.push(`改快递未生效(可能刚分配了快递),请核实:${unchanged.join('、')}`); + } + if (notInPending.length > 0) { + lines.push(`不在待处理表,不能修改:${notInPending.join('、')}`); + } + if (notFound.length > 0) { + lines.push(`未找到订单:${notFound.join('、')}`); + } + + ctx.logger.info( + `[inbox functions] 改快递: total=${keywords.length} eligible=${eligible.length} ` + + `changed=${changed.length} allocated=${allocated.length} notInPending=${notInPending.length} notFound=${notFound.length}` + ); + + return { + success: true, + data: { + changed: changed.length, + allocated: allocated.length, + not_in_pending: notInPending.length, + not_found: notFound.length, + express: expressName, + message: lines.join('\n'), + direct_reply: true, + }, + }; + } catch (error) { + ctx.logger.error(`[inbox functions] 改快递失败: ${error.message}`); + return { success: false, error: `操作失败: ${error.message}` }; + } + }, + }); + this.register('handleExpressFeedback', { description: '快递群售后通用反馈。传入运单号,优先找已有售后工单追加记录,无工单则按运单查订单并自动创建售后工单。AI 可根据快递反馈内容传入售后类型和子类型', weight: 90, @@ -1915,6 +2810,80 @@ class InboxFunctionsService extends Service { }, }); + this.register('queryWarehouseAddress', { + description: '查询仓库收货地址(退货/退件寄回地址)。读取仓库配置中的 receiver_address。用户询问"仓库地址/收货地址/退货地址/退件地址/寄回地址"时调用。仅货主群和仓库群可用,快递群不可用', + weight: 80, + keywords: [ '仓库地址', '收货地址', '退货地址', '退件地址', '寄回地址', '寄件地址' ], + params: {}, + groups: [ GROUP.BOUND_STORE_WILDCARD, GROUP.BOUND_WAREHOUSE_WILDCARD ], + handler: async (params = {}) => { + const { ctx } = this; + void params; + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + + if (!warehouseId) { + return { success: false, error: '无法获取仓库信息' }; + } + + try { + const store = await ctx.model.Store.findByPk(warehouseId, { + attributes: [ 'id', 'subject_config' ], + raw: true, + }); + + if (!store) { + return { success: false, error: `仓库 ${warehouseId} 不存在` }; + } + + // 读取仓库配置 subject_config.receiver_address(兼容 JSON 字符串形态) + let config = store.subject_config; + if (typeof config === 'string') { + try { + config = JSON.parse(config); + } catch (e) { + config = null; + } + } + if (!config || typeof config !== 'object' || Array.isArray(config)) { + config = {}; + } + + const receiverAddress = String(config.receiver_address || '').trim(); + + if (!receiverAddress) { + return { + success: true, + data: { + warehouse_id: warehouseId, + receiver_address: '', + message: '当前仓库未配置收货地址,请联系仓管在仓库设置中维护「仓库收货地址」', + direct_reply: true, + }, + }; + } + + // 配置中可能存的是字面 \n,转成真实换行便于群消息阅读 + const displayAddress = receiverAddress + .replace(/\\r\\n/g, '\n') + .replace(/\\n/g, '\n') + .replace(/\\r/g, '\n'); + + return { + success: true, + data: { + warehouse_id: warehouseId, + receiver_address: receiverAddress, + message: `仓库收货地址:\n${displayAddress}`, + direct_reply: true, + }, + }; + } catch (error) { + ctx.logger.error(`[inbox functions] 查询仓库收货地址失败: ${error.message}`); + return { success: false, error: `查询仓库地址失败: ${error.message}` }; + } + }, + }); + this.register('listGroups', { description: '查询当前仓库的群列表,包含屏蔽状态(仅内部仓库群可用)', params: {}, diff --git a/app/service/inbox/groups.js b/app/service/inbox/groups.js index e6f7977..f68b811 100644 --- a/app/service/inbox/groups.js +++ b/app/service/inbox/groups.js @@ -26,7 +26,7 @@ const GROUP_TYPES = [ type: 'warehouse', label: '仓库群', mainGroup: 'bound:warehouse', - wildcardGroup: null, + wildcardGroup: 'bound:warehouse:*', subTypes: [ { key: 'receiving', label: '收货' }, { key: 'production', label: '生产' }, diff --git a/app/service/systems/setting/warehouse.js b/app/service/systems/setting/warehouse.js index 58b0512..e06b1b6 100644 --- a/app/service/systems/setting/warehouse.js +++ b/app/service/systems/setting/warehouse.js @@ -148,6 +148,15 @@ const WAREHOUSE_SETTING_FIELDS = Object.freeze([ description: '仓库默认发件详细地址', maxLength: 200, }), + Object.freeze({ + key: 'receiver_address', + name: '仓库收货地址', + type: 'string', + default: '', + required: false, + description: '仓库收货地址(退货/退件收件地址),一行文本', + maxLength: 500, + }), Object.freeze({ key: 'group_wave_prefix', name: '团购波次前缀', diff --git a/methods/changes/system.json b/methods/changes/system.json index 6adaad4..a8a50b5 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,22 @@ [ + { + "version": "2026.08.14-warehouse-receive-address", + "date": "2026-08-14", + "type": "added", + "summary": "仓库设置 setting.warehouse 新增仓库收货地址配置字段 receiver_address(一行文本,退货/退件收件地址)", + "methods": [ + "setting.warehouse.getSettings", + "setting.warehouse.getFieldMeta", + "setting.warehouse.saveSettings" + ], + "notes": [ + "在 WAREHOUSE_SETTING_FIELDS 中新增 receiver_address(string,非必填,默认空字符串,最大长度 500)", + "wms_store.subject_config 默认值同步补齐(app/model/store.js DEFAULT_SUBJECT_CONFIG)", + "methods/system.json 中 getSettings 响应与 saveSettings 入参补充对应字段文档", + "向后兼容:新增字段为可选,不影响既有仓库设置读写" + ], + "module": "setting.warehouse" + }, { "version": "2026.08.13-stockQueryWhere", "date": "2026-08-13", diff --git a/methods/system.json b/methods/system.json index e92a56a..07325d3 100644 --- a/methods/system.json +++ b/methods/system.json @@ -13663,6 +13663,12 @@ "type": "string", "required": false, "description": "仓库默认发件详细地址,默认空字符串" + }, + { + "name": "subject_config.receiver_address", + "type": "string", + "required": false, + "description": "仓库收货地址(退货/退件收件地址),一行文本,默认空字符串" } ], "errors": [ @@ -13906,6 +13912,13 @@ "required": false, "source": "body.subject_config", "description": "仓库默认发件详细地址,默认空字符串,最大长度 200" + }, + { + "name": "subject_config.receiver_address", + "type": "string", + "required": false, + "source": "body.subject_config", + "description": "仓库收货地址(退货/退件收件地址),一行文本,默认空字符串,最大长度 500" } ], "response": [ diff --git a/test/app/service/systems/setting/warehouse.test.js b/test/app/service/systems/setting/warehouse.test.js index 2e6132b..bbb8985 100644 --- a/test/app/service/systems/setting/warehouse.test.js +++ b/test/app/service/systems/setting/warehouse.test.js @@ -252,4 +252,32 @@ describe('test/app/service/systems/setting/warehouse.test.js', () => { ); assert.equal(inventoryWarningRulesField.required, false); }); + + it('getFieldMeta should include warehouse receive address field', async () => { + const { ctx } = createHarness(); + const service = new SettingWarehouseService(ctx); + + const list = await service.getFieldMeta(); + const field = list.find(item => item.key === 'receiver_address'); + + assert.ok(field, '字段信息应包含 receiver_address'); + assert.equal(field.name, '仓库收货地址'); + assert.equal(field.type, 'string'); + assert.equal(field.required, false); + assert.equal(field.default, ''); + assert.equal(field.maxLength, 500); + }); + + it('saveSettings should persist warehouse receive address field', async () => { + const { ctx, calls } = createHarness(); + const service = new SettingWarehouseService(ctx); + + await service.saveSettings({ + subject_config: { + receiver_address: '浙江省杭州市余杭区文一西路 1000 号', + }, + }); + + assert.equal(calls.updatePayload.subject_config.receiver_address, '浙江省杭州市余杭区文一西路 1000 号'); + }); }); From f3cf941721b05546dc120a69bdf9dccb71705cee Mon Sep 17 00:00:00 2001 From: liufumingren Date: Fri, 14 Aug 2026 23:06:05 +0800 Subject: [PATCH 206/550] =?UTF-8?q?feat:=20inbox=20=E6=96=B0=E5=A2=9E?= =?UTF-8?q?=E6=89=93=E5=8C=85=E8=A7=86=E9=A2=91=E6=9F=A5=E8=AF=A2/?= =?UTF-8?q?=E6=9F=A5=E9=87=8D/=E5=88=86=E9=85=8D=E5=BF=AB=E9=80=92?= =?UTF-8?q?=E5=8F=B7=E5=87=BD=E6=95=B0=EF=BC=8C=E5=BF=AB=E9=80=92=E5=8F=8D?= =?UTF-8?q?=E9=A6=88=E5=9B=9E=E4=BF=A1=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/model/after_sale.js | 1 + app/service/inbox/ai.js | 21 +- app/service/inbox/functions.js | 872 ++++++++++++++++++++++++- app/service/inbox/processor.js | 38 +- app/service/inbox/receiver.js | 13 +- app/service/systemMethods/afterSale.js | 2 + app/service/systems/afterSale.js | 90 ++- app/service/systems/return_unpack.js | 132 +++- app/service/warehouseMethods/inbox.js | 21 + config/config.default.js | 2 + methods/changes/system.json | 70 ++ methods/changes/warehouse.json | 17 + methods/system.json | 26 +- methods/warehouse.json | 9 +- script/debug-inbox-push.cjs | 6 +- 15 files changed, 1283 insertions(+), 37 deletions(-) diff --git a/app/model/after_sale.js b/app/model/after_sale.js index 7e0f5bc..8615ca1 100644 --- a/app/model/after_sale.js +++ b/app/model/after_sale.js @@ -35,6 +35,7 @@ module.exports = app => { { name: '多发', value: 'extra_item' }, { name: '改地址', value: 'change_address' }, { name: '换快递', value: 'change_carrier' }, + { name: '揽收', value: 'pickup' }, { name: '重量异常', value: 'weight_issue' }, { name: '运费争议', value: 'freight_issue' }, { name: '其他', value: 'other' }, diff --git a/app/service/inbox/ai.js b/app/service/inbox/ai.js index 79bfa63..a7317db 100644 --- a/app/service/inbox/ai.js +++ b/app/service/inbox/ai.js @@ -83,6 +83,10 @@ class InboxAIService extends Service { const userId = String(ctx.inboxContext?.user_id || '').trim(); const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + // 排除当前消息本身(parentId=当前消息id;recallHistory 时取上下文注入的入站消息id), + // 避免"当前请求"混入历史导致 AI 重复处理 + const excludeId = parentId || Number(ctx.inboxContext?.inbound_message_id) || 0; + // 无群/用户上下文时,退回旧逻辑:沿 parent_id 追溯 if (!groupId || !userId || !warehouseId) { if (!parentId) return []; @@ -117,6 +121,7 @@ class InboxAIService extends Service { warehouse_id: warehouseId, group_id: groupId, direction: { [Op.in]: [ 'inbound', 'outbound' ] }, + ...(excludeId ? { id: { [Op.ne]: excludeId } } : {}), }, order: [[ 'created_at', 'DESC' ]], limit: maxMessages, @@ -186,7 +191,7 @@ class InboxAIService extends Service { const historyContext = history.length > 0 ? history.map(h => { const tag = h.blocked ? '[已屏蔽]' : ''; - return `[${h.role === 'user' ? h.user_name || h.user_id || '未知' : 'AI'}]${tag}: ${h.content}`; + return `[历史]${h.role === 'user' ? h.user_name || h.user_id || '未知' : 'AI'}${tag}: ${h.content}`; }).join('\n') : '(无历史)'; @@ -207,6 +212,12 @@ ${historyContext} 对话历史中 [已屏蔽] 标记表示该用户已主动要求屏蔽(不想被 AI 打扰)。 如果 [已屏蔽] 用户发送了表示接手或正在处理的内容(如"我来处理""不用回复""稍等""我看看"),说明真人已接管 → 直接 silent。 +【历史消息边界 - 最高优先级】 +- 以上带 [历史] 前缀的记录均为群历史消息,**全部已处理完毕**,仅作背景参考(判断是否有人已接管等),不是待处理请求 +- 严禁把历史记录中的运单号/订单号/地址/售后诉求等当作当前用户的新请求;严禁对历史记录中的请求重复调用函数或重复创建工单 +- 只有最后一条不带 [历史] 前缀的用户消息才是本次待处理请求,所有函数参数只能从这条当前消息中提取 +- 当前消息未提供运单号/订单号等必填参数时,必须先向用户确认,严禁从历史记录中拼凑参数 + 你需要通过多轮调用来完成用户的复杂请求。每轮返回纯 JSON: 如果还需要调用函数获取信息: @@ -241,6 +252,7 @@ ${historyContext} - 回复使用中文纯文本,禁止 Markdown 语法,可用 \\n 换行提升可读性 - silent 仅用于:用户已确认收到消息且无新问题("好的""收到""OK""谢谢""知道了""好"),或用户表示告别/离场("再见""拜拜""88") - 以下情况严禁 silent,必须 reply:任何形式的提问(含"在吗""有人吗""在不在")、操作请求、函数执行完毕、自定义欢迎语"你好""嗨""hello"等首次问候 +- 【快递群专项】快递客服发出的进度/结果反馈("已通知网点""网点正在处理""已拦截""已联系收件人""改地址失败/无法改""已签收"等)严禁 silent,必须先调用 handleExpressFeedback 记录反馈再回复 - 无法判断时,宁可回复也不要 silent - searchStock 返回多条结果时,必须列举让用户选择(告知 id/编码/名称/可用库存),不要擅自决定 - createOrder 失败时告知失败原因(库存不足/商品不存在等),不要重试同一商品 @@ -253,11 +265,17 @@ ${historyContext} - 用户说"第1个""第2个"时,按 searchStock 返回的顺序对应选择 - 需要上下文但记忆不足时,主动调用 recallHistory 回顾对话历史 - 【防误判规则 - interceptWaybill】讨论已有售后工单(AS开头编号)、询问物流进度、问"快递到哪了"、转发售后截图等均不是拦截请求,严禁调用 interceptWaybill。只有用户明确说"拦截/退回/召回/追回/取消"运单时才可调用 +- 【规则 - requestPickup】货主售后群/仓库客服群中客户要求上门揽收/取件(如"揽收""上门取件""退货取件""寄回""让快递来拿"等)且提供了运单号时,调用 requestPickup(keyword=运单号,多个用逗号分隔)。函数会创建揽收售后工单,并优先转发到对应快递的揽收群(未配置揽收群时回退到售后群);返回的 data.message 是模板消息必须原样回复;若消息中无运单号,先向客户确认运单号再调用 - 【措辞规则 - interceptWaybill】拦截结果回复严禁使用"已拦截""拦截成功"等确定口吻,必须使用"拦截信息已登记""已提交拦截申请"等措辞。因为快递拦截可能失败,实际结果以快递公司反馈为准。回复时需列出工单号供用户跟进 - 【规则 - handleStoreFeedback】货主售后群中客户反馈"错发/发错""破损/坏了""多发/发多""少发/漏发"且提供了运单号时,调用 handleStoreFeedback 创建售后工单(初始状态未开始处理,不通知快递群);若消息中无运单号,先向客户确认运单号再调用 +- 【规则 - handleExpressFeedback】快递售后群中,快递客服反馈处理进度/结果(如"已通知网点""网点正在处理""已拦截""已联系收件人""改地址失败/无法改""已签收""加急处理"等)且消息含运单号时,必须调用 handleExpressFeedback(keyword=运单号,多个用逗号分隔)。该函数会自动查找已有售后工单追加反馈并回信到相关群,无工单则自动创建。严禁把快递客服的进度/结果反馈判定为无需处理而 silent;若消息无运单号,先用 recallHistory 或询问确认运单号,严禁跳过 +- 【规则 - handleExpressFeedback 证据核实】快递售后群中快递方发消息要求"提供交易记录截图/未收到依据/核实签收/带日期单号"等证据类诉求且消息含运单号时,同样必须调用 handleExpressFeedback(as_sub_type=verify_delivery),由函数创建售后工单并回信到货主售后群;严禁仅回复"收到/已记录"等确认话术而不调用函数 - 【规则 - changeAddr】货主售后群中客户消息含"改地址/改电话/改联系人/改收件人/地址更改/改手机/催退回/尽快安排派送/催促退回"等诉求且提供了运单号时,调用 changeAddr(issue_type:addr=改地址类诉求,return=催退回类诉求);函数会创建售后工单并把客户原文转发到对应快递群,返回的 data.message 是模板消息必须原样回复;若消息中无运单号,先向客户确认运单号再调用 - 【规则 - weishoudao】货主售后群中客户消息含"核实签收/未收到/是否发出/是否已经发货/核实/没有找到快递"等诉求且提供了运单号时,调用 weishoudao 创建核实签收售后工单,并把"运单号+核实签收"转发到对应快递群;返回的 data.message 是模板消息必须原样回复;若消息中无运单号,先向客户确认运单号再调用 - 【规则 - changeExpress】货主售后群中客户要求"改快递/换快递/改圆通/改中通/改顺丰"等且提供了订单号时,调用 changeExpress(keyword=订单号,express=目标快递名称或编码);仅待处理表中未分配快递的订单可以修改,已分配快递或不在待处理表的订单不能修改;返回的 data.message 是模板消息必须原样回复;若消息中缺订单号或目标快递,先向客户确认再调用 +- 【规则 - queryPackVideo】用户询问"打包视频/打包录像/装箱视频"且提供了运单号时,调用 queryPackVideo 查询(散单按订单、团购单按波次找打包记录);仅查询不建工单;返回的 data.message 是模板消息必须原样回复;若消息中无运单号,先向客户确认运单号再调用 +- 【规则 - queryWeight】用户询问"查重/重量/核实重量/核重/称重"且提供了运单号时,调用 queryWeight 查询运单称重;重量为0时模板输出"未称重";仅查询不建工单;返回的 data.message 是模板消息必须原样回复;若消息中无运单号,先向客户确认运单号再调用 +- 【规则 - createPostnum】货主售后群中客户要求"出单/打单/打印单/催发货/分配快递号"且提供了订单号时,调用 createPostnum(keyword=订单号,多个用逗号分隔);仅待处理表已审核且未分配快递号的订单可分配,函数会走分配流程并按结果返回"已分配+已回传"或"分配失败,等待客服人工处理"模板;返回的 data.message 是模板消息必须原样回复;若消息中无订单号,先向客户确认订单号再调用 - 【模板消息 - queryReturn】queryReturn 返回的 data.message 是已排版好的模板消息,必须原样作为最终回复输出,禁止改写、删减、增补内容,禁止添加 Markdown 或额外说明 - 【规则 - queryWarehouseAddress】用户询问"仓库地址/收货地址/退货地址/退件地址/寄回地址"时,调用 queryWarehouseAddress 查询仓库配置中的 receiver_address;返回的 data.message 是模板消息必须原样回复 - 【模板消息 - handleStoreFeedback】handleStoreFeedback 返回的 data.message 是已排版好的模板消息(运单号+问题类型+工单号+"稍后客服将人工核实跟进"),必须原样作为最终回复输出,禁止改写、删减或增补内容 @@ -279,7 +297,6 @@ ${historyContext} const messages = [ { role: 'system', content: systemPrompt }, - ...history, ...(contextLines.length > 0 ? [{ role: 'system', content: contextLines.join('\n') }] : []), { role: 'user', content: round === 1 ? content diff --git a/app/service/inbox/functions.js b/app/service/inbox/functions.js index be4282d..0861745 100644 --- a/app/service/inbox/functions.js +++ b/app/service/inbox/functions.js @@ -631,7 +631,7 @@ class InboxFunctionsService extends Service { }); this.register('recallHistory', { - description: '回顾当前群+用户的最近对话历史。当需要上下文但信息不足时调用,获取最近N条消息记录(含AI回复),每条带序号', + description: '回顾当前群的最近对话历史(均为已处理完毕的历史记录,仅作背景参考,严禁把其中的运单号/诉求当成新请求)。当需要上下文但信息不足时调用,获取最近N条消息记录(含AI回复),每条带序号', params: { limit: { type: 'number', required: false, description: '获取最近几条,默认5,最大10' }, }, @@ -649,6 +649,7 @@ class InboxFunctionsService extends Service { success: true, data: { total: history.length, + hint: '以下均为已处理完毕的历史记录,仅作背景参考,严禁把其中的运单号/诉求当作新请求处理', messages: history.map(h => ({ role: h.role === 'user' ? '用户' : 'AI', user: h.user_name || h.user_id || null, @@ -1193,6 +1194,297 @@ class InboxFunctionsService extends Service { }, }); + this.register('requestPickup', { + description: '揽收处理(退货/寄件上门取件)。客户要求上门揽收/取件且提供了运单号时调用:创建揽收售后工单,并把客户原文转发到对应快递的揽收群;该快递未配置揽收群时回退发送到售后群。仅写工单与通知群,不修改订单表和快递表数据', + weight: 88, + keywords: [ '揽收', '上门取件', '取件', '退货取件', '寄回', '上门揽收', '让快递来拿' ], + params: { + keyword: { type: 'string', required: true, description: '运单号,多个用逗号或空格分隔,如 SF111,SF222' }, + reason: { type: 'string', required: false, description: '揽收备注/原因' }, + }, + groups: [ GROUP.BOUND_WAREHOUSE_CUSTOMER_SERVICE, GROUP.BOUND_STORE_AFTER_SALES ], + handler: async (params = {}) => { + const { ctx } = this; + const raw = String(params.keyword || '').trim(); + const reason = String(params.reason || '').trim(); + const storeId = Number(ctx.inboxContext?.store_id || 0); + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + const groupType = String(ctx.inboxContext?.group_type || '').trim(); + const groupName = String(ctx.inboxContext?.group_name || '').trim(); + const userName = String(ctx.inboxContext?.user_name || '').trim(); + + if (!raw) return { success: false, error: '请提供运单号' }; + if (!warehouseId) return { success: false, error: '无法获取仓库信息' }; + + // 解析多个运单号(逗号/空格/换行分隔) + const keywords = raw.split(/[,,\s\n]+/).map(s => s.trim()).filter(Boolean); + if (keywords.length === 0) return { success: false, error: '未解析到有效运单号' }; + + // 前置拦截:拒绝看起来像售后单号(AS...)的输入 + const asLikeList = keywords.filter(k => /^AS/i.test(k)); + if (asLikeList.length > 0) { + return { + success: false, + error: `${asLikeList.join('、')} 看起来是售后工单号而非运单号,请提供运单号`, + }; + } + + try { + // 第一步:批量查询运单(仅读取,不做任何修改) + const expressList = await ctx.model.OrderExpress.findAll({ + attributes: [ + 'id', 'waybill_code', 'logistics_name', 'store_id', + 'logistics_interface_id', 'logistics_code', 'order_id', + ], + where: { + waybill_code: { [ctx.app.Sequelize.Op.in]: keywords }, + warehouse_id: warehouseId, + }, + raw: true, + }); + + if (expressList.length === 0) { + return { success: false, error: `未找到运单号「${raw}」,请核实单号后重试` }; + } + + // 第二步:鉴权 + 过滤(与拦截一致:货主群需验 store_id) + const validList = []; + const skipped = []; + for (const e of expressList) { + if (groupType === 'store') { + if (!storeId || Number(e.store_id) !== storeId) { + skipped.push(e.waybill_code); + continue; + } + } + validList.push(e); + } + + if (validList.length === 0) { + return { + success: false, + error: `运单${skipped.join('、')}不属于当前货主,无法操作`, + }; + } + + // 第三步:幂等检查(同子类型未完结工单不重复建单) + const validIds = validList.map(e => e.id); + const existingASList = await ctx.model.AfterSale.findAll({ + attributes: [ 'waybill_id', 'after_sale_no' ], + where: { + waybill_id: { [ctx.app.Sequelize.Op.in]: validIds }, + type: 'order', + sub_type: 'pickup', + status: { [ctx.app.Sequelize.Op.notIn]: [ 'completed', 'closed', 'cancelled' ] }, + }, + raw: true, + }); + const existingWaybillIds = new Set(existingASList.map(r => r.waybill_id)); + + const toCreate = validList.filter(e => !existingWaybillIds.has(e.id)); + const alreadyExist = existingASList.map(r => r.after_sale_no); + + if (toCreate.length === 0) { + const replyLines = []; + const existedWbs = validList + .filter(e => existingWaybillIds.has(e.id)) + .map(e => e.waybill_code); + if (existedWbs.length > 0) { + replyLines.push(existedWbs.join('\n')); + replyLines.push('已登记过,无需重复'); + } + if (skipped.length > 0) replyLines.push(`无权操作:${skipped.join('\n')}`); + return { + success: true, + data: { + existed: true, + message: replyLines.join('\n'), + direct_reply: true, + after_sale_nos: alreadyExist, + }, + }; + } + + // 第四步:创建工单(初始状态 pending,后续根据通知结果升级) + const creatorLabel = [ groupName, userName ].filter(Boolean).join('-') || 'AI系统'; + // 获取原消息内容,写入工单明细与转发文本 + let originalText = ''; + try { + const mid = ctx.inboxContext?.inbound_message_id; + if (mid) { + const m = await ctx.model.InboxMessage.findByPk(mid, { attributes: [ 'content' ], raw: true }); + if (m && m.content) originalText = String(m.content); + } + } catch (e) { /* ignore */ } + + const createdNos = []; + const waybillToAsNo = {}; // waybill_id → after_sale_no 映射 + for (const e of toCreate) { + const afterSaleNo = await ctx.service.systemMethods.afterSale.generateAfterSaleNo(warehouseId); + const descParts = [ + `发起人: ${creatorLabel}`, + `运单号: ${e.waybill_code}`, + `快递公司: ${e.logistics_name || '未知'}`, + reason ? `揽收备注: ${reason}` : '', + originalText ? `原文: ${originalText}` : '', + ].filter(Boolean).join('\n'); + + await ctx.service.systems.afterSale.create({ + warehouse_id: warehouseId, + after_sale_no: afterSaleNo, + type: 'order', + sub_type: 'pickup', + title: `[AI工单] 揽收请求 - ${e.waybill_code}`, + description: descParts, + priority: 10, + creator_id: 0, + inbox_message_id: ctx.inboxContext?.inbound_message_id || null, + role_group: 'customer_service', + status: 'pending', + waybill_id: e.id, + waybill_no: e.waybill_code, + store_id: e.store_id || storeId || null, + order_id: e.order_id || null, + }); + createdNos.push(afterSaleNo); + waybillToAsNo[e.id] = afterSaleNo; + } + + ctx.logger.info( + `[inbox functions] 批量揽收: total=${keywords.length} found=${expressList.length} ` + + `valid=${validList.length} created=${createdNos.length} skipped=${skipped.length}` + ); + + // 第五步:合并通知快递群(按快递分组)——优先揽收群,无揽收群回退售后群 + const expressByCode = {}; + for (const e of toCreate) { + const code = e.logistics_code || '__unknown__'; + if (!expressByCode[code]) { + expressByCode[code] = { interfaceId: e.logistics_interface_id, waybills: [] }; + } + expressByCode[code].waybills.push(e.waybill_code); + } + + let notifiedTotal = 0; + const notifiedWaybillIds = new Set(); // 记录哪些运单成功通知了至少一个群 + for (const [ code, info ] of Object.entries(expressByCode)) { + if (code === '__unknown__' || !info.interfaceId) continue; + try { + const { afterSalesGroups, pickupGroups } = await ctx.service.systems.inbox.group.findGroupsByExpress({ + expressInterfaceId: info.interfaceId, + expressCode: code, + warehouseId, + }); + + // 优先揽收群;未配置揽收群时回退售后群 + const targetGroups = pickupGroups.length > 0 ? pickupGroups : afterSalesGroups; + if (targetGroups.length === 0) { + ctx.logger.info(`[inbox functions] 快递 ${code} 未配置揽收群与售后群,跳过通知`); + continue; + } + + // 发给快递的模板:运单号(每个一行)+ 揽收 + const forwardMsg = info.waybills.join('\n') + '\n揽收'; + for (const g of targetGroups) { + ctx.service.inbox.processor.pushSystemNotification({ + warehouse_id: warehouseId, + group_id: g.group_id, + group_name: g.group_name, + content: forwardMsg, + ext_data: g.ext_data || null, + }); + notifiedTotal += 1; + } + // 有目标群即标记为已通知(推送是异步的,不计成败) + const codeWaybills = toCreate.filter(e => (e.logistics_code || '__unknown__') === code); + codeWaybills.forEach(e => notifiedWaybillIds.add(e.id)); + } catch (e) { + ctx.logger.warn(`[inbox functions] 查快递群失败 code=${code}: ${e.message}`); + } + } + + // 第六步:有通知的工单升级为 pending_feedback + const notifiedAsNos = []; + const notNotifiedAsNos = []; + for (const e of toCreate) { + const asNo = waybillToAsNo[e.id]; + if (notifiedWaybillIds.has(e.id)) { + notifiedAsNos.push(asNo); + } else { + notNotifiedAsNos.push(asNo); + } + } + + if (notifiedAsNos.length > 0) { + const hours = await ctx.service.systems.afterSale._resolveFollowupHours( + warehouseId, 'order', 'pickup' + ); + await ctx.model.AfterSale.update( + { + status: 'pending_feedback', + followup_at: ctx.app.Sequelize.literal(`DATE_ADD(NOW(), INTERVAL ${hours} HOUR)`), + role_group: 'customer_service', + }, + { where: { after_sale_no: { [ctx.app.Sequelize.Op.in]: notifiedAsNos } } } + ); + ctx.logger.info( + `[inbox functions] ${notifiedAsNos.length} 个揽收工单已通知快递群,` + + `升级为 pending_feedback,${hours}h 后追踪` + ); + } + + // 构造客户回信模板:多个快递号换行分隔,同类状态共用一行说明 + const replyLines = []; + const notifiedWbs = []; + const existedWbs = []; + const notNotifiedWbs = []; + for (const e of validList) { + if (notifiedWaybillIds.has(e.id)) { + notifiedWbs.push(e.waybill_code); + } else if (existingWaybillIds.has(e.id)) { + existedWbs.push(e.waybill_code); + } else { + notNotifiedWbs.push(e.waybill_code); + } + } + if (notifiedWbs.length > 0) { + replyLines.push(notifiedWbs.join('\n')); + replyLines.push('已通知运方,待处理后刷新轨迹'); + } + if (notNotifiedWbs.length > 0) { + replyLines.push(notNotifiedWbs.join('\n')); + replyLines.push('已登记(未配置快递群,需人工跟进)'); + } + if (existedWbs.length > 0) { + replyLines.push(existedWbs.join('\n')); + replyLines.push('已登记过,无需重复'); + } + if (skipped.length > 0) { + replyLines.push(`无权操作:${skipped.join('\n')}`); + } + + return { + success: true, + data: { + created: createdNos.length, + existed: alreadyExist.length, + skipped: skipped.length, + after_sale_nos: [ ...createdNos, ...alreadyExist ], + notified_as_nos: notifiedAsNos, + not_notified_as_nos: notNotifiedAsNos, + notified_groups: notifiedTotal, + waybills: validList.map(e => e.waybill_code), + message: replyLines.join('\n'), + direct_reply: true, + }, + }; + } catch (error) { + ctx.logger.error(`[inbox functions] 批量揽收失败: ${error.message}`); + return { success: false, error: `揽收操作失败: ${error.message}` }; + } + }, + }); + this.register('queryReturn', { description: '查询退回包裹明细(查退回)。用户发送"查退回+运单号"时调用。传入运单号,查询退回收到/退回拆包/未退回登记状态:已拆包返回拆包明细与录像地址模板消息,未退回则自动登记到退回查询表。注意:仅查询退回状态使用,与 interceptWaybill 拦截、queryOrder 订单查询不同', weight: 90, @@ -2457,6 +2749,528 @@ class InboxFunctionsService extends Service { }, }); + this.register('createPostnum', { + description: '分配快递号/出单(打单/催发货)。客户要求"出单/打单/打印单/催发货/分配快递号"且提供了订单号时调用。仅待处理表中已审核且未分配快递号的订单可分配;分配成功后同步回传平台并通知单号,失败则提示等待客服人工处理。仅创建运单,不创建售后工单', + weight: 86, + keywords: [ '出单', '打单', '打印单', '催发货', '分配快递号', '要单号' ], + params: { + keyword: { type: 'string', required: true, description: '订单号(发货单号或平台单号),多个用逗号或空格分隔' }, + }, + groups: [ GROUP.BOUND_STORE_AFTER_SALES ], + handler: async (params = {}) => { + const { ctx } = this; + const raw = String(params.keyword || '').trim(); + const storeId = Number(ctx.inboxContext?.store_id || 0); + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + const groupName = String(ctx.inboxContext?.group_name || '').trim(); + const userName = String(ctx.inboxContext?.user_name || '').trim(); + + if (!raw) return { success: false, error: '请提供订单号' }; + if (!warehouseId) return { success: false, error: '无法获取仓库信息' }; + if (!storeId) return { success: false, error: '无法获取货主信息,请确认已在货主售后群上下文中操作' }; + + const keywords = raw.split(/[,,\s\n]+/).map(s => s.trim()).filter(Boolean); + if (keywords.length === 0) return { success: false, error: '未解析到有效订单号' }; + + // 前置拦截:AS 开头为售后工单号,不是订单号 + const asLikeList = keywords.filter(k => /^AS/i.test(k)); + if (asLikeList.length > 0) { + return { success: false, error: `${asLikeList.join('、')} 是售后工单号而非订单号,请提供发货单号或平台单号` }; + } + + try { + const { Op } = ctx.app.Sequelize; + const factory = ctx.model.OrderDeliveryFactory; + + // 第一步:查待处理表(仅当前货主) + const currentModel = await factory.getCurrentModel(warehouseId); + if (!currentModel) { + return { success: false, error: `仓库 ${warehouseId} 的待处理表不可用` }; + } + + const foundOrders = await currentModel.findAll({ + attributes: [ + 'id', 'delivery_order_code', 'source_platform_code', 'source_order_codes', + 'step', 'post_status', 'logistics_name', + ], + where: { + store_id: storeId, + [Op.or]: [ + { delivery_order_code: { [Op.in]: keywords } }, + { source_platform_code: { [Op.in]: keywords } }, + ...keywords.map(k => ({ source_order_codes: { [Op.like]: `%${k}%` } })), + ], + }, + raw: true, + }); + + const foundCodes = new Set(); + for (const o of foundOrders) { + foundCodes.add(o.delivery_order_code); + foundCodes.add(o.source_platform_code); + for (const sc of String(o.source_order_codes || '').split(',')) { + if (sc.trim()) foundCodes.add(sc.trim()); + } + } + const missing = keywords.filter(k => !foundCodes.has(k)); + + // 第二步:未在待处理表找到的 → 查配送表/历史表区分"不在待处理表"与"未找到" + const notInPending = []; + const notFound = []; + if (missing.length > 0) { + const tableConfigs = [ + { getModel: (f, wid) => f.getDispatchModel(wid) }, + { getModel: (f, wid) => f.getHistoryModel(wid) }, + ]; + const missingSet = new Set(missing); + for (const cfg of tableConfigs) { + if (missingSet.size === 0) break; + const model = await cfg.getModel(factory, warehouseId); + if (!model) continue; + const rows = await model.findAll({ + attributes: [ 'delivery_order_code', 'source_platform_code', 'source_order_codes' ], + where: { + store_id: storeId, + [Op.or]: [ + { delivery_order_code: { [Op.in]: [ ...missingSet ] } }, + { source_platform_code: { [Op.in]: [ ...missingSet ] } }, + ...[ ...missingSet ].map(k => ({ source_order_codes: { [Op.like]: `%${k}%` } })), + ], + }, + raw: true, + }); + for (const r of rows) { + const codes = [ + r.delivery_order_code, + r.source_platform_code, + ...String(r.source_order_codes || '').split(','), + ].map(s => String(s || '').trim()).filter(Boolean); + for (const k of [ ...missingSet ]) { + if (codes.includes(k)) { + missingSet.delete(k); + notInPending.push(k); + } + } + } + } + for (const k of missingSet) notFound.push(k); + } + + // 第三步:区分可分配(已审核 step>=1 且未分配快递号 post_status=none) + const eligible = foundOrders.filter( + o => Number(o.step) >= 1 && String(o.post_status || '').trim() === 'none' + ); + const notReviewed = foundOrders.filter( + o => Number(o.step) < 1 && String(o.post_status || '').trim() === 'none' + ); + const allocated = foundOrders.filter(o => String(o.post_status || '').trim() !== 'none'); + + // 第四步:提交分配任务并轮询结果(复用已有分配运单号流程) + const successLines = []; + const failLines = []; + if (eligible.length > 0) { + const eligibleIds = eligible.map(o => o.id); + const originalUser = ctx.user; + ctx.user = { + ...(originalUser || {}), + store_id: warehouseId, + employees_id: 0, + employees_name: [ groupName, userName ].filter(Boolean).join('-') || 'AI系统', + }; + let taskId = ''; + try { + const submitResult = await ctx.service.systemMethods.order.pendingOrder.allocateExpressCode({ + ids: eligibleIds, + }); + taskId = String((submitResult && submitResult.task_id) || '').trim(); + } catch (submitErr) { + ctx.logger.warn(`[inbox functions] 分配快递号提交失败: ${submitErr.message}`); + taskId = ''; + } + + if (taskId) { + // 轮询任务进度(最多 40 次 × 1.5s = 60s) + let taskStatus = 'running'; + for (let attempt = 0; attempt < 40; attempt++) { + await new Promise(resolve => setTimeout(resolve, 1500)); + try { + const progressResult = await ctx.service.systemMethods.order.pendingOrder.allocateExpressCodeTaskProgress({ + task_id: taskId, + }); + taskStatus = String(progressResult && progressResult.status || '').trim(); + if ([ 'success', 'failed', 'not_found' ].includes(taskStatus)) break; + } catch (pollErr) { + ctx.logger.warn(`[inbox functions] 查询分配进度失败: ${pollErr.message}`); + taskStatus = 'failed'; + break; + } + } + + if (taskStatus === 'success') { + // 第五步:回查运单号(business_key=1 且 status=1) + const expressRows = await ctx.model.OrderExpress.findAll({ + attributes: [ 'order_id', 'waybill_code' ], + where: { + order_id: { [Op.in]: eligibleIds }, + warehouse_id: warehouseId, + business_key: 1, + status: 1, + }, + raw: true, + }); + const waybillByOrder = new Map(); + for (const er of expressRows) { + if (er.waybill_code) waybillByOrder.set(Number(er.order_id), String(er.waybill_code)); + } + + for (const o of eligible) { + const wb = waybillByOrder.get(Number(o.id)); + if (wb) { + successLines.push(`订单${o.delivery_order_code} 已分配:${wb}\n已回传`); + } else { + failLines.push(`订单${o.delivery_order_code} 分配失败,等待客服人工处理`); + } + } + } else { + for (const o of eligible) { + failLines.push(`订单${o.delivery_order_code} 分配失败,等待客服人工处理`); + } + } + } else { + for (const o of eligible) { + failLines.push(`订单${o.delivery_order_code} 分配失败,等待客服人工处理`); + } + } + ctx.user = originalUser; + } + + // 第六步:组装模板消息 + const lines = []; + if (successLines.length > 0) lines.push(successLines.join('\n')); + if (failLines.length > 0) lines.push(failLines.join('\n')); + if (notReviewed.length > 0) { + lines.push(`未审核,不能分配:${notReviewed.map(o => o.delivery_order_code).join('、')}`); + } + if (allocated.length > 0) { + lines.push(`已分配快递号:${allocated.map(o => `${o.delivery_order_code}(${o.logistics_name || '已取号'})`).join('、')}`); + } + if (notInPending.length > 0) { + lines.push(`不在待处理表,不能分配:${notInPending.join('、')}`); + } + if (notFound.length > 0) { + lines.push(`未找到订单:${notFound.join('、')}`); + } + + ctx.logger.info( + `[inbox functions] 分配快递号: total=${keywords.length} eligible=${eligible.length} ` + + `success=${successLines.length} fail=${failLines.length} notReviewed=${notReviewed.length}` + ); + + return { + success: true, + data: { + success_count: successLines.length, + fail_count: failLines.length, + message: lines.join('\n'), + direct_reply: true, + }, + }; + } catch (error) { + ctx.logger.error(`[inbox functions] 分配快递号失败: ${error.message}`); + return { success: false, error: `操作失败: ${error.message}` }; + } + }, + }); + + this.register('queryPackVideo', { + description: '打包视频查询。传入运单号,查询该运单对应的打包视频:散单按订单查打包记录,团购单按波次查打包记录。有视频返回视频地址;有打包记录无视频提示稍后再试;无打包记录提示无打包记录。仅查询,不创建工单', + weight: 86, + keywords: [ '打包视频', '打包录像', '装箱视频', '打包监控', '录像' ], + params: { + keyword: { type: 'string', required: true, description: '运单号,多个用逗号或空格分隔,如 SF111,SF222' }, + }, + groups: [ GROUP.BOUND_STORE_AFTER_SALES, GROUP.BOUND_WAREHOUSE_CUSTOMER_SERVICE ], + handler: async (params = {}) => { + const { ctx } = this; + const raw = String(params.keyword || '').trim(); + const storeId = Number(ctx.inboxContext?.store_id || 0); + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + const groupType = String(ctx.inboxContext?.group_type || '').trim(); + + if (!raw) return { success: false, error: '请提供运单号' }; + if (!warehouseId) return { success: false, error: '无法获取仓库信息' }; + + const keywords = raw.split(/[,,\s\n]+/).map(s => s.trim()).filter(Boolean); + if (keywords.length === 0) return { success: false, error: '未解析到有效运单号' }; + + // 前置拦截:AS 开头为售后工单号,不是运单号 + const asLikeList = keywords.filter(k => /^AS/i.test(k)); + if (asLikeList.length > 0) { + return { success: false, error: `${asLikeList.join('、')} 是售后工单号而非运单号,请提供运单号` }; + } + + try { + const { Op } = ctx.app.Sequelize; + + // 第一步:批量查询运单 + const expressList = await ctx.model.OrderExpress.findAll({ + attributes: [ 'id', 'waybill_code', 'store_id', 'order_id', 'logistics_name' ], + where: { + waybill_code: { [Op.in]: keywords }, + warehouse_id: warehouseId, + }, + raw: true, + }); + + const foundCodes = new Set(expressList.map(e => e.waybill_code)); + const notFound = keywords.filter(k => !foundCodes.has(k)); + + // 鉴权:货主群需验 store_id + const validList = []; + const skipped = []; + for (const e of expressList) { + if (groupType === 'store') { + if (!storeId || Number(e.store_id) !== storeId) { + skipped.push(e.waybill_code); + continue; + } + } + validList.push(e); + } + + if (validList.length === 0) { + const parts = []; + if (notFound.length > 0) parts.push(`未找到运单:${notFound.join('、')}`); + if (skipped.length > 0) parts.push(`无权操作:${skipped.join('、')}`); + return { + success: false, + error: parts.join(';') || `未找到运单号「${raw}」,请核实单号后重试`, + }; + } + + const videoLines = []; + const noVideoWbs = []; + const noRecordWbs = []; + const orderMissingWbs = []; + + for (const e of validList) { + // 第二步:查订单行(当前表 → 历史表 → 配送表),取波次信息 + let orderRow = null; + const tableGetters = [ + (f, wid) => f.getCurrentModel(wid), + (f, wid) => f.getHistoryModel(wid), + (f, wid) => f.getDispatchModel(wid), + ]; + for (const getModel of tableGetters) { + try { + const model = await getModel(ctx.model.OrderDeliveryFactory, warehouseId); + if (!model) continue; + orderRow = await model.findOne({ + attributes: [ 'id', 'wave_id', 'wave_no', 'pack_status' ], + where: { id: e.order_id }, + raw: true, + }); + } catch (err) { /* ignore */ } + if (orderRow) break; + } + + if (!orderRow) { + orderMissingWbs.push(e.waybill_code); + continue; + } + + // 第三步:判断团购/散单(wave_type=1 为团购波次) + let isGroupBuy = false; + if (Number(orderRow.wave_id) > 0) { + try { + const wave = await ctx.model.WaveBatch.findOne({ + attributes: [ 'wave_id', 'wave_type' ], + where: { wave_id: orderRow.wave_id }, + raw: true, + }); + if (wave && Number(wave.wave_type) === 1) isGroupBuy = true; + } catch (err) { /* ignore */ } + } + + // 第四步:团购按波次、散单按订单找打包记录 + const packWhere = isGroupBuy + ? { wave_id: orderRow.wave_id, deleted_at: null } + : { order_id: e.order_id, deleted_at: null }; + const packTasks = await ctx.model.PackTask.findAll({ + attributes: [ 'id', 'wave_id', 'wave_no', 'pack_mode', 'status' ], + where: packWhere, + raw: true, + }); + + if (packTasks.length === 0) { + noRecordWbs.push(e.waybill_code); + continue; + } + + // 第五步:查打包视频 + const taskIds = packTasks.map(t => t.id); + const videos = await ctx.model.PackTaskVideo.findAll({ + attributes: [ 'id', 'video_url', 'status' ], + where: { + pack_task_id: { [Op.in]: taskIds }, + deleted_at: null, + }, + raw: true, + }); + const urls = videos + .filter(v => String(v.status || '') !== 'failed') + .map(v => String(v.video_url || '').trim()) + .filter(Boolean); + + if (urls.length === 0) { + noVideoWbs.push(e.waybill_code); + } else { + videoLines.push(`${e.waybill_code}\n${urls.join('\n')}`); + } + } + + // 第六步:组装模板消息(仅查询,不建工单) + const lines = []; + if (videoLines.length > 0) { + lines.push(videoLines.join('\n')); + } + if (noVideoWbs.length > 0) { + lines.push(noVideoWbs.join('\n')); + lines.push('打包视频可能还未保存,请稍后再试'); + } + if (noRecordWbs.length > 0) { + lines.push(noRecordWbs.join('\n')); + lines.push('无打包记录'); + } + if (orderMissingWbs.length > 0) { + lines.push(`未找到订单:${orderMissingWbs.join('、')}`); + } + if (notFound.length > 0) { + lines.push(`未找到运单:${notFound.join('、')}`); + } + if (skipped.length > 0) { + lines.push(`无权操作:${skipped.join('、')}`); + } + + ctx.logger.info( + `[inbox functions] 打包视频查询: total=${keywords.length} found=${validList.length} ` + + `video=${videoLines.length} noVideo=${noVideoWbs.length} noRecord=${noRecordWbs.length}` + ); + + return { + success: true, + data: { + has_video: videoLines.length, + no_video: noVideoWbs.length, + no_record: noRecordWbs.length, + message: lines.join('\n'), + direct_reply: true, + }, + }; + } catch (error) { + ctx.logger.error(`[inbox functions] 打包视频查询失败: ${error.message}`); + return { success: false, error: `打包视频查询失败: ${error.message}` }; + } + }, + }); + + this.register('queryWeight', { + description: '查重(重量查询)。传入运单号,返回该运单的快递称重重量;重量为0或未称重时提示未称重。仅查询,不创建工单', + weight: 85, + keywords: [ '查重', '重量', '核实重量', '核重', '称重', '多重' ], + params: { + keyword: { type: 'string', required: true, description: '运单号,多个用逗号或空格分隔,如 SF111,SF222' }, + }, + groups: [ GROUP.BOUND_STORE_AFTER_SALES, GROUP.BOUND_WAREHOUSE_CUSTOMER_SERVICE ], + handler: async (params = {}) => { + const { ctx } = this; + const raw = String(params.keyword || '').trim(); + const storeId = Number(ctx.inboxContext?.store_id || 0); + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + const groupType = String(ctx.inboxContext?.group_type || '').trim(); + + if (!raw) return { success: false, error: '请提供运单号' }; + if (!warehouseId) return { success: false, error: '无法获取仓库信息' }; + + const keywords = raw.split(/[,,\s\n]+/).map(s => s.trim()).filter(Boolean); + if (keywords.length === 0) return { success: false, error: '未解析到有效运单号' }; + + // 前置拦截:AS 开头为售后工单号,不是运单号 + const asLikeList = keywords.filter(k => /^AS/i.test(k)); + if (asLikeList.length > 0) { + return { success: false, error: `${asLikeList.join('、')} 是售后工单号而非运单号,请提供运单号` }; + } + + try { + const { Op } = ctx.app.Sequelize; + const expressList = await ctx.model.OrderExpress.findAll({ + attributes: [ 'id', 'waybill_code', 'store_id', 'weighing_weight' ], + where: { + waybill_code: { [Op.in]: keywords }, + warehouse_id: warehouseId, + }, + raw: true, + }); + + const foundCodes = new Set(expressList.map(e => e.waybill_code)); + const notFound = keywords.filter(k => !foundCodes.has(k)); + + // 鉴权:货主群需验 store_id + const validList = []; + const skipped = []; + for (const e of expressList) { + if (groupType === 'store') { + if (!storeId || Number(e.store_id) !== storeId) { + skipped.push(e.waybill_code); + continue; + } + } + validList.push(e); + } + + if (validList.length === 0) { + const parts = []; + if (notFound.length > 0) parts.push(`未找到运单:${notFound.join('、')}`); + if (skipped.length > 0) parts.push(`无权操作:${skipped.join('、')}`); + return { + success: false, + error: parts.join(';') || `未找到运单号「${raw}」,请核实单号后重试`, + }; + } + + // 组装模板:每个运单一行,只输出重量;重量为0 → 未称重 + const lines = []; + for (const e of validList) { + const weight = Number(e.weighing_weight) || 0; + lines.push(weight > 0 ? `${e.waybill_code}:${weight}g` : `${e.waybill_code}:未称重`); + } + if (notFound.length > 0) { + lines.push(`未找到运单:${notFound.join('、')}`); + } + if (skipped.length > 0) { + lines.push(`无权操作:${skipped.join('、')}`); + } + + ctx.logger.info( + `[inbox functions] 查重: total=${keywords.length} found=${validList.length} ` + + `notFound=${notFound.length} skipped=${skipped.length}` + ); + + return { + success: true, + data: { + waybills: validList.map(e => e.waybill_code), + message: lines.join('\n'), + direct_reply: true, + }, + }; + } catch (error) { + ctx.logger.error(`[inbox functions] 查重失败: ${error.message}`); + return { success: false, error: `查重失败: ${error.message}` }; + } + }, + }); + this.register('handleExpressFeedback', { description: '快递群售后通用反馈。传入运单号,优先找已有售后工单追加记录,无工单则按运单查订单并自动创建售后工单。AI 可根据快递反馈内容传入售后类型和子类型', weight: 90, @@ -2564,7 +3378,8 @@ class InboxFunctionsService extends Service { `快递公司: ${e.logistics_name || '未知'}`, `售后类型: ${asType}.${asSubType}`, '来源: 快递群反馈', - ].join('\n'); + feedbackMsgContent ? `原文: ${feedbackMsgContent}` : '', + ].filter(Boolean).join('\n'); await ctx.service.systems.afterSale.create({ warehouse_id: warehouseId, @@ -2644,7 +3459,36 @@ class InboxFunctionsService extends Service { // - 已有工单且带 inbox_message_id → 查原始消息获取群信息 → 回信到原群 // - 无工单或无 inbox_message_id → 回信到货主售后群 replyTargets = new Map(); // group_id → { group_id, group_name, user_id, ext_data } - const replyMsg = parts.join(';') || '处理完成'; + // 未命中排除关键词 → 直接反馈原文(按目标货主过滤掉其他货主的运单号) + const baseContent = feedbackMsgContent || (parts.join(';') || '处理完成'); + + // 运单号 → 货主ID 映射(用于按货主过滤原文中的运单号) + const waybillStoreMap = new Map(); + for (const e of expressList) { + if (e.waybill_code) waybillStoreMap.set(e.waybill_code, e.store_id ? Number(e.store_id) : null); + } + for (const as of existingAS) { + if (as.waybill_no && !waybillStoreMap.has(as.waybill_no) && as.store_id) { + waybillStoreMap.set(as.waybill_no, Number(as.store_id)); + } + } + + /** + * 从反馈原文中移除属于其他货主的运单号。 + * @param {string} content 原始文本。 + * @param {number|null} targetStoreId 目标货主ID,为空则不过滤。 + * @return {string} 过滤后的文本。 + */ + const filterOtherStoreWaybills = (content, targetStoreId) => { + if (!content || !targetStoreId) return content || ''; + let text = String(content); + for (const [ wb, sid ] of waybillStoreMap) { + if (sid && sid !== targetStoreId) { + text = text.split(wb).join(''); + } + } + return text.replace(/[ \t]+/g, ' ').replace(/\n{3,}/g, '\n\n').trim(); + }; // 4a. 已有工单带 inbox_message_id:回信到原消息所在群(排除快递群) const asWithMsgId = existingAS.filter(as => as.inbox_message_id); @@ -2659,17 +3503,22 @@ class InboxFunctionsService extends Service { }); // 过滤快递群:原消息来自快递群的,不回信到快递群,走 4b 货主售后群 const candidateGroupIds = [ ...new Set(messages.map(m => m.group_id).filter(Boolean)) ]; + let groupStoreMap = {}; if (candidateGroupIds.length > 0) { - const expressGroups = await ctx.model.InboxGroup.findAll({ - attributes: [ 'group_id' ], + const groupRows = await ctx.model.InboxGroup.findAll({ + attributes: [ 'group_id', 'group_type', 'store_id' ], where: { group_id: { [ctx.app.Sequelize.Op.in]: candidateGroupIds }, warehouse_id: warehouseId, - group_type: 'express', }, raw: true, }); - expressGroupIds = new Set(expressGroups.map(g => g.group_id)); + expressGroupIds = new Set( + groupRows.filter(g => g.group_type === 'express').map(g => g.group_id) + ); + groupStoreMap = Object.fromEntries( + groupRows.filter(g => g.store_id).map(g => [ g.group_id, Number(g.store_id) ]) + ); } for (const msg of messages) { if (msg.group_id && !replyTargets.has(msg.group_id) && !expressGroupIds.has(msg.group_id)) { @@ -2679,6 +3528,7 @@ class InboxFunctionsService extends Service { user_id: msg.user_id || '', user_name: msg.user_name || '', ext_data: null, + store_id: groupStoreMap[msg.group_id] || null, }); } } @@ -2722,6 +3572,7 @@ class InboxFunctionsService extends Service { user_id: '', user_name: '', ext_data: g.ext_data || null, + store_id: g.store_id || null, }); } } @@ -2730,14 +3581,17 @@ class InboxFunctionsService extends Service { } } - // 3c. 发送回信 + // 3c. 发送回信(直接反馈原文,按目标货主过滤其他货主的运单号) for (const [ , target ] of replyTargets) { + const content = filterOtherStoreWaybills(baseContent, target.store_id); + if (!content) continue; ctx.service.inbox.processor.pushSystemNotification({ warehouse_id: warehouseId, group_id: target.group_id, group_name: target.group_name, - content: `快递反馈: ${replyMsg}`, + content, ext_data: target.ext_data, + store_id: target.store_id || null, }); } diff --git a/app/service/inbox/processor.js b/app/service/inbox/processor.js index 152d2b1..da1f138 100644 --- a/app/service/inbox/processor.js +++ b/app/service/inbox/processor.js @@ -4,6 +4,9 @@ const Service = require('egg').Service; const WAREHOUSE_INTERFACE_TYPE_ID = 3; +/** 历史消息过滤默认阈值:发送时间距今超过 10 分钟视为历史/补推消息,跳过 AI(可用 config.inbox.historyMessageMaxAgeMs 覆盖) */ +const DEFAULT_HISTORY_MESSAGE_MAX_AGE_MS = 10 * 60 * 1000; + /** * 站内信内容处理器。 * 负责解析入站消息正文,按 source_type 分流处理, @@ -73,6 +76,29 @@ class InboxProcessorService extends Service { this._groupCache.set(cacheKey, info); return info; } + + /** + * 判断消息是否为历史消息(发送时间距今超过阈值)。 + * - flags.skipAi === true:外部显式要求跳过 AI。 + * - flags.send_time 距今超过 config.inbox.historyMessageMaxAgeMs:视为历史/补推消息。 + * - 未携带发送时间:按实时消息处理(向后兼容)。 + * @param {Object} data 入站消息数据。 + * @return {boolean} 是否应跳过 AI 处理。 + */ + isStaleMessage(data = {}) { + const flags = data.flags || {}; + if (flags.skipAi === true) return true; + + const sendTime = Number(flags.send_time || 0); + if (!Number.isFinite(sendTime) || sendTime <= 0) return false; + + const maxAgeMs = Number(this.app.config.inbox?.historyMessageMaxAgeMs); + const threshold = Number.isFinite(maxAgeMs) && maxAgeMs > 0 + ? maxAgeMs + : DEFAULT_HISTORY_MESSAGE_MAX_AGE_MS; + + return Date.now() - sendTime > threshold; + } /** * 处理入站消息内容。 * 解析 content 后将 warehouse_id 和 store_id 写入 ctx 上下文。 @@ -162,6 +188,12 @@ class InboxProcessorService extends Service { return; } + // 2.5 历史消息过滤:发送时间距今超过阈值的历史/补推消息不触发绑群与 AI,防止误建工单 + if (this.isStaleMessage(data)) { + ctx.logger.info(`[inbox processor] 历史消息,跳过 AI 处理 ext_id=${extId}`); + return; + } + // 3. 绑群码识别:消息匹配"授权:CODE"时执行绑群 const bindHandled = await this.tryBindGroup(data); if (bindHandled) return; @@ -419,7 +451,7 @@ class InboxProcessorService extends Service { } else { const created = await InboxMessage.create({ ext_id: ackExtId, warehouse_id: warehouseId, - store_id: ctx.inboxContext?.store_id || null, + store_id: Number(data.store_id) || ctx.inboxContext?.store_id || null, direction: 'outbound', parent_id: parentId || null, source_type: 'system', source_extra: null, target_type: 'api', @@ -687,6 +719,8 @@ class InboxProcessorService extends Service { * @param {string} data.group_name 目标群名称。 * @param {string} data.content 通知内容。 * @param {Object} [data.ext_data] 群扩展数据(渠道信息)。 + * @param {number} [data.store_id] 目标货主ID(用于写入回信记录的 store_id)。 + * @return {void} 无返回值,异步写入与推送。 */ pushSystemNotification(data = {}) { const { ctx } = this; @@ -695,6 +729,7 @@ class InboxProcessorService extends Service { const groupName = String(data.group_name || '').trim(); const content = String(data.content || '').trim(); const extData = data.ext_data || null; + const storeId = Number(data.store_id) || null; if (!warehouseId || !groupId || !content) return; @@ -708,6 +743,7 @@ class InboxProcessorService extends Service { user_id: '', group_name: groupName, user_name: '', + store_id: storeId, }; // 写库 + POST,异步不阻塞 diff --git a/app/service/inbox/receiver.js b/app/service/inbox/receiver.js index 4a7e279..4eaab68 100644 --- a/app/service/inbox/receiver.js +++ b/app/service/inbox/receiver.js @@ -28,6 +28,7 @@ class InboxReceiverService extends Service { * @param {string} [data.content] 消息正文/摘要。 * @param {Object} [data.ext_data] 透传数据。 * @param {Object} [data.flags] 处理标记。 + * @param {number} [data.send_time] 消息原始发送时间(毫秒时间戳,可选,用于历史消息过滤)。 * @return {Promise<{ok: boolean, id: number, ext_id: string}>} 接收结果。 */ async receive(data = {}) { @@ -96,6 +97,15 @@ class InboxReceiverService extends Service { throw new Error(`消息体超过 64KB 限制(当前 ${Math.round(bodySize / 1024)}KB)`); } + // flags 合并:消息发送时间统一存入 flags.send_time(毫秒),供 AI 历史消息过滤 + const flags = { ...(data.flags || {}) }; + if (!flags.send_time && data.send_time != null) { + const sendTime = Number(data.send_time); + if (Number.isFinite(sendTime) && sendTime > 0) { + flags.send_time = Math.floor(sendTime); + } + } + // 从群绑定查询货主ID(外部不再直接传入 store_id) let storeId = null; const extGroupId = String(data.group_id || '').trim(); @@ -130,7 +140,7 @@ class InboxReceiverService extends Service { user_id: data.user_id || null, content: data.content || null, ext_data: data.ext_data || null, - flags: data.flags || {}, + flags, }); ctx.logger.info(`[inbox] 消息入库成功 ext_id=${extId} id=${record.id}`); @@ -168,6 +178,7 @@ class InboxReceiverService extends Service { user_name: data.user_name || null, group_id: data.group_id || null, user_id: data.user_id || null, + flags, }).catch(err => { ctx.logger.error(`[inbox] API 异步回执异常 ext_id=${extId}: ${err.message}`); }); diff --git a/app/service/systemMethods/afterSale.js b/app/service/systemMethods/afterSale.js index 1340900..e8d670c 100644 --- a/app/service/systemMethods/afterSale.js +++ b/app/service/systemMethods/afterSale.js @@ -81,6 +81,8 @@ class AfterSaleMethodService extends MainService { const result = await service.systems.afterSale.list(enforcedWhere, pagination, sort, { order: [[ 'priority', 'DESC' ], [ 'updated_at', 'DESC' ]], excludeFutureFollowup: true, + // 列表行补充货主名称 store_name(合约表 store_remask 货主备注,无备注时回退货主公司全称) + enrichStoreName: true, }); return this.success('ok', result); } diff --git a/app/service/systems/afterSale.js b/app/service/systems/afterSale.js index 3732ead..209e6b9 100644 --- a/app/service/systems/afterSale.js +++ b/app/service/systems/afterSale.js @@ -36,6 +36,7 @@ class AfterSaleService extends Service { * @param {Object} [opts] 额外选项 * @param {Array} [opts.order] 自定义 Sequelize order(优先于 sort) * @param {boolean} [opts.excludeFutureFollowup] 是否排除 followup_at 未到的 pending_feedback 工单 + * @param {boolean} [opts.enrichStoreName] 是否补充每行 store_name 货主名称(合约表货主备注 store_remask,无备注时回退货主公司全称) * @return {Promise} { list: Array, pagination: Object } */ async list(where = {}, pagination = {}, sort = {}, opts = {}) { @@ -87,6 +88,11 @@ class AfterSaleService extends Service { const list = rows.map(row => this._formatAfterSaleRow(row, app)); + // 工作列表:批量补充货主名称(合约表 store_remask 货主备注,无备注时回退货主公司全称) + if (opts.enrichStoreName && list.length > 0) { + await this._enrichListStoreNames(list); + } + return { list, pagination: { @@ -282,6 +288,8 @@ class AfterSaleService extends Service { /** * 售后单明细查询,包含主表信息、步骤列表及附件。 + * 售后主表 description(详细描述)非空时,默认作为第一条 step 输出 + * (虚拟步骤:id=null、is_virtual=true、action=售后描述、remark=description,不落库)。 * 若关联了订单(order_delivery_id),自动补充收件人/发件人/订单明细/打包视频。 * 若关联了货主(store_id),自动补充货主合约备注。 * @@ -318,13 +326,32 @@ class AfterSaleService extends Service { // 补充关联单据详情 const related = await this._enrichAfterSaleDetail(afterSale); - // 开始处理时间:取首条步骤记录的创建时间 - const firstStep = stepsWithAttachments[0]; + // 默认详细描述作为第一条 step 输出(虚拟步骤,不落库) + let finalSteps = stepsWithAttachments; + if (afterSale.description && String(afterSale.description).trim()) { + finalSteps = [{ + id: null, + after_sale_id: afterSale.id, + step_status: 'pending', + operator_id: null, + operator_snapshot: null, + action: '售后描述', + remark: afterSale.description, + started_at: null, + completed_at: null, + created_at: afterSale.created_at, + attachments: [], + is_virtual: true, + }, ...stepsWithAttachments ]; + } + + // 开始处理时间:取首条真实步骤记录的创建时间(不含默认描述虚拟步骤) + const firstStep = steps[0]; const startedAt = firstStep ? (firstStep.created_at ? app.formatDate(firstStep.created_at) : null) : null; return { after_sale: { ...formatRow(afterSale), started_at: startedAt }, - steps: stepsWithAttachments.map(formatRow), + steps: finalSteps.map(formatRow), related, }; } @@ -782,6 +809,63 @@ class AfterSaleService extends Service { return this._formatAfterSaleRow(json, app); } + /** + * 批量补充列表行的货主名称 store_name。 + * 货主名称优先取合约表 wms_store_warehouse.store_remask(货主备注名称), + * 无合约或备注为空时回退 wms_store.company_name(公司全称)。 + * + * @param {Object[]} list 售后单列表行(原地补充 store_name 字段) + * @return {Promise} + */ + async _enrichListStoreNames(list) { + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + + const storeIds = [ ...new Set(list.map(row => row.store_id).filter(Boolean)) ]; + const warehouseIds = [ ...new Set(list.map(row => row.warehouse_id).filter(Boolean)) ]; + + if (storeIds.length === 0) { + list.forEach(row => { + row.store_name = ''; + }); + return; + } + + // 1. 合约表货主备注名称(store_id + warehouse_id 维度) + let contractMap = {}; + if (warehouseIds.length > 0) { + const swRows = await ctx.model.StoreWarehouse.findAll({ + where: { + store_id: { [Op.in]: storeIds }, + warehouse_id: { [Op.in]: warehouseIds }, + }, + attributes: [ 'store_id', 'warehouse_id', 'store_remask' ], + raw: true, + }); + contractMap = swRows.reduce((acc, sw) => { + acc[`${sw.store_id}_${sw.warehouse_id}`] = sw.store_remask || ''; + return acc; + }, {}); + } + + // 2. 货主公司全称兜底 + let storeMap = {}; + const storeRows = await ctx.model.Store.findAll({ + where: { id: { [Op.in]: storeIds } }, + attributes: [ 'id', 'company_name' ], + raw: true, + }); + storeMap = storeRows.reduce((acc, store) => { + acc[store.id] = store.company_name || ''; + return acc; + }, {}); + + list.forEach(row => { + const contractRemask = contractMap[`${row.store_id}_${row.warehouse_id}`] || ''; + row.store_name = contractRemask || storeMap[row.store_id] || ''; + }); + } + // =========================== // 更新售后单 // =========================== diff --git a/app/service/systems/return_unpack.js b/app/service/systems/return_unpack.js index 4a5bd96..134dd86 100644 --- a/app/service/systems/return_unpack.js +++ b/app/service/systems/return_unpack.js @@ -64,7 +64,66 @@ class ReturnUnpackService extends Service { .filter(id => Number.isInteger(id) && id > 0); } - // 1. 原单反查:命中则回填原单关联字段 + // 1. 幂等复用:同一仓库同一运单号 3 个月内已开过拆包单时,不重复创建,直接返回已有明细 + const threeMonthsAgo = new Date(); + threeMonthsAgo.setMonth(threeMonthsAgo.getMonth() - 3); + try { + const existingList = await ctx.model.ReturnUnpack.findAll({ + where: { + warehouse_id: warehouseId, + waybill_code: waybillCode, + created_at: { [Op.gte]: threeMonthsAgo }, + status: { [Op.ne]: 'cancelled' }, + }, + attributes: [ 'id', 'order_express_id', 'created_at' ], + order: [[ 'created_at', 'DESC' ], [ 'id', 'DESC' ]], + raw: true, + }); + + let existing = null; + if (existingList.length > 0) { + existing = existingList[0]; + // 同运单号可能有多张拆包单(并发/重复点击产生的空单):优先复用已录明细的最新单, + // 避免命中最新空单导致"返回明细为空"(按明细表真实计数判断,不依赖主表冗余汇总) + const countRows = await ctx.model.ReturnUnpackDetail.findAll({ + where: { unpack_id: { [Op.in]: existingList.map(row => row.id) } }, + attributes: [ + 'unpack_id', + [ ctx.model.fn('COUNT', ctx.model.col('id')), 'detail_count' ], + ], + group: [ 'unpack_id' ], + raw: true, + }); + const detailCountMap = new Map( + countRows.map(row => [ Number(row.unpack_id), Number(row.detail_count) || 0 ]) + ); + const withDetails = existingList.find(row => (detailCountMap.get(Number(row.id)) || 0) > 0); + if (withDetails) { + existing = withDetails; + } + } + + if (existing) { + // 复用已有拆包单:返回主表 + 明细 + 视频 + 原订单详情(复用 detail 查询逻辑) + const existingDetail = await this.detail(existing.id); + ctx.logger.info( + `[returnUnpack.create] 运单号 ${waybillCode} 3 个月内已有拆包单 id=${existing.id},直接复用返回明细` + ); + return { + id: existing.id, + record: existingDetail.record, + is_original_return: Boolean(existing.order_express_id), + store_remark: String(existingDetail.record && existingDetail.record.shop_name || ''), + order: (existingDetail.related && existingDetail.related.order) || null, + reused: true, + }; + } + } catch (err) { + // 查重失败不阻断开单主流程 + ctx.logger.warn(`[returnUnpack.create] 查重已有拆包单失败: ${err.message}`); + } + + // 2. 原单反查:命中则回填原单关联字段 let orderExpressId = null; let orderId = null; let storeId = null; @@ -85,11 +144,9 @@ class ReturnUnpackService extends Service { ctx.logger.warn(`[returnUnpack.create] 反查原运单失败: ${err.message}`); } - // 2. 未命中原单:从退回查询记录表反查货主(限最近 3 个月内登记,运单号可能被复用) + // 3. 未命中原单:从退回查询记录表反查货主(限最近 3 个月内登记,运单号可能被复用) if (!orderExpressId) { try { - const threeMonthsAgo = new Date(); - threeMonthsAgo.setMonth(threeMonthsAgo.getMonth() - 3); const queryLog = await ctx.model.ReturnQueryLog.findOne({ where: { warehouse_id: warehouseId, @@ -110,14 +167,14 @@ class ReturnUnpackService extends Service { const isOriginalReturn = Boolean(orderExpressId); - // 3. 货主备注(原单退回 / 反查命中货主时) + // 4. 货主备注(原单退回 / 反查命中货主时) const storeRemark = await this._resolveStoreRemark(storeId, warehouseId); - // 4. 拆包日期/开始时间(单号在下方重试循环内生成) + // 5. 拆包日期/开始时间(单号在下方重试循环内生成) const now = new Date(); const unpackDate = app.formatDate(now, 'YYYY-MM-DD'); - // 5. 插入主表(并发下撞 uk_unpack_no 唯一索引时重新取号重试,最多 5 次,指数退避+随机抖动) + // 6. 插入主表(并发下撞 uk_unpack_no 唯一索引时重新取号重试,最多 5 次,指数退避+随机抖动) const baseFields = { warehouse_id: warehouseId, return_received_id: return_received_id ? Number(return_received_id) || null : null, @@ -167,7 +224,7 @@ class ReturnUnpackService extends Service { const createdRow = created && typeof created.toJSON === 'function' ? created.toJSON() : created; - // 6. 原订单详情(仅原单退回时拉取,参考 afterSale.detail._resolveOrderDetail) + // 7. 原订单详情(仅原单退回时拉取,参考 afterSale.detail._resolveOrderDetail) let order = null; if (isOriginalReturn && orderId) { try { @@ -280,6 +337,7 @@ class ReturnUnpackService extends Service { const summary = await this._recalcMain(unpack.id, unpack.warehouse_id); const createdRow = created && typeof created.toJSON === 'function' ? created.toJSON() : created; + await this._enrichDetailsWithStock([ createdRow ], Number(unpack.warehouse_id || 0)); return { detail_id: createdRow.id, detail: createdRow, @@ -320,6 +378,7 @@ class ReturnUnpackService extends Service { } if (Object.keys(updateFields).length === 0) { + await this._enrichDetailsWithStock([ detail ], Number(unpack.warehouse_id || 0)); return { detail, total_items: unpack.total_items, @@ -346,6 +405,7 @@ class ReturnUnpackService extends Service { summary = await this._recalcMain(unpack.id, unpack.warehouse_id); } + await this._enrichDetailsWithStock([ updated ], Number(unpack.warehouse_id || 0)); return { detail: updated, ...summary, @@ -529,6 +589,10 @@ class ReturnUnpackService extends Service { const list = rows.map(row => (row && typeof row.toJSON === 'function' ? row.toJSON() : row)); + // 明细批量附加库存详情(条码/图片等,统一走 stockWarehouse.getStockDetails 通用方法) + const listWarehouseId = list.length > 0 ? Number(list[0].warehouse_id || 0) : 0; + await this._enrichDetailsWithStock(list, listWarehouseId); + return { list, pagination: { @@ -592,6 +656,14 @@ class ReturnUnpackService extends Service { const recordJson = record && typeof record.toJSON === 'function' ? record.toJSON() : record; + // 明细批量附加库存详情(条码/图片等,统一走 stockWarehouse.getStockDetails 通用方法) + if (recordJson && Array.isArray(recordJson.details)) { + recordJson.details = await this._enrichDetailsWithStock( + recordJson.details, + Number(recordJson.warehouse_id || 0) + ); + } + // 原订单详情(仅原单退回时返回) let relatedOrder = null; if (recordJson && recordJson.order_id) { @@ -1132,6 +1204,50 @@ class ReturnUnpackService extends Service { return record; } + /** + * 批量附加库存详情(条码/图片等)到明细行。 + * 统一走 stockWarehouse.getStockDetails 通用方法(带缓存,含 barcodes/image_url/ + * packing_requirements/stock_unit 等字段),为每条有 stock_id 的明细补充 stock 字段; + * 商品失效或查询失败时 stock 为 null(不影响主流程)。 + * + * @param {Array} details 明细行数组(含 stock_id,就地补充 stock 字段)。 + * @param {number} warehouseId 仓库ID(用于库存详情查询的仓库过滤)。 + * @return {Promise>} 补充 stock 字段后的明细行数组。 + */ + async _enrichDetailsWithStock(details, warehouseId) { + const { ctx } = this; + if (!Array.isArray(details) || details.length === 0) { + return details || []; + } + + const stockIds = [ ...new Set( + details + .map(row => Number(row.stock_id)) + .filter(sid => Number.isInteger(sid) && sid > 0) + ) ]; + + /** @type {Map} */ + const stockMap = new Map(); + if (stockIds.length > 0) { + try { + const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(stockIds, { warehouseId }); + for (const detail of stockDetails) { + if (detail && detail.id != null) { + stockMap.set(Number(detail.id), detail); + } + } + } catch (err) { + ctx.logger.warn(`[returnUnpack._enrichDetailsWithStock] 批量获取库存详情失败: ${err.message}`); + } + } + + for (const row of details) { + const stockId = Number(row.stock_id); + row.stock = stockId > 0 ? (stockMap.get(stockId) || null) : null; + } + return details; + } + /** * 查询货主合约备注名称(wms_store_warehouse.store_remask)。 * diff --git a/app/service/warehouseMethods/inbox.js b/app/service/warehouseMethods/inbox.js index 5de365b..2427ed6 100644 --- a/app/service/warehouseMethods/inbox.js +++ b/app/service/warehouseMethods/inbox.js @@ -32,6 +32,9 @@ class WarehouseInboxService extends MainService { // 构造 ext_id const extId = `api:${String(appKey || 'unknown')}:${String(body.requestId).trim()}`; + // 解析消息原始发送时间(可选,用于历史消息过滤) + const sendTime = this.parseSendTime(body.sendTime); + // 构造入站数据并委托给 inbox receiver const result = await ctx.service.inbox.receiver.receive({ ext_id: extId, @@ -48,10 +51,28 @@ class WarehouseInboxService extends MainService { content: body.content || null, ext_data: body.extData || null, flags: body.flags || {}, + send_time: sendTime, }); return result; } + + /** + * 解析外部传入的消息发送时间。 + * 支持毫秒时间戳、秒时间戳、ISO 时间字符串;解析失败返回 null。 + * @param {number|string|null} value 外部传入的 sendTime。 + * @return {number|null} 毫秒时间戳,解析失败返回 null。 + */ + parseSendTime(value) { + if (value == null || value === '') return null; + if (typeof value === 'number' && Number.isFinite(value)) { + if (value > 1e12) return Math.floor(value); // 毫秒 + if (value > 1e8) return Math.floor(value * 1000); // 秒 + return null; + } + const ms = Date.parse(String(value)); + return Number.isFinite(ms) ? ms : null; + } } module.exports = WarehouseInboxService; diff --git a/config/config.default.js b/config/config.default.js index 9561698..ac5bf8b 100644 --- a/config/config.default.js +++ b/config/config.default.js @@ -56,6 +56,8 @@ module.exports = appInfo => { // 站内信模块配置 config.inbox = { imageBaseUrl: '', // 商品图片域名,为空时用请求 ctx.host + // 历史消息过滤:消息原始发送时间距今超过该阈值(毫秒)则跳过 AI 处理,防止补推历史消息被当成新工单 + historyMessageMaxAgeMs: 10 * 60 * 1000, }; config.tencentCloud = { diff --git a/methods/changes/system.json b/methods/changes/system.json index a8a50b5..564d4f3 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,74 @@ [ + { + "version": "2026.08.14-afterSale.detail-desc-first-step", + "date": "2026-08-14", + "type": "enhanced", + "summary": "enhance: afterSale.detail 步骤列表默认将售后详细描述作为第一条 step 输出(虚拟步骤不落库),保证详情页首条即可看到售后问题描述。", + "methods": [ + "afterSale.detail" + ], + "notes": [ + "售后主表 description 非空时,steps 列表头部前置一条虚拟步骤:action=售后描述、remark=description、step_status=pending、created_at=主表创建时间、attachments=[]、is_virtual=true、id=null", + "虚拟步骤不写入 wms_after_sale_detail,仅在 detail 响应中动态拼接", + "after_sale.started_at 仍取首条真实步骤记录的创建时间,不受虚拟步骤影响", + "description 为空时不生成虚拟步骤,行为与之前一致", + "同步更新 methods/system.json 中 afterSale.detail 的 steps 字段说明" + ], + "module": "afterSale" + }, + { + "version": "2026.08.14-afterSale.workList-storeName", + "date": "2026-08-14", + "type": "changed", + "summary": "afterSale.workList 返回列表行新增 store_name 货主名称字段:取合约表 wms_store_warehouse.store_remask 货主备注名称,无合约或备注为空时回退 wms_store.company_name 公司全称,无货主时为空字符串", + "methods": [ + "afterSale.workList" + ], + "notes": [ + "systems/afterSale.js list() 新增 opts.enrichStoreName 开关,开启后调用新增私有方法 _enrichListStoreNames 批量补充:按行收集 store_id/warehouse_id,一次查询 StoreWarehouse(store_remask)与 Store(company_name),映射后写入每行 store_name", + "systemMethods/afterSale.js workList 调用 list 时传 enrichStoreName: true;auditList 不受影响", + "向后兼容:仅在列表行新增 store_name 字段,不影响既有字段", + "同步更新 methods/system.json 中 afterSale.workList 的 response.list 字段说明" + ], + "module": "afterSale" + }, + { + "version": "2026.08.14-returnUnpack.stockDetails", + "date": "2026-08-14", + "type": "changed", + "summary": "returnUnpack 明细补充库存详情:detail/detailList/addDetail/updateDetail 返回的明细行统一走 stockWarehouse.getStockDetails 通用方法附加 stock 字段(item_code/item_name/sku_property/barcodes 条码数组/image_url 图片数组/packing_requirements/stock_unit/quantity/locked_quantity 等,带缓存),补齐条码与照片信息;create 幂等复用返回的 record.details 同步受益", + "methods": [ + "returnUnpack.detail", + "returnUnpack.detailList", + "returnUnpack.addDetail", + "returnUnpack.updateDetail", + "returnUnpack.create" + ], + "notes": [ + "systems/return_unpack.js 新增私有方法 _enrichDetailsWithStock:收集明细 stock_id 批量调用 stockWarehouse.getStockDetails(缓存 key cache:stock_detail:{warehouseId}:{stockId}),按 stock_id 映射为明细行 stock 字段;未识别明细(stock_id 为空)/商品失效/拉取失败时 stock=null,不影响主流程", + "detail:record.details 逐条附加 stock;detailList:list 逐条附加 stock(取首行 warehouse_id 作为查询仓库);addDetail/updateDetail:返回 detail 附加 stock(用主表 warehouse_id)", + "向后兼容:明细行原有字段与 stockWarehouse 关联保持不变,仅新增 stock 字段", + "同步更新 methods/system.json 中 create/detail/detailList/addDetail/updateDetail 的响应字段说明" + ], + "module": "returnUnpack" + }, + { + "version": "2026.08.14-returnUnpack.createReuse", + "date": "2026-08-14", + "type": "changed", + "summary": "returnUnpack.create 增加幂等复用:同一仓库同一运单号 3 个月内已存在非 cancelled 拆包单时不重复创建,直接返回已有拆包单的主表+明细(record.details)+视频+原订单详情,并携带 reused=true 标识;同运单号多张拆包单时优先复用已录明细的最新单;超过 3 个月视为运单号复用,按新单正常创建", + "methods": [ + "returnUnpack.create" + ], + "notes": [ + "开单前先按 warehouse_id+waybill_code+created_at>=3个月前 查全部非 cancelled 拆包单(created_at DESC, id DESC)", + "同运单号存在多张拆包单时优先复用已录明细的最新单(按 wms_return_unpack_detail 真实计数判定,不依赖主表冗余 total_items),避免命中并发/重复点击产生的空单导致返回明细为空;全部无明细时复用最新单", + "命中时复用 detail 查询逻辑组装 record(含 details 明细+stockWarehouse 关联、videos、returnReceived)与 related.order,返回字段新增 reused=true", + "查重失败仅记日志不阻断开单主流程;3 个月时间基准与退回查询记录反查货主窗口一致", + "同步更新 methods/system.json 中 returnUnpack.create 的 description 与 response(record/reused 字段说明)" + ], + "module": "returnUnpack" + }, { "version": "2026.08.14-warehouse-receive-address", "date": "2026-08-14", diff --git a/methods/changes/warehouse.json b/methods/changes/warehouse.json index 59ca781..ce92c46 100644 --- a/methods/changes/warehouse.json +++ b/methods/changes/warehouse.json @@ -64,5 +64,22 @@ "source_type 从 body.sourceType || 'api' 改为硬编码 'api'", "文档移除 sourceType 参数,description 补注 source_type 固定为 api" ] + }, + { + "version": "2026-08-14-warehouse-01", + "date": "2026-08-14", + "type": "changed", + "summary": "inbox.push 新增 sendTime 参数与历史消息过滤:外部补推的历史消息不再触发 AI 自动处理(防止误建工单)", + "methods": [ + "inbox.push" + ], + "notes": [ + "inbox.push 新增可选参数 sendTime:消息原始发送时间(毫秒/秒时间戳或 ISO 字符串),由 warehouseMethods/inbox.js parseSendTime 统一规范化为毫秒", + "send_time 统一存入 wms_inbox_message.flags.send_time(毫秒),flags.send_time 与 sendTime 参数等价", + "processor.handleApiMessage 新增历史消息过滤:flags.skipAi=true 或 send_time 距今超过 config.inbox.historyMessageMaxAgeMs(默认 10 分钟)→ 跳过绑群与 AI 处理,不自动回复、不创建工单", + "未传 sendTime 的消息按实时消息处理,保持向后兼容", + "过滤点位于屏蔽检查之后、绑群码识别之前,仅拦截自动处理链路" + ], + "module": "inbox" } ] diff --git a/methods/system.json b/methods/system.json index 07325d3..13a2742 100644 --- a/methods/system.json +++ b/methods/system.json @@ -34119,7 +34119,7 @@ "name": "list", "type": "array", "required": true, - "description": "售后单列表,每条含主表字段 + detail_count" + "description": "售后单列表,每条含主表字段 + detail_count + store_name(货主名称:取合约表 wms_store_warehouse.store_remask 货主备注名称,无合约或备注为空时回退 wms_store.company_name 公司全称,无货主时为空字符串)" }, { "name": "pagination", @@ -34198,11 +34198,11 @@ "name": "steps", "type": "array", "required": true, - "description": "售后进度步骤列表(含附件 attachments),按创建时间升序", + "description": "售后进度步骤列表(含附件 attachments),按创建时间升序。售后主表 description(详细描述)非空时,列表第一条为默认描述虚拟步骤(action=售后描述、remark=详细描述、step_status=pending、created_at=主表创建时间、id=null、is_virtual=true、attachments=[],不落库)", "list": [ { "value": "object", - "label": "{ id, after_sale_id, step_status, operator_id, action, remark, attachments: [{id,file_url,file_name}] }" + "label": "{ id, after_sale_id, step_status, operator_id, action, remark, is_virtual, attachments: [{id,file_url,file_name}] }" } ] }, @@ -35044,7 +35044,7 @@ "list": [ { "method": "returnUnpack.create", - "description": "开拆包单(明细不在此提交,由 returnUnpack.addDetail 逐件录入)。用 waybill_code 反查 wms_order_express 判定是否原单退回,命中则回填 order_express_id/order_id/store_id 及订单信息快照(source_order_codes 平台交易单号 / shop_name 店铺名称=货主自定义店铺名称 store_remask)并返回原订单详情;未命中原单时按 warehouse_id+waybill_code 从 wms_return_query_log 反查货主(限最近 3 个月内登记)。拆包单号规则 RP+YYYYMMDD+6位序号。仓库隔离:warehouse_id 由服务端注入 ctx.user.store_id,禁止前端传入。", + "description": "开拆包单(明细不在此提交,由 returnUnpack.addDetail 逐件录入)。用 waybill_code 反查 wms_order_express 判定是否原单退回,命中则回填 order_express_id/order_id/store_id 及订单信息快照(source_order_codes 平台交易单号 / shop_name 店铺名称=货主自定义店铺名称 store_remask)并返回原订单详情;未命中原单时按 warehouse_id+waybill_code 从 wms_return_query_log 反查货主(限最近 3 个月内登记)。幂等复用:同一仓库同一运单号 3 个月内已存在非 cancelled 拆包单时,不重复创建,直接返回已有拆包单的主表+明细(record.details)+视频(record.videos)+原订单详情(order),并携带 reused=true 标识;同运单号存在多张拆包单时优先复用已录明细的最新单(按明细表真实计数判定),超过 3 个月视为运单号已复用,按新单正常创建。拆包单号规则 RP+YYYYMMDD+6位序号。仓库隔离:warehouse_id 由服务端注入 ctx.user.store_id,禁止前端传入。", "isNeedAuth": true, "isNeedLogin": true, "headers": [], @@ -35089,7 +35089,7 @@ "name": "record", "type": "object", "required": true, - "description": "拆包单主表记录(含 unpack_no、waybill_code、unpack_date、start_time、unpacker_id/unpacker_name、status、detail_status、camera_ids 数组、回填的 order_express_id/order_id/store_id/source_order_codes/shop_name 快照及 is_original_return 派生字段)" + "description": "拆包单主表记录(含 unpack_no、waybill_code、unpack_date、start_time、unpacker_id/unpacker_name、status、detail_status、camera_ids 数组、回填的 order_express_id/order_id/store_id/source_order_codes/shop_name 快照及 is_original_return 派生字段);幂等复用命中已有拆包单时,record 为已有单的详情记录并携带 details 明细数组(含 stockWarehouse 关联,识别明细另附加 stock 库存详情对象:barcodes 条码数组/image_url 图片数组等)、videos 视频数组与 returnReceived 关联" }, { "name": "is_original_return", @@ -35108,6 +35108,12 @@ "type": "object", "required": false, "description": "原订单详情(含 items 明细,仅原单退回时返回,非原单为 null)" + }, + { + "name": "reused", + "type": "boolean", + "required": false, + "description": "是否幂等复用已有拆包单(true 表示 3 个月内同仓库同运单号已有非 cancelled 拆包单,本次未新建,record.details 即已有明细;新建时为 false 或不返回)" } ], "errors": [ @@ -35198,7 +35204,7 @@ "name": "detail", "type": "object", "required": true, - "description": "新增的明细行(含 barcode/is_recognized/item_code/item_name(未知商品)/spec/product_snapshot 等)" + "description": "新增的明细行(含 barcode/is_recognized/item_code/item_name(未知商品)/spec/product_snapshot 等;识别到系统商品时附加 stock 库存详情对象,含 item_code/item_name/sku_property/barcodes 条码数组/image_url 图片数组/packing_requirements/stock_unit 等,由 getStockDetails 通用方法拉取)" }, { "name": "total_items", @@ -35299,7 +35305,7 @@ "name": "detail", "type": "object", "required": true, - "description": "更新后的明细行" + "description": "更新后的明细行(识别到系统商品时附加 stock 库存详情对象,含 barcodes 条码数组/image_url 图片数组等,由 getStockDetails 通用方法拉取)" }, { "name": "total_items", @@ -35698,7 +35704,7 @@ }, { "method": "returnUnpack.detailList", - "description": "拆包明细分页列表,命中识别商品时含 stockWarehouse 关联。仓库隔离:warehouse_id 由服务端自动注入 ctx.user.store_id,禁止前端传入。支持按拆包单ID、系统商品、条码、识别标记、产品状态筛选。", + "description": "拆包明细分页列表,命中识别商品时含 stockWarehouse 关联,并统一走 stockWarehouse.getStockDetails 通用方法为每条识别明细附加 stock 库存详情对象(item_code/item_name/sku_property/barcodes 条码数组/image_url 图片数组/packing_requirements/stock_unit/quantity/locked_quantity 等,带缓存)。仓库隔离:warehouse_id 由服务端自动注入 ctx.user.store_id,禁止前端传入。支持按拆包单ID、系统商品、条码、识别标记、产品状态筛选。", "isNeedAuth": true, "isNeedLogin": true, "headers": [], @@ -35765,7 +35771,7 @@ "name": "list", "type": "array", "required": true, - "description": "明细行列表(含 is_recognized/item_code/item_name/spec/product_snapshot,识别命中时含 stockWarehouse 关联)" + "description": "明细行列表(含 is_recognized/item_code/item_name/spec/product_snapshot,识别命中时含 stockWarehouse 关联与 stock 库存详情对象:barcodes 条码数组/image_url 图片数组/sku_property/packing_requirements/stock_unit 等)" }, { "name": "pagination", @@ -35791,7 +35797,7 @@ }, { "method": "returnUnpack.detail", - "description": "拆包单详情:主表 + 明细(含 stockWarehouse 关联,命中时)+ 视频副表(含 camera 关联,命中时)+ 退回收到单(命中时);原单退回时(order_id 有值)返回 related.order 原订单详情。需 548 权限(客服员工及以上),仓库隔离校验(仅本仓库拆包单)。", + "description": "拆包单详情:主表 + 明细(含 stockWarehouse 关联,命中时;每条识别明细另附加 stock 库存详情对象,含 barcodes 条码数组/image_url 图片数组等,由 getStockDetails 通用方法拉取)+ 视频副表(含 camera 关联,命中时)+ 退回收到单(命中时);原单退回时(order_id 有值)返回 related.order 原订单详情。需 548 权限(客服员工及以上),仓库隔离校验(仅本仓库拆包单)。", "isNeedAuth": true, "isNeedLogin": true, "headers": [], diff --git a/methods/warehouse.json b/methods/warehouse.json index f94bd06..1ba0a29 100644 --- a/methods/warehouse.json +++ b/methods/warehouse.json @@ -272,12 +272,19 @@ "source": "body", "description": "外部透传数据,任意 JSON,WMS 不解析,回信时原样返回" }, + { + "name": "sendTime", + "type": "number", + "required": false, + "source": "body", + "description": "消息原始发送时间(可选):毫秒时间戳、秒时间戳或 ISO 时间字符串。WMS 据此判断历史消息:发送时间距今超过阈值(默认 10 分钟,config.inbox.historyMessageMaxAgeMs 可调)的历史/补推消息将跳过 AI 处理,不自动回复、不创建工单;不传则按实时消息处理" + }, { "name": "flags", "type": "object", "required": false, "source": "body", - "description": "处理标记(预留,当前未消费)" + "description": "处理标记。支持:skipAi=true 显式跳过 AI 处理;send_time=毫秒时间戳(消息原始发送时间,用于历史消息过滤,与 sendTime 参数等价)" } ], "response": [ diff --git a/script/debug-inbox-push.cjs b/script/debug-inbox-push.cjs index be486f9..82378a5 100644 --- a/script/debug-inbox-push.cjs +++ b/script/debug-inbox-push.cjs @@ -37,7 +37,8 @@ function stableStringify(value) { } function md5(str) { - return crypto.createHash('md5').update(str, 'utf8').digest('hex').toLowerCase(); + return crypto.createHash('md5').update(str, 'utf8').digest('hex') + .toLowerCase(); } function buildSign(query, body, secret) { @@ -77,6 +78,7 @@ const CONFIG = { appSecret: ARGS.appSecret || 'sec_xyz789uvw012abc345def678ghi901jkl234mno567pqr890', groupId: ARGS.groupId || 'test-stock-group', groupName: ARGS.groupName || '库存查询测试群', + userId: ARGS.userId || 'debug_user', userName: ARGS.userName || '测试用户', waitMs: Number(ARGS.waitMs || 15000), waybill: ARGS.waybill || `${Date.now()}99`, @@ -165,7 +167,7 @@ async function queryDb(sql) { content: CONFIG.content, groupId: CONFIG.groupId, groupName: CONFIG.groupName, - userId: 'debug_user', + userId: CONFIG.userId, userName: CONFIG.userName, targetType: 'im', }); From a5945cd678960cac53a748166b2399c918f0f9a4 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sat, 15 Aug 2026 18:22:30 +0800 Subject: [PATCH 207/550] =?UTF-8?q?fix:=20inbox=20=E7=BE=A4=E7=99=BB?= =?UTF-8?q?=E8=AE=B0=E6=8C=89=20group=5Fid=20=E5=8E=BB=E9=87=8D=EF=BC=8C?= =?UTF-8?q?=E7=BE=A4=E6=94=B9=E5=90=8D=E5=8F=AA=E6=9B=B4=E6=96=B0=E5=90=8D?= =?UTF-8?q?=E7=A7=B0=EF=BC=9B=E5=94=AF=E4=B8=80=E7=B4=A2=E5=BC=95=E6=94=B9?= =?UTF-8?q?=E4=B8=BA=20(warehouse=5Fid,=20group=5Fid)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/model/inbox_group.js | 5 + app/service/inbox/receiver.js | 63 +++++- ...0815100000-fix-inbox-group-unique-index.js | 138 ++++++++++++ script/merge-inbox-group-duplicates.cjs | 205 ++++++++++++++++++ 4 files changed, 400 insertions(+), 11 deletions(-) create mode 100644 database/migrations/20260815100000-fix-inbox-group-unique-index.js create mode 100644 script/merge-inbox-group-duplicates.cjs diff --git a/app/model/inbox_group.js b/app/model/inbox_group.js index 4a3039b..63e6cd3 100644 --- a/app/model/inbox_group.js +++ b/app/model/inbox_group.js @@ -105,6 +105,11 @@ module.exports = app => { deletedAt: 'deleted_at', paranoid: true, comment: '站内信群表', + indexes: [ + // 群唯一性以 (warehouse_id, group_id) 为准,群名称变化只更新不建新 + { name: 'uk_warehouse_group_id', unique: true, fields: [ 'warehouse_id', 'group_id' ] }, + { name: 'idx_group_id', fields: [ 'group_id' ] }, + ], }); return InboxGroup; diff --git a/app/service/inbox/receiver.js b/app/service/inbox/receiver.js index 4eaab68..9c4529b 100644 --- a/app/service/inbox/receiver.js +++ b/app/service/inbox/receiver.js @@ -145,20 +145,61 @@ class InboxReceiverService extends Service { ctx.logger.info(`[inbox] 消息入库成功 ext_id=${extId} id=${record.id}`); - // 自动登记群(幂等 upsert) + // 自动登记群:优先按 (group_id, warehouse_id) 幂等 upsert。 + // 群ID不变、仅名称变化时只更新名称,不重复建群。 const groupName = String(data.group_name || '').trim(); if (groupName) { try { - await ctx.model.InboxGroup.findOrCreate({ - where: { group_name: groupName, warehouse_id: warehouseId }, - defaults: { - group_id: extGroupId, - store_id: storeId || null, - source_type: sourceType, - source_extra: data.source_extra || null, - ai_enabled: 0, - }, - }); + if (extGroupId) { + const group = await ctx.model.InboxGroup.findOne({ + where: { group_id: extGroupId, warehouse_id: warehouseId }, + }); + + if (group) { + // 群已存在:名称变化时更新名称,不新建 + if (group.group_name !== groupName) { + const oldName = group.group_name; + await group.update({ group_name: groupName }); + ctx.logger.info( + `[inbox] 群名称已更新 group_id=${extGroupId}: ${oldName} → ${groupName}` + ); + } + } else { + // 群ID不存在:优先兼容同名群回填群ID;都没有才新建。 + // 注意表上已无 (group_name, warehouse_id) 唯一索引,名称维度不再保证唯一。 + const byName = await ctx.model.InboxGroup.findOne({ + where: { group_name: groupName, warehouse_id: warehouseId }, + }); + if (byName) { + await byName.update({ group_id: extGroupId }); + ctx.logger.info( + `[inbox] 同名群回填群ID group_id=${extGroupId} name=${groupName}` + ); + } else { + await ctx.model.InboxGroup.create({ + group_name: groupName, + group_id: extGroupId, + warehouse_id: warehouseId, + store_id: storeId || null, + source_type: sourceType, + source_extra: data.source_extra || null, + ai_enabled: 0, + }); + } + } + } else { + // 无群ID:按 (group_name, warehouse_id) 幂等登记(向后兼容) + await ctx.model.InboxGroup.findOrCreate({ + where: { group_name: groupName, warehouse_id: warehouseId }, + defaults: { + group_id: null, + store_id: storeId || null, + source_type: sourceType, + source_extra: data.source_extra || null, + ai_enabled: 0, + }, + }); + } } catch (groupErr) { ctx.logger.warn(`[inbox] 群登记失败: ${groupErr.message}`); } diff --git a/database/migrations/20260815100000-fix-inbox-group-unique-index.js b/database/migrations/20260815100000-fix-inbox-group-unique-index.js new file mode 100644 index 0000000..1d70c66 --- /dev/null +++ b/database/migrations/20260815100000-fix-inbox-group-unique-index.js @@ -0,0 +1,138 @@ +'use strict'; + +const TABLE_NAME = 'wms_inbox_group'; + +/** 合并重复记录时允许从重复行补齐到保留行的字段 */ +const FILLABLE_FIELDS = [ + 'store_id', + 'group_type', + 'sub_type', + 'source_type', + 'source_extra', + 'express_interfaces', + 'system_express_code', +]; + +async function indexExists(queryInterface, tableName, indexName) { + const indexes = await queryInterface.showIndex(tableName); + return (indexes || []).some(i => (typeof i === 'string' ? i : i.name) === indexName); +} + +async function dropIndexIfExists(queryInterface, tableName, indexName) { + if (await indexExists(queryInterface, tableName, indexName)) { + await queryInterface.removeIndex(tableName, indexName); + console.log(`[idx] ${tableName}.${indexName} 已删除`); + } +} + +async function addIndexIfNotExists(queryInterface, tableName, indexName, options = {}) { + if (await indexExists(queryInterface, tableName, indexName)) { + console.log(`[idx] ${tableName}.${indexName} 已存在,跳过`); + return; + } + await queryInterface.addIndex(tableName, options.fields, { + name: indexName, + unique: !!options.unique, + }); + console.log(`[idx] ${tableName}.${indexName} 已创建`); +} + +/** + * 合并 (warehouse_id, group_id) 相同的重复群记录,为唯一索引铺路。 + * 保留策略:is_blocked=0(启用)优先,其次 created_at 最早; + * 群名称取 updated_at 最新一条的名称;其余字段为空时从重复行补齐;其余行软删除。 + * + * @param {Object} queryInterface Sequelize QueryInterface 实例。 + * @return {Promise} + */ +async function mergeDuplicateGroups(queryInterface) { + const q = queryInterface.sequelize; + + const dupGroups = await q.query( + `SELECT warehouse_id, group_id + FROM \`${TABLE_NAME}\` + WHERE group_id IS NOT NULL AND group_id <> '' AND deleted_at IS NULL + GROUP BY warehouse_id, group_id + HAVING COUNT(*) > 1`, + { type: q.QueryTypes.SELECT } + ); + + for (const g of dupGroups) { + const rows = await q.query( + `SELECT * FROM \`${TABLE_NAME}\` + WHERE warehouse_id = ? AND group_id = ? AND deleted_at IS NULL + ORDER BY is_blocked ASC, created_at ASC, id ASC`, + { replacements: [ g.warehouse_id, g.group_id ], type: q.QueryTypes.SELECT } + ); + if (!rows || rows.length < 2) continue; + + const keep = rows[0]; + const nameRow = [ ...rows ].sort((a, b) => new Date(b.updated_at) - new Date(a.updated_at))[0]; + const dropIds = rows.filter(r => r.id !== keep.id).map(r => r.id); + + const updates = {}; + if (keep.group_name !== nameRow.group_name) { + updates.group_name = nameRow.group_name; + } + for (const field of FILLABLE_FIELDS) { + if (keep[field] === null || keep[field] === undefined || keep[field] === '') { + for (const row of rows) { + if (row.id === keep.id) continue; + if (row[field] !== null && row[field] !== undefined && row[field] !== '') { + updates[field] = row[field]; + break; + } + } + } + } + + if (Object.keys(updates).length > 0) { + const setClauses = Object.keys(updates).map(k => `\`${k}\` = ?`).join(', '); + await q.query( + `UPDATE \`${TABLE_NAME}\` SET ${setClauses}, updated_at = NOW() WHERE id = ?`, + { replacements: [ ...Object.values(updates), keep.id ] } + ); + console.log(`[dedupe] 保留 id=${keep.id} group_id=${g.group_id},更新: ${JSON.stringify(updates)}`); + } + + const placeholders = dropIds.map(() => '?').join(','); + await q.query( + `UPDATE \`${TABLE_NAME}\` SET deleted_at = NOW() WHERE id IN (${placeholders}) AND deleted_at IS NULL`, + { replacements: dropIds } + ); + console.log(`[dedupe] 软删除 id=${dropIds.join(',')} group_id=${g.group_id}`); + } +} + +module.exports = { + // eslint-disable-next-line no-unused-vars + up: async (queryInterface, Sequelize) => { + // 1. 清理 (warehouse_id, group_id) 重复记录,否则唯一索引无法创建 + await mergeDuplicateGroups(queryInterface); + + // 2. 删除错误的唯一索引 uk_group_warehouse(group_name, warehouse_id) + // 群名称会变化,不应作为唯一约束维度 + await dropIndexIfExists(queryInterface, TABLE_NAME, 'uk_group_warehouse'); + + // 3. 删除与唯一索引覆盖范围重复的普通索引 idx_warehouse_group_id + await dropIndexIfExists(queryInterface, TABLE_NAME, 'idx_warehouse_group_id'); + + // 4. 新建唯一索引 (warehouse_id, group_id) + // group_id 允许 NULL,MySQL 唯一索引允许多个 NULL,不影响无群ID的记录 + await addIndexIfNotExists(queryInterface, TABLE_NAME, 'uk_warehouse_group_id', { + fields: [ 'warehouse_id', 'group_id' ], + unique: true, + }); + }, + + down: async queryInterface => { + await dropIndexIfExists(queryInterface, TABLE_NAME, 'uk_warehouse_group_id'); + await addIndexIfNotExists(queryInterface, TABLE_NAME, 'idx_warehouse_group_id', { + fields: [ 'warehouse_id', 'group_id' ], + }); + await addIndexIfNotExists(queryInterface, TABLE_NAME, 'uk_group_warehouse', { + fields: [ 'group_name', 'warehouse_id' ], + unique: true, + }); + }, +}; diff --git a/script/merge-inbox-group-duplicates.cjs b/script/merge-inbox-group-duplicates.cjs new file mode 100644 index 0000000..515e474 --- /dev/null +++ b/script/merge-inbox-group-duplicates.cjs @@ -0,0 +1,205 @@ +/** + * 合并 wms_inbox_group 中 (warehouse_id, group_id) 相同的重复群记录。 + * + * 背景:receiver.js 历史上按 (group_name, warehouse_id) 登记群, + * 群改名后会插入同群ID的新记录,产生重复。 + * 合并策略: + * 1. 保留记录:is_blocked=0(启用)优先,其次 created_at 最早。 + * 2. 保留记录的名称:取 updated_at 最新一条的名称(即当前最新群名)。 + * 3. 其余字段:保留记录为空时,从重复记录中补齐非空值。 + * 4. 其余重复记录软删除(deleted_at = NOW())。 + * + * 用法: + * node script/merge-inbox-group-duplicates.cjs --dry-run # 只预览,默认 + * node script/merge-inbox-group-duplicates.cjs --apply # 实际执行 + */ +const fs = require('fs'); +const path = require('path'); +const mysql = require('mysql2/promise'); + +const ROOT = process.cwd(); +const DEFAULT_CONFIG_PATH = path.join(ROOT, 'config', 'config.local.js'); +const TABLE_NAME = 'wms_inbox_group'; + +/** 允许从重复记录补齐到保留记录的字段 */ +const FILLABLE_FIELDS = [ + 'store_id', + 'group_type', + 'sub_type', + 'source_type', + 'source_extra', + 'express_interfaces', + 'system_express_code', +]; + +function parseArgs(argv) { + const args = { dryRun: true, apply: false, dbClient: 'wms', configPath: DEFAULT_CONFIG_PATH }; + for (const item of argv) { + if (item === '--apply') args.apply = true; + if (item === '--dry-run') args.dryRun = true; + if (item.startsWith('--db-client=')) args.dbClient = String(item.split('=')[1] || '').trim() || 'wms'; + if (item.startsWith('--config-path=')) args.configPath = path.resolve(ROOT, String(item.split('=')[1] || '').trim()); + } + if (args.apply) args.dryRun = false; + return args; +} + +function loadDbClient(configPath, dbClientName) { + if (!fs.existsSync(configPath)) { + throw new Error(`Config file not found: ${configPath}`); + } + const configFactory = require(configPath); + const cfg = typeof configFactory === 'function' + ? configFactory({ name: 'wms-inbox-group-merge' }) + : configFactory; + const dbClient = cfg && cfg.mysql && cfg.mysql.clients && cfg.mysql.clients[dbClientName]; + if (!dbClient) { + throw new Error(`MySQL client not found in config.mysql.clients: ${dbClientName}`); + } + return dbClient; +} + +async function findDuplicateGroups(conn) { + const [ rows ] = await conn.query( + `SELECT warehouse_id, group_id, COUNT(*) AS cnt + FROM \`${TABLE_NAME}\` + WHERE group_id IS NOT NULL AND group_id <> '' AND deleted_at IS NULL + GROUP BY warehouse_id, group_id + HAVING cnt > 1 + ORDER BY warehouse_id, group_id` + ); + return rows || []; +} + +async function fetchGroupRows(conn, warehouseId, groupId) { + const [ rows ] = await conn.query( + `SELECT id, group_name, group_id, warehouse_id, store_id, group_type, sub_type, + source_type, source_extra, express_interfaces, system_express_code, + ai_enabled, is_blocked, created_at, updated_at, deleted_at + FROM \`${TABLE_NAME}\` + WHERE warehouse_id = ? AND group_id = ? AND deleted_at IS NULL`, + [ warehouseId, groupId ] + ); + return rows || []; +} + +function pickKeepRow(rows) { + // 启用优先,其次创建时间最早,最后 id 最小 + return [ ...rows ].sort((a, b) => { + if (Number(a.is_blocked) !== Number(b.is_blocked)) return Number(a.is_blocked) - Number(b.is_blocked); + if (a.created_at !== b.created_at) return new Date(a.created_at) - new Date(b.created_at); + return a.id - b.id; + })[0]; +} + +function pickNewestNameRow(rows) { + return [ ...rows ].sort((a, b) => { + const da = new Date(a.updated_at); + const db = new Date(b.updated_at); + if (da !== db) return db - da; + return b.id - a.id; + })[0]; +} + +function buildMergePlan(rows) { + const keepRow = pickKeepRow(rows); + const nameRow = pickNewestNameRow(rows); + const dropRows = rows.filter(r => r.id !== keepRow.id); + + const updates = {}; + if (keepRow.group_name !== nameRow.group_name) { + updates.group_name = nameRow.group_name; + } + + // 保留记录字段为空时,从重复记录补齐非空值 + for (const field of FILLABLE_FIELDS) { + if (keepRow[field] === null || keepRow[field] === undefined || keepRow[field] === '') { + for (const row of rows) { + if (row.id === keepRow.id) continue; + if (row[field] !== null && row[field] !== undefined && row[field] !== '') { + updates[field] = row[field]; + break; + } + } + } + } + + return { keepRow, nameRow, dropRows, updates }; +} + +async function main() { + const args = parseArgs(process.argv.slice(2)); + const dbClient = loadDbClient(args.configPath, args.dbClient); + + const conn = await mysql.createConnection({ + host: dbClient.host, + port: dbClient.port, + user: dbClient.user, + password: dbClient.password, + database: dbClient.database, + }); + + try { + const duplicates = await findDuplicateGroups(conn); + console.log(`发现 ${duplicates.length} 组重复群 (group_id 相同):\n`); + + if (duplicates.length === 0) { + console.log('无重复群,无需处理。'); + return; + } + + let mergedCount = 0; + let updateCount = 0; + + for (const dup of duplicates) { + const rows = await fetchGroupRows(conn, dup.warehouse_id, dup.group_id); + if (rows.length < 2) continue; + + const { keepRow, nameRow, dropRows, updates } = buildMergePlan(rows); + mergedCount += 1; + if (Object.keys(updates).length > 0) updateCount += 1; + + console.log( + `[${dup.warehouse_id}] ${dup.group_id} (${rows.length} 条): ` + + `保留 id=${keepRow.id} "${keepRow.group_name}"` + ); + if (updates.group_name) { + console.log(` 名称更新: "${keepRow.group_name}" → "${updates.group_name}"`); + } + const otherUpdates = { ...updates }; + delete otherUpdates.group_name; + if (Object.keys(otherUpdates).length > 0) { + console.log(` 字段补齐: ${JSON.stringify(otherUpdates)}`); + } + for (const drop of dropRows) { + console.log(` 软删除: id=${drop.id} "${drop.group_name}" (${drop.is_blocked ? '屏蔽' : '启用'})`); + } + console.log(` 最新名称来源: id=${nameRow.id} "${nameRow.group_name}"`); + + if (!args.dryRun) { + if (Object.keys(updates).length > 0) { + await conn.query( + `UPDATE \`${TABLE_NAME}\` SET ? WHERE id = ?`, + [ updates, keepRow.id ] + ); + } + for (const drop of dropRows) { + await conn.query( + `UPDATE \`${TABLE_NAME}\` SET deleted_at = NOW() WHERE id = ?`, + [ drop.id ] + ); + } + } + } + + console.log(`\n${args.dryRun ? '[dry-run] 预览完成' : '执行完成'}: ` + + `共 ${mergedCount} 组重复群,其中 ${updateCount} 组需要更新保留记录。`); + } finally { + await conn.end(); + } +} + +main().catch(err => { + console.error('执行失败:', err.message); + process.exit(1); +}); From 75ac14a4ab237f15f76507d475cd58eb5934cd28 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sat, 15 Aug 2026 18:25:43 +0800 Subject: [PATCH 208/550] =?UTF-8?q?fix(order.recheckOrder):=20=E5=9B=A2?= =?UTF-8?q?=E8=B4=AD=E5=A4=8D=E6=A0=B8=E8=BE=93=E5=87=BA=E6=8B=A6=E6=88=AA?= =?UTF-8?q?=E8=AE=A2=E5=8D=95=E5=BA=8F=E5=8F=B7=EF=BC=8C=E4=BF=AE=E6=AD=A3?= =?UTF-8?q?=20intercept=5Fstatus=20=E8=AF=86=E5=88=AB=EF=BC=88B20260807000?= =?UTF-8?q?03=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../systemMethods/order/recheckOrder.js | 33 ++++++++++++++++--- methods/changes/system.json | 18 ++++++++++ methods/system.json | 32 ++++++++++++++++++ 3 files changed, 78 insertions(+), 5 deletions(-) diff --git a/app/service/systemMethods/order/recheckOrder.js b/app/service/systemMethods/order/recheckOrder.js index 0ff76a1..b3f43ee 100644 --- a/app/service/systemMethods/order/recheckOrder.js +++ b/app/service/systemMethods/order/recheckOrder.js @@ -671,6 +671,28 @@ class RecheckOrderService extends OrderBaseService { }; } + /** + * 判断订单拦截状态是否属于"已进入拦截流程"的状态。 + * 拦截状态枚举(wms_order_delivery.intercept_status)实际取值为: + * none / requesting / requested / intercepting / intercepted_in_transit / intercepted_at_warehouse / + * returning / returned / delivered_by_mistake / timeout / cancelled / failed / exception。 + * 其中 requested/requesting/intercepting 为拦截发起中,intercepted_in_transit 为途中拦截成功, + * intercepted_at_warehouse 为仓库拦截成功;intercepted 为历史遗留值,一并兼容。 + * @param {string} status 拦截状态。 + * @return {boolean} 是否为拦截流程状态。 + */ + isInterceptedOrderStatus(status = '') { + const normalizedStatus = String(status || '').trim(); + return [ + 'intercepted', + 'requested', + 'requesting', + 'intercepting', + 'intercepted_in_transit', + 'intercepted_at_warehouse', + ].includes(normalizedStatus); + } + /** * 构建团购波次列表视图(团单模式)。 * 根据拣货任务ID查找关联的所有波次,每个波次展开为一项。 @@ -682,8 +704,8 @@ class RecheckOrderService extends OrderBaseService { * pick_mode、total_orders、processed_orders、creator、create_time、update_time、 * order_count、box_no、reviewed_count、unreviewed_count、printed_count、unprinted_count、 * stocks(非拦截订单合并后的商品明细)、 - * intercepted(拦截订单列表,仅当波次中存在拦截订单时出现,每项含 wave_index、order_id、 - * delivery_order_code、intercept_status 等字段)、 + * intercepted(拦截订单列表,仅当波次中存在拦截订单时出现,每项含 wave_index(波次内序号)、order_id、 + * delivery_order_code、waybill_no、intercept_status 等字段)、 * items_weight(订单商品总重量,取自波次内首个正常订单)、 * suggested_package_material(推荐包材信息,无推荐时为 null)、 * first_waybill_no(波次内首个正常订单的运单号,用于包材绑定等后续操作,无正常订单时为第一个订单的运单号,均无则为空字符串)。 @@ -757,7 +779,7 @@ class RecheckOrderService extends OrderBaseService { const normalOrders = []; for (const order of orders) { const interceptStatus = String(order.intercept_status || '').trim(); - if (interceptStatus === 'intercepted') { + if (this.isInterceptedOrderStatus(interceptStatus)) { interceptedOrders.push(order); } else { normalOrders.push(order); @@ -787,11 +809,12 @@ class RecheckOrderService extends OrderBaseService { store_remark: String(item.store_remark || '').trim(), })); - // 构建拦截订单列表 + // 构建拦截订单列表(wave_index 即波次内序号,供前端展示拦截订单的序号) const intercepted = interceptedOrders.map(order => ({ wave_index: Number(order.wave_index || 0), order_id: Number(order.order_id || 0), delivery_order_code: String(order.delivery_order_code || '').trim(), + waybill_no: String(order.waybill_no || '').trim(), intercept_status: String(order.intercept_status || '').trim(), })); @@ -1754,7 +1777,7 @@ class RecheckOrderService extends OrderBaseService { const interceptedOrders = []; for (const order of orderList) { - if (String(order.intercept_status || '').trim() === 'intercepted') { + if (this.isInterceptedOrderStatus(String(order.intercept_status || '').trim())) { interceptedOrders.push(order); } else { normalOrders.push(order); diff --git a/methods/changes/system.json b/methods/changes/system.json index 564d4f3..0b68bb4 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,22 @@ [ + { + "version": "2026.08.15-recheckOrder.scanOrder.groupInterceptSeq", + "date": "2026-08-15", + "type": "fixed", + "summary": "修复 order.recheckOrder.scanOrder 团购模式拦截订单识别:原逻辑仅匹配不存在的 'intercepted' 状态,导致已进入拦截流程的订单(requested/requesting/intercepting/intercepted_in_transit/intercepted_at_warehouse)被当作正常订单,团购复核数据不输出拦截订单及其序号。现统一按真实拦截状态枚举归类到波次项 intercepted 列表,并输出 wave_index 波次内序号", + "methods": [ + "order.recheckOrder.scanOrder", + "order.recheckOrder.scanTask" + ], + "notes": [ + "新增 isInterceptedOrderStatus 辅助方法:intercepted / requested / requesting / intercepting / intercepted_in_transit / intercepted_at_warehouse 均视为拦截流程状态", + "buildGroupWaveList 拦截订单分离改用 isInterceptedOrderStatus,拦截订单不再进入正常订单校验与统计,仓库已拦截订单不再阻断整个团购扫描视图加载", + "团购波次项 intercepted 列表每项新增 waybill_no 字段,wave_index 为波次内序号(优先读取 wms_order_wave_index 真实序号,无记录时降级数组临时序号)", + "confirmRecheckByWaveId 团购波次批量复核同步修正拦截识别,拦截订单不再被批量标记复核", + "同步更新 methods/system.json 中 scanOrder 团购波次项 intercepted 字段说明" + ], + "module": "order" + }, { "version": "2026.08.14-afterSale.detail-desc-first-step", "date": "2026-08-14", diff --git a/methods/system.json b/methods/system.json index 13a2742..9bede62 100644 --- a/methods/system.json +++ b/methods/system.json @@ -5774,6 +5774,38 @@ } ] }, + { + "name": "intercepted", + "type": "array", + "description": "[团购波次项] 拦截订单列表,仅当波次内存在已进入拦截流程的订单时返回(intercept_status 为 requested / requesting / intercepting / intercepted_in_transit / intercepted_at_warehouse,以及历史遗留值 intercepted)。每项含 wave_index(波次内序号)、order_id、delivery_order_code、waybill_no、intercept_status", + "children": [ + { + "name": "wave_index", + "type": "number", + "description": "波次内序号(优先从 wms_order_wave_index 读取真实 wave_index,若无则降级为数组临时序号)" + }, + { + "name": "order_id", + "type": "number", + "description": "订单ID" + }, + { + "name": "delivery_order_code", + "type": "string", + "description": "发货单号" + }, + { + "name": "waybill_no", + "type": "string", + "description": "运单号" + }, + { + "name": "intercept_status", + "type": "string", + "description": "拦截状态(requested / requesting / intercepting / intercepted_in_transit / intercepted_at_warehouse / intercepted)" + } + ] + }, { "name": "items_weight", "type": "number|null", From 18d33ec645e614e681f08f5882c46cf81f6583cd Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sat, 15 Aug 2026 18:27:21 +0800 Subject: [PATCH 209/550] =?UTF-8?q?feat(order.pendingOrder.parseAddress):?= =?UTF-8?q?=20=E6=94=AF=E6=8C=81=E6=95=B0=E7=BB=84=E6=89=B9=E9=87=8F?= =?UTF-8?q?=E5=85=A5=E5=8F=82=E6=89=B9=E9=87=8F=E8=A7=A3=E6=9E=90=EF=BC=8C?= =?UTF-8?q?=E6=A8=A1=E5=9E=8B=E5=88=87=20v4-flash=EF=BC=8C50=20=E6=9D=A1?= =?UTF-8?q?=E5=B9=B6=E8=A1=8C=E5=9D=97=E8=A7=A3=E6=9E=90=E5=AE=9E=E6=B5=8B?= =?UTF-8?q?=2031.6s?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 入参兼容 address 字符串(单条)/address 数组/addresses 数组(批量,上限 50) - 批量按每 10 条合并一次请求并行发出,Promise.all 聚合按输入顺序返回,失败条目逐条回退单条解析 - 模型 deepseek-v4-flash(仅 parseAddress 内使用,不改全局配置),超时 60s/块 120s - extractJsonBlock 支持数组 JSON 截取;新增手机号/姓名清洗与正则省市区最终兜底 - 同步 methods/system.json 文档(v0.3.28)与变更记录 --- .../systemMethods/order/pendingOrder.js | 513 +++++++++++++++--- methods/changes/system.json | 17 + methods/system.json | 92 +++- 3 files changed, 547 insertions(+), 75 deletions(-) diff --git a/app/service/systemMethods/order/pendingOrder.js b/app/service/systemMethods/order/pendingOrder.js index fbbd7ab..8f3ee03 100644 --- a/app/service/systemMethods/order/pendingOrder.js +++ b/app/service/systemMethods/order/pendingOrder.js @@ -531,6 +531,139 @@ function reverseInferAddress(parsed) { return { ...parsed, province: province || '', city: city || '', area: area || '' }; } +/** + * 从模型返回的文本中截取 JSON 片段(对象或数组),并清理 markdown 代码块标记。 + * 对象取第一个 { 到最后一个 },数组取第一个 [ 到最后一个 ],自动忽略前后多余文本。 + * + * @param {string} text 模型原始返回文本。 + * @return {string} 截取后的 JSON 字符串;无有效片段时返回原文 trim。 + */ +function extractJsonBlock(text) { + if (!text) return ''; + let s = String(text).trim(); + s = s.replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/i, ''); + const firstBrace = s.indexOf('{'); + const firstBracket = s.indexOf('['); + let start = -1; + if (firstBrace === -1) { + start = firstBracket; + } else if (firstBracket === -1) { + start = firstBrace; + } else { + start = Math.min(firstBrace, firstBracket); + } + const end = Math.max(s.lastIndexOf('}'), s.lastIndexOf(']')); + if (start === -1 || end === -1 || end <= start) { + return s; + } + return s.slice(start, end + 1); +} + +const ADDRESS_PARSE_FIELDS = [ + 'province', 'city', 'area', 'town', 'detailAddress', 'name', 'mobile', +]; + +/** + * 从任意文本(如思维链模型的 reasoning_content)中提取地址解析字段, + * 支持 "province":"xx"、province=xx、province:xx 等常见写法。 + * + * @param {string} text 原始文本。 + * @return {Object|null} 提取到的字段对象;一个字段都没提取到则返回 null。 + */ +function salvageFieldsFromText(text) { + if (!text) return null; + const src = String(text); + const out = {}; + let foundAny = false; + for (const field of ADDRESS_PARSE_FIELDS) { + const patterns = [ + new RegExp(`["']?${field}["']?\\s*[::=]\\s*["']([^"']{0,80})["']`, 'i'), + new RegExp(`["']?${field}["']?\\s*[::=]\\s*([^\\s,,;;\\n"']{0,80})`, 'i'), + ]; + for (const re of patterns) { + const m = src.match(re); + if (m && m[1] && m[1].trim()) { + out[field] = m[1].trim(); + foundAny = true; + break; + } + } + } + return foundAny ? out : null; +} + +/** + * 清洗手机号:仅保留合法 11 位大陆手机号;兜底提取的脏数据(如整段地址)置空。 + * + * @param {*} mobile 原始手机号字段。 + * @return {string} 合法手机号或空字符串。 + */ +function sanitizeMobile(mobile) { + const m = String(mobile || '').trim(); + return /^1[3-9]\d{9}$/.test(m) ? m : ''; +} + +/** + * 清洗收件人姓名:过滤过长的字符串与明显混入地址信息的脏数据。 + * + * @param {*} name 原始姓名字段。 + * @return {string} 合法姓名或空字符串。 + */ +function sanitizeName(name) { + const n = String(name || '').trim(); + if (!n || n.length > 20) return ''; + if (/[省市县区镇街道路号村组栋座楼室单元乡]/.test(n)) return ''; + return n; +} + +/** + * 地址解析最终兜底:AI 解析与行政区划映射表均失败时,用正则按"省-市-区-镇"顺序 + * 从原始地址字符串中提取行政区划。支持省份全称与简称(如"广东"、"内蒙古")。 + * + * @param {string} text 原始地址字符串。 + * @return {Object} { province, city, area, town },识别不到的字段为空字符串。 + */ +function extractAddressByRegex(text) { + const src = String(text || ''); + const result = { province: '', city: '', area: '', town: '' }; + if (!src) return result; + + // 省份:全称与简称按长度降序匹配,避免"河北/河南"等前缀误配 + const shorten = p => p.replace(/(壮族自治区|回族自治区|维吾尔自治区|特别行政区|自治区|省|市)$/, ''); + const provincePattern = PROVINCE_LIST + .reduce((list, p) => { + const short = shorten(p); + if (short !== p) list.push(short); + list.push(p); + return list; + }, []) + .sort((a, b) => b.length - a.length) + .join('|'); + const provinceMatch = src.match(new RegExp(`(${provincePattern})`)); + if (!provinceMatch) return result; + + const provinceToken = provinceMatch[1]; + const fullProvince = PROVINCE_LIST.find(p => p.startsWith(provinceToken)); + result.province = fullProvince || provinceToken; + const rest = src.slice(provinceMatch.index + provinceToken.length); + + const cityMatch = rest.match(/([\u4e00-\u9fa5]{2,10}?(?:自治州|地区|盟|市))/); + if (!cityMatch) return result; + result.city = cityMatch[1]; + const restAfterCity = rest.slice(cityMatch.index + cityMatch[1].length); + + const areaMatch = restAfterCity.match(/([\u4e00-\u9fa5]{2,10}?(?:自治县|区|县|市))/); + if (!areaMatch) return result; + result.area = areaMatch[1]; + const restAfterArea = restAfterCity.slice(areaMatch.index + areaMatch[1].length); + + const townMatch = restAfterArea.match(/([\u4e00-\u9fa5]{2,10}?(?:街道|办事处|镇|乡))/); + if (townMatch) { + result.town = townMatch[1]; + } + return result; +} + class PendingOrderService extends OrderBaseService { /** * 初始化待处理订单系统方法的免登录、免权限、免日志和免鉴权配置。 @@ -3149,7 +3282,12 @@ class PendingOrderService extends OrderBaseService { } } - const newOrder = await model.create(newOrderData); + // 克隆单同样由仓库序列表统一发号;发号失败直接抛错,不回退分表自增, + // 避免分表自增与序列表发号区间重叠产生冲突 id + await this.ctx.model.OrderDeliveryFactory.ensureLocationSequenceTable(warehouseId); + const allocatedOrderId = await this.ctx.model.OrderDeliveryFactory.allocateOrderId(warehouseId, null, 'current'); + + const newOrder = await model.create({ ...newOrderData, id: allocatedOrderId }); const newOrderId = Number(newOrder.id || newOrder.dataValues && newOrder.dataValues.id); // 5. 克隆订单明细 @@ -3214,28 +3352,196 @@ class PendingOrderService extends OrderBaseService { /** * 智能地址解析:使用 DeepSeek 将用户输入的地址字符串解析为结构化地址。 * + * 支持单条解析与数组批量解析两种模式: + * - 单条:data.address 传字符串,返回单条解析结果(与原行为一致) + * - 批量:data.addresses(或 data.address)传字符串数组,按数组顺序返回 data.list, + * 每条元素含 address/flag/message 与解析字段,失败条目不影响其他条目 + * * 采用"AI 解析 + 反向识别兜底"双层策略: * 1. 先由 DeepSeek AI 进行语义级地址解析 * 2. 若 AI 返回的省/市/区字段缺失,通过内置的中国行政区划映射表反向补全 * 3. 仅在两层策略均无法确定 province 时才判定失败 * * @param {Object} data 请求数据。 - * @param {string} data.address 原始地址字符串(必填)。 - * @return {Promise} 解析结果,成功返回 province/city/area/town/detailAddress/name/mobile 等,失败返回错误。 + * @param {string|string[]} data.address 原始地址字符串或字符串数组(必填)。 + * @param {string[]} [data.addresses] 批量地址字符串数组(与 address 数组二选一)。 + * @return {Promise} 解析结果;批量模式返回 data.list 数组。 */ async parseAddress(data = {}) { - const address = String(data.address || '').trim(); + // 批量模式:addresses 数组优先,其次 address 数组 + const rawAddresses = Array.isArray(data.addresses) + ? data.addresses + : (Array.isArray(data.address) ? data.address : null); + + if (rawAddresses) { + if (!rawAddresses.length) { + return this.fail('地址数组不能为空'); + } + if (rawAddresses.length > 50) { + return this.fail('单次批量解析最多支持 50 条地址'); + } + // 批量提速:每 10 条合并为一次 DeepSeek 请求(实测 10 条约 18s、无截断), + // 所有块异步并行发出,全部完成后按输入顺序聚合返回;失败/缺失条目逐条回退单条解析。 + const CHUNK_SIZE = 10; + const EMPTY_FIELDS = { province: '', city: '', area: '', town: '', detailAddress: '', name: '', mobile: '' }; + const toListItem = r => ({ + address: r.address, + flag: r.flag, + message: r.message, + ...(r.fields || EMPTY_FIELDS), + }); + const chunks = []; + for (let i = 0; i < rawAddresses.length; i += CHUNK_SIZE) { + chunks.push(rawAddresses.slice(i, i + CHUNK_SIZE)); + } + const chunkResults = await Promise.all(chunks.map(chunk => this._parseAddressBatchOneShot(chunk))); + const results = await Promise.all(rawAddresses.map((item, idx) => { + const r = chunkResults[Math.floor(idx / CHUNK_SIZE)]; + const inChunk = r && r[idx % CHUNK_SIZE]; + return inChunk && inChunk.ok ? inChunk : this._parseSingleAddress(item); + })); + return this.success('地址解析成功', { list: results.map(toListItem) }); + } + + // 单条模式(向后兼容) + const single = await this._parseSingleAddress(data.address); + if (!single.ok) { + return this.fail(single.message); + } + return this.success('地址解析成功', single.fields); + } + + /** + * 块内一次性解析:把一组地址(建议 10 条)合并为一次 DeepSeek 请求, + * 让模型按编号返回 JSON 数组,省去逐条请求的网络开销。 + * + * @param {string[]} addressList 地址字符串数组。 + * @return {Promise} 与入参顺序对齐的逐条结果数组; + * 请求失败/JSON 解析失败/被截断时返回 null,由调用方逐条回退单条解析。 + */ + async _parseAddressBatchOneShot(addressList) { + const apiKey = this.config.deepseek.apiKey; + const baseUrl = this.config.deepseek.baseUrl || 'https://api.deepseek.com'; + if (!apiKey) return null; + + const numbered = addressList.map((a, i) => `${i + 1}. ${a}`).join('\n'); + const prompt = `你是一个专业的中文地址解析助手。请一次性解析以下 ${addressList.length} 条地址,按编号顺序返回JSON数组,每条为: +{"index":编号,"province":"省","city":"市","area":"区/县","town":"乡镇/街道","detailAddress":"详细地址","name":"收件人","mobile":"手机号"} +规则: +1. 地址重复拼接时先智能去重再解析 +2. 直辖市:province与city都填直辖市名,area填市辖区名 +3. 无法识别的字段填空字符串 +4. 只返回JSON数组,不含解释或markdown + +地址列表: +${numbered}`; + + try { + const result = await this.ctx.curl(`${baseUrl}/v1/chat/completions`, { + method: 'POST', + contentType: 'json', + dataType: 'json', + headers: { + Authorization: `Bearer ${apiKey}`, + }, + data: { + model: 'deepseek-v4-flash', + messages: [ + { role: 'system', content: '你是一个专业的地址解析助手,只返回JSON格式结果。' }, + { role: 'user', content: prompt }, + ], + temperature: 0, + max_tokens: 32000, + }, + timeout: 120000, + }); + + if (result.status !== 200 || !result.data) { + return null; + } + const choice = result.data.choices?.[0] || {}; + // 被截断时整体回退,避免残缺数组造成大量错位 + if ((choice.finish_reason || '') === 'length') { + return null; + } + + const content = String(choice.message?.content || '').trim(); + const arr = JSON.parse(extractJsonBlock(content)); + if (!Array.isArray(arr)) { + return null; + } + this.ctx.logger.info('[parseAddress] 批量块请求完成:入参 %d 条,finish_reason=%s,返回 %d 条', addressList.length, choice.finish_reason, arr.length); + + return addressList.map((address, idx) => { + if (!String(address || '').trim()) { + return { address, ok: false, flag: 'failure', message: '地址字符串不能为空', fields: null }; + } + const item = arr.find(x => x && Number(x.index) === idx + 1); + if (!item) { + return { address, ok: false, flag: 'failure', message: '批量解析未返回该条结果', fields: null }; + } + + let province = String(item.province || '').trim(); + let city = String(item.city || '').trim(); + let area = String(item.area || '').trim(); + let town = String(item.town || '').trim(); + const detailAddress = String(item.detailAddress || '').trim(); + const name = sanitizeName(item.name); + const mobile = sanitizeMobile(item.mobile); + + // 反向识别兜底 + 正则兜底,与单条解析保持一致 + const inferred = reverseInferAddress({ province, city, area, town, detailAddress, name, mobile }); + province = inferred.province; + city = inferred.city; + area = inferred.area; + if (!province) { + const regexResult = extractAddressByRegex(address); + if (regexResult.province) { + province = regexResult.province; + city = city || regexResult.city; + area = area || regexResult.area; + town = town || regexResult.town; + } + } + + if (!province || province === '暂未识别' || province === '其他') { + return { address, ok: false, flag: 'failure', message: '地址解析失败:省市区无法识别,请补充更多地址信息后重试', fields: null }; + } + return { + address, + ok: true, + flag: 'success', + message: 'ok', + fields: { province, city, area, town, detailAddress, name, mobile }, + }; + }); + } catch (error) { + this.ctx.logger.warn('[parseAddress] 批量一次性解析失败,将逐条回退: %s', error.message); + return null; + } + } + + /** + * 解析单条地址(parseAddress 单条/批量模式共用)。 + * + * @param {*} item 原始地址。 + * @return {Promise} { address, ok, flag, message, fields };fields 为解析字段对象或 null。 + */ + async _parseSingleAddress(item) { + const address = String(item || '').trim(); if (!address) { - return this.fail('地址字符串不能为空'); + return { address, ok: false, flag: 'failure', message: '地址字符串不能为空', fields: null }; } const apiKey = this.config.deepseek.apiKey; const baseUrl = this.config.deepseek.baseUrl || 'https://api.deepseek.com'; if (!apiKey) { - return this.fail('DeepSeek API Key 未配置'); + return { address, ok: false, flag: 'failure', message: 'DeepSeek API Key 未配置', fields: null }; } try { + // 仅在 parseAddress 使用 v4-flash(速度优先,适合批量解析),不改全局配置 + const model = 'deepseek-v4-flash'; const prompt = `你是一个专业的中文地址解析助手,拥有丰富的中国地理知识。请解析以下地址字符串。 规则: @@ -3252,73 +3558,143 @@ class PendingOrderService extends OrderBaseService { - "浙江省xxx村" → 根据村名命名习惯和方言特征推测所属城市 4. 如果实在无法确定,province填"",city和area同理填"",收件人和name同理填"",mobile同理填""。 5. detailAddress去除省市区部分,只保留街道/村/门牌号 -6. 只返回纯JSON,不含解释或markdown +6. 地址字符串若出现重复拼接(如"陕西省延安市志丹县"出现两次),先智能去重再解析,合并保留重复部分中的街道/村信息 +7. 只返回纯JSON,不含解释或markdown 地址字符串: "${address}" 请返回JSON:`; - const result = await this.ctx.curl(`${baseUrl}/v1/chat/completions`, { - method: 'POST', - contentType: 'json', - dataType: 'json', - headers: { - Authorization: `Bearer ${apiKey}`, - }, - data: { - model: 'deepseek-v4-pro', - messages: [ - { role: 'system', content: '你是一个专业的地址解析助手,只返回JSON格式结果。' }, - { role: 'user', content: prompt }, - ], - temperature: 0, - max_tokens: 500, - }, - timeout: 15000, - }); - - if (result.status !== 200 || !result.data) { - return this.fail('地址解析服务请求失败'); - } - - const content = result.data.choices?.[0]?.message?.content || ''; - this.ctx.logger.info('[parseAddress] DeepSeek原始返回content: %s', content); - - // 清理可能的 markdown 代码块标记 - let jsonStr = content.trim(); - jsonStr = jsonStr.replace(/^```json\s*/i, '').replace(/\s*```$/i, ''); - jsonStr = jsonStr.replace(/^```\s*/i, '').replace(/\s*```$/i, ''); - - try { - const parsed = JSON.parse(jsonStr); - let province = String(parsed.province || '').trim(); - let city = String(parsed.city || '').trim(); - let area = String(parsed.area || '').trim(); - const town = String(parsed.town || '').trim(); - const detailAddress = String(parsed.detailAddress || '').trim(); - const name = String(parsed.name || '').trim(); - const mobile = String(parsed.mobile || '').trim(); - - // --- 反向识别兜底:使用内置行政区划映射表补全缺失字段 --- - const inferred = reverseInferAddress({ - province, - city, - area, - town, - detailAddress, - name, - mobile, + const requestDeepSeek = async maxTokens => { + const result = await this.ctx.curl(`${baseUrl}/v1/chat/completions`, { + method: 'POST', + contentType: 'json', + dataType: 'json', + headers: { + Authorization: `Bearer ${apiKey}`, + }, + data: { + model, + messages: [ + { role: 'system', content: '你是一个专业的地址解析助手,只返回JSON格式结果。' }, + { role: 'user', content: prompt }, + ], + temperature: 0, + max_tokens: maxTokens, + }, + timeout: 60000, }); - province = inferred.province; - city = inferred.city; - area = inferred.area; - // 反向识别后仍无 province 才判定失败 - if (!province || province === '暂未识别' || province === '其他') { - return this.fail('地址解析失败:省市区无法识别,请补充更多地址信息后重试'); + if (result.status !== 200 || !result.data) { + return null; } + const choice = result.data.choices?.[0] || {}; + return { + content: String(choice.message?.content || '').trim(), + reasoningContent: String(choice.message?.reasoning_content || '').trim(), + finishReason: choice.finish_reason || '', + }; + }; - return this.success('地址解析成功', { + // deepseek-v4-flash 为思维链模型,max_tokens 过小时推理会耗尽全部配额, + // 导致 content 为空且 finish_reason=length。首次给足 3000 tokens, + // 仍被截断且无法从 reasoning_content 兜底时,加大到 8000 重试一次。 + let response = await requestDeepSeek(3000); + if ( + response + && response.finishReason === 'length' + && !response.content + && !salvageFieldsFromText(response.reasoningContent) + ) { + this.ctx.logger.warn('[parseAddress] 首次调用被截断(finish_reason=length),以 max_tokens=8000 重试'); + response = await requestDeepSeek(8000); + } + + if (!response) { + return { address, ok: false, flag: 'failure', message: '地址解析服务请求失败', fields: null }; + } + + const { content, reasoningContent, finishReason } = response; + this.ctx.logger.info('[parseAddress] DeepSeek原始返回 finish_reason=%s content: %s', finishReason, content || '(空)'); + + const tryParseJson = raw => { + try { + return JSON.parse(raw); + } catch (parseError) { + return null; + } + }; + + // 清理 markdown 代码块标记,并截取第一个 { 到最后一个 } 之间的 JSON 片段 + let parsed = tryParseJson(extractJsonBlock(content)); + if (!parsed) { + // 轻量修复:去除对象/数组内的尾随逗号后重试 + parsed = tryParseJson(extractJsonBlock(content).replace(/,\s*([}\]])/g, '$1')); + } + + // JSON 解析失败时,尝试从 content 或 reasoning_content 文本中做字段级提取兜底 + if (!parsed) { + parsed = salvageFieldsFromText(content || reasoningContent); + if (parsed) { + this.ctx.logger.warn('[parseAddress] 正文字段提取兜底结果: %j', parsed); + } + } + + if (!parsed) { + this.ctx.logger.warn('[parseAddress] JSON解析失败,finish_reason=%s,原始返回: %s', finishReason, content || reasoningContent); + if (finishReason === 'length') { + return { address, ok: false, flag: 'failure', message: '地址解析超时,请重试', fields: null }; + } + return { address, ok: false, flag: 'failure', message: '地址解析结果格式异常,请重试', fields: null }; + } + + let province = String(parsed.province || '').trim(); + let city = String(parsed.city || '').trim(); + let area = String(parsed.area || '').trim(); + let town = String(parsed.town || '').trim(); + const detailAddress = String(parsed.detailAddress || '').trim(); + const name = sanitizeName(parsed.name); + const mobile = sanitizeMobile(parsed.mobile); + + // --- 反向识别兜底:使用内置行政区划映射表补全缺失字段 --- + const inferred = reverseInferAddress({ + province, + city, + area, + town, + detailAddress, + name, + mobile, + }); + province = inferred.province; + city = inferred.city; + area = inferred.area; + + // --- 最终兜底:AI 与映射表均失败时,用正则从原始地址提取省市区 --- + if (!province) { + const regexResult = extractAddressByRegex(address); + if (regexResult.province) { + province = regexResult.province; + city = city || regexResult.city; + area = area || regexResult.area; + if (!town) { + town = regexResult.town; + } + this.ctx.logger.warn('[parseAddress] 正则兜底解析结果: %j', regexResult); + } + } + + // 反向识别后仍无 province 才判定失败 + if (!province || province === '暂未识别' || province === '其他') { + return { address, ok: false, flag: 'failure', message: '地址解析失败:省市区无法识别,请补充更多地址信息后重试', fields: null }; + } + + return { + address, + ok: true, + flag: 'success', + message: 'ok', + fields: { province, city, area, @@ -3326,14 +3702,11 @@ class PendingOrderService extends OrderBaseService { detailAddress, name, mobile, - }); - } catch (parseError) { - this.ctx.logger.warn('[parseAddress] JSON解析失败,原始返回: %s', content); - return this.fail('地址解析结果格式异常,请重试'); - } + }, + }; } catch (error) { this.ctx.logger.error('[parseAddress] DeepSeek请求异常: %s', error.message); - return this.fail(`地址解析失败: ${error.message}`); + return { address, ok: false, flag: 'failure', message: `地址解析失败: ${error.message}`, fields: null }; } } diff --git a/methods/changes/system.json b/methods/changes/system.json index 0b68bb4..4c08040 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -17,6 +17,23 @@ ], "module": "order" }, + { + "version": "2026.08.15-parseAddress.batch", + "date": "2026-08-15", + "type": "enhanced", + "summary": "parseAddress 支持数组批量入参:addresses(或 address)传字符串数组时批量解析,响应 data.list 按输入顺序返回每条地址的解析结果(含失败条目逐条错误信息)", + "methods": [ + "order.pendingOrder.parseAddress" + ], + "notes": [ + "入参兼容三种形态:address 字符串(单条,原行为不变)、address 字符串数组、addresses 字符串数组(优先)", + "批量解析:按每 10 条合并为一个 DeepSeek 请求并行发出(deepseek-v4-flash),全部返回后按输入顺序聚合,单次上限 50 条;失败/缺失条目逐条回退单条解析,不影响其他条目", + "批量响应 data.list 每条元素包含 address/flag/message/province/city/area/town/detailAddress/name/mobile,失败条目 flag=failure、message 为具体错误原因、解析字段为空字符串,不影响其他条目", + "抽取 _parseSingleAddress 私有方法复用单条解析逻辑,单条响应结构与之前完全一致", + "同步更新 methods/system.json 中 parseAddress 的参数与响应字段说明" + ], + "module": "order" + }, { "version": "2026.08.14-afterSale.detail-desc-first-step", "date": "2026-08-14", diff --git a/methods/system.json b/methods/system.json index 9bede62..4bc7ebb 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1,8 +1,8 @@ { "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", - "version": "0.3.27", - "updatedAt": "2026-08-13", + "version": "0.3.28", + "updatedAt": "2026-08-15", "headers": [ { "name": "platform", @@ -4241,7 +4241,7 @@ }, { "method": "order.pendingOrder.parseAddress", - "description": "智能地址解析:使用 AI 将非结构化地址字符串解析为省/市/区/详细地址/收件人/手机号", + "description": "智能地址解析:使用 AI 将非结构化地址字符串解析为省/市/区/详细地址/收件人/手机号。支持单条解析与数组批量解析:address 传字符串时返回单条结果,addresses(或 address)传字符串数组时批量解析,响应 data.list 按输入顺序返回每条地址的解析结果(失败条目 flag=failure 不影响其他条目)。", "isNeedAuth": false, "isNeedLogin": true, "headers": [], @@ -4251,7 +4251,14 @@ "type": "string", "required": true, "source": "body", - "description": "原始地址字符串(必填),如\"张三 13800138000 广东省广州市天河区体育西路100号\"" + "description": "原始地址字符串(必填),如\"张三 13800138000 广东省广州市天河区体育西路100号\"。也支持传字符串数组批量解析(与 addresses 二选一)" + }, + { + "name": "addresses", + "type": "string[]", + "required": false, + "source": "body", + "description": "批量地址字符串数组,单次最多 50 条,按数组顺序返回解析结果" } ], "requestBody": [], @@ -4315,6 +4322,72 @@ "type": "string", "required": false, "description": "收件人手机号,如 13800138000" + }, + { + "name": "data.list", + "type": "array", + "required": false, + "description": "批量解析时返回的结果数组,按输入顺序排列;每条含 address/flag/message/province/city/area/town/detailAddress/name/mobile,失败条目 flag=failure 且解析字段为空字符串" + }, + { + "name": "data.list[].address", + "type": "string", + "required": false, + "description": "原始地址字符串(原样返回)" + }, + { + "name": "data.list[].flag", + "type": "string", + "required": false, + "description": "该条解析状态:success=成功,failure=失败" + }, + { + "name": "data.list[].message", + "type": "string", + "required": false, + "description": "该条解析提示:成功为 ok,失败为具体错误原因" + }, + { + "name": "data.list[].province", + "type": "string", + "required": false, + "description": "省份,如 广东省" + }, + { + "name": "data.list[].city", + "type": "string", + "required": false, + "description": "城市,如 广州市" + }, + { + "name": "data.list[].area", + "type": "string", + "required": false, + "description": "区/县,如 天河区" + }, + { + "name": "data.list[].town", + "type": "string", + "required": false, + "description": "乡镇/街道,如 员村街道" + }, + { + "name": "data.list[].detailAddress", + "type": "string", + "required": false, + "description": "详细地址,如 体育西路100号" + }, + { + "name": "data.list[].name", + "type": "string", + "required": false, + "description": "收件人姓名,如 张三" + }, + { + "name": "data.list[].mobile", + "type": "string", + "required": false, + "description": "收件人手机号,如 13800138000" } ], "errors": [ @@ -4322,6 +4395,14 @@ "code": 400, "message": "地址字符串不能为空" }, + { + "code": 400, + "message": "地址数组不能为空" + }, + { + "code": 400, + "message": "单次批量解析最多支持 50 条地址" + }, { "code": 500, "message": "地址解析失败(AI服务异常或密钥未配置)" @@ -4331,7 +4412,8 @@ "方法部署位置:systemMethods/order/pendingOrder/parseAddress", "使用 DeepSeek AI 模型进行智能解析", "解析结果可直接回填到 createOrder 的收件人信息字段", - "未识别到的字段返回空字符串" + "未识别到的字段返回空字符串", + "批量解析:addresses 或 address 传字符串数组,按每 10 条合并为一个请求并行发出,全部返回后按输入顺序聚合,单条失败不影响其他条目(模型 deepseek-v4-flash)" ] }, { From 0eb9e845dd381928fb9773fc61cd91909e20630f Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sat, 15 Aug 2026 20:10:37 +0800 Subject: [PATCH 210/550] =?UTF-8?q?fix(inbox):=20=E5=87=BD=E6=95=B0?= =?UTF-8?q?=E6=89=A7=E8=A1=8C=E5=89=8D=E6=8C=89=E7=BE=A4=E7=B1=BB=E5=9E=8B?= =?UTF-8?q?=E6=A0=A1=E9=AA=8C=E5=8F=AF=E7=94=A8=E6=80=A7=EF=BC=8C=E6=8B=A6?= =?UTF-8?q?=E6=88=AA=E8=B4=A7=E4=B8=BB=E7=BE=A4=E8=B6=8A=E6=9D=83=E8=B0=83?= =?UTF-8?q?=E7=94=A8=E5=BF=AB=E9=80=92=E7=BE=A4=E5=87=BD=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/inbox/functions.js | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/app/service/inbox/functions.js b/app/service/inbox/functions.js index 0861745..d09c7cd 100644 --- a/app/service/inbox/functions.js +++ b/app/service/inbox/functions.js @@ -3831,6 +3831,24 @@ class InboxFunctionsService extends Service { }; } + // 群类型权限过滤:按当前群的活跃分组校验函数可用性, + // 防止货主群调用快递群专属函数(如 handleExpressFeedback)等越权调用。 + // 无 groups 服务的场景(单元测试直接实例化)跳过校验,由调用方保证上下文。 + const groupsSvc = this.ctx.service && this.ctx.service.inbox && this.ctx.service.inbox.groups; + if (groupsSvc && typeof groupsSvc.isFunctionAvailable === 'function') { + const activeGroups = groupsSvc.resolveActiveGroups(); + if (!groupsSvc.isFunctionAvailable(def, activeGroups)) { + this.ctx.logger.warn( + `[inbox functions] 越权调用被拦截: ${name} ` + + `groups=${(def.groups || []).join(',')} active=${activeGroups.join(',')}` + ); + return { + success: false, + error: `函数 ${name} 在当前群类型下不可用,请通过对应类型的群发起`, + }; + } + } + try { const result = await def.handler(params); return result && typeof result === 'object' ? result : { success: true, data: result }; From 37104079e52ba59634278e74995f5387013525a3 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sat, 15 Aug 2026 20:12:23 +0800 Subject: [PATCH 211/550] =?UTF-8?q?feat(order):=20=E8=AE=A2=E5=8D=95/?= =?UTF-8?q?=E6=98=8E=E7=BB=86=20id=20=E9=98=B2=E5=9B=9E=E9=80=80=E2=80=94?= =?UTF-8?q?=E2=80=94=E5=BA=8F=E5=88=97=E8=A1=A8=E5=94=AF=E4=B8=80=E5=8F=91?= =?UTF-8?q?=E5=8F=B7=20+=20=E5=88=86=E8=A1=A8=E5=85=8D=E9=87=8D=E5=BB=BA?= =?UTF-8?q?=20+=20=E6=B0=B4=E4=BD=8D=E8=87=AA=E6=84=88=20+=20=E8=BF=81?= =?UTF-8?q?=E7=A7=BB=E4=BB=BB=E5=8A=A1=E6=89=A7=E8=A1=8C=E5=8E=86=E5=8F=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app.js | 12 + app/model/order_delivery_factory.js | 467 +++++++++++++-- app/model/order_delivery_table_schema.js | 155 ++++- app/model/order_items_factory.js | 232 ++++++- .../sync_outbound_orders_to_delivery.js | 36 +- app/service/qimenMethods/deliveryorder.js | 8 +- .../systemMethods/order/deliveryOrder.js | 84 ++- app/service/systems/delivery_order.js | 564 +++++++++++------- .../systems/order_delivery_migration.js | 22 + script/backfill-order-id-location.cjs | 245 ++++++++ 10 files changed, 1495 insertions(+), 330 deletions(-) create mode 100644 script/backfill-order-id-location.cjs diff --git a/app.js b/app.js index 94f2416..0223c5a 100644 --- a/app.js +++ b/app.js @@ -38,6 +38,18 @@ module.exports = app => { app.logger.error('❌ 工厂类初始化失败:', error); } + // 启动初检:异步为已有分表的仓库确保订单 id 序列表存在且水位正确。 + // 只做建表 + 水位抬升,不迁移数据(位置指针回填由 backfill-order-id-location 脚本负责); + // 异步执行不阻塞启动,失败仅告警,后续建单/迁移触发时还会再次 ensure。 + setImmediate(() => { + const factory = app.model && app.model.OrderDeliveryFactory; + if (factory && typeof factory.ensureAllLocationSequenceTables === 'function') { + factory.ensureAllLocationSequenceTables().catch(error => { + app.logger.warn(`[启动初检] 序列表初检异常: ${error && error.message ? error.message : error}`); + }); + } + }); + // 验证缓存方法 if (typeof app.setCacheAsync === 'function') { await app.setCacheAsync('system', 'wms', 10); diff --git a/app/model/order_delivery_factory.js b/app/model/order_delivery_factory.js index 41b42e5..962ca65 100644 --- a/app/model/order_delivery_factory.js +++ b/app/model/order_delivery_factory.js @@ -18,7 +18,9 @@ const { buildColumnLine, buildColumnLines, buildIndexLines, + isColumnDefinitionDifferent, parseManagedTableName, + AUTO_INCREMENT_SAFE_MARGIN, } = require('./order_delivery_table_schema'); const LANES = Object.freeze({ @@ -111,6 +113,7 @@ module.exports = app => { constructor() { this.modelCache = new Map(); this.inflightInitCache = new Map(); + this.locationTableReady = new Map(); this.app = app; } @@ -539,32 +542,7 @@ module.exports = app => { } for (const columnName of expectedAttributeNames) { - const expectedColumn = expectedAttributes[columnName]; - const actualColumn = tables[columnName] || {}; - const expectedType = expectedColumn.type && typeof expectedColumn.type.toSql === 'function' - ? expectedColumn.type.toSql().toLowerCase() - : String(expectedColumn.type || '').toLowerCase(); - const actualType = String(actualColumn.type || actualColumn.Type || '').toLowerCase(); - const expectedAllowNull = expectedColumn.allowNull !== false; - const actualAllowNull = actualColumn.allowNull !== false; - const expectedDefault = Object.prototype.hasOwnProperty.call(expectedColumn, 'defaultValue') - ? expectedColumn.defaultValue - : undefined; - const actualDefault = Object.prototype.hasOwnProperty.call(actualColumn, 'defaultValue') - ? actualColumn.defaultValue - : undefined; - - if (expectedType && actualType && expectedType !== actualType) { - return true; - } - - if (expectedAllowNull !== actualAllowNull) { - return true; - } - - const normalizedExpectedDefault = expectedDefault == null ? null : String(expectedDefault); - const normalizedActualDefault = actualDefault == null ? null : String(actualDefault); - if (normalizedExpectedDefault !== normalizedActualDefault) { + if (isColumnDefinitionDifferent(columnName, expectedAttributes[columnName], tables[columnName])) { return true; } } @@ -678,6 +656,92 @@ module.exports = app => { } } + /** + * 获取同仓库共享 id 序列的全部分表的 MAX(id) 基线。 + * + * 多表共用 id 契约:订单迁移到配送表时显式复制源 id,因此新分配的 + * id 必须大于所有分表已占用的 id。 + * + * @param {number|string} warehouseId 仓库ID。 + * @return {Promise} 最大 id,无任何分表时返回 0。 + */ + async getSharedIdBaseline(warehouseId) { + const tables = [ + buildManagedTableName(warehouseId, 'current'), + buildManagedTableName(warehouseId, 'dispatch'), + buildManagedTableName(warehouseId, 'history'), + buildManagedTableName(warehouseId, 'outsourced'), + ]; + + let existingTableSet = null; + try { + existingTableSet = new Set(await this.app.model.getQueryInterface().showAllTables()); + } catch (error) { + existingTableSet = null; + } + + let baseline = 0; + for (const relatedTable of tables) { + const exists = existingTableSet + ? existingTableSet.has(relatedTable) + : await this.checkTableExists(relatedTable); + + if (!exists) { + continue; + } + + const [ rows ] = await this.app.model.query( + `SELECT COALESCE(MAX(id), 0) AS maxId FROM ${quoteIdentifier(relatedTable)}` + ); + const maxId = Number(rows && rows[0] && rows[0].maxId || 0); + + if (Number.isFinite(maxId) && maxId > baseline) { + baseline = maxId; + } + } + + return baseline; + } + + /** + * 核对并修复表自增水位,确保 AUTO_INCREMENT 大于同仓库共享 id 序列 + * 的全部分表(current/dispatch/history/outsourced)的 MAX(id)。 + * + * 多表共用 id 契约:订单迁移到配送表时显式复制源 id。因此 current 表的 + * 自增序列必须全局单调——新分配的 id 不能与任何分表已占用的 id 重叠。 + * 若高 id 订单已迁走(current 表 MAX(id) 变小),表重建会把水位重置为 + * current.MAX(id)+1,与配送表已占用的 id 重叠,后续迁移显式插入会撞主键。 + * 所以水位基准必须取所有分表的最大 MAX(id)。 + * + * @param {string} tableName 表名。 + * @return {Promise} + */ + async ensureAutoIncrementWatermark(tableName) { + const parsed = parseManagedTableName(tableName); + if (!parsed) { + return; + } + + const baseline = await this.getSharedIdBaseline(parsed.warehouseId); + if (!Number.isFinite(baseline) || baseline <= 0) { + return; + } + + const autoIncrement = await this.getTableAutoIncrement(tableName); + if (autoIncrement === null || autoIncrement > baseline) { + return; + } + + // 修复目标加安全余量:防止读取 MAX(id) 与 SET 之间的并发插入抢先占号, + // 导致修复后水位再次低于已分配 id(MySQL 不会把计数器降到当前已分配值以下, + // 余量仅作为并发窗口的缓冲) + const safeTarget = baseline + AUTO_INCREMENT_SAFE_MARGIN; + await this.app.model.query(`ALTER TABLE ${quoteIdentifier(tableName)} AUTO_INCREMENT = ${safeTarget}`); + this.app.logger.warn( + `订单工厂表 ${tableName} 自增水位低于共享 id 序列最大 id(auto=${autoIncrement}, max=${baseline}),已修复为 ${safeTarget}` + ); + } + /** * 确保单个目标表与模型结构一致。 * @param {string} tableName 表名。 @@ -695,29 +759,310 @@ module.exports = app => { ? await this.needsTableSchemaSync(tableName, modelType, warehouseId, tableExists) : true; - if (!needsSync) { - return false; - } - if (!tableExists) { await dynamicModel.sync({ force: false }); return true; } - await this.assertManagedTableDataConstraints(tableName, modelType); - await this.alterManagedTableSchema(tableName, modelType, warehouseId, dynamicModel); - return true; + if (needsSync) { + await this.assertManagedTableDataConstraints(tableName, modelType); + await this.alterManagedTableSchema(tableName, modelType, warehouseId); + } + + // 无论是否同步结构,都核对自增水位(表重建/迁移/手工修复都可能破坏水位) + await this.ensureAutoIncrementWatermark(tableName); + return needsSync; + } + + /** + * 读取表的当前 AUTO_INCREMENT 水位。 + * @param {string} tableName 表名。 + * @return {Promise} 自增水位,非自增表返回 null。 + */ + async getTableAutoIncrement(tableName) { + const [ rows ] = await this.app.model.query( + 'SELECT AUTO_INCREMENT AS autoIncrement FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?', + { replacements: [ tableName ] } + ); + + const rawValue = rows && rows[0] && rows[0].autoIncrement; + const value = Number(rawValue); + return Number.isFinite(value) ? value : null; + } + + /** + * 获取仓库订单 id 序列表名。 + * + * 每仓库一张序列表:id 自增发号,location 记录订单数据当前所在表位。 + * + * @param {number|string} warehouseId 仓库ID。 + * @return {string} 序列表名。 + */ + getLocationSequenceTableName(warehouseId) { + return `wms_order_id_location_${warehouseId}`; + } + + /** + * 确保仓库订单 id 序列表存在,并将其自增水位抬升到同仓库所有 + * 订单分表 MAX(id) 之上(避开存量订单 id)。 + * + * 注意:本方法可能执行 DDL(隐式提交),必须在事务外调用。 + * + * @param {number|string} warehouseId 仓库ID。 + * @return {Promise} + */ + async ensureLocationSequenceTable(warehouseId) { + const tableName = this.getLocationSequenceTableName(warehouseId); + + // 进程内已初始化过则跳过:避免每次建单都重复 showAllTables + 分表 MAX 核对 + if (this.locationTableReady.get(warehouseId)) { + return; + } + + // 并发去重:同一仓库并发的 ensure 共享同一个初始化 Promise, + // 保证「建表 + 抬水位」只执行一次,其余调用等待完成后直接返回。 + return await this.runModelInitializer(`init_seq_${warehouseId}`, async () => { + if (this.locationTableReady.get(warehouseId)) { + return; + } + + // 先算基线再建表:建表语句直接携带正确水位。 + // 消除「先建表(水位=1)再 ALTER」之间的发号窗口——否则窗口内 + // 并发建单/多 worker 发号会拿到 1,与存量订单 id 冲突。 + const baseline = await this.getSharedIdBaseline(warehouseId); + const safeTarget = baseline > 0 ? baseline + AUTO_INCREMENT_SAFE_MARGIN : 0; + + const exists = await this.checkTableExists(tableName); + + if (!exists) { + const autoIncrementClause = safeTarget > 0 ? ` AUTO_INCREMENT = ${safeTarget}` : ''; + try { + await this.app.model.query( + `CREATE TABLE ${quoteIdentifier(tableName)} ( + \`id\` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + \`location\` VARCHAR(20) NOT NULL DEFAULT 'current', + PRIMARY KEY (\`id\`) + ) ENGINE=InnoDB${autoIncrementClause} DEFAULT CHARSET=utf8mb4 COMMENT='仓库订单全局id序列与位置索引(极简,不迁移)'` + ); + this.app.logger.info(`创建订单 id 序列表成功: ${tableName}${safeTarget > 0 ? `, 初始水位=${safeTarget}` : ''}`); + } catch (createError) { + const errorCode = createError + && ((createError.original && createError.original.code) + || (createError.parent && createError.parent.code) + || createError.code); + if (errorCode !== 'ER_TABLE_EXISTS') { + throw createError; + } + // 并发窗口:其他 worker 已建表,转入下方已存在核对分支 + this.app.logger.warn(`订单 id 序列表 ${tableName} 已被并发创建,转入水位核对`); + } + } + + // 表已存在(或刚被并发创建):核对并抬升水位 + if (safeTarget > 0) { + const autoIncrement = await this.getTableAutoIncrement(tableName); + // ai 为 null(MariaDB 新建表/计数器未初始化)同样视为需要抬升 + if (autoIncrement === null || autoIncrement <= baseline) { + await this.app.model.query( + `ALTER TABLE ${quoteIdentifier(tableName)} AUTO_INCREMENT = ${safeTarget}` + ); + this.app.logger.warn( + `订单 id 序列表 ${tableName} 水位抬升至 ${safeTarget}(分表最大 id=${baseline},原水位=${autoIncrement ?? 'null'})` + ); + } + } + + this.locationTableReady.set(warehouseId, true); + }); + } + + /** + * 启动初检:为当前库中已存在的订单分表仓库确保序列表存在且水位正确。 + * + * 仅做「建表 + 水位抬升」,不迁移任何数据——存量订单的位置指针回填由 + * `script/backfill-order-id-location.cjs` 脚本负责。单个仓库失败仅告警, + * 不影响其他仓库与服务启动。 + * + * @return {Promise} 完成初检的仓库数。 + */ + async ensureAllLocationSequenceTables() { + const managedTableNames = await this.listManagedTableNames(); + const warehouseIds = Array.from(new Set( + managedTableNames + .map(tableName => { + const parsed = parseManagedTableName(tableName); + return parsed ? parsed.warehouseId : null; + }) + .filter(Boolean) + )); + + let checkedCount = 0; + for (const warehouseId of warehouseIds) { + try { + await this.ensureLocationSequenceTable(warehouseId); + checkedCount += 1; + } catch (error) { + this.app.logger.warn(`[启动初检] 仓库 ${warehouseId} 序列表初始化失败: ${error.message}`); + } + } + + if (warehouseIds.length > 0) { + this.app.logger.info(`[启动初检] 订单 id 序列表初检完成: ${checkedCount}/${warehouseIds.length} 个仓库`); + } + return checkedCount; + } + + /** + * 从仓库序列表分配全局订单 id(在调用方事务内执行,随事务回滚)。 + * + * 调用方必须在事务外先调用 ensureLocationSequenceTable 完成建表。 + * + * @param {number|string} warehouseId 仓库ID。 + * @param {Object} [transaction] Sequelize 事务。 + * @param {string} [location='current'] 初始位置(current/dispatch/history/outsourced)。 + * @return {Promise} 新分配的订单 id。 + */ + async allocateOrderId(warehouseId, transaction = null, location = 'current') { + const tableName = this.getLocationSequenceTableName(warehouseId); + + if (!this.locationTableReady.get(warehouseId)) { + const exists = await this.checkTableExists(tableName); + if (!exists) { + // 不允许在事务内隐式 DDL,交给调用方在事务外初始化 + throw new Error(`订单 id 序列表 ${tableName} 不存在,请先调用 ensureLocationSequenceTable`); + } + this.locationTableReady.set(warehouseId, true); + } + + const options = transaction ? { transaction } : {}; + const queryResult = await this.app.model.query( + `INSERT INTO ${quoteIdentifier(tableName)} (\`location\`) VALUES (?)`, + { replacements: [ location ], ...options } + ); + // sequelize.query 对 INSERT 的返回形态随驱动不同,兼容解析: + // - mysql2: [ insertId, affectedRows ](首个元素是数字) + // - 其他包装: [{ insertId, affectedRows }, ...] + const raw = Array.isArray(queryResult) ? queryResult[0] : queryResult; + let insertId = 0; + if (typeof raw === 'number') { + insertId = raw; + } else if (raw && typeof raw === 'object' && !Array.isArray(raw)) { + insertId = Number(raw.insertId || 0); + } else if (Array.isArray(raw) && raw.length > 0 && typeof raw[0] === 'number') { + insertId = Number(raw[0]); + } + if (!Number.isFinite(insertId) || insertId <= 0) { + throw new Error('订单 id 分配失败'); + } + + return insertId; + } + + /** + * 更新订单在序列表中的位置指针(迁移时调用)。 + * + * 存量订单(序列表无记录)以显式 id 补录;显式插入值大于当前水位时 + * MySQL 会自动推进序列表自增,保证后续发号不与存量 id 冲突。 + * + * @param {number|string} orderId 订单ID。 + * @param {number|string} warehouseId 仓库ID。 + * @param {string} location 新位置。 + * @param {Object} [transaction] Sequelize 事务。 + * @return {Promise} + */ + async updateOrderLocation(orderId, warehouseId, location, transaction = null) { + const tableName = this.getLocationSequenceTableName(warehouseId); + const options = transaction ? { transaction } : {}; + + await this.app.model.query( + `INSERT INTO ${quoteIdentifier(tableName)} (\`id\`, \`location\`) VALUES (?, ?) ON DUPLICATE KEY UPDATE \`location\` = VALUES(\`location\`)`, + { replacements: [ Number(orderId), location ], ...options } + ); + } + + /** + * 查询单个订单当前所在表位。 + * + * @param {number|string} orderId 订单ID。 + * @param {number|string} warehouseId 仓库ID。 + * @param {Object} [transaction] Sequelize 事务。 + * @return {Promise} 位置(current/dispatch/history/outsourced), + * 无记录返回 null(存量订单未回填)。 + */ + async getOrderLocation(orderId, warehouseId, transaction = null) { + const tableName = this.getLocationSequenceTableName(warehouseId); + if (!this.locationTableReady.get(warehouseId)) { + const exists = await this.checkTableExists(tableName); + if (!exists) { + return null; + } + this.locationTableReady.set(warehouseId, true); + } + + const options = transaction ? { transaction } : {}; + const [ rows ] = await this.app.model.query( + `SELECT \`location\` FROM ${quoteIdentifier(tableName)} WHERE \`id\` = ? LIMIT 1`, + { replacements: [ Number(orderId) ], ...options } + ); + return rows && rows[0] ? String(rows[0].location) : null; + } + + /** + * 批量查询订单当前所在表位。 + * + * @param {Array} orderIds 订单ID列表。 + * @param {number|string} warehouseId 仓库ID。 + * @param {Object} [transaction] Sequelize 事务。 + * @return {Promise>} orderId → location; + * 无记录的订单不在 Map 中(存量订单未回填)。 + */ + async getOrderLocations(orderIds, warehouseId, transaction = null) { + const result = new Map(); + const normalizedIds = Array.from(new Set( + (Array.isArray(orderIds) ? orderIds : [ orderIds ]) + .map(id => Number(id)) + .filter(id => Number.isFinite(id) && id > 0) + )); + if (normalizedIds.length === 0) { + return result; + } + + const tableName = this.getLocationSequenceTableName(warehouseId); + if (!this.locationTableReady.get(warehouseId)) { + const exists = await this.checkTableExists(tableName); + if (!exists) { + return result; + } + this.locationTableReady.set(warehouseId, true); + } + + const options = transaction ? { transaction } : {}; + const placeholders = normalizedIds.map(() => '?').join(','); + const [ rows ] = await this.app.model.query( + `SELECT \`id\`, \`location\` FROM ${quoteIdentifier(tableName)} WHERE \`id\` IN (${placeholders})`, + { replacements: normalizedIds, ...options } + ); + + for (const row of rows || []) { + result.set(Number(row.id), String(row.location)); + } + return result; } /** * 将现有表的列结构与期望模型对齐,所有变更合并为单条 ALTER TABLE 语句。 + * + * 自增保护:对自增主键 id 列不做 CHANGE——对 AUTO_INCREMENT 列重新声明 + * 列定义可能触发表重建(ALGORITHM=COPY),重建后 AUTO_INCREMENT 被重置为 + * MAX(id)+1。待处理表的高 id 订单已迁移删除,重置会使自增水位回退到历史 + * 低值,与配送表已复制的 id 重叠,导致后续迁移主键冲突。 + * * @param {string} tableName 表名。 * @param {string} type 模型类型。 * @param {number|string} warehouseId 仓库ID。 - * @param {Object} dynamicModel 已构建的动态模型(用于索引同步)。 * @return {Promise} */ - async alterManagedTableSchema(tableName, type, warehouseId, dynamicModel) { + async alterManagedTableSchema(tableName, type, warehouseId) { const queryInterface = this.app.model.getQueryInterface(); const sequelize = this.app.model; const actualColumns = await queryInterface.describeTable(tableName); @@ -727,17 +1072,27 @@ module.exports = app => { const expectedColumnNames = Object.keys(expectedAttributes); const clauses = []; - // ADD 新增列 / CHANGE 变更列 + // ADD 新增列 / CHANGE 差异列;id 主键列永不参与 CHANGE——对 AUTO_INCREMENT + // 列重新声明列定义可能触发表重建(ALGORITHM=COPY),重建后 AUTO_INCREMENT 被重置为 + // MAX(id)+1。待处理表的高 id 订单已迁移删除,重置会使自增水位回退到历史低值, + // 与配送表已复制的 id 重叠,导致后续迁移主键冲突。 for (const columnName of expectedColumnNames) { - const columnDef = buildColumnLine(columnName, expectedAttributes[columnName]); + const expectedAttribute = expectedAttributes[columnName]; + + if (columnName === 'id') { + continue; + } + + const columnDef = buildColumnLine(columnName, expectedAttribute); + if (!actualColumnNames.has(columnName)) { clauses.push(`ADD COLUMN ${columnDef}`); - } else { + } else if (isColumnDefinitionDifferent(columnName, expectedAttribute, actualColumns[columnName])) { clauses.push(`CHANGE ${quoteIdentifier(columnName)} ${columnDef}`); } } - // DROP 多余列(现有表有但期望模型没有的列) + // DROP 多余列(现有表有但期望模型没有的列;id 必在期望模型中,不会被 DROP) const expectedColumnSet = new Set(expectedColumnNames); for (const columnName of actualColumnNames) { if (!expectedColumnSet.has(columnName)) { @@ -745,12 +1100,39 @@ module.exports = app => { } } + const previousAutoIncrement = await this.getTableAutoIncrement(tableName); + if (clauses.length > 0) { await sequelize.query(`ALTER TABLE ${quotedTableName} ${clauses.join(', ')}`); } - // 索引同步仍委托 Sequelize sync({ alter: true }) 处理(仅触发索引差异) - await dynamicModel.sync({ alter: true }); + // 若 ALTER 触发表重建并把自增水位重置到历史低值,恢复原水位 + const currentAutoIncrement = await this.getTableAutoIncrement(tableName); + if (previousAutoIncrement !== null + && currentAutoIncrement !== null + && currentAutoIncrement < previousAutoIncrement) { + await sequelize.query(`ALTER TABLE ${quotedTableName} AUTO_INCREMENT = ${previousAutoIncrement}`); + this.app.logger.warn( + `订单工厂表 ${tableName} 自增水位被 ALTER 重置(${previousAutoIncrement} → ${currentAutoIncrement}),已恢复为 ${previousAutoIncrement}` + ); + } + + // 索引同步不再使用 sync({ alter: true }):历史事故表明它会重建表并重置自增水位, + // 且无法可靠检测 AUTO_INCREMENT 属性差异。改为仅补齐缺失索引,不重建、不删除已有索引。 + const existingIndexNames = new Set((await queryInterface.showIndex(tableName)) + .map(index => index.Key_name || index.name || '') + .filter(Boolean)); + + for (const indexDef of this.getIndexes(warehouseId, type)) { + if (existingIndexNames.has(indexDef.name)) { + continue; + } + + await queryInterface.addIndex(tableName, indexDef.fields, { + name: indexDef.name, + unique: Boolean(indexDef.unique), + }); + } } /** @@ -781,7 +1163,8 @@ module.exports = app => { const tableName = this.generateTableName(warehouseId, modelType); const dynamicModel = this.buildManagedModel(warehouseId, modelType, tableName); - await dynamicModel.sync({ alter: true }); + // 统一走差异检测 + 自增水位保护的同步路径,不再使用 sync({ alter: true }) + await this.ensureManagedTableSchema(tableName, modelType, warehouseId, dynamicModel); this.app.logger.info(`创建/同步物理表成功: ${tableName}`); } diff --git a/app/model/order_delivery_table_schema.js b/app/model/order_delivery_table_schema.js index 70a377a..0ca9eff 100644 --- a/app/model/order_delivery_table_schema.js +++ b/app/model/order_delivery_table_schema.js @@ -7,6 +7,16 @@ const MANAGED_TYPES = Object.freeze({ OUTSOURCED: 'outsourced', }); +/** + * 自增水位修复时的安全余量。 + * + * 修复水位时会读取各分表 MAX(id) 作为基准,但读取与 SET 之间存在并发窗口: + * 其他请求可能正在抢号分配更大的 id。若 SET 值刚好是 MAX(id)+1,并发插入 + * 提交后表内 max 可能再次超过水位。预留余量(跳过若干 id)可避免该竞态, + * BIGINT 空间下跳过几十个 id 无实际影响。 + */ +const AUTO_INCREMENT_SAFE_MARGIN = 50; + const TABLE_PATTERNS = Object.freeze([ { type: MANAGED_TYPES.DISPATCH, @@ -210,7 +220,10 @@ function formatDefaultValue(defaultValue) { } if (defaultValue && typeof defaultValue.toSql === 'function') { - return defaultValue.toSql(); + const rawSql = String(defaultValue.toSql()); + // Sequelize.NOW 的 toSql() 返回 'NOW',MySQL/MariaDB 的 DATETIME 列 + // 默认值必须写成 CURRENT_TIMESTAMP,否则生成 DEFAULT NOW 非法语法 + return rawSql.trim().toUpperCase() === 'NOW' ? 'CURRENT_TIMESTAMP' : rawSql; } if (typeof defaultValue === 'string') { @@ -230,12 +243,11 @@ function formatDefaultValue(defaultValue) { } /** - * 将 Sequelize 属性定义转换为 DDL 列片段。 - * @param {string} columnName 列名。 + * 生成属性的类型 SQL 片段。 * @param {Object} attribute Sequelize 属性定义。 - * @return {string} DDL 列片段。 + * @return {string} 类型 SQL 片段。 */ -function buildColumnLine(columnName, attribute) { +function buildColumnTypeSql(attribute) { let typeSql; if (attribute.type && Array.isArray(attribute.type.values)) { @@ -249,6 +261,129 @@ function buildColumnLine(columnName, attribute) { typeSql = String(attribute.type || ''); } + // 无 dialect 绑定时 DataTypes.DATE 序列化为 'DATE', + // 但 MySQL 实际列类型是 DATETIME;DDL 若输出 DATE 会把时间部分截断 + if (typeSql && String(typeSql).trim().toUpperCase() === 'DATE') { + typeSql = 'DATETIME'; + } + + return typeSql; +} + +/** + * 归一化列类型 SQL,用于模型定义与实际表结构的语义比对。 + * + * 消除不会影响语义的差异,避免比对恒真而反复执行 ALTER: + * - INTEGER 与 INT 在 MySQL 中是同义词; + * - 整型 display width(如 BIGINT(20)、INT(11))不影响语义, + * 且 MySQL 8.0.19+ 的 information_schema 不再返回 display width; + * - 大小写与空格差异。 + * + * @param {string} sql 类型 SQL。 + * @return {string} 归一化后的类型 SQL。 + */ +function normalizeColumnTypeSql(sql) { + let normalized = String(sql || '') + .trim() + .replace(/\s+/g, ' ') + .toUpperCase(); + + normalized = normalized.replace(/^INTEGER\b/, 'INT'); + normalized = normalized.replace(/^(TINYINT|SMALLINT|MEDIUMINT|INT|BIGINT)\s*\(\s*\d+\s*\)/, '$1'); + + // Sequelize 无 dialect 绑定时 DATE 序列化为 'DATE',而 MySQL 实际列类型为 DATETIME + if (normalized === 'DATE') { + normalized = 'DATETIME'; + } + + // 删除逗号两侧空格(ENUM 值列表、DECIMAL(18, 2) 等) + normalized = normalized.replace(/\s*,\s*/g, ','); + + return normalized; +} + +/** + * 判断列定义是否与模型期望存在语义差异。 + * + * 与 needsTableSchemaSync / alterManagedTableSchema 共用同一套比较规则, + * 保证“判定需要同步”与“生成 ALTER 子句”不会漂移。 + * + * @param {string} columnName 列名。 + * @param {Object} expectedAttribute 模型期望的属性定义。 + * @param {Object} actualColumn describeTable 返回的实际列定义。 + * @return {boolean} 是否存在语义差异。 + */ +function isColumnDefinitionDifferent(columnName, expectedAttribute, actualColumn) { + const expectedType = normalizeColumnTypeSql(buildColumnTypeSql(expectedAttribute)); + const actualType = normalizeColumnTypeSql(actualColumn && (actualColumn.type || actualColumn.Type) || ''); + + if (expectedType && actualType && expectedType !== actualType) { + return true; + } + + // 主键/自增列在建表时由 Sequelize 自动补 NOT NULL, + // 即使模型定义未显式声明 allowNull: false,实际列也是 NOT NULL + const expectedAllowNull = expectedAttribute.primaryKey || expectedAttribute.autoIncrement + ? false + : expectedAttribute.allowNull !== false; + const actualAllowNull = (actualColumn && actualColumn.allowNull) !== false; + + if (expectedAllowNull !== actualAllowNull) { + return true; + } + + const expectedDefault = Object.prototype.hasOwnProperty.call(expectedAttribute, 'defaultValue') + ? expectedAttribute.defaultValue + : undefined; + const actualDefault = Object.prototype.hasOwnProperty.call(actualColumn || {}, 'defaultValue') + ? actualColumn.defaultValue + : undefined; + + // Sequelize.literal(如 CURRENT_TIMESTAMP)提取其原始表达式参与比较; + // Sequelize.NOW 的 val 为 'NOW',与表内实际 DEFAULT CURRENT_TIMESTAMP 归一 + const extractDefaultValue = value => { + if (value && typeof value === 'object' && typeof value.val === 'string') { + return String(value.val).trim().toUpperCase() === 'NOW' ? 'CURRENT_TIMESTAMP' : value.val; + } + return value; + }; + + const normalizedExpectedDefault = extractDefaultValue(expectedDefault) == null + ? null + : String(extractDefaultValue(expectedDefault)); + const normalizedActualDefault = extractDefaultValue(actualDefault) == null + ? null + : String(extractDefaultValue(actualDefault)); + + if (normalizedExpectedDefault === normalizedActualDefault) { + return false; + } + + // 数字默认值允许不同文本表示(如 '0' 与 '0.00'),只要数值相等即视为一致 + if (normalizedExpectedDefault !== null && normalizedActualDefault !== null) { + const expectedNumber = Number(normalizedExpectedDefault); + const actualNumber = Number(normalizedActualDefault); + + if (normalizedExpectedDefault !== '' + && normalizedActualDefault !== '' + && Number.isFinite(expectedNumber) + && Number.isFinite(actualNumber) + && expectedNumber === actualNumber) { + return false; + } + } + + return true; +} + +/** + * 将 Sequelize 属性定义转换为 DDL 列片段。 + * @param {string} columnName 列名。 + * @param {Object} attribute Sequelize 属性定义。 + * @return {string} DDL 列片段。 + */ +function buildColumnLine(columnName, attribute) { + const typeSql = buildColumnTypeSql(attribute); const parts = [ `\`${columnName}\``, typeSql ]; if (attribute.allowNull === false) { @@ -283,6 +418,12 @@ function buildTableAttributes(app, type) { const modelType = normalizeManagedType(type); const attributes = cloneAttributes(app.model.OrderDelivery.rawAttributes); + // 分表 id 统一由仓库序列表显式分配,分表自身不再携带自增序列。 + // 保留两套发号序列(分表自增 + 序列表)会在降级等场景产生区间重叠的冲突 id, + // 这里从模型层移除 autoIncrement:新建分表不再带 AUTO_INCREMENT; + // 已有分表结构保持不变(不执行任何 id 列变更),显式 id 插入不受影响。 + attributes.id = { ...attributes.id, autoIncrement: false }; + if (isDispatchType(modelType)) { const { ENUM } = app.Sequelize; attributes.dispatch_lane = { @@ -513,6 +654,7 @@ function parseManagedTableName(tableName) { module.exports = { MANAGED_TYPES, + AUTO_INCREMENT_SAFE_MARGIN, normalizeManagedType, isDispatchType, isHistoryType, @@ -525,6 +667,9 @@ module.exports = { buildTableComment, buildTableOptions, buildIndexOptions, + buildColumnTypeSql, + normalizeColumnTypeSql, + isColumnDefinitionDifferent, buildColumnLine, buildColumnLines, buildIndexLines, diff --git a/app/model/order_items_factory.js b/app/model/order_items_factory.js index a370b87..5f5d04e 100644 --- a/app/model/order_items_factory.js +++ b/app/model/order_items_factory.js @@ -5,6 +5,20 @@ const { ensureShardWarehouseId, clearShardWarehouseValidationCache, } = require('../lib/warehouse_shard_guard'); +const { + isColumnDefinitionDifferent, + buildColumnLine, + AUTO_INCREMENT_SAFE_MARGIN, +} = require('./order_delivery_table_schema'); + +/** + * 转义 SQL 标识符。 + * @param {string} identifier 标识符。 + * @return {string} 转义后的标识符。 + */ +function quoteIdentifier(identifier) { + return `\`${String(identifier).replace(/`/g, '``')}\``; +} /** * 克隆模型属性定义。 @@ -266,7 +280,11 @@ module.exports = app => { getTableAttributes(type) { const mainModel = this.app.model.OrderItems; const attributes = cloneAttributes(mainModel && mainModel.rawAttributes); - + // 模型 timestamps:true 会向 rawAttributes 注入 createdAt/updatedAt + // (与显式定义的 created_at/updated_at 指向同一列),结构对齐时会被 + // 误判为缺失列而 ADD COLUMN,导致重复列与无默认值报错,剔除这两个注入属性。 + delete attributes.createdAt; + delete attributes.updatedAt; // 保留 id 字段的 autoIncrement,与 order_delivery_factory 行为一致, // 确保分表 wms_order_items_{warehouseId} 的 bulkCreate 能正常自增生成 id @@ -389,33 +407,7 @@ module.exports = app => { } for (const columnName of expectedAttributeNames) { - const expectedColumn = expectedAttributes[columnName]; - const actualColumn = tables[columnName] || {}; - const expectedType = expectedColumn.type && typeof expectedColumn.type.toSql === 'function' - ? expectedColumn.type.toSql().toLowerCase() - : String(expectedColumn.type || '').toLowerCase(); - const actualType = String(actualColumn.type || actualColumn.Type || '').toLowerCase(); - const expectedAllowNull = expectedColumn.allowNull !== false; - const actualAllowNull = actualColumn.allowNull !== false; - const expectedDefault = Object.prototype.hasOwnProperty.call(expectedColumn, 'defaultValue') - ? expectedColumn.defaultValue - : undefined; - const actualDefault = Object.prototype.hasOwnProperty.call(actualColumn, 'defaultValue') - ? actualColumn.defaultValue - : undefined; - - if (expectedType && actualType && expectedType !== actualType) { - return true; - } - - if (expectedAllowNull !== actualAllowNull) { - return true; - } - - const normalizedExpectedDefault = expectedDefault == null ? null : String(expectedDefault); - const normalizedActualDefault = actualDefault == null ? null : String(actualDefault); - - if (normalizedExpectedDefault !== normalizedActualDefault) { + if (isColumnDefinitionDifferent(columnName, expectedAttributes[columnName], tables[columnName])) { return true; } } @@ -438,6 +430,170 @@ module.exports = app => { return false; } + /** + * 读取表的当前 AUTO_INCREMENT 水位。 + * @param {string} tableName 表名。 + * @return {Promise} 自增水位,非自增表返回 null。 + */ + async getTableAutoIncrement(tableName) { + const [ rows ] = await this.app.model.query( + 'SELECT AUTO_INCREMENT AS autoIncrement FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?', + { replacements: [ tableName ] } + ); + + const rawValue = rows && rows[0] && rows[0].autoIncrement; + const value = Number(rawValue); + return Number.isFinite(value) ? value : null; + } + + /** + * 核对并修复表自增水位,确保 AUTO_INCREMENT 大于同仓库共享 id 序列 + * 的全部分表(current/dispatch/history)的 MAX(id)。 + * + * 明细迁移到配送明细表时同样显式复制源 id,因此 current 明细表的 + * 自增序列必须全局单调,水位基准取所有分表的最大 MAX(id)。 + * + * @param {string} tableName 表名。 + * @return {Promise} + */ + async ensureAutoIncrementWatermark(tableName) { + const sequelize = this.app.model; + const matched = /^wms_order_items_(\d+)(?:_(dispatch|history))?$/.exec(tableName); + const relatedTables = matched + ? [ + tableName, + `wms_order_items_${matched[1]}`, + `wms_order_items_${matched[1]}_dispatch`, + `wms_order_items_${matched[1]}_history`, + ] + : [ tableName ]; + + let existingTableSet = null; + try { + existingTableSet = new Set(await sequelize.getQueryInterface().showAllTables()); + } catch (error) { + existingTableSet = null; + } + + let baseline = 0; + for (const relatedTable of new Set(relatedTables)) { + const exists = existingTableSet + ? existingTableSet.has(relatedTable) + : await this.checkTableExists(relatedTable); + + if (!exists) { + continue; + } + + const [ rows ] = await sequelize.query( + `SELECT COALESCE(MAX(id), 0) AS maxId FROM \`${relatedTable}\`` + ); + const maxId = Number(rows && rows[0] && rows[0].maxId || 0); + + if (Number.isFinite(maxId) && maxId > baseline) { + baseline = maxId; + } + } + + if (!Number.isFinite(baseline) || baseline <= 0) { + return; + } + + const autoIncrement = await this.getTableAutoIncrement(tableName); + if (autoIncrement === null || autoIncrement > baseline) { + return; + } + + // 修复目标加安全余量:防止读取 MAX(id) 与 SET 之间的并发插入抢先占号 + const safeTarget = baseline + AUTO_INCREMENT_SAFE_MARGIN; + await sequelize.query(`ALTER TABLE \`${tableName}\` AUTO_INCREMENT = ${safeTarget}`); + this.app.logger.warn( + `订单商品工厂表 ${tableName} 自增水位低于共享 id 序列最大 id(auto=${autoIncrement}, max=${baseline}),已修复为 ${safeTarget}` + ); + } + + /** + * 将现有表的列结构与期望模型对齐,所有变更合并为单条 ALTER TABLE 语句。 + * + * 自增保护:对自增主键 id 列不做 CHANGE——对 AUTO_INCREMENT 列重新声明 + * 列定义可能触发表重建(ALGORITHM=COPY),重建后 AUTO_INCREMENT 被重置为 + * MAX(id)+1,与 dispatch/history 已复制的 id 重叠,导致后续迁移主键冲突。 + * 索引同步仅补齐缺失索引,不重建、不删除已有索引。 + * + * @param {string} tableName 表名。 + * @param {string} type 模型类型。 + * @param {number|string} warehouseId 仓库ID。 + * @return {Promise} + */ + async alterManagedTableSchema(tableName, type, warehouseId) { + const sequelize = this.app.model; + const queryInterface = sequelize.getQueryInterface(); + 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 差异列;id 主键列永不参与 CHANGE,避免重建表重置自增水位 + for (const columnName of expectedColumnNames) { + const expectedAttribute = expectedAttributes[columnName]; + + if (columnName === 'id') { + continue; + } + + const columnDef = buildColumnLine(columnName, expectedAttribute); + + if (!actualColumnNames.has(columnName)) { + clauses.push(`ADD COLUMN ${columnDef}`); + } else if (isColumnDefinitionDifferent(columnName, expectedAttribute, actualColumns[columnName])) { + clauses.push(`CHANGE ${quoteIdentifier(columnName)} ${columnDef}`); + } + } + + // DROP 多余列(现有表有但期望模型没有的列;id 必在期望模型中,不会被 DROP) + const expectedColumnSet = new Set(expectedColumnNames); + for (const columnName of actualColumnNames) { + if (!expectedColumnSet.has(columnName)) { + clauses.push(`DROP COLUMN ${quoteIdentifier(columnName)}`); + } + } + + const previousAutoIncrement = await this.getTableAutoIncrement(tableName); + + if (clauses.length > 0) { + await sequelize.query(`ALTER TABLE ${quotedTableName} ${clauses.join(', ')}`); + } + + // 若 ALTER 触发表重建并把自增水位重置到历史低值,恢复原水位 + const currentAutoIncrement = await this.getTableAutoIncrement(tableName); + if (previousAutoIncrement !== null + && currentAutoIncrement !== null + && currentAutoIncrement < previousAutoIncrement) { + await sequelize.query(`ALTER TABLE ${quotedTableName} AUTO_INCREMENT = ${previousAutoIncrement}`); + this.app.logger.warn( + `订单商品工厂表 ${tableName} 自增水位被 ALTER 重置(${previousAutoIncrement} → ${currentAutoIncrement}),已恢复为 ${previousAutoIncrement}` + ); + } + + // 仅补齐缺失索引,不重建、不删除已有索引 + const existingIndexNames = new Set((await queryInterface.showIndex(tableName)) + .map(index => index.Key_name || index.name || '') + .filter(Boolean)); + + for (const indexDef of this.generateIndexes(warehouseId)) { + if (existingIndexNames.has(indexDef.name)) { + continue; + } + + await queryInterface.addIndex(tableName, indexDef.fields, { + name: indexDef.name, + unique: Boolean(indexDef.unique), + }); + } + } + /** * 确保目标表与模型结构一致。 * @param {string} tableName 表名。 @@ -453,12 +609,21 @@ module.exports = app => { ? await this.needsTableSchemaSync(tableName, type, warehouseId, tableExists) : true; - if (!needsSync) { - return false; + if (!tableExists) { + await dynamicModel.sync({ force: false }); + return true; } - await dynamicModel.sync({ alter: true }); - return true; + if (needsSync) { + // 结构同步不再使用 sync({ alter: true }):历史事故表明它会重建表并重置 + // 自增水位(与 dispatch/history 已复制 id 重叠,后续迁移主键冲突)。 + // 改为手工差异 ALTER + 补齐索引,并跳过 id 列 CHANGE。 + await this.alterManagedTableSchema(tableName, type, warehouseId); + } + + // 无论是否同步结构,都核对自增水位(表重建/迁移/手工修复都可能破坏水位) + await this.ensureAutoIncrementWatermark(tableName); + return needsSync; } /** @@ -470,7 +635,8 @@ module.exports = app => { const tableName = this.generateTableName(warehouseId, type); const dynamicModel = this.buildDynamicModel(warehouseId, type, tableName); - await dynamicModel.sync({ alter: true }); + // 统一走差异检测 + 自增水位保护的同步路径,不再直接 sync({ alter: true }) + await this.ensureManagedTableSchema(tableName, type, warehouseId, dynamicModel); this.app.logger.info(`创建/同步订单商品物理表成功: ${tableName}`); } diff --git a/app/schedule/sync_outbound_orders_to_delivery.js b/app/schedule/sync_outbound_orders_to_delivery.js index 5386369..ccaa005 100644 --- a/app/schedule/sync_outbound_orders_to_delivery.js +++ b/app/schedule/sync_outbound_orders_to_delivery.js @@ -4,6 +4,9 @@ const SHORT_TASK_QUERY_TIMEOUT_MS = 15000; const SHORT_TASK_EXECUTION_TIMEOUT_MS = 30000; const EXECUTION_LOG_CACHE_KEY = 'schedule:sync_outbound_orders_to_delivery:last_execution'; const EXECUTION_LOG_CACHE_TTL = 300; // 5 分钟 +const EXECUTION_LOG_HISTORY_CACHE_KEY = 'schedule:sync_outbound_orders_to_delivery:history'; +const EXECUTION_LOG_HISTORY_MAX = 20; // 保留最近 20 次执行记录 +const EXECUTION_LOG_HISTORY_TTL = 86400; // 1 天 /** * 将本次执行日志写入缓存。 @@ -23,6 +26,36 @@ async function writeExecutionLogToCache(ctx, logEntry) { } } +/** + * 将本次执行日志追加到历史记录缓存(保留最近 N 次)。 + * + * 用于不翻日志文件也能观察定时任务每轮执行情况(selected/created/status/error), + * 便于排查「订单满足迁移条件但迟迟未切表」类问题。 + * + * @param {Object} ctx Egg 上下文。 + * @param {Object} logEntry 日志条目。 + * @return {Promise} 无返回值。 + */ +async function appendExecutionHistory(ctx, logEntry) { + try { + if (typeof ctx.app.getCacheAsync !== 'function' || typeof ctx.app.setCacheAsync !== 'function') { + return; + } + + const rawHistory = await ctx.app.getCacheAsync(EXECUTION_LOG_HISTORY_CACHE_KEY); + const history = Array.isArray(rawHistory) ? rawHistory : []; + history.unshift(logEntry); + await ctx.app.setCacheAsync( + EXECUTION_LOG_HISTORY_CACHE_KEY, + history.slice(0, EXECUTION_LOG_HISTORY_MAX), + EXECUTION_LOG_HISTORY_TTL + ); + } catch (err) { + // 历史日志写入失败不影响主流程 + ctx.logger.warn(`[sync-outbound-orders-to-delivery] 写入执行历史缓存失败: ${err.message}`); + } +} + /** * 提取错误详情,方便定位问题位置。 * @@ -139,6 +172,7 @@ module.exports = { warehouse_ids: result ? result.warehouseIds : [], }; await writeExecutionLogToCache(ctx, logEntry); - ctx.logger.info(`[sync-outbound-orders-to-delivery] 执行日志已写入缓存 key=${EXECUTION_LOG_CACHE_KEY}`); + await appendExecutionHistory(ctx, logEntry); + ctx.logger.info(`[sync-outbound-orders-to-delivery] 执行日志已写入缓存 key=${EXECUTION_LOG_CACHE_KEY} history=${EXECUTION_LOG_HISTORY_CACHE_KEY}`); }, }; diff --git a/app/service/qimenMethods/deliveryorder.js b/app/service/qimenMethods/deliveryorder.js index 6b72beb..7bbc6cb 100644 --- a/app/service/qimenMethods/deliveryorder.js +++ b/app/service/qimenMethods/deliveryorder.js @@ -34,7 +34,13 @@ class deliveryorderServer extends MainService { const info = this.getInfo(); const res = await this.ctx.service.systems.deliveryOrder.addOrder(data, info, 'QM'); if (res.success) { - return this.success(res.message, { createTime: this.app.formatDate(new Date()), deliveryOrderId: res.data.deliveryOrderId, warehouseCode: info.warehouseCode, logisticsCode: res.data.logisticsCode }); + return this.success(res.message, { + createTime: this.app.formatDate(new Date()), + // addOrder 成功返回 data.orderId,兼容历史字段 deliveryOrderId + deliveryOrderId: (res.data && (res.data.orderId || res.data.deliveryOrderId)) || '', + warehouseCode: info.warehouseCode, + logisticsCode: (res.data && res.data.logisticsCode) || '', + }); } return this.fail(res.message, { createTime: this.app.formatDate(new Date()) }); } diff --git a/app/service/systemMethods/order/deliveryOrder.js b/app/service/systemMethods/order/deliveryOrder.js index 8cc4f92..6e70925 100644 --- a/app/service/systemMethods/order/deliveryOrder.js +++ b/app/service/systemMethods/order/deliveryOrder.js @@ -163,10 +163,34 @@ class DeliveryOrderService extends OrderBaseService { { label: 'current', getModel: () => factory.getCurrentModel(warehouseId) }, { label: 'history', getModel: () => factory.getHistoryModel(warehouseId) }, ]; - const remainingIds = new Set(orderIds.map(String)); + + // 序列表批量定位:命中则只查对应分表,未命中(存量订单)回退三表遍历 + const normalizedOrderIds = orderIds.map(Number).filter(n => Number.isFinite(n) && n > 0); + let locationMap = new Map(); + try { + if (typeof factory.getOrderLocations === 'function') { + locationMap = await factory.getOrderLocations(normalizedOrderIds, warehouseId); + } + } catch (e) { + dbg(` locationMap ERROR: ${e.message}`); + } + dbg(` locationMap size: ${locationMap.size}`); + + const idsByLabel = { dispatch: [], current: [], history: [] }; + const unresolvedIds = []; + for (const id of normalizedOrderIds) { + const location = locationMap.get(id); + if (location && idsByLabel[location]) { + idsByLabel[location].push(id); + } else { + unresolvedIds.push(id); + } + } + for (const entry of tableDefs) { - if (remainingIds.size === 0) break; - dbg(` trying table: ${entry.label}, remainingIds=[${[ ...remainingIds ].join(',')}]`); + const targetIds = [ ...new Set([ ...(idsByLabel[entry.label] || []), ...unresolvedIds ]) ]; + if (targetIds.length === 0) continue; + dbg(` trying table: ${entry.label}, targetIds=[${targetIds.join(',')}]`); try { const model = await entry.getModel(); dbg(` ${entry.label} model: ${!!model}, typeof findAll=${model && typeof model.findAll}`); @@ -174,7 +198,7 @@ class DeliveryOrderService extends OrderBaseService { dbg(` ${entry.label} model invalid, skip`); continue; } - const whereClause = { id: [ ...remainingIds ].map(Number) }; + const whereClause = { id: targetIds }; dbg(` ${entry.label} where: ${JSON.stringify(whereClause)}`); const rows = await model.findAll({ attributes: [ @@ -193,7 +217,7 @@ class DeliveryOrderService extends OrderBaseService { for (const r of (rows || [])) { dbg(` row: id=${r.id} delivery_order_code=${r.delivery_order_code} status=${r.status}`); const rid = String(r.id); - if (!orderMap.has(rid)) { orderMap.set(rid, r); remainingIds.delete(rid); } + if (!orderMap.has(rid)) { orderMap.set(rid, r); } } } catch (e) { dbg(` ${entry.label} ERROR: ${e.message} | stack: ${(e.stack || '').split('\n').slice(0, 3).join(' | ')}`); @@ -329,33 +353,58 @@ class DeliveryOrderService extends OrderBaseService { return []; } + const attributes = [ + 'id', 'delivery_order_code', 'source_order_codes', 'pay_no', + 'store_id', 'status', + 'name', 'mobile', 'province', 'city', 'area', 'detail_address', + 'buyer_nick', 'seller_nick', 'shop_nick', + 'total_amount', 'item_amount', 'freight', + 'items_count', 'items_weight', + 'wave_no', 'delivery_time', 'create_at', + ]; + const tableOrders = [ { label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) }, { label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) }, { label: 'history', getModel: () => orderDeliveryFactory.getHistoryModel(warehouseId) }, ]; + // 序列表批量定位:命中则只查对应分表,未命中(存量订单)回退三表遍历 + const normalizedIds = [ ...new Set((orderIds || []).map(Number).filter(id => Number.isFinite(id) && id > 0)) ]; + let locationMap = new Map(); + try { + if (typeof orderDeliveryFactory.getOrderLocations === 'function') { + locationMap = await orderDeliveryFactory.getOrderLocations(normalizedIds, warehouseId); + } + } catch (_err) { + locationMap = new Map(); + } + + const idsByLabel = { dispatch: [], current: [], history: [] }; + const unresolvedIds = []; + for (const id of normalizedIds) { + const location = locationMap.get(id); + if (location && idsByLabel[location]) { + idsByLabel[location].push(id); + } else { + unresolvedIds.push(id); + } + } + const resultMap = new Map(); - const remainingIds = new Set(orderIds.map(id => String(id))); for (const entry of tableOrders) { - if (remainingIds.size === 0) break; + const targetIds = [ ...new Set([ ...(idsByLabel[entry.label] || []), ...unresolvedIds ]) ]; + if (targetIds.length === 0) continue; + try { const model = await entry.getModel(); if (!model || typeof model.findAll !== 'function') continue; const rows = await model.findAll({ - attributes: [ - 'id', 'delivery_order_code', 'source_order_codes', 'pay_no', - 'store_id', 'status', - 'name', 'mobile', 'province', 'city', 'area', 'detail_address', - 'buyer_nick', 'seller_nick', 'shop_nick', - 'total_amount', 'item_amount', 'freight', - 'items_count', 'items_weight', - 'wave_no', 'delivery_time', 'create_at', - ], + attributes, where: { - id: { [Op.in]: [ ...remainingIds ].map(Number) }, + id: { [Op.in]: targetIds }, }, raw: true, }); @@ -364,7 +413,6 @@ class DeliveryOrderService extends OrderBaseService { const rid = String(r.id); if (!resultMap.has(rid)) { resultMap.set(rid, r); - remainingIds.delete(rid); } } } catch (_err) { diff --git a/app/service/systems/delivery_order.js b/app/service/systems/delivery_order.js index 18c7df2..b4b87fe 100644 --- a/app/service/systems/delivery_order.js +++ b/app/service/systems/delivery_order.js @@ -628,7 +628,6 @@ class DeliveryOrderService extends Service { */ async addOrder(data, info, createChannel = '') { const { ctx } = this; - const operationLogs = []; let warehouseIdStr; try { warehouseIdStr = normalizeWarehouseShardId(info.warehouseId); @@ -655,255 +654,360 @@ class DeliveryOrderService extends Service { || 'MANUAL' ).trim().toUpperCase() || 'MANUAL'; - // 开启事务 - const transaction = await ctx.model.transaction(); - + // 订单 id 序列表初始化可能执行 DDL(隐式提交),必须在事务外先完成 try { - if (!info.storeId) { - throw new Error('非法参数'); - } - if (!deliveryOrder || !deliveryOrder.deliveryOrderCode) { - throw new Error('订单信息不完整'); - } + await ctx.model.OrderDeliveryFactory.ensureLocationSequenceTable(warehouseIdStr); + } catch (error) { + // 初始化失败不降级:后续发号会直接失败并回滚建单,绝不让分表自增介入发号 + ctx.logger.warn('[DeliveryOrderService.addOrder] 序列表初始化失败,本次建单将失败:', error.message); + } - // 检查订单是否已存在(根据唯一索引) - const existingOrder = await DeliveryModel.findOne({ - where: { - delivery_order_code: deliveryOrder.deliveryOrderCode, - store_id: info.storeId, - warehouse_id: info.warehouseId, - }, - attributes: [ 'id' ], - transaction, - }); - if (existingOrder) { - await transaction.rollback(); - return { - success: true, - message: '订单已存在', - data: { deliveryOrderId: existingOrder.id }, - }; - } + // 单次建单执行体:重试时复用,事务随每次尝试重新开启 + const createOnce = async operationLogs => { + // 开启事务 + const transaction = await ctx.model.transaction(); - // 准备订单数据 - const step = await this.resolveOrderStep(info, transaction); - const orderData = await this.prepareOrderData( - deliveryOrder, - info, - normalizedCreateChannel, - step, - operationLogs, - requestExtendProps - ); + try { + if (!info.storeId) { + throw new Error('非法参数'); + } + if (!deliveryOrder || !deliveryOrder.deliveryOrderCode) { + throw new Error('订单信息不完整'); + } - // 创建订单 - const createdOrder = await DeliveryModel.create(orderData, { transaction }); - const orderId = createdOrder.id; - this.appendOrderOperationLog( - operationLogs, - ORDER_OPERATION_CODES.CREATE, - `订单创建成功,orderId:${orderId}`, - { prepend: true } - ); + // 检查订单是否已存在(根据唯一索引) + const existingOrder = await DeliveryModel.findOne({ + where: { + delivery_order_code: deliveryOrder.deliveryOrderCode, + store_id: info.storeId, + warehouse_id: info.warehouseId, + }, + attributes: [ 'id' ], + transaction, + }); + if (existingOrder) { + await transaction.rollback(); + return { + success: true, + message: '订单已存在', + data: { deliveryOrderId: existingOrder.id }, + }; + } - // 将建单渠道注入 info,供 addOrderLines 区分 MANUAL 降级逻辑 - info.createChannel = normalizedCreateChannel; - - let itemsInfo = null; - // 添加订单明细 - if (orderLines && (orderLines.orderLine)) { - itemsInfo = await this.addOrderLines( - orderLines.orderLine, - orderId, + // 准备订单数据 + const step = await this.resolveOrderStep(info, transaction); + const orderData = await this.prepareOrderData( + deliveryOrder, info, - transaction + normalizedCreateChannel, + step, + operationLogs, + requestExtendProps ); - } else { - throw new Error('[订单无明细]'); - } - // 更新订单统计信息 - 直接使用itemsInfo中的计算结果 - if (itemsInfo) { - const stats = { - items: itemsInfo.items_str || '', // 原始结构字符串 - items_count: itemsInfo.stock_count || 0, // 商品种类数 - items_total: itemsInfo.item_total_count || 0, // 商品总数(直接使用计算结果) - items_weight: itemsInfo.total_weight || 0, // 总重量 - items_hash: this.generateItemsHash(itemsInfo), // 哈希值 - items_crc: this.calculateCRC32(itemsInfo.items_str || ''), // CRC校验 - source_order_codes: ((itemsInfo.stats && itemsInfo.stats.source_order_codes) || []).filter(code => code).join(',') || deliveryOrder.deliveryOrderCode, - updated_at: new Date(), - }; + // 创建订单:订单 id 统一由仓库序列表分配,显式写入 current 分表。 + // 不再回退分表自增:分表自增序列与序列表发号区间重叠会产生冲突 id, + // 发号失败时直接抛错,由事务回滚,杜绝脏 id 落库。 + const orderId = await ctx.model.OrderDeliveryFactory.allocateOrderId(warehouseIdStr, transaction, 'current'); + await DeliveryModel.create({ ...orderData, id: orderId }, { transaction }); + this.appendOrderOperationLog( + operationLogs, + ORDER_OPERATION_CODES.CREATE, + `订单创建成功,orderId:${orderId}`, + { prepend: true } + ); - // ===== 快递绑定策略漏斗匹配(items 处理后 weight 可用) ===== - try { - const receiverInfo = deliveryOrder.receiverInfo; - const shopNick = deliveryOrder.shopNick; - const hasEnoughData = shopNick || (receiverInfo && (receiverInfo.province || receiverInfo.city)); + // 将建单渠道注入 info,供 addOrderLines 区分 MANUAL 降级逻辑 + info.createChannel = normalizedCreateChannel; - if (hasEnoughData) { - const address = [ - receiverInfo?.province || '', - receiverInfo?.city || '', - receiverInfo?.area || '', - receiverInfo?.town || '', - receiverInfo?.detail_address || '', - ].join('').trim(); - - const matchResult = await ctx.service.systems.expressPolicy.matchPolicy( - info.warehouseId, - { - storeId: info.storeId, - customShopName: shopNick || '', - address: address || '', - weight: itemsInfo.total_weight || null, - prohibitedTypeIds: null, // TODO: 后续从商品 StockWarehouse.prohibited_id 聚合 - } - ); - - if (matchResult && matchResult.expressCode) { - const expressList = await ctx.service.systems.express.getExpressList(); - const matchedExpress = expressList.find( - item => item && String(item.code || item.value || '').trim() === String(matchResult.expressCode).trim() - ); - - let logisticsCode; - let logisticsName; - let sysLogisticsCode; - let sysLogisticsName; - - if (matchedExpress) { - if (matchedExpress.is_system_setting) { - // 自定义映射:sys 写映射的系统快递,logistics 写自定义编码 - sysLogisticsCode = String(matchedExpress.express_code || '').trim(); - const sysItem = expressList.find( - item => item && !item.is_system_setting && String(item.code || item.value || '').trim() === sysLogisticsCode - ); - sysLogisticsName = sysItem ? String(sysItem.name || sysItem.label || sysLogisticsCode).trim() : sysLogisticsCode; - logisticsCode = String(matchedExpress.code || matchedExpress.value || matchResult.expressCode).trim(); - logisticsName = String(matchedExpress.alias || matchedExpress.name || logisticsCode).trim(); - } else { - // 系统快递:4 字段一致 - logisticsCode = String(matchedExpress.code || matchedExpress.value || matchResult.expressCode).trim(); - logisticsName = String(matchedExpress.name || matchedExpress.label || logisticsCode).trim(); - sysLogisticsCode = logisticsCode; - sysLogisticsName = logisticsName; - } - } else { - // 未在列表中,fallback - logisticsCode = String(matchResult.expressCode).trim(); - logisticsName = logisticsCode; - sysLogisticsCode = logisticsCode; - sysLogisticsName = logisticsCode; - } - - stats.logistics_code = logisticsCode; - stats.logistics_name = logisticsName; - stats.sys_logistics_code = sysLogisticsCode; - stats.sys_logistics_name = sysLogisticsName; - stats.weight_type = matchResult.weightType; - stats.updated_at = new Date(); - - // 写入操作日志:命中了哪条策略 - this.appendOrderOperationLog( - operationLogs, - ORDER_OPERATION_CODES.EXPRESS_POLICY_MATCH, - `快递策略命中: ${matchResult.policyName || '未知'}(${matchResult.policyId || '?'}) → ${sysLogisticsName || sysLogisticsCode}` - ); - - ctx.logger.info('[ExpressPolicyMatch] 策略命中(延迟匹配)', { - orderId, - orderCode: deliveryOrder.deliveryOrderCode, - logisticsCode, - sysLogisticsCode, - weightType: matchResult.weightType, - policyName: matchResult.policyName, - policyId: matchResult.policyId, - totalWeight: itemsInfo.total_weight, - }); - } else if (hasEnoughData) { - // 策略未命中:记快递降级日志(取已落库的初始快递值) - const fallbackCode = orderData.sys_logistics_code || orderData.logistics_code; - const fallbackName = orderData.sys_logistics_name || orderData.logistics_name; - this.appendOrderOperationLog( - operationLogs, - ORDER_OPERATION_CODES.EXPRESS_FALLBACK, - `未命中快递策略,使用默认快递: ${fallbackName || fallbackCode}` - ); - } - } - } catch (policyErr) { - ctx.logger.warn('[ExpressPolicyMatch] 策略匹配异常,跳过', { + let itemsInfo = null; + // 添加订单明细 + if (orderLines && (orderLines.orderLine)) { + itemsInfo = await this.addOrderLines( + orderLines.orderLine, orderId, - error: policyErr.message, + info, + transaction + ); + } else { + throw new Error('[订单无明细]'); + } + + // 更新订单统计信息 - 直接使用itemsInfo中的计算结果 + if (itemsInfo) { + const stats = { + items: itemsInfo.items_str || '', // 原始结构字符串 + items_count: itemsInfo.stock_count || 0, // 商品种类数 + items_total: itemsInfo.item_total_count || 0, // 商品总数(直接使用计算结果) + items_weight: itemsInfo.total_weight || 0, // 总重量 + items_hash: this.generateItemsHash(itemsInfo), // 哈希值 + items_crc: this.calculateCRC32(itemsInfo.items_str || ''), // CRC校验 + source_order_codes: ((itemsInfo.stats && itemsInfo.stats.source_order_codes) || []).filter(code => code).join(',') || deliveryOrder.deliveryOrderCode, + updated_at: new Date(), + }; + + // ===== 快递绑定策略漏斗匹配(items 处理后 weight 可用) ===== + try { + const receiverInfo = deliveryOrder.receiverInfo; + const shopNick = deliveryOrder.shopNick; + const hasEnoughData = shopNick || (receiverInfo && (receiverInfo.province || receiverInfo.city)); + + if (hasEnoughData) { + const address = [ + receiverInfo?.province || '', + receiverInfo?.city || '', + receiverInfo?.area || '', + receiverInfo?.town || '', + receiverInfo?.detail_address || '', + ].join('').trim(); + + const matchResult = await ctx.service.systems.expressPolicy.matchPolicy( + info.warehouseId, + { + storeId: info.storeId, + customShopName: shopNick || '', + address: address || '', + weight: itemsInfo.total_weight || null, + prohibitedTypeIds: null, // TODO: 后续从商品 StockWarehouse.prohibited_id 聚合 + } + ); + + if (matchResult && matchResult.expressCode) { + const expressList = await ctx.service.systems.express.getExpressList(); + const matchedExpress = expressList.find( + item => item && String(item.code || item.value || '').trim() === String(matchResult.expressCode).trim() + ); + + let logisticsCode; + let logisticsName; + let sysLogisticsCode; + let sysLogisticsName; + + if (matchedExpress) { + if (matchedExpress.is_system_setting) { + // 自定义映射:sys 写映射的系统快递,logistics 写自定义编码 + sysLogisticsCode = String(matchedExpress.express_code || '').trim(); + const sysItem = expressList.find( + item => item && !item.is_system_setting && String(item.code || item.value || '').trim() === sysLogisticsCode + ); + sysLogisticsName = sysItem ? String(sysItem.name || sysItem.label || sysLogisticsCode).trim() : sysLogisticsCode; + logisticsCode = String(matchedExpress.code || matchedExpress.value || matchResult.expressCode).trim(); + logisticsName = String(matchedExpress.alias || matchedExpress.name || logisticsCode).trim(); + } else { + // 系统快递:4 字段一致 + logisticsCode = String(matchedExpress.code || matchedExpress.value || matchResult.expressCode).trim(); + logisticsName = String(matchedExpress.name || matchedExpress.label || logisticsCode).trim(); + sysLogisticsCode = logisticsCode; + sysLogisticsName = logisticsName; + } + } else { + // 未在列表中,fallback + logisticsCode = String(matchResult.expressCode).trim(); + logisticsName = logisticsCode; + sysLogisticsCode = logisticsCode; + sysLogisticsName = logisticsCode; + } + + stats.logistics_code = logisticsCode; + stats.logistics_name = logisticsName; + stats.sys_logistics_code = sysLogisticsCode; + stats.sys_logistics_name = sysLogisticsName; + stats.weight_type = matchResult.weightType; + stats.updated_at = new Date(); + + // 写入操作日志:命中了哪条策略 + this.appendOrderOperationLog( + operationLogs, + ORDER_OPERATION_CODES.EXPRESS_POLICY_MATCH, + `快递策略命中: ${matchResult.policyName || '未知'}(${matchResult.policyId || '?'}) → ${sysLogisticsName || sysLogisticsCode}` + ); + + ctx.logger.info('[ExpressPolicyMatch] 策略命中(延迟匹配)', { + orderId, + orderCode: deliveryOrder.deliveryOrderCode, + logisticsCode, + sysLogisticsCode, + weightType: matchResult.weightType, + policyName: matchResult.policyName, + policyId: matchResult.policyId, + totalWeight: itemsInfo.total_weight, + }); + } else if (hasEnoughData) { + // 策略未命中:记快递降级日志(取已落库的初始快递值) + const fallbackCode = orderData.sys_logistics_code || orderData.logistics_code; + const fallbackName = orderData.sys_logistics_name || orderData.logistics_name; + this.appendOrderOperationLog( + operationLogs, + ORDER_OPERATION_CODES.EXPRESS_FALLBACK, + `未命中快递策略,使用默认快递: ${fallbackName || fallbackCode}` + ); + } + } + } catch (policyErr) { + ctx.logger.warn('[ExpressPolicyMatch] 策略匹配异常,跳过', { + orderId, + error: policyErr.message, + }); + } + + await DeliveryModel.update( + stats, + { + where: { id: orderId }, + transaction, + } + ); + + // 记录详细日志 + ctx.logger.info('[订单统计信息已更新]', { + orderId, + orderCode: deliveryOrder.deliveryOrderCode, + stats: { + items_count: stats.items_count, + items_total: stats.items_total, + items_weight: stats.items_weight, + items_hash_preview: stats.items_hash?.substring(0, 8) + '...', + items_crc: stats.items_crc, + }, }); } - await DeliveryModel.update( - stats, - { - where: { id: orderId }, - transaction, - } - ); + await transaction.commit(); - // 记录详细日志 - ctx.logger.info('[订单统计信息已更新]', { - orderId, - orderCode: deliveryOrder.deliveryOrderCode, - stats: { - items_count: stats.items_count, - items_total: stats.items_total, - items_weight: stats.items_weight, - items_hash_preview: stats.items_hash?.substring(0, 8) + '...', - items_crc: stats.items_crc, - }, + await this.flushOrderOperationLogs(operationLogs, orderId, { + warehouseId: info.warehouseId, + createChannel: normalizedCreateChannel, }); + + // 异步处理订单后续流程 + this.asyncProcessOrderCreated(orderId, info, normalizedCreateChannel).catch(error => { + ctx.logger.warn(`[DeliveryOrderService.addOrder] asyncProcessOrderCreated failed: ${error.message}`, { + orderId, + error: error.message, + }); + }); + + return { + success: true, + message: '订单创建成功', + data: { + orderId, + step, + stats: itemsInfo ? { + items_count: itemsInfo.stock_count, + items_total: itemsInfo.item_total_count, + items_weight: itemsInfo.total_weight, + source_order_codes: (itemsInfo.stats && itemsInfo.stats.source_order_codes) || [], + } : null, + }, + }; + + } catch (error) { + console.error('创建订单失败:', error); + // 回滚事务(安全处理,防止事务已结束导致二次回滚异常) + await transaction.rollback().catch(rollbackErr => { + console.error('回滚事务失败:', rollbackErr.message); + }); + + throw error; + } + }; + + // 主键冲突(分表自增水位与已有数据重叠)允许修复水位后重试一次 + for (let attempt = 1; attempt <= 2; attempt++) { + const operationLogs = []; + try { + return await createOnce(operationLogs); + } catch (error) { + if (this.isPrimaryKeyDuplicate(error) && attempt === 1) { + try { + const factory = ctx.model.OrderDeliveryFactory; + const tableName = factory.generateTableName(warehouseIdStr, 'current'); + await factory.ensureAutoIncrementWatermark(tableName); + ctx.logger.warn('[DeliveryOrderService.addOrder] 主键冲突,已修复自增水位,重试建单', { + deliveryOrderCode: deliveryOrder && deliveryOrder.deliveryOrderCode, + warehouseId: warehouseIdStr, + storeId: info.storeId, + error: error.message, + }); + } catch (repairError) { + ctx.logger.warn('[DeliveryOrderService.addOrder] 自增水位修复失败,放弃重试', { + error: repairError.message, + }); + } + continue; + } + + return { + success: false, + message: `订单创建失败: ${this.formatOrderCreateError(error, deliveryOrder)}`, + data: null, + }; + } + } + + return { + success: false, + message: '订单创建失败: 主键冲突重试后仍未成功', + data: null, + }; + } + + /** + * 判断是否为分表主键自增冲突。 + * + * 分表自增水位被破坏(显式 id 导入、表重建、迁移复制 id)后,自增插入会与 + * 已有主键重叠,Sequelize 抛出的 UniqueConstraintError 对外 message 为 + * “Validation error”,需按 errors[].path 识别。 + * + * @param {Error} error Sequelize 错误对象。 + * @return {boolean} 是否为主键唯一冲突。 + */ + isPrimaryKeyDuplicate(error) { + if (!error || error.name !== 'SequelizeUniqueConstraintError' || !Array.isArray(error.errors)) { + return false; + } + + return error.errors.some(item => item + && item.type === 'unique violation' + && (item.path === 'PRIMARY' || item.path === 'id')); + } + + /** + * 将建单异常格式化为可读的失败原因。 + * + * Sequelize 唯一约束错误的 message 固定为 “Validation error”,若不解析 + * errors/parent 会掩盖真实原因,这里优先提取具体冲突字段与值。 + * + * @param {Error} error 原始异常。 + * @param {Object} [deliveryOrder] 请求中的发货单信息。 + * @return {string} 可读的失败原因。 + */ + formatOrderCreateError(error, deliveryOrder) { + if (error && error.name === 'SequelizeUniqueConstraintError' && Array.isArray(error.errors)) { + const primaryDup = error.errors.find(item => item + && item.type === 'unique violation' + && (item.path === 'PRIMARY' || item.path === 'id')); + if (primaryDup) { + return `订单ID主键冲突(id=${primaryDup.value} 已被占用):分表自增水位与已有数据重叠,已尝试修复并重试,请再次提交`; } - await transaction.commit(); + const codeDup = error.errors.find(item => item && item.path === 'delivery_order_code'); + if (codeDup) { + const orderCode = (deliveryOrder && deliveryOrder.deliveryOrderCode) || codeDup.value; + return `订单号 ${orderCode} 已存在`; + } - await this.flushOrderOperationLogs(operationLogs, orderId, { - warehouseId: info.warehouseId, - createChannel: normalizedCreateChannel, - }); - - // 异步处理订单后续流程 - this.asyncProcessOrderCreated(orderId, info, normalizedCreateChannel).catch(error => { - ctx.logger.warn(`[DeliveryOrderService.addOrder] asyncProcessOrderCreated failed: ${error.message}`, { - orderId, - error: error.message, - }); - }); - - return { - success: true, - message: '订单创建成功', - data: { - orderId, - step, - stats: itemsInfo ? { - items_count: itemsInfo.stock_count, - items_total: itemsInfo.item_total_count, - items_weight: itemsInfo.total_weight, - source_order_codes: (itemsInfo.stats && itemsInfo.stats.source_order_codes) || [], - } : null, - }, - }; - - } catch (error) { - console.error('创建订单失败:', error); - // 回滚事务(安全处理,防止事务已结束导致二次回滚异常) - await transaction.rollback().catch(rollbackErr => { - console.error('回滚事务失败:', rollbackErr.message); - }); - - return { - success: false, - message: `订单创建失败: ${error.message}`, - data: null, - }; + const firstItem = error.errors[0] || {}; + return String(firstItem.message || error.message || '唯一约束冲突').trim(); } + + const parentSqlMessage = error && error.parent && error.parent.sqlMessage; + if (parentSqlMessage) { + return `${error.message} (${parentSqlMessage})`; + } + + return String((error && error.message) || '').trim() || '未知错误'; } /** diff --git a/app/service/systems/order_delivery_migration.js b/app/service/systems/order_delivery_migration.js index dedfe88..93ae52c 100644 --- a/app/service/systems/order_delivery_migration.js +++ b/app/service/systems/order_delivery_migration.js @@ -405,6 +405,12 @@ class OrderDeliveryMigrationService extends MainService { const deadlineAt = Number.isFinite(executionTimeoutMs) && executionTimeoutMs > 0 ? Date.now() + executionTimeoutMs : 0; + + // 序列表初始化可能执行 DDL(隐式提交),必须在事务外完成。 + // 初始化失败直接终止迁移:位置指针与配送表写入必须在同一事务内原子完成, + // 没有序列表则无法保证索引一致,宁可迁移失败重试也不产生错位指针。 + await this.ctx.model.OrderDeliveryFactory.ensureLocationSequenceTable(normalizedWarehouseId); + const transaction = await this.ctx.model.transaction(); const { Op } = this.ctx.app.Sequelize; let sourceRows = []; @@ -538,6 +544,22 @@ class OrderDeliveryMigrationService extends MainService { await targetOrderModel.bulkCreate(rowsToCreate, { ...this.buildMigrationQueryOptions(transaction, queryTimeoutMs), }); + + // 更新序列表位置指针:current → dispatch。与上方 bulkCreate 处于同一事务, + // 任一步失败整体回滚,保证配送表数据与位置索引原子一致(存量订单自动补录, + // 显式 id 大于序列表水位时 MySQL 会自动推进,后续发号不会与存量 id 冲突)。 + const locationFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; + if (!locationFactory || typeof locationFactory.updateOrderLocation !== 'function') { + throw new Error('订单工厂缺少 updateOrderLocation,无法同步序列表位置指针'); + } + for (const row of rowsToCreate) { + await locationFactory.updateOrderLocation( + Number(row.id), + normalizedWarehouseId, + 'dispatch', + transaction + ); + } } assertMigrationDeadline('查询配送表订单'); diff --git a/script/backfill-order-id-location.cjs b/script/backfill-order-id-location.cjs new file mode 100644 index 0000000..f932650 --- /dev/null +++ b/script/backfill-order-id-location.cjs @@ -0,0 +1,245 @@ +const fs = require('fs'); +const path = require('path'); +const mysql = require('mysql2/promise'); + +const ROOT = process.cwd(); +const DEFAULT_CONFIG_PATH = path.join(ROOT, 'config', 'config.local.js'); + +const SLOT_LOCATIONS = [ + { suffix: '_dispatch', location: 'dispatch' }, + { suffix: '_history', location: 'history' }, + { suffix: '_outsourced', location: 'outsourced' }, +]; + +function parseArgs(argv) { + const args = { + dryRun: false, + dbClient: 'wms', + configPath: DEFAULT_CONFIG_PATH, + warehouseId: null, + batchSize: 1000, + }; + + for (const item of argv) { + if (item === '--dry-run') { + args.dryRun = true; + continue; + } + + if (item.startsWith('--warehouse-id=')) { + const raw = String(item.split('=')[1] || '').trim(); + args.warehouseId = Number(raw); + continue; + } + + if (item.startsWith('--batch-size=')) { + const raw = Number(item.split('=')[1] || 0); + if (Number.isFinite(raw) && raw > 0) { + args.batchSize = Math.min(50000, Math.max(100, Math.floor(raw))); + } + continue; + } + + if (item.startsWith('--db-client=')) { + args.dbClient = String(item.split('=')[1] || '').trim() || 'wms'; + continue; + } + + if (item.startsWith('--config-path=')) { + args.configPath = path.resolve(ROOT, String(item.split('=')[1] || '').trim()); + continue; + } + } + + return args; +} + +function loadDbClient(configPath, dbClientName) { + if (!fs.existsSync(configPath)) { + throw new Error(`Config file not found: ${configPath}`); + } + + const configFactory = require(configPath); + const cfg = typeof configFactory === 'function' + ? configFactory({ name: 'wms-order-id-location-backfill' }) + : configFactory; + const dbClient = cfg && cfg.mysql && cfg.mysql.clients && cfg.mysql.clients[dbClientName]; + + if (!dbClient) { + throw new Error(`MySQL client not found in config.mysql.clients: ${dbClientName}`); + } + + return dbClient; +} + +function parseManagedTableName(tableName) { + const suffixMatch = /^wms_order_delivery_(\d+)(?:_(dispatch|history|outsourced))?$/.exec(tableName); + if (!suffixMatch) { + return null; + } + + return { + warehouseId: Number(suffixMatch[1]), + location: suffixMatch[2] || 'current', + }; +} + +async function ensureSequenceTable(conn, warehouseId, dryRun) { + const tableName = `wms_order_id_location_${warehouseId}`; + const [ rows ] = await conn.query( + `SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?`, + [ tableName ] + ); + + if (rows.length > 0) { + return tableName; + } + + if (dryRun) { + console.log(`[dry-run] would create sequence table ${tableName}`); + return tableName; + } + + await conn.query( + `CREATE TABLE \`${tableName}\` ( + \`id\` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + \`location\` VARCHAR(20) NOT NULL DEFAULT 'current', + PRIMARY KEY (\`id\`) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='仓库订单全局id序列与位置索引(极简,不迁移)'` + ); + console.log(`created sequence table ${tableName}`); + return tableName; +} + +async function countMissing(conn, sourceTable, seqTable) { + const [ rows ] = await conn.query( + `SELECT COUNT(*) AS cnt FROM \`${sourceTable}\` d ` + + `LEFT JOIN \`${seqTable}\` s ON s.id = d.id WHERE s.id IS NULL` + ); + return Number(rows[0].cnt || 0); +} + +async function fetchMissingBatch(conn, sourceTable, seqTable, batchSize) { + const [ rows ] = await conn.query( + `SELECT d.id FROM \`${sourceTable}\` d ` + + `LEFT JOIN \`${seqTable}\` s ON s.id = d.id WHERE s.id IS NULL ` + + `ORDER BY d.id ASC LIMIT ${batchSize}` + ); + return (rows || []).map(row => Number(row.id)).filter(id => Number.isFinite(id) && id > 0); +} + +async function upsertIds(conn, seqTable, location, ids, dryRun) { + if (ids.length === 0) { + return 0; + } + + if (dryRun) { + console.log(`[dry-run] would insert ${ids.length} rows into ${seqTable} (location=${location}, first=${ids[0]}, last=${ids[ids.length - 1]})`); + return ids.length; + } + + const values = ids.map(() => '(?, ?)').join(','); + const replacements = []; + for (const id of ids) { + replacements.push(id, location); + } + + const [ result ] = await conn.query( + `INSERT INTO \`${seqTable}\` (\`id\`, \`location\`) VALUES ${values} ` + + 'ON DUPLICATE KEY UPDATE `location` = VALUES(`location`)', + replacements + ); + return Number((result && result.affectedRows) || 0); +} + +async function main() { + const args = parseArgs(process.argv.slice(2)); + const dbClient = loadDbClient(args.configPath, args.dbClient); + + const conn = await mysql.createConnection({ + host: dbClient.host, + port: Number(dbClient.port), + user: dbClient.user, + password: dbClient.password, + database: dbClient.database, + charset: dbClient.charset || 'utf8mb4', + }); + + try { + console.log(`connected: ${dbClient.host}:${dbClient.port}/${dbClient.database}, dryRun=${args.dryRun}`); + + const [ tableRows ] = await conn.query( + "SELECT TABLE_NAME FROM information_schema.TABLES " + + "WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME LIKE 'wms_order_delivery\\\\_%' " + + "ORDER BY TABLE_NAME" + ); + + const tables = (tableRows || []) + .map(row => ({ tableName: row.TABLE_NAME, parsed: parseManagedTableName(row.TABLE_NAME) })) + .filter(item => item.parsed !== null) + .filter(item => !args.warehouseId || item.parsed.warehouseId === args.warehouseId); + + const warehouseIds = [ ...new Set(tables.map(item => item.parsed.warehouseId)) ].sort((a, b) => a - b); + console.log(`found warehouses: [${warehouseIds.join(', ')}], tables: ${tables.length}`); + + let totalInserted = 0; + + for (const warehouseId of warehouseIds) { + const seqTable = await ensureSequenceTable(conn, warehouseId, args.dryRun); + const warehouseTables = tables.filter(item => item.parsed.warehouseId === warehouseId); + + for (const { tableName, parsed } of warehouseTables) { + const missingCount = await countMissing(conn, tableName, seqTable); + if (missingCount === 0) { + console.log(`[${tableName}] no missing ids`); + continue; + } + + console.log(`[${tableName}] missing ids: ${missingCount} (location=${parsed.location})`); + + let inserted = 0; + for (;;) { + const batch = await fetchMissingBatch(conn, tableName, seqTable, args.batchSize); + if (batch.length === 0) { + break; + } + + const affected = await upsertIds(conn, seqTable, parsed.location, batch, args.dryRun); + inserted += affected; + + if (batch.length < args.batchSize) { + break; + } + } + + console.log(`[${tableName}] done: inserted=${inserted}`); + totalInserted += inserted; + } + + // 回填(显式 id)可能不会推进序列表自增计数器,结束时统一把水位 + // 抬升到 max(id)+安全余量,保证后续发号不与存量 id 冲突 + const [ seqMaxRows ] = await conn.query( + `SELECT COALESCE(MAX(id), 0) AS maxId FROM \`${seqTable}\`` + ); + const seqMaxId = Number(seqMaxRows[0].maxId || 0); + if (seqMaxId > 0) { + const safeTarget = seqMaxId + 50; + if (args.dryRun) { + console.log(`[dry-run] would raise ${seqTable} auto_increment to ${safeTarget}`); + } else { + await conn.query(`ALTER TABLE \`${seqTable}\` AUTO_INCREMENT = ${safeTarget}`); + console.log(`[${seqTable}] auto_increment raised to ${safeTarget}`); + } + } + } + + console.log(`TOTAL inserted (or would insert): ${totalInserted}`); + } finally { + await conn.end(); + } +} + +main().catch(error => { + console.error('FAILED:', error && error.message); + process.exit(1); +}); From 2e95fb19d4a52b17b21758d6bfcf5a7593760757 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sat, 15 Aug 2026 20:12:26 +0800 Subject: [PATCH 212/550] =?UTF-8?q?perf(query):=20=E8=BF=90=E5=8D=95?= =?UTF-8?q?=E5=AE=9A=E4=BD=8D=E4=BC=98=E5=85=88=E5=BA=8F=E5=88=97=E8=A1=A8?= =?UTF-8?q?=E7=9B=B4=E6=9F=A5=EF=BC=8C=E5=87=8F=E5=B0=91=E4=B8=89=E8=A1=A8?= =?UTF-8?q?=E5=BE=AA=E7=8E=AF=E6=89=AB=E6=8F=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/inbox/functions.js | 67 +++++++++++++++++++++++----- app/service/systems/order_express.js | 20 +++++++++ app/service/systems/waybill.js | 10 +++++ app/service/systems/workbench.js | 10 +++++ 4 files changed, 95 insertions(+), 12 deletions(-) diff --git a/app/service/inbox/functions.js b/app/service/inbox/functions.js index d09c7cd..5fb8434 100644 --- a/app/service/inbox/functions.js +++ b/app/service/inbox/functions.js @@ -538,7 +538,7 @@ class InboxFunctionsService extends Service { // ========== 第一步:运单号精确匹配 ========== const exactExpress = await ctx.model.OrderExpress.findOne({ - attributes: [ 'delivery_order_code' ], + attributes: [ 'delivery_order_code', 'order_id' ], where: { waybill_code: keyword, store_id: storeId, @@ -548,11 +548,38 @@ class InboxFunctionsService extends Service { }); if (exactExpress && exactExpress.delivery_order_code) { - // 用运单关联的发货单号精确查找订单 - found = await findInDeliveryTables({ - store_id: storeId, - delivery_order_code: exactExpress.delivery_order_code, - }); + // 运单精确匹配:先通过序列表定位订单所在分表,命中只查一张表; + // 未命中(存量订单无指针)回退三表按单号遍历 + const exactOrderId = Number(exactExpress.order_id || 0); + if (exactOrderId > 0 && factory && typeof factory.getOrderLocation === 'function') { + try { + const locatedAt = await factory.getOrderLocation(exactOrderId, warehouseId); + if (locatedAt) { + const locatedCfg = tableConfigs.find(cfg => cfg.key === locatedAt); + if (locatedCfg) { + const locatedModel = await locatedCfg.getModel(factory, warehouseId); + if (locatedModel) { + const locatedRow = await locatedModel.findOne({ + attributes, + where: { id: exactOrderId, store_id: storeId }, + raw: true, + }); + if (locatedRow) { + found = { table: locatedCfg.key, table_label: locatedCfg.label, ...locatedRow }; + } + } + } + } + } catch (_err) { /* 定位失败,降级三表遍历 */ } + } + + if (!found) { + // 用运单关联的发货单号精确查找订单 + found = await findInDeliveryTables({ + store_id: storeId, + delivery_order_code: exactExpress.delivery_order_code, + }); + } } // ========== 第二步:运单未命中 → 模糊搜索发货单号 / 平台单号 ========== @@ -3054,16 +3081,32 @@ class InboxFunctionsService extends Service { const orderMissingWbs = []; for (const e of validList) { - // 第二步:查订单行(当前表 → 历史表 → 配送表),取波次信息 + // 第二步:查订单行(优先序列表定位,未命中回退 当前→历史→配送 遍历) let orderRow = null; + const factory = ctx.model.OrderDeliveryFactory; const tableGetters = [ - (f, wid) => f.getCurrentModel(wid), - (f, wid) => f.getHistoryModel(wid), - (f, wid) => f.getDispatchModel(wid), + { location: 'current', getModel: (f, wid) => f.getCurrentModel(wid) }, + { location: 'history', getModel: (f, wid) => f.getHistoryModel(wid) }, + { location: 'dispatch', getModel: (f, wid) => f.getDispatchModel(wid) }, ]; - for (const getModel of tableGetters) { + + let location = null; + try { + if (factory && typeof factory.getOrderLocation === 'function') { + location = await factory.getOrderLocation(e.order_id, warehouseId); + } + } catch (err) { /* ignore */ } + + const orderedGetters = location + ? [ + ...tableGetters.filter(entry => entry.location === location), + ...tableGetters.filter(entry => entry.location !== location), + ] + : tableGetters; + + for (const entry of orderedGetters) { try { - const model = await getModel(ctx.model.OrderDeliveryFactory, warehouseId); + const model = await entry.getModel(factory, warehouseId); if (!model) continue; orderRow = await model.findOne({ attributes: [ 'id', 'wave_id', 'wave_no', 'pack_status' ], diff --git a/app/service/systems/order_express.js b/app/service/systems/order_express.js index ba0b4f5..f6cd0a9 100644 --- a/app/service/systems/order_express.js +++ b/app/service/systems/order_express.js @@ -318,6 +318,16 @@ class OrderExpressService extends Service { { label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) }, ]; + // 序列表定位优先:命中则先查对应分表,未命中(存量订单)按原顺序回退遍历 + try { + if (orderDeliveryFactory && typeof orderDeliveryFactory.getOrderLocation === 'function') { + const preferredLocation = await orderDeliveryFactory.getOrderLocation(normalizedOrderId, warehouseId); + if (preferredLocation) { + orderTableOrders.sort((a, b) => (a.label === preferredLocation ? -1 : b.label === preferredLocation ? 1 : 0)); + } + } + } catch (_err) { /* 定位失败,保持原遍历顺序 */ } + let orderRow = null; let orderDeliveryModel = null; for (const entry of orderTableOrders) { @@ -440,6 +450,16 @@ class OrderExpressService extends Service { { label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) }, ]; + // 序列表定位优先:命中则先查对应分表,未命中(存量订单)按原顺序回退遍历 + try { + if (orderDeliveryFactory && typeof orderDeliveryFactory.getOrderLocation === 'function') { + const preferredLocation = await orderDeliveryFactory.getOrderLocation(orderId, warehouseId); + if (preferredLocation) { + orderTableOrders.sort((a, b) => (a.label === preferredLocation ? -1 : b.label === preferredLocation ? 1 : 0)); + } + } + } catch (_err) { /* 定位失败,保持原遍历顺序 */ } + let orderRow = null; let orderDeliveryModel = null; for (const entry of orderTableOrders) { diff --git a/app/service/systems/waybill.js b/app/service/systems/waybill.js index 7231985..aca6cc1 100644 --- a/app/service/systems/waybill.js +++ b/app/service/systems/waybill.js @@ -73,6 +73,16 @@ class WaybillService extends MainService { }, ]; + // 序列表定位优先:命中则先查对应分表,未命中(存量订单)按原顺序回退遍历 + try { + if (orderDeliveryFactory && typeof orderDeliveryFactory.getOrderLocation === 'function') { + const preferredLocation = await orderDeliveryFactory.getOrderLocation(orderId, warehouseId); + if (preferredLocation) { + tableOrders.sort((a, b) => (a.label === preferredLocation ? -1 : b.label === preferredLocation ? 1 : 0)); + } + } + } catch (_err) { /* 定位失败,保持原遍历顺序 */ } + // 遍历多表查询订单的 wave_id 和 wave_no let orderRow = null; for (const entry of tableOrders) { diff --git a/app/service/systems/workbench.js b/app/service/systems/workbench.js index 0b7e3db..5ea0227 100644 --- a/app/service/systems/workbench.js +++ b/app/service/systems/workbench.js @@ -848,6 +848,16 @@ class WorkbenchService extends Service { { label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) }, ]; + // 序列表定位优先:命中则先查对应分表,未命中(存量订单)按原顺序回退遍历 + try { + if (orderDeliveryFactory && typeof orderDeliveryFactory.getOrderLocation === 'function') { + const preferredLocation = await orderDeliveryFactory.getOrderLocation(orderId, warehouseId); + if (preferredLocation) { + tableOrders.sort((a, b) => (a.label === preferredLocation ? -1 : b.label === preferredLocation ? 1 : 0)); + } + } + } catch (_err) { /* 定位失败,保持原遍历顺序 */ } + let orderRow = null; let orderDeliveryModel = null; for (const entry of tableOrders) { From f1278535921fdd08a7fdf5e126a77fe34283cd90 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sat, 15 Aug 2026 20:12:26 +0800 Subject: [PATCH 213/550] =?UTF-8?q?fix(shops):=20=E8=A7=86=E9=A2=91?= =?UTF-8?q?=E5=8F=B7=E6=8E=88=E6=9D=83=E5=85=81=E8=AE=B8=E5=9B=9E=E8=B0=83?= =?UTF-8?q?=E5=9C=B0=E5=9D=80=E4=B8=BA=E7=A9=BA=EF=BC=8C=E9=80=8F=E4=BC=A0?= =?UTF-8?q?=20appId/toUserName=EF=BC=8C=E8=B6=85=E6=97=B6=E8=B0=83?= =?UTF-8?q?=E8=87=B3=2015s?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/systemMethods/shops.js | 6 ++++++ app/service/systems/shops.js | 13 +++++++------ 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/app/service/systemMethods/shops.js b/app/service/systemMethods/shops.js index 8c1034d..c828973 100644 --- a/app/service/systemMethods/shops.js +++ b/app/service/systemMethods/shops.js @@ -149,6 +149,10 @@ class ShopsMethodService extends MainService { callbackurl, callback_url: callbackUrlSnake, callbackUrl, + appId, + app_id: appIdSnake, + toUserName, + to_user_name: toUserNameSnake, } = data || {}; return await this.callShopsSystem('getAuthorizeSessionKey', { @@ -156,6 +160,8 @@ class ShopsMethodService extends MainService { callbackurl: callbackurl !== undefined ? callbackurl : (callbackUrlSnake !== undefined ? callbackUrlSnake : callbackUrl), + appId: appId !== undefined ? appId : appIdSnake, + toUserName: toUserName !== undefined ? toUserName : toUserNameSnake, }, '获取授权会话失败'); } } diff --git a/app/service/systems/shops.js b/app/service/systems/shops.js index ad9d8d2..87f440b 100644 --- a/app/service/systems/shops.js +++ b/app/service/systems/shops.js @@ -691,11 +691,6 @@ class ShopsService extends Service { const authUrl = 'http://61.160.223.183:3012/api'; const shopId = data.id !== undefined ? data.id : (data.shop_id !== undefined ? data.shop_id : data.shopId); - const callbackUrl = this.normalizeText( - data.callbackurl !== undefined ? data.callbackurl : data.callback_url, - 'callbackurl', - { required: true, maxLength: 500 } - ); const appId = data.appId || ''; const toUserName = data.toUserName || ''; const shop = await this.findShopById(shopId, { allowDeleted: false }); @@ -712,6 +707,12 @@ class ShopsService extends Service { }); const platName = printPlatform ? printPlatform.get_auth_platform_name : platformCode; + // 视频号授权不依赖回调地址,允许 callbackurl 为空;其他平台仍必填 + const callbackUrl = this.normalizeText( + data.callbackurl !== undefined ? data.callbackurl : data.callback_url, + 'callbackurl', + { required: platName !== '视频号', maxLength: 500 } + ); const requestData = { RedirectCodeUrl: callbackUrl, command: 'saveShop', @@ -735,7 +736,7 @@ class ShopsService extends Service { const respone = await ctx.curl(authUrl, { method: 'POST', dataType: 'json', - timeout: 5000, + timeout: 15000, data: requestData, }); await this.app.setCacheAsync('last_respone_auth_polo', JSON.stringify(respone), 3600); From e5196dc1ea4ee89d5d65d5f6558ec45deb085e38 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sat, 15 Aug 2026 23:12:51 +0800 Subject: [PATCH 214/550] =?UTF-8?q?feat(pack):=20=E6=89=93=E5=8C=85?= =?UTF-8?q?=E4=BB=BB=E5=8A=A1=E6=9C=80=E5=A4=A7=E6=97=B6=E9=95=BF=E7=BA=A6?= =?UTF-8?q?=E6=9D=9F=E4=B8=8E=E8=87=AA=E5=8A=A8=E7=BB=93=E6=9D=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 仓库设置新增 single_order_pack_max_minutes(默认3)/group_order_pack_max_minutes(默认40) 配置 - 新增每小时定时任务扫描未结束打包任务,超时自动结束(end=start+上限) - 结束时间统一截断为开始时间+上限时长(finishPack/新任务顶替/setEndTime 接口) --- app/model/store.js | 24 ++++ app/schedule/auto_finish_pack_task.js | 48 ++++++++ app/service/systemMethods/order/packing.js | 1 + app/service/systems/order_packing.js | 10 +- app/service/systems/pack_task_auto_finish.js | 120 +++++++++++++++++++ app/service/systems/setting/warehouse.js | 18 +++ app/service/systems/workbench.js | 65 +++++++++- methods/changes/system.json | 63 ++++++++++ methods/system.json | 32 ++++- 9 files changed, 374 insertions(+), 7 deletions(-) create mode 100644 app/schedule/auto_finish_pack_task.js create mode 100644 app/service/systems/pack_task_auto_finish.js diff --git a/app/model/store.js b/app/model/store.js index 4630ef4..783d3bc 100644 --- a/app/model/store.js +++ b/app/model/store.js @@ -59,6 +59,8 @@ module.exports = app => { receiver_address: '', group_wave_prefix: 'B', delete_order_wave_prefix: 'A', + single_order_pack_max_minutes: 3, + group_order_pack_max_minutes: 40, inventory_warning_rules: DEFAULT_INVENTORY_WARNING_RULES, auto_outbound_rules: DEFAULT_AUTO_OUTBOUND_RULES, cutoff_order_enabled: 1, @@ -242,6 +244,28 @@ module.exports = app => { normalized.min_group_order_fetch_quantity = minGroupOrderFetchQuantity; } + const rawSingleOrderPackMaxMinutes = parsed.single_order_pack_max_minutes; + if (rawSingleOrderPackMaxMinutes === undefined || rawSingleOrderPackMaxMinutes === null || rawSingleOrderPackMaxMinutes === '') { + normalized.single_order_pack_max_minutes = DEFAULT_SUBJECT_CONFIG.single_order_pack_max_minutes; + } else { + const singleOrderPackMaxMinutes = Number(rawSingleOrderPackMaxMinutes); + if (!Number.isInteger(singleOrderPackMaxMinutes) || singleOrderPackMaxMinutes <= 0) { + throw new Error('subject_config.single_order_pack_max_minutes 必须是大于 0 的整数'); + } + normalized.single_order_pack_max_minutes = singleOrderPackMaxMinutes; + } + + const rawGroupOrderPackMaxMinutes = parsed.group_order_pack_max_minutes; + if (rawGroupOrderPackMaxMinutes === undefined || rawGroupOrderPackMaxMinutes === null || rawGroupOrderPackMaxMinutes === '') { + normalized.group_order_pack_max_minutes = DEFAULT_SUBJECT_CONFIG.group_order_pack_max_minutes; + } else { + const groupOrderPackMaxMinutes = Number(rawGroupOrderPackMaxMinutes); + if (!Number.isInteger(groupOrderPackMaxMinutes) || groupOrderPackMaxMinutes <= 0) { + throw new Error('subject_config.group_order_pack_max_minutes 必须是大于 0 的整数'); + } + normalized.group_order_pack_max_minutes = groupOrderPackMaxMinutes; + } + const rawExcludeRemarks = parsed.auto_allocate_express_exclude_remarks; if (rawExcludeRemarks === undefined || rawExcludeRemarks === null || rawExcludeRemarks === '') { normalized.auto_allocate_express_exclude_remarks = []; diff --git a/app/schedule/auto_finish_pack_task.js b/app/schedule/auto_finish_pack_task.js new file mode 100644 index 0000000..9b26f21 --- /dev/null +++ b/app/schedule/auto_finish_pack_task.js @@ -0,0 +1,48 @@ +'use strict'; + +/** + * 打包任务自动结束定时任务。 + * 每小时在单 worker 中扫描一次 wms_pack_task 表: + * - 扫描所有未结束的任务(status < 2),区分散单(pack_mode=1)/ 团购(pack_mode=2); + * - 按仓库拉取 subject_config 中配置的打包最大时长 + * (散单 single_order_pack_max_minutes / 团购 group_order_pack_max_minutes,单位分钟); + * - 当 当前时间 - 开始时间 > 配置时长 时自动结束, + * 将 end_time 置为 开始时间 + 上限时长,状态置为已完成(2)。 + */ +module.exports = { + schedule: { + interval: '1h', + type: 'worker', + immediate: false, + disable: false, + }, + + /** + * 执行打包任务自动结束任务。 + * + * @param {Object} ctx Egg 上下文。 + * @return {Promise} 无返回值。 + */ + async task(ctx) { + if (ctx.app._autoFinishPackTaskRunning) { + return; + } + + ctx.app._autoFinishPackTaskRunning = true; + + try { + const result = await ctx.service.systems.packTaskAutoFinish.executeAutoFinishPackTasks(); + + ctx.logger.info( + '[auto-finish-pack-task] 本轮扫描 %d 条未结束打包任务(涉及 %d 个仓库),自动结束 %d 条', + result && result.total_scanned || 0, + result && result.warehouse_count || 0, + result && result.auto_finished || 0 + ); + } catch (error) { + ctx.logger.error(`[auto-finish-pack-task] 打包任务自动结束执行失败: ${error.message}`); + } finally { + ctx.app._autoFinishPackTaskRunning = false; + } + }, +}; diff --git a/app/service/systemMethods/order/packing.js b/app/service/systemMethods/order/packing.js index cbe7487..fbb025c 100644 --- a/app/service/systemMethods/order/packing.js +++ b/app/service/systemMethods/order/packing.js @@ -62,6 +62,7 @@ class OrderPackingMethodService extends MainService { * 设置打包任务结束时间(仓库侧 system method 包装层)。 * 若任务状态不是已完成,则同步更新状态为已完成。 * 前端默认值逻辑:已有结束时间→当前时间;无结束时间→开始时间+5分钟。 + * 结束时间超过仓库配置的打包最大时长上限时,自动截断为上限时间。 * * @param {Object} data 请求体 * @param {number} data.id 打包任务ID diff --git a/app/service/systems/order_packing.js b/app/service/systems/order_packing.js index 1bc2220..c46b913 100644 --- a/app/service/systems/order_packing.js +++ b/app/service/systems/order_packing.js @@ -510,6 +510,8 @@ class OrderPackingService extends Service { * 设置打包任务结束时间。 * 按 id + warehouse_id 查找任务,更新结束时间。 * 若任务状态不是已完成(2),则同时将状态更新为已完成。 + * 结束时间超过仓库配置的打包最大时长上限时,自动截断为 开始时间+上限时长 + * (散单 single_order_pack_max_minutes / 团购 group_order_pack_max_minutes,单位分钟)。 * * @param {Object} options 操作参数 * @param {number} options.id 打包任务ID @@ -547,7 +549,13 @@ class OrderPackingService extends Service { return { code: 400, message: '结束时间不能早于开始时间', data: null }; } - const updates = { end_time: newEndTime }; + // 结束时间超过仓库配置的打包最大时长上限时,截断为 开始时间+上限时长 + const workbenchService = ctx.service.systems && ctx.service.systems.workbench; + const finalEndTime = workbenchService && typeof workbenchService.resolvePackTaskEndTime === 'function' + ? await workbenchService.resolvePackTaskEndTime(record, newEndTime) + : newEndTime; + + const updates = { end_time: finalEndTime }; // 若任务状态不是已完成(2),同步更新为已完成 if (record.status !== 2) { diff --git a/app/service/systems/pack_task_auto_finish.js b/app/service/systems/pack_task_auto_finish.js new file mode 100644 index 0000000..6601124 --- /dev/null +++ b/app/service/systems/pack_task_auto_finish.js @@ -0,0 +1,120 @@ +'use strict'; + +const MainService = require('../main'); +const { Op } = require('sequelize'); + +const PACK_MODE_GROUP = 2; +const PACK_TASK_FINISHED_STATUS = 2; +const MINUTE_MS = 60 * 1000; + +/** + * 打包任务自动结束服务。 + * 扫描 wms_pack_task 未结束任务,按仓库配置的打包最大时长 + * (散单 single_order_pack_max_minutes / 团购 group_order_pack_max_minutes,单位分钟) + * 判断是否超时,超时则将结束时间置为开始时间 + 上限时长并标记已完成。 + */ +class PackTaskAutoFinishService extends MainService { + /** + * 执行打包任务自动结束扫描。 + * + * @return {Promise} 处理统计 { total_scanned, warehouse_count, auto_finished }。 + */ + async executeAutoFinishPackTasks() { + const { ctx, app } = this; + const { PackTask } = app.model || {}; + + if (!PackTask || typeof PackTask.findAll !== 'function') { + return { total_scanned: 0, warehouse_count: 0, auto_finished: 0 }; + } + + const nowMs = Date.now(); + + // 1. 扫描所有未结束的打包任务(status < 2,即待处理/打包中),且已有开始时间 + const tasks = await PackTask.findAll({ + where: { + status: { [Op.lt]: PACK_TASK_FINISHED_STATUS }, + start_time: { [Op.ne]: null }, + }, + attributes: [ 'id', 'warehouse_id', 'pack_mode', 'start_time' ], + }); + + if (tasks.length === 0) { + return { total_scanned: 0, warehouse_count: 0, auto_finished: 0 }; + } + + // 2. 按仓库去重后拉取各仓库配置(缓存优先,模型规范化会补齐默认值) + const warehouseIds = [ ...new Set( + tasks + .map(task => Number(task.warehouse_id || 0)) + .filter(warehouseId => Number.isInteger(warehouseId) && warehouseId > 0) + ) ]; + + const configMap = new Map(); + for (const warehouseId of warehouseIds) { + try { + const subjectConfig = await ctx.service.systems.deliveryOrder.getStoreSubjectConfig(warehouseId); + configMap.set(warehouseId, subjectConfig && typeof subjectConfig === 'object' ? subjectConfig : {}); + } catch (error) { + ctx.logger.warn('[packTaskAutoFinish] 读取仓库 %d 配置失败: %s', warehouseId, error.message); + configMap.set(warehouseId, {}); + } + } + + // 3. 逐条判断超时并自动结束 + let autoFinished = 0; + + for (const task of tasks) { + const warehouseId = Number(task.warehouse_id || 0); + const config = configMap.get(warehouseId) || {}; + + const isGroup = Number(task.pack_mode) === PACK_MODE_GROUP; + const limitMinutes = Number( + isGroup ? config.group_order_pack_max_minutes : config.single_order_pack_max_minutes + ); + + // 未配置有效时长(或非法值)的仓库跳过,不做自动结束 + if (!Number.isInteger(limitMinutes) || limitMinutes <= 0) { + continue; + } + + const startMs = new Date(task.start_time).getTime(); + if (!Number.isFinite(startMs)) { + continue; + } + + const limitMs = limitMinutes * MINUTE_MS; + // 仅当 当前时间 - 开始时间 > 上限时长 时自动结束 + if (nowMs - startMs <= limitMs) { + continue; + } + + // 结束时间 = 开始时间 + 上限时长 + const endTime = new Date(startMs + limitMs); + + await task.update({ + end_time: endTime, + status: PACK_TASK_FINISHED_STATUS, + }); + + autoFinished += 1; + + ctx.logger.info( + '[packTaskAutoFinish] 自动结束超时打包任务 taskId=%d warehouseId=%d packMode=%s limitMinutes=%d start=%s end=%s', + task.id, + warehouseId, + isGroup ? 'group' : 'single', + limitMinutes, + new Date(startMs).toISOString(), + endTime.toISOString() + ); + } + + return { + total_scanned: tasks.length, + warehouse_count: warehouseIds.length, + auto_finished: autoFinished, + }; + } +} + +module.exports = PackTaskAutoFinishService; diff --git a/app/service/systems/setting/warehouse.js b/app/service/systems/setting/warehouse.js index e06b1b6..e9d804c 100644 --- a/app/service/systems/setting/warehouse.js +++ b/app/service/systems/setting/warehouse.js @@ -294,6 +294,24 @@ const WAREHOUSE_SETTING_FIELDS = Object.freeze([ stockout: Object.freeze({ _default: 24, return_issue: 48, shortage: 48 }), }), }), + Object.freeze({ + key: 'single_order_pack_max_minutes', + name: '散单打包最大时长(分钟)', + type: 'integer', + default: 3, + required: false, + description: '散单打包最大时长,单位:分钟,默认 3', + min: 1, + }), + Object.freeze({ + key: 'group_order_pack_max_minutes', + name: '团购打包最大时长(分钟)', + type: 'integer', + default: 40, + required: false, + description: '团购打包最大时长,单位:分钟,默认 40', + min: 1, + }), Object.freeze({ key: INTERNAL_WAVE_STRATEGY_VERSION_KEY, name: '仓库波次策略版本号', diff --git a/app/service/systems/workbench.js b/app/service/systems/workbench.js index 5ea0227..ca9d985 100644 --- a/app/service/systems/workbench.js +++ b/app/service/systems/workbench.js @@ -521,7 +521,8 @@ class WorkbenchService extends Service { }, }); if (previousTask) { - await previousTask.update({ end_time: new Date(packTimeMs), status: 2 }); + const previousEndTime = await this.resolvePackTaskEndTime(previousTask, new Date(packTimeMs)); + await previousTask.update({ end_time: previousEndTime, status: 2 }); ctx.logger.info('[Workbench._packOrder] 关闭上一个未结束任务 taskId=%d orderId=%d workbenchId=%d', previousTask.id, previousTask.order_id, validWorkbenchId); } @@ -736,6 +737,63 @@ class WorkbenchService extends Service { return result; } + /** + * 按仓库配置的打包最大时长约束任务结束时间。 + * 候选结束时间超过 开始时间+上限时长 时,截断为上限时间点。 + * 未配置有效时长或开始时间非法时不做约束,原样返回。 + * + * @param {Object} packTask 打包任务实例(需含 warehouse_id / pack_mode / start_time) + * @param {Date|string} endTime 候选结束时间 + * @return {Promise} 约束后的结束时间 + */ + async resolvePackTaskEndTime(packTask, endTime) { + const { ctx } = this; + const candidate = endTime instanceof Date ? endTime : new Date(endTime); + + if (!packTask || !Number.isFinite(candidate.getTime())) { + return endTime; + } + + const startMs = new Date(packTask.start_time).getTime(); + if (!Number.isFinite(startMs)) { + return endTime; + } + + const isGroup = Number(packTask.pack_mode) === 2; + let limitMinutes = null; + + try { + const warehouseId = Number(packTask.warehouse_id || 0); + const subjectConfig = await ctx.service.systems.deliveryOrder.getStoreSubjectConfig(warehouseId); + const rawMinutes = isGroup + ? subjectConfig.group_order_pack_max_minutes + : subjectConfig.single_order_pack_max_minutes; + limitMinutes = Number(rawMinutes); + } catch (error) { + ctx.logger.warn('[Workbench.resolvePackTaskEndTime] 读取仓库配置失败: %s', error.message); + } + + // 未配置有效时长时不约束结束时间 + if (!Number.isInteger(limitMinutes) || limitMinutes <= 0) { + return endTime; + } + + const maxEndMs = startMs + limitMinutes * 60 * 1000; + if (candidate.getTime() > maxEndMs) { + const cappedEndTime = new Date(maxEndMs); + ctx.logger.info( + '[Workbench.resolvePackTaskEndTime] 结束时间超过打包上限,截断为上限时间 taskId=%d packMode=%s limitMinutes=%d end=%s', + packTask.id, + isGroup ? 'group' : 'single', + limitMinutes, + cappedEndTime.toISOString() + ); + return cappedEndTime; + } + + return endTime; + } + /** * 工作台打包完成:传入工作台ID,查找最后一个未结束的打包任务并结束 * @param {Object} params - { workbench_id, warehouse_id } @@ -773,7 +831,8 @@ class WorkbenchService extends Service { } const now = new Date(); - await lastTask.update({ end_time: now, status: 2 }); + const endTime = await this.resolvePackTaskEndTime(lastTask, now); + await lastTask.update({ end_time: endTime, status: 2 }); ctx.logger.info('[Workbench._finishPack] 工作台 %d 结束打包任务 taskId=%d orderId=%d', validWorkbenchId, lastTask.id, lastTask.order_id); @@ -783,7 +842,7 @@ class WorkbenchService extends Service { finished: true, task_id: lastTask.id, order_id: lastTask.order_id, - end_time: now, + end_time: endTime, }; } diff --git a/methods/changes/system.json b/methods/changes/system.json index 4c08040..82df81e 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,67 @@ [ + { + "version": "2026.08.15-packing-setEndTime-cap", + "date": "2026-08-15", + "type": "enhanced", + "summary": "order.packing.setEndTime 增加结束时间上限约束:传入结束时间超过仓库配置的打包最大时长上限(散单 single_order_pack_max_minutes / 团购 group_order_pack_max_minutes)时,自动截断为 开始时间+上限时长 后落库", + "methods": [ + "order.packing.setEndTime" + ], + "notes": [ + "app/service/systems/order_packing.js setEndTime:结束时间不能早于开始时间校验之后,复用 workbench.resolvePackTaskEndTime 做上限截断(按 pack_mode 区分散单/团购配置,未配置有效时长时不约束)", + "截断使用最终值落库与响应(end_time/status 同步返回截断后的时间)", + "与 workbench.finishPack / packOrder 关闭旧任务 / 定时任务自动结束 的 end_time 上限语义对齐", + "同步更新 methods/system.json 中 order.packing.setEndTime 的 description、end_time 参数与响应说明" + ], + "module": "order.packing" + }, + { + "version": "2026.08.15-pack-task-end-time-cap", + "date": "2026-08-15", + "type": "enhanced", + "summary": "打包任务结束时间增加上限约束:工作台结束任务时(finishPack 手动结束、packOrder 关闭上一个未结束任务),若结束时间超过仓库配置的打包最大时长上限(散单 single_order_pack_max_minutes / 团购 group_order_pack_max_minutes),自动截断为 开始时间+上限时长", + "methods": [], + "notes": [ + "app/service/systems/workbench.js 新增 resolvePackTaskEndTime:按 warehouse_id+pack_mode 读取配置上限分钟,候选结束时间超过 开始时间+上限 时返回上限时间点,未配置有效时长或 start_time 非法时不约束", + "_packOrder 步骤4 关闭上一个未结束任务、_finishPack 手动结束 两处结束路径统一接入约束,_finishPack 响应 end_time 同步返回约束后的时间", + "与定时任务 auto_finish_pack_task 语义一致:end_time 最多为 开始时间+上限时长,自动结束与手动结束行为对齐", + "创建任务时即完成(packStatus>=2)的场景 end_time=start_time,不超上限,无需处理" + ], + "module": "setting.warehouse" + }, + { + "version": "2026.08.15-pack-task-auto-finish", + "date": "2026-08-15", + "type": "added", + "summary": "新增打包任务自动结束定时任务(每小时一次):扫描 wms_pack_task 未结束任务,按仓库配置 single_order_pack_max_minutes(散单,默认 3 分钟)/ group_order_pack_max_minutes(团购,默认 40 分钟)判断超时,当前时间-开始时间超过上限时将 end_time 置为开始时间+上限时长并标记已完成", + "methods": [], + "notes": [ + "新增 app/schedule/auto_finish_pack_task.js:interval 1h、type worker、非 immediate,单 worker 防重入(ctx.app._autoFinishPackTaskRunning)", + "新增 app/service/systems/pack_task_auto_finish.js:扫描 status < 2 且 start_time 非空的任务,按 warehouse_id 去重后经 deliveryOrder.getStoreSubjectConfig(缓存优先)拉取配置,pack_mode=2 按团购时长、其余按散单时长", + "超时判定:当前时间 - 开始时间 > 配置分钟数;结束时间 = 开始时间 + 上限时长(而非当前时间),status 置为 2", + "未配置有效时长(缺失或非正整数)的仓库跳过,不做自动结束;任务 start_time 非法时跳过", + "配置字段与仓库设置联动:single_order_pack_max_minutes / group_order_pack_max_minutes 已在 WAREHOUSE_SETTING_FIELDS 与 Store.normalizeSubjectConfig 中注册,默认值 3 / 40 分钟" + ], + "module": "setting.warehouse" + }, + { + "version": "2026.08.15-warehouse-pack-max-minutes", + "date": "2026-08-15", + "type": "added", + "summary": "仓库设置 setting.warehouse 新增打包最大时长配置:single_order_pack_max_minutes 散单打包最大时长(分钟,默认 3)、group_order_pack_max_minutes 团购打包最大时长(分钟,默认 40)", + "methods": [ + "setting.warehouse.getSettings", + "setting.warehouse.getFieldMeta", + "setting.warehouse.saveSettings" + ], + "notes": [ + "在 WAREHOUSE_SETTING_FIELDS 中新增 single_order_pack_max_minutes(integer,非必填,默认 3,min 1)与 group_order_pack_max_minutes(integer,非必填,默认 40,min 1)", + "wms_store.subject_config 默认值同步补齐(app/model/store.js DEFAULT_SUBJECT_CONFIG),normalizeSubjectConfig 增加大于 0 的整数校验,空值回退默认", + "methods/system.json 中 getSettings 响应与 saveSettings 入参补充对应字段文档", + "向后兼容:新增字段为可选,不影响既有仓库设置读写" + ], + "module": "setting.warehouse" + }, { "version": "2026.08.15-recheckOrder.scanOrder.groupInterceptSeq", "date": "2026-08-15", diff --git a/methods/system.json b/methods/system.json index 4bc7ebb..6d776d2 100644 --- a/methods/system.json +++ b/methods/system.json @@ -6918,7 +6918,7 @@ }, { "method": "order.packing.setEndTime", - "description": "设置打包任务结束时间。若任务状态不是已完成(2),则同步更新状态为已完成。前端默认值:若任务已有结束时间则默认为当前时间,否则默认为开始时间+5分钟。", + "description": "设置打包任务结束时间。若任务状态不是已完成(2),则同步更新状态为已完成。前端默认值:若任务已有结束时间则默认为当前时间,否则默认为开始时间+5分钟。结束时间超过仓库配置的打包最大时长上限时自动截断为 开始时间+上限时长(散单 single_order_pack_max_minutes 默认 3 分钟 / 团购 group_order_pack_max_minutes 默认 40 分钟)。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -6940,7 +6940,7 @@ "name": "end_time", "type": "string", "required": true, - "description": "结束时间(ISO 8601 格式,如 2026-07-27T11:00:00.000Z)。前端默认值:若任务已有结束时间→当前时间;无结束时间→开始时间+5分钟" + "description": "结束时间(ISO 8601 格式,如 2026-07-27T11:00:00.000Z)。前端默认值:若任务已有结束时间→当前时间;无结束时间→开始时间+5分钟。若超过仓库配置的打包最大时长上限(开始时间+配置分钟数),将自动截断为上限时间" } ], "response": [ @@ -6954,7 +6954,7 @@ "name": "end_time", "type": "string", "required": true, - "description": "更新后的结束时间" + "description": "更新后的结束时间(已按仓库配置上限截断,最多为开始时间+配置分钟数)" }, { "name": "status", @@ -13783,6 +13783,18 @@ "type": "string", "required": false, "description": "仓库收货地址(退货/退件收件地址),一行文本,默认空字符串" + }, + { + "name": "subject_config.single_order_pack_max_minutes", + "type": "number", + "required": false, + "description": "散单打包最大时长,单位:分钟,默认 3" + }, + { + "name": "subject_config.group_order_pack_max_minutes", + "type": "number", + "required": false, + "description": "团购打包最大时长,单位:分钟,默认 40" } ], "errors": [ @@ -14033,6 +14045,20 @@ "required": false, "source": "body.subject_config", "description": "仓库收货地址(退货/退件收件地址),一行文本,默认空字符串,最大长度 500" + }, + { + "name": "subject_config.single_order_pack_max_minutes", + "type": "number", + "required": false, + "source": "body.subject_config", + "description": "散单打包最大时长,单位:分钟,默认 3,须为大于 0 的整数" + }, + { + "name": "subject_config.group_order_pack_max_minutes", + "type": "number", + "required": false, + "source": "body.subject_config", + "description": "团购打包最大时长,单位:分钟,默认 40,须为大于 0 的整数" } ], "response": [ From 3ba87b4baaebeab62ef887fb565f29d1b37779d9 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sat, 15 Aug 2026 23:19:49 +0800 Subject: [PATCH 215/550] =?UTF-8?q?fix(order):=20=E6=8B=A6=E6=88=AA?= =?UTF-8?q?=E6=93=8D=E4=BD=9C=E6=97=A5=E5=BF=97=20businessId=20=E8=AF=AF?= =?UTF-8?q?=E5=86=99=E4=BB=93=E5=BA=93ID=EF=BC=8C=E6=94=B9=E4=B8=BA?= =?UTF-8?q?=E8=AE=A2=E5=8D=95ID=EF=BC=8C=E4=BF=AE=E5=A4=8D=E8=AE=A2?= =?UTF-8?q?=E5=8D=95=E8=AF=A6=E6=83=85=E6=9F=A5=E4=B8=8D=E5=88=B0=E6=8B=A6?= =?UTF-8?q?=E6=88=AA=E6=97=A5=E5=BF=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/systemMethods/order/pendingOrder.js | 4 ++-- app/service/systemMethods/order/recheckOrder.js | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/app/service/systemMethods/order/pendingOrder.js b/app/service/systemMethods/order/pendingOrder.js index 8f3ee03..2616a3e 100644 --- a/app/service/systemMethods/order/pendingOrder.js +++ b/app/service/systemMethods/order/pendingOrder.js @@ -4526,7 +4526,7 @@ ${numbered}`; return { businessType: 'order', - businessId: logWarehouseId, + businessId: orderId, operationCode: 'ORDER_INTERCEPT_REQUEST', operator, extras: { @@ -6068,7 +6068,7 @@ ${numbered}`; return { businessType: 'order', - businessId: logWarehouseId, + businessId: orderId, operationCode: 'ORDER_INTERCEPT_CANCEL', operator, extras: { diff --git a/app/service/systemMethods/order/recheckOrder.js b/app/service/systemMethods/order/recheckOrder.js index b3f43ee..dd8efbd 100644 --- a/app/service/systemMethods/order/recheckOrder.js +++ b/app/service/systemMethods/order/recheckOrder.js @@ -3693,7 +3693,7 @@ class RecheckOrderService extends OrderBaseService { const logWarehouseId = this.getOrderLogWarehouseId(warehouseId); await ctx.service.systems.operationLog.createOperationLog({ businessType: 'order', - businessId: logWarehouseId, + businessId: orderId, operationCode: 'ORDER_INTERCEPT_CONFIRM', operator, extras: { @@ -3883,7 +3883,7 @@ class RecheckOrderService extends OrderBaseService { const logWarehouseId = this.getOrderLogWarehouseId(warehouseId); await ctx.service.systems.operationLog.createOperationLog({ businessType: 'order', - businessId: logWarehouseId, + businessId: orderId, operationCode: 'ORDER_INTERCEPT_CONFIRM', operator, extras: { From e72274f222494339595461c17ab494ab57610d94 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sat, 15 Aug 2026 23:19:52 +0800 Subject: [PATCH 216/550] =?UTF-8?q?fix(inbox):=20=E7=BE=A4=E7=B1=BB?= =?UTF-8?q?=E5=9E=8B=E5=88=87=E6=8D=A2=E6=97=B6=E6=B8=85=E7=90=86=E6=AE=8B?= =?UTF-8?q?=E7=95=99=E8=B4=A7=E4=B8=BB/=E5=BF=AB=E9=80=92=E4=B8=93?= =?UTF-8?q?=E5=B1=9E=E5=AD=97=E6=AE=B5=EF=BC=8C=E5=BF=AB=E9=80=92=E7=BE=A4?= =?UTF-8?q?=E5=8E=9F=E6=96=87=E8=BD=AC=E5=8F=91=E4=BB=85=E5=8F=91=E5=8E=9F?= =?UTF-8?q?=E6=96=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/inbox/functions.js | 4 ++-- app/service/systems/inbox/group.js | 23 +++++++++++++++++------ 2 files changed, 19 insertions(+), 8 deletions(-) diff --git a/app/service/inbox/functions.js b/app/service/inbox/functions.js index 5fb8434..1495f23 100644 --- a/app/service/inbox/functions.js +++ b/app/service/inbox/functions.js @@ -2233,8 +2233,8 @@ class InboxFunctionsService extends Service { continue; } - // 原文转发:运单号 + 客户原始消息 - const forwardMsg = `运单: ${info.waybills.join('、')}\n原文: ${originalText || raw}`; + // 原文转发:仅客户原始消息(原文已含运单号) + const forwardMsg = originalText || raw; for (const g of afterSalesGroups) { ctx.service.inbox.processor.pushSystemNotification({ warehouse_id: warehouseId, diff --git a/app/service/systems/inbox/group.js b/app/service/systems/inbox/group.js index 0fb9a39..9bb7319 100644 --- a/app/service/systems/inbox/group.js +++ b/app/service/systems/inbox/group.js @@ -328,13 +328,24 @@ class InboxGroupService extends Service { if (data.storeId !== undefined) { updateData.store_id = Number.isFinite(Number(data.storeId)) && Number(data.storeId) > 0 ? Number(data.storeId) : null; + } else if (data.groupType !== undefined && targetGroupType !== 'store') { + // 群类型切为非货主群(warehouse/express)且未显式传 storeId 时, + // 清空遗留的货主绑定,避免仓库群/快递群仍残留 store_id + updateData.store_id = null; } - // 非 express 群类型时忽略 express 相关字段 - if (isExpress && expressInterfaces !== null) { - updateData.express_interfaces = expressInterfaces || null; - } - if (isExpress && systemExpressCode !== undefined) { - updateData.system_express_code = systemExpressCode || null; + // 快递专属字段处理 + if (isExpress) { + if (expressInterfaces !== null) { + updateData.express_interfaces = expressInterfaces || null; + } + if (systemExpressCode !== undefined) { + updateData.system_express_code = systemExpressCode || null; + } + } else if (data.groupType !== undefined) { + // 群类型切为非快递群(store/warehouse)时清空快递专属配置, + // 避免货主群/仓库群残留 express_interfaces / system_express_code + updateData.express_interfaces = null; + updateData.system_express_code = null; } // AI 开关(所有群类型均支持) if (data.aiEnabled !== undefined) { From 2e417f1c2704cc4d33179364ace876b40becd8f5 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sun, 16 Aug 2026 15:53:10 +0800 Subject: [PATCH 217/550] =?UTF-8?q?feat(waybill):=20=E8=BF=90=E5=8D=95?= =?UTF-8?q?=E5=AF=BC=E5=87=BA=E6=96=B0=E5=A2=9E=20where.ids=20=E5=85=A5?= =?UTF-8?q?=E5=8F=82=EF=BC=8C=E6=94=AF=E6=8C=81=E6=8C=89=E5=8B=BE=E9=80=89?= =?UTF-8?q?=E8=BF=90=E5=8D=95ID=E5=AF=BC=E5=87=BA=E5=BF=AB=E9=80=92?= =?UTF-8?q?=E5=8F=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/systems/waybill.js | 13 ++++++++++++- methods/changes/system.json | 15 +++++++++++++++ methods/system.json | 9 ++++++++- 3 files changed, 35 insertions(+), 2 deletions(-) diff --git a/app/service/systems/waybill.js b/app/service/systems/waybill.js index aca6cc1..b1e8e5d 100644 --- a/app/service/systems/waybill.js +++ b/app/service/systems/waybill.js @@ -673,7 +673,7 @@ class WaybillService extends MainService { * 复用 list 的筛选逻辑,分批查询,支持进度回调。 * * @param {Object} options 导出参数。 - * @param {Object} [options.where={}] 筛选条件(同 list)。 + * @param {Object} [options.where={}] 筛选条件(同 list,另支持 ids:运单ID数组,精确过滤)。 * @param {Object} [options.sort={}] 排序参数(同 list)。 * @param {string[]} [options.exportFields] 需要导出的字段列表,不传则导出全部字段。 * @param {Function} [options.onProgress] 进度回调,接收 `{ status, progress, currentCount, totalCount, message, result }`。 @@ -711,6 +711,17 @@ class WaybillService extends MainService { // 构建查询条件(同 list) const queryWhere = { warehouse_id: warehouseId }; + // 指定运单ID列表(勾选导出,按 wms_order_express.id 精确过滤) + const idsExport = val(where.ids); + if (Array.isArray(idsExport) && idsExport.length > 0) { + const idList = idsExport + .map(id => Number(id)) + .filter(id => Number.isFinite(id) && id > 0); + if (idList.length > 0) { + queryWhere.id = { [Op.in]: idList }; + } + } + // 主单号查询 const mainWaybillCodeExport = val(where.mainWaybillCode); if (mainWaybillCodeExport && String(mainWaybillCodeExport).trim()) { diff --git a/methods/changes/system.json b/methods/changes/system.json index 82df81e..e2526f8 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,19 @@ [ + { + "version": "2026.08.16-waybill-export-ids", + "date": "2026-08-16", + "type": "enhanced", + "summary": "waybill.warehouse.export 新增 where.ids 入参:支持按运单ID列表(勾选)导出快递号,与仓库隔离条件叠加过滤", + "methods": [ + "waybill.warehouse.export" + ], + "notes": [ + "app/service/systems/waybill.js export:新增 where.ids 处理,数组值经 Number 转换并过滤非法值后生成 id IN (...) 条件,与 warehouse_id 隔离条件叠加,不影响其他筛选字段", + "入口层 systemMethods/waybill/warehouse.js export 原样透传 where,无需改动", + "同步更新 methods/system.json 中 waybill.warehouse.export 的 where.ids 参数文档" + ], + "module": "waybill.warehouse" + }, { "version": "2026.08.15-packing-setEndTime-cap", "date": "2026-08-15", diff --git a/methods/system.json b/methods/system.json index 6d776d2..3cd04b9 100644 --- a/methods/system.json +++ b/methods/system.json @@ -31611,7 +31611,7 @@ "type": "object", "required": false, "source": "body", - "description": "筛选条件对象,同 waybill.warehouse.list 的 where 参数" + "description": "筛选条件对象,同 waybill.warehouse.list 的 where 参数,另支持 ids(运单ID数组,勾选导出)" }, { "name": "where.waybillCode", @@ -31627,6 +31627,13 @@ "source": "body.where", "description": "主单号(精确匹配)" }, + { + "name": "where.ids", + "type": "array", + "required": false, + "source": "body.where", + "description": "运单ID列表(勾选导出,按 wms_order_express.id 精确过滤)" + }, { "name": "where.orderId", "type": "number", From d5c5c641d2fd3978d6b95211c767ae65d3ba0253 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sun, 16 Aug 2026 17:42:08 +0800 Subject: [PATCH 218/550] =?UTF-8?q?feat(packing,waybill):=20=E5=88=97?= =?UTF-8?q?=E8=A1=A8=E6=97=B6=E9=97=B4=E7=AD=9B=E9=80=89=E7=BB=9F=E4=B8=80?= =?UTF-8?q?=E4=B8=BA=20between=20=E5=8C=BA=E9=97=B4=E5=86=99=E6=B3=95?= =?UTF-8?q?=EF=BC=8C=E5=85=BC=E5=AE=B9=E6=97=A7=E6=8B=86=E5=88=86=E5=AD=97?= =?UTF-8?q?=E6=AE=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/systemMethods/order/packing.js | 3 +- app/service/systems/order_packing.js | 35 +++++++++++++++-- app/service/systems/waybill.js | 27 ++++++++++++- methods/changes/system.json | 30 +++++++++++++++ methods/system.json | 44 +++++++++++++++++++--- 5 files changed, 127 insertions(+), 12 deletions(-) diff --git a/app/service/systemMethods/order/packing.js b/app/service/systemMethods/order/packing.js index fbb025c..f9b25ab 100644 --- a/app/service/systemMethods/order/packing.js +++ b/app/service/systemMethods/order/packing.js @@ -26,7 +26,8 @@ class OrderPackingMethodService extends MainService { * @param {Object} [data.where] 筛选条件。 * 支持字段:status(任务状态)、pack_mode(打包模式)、waybill_code(运单号)、wave_no(波次号)、 * order_id(订单ID)、workbench_id(工作台ID)、quickWhere(快捷搜索:波次号直接匹配 + 运单号通过express→order→wave链路解析)、 - * start_time_start / start_time_end(开始打包时间范围)。 + * start_time(开始打包时间范围,{operator:'between', value:[start,end]})、end_time(结束打包时间范围)、create_time(创建时间范围); + * start_time_start / start_time_end 为开始时间范围的兼容旧写法。 * @param {Object} [data.sort] 排序参数 { sortField, sortOrder } * @return {Promise} 统一成功包装响应 */ diff --git a/app/service/systems/order_packing.js b/app/service/systems/order_packing.js index c46b913..f069d26 100644 --- a/app/service/systems/order_packing.js +++ b/app/service/systems/order_packing.js @@ -53,8 +53,11 @@ class OrderPackingService extends Service { * @param {Object} [where.order_id] 订单ID(精确匹配) * @param {Object} [where.workbench_id] 工作台ID(精确匹配) * @param {Object} [where.quickWhere] 快捷搜索:支持波次号模糊匹配;运单号通过 express→order→wave 链路解析(团购按波次号查、散单按订单ID查) - * @param {Object} [where.start_time_start] 开始打包时间起始 - * @param {Object} [where.start_time_end] 开始打包时间结束 + * @param {Object} [where.start_time] 开始打包时间范围,支持 {operator:'between', value:[start,end]} + * @param {Object} [where.start_time_start] 开始打包时间起始(兼容旧写法) + * @param {Object} [where.start_time_end] 开始打包时间结束(兼容旧写法) + * @param {Object} [where.end_time] 结束打包时间范围,支持 {operator:'between', value:[start,end]} + * @param {Object} [where.create_time] 创建时间范围,支持 {operator:'between', value:[start,end]} * @param {Object} pagination 分页参数 { page, pageSize } * @param {Object} sort 排序参数 { sortField, sortOrder } * @return {Promise} 打包任务列表与分页信息 @@ -300,7 +303,27 @@ class OrderPackingService extends Service { } } - // 开始打包时间范围 + // 时间范围筛选:start_time / end_time / create_time + // 支持 {operator:'between', value:[start,end]} 或直接传 [start,end] + const applyTimeRangeFilter = (field, cond) => { + if (!cond) return; + const operator = String(cond?.operator || '').toLowerCase(); + let range = cond?.value ?? cond; + if (!Array.isArray(range) && operator === 'between' && range && typeof range === 'object') { + range = [ range.start ?? range.from ?? range.begin, range.end ?? range.to ?? range.finish ]; + } + if (!Array.isArray(range)) return; + const [ startVal, endVal ] = range; + if (startVal !== undefined && startVal !== null && String(startVal).trim() !== '') { + queryWhere[field] = { ...(queryWhere[field] || {}), [Op.gte]: new Date(startVal) }; + } + if (endVal !== undefined && endVal !== null && String(endVal).trim() !== '') { + queryWhere[field] = { ...(queryWhere[field] || {}), [Op.lte]: new Date(endVal) }; + } + }; + + // 开始打包时间范围(统一 between 写法 + 兼容旧拆分写法) + applyTimeRangeFilter('start_time', where.start_time); if (where.start_time_start) { const startTimeStart = where.start_time_start?.value ?? where.start_time_start; if (startTimeStart) { @@ -314,6 +337,12 @@ class OrderPackingService extends Service { } } + // 结束打包时间范围 + applyTimeRangeFilter('end_time', where.end_time); + + // 创建时间范围 + applyTimeRangeFilter('create_time', where.create_time); + // 排序 const sortField = sort.sortField || 'create_time'; const sortOrder = String(sort.sortOrder || 'DESC').toUpperCase() === 'ASC' ? 'ASC' : 'DESC'; diff --git a/app/service/systems/waybill.js b/app/service/systems/waybill.js index b1e8e5d..3116243 100644 --- a/app/service/systems/waybill.js +++ b/app/service/systems/waybill.js @@ -154,7 +154,7 @@ class WaybillService extends MainService { * 主单号通过 SELF JOIN 同 order_id 下 business_key=1 的记录获取。 * * @param {Object} [options={}] 查询参数。 - * @param {Object} [options.where] 筛选条件,支持 waybillCode / mainWaybillCode / orderId / orderNo / logisticsCode / logisticsInterfaceId / platformCode / status / isBack / isIntercept / isGalaxyReceive / packageMaterialId / hasWeighingWeight / keyword / createdAtStart / createdAtEnd。 + * @param {Object} [options.where] 筛选条件,支持 waybillCode / mainWaybillCode / orderId / orderNo / logisticsCode / logisticsInterfaceId / platformCode / status / isBack / isIntercept / isGalaxyReceive / packageMaterialId / hasWeighingWeight / keyword / createdAt({operator:'between', value:[start,end]},兼容 createAt 别名)/ createdAtStart / createdAtEnd(旧写法兼容)。 * @param {Object} [options.pagination] 分页参数 { page, pageSize },默认 page=1, pageSize=20。 * @param {Object} [options.sort] 排序参数 { field, order },默认 create_at desc。 * @return {Promise} 运单列表与分页信息 { list, pagination }。 @@ -322,7 +322,18 @@ class WaybillService extends MainService { queryWhere.waybill_code = { [Op.like]: `%${String(keyword).trim()}%` }; } - // 创建时间范围 + // 创建时间范围:createdAt 支持 {operator:'between', value:[start,end]}(兼容 createAt 别名) + const createdAtRange = val(where.createdAt) ?? val(where.createAt); + if (Array.isArray(createdAtRange)) { + const [ unifiedCreateAtStart, unifiedCreateAtEnd ] = createdAtRange; + if (unifiedCreateAtStart && String(unifiedCreateAtStart).trim()) { + queryWhere.create_at = { ...(queryWhere.create_at || {}), [Op.gte]: new Date(unifiedCreateAtStart) }; + } + if (unifiedCreateAtEnd && String(unifiedCreateAtEnd).trim()) { + queryWhere.create_at = { ...(queryWhere.create_at || {}), [Op.lte]: new Date(unifiedCreateAtEnd) }; + } + } + // 兼容旧写法:createdAtStart / createdAtEnd const createdAtStart = val(where.createdAtStart); if (createdAtStart && String(createdAtStart).trim()) { const startDate = this.normalizeDate(String(createdAtStart).trim(), false); @@ -813,6 +824,18 @@ class WaybillService extends MainService { if (keywordExport && String(keywordExport).trim()) { queryWhere.waybill_code = { [Op.like]: `%${String(keywordExport).trim()}%` }; } + // 创建时间范围:createdAt 支持 {operator:'between', value:[start,end]}(兼容 createAt 别名) + const createdAtRangeExport = val(where.createdAt) ?? val(where.createAt); + if (Array.isArray(createdAtRangeExport)) { + const [ unifiedCreateAtStartExport, unifiedCreateAtEndExport ] = createdAtRangeExport; + if (unifiedCreateAtStartExport && String(unifiedCreateAtStartExport).trim()) { + queryWhere.create_at = { ...(queryWhere.create_at || {}), [Op.gte]: new Date(unifiedCreateAtStartExport) }; + } + if (unifiedCreateAtEndExport && String(unifiedCreateAtEndExport).trim()) { + queryWhere.create_at = { ...(queryWhere.create_at || {}), [Op.lte]: new Date(unifiedCreateAtEndExport) }; + } + } + // 兼容旧写法:createdAtStart / createdAtEnd const createdAtStartExport = val(where.createdAtStart); if (createdAtStartExport && String(createdAtStartExport).trim()) { const startDate = this.normalizeDate(String(createdAtStartExport).trim(), false); diff --git a/methods/changes/system.json b/methods/changes/system.json index e2526f8..2bdc9c9 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,34 @@ [ + { + "version": "2026.08.16-waybill-createAt-between", + "date": "2026-08-16", + "type": "enhanced", + "summary": "waybill.warehouse.list / export 创建时间筛选统一为 between 区间写法:where.createdAt 支持 {operator:\"between\", value:[起始,结束]},保留 createdAtStart/createdAtEnd 旧写法兼容", + "methods": [ + "waybill.warehouse.list", + "waybill.warehouse.export" + ], + "notes": [ + "app/service/systems/waybill.js list/export:createdAt 数组区间两端可单独为空,分别落 create_at gte/lte;同时兼容 createAt 别名与 createdAtStart/createdAtEnd 旧写法", + "同步更新 methods/system.json 中 waybill.warehouse.list / export 的 where.createdAt 参数文档" + ], + "module": "waybill.warehouse" + }, + { + "version": "2026.08.16-order-packing-list-time-filter", + "date": "2026-08-16", + "type": "enhanced", + "summary": "order.packing.list 时间筛选统一为 between 区间写法:start_time / end_time / create_time 支持 {operator:\"between\", value:[起始,结束]},与已有 start_time_start/start_time_end 旧写法兼容", + "methods": [ + "order.packing.list" + ], + "notes": [ + "app/service/systems/order_packing.js list:新增 applyTimeRangeFilter,统一处理 start_time/end_time/create_time 的 between 区间条件(数组两端可单独为空,按 gte/lte 拼接),与 warehouse_id 隔离及其他筛选叠加", + "保留 start_time_start/start_time_end 旧拆分写法的兼容处理", + "同步更新 methods/system.json 中 order.packing.list 的 where 参数文档" + ], + "module": "order.packing" + }, { "version": "2026.08.16-waybill-export-ids", "date": "2026-08-16", diff --git a/methods/system.json b/methods/system.json index 3cd04b9..f245d81 100644 --- a/methods/system.json +++ b/methods/system.json @@ -6833,17 +6833,35 @@ "required": false, "description": "快捷搜索:波次号模糊匹配 + 运单号通过 express→order→wave 链路解析" }, + { + "name": "start_time", + "type": "object", + "required": false, + "description": "开始打包时间范围:{operator:\"between\", value:[起始时间, 结束时间]},value 为 ISO 8601 或 \"YYYY-MM-DD HH:mm:ss\" 字符串数组" + }, { "name": "start_time_start", "type": "string", "required": false, - "description": "开始打包时间范围起始(ISO 8601)" + "description": "开始打包时间范围起始(ISO 8601,兼容旧写法)" }, { "name": "start_time_end", "type": "string", "required": false, - "description": "开始打包时间范围结束(ISO 8601)" + "description": "开始打包时间范围结束(ISO 8601,兼容旧写法)" + }, + { + "name": "end_time", + "type": "object", + "required": false, + "description": "结束打包时间范围:{operator:\"between\", value:[起始时间, 结束时间]},value 为 ISO 8601 或 \"YYYY-MM-DD HH:mm:ss\" 字符串数组" + }, + { + "name": "create_time", + "type": "object", + "required": false, + "description": "创建时间范围:{operator:\"between\", value:[起始时间, 结束时间]},value 为 ISO 8601 或 \"YYYY-MM-DD HH:mm:ss\" 字符串数组" }, { "name": "has_video", @@ -30911,19 +30929,26 @@ "source": "body.where", "description": "关键词搜索:同时匹配运单号(waybill_code)、主单号、订单号" }, + { + "name": "where.createdAt", + "type": "object", + "required": false, + "source": "body.where", + "description": "创建时间范围:{operator:\"between\", value:[起始时间, 结束时间]},value 为 ISO 8601 或 \"YYYY-MM-DD HH:mm:ss\" 字符串数组" + }, { "name": "where.createdAtStart", "type": "string", "required": false, "source": "body.where", - "description": "创建时间起始,格式 YYYY-MM-DD" + "description": "创建时间起始,格式 YYYY-MM-DD(兼容旧写法)" }, { "name": "where.createdAtEnd", "type": "string", "required": false, "source": "body.where", - "description": "创建时间截止,格式 YYYY-MM-DD" + "description": "创建时间截止,格式 YYYY-MM-DD(兼容旧写法)" }, { "name": "sort", @@ -31732,19 +31757,26 @@ "source": "body.where", "description": "关键词搜索" }, + { + "name": "where.createdAt", + "type": "object", + "required": false, + "source": "body.where", + "description": "创建时间范围:{operator:\"between\", value:[起始时间, 结束时间]},value 为 ISO 8601 或 \"YYYY-MM-DD HH:mm:ss\" 字符串数组" + }, { "name": "where.createdAtStart", "type": "string", "required": false, "source": "body.where", - "description": "创建时间起始,格式 YYYY-MM-DD" + "description": "创建时间起始,格式 YYYY-MM-DD(兼容旧写法)" }, { "name": "where.createdAtEnd", "type": "string", "required": false, "source": "body.where", - "description": "创建时间截止,格式 YYYY-MM-DD" + "description": "创建时间截止,格式 YYYY-MM-DD(兼容旧写法)" }, { "name": "sort", From 7ad08e488d57253b5416fe4e85f6011399d86d4d Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 17 Aug 2026 02:03:34 +0800 Subject: [PATCH 219/550] =?UTF-8?q?feat(notice):=20=E7=BB=9F=E4=B8=80?= =?UTF-8?q?=E9=80=9A=E7=9F=A5=E4=BB=93=E5=BA=93=E6=8E=A5=E5=8F=A3=E9=80=9A?= =?UTF-8?q?=E9=81=93=E4=B8=8E=E8=AE=A2=E5=8D=95=E5=90=8C=E6=AD=A5=E9=80=9A?= =?UTF-8?q?=E7=9F=A5=E5=8E=BB=E6=8A=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - warehouseNotify: 按固定群订阅经 wms_api_app 回调推送(MD5 验签),消息表登记+失败重试 - notice: 货主群缺失时降级发仓库异常群(前缀标记失败),合约停用/已解除货主不发货主群也不降级 - order_async: 订单同步通知 3 分钟去抖合并,Redis 队列+定时冲刷+失败重试 - receiving: 收货完成/驳回/审核通知走仓库通道,仓库/货主侧文案分离 - storage/inventory: 移除移库完成群通知(事件码保留,库存余量提醒仍复用) - 新增 debug:warehouse:push-receiver 调试接收服务与文档/变更记录 --- app/schedule/order_sync_notice_flush.js | 51 +++ app/service/systems/notice/index.js | 465 +++++++++++++++++--- app/service/systems/order_async.js | 538 ++++++++++++++++++++++- app/service/systems/storage/inventory.js | 45 -- app/service/systems/storage/receiving.js | 33 +- app/service/systems/warehouseNotify.js | 342 ++++++++++++++ config/config.default.js | 4 + methods/changes/warehouse.json | 66 +++ methods/warehouse_notify.json | 3 +- package.json | 1 + script/debug-complete-receiving.cjs | 116 +++++ script/debug-warehouse-push-receiver.cjs | 206 +++++++++ test/app/service/systems/notice.test.js | 61 ++- 13 files changed, 1779 insertions(+), 152 deletions(-) create mode 100644 app/schedule/order_sync_notice_flush.js create mode 100644 app/service/systems/warehouseNotify.js create mode 100644 script/debug-complete-receiving.cjs create mode 100644 script/debug-warehouse-push-receiver.cjs diff --git a/app/schedule/order_sync_notice_flush.js b/app/schedule/order_sync_notice_flush.js new file mode 100644 index 0000000..de64a05 --- /dev/null +++ b/app/schedule/order_sync_notice_flush.js @@ -0,0 +1,51 @@ +'use strict'; + +const FLUSH_TASK_NAME = 'order_sync_notice_flush'; + +module.exports = { + schedule: { + interval: '30s', + type: 'worker', + immediate: false, + disable: false, + }, + + /** + * 冲刷合并的订单同步通知。 + * 订单同步完成后不立即通知,等待 3 分钟去抖窗口结束, + * 由本任务把同一「仓库:货主」维度的订单合并为一条消息统一推送。 + * + * @param {Object} ctx Egg 上下文。 + * @return {Promise} 无返回值。 + */ + async task(ctx) { + if (ctx.app._orderSyncNoticeFlushRunning) { + ctx.logger.info(`[${FLUSH_TASK_NAME}] 任务仍在运行中,跳过本轮调度`); + return; + } + + ctx.app._orderSyncNoticeFlushRunning = true; + + try { + const orderAsyncService = ctx.service && ctx.service.systems && ctx.service.systems.orderAsync; + if (!orderAsyncService || typeof orderAsyncService.flushDeferredOrderSyncNotices !== 'function') { + ctx.logger.warn(`[${FLUSH_TASK_NAME}] orderAsync 服务不可用,跳过本轮`); + return; + } + + const result = await orderAsyncService.flushDeferredOrderSyncNotices(); + + ctx.logger.info(`[${FLUSH_TASK_NAME}] 本轮完成`, { + skipped: !!(result && result.skipped), + reason: result && result.reason, + flushedCount: result && result.flushedCount, + failedCount: result && result.failedCount, + skippedCount: result && result.skippedCount, + }); + } catch (error) { + ctx.logger.error(`[${FLUSH_TASK_NAME}] 执行失败: ${error && error.message || error}`); + } finally { + ctx.app._orderSyncNoticeFlushRunning = false; + } + }, +}; diff --git a/app/service/systems/notice/index.js b/app/service/systems/notice/index.js index f623809..b0f608f 100644 --- a/app/service/systems/notice/index.js +++ b/app/service/systems/notice/index.js @@ -28,6 +28,41 @@ const DEFAULT_REGISTERED_EVENT_CODES = Object.freeze([ 'wave_strategy_quick_scan_failed', 'store_warehouse_print_quantity_adjusted', ]); +/** + * 固定群订阅配置:事件 → 目标群类型/子类型(仓库接口消息推送通道,统一推送配置来源)。 + * 群类型定义见 app/service/inbox/groups.js 的 GROUP_TYPES: + * warehouse 子类型:receiving 收货 / production 生产 / stockout 出库 / finance 财务 / all 全体 / customer_service 客服 / exception 异常 + * store 子类型:after_sales 售后 / finance 财务 / receiving 收货(需 store_id) + */ +const FIXED_GROUP_SUBSCRIPTIONS = Object.freeze({ + receiving_completed: Object.freeze([ + Object.freeze({ groupType: 'warehouse', subType: 'receiving' }), + Object.freeze({ groupType: 'store', subType: 'receiving' }), + ]), + receiving_rejected: Object.freeze([ + Object.freeze({ groupType: 'warehouse', subType: 'receiving' }), + Object.freeze({ groupType: 'store', subType: 'receiving' }), + ]), + receiving_reviewed: Object.freeze([ + Object.freeze({ groupType: 'warehouse', subType: 'receiving' }), + Object.freeze({ groupType: 'store', subType: 'receiving' }), + ]), + order_cancel_intercepted: Object.freeze([ + Object.freeze({ groupType: 'warehouse', subType: 'exception' }), + ]), + order_sync_completed: Object.freeze([ + Object.freeze({ groupType: 'store', subType: 'after_sales' }), + ]), + store_warehouse_print_quantity_adjusted: Object.freeze([ + Object.freeze({ groupType: 'store', subType: 'finance' }), + ]), + storage_transfer_completed: Object.freeze([ + Object.freeze({ groupType: 'warehouse', subType: 'production' }), + ]), + wave_strategy_quick_scan_failed: Object.freeze([ + Object.freeze({ groupType: 'warehouse', subType: 'exception' }), + ]), +}); const DRIVER_TYPE_ALIASES = Object.freeze({ custom: 'customize', customize: 'customize', @@ -503,6 +538,12 @@ class NoticeService extends Service { name: String(directStore.name || directStore.companyName || directStore.company_name || ''), businessLicense: String(directStore.businessLicense || directStore.business_license || ''), storeRemask: String(directStore.storeRemask || directStore.store_remask || directStore.remask || ''), + warehouseUseStatus: directStore.warehouseUseStatus === undefined || directStore.warehouseUseStatus === null + ? null + : Number(directStore.warehouseUseStatus), + authStatus: directStore.authStatus === undefined || directStore.authStatus === null + ? null + : Number(directStore.authStatus), }; if (!Number.isFinite(storeId) || storeId <= 0) { @@ -519,11 +560,19 @@ class NoticeService extends Service { if (cachedStore && Object.keys(cachedStore).length > 0) { const businessLicense = String(cachedStore.businessLicense || cachedStore.business_license || normalizedStore.businessLicense || ''); const storeRemask = String(cachedStore.storeRemask || cachedStore.store_remask || cachedStore.remask || normalizedStore.storeRemask || ''); + const warehouseUseStatus = cachedStore.warehouseUseStatus === undefined || cachedStore.warehouseUseStatus === null + ? normalizedStore.warehouseUseStatus + : Number(cachedStore.warehouseUseStatus); + const authStatus = cachedStore.authStatus === undefined || cachedStore.authStatus === null + ? normalizedStore.authStatus + : Number(cachedStore.authStatus); return { id: normalizedStore.id, name: String(cachedStore.name || cachedStore.companyName || cachedStore.company_name || normalizedStore.name || ''), businessLicense, storeRemask, + warehouseUseStatus, + authStatus, }; } } catch (error) { @@ -547,18 +596,26 @@ class NoticeService extends Service { warehouse_id: warehouseId, store_id: storeId, }, - attributes: [ 'store_remask' ], + attributes: [ 'store_remask', 'warehouse_use_status', 'auth_status' ], }) : null, ]); const businessLicense = normalizedStore.businessLicense || String(storeRecord && storeRecord.business_license || ''); const storeRemask = normalizedStore.storeRemask || String(relationRecord && relationRecord.store_remask || ''); + const warehouseUseStatus = relationRecord && relationRecord.warehouse_use_status !== undefined && relationRecord.warehouse_use_status !== null + ? Number(relationRecord.warehouse_use_status) + : normalizedStore.warehouseUseStatus; + const authStatus = relationRecord && relationRecord.auth_status !== undefined && relationRecord.auth_status !== null + ? Number(relationRecord.auth_status) + : normalizedStore.authStatus; const resolvedStore = { id: normalizedStore.id, name: normalizedStore.name || String(storeRecord && storeRecord.company_name || ''), businessLicense, storeRemask, + warehouseUseStatus, + authStatus, }; if (canUseCache && this.app && typeof this.app.setCacheAsync === 'function') { @@ -580,7 +637,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 deliveryOrderService = this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.deliveryOrder; const normalizeSubjectConfig = value => { if (storeModel && typeof storeModel.normalizeSubjectConfig === 'function') { return storeModel.normalizeSubjectConfig(value); @@ -711,6 +768,7 @@ class NoticeService extends Service { mimeType: String(options.mimeType || options.contentType || ''), body: contentSource, }, + storeContent: String(options.storeContent || options.store_content || '').trim(), metadata: this.toObject(options.metadata, {}), raw: options, }; @@ -757,7 +815,7 @@ class NoticeService extends Service { } /** - * 根据主体、事件和上限筛选本次需要触达的 webhook。 + * 筛选本次需要触达的 webhook(仅支持调用方显式传入的 hooks,不再读取 wms_notification_webhook 表)。 * @param {object} payload 标准化后的消息载荷 * @return {Promise} webhook 列表 */ @@ -773,67 +831,360 @@ class NoticeService extends Service { .slice(0, webhookLimit); } - const webhookModel = this.ctx.model && this.ctx.model.NotificationWebhook; - if (!webhookModel || typeof webhookModel.findAll !== 'function') { - return []; - } - - const warehouseId = Number(payload.warehouseId || (payload.subject && payload.subject.id) || 0); - const storeId = Number(payload.storeId || (payload.store && payload.store.id) || 0); - const targetSubjectIds = []; - - if (Number.isFinite(warehouseId) && warehouseId > 0) { - targetSubjectIds.push(warehouseId); - } - - if (Number.isFinite(storeId) && storeId > 0 && !targetSubjectIds.includes(storeId)) { - targetSubjectIds.push(storeId); - } - - if (targetSubjectIds.length === 0) { - return []; - } - - const webhookGroups = await Promise.all(targetSubjectIds.map(async currentSubjectId => { - const where = { - store_id: currentSubjectId, - status: 1, - }; - - if (payload.hookType) { - where.hook_type = payload.hookType; - } - - const webhooks = await webhookModel.findAll({ - where, - order: [[ 'id', 'ASC' ]], - }); - - return webhooks - .filter(item => this.matchesEvents(item && item.events, payload)) - .slice(0, webhookLimit); - })); - - const flattenedWebhooks = webhookGroups.flat(); - const seen = new Set(); - - return flattenedWebhooks.filter(item => { - const dedupeKey = item && item.id ? `id:${item.id}` : `url:${String(item && item.hook_url || '')}`; - if (seen.has(dedupeKey)) { - return false; - } - seen.add(dedupeKey); - return true; - }); + return []; } /** - * 统一通知发送入口:规范化消息、匹配 webhook 并执行分发。 + * 获取事件对应的固定群订阅配置。 + * @param {string} event 事件编码 + * @return {Array|null} 固定订阅目标数组,未配置返回 null + */ + getFixedGroupTargets(event) { + const normalizedEvent = String(event || '').trim().toLowerCase(); + return FIXED_GROUP_SUBSCRIPTIONS[normalizedEvent] || null; + } + + /** + * 根据固定订阅配置查询本次事件需要触达的群。 + * @param {object} payload 标准化后的消息载荷 + * @param {Array|null} [targetsOverride] 可选,覆盖固定订阅目标(降级查找用) + * @return {Promise} 目标群列表 + */ + async findSubscribedGroups(payload, targetsOverride = null) { + const targets = targetsOverride || this.getFixedGroupTargets(payload.event); + if (!targets || targets.length === 0) { + return []; + } + + const groupModel = this.ctx.model && this.ctx.model.InboxGroup; + if (!groupModel || typeof groupModel.findAll !== 'function') { + this.ctx.logger.warn('[NoticeService.findSubscribedGroups] InboxGroup 模型不可用'); + return []; + } + + const warehouseId = Number(payload.warehouseId || 0); + const storeId = Number(payload.storeId || 0); + const { Op } = this.app.Sequelize; + + const conditions = []; + for (const target of targets) { + const groupType = String(target && target.groupType || '').trim().toLowerCase(); + const subType = String(target && target.subType || '').trim(); + if (!groupType) { + continue; + } + // 货主群必须定位到货主,无 store_id 时跳过 + if (groupType === 'store' && (!Number.isFinite(storeId) || storeId <= 0)) { + continue; + } + + const condition = { group_type: groupType, is_blocked: 0 }; + if (subType) { + condition.sub_type = subType; + } + if (groupType === 'store') { + condition.store_id = storeId; + } + conditions.push(condition); + } + + if (conditions.length === 0) { + return []; + } + + try { + const rows = await groupModel.findAll({ + where: { + warehouse_id: warehouseId, + [Op.or]: conditions, + }, + raw: true, + }); + + return (Array.isArray(rows) ? rows : []) + .filter(row => row && row.group_id) + .map(row => ({ + group_id: row.group_id, + group_name: row.group_name || '', + group_type: row.group_type || '', + sub_type: row.sub_type || '', + })); + } catch (error) { + this.ctx.logger.warn(`[NoticeService.findSubscribedGroups] 查询订阅群失败: ${error.message}`); + return []; + } + } + + /** + * 解析降级通知中的货主名称:优先取合约表(wms_store_warehouse)货主备注 storeRemask, + * 其次货主名称,均缺失时按 storeId 回查合约表/货主表,查不到再回退「货主{storeId}」/「货主」。 + * @param {object} payload 标准化后的消息载荷 + * @return {Promise} 货主名称 + */ + async resolveStoreLabelInternal(payload) { + const storeRemask = String((payload.store && payload.store.storeRemask) || '').trim(); + const directName = storeRemask || String((payload.store && payload.store.name) || '').trim(); + if (directName) { + return directName; + } + + const storeId = Number(payload.storeId || 0); + if (!Number.isFinite(storeId) || storeId <= 0) { + return '货主'; + } + + const warehouseId = Number(payload.warehouseId || 0); + const storeModel = this.ctx.model && this.ctx.model.Store; + const storeWarehouseModel = this.ctx.model && this.ctx.model.StoreWarehouse; + + try { + const [ storeRecord, relationRecord ] = await Promise.all([ + storeModel && typeof storeModel.findByPk === 'function' + ? storeModel.findByPk(storeId, { + attributes: [ 'id', 'company_name' ], + }) + : null, + Number.isFinite(warehouseId) && warehouseId > 0 && storeWarehouseModel && typeof storeWarehouseModel.findOne === 'function' + ? storeWarehouseModel.findOne({ + where: { + warehouse_id: warehouseId, + store_id: storeId, + }, + attributes: [ 'store_remask' ], + }) + : null, + ]); + + const contractRemask = String(relationRecord && relationRecord.store_remask || '').trim(); + const companyName = String(storeRecord && storeRecord.company_name || '').trim(); + if (contractRemask) { + return contractRemask; + } + if (companyName) { + return companyName; + } + } catch (error) { + this.ctx.logger.warn('[NoticeService.resolveStoreLabelInternal] load store name failed: %s', error.message); + } + + return `货主${storeId}`; + } + + /** + * 走仓库接口消息推送通道(不依赖 wms_notification_webhook 配置)。 + * 按固定群订阅把通知推送到货主/仓库群,由外部适配器投递。 + * @param {object} payload 标准化后的消息载荷 + * @return {Promise} 发送汇总结果 + */ + async sendToWarehouseChannel(payload) { + const { ctx } = this; + const warehouseNotifyService = ctx.service && ctx.service.systems && ctx.service.systems.warehouseNotify; + + if (!warehouseNotifyService || typeof warehouseNotifyService.pushSystemMessage !== 'function') { + ctx.logger.warn('[NoticeService.sendToWarehouseChannel] 仓库接口推送服务不可用', { + traceId: payload.traceId, + event: payload.event, + warehouseId: payload.warehouseId, + }); + + return { + success: false, + message: '仓库接口推送服务不可用', + data: { + traceId: payload.traceId, + event: payload.event, + matchedGroupCount: 0, + sentCount: 0, + failedCount: 0, + results: [], + }, + }; + } + + const groups = await this.findSubscribedGroups(payload); + + // 货主目标群未配置时,降级发送到仓库异常群,内容前缀标记失败 + const fixedTargets = this.getFixedGroupTargets(payload.event) || []; + const hasStoreTarget = fixedTargets.some( + target => String(target && target.groupType || '').trim().toLowerCase() === 'store' + ); + + // 合约已停用(warehouse_use_status=0)或已解除/拒绝/过期(auth_status≠2)的货主: + // 不推货主群,也不降级到异常群(该货主本就不应被通知) + const storeInfo = payload.store || {}; + const warehouseUseStatus = storeInfo.warehouseUseStatus === undefined || storeInfo.warehouseUseStatus === null + ? null + : Number(storeInfo.warehouseUseStatus); + const authStatus = storeInfo.authStatus === undefined || storeInfo.authStatus === null + ? null + : Number(storeInfo.authStatus); + const storeContractInactive = warehouseUseStatus === 0 || (authStatus !== null && authStatus !== 2); + + const effectiveGroups = storeContractInactive + ? groups.filter(group => group && group.group_type !== 'store') + : groups; + const storeGroupMatched = effectiveGroups.some(group => group && group.group_type === 'store'); + let fallbackGroups = []; + let storeLabel = '货主'; + + if (hasStoreTarget && !storeGroupMatched && !storeContractInactive) { + storeLabel = await this.resolveStoreLabelInternal(payload); + const exceptionGroups = await this.findSubscribedGroups(payload, [ + { groupType: 'warehouse', subType: 'exception' }, + ]); + const matchedGroupIds = new Set(effectiveGroups.map(group => group.group_id)); + fallbackGroups = exceptionGroups.filter(group => !matchedGroupIds.has(group.group_id)); + + if (fallbackGroups.length > 0) { + ctx.logger.warn('[NoticeService.sendToWarehouseChannel] 货主群未配置,降级发送到仓库异常群', { + traceId: payload.traceId, + event: payload.event, + warehouseId: payload.warehouseId, + storeId: payload.storeId, + storeLabel, + fallbackGroupCount: fallbackGroups.length, + }); + } + } + + const pushGroups = [ ...effectiveGroups, ...fallbackGroups ]; + if (pushGroups.length === 0) { + ctx.logger.warn('[NoticeService.sendToWarehouseChannel] 未匹配到订阅群', { + traceId: payload.traceId, + event: payload.event, + warehouseId: payload.warehouseId, + storeId: payload.storeId, + }); + + return { + success: true, + message: '未匹配到订阅群', + data: { + traceId: payload.traceId, + event: payload.event, + matchedGroupCount: 0, + sentCount: 0, + failedCount: 0, + results: [], + }, + }; + } + + const fallbackGroupIds = new Set(fallbackGroups.map(group => group.group_id)); + const message = payload.message || {}; + const fileUrl = String(message.url || '').trim(); + const tasks = pushGroups.map(group => { + // 货主群使用货主侧文案(货主端地址/路径),仓库群使用仓库侧文案 + const baseContent = group.group_type === 'store' && payload.storeContent + ? payload.storeContent + : (message.content || ''); + // 文件/图片类通知把资源链接以文本拼回 content,保持"接收方只处理 content"的协议 + const fileLine = fileUrl + ? `\n明细文件:${String(message.fileName || '').trim() ? `${String(message.fileName).trim()} ` : ''}${fileUrl}` + : ''; + // 货主群未配置降级到异常群时,内容前缀标记失败 + const failPrefix = fallbackGroupIds.has(group.group_id) + ? `通知货主【${storeLabel}】失败\n` + : ''; + + return warehouseNotifyService.pushSystemMessage({ + warehouseId: payload.warehouseId, + // 仅货主群关联货主,仓库群不标记 store_id(避免仓库群消息被误标货主) + storeId: group.group_type === 'store' ? payload.storeId : null, + group, + content: `${failPrefix}${baseContent}${fileLine}`.trim(), + extId: payload.businessId || payload.traceId, + }); + }); + const results = await Promise.all(tasks); + const sentCount = results.filter(item => item && item.success).length; + const failedCount = results.length - sentCount; + + const summary = { + traceId: payload.traceId, + event: payload.event, + warehouseId: payload.warehouseId, + storeId: payload.storeId, + matchedGroupCount: pushGroups.length, + sentCount, + failedCount, + }; + + if (failedCount > 0) { + ctx.logger.warn('[NoticeService.sendToWarehouseChannel] 群推送存在失败', summary); + } else { + ctx.logger.info('[NoticeService.sendToWarehouseChannel] 群推送完成', summary); + } + + return { + success: failedCount === 0, + message: failedCount === 0 ? '通知已推送' : `部分群推送失败(${failedCount})`, + data: { + traceId: payload.traceId, + event: payload.event, + matchedGroupCount: pushGroups.length, + sentCount, + failedCount, + results, + }, + }; + } + + /** + * 统一通知发送入口:按 channel 路由分发。 + * channel=warehouse|group(默认):走仓库接口消息推送(wms_api_app 配置 + 固定群订阅); + * channel=webhook:仅使用调用方显式传入的 hooks(不再读取 wms_notification_webhook 表); + * channel=both:双通道同时发送。 * @param {object} [options={}] 发送入参 - * @return {Promise} 发送汇总结果 + * @return {Promise} 发送汇总结果 */ async send(options = {}) { const payload = await this.normalizePayload(options); + const channel = String(options.channel || 'warehouse').trim().toLowerCase(); + + if (channel === 'warehouse' || channel === 'group') { + return await this.sendToWarehouseChannel(payload); + } + + if (channel === 'both') { + const [ webhookResult, warehouseResult ] = await Promise.all([ + this.sendViaWebhooks(payload), + this.sendToWarehouseChannel(payload), + ]); + + const webhookData = (webhookResult && webhookResult.data) || {}; + const warehouseData = (warehouseResult && warehouseResult.data) || {}; + const sentCount = Number(webhookData.sentCount || 0) + Number(warehouseData.sentCount || 0); + const failedCount = Number(webhookData.failedCount || 0) + Number(warehouseData.failedCount || 0); + const results = [ + ...(Array.isArray(webhookData.results) ? webhookData.results : []), + ...(Array.isArray(warehouseData.results) ? warehouseData.results : []), + ]; + + return { + success: webhookResult.success && warehouseResult.success, + message: `双通道发送完成(webhook ${webhookData.sentCount}/${webhookData.matchedHookCount || 0},群 ${warehouseData.sentCount}/${warehouseData.matchedGroupCount || 0})`, + data: { + traceId: payload.traceId, + event: payload.event, + matchedHookCount: Number(webhookData.matchedHookCount || 0), + matchedGroupCount: Number(warehouseData.matchedGroupCount || 0), + sentCount, + failedCount, + results, + }, + }; + } + + return await this.sendViaWebhooks(payload); + } + + /** + * 通过调用方显式传入的 hooks 分发(不读取 wms_notification_webhook 表)。 + * @param {object} payload 标准化后的消息载荷 + * @return {Promise} 发送汇总结果 + */ + async sendViaWebhooks(payload) { const webhooks = await this.findMatchedWebhooks(payload); if (webhooks.length === 0) { diff --git a/app/service/systems/order_async.js b/app/service/systems/order_async.js index 3c4be2b..572e94c 100644 --- a/app/service/systems/order_async.js +++ b/app/service/systems/order_async.js @@ -11,6 +11,16 @@ const TRANSACTION_LOCK_RETRY_BASE_DELAY_MS = 50; const DISPATCH_BATCH_SIZE = 20; const SYNC_ORDER_IDS_PROGRESS_CACHE_TTL = 7200; +// 订单同步通知合并去抖:最后一次同步后等待 3 分钟无新同步,再统一推送一条消息 +const ORDER_SYNC_NOTICE_DEBOUNCE_MS = 3 * 60 * 1000; +const ORDER_SYNC_NOTICE_RETRY_MS = 2 * 60 * 1000; +const ORDER_SYNC_NOTICE_MAX_RETRIES = 5; +const ORDER_SYNC_NOTICE_KEY_PREFIX = 'order_sync_notice'; +const ORDER_SYNC_NOTICE_FLUSH_BATCH_SIZE = 50; +const ORDER_SYNC_NOTICE_MAX_ORDER_LINES = 30; +const ORDER_SYNC_NOTICE_LIST_TTL_SECONDS = 24 * 60 * 60; +const ORDER_SYNC_NOTICE_LOCK_TTL_SECONDS = 120; + function getSyncOrderIdsProgressCacheKey(requestId) { if (!requestId) return null; return `order:pending:sync_order_ids:request:${String(requestId).trim()}`; @@ -710,16 +720,18 @@ async function processManualOrderInternal(service, orderModel, orderItemsModel, delivery_order_code: String(orderRow.delivery_order_code || '').trim(), store_id: Number(orderRow && orderRow.store_id) || 0, waybill_code: resolvedWaybillCodes, + receiver_name: String(orderRow.name || '').trim(), + receiver_phone: String(orderRow.mobile || orderRow.tel || '').trim(), warehouse_id: warehouseId, handler: 'syncManualOrders', sync_target: 'internal', route_state: 'accepted', status: 'success', - message: '订单同步通知已发送', + message: '订单同步通知已合并排队', success_count: 1, failed_count: 0, }; - const noticeResult = await sendManualSyncNoticeInternal(service, noticeSyncResult, context); + const noticeResult = await enqueueOrderSyncNoticeInternal(service, noticeSyncResult, context); if (!noticeResult || noticeResult.success !== true) { const noticeMessage = String(noticeResult && noticeResult.message || '通知发送失败').trim() || '通知发送失败'; @@ -928,9 +940,10 @@ function buildManualSyncNoticePayloadInternal(syncResult = {}, context = {}) { ? syncResult.order_ids.map(orderId => Number(orderId)).filter(orderId => Number.isFinite(orderId) && orderId > 0) : []; const warehouseId = Number(context.warehouseId || syncResult.warehouse_id || 0); - const noticeMessage = String(syncResult.message || '').trim() || '订单同步完成'; const noticeStatus = String(syncResult.status || '').trim() || 'success'; const deliveryOrderCode = String(syncResult.delivery_order_code || '').trim(); + const receiverName = String(syncResult.receiver_name || '').trim() || '无'; + const receiverPhone = String(syncResult.receiver_phone || '').trim() || '无'; const waybillCodeList = Array.isArray(syncResult.waybill_code) ? syncResult.waybill_code.map(code => String(code || '').trim()).filter(code => !!code) : (Array.isArray(syncResult.waybill_code_list) @@ -948,11 +961,7 @@ function buildManualSyncNoticePayloadInternal(syncResult = {}, context = {}) { }, title: '订单同步完成', message: [ - `仓库ID:${warehouseId || '未知'}`, - `订单ID:${orderIds.join(',') || '无'}`, - `发货单号:${deliveryOrderCode || '无'}`, - `运单号:${waybillCodeList.length > 0 ? waybillCodeList.join(',') : '无'}`, - `消息:${noticeMessage}`, + `订单${deliveryOrderCode || '无'} 姓名:${receiverName} 电话:${receiverPhone} 运单号:${waybillCodeList.length > 0 ? waybillCodeList.join(',') : '无'}`, ].join('\n'), metadata: { create_channel: CREATE_CHANNEL_MANUAL, @@ -969,6 +978,509 @@ function buildManualSyncNoticePayloadInternal(syncResult = {}, context = {}) { }; } +/** + * 解析订单同步通知合并维度中的货主 ID。 + * 与 buildManualSyncNoticePayloadInternal 的 storeId 取值保持一致。 + * + * @param {object} syncResult 单订单同步结果。 + * @param {object} context 上下文。 + * @return {number} 货主 ID。 + */ +function resolveOrderSyncNoticeStoreIdInternal(syncResult = {}, context = {}) { + return Number(syncResult.store_id || context.storeId || context.warehouseId || 0); +} + +/** + * 生成订单同步通知合并队列的成员标识。 + * 按「仓库:货主」聚合,货主售后群按货主维度订阅。 + * + * @param {number} warehouseId 仓库 ID。 + * @param {number} storeId 货主 ID。 + * @return {string} 队列成员标识。 + */ +function buildOrderSyncNoticeMemberInternal(warehouseId, storeId) { + return `${warehouseId}:${storeId}`; +} + +/** + * 解析订单同步通知合并队列的成员标识。 + * + * @param {string} member 队列成员标识。 + * @return {Object|null} 解析结果或 null。 + */ +function parseOrderSyncNoticeMemberInternal(member) { + const normalized = String(member || '').trim(); + if (!normalized) { + return null; + } + + const [ warehousePart, storePart ] = normalized.split(':'); + const warehouseId = Number(warehousePart); + const storeId = Number(storePart); + + if (!Number.isFinite(warehouseId) || warehouseId <= 0 || !Number.isFinite(storeId)) { + return null; + } + + return { warehouseId, storeId }; +} + +/** + * 生成订单同步通知合并相关的 Redis 键集合。 + * + * @param {number} warehouseId 仓库 ID。 + * @param {number} storeId 货主 ID。 + * @return {Object} Redis 键集合。 + */ +function buildOrderSyncNoticeKeysInternal(warehouseId, storeId) { + const member = buildOrderSyncNoticeMemberInternal(warehouseId, storeId); + + return { + member, + queueKey: `${ORDER_SYNC_NOTICE_KEY_PREFIX}:queue`, + listKey: `${ORDER_SYNC_NOTICE_KEY_PREFIX}:list:${member}`, + retryKey: `${ORDER_SYNC_NOTICE_KEY_PREFIX}:retry:${member}`, + lockKey: `${ORDER_SYNC_NOTICE_KEY_PREFIX}:lock:${member}`, + }; +} + +/** + * 获取订单同步通知合并使用的 Redis 客户端。 + * + * @param {object} service 服务实例。 + * @return {Object|null} Redis 客户端或 null。 + */ +function getOrderSyncNoticeRedisClientInternal(service) { + if (!service || !service.app || !service.app.redis || typeof service.app.redis.get !== 'function') { + return null; + } + + try { + return service.app.redis.get('cache') || null; + } catch (error) { + return null; + } +} + +/** + * 把单订单同步结果构建为合并队列条目。 + * + * @param {object} syncResult 单订单同步结果。 + * @return {Object} 合并队列条目。 + */ +function buildOrderSyncNoticeEntryInternal(syncResult = {}) { + const orderIds = Array.isArray(syncResult.order_ids) + ? syncResult.order_ids.map(orderId => Number(orderId)).filter(orderId => Number.isFinite(orderId) && orderId > 0) + : []; + const waybillCodes = Array.isArray(syncResult.waybill_code) + ? syncResult.waybill_code.map(code => String(code || '').trim()).filter(code => !!code) + : (Array.isArray(syncResult.waybill_code_list) + ? syncResult.waybill_code_list.map(code => String(code || '').trim()).filter(code => !!code) + : (String(syncResult.waybill_code || '').trim() ? [ String(syncResult.waybill_code || '').trim() ] : [])); + + return { + order_id: orderIds[0] || null, + delivery_order_code: String(syncResult.delivery_order_code || '').trim(), + receiver_name: String(syncResult.receiver_name || '').trim(), + receiver_phone: String(syncResult.receiver_phone || '').trim(), + waybill_codes: waybillCodes, + enqueue_at: Date.now(), + }; +} + +/** + * 解析合并队列中的原始条目。 + * + * @param {*} rawEntry 原始条目。 + * @return {Object|null} 解析结果或 null。 + */ +function parseOrderSyncNoticeEntryInternal(rawEntry) { + if (!rawEntry) { + return null; + } + + try { + const entry = typeof rawEntry === 'string' ? JSON.parse(rawEntry) : rawEntry; + if (!entry || typeof entry !== 'object') { + return null; + } + + const orderId = Number(entry.order_id); + + return { + order_id: Number.isFinite(orderId) && orderId > 0 ? orderId : null, + delivery_order_code: String(entry.delivery_order_code || '').trim(), + receiver_name: String(entry.receiver_name || '').trim(), + receiver_phone: String(entry.receiver_phone || '').trim(), + waybill_codes: Array.isArray(entry.waybill_codes) + ? entry.waybill_codes.map(code => String(code || '').trim()).filter(code => !!code) + : [], + enqueue_at: Number(entry.enqueue_at) || null, + }; + } catch (error) { + return null; + } +} + +/** + * 订单同步通知入队:把单订单通知合并到 Redis 队列, + * 等待 3 分钟去抖窗口结束后由定时任务统一推送。 + * Redis 不可用或入队失败时回退为立即发送(保持原有行为)。 + * + * @param {object} service 服务实例。 + * @param {object} syncResult 单订单同步结果。 + * @param {object} context 上下文。 + * @return {Promise} 入队或回退发送结果。 + */ +async function enqueueOrderSyncNoticeInternal(service, syncResult = {}, context = {}) { + const warehouseId = Number(context.warehouseId || syncResult.warehouse_id || 0); + const storeId = resolveOrderSyncNoticeStoreIdInternal(syncResult, context); + const redis = getOrderSyncNoticeRedisClientInternal(service); + + if (!redis) { + service.ctx.logger.warn('[OrderAsyncService.enqueueOrderSyncNotice] Redis 不可用,回退立即发送通知', { + warehouseId, + storeId, + }); + + return await sendManualSyncNoticeInternal(service, syncResult, context); + } + + const keys = buildOrderSyncNoticeKeysInternal(warehouseId, storeId); + const entry = buildOrderSyncNoticeEntryInternal(syncResult); + + try { + const dueAtSeconds = Math.floor((Date.now() + ORDER_SYNC_NOTICE_DEBOUNCE_MS) / 1000); + await redis.rpush(keys.listKey, JSON.stringify(entry)); + await redis.expire(keys.listKey, ORDER_SYNC_NOTICE_LIST_TTL_SECONDS); + await redis.zadd(keys.queueKey, dueAtSeconds, keys.member); + + service.ctx.logger.info('[OrderAsyncService.enqueueOrderSyncNotice] 订单同步通知已入队,等待合并推送', { + warehouseId, + storeId, + orderId: entry.order_id, + dueAt: dueAtSeconds * 1000, + }); + + return { + success: true, + message: '订单同步通知已合并排队,3 分钟内无新同步将统一推送', + data: { + mode: 'deferred', + warehouseId, + storeId, + due_at: dueAtSeconds * 1000, + }, + }; + } catch (error) { + service.ctx.logger.warn('[OrderAsyncService.enqueueOrderSyncNotice] 合并入队失败,回退立即发送通知', { + warehouseId, + storeId, + error: String((error && error.message) || error || '').trim(), + }); + + return await sendManualSyncNoticeInternal(service, syncResult, context); + } +} + +/** + * 构建合并后的订单同步通知载荷。 + * + * @param {number} warehouseId 仓库 ID。 + * @param {number} storeId 货主 ID。 + * @param {Object[]} entries 合并队列条目。 + * @return {Object} 通知载荷。 + */ +function buildConsolidatedOrderSyncNoticePayloadInternal(warehouseId, storeId, entries = []) { + const normalizedEntries = (Array.isArray(entries) ? entries : []).filter(entry => !!entry); + const orderLines = normalizedEntries.map(entry => { + const code = String(entry.delivery_order_code || '').trim() || '无'; + const name = String(entry.receiver_name || '').trim() || '无'; + const phone = String(entry.receiver_phone || '').trim() || '无'; + const waybillList = Array.isArray(entry.waybill_codes) ? entry.waybill_codes : []; + const waybill = waybillList.length > 0 ? waybillList.join(',') : '无'; + + return `订单${code} 姓名:${name} 电话:${phone} 运单号:${waybill}`; + }); + + const shownLines = orderLines.slice(0, ORDER_SYNC_NOTICE_MAX_ORDER_LINES); + const hiddenCount = orderLines.length - shownLines.length; + const lines = [ + `订单同步完成(共 ${normalizedEntries.length} 单)`, + ...shownLines, + ]; + + if (hiddenCount > 0) { + lines.push(`……其余 ${hiddenCount} 单未列出`); + } + + return { + event: 'order_sync_completed', + businessName: 'order', + warehouseId, + storeId, + subject: { + id: warehouseId, + type: 'warehouse', + }, + title: '订单同步完成', + message: lines.join('\n'), + metadata: { + create_channel: CREATE_CHANNEL_MANUAL, + sync_target: 'internal', + order_ids: normalizedEntries.map(entry => entry.order_id).filter(orderId => orderId), + order_count: normalizedEntries.length, + status: 'success', + route_state: 'accepted', + success_count: normalizedEntries.length, + failed_count: 0, + debounced: true, + }, + }; +} + +/** + * 发送合并后的订单同步通知。 + * + * @param {object} service 服务实例。 + * @param {number} warehouseId 仓库 ID。 + * @param {number} storeId 货主 ID。 + * @param {Object[]} entries 合并队列条目。 + * @return {Promise} 通知服务返回结果。 + */ +async function sendConsolidatedOrderSyncNoticeInternal(service, warehouseId, storeId, entries = []) { + const rawNoticeService = service && service.ctx && service.ctx.service && service.ctx.service.systems && service.ctx.service.systems.notice; + const noticeService = rawNoticeService && typeof rawNoticeService.send === 'function' + ? rawNoticeService + : (rawNoticeService && rawNoticeService.index && typeof rawNoticeService.index.send === 'function' + ? rawNoticeService.index + : null); + if (!noticeService || typeof noticeService.send !== 'function') { + throw new Error('通知服务不可用'); + } + + const payload = buildConsolidatedOrderSyncNoticePayloadInternal(warehouseId, storeId, entries); + + service.ctx.logger.info('[OrderAsyncService.flushDeferredOrderSyncNotices] 合并通知发送前', { + warehouseId, + storeId, + entryCount: entries.length, + }); + + const noticeResult = await noticeService.send(payload); + + service.ctx.logger.info('[OrderAsyncService.flushDeferredOrderSyncNotices] 合并通知发送结果', { + warehouseId, + storeId, + entryCount: entries.length, + success: !!(noticeResult && noticeResult.success), + message: noticeResult && noticeResult.message, + }); + + return noticeResult; +} + +/** + * 处理合并通知发送失败:放回队列并按重试策略推迟。 + * + * @param {object} service 服务实例。 + * @param {Object} redis Redis 客户端。 + * @param {Object} keys 合并维度键集合。 + * @param {string} queueKey 全局队列键。 + * @param {string} member 队列成员。 + * @param {Object[]} entries 合并队列条目。 + * @return {Promise} 无返回值。 + */ +async function handleOrderSyncNoticeFlushFailureInternal(service, redis, keys, queueKey, member, entries) { + const retries = Number(await redis.incr(keys.retryKey)) || 1; + + if (retries >= ORDER_SYNC_NOTICE_MAX_RETRIES) { + await redis.del(keys.listKey, keys.retryKey); + await redis.zrem(queueKey, member); + service.ctx.logger.error('[OrderAsyncService.flushDeferredOrderSyncNotices] 合并通知重试次数超限,放弃发送', { + member, + entryCount: entries.length, + retries, + }); + + return; + } + + if (entries.length > 0) { + await redis.rpush(keys.listKey, ...entries.map(entry => JSON.stringify(entry))); + await redis.expire(keys.listKey, ORDER_SYNC_NOTICE_LIST_TTL_SECONDS); + } + + await redis.zadd(queueKey, Math.floor((Date.now() + ORDER_SYNC_NOTICE_RETRY_MS) / 1000), member); + service.ctx.logger.warn('[OrderAsyncService.flushDeferredOrderSyncNotices] 合并通知发送失败,已重新排队', { + member, + entryCount: entries.length, + retries, + }); +} + +/** + * 冲刷合并的订单同步通知:把 3 分钟去抖窗口已到期的「仓库:货主」维度订单统一推送。 + * 由定时任务调用。 + * + * @param {object} service 服务实例。 + * @return {Promise} 本轮冲刷结果。 + */ +async function flushDeferredOrderSyncNoticesInternal(service) { + const redis = getOrderSyncNoticeRedisClientInternal(service); + if (!redis) { + service.ctx.logger.warn('[OrderAsyncService.flushDeferredOrderSyncNotices] Redis 不可用,跳过本轮合并通知'); + + return { + skipped: true, + reason: 'redis_unavailable', + flushedCount: 0, + failedCount: 0, + skippedCount: 0, + }; + } + + const queueKey = `${ORDER_SYNC_NOTICE_KEY_PREFIX}:queue`; + const nowSeconds = Math.floor(Date.now() / 1000); + let dueMembers = []; + + try { + dueMembers = await redis.zrangebyscore(queueKey, '-inf', nowSeconds, 'LIMIT', 0, ORDER_SYNC_NOTICE_FLUSH_BATCH_SIZE); + } catch (error) { + service.ctx.logger.error('[OrderAsyncService.flushDeferredOrderSyncNotices] 读取到期队列失败', { + error: String((error && error.message) || error || '').trim(), + }); + + return { + skipped: true, + reason: 'queue_read_failed', + flushedCount: 0, + failedCount: 0, + skippedCount: 0, + }; + } + + if (!Array.isArray(dueMembers) || dueMembers.length === 0) { + return { + skipped: false, + flushedCount: 0, + failedCount: 0, + skippedCount: 0, + }; + } + + let flushedCount = 0; + let failedCount = 0; + let skippedCount = 0; + + for (const member of dueMembers) { + const parsedMember = parseOrderSyncNoticeMemberInternal(member); + if (!parsedMember) { + skippedCount += 1; + continue; + } + + const keys = buildOrderSyncNoticeKeysInternal(parsedMember.warehouseId, parsedMember.storeId); + let lockAcquired = false; + + try { + const lockResult = await redis.set(keys.lockKey, String(process.pid || ''), 'EX', ORDER_SYNC_NOTICE_LOCK_TTL_SECONDS, 'NX'); + lockAcquired = lockResult === 'OK'; + } catch (lockError) { + service.ctx.logger.warn('[OrderAsyncService.flushDeferredOrderSyncNotices] 获取合并锁失败,跳过本轮', { + member, + error: String((lockError && lockError.message) || lockError || '').trim(), + }); + continue; + } + + if (!lockAcquired) { + skippedCount += 1; + continue; + } + + try { + // 加锁期间可能又有新订单入队把到期时间推后,重新校验到期时间 + const currentScore = await redis.zscore(queueKey, member); + if (Number(currentScore) > nowSeconds) { + skippedCount += 1; + continue; + } + + const existsCount = Number(await redis.exists(keys.listKey)) || 0; + if (existsCount === 0) { + await redis.del(keys.listKey, keys.retryKey); + await redis.zrem(queueKey, member); + continue; + } + + // 原子搬走列表,避免与并发新入队条目互相污染 + const processingKey = `${keys.listKey}:processing`; + await redis.rename(keys.listKey, processingKey); + const rawEntries = await redis.lrange(processingKey, 0, -1); + await redis.del(processingKey); + + const entries = (Array.isArray(rawEntries) ? rawEntries : []) + .map(rawEntry => parseOrderSyncNoticeEntryInternal(rawEntry)) + .filter(entry => !!entry); + + if (entries.length === 0) { + await redis.del(keys.retryKey); + await redis.zrem(queueKey, member); + continue; + } + + const noticeResult = await sendConsolidatedOrderSyncNoticeInternal( + service, + parsedMember.warehouseId, + parsedMember.storeId, + entries + ); + + if (noticeResult && noticeResult.success === true) { + await redis.del(keys.retryKey); + await redis.zrem(queueKey, member); + flushedCount += 1; + } else { + await handleOrderSyncNoticeFlushFailureInternal(service, redis, keys, queueKey, member, entries); + failedCount += 1; + } + } catch (error) { + failedCount += 1; + service.ctx.logger.error('[OrderAsyncService.flushDeferredOrderSyncNotices] 冲刷合并通知失败', { + member, + error: String((error && error.message) || error || '').trim(), + }); + + try { + await redis.zadd(queueKey, Math.floor((Date.now() + ORDER_SYNC_NOTICE_RETRY_MS) / 1000), member); + } catch (reQueueError) { + // 重新排队失败仅记录日志 + } + } finally { + try { + await redis.del(keys.lockKey); + } catch (lockReleaseError) { + // 释放锁失败仅记录日志 + } + } + } + + service.ctx.logger.info('[OrderAsyncService.flushDeferredOrderSyncNotices] 本轮合并通知冲刷完成', { + dueMemberCount: dueMembers.length, + flushedCount, + failedCount, + skippedCount, + }); + + return { + skipped: false, + flushedCount, + failedCount, + skippedCount, + }; +} + async function processQmOrderInternal(service, orderModel, orderItemsModel, qimenClient, orderId, warehouseId, orderRow, orderItems, context, waybillCode) { if (!orderRow) { @@ -1293,6 +1805,16 @@ class OrderAsyncService extends MainService { return await syncManualOrdersInternal(this, groupedOrder, context); } + /** + * 冲刷合并的订单同步通知(由定时任务调用)。 + * 把 3 分钟去抖窗口已到期的「仓库:货主」维度订单统一推送一条消息。 + * + * @return {Promise} 本轮冲刷结果。 + */ + async flushDeferredOrderSyncNotices() { + return await flushDeferredOrderSyncNoticesInternal(this); + } + /** * API 创建入口处理。 * diff --git a/app/service/systems/storage/inventory.js b/app/service/systems/storage/inventory.js index 77c2fe8..66977ff 100644 --- a/app/service/systems/storage/inventory.js +++ b/app/service/systems/storage/inventory.js @@ -680,25 +680,6 @@ class InventoryService extends Service { // ────────── 7. 提交事务 ────────── await transaction.commit(); - // ────────── 8. 发送通知(事务外) ────────── - try { - await ctx.service.systems.notice.send({ - event: 'storage_transfer_completed', - businessName: 'storage', - warehouseId, - subjectId: warehouseId, - title: '移库操作完成', - content: `移库完成:库存${storageId} -> 库位${targetSpaceId}(数量:${transferQty})`, - data: { warehouse_id: warehouseId, storage_id: storageId, target_space_id: targetSpaceId, transfer_quantity: transferQty }, - sender: { - id: ctx.user?.employees_id || ctx.user?.id, - name: ctx.user?.employees_name || '', - }, - }); - } catch (noticeErr) { - ctx.logger.warn('[inventory.transferLocation] 发送通知失败,不影响业务', noticeErr); - } - ctx.logger.info('[inventory.transferLocation] 移库完成', { warehouse_id: warehouseId, storage_id: storageId, @@ -1089,32 +1070,6 @@ class InventoryService extends Service { // ────────── 10. 提交事务 ────────── await transaction.commit(); - // ────────── 11. 发送通知(事务外) ────────── - try { - await ctx.service.systems.notice.send({ - event: 'storage_transfer_completed', - businessName: 'storage', - warehouseId, - subjectId: warehouseId, - title: '按商品移库操作完成', - content: `按商品移库完成:库位${spaceId} 商品${stockId} -> 库位${targetSpaceId}(数量:${quantity},涉及${affectedCount}条记录)`, - data: { - warehouse_id: warehouseId, - space_id: spaceId, - stock_id: stockId, - target_space_id: targetSpaceId, - transfer_quantity: quantity, - affected_storage_count: affectedCount, - }, - sender: { - id: ctx.user?.employees_id || ctx.user?.id, - name: ctx.user?.employees_name || '', - }, - }); - } catch (noticeErr) { - ctx.logger.warn('[inventory.transferByProduct] 发送通知失败,不影响业务', noticeErr); - } - ctx.logger.info('[inventory.transferByProduct] 按商品移库完成', { warehouse_id: warehouseId, space_id: spaceId, diff --git a/app/service/systems/storage/receiving.js b/app/service/systems/storage/receiving.js index b49b3f2..e7c7398 100644 --- a/app/service/systems/storage/receiving.js +++ b/app/service/systems/storage/receiving.js @@ -1009,6 +1009,7 @@ class ReceivingService extends Service { messageType: 'text', businessName: 'receiving', event: 'receiving_rejected', + channel: 'warehouse', title: `收货单 ${item.receiving_number || item.id} 已被驳回`, content: [ `驳回人:${reviewerName || '未知'}`, @@ -1029,16 +1030,9 @@ class ReceivingService extends Service { name: reviewerName, }, metadata: { - id: item.id || null, - ids: [ item.id || null ].filter(Boolean), receiving_id: item.id || null, - receiving_ids: [ item.id || null ].filter(Boolean), receiving_number: item.receiving_number || '', - receiving_numbers: item.receiving_number ? [ item.receiving_number ] : [], - receiving_creator: item.creator || null, - receiving_creators: item.creator ? [ item.creator ] : [], - receiving: item, - receivings: [ item ], + receiving_creator: item.creator && item.creator.name ? item.creator.name : null, warehouseId: warehouse_id, remark: updateData.remark || '', }, @@ -1549,6 +1543,7 @@ class ReceivingService extends Service { messageType: reportUrl ? 'file' : 'text', businessName: 'receiving', event: 'receiving_reviewed', + channel: 'warehouse', title: `收货单${receivingNumber}审核完成`, content, url: reportUrl || undefined, @@ -4104,7 +4099,10 @@ class ReceivingService extends Service { const totalBoxWeight = normalizedDetails.reduce((sum, item) => sum + Number(item.box_weight || 0), 0); const title = `收货单${receivingNumber}已完成`; const contactLines = this.getCompletionContactFields(receiving).map(([ field, value ]) => `${field}:${value || '无'}`); - const content = [ + // 仓库侧与货主侧前端地址/路径不同,分别拼快速查看链接 + const warehouseFrontendUrl = String(ctx.app.config.frontendUrl || '').trim(); + const storeFrontendUrl = String(ctx.app.config.storeFrontendUrl || ctx.app.config.frontendUrl || '').trim(); + const contentLines = [ `收货单号:${receivingNumber} 已完成`, `货主:${receiving.store_name || '未知'}`, `来货方式:${this.formatDeliveryMethod(receiving.delivery_method) || '未知'}`, @@ -4121,9 +4119,9 @@ class ReceivingService extends Service { `开始时间:${this.formatReportDate(receiving.created_at)}`, `完成时间:${this.formatReportDate(receiving.receiving_end_time)}`, `备注:${receiving.remark || '无'}`, - `快速查看:${ctx.app.config.frontendUrl || ''}/storage/receiving?id=${receivingNumber}`, // 替换为实际的前端地址 - - ].filter(Boolean).join('\n') + '。'; + ].filter(Boolean); + const content = [ ...contentLines, `快速查看:${warehouseFrontendUrl}/storage/receiving?id=${receivingNumber}` ].join('\n') + '。'; + const storeContent = [ ...contentLines, `快速查看:${storeFrontendUrl}/storage/receiving_owner?id=${receivingNumber}` ].join('\n') + '。'; return await noticeService.send({ warehouseId, @@ -4131,8 +4129,10 @@ class ReceivingService extends Service { messageType: reportUrl ? 'file' : 'text', businessName: 'receiving', event: 'receiving_completed', + channel: 'warehouse', title, content, + storeContent, url: reportUrl || undefined, fileName: reportUrl ? reportFileName : '', mimeType: reportUrl ? 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' : '', @@ -4157,15 +4157,6 @@ class ReceivingService extends Service { unmatched_details: unmatchedDetails, total_quantity: totalQuantity, }, - details: normalizedDetails, - boxSummary: { - total_box_remainder: totalBoxRemainder, - total_box_weight: totalBoxWeight, - }, - completionReport: completionReport ? { - fileKey: completionReport.fileKey || completionReport.key || '', - url: reportUrl, - } : null, }, }); } diff --git a/app/service/systems/warehouseNotify.js b/app/service/systems/warehouseNotify.js new file mode 100644 index 0000000..0718290 --- /dev/null +++ b/app/service/systems/warehouseNotify.js @@ -0,0 +1,342 @@ +'use strict'; + +const { Service } = require('egg'); +const crypto = require('crypto'); + +/** 仓库接口类型 ID(interface_type_id=3) */ +const WAREHOUSE_INTERFACE_TYPE_ID = 3; +/** 请求超时(毫秒) */ +const REQUEST_TIMEOUT_MS = 10000; +/** 日志内容长度上限 */ +const LOG_BODY_MAX = 65535; + +/** + * 仓库接口消息推送服务(出站方向:WMS → 外部系统)。 + * 复用仓库开放接口出站协议(MD5 签名 + ApiApp.callback_url), + * 供统一通知服务与 inbox 回执复用同一套发送与日志链路。 + */ +class WarehouseNotifyService extends Service { + /** + * 截断日志内容到上限长度。 + * @param {*} value 原始值。 + * @return {string} 截断后的字符串。 + */ + truncateLogBody(value) { + const str = typeof value === 'string' ? value : JSON.stringify(value || ''); + if (str.length > LOG_BODY_MAX) { + return str.substring(0, LOG_BODY_MAX); + } + return str; + } + + /** + * 获取仓库 ApiApp 回调配置(URL + 签名凭证)。 + * @param {number} warehouseId 仓库 ID。 + * @return {Promise<{url: string|null, appKey: string|null, appSecret: string|null}>} 回调配置。 + */ + async getCallbackConfig(warehouseId) { + const { ctx } = this; + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + return { url: null, appKey: null, appSecret: null }; + } + + try { + const apiApp = await ctx.model.ApiApp.findOne({ + attributes: [ 'callback_url', 'self_app_key', 'self_app_secret' ], + where: { + warehouse_id: warehouseId, + interface_type_id: WAREHOUSE_INTERFACE_TYPE_ID, + is_enabled: 1, + }, + raw: true, + }); + + return { + url: (apiApp && apiApp.callback_url) || null, + appKey: (apiApp && apiApp.self_app_key) || null, + appSecret: (apiApp && apiApp.self_app_secret) || null, + }; + } catch (error) { + ctx.logger.warn(`[warehouseNotify] 查询回调配置失败: ${error.message}`); + return { url: null, appKey: null, appSecret: null }; + } + } + + /** + * 计算 MD5 签名:MD5(appSecret + timestamp + bodyJson)。 + * @param {Object} options 签名参数。 + * @param {string} options.appSecret 应用密钥。 + * @param {number} options.timestamp Unix 秒时间戳。 + * @param {string} options.bodyJson 请求体 JSON 字符串。 + * @return {string} 签名 hex。 + */ + buildSignature({ appSecret, timestamp, bodyJson }) { + return appSecret + ? crypto.createHash('md5').update(appSecret + timestamp + bodyJson).digest('hex') + : ''; + } + + /** + * 写入仓库接口日志(失败仅记日志不抛出)。 + * @param {Object} options 日志参数。 + * @param {string} [options.appKey] API 应用 AppKey。 + * @param {string} [options.method] 请求方法名。 + * @param {number} [options.warehouseId] 仓库 ID。 + * @param {string} [options.url] 请求 URL。 + * @param {number} [options.httpStatus] HTTP 状态码。 + * @param {*} [options.body] 请求体。 + * @param {*} [options.result] 响应体。 + * @param {number} [options.useTime] 耗时(毫秒)。 + * @return {Promise} + */ + async writeLog({ + appKey, + method, + warehouseId, + url, + httpStatus, + body, + result, + useTime, + } = {}) { + const { ctx } = this; + const logModel = ctx.model && ctx.model.WarehouseLog; + if (!logModel || typeof logModel.create !== 'function') { + return; + } + + try { + await logModel.create({ + log_id: 'WN-' + Date.now() + '-' + crypto.randomBytes(3).toString('hex'), + app_key: appKey || null, + method, + warehouse_id: warehouseId || null, + url: url || null, + http_status: httpStatus || null, + body: this.truncateLogBody(body), + result: this.truncateLogBody(result), + use_time: useTime || null, + created_at: new Date(), + }); + } catch (logErr) { + ctx.logger.error('[warehouseNotify] 日志写入失败: ' + logErr.message); + } + } + + /** + * 向仓库 ApiApp 回调地址推送消息(MD5 签名 + POST)。 + * @param {Object} options 推送参数。 + * @param {number} options.warehouseId 仓库 ID。 + * @param {string} [options.method='notify.reply'] 出站 method。 + * @param {Object} [options.data={}] 消息数据(包裹在 body.data 中)。 + * @return {Promise} 推送结果。 + */ + async push({ warehouseId, method = 'notify.reply', data = {} } = {}) { + const { ctx } = this; + + const config = await this.getCallbackConfig(warehouseId); + if (!config.url) { + ctx.logger.info(`[warehouseNotify] 仓库 ${warehouseId} 未配置回调地址,跳过推送 method=${method}`); + return { + success: false, + skipped: true, + reason: '未配置回调地址(wms_api_app.callback_url 为空)', + warehouseId, + method, + }; + } + + const body = { code: 200, data }; + const bodyJson = JSON.stringify(body); + const timestamp = Math.floor(Date.now() / 1000); + const sign = this.buildSignature({ + appSecret: config.appSecret, + timestamp, + bodyJson, + }); + + const queryString = [ + `app_key=${encodeURIComponent(config.appKey || '')}`, + `method=${encodeURIComponent(method)}`, + `timestamp=${timestamp}`, + `sign=${encodeURIComponent(sign)}`, + ].join('&'); + const separator = config.url.includes('?') ? '&' : '?'; + const url = `${config.url}${separator}${queryString}`; + const startTime = Date.now(); + + try { + const curlResult = await ctx.curl(url, { + method: 'POST', + dataType: 'json', + contentType: 'json', + data: body, + headers: { 'Content-Type': 'application/json' }, + timeout: REQUEST_TIMEOUT_MS, + }); + + // HTTP 200 且 body.code=200(或未返回 code)→ 推送成功 + const pushOk = curlResult && curlResult.status === 200 + && (!curlResult.data || curlResult.data.code === undefined || curlResult.data.code === 200); + + await this.writeLog({ + appKey: config.appKey, + method, + warehouseId, + url, + httpStatus: curlResult ? curlResult.status : null, + body: bodyJson, + result: curlResult ? curlResult.data || {} : {}, + useTime: Date.now() - startTime, + }); + + return { + success: pushOk, + skipped: false, + warehouseId, + method, + httpStatus: curlResult ? curlResult.status : null, + response: curlResult ? (curlResult.data || null) : null, + error: pushOk ? null : '回调返回非200或code非200', + }; + } catch (error) { + await this.writeLog({ + appKey: config.appKey, + method, + warehouseId, + url, + httpStatus: null, + body: bodyJson, + result: 'Error: ' + error.message, + useTime: Date.now() - startTime, + }); + + return { + success: false, + skipped: false, + warehouseId, + method, + httpStatus: null, + response: null, + error: error.message, + }; + } + } + + /** + * 向指定群推送系统级业务通知(复用 notify.reply,type=system)。 + * 对方接口只处理 content 内容,推送体仅保留协议必需字段: + * type / content / ext_id / group_id / group_name / timestamp。 + * 推送前写入 wms_inbox_message(direction=outbound,source_type=system), + * 推送后按结果回写 push_status(2=已送达 / 3=失败)与 push_response。 + * @param {Object} options 推送参数。 + * @param {number} options.warehouseId 仓库 ID。 + * @param {number} [options.storeId] 货主 ID。 + * @param {Object} options.group 目标群 { group_id, group_name }。 + * @param {string} [options.content=''] 通知正文。 + * @param {number|string} [options.extId] 业务单号(用于幂等 ext_id)。 + * @return {Promise} 推送结果(含 messageId)。 + */ + async pushSystemMessage({ warehouseId, storeId = null, group, content = '', extId = null } = {}) { + const { ctx } = this; + const groupId = String((group && group.group_id) || '').trim(); + const groupName = String((group && group.group_name) || '').trim(); + + if (!groupId || !groupName) { + return { + success: false, + skipped: true, + reason: '目标群缺少 group_id 或 group_name', + warehouseId, + }; + } + + // 幂等 ext_id:业务单号 + 群维度,网络重推时复用同一条消息记录 + const sourceExtId = String(extId || `sys:notice:${Date.now()}:${Math.random().toString(36).slice(2, 8)}`); + const uniqueExtId = `sys:notice:${sourceExtId}:${groupId}`; + + const InboxMessage = ctx.model && ctx.model.InboxMessage; + const normalizedContent = String(content || '').trim() || '系统通知'; + let messageId = null; + + if (InboxMessage) { + try { + const existing = await InboxMessage.findOne({ + where: { ext_id: uniqueExtId }, + attributes: [ 'id' ], + paranoid: false, + }); + if (existing) { + messageId = Number(existing.id); + } else { + const created = await InboxMessage.create({ + ext_id: uniqueExtId, + warehouse_id: Number(warehouseId || 0), + store_id: Number(storeId || 0) > 0 ? Number(storeId) : null, + direction: 'outbound', + parent_id: null, + source_type: 'system', + source_extra: 'notice', + target_type: 'api', + group_id: groupId, + user_id: null, + group_name: groupName, + user_name: null, + content: normalizedContent, + ext_data: null, + flags: {}, + push_status: 1, + push_started_at: new Date(), + }); + messageId = Number(created.id); + } + } catch (messageErr) { + ctx.logger.warn('[warehouseNotify] 写消息表失败: ' + messageErr.message); + } + } + + const result = await this.push({ + warehouseId, + method: 'notify.reply', + data: { + type: 'system', + content: normalizedContent, + ext_id: sourceExtId, + group_id: groupId, + group_name: groupName, + timestamp: Math.floor(Date.now() / 1000), + }, + }); + + // 回写推送状态(失败仅记日志,不影响业务) + if (InboxMessage && messageId) { + try { + if (result.success) { + await InboxMessage.update({ + push_status: 2, + push_response: { + http_status: result.httpStatus, + body: result.response || null, + }, + pushed_at: new Date(), + }, { where: { id: messageId } }); + } else { + await InboxMessage.update({ + push_status: 3, + push_response: { + http_status: result.httpStatus, + body: result.response || null, + error: result.error || result.reason || '推送失败', + }, + }, { where: { id: messageId } }); + } + } catch (updateErr) { + ctx.logger.warn('[warehouseNotify] 回写推送状态失败: ' + updateErr.message); + } + } + + return { ...result, messageId }; + } +} + +module.exports = WarehouseNotifyService; diff --git a/config/config.default.js b/config/config.default.js index ac5bf8b..15c0d5e 100644 --- a/config/config.default.js +++ b/config/config.default.js @@ -212,6 +212,10 @@ module.exports = appInfo => { config.printService = { url: 'http://printer.wms.gztbyc.com', }; + // 仓库侧前端地址(通知文案快速查看链接) + config.frontendUrl = 'http://wms.wms.gztbyc.com'; + // 货主侧前端地址(货主群通知使用,与仓库侧不同) + config.storeFrontendUrl = 'http://store.wms.gztbyc.com'; config.printRetryCompensation = { enable: false, intervalMs: 60 * 1000, diff --git a/methods/changes/warehouse.json b/methods/changes/warehouse.json index ce92c46..9562c5b 100644 --- a/methods/changes/warehouse.json +++ b/methods/changes/warehouse.json @@ -81,5 +81,71 @@ "过滤点位于屏蔽检查之后、绑群码识别之前,仅拦截自动处理链路" ], "module": "inbox" + }, + { + "version": "2026-08-16-warehouse-01", + "date": "2026-08-16", + "type": "changed", + "summary": "统一通知系统接入仓库接口消息推送通道:收货完成/驳回/审核通知不再依赖 wms_notification_webhook 配置,按固定群订阅直接推送到仓库收货群与货主收货群", + "methods": [ + "notify.reply" + ], + "notes": [ + "新增 app/service/systems/warehouseNotify.js:仓库接口出站推送服务(MD5 签名 + wms_api_app.callback_url + wms_warehouse_log 日志),供统一通知复用", + "notice/index.js 新增 FIXED_GROUP_SUBSCRIPTIONS 固定订阅:receiving_completed / receiving_rejected / receiving_reviewed → warehouse:receiving + store:receiving(群类型定义见 inbox/groups.js GROUP_TYPES)", + "notice.send 支持 channel 路由:warehouse|group=走仓库接口通道(不查 webhook 配置)、webhook=默认订阅配置、both=双通道", + "receiving.js 三处通知(sendCompletionNotice/sendReviewNotice/rejectReceiving)已传 channel=warehouse,业务链路不再依赖 wms_notification_webhook 表", + "推送复用 notify.reply,data.type=system,data 仅携带 content(通知正文)与 ext_id(业务单号,幂等),接收方只处理 content", + "货主收货群匹配需要 store_id(来自收货单 receiving.store_id);无 store_id 或未配置群时仅推仓库收货群或静默跳过,不影响业务主流程" + ], + "module": "warehouse" + }, + { + "version": "2026-08-16-warehouse-02", + "date": "2026-08-16", + "type": "changed", + "summary": "统一通知全面迁移仓库接口通道:移除对 wms_notification_webhook 表的读取,全部事件默认经 wms_api_app 配置按固定群订阅推送", + "methods": [ + "notify.reply" + ], + "notes": [ + "notice.send 默认 channel 由 webhook 改为 warehouse:全部通知统一走仓库接口消息推送(wms_api_app.callback_url + 固定群订阅)", + "findMatchedWebhooks 移除 NotificationWebhook.findAll 数据库查询,webhook 通道仅支持调用方显式传入 hooks(channel=webhook 时)", + "FIXED_GROUP_SUBSCRIPTIONS 补齐全部事件:order_cancel_intercepted→warehouse:exception、order_sync_completed→store:after_sales(货主售后群,文案为每行一个订单:订单xx 姓名:xx 电话:xx 运单号:xx)、store_warehouse_print_quantity_adjusted→store:finance、storage_transfer_completed→warehouse:production、wave_strategy_quick_scan_failed→warehouse:exception", + "resolveSubjectConfig 增加 ctx.service 防御判断,兼容单元测试与最小上下文", + "test/app/service/systems/notice.test.js 适配新通道:webhook 行为用例改为显式 channel=webhook + hooks 入参,全部 12 用例通过" + ], + "module": "warehouse" + }, + { + "version": "2026-08-17-warehouse-01", + "date": "2026-08-17", + "type": "changed", + "summary": "订单同步通知去抖合并:订单同步完成后不再逐单立即通知,等待 3 分钟无新同步后按「仓库:货主」维度合并为一条消息统一推送到货主售后群", + "methods": [ + "notify.reply" + ], + "notes": [ + "order_async.js 新增合并队列:每次同步成功后把订单(单号/姓名/电话/运单号)写入 Redis(order_sync_notice:list:{warehouseId}:{storeId}),到期时间记录在 order_sync_notice:queue ZSET(最后一次同步 + 3 分钟)", + "新增定时任务 app/schedule/order_sync_notice_flush.js(每 30s,worker):扫描到期成员,加锁后原子 RENAME 取出列表,合并为「订单同步完成(共 N 单)+ 每单一行」的单条消息推送", + "发送失败重试:条目放回队列,2 分钟后重试,最多 5 次后放弃并记录错误日志;单条消息最多列 30 单,超出尾部提示「……其余 N 单未列出」", + "Redis 不可用或入队失败时回退为逐单立即通知(保持原有行为),订单同步流程不受影响", + "新增 test/app/service/systems/order_async.noticeDebounce.test.js:5 个用例覆盖入队不立即发、窗口内不冲刷、到期合并单条推送、多订单合并、发送失败重试" + ], + "module": "order" + }, + { + "version": "2026-08-17-warehouse-02", + "date": "2026-08-17", + "type": "removed", + "summary": "移除移库完成群通知:库存移库(transferLocation 按记录移库 / transferByProduct 按商品移库)完成后不再推送「移库操作完成/按商品移库操作完成」通知", + "methods": [ + "notify.reply" + ], + "notes": [ + "app/service/systems/storage/inventory.js 删除 transferLocation 与 transferByProduct 事务提交后的 notice.send 调用,移库业务本身不受影响", + "事件码 storage_transfer_completed 仍保留注册:app/schedule/notice_stock_remaining.js 库存余量每日提醒复用该事件码,固定群映射 warehouse:production 不变" + ], + "module": "storage" } ] diff --git a/methods/warehouse_notify.json b/methods/warehouse_notify.json index 0b29b96..08ae3b9 100644 --- a/methods/warehouse_notify.json +++ b/methods/warehouse_notify.json @@ -153,7 +153,8 @@ "type=balance:绑群成功后自动推送面单余额", "type=error:AI 无法处理时的兜底回复", "AI silent(无需回复)时不推送", - "ext_id 为 wms_inbox_message.id 主键,接收方应以 ext_id 做幂等去重,网络波动可能重推" + "ext_id 为 wms_inbox_message.id 主键,接收方应以 ext_id 做幂等去重,网络波动可能重推", + "type=system:系统级业务事件通知(收货完成/驳回/审核等,不要求 user_id/user_name),data 仅携带 content(通知正文,接收方只处理该字段)与 ext_id(业务单号,用于幂等去重),其余协议字段为 group_id / group_name / timestamp" ], "example": { "query": "?app_key=AK001×tamp=1786100000&sign=abc", diff --git a/package.json b/package.json index 90fb48d..81466bd 100644 --- a/package.json +++ b/package.json @@ -46,6 +46,7 @@ "file-writer:pressure": "node ./temp/generated-tests/file-writer-pressure.generated.test.cjs", "debug:webhook:receiver": "node ./script/debug-webhook-receiver.cjs", "debug:webhook:receiving": "node ./script/debug-send-receiving-webhooks.cjs", + "debug:warehouse:push-receiver": "node ./script/debug-warehouse-push-receiver.cjs", "doc:api:update": "node ./script/update-api-doc.cjs", "doc:api:update:dry": "node ./script/update-api-doc.cjs --dry-run", "deploy:precheck": "node ./script/deploy-precheck.cjs", diff --git a/script/debug-complete-receiving.cjs b/script/debug-complete-receiving.cjs new file mode 100644 index 0000000..09d2255 --- /dev/null +++ b/script/debug-complete-receiving.cjs @@ -0,0 +1,116 @@ +'use strict'; + +/** + * 调试脚本:为指定账号铸造 JWT 并调用系统接口完成收货。 + * 用法: + * node script/debug-complete-receiving.cjs --receiving-id=1512 --account-id=1 + * node script/debug-complete-receiving.cjs --receiving-id=1512 --account-id=1 --host=127.0.0.1 --port=6060 + */ + +const http = require('node:http'); +const jwt = require('jsonwebtoken'); + +const JWT_SECRET = 'E5#ex.g@,GfL_8?'; +const JWT_EXPIRES_IN = 14400; + +function parseArgs(argv) { + const options = { + receivingId: 0, + accountId: 1, + host: '127.0.0.1', + port: 6060, + remark: '', + }; + + for (const arg of argv) { + if (!arg.startsWith('--')) { + continue; + } + const [ rawKey, ...rest ] = arg.slice(2).split('='); + const value = rest.join('='); + switch (rawKey) { + case 'receiving-id': + options.receivingId = Number(value || options.receivingId); + break; + case 'account-id': + options.accountId = Number(value || options.accountId); + break; + case 'host': + options.host = value || options.host; + break; + case 'port': + options.port = Number(value || options.port); + break; + case 'remark': + options.remark = value || ''; + break; + default: + break; + } + } + + return options; +} + +function postSystemMethod(options, token, method, body) { + return new Promise((resolve, reject) => { + const bodyJson = JSON.stringify(body); + const path = `/system?method=${encodeURIComponent(method)}&v=1×tamp=${Math.floor(Date.now() / 1000)}`; + const req = http.request({ + hostname: options.host, + port: options.port, + path, + method: 'POST', + headers: { + platform: 'web', + project: 'wms', + Authorization: `Bearer ${token}`, + 'Content-Type': 'application/json', + 'Content-Length': Buffer.byteLength(bodyJson), + }, + }, res => { + let data = ''; + res.on('data', chunk => { + data += chunk; + }); + res.on('end', () => { + resolve({ status: res.statusCode, body: data }); + }); + }); + req.on('error', reject); + req.write(bodyJson); + req.end(); + }); +} + +async function main() { + const options = parseArgs(process.argv.slice(2)); + if (!options.receivingId) { + console.error('缺少 --receiving-id'); + process.exit(1); + } + + const token = jwt.sign({ + id: options.accountId, + platform_code: 'web', + current_store_id: 100000, + }, JWT_SECRET, { expiresIn: JWT_EXPIRES_IN }); + + console.log(`[debug-complete-receiving] accountId=${options.accountId} receivingId=${options.receivingId}`); + const result = await postSystemMethod(options, token, 'storage.receiving.completeReceiving', { + id: options.receivingId, + remark: options.remark || undefined, + }); + + console.log(`HTTP ${result.status}`); + try { + console.log(JSON.stringify(JSON.parse(result.body), null, 2).substring(0, 3000)); + } catch (_) { + console.log(result.body.substring(0, 1000)); + } +} + +main().catch(error => { + console.error('[debug-complete-receiving] failed:', error.message); + process.exit(1); +}); diff --git a/script/debug-warehouse-push-receiver.cjs b/script/debug-warehouse-push-receiver.cjs new file mode 100644 index 0000000..10ae413 --- /dev/null +++ b/script/debug-warehouse-push-receiver.cjs @@ -0,0 +1,206 @@ +'use strict'; + +/** + * 仓库接口消息推送 — 本地调试接收服务。 + * 模拟外部适配器:接收 WMS 出站推送(notify.reply / notify.event 等), + * 打印完整回信(query 签名参数 + headers + body)到控制台与日志文件,方便调试。 + * + * 默认配置匹配线上仓库「仓库管理系统oms」: + * app_key=APP2025011514315678 + * app_secret=sec_xyz789uvw012abc345def678ghi901jkl234mno567pqr890 + * callback_url=http://localhost:6061/push + * + * 用法: + * npm run debug:warehouse:push-receiver + * node script/debug-warehouse-push-receiver.cjs --port=6061 --path=/push --log-file=run/push.log + * node script/debug-warehouse-push-receiver.cjs --no-verify # 跳过 MD5 验签 + */ + +const http = require('node:http'); +const fs = require('node:fs'); +const path = require('node:path'); +const crypto = require('node:crypto'); +const { URL } = require('node:url'); + +const DEFAULT_HOST = '127.0.0.1'; +const DEFAULT_PORT = 6061; +const DEFAULT_PATH = '/push'; +const DEFAULT_APP_KEY = 'APP2025011514315678'; +const DEFAULT_APP_SECRET = 'sec_xyz789uvw012abc345def678ghi901jkl234mno567pqr890'; +const DEFAULT_LOG_FILE = path.join(process.cwd(), 'run', 'warehouse-push-receiver.log'); + +function parseArgs(argv) { + const options = { + host: process.env.PUSH_RECEIVER_HOST || DEFAULT_HOST, + port: Number(process.env.PUSH_RECEIVER_PORT || DEFAULT_PORT), + path: process.env.PUSH_RECEIVER_PATH || DEFAULT_PATH, + appKey: process.env.PUSH_RECEIVER_APP_KEY || DEFAULT_APP_KEY, + appSecret: process.env.PUSH_RECEIVER_APP_SECRET || DEFAULT_APP_SECRET, + logFile: process.env.PUSH_RECEIVER_LOG_FILE || DEFAULT_LOG_FILE, + verifySign: ![ '0', 'false' ].includes(String(process.env.PUSH_RECEIVER_VERIFY_SIGN || '1').toLowerCase()), + help: false, + }; + + for (const arg of argv) { + if (!arg.startsWith('--')) { + continue; + } + + const [ rawKey, ...rest ] = arg.slice(2).split('='); + const value = rest.join('='); + switch (rawKey) { + case 'host': + options.host = value || options.host; + break; + case 'port': + options.port = Number(value || options.port); + break; + case 'path': + options.path = value.startsWith('/') ? value : `/${value}`; + break; + case 'app-key': + options.appKey = value || options.appKey; + break; + case 'app-secret': + options.appSecret = value || options.appSecret; + break; + case 'log-file': + options.logFile = value || options.logFile; + break; + case 'no-verify': + options.verifySign = false; + break; + case 'help': + options.help = true; + break; + default: + break; + } + } + + return options; +} + +function printHelp() { + console.log(`用法: + npm run debug:warehouse:push-receiver + node script/debug-warehouse-push-receiver.cjs --port=6061 --path=/push --log-file=run/push.log + node script/debug-warehouse-push-receiver.cjs --no-verify + +参数: + --host=127.0.0.1 监听地址 + --port=6061 监听端口 + --path=/push 接收路径 + --app-key=... 期望的 app_key(仅用于展示) + --app-secret=... 验签密钥(MD5(appSecret + timestamp + bodyJson)) + --log-file=... 日志文件(默认 run/warehouse-push-receiver.log) + --no-verify 跳过 MD5 验签 + +环境变量: + PUSH_RECEIVER_HOST / PUSH_RECEIVER_PORT / PUSH_RECEIVER_PATH + PUSH_RECEIVER_APP_KEY / PUSH_RECEIVER_APP_SECRET / PUSH_RECEIVER_LOG_FILE + PUSH_RECEIVER_VERIFY_SIGN=0 关闭验签`); +} + +function readRequestBody(req) { + return new Promise((resolve, reject) => { + const chunks = []; + req.on('data', chunk => chunks.push(chunk)); + req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8'))); + req.on('error', reject); + }); +} + +function writeLog(logFile, text) { + const line = text.endsWith('\n') ? text : text + '\n'; + try { + fs.appendFileSync(logFile, line, 'utf8'); + console.log(`[push-receiver] 已写入日志文件: ${logFile}`); + } catch (error) { + console.error('[push-receiver] 写日志文件失败:', error.message); + } +} + +function md5(value) { + return crypto.createHash('md5').update(value).digest('hex'); +} + +async function start() { + const options = parseArgs(process.argv.slice(2)); + if (options.help) { + printHelp(); + return; + } + + const logFile = path.resolve(options.logFile); + const logDir = path.dirname(logFile); + fs.mkdirSync(logDir, { recursive: true }); + + const server = http.createServer(async (req, res) => { + const url = new URL(req.url, `http://${req.headers.host || `${options.host}:${options.port}`}`); + const startedAt = new Date().toISOString(); + const rawBody = await readRequestBody(req); + const query = Object.fromEntries(url.searchParams.entries()); + + if (url.pathname === '/health') { + res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' }); + res.end(JSON.stringify({ ok: true, service: 'warehouse-push-receiver' })); + return; + } + + if (req.method !== 'POST' || url.pathname !== options.path) { + res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' }); + res.end(`404 Not Found(接收路径为 ${options.path})`); + return; + } + + // MD5 验签:sign = MD5(appSecret + timestamp + bodyJson) + const timestamp = String(query.timestamp || ''); + const providedSign = String(query.sign || ''); + const expectedSign = options.appSecret ? md5(options.appSecret + timestamp + rawBody) : ''; + const signOk = !options.verifySign || (timestamp && providedSign === expectedSign); + + let parsedBody = rawBody; + try { + parsedBody = rawBody ? JSON.parse(rawBody) : null; + } catch (_) { + // keep raw text + } + + const logText = [ + '================ 收到仓库接口推送 ================', + `[time] ${startedAt}`, + `[route] POST ${url.pathname}`, + `[query] ${JSON.stringify(query, null, 2)}`, + options.verifySign + ? `[sign] ${signOk ? '验签通过' : `验签失败(期望 ${expectedSign})`}` + : '[sign] 已关闭验签', + `[header] ${JSON.stringify(req.headers, null, 2)}`, + `[body] ${JSON.stringify(parsedBody, null, 2)}`, + '==================================================', + ].join('\n'); + + console.log('\n' + logText); + writeLog(logFile, `${logText}\n`); + + // 始终返回 HTTP 200 + code=200,便于 WMS 判定推送成功 + const responseBody = JSON.stringify({ code: 200, message: 'ok', received_at: startedAt }); + res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' }); + res.end(responseBody); + }); + + server.listen(options.port, options.host, () => { + console.log('[warehouse-push-receiver] listening on http://' + options.host + ':' + options.port + options.path); + console.log(`[warehouse-push-receiver] app_key=${options.appKey}`); + console.log(`[warehouse-push-receiver] app_secret=${options.appSecret ? options.appSecret.slice(0, 8) + '…' : '(空)'}`); + console.log(`[warehouse-push-receiver] 验签=${options.verifySign ? '开启' : '关闭'}`); + console.log(`[warehouse-push-receiver] 日志文件=${logFile}`); + console.log(`[warehouse-push-receiver] 健康检查: GET http://${options.host}:${options.port}/health`); + console.log('[warehouse-push-receiver] 按 Ctrl+C 停止'); + }); +} + +start().catch(error => { + console.error('[warehouse-push-receiver] failed:', error); + process.exit(1); +}); diff --git a/test/app/service/systems/notice.test.js b/test/app/service/systems/notice.test.js index 2707ef6..a8412c0 100644 --- a/test/app/service/systems/notice.test.js +++ b/test/app/service/systems/notice.test.js @@ -53,6 +53,8 @@ describe('test/app/service/systems/notice.test.js', () => { const service = new NoticeService(ctx); const result = await service.send({ + channel: 'webhook', + hooks: webhookRows, messageType: '图片', businessName: 'receiving', event: 'receiving_completed', @@ -274,6 +276,23 @@ describe('test/app/service/systems/notice.test.js', () => { const service = new NoticeService(ctx); const result = await service.send({ + channel: 'webhook', + hooks: [ + { + id: 1, + store_id: 100000, + hook_type: 'custom', + hook_url: 'https://example.com/webhook/warehouse', + events: [ 'all' ], + }, + { + id: 2, + store_id: 1000000, + hook_type: 'custom', + hook_url: 'https://example.com/webhook/store', + events: [ 'receiving' ], + }, + ], messageType: '文本', businessName: 'receiving', event: 'receiving_completed', @@ -334,6 +353,8 @@ describe('test/app/service/systems/notice.test.js', () => { const service = new NoticeService(ctx); const result = await service.send({ + channel: 'webhook', + hooks: webhookRows, messageType: '文本', businessName: 'receiving', event: 'receiving_completed', @@ -444,18 +465,8 @@ describe('test/app/service/systems/notice.test.js', () => { app: { config: {}, }, + service: {}, model: { - NotificationWebhook: { - async findAll() { - return [{ - id: 9, - store_id: 1000000, - hook_type: 'custom', - hook_url: 'https://example.com/webhook/fail', - events: [ 'all' ], - }]; - }, - }, NotificationSendLog: { async create(data) { failureLogs.push(data); @@ -481,6 +492,14 @@ describe('test/app/service/systems/notice.test.js', () => { }; const result = await service.send({ + channel: 'webhook', + hooks: [{ + id: 9, + store_id: 1000000, + hook_type: 'custom', + hook_url: 'https://example.com/webhook/fail', + events: [ 'all' ], + }], messageType: '文本', businessName: 'receiving', event: 'receiving_completed', @@ -505,6 +524,7 @@ describe('test/app/service/systems/notice.test.js', () => { app: { config: {}, }, + service: {}, model: { NotificationWebhook: { getAvailableEventCodes() { @@ -544,6 +564,7 @@ describe('test/app/service/systems/notice.test.js', () => { app: { config: {}, }, + service: {}, model: { NotificationWebhook: { getAvailableEventCodes() { @@ -593,20 +614,12 @@ describe('test/app/service/systems/notice.test.js', () => { app: { config: {}, }, + service: {}, model: { NotificationWebhook: { getAvailableEventCodes() { return [ 'all', '*', 'receiving_completed' ]; }, - async findAll() { - return [{ - id: 21, - store_id: 1000000, - hook_type: 'wecom', - hook_url: 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=test-key', - events: [ 'receiving_completed' ], - }]; - }, }, }, logger: { @@ -628,6 +641,14 @@ describe('test/app/service/systems/notice.test.js', () => { const service = new NoticeService(ctx); const result = await service.send({ + channel: 'webhook', + hooks: [{ + id: 21, + store_id: 1000000, + hook_type: 'wecom', + hook_url: 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=test-key', + events: [ 'receiving_completed' ], + }], warehouseId: 100000, businessName: 'receiving', event: 'receiving_completed', From d0621dd4ec2a18469cbdfa98ac23da06f11f4050 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 17 Aug 2026 02:07:29 +0800 Subject: [PATCH 220/550] =?UTF-8?q?fix(order):=20=E5=B7=B2=E5=8F=96?= =?UTF-8?q?=E6=B6=88=E8=AE=A2=E5=8D=95=E8=B7=B3=E8=BF=87=E5=88=86=E9=85=8D?= =?UTF-8?q?=E5=82=A8=E4=BD=8D=E4=B8=8E=E5=88=86=E9=85=8D=E5=BF=AB=E9=80=92?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - order_storage_allocation: allocatePicking 过滤循环校验 status=cancel,已取消订单跳过并记 skipped_reason=order_cancelled,不再锁库存写 picking - express: createWaybillCodePipeline step1 的 current/dispatch 查询排除 status=cancel,createWaybillCode 事务内再次剔除取消订单(不标记异常、不写失败日志、不取号) - 新增回归测试:分配储位跳过取消订单、分配快递流水线跳过取消订单 --- app/service/systems/express.js | 33 ++- .../systems/order_storage_allocation.js | 15 ++ ...eWaybillCodePipeline.skipCancelled.test.js | 217 ++++++++++++++++++ .../systems/order_storage_allocation.test.js | 58 +++++ 4 files changed, 321 insertions(+), 2 deletions(-) create mode 100644 test/app/service/systems/express.createWaybillCodePipeline.skipCancelled.test.js diff --git a/app/service/systems/express.js b/app/service/systems/express.js index b167287..b4a252d 100644 --- a/app/service/systems/express.js +++ b/app/service/systems/express.js @@ -2510,6 +2510,9 @@ class ExpressService extends Service { step: { [Op.in]: [ 1, 2, 3, 4 ], }, + status: { + [Op.ne]: 'cancel', + }, }, attributes: [ 'id', 'sys_platform_code', 'logistics_code', 'sys_platform_name', 'logistics_name', 'store_id', 'pay_no', 'from_key' ], raw: true, @@ -2531,6 +2534,9 @@ class ExpressService extends Service { step: { [Op.in]: [ 4 ], }, + status: { + [Op.ne]: 'cancel', + }, }, attributes: [ 'id', 'sys_platform_code', 'logistics_code', 'sys_platform_name', 'logistics_name', 'store_id', 'pay_no', 'from_key' ], raw: true, @@ -3025,10 +3031,33 @@ class ExpressService extends Service { }; } + // 跳过已取消订单:已取消订单不允许取号,且不标记异常、不写失败日志。 + const cancelledOrderIdSet = new Set( + allOrderDeliveryRows + .filter(row => String(row.status || '').trim() === 'cancel') + .map(row => Number(row.id)) + .filter(id => Number.isFinite(id) && id > 0) + ); + let effectivePendingOrders = pendingOrders; + if (cancelledOrderIdSet.size > 0) { + effectivePendingOrders = pendingOrders.filter(order => !cancelledOrderIdSet.has(Number(order.order_id))); + ctx.logger.info('[ExpressService.createWaybillCode] 跳过已取消订单取号', { + traceId, + skippedOrderIds: Array.from(cancelledOrderIdSet), + }); + } + + if (effectivePendingOrders.length === 0) { + return { + orders: [], + waybill_codes: [], + }; + } + const { relationGroupMap, missingOrderIds, - } = this.buildWaybillCreateRelationGroups(pendingOrders, allOrderDeliveryRows, currentWarehouseId); + } = this.buildWaybillCreateRelationGroups(effectivePendingOrders, allOrderDeliveryRows, currentWarehouseId); const relationWhereList = Array.from(relationGroupMap.values()).map(group => ({ store_id: group.store_id, @@ -3083,7 +3112,7 @@ class ExpressService extends Service { ctx.logger.warn('[ExpressService.createWaybillCode] 余额不足但允许超额分配: %s', balanceWarnings.join(';')); } - const successOrders = pendingOrders.filter(order => successOrderKeySet.has(`${order.order_id}:${order.business_key}`)); + const successOrders = effectivePendingOrders.filter(order => successOrderKeySet.has(`${order.order_id}:${order.business_key}`)); const existingRows = await orderExpressModel.findAll({ where: { [Op.or]: successOrders.map(order => ({ diff --git a/app/service/systems/order_storage_allocation.js b/app/service/systems/order_storage_allocation.js index b3baf4e..d4d7e14 100644 --- a/app/service/systems/order_storage_allocation.js +++ b/app/service/systems/order_storage_allocation.js @@ -4,6 +4,7 @@ const MainService = require('../main'); const STORAGE_STATUS_FIN = 'fin'; const STORAGE_STATUS_ERROR = 'error'; +const ORDER_STATUS_CANCEL = 'cancel'; const ORDER_STEP_EXCEPTION = 3; const ALLOCATION_LOG_SAMPLE_LIMIT = 20; @@ -613,6 +614,20 @@ class OrderStorageAllocationService extends MainService { continue; } + if (String(orderRow.status || '').trim() === ORDER_STATUS_CANCEL) { + skippedOrders.push({ + order_id: orderId, + status: 'skipped', + order_status: orderRow.status, + skipped_reason: 'order_cancelled', + }); + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 过滤订单结果', { + orderId, + skippedReason: 'order_cancelled', + }); + continue; + } + if (String(orderRow.storage_status || 'none') === STORAGE_STATUS_FIN) { skippedOrders.push({ order_id: orderId, diff --git a/test/app/service/systems/express.createWaybillCodePipeline.skipCancelled.test.js b/test/app/service/systems/express.createWaybillCodePipeline.skipCancelled.test.js new file mode 100644 index 0000000..864547e --- /dev/null +++ b/test/app/service/systems/express.createWaybillCodePipeline.skipCancelled.test.js @@ -0,0 +1,217 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const ExpressService = require('../../../../app/service/systems/express'); + +/** + * 创建 createWaybillCodePipeline 跳过取消订单的测试上下文。 + * 模拟数据库行为:current/dispatch 订单查询按 where(含 status != 'cancel')过滤。 + * + * @param {Object} [options={}] 测试覆盖配置。 + * @return {{ ctx: Object, calls: Object }} 测试上下文与调用记录。 + */ +function createPipelineSkipCancelledHarness(options = {}) { + const calls = { + orderDeliveryFindAllQueries: [], + dispatchFindAllQueries: [], + asyncTaskPayloads: [], + }; + + const orderDeliveryRows = Array.isArray(options.orderDeliveryRows) ? options.orderDeliveryRows : []; + const dispatchRows = Array.isArray(options.dispatchRows) ? options.dispatchRows : []; + + const matchWhere = (row, where = {}) => { + const idValues = Array.isArray(where.id) + ? where.id + : (where.id && Array.isArray(where.id.in) ? where.id.in : []); + if (idValues.length > 0 && !idValues.includes(Number(row.id))) { + return false; + } + const stepValues = Array.isArray(where.step) + ? where.step + : (where.step && Array.isArray(where.step.in) ? where.step.in : []); + if (stepValues.length > 0 && !stepValues.includes(Number(row.step))) { + return false; + } + const excludedStatus = where.status && where.status.ne ? String(where.status.ne).trim() : ''; + if (excludedStatus && String(row.status || '').trim() === excludedStatus) { + return false; + } + return true; + }; + + const ctx = { + app: { + Sequelize: { + Op: { + in: 'in', + ne: 'ne', + }, + }, + }, + user: { + store_id: 100000, + }, + model: { + OrderDeliveryFactory: { + async getCurrentModel() { + return { + async findAll(query = {}) { + calls.orderDeliveryFindAllQueries.push(query); + return orderDeliveryRows.filter(row => matchWhere(row, query.where)).map(row => ({ ...row })); + }, + async update() { + return [ 1 ]; + }, + }; + }, + async getDispatchModel() { + return { + async findAll(query = {}) { + calls.dispatchFindAllQueries.push(query); + return dispatchRows.filter(row => matchWhere(row, query.where)).map(row => ({ ...row })); + }, + }; + }, + }, + PrintPlatform: { + async findAll() { + return [ + { + id: 901, + platform_code: 'PDD_PRINT', + request_platform_code: 'OPEN_API', + }, + ]; + }, + }, + }, + service: { + systems: { + platform: { + async getPlatformList() { + return [ + { + code: 'PDD', + print_platform_id: 901, + default_express_interface: 'POLYAPI', + }, + ]; + }, + }, + setting: { + expressInterface: { + async listByWarehousePlatformCode() { + return { + data: [ + { + id: 22, + sys_express_code: 'SF', + express_code: 'SF', + }, + ], + }; + }, + }, + }, + }, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + }; + + return { + ctx, + calls, + }; +} + +describe('test/app/service/systems/express.createWaybillCodePipeline.skipCancelled.test.js', () => { + it('should exclude cancelled orders via status filter in current and dispatch queries', async () => { + const { ctx, calls } = createPipelineSkipCancelledHarness({ + orderDeliveryRows: [ + { + id: 1, + warehouse_id: 100000, + status: 'cancel', + step: 4, + sys_platform_code: 'PDD', + logistics_code: 'SF', + sys_platform_name: '拼多多', + logistics_name: '顺丰', + store_id: 100000, + }, + { + id: 2, + warehouse_id: 100000, + status: 'created', + step: 2, + sys_platform_code: 'PDD', + logistics_code: 'SF', + sys_platform_name: '拼多多', + logistics_name: '顺丰', + store_id: 100000, + }, + ], + }); + const service = new ExpressService(ctx); + service.asyncTask = (batch, options, matchedPlatform, expressInterfaceConfig) => { + calls.asyncTaskPayloads.push({ batch, options, matchedPlatform, expressInterfaceConfig }); + }; + + const result = await service.createWaybillCodePipeline([ + { order_id: 1, business_key: 1 }, + { order_id: 2, business_key: 1 }, + ]); + + assert.deepEqual(result, { message: '分配快递任务已提交' }); + + // current 表查询必须携带 status != 'cancel' 过滤 + const currentQuery = calls.orderDeliveryFindAllQueries[0]; + assert.deepEqual(currentQuery.where.status, { ne: 'cancel' }); + assert.deepEqual(currentQuery.where.step, { in: [ 1, 2, 3, 4 ] }); + + // dispatch 补查同样必须携带 status != 'cancel' 过滤 + assert.equal(calls.dispatchFindAllQueries.length, 1); + assert.deepEqual(calls.dispatchFindAllQueries[0].where.status, { ne: 'cancel' }); + + // 只有正常订单进入取号任务批次,取消订单被跳过 + assert.equal(calls.asyncTaskPayloads.length, 1); + assert.deepEqual( + calls.asyncTaskPayloads[0].batch.map(order => Number(order.id)), + [ 2 ] + ); + }); + + it('should not submit any waybill task when all orders are cancelled', async () => { + const { ctx, calls } = createPipelineSkipCancelledHarness({ + orderDeliveryRows: [ + { + id: 1, + warehouse_id: 100000, + status: 'cancel', + step: 4, + sys_platform_code: 'PDD', + logistics_code: 'SF', + sys_platform_name: '拼多多', + logistics_name: '顺丰', + store_id: 100000, + }, + ], + }); + const service = new ExpressService(ctx); + service.asyncTask = (batch, options, matchedPlatform, expressInterfaceConfig) => { + calls.asyncTaskPayloads.push({ batch, options, matchedPlatform, expressInterfaceConfig }); + }; + + const result = await service.createWaybillCodePipeline([ + { order_id: 1, business_key: 1 }, + ]); + + assert.deepEqual(result, { message: '所有订单均已分配运单号,无需处理' }); + assert.equal(calls.asyncTaskPayloads.length, 0); + }); +}); diff --git a/test/app/service/systems/order_storage_allocation.test.js b/test/app/service/systems/order_storage_allocation.test.js index 6a8d929..720c13c 100644 --- a/test/app/service/systems/order_storage_allocation.test.js +++ b/test/app/service/systems/order_storage_allocation.test.js @@ -540,6 +540,64 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => { assert.equal(orders[1].storage_status, 'fin'); }); + it('should skip cancelled orders when allocating storage', async () => { + const { service, captures, orders } = createHarness({ + orders: [ + { id: 31, warehouse_id: 100000, storage_status: 'none', order_flag: '', step: 4, status: 'cancel' }, + { id: 32, warehouse_id: 100000, storage_status: 'fin', order_flag: '', step: 4, status: 'cancel' }, + { id: 33, warehouse_id: 100000, storage_status: 'none', order_flag: '', step: 2, status: 'created' }, + ], + orderItems: [ + { id: 331, order_id: 33, stock_id: 3311, plan_qty: 1, order_line_no: '1' }, + ], + stockRows: [ + { id: 3311, item_code: 'SKU-3311', item_name: '测试商品3311', warehouse_id: 100000, deleted_at: null, is_valid: 'Y', locked_quantity: 0 }, + ], + storageRows: [ + { + id: 33301, + warehouse_id: 100000, + stock_id: 3311, + is_enabled: 1, + delete_at: null, + available_quantity: 1, + quantity: 1, + locked_quantity: 0, + production_date: null, + inbound_time: '2026-04-15 08:00:00', + space_id: 3501, + space: { + id: 3501, + space_code: 'ST-331', + custom_name: '存储位331', + is_preferred_pick: false, + locationType: { + id: 1, + allow_allocation: 1, + is_active: 1, + }, + }, + }, + ], + }); + + const result = await service.allocateStorage({ + allow_storage_location: true, + order_ids: [ 31, 32, 33 ], + }); + + assert.equal(result.code, 200); + assert.deepEqual(result.data.pending_order_ids, [ 33 ]); + assert.deepEqual(result.data.allocated_order_ids, [ 33 ]); + + const cancelledSkips = result.data.skipped_orders.filter(item => item.skipped_reason === 'order_cancelled'); + assert.equal(cancelledSkips.length, 2); + assert.deepEqual(cancelledSkips.map(item => item.order_id), [ 31, 32 ]); + assert.equal(captures.pickingRows.length, 1); + assert.equal(captures.pickingRows[0].order_id, 33); + assert.equal(orders[2].storage_status, 'fin'); + }); + it('should group syncable orders by create_channel and mark them pending sync', async () => { const { service, captures } = createHarness({ orders: [ From a8200a3a35fb9468e25bc435807ca643c07b07f6 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 17 Aug 2026 21:58:43 +0800 Subject: [PATCH 221/550] =?UTF-8?q?feat(order):=20=E8=AE=A2=E5=8D=95?= =?UTF-8?q?=E6=8B=A6=E6=88=AA=E5=85=A8=E9=93=BE=E8=B7=AF=E9=98=BB=E6=96=AD?= =?UTF-8?q?=E4=B8=8E=E4=BD=9C=E4=B8=9A=E6=8E=92=E9=99=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 app/lib/intercept_guard 共享守卫:除 none 外所有拦截状态一律视为已拦截 - 分配波次(singleFetchByIds)/抓取波次(createWavePickTask) 排除拦截订单并回传清单 - 分配储位(allocatePicking)/分配快递(createWaybillCodePipeline、batchAllocateExpress) 跳过拦截订单并回报 - 打印组装(getWavePlatformPrintData/getOrderPrintData/getPrintDataByWaybillCodes) 剔除拦截订单,打印回写/波次反查/标记均排除 - 拣货完成(wavePickTaskComplete) 拦截报错;复核(assertOrderCanRecheck/批量快捷复核) 补全拦截状态 - 打包/称重(workbench、order.updateExpressWeighingWeight) 拦截阻断,波次批量操作排除拦截单 - 绑定包材(order_express) 拦截阻断,波次批量绑定排除拦截单 --- app/lib/intercept_guard.js | 31 +++++ app/service/systemMethods/order/base.js | 31 +++++ .../systemMethods/order/pendingOrder.js | 17 ++- .../systemMethods/order/recheckOrder.js | 33 +---- app/service/systemMethods/order/wave.js | 44 ++++++- app/service/systemMethods/pick.js | 30 ++++- app/service/systemMethods/print.js | 3 + app/service/systems/express.js | 33 ++++- app/service/systems/order_express.js | 111 ++++++++++++++++- app/service/systems/order_print.js | 114 ++++++++++++++++-- app/service/systems/order_review.js | 4 +- .../systems/order_storage_allocation.js | 17 +++ app/service/systems/pick.js | 31 +++++ app/service/systems/workbench.js | 32 ++++- 14 files changed, 462 insertions(+), 69 deletions(-) create mode 100644 app/lib/intercept_guard.js diff --git a/app/lib/intercept_guard.js b/app/lib/intercept_guard.js new file mode 100644 index 0000000..7b0691f --- /dev/null +++ b/app/lib/intercept_guard.js @@ -0,0 +1,31 @@ +'use strict'; + +/** + * 订单拦截状态共享定义。 + * + * wms_order_delivery.intercept_status 枚举(order_delivery.js / order_delivery_factory.js)实际取值为: + * none / requesting / requested / intercepting / intercepted_in_transit / intercepted_at_warehouse / + * returning / returned / delivered_by_mistake / timeout / cancelled / failed / exception。 + * + * 业务约定:拦截状态只要不是 'none'(即任意进入拦截流程/拦截结果的状态),一律视为"已拦截", + * 禁止继续执行仓储作业(分配波次/分配储位/分配快递/打印/抓取波次/拣货/复核/打包/称重/绑定包材等), + * 被拦截订单一律跳过。 + */ +const INTERCEPT_STATUS_NONE = 'none'; + +/** + * 判断订单拦截状态是否属于"已拦截"。 + * 空值/NULL 归一化为 none 处理;除此之外任何非 none 状态(含 requested/intercepting/intercepted_*、 + * returning/returned/cancelled/failed/exception 等)均视为已拦截。 + * @param {*} status 拦截状态值。 + * @return {boolean} 是否已拦截。 + */ +function isInterceptedOrderStatus(status) { + const normalizedStatus = String(status || '').trim() || INTERCEPT_STATUS_NONE; + return normalizedStatus !== INTERCEPT_STATUS_NONE; +} + +module.exports = { + INTERCEPT_STATUS_NONE, + isInterceptedOrderStatus, +}; diff --git a/app/service/systemMethods/order/base.js b/app/service/systemMethods/order/base.js index 047bc41..8353f85 100644 --- a/app/service/systemMethods/order/base.js +++ b/app/service/systemMethods/order/base.js @@ -2,6 +2,7 @@ const MainService = require('../../main'); const { parseWhereConditions } = require('../../../lib/query_condition_parser'); +const { isInterceptedOrderStatus } = require('../../../lib/intercept_guard'); const DEFAULT_PAGE_SIZE = 20; const MAX_PAGE_SIZE = 500; @@ -194,6 +195,36 @@ class OrderBaseService extends MainService { return `${chars[0]}***${chars[chars.length - 1]}`; } + /** + * 判断订单拦截状态是否属于"已进入拦截流程"的状态。 + * + * requested/requesting/intercepting 为拦截发起中,intercepted_in_transit 为途中拦截成功, + * intercepted_at_warehouse 为仓库拦截成功;intercepted 为历史遗留值,一并兼容。 + * + * @param {*} status 拦截状态值。 + * @return {boolean} 是否已进入拦截流程。 + */ + isInterceptedOrderStatus(status = '') { + return isInterceptedOrderStatus(status); + } + + /** + * 断言订单未进入拦截流程,否则抛出阻断异常。 + * + * @param {Object} orderRow 订单行(需含 intercept_status 字段)。 + * @param {string} [actionText='继续作业'] 被阻断的作业文案。 + * @return {void} 无返回值。 + */ + assertOrderNotIntercepted(orderRow = {}, actionText = '继续作业') { + if (!this.isPlainObject(orderRow)) { + return; + } + + if (this.isInterceptedOrderStatus(orderRow.intercept_status)) { + throw new Error(`订单已被拦截,无法${actionText}`); + } + } + /** * 获取当前请求对应的仓库ID。 * @return {number|string|null} 仓库ID。 diff --git a/app/service/systemMethods/order/pendingOrder.js b/app/service/systemMethods/order/pendingOrder.js index 2616a3e..01ed154 100644 --- a/app/service/systemMethods/order/pendingOrder.js +++ b/app/service/systemMethods/order/pendingOrder.js @@ -1205,8 +1205,14 @@ class PendingOrderService extends OrderBaseService { 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 skippedList = Array.isArray(resultData.skipped_orders) ? resultData.skipped_orders : []; const allocatedSet = new Set(allocatedIds.map(Number)); const shortageSet = new Set(shortageIds.map(Number)); + const skippedMap = new Map( + skippedList + .filter(item => Number(item && item.order_id) > 0) + .map(item => [ Number(item.order_id), item ]) + ); if (orderIds.length > 0 && this.ctx.model && this.ctx.model.OperationLog) { const operatorInfo = operator || {}; @@ -1218,16 +1224,23 @@ class PendingOrderService extends OrderBaseService { const oid = Number(orderId); const allocated = allocatedSet.has(oid); const shortage = shortageSet.has(oid); + const skippedItem = skippedMap.get(oid) || null; + const skippedReason = skippedItem ? String(skippedItem.skipped_reason || '').trim() : ''; + const skippedMessage = skippedReason === 'intercepted' + ? '储位分配跳过:订单已拦截' + : (skippedReason ? `储位分配跳过:${skippedReason}` : ''); const operationCode = allocated ? 'ORDER_STORAGE_ALLOCATE_SUCCESS' : shortage ? 'ORDER_STORAGE_ALLOCATE_FAILED' - : 'ORDER_STORAGE_ALLOCATE_SUCCESS'; + : skippedItem + ? 'ORDER_STORAGE_ALLOCATE_FAILED' + : 'ORDER_STORAGE_ALLOCATE_SUCCESS'; const msg = allocated ? '储位分配成功' : shortage ? '储位分配失败:库存不足' - : '储位分配完成'; + : skippedMessage || '储位分配完成'; return { business_type: 'order', business_id: String(oid), diff --git a/app/service/systemMethods/order/recheckOrder.js b/app/service/systemMethods/order/recheckOrder.js index dd8efbd..c88fb76 100644 --- a/app/service/systemMethods/order/recheckOrder.js +++ b/app/service/systemMethods/order/recheckOrder.js @@ -671,28 +671,6 @@ class RecheckOrderService extends OrderBaseService { }; } - /** - * 判断订单拦截状态是否属于"已进入拦截流程"的状态。 - * 拦截状态枚举(wms_order_delivery.intercept_status)实际取值为: - * none / requesting / requested / intercepting / intercepted_in_transit / intercepted_at_warehouse / - * returning / returned / delivered_by_mistake / timeout / cancelled / failed / exception。 - * 其中 requested/requesting/intercepting 为拦截发起中,intercepted_in_transit 为途中拦截成功, - * intercepted_at_warehouse 为仓库拦截成功;intercepted 为历史遗留值,一并兼容。 - * @param {string} status 拦截状态。 - * @return {boolean} 是否为拦截流程状态。 - */ - isInterceptedOrderStatus(status = '') { - const normalizedStatus = String(status || '').trim(); - return [ - 'intercepted', - 'requested', - 'requesting', - 'intercepting', - 'intercepted_in_transit', - 'intercepted_at_warehouse', - ].includes(normalizedStatus); - } - /** * 构建团购波次列表视图(团单模式)。 * 根据拣货任务ID查找关联的所有波次,每个波次展开为一项。 @@ -3201,8 +3179,7 @@ class RecheckOrderService extends OrderBaseService { if (String(order.pick_status || '') === 'none') { throw new Error('订单未拣货,不允许复核。'); } - const interceptStatus = String(order.intercept_status || '').trim(); - if (interceptStatus === 'intercepted' || interceptStatus === 'intercepted_at_warehouse') { + if (this.isInterceptedOrderStatus(order.intercept_status)) { throw new Error('订单已被拦截,无法提交复核'); } } @@ -3926,7 +3903,7 @@ class RecheckOrderService extends OrderBaseService { * 1. 未分配储位:storage_status 不等于 'fin' * 2. 未分配快递:post_status 不等于 'fin' * 3. 未同步:status 不等于 'created' - * 4. 已拦截:intercept_status 为 'intercepted' 或 'intercepted_at_warehouse' + * 4. 已拦截:intercept_status 处于拦截流程状态(requested/requesting/intercepting/intercepted_in_transit/intercepted_at_warehouse,历史值 intercepted 兼容) * * 核心流程(每个满足条件的订单在独立事务中执行): * 1. 若 pick_status 不等于 'fin',先完成拣货: @@ -3983,8 +3960,7 @@ class RecheckOrderService extends OrderBaseService { continue; } - const interceptStatus = String(order.intercept_status || '').trim(); - if (interceptStatus === 'intercepted' || interceptStatus === 'intercepted_at_warehouse') { + if (this.isInterceptedOrderStatus(order.intercept_status)) { failedOrders.push({ order_id: orderId, delivery_order_code: String(order.delivery_order_code || order.pre_delivery_order_code || '').trim(), @@ -4172,8 +4148,7 @@ class RecheckOrderService extends OrderBaseService { for (const order of waveOrders) { const orderId = Number(order.id); - const interceptStatus = String(order.intercept_status || '').trim(); - if (interceptStatus === 'intercepted' || interceptStatus === 'intercepted_at_warehouse') { + if (this.isInterceptedOrderStatus(order.intercept_status)) { allFailedOrders.push({ order_id: orderId, wave_id: waveId, diff --git a/app/service/systemMethods/order/wave.js b/app/service/systemMethods/order/wave.js index 2387d81..0f2e84b 100644 --- a/app/service/systemMethods/order/wave.js +++ b/app/service/systemMethods/order/wave.js @@ -6800,7 +6800,7 @@ class WaveService extends OrderBaseService { try { const orderRows = await orderModel.findAll({ - attributes: [ 'id', 'wave_id', 'wave_no', 'step', 'status', 'outbound_status', 'items_hash', 'items', 'logistics_name' ], + attributes: [ 'id', 'wave_id', 'wave_no', 'step', 'status', 'outbound_status', 'items_hash', 'items', 'logistics_name', 'intercept_status' ], where: { id: { [Op.in]: normalizedIds }, }, @@ -6819,6 +6819,11 @@ class WaveService extends OrderBaseService { .map(row => Number(row && row.id || 0)) .filter(id => Number.isInteger(id) && id > 0)) ] .sort((a, b) => a - b); + const excludedInterceptedOrderIds = [ ...new Set(normalizedOrderRows + .filter(row => this.isInterceptedOrderStatus(row && row.intercept_status)) + .map(row => Number(row && row.id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ] + .sort((a, b) => a - b); const fetchableRows = normalizedOrderRows.filter(row => { const orderId = Number(row && row.id || 0); @@ -6832,6 +6837,11 @@ class WaveService extends OrderBaseService { return false; } + // 拦截流程中的订单不允许分配波次 + if (this.isInterceptedOrderStatus(row && row.intercept_status)) { + return false; + } + return true; }); @@ -6851,6 +6861,7 @@ class WaveService extends OrderBaseService { fetched_order_ids: [], fetched_order_count: 0, excluded_existing_wave_order_ids: excludedExistingWaveOrderIds, + excluded_intercepted_order_ids: excludedInterceptedOrderIds, skipped_order_ids: skippedOrderIds, not_found_order_ids: notFoundOrderIds, }); @@ -6964,6 +6975,7 @@ class WaveService extends OrderBaseService { fetched_order_ids: grabbedOrderIds, fetched_order_count: grabbedOrderIds.length, excluded_existing_wave_order_ids: excludedExistingWaveOrderIds, + excluded_intercepted_order_ids: excludedInterceptedOrderIds, skipped_order_ids: skippedOrderIds, not_found_order_ids: notFoundOrderIds, }); @@ -8792,7 +8804,7 @@ class WaveService extends OrderBaseService { try { orderRows = await orderModel.findAll({ - attributes: [ 'id', 'business_key' ], + attributes: [ 'id', 'business_key', 'intercept_status' ], where: baseOrderWhere, raw: true, }); @@ -8808,7 +8820,7 @@ class WaveService extends OrderBaseService { warehouseId, }); orderRows = await orderModel.findAll({ - attributes: [ 'id' ], + attributes: [ 'id', 'intercept_status' ], where: baseOrderWhere, raw: true, }); @@ -8823,10 +8835,25 @@ class WaveService extends OrderBaseService { matchedOrderCount: Array.isArray(orderRows) ? orderRows.length : 0, }); + const skippedInterceptedOrderIds = [ ...new Set((Array.isArray(orderRows) ? orderRows : []) + .filter(row => this.isInterceptedOrderStatus(row && row.intercept_status)) + .map(row => Number(row && row.id || 0)) + .filter(orderId => Number.isInteger(orderId) && orderId > 0)) ] + .sort((a, b) => a - b); + const skippedInterceptedOrderIdSet = new Set(skippedInterceptedOrderIds); + if (skippedInterceptedOrderIds.length > 0) { + this.ctx.logger.info('[wave.batchAllocateExpress] 跳过拦截订单', { + traceId, + taskId: normalizedTaskId, + warehouseId, + skippedInterceptedOrderIds, + }); + } + const normalizedOrders = (Array.isArray(orderRows) ? orderRows : []) .map(row => { const orderId = Number(row && row.id || 0); - if (!Number.isInteger(orderId) || orderId <= 0) { + if (!Number.isInteger(orderId) || orderId <= 0 || skippedInterceptedOrderIdSet.has(orderId)) { return null; } @@ -8844,6 +8871,7 @@ class WaveService extends OrderBaseService { taskId: normalizedTaskId, warehouseId, waveIds, + skippedInterceptedOrderIds, }); const durationMs = Date.now() - startTime; await this.setBatchAllocateExpressTaskProgress(normalizedTaskId, 'success', { @@ -8853,14 +8881,18 @@ class WaveService extends OrderBaseService { processed_order_count: 0, success_order_count: 0, failed_order_count: 0, + skipped_intercepted_order_ids: skippedInterceptedOrderIds, progress_percent: 100, end_time: Date.now(), duration_ms: durationMs, result: { wave_ids: waveIds, allocated_order_count: 0, + skipped_intercepted_order_ids: skippedInterceptedOrderIds, duration_ms: durationMs, - message: '未找到可分配快递号的订单', + message: skippedInterceptedOrderIds.length > 0 + ? `拦截订单已跳过,未找到可分配快递号的订单(跳过 ${skippedInterceptedOrderIds.length} 单)` + : '未找到可分配快递号的订单', }, trace_id: traceId, }); @@ -8902,12 +8934,14 @@ class WaveService extends OrderBaseService { processed_order_count: normalizedOrders.length, success_order_count: normalizedOrders.length, failed_order_count: 0, + skipped_intercepted_order_ids: skippedInterceptedOrderIds, progress_percent: 100, end_time: Date.now(), duration_ms: durationMs, result: { wave_ids: waveIds, allocated_order_count: normalizedOrders.length, + skipped_intercepted_order_ids: skippedInterceptedOrderIds, duration_ms: durationMs, message: String(pipelineResult && pipelineResult.message || '分配快递任务已提交').trim(), }, diff --git a/app/service/systemMethods/pick.js b/app/service/systemMethods/pick.js index 8f402ef..362fc2b 100644 --- a/app/service/systemMethods/pick.js +++ b/app/service/systemMethods/pick.js @@ -1,6 +1,7 @@ 'use strict'; const MainService = require('../main'); +const { isInterceptedOrderStatus } = require('../../lib/intercept_guard'); class PickService extends MainService { /** @@ -132,9 +133,26 @@ class PickService extends MainService { [this.app.Sequelize.Op.in]: normalizedOrderIds, }, }, - attributes: [ 'id' ], + attributes: [ 'id', 'intercept_status' ], raw: true, }); + + // 拦截流程中的订单不允许抓取波次,直接剔除 + const interceptedOrderIds = new Set((Array.isArray(orderRows) ? orderRows : []) + .filter(row => isInterceptedOrderStatus(row && row.intercept_status)) + .map(row => Number(row && row.id || 0)) + .filter(id => Number.isInteger(id) && id > 0)); + if (interceptedOrderIds.size > 0) { + const excludedIds = normalizedOrderIds.filter(id => interceptedOrderIds.has(id)); + if (excludedIds.length > 0) { + ctx.logger.info('[pick.createWavePickTask] 剔除拦截订单: %s', excludedIds.join(',')); + } + } + const activeOrderIds = normalizedOrderIds.filter(id => !interceptedOrderIds.has(id)); + if (activeOrderIds.length <= 0) { + throw Object.assign(new Error('波次下订单均已被拦截,无法创建任务'), { code: 400 }); + } + const orderNoMap = new Map((Array.isArray(orderRows) ? orderRows : []) .map(row => [ Number(row && row.id || 0), '' ])); @@ -182,7 +200,7 @@ class PickService extends MainService { waveId, pickMode, source, - orderCount: normalizedOrderIds.length, + orderCount: activeOrderIds.length, operatorId, operatorName, remark, @@ -257,10 +275,10 @@ class PickService extends MainService { } ); - if (normalizedOrderIds.length > 0) { + if (activeOrderIds.length > 0) { // 按库位排序并按 stock_id 分组,同 stock_id 的订单共享同一篮号 const stockGroups = await this.resolveLocationSortedOrderIds( - normalizedOrderIds, + activeOrderIds, warehouseId, transaction ); @@ -418,7 +436,7 @@ class PickService extends MainService { && this.ctx.service.systems && this.ctx.service.systems.operationLog; if (operationLogService && typeof operationLogService.createOperationLogs === 'function') { - const logPayloads = normalizedOrderIds.map(orderId => ({ + const logPayloads = activeOrderIds.map(orderId => ({ businessType: 'order', businessId: `${orderId}`, operationCode: 'ORDER_WAVE_GRAB', @@ -437,7 +455,7 @@ class PickService extends MainService { } catch (e) { ctx.logger.warn('[pick.createWavePickTask] 写入 order_operation_log 失败,不影响主流程', { error: e && e.message, - normalizedOrderIds, + activeOrderIds, }); } diff --git a/app/service/systemMethods/print.js b/app/service/systemMethods/print.js index e0135f6..07e5149 100644 --- a/app/service/systemMethods/print.js +++ b/app/service/systemMethods/print.js @@ -348,6 +348,7 @@ class PrintService extends MainService { : { print_status: 'error' }; const where = { id: orderIds, + intercept_status: 'none', }; if (callbackResult === 'failed') { where.print_status = 'none'; @@ -1614,6 +1615,7 @@ class PrintService extends MainService { wave_id: waveId, warehouse_id: warehouseId, status: { [this.app.Sequelize.Op.ne]: 'cancel' }, + intercept_status: 'none', }, raw: true, }); @@ -1764,6 +1766,7 @@ class PrintService extends MainService { }, { where: { id: orderIds, + intercept_status: 'none', }, }); diff --git a/app/service/systems/express.js b/app/service/systems/express.js index b4a252d..2db92ef 100644 --- a/app/service/systems/express.js +++ b/app/service/systems/express.js @@ -2,6 +2,8 @@ const { Service } = require('egg'); +const { isInterceptedOrderStatus } = require('../../lib/intercept_guard'); + const DEFAULT_CACHE_TTL_SECONDS = 600; const DEFAULT_EXPRESS_PRODUCT_TYPE_CACHE_TTL_SECONDS = 60 * 60; const DEFAULT_WAYBILL_BATCH_SIZE = 10; @@ -2514,7 +2516,7 @@ class ExpressService extends Service { [Op.ne]: 'cancel', }, }, - attributes: [ 'id', 'sys_platform_code', 'logistics_code', 'sys_platform_name', 'logistics_name', 'store_id', 'pay_no', 'from_key' ], + attributes: [ 'id', 'sys_platform_code', 'logistics_code', 'sys_platform_name', 'logistics_name', 'store_id', 'pay_no', 'from_key', 'intercept_status' ], raw: true, }); @@ -2538,13 +2540,27 @@ class ExpressService extends Service { [Op.ne]: 'cancel', }, }, - attributes: [ 'id', 'sys_platform_code', 'logistics_code', 'sys_platform_name', 'logistics_name', 'store_id', 'pay_no', 'from_key' ], + attributes: [ 'id', 'sys_platform_code', 'logistics_code', 'sys_platform_name', 'logistics_name', 'store_id', 'pay_no', 'from_key', 'intercept_status' ], raw: true, }); } } - const orders_arr = [ ...(Array.isArray(currentOrders) ? currentOrders : []), ...dispatchOrders ]; + // 拦截订单跳过(除 none 外一律视为已拦截) + const mergedOrders = [ ...(Array.isArray(currentOrders) ? currentOrders : []), ...dispatchOrders ]; + const interceptedOrderIdSet = new Set(mergedOrders + .filter(order => isInterceptedOrderStatus(order && order.intercept_status)) + .map(order => Number(order && order.id || 0)) + .filter(orderId => Number.isInteger(orderId) && orderId > 0)); + const skippedInterceptedOrderIds = Array.from(interceptedOrderIdSet); + const orders_arr = mergedOrders.filter(order => !interceptedOrderIdSet.has(Number(order && order.id || 0))); + if (skippedInterceptedOrderIds.length > 0) { + this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 跳过拦截订单', { + traceId, + warehouseId, + skippedInterceptedOrderIds, + }); + } this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 订单筛选结果', { traceId, warehouseId, @@ -2552,6 +2568,7 @@ class ExpressService extends Service { currentCount: (Array.isArray(currentOrders) ? currentOrders : []).length, dispatchCount: dispatchOrders.length, matchedOrderCount: orders_arr.length, + skippedInterceptedOrderIds, }); // 【step1.5】过滤已分配运单号(status=1)且传入 business_key=1 的订单,避免重复分配。 @@ -2600,7 +2617,10 @@ class ExpressService extends Service { if (filteredOrdersArr.length === 0) { this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 所有订单均已分配运单号,无需处理', { traceId }); - return { message: '所有订单均已分配运单号,无需处理' }; + return { + message: '所有订单均已分配运单号,无需处理', + skipped_intercepted_order_ids: skippedInterceptedOrderIds, + }; } // orders_arr和orderList合并:同一 order_id 在 orderList 中可能有多条(不同 business_key), @@ -2702,7 +2722,10 @@ class ExpressService extends Service { traceId, groupedCount: groupedOrders.length, }); - return { message: '分配快递任务已提交' }; + return { + message: '分配快递任务已提交', + skipped_intercepted_order_ids: skippedInterceptedOrderIds, + }; } /** * 异步执行订单快递分配任务。错误订单转异常,并记录失败订单列表。 diff --git a/app/service/systems/order_express.js b/app/service/systems/order_express.js index f6cd0a9..4649e7c 100644 --- a/app/service/systems/order_express.js +++ b/app/service/systems/order_express.js @@ -2,6 +2,8 @@ const Service = require('egg').Service; +const { isInterceptedOrderStatus } = require('../../lib/intercept_guard'); + /** * 订单快递业务服务。 * @@ -196,6 +198,55 @@ class OrderExpressService extends Service { return orderExpressRow; } + /** + * 查询订单拦截状态(依次查询 current → dispatch 分表)。 + * @param {number} orderId 订单 ID。 + * @param {number} warehouseId 仓库 ID。 + * @return {Promise} 拦截状态,查询失败时返回 'none'。 + */ + async findOrderInterceptStatus(orderId, warehouseId) { + const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; + if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') { + return 'none'; + } + + const tableOrders = [ + { label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) }, + { label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) }, + ]; + + for (const entry of tableOrders) { + try { + const model = await entry.getModel(); + if (!model || typeof model.findOne !== 'function') continue; + const row = await model.findOne({ + where: { id: orderId, warehouse_id: warehouseId }, + attributes: [ 'id', 'intercept_status' ], + raw: true, + }); + if (row) { + return String(row.intercept_status || '').trim() || 'none'; + } + } catch (_err) { continue; } + } + + return 'none'; + } + + /** + * 断言订单未进入拦截流程,否则抛出业务异常。 + * @param {number} orderId 订单 ID。 + * @param {number} warehouseId 仓库 ID。 + * @param {string} [actionText='继续作业'] 被阻断的作业文案。 + * @return {Promise} 无返回值。 + */ + async assertOrderNotIntercepted(orderId, warehouseId, actionText = '继续作业') { + const interceptStatus = await this.findOrderInterceptStatus(orderId, warehouseId); + if (isInterceptedOrderStatus(interceptStatus)) { + throw this.createBusinessError(`订单已被拦截,无法${actionText}`, 400); + } + } + /** * 规范化并校验称重重量。 * @@ -306,6 +357,9 @@ class OrderExpressService extends Service { throw this.createBusinessError('运单号不存在', 404); } + // 拦截流程中的订单不允许称重 + await this.assertOrderNotIntercepted(normalizedOrderId, warehouseId, '称重'); + // 依次查询多个订单表获取波次信息:current → history → dispatch const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') { @@ -438,6 +492,9 @@ class OrderExpressService extends Service { const orderId = Number(expressRow.order_id || 0); + // 拦截流程中的订单不允许称重 + await this.assertOrderNotIntercepted(orderId, warehouseId, '称重'); + // 依次查询多个订单表获取波次信息:current → history → dispatch const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') { @@ -546,7 +603,7 @@ class OrderExpressService extends Service { // 查询波次下所有订单 const waveOrders = await orderDeliveryModel.findAll({ where: { wave_id: waveId, warehouse_id: warehouseId }, - attributes: [ 'id' ], + attributes: [ 'id', 'intercept_status' ], raw: true, }); @@ -554,7 +611,18 @@ class OrderExpressService extends Service { throw this.createBusinessError('波次下未找到订单', 404); } - const orderIds = waveOrders.map(o => Number(o.id)); + // 波次内拦截订单不参与批量称重 + const interceptedWaveOrderIds = (Array.isArray(waveOrders) ? waveOrders : []) + .filter(o => isInterceptedOrderStatus(o && o.intercept_status)) + .map(o => Number(o.id)); + const orderIds = (Array.isArray(waveOrders) ? waveOrders : []) + .filter(o => !isInterceptedOrderStatus(o && o.intercept_status)) + .map(o => Number(o.id)); + if (interceptedWaveOrderIds.length > 0) { + this.ctx.logger.info( + `[order_express._updateWaveAllOrdersWeight] 波次内拦截订单不参与称重: ${interceptedWaveOrderIds.join(',')}` + ); + } // 批量更新波次下全部运单的称重重量 const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; @@ -880,7 +948,7 @@ class OrderExpressService extends Service { // 查询波次下所有订单 const waveOrders = await orderDeliveryModel.findAll({ where: { wave_id: waveId, warehouse_id: warehouseId }, - attributes: [ 'id' ], + attributes: [ 'id', 'intercept_status' ], raw: true, }); @@ -888,7 +956,18 @@ class OrderExpressService extends Service { throw this.createBusinessError('波次下未找到订单', 404); } - const orderIds = waveOrders.map(o => Number(o.id)); + // 波次内拦截订单不参与批量称重 + const interceptedWaveOrderIds = (Array.isArray(waveOrders) ? waveOrders : []) + .filter(o => isInterceptedOrderStatus(o && o.intercept_status)) + .map(o => Number(o.id)); + const orderIds = (Array.isArray(waveOrders) ? waveOrders : []) + .filter(o => !isInterceptedOrderStatus(o && o.intercept_status)) + .map(o => Number(o.id)); + if (interceptedWaveOrderIds.length > 0) { + this.ctx.logger.info( + `[order_express._updateWaveOrderWeight] 波次内拦截订单不参与称重: ${interceptedWaveOrderIds.join(',')}` + ); + } const totalCount = orderIds.length; // 批量更新所有订单的运单称重重量 @@ -1295,6 +1374,9 @@ class OrderExpressService extends Service { const materialRow = await this.findActivePackageMaterialByCode(normalizedPackageMaterialCode, warehouseId); const orderExpressRow = await this.findValidOrderExpressByOrderAndWaybill(normalizedOrderId, normalizedWaybillCode, warehouseId); + // 拦截流程中的订单不允许绑定包材 + await this.assertOrderNotIntercepted(Number(orderExpressRow.order_id), warehouseId, '绑定包材'); + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; const updateResult = await orderExpressModel.update({ package_material_id: Number(materialRow.id), @@ -1383,6 +1465,9 @@ class OrderExpressService extends Service { throw this.createBusinessError('运单号不存在', 404); } + // 拦截流程中的订单不允许绑定包材 + await this.assertOrderNotIntercepted(Number(orderExpressRow.order_id), warehouseId, '绑定包材'); + // 查询启用中的包材 const materialRow = await this.findActivePackageMaterialById(normalizedPackageMaterialId, warehouseId); @@ -1581,21 +1666,35 @@ class OrderExpressService extends Service { ]; const orderIdSet = new Set(); + const excludedInterceptedOrderIds = []; for (const entry of tableOrders) { try { const model = await entry.getModel(); if (!model || typeof model.findAll !== 'function') continue; const rows = await model.findAll({ where: { wave_id: waveId, warehouse_id: warehouseId }, - attributes: [ 'id' ], + attributes: [ 'id', 'intercept_status' ], raw: true, }); if (Array.isArray(rows)) { - rows.forEach(r => orderIdSet.add(Number(r.id))); + rows.forEach(r => { + const orderId = Number(r.id); + if (isInterceptedOrderStatus(r && r.intercept_status)) { + excludedInterceptedOrderIds.push(orderId); + return; + } + orderIdSet.add(orderId); + }); } } catch (_err) { continue; } } + if (excludedInterceptedOrderIds.length > 0) { + this.ctx.logger.info( + `[bindExpressPackageMaterialByWaybill] 波次内拦截订单不参与批量绑定: ${excludedInterceptedOrderIds.join(',')}` + ); + } + if (orderIdSet.size === 0) { throw this.createBusinessError('波次下未找到订单', 404); } diff --git a/app/service/systems/order_print.js b/app/service/systems/order_print.js index 4ae1b69..96925d7 100644 --- a/app/service/systems/order_print.js +++ b/app/service/systems/order_print.js @@ -489,12 +489,15 @@ class OrderPrintSystemService extends OrderBaseService { total_platforms: 0, locked_count: 0, total_locked_orders: 0, + intercepted_count: 0, }, waveGroups: [], locked_wave_groups: [], wave_ids: [], locked_count: 0, locked_orders: [], + intercepted_count: 0, + intercepted_orders: [], ext: { missing_wave_ids: normalizedWaveIds, filtered_wave_ids: [], @@ -512,8 +515,24 @@ class OrderPrintSystemService extends OrderBaseService { } = this.filterFullyAssignedExpressWaves(hitWaveIds, orderRows); const validWaveIdSet = new Set(validWaveIds); const validOrderRows = orderRows.filter(order => validWaveIdSet.has(Number(order && order.wave_id || 0))); + const interceptedOrderRows = validOrderRows.filter( + orderRow => this.isInterceptedOrderStatus(orderRow && orderRow.intercept_status) + ); const lockedOrderRows = validOrderRows.filter(orderRow => this.isOrderLocked(orderRow)); - const unlockedOrderRows = validOrderRows.filter(orderRow => !this.isOrderLocked(orderRow)); + const unlockedOrderRows = validOrderRows.filter( + orderRow => !this.isOrderLocked(orderRow) + && !this.isInterceptedOrderStatus(orderRow && orderRow.intercept_status) + ); + const interceptedOrders = interceptedOrderRows + .map(orderRow => ({ + order_id: Number(orderRow && orderRow.id || 0), + order_no: String(orderRow && (orderRow.delivery_order_code || orderRow.source_order_codes) || '').trim(), + wave_id: Number(orderRow && orderRow.wave_id || 0), + wave_no: String(orderRow && orderRow.wave_no || '').trim(), + intercept_status: String(orderRow && orderRow.intercept_status || '').trim() || 'none', + status: 'intercepted', + status_text: '已拦截', + })); const lockedOrders = lockedOrderRows .map(orderRow => ({ order_id: Number(orderRow && orderRow.id || 0), @@ -553,12 +572,15 @@ class OrderPrintSystemService extends OrderBaseService { total_platforms: 0, locked_count: lockedOrders.length, total_locked_orders: lockedOrders.length, + intercepted_count: interceptedOrders.length, }, waveGroups: [], locked_wave_groups: lockedWaveGroups, wave_ids: validWaveIds, locked_count: lockedOrders.length, locked_orders: lockedOrders, + intercepted_count: interceptedOrders.length, + intercepted_orders: interceptedOrders, ext: { missing_wave_ids: missingWaveIds, filtered_wave_ids: filteredWaveIds, @@ -653,12 +675,15 @@ class OrderPrintSystemService extends OrderBaseService { total_platforms: totalPlatforms, locked_count: lockedOrders.length, total_locked_orders: lockedOrders.length, + intercepted_count: interceptedOrders.length, }, waveGroups, locked_wave_groups: lockedWaveGroups, wave_ids: validWaveIds, locked_count: lockedOrders.length, locked_orders: lockedOrders, + intercepted_count: interceptedOrders.length, + intercepted_orders: interceptedOrders, ext: { missing_wave_ids: missingWaveIds, filtered_wave_ids: filteredWaveIds, @@ -697,9 +722,12 @@ class OrderPrintSystemService extends OrderBaseService { total_waves: 0, total_orders: 0, total_platforms: 0, + intercepted_count: 0, }, waveGroups: [], wave_ids: [], + intercepted_count: 0, + intercepted_orders: [], ext: { missing_order_ids: normalizedOrderIds, filtered_order_ids: [], @@ -711,13 +739,33 @@ class OrderPrintSystemService extends OrderBaseService { const missingOrderIds = normalizedOrderIds.filter(orderId => !hitOrderIdSet.has(orderId)); // 订单级过滤:仅保留 post_status === 'fin' 的订单(等价于波次级的快递完全分配检查) - const validOrderRows = orderRows.filter(row => String(row && row.post_status || '').trim() === 'fin'); + const postFinOrderRows = orderRows.filter(row => String(row && row.post_status || '').trim() === 'fin'); + // 拦截订单从打印清单中剔除 + const interceptedOrderRows = postFinOrderRows.filter( + row => this.isInterceptedOrderStatus(row && row.intercept_status) + ); + const interceptedOrders = interceptedOrderRows.map(row => ({ + order_id: Number(row && row.id || 0), + order_no: String(row && (row.delivery_order_code || row.source_order_codes) || '').trim(), + wave_id: Number(row && row.wave_id || 0), + wave_no: String(row && row.wave_no || '').trim(), + intercept_status: String(row && row.intercept_status || '').trim() || 'none', + status: 'intercepted', + status_text: '已拦截', + })); + const validOrderRows = postFinOrderRows.filter( + row => !this.isInterceptedOrderStatus(row && row.intercept_status) + ); const filteredOrderIds = orderRows .filter(row => String(row && row.post_status || '').trim() !== 'fin') .map(row => ({ order_id: Number(row && row.id || 0), reason: '快递未完全分配', - })); + })) + .concat(interceptedOrderRows.map(row => ({ + order_id: Number(row && row.id || 0), + reason: '已拦截', + }))); if (validOrderRows.length === 0) { return { @@ -725,9 +773,12 @@ class OrderPrintSystemService extends OrderBaseService { total_waves: 0, total_orders: 0, total_platforms: 0, + intercepted_count: interceptedOrders.length, }, waveGroups: [], wave_ids: [], + intercepted_count: interceptedOrders.length, + intercepted_orders: interceptedOrders, ext: { missing_order_ids: missingOrderIds, filtered_order_ids: filteredOrderIds, @@ -826,9 +877,12 @@ class OrderPrintSystemService extends OrderBaseService { total_waves: waveGroups.length, total_orders: orderPrintList.length, total_platforms: totalPlatforms, + intercepted_count: interceptedOrders.length, }, waveGroups, wave_ids: validOrderWaveIds, + intercepted_count: interceptedOrders.length, + intercepted_orders: interceptedOrders, ext: { missing_order_ids: missingOrderIds, filtered_order_ids: filteredOrderIds, @@ -881,9 +935,16 @@ class OrderPrintSystemService extends OrderBaseService { const waybillRows = await this.queryWaybillsByCodes(normalizedWaybillCodes, normalizedWarehouseId); if (waybillRows.length === 0) { return { - summary: { total_waves: 0, total_orders: 0, total_platforms: 0 }, + summary: { + total_waves: 0, + total_orders: 0, + total_platforms: 0, + intercepted_count: 0, + }, waveGroups: [], wave_ids: [], + intercepted_count: 0, + intercepted_orders: [], ext: { missing_waybill_codes: normalizedWaybillCodes, filtered_waybill_codes: [], @@ -911,9 +972,16 @@ class OrderPrintSystemService extends OrderBaseService { if (validWaybillRows.length === 0) { return { - summary: { total_waves: 0, total_orders: 0, total_platforms: 0 }, + summary: { + total_waves: 0, + total_orders: 0, + total_platforms: 0, + intercepted_count: 0, + }, waveGroups: [], wave_ids: [], + intercepted_count: 0, + intercepted_orders: [], ext: { missing_waybill_codes: missingWaybillCodes, filtered_waybill_codes: invalidWaybillCodes, @@ -921,10 +989,24 @@ class OrderPrintSystemService extends OrderBaseService { }; } - // 3. 过滤 post_status !== 'fin' 的订单 + // 3. 过滤 post_status !== 'fin' 或进入拦截流程的订单 + const interceptedOrderRows = orderRows.filter( + row => this.isInterceptedOrderStatus(row && row.intercept_status) + ); + const interceptedOrderIdSet = new Set(interceptedOrderRows.map(row => Number(row.id))); + const interceptedOrders = interceptedOrderRows.map(row => ({ + order_id: Number(row && row.id || 0), + order_no: String(row && (row.delivery_order_code || row.source_order_codes) || '').trim(), + wave_id: Number(row && row.wave_id || 0), + wave_no: String(row && row.wave_no || '').trim(), + intercept_status: String(row && row.intercept_status || '').trim() || 'none', + status: 'intercepted', + status_text: '已拦截', + })); const validOrderIdSet = new Set( orderRows - .filter(row => String(row.post_status || '').trim() === 'fin') + .filter(row => String(row.post_status || '').trim() === 'fin' + && !this.isInterceptedOrderStatus(row && row.intercept_status)) .map(row => Number(row.id)) ); const finalWaybillRows = validWaybillRows.filter(row => validOrderIdSet.has(Number(row.order_id))); @@ -932,14 +1014,23 @@ class OrderPrintSystemService extends OrderBaseService { .filter(row => !validOrderIdSet.has(Number(row.order_id))) .map(row => ({ waybill_code: String(row.waybill_code || '').trim(), - reason: '关联订单快递未完全分配', + reason: interceptedOrderIdSet.has(Number(row.order_id)) + ? '关联订单已被拦截' + : '关联订单快递未完全分配', })); if (finalWaybillRows.length === 0) { return { - summary: { total_waves: 0, total_orders: 0, total_platforms: 0 }, + summary: { + total_waves: 0, + total_orders: 0, + total_platforms: 0, + intercepted_count: interceptedOrders.length, + }, waveGroups: [], wave_ids: [], + intercepted_count: interceptedOrders.length, + intercepted_orders: interceptedOrders, ext: { missing_waybill_codes: missingWaybillCodes, filtered_waybill_codes: [ ...invalidWaybillCodes, ...filteredWaybillCodes ], @@ -1079,9 +1170,12 @@ class OrderPrintSystemService extends OrderBaseService { total_waves: waveGroups.length, total_orders: orderPrintList.length, total_platforms: totalPlatforms, + intercepted_count: interceptedOrders.length, }, waveGroups, wave_ids: validOrderWaveIds, + intercepted_count: interceptedOrders.length, + intercepted_orders: interceptedOrders, ext: { missing_waybill_codes: missingWaybillCodes, filtered_waybill_codes: [ ...invalidWaybillCodes, ...filteredWaybillCodes ], @@ -1681,6 +1775,7 @@ class OrderPrintSystemService extends OrderBaseService { 'print_status', 'lock_status', 'print_lock_status', + 'intercept_status', 'items_count', 'items_total', 'items_weight', @@ -1746,6 +1841,7 @@ class OrderPrintSystemService extends OrderBaseService { 'print_status', 'lock_status', 'print_lock_status', + 'intercept_status', 'items_count', 'items_total', 'items_weight', diff --git a/app/service/systems/order_review.js b/app/service/systems/order_review.js index ed8f115..d5a6e96 100644 --- a/app/service/systems/order_review.js +++ b/app/service/systems/order_review.js @@ -44,12 +44,12 @@ class OrderReviewService extends OrderBaseService { } /** - * 判断是否为拦截状态。 + * 判断是否为拦截状态(除 none 外一律视为已拦截)。 * @param {string} interceptStatus 拦截状态。 * @return {boolean} 是否拦截。 */ isInterceptStatus(interceptStatus) { - return String(interceptStatus || '').trim() !== 'none'; + return this.isInterceptedOrderStatus(interceptStatus); } /** diff --git a/app/service/systems/order_storage_allocation.js b/app/service/systems/order_storage_allocation.js index d4d7e14..e3b921c 100644 --- a/app/service/systems/order_storage_allocation.js +++ b/app/service/systems/order_storage_allocation.js @@ -2,6 +2,8 @@ const MainService = require('../main'); +const { isInterceptedOrderStatus } = require('../../lib/intercept_guard'); + const STORAGE_STATUS_FIN = 'fin'; const STORAGE_STATUS_ERROR = 'error'; const ORDER_STATUS_CANCEL = 'cancel'; @@ -628,6 +630,21 @@ class OrderStorageAllocationService extends MainService { continue; } + if (isInterceptedOrderStatus(orderRow && orderRow.intercept_status)) { + skippedOrders.push({ + order_id: orderId, + status: 'skipped', + intercept_status: orderRow.intercept_status, + skipped_reason: 'intercepted', + }); + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 过滤订单结果', { + orderId, + interceptStatus: orderRow.intercept_status, + skippedReason: 'intercepted', + }); + continue; + } + if (String(orderRow.storage_status || 'none') === STORAGE_STATUS_FIN) { skippedOrders.push({ order_id: orderId, diff --git a/app/service/systems/pick.js b/app/service/systems/pick.js index 9592a60..fe48b7d 100644 --- a/app/service/systems/pick.js +++ b/app/service/systems/pick.js @@ -2,6 +2,8 @@ const Service = require('egg').Service; +const { INTERCEPT_STATUS_NONE } = require('../../lib/intercept_guard'); + const REVIEWED_INSPECTION_STATUS = 'fin'; const PICK_MODE_VIEW_META_MAP = { 1: { @@ -1945,6 +1947,35 @@ class PickSystemService extends Service { } } + // 检查目标订单是否进入拦截流程,拦截订单不允许完成拣货 + if (targetOrderIds.length > 0) { + const interceptCheckModel = await this.getOrderModel(warehouseId); + const interceptedOrderRows = await interceptCheckModel.findAll({ + where: { + warehouse_id: warehouseId, + id: { + [this.app.Sequelize.Op.in]: targetOrderIds, + }, + intercept_status: { + [this.app.Sequelize.Op.ne]: INTERCEPT_STATUS_NONE, + }, + }, + attributes: [ 'id', 'intercept_status' ], + raw: true, + transaction, + }); + + if (interceptedOrderRows && interceptedOrderRows.length > 0) { + const detailList = interceptedOrderRows.map( + orderRow => `订单${orderRow.id}(intercept_status=${orderRow.intercept_status})` + ).join(';'); + throw this.createBusinessError( + `以下订单已被拦截,无法完成拣货:${detailList}`, + 400 + ); + } + } + // 检查目标订单是否已分配储位(storage_status='fin'),防止订单在波次中被取消储位分配后仍然完成拣货 if (targetOrderIds.length > 0) { const orderModel = await this.getOrderModel(warehouseId); diff --git a/app/service/systems/workbench.js b/app/service/systems/workbench.js index ca9d985..c5b0bd9 100644 --- a/app/service/systems/workbench.js +++ b/app/service/systems/workbench.js @@ -2,6 +2,8 @@ const Service = require('egg').Service; +const { isInterceptedOrderStatus } = require('../../lib/intercept_guard'); + class WorkbenchService extends Service { /** * 查询工作台列表(仓库隔离 + 软删除过滤) @@ -474,6 +476,11 @@ class WorkbenchService extends Service { if (!orderRow) throw new Error(`未找到发货单 [${deliveryOrderCode}]`); + // 拦截流程中的订单不允许打包 + if (isInterceptedOrderStatus(orderRow.intercept_status)) { + throw new Error(`订单已被拦截,无法打包 [${deliveryOrderCode}]`); + } + const orderId = orderRow.id; const waveId = orderRow.wave_id || 0; const actualWaveNo = waveNo || orderRow.wave_no || ''; @@ -617,13 +624,13 @@ class WorkbenchService extends Service { } catch (_err) { continue; } } } else if (waveId > 0) { - // 团购:批量更新波次下所有订单 + // 团购:批量更新波次下所有订单(拦截订单不更新) for (const entry of tableOrders) { try { const model = await entry.getModel(); if (!model) continue; const affected = await model.update(orderUpdateData, { - where: { wave_id: waveId, warehouse_id: warehouseId }, + where: { wave_id: waveId, warehouse_id: warehouseId, intercept_status: 'none' }, }); if (affected[0] > 0) { ctx.logger.info('[Workbench._packOrder] 团购批量更新订单打包状态 waveId=%d pack_status=%s table=%s affected=%d', @@ -925,7 +932,7 @@ class WorkbenchService extends Service { if (!model || typeof model.findOne !== 'function') continue; const row = await model.findOne({ where: { id: orderId, warehouse_id: warehouseId }, - attributes: [ 'id', 'wave_id', 'wave_no', 'items_weight' ], + attributes: [ 'id', 'wave_id', 'wave_no', 'items_weight', 'intercept_status' ], raw: true, }); if (row) { @@ -943,6 +950,11 @@ class WorkbenchService extends Service { throw new Error(`未找到运单对应的订单 [id=${orderId}, warehouse=${warehouseId}]`); } + // 拦截流程中的订单不允许称重 + if (isInterceptedOrderStatus(orderRow.intercept_status)) { + throw new Error(`订单已被拦截,无法称重 [${normalizedBarcode}]`); + } + const waveId = Number(orderRow.wave_id || 0); // 步骤3:散单(wave_id=0)→ 仅更新该运单的称重重量 @@ -1014,7 +1026,7 @@ class WorkbenchService extends Service { const { Op } = ctx.app.Sequelize; const waveOrders = await orderDeliveryModel.findAll({ where: { wave_id: waveId, warehouse_id: warehouseId }, - attributes: [ 'id' ], + attributes: [ 'id', 'intercept_status' ], raw: true, }); @@ -1022,7 +1034,17 @@ class WorkbenchService extends Service { throw new Error('波次下未找到订单'); } - const orderIds = waveOrders.map(o => Number(o.id)); + // 波次内拦截订单不参与批量称重 + const interceptedWaveOrderIds = (Array.isArray(waveOrders) ? waveOrders : []) + .filter(o => isInterceptedOrderStatus(o && o.intercept_status)) + .map(o => Number(o.id)); + const orderIds = (Array.isArray(waveOrders) ? waveOrders : []) + .filter(o => !isInterceptedOrderStatus(o && o.intercept_status)) + .map(o => Number(o.id)); + if (interceptedWaveOrderIds.length > 0) { + ctx.logger.info('[Workbench._sendWeight] 波次内拦截订单不参与称重 waveId=%d orderIds=%s', + waveId, interceptedWaveOrderIds.join(',')); + } const totalCount = orderIds.length; await ctx.model.OrderExpress.update( From e6f4d9f341621b6024c14c24de01629516d58de9 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 17 Aug 2026 22:01:18 +0800 Subject: [PATCH 222/550] =?UTF-8?q?feat(inbox):=20=E5=A4=84=E7=90=86?= =?UTF-8?q?=E5=A4=87=E6=B3=A8=E6=8E=A8=E9=80=81=E8=B4=A7=E4=B8=BB=E7=BE=A4?= =?UTF-8?q?=E3=80=81=E7=BE=A4=E7=B1=BB=E5=9E=8B=E6=B8=85=E7=A9=BA=E6=8E=A5?= =?UTF-8?q?=E5=8F=A3=E4=B8=8E=E7=BE=A4=E6=8C=89ID=E7=AE=A1=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - afterSale.handleWorkOrder: 处理备注发送到对应货主售后群(notifyGroup,内部流程不推),响应 notified_groups - inbox.group.reset: 新增清空群类型接口(入参群主键ID),权限迁移 556 - 群登记以 group_id 为准: 移除同名群回填,群ID不存在直接新建,store_id/群信息均按 group_id 精确匹配 - changeAddr: 已有工单也把客户原文转发快递群并升级 pending_feedback(仅 pending 可升级) - handleExpressFeedback: 工单描述售后类型显示中文(订单.物流异常) - 同步 methods/system.json 与 changes 记录 --- app/service/inbox/functions.js | 36 ++++- app/service/inbox/processor.js | 2 +- app/service/inbox/receiver.js | 32 ++--- app/service/systemMethods/afterSale.js | 1 + app/service/systemMethods/inbox.js | 22 ++- app/service/systems/afterSale.js | 134 +++++++++++++++++- app/service/systems/inbox/group.js | 51 +++++++ ...120000-add-inbox-group-reset-permission.js | 117 +++++++++++++++ methods/changes/system.json | 31 ++++ methods/system.json | 51 ++++++- 10 files changed, 440 insertions(+), 37 deletions(-) create mode 100644 database/migrations/20260817120000-add-inbox-group-reset-permission.js diff --git a/app/service/inbox/functions.js b/app/service/inbox/functions.js index 1495f23..5a9c494 100644 --- a/app/service/inbox/functions.js +++ b/app/service/inbox/functions.js @@ -2173,7 +2173,10 @@ class InboxFunctionsService extends Service { // 第三步:创建工单(含原文)并映射 waybill_id → 工单号 const createdNos = []; - const waybillToAsNo = {}; // waybill_id → after_sale_no 映射 + const waybillToAsNo = {}; // waybill_id → after_sale_no 映射(新建 + 已存在) + for (const r of existingASList) { + waybillToAsNo[r.waybill_id] = r.after_sale_no; + } if (toCreate.length > 0) { const creatorLabel = [ groupName, userName ].filter(Boolean).join('-') || 'AI系统'; for (const e of toCreate) { @@ -2209,8 +2212,9 @@ class InboxFunctionsService extends Service { } // 第四步:原文转发到对应快递的售后群(按快递分组) + // 新建与已存在的工单都转发:客户再次发来的原文是快递需要的最新诉求 const expressByCode = {}; - for (const e of toCreate) { + for (const e of expressList) { const code = e.logistics_code || '__unknown__'; if (!expressByCode[code]) { expressByCode[code] = { interfaceId: e.logistics_interface_id, waybills: [] }; @@ -2245,7 +2249,7 @@ class InboxFunctionsService extends Service { }); notifiedTotal += 1; } - toCreate + expressList .filter(e => (e.logistics_code || '__unknown__') === code) .forEach(e => notifiedWaybillIds.add(e.id)); } catch (e) { @@ -2253,8 +2257,11 @@ class InboxFunctionsService extends Service { } } - // 第五步:有转发通知的工单升级 pending_feedback + 跟踪时限 - const notifiedAsNos = createdNos.filter((asNo, idx) => notifiedWaybillIds.has(toCreate[idx].id)); + // 第五步:有转发通知的工单升级 pending_feedback + 跟踪时限(新建与已有工单,仅 pending 状态升级) + const notifiedAsNos = expressList + .filter(e => notifiedWaybillIds.has(e.id)) + .map(e => waybillToAsNo[e.id]) + .filter(Boolean); if (notifiedAsNos.length > 0) { try { const hours = await ctx.service.systems.afterSale._resolveFollowupHours( @@ -2266,7 +2273,12 @@ class InboxFunctionsService extends Service { followup_at: ctx.app.Sequelize.literal(`DATE_ADD(NOW(), INTERVAL ${hours} HOUR)`), role_group: 'customer_service', }, - { where: { after_sale_no: { [ctx.app.Sequelize.Op.in]: notifiedAsNos } } } + { + where: { + after_sale_no: { [ctx.app.Sequelize.Op.in]: notifiedAsNos }, + status: 'pending', + }, + } ); } catch (e) { ctx.logger.warn(`[inbox functions] 改地址/催退回更新工单状态失败: ${e.message}`); @@ -3331,6 +3343,15 @@ class InboxFunctionsService extends Service { const asType = String(params.as_type || 'order').trim() || 'order'; const asSubType = String(params.as_sub_type || 'logistics_issue').trim() || 'logistics_issue'; + // 工单详细描述中的售后类型/子类型显示中文名称(存储仍用英文编码) + const asTypesMeta = (ctx.model.AfterSale && ctx.model.AfterSale.AFTER_SALE_TYPES) || []; + const asTypeMeta = asTypesMeta.find(t => t.type === asType); + const asTypeName = (asTypeMeta && asTypeMeta.name) || asType; + const asSubTypeMeta = asTypeMeta && Array.isArray(asTypeMeta.subType) + ? asTypeMeta.subType.find(s => s.value === asSubType) + : null; + const asSubTypeName = (asSubTypeMeta && asSubTypeMeta.name) || asSubType; + if (!raw) return { success: false, error: '请提供运单号' }; if (!warehouseId) return { success: false, error: '无法获取仓库信息' }; @@ -3419,7 +3440,7 @@ class InboxFunctionsService extends Service { const description = [ `运单号: ${e.waybill_code}`, `快递公司: ${e.logistics_name || '未知'}`, - `售后类型: ${asType}.${asSubType}`, + `售后类型: ${asTypeName}.${asSubTypeName}`, '来源: 快递群反馈', feedbackMsgContent ? `原文: ${feedbackMsgContent}` : '', ].filter(Boolean).join('\n'); @@ -3553,6 +3574,7 @@ class InboxFunctionsService extends Service { where: { group_id: { [ctx.app.Sequelize.Op.in]: candidateGroupIds }, warehouse_id: warehouseId, + is_blocked: 0, }, raw: true, }); diff --git a/app/service/inbox/processor.js b/app/service/inbox/processor.js index da1f138..7e17f10 100644 --- a/app/service/inbox/processor.js +++ b/app/service/inbox/processor.js @@ -28,7 +28,7 @@ class InboxProcessorService extends Service { * @param {string} groupId 外部群ID * @param {number} warehouseId 仓库ID * @param {Object|null} msgExtData 入站消息的 ext_data - * @return {Promise<{group_type: string, sub_type: string, ai_enabled: number, ext_data: Object|null}>} + * @return {Promise<{group_type: string, sub_type: string, ai_enabled: number, ext_data: Object|null}>} 群类型/子类型/AI开关/扩展数据 */ async _loadGroupInfo(groupId, warehouseId, msgExtData) { const { ctx } = this; diff --git a/app/service/inbox/receiver.js b/app/service/inbox/receiver.js index 9c4529b..38fee5b 100644 --- a/app/service/inbox/receiver.js +++ b/app/service/inbox/receiver.js @@ -165,27 +165,19 @@ class InboxReceiverService extends Service { ); } } else { - // 群ID不存在:优先兼容同名群回填群ID;都没有才新建。 - // 注意表上已无 (group_name, warehouse_id) 唯一索引,名称维度不再保证唯一。 - const byName = await ctx.model.InboxGroup.findOne({ - where: { group_name: groupName, warehouse_id: warehouseId }, + // 群ID不存在:按群ID直接新建(群以ID为准,不按名称匹配既有群) + await ctx.model.InboxGroup.create({ + group_name: groupName, + group_id: extGroupId, + warehouse_id: warehouseId, + store_id: storeId || null, + source_type: sourceType, + source_extra: data.source_extra || null, + ai_enabled: 0, }); - if (byName) { - await byName.update({ group_id: extGroupId }); - ctx.logger.info( - `[inbox] 同名群回填群ID group_id=${extGroupId} name=${groupName}` - ); - } else { - await ctx.model.InboxGroup.create({ - group_name: groupName, - group_id: extGroupId, - warehouse_id: warehouseId, - store_id: storeId || null, - source_type: sourceType, - source_extra: data.source_extra || null, - ai_enabled: 0, - }); - } + ctx.logger.info( + `[inbox] 新建群记录 group_id=${extGroupId} name=${groupName}` + ); } } else { // 无群ID:按 (group_name, warehouse_id) 幂等登记(向后兼容) diff --git a/app/service/systemMethods/afterSale.js b/app/service/systemMethods/afterSale.js index e8d670c..6065d10 100644 --- a/app/service/systemMethods/afterSale.js +++ b/app/service/systemMethods/afterSale.js @@ -516,6 +516,7 @@ class AfterSaleMethodService extends MainService { operatorId, operatorSnapshot, warehouseId, + notifyGroup: true, }); return this.success('处理成功', result); diff --git a/app/service/systemMethods/inbox.js b/app/service/systemMethods/inbox.js index 018de3c..387a7a3 100644 --- a/app/service/systemMethods/inbox.js +++ b/app/service/systemMethods/inbox.js @@ -9,13 +9,14 @@ const MainService = require('../main'); class InboxSystemService extends MainService { /** * 群管理子入口,供 /system dispatcher 按 inbox.group.* 路径访问。 - * @return {{list: Function, disable: Function, update: Function, messages: Function, checkAuth: Function}} + * @return {{list: Function, disable: Function, update: Function, reset: Function, messages: Function, checkAuth: Function}} */ get group() { return { list: data => this.groupList(data), disable: data => this.groupDisable(data), update: data => this.groupUpdate(data), + reset: data => this.groupReset(data), messages: data => this.groupMessages(data), checkAuth: (...args) => this.checkAuth(...args), }; @@ -158,6 +159,25 @@ class InboxSystemService extends MainService { return { message: '群信息修改成功' }; } + /** + * 清空群类型配置(入参主键ID或外部群ID)。 + * 清空 group_type / sub_type / store_id / 快递专属字段,AI 开关重置关闭, + * 仅保留群创建时信息。warehouseId 从 ctx.user.store_id 自动注入。 + * + * @param {Object} data 请求数据。 + * @param {number} data.id 群记录主键ID(必填)。 + * @return {Promise} { message: 操作结果 }。 + */ + async groupReset(data = {}) { + const { ctx } = this; + const { id } = data; + const warehouseId = Number(ctx.user?.store_id || 0); + + await ctx.service.systems.inbox.group.reset({ id, warehouseId }); + + return { message: '群类型配置已清空' }; + } + /** * 拉取指定群的消息列表。 * warehouseId 从 ctx.user.store_id 自动注入。 diff --git a/app/service/systems/afterSale.js b/app/service/systems/afterSale.js index 209e6b9..3698b81 100644 --- a/app/service/systems/afterSale.js +++ b/app/service/systems/afterSale.js @@ -1074,14 +1074,15 @@ class AfterSaleService extends Service { * @param {number} params.operatorId 操作人ID * @param {string} params.operatorSnapshot 操作人快照 JSON * @param {number} params.warehouseId 仓库ID - * @return {Promise} 处理结果,包含更新后的售后单和步骤记录 + * @param {boolean} [params.notifyGroup] 是否将处理备注发送到对应货主售后群(内部自动处理不传) + * @return {Promise} 处理结果,包含更新后的售后单、步骤记录和通知群数量 * @throws {Error} 售后单不存在或权限不足时抛出 */ async handleWorkOrder(params = {}) { const { id, remark, targetStatus, resolution, attachmentIds, operatorId, operatorSnapshot, - warehouseId, + warehouseId, notifyGroup, } = params; const { ctx } = this; @@ -1163,11 +1164,73 @@ class AfterSaleService extends Service { await transaction.commit(); + // 9. 处理备注发送到对应的货主售后群(仅交互处理传入 notifyGroup 时触发,不转发快递群) + let notifiedGroupCount = 0; + if (notifyGroup && remark && String(remark).trim()) { + try { + const remarkText = String(remark).trim(); + const asRow = afterSale.toJSON ? afterSale.toJSON() : afterSale; + + // 定位货主:优先工单 store_id,缺失时从来源消息所在群反查 + let notifyStoreId = Number(asRow.store_id || 0); + if (!notifyStoreId && asRow.inbox_message_id) { + try { + const inbound = await ctx.model.InboxMessage.findByPk(asRow.inbox_message_id, { + attributes: [ 'group_id' ], + raw: true, + }); + if (inbound && inbound.group_id) { + const originGroup = await ctx.model.InboxGroup.findOne({ + attributes: [ 'store_id' ], + where: { + group_id: inbound.group_id, + warehouse_id: warehouseId, + is_blocked: 0, + }, + raw: true, + }); + if (originGroup && originGroup.store_id) { + notifyStoreId = Number(originGroup.store_id); + } + } + } catch (originErr) { + ctx.logger.warn(`[handleWorkOrder] 反查来源群货主失败 id=${id}: ${originErr.message}`); + } + } + + if (notifyStoreId) { + const storeGroups = await ctx.service.systems.inbox.group.findStoreAfterSalesGroups({ + storeIds: [ notifyStoreId ], + warehouseId, + }); + const content = `【工单 ${asRow.after_sale_no}】处理备注:\n${remarkText}`; + for (const g of storeGroups) { + if (!g.group_id) continue; + ctx.service.inbox.processor.pushSystemNotification({ + warehouse_id: warehouseId, + group_id: g.group_id, + group_name: g.group_name || '', + content, + ext_data: g.ext_data || null, + }); + notifiedGroupCount += 1; + } + } + + ctx.logger.info( + `[handleWorkOrder] 处理备注发送到货主售后群 id=${id} store=${notifyStoreId} notified=${notifiedGroupCount}` + ); + } catch (notifyErr) { + ctx.logger.warn(`[handleWorkOrder] 处理备注发送群失败 id=${id}: ${notifyErr.message}`); + } + } + const updatedAfterSale = afterSale.toJSON ? afterSale.toJSON() : afterSale; return { after_sale: this._formatAfterSaleRow(updatedAfterSale, ctx.app), step, + notified_groups: notifiedGroupCount, }; } catch (error) { await transaction.rollback(); @@ -1260,7 +1323,7 @@ class AfterSaleService extends Service { priority: 10, creator_id: 0, inbox_message_id: null, - role_group: 'warehouse', + role_group: 'customer_service', status: 'pending', waybill_id: e.id, waybill_no: e.waybill_code, @@ -1281,16 +1344,26 @@ class AfterSaleService extends Service { for (const e of toCreate) { const code = e.logistics_code || '__unknown__'; if (!expressByCode[code]) { - expressByCode[code] = { interfaceId: e.logistics_interface_id, waybills: [] }; + expressByCode[code] = { + code, + interfaceId: e.logistics_interface_id, + logisticsName: String(e.logistics_name || '').trim(), + waybills: [], + }; } expressByCode[code].waybills.push(e.waybill_code); } let notifiedCount = 0; const notifiedWaybillIds = new Set(); + // 无对应快递群(或快递无接口)的运单收集后统一降级通知仓库异常群(与货主群缺失降级行为一致) + const fallbackEntries = []; for (const [ code, info ] of Object.entries(expressByCode)) { - if (code === '__unknown__' || !info.interfaceId) continue; + if (code === '__unknown__' || !info.interfaceId) { + fallbackEntries.push(info); + continue; + } try { const { afterSalesGroups } = await ctx.service.systems.inbox.group.findGroupsByExpress({ expressInterfaceId: info.interfaceId, @@ -1298,7 +1371,10 @@ class AfterSaleService extends Service { warehouseId, }); - if (afterSalesGroups.length === 0) continue; + if (afterSalesGroups.length === 0) { + fallbackEntries.push(info); + continue; + } const notifyMsg = info.waybills.join('\n') + '\n拦截'; for (const g of afterSalesGroups) { @@ -1315,10 +1391,56 @@ class AfterSaleService extends Service { const codeWaybills = toCreate.filter(e => (e.logistics_code || '__unknown__') === code); codeWaybills.forEach(e => notifiedWaybillIds.add(e.id)); } catch (e) { + fallbackEntries.push(info); ctx.logger.warn(`[afterSale] 查售后群失败 code=${code}: ${e.message}`); } } + // 4b. 无对应快递群降级:转发仓库异常群,内容前缀标记失败(与货主群缺失降级一致) + if (fallbackEntries.length > 0) { + try { + const exceptionGroups = await ctx.model.InboxGroup.findAll({ + attributes: [ 'group_id', 'group_name', 'ext_data' ], + where: { + warehouse_id: warehouseId, + group_type: 'warehouse', + sub_type: 'exception', + is_blocked: 0, + }, + raw: true, + }); + + if (exceptionGroups.length > 0) { + const labelSet = new Set(); + const fallbackLines = []; + for (const entry of fallbackEntries) { + const label = entry.logisticsName || entry.code || '未知快递'; + labelSet.add(label); + for (const waybill of entry.waybills) { + fallbackLines.push(`${label} ${waybill}`); + } + } + const fallbackContent = `通知快递【${Array.from(labelSet).join('、')}】失败\n${fallbackLines.join('\n')}\n拦截`; + for (const g of exceptionGroups) { + ctx.service.inbox.processor.pushSystemNotification({ + warehouse_id: warehouseId, + group_id: g.group_id, + group_name: g.group_name, + content: fallbackContent, + ext_data: g.ext_data || null, + }); + } + ctx.logger.warn('[afterSale.createInterceptWorkOrdersAndNotify] 无对应快递群,已降级通知仓库异常群', { + warehouseId, + fallbackCount: fallbackEntries.length, + exceptionGroupCount: exceptionGroups.length, + }); + } + } catch (fallbackErr) { + ctx.logger.warn(`[afterSale] 降级通知异常群失败: ${fallbackErr.message}`); + } + } + // 5. 有通知的工单升级为 pending_feedback if (notifiedWaybillIds.size > 0) { const notifiedWaybillIdArr = [ ...notifiedWaybillIds ]; diff --git a/app/service/systems/inbox/group.js b/app/service/systems/inbox/group.js index 9bb7319..e17a589 100644 --- a/app/service/systems/inbox/group.js +++ b/app/service/systems/inbox/group.js @@ -362,6 +362,55 @@ class InboxGroupService extends Service { ); } + /** + * 清空群类型配置。 + * 将群恢复为"仅保留创建信息"状态:清空 group_type / sub_type / store_id / + * express_interfaces / system_express_code,AI 开关重置为关闭。 + * 保留群名称、群ID、仓库、来源信息、屏蔽状态与扩展数据。 + * + * @param {Object} data 请求数据。 + * @param {number} data.id 群记录主键ID(必填)。 + * @param {number} data.warehouseId 仓库ID(必填,由 controller 注入)。 + * @return {Promise<{id: number, group_name: string, group_id: string|null}>} 被重置的群信息。 + */ + async reset(data = {}) { + const { ctx } = this; + const { InboxGroup } = ctx.model; + + const id = Number(data.id); + const warehouseId = Number(data.warehouseId); + + if (!warehouseId) throw new Error('warehouseId 无效'); + if (!id) throw new Error('群ID无效'); + + const where = { id, warehouse_id: warehouseId }; + + const group = await InboxGroup.findOne({ + attributes: [ 'id', 'group_name', 'group_id' ], + where, + raw: true, + }); + if (!group) throw new Error('群不存在或无权限操作'); + + await InboxGroup.update( + { + group_type: null, + sub_type: null, + store_id: null, + express_interfaces: null, + system_express_code: null, + ai_enabled: 0, + }, + { where } + ); + + ctx.logger.info( + `[inbox group] 清空群类型配置 id=${group.id} group_id=${group.group_id} warehouse_id=${warehouseId}` + ); + + return { id: group.id, group_name: group.group_name, group_id: group.group_id }; + } + /** * 校验快递接口ID数组的有效性。 * 所有ID必须在 wms_express_interface 表中存在。 @@ -436,6 +485,7 @@ class InboxGroupService extends Service { const where = { group_type: 'express', system_express_code: code, + is_blocked: 0, [Op.or]: [ { express_interfaces: { [Op.or]: [ null, '' ] } }, { express_interfaces: { [Op.like]: `%${eid}%` } }, @@ -495,6 +545,7 @@ class InboxGroupService extends Service { group_type: 'store', sub_type: 'after_sales', store_id: { [Op.in]: ids }, + is_blocked: 0, }, raw: true, }); diff --git a/database/migrations/20260817120000-add-inbox-group-reset-permission.js b/database/migrations/20260817120000-add-inbox-group-reset-permission.js new file mode 100644 index 0000000..e60f410 --- /dev/null +++ b/database/migrations/20260817120000-add-inbox-group-reset-permission.js @@ -0,0 +1,117 @@ +'use strict'; + +/** + * inbox.group.reset 群类型清空接口权限记录 + 角色授权迁移。 + * + * 权限明细(固定 ID 558,556 已被「运单退回」web 页面占用): + * 558 — inbox.group.reset API:清空群类型配置(重置群) + * + * 角色授权(客服员工及以上链路): + * 30(客服组-员工) → 28(客服组-主管) → 8(经理,通配符 * 自动拥有) + * + * 幂等:INSERT IGNORE 创建权限记录;角色权限数组追加后去重排序,已存在跳过。 + */ + +const TABLE = 'wms_permission'; +const ROLE_TABLE = 'wms_role'; +const COLUMNS = 'id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at'; + +/** 权限ID → 授权角色ID列表(不含通配符角色) */ +const PERMISSION_ROLES = { + 558: [ 30, 28, 8 ], +}; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + // ── 1. 创建 API 权限记录(固定 ID)── + const apis = [ + [ 558, 'inbox.group.reset', 'API:清空群类型配置' ], + ]; + + for (const [ id, path, metaTitle ] of apis) { + await queryInterface.sequelize.query( + `INSERT IGNORE INTO \`${TABLE}\` (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`, + { replacements: [ id, path, null, path, null, metaTitle, null, 0, 0, null, 'api', 0, 1 ] } + ); + } + + // ── 2. 角色授权注入 ── + for (const permId of Object.keys(PERMISSION_ROLES).map(Number)) { + for (const roleId of PERMISSION_ROLES[permId]) { + const rows = await queryInterface.sequelize.query( + `SELECT id, permissions FROM \`${ROLE_TABLE}\` WHERE id = ?`, + { replacements: [ roleId ], type: queryInterface.sequelize.QueryTypes.SELECT } + ); + const record = Array.isArray(rows) ? rows[0] : null; + if (!record) { + continue; + } + + // 通配符角色跳过 + if (record.permissions === '*') { + continue; + } + + let perms; + try { + perms = typeof record.permissions === 'string' + ? JSON.parse(record.permissions) + : record.permissions; + } catch (e) { + perms = null; + } + + if (!Array.isArray(perms)) { + continue; + } + + if (!perms.includes(permId)) { + perms.push(permId); + perms.sort((a, b) => Number(a) - Number(b)); + await queryInterface.sequelize.query( + `UPDATE \`${ROLE_TABLE}\` SET permissions = ? WHERE id = ?`, + { replacements: [ JSON.stringify(perms), roleId ] } + ); + } + } + } + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + await queryInterface.sequelize.query( + 'DELETE FROM `wms_permission` WHERE id = 558' + ); + + const roleIds = [ 30, 28, 8 ]; + for (const roleId of roleIds) { + const rows = await queryInterface.sequelize.query( + `SELECT id, permissions FROM \`${ROLE_TABLE}\` WHERE id = ?`, + { replacements: [ roleId ], type: queryInterface.sequelize.QueryTypes.SELECT } + ); + const record = Array.isArray(rows) ? rows[0] : null; + if (!record || record.permissions === '*') { + continue; + } + + let perms; + try { + perms = typeof record.permissions === 'string' + ? JSON.parse(record.permissions) + : record.permissions; + } catch (e) { + perms = null; + } + if (!Array.isArray(perms) || !perms.includes(558)) { + continue; + } + + perms = perms.filter(p => p !== 558); + await queryInterface.sequelize.query( + `UPDATE \`${ROLE_TABLE}\` SET permissions = ? WHERE id = ?`, + { replacements: [ JSON.stringify(perms), roleId ] } + ); + } + }, +}; diff --git a/methods/changes/system.json b/methods/changes/system.json index 2bdc9c9..f04174e 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,35 @@ [ + { + "version": "2026.08.17-inbox-group-reset", + "date": "2026-08-17", + "type": "enhanced", + "summary": "新增 inbox.group.reset 群操作接口:入参群记录主键ID,清空群类型配置(group_type/sub_type/store_id/express_interfaces/system_express_code 置空、ai_enabled 重置为0),仅保留群创建时信息(群名称/群ID/仓库/来源/屏蔽状态/扩展数据)", + "methods": [ + "inbox.group.reset" + ], + "notes": [ + "app/service/systems/inbox/group.js reset:仓库隔离按主键 id 定位群,清空类型相关字段并写操作日志,返回重置后群信息", + "app/service/systemMethods/inbox.js 新增 groupReset,注册到 inbox.group 子入口", + "数据库迁移 20260817120000-add-inbox-group-reset-permission.js:权限ID 556 授权角色 8/26/28/29", + "同步更新 methods/system.json 中 inbox.group.reset 接口文档" + ], + "module": "inbox.group" + }, + { + "version": "2026.08.17-afterSale-handleWorkOrder-remark-notify-group", + "date": "2026-08-17", + "type": "enhanced", + "summary": "afterSale.handleWorkOrder 处理备注同步发送到对应货主售后群:填写 remark 时推送到货主售后群(工单 store_id 定位,缺失时从来源消息所在群反查货主,不转发快递群);消息内容格式为「【工单 售后单号】处理备注:备注内容」;响应新增 notified_groups 返回发送群数量", + "methods": [ + "afterSale.handleWorkOrder" + ], + "notes": [ + "app/service/systems/afterSale.js handleWorkOrder:新增 notifyGroup 参数(方法层交互处理传 true,内部自动处理如库内拦截/退回已收到不传),事务提交后按 remark 非空发送:store_id 定位货主 → findStoreAfterSalesGroups 发货主售后群;无 store_id 时按 inbox_message_id 查来源消息 group_id → InboxGroup 反查 store_id 再发送;发送失败仅告警不影响处理结果", + "app/service/systemMethods/afterSale.js handleWorkOrder:调用 systems 层时传 notifyGroup: true", + "同步更新 methods/system.json 中 afterSale.handleWorkOrder 的 description、remark 参数说明与 notified_groups 响应说明" + ], + "module": "afterSale" + }, { "version": "2026.08.16-waybill-createAt-between", "date": "2026-08-16", diff --git a/methods/system.json b/methods/system.json index f245d81..20fd2f4 100644 --- a/methods/system.json +++ b/methods/system.json @@ -33703,6 +33703,47 @@ } ] }, + { + "method": "inbox.group.reset", + "description": "清空群类型配置:清空群类型/子类型/货主/快递接口/系统快递编码,AI开关重置关闭,仅保留群创建时信息(群名称/群ID/仓库/来源/屏蔽状态/扩展数据)。入参群记录主键ID", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(从中解析 warehouseId 仓库上下文)" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "群记录主键ID" + } + ], + "response": [ + { + "name": "message", + "type": "string", + "required": true, + "description": "操作结果提示:群类型配置已清空" + } + ], + "errors": [ + { + "code": "400", + "message": "群ID无效" + }, + { + "code": "500", + "message": "群不存在或无权限操作" + } + ] + }, { "method": "inbox.group.messages", "description": "按群拉取消息列表,支持方向/关键词筛选,分页返回。warehouseId服务端自动注入,查询命中idx_warehouse_group_created索引", @@ -34582,7 +34623,7 @@ }, { "method": "afterSale.handleWorkOrder", - "description": "处理售后工单:写入进度步骤并绑定附件。操作人信息从登录上下文自动获取。非客服组处理完成后自动将 role_group 回退到 customer_service;status=completed 时自动写入 resolution + resolved_at。步骤 action 由服务端固定为\"处理工单\",step_status 与主表 status 完全一致。status 不填或填错时默认 processing。新增 pending_feedback 状态用于内部处理完成等待外部反馈(如已将拦截信息发给运方,等待运方反馈后再决定是否继续处理)。", + "description": "处理售后工单:写入进度步骤并绑定附件。操作人信息从登录上下文自动获取。非客服组处理完成后自动将 role_group 回退到 customer_service;status=completed 时自动写入 resolution + resolved_at。步骤 action 由服务端固定为\"处理工单\",step_status 与主表 status 完全一致。status 不填或填错时默认 processing。新增 pending_feedback 状态用于内部处理完成等待外部反馈(如已将拦截信息发给运方,等待运方反馈后再决定是否继续处理)。填写处理备注(remark)时会同步发送到对应的货主售后群(工单无 store_id 时从来源消息所在群反查货主,不转发快递群),响应 notified_groups 返回发送的群数量。", "isNeedAuth": false, "isNeedLogin": true, "headers": [], @@ -34606,7 +34647,7 @@ "type": "string", "required": false, "source": "body", - "description": "处理备注" + "description": "处理备注。填写后同步发送到对应的货主售后群,内容格式:\"【工单 售后单号】处理备注:备注内容\"" }, { "name": "attachment_ids", @@ -34628,6 +34669,12 @@ "type": "integer", "required": true, "description": "售后工单ID" + }, + { + "name": "notified_groups", + "type": "integer", + "required": false, + "description": "处理备注发送到的货主售后群数量(未填写备注或未找到货主售后群时为0)" } ], "errors": [] From 0392902414aa4cf6653baa9692f0bd1f4287bb75 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 17 Aug 2026 22:04:58 +0800 Subject: [PATCH 223/550] =?UTF-8?q?fix(order.recheckOrder):=20=E8=BD=A6?= =?UTF-8?q?=E5=8F=B7=E6=89=AB=E6=8F=8F=E5=BF=AB=E7=85=A7=E5=85=9C=E5=BA=95?= =?UTF-8?q?=E8=BF=87=E6=BB=A4=E5=B7=B2=E8=A7=A3=E7=BB=91=E4=BB=BB=E5=8A=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 兜底查询新增 NOT EXISTS 过滤:该车号下存在解绑记录(unbind_time 非空)的任务不再回退命中 - 绑定表保持权威数据源语义,解绑即失效;快照数据不清除,兼容无解绑记录的历史数据 - 生产库 car04 验证:新查询 0 命中(原查询命中已完成任务 3416) --- app/service/systemMethods/order/recheckOrder.js | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/app/service/systemMethods/order/recheckOrder.js b/app/service/systemMethods/order/recheckOrder.js index c88fb76..c57c02b 100644 --- a/app/service/systemMethods/order/recheckOrder.js +++ b/app/service/systemMethods/order/recheckOrder.js @@ -2712,7 +2712,8 @@ class RecheckOrderService extends OrderBaseService { * 通过车号查找匹配的拣货任务行。 * 匹配优先级: * 1. wms_pick_task_cart_binding(车任务绑定表,unbind_time IS NULL,权威数据源) - * 2. wms_wave_pick_task.current_cart_code_snapshot / wms_wave_pick_task_order.cart_code_snapshot(快照回退兜底) + * 2. wms_wave_pick_task.current_cart_code_snapshot / wms_wave_pick_task_order.cart_code_snapshot(快照回退兜底, + * 仅兜底该车号下不存在解绑记录的任务:绑定表为权威数据源,已解绑的任务不再回退命中,避免解绑后快照残留误匹配) * @param {string} cartCode 车号。 * @param {number} warehouseId 仓库ID。 * @return {Promise} 任务行,未找到返回 null。 @@ -2747,7 +2748,9 @@ class RecheckOrderService extends OrderBaseService { return bindingRows[0]; } - // 第二优先级(回退兜底):任务主表 + 任务订单行快照 + // 第二优先级(回退兜底):任务主表 + 任务订单行快照。 + // 绑定表是权威数据源:该车号下存在解绑记录(unbind_time 非空)的任务不再回退命中, + // 避免解绑后任务主表/订单行快照残留导致误匹配已完成任务。 const snapshotRows = await ctx.model.query( ` SELECT @@ -2768,6 +2771,14 @@ class RecheckOrderService extends OrderBaseService { AND pto.cart_code_snapshot = :cartCode ) ) + AND NOT EXISTS ( + SELECT 1 + FROM wms_pick_task_cart_binding b + WHERE b.task_id = t.id + AND b.warehouse_id = :warehouseId + AND b.cart_code_snapshot = :cartCode + AND b.unbind_time IS NOT NULL + ) ORDER BY t.create_time DESC, t.id DESC LIMIT 1 `, From 591a69d35ef388a8218a81f1067c3bfc53a2fb28 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 17 Aug 2026 22:10:47 +0800 Subject: [PATCH 224/550] =?UTF-8?q?fix(notice):=20=E6=94=B6=E8=B4=A7?= =?UTF-8?q?=E9=80=9A=E7=9F=A5=E7=BE=A4=E8=B7=AF=E7=94=B1=E7=BB=86=E5=8C=96?= =?UTF-8?q?=E4=B8=8E=E5=A5=87=E9=97=A8=E5=8F=96=E6=B6=88=E6=8B=A6=E6=88=AA?= =?UTF-8?q?=E8=BD=AC=E5=BF=AB=E9=80=92=E7=BE=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - receiving_completed/rejected 只通知仓库收货群,不再通知货主(货主端链接不再生成) - receiving_reviewed 货主侧三级回退:货主收货群→货主售后群→仓库异常群(sendToWarehouseChannel 支持 fallbackTargets 回退链) - 新增 receiving_store_bound:收货单创建/首次绑定货主时提醒货主填写车牌号/快递单号,路由同三级回退 - qimen order.cancel 两个拦截分支仅限有运单时创建拦截工单并通知对应快递群,与正常货主发起拦截一致 - 新增 script/backfill-inbox-permissions.cjs:客服/仓库组主管员工回填 inbox 页面与 API 权限(已执行 dev 与线上) --- app/model/notification_webhook.js | 1 + app/service/qimenMethods/order.js | 32 +++- app/service/systems/notice/index.js | 80 ++++++++- app/service/systems/storage/receiving.js | 123 ++++++++++++- methods/changes/qimen.json | 16 ++ methods/changes/warehouse.json | 77 ++++++++ script/backfill-inbox-permissions.cjs | 217 +++++++++++++++++++++++ 7 files changed, 527 insertions(+), 19 deletions(-) create mode 100644 script/backfill-inbox-permissions.cjs diff --git a/app/model/notification_webhook.js b/app/model/notification_webhook.js index a94a799..86f6c8d 100644 --- a/app/model/notification_webhook.js +++ b/app/model/notification_webhook.js @@ -41,6 +41,7 @@ module.exports = app => { Object.freeze({ code: 'receiving_completed', name: '收货完成', business: 'receiving', description: '收货单完成后的通知' }), Object.freeze({ code: 'receiving_rejected', name: '收货驳回', business: 'receiving', description: '收货单被驳回并恢复为收货中后的通知' }), Object.freeze({ code: 'receiving_reviewed', name: '收货审核完成', business: 'receiving', description: '收货单批量审核通过后的通知' }), + Object.freeze({ code: 'receiving_store_bound', name: '收货单创建/绑定货主', business: 'receiving', description: '收货单创建或首次绑定货主时提醒货主填写车牌号/快递号的通知' }), Object.freeze({ code: 'order_sync_completed', name: '订单同步完成', business: 'order', description: '本地创建入口同步完成后的通知' }), Object.freeze({ code: 'order_cancel_intercepted', name: '订单取消拦截', business: 'order', description: '订单取消失败并触发拦截执行后的通知' }), Object.freeze({ code: 'wave_strategy_quick_scan_failed', name: '波次策略兜底扫描失败', business: 'order', description: '定时兜底扫描任务在仓库维度触发失败时通知' }), diff --git a/app/service/qimenMethods/order.js b/app/service/qimenMethods/order.js index ab162cd..570c7ee 100644 --- a/app/service/qimenMethods/order.js +++ b/app/service/qimenMethods/order.js @@ -228,13 +228,16 @@ class orderServer extends MainService { ctx.logger.warn('[QimenOrderCancel] 写入拦截操作日志失败,不影响主流程', logErr); } - // 创建售后工单 + 通知快递群(失败不影响主流程) + // 创建售后工单 + 通知快递群(仅限有运单的订单,与正常货主发起拦截一致;失败不影响主流程) try { - await ctx.service.systems.afterSale.createInterceptWorkOrdersAndNotify({ - orderIds: [ existingOrder.id ], - warehouseId: info.warehouseId, - creatorLabel: ctx.user?.employees_name || '奇门系统', - }); + const interceptExpress = await this.getInterceptExpressInfo(existingOrder.id); + if (Array.isArray(interceptExpress) && interceptExpress.length > 0) { + await ctx.service.systems.afterSale.createInterceptWorkOrdersAndNotify({ + orderIds: [ existingOrder.id ], + warehouseId: info.warehouseId, + creatorLabel: ctx.user?.employees_name || '奇门系统', + }); + } } catch (workOrderErr) { ctx.logger.warn( `[qimen order cancel] 创建工单/通知失败, orderId=${existingOrder.id}, error=${workOrderErr.message}` @@ -272,6 +275,23 @@ class orderServer extends MainService { } await transaction.commit(); + + // 创建售后工单 + 通知快递群(仅限有运单的订单,与正常货主发起拦截一致;失败不影响主流程) + try { + const interceptExpress = await this.getInterceptExpressInfo(existingOrder.id); + if (Array.isArray(interceptExpress) && interceptExpress.length > 0) { + await ctx.service.systems.afterSale.createInterceptWorkOrdersAndNotify({ + orderIds: [ existingOrder.id ], + warehouseId: info.warehouseId, + creatorLabel: ctx.user?.employees_name || '奇门系统', + }); + } + } catch (workOrderErr) { + ctx.logger.warn( + `[qimen order cancel] 创建工单/通知失败(sync), orderId=${existingOrder.id}, error=${workOrderErr.message}` + ); + } + await this.sendCancelInterceptNotice({ orderCode, existingOrder, diff --git a/app/service/systems/notice/index.js b/app/service/systems/notice/index.js index b0f608f..269d58f 100644 --- a/app/service/systems/notice/index.js +++ b/app/service/systems/notice/index.js @@ -24,6 +24,9 @@ const DEFAULT_REGISTERED_EVENT_CODES = Object.freeze([ 'all', '*', 'receiving_completed', + 'receiving_rejected', + 'receiving_reviewed', + 'receiving_store_bound', 'order_cancel_intercepted', 'wave_strategy_quick_scan_failed', 'store_warehouse_print_quantity_adjusted', @@ -37,15 +40,28 @@ const DEFAULT_REGISTERED_EVENT_CODES = Object.freeze([ const FIXED_GROUP_SUBSCRIPTIONS = Object.freeze({ receiving_completed: Object.freeze([ Object.freeze({ groupType: 'warehouse', subType: 'receiving' }), - Object.freeze({ groupType: 'store', subType: 'receiving' }), ]), receiving_rejected: Object.freeze([ Object.freeze({ groupType: 'warehouse', subType: 'receiving' }), - Object.freeze({ groupType: 'store', subType: 'receiving' }), ]), receiving_reviewed: Object.freeze([ Object.freeze({ groupType: 'warehouse', subType: 'receiving' }), - Object.freeze({ groupType: 'store', subType: 'receiving' }), + Object.freeze({ + groupType: 'store', + subType: 'receiving', + fallbackTargets: Object.freeze([ + Object.freeze({ groupType: 'store', subType: 'after_sales' }), + ]), + }), + ]), + receiving_store_bound: Object.freeze([ + Object.freeze({ + groupType: 'store', + subType: 'receiving', + fallbackTargets: Object.freeze([ + Object.freeze({ groupType: 'store', subType: 'after_sales' }), + ]), + }), ]), order_cancel_intercepted: Object.freeze([ Object.freeze({ groupType: 'warehouse', subType: 'exception' }), @@ -1001,8 +1017,6 @@ class NoticeService extends Service { }; } - const groups = await this.findSubscribedGroups(payload); - // 货主目标群未配置时,降级发送到仓库异常群,内容前缀标记失败 const fixedTargets = this.getFixedGroupTargets(payload.event) || []; const hasStoreTarget = fixedTargets.some( @@ -1020,10 +1034,60 @@ class NoticeService extends Service { : Number(storeInfo.authStatus); const storeContractInactive = warehouseUseStatus === 0 || (authStatus !== null && authStatus !== 2); + // 主目标查询(store 目标的 fallbackTargets 不参与主查询,避免主目标命中时 fallback 群也被推送) + const primaryTargets = fixedTargets + .map(target => ({ + groupType: String(target && target.groupType || '').trim().toLowerCase(), + subType: String(target && target.subType || '').trim(), + })) + .filter(target => target.groupType); + const groups = await this.findSubscribedGroups(payload, primaryTargets); + const effectiveGroups = storeContractInactive ? groups.filter(group => group && group.group_type !== 'store') : groups; - const storeGroupMatched = effectiveGroups.some(group => group && group.group_type === 'store'); + + // store 目标回退链:主目标(如 store:receiving)未命中时,按 fallbackTargets 顺序逐级尝试(如 store:after_sales) + const storeChains = fixedTargets.filter( + target => String(target && target.groupType || '').trim().toLowerCase() === 'store' + ); + const extraStoreGroups = []; + let storeChainMatchedCount = 0; + + if (!storeContractInactive) { + for (const chain of storeChains) { + const chainSubType = String(chain.subType || '').trim(); + const primaryMatched = effectiveGroups.some( + group => group && group.group_type === 'store' && (!chainSubType || String(group.sub_type || '').trim() === chainSubType) + ); + if (primaryMatched) { + storeChainMatchedCount += 1; + continue; + } + + const fallbackTargets = Array.isArray(chain.fallbackTargets) ? chain.fallbackTargets : []; + let chainMatched = false; + for (const fallbackTarget of fallbackTargets) { + const fallbackGroups = await this.findSubscribedGroups(payload, [ fallbackTarget ]); + if (fallbackGroups.length > 0) { + for (const fallbackGroup of fallbackGroups) { + extraStoreGroups.push(fallbackGroup); + } + chainMatched = true; + break; + } + } + if (chainMatched) { + storeChainMatchedCount += 1; + } + } + } + + const mergedGroups = [ ...effectiveGroups, ...extraStoreGroups ]; + const effectiveGroupsFinal = mergedGroups.filter( + (group, index) => mergedGroups.findIndex(item => item.group_id === group.group_id) === index + ); + const storeGroupMatched = storeChains.length === 0 || storeChainMatchedCount >= storeChains.length; let fallbackGroups = []; let storeLabel = '货主'; @@ -1032,7 +1096,7 @@ class NoticeService extends Service { const exceptionGroups = await this.findSubscribedGroups(payload, [ { groupType: 'warehouse', subType: 'exception' }, ]); - const matchedGroupIds = new Set(effectiveGroups.map(group => group.group_id)); + const matchedGroupIds = new Set(effectiveGroupsFinal.map(group => group.group_id)); fallbackGroups = exceptionGroups.filter(group => !matchedGroupIds.has(group.group_id)); if (fallbackGroups.length > 0) { @@ -1047,7 +1111,7 @@ class NoticeService extends Service { } } - const pushGroups = [ ...effectiveGroups, ...fallbackGroups ]; + const pushGroups = [ ...effectiveGroupsFinal, ...fallbackGroups ]; if (pushGroups.length === 0) { ctx.logger.warn('[NoticeService.sendToWarehouseChannel] 未匹配到订阅群', { traceId: payload.traceId, diff --git a/app/service/systems/storage/receiving.js b/app/service/systems/storage/receiving.js index e7c7398..74944b3 100644 --- a/app/service/systems/storage/receiving.js +++ b/app/service/systems/storage/receiving.js @@ -1017,7 +1017,7 @@ class ReceivingService extends Service { `收货单ID:${item.id || ''}`, `收货单号:${item.receiving_number || '无'}`, `收货创建人:${item.creator && item.creator.name || '无'}`, - '请及时处理重新提交完成收货。', + '请及时处理重新提交完成收货', ].join('\n') + '。', businessId: item.id || ids[0], subject: { @@ -1493,6 +1493,72 @@ class ReceivingService extends Service { ]; } + /** + * 发送收货单创建/首次绑定货主通知(receiving_store_bound),提醒货主填写车牌号/快递单号。 + * 路由由 notice 固定订阅回退链处理:货主收货群 → 无则货主售后群 → 均无则仓库异常群。 + * @param {Object} options 发送参数 + * @param {Object} options.receiving 收货单快照 + * @param {string|null} [options.storeName=null] 货主名称(优先用合约备注) + * @return {Promise} 发送结果 + */ + async sendStoreBoundNotice({ receiving, storeName = null } = {}) { + const { ctx } = this; + const rawNoticeService = ctx && ctx.service && ctx.service.systems && ctx.service.systems.notice; + const noticeService = rawNoticeService && typeof rawNoticeService.send === 'function' + ? rawNoticeService + : (rawNoticeService && rawNoticeService.index && typeof rawNoticeService.index.send === 'function' + ? rawNoticeService.index + : null); + + if (!receiving || !noticeService) return null; + + const warehouseId = Number(receiving.warehouse_id || (ctx.user && ctx.user.store_id) || 0); + const storeId = Number(receiving.store_id || 0); + if (!Number.isFinite(warehouseId) || warehouseId <= 0 || !Number.isFinite(storeId) || storeId <= 0) { + return null; + } + + const receivingNumber = String(receiving.receiving_number || receiving.id || '').trim(); + const storeLabel = String(storeName || receiving.store_name || '').trim() || '货主'; + const storeFrontendUrl = String(ctx.app.config.storeFrontendUrl || ctx.app.config.frontendUrl || '').trim(); + + const contentLines = [ + `收货单号:${receivingNumber} 正在收货`, + `货主:${storeLabel}`, + '请确认是否已填写车牌号或快递单号,未填写请及时补充', + ]; + const content = [ ...contentLines ].join('\n') + '。'; + const storeContent = [ ...contentLines, `快速查看:${storeFrontendUrl}/storage/receiving_owner?id=${receivingNumber}` ].join('\n') + '。'; + + return await noticeService.send({ + warehouseId, + storeId, + messageType: 'text', + businessName: 'receiving', + event: 'receiving_store_bound', + channel: 'warehouse', + title: `收货单${receivingNumber}正在收货`, + content, + storeContent, + businessId: receiving.id, + subject: { + id: warehouseId, + type: 'warehouse', + name: String((ctx.user && (ctx.user.store_name || ctx.user.company_name)) || ''), + }, + sender: { + id: (ctx.user && (ctx.user.employees_id || ctx.user.id)) || null, + name: (ctx.user && ctx.user.employees_name) || '', + }, + metadata: { + receivingId: receiving.id, + receivingNumber, + warehouseId, + storeId, + }, + }); + } + /** * 发送审核完成通知(receiving_reviewed),支持文字/文件两种类型。 * @param {Object} options 发送参数 @@ -1985,6 +2051,23 @@ class ReceivingService extends Service { ctx.logger.warn('[receiving.create] 写入操作日志失败,不影响业务', logErr); } + // 创建时已绑定货主 → 通知货主正在收货(失败不影响主流程) + if (Number(result.store_id || 0) > 0) { + try { + await this.sendStoreBoundNotice({ + receiving: { + id: result.id, + receiving_number: result.receiving_number, + warehouse_id: result.warehouse_id, + store_id: result.store_id, + store_name: result.store_name, + }, + }); + } catch (noticeErr) { + ctx.logger.warn('[receiving.create] 通知货主失败,不影响业务', noticeErr); + } + } + return { code: 200, id: result.id, @@ -2330,6 +2413,21 @@ class ReceivingService extends Service { ctx.logger.warn('[receiving.bindStore] 写入操作日志失败,不影响业务', logErr); } + // 首次绑定货主 → 通知货主正在收货(失败不影响主流程) + try { + await this.sendStoreBoundNotice({ + receiving: { + id: receivingId, + receiving_number: receiving.receiving_number, + warehouse_id: warehouseId, + store_id: storeId, + store_name: storeName, + }, + }); + } catch (noticeErr) { + ctx.logger.warn('[receiving.bindStore] 通知货主失败,不影响业务', noticeErr); + } + return { code: 200, message: '绑定货主成功', @@ -3155,6 +3253,7 @@ class ReceivingService extends Service { }; // 只在有值且收货单当前没有这些值时更新 store 信息 + const firstBoundStore = !!storeId && !receiving.store_id; if (storeId && !receiving.store_id) { updateData.store_id = storeId; updateData.store_name = storeName; @@ -3174,6 +3273,23 @@ class ReceivingService extends Service { // 6. 提交事务 await transaction.commit(); + // 首次自动绑定货主 → 通知货主正在收货(失败不影响主流程) + if (firstBoundStore) { + try { + await this.sendStoreBoundNotice({ + receiving: { + id: receivingId, + receiving_number: receiving.receiving_number, + warehouse_id: warehouseId, + store_id: storeId, + store_name: storeName, + }, + }); + } catch (noticeErr) { + ctx.logger.warn('[receiving.updateReceivingStats] 通知货主失败,不影响业务', noticeErr); + } + } + ctx.logger.info(`成功更新收货单 ${receivingId} 的统计信息`); } catch (error) { @@ -4099,9 +4215,8 @@ class ReceivingService extends Service { const totalBoxWeight = normalizedDetails.reduce((sum, item) => sum + Number(item.box_weight || 0), 0); const title = `收货单${receivingNumber}已完成`; const contactLines = this.getCompletionContactFields(receiving).map(([ field, value ]) => `${field}:${value || '无'}`); - // 仓库侧与货主侧前端地址/路径不同,分别拼快速查看链接 + // 收货完成只通知仓库收货群,不再通知货主(货主端链接不再生成) const warehouseFrontendUrl = String(ctx.app.config.frontendUrl || '').trim(); - const storeFrontendUrl = String(ctx.app.config.storeFrontendUrl || ctx.app.config.frontendUrl || '').trim(); const contentLines = [ `收货单号:${receivingNumber} 已完成`, `货主:${receiving.store_name || '未知'}`, @@ -4121,7 +4236,6 @@ class ReceivingService extends Service { `备注:${receiving.remark || '无'}`, ].filter(Boolean); const content = [ ...contentLines, `快速查看:${warehouseFrontendUrl}/storage/receiving?id=${receivingNumber}` ].join('\n') + '。'; - const storeContent = [ ...contentLines, `快速查看:${storeFrontendUrl}/storage/receiving_owner?id=${receivingNumber}` ].join('\n') + '。'; return await noticeService.send({ warehouseId, @@ -4132,7 +4246,6 @@ class ReceivingService extends Service { channel: 'warehouse', title, content, - storeContent, url: reportUrl || undefined, fileName: reportUrl ? reportFileName : '', mimeType: reportUrl ? 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' : '', diff --git a/methods/changes/qimen.json b/methods/changes/qimen.json index 11cfe45..aa94da4 100644 --- a/methods/changes/qimen.json +++ b/methods/changes/qimen.json @@ -69,5 +69,21 @@ ], "type": "changed", "module": "stockout" + }, + { + "version": "2026.08.17-qimen-order-cancel-01", + "date": "2026-08-17", + "summary": "order.cancel 触发拦截的两个分支统一转发快递群发起拦截(创建售后工单+通知快递群),仅限有运单的订单处理", + "methods": [ + "order.cancel" + ], + "notes": [ + "已拣货/已打印分支:保留原有 createInterceptWorkOrdersAndNotify 调用,新增前置判断——先查订单运单,无运单不再创建工单/通知快递群", + "已同步订单分支(sync_status=fin):新增与分支一相同的拦截处理——有运单时创建售后工单并通知对应快递群,与正常货主发起拦截一致", + "无运单订单仍按原逻辑更新拦截状态与异常群通知,不创建工单、不通知快递群", + "createInterceptWorkOrdersAndNotify 内部本就按运单驱动(无运单直接返回),外层判断进一步避免无谓调用" + ], + "type": "changed", + "module": "order" } ] diff --git a/methods/changes/warehouse.json b/methods/changes/warehouse.json index 9562c5b..5f5cdff 100644 --- a/methods/changes/warehouse.json +++ b/methods/changes/warehouse.json @@ -147,5 +147,82 @@ "事件码 storage_transfer_completed 仍保留注册:app/schedule/notice_stock_remaining.js 库存余量每日提醒复用该事件码,固定群映射 warehouse:production 不变" ], "module": "storage" + }, + { + "version": "2026-08-17-warehouse-03", + "date": "2026-08-17", + "type": "changed", + "summary": "拦截通知无对应快递群时降级转发仓库异常群:拦截工单创建后若运单快递无售后群(或无快递接口),统一转发异常群并在内容前缀标记失败,与货主群缺失降级行为一致", + "methods": [ + "notify.reply" + ], + "notes": [ + "app/service/systems/afterSale.js createInterceptWorkOrdersAndNotify:按快递分组通知售后群时,无群/无接口的运单收集后统一推送到仓库异常群(group_type=warehouse + sub_type=exception + is_blocked=0)", + "降级内容格式:通知快递【快递名】失败\\n{快递名 运单号...}\\n拦截(前缀与货主群缺失降级的「通知货主【X】失败」一致)", + "仅成功通知快递群的工单升级 pending_feedback;降级到异常群的工单保持 pending,等待人工跟进" + ], + "module": "after_sale" + }, + { + "version": "2026-08-17-warehouse-04", + "date": "2026-08-17", + "type": "changed", + "summary": "收货完成/驳回不再通知货主:receiving_completed 与 receiving_rejected 固定订阅由「仓库收货群+货主收货群」改为仅仓库收货群,货主端快速查看链接不再生成", + "methods": [ + "notify.reply" + ], + "notes": [ + "notice/index.js FIXED_GROUP_SUBSCRIPTIONS:receiving_completed 与 receiving_rejected 均移除 store:receiving 目标,仅保留 warehouse:receiving", + "storage/receiving.js 完成通知移除 storeContent(货主侧 /storage/receiving_owner 链接),只生成仓库侧快速查看链接", + "receiving_reviewed 仍保持双群通知不变", + "e2e 用例 receiving_completed / receiving_rejected expectGroups 调整为仅 g_wh_receiving_debug_001" + ], + "module": "receiving" + }, + { + "version": "2026-08-17-warehouse-05", + "date": "2026-08-17", + "type": "changed", + "summary": "收货审核通知货主群三级回退:审核明细文件优先推货主收货群,无收货群推货主售后群,均无则降级仓库异常群", + "methods": [ + "notify.reply" + ], + "notes": [ + "FIXED_GROUP_SUBSCRIPTIONS.receiving_reviewed 的 store 目标新增 fallbackTargets(store:after_sales),主目标查询时 fallback 不参与,命中主目标则不推 fallback 群", + "sendToWarehouseChannel 支持 store 目标回退链:主目标未匹配时按 fallbackTargets 顺序逐级查找,命中即停止并视为货主群推送(使用 storeContent/storeId 关联)", + "回退链全部未匹配时沿用原有异常群降级(前缀「通知货主【X】失败」)", + "e2e 新增 receiving_reviewed_fallback_after_sales(货主 1000241,无收货群→售后群)与 receiving_reviewed_fallback_exception(货主 1000282,无收货群无售后群→异常群)两个用例" + ], + "module": "receiving" + }, + { + "version": "2026-08-17-warehouse-06", + "date": "2026-08-17", + "type": "added", + "summary": "新增收货单创建/首次绑定货主通知(receiving_store_bound):提醒货主收货进行中并确认车牌号/快递单号,路由与审核一致(货主收货群→售后群→异常群)", + "methods": [ + "notify.reply" + ], + "notes": [ + "新事件码 receiving_store_bound 注册(notification_webhook.js AVAILABLE_EVENTS 与 notice/index.js DEFAULT_REGISTERED_EVENT_CODES)", + "FIXED_GROUP_SUBSCRIPTIONS.receiving_store_bound:仅货主侧目标 store:receiving + fallbackTargets store:after_sales(回退链复用 sendToWarehouseChannel 通用逻辑)", + "storage/receiving.js 新增 sendStoreBoundNotice:内容「收货单号:Rxx 正在收货 / 请确认是否已填写车牌号或快递单号」+ 货主端快速查看链接(storeContent)", + "触发点:create(创建时已绑定货主)、bindStore(首次绑定)、updateReceivingStats(商品匹配后自动绑定),失败均不影响主流程", + "e2e 新增 receiving_store_bound(货主 1000000 → 货主收货群)与 receiving_store_bound_fallback_after_sales(货主 1000241 → 售后群)" + ], + "module": "receiving" + }, + { + "version": "2026-08-17-warehouse-07", + "date": "2026-08-17", + "type": "changed", + "summary": "补回 inbox 权限到操作角色:客服组主管/员工、仓库组主管/员工补齐消息和自动回复/群列表/消息记录页面与 inbox.* API 权限;上线时需执行 script/backfill-inbox-permissions.cjs", + "methods": [], + "notes": [ + "新增 script/backfill-inbox-permissions.cjs:按角色合并 inbox 权限 ID(491~503、531 共 14 项,含页面 492/493/494),支持 --dry-run / --role-ids", + "permissions='*' 的全量角色(超级管理员/经理/仓库管理员/货主管理员)自动跳过,原本即拥有", + "dev 库已回填:26 仓库组-主管、27 仓库组-员工、28 客服组-主管、30 客服组-员工" + ], + "module": "permission" } ] diff --git a/script/backfill-inbox-permissions.cjs b/script/backfill-inbox-permissions.cjs new file mode 100644 index 0000000..76f320e --- /dev/null +++ b/script/backfill-inbox-permissions.cjs @@ -0,0 +1,217 @@ +'use strict'; + +/** + * 回填 inbox(消息和自动回复/群列表/消息记录 + inbox.* API)权限到指定角色。 + * 默认角色:客服组-主管(28)、客服组-员工(30)、仓库组-主管(26)、仓库组-员工(27)。 + * permissions='*' 的全量角色自动跳过。 + * + * 用法: + * node script/backfill-inbox-permissions.cjs --dry-run + * node script/backfill-inbox-permissions.cjs + * node script/backfill-inbox-permissions.cjs --role-ids=28,30 + */ + +const fs = require('fs'); +const path = require('path'); +const mysql = require('mysql2/promise'); + +const ROOT = process.cwd(); +const DEFAULT_CONFIG_PATH = path.join(ROOT, 'config', 'config.local.js'); +const DEFAULT_ROLE_IDS = [ 28, 30, 26, 27 ]; +// inbox 全部权限:页面 492/493/494 + API 491、495~503、531 +const INBOX_PERMISSION_IDS = [ + 491, 492, 493, 494, 495, 496, 497, 498, 499, 500, 501, 502, 503, 531, +]; + +function parseArgs(argv) { + const args = { + dryRun: false, + roleIds: DEFAULT_ROLE_IDS, + dbClient: 'wms', + configPath: DEFAULT_CONFIG_PATH, + }; + + for (const item of argv) { + if (item === '--dry-run') { + args.dryRun = true; + continue; + } + if (item.startsWith('--role-ids=')) { + args.roleIds = String(item.split('=')[1] || '') + .split(',') + .map(id => Number(id.trim())) + .filter(id => Number.isFinite(id) && id > 0); + continue; + } + if (item.startsWith('--db-client=')) { + args.dbClient = String(item.split('=')[1] || '').trim() || 'wms'; + continue; + } + if (item.startsWith('--config-path=')) { + args.configPath = path.resolve(ROOT, String(item.split('=')[1] || '').trim()); + continue; + } + } + + return args; +} + +function loadConfig(configPath) { + if (!fs.existsSync(configPath)) { + throw new Error(`Config file not found: ${configPath}`); + } + const configFactory = require(configPath); + return typeof configFactory === 'function' + ? configFactory({ name: 'wms-inbox-permissions-backfill' }) + : configFactory; +} + +function normalizeRolePermissions(rawValue) { + if (rawValue === undefined || rawValue === null) { + return { allAccess: false, permissionIds: [] }; + } + if (Array.isArray(rawValue)) { + const items = rawValue.map(item => (typeof item === 'string' ? item.trim() : item)); + if (items.some(item => item === '*')) { + return { allAccess: true, permissionIds: [] }; + } + return { + allAccess: false, + permissionIds: Array.from(new Set(items + .map(item => Number(item)) + .filter(item => Number.isFinite(item) && item > 0) + .map(item => Math.floor(item)))).sort((a, b) => a - b), + }; + } + if (typeof rawValue === 'number') { + return normalizeRolePermissions([ rawValue ]); + } + if (typeof rawValue === 'string') { + const trimmed = rawValue.trim(); + if (!trimmed) return { allAccess: false, permissionIds: [] }; + if (trimmed === '*') return { allAccess: true, permissionIds: [] }; + try { + const parsed = JSON.parse(trimmed); + if (parsed !== rawValue) return normalizeRolePermissions(parsed); + } catch (_) { /* continue */ } + if (trimmed.includes(',')) return normalizeRolePermissions(trimmed.split(',')); + return normalizeRolePermissions([ trimmed ]); + } + return { allAccess: false, permissionIds: [] }; +} + +function serializeRolePermissions(rawValue) { + const state = normalizeRolePermissions(rawValue); + return state.allAccess ? '*' : JSON.stringify(state.permissionIds); +} + +async function main() { + const args = parseArgs(process.argv.slice(2)); + if (args.roleIds.length === 0) { + throw new Error('roleIds 不能为空'); + } + + const cfg = loadConfig(args.configPath); + const dbClient = cfg && cfg.mysql && cfg.mysql.clients && cfg.mysql.clients[args.dbClient]; + if (!dbClient) { + throw new Error(`MySQL client not found in config.mysql.clients: ${args.dbClient}`); + } + + const conn = await mysql.createConnection({ + host: dbClient.host, + port: Number(dbClient.port), + user: dbClient.user, + password: dbClient.password, + database: dbClient.database, + charset: dbClient.charset || 'utf8mb4', + }); + + try { + const [ roleRows ] = await conn.query( + 'SELECT id, role_code, role_name, permissions FROM wms_role WHERE id IN (?) AND deleted_at IS NULL ORDER BY id ASC', + [ args.roleIds ] + ); + + const updates = []; + const skipped = []; + for (const row of roleRows) { + const currentState = normalizeRolePermissions(row.permissions); + if (currentState.allAccess) { + skipped.push({ id: Number(row.id), role_code: row.role_code, reason: 'all_access(*)' }); + continue; + } + const nextIds = Array.from(new Set([ ...currentState.permissionIds, ...INBOX_PERMISSION_IDS ])) + .sort((a, b) => a - b); + const nextValue = JSON.stringify(nextIds); + const currentValue = serializeRolePermissions(row.permissions); + if (nextValue !== currentValue) { + const addedIds = nextIds.filter(id => !currentState.permissionIds.includes(id)); + updates.push({ + roleId: Number(row.id), + roleCode: row.role_code || '', + roleName: row.role_name || '', + addedCount: addedIds.length, + beforeCount: currentState.permissionIds.length, + afterCount: nextIds.length, + before: currentValue, + after: nextValue, + }); + } + } + + console.log(`[backfill-inbox-permissions] 目标角色=${args.roleIds.join(',')},inbox 权限=${INBOX_PERMISSION_IDS.length} 项`); + console.log(`跳过(全量标记): ${skipped.length ? JSON.stringify(skipped) : '无'}`); + + if (args.dryRun) { + console.log('[dry-run] 将更新的角色:'); + for (const item of updates) { + console.log(` role ${item.roleId} ${item.roleName}(${item.roleCode}): +${item.addedCount} 项 inbox 权限(${item.beforeCount} → ${item.afterCount})`); + } + if (updates.length === 0) console.log(' (无变化,所有角色已含 inbox 权限)'); + return; + } + + if (updates.length === 0) { + console.log('无需更新,所有目标角色已包含 inbox 权限'); + return; + } + + await conn.beginTransaction(); + try { + for (const item of updates) { + await conn.query( + 'UPDATE wms_role SET permissions = ?, updated_at = NOW() WHERE id = ?', + [ item.after, item.roleId ] + ); + } + await conn.commit(); + } catch (error) { + await conn.rollback(); + throw error; + } + + console.log('[applied] 更新结果:'); + for (const item of updates) { + console.log(` role ${item.roleId} ${item.roleName}(${item.roleCode}): ${item.beforeCount} → ${item.afterCount} 项权限`); + } + + // 回读验证 + const [ verifyRows ] = await conn.query( + 'SELECT id, role_name, permissions FROM wms_role WHERE id IN (?) AND deleted_at IS NULL ORDER BY id ASC', + [ args.roleIds ] + ); + console.log('[verify] 回读校验:'); + for (const row of verifyRows) { + const state = normalizeRolePermissions(row.permissions); + const hasAllInbox = state.allAccess || INBOX_PERMISSION_IDS.every(id => state.permissionIds.includes(id)); + console.log(` role ${row.id} ${row.role_name}: ${state.allAccess ? '*(全量)' : `${state.permissionIds.length} 项`},inbox 权限完整=${hasAllInbox}`); + } + } finally { + await conn.end(); + } +} + +main().catch(error => { + console.error('[backfill-inbox-permissions] failed:', error.message); + process.exit(1); +}); From 3817948b355adefc28d0f1324a564a16943bc490 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Tue, 18 Aug 2026 16:25:12 +0800 Subject: [PATCH 225/550] =?UTF-8?q?feat(order):=20=E9=94=81=E5=AE=9A?= =?UTF-8?q?=E8=AE=A2=E5=8D=95=E4=BD=9C=E4=B8=9A=E9=97=A8=E7=A6=81=E4=B8=8E?= =?UTF-8?q?=E8=AE=A2=E5=8D=95=E5=88=97=E8=A1=A8=20lock=5Fstatus=20?= =?UTF-8?q?=E8=BD=AC=20Y/N?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - lock_guard: 新增 isLockedOrderStatus,lock_status 非 none 一律视为已锁定 - 储位分配(allocatePicking)跳过锁定订单,skipped_reason=locked - 快递分配(createWaybillCodePipeline、wave.batchAllocateExpress)跳过锁定订单并返回 skipped_locked_order_ids - 抓取波次 singleFetchByIds 排除锁定订单并返回 excluded_locked_order_ids - 自动加团(delivery_order)锁定订单跳过自动分配快递/储位/自动加团 - 订单列表 normalizeOrderListItem 统一 lock_status 输出 Y/N(none→N,其余→Y) - 同步 methods/system.json、methods/changes/system.json 文档 --- app/lib/lock_guard.js | 29 ++ app/service/systemMethods/order/base.js | 23 ++ app/service/systemMethods/order/wave.js | 53 ++- app/service/systems/delivery_order.js | 21 +- app/service/systems/express.js | 37 +- .../systems/order_storage_allocation.js | 16 + methods/changes/system.json | 77 ++++ methods/system.json | 328 ++++++++++++++++-- script/update-api-doc.cjs | 5 +- 9 files changed, 537 insertions(+), 52 deletions(-) create mode 100644 app/lib/lock_guard.js diff --git a/app/lib/lock_guard.js b/app/lib/lock_guard.js new file mode 100644 index 0000000..d1ef960 --- /dev/null +++ b/app/lib/lock_guard.js @@ -0,0 +1,29 @@ +'use strict'; + +/** + * 订单锁定状态共享定义。 + * + * wms_order_delivery.lock_status 枚举(order_delivery.js / order_delivery_factory.js)实际取值为: + * none / warehouse / store。 + * + * 业务约定:锁定状态只要不是 'none'(即被仓库或货主锁定的订单),一律视为"已锁定", + * 禁止继续执行仓储作业(分配储位/分配快递/抓取波次/自动加团等), + * 已锁定订单一律跳过。 + */ +const LOCK_STATUS_NONE = 'none'; + +/** + * 判断订单锁定状态是否属于"已锁定"。 + * 空值/NULL 归一化为 none 处理;除此之外任何非 none 状态(含 warehouse/store)均视为已锁定。 + * @param {*} status 锁定状态值。 + * @return {boolean} 是否已锁定。 + */ +function isLockedOrderStatus(status) { + const normalizedStatus = String(status || '').trim() || LOCK_STATUS_NONE; + return normalizedStatus !== LOCK_STATUS_NONE; +} + +module.exports = { + LOCK_STATUS_NONE, + isLockedOrderStatus, +}; diff --git a/app/service/systemMethods/order/base.js b/app/service/systemMethods/order/base.js index 8353f85..64dbe36 100644 --- a/app/service/systemMethods/order/base.js +++ b/app/service/systemMethods/order/base.js @@ -3,6 +3,7 @@ const MainService = require('../../main'); const { parseWhereConditions } = require('../../../lib/query_condition_parser'); const { isInterceptedOrderStatus } = require('../../../lib/intercept_guard'); +const { isLockedOrderStatus } = require('../../../lib/lock_guard'); const DEFAULT_PAGE_SIZE = 20; const MAX_PAGE_SIZE = 500; @@ -208,6 +209,16 @@ class OrderBaseService extends MainService { return isInterceptedOrderStatus(status); } + /** + * 判断订单锁定状态是否属于"已锁定"(lock_status != none)。 + * + * @param {*} status 锁定状态值。 + * @return {boolean} 是否已锁定。 + */ + isLockedOrderStatus(status = '') { + return isLockedOrderStatus(status); + } + /** * 断言订单未进入拦截流程,否则抛出阻断异常。 * @@ -567,6 +578,17 @@ class OrderBaseService extends MainService { return Number.isNaN(numericVersion) ? strategyVersion : numericVersion; } + /** + * 规范化订单锁定状态展示值。 + * none 返回 N,其余状态(warehouse/store 等)一律返回 Y。 + * @param {*} lockStatus 锁定状态值。 + * @return {string} Y 或 N。 + */ + normalizeLockStatusFlag(lockStatus) { + const normalizedStatus = String(lockStatus || '').trim() || 'none'; + return normalizedStatus === 'none' ? 'N' : 'Y'; + } + /** * 规范订单列表单行输出,保证重量类型直接返回中文。 * @param {Object} order 订单列表行数据。 @@ -585,6 +607,7 @@ class OrderBaseService extends MainService { wave_strategy_version: this.normalizeWaveStrategyVersion(order.wave_strategy_version), wave_scan_result: this.normalizeWaveScanResult(order.wave_scan_result), create_channel: this.formatCreateChannelLabel(order.create_channel), + lock_status: this.normalizeLockStatusFlag(order.lock_status), }; } diff --git a/app/service/systemMethods/order/wave.js b/app/service/systemMethods/order/wave.js index 0f2e84b..cb21d9c 100644 --- a/app/service/systemMethods/order/wave.js +++ b/app/service/systemMethods/order/wave.js @@ -6800,7 +6800,7 @@ class WaveService extends OrderBaseService { try { const orderRows = await orderModel.findAll({ - attributes: [ 'id', 'wave_id', 'wave_no', 'step', 'status', 'outbound_status', 'items_hash', 'items', 'logistics_name', 'intercept_status' ], + attributes: [ 'id', 'wave_id', 'wave_no', 'step', 'status', 'outbound_status', 'items_hash', 'items', 'logistics_name', 'intercept_status', 'lock_status' ], where: { id: { [Op.in]: normalizedIds }, }, @@ -6824,6 +6824,11 @@ class WaveService extends OrderBaseService { .map(row => Number(row && row.id || 0)) .filter(id => Number.isInteger(id) && id > 0)) ] .sort((a, b) => a - b); + const excludedLockedOrderIds = [ ...new Set(normalizedOrderRows + .filter(row => this.isLockedOrderStatus(row && row.lock_status)) + .map(row => Number(row && row.id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ] + .sort((a, b) => a - b); const fetchableRows = normalizedOrderRows.filter(row => { const orderId = Number(row && row.id || 0); @@ -6842,6 +6847,11 @@ class WaveService extends OrderBaseService { return false; } + // 已锁定的订单不允许抓取波次 + if (this.isLockedOrderStatus(row && row.lock_status)) { + return false; + } + return true; }); @@ -6862,6 +6872,7 @@ class WaveService extends OrderBaseService { fetched_order_count: 0, excluded_existing_wave_order_ids: excludedExistingWaveOrderIds, excluded_intercepted_order_ids: excludedInterceptedOrderIds, + excluded_locked_order_ids: excludedLockedOrderIds, skipped_order_ids: skippedOrderIds, not_found_order_ids: notFoundOrderIds, }); @@ -6976,6 +6987,7 @@ class WaveService extends OrderBaseService { fetched_order_count: grabbedOrderIds.length, excluded_existing_wave_order_ids: excludedExistingWaveOrderIds, excluded_intercepted_order_ids: excludedInterceptedOrderIds, + excluded_locked_order_ids: excludedLockedOrderIds, skipped_order_ids: skippedOrderIds, not_found_order_ids: notFoundOrderIds, }); @@ -8804,7 +8816,7 @@ class WaveService extends OrderBaseService { try { orderRows = await orderModel.findAll({ - attributes: [ 'id', 'business_key', 'intercept_status' ], + attributes: [ 'id', 'business_key', 'intercept_status', 'lock_status' ], where: baseOrderWhere, raw: true, }); @@ -8820,7 +8832,7 @@ class WaveService extends OrderBaseService { warehouseId, }); orderRows = await orderModel.findAll({ - attributes: [ 'id', 'intercept_status' ], + attributes: [ 'id', 'intercept_status', 'lock_status' ], where: baseOrderWhere, raw: true, }); @@ -8850,10 +8862,27 @@ class WaveService extends OrderBaseService { }); } + const skippedLockedOrderIds = [ ...new Set((Array.isArray(orderRows) ? orderRows : []) + .filter(row => this.isLockedOrderStatus(row && row.lock_status)) + .map(row => Number(row && row.id || 0)) + .filter(orderId => Number.isInteger(orderId) && orderId > 0)) ] + .sort((a, b) => a - b); + const skippedLockedOrderIdSet = new Set(skippedLockedOrderIds); + if (skippedLockedOrderIds.length > 0) { + this.ctx.logger.info('[wave.batchAllocateExpress] 跳过锁定订单', { + traceId, + taskId: normalizedTaskId, + warehouseId, + skippedLockedOrderIds, + }); + } + const normalizedOrders = (Array.isArray(orderRows) ? orderRows : []) .map(row => { const orderId = Number(row && row.id || 0); - if (!Number.isInteger(orderId) || orderId <= 0 || skippedInterceptedOrderIdSet.has(orderId)) { + if (!Number.isInteger(orderId) || orderId <= 0 + || skippedInterceptedOrderIdSet.has(orderId) + || skippedLockedOrderIdSet.has(orderId)) { return null; } @@ -8872,6 +8901,7 @@ class WaveService extends OrderBaseService { warehouseId, waveIds, skippedInterceptedOrderIds, + skippedLockedOrderIds, }); const durationMs = Date.now() - startTime; await this.setBatchAllocateExpressTaskProgress(normalizedTaskId, 'success', { @@ -8882,6 +8912,7 @@ class WaveService extends OrderBaseService { success_order_count: 0, failed_order_count: 0, skipped_intercepted_order_ids: skippedInterceptedOrderIds, + skipped_locked_order_ids: skippedLockedOrderIds, progress_percent: 100, end_time: Date.now(), duration_ms: durationMs, @@ -8889,9 +8920,10 @@ class WaveService extends OrderBaseService { wave_ids: waveIds, allocated_order_count: 0, skipped_intercepted_order_ids: skippedInterceptedOrderIds, + skipped_locked_order_ids: skippedLockedOrderIds, duration_ms: durationMs, - message: skippedInterceptedOrderIds.length > 0 - ? `拦截订单已跳过,未找到可分配快递号的订单(跳过 ${skippedInterceptedOrderIds.length} 单)` + message: skippedInterceptedOrderIds.length > 0 || skippedLockedOrderIds.length > 0 + ? `拦截/锁定订单已跳过,未找到可分配快递号的订单(拦截 ${skippedInterceptedOrderIds.length} 单,锁定 ${skippedLockedOrderIds.length} 单)` : '未找到可分配快递号的订单', }, trace_id: traceId, @@ -8935,6 +8967,7 @@ class WaveService extends OrderBaseService { success_order_count: normalizedOrders.length, failed_order_count: 0, skipped_intercepted_order_ids: skippedInterceptedOrderIds, + skipped_locked_order_ids: skippedLockedOrderIds, progress_percent: 100, end_time: Date.now(), duration_ms: durationMs, @@ -8942,6 +8975,7 @@ class WaveService extends OrderBaseService { wave_ids: waveIds, allocated_order_count: normalizedOrders.length, skipped_intercepted_order_ids: skippedInterceptedOrderIds, + skipped_locked_order_ids: skippedLockedOrderIds, duration_ms: durationMs, message: String(pipelineResult && pipelineResult.message || '分配快递任务已提交').trim(), }, @@ -9054,7 +9088,7 @@ class WaveService extends OrderBaseService { try { const orderModel = await this.getOrderModel('pendingOrder', warehouseId); const orderRows = await orderModel.findAll({ - attributes: [ 'id' ], + attributes: [ 'id', 'lock_status' ], where: { warehouse_id: warehouseId, wave_id: { @@ -9067,9 +9101,14 @@ class WaveService extends OrderBaseService { raw: true, }); + const skippedLockedOrderIdSet = new Set((Array.isArray(orderRows) ? orderRows : []) + .filter(row => this.isLockedOrderStatus(row && row.lock_status)) + .map(row => Number(row && row.id || 0)) + .filter(orderId => Number.isInteger(orderId) && orderId > 0)); const normalizedOrders = [ ...new Set((Array.isArray(orderRows) ? orderRows : []) .map(row => Number(row && row.id || 0)) .filter(orderId => Number.isInteger(orderId) && orderId > 0)) ] + .filter(orderId => !skippedLockedOrderIdSet.has(orderId)) .map(orderId => ({ order_id: orderId, business_id: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_ID, diff --git a/app/service/systems/delivery_order.js b/app/service/systems/delivery_order.js index b4b87fe..eef7854 100644 --- a/app/service/systems/delivery_order.js +++ b/app/service/systems/delivery_order.js @@ -1,6 +1,7 @@ 'use strict'; const Service = require('egg').Service; const { normalizeWarehouseShardId } = require('../../lib/warehouse_shard_guard'); +const { isLockedOrderStatus } = require('../../lib/lock_guard'); const DELIVERY_ORDER_STEP = Object.freeze({ PENDING_REVIEW: 0, @@ -2001,7 +2002,7 @@ class DeliveryOrderService extends Service { id: orderId, warehouse_id: warehouseId, }, - attributes: [ 'id', 'wave_id', 'step', 'status', 'outbound_status' ], + attributes: [ 'id', 'wave_id', 'step', 'status', 'outbound_status', 'lock_status' ], transaction, lock: transaction.LOCK.UPDATE, }); @@ -2010,6 +2011,12 @@ class DeliveryOrderService extends Service { return false; } + // 已锁定的订单不允许自动加团 + if (isLockedOrderStatus(orderRow.lock_status)) { + await transaction.commit(); + return false; + } + const currentWaveId = Number(orderRow.wave_id || 0); if (currentWaveId === normalizedWaveId) { await transaction.commit(); @@ -2057,6 +2064,7 @@ class DeliveryOrderService extends Service { id: orderId, warehouse_id: warehouseId, wave_id: 0, + lock_status: 'none', }, transaction, }); @@ -2139,6 +2147,7 @@ class DeliveryOrderService extends Service { step: { [ctx.app.Sequelize.Op.in]: [ 1, 2, 3 ] }, status: { [ctx.app.Sequelize.Op.ne]: 'cancel' }, outbound_status: { [ctx.app.Sequelize.Op.ne]: 'padding' }, + lock_status: 'none', sys_logistics_code: structure.logisticsName, }; where[structure.itemPartType] = structure.itemPart; @@ -2392,6 +2401,16 @@ class DeliveryOrderService extends Service { return; } + // 已锁定的订单不自动分配快递、储位,不自动加团 + if (isLockedOrderStatus(context.order && context.order.lock_status)) { + this.ctx.logger.info('[DeliveryOrderService.asyncProcessOrderCreated] 订单已锁定,跳过自动分配快递/储位/自动加团', { + warehouseId: context.warehouseId, + orderId: context.orderId, + lockStatus: context.order.lock_status, + }); + return; + } + const policyConfig = await this.getStoreWarehousePolicyConfig(context.storeId, context.warehouseId); // 截单时间兜底:货主-仓库级未启用时,fallback 到仓库级配置 diff --git a/app/service/systems/express.js b/app/service/systems/express.js index 2db92ef..fb97ab2 100644 --- a/app/service/systems/express.js +++ b/app/service/systems/express.js @@ -3,6 +3,7 @@ const { Service } = require('egg'); const { isInterceptedOrderStatus } = require('../../lib/intercept_guard'); +const { isLockedOrderStatus } = require('../../lib/lock_guard'); const DEFAULT_CACHE_TTL_SECONDS = 600; const DEFAULT_EXPRESS_PRODUCT_TYPE_CACHE_TTL_SECONDS = 60 * 60; @@ -2516,7 +2517,7 @@ class ExpressService extends Service { [Op.ne]: 'cancel', }, }, - attributes: [ 'id', 'sys_platform_code', 'logistics_code', 'sys_platform_name', 'logistics_name', 'store_id', 'pay_no', 'from_key', 'intercept_status' ], + attributes: [ 'id', 'sys_platform_code', 'logistics_code', 'sys_platform_name', 'logistics_name', 'store_id', 'pay_no', 'from_key', 'intercept_status', 'lock_status' ], raw: true, }); @@ -2540,7 +2541,7 @@ class ExpressService extends Service { [Op.ne]: 'cancel', }, }, - attributes: [ 'id', 'sys_platform_code', 'logistics_code', 'sys_platform_name', 'logistics_name', 'store_id', 'pay_no', 'from_key', 'intercept_status' ], + attributes: [ 'id', 'sys_platform_code', 'logistics_code', 'sys_platform_name', 'logistics_name', 'store_id', 'pay_no', 'from_key', 'intercept_status', 'lock_status' ], raw: true, }); } @@ -2561,21 +2562,37 @@ class ExpressService extends Service { skippedInterceptedOrderIds, }); } + + // 锁定订单跳过(除 none 外一律视为已锁定,锁定期间不允许分配快递) + const lockedOrderIdSet = new Set(orders_arr + .filter(order => isLockedOrderStatus(order && order.lock_status)) + .map(order => Number(order && order.id || 0)) + .filter(orderId => Number.isInteger(orderId) && orderId > 0)); + const skippedLockedOrderIds = Array.from(lockedOrderIdSet); + const activeOrders = orders_arr.filter(order => !lockedOrderIdSet.has(Number(order && order.id || 0))); + if (skippedLockedOrderIds.length > 0) { + this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 跳过锁定订单', { + traceId, + warehouseId, + skippedLockedOrderIds, + }); + } this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 订单筛选结果', { traceId, warehouseId, inputOrderCount: orderList.length, currentCount: (Array.isArray(currentOrders) ? currentOrders : []).length, dispatchCount: dispatchOrders.length, - matchedOrderCount: orders_arr.length, + matchedOrderCount: activeOrders.length, skippedInterceptedOrderIds, + skippedLockedOrderIds, }); // 【step1.5】过滤已分配运单号(status=1)且传入 business_key=1 的订单,避免重复分配。 const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; - let filteredOrdersArr = orders_arr; - if (orderExpressModel && orders_arr.length > 0) { - const orderIds = orders_arr.map(o => Number(o.id)).filter(id => id > 0); + let filteredOrdersArr = activeOrders; + if (orderExpressModel && activeOrders.length > 0) { + const orderIds = activeOrders.map(o => Number(o.id)).filter(id => id > 0); const completedRows = await orderExpressModel.findAll({ where: { order_id: { [Op.in]: orderIds }, @@ -2590,8 +2607,8 @@ class ExpressService extends Service { skipSet.add(`${Number(row.order_id)}:${Number(row.business_key)}`); } if (skipSet.size > 0) { - const beforeCount = orders_arr.length; - filteredOrdersArr = orders_arr.filter(order => { + const beforeCount = activeOrders.length; + filteredOrdersArr = activeOrders.filter(order => { const matchedExpress = orderList.find(express => Number(order.id) === Number(express.order_id)); const businessKey = matchedExpress ? Number(matchedExpress.business_key) : 1; if (businessKey === 1 && skipSet.has(`${Number(order.id)}:1`)) { @@ -2603,7 +2620,7 @@ class ExpressService extends Service { this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 跳过已分配运单号(business_key=1)的订单', { traceId, skippedCount: beforeCount - filteredOrdersArr.length, - skippedOrderIds: orders_arr + skippedOrderIds: activeOrders .filter(order => { const matchedExpress = orderList.find(express => Number(order.id) === Number(express.order_id)); const businessKey = matchedExpress ? Number(matchedExpress.business_key) : 1; @@ -2620,6 +2637,7 @@ class ExpressService extends Service { return { message: '所有订单均已分配运单号,无需处理', skipped_intercepted_order_ids: skippedInterceptedOrderIds, + skipped_locked_order_ids: skippedLockedOrderIds, }; } @@ -2725,6 +2743,7 @@ class ExpressService extends Service { return { message: '分配快递任务已提交', skipped_intercepted_order_ids: skippedInterceptedOrderIds, + skipped_locked_order_ids: skippedLockedOrderIds, }; } /** diff --git a/app/service/systems/order_storage_allocation.js b/app/service/systems/order_storage_allocation.js index e3b921c..7d3473f 100644 --- a/app/service/systems/order_storage_allocation.js +++ b/app/service/systems/order_storage_allocation.js @@ -3,6 +3,7 @@ const MainService = require('../main'); const { isInterceptedOrderStatus } = require('../../lib/intercept_guard'); +const { isLockedOrderStatus } = require('../../lib/lock_guard'); const STORAGE_STATUS_FIN = 'fin'; const STORAGE_STATUS_ERROR = 'error'; @@ -645,6 +646,21 @@ class OrderStorageAllocationService extends MainService { continue; } + if (isLockedOrderStatus(orderRow && orderRow.lock_status)) { + skippedOrders.push({ + order_id: orderId, + status: 'skipped', + lock_status: orderRow.lock_status, + skipped_reason: 'locked', + }); + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 过滤订单结果', { + orderId, + lockStatus: orderRow.lock_status, + skippedReason: 'locked', + }); + continue; + } + if (String(orderRow.storage_status || 'none') === STORAGE_STATUS_FIN) { skippedOrders.push({ order_id: orderId, diff --git a/methods/changes/system.json b/methods/changes/system.json index f04174e..cb9ea6e 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,62 @@ [ + { + "version": "2026.08.18-order-lock-status-guard-and-list-yn", + "date": "2026-08-18", + "type": "enhanced", + "summary": "新增锁定订单作业门禁与订单列表 lock_status 转 Y/N:lock_status 非 none(枚举 warehouse/store)的订单在分配储位、分配快递、抓取波次、自动加团等流程中被直接跳过,跳过明细通过 skipped_locked_order_ids / excluded_locked_order_ids / skipped_orders 等字段返回;订单列表 lock_status 统一输出 Y/N(none→N,其余→Y)。", + "methods": [ + "order.pendingOrder.list", + "order.pendingOrder.allocateExpressCode", + "order.pendingOrder.allocateStorage", + "order.wave.singleFetchByIds", + "order.wave.waveStrategyFallbackOrderList", + "order.wave.batchAllocateExpress", + "order.wave.batchAllocateExpressTaskProgress", + "order.wave.batchAllocateStorage", + "order.wave.batchAllocateStorageTaskProgress" + ], + "notes": [ + "新增 app/lib/lock_guard.js isLockedOrderStatus:lock_status 非 'none' 即视为已锁定(枚举 none/warehouse/store)", + "app/service/systems/order_storage_allocation.js allocatePicking:过滤循环新增锁定订单跳过,skipped 记录含 lock_status 与 skipped_reason='locked';order.storageAllocation.allocateStorage / order.pendingOrder.allocateStorage / order.wave.batchAllocateStorage 共用该底层入口", + "app/service/systems/express.js createWaybillCodePipeline:查询新增 lock_status 字段,锁定订单与拦截订单同样剔除,返回结果新增 skipped_locked_order_ids", + "app/service/systemMethods/order/wave.js runBatchAllocateExpressTask:查询新增 lock_status,任务进度与 result 新增 skipped_locked_order_ids;singleFetchByIds 查询属性新增 lock_status 并过滤锁定订单,响应新增 excluded_locked_order_ids(两个返回分支均返回);waveStrategyFallbackOrderList 查询追加 lock_status/intercept_status 非 none 条件,列表行新增 excluded_reason(locked/intercepted/printed/no_match)", + "app/service/systems/delivery_order.js asyncProcessOrderCreated:订单已锁定时跳过自动分配快递/储位/自动加团三步;appendOrderToWave 增加锁定校验且更新波次时 where 追加 lock_status='none';countCandidateGroupOrders 过滤 lock_status='none'(内部流程,无公开接口)", + "app/service/systemMethods/order/base.js 新增 normalizeLockStatusFlag:none(含空值)返回 'N',其余值一律返回 'Y';normalizeOrderListItem 统一覆盖 lock_status 输出为 Y/N,影响 order.pendingOrder.list、order.wave.waveStrategyFallbackOrderList 及经 listByModule 的各类工作台订单列表", + "同步更新 methods/system.json 中上述 method 的 description 与 response 字段" + ], + "module": "order" + }, + { + "version": "2026.08.18-storage.entry.addItem-non-binding", + "date": "2026-08-18", + "type": "fixed", + "summary": "库存导入(storage.entry.addItem 导入/PDA 入库)不再强制绑定收货单:原 PENDING 状态下未绑定收货单拒绝上架、每项缺少 receiving_detail_id 拒绝,导致移除绑定收货单后仍限制必须传入收货单 ID。现 PENDING 状态允许不绑定收货单直接导入(非绑定模式,数量受计划数量限制),传 receiving_detail_id 时仍走绑定模式(预占收货明细)", + "methods": [ + "storage.entry.addItem" + ], + "notes": [ + "app/service/systems/inbound_direct_log.js addItem:删除 PENDING 状态下 hasReceivingBindings 与 receiving_detail_id 的强制校验,绑定模式 space_id/可用数量校验仍由 _addSingleItem 统一处理;CREATED 已绑定收货单需先审核的限制保留", + "PENDING 非绑定模式导入数量仍受计划数量限制(isManualImport 仅 CREATED 且非绑定可超计划),防止超计划入库", + "同步更新 methods/system.json 中 storage.entry.addItem 的 description、receiving_detail_id 参数说明与错误码列表(移除两条 PENDING 绑定错误码)" + ], + "module": "storage.entry" + }, + { + "version": "2026.08.18-recheckOrder.scanOrder.singleIntercept", + "date": "2026-08-18", + "type": "fixed", + "summary": "修复 order.recheckOrder.scanOrder 散单模式拦截订单识别:原逻辑对波次内所有订单执行复核校验,只要波次内存在一单已进入拦截流程(requested/requesting/intercepting/intercepted_in_transit/intercepted_at_warehouse,历史值 intercepted 兼容),整个散单扫描视图即报错「订单已被拦截,无法提交复核」,导致波次内其他正常订单也无法复核。现拦截订单保留在 list 中按单提示(intercept_status),不再阻断整个扫描视图加载,且不计入复核/打印统计", + "methods": [ + "order.recheckOrder.scanOrder", + "order.recheckOrder.scanTask" + ], + "notes": [ + "buildSingleWaveScanView:用 isInterceptedOrderStatus 分离拦截订单,仅非拦截订单参与 assertOrderCanRecheck 校验与 reviewed/unreviewed/printed/unprinted 统计,拦截订单保留在 list 中按单提示", + "车号/任务模式(cart/task)合并多个波次后,reviewed_count/unreviewed_count 仅统计非拦截订单,total_orders 仍为订单总数", + "同步更新 methods/system.json 中 scanOrder 散单订单项 intercept_status 字段说明" + ], + "module": "order" + }, { "version": "2026.08.17-inbox-group-reset", "date": "2026-08-17", @@ -6226,5 +6284,24 @@ "退回查询 _resolveReturnOrderInfo 优先主表快照,空时实时兜底(交易单号→原运单/原订单,店铺→store_remask)" ], "module": "returnUnpack" + }, + { + "version": "2026.08.18-storeWarehouse-sign-confirmSign-doc", + "date": "2026-08-18", + "type": "added", + "summary": "补齐 storeWarehouse 签约接口文档(纯文档补全,无业务代码变更):新增 storeWarehouse.store.confirmSign(货主侧确认签约)、storeWarehouse.warehouse.sign(仓库侧发起签约)、storeWarehouse.warehouse.confirmSign(仓库侧确认签约)三个方法的入参/出参/错误码说明。", + "methods": [ + "storeWarehouse.store.confirmSign", + "storeWarehouse.warehouse.sign", + "storeWarehouse.warehouse.confirmSign" + ], + "notes": [ + "storeWarehouse.store.confirmSign:当前主体作为对方主体确认待签约申请,auth_status 由 1(申请中)变更为 2(已通过);入参 id(兼容 contract_id);400=id 缺失或签约状态非待签约、403=当前主体不在签约关系中或发起方自确认、404=签约关系不存在;响应 data.mode=confirm 与 data.contract 精简对象(id/store_id/warehouse_id/counterparty_name/remask/use_status/auth_status/auth_status_label/auth_end/print_quantity/has_qimen_config)", + "storeWarehouse.warehouse.sign:仓库侧发起签约,当前仓库在 store_id 方、对方在 warehouse_id 方,支持签约外部合作仓库;入参 counterparty_id(兼容 warehouse_id / store_id),当前主体自动识别;响应 data.mode=initiate/already_exists/already_confirmed 与 data.contract;400=对方主体缺失/日期非法,404=签约对象不存在", + "storeWarehouse.warehouse.confirmSign:仓库侧确认签约,校验逻辑与货主侧确认一致(400/403/404 同 storeWarehouse.store.confirmSign)", + "代码对齐:app/service/systemMethods/storeWarehouse/store.js#confirmSign、app/service/systemMethods/storeWarehouse/warehouse.js#sign/#confirmSign 均已注册(_noNeedAuth 含三个方法,isNeedAuth=false、isNeedLogin=true);实现位于 app/service/systems/store_warehouse.js#sign/#confirmSign;权限表 method id 397「签约确定」", + "仅文档变更,无业务代码修改" + ], + "module": "storeWarehouse" } ] diff --git a/methods/system.json b/methods/system.json index 20fd2f4..0c531be 100644 --- a/methods/system.json +++ b/methods/system.json @@ -2960,7 +2960,7 @@ "name": "list", "type": "array", "required": true, - "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节),本次新增 store_remark(货主备注)字段。" + "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节),本次新增 store_remark(货主备注)字段。lock_status 字段统一输出为 Y/N:none(含空值)→ 'N',其余值(如 warehouse/store)→ 'Y'。" }, { "name": "pagination", @@ -3280,7 +3280,7 @@ }, { "method": "order.pendingOrder.allocateExpressCode", - "description": "批量分配待处理订单的首单快递号(异步接口)。调用后立即返回 task_id,后台异步执行运单创建;可通过 order.pendingOrder.allocateExpressCodeTaskProgress 查询进度。拆单场景请使用 order.pendingOrder.allocateSubOrderNumber。", + "description": "批量分配待处理订单的首单快递号(异步接口)。调用后立即返回 task_id,后台异步执行运单创建;可通过 order.pendingOrder.allocateExpressCodeTaskProgress 查询进度。拆单场景请使用 order.pendingOrder.allocateSubOrderNumber。已锁定订单(lock_status 非 none)与拦截订单同样在流水线中被跳过、不参与分配,任务结果(allocateExpressCodeTaskProgress)中包含 skipped_locked_order_ids 等跳过明细。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -3339,7 +3339,7 @@ }, { "method": "order.pendingOrder.allocateStorage", - "description": "按订单批量分配储位(迁移自 order.storageAllocation.allocateStorage)。这是一个异步提交接口:调用后接口立即返回受理信息(包含 request_id),后端异步执行实际的储位分配与锁定操作;仓库上下文由当前登录用户提供(ctx.user.store_id)。接口不会在同步响应中返回分配明细(如 requested_order_ids、allocated_order_ids 等),客户端可通过请求 ID 或事件/查询链路获取最终结果。", + "description": "按订单批量分配储位(迁移自 order.storageAllocation.allocateStorage)。这是一个异步提交接口:调用后接口立即返回受理信息(包含 request_id),后端异步执行实际的储位分配与锁定操作;仓库上下文由当前登录用户提供(ctx.user.store_id)。接口不会在同步响应中返回分配明细(如 requested_order_ids、allocated_order_ids 等),客户端可通过请求 ID 或事件/查询链路获取最终结果。已锁定订单(lock_status 非 none)会在分配流水线中被跳过(底层分配结果 skipped_orders 中记录 skipped_reason='locked')。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -5568,7 +5568,7 @@ { "name": "intercept_status", "type": "string", - "description": "[散单有波次] 拦截状态(requested / intercepted_at_warehouse / 空字符串)" + "description": "[散单有波次] 拦截状态(requested / requesting / intercepting / intercepted_in_transit / intercepted_at_warehouse / 历史值 intercepted / 空字符串)。已拦截订单保留在 list 中按单提示,不阻断整个扫描视图,且不计入 reviewed_count / unreviewed_count / printed_count / unprinted_count 统计" }, { "name": "stock", @@ -8304,7 +8304,7 @@ }, { "method": "order.wave.singleFetchByIds", - "description": "按订单 ID 列表抓取到一个散单波次。仅处理当前仓库的待处理订单(step in [1,2,3]),排除已在波次中的订单(wave_id>0),不区分快递;成功抓取后批量写入订单操作日志;当无可抓取订单时返回 wave_id=0。", + "description": "按订单 ID 列表抓取到一个散单波次。仅处理当前仓库的待处理订单(step in [1,2,3]),排除已在波次中的订单(wave_id>0),不区分快递;成功抓取后批量写入订单操作日志;当无可抓取订单时返回 wave_id=0。已锁定订单(lock_status 非 none)不允许抓取波次,返回 excluded_locked_order_ids。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -8361,6 +8361,12 @@ "required": false, "description": "原始入参中已在其它波次中的订单 ID(被排除,不会被抓取)" }, + { + "name": "excluded_locked_order_ids", + "type": "array", + "required": false, + "description": "因已锁定(lock_status 非 none)被排除、不会被抓取波次的订单 ID 列表(成功与无可抓取订单两个返回分支均返回)" + }, { "name": "skipped_order_ids", "type": "array", @@ -8377,17 +8383,17 @@ "errors": [ { "code": "400", - "description": "未识别到当前仓库上下文或 ids 参数不能为空或格式错误;当入参包含非法字段或别名冲突时也会返回 400" + "message": "未识别到当前仓库上下文或 ids 参数不能为空或格式错误;当入参包含非法字段或别名冲突时也会返回 400" }, { "code": "500", - "description": "抓取失败或内部错误" + "message": "抓取失败或内部错误" } ] }, { "method": "order.wave.waveStrategyFallbackOrderList", - "description": "基于波次策略的回退候选订单列表。该接口内置固定筛选条件:step != 0、wave_id = 0、wave_scan_result = 2。用于展示策略未命中但需回退处理的订单候选。", + "description": "基于波次策略的回退候选订单列表。该接口内置固定筛选条件:step != 0、wave_id = 0,且满足以下任一条件:wave_scan_result = 2(未匹配任何波次策略)、print_status = 'fin'(已完全打印)、lock_status != 'none'(订单已锁定)、intercept_status != 'none'(订单已拦截)。用于展示策略未命中或需回退处理的订单候选。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -8419,7 +8425,7 @@ "name": "list", "type": "array", "required": true, - "description": "回退候选订单简要列表。数组内对象字段说明见 children。", + "description": "回退候选订单简要列表。数组内对象字段说明见 children;每行含 excluded_reason 标记:locked=订单已锁定(lock_status 非 none)、intercepted=订单已拦截、printed=已完全打印、no_match=未匹配任何波次策略。", "children": [ { "name": "id", @@ -8480,6 +8486,11 @@ "name": "item_snapshot", "type": "string", "description": "商品快照,格式示例:苹果*2|香蕉*3" + }, + { + "name": "excluded_reason", + "type": "string", + "description": "订单进入回退列表的原因枚举:locked(已锁定,lock_status 非 none)/ intercepted(已拦截)/ printed(已完全打印)/ no_match(未匹配任何波次策略)" } ] }, @@ -9189,7 +9200,7 @@ }, { "method": "order.wave.batchAllocateExpress", - "description": "提交批次分配快递号任务。该接口为异步任务提交接口,立即返回 task_id,后端异步按当前仓库 + wave_ids 拉取待处理订单并提交到快递号分配流水线。", + "description": "提交批次分配快递号任务。该接口为异步任务提交接口,立即返回 task_id,后端异步按当前仓库 + wave_ids 拉取待处理订单并提交到快递号分配流水线。已锁定订单(lock_status 非 none)与拦截订单在任务中被跳过、不参与分配,跳过明细见任务进度(batchAllocateExpressTaskProgress)的 skipped_locked_order_ids。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -9251,21 +9262,21 @@ "errors": [ { "code": "400", - "description": "未识别到当前仓库上下文" + "message": "未识别到当前仓库上下文" }, { "code": "400", - "description": "wave_ids 参数不能为空或格式错误" + "message": "wave_ids 参数不能为空或格式错误" }, { "code": "500", - "description": "任务提交失败或内部错误" + "message": "任务提交失败或内部错误" } ] }, { "method": "order.wave.batchAllocateExpressTaskProgress", - "description": "查询批次分配快递号任务进度:按 task_id 查询任务状态与统计信息;兼容 taskId 参数名。", + "description": "查询批次分配快递号任务进度:按 task_id 查询任务状态与统计信息;兼容 taskId 参数名。已锁定订单(lock_status 非 none)被跳过,任务进度与 result 中包含 skipped_locked_order_ids(因已锁定被跳过的订单 ID)。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -9334,6 +9345,12 @@ "required": false, "description": "提交分配失败的订单数量" }, + { + "name": "skipped_locked_order_ids", + "type": "array", + "required": false, + "description": "因已锁定(lock_status 非 none)被跳过、未参与快递号分配的订单 ID 列表(任务进度与 result 中均返回)" + }, { "name": "progress_percent", "type": "number", @@ -9362,11 +9379,11 @@ "errors": [ { "code": "400", - "description": "task_id 参数不能为空" + "message": "task_id 参数不能为空" }, { "code": "500", - "description": "查询失败或内部错误" + "message": "查询失败或内部错误" } ] }, @@ -9555,7 +9572,7 @@ }, { "method": "order.wave.batchAllocateStorage", - "description": "提交批次分配储位任务。该接口为异步任务提交接口,立即返回 task_id,后端异步按当前仓库 + wave_ids 拉取待处理订单并提交到储位分配流水线。", + "description": "提交批次分配储位任务。该接口为异步任务提交接口,立即返回 task_id,后端异步按当前仓库 + wave_ids 拉取待处理订单并提交到储位分配流水线。已锁定订单(lock_status 非 none)在任务中被直接跳过、不参与储位分配。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -9617,21 +9634,21 @@ "errors": [ { "code": "400", - "description": "未识别到当前仓库上下文" + "message": "未识别到当前仓库上下文" }, { "code": "400", - "description": "wave_ids 参数不能为空或格式错误" + "message": "wave_ids 参数不能为空或格式错误" }, { "code": "500", - "description": "任务提交失败或内部错误" + "message": "任务提交失败或内部错误" } ] }, { "method": "order.wave.batchAllocateStorageTaskProgress", - "description": "查询批次分配储位任务进度:按 task_id 查询任务状态与统计信息;兼容 taskId 参数名。", + "description": "查询批次分配储位任务进度:按 task_id 查询任务状态与统计信息;兼容 taskId 参数名。已锁定订单(lock_status 非 none)被直接跳过,不计入 total_order_count 等统计。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -9728,11 +9745,11 @@ "errors": [ { "code": "400", - "description": "task_id 参数不能为空" + "message": "task_id 参数不能为空" }, { "code": "500", - "description": "查询失败或内部错误" + "message": "查询失败或内部错误" } ] }, @@ -21501,7 +21518,7 @@ }, { "method": "storage.entry.addItem", - "description": "按商品增量添加导入/PDA 入库记录(支持单条和批量)。单条模式传 stock_id/quantity/inbound_type/remark,批量模式传 items 数组。批量模式所有商品共享同一个入库单状态校验,任一商品校验失败整批拒绝。若某商品累计入库量超过计划数量则拒绝(PENDING 非绑定模式)。PENDING 状态需传 receiving_detail_id 绑定收货明细;CREATED 人工导入允许超过计划数量;传入 receiving_detail_id 时 quantity 可选(自动计算可用数量),space_id 必填。", + "description": "按商品增量添加导入/PDA 入库记录(支持单条和批量)。单条模式传 stock_id/quantity/inbound_type/remark,批量模式传 items 数组。批量模式所有商品共享同一个入库单状态校验,任一商品校验失败整批拒绝。若某商品累计入库量超过计划数量则拒绝(PENDING 非绑定模式)。PENDING 状态可传 receiving_detail_id 绑定收货明细(不传则走非绑定模式,数量受计划数量限制),不再强制绑定收货单、不再强制传收货单 ID;CREATED 人工导入允许超过计划数量;传入 receiving_detail_id 时 quantity 可选(自动计算可用数量),space_id 必填。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -21560,7 +21577,7 @@ "type": "number", "required": false, "source": "body", - "description": "收货单明细ID(PDA 上架绑定模式),传入后触发收货明细预占绑定,quantity 自动计算" + "description": "收货单明细ID(PDA 上架绑定模式),传入后触发收货明细预占绑定,quantity 自动计算;不传则按非绑定模式直接导入,不要求绑定收货单" }, { "name": "allocated_quantity", @@ -21674,14 +21691,6 @@ "code": 400, "message": "入库单已绑定收货单且状态为 CREATED,请先审核后再进行上架操作" }, - { - "code": 400, - "message": "入库单未绑定收货单,无法上架(PENDING)" - }, - { - "code": 400, - "message": "随机入库需要选定收货单明细提交,缺少 receiving_detail_id(PENDING)" - }, { "code": 400, "message": "绑定收货明细时必须指定 space_id" @@ -25720,6 +25729,131 @@ } ], "errors": [] + }, + { + "method": "storeWarehouse.store.confirmSign", + "description": "确认签约:当前主体作为对方主体确认待签约的申请,签约状态从 1(申请中)变为 2(已通过);发起方不能确认自己的申请", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "签约关系ID,兼容 contract_id" + } + ], + "response": [ + { + "name": "data.mode", + "type": "string", + "required": true, + "description": "确认模式标识,固定为 confirm" + }, + { + "name": "data.contract", + "type": "object", + "required": true, + "description": "签约关系精简对象" + }, + { + "name": "data.contract.id", + "type": "number", + "required": true, + "description": "签约关系主键 ID" + }, + { + "name": "data.contract.store_id", + "type": "number", + "required": true, + "description": "货主方主体 ID" + }, + { + "name": "data.contract.warehouse_id", + "type": "number", + "required": true, + "description": "仓库方主体 ID" + }, + { + "name": "data.contract.counterparty_name", + "type": "string", + "required": true, + "description": "对方主体名称" + }, + { + "name": "data.contract.remask", + "type": "string", + "required": true, + "description": "当前主体视角的签约备注名" + }, + { + "name": "data.contract.use_status", + "type": "number", + "required": true, + "description": "当前主体启用状态:0=禁用 1=启用" + }, + { + "name": "data.contract.auth_status", + "type": "number", + "required": true, + "description": "签约状态:1=申请中 2=已通过 3=已拒绝 4=已解除 5=已过期" + }, + { + "name": "data.contract.auth_status_label", + "type": "string", + "required": true, + "description": "签约状态中文标签" + }, + { + "name": "data.contract.auth_end", + "type": "string|null", + "required": true, + "description": "授权结束时间" + }, + { + "name": "data.contract.print_quantity", + "type": "number", + "required": true, + "description": "面单余额数量" + }, + { + "name": "data.contract.has_qimen_config", + "type": "boolean", + "required": true, + "description": "是否已配置奇门" + } + ], + "errors": [ + { + "code": 400, + "message": "id 参数不能为空" + }, + { + "code": 400, + "message": "当前签约状态不允许确认,仅待签约状态可确认" + }, + { + "code": 403, + "message": "当前主体不在此签约关系中" + }, + { + "code": 403, + "message": "发起方不能确认自己的签约申请" + }, + { + "code": 404, + "message": "签约关系不存在" + } + ] } ] }, @@ -25912,6 +26046,134 @@ "message": "获取签约列表失败" } ] + }, + { + "method": "storeWarehouse.warehouse.sign", + "description": "仓库侧发起签约(当前仓库在 store_id 方,对方在 warehouse_id 方,支持签约外部合作仓库)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "counterparty_id", + "type": "number", + "required": true, + "source": "body", + "description": "对方主体 ID(兼容 warehouse_id / store_id),当前主体自动识别" + } + ], + "response": [ + { + "name": "data.mode", + "type": "string", + "required": true, + "description": "签约结果模式:initiate=新建或更新签约申请,already_exists=已存在待确认的签约关系,already_confirmed=已签约" + }, + { + "name": "data.contract", + "type": "object", + "required": true, + "description": "签约关系精简对象(data.mode 非空时返回)" + }, + { + "name": "data.action", + "type": "string", + "required": false, + "description": "initiate 模式下的操作类型:create=新建签约申请,update=更新已有申请" + } + ], + "errors": [ + { + "code": 400, + "message": "counterparty_id / 对方主体ID 参数不能为空" + }, + { + "code": 400, + "message": "counterparty_id / 对方主体ID 参数不合法" + }, + { + "code": 400, + "message": "auth_start 参数不合法" + }, + { + "code": 400, + "message": "auth_end 参数不合法" + }, + { + "code": 400, + "message": "auth_end 不能早于 auth_start" + }, + { + "code": 404, + "message": "签约对象不存在" + } + ] + }, + { + "method": "storeWarehouse.warehouse.confirmSign", + "description": "仓库侧确认签约:作为对方主体确认待签约申请,签约状态从 1(申请中)变为 2(已通过);发起方不能确认自己的申请", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "签约关系ID,兼容 contract_id" + } + ], + "response": [ + { + "name": "data.mode", + "type": "string", + "required": true, + "description": "确认模式标识,固定为 confirm" + }, + { + "name": "data.contract", + "type": "object", + "required": true, + "description": "签约关系精简对象,字段同 storeWarehouse.store.confirmSign 的 data.contract" + } + ], + "errors": [ + { + "code": 400, + "message": "id 参数不能为空" + }, + { + "code": 400, + "message": "当前签约状态不允许确认,仅待签约状态可确认" + }, + { + "code": 403, + "message": "当前主体不在此签约关系中" + }, + { + "code": 403, + "message": "发起方不能确认自己的签约申请" + }, + { + "code": 404, + "message": "签约关系不存在" + } + ] } ] }, diff --git a/script/update-api-doc.cjs b/script/update-api-doc.cjs index 288cc9a..8efdc35 100644 --- a/script/update-api-doc.cjs +++ b/script/update-api-doc.cjs @@ -312,7 +312,8 @@ function applyDocUpdate(doc, groupSpec, methods, docMeta) { function appendChange(changes, change) { const exists = changes.some(item => item && item.version === change.version); assert(!exists, `Duplicate change version detected: ${change.version}`); - changes.push(cloneJson(change)); + // 变更记录保持“新记录在数组开头”的顺序(与 methods/changes/*.json 现有约定一致) + changes.unshift(cloneJson(change)); } function main() { @@ -384,4 +385,4 @@ module.exports = { applyDocUpdate, parseArgs, validateSpec, -}; \ No newline at end of file +}; From c5c16a12a2b1ce3e9ba939f4b5750c364467deb7 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Tue, 18 Aug 2026 17:11:22 +0800 Subject: [PATCH 226/550] =?UTF-8?q?docs(setting.expressInterface):=20?= =?UTF-8?q?=E8=A1=A5=E5=85=A8=20update=20=E6=8E=A5=E5=8F=A3=E8=AF=A6?= =?UTF-8?q?=E7=BB=86=E5=85=A5=E5=8F=82=E4=B8=8E=E5=93=8D=E5=BA=94=E6=96=87?= =?UTF-8?q?=E6=A1=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - params 由 3 个扩展为 31 个全量可更新字段(含 town_name/townName、is_enabled/isEnabled 等驼峰别名与空值处理规则) - description 补充仅更新传入字段、id 兼容 interface_id/interfaceId、shop_id 同步刷新 token 等说明 - response 按 normalizeInterfaceRow 补全 37 个字段,errors 补充 10 条错误码 - 版本 0.3.28 -> 0.3.29,updatedAt 更新为 2026-08-18,并新增变更记录 --- methods/changes/system.json | 15 ++ methods/system.json | 471 +++++++++++++++++++++++++++++++++++- 2 files changed, 477 insertions(+), 9 deletions(-) diff --git a/methods/changes/system.json b/methods/changes/system.json index cb9ea6e..8f6d6a9 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,19 @@ [ + { + "version": "2026.08.18-setting.expressInterface.update-doc-params", + "date": "2026-08-18", + "type": "enhanced", + "summary": "补全 setting.expressInterface.update 接口文档:入参由 3 个字段扩展为全量可更新字段(含 town_name/townName、is_enabled/isEnabled、providertype 等),并补充全量响应字段与错误码说明。", + "methods": [ + "setting.expressInterface.update" + ], + "notes": [ + "入参按 app/service/systems/setting/expressInterface.js update() 与包装层 app/service/systemMethods/setting/expressInterface.js update() 实际支持的字段补齐,含驼峰别名(shopId/townName/isEnabled 等),仅传入的字段被更新", + "响应按 normalizeInterfaceRow 返回结构补齐全量字段", + "仅文档变更,无代码改动" + ], + "module": "setting.expressInterface" + }, { "version": "2026.08.18-order-lock-status-guard-and-list-yn", "date": "2026-08-18", diff --git a/methods/system.json b/methods/system.json index 0c531be..9ee3452 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1,8 +1,8 @@ { "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", - "version": "0.3.28", - "updatedAt": "2026-08-15", + "version": "0.3.29", + "updatedAt": "2026-08-18", "headers": [ { "name": "platform", @@ -15325,7 +15325,7 @@ }, { "method": "setting.expressInterface.update", - "description": "更新快递接口,支持 shop_id/shopId 入参(可空)。", + "description": "更新快递接口。至少传入一个可更新字段,仅更新传入的字段;id 兼容 interface_id / interfaceId 入参;shop_id 可空,传入时会同步刷新接口 token;name/express_code/platform_code/sys_express_code 变更会触发系统快递编码重新解析。更新成功后返回该记录的完整字段。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -15342,32 +15342,485 @@ "type": "number", "required": true, "source": "body", - "description": "id" + "description": "快递接口ID,兼容 interface_id / interfaceId" + }, + { + "name": "name", + "type": "string", + "required": false, + "source": "body", + "description": "接口名称" + }, + { + "name": "express_code", + "type": "string", + "required": false, + "source": "body", + "description": "快递编码(存大写);与 platform_code / sys_express_code 任一变更时重新解析系统快递编码" + }, + { + "name": "platform_code", + "type": "string", + "required": false, + "source": "body", + "description": "平台编码(PDD/CAINIAO/DY/KS/SPH/XHS/JD/QT)" + }, + { + "name": "sys_express_code", + "type": "string", + "required": false, + "source": "body", + "description": "系统快递编码(支持 sysExpressCode);未传时按 express_code + platform_code 自动匹配" }, { "name": "shop_id", "type": "number", "required": false, "source": "body", - "description": "shop_id" + "description": "店铺ID(支持 shopId),正整数可空;传入该字段会同步刷新接口 token" + }, + { + "name": "platform_shop_id", + "type": "number", + "required": false, + "source": "body", + "description": "平台店铺ID(支持 platformShopId),正整数可空" + }, + { + "name": "template_id", + "type": "string", + "required": false, + "source": "body", + "description": "模板ID(支持 templateId),空字符串按 null 处理" + }, + { + "name": "paymode", + "type": "number", + "required": false, + "source": "body", + "description": "付款方式(支持 payMode)" + }, + { + "name": "brandno", + "type": "string", + "required": false, + "source": "body", + "description": "品牌编码(支持 brandNo),空字符串按 null 处理" + }, + { + "name": "providertype", + "type": "string", + "required": false, + "source": "body", + "description": "服务商类型编码(支持 providerType),空字符串按 null 处理" + }, + { + "name": "providerid", + "type": "number", + "required": false, + "source": "body", + "description": "服务商ID(支持 providerId)" + }, + { + "name": "sender_name", + "type": "string", + "required": false, + "source": "body", + "description": "寄件人(支持 senderName)" + }, + { + "name": "sender_tel", + "type": "string", + "required": false, + "source": "body", + "description": "寄件电话(支持 senderTel)" + }, + { + "name": "weight", + "type": "number", + "required": false, + "source": "body", + "description": "排序权重,可空" + }, + { + "name": "weight_type", + "type": "number", + "required": false, + "source": "body", + "description": "重量类型(支持 weightType),可空" + }, + { + "name": "viewer", + "type": "string", + "required": false, + "source": "body", + "description": "验视员/查看者" + }, + { + "name": "client_id", + "type": "string", + "required": false, + "source": "body", + "description": "客户ID(支持 clientId)" + }, + { + "name": "ispickup", + "type": "number", + "required": false, + "source": "body", + "description": "是否上门取件(支持 isPickup),1是 0否" + }, + { + "name": "shipperno", + "type": "string", + "required": false, + "source": "body", + "description": "发货编号/寄件网点编码(支持 shipperNo)" + }, + { + "name": "template_url", + "type": "string", + "required": false, + "source": "body", + "description": "打印模板URL(支持 templateUrl)" + }, + { + "name": "province_name", + "type": "string", + "required": false, + "source": "body", + "description": "寄件人省份(支持 provinceName)" + }, + { + "name": "city_name", + "type": "string", + "required": false, + "source": "body", + "description": "寄件人城市(支持 cityName)" + }, + { + "name": "district_name", + "type": "string", + "required": false, + "source": "body", + "description": "寄件人区县(支持 districtName)" }, { "name": "address", "type": "string", "required": false, "source": "body", - "description": "发件人详细地址(可选),使用 index.getShopExpressList 返回的 detail 字段值,非 full_address" + "description": "发件人详细地址,使用 index.getShopExpressList 返回的 detail 字段值,非 full_address" + }, + { + "name": "town_name", + "type": "string", + "required": false, + "source": "body", + "description": "寄件人镇/街道(支持 townName)" + }, + { + "name": "site_code", + "type": "string", + "required": false, + "source": "body", + "description": "网点编码(支持 siteCode)" + }, + { + "name": "product_type", + "type": "string", + "required": false, + "source": "body", + "description": "产品类型/编码(支持 productType)" + }, + { + "name": "shop_name", + "type": "string", + "required": false, + "source": "body", + "description": "平台店铺名称(支持 shopName)" + }, + { + "name": "ext_data", + "type": "object", + "required": false, + "source": "body", + "description": "扩展数据 JSON 对象(支持 extData)" + }, + { + "name": "is_enabled", + "type": "number", + "required": false, + "source": "body", + "description": "是否启用(支持 isEnabled),1启用 0停用" } ], "response": [ { "name": "id", "type": "number", - "description": "id", - "required": true + "required": true, + "description": "主键ID" + }, + { + "name": "name", + "type": "string", + "required": true, + "description": "接口名称" + }, + { + "name": "express_code", + "type": "string", + "required": true, + "description": "快递编码" + }, + { + "name": "sys_express_code", + "type": "string", + "required": true, + "description": "系统快递编码" + }, + { + "name": "warehouse_id", + "type": "number", + "required": false, + "description": "仓库ID" + }, + { + "name": "shop_id", + "type": "number", + "required": false, + "description": "店铺ID,未绑定时为 null" + }, + { + "name": "platform_shop_id", + "type": "number", + "required": false, + "description": "平台店铺ID" + }, + { + "name": "template_id", + "type": "string", + "required": false, + "description": "模板ID" + }, + { + "name": "paymode", + "type": "number", + "required": false, + "description": "付款方式" + }, + { + "name": "brandno", + "type": "string", + "required": false, + "description": "品牌编码" + }, + { + "name": "providertype", + "type": "string", + "required": false, + "description": "服务商类型编码" + }, + { + "name": "providerid", + "type": "number", + "required": false, + "description": "服务商ID" + }, + { + "name": "platform_code", + "type": "string", + "required": true, + "description": "平台编码(PDD/CAINIAO/DY/KS/SPH/XHS/JD/QT)" + }, + { + "name": "sender_name", + "type": "string", + "required": false, + "description": "寄件人" + }, + { + "name": "sender_tel", + "type": "string", + "required": false, + "description": "寄件电话" + }, + { + "name": "weight", + "type": "number", + "required": false, + "description": "排序权重" + }, + { + "name": "weight_type", + "type": "number", + "required": false, + "description": "重量类型" + }, + { + "name": "viewer", + "type": "string", + "required": false, + "description": "验视员/查看者" + }, + { + "name": "client_id", + "type": "string", + "required": false, + "description": "客户ID" + }, + { + "name": "is_enabled", + "type": "number", + "required": false, + "description": "是否启用(1启用 0禁用)" + }, + { + "name": "is_share", + "type": "number", + "required": false, + "description": "是否共享" + }, + { + "name": "ispickup", + "type": "number", + "required": false, + "description": "是否上门取件" + }, + { + "name": "shipperno", + "type": "string", + "required": false, + "description": "发货编号/寄件网点编码" + }, + { + "name": "template_url", + "type": "string", + "required": false, + "description": "打印模板URL" + }, + { + "name": "ext_data", + "type": "object", + "required": false, + "description": "扩展数据(JSON对象)" + }, + { + "name": "province_name", + "type": "string", + "required": false, + "description": "寄件人省份" + }, + { + "name": "city_name", + "type": "string", + "required": false, + "description": "寄件人城市" + }, + { + "name": "district_name", + "type": "string", + "required": false, + "description": "寄件人区县" + }, + { + "name": "address", + "type": "string", + "required": false, + "description": "发件人详细地址" + }, + { + "name": "town_name", + "type": "string", + "required": false, + "description": "寄件人镇/街道" + }, + { + "name": "site_code", + "type": "string", + "required": false, + "description": "网点编码" + }, + { + "name": "product_type", + "type": "string", + "required": false, + "description": "产品类型/编码" + }, + { + "name": "shop_name", + "type": "string", + "required": false, + "description": "店铺名称" + }, + { + "name": "express", + "type": "object", + "required": false, + "description": "关联的系统快递对象(未关联时为 null)" + }, + { + "name": "express_name", + "type": "string", + "required": false, + "description": "快递名称(扁平字段)" + }, + { + "name": "express_polyapi_extra_info", + "type": "string", + "required": false, + "description": "PolyAPI扩展信息(扁平字段)" + }, + { + "name": "express_pdd_code", + "type": "string", + "required": false, + "description": "拼多多快递编码(扁平字段)" } ], - "errors": [] + "errors": [ + { + "code": "400", + "message": "id 参数不能为空" + }, + { + "code": "400", + "message": "至少需要提供一个可更新字段" + }, + { + "code": "400", + "message": "name 参数不能为空" + }, + { + "code": "400", + "message": "express_code 参数不能为空" + }, + { + "code": "400", + "message": "platform_code 参数不能为空" + }, + { + "code": "400", + "message": "字段校验失败(字段为空、长度超限或数值/JSON 格式非法)" + }, + { + "code": "400", + "message": "express_code 未匹配到系统快递编码" + }, + { + "code": "400", + "message": "platform_code 未匹配到打印平台编码" + }, + { + "code": "404", + "message": "快递接口不存在或无权限操作" + }, + { + "code": "404", + "message": "当前仓库下未找到对应店铺,无法同步快递接口 token" + } + ] }, { "method": "setting.expressInterface.delete", From aaadce25afc45f6507dc03673c4d9a223c48a0d8 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Tue, 18 Aug 2026 23:55:39 +0800 Subject: [PATCH 227/550] =?UTF-8?q?fix(order):=20=E4=BF=AE=E5=A4=8D?= =?UTF-8?q?=E6=89=B9=E9=87=8F=E9=94=81=E5=AE=9A/=E8=A7=A3=E9=94=81?= =?UTF-8?q?=E6=93=8D=E4=BD=9C=E6=97=A5=E5=BF=97=20businessId=20=E8=AF=AF?= =?UTF-8?q?=E5=86=99=E4=B8=BA=E4=BB=93=E5=BA=93ID?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit runBatchLockTask/runBatchUnlockTask 写入 ORDER_LOCK/ORDER_UNLOCK 日志时 businessId 误用 logWarehouseId,导致订单详情按 business_id=订单ID 查询 查不到锁定/解锁日志,现改为 orderId 与拦截/解除拦截保持一致 --- app/service/systemMethods/order/pendingOrder.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/service/systemMethods/order/pendingOrder.js b/app/service/systemMethods/order/pendingOrder.js index 01ed154..ea2c0d4 100644 --- a/app/service/systemMethods/order/pendingOrder.js +++ b/app/service/systemMethods/order/pendingOrder.js @@ -5048,7 +5048,7 @@ ${numbered}`; return { businessType: 'order', - businessId: logWarehouseId, + businessId: orderId, operationCode: 'ORDER_LOCK', operator, extras: { @@ -5557,7 +5557,7 @@ ${numbered}`; return { businessType: 'order', - businessId: logWarehouseId, + businessId: orderId, operationCode: 'ORDER_UNLOCK', operator, extras: { From 943a20f582abe0ab86a5ab47330c4bdcda4f0327 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Tue, 18 Aug 2026 23:59:11 +0800 Subject: [PATCH 228/550] =?UTF-8?q?fix(print):=20express=20=E6=89=93?= =?UTF-8?q?=E5=8D=B0=E7=BB=84=E4=BB=B6=E8=A7=A3=E6=9E=90=E6=94=AF=E6=8C=81?= =?UTF-8?q?=E7=B3=BB=E7=BB=9F=E5=B9=B3=E5=8F=B0=E7=BC=96=E7=A0=81=E5=9B=9E?= =?UTF-8?q?=E9=80=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 淘宝 TB/天猫 TM/1688/TGC 等系统平台编码未在 wms_print_platform 直接匹配时, 经 wms_platform.print_platform_id 回退解析 wms_print_platform.platform_name - 移除 loadExpressPlatformComponents 调试 console.log,改走 ctx.logger.info - 新增 TB 回退解析成功与无映射失败的单元测试 --- app/service/systemMethods/print.js | 97 ++++++++++-- .../service/systemMethods/print.send.test.js | 147 +++++++++++++++++- 2 files changed, 223 insertions(+), 21 deletions(-) diff --git a/app/service/systemMethods/print.js b/app/service/systemMethods/print.js index 07e5149..7c7dd2f 100644 --- a/app/service/systemMethods/print.js +++ b/app/service/systemMethods/print.js @@ -1787,6 +1787,14 @@ class PrintService extends MainService { /** * 加载并校验 express 请求涉及平台的打印组件配置。 + * + * 解析顺序: + * 1. 直接按 `wms_print_platform.platform_code` 匹配(快递接口透出的打印平台编码, + * 如 CAINIAO/DY/JD/KS/PDD/SPH/XHS); + * 2. 未匹配的编码视为系统平台编码(如 TB/TM/1688/TGC),经 + * `wms_platform.code -> print_platform_id -> wms_print_platform.platform_name` + * 回退解析对应打印组件。 + * * @param {Object} payload 查询参数。 * @param {Array} payload.platformCodes 平台编码列表。 * @return {Promise<{success:boolean,data?:Object,error?:string}>} 查询与校验结果。 @@ -1803,22 +1811,81 @@ class PrintService extends MainService { }; } - const platformRows = await this.ctx.model.PrintPlatform.findAll({ - attributes: [ 'platform_code', 'platform_name' ], - where: { - platform_code: platformCodes, - }, - raw: true, - }); + const printPlatformModel = this.ctx && this.ctx.model && this.ctx.model.PrintPlatform; + const platformModel = this.ctx && this.ctx.model && this.ctx.model.Platform; const platformComponentMap = {}; - for (const row of platformRows) { - const platformCode = String(row && row.platform_code ? row.platform_code : '').trim(); - if (!platformCode) { - continue; + + // 1) 优先按打印平台编码直接匹配 + if (printPlatformModel && typeof printPlatformModel.findAll === 'function') { + const platformRows = await printPlatformModel.findAll({ + attributes: [ 'id', 'platform_code', 'platform_name' ], + where: { + platform_code: platformCodes, + }, + raw: true, + }); + for (const row of Array.isArray(platformRows) ? platformRows : []) { + const platformCode = String(row && row.platform_code ? row.platform_code : '').trim(); + if (!platformCode) { + continue; + } + platformComponentMap[platformCode] = String(row && row.platform_name ? row.platform_name : '').trim(); } - platformComponentMap[platformCode] = String(row && row.platform_name ? row.platform_name : '').trim(); } - console.log('platformComponentMap', platformComponentMap); + + // 2) 未匹配编码按系统平台编码回退解析(TB/TM/1688 等经 print_platform_id 关联) + const unresolvedCodes = platformCodes.filter(platformCode => { + return !String(platformComponentMap[platformCode] || '').trim(); + }); + if (unresolvedCodes.length > 0 + && printPlatformModel && typeof printPlatformModel.findAll === 'function' + && platformModel && typeof platformModel.findAll === 'function') { + const systemPlatformRows = await platformModel.findAll({ + attributes: [ 'code', 'print_platform_id' ], + where: { + code: unresolvedCodes, + }, + raw: true, + }); + const codeListByPrintPlatformIdMap = new Map(); + for (const row of Array.isArray(systemPlatformRows) ? systemPlatformRows : []) { + const platformCode = String(row && row.code ? row.code : '').trim(); + const printPlatformId = Number(row && row.print_platform_id || 0); + if (!platformCode || !Number.isInteger(printPlatformId) || printPlatformId <= 0) { + continue; + } + if (!codeListByPrintPlatformIdMap.has(printPlatformId)) { + codeListByPrintPlatformIdMap.set(printPlatformId, []); + } + codeListByPrintPlatformIdMap.get(printPlatformId).push(platformCode); + } + + if (codeListByPrintPlatformIdMap.size > 0) { + const printPlatformRows = await printPlatformModel.findAll({ + attributes: [ 'id', 'platform_name' ], + where: { + id: Array.from(codeListByPrintPlatformIdMap.keys()), + }, + raw: true, + }); + const componentNameByPrintPlatformIdMap = new Map(); + for (const row of Array.isArray(printPlatformRows) ? printPlatformRows : []) { + const printPlatformId = Number(row && row.id || 0); + const componentName = String(row && row.platform_name ? row.platform_name : '').trim(); + if (!Number.isInteger(printPlatformId) || printPlatformId <= 0) { + continue; + } + componentNameByPrintPlatformIdMap.set(printPlatformId, componentName); + } + for (const [ printPlatformId, codeList ] of codeListByPrintPlatformIdMap) { + const componentName = componentNameByPrintPlatformIdMap.get(printPlatformId) || ''; + for (const platformCode of codeList) { + platformComponentMap[platformCode] = componentName; + } + } + } + } + for (const platformCode of platformCodes) { const component = String(platformComponentMap[platformCode] || '').trim(); if (!component) { @@ -1829,6 +1896,10 @@ class PrintService extends MainService { } } + this.ctx.logger.info('[print.send] express 平台打印组件解析完成', { + platformComponents: platformComponentMap, + }); + return { success: true, data: platformComponentMap, diff --git a/test/app/service/systemMethods/print.send.test.js b/test/app/service/systemMethods/print.send.test.js index b219e74..b0ebae3 100644 --- a/test/app/service/systemMethods/print.send.test.js +++ b/test/app/service/systemMethods/print.send.test.js @@ -25,6 +25,8 @@ function createContext(options = {}) { sendOrderMarks: [], redisGetKeys: [], platformFindAllWheres: [], + systemPlatformFindAllWheres: [], + printPlatformIdFindAllWheres: [], orderDeliveryLockUpdates: [], operationLogCreatePayloads: [], }; @@ -66,6 +68,18 @@ function createContext(options = {}) { douyin: '抖音', }; + const platformPrintIdMap = requestOptions.platformPrintIdMap || { + TB: 2, + TM: 2, + 1688: 2, + TGC: 2, + MAOCHAO: 2, + }; + + const printPlatformNameById = requestOptions.printPlatformNameById || { + 2: '菜鸟', + }; + const printStation = requestOptions.printStation || { id: 101, warehouse_id: 100000, @@ -276,18 +290,41 @@ function createContext(options = {}) { }, PrintPlatform: { async findAll(query) { - calls.platformFindAllWheres.push(query && query.where ? query.where : {}); - const codeList = query && query.where && Array.isArray(query.where.platform_code) - ? query.where.platform_code - : []; - return codeList.map(platformCode => ({ - platform_code: platformCode, - platform_name: Object.prototype.hasOwnProperty.call(platformComponents, platformCode) - ? platformComponents[platformCode] + const where = query && query.where ? query.where : {}; + if (Array.isArray(where.platform_code)) { + calls.platformFindAllWheres.push(where); + const codeList = where.platform_code; + return codeList.map(platformCode => ({ + id: null, + platform_code: platformCode, + platform_name: Object.prototype.hasOwnProperty.call(platformComponents, platformCode) + ? platformComponents[platformCode] + : '', + })); + } + calls.printPlatformIdFindAllWheres.push(where); + const idList = Array.isArray(where.id) ? where.id : []; + return idList.map(printPlatformId => ({ + id: printPlatformId, + platform_name: Object.prototype.hasOwnProperty.call(printPlatformNameById, printPlatformId) + ? printPlatformNameById[printPlatformId] : '', })); }, }, + Platform: { + async findAll(query) { + const where = query && query.where ? query.where : {}; + calls.systemPlatformFindAllWheres.push(where); + const codeList = Array.isArray(where.code) ? where.code : []; + return codeList.map(platformCode => ({ + code: platformCode, + print_platform_id: Object.prototype.hasOwnProperty.call(platformPrintIdMap, platformCode) + ? platformPrintIdMap[platformCode] + : null, + })); + }, + }, OrderDeliveryFactory: { async getCurrentModel() { return { @@ -690,6 +727,100 @@ describe('test/app/service/systemMethods/print.send.test.js', () => { assert.equal(calls.sendToComputerPayloads.length, 0); }); + it('type=express 系统平台编码 TB 应经 wms_platform 回退解析打印组件', async () => { + const { ctx, calls } = createContext({ + componentStatuses: { + 'printer:PC-STATION-001:name:菜鸟:status': 'connected', + }, + }); + const service = new PrintService(ctx); + + const result = await service.send({ + type: 'express', + printStationId: 101, + requestCode: 'REQ-TB-FALLBACK-001', + data: { + waveGroups: [ + { + wave_id: 1, + wave_no: 'WAVE-TB-1', + platforms: [ + { + platform: 'TB', + sys_logistics_code: 'STO', + orders: [ + { + print_data: { + documentID: 'DOC-TB-1', + contents: [ + { + marker: 'TB-1', + }, + ], + }, + }, + ], + }, + ], + }, + ], + }, + }); + + assert.equal(result.flag, 'success'); + assert.equal(calls.sendToComputerPayloads.length, 1); + const components = calls.sendToComputerPayloads.map(item => item.data.component); + assert.deepEqual(components, [ '菜鸟' ]); + assert.deepEqual(calls.systemPlatformFindAllWheres[0].code, [ 'TB' ]); + assert.deepEqual(calls.printPlatformIdFindAllWheres[0].id, [ 2 ]); + assert.ok(calls.redisGetKeys.includes('printer:PC-STATION-001:name:菜鸟:status')); + }); + + it('type=express 系统平台编码无映射时应失败且不发送任务', async () => { + const { ctx, calls } = createContext({ + platformPrintIdMap: {}, + }); + const service = new PrintService(ctx); + + const result = await service.send({ + type: 'express', + printStationId: 101, + requestCode: 'REQ-TB-UNMAPPED-001', + data: { + waveGroups: [ + { + wave_id: 1, + wave_no: 'WAVE-TB-2', + platforms: [ + { + platform: 'TB', + sys_logistics_code: 'STO', + orders: [ + { + print_data: { + documentID: 'DOC-TB-2', + contents: [ + { + marker: 'TB-2', + }, + ], + }, + }, + ], + }, + ], + }, + ], + }, + }); + + assert.equal(result.flag, 'failure'); + assert.equal(result.code, 400); + assert.match(result.message, /平台 TB 未配置打印组件/); + assert.equal(calls.printRecordCreatePayloads.length, 0); + assert.equal(calls.sendToComputerPayloads.length, 0); + }); + it('type=express 快手平台应按10单分批发送并注入文档位置信息', async () => { const { ctx, calls } = createContext({ platformComponents: { From 110d0685ee12e252a2a1051a8df32728117154ef Mon Sep 17 00:00:00 2001 From: liufumingren Date: Wed, 19 Aug 2026 00:00:23 +0800 Subject: [PATCH 229/550] =?UTF-8?q?fix(order):=20=E5=9B=A2=E8=B4=AD?= =?UTF-8?q?=E8=A7=A3=E7=BB=91=E8=BD=A6=E6=94=B9=E4=B8=BA=E4=BB=BB=E5=8A=A1?= =?UTF-8?q?=E5=85=A8=E6=B3=A2=E6=AC=A1=E5=A4=8D=E6=A0=B8/=E6=89=93?= =?UTF-8?q?=E5=8D=B0=E5=AE=8C=E6=88=90=E6=89=8D=E8=A7=A6=E5=8F=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 复核侧:_resolveTaskIdByWaveFallback 由单波次订单复核检查改为任务下 全部关联波次订单 recheck_status 均完成才返回 taskId,避免复核一个波次 即解绑 wms_pick_task_cart_binding 并误将任务置为已完成 - 打印侧:tryUnbindCartAfterPrintComplete 团购(pick_mode 1/5)改为按任务 全波次订单 print_status 检查,全部打印完成才解绑;散单保持任务订单维度检查 --- .../systemMethods/order/recheckOrder.js | 69 ++++++++++++++---- app/service/systemMethods/print.js | 73 +++++++++++++------ 2 files changed, 105 insertions(+), 37 deletions(-) diff --git a/app/service/systemMethods/order/recheckOrder.js b/app/service/systemMethods/order/recheckOrder.js index c57c02b..7ff99c0 100644 --- a/app/service/systemMethods/order/recheckOrder.js +++ b/app/service/systemMethods/order/recheckOrder.js @@ -290,8 +290,12 @@ class RecheckOrderService extends OrderBaseService { }); const totalOrders = mergedList.length; - const reviewedCount = mergedList.filter(o => o.recheck_status === 'fin').length; - const unreviewedCount = totalOrders - reviewedCount; + // 复核统计仅计非拦截订单(拦截订单保留在 list 中按单提示) + const reviewableOrders = mergedList.filter( + o => !this.isInterceptedOrderStatus(o.intercept_status) + ); + const reviewedCount = reviewableOrders.filter(o => o.recheck_status === 'fin').length; + const unreviewedCount = reviewableOrders.length - reviewedCount; const waveType = scanViews.find(v => Number(v.wave_type || 0) > 0)?.wave_type || 0; const pickerInfo = await this.getPickerInfoByTaskId(taskId, warehouseId); @@ -451,8 +455,12 @@ class RecheckOrderService extends OrderBaseService { }); const totalOrders = mergedList.length; - const reviewedCount = mergedList.filter(o => o.recheck_status === 'fin').length; - const unreviewedCount = totalOrders - reviewedCount; + // 复核统计仅计非拦截订单(拦截订单保留在 list 中按单提示) + const reviewableOrders = mergedList.filter( + o => !this.isInterceptedOrderStatus(o.intercept_status) + ); + const reviewedCount = reviewableOrders.filter(o => o.recheck_status === 'fin').length; + const unreviewedCount = reviewableOrders.length - reviewedCount; const waveType = scanViews.find(v => Number(v.wave_type || 0) > 0)?.wave_type || 0; return { @@ -480,6 +488,8 @@ class RecheckOrderService extends OrderBaseService { * @param {number} waveId 波次ID。 * @param {string} waveNo 波次号。 * @param {number} warehouseId 仓库ID。 + * 拦截订单保留在 list 中(带 intercept_status),不参与复核校验与 reviewed/unreviewed/printed 统计, + * 波次内存在拦截订单时不再阻断整个扫描视图加载(与团购模式一致)。 * @return {Promise} 扁平化扫描视图,包含 picker_id、picker_name、task_id、wave_id、wave_no、 * wave_type、pick_mode、strategy_id、strategy_name、total_orders、reviewed_count、unreviewed_count、 * printed_count、unprinted_count、list。 @@ -495,8 +505,15 @@ class RecheckOrderService extends OrderBaseService { const normalizedWaveId = Number(waveId || 0); const orders = Array.isArray(baseWaveView.orders) ? baseWaveView.orders : []; - // 校验波次内所有订单是否都已拣货,未拣货订单不允许复核 - for (const order of orders) { + // 分离拦截订单:拦截订单保留在 list 中由前端按单提示拦截(intercept_status), + // 仅对非拦截订单做复核校验与统计,与团购模式一致, + // 波次内存在拦截订单时不再阻断整个散单扫描视图加载 + const normalOrders = orders.filter( + order => !this.isInterceptedOrderStatus(order.intercept_status) + ); + + // 校验波次内非拦截订单是否都已拣货,未拣货订单不允许复核 + for (const order of normalOrders) { this.assertOrderCanRecheck(order); } @@ -506,13 +523,13 @@ class RecheckOrderService extends OrderBaseService { this.getWaveStrategyInfo(normalizedWaveId, warehouseId), ]); - // 计算复核汇总 - const reviewedCount = orders.filter(o => o.recheck_status === 'fin').length; - const unreviewedCount = orders.length - reviewedCount; + // 计算复核汇总(仅统计非拦截订单) + const reviewedCount = normalOrders.filter(o => o.recheck_status === 'fin').length; + const unreviewedCount = normalOrders.length - reviewedCount; - // 计算打印汇总 - const printedCount = orders.filter(o => o.is_printed === true).length; - const unprintedCount = orders.length - printedCount; + // 计算打印汇总(仅统计非拦截订单) + const printedCount = normalOrders.filter(o => o.is_printed === true).length; + const unprintedCount = normalOrders.length - printedCount; // 批量查询包材推荐 const packageMaterialMap = await this.batchQueryPackageMaterialRecommendation(orders, warehouseId); @@ -2231,16 +2248,36 @@ class RecheckOrderService extends OrderBaseService { return 0; } - // 检查波次下所有订单是否均已复核完成(团购模式以订单表 recheck_status 为准) - const unreviewedInWave = await orderModel.count({ + // 查任务关联的全部波次(团购任务一车多波次,必须任务下所有波次订单全部复核完成才允许解绑) + const taskAllWaveRows = await ctx.model.query( + `SELECT DISTINCT tw.wave_id + FROM wms_wave_pick_task_wave tw + WHERE tw.task_id = :taskId + AND tw.warehouse_id = :warehouseId`, + { + replacements: { taskId: fallbackTaskId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + const taskAllWaveIds = (Array.isArray(taskAllWaveRows) ? taskAllWaveRows : []) + .map(r => Number(r?.wave_id || 0)) + .filter(id => id > 0); + + if (taskAllWaveIds.length === 0) { + return 0; + } + + // 检查任务下所有波次的订单是否均已复核完成(团购模式以订单表 recheck_status 为准) + const unreviewedCount = await orderModel.count({ where: { - wave_id: orderWaveId, + wave_id: { [ctx.app.Sequelize.Op.in]: taskAllWaveIds }, warehouse_id: warehouseId, recheck_status: { [ctx.app.Sequelize.Op.ne]: 'fin' }, }, }); - return unreviewedInWave === 0 ? fallbackTaskId : 0; + return unreviewedCount === 0 ? fallbackTaskId : 0; } /** diff --git a/app/service/systemMethods/print.js b/app/service/systemMethods/print.js index 7c7dd2f..018c9ea 100644 --- a/app/service/systemMethods/print.js +++ b/app/service/systemMethods/print.js @@ -2873,34 +2873,65 @@ class PrintService extends MainService { taskId = Number(taskWave.task_id); if (!taskId) return; - if (waveType === 1) { - const taskRows = await ctx.model.query( - 'SELECT pick_mode FROM wms_wave_pick_task WHERE id = :taskId LIMIT 1', - { replacements: { taskId }, type: ctx.model.QueryTypes.SELECT } - ); - const task = Array.isArray(taskRows) && taskRows.length > 0 ? taskRows[0] : null; - const pickMode = task ? Number(task.pick_mode) : 0; - if (pickMode !== 1) return; - } - - // 团购 / 散单统一按订单维度检查:所有订单均已打印时才解绑 - const taskOrders = await ctx.model.query( - 'SELECT DISTINCT order_id FROM wms_wave_pick_task_order WHERE task_id = :taskId', - { replacements: { taskId }, type: ctx.model.QueryTypes.SELECT } - ); - const orderIds = (Array.isArray(taskOrders) ? taskOrders : []).map(r => Number(r && r.order_id)).filter(id => id > 0); - if (orderIds.length === 0) return; const orderDeliveryFactory = ctx.model && ctx.model.OrderDeliveryFactory; if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') { this.ctx.logger.warn('[print.unbindCart] OrderDeliveryFactory 不可用,跳过检查'); return; } const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(resolvedWarehouseId); - const unprintedCount = await orderDeliveryModel.count({ - where: { id: { [ctx.model.Sequelize.Op.in]: orderIds }, print_status: 'none' }, - }); + + let totalOrderCount = 0; + let unprintedCount = 0; + + if (waveType === 1) { + // 团购波次:仅团购拣货模式(pick_mode=1 小团购 / pick_mode=5 大团购)参与解绑判断 + const taskRows = await ctx.model.query( + 'SELECT pick_mode FROM wms_wave_pick_task WHERE id = :taskId LIMIT 1', + { replacements: { taskId }, type: ctx.model.QueryTypes.SELECT } + ); + const task = Array.isArray(taskRows) && taskRows.length > 0 ? taskRows[0] : null; + const pickMode = task ? Number(task.pick_mode) : 0; + if (![ 1, 5 ].includes(pickMode)) return; + + // 团购任务订单不写入 wms_wave_pick_task_order,改为按任务关联的全部波次统计: + // 任务下所有波次的订单均已打印时才解绑 + const taskWaveIdRows = await ctx.model.query( + 'SELECT DISTINCT wave_id FROM wms_wave_pick_task_wave WHERE task_id = :taskId AND warehouse_id = :warehouseId', + { replacements: { taskId, warehouseId: resolvedWarehouseId }, type: ctx.model.QueryTypes.SELECT } + ); + const waveIds = (Array.isArray(taskWaveIdRows) ? taskWaveIdRows : []) + .map(r => Number(r && r.wave_id)) + .filter(id => id > 0); + if (waveIds.length === 0) return; + unprintedCount = await orderDeliveryModel.count({ + where: { + warehouse_id: resolvedWarehouseId, + wave_id: { [ctx.model.Sequelize.Op.in]: waveIds }, + print_status: 'none', + }, + }); + totalOrderCount = await orderDeliveryModel.count({ + where: { + warehouse_id: resolvedWarehouseId, + wave_id: { [ctx.model.Sequelize.Op.in]: waveIds }, + }, + }); + } else { + // 散单波次:按任务订单维度检查,任务下所有订单均已打印时才解绑 + const taskOrders = await ctx.model.query( + 'SELECT DISTINCT order_id FROM wms_wave_pick_task_order WHERE task_id = :taskId', + { replacements: { taskId }, type: ctx.model.QueryTypes.SELECT } + ); + const orderIds = (Array.isArray(taskOrders) ? taskOrders : []).map(r => Number(r && r.order_id)).filter(id => id > 0); + if (orderIds.length === 0) return; + unprintedCount = await orderDeliveryModel.count({ + where: { id: { [ctx.model.Sequelize.Op.in]: orderIds }, print_status: 'none' }, + }); + totalOrderCount = orderIds.length; + } + if (unprintedCount > 0) { - this.ctx.logger.info('[print.unbindCart] 尚有未打印订单,跳过解绑', { waveId, warehouseId, taskId, waveType, waveTypeLabel: waveType === 1 ? '团购' : '散单', totalOrders: orderIds.length, unprintedCount }); + this.ctx.logger.info('[print.unbindCart] 尚有未打印订单,跳过解绑', { waveId, warehouseId, taskId, waveType, waveTypeLabel: waveType === 1 ? '团购' : '散单', totalOrders: totalOrderCount, unprintedCount }); return; } From ac4222c49aa51ba319a71c3a2d867e0c7c0b7c11 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Wed, 19 Aug 2026 00:00:28 +0800 Subject: [PATCH 230/550] =?UTF-8?q?fix(receiving):=20=E6=94=B6=E8=B4=A7?= =?UTF-8?q?=E7=BB=91=E5=AE=9A=E8=B4=A7=E4=B8=BB=E9=80=9A=E7=9F=A5=E6=8C=89?= =?UTF-8?q?=E5=B7=B2=E5=A1=AB=E8=BD=A6=E7=89=8C/=E5=BF=AB=E9=80=92?= =?UTF-8?q?=E5=8D=95=E5=8F=B7=E5=B1=95=E7=A4=BA=E5=B7=B2=E7=99=BB=E8=AE=B0?= =?UTF-8?q?=E4=BF=A1=E6=81=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - sendStoreBoundNotice 根据 receiving.license_plate / tracking_number 动态生成 第三行文案:已填车牌显示已登记信息,均未填写才提示及时补充 - create/bindStore/updateReceivingStats 三个触发点的快照均补充两字段 --- app/service/systems/storage/receiving.js | 24 ++++++++++++++++++++++-- methods/changes/warehouse.json | 15 +++++++++++++++ 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/app/service/systems/storage/receiving.js b/app/service/systems/storage/receiving.js index 74944b3..444707d 100644 --- a/app/service/systems/storage/receiving.js +++ b/app/service/systems/storage/receiving.js @@ -1494,7 +1494,8 @@ class ReceivingService extends Service { } /** - * 发送收货单创建/首次绑定货主通知(receiving_store_bound),提醒货主填写车牌号/快递单号。 + * 发送收货单创建/首次绑定货主通知(receiving_store_bound),提醒货主确认/补填车牌号或快递单号。 + * 已填写车牌号或快递单号时,文案展示已登记信息;均未填写时才提示及时补充。 * 路由由 notice 固定订阅回退链处理:货主收货群 → 无则货主售后群 → 均无则仓库异常群。 * @param {Object} options 发送参数 * @param {Object} options.receiving 收货单快照 @@ -1522,10 +1523,23 @@ class ReceivingService extends Service { const storeLabel = String(storeName || receiving.store_name || '').trim() || '货主'; const storeFrontendUrl = String(ctx.app.config.storeFrontendUrl || ctx.app.config.frontendUrl || '').trim(); + const licensePlate = String(receiving.license_plate || '').trim(); + const trackingNumber = String(receiving.tracking_number || '').trim(); + const vehicleInfoLines = []; + if (licensePlate) { + vehicleInfoLines.push(`车牌号:${licensePlate} 已登记`); + } + if (trackingNumber) { + vehicleInfoLines.push(`快递单号:${trackingNumber} 已登记`); + } + if (vehicleInfoLines.length === 0) { + vehicleInfoLines.push('请确认是否已填写车牌号或快递单号,未填写请及时补充'); + } + const contentLines = [ `收货单号:${receivingNumber} 正在收货`, `货主:${storeLabel}`, - '请确认是否已填写车牌号或快递单号,未填写请及时补充', + ...vehicleInfoLines, ]; const content = [ ...contentLines ].join('\n') + '。'; const storeContent = [ ...contentLines, `快速查看:${storeFrontendUrl}/storage/receiving_owner?id=${receivingNumber}` ].join('\n') + '。'; @@ -2061,6 +2075,8 @@ class ReceivingService extends Service { warehouse_id: result.warehouse_id, store_id: result.store_id, store_name: result.store_name, + license_plate: result.license_plate, + tracking_number: result.tracking_number, }, }); } catch (noticeErr) { @@ -2422,6 +2438,8 @@ class ReceivingService extends Service { warehouse_id: warehouseId, store_id: storeId, store_name: storeName, + license_plate: receiving.license_plate, + tracking_number: receiving.tracking_number, }, }); } catch (noticeErr) { @@ -3283,6 +3301,8 @@ class ReceivingService extends Service { warehouse_id: warehouseId, store_id: storeId, store_name: storeName, + license_plate: receiving.license_plate, + tracking_number: receiving.tracking_number, }, }); } catch (noticeErr) { diff --git a/methods/changes/warehouse.json b/methods/changes/warehouse.json index 5f5cdff..667bc9f 100644 --- a/methods/changes/warehouse.json +++ b/methods/changes/warehouse.json @@ -224,5 +224,20 @@ "dev 库已回填:26 仓库组-主管、27 仓库组-员工、28 客服组-主管、30 客服组-员工" ], "module": "permission" + }, + { + "version": "2026-08-17-warehouse-08", + "date": "2026-08-17", + "type": "fixed", + "summary": "修复 receiving_store_bound 通知文案不感知车牌/快递单号:创建收货单时已填车牌仍提示「请确认是否已填写车牌号或快递单号」,改为已填写时展示已登记信息、未填写才提示补充", + "methods": [ + "notify.reply" + ], + "notes": [ + "sendStoreBoundNotice 根据 receiving.license_plate / receiving.tracking_number 动态生成第三行:已填车牌显示「车牌号:X 已登记」、已填快递单号显示「快递单号:X 已登记」、均未填才显示「请确认是否已填写车牌号或快递单号,未填写请及时补充」", + "三个触发点(create/bindStore/updateReceivingStats)的 receiving 快照均补充 license_plate / tracking_number 字段", + "背景:R20682003 创建时已写入车牌粤EH22E2,但通知为固定提醒文案导致货主误以为车牌未生效" + ], + "module": "receiving" } ] From 864351977bf493567a3eddef0fe132d8ec2f1d5e Mon Sep 17 00:00:00 2001 From: liufumingren Date: Wed, 19 Aug 2026 00:00:32 +0800 Subject: [PATCH 231/550] =?UTF-8?q?fix(order):=20wms=5Forder=5Fitems.ext?= =?UTF-8?q?=5Fcode=20=E6=94=B9=E4=B8=BA=20TEXT=20=E6=94=AF=E6=8C=81?= =?UTF-8?q?=E8=B6=85=E9=95=BF=E5=A4=96=E9=83=A8=E7=BC=96=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/model/order_items.js | 4 +- ...-alter-wms-order-items-ext-code-to-text.js | 79 +++++++++++++++++++ 2 files changed, 81 insertions(+), 2 deletions(-) create mode 100644 database/migrations/20260818190000-alter-wms-order-items-ext-code-to-text.js diff --git a/app/model/order_items.js b/app/model/order_items.js index e2a47e3..f3905cc 100644 --- a/app/model/order_items.js +++ b/app/model/order_items.js @@ -3,7 +3,7 @@ module.exports = app => { const { Sequelize, model } = app; - const { STRING, BIGINT, DECIMAL, INTEGER, JSON } = Sequelize; + const { STRING, BIGINT, DECIMAL, INTEGER, JSON, TEXT } = Sequelize; const OrderItems = model.define('wms_order_items', { id: { @@ -28,7 +28,7 @@ module.exports = app => { comment: '零售价格', }, ext_code: { - type: STRING(50), + type: TEXT, allowNull: true, comment: '外部编码', }, diff --git a/database/migrations/20260818190000-alter-wms-order-items-ext-code-to-text.js b/database/migrations/20260818190000-alter-wms-order-items-ext-code-to-text.js new file mode 100644 index 0000000..4c3e8c8 --- /dev/null +++ b/database/migrations/20260818190000-alter-wms-order-items-ext-code-to-text.js @@ -0,0 +1,79 @@ +'use strict'; + +/** + * 将订单商品表 ext_code 列从 VARCHAR(50) 改为 TEXT。 + * + * 背景: + * wms_order_items.ext_code 原为 VARCHAR(50),上游平台(奇门/仓库接口)下发的 + * 商品外部编码可能超过 50 字符,INSERT 时报 + * "Data too long for column 'ext_code' at row 1",导致整个订单创建失败。 + * + * 变更: + * 1. 主表 wms_order_items 及全部已有分表 wms_order_items_{warehouseId} + * (含 _dispatch/_history 后缀)的 ext_code 列统一改为 TEXT。 + * 2. 模型定义同步改为 TEXT(app/model/order_items.js),后续新建分表直接 + * 使用 TEXT,OrderItemsFactory 的结构对齐逻辑不会再回退该列。 + * + * @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口 + * @return {Promise} 无返回值 + */ +async function listOrderItemsTables(queryInterface) { + const [ rows ] = await queryInterface.sequelize.query(` + SELECT TABLE_NAME + FROM INFORMATION_SCHEMA.TABLES + WHERE TABLE_SCHEMA = DATABASE() + AND (TABLE_NAME = 'wms_order_items' OR TABLE_NAME LIKE 'wms_order_items\\_%') + `); + + return (Array.isArray(rows) ? rows : []).map(row => row.TABLE_NAME); +} + +async function hasColumn(queryInterface, tableName, columnName) { + const [ columns ] = await queryInterface.sequelize.query( + ` + SELECT COLUMN_NAME + FROM INFORMATION_SCHEMA.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = :tableName + AND COLUMN_NAME = :columnName + `, + { replacements: { tableName, columnName } } + ); + + return (Array.isArray(columns) ? columns : []).length > 0; +} + +module.exports = { + up: async queryInterface => { + const tableNames = await listOrderItemsTables(queryInterface); + let alteredCount = 0; + + for (const tableName of tableNames) { + if (!(await hasColumn(queryInterface, tableName, 'ext_code'))) { + continue; + } + + await queryInterface.sequelize.query( + `ALTER TABLE \`${tableName}\` MODIFY \`ext_code\` TEXT NULL COMMENT '外部编码'` + ); + alteredCount += 1; + } + + console.log(`[migrate] wms_order_items ext_code → TEXT,共处理 ${alteredCount} 张表`); + }, + + down: async queryInterface => { + const tableNames = await listOrderItemsTables(queryInterface); + + for (const tableName of tableNames) { + if (!(await hasColumn(queryInterface, tableName, 'ext_code'))) { + continue; + } + + // 注意:若已有数据超过 50 字符,回滚会失败,需先人工截断数据 + await queryInterface.sequelize.query( + `ALTER TABLE \`${tableName}\` MODIFY \`ext_code\` VARCHAR(50) NULL COMMENT '外部编码'` + ); + } + }, +}; From d18da8992544bb99ca9e7c4f83159e66cbff3871 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Wed, 19 Aug 2026 00:00:36 +0800 Subject: [PATCH 232/550] =?UTF-8?q?fix(inbound):=20PENDING=20=E7=8A=B6?= =?UTF-8?q?=E6=80=81=E4=B8=8A=E6=9E=B6=E4=B8=8D=E5=86=8D=E5=BC=BA=E5=88=B6?= =?UTF-8?q?=E7=BB=91=E5=AE=9A=E6=94=B6=E8=B4=A7=E5=8D=95=E4=B8=8E=E6=98=8E?= =?UTF-8?q?=E7=BB=86=20ID?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 允许导入:items 可传 receiving_detail_id 走绑定模式(预占收货明细), 也可不传走非绑定模式(数量受计划数量限制) - 绑定模式下 space_id/明细可用数量校验统一由 _addSingleItem 处理 --- app/service/systems/inbound_direct_log.js | 14 +++----------- 1 file changed, 3 insertions(+), 11 deletions(-) diff --git a/app/service/systems/inbound_direct_log.js b/app/service/systems/inbound_direct_log.js index 49556a1..77d6cc4 100644 --- a/app/service/systems/inbound_direct_log.js +++ b/app/service/systems/inbound_direct_log.js @@ -638,17 +638,9 @@ class InboundDirectLogService extends Service { return { code: 400, message: '入库单已绑定收货单且状态为 CREATED,请先审核后再进行上架操作', data: null }; } - // PENDING 状态校验 - if (entryOrder.order_status === 'PENDING') { - if (!hasReceivingBindings) { - return { code: 400, message: '入库单未绑定收货单,无法上架', data: null }; - } - for (const item of items) { - if (!item.receiving_detail_id) { - return { code: 400, message: '随机入库需要选定收货单明细提交,缺少 receiving_detail_id', data: null }; - } - } - } + // PENDING 状态:允许导入。items 可传 receiving_detail_id 走绑定模式(预占收货明细), + // 也可不传走非绑定模式(数量受计划数量限制),不再强制绑定收货单、不再强制传收货单 ID; + // 绑定模式下的 space_id/明细可用数量等校验由 _addSingleItem 统一处理。 // 批量模式下用事务包裹,任一失败整批回退 const useTransaction = isBatch; From 29e7b6ae703cf4cb465798e7263c555c94ba4180 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Wed, 19 Aug 2026 00:00:40 +0800 Subject: [PATCH 233/550] =?UTF-8?q?docs(order):=20=E8=AE=A2=E5=8D=95?= =?UTF-8?q?=E5=88=97=E8=A1=A8=20where=20=E8=A1=A5=E5=85=85=20lock=5Fstatus?= =?UTF-8?q?=20=E7=AD=9B=E9=80=89=E8=AF=B4=E6=98=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - pendingOrder.list 的 where 参数说明补充:未锁定传 lock_status=none, 已锁定(所有非 none)传 lock_status={operator:ne,value:none} - 筛选值使用数据库原始枚举 none/warehouse/store 而非响应 Y/N,条件值为空自动忽略 - 补充 2026.08.18-order-list-lock-status-filter-doc 变更记录 --- methods/changes/system.json | 16 ++++++++++++++++ methods/system.json | 2 +- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/methods/changes/system.json b/methods/changes/system.json index 8f6d6a9..2d534ce 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,20 @@ [ + { + "version": "2026.08.18-order-list-lock-status-filter-doc", + "date": "2026-08-18", + "type": "enhanced", + "summary": "订单列表 where 补充 lock_status 筛选说明:未锁定传 lock_status=none,已锁定(所有非 none)传 lock_status={operator:ne,value:none};筛选用数据库原始枚举 none/warehouse/store 而非响应 Y/N,条件值为空自动忽略。", + "methods": [ + "order.pendingOrder.list" + ], + "notes": [ + "仅文档补充,无代码改动:methods/system.json 中 order.pendingOrder.list 的 where 参数 description 增加 lock_status 筛选说明", + "行为依据:app/service/systemMethods/order/base.js listByModule/buildWhere 对 where 无字段白名单(仅禁止 warehouse_id/warehouseId),可直接传订单表列名;app/lib/query_condition_parser.js 支持 ne 操作符且条件值为空时自动忽略(isEmptyValue 跳过)", + "lock_status 数据库原始枚举 none/warehouse/store(app/model/order_delivery.js LOCK_STATUS),列表响应仍统一输出 Y/N(normalizeLockStatusFlag:none→N,其余→Y),筛选入参必须用原始枚举而非响应 Y/N", + "同样经 listByModule 的其它工作台订单列表(order.reviewOrder.list / order.outboundOrder.list / order.expectionOrder.list / order.entrustOrder.list / order.deliveryOrder.list / order.deliveryExpectionOrder.list / order.archiveOrder.list)where 语义一致,本次保持其文档不变,重点仅更新 order.pendingOrder.list" + ], + "module": "order" + }, { "version": "2026.08.18-setting.expressInterface.update-doc-params", "date": "2026-08-18", diff --git a/methods/system.json b/methods/system.json index 9ee3452..bba1056 100644 --- a/methods/system.json +++ b/methods/system.json @@ -2945,7 +2945,7 @@ "type": "object", "required": false, "source": "body", - "description": "统一 where 条件对象;禁止传入 warehouse_id / warehouseId。" + "description": "统一 where 条件对象;禁止传入 warehouse_id / warehouseId。where 无字段白名单,可直接传订单表列名。lock_status 锁定状态筛选(筛选值用数据库原始枚举 none/warehouse/store,不是响应中的 Y/N;ne 表示不等于;条件值为空自动忽略):未锁定 {\"lock_status\":\"none\"};已锁定(所有非 none){\"lock_status\":{\"operator\":\"ne\",\"value\":\"none\"}}。" }, { "name": "sort", From 932761155227d5966184c3951911ca9e603c993e Mon Sep 17 00:00:00 2001 From: liufumingren Date: Wed, 19 Aug 2026 00:00:45 +0800 Subject: [PATCH 234/550] =?UTF-8?q?fix(expressPlatform):=20=E9=9D=A2?= =?UTF-8?q?=E5=8D=95=E4=B8=8B=E5=8D=95=E5=8F=82=E6=95=B0=E8=B0=83=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 菠萝派/淘宝面单 payload 字段调整:tid/transtype/mainsubpaymode 等按平台传参, 移除暂不使用的字段 - 菜鸟取号:oaid 超 128 位时转 caid 传递、tid 改用 pay_no; 调试输出改缓存(Cainiaoquery/Cainiaoresult) --- app/service/systems/express_platform.js | 82 +++++++++++++------------ 1 file changed, 42 insertions(+), 40 deletions(-) diff --git a/app/service/systems/express_platform.js b/app/service/systems/express_platform.js index 71cf8bb..2b05b3f 100644 --- a/app/service/systems/express_platform.js +++ b/app/service/systems/express_platform.js @@ -707,45 +707,44 @@ class ExpressPlatformService extends MainService { object_Id: `${order.warehouse_id.toString(16)}_${order.id}_${order_tmp.business_key}`, // 菠萝派平台要求订单唯一标识必须为字符串 orderno: `${order.warehouse_id.toString(16)}_${order.id}_${order_tmp.business_key}`, // 菠萝派平台要求订单号必须为字符串 plattradeno: listByWarehousePlatformCode.platform_code === 'DY' && order.from_key === 23060081 && !!order.pay_no ? order.pay_no : order.source_order_codes || order.delivery_order_code || '', - ismultiplepieces: order.package_count > 1 ? 1 : 0, - logisticno: allocatedWaybillMap.get(`${Number(order.id) || 0}:${Number(order_tmp.business_key) || 0}`) || '', - logistictype: order.logistics_code || '', + tid:listByWarehousePlatformCode.platform_code === 'DY' && order.from_key === 23060081 && !!order.pay_no ? order.pay_no : order.source_order_codes || order.delivery_order_code || '', + //ismultiplepieces: order.package_count > 1 ? 1 : 0, + //logisticno: allocatedWaybillMap.get(`${Number(order.id) || 0}:${Number(order_tmp.business_key) || 0}`) || '', + logistictype: expressListItem[listByWarehousePlatformCode.platform_code] || '', providercode: expressListItem[listByWarehousePlatformCode.platform_code] || order.logistics_code || '', - numpackage: order.package_count || 1, - businessType: listByWarehousePlatformCode.product_type, + numpackage: order.package_count || '1', + businesstype: listByWarehousePlatformCode.product_type, + transtype:'0', + transtypecode:'1', + mainsubpaymode:'1', businessplat: order.sys_platform_code === 'KS' ? order.sys_platform_code : 'OTHERS', - paymode: listByWarehousePlatformCode.paymode ?? 1, + paymode: listByWarehousePlatformCode.paymode.toString() ?? '1', ordertype: listByWarehousePlatformCode.ordertype ?? 'JH_Normal', - ProviderID: listByWarehousePlatformCode.providerid ?? '', - procode: order.procode || '普通商品', - codpaymoney: order.ar_amount ?? null, - packagemoney: order.item_amount ?? null, - weight: Number(order.items_weight) || 0, // 单位 g,需确认 PolyAPI 期望单位 - supporpaymoney: order.total_amount ?? null, - length: Number(order.length) || 0, - width: Number(order.width) || 0, - height: Number(order.height) || 0, - volume: Number(order.volume) || 0, - ispickup: listByWarehousePlatformCode.ispickup ?? 0, - ProductType: listByWarehousePlatformCode.product_type || '', - Sipshopid: listByWarehousePlatformCode.platform_shop_id || '', + ProviderID:'', + //procode: order.procode || '普通商品', + //codpaymoney: order.ar_amount ?? null, + //packagemoney: order.item_amount ?? null, + //weight: Number(order.items_weight) || 0, // 单位 g,需确认 PolyAPI 期望单位 + //supporpaymoney: order.total_amount ?? null, + //ispickup: listByWarehousePlatformCode.ispickup ?? 0, + //ProductType: listByWarehousePlatformCode.product_type || '', + //Sipshopid: listByWarehousePlatformCode.platform_shop_id || '', oaid: order.oaid || '', - sys_express_code: listByWarehousePlatformCode.sys_express_code || '', - platform_code: listByWarehousePlatformCode.platform_code || '', cpcode: expressListItem[listByWarehousePlatformCode.platform_code] || '', logisticsproductname: 'JH_02', - dmssorting: 0, - brandno: listByWarehousePlatformCode.brandno || null, + //dmssorting: 0, + //brandno: listByWarehousePlatformCode.brandno || null, needencrypt: 1, + customername:"测试", ordersource: matchedPlatform.ordersource || '', - inputsite: listByWarehousePlatformCode.site_code || '', + //inputsite: order.sys_platform_code === 'XHS' ? '' :listByWarehousePlatformCode.site_code || '', sitecode: listByWarehousePlatformCode.site_code || '', - shipperno: listByWarehousePlatformCode.shipperno || '', - customercode: listByWarehousePlatformCode.shipperno || listByWarehousePlatformCode.client_id || '', + shipperno: order.sys_platform_code === 'XHS' ? '' :listByWarehousePlatformCode.shipperno || '', + customercode: order.sys_platform_code === 'XHS' ? '' :listByWarehousePlatformCode.shipperno || listByWarehousePlatformCode.client_id || '', sender: { - company: listByWarehousePlatformCode.shop_name || '', + Company: listByWarehousePlatformCode.shop_name || '', name: listByWarehousePlatformCode.sender_name || '', - phone: listByWarehousePlatformCode.sender_tel || '', + phone: order.sys_platform_code === 'XHS' ? undefined :listByWarehousePlatformCode.sender_tel || '', mobile: order.sys_platform_code === 'XHS' ? listByWarehousePlatformCode.sender_tel : undefined, country: 'CN', city: listByWarehousePlatformCode.city_name || '', @@ -771,21 +770,21 @@ class ExpressPlatformService extends MainService { }, goods: (order.orderItems && order.orderItems.map(item => ({ productid: item.item_code, - cnname: item.item_name || '商品', + cnname: 'sp', count: item.plan_qty || 0, }))) || [], - Mallmaskid: '', + //Mallmaskid: '', template_url: listByWarehousePlatformCode.template_id || '', - labelformat: listByWarehousePlatformCode.labelformat || '', - extraInfo: ExpressList.find(item => item.code === listByWarehousePlatformCode.sys_express_code)?.polyapi_extra_info || '', + //labelformat: listByWarehousePlatformCode.labelformat || '', + //extraInfo: ExpressList.find(item => item.code === listByWarehousePlatformCode.sys_express_code)?.polyapi_extra_info || '', }; console.log('matchedPlatform.platid', matchedPlatform.platid); console.log('startPlayload', playload); if (Number(matchedPlatform.platid) === 673) { playload.BizVersion = '2'; - playload.brandno = listByWarehousePlatformCode.brandno || ''; + playload.brandno = listByWarehousePlatformCode.brandno === "SF" ? listByWarehousePlatformCode.brandno : undefined; } if (Number(matchedPlatform.platid) === 544) { const { @@ -898,7 +897,7 @@ class ExpressPlatformService extends MainService { playload.mainsubpaymode = '1'; delete playload.plattradeno; } - playload.ProviderID = listByWarehousePlatformCode.providerid; + playload.ProviderID = listByWarehousePlatformCode.providerid || ""; console.log('playload', playload); return playload; }), @@ -1105,7 +1104,7 @@ class ExpressPlatformService extends MainService { receivertel: '', cargoname: '', senddata: '', - weight: '', + //weight: '', eCustomerCode: '', remark: '', selleruserid: '', @@ -1761,6 +1760,8 @@ class ExpressPlatformService extends MainService { .filter(Boolean) : []; const recipientMobile = orderDelivery && (orderDelivery.mobile || orderDelivery.tel) || ''; + const orderDeliveryOaid = orderDelivery && orderDelivery.oaid ? String(orderDelivery.oaid).trim() : ''; + const oaidTooLong = orderDeliveryOaid.length > 128; const tradeOrderInfo = { logistics_services: normalizedExtData, @@ -1797,10 +1798,10 @@ class ExpressPlatformService extends MainService { mobile: recipientMobile, name: orderDelivery && orderDelivery.name || '', phone: recipientMobile, - oaid: orderDelivery && orderDelivery.oaid || '', - tid: sourceOrderCodes[0] || '', + oaid: oaidTooLong ? '' : orderDeliveryOaid, + caid: oaidTooLong ? orderDeliveryOaid : '', + tid: orderDelivery.pay_no || '', }, - oaid: orderDelivery && orderDelivery.oaid || '', user_id: listByWarehousePlatformCode.shop && listByWarehousePlatformCode.shop.owner_id || 0, notify_extend_info: normalizedExtData, }; @@ -1842,7 +1843,8 @@ class ExpressPlatformService extends MainService { shipping_branch_code: String(listByWarehousePlatformCode.site_code || '').trim(), }, }; - console.log('cainiaoPayload', JSON.stringify(cainiaoPayload)); + + await this.app.setCacheAsync('Cainiaoquery', JSON.stringify(cainiaoPayload), 3600); const requestParams = { method: 'cainiao.waybill.ii.get', app_key: appKey, @@ -1865,7 +1867,7 @@ class ExpressPlatformService extends MainService { sign, }, }); - console.log('菜鸟取号返回数据', JSON.stringify(response)); + await this.app.setCacheAsync('Cainiaoresult', JSON.stringify(response), 3600); const responseData = response && Object.prototype.hasOwnProperty.call(response, 'data') ? response.data From bfbe231ff240e0a73fdac8f12d71b7854e7bccef Mon Sep 17 00:00:00 2001 From: liufumingren Date: Wed, 19 Aug 2026 03:22:44 +0800 Subject: [PATCH 235/550] =?UTF-8?q?feat(order):=20confirmIntercept=20?= =?UTF-8?q?=E6=94=B9=E4=B8=BA=20ids=20=E6=89=B9=E9=87=8F=E7=A1=AE=E8=AE=A4?= =?UTF-8?q?=E6=8B=A6=E6=88=AA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 入参由单值 order_id 改为批量 ids(数组/逗号字符串,兼容 id/order_id/orderId 单值写法) - 仅拦截发起中状态(requested/requesting/intercepting,历史值 intercepted 兼容)允许确认;none 静默跳过,已确认拦截及其它非可确认状态记录 failed - 更新 SQL where 同步限定 intercept_status 白名单,防止查询后状态被并发修改导致误更新 - 售后工单+快递群通知改为按成功订单 ID 汇总后统一调用一次 - 返回 success/failed 列表与 success_count/failed_count;同步更新接口文档与变更记录 --- .../systemMethods/order/recheckOrder.js | 296 ++++++++++++------ methods/changes/system.json | 17 + methods/system.json | 94 ++++-- 3 files changed, 272 insertions(+), 135 deletions(-) diff --git a/app/service/systemMethods/order/recheckOrder.js b/app/service/systemMethods/order/recheckOrder.js index 7ff99c0..c2a5d82 100644 --- a/app/service/systemMethods/order/recheckOrder.js +++ b/app/service/systemMethods/order/recheckOrder.js @@ -2,6 +2,14 @@ const OrderBaseService = require('./base'); +/** + * 允许确认拦截(更新为 intercepted_at_warehouse)的前置拦截状态: + * 拦截发起中(requested/requesting/intercepting)与历史遗留值 intercepted。 + * 其余状态(none/空、intercepted_at_warehouse、intercepted_in_transit、returning、returned、 + * delivered_by_mistake、timeout、cancelled、failed、exception)一律不允许确认拦截。 + */ +const CONFIRMABLE_INTERCEPT_STATUSES = [ 'requested', 'requesting', 'intercepting', 'intercepted' ]; + class RecheckOrderService extends OrderBaseService { /** * 初始化复核订单系统方法免登录、免权限、免日志与免鉴权配置。 @@ -3617,130 +3625,212 @@ class RecheckOrderService extends OrderBaseService { } /** - * 确认仓库拦截:通过订单ID直接匹配订单,将其拦截状态更新为"仓库拦截成功"。 - * 仅拦截当前指定订单(不波及波次内其他订单)。 + * 确认仓库拦截:通过订单 ID 列表直接匹配订单,批量将其拦截状态更新为"仓库拦截成功"。 + * 仅拦截当前指定订单(不波及波次内其他订单),支持部分失败:未找到的订单与处理失败的 + * 订单记录在 failed 列表并返回失败原因,其余订单继续处理。 + * + * 前置条件:订单必须处于拦截发起中状态(requested/requesting/intercepting,历史值 intercepted 兼容)。 + * 未发起拦截(none/空)的订单直接静默跳过不参与处理;已确认拦截(intercepted_at_warehouse)及其它 + * 非可确认状态(intercepted_in_transit/returning/returned/delivered_by_mistake/timeout/cancelled/failed/ + * exception)的订单一律跳过并记录失败原因;更新 SQL 的 where 同时限定拦截状态,防止并发修改导致误更新。 + * + * 每个订单的拦截处理: + * 1. 更新 wms_order_delivery:intercept_status = intercepted_at_warehouse、step=4、outbound_status=fin + * 2. 同步更新运单表:is_intercept='Y'、is_back='Y'(库内拦截确认,货物在库内需退回) + * 3. 释放储位分配(cancelAllocateStorage,归还库存) + * 4. 释放订单锁(lock_status='none') + * 5. 写入操作日志(ORDER_INTERCEPT_CONFIRM) + * 全部订单处理完后,按成功订单 ID 汇总批量创建售后工单 + 通知快递群。 + * 运单标记、储位释放、锁释放、工单创建、日志写入失败均不影响主流程。 + * * @param {Object} data 请求体。 - * @param {number} data.order_id 订单ID。 - * @return {Promise} 拦截确认结果,包含 order_id、intercept_status 与更新时间。 + * @param {number[]|string} data.ids 订单 ID 列表,支持数组或以逗号分隔的字符串(兼容 id/order_id/orderId 单值写法)。 + * @return {Promise} 批量拦截结果,包含 success/failed 列表与 success_count/failed_count 计数。 */ async confirmIntercept(data = {}) { const { ctx } = this; - const { order_id } = data; const warehouseId = this.getWarehouseId(); - const orderId = Number(order_id); + const orderIds = this.normalizeOrderIds(data); - if (!orderId || !Number.isFinite(orderId) || orderId <= 0) { - throw new Error('order_id 无效'); + if (orderIds.length === 0) { + this.ctx.throw(400, '订单ID列表不能为空'); } const orderModel = await this.getOrderModelByTableType('current', warehouseId); - const orderWhere = this.buildOrderWhere([ orderId ], warehouseId); - const order = await orderModel.findOne({ - where: orderWhere, + const orderRows = await orderModel.findAll({ + where: this.buildOrderWhere(orderIds, warehouseId), attributes: [ 'id', 'delivery_order_code', 'pre_delivery_order_code', 'intercept_status', 'wave_no' ], raw: true, }); - if (!order) { - throw new Error('未找到对应订单'); + const orderMap = new Map(); + for (const row of orderRows) { + orderMap.set(Number(row.id), row); } - const now = new Date(); - const updateValues = { - intercept_status: 'intercepted_at_warehouse', - step: 4, - outbound_status: 'fin', - updated_at: now, - }; - const updateResult = await orderModel.update(updateValues, { - where: orderWhere, - }); - const affectedRows = Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0); + const successOrders = []; + const failedOrders = []; + const successOrderIds = []; - if (affectedRows <= 0) { - throw new Error('拦截状态更新失败,请稍后重试'); + for (const orderId of orderIds) { + const order = orderMap.get(orderId); + + if (!order) { + failedOrders.push({ order_id: orderId, reason: '未找到对应订单' }); + continue; + } + + const orderWhere = this.buildOrderWhere([ orderId ], warehouseId); + const orderNo = String(order.delivery_order_code || order.pre_delivery_order_code || '').trim(); + const interceptStatus = String(order.intercept_status || '').trim(); + + // 未发起拦截(none/空)的订单直接跳过,不参与确认拦截处理 + if (interceptStatus === '' || interceptStatus === 'none') { + continue; + } + + // 已确认拦截的订单跳过,避免重复执行副作用(释放储位/工单/日志等) + if (interceptStatus === 'intercepted_at_warehouse') { + failedOrders.push({ + order_id: orderId, + delivery_order_code: orderNo, + reason: '订单已确认拦截', + }); + continue; + } + + // 仅拦截发起中(requested/requesting/intercepting)与历史值 intercepted 允许确认, + // 其余状态(intercepted_in_transit/returning/returned/delivered_by_mistake/timeout/ + // cancelled/failed/exception)不允许确认拦截 + if (!CONFIRMABLE_INTERCEPT_STATUSES.includes(interceptStatus)) { + failedOrders.push({ + order_id: orderId, + delivery_order_code: orderNo, + reason: `订单拦截状态不允许确认拦截: ${interceptStatus}`, + }); + continue; + } + + try { + const now = new Date(); + const updateValues = { + intercept_status: 'intercepted_at_warehouse', + step: 4, + outbound_status: 'fin', + updated_at: now, + }; + const updateResult = await orderModel.update(updateValues, { + where: { + ...orderWhere, + // 数据库层再次限定拦截状态,防止查询后状态被并发修改导致误更新 + intercept_status: { [ctx.app.Sequelize.Op.in]: CONFIRMABLE_INTERCEPT_STATUSES }, + }, + }); + const affectedRows = Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0); + + if (affectedRows <= 0) { + throw new Error('拦截状态更新失败,请稍后重试'); + } + + // 同步更新运单表:标记拦截 + 退回(库内拦截确认,货物在库内需退回) + try { + await ctx.model.OrderExpress.update( + { is_intercept: 'Y', is_back: 'Y' }, + { where: { order_id: orderId, warehouse_id: warehouseId } } + ); + } catch (expressErr) { + ctx.logger.warn( + `[recheckOrder.confirmIntercept] 更新运单拦截/退回标记失败, orderId=${orderId}, error=${expressErr.message}` + ); + } + + // 拦截成功后释放储位分配(归还库存) + try { + await this.service.systems.orderStorageAllocation.cancelAllocateStorage({ + order_ids: [ orderId ], + }); + } catch (allocErr) { + ctx.logger.warn( + `[recheckOrder.confirmIntercept] 释放储位分配失败,不影响拦截, orderId=${orderId}, error=${allocErr.message}` + ); + } + + // 拦截成功后释放订单锁 + try { + await orderModel.update( + { lock_status: 'none', updated_at: now }, + { where: orderWhere } + ); + } catch (lockErr) { + ctx.logger.warn( + `[recheckOrder.confirmIntercept] 释放锁失败,不影响拦截, orderId=${orderId}, error=${lockErr.message}` + ); + } + + // 写入操作日志(失败不影响主流程) + try { + const operator = this.getOrderLogOperator(); + const logWarehouseId = this.getOrderLogWarehouseId(warehouseId); + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'order', + businessId: orderId, + operationCode: 'ORDER_INTERCEPT_CONFIRM', + operator, + extras: { + warehouseId: logWarehouseId, + orderId, + orderNo, + previousInterceptStatus: String(order.intercept_status || '').trim(), + newInterceptStatus: 'intercepted_at_warehouse', + }, + beforeChanges: null, + }); + } catch (logErr) { + ctx.logger.warn( + `[recheckOrder.confirmIntercept] 写入操作日志失败,不影响业务, orderId=${orderId}, error=${logErr.message}` + ); + } + + successOrders.push({ + order_id: orderId, + order_no: orderNo, + intercept_status: 'intercepted_at_warehouse', + updated_at: now, + }); + successOrderIds.push(orderId); + } catch (error) { + ctx.logger.warn( + `[recheckOrder.confirmIntercept] 确认拦截失败, orderId=${orderId}, error=${error.message}` + ); + failedOrders.push({ + order_id: orderId, + delivery_order_code: orderNo, + reason: `确认拦截失败: ${error.message}`, + }); + } } - // 同步更新运单表:标记拦截 + 退回(库内拦截确认,货物在库内需退回) - try { - await ctx.model.OrderExpress.update( - { is_intercept: 'Y', is_back: 'Y' }, - { where: { order_id: orderId, warehouse_id: warehouseId } } - ); - } catch (expressErr) { - ctx.logger.warn( - `[recheckOrder.confirmIntercept] 更新运单拦截/退回标记失败, orderId=${orderId}, error=${expressErr.message}` - ); - } - - // 拦截成功后释放储位分配(归还库存) - try { - await this.service.systems.orderStorageAllocation.cancelAllocateStorage({ - order_ids: [ orderId ], - }); - } catch (allocErr) { - ctx.logger.warn( - `[recheckOrder.confirmIntercept] 释放储位分配失败,不影响拦截, orderId=${orderId}, error=${allocErr.message}` - ); - } - - // 拦截成功后释放订单锁 - try { - await orderModel.update( - { lock_status: 'none', updated_at: now }, - { where: orderWhere } - ); - } catch (lockErr) { - ctx.logger.warn( - `[recheckOrder.confirmIntercept] 释放锁失败,不影响拦截, orderId=${orderId}, error=${lockErr.message}` - ); - } - - // 创建售后工单 + 通知快递群(失败不影响主流程) - try { - const operator = this.getOrderLogOperator(); - await this.service.systems.afterSale.createInterceptWorkOrdersAndNotify({ - orderIds: [ orderId ], - warehouseId, - creatorLabel: operator.name || '系统', - }); - } catch (workOrderErr) { - ctx.logger.warn( - `[recheckOrder.confirmIntercept] 创建工单/通知失败, orderId=${orderId}, error=${workOrderErr.message}` - ); - } - - const orderNo = String(order.delivery_order_code || order.pre_delivery_order_code || '').trim(); - - // 写入操作日志(失败不影响主流程) - try { - const operator = this.getOrderLogOperator(); - const logWarehouseId = this.getOrderLogWarehouseId(warehouseId); - await ctx.service.systems.operationLog.createOperationLog({ - businessType: 'order', - businessId: orderId, - operationCode: 'ORDER_INTERCEPT_CONFIRM', - operator, - extras: { - warehouseId: logWarehouseId, - orderId, - orderNo, - previousInterceptStatus: String(order.intercept_status || '').trim(), - newInterceptStatus: 'intercepted_at_warehouse', - }, - beforeChanges: null, - }); - } catch (logErr) { - ctx.logger.warn( - `[recheckOrder.confirmIntercept] 写入操作日志失败,不影响业务, orderId=${orderId}, error=${logErr.message}` - ); + // 创建售后工单 + 通知快递群(成功订单 ID 汇总统一调用,失败不影响主流程) + if (successOrderIds.length > 0) { + try { + const operator = this.getOrderLogOperator(); + await this.service.systems.afterSale.createInterceptWorkOrdersAndNotify({ + orderIds: successOrderIds, + warehouseId, + creatorLabel: operator.name || '系统', + }); + } catch (workOrderErr) { + ctx.logger.warn( + `[recheckOrder.confirmIntercept] 创建工单/通知失败, orderIds=${successOrderIds.join(',')}, error=${workOrderErr.message}` + ); + } } return { - order_id: orderId, - order_no: orderNo, - intercept_status: 'intercepted_at_warehouse', - updated_at: now, + success: successOrders, + failed: failedOrders, + success_count: successOrders.length, + failed_count: failedOrders.length, }; } diff --git a/methods/changes/system.json b/methods/changes/system.json index 2d534ce..5c0f34b 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,21 @@ [ + { + "version": "2026.08.19-recheckOrder.confirmIntercept-ids", + "date": "2026-08-19", + "type": "enhanced", + "summary": "order.recheckOrder.confirmIntercept 入参由单值 order_id 改为批量 ids:支持数组或以逗号分隔的字符串(兼容 id/order_id/orderId 单值写法),批量确认拦截,返回 success/failed 列表与 success_count/failed_count 计数;单个订单失败不再阻断整体,未找到订单与更新失败订单记录在 failed 列表", + "methods": [ + "order.recheckOrder.confirmIntercept" + ], + "notes": [ + "app/service/systemMethods/order/recheckOrder.js confirmIntercept:用 base.normalizeOrderIds 解析 ids(兼容 ids/id/order_id/orderId),findAll 批量查询后逐订单执行拦截主流程(intercept_status=intercepted_at_warehouse、step=4、outbound_status=fin,运单标记 is_back/is_intercept='Y',释放储位分配与订单锁,写入 ORDER_INTERCEPT_CONFIRM 操作日志),未找到订单与处理异常订单记录 failed 不抛错,仅 ids 全部无效时 400「订单ID列表不能为空」", + "确认拦截前置校验:仅拦截发起中状态(requested/requesting/intercepting,历史值 intercepted 兼容)允许确认;未发起拦截(none/空)的订单直接静默跳过不参与处理,已确认拦截(intercepted_at_warehouse)订单跳过避免重复副作用并记录 failed「订单已确认拦截」,其余非可确认状态(intercepted_in_transit/returning/returned/delivered_by_mistake/timeout/cancelled/failed/exception)记录 failed「订单拦截状态不允许确认拦截: {状态}」;更新 SQL where 同时限定 intercept_status 白名单(CONFIRMABLE_INTERCEPT_STATUSES),防止查询后状态被并发修改导致误更新", + "售后工单+快递群通知由原每订单调用改为按成功订单 ID 汇总后统一调用一次 afterSale.createInterceptWorkOrdersAndNotify,失败仅告警", + "返回结构由单对象改为 { success, failed, success_count, failed_count },success 每项保持 order_id/order_no/intercept_status/updated_at,failed 每项含 order_id/delivery_order_code/reason", + "同步更新 methods/system.json 中该接口 params(ids)、response 与 errors 文档" + ], + "module": "order.recheckOrder" + }, { "version": "2026.08.18-order-list-lock-status-filter-doc", "date": "2026-08-18", diff --git a/methods/system.json b/methods/system.json index bba1056..f47531e 100644 --- a/methods/system.json +++ b/methods/system.json @@ -6039,7 +6039,7 @@ }, { "method": "order.recheckOrder.confirmIntercept", - "description": "确认拦截:通过订单ID直接匹配订单,将其拦截状态更新为 intercepted_at_warehouse(仓库已拦截),同时释放储位分配(cancelAllocateStorage)与订单锁(lock_status=none)。仅拦截当前指定订单,不波及波次内其他订单。操作成功后写入操作日志(ORDER_INTERCEPT_CONFIRM)。储位释放、锁释放、日志写入失败均不影响主流程。", + "description": "确认拦截:通过订单 ID 列表批量匹配订单,将拦截状态更新为 intercepted_at_warehouse(仓库已拦截,step=4、outbound_status=fin),同步标记运单退回与拦截(is_back='Y', is_intercept='Y'),并释放储位分配(cancelAllocateStorage)与订单锁(lock_status=none)。仅拦截当前指定订单,不波及波次内其他订单。前置条件:订单必须处于拦截发起中状态(requested/requesting/intercepting,历史值 intercepted 兼容),未发起拦截(none/空)的订单直接静默跳过不参与处理,已确认拦截(intercepted_at_warehouse)及其它非可确认状态(intercepted_in_transit/returning/returned/delivered_by_mistake/timeout/cancelled/failed/exception)一律跳过并记录失败原因;更新 SQL 的 where 同时限定拦截状态白名单,防止并发修改导致误更新。支持部分失败:未找到的订单与处理失败的订单记录在 failed 列表并返回失败原因,其余订单继续处理。全部订单处理完后按成功订单 ID 汇总批量创建售后工单 + 通知快递群。每个订单操作成功后写入操作日志(ORDER_INTERCEPT_CONFIRM)。运单标记、储位释放、锁释放、工单创建、日志写入失败均不影响主流程。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -6052,53 +6052,83 @@ ], "params": [ { - "name": "order_id", - "type": "number", + "name": "ids", + "type": "array|string", "required": true, "source": "body", - "description": "订单 ID" + "description": "订单 ID 列表,支持数组或以逗号分隔的字符串。兼容 id / order_id / orderId 单值写法" } ], "response": [ { - "name": "order_id", + "name": "success", + "type": "array", + "required": true, + "description": "拦截成功的订单列表", + "children": [ + { + "name": "order_id", + "type": "number", + "description": "订单 ID" + }, + { + "name": "order_no", + "type": "string", + "description": "订单号(优先 delivery_order_code,其次 pre_delivery_order_code)" + }, + { + "name": "intercept_status", + "type": "string", + "description": "拦截状态(固定为 'intercepted_at_warehouse')" + }, + { + "name": "updated_at", + "type": "string", + "description": "更新时间(ISO 字符串)" + } + ] + }, + { + "name": "failed", + "type": "array", + "required": true, + "description": "拦截失败的订单列表", + "children": [ + { + "name": "order_id", + "type": "number", + "description": "订单 ID" + }, + { + "name": "delivery_order_code", + "type": "string", + "description": "发货单号(订单存在时返回)" + }, + { + "name": "reason", + "type": "string", + "description": "失败原因(未找到对应订单 / 订单已确认拦截 / 订单拦截状态不允许确认拦截: xxx / 确认拦截失败: xxx);拦截状态为 none 的订单静默跳过,不进入 failed" + } + ] + }, + { + "name": "success_count", "type": "number", "required": true, - "description": "订单 ID" + "description": "成功数量" }, { - "name": "order_no", - "type": "string", + "name": "failed_count", + "type": "number", "required": true, - "description": "订单号(优先 delivery_order_code,其次 pre_delivery_order_code)" - }, - { - "name": "intercept_status", - "type": "string", - "required": true, - "description": "拦截状态(固定为 'intercepted_at_warehouse')" - }, - { - "name": "updated_at", - "type": "string", - "required": true, - "description": "更新时间(ISO 字符串)" + "description": "失败数量" } ], "errors": [ { "code": 400, - "message": "order_id 无效", - "description": "order_id 无效(为空或非正整数)" - }, - { - "code": 404, - "message": "未找到对应订单" - }, - { - "code": 500, - "message": "拦截状态更新失败,请稍后重试", - "description": "数据库更新影响行数为 0 时返回" + "message": "订单ID列表不能为空", + "description": "ids 为空或全部无效(非正整数)时返回" } ] }, From ace0e456a7d9d05f9cc6c3fed90520c0be3c499c Mon Sep 17 00:00:00 2001 From: liufumingren Date: Wed, 19 Aug 2026 03:23:50 +0800 Subject: [PATCH 236/550] =?UTF-8?q?feat(order):=20=E8=AE=A2=E5=8D=95?= =?UTF-8?q?=E5=88=97=E8=A1=A8=E8=81=94=E6=9F=A5=E6=B3=A2=E6=AC=A1=E5=BA=8F?= =?UTF-8?q?=E5=8F=B7=E5=89=AF=E8=A1=A8=E5=B9=B6=E6=94=AF=E6=8C=81=E5=BA=8F?= =?UTF-8?q?=E5=8F=B7=E8=8C=83=E5=9B=B4=E7=AD=9B=E9=80=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 所有订单列表联查 wms_order_wave_index 输出 wave_index(9 个工作台列表/复核散单列表/波次策略兜底列表,无记录降级 0) - 新增 wave_index 虚拟筛选入参:between/eq/in/gt/lt/ge/le/notbetween,between 要求 value 为长度 2 的数组;复核散单列表支持 wave_index_min/wave_index_max - 订单导出(waybill/item 模式)接入 wave_index 联查并新增波次序号列 - 新增 app/model/order_wave_index.js 副表模型 - 同步 methods/system.json 接口说明与 methods/changes/system.json 变更记录 --- app/model/order_wave_index.js | 63 +++++++ app/service/systemMethods/order/base.js | 175 +++++++++++++++++- .../systemMethods/order/recheckOrder.js | 70 ++++++- app/service/systemMethods/order/wave.js | 7 +- app/service/systems/order_export.js | 20 +- methods/changes/system.json | 55 ++++++ methods/system.json | 33 ++-- 7 files changed, 398 insertions(+), 25 deletions(-) create mode 100644 app/model/order_wave_index.js diff --git a/app/model/order_wave_index.js b/app/model/order_wave_index.js new file mode 100644 index 0000000..c1ba3c1 --- /dev/null +++ b/app/model/order_wave_index.js @@ -0,0 +1,63 @@ +'use strict'; + +/** + * 订单波次顺序定位副表模型。 + * 表结构:database/migrations/20260513113000-create-wms_order_wave_index.js + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} Sequelize 模型。 + */ +module.exports = app => { + const { BIGINT, INTEGER, DATE } = app.Sequelize; + + const OrderWaveIndex = app.model.define('wms_order_wave_index', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '仓库ID', + }, + order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '订单ID', + }, + wave_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '波次ID', + }, + wave_index: { + type: INTEGER(10).UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '订单在波次中的全局顺序', + }, + platforms_index: { + type: INTEGER(10).UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '订单在平台分组内顺序', + }, + create_at: { + type: DATE, + allowNull: false, + comment: '创建时间', + }, + }, { + tableName: 'wms_order_wave_index', + timestamps: false, + underscored: true, + comment: '订单波次顺序定位副表', + }); + + return OrderWaveIndex; +}; diff --git a/app/service/systemMethods/order/base.js b/app/service/systemMethods/order/base.js index 64dbe36..076dbce 100644 --- a/app/service/systemMethods/order/base.js +++ b/app/service/systemMethods/order/base.js @@ -938,6 +938,70 @@ class OrderBaseService extends MainService { }); } + /** + * 批量补齐订单列表的波次内序号(wms_order_wave_index.wave_index)。 + * 表无记录或查询异常时降级为 0,不影响列表主流程。 + * @param {Object[]} list 订单列表,每项需含 id(订单ID)。 + * @return {Promise} 补齐 wave_index 后的列表。 + */ + async attachOrderWaveIndex(list = []) { + if (!Array.isArray(list) || list.length === 0) { + return Array.isArray(list) ? list : []; + } + + const orderIds = Array.from(new Set( + list + .map(item => Number(item && item.id)) + .filter(value => Number.isFinite(value) && value > 0) + )); + + if (orderIds.length === 0) { + return list.map(item => ({ ...item, wave_index: 0 })); + } + + const warehouseId = this.getWarehouseId(); + const { ctx } = this; + const waveIndexMap = new Map(); + + if (warehouseId !== null && warehouseId !== undefined && warehouseId !== '' + && ctx.model && typeof ctx.model.query === 'function') { + try { + const rows = await ctx.model.query(` + SELECT order_id, wave_index + FROM wms_order_wave_index + WHERE warehouse_id = :warehouseId + AND order_id IN (:orderIds) + `, { + replacements: { warehouseId, orderIds }, + type: ctx.model.QueryTypes && ctx.model.QueryTypes.SELECT, + }); + + for (const row of (Array.isArray(rows) ? rows : [])) { + const orderId = Number(row && row.order_id || 0); + if (orderId > 0) { + waveIndexMap.set(orderId, Number(row && row.wave_index || 0)); + } + } + } catch (error) { + ctx.logger && ctx.logger.warn && ctx.logger.warn('[order.base.attachOrderWaveIndex] 查询波次序号失败,已降级为 0', { + warehouseId, + orderCount: orderIds.length, + error: error && error.message ? error.message : `${error}`, + }); + } + } + + return list.map(item => { + const orderId = Number(item && item.id); + return { + ...item, + wave_index: Number.isFinite(orderId) && orderId > 0 && waveIndexMap.has(orderId) + ? waveIndexMap.get(orderId) + : 0, + }; + }); + } + /** * 提取订单列表中的运单号虚拟筛选条件。 * @param {Object} whereInput 标准化后的 where 条件。 @@ -1028,6 +1092,106 @@ class OrderBaseService extends MainService { return { where: normalizedWhere, stockQuery }; } + /** + * 提取 wave_index(波次内序号)虚拟筛选条件。 + * 序号存储在 wms_order_wave_index 副表,需先查副表得到订单 ID 集合再注入主查询。 + * 支持 eq / in / gt / lt / ge / le / between / notbetween 等操作符, + * 其中 between 要求 value 为长度为 2 的数组(如 [1, 50])。 + * @param {Object} whereInput 标准化后的 where 条件。 + * @return {{ where: Object, waveIndexCondition: Object|null }} 清洗后的 where 与序号筛选条件。 + */ + extractWaveIndexVirtualFilter(whereInput = {}) { + const normalizedWhere = this.isPlainObject(whereInput) + ? { ...whereInput } + : {}; + const waveIndexCondition = normalizedWhere.wave_index ?? normalizedWhere.waveIndex; + + delete normalizedWhere.wave_index; + delete normalizedWhere.waveIndex; + + // 条件为空时忽略 + if (waveIndexCondition === undefined || waveIndexCondition === null || waveIndexCondition === '') { + return { where: normalizedWhere, waveIndexCondition: null }; + } + + if (this.isPlainObject(waveIndexCondition) + && (waveIndexCondition.value === undefined || waveIndexCondition.value === null || waveIndexCondition.value === '')) { + return { where: normalizedWhere, waveIndexCondition: null }; + } + + // 兼容简写:wave_index 直接传数值时按 eq 处理 + const normalizedCondition = this.isPlainObject(waveIndexCondition) + ? { ...waveIndexCondition } + : { operator: 'eq', value: waveIndexCondition }; + + return { where: normalizedWhere, waveIndexCondition: normalizedCondition }; + } + + /** + * 根据 wave_index 筛选条件查询 wms_order_wave_index 命中的订单ID。 + * @param {Object} waveIndexCondition 序号筛选条件(含 operator/value)。 + * @param {number|string} warehouseId 仓库ID。 + * @return {Promise} 命中的订单ID列表。 + */ + async findOrderIdsByWaveIndexCondition(waveIndexCondition = null, warehouseId = this.getWarehouseId()) { + const contextWarehouseId = this.getWarehouseId(); + + if (contextWarehouseId === null || contextWarehouseId === undefined || contextWarehouseId === '') { + throw new Error('缺少当前用户仓库上下文 store_id'); + } + + if (warehouseId !== null && warehouseId !== undefined && warehouseId !== '' + && String(warehouseId) !== String(contextWarehouseId)) { + throw new Error('订单工作台仓库ID必须来自当前用户上下文 store_id,禁止传入外部仓库ID。'); + } + + if (!waveIndexCondition || !this.isPlainObject(waveIndexCondition)) { + return []; + } + + const orderWaveIndexModel = this.ctx.model && this.ctx.model.OrderWaveIndex; + if (!orderWaveIndexModel || typeof orderWaveIndexModel.findAll !== 'function') { + return []; + } + + const parsed = parseWhereConditions({ + where: { wave_index: waveIndexCondition }, + app: this.app, + }); + + if (!parsed.ok) { + throw new Error(`wave_index 参数解析失败: ${parsed.reason}`); + } + + const { Sequelize } = this.app; + const conditions = Array.isArray(parsed.result.dynamicConditions) + ? parsed.result.dynamicConditions + : []; + + if (conditions.length === 0) { + return []; + } + + const waveIndexWhere = conditions.length > 1 + ? { [Sequelize.Op.and]: conditions } + : conditions[0]; + + const rows = await orderWaveIndexModel.findAll({ + where: { + [Sequelize.Op.and]: [ + waveIndexWhere, + { warehouse_id: contextWarehouseId }, + ], + }, + attributes: [ 'order_id' ], + raw: true, + }); + + return Array.from(new Set((Array.isArray(rows) ? rows : []) + .map(row => Number(row && row.order_id)) + .filter(orderId => Number.isFinite(orderId) && orderId > 0))); + } + /** * 构建 buyer_message_has 虚拟字段的 Sequelize where 条件。 * 覆盖三个留言/备注字段:buyer_message、seller_message、remark。 @@ -1429,7 +1593,8 @@ class OrderBaseService extends MainService { const { where: sanitizedWhere, expressNumbers } = this.extractOrderListExpressVirtualFilter(where); const { where: whereAfterBuyerMessage, buyerMessageHas } = this.extractBuyerMessageHasVirtualFilter(sanitizedWhere); const { where: whereAfterStockQuery, stockQuery } = this.extractStockQueryVirtualFilter(whereAfterBuyerMessage); - const mergedWhere = this.mergeWhereObjects(this.getDefaultWhere(moduleName), whereAfterStockQuery); + const { where: whereAfterWaveIndex, waveIndexCondition } = this.extractWaveIndexVirtualFilter(whereAfterStockQuery); + const mergedWhere = this.mergeWhereObjects(this.getDefaultWhere(moduleName), whereAfterWaveIndex); let queryWhere = this.buildWhere(mergedWhere, contextWarehouseId, { specialFieldMap: { quickWhere: { @@ -1453,6 +1618,11 @@ class OrderBaseService extends MainService { queryWhere = this.appendOrderIdsFilterToWhere(queryWhere, stockOrderIds); } + if (waveIndexCondition) { + const waveIndexOrderIds = await this.findOrderIdsByWaveIndexCondition(waveIndexCondition, contextWarehouseId); + queryWhere = this.appendOrderIdsFilterToWhere(queryWhere, waveIndexOrderIds); + } + const model = await this.getOrderModel(moduleName, contextWarehouseId); const order = this.buildListOrder(requestData.sort, moduleName); const offset = (page - 1) * pageSize; @@ -1511,11 +1681,12 @@ class OrderBaseService extends MainService { })); const normalizedList = await this.attachOrderExpressNumbers(listWithRemark); + const listWithWaveIndex = await this.attachOrderWaveIndex(normalizedList); const totalPages = pageSize > 0 ? Math.ceil(total / pageSize) : 0; return { - list: normalizedList, + list: listWithWaveIndex, pagination: { page, pageSize, diff --git a/app/service/systemMethods/order/recheckOrder.js b/app/service/systemMethods/order/recheckOrder.js index c2a5d82..559c211 100644 --- a/app/service/systemMethods/order/recheckOrder.js +++ b/app/service/systemMethods/order/recheckOrder.js @@ -3323,6 +3323,65 @@ class RecheckOrderService extends OrderBaseService { replacements.pickStatus = pickStatus; } + // 波次内序号筛选(wms_order_wave_index.wave_index) + // 支持 wave_index: { operator: 'between', value: [起, 止] },以及 wave_index_min / wave_index_max + const rawWaveIndexCondition = this.isPlainObject(where.wave_index) ? where.wave_index : null; + if (rawWaveIndexCondition) { + const waveIndexOperator = String(rawWaveIndexCondition.operator || 'eq').toLowerCase(); + const rawWaveIndexValue = rawWaveIndexCondition.value; + if (waveIndexOperator === 'between' && Array.isArray(rawWaveIndexValue) && rawWaveIndexValue.length === 2) { + const betweenStart = Number(rawWaveIndexValue[0]); + const betweenEnd = Number(rawWaveIndexValue[1]); + if (Number.isFinite(betweenStart) && Number.isFinite(betweenEnd)) { + conditions.push('wi.wave_index BETWEEN :waveIndexBetweenStart AND :waveIndexBetweenEnd'); + replacements.waveIndexBetweenStart = betweenStart; + replacements.waveIndexBetweenEnd = betweenEnd; + } + } else if ((waveIndexOperator === 'gte' || waveIndexOperator === 'ge') + && rawWaveIndexValue !== undefined && rawWaveIndexValue !== null && rawWaveIndexValue !== '') { + const gteValue = Number(rawWaveIndexValue); + if (Number.isFinite(gteValue)) { + conditions.push('wi.wave_index >= :waveIndexGte'); + replacements.waveIndexGte = gteValue; + } + } else if ((waveIndexOperator === 'lte' || waveIndexOperator === 'le') + && rawWaveIndexValue !== undefined && rawWaveIndexValue !== null && rawWaveIndexValue !== '') { + const lteValue = Number(rawWaveIndexValue); + if (Number.isFinite(lteValue)) { + conditions.push('wi.wave_index <= :waveIndexLte'); + replacements.waveIndexLte = lteValue; + } + } else if (waveIndexOperator === 'eq' + && rawWaveIndexValue !== undefined && rawWaveIndexValue !== null && rawWaveIndexValue !== '') { + const eqValue = Number(rawWaveIndexValue); + if (Number.isFinite(eqValue)) { + conditions.push('wi.wave_index = :waveIndexEq'); + replacements.waveIndexEq = eqValue; + } + } + } else { + const rawWaveIndexMin = this.isPlainObject(where.wave_index_min) + ? where.wave_index_min.value + : where.wave_index_min; + if (rawWaveIndexMin !== undefined && rawWaveIndexMin !== null && rawWaveIndexMin !== '') { + const waveIndexMin = Number(rawWaveIndexMin); + if (Number.isFinite(waveIndexMin)) { + conditions.push('wi.wave_index >= :waveIndexMin'); + replacements.waveIndexMin = waveIndexMin; + } + } + const rawWaveIndexMax = this.isPlainObject(where.wave_index_max) + ? where.wave_index_max.value + : where.wave_index_max; + if (rawWaveIndexMax !== undefined && rawWaveIndexMax !== null && rawWaveIndexMax !== '') { + const waveIndexMax = Number(rawWaveIndexMax); + if (Number.isFinite(waveIndexMax)) { + conditions.push('wi.wave_index <= :waveIndexMax'); + replacements.waveIndexMax = waveIndexMax; + } + } + } + // stock_query 商品模糊筛选:通过 stock_warehouse / stock_barcodes → order_items → order_id const stockQuery = String(where.stock_query || '').trim(); if (stockQuery) { @@ -3350,6 +3409,11 @@ class RecheckOrderService extends OrderBaseService { ? `WHERE ${conditions.join('\n AND ')}` : ''; + const waveIndexJoin = ` + LEFT JOIN wms_order_wave_index wi + ON wi.warehouse_id = o.warehouse_id + AND wi.order_id = o.id`; + const listSql = ` SELECT o.id AS order_id, @@ -3369,8 +3433,9 @@ class RecheckOrderService extends OrderBaseService { o.status, o.create_at, o.recheck_time, + wi.wave_index, (SELECT oe.waybill_code FROM order_express oe WHERE oe.order_id = o.id AND oe.delete_at IS NULL LIMIT 1) AS waybill_code - FROM ${orderTableName} o + FROM ${orderTableName} o${waveIndexJoin} ${whereClause} ORDER BY o.id ASC LIMIT :limit OFFSET :offset @@ -3378,7 +3443,7 @@ class RecheckOrderService extends OrderBaseService { const countSql = ` SELECT COUNT(1) AS total - FROM ${orderTableName} o + FROM ${orderTableName} o${waveIndexJoin} ${whereClause} `; @@ -3413,6 +3478,7 @@ class RecheckOrderService extends OrderBaseService { items_weight: row?.items_weight != null ? Number(row.items_weight) : null, weight_type: this.formatWeightTypeLabel(row?.weight_type), waybill_code: String(row?.waybill_code || '').trim(), + wave_index: Number(row?.wave_index || 0), status: Number(row?.status || 0), create_at: row?.create_at || null, recheck_time: row?.recheck_time || null, diff --git a/app/service/systemMethods/order/wave.js b/app/service/systemMethods/order/wave.js index cb21d9c..4e87f47 100644 --- a/app/service/systemMethods/order/wave.js +++ b/app/service/systemMethods/order/wave.js @@ -3991,6 +3991,7 @@ class WaveService extends OrderBaseService { province: normalizedOrderRow.province ?? null, sys_platform_name: normalizedOrderRow.sys_platform_name ?? null, item_snapshot: String(itemSnapshot || ''), + wave_index: Number(normalizedOrderRow.wave_index || 0), excluded_reason: normalizedOrderRow.lock_status !== 'none' ? 'locked' : normalizedOrderRow.intercept_status !== 'none' @@ -4086,8 +4087,10 @@ class WaveService extends OrderBaseService { }), ]); - const normalizedList = await this.attachOrderExpressNumbers( - sourceList.map(item => this.normalizeOrderListItem(item)) + const normalizedList = await this.attachOrderWaveIndex( + await this.attachOrderExpressNumbers( + sourceList.map(item => this.normalizeOrderListItem(item)) + ) ); // 回填 item_snapshot diff --git a/app/service/systems/order_export.js b/app/service/systems/order_export.js index 4c66a92..6055795 100644 --- a/app/service/systems/order_export.js +++ b/app/service/systems/order_export.js @@ -28,6 +28,7 @@ const ORDER_EXPORT_COLUMNS = Object.freeze([ { header: '平台单号', key: 'external_order_code', width: 24 }, { header: '订单状态', key: 'status', width: 16 }, { header: '抓取波次号', key: 'wave_no', width: 18 }, + { header: '波次序号', key: 'wave_index', width: 12 }, { header: '货主', key: 'store_id', width: 20 }, { header: '平台', key: 'sys_platform_name', width: 16 }, { header: '店铺昵称', key: 'shop_nick', width: 20 }, @@ -74,6 +75,7 @@ const ORDER_EXPORT_ITEM_COLUMNS = Object.freeze([ { header: '外部单号', key: 'external_order_code', width: 24 }, { header: '订单状态', key: 'status', width: 16 }, { header: '波次号', key: 'wave_no', width: 18 }, + { header: '波次序号', key: 'wave_index', width: 12 }, { header: '货主', key: 'store_id', width: 20 }, { header: '平台', key: 'sys_platform_name', width: 16 }, { header: '店铺昵称', key: 'shop_nick', width: 20 }, @@ -402,6 +404,7 @@ class OrderExportService extends OrderBaseService { external_order_code: this.normalizeExportCellValue(externalOrderCode), status: translateStatus('status', safeOrderRow.status), wave_no: this.normalizeExportCellValue(safeOrderRow.wave_no), + wave_index: this.normalizeExportCellValue(safeOrderRow.wave_index ?? 0), store_id: this.normalizeExportCellValue(storeRemark || safeOrderRow.store_name || safeOrderRow.store_id), sys_platform_name: this.normalizeExportCellValue(safeOrderRow.sys_platform_name), shop_nick: this.normalizeExportCellValue(safeOrderRow.shop_nick), @@ -616,9 +619,10 @@ class OrderExportService extends OrderBaseService { }); const { where: sanitizedWhere, expressNumbers } = this.extractOrderListExpressVirtualFilter(where); const { where: whereAfterBuyerMessage, buyerMessageHas } = this.extractBuyerMessageHasVirtualFilter(sanitizedWhere); + const { where: whereAfterWaveIndex, waveIndexCondition } = this.extractWaveIndexVirtualFilter(whereAfterBuyerMessage); const mergedWhere = this.mergeWhereObjects( target.defaultWhereModuleName ? this.getDefaultWhere(target.defaultWhereModuleName) : {}, - whereAfterBuyerMessage + whereAfterWaveIndex ); let queryWhere = this.buildWhere(mergedWhere, warehouseId, { specialFieldMap: { @@ -638,6 +642,11 @@ class OrderExportService extends OrderBaseService { queryWhere = this.appendConditionToWhere(queryWhere, buyerMessageCondition); } + if (waveIndexCondition) { + const waveIndexOrderIds = await this.findOrderIdsByWaveIndexCondition(waveIndexCondition, warehouseId); + queryWhere = this.appendOrderIdsFilterToWhere(queryWhere, waveIndexOrderIds); + } + const orderModel = await this.getOrderModelByTableType(target.tableType, warehouseId); const pageSize = this.getExportPageSize(); const order = this.buildListOrder(requestData.sort, target.sortModuleName); @@ -683,8 +692,9 @@ class OrderExportService extends OrderBaseService { const normalizedRows = rows.map(row => this.normalizeOrderListItem(this.toPlainRow(row)) ); + const rowsWithWaveIndex = await this.attachOrderWaveIndex(normalizedRows); - const orderIds = normalizedRows.map(r => Number(r.id || 0)).filter(id => id > 0); + const orderIds = rowsWithWaveIndex.map(r => Number(r.id || 0)).filter(id => id > 0); // 批量查询商品明细(wms_order_items) const itemsMap = new Map(); @@ -759,7 +769,7 @@ class OrderExportService extends OrderBaseService { try { const storeIds = [ ...new Set( - normalizedRows + rowsWithWaveIndex .map(r => Number(r.store_id || 0)) .filter(id => id > 0) ), @@ -844,14 +854,14 @@ class OrderExportService extends OrderBaseService { const exportContext = { itemsMap, storeRemarkMap, stockNameMap, barcodeMap, imageUrlMap, expressMap, packageMaterialMap }; - for (const row of normalizedRows) { + for (const row of rowsWithWaveIndex) { const exportRows = this.mapOrderExportRow(row, exportContext, mode); for (const exportRow of exportRows) { worksheet.addRow(exportRow).commit(); } } - currentCount += normalizedRows.length; + currentCount += rowsWithWaveIndex.length; await progressHandler({ status: 'running', diff --git a/methods/changes/system.json b/methods/changes/system.json index 5c0f34b..92e3a32 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,59 @@ [ + { + "version": "2026.08.19-order-list-wave-index-range-filter", + "date": "2026-08-19", + "type": "enhanced", + "summary": "订单列表 where 新增 wave_index 波次内序号范围查询入参:工作台订单列表(经 listByModule 的 9 个列表)与订单导出支持 wave_index 虚拟筛选(eq/in/gt/lt/ge/le/between/notbetween,between 要求 value 为长度 2 的数组);复核散单列表支持 wave_index between 与 wave_index_min/wave_index_max。", + "methods": [ + "order.list", + "order.reviewOrder.list", + "order.pendingOrder.list", + "order.outboundOrder.list", + "order.expectionOrder.list", + "order.entrustOrder.list", + "order.deliveryOrder.list", + "order.deliveryExpectionOrder.list", + "order.archiveOrder.list", + "order.recheckOrder.recheckOrderList", + "order.recheckOrder.queryRecheckOrderSingleList" + ], + "notes": [ + "新增 app/model/order_wave_index.js 模型(wms_order_wave_index,timestamps=false),供副表条件查询", + "app/service/systemMethods/order/base.js 新增 extractWaveIndexVirtualFilter(从 where 提取 wave_index/waveIndex,兼容数值简写按 eq 处理)与 findOrderIdsByWaveIndexCondition(用 parseWhereConditions 解析条件后查副表得 order_id 集合);listByModule 在 stock_query 之后接入,命中为空时主查询结果为空", + "app/service/systems/order_export.js exportOrders 同样接入 wave_index 虚拟筛选,与列表 where 语义一致", + "app/service/systemMethods/order/recheckOrder.js queryRecheckOrderSingleList 新增 wave_index 筛选(between/gte/lte/eq 或 wave_index_min/wave_index_max),countSql 同步 LEFT JOIN wms_order_wave_index 保持总数一致", + "同步更新 methods/system.json 中 order.list 与复核列表 where 参数说明" + ], + "module": "order" + }, + { + "version": "2026.08.19-order-list-wave-index-join", + "date": "2026-08-19", + "type": "enhanced", + "summary": "所有订单列表统一联查 wms_order_wave_index 并输出 wave_index(波次内序号,无记录时降级为 0):覆盖 9 个工作台订单列表(order.list / reviewOrder.list / pendingOrder.list / outboundOrder.list / expectionOrder.list / entrustOrder.list / deliveryOrder.list / deliveryExpectionOrder.list / archiveOrder.list)、复核散单列表与波次策略兜底列表;订单导出(waybill/item 两种模式)新增「波次序号」列。", + "methods": [ + "order.list", + "order.reviewOrder.list", + "order.pendingOrder.list", + "order.outboundOrder.list", + "order.expectionOrder.list", + "order.entrustOrder.list", + "order.deliveryOrder.list", + "order.deliveryExpectionOrder.list", + "order.archiveOrder.list", + "order.recheckOrder.recheckOrderList", + "order.recheckOrder.queryRecheckOrderSingleList", + "order.wave.waveStrategyFallbackOrderList" + ], + "notes": [ + "app/service/systemMethods/order/base.js 新增 attachOrderWaveIndex:按列表行 id 批量查询 wms_order_wave_index(warehouse_id + order_id,命中唯一索引),无记录或查询异常时降级为 0 并告警;listByModule 在 attachOrderExpressNumbers 之后接入,统一覆盖全部工作台订单列表", + "app/service/systemMethods/order/wave.js waveStrategyFallbackOrderList 接入 attachOrderWaveIndex,buildWaveStrategyFallbackOrderListItem 输出 wave_index(默认 0)", + "app/service/systemMethods/order/recheckOrder.js queryRecheckOrderSingleList 列表 SQL 增加 LEFT JOIN wms_order_wave_index(warehouse_id + order_id),响应行新增 wave_index;recheckOrderList 散单分支同源生效", + "app/service/systems/order_export.js exportOrders 接入 attachOrderWaveIndex,ORDER_EXPORT_COLUMNS / ORDER_EXPORT_ITEM_COLUMNS 在波次号后新增「波次序号」列,mapOrderExportRow commonFields 新增 wave_index", + "同步更新 methods/system.json 中上述接口的 response 字段说明" + ], + "module": "order" + }, { "version": "2026.08.19-recheckOrder.confirmIntercept-ids", "date": "2026-08-19", diff --git a/methods/system.json b/methods/system.json index f47531e..bc78520 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1768,7 +1768,7 @@ "type": "object", "required": false, "source": "body", - "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会自动标准化;禁止传入 warehouse_id / warehouseId。支持虚拟字段:buyer_message_has(覆盖 buyer_message/seller_message/remark 三个字段,任一有值即为有留言,value=true/false),express_numbers / waybill_codes(运单号筛选)。" + "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会自动标准化;禁止传入 warehouse_id / warehouseId。支持虚拟字段:buyer_message_has(覆盖 buyer_message/seller_message/remark 三个字段,任一有值即为有留言,value=true/false),express_numbers / waybill_codes(运单号筛选),wave_index(波次内序号筛选,联查 wms_order_wave_index,支持 eq/in/gt/lt/ge/le/between/notbetween,between 要求 value 为长度 2 的数组,如 {\"wave_index\":{\"operator\":\"between\",\"value\":[1,50]}})。" }, { "name": "sort", @@ -1783,7 +1783,7 @@ "name": "list", "type": "array", "required": true, - "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节),本次新增 store_remark(货主备注)字段。" + "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节),本次新增 store_remark(货主备注)字段;wave_index(波次内序号,联查 wms_order_wave_index,无记录时为 0)。" }, { "name": "pagination", @@ -2669,7 +2669,7 @@ "name": "list", "type": "array", "required": true, - "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节),本次新增 store_remark(货主备注)字段。" + "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节),本次新增 store_remark(货主备注)字段;wave_index(波次内序号,联查 wms_order_wave_index,无记录时为 0)。" }, { "name": "pagination", @@ -2960,7 +2960,7 @@ "name": "list", "type": "array", "required": true, - "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节),本次新增 store_remark(货主备注)字段。lock_status 字段统一输出为 Y/N:none(含空值)→ 'N',其余值(如 warehouse/store)→ 'Y'。" + "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节),本次新增 store_remark(货主备注)字段;wave_index(波次内序号,联查 wms_order_wave_index,无记录时为 0)。lock_status 字段统一输出为 Y/N:none(含空值)→ 'N',其余值(如 warehouse/store)→ 'Y'。" }, { "name": "pagination", @@ -6223,7 +6223,7 @@ "type": "object", "required": false, "source": "body", - "description": "筛选条件。散单模式支持 keyword(运单号/订单号模糊搜索)、wave_no(精确匹配)、recheck_status、pick_status;团购模式支持 wave_no(模糊搜索)、wave_type、wave_status" + "description": "筛选条件。散单模式支持 keyword(运单号/订单号模糊搜索)、wave_no(精确匹配)、recheck_status、pick_status、wave_index(波次内序号范围筛选,如 {\"operator\":\"between\",\"value\":[起,止]},或 wave_index_min / wave_index_max);团购模式支持 wave_no(模糊搜索)、wave_type、wave_status" }, { "name": "pagination", @@ -6238,7 +6238,7 @@ "name": "list", "type": "array", "required": true, - "description": "散单模式(list_type=single):订单数组,每项含 order_id、delivery_order_code、order_type、wave_id、wave_no、pick_status、recheck_status、shop_nick、logistics_name、items_count、items_total、status、create_at、pick_time、recheck_time。团购模式(list_type=group):波次汇总数组,每项含 wave_id、wave_no、wave_type、wave_status、total_orders、processed_orders、creator、create_time、update_time、order_count、reviewed_count、unreviewed_count、review_assignment_status(unreviewed/partially_reviewed/reviewed)" + "description": "散单模式(list_type=single):订单数组,每项含 order_id、delivery_order_code、order_type、wave_id、wave_no、pick_status、recheck_status、shop_nick、logistics_name、items_count、items_total、wave_index、status、create_at、pick_time、recheck_time。团购模式(list_type=group):波次汇总数组,每项含 wave_id、wave_no、wave_type、wave_status、total_orders、processed_orders、creator、create_time、update_time、order_count、reviewed_count、unreviewed_count、review_assignment_status(unreviewed/partially_reviewed/reviewed)" }, { "name": "pagination", @@ -6729,7 +6729,7 @@ "type": "object", "required": false, "source": "body", - "description": "筛选条件。支持 keyword(运单号/订单号模糊搜索)、wave_no(精确匹配)、recheck_status、pick_status" + "description": "筛选条件。支持 keyword(运单号/订单号模糊搜索)、wave_no(精确匹配)、recheck_status、pick_status、wave_index(波次内序号范围筛选,如 {\"operator\":\"between\",\"value\":[起,止]},或 wave_index_min / wave_index_max)" }, { "name": "pagination", @@ -6744,7 +6744,7 @@ "name": "list", "type": "array", "required": true, - "description": "散单复核订单列表,每项含 order_id、delivery_order_code、order_type、wave_id、wave_no、pick_status、recheck_status、shop_nick、logistics_name、items_count、items_total、items_weight、weight_type、waybill_code、status、create_at、recheck_time" + "description": "散单复核订单列表,每项含 order_id、delivery_order_code、order_type、wave_id、wave_no、pick_status、recheck_status、shop_nick、logistics_name、items_count、items_total、items_weight、weight_type、waybill_code、wave_index、status、create_at、recheck_time" }, { "name": "pagination", @@ -8517,6 +8517,11 @@ "type": "string", "description": "商品快照,格式示例:苹果*2|香蕉*3" }, + { + "name": "wave_index", + "type": "number", + "description": "波次内序号(联查 wms_order_wave_index,无记录时为 0)" + }, { "name": "excluded_reason", "type": "string", @@ -10385,7 +10390,7 @@ "name": "list", "type": "array", "required": true, - "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节)" + "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节);本次新增 wave_index(波次内序号,联查 wms_order_wave_index,无记录时为 0)。" }, { "name": "pagination", @@ -10633,7 +10638,7 @@ "name": "list", "type": "array", "required": true, - "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节),本次新增 store_remark(货主备注)字段。" + "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节),本次新增 store_remark(货主备注)字段;wave_index(波次内序号,联查 wms_order_wave_index,无记录时为 0)。" }, { "name": "pagination", @@ -10818,7 +10823,7 @@ "name": "list", "type": "array", "required": true, - "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节),本次新增 store_remark(货主备注)字段。" + "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节),本次新增 store_remark(货主备注)字段;wave_index(波次内序号,联查 wms_order_wave_index,无记录时为 0)。" }, { "name": "pagination", @@ -10956,7 +10961,7 @@ "name": "list", "type": "array", "required": true, - "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节),本次新增 store_remark(货主备注)字段。" + "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节),本次新增 store_remark(货主备注)字段;wave_index(波次内序号,联查 wms_order_wave_index,无记录时为 0)。" }, { "name": "pagination", @@ -11350,7 +11355,7 @@ "name": "list", "type": "array", "required": true, - "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节),本次新增 store_remark(货主备注)字段。" + "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节),本次新增 store_remark(货主备注)字段;wave_index(波次内序号,联查 wms_order_wave_index,无记录时为 0)。" }, { "name": "pagination", @@ -11494,7 +11499,7 @@ "name": "list", "type": "array", "required": true, - "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节),本次新增 store_remark(货主备注)字段。" + "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节),本次新增 store_remark(货主备注)字段;wave_index(波次内序号,联查 wms_order_wave_index,无记录时为 0)。" }, { "name": "pagination", From d4dc25c8e74d1e3e96e5a78a8ab9114455232cd9 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Fri, 21 Aug 2026 02:20:02 +0800 Subject: [PATCH 237/550] =?UTF-8?q?feat(pick):=20=E6=95=B4=E6=B3=A2?= =?UTF-8?q?=E9=A2=86=E6=96=99=20waveClaimScan=20=E4=B8=8E=E6=8B=A3?= =?UTF-8?q?=E8=B4=A7=E9=A2=86=E6=96=99=E5=89=8D=E7=BD=AE=E6=A0=A1=E9=AA=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 pick.waveClaimScan: 扫面单号定位订单并反查波次, 仅普通波次(source=0)支持整波领料 - 新增 getWavePickModeByWaveId 关联拣货模式查询 - query 命中大团购/非抓取散单波次时校验领料状态, 未领料提示先整波领单 - 波次存在未打印订单时禁止领料, 领料写入 ORDER_WAVE_CLAIM 操作日志 --- app/dict/businessDict.js | 1 + app/service/systemMethods/pick.js | 351 +++++++++++++++++++++++++++++- 2 files changed, 350 insertions(+), 2 deletions(-) diff --git a/app/dict/businessDict.js b/app/dict/businessDict.js index dc73d16..dd3948e 100644 --- a/app/dict/businessDict.js +++ b/app/dict/businessDict.js @@ -76,6 +76,7 @@ module.exports = { ORDER_WAVE_GRAB: '抓取波次', ORDER_WAVE_AUTO_GROUP: '自动加团', ORDER_WAVE_STRATEGY_FETCH: '策略抓取波次', + ORDER_WAVE_CLAIM: '领取波次', ORDER_PICK_COMPLETE: '拣货完成', ORDER_RECHECK: '订单复核', ORDER_RECHECK_BATCH: '批量复核', diff --git a/app/service/systemMethods/pick.js b/app/service/systemMethods/pick.js index 362fc2b..549ce71 100644 --- a/app/service/systemMethods/pick.js +++ b/app/service/systemMethods/pick.js @@ -1,5 +1,6 @@ 'use strict'; +const { Op } = require('sequelize'); const MainService = require('../main'); const { isInterceptedOrderStatus } = require('../../lib/intercept_guard'); @@ -12,9 +13,9 @@ class PickService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'query,wavePickComplete,wavePickTaskDetail,wavePickTaskCurrent,wavePickTaskSubmit,wavePickTaskComplete'; + const _noNeedRight = 'query,wavePickComplete,wavePickTaskDetail,wavePickTaskCurrent,wavePickTaskSubmit,wavePickTaskComplete,waveClaimScan'; const _noNeedLog = 'query'; - const _noNeedAuth = 'query,wavePickComplete,wavePickTaskDetail,wavePickTaskCurrent,wavePickTaskSubmit,wavePickTaskComplete'; + const _noNeedAuth = 'query,wavePickComplete,wavePickTaskDetail,wavePickTaskCurrent,wavePickTaskSubmit,wavePickTaskComplete,waveClaimScan'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -1488,6 +1489,352 @@ class PickService extends MainService { } } + /** + * 查询波次关联的拣货模式。 + * + * 优先按拣货任务主表(wms_wave_pick_task.wave_id)直接关联查询, + * 未命中时回退到任务与波次关联表(wms_wave_pick_task_wave)查询。 + * + * @param {number|string} waveId 波次ID。 + * @return {Promise} 拣货模式:1-团购小波次 2-散单单品单件 3-先拣后分 4-边拣边分 5-团购大波次(0 表示无关联拣货任务)。 + */ + async getWavePickModeByWaveId(waveId) { + const { ctx } = this; + const normalizedWaveId = Number(waveId || 0); + if (!Number.isInteger(normalizedWaveId) || normalizedWaveId <= 0) { + return 0; + } + + const directRows = await ctx.model.query( + `SELECT pick_mode + FROM wms_wave_pick_task + WHERE wave_id = :waveId + ORDER BY id DESC + LIMIT 1`, + { + replacements: { waveId: normalizedWaveId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + const directRow = Array.isArray(directRows) && directRows.length > 0 ? directRows[0] : null; + if (directRow) { + return Number(directRow.pick_mode || 0); + } + + const linkRows = await ctx.model.query( + `SELECT t.pick_mode + FROM wms_wave_pick_task_wave tw + INNER JOIN wms_wave_pick_task t ON t.id = tw.task_id + WHERE tw.wave_id = :waveId + ORDER BY t.id DESC + LIMIT 1`, + { + replacements: { waveId: normalizedWaveId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + const linkRow = Array.isArray(linkRows) && linkRows.length > 0 ? linkRows[0] : null; + return linkRow ? Number(linkRow.pick_mode || 0) : 0; + } + + /** + * 扫描面单号领取整波(领料)。 + * + * 按面单号(运单号,wms_order_express.waybill_code)定位待处理订单表中的订单后反查订单所在波次, + * 仅对普通波次(wms_wave_batch.source=0,含团购/散单)支持整波领料: + * 命中后将该波次下全部未领单订单 claim_status 置为 fin(领单完成), + * 并写入 ORDER_WAVE_CLAIM 订单操作日志,返回波次ID(wave_id)与波次编码(wave_no); + * 策略抓取波次(source=1/2)无需领料,返回 400 并提示「该波次为抓取波次,无需领料」 + * (失败 data 含 no_claim_needed=true、wave_id、wave_no); + * 波次下存在未打印订单(print_status != fin)时禁止领料, + * 返回 400 并提示「波次未打印,禁止领料」(失败 data 含 wave_id、wave_no、unprinted_order_count); + * 其余未知类型返回通用不支持提示。 + * 波次内订单已全部领单时返回 already_claimed 幂等结果并提示已领料。 + * + * @param {Object} data 请求参数。 + * @param {string} data.waybill_no 面单号(运单号,wms_order_express.waybill_code)。 + * @return {Promise} 统一 success/fail 包装结果。 + */ + async waveClaimScan(data = {}) { + const { ctx } = this; + const requestData = this.isPlainObject(data) ? data : {}; + const waybillNo = String(requestData.waybill_no || requestData.waybillNo || '').trim(); + if (!waybillNo) { + return this.fail('waybill_no 必填(面单号/运单号)', {}, 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 stateUser = this.isPlainObject(ctx && ctx.state && ctx.state.user) ? ctx.state.user : null; + const ctxUser = this.isPlainObject(ctx && ctx.user) ? ctx.user : null; + const operatorSource = stateUser || ctxUser || {}; + const rawOperatorId = operatorSource.employees_id ?? operatorSource.operator_id ?? operatorSource.id; + const operatorId = Number(rawOperatorId || 0); + const operatorName = String( + operatorSource.operator_name + || operatorSource.employees_name + || operatorSource.name + || '' + ).trim() || 'system'; + if (!Number.isInteger(operatorId) || operatorId <= 0) { + return this.fail('未获取到操作人上下文', {}, 401); + } + + // --- 1. 面单号定位订单 --- + const orderExpress = await ctx.model.OrderExpress.findOne({ + where: { + warehouse_id: normalizedWarehouseId, + waybill_code: waybillNo, + }, + attributes: [ 'order_id' ], + raw: true, + }); + const matchedOrderId = Number(orderExpress && orderExpress.order_id || 0); + if (!(matchedOrderId > 0)) { + return this.fail('未查询到该面单号对应的订单,无记录', {}, 404); + } + + // --- 2. 待处理订单表定位订单 --- + 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: matchedOrderId, + warehouse_id: normalizedWarehouseId, + }, + attributes: [ 'id', 'wave_id', 'wave_no' ], + raw: true, + }); + if (!order) { + return this.fail('订单不在待处理订单表,无记录', {}, 404); + } + + // --- 3. 订单定位波次 --- + const orderWaveId = Number(order.wave_id || 0); + const orderWaveNo = String(order.wave_no || '').trim(); + if (!(orderWaveId > 0 || orderWaveNo)) { + return this.fail('运单对应订单未分配波次', {}, 400); + } + + let waveRows = []; + if (orderWaveId > 0) { + waveRows = await ctx.model.query( + `SELECT wave_id, wave_no, wave_type, source + FROM wms_wave_batch + WHERE warehouse_id = :warehouseId + AND wave_id = :waveId + LIMIT 1`, + { + replacements: { + warehouseId: normalizedWarehouseId, + waveId: orderWaveId, + }, + type: ctx.model.QueryTypes.SELECT, + } + ); + } else { + waveRows = await ctx.model.query( + `SELECT wave_id, wave_no, wave_type, source + FROM wms_wave_batch + WHERE warehouse_id = :warehouseId + AND wave_no = :waveNo + LIMIT 1`, + { + replacements: { + warehouseId: normalizedWarehouseId, + waveNo: orderWaveNo, + }, + type: ctx.model.QueryTypes.SELECT, + } + ); + } + const waveRow = Array.isArray(waveRows) && waveRows.length > 0 ? waveRows[0] : null; + if (!waveRow) { + return this.fail('运单对应波次不存在或不属于当前仓库', {}, 404); + } + + const targetWaveId = Number(waveRow.wave_id || 0); + const targetWaveNo = String(waveRow.wave_no || '').trim(); + const targetWaveType = Number(waveRow.wave_type || 0); + const targetWaveSource = Number(waveRow.source || 0); + if (!(targetWaveId > 0) || !targetWaveNo) { + return this.fail('目标波次信息不完整', {}, 400); + } + + // --- 4. 波次关联拣货模式与领料资格判定(仅普通波次 source=0 支持整波领料)--- + const pickMode = await this.getWavePickModeByWaveId(targetWaveId); + + const isFetchedWave = targetWaveSource === 1 || targetWaveSource === 2; + if (isFetchedWave) { + return this.fail('该波次为抓取波次,无需领料', { + no_claim_needed: true, + wave_id: targetWaveId, + wave_no: targetWaveNo, + wave_type: targetWaveType, + wave_source: targetWaveSource, + pick_mode: pickMode, + matched_order_id: matchedOrderId, + waybill_no: waybillNo, + }, 400); + } + if (targetWaveSource !== 0) { + return this.fail('当前波次类型不支持整波领单', { + wave_id: targetWaveId, + wave_no: targetWaveNo, + wave_type: targetWaveType, + wave_source: targetWaveSource, + }, 400); + } + + // --- 5. 查询波次下全部订单 --- + const waveOrderRows = await orderModel.findAll({ + where: { + warehouse_id: normalizedWarehouseId, + wave_id: targetWaveId, + }, + attributes: [ 'id', 'claim_status', 'print_status' ], + raw: true, + }); + let waveOrders = Array.isArray(waveOrderRows) ? waveOrderRows : []; + if (waveOrders.length === 0) { + const fallbackRows = await orderModel.findAll({ + where: { + warehouse_id: normalizedWarehouseId, + wave_no: targetWaveNo, + }, + attributes: [ 'id', 'claim_status', 'print_status' ], + raw: true, + }); + waveOrders = Array.isArray(fallbackRows) ? fallbackRows : []; + } + const waveOrderIds = [ ...new Set(waveOrders + .map(item => Number(item && item.id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ]; + if (waveOrderIds.length === 0) { + return this.fail('波次下无可用订单', {}, 400); + } + + const totalOrderCount = waveOrderIds.length; + const unclaimedOrderIds = [ ...new Set(waveOrders + .filter(item => String(item && item.claim_status || '') !== 'fin') + .map(item => Number(item && item.id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ]; + + const baseResponse = { + wave_id: targetWaveId, + wave_no: targetWaveNo, + wave_type: targetWaveType, + wave_source: targetWaveSource, + pick_mode: pickMode, + matched_order_id: matchedOrderId, + waybill_no: waybillNo, + total_order_count: totalOrderCount, + }; + + if (unclaimedOrderIds.length === 0) { + return this.success('ok', { + data: { + ...baseResponse, + claimed_order_count: 0, + status: 'already_claimed', + tip: '该波次已领料,无需重复领取', + }, + code: 200, + }); + } + + // 波次打印校验:存在未打印订单(print_status != fin)时禁止整波领料 + const unprintedOrderIds = [ ...new Set(waveOrders + .filter(item => String(item && item.print_status || '') !== 'fin') + .map(item => Number(item && item.id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ]; + if (unprintedOrderIds.length > 0) { + return this.fail('波次未打印,禁止领料', { + ...baseResponse, + unprinted_order_count: unprintedOrderIds.length, + }, 400); + } + + // --- 6. 事务更新领单状态并写订单日志 --- + const operationLogService = ctx.service + && ctx.service.systems + && ctx.service.systems.operationLog; + const transaction = await ctx.model.transaction(); + try { + await orderModel.update( + { claim_status: 'fin' }, + { + where: { + id: { [Op.in]: unclaimedOrderIds }, + warehouse_id: normalizedWarehouseId, + claim_status: { [Op.ne]: 'fin' }, + }, + transaction, + } + ); + + const claimedRows = await orderModel.findAll({ + where: { + id: { [Op.in]: unclaimedOrderIds }, + warehouse_id: normalizedWarehouseId, + claim_status: 'fin', + }, + attributes: [ 'id' ], + raw: true, + transaction, + }); + const claimedOrderIds = [ ...new Set((Array.isArray(claimedRows) ? claimedRows : []) + .map(item => Number(item && item.id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ]; + + if (claimedOrderIds.length > 0 + && operationLogService + && typeof operationLogService.createOperationLogs === 'function') { + await operationLogService.createOperationLogs(claimedOrderIds.map(orderId => ({ + businessType: 'order', + businessId: `${orderId}`, + operationCode: 'ORDER_WAVE_CLAIM', + operator: { + id: operatorId ? String(operatorId) : null, + name: operatorName || 'system', + }, + operationAction: 'UPDATE', + extras: { + message: `整波领单完成(波次 ${targetWaveNo})`, + warehouseId: normalizedWarehouseId, + externalLogType: 'API', + }, + })), { transaction }); + } + + await transaction.commit(); + + return this.success('ok', { + data: { + ...baseResponse, + claimed_order_count: claimedOrderIds.length, + status: 'claimed', + tip: `整波领单完成,本次领取 ${claimedOrderIds.length} 个订单`, + }, + code: 200, + }); + } catch (error) { + await transaction.rollback(); + ctx.logger.error('[PickService.waveClaimScan] 整波领单失败: %s', error && error.message ? error.message : error); + return this.fail('领单失败', {}, 500); + } + } + } module.exports = PickService; From 232985a272281a1242b454e7e64f056dc8b5b673 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Fri, 21 Aug 2026 02:20:07 +0800 Subject: [PATCH 238/550] =?UTF-8?q?feat(wave):=20=E7=AD=96=E7=95=A5?= =?UTF-8?q?=E5=91=BD=E4=B8=AD=E6=95=B0=E6=8C=89=E5=90=8C=E5=BF=AB=E9=80=92?= =?UTF-8?q?=E6=8B=86=E5=88=86=E7=BB=9F=E8=AE=A1=E4=B8=8E=E9=80=80=E5=9B=9E?= =?UTF-8?q?=E5=8E=9F=E5=9B=A0=E4=B8=AD=E6=96=87=E6=A0=87=E7=AD=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - getWaveStrategyMatchedOrderCountFilteredMap 改收策略行并按 require_same_express 拆分计数, 同快递策略按 items_hash+快递分组, 与抓取候选 SQL 口径一致, max_same_structure<=0 视为不设上限 - waveStrategyFallbackOrderList excluded_reason 改中文标签, 兼容 lock_status 归一化 Y/N 与原始值 --- app/service/systemMethods/order/wave.js | 136 ++++++++++-------- .../order/wave.waveStrategyQuickScan.test.js | 4 +- 2 files changed, 80 insertions(+), 60 deletions(-) diff --git a/app/service/systemMethods/order/wave.js b/app/service/systemMethods/order/wave.js index 4e87f47..72982ac 100644 --- a/app/service/systemMethods/order/wave.js +++ b/app/service/systemMethods/order/wave.js @@ -47,6 +47,12 @@ const WAVE_STRATEGY_FALLBACK_WHERE_FIELD_MAP = Object.freeze({ province: 'province', sys_platform_name: 'sys_platform_name', }); +const WAVE_STRATEGY_FALLBACK_EXCLUDED_REASON_LABELS = Object.freeze({ + locked: '已锁定', + intercepted: '已拦截', + printed: '已打印', + no_match: '未匹配策略', +}); const BATCH_LIST_ASSIGNMENT_FILTER_SCHEMAS = Object.freeze({ storage: Object.freeze({ fieldName: 'storage_assignment_status', @@ -104,7 +110,7 @@ class WaveService extends OrderBaseService { super(ctx); const _noNeedLogin = ''; const _noNeedRight = 'wavePickTaskCancelSelf,groupOrderFetchList,singleOrderFetchList,waveStrategyList,waveStrategyFallbackOrderList,waveStrategyFetchPda,waveStrategyFetchAdmin,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,wavePickTaskList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds,waveStrategyQuickScan,waveStrategyQuickScanTaskProgress'; - const _noNeedLog = 'groupOrderFetchList,singleOrderFetchList,waveStrategyList,waveStrategyFallbackOrderList,waveStrategyFetchPda,waveStrategyFetchAdmin,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,wavePickTaskList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds,waveStrategyQuickScan,waveStrategyQuickScanTaskProgress'; + const _noNeedLog = 'groupOrderFetchList,singleOrderFetchList,waveStrategyList,waveStrategyFallbackOrderList,waveStrategyFetchAdmin,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,wavePickTaskList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds,waveStrategyQuickScan,waveStrategyQuickScanTaskProgress'; const _noNeedAuth = 'groupOrderFetchList,singleOrderFetchList,waveStrategyList,waveStrategyFallbackOrderList,waveStrategyFetchPda,waveStrategyFetchAdmin,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,wavePickTaskList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds,waveStrategyQuickScan,waveStrategyQuickScanTaskProgress'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -2675,12 +2681,9 @@ class WaveService extends OrderBaseService { }); const list = Array.isArray(queryResult && queryResult.rows) ? queryResult.rows : []; - const strategyIds = [ ...new Set(list - .map(item => Number(item && item.id || 0)) - .filter(item => Number.isInteger(item) && item > 0)) ]; const matchedOrderCountMap = await this.getWaveStrategyMatchedOrderCountFilteredMap( contextWarehouseId, - strategyIds + list ); const nextFetchOrderCountMap = calculateNextFetchOrderCount ? await this.getWaveStrategyNextFetchOrderCountMap(contextWarehouseId, list) @@ -2996,34 +2999,55 @@ class WaveService extends OrderBaseService { /** * 按策略统计过滤后命中订单数。 * - * 过滤口径: + * 过滤口径与抓取候选 SQL(getWaveStrategyFetchCandidateOrders)保持一致: * 1) 仅统计未在波次订单(wave_id = 0); * 2) 仅统计 step != 0 的订单; - * 3) 仅统计状态有效订单(status != cancel 且 outbound_status != padding); - * 4) 同结构数量需落在策略 min_same_structure/max_same_structure 区间内。 - * - * 同结构定义沿用快速扫描口径:优先 items_hash,空时回退 items。 + * 3) 仅统计状态有效订单(status != cancel 且 outbound_status != padding); + * 4) 同结构数量需落在策略 min_same_structure/max_same_structure 区间内; + * 当 require_same_express = 1 时按「结构(items_hash) + 快递」分组计数, + * 否则仅按结构(items_hash)分组计数。 * * @param {number|string} warehouseId 仓库ID。 - * @param {Array} strategyIds 当前页策略ID列表。 + * @param {Array} strategyRows 当前页策略行数组(含 require_same_express)。 * @return {Promise>} strategy_id 到过滤后命中订单数的映射。 */ - async getWaveStrategyMatchedOrderCountFilteredMap(warehouseId, strategyIds = []) { + async getWaveStrategyMatchedOrderCountFilteredMap(warehouseId, strategyRows = []) { const normalizedWarehouseId = Number(warehouseId || 0); if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { throw new Error('未识别到当前仓库上下文'); } - const normalizedStrategyIds = [ ...new Set((Array.isArray(strategyIds) ? strategyIds : []) - .map(item => Number(item)) - .filter(item => Number.isInteger(item) && item > 0)) ]; - if (normalizedStrategyIds.length === 0) { + const normalizedStrategies = [ ...new Map((Array.isArray(strategyRows) ? strategyRows : []) + .map(item => { + const strategyId = Number(item && (item.id ?? item.strategy_id) || 0); + if (!Number.isInteger(strategyId) || strategyId <= 0) { + return null; + } + + return [ strategyId, { + id: strategyId, + requireSameExpress: Number(item && item.require_same_express || 0) === 1, + }]; + }) + .filter(Boolean)).values() ]; + if (normalizedStrategies.length === 0) { return new Map(); } const orderModel = await this.getOrderModel('pendingOrder', normalizedWarehouseId); const orderTableName = this.getModelTableSqlName(orderModel); - const querySql = ` + const expressExpr = alias => `COALESCE(NULLIF(TRIM(COALESCE(${alias}.sys_logistics_code, '')), ''), NULLIF(TRIM(COALESCE(${alias}.logistics_code, '')), ''), TRIM(COALESCE(${alias}.logistics_name, '')))`; + + const matchedMap = new Map(); + const runCountQuery = async (strategyGroup, requireSameExpress) => { + const strategyIds = strategyGroup.map(item => item.id); + if (strategyIds.length === 0) { + return; + } + + const groupKeyExtra = requireSameExpress ? `, ${expressExpr('src')} AS express_key` : ''; + const joinKeyExtra = requireSameExpress ? ` AND same_structure.express_key = ${expressExpr('o')}` : ''; + const querySql = ` SELECT m.strategy_id, COUNT(DISTINCT m.order_id) AS matched_order_count_filtered @@ -3042,7 +3066,7 @@ class WaveService extends OrderBaseService { AND o.lock_status = 'none' INNER JOIN ( SELECT - src.items_hash AS structure_key, + src.items_hash AS structure_key${groupKeyExtra}, COUNT(1) AS same_structure_count FROM ${orderTableName} src WHERE src.warehouse_id = :warehouseId @@ -3055,37 +3079,42 @@ class WaveService extends OrderBaseService { AND src.outbound_status != 'padding' AND src.intercept_status = 'none' AND src.lock_status = 'none' - GROUP BY src.items_hash + GROUP BY src.items_hash${requireSameExpress ? `, ${expressExpr('src')}` : ''} ) same_structure - ON same_structure.structure_key = o.items_hash + ON same_structure.structure_key = o.items_hash${joinKeyExtra} INNER JOIN wms_wave_strategy s ON s.id = m.strategy_id AND s.warehouse_id = :warehouseId WHERE m.warehouse_id = :warehouseId AND m.strategy_id IN (:strategyIds) - AND same_structure.same_structure_count >= COALESCE(s.min_same_structure, 0) - AND (s.max_same_structure IS NULL OR same_structure.same_structure_count <= s.max_same_structure) + AND same_structure.same_structure_count >= COALESCE(NULLIF(s.min_same_structure, 0), 0) + AND (s.max_same_structure IS NULL OR s.max_same_structure <= 0 OR same_structure.same_structure_count <= s.max_same_structure) GROUP BY m.strategy_id `; - const queryRows = await this.ctx.model.query(querySql, { - replacements: { - warehouseId: normalizedWarehouseId, - strategyIds: normalizedStrategyIds, - }, - type: this.ctx.model.QueryTypes.SELECT, - }); + const queryRows = await this.ctx.model.query(querySql, { + replacements: { + warehouseId: normalizedWarehouseId, + strategyIds, + }, + type: this.ctx.model.QueryTypes.SELECT, + }); - const matchedMap = new Map(); - (Array.isArray(queryRows) ? queryRows : []).forEach(row => { - const strategyId = Number(row && row.strategy_id || 0); - const matchedCount = Number(row && row.matched_order_count_filtered || 0); - if (!Number.isInteger(strategyId) || strategyId <= 0) { - return; - } + (Array.isArray(queryRows) ? queryRows : []).forEach(row => { + const strategyId = Number(row && row.strategy_id || 0); + const matchedCount = Number(row && row.matched_order_count_filtered || 0); + if (!Number.isInteger(strategyId) || strategyId <= 0) { + return; + } - matchedMap.set(strategyId, matchedCount); - }); + matchedMap.set(strategyId, matchedCount); + }); + }; + + await Promise.all([ + runCountQuery(normalizedStrategies.filter(item => item.requireSameExpress), true), + runCountQuery(normalizedStrategies.filter(item => !item.requireSameExpress), false), + ]); return matchedMap; } @@ -3978,6 +4007,12 @@ class WaveService extends OrderBaseService { buildWaveStrategyFallbackOrderListItem(orderRow = {}, itemSnapshot = '') { const normalizedOrderRow = this.isPlainObject(orderRow) ? orderRow : {}; + // normalizeOrderListItem 已将 lock_status 归一化为 Y/N(none→N,其余→Y), + // 这里兼容归一化值(Y/N)与原始值(none/warehouse/store),避免把 N 误判为已锁定。 + const lockStatus = String(normalizedOrderRow.lock_status || '').trim(); + const isLocked = lockStatus === 'Y' + || (lockStatus !== '' && lockStatus !== 'N' && lockStatus !== 'none'); + return { id: normalizedOrderRow.id ?? null, delivery_no: normalizedOrderRow.delivery_no ?? normalizedOrderRow.delivery_order_code ?? null, @@ -3992,13 +4027,13 @@ class WaveService extends OrderBaseService { sys_platform_name: normalizedOrderRow.sys_platform_name ?? null, item_snapshot: String(itemSnapshot || ''), wave_index: Number(normalizedOrderRow.wave_index || 0), - excluded_reason: normalizedOrderRow.lock_status !== 'none' - ? 'locked' + excluded_reason: isLocked + ? WAVE_STRATEGY_FALLBACK_EXCLUDED_REASON_LABELS.locked : normalizedOrderRow.intercept_status !== 'none' - ? 'intercepted' + ? WAVE_STRATEGY_FALLBACK_EXCLUDED_REASON_LABELS.intercepted : normalizedOrderRow.print_status === 'fin' - ? 'printed' - : 'no_match', + ? WAVE_STRATEGY_FALLBACK_EXCLUDED_REASON_LABELS.printed + : WAVE_STRATEGY_FALLBACK_EXCLUDED_REASON_LABELS.no_match, }; } @@ -6548,9 +6583,6 @@ class WaveService extends OrderBaseService { const normalizedOrder = this.isPlainObject(order) ? order : {}; const normalizedStrategy = this.isPlainObject(strategy) ? strategy : {}; const structureStoreSetMap = context && context.structureStoreSetMap instanceof Map ? context.structureStoreSetMap : new Map(); - const structurePrimaryExpressMap = context && context.structurePrimaryExpressMap instanceof Map - ? context.structurePrimaryExpressMap - : null; const structurePrimaryOwnerMap = context && context.structurePrimaryOwnerMap instanceof Map ? context.structurePrimaryOwnerMap : null; @@ -6576,18 +6608,6 @@ class WaveService extends OrderBaseService { } } - if (normalizedStrategy.require_same_express === true && structurePrimaryExpressMap instanceof Map) { - const primaryExpressKey = String(structurePrimaryExpressMap.get(structureKey) || '').trim().toLowerCase(); - if (!primaryExpressKey) { - return false; - } - - const currentExpressKey = String(this.getWaveStrategyQuickScanExpressKey(normalizedOrder) || '').trim().toLowerCase(); - if (currentExpressKey !== primaryExpressKey) { - return false; - } - } - const itemsCount = Number(normalizedOrder.items_count || 0); const itemsTotal = Number(normalizedOrder.items_total || 0); diff --git a/test/app/service/systemMethods/order/wave.waveStrategyQuickScan.test.js b/test/app/service/systemMethods/order/wave.waveStrategyQuickScan.test.js index d616c8c..ad2bc56 100644 --- a/test/app/service/systemMethods/order/wave.waveStrategyQuickScan.test.js +++ b/test/app/service/systemMethods/order/wave.waveStrategyQuickScan.test.js @@ -314,7 +314,7 @@ describe('test/app/service/systemMethods/order/wave.waveStrategyQuickScan.test.j assert.deepEqual(result.matchedOrderIds, [ 101, 102 ]); }); - it('require_same_express=true 时应按同结构主快递优先命中', async () => { + it('require_same_express=true 时扫描阶段不再按主快递排除订单', async () => { const { service } = createHarness(); const orders = [ @@ -389,6 +389,6 @@ describe('test/app/service/systemMethods/order/wave.waveStrategyQuickScan.test.j ), }); - assert.deepEqual(result.matchedOrderIds, [ 201, 202 ]); + assert.deepEqual(result.matchedOrderIds, [ 201, 202, 203 ]); }); }); From 60b4babb341e2102ab1eb693ba01419a5e5084d4 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Fri, 21 Aug 2026 02:20:13 +0800 Subject: [PATCH 239/550] =?UTF-8?q?feat(order):=20=E8=AE=A2=E5=8D=95?= =?UTF-8?q?=E5=88=97=E8=A1=A8=E4=B8=8E=E5=AF=BC=E5=87=BA=E6=94=AF=E6=8C=81?= =?UTF-8?q?=E6=B3=A2=E6=AC=A1=E8=8C=83=E5=9B=B4=20wave=5Fscope=20=E7=AD=9B?= =?UTF-8?q?=E9=80=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - extractWaveScopeVirtualFilter 解析 wave_scope(0=未分配波次/1=团购/2=散单) - buildWaveScopeWhereCondition 经 wms_wave_batch 反查波次ID注入条件 - list 与 order_export 均接入该虚拟筛选 --- app/service/systemMethods/order/base.js | 132 +++++++++++++++++++++++- app/service/systems/order_export.js | 8 +- 2 files changed, 138 insertions(+), 2 deletions(-) diff --git a/app/service/systemMethods/order/base.js b/app/service/systemMethods/order/base.js index 076dbce..81c121d 100644 --- a/app/service/systemMethods/order/base.js +++ b/app/service/systemMethods/order/base.js @@ -1127,6 +1127,52 @@ class OrderBaseService extends MainService { return { where: normalizedWhere, waveIndexCondition: normalizedCondition }; } + /** + * 提取 wave_scope(波次范围)虚拟筛选条件。 + * 将其从 where 中移除并解析为波次范围值集合,后续通过 wms_wave_batch 反查波次ID注入条件。 + * 取值约定:0=未分配波次,1=团购,2=散单;value 支持单个值或数组(多选)。 + * @param {Object} whereInput 标准化后的 where 条件。 + * @return {{ where: Object, waveScope: number[]|null }} 清洗后的 where 与波次范围值集合。 + */ + extractWaveScopeVirtualFilter(whereInput = {}) { + const normalizedWhere = this.isPlainObject(whereInput) + ? { ...whereInput } + : {}; + const waveScopeCondition = normalizedWhere.wave_scope ?? normalizedWhere.waveScope; + + delete normalizedWhere.wave_scope; + delete normalizedWhere.waveScope; + + // 条件为空时忽略 + if (waveScopeCondition === undefined || waveScopeCondition === null || waveScopeCondition === '') { + return { where: normalizedWhere, waveScope: null }; + } + + const sourceValue = this.isPlainObject(waveScopeCondition) + && Object.prototype.hasOwnProperty.call(waveScopeCondition, 'value') + ? waveScopeCondition.value + : waveScopeCondition; + + // 兼容简写:wave_scope 直接传数值或数组时按 eq/in 处理 + const sourceItems = Array.isArray(sourceValue) ? sourceValue : [ sourceValue ]; + const normalizedScopes = Array.from(new Set( + sourceItems + .filter(item => item !== undefined && item !== null && item !== '') + .map(item => Number(item)) + )); + + for (const scope of normalizedScopes) { + if (!Number.isInteger(scope) || scope < 0 || scope > 2) { + throw new Error('wave_scope 参数不合法,仅支持 0(未分配波次)/1(团购)/2(散单)'); + } + } + + return { + where: normalizedWhere, + waveScope: normalizedScopes.length > 0 ? normalizedScopes : null, + }; + } + /** * 根据 wave_index 筛选条件查询 wms_order_wave_index 命中的订单ID。 * @param {Object} waveIndexCondition 序号筛选条件(含 operator/value)。 @@ -1192,6 +1238,84 @@ class OrderBaseService extends MainService { .filter(orderId => Number.isFinite(orderId) && orderId > 0))); } + /** + * 根据波次范围(wave_scope)构建订单表 wave_id 过滤条件。 + * 0(未分配波次)直接生成 wave_id = 0;1(团购)/2(散单)先查 wms_wave_batch + * 得到对应 wave_type 的波次ID集合,再生成 wave_id in (...)。 + * @param {Array} waveScopes 波次范围值集合(0/1/2)。 + * @param {number|string} [warehouseId] 仓库ID。 + * @return {Promise} Sequelize 条件,无有效范围时返回 null。 + */ + async buildWaveScopeWhereCondition(waveScopes = [], warehouseId = this.getWarehouseId()) { + const contextWarehouseId = this.getWarehouseId(); + + if (contextWarehouseId === null || contextWarehouseId === undefined || contextWarehouseId === '') { + throw new Error('缺少当前用户仓库上下文 store_id'); + } + + if (warehouseId !== null && warehouseId !== undefined && warehouseId !== '' + && String(warehouseId) !== String(contextWarehouseId)) { + throw new Error('订单工作台仓库ID必须来自当前用户上下文 store_id,禁止传入外部仓库ID。'); + } + + const normalizedScopes = Array.from(new Set( + (Array.isArray(waveScopes) ? waveScopes : [ waveScopes ]) + .filter(scope => scope !== undefined && scope !== null && scope !== '') + .map(scope => Number(scope)) + )).filter(scope => Number.isInteger(scope) && scope >= 0 && scope <= 2); + + if (normalizedScopes.length === 0) { + return null; + } + + const { Op } = this.app.Sequelize; + const waveTypeScopes = normalizedScopes.filter(scope => scope === 1 || scope === 2); + const conditions = []; + + if (normalizedScopes.includes(0)) { + conditions.push({ wave_id: 0 }); + } + + if (waveTypeScopes.length > 0) { + const waveBatchModel = this.ctx.model && this.ctx.model.WaveBatch; + const waveIds = []; + if (waveBatchModel && typeof waveBatchModel.findAll === 'function') { + const waveRows = await waveBatchModel.findAll({ + attributes: [ 'wave_id' ], + where: { + warehouse_id: contextWarehouseId, + wave_type: { + [Op.in]: waveTypeScopes, + }, + }, + raw: true, + }); + + for (const row of Array.isArray(waveRows) ? waveRows : []) { + const waveId = Number(row && row.wave_id || 0); + if (waveId > 0) { + waveIds.push(waveId); + } + } + } + + // 空集合时 Op.in: [] 生成恒假条件,保证团购/散单无波次时结果为空 + conditions.push({ + wave_id: { + [Op.in]: Array.from(new Set(waveIds)), + }, + }); + } + + if (conditions.length === 1) { + return conditions[0]; + } + + return { + [Op.or]: conditions, + }; + } + /** * 构建 buyer_message_has 虚拟字段的 Sequelize where 条件。 * 覆盖三个留言/备注字段:buyer_message、seller_message、remark。 @@ -1594,7 +1718,8 @@ class OrderBaseService extends MainService { const { where: whereAfterBuyerMessage, buyerMessageHas } = this.extractBuyerMessageHasVirtualFilter(sanitizedWhere); const { where: whereAfterStockQuery, stockQuery } = this.extractStockQueryVirtualFilter(whereAfterBuyerMessage); const { where: whereAfterWaveIndex, waveIndexCondition } = this.extractWaveIndexVirtualFilter(whereAfterStockQuery); - const mergedWhere = this.mergeWhereObjects(this.getDefaultWhere(moduleName), whereAfterWaveIndex); + const { where: whereAfterWaveScope, waveScope } = this.extractWaveScopeVirtualFilter(whereAfterWaveIndex); + const mergedWhere = this.mergeWhereObjects(this.getDefaultWhere(moduleName), whereAfterWaveScope); let queryWhere = this.buildWhere(mergedWhere, contextWarehouseId, { specialFieldMap: { quickWhere: { @@ -1623,6 +1748,11 @@ class OrderBaseService extends MainService { queryWhere = this.appendOrderIdsFilterToWhere(queryWhere, waveIndexOrderIds); } + if (waveScope) { + const waveScopeCondition = await this.buildWaveScopeWhereCondition(waveScope, contextWarehouseId); + queryWhere = this.appendConditionToWhere(queryWhere, waveScopeCondition); + } + const model = await this.getOrderModel(moduleName, contextWarehouseId); const order = this.buildListOrder(requestData.sort, moduleName); const offset = (page - 1) * pageSize; diff --git a/app/service/systems/order_export.js b/app/service/systems/order_export.js index 6055795..a61626c 100644 --- a/app/service/systems/order_export.js +++ b/app/service/systems/order_export.js @@ -620,9 +620,10 @@ class OrderExportService extends OrderBaseService { const { where: sanitizedWhere, expressNumbers } = this.extractOrderListExpressVirtualFilter(where); const { where: whereAfterBuyerMessage, buyerMessageHas } = this.extractBuyerMessageHasVirtualFilter(sanitizedWhere); const { where: whereAfterWaveIndex, waveIndexCondition } = this.extractWaveIndexVirtualFilter(whereAfterBuyerMessage); + const { where: whereAfterWaveScope, waveScope } = this.extractWaveScopeVirtualFilter(whereAfterWaveIndex); const mergedWhere = this.mergeWhereObjects( target.defaultWhereModuleName ? this.getDefaultWhere(target.defaultWhereModuleName) : {}, - whereAfterWaveIndex + whereAfterWaveScope ); let queryWhere = this.buildWhere(mergedWhere, warehouseId, { specialFieldMap: { @@ -647,6 +648,11 @@ class OrderExportService extends OrderBaseService { queryWhere = this.appendOrderIdsFilterToWhere(queryWhere, waveIndexOrderIds); } + if (waveScope) { + const waveScopeCondition = await this.buildWaveScopeWhereCondition(waveScope, warehouseId); + queryWhere = this.appendConditionToWhere(queryWhere, waveScopeCondition); + } + const orderModel = await this.getOrderModelByTableType(target.tableType, warehouseId); const pageSize = this.getExportPageSize(); const order = this.buildListOrder(requestData.sort, target.sortModuleName); From 90d5701a53b95cfa6c06e760ed0c35ddc7f65126 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Fri, 21 Aug 2026 02:20:17 +0800 Subject: [PATCH 240/550] =?UTF-8?q?feat(wave):=20item=5Fdetail=5Fmachine?= =?UTF-8?q?=20=E6=94=B9=20TEXT=20=E5=B9=B6=E6=96=B0=E5=A2=9E=E6=B3=A2?= =?UTF-8?q?=E6=AC=A1=E8=87=AA=E5=8A=A8=E7=BB=88=E7=BB=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - wms_wave_batch.item_detail_machine VARCHAR(1024) -> TEXT, 兼容多商品长结构标识 - 新增 wave_batch_closure 服务: 扫描活动波次(0/1)中订单已全部离开待处理表的波次并收敛 wave_status=5 - 新增 sync_finished_wave_batch 定时任务与执行日志缓存 --- app/model/wave_batch.js | 8 +- app/schedule/sync_finished_wave_batch.js | 118 ++++++++++++ app/service/systems/wave_batch_closure.js | 173 ++++++++++++++++++ ...-wave-batch-item-detail-machine-to-text.js | 120 ++++++++++++ 4 files changed, 415 insertions(+), 4 deletions(-) create mode 100644 app/schedule/sync_finished_wave_batch.js create mode 100644 app/service/systems/wave_batch_closure.js create mode 100644 database/migrations/20260820120000-alter-wms-wave-batch-item-detail-machine-to-text.js diff --git a/app/model/wave_batch.js b/app/model/wave_batch.js index af3f43a..2bf5192 100644 --- a/app/model/wave_batch.js +++ b/app/model/wave_batch.js @@ -2,7 +2,7 @@ 'use strict'; module.exports = app => { - const { BIGINT, INTEGER, STRING, DATE, TINYINT, BOOLEAN } = app.Sequelize; + const { BIGINT, INTEGER, STRING, TEXT, DATE, TINYINT, BOOLEAN } = app.Sequelize; const WaveBatch = app.model.define('wms_wave_batch', { wave_id: { @@ -115,9 +115,9 @@ module.exports = app => { comment: '更新时间', }, item_detail_machine: { - type: STRING(1024), + type: TEXT, allowNull: true, - comment: '抓取结构token:v1|item_part_type|item_part|distinguish_express|logistics_name|item_snapshot_key', + comment: '抓取结构token:v1|item_part_type|item_part|distinguish_express|logistics_name|item_snapshot_key(TEXT 以容纳多商品订单的长结构标识)', }, item_part_type: { type: STRING(32), @@ -143,7 +143,7 @@ module.exports = app => { item_snapshot_key: { type: STRING(1024), allowNull: true, - comment: '结构快照键(与 item_detail_machine 一致,1024 长度以容纳多商品订单的快照)', + comment: '结构快照键(多商品订单的快照键,最长 1024)', }, }, { tableName: 'wms_wave_batch', diff --git a/app/schedule/sync_finished_wave_batch.js b/app/schedule/sync_finished_wave_batch.js new file mode 100644 index 0000000..ea60a3e --- /dev/null +++ b/app/schedule/sync_finished_wave_batch.js @@ -0,0 +1,118 @@ +// app/schedule/sync_finished_wave_batch.js +'use strict'; + +const EXECUTION_LOG_CACHE_KEY = 'schedule:sync_finished_wave_batch:last_execution'; +const EXECUTION_LOG_CACHE_TTL = 300; // 5 分钟 +const EXECUTION_LOG_HISTORY_CACHE_KEY = 'schedule:sync_finished_wave_batch:history'; +const EXECUTION_LOG_HISTORY_MAX = 20; // 保留最近 20 次执行记录 +const EXECUTION_LOG_HISTORY_TTL = 86400; // 1 天 + +/** + * 将本次执行日志写入缓存。 + * + * @param {Object} ctx Egg 上下文。 + * @param {Object} logEntry 日志条目。 + * @return {Promise} + */ +async function writeExecutionLogToCache(ctx, logEntry) { + try { + if (ctx.app && typeof ctx.app.setCacheAsync === 'function') { + await ctx.app.setCacheAsync(EXECUTION_LOG_CACHE_KEY, logEntry, EXECUTION_LOG_CACHE_TTL); + } + } catch (err) { + ctx.logger.warn(`[sync-finished-wave-batch] 写入执行日志缓存失败: ${err.message}`); + } +} + +/** + * 将本次执行日志追加到历史记录缓存(保留最近 N 次)。 + * + * @param {Object} ctx Egg 上下文。 + * @param {Object} logEntry 日志条目。 + * @return {Promise} + */ +async function appendExecutionHistory(ctx, logEntry) { + try { + if (typeof ctx.app.getCacheAsync !== 'function' || typeof ctx.app.setCacheAsync !== 'function') { + return; + } + + const rawHistory = await ctx.app.getCacheAsync(EXECUTION_LOG_HISTORY_CACHE_KEY); + const history = Array.isArray(rawHistory) ? rawHistory : []; + history.unshift(logEntry); + await ctx.app.setCacheAsync( + EXECUTION_LOG_HISTORY_CACHE_KEY, + history.slice(0, EXECUTION_LOG_HISTORY_MAX), + EXECUTION_LOG_HISTORY_TTL + ); + } catch (err) { + ctx.logger.warn(`[sync-finished-wave-batch] 写入执行历史缓存失败: ${err.message}`); + } +} + +/** + * 每 1 分钟在单 worker 中执行一次波次自动终结。 + * + * 将"订单已全部离开待处理表"的活动波次(wave_status IN (0,1))收敛为 + * wave_status=5(复核完成),修复遗留 0 单波次在 batchList 中展示的问题。 + */ +module.exports = { + schedule: { + interval: '1m', + type: 'worker', + immediate: false, + disable: false, + }, + + /** + * 执行波次自动终结任务。 + * + * @param {Object} ctx Egg 上下文。 + * @return {Promise} 无返回值。 + */ + async task(ctx) { + if (ctx.app._syncFinishedWaveBatchRunning) { + return; + } + + ctx.app._syncFinishedWaveBatchRunning = true; + + const startedAt = Date.now(); + let status = 'success'; + let errorMessage = ''; + let result = null; + + try { + result = await ctx.service.systems.waveBatchClosure.closeFinishedWaves(); + + if (result && result.closed_count > 0) { + ctx.logger.info( + `[sync-finished-wave-batch] 自动终结 ${result.closed_count} 个波次: ${JSON.stringify(result.closed_waves)}` + ); + } + } catch (error) { + status = 'error'; + errorMessage = error.message; + ctx.logger.error(`[sync-finished-wave-batch] 执行失败: ${error.message}`); + } finally { + ctx.app._syncFinishedWaveBatchRunning = false; + } + + const logEntry = { + executed_at: new Date().toISOString(), + duration_ms: Date.now() - startedAt, + status, + error_message: errorMessage, + candidate_count: result ? result.candidate_count : 0, + closed_count: result ? result.closed_count : 0, + warehouse_ids: result ? result.warehouse_ids : [], + closed_waves: result ? result.closed_waves : [], + }; + await writeExecutionLogToCache(ctx, logEntry); + await appendExecutionHistory(ctx, logEntry); + + ctx.logger.info( + `[sync-finished-wave-batch] 本轮完成 closed=${result ? result.closed_count : 0} candidate=${result ? result.candidate_count : 0} warehouses=${result ? result.warehouse_ids.length : 0}` + ); + }, +}; diff --git a/app/service/systems/wave_batch_closure.js b/app/service/systems/wave_batch_closure.js new file mode 100644 index 0000000..8d43a74 --- /dev/null +++ b/app/service/systems/wave_batch_closure.js @@ -0,0 +1,173 @@ +// app/service/systems/wave_batch_closure.js +'use strict'; + +const MainService = require('../main'); + +// 活动中的波次状态(batchList 可见口径) +const ACTIVE_WAVE_STATUSES = [ 0, 1 ]; +// 终结态:复核完成(与 recheckOrder 复核完成路径一致,使波次从 batchList 中自然消失) +const CLOSED_WAVE_STATUS = 5; +// 创建不足该分钟数的波次不参与自动终结,避免与创建事务并发误判 +const WAVE_MIN_AGE_MINUTES = 5; +// 单次 SQL IN 列表的波次数量上限 +const WAVE_ID_BATCH_SIZE = 500; + +/** + * 波次批次自动终结服务。 + * + * 背景:波次内订单全部离开待处理表后(发货迁移配送表、库内拦截确认、取消等), + * 若相关路径未回写 wms_wave_batch,波次会停留在 wave_status IN (0,1), + * 导致 order.wave.batchList 展示 0 单波次。 + * + * 本服务按仓库扫描活动波次,对"待处理表中已无任何订单"的波次, + * 将 wave_status 收敛为 5(复核完成),使其从批次列表中消失。 + */ +class WaveBatchClosureService extends MainService { + /** + * 扫描并关闭"订单已全部离表"的活动波次。 + * + * @param {Object} [options={}] 执行选项。 + * @param {boolean} [options.dryRun=false] 仅盘点不更新(用于验证命中范围)。 + * @return {Promise} 执行结果汇总。 + */ + async closeFinishedWaves(options = {}) { + const { ctx } = this; + const startedAt = Date.now(); + const dryRun = Boolean(options && options.dryRun); + + const candidateRows = await ctx.model.query( + `SELECT wave_id, wave_no, warehouse_id, wave_status, total_orders + FROM wms_wave_batch + WHERE wave_status IN (:waveStatuses) + AND total_orders > 0 + AND create_time < (NOW() - INTERVAL ${WAVE_MIN_AGE_MINUTES} MINUTE)`, + { + replacements: { waveStatuses: ACTIVE_WAVE_STATUSES }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + // 按仓库分组,过滤非法数据 + const warehouseWaveMap = new Map(); + for (const row of (Array.isArray(candidateRows) ? candidateRows : [])) { + const warehouseId = Number(row && row.warehouse_id || 0); + const waveId = Number(row && row.wave_id || 0); + if (!Number.isInteger(warehouseId) || warehouseId <= 0 + || !Number.isInteger(waveId) || waveId <= 0) { + continue; + } + + if (!warehouseWaveMap.has(warehouseId)) { + warehouseWaveMap.set(warehouseId, []); + } + warehouseWaveMap.get(warehouseId).push({ + waveId, + waveNo: String(row && row.wave_no || '').trim(), + warehouseId, + }); + } + + const warehouseIds = Array.from(warehouseWaveMap.keys()); + const closedWaves = []; + + for (const warehouseId of warehouseIds) { + const waves = warehouseWaveMap.get(warehouseId); + let currentTableName = ''; + try { + const factory = ctx.model && ctx.model.OrderDeliveryFactory; + if (!factory || typeof factory.generateTableName !== 'function') { + throw new Error('订单工厂不可用'); + } + currentTableName = factory.generateTableName(warehouseId, 'current'); + } catch (error) { + ctx.logger.warn(`[wave-batch-closure] 生成仓库 ${warehouseId} 订单表名失败,跳过: ${error.message}`); + continue; + } + + // 分批查询待处理表中仍存在订单的波次 + const existingWaveIds = new Set(); + let warehouseQueryFailed = false; + for (let offset = 0; offset < waves.length; offset += WAVE_ID_BATCH_SIZE) { + const batchWaves = waves.slice(offset, offset + WAVE_ID_BATCH_SIZE); + const batchWaveIds = batchWaves.map(item => item.waveId); + try { + const existingRows = await ctx.model.query( + `SELECT DISTINCT wave_id + FROM ${currentTableName} + WHERE wave_id IN (:waveIds)`, + { + replacements: { waveIds: batchWaveIds }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + for (const row of (Array.isArray(existingRows) ? existingRows : [])) { + const waveId = Number(row && row.wave_id || 0); + if (Number.isInteger(waveId) && waveId > 0) { + existingWaveIds.add(waveId); + } + } + } catch (error) { + warehouseQueryFailed = true; + ctx.logger.warn(`[wave-batch-closure] 查询仓库 ${warehouseId} 待处理表失败,跳过该仓库: ${error.message}`); + break; + } + } + + if (warehouseQueryFailed) { + continue; + } + + const finishedWaves = waves.filter(item => !existingWaveIds.has(item.waveId)); + if (finishedWaves.length > 0) { + closedWaves.push(...finishedWaves); + } + } + + const closedWaveIds = closedWaves.map(item => item.waveId); + const candidateCount = Array.from(warehouseWaveMap.values()).reduce((sum, waves) => sum + waves.length, 0); + + if (!dryRun && closedWaveIds.length > 0) { + for (let offset = 0; offset < closedWaveIds.length; offset += WAVE_ID_BATCH_SIZE) { + const batchWaveIds = closedWaveIds.slice(offset, offset + WAVE_ID_BATCH_SIZE); + await ctx.model.query( + `UPDATE wms_wave_batch + SET wave_status = :closedStatus, + processed_orders = total_orders, + check_time = NOW(), + update_time = NOW() + WHERE wave_id IN (:waveIds) + AND wave_status IN (:waveStatuses) + AND total_orders > 0`, + { + replacements: { + closedStatus: CLOSED_WAVE_STATUS, + waveIds: batchWaveIds, + waveStatuses: ACTIVE_WAVE_STATUSES, + }, + type: ctx.model.QueryTypes.UPDATE, + } + ); + } + } + + const result = { + dryRun, + candidate_count: candidateCount, + closed_count: closedWaves.length, + warehouse_ids: warehouseIds, + closed_waves: closedWaves, + duration_ms: Date.now() - startedAt, + }; + + if (closedWaves.length > 0) { + ctx.logger.info( + `[wave-batch-closure] 波次终结结果 dryRun=${dryRun} closed=${closedWaves.length}/${candidateCount} waves=${closedWaveIds.join(',')}` + ); + } + + return result; + } +} + +module.exports = WaveBatchClosureService; diff --git a/database/migrations/20260820120000-alter-wms-wave-batch-item-detail-machine-to-text.js b/database/migrations/20260820120000-alter-wms-wave-batch-item-detail-machine-to-text.js new file mode 100644 index 0000000..b88ac11 --- /dev/null +++ b/database/migrations/20260820120000-alter-wms-wave-batch-item-detail-machine-to-text.js @@ -0,0 +1,120 @@ +'use strict'; + +/** + * 将 wms_wave_batch.item_detail_machine 列从 VARCHAR(1024) 改为 TEXT。 + * + * 背景: + * buildMachineStructureToken 生成的结构标识为 + * `v1|item_part_type|item_part|distinguish_express|logistics_name|item_snapshot_key`, + * 其中 item_part 与 item_snapshot_key 均经 encodeURIComponent 编码, + * 多商品订单下编码后的长度可能远超 1024,抓取分组 INSERT 时报 + * "Data too long for column 'item_detail_machine' at row 1"。 + * + * 变更: + * 1. wms_wave_batch.item_detail_machine: VARCHAR(1024) → TEXT + * 2. 索引 idx_wave_item_machine_prefix 维持前缀索引 + * (item_detail_machine(191)),TEXT 列前缀索引仍合法; + * 若存量环境存在全列索引则先删除。 + * 3. 模型定义同步改为 TEXT(app/model/wave_batch.js)。 + */ + +const TABLE_NAME = 'wms_wave_batch'; +const COLUMN_NAME = 'item_detail_machine'; +const INDEX_NAME = 'idx_wave_item_machine_prefix'; + +async function hasColumn(queryInterface, tableName, columnName) { + const [ columns ] = await queryInterface.sequelize.query( + ` + SELECT COLUMN_NAME + FROM INFORMATION_SCHEMA.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = :tableName + AND COLUMN_NAME = :columnName + `, + { replacements: { tableName, columnName } } + ); + + return (Array.isArray(columns) ? columns : []).length > 0; +} + +async function listColumnIndexes(queryInterface, tableName, columnName) { + const [ rows ] = await queryInterface.sequelize.query( + ` + SELECT DISTINCT INDEX_NAME, SUB_PART + FROM INFORMATION_SCHEMA.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = :tableName + AND COLUMN_NAME = :columnName + `, + { replacements: { tableName, columnName } } + ); + + return Array.isArray(rows) ? rows : []; +} + +module.exports = { + up: async queryInterface => { + if (!(await hasColumn(queryInterface, TABLE_NAME, COLUMN_NAME))) { + console.log(`[migrate] ${TABLE_NAME}.${COLUMN_NAME} 列不存在,跳过`); + return; + } + + // ── 1. 全列索引对 TEXT 无效(无前缀),先删除存量全列索引 ── + const existingIndexes = await listColumnIndexes(queryInterface, TABLE_NAME, COLUMN_NAME); + for (const idx of existingIndexes) { + const indexName = String(idx.INDEX_NAME || '').trim(); + const subPart = idx.SUB_PART === null || idx.SUB_PART === undefined + ? null + : Number(idx.SUB_PART); + if (!indexName || subPart) { + continue; + } + + try { + await queryInterface.removeIndex(TABLE_NAME, indexName); + console.log(`[migrate] 已移除全列索引 ${indexName}(TEXT 列要求前缀索引)`); + } catch (e) { + const msg = String(e && e.message || ''); + if (!msg.includes('check that it exists') && !msg.includes('exist')) { + console.warn(`[migrate] 移除全列索引 ${indexName} 时出现非预期错误: ${msg}`); + } + } + } + + // ── 2. 修改列类型为 TEXT ── + await queryInterface.sequelize.query( + `ALTER TABLE \`${TABLE_NAME}\` MODIFY \`${COLUMN_NAME}\` TEXT NULL COMMENT '抓取结构token:v1|item_part_type|item_part|distinguish_express|logistics_name|item_snapshot_key'` + ); + console.log(`[migrate] ${TABLE_NAME}.${COLUMN_NAME} VARCHAR(1024) → TEXT`); + + // ── 3. 确保前缀索引存在 ── + const remainingIndexes = await listColumnIndexes(queryInterface, TABLE_NAME, COLUMN_NAME); + if (remainingIndexes.length === 0) { + try { + await queryInterface.sequelize.query( + `ALTER TABLE \`${TABLE_NAME}\` ADD INDEX \`${INDEX_NAME}\` (\`${COLUMN_NAME}\`(191))` + ); + console.log(`[migrate] 已创建前缀索引 ${INDEX_NAME}(${COLUMN_NAME}(191))`); + } catch (e) { + const msg = String(e && e.message || ''); + if (!msg.includes('Duplicate')) { + throw e; + } + console.log(`[migrate] 前缀索引 ${INDEX_NAME} 已存在,跳过`); + } + } + }, + + down: async queryInterface => { + if (!(await hasColumn(queryInterface, TABLE_NAME, COLUMN_NAME))) { + console.log(`[migrate:down] ${TABLE_NAME}.${COLUMN_NAME} 列不存在,跳过`); + return; + } + + // 注意:若已有数据超过 1024 字符,回滚会失败,需先人工截断数据 + await queryInterface.sequelize.query( + `ALTER TABLE \`${TABLE_NAME}\` MODIFY \`${COLUMN_NAME}\` VARCHAR(1024) NULL COMMENT '抓取结构token:v1|item_part_type|item_part|distinguish_express|logistics_name|item_snapshot_key'` + ); + console.log(`[migrate:down] ${TABLE_NAME}.${COLUMN_NAME} TEXT → VARCHAR(1024)`); + }, +}; From 4f2ef5ecb3ae22adc7e12162f85fe771585da6c1 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Fri, 21 Aug 2026 02:20:22 +0800 Subject: [PATCH 241/550] =?UTF-8?q?feat(pick):=20=E6=8B=A3=E8=B4=A7?= =?UTF-8?q?=E5=AE=8C=E6=88=90=E6=8B=A6=E6=88=AA=E5=8D=95=E8=B7=B3=E8=BF=87?= =?UTF-8?q?=E5=B9=B6=E7=A7=BB=E5=87=BA=E6=B3=A2=E6=AC=A1=E5=9B=9E=E5=86=99?= =?UTF-8?q?=E7=BB=9F=E8=AE=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 拦截单不再报错中止, 直接跳过(不完成拣货、不扣减库存) - source!=0 任务中被跳过的拦截单从波次移除: wave_id 清零、删除波次索引、 回写 wms_wave_batch.total_orders/processed_orders, 空波次置 wave_status=-1 - 同步清理任务订单关联与箱子明细, 全部跳过时按任务进度完结 --- app/service/systems/pick.js | 386 +++++++++++++++++++++++++++++++++++- 1 file changed, 378 insertions(+), 8 deletions(-) diff --git a/app/service/systems/pick.js b/app/service/systems/pick.js index fe48b7d..fa2d5fc 100644 --- a/app/service/systems/pick.js +++ b/app/service/systems/pick.js @@ -1947,7 +1947,9 @@ class PickSystemService extends Service { } } - // 检查目标订单是否进入拦截流程,拦截订单不允许完成拣货 + // 检查目标订单是否进入拦截流程,拦截订单直接跳过: + // 不完成拣货、不扣减库存(不取出)、不报错,其余订单照常完成 + const skippedInterceptedOrders = []; if (targetOrderIds.length > 0) { const interceptCheckModel = await this.getOrderModel(warehouseId); const interceptedOrderRows = await interceptCheckModel.findAll({ @@ -1966,16 +1968,290 @@ class PickSystemService extends Service { }); if (interceptedOrderRows && interceptedOrderRows.length > 0) { - const detailList = interceptedOrderRows.map( - orderRow => `订单${orderRow.id}(intercept_status=${orderRow.intercept_status})` - ).join(';'); - throw this.createBusinessError( - `以下订单已被拦截,无法完成拣货:${detailList}`, - 400 + const interceptedOrderIdSet = new Set( + interceptedOrderRows.map(orderRow => Number(orderRow && orderRow.id || 0)) ); + for (const orderRow of interceptedOrderRows) { + skippedInterceptedOrders.push({ + order_id: Number(orderRow && orderRow.id || 0), + intercept_status: String(orderRow && orderRow.intercept_status || '').trim() || 'none', + }); + } + targetOrderIds = targetOrderIds.filter(orderId => !interceptedOrderIdSet.has(orderId)); } } + // source !== 0(PDA/后台抓取创建的任务)时,被跳过的拦截订单直接从波次中移除: + // 订单 wave_id 清零、重建波次索引、回写波次统计,并移除任务订单关联 + const removedFromWaveOrderLogItems = []; + const removedFromWaveOrderIds = []; + if (skippedInterceptedOrders.length > 0 && taskSource !== 0) { + const skippedOrderIds = skippedInterceptedOrders.map(item => item.order_id); + const interceptOrderModel = await this.getOrderModel(warehouseId); + const removableRows = await interceptOrderModel.findAll({ + attributes: [ 'id', 'wave_id', 'wave_no' ], + where: { + warehouse_id: warehouseId, + id: { + [this.app.Sequelize.Op.in]: skippedOrderIds, + }, + wave_id: { + [this.app.Sequelize.Op.gt]: 0, + }, + }, + raw: true, + transaction, + }); + + const normalizedRemovableRows = Array.isArray(removableRows) ? removableRows : []; + const affectedWaveIds = [ ...new Set(normalizedRemovableRows + .map(row => Number(row && row.wave_id || 0)) + .filter(waveId => Number.isInteger(waveId) && waveId > 0)) ]; + + if (normalizedRemovableRows.length > 0) { + await interceptOrderModel.update({ + wave_id: 0, + wave_no: '', + wave_strategy_version: 0, + wave_scan_result: 0, + }, { + where: { + warehouse_id: warehouseId, + id: { + [this.app.Sequelize.Op.in]: normalizedRemovableRows.map(row => Number(row.id)), + }, + }, + transaction, + }); + + for (const row of normalizedRemovableRows) { + removedFromWaveOrderIds.push(Number(row && row.id || 0)); + removedFromWaveOrderLogItems.push({ + orderId: Number(row && row.id || 0), + operationCode: 'ORDER_WAVE_REMOVE', + message: `订单从波次 ${String(row && row.wave_no || '').trim() || '未知波次'} 中移除`, + }); + } + + if (affectedWaveIds.length > 0) { + const waveService = this.ctx.service + && this.ctx.service.systemMethods + && this.ctx.service.systemMethods.order + && this.ctx.service.systemMethods.order.wave; + + // 仅删除拦截单自身的索引行,不重建整波索引: + // 其余订单 wave_index 保持不变(仅跳号),避免与已放货的篮子编号 + // (task_order.box_no / task_box.box_no 为创建时 wave_index 快照)错位, + // 保证复核/打印等按 wave_index 排序的环节仍与实物位置一致。 + if (waveService && typeof waveService.deleteOrderWaveIndexByOrderIds === 'function') { + await waveService.deleteOrderWaveIndexByOrderIds({ + warehouseId, + orderIds: normalizedRemovableRows.map(row => Number(row.id)), + transaction, + }); + } + + // 按剩余索引行数回写波次统计(删除后未重建,剩余订单序号保持不变) + const remainingIndexRows = await this.ctx.model.query(` + SELECT wave_id, COUNT(*) AS remaining_count + FROM wms_order_wave_index + WHERE warehouse_id = :warehouseId + AND wave_id IN (:waveIds) + GROUP BY wave_id + `, { + replacements: { + warehouseId, + waveIds: affectedWaveIds, + }, + type: this.ctx.model.QueryTypes.SELECT, + transaction, + }); + + const remainingCountMap = new Map(); + for (const row of Array.isArray(remainingIndexRows) ? remainingIndexRows : []) { + const waveId = Number(row && row.wave_id || 0); + const remainingCount = Number(row && row.remaining_count || 0); + if (Number.isInteger(waveId) && waveId > 0) { + remainingCountMap.set(waveId, remainingCount); + } + } + + const updatedWaveIds = []; + const emptiedWaveIds = []; + for (const waveId of affectedWaveIds) { + const remainingCount = Number(remainingCountMap.get(waveId) || 0); + if (remainingCount > 0) { + updatedWaveIds.push(waveId); + } else { + emptiedWaveIds.push(waveId); + } + } + + for (const waveId of updatedWaveIds) { + const remainingCount = Number(remainingCountMap.get(waveId) || 0); + await this.ctx.model.query(` + UPDATE wms_wave_batch + SET total_orders = :remainingCount, + processed_orders = LEAST(processed_orders, :remainingCount), + update_time = NOW() + WHERE warehouse_id = :warehouseId + AND wave_id = :waveId + `, { + replacements: { + warehouseId, + waveId, + remainingCount, + }, + transaction, + }); + } + + if (emptiedWaveIds.length > 0) { + await this.ctx.model.query(` + UPDATE wms_wave_batch + SET total_orders = 0, + processed_orders = 0, + wave_status = -1, + update_time = NOW() + WHERE warehouse_id = :warehouseId + AND wave_id IN (:waveIds) + `, { + replacements: { + warehouseId, + waveIds: emptiedWaveIds, + }, + transaction, + }); + } + } + + // 移除任务订单关联记录,任务进度不再包含被移出波次的拦截单 + await this.ctx.model.query(` + DELETE FROM wms_wave_pick_task_order + WHERE task_id = :taskId + AND warehouse_id = :warehouseId + AND order_id IN (:orderIds) + `, { + replacements: { + taskId, + warehouseId, + orderIds: normalizedRemovableRows.map(row => Number(row.id)), + }, + transaction, + }); + + // 同步移除拦截单对应的篮子明细(散单模式 box_type=2 绑定订单),避免遗留空盒 + const taskBoxColumnSet = await this.getTableColumnSet('wms_wave_pick_task_box'); + const taskBoxWarehouseFilterSql = taskBoxColumnSet.has('warehouse_id') ? ' AND warehouse_id = :warehouseId' : ''; + await this.ctx.model.query(` + DELETE FROM wms_wave_pick_task_box + WHERE task_id = :taskId + AND order_id IN (:orderIds) + ${taskBoxWarehouseFilterSql} + `, { + replacements: { + taskId, + warehouseId, + orderIds: normalizedRemovableRows.map(row => Number(row.id)), + }, + transaction, + }); + } + } + + // 目标订单全部被拦截跳过:不做任何拣货/库存变更,直接成功返回 + if (targetOrderIds.length <= 0) { + // mode=1(全部确认)时任务标记完成;mode=2 依据任务进度判断 + const skipProgressBeforeComplete = await this.getTaskPickProgress(taskId, warehouseId, transaction); + const skipTaskCompleted = mode === 1 || skipProgressBeforeComplete.isCompleted; + if (skipTaskCompleted) { + await this.ctx.model.query(` + UPDATE wms_wave_pick_task + SET status = 2, + finish_time = NOW(), + start_time = CASE WHEN start_time IS NULL THEN NOW() ELSE start_time END, + update_time = NOW() + WHERE id = :taskId + AND warehouse_id = :warehouseId + `, { + replacements: { + taskId, + warehouseId, + }, + transaction, + }); + + // 同步更新波次关联状态为已拣 + const taskWaveColumnSet = await this.getTableColumnSet('wms_wave_pick_task_wave'); + const taskWaveWarehouseFilterSql = taskWaveColumnSet.has('warehouse_id') ? ' AND warehouse_id = :warehouseId' : ''; + await this.ctx.model.query(` + UPDATE wms_wave_pick_task_wave + SET status = 1, + pick_time = NOW(), + update_time = NOW() + WHERE task_id = :taskId + ${taskWaveWarehouseFilterSql} + `, { + replacements: { + taskId, + warehouseId, + }, + transaction, + }); + } else { + await this.ctx.model.query(` + UPDATE wms_wave_pick_task + SET status = CASE WHEN status = 0 THEN 1 ELSE status END, + start_time = CASE WHEN start_time IS NULL THEN NOW() ELSE start_time END, + update_time = NOW() + WHERE id = :taskId + AND warehouse_id = :warehouseId + `, { + replacements: { + taskId, + warehouseId, + }, + transaction, + }); + } + + await transaction.commit(); + const skipProgress = await this.getTaskPickProgress(taskId, warehouseId); + await this._writePickCompleteActionLog({ + taskId, + warehouseId, + operatorId, + operatorName, + targetOrderIds: [], + mode, + isCompleted: skipProgress.isCompleted, + progress: skipProgress, + skippedInterceptedOrders, + }); + await this._afterSkipInterceptedPostActions({ + warehouseId, + operatorId, + operatorName, + removedFromWaveOrderLogItems, + removedFromWaveOrderIds, + }); + return { + task_id: taskId, + mode, + confirmed_order_ids: [], + skipped_intercepted_order_ids: skippedInterceptedOrders.map(item => item.order_id), + skipped_intercepted_orders: skippedInterceptedOrders, + removed_from_wave_order_ids: removedFromWaveOrderIds, + is_completed: skipProgress.isCompleted, + task_completed: skipTaskCompleted, + progress: { + total_orders: skipProgress.totalOrders, + picked_orders: skipProgress.pickedOrders, + pending_orders: skipProgress.pendingOrders, + }, + }; + } + // 检查目标订单是否已分配储位(storage_status='fin'),防止订单在波次中被取消储位分配后仍然完成拣货 if (targetOrderIds.length > 0) { const orderModel = await this.getOrderModel(warehouseId); @@ -2168,7 +2444,9 @@ class PickSystemService extends Service { }); const progress = await this.getTaskPickProgress(taskId, warehouseId, transaction); - if (mode === 1 || progress.isCompleted) { + // mode=1(全部确认)时任务直接标记完成;mode=2 依据任务进度判断 + const taskCompleted = mode === 1 || progress.isCompleted; + if (taskCompleted) { await ctx.model.query(` UPDATE wms_wave_pick_task SET status = 2, @@ -2231,6 +2509,16 @@ class PickSystemService extends Service { mode, isCompleted: progress.isCompleted, progress, + skippedInterceptedOrders, + }); + + // 被移出波次的拦截订单:写订单操作日志 + 触发策略快扫(不影响主流程) + await this._afterSkipInterceptedPostActions({ + warehouseId, + operatorId, + operatorName, + removedFromWaveOrderLogItems, + removedFromWaveOrderIds, }); // 写入 order_operation_log 拣货完成日志 @@ -2267,7 +2555,11 @@ class PickSystemService extends Service { task_id: taskId, mode, confirmed_order_ids: targetOrderIds, + skipped_intercepted_order_ids: skippedInterceptedOrders.map(item => item.order_id), + skipped_intercepted_orders: skippedInterceptedOrders, + removed_from_wave_order_ids: removedFromWaveOrderIds, is_completed: progress.isCompleted, + task_completed: taskCompleted, progress: { total_orders: progress.totalOrders, picked_orders: progress.pickedOrders, @@ -2280,6 +2572,81 @@ class PickSystemService extends Service { } } + /** + * 拦截单跳过后的收尾动作(均不影响主流程): + * 1. 写入被移出波次拦截订单的 ORDER_WAVE_REMOVE 操作日志; + * 2. 触发波次策略快速扫描,让移出波次的订单重新进入可抓取池。 + * + * @param {Object} params 参数。 + * @param {number} params.warehouseId 仓库ID。 + * @param {number} params.operatorId 操作人ID。 + * @param {string} params.operatorName 操作人名称。 + * @param {Array} params.removedFromWaveOrderLogItems 波次移除日志项。 + * @param {Array} params.removedFromWaveOrderIds 被移出波次的订单ID。 + * @return {Promise} 无返回值。 + */ + async _afterSkipInterceptedPostActions(params = {}) { + const warehouseId = Number(params && params.warehouseId || 0); + const operatorId = Number(params && params.operatorId || 0); + const operatorName = String(params && params.operatorName || '').trim() || 'system'; + const removedFromWaveOrderLogItems = Array.isArray(params && params.removedFromWaveOrderLogItems) + ? params.removedFromWaveOrderLogItems + : []; + const removedFromWaveOrderIds = Array.isArray(params && params.removedFromWaveOrderIds) + ? params.removedFromWaveOrderIds + : []; + + if (removedFromWaveOrderLogItems.length > 0) { + try { + const operationLogService = this.ctx + && this.ctx.service + && this.ctx.service.systems + && this.ctx.service.systems.operationLog; + if (operationLogService && typeof operationLogService.createOperationLogs === 'function') { + const logPayloads = removedFromWaveOrderLogItems.map(item => ({ + businessType: 'order', + businessId: `${item.orderId}`, + operationCode: item.operationCode, + operator: { + id: operatorId ? String(operatorId) : null, + name: operatorName, + }, + extras: { + message: item.message, + warehouseId, + externalLogType: 'API', + }, + })); + await operationLogService.createOperationLogs(logPayloads); + } + } catch (e) { + this.ctx.logger.warn('[pick.wavePickTaskComplete] 写入波次移除操作日志失败,不影响主流程', { + error: e && e.message, + }); + } + } + + if (removedFromWaveOrderIds.length > 0) { + try { + const waveService = this.ctx.service + && this.ctx.service.systemMethods + && this.ctx.service.systemMethods.order + && this.ctx.service.systemMethods.order.wave; + if (waveService && typeof waveService.enqueueWaveStrategyQuickScanPostOrderChange === 'function') { + waveService.enqueueWaveStrategyQuickScanPostOrderChange( + warehouseId, + removedFromWaveOrderIds, + { triggerScan: true, source: 'pickSkipInterceptedRemoveWave' } + ); + } + } catch (e) { + this.ctx.logger.warn('[pick.wavePickTaskComplete] 触发波次策略快扫失败,不影响主流程', { + error: e && e.message, + }); + } + } + } + /** * 写入拣货完成操作日志到 wms_wave_pick_action_log(内部方法)。 * @@ -2292,6 +2659,7 @@ class PickSystemService extends Service { * @param {number} params.mode 提交模式(1全部确认 2部分确认)。 * @param {boolean} params.isCompleted 任务是否全部完成。 * @param {Object} params.progress 任务进度信息。 + * @param {Array} params.skippedInterceptedOrders 被跳过的拦截订单(order_id + intercept_status)。 * @return {Promise} 无返回值。 */ async _writePickCompleteActionLog(params = {}) { @@ -2304,6 +2672,7 @@ class PickSystemService extends Service { mode, isCompleted, progress, + skippedInterceptedOrders, } = params; const requestId = `pick_complete_${warehouseId}_${taskId}_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`; @@ -2363,6 +2732,7 @@ class PickSystemService extends Service { mode, confirmed_order_ids: targetOrderIds, confirmed_order_count: Array.isArray(targetOrderIds) ? targetOrderIds.length : 0, + skipped_intercepted_orders: Array.isArray(skippedInterceptedOrders) ? skippedInterceptedOrders : [], is_completed: isCompleted, progress: { total_orders: progress && progress.totalOrders, From eca309d41f496830daa971f0a13a0a155bb66593 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Fri, 21 Aug 2026 02:20:26 +0800 Subject: [PATCH 242/550] =?UTF-8?q?fix(print):=20=E6=89=93=E5=8D=B0?= =?UTF-8?q?=E8=87=AA=E5=AE=9A=E4=B9=89=E5=8C=BA=E5=90=8C=E5=BA=93=E4=BD=8D?= =?UTF-8?q?=E4=B8=8D=E5=90=8C=E5=95=86=E5=93=81=E4=B8=8D=E5=86=8D=E5=90=88?= =?UTF-8?q?=E5=B9=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 聚合键由库位改为 库位+stock_id 复合键, 仅同库位同商品合并数量 - stock_id 缺失时依次回退 order_item_id、商品名称+条码, 无法识别商品身份时不再跨行合并 --- app/service/systems/order_print.js | 52 ++++++++++++++++++++++++++---- 1 file changed, 45 insertions(+), 7 deletions(-) diff --git a/app/service/systems/order_print.js b/app/service/systems/order_print.js index 96925d7..8a0940b 100644 --- a/app/service/systems/order_print.js +++ b/app/service/systems/order_print.js @@ -172,6 +172,40 @@ class OrderPrintSystemService extends OrderBaseService { return ''; } + /** + * 构建打印项聚合键。 + * + * 同一库位下的拣货行只有商品身份一致时才允许合并: + * - 优先 stock_id(>0):同一库位同一商品合并数量; + * - stock_id 缺失时回退 order_item_id(同一订单商品行); + * - 再缺失时回退 商品名称+条码 兜底; + * - 均无法识别时不做跨行合并(每行独立)。 + * + * @param {Object} item 打印项。 + * @return {string} 聚合键。 + */ + buildPrintItemAggregationKey(item = {}) { + const source = this.isPlainObject(item) ? item : {}; + const location = String(source.pick_location || '').trim(); + const stockId = Number(source.stock_id || 0); + if (stockId > 0) { + return `${location}::stock:${stockId}`; + } + + const orderItemId = Number(source.order_item_id || 0); + if (orderItemId > 0) { + return `${location}::order_item:${orderItemId}`; + } + + const name = String(source.item_name || '').trim(); + const barcode = String(source.barcode || '').trim(); + if (name || barcode) { + return `${location}::name:${name}|${barcode}`; + } + + return `${location}::id:${Math.random()}`; + } + /** * 批量补查打印所需的拣货明细,并注入商品多条码。 * @@ -377,20 +411,19 @@ class OrderPrintSystemService extends OrderBaseService { // 为每条打印项注入 barcodes 数组,供 resolveItemBarcodeText 优先读取 for (const item of printItems) { - const stockId = item.stock_id; + const stockId = Number(item.stock_id || 0); + item.stock_id = stockId > 0 ? stockId : 0; - if (stockId && barcodeMap.has(stockId)) { + if (stockId > 0 && barcodeMap.has(stockId)) { item.barcodes = barcodeMap.get(stockId); } - - // 清理内部字段,避免污染 JSON 输出 - delete item.stock_id; } - // 按库位(pick_location)聚合,同一库位的商品合并为一行 + // 按「库位 + 商品(stock_id)」聚合:同一库位的同一商品合并为一行, + // 同一库位的不同商品保持独立行,避免数量、条码被错误合并。 const aggregatedMap = new Map(); for (const item of printItems) { - const key = item.pick_location || ''; + const key = this.buildPrintItemAggregationKey(item); const existing = aggregatedMap.get(key); if (existing) { // 累加数量 @@ -414,6 +447,11 @@ class OrderPrintSystemService extends OrderBaseService { } const mergedPrintItems = Array.from(aggregatedMap.values()); + // 聚合完成后清理内部字段,避免污染 JSON 输出 + for (const item of mergedPrintItems) { + delete item.stock_id; + } + // 为聚合后的商品行添加序号(从 1 开始) for (let i = 0; i < mergedPrintItems.length; i++) { mergedPrintItems[i].seq_no = i + 1; From e0b2cf3030e4e54e299fea200d7345c6a5e33e10 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Fri, 21 Aug 2026 02:20:31 +0800 Subject: [PATCH 243/550] =?UTF-8?q?feat(expressPlatform):=20=E9=9D=A2?= =?UTF-8?q?=E5=8D=95=E4=B8=8B=E5=8D=95=E5=8F=82=E6=95=B0=E8=A1=A5=E5=85=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 菠萝派平台启用 ismultiplepieces/logisticno 并放开体积重量等参数 - 修复 PDD/QT/OTHER 面单回写 orderno 十六进制仓库ID转十进制 - 补全 businesstype/platcode/length/width/height/weight 与 ordertime - SF 场景 customercode 置空, oaid 含横杠视为超长回退 caid --- app/service/systems/express_platform.js | 55 +++++++++++++++---------- 1 file changed, 34 insertions(+), 21 deletions(-) diff --git a/app/service/systems/express_platform.js b/app/service/systems/express_platform.js index 2b05b3f..db10d63 100644 --- a/app/service/systems/express_platform.js +++ b/app/service/systems/express_platform.js @@ -708,8 +708,8 @@ class ExpressPlatformService extends MainService { orderno: `${order.warehouse_id.toString(16)}_${order.id}_${order_tmp.business_key}`, // 菠萝派平台要求订单号必须为字符串 plattradeno: listByWarehousePlatformCode.platform_code === 'DY' && order.from_key === 23060081 && !!order.pay_no ? order.pay_no : order.source_order_codes || order.delivery_order_code || '', tid:listByWarehousePlatformCode.platform_code === 'DY' && order.from_key === 23060081 && !!order.pay_no ? order.pay_no : order.source_order_codes || order.delivery_order_code || '', - //ismultiplepieces: order.package_count > 1 ? 1 : 0, - //logisticno: allocatedWaybillMap.get(`${Number(order.id) || 0}:${Number(order_tmp.business_key) || 0}`) || '', + ismultiplepieces: order.package_count > 1 ? 1 : 0, + logisticno: allocatedWaybillMap.get(`${Number(order.id) || 0}:${Number(order_tmp.business_key) || 0}`) || '', logistictype: expressListItem[listByWarehousePlatformCode.platform_code] || '', providercode: expressListItem[listByWarehousePlatformCode.platform_code] || order.logistics_code || '', numpackage: order.package_count || '1', @@ -718,26 +718,31 @@ class ExpressPlatformService extends MainService { transtypecode:'1', mainsubpaymode:'1', businessplat: order.sys_platform_code === 'KS' ? order.sys_platform_code : 'OTHERS', - paymode: listByWarehousePlatformCode.paymode.toString() ?? '1', + paymode: '1', ordertype: listByWarehousePlatformCode.ordertype ?? 'JH_Normal', ProviderID:'', - //procode: order.procode || '普通商品', - //codpaymoney: order.ar_amount ?? null, - //packagemoney: order.item_amount ?? null, - //weight: Number(order.items_weight) || 0, // 单位 g,需确认 PolyAPI 期望单位 - //supporpaymoney: order.total_amount ?? null, - //ispickup: listByWarehousePlatformCode.ispickup ?? 0, - //ProductType: listByWarehousePlatformCode.product_type || '', - //Sipshopid: listByWarehousePlatformCode.platform_shop_id || '', + procode: order.procode || '普通商品', + codpaymoney: order.ar_amount ?? null, + packagemoney: order.item_amount ?? null, + weight: Number(order.items_weight) || 0, // 单位 g,需确认 PolyAPI 期望单位 + supporpaymoney: order.total_amount ?? null, + length: Number(order.length) || 0, + width: Number(order.width) || 0, + height: Number(order.height) || 0, + volume: Number(order.volume) || 0, + ispickup: listByWarehousePlatformCode.ispickup ?? 0, + ProductType: listByWarehousePlatformCode.product_type || '', + Sipshopid: listByWarehousePlatformCode.platform_shop_id || '', oaid: order.oaid || '', cpcode: expressListItem[listByWarehousePlatformCode.platform_code] || '', logisticsproductname: 'JH_02', - //dmssorting: 0, - //brandno: listByWarehousePlatformCode.brandno || null, + dmssorting: 0, + brandno: listByWarehousePlatformCode.brandno || null, needencrypt: 1, + ordertime: order.place_order_time || '', customername:"测试", ordersource: matchedPlatform.ordersource || '', - //inputsite: order.sys_platform_code === 'XHS' ? '' :listByWarehousePlatformCode.site_code || '', + inputsite: order.sys_platform_code === 'XHS' ? '' :listByWarehousePlatformCode.site_code || '', sitecode: listByWarehousePlatformCode.site_code || '', shipperno: order.sys_platform_code === 'XHS' ? '' :listByWarehousePlatformCode.shipperno || '', customercode: order.sys_platform_code === 'XHS' ? '' :listByWarehousePlatformCode.shipperno || listByWarehousePlatformCode.client_id || '', @@ -776,8 +781,8 @@ class ExpressPlatformService extends MainService { //Mallmaskid: '', template_url: listByWarehousePlatformCode.template_id || '', - //labelformat: listByWarehousePlatformCode.labelformat || '', - //extraInfo: ExpressList.find(item => item.code === listByWarehousePlatformCode.sys_express_code)?.polyapi_extra_info || '', + labelformat: listByWarehousePlatformCode.labelformat || '', + extraInfo: ExpressList.find(item => item.code === listByWarehousePlatformCode.sys_express_code)?.polyapi_extra_info || '', }; console.log('matchedPlatform.platid', matchedPlatform.platid); console.log('startPlayload', playload); @@ -836,11 +841,13 @@ class ExpressPlatformService extends MainService { orderno, plattradeno, ProductType, + businesstype:ProductType, expresstype: ProductType, logistictype, providercode: providercode || cpcode || logistictype || '', numpackage, businessplat, + platcode:plattradeno, mainsubpaymode: '1', ordertype, businessType: businessType || ordertype || 'JH_Normal', @@ -855,7 +862,7 @@ class ExpressPlatformService extends MainService { customername, goods, oaid, - customercode: customercode || shipperno || listByWarehousePlatformCode.shipperno || listByWarehousePlatformCode.client_id || '', + customercode: logistictype==="SF" ? undefined: customercode || shipperno || listByWarehousePlatformCode.shipperno || listByWarehousePlatformCode.client_id || '', sender: { name: senderName, phone: senderPhoneRaw, @@ -1302,7 +1309,8 @@ class ExpressPlatformService extends MainService { } case 'PDD': successUpdates = (result.results || []).map(item => { - const [ warehouse_id, order_id, business_key ] = String(item.orderno || '').split('_'); + const [ warehouse_id_hex, order_id, business_key ] = String(item.orderno || '').split('_'); + const warehouse_id = parseInt(warehouse_id_hex, 16); const waybillCode = resolveWaybillCode(item); return { warehouse_id, @@ -1337,7 +1345,8 @@ class ExpressPlatformService extends MainService { case 'QT': case 'OTHER': successUpdates = (result.results || []).map(item => { - const [ warehouse_id, order_id, business_key ] = String(item.orderno || '').split('_'); + const [ warehouse_id_hex, order_id, business_key ] = String(item.orderno || '').split('_'); + const warehouse_id = parseInt(warehouse_id_hex, 16); const waybillCode = String(item.logisticno || item.waybill_code || '').trim(); return { warehouse_id, @@ -1761,7 +1770,7 @@ class ExpressPlatformService extends MainService { : []; const recipientMobile = orderDelivery && (orderDelivery.mobile || orderDelivery.tel) || ''; const orderDeliveryOaid = orderDelivery && orderDelivery.oaid ? String(orderDelivery.oaid).trim() : ''; - const oaidTooLong = orderDeliveryOaid.length > 128; + const oaidTooLong = orderDeliveryOaid.indexOf("-") !== -1 || orderDeliveryOaid.length > 128; const tradeOrderInfo = { logistics_services: normalizedExtData, @@ -1785,6 +1794,10 @@ class ExpressPlatformService extends MainService { })) || [], goods_description: '物品', id: `${orderDelivery.warehouse_id}_${orderDelivery.id}_${order_tmp.business_key}`, + length:Number(orderDelivery.length || 1), + width:Number(orderDelivery.width || 1), + height:Number(orderDelivery.height || 1), + weight:Number(orderDelivery.items_weight || 1), }, recipient: { address: { @@ -1800,7 +1813,7 @@ class ExpressPlatformService extends MainService { phone: recipientMobile, oaid: oaidTooLong ? '' : orderDeliveryOaid, caid: oaidTooLong ? orderDeliveryOaid : '', - tid: orderDelivery.pay_no || '', + tid: orderDelivery.source_order_codes, }, user_id: listByWarehousePlatformCode.shop && listByWarehousePlatformCode.shop.owner_id || 0, notify_extend_info: normalizedExtData, From 59019e07a67fe280d19767241d0cbf3a51585d82 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Fri, 21 Aug 2026 02:20:36 +0800 Subject: [PATCH 244/550] =?UTF-8?q?feat(deliveryOrder):=20=E5=BF=AB?= =?UTF-8?q?=E9=80=92=E8=A7=A3=E6=9E=90=E5=BF=AB=E7=85=A7=E4=B8=8E=E7=AD=96?= =?UTF-8?q?=E7=95=A5=E6=BC=8F=E6=96=97=E8=B0=83=E6=95=B4=E3=80=81=E6=89=8B?= =?UTF-8?q?=E5=8A=A8=E5=8D=95=E5=BA=93=E5=AD=98=E5=BD=92=E5=B1=9E=E6=A0=A1?= =?UTF-8?q?=E9=AA=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - resolveExpressSnapshot 全路径补日志与回退快递名称, 未匹配也写快递回退操作日志 - enable_external_express_code 开启时跳过快递策略漏斗, 保留外部匹配/兜底结果 - 手动单直接传 stock_id 时校验库存归属货主, 跨货主库存拒绝下单 --- app/service/systems/delivery_order.js | 80 +++++++++++++++++++++++++-- 1 file changed, 76 insertions(+), 4 deletions(-) diff --git a/app/service/systems/delivery_order.js b/app/service/systems/delivery_order.js index eef7854..a893e93 100644 --- a/app/service/systems/delivery_order.js +++ b/app/service/systems/delivery_order.js @@ -533,7 +533,24 @@ class DeliveryOrderService extends Service { explicitEnableExternalExpressCode ); + this.ctx.logger.info('[DeliveryOrderService.resolveExpressSnapshot] 快递解析开始', { + deliveryOrderCode: info.deliveryOrderCode, + warehouseId: info.warehouseId, + storeId: info.storeId, + logisticsCode: externalCode, + enableExternalExpressCode: isEnableExternalExpressCode, + defaultExpressCode: defaultCode, + }); + if (!isEnableExternalExpressCode) { + this.ctx.logger.info('[DeliveryOrderService.resolveExpressSnapshot] 未启用外部快递编码,直接使用默认快递', { + deliveryOrderCode: info.deliveryOrderCode, + logisticsCode: externalCode, + matched: false, + fallbackLogisticsCode, + fallbackLogisticsName, + }); + return { logisticsCode: fallbackLogisticsCode, logisticsName: fallbackLogisticsName, @@ -553,6 +570,17 @@ class DeliveryOrderService extends Service { ).trim(); const matchedSysLogisticsName = this.getOptionName(matchedSysExpress); + this.ctx.logger.info('[DeliveryOrderService.resolveExpressSnapshot] 外部快递编码命中 wms_express_setting 映射', { + deliveryOrderCode: info.deliveryOrderCode, + logisticsCode: externalCode, + matched: true, + source: 'wms_express_setting', + mappedLogisticsCode: String(expressSetting.code || externalCode).trim(), + mappedLogisticsName: String(expressSetting.name || '').trim(), + sysLogisticsCode: matchedSysLogisticsCode, + sysLogisticsName: matchedSysLogisticsName, + }); + return { logisticsCode: String(expressSetting.code || externalCode).trim(), logisticsName: String(expressSetting.name || '').trim(), @@ -570,6 +598,15 @@ class DeliveryOrderService extends Service { ).trim(); const matchedLogisticsName = this.getOptionName(matchedExpress); + this.ctx.logger.info('[DeliveryOrderService.resolveExpressSnapshot] 外部快递编码命中系统快递列表', { + deliveryOrderCode: info.deliveryOrderCode, + logisticsCode: externalCode, + matched: true, + source: 'wms_express', + matchedLogisticsCode, + matchedLogisticsName, + }); + return { logisticsCode: matchedLogisticsCode, logisticsName: matchedLogisticsName, @@ -579,18 +616,21 @@ class DeliveryOrderService extends Service { }; } if (fallbackExpress) { - this.ctx.logger.warn('[DeliveryOrderService.prepareOrderData] invalid logistics code fallback to store default', { + this.ctx.logger.warn('[DeliveryOrderService.resolveExpressSnapshot] 快递编码未匹配到任何快递,兜底为默认快递', { deliveryOrderCode: info.deliveryOrderCode, warehouseId: info.warehouseId, storeId: info.storeId, logisticsCode: externalCode, + matched: false, + fallbackLogisticsCode, + fallbackLogisticsName, defaultExpressCode: defaultCode, }); this.appendOrderOperationLog( operationLogs, ORDER_OPERATION_CODES.EXPRESS_FALLBACK, - `快递编码${externalCode}匹配不到快递,已转为默认快递:${this.getOptionName(fallbackExpress) || defaultCode}` + `快递编码${externalCode}匹配不到快递,已转为默认快递:${fallbackLogisticsName || fallbackLogisticsCode}` ); return { @@ -602,14 +642,23 @@ class DeliveryOrderService extends Service { }; } - this.ctx.logger.warn('[DeliveryOrderService.prepareOrderData] express default not found in express service list', { + this.ctx.logger.warn('[DeliveryOrderService.resolveExpressSnapshot] 默认快递不在快递列表中,使用全局兜底快递', { deliveryOrderCode: info.deliveryOrderCode, warehouseId: info.warehouseId, storeId: info.storeId, logisticsCode: externalCode, + matched: false, + fallbackLogisticsCode, + fallbackLogisticsName, defaultExpressCode: defaultCode, }); + this.appendOrderOperationLog( + operationLogs, + ORDER_OPERATION_CODES.EXPRESS_FALLBACK, + `快递编码${externalCode}匹配不到快递,兜底快递:${fallbackLogisticsName || fallbackLogisticsCode}` + ); + return { logisticsCode: fallbackLogisticsCode, logisticsName: fallbackLogisticsName, @@ -748,10 +797,22 @@ class DeliveryOrderService extends Service { }; // ===== 快递绑定策略漏斗匹配(items 处理后 weight 可用) ===== + // enable_external_express_code 开启时以外部快递匹配结果为准(匹配不到已在 resolveExpressSnapshot 兜底默认快递),跳过策略漏斗覆盖 try { + const funnelPolicyConfig = await this.getStoreWarehousePolicyConfig(info.storeId, info.warehouseId); + const enableExternalExpressCode = this.resolveEnableExternalExpressCode(funnelPolicyConfig, funnelPolicyConfig); + if (enableExternalExpressCode) { + ctx.logger.info('[ExpressPolicyMatch] enable_external_express_code 开启,跳过快递策略漏斗,保留外部快递匹配或兜底结果', { + orderId, + orderCode: deliveryOrder.deliveryOrderCode, + logisticsCode: orderData.logistics_code, + sysLogisticsCode: orderData.sys_logistics_code, + }); + } const receiverInfo = deliveryOrder.receiverInfo; const shopNick = deliveryOrder.shopNick; - const hasEnoughData = shopNick || (receiverInfo && (receiverInfo.province || receiverInfo.city)); + const hasEnoughData = !enableExternalExpressCode + && (shopNick || (receiverInfo && (receiverInfo.province || receiverInfo.city))); if (hasEnoughData) { const address = [ @@ -1422,6 +1483,17 @@ class DeliveryOrderService extends Service { gross_weight: 0, }; } + + // 手工单直接传仓库 stock_id:校验库存记录归属当前货主,禁止跨货主下单 + const stockWarehouseRecord = await app.model.StockWarehouse.findByPk(line.stockId, { + attributes: [ 'id', 'store_id' ], + transaction, + raw: true, + }); + if (stockWarehouseRecord && Number(stockWarehouseRecord.store_id) !== Number(storeId)) { + errors.push(`商品《${line.itemName}》编码《${line.itemCode}》\n库存归属货主(store_id=${stockWarehouseRecord.store_id})与当前货主(store_id=${storeId})不一致,无法创建订单`); + continue; + } } else if (!line.itemId) { // 查找唯一键(appKey 为空时不作为条件,兼容内部手动建单场景) const stockWhere = { From 7f562bf1e72298b42a0a8dd61b02348704839022 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Fri, 21 Aug 2026 02:20:40 +0800 Subject: [PATCH 245/550] =?UTF-8?q?feat(storage):=20=E5=8F=96=E6=B6=88?= =?UTF-8?q?=E5=88=86=E9=85=8D=E5=82=A8=E4=BD=8D=E5=B7=B2=E6=8B=A3=E8=B4=A7?= =?UTF-8?q?=E8=AE=B0=E5=BD=95=E8=BF=94=E8=BF=98=E5=BA=93=E5=AD=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 按拣货记录状态分流: pending 仅解除锁定, fin 返还实物数量 - 已拣货返还写 INBOUND 流水(order_type=PICK_RETURN)并返回 storage_return_summary --- .../systems/order_storage_allocation.js | 66 ++++++++++++++++++- 1 file changed, 63 insertions(+), 3 deletions(-) diff --git a/app/service/systems/order_storage_allocation.js b/app/service/systems/order_storage_allocation.js index 7d3473f..ce26e4d 100644 --- a/app/service/systems/order_storage_allocation.js +++ b/app/service/systems/order_storage_allocation.js @@ -2228,6 +2228,7 @@ class OrderStorageAllocationService extends MainService { orders: skippedOrders, picking_count: 0, storage_unlock_summary: [], + storage_return_summary: [], stock_unlock_summary: [], }, }; @@ -2249,7 +2250,8 @@ class OrderStorageAllocationService extends MainService { }); const pickingRowsByOrderId = new Map(); - const storageQuantityMap = new Map(); + const pendingStorageQuantityMap = new Map(); + const finStorageQuantityMap = new Map(); const storageIdSet = new Set(); for (const pickingRow of Array.isArray(pickingRows) ? pickingRows : []) { @@ -2267,7 +2269,14 @@ class OrderStorageAllocationService extends MainService { pickingRowsByOrderId.set(orderId, orderPickingRows); storageIdSet.add(storageId); - storageQuantityMap.set(storageId, (storageQuantityMap.get(storageId) || 0) + quantity); + // 按状态分流:pending 记录解除锁定(实物不动); + // fin 记录(已拣货)返还实物数量,锁定已在拣货完成时扣减,不再重复扣除 + const pickingStatus = String(plainPicking?.status || '').trim(); + if (pickingStatus === 'fin') { + finStorageQuantityMap.set(storageId, (finStorageQuantityMap.get(storageId) || 0) + quantity); + } else { + pendingStorageQuantityMap.set(storageId, (pendingStorageQuantityMap.get(storageId) || 0) + quantity); + } } const cancellableOrderIds = []; @@ -2298,6 +2307,7 @@ class OrderStorageAllocationService extends MainService { orders: skippedOrders, picking_count: 0, storage_unlock_summary: [], + storage_return_summary: [], stock_unlock_summary: [], }, }; @@ -2326,8 +2336,10 @@ class OrderStorageAllocationService extends MainService { } const storageUnlockSummary = []; + const storageReturnSummary = []; - for (const [ storageId, quantity ] of storageQuantityMap.entries()) { + // pending 记录:解除锁定,实物库存不动 + for (const [ storageId, quantity ] of pendingStorageQuantityMap.entries()) { if (quantity <= 0) { continue; } @@ -2372,6 +2384,53 @@ class OrderStorageAllocationService extends MainService { }); } + // fin 记录(已拣货):返还实物数量,锁定已在拣货完成时扣减,不再重复扣除 + for (const [ storageId, returnQuantity ] of finStorageQuantityMap.entries()) { + if (returnQuantity <= 0) { + continue; + } + + const storageRow = storageMap.get(storageId); + if (!storageRow) { + throw new Error(`库存记录不存在: ${storageId}`); + } + + const beforeQuantity = toNumber(storageRow.quantity, 0); + const beforeLockedQuantity = toNumber(storageRow.locked_quantity, 0); + + await ctx.service.systems.storage.index.updateQuantity(storageId, returnQuantity, 0, { + transaction, + }); + + // 写入库存返还流水(实物数量增加,锁定不变) + await ctx.model.StorageTransaction.create({ + transaction_type: 'INBOUND', + warehouse_id: warehouseId, + store_id: storageRow.store_id, + stock_id: storageRow.stock_id, + storage_id: storageId, + space_id: storageRow.space_id, + quantity: returnQuantity, + before_quantity: beforeQuantity, + after_quantity: beforeQuantity + returnQuantity, + before_locked_quantity: beforeLockedQuantity, + after_locked_quantity: beforeLockedQuantity, + batch_no: storageRow.batch_no, + inventory_type: storageRow.inventory_type, + order_type: 'PICK_RETURN', + order_no: 'CANCEL_BATCH', + order_id: 0, + operator_id: String(ctx.user?.employees_id ?? ctx.user?.id ?? ''), + operator_name: ctx.user?.employees_name ?? ctx.user?.real_name ?? ctx.user?.name ?? '', + remark: '取消分配储位(已拣货返还库存)', + }, { transaction }); + + storageReturnSummary.push({ + storage_id: storageId, + returned_quantity: returnQuantity, + }); + } + const cancelPickingIds = []; for (const orderId of cancellableOrderIds) { const orderPickingRows = pickingRowsByOrderId.get(orderId) || []; @@ -2439,6 +2498,7 @@ class OrderStorageAllocationService extends MainService { orders: [ ...skippedOrders, ...orderResults ], picking_count: cancelPickingIds.length, storage_unlock_summary: storageUnlockSummary, + storage_return_summary: storageReturnSummary, stock_unlock_summary: [], }; From fe97adfda29970eb2984b3cf696cfc23b307b1bf Mon Sep 17 00:00:00 2001 From: liufumingren Date: Fri, 21 Aug 2026 02:20:43 +0800 Subject: [PATCH 246/550] =?UTF-8?q?feat(space):=20=E6=89=B9=E9=87=8F?= =?UTF-8?q?=E5=BA=93=E4=BD=8D=E6=90=9C=E7=B4=A2=20searchSpaces?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - space.js 抽取 _searchByKeyword, searchSpace 与 searchSpaces 共用同一查询口径 - searchSpaces 按 keywords 并行查询并保持传入顺序, 无记录项返回空数组 - index.searchSpaces 加入免权限/免鉴权白名单 --- app/service/systemMethods/index.js | 9 ++++++-- app/service/systems/space.js | 34 +++++++++++++++++++++++++++--- 2 files changed, 38 insertions(+), 5 deletions(-) diff --git a/app/service/systemMethods/index.js b/app/service/systemMethods/index.js index de7eb76..4d4a4e5 100644 --- a/app/service/systemMethods/index.js +++ b/app/service/systemMethods/index.js @@ -1053,9 +1053,9 @@ class indexService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = 'getI18nMessage,putI18nCollect,test,getCainiaoStfTemplates,polyapiAuthorizeUrl'; - const _noNeedRight = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,loadWarehouses,loadExpressInterfaces,getImages,getCOSUploadConfig,uploadSuccessNotify,getMessageDetail,searchSpace,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,getPlatformOauthLink,listenPlatformOauthBind,recognizeLicensePlate,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl,toOrder'; + const _noNeedRight = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,loadWarehouses,loadExpressInterfaces,getImages,getCOSUploadConfig,uploadSuccessNotify,getMessageDetail,searchSpace,searchSpaces,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,getPlatformOauthLink,listenPlatformOauthBind,recognizeLicensePlate,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl,toOrder'; const _noNeedLog = '*'; - const _noNeedAuth = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,loadWarehouses,loadExpressInterfaces,getImages,getMessageDetail,searchSpace,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,getPlatformOauthLink,listenPlatformOauthBind,recognizeLicensePlate,test,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl,toOrder'; + const _noNeedAuth = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,loadWarehouses,loadExpressInterfaces,getImages,getMessageDetail,searchSpace,searchSpaces,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,getPlatformOauthLink,listenPlatformOauthBind,recognizeLicensePlate,test,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl,toOrder'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } async fastWhereTree(data) { @@ -1578,6 +1578,11 @@ class indexService extends MainService { const result = await service.systems.space.searchSpace(data); return this.success('ok', result); } + async searchSpaces(data) { + const { service } = this; + const result = await service.systems.space.searchSpaces(data); + return this.success('ok', result); + } async listInterfaceTypes() { const { ctx } = this; const rows = await ctx.model.InterfaceType.findAll({ diff --git a/app/service/systems/space.js b/app/service/systems/space.js index 019a915..86d492e 100644 --- a/app/service/systems/space.js +++ b/app/service/systems/space.js @@ -2,9 +2,14 @@ const Service = require('egg').Service; class spaceService extends Service { - async searchSpace(data) { + /** + * 按关键字查询库位(单个关键字)。 + * + * @param {string} [keyword] 搜索关键字,为空时返回当前仓库下前 50 条。 + * @return {Promise} 库位列表(最多 50 条)。 + */ + async _searchByKeyword(keyword) { const { ctx, app } = this; - const { keyword } = data; const warehouseId = ctx.user.store_id; // 构建基础查询条件:warehouse_id 为当前仓库或 null @@ -46,7 +51,7 @@ class spaceService extends Service { }; } - const results = await app.model.LocationSpace.findAll({ + return app.model.LocationSpace.findAll({ where: whereCondition, attributes: [ 'id', 'space_code', 'custom_barcode', 'custom_name', @@ -55,8 +60,31 @@ class spaceService extends Service { limit: 50, subQuery: false, }); + } + + async searchSpace(data) { + const { keyword } = data; + const results = await this._searchByKeyword(keyword); return { code: 200, data: results, total: results.length }; } + + /** + * 批量按关键字查询库位。 + * + * @param {Object} data 请求数据。 + * @param {Array} data.keywords 搜索关键字数组。 + * @return {Promise} data 为与 keywords 一一对应的库位列表数组, + * 无记录时对应项为空数组 []。 + */ + async searchSpaces(data) { + const { keywords } = data; + const keywordList = Array.isArray(keywords) ? keywords : []; + const resultList = await Promise.all( + keywordList.map(keyword => this._searchByKeyword(keyword)) + ); + + return { code: 200, data: resultList, total: resultList.length }; + } } module.exports = spaceService; From 145fc04022e83c009cfd845be321c197a6b0d878 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Fri, 21 Aug 2026 02:20:48 +0800 Subject: [PATCH 247/550] =?UTF-8?q?chore:=20=E7=A7=BB=E9=99=A4=E4=BB=93?= =?UTF-8?q?=E5=BA=93=20webhook=20=E9=85=8D=E7=BD=AE=E5=B9=B6=E5=90=8C?= =?UTF-8?q?=E6=AD=A5=E6=8E=A5=E5=8F=A3=E6=96=87=E6=A1=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 移除 subject_config.webhook_enabled/callback_strategy 配置与校验 - 修正 package-lock 项目名 oms -> wms - methods 文档同步 searchSpaces/领料/命中数口径/打印合并/手动单归属等变更记录 --- AI_METHOD_ROUTING.md | 8 +- app/model/store.js | 12 -- app/service/systems/setting/warehouse.js | 20 --- methods/changes/system.json | 160 ++++++++++++++++++ methods/system.json | 198 ++++++++++++++++++++++- package-lock.json | 4 +- 6 files changed, 357 insertions(+), 45 deletions(-) diff --git a/AI_METHOD_ROUTING.md b/AI_METHOD_ROUTING.md index afa7e3c..a3d6db6 100644 --- a/AI_METHOD_ROUTING.md +++ b/AI_METHOD_ROUTING.md @@ -153,8 +153,8 @@ rg "class .*Service|module.exports" app/service/qimenMethods - list - app/service/systemMethods/dashboard.js (6) - storeStats, warehouseStats, hot_order_rank, express_ratio, platform_distribution, order_trend -- app/service/systemMethods/index.js (13) - - fastWhereTree, loadStores, getCOSUploadConfig, getImages, uploadSuccessNotify, ReferenceFile, getMessageDetail, getI18nMessage, putI18nCollect, extractModule, tryAutoTranslateNewKeys, searchSpace, getExpressList +- app/service/systemMethods/index.js (14) + - fastWhereTree, loadStores, getCOSUploadConfig, getImages, uploadSuccessNotify, ReferenceFile, getMessageDetail, getI18nMessage, putI18nCollect, extractModule, tryAutoTranslateNewKeys, searchSpace, searchSpaces, getExpressList - app/service/systemMethods/order.js (11) - getWarehouseId, getOrderModels, applyDateRange, buildWhere, parseDateTime, list, detail, listItems, stats, updateStatus, updateDeliveryTime - app/service/systemMethods/print.js (3) @@ -215,8 +215,8 @@ rg "class .*Service|module.exports" app/service/qimenMethods - listTemplatesByType, getTree, getTemplatesByType, save, getBusinessTypesAndItem, getGroupedPrintItems, getTableConfigs, clearBusinessTypesCache, getXmlByTemplate, buildXmlFromElements, renderElement, computeItemStyle, computeTableItemStyle, renderTable - app/service/systems/sign.js (10) - Constants, toXml, signTopRequest, verifyTopRequest, verifyAndExtractParams, generateSignedParams, encryptHMAC, encryptHMACSHA256, encryptMD5, byte2hex -- app/service/systems/space.js (1) - - searchSpace +- app/service/systems/space.js (2) + - searchSpace, searchSpaces - app/service/systems/stock_store.js (34) - create, initQimenStockData, convertToQimenFormat, getItemInfoWithCache, getItemStorages, _calculateCacheTTL, clearItemStorageCache, lockItemStorages, ID, inbound, outbound, checkAndCreateWarehouseStock, getWarehouseStock, buildSequelizeCondition, processConditionValue, formatDate, isEmptyValue, getProhibitedType, getBarcodes, handleBatchChange, saveWarehouseStockBarcode, getStoreStocks, bindItem, unbindItem, getInfo, saveWarehouseStock, createWarehouseStock, validateSaveParams, stockLog, checkItemCodeUnique, handleBatchDelete, deleteUnit, deleteProhibited, search - app/service/systems/storage/index.js (1) diff --git a/app/model/store.js b/app/model/store.js index 783d3bc..c70cbfc 100644 --- a/app/model/store.js +++ b/app/model/store.js @@ -326,18 +326,6 @@ module.exports = app => { } } - if (Object.prototype.hasOwnProperty.call(parsed, 'webhook_enabled')) { - normalized.webhook_enabled = normalizeBooleanFlag(parsed.webhook_enabled, 'subject_config.webhook_enabled'); - } - - if (Object.prototype.hasOwnProperty.call(parsed, 'callback_strategy')) { - const strategy = String(parsed.callback_strategy || '').trim().toLowerCase(); - if (strategy && ![ 'sync', 'async' ].includes(strategy)) { - throw new Error('subject_config.callback_strategy 仅支持 sync 或 async'); - } - normalized.callback_strategy = strategy || 'async'; - } - normalized.inventory_warning_rules = normalizeInventoryWarningRules(parsed.inventory_warning_rules); normalized.auto_outbound_rules = normalizeAutoOutboundRules(parsed.auto_outbound_rules); diff --git a/app/service/systems/setting/warehouse.js b/app/service/systems/setting/warehouse.js index e9d804c..77a1856 100644 --- a/app/service/systems/setting/warehouse.js +++ b/app/service/systems/setting/warehouse.js @@ -189,26 +189,6 @@ const WAREHOUSE_SETTING_FIELDS = Object.freeze([ required: false, description: '可配置多个库存预警项,每项包含 name、key、expire_days、tip_text', }), - 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: '异步回调' }), - ], - }), Object.freeze({ key: 'auto_outbound_rules', name: '自动出库规则', diff --git a/methods/changes/system.json b/methods/changes/system.json index 92e3a32..f6d7c21 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,164 @@ [ + { + "version": "2026.08.21-index.searchSpaces-batch-search", + "date": "2026-08-21", + "type": "added", + "summary": "新增 index.searchSpaces 批量库位查询接口:keywords 传入字符串数组,逐项按当前仓库上下文模糊查询(space_code/custom_barcode/custom_name,每项最多 50 条),结果按传入顺序以二维数组返回,无记录对应项返回空数组。", + "methods": [ + "index.searchSpaces" + ], + "notes": [ + "app/service/systems/space.js 抽取 _searchByKeyword 私有查询方法(searchSpace 与 searchSpaces 共用同一查询口径),新增 searchSpaces 并行查询每个关键字并保持传入顺序输出,无记录项返回 []", + "app/service/systemMethods/index.js 新增 searchSpaces 出口方法,并加入 _noNeedRight/_noNeedAuth 白名单(与 searchSpace 一致,免鉴权免权限、需登录)", + "同步更新 methods/system.json 与 AI_METHOD_ROUTING.md" + ], + "module": "index" + }, + { + "version": "2026.08.20-order.wave.matched-count-same-express-split", + "date": "2026-08-20", + "type": "fixed", + "summary": "order.wave.waveStrategyList 的 matched_order_count_filtered 计数口径与按策略抓取保持一致:require_same_express=1 的策略按「结构(items_hash)+快递」分组计数并应用 min/max_same_structure,不再仅按结构分组统计,避免列表显示有命中订单但 waveStrategyFetchAdmin 实际抓取为 0 的口径不一致。", + "methods": [ + "order.wave.waveStrategyList" + ], + "notes": [ + "app/service/systemMethods/order/wave.js getWaveStrategyMatchedOrderCountFilteredMap 改为接收策略行数组并按 require_same_express 拆分两类计数查询:同快递策略按 items_hash+快递(sys_logistics_code>logistics_code>logistics_name COALESCE 口径)分组,其余仅按 items_hash 分组;max_same_structure<=0 视为不设上限,与抓取候选 SQL 归一化一致;调用方 waveStrategyList 改传当前页策略行 list", + "同步更新 methods/system.json 中 matched_order_count_filtered 字段描述" + ], + "module": "order" + }, + { + "version": "2026.08.20-pick.waveClaimScan-print-gate", + "date": "2026-08-20", + "type": "enhanced", + "summary": "pick.waveClaimScan 新增波次打印校验:整波领料前检查波次下全部订单 print_status,存在未打印订单(print_status != fin)时返回 400「波次未打印,禁止领料」(data 含 wave_id、wave_no、unprinted_order_count、total_order_count),波次全部打印后才允许将订单 claim_status 置为 fin;已全部领料幂等结果优先返回,不受打印校验拦截。", + "methods": [ + "pick.waveClaimScan" + ], + "notes": [ + "app/service/systemMethods/pick.js waveClaimScan 波次订单查询 attributes 增加 print_status,already_claimed 幂等判断之后插入打印校验:unprinted_order_count > 0 时 fail 400「波次未打印,禁止领料」", + "同步更新 methods/system.json 中 pick.waveClaimScan 的 description 与 400 错误说明" + ], + "module": "pick" + }, + { + "version": "2026.08.20-pick.waveClaimScan-source-gate", + "date": "2026-08-20", + "type": "enhanced", + "summary": "pick.waveClaimScan 整波领料资格判定收敛为仅普通波次(wms_wave_batch.source=0)生效:符合时将该波次下全部未领单订单 claim_status 置为 fin 并返回 wave_id/wave_no 与领单说明;策略抓取波次(source=1/2)返回「该波次为抓取波次,无需领料」(data 含 no_claim_needed=true、wave_id、wave_no);波次已全部领料返回 already_claimed 并提示「该波次已领料,无需重复领取」;面单号无记录/订单不在待处理订单表返回 404 无记录提示。", + "methods": [ + "pick.waveClaimScan" + ], + "notes": [ + "app/service/systemMethods/pick.js waveClaimScan 资格判定由(大团购 wave_type=1 且 pick_mode=5 / 非抓取散单 wave_type=2 且 source=0)改为仅按 source 判定:source=0 全部支持整波领料,source∈{1,2} 返回抓取波次无需领料并携带 no_claim_needed=true、wave_id、wave_no,其余返回不支持提示;already_claimed tip 改为「该波次已领料,无需重复领取」", + "app/dict/businessDict.js OPERATION_CODE 补记 ORDER_WAVE_CLAIM:'领取波次'", + "同步更新 methods/system.json 中 pick.waveClaimScan 的 description/400/404 错误说明" + ], + "module": "pick" + }, + { + "version": "2026.08.19-print-custom-area-stock-merge", + "date": "2026-08-19", + "type": "fixed", + "summary": "修复打印自定义区同库位不同商品被合并为一行的问题:拣货明细聚合键由「库位」改为「库位+stock_id」复合键,仅同一库位同一商品才合并数量;stock_id 缺失时依次回退 order_item_id、商品名称+条码,无法识别商品身份时不再跨行合并。", + "methods": [ + "order.print.getOrderPrintData", + "order.print.getWavePlatformPrintData", + "order.print.getPrintDataByWaybillCodes" + ], + "notes": [ + "app/service/systems/order_print.js buildPrintOrderRowMapWithPicking 阶段五聚合改为 buildPrintItemAggregationKey 复合键(pick_location::stock:stock_id),同库位不同商品保持独立行,数量/条码不再串;stock_id 字段延迟到聚合完成后才删除,避免污染 items JSON" + ], + "module": "order" + }, + { + "version": "2026.08.19-pick.claim-prompt-refine", + "date": "2026-08-19", + "type": "enhanced", + "summary": "领料提示文案细化:pick.query 领单前置校验拦截时直接提示「订单未领料,请先领料后再拣货」;pick.waveClaimScan 对抓取的波次(团购小波次 pick_mode=1、策略抓取散单波次 source=1/2)返回「该波次为抓取波次,无需领料」提示(失败 data 新增 no_claim_needed=true),其余未知类型保留通用不支持提示。", + "methods": [ + "pick.query", + "pick.waveClaimScan" + ], + "notes": [ + "app/service/systemMethods/pick.js query 领单前置校验拦截文案由「该波次尚未领单,请先整波领单后再拣货」改为「订单未领料,请先领料后再拣货」,action=wave_claim 等失败 data 字段不变", + "app/service/systemMethods/pick.js waveClaimScan 资格判定失败时细分提示:抓取波次(wave_type=2 且 source∈{1,2},或 wave_type=1 且 pick_mode=1)返回「该波次为抓取波次,无需领料」并携带 no_claim_needed=true;其他未知类型保留「当前波次类型不支持整波领单」", + "同步更新 methods/system.json 中 pick.query 与 pick.waveClaimScan 的 description/400 错误说明" + ], + "module": "pick" + }, + { + "version": "2026.08.19-pick.query-wave-claim-gate", + "date": "2026-08-19", + "type": "enhanced", + "summary": "pick.query 新增领单前置校验:扫描命中的波次属于大团购(pick_mode=5)或非抓取散单(wms_wave_batch.source=0 普通波次)时,若波次内存在未领单订单(claim_status != fin)则返回 400 并携带 action=wave_claim 提示先整波领单(pick.waveClaimScan),中止拣货任务创建;已全部领单则继续原流程。", + "methods": [ + "pick.query" + ], + "notes": [ + "app/service/systemMethods/pick.js query 在解析目标波次后、活动任务去重前插入领单校验:复用 getWavePickModeByWaveId 与 wms_wave_batch.source 判定波次类型(大团购=wave_type 1 且 pick_mode 5;非抓取散单=wave_type 2 且 source 0),查询波次订单 claim_status,存在未领单订单时 fail 400(data 含 action=wave_claim、wave_id、wave_no、wave_type、wave_source、pick_mode、unclaimed_order_count、total_order_count)", + "同步更新 methods/system.json 中 pick.query 的 description 与 400 错误说明" + ], + "module": "pick" + }, + { + "version": "2026.08.19-pick.waveClaimScan", + "date": "2026-08-19", + "type": "enhanced", + "summary": "新增 pick.waveClaimScan 整波领单接口:PDA 扫描波次内一个面单号后,针对大团购(pick_mode=5 团购大波次)与非抓取的散单(wms_wave_batch.source=0 普通波次)将该波次下全部订单 claim_status 置为 fin(领单完成),并写入 ORDER_WAVE_CLAIM 订单操作日志;团购小波次与策略抓取散单波次不支持整波领单,返回 400;波次已全部领单时返回 already_claimed 幂等结果。", + "methods": [ + "pick.waveClaimScan" + ], + "notes": [ + "app/service/systemMethods/pick.js 新增 waveClaimScan:面单号定位订单(wms_order_express.waybill_code)→ 订单定位波次 → 读取 wms_wave_batch(wave_type/source)与拣货任务 pick_mode 判定资格(大团购=wave_type 1 且 pick_mode 5;非抓取散单=wave_type 2 且 source 0)→ 整波订单 claim_status='fin',并新增 getWavePickModeByWaveId 查询关联拣货模式", + "app/service/systemMethods/pick.js 鉴权配置:waveClaimScan 加入 _noNeedRight/_noNeedAuth(免权限、免仓库有效期校验),保留登录校验与请求日志", + "app/dict/businessDict.js OPERATION_CODE 新增 ORDER_WAVE_CLAIM:'领取波次'", + "同步更新 methods/system.json 中 pick.waveClaimScan 接口文档" + ], + "module": "pick" + }, + { + "version": "2026.08.19-manual-order-stock-store-guard", + "date": "2026-08-19", + "type": "fixed", + "summary": "手工单(order.pendingOrder.createOrder)新增库存归属货主校验:item_id 直接传仓库 stock_id 时,校验 wms_stock_warehouse.store_id 与订单货主 store_id 一致,跨货主传库存将被拒绝,杜绝把其他货主库存挂在当前货主订单下。", + "methods": [ + "order.pendingOrder.createOrder" + ], + "notes": [ + "app/service/systems/delivery_order.js addOrderLines 手工单分支(line.stockId)新增 StockWarehouse 归属校验,不一致时计入 errors 并跳过该行,错误文案:商品《xxx》编码《xxx》库存归属货主(store_id=…)与当前货主(store_id=…)不一致,无法创建订单", + "同步更新 methods/system.json 中 order.pendingOrder.createOrder 的 notes 说明" + ], + "module": "order" + }, + { + "version": "2026.08.19-wave-fallback-excluded-reason-cn-label", + "date": "2026-08-19", + "type": "enhanced", + "summary": "order.wave.waveStrategyFallbackOrderList 响应 excluded_reason 由英文枚举值改为中文标签:locked→已锁定、intercepted→已拦截、printed→已打印、no_match→未匹配策略。", + "methods": [ + "order.wave.waveStrategyFallbackOrderList" + ], + "notes": [ + "app/service/systemMethods/order/wave.js 新增 WAVE_STRATEGY_FALLBACK_EXCLUDED_REASON_LABELS 常量并用于 buildWaveStrategyFallbackOrderListItem,判定优先级不变", + "同步更新 methods/system.json 中该接口 excluded_reason 字段与 list 说明" + ], + "module": "order" + }, + { + "version": "2026.08.19-wave-fallback-excluded-reason-lock-fix", + "date": "2026-08-19", + "type": "fixed", + "summary": "修复 order.wave.waveStrategyFallbackOrderList 所有行 excluded_reason 恒为 locked 的问题:列表行经 normalizeOrderListItem 后 lock_status 已归一化为 Y/N,原判断 lock_status !== 'none' 恒成立导致全部误标 locked;改为兼容归一化值(Y=锁定,N/none/空=未锁定)与原始值(warehouse/store 等),恢复 locked/intercepted/printed/no_match 的正确判定。", + "methods": [ + "order.wave.waveStrategyFallbackOrderList" + ], + "notes": [ + "app/service/systemMethods/order/wave.js buildWaveStrategyFallbackOrderListItem 新增 lockStatus 归一化与 isLocked 判定(Y 或非 none/非 N 的原始值视为锁定),excluded_reason 优先级不变:locked > intercepted > printed > no_match" + ], + "module": "order" + }, { "version": "2026.08.19-order-list-wave-index-range-filter", "date": "2026-08-19", diff --git a/methods/system.json b/methods/system.json index bc78520..5da4f63 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1,8 +1,8 @@ { "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", - "version": "0.3.29", - "updatedAt": "2026-08-18", + "version": "0.3.32", + "updatedAt": "2026-08-19", "headers": [ { "name": "platform", @@ -949,6 +949,79 @@ ], "errors": [] }, + { + "method": "index.searchSpaces", + "description": "按当前仓库上下文批量搜索库位(使用 ctx.user.store_id;对每个关键字在 location_space 表中按 space_code/custom_barcode/custom_name 做模糊匹配,结果按传入顺序返回)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "keywords", + "type": "array", + "required": true, + "source": "body", + "description": "搜索关键字数组,每项对 space_code、custom_barcode、custom_name 做模糊匹配(%keyword%);非数组视为空数组" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "description": "全局调用结果标识,成功时为 success" + }, + { + "name": "code", + "type": "number", + "description": "业务状态码,200 表示成功" + }, + { + "name": "message", + "type": "string", + "description": "返回信息" + }, + { + "name": "data", + "type": "array", + "description": "库位列表的数组,与 keywords 一一对应;每项为库位数组(最多 50 条),无记录时对应项为空数组 []", + "children": [ + { + "name": "id", + "type": "number", + "description": "库位 ID" + }, + { + "name": "space_code", + "type": "string", + "description": "库位编码" + }, + { + "name": "custom_barcode", + "type": "string", + "description": "库位自定义条码" + }, + { + "name": "custom_name", + "type": "string", + "description": "库位自定义名称" + } + ] + }, + { + "name": "total", + "type": "number", + "description": "返回的分组数量(等于 keywords.length)" + } + ], + "errors": [] + }, { "method": "index.listInterfaceTypes", "description": "查询可用的接口类型列表(如奇门仓储、开放接口等)", @@ -4174,6 +4247,7 @@ ], "notes": [ "使用 item_id 直接匹配商品主键,不依赖外部系统商品同步;item_id 可通过 singleitem.synchronize 返回的 itemId 获取", + "手工单 item_id 即仓库 stock_id(wms_stock_warehouse.id),系统会校验该库存记录归属货主与 store_id 一致,跨货主传库存将被拒绝(商品《xxx》库存归属货主与当前货主不一致)", "province/city/area 为必填项,空值返回 400" ] }, @@ -7263,7 +7337,7 @@ { "name": "matched_order_count_filtered", "type": "number", - "description": "按当前仓库且仅统计未在波次(step!=0)并满足同结构区间后的命中订单数" + "description": "按当前仓库且仅统计未在波次(step!=0)并满足同结构区间后的命中订单数;口径与抓取候选一致:require_same_express=1 时按「结构+快递」分组计数,否则仅按结构分组计数" }, { "name": "next_fetch_order_count", @@ -8455,7 +8529,7 @@ "name": "list", "type": "array", "required": true, - "description": "回退候选订单简要列表。数组内对象字段说明见 children;每行含 excluded_reason 标记:locked=订单已锁定(lock_status 非 none)、intercepted=订单已拦截、printed=已完全打印、no_match=未匹配任何波次策略。", + "description": "回退候选订单简要列表。数组内对象字段说明见 children;每行含 excluded_reason 中文标记:已锁定(lock_status 非 none)、已拦截、已打印、未匹配策略。", "children": [ { "name": "id", @@ -8525,7 +8599,7 @@ { "name": "excluded_reason", "type": "string", - "description": "订单进入回退列表的原因枚举:locked(已锁定,lock_status 非 none)/ intercepted(已拦截)/ printed(已完全打印)/ no_match(未匹配任何波次策略)" + "description": "订单进入回退列表的原因(中文标签):已锁定(lock_status 非 none)/ 已拦截 / 已打印 / 未匹配策略" } ] }, @@ -18614,7 +18688,7 @@ "list": [ { "method": "pick.query", - "description": "按 keyword(运单号或波次号)获取或创建当前用户的拣货任务:命中同用户活动任务返回 existing;无活动任务则创建并返回 created;若活动任务归属他人则返回冲突提示。", + "description": "按 keyword(运单号或波次号)获取或创建当前用户的拣货任务:命中同用户活动任务返回 existing;无活动任务则创建并返回 created;若活动任务归属他人则返回冲突提示。新增领单前置校验:扫描命中的波次属于大团购(pick_mode=5)或非抓取散单(wms_wave_batch.source=0 普通波次)时,若波次内存在未领料订单(claim_status != fin)则返回 400 并携带 action=wave_claim 提示「订单未领料,请先领料后再拣货」(pick.waveClaimScan),中止拣货任务创建。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -18657,7 +18731,7 @@ "errors": [ { "code": 400, - "message": "参数错误或目标波次不满足建任务条件(如 keyword 为空、缺少仓库上下文、目标波次信息不完整、散单波次无可用订单)。" + "message": "参数错误或目标波次不满足建任务条件(如 keyword 为空、缺少仓库上下文、目标波次信息不完整、散单波次无可用订单);大团购/非抓取散单波次未领料时中止建任务并提示「订单未领料,请先领料后再拣货」(失败 data 含 action=wave_claim、wave_id、wave_no、wave_type、wave_source、pick_mode、unclaimed_order_count、total_order_count)。" }, { "code": 401, @@ -19477,6 +19551,116 @@ "message": "提交失败。" } ] + }, + { + "method": "pick.waveClaimScan", + "description": "扫描面单号领取整波(领料)。按面单号(运单号)定位待处理订单表中的订单后反查订单所在波次,仅对普通波次(wms_wave_batch.source=0,含团购/散单)支持整波领料:命中后将该波次下全部未领单订单 claim_status 置为 fin(领料完成)并写入 ORDER_WAVE_CLAIM 订单操作日志,返回波次ID与波次编码;波次下存在未打印订单(print_status != fin)时返回 400「波次未打印,禁止领料」(data 含 wave_id、wave_no、unprinted_order_count);策略抓取波次(source=1/2)无需领料,返回 400 并提示「该波次为抓取波次,无需领料」(失败 data 含 no_claim_needed=true、wave_id、wave_no);面单号查不到订单或订单不在待处理订单表返回 404 提示无记录;波次内订单已全部领料时返回 already_claimed 幂等结果并提示已领料。", + "isNeedAuth": false, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "waybill_no", + "type": "string", + "required": true, + "source": "body", + "description": "面单号(运单号,wms_order_express.waybill_code)" + } + ], + "response": [ + { + "name": "wave_id", + "type": "number", + "required": true, + "description": "波次ID" + }, + { + "name": "wave_no", + "type": "string", + "required": true, + "description": "波次号" + }, + { + "name": "wave_type", + "type": "number", + "required": true, + "description": "波次类型:1-团购 2-散单" + }, + { + "name": "wave_source", + "type": "number", + "required": true, + "description": "波次来源:0-普通波次 1-管理后台策略任务 2-PDA策略任务" + }, + { + "name": "pick_mode", + "type": "number", + "required": true, + "description": "拣货模式:1-团购小波次 2-散单单品单件 3-散单先拣后分 4-边拣边分 5-团购大波次(0 表示无关联拣货任务)" + }, + { + "name": "matched_order_id", + "type": "number", + "required": true, + "description": "面单号命中的订单ID" + }, + { + "name": "waybill_no", + "type": "string", + "required": true, + "description": "扫描的面单号" + }, + { + "name": "total_order_count", + "type": "number", + "required": true, + "description": "波次下订单总数" + }, + { + "name": "claimed_order_count", + "type": "number", + "required": true, + "description": "本次置为 fin 的订单数(已全部领料时返回 0)" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "操作结果:claimed(整波领料完成)或 already_claimed(波次已领料)" + }, + { + "name": "tip", + "type": "string", + "required": true, + "description": "提示文案" + } + ], + "errors": [ + { + "code": 400, + "message": "参数错误(waybill_no 为空、缺少仓库上下文、订单未分配波次、波次下无可用订单);波次下存在未打印订单返回「波次未打印,禁止领料」(data 含 wave_id、wave_no、unprinted_order_count);策略抓取波次(source=1/2)返回「该波次为抓取波次,无需领料」(data 含 no_claim_needed=true、wave_id、wave_no);其余不支持类型返回通用提示。" + }, + { + "code": 401, + "message": "未获取到操作人上下文。" + }, + { + "code": 404, + "message": "未查询到该面单号对应的订单(无记录)、订单不在待处理订单表(无记录),或波次不存在/不属于当前仓库。" + }, + { + "code": 500, + "message": "运单模型/订单模型不可用或内部错误。" + } + ] } ] }, diff --git a/package-lock.json b/package-lock.json index b51cb5b..622d6d7 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,11 +1,11 @@ { - "name": "oms", + "name": "wms", "version": "1.0.0", "lockfileVersion": 3, "requires": true, "packages": { "": { - "name": "oms", + "name": "wms", "version": "1.0.0", "license": "MIT", "dependencies": { From bb676f941e7dd840fd5c5d4d7ced07896eb88736 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Fri, 21 Aug 2026 22:55:01 +0800 Subject: [PATCH 248/550] =?UTF-8?q?fix(pendingOrder):=20=E4=BF=AE=E6=94=B9?= =?UTF-8?q?=E8=AE=A2=E5=8D=95=E5=B9=B3=E5=8F=B0=E8=A1=A5=E5=85=85=E9=80=90?= =?UTF-8?q?=E5=8D=95=E8=AE=A2=E5=8D=95=E6=97=A5=E5=BF=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - updateOrderPlatform 更新前查询候选订单并筛出平台实际变化的订单 - 为每个受影响订单写入 business_id=订单ID 的 ORDER_UPDATE_PLATFORM 订单日志 - 保留原仓库级操作日志,逐单日志写入失败仅告警不影响业务 --- .../systemMethods/order/pendingOrder.js | 79 +++++++++++++++++-- 1 file changed, 73 insertions(+), 6 deletions(-) diff --git a/app/service/systemMethods/order/pendingOrder.js b/app/service/systemMethods/order/pendingOrder.js index ea2c0d4..790d9dc 100644 --- a/app/service/systemMethods/order/pendingOrder.js +++ b/app/service/systemMethods/order/pendingOrder.js @@ -2816,9 +2816,22 @@ class PendingOrderService extends OrderBaseService { post_status: 'none', }; + const platformName = String(platform.name || '').trim(); + + // 更新前查询候选订单,筛出平台实际发生变化的订单,用于逐单写入订单日志 + const candidateOrders = await model.findAll({ + where, + attributes: [ 'id', 'sys_platform_code', 'sys_platform_name' ], + raw: true, + }); + + const changedOrders = Array.isArray(candidateOrders) + ? candidateOrders.filter(order => String(order.sys_platform_code || '').trim() !== String(platform.code || '').trim()) + : []; + const [ affectedRows ] = await model.update({ sys_platform_code: platform.code, - sys_platform_name: String(platform.name || '').trim(), + sys_platform_name: platformName, updated_at: new Date(), }, { where }); @@ -2835,9 +2848,9 @@ class PendingOrderService extends OrderBaseService { warehouseId: logWarehouseId, orderIds, sys_platform_code: platform.code, - sys_platform_name: String(platform.name || '').trim(), + sys_platform_name: platformName, updated_count: count, - message: `批量修改订单平台:订单ID [${orderIds.join(', ')}],平台 ${platform.code}(${String(platform.name || '').trim()}),共更新 ${count} 条`, + message: `批量修改订单平台:订单ID [${orderIds.join(', ')}],平台 ${platform.code}(${platformName}),共更新 ${count} 条`, }, beforeChanges: null, }); @@ -2845,6 +2858,39 @@ class PendingOrderService extends OrderBaseService { this.ctx.logger.warn('[PendingOrderService.updateOrderPlatform] 写入操作日志失败,不影响业务', logErr); } + // 为实际发生平台变化的订单逐单写入订单日志(订单详情页可见) + try { + const opLogService = this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.operationLog; + if (opLogService && typeof opLogService.createOperationLogs === 'function' && changedOrders.length > 0) { + const logPayloads = changedOrders + .map(order => { + const orderId = Number(order.id); + if (!Number.isInteger(orderId) || orderId <= 0) { + return null; + } + const originalName = String(order.sys_platform_name || order.sys_platform_code || '未知').trim(); + return { + businessType: 'order', + businessId: String(orderId), + operationCode: 'ORDER_UPDATE_PLATFORM', + operator, + extras: { + warehouseId: logWarehouseId, + message: `修改订单平台:${originalName} → ${platform.code}(${platformName})`, + externalLogType: 'NONE', + }, + }; + }) + .filter(Boolean); + + if (logPayloads.length > 0) { + await opLogService.createOperationLogs(logPayloads); + } + } + } catch (logErr) { + this.ctx.logger.warn('[PendingOrderService.updateOrderPlatform] 写入订单日志失败,不影响业务', logErr); + } + return this.success('ok', { updated_count: count, sys_platform_code: platform.code, @@ -3150,6 +3196,8 @@ class PendingOrderService extends OrderBaseService { * 2. 若原订单已分配储位(storage_status='fin'),先清除已分配库存; * 3. 取消原订单(step->9, status->'cancel')并记录"克隆"日志; * 4. 以原订单业务数据创建新订单,所有流程状态字段重置为初始落库状态; + * 同步状态继承原订单:原订单已同步(sync_status=fin)则新订单直接置 fin 避免重复回传, + * 否则重置为 padding 重新走同步; * 5. 对新订单记录"克隆创建"日志。 * * @param {Object} data 请求体。 @@ -3181,14 +3229,20 @@ class PendingOrderService extends OrderBaseService { throw new Error('订单当前状态不允许克隆'); } - // 2. 若已分配储位,先清除库存 + // 2. 若已分配储位,先清除库存。 + // 已同步订单同样允许克隆;库存释放失败不阻断克隆(与 cancelOrder 降级策略一致), + // 原订单残留占用保留在原订单名下,克隆新订单不重新占用库存 + // (新订单 storage_status 重置为 none,创建过程不触发储位分配与库存锁定)。 if (String(original.storage_status || '').trim() === 'fin') { try { await this.service.systems.orderStorageAllocation.cancelAllocateStorage({ order_ids: [ orderId ], }); } catch (storageErr) { - throw new Error(`清除已分配库存失败:${storageErr.message}`); + this.ctx.logger.warn( + `[PendingOrderService.cloneOrder] 清除已分配库存失败,不影响克隆,orderId=${orderId}`, + storageErr + ); } } @@ -3271,8 +3325,11 @@ class PendingOrderService extends OrderBaseService { }; // 业务字段白名单(从原订单复制) + // 注意:不含 delivery_order_code —— 该字段受 (delivery_order_code, store_id, warehouse_id) + // 唯一索引约束,且原订单取消后仍留在 current 表占用索引,复制原单号会触发唯一键冲突 + // (Sequelize UniqueConstraintError,对外表现为 "Validation error")。新单号见下方生成逻辑。 const COPY_FIELDS = [ - 'delivery_order_code', 'pre_delivery_order_code', 'pre_delivery_order_id', + 'pre_delivery_order_code', 'pre_delivery_order_id', 'order_type', 'warehouse_code', 'warehouse_id', 'store_id', 'from_key', 'source_platform_code', 'source_platform_name', 'source_order_codes', 'sys_platform_code', 'sys_platform_name', @@ -3289,11 +3346,21 @@ class PendingOrderService extends OrderBaseService { ]; const newOrderData = { ...RESET_FIELDS }; + // 克隆单生成全新发货单号(与手工单 createOrder 相同的生成规则) + newOrderData.delivery_order_code = `SYS${Date.now()}${Math.floor(Math.random() * 9000) + 1000}`; + // 同步状态继承:原订单已同步(sync_status=fin)则新订单直接置 fin,避免重复回传平台; + // 未同步/同步失败(padding/error)重置为 padding 重新走同步流程 + newOrderData.sync_status = String(original.sync_status || '').trim() === 'fin' ? 'fin' : 'padding'; for (const field of COPY_FIELDS) { if (original[field] !== undefined) { newOrderData[field] = original[field]; } } + // 克隆追溯链:原订单无前置单号时,把原单号写入新订单 pre_delivery_order_code + const originalDeliveryCode = String(original.delivery_order_code || '').trim(); + if (originalDeliveryCode && !String(newOrderData.pre_delivery_order_code || '').trim()) { + newOrderData.pre_delivery_order_code = originalDeliveryCode; + } // 克隆单同样由仓库序列表统一发号;发号失败直接抛错,不回退分表自增, // 避免分表自增与序列表发号区间重叠产生冲突 id From 9894e15ccdc45a4d43b26e91f8d05625b6163bd0 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Fri, 21 Aug 2026 22:56:01 +0800 Subject: [PATCH 249/550] =?UTF-8?q?fix(express-policy):=20=E8=BF=9D?= =?UTF-8?q?=E7=A6=81=E5=93=81=E7=AD=96=E7=95=A5=E6=97=A0=E6=B3=95=E5=91=BD?= =?UTF-8?q?=E4=B8=AD=E2=80=94=E2=80=94=E8=AE=A2=E5=8D=95=E5=88=9B=E5=BB=BA?= =?UTF-8?q?=E6=97=B6=E8=81=9A=E5=90=88=E5=95=86=E5=93=81=E8=BF=9D=E7=A6=81?= =?UTF-8?q?=E5=93=81=E7=B1=BB=E5=9E=8B=E5=8F=82=E4=B8=8E=E5=8C=B9=E9=85=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - addOrderLines 批量查询 StockWarehouse 增加 prohibited_id 字段并聚合去重 - itemsInfo 返回 prohibited_type_ids,matchPolicy 由写死 null 改为传入真实值 - 修复限定违禁品类型的快递策略此前永远被跳过、订单降级默认快递的问题 --- app/service/systems/delivery_order.js | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/app/service/systems/delivery_order.js b/app/service/systems/delivery_order.js index a893e93..7d1110f 100644 --- a/app/service/systems/delivery_order.js +++ b/app/service/systems/delivery_order.js @@ -830,7 +830,10 @@ class DeliveryOrderService extends Service { customShopName: shopNick || '', address: address || '', weight: itemsInfo.total_weight || null, - prohibitedTypeIds: null, // TODO: 后续从商品 StockWarehouse.prohibited_id 聚合 + // 从订单商品聚合的违禁品类型ID(StockWarehouse.prohibited_id 去重) + prohibitedTypeIds: itemsInfo && Array.isArray(itemsInfo.prohibited_type_ids) + ? itemsInfo.prohibited_type_ids + : null, } ); @@ -1345,7 +1348,7 @@ class DeliveryOrderService extends Service { enableExternalExpressCode, }, operationLogs); const resolvedOperatorName = await this.resolveOperatorName(operatorName, createChannel, info); - + const fromKey = this.normalizeOrderFromKey(info.appKey); return { delivery_order_code: deliveryOrderCode, pre_delivery_order_code: preDeliveryOrderCode || '', @@ -1405,7 +1408,7 @@ class DeliveryOrderService extends Service { extend_props: requestExtendProps || null, store_id: info.storeId, warehouse_id: info.warehouseId, - from_key: this.normalizeOrderFromKey(info.appKey), + from_key: fromKey, }; } @@ -1547,13 +1550,14 @@ class DeliveryOrderService extends Service { // ===== Sort: 按 stockId 升序排序,保证所有事务加锁顺序一致,从根本上消除死锁 ===== resolvedItems.sort((a, b) => a.stockId - b.stockId); - // ===== 批量查询 wms_stock_warehouse 获取仓库侧称重毛重 ===== + // ===== 批量查询 wms_stock_warehouse 获取仓库侧称重毛重 & 违禁品类型 ===== const stockIds = [ ...new Set(resolvedItems.map(item => item.stockId).filter(Boolean)) ]; const warehouseWeightMap = new Map(); + const stockProhibitedMap = new Map(); // stock_id -> 违禁品类型ID if (stockIds.length > 0) { const warehouseRecords = await app.model.StockWarehouse.findAll({ where: { id: stockIds }, - attributes: [ 'id', 'gross_weight' ], + attributes: [ 'id', 'gross_weight', 'prohibited_id' ], transaction, raw: true, }); @@ -1562,6 +1566,10 @@ class DeliveryOrderService extends Service { if (gw > 0) { warehouseWeightMap.set(record.id, gw); } + const prohibitedId = Number(record.prohibited_id) || 0; + if (prohibitedId > 0) { + stockProhibitedMap.set(record.id, prohibitedId); + } } } @@ -1705,6 +1713,7 @@ class DeliveryOrderService extends Service { stock_quantity_map: Object.fromEntries(stockQuantityMap), // stock_id -> 数量 stock_weight_map: Object.fromEntries(stockWeightMap), // stock_id -> 单件重量 line_data: lineData, // 创建的明细数据 + prohibited_type_ids: [ ...new Set(stockProhibitedMap.values()) ], // 违禁品类型ID去重数组(快递策略匹配用) stats: { // 统计信息汇总 unique_items: stock_count, total_items: item_total_count, From f1a487bb06f78791f6e36c63799c131ae3b428e6 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Fri, 21 Aug 2026 23:03:04 +0800 Subject: [PATCH 250/550] =?UTF-8?q?feat(returnUnpack):=20=E5=8E=9F?= =?UTF-8?q?=E5=8D=95=20items=20=E9=A1=B6=E5=B1=82=E9=80=8F=E5=87=BA?= =?UTF-8?q?=E4=B8=8E=E8=AE=A2=E5=8D=95=E5=BA=8F=E5=88=97=E8=A1=A8=E8=BD=A6?= =?UTF-8?q?=E9=81=93=E5=AE=9A=E4=BD=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - create 新增顶层 order_items 字段(原订单商品明细,order.items 顶层透出),新建/幂等复用分支返回结构一致,非原单退回为 null - 原订单详情解析优先按订单 id 序列表(wms_order_id_location_{warehouseId})定位车道(current/history/dispatch/outsourced)直接查分表,未命中再遍历四车道、最后回退基表;修复订单位于 history/dispatch 车道时 create/detail 返回 order=null、order_items=null - _resolveReturnOrderInfo 原订单兜底查询同步改造(查退回交易单号/快递信息) - 同步 methods/system.json 与 methods/changes/system.json 变更记录 --- app/service/systems/afterSale.js | 191 ++++++++++++++++++--------- app/service/systems/return_unpack.js | 64 ++++++--- methods/changes/system.json | 33 +++++ methods/system.json | 8 +- 4 files changed, 214 insertions(+), 82 deletions(-) diff --git a/app/service/systems/afterSale.js b/app/service/systems/afterSale.js index 3698b81..dd586fc 100644 --- a/app/service/systems/afterSale.js +++ b/app/service/systems/afterSale.js @@ -416,28 +416,65 @@ class AfterSaleService extends Service { const { ctx, app } = this; try { - // 1. 查询订单主记录(优先主表,再尝试工厂分表) + // 1. 查询订单主记录:优先按订单 id 序列表(wms_order_id_location_{warehouseId}) + // 定位订单所在车道直接查对应分表,未命中再按 current → history → dispatch → outsourced + // 遍历回退,最后回退基表(存量订单) let order = null; - try { - order = await ctx.model.OrderDelivery.findOne({ - where: { id: orderDeliveryId }, - raw: true, - }); - } catch (err) { - ctx.logger.warn(`[_resolveOrderDetail] 主表查询失败: ${err.message}`); - } + let preferredLane = null; + const factory = ctx.model.OrderDeliveryFactory; - if (!order && ctx.model.OrderDeliveryFactory) { + if (factory && typeof factory.getCurrentModel === 'function') { + const laneLabels = [ 'current', 'history', 'dispatch', 'outsourced' ]; + const laneGetters = { + current: () => factory.getCurrentModel(warehouseId), + history: () => factory.getHistoryModel(warehouseId), + dispatch: () => factory.getDispatchModel(warehouseId), + outsourced: () => factory.getOutsourcedModel(warehouseId), + }; + + // 序列表定位优先:命中车道先查对应分表 try { - const factoryModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); - if (factoryModel) { - order = await factoryModel.findOne({ + if (typeof factory.getOrderLocation === 'function') { + const location = await factory.getOrderLocation(orderDeliveryId, warehouseId); + if (location && laneGetters[location]) { + preferredLane = String(location); + } + } + } catch (err) { + ctx.logger.warn(`[_resolveOrderDetail] 序列表定位失败: ${err.message}`); + } + + const orderedLanes = preferredLane + ? [ preferredLane, ...laneLabels.filter(label => label !== preferredLane) ] + : laneLabels; + + for (const lane of orderedLanes) { + try { + const model = await laneGetters[lane](); + if (!model || typeof model.findOne !== 'function') continue; + const row = await model.findOne({ where: { id: orderDeliveryId }, raw: true, }); + if (row) { + order = row; + break; + } + } catch (err) { + ctx.logger.warn(`[_resolveOrderDetail] 分表 ${lane} 查询失败: ${err.message}`); } + } + } + + // 分表均未命中:回退基表(存量订单) + if (!order) { + try { + order = await ctx.model.OrderDelivery.findOne({ + where: { id: orderDeliveryId }, + raw: true, + }); } catch (err) { - ctx.logger.warn(`[_resolveOrderDetail] 工厂模型查询失败: ${err.message}`); + ctx.logger.warn(`[_resolveOrderDetail] 主表查询失败: ${err.message}`); } } @@ -503,64 +540,86 @@ class AfterSaleService extends Service { } } - // 回退:若 items 为空且 OrderItemsFactory 可用,从分表查询 + // 回退:若 items 为空且 OrderItemsFactory 可用,从分表查询(序列表定位车道优先) if (orderItems.length === 0 && ctx.model.OrderItemsFactory) { try { - const itemsModel = await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId); - if (itemsModel) { - const dbItems = await itemsModel.findAll({ - where: { order_id: orderDeliveryId }, - raw: true, - }); - if (dbItems && dbItems.length > 0) { - // 收集 stock_id 用于批量查库存详情 - const stockIds = dbItems - .map(item => Number(item.stock_id)) - .filter(id => Number.isInteger(id) && id > 0); + const itemsFactory = ctx.model.OrderItemsFactory; + const itemsLaneLabels = [ 'current', 'history', 'dispatch' ]; + const itemsLaneGetters = { + current: () => itemsFactory.getCurrentModel(warehouseId), + history: () => itemsFactory.getHistoryModel(warehouseId), + dispatch: () => itemsFactory.getDispatchModel(warehouseId), + }; + const orderedItemsLanes = preferredLane && itemsLaneGetters[preferredLane] + ? [ preferredLane, ...itemsLaneLabels.filter(label => label !== preferredLane) ] + : itemsLaneLabels; - // 批量获取库存详情(带缓存的并行查询:条码 + 图片 + 库存属性) - const stockDetailsMap = new Map(); - if (stockIds.length > 0) { - try { - const details = await ctx.service.systems.stockWarehouse.getStockDetails(stockIds, { - warehouseId, - cacheTTL: 300, - }); - for (const detail of details) { - stockDetailsMap.set(detail.id, detail); - } - } catch (err) { - ctx.logger.warn(`[_resolveOrderDetail] 批量获取库存详情失败: ${err.message}`); - } - } - - orderItems = dbItems.map(item => { - const stock = stockDetailsMap.get(Number(item.stock_id)) || {}; - return { - id: item.id, - order_line_no: item.order_line_no || '', - item_code: item.item_code || stock.item_code || '', - item_name: item.item_name || stock.item_name || '', - sku_property: stock.sku_property || '', - quantity: stock.quantity || 0, - locked_quantity: stock.locked_quantity || 0, - is_batch_mgmt: stock.is_batch_mgmt || 'N', - is_shelf_life_mgmt: stock.is_shelf_life_mgmt || 'N', - is_images: stock.is_images || 'N', - store_id: stock.store_id || null, - packing_requirements: stock.packing_requirements || '', - stock_unit: stock.stock_unit || '', - image_url: stock.image_url || [], - barcodes: stock.barcodes || [], - plan_qty: item.plan_qty || 0, - stock_id: item.stock_id || null, - order_item_id: item.id, - order_id: orderDeliveryId, - }; + let dbItems = []; + for (const lane of orderedItemsLanes) { + try { + const itemsModel = await itemsLaneGetters[lane](); + if (!itemsModel || typeof itemsModel.findAll !== 'function') continue; + const laneRows = await itemsModel.findAll({ + where: { order_id: orderDeliveryId }, + raw: true, }); - ctx.logger.info(`[_resolveOrderDetail] 从分表加载 ${orderItems.length} 条明细(含库存详情)`); + if (laneRows && laneRows.length > 0) { + dbItems = laneRows; + break; + } + } catch (err) { + ctx.logger.warn(`[_resolveOrderDetail] 商品明细分表 ${lane} 查询失败: ${err.message}`); } } + + if (dbItems.length > 0) { + // 收集 stock_id 用于批量查库存详情 + const stockIds = dbItems + .map(item => Number(item.stock_id)) + .filter(id => Number.isInteger(id) && id > 0); + + // 批量获取库存详情(带缓存的并行查询:条码 + 图片 + 库存属性) + const stockDetailsMap = new Map(); + if (stockIds.length > 0) { + try { + const details = await ctx.service.systems.stockWarehouse.getStockDetails(stockIds, { + warehouseId, + cacheTTL: 300, + }); + for (const detail of details) { + stockDetailsMap.set(detail.id, detail); + } + } catch (err) { + ctx.logger.warn(`[_resolveOrderDetail] 批量获取库存详情失败: ${err.message}`); + } + } + + orderItems = dbItems.map(item => { + const stock = stockDetailsMap.get(Number(item.stock_id)) || {}; + return { + id: item.id, + order_line_no: item.order_line_no || '', + item_code: item.item_code || stock.item_code || '', + item_name: item.item_name || stock.item_name || '', + sku_property: stock.sku_property || '', + quantity: stock.quantity || 0, + locked_quantity: stock.locked_quantity || 0, + is_batch_mgmt: stock.is_batch_mgmt || 'N', + is_shelf_life_mgmt: stock.is_shelf_life_mgmt || 'N', + is_images: stock.is_images || 'N', + store_id: stock.store_id || null, + packing_requirements: stock.packing_requirements || '', + stock_unit: stock.stock_unit || '', + image_url: stock.image_url || [], + barcodes: stock.barcodes || [], + plan_qty: item.plan_qty || 0, + stock_id: item.stock_id || null, + order_item_id: item.id, + order_id: orderDeliveryId, + }; + }); + ctx.logger.info(`[_resolveOrderDetail] 从分表加载 ${orderItems.length} 条明细(含库存详情)`); + } } catch (err) { ctx.logger.warn(`[_resolveOrderDetail] 分表查询商品明细失败: ${err.message}`); } diff --git a/app/service/systems/return_unpack.js b/app/service/systems/return_unpack.js index 134dd86..d852683 100644 --- a/app/service/systems/return_unpack.js +++ b/app/service/systems/return_unpack.js @@ -31,7 +31,7 @@ class ReturnUnpackService extends Service { * @param {Array} [params.camera_ids] 摄像头ID列表。 * @param {number} [params.return_received_id] 关联退回收到单ID。 * @param {string} [params.remark] 备注。 - * @return {Promise} 开单结果,含 id、record、is_original_return、store_remark、order。 + * @return {Promise} 开单结果,含 id、record、is_original_return、store_remark、order、order_items。 */ async create({ waybill_code, camera_ids, return_received_id, remark }) { const { ctx, app } = this; @@ -106,6 +106,7 @@ class ReturnUnpackService extends Service { if (existing) { // 复用已有拆包单:返回主表 + 明细 + 视频 + 原订单详情(复用 detail 查询逻辑) const existingDetail = await this.detail(existing.id); + const existingOrder = (existingDetail.related && existingDetail.related.order) || null; ctx.logger.info( `[returnUnpack.create] 运单号 ${waybillCode} 3 个月内已有拆包单 id=${existing.id},直接复用返回明细` ); @@ -114,7 +115,8 @@ class ReturnUnpackService extends Service { record: existingDetail.record, is_original_return: Boolean(existing.order_express_id), store_remark: String(existingDetail.record && existingDetail.record.shop_name || ''), - order: (existingDetail.related && existingDetail.related.order) || null, + order: existingOrder, + order_items: existingOrder && Array.isArray(existingOrder.items) ? existingOrder.items : null, reused: true, }; } @@ -240,6 +242,7 @@ class ReturnUnpackService extends Service { is_original_return: isOriginalReturn, store_remark: storeRemark, order, + order_items: order && Array.isArray(order.items) ? order.items : null, }; } @@ -988,24 +991,55 @@ class ReturnUnpackService extends Service { if (order_id && !info.trade_no) { try { let order = null; - try { - order = await ctx.model.OrderDelivery.findOne({ - where: { id: order_id }, - raw: true, - }); - } catch (err) { - // 主表查询失败,继续走工厂分表兜底 - } - if (!order && ctx.model.OrderDeliveryFactory) { + const factory = ctx.model.OrderDeliveryFactory; + if (factory && typeof factory.getCurrentModel === 'function') { + const laneLabels = [ 'current', 'history', 'dispatch', 'outsourced' ]; + const laneGetters = { + current: () => factory.getCurrentModel(warehouse_id), + history: () => factory.getHistoryModel(warehouse_id), + dispatch: () => factory.getDispatchModel(warehouse_id), + outsourced: () => factory.getOutsourcedModel(warehouse_id), + }; + + // 序列表定位优先:命中车道先查对应分表,未命中按原顺序遍历回退 try { - const factoryModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouse_id); - if (factoryModel) { - order = await factoryModel.findOne({ where: { id: order_id }, raw: true }); + if (typeof factory.getOrderLocation === 'function') { + const location = await factory.getOrderLocation(order_id, warehouse_id); + if (location && laneGetters[location]) { + laneLabels.sort((a, b) => (a === location ? -1 : b === location ? 1 : 0)); + } } } catch (err) { - // 分表查询失败忽略 + // 定位失败忽略,保持遍历顺序 + } + + for (const lane of laneLabels) { + try { + const model = await laneGetters[lane](); + if (!model || typeof model.findOne !== 'function') continue; + const row = await model.findOne({ where: { id: order_id }, raw: true }); + if (row) { + order = row; + break; + } + } catch (err) { + // 该表可能不存在,继续下一张 + } } } + + // 分表均未命中:回退基表(存量订单) + if (!order) { + try { + order = await ctx.model.OrderDelivery.findOne({ + where: { id: order_id }, + raw: true, + }); + } catch (err) { + // 主表查询失败忽略 + } + } + if (order) { info.trade_no = String(order.source_order_codes || order.source_platform_code || ''); if (!info.express && order.logistics_name) info.express = String(order.logistics_name); diff --git a/methods/changes/system.json b/methods/changes/system.json index f6d7c21..2a0cc78 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,37 @@ [ + { + "version": "2026.08.21-returnUnpack.orderLocationLane", + "date": "2026-08-21", + "type": "fixed", + "summary": "returnUnpack 原订单详情解析修复:优先按订单 id 序列表(wms_order_id_location_{warehouseId})定位订单所在车道(current/history/dispatch/outsourced)直接查对应分表,未命中再按 current→history→dispatch→outsourced 遍历、最后回退基表。修复订单位于 history/dispatch 车道时 create/detail 返回 order=null、order_items=null 的问题。", + "methods": [ + "returnUnpack.create", + "returnUnpack.detail", + "returnUnpack.queryByWaybill" + ], + "notes": [ + "app/service/systems/afterSale.js _resolveOrderDetail:主记录查询由「基表优先→current 分表」改为「OrderDeliveryFactory.getOrderLocation 序列表定位车道优先→current/history/dispatch/outsourced 四车道遍历→基表回退(存量订单)」;商品明细回退查询同步按定位车道优先遍历 current/history/dispatch 三个 items 分表", + "app/service/systems/return_unpack.js _resolveReturnOrderInfo:原订单兜底查询同改(交易单号/快递信息),查退回场景同步受益", + "序列表未回填的存量订单(getOrderLocation 返回 null)自动落入遍历回退,行为不退化;定位/单表查询失败仅告警不阻断主流程", + "无 API 出参结构变化(仅修复 order/order_items 由 null 变正常返回),methods/system.json 无需更新" + ], + "module": "returnUnpack" + }, + { + "version": "2026.08.21-returnUnpack.create-orderItems", + "date": "2026-08-21", + "type": "enhanced", + "summary": "returnUnpack.create 返回新增顶层 order_items 字段:原订单商品明细数组(即 order.items 的顶层透出,含 item_code/item_name/sku_property/quantity/plan_qty/barcodes/image_url 等),仅原单退回且原订单详情解析成功时返回;非原单退回或原订单详情缺失时为 null。新建与幂等复用两个分支返回结构一致。", + "methods": [ + "returnUnpack.create" + ], + "notes": [ + "app/service/systems/return_unpack.js create:新建分支返回 order_items(order.items 为数组时透出,否则 null);幂等复用分支从 detail().related.order 提取同名字段,与 order 字段同源", + "向后兼容:仅新增顶层字段,order/record 等既有字段不变", + "同步更新 methods/system.json 中 returnUnpack.create 的 response(新增 order_items 字段说明)" + ], + "module": "returnUnpack" + }, { "version": "2026.08.21-index.searchSpaces-batch-search", "date": "2026-08-21", diff --git a/methods/system.json b/methods/system.json index 5da4f63..c5ef839 100644 --- a/methods/system.json +++ b/methods/system.json @@ -36204,7 +36204,7 @@ "list": [ { "method": "returnUnpack.create", - "description": "开拆包单(明细不在此提交,由 returnUnpack.addDetail 逐件录入)。用 waybill_code 反查 wms_order_express 判定是否原单退回,命中则回填 order_express_id/order_id/store_id 及订单信息快照(source_order_codes 平台交易单号 / shop_name 店铺名称=货主自定义店铺名称 store_remask)并返回原订单详情;未命中原单时按 warehouse_id+waybill_code 从 wms_return_query_log 反查货主(限最近 3 个月内登记)。幂等复用:同一仓库同一运单号 3 个月内已存在非 cancelled 拆包单时,不重复创建,直接返回已有拆包单的主表+明细(record.details)+视频(record.videos)+原订单详情(order),并携带 reused=true 标识;同运单号存在多张拆包单时优先复用已录明细的最新单(按明细表真实计数判定),超过 3 个月视为运单号已复用,按新单正常创建。拆包单号规则 RP+YYYYMMDD+6位序号。仓库隔离:warehouse_id 由服务端注入 ctx.user.store_id,禁止前端传入。", + "description": "开拆包单(明细不在此提交,由 returnUnpack.addDetail 逐件录入)。用 waybill_code 反查 wms_order_express 判定是否原单退回,命中则回填 order_express_id/order_id/store_id 及订单信息快照(source_order_codes 平台交易单号 / shop_name 店铺名称=货主自定义店铺名称 store_remask)并返回原订单详情(order)与顶层原单商品明细(order_items);未命中原单时按 warehouse_id+waybill_code 从 wms_return_query_log 反查货主(限最近 3 个月内登记)。幂等复用:同一仓库同一运单号 3 个月内已存在非 cancelled 拆包单时,不重复创建,直接返回已有拆包单的主表+明细(record.details)+视频(record.videos)+原订单详情(order),并携带 reused=true 标识;同运单号存在多张拆包单时优先复用已录明细的最新单(按明细表真实计数判定),超过 3 个月视为运单号已复用,按新单正常创建。拆包单号规则 RP+YYYYMMDD+6位序号。仓库隔离:warehouse_id 由服务端注入 ctx.user.store_id,禁止前端传入。", "isNeedAuth": true, "isNeedLogin": true, "headers": [], @@ -36269,6 +36269,12 @@ "required": false, "description": "原订单详情(含 items 明细,仅原单退回时返回,非原单为 null)" }, + { + "name": "order_items", + "type": "array", + "required": false, + "description": "原订单商品明细数组(即 order.items 的顶层透出,含 item_code/item_name/sku_property/quantity/plan_qty/barcodes/image_url 等,仅原单退回时返回;非原单退回或原订单详情缺失时为 null)" + }, { "name": "reused", "type": "boolean", From 0dc7e1cd09fda05e0f06789ba23c15c26d530c09 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Fri, 21 Aug 2026 23:07:51 +0800 Subject: [PATCH 251/550] =?UTF-8?q?feat(stock):=20stock.warehouse.search?= =?UTF-8?q?=20=E8=BF=94=E5=9B=9E=E6=96=B0=E5=A2=9E=20images=20=E5=95=86?= =?UTF-8?q?=E5=93=81=E5=9B=BE=E7=89=87=E5=88=97=E8=A1=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - stock_store.search 批查 wms_file_reference(business_type=stock)+wms_file, 按 display_order 升序注入 item.images,无图片返回空数组(口径与 list 一致) - 同步更新 methods/system.json response 字段与 methods/changes/system.json 变更记录 --- app/service/systems/stock_store.js | 32 +++++++++++++ methods/changes/system.json | 75 ++++++++++++++++++++++++++++++ methods/system.json | 32 ++++++++++++- 3 files changed, 138 insertions(+), 1 deletion(-) diff --git a/app/service/systems/stock_store.js b/app/service/systems/stock_store.js index aedcf07..599eee3 100644 --- a/app/service/systems/stock_store.js +++ b/app/service/systems/stock_store.js @@ -3824,6 +3824,38 @@ class stockStoreService extends Service { return result; }); + // 批查商品图片(与 stock.warehouse.list 一致:wms_file_reference + wms_file) + if (formattedResults.length > 0) { + const stockIds = formattedResults.map(r => r.id); + const imageRows = await app.model.FileReference.findAll({ + where: { + business_type: 'stock', + business_id: { [Op.in]: stockIds.map(String) }, + }, + include: [{ + model: app.model.File, + as: 'file', + attributes: [ 'file_url' ], + required: false, + }], + order: [[ 'display_order', 'ASC' ]], + raw: true, + }); + + const imageMap = new Map(); + for (const row of imageRows) { + const sid = Number(row.business_id); + const url = (row['file.file_url'] && String(row['file.file_url']).trim()) || ''; + if (!url) continue; + if (!imageMap.has(sid)) imageMap.set(sid, []); + imageMap.get(sid).push(url); + } + + for (const item of formattedResults) { + item.images = imageMap.get(item.id) || []; + } + } + // with_stock=true 时关联查询库存数据 if (with_stock && formattedResults.length > 0) { const stockIds = formattedResults.map(r => r.id); diff --git a/methods/changes/system.json b/methods/changes/system.json index 2a0cc78..1c2b4a7 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,21 @@ [ + { + "version": "2026.08.21-storage.entry.list-row-quantity", + "date": "2026-08-21", + "type": "enhanced", + "summary": "storage.entry.list / storage.entry.listStore 列表每行新增 total_quantity(该入库单商品总数量,计划数)与 received_quantity(已入库数量)字段:按当前页入库单批量聚合 wms_entry_items 明细(SUM(count)/SUM(received_quantity))注入,与 total_order_lines(单据总行数/品类数)区分,无明细行时补 0。", + "methods": [ + "storage.entry.list", + "storage.entry.listStore" + ], + "notes": [ + "app/service/systems/storage/entry.js list:receivingBindings 批量查询后新增按 order_id 分组的 EntryItems 聚合,注入 enrichedRows 每行的 total_quantity/received_quantity", + "聚合仅针对当前页入库单 ID,不影响筛选/分页/排序逻辑", + "向后兼容:仅新增行级字段,list/pagination/summary 既有结构不变", + "同步更新 methods/system.json 中 storage.entry.list 与 storage.entry.listStore 的 response(新增 list[].total_quantity / list[].received_quantity)" + ], + "module": "storage" + }, { "version": "2026.08.21-returnUnpack.orderLocationLane", "date": "2026-08-21", @@ -32,6 +49,64 @@ ], "module": "returnUnpack" }, + { + "version": "2026.08.21-stock.warehouse.search-return-images", + "date": "2026-08-21", + "type": "enhanced", + "summary": "stock.warehouse.search 默认模式返回数据新增 images 字段:批查 wms_file_reference(business_type=stock)+ wms_file 获取商品图片URL列表,按 display_order 升序;无图片时返回空数组。mode=\"combo\" 时不返回该字段。", + "methods": [ + "stock.warehouse.search" + ], + "notes": [ + "app/service/systems/stock_store.js search:formattedResults 生成后批量查询 FileReference(include File.file_url,raw),按 business_id(商品ID)分组注入 item.images,与 stock.warehouse.list 图片口径一致", + "同步更新 methods/system.json 中 stock.warehouse.search 的 response 字段" + ], + "module": "stock" + }, + { + "version": "2026.08.21-order.pendingOrder.cloneOrder-sync-status-inherit", + "date": "2026-08-21", + "type": "enhanced", + "summary": "order.pendingOrder.cloneOrder 同步状态继承原订单:原订单已同步(sync_status=fin)时新订单直接置 fin,避免克隆后重复回传平台;原订单未同步/同步失败(padding/error)则重置为 padding 重新走同步流程。", + "methods": [ + "order.pendingOrder.cloneOrder" + ], + "notes": [ + "app/service/systemMethods/order/pendingOrder.js cloneOrder 第 4 步 newOrderData.sync_status 按 original.sync_status 判定:fin→fin,其余→padding(RESET_FIELDS 保留 padding 兜底)", + "已同步新订单分配运单号不受 sync_status 限制(createWaybillCodePipeline 只校验 step 1/2/3/4、status、拦截、锁定、已分配运单号),但新订单 step=0 需先审核进入待处理才能分配;已同步订单分配新运单号后不会自动回传平台", + "同步更新 methods/system.json 中 cloneOrder 的 description" + ], + "module": "order" + }, + { + "version": "2026.08.21-order.pendingOrder.cloneOrder-storage-release-tolerant", + "date": "2026-08-21", + "type": "enhanced", + "summary": "order.pendingOrder.cloneOrder 支持克隆已同步(sync_status=fin)订单且库存释放失败不阻断:原订单已分配储位时先清除已分配库存,cancelAllocateStorage 失败降级为告警(与 cancelOrder 策略一致),克隆继续执行;残留占用保留在原订单名下,克隆新订单不重新占用库存(storage_status=none,创建过程不触发储位分配与库存锁定)。", + "methods": [ + "order.pendingOrder.cloneOrder" + ], + "notes": [ + "app/service/systemMethods/order/pendingOrder.js cloneOrder 第 2 步:清除已分配库存失败由抛错阻断改为 ctx.logger.warn 降级,不影响克隆主流程", + "克隆新订单库存零占用(storage_status 重置 none、无自动储位分配),后续如需发货需在待处理工作台重新分配储位", + "同步更新 methods/system.json 中 cloneOrder 的 description" + ], + "module": "order" + }, + { + "version": "2026.08.21-order.pendingOrder.cloneOrder-unique-delivery-code", + "date": "2026-08-21", + "type": "fixed", + "summary": "修复 order.pendingOrder.cloneOrder 复制原单号导致唯一键冲突:新订单 delivery_order_code 重新生成(SYS+时间戳+随机4位,与 createOrder 同规则),原单号写入 pre_delivery_order_code 保留克隆追溯链;此前复制原单号会命中 (delivery_order_code, store_id, warehouse_id) 唯一索引,克隆报「Validation error」且原订单已被取消、新订单未创建(原订单损坏)。", + "methods": [ + "order.pendingOrder.cloneOrder" + ], + "notes": [ + "app/service/systemMethods/order/pendingOrder.js cloneOrder:COPY_FIELDS 移除 delivery_order_code,新订单单号改为 SYS${Date.now()}${1000~9999 随机} 生成;原订单无 pre_delivery_order_code 时写入原单号保留追溯链;注释说明唯一索引约束与 UniqueConstraintError 表现", + "同步更新 methods/system.json 中 cloneOrder 的 description" + ], + "module": "order" + }, { "version": "2026.08.21-index.searchSpaces-batch-search", "date": "2026-08-21", diff --git a/methods/system.json b/methods/system.json index c5ef839..8b501c0 100644 --- a/methods/system.json +++ b/methods/system.json @@ -3982,7 +3982,7 @@ }, { "method": "order.pendingOrder.cloneOrder", - "description": "克隆待处理订单。完整流程:1. 查找原订单,校验可取消状态(step 0/1/2/3);2. 若原订单已分配储位(storage_status='fin'),先清除已分配库存;3. 取消原订单(step→9, status→cancel),记录克隆日志;4. 以原订单业务数据创建新订单,所有流程状态字段重置为初始落库状态;5. 克隆订单明细(含 stock_id),重置 order_id 为新订单 ID;6. 对新订单记录克隆创建日志。", + "description": "克隆待处理订单(含已同步 sync_status=fin 订单)。完整流程:1. 查找原订单,校验可取消状态(step 0/1/2/3);2. 若原订单已分配储位(storage_status='fin'),先清除已分配库存,释放失败不阻断克隆(残留占用保留在原订单名下);3. 取消原订单(step→9, status→cancel),记录克隆日志;4. 以原订单业务数据创建新订单,所有流程状态字段重置为初始落库状态,发货单号重新生成为 SYS 前缀新单号(受唯一索引 delivery_order_code+store_id+warehouse_id 约束,不可复制原单号),原单号写入 pre_delivery_order_code 保留克隆追溯链,同步状态继承原订单(原订单已同步 sync_status=fin 则新订单直接置 fin 避免重复回传,否则重置 padding 重新同步);5. 克隆订单明细(含 stock_id),重置 order_id 为新订单 ID;6. 对新订单记录克隆创建日志。克隆新订单不重新占用库存(storage_status=none,不触发储位分配与库存锁定)。", "isNeedAuth": true, "isNeedLogin": true, "headers": [ @@ -17920,6 +17920,12 @@ "description": "商品条形码列表(string[])。mode=\"combo\" 时不返回此字段", "required": false }, + { + "name": "images", + "type": "array", + "description": "商品图片URL列表(string[]),来自 wms_file_reference(business_type=stock)关联 wms_file.file_url,按 display_order 升序;无图片时为空数组。mode=\"combo\" 时不返回此字段", + "required": false + }, { "name": "store_stock", "type": "object", @@ -21803,6 +21809,18 @@ "required": true, "description": "入库单列表" }, + { + "name": "list[].total_quantity", + "type": "number", + "required": true, + "description": "该入库单商品总数量(计划数,明细 count 合计,区别于 total_order_lines 单据总行数/品类数)" + }, + { + "name": "list[].received_quantity", + "type": "number", + "required": true, + "description": "该入库单已入库数量(明细 received_quantity 合计)" + }, { "name": "pagination", "type": "object", @@ -21884,6 +21902,18 @@ "required": true, "description": "入库单列表" }, + { + "name": "list[].total_quantity", + "type": "number", + "required": true, + "description": "该入库单商品总数量(计划数,明细 count 合计,区别于 total_order_lines 单据总行数/品类数)" + }, + { + "name": "list[].received_quantity", + "type": "number", + "required": true, + "description": "该入库单已入库数量(明细 received_quantity 合计)" + }, { "name": "pagination", "type": "object", From 6d332106243d51279e18fbe67cb0e3fcdab9dc25 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Fri, 21 Aug 2026 23:23:06 +0800 Subject: [PATCH 252/550] =?UTF-8?q?fix(storage):=20=E4=BF=AE=E5=A4=8D?= =?UTF-8?q?=E5=BA=93=E5=AD=98/=E5=95=86=E5=93=81=E5=88=97=E8=A1=A8?= =?UTF-8?q?=E6=8C=89=E6=95=B0=E9=87=8F=E7=AD=89=E5=AD=97=E6=AE=B5=E6=8E=92?= =?UTF-8?q?=E5=BA=8F=E4=B8=8D=E7=94=9F=E6=95=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - stock.warehouse.list: 透传 sort 参数给 getWarehouseStock(此前漏传,后端始终按 id DESC 排序,quantity/available_quantity 等排序字段均无效) - systems/storage/inventory getInventoryList/exportInventoryList: - 汇总模式(按 stock_id 合并)order 原写死 last_inbound_time,现支持按聚合别名排序:quantity/locked_quantity/available_quantity/batch_count/first_inbound_time/last_inbound_time/production_date/expiry_date,其余回退 last_inbound_time - 明细模式新增真实列白名单,非法字段回退默认列,避免 SQL 报错/注入 - sortOrder 统一归一化为 ASC/DESC,分页兼容 currentPage --- app/service/systemMethods/stock/warehouse.js | 10 +++- app/service/systems/storage/inventory.js | 50 +++++++++++++++++--- 2 files changed, 52 insertions(+), 8 deletions(-) diff --git a/app/service/systemMethods/stock/warehouse.js b/app/service/systemMethods/stock/warehouse.js index 153c171..b06a05b 100644 --- a/app/service/systemMethods/stock/warehouse.js +++ b/app/service/systemMethods/stock/warehouse.js @@ -51,11 +51,19 @@ class WarehouseService extends MainService { * @param {Object} data 请求体 * @param {Object} [data.pagination] 分页参数 * @param {Object} [data.where] 筛选条件 + * @param {Object} [data.sort] 排序参数 + * @param {string} [data.sort.sortField] 排序字段(兼容:sort_field) + * @param {string} [data.sort.sortOrder] 排序顺序(兼容:sort_order) * @return {Promise} 统一成功包装响应 */ async list(data = {}) { const { service } = this; const { pagination } = data; + const sort = data.sort || {}; + const sortParams = { + sortField: sort.sortField || sort.sort_field || 'id', + sortOrder: sort.sortOrder || sort.sort_order || 'DESC', + }; if (this.isPlainObject(data)) { const rawWhere = this.isPlainObject(data.where) ? data.where : {}; data.where = this.normalizeWarehouseRecycleWhere(rawWhere); @@ -75,7 +83,7 @@ class WarehouseService extends MainService { }, }, }); - const result = await service.systems.stockStore.getWarehouseStock(where, pagination); + const result = await service.systems.stockStore.getWarehouseStock(where, pagination, sortParams); return this.success('ok', result); } diff --git a/app/service/systems/storage/inventory.js b/app/service/systems/storage/inventory.js index 66977ff..7ee56a8 100644 --- a/app/service/systems/storage/inventory.js +++ b/app/service/systems/storage/inventory.js @@ -3,6 +3,33 @@ const Service = require('egg').Service; const DAY_MS = 24 * 60 * 60 * 1000; +/** + * 库存明细(逐条)模式允许的排序字段白名单(wms_storage 真实列), + * 防止非法字段进入 ORDER BY 导致 SQL 报错或注入。 + */ +const STORAGE_BATCH_SORT_FIELD_WHITELIST = new Set([ + 'id', 'stock_id', 'space_id', 'batch_no', 'inventory_type', + 'quantity', 'locked_quantity', 'available_quantity', + 'production_date', 'expiry_date', 'inbound_time', + 'created_at', 'updated_at', +]); + +/** + * 库存汇总(按 stock_id 合并)模式允许的排序字段 → 聚合别名映射。 + * 汇总查询中 quantity/locked_quantity/available_quantity 等为 SUM/MIN/MAX 别名, + * MySQL 支持 ORDER BY 别名,因此直接按别名排序。 + */ +const STORAGE_AGGREGATE_ORDER_FIELD_MAP = { + quantity: 'quantity', + locked_quantity: 'locked_quantity', + available_quantity: 'available_quantity', + batch_count: 'batch_count', + first_inbound_time: 'first_inbound_time', + last_inbound_time: 'last_inbound_time', + production_date: 'production_date', + expiry_date: 'expiry_date', +}; + /** * 计算库存批次的保质期预警状态。 * @@ -1135,7 +1162,7 @@ class InventoryService extends Service { * @param {number} [pageParams.page=1] 页码 * @param {number} [pageParams.pageSize=20] 每页数量 * @param {Object} [sortParams={}] 排序参数 - * @param {string} [sortParams.sortField='created_at'] 排序字段 + * @param {string} [sortParams.sortField='created_at'] 排序字段(明细模式支持 wms_storage 真实列;汇总模式仅支持 quantity/locked_quantity/available_quantity/batch_count/first_inbound_time/last_inbound_time/production_date/expiry_date,其余回退 last_inbound_time) * @param {string} [sortParams.sortOrder='DESC'] 排序方向 * @param {boolean} [groupByBatch=false] 是否按批次明细返回 * @return {Promise<{list: Object[], pagination: {page: number, pageSize: number, total: number, totalPages: number}}>} 库存列表结果 @@ -1146,8 +1173,14 @@ class InventoryService extends Service { const nowMs = Date.now(); const warehouseId = ctx.user.store_id; - const { page = 1, pageSize = 20 } = pageParams; - const { sortField = 'created_at', sortOrder = 'DESC' } = sortParams; + const page = Math.max(Number(pageParams.page || pageParams.currentPage || 1) || 1, 1); + const pageSize = Math.max(Number(pageParams.pageSize || 20) || 20, 1); + const sortField = sortParams.sortField || sortParams.sort_field || 'created_at'; + const sortOrder = sortParams.sortOrder || sortParams.sort_order || 'DESC'; + const safeSortOrder = String(sortOrder).toUpperCase() === 'ASC' ? 'ASC' : 'DESC'; + // 明细模式按真实列排序;汇总模式按聚合别名排序(默认 last_inbound_time,与历史行为一致) + const batchSortField = STORAGE_BATCH_SORT_FIELD_WHITELIST.has(sortField) ? sortField : 'created_at'; + const aggregateOrderField = STORAGE_AGGREGATE_ORDER_FIELD_MAP[sortField] || 'last_inbound_time'; // 基础条件 const baseWhere = { @@ -1188,7 +1221,7 @@ class InventoryService extends Service { // 按批次明细:逐条返回 const { count: total, rows } = await ctx.model.Storage.findAndCountAll({ where: baseWhere, - order: [[ sortField, sortOrder ]], + order: [[ batchSortField, safeSortOrder ]], offset, limit, include: [ @@ -1291,7 +1324,7 @@ class InventoryService extends Service { [ fn('COUNT', col('wms_storage.id')), 'batch_count' ], ], group: groupFields, - order: [[ literal('last_inbound_time'), sortOrder ]], + order: [[ literal(aggregateOrderField), safeSortOrder ]], offset, limit, include: [ @@ -1660,6 +1693,9 @@ class InventoryService extends Service { const { Op, fn, col, literal } = app.Sequelize; const warehouseId = ctx.user.store_id; const { sortField = 'id', sortOrder = 'DESC' } = sortParams; + const safeSortOrder = String(sortOrder).toUpperCase() === 'ASC' ? 'ASC' : 'DESC'; + const batchSortField = STORAGE_BATCH_SORT_FIELD_WHITELIST.has(sortField) ? sortField : 'id'; + const aggregateOrderField = STORAGE_AGGREGATE_ORDER_FIELD_MAP[sortField] || 'last_inbound_time'; const pageSize = 500; let page = 1; let hasNext = true; @@ -1692,7 +1728,7 @@ class InventoryService extends Service { 'supplier_batch_no', 'store_id', 'warehouse_id', 'created_at', 'updated_at', ], - order: [[ sortField, sortOrder ]], + order: [[ batchSortField, safeSortOrder ]], offset: (page - 1) * pageSize, limit: pageSize, include: [ @@ -1783,7 +1819,7 @@ class InventoryService extends Service { [ fn('MAX', col('wms_storage.updated_at')), 'last_updated_at' ], ], group: groupFields, - order: [[ literal('last_inbound_time'), sortOrder ]], + order: [[ literal(aggregateOrderField), safeSortOrder ]], offset: (page - 1) * pageSize, limit: pageSize, include: [ From 4b4b645257a3c419dc61c5f506fe5f6cf3d0d1ea Mon Sep 17 00:00:00 2001 From: liufumingren Date: Fri, 21 Aug 2026 23:25:53 +0800 Subject: [PATCH 253/550] =?UTF-8?q?fix(express):=E4=BF=AE=E5=A4=8D?= =?UTF-8?q?=E5=88=86=E9=85=8D=E5=BF=AB=E9=80=92=E5=8F=B7=E8=81=9A=E6=B0=B4?= =?UTF-8?q?=E6=BD=AD=E5=90=88=E5=8D=95=E5=A4=96=E9=83=A8=E8=AE=A2=E5=8D=95?= =?UTF-8?q?=E5=8F=B7=E5=9C=A8pay=5Fno=E4=B8=8D=E5=90=88=E5=8D=95=E4=B8=8D?= =?UTF-8?q?=E5=9C=A8=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/systems/express_platform.js | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/app/service/systems/express_platform.js b/app/service/systems/express_platform.js index db10d63..4cb4879 100644 --- a/app/service/systems/express_platform.js +++ b/app/service/systems/express_platform.js @@ -703,11 +703,15 @@ class ExpressPlatformService extends MainService { const order = order_tmp.order_delivery; console.log('order', order); const expressListItem = ExpressList.find(item => item.code === listByWarehousePlatformCode.sys_express_code) || {}; + let plattradeno = order.source_order_codes; + if(listByWarehousePlatformCode.platform_code === 'DY' && order.from_key === 23060081 && !!order.pay_no && plattradeno.indexOf(",") > -1){ + plattradeno = order.pay_no; + } let playload = { object_Id: `${order.warehouse_id.toString(16)}_${order.id}_${order_tmp.business_key}`, // 菠萝派平台要求订单唯一标识必须为字符串 orderno: `${order.warehouse_id.toString(16)}_${order.id}_${order_tmp.business_key}`, // 菠萝派平台要求订单号必须为字符串 - plattradeno: listByWarehousePlatformCode.platform_code === 'DY' && order.from_key === 23060081 && !!order.pay_no ? order.pay_no : order.source_order_codes || order.delivery_order_code || '', - tid:listByWarehousePlatformCode.platform_code === 'DY' && order.from_key === 23060081 && !!order.pay_no ? order.pay_no : order.source_order_codes || order.delivery_order_code || '', + plattradeno: plattradeno, + tid: plattradeno, ismultiplepieces: order.package_count > 1 ? 1 : 0, logisticno: allocatedWaybillMap.get(`${Number(order.id) || 0}:${Number(order_tmp.business_key) || 0}`) || '', logistictype: expressListItem[listByWarehousePlatformCode.platform_code] || '', From f6ee444d36cbae5a5477ea1ed943f397f8a0ceec Mon Sep 17 00:00:00 2001 From: liufumingren Date: Fri, 21 Aug 2026 23:34:06 +0800 Subject: [PATCH 254/550] =?UTF-8?q?feat(storage):=20=E5=85=A5=E5=BA=93?= =?UTF-8?q?=E5=8D=95=E5=88=97=E8=A1=A8=E8=A1=8C=E7=BA=A7=E6=96=B0=E5=A2=9E?= =?UTF-8?q?=20total=5Fquantity/received=5Fquantity=20=E6=95=B0=E9=87=8F?= =?UTF-8?q?=E6=B1=87=E6=80=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - storage.entry.list/listStore 按当前页入库单批量聚合 wms_entry_items(SUM(count)/SUM(received_quantity))注入每行 - 无明细行补 0,不影响筛选/分页/排序逻辑 --- app/service/systems/storage/entry.js | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/app/service/systems/storage/entry.js b/app/service/systems/storage/entry.js index 260a70a..26b619d 100644 --- a/app/service/systems/storage/entry.js +++ b/app/service/systems/storage/entry.js @@ -490,12 +490,37 @@ class EntryService extends Service { } } - // 为每行附加收货单绑定信息 + // 批量聚合当前页入库单的商品总数量(计划数)与已入库数量 + /** @type {Map} */ + const quantityMap = new Map(); + if (entryOrderIds.length > 0) { + const quantityRows = await ctx.model.EntryItems.findAll({ + attributes: [ + 'order_id', + [ Sequelize.fn('SUM', Sequelize.col('count')), 'total_quantity' ], + [ Sequelize.fn('SUM', Sequelize.col('received_quantity')), 'received_quantity' ], + ], + where: { order_id: { [Op.in]: entryOrderIds } }, + group: [ 'order_id' ], + raw: true, + }); + for (const item of quantityRows) { + quantityMap.set(Number(item.order_id), { + total_quantity: Number(item.total_quantity) || 0, + received_quantity: Number(item.received_quantity) || 0, + }); + } + } + + // 为每行附加收货单绑定信息与数量汇总 const enrichedRows = rows.map(row => { const rowJSON = row.toJSON ? row.toJSON() : row; const bindings = receivingBindingsMap.get(row.id) || []; + const quantity = quantityMap.get(row.id) || { total_quantity: 0, received_quantity: 0 }; return { ...rowJSON, + total_quantity: quantity.total_quantity, + received_quantity: quantity.received_quantity, receivingBindings: bindings, hasReceiving: bindings.length > 0, }; From c77b12be2cba9562c012565207607ba0ade811d7 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Fri, 21 Aug 2026 23:34:10 +0800 Subject: [PATCH 255/550] =?UTF-8?q?docs(storage):=20=E7=A7=BB=E9=99=A4=20s?= =?UTF-8?q?torage.entry=20=E8=A1=8C=E7=BA=A7=E6=95=B0=E9=87=8F=E5=AD=97?= =?UTF-8?q?=E6=AE=B5=E6=96=87=E6=A1=A3=E4=B8=8E=E5=8F=98=E6=9B=B4=E8=AE=B0?= =?UTF-8?q?=E5=BD=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - methods/system.json: 移除 storage.entry.list/listStore 的 list[].total_quantity / list[].received_quantity 字段说明 - methods/changes/system.json: 移除 storage.entry.list-row-quantity 变更记录 --- methods/changes/system.json | 17 ----------------- methods/system.json | 24 ------------------------ 2 files changed, 41 deletions(-) diff --git a/methods/changes/system.json b/methods/changes/system.json index 1c2b4a7..a550334 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,21 +1,4 @@ [ - { - "version": "2026.08.21-storage.entry.list-row-quantity", - "date": "2026-08-21", - "type": "enhanced", - "summary": "storage.entry.list / storage.entry.listStore 列表每行新增 total_quantity(该入库单商品总数量,计划数)与 received_quantity(已入库数量)字段:按当前页入库单批量聚合 wms_entry_items 明细(SUM(count)/SUM(received_quantity))注入,与 total_order_lines(单据总行数/品类数)区分,无明细行时补 0。", - "methods": [ - "storage.entry.list", - "storage.entry.listStore" - ], - "notes": [ - "app/service/systems/storage/entry.js list:receivingBindings 批量查询后新增按 order_id 分组的 EntryItems 聚合,注入 enrichedRows 每行的 total_quantity/received_quantity", - "聚合仅针对当前页入库单 ID,不影响筛选/分页/排序逻辑", - "向后兼容:仅新增行级字段,list/pagination/summary 既有结构不变", - "同步更新 methods/system.json 中 storage.entry.list 与 storage.entry.listStore 的 response(新增 list[].total_quantity / list[].received_quantity)" - ], - "module": "storage" - }, { "version": "2026.08.21-returnUnpack.orderLocationLane", "date": "2026-08-21", diff --git a/methods/system.json b/methods/system.json index 8b501c0..d174630 100644 --- a/methods/system.json +++ b/methods/system.json @@ -21809,18 +21809,6 @@ "required": true, "description": "入库单列表" }, - { - "name": "list[].total_quantity", - "type": "number", - "required": true, - "description": "该入库单商品总数量(计划数,明细 count 合计,区别于 total_order_lines 单据总行数/品类数)" - }, - { - "name": "list[].received_quantity", - "type": "number", - "required": true, - "description": "该入库单已入库数量(明细 received_quantity 合计)" - }, { "name": "pagination", "type": "object", @@ -21902,18 +21890,6 @@ "required": true, "description": "入库单列表" }, - { - "name": "list[].total_quantity", - "type": "number", - "required": true, - "description": "该入库单商品总数量(计划数,明细 count 合计,区别于 total_order_lines 单据总行数/品类数)" - }, - { - "name": "list[].received_quantity", - "type": "number", - "required": true, - "description": "该入库单已入库数量(明细 received_quantity 合计)" - }, { "name": "pagination", "type": "object", From 84929b69048303a1507bc57cb766db15fd5bdd79 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Fri, 21 Aug 2026 23:34:19 +0800 Subject: [PATCH 256/550] =?UTF-8?q?docs(returnUnpack):=20=E7=A7=BB?= =?UTF-8?q?=E9=99=A4=E8=AE=A2=E5=8D=95=E8=BD=A6=E9=81=93=E5=AE=9A=E4=BD=8D?= =?UTF-8?q?=E5=8F=98=E6=9B=B4=E8=AE=B0=E5=BD=95=E5=B9=B6=E8=BF=98=E5=8E=9F?= =?UTF-8?q?=20create=20=E6=8F=8F=E8=BF=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - methods/changes/system.json: 移除 returnUnpack.orderLocationLane 变更记录 - methods/system.json: returnUnpack.create 描述移除顶层 order_items 提及 --- methods/changes/system.json | 18 ------------------ methods/system.json | 2 +- 2 files changed, 1 insertion(+), 19 deletions(-) diff --git a/methods/changes/system.json b/methods/changes/system.json index a550334..c70c931 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,22 +1,4 @@ [ - { - "version": "2026.08.21-returnUnpack.orderLocationLane", - "date": "2026-08-21", - "type": "fixed", - "summary": "returnUnpack 原订单详情解析修复:优先按订单 id 序列表(wms_order_id_location_{warehouseId})定位订单所在车道(current/history/dispatch/outsourced)直接查对应分表,未命中再按 current→history→dispatch→outsourced 遍历、最后回退基表。修复订单位于 history/dispatch 车道时 create/detail 返回 order=null、order_items=null 的问题。", - "methods": [ - "returnUnpack.create", - "returnUnpack.detail", - "returnUnpack.queryByWaybill" - ], - "notes": [ - "app/service/systems/afterSale.js _resolveOrderDetail:主记录查询由「基表优先→current 分表」改为「OrderDeliveryFactory.getOrderLocation 序列表定位车道优先→current/history/dispatch/outsourced 四车道遍历→基表回退(存量订单)」;商品明细回退查询同步按定位车道优先遍历 current/history/dispatch 三个 items 分表", - "app/service/systems/return_unpack.js _resolveReturnOrderInfo:原订单兜底查询同改(交易单号/快递信息),查退回场景同步受益", - "序列表未回填的存量订单(getOrderLocation 返回 null)自动落入遍历回退,行为不退化;定位/单表查询失败仅告警不阻断主流程", - "无 API 出参结构变化(仅修复 order/order_items 由 null 变正常返回),methods/system.json 无需更新" - ], - "module": "returnUnpack" - }, { "version": "2026.08.21-returnUnpack.create-orderItems", "date": "2026-08-21", diff --git a/methods/system.json b/methods/system.json index d174630..e22ef73 100644 --- a/methods/system.json +++ b/methods/system.json @@ -36210,7 +36210,7 @@ "list": [ { "method": "returnUnpack.create", - "description": "开拆包单(明细不在此提交,由 returnUnpack.addDetail 逐件录入)。用 waybill_code 反查 wms_order_express 判定是否原单退回,命中则回填 order_express_id/order_id/store_id 及订单信息快照(source_order_codes 平台交易单号 / shop_name 店铺名称=货主自定义店铺名称 store_remask)并返回原订单详情(order)与顶层原单商品明细(order_items);未命中原单时按 warehouse_id+waybill_code 从 wms_return_query_log 反查货主(限最近 3 个月内登记)。幂等复用:同一仓库同一运单号 3 个月内已存在非 cancelled 拆包单时,不重复创建,直接返回已有拆包单的主表+明细(record.details)+视频(record.videos)+原订单详情(order),并携带 reused=true 标识;同运单号存在多张拆包单时优先复用已录明细的最新单(按明细表真实计数判定),超过 3 个月视为运单号已复用,按新单正常创建。拆包单号规则 RP+YYYYMMDD+6位序号。仓库隔离:warehouse_id 由服务端注入 ctx.user.store_id,禁止前端传入。", + "description": "开拆包单(明细不在此提交,由 returnUnpack.addDetail 逐件录入)。用 waybill_code 反查 wms_order_express 判定是否原单退回,命中则回填 order_express_id/order_id/store_id 及订单信息快照(source_order_codes 平台交易单号 / shop_name 店铺名称=货主自定义店铺名称 store_remask)并返回原订单详情;未命中原单时按 warehouse_id+waybill_code 从 wms_return_query_log 反查货主(限最近 3 个月内登记)。幂等复用:同一仓库同一运单号 3 个月内已存在非 cancelled 拆包单时,不重复创建,直接返回已有拆包单的主表+明细(record.details)+视频(record.videos)+原订单详情(order),并携带 reused=true 标识;同运单号存在多张拆包单时优先复用已录明细的最新单(按明细表真实计数判定),超过 3 个月视为运单号已复用,按新单正常创建。拆包单号规则 RP+YYYYMMDD+6位序号。仓库隔离:warehouse_id 由服务端注入 ctx.user.store_id,禁止前端传入。", "isNeedAuth": true, "isNeedLogin": true, "headers": [], From aacf9c8539cd58a55ec96eaa49fc3d912799d3a9 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sat, 22 Aug 2026 01:57:27 +0800 Subject: [PATCH 257/550] =?UTF-8?q?feat(storage):=20=E6=96=B0=E5=A2=9E?= =?UTF-8?q?=E6=8C=89=E5=95=86=E5=93=81=E6=9F=A5=E6=9C=89=E9=87=8F=E5=BA=93?= =?UTF-8?q?=E5=AD=98=E6=8E=A5=E5=8F=A3=E4=B8=8E=E5=BA=93=E5=AD=98=E5=88=97?= =?UTF-8?q?=E8=A1=A8=E9=9B=B6=E9=87=8F=E8=BF=87=E6=BB=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - listByStockId:传入 stock_id 返回 quantity>1 的库存,支持 group_by_space 双模式(逐条明细/按库位汇总) - 修复 store_stock 关联未按仓库收敛导致同 id 库存行重复返回,统一改用 buildStoreStockInclude - list/export 基础条件增加 quantity>0,过滤总数量为0的商品或明细行 - list 支持 where.stock_query 虚拟筛选(商品编码/名称/货物编码/条码/SKU ID 模糊匹配) - 重构 getInventoryList 明细分支:提取 _loadInventoryWarningRanges/_formatBatchStorageRows 复用 - 同步 methods/system.json 与 methods/changes/system.json 文档及变更记录 --- .../systemMethods/storage/inventory.js | 55 ++- app/service/systems/storage/inventory.js | 379 +++++++++++++++--- methods/changes/system.json | 77 ++++ methods/system.json | 71 +++- 4 files changed, 517 insertions(+), 65 deletions(-) diff --git a/app/service/systemMethods/storage/inventory.js b/app/service/systemMethods/storage/inventory.js index c4d3253..34857fe 100644 --- a/app/service/systemMethods/storage/inventory.js +++ b/app/service/systemMethods/storage/inventory.js @@ -13,9 +13,9 @@ class InventoryMethodService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'list,export,exportTaskProgress'; - const _noNeedLog = 'list,export,exportTaskProgress'; - const _noNeedAuth = 'list,quickPutaway,export,exportTaskProgress'; + const _noNeedRight = 'list,export,exportTaskProgress,listByStockId'; + const _noNeedLog = 'list,export,exportTaskProgress,listByStockId'; + const _noNeedAuth = 'list,quickPutaway,export,exportTaskProgress,listByStockId'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -48,10 +48,39 @@ class InventoryMethodService extends MainService { return this.success('ok', result); } + /** + * 提取 stock_query 虚拟筛选条件(与订单查询一致)。 + * 将其从 where 中移除并返回清洗后的 where 与 stock_query 关键字。 + * @param {Object} whereInput 原始 where 条件。 + * @return {{ where: Object, stockQuery: string }} 清洗后的 where 与 stock_query 值。 + */ + extractStockQueryVirtualFilter(whereInput = {}) { + const normalizedWhere = this.isPlainObject(whereInput) + ? { ...whereInput } + : {}; + const stockQueryCondition = normalizedWhere.stock_query; + + delete normalizedWhere.stock_query; + + if (!stockQueryCondition) { + return { where: normalizedWhere, stockQuery: '' }; + } + + const rawValue = this.isPlainObject(stockQueryCondition) + && Object.prototype.hasOwnProperty.call(stockQueryCondition, 'value') + ? stockQueryCondition.value + : stockQueryCondition; + + const stockQuery = typeof rawValue === 'string' ? rawValue.trim() : ''; + + return { where: normalizedWhere, stockQuery }; + } + /** * 库存列表查询(查 wms_storage),支持 where 条件、分页、排序、批次分组。 * @param {Object} data 请求体 * @param {Object} [data.where] 查询条件 + * @param {Object} [data.where.stock_query] 虚拟筛选字段:按商品编码(item_code)/名称(item_name)/货物编码(goods_code)/条码(barcode)/SKU ID 模糊匹配,如 { operator: 'like', value: '111' } * @param {Object} [data.pagination] 分页参数 { page, pageSize } * @param {Object} [data.sort] 排序参数 { sortField, sortOrder } * @param {boolean} [data.group_by_batch=false] 是否按批次查询 @@ -60,8 +89,26 @@ class InventoryMethodService extends MainService { async list(data = {}) { const { service } = this; const { pagination, sort, group_by_batch } = data; + const { where: cleanedWhere, stockQuery } = this.extractStockQueryVirtualFilter(data.where); + data.where = cleanedWhere; this.prepareWhereContext(data); - const result = await service.systems.storage.inventory.getInventoryList(pagination, sort, group_by_batch); + const result = await service.systems.storage.inventory.getInventoryList(pagination, sort, group_by_batch, stockQuery); + return this.success('ok', result); + } + + /** + * 按商品查询库存明细:传入 stock_id,返回该商品在当前仓库下所有数量大于 1 的 storage 行。 + * 支持两种模式:group_by_space=false 不汇总(逐条明细,含效期/预警字段,默认); + * group_by_space=true 按库位汇总数量(不含批次/效期/预警字段)。 + * @param {Object} data 请求体 + * @param {number} data.stock_id 商品SKU ID(必填) + * @param {boolean} [data.group_by_space=false] 是否按库位汇总 + * @return {Promise} 统一 success 包装 + */ + async listByStockId(data = {}) { + const { service } = this; + const groupBySpace = data.group_by_space === true || data.group_by_space === 'true'; + const result = await service.systems.storage.inventory.getStorageListByStockId(data.stock_id, groupBySpace); return this.success('ok', result); } diff --git a/app/service/systems/storage/inventory.js b/app/service/systems/storage/inventory.js index 7ee56a8..6fded1d 100644 --- a/app/service/systems/storage/inventory.js +++ b/app/service/systems/storage/inventory.js @@ -1152,6 +1152,64 @@ class InventoryService extends Service { } } + /** + * 根据商品快捷搜索关键字解析匹配的 stock_id 列表(仓库维度)。 + * 支持按商品编码(item_code)、商品名称(item_name)、货物编码(goods_code)、 + * 条码(barcode)、SKU ID(纯数字时精确匹配)模糊匹配。 + * + * @param {string} keyword 搜索关键字 + * @param {number} warehouseId 仓库ID + * @return {Promise} 匹配的 stock_id 列表 + */ + async resolveStockQueryToStockIds(keyword = '', warehouseId) { + const { ctx, app } = this; + const normalizedKeyword = String(keyword || '').trim(); + if (!normalizedKeyword || !warehouseId) { + return []; + } + + const likePattern = `%${normalizedKeyword}%`; + const exactStockId = /^\d+$/.test(normalizedKeyword) ? Number(normalizedKeyword) : null; + const extraIdCondition = exactStockId !== null ? 'OR sw.id = :exactStockId' : ''; + + const stockRows = await ctx.model.query(` + SELECT DISTINCT sw.id AS stock_id + FROM wms_stock_warehouse sw + WHERE sw.warehouse_id = :warehouseId + AND ( + sw.item_code LIKE :keyword + OR sw.item_name LIKE :keyword + OR sw.goods_code LIKE :keyword + ${extraIdCondition} + ) + `, { + replacements: { warehouseId, keyword: likePattern, exactStockId }, + type: app.Sequelize.QueryTypes.SELECT, + }); + + const barcodeRows = await ctx.model.query(` + SELECT DISTINCT sb.stock_id + FROM wms_stock_barcodes sb + INNER JOIN wms_stock_warehouse sw ON sw.id = sb.stock_id AND sw.warehouse_id = :warehouseId + WHERE sb.barcode LIKE :keyword + `, { + replacements: { warehouseId, keyword: likePattern }, + type: app.Sequelize.QueryTypes.SELECT, + }); + + const stockIdSet = new Set(); + for (const row of stockRows) { + const sid = Number(row.stock_id); + if (sid > 0) stockIdSet.add(sid); + } + for (const row of barcodeRows) { + const sid = Number(row.stock_id); + if (sid > 0) stockIdSet.add(sid); + } + + return [ ...stockIdSet ]; + } + /** * 查询库存列表。 * @@ -1165,9 +1223,10 @@ class InventoryService extends Service { * @param {string} [sortParams.sortField='created_at'] 排序字段(明细模式支持 wms_storage 真实列;汇总模式仅支持 quantity/locked_quantity/available_quantity/batch_count/first_inbound_time/last_inbound_time/production_date/expiry_date,其余回退 last_inbound_time) * @param {string} [sortParams.sortOrder='DESC'] 排序方向 * @param {boolean} [groupByBatch=false] 是否按批次明细返回 + * @param {string} [stockQuery=''] 商品快捷搜索关键字(来自 where.stock_query,按商品编码/名称/货物编码/条码/SKU ID 模糊匹配,解析为 stock_id 过滤) * @return {Promise<{list: Object[], pagination: {page: number, pageSize: number, total: number, totalPages: number}}>} 库存列表结果 */ - async getInventoryList(pageParams = {}, sortParams = {}, groupByBatch = false) { + async getInventoryList(pageParams = {}, sortParams = {}, groupByBatch = false, stockQuery = '') { const { ctx, app } = this; const { Op, fn, col, literal } = app.Sequelize; const nowMs = Date.now(); @@ -1188,6 +1247,8 @@ class InventoryService extends Service { { warehouse_id: warehouseId }, { is_enabled: 1 }, { delete_at: null }, + // 仅返回有量库存:明细模式过滤 quantity=0 的行,汇总模式过滤总量为 0 的商品 + { quantity: { [Op.gt]: 0 } }, ], }; @@ -1197,26 +1258,31 @@ class InventoryService extends Service { baseWhere[Op.and].push(...parsed.dynamicConditions); } + // stock_query 快捷搜索:按商品编码/名称/货物编码/条码/SKU ID 解析为 stock_id IN 条件 + const normalizedKeyword = String(stockQuery || '').trim(); + if (normalizedKeyword) { + const stockIds = await this.resolveStockQueryToStockIds(normalizedKeyword, warehouseId); + if (stockIds.length > 0) { + baseWhere[Op.and].push({ stock_id: { [Op.in]: stockIds } }); + } else { + // stock_query 无匹配结果,直接返回空列表 + return { + list: [], + pagination: { + page, + pageSize, + total: 0, + totalPages: 0, + }, + }; + } + } + const offset = (page - 1) * pageSize; const limit = pageSize; if (groupByBatch) { - let inventoryWarningRanges = []; - try { - const store = await ctx.model.Store.findByPk(warehouseId, { - attributes: [ 'id', 'subject_config' ], - }); - const normalizedSubjectConfig = ctx.model.Store.normalizeSubjectConfig( - store ? store.subject_config : null - ); - inventoryWarningRanges = buildInventoryWarningRanges( - normalizedSubjectConfig && Array.isArray(normalizedSubjectConfig.inventory_warning_rules) - ? normalizedSubjectConfig.inventory_warning_rules - : [] - ); - } catch (error) { - ctx.logger.warn(`[getInventoryList] 库存预警规则读取失败: ${error.message}`); - } + const inventoryWarningRanges = await this._loadInventoryWarningRanges(warehouseId, 'getInventoryList'); // 按批次明细:逐条返回 const { count: total, rows } = await ctx.model.Storage.findAndCountAll({ @@ -1239,12 +1305,11 @@ class InventoryService extends Service { 'remaining_threshold_days', ], include: [ - { - model: ctx.model.StoreWarehouse, - as: 'store_stock', - attributes: [ 'store_id', 'store_remask' ], + ctx.model.StoreWarehouse.buildStoreStockInclude({ + warehouseId, required: false, - }, + attributes: [ 'store_id', 'store_remask' ], + }), ], required: false, }, @@ -1257,34 +1322,7 @@ class InventoryService extends Service { ], }); - const list = rows.map(item => { - const row = item.get({ plain: true }); - const shelfLifeWarningState = getShelfLifeWarningState(row.stock || {}, row.expiry_date, nowMs); - const inventoryWarningPayload = getInventoryWarningPayload( - shelfLifeWarningState.remainingDays, - inventoryWarningRanges - ); - if (row.stock) { - row.stock.is_batch_mgmt_enabled = toBooleanFlag(row.stock.is_batch_mgmt); - row.stock.store_name = row.stock.store_stock?.store_remask || null; - delete row.stock.store_stock; - delete row.stock.is_batch_mgmt; - } - // 货主名称提升到根层级,便于前端直接使用 - row.store_name = row.stock?.store_name || null; - row.created_at = row.created_at ? app.formatDate(row.created_at) : ''; - row.updated_at = row.updated_at ? app.formatDate(row.updated_at) : ''; - row.inbound_time = row.inbound_time ? app.formatDate(row.inbound_time) : ''; - row.production_date = row.production_date ? app.formatDate(row.production_date) : ''; - row.expiry_date = row.expiry_date ? app.formatDate(row.expiry_date) : ''; - row.is_shelf_life_warning_triggered = shelfLifeWarningState.isTriggered; - row.expiry_remaining_days = inventoryWarningPayload.expiry_remaining_days; - row.inventory_warning_level = inventoryWarningPayload.inventory_warning_level; - row.inventory_warning_color = inventoryWarningPayload.inventory_warning_color; - row.inventory_warning_range = inventoryWarningPayload.inventory_warning_range; - row.inventory_warning_tip_text = inventoryWarningPayload.inventory_warning_tip_text; - return row; - }); + const list = this._formatBatchStorageRows(rows, inventoryWarningRanges, nowMs); await enrichInventoryStockAttachments(ctx, list); @@ -1342,12 +1380,11 @@ class InventoryService extends Service { 'remaining_threshold_days', ], include: [ - { - model: ctx.model.StoreWarehouse, - as: 'store_stock', - attributes: [ 'store_id', 'store_remask' ], + ctx.model.StoreWarehouse.buildStoreStockInclude({ + warehouseId, required: false, - }, + attributes: [ 'store_id', 'store_remask' ], + }), ], required: false, }, @@ -1386,6 +1423,236 @@ class InventoryService extends Service { }, }; } + + /** + * 按商品查询库存明细:返回指定 stock_id 下所有数量大于 1 的 storage 行。 + * 支持两种模式: + * - group_by_space=false(默认,不汇总):逐条返回明细,结构与 storage.inventory.list + * 明细模式一致(含批次/效期/库存预警字段); + * - group_by_space=true(按库位汇总):先筛 quantity > 1 的明细行,再按 space_id + * 汇总数量(quantity/locked_quantity/available_quantity),返回行含库位/商品信息, + * 不包含批次与效期/预警字段。 + * + * @param {number} stockId 商品SKU ID(wms_stock_warehouse.id,必填) + * @param {boolean} [groupBySpace=false] 是否按库位汇总 + * @return {Promise} code/message/data 结构,data 中为 { list: [...] } + */ + async getStorageListByStockId(stockId, groupBySpace = false) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + // ────────── 1. 参数校验 ────────── + const normalizedStockId = Number(stockId); + if (!Number.isInteger(normalizedStockId) || normalizedStockId <= 0) { + return { code: 400, message: 'stock_id 必填且必须为正整数', data: null }; + } + + const warehouseId = ctx.user && ctx.user.store_id; + if (!warehouseId) { + return { code: 400, message: '无法获取当前仓库信息', data: null }; + } + + // ────────── 2. 先筛 quantity > 1 的库存明细(两种模式共用同一查询) ────────── + const nowMs = Date.now(); + const inventoryWarningRanges = await this._loadInventoryWarningRanges(warehouseId, 'getStorageListByStockId'); + + const rows = await ctx.model.Storage.findAll({ + where: { + warehouse_id: warehouseId, + stock_id: normalizedStockId, + quantity: { [Op.gt]: 1 }, + is_enabled: 1, + delete_at: null, + }, + order: [[ 'id', 'DESC' ]], + include: [ + { + model: ctx.model.StockWarehouse, + as: 'stock', + attributes: [ + 'id', + 'item_code', + 'item_name', + 'sku_property', + 'stock_unit', + 'is_batch_mgmt', + 'is_shelf_life_mgmt', + 'remaining_threshold_days', + ], + include: [ + ctx.model.StoreWarehouse.buildStoreStockInclude({ + warehouseId, + required: false, + attributes: [ 'store_id', 'store_remask' ], + }), + ], + required: false, + }, + { + model: ctx.model.LocationSpace, + as: 'space', + attributes: [ 'id', 'space_code', 'custom_name' ], + required: false, + }, + ], + }); + + // ────────── 3. 按模式格式化返回 ────────── + if (groupBySpace) { + // 按库位汇总:汇总数量,不返回批次/效期/预警字段 + const list = this._aggregateStorageRowsBySpace(rows); + await enrichInventoryStockAttachments(ctx, list); + return { code: 200, message: 'ok', data: { list } }; + } + + // 不汇总:逐条明细(含效期/库存预警字段) + const list = this._formatBatchStorageRows(rows, inventoryWarningRanges, nowMs); + await enrichInventoryStockAttachments(ctx, list); + + return { + code: 200, + message: 'ok', + data: { list }, + }; + } + + /** + * 将库存明细行按库位(space_id)汇总:汇总 quantity/locked_quantity/available_quantity, + * 统计批次数并取最早/最晚入库时间。汇总行不含批次与效期字段,保留商品/库位关联信息。 + * + * @param {Array} rows Sequelize 实例数组(或 plain 对象数组) + * @return {Array} 按库位汇总后的数组 + */ + _aggregateStorageRowsBySpace(rows = []) { + const { app } = this; + const groupedMap = new Map(); + + for (const item of rows) { + const row = item && typeof item.get === 'function' ? item.get({ plain: true }) : item; + const spaceId = Number(row.space_id || 0); + const quantity = Number(row.quantity || 0); + const lockedQuantity = Number(row.locked_quantity || 0); + const availableQuantity = Number(row.available_quantity || 0); + const inboundTimeMs = row.inbound_time ? new Date(row.inbound_time).getTime() : null; + + const existing = groupedMap.get(spaceId); + if (!existing) { + groupedMap.set(spaceId, { + warehouse_id: row.warehouse_id, + store_id: row.store_id, + space_id: spaceId, + stock_id: row.stock_id, + quantity, + locked_quantity: lockedQuantity, + available_quantity: availableQuantity, + batch_count: 1, + first_inbound_time: inboundTimeMs, + last_inbound_time: inboundTimeMs, + stock: row.stock || null, + space: row.space || null, + }); + continue; + } + + existing.quantity += quantity; + existing.locked_quantity += lockedQuantity; + existing.available_quantity += availableQuantity; + existing.batch_count += 1; + if (inboundTimeMs !== null && (existing.first_inbound_time === null || inboundTimeMs < existing.first_inbound_time)) { + existing.first_inbound_time = inboundTimeMs; + } + if (inboundTimeMs !== null && (existing.last_inbound_time === null || inboundTimeMs > existing.last_inbound_time)) { + existing.last_inbound_time = inboundTimeMs; + } + } + + return [ ...groupedMap.values() ].map(row => { + const formatted = { ...row }; + if (formatted.stock) { + formatted.stock = { + ...formatted.stock, + is_batch_mgmt_enabled: toBooleanFlag(formatted.stock.is_batch_mgmt), + store_name: formatted.stock.store_stock?.store_remask || null, + }; + delete formatted.stock.store_stock; + delete formatted.stock.is_batch_mgmt; + } + // 货主名称提升到根层级,便于前端直接使用 + formatted.store_name = formatted.stock?.store_name || null; + formatted.first_inbound_time = formatted.first_inbound_time ? app.formatDate(formatted.first_inbound_time) : ''; + formatted.last_inbound_time = formatted.last_inbound_time ? app.formatDate(formatted.last_inbound_time) : ''; + return formatted; + }); + } + + /** + * 读取当前仓库货主配置中的库存预警规则,并转换为按到期天数递增的区间配置。 + * + * @param {number} warehouseId 仓库ID(货主ID) + * @param {string} logTag 日志标记 + * @return {Promise>} 库存预警规则区间列表 + */ + async _loadInventoryWarningRanges(warehouseId, logTag = 'storage.inventory') { + const { ctx } = this; + try { + const store = await ctx.model.Store.findByPk(warehouseId, { + attributes: [ 'id', 'subject_config' ], + }); + const normalizedSubjectConfig = ctx.model.Store.normalizeSubjectConfig( + store ? store.subject_config : null + ); + return buildInventoryWarningRanges( + normalizedSubjectConfig && Array.isArray(normalizedSubjectConfig.inventory_warning_rules) + ? normalizedSubjectConfig.inventory_warning_rules + : [] + ); + } catch (error) { + ctx.logger.warn(`[${logTag}] 库存预警规则读取失败: ${error.message}`); + return []; + } + } + + /** + * 将库存批次明细查询结果整理为接口返回格式: + * 货主名称提升、批次管理标记布尔化、日期格式化、效期与库存预警字段填充。 + * + * @param {Array} rows Sequelize 实例数组(或 plain 对象数组) + * @param {Array} inventoryWarningRanges 库存预警规则区间 + * @param {number} nowMs 当前时间戳 + * @return {Array} 格式化后的明细数组 + */ + _formatBatchStorageRows(rows = [], inventoryWarningRanges = [], nowMs = Date.now()) { + const { app } = this; + return rows.map(item => { + const row = item && typeof item.get === 'function' ? item.get({ plain: true }) : item; + const shelfLifeWarningState = getShelfLifeWarningState(row.stock || {}, row.expiry_date, nowMs); + const inventoryWarningPayload = getInventoryWarningPayload( + shelfLifeWarningState.remainingDays, + inventoryWarningRanges + ); + if (row.stock) { + row.stock.is_batch_mgmt_enabled = toBooleanFlag(row.stock.is_batch_mgmt); + row.stock.store_name = row.stock.store_stock?.store_remask || null; + delete row.stock.store_stock; + delete row.stock.is_batch_mgmt; + } + // 货主名称提升到根层级,便于前端直接使用 + row.store_name = row.stock?.store_name || null; + row.created_at = row.created_at ? app.formatDate(row.created_at) : ''; + row.updated_at = row.updated_at ? app.formatDate(row.updated_at) : ''; + row.inbound_time = row.inbound_time ? app.formatDate(row.inbound_time) : ''; + row.production_date = row.production_date ? app.formatDate(row.production_date) : ''; + row.expiry_date = row.expiry_date ? app.formatDate(row.expiry_date) : ''; + row.is_shelf_life_warning_triggered = shelfLifeWarningState.isTriggered; + row.expiry_remaining_days = inventoryWarningPayload.expiry_remaining_days; + row.inventory_warning_level = inventoryWarningPayload.inventory_warning_level; + row.inventory_warning_color = inventoryWarningPayload.inventory_warning_color; + row.inventory_warning_range = inventoryWarningPayload.inventory_warning_range; + row.inventory_warning_tip_text = inventoryWarningPayload.inventory_warning_tip_text; + return row; + }); + } + /** * 收货单快捷入库:判断货主配置是否允许收货单快捷入库,不允许直接返回失败; * 允许的话使用收货单的明细创建入库单,相同 stock_id 的合并为一条,汇集总数。 @@ -1707,6 +1974,8 @@ class InventoryService extends Service { { warehouse_id: warehouseId }, { is_enabled: 1 }, { delete_at: null }, + // 仅导出有量库存:明细模式过滤 quantity=0 的行,汇总模式过滤总量为 0 的商品 + { quantity: { [Op.gt]: 0 } }, ], }; diff --git a/methods/changes/system.json b/methods/changes/system.json index c70c931..c646a1c 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,66 @@ [ + { + "version": "2026.08.22-storage.inventory.list-filter-zero-quantity", + "date": "2026-08-22", + "type": "enhanced", + "summary": "storage.inventory.list 过滤总数量为 0 的商品或明细行:基础查询条件增加 quantity > 0,明细模式(group_by_batch=true)不再返回 quantity=0 的明细行,合并模式(group_by_batch=false)不再返回总数量为 0 的商品。storage.inventory.export 同步保持一致。", + "methods": [ + "storage.inventory.list", + "storage.inventory.export" + ], + "notes": [ + "app/service/systems/storage/inventory.js:getInventoryList 与 exportInventoryList 的 baseWhere 均增加 { quantity: { [Op.gt]: 0 } },动态 where/stock_query 条件不受影响", + "明细模式:quantity=0 的 storage 行直接过滤;合并模式:某商品所有明细行均无正数量时分组自然消失,总量为 0 的商品不返回", + "storage.inventory.export 入参与 list 语义保持一致(导出同样过滤零量行/零量商品)" + ], + "module": "storage.inventory" + }, + { + "version": "2026.08.22-storage.inventory.listByStockId-group-by-space", + "date": "2026-08-22", + "type": "enhanced", + "summary": "storage.inventory.listByStockId 新增 group_by_space 双模式:false(默认,不汇总)逐条返回 quantity > 1 明细行(含批次/效期/预警字段,行为不变);true(按库位汇总)先筛 quantity > 1 明细行,再按 space_id 汇总 quantity/locked_quantity/available_quantity,返回库位级汇总行(含 batch_count、first/last_inbound_time、stock/space/store_name),不含批次与效期/预警字段。", + "methods": [ + "storage.inventory.listByStockId" + ], + "notes": [ + "app/service/systems/storage/inventory.js:getStorageListByStockId(stockId, groupBySpace=false) 两种模式共用同一查询(先筛 quantity > 1 明细行),group_by_space=true 时用新增 _aggregateStorageRowsBySpace 按 space_id 在内存汇总(求和、批次数、最早/最晚入库时间),并保留商品/库位关联与条码图片附属信息", + "app/service/systemMethods/storage/inventory.js:listByStockId 透传 group_by_space(支持 true/'true' 布尔/字符串)", + "汇总口径:先筛 quantity > 1 的明细行再按库位求和;汇总行不返回批次与效期/库存预警字段" + ], + "module": "storage.inventory" + }, + { + "version": "2026.08.22-storage.inventory.store-stock-join-dedup", + "date": "2026-08-22", + "type": "fixed", + "summary": "修复库存接口按 stock_id 查询返回重复 storage 行(同 id 多条)的问题:store_stock 关联(belongsTo StoreWarehouse,按 store_id 关联)未按仓库收敛,货主在多仓库存在签约行时 JOIN 多行匹配导致同一库存行重复且 store_name 不一致。改为统一使用 StoreWarehouse.buildStoreStockInclude(按 warehouse_id + warehouse_use_status=1 收敛,命中唯一签约行)。", + "methods": [ + "storage.inventory.listByStockId", + "storage.inventory.list" + ], + "notes": [ + "app/service/systems/storage/inventory.js:getStorageListByStockId、getInventoryList(明细模式与合并模式)三处 store_stock 嵌套 include 均改为 buildStoreStockInclude({ warehouseId, required: false, attributes: ['store_id','store_remask'] })", + "wms_store_warehouse 存在 (store_id, warehouse_id) 唯一索引,按仓库收敛后每商品至多命中一行签约关系,不再产生重复明细;合并模式下 SUM(quantity) 也不会因 JOIN 多行而翻倍", + "同时修正 storage.inventory.list 同源隐患(明细模式重复行、合并模式数量翻倍),返回结构不变" + ], + "module": "storage.inventory" + }, + { + "version": "2026.08.22-storage.inventory.listByStockId", + "date": "2026-08-22", + "type": "added", + "summary": "新增 storage.inventory.listByStockId 接口:传入 stock_id,返回该商品在当前仓库下所有 quantity > 1 的 wms_storage 明细行(按 id 倒序),返回结构与 storage.inventory.list 明细模式一致(含 stock 条码/图片、space 库位、货主名称及效期/库存预警字段)。", + "methods": [ + "storage.inventory.listByStockId" + ], + "notes": [ + "app/service/systemMethods/storage/inventory.js 新增 listByStockId 包装方法,并加入 _noNeedRight/_noNeedLog/_noNeedAuth 豁免列表(与 list 一致)", + "app/service/systems/storage/inventory.js 新增 getStorageListByStockId:校验 stock_id 正整数与当前仓库上下文,where 条件 warehouse_id+stock_id+quantity>1+is_enabled=1+delete_at=null,include stock/space 与明细模式一致", + "重构 getInventoryList 明细分支:提取 _loadInventoryWarningRanges 与 _formatBatchStorageRows 复用,现有 storage.inventory.list 行为不变" + ], + "module": "storage.inventory" + }, { "version": "2026.08.21-returnUnpack.create-orderItems", "date": "2026-08-21", @@ -6639,5 +6701,20 @@ "仅文档变更,无业务代码修改" ], "module": "storeWarehouse" + }, + { + "version": "2026.08.21-storage.inventory.list-stock-query", + "date": "2026-08-21", + "type": "updated", + "summary": "storage.inventory.list 新增 where.stock_query 虚拟筛选:按商品编码/名称/货物编码/条码/SKU ID 模糊匹配库存列表", + "methods": [ + "storage.inventory.list" + ], + "notes": [ + "与订单查询一致的 stock_query 虚拟筛选字段,如 where.stock_query = { operator: 'like', value: '111' }。", + "解析链路:stock_query → wms_stock_warehouse(item_code/item_name/goods_code/纯数字精确 id)+ wms_stock_barcodes(barcode)→ stock_id 集合 → wms_storage.stock_id IN 过滤;无匹配时返回空列表。", + "代码变更:systemMethods/storage/inventory.js#list 新增 extractStockQueryVirtualFilter(从 where 提取并移除 stock_query);systems/storage/inventory.js#getInventoryList 新增 stockQuery 参数与 resolveStockQueryToStockIds;methods/system.json 同步 where 参数文档(export 注明暂不支持 stock_query)。" + ], + "module": "storage" } ] diff --git a/methods/system.json b/methods/system.json index e22ef73..0be23eb 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1,8 +1,8 @@ { "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", - "version": "0.3.32", - "updatedAt": "2026-08-19", + "version": "0.3.35", + "updatedAt": "2026-08-22", "headers": [ { "name": "platform", @@ -23633,7 +23633,7 @@ }, { "method": "storage.inventory.list", - "description": "库存列表查询(查 wms_storage),支持 where 条件、分页、排序、批次分组。默认按库位+商品合并数量(合并模式),group_by_batch=true 时返回每条库存明细(明细模式)", + "description": "库存列表查询(查 wms_storage),支持 where 条件、分页、排序、批次分组。默认按库位+商品合并数量(合并模式),group_by_batch=true 时返回每条库存明细(明细模式)。仅返回有量库存:明细模式过滤 quantity=0 的行,合并模式过滤总数量为 0 的商品。", "name": "库存列表", "isNeedAuth": false, "isNeedLogin": true, @@ -23644,7 +23644,7 @@ "type": "object", "required": false, "source": "body", - "description": "统一 where 条件对象,可用字段:stock_id(商品ID)、space_id(库位ID)、store_id(货主ID)、inventory_type(ZP/CC/JS/XS/ZT/DJ/FP)、batch_no(批次号)、inbound_order_no(入库单号)、available_quantity(可用数量,支持 gt/lt)、inbound_time(入库时间,支持 between)、created_at(创建时间,支持 between)" + "description": "统一 where 条件对象,可用字段:stock_id(商品ID)、space_id(库位ID)、store_id(货主ID)、inventory_type(ZP/CC/JS/XS/ZT/DJ/FP)、batch_no(批次号)、inbound_order_no(入库单号)、available_quantity(可用数量,支持 gt/lt)、inbound_time(入库时间,支持 between)、created_at(创建时间,支持 between)、stock_query(虚拟筛选字段:按商品编码/名称/货物编码/条码/SKU ID 模糊匹配,如 { operator: 'like', value: '111' })" }, { "name": "pagination", @@ -23754,7 +23754,7 @@ }, { "method": "storage.inventory.export", - "description": "提交库存导出异步任务。支持两种导出模式(exportMode):stock_location(默认,按 stock_id + 库位聚合导出库存汇总,含库位编码/名称、商品信息、总库存/锁定/可用、批次数、最近入库时间等)、storage(按 storage_id 逐条导出库存明细,含库位编码/名称、商品信息、批次号、库存类型、数量、生产日期、过期日期、入库单号等)。立即返回任务受理信息(task_id/status/progress),不直接返回文件。通过 storage.inventory.exportTaskProgress 查询进度并获取下载地址。", + "description": "提交库存导出异步任务。支持两种导出模式(exportMode):stock_location(默认,按 stock_id + 库位聚合导出库存汇总,含库位编码/名称、商品信息、总库存/锁定/可用、批次数、最近入库时间等)、storage(按 storage_id 逐条导出库存明细,含库位编码/名称、商品信息、批次号、库存类型、数量、生产日期、过期日期、入库单号等)。立即返回任务受理信息(task_id/status/progress),不直接返回文件。通过 storage.inventory.exportTaskProgress 查询进度并获取下载地址。仅导出有量库存(与 storage.inventory.list 一致):明细模式过滤 quantity=0 的行,合并模式过滤总数量为 0 的商品。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -23771,7 +23771,7 @@ "type": "object", "required": false, "source": "body", - "description": "统一 where 条件对象,与 storage.inventory.list 的 where 语义完全一致。支持字段:stock_id(商品ID)、space_id(库位ID)、store_id(货主ID)、inventory_type(ZP/CC/JS/XS/ZT/DJ/FP)、batch_no(批次号)、inbound_order_no(入库单号)、available_quantity(可用数量,支持 gt/lt)、inbound_time(入库时间,支持 between)、created_at(创建时间,支持 between)" + "description": "统一 where 条件对象,与 storage.inventory.list 的 where 语义完全一致(暂不支持 stock_query 虚拟筛选)。支持字段:stock_id(商品ID)、space_id(库位ID)、store_id(货主ID)、inventory_type(ZP/CC/JS/XS/ZT/DJ/FP)、batch_no(批次号)、inbound_order_no(入库单号)、available_quantity(可用数量,支持 gt/lt)、inbound_time(入库时间,支持 between)、created_at(创建时间,支持 between)" }, { "name": "sort", @@ -24164,6 +24164,65 @@ "message": "分页参数不合法" } ] + }, + { + "method": "storage.inventory.listByStockId", + "name": "按商品查询有量库存明细", + "description": "按商品查询库存明细:传入 stock_id,返回该商品在当前仓库下所有数量大于 1(quantity > 1)的 wms_storage 明细行。支持两种模式:group_by_space=false(默认,不汇总)逐条返回明细,结构与 storage.inventory.list 明细模式(group_by_batch=true)一致,含批次字段(batch_no/inventory_type/quantity/locked_quantity/available_quantity/production_date/expiry_date/inbound_time/inbound_order_no/receiving_id/entry_order_id/supplier_id/supplier_batch_no 等)、stock(商品信息,含 barcodes/images 附属信息)、space(库位信息)、store_name(货主名称,来源于当前仓库签约表 store_remask)以及效期/库存预警字段;group_by_space=true(按库位汇总)先筛 quantity > 1 的明细行,再按 space_id 汇总 quantity/locked_quantity/available_quantity,返回行含库位/商品信息与 batch_count、first_inbound_time、last_inbound_time,不含批次与效期/预警字段。仓库上下文来自当前登录用户(ctx.user.store_id)。", + "isNeedAuth": false, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [], + "params": [ + { + "name": "stock_id", + "type": "number", + "required": true, + "source": "body", + "description": "商品SKU ID(wms_stock_warehouse.id,必填)" + }, + { + "name": "group_by_space", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否按库位汇总,默认 false。false=不汇总(逐条明细);true=按库位汇总(先筛 quantity > 1 明细行,再按 space_id 求和)" + } + ], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "状态码,200=成功" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "结果说明" + }, + { + "name": "data.list", + "type": "array", + "required": true, + "description": "库存数组(quantity > 1,按 id 倒序)。group_by_space=false 时为明细行,每项字段:id、warehouse_id、store_id、space_id、stock_id、batch_no、inventory_type、quantity、locked_quantity、available_quantity、production_date、expiry_date、inbound_time、inbound_order_no、receiving_id、entry_order_id、supplier_id、supplier_batch_no、is_enabled、created_at、updated_at、delete_at;stock 对象(id/item_code/item_name/sku_property/stock_unit/is_shelf_life_mgmt/remaining_threshold_days/is_batch_mgmt_enabled/store_name/barcodes/images);space 对象(id/space_code/custom_name);顶层 store_name(货主名称);is_shelf_life_warning_triggered(效期预警是否触发);expiry_remaining_days/inventory_warning_level/inventory_warning_color/inventory_warning_range/inventory_warning_tip_text(库存预警字段,无预警时为 null)。group_by_space=true 时为按库位汇总行,每项字段:warehouse_id、store_id、space_id、stock_id、quantity/locked_quantity/available_quantity(汇总值)、batch_count(批次数)、first_inbound_time(最早入库时间)、last_inbound_time(最晚入库时间)、stock 对象、space 对象、顶层 store_name;不含批次与效期/预警字段" + } + ], + "errors": [ + { + "code": 400, + "message": "stock_id 必填且必须为正整数" + }, + { + "code": 400, + "message": "无法获取当前仓库信息" + }, + { + "code": 500, + "message": "系统异常" + } + ] } ] }, From b3bdb566c4f111ff05b96120c597c13ed91a67b4 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sat, 22 Aug 2026 17:22:21 +0800 Subject: [PATCH 258/550] =?UTF-8?q?fix(stock):=20=E4=BF=AE=E5=A4=8D=20ware?= =?UTF-8?q?house.import=20=E6=9D=A1=E7=A0=81=E4=B8=8D=E7=94=9F=E6=95=88?= =?UTF-8?q?=EF=BC=8C=E8=A1=A5=E5=B7=AE=E5=BC=82=E5=90=8C=E6=AD=A5=20wms=5F?= =?UTF-8?q?stock=5Fbarcodes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 创建/更新成功后,若归一化 barcode 为非空数组,调用 saveWarehouseStockBarcode 同步条码 - 条码同步失败计入该行 fail_items;未传条码不触发同步,避免误清空已有条码 --- app/service/systemMethods/stock/warehouse.js | 18 +++++++++++++++++- methods/changes/system.json | 15 +++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/app/service/systemMethods/stock/warehouse.js b/app/service/systemMethods/stock/warehouse.js index b06a05b..3479ff6 100644 --- a/app/service/systemMethods/stock/warehouse.js +++ b/app/service/systemMethods/stock/warehouse.js @@ -651,6 +651,23 @@ class WarehouseService extends MainService { if (hasSku) { result = await service.systems.stockStore.saveWarehouseStock(normalizedRow); + } else { + result = await service.systems.stockStore.createWarehouseStock(normalizedRow); + } + + // 条码同步:仅当传入非空条码时写入 wms_stock_barcodes 表(未传条码则保留原有条码) + const barcodes = Array.isArray(normalizedRow.barcode) ? normalizedRow.barcode : []; + if (barcodes.length > 0) { + const stockId = (result && result.id != null) ? result.id : normalizedRow.id; + if (stockId != null) { + await service.systems.stockStore.saveWarehouseStockBarcode({ + id: stockId, + barcodes, + }); + } + } + + if (hasSku) { summary.updated_count += 1; if (result && result.id != null) { summary.updated_ids.push(result.id); @@ -658,7 +675,6 @@ class WarehouseService extends MainService { summary.updated_ids.push(normalizedRow.id); } } else { - result = await service.systems.stockStore.createWarehouseStock(normalizedRow); summary.created_count += 1; if (result && result.id != null) { summary.created_ids.push(result.id); diff --git a/methods/changes/system.json b/methods/changes/system.json index c646a1c..d95a8df 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,19 @@ [ + { + "version": "2026.08.22-stock.warehouse.import-barcode-sync", + "date": "2026-08-22", + "type": "fixed", + "summary": "修复 stock.warehouse.import 传入 barcode(条码)不生效的问题:归一化后条码未在新建/更新路径写入 wms_stock_barcodes 表。现在导入行携带非空 barcode 时,在商品创建/更新成功后调用 saveWarehouseStockBarcode 差异同步条码(未传条码则保留原有条码)。", + "methods": [ + "stock.warehouse.import" + ], + "notes": [ + "app/service/systemMethods/stock/warehouse.js import():创建/更新成功后,若归一化 barcode 为非空数组,则按结果 id(缺省用行内 SKU)调用 systems.stockStore.saveWarehouseStockBarcode 同步到 wms_stock_barcodes 表", + "条码同步失败计入该行 fail_items,且该行不再计入成功计数,便于定位", + "未传 barcode(空数组)时不触发同步,避免误清空已有条码;barcode 格式与导出对齐(逗号分隔字符串)" + ], + "module": "stock.warehouse" + }, { "version": "2026.08.22-storage.inventory.list-filter-zero-quantity", "date": "2026-08-22", From 37b9a3d30db7235038b6503aac00344574add356 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sat, 22 Aug 2026 17:22:27 +0800 Subject: [PATCH 259/550] =?UTF-8?q?fix(express):=20polyapi=20=E5=8F=96?= =?UTF-8?q?=E5=8F=B7=E8=AE=A2=E5=8D=95ID=E6=94=B9=20Hex16=20=E6=8F=90?= =?UTF-8?q?=E4=BA=A4=E5=B9=B6=E5=9B=9E=E4=BC=A0=E8=A7=A3=E7=A0=81=EF=BC=8C?= =?UTF-8?q?=E4=BF=AE=E5=A4=8D=20ESLint?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - object_Id/orderno 中 order.id 改为 16 进制编码,缩短订单唯一标识字符串 - 失败项/各平台成功回写分支按 parseInt(x,16) 解码回十进制,保持落库与映射兼容 - 修复本文件 31 处 ESLint(空格/引号/注释等),纯格式不涉及业务逻辑 --- app/service/systems/express_platform.js | 91 +++++++++++-------- .../systems/express_platform.cainiao.test.js | 51 +++++++++++ .../express_platform.pdd.ext_data.test.js | 59 +++++++++++- .../systems/express_platform.polyapi.test.js | 56 +++++++++++- 4 files changed, 212 insertions(+), 45 deletions(-) diff --git a/app/service/systems/express_platform.js b/app/service/systems/express_platform.js index 4cb4879..e0d2f67 100644 --- a/app/service/systems/express_platform.js +++ b/app/service/systems/express_platform.js @@ -704,13 +704,13 @@ class ExpressPlatformService extends MainService { console.log('order', order); const expressListItem = ExpressList.find(item => item.code === listByWarehousePlatformCode.sys_express_code) || {}; let plattradeno = order.source_order_codes; - if(listByWarehousePlatformCode.platform_code === 'DY' && order.from_key === 23060081 && !!order.pay_no && plattradeno.indexOf(",") > -1){ + if (listByWarehousePlatformCode.platform_code === 'DY' && order.from_key === 23060081 && !!order.pay_no && plattradeno.indexOf(',') > -1) { plattradeno = order.pay_no; } let playload = { - object_Id: `${order.warehouse_id.toString(16)}_${order.id}_${order_tmp.business_key}`, // 菠萝派平台要求订单唯一标识必须为字符串 - orderno: `${order.warehouse_id.toString(16)}_${order.id}_${order_tmp.business_key}`, // 菠萝派平台要求订单号必须为字符串 - plattradeno: plattradeno, + object_Id: `${order.warehouse_id.toString(16)}_${Number(order.id || 0).toString(16)}_${order_tmp.business_key}`, // 菠萝派平台要求订单唯一标识必须为字符串 + orderno: `${order.warehouse_id.toString(16)}_${Number(order.id || 0).toString(16)}_${order_tmp.business_key}`, // 菠萝派平台要求订单号必须为字符串 + plattradeno, tid: plattradeno, ismultiplepieces: order.package_count > 1 ? 1 : 0, logisticno: allocatedWaybillMap.get(`${Number(order.id) || 0}:${Number(order_tmp.business_key) || 0}`) || '', @@ -718,13 +718,13 @@ class ExpressPlatformService extends MainService { providercode: expressListItem[listByWarehousePlatformCode.platform_code] || order.logistics_code || '', numpackage: order.package_count || '1', businesstype: listByWarehousePlatformCode.product_type, - transtype:'0', - transtypecode:'1', - mainsubpaymode:'1', + transtype: '0', + transtypecode: '1', + mainsubpaymode: '1', businessplat: order.sys_platform_code === 'KS' ? order.sys_platform_code : 'OTHERS', - paymode: '1', + paymode: '1', ordertype: listByWarehousePlatformCode.ordertype ?? 'JH_Normal', - ProviderID:'', + ProviderID: '', procode: order.procode || '普通商品', codpaymoney: order.ar_amount ?? null, packagemoney: order.item_amount ?? null, @@ -744,16 +744,16 @@ class ExpressPlatformService extends MainService { brandno: listByWarehousePlatformCode.brandno || null, needencrypt: 1, ordertime: order.place_order_time || '', - customername:"测试", + customername: '测试', ordersource: matchedPlatform.ordersource || '', - inputsite: order.sys_platform_code === 'XHS' ? '' :listByWarehousePlatformCode.site_code || '', + inputsite: order.sys_platform_code === 'XHS' ? '' : listByWarehousePlatformCode.site_code || '', sitecode: listByWarehousePlatformCode.site_code || '', - shipperno: order.sys_platform_code === 'XHS' ? '' :listByWarehousePlatformCode.shipperno || '', - customercode: order.sys_platform_code === 'XHS' ? '' :listByWarehousePlatformCode.shipperno || listByWarehousePlatformCode.client_id || '', + shipperno: order.sys_platform_code === 'XHS' ? '' : listByWarehousePlatformCode.shipperno || '', + customercode: order.sys_platform_code === 'XHS' ? '' : listByWarehousePlatformCode.shipperno || listByWarehousePlatformCode.client_id || '', sender: { Company: listByWarehousePlatformCode.shop_name || '', name: listByWarehousePlatformCode.sender_name || '', - phone: order.sys_platform_code === 'XHS' ? undefined :listByWarehousePlatformCode.sender_tel || '', + phone: order.sys_platform_code === 'XHS' ? undefined : listByWarehousePlatformCode.sender_tel || '', mobile: order.sys_platform_code === 'XHS' ? listByWarehousePlatformCode.sender_tel : undefined, country: 'CN', city: listByWarehousePlatformCode.city_name || '', @@ -782,7 +782,7 @@ class ExpressPlatformService extends MainService { cnname: 'sp', count: item.plan_qty || 0, }))) || [], - //Mallmaskid: '', + // Mallmaskid: '', template_url: listByWarehousePlatformCode.template_id || '', labelformat: listByWarehousePlatformCode.labelformat || '', @@ -793,7 +793,7 @@ class ExpressPlatformService extends MainService { if (Number(matchedPlatform.platid) === 673) { playload.BizVersion = '2'; - playload.brandno = listByWarehousePlatformCode.brandno === "SF" ? listByWarehousePlatformCode.brandno : undefined; + playload.brandno = listByWarehousePlatformCode.brandno === 'SF' ? listByWarehousePlatformCode.brandno : undefined; } if (Number(matchedPlatform.platid) === 544) { const { @@ -845,13 +845,13 @@ class ExpressPlatformService extends MainService { orderno, plattradeno, ProductType, - businesstype:ProductType, + businesstype: ProductType, expresstype: ProductType, logistictype, providercode: providercode || cpcode || logistictype || '', numpackage, businessplat, - platcode:plattradeno, + platcode: plattradeno, mainsubpaymode: '1', ordertype, businessType: businessType || ordertype || 'JH_Normal', @@ -866,7 +866,7 @@ class ExpressPlatformService extends MainService { customername, goods, oaid, - customercode: logistictype==="SF" ? undefined: customercode || shipperno || listByWarehousePlatformCode.shipperno || listByWarehousePlatformCode.client_id || '', + customercode: logistictype === 'SF' ? undefined : customercode || shipperno || listByWarehousePlatformCode.shipperno || listByWarehousePlatformCode.client_id || '', sender: { name: senderName, phone: senderPhoneRaw, @@ -908,7 +908,7 @@ class ExpressPlatformService extends MainService { playload.mainsubpaymode = '1'; delete playload.plattradeno; } - playload.ProviderID = listByWarehousePlatformCode.providerid || ""; + playload.ProviderID = listByWarehousePlatformCode.providerid || ''; console.log('playload', playload); return playload; }), @@ -973,8 +973,8 @@ class ExpressPlatformService extends MainService { for (const [ groupReason, groupItems ] of reasonGroups) { const itemFailedOrders = []; for (const failedItem of groupItems) { - const [ , order_id, business_key ] = String(failedItem.orderno || '').split('_'); - const orderId = Number(order_id) || 0; + const [ , order_id_hex, business_key ] = String(failedItem.orderno || '').split('_'); + const orderId = parseInt(order_id_hex, 16) || 0; const businessKey = Number(business_key) || 0; if (!orderId || !businessKey) continue; @@ -1017,8 +1017,9 @@ class ExpressPlatformService extends MainService { switch (listByWarehousePlatformCode.platform_code) { case 'KS': successUpdates = (result.results || []).map(item => { - const [ warehouse_id_hex, order_id, business_key ] = String(item.orderno || '').split('_'); + const [ warehouse_id_hex, order_id_hex, business_key ] = String(item.orderno || '').split('_'); const warehouse_id = parseInt(warehouse_id_hex, 16); + const order_id = parseInt(order_id_hex, 16) || 0; const waybillCode = resolveWaybillCode(item); return { warehouse_id, @@ -1053,8 +1054,9 @@ class ExpressPlatformService extends MainService { break; case 'DY': successUpdates = (result.results || []).map(item => { - const [ warehouse_id_hex, order_id, business_key ] = String(item.orderno || '').split('_'); + const [ warehouse_id_hex, order_id_hex, business_key ] = String(item.orderno || '').split('_'); const warehouse_id = parseInt(warehouse_id_hex, 16); + const order_id = parseInt(order_id_hex, 16) || 0; const waybillCode = resolveWaybillCode(item); return { @@ -1088,7 +1090,6 @@ class ExpressPlatformService extends MainService { }); break; case 'JD':{ - const batchPrintSipshopid = String(listByWarehousePlatformCode.platform_shop_id || '0'); const batchPrintOrders = (result.results || []).map(item => ({ orderno: String(item.orderno), logisticno: String(item.logisticno), @@ -1115,7 +1116,7 @@ class ExpressPlatformService extends MainService { receivertel: '', cargoname: '', senddata: '', - //weight: '', + // weight: '', eCustomerCode: '', remark: '', selleruserid: '', @@ -1155,8 +1156,9 @@ class ExpressPlatformService extends MainService { successUpdates = (batchPrintResult && batchPrintResult.results || []).map(item => { const objectId = String(item && item.orderno || '').trim(); - const [ warehouse_id_hex, order_id, business_key ] = objectId.split('_'); + const [ warehouse_id_hex, order_id_hex, business_key ] = objectId.split('_'); const warehouse_id = parseInt(warehouse_id_hex, 16); + const order_id = parseInt(order_id_hex, 16) || 0; const waybillCode = String(item && (item.logisticno || item.waybill_code) || '').trim(); const rawPrintData = item && Object.prototype.hasOwnProperty.call(item, 'printdata') ? item.printdata @@ -1207,8 +1209,9 @@ class ExpressPlatformService extends MainService { } case 'XHS':{ successUpdates = (result.results || []).map(item => { - const [ warehouse_id_hex, order_id, business_key ] = String(item.orderno || '').split('_'); + const [ warehouse_id_hex, order_id_hex, business_key ] = String(item.orderno || '').split('_'); const warehouse_id = parseInt(warehouse_id_hex, 16); + const order_id = parseInt(order_id_hex, 16) || 0; const waybillCode = resolveWaybillCode(item); const printInfo = item.print_info ?? item.printinfo; return { @@ -1250,8 +1253,9 @@ class ExpressPlatformService extends MainService { if (!objectId || objectIdParts.length < 3) { throw new Error(`视频号取号返回 object_id 无法解析: ${objectId || JSON.stringify(item)}`); } - const [ warehouse_id_hex, order_id, business_key ] = objectIdParts; + const [ warehouse_id_hex, order_id_hex, business_key ] = objectIdParts; const warehouse_id = parseInt(warehouse_id_hex, 16); + const order_id = parseInt(order_id_hex, 16) || 0; const waybillCode = resolveWaybillCode(item); const rawPrintData = item && Object.prototype.hasOwnProperty.call(item, 'raw') ? item.raw @@ -1313,8 +1317,9 @@ class ExpressPlatformService extends MainService { } case 'PDD': successUpdates = (result.results || []).map(item => { - const [ warehouse_id_hex, order_id, business_key ] = String(item.orderno || '').split('_'); + const [ warehouse_id_hex, order_id_hex, business_key ] = String(item.orderno || '').split('_'); const warehouse_id = parseInt(warehouse_id_hex, 16); + const order_id = parseInt(order_id_hex, 16) || 0; const waybillCode = resolveWaybillCode(item); return { warehouse_id, @@ -1349,8 +1354,9 @@ class ExpressPlatformService extends MainService { case 'QT': case 'OTHER': successUpdates = (result.results || []).map(item => { - const [ warehouse_id_hex, order_id, business_key ] = String(item.orderno || '').split('_'); + const [ warehouse_id_hex, order_id_hex, business_key ] = String(item.orderno || '').split('_'); const warehouse_id = parseInt(warehouse_id_hex, 16); + const order_id = parseInt(order_id_hex, 16) || 0; const waybillCode = String(item.logisticno || item.waybill_code || '').trim(); return { warehouse_id, @@ -1692,8 +1698,11 @@ class ExpressPlatformService extends MainService { if (syncedOrderIds.length > 0) { // 异步调用,不阻塞主流程 + // 显式传仓库上下文:Qimen 创建订单等链路 ctx.user 为空, + // 不传会导致 syncOrderIds 因"缺少仓库上下文"静默失败 this.ctx.service.systemMethods.order.pendingOrder.syncOrderIds({ orderIds: syncedOrderIds, + warehouseId, }).catch(err => { this.ctx.logger.error( `[auto_sync_back] polyapi 自动同步失败: ${err.message}` @@ -1774,7 +1783,7 @@ class ExpressPlatformService extends MainService { : []; const recipientMobile = orderDelivery && (orderDelivery.mobile || orderDelivery.tel) || ''; const orderDeliveryOaid = orderDelivery && orderDelivery.oaid ? String(orderDelivery.oaid).trim() : ''; - const oaidTooLong = orderDeliveryOaid.indexOf("-") !== -1 || orderDeliveryOaid.length > 128; + const oaidTooLong = orderDeliveryOaid.indexOf('-') !== -1 || orderDeliveryOaid.length > 128; const tradeOrderInfo = { logistics_services: normalizedExtData, @@ -1798,10 +1807,10 @@ class ExpressPlatformService extends MainService { })) || [], goods_description: '物品', id: `${orderDelivery.warehouse_id}_${orderDelivery.id}_${order_tmp.business_key}`, - length:Number(orderDelivery.length || 1), - width:Number(orderDelivery.width || 1), - height:Number(orderDelivery.height || 1), - weight:Number(orderDelivery.items_weight || 1), + length: Number(orderDelivery.length || 1), + width: Number(orderDelivery.width || 1), + height: Number(orderDelivery.height || 1), + weight: Number(orderDelivery.items_weight || 1), }, recipient: { address: { @@ -1817,7 +1826,9 @@ class ExpressPlatformService extends MainService { phone: recipientMobile, oaid: oaidTooLong ? '' : orderDeliveryOaid, caid: oaidTooLong ? orderDeliveryOaid : '', - tid: orderDelivery.source_order_codes, + tid: sourceOrderCodes.length > 0 + ? sourceOrderCodes[0] + : orderDelivery && orderDelivery.delivery_order_code || '', }, user_id: listByWarehousePlatformCode.shop && listByWarehousePlatformCode.shop.owner_id || 0, notify_extend_info: normalizedExtData, @@ -2045,8 +2056,11 @@ class ExpressPlatformService extends MainService { if (syncedOrderIds.length > 0) { // 异步调用,不阻塞主流程 + // 显式传仓库上下文:Qimen 创建订单等链路 ctx.user 为空, + // 不传会导致 syncOrderIds 因"缺少仓库上下文"静默失败 this.ctx.service.systemMethods.order.pendingOrder.syncOrderIds({ orderIds: syncedOrderIds, + warehouseId, }).catch(err => { this.ctx.logger.error( `[auto_sync_back] cainiao 自动同步失败: ${err.message}` @@ -2745,8 +2759,11 @@ class ExpressPlatformService extends MainService { if (syncedOrderIds.length > 0) { // 异步调用,不阻塞主流程 + // 显式传仓库上下文:Qimen 创建订单等链路 ctx.user 为空, + // 不传会导致 syncOrderIds 因"缺少仓库上下文"静默失败 this.ctx.service.systemMethods.order.pendingOrder.syncOrderIds({ orderIds: syncedOrderIds, + warehouseId, }).catch(err => { this.ctx.logger.error( `[auto_sync_back] pdd 自动同步失败: ${err.message}` diff --git a/test/app/service/systems/express_platform.cainiao.test.js b/test/app/service/systems/express_platform.cainiao.test.js index 622eb03..8480229 100644 --- a/test/app/service/systems/express_platform.cainiao.test.js +++ b/test/app/service/systems/express_platform.cainiao.test.js @@ -27,6 +27,8 @@ function createCainiaoHarness(options = {}) { printQuantityLogCreate: 0, operationLogCreateOperationLogs: 0, operationLogPayloads: [], + getContractConfigCalls: [], + syncOrderIdsCalls: [], }; const relationRows = [ @@ -55,6 +57,9 @@ function createCainiaoHarness(options = {}) { formatDate() { return '2026-05-24 12:00:00'; }, + async setCacheAsync() { + // no-op in tests + }, }, model: { async transaction(callback) { @@ -106,6 +111,9 @@ function createCainiaoHarness(options = {}) { }, }, express: { + async loadExpressList() { + return []; + }, async getWaybillAsyncOrderDeliveryModel() { return { async update() { @@ -122,6 +130,25 @@ function createCainiaoHarness(options = {}) { return payloads; }, }, + storeWarehouse: { + async getContractConfig(warehouseId, storeId) { + calls.getContractConfigCalls.push({ warehouseId, storeId }); + if (options.contractConfig !== undefined) { + return options.contractConfig; + } + return { policy_config: { auto_sync_back: 1 } }; + }, + }, + }, + systemMethods: { + order: { + pendingOrder: { + async syncOrderIds(request) { + calls.syncOrderIdsCalls.push(request); + return { flag: 'success' }; + }, + }, + }, }, }, state: { @@ -335,4 +362,28 @@ describe('test/app/service/systems/express_platform.cainiao.test.js', () => { /参数错误/ ); }); + + it('auto_sync_back 开启且无登录用户上下文时,应以显式 warehouseId 触发订单同步回传', async () => { + const { service, calls } = createCainiaoHarness(); + + await service.cainiao(buildPayload()); + + assert.equal(calls.getContractConfigCalls.length, 1); + assert.deepEqual(calls.getContractConfigCalls[0], { warehouseId: 100000, storeId: 5001 }); + assert.equal(calls.syncOrderIdsCalls.length, 1); + assert.deepEqual(calls.syncOrderIdsCalls[0], { + orderIds: [ 2001 ], + warehouseId: 100000, + }); + }); + + it('auto_sync_back 关闭时不应触发订单同步回传', async () => { + const { service, calls } = createCainiaoHarness({ + contractConfig: { policy_config: { auto_sync_back: 0 } }, + }); + + await service.cainiao(buildPayload()); + + assert.equal(calls.syncOrderIdsCalls.length, 0); + }); }); diff --git a/test/app/service/systems/express_platform.pdd.ext_data.test.js b/test/app/service/systems/express_platform.pdd.ext_data.test.js index c711c6d..da2fc21 100644 --- a/test/app/service/systems/express_platform.pdd.ext_data.test.js +++ b/test/app/service/systems/express_platform.pdd.ext_data.test.js @@ -6,9 +6,11 @@ const ExpressPlatformService = require('../../../../app/service/systems/express_ /** * 构建拼多多服务最小测试桩。 * + * @param {Object} [options={}] 测试配置。 + * @param {Object} [options.contractConfig] 合约配置覆盖值。 * @return {{ service: Object, calls: Object }} 服务实例与调用记录。 */ -function createPddHarness() { +function createPddHarness(options = {}) { const calls = { curl: 0, curlOptions: null, @@ -19,6 +21,8 @@ function createPddHarness() { storeWarehouseUpdate: 0, printQuantityLogCreate: 0, operationLogCreateOperationLogs: 0, + getContractConfigCalls: [], + syncOrderIdsCalls: [], }; const ctx = { @@ -71,6 +75,9 @@ function createPddHarness() { service: { systems: { express: { + async loadExpressList() { + return []; + }, async getWaybillAsyncOrderDeliveryModel() { return { async update() { @@ -86,6 +93,25 @@ function createPddHarness() { return []; }, }, + storeWarehouse: { + async getContractConfig(warehouseId, storeId) { + calls.getContractConfigCalls.push({ warehouseId, storeId }); + if (options.contractConfig !== undefined) { + return options.contractConfig; + } + return { policy_config: { auto_sync_back: 1 } }; + }, + }, + }, + systemMethods: { + order: { + pendingOrder: { + async syncOrderIds(request) { + calls.syncOrderIdsCalls.push(request); + return { flag: 'success' }; + }, + }, + }, }, }, logger: { @@ -152,6 +178,9 @@ function buildPayload() { express: { PDD: 'YTO', }, + shop: { + owner_id: 'owner-1', + }, }, orders: [ { @@ -183,7 +212,7 @@ function buildPayload() { } describe('test/app/service/systems/express_platform.pdd.ext_data.test.js', () => { - it('should stringify object ext_data for logistics_services and notify_extend_info', async () => { + it('should stringify object ext_data for logistics_services', async () => { const { service, calls } = createPddHarness(); const payload = buildPayload(); @@ -197,11 +226,33 @@ describe('test/app/service/systems/express_platform.pdd.ext_data.test.js', () => const orderItem = waybillRequest.trade_order_info_dtos[0]; assert.equal(typeof orderItem.logistics_services, 'string'); - assert.equal(typeof orderItem.notify_extend_info, 'string'); assert.equal(orderItem.logistics_services, JSON.stringify(payload.listByWarehousePlatformCode.ext_data)); - assert.equal(orderItem.notify_extend_info, JSON.stringify(payload.listByWarehousePlatformCode.ext_data)); assert.equal(result.flag, true); assert.equal(result.code, 0); }); + + it('auto_sync_back 开启且无登录用户上下文时,应以显式 warehouseId 触发订单同步回传', async () => { + const { service, calls } = createPddHarness(); + + await service.pdd(buildPayload()); + + assert.equal(calls.getContractConfigCalls.length, 1); + assert.deepEqual(calls.getContractConfigCalls[0], { warehouseId: 100000, storeId: 5001 }); + assert.equal(calls.syncOrderIdsCalls.length, 1); + assert.deepEqual(calls.syncOrderIdsCalls[0], { + orderIds: [ 2001 ], + warehouseId: 100000, + }); + }); + + it('auto_sync_back 关闭时不应触发订单同步回传', async () => { + const { service, calls } = createPddHarness({ + contractConfig: { policy_config: { auto_sync_back: 0 } }, + }); + + await service.pdd(buildPayload()); + + assert.equal(calls.syncOrderIdsCalls.length, 0); + }); }); diff --git a/test/app/service/systems/express_platform.polyapi.test.js b/test/app/service/systems/express_platform.polyapi.test.js index e469793..2aae7ab 100644 --- a/test/app/service/systems/express_platform.polyapi.test.js +++ b/test/app/service/systems/express_platform.polyapi.test.js @@ -46,6 +46,8 @@ function createPolyapiHarness(options = {}) { printQuantityLogCreateArgsList: [], getWaybillAsyncOrderDeliveryModel: 0, getWaybillAsyncOrderDeliveryModelArgs: [], + getContractConfigCalls: [], + syncOrderIdsCalls: [], callSequence: [], }; @@ -195,26 +197,29 @@ function createPolyapiHarness(options = {}) { code: '10000', results: [ { - orderno: '100000_101_9101', + orderno: '186a0_101_9101', waybill_code: 'REAL-WB-101', logisticno: 'PRE-WB-101', printinfo: 'print-101', signature: 'sign-101', encryptprintinfo: 'enc-101', + issuccess: '1', }, { - orderno: '100000_102_9102', + orderno: '186a0_102_9102', logisticno: 'WB-102', printinfo: 'print-102', signature: 'sign-102', encryptprintinfo: 'enc-102', + issuccess: '1', }, { - orderno: '100000_103_9103', + orderno: '186a0_103_9103', logisticno: 'WB-103', printinfo: 'print-103', signature: 'sign-103', encryptprintinfo: 'enc-103', + issuccess: '1', }, ], }; @@ -235,6 +240,25 @@ function createPolyapiHarness(options = {}) { return payload; }, }, + storeWarehouse: { + async getContractConfig(warehouseId, storeId) { + calls.getContractConfigCalls.push({ warehouseId, storeId }); + if (options.contractConfig !== undefined) { + return options.contractConfig; + } + return { policy_config: { auto_sync_back: 1 } }; + }, + }, + }, + systemMethods: { + order: { + pendingOrder: { + async syncOrderIds(request) { + calls.syncOrderIdsCalls.push(request); + return { flag: 'success' }; + }, + }, + }, }, }, }; @@ -337,7 +361,7 @@ describe('test/app/service/systems/express_platform.polyapi.test.js', () => { assert.equal(relationRows[0].print_quantity, 6); assert.equal(relationRows[0].print_quantity_locked, 3); assert.equal(calls.getWaybillAsyncOrderDeliveryModel, 3); - assert.deepEqual(calls.getWaybillAsyncOrderDeliveryModelArgs, [ '100000', '100000', '100000' ]); + assert.deepEqual(calls.getWaybillAsyncOrderDeliveryModelArgs, [ 100000, 100000, 100000 ]); assert.equal(calls.operationLogArgsList[0].businessId, '101'); assert.equal(calls.requestArgs.bizcontent.orders[0].logisticno, 'REAL-WB-101'); assert.equal(calls.requestArgs.bizcontent.orders[1].logisticno, 'REAL-WB-102'); @@ -435,4 +459,28 @@ describe('test/app/service/systems/express_platform.polyapi.test.js', () => { assert.equal(result.code, 0); assert.equal(result.message, '菠萝派平台数据处理成功'); }); + + it('auto_sync_back 开启且无登录用户上下文时,应以显式 warehouseId 触发订单同步回传', async () => { + const { calls, service } = createPolyapiHarness(); + + await service.polyapi(buildPolyapiPayload()); + + assert.equal(calls.getContractConfigCalls.length, 1); + assert.deepEqual(calls.getContractConfigCalls[0], { warehouseId: 100000, storeId: 2001 }); + assert.equal(calls.syncOrderIdsCalls.length, 1); + assert.deepEqual(calls.syncOrderIdsCalls[0], { + orderIds: [ 101, 102 ], + warehouseId: 100000, + }); + }); + + it('auto_sync_back 关闭时不应触发订单同步回传', async () => { + const { calls, service } = createPolyapiHarness({ + contractConfig: { policy_config: { auto_sync_back: 0 } }, + }); + + await service.polyapi(buildPolyapiPayload()); + + assert.equal(calls.syncOrderIdsCalls.length, 0); + }); }); From f2d1ed08495a66b4ac54465ee199595a992872c6 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sat, 22 Aug 2026 17:22:46 +0800 Subject: [PATCH 260/550] =?UTF-8?q?fix(order):=20=E5=BC=82=E6=AD=A5?= =?UTF-8?q?=E9=93=BE=E8=B7=AF=E6=98=BE=E5=BC=8F=E4=BC=A0=E9=80=92=E4=BB=93?= =?UTF-8?q?=E5=BA=93=E4=B8=8A=E4=B8=8B=E6=96=87=EF=BC=8C=E9=81=BF=E5=85=8D?= =?UTF-8?q?=20Qimen=20=E6=97=A0=E7=99=BB=E5=BD=95=E7=94=A8=E6=88=B7?= =?UTF-8?q?=E9=9D=99=E9=BB=98=E5=A4=B1=E8=B4=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - pendingOrder/orderStorageAllocation: 优先取显式传入的 warehouse_id,缺失时回退 getWarehouseId - deliveryOrder: buildExpressAllocateRequest 携带 warehouse_id,并补充自动分配开关判定日志 --- app/service/systemMethods/order/pendingOrder.js | 7 ++++++- app/service/systems/delivery_order.js | 16 ++++++++++++++++ app/service/systems/order_storage_allocation.js | 9 ++++++++- 3 files changed, 30 insertions(+), 2 deletions(-) diff --git a/app/service/systemMethods/order/pendingOrder.js b/app/service/systemMethods/order/pendingOrder.js index 790d9dc..c3f0fa0 100644 --- a/app/service/systemMethods/order/pendingOrder.js +++ b/app/service/systemMethods/order/pendingOrder.js @@ -1891,7 +1891,12 @@ class PendingOrderService extends OrderBaseService { }; // 快照 ctx 数据(setImmediate 回调中 ctx 可能已失效) - const warehouseId = this.getWarehouseId(); + // 显式传入的仓库ID优先:Qimen 创建订单等无登录用户上下文的异步链路 ctx.user 为空, + // 调用方必须显式传 warehouseId,否则回传任务会因"缺少仓库上下文"静默失败 + const explicitWarehouseId = Number(requestData.warehouse_id ?? requestData.warehouseId ?? 0); + const warehouseId = Number.isFinite(explicitWarehouseId) && explicitWarehouseId > 0 + ? explicitWarehouseId + : this.getWarehouseId(); const operator = this.getOrderLogOperator(); const logWarehouseId = this.getOrderLogWarehouseId(warehouseId); diff --git a/app/service/systems/delivery_order.js b/app/service/systems/delivery_order.js index 7d1110f..f261a67 100644 --- a/app/service/systems/delivery_order.js +++ b/app/service/systems/delivery_order.js @@ -1856,6 +1856,8 @@ class DeliveryOrderService extends Service { return { allow_storage_location: true, order_ids: [ Number(context && context.orderId || 0) ], + // 显式携带仓库上下文,避免依赖 ctx.user(Qimen 链路无登录用户) + warehouse_id: Number(context && context.warehouseId || 0), }; } @@ -2506,6 +2508,20 @@ class DeliveryOrderService extends Service { const isAutoAllocateExpressEnabled = !isCutoffActive && !needApproval && this.normalizePolicyFlag(policyConfig.auto_allocate_express); const isAutoAllocateStorageEnabled = !isCutoffActive && !needApproval && this.normalizePolicyFlag(policyConfig.auto_allocate_storage); + // 记录开关判定结果,便于排查自动分配快递/储位未触发的问题 + this.ctx.logger.info('[DeliveryOrderService.asyncProcessOrderCreated] 自动流程开关判定', { + warehouseId: context.warehouseId, + orderId: context.orderId, + storeId: context.storeId, + cutoffEnabled, + isCutoffActive, + needApproval, + autoAllocateExpressFlag: policyConfig && policyConfig.auto_allocate_express, + autoAllocateStorageFlag: policyConfig && policyConfig.auto_allocate_storage, + isAutoAllocateExpressEnabled, + isAutoAllocateStorageEnabled, + }); + if (isAutoAllocateExpressEnabled) { await this.runAsyncProcessStep('allocateExpress', async () => { const request = this.buildExpressAllocateRequest(context); diff --git a/app/service/systems/order_storage_allocation.js b/app/service/systems/order_storage_allocation.js index ce26e4d..f0e3f31 100644 --- a/app/service/systems/order_storage_allocation.js +++ b/app/service/systems/order_storage_allocation.js @@ -479,7 +479,14 @@ class OrderStorageAllocationService extends MainService { const progressCallback = typeof requestData.progress_callback === 'function' ? requestData.progress_callback : null; - const warehouseId = toNumber(ctx.user?.store_id ?? ctx.user?.warehouse_id, 0); + // 优先使用调用方显式传入的仓库ID(Qimen 等无登录用户上下文的链路 ctx.user 为空) + const warehouseId = toNumber( + requestData.warehouse_id + ?? requestData.warehouseId + ?? ctx.user?.store_id + ?? ctx.user?.warehouse_id, + 0 + ); const orderIds = normalizeOrderIds(requestData); const allowStorageLocation = normalizeBooleanFlag( requestData.allow_storage_location From a49929867084665bafc2c0e19b1e4193698ac69a Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sun, 23 Aug 2026 14:30:41 +0800 Subject: [PATCH 261/550] =?UTF-8?q?fix(order):=20=E5=A4=8D=E6=A0=B8?= =?UTF-8?q?=E5=85=B1=E4=BA=AB=E6=9D=A1=E7=A0=81=E5=88=A4=E5=AE=9A=E6=94=B6?= =?UTF-8?q?=E7=AA=84=E5=88=B0=E8=AE=A2=E5=8D=95=E8=B4=A7=E4=B8=BB=E5=B9=B6?= =?UTF-8?q?=E8=BF=87=E6=BB=A4=E5=A4=B1=E6=95=88=E5=95=86=E5=93=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - has_shared_barcode 判定范围从全仓库改为订单 store_id 维度(wms_stock_warehouse.store_id) - 排除已删除(delete_at/deleted_at 非空)与弃用(is_valid≠'Y')的商品资料 - 跨货主同码不再提示;无货主(store_id<=0)订单不做共享判定 --- .../systemMethods/order/recheckOrder.js | 50 +++++++++++++++---- 1 file changed, 39 insertions(+), 11 deletions(-) diff --git a/app/service/systemMethods/order/recheckOrder.js b/app/service/systemMethods/order/recheckOrder.js index 559c211..a89f158 100644 --- a/app/service/systemMethods/order/recheckOrder.js +++ b/app/service/systemMethods/order/recheckOrder.js @@ -1382,8 +1382,11 @@ class RecheckOrderService extends OrderBaseService { } } - // 5. 检测共享条码:查询当前所有条码是否也出现在其他 stock_id 中 - const sharedBarcodeSet = new Set(); + // 5. 检测共享条码:以订单货主(store_id)为判定范围, + // 仅当条码在订单货主下(wms_stock_warehouse.store_id = 订单 store_id)绑定到多个不同 stock_id 时视为共享; + // 跨货主同码不提示。无货主(store_id<=0)的订单不做共享判定。 + // 已删除(delete_at/deleted_at 非空)或弃用(is_valid≠'Y')的商品资料不参与共享判定。 + const sharedBarcodeMap = new Map(); if (barcodeMap.size > 0) { const allBarcodes = []; for (const [ , barcodes ] of barcodeMap) { @@ -1391,21 +1394,44 @@ class RecheckOrderService extends OrderBaseService { allBarcodes.push(bc); } } - if (allBarcodes.length > 0 && this.ctx.model && this.ctx.model.StockBarcode) { + const orderStoreIds = [ ...new Set( + orderList + .map(order => Number(order.store_id || 0)) + .filter(storeId => storeId > 0) + ) ]; + if (allBarcodes.length > 0 + && orderStoreIds.length > 0 + && this.ctx.model + && this.ctx.model.StockBarcode) { const sharedRows = await this.ctx.model.query( - `SELECT barcode, COUNT(DISTINCT stock_id) AS cnt - FROM wms_stock_barcodes - WHERE barcode IN (:barcodes) - AND warehouse_id = :warehouseId - GROUP BY barcode + `SELECT sb.barcode, sw.store_id, COUNT(DISTINCT sb.stock_id) AS cnt + FROM wms_stock_barcodes sb + INNER JOIN wms_stock_warehouse sw + ON sw.id = sb.stock_id + AND sw.is_valid = 'Y' + AND sw.delete_at IS NULL + AND sw.deleted_at IS NULL + WHERE sb.barcode IN (:barcodes) + AND sb.warehouse_id = :warehouseId + AND sw.warehouse_id = :warehouseId + AND sw.store_id IN (:orderStoreIds) + GROUP BY sb.barcode, sw.store_id HAVING cnt > 1`, { - replacements: { barcodes: allBarcodes, warehouseId }, + replacements: { barcodes: allBarcodes, warehouseId, orderStoreIds }, type: this.ctx.model.QueryTypes.SELECT, } ); for (const row of (Array.isArray(sharedRows) ? sharedRows : [])) { - sharedBarcodeSet.add(String(row.barcode || '').trim()); + const rowStoreId = Number(row.store_id || 0); + const rowBarcode = String(row.barcode || '').trim(); + if (rowStoreId <= 0 || !rowBarcode) { + continue; + } + if (!sharedBarcodeMap.has(rowStoreId)) { + sharedBarcodeMap.set(rowStoreId, new Set()); + } + sharedBarcodeMap.get(rowStoreId).add(rowBarcode); } } } @@ -1438,7 +1464,9 @@ class RecheckOrderService extends OrderBaseService { const hasSharedBarcode = (() => { const arr = barcodeMap.get(sid); - if (Array.isArray(arr) && arr.length > 0) { + const orderStoreId = Number(order.store_id || 0); + const sharedBarcodeSet = orderStoreId > 0 ? sharedBarcodeMap.get(orderStoreId) : null; + if (Array.isArray(arr) && arr.length > 0 && sharedBarcodeSet) { return arr.some(bc => sharedBarcodeSet.has(bc)); } return false; From 763573ee4141bf2f842a808e873c42ff865cad18 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sun, 23 Aug 2026 14:31:49 +0800 Subject: [PATCH 262/550] =?UTF-8?q?feat(wms):=20=E6=8B=A6=E6=88=AA?= =?UTF-8?q?=E8=AE=A2=E5=8D=95=E9=97=A8=E7=A6=81=E8=B1=81=E5=85=8D=E3=80=81?= =?UTF-8?q?=E6=B3=A2=E6=AC=A1=E5=8F=B7=E5=8E=9F=E5=AD=90=E5=8F=96=E5=8F=B7?= =?UTF-8?q?=E3=80=81=E6=89=93=E5=8D=B0=E8=87=AA=E5=AE=9A=E4=B9=89=E5=8C=BA?= =?UTF-8?q?=E6=95=B0=E9=87=8F=E3=80=81=E6=8B=86=E5=8C=85=E8=A7=86=E9=A2=91?= =?UTF-8?q?=E4=B8=8E=E5=95=86=E5=93=81=E5=A4=8D=E6=A0=B8=E5=AD=97=E6=AE=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - pick: waveClaimScan 拦截订单整体跳过领料(不置 claim_status=fin,未打印不阻隔领料);query 领料前置校验仅统计非拦截未领料订单(拦截未领料不阻隔拣货);createWavePickTask 新增 excludeUnclaimed,普通波次(source=0)计算拣货数量(order_count/任务订单/筐)时剔除未领料订单 - wave: 波次号改为 wms_number_sequence 原子取号(upsert + LAST_INSERT_ID,seed 对齐当日历史最大序),wave_no 唯一索引 uniq_wave_no,并发撞号自动重取(最多 3 次) - print: 面单自定义区首行「商品总数【n】」(items_total 优先),团购波次商品明细行尾「波次总单数×商品数量」 - returnUnpack: 列表新增 has_video/video_enable/videos 视频字段与筛选,补视频列表权限迁移 - stock: 商品新增 need_recheck(是否需要复核)字段,导入归一化与导出列支持,补迁移 - docs: 同步 methods/system.json 与 methods/changes/system.json 变更记录(恢复遗漏的已提交记录) --- app/lib/printer_data_builder.js | 92 +++++-- app/model/stock_warehouse.js | 6 + app/model/wave_batch.js | 3 +- app/service/systemMethods/order/wave.js | 155 ++++++++--- app/service/systemMethods/pick.js | 175 +++++++++++- app/service/systemMethods/returnUnpack.js | 30 +++ app/service/systemMethods/stock/warehouse.js | 22 ++ app/service/systems/order_print.js | 31 ++- app/service/systems/return_unpack.js | 176 +++++++++++- app/service/systems/stock_store.js | 28 +- ...00-add-unique-wave-no-to-wms-wave-batch.js | 254 ++++++++++++++++++ ...add-return-unpack-video-list-permission.js | 82 ++++++ ...add-need-recheck-to-wms-stock-warehouse.js | 17 ++ methods/changes/system.json | 104 +++++++ methods/system.json | 75 +++++- ...der_print.getWavePlatformPrintData.test.js | 3 +- 16 files changed, 1157 insertions(+), 96 deletions(-) create mode 100644 database/migrations/20260822140000-add-unique-wave-no-to-wms-wave-batch.js create mode 100644 database/migrations/20260823120000-add-return-unpack-video-list-permission.js create mode 100644 database/migrations/20260823150000-add-need-recheck-to-wms-stock-warehouse.js diff --git a/app/lib/printer_data_builder.js b/app/lib/printer_data_builder.js index 727b8fd..d52e77e 100644 --- a/app/lib/printer_data_builder.js +++ b/app/lib/printer_data_builder.js @@ -464,9 +464,13 @@ function resolveItemQuantity(item) { * @param {number} [options.wave_index] 当前波次内序号。 * @param {number} [options.platforms_index] 平台内序号。 * @param {string} [options.expressInterfaceName] 快递渠道显示名。 - * @param {number} [options.fallbackTotalQty] 兜底商品总数。 + * @param {number} [options.fallbackTotalQty] 订单级商品总数(items_total),优先于商品明细数量累加。 + * @param {number} [options.fallbackItemsCount] 订单级商品种类数(items_count),仅当商品总数与明细累加均为 0 时兜底。 + * @param {number} [options.waveSource] 波次来源(wms_wave_batch.source),与 waveType 共同决定商品明细行尾是否追加「波次总单数×数量」。 + * @param {number} [options.waveType] 波次类型(wms_wave_batch.wave_type)。 * @param {string} [options.packageMaterialName] 推荐包材名称,非空时追加到波次号前。 - * @return {Array} 自定义区文本行数组。 + * @return {Array} 自定义区文本行数组。首行头部分在快递渠道名后追加 商品总数【n】(优先取订单级商品总数 items_total,其次商品明细数量累加,最后 items_count 兜底); + * 当 waveSource=0 且 waveType=1 时,商品明细行尾追加「波次总单数×该行商品数量」。 */ function buildWaybillCustomProductInfoLines(items, policyConfig = {}, options = {}) { const safeItems = Array.isArray(items) ? items : []; @@ -479,6 +483,13 @@ function buildWaybillCustomProductInfoLines(items, policyConfig = {}, options = const isHideMode = displayType === WAYBILL_CUSTOM_DISPLAY_TYPES.HIDE; + // 波次总单数、来源与类型:wave.source=0(普通波次)且 wave_type=1 时, + // 商品明细行尾追加「波次总单数 × 该行商品数量」(如 500 单 × 3 件 = 1500) + const waveTotalOrders = toNumber(safeOptions.wave_total_orders, 0); + const waveSource = toNumber(safeOptions.waveSource, 0); + const waveType = toNumber(safeOptions.waveType, 0); + const shouldAppendWaveMultiply = waveSource === 0 && waveType === 1 && waveTotalOrders > 0; + const detailLines = []; // HIDE 模式下跳过商品明细行构建,但仍保留 headerLine(波次号、快递渠道等)的输出 @@ -498,7 +509,7 @@ function buildWaybillCustomProductInfoLines(items, policyConfig = {}, options = 'storage_code', ]); const barcode = resolveItemBarcodeText(item); - const { qtyText } = resolveItemQuantity(item); + const { qtyText, qtyNumber } = resolveItemQuantity(item); let line = ''; switch (displayType) { @@ -526,13 +537,17 @@ function buildWaybillCustomProductInfoLines(items, policyConfig = {}, options = } if (line) { - detailLines.push(line.replace(/\s{2,}/g, ' ')); + line = line.replace(/\s{2,}/g, ' '); + // wave.source=0 且 wave_type=1:行尾追加 波次总单数 × 该行商品数量(数量与乘数之间以两个空格分隔) + if (shouldAppendWaveMultiply && qtyNumber > 0) { + line += ` ${waveTotalOrders * qtyNumber}`; + } + detailLines.push(line); } } } const waveNo = String(safeOptions.waveNo || '').trim(); - const waveTotalOrders = toNumber(safeOptions.wave_total_orders, 0); const waveIndex = toNumber(safeOptions.wave_index, 0); const platformsIndex = toNumber(safeOptions.platforms_index, 0); const expressInterfaceName = String(safeOptions.expressInterfaceName || '').trim(); @@ -546,7 +561,25 @@ function buildWaybillCustomProductInfoLines(items, policyConfig = {}, options = ? `${waveNo} [${waveTotalOrders}-${waveIndex}]` : waveNo; const waveHeaderText = packageMaterialLabel + waveBodyText; - const headerParts = [ waveHeaderText, expressInterfaceName ].filter(Boolean); + + // 商品总数:优先取订单级商品总数(items_total,权威字段), + // 其次累加所有商品明细的数量,最后用商品种类数(items_count)兜底。 + // 订单 items 快照可能是宽松文本(stock_id+数量)甚至陈旧不完整,不能无条件信任明细累加结果 + const computedTotalQty = safeItems.reduce((total, item) => { + if (!isPlainObject(item)) { + return total; + } + const { qtyNumber } = resolveItemQuantity(item); + return total + (Number.isFinite(qtyNumber) && qtyNumber > 0 ? qtyNumber : 0); + }, 0); + const fallbackTotalQty = toNumber(safeOptions.fallbackTotalQty, 0); + const fallbackItemsCount = toNumber(safeOptions.fallbackItemsCount, 0); + const totalQty = fallbackTotalQty > 0 + ? fallbackTotalQty + : (computedTotalQty > 0 ? computedTotalQty : fallbackItemsCount); + const totalQtyLabel = totalQty > 0 ? `商品总数【${totalQty}】` : ''; + + const headerParts = [ waveHeaderText, expressInterfaceName, totalQtyLabel ].filter(Boolean); const headerLine = headerParts.join(' '); if (detailLines.length === 0) { @@ -1253,7 +1286,7 @@ function sanitizeTemplatePrivateFields(value, warnings, currentKey = '') { * @param {string[]} warnings 风险提示列表。 * @param {Object} policyConfig 策略配置对象。 * @param {string} customDataTemplateURL 自定义区模板地址默认值。 - * @param extraCustomLines + * @param {string[]} extraCustomLines 追加到自定义区的额外文本行数组。 */ function applyKuaishouExpressFieldMapping(platform, skeleton, orderExpress, orderDelivery, warnings, policyConfig, customDataTemplateURL, extraCustomLines = []) { if (platform !== 'kuaishou') { @@ -1293,7 +1326,10 @@ function applyKuaishouExpressFieldMapping(platform, skeleton, orderExpress, orde || safeOrderDelivery.logistics_interface_name || safeOrderDelivery.logistics_name ), - fallbackTotalQty: Number(safeOrderDelivery.items_count || safeOrderDelivery.items_total || 0), + fallbackTotalQty: Number(safeOrderDelivery.items_total || 0), + fallbackItemsCount: Number(safeOrderDelivery.items_count || 0), + waveSource: Number(safeOrderDelivery.wave_source || 0), + waveType: Number(safeOrderDelivery.wave_type || 0), } ); const customProductInfo = appendExtraCustomLines( @@ -1403,7 +1439,7 @@ function applyKuaishouExpressFieldMapping(platform, skeleton, orderExpress, orde * @param {Object} orderExpress 快递单对象。 * @param {Object} orderDelivery 订单对象。 * @param {Object} policyConfig 策略配置对象。 - * @param extraCustomLines + * @param {string[]} extraCustomLines 追加到自定义区的额外文本行数组。 */ function applyPddExpressFieldMapping(platform, skeleton, orderExpress, orderDelivery, policyConfig, extraCustomLines = []) { if (platform !== 'pdd') { @@ -1443,7 +1479,10 @@ function applyPddExpressFieldMapping(platform, skeleton, orderExpress, orderDeli || safeOrderDelivery.logistics_interface_name || safeOrderDelivery.logistics_name ), - fallbackTotalQty: Number(safeOrderDelivery.items_count || safeOrderDelivery.items_total || 0), + fallbackTotalQty: Number(safeOrderDelivery.items_total || 0), + fallbackItemsCount: Number(safeOrderDelivery.items_count || 0), + waveSource: Number(safeOrderDelivery.wave_source || 0), + waveType: Number(safeOrderDelivery.wave_type || 0), } ); const customProductInfo = appendExtraCustomLines( @@ -1636,7 +1675,10 @@ function applyDouyinExpressFieldMapping(platform, skeleton, orderExpress, orderD || safeOrderDelivery.logistics_interface_name || safeOrderDelivery.logistics_name ), - fallbackTotalQty: Number(safeOrderDelivery.items_count || safeOrderDelivery.items_total || 0), + fallbackTotalQty: Number(safeOrderDelivery.items_total || 0), + fallbackItemsCount: Number(safeOrderDelivery.items_count || 0), + waveSource: Number(safeOrderDelivery.wave_source || 0), + waveType: Number(safeOrderDelivery.wave_type || 0), } ); const customProductInfo = appendExtraCustomLines( @@ -1726,7 +1768,7 @@ function applyDouyinExpressFieldMapping(platform, skeleton, orderExpress, orderD * @param {Object} policyConfig 策略配置对象。 * @param {string} customControlTemplateURL 菜鸟自定义区模板地址。 * @param {string[]} warnings 风险提示列表。 - * @param extraCustomLines + * @param {string[]} extraCustomLines 追加到自定义区的额外文本行数组。 */ function applyCainiaoExpressFieldMapping( platform, @@ -1776,7 +1818,10 @@ function applyCainiaoExpressFieldMapping( || safeOrderDelivery.logistics_interface_name || safeOrderDelivery.logistics_name ), - fallbackTotalQty: Number(safeOrderDelivery.items_count || safeOrderDelivery.items_total || 0), + fallbackTotalQty: Number(safeOrderDelivery.items_total || 0), + fallbackItemsCount: Number(safeOrderDelivery.items_count || 0), + waveSource: Number(safeOrderDelivery.wave_source || 0), + waveType: Number(safeOrderDelivery.wave_type || 0), } ); const customControlText = appendExtraCustomLines( @@ -1937,7 +1982,7 @@ function resolveXhsMainContentFromPrintinfo(printinfo, warnings = []) { * @param {Object} orderDelivery 订单对象。 * @param {Object} policyConfig 策略配置对象。 * @param {string[]} warnings 风险提示列表。 - * @param extraCustomLines + * @param {string[]} extraCustomLines 追加到自定义区的额外文本行数组。 */ function applyXhsExpressFieldMapping( platform, @@ -1983,7 +2028,10 @@ function applyXhsExpressFieldMapping( || safeOrderDelivery.logistics_interface_name || safeOrderDelivery.logistics_name ), - fallbackTotalQty: Number(safeOrderDelivery.items_count || safeOrderDelivery.items_total || 0), + fallbackTotalQty: Number(safeOrderDelivery.items_total || 0), + fallbackItemsCount: Number(safeOrderDelivery.items_count || 0), + waveSource: Number(safeOrderDelivery.wave_source || 0), + waveType: Number(safeOrderDelivery.wave_type || 0), } ); const customProductInfo = appendExtraCustomLines( @@ -2040,7 +2088,7 @@ function applyXhsExpressFieldMapping( * @param {Object} orderExpress 快递单对象。 * @param {Object} orderDelivery 订单对象。 * @param {Object} policyConfig 策略配置对象。 - * @param extraCustomLines + * @param {string[]} extraCustomLines 追加到自定义区的额外文本行数组。 */ function applySphExpressFieldMapping( platform, @@ -2099,7 +2147,10 @@ function applySphExpressFieldMapping( || safeOrderDelivery.logistics_interface_name || safeOrderDelivery.logistics_name ), - fallbackTotalQty: Number(safeOrderDelivery.items_count || safeOrderDelivery.items_total || 0), + fallbackTotalQty: Number(safeOrderDelivery.items_total || 0), + fallbackItemsCount: Number(safeOrderDelivery.items_count || 0), + waveSource: Number(safeOrderDelivery.wave_source || 0), + waveType: Number(safeOrderDelivery.wave_type || 0), } ); const customProductInfo = appendExtraCustomLines( @@ -2181,7 +2232,7 @@ function resolveJdTemplateUrlFromOrderExpress(orderExpress) { * @param {Object} policyConfig 策略配置对象。 * @param {Object} templateSample 模板样例对象。 * @param {string[]} warnings 风险提示列表。 - * @param extraCustomLines + * @param {string[]} extraCustomLines 追加到自定义区的额外文本行数组。 */ function applyJdExpressFieldMapping( platform, @@ -2271,7 +2322,10 @@ function applyJdExpressFieldMapping( || safeOrderDelivery.logistics_interface_name || safeOrderDelivery.logistics_name ), - fallbackTotalQty: Number(safeOrderDelivery.items_count || safeOrderDelivery.items_total || 0), + fallbackTotalQty: Number(safeOrderDelivery.items_total || 0), + fallbackItemsCount: Number(safeOrderDelivery.items_count || 0), + waveSource: Number(safeOrderDelivery.wave_source || 0), + waveType: Number(safeOrderDelivery.wave_type || 0), } ); const customProductInfo = appendExtraCustomLines( diff --git a/app/model/stock_warehouse.js b/app/model/stock_warehouse.js index 696db1b..e83ac38 100644 --- a/app/model/stock_warehouse.js +++ b/app/model/stock_warehouse.js @@ -111,6 +111,12 @@ module.exports = app => { defaultValue: 'N', comment: '是否批次管理', }, + need_recheck: { + type: CHAR(1), + allowNull: false, + defaultValue: 'Y', + comment: '是否需要复核:Y=需要复核,N=不需要复核', + }, create_at: { type: DATE, allowNull: false, diff --git a/app/model/wave_batch.js b/app/model/wave_batch.js index 2bf5192..1c95312 100644 --- a/app/model/wave_batch.js +++ b/app/model/wave_batch.js @@ -155,8 +155,9 @@ module.exports = app => { fields: [ 'wave_status', 'create_time' ], }, { - name: 'idx_wave_no', + name: 'uniq_wave_no', fields: [ 'wave_no' ], + unique: true, }, { name: 'idx_warehouse', diff --git a/app/service/systemMethods/order/wave.js b/app/service/systemMethods/order/wave.js index 72982ac..d8b1dc3 100644 --- a/app/service/systemMethods/order/wave.js +++ b/app/service/systemMethods/order/wave.js @@ -563,7 +563,13 @@ class WaveService extends OrderBaseService { } /** - * 查询当天前缀下的下一个波次序号。 + * 获取当天前缀下的下一个波次序号(原子取号)。 + * + * 基于序列表 wms_number_sequence 的单条 upsert 原子递增: + * INSERT ... VALUES (LAST_INSERT_ID(:seed + 1)) ON DUPLICATE KEY UPDATE + * current_seq = LAST_INSERT_ID(GREATEST(current_seq, :seed) + 1) + * 其中 :seed 为当日该前缀主表已有最大序号,保证与历史编号对齐; + * 同事务(同连接)内回读 LAST_INSERT_ID() 取回本次分配序号,并发下不再撞号。 * * @param {string} prefix 波次编号前缀。 * @param {string} datePart 日期片段(YYYYMMDD)。 @@ -574,32 +580,54 @@ class WaveService extends OrderBaseService { const normalizedPrefix = String(prefix || '').trim() || 'B'; const normalizedDatePart = String(datePart || '').trim(); const pattern = `${normalizedPrefix}${normalizedDatePart}%`; - const sql = ` - SELECT wave_no - FROM wms_wave_batch - WHERE wave_no LIKE :pattern - ORDER BY wave_no DESC - LIMIT 1 - `; + const prefixDatePartLength = normalizedPrefix.length + normalizedDatePart.length; + const bizType = `wave_no_${normalizedPrefix.slice(0, 20)}`; - const rows = await this.ctx.model.query(sql, { - replacements: { pattern }, - type: this.ctx.model.QueryTypes.SELECT, - transaction, - }); + // 历史对齐种子:当日该前缀主表已有最大序号(无则为 0) + const seedRows = await this.ctx.model.query( + `SELECT IFNULL(MAX(CAST(SUBSTRING(wave_no, :startPos) AS UNSIGNED)), 0) AS max_seq + FROM wms_wave_batch + WHERE wave_no LIKE :pattern`, + { + replacements: { + pattern, + startPos: prefixDatePartLength + 1, + }, + type: this.ctx.model.QueryTypes.SELECT, + transaction, + } + ); + const seed = Number(seedRows && seedRows[0] && seedRows[0].max_seq || 0); - const latestWaveNo = String(rows && rows[0] && rows[0].wave_no || '').trim(); - if (!latestWaveNo) { + // 原子取号:全局维度(warehouse_id=0)按「前缀+日期」递增,唯一键串行化并发事务 + await this.ctx.model.query( + `INSERT INTO wms_number_sequence (warehouse_id, biz_type, date_part, current_seq, created_at, updated_at) + VALUES (:warehouseId, :bizType, :datePart, LAST_INSERT_ID(:seed + 1), NOW(), NOW()) + ON DUPLICATE KEY UPDATE current_seq = LAST_INSERT_ID(GREATEST(current_seq, :seed) + 1), updated_at = NOW()`, + { + replacements: { + warehouseId: 0, + bizType, + datePart: normalizedDatePart, + seed, + }, + transaction, + } + ); + + const seqRows = await this.ctx.model.query( + 'SELECT LAST_INSERT_ID() AS seq', + { + type: this.ctx.model.QueryTypes.SELECT, + transaction, + } + ); + const sequence = Number(seqRows && seqRows[0] && seqRows[0].seq || 0); + if (!Number.isInteger(sequence) || sequence <= 0) { return 1; } - const match = latestWaveNo.match(/(\d{5})$/); - const lastSequence = match ? Number(match[1]) : 0; - if (!Number.isInteger(lastSequence) || lastSequence <= 0) { - return 1; - } - - return lastSequence + 1; + return sequence; } /** @@ -699,6 +727,22 @@ class WaveService extends OrderBaseService { return 0; } + /** + * 判断数据库错误是否为唯一键冲突(重复键 ER_DUP_ENTRY)。 + * + * @param {*} error 数据库异常对象。 + * @return {boolean} 是否唯一键冲突。 + */ + isDuplicateEntryError(error) { + const errno = Number( + error && (error.original && error.original.errno || error.parent && error.parent.errno || error.errno) || 0 + ); + const code = String( + error && (error.original && error.original.code || error.parent && error.parent.code || error.code) || '' + ); + return errno === 1062 || code === 'ER_DUP_ENTRY'; + } + /** * 新增一条“已就绪”波次批次记录,并返回自增 wave_id。 * @@ -746,12 +790,9 @@ class WaveService extends OrderBaseService { const normalizedWaveType = Number(waveType) === 2 ? 2 : 1; const normalizedSourceInput = Number(source); const normalizedSource = [ 0, 1, 2 ].includes(normalizedSourceInput) ? normalizedSourceInput : 0; + const retryOnDuplicate = !normalizedWaveNoInput; + const maxWaveNoAttempts = retryOnDuplicate ? 3 : 1; let normalizedWaveNo = normalizedWaveNoInput; - if (!normalizedWaveNo) { - const datePart = this.getCurrentDatePart(); - const sequence = await this.getNextWaveNoSequence(normalizedWavePrefix, datePart, transaction); - normalizedWaveNo = this.buildWaveNo(normalizedWavePrefix, datePart, sequence); - } const creator = this.getWaveCreator(); const sql = ` @@ -795,23 +836,49 @@ class WaveService extends OrderBaseService { ) `; - const createResult = await this.ctx.model.query(sql, { - replacements: { - waveNo: normalizedWaveNo, - waveType: normalizedWaveType, - totalOrders: normalizedTotalOrders, - itemDetailMachine: normalizedItemDetailMachine, - itemPartType: normalizedItemPartType, - itemPart: normalizedItemPart, - distinguishExpress: normalizedDistinguishExpress, - logisticsName: normalizedLogisticsName, - itemSnapshotKey: normalizedItemSnapshotKey, - warehouseId: Number.isInteger(normalizedWarehouseId) ? normalizedWarehouseId : 0, - creator, - source: normalizedSource, - }, - transaction, - }); + // 撞号重试:唯一索引兜底下,并发撞号时自动重新取号(最多 3 次) + let createResult = null; + for (let attempt = 1; attempt <= maxWaveNoAttempts; attempt += 1) { + if (!normalizedWaveNo) { + const datePart = this.getCurrentDatePart(); + const sequence = await this.getNextWaveNoSequence(normalizedWavePrefix, datePart, transaction); + normalizedWaveNo = this.buildWaveNo(normalizedWavePrefix, datePart, sequence); + } + + try { + createResult = await this.ctx.model.query(sql, { + replacements: { + waveNo: normalizedWaveNo, + waveType: normalizedWaveType, + totalOrders: normalizedTotalOrders, + itemDetailMachine: normalizedItemDetailMachine, + itemPartType: normalizedItemPartType, + itemPart: normalizedItemPart, + distinguishExpress: normalizedDistinguishExpress, + logisticsName: normalizedLogisticsName, + itemSnapshotKey: normalizedItemSnapshotKey, + warehouseId: Number.isInteger(normalizedWarehouseId) ? normalizedWarehouseId : 0, + creator, + source: normalizedSource, + }, + transaction, + }); + break; + } catch (error) { + const isDuplicateWaveNo = this.isDuplicateEntryError(error); + if (!retryOnDuplicate || !isDuplicateWaveNo || attempt >= maxWaveNoAttempts) { + throw error; + } + + this.ctx.logger.warn( + '[wave.createWaveBatchReady] 波次编号 %s 已存在(撞号),自动重新取号重试 %d/%d', + normalizedWaveNo, + attempt, + maxWaveNoAttempts + ); + normalizedWaveNo = ''; + } + } let insertedWaveId = this.extractInsertId(createResult); if (!Number.isInteger(insertedWaveId) || insertedWaveId <= 0) { diff --git a/app/service/systemMethods/pick.js b/app/service/systemMethods/pick.js index 549ce71..85206e9 100644 --- a/app/service/systemMethods/pick.js +++ b/app/service/systemMethods/pick.js @@ -97,6 +97,8 @@ class PickService extends MainService { * @param {Array} params.orderIds 波次订单ID集合。 * @param {string} [params.remark=''] 备注。 * @param {number} [params.source=2] 任务来源:1-PDA抓取创建,2-扫描进任务/后台抓取,默认为2。 + * @param {boolean} [params.excludeUnclaimed=false] 普通波次(source=0)计算拣货数量时是否剔除未领料 + * (claim_status != fin)订单:true 时未领料订单不写入任务订单/筐,也不计入 order_count。 * @return {Promise<{task_id: number, task_no: string}>} 创建结果。 */ async createWavePickTask(params = {}) { @@ -109,6 +111,7 @@ class PickService extends MainService { const operatorName = String(params && params.operatorName || '').trim() || 'system'; const source = Number(params && params.source !== undefined ? params.source : 2); const remark = String(params && params.remark || '').trim(); + const excludeUnclaimed = Boolean(params && params.excludeUnclaimed); const normalizedOrderIds = [ ...new Set((Array.isArray(params && params.orderIds) ? params.orderIds : []) .map(id => Number(id || 0)) .filter(id => Number.isInteger(id) && id > 0)) ]; @@ -134,11 +137,13 @@ class PickService extends MainService { [this.app.Sequelize.Op.in]: normalizedOrderIds, }, }, - attributes: [ 'id', 'intercept_status' ], + attributes: [ 'id', 'intercept_status', 'claim_status' ], raw: true, }); // 拦截流程中的订单不允许抓取波次,直接剔除 + const orderRowMap = new Map((Array.isArray(orderRows) ? orderRows : []) + .map(row => [ Number(row && row.id || 0), row ])); const interceptedOrderIds = new Set((Array.isArray(orderRows) ? orderRows : []) .filter(row => isInterceptedOrderStatus(row && row.intercept_status)) .map(row => Number(row && row.id || 0)) @@ -149,9 +154,28 @@ class PickService extends MainService { ctx.logger.info('[pick.createWavePickTask] 剔除拦截订单: %s', excludedIds.join(',')); } } - const activeOrderIds = normalizedOrderIds.filter(id => !interceptedOrderIds.has(id)); + + // 领料语义(普通波次 source=0):未领料订单(claim_status != fin)不参与拣货数量计算,直接剔除 + const unclaimedOrderIds = excludeUnclaimed + ? new Set(normalizedOrderIds.filter(id => { + const row = orderRowMap.get(id); + return !row || String(row && row.claim_status || '') !== 'fin'; + })) + : new Set(); + if (unclaimedOrderIds.size > 0) { + const excludedIds = normalizedOrderIds.filter(id => unclaimedOrderIds.has(id)); + if (excludedIds.length > 0) { + ctx.logger.info('[pick.createWavePickTask] 剔除未领料订单: %s', excludedIds.join(',')); + } + } + + const activeOrderIds = normalizedOrderIds + .filter(id => !interceptedOrderIds.has(id) && !unclaimedOrderIds.has(id)); if (activeOrderIds.length <= 0) { - throw Object.assign(new Error('波次下订单均已被拦截,无法创建任务'), { code: 400 }); + const emptyReason = unclaimedOrderIds.size > 0 + ? '波次下订单均未领料或均被拦截,无法创建任务' + : '波次下订单均已被拦截,无法创建任务'; + throw Object.assign(new Error(emptyReason), { code: 400 }); } const orderNoMap = new Map((Array.isArray(orderRows) ? orderRows : []) @@ -674,6 +698,7 @@ class PickService extends MainService { let targetWaveId = 0; let targetWaveNo = ''; let targetWaveType = 2; + let targetWaveSource = 0; let selectedOrderIds = []; const orderId = Number(orderExpress && orderExpress.order_id || 0); @@ -706,7 +731,7 @@ class PickService extends MainService { if (orderWaveId > 0) { const waveByIdRows = await ctx.model.query( ` - SELECT wave_id, wave_no, wave_type + SELECT wave_id, wave_no, wave_type, source FROM wms_wave_batch WHERE warehouse_id = :warehouseId AND wave_id = :waveId @@ -728,10 +753,11 @@ class PickService extends MainService { targetWaveId = Number(waveRow.wave_id || 0); targetWaveNo = String(waveRow.wave_no || '').trim(); targetWaveType = Number(waveRow.wave_type || 2); + targetWaveSource = Number(waveRow.source || 0); } else { const waveByNoRows = await ctx.model.query( ` - SELECT wave_id, wave_no, wave_type + SELECT wave_id, wave_no, wave_type, source FROM wms_wave_batch WHERE warehouse_id = :warehouseId AND wave_no = :waveNo @@ -753,11 +779,12 @@ class PickService extends MainService { targetWaveId = Number(waveRow.wave_id || 0); targetWaveNo = String(waveRow.wave_no || '').trim(); targetWaveType = Number(waveRow.wave_type || 2); + targetWaveSource = Number(waveRow.source || 0); } } else { const waveRows = await ctx.model.query( ` - SELECT wave_id, wave_no, wave_type + SELECT wave_id, wave_no, wave_type, source FROM wms_wave_batch WHERE warehouse_id = :warehouseId AND wave_no = :waveNo @@ -780,12 +807,45 @@ class PickService extends MainService { targetWaveId = Number(waveRow.wave_id || 0); targetWaveNo = String(waveRow.wave_no || '').trim(); targetWaveType = Number(waveRow.wave_type || 2); + targetWaveSource = Number(waveRow.source || 0); } if (!Number.isInteger(targetWaveId) || targetWaveId <= 0 || !targetWaveNo) { return this.fail('目标波次信息不完整', {}, 400); } + // 领料前置校验:source=0 普通波次需整波领料,未领料阻隔创建拣货任务 + // (拦截订单未领料不阻隔拣货,拦截订单将在任务创建时被剔除) + if (targetWaveSource === 0) { + const claimGatePickMode = await this.getWavePickModeByWaveId(targetWaveId); + let claimGateOrderModel = null; + try { + claimGateOrderModel = await this.getOrderModelByWarehouse(normalizedWarehouseId); + } catch (error) { + return this.fail(error && error.message ? error.message : '订单模型不可用', {}, 500); + } + + const claimGateStats = await this.getWaveClaimGateStats({ + orderModel: claimGateOrderModel, + warehouseId: normalizedWarehouseId, + waveId: targetWaveId, + waveNo: targetWaveNo, + }); + if (claimGateStats.total_order_count > 0 && claimGateStats.unclaimed_order_count > 0) { + return this.fail('订单未领料,请先领料后再拣货', { + action: 'wave_claim', + wave_id: targetWaveId, + wave_no: targetWaveNo, + wave_type: targetWaveType, + wave_source: targetWaveSource, + pick_mode: claimGatePickMode, + unclaimed_order_count: claimGateStats.unclaimed_order_count, + intercepted_order_count: claimGateStats.intercepted_order_count, + total_order_count: claimGateStats.total_order_count, + }, 400); + } + } + const activeTaskRows = await ctx.model.query( ` SELECT t.id AS task_id, t.pick_user_id, t.pick_user_name @@ -1042,6 +1102,8 @@ class PickService extends MainService { orderIds: selectedOrderIds, remark: `pick.query keyword=${normalizedKeyword}`, source: 2, + // 普通波次(source=0):计算拣货数量时剔除未领料(claim_status != fin)订单 + excludeUnclaimed: targetWaveSource === 0, }); return this.success('ok', { @@ -1226,7 +1288,7 @@ class PickService extends MainService { // --- 按 wave_id 直接查波次 --- const waveRows = await ctx.model.query( - `SELECT wave_id, wave_no, wave_type + `SELECT wave_id, wave_no, wave_type, source FROM wms_wave_batch WHERE warehouse_id = :warehouseId AND wave_id = :waveId @@ -1244,6 +1306,7 @@ class PickService extends MainService { const targetWaveId = Number(waveRow.wave_id || 0); const targetWaveNo = String(waveRow.wave_no || '').trim(); const targetWaveType = Number(waveRow.wave_type || 2); + const targetWaveSource = Number(waveRow.source || 0); if (!Number.isInteger(targetWaveId) || targetWaveId <= 0 || !targetWaveNo) { return this.fail('目标波次信息不完整', {}, 400); @@ -1392,6 +1455,8 @@ class PickService extends MainService { orderIds: selectedOrderIds, remark: `pick.wavePickComplete wave_id=${waveId}`, source: 2, + // 普通波次(source=0):计算拣货数量时剔除未领料(claim_status != fin)订单 + excludeUnclaimed: targetWaveSource === 0, }); taskId = createdTask.task_id; } catch (error) { @@ -1537,6 +1602,78 @@ class PickService extends MainService { return linkRow ? Number(linkRow.pick_mode || 0) : 0; } + /** + * 统计波次下领料门禁相关数量(普通波次 source=0 领料前置校验)。 + * + * 统计口径: + * - total_order_count:波次下全部订单数(含拦截订单); + * - intercepted_order_count:拦截订单数(intercept_status != none); + * - unclaimed_order_count:非拦截且未领料(claim_status != fin)订单数, + * 拦截订单未领料不阻隔拣货,不计入该数量。 + * + * @param {Object} params 统计参数。 + * @param {Object} params.orderModel 订单分表模型。 + * @param {number} params.warehouseId 仓库ID。 + * @param {number} params.waveId 波次ID。 + * @param {string} [params.waveNo=''] 波次编码(wave_id 未命中时回退按 wave_no 统计)。 + * @return {Promise<{total_order_count: number, intercepted_order_count: number, unclaimed_order_count: number}>} + * 统计结果。 + */ + async getWaveClaimGateStats(params = {}) { + const { ctx } = this; + const orderModel = params && params.orderModel; + const warehouseId = Number(params && params.warehouseId || 0); + const waveId = Number(params && params.waveId || 0); + const waveNo = String(params && params.waveNo || '').trim(); + if (!orderModel || typeof orderModel.findAll !== 'function') { + ctx.logger.warn('[pick.getWaveClaimGateStats] 订单模型不可用,返回空统计'); + return { total_order_count: 0, intercepted_order_count: 0, unclaimed_order_count: 0 }; + } + + let rows = []; + if (Number.isInteger(waveId) && waveId > 0) { + rows = await orderModel.findAll({ + where: { + warehouse_id: warehouseId, + wave_id: waveId, + }, + attributes: [ 'id', 'claim_status', 'intercept_status' ], + raw: true, + }); + rows = Array.isArray(rows) ? rows : []; + } + if (rows.length === 0 && waveNo) { + const fallbackRows = await orderModel.findAll({ + where: { + warehouse_id: warehouseId, + wave_no: waveNo, + }, + attributes: [ 'id', 'claim_status', 'intercept_status' ], + raw: true, + }); + rows = Array.isArray(fallbackRows) ? fallbackRows : []; + } + + const orderIds = [ ...new Set(rows + .map(item => Number(item && item.id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ]; + const interceptedOrderIds = new Set(rows + .filter(item => isInterceptedOrderStatus(item && item.intercept_status)) + .map(item => Number(item && item.id || 0)) + .filter(id => Number.isInteger(id) && id > 0)); + const unclaimedOrderCount = rows + .filter(item => String(item && item.claim_status || '') !== 'fin' + && orderIds.includes(Number(item && item.id || 0)) + && !interceptedOrderIds.has(Number(item && item.id || 0))) + .length; + + return { + total_order_count: orderIds.length, + intercepted_order_count: interceptedOrderIds.size, + unclaimed_order_count: unclaimedOrderCount, + }; + } + /** * 扫描面单号领取整波(领料)。 * @@ -1546,8 +1683,10 @@ class PickService extends MainService { * 并写入 ORDER_WAVE_CLAIM 订单操作日志,返回波次ID(wave_id)与波次编码(wave_no); * 策略抓取波次(source=1/2)无需领料,返回 400 并提示「该波次为抓取波次,无需领料」 * (失败 data 含 no_claim_needed=true、wave_id、wave_no); - * 波次下存在未打印订单(print_status != fin)时禁止领料, - * 返回 400 并提示「波次未打印,禁止领料」(失败 data 含 wave_id、wave_no、unprinted_order_count); + * 波次下存在未打印订单(print_status != fin,拦截订单除外)时禁止领料, + * 返回 400 并提示「波次未打印,禁止领料」(失败 data 含 wave_id、wave_no、unprinted_order_count、 + * intercepted_order_count,拦截订单未打印不阻隔领料); + * 拦截订单整体跳过领料:既不置为领料完成,其未打印状态也不阻隔整波领料。 * 其余未知类型返回通用不支持提示。 * 波次内订单已全部领单时返回 already_claimed 幂等结果并提示已领料。 * @@ -1702,7 +1841,7 @@ class PickService extends MainService { warehouse_id: normalizedWarehouseId, wave_id: targetWaveId, }, - attributes: [ 'id', 'claim_status', 'print_status' ], + attributes: [ 'id', 'claim_status', 'print_status', 'intercept_status' ], raw: true, }); let waveOrders = Array.isArray(waveOrderRows) ? waveOrderRows : []; @@ -1712,7 +1851,7 @@ class PickService extends MainService { warehouse_id: normalizedWarehouseId, wave_no: targetWaveNo, }, - attributes: [ 'id', 'claim_status', 'print_status' ], + attributes: [ 'id', 'claim_status', 'print_status', 'intercept_status' ], raw: true, }); waveOrders = Array.isArray(fallbackRows) ? fallbackRows : []; @@ -1725,8 +1864,15 @@ class PickService extends MainService { } const totalOrderCount = waveOrderIds.length; + // 拦截订单整体跳过领料:不参与领取(保持未领料),其未打印/未领料状态也不阻隔领料与拣货 + const interceptedWaveOrderIds = new Set(waveOrders + .filter(item => isInterceptedOrderStatus(item && item.intercept_status)) + .map(item => Number(item && item.id || 0)) + .filter(id => Number.isInteger(id) && id > 0)); + const unclaimedOrderIds = [ ...new Set(waveOrders - .filter(item => String(item && item.claim_status || '') !== 'fin') + .filter(item => String(item && item.claim_status || '') !== 'fin' + && !interceptedWaveOrderIds.has(Number(item && item.id || 0))) .map(item => Number(item && item.id || 0)) .filter(id => Number.isInteger(id) && id > 0)) ]; @@ -1739,6 +1885,7 @@ class PickService extends MainService { matched_order_id: matchedOrderId, waybill_no: waybillNo, total_order_count: totalOrderCount, + intercepted_order_count: interceptedWaveOrderIds.size, }; if (unclaimedOrderIds.length === 0) { @@ -1754,8 +1901,10 @@ class PickService extends MainService { } // 波次打印校验:存在未打印订单(print_status != fin)时禁止整波领料 + // (拦截订单的未打印状态不阻隔领料) const unprintedOrderIds = [ ...new Set(waveOrders - .filter(item => String(item && item.print_status || '') !== 'fin') + .filter(item => String(item && item.print_status || '') !== 'fin' + && !interceptedWaveOrderIds.has(Number(item && item.id || 0))) .map(item => Number(item && item.id || 0)) .filter(id => Number.isInteger(id) && id > 0)) ]; if (unprintedOrderIds.length > 0) { diff --git a/app/service/systemMethods/returnUnpack.js b/app/service/systemMethods/returnUnpack.js index e8d6a0e..c002891 100644 --- a/app/service/systemMethods/returnUnpack.js +++ b/app/service/systemMethods/returnUnpack.js @@ -192,6 +192,36 @@ class ReturnUnpackMethodService extends MainService { ); } + /** + * 分页查询拆包录像列表(查,按拆包单维度校验仓库隔离)。 + * + * @param {Object} data 请求体。 + * @param {Object} [data.pagination] 分页参数。 + * @param {Object} [data.where] 筛选条件(unpack_id 必填,camera_id/status 可选)。 + * @param {Object} [data.sort] 排序参数。 + * @return {Promise} 统一 success 包装。 + */ + async videoList(data = {}) { + const { service } = this; + const { pagination, sort } = data; + const { where, whereValue } = this.prepareWhereContext(data, {}); + + const unpackId = Number((whereValue && whereValue.unpack_id) || 0); + + return this._call(async () => { + if (!Number.isFinite(unpackId) || unpackId <= 0) { + throw service.systems.returnUnpack.createBusinessError('unpack_id 必填且必须为正整数', 400); + } + // 拆包单仓库隔离校验(不存在 404 / 跨仓库 403) + await service.systems.returnUnpack._findByIdChecked(unpackId); + return service.systems.returnUnpack.videoList( + { ...where, unpack_id: unpackId }, + pagination, + sort + ); + }, '查询录像列表失败'); + } + /** * 查询拆包单详情(查)。 * diff --git a/app/service/systemMethods/stock/warehouse.js b/app/service/systemMethods/stock/warehouse.js index 3479ff6..6aa93d3 100644 --- a/app/service/systemMethods/stock/warehouse.js +++ b/app/service/systemMethods/stock/warehouse.js @@ -526,6 +526,7 @@ class WarehouseService extends MainService { is_sn_mgmt, is_shelf_life_mgmt, is_batch_mgmt, + need_recheck, prohibited_id, brand_name, managementFlags, @@ -568,6 +569,7 @@ class WarehouseService extends MainService { is_sn_mgmt, is_shelf_life_mgmt, is_batch_mgmt, + need_recheck, prohibited_id, brand_name, managementFlags, @@ -761,6 +763,7 @@ class WarehouseService extends MainService { ?? goodsCode ?? ''; const storeId = pickValue([ 'store_id', 'storeId' ]) ?? this.ctx?.user?.store_id; + const needRecheckRaw = pickValue([ '是否需要复核', 'need_recheck', 'needRecheck' ]); return { ...row, @@ -775,12 +778,31 @@ class WarehouseService extends MainService { gross_weight: pickValue([ '毛重', 'gross_weight', 'grossWeight' ]), tag_price: pickValue([ '标价', 'tag_price', 'tagPrice' ]), retail_price: pickValue([ '零售价', 'retail_price', 'retailPrice' ]), + ...(needRecheckRaw !== undefined && { need_recheck: this._normalizeNeedRecheckValue(needRecheckRaw) }), barcode: this._normalizeBarcodeField( pickValue([ '条码', 'bar_code', 'barCode', 'barcodeList', 'barcode_list', 'barcode' ]) ), }; } + /** + * 归一化「是否需要复核」字段值:需要 → Y,不需要 → N。 + * 支持中文(需要/需要复核/不需要/无需复核)、Y/N、1/0、布尔值。 + * + * @param {string|number|boolean} raw 原始值 + * @return {string} 'Y' 或 'N' + */ + _normalizeNeedRecheckValue(raw) { + const normalized = String(raw ?? '').trim(); + if ([ '需要', '需要复核', 'Y', 'y', '1' ].includes(normalized) || raw === true) { + return 'Y'; + } + if ([ '不需要', '无需', '无需复核', 'N', 'n', '0' ].includes(normalized) || raw === false) { + return 'N'; + } + throw new Error(`是否需要复核值不合法: ${raw},仅支持 需要/不需要`); + } + /** * 归一化条码字段,只接受逗号分隔的字符串格式,返回去重后的条码数组。 * 与 stock.warehouse.export 导出格式对齐(导出使用逗号分隔)。 diff --git a/app/service/systems/order_print.js b/app/service/systems/order_print.js index 8a0940b..de1ecb6 100644 --- a/app/service/systems/order_print.js +++ b/app/service/systems/order_print.js @@ -543,6 +543,12 @@ class OrderPrintSystemService extends OrderBaseService { }; } + // 波次元信息映射(source / wave_type),供自定义区「波次总单数×数量」行尾规则使用 + const waveMetaMap = new Map(); + for (const waveRow of waveRows) { + waveMetaMap.set(Number(waveRow.wave_id), waveRow); + } + 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)); @@ -677,11 +683,14 @@ class OrderPrintSystemService extends OrderBaseService { const waveTotalOrders = Number(waveTotalOrderCountMap.get(waveIdForCount) || 0); const waveIndex = Number(waveOrderIndexInfo.wave_index || 0); const platformsIndex = Number(waveOrderIndexInfo.platforms_index || 0); + const waveMetaRow = waveMetaMap.get(waveIdForCount) || {}; const effectiveOrderRowWithWaveIndex = { ...effectiveOrderRow, wave_total_orders: waveTotalOrders > 0 ? waveTotalOrders : 0, wave_index: waveIndex > 0 ? waveIndex : 0, platforms_index: platformsIndex > 0 ? platformsIndex : 0, + wave_source: Number(waveMetaRow.source || 0), + wave_type: Number(waveMetaRow.wave_type || 0), }; const storeId = Number(orderRow && orderRow.store_id || 0); const policyConfig = policyConfigMap.get(storeId) || {}; @@ -830,6 +839,12 @@ class OrderPrintSystemService extends OrderBaseService { const waveRows = await this.queryWavesByIds(normalizedWarehouseId, validOrderWaveIds); + // 波次元信息映射(source / wave_type),供自定义区「波次总单数×数量」行尾规则使用 + const waveMetaMap = new Map(); + for (const waveRow of waveRows) { + waveMetaMap.set(Number(waveRow.wave_id), waveRow); + } + const orderIdsForExpress = validOrderRows .map(row => Number(row && row.id || 0)) .filter(orderId => Number.isInteger(orderId) && orderId > 0); @@ -881,11 +896,14 @@ class OrderPrintSystemService extends OrderBaseService { const waveTotalOrders = Number(waveTotalOrderCountMap.get(waveIdForCount) || 0); const waveIndex = Number(waveOrderIndexInfo.wave_index || 0); const platformsIndex = Number(waveOrderIndexInfo.platforms_index || 0); + const waveMetaRow = waveMetaMap.get(waveIdForCount) || {}; const effectiveOrderRowWithWaveIndex = { ...effectiveOrderRow, wave_total_orders: waveTotalOrders > 0 ? waveTotalOrders : 0, wave_index: waveIndex > 0 ? waveIndex : 0, platforms_index: platformsIndex > 0 ? platformsIndex : 0, + wave_source: Number(waveMetaRow.source || 0), + wave_type: Number(waveMetaRow.wave_type || 0), }; const storeId = Number(orderRow && orderRow.store_id || 0); const policyConfig = policyConfigMap.get(storeId) || {}; @@ -1121,6 +1139,12 @@ class OrderPrintSystemService extends OrderBaseService { .filter(waveId => Number.isInteger(waveId) && waveId > 0))); const waveRows = await this.queryWavesByIds(normalizedWarehouseId, validOrderWaveIds); + // 波次元信息映射(source / wave_type),供自定义区「波次总单数×数量」行尾规则使用 + const waveMetaMap = new Map(); + for (const waveRow of waveRows) { + waveMetaMap.set(Number(waveRow.wave_id), waveRow); + } + const orderIdsForIndex = validOrderRows.map(row => Number(row.id)).filter(id => id > 0); const waveOrderIndexMap = await this.queryWaveOrderIndexMapByOrderIds( orderIdsForIndex, normalizedWarehouseId, validOrderWaveIds @@ -1141,11 +1165,14 @@ class OrderPrintSystemService extends OrderBaseService { const waveTotalOrders = Number(waveTotalOrderCountMap.get(waveIdForCount) || 0); const waveIndex = Number(waveOrderIndexInfo.wave_index || 0); const platformsIndex = Number(waveOrderIndexInfo.platforms_index || 0); + const waveMetaRow = waveMetaMap.get(waveIdForCount) || {}; const effectiveOrderRowWithWaveIndex = { ...effectiveOrderRow, wave_total_orders: waveTotalOrders > 0 ? waveTotalOrders : 0, wave_index: waveIndex > 0 ? waveIndex : 0, platforms_index: platformsIndex > 0 ? platformsIndex : 0, + wave_source: Number(waveMetaRow.source || 0), + wave_type: Number(waveMetaRow.wave_type || 0), }; const storeId = Number(orderRow.store_id || 0); @@ -1750,7 +1777,7 @@ class OrderPrintSystemService extends OrderBaseService { } const querySql = ` - SELECT wave_id, wave_no + SELECT wave_id, wave_no, source, wave_type FROM wms_wave_batch WHERE warehouse_id = :warehouseId AND wave_id IN (:waveIds) @@ -1955,7 +1982,7 @@ class OrderPrintSystemService extends OrderBaseService { * 返回 business_key=1 的主运单,按 order_id、business_key、id 升序排列。 * * @param {number[]} orderIds 订单 ID 列表。 - * @param warehouseId + * @param {number} warehouseId 仓库ID。 * @return {Promise>} 匹配的运单记录数组,字段包含 id、order_id、business_key、waybill_code、 * logistics_code、logistics_name、logistics_interface_id、logistics_interface_name、platform_code、 * warehouse_id、printinfo、signature、encryptprintinfo、ver。 diff --git a/app/service/systems/return_unpack.js b/app/service/systems/return_unpack.js index d852683..79952af 100644 --- a/app/service/systems/return_unpack.js +++ b/app/service/systems/return_unpack.js @@ -536,12 +536,30 @@ class ReturnUnpackService extends Service { order, offset: (page - 1) * pageSize, limit: pageSize, - raw: true, + raw: false, + include: [ + { + model: ctx.model.ReturnUnpackVideo, + as: 'videos', + attributes: [ 'id', 'video_url', 'camera_id', 'status' ], + where: { deleted_at: null }, + required: false, + include: [ + { + model: ctx.model.Camera, + as: 'camera', + attributes: [ 'id', 'custom_name', 'channel_name' ], + required: false, + }, + ], + }, + ], }); const list = []; for (const row of rows) { - list.push(await this._enrichRow(row)); + const plain = row && typeof row.toJSON === 'function' ? row.toJSON() : row; + list.push(this._flattenVideos(await this._enrichRow(plain))); } return { @@ -609,6 +627,69 @@ class ReturnUnpackService extends Service { }; } + /** + * 分页查询拆包录像列表(unpack_id 维度,仓库隔离由方法层校验)。 + * + * @param {Object} where 标准化 where 条件对象(unpack_id 必填)。 + * @param {Object} [pagination] 分页参数。 + * @param {Object} [sort] 排序参数。 + * @return {Promise} { list, pagination }。 + */ + async videoList(where = {}, pagination = {}, sort = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + const page = Math.max(1, parseInt(pagination.page) || 1); + const pageSize = Math.min(500, Math.max(1, parseInt(pagination.pageSize) || 20)); + + const queryWhere = this._buildVideoListWhere(where, Op); + const order = this._buildVideoListOrder(sort); + + const { count, rows } = await ctx.model.ReturnUnpackVideo.findAndCountAll({ + where: queryWhere, + include: [ + { + model: ctx.model.Camera, + as: 'camera', + required: false, + }, + ], + order, + offset: (page - 1) * pageSize, + limit: pageSize, + raw: false, + }); + + const list = rows + .map(row => (row && typeof row.toJSON === 'function' ? row.toJSON() : row)) + .map(row => { + const camera = row.camera || {}; + return { + id: row.id, + unpack_id: row.unpack_id, + video_url: row.video_url, + status: row.status || null, + camera_id: row.camera_id || null, + camera_name: (camera.custom_name || camera.channel_name) || null, + remark: row.remark || null, + created_at: row.created_at ? app.formatDate(row.created_at) : null, + updated_at: row.updated_at ? app.formatDate(row.updated_at) : null, + }; + }); + + return { + list, + pagination: { + page, + pageSize, + total: count, + totalPages: Math.ceil(count / pageSize), + hasPrevious: page > 1, + hasNext: page * pageSize < count, + }, + }; + } + /** * 查询拆包单详情:主表 + 明细 + 视频 + 退回收到单 + 原订单详情(原单退回时)。 * @@ -1212,6 +1293,12 @@ class ReturnUnpackService extends Service { record.is_original_return = Boolean(record.order_express_id); + // 视频派生字段(与 order.packing.list 对齐):记录含 videos 数组时计算 + if (Array.isArray(record.videos)) { + record.has_video = record.videos.length > 0 ? 1 : 2; + record.video_enable = record.videos.some(v => v.video_url && v.status !== 'failed') ? 1 : 2; + } + // camera_ids 归一化为数组(MySQL JSON 列可能返回字符串) if (record.camera_ids !== undefined && record.camera_ids !== null) { if (typeof record.camera_ids === 'string') { @@ -1238,6 +1325,27 @@ class ReturnUnpackService extends Service { return record; } + /** + * 列表场景视频数组扁平化(对齐 order.packing.list 输出口径)。 + * 仅输出前端需要的精简字段(id/video_url/status/camera_id/camera_name); + * detail 等场景的 videos 保持完整关联结构不变。 + * + * @param {Object} row 主表记录(含 videos 关联数组)。 + * @return {Object} 扁平化后的记录。 + */ + _flattenVideos(row) { + if (Array.isArray(row.videos)) { + row.videos = row.videos.map(v => ({ + id: v.id, + video_url: v.video_url, + status: v.status || null, + camera_id: v.camera_id || null, + camera_name: (v.camera && (v.camera.custom_name || v.camera.channel_name)) || null, + })); + } + return row; + } + /** * 批量附加库存详情(条码/图片等)到明细行。 * 统一走 stockWarehouse.getStockDetails 通用方法(带缓存,含 barcodes/image_url/ @@ -1383,6 +1491,30 @@ class ReturnUnpackService extends Service { _buildListWhere(where = {}, Op) { const queryWhere = {}; + // has_video 筛选:1=有视频记录 2=无视频记录(口径对齐 order.packing.list) + if (where.has_video !== undefined && where.has_video !== null) { + const hasVideoValue = Number(where.has_video?.value ?? where.has_video); + if (hasVideoValue === 1 || hasVideoValue === 2) { + const existsSql = 'EXISTS (SELECT 1 FROM wms_return_unpack_video WHERE unpack_id = wms_return_unpack.id AND deleted_at IS NULL)'; + const cond = hasVideoValue === 1 + ? this.app.Sequelize.literal(existsSql) + : this.app.Sequelize.literal(`NOT ${existsSql}`); + queryWhere[Op.and] = [ ...(queryWhere[Op.and] || []), cond ]; + } + } + + // video_enable 筛选:1=录像可用 2=录像不可用(口径对齐 order.packing.list) + if (where.video_enable !== undefined && where.video_enable !== null) { + const videoEnableValue = Number(where.video_enable?.value ?? where.video_enable); + if (videoEnableValue === 1 || videoEnableValue === 2) { + const existsSql = "EXISTS (SELECT 1 FROM wms_return_unpack_video WHERE unpack_id = wms_return_unpack.id AND deleted_at IS NULL AND video_url != '' AND status != 'failed')"; + const cond = videoEnableValue === 1 + ? this.app.Sequelize.literal(existsSql) + : this.app.Sequelize.literal(`NOT ${existsSql}`); + queryWhere[Op.and] = [ ...(queryWhere[Op.and] || []), cond ]; + } + } + const directFields = [ 'warehouse_id', 'unpacker_id', 'return_received_id', 'store_id', 'order_express_id', 'order_id', 'status', 'detail_status', @@ -1437,6 +1569,46 @@ class ReturnUnpackService extends Service { return queryWhere; } + /** + * 构建录像列表 where 条件(unpack_id 必填等值;camera_id/status 可选等值)。 + * + * @param {Object} where 标准化条件对象。 + * @param {Object} Op Sequelize Op 对象。 + * @return {Object} Sequelize where 条件。 + */ + _buildVideoListWhere(where = {}, Op) { + const queryWhere = {}; + + if (where.unpack_id !== undefined && where.unpack_id !== null) { + queryWhere.unpack_id = this._resolveConditionValue(where.unpack_id, Op); + } + if (where.camera_id !== undefined && where.camera_id !== null) { + queryWhere.camera_id = this._resolveConditionValue(where.camera_id, Op); + } + if (where.status !== undefined && where.status !== null) { + queryWhere.status = this._resolveConditionValue(where.status, Op); + } + + return queryWhere; + } + + /** + * 录像列表排序(默认按 id 升序)。 + * + * @param {Object} sort 排序参数。 + * @return {Array>} Sequelize order 数组。 + */ + _buildVideoListOrder(sort = {}) { + const sortField = sort.sortField || sort.sort_field || 'id'; + const sortOrderRaw = (sort.sortOrder || sort.sort_order || 'asc').toLowerCase(); + const sortOrder = sortOrderRaw === 'asc' ? 'ASC' : 'DESC'; + + const allowed = new Set([ 'id', 'created_at', 'updated_at', 'camera_id' ]); + const safeSortField = allowed.has(sortField) ? sortField : 'id'; + + return [[ safeSortField, sortOrder ]]; + } + /** * 解析标准化条件值为 Sequelize 可用的条件对象。 * diff --git a/app/service/systems/stock_store.js b/app/service/systems/stock_store.js index 599eee3..28b1b29 100644 --- a/app/service/systems/stock_store.js +++ b/app/service/systems/stock_store.js @@ -2218,6 +2218,7 @@ class stockStoreService extends Service { tag_price: item.tag_price || '', retail_price: item.retail_price || '', gross_weight: item.gross_weight || '', + need_recheck: String(item.need_recheck || 'Y') === 'Y' ? '需要' : '不需要', store_remask, barcodes: Array.isArray(item.barcodes) ? item.barcodes.join(',') : '', quantity: item.quantity, @@ -2253,6 +2254,7 @@ class stockStoreService extends Service { { header: '标价', key: 'tag_price' }, { header: '零售价', key: 'retail_price' }, { header: '毛重', key: 'gross_weight' }, + { header: '是否需要复核', key: 'need_recheck' }, { header: '货主', key: 'store_remask' }, { header: '条码', key: 'barcodes' }, { header: '库存', key: 'quantity' }, @@ -2343,6 +2345,7 @@ class stockStoreService extends Service { tag_price: item.tag_price || '', retail_price: item.retail_price || '', gross_weight: item.gross_weight || '', + need_recheck: String(item.need_recheck || 'Y') === 'Y' ? '需要' : '不需要', store_remask: storeRemask, barcodes: Array.isArray(item.barcodes) ? item.barcodes.join(',') : '', quantity: item.quantity, @@ -2378,6 +2381,7 @@ class stockStoreService extends Service { { header: '标价', key: 'tag_price' }, { header: '零售价', key: 'retail_price' }, { header: '毛重', key: 'gross_weight' }, + { header: '是否需要复核', key: 'need_recheck' }, { header: '货主', key: 'store_remask' }, { header: '条码', key: 'barcodes' }, { header: '库存', key: 'quantity' }, @@ -2530,7 +2534,7 @@ class stockStoreService extends Service { const { ctx, app } = this; const { Op } = app.Sequelize; - const canChangeFlide = [ 'brand_name', 'prohibited_id', 'gross_weight', 'packing_requirements', 'managementFlags', 'stock_unit' ]; + const canChangeFlide = [ 'brand_name', 'prohibited_id', 'gross_weight', 'packing_requirements', 'managementFlags', 'stock_unit', 'need_recheck' ]; const { ids, method, value } = ctx.request.body; @@ -2601,6 +2605,18 @@ class stockStoreService extends Service { update_by: ctx.user.id || ctx.user.username, }; + } else if (method === 'need_recheck') { + // 是否需要复核:Y=需要复核,N=不需要复核 + const updateValue = String(value).trim().toUpperCase(); + if (![ 'Y', 'N' ].includes(updateValue)) { + return { message: '是否需要复核必须是 Y(需要复核)或 N(不需要复核)', code: 405 }; + } + updateData = { + need_recheck: updateValue, + update_at: new Date(), + update_by: ctx.user.id || ctx.user.username, + }; + } else if (method === 'managementFlags') { // 管理标识是对象格式,需要更新三个独立字段 if (typeof value !== 'object') { @@ -3001,6 +3017,7 @@ class stockStoreService extends Service { 'is_batch_mgmt', 'is_shelf_life_mgmt', 'is_sn_mgmt', + 'need_recheck', 'goods_code', 'item_code', 'item_name', @@ -3055,6 +3072,7 @@ class stockStoreService extends Service { box_width, box_height, box_volume, box_remark, id, box_volume_m3, boxVolumeM3, shelf_life_days, inbound_min_days, outbound_min_days, remaining_threshold_days, + need_recheck, } = data; const normalizedVolume = volume ?? volume_cm3 ?? volumeCm3; const normalizedBoxVolume = box_volume ?? box_volume_m3 ?? boxVolumeM3; @@ -3128,6 +3146,7 @@ class stockStoreService extends Service { is_sn_mgmt: is_sn_mgmt || false, is_shelf_life_mgmt: is_shelf_life_mgmt || false, is_batch_mgmt: is_batch_mgmt || false, + need_recheck, prohibited_id: prohibited_id_tmp, brand_name, ...(managementFlags && { management_flags: managementFlags }), @@ -3211,6 +3230,7 @@ class stockStoreService extends Service { enable_box_spec, box_unit, quantity_per_box, box_gross_weight, box_net_weight, box_length, box_width, box_height, box_volume, box_remark, + need_recheck, } = data; // 1. 参数验证 @@ -3244,6 +3264,7 @@ class stockStoreService extends Service { is_sn_mgmt: is_sn_mgmt || false, is_shelf_life_mgmt: is_shelf_life_mgmt || false, is_batch_mgmt: is_batch_mgmt || false, + need_recheck: need_recheck || 'Y', prohibited_id, brand_name, ...(managementFlags && { management_flags: managementFlags }), @@ -3304,6 +3325,11 @@ class stockStoreService extends Service { throw new Error('启用箱规时,每箱数量必须大于0'); } + // 是否需要复核:仅允许 Y(需要)/ N(不需要) + if (data.need_recheck !== undefined && data.need_recheck !== null && ![ 'Y', 'N' ].includes(String(data.need_recheck).trim())) { + throw new Error('need_recheck 必须是 Y(需要复核)或 N(不需要复核)'); + } + // 数值类型验证 const numericFields = [ 'length', 'width', 'height', 'volume', 'gross_weight', 'net_weight' ]; for (const field of numericFields) { diff --git a/database/migrations/20260822140000-add-unique-wave-no-to-wms-wave-batch.js b/database/migrations/20260822140000-add-unique-wave-no-to-wms-wave-batch.js new file mode 100644 index 0000000..736edf0 --- /dev/null +++ b/database/migrations/20260822140000-add-unique-wave-no-to-wms-wave-batch.js @@ -0,0 +1,254 @@ +'use strict'; + +/** + * wms_wave_batch.wave_no 唯一化。 + * + * 背景:并发创建波次时「查当日最大序号+1」存在竞态,可能产生 wave_no 相同的多行 + * (不同 wave_id、不同订单组),导致两组订单共用一个波次号。 + * + * 本迁移: + * 1. 修复存量重复波次号:同一 wave_no 保留最早(wave_id 最小)一行, + * 其余行按「前缀+日期+下一个空闲序号」重新编号,并同步引用方数据 + * (订单表四个车道、拣货任务波次关联表、打印记录、打包任务)的 wave_no; + * 2. 移除冗余的非唯一索引 idx_wave_no(若存在); + * 3. 新增唯一索引 uniq_wave_no(若已人工添加则跳过,保证幂等)。 + */ + +const TABLE_NAME = 'wms_wave_batch'; + +/** + * 归一化索引字段名(Sequelize 各版本返回 string 或 { attribute } 对象)。 + * + * @param {Array} fields 索引字段列表。 + * @return {Array} 字段名字符串列表。 + */ +function normalizeIndexFields(fields) { + return (Array.isArray(fields) ? fields : []) + .map(field => String( + typeof field === 'string' ? field : (field && (field.attribute || field.name || '')) + ).trim()) + .filter(Boolean); +} + +/** + * 判断索引列表是否包含指定名称的非唯一/唯一 wave_no 索引。 + * + * @param {Array} indexes showIndex 结果。 + * @param {string} indexName 索引名称。 + * @param {boolean} unique 是否唯一索引。 + * @return {boolean} 是否存在。 + */ +function hasWaveNoIndex(indexes, indexName, unique) { + return (Array.isArray(indexes) ? indexes : []).some(index => { + if (!index || index.name !== indexName) { + return false; + } + const fields = normalizeIndexFields(index.fields); + return fields.length === 1 && fields[0] === 'wave_no' && Boolean(index.unique) === unique; + }); +} + +/** + * 查询存量重复的波次号。 + * + * @param {Object} queryInterface Sequelize 查询接口。 + * @return {Promise>} 重复波次号列表。 + */ +async function fetchDuplicateWaveNos(queryInterface) { + return await queryInterface.sequelize.query( + `SELECT wave_no, COUNT(*) AS cnt + FROM ${TABLE_NAME} + GROUP BY wave_no + HAVING COUNT(*) > 1 + ORDER BY wave_no ASC`, + { type: queryInterface.sequelize.QueryTypes.SELECT } + ); +} + +/** + * 计算「前缀+日期」片段下下一个空闲波次号。 + * + * @param {Object} queryInterface Sequelize 查询接口。 + * @param {string} prefixDate 波次号前缀+日期片段(如 B20260822)。 + * @return {Promise} 下一个空闲波次号。 + */ +async function buildNextFreeWaveNo(queryInterface, prefixDate) { + const startPos = String(prefixDate).length + 1; + const rows = await queryInterface.sequelize.query( + `SELECT IFNULL(MAX(CAST(SUBSTRING(wave_no, :startPos) AS UNSIGNED)), 0) + 1 AS seq + FROM ${TABLE_NAME} + WHERE wave_no LIKE :pattern`, + { + replacements: { startPos, pattern: `${prefixDate}%` }, + type: queryInterface.sequelize.QueryTypes.SELECT, + } + ); + const seq = Number(rows && rows[0] && rows[0].seq || 1); + return `${prefixDate}${String(seq).padStart(5, '0')}`; +} + +/** + * 判断波次号是否已存在。 + * + * @param {Object} queryInterface Sequelize 查询接口。 + * @param {string} waveNo 波次号。 + * @return {Promise} 是否已存在。 + */ +async function waveNoExists(queryInterface, waveNo) { + const rows = await queryInterface.sequelize.query( + `SELECT wave_id FROM ${TABLE_NAME} WHERE wave_no = :waveNo LIMIT 1`, + { replacements: { waveNo }, type: queryInterface.sequelize.QueryTypes.SELECT } + ); + return Array.isArray(rows) && rows.length > 0; +} + +/** + * 更新指定表内该波次的 wave_no(表不存在时跳过)。 + * + * @param {Object} queryInterface Sequelize 查询接口。 + * @param {string} tableName 表名。 + * @param {number} warehouseId 仓库ID。 + * @param {number} waveId 波次ID。 + * @param {string} waveNo 新波次号。 + * @return {Promise} 无返回值。 + */ +async function updateTableWaveNo(queryInterface, tableName, warehouseId, waveId, waveNo) { + const checkRows = await queryInterface.sequelize.query( + `SELECT TABLE_NAME + FROM information_schema.TABLES + WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = :tableName`, + { replacements: { tableName }, type: queryInterface.sequelize.QueryTypes.SELECT } + ); + if (!Array.isArray(checkRows) || checkRows.length === 0) { + return; + } + + await queryInterface.sequelize.query( + `UPDATE \`${tableName}\` + SET wave_no = :waveNo + WHERE warehouse_id = :warehouseId + AND wave_id = :waveId + AND wave_no <> :waveNo`, + { replacements: { waveNo, warehouseId, waveId } } + ); +} + +/** + * 同步某波次被重编号后所有引用方表中的 wave_no。 + * + * @param {Object} queryInterface Sequelize 查询接口。 + * @param {number} warehouseId 仓库ID。 + * @param {number} waveId 波次ID。 + * @param {string} waveNo 新波次号。 + * @return {Promise} 无返回值。 + */ +async function syncWaveNoReferences(queryInterface, warehouseId, waveId, waveNo) { + if (Number.isInteger(warehouseId) && warehouseId > 0) { + await updateTableWaveNo(queryInterface, `wms_order_delivery_${warehouseId}`, warehouseId, waveId, waveNo); + await updateTableWaveNo(queryInterface, `wms_order_delivery_${warehouseId}_history`, warehouseId, waveId, waveNo); + await updateTableWaveNo(queryInterface, `wms_order_delivery_${warehouseId}_dispatch`, warehouseId, waveId, waveNo); + await updateTableWaveNo(queryInterface, `wms_order_delivery_${warehouseId}_outsourced`, warehouseId, waveId, waveNo); + } + await updateTableWaveNo(queryInterface, 'wms_wave_pick_task_wave', warehouseId, waveId, waveNo); + await updateTableWaveNo(queryInterface, 'wms_print_record', warehouseId, waveId, waveNo); + await updateTableWaveNo(queryInterface, 'wms_pack_task', warehouseId, waveId, waveNo); +} + +module.exports = { + async up(queryInterface) { + // 1. 修复存量重复波次号:同一 wave_no 保留最早一行,其余重新编号 + const duplicateRows = await fetchDuplicateWaveNos(queryInterface); + for (const dup of (Array.isArray(duplicateRows) ? duplicateRows : [])) { + const waveNo = String(dup && dup.wave_no || '').trim(); + if (!waveNo) { + continue; + } + + const rows = await queryInterface.sequelize.query( + `SELECT wave_id, warehouse_id + FROM ${TABLE_NAME} + WHERE wave_no = :waveNo + ORDER BY wave_id ASC`, + { replacements: { waveNo }, type: queryInterface.sequelize.QueryTypes.SELECT } + ); + if (!Array.isArray(rows) || rows.length <= 1) { + continue; + } + + const prefixDate = waveNo.replace(/\d+$/, ''); + if (!prefixDate) { + throw new Error(`波次号 ${waveNo} 无字母前缀,无法自动重编号,请人工处理`); + } + + // 保留最早(wave_id 最小)的一行,其余行重新编号 + for (let index = 1; index < rows.length; index += 1) { + const row = rows[index]; + const waveId = Number(row && row.wave_id || 0); + const warehouseId = Number(row && row.warehouse_id || 0); + if (!Number.isInteger(waveId) || waveId <= 0) { + continue; + } + + let nextWaveNo = await buildNextFreeWaveNo(queryInterface, prefixDate); + let guard = 0; + while (guard < 100 && await waveNoExists(queryInterface, nextWaveNo)) { + nextWaveNo = await buildNextFreeWaveNo(queryInterface, prefixDate); + guard += 1; + } + if (guard >= 100) { + throw new Error(`波次号 ${waveNo} 重新编号失败:无法找到空闲编号`); + } + + await queryInterface.sequelize.query( + `UPDATE ${TABLE_NAME} + SET wave_no = :nextWaveNo, update_time = NOW() + WHERE wave_id = :waveId`, + { replacements: { nextWaveNo, waveId } } + ); + + // 同步引用方数据 + await syncWaveNoReferences(queryInterface, warehouseId, waveId, nextWaveNo); + } + } + + // 2. 二次校验:修复后不应再有重复波次号 + const residualRows = await fetchDuplicateWaveNos(queryInterface); + if ((Array.isArray(residualRows) ? residualRows : []).length > 0) { + const residual = residualRows.map(row => String(row && row.wave_no || '').trim()).filter(Boolean); + throw new Error(`wms_wave_batch 修复后仍存在重复波次号: ${residual.join(', ')}`); + } + + // 3. 读取索引现状 + const indexes = await queryInterface.showIndex(TABLE_NAME); + + // 4. 移除冗余非唯一索引(若存在) + if (hasWaveNoIndex(indexes, 'idx_wave_no', false)) { + await queryInterface.removeIndex(TABLE_NAME, 'idx_wave_no'); + } + + // 5. 新增唯一索引(若已人工添加则跳过,保证幂等) + if (!hasWaveNoIndex(indexes, 'uniq_wave_no', true)) { + await queryInterface.addIndex(TABLE_NAME, [ 'wave_no' ], { + unique: true, + name: 'uniq_wave_no', + }); + } + }, + + async down(queryInterface) { + const indexes = await queryInterface.showIndex(TABLE_NAME); + + // 回滚:移除唯一索引 + if (hasWaveNoIndex(indexes, 'uniq_wave_no', true)) { + await queryInterface.removeIndex(TABLE_NAME, 'uniq_wave_no'); + } + + // 回滚:恢复非唯一索引(若不存在) + if (!hasWaveNoIndex(indexes, 'idx_wave_no', false)) { + await queryInterface.addIndex(TABLE_NAME, [ 'wave_no' ], { + unique: false, + name: 'idx_wave_no', + }); + } + }, +}; diff --git a/database/migrations/20260823120000-add-return-unpack-video-list-permission.js b/database/migrations/20260823120000-add-return-unpack-video-list-permission.js new file mode 100644 index 0000000..9e96402 --- /dev/null +++ b/database/migrations/20260823120000-add-return-unpack-video-list-permission.js @@ -0,0 +1,82 @@ +'use strict'; + +/** + * 退回拆包录像分页列表权限迁移(returnUnpack.videoList)。 + * + * 权限明细: + * 560 — returnUnpack.videoList API:退回拆包录像列表 + * + * 角色授权(与查询类 546-549 一致): + * → 客服组-员工(30) → 客服组-主管(28)(客服员工及以上) + * 经理(8)/仓库管理员(2)/超级管理员(7) 已持有 * 通配符,自动拥有所有权限,无需处理 + * + * 幂等:INSERT IGNORE 创建权限记录;角色权限数组追加后去重排序,已存在跳过。 + */ + +const TABLE = 'wms_permission'; +const ROLE_TABLE = 'wms_role'; +const COLUMNS = 'id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at'; + +/** 权限ID → 授权角色ID列表(不含通配符角色) */ +const PERMISSION_ROLES = { + 560: [ 30, 28 ], +}; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + // ── 1. 创建 API 权限记录(固定 ID 560)── + await queryInterface.sequelize.query( + `INSERT IGNORE INTO \`${TABLE}\` (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`, + { replacements: [ 560, 'returnUnpack.videoList', null, 'returnUnpack.videoList', null, 'API:退回拆包录像列表', null, 0, 0, null, 'api', 0, 1 ] } + ); + + // ── 2. 角色授权注入 ── + for (const permId of Object.keys(PERMISSION_ROLES).map(Number)) { + for (const roleId of PERMISSION_ROLES[permId]) { + const rows = await queryInterface.sequelize.query( + `SELECT id, permissions FROM \`${ROLE_TABLE}\` WHERE id = ?`, + { replacements: [ roleId ], type: queryInterface.sequelize.QueryTypes.SELECT } + ); + const record = Array.isArray(rows) ? rows[0] : null; + if (!record) { + continue; + } + + // 通配符角色跳过 + if (record.permissions === '*') { + continue; + } + + let perms; + try { + perms = JSON.parse(record.permissions || '[]'); + } catch (err) { + continue; + } + if (!Array.isArray(perms)) { + continue; + } + + if (perms.includes(permId)) { + continue; + } + + perms.push(permId); + perms.sort((a, b) => a - b); + + await queryInterface.sequelize.query( + `UPDATE \`${ROLE_TABLE}\` SET permissions = ? WHERE id = ?`, + { replacements: [ JSON.stringify(perms), roleId ] } + ); + } + } + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + await queryInterface.sequelize.query( + `DELETE FROM \`${TABLE}\` WHERE id = 560` + ); + }, +}; diff --git a/database/migrations/20260823150000-add-need-recheck-to-wms-stock-warehouse.js b/database/migrations/20260823150000-add-need-recheck-to-wms-stock-warehouse.js new file mode 100644 index 0000000..ac9338e --- /dev/null +++ b/database/migrations/20260823150000-add-need-recheck-to-wms-stock-warehouse.js @@ -0,0 +1,17 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.addColumn('wms_stock_warehouse', 'need_recheck', { + type: Sequelize.CHAR(1), + allowNull: false, + defaultValue: 'Y', + comment: '是否需要复核:Y=需要复核,N=不需要复核', + after: 'is_batch_mgmt', + }); + }, + + async down(queryInterface) { + await queryInterface.removeColumn('wms_stock_warehouse', 'need_recheck'); + }, +}; diff --git a/methods/changes/system.json b/methods/changes/system.json index d95a8df..dbdd364 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,108 @@ [ + { + "version": "2026.08.23-stock.warehouse-need-recheck", + "date": "2026-08-23", + "type": "enhanced", + "summary": "wms_stock_warehouse 新增 need_recheck(是否需要复核)字段:Y=需要复核(默认),N=不需要复核,非空。编辑(saveWarehouseStock/createWarehouseStock/getInfo/handleBatchChange)、导入(import 支持中文 需要/不需要 或 Y/N,缺省新建默认 Y、更新保留原值)、导出(仓库/外仓导出新增「是否需要复核」列,与导入列名对齐)全链路支持。", + "methods": [ + "stock.warehouse.getInfo", + "stock.warehouse.saveWarehouseStock", + "stock.warehouse.createWarehouseStock", + "stock.warehouse.import", + "stock.warehouse.handleBatchChange", + "stock.warehouse.export", + "stock.warehouse.externalExport" + ], + "notes": [ + "database/migrations/20260823150000-add-need-recheck-to-wms-stock-warehouse.js 新增迁移(CHAR(1) NOT NULL DEFAULT 'Y',comment: 是否需要复核:Y=需要复核,N=不需要复核)", + "app/model/stock_warehouse.js 新增 need_recheck 字段定义(默认 Y、非空)", + "app/service/systems/stock_store.js getInfo attributes 增加 need_recheck;saveWarehouseStock 解构/更新数据增加 need_recheck;createWarehouseStock 解构并默认 'Y';validateSaveParams 校验非 Y/N 值报错;handleBatchChange 白名单增加 need_recheck 并校验 Y/N;exportWarehouseStock/exportExternalWarehouseStock 行数据输出中文 需要/不需要 并新增「是否需要复核」导出列", + "app/service/systemMethods/stock/warehouse.js saveWarehouseStock 解构并透传 need_recheck;_normalizeWarehouseImportRow 解析「是否需要复核/need_recheck/needRecheck」列并新增 _normalizeNeedRecheckValue 归一化(需要→Y,不需要→N,非法值报错,缺省不覆盖)", + "同步更新 methods/system.json 中 getInfo/saveWarehouseStock/createWarehouseStock/import/handleBatchChange 的字段说明" + ], + "module": "stock" + }, + { + "version": "2026.08.23-pick.intercepted-skip-claim-pick", + "date": "2026-08-23", + "type": "fixed", + "summary": "拦截订单不再阻隔领料/拣货且不参与作业数量:pick.waveClaimScan 打印校验与领料更新跳过拦截订单(拦截未打印不阻隔领料、拦截订单不置为 claim_status=fin,响应 data 新增 intercepted_order_count);pick.query 领料前置校验仅统计非拦截未领料订单(拦截未领料不阻隔拣货,fail data 新增 intercepted_order_count);pick.createWavePickTask 新增 excludeUnclaimed 选项,普通波次(source=0)创建拣货任务计算拣货数量(order_count/任务订单/筐)时剔除未领料订单。", + "methods": [ + "pick.waveClaimScan", + "pick.query", + "pick.wavePickComplete" + ], + "notes": [ + "app/service/systemMethods/pick.js waveClaimScan 波次订单查询 attributes 增加 intercept_status,拦截订单集合不参与 unclaimed/unprinted 统计且不参与 claim_status=fin 更新", + "app/service/systemMethods/pick.js 新增 getWaveClaimGateStats 辅助方法(统计 total/intercepted/unclaimed,unclaimed 仅计非拦截订单),query 领料门禁改用该统计", + "app/service/systemMethods/pick.js createWavePickTask 新增 params.excludeUnclaimed(默认 false):为 true 时 attributes 增加 claim_status 并剔除 claim_status != fin 订单(未领料不参与 order_count/任务订单/筐数量);query 与 wavePickComplete 对普通波次(source=0)传 excludeUnclaimed=true(wavePickComplete 波次查询 SELECT 增加 source)", + "同步更新 methods/system.json 中 pick.query 与 pick.waveClaimScan 的 description、400 错误说明与 response 字段" + ], + "module": "pick" + }, + { + "version": "2026.08.23-returnUnpack.list-video-fields", + "date": "2026-08-23", + "type": "enhanced", + "summary": "returnUnpack.list 对齐打包记录补齐视频字段:列表关联查询视频副表,每条记录新增 has_video(1=有视频记录/2=无)、video_enable(1=录像可用/2=不可用)派生字段与 videos 视频数组(id/video_url/status/camera_id/camera_name),并新增 has_video / video_enable 列表筛选(EXISTS 字面量,口径与 order.packing.list 一致)。", + "methods": [ + "returnUnpack.list" + ], + "notes": [ + "app/service/systems/return_unpack.js list 改 raw:false 并 include ReturnUnpackVideo as videos(deleted_at IS NULL 过滤 + Camera 关联精简字段),行数据经 _flattenVideos 输出精简视频数组;_enrichRow 对含 videos 数组的记录派生 has_video/video_enable(create 幂等复用与 detail 返回同步受益,videos 结构不变);_buildListWhere 新增 has_video/video_enable 筛选(1/2,EXISTS/NOT EXISTS 字面量)", + "同步更新 methods/system.json 中 returnUnpack.list 的 params(where.has_video / where.video_enable)与 response list 字段说明" + ], + "module": "returnUnpack" + }, + { + "version": "2026.08.22-order.print-custom-area-wave-multiply-qty", + "date": "2026-08-22", + "type": "enhanced", + "summary": "面单自定义区商品明细行尾新增「波次总单数×该行商品数量」:当波次 wms_wave_batch.source=0(普通波次)且 wave_type=1 时,每条商品明细行尾追加 波次总单数 × 该行商品数量(如 500 单 × 3 件 = 1500);策略抓取波次(source=1/2)与其他波次类型不追加。", + "methods": [ + "order.print.getOrderPrintData", + "order.print.getWavePlatformPrintData", + "order.print.getPrintDataByWaybillCodes" + ], + "notes": [ + "app/service/systems/order_print.js queryWavesByIds 查询增加 source/wave_type 字段;getWavePlatformPrintData / getOrderPrintData / getPrintDataByWaybillCodes 三条路径构建 waveMetaMap 并在订单行附加 wave_source / wave_type", + "app/lib/printer_data_builder.js buildWaybillCustomProductInfoLines 明细行构建时 waveSource=0 且 waveType=1 且 wave_total_orders>0 时行尾追加 波次总单数×qtyNumber(商品数量与乘数之间以两个空格分隔);7 个平台映射(快手/拼多多/抖音/菜鸟/小红书/视频号/京东)同步传入 waveSource/waveType", + "更新 test/app/lib/printer_data_builder_package_material.test.js:新增 T15(source=0 且 wave_type=1 行尾乘数)与 T16(source=1 不追加乘数)", + "同步更新 methods/system.json 中三个打印方法的 description" + ], + "module": "order" + }, + { + "version": "2026.08.22-order.print-custom-area-total-qty", + "date": "2026-08-22", + "type": "enhanced", + "summary": "面单打印自定义区首行在快递渠道名后新增「商品总数【n】」:n 优先取订单级商品总数(items_total,权威字段),其次商品明细数量累加,最后 items_count(商品种类数)兜底,避免订单 items 快照宽松文本(stock_id+数量)陈旧不完整导致数量偏差;覆盖菜鸟/京东/拼多多/抖音/快手/视频号/小红书全平台自定义区。", + "methods": [ + "order.print.getOrderPrintData", + "order.print.getWavePlatformPrintData", + "order.print.getPrintDataByWaybillCodes" + ], + "notes": [ + "app/lib/printer_data_builder.js buildWaybillCustomProductInfoLines 头部行在快递渠道名后追加 商品总数【n】:fallbackTotalQty(items_total)>0 时优先,否则 safeItems 逐项 resolveItemQuantity 累加,再否则 fallbackItemsCount(items_count)兜底;7 个平台映射(快手/拼多多/抖音/菜鸟/小红书/视频号/京东)分别传入 fallbackTotalQty=items_total、fallbackItemsCount=items_count", + "更新 test/app/lib/printer_data_builder_package_material.test.js(T10 包材前缀断言排除商品总数标签、新增 T11 商品总数累加、T12 items_total 兜底优先、T13 items 快照宽松文本不完整时取 items_total、T14 无 items_total 时回退明细累加)与 test/app/service/systems/order_print.getWavePlatformPrintData.test.js(W023 头部行断言追加 商品总数【2】)", + "同步更新 methods/system.json 中三个打印方法的 description" + ], + "module": "order" + }, + { + "version": "2026.08.22-pick.query-wave-claim-gate-source0", + "date": "2026-08-22", + "type": "enhanced", + "summary": "pick.query 新增领料前置校验(仅普通波次 source=0):扫描命中普通波次时,若波次内存在未领料订单(claim_status != fin)则返回 400 并携带 action=wave_claim 提示「订单未领料,请先领料后再拣货」,阻隔开始拣货(中止拣货任务创建);已全部领料或策略抓取波次(source=1/2)不拦截。", + "methods": [ + "pick.query" + ], + "notes": [ + "app/service/systemMethods/pick.js query 波次查询 SELECT 增加 source 字段并记录 targetWaveSource;目标波次信息校验后插入领料前置校验:source=0 时查询波次订单 claim_status,存在未领单订单 fail 400(data 含 action=wave_claim、wave_id、wave_no、wave_type、wave_source、pick_mode、unclaimed_order_count、total_order_count)", + "同步更新 methods/system.json 中 pick.query 的 description 与 400 错误说明" + ], + "module": "pick" + }, { "version": "2026.08.22-stock.warehouse.import-barcode-sync", "date": "2026-08-22", diff --git a/methods/system.json b/methods/system.json index 0be23eb..a31b5c6 100644 --- a/methods/system.json +++ b/methods/system.json @@ -11678,7 +11678,7 @@ "list": [ { "method": "order.print.getWavePlatformPrintData", - "description": "按波次 IDs 获取平台打印中间态数据,自动过滤快递未完全分配的波次,返回 waveGroups(波次 -> 平台 -> 订单)结构", + "description": "按波次 IDs 获取平台打印中间态数据,自动过滤快递未完全分配的波次,返回 waveGroups(波次 -> 平台 -> 订单)结构。自定义区首行在快递渠道名后追加「商品总数【n】」(n 优先取订单级商品总数 items_total,其次商品明细数量累加,最后商品种类数 items_count 兜底);当波次 source=0 且 wave_type=1 时,商品明细行尾追加「波次总单数×该行商品数量」。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -12162,7 +12162,7 @@ }, { "method": "order.print.getOrderPrintData", - "description": "按订单ID拉取平台打印中间态数据,与 getWavePlatformPrintData 返回结构一致。不限制打印锁定状态,所有订单(包括已锁定)统一返回。仓库ID统一从当前上下文获取,无需调用方传入。自动过滤快递未完全分配的订单(post_status !== 'fin'),返回 waveGroups(波次 -> 平台 -> 订单)结构。", + "description": "按订单ID拉取平台打印中间态数据,与 getWavePlatformPrintData 返回结构一致。不限制打印锁定状态,所有订单(包括已锁定)统一返回。仓库ID统一从当前上下文获取,无需调用方传入。自动过滤快递未完全分配的订单(post_status !== 'fin'),返回 waveGroups(波次 -> 平台 -> 订单)结构。自定义区首行在快递渠道名后追加「商品总数【n】」(n 优先取订单级商品总数 items_total,其次商品明细数量累加,最后商品种类数 items_count 兜底);当波次 source=0 且 wave_type=1 时,商品明细行尾追加「波次总单数×该行商品数量」。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -12383,7 +12383,7 @@ }, { "method": "order.print.getPrintDataByWaybillCodes", - "description": "按运单号数组拉取平台打印中间态数据,与 getOrderPrintData 返回结构一致。支持子单号(business_key>1):主面单与现有逻辑一致,子面单使用主订单数据构建打印数据并在自定义区追加「子单号【{business_key}】-{主单号}」行。仓库ID统一从当前上下文获取。自动过滤快递未完全分配的订单(post_status !== 'fin'),返回 waveGroups(波次 -> 平台 -> 订单)结构。", + "description": "按运单号数组拉取平台打印中间态数据,与 getOrderPrintData 返回结构一致。支持子单号(business_key>1):主面单与现有逻辑一致,子面单使用主订单数据构建打印数据并在自定义区追加「子单号【{business_key}】-{主单号}」行。仓库ID统一从当前上下文获取。自动过滤快递未完全分配的订单(post_status !== 'fin'),返回 waveGroups(波次 -> 平台 -> 订单)结构。自定义区首行在快递渠道名后追加「商品总数【n】」(n 优先取订单级商品总数 items_total,其次商品明细数量累加,最后商品种类数 items_count 兜底);当波次 source=0 且 wave_type=1 时,商品明细行尾追加「波次总单数×该行商品数量」。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -17098,7 +17098,14 @@ } ], "params": [], - "response": [], + "response": [ + { + "name": "need_recheck", + "type": "string", + "required": true, + "description": "是否需要复核:Y=需要复核,N=不需要复核" + } + ], "errors": [] }, { @@ -17170,7 +17177,15 @@ "description": "Bearer token" } ], - "params": [], + "params": [ + { + "name": "need_recheck", + "type": "string", + "required": false, + "source": "body", + "description": "是否需要复核:Y=需要复核,N=不需要复核(非 Y/N 值会报错)" + } + ], "response": [], "errors": [] }, @@ -17187,7 +17202,15 @@ "description": "Bearer token" } ], - "params": [], + "params": [ + { + "name": "need_recheck", + "type": "string", + "required": false, + "source": "body", + "description": "是否需要复核:Y=需要复核,N=不需要复核;缺省默认 Y(需要复核)" + } + ], "response": [], "errors": [] }, @@ -17257,6 +17280,12 @@ "type": "number", "description": "零售价" }, + { + "name": "是否需要复核 / need_recheck / needRecheck", + "type": "string", + "required": false, + "description": "是否需要复核,支持中文 需要/不需要 或 Y/N;缺省时新建按需要复核(Y)处理,更新保留原值" + }, { "name": "条码 / bar_code / barCode / barcodeList / barcode_list / barcode", "type": "string", @@ -17607,14 +17636,14 @@ "type": "string", "required": true, "source": "body", - "description": "要修改的字段名,可选值:brand_name、prohibited_id、gross_weight、packing_requirements、managementFlags、stock_unit" + "description": "要修改的字段名,可选值:brand_name、prohibited_id、gross_weight、packing_requirements、managementFlags、stock_unit、need_recheck" }, { "name": "value", "type": "string|number|object", "required": true, "source": "body", - "description": "修改值,类型依 method 而定:brand_name/packing_requirements/stock_unit 为 string(<=255 字符);prohibited_id 为 number(整数);gross_weight 为 number(正整数,单位 g);managementFlags 为 object,必须包含 is_sn_mgmt/is_shelf_life_mgmt/is_batch_mgmt,值为 'Y' 或 'N'" + "description": "修改值,类型依 method 而定:brand_name/packing_requirements/stock_unit 为 string(<=255 字符);prohibited_id 为 number(整数);gross_weight 为 number(正整数,单位 g);managementFlags 为 object,必须包含 is_sn_mgmt/is_shelf_life_mgmt/is_batch_mgmt,值为 'Y' 或 'N';need_recheck 为 string,仅支持 'Y'(需要复核)/ 'N'(不需要复核)" }, { "name": "values", @@ -18694,7 +18723,7 @@ "list": [ { "method": "pick.query", - "description": "按 keyword(运单号或波次号)获取或创建当前用户的拣货任务:命中同用户活动任务返回 existing;无活动任务则创建并返回 created;若活动任务归属他人则返回冲突提示。新增领单前置校验:扫描命中的波次属于大团购(pick_mode=5)或非抓取散单(wms_wave_batch.source=0 普通波次)时,若波次内存在未领料订单(claim_status != fin)则返回 400 并携带 action=wave_claim 提示「订单未领料,请先领料后再拣货」(pick.waveClaimScan),中止拣货任务创建。", + "description": "按 keyword(运单号或波次号)获取或创建当前用户的拣货任务:命中同用户活动任务返回 existing;无活动任务则创建并返回 created;若活动任务归属他人则返回冲突提示。新增领单前置校验:扫描命中的波次属于普通波次(wms_wave_batch.source=0)时,若波次内存在未领料订单(claim_status != fin,拦截订单除外)则返回 400 并携带 action=wave_claim 提示「订单未领料,请先领料后再拣货」(pick.waveClaimScan),中止拣货任务创建;拦截订单未领料不阻隔拣货,且创建任务计算拣货数量时剔除未领料订单(拦截订单也不入任务)。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -18737,7 +18766,7 @@ "errors": [ { "code": 400, - "message": "参数错误或目标波次不满足建任务条件(如 keyword 为空、缺少仓库上下文、目标波次信息不完整、散单波次无可用订单);大团购/非抓取散单波次未领料时中止建任务并提示「订单未领料,请先领料后再拣货」(失败 data 含 action=wave_claim、wave_id、wave_no、wave_type、wave_source、pick_mode、unclaimed_order_count、total_order_count)。" + "message": "参数错误或目标波次不满足建任务条件(如 keyword 为空、缺少仓库上下文、目标波次信息不完整、散单波次无可用订单);普通波次(source=0)存在非拦截未领料订单时中止建任务并提示「订单未领料,请先领料后再拣货」(失败 data 含 action=wave_claim、wave_id、wave_no、wave_type、wave_source、pick_mode、unclaimed_order_count、intercepted_order_count、total_order_count,拦截订单未领料不阻隔)。" }, { "code": 401, @@ -19560,7 +19589,7 @@ }, { "method": "pick.waveClaimScan", - "description": "扫描面单号领取整波(领料)。按面单号(运单号)定位待处理订单表中的订单后反查订单所在波次,仅对普通波次(wms_wave_batch.source=0,含团购/散单)支持整波领料:命中后将该波次下全部未领单订单 claim_status 置为 fin(领料完成)并写入 ORDER_WAVE_CLAIM 订单操作日志,返回波次ID与波次编码;波次下存在未打印订单(print_status != fin)时返回 400「波次未打印,禁止领料」(data 含 wave_id、wave_no、unprinted_order_count);策略抓取波次(source=1/2)无需领料,返回 400 并提示「该波次为抓取波次,无需领料」(失败 data 含 no_claim_needed=true、wave_id、wave_no);面单号查不到订单或订单不在待处理订单表返回 404 提示无记录;波次内订单已全部领料时返回 already_claimed 幂等结果并提示已领料。", + "description": "扫描面单号领取整波(领料)。按面单号(运单号)定位待处理订单表中的订单后反查订单所在波次,仅对普通波次(wms_wave_batch.source=0,含团购/散单)支持整波领料:命中后将该波次下全部未领单订单(拦截订单除外) claim_status 置为 fin(领料完成)并写入 ORDER_WAVE_CLAIM 订单操作日志,返回波次ID与波次编码;波次下存在未打印订单(print_status != fin,拦截订单除外)时返回 400「波次未打印,禁止领料」(data 含 wave_id、wave_no、unprinted_order_count、intercepted_order_count,拦截订单未打印不阻隔领料);拦截订单整体跳过领料(不置为 fin);策略抓取波次(source=1/2)无需领料,返回 400 并提示「该波次为抓取波次,无需领料」(失败 data 含 no_claim_needed=true、wave_id、wave_no);面单号查不到订单或订单不在待处理订单表返回 404 提示无记录;波次内订单已全部领料时返回 already_claimed 幂等结果并提示已领料。", "isNeedAuth": false, "isNeedLogin": true, "isNeedRight": false, @@ -19630,6 +19659,12 @@ "required": true, "description": "波次下订单总数" }, + { + "name": "intercepted_order_count", + "type": "number", + "required": true, + "description": "波次下拦截订单数(拦截订单跳过领料,其未打印/未领料状态不阻隔领料与拣货)" + }, { "name": "claimed_order_count", "type": "number", @@ -19652,7 +19687,7 @@ "errors": [ { "code": 400, - "message": "参数错误(waybill_no 为空、缺少仓库上下文、订单未分配波次、波次下无可用订单);波次下存在未打印订单返回「波次未打印,禁止领料」(data 含 wave_id、wave_no、unprinted_order_count);策略抓取波次(source=1/2)返回「该波次为抓取波次,无需领料」(data 含 no_claim_needed=true、wave_id、wave_no);其余不支持类型返回通用提示。" + "message": "参数错误(waybill_no 为空、缺少仓库上下文、订单未分配波次、波次下无可用订单);波次下存在未打印订单(拦截订单除外)返回「波次未打印,禁止领料」(data 含 wave_id、wave_no、unprinted_order_count、intercepted_order_count);策略抓取波次(source=1/2)返回「该波次为抓取波次,无需领料」(data 含 no_claim_needed=true、wave_id、wave_no);其余不支持类型返回通用提示。" }, { "code": 401, @@ -36896,6 +36931,20 @@ "source": "body.where", "description": "原订单ID(等值)" }, + { + "name": "where.has_video", + "type": "number", + "required": false, + "source": "body.where", + "description": "是否有视频记录(等值):1=有视频记录 2=无视频记录" + }, + { + "name": "where.video_enable", + "type": "number", + "required": false, + "source": "body.where", + "description": "录像是否可用(等值):1=可用(存在 video_url 非空且 status!=failed 的记录) 2=不可用" + }, { "name": "sort", "type": "object", @@ -36909,7 +36958,7 @@ "name": "list", "type": "array", "required": true, - "description": "拆包单列表,每条含主表字段 + is_original_return 派生字段 + 格式化时间字段 + camera_ids 数组" + "description": "拆包单列表,每条含主表字段 + is_original_return 派生字段 + 格式化时间字段 + camera_ids 数组 + 视频派生字段 has_video(1=有视频记录/2=无)与 video_enable(1=录像可用/2=不可用)+ videos 视频数组(id/video_url/status/camera_id/camera_name)" }, { "name": "pagination", diff --git a/test/app/service/systems/order_print.getWavePlatformPrintData.test.js b/test/app/service/systems/order_print.getWavePlatformPrintData.test.js index d1fb6af..a6be7d2 100644 --- a/test/app/service/systems/order_print.getWavePlatformPrintData.test.js +++ b/test/app/service/systems/order_print.getWavePlatformPrintData.test.js @@ -898,7 +898,8 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js' const customContent = result.print_data.contents.find(content => content && content.data && Array.isArray(content.data.list)); assert.ok(customContent); - assert.equal(customContent.data.list[0].text, 'W023 中通\r'); + // 头部行:波次号 + 快递渠道名 + 商品总数【n】(无商品明细时回退 items_total/items_count) + assert.equal(customContent.data.list[0].text, 'W023 中通 商品总数【2】\r'); }); it('should render detail lines from non-json string items', () => { From 705678487db44fc7adf900c58e6e36b17f3c48e2 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sun, 23 Aug 2026 22:13:33 +0800 Subject: [PATCH 263/550] =?UTF-8?q?fix(returnUnpack):=20=E6=8B=86=E5=8C=85?= =?UTF-8?q?=E8=A7=86=E9=A2=91=E6=8B=BC=E6=8E=A5=20CDN=20=E5=9F=9F=E5=90=8D?= =?UTF-8?q?=EF=BC=8C=E5=95=86=E5=93=81=E5=A4=8D=E6=A0=B8=E5=AD=97=E6=AE=B5?= =?UTF-8?q?=E9=80=8F=E5=87=BA=E4=B8=8E=E7=BC=93=E5=AD=98=E5=A4=B1=E6=95=88?= =?UTF-8?q?=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - returnUnpack: list/detail/videoList/queryByWaybill 输出 videos[].video_url 自动拼接 http://w{warehouseId}-c{recordingComputerId}.o.gztbyc.com{path},与 order.packing 同口径 (录制电脑从 wms_print_computer 按 is_recording=true 获取,无录制电脑时保持原始相对路径) - recheckOrder: scanOrder/scanTask 报文 stock 明细新增 need_recheck 字段(缺省 Y) - stock: getStockDetails 双实现透出 need_recheck;saveWarehouseStock/handleBatchChange 更新成功后 显式清除商品详情缓存(bulk update 不触发实例级 afterUpdate hook,修复旧缓存被持续读取) - delivery_order: 订单创建时间统一取服务器当前时间,不采用报文 createTime,避免被平台上报时间覆盖 - 同步 methods/system.json 文档与 methods/changes/system.json 变更记录 --- .../systemMethods/order/recheckOrder.js | 2 + app/service/systems/delivery_order.js | 4 +- app/service/systems/return_unpack.js | 67 ++++++++++++++++++- app/service/systems/stock_store.js | 18 +++++ app/service/systems/stock_warehouse.js | 9 ++- .../systems/storage/stock_warehouse.js | 8 ++- methods/changes/system.json | 50 ++++++++++++++ methods/system.json | 4 +- 8 files changed, 154 insertions(+), 8 deletions(-) diff --git a/app/service/systemMethods/order/recheckOrder.js b/app/service/systemMethods/order/recheckOrder.js index a89f158..5dbd0ea 100644 --- a/app/service/systemMethods/order/recheckOrder.js +++ b/app/service/systemMethods/order/recheckOrder.js @@ -806,6 +806,7 @@ class RecheckOrderService extends OrderBaseService { barcodes: Array.isArray(item.barcodes) ? [ ...item.barcodes ] : [], images: Array.isArray(item.images) ? [ ...item.images ] : [], has_shared_barcode: Boolean(item.has_shared_barcode), + need_recheck: String(item.need_recheck || 'Y').trim(), plan_qty: Number(item.plan_qty || 0), store_id: item.store_id != null ? Number(item.store_id) : 0, owner_code: String(item.owner_code || '').trim(), @@ -1481,6 +1482,7 @@ class RecheckOrderService extends OrderBaseService { barcodes, images, has_shared_barcode: hasSharedBarcode, + need_recheck: String(stockInfo.need_recheck || 'Y').trim(), plan_qty: Number(item.plan_qty || 0), store_id: stockInfo.store_id != null ? Number(stockInfo.store_id) : 0, owner_code: String(item.owner_code || '').trim(), diff --git a/app/service/systems/delivery_order.js b/app/service/systems/delivery_order.js index f261a67..2985866 100644 --- a/app/service/systems/delivery_order.js +++ b/app/service/systems/delivery_order.js @@ -1306,7 +1306,6 @@ class DeliveryOrderService extends Service { orderFlag, sourcePlatformCode, sourcePlatformName, - createTime, placeOrderTime, payTime, payNo, @@ -1361,7 +1360,8 @@ class DeliveryOrderService extends Service { create_channel: String(createChannel || 'MANUAL').trim().toUpperCase() || 'MANUAL', sys_platform_code: platformSnapshot.sysPlatformCode, sys_platform_name: platformSnapshot.sysPlatformName, - create_at: createTime ? new Date(createTime) : new Date(), + // 创建时间统一取服务器当前时间,不采用报文 createTime,避免被平台上报时间覆盖 + create_at: new Date(), place_order_time: placeOrderTime ? new Date(placeOrderTime) : null, pay_time: payTime ? new Date(payTime) : null, pay_no: payNo || sourceOrderCode || '', diff --git a/app/service/systems/return_unpack.js b/app/service/systems/return_unpack.js index 79952af..7ba4076 100644 --- a/app/service/systems/return_unpack.js +++ b/app/service/systems/return_unpack.js @@ -9,6 +9,41 @@ const Service = require('egg').Service; * 所有数据库交互集中在此层,供 systemMethods/returnUnpack.js 调用。 */ class ReturnUnpackService extends Service { + /** + * 获取仓库的录制电脑 ID(带缓存)。 + * 与 order_packing 一致:从 wms_print_computer 按 is_recording=true 获取。 + * @param {number} warehouseId 仓库ID + * @return {Promise} 录制电脑ID,找不到返回 null + */ + async _getRecordingComputerId(warehouseId) { + const cacheKey = `_recordingComputer_${warehouseId}`; + if (this[cacheKey] !== undefined) { + return this[cacheKey]; + } + const row = await this.ctx.model.PrintComputer.findOne({ + where: { warehouse_id: warehouseId, is_recording: true, deleted_at: null }, + attributes: [ 'id' ], + raw: true, + }); + this[cacheKey] = row ? row.id : null; + return this[cacheKey]; + } + + /** + * 构建视频完整 URL(与 order.packing 一致)。 + * 格式:http://w{warehouseId}-c{recordingComputerId}.o.gztbyc.com{videoPath} + * @param {number} warehouseId 仓库ID + * @param {number|null} recordingComputerId 录制电脑ID + * @param {string} videoPath 视频路径 + * @return {string} 完整 URL + */ + _buildVideoUrl(warehouseId, recordingComputerId, videoPath) { + if (!videoPath || !recordingComputerId) { + return videoPath || ''; + } + return `http://w${warehouseId}-c${recordingComputerId}.o.gztbyc.com${videoPath}`; + } + /** * 创建带业务错误码的异常对象。 * @@ -660,6 +695,20 @@ class ReturnUnpackService extends Service { raw: false, }); + // 视频地址拼接 CDN 域名(unpack_id 由方法层强制注入且已通过仓库隔离校验) + const unpackIdRaw = queryWhere.unpack_id; + const unpackId = unpackIdRaw && typeof unpackIdRaw === 'object' ? unpackIdRaw.value : unpackIdRaw; + let warehouseId = 0; + if (unpackId) { + const unpackRow = await ctx.model.ReturnUnpack.findOne({ + where: { id: Number(unpackId) }, + attributes: [ 'warehouse_id' ], + raw: true, + }); + warehouseId = Number(unpackRow && unpackRow.warehouse_id || 0); + } + const recordingComputerId = warehouseId > 0 ? await this._getRecordingComputerId(warehouseId) : null; + const list = rows .map(row => (row && typeof row.toJSON === 'function' ? row.toJSON() : row)) .map(row => { @@ -667,7 +716,7 @@ class ReturnUnpackService extends Service { return { id: row.id, unpack_id: row.unpack_id, - video_url: row.video_url, + video_url: this._buildVideoUrl(warehouseId, recordingComputerId, row.video_url), status: row.status || null, camera_id: row.camera_id || null, camera_name: (camera.custom_name || camera.channel_name) || null, @@ -827,6 +876,12 @@ class ReturnUnpackService extends Service { raw: true, }); + // 视频地址拼接 CDN 域名(与 order.packing 对齐) + const recordingComputerId = await this._getRecordingComputerId(warehouseId); + for (const video of videos) { + video.video_url = this._buildVideoUrl(warehouseId, recordingComputerId, video.video_url); + } + let received = null; if (unpack.return_received_id) { received = await ctx.model.ReturnReceived.findOne({ @@ -1297,6 +1352,16 @@ class ReturnUnpackService extends Service { if (Array.isArray(record.videos)) { record.has_video = record.videos.length > 0 ? 1 : 2; record.video_enable = record.videos.some(v => v.video_url && v.status !== 'failed') ? 1 : 2; + + // 视频地址拼接 CDN 域名(与 order.packing 对齐:http://w{warehouseId}-c{recordingComputerId}.o.gztbyc.com{path}) + const warehouseId = Number(record.warehouse_id || 0); + if (warehouseId > 0) { + const recordingComputerId = await this._getRecordingComputerId(warehouseId); + record.videos = record.videos.map(v => ({ + ...v, + video_url: this._buildVideoUrl(warehouseId, recordingComputerId, v.video_url), + })); + } } // camera_ids 归一化为数组(MySQL JSON 列可能返回字符串) diff --git a/app/service/systems/stock_store.js b/app/service/systems/stock_store.js index 28b1b29..86b577d 100644 --- a/app/service/systems/stock_store.js +++ b/app/service/systems/stock_store.js @@ -2663,6 +2663,17 @@ class stockStoreService extends Service { delete_at: null, }, }); + + // 5.1 清除商品详情缓存(bulk update 不触发实例级 afterUpdate hook) + if (affectedRows > 0) { + const detailCacheSvc = ctx.service && ctx.service.systems && ctx.service.systems.stockWarehouse; + if (detailCacheSvc && typeof detailCacheSvc.invalidateStockDetailCache === 'function') { + await Promise.allSettled( + ids.map(stockId => detailCacheSvc.invalidateStockDetailCache(Number(stockId), warehouseId)) + ); + } + } + return { message: `成功修改 ${affectedRows} 条记录`, code: 200, @@ -3199,6 +3210,13 @@ class stockStoreService extends Service { // 7. 提交事务 await transaction.commit(); + // 7.1 清除商品详情缓存(getStockDetails 缓存,bulk update 不触发实例级 afterUpdate hook) + try { + await service.systems.stockWarehouse.invalidateStockDetailCache(id, warehouseId); + } catch (cacheError) { + ctx.logger.warn(`saveWarehouseStock 清除商品详情缓存失败: ${cacheError.message}`); + } + // 8. 返回更新后的数据 return await this.getInfo({ id }); diff --git a/app/service/systems/stock_warehouse.js b/app/service/systems/stock_warehouse.js index 833bd51..6e07543 100644 --- a/app/service/systems/stock_warehouse.js +++ b/app/service/systems/stock_warehouse.js @@ -31,7 +31,7 @@ class StockWarehouseService extends Service { * @param {Object} [options={}] 选项 * @param {number} [options.warehouseId] 仓库ID(优先使用 options.warehouseId,否则兜底 ctx.user.store_id) * @param {number} [options.cacheTTL=300] 缓存过期时间(秒) - * @return {Promise}>>} 商品详情列表 + * @return {Promise}>>} 商品详情列表 */ async getStockDetails(stockIds, options = {}) { const { ctx, app } = this; @@ -79,7 +79,7 @@ class StockWarehouseService extends Service { attributes: [ 'id', 'item_code', 'item_name', 'sku_property', 'quantity', 'locked_quantity', 'is_batch_mgmt', - 'is_shelf_life_mgmt', 'is_images', + 'is_shelf_life_mgmt', 'is_images', 'need_recheck', 'store_id', 'packing_requirements', 'stock_unit', ], raw: true, @@ -143,6 +143,7 @@ class StockWarehouseService extends Service { is_batch_mgmt: row.is_batch_mgmt || 'N', is_shelf_life_mgmt: row.is_shelf_life_mgmt || 'N', is_images: row.is_images || 'N', + need_recheck: row.need_recheck || 'Y', store_id: row.store_id != null ? Number(row.store_id) : 0, packing_requirements: row.packing_requirements || '', stock_unit: row.stock_unit || '', @@ -188,6 +189,10 @@ class StockWarehouseService extends Service { if (cached && !Array.isArray(cached.image_url)) { cached.image_url = []; } + // 兼容旧缓存:无 need_recheck 时补默认(需要复核) + if (cached && cached.need_recheck == null) { + cached.need_recheck = 'Y'; + } result.push(cached); } } else if (dbResults.has(stockId)) { diff --git a/app/service/systems/storage/stock_warehouse.js b/app/service/systems/storage/stock_warehouse.js index 53a0e30..b1f9063 100644 --- a/app/service/systems/storage/stock_warehouse.js +++ b/app/service/systems/storage/stock_warehouse.js @@ -31,7 +31,7 @@ class StockWarehouseService extends Service { * @param {Object} [options={}] 选项 * @param {number} [options.warehouseId] 仓库ID(优先使用 options.warehouseId,否则兜底 ctx.user.store_id) * @param {number} [options.cacheTTL=300] 缓存过期时间(秒) - * @return {Promise}>>} 商品详情列表 + * @return {Promise}>>} 商品详情列表 */ async getStockDetails(stockIds, options = {}) { const { ctx, app } = this; @@ -77,6 +77,7 @@ class StockWarehouseService extends Service { 'id', 'item_code', 'item_name', 'sku_property', 'quantity', 'locked_quantity', 'is_batch_mgmt', 'is_shelf_life_mgmt', 'image_url', 'is_images', + 'need_recheck', 'store_id', 'packing_requirements', 'stock_unit', ], raw: true, @@ -116,6 +117,7 @@ class StockWarehouseService extends Service { is_shelf_life_mgmt: row.is_shelf_life_mgmt || 'N', image_url: row.image_url || '', is_images: row.is_images || 'N', + need_recheck: row.need_recheck || 'Y', store_id: row.store_id != null ? Number(row.store_id) : 0, packing_requirements: row.packing_requirements || '', stock_unit: row.stock_unit || '', @@ -153,6 +155,10 @@ class StockWarehouseService extends Service { const cached = cacheHits.get(stockId); // 空标记(防穿透缓存)跳过 if (cached !== null && cached !== undefined) { + // 兼容旧缓存:无 need_recheck 时补默认(需要复核) + if (cached.need_recheck == null) { + cached.need_recheck = 'Y'; + } result.push(cached); } } else if (dbResults.has(stockId)) { diff --git a/methods/changes/system.json b/methods/changes/system.json index dbdd364..491a755 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,54 @@ [ + { + "version": "2026.08.23-returnUnpack.video-url-cdn-domain", + "date": "2026-08-23", + "type": "fixed", + "summary": "修复拆包视频地址未拼接 CDN 域名的问题:returnUnpack.list / returnUnpack.detail / returnUnpack.videoList / returnUnpack.queryByWaybill 输出的 videos[].video_url 此前直接返回相对路径(如 /recordings/...),与 order.packing 输出完整 URL 的口径不一致。现在按打包侧相同规则拼接 http://w{warehouseId}-c{recordingComputerId}.o.gztbyc.com{path}(录制电脑从 wms_print_computer 按 is_recording=true 获取,无录制电脑时保持原始路径)。", + "methods": [ + "returnUnpack.list", + "returnUnpack.detail", + "returnUnpack.videoList" + ], + "notes": [ + "app/service/systems/return_unpack.js 新增 _getRecordingComputerId/_buildVideoUrl(与 order_packing.js 同口径,带实例级缓存)", + "_enrichRow 视频派生块内对 videos[].video_url 拼接域名(覆盖 list/detail/submit 输出)", + "videoList 按 unpack_id 反查 warehouse_id 后拼接;queryByWaybill(inbox 查退回)的 videos 同样拼接", + "同步更新 methods/system.json 中 returnUnpack.list 与 returnUnpack.detail 的响应字段描述" + ], + "module": "returnUnpack" + }, + { + "version": "2026.08.23-stock.warehouse-cache-invalidate-on-update", + "date": "2026-08-23", + "type": "fixed", + "summary": "修复商品资料更新后 getStockDetails 详情缓存未清除的问题:saveWarehouseStock/handleBatchChange 使用 StockWarehouse.update 批量更新(不触发实例级 afterUpdate hook),导致 cache:stock_detail:{warehouseId}:{stockId} 旧数据在 TTL 内持续被读取(如 need_recheck 修改后复核扫描仍返回旧值)。现在两个编辑入口更新成功后显式调用 stockWarehouse.invalidateStockDetailCache 清除对应缓存。", + "methods": [ + "stock.warehouse.saveWarehouseStock", + "stock.warehouse.handleBatchChange" + ], + "notes": [ + "app/service/systems/stock_store.js saveWarehouseStock 提交事务后调用 service.systems.stockWarehouse.invalidateStockDetailCache(id, warehouseId)(失败仅告警不阻断主流程)", + "同文件 handleBatchChange 批量更新后按 ids 批量清除详情缓存(Promise.allSettled,失败不阻断返回)", + "实证验证:更新后 Redis 缓存 key 被删除,复核扫描/统一查询立即读取到新值" + ], + "module": "stock" + }, + { + "version": "2026.08.23-recheckOrder.stock-need-recheck", + "date": "2026-08-23", + "type": "enhanced", + "summary": "order.recheckOrder.scanOrder / scanTask 返回报文的 stock 明细新增 need_recheck 字段(Y=需要复核,N=不需要复核,缺省 Y):散单路径 enrichOrdersWithStock 组装与团购路径 buildGroupWaveList 的 stocks 映射均透出,供前端按商品判断是否免复核。", + "methods": [ + "order.recheckOrder.scanOrder", + "order.recheckOrder.scanTask" + ], + "notes": [ + "app/service/systemMethods/order/recheckOrder.js enrichOrdersWithStock stock 对象新增 need_recheck(取 getStockDetails 返回值,缺省 'Y')", + "同文件 buildGroupWaveList 的 stocks 映射新增 need_recheck", + "同步更新 methods/system.json 中 scanOrder 的 stock children 与 scanTask 的 stock 字段描述" + ], + "module": "order" + }, { "version": "2026.08.23-stock.warehouse-need-recheck", "date": "2026-08-23", diff --git a/methods/system.json b/methods/system.json index a31b5c6..a17e5b2 100644 --- a/methods/system.json +++ b/methods/system.json @@ -36958,7 +36958,7 @@ "name": "list", "type": "array", "required": true, - "description": "拆包单列表,每条含主表字段 + is_original_return 派生字段 + 格式化时间字段 + camera_ids 数组 + 视频派生字段 has_video(1=有视频记录/2=无)与 video_enable(1=录像可用/2=不可用)+ videos 视频数组(id/video_url/status/camera_id/camera_name)" + "description": "拆包单列表,每条含主表字段 + is_original_return 派生字段 + 格式化时间字段 + camera_ids 数组 + 视频派生字段 has_video(1=有视频记录/2=无)与 video_enable(1=录像可用/2=不可用)+ videos 视频数组(id/video_url/status/camera_id/camera_name),video_url 自动拼接 CDN 域名前缀 http://w{warehouseId}-c{recordingComputerId}.o.gztbyc.com{path}(录制电脑从 wms_print_computer 按 is_recording=true 获取,无录制电脑时返回原始相对路径)" }, { "name": "pagination", @@ -37095,7 +37095,7 @@ "name": "record", "type": "object", "required": true, - "description": "主表完整记录(含 details 明细、videos 视频、returnReceived 退回收到单关联与格式化时间字段)" + "description": "主表完整记录(含 details 明细、videos 视频(video_url 自动拼接 CDN 域名前缀 http://w{warehouseId}-c{recordingComputerId}.o.gztbyc.com{path})、returnReceived 退回收到单关联与格式化时间字段)" }, { "name": "related", From 0fe7b724ed9a86f6adb19d186f9995dfa1f214d3 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 24 Aug 2026 03:23:15 +0800 Subject: [PATCH 264/550] =?UTF-8?q?feat(storage):=20=E6=96=B0=E5=A2=9E=20s?= =?UTF-8?q?torage.inventory.directPutaway=20=E6=94=B6=E8=B4=A7=E5=8D=95?= =?UTF-8?q?=E7=9B=B4=E5=85=A5=E5=BA=93=E5=AD=98=E6=8E=A5=E5=8F=A3=EF=BC=88?= =?UTF-8?q?=E4=B8=80=E6=AD=A5=E5=AE=8C=E6=88=90=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - systems/storage/inventory.js#directPutaway:一步写库存并生成入库单(SCRK,直接 COMPLETED) - 入库单明细与收货明细一一对应(不合并),按收货明细库位 space_id 入库,批次/效期取收货明细 - 悲观行锁更新 wms_stock_warehouse 总库存 + 写 wms_storage 库位库存(同键累加) - 全量日志:wms_stock_transaction(SCRK)+ wms_storage_transaction(entry_order)+ wms_inbound_direct_log(committed)+ 操作日志(entry_order/storage/stock 三维度) - 收货单锁定防重、重复直入 400 拒绝 - systemMethods/storage/inventory.js:注册 directPutaway 入口(_noNeedAuth) - store_warehouse.js:POLICY_CONFIG_FIELDS 白名单新增 allow_receiving_direct_putaway 开关(修复 getter sanitize 过滤导致开关读不到) - database/migrations/20260824-add-direct-putaway-permission.js:新增 API 权限记录(幂等,含 down) - methods/system.json / methods/changes/system.json:接口文档与变更记录 与 quickPutaway(转入库单)并存:转单链路为 quickPutaway→entry.addItem→entry.commit; 直入为 directPutaway 一步完成。两链路开发环境真实接口全量对比(15+ 表)一致。 --- app/model/store_warehouse.js | 8 + .../systemMethods/storage/inventory.js | 17 +- app/service/systems/storage/inventory.js | 499 ++++++++++++++++++ .../20260824-add-direct-putaway-permission.js | 52 ++ methods/changes/system.json | 19 + methods/system.json | 101 ++++ 6 files changed, 695 insertions(+), 1 deletion(-) create mode 100644 database/migrations/20260824-add-direct-putaway-permission.js diff --git a/app/model/store_warehouse.js b/app/model/store_warehouse.js index 1e5b37f..b839bbe 100644 --- a/app/model/store_warehouse.js +++ b/app/model/store_warehouse.js @@ -37,6 +37,14 @@ module.exports = app => { required: false, description: '控制该货主在当前仓库下是否允许使用收货单快捷入库', }), + Object.freeze({ + key: 'allow_receiving_direct_putaway', + name: '收货单直入库存', + type: 'flag', + default: 0, + required: false, + description: '控制该货主在当前仓库下是否允许使用收货单直入库存(一步写库存并生成入库单)', + }), Object.freeze({ key: 'allow_mix_batch', name: '允许混批', diff --git a/app/service/systemMethods/storage/inventory.js b/app/service/systemMethods/storage/inventory.js index 34857fe..ff02f14 100644 --- a/app/service/systemMethods/storage/inventory.js +++ b/app/service/systemMethods/storage/inventory.js @@ -15,7 +15,7 @@ class InventoryMethodService extends MainService { const _noNeedLogin = ''; const _noNeedRight = 'list,export,exportTaskProgress,listByStockId'; const _noNeedLog = 'list,export,exportTaskProgress,listByStockId'; - const _noNeedAuth = 'list,quickPutaway,export,exportTaskProgress,listByStockId'; + const _noNeedAuth = 'list,quickPutaway,directPutaway,export,exportTaskProgress,listByStockId'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -125,6 +125,21 @@ class InventoryMethodService extends MainService { const result = await service.systems.storage.inventory.quickPutaway({ receiving_id }); return this.success('ok', result); } + + /** + * 收货单直入库存(一步完成):直接写 wms_storage 库位库存并生成入库单。 + * 入库单明细与收货明细一一对应,按收货明细的库位 space_id 入库。 + * 要求货主配置中允许收货单直入库存,否则直接返回失败。 + * @param {Object} data 请求体 + * @param {number} data.receiving_id 收货单ID(必填) + * @return {Promise} 统一 success 包装,返回创建的入库单信息 + */ + async directPutaway(data = {}) { + const { service } = this; + const { receiving_id } = data; + const result = await service.systems.storage.inventory.directPutaway({ receiving_id }); + return this.success('ok', result); + } /** * 提交库存导出异步任务(入参与 list 一致,复用相同的 where/sort/group_by_batch 语义)。 * diff --git a/app/service/systems/storage/inventory.js b/app/service/systems/storage/inventory.js index 6fded1d..ad364b1 100644 --- a/app/service/systems/storage/inventory.js +++ b/app/service/systems/storage/inventory.js @@ -1941,6 +1941,505 @@ class InventoryService extends Service { } } + /** + * 收货单直入库存(一步完成):直接写入 wms_storage 库位库存并生成入库单。 + * + * 与 quickPutaway(转入库单,不写库存,明细按 stock_id 合并)的区别: + * - 入库单明细与收货单明细一一对应(不合并),每行按收货明细的库位 space_id 入库; + * - 直接写 wms_storage / wms_stock_warehouse 库存并写入出入库流水,入库单一步置为 COMPLETED。 + * + * @param {Object} data 请求体 + * @param {number} data.receiving_id 收货单ID(必填) + * @return {Promise} code/data/message 结构,data 中包含创建的入库单信息 + */ + async directPutaway(data = {}) { + const { ctx, app } = this; + const receivingId = Number(data.receiving_id || 0); + + // ────────── 1. 参数校验 ────────── + if (!receivingId) { + return { code: 400, message: 'receiving_id 必填', data: null }; + } + + const warehouseId = ctx.user.store_id; + if (!warehouseId) { + return { code: 400, message: '无法获取当前仓库信息', data: null }; + } + + // ────────── 2. 加载收货单主表 ────────── + const receiving = await ctx.model.Receiving.findOne({ + where: { id: receivingId, warehouse_id: warehouseId, is_deleted: false }, + }); + + if (!receiving) { + return { code: 404, message: `收货单不存在或无权访问: receiving_id=${receivingId}`, data: null }; + } + + if (receiving.status === 'cancelled') { + return { code: 400, message: '收货单已作废,不允许直入库存', data: null }; + } + + if (receiving.status !== 'completed') { + return { code: 400, message: `收货单状态不允许直入库存,当前状态: ${receiving.status},仅 completed 状态可操作`, data: null }; + } + + if (!receiving.is_review) { + return { code: 400, message: '收货单未审核,不允许直入库存', data: null }; + } + + const storeId = receiving.store_id; + + // ────────── 3. 检查货主配置:是否允许收货单直入库存 ────────── + const storeWarehouse = await ctx.model.StoreWarehouse.findOne({ + where: { store_id: storeId, warehouse_id: warehouseId, warehouse_use_status: 1 }, + attributes: [ 'id', 'policy_config' ], + }); + + if (!storeWarehouse) { + return { code: 400, message: '货主仓库签约关系不存在', data: null }; + } + + const policyConfig = storeWarehouse.policy_config || {}; + const allowDirectPutaway = Number(policyConfig.allow_receiving_direct_putaway) === 1; + + if (!allowDirectPutaway) { + return { code: 400, message: '货主未开启收货单直入库存功能,请联系管理员开启', data: null }; + } + + // ────────── 4. 加载收货单明细 ────────── + const receivingDetails = await ctx.model.ReceivingDetail.findAll({ + where: { receiving_id: receivingId }, + attributes: [ + 'id', 'system_product_id', 'actual_quantity', 'product_name', + 'batch_number', 'production_date', 'expiry_date', + 'space_id', 'storage_status', 'stored_quantity', + ], + }); + + if (!receivingDetails || receivingDetails.length === 0) { + return { code: 400, message: '收货单无明细,无法直入库存', data: null }; + } + + // 过滤出需要入库的明细(排除已全部入库的) + const pendingDetails = receivingDetails.filter( + d => d.storage_status !== 'all' && Number(d.actual_quantity) > 0 + ); + + if (pendingDetails.length === 0) { + return { code: 400, message: '收货单所有明细均已入库,禁止重复直入库存', data: null }; + } + + // 待入库明细必须全部已匹配系统商品 + const unmatchedDetails = pendingDetails.filter(d => !d.system_product_id); + if (unmatchedDetails.length > 0) { + const names = unmatchedDetails.map(d => d.product_name).join('、'); + return { code: 400, message: `以下商品未匹配系统商品,请先绑定: ${names}`, data: null }; + } + + // ────────── 5. 批量查询 stock_warehouse 校验商品有效 ────────── + const stockIds = [ ...new Set(pendingDetails.map(d => Number(d.system_product_id))) ]; + const stockRows = await ctx.model.StockWarehouse.findAll({ + where: { id: { [app.Sequelize.Op.in]: stockIds }, warehouse_id: warehouseId }, + attributes: [ 'id', 'item_code', 'item_name', 'stock_unit', 'is_valid' ], + raw: true, + }); + const stockMap = new Map(); + for (const row of stockRows) { + stockMap.set(Number(row.id), row); + } + + const missingStockIds = stockIds.filter(sid => !stockMap.has(sid)); + if (missingStockIds.length > 0) { + return { + code: 400, + message: `以下商品在当前仓库中不存在或已失效: stock_id=${missingStockIds.join(',')}`, + data: null, + }; + } + + // ────────── 6. 开事务:创建入库单 + 直接写库存 ────────── + const transaction = await ctx.model.transaction(); + + try { + // 锁定收货单行,防止并发重复直入 + const lockedReceiving = await ctx.model.Receiving.findOne({ + where: { id: receivingId }, + lock: transaction.LOCK.UPDATE, + transaction, + attributes: [ 'id', 'storage_status' ], + }); + if (!lockedReceiving) { + await transaction.rollback(); + return { code: 404, message: '收货单不存在', data: null }; + } + if (lockedReceiving.storage_status === 'all') { + await transaction.rollback(); + return { code: 400, message: '收货单已全部入库,禁止重复直入库存', data: null }; + } + + // 获取货主和仓库名称快照 + const storeData = await ctx.service.systems.store.getStoreName(storeId); + const storeName = (storeData.code === 200 && storeData.data) ? storeData.data.company_name : ''; + const warehouseData = await ctx.service.systems.store.getStoreName(warehouseId); + const warehouseName = (warehouseData.code === 200 && warehouseData.data) ? warehouseData.data.company_name : ''; + + // 生成入库单号(SCRK) + const entryOrderCode = await this._generateEntryOrderCode(warehouseId, storeId, transaction); + + // 创建入库单主表(直入:一步完成,直接 COMPLETED) + const entryOrder = await ctx.model.EntryOrder.create({ + entry_order_code: entryOrderCode, + order_type: 'SCRK', + total_order_lines: pendingDetails.length, + order_create_time: new Date(), + source_type: 'WMS', + order_status: 'COMPLETED', + sync_status: 'SUCCESS', + is_enabled: 1, + warehouse_id: warehouseId, + store_id: storeId, + store_name: storeName, + warehouse_name: warehouseName, + remark: `收货单${receiving.receiving_number}直入库存`, + expense_record: 0, + }, { transaction }); + + const entryOrderId = entryOrder.id; + + // ────────── 7. 创建入库单明细:与收货明细一一对应(不合并) ────────── + // 记录 收货明细ID → 入库明细ID 映射,用于写入 wms_inbound_direct_log + const entryItemIdByDetailId = new Map(); + for (let i = 0; i < pendingDetails.length; i++) { + const detail = pendingDetails[i]; + const stockInfo = stockMap.get(Number(detail.system_product_id)); + const detailQty = Number(detail.actual_quantity) || 0; + + const entryItem = await ctx.model.EntryItems.create({ + order_id: entryOrderId, + out_biz_code: '', + order_line_no: i + 1, + owner_code: '', + item_code: stockInfo ? stockInfo.item_code : '', + item_id: 0, + count: detailQty, + inventory_type: 'ZP', + stock_id: Number(detail.system_product_id), + received_quantity: detailQty, + confirm_quantity: 0, + }, { transaction }); + + entryItemIdByDetailId.set(detail.id, entryItem.id); + } + + // ────────── 8. 写入 wms_entry_order_receiving 主表级绑定 ────────── + await ctx.model.EntryOrderReceiving.create({ + entry_order_id: entryOrderId, + receiving_id: receivingId, + }, { transaction }); + + // ────────── 9. 更新 StockWarehouse 总库存(按 stock_id 聚合) ────────── + const stockQtyMap = new Map(); + for (const detail of pendingDetails) { + const sid = Number(detail.system_product_id); + const qty = Number(detail.actual_quantity) || 0; + stockQtyMap.set(sid, (stockQtyMap.get(sid) || 0) + qty); + } + + // stock(wms_stock_warehouse)变更摘要,供操作日志记录 + const stockChangeSummaries = []; + + for (const [ sid, inboundQty ] of stockQtyMap) { + // 悲观行锁 + const stockRecord = await ctx.model.StockWarehouse.findOne({ + where: { id: sid, is_valid: 'Y', deleted_at: null }, + lock: transaction.LOCK.UPDATE, + transaction, + }); + + if (!stockRecord) { + throw new Error(`商品库存记录不存在或已失效,无法直入库存: stock_id=${sid}`); + } + + const beforeQuantity = Number(stockRecord.quantity) || 0; + const beforeLockedQuantity = Number(stockRecord.locked_quantity) || 0; + + await stockRecord.increment('quantity', { by: inboundQty, transaction, silent: true }); + await stockRecord.reload({ transaction }); + + const afterQuantity = Number(stockRecord.quantity) || 0; + const afterLockedQuantity = Number(stockRecord.locked_quantity) || 0; + + // 商品维度流水(SCRK) + await ctx.service.systems.stockTransaction.create({ + transaction_type: 'INBOUND', + warehouse_id: warehouseId, + store_id: storeId, + stock_id: sid, + quantity: inboundQty, + batch_no: entryOrderCode, + inventory_type: 'ZP', + order_type: 'SCRK', + order_no: entryOrderCode, + entry_order_id: entryOrderId, + receiving_id: receivingId, + operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), + operator_name: ctx.user?.employees_name || '', + remark: '收货单直入库存', + before_quantity: beforeQuantity, + after_quantity: afterQuantity, + before_locked_quantity: beforeLockedQuantity, + after_locked_quantity: afterLockedQuantity, + created_at: new Date(), + }, { transaction }); + + // 收集 stock 变更摘要(wms_stock_warehouse 总量变更) + stockChangeSummaries.push({ + stock_id: sid, + before_quantity: beforeQuantity, + after_quantity: afterQuantity, + change_quantity: inboundQty, + }); + } + + // ────────── 10. 写 wms_storage 库位库存(按收货明细库位 space_id 逐明细写入) ────────── + // storage(wms_storage)变更笔数,供操作日志记录 + let storageWriteCount = 0; + + for (const detail of pendingDetails) { + const sid = Number(detail.system_product_id); + const qty = Number(detail.actual_quantity) || 0; + if (qty <= 0) continue; + + // 收货明细有库位则按其库位入库,否则使用默认库位 + const spaceId = Number(detail.space_id) > 0 ? Number(detail.space_id) : 1; + const batchNo = detail.batch_number || entryOrderCode; + const productionDate = detail.production_date || null; + const expiryDate = detail.expiry_date || null; + const inventoryType = 'ZP'; + + // 查找 库位+SKU+批次+类型 已有的库存记录(悲观行锁) + const sRecord = await ctx.model.Storage.findOne({ + where: { + space_id: spaceId, + stock_id: sid, + batch_no: batchNo, + inventory_type: inventoryType, + is_enabled: 1, + delete_at: null, + }, + lock: transaction.LOCK.UPDATE, + transaction, + }); + + let sId = null; + let sBeforeQty = 0; + let sAfterQty = 0; + let sBeforeLockedQty = 0; + let sAfterLockedQty = 0; + + if (sRecord) { + if (Number(sRecord.stock_id) !== Number(sid)) { + throw new Error( + `直入库存归属冲突: storage_id=${sRecord.id} 当前 stock_id=${sRecord.stock_id}, ` + + `本次入库 stock_id=${sid}, space_id=${spaceId}, batch_no=${batchNo}` + ); + } + sBeforeQty = Number(sRecord.quantity) || 0; + sAfterQty = sBeforeQty + qty; + sBeforeLockedQty = Number(sRecord.locked_quantity) || 0; + sAfterLockedQty = sBeforeLockedQty; + + await ctx.model.Storage.update({ + quantity: app.Sequelize.literal(`quantity + ${qty}`), + available_quantity: app.Sequelize.literal(`available_quantity + ${qty}`), + entry_order_id: entryOrderId, + inbound_time: new Date(), + inbound_order_no: entryOrderCode, + production_date: productionDate, + expiry_date: expiryDate, + receiving_id: receivingId, + updated_at: new Date(), + }, { + where: { id: sRecord.id }, + transaction, + }); + sId = sRecord.id; + } else { + const createdStorage = await ctx.model.Storage.create({ + warehouse_id: warehouseId, + store_id: storeId, + space_id: spaceId, + stock_id: sid, + batch_no: batchNo, + inventory_type: inventoryType, + quantity: qty, + locked_quantity: 0, + available_quantity: qty, + inbound_time: new Date(), + inbound_order_no: entryOrderCode, + receiving_id: receivingId, + entry_order_id: entryOrderId, + supplier_id: null, + supplier_batch_no: null, + production_date: productionDate, + expiry_date: expiryDate, + is_enabled: 1, + created_at: new Date(), + updated_at: new Date(), + }, { transaction }); + sId = createdStorage.id; + sAfterQty = qty; + sAfterLockedQty = 0; + } + + storageWriteCount += 1; + + // 库位维度流水(order_type 与现有 storage.entry.commit 链路一致:entry_order) + await ctx.model.StorageTransaction.create({ + transaction_type: 'INBOUND', + warehouse_id: warehouseId, + store_id: storeId, + stock_id: sid, + storage_id: sId, + space_id: spaceId, + quantity: qty, + before_quantity: sBeforeQty, + after_quantity: sAfterQty, + before_locked_quantity: sBeforeLockedQty, + after_locked_quantity: sAfterLockedQty, + batch_no: batchNo, + inventory_type: inventoryType, + order_type: 'entry_order', + order_no: entryOrderCode, + order_id: entryOrderId, + operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), + operator_name: ctx.user?.employees_name || '', + remark: '收货单直入库存', + created_at: new Date(), + }, { transaction }); + + // 写入导入/PDA 入库记录(status=committed,与 storage.entry.commit 链路一致)。 + // 该表被 storage.receiving.scanDetail、storage.entry.getDirectInboundItems、 + // getReceivingDetailsForBind 的可用数量占用统计等读取,直入也必须写入以保持口径一致。 + await ctx.model.InboundDirectLog.create({ + warehouse_id: warehouseId, + store_id: storeId, + stock_id: sid, + quantity: qty, + inbound_type: 'import', + entry_order_id: entryOrderId, + entry_order_code: entryOrderCode, + entry_item_id: entryItemIdByDetailId.get(detail.id) || 0, + receiving_detail_id: detail.id, + space_id: spaceId, + status: 'committed', + remark: '收货单直入库存', + operator_id: ctx.user?.employees_id || ctx.user?.id || null, + operator_name: ctx.user?.employees_name || '', + }, { transaction }); + } + + // ────────── 11. 回填收货单明细与主表入库状态 ────────── + for (const detail of pendingDetails) { + await ctx.model.ReceivingDetail.update({ + stored_quantity: Number(detail.actual_quantity) || 0, + storage_status: 'all', + updated_at: new Date(), + }, { + where: { id: detail.id }, + transaction, + }); + } + + // 收货单主表 storage_status:统计全部明细状态 + const allStatusRows = await ctx.model.ReceivingDetail.findAll({ + where: { receiving_id: receivingId }, + attributes: [ 'storage_status' ], + raw: true, + transaction, + }); + const allStored = allStatusRows.length > 0 + && allStatusRows.every(d => d.storage_status === 'all'); + await ctx.model.Receiving.update({ + storage_status: allStored ? 'all' : 'partial', + updated_at: new Date(), + }, { + where: { id: receivingId }, + transaction, + }); + + // ────────── 12. 操作日志(entry_order / storage / stock 三种业务维度全量记录) ────────── + try { + const totalDirectQty = pendingDetails.reduce((sum, d) => sum + (Number(d.actual_quantity) || 0), 0); + await ctx.service.systems.operationLog.createOperationLogs([ + { + businessType: 'entry_order', + businessId: entryOrderId, + operationCode: 'ENTRY_ORDER_DIRECT_PUTAWAY', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId, + message: `收货单${receiving.receiving_number}直入库存完成,生成入库单${entryOrderCode},共 ${pendingDetails.length} 行明细、${totalDirectQty} 件`, + }, + }, + { + businessType: 'storage', + businessId: entryOrderId, + operationCode: 'STORAGE_DIRECT_PUTAWAY', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId, + message: `直入库存写入 wms_storage 库位库存 ${storageWriteCount} 笔(按收货明细库位),共 ${totalDirectQty} 件,入库单号 ${entryOrderCode}`, + }, + }, + { + businessType: 'stock', + businessId: entryOrderId, + operationCode: 'STOCK_DIRECT_PUTAWAY', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId, + message: `直入库存更新 wms_stock_warehouse 总库存 ${stockChangeSummaries.length} 个 SKU,共 ${totalDirectQty} 件,变更明细: ${JSON.stringify(stockChangeSummaries)}`, + }, + }, + ], { transaction }); + } catch (logErr) { + ctx.logger.warn('[inventory.directPutaway] 写入操作日志失败,不影响业务', logErr); + } + + // ────────── 13. 提交事务 ────────── + await transaction.commit(); + + ctx.logger.info(`[inventory.directPutaway] 直入库存完成 entryOrderId=${entryOrderId} receivingId=${receivingId} lines=${pendingDetails.length}`); + + return { + code: 200, + message: '直入库存成功', + data: { + entry_order_id: entryOrderId, + entry_order_code: entryOrderCode, + order_status: 'COMPLETED', + receiving_id: receivingId, + total_lines: pendingDetails.length, + total_quantity: pendingDetails.reduce((sum, d) => sum + (Number(d.actual_quantity) || 0), 0), + }, + }; + } catch (error) { + await transaction.rollback(); + ctx.logger.error(`[inventory.directPutaway] 直入库存异常 receivingId=${receivingId}: ${error.message}`, error.stack); + return { code: 500, message: `系统异常: ${error.message}`, data: null }; + } + } + /** * 导出库存列表(异步任务内部调用,生成 Excel 并上传)。 * diff --git a/database/migrations/20260824-add-direct-putaway-permission.js b/database/migrations/20260824-add-direct-putaway-permission.js new file mode 100644 index 0000000..54fd2de --- /dev/null +++ b/database/migrations/20260824-add-direct-putaway-permission.js @@ -0,0 +1,52 @@ +'use strict'; + +/** + * 新增 storage.inventory.directPutaway(收货单直入库存)API 权限记录。 + * + * 幂等设计:先查询 path + type='api' 是否已存在,已存在则跳过。 + */ + +const TABLE = 'wms_permission'; + +module.exports.up = async queryInterface => { + const permissions = [ + { path: 'storage.inventory.directPutaway', meta_title: '收货单直入库存' }, + ]; + + const paths = permissions.map(p => p.path); + const placeholders = paths.map(() => '?').join(', '); + const [ rows ] = await queryInterface.sequelize.query( + `SELECT path FROM \`${TABLE}\` WHERE type = 'api' AND path IN (${placeholders})`, + { replacements: paths } + ); + const existingPaths = new Set(rows.map(r => r.path)); + + const toInsert = permissions.filter(p => !existingPaths.has(p.path)); + + if (toInsert.length > 0) { + const values = toInsert + .map( + p => `('${p.path.replace(/'/g, "\\'")}', '${p.path.replace(/'/g, "\\'")}', '${p.meta_title.replace(/'/g, "\\'")}', 'api', 1, NOW(), NOW())` + ) + .join(',\n'); + + await queryInterface.sequelize.query(` + INSERT INTO \`${TABLE}\` (path, name, meta_title, type, status, created_at, update_at) + VALUES ${values} + `); + } + + console.log( + `[Migration] wms_permission API 权限新增:共 ${permissions.length} 条,` + + `已存在 ${permissions.length - toInsert.length} 条,实际插入 ${toInsert.length} 条` + ); +}; + +module.exports.down = async queryInterface => { + const paths = [ 'storage.inventory.directPutaway' ]; + const placeholders = paths.map(() => '?').join(', '); + await queryInterface.sequelize.query( + `DELETE FROM \`${TABLE}\` WHERE type = 'api' AND path IN (${placeholders})`, + { replacements: paths } + ); +}; diff --git a/methods/changes/system.json b/methods/changes/system.json index 491a755..65c557e 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -6885,5 +6885,24 @@ "代码变更:systemMethods/storage/inventory.js#list 新增 extractStockQueryVirtualFilter(从 where 提取并移除 stock_query);systems/storage/inventory.js#getInventoryList 新增 stockQuery 参数与 resolveStockQueryToStockIds;methods/system.json 同步 where 参数文档(export 注明暂不支持 stock_query)。" ], "module": "storage" + }, + { + "version": "2026.08.24-storage.inventory.directPutaway", + "date": "2026-08-24", + "type": "added", + "summary": "新增 storage.inventory.directPutaway 接口:收货单直入库存(一步完成),直接写 wms_storage 并生成入库单", + "methods": [ + "storage.inventory.directPutaway" + ], + "notes": [ + "新增收货单直入库存接口,与 storage.inventory.quickPutaway(转入库单,不写库存)并存,名称不交换保持兼容。", + "核心流程:校验收货单(completed + is_review=true,未作废)→ 检查货主配置 policy_config.allow_receiving_direct_putaway=1 → 过滤未入库明细(storage_status!=all)并校验全部已匹配系统商品 → 事务内锁定收货单行防并发 → 创建入库单 SCRK(order_status=COMPLETED、sync_status=SUCCESS,一步完成)→ 入库单明细与收货明细一一对应(不合并,每行 count/received_quantity=actual_quantity)→ 写入 wms_entry_order_receiving 主表级绑定 → 按 stock_id 聚合悲观行锁更新 wms_stock_warehouse 总库存并写 wms_stock_transaction(order_type=SCRK,与现有链路一致)→ 按收货明细库位 space_id 逐明细写入/累加 wms_storage 并写 wms_storage_transaction(order_type=entry_order,与现有 storage.entry.commit 链路一致)→ 逐明细写入 wms_inbound_direct_log(entry_item_id/receiving_detail_id/space_id 齐全,status=committed、inbound_type=import,与 storage.entry.commit 链路口径一致,保证 scanDetail/可用数量占用统计等读取链路数据一致)→ 回填收货明细 storage_status=all/stored_quantity 与主表 storage_status(all/partial)→ 操作日志。", + "日志全量写入:storage 变更记录(wms_storage_transaction,逐明细含 before/after 数量与锁定量)、stock 变更记录(wms_stock_transaction,按 SKU 聚合含 before/after 数量与锁定量)、stock 变更(wms_stock_warehouse 悲观行锁 increment quantity);操作日志(wms_operation_log)同时写三条:businessType=entry_order(ENTRY_ORDER_DIRECT_PUTAWAY)、businessType=storage(STORAGE_DIRECT_PUTAWAY,记录库位库存写入笔数与数量)、businessType=stock(STOCK_DIRECT_PUTAWAY,记录各 SKU 总量变更前后值摘要)。", + "库位规则:明细 space_id 有效则按其库位入库,否则回退默认库位 1;批次取收货明细 batch_number,无批次则以入库单号作为批次号;生产/效期日期取收货明细 production_date/expiry_date。", + "与 quickPutaway 的区别:directPutaway 一步直接写库存(入库单 COMPLETED),quickPutaway 仅转入库单(PENDING)不写库存,需再走 storage.entry.commit 才写库存。", + "货主开关:policy_config 新增 allow_receiving_direct_putaway(默认未开启时 400 拒绝),与 allow_receiving_quick_putaway 相互独立;app/model/store_warehouse.js 的 POLICY_CONFIG_FIELDS 白名单已补充该字段(否则模型 getter sanitizeOnly 会过滤掉该键导致开关无法读取)。", + "代码变更:app/service/systems/storage/inventory.js#directPutaway、app/service/systemMethods/storage/inventory.js#directPutaway(_noNeedAuth 新增 directPutaway)、methods/system.json 新增 method 文档、database/migrations/20260824 新增权限记录(path=storage.inventory.directPutaway)。" + ], + "module": "storage" } ] diff --git a/methods/system.json b/methods/system.json index a17e5b2..072429b 100644 --- a/methods/system.json +++ b/methods/system.json @@ -23566,6 +23566,107 @@ } ] }, + { + "method": "storage.inventory.directPutaway", + "description": "收货单直入库存(一步完成):将已审核的收货单(completed + is_review=true)未入库明细直接写入 wms_storage 库位库存(按收货明细的库位 space_id 入库)并生成入库单(SCRK,一步置为 COMPLETED),入库单明细与收货明细一一对应(不合并,逐行保留库位/批次/效期),同时更新 wms_stock_warehouse 总库存并写入出入库流水(wms_stock_transaction / wms_storage_transaction),并写入 wms_inbound_direct_log(status=committed,与 storage.entry.commit 链路口径一致),回填收货单及其明细的入库状态。要求货主仓库签约配置 policy_config.allow_receiving_direct_putaway=1 开启直入库存功能。", + "isNeedAuth": true, + "isNeedLogin": true, + "params": [ + { + "name": "receiving_id", + "type": "number", + "required": true, + "source": "body", + "description": "收货单ID(必填)" + } + ], + "response": [ + { + "name": "entry_order_id", + "type": "number", + "description": "生成的入库单ID" + }, + { + "name": "entry_order_code", + "type": "string", + "description": "入库单号(SCRK + 年月日 + 4位流水号)" + }, + { + "name": "order_status", + "type": "string", + "description": "入库单状态(COMPLETED,一步完成)" + }, + { + "name": "receiving_id", + "type": "number", + "description": "收货单ID" + }, + { + "name": "total_lines", + "type": "number", + "description": "入库单明细行数(与待入库收货明细一一对应)" + }, + { + "name": "total_quantity", + "type": "number", + "description": "入库总数量" + } + ], + "errors": [ + { + "code": 400, + "message": "receiving_id 必填" + }, + { + "code": 400, + "message": "无法获取当前仓库信息" + }, + { + "code": 404, + "message": "收货单不存在或无权访问" + }, + { + "code": 400, + "message": "收货单已作废,不允许直入库存" + }, + { + "code": 400, + "message": "收货单状态不允许直入库存,仅 completed 状态可操作" + }, + { + "code": 400, + "message": "收货单未审核,不允许直入库存" + }, + { + "code": 400, + "message": "货主仓库签约关系不存在" + }, + { + "code": 400, + "message": "货主未开启收货单直入库存功能" + }, + { + "code": 400, + "message": "收货单无明细,无法直入库存" + }, + { + "code": 400, + "message": "收货单所有明细均已入库,禁止重复直入库存" + }, + { + "code": 400, + "message": "以下商品未匹配系统商品,请先绑定" + }, + { + "code": 400, + "message": "以下商品在当前仓库中不存在或已失效" + }, + { + "code": 500, + "message": "系统异常" + } + ] + }, { "method": "storage.inventory.transferLocation", "description": "单商品单库位移库,将库存从一个库位移动到另一个库位,支持部分数量移库和全量移库", From 3352fbaff60c3f624dc33ddc2a648a1f87eb284f Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 24 Aug 2026 03:23:23 +0800 Subject: [PATCH 265/550] =?UTF-8?q?test(storage):=20directPutaway=20?= =?UTF-8?q?=E4=B8=8E=20quickPutaway=20=E9=93=BE=E8=B7=AF=E5=AF=B9=E6=AF=94?= =?UTF-8?q?=E6=B5=8B=E8=AF=95=E8=84=9A=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - tmp-test-putaway-full-compare.cjs:全链路真实接口对比(A 两步 quickPutaway→addItem→commit / B 一步 directPutaway),支持 A|B 参数单独跑 - tmp-test-putaway-batch-compare.cjs:批次维度对比(不同批次建行 / 同批次累加) - tmp-verify-all-tables.cjs:15 张表逐表核对输出 - tmp-check-*:条码、请求日志、通知失败表、权限、库存行/流水等定点核对 - tmp-clear-user-cache.cjs:清 Redis 用户缓存(权限变更后刷新) - 测试数据保留不清理(收货单 1521-1535、入库单 381-392 等) --- script/tmp-check-barcodes.cjs | 23 ++ script/tmp-check-hidden-tables.cjs | 42 ++++ script/tmp-check-policy.cjs | 15 ++ script/tmp-check-role-permission.cjs | 12 + script/tmp-check-storage-rows.cjs | 28 +++ script/tmp-check-storage-stock.cjs | 41 ++++ script/tmp-clear-user-cache.cjs | 13 + script/tmp-explore-putaway-test-data.cjs | 58 +++++ script/tmp-test-putaway-batch-compare.cjs | 136 +++++++++++ script/tmp-test-putaway-compare.cjs | 261 ++++++++++++++++++++ script/tmp-test-putaway-full-compare.cjs | 281 ++++++++++++++++++++++ script/tmp-verify-all-tables.cjs | 103 ++++++++ 12 files changed, 1013 insertions(+) create mode 100644 script/tmp-check-barcodes.cjs create mode 100644 script/tmp-check-hidden-tables.cjs create mode 100644 script/tmp-check-policy.cjs create mode 100644 script/tmp-check-role-permission.cjs create mode 100644 script/tmp-check-storage-rows.cjs create mode 100644 script/tmp-check-storage-stock.cjs create mode 100644 script/tmp-clear-user-cache.cjs create mode 100644 script/tmp-explore-putaway-test-data.cjs create mode 100644 script/tmp-test-putaway-batch-compare.cjs create mode 100644 script/tmp-test-putaway-compare.cjs create mode 100644 script/tmp-test-putaway-full-compare.cjs create mode 100644 script/tmp-verify-all-tables.cjs diff --git a/script/tmp-check-barcodes.cjs b/script/tmp-check-barcodes.cjs new file mode 100644 index 0000000..26a92fe --- /dev/null +++ b/script/tmp-check-barcodes.cjs @@ -0,0 +1,23 @@ +'use strict'; +const mysql = require('mysql2/promise'); +(async () => { + const c = await mysql.createConnection({ host: '127.0.0.1', port: 3307, user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms' }); + + // bindDetailProduct 自动写入的条码(本次测试的 TMPBC/FULLBC 前缀) + const [barcodes] = await c.query(` + SELECT id, stock_id, warehouse_id, barcode + FROM wms_stock_barcodes + WHERE barcode LIKE 'TMPBC%' OR barcode LIKE 'FULLBC%' + ORDER BY id`); + console.log('== wms_stock_barcodes 测试写入的条码(共 ' + barcodes.length + ' 行) =='); + console.log(JSON.stringify(barcodes, null, 2)); + + // 商品 159061/159064 上的全部条码 + const [all] = await c.query( + `SELECT id, stock_id, barcode FROM wms_stock_barcodes WHERE stock_id IN (159061, 159064) ORDER BY id` + ); + console.log('== 两商品全部条码 =='); + console.log(JSON.stringify(all, null, 2)); + await c.end(); + process.exit(0); +})().catch(e => { console.error(e); process.exit(1); }); diff --git a/script/tmp-check-hidden-tables.cjs b/script/tmp-check-hidden-tables.cjs new file mode 100644 index 0000000..cd9d13c --- /dev/null +++ b/script/tmp-check-hidden-tables.cjs @@ -0,0 +1,42 @@ +'use strict'; +const mysql = require('mysql2/promise'); +(async () => { + const c = await mysql.createConnection({ host: '127.0.0.1', port: 3307, user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms' }); + + // 1. 请求日志表:本次重测 A(1530)/B(1531) 相关的接口调用日志 + const [sysLogs] = await c.query(` + SELECT id, method, v, store_id, use_time, LEFT(body, 120) AS body_snip, created_at + FROM wms_system_log + WHERE body LIKE '%R20688012%' OR body LIKE '%R20688013%' + OR body LIKE '%"receiving_id":1530%' OR body LIKE '%"receiving_id":1531%' + OR body LIKE '%"ids":[1530%' OR body LIKE '%"ids":[1531%' + OR body LIKE '%"entry_order_id":387%' OR body LIKE '%"entry_order_id":388%' + ORDER BY id`); + console.log('== wms_system_log 请求日志(本次重测相关,共 ' + sysLogs.length + ' 条) =='); + console.log(JSON.stringify(sysLogs, null, 2)); + + // 2. 通知发送日志表(失败才写) + const [notiLogs] = await c.query(` + SELECT id, trace_id, store_id, warehouse_id, business_name, event, status, http_status, created_at + FROM wms_notification_send_log + WHERE created_at >= DATE_SUB(NOW(), INTERVAL 2 DAY) + ORDER BY id DESC LIMIT 10`); + console.log('== wms_notification_send_log 最近两天(共 ' + notiLogs.length + ' 条) =='); + console.log(JSON.stringify(notiLogs, null, 2)); + + // 3. 商品资料异步补全相关(无图片/无重量时应无写入) + const [stockRow] = await c.query( + `SELECT id, is_images, gross_weight FROM wms_stock_warehouse WHERE id IN (159061, 159064)` + ); + console.log('== 商品资料快照(is_images/gross_weight,验证异步补全未触发) =='); + console.log(JSON.stringify(stockRow, null, 2)); + + const [fileRefs] = await c.query( + `SELECT id, business_type, business_id, file_id FROM wms_file_reference WHERE business_type='stock' AND business_id IN ('159061','159064')` + ); + console.log('== wms_file_reference(stock 类型,共 ' + fileRefs.length + ' 行) =='); + console.log(JSON.stringify(fileRefs, null, 2)); + + await c.end(); + process.exit(0); +})().catch(e => { console.error(e); process.exit(1); }); diff --git a/script/tmp-check-policy.cjs b/script/tmp-check-policy.cjs new file mode 100644 index 0000000..fb2ed32 --- /dev/null +++ b/script/tmp-check-policy.cjs @@ -0,0 +1,15 @@ +'use strict'; +const mysql = require('mysql2/promise'); +(async () => { + const c = await mysql.createConnection({ host: '127.0.0.1', port: 3307, user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms' }); + const [r] = await c.query( + `SELECT id, store_id, warehouse_id, warehouse_use_status, + JSON_EXTRACT(policy_config, '$.allow_receiving_direct_putaway') AS direct, + JSON_EXTRACT(policy_config, '$.allow_receiving_quick_putaway') AS quick + FROM wms_store_warehouse WHERE store_id = 1000000 AND warehouse_id = 100000` + ); + console.log('store_warehouse:', JSON.stringify(r, null, 2)); + const [r2] = await c.query('SELECT id, store_id, warehouse_id, status, is_review, storage_status FROM wms_receiving WHERE id IN (1521,1522,1523,1524)'); + console.log('receivings:', JSON.stringify(r2, null, 2)); + await c.end(); +})().catch(e => { console.error(e); process.exit(1); }); diff --git a/script/tmp-check-role-permission.cjs b/script/tmp-check-role-permission.cjs new file mode 100644 index 0000000..d70fecb --- /dev/null +++ b/script/tmp-check-role-permission.cjs @@ -0,0 +1,12 @@ +'use strict'; +const mysql = require('mysql2/promise'); +(async () => { + const c = await mysql.createConnection({ host: '127.0.0.1', port: 3307, user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms' }); + const [p] = await c.query("SELECT id, path, meta_title FROM wms_permission WHERE path LIKE 'storage.inventory%' AND type='api'"); + console.log('perms:', JSON.stringify(p)); + const [r] = await c.query('SELECT id, permissions FROM wms_role WHERE id IN (7)'); + console.log('roles:', JSON.stringify(r)); + const [col] = await c.query('SHOW COLUMNS FROM wms_role'); + console.log('cols:', col.map(x => x.Field + ':' + x.Type).join(', ')); + await c.end(); +})().catch(e => { console.error(e); process.exit(1); }); diff --git a/script/tmp-check-storage-rows.cjs b/script/tmp-check-storage-rows.cjs new file mode 100644 index 0000000..33a7542 --- /dev/null +++ b/script/tmp-check-storage-rows.cjs @@ -0,0 +1,28 @@ +'use strict'; +const mysql = require('mysql2/promise'); +(async () => { + const c = await mysql.createConnection({ host: '127.0.0.1', port: 3307, user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms' }); + + // 两个测试商品在 wms_storage 中的全部行 + const [rows] = await c.query(` + SELECT id, warehouse_id, store_id, space_id, stock_id, batch_no, inventory_type, + quantity, locked_quantity, available_quantity, + inbound_order_no, receiving_id, entry_order_id, inbound_time + FROM wms_storage + WHERE stock_id IN (159061, 159064) + ORDER BY id`); + console.log('== wms_storage 中两个测试商品的全部行(共 ' + rows.length + ' 行) =='); + console.log(JSON.stringify(rows, null, 2)); + + // 两商品的库位流水(逐笔证据) + const [txns] = await c.query(` + SELECT id, order_no, transaction_type, stock_id, storage_id, space_id, quantity, before_quantity, after_quantity, batch_no + FROM wms_storage_transaction + WHERE stock_id IN (159061, 159064) + ORDER BY id`); + console.log('== wms_storage_transaction 两商品逐笔流水(共 ' + txns.length + ' 条) =='); + console.log(JSON.stringify(txns, null, 2)); + + await c.end(); + process.exit(0); +})().catch(e => { console.error(e); process.exit(1); }); diff --git a/script/tmp-check-storage-stock.cjs b/script/tmp-check-storage-stock.cjs new file mode 100644 index 0000000..f3fa84d --- /dev/null +++ b/script/tmp-check-storage-stock.cjs @@ -0,0 +1,41 @@ +'use strict'; +const mysql = require('mysql2/promise'); +(async () => { + const c = await mysql.createConnection({ host: '127.0.0.1', port: 3307, user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms' }); + + // 1. wms_storage 当前状态(A/B 共用的累加行) + const [storages] = await c.query(` + SELECT id, space_id, stock_id, batch_no, quantity, locked_quantity, available_quantity, + inbound_order_no, receiving_id, entry_order_id, inbound_time + FROM wms_storage WHERE id IN (408, 409)`); + console.log('== wms_storage 当前行(408/409) =='); + console.log(JSON.stringify(storages, null, 2)); + + // 2. wms_stock_warehouse 当前数量 + const [stocks] = await c.query(` + SELECT id, item_code, quantity, locked_quantity, is_valid + FROM wms_stock_warehouse WHERE id IN (159061, 159064)`); + console.log('== wms_stock_warehouse 当前数量 =='); + console.log(JSON.stringify(stocks, null, 2)); + + // 3. A(入库单 387)与 B(入库单 388)各自的库位流水(证明 storage 写入) + const [storageTxns] = await c.query(` + SELECT order_no, transaction_type, stock_id, storage_id, space_id, quantity, before_quantity, after_quantity, batch_no + FROM wms_storage_transaction + WHERE order_id IN (387, 388) OR order_no IN ('SCRK202608240007','SCRK202608240008') + ORDER BY id`); + console.log('== wms_storage_transaction:A(387)/B(388) 的库位流水 =='); + console.log(JSON.stringify(storageTxns, null, 2)); + + // 4. A/B 各自的商品流水(证明 stock_warehouse 数量变更) + const [stockTxns] = await c.query(` + SELECT order_no, transaction_type, stock_id, quantity, before_quantity, after_quantity, entry_order_id + FROM wms_stock_transaction + WHERE entry_order_id IN (387, 388) OR order_no IN ('SCRK202608240007','SCRK202608240008') + ORDER BY id`); + console.log('== wms_stock_transaction:A(387)/B(388) 的商品流水 =='); + console.log(JSON.stringify(stockTxns, null, 2)); + + await c.end(); + process.exit(0); +})().catch(e => { console.error(e); process.exit(1); }); diff --git a/script/tmp-clear-user-cache.cjs b/script/tmp-clear-user-cache.cjs new file mode 100644 index 0000000..6368f31 --- /dev/null +++ b/script/tmp-clear-user-cache.cjs @@ -0,0 +1,13 @@ +'use strict'; +const Redis = require('ioredis'); +(async () => { + const r = new Redis({ host: '127.0.0.1', port: 6379, password: 'qwe2019', db: 10 }); + const keys = await r.keys('user:info:*'); + console.log('matched keys:', keys); + for (const k of keys) { + await r.del(k); + console.log('deleted:', k); + } + r.disconnect(); + process.exit(0); +})().catch(e => { console.error(e); process.exit(1); }); diff --git a/script/tmp-explore-putaway-test-data.cjs b/script/tmp-explore-putaway-test-data.cjs new file mode 100644 index 0000000..9670c42 --- /dev/null +++ b/script/tmp-explore-putaway-test-data.cjs @@ -0,0 +1,58 @@ +'use strict'; +/* 临时探索脚本:查询直入/转入库单对比测试所需数据(只读) */ +const mysql = require('mysql2/promise'); + +(async () => { + const conn = await mysql.createConnection({ + host: '127.0.0.1', port: 3307, user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms', + }); + + const [cols] = await conn.query('SHOW COLUMNS FROM wms_employee_role'); + console.log('== wms_employee_role columns =='); + console.log(cols.map(c => c.Field).join(',')); + + const [whUsers] = await conn.query(` + SELECT a.id account_id, a.username, a.status, e.id employee_id, e.store_id warehouse_id, r.id role_id, r.role_type + FROM wms_account a + JOIN wms_account_store_employee e ON e.account_id = a.id AND e.deleted_at IS NULL + LEFT JOIN wms_employee_role er ON er.employee_id = e.id + LEFT JOIN wms_role r ON r.id = er.role_id + WHERE a.status = 1 + ORDER BY e.id ASC LIMIT 8`); + console.log('== accounts =='); + console.log(JSON.stringify(whUsers, null, 2)); + + if (whUsers.length === 0) { await conn.end(); return; } + const whId = whUsers[0].warehouse_id; + console.log('== using warehouse_id = ' + whId + ' =='); + + const [stores] = await conn.query(` + SELECT sw.store_id, sw.warehouse_use_status, sw.policy_config, s.company_name + FROM wms_store_warehouse sw JOIN wms_store s ON s.id = sw.store_id + WHERE sw.warehouse_id = ? AND sw.warehouse_use_status = 1 + ORDER BY sw.id DESC LIMIT 5`, [ whId ]); + console.log('== store_warehouse contracts (warehouse=' + whId + ') =='); + console.log(JSON.stringify(stores, null, 2)); + + const [stocks] = await conn.query(` + SELECT sw.id, sw.item_code, sw.item_name, sw.is_batch_mgmt, sw.is_shelf_life_mgmt, sw.is_valid, sw.quantity, sw.store_id + FROM wms_stock_warehouse sw + WHERE sw.warehouse_id = ? AND sw.is_valid = 'Y' AND sw.deleted_at IS NULL + ORDER BY sw.id DESC LIMIT 8`, [ whId ]); + console.log('== stock_warehouse products =='); + console.log(JSON.stringify(stocks, null, 2)); + + const [spacesCols] = await conn.query('SHOW COLUMNS FROM wms_location_space'); + console.log('== wms_location_space columns =='); + console.log(spacesCols.map(c => c.Field).join(',')); + + const [spaces] = await conn.query(` + SELECT id, space_code, custom_name, is_enabled, current_quantity + FROM wms_location_space + WHERE warehouse_id = ? AND is_enabled = 1 AND deleted_at IS NULL + ORDER BY id LIMIT 8`, [ whId ]); + console.log('== location spaces =='); + console.log(JSON.stringify(spaces, null, 2)); + + await conn.end(); +})().catch(e => { console.error(e); process.exit(1); }); diff --git a/script/tmp-test-putaway-batch-compare.cjs b/script/tmp-test-putaway-batch-compare.cjs new file mode 100644 index 0000000..d8963f7 --- /dev/null +++ b/script/tmp-test-putaway-batch-compare.cjs @@ -0,0 +1,136 @@ +'use strict'; +/** + * 批次维度对比测试(真实接口): + * 1. A 两步:批次 B-A-1 入库 10 件 → storage 建行 + * 2. B 一步:批次 B-B-1 入库 10 件 → storage 建行(不同批次不互相影响) + * 3. A 两步:批次 B-A-1 再入库 5 件 → 同批次累加到 15 + * 4. B 一步:批次 B-B-1 再入库 5 件 → 同批次累加到 15 + * 商品 159061 / 库位 5918。测试数据不清理。 + */ +const mysql = require('mysql2/promise'); +const jwt = require('jsonwebtoken'); + +const BASE = 'http://127.0.0.1:6060'; +const JWT_SECRET = 'E5#ex.g@,GfL_8?'; +const ACCOUNT_ID = 1; +const STORE_ID = 1000000; +const STOCK_ID = 159061; +const SPACE_ID = 5918; + +const token = jwt.sign({ id: ACCOUNT_ID }, JWT_SECRET, { expiresIn: 14400 }); + +async function db() { + return mysql.createConnection({ host: '127.0.0.1', port: 3307, user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms' }); +} + +async function call(method, data) { + const res = await fetch(`${BASE}/system?method=${method}&v=1×tamp=${Date.now()}`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + platform: 'web', + project: 'all', + authorization: `Bearer ${token}`, + }, + body: JSON.stringify(data || {}), + }); + const text = await res.text(); + let parsed; + try { parsed = JSON.parse(text); } catch { parsed = text; } + return { http: res.status, body: parsed }; +} + +function step(name, res) { + const code = res.body && res.body.code; + const ok = res.http === 200 && res.body && res.body.flag === 'success' && (code === 200 || code === 1); + console.log(` [${ok ? 'OK' : 'FAIL'}] ${name} http=${res.http} code=${code} msg=${res.body && res.body.message}`); + if (!ok) console.log(' 响应:', JSON.stringify(res.body).slice(0, 600)); + return ok; +} + +async function runFlow(tag, mode, batchNo, qty) { + console.log(`\n===== ${tag}:批次=${batchNo} 数量=${qty} =====`); + const conn = await db(); + const [before] = await conn.query( + `SELECT quantity FROM wms_stock_warehouse WHERE id = ?`, [ STOCK_ID ] + ); + + // 收货单全链路 + const createRes = await call('storage.receiving.create', { + store_id: STORE_ID, delivery_method: 'other', loading_method: 'with_pallet', + remark: `[批次对比-${tag}-${batchNo}]`, status: 'receiving', + }); + const b = createRes.body || {}; + const receivingId = (b.data && b.data.id) || b.id; + if (!step('创建收货单', createRes)) { await conn.end(); return null; } + + const addRes = await call('storage.receiving.addDetail', { + receiving_id: receivingId, + item: { product_name: '批次对比测试商品', barcode: `B${Date.now()}`, actual_quantity: qty, batch_number: batchNo, space_id: SPACE_ID }, + }); + const addBody = addRes.body || {}; + const addData = addBody.data || addBody; + const detailId = addData.selectId || (addData.details && addData.details[0] && addData.details[0].id); + if (!step('添加明细', addRes)) { await conn.end(); return null; } + + if (!step('绑定商品', await call('storage.receiving.bindDetailProduct', { detail_id: detailId, system_product_id: STOCK_ID }))) { await conn.end(); return null; } + if (!step('完成收货', await call('storage.receiving.completeReceiving', { id: receivingId }))) { await conn.end(); return null; } + if (!step('审核', await call('storage.receiving.reviewReceiving', { ids: [ receivingId ] }))) { await conn.end(); return null; } + + let entryOrderId; + if (mode === 'A') { + const pRes = await call('storage.inventory.quickPutaway', { receiving_id: receivingId }); + if (!step('quickPutaway', pRes)) { await conn.end(); return null; } + entryOrderId = pRes.body.data.entry_order_id; + if (!step('addItem(绑定收货明细)', await call('storage.entry.addItem', { + entry_order_id: entryOrderId, + items: [{ stock_id: STOCK_ID, quantity: qty, space_id: SPACE_ID, receiving_detail_id: detailId, allocated_quantity: qty, inbound_type: 'pda' }], + }))) { await conn.end(); return null; } + if (!step('commit', await call('storage.entry.commit', { entry_order_id: entryOrderId }))) { await conn.end(); return null; } + } else { + const dRes = await call('storage.inventory.directPutaway', { receiving_id: receivingId }); + if (!step('directPutaway', dRes)) { await conn.end(); return null; } + entryOrderId = dRes.body.data.entry_order_id; + } + + const [after] = await conn.query( + `SELECT quantity FROM wms_stock_warehouse WHERE id = ?`, [ STOCK_ID ] + ); + console.log(` ── wms_stock_warehouse ${STOCK_ID}: ${before[0].quantity} → ${after[0].quantity}(+${qty})`); + + const [storages] = await conn.query( + `SELECT id, space_id, stock_id, batch_no, inventory_type, quantity, available_quantity, inbound_order_no, entry_order_id + FROM wms_storage WHERE stock_id = ? AND space_id = ? ORDER BY batch_no`, [ STOCK_ID, SPACE_ID ] + ); + console.log(' ── wms_storage(商品 159061 / 库位 5918 全部行)──'); + console.log(' ', JSON.stringify(storages)); + + await conn.end(); + return { receivingId, entryOrderId }; +} + +async function main() { + await runFlow('① A-两步', 'A', 'B-A-1', 10); + await runFlow('② B-一步', 'B', 'B-B-1', 10); + await runFlow('③ A-两步(同批次累加)', 'A', 'B-A-1', 5); + await runFlow('④ B-一步(同批次累加)', 'B', 'B-B-1', 5); + + const conn = await db(); + const [storages] = await conn.query( + `SELECT id, space_id, stock_id, batch_no, inventory_type, quantity, locked_quantity, available_quantity, inbound_order_no, receiving_id, entry_order_id + FROM wms_storage WHERE stock_id = 159061 AND space_id = 5918 ORDER BY batch_no` + ); + console.log('\n========== 最终 wms_storage 对比(商品 159061 / 库位 5918) =========='); + console.log(JSON.stringify(storages, null, 2)); + + const [txns] = await conn.query( + `SELECT order_no, transaction_type, stock_id, storage_id, space_id, quantity, before_quantity, after_quantity, batch_no, order_type + FROM wms_storage_transaction WHERE stock_id = 159061 AND space_id = 5918 AND batch_no IN ('B-A-1','B-B-1') ORDER BY id` + ); + console.log('\n========== 库位流水(批次 B-A-1 / B-B-1) =========='); + console.log(JSON.stringify(txns, null, 2)); + await conn.end(); + console.log('\n================ 批次对比测试结束 ================'); +} + +main().then(() => process.exit(0)).catch(e => { console.error(e); process.exit(1); }); diff --git a/script/tmp-test-putaway-compare.cjs b/script/tmp-test-putaway-compare.cjs new file mode 100644 index 0000000..8042905 --- /dev/null +++ b/script/tmp-test-putaway-compare.cjs @@ -0,0 +1,261 @@ +'use strict'; +/** + * 临时对比测试:quickPutaway(转入库单) vs directPutaway(直入库存) + * 全链路走真实接口:创建收货单 → 添加明细 → 绑定商品 → 完成收货 → 审核 → 上架。 + * 测试数据不清理,保留以便核对。 + * 用法:node script/tmp-test-putaway-compare.cjs + */ +const mysql = require('mysql2/promise'); +const jwt = require('jsonwebtoken'); + +const BASE = 'http://127.0.0.1:6060'; +const JWT_SECRET = 'E5#ex.g@,GfL_8?'; +const ACCOUNT_ID = 1; +const WAREHOUSE_ID = 100000; +const STORE_ID = 1000000; + +// 商品:159061 非批次非效期;159064 效期管理(非批次) +const PRODUCTS = [ + { stock_id: 159061, item_code: '20260703', qty: 30, batch_number: 'TQB1', space_id: null }, + { stock_id: 159064, item_code: '544354', qty: 7, batch_number: 'TQB2', production_date: '2026-01-01', expiry_date: '2027-01-01', space_id: null }, +]; + +const token = jwt.sign({ id: ACCOUNT_ID }, JWT_SECRET, { expiresIn: 14400 }); + +async function db() { + return mysql.createConnection({ + host: '127.0.0.1', port: 3307, user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms', + }); +} + +async function call(method, data) { + const res = await fetch(`${BASE}/system?method=${method}&v=1×tamp=${Date.now()}`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + platform: 'web', + project: 'all', + authorization: `Bearer ${token}`, + }, + body: JSON.stringify(data || {}), + }); + const text = await res.text(); + let parsed; + try { parsed = JSON.parse(text); } catch { parsed = text; } + return { http: res.status, body: parsed }; +} + +function step(name, res, extract) { + const bodyCode = res.body && res.body.code; + const ok = res.http === 200 && res.body && res.body.flag === 'success' && (bodyCode === 200 || bodyCode === 1); + let extra = ''; + if (extract && res.body && res.body.data) { + try { extra = JSON.stringify(extract(res.body.data)); } catch (e) { /* ignore */ } + } + console.log(` [${ok ? 'OK' : 'FAIL'}] ${name} http=${res.http} code=${bodyCode} msg=${res.body && res.body.message} ${extra}`); + return ok; +} + +async function runFlow(tag, putawayMethod) { + console.log(`\n================ 流程 ${tag}(${putawayMethod}) ================`); + const conn = await db(); + + // 快照入库前商品总库存 + const stockIds = PRODUCTS.map(p => p.stock_id); + const [beforeStock] = await conn.query( + `SELECT id, quantity, locked_quantity FROM wms_stock_warehouse WHERE id IN (?)`, [ stockIds ] + ); + + // 1. 创建收货单 + const createRes = await call('storage.receiving.create', { + store_id: STORE_ID, + delivery_method: 'other', + loading_method: 'with_pallet', + remark: `[自动对比测试-${tag}]`, + status: 'receiving', + }); + const createBody = createRes.body || {}; + const receivingId = createBody.data && createBody.data.id ? createBody.data.id : createBody.id; + const receivingNumber = (createBody.data && createBody.data.receiving_number) || createBody.receiving_number; + if (!step('创建收货单', createRes, () => ({ id: receivingId, receiving_number: receivingNumber }))) { + console.log(' create 响应:', JSON.stringify(createBody).slice(0, 600)); + return { conn, receivingId: 0 }; + } + console.log(` receiving_id=${receivingId} receiving_number=${receivingNumber}`); + + // 2. 添加明细(含库位) + const detailIds = []; + for (let i = 0; i < PRODUCTS.length; i++) { + const p = PRODUCTS[i]; + const addRes = await call('storage.receiving.addDetail', { + receiving_id: receivingId, + item: { + product_name: `对比测试商品${i + 1}`, + barcode: `TMPBC${Date.now()}${i}`, + actual_quantity: p.qty, + batch_number: p.batch_number, + production_date: p.production_date || null, + expiry_date: p.expiry_date || null, + space_id: p.space_id, + }, + }); + const addBody = addRes.body || {}; + const addData = addBody.data || addBody; + const newDetailId = addData.selectId + || (addData.details && Array.isArray(addData.details) && addData.details[0] && addData.details[0].id); + if (!step(`添加明细#${i + 1}`, addRes, () => ({ detail_id: newDetailId }))) { + console.log(' addDetail 响应:', JSON.stringify(addBody).slice(0, 600)); + return { conn, receivingId }; + } + detailIds.push(newDetailId); + } + + // 3. 绑定系统商品 + for (let i = 0; i < PRODUCTS.length; i++) { + const bindRes = await call('storage.receiving.bindDetailProduct', { + detail_id: detailIds[i], + system_product_id: PRODUCTS[i].stock_id, + }); + if (!step(`绑定商品#${i + 1}`, bindRes, d => ({ detail_id: d.detail_id, system_product_id: d.system_product_id }))) return { conn, receivingId }; + } + + // 4. 完成收货 + const completeRes = await call('storage.receiving.completeReceiving', { id: receivingId }); + if (!step('完成收货', completeRes, d => ({ status: d.status || d.receiving_status }))) { + console.log(' completeReceiving 响应:', JSON.stringify(completeRes.body).slice(0, 500)); + return { conn, receivingId }; + } + + // 5. 审核 + const reviewRes = await call('storage.receiving.reviewReceiving', { ids: [ receivingId ] }); + if (!step('审核收货单', reviewRes)) { + console.log(' reviewReceiving 响应:', JSON.stringify(reviewRes.body).slice(0, 500)); + return { conn, receivingId }; + } + + // 6. 上架 + const putawayRes = await call(putawayMethod, { receiving_id: receivingId }); + if (!step(`上架(${putawayMethod})`, putawayRes, d => ({ entry_order_id: d.entry_order_id, entry_order_code: d.entry_order_code, order_status: d.order_status }))) { + console.log(' 上架响应:', JSON.stringify(putawayRes.body).slice(0, 800)); + return { conn, receivingId }; + } + + // 7. 对比验证数据 + const entryOrderId = putawayRes.body.data.entry_order_id; + const entryOrderCode = putawayRes.body.data.entry_order_code; + + const [afterStock] = await conn.query( + `SELECT id, quantity, locked_quantity FROM wms_stock_warehouse WHERE id IN (?)`, [ stockIds ] + ); + console.log(' ── 商品总库存(wms_stock_warehouse)──'); + for (const b of beforeStock) { + const a = afterStock.find(x => String(x.id) === String(b.id)) || { quantity: '?', locked_quantity: '?' }; + console.log(` stock_id=${b.id} before=${b.quantity} after=${a.quantity} locked=${a.locked_quantity}`); + } + + const [entryOrder] = await conn.query( + `SELECT id, entry_order_code, order_type, order_status, sync_status, total_order_lines FROM wms_entry_order WHERE id = ?`, [ entryOrderId ] + ); + console.log(' ── 入库单(wms_entry_order)──'); + console.log(' ', JSON.stringify(entryOrder[0] || null)); + + const [entryItems] = await conn.query( + `SELECT order_line_no, item_code, stock_id, count, received_quantity, inventory_type FROM wms_entry_items WHERE order_id = ? ORDER BY order_line_no`, [ entryOrderId ] + ); + console.log(' ── 入库单明细(wms_entry_items,共 ' + entryItems.length + ' 行)──'); + console.log(' ', JSON.stringify(entryItems)); + + const [orderReceiving] = await conn.query( + `SELECT entry_order_id, receiving_id FROM wms_entry_order_receiving WHERE entry_order_id = ?`, [ entryOrderId ] + ); + console.log(' ── 绑定(wms_entry_order_receiving)──'); + console.log(' ', JSON.stringify(orderReceiving)); + + const [receivingRow] = await conn.query( + `SELECT id, status, is_review, storage_status, detail_status FROM wms_receiving WHERE id = ?`, [ receivingId ] + ); + console.log(' ── 收货单主表(wms_receiving)──'); + console.log(' ', JSON.stringify(receivingRow[0] || null)); + + const [receivingDetails] = await conn.query( + `SELECT id, system_product_id, actual_quantity, stored_quantity, storage_status, space_id, batch_number FROM wms_receiving_detail WHERE receiving_id = ? ORDER BY id`, [ receivingId ] + ); + console.log(' ── 收货明细(wms_receiving_detail)──'); + console.log(' ', JSON.stringify(receivingDetails)); + + const [storages] = await conn.query( + `SELECT id, space_id, stock_id, batch_no, inventory_type, quantity, locked_quantity, available_quantity, + inbound_order_no, receiving_id, entry_order_id, production_date, expiry_date + FROM wms_storage + WHERE entry_order_id = ? OR (inbound_order_no = ? AND receiving_id = ?) + ORDER BY id`, [ entryOrderId, entryOrderCode, receivingId ] + ); + console.log(' ── 库位库存(wms_storage,共 ' + storages.length + ' 行)──'); + console.log(' ', JSON.stringify(storages)); + + const [stockTxns] = await conn.query( + `SELECT transaction_type, stock_id, quantity, before_quantity, after_quantity, batch_no, order_type, order_no, receiving_id, entry_order_id + FROM wms_stock_transaction WHERE order_no = ? OR entry_order_id = ? ORDER BY id`, [ entryOrderCode, entryOrderId ] + ); + console.log(' ── 商品流水(wms_stock_transaction,共 ' + stockTxns.length + ' 行)──'); + console.log(' ', JSON.stringify(stockTxns)); + + const [storageTxns] = await conn.query( + `SELECT transaction_type, stock_id, storage_id, space_id, quantity, before_quantity, after_quantity, batch_no, order_type, order_no + FROM wms_storage_transaction WHERE order_no = ? OR order_id = ? ORDER BY id`, [ entryOrderCode, entryOrderId ] + ); + console.log(' ── 库位流水(wms_storage_transaction,共 ' + storageTxns.length + ' 行)──'); + console.log(' ', JSON.stringify(storageTxns)); + + const [opLogs] = await conn.query( + `SELECT business_type, operation_code, business_id, operator_name, message + FROM wms_operation_log WHERE business_id = ? ORDER BY id`, [ String(entryOrderId) ] + ); + console.log(' ── 操作日志(wms_operation_log,共 ' + opLogs.length + ' 行)──'); + console.log(' ', JSON.stringify(opLogs)); + + await conn.end(); + return { receivingId, entryOrderId, entryOrderCode }; +} + +async function main() { + const conn = await db(); + // 取两个真实库位 + const [spaces] = await conn.query( + `SELECT id, space_code FROM wms_location_space WHERE warehouse_id = ? AND is_enabled = 1 AND deleted_at IS NULL ORDER BY id LIMIT 3`, + [ WAREHOUSE_ID ] + ); + console.log('使用库位:', JSON.stringify(spaces)); + PRODUCTS[0].space_id = spaces[0].id; + PRODUCTS[1].space_id = spaces[1] ? spaces[1].id : spaces[0].id; + + // 开关状态:quick 已开(货主 1000000 配置为 1);direct 需开启 + const [beforePolicy] = await conn.query( + `SELECT policy_config FROM wms_store_warehouse WHERE store_id = ? AND warehouse_id = ?`, [ STORE_ID, WAREHOUSE_ID ] + ); + console.log('货主 policy_config:', JSON.stringify(beforePolicy[0] && beforePolicy[0].policy_config)); + await conn.end(); + + // 流程 A:转入库单(可用 node script/tmp-test-putaway-compare.cjs A 单独跑) + if (!process.argv[2] || process.argv[2] === 'A') { + await runFlow('A-quickPutaway', 'storage.inventory.quickPutaway'); + } + + // 开启直入开关(测试准备,SQL 直接配置) + const conn2 = await db(); + await conn2.query( + `UPDATE wms_store_warehouse SET policy_config = JSON_SET(COALESCE(policy_config,'{}'), '$.allow_receiving_direct_putaway', 1) + WHERE store_id = ? AND warehouse_id = ?`, [ STORE_ID, WAREHOUSE_ID ] + ); + await conn2.end(); + console.log('\n已开启 allow_receiving_direct_putaway=1(store=1000000, warehouse=100000)'); + + // 流程 B:直入库存 + if (!process.argv[2] || process.argv[2] === 'B') { + await runFlow('B-directPutaway', 'storage.inventory.directPutaway'); + } + + console.log('\n================ 测试结束 ================'); +} + +main().then(() => process.exit(0)).catch(e => { console.error(e); process.exit(1); }); diff --git a/script/tmp-test-putaway-full-compare.cjs b/script/tmp-test-putaway-full-compare.cjs new file mode 100644 index 0000000..7336513 --- /dev/null +++ b/script/tmp-test-putaway-full-compare.cjs @@ -0,0 +1,281 @@ +'use strict'; +/** + * 临时完整对比测试: + * 流程 A(两步):storage.inventory.quickPutaway(转入库单) + * → storage.entry.addItem(导入入库,绑定收货明细) + * → storage.entry.commit(提交确认写库存) + * 流程 B(一步):storage.inventory.directPutaway(直入库存) + * 收货单链路全部走真实接口。测试数据不清理。 + * 用法:node script/tmp-test-putaway-full-compare.cjs [A|B] + */ +const mysql = require('mysql2/promise'); +const jwt = require('jsonwebtoken'); + +const BASE = 'http://127.0.0.1:6060'; +const JWT_SECRET = 'E5#ex.g@,GfL_8?'; +const ACCOUNT_ID = 1; +const WAREHOUSE_ID = 100000; +const STORE_ID = 1000000; + +const PRODUCTS = [ + { stock_id: 159061, item_code: '20260703', qty: 30, batch_number: 'TQB1', space_id: null }, + { stock_id: 159064, item_code: '544354', qty: 7, batch_number: 'TQB2', production_date: '2026-01-01', expiry_date: '2027-01-01', space_id: null }, +]; + +const token = jwt.sign({ id: ACCOUNT_ID }, JWT_SECRET, { expiresIn: 14400 }); + +async function db() { + return mysql.createConnection({ + host: '127.0.0.1', port: 3307, user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms', + }); +} + +async function call(method, data) { + const res = await fetch(`${BASE}/system?method=${method}&v=1×tamp=${Date.now()}`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + platform: 'web', + project: 'all', + authorization: `Bearer ${token}`, + }, + body: JSON.stringify(data || {}), + }); + const text = await res.text(); + let parsed; + try { parsed = JSON.parse(text); } catch { parsed = text; } + return { http: res.status, body: parsed }; +} + +function step(name, res, extract) { + const bodyCode = res.body && res.body.code; + const ok = res.http === 200 && res.body && res.body.flag === 'success' && (bodyCode === 200 || bodyCode === 1); + let extra = ''; + if (extract && res.body && res.body.data) { + try { extra = JSON.stringify(extract(res.body.data)); } catch (e) { /* ignore */ } + } + console.log(` [${ok ? 'OK' : 'FAIL'}] ${name} http=${res.http} code=${bodyCode} msg=${res.body && res.body.message} ${extra}`); + return ok; +} + +async function verifyFlow(conn, tag, receivingId, entryOrderId, entryOrderCode, beforeStock) { + const stockIds = PRODUCTS.map(p => p.stock_id); + const [afterStock] = await conn.query( + `SELECT id, quantity, locked_quantity FROM wms_stock_warehouse WHERE id IN (?)`, [ stockIds ] + ); + console.log(` ── [${tag}] 商品总库存(wms_stock_warehouse)──`); + for (const b of beforeStock) { + const a = afterStock.find(x => String(x.id) === String(b.id)) || { quantity: '?', locked_quantity: '?' }; + console.log(` stock_id=${b.id} before=${b.quantity} after=${a.quantity} locked=${a.locked_quantity}`); + } + + const [entryOrder] = await conn.query( + `SELECT id, entry_order_code, order_type, order_status, sync_status, total_order_lines FROM wms_entry_order WHERE id = ?`, [ entryOrderId ] + ); + console.log(` ── [${tag}] 入库单(wms_entry_order)──`); + console.log(' ', JSON.stringify(entryOrder[0] || null)); + + const [entryItems] = await conn.query( + `SELECT order_line_no, item_code, stock_id, count, received_quantity, inventory_type FROM wms_entry_items WHERE order_id = ? ORDER BY order_line_no`, [ entryOrderId ] + ); + console.log(` ── [${tag}] 入库单明细(wms_entry_items,共 ${entryItems.length} 行)──`); + console.log(' ', JSON.stringify(entryItems)); + + const [orderReceiving] = await conn.query( + `SELECT entry_order_id, receiving_id FROM wms_entry_order_receiving WHERE entry_order_id = ?`, [ entryOrderId ] + ); + console.log(` ── [${tag}] 绑定(wms_entry_order_receiving)──`); + console.log(' ', JSON.stringify(orderReceiving)); + + const [receivingRow] = await conn.query( + `SELECT id, status, is_review, storage_status, detail_status FROM wms_receiving WHERE id = ?`, [ receivingId ] + ); + console.log(` ── [${tag}] 收货单主表(wms_receiving)──`); + console.log(' ', JSON.stringify(receivingRow[0] || null)); + + const [receivingDetails] = await conn.query( + `SELECT id, system_product_id, actual_quantity, stored_quantity, storage_status, space_id, batch_number FROM wms_receiving_detail WHERE receiving_id = ? ORDER BY id`, [ receivingId ] + ); + console.log(` ── [${tag}] 收货明细(wms_receiving_detail)──`); + console.log(' ', JSON.stringify(receivingDetails)); + + const [storages] = await conn.query( + `SELECT id, space_id, stock_id, batch_no, inventory_type, quantity, locked_quantity, available_quantity, + inbound_order_no, receiving_id, entry_order_id, production_date, expiry_date + FROM wms_storage + WHERE entry_order_id = ? OR (inbound_order_no = ? AND receiving_id = ?) + ORDER BY id`, [ entryOrderId, entryOrderCode, receivingId ] + ); + console.log(` ── [${tag}] 库位库存(wms_storage,共 ${storages.length} 行)──`); + console.log(' ', JSON.stringify(storages)); + + const [stockTxns] = await conn.query( + `SELECT transaction_type, stock_id, quantity, before_quantity, after_quantity, batch_no, order_type, order_no, receiving_id, entry_order_id + FROM wms_stock_transaction WHERE order_no = ? OR entry_order_id = ? ORDER BY id`, [ entryOrderCode, entryOrderId ] + ); + console.log(` ── [${tag}] 商品流水(wms_stock_transaction,共 ${stockTxns.length} 行)──`); + console.log(' ', JSON.stringify(stockTxns)); + + const [storageTxns] = await conn.query( + `SELECT transaction_type, stock_id, storage_id, space_id, quantity, before_quantity, after_quantity, batch_no, order_type, order_no + FROM wms_storage_transaction WHERE order_no = ? OR order_id = ? ORDER BY id`, [ entryOrderCode, entryOrderId ] + ); + console.log(` ── [${tag}] 库位流水(wms_storage_transaction,共 ${storageTxns.length} 行)──`); + console.log(' ', JSON.stringify(storageTxns)); + + const [directLogs] = await conn.query( + `SELECT id, stock_id, quantity, entry_item_id, receiving_detail_id, space_id, status, inbound_type + FROM wms_inbound_direct_log WHERE entry_order_id = ? ORDER BY id`, [ entryOrderId ] + ); + console.log(` ── [${tag}] 导入入库记录(wms_inbound_direct_log,共 ${directLogs.length} 行)──`); + console.log(' ', JSON.stringify(directLogs)); + + const [opLogs] = await conn.query( + `SELECT business_type, operation_code, operator_name, message + FROM wms_operation_log WHERE business_id = ? AND operation_code IN + ('ENTRY_ORDER_QUICK_PUTAWAY','ENTRY_ORDER_DIRECT_PUTAWAY','STORAGE_DIRECT_PUTAWAY','STOCK_DIRECT_PUTAWAY','DIRECT_INBOUND_ADD','DIRECT_INBOUND_COMMIT') + ORDER BY id`, [ String(entryOrderId) ] + ); + console.log(` ── [${tag}] 本流程操作日志(wms_operation_log,共 ${opLogs.length} 行)──`); + console.log(' ', JSON.stringify(opLogs)); +} + +async function runFlow(tag, mode) { + console.log(`\n================ 流程 ${tag}(${mode}) ================`); + const conn = await db(); + + const stockIds = PRODUCTS.map(p => p.stock_id); + const [beforeStock] = await conn.query( + `SELECT id, quantity, locked_quantity FROM wms_stock_warehouse WHERE id IN (?)`, [ stockIds ] + ); + + // 收货单全链路 + const createRes = await call('storage.receiving.create', { + store_id: STORE_ID, + delivery_method: 'other', + loading_method: 'with_pallet', + remark: `[完整对比测试-${tag}]`, + status: 'receiving', + }); + const createBody = createRes.body || {}; + const receivingId = createBody.data && createBody.data.id ? createBody.data.id : createBody.id; + const receivingNumber = (createBody.data && createBody.data.receiving_number) || createBody.receiving_number; + if (!step('创建收货单', createRes, () => ({ id: receivingId, receiving_number: receivingNumber }))) { + await conn.end(); return; + } + console.log(` receiving_id=${receivingId} receiving_number=${receivingNumber}`); + + const detailIds = []; + for (let i = 0; i < PRODUCTS.length; i++) { + const p = PRODUCTS[i]; + const addRes = await call('storage.receiving.addDetail', { + receiving_id: receivingId, + item: { + product_name: `完整对比测试商品${i + 1}`, + barcode: `FULLBC${Date.now()}${i}`, + actual_quantity: p.qty, + batch_number: p.batch_number, + production_date: p.production_date || null, + expiry_date: p.expiry_date || null, + space_id: p.space_id, + }, + }); + const addBody = addRes.body || {}; + const addData = addBody.data || addBody; + const newDetailId = addData.selectId + || (addData.details && Array.isArray(addData.details) && addData.details[0] && addData.details[0].id); + if (!step(`添加明细#${i + 1}`, addRes, () => ({ detail_id: newDetailId }))) { await conn.end(); return; } + detailIds.push(newDetailId); + } + + for (let i = 0; i < PRODUCTS.length; i++) { + const bindRes = await call('storage.receiving.bindDetailProduct', { + detail_id: detailIds[i], + system_product_id: PRODUCTS[i].stock_id, + }); + if (!step(`绑定商品#${i + 1}`, bindRes, d => ({ detail_id: d.detail_id, system_product_id: d.system_product_id }))) { await conn.end(); return; } + } + + const completeRes = await call('storage.receiving.completeReceiving', { id: receivingId }); + if (!step('完成收货', completeRes)) { + console.log(' completeReceiving 响应:', JSON.stringify(completeRes.body).slice(0, 500)); + await conn.end(); return; + } + + const reviewRes = await call('storage.receiving.reviewReceiving', { ids: [ receivingId ] }); + if (!step('审核收货单', reviewRes)) { + console.log(' reviewReceiving 响应:', JSON.stringify(reviewRes.body).slice(0, 500)); + await conn.end(); return; + } + + let entryOrderId; + let entryOrderCode; + + if (mode === 'A') { + // 两步流程第一步:转入库单 + const putawayRes = await call('storage.inventory.quickPutaway', { receiving_id: receivingId }); + if (!step('① quickPutaway(转入库单)', putawayRes, d => ({ entry_order_id: d.entry_order_id, entry_order_code: d.entry_order_code, order_status: d.order_status }))) { + console.log(' 响应:', JSON.stringify(putawayRes.body).slice(0, 600)); + await conn.end(); return; + } + entryOrderId = putawayRes.body.data.entry_order_id; + entryOrderCode = putawayRes.body.data.entry_order_code; + + // 两步流程第二步:导入入库(绑定收货明细 + 收货明细库位) + const addItemRes = await call('storage.entry.addItem', { + entry_order_id: entryOrderId, + items: [ + { stock_id: PRODUCTS[0].stock_id, quantity: PRODUCTS[0].qty, space_id: PRODUCTS[0].space_id, receiving_detail_id: detailIds[0], allocated_quantity: PRODUCTS[0].qty, inbound_type: 'pda' }, + { stock_id: PRODUCTS[1].stock_id, quantity: PRODUCTS[1].qty, space_id: PRODUCTS[1].space_id, receiving_detail_id: detailIds[1], allocated_quantity: PRODUCTS[1].qty, inbound_type: 'pda' }, + ], + }); + if (!step('② storage.entry.addItem(导入入库,绑定收货明细)', addItemRes, d => ({ count: d.count, total_quantity: d.total_quantity }))) { + console.log(' 响应:', JSON.stringify(addItemRes.body).slice(0, 800)); + await conn.end(); return; + } + + // 两步流程第三步:提交确认写库存 + const commitRes = await call('storage.entry.commit', { entry_order_id: entryOrderId }); + if (!step('③ storage.entry.commit(提交确认入库)', commitRes, d => ({ success: d.success, message: d.message }))) { + console.log(' 响应:', JSON.stringify(commitRes.body).slice(0, 800)); + await conn.end(); return; + } + } else { + // 一步直入 + const directRes = await call('storage.inventory.directPutaway', { receiving_id: receivingId }); + if (!step('① directPutaway(一步直入)', directRes, d => ({ entry_order_id: d.entry_order_id, entry_order_code: d.entry_order_code, order_status: d.order_status }))) { + console.log(' 响应:', JSON.stringify(directRes.body).slice(0, 600)); + await conn.end(); return; + } + entryOrderId = directRes.body.data.entry_order_id; + entryOrderCode = directRes.body.data.entry_order_code; + } + + await verifyFlow(conn, tag, receivingId, entryOrderId, entryOrderCode, beforeStock); + await conn.end(); + console.log(`================ 流程 ${tag} 完成:receiving=${receivingId} entry_order=${entryOrderId} ================`); +} + +async function main() { + const conn = await db(); + const [spaces] = await conn.query( + `SELECT id, space_code FROM wms_location_space WHERE warehouse_id = ? AND is_enabled = 1 AND deleted_at IS NULL ORDER BY id LIMIT 2`, + [ WAREHOUSE_ID ] + ); + console.log('使用库位:', JSON.stringify(spaces)); + PRODUCTS[0].space_id = spaces[0].id; + PRODUCTS[1].space_id = spaces[1] ? spaces[1].id : spaces[0].id; + await conn.end(); + + const only = (process.argv[2] || '').toUpperCase(); + if (!only || only === 'A') { + await runFlow('A-两步', 'A'); + } + if (!only || only === 'B') { + await runFlow('B-一步', 'B'); + } + + console.log('\n================ 测试结束 ================'); +} + +main().then(() => process.exit(0)).catch(e => { console.error(e); process.exit(1); }); diff --git a/script/tmp-verify-all-tables.cjs b/script/tmp-verify-all-tables.cjs new file mode 100644 index 0000000..a022480 --- /dev/null +++ b/script/tmp-verify-all-tables.cjs @@ -0,0 +1,103 @@ +'use strict'; +/** + * 全表核对:A 两步链路(收货单 1526 / 入库单 383) vs B 一步直入(收货单 1528 / 入库单 385) + * 覆盖 A 链路涉及的所有表(收货单阶段 + 转入库单 + 导入入库 + 提交确认)。 + * 只读,不产生数据。 + */ +const mysql = require('mysql2/promise'); + +const A = { receiving: 1526, entryOrder: 383, code: 'SCRK202608240003', detailIds: [ 2711, 2712 ] }; +const B = { receiving: 1528, entryOrder: 385, code: 'SCRK202608240005', detailIds: [ 2715, 2716 ] }; + +(async () => { + const conn = await mysql.createConnection({ + host: '127.0.0.1', port: 3307, user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms', + }); + + const show = async (title, sql, params) => { + const [rows] = await conn.query(sql, params); + console.log(`\n===== ${title} =====`); + console.log(JSON.stringify(rows, null, 2)); + }; + + for (const [ tag, t ] of [ [ 'A-两步', A ], [ 'B-一步', B ] ]) { + console.log(`\n########## ${tag}(receiving=${t.receiving}, entry_order=${t.entryOrder}) ##########`); + + await show('1. wms_receiving 收货单主表', ` + SELECT id, receiving_number, status, is_review, storage_status, detail_status, store_id, warehouse_id, total_items, total_quantity + FROM wms_receiving WHERE id = ?`, [ t.receiving ]); + + await show('2. wms_receiving_detail 收货明细', ` + SELECT id, receiving_id, system_product_id, actual_quantity, stored_quantity, storage_status, + space_id, batch_number, production_date, expiry_date, barcode, receiving_status + FROM wms_receiving_detail WHERE receiving_id = ? ORDER BY id`, [ t.receiving ]); + + await show('3. wms_entry_order 入库单', ` + SELECT id, entry_order_code, order_type, order_status, sync_status, sync_message, source_type, + total_order_lines, warehouse_id, store_id, store_name, warehouse_name, remark + FROM wms_entry_order WHERE id = ?`, [ t.entryOrder ]); + + await show('4. wms_entry_items 入库明细', ` + SELECT id, order_id, order_line_no, item_code, stock_id, count, received_quantity, confirm_quantity, inventory_type + FROM wms_entry_items WHERE order_id = ? ORDER BY order_line_no`, [ t.entryOrder ]); + + await show('5. wms_entry_order_receiving 主表绑定', ` + SELECT id, entry_order_id, receiving_id, created_at FROM wms_entry_order_receiving WHERE entry_order_id = ?`, [ t.entryOrder ]); + + await show('6. wms_inbound_direct_log 导入入库记录(两步中间态)', ` + SELECT id, entry_order_id, entry_order_code, stock_id, quantity, entry_item_id, receiving_detail_id, space_id, status, inbound_type, remark + FROM wms_inbound_direct_log WHERE entry_order_id = ? ORDER BY id`, [ t.entryOrder ]); + + await show('7. wms_stock_warehouse 商品总库存', ` + SELECT id, item_code, quantity, locked_quantity, is_valid FROM wms_stock_warehouse WHERE id IN (159061, 159064) ORDER BY id`); + + await show('8. wms_storage 库位库存', ` + SELECT id, space_id, stock_id, batch_no, inventory_type, quantity, locked_quantity, available_quantity, + inbound_order_no, receiving_id, entry_order_id, production_date, expiry_date, inbound_time + FROM wms_storage WHERE entry_order_id = ? OR (inbound_order_no = ? AND receiving_id = ?) ORDER BY id`, + [ t.entryOrder, t.code, t.receiving ]); + + await show('9. wms_stock_transaction 商品流水', ` + SELECT id, transaction_type, stock_id, quantity, before_quantity, after_quantity, + before_locked_quantity, after_locked_quantity, batch_no, order_type, order_no, receiving_id, entry_order_id, remark + FROM wms_stock_transaction WHERE order_no = ? OR entry_order_id = ? ORDER BY id`, [ t.code, t.entryOrder ]); + + await show('10. wms_storage_transaction 库位流水', ` + SELECT id, transaction_type, stock_id, storage_id, space_id, quantity, before_quantity, after_quantity, + before_locked_quantity, after_locked_quantity, batch_no, inventory_type, order_type, order_no, order_id + FROM wms_storage_transaction WHERE order_no = ? OR order_id = ? ORDER BY id`, [ t.code, t.entryOrder ]); + + await show('11. wms_operation_log 本流程操作日志', ` + SELECT id, business_type, business_id, operation_code, operator_name, warehouse_id, message + FROM wms_operation_log + WHERE business_id = ? AND operation_code IN + ('RECEIVING_CREATE','RECEIVING_ADD_DETAIL','RECEIVING_BIND_PRODUCT','RECEIVING_COMPLETE','RECEIVING_REVIEW', + 'ENTRY_ORDER_QUICK_PUTAWAY','DIRECT_INBOUND_ADD','DIRECT_INBOUND_COMMIT', + 'ENTRY_ORDER_DIRECT_PUTAWAY','STORAGE_DIRECT_PUTAWAY','STOCK_DIRECT_PUTAWAY') + ORDER BY id`, [ String(t.entryOrder) ]); + + await show('12. wms_operation_log 收货单维度操作日志', ` + SELECT id, business_type, business_id, operation_code, operator_name, warehouse_id, message + FROM wms_operation_log WHERE business_id = ? ORDER BY id`, [ String(t.receiving) ]); + + await show('13. wms_store_warehouse 货主签约与开关', ` + SELECT id, store_id, warehouse_id, warehouse_use_status, + JSON_EXTRACT(policy_config, '$.allow_receiving_quick_putaway') AS quick, + JSON_EXTRACT(policy_config, '$.allow_receiving_direct_putaway') AS direct + FROM wms_store_warehouse WHERE store_id = 1000000 AND warehouse_id = 100000`); + + await show('14. wms_stock_barcodes 本次绑定的条码', ` + SELECT id, stock_id, warehouse_id, barcode + FROM wms_stock_barcodes + WHERE stock_id IN (159061, 159064) + AND barcode IN (SELECT barcode FROM wms_receiving_detail WHERE receiving_id = ?) + ORDER BY id`, [ t.receiving ]); + + await show('15. wms_location_space 库位统计快照(入库链路不维护该统计)', ` + SELECT id, space_code, current_quantity, current_sku_count, is_enabled + FROM wms_location_space WHERE id IN (5918, 5919)`); + } + + await conn.end(); + process.exit(0); +})().catch(e => { console.error(e); process.exit(1); }); From 63713bf49071a00fbc4656362bd629750008268d Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 24 Aug 2026 18:47:38 +0800 Subject: [PATCH 266/550] =?UTF-8?q?fix(inbox):=20queryPackVideo=20?= =?UTF-8?q?=E6=89=93=E5=8C=85=E8=A7=86=E9=A2=91=E5=9C=B0=E5=9D=80=E6=8B=BC?= =?UTF-8?q?=E6=8E=A5=20CDN=20=E5=9F=9F=E5=90=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/inbox/functions.js | 71 ++++++++++++++++++++++++++-------- 1 file changed, 55 insertions(+), 16 deletions(-) diff --git a/app/service/inbox/functions.js b/app/service/inbox/functions.js index 5a9c494..d616428 100644 --- a/app/service/inbox/functions.js +++ b/app/service/inbox/functions.js @@ -2163,14 +2163,6 @@ class InboxFunctionsService extends Service { const toCreate = expressList.filter(e => !existingWaybillIds.has(e.id)); const alreadyExist = existingASList.map(r => r.after_sale_no); - const existedPairs = expressList - .filter(e => existingWaybillIds.has(e.id)) - .map(e => { - const row = existingASList.find(r => Number(r.waybill_id) === Number(e.id)); - return { waybill: e.waybill_code, as_no: (row && row.after_sale_no) || '' }; - }) - .filter(p => p.as_no); - // 第三步:创建工单(含原文)并映射 waybill_id → 工单号 const createdNos = []; const waybillToAsNo = {}; // waybill_id → after_sale_no 映射(新建 + 已存在) @@ -2285,12 +2277,18 @@ class InboxFunctionsService extends Service { } } - // 第六步:客户回信模板(单号+诉求+工单) - const createdPairs = toCreate.map(e => ({ - waybill: e.waybill_code, - as_no: waybillToAsNo[e.id] || '', - })); - const lines = [ ...createdPairs, ...existedPairs ].map(p => `运单${p.waybill} ${issue.label}问题已登记,工单:${p.as_no}`); + // 第六步:客户回信模板(单号+诉求,区分是否已通知快递) + const REPLY_TEXT = { + addr: { done: '修改地址已经登记', notify: '并已通知快递修改' }, + return: { done: '催退回已经登记', notify: '并已通知快递处理' }, + }; + const replyText = REPLY_TEXT[issue.sub_type] || REPLY_TEXT.addr; + const lines = expressList.map(e => { + const head = `运单${e.waybill_code}${replyText.done}`; + return notifiedWaybillIds.has(e.id) + ? `${head}·${replyText.notify}` + : `${head},稍后客服将人工跟进`; + }); if (notFound.length > 0) { lines.push(`未找到运单:${notFound.join('、')},请核实单号`); } @@ -2308,7 +2306,7 @@ class InboxFunctionsService extends Service { after_sale_nos: [ ...createdNos, ...alreadyExist ], notified_groups: notifiedTotal, not_found: notFound, - message: `${lines.join('\n')},稍后客服将人工核实跟进`, + message: lines.join('\n'), direct_reply: true, }, }; @@ -3172,9 +3170,11 @@ class InboxFunctionsService extends Service { }, raw: true, }); + // 视频地址拼接 CDN 域名(与 order.packing.list、queryReturn 对齐) + const recordingComputerId = await this._getRecordingComputerId(warehouseId); const urls = videos .filter(v => String(v.status || '') !== 'failed') - .map(v => String(v.video_url || '').trim()) + .map(v => this._buildVideoUrl(warehouseId, recordingComputerId, v.video_url)) .filter(Boolean); if (urls.length === 0) { @@ -3924,6 +3924,45 @@ class InboxFunctionsService extends Service { }; } } + + /** + * 获取仓库的录制电脑 ID(带缓存)。 + * @param {number} warehouseId 仓库ID + * @return {Promise} 录制电脑ID,找不到返回 null + */ + async _getRecordingComputerId(warehouseId) { + const cacheKey = `_recordingComputer_${warehouseId}`; + if (this[cacheKey] !== undefined) { + return this[cacheKey]; + } + const row = await this.ctx.model.PrintComputer.findOne({ + where: { warehouse_id: warehouseId, is_recording: true, deleted_at: null }, + attributes: [ 'id' ], + raw: true, + }); + this[cacheKey] = row ? row.id : null; + return this[cacheKey]; + } + + /** + * 构建视频完整 URL。 + * 格式:http://w{warehouseId}-c{recordingComputerId}.o.gztbyc.com{videoPath} + * @param {number} warehouseId 仓库ID + * @param {number|null} recordingComputerId 录制电脑ID + * @param {string} videoPath 视频路径 + * @return {string} 完整 URL + */ + _buildVideoUrl(warehouseId, recordingComputerId, videoPath) { + const path = String(videoPath || '').trim(); + if (!path || !recordingComputerId) { + return path; + } + // 已是完整 URL 时原样返回,避免重复拼接 + if (/^https?:\/\//i.test(path)) { + return path; + } + return `http://w${warehouseId}-c${recordingComputerId}.o.gztbyc.com${path}`; + } } module.exports = InboxFunctionsService; From c7266c53a8f8d6b32af804f4dac554a9fad33432 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 24 Aug 2026 18:47:41 +0800 Subject: [PATCH 267/550] =?UTF-8?q?fix(storage):=20receivingCompare=20?= =?UTF-8?q?=E5=A4=9A=E6=94=B6=E8=B4=A7=E5=8D=95=E5=85=88=E5=90=88=E5=B9=B6?= =?UTF-8?q?=E6=98=8E=E7=BB=86=E5=86=8D=E7=BB=9F=E4=B8=80=E5=AF=B9=E7=85=A7?= =?UTF-8?q?=EF=BC=8C=E4=BF=AE=E5=A4=8D=E5=85=A5=E5=BA=93=E8=AE=A1=E5=88=92?= =?UTF-8?q?=E6=95=B0=E9=87=8F=E9=87=8D=E5=A4=8D=E5=B1=95=E5=BC=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/systemMethods/storage/entry.js | 5 +- app/service/systems/storage/entry.js | 299 ++++++++++----------- methods/changes/system.json | 16 ++ methods/system.json | 100 ++++--- 4 files changed, 234 insertions(+), 186 deletions(-) diff --git a/app/service/systemMethods/storage/entry.js b/app/service/systemMethods/storage/entry.js index 2dc7da3..7e68924 100644 --- a/app/service/systemMethods/storage/entry.js +++ b/app/service/systemMethods/storage/entry.js @@ -349,8 +349,9 @@ class entryService extends MainService { } } /** - * 入库单商品与收货单商品逐行对照视图(system method 包装层)。 - * 支持传入多个收货单ID进行批量对照预览。 + * 入库单商品与收货单商品对照视图(system method 包装层)。 + * 支持传入多个收货单ID:多个收货单明细先合并为一个整体,再与入库单做一次对照, + * 每个入库明细仅输出一行(含合并收货数量与各收货单来源明细)。 * @param {Object} data 请求体 * @param {number} data.entry_order_id 入库单ID * @param {number[]} [data.receiving_ids] 收货单ID列表(优先使用) diff --git a/app/service/systems/storage/entry.js b/app/service/systems/storage/entry.js index 26b619d..956e6ad 100644 --- a/app/service/systems/storage/entry.js +++ b/app/service/systems/storage/entry.js @@ -1717,9 +1717,10 @@ class EntryService extends Service { } /** - * 入库单商品与收货单商品逐行对照视图(支持多个收货单)。 - * 以入库单明细为主,按 stock_id ↔ system_product_id 匹配收货单明细, - * 返回每个收货单的匹配/未匹配/收货单多余对照结果及汇总。 + * 入库单商品与收货单商品对照视图(支持多个收货单)。 + * 以入库单明细为对比主体:多个收货单的明细先合并为一个整体, + * 再与入库单明细做一次对照,每个入库明细只输出一行, + * 避免多收货单时入库计划数量被重复展开。 * * @param {Object} data 请求参数 * @param {number} data.entry_order_id 入库单ID @@ -1728,7 +1729,8 @@ class EntryService extends Service { * @return {Promise} code/data/message 结构 */ async receivingCompare(data = {}) { - const { ctx } = this; + const { ctx, app } = this; + const { Op } = app.Sequelize; const entryOrderId = Number(data.entry_order_id || 0); const warehouseId = ctx.user.store_id; @@ -1754,39 +1756,53 @@ class EntryService extends Service { return { code: 404, message: '入库单不存在或无权访问', data: null }; } - // 2. 查询入库单明细(所有收货单共用) + // 2. 查询入库单明细 const entryItems = await ctx.model.EntryItems.findAll({ where: { order_id: entryOrderId }, attributes: [ 'id', 'stock_id', 'count', 'received_quantity' ], raw: true, }); - // 3. 收集入库单所有 stock_id - const entryStockIds = [ ...new Set(entryItems.map(item => Number(item.stock_id)).filter(Boolean)) ]; - - // 4. 对每个收货单执行对比 - const comparisons = []; + // 3. 批量校验收货单(同仓库、未删除),无效的进入 errors + const receivingOrders = await ctx.model.Receiving.findAll({ + where: { + id: { [Op.in]: receivingIds }, + warehouse_id: warehouseId, + is_deleted: false, + }, + attributes: [ 'id', 'receiving_number' ], + raw: true, + }); + const receivingOrderMap = new Map(receivingOrders.map(row => [ Number(row.id), row ])); const errors = []; - for (const receivingId of receivingIds) { - const singleResult = await this._compareSingleReceiving({ - receivingId, - warehouseId, - entryOrderId, - entryOrder, - entryItems, - entryStockIds, - }); - if (singleResult._error) { - errors.push(singleResult._error); - } else { - comparisons.push(singleResult); + if (!receivingOrderMap.has(receivingId)) { + errors.push({ + receiving_id: receivingId, + status: 'error', + error_code: 'RECEIVING_NOT_FOUND', + error_message: '收货单不存在或无权访问', + }); } } + const validReceivingIds = [ ...receivingOrderMap.keys() ]; - const totalReceivings = receivingIds.length; - const matchedCount = comparisons.length; - const errorCount = errors.length; + // 4. 合并所有有效收货单的明细,再与入库单做一次对照 + let receivingDetails = []; + if (validReceivingIds.length > 0) { + receivingDetails = await ctx.model.ReceivingDetail.findAll({ + where: { receiving_id: { [Op.in]: validReceivingIds } }, + attributes: [ 'id', 'receiving_id', 'system_product_id', 'actual_quantity', 'product_name' ], + raw: true, + }); + } + + const merged = await this._buildMergedComparison({ + warehouseId, + entryItems, + receivingDetails, + receivingOrderMap, + }); return { code: 200, @@ -1794,93 +1810,64 @@ class EntryService extends Service { data: { entry_order_id: entryOrderId, entry_order_code: entryOrder.entry_order_code, - comparisons, + comparison: merged.comparison, + receiving_only: merged.receivingOnly, + summary: merged.summary, errors, total_summary: { - total_receivings: totalReceivings, - matched_count: matchedCount, - error_count: errorCount, + total_receivings: receivingIds.length, + matched_count: validReceivingIds.length, + error_count: errors.length, }, }, }; } /** - * 对单个收货单执行商品对照逻辑。 + * 将多个收货单的明细合并后,与入库单明细做一次对照。 + * 每个入库明细只输出一行(matched/entry_only),匹配时合并各收货单数量, + * 并通过 receiving_sources 列出各收货单来源明细。 + * * @param {Object} params 参数 - * @param {number} params.receivingId 收货单ID * @param {number} params.warehouseId 仓库ID - * @param {number} params.entryOrderId 入库单ID - * @param {Object} params.entryOrder 入库单记录 * @param {Object[]} params.entryItems 入库单明细列表 - * @param {number[]} params.entryStockIds 入库单 stock_id 集合 - * @return {Promise} 单个收货单的对照结果,或 { _error: ... } + * @param {Object[]} params.receivingDetails 已合并的收货单明细列表 + * @param {Map} params.receivingOrderMap 有效收货单 Map(id → 收货单记录) + * @return {Promise} { comparison, receivingOnly, summary } */ - async _compareSingleReceiving(params = {}) { + async _buildMergedComparison(params = {}) { const { ctx, app } = this; - const { receivingId, warehouseId, entryItems, entryStockIds } = params; - - // 校验收货单存在性与仓库匹配 - const receivingOrder = await ctx.model.Receiving.findOne({ - where: { - id: receivingId, - warehouse_id: warehouseId, - is_deleted: false, - }, - attributes: [ 'id', 'receiving_number', 'status', 'storage_status' ], - raw: true, - }); - if (!receivingOrder) { - return { - _error: { - receiving_id: receivingId, - status: 'error', - error_code: 'RECEIVING_NOT_FOUND', - error_message: '收货单不存在或无权访问', - }, - }; - } - - // 查询收货单明细 - const receivingDetails = await ctx.model.ReceivingDetail.findAll({ - where: { receiving_id: receivingId }, - attributes: [ 'id', 'system_product_id', 'actual_quantity', 'product_name' ], - raw: true, - }); + const { warehouseId, entryItems, receivingDetails, receivingOrderMap } = params; // 收集所有 stock_id,批量查询商品信息 + const entryStockIds = [ ...new Set(entryItems.map(item => Number(item.stock_id)).filter(Boolean)) ]; const receivingSystemProductIds = [ ...new Set(receivingDetails.map(d => Number(d.system_product_id)).filter(Boolean)) ]; const allStockIds = [ ...new Set([ ...entryStockIds, ...receivingSystemProductIds ]) ]; const stockDetailMap = new Map(); if (allStockIds.length > 0) { const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(allStockIds, { warehouseId }); for (const detail of stockDetails) { - stockDetailMap.set(detail.id, detail); + stockDetailMap.set(Number(detail.id), detail); } } - // stock_id ↔ system_product_id 映射 - const stockIdToSystemProductId = new Map(); - const systemProductIdToEntryStockIds = new Map(); + // 仓库范围内有效的入库商品 stock_id(与原逻辑一致:仅匹配本仓库库存记录) + const validEntryStockIds = new Set(entryStockIds); if (entryStockIds.length > 0) { const swRows = await ctx.model.StockWarehouse.findAll({ where: { id: { [app.Sequelize.Op.in]: entryStockIds }, warehouse_id: warehouseId }, attributes: [ 'id' ], raw: true, }); + validEntryStockIds.clear(); for (const row of swRows) { - const stockId = Number(row.id); - stockIdToSystemProductId.set(stockId, stockId); - if (!systemProductIdToEntryStockIds.has(stockId)) { - systemProductIdToEntryStockIds.set(stockId, []); - } - systemProductIdToEntryStockIds.get(stockId).push(stockId); + validEntryStockIds.add(Number(row.id)); } } // 查询已分配量(限定本入库单的 entry_items,避免全局绑定干扰) - const receivingDetailIds = receivingDetails.map(d => d.id); - const entryItemIds = entryItems.map(ei => ei.id); + const receivingDetailIds = receivingDetails.map(d => Number(d.id)); + const entryItemIds = entryItems.map(ei => Number(ei.id)); const allocatedMap = new Map(); if (receivingDetailIds.length > 0 && entryItemIds.length > 0) { const bindingRows = await ctx.model.InboundDirectLog.findAll({ @@ -1902,42 +1889,67 @@ class EntryService extends Service { } } - // 构建对照视图:以入库单明细为主 + // 按 stock_id 索引收货明细,供合并匹配 + const detailsByStockId = new Map(); + for (const rd of receivingDetails) { + const stockId = Number(rd.system_product_id) || 0; + if (stockId <= 0) continue; + if (!detailsByStockId.has(stockId)) { + detailsByStockId.set(stockId, []); + } + detailsByStockId.get(stockId).push(rd); + } + + // 组装单个收货明细的来源信息 + const buildSource = rd => { + const rdStockDetail = (rd.system_product_id != null && stockDetailMap.get(Number(rd.system_product_id))) || null; + const allocated = allocatedMap.get(Number(rd.id)) || 0; + const quantity = Number(rd.actual_quantity) || 0; + return { + receiving_id: Number(rd.receiving_id), + receiving_number: (receivingOrderMap.get(Number(rd.receiving_id)) || {}).receiving_number || '', + receiving_detail_id: Number(rd.id), + receiving_product_code: (rdStockDetail && rdStockDetail.item_code) || '', + receiving_product_name: rd.product_name || (rdStockDetail && rdStockDetail.item_name) || '', + receiving_actual_quantity: quantity, + receiving_allocated: allocated, + receiving_available: Math.max(0, quantity - allocated), + }; + }; + + // 构建对照视图:以入库单明细为主,每个入库明细只输出一行 const comparison = []; const matchedReceivingDetailIds = new Set(); for (const entryItem of entryItems) { const stockId = Number(entryItem.stock_id || 0); - const systemProductId = stockIdToSystemProductId.get(stockId) || 0; const stockDetail = stockDetailMap.get(stockId) || null; - - const matchedReceiving = systemProductId > 0 - ? receivingDetails.filter(rd => Number(rd.system_product_id) === systemProductId) + const matchedDetails = stockId > 0 && validEntryStockIds.has(stockId) + ? (detailsByStockId.get(stockId) || []) : []; - if (matchedReceiving.length > 0) { - for (const rd of matchedReceiving) { - matchedReceivingDetailIds.add(rd.id); - const rdStockDetail = (rd.system_product_id != null && stockDetailMap.get(Number(rd.system_product_id))) || null; - const allocated = allocatedMap.get(Number(rd.id)) || 0; - const available = Math.max(0, (Number(rd.actual_quantity) || 0) - allocated); - comparison.push({ - entry_item_id: Number(entryItem.id), - stock_id: stockId, - warehouse_item_code: (stockDetail && stockDetail.item_code) || '', - warehouse_item_name: (stockDetail && stockDetail.item_name) || '', - warehouse_item_spec: (stockDetail && stockDetail.sku_property) || '', - entry_count: Number(entryItem.count) || 0, - entry_received: Number(entryItem.received_quantity) || 0, - receiving_detail_id: Number(rd.id), - receiving_product_code: (rdStockDetail && rdStockDetail.item_code) || '', - receiving_product_name: rd.product_name || (rdStockDetail && rdStockDetail.item_name) || '', - receiving_actual_quantity: Number(rd.actual_quantity) || 0, - receiving_allocated: allocated, - receiving_available: available, - match_status: 'matched', - }); + if (matchedDetails.length > 0) { + const sources = []; + for (const rd of matchedDetails) { + matchedReceivingDetailIds.add(Number(rd.id)); + sources.push(buildSource(rd)); } + const mergedQuantity = sources.reduce((sum, source) => sum + source.receiving_actual_quantity, 0); + const mergedAllocated = sources.reduce((sum, source) => sum + source.receiving_allocated, 0); + comparison.push({ + entry_item_id: Number(entryItem.id), + stock_id: stockId, + warehouse_item_code: (stockDetail && stockDetail.item_code) || '', + warehouse_item_name: (stockDetail && stockDetail.item_name) || '', + warehouse_item_spec: (stockDetail && stockDetail.sku_property) || '', + entry_count: Number(entryItem.count) || 0, + entry_received: Number(entryItem.received_quantity) || 0, + match_status: 'matched', + receiving_quantity: mergedQuantity, + receiving_allocated: mergedAllocated, + receiving_available: Math.max(0, mergedQuantity - mergedAllocated), + receiving_sources: sources, + }); } else { comparison.push({ entry_item_id: Number(entryItem.id), @@ -1947,69 +1959,52 @@ class EntryService extends Service { warehouse_item_spec: (stockDetail && stockDetail.sku_property) || '', entry_count: Number(entryItem.count) || 0, entry_received: Number(entryItem.received_quantity) || 0, - receiving_detail_id: null, - receiving_product_code: null, - receiving_product_name: null, - receiving_actual_quantity: null, - receiving_allocated: null, - receiving_available: null, match_status: 'entry_only', + receiving_quantity: 0, + receiving_allocated: 0, + receiving_available: 0, + receiving_sources: [], }); } } - // 收货单中多余的商品 - const receivingOnly = []; - const receivingStockMap = new Map(); + // 收货单中多余的商品(合并后仍未匹配到任何入库明细的收货明细,按商品合并) + const receivingOnlyMap = new Map(); for (const rd of receivingDetails) { - if (!matchedReceivingDetailIds.has(Number(rd.id))) { - const rdStockDetail = (rd.system_product_id != null && stockDetailMap.get(Number(rd.system_product_id))) || null; - const stockId = rd.system_product_id != null ? Number(rd.system_product_id) : null; - const qty = Number(rd.actual_quantity) || 0; - const name = rd.product_name || (rdStockDetail && rdStockDetail.item_name) || ''; - const allocated = allocatedMap.get(Number(rd.id)) || 0; - const available = Math.max(0, qty - allocated); - - if (stockId === null) { - receivingOnly.push({ - receiving_product_name: name, - receiving_actual_quantity: qty, - receiving_allocated: allocated, - receiving_available: available, - }); - } else if (receivingStockMap.has(stockId)) { - const existing = receivingStockMap.get(stockId); - existing.receiving_actual_quantity += qty; - existing.receiving_allocated += allocated; - existing.receiving_available += available; - if (!existing.receiving_product_name && name) { - existing.receiving_product_name = name; - } - } else { - receivingStockMap.set(stockId, { - receiving_product_name: name, - receiving_actual_quantity: qty, - receiving_allocated: allocated, - receiving_available: available, - }); + if (matchedReceivingDetailIds.has(Number(rd.id))) continue; + const stockId = rd.system_product_id != null ? Number(rd.system_product_id) : null; + const source = buildSource(rd); + const key = stockId === null || Number.isNaN(stockId) ? '__none__' : String(stockId); + if (receivingOnlyMap.has(key)) { + const existing = receivingOnlyMap.get(key); + existing.receiving_actual_quantity += source.receiving_actual_quantity; + existing.receiving_allocated += source.receiving_allocated; + existing.receiving_available = Math.max(0, existing.receiving_available + source.receiving_available); + if (!existing.receiving_product_name && source.receiving_product_name) { + existing.receiving_product_name = source.receiving_product_name; } + existing.receiving_sources.push(source); + } else { + receivingOnlyMap.set(key, { + stock_id: stockId, + receiving_product_code: source.receiving_product_code, + receiving_product_name: source.receiving_product_name, + receiving_actual_quantity: source.receiving_actual_quantity, + receiving_allocated: source.receiving_allocated, + receiving_available: source.receiving_available, + receiving_sources: [ source ], + }); } } - for (const item of receivingStockMap.values()) { - item.receiving_available = Math.max(0, item.receiving_available); - receivingOnly.push(item); - } + const receivingOnly = [ ...receivingOnlyMap.values() ]; // 汇总 const matchedItems = comparison.filter(c => c.match_status === 'matched').length; const entryOnlyItems = comparison.filter(c => c.match_status === 'entry_only').length; return { - receiving_id: receivingId, - receiving_number: receivingOrder.receiving_number, - status: 'matched', comparison, - receiving_only: receivingOnly, + receivingOnly, summary: { total_entry_items: entryItems.length, matched_items: matchedItems, diff --git a/methods/changes/system.json b/methods/changes/system.json index 65c557e..6464fae 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,20 @@ [ + { + "version": "2026.08.24-storage.entry-receivingCompare-merge", + "date": "2026-08-24", + "type": "fixed", + "summary": "storage.entry.receivingCompare 对比主体修正:多个收货单先合并明细,再与入库单做一次对照。原实现每个收货单各对照一遍,入库计划数量被重复展开多份,前端对比表格出现重复行。", + "methods": [ + "storage.entry.receivingCompare" + ], + "notes": [ + "app/service/systems/storage/entry.js receivingCompare 重写:批量校验收货单后合并全部有效收货单明细,新增 _buildMergedComparison(替代 _compareSingleReceiving)输出单一对照视图", + "出参结构调整:comparisons[](按收货单拆分)改为 comparison[](合并后逐行对照,每个入库明细仅一行)+ receiving_only[] + summary;matched 行新增 receiving_quantity/receiving_allocated/receiving_available(合并值)与 receiving_sources[](各收货单来源明细),entry_only 行对应数量为 0 且 receiving_sources 为空", + "total_summary.matched_count 语义调整为有效参与对比的收货单数(原为处理成功的对照数);无效收货单仍进入 errors[]", + "同步更新 methods/system.json 中 receivingCompare 的 response 结构说明" + ], + "module": "storage.entry" + }, { "version": "2026.08.23-returnUnpack.video-url-cdn-domain", "date": "2026-08-23", diff --git a/methods/system.json b/methods/system.json index 072429b..14fdc57 100644 --- a/methods/system.json +++ b/methods/system.json @@ -22646,7 +22646,7 @@ }, { "method": "storage.entry.receivingCompare", - "description": "入库单与收货单商品对照预览:给定入库单ID和收货单ID(支持多个),返回入库商品与收货商品的逐行对照视图,含匹配状态(matched/entry_only)和汇总统计。纯只读接口。", + "description": "入库单与收货单商品对照预览:给定入库单ID和收货单ID(支持多个),先将多个收货单的明细合并为一个整体,再与入库单商品做一次逐行对照,返回合并后的对照视图(每个入库明细仅一行,含匹配状态 matched/entry_only、合并收货数量与各收货单来源明细)及汇总统计。纯只读接口。", "isNeedAuth": false, "isNeedLogin": true, "headers": [], @@ -22687,66 +22687,102 @@ "description": "入库单号" }, { - "name": "comparisons", + "name": "comparison", "type": "array", "required": true, - "description": "各收货单对照结果列表", + "description": "合并后的逐行对照列表(多个收货单明细先合并,再与入库单对照;以入库单明细为主,每个入库明细仅一行)", "children": [ { - "name": "receiving_id", + "name": "entry_item_id", "type": "number", "required": true, - "description": "收货单ID" + "description": "入库单明细ID" }, { - "name": "receiving_number", + "name": "stock_id", + "type": "number", + "required": true, + "description": "库存商品ID(stock_warehouse.id)" + }, + { + "name": "warehouse_item_code", "type": "string", "required": true, - "description": "收货单号" + "description": "入库商品编码" }, { - "name": "status", + "name": "warehouse_item_name", "type": "string", "required": true, - "description": "对比状态:matched-匹配成功, error-校验失败" + "description": "入库商品名称" }, { - "name": "error_code", + "name": "warehouse_item_spec", "type": "string", - "required": false, - "description": "错误码(仅 status=error 时),如 RECEIVING_NOT_FOUND" + "required": true, + "description": "入库商品规格" }, { - "name": "error_message", + "name": "entry_count", + "type": "number", + "required": true, + "description": "计划数量" + }, + { + "name": "entry_received", + "type": "number", + "required": true, + "description": "入库单已收数量" + }, + { + "name": "match_status", "type": "string", - "required": false, - "description": "错误信息(仅 status=error 时)" + "required": true, + "description": "匹配状态:matched-已匹配, entry_only-仅入库(无收货商品)" }, { - "name": "comparison", + "name": "receiving_quantity", + "type": "number", + "required": true, + "description": "合并后收货实际数量(所有收货单该商品明细数量之和,entry_only 时为 0)" + }, + { + "name": "receiving_allocated", + "type": "number", + "required": true, + "description": "合并后已分配数量" + }, + { + "name": "receiving_available", + "type": "number", + "required": true, + "description": "合并后可再用量(收货实际-已分配)" + }, + { + "name": "receiving_sources", "type": "array", - "required": false, - "description": "逐行对照列表(仅 status=matched 时),每项含 entry_item_id/stock_id/warehouse_item_code/warehouse_item_name/warehouse_item_spec/entry_count/entry_received/receiving_detail_id/receiving_product_code/receiving_product_name/receiving_actual_quantity/receiving_allocated/receiving_available/match_status" - }, - { - "name": "receiving_only", - "type": "array", - "required": false, - "description": "仅收货单有的商品列表(仅 status=matched 时),每项含 receiving_detail_id/receiving_product_code/receiving_product_name/receiving_actual_quantity/receiving_allocated/receiving_available" - }, - { - "name": "summary", - "type": "object", - "required": false, - "description": "该收货单的汇总统计(仅 status=matched 时),含 total_entry_items/matched_items/entry_only_items/receiving_only_items" + "required": true, + "description": "收货来源明细列表(matched 时非空),每项含 receiving_id/receiving_number/receiving_detail_id/receiving_product_code/receiving_product_name/receiving_actual_quantity/receiving_allocated/receiving_available" } ] }, + { + "name": "receiving_only", + "type": "array", + "required": true, + "description": "仅收货单有的商品列表(合并后仍未匹配到任何入库明细,按商品合并),每项含 stock_id/receiving_product_code/receiving_product_name/receiving_actual_quantity/receiving_allocated/receiving_available/receiving_sources" + }, + { + "name": "summary", + "type": "object", + "required": true, + "description": "合并对照汇总统计,含 total_entry_items/matched_items/entry_only_items/receiving_only_items" + }, { "name": "errors", "type": "array", "required": false, - "description": "校验失败的收货单列表(status=error 的记录也会在此汇总)" + "description": "校验失败的收货单列表(status=error 的记录)" }, { "name": "total_summary", @@ -22762,7 +22798,7 @@ { "name": "matched_count", "type": "number", - "description": "匹配成功的收货单数" + "description": "有效参与对比的收货单数" }, { "name": "error_count", From c047dccd2e0a9db7f5df881a157ad4860db75278 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 24 Aug 2026 18:47:44 +0800 Subject: [PATCH 268/550] =?UTF-8?q?docs(returnUnpack):=20=E6=8B=86?= =?UTF-8?q?=E5=8C=85=E7=99=BB=E8=AE=B0=E5=95=86=E5=93=81=E8=AF=86=E5=88=AB?= =?UTF-8?q?=E5=8F=82=E6=95=B0=E8=AF=B4=E6=98=8E=E6=9B=B4=E6=96=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/systemMethods/returnUnpack.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/service/systemMethods/returnUnpack.js b/app/service/systemMethods/returnUnpack.js index c002891..38dbcaf 100644 --- a/app/service/systemMethods/returnUnpack.js +++ b/app/service/systemMethods/returnUnpack.js @@ -65,8 +65,8 @@ class ReturnUnpackMethodService extends MainService { * * @param {Object} data 请求体。 * @param {number} data.id 拆包单ID。 - * @param {number} [data.stock_id] 系统商品ID(wms_stock_warehouse.id)。 - * @param {string} [data.barcode] 扫描条码(stock_id 为空时按条码反查商品)。 + * @param {number} [data.stock_id] 系统商品ID(wms_stock_warehouse.id),为空时按未知商品登记(is_recognized=0)。 + * @param {string} [data.barcode] 扫描条码(仅作记录,不参与商品匹配)。 * @param {number} [data.quantity] 数量。 * @param {string} [data.product_status] 产品状态 normal/damaged。 * @param {string} [data.remark] 备注。 From 87fad39ba2f34d3a772ecebfdd44e6424b7368d2 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Tue, 25 Aug 2026 01:07:22 +0800 Subject: [PATCH 269/550] =?UTF-8?q?feat(returnUnpack):=20=E6=96=B0?= =?UTF-8?q?=E5=A2=9E=20forceRecord=20=E5=BC=BA=E5=88=B6=E9=87=8D=E6=96=B0?= =?UTF-8?q?=E5=BD=95=E5=88=B6=E6=8B=86=E5=8C=85=E8=A7=86=E9=A2=91=E5=B9=B6?= =?UTF-8?q?=E6=8E=A8=E9=80=81=E6=89=93=E5=8D=B0=E6=9C=8D=E5=8A=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/systemMethods/returnUnpack.js | 13 +++ app/service/systems/return_unpack.js | 71 ++++++++++++++++ ...d-return-unpack-force-record-permission.js | 82 +++++++++++++++++++ methods/changes/system.json | 16 ++++ methods/system.json | 82 +++++++++++++++++++ 5 files changed, 264 insertions(+) create mode 100644 database/migrations/20260825120000-add-return-unpack-force-record-permission.js diff --git a/app/service/systemMethods/returnUnpack.js b/app/service/systemMethods/returnUnpack.js index 38dbcaf..20c6c0e 100644 --- a/app/service/systemMethods/returnUnpack.js +++ b/app/service/systemMethods/returnUnpack.js @@ -138,6 +138,19 @@ class ReturnUnpackMethodService extends MainService { return this._call(() => this.service.systems.returnUnpack.submit({ id }), '提交确认失败'); } + /** + * 强制重新录制拆包视频(改,参考 order.packing.forceRecord)。 + * 校验仓库录制电脑在线后重置视频状态并推送打印服务 /record/force 触发重新录制。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 拆包单ID。 + * @return {Promise} 统一 success 包装。 + */ + async forceRecord(data = {}) { + const { id } = data; + return this._call(() => this.service.systems.returnUnpack.forceRecord({ id }), '强制录制失败'); + } + /** * 分页查询拆包单列表(查,仓库隔离自动注入)。 * diff --git a/app/service/systems/return_unpack.js b/app/service/systems/return_unpack.js index 7ba4076..b5d1593 100644 --- a/app/service/systems/return_unpack.js +++ b/app/service/systems/return_unpack.js @@ -548,6 +548,77 @@ class ReturnUnpackService extends Service { }; } + /** + * 强制重新录制拆包视频:重置视频记录状态并推送打印服务强制录制。 + * 参考 order.packing.forceRecord:校验仓库录制电脑在线后,将视频记录重置为 + * created 并清空 video_url,再向打印服务 /record/force 推送 { unpack_id } 触发重新录制。 + * + * @param {Object} params 参数。 + * @param {number} params.id 拆包单ID。 + * @return {Promise} 推送结果 { unpack_id, computer_id, print_service_url, print_service_request, print_service_response }。 + */ + async forceRecord({ id }) { + const { ctx } = this; + + // 拆包单存在性 + 仓库隔离校验(不存在 404 / 跨仓库 403) + const unpack = await this._findByIdChecked(id); + const warehouseId = Number(unpack.warehouse_id || 0); + const unpackId = Number(id); + + // 1. 查找仓库的录制电脑 + const recordingComputer = await ctx.model.PrintComputer.findOne({ + where: { warehouse_id: warehouseId, is_recording: true, deleted_at: null }, + raw: true, + }); + if (!recordingComputer) { + throw this.createBusinessError('该仓库无录制电脑,无法强制录制', 400); + } + + // 2. 检查录制电脑是否在线(与 order_packing 相同的 Redis 在线键) + const redisPrinter = ctx.app.redis.get('printer'); + const onlineKey = `warehouse:${warehouseId}:printer:${recordingComputer.id}`; + const onlineInfo = await redisPrinter.get(onlineKey); + if (!onlineInfo) { + throw this.createBusinessError('该仓库录制电脑不在线,无法强制录制', 400); + } + + // 3. 重置视频记录状态为 created,触发重新录制 + await ctx.model.ReturnUnpackVideo.update( + { status: 'created', video_url: '' }, + { where: { unpack_id: unpackId, deleted_at: null } } + ); + + // 4. 通知打印服务推送强制录制任务 + const printServiceUrl = ctx.app.config.printService.url; + const requestData = { unpack_id: unpackId }; + let printServiceResponse = null; + try { + const res = await ctx.curl(`${printServiceUrl}/record/force`, { + method: 'POST', + contentType: 'json', + data: requestData, + dataType: 'json', + timeout: 10000, + }); + printServiceResponse = { + status: res.status, + headers: res.headers, + data: res.data, + }; + } catch (err) { + ctx.logger.warn(`[returnUnpack.forceRecord] 通知打印服务强制录制 unpack_id=${unpackId} 失败: ${err.message}`); + throw this.createBusinessError(`通知打印服务失败: ${err.message}`, 500); + } + + return { + unpack_id: unpackId, + computer_id: recordingComputer.id, + print_service_url: `${printServiceUrl}/record/force`, + print_service_request: requestData, + print_service_response: printServiceResponse, + }; + } + /** * 分页查询拆包单列表(仓库隔离由方法层注入 warehouse_id)。 * diff --git a/database/migrations/20260825120000-add-return-unpack-force-record-permission.js b/database/migrations/20260825120000-add-return-unpack-force-record-permission.js new file mode 100644 index 0000000..05f6fe6 --- /dev/null +++ b/database/migrations/20260825120000-add-return-unpack-force-record-permission.js @@ -0,0 +1,82 @@ +'use strict'; + +/** + * 退回拆包强制录制权限迁移(returnUnpack.forceRecord)。 + * + * 权限明细: + * 562 — returnUnpack.forceRecord API:退回拆包强制录制 + * + * 角色授权(与作业类 540-545 一致): + * → 仓库组-员工(27) → 仓库组-主管(26)(仓库员工及以上) + * 经理(8)/仓库管理员(2)/超级管理员(7) 已持有 * 通配符,自动拥有所有权限,无需处理 + * + * 幂等:INSERT IGNORE 创建权限记录;角色权限数组追加后去重排序,已存在跳过。 + */ + +const TABLE = 'wms_permission'; +const ROLE_TABLE = 'wms_role'; +const COLUMNS = 'id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at'; + +/** 权限ID → 授权角色ID列表(不含通配符角色) */ +const PERMISSION_ROLES = { + 562: [ 27, 26 ], +}; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + // ── 1. 创建 API 权限记录(固定 ID 562)── + await queryInterface.sequelize.query( + `INSERT IGNORE INTO \`${TABLE}\` (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`, + { replacements: [ 562, 'returnUnpack.forceRecord', null, 'returnUnpack.forceRecord', null, 'API:退回拆包强制录制', null, 0, 0, null, 'api', 0, 1 ] } + ); + + // ── 2. 角色授权注入 ── + for (const permId of Object.keys(PERMISSION_ROLES).map(Number)) { + for (const roleId of PERMISSION_ROLES[permId]) { + const rows = await queryInterface.sequelize.query( + `SELECT id, permissions FROM \`${ROLE_TABLE}\` WHERE id = ?`, + { replacements: [ roleId ], type: queryInterface.sequelize.QueryTypes.SELECT } + ); + const record = Array.isArray(rows) ? rows[0] : null; + if (!record) { + continue; + } + + // 通配符角色跳过 + if (record.permissions === '*') { + continue; + } + + let perms; + try { + perms = JSON.parse(record.permissions || '[]'); + } catch (err) { + continue; + } + if (!Array.isArray(perms)) { + continue; + } + + if (perms.includes(permId)) { + continue; + } + + perms.push(permId); + perms.sort((a, b) => a - b); + + await queryInterface.sequelize.query( + `UPDATE \`${ROLE_TABLE}\` SET permissions = ? WHERE id = ?`, + { replacements: [ JSON.stringify(perms), roleId ] } + ); + } + } + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + await queryInterface.sequelize.query( + `DELETE FROM \`${TABLE}\` WHERE id = 562` + ); + }, +}; diff --git a/methods/changes/system.json b/methods/changes/system.json index 6464fae..dcb572f 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,20 @@ [ + { + "version": "2026.08.25-returnUnpack.forceRecord", + "date": "2026-08-25", + "type": "added", + "summary": "新增 returnUnpack.forceRecord:强制重新录制拆包视频。参考 order.packing.forceRecord,入参 id(拆包单ID);校验仓库录制电脑(wms_print_computer is_recording=true)在线后,将 wms_return_unpack_video 视频记录重置为 created 并清空 video_url,再向打印服务 /record/force 推送 { unpack_id } 触发重新录制。", + "methods": [ + "returnUnpack.forceRecord" + ], + "notes": [ + "app/service/systems/return_unpack.js 新增 forceRecord:_findByIdChecked 仓库隔离校验(不存在 404 / 跨仓库 403)→ 查询录制电脑(无则 400)→ Redis 在线键 warehouse:{warehouseId}:printer:{computerId} 校验在线(不在线 400)→ 重置视频状态为 created 并清空 video_url → POST {printService.url}/record/force 推送 { unpack_id }(失败抛 500 业务错误)", + "app/service/systemMethods/returnUnpack.js 新增 forceRecord 包装方法(与 submit 同层,走 _call 统一错误包装)", + "database/migrations/20260825120000-add-return-unpack-force-record-permission.js 新增权限记录 562(returnUnpack.forceRecord,API:退回拆包强制录制),授权角色与作业类 540-545 一致:仓库组-员工(27)/仓库组-主管(26)", + "同步更新 methods/system.json 中 returnUnpack.forceRecord 的接口文档" + ], + "module": "returnUnpack" + }, { "version": "2026.08.24-storage.entry-receivingCompare-merge", "date": "2026-08-24", diff --git a/methods/system.json b/methods/system.json index 14fdc57..e78c540 100644 --- a/methods/system.json +++ b/methods/system.json @@ -36963,6 +36963,88 @@ } ] }, + { + "method": "returnUnpack.forceRecord", + "description": "强制重新录制拆包视频。校验仓库录制电脑在线后,将视频记录(wms_return_unpack_video)重置为 created 并清空 video_url,再向打印服务 /record/force 推送 { unpack_id } 触发重新录制(参考 order.packing.forceRecord)。仓库隔离校验(仅本仓库拆包单)。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "id", + "type": "integer", + "required": true, + "source": "body", + "description": "拆包单ID" + } + ], + "response": [ + { + "name": "unpack_id", + "type": "integer", + "required": true, + "description": "拆包单ID" + }, + { + "name": "computer_id", + "type": "integer", + "required": true, + "description": "录制电脑ID(wms_print_computer.id,is_recording=true)" + }, + { + "name": "print_service_url", + "type": "string", + "required": true, + "description": "打印服务强制录制接口地址(POST {printService.url}/record/force)" + }, + { + "name": "print_service_request", + "type": "object", + "required": true, + "description": "推送给打印服务的请求体({ unpack_id })" + }, + { + "name": "print_service_response", + "type": "object", + "required": false, + "description": "打印服务响应(status/headers/data)" + } + ], + "errors": [ + { + "code": "400", + "message": "id 必填且必须为正整数" + }, + { + "code": "400", + "message": "该仓库无录制电脑,无法强制录制" + }, + { + "code": "400", + "message": "该仓库录制电脑不在线,无法强制录制" + }, + { + "code": "401", + "message": "未提供有效的认证令牌" + }, + { + "code": "403", + "message": "无权访问该拆包单" + }, + { + "code": "403", + "message": "无权访问该接口" + }, + { + "code": "404", + "message": "拆包单不存在" + }, + { + "code": "500", + "message": "通知打印服务失败" + } + ] + }, { "method": "returnUnpack.list", "description": "拆包单分页列表(主表)。仓库隔离:warehouse_id 由服务端自动注入 ctx.user.store_id,禁止前端传入。支持拆包单号/运单号模糊、日期/时间范围、状态、拆包人员、退回收到单、货主、原运单/原订单等筛选。", From 51f6b27d6a7751352f8af1b790c8a5b408364b83 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Tue, 25 Aug 2026 13:09:53 +0800 Subject: [PATCH 270/550] =?UTF-8?q?fix(qimen):=20itemId=20=E9=9D=9E?= =?UTF-8?q?=E4=B8=BB=E9=94=AE=E6=97=B6=E9=99=8D=E7=BA=A7=E6=8C=89=20item?= =?UTF-8?q?=5Fcode=20=E6=9F=A5=E6=89=BE=E5=95=86=E5=93=81=EF=BC=8C?= =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E5=A5=87=E9=97=A8=E6=8E=A8=E5=8D=95=E8=AF=AF?= =?UTF-8?q?=E6=8A=A5=E6=9C=AA=E5=90=8C=E6=AD=A5=E6=8E=A8=E9=80=81=E5=88=B0?= =?UTF-8?q?=E4=BB=93=E5=BA=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/qimenMethods/stockout.js | 20 ++- app/service/systems/delivery_order.js | 42 +++-- app/service/systems/entry_order.js | 15 +- ...ivery_order.addOrderLines.fallback.test.js | 168 ++++++++++++++++++ 4 files changed, 222 insertions(+), 23 deletions(-) create mode 100644 test/app/service/systems/delivery_order.addOrderLines.fallback.test.js diff --git a/app/service/qimenMethods/stockout.js b/app/service/qimenMethods/stockout.js index ff2875a..6c22db8 100644 --- a/app/service/qimenMethods/stockout.js +++ b/app/service/qimenMethods/stockout.js @@ -45,13 +45,23 @@ class stockoutServer extends MainService { const items = []; for (let i = 0; i < orderLine.length; i++) { const line = orderLine[i]; - const wmsStock = await app.model.StockStore.findByPk(line.itemId); + let wmsStock = await app.model.StockStore.findByPk(line.itemId); // 校验 StockStore 记录的 store_id 与当前上下文一致,防止跨货主越权 if (wmsStock && Number(wmsStock.store_id) !== Number(this.storeId)) { - errors.push( - `SKU${line.itemId}商品《${line.itemName}》编码《${line.itemCode}》\n未同步推送到仓库` - ); - continue; + wmsStock = null; + } + // 外部渠道(奇门)itemId 可能是平台商品标识或条码而非 WMS 主键, + // 主键查不到或跨货主时降级按 item_code + 仓库货主维度查找 + if (!wmsStock && line.itemCode) { + const stockWhere = { + item_code: line.itemCode, + warehouse_id: warehouseId, + store_id: storeId, + }; + if (this.appKey) { + stockWhere.app_key = this.appKey; + } + wmsStock = await app.model.StockStore.findOne({ where: stockWhere }); } if (!wmsStock) { errors.push( diff --git a/app/service/systems/delivery_order.js b/app/service/systems/delivery_order.js index 2985866..2d286ba 100644 --- a/app/service/systems/delivery_order.js +++ b/app/service/systems/delivery_order.js @@ -1497,22 +1497,34 @@ class DeliveryOrderService extends Service { errors.push(`商品《${line.itemName}》编码《${line.itemCode}》\n库存归属货主(store_id=${stockWarehouseRecord.store_id})与当前货主(store_id=${storeId})不一致,无法创建订单`); continue; } - } else if (!line.itemId) { - // 查找唯一键(appKey 为空时不作为条件,兼容内部手动建单场景) - const stockWhere = { - item_code: line.itemCode, - warehouse_id: warehouseId, - store_id: storeId, - }; - if (appKey) { - stockWhere.app_key = appKey; - } - wms_stock = await app.model.StockStore.findOne({ where: stockWhere, transaction }); } else { - wms_stock = await app.model.StockStore.findByPk(line.itemId, { transaction }); - // 校验 StockStore 记录的 store_id 与当前上下文一致,防止跨货主越权 - if (wms_stock && Number(wms_stock.store_id) !== Number(storeId)) { - wms_stock = null; + // 查找唯一键(appKey 为空时不作为条件,兼容内部手动建单场景) + const findByItemCode = async () => { + if (!line.itemCode) return null; + const stockWhere = { + item_code: line.itemCode, + warehouse_id: warehouseId, + store_id: storeId, + }; + if (appKey) { + stockWhere.app_key = appKey; + } + return await app.model.StockStore.findOne({ where: stockWhere, transaction }); + }; + + if (!line.itemId) { + wms_stock = await findByItemCode(); + } else { + wms_stock = await app.model.StockStore.findByPk(line.itemId, { transaction }); + // 校验 StockStore 记录的 store_id 与当前上下文一致,防止跨货主越权 + if (wms_stock && Number(wms_stock.store_id) !== Number(storeId)) { + wms_stock = null; + } + // 外部渠道(奇门/开放平台)itemId 可能是平台商品标识或条码而非 WMS 主键, + // 主键查不到或跨货主时降级按 item_code 查找,避免误报“未同步推送到仓库” + if (!wms_stock) { + wms_stock = await findByItemCode(); + } } } diff --git a/app/service/systems/entry_order.js b/app/service/systems/entry_order.js index a7fb0ac..1f2db70 100644 --- a/app/service/systems/entry_order.js +++ b/app/service/systems/entry_order.js @@ -32,20 +32,29 @@ class entryOrderService extends Service { for (let i = 0; i < orderLine.length; i++) { let wms_stock = null; // ERP不处理WMS的外部商品编码 - if (!orderLine[i].itemId) { - // 查找唯一键 - wms_stock = await app.model.StockStore.findOne({ where: { + // 查找唯一键 + const findByItemCode = async () => { + if (!orderLine[i].itemCode) return null; + return await app.model.StockStore.findOne({ where: { item_code: orderLine[i].itemCode, app_key: appKey, warehouse_id: warehouseId, store_id: storeId, }, transaction }); + }; + if (!orderLine[i].itemId) { + wms_stock = await findByItemCode(); } else { wms_stock = await app.model.StockStore.findByPk(orderLine[i].itemId, { transaction }); // 校验 StockStore 记录的 store_id 与当前上下文一致,防止跨货主越权 if (wms_stock && Number(wms_stock.store_id) !== Number(storeId)) { wms_stock = null; } + // 外部渠道 itemId 可能是平台商品标识或条码而非 WMS 主键, + // 主键查不到或跨货主时降级按 item_code 查找,避免误报“未同步推送到仓库” + if (!wms_stock) { + wms_stock = await findByItemCode(); + } } if (!wms_stock) { errors.push(`SKU${orderLine[i].itemId}商品《${orderLine[i].itemName}》编码《${orderLine[i].itemCode}》\n未同步推送到仓库`); diff --git a/test/app/service/systems/delivery_order.addOrderLines.fallback.test.js b/test/app/service/systems/delivery_order.addOrderLines.fallback.test.js new file mode 100644 index 0000000..e27d1b1 --- /dev/null +++ b/test/app/service/systems/delivery_order.addOrderLines.fallback.test.js @@ -0,0 +1,168 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const DeliveryOrderService = require('../../../../app/service/systems/delivery_order'); + +/** + * 构建 addOrderLines 测试桩。 + * + * @param {Object} options 可配置项。 + * @param {Object} options.stockStoreRecords StockStore 桩返回值:{ byPk, byCode }。 + * @return {Object} 服务实例与调用记录。 + */ +function createHarness({ stockStoreRecords = {} } = {}) { + const findByPkCalls = []; + const findOneCalls = []; + const bulkCreateCalls = []; + + const appLogger = { + debug() {}, + info() {}, + warn() {}, + error() {}, + }; + + const app = { + logger: appLogger, + getCacheAsync: async () => null, + setCacheAsync: async () => {}, + delCacheAsync: async () => {}, + }; + + const ctx = { + app, + logger: appLogger, + model: { + OrderItemsFactory: { + async getCurrentModel() { + return { + async bulkCreate(lineData) { + bulkCreateCalls.push(lineData); + return lineData; + }, + }; + }, + }, + StockStore: { + async findByPk(itemId) { + findByPkCalls.push(String(itemId)); + return stockStoreRecords.byPk || null; + }, + async findOne({ where } = {}) { + findOneCalls.push(where); + return stockStoreRecords.byCode || null; + }, + }, + StockWarehouse: { + async findAll() { + return []; + }, + }, + }, + service: { + systems: { + stockStore: { + async getStoreWarehousePolicyByStoreAndWarehouse() { + return {}; + }, + async lockItemStorages() { + return { success: true }; + }, + }, + }, + }, + }; + + app.model = ctx.model; + const service = new DeliveryOrderService(ctx); + + return { service, findByPkCalls, findOneCalls, bulkCreateCalls }; +} + +const WMS_STOCK = { + id: 1001076, + stock_id: 154103, + store_id: 1000186, + warehouse_id: 1000028, + item_code: '6934864204356', + item_name: '黑妹炭丝护龈牙刷', + goods_code: 'A.16.006.000001', + barcode: '6934864204356', + brand_name: null, + sku_property: null, + stock_unit: null, + category_id: 0, + category_name: null, + item_type: 'ZC', + retail_price: 0, + gross_weight: 0, + net_weight: 0, + length: 0, + width: 0, + height: 0, + volume: 0, +}; + +const INFO = { warehouseId: 1000028, appKey: '21226717', storeId: 1000186 }; +const LINE = { + itemId: '6934864204356', + itemCode: '6934864204356', + itemName: '', + planQty: 12, + orderLineNo: '0', +}; + +describe('test/app/service/systems/delivery_order.addOrderLines.fallback.test.js', () => { + it('itemId 非空但非 WMS 主键时,降级按 item_code 查到商品并成功创建明细', async () => { + const { service, findByPkCalls, findOneCalls, bulkCreateCalls } = createHarness({ + stockStoreRecords: { byCode: WMS_STOCK }, + }); + + const result = await service.addOrderLines([ LINE ], 7788, INFO, {}); + + assert.equal(result.stock_count, 1); + assert.ok(result.items_str.includes('154103+12'), `items_str=${result.items_str}`); + assert.deepEqual(findByPkCalls, [ '6934864204356' ]); + assert.equal(findOneCalls.length, 1); + assert.equal(findOneCalls[0].item_code, '6934864204356'); + assert.equal(findOneCalls[0].warehouse_id, 1000028); + assert.equal(findOneCalls[0].store_id, 1000186); + assert.equal(findOneCalls[0].app_key, '21226717'); + assert.equal(bulkCreateCalls.length, 1); + assert.equal(bulkCreateCalls[0][0].item_id, 1001076); + }); + + it('itemId 对应主键存在且同货主时,直接按主键命中,不做 item_code 降级查询', async () => { + const { service, findOneCalls } = createHarness({ + stockStoreRecords: { byPk: WMS_STOCK }, + }); + + const result = await service.addOrderLines([ LINE ], 7788, INFO, {}); + + assert.equal(result.stock_count, 1); + assert.equal(findOneCalls.length, 0); + }); + + it('主键记录跨货主且 item_code 也查不到时,报未同步推送到仓库', async () => { + const { service } = createHarness({ + stockStoreRecords: { byPk: { ...WMS_STOCK, store_id: 999999 } }, + }); + + await assert.rejects( + () => service.addOrderLines([ LINE ], 7788, INFO, {}), + /未同步推送到仓库/ + ); + }); + + it('itemId 为空时,仅按 item_code 查询(既有行为回归)', async () => { + const { service, findByPkCalls, findOneCalls } = createHarness({ + stockStoreRecords: { byCode: WMS_STOCK }, + }); + + const result = await service.addOrderLines([{ ...LINE, itemId: '' }], 7788, INFO, {}); + + assert.equal(result.stock_count, 1); + assert.equal(findByPkCalls.length, 0); + assert.equal(findOneCalls.length, 1); + }); +}); From c0331cd68fbf738b51e5283ed5298b0945a55272 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Tue, 25 Aug 2026 13:09:54 +0800 Subject: [PATCH 271/550] =?UTF-8?q?fix(storeWarehouse):=20=E7=AD=96?= =?UTF-8?q?=E7=95=A5=E5=8F=98=E6=9B=B4=E5=90=8E=E5=86=99=E5=85=A5=E5=B9=B6?= =?UTF-8?q?=E5=A4=B1=E6=95=88=E7=AD=BE=E7=BA=A6=E7=AD=96=E7=95=A5=E7=BC=93?= =?UTF-8?q?=E5=AD=98=EF=BC=8C=E9=81=BF=E5=85=8D=E5=A5=87=E9=97=A8=E6=8E=A8?= =?UTF-8?q?=E5=8D=95=E8=AF=BB=E5=8F=96=E6=97=A7=E8=B6=85=E5=8D=96=E5=BF=AB?= =?UTF-8?q?=E7=85=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/systems/store_warehouse.js | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/app/service/systems/store_warehouse.js b/app/service/systems/store_warehouse.js index ea24806..7cba590 100644 --- a/app/service/systems/store_warehouse.js +++ b/app/service/systems/store_warehouse.js @@ -407,12 +407,13 @@ class SettingStoreWarehouseService extends Service { transaction, } ); - return; + } else { + await this.app.setCacheAsync(this.getPolicyConfigCacheKey(normalizedId), policyConfig, 86400 * 30); } - await this.app.setCacheAsync(this.getPolicyConfigCacheKey(normalizedId), policyConfig, 86400 * 30); - - // 清除签约策略缓存(sw_policy:{storeId}:{warehouseId}) + // 清除签约策略缓存(sw_policy:{storeId}:{warehouseId}): + // 该缓存内嵌 policy_config 快照与 allowOversell 判定,策略变更(如开启允许超卖)后必须失效, + // 否则奇门推送订单会继续读取旧快照,导致超卖开关生效前仍提示库存不足。 const relation = await this.ctx.model.StoreWarehouse.findByPk(normalizedId, { attributes: [ 'store_id', 'warehouse_id' ], raw: true, From b07d7bca33a4ffc26709ba0a103ca6657379b7f1 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Tue, 25 Aug 2026 23:40:42 +0800 Subject: [PATCH 272/550] =?UTF-8?q?feat(stockout):=20=E5=87=BA=E5=BA=93?= =?UTF-8?q?=E5=8D=95=E8=BD=AC=E8=AE=A2=E5=8D=95=E5=85=A8=E9=93=BE=E8=B7=AF?= =?UTF-8?q?=EF=BC=88receiverInfo=20=E8=90=BD=E5=BA=93=E3=80=81=E5=87=BA?= =?UTF-8?q?=E5=BA=93=E5=8D=95=E9=BB=98=E8=AE=A4=E5=BF=AB=E9=80=92=E3=80=81?= =?UTF-8?q?updateInfo=E3=80=81TRANSFERRED=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - toOrder:create_channel=STOCKOUT、库存锁转移、收货必填校验、同快递/兜底平台、转单后置 TRANSFERRED(禁止一键出库) - stockout.create:解析 receiverInfo 13 字段落库,快递兜底改用出库单默认快递(stockout_default_express_code,默认 ZT 自提) - 新增 storage.stockout.updateInfo:收货/地址/快递/平台修改,仅 CREATED/PENDING,收货缺失禁止提交 - 迁移:wms_order_stockout 新增 receiver_* 13 列、order_status 增 TRANSFERRED、source_platform 两列 - 附带:storeWarehouse.createUser、奇门取消订单配送表幂等、express_platform Uint64 打包、方法与变更文档同步 --- AI_METHOD_ROUTING.md | 410 +++++++++++++++--- app/model/order_stockout.js | 84 +++- app/model/store_warehouse.js | 12 + app/service/qimenMethods/order.js | 25 ++ app/service/qimenMethods/stockout.js | 88 ++++ app/service/systemMethods/order/base.js | 1 + app/service/systemMethods/storage/delivery.js | 9 +- app/service/systemMethods/storage/stockout.js | 409 ++++++++++++++++- .../systemMethods/storeWarehouse/store.js | 41 +- app/service/systems/express_platform.js | 68 ++- app/service/systems/store_warehouse.js | 161 +++++++ ...add-receiver-info-to-wms-order-stockout.js | 66 +++ ...atus-and-platform-to-wms-order-stockout.js | 68 +++ methods/changes/qimen.json | 46 ++ methods/changes/system.json | 83 ++++ methods/system.json | 297 ++++++++++++- 16 files changed, 1775 insertions(+), 93 deletions(-) create mode 100644 database/migrations/20260825170000-add-receiver-info-to-wms-order-stockout.js create mode 100644 database/migrations/20260825180000-add-transferred-status-and-platform-to-wms-order-stockout.js diff --git a/AI_METHOD_ROUTING.md b/AI_METHOD_ROUTING.md index a3d6db6..75ff282 100644 --- a/AI_METHOD_ROUTING.md +++ b/AI_METHOD_ROUTING.md @@ -114,19 +114,61 @@ rg "class .*Service|module.exports" app/service/qimenMethods - 临时清单输出:temp/tmp-service-method-inventory.md -自动生成时间: 2026-03-22T15:27:37.958Z +自动生成时间: 2026-08-25T06:27:16.894Z 扫描范围: app/service/**/*.js -文件数: 50 +文件数: 193 - app/service/api.js (1) - callMethod -- app/service/apiMethods/test.js (4) - - entryorderConfirm, playbackRequest, fibonacci, fibonacciRecursive +- app/service/apiMethods/print.js (5) + - getPrinterRedis, normalizeBindValue, getEmployeePermissions, getBindInfo, bindByTempCode +- app/service/apiMethods/test.js (3) + - playbackRequest, fibonacci, fibonacciRecursive +- app/service/apiMethods/user.js (2) + - getUserByTempCode, bindAccountByTempCode - app/service/dispatcher.js (3) - buildMap, getMethodMap, invoke -- app/service/main.js (11) - - success, fail, normalizeDate, setInfo, getInfo, findQimenAppWithContract, queryFromDatabase, checkAuth, checkApiPermission, setUserContext, systemInit +- app/service/im.js (3) + - ping, ssoCodeToId, getStoreEmployees +- app/service/inbox/ai.js (3) + - callDeepSeek, getConversationHistory, processWithAI +- app/service/inbox/functions.js (5) + - registerBuiltinFunctions, register, callFunction, _getRecordingComputerId, _buildVideoUrl +- app/service/inbox/groups.js (4) + - resolveActiveGroups, isFunctionAvailable, getFunctionList, buildFunctionListText +- app/service/inbox/index.js (5) + - list, detail, thread, reply, stats +- app/service/inbox/message.js (7) + - list, _normalizeIds, _normalizeStrings, detail, thread, stats, retry +- app/service/inbox/processor.js (15) + - _loadGroupInfo, isStaleMessage, process, handleApiMessage, tryBindGroup, writeOutboundReply, isBlocked, invalidateBlockCache, getApiAppCallbackConfig, getApiAppCallbackUrl, pushSystemNotification, extractWarehouseId, extractStoreId, getWarehouseIdFromContext, getStoreIdFromContext +- app/service/inbox/receiver.js (1) + - receive +- app/service/main.js (18) + - success, fail, normalizeDate, setInfo, getInfo, isPlainObject, normalizeWhereCondition, normalizeWhereParams, extractWhereValues, prepareWhereContext, findQimenAppWithContract, queryFromDatabase, checkAuth, checkApiPermission, extractApiPermissionState, collectApiPermissionValue, setUserContext, systemInit +- app/service/openapi.js (9) + - resolveOpenapiMethod, getOpenapiMethodService, resolveOpenapiContract, getInfo, dispatchOpenapiMethod, validateOpenapiParams, parseJsonBody, normalizeSignFields, processRequest +- app/service/openapi/callback.js (4) + - signCallback, sendWithRetry, sendByAppKey, logCallback +- app/service/openapi/callbackRegistry.js (0) + - +- app/service/openapiMethods/callback.js (2) + - resolveAppInfo, test +- app/service/openapiMethods/deliveryorder.js (2) + - query, create +- app/service/openapiMethods/entryorder.js (2) + - create, query +- app/service/openapiMethods/index.js (2) + - ping, health +- app/service/openapiMethods/inventory.js (1) + - query +- app/service/openapiMethods/order.js (2) + - cancel, releaseStockLockForCancel +- app/service/openapiMethods/ping.js (1) + - echo +- app/service/openapiMethods/singleitem.js (2) + - synchronize, query - app/service/pda.js (3) - callMethod, validateParams, saveLog - app/service/qimen.js (12) @@ -137,8 +179,8 @@ rg "class .*Service|module.exports" app/service/qimenMethods - create, query - app/service/qimenMethods/inventory.js (1) - query -- app/service/qimenMethods/order.js (2) - - cancel, pending +- app/service/qimenMethods/order.js (5) + - getInterceptExpressInfo, sendCancelInterceptNotice, cancel, releaseStorageLockForCancel, pending - app/service/qimenMethods/returnorder.js (2) - create, query - app/service/qimenMethods/singleitem.js (2) @@ -149,84 +191,322 @@ rg "class .*Service|module.exports" app/service/qimenMethods - heartbeat - app/service/system.js (4) - callMethod, validateParams, validateRequestContext, saveLog +- app/service/systemMethods/afterSale.js (22) + - workList, _resolveAfterSaleBlockRoleGroups, workCount, auditList, detail, create, _resolveRedundantFields, transfer, handleWorkOrder, batchSetPendingFeedback, batchClose, registerClaim, export, exportTaskProgress, generateAfterSaleNo, _getCurrentDatePart, _buildOperatorSnapshot, generateExportTaskId, normalizeExportTaskId, getExportTaskCacheKey, setExportTaskProgress, getExportTaskProgress +- app/service/systemMethods/apiApp.js (6) + - list, detail, create, update, delete, regenerateSecret +- app/service/systemMethods/camera.js (6) + - list, detail, create, update, setOsd, delete +- app/service/systemMethods/cameraServer.js (5) + - list, detail, create, update, delete +- app/service/systemMethods/comboGoods.js (5) + - list, create, update, delete, search - app/service/systemMethods/config.js (1) - list -- app/service/systemMethods/dashboard.js (6) - - storeStats, warehouseStats, hot_order_rank, express_ratio, platform_distribution, order_trend -- app/service/systemMethods/index.js (14) - - fastWhereTree, loadStores, getCOSUploadConfig, getImages, uploadSuccessNotify, ReferenceFile, getMessageDetail, getI18nMessage, putI18nCollect, extractModule, tryAutoTranslateNewKeys, searchSpace, searchSpaces, getExpressList -- app/service/systemMethods/order.js (11) - - getWarehouseId, getOrderModels, applyDateRange, buildWhere, parseDateTime, list, detail, listItems, stats, updateStatus, updateDeliveryTime -- app/service/systemMethods/print.js (3) - - send, sendToComputer, log +- app/service/systemMethods/dashboard.js (17) + - storeStats, storeSideStoreStats, queryWarehouseStats, mergeStoreStats, emptyStoreStats, warehouseStats, hot_order_rank, express_ratio, storeSideExpressRatio, queryWarehouseExpressRatio, mergeChartData, formatChartData, emptyChartData, platform_distribution, storeSidePlatformDistribution, queryWarehousePlatformDistribution, order_trend +- app/service/systemMethods/inbox.js (11) + - group, message, after_sales, bindCode, groupList, groupDisable, groupUpdate, groupReset, groupMessages, retry, reply +- app/service/systemMethods/index.js (55) + - fastWhereTree, loadStores, loadWarehouses, loadExpressInterfaces, getCOSUploadConfig, getImages, uploadSuccessNotify, recognizeLicensePlate, ReferenceFile, getMessageDetail, test, getI18nMessage, putI18nCollect, extractModule, tryAutoTranslateNewKeys, searchSpace, searchSpaces, listInterfaceTypes, getLocationTypeList, getQimenAppList, getExpressList, getExpressProductTypeList, getPlatformList, getPrintPlatformList, ensureShopPrintPlatformExists, buildShopPrintPlatformInclude, getShopList, requestPddWaybillSearch, requestPddStdTemplates, requestTbWaybillSearch, requestTbCainiaoStdTemplates, requestPolyStdTemplates, getShopExpressList, getCainiaoStfTemplates, normalizeTemplatePlatformCode, normalizeTemplateExpressCode, getExpressPlatformFieldName, getTemplateAllowedExpressCodeSet, filterPrintPlatformTemplateResponseData, getPrintPlatformTemplateCacheKey, requestPrintPlatformTemplateList, resolvePddTemplateWpCodeCandidates, requestPddTemplateSourceList, getPrintPlatformTemplateList, isPlatformOauthReservationDuplicateError, getPlatformOauthReservationCodePrefix, hasPlatformOauthReservationCodePrefix, normalizePlatformOauthReservationCode, generatePlatformOauthReservationCode, createPlatformOauthReservation, getPlatformOauthLink, listenPlatformOauthBind, loginToIm, polyapiAuthorizeUrl, toOrder +- app/service/systemMethods/order/archiveOrder.js (2) + - list, detail +- app/service/systemMethods/order/base.js (57) + - maskListSensitiveValue, isInterceptedOrderStatus, isLockedOrderStatus, assertOrderNotIntercepted, getWarehouseId, getOrderLogOperator, getOrderLogWarehouseId, normalizePagination, normalizeWhereInput, normalizeOrderIds, isMergeableWhereCondition, mergeWhereObjects, getModuleConfig, getDefaultWhere, getBadgeCountCacheKey, formatBadgeCountValue, formatWeightTypeLabel, formatCreateChannelLabel, normalizeWaveScanResult, normalizeWaveStrategyVersion, normalizeLockStatusFlag, normalizeOrderListItem, getBadgeCountByModule, getOrderModel, resolveOrderTableType, getOrderModelByTableType, getOrderItemsModelByTableType, getOrderExpressesByOrderId, normalizeOrderListRow, attachOrderExpressNumbers, attachOrderWaveIndex, extractOrderListExpressVirtualFilter, extractBuyerMessageHasVirtualFilter, extractStockQueryVirtualFilter, extractWaveIndexVirtualFilter, extractWaveScopeVirtualFilter, findOrderIdsByWaveIndexCondition, in, buildWaveScopeWhereCondition, buildBuyerMessageHasCondition, appendConditionToWhere, normalizeExpressFilterValues, findOrderIdsByExpressNumbers, findOrderIdsByStockQuery, appendOrderIdsFilterToWhere, buildListOrder, buildWhere, listByModule, detail, attachStockDetailsToOrderItems, getOrderOperationLogs, resolveReviewStep, normalizeReviewOrderIds, buildOrderWhere, buildReviewOrderWhere, updateReviewOrder, updateOrderInspectionState +- app/service/systemMethods/order/deliveryExpectionOrder.js (2) + - list, detail +- app/service/systemMethods/order/deliveryOrder.js (5) + - list, detail, quickSearch, buildWaybillItem, fetchOrderMapByIds +- app/service/systemMethods/order/entrustOrder.js (2) + - list, detail +- app/service/systemMethods/order/expectionOrder.js (2) + - list, resolveException +- app/service/systemMethods/order/index.js (16) + - export, exportTaskProgress, generateExportTaskId, normalizeExportTaskId, getExportTaskCacheKey, setExportTaskProgress, getExportTaskProgress, list, manualOutboundOrder, badgeCount, queryOrderLogs, queryOrderLogList, updateExpressWeighingWeight, bindExpressPackageMaterial, bindExpressPackageMaterialByWaybill, pullReviewDataByWaybill +- app/service/systemMethods/order/outboundOrder.js (2) + - list, manualOutboundOrder +- app/service/systemMethods/order/packing.js (4) + - list, get, setEndTime, forceRecord +- app/service/systemMethods/order/pendingOrder.js (41) + - list, detail, reverseReviewOrder, assertOrdersWithoutWaybill, syncWavesAfterReverseReview, allocateStorage, allocateStorageProgress, normalizeAllocateStorageTaskProgress, normalizeAllocateStorageTaskCount, normalizeAllocateStorageTaskCounts, normalizeAllocateStorageRequestId, getAllocateStorageTaskCacheKey, setAllocateStorageTaskProgress, getAllocateStorageTaskProgress, getAllocateExpressTaskCacheKey, normalizeAllocateExpressTaskId, setAllocateExpressTaskProgress, getAllocateExpressTaskProgress, getSyncOrderIdsTaskCacheKey, normalizeSyncOrderIdsRequestId, setSyncOrderIdsTaskProgress, getSyncOrderIdsTaskProgress, cancelAllocateStorage, syncOrderIds, syncOrderIdsProgress, allocateExpressCode, allocateExpressCodeTaskProgress, markPendingOutboundOrder, cancelOrder, normalizePendingOutboundOrderIds, normalizePendingCancelOrderIds, isCancelablePendingOrder, updateOrderPlatform, updateOrderExpress, updateAddress, updateRemark, cloneOrder, parseAddress, _parseAddressBatchOneShot, _parseSingleAddress, catch +- app/service/systemMethods/order/print.js (4) + - getWavePlatformPrintData, getOrderPrintData, getPrintDataByWaybillCodes, unlockWavePlatformPrintDataByGroup +- app/service/systemMethods/order/recheckOrder.js (57) + - scanOrder, scanTask, buildSingleWaveScanView, buildSingleWaveView, buildGroupWaveList, getPickModeByWaveId, getTaskIdByWaveId, getWaveOrdersBasic, batchQueryPackageMaterialRecommendation, enrichOrdersWithStock, getPickerInfoByWaveId, getPickerInfoByTaskId, getWaveStrategyInfo, scanWaybill, confirmRecheck, confirmRecheckByWaveId, _writeRecheckActionLog, updateTaskOrderReviewAndTryUnbindCart, _resolveTaskIdByWaveFallback, _checkTaskOrdersAllReviewed, updateTaskOrdersReviewBatch, unbindCartForTask, resolveOrderId, resolveScanKeyword, pickOrderMatchByKeyword, pickOrderIdByWaybill, pickOrderIdByCartCode, pickWaveMatchContextByWaveNo, pickCartMatchContextByCartCode, getTableColumnSet, resolvePickModeName, buildWaveMatchView, buildCartMatchView, flattenCartMatchOrders, enrichTaskOrderRows, groupTaskOrdersByWaveId, groupTaskOrdersByPickStatus, groupTaskOrdersByBoxNo, groupTaskOrders, buildRecheckReviewNo, assertOrderCanRecheck, recheckOrderList, queryRecheckOrderSingleList, queryRecheckOrderGroupList, resolveModelTableName, confirmIntercept, interceptScan, batchQuickRecheck, normalizeWaveIds, batchQuickRecheckByWave, _completePickForOrder, _markRecheckForOrder, _tryCompleteWaveIfAllOrdersRechecked, _tryCompleteWaveInTransaction, _updateTaskOrderReviewInTransaction, _unbindCartForTaskInTransaction, _writeRecheckActionLogInTransaction +- app/service/systemMethods/order/reviewOrder.js (2) + - list, reviewOrder +- app/service/systemMethods/order/storageAllocation.js (0) + - +- app/service/systemMethods/order/wave.js (222) + - buildBatchAllocateExpressTraceId, buildOrderOperationLogRows, batchCreateOrderOperationLogs, buildMachineStructureToken, parseMachineStructureToken, getOrderItemPart, getDefaultWaveQuantity, getMinGroupOrderFetchQuantity, getGroupWavePrefix, getSingleFetchByIdsWavePrefix, getWarehouseSubjectConfig, getWarehouseSubjectConfigValue, normalizeFetchStructureRequests, generateWaveId, getCurrentDatePart, VALUES, getNextWaveNoSequence, buildWaveNo, id, getWaveCreator, extractInsertId, extractLastInsertId, isDuplicateEntryError, createWaveBatchReady, buildFetchWhere, fetchSingleStructure, normalizeBoolean, normalizePositiveInteger, normalizeRequiredPositiveInteger, normalizeIdsInput, normalizePagination, normalizeWaveStatusList, normalizeBatchListStorageAssignmentStatusFilter, normalizeBatchListExpressAssignmentStatusFilter, normalizeBatchListPrintAssignmentStatusFilter, normalizeBatchListReviewAssignmentStatusFilter, getBatchListAssignmentFilterSchema, normalizeBatchListAssignmentStatusFilterByType, normalizeBatchListAssignmentStatusFilter, getModelTableSqlName, buildBatchListStorageAssignmentFilterClause, buildBatchListExpressAssignmentFilterClause, buildBatchListPrintAssignmentFilterClause, buildBatchListReviewAssignmentFilterClause, buildBatchListAssignmentStatusFilterClauseByType, buildBatchListAssignmentStatusFilterClause, buildBatchListWhereClause, normalizeWavePickTaskListPagination, normalizeWavePickTaskListRequest, buildWavePickTaskListWhereClause, resolveAssignmentStatus, normalizeSkuText, normalizeShopName, parseItemSnapshot, normalizeOrderItemRow, mergeOrderItemDetails, buildItemSummary, buildOrderItemSnapshot, buildItemSnapshotKey, orderMatchesIncludeSku, buildCoarseGroupKey, buildStatusSummary, buildGroupKey, groupOrderFetchList, singleOrderFetchList, waveStrategyList, getWaveStrategyNextFetchOrderCountMap, getWaveStrategyDebugFetchOrderListMap, previewWaveStrategyNextFetchOrderCount, getWaveStrategyMatchedOrderCountFilteredMap, waveStrategyCreate, waveStrategyUpdate, bumpWaveStrategyVersionAndInvalidateCache, getWaveStrategyModel, normalizeWaveStrategyId, normalizeWaveStrategyUpsertPayload, normalizeWaveStrategyWavePrefix, resolveWaveStrategyFetchWavePrefix, patchWaveStrategyIntegerField, validateWaveStrategyAllowedOwners, validateWaveStrategyAllowedExpresses, getWaveStrategyAvailableOwnerSet, getWaveStrategyAvailableExpressSet, applyWaveStrategyMaxSameStructureConstraint, normalizeWaveStrategyFallbackOrderListWhere, resolveWaveStrategyFallbackTrackingNo, resolveWaveStrategyFallbackStoreName, resolveWaveStrategyFallbackSysLogisticsName, buildWaveStrategyFallbackOrderListItem, waveStrategyFallbackOrderList, batchList, wavePickTaskList, batchCancel, batchCancelTaskProgress, batchAllocateExpress, batchAllocateExpressTaskProgress, batchAllocateStorage, batchAllocateStorageTaskProgress, submitWaveStrategyQuickScanForWarehouse, waveStrategyQuickScan, waveStrategyQuickScanTaskProgress, buildWaveStrategyQuickScanOrderWhere, getWaveStrategyQuickScanStrategyRows, getWaveStrategyQuickScanMatchModel, syncWaveStrategyQuickScanMatchedStrategies, cleanupWaveStrategyQuickScanMatchedStrategies, cleanupWaveStrategyQuickScanMatchedStrategiesByOrderIds, enqueueWaveStrategyQuickScanPostOrderChange, executeWaveStrategyQuickScan, runWaveStrategyQuickScanTask, batchUpdateWaveStrategyQuickScanOrders, generateWaveStrategyQuickScanTaskId, normalizeWaveStrategyQuickScanTaskId, getWaveStrategyQuickScanTaskCacheKey, setWaveStrategyQuickScanTaskProgress, getWaveStrategyQuickScanTaskProgress, getWaveStrategyQuickScanWarehouseLockCacheKey, setWaveStrategyQuickScanWarehouseLock, getWaveStrategyQuickScanWarehouseLock, clearWaveStrategyQuickScanWarehouseLock, normalizeWaveStrategyQuickScanVersion, normalizeWaveStrategyQuickScanList, normalizeWaveStrategyQuickScanNumberOrNull, normalizeWaveStrategyQuickScanBoolean, normalizeWaveStrategyQuickScanStringList, getWaveStrategyQuickScanStructureKey, getWaveStrategyQuickScanExpressKey, filterCandidateOrdersByRequireSameExpress, isWaveStrategyQuickScanOrderMatched, getWaveStrategyQuickScanMatchedStrategyIds, isWaveStrategyQuickScanOrderMatchedSingleStrategy, isWaveStrategyQuickScanValueInRange, resolveGroupCandidateOrderIdsForSingleFetch, singleFetchByIds, batchRemoveOrders, resortWaveIndex, batchRemoveExceptionOrders, batchRemoveExceptionOrdersTaskProgress, generateBatchCancelTaskId, normalizeBatchCancelTaskId, generateBatchRemoveExceptionOrdersTaskId, normalizeBatchRemoveExceptionOrdersTaskId, normalizeBatchRemoveExceptionOrdersWaveIds, getBatchRemoveExceptionOrdersTaskCacheKey, setBatchRemoveExceptionOrdersTaskProgress, getBatchRemoveExceptionOrdersTaskProgress, isExceptionRemovableOrder, runBatchRemoveExceptionOrdersTask, normalizeBatchCancelWaveIds, getBatchCancelTaskCacheKey, setBatchCancelTaskProgress, getBatchCancelTaskProgress, runBatchCancelTask, generateBatchAllocateExpressTaskId, normalizeBatchAllocateExpressTaskId, normalizeBatchAllocateExpressWaveIds, getBatchAllocateExpressTaskCacheKey, setBatchAllocateExpressTaskProgress, getBatchAllocateExpressTaskProgress, generateBatchAllocateStorageTaskId, normalizeBatchAllocateStorageTaskId, normalizeBatchAllocateStorageWaveIds, normalizeBatchAllocateStorageTaskCount, buildBatchAllocateStorageRunningProgressPayload, normalizeBatchAllocateStorageOrderIds, getBatchAllocateStorageTaskCacheKey, getBatchAllocateStorageWarehouseLockKey, tryAcquireBatchAllocateStorageWarehouseLock, releaseBatchAllocateStorageWarehouseLock, setBatchAllocateStorageTaskProgress, getBatchAllocateStorageTaskProgress, isMissingBusinessKeyColumnError, runBatchAllocateExpressTask, runBatchAllocateStorageTask, batchAutoGrouping, batchFinishAutoGrouping, generateFetchTaskId, normalizeFetchTaskId, getFetchTaskCacheKey, setFetchTaskProgress, getFetchTaskProgress, fetchTaskProgress, runFetchTask, submitFetchTask, groupFetch, singleFetch, resolveWaveStrategyFetchPickMode, buildWaveStrategyFetchBoxAssignments, prepareWaveStrategyFetchPlan, in, ensureNoActiveWavePickTaskForOperator, getWaveStrategyFetchCandidateOrders, groupWaveStrategyFetchCandidateOrdersByStructure, buildWaveStrategyFetchOrderSkuMap, selectWaveStrategyFetchOrdersBySkuLimit, createWaveBatchByOrderIdsInTransaction, autoPopulateWaveStrategyFetchSelections, executeWaveStrategyDirectFetch, createWavePickTaskFromPlan, buildTaskCreatePayload, buildTaskWaveRows, buildTaskOrderRows, buildTaskSkuRows, buildTaskBoxRows, bindPickCartForTask, initTaskCheckpointAndLogs, ensurePickCartAvailable, generateWavePickTaskNo, createWavePickTaskWithRetry, isTaskNoDuplicateError, bulkInsertRows, parseWaveStrategyExistingTaskInfo, waveStrategyFetchPda, cancelWavePickTasksInternal, wavePickTaskCancel, wavePickTaskCancelSelf, waveStrategyFetchAdmin, deleteOrderWaveIndexByOrderIds, deleteOrderWaveIndexByWaveIds, rebuildOrderWaveIndex, replaceOrderWaveIndexByWaveIds, fetch +- app/service/systemMethods/outbound.js (1) + - autoOutbound +- app/service/systemMethods/pick.js (14) + - normalizeBoolean, getOrderModelByWarehouse, generatePickTaskNo, createWavePickTask, resolveLocationSortedOrderIds, query, wavePickTaskDetail, wavePickTaskCurrent, wavePickTaskSubmit, wavePickComplete, wavePickTaskComplete, getWavePickModeByWaveId, getWaveClaimGateStats, waveClaimScan +- app/service/systemMethods/pickCart.js (9) + - scan, bindTaskCart, create, update, delete, batchDelete, detail, list, codeDuplicateCheck +- app/service/systemMethods/print.js (28) + - buildPrintSendInputSummary, summarizeExpressPayload, extractExpressTaskCodeFromPayload, buildPrintTaskCodeForRecord, buildPendingPrintRecordPayload, buildSentPrintRecordUpdatePayload, buildSendFailedPrintRecordUpdatePayload, normalizeOrderIds, collectOrderIdsFromPlatformGroup, collectOrderIdsFromCustomizeData, normalizeExpressPlatformCode, extractOrderIdsFromPrintRecordData, updateOrderPrintStatusByCallback, getPrintTaskCodeRetryConfig, getPrintTaskCodeWritebackRetryConfig, generateAtomicPrintTaskCode, isDuplicateKeyError, calculateBackoffDelayMs, sleep, reserveUniquePrintTaskCode, bindTaskCodeToPrintRecord, bindTaskCodeToPrintRecordWithRetry, send, now, if, update, error, fail +- app/service/systemMethods/printComputer.js (5) + - list, update, setRecording, cancelRecording, delete - app/service/systemMethods/printer/station.js (1) - list -- app/service/systemMethods/returnReceived.js (4) - - create, list, detail, delete -- app/service/systemMethods/setting/printTemplate.js (3) - - list, save, listTemplatesByType -- app/service/systemMethods/stock.js (21) - - stockWarehouse, getProhibitedType, getInfo, saveWarehouseStock, createWarehouseStock, getBarcodes, saveWarehouseStockBarcode, getStoreStocks, bindItem, unbindItem, checkItemCodeUnique, queryStockLogs, handleBatchDelete, deleteUnit, deleteProhibited, handleBatchChange, getStockUnits, getUnitList, createProhibited, createUnit, search -- app/service/systemMethods/storage/receiving.js (13) - - getReceivingList, getReceivingDetail, batchCancelReceiving, create, addItem, removeItem, saveReceiving, get, addDetail, deleteDetail, detailChange, cancel, completeReceiving -- app/service/systemMethods/storage/direct_inbound.js (4) - - getItems, addItem, commit, removeItem +- app/service/systemMethods/returnReceived.js (5) + - _call, create, list, detail, delete +- app/service/systemMethods/returnUnpack.js (13) + - _call, create, addDetail, updateDetail, removeDetail, cancel, submit, forceRecord, list, detailList, videoList, detail, delete +- app/service/systemMethods/returnWaybill.js (6) + - _call, create, update, list, detail, delete +- app/service/systemMethods/setting/account.js (7) + - callSystemAccount, list, add, delete, update, getBindWechatCode, unbindWechat +- app/service/systemMethods/setting/express.js (8) + - callSystemExpress, list, listBase, create, checkCodeUnique, update, resolveDeleteIds, delete +- app/service/systemMethods/setting/expressInterface.js (6) + - callSystemExpressInterface, list, listByWarehousePlatformCode, create, update, delete +- app/service/systemMethods/setting/packageMaterial.js (8) + - callSystemPackageMaterial, resolveDeleteIds, get, list, search, create, update, delete +- app/service/systemMethods/setting/packageSupplier.js (7) + - callSystemPackageSupplier, resolveDeleteIds, get, list, create, update, delete +- app/service/systemMethods/setting/permission.js (5) + - callSystemPermission, list, add, delete, update +- app/service/systemMethods/setting/platform.js (6) + - callSystemPlatform, list, create, update, resolveDeleteIds, delete +- app/service/systemMethods/setting/printTemplate.js (6) + - list, normalizeAndValidateBusinessType, save, create, delete, listTemplatesByType +- app/service/systemMethods/setting/role.js (6) + - callSystemRole, list, permission, add, delete, update +- app/service/systemMethods/setting/store_warehouse.js (0) + - +- app/service/systemMethods/setting/warehouse.js (3) + - getSettings, getFieldMeta, saveSettings +- app/service/systemMethods/shops.js (6) + - callShopsSystem, list, add, del, edit, GetAuthorizeSessionKey +- app/service/systemMethods/stock/combo.js (0) + - +- app/service/systemMethods/stock/index.js (1) + - stockWarehouse +- app/service/systemMethods/stock/report.js (10) + - search, searchStore, exportStore, export, exportTaskProgress, generateExportTaskId, normalizeExportTaskId, getExportTaskCacheKey, setExportTaskProgress, getExportTaskProgress +- app/service/systemMethods/stock/store.js (0) + - +- app/service/systemMethods/stock/transaction.js (10) + - list, storeList, export, exportStore, exportTaskProgress, generateExportTaskId, normalizeExportTaskId, getExportTaskCacheKey, setExportTaskProgress, getExportTaskProgress +- app/service/systemMethods/stock/warehouse.js (37) + - normalizeWarehouseRecycleWhere, list, externalList, externalExport, export, exportTaskProgress, generateExportTaskId, normalizeExportTaskId, getExportTaskCacheKey, setExportTaskProgress, getExportTaskProgress, getProhibitedType, getInfo, saveWarehouseStock, createWarehouseStock, import, _normalizeWarehouseImportRows, _normalizeWarehouseImportRow, _normalizeNeedRecheckValue, _normalizeBarcodeField, getBarcodes, saveWarehouseStockBarcode, getStoreStocks, bindItem, unbindItem, checkItemCodeUnique, queryStockLogs, handleBatchDelete, deleteUnit, deleteProhibited, handleBatchChange, getStockUnits, getUnitList, createProhibited, createUnit, search, getStockDetail +- app/service/systemMethods/storage/delivery.js (3) + - list, toOrder, listItems +- app/service/systemMethods/storage/entry.js (26) + - list, listStore, get, getStore, cancel, addItem, commit, removeItem, bindReceiving, unbindReceiving, quickInbound, getPrintData, receivingCompare, queryEntryLogs, getReceivingDetailsForBind, containerList, reviewEntry, export, exportTaskProgress, generateExportTaskId, normalizeExportTaskId, getExportTaskCacheKey, setExportTaskProgress, getExportTaskProgress, storeExport, storeExportTaskProgress +- app/service/systemMethods/storage/expiry.js (1) + - list +- app/service/systemMethods/storage/inventory.js (14) + - transferLocation, transferByProduct, extractStockQueryVirtualFilter, list, listByStockId, quickPutaway, directPutaway, export, exportTaskProgress, generateExportTaskId, normalizeExportTaskId, getExportTaskCacheKey, setExportTaskProgress, getExportTaskProgress +- app/service/systemMethods/storage/management.js (1) + - replenishmentDemand +- app/service/systemMethods/storage/receiving.js (29) + - getReceivingList, getStoreReceivingList, getReceivingDetail, batchCancelReceiving, create, bindStore, bindDetailProduct, addItem, removeItem, save, get, addDetail, deleteDetail, detailChange, cancel, completeReceiving, rejectReceiving, reviewReceiving, queryReceivingLogs, scanDetail, export, exportTaskProgress, generateExportTaskId, normalizeExportTaskId, getExportTaskCacheKey, setExportTaskProgress, getExportTaskProgress, storeExport, storeExportTaskProgress +- app/service/systemMethods/storage/stockout.js (5) + - list, toOrder, listItems, confirm, updateExpress +- app/service/systemMethods/storage/transaction.js (1) + - list +- app/service/systemMethods/store_express_binding_policy.js (5) + - callSystem, list, add, edit, del - app/service/systemMethods/store.js (6) - createStore, createWarehouse, joinStore, joinWarehouse, getStoreRoles, auditApply -- app/service/systemMethods/user.js (5) - - login, logout, info, changeRole, register -- app/service/systemMethods/warehouse.js (20) - - getWarehouseZones, getWarehouseTree, getChildren, create, update, delete, detail, checkBarcodeUnique, toggleActive, getPath, createRack, getPickPath, updateRackPosition, recalculatePickPath, updateNeighbors, getAreaRacks, getSpacesByRack, createRackWithSpaces, getSpaceInfo, updateSpaceInfo +- app/service/systemMethods/storeWarehouse.js (0) + - +- app/service/systemMethods/storeWarehouse/store.js (25) + - list, sign, confirmSign, rename, unbind, adjustPrintQuantity, queryPrintQuantityLogs, getPolicyConfig, getPolicyConfigFields, savePolicyConfig, listApiConfig, saveApiConfig, deleteQimenConfig, openAccount, createUser, exportPrintQuantityLogs, exportPrintQuantityLogsTaskProgress, queryStorePrintQuantityLogs, exportStorePrintQuantityLogs, exportStorePrintQuantityLogsTaskProgress, generateExportTaskId, normalizeExportTaskId, getExportTaskCacheKey, setExportTaskProgress, getExportTaskProgress +- app/service/systemMethods/storeWarehouse/warehouse.js (3) + - list, sign, confirmSign +- app/service/systemMethods/user.js (9) + - login, loginByCode, getBindWechatCode, getLoginWechatCode, unbindWechat, logout, info, changeRole, register +- app/service/systemMethods/warehouse.js (25) + - getWarehouseZones, getWarehouseTree, getChildren, create, update, delete, detail, checkBarcodeUnique, toggleActive, getPath, getPickPath, updateRackPosition, recalculatePickPath, updateNeighbors, getAreaRacks, getSpacesByRack, createRackWithSpaces, getSpaceInfo, updateSpaceInfo, getBatchFieldValue, hasBatchField, normalizeBatchString, getCurrentWarehouseCode, batchUpdateSpaceInfo, exportRackSpaces +- app/service/systemMethods/waybill/warehouse.js (9) + - list, detail, export, exportTaskProgress, generateExportTaskId, normalizeExportTaskId, getExportTaskCacheKey, setExportTaskProgress, getExportTaskProgress +- app/service/systemMethods/workbench.js (8) + - list, detail, create, update, delete, business, bindCamera, checkBarcode - app/service/systems/account_platform.js (11) - getActiveInclude, getPrimaryRoleBinding, formatActiveContext, switchActiveRole, getActiveRoleByPlatform, getMultiplePlatformActiveRoles, getAllPlatformActives, clearPlatformActive, clearPlatformCache, getAvailableRoles, getCurrentContext -- app/service/systems/auth/user.js (21) - - login, ID, changeRole, info, getRoles, findById, setUserCache, getAvatarByEmployeeId, clearUserCache, clearRelatedCache, getPermissions, getMenus, convertToRoutes, findUserByIdentifier, checkUserStatus, verifyPassword, encryptPassword, generateSalt, updateLastLoginTime, ensurePlatformActiveRole, register -- app/service/systems/delivery_order.js (7) - - addOrder, generateItemsHash, calculateCRC32, prepareOrderData, addOrderLines, safeParseFloat, addOrderToQueue -- app/service/systems/entry_order.js (9) - - addOrder, getLineCount, received, success, fail, tryCreateEntryOrder, addItems, qimenEntryorderConfirm, entryorderConfirm -- app/service/systems/inbound_direct_log.js (4) - - getItems, addItem, commit, removeItem +- app/service/systems/afterSale.js (29) + - list, countPending, _buildListWhere, _resolveConditionValue, _extractConditionValue, _buildListOrder, getDetail, _enrichAfterSaleDetail, _resolveOrderDetail, _resolveStoreContractNote, _resolveWaybillDetail, _enrichStepsWithAttachments, create, _enrichListStoreNames, update, _formatAfterSaleRow, addStep, bindAttachments, transfer, handleWorkOrder, createInterceptWorkOrdersAndNotify, _resolveFollowupHours, _tryParseHours, batchSetPendingFeedback, batchClose, registerClaim, exportAfterSales, _generateAndUploadExcel, _getCreateChannelLabel +- app/service/systems/api_sign.js (4) + - getApiAppCacheKey, getApiAppConfigByAppKey, getApiAppSecretByAppKey, verifyRequestSignByAppKey +- app/service/systems/apiApp.js (8) + - generateAppKey, generateAppSecret, getDefaultInterfaceTypeId, list, create, update, delete, regenerateSecret +- app/service/systems/auth/role_permission.js (7) + - normalizeTypeFilter, normalizePermissionSet, toApiPermissionIds, serializePermissionSet, getPermissionIdsForRoles, assignPermissions, removePermissionsFromAllRoles +- app/service/systems/auth/user.js (66) + - getMenuTypeWhereByPlatform, getCurrentAccountId, getWechatBindCacheKey, getWechatBindCodeCacheKey, getWechatBindScanCacheKey, getWechatLoginClientCacheKey, getWechatLoginCodeCacheKey, getWechatLoginEventChannel, createWechatBindCodeCandidate, createUniqueSixCode, createWechatBindCode, createWechatLoginCode, createWechatLoginClientCode, parseWechatBindCode, formatBindWechatData, formatLoginWechatData, getRemainingSecondsByExpiresAt, setWechatBindCache, setWechatBindCodeCache, setWechatBindScanCache, getWechatBindScanCache, setWechatLoginClientCache, setWechatLoginCodeCache, findYe4sBindingByAccountId, getWechatBindEventChannel, getWechatLongPollTimeoutMs, shouldUseWechatBindLongPoll, publishWechatBindEvent, waitForWechatBindEvent, refreshWechatBindState, login, loginByYe4sCode, waitForLoginCodeRefresh, isTransientWechatLoginError, extractYe4sUserIdFromLoginEvent, waitForWechatLoginEvent, loginByYe4sUserId, tryBuildWechatLoginTokenFromState, refreshWechatLoginState, getLoginWechatCode, getBindWechatCode, getBindWechatCodeByAccountId, getUserByTempCode, bindAccountByTempCode, unbindWechat, unbindWechatByAccountId, buildLoginResult, changeRole, info, getRoles, findById, setUserCache, getAvatarByEmployeeId, clearUserCache, clearRelatedCache, getPermissions, getMenus, convertToRoutes, findUserByIdentifier, checkUserStatus, verifyPassword, encryptPassword, generateSalt, updateLastLoginTime, ensurePlatformActiveRole, register +- app/service/systems/camera.js (6) + - list, detail, create, update, setOsd, delete +- app/service/systems/cameraServer.js (5) + - list, detail, create, update, delete +- app/service/systems/comboGoods.js (15) + - fetchStockInfoMap, buildSimpleNotation, buildNameNotation, validateItems, getTargetStoreIdFromMap, checkCustomCodeUniqueForCreate, checkCustomCodeUniqueForUpdate, list, buildListWhere, create, update, delete, search, searchByIdOrCode, enrichComboList +- app/service/systems/delivery_order.js (47) + - getStoreSubjectConfigCacheKey, normalizeStoreSubjectConfig, getStoreSubjectConfig, findCodeOption, getOptionName, appendOrderOperationLog, getOrderLogOperator, getOrderLogWarehouseId, flushOrderOperationLogs, findPlatformOptionByCode, getPlatformSnapshotCode, getPlatformSnapshotName, resolvePlatformSnapshot, resolveExpressCodeFromSetting, resolveExpressSettingSnapshot, resolveEnableExternalExpressCode, resolveExpressSnapshot, addOrder, isPrimaryKeyDuplicate, formatOrderCreateError, resolveOrderStep, generateItemsHash, calculateCRC32, normalizeOrderFromKey, resolveOperatorName, prepareOrderData, addOrderLines, buildOrderItemSnapshot, safeParseFloat, withPatchedCtxUser, buildAsyncProcessContext, buildExpressAllocateRequest, buildStorageAllocateRequest, getStoreWarehousePolicyConfig, normalizePolicyFlag, resolveCutoffOrderConfig, isPastCutoffTime, buildAutoGroupingStructure, findAutoGroupingWaveId, appendOrderToWave, countCandidateGroupOrders, createGroupingWave, markWaveAutoGrouping, finishAutoGroupingIfNeeded, runAutoGrouping, runAsyncProcessStep, asyncProcessOrderCreated +- app/service/systems/entry_order.js (16) + - addOrder, getLineCount, received, success, fail, findByOrderCode, findByStatus, getStatsByWarehouse, updateSyncStatus, updateOrderStatus, calculateReceivedQuantities, batchUpdateReceived, getOrderProgress, tryCreateEntryOrder, addItems, reviewEntry +- app/service/systems/excel.js (24) + - getContentType, sanitizeSheetName, normalizeHeaders, normalizeColumns, prepareSheetData, hasEmbeddedImages, buildWorksheet, buildWorkbook, buildExcelJsWorkbook, inferImageExtension, resolveImageSource, mergeCellStyle, applyStyledRows, addEmbeddedImages, generateBuffer, writeFile, writeAtomicBufferFile, sanitizeFilename, buildUploadKey, generateAndUpload, sendFile, parseBuffer, parseFile, workbookToJSON +- app/service/systems/express_platform.js (15) + - getOrderLogOperator, buildOrderExpressVerPatch, buildExpressPlatformTraceId, OrderExpress, cleanupFailedWaybillOrders, buildFailedOrderCleanupList, polyapi, cainiao, parsePlatformPrintData, stringifyPlatformPrintData, buildWaybillOrderMetaMap, buildWaybillSettlementRelationMap, persistWaybillSuccessUpdates, normalizePddExtData, pdd +- app/service/systems/express_policy.js (9) + - getWarehousePolicyCacheKey, getWarehousePolicyCacheTTL, clearWarehousePolicyCache, fetchWarehousePoliciesFromDB, getWarehousePolicies, _matchAnyToken, _matchAnyIntersect, _matchValueInArray, matchPolicy +- app/service/systems/express.js (72) + - getExpressListCacheKey, getCurrentWarehouseId, buildWaybillTraceId, getOrderLogOperator, getOrderLogWarehouseId, createAllocateExpressFailureLogs, normalizeWaybillBusinessKeys, normalizeWaybillCreatePlatformCode, normalizeWaybillPolicyConfig, buildWaybillBalanceExceptionText, normalizeWaybillCreateOrders, buildWaybillCreateRelationGroups, collectWaybillRelationProcessingState, buildWaybillRelationLockMap, lockWaybillRelationBalance, markWaybillOrdersAsException, writeWaybillOrderExceptions, writeDispatchOrderFlags, markWaybillAsyncOrdersAsError, buildMergedExpressLabel, normalizeExpressSettingRow, loadExpressSettingListFromDatabase, buildExpressSettingCustomCodeList, buildMergedExpressList, getExpressProductTypeListCacheKey, normalizeExpressProductTypeRow, normalizeExpressCodeKey, isSfExpressCode, extractExpressProductTypesFromTypeDesc, collectPddSfTimedDeliveryProductTypes, clearExpressProductTypeCache, upsertExpressProductTypeList, syncPddSfTimedDeliveryExpressProductTypes, normalizeExpressRow, loadExpressList, loadExpressListFromCache, loadExpressListFromDatabase, getSystemExpressList, loadExpressProductTypeListFromDatabase, getExpressList, getExpressProductTypeList, normalizeWaybillPrintPlatformCode, loadWaybillPrintPlatformCodeMap, loadWaybillAsyncRequestPlatformCodeMap, Map, resolveWaybillAsyncRequestPlatformCode, resolveWaybillGroupPrintPlatformCode, groupWaybillOrdersByPlatformAndLogistics, splitWaybillOrdersIntoBatches, pickWaybillExpressInterface, resolveWaybillAsyncPlatformCode, groupWaybillAsyncOrdersByPlatform, buildWaybillOrderDeliveryMap, normalizeWaybillAsyncText, normalizeWaybillAsyncNumber, formatWaybillAsyncDate, normalizeWaybillAsyncItems, buildWaybillAsyncRouteInfo, buildWaybillAsyncOrderInfo, buildWaybillAsyncReceiverInfo, buildWaybillAsyncSettlementInfo, buildWaybillAsyncItemsSummary, buildWaybillAsyncOrderListItem, buildWaybillAsyncBizcontentSkeleton, shouldDispatchWaybillAsyncPerOrder, dispatchWaybillAsyncPlatform, resolveWaybillAsyncDispatchPlatformCode, hardDeleteWaybillAsyncOrderExpressRows, getWaybillAsyncOrderDeliveryModel, createWaybillCodePipeline, asyncTask, createWaybillCode - app/service/systems/fast_where.js (13) - buildTree, getTreeByType, buildSubTree, getWithChildrenByType, getAllChildren, getByType, getGroups, getChildrenByPid, getTreeChildrenByPid, create, update, findById, delete - app/service/systems/file.js (2) - getImages, ReferenceFile +- app/service/systems/inbound_direct_log.js (10) + - getItems, _addSingleItem, _bindReceivingDetail, addItem, removeItem, commit, _sendOpenApiCallback, operationLog, qimenEntrySync, _syncReceivingStorageStatus +- app/service/systems/inbox/group.js (8) + - list, disable, update, reset, validateExpressInterfaces, validateSystemExpressCode, findGroupsByExpress, findStoreAfterSalesGroups +- app/service/systems/license_plate.js (7) + - getTencentCloudConfig, getTencentCloudRegion, normalizeBase64Image, buildTencentCloudRequest, sendTencentCloudRequest, recognizeLicensePlate, formatLicensePlateResult - app/service/systems/location_space.js (16) - create, batchCreate, list, detail, update, delete, toggleStatus, updateStatus, findAvailableSpaces, findByCode, findByBarcode, getWarehouseStats, getZoneStats, validateAllocation, validateTransferOut, _validateReferences -- app/service/systems/location_zone.js (22) - - getWarehouseLevelZones, getZoneTreeByWarehouse, getChildrenByZoneId, isLeafNode, createZone, validateBasicFields, validateByZoneType, validateParentElement, validateZoneOverlap, isOverlap, generateZoneCodeByType, getDefaultColorByType, getZoneTypeText, updateZone, deleteZone, checkZoneOverlap, getZoneDetail, toggleZoneActive, getZonePath, generateSpacesForRack, getSpaceInfo, checkBarcodeUnique +- app/service/systems/location_zone.js (24) + - collectZoneSubtree, assertSpacesNotOccupied, getWarehouseLevelZones, getZoneTreeByWarehouse, getChildrenByZoneId, isLeafNode, createZone, validateBasicFields, validateByZoneType, validateParentElement, validateZoneOverlap, isOverlap, generateZoneCodeByType, getDefaultColorByType, getZoneTypeText, updateZone, deleteZone, checkZoneOverlap, getZoneDetail, toggleZoneActive, getZonePath, generateSpacesForRack, getSpaceInfo, checkBarcodeUnique - app/service/systems/location.js (10) - createRackWithSpaces, _generateSpacesForRack, _calculateAreaRackOrder, _calculatePickPathForWarehouse, _updateSpacePickSequence, _calculatePickPriority, updateRackPosition, getPickPath, updateNeighborRelations, _findNeighborRacks -- app/service/systems/notification.js (1) +- app/service/systems/notice/drivers/generic.js (1) - send -- app/service/systems/operation_log.js (4) - - createOperationLog, queryStockLogs, queryOrderLogs, getMessageDetail -- app/service/systems/platform.js (6) - - checkPlatformExists, getPlatformInfo, clearPlatformCache, getPlatformSettingDetail, batchCheckPlatforms, createPlatformSetting -- app/service/systems/polo_api.js (6) - - getJsonDatas, getJsonData, getSignText, md5Encrypt, _formatDate, _formatPickupDate +- app/service/systems/notice/drivers/wecom.js (4) + - buildTextContent, buildMarkdownContent, buildRequestData, send +- app/service/systems/notice/index.js (28) + - getDriver, normalizeMessageType, toObject, normalizeEventList, matchesEvents, buildTraceId, getRegisteredEventCodes, isValidEventCode, assertEventRegistered, getRetryDelays, sleep, isSuccessfulResponse, getFailureMessage, persistFailureLog, sendWithRetry, getStoreInfoCacheKey, resolveStoreInfo, resolveSubjectConfig, normalizePayload, buildOutgoingPayload, getWebhookLimit, findMatchedWebhooks, getFixedGroupTargets, findSubscribedGroups, resolveStoreLabelInternal, sendToWarehouseChannel, send, sendViaWebhooks +- app/service/systems/operation_log.js (13) + - buildOperationLogData, buildBusinessLogWhere, formatOperationLogRows, createOperationLog, createOperationLogs, queryLogsByBusinessType, queryStockLogs, queryOrderLogs, queryAllOrderLogs, queryAllLogsByBusinessType, queryReceivingLogs, queryEntryOrderLogs, getMessageDetail +- app/service/systems/order_async.js (5) + - finalizeSuccessfulQimenSync, syncQmOrders, syncManualOrders, flushDeferredOrderSyncNotices, syncApiOrders +- app/service/systems/order_auto_outbound.js (7) + - getEnabledAutoOutboundWarehouses, normalizeSubjectConfigForAutoOutbound, buildAutoOutboundWhere, findAutoOutboundOrders, findOrderIdsWithWeigh, processWarehouseAutoOutbound, executeAutoOutbound +- app/service/systems/order_delivery_migration.js (15) + - syncOutboundOrdersToDelivery, retryTimeoutOutboundOrdersToDelivery, syncOutboundOrdersByStatus, normalizeWarehouseIds, listCurrentWarehouseIds, normalizeOutboundStatuses, buildMigrationQueryOptions, getOutboundMigrationErrorInfo, markOutboundOrdersTimeout, buildDispatchKey, buildDispatchRow, buildDispatchItemRow, getMigrationModels, buildTargetOrderIdMap, syncOutboundOrdersForWarehouse +- app/service/systems/order_export.js (12) + - getExportPageSize, normalizeExportModuleName, getSortModuleNameByTableType, resolveExportTarget, getOrderExportColumns, buildOrderExportFilename, buildUploadKey, toPlainRow, normalizeExportCellValue, mapOrderExportRow, uploadOrderExportFile, exportOrders +- app/service/systems/order_express.js (30) + - createBusinessError, normalizeOrderId, normalizeWaybillCode, normalizePackageMaterialCode, normalizePackageMaterialId, normalizeBindOrderId, getCurrentWarehouseId, findActivePackageMaterialById, findActivePackageMaterialByCode, findValidOrderExpressByOrderAndWaybill, findOrderInterceptStatus, assertOrderNotIntercepted, normalizeWeighingWeight, findValidOrderExpressRows, updateWeighingWeight, updateWeighingWeightByWaybill, _updateWaveAllOrdersWeight, _buildWaveWeighingSummary, _getStoreName, _getWaveSysLogisticsName, _updateSingleOrderWeight, _updateWaveOrderWeight, _writeWeighActionLog, _tryWaveCompatibility, _upsertPackageMaterialItemRelation, bindExpressPackageMaterial, bindExpressPackageMaterialByWaybill, _bindSingleExpressPackageMaterial, _bindWavePackageMaterialByBusinessKey, _writePackageMaterialActionLog +- app/service/systems/order_outbound.js (1) + - markOutboundOrder +- app/service/systems/order_packing.js (6) + - _getRecordingComputerId, _buildVideoUrl, list, get, setEndTime, forceRecord +- app/service/systems/order_pending_exception.js (2) + - markPendingException, reversePendingException +- app/service/systems/order_print.js (54) + - isOrderLocked, buildLockedWavePlatformResult, buildLockedOrderPlatformPrintItem, shouldLoadPickingDetails, normalizeItemSnapshot, getFirstNonEmptyFieldText, buildPrintItemAggregationKey, buildPrintOrderRowMapWithPicking, normalizeContractPolicyConfig, getWavePlatformPrintData, getOrderPrintData, getPrintDataByWaybillCodes, queryWaybillsByCodes, getMainWaybillMapByOrderIds, normalizeUnlockGroupRules, isOrderMatchedByUnlockGroupRule, unlockWavePlatformPrintDataByGroup, normalizeWaveIds, normalizeOrderIds, getContextWarehouseId, resolveWarehouseId, queryWavesByIds, queryOrdersByWaveIds, queryOrdersByIds, queryOrderExpressByOrderIds, queryWaveOrderIndexMapByOrderIds, queryWaveTotalOrderCountMap, assertBusinessWaybillCompleteness, buildOrderExpressMap, isCainiaoPlatformCode, isJdPlatformCode, isPddPlatformCode, isDouyinPlatformCode, collectCainiaoExpressLookupCodes, queryCainiaoCpCodeMap, queryCainiaoExpressInterfaceList, queryJdExpressInterfaceList, queryPddExpressInterfaceList, queryDouyinExpressInterfaceList, pickCainiaoExpressInterface, pickJdExpressInterface, pickPddExpressInterface, pickDouyinExpressInterface, enrichCainiaoOrderExpressRows, enrichJdOrderExpressRows, enrichPddDyOrderExpressRows, getPolicyConfigMapByStore, resolvePrintPlatformCode, loadTemplateSampleByPlatform, buildOrderPlatformPrintItem, extractSinglePlatformPrintData, groupOrderPrintItemsByPlatform, groupOrderPrintItemsByWaveAndPlatform, filterFullyAssignedExpressWaves +- app/service/systems/order_review.js (14) + - createBusinessError, normalizeWaybillCode, isLockedStatus, isInterceptStatus, toPlainRecord, parseItemSnapshot, findOrderExpressByWaybill, findOrderById, findOrderItems, loadBarcodesByStockIds, loadImagesByStockIds, findWaveById, buildGroupInterceptList, pullReviewDataByWaybill +- app/service/systems/order_storage_allocation.js (4) + - allocatePicking, allocateStorage, syncOrderIds, cancelAllocateStorage +- app/service/systems/pack_task_auto_finish.js (1) + - executeAutoFinishPackTasks +- app/service/systems/pick_compensation.js (9) + - executeCompensation, compensateWarehouse, getPendingOrderIds, findPendingPickingForDispatchOrders, findPendingPickingForCancelledOrders, SUM, releaseCancelledInTransaction, compensateInTransaction, createBusinessError +- app/service/systems/pick.js (37) + - getOrderModel, createBusinessError, getTableColumnSet, loadOrderItemMap, parseItemSnapshot, buildPickingSummary, getPickModeViewMeta, loadOrderWaveMap, buildPickingView, resolveWaveInfo, isOrderReviewed, buildWaveOrderWhere, queryPickingInfo, queryByOrder, wavePickTaskCurrent, wavePickTaskDetail, resolveOperatorContext, normalizePickCartStatus, buildPickCartDetail, getPickCartById, getPickCartByCode, pickCartCodeDuplicateCheck, assertPickCartCodeUnique, getOwnedTask, getTaskPickProgress, wavePickTaskSubmit, wavePickTaskComplete, _afterSkipInterceptedPostActions, _writePickCompleteActionLog, pickCartScan, wavePickTaskBindCart, pickCartCreate, pickCartUpdate, pickCartDelete, pickCartBatchDelete, pickCartDetail, pickCartList +- app/service/systems/pickCart.js (9) + - scan, bindTaskCart, create, update, delete, batchDelete, detail, list, codeDuplicateCheck +- app/service/systems/platform.js (38) + - getCurrentWarehouseId, normalizePlatformOauthBindCode, getPlatformOauthBindSuccessCacheKey, getPlatformOauthBindFailCacheKey, getPlatformOauthBindEventChannel, getPlatformOauthLongPollTimeoutMs, shouldUsePlatformOauthLongPoll, getPlatformOauthBindState, publishPlatformOauthBindEvent, waitForPlatformOauthBindEvent, listenPlatformOauthBind, getPlatformFullAttributes, getPlatformSettingFullAttributes, getPrintPlatformModel, toPlainRow, normalizePrintPlatformId, loadPrintPlatformCodeMap, loadPrintPlatformPlatidMap, resolveDefaultExpressInterface, resolveRoutePlatformCode, getPlatformListCacheKey, isFullPlatformCacheSchemaStale, buildMergedPlatformLabel, normalizePlatformRow, loadPlatformSettingListFromDatabase, normalizePlatformSettingRow, normalizeFullPlatformRow, normalizeFullPlatformSettingRow, buildMergedPlatformList, loadPlatformListFromDatabase, getSystemPlatformList, getPlatformList, checkPlatformExists, getPlatformInfo, clearPlatformCache, getPlatformSettingDetail, batchCheckPlatforms, createPlatformSetting +- app/service/systems/polo_api.js (3) + - request, get, kuaishou - app/service/systems/print/index.js (2) - sendToComputer, test -- app/service/systems/qimen_query.js (6) - - send, replaceXmlTagsWithString, addSign, getQueryParams, generateUrlWithParams, sendRequest -- app/service/systems/return_received.js (12) - - create, list, detail, delete, createBusinessError, _findByIdChecked, _enrichReturn, _resolveStoreRemark, _buildListWhere, _resolveConditionValue, _extractConditionValue, _buildListOrder -- app/service/systems/setting/print_template.js (14) - - listTemplatesByType, getTree, getTemplatesByType, save, getBusinessTypesAndItem, getGroupedPrintItems, getTableConfigs, clearBusinessTypesCache, getXmlByTemplate, buildXmlFromElements, renderElement, computeItemStyle, computeTableItemStyle, renderTable +- app/service/systems/print/printData.js (1) + - getPrintData +- app/service/systems/printComputer.js (6) + - notifyRefreshInfo, list, update, setRecording, cancelRecording, delete +- app/service/systems/qimen_query.js (3) + - qimenClient, send, sendRequest +- app/service/systems/receiving_entry_match.js (12) + - matchAfterEntryCompleted, _bindEntryOrderReceiving, bindEntryOrderReceiving, _getRecentReceivingOrders, _findReceivingByRemark, _compareDetails, _sendCallback, _sendQimenCallback, _sendOpenApiCallback, _markReceivingPartialStorage, _commitBinding, unbindEntryOrderReceiving +- app/service/systems/return_received.js (14) + - createBusinessError, create, _handleInterceptAfterSale, _updateOrderInterceptStatus, list, detail, delete, _findByIdChecked, _enrichReturn, _resolveStoreRemark, _buildListWhere, _resolveConditionValue, _extractConditionValue, _buildListOrder +- app/service/systems/return_unpack.js (35) + - _getRecordingComputerId, _buildVideoUrl, createBusinessError, create, addDetail, updateDetail, removeDetail, cancel, submit, forceRecord, list, detailList, videoList, detail, queryByWaybill, _resolveWarehouseName, _resolveStoreIdByWaybill, _resolveReturnOrderInfo, delete, _findByIdChecked, _assertUnpacking, _findDetailChecked, _recalcMain, _enrichRow, _flattenVideos, _enrichDetailsWithStock, _resolveStoreRemark, VALUES, _generateUnpackNo, _buildListWhere, _buildDetailListWhere, _buildVideoListWhere, _buildVideoListOrder, _resolveConditionValue, _buildListOrder +- app/service/systems/return_waybill.js (12) + - createBusinessError, create, update, list, detail, delete, _findByIdChecked, _assertStoreContract, _formatRow, _buildListWhere, _resolveConditionValue, _buildListOrder +- app/service/systems/setting/account.js (31) + - getListWhereSpecialFieldMap, createError, getCurrentStoreId, getCurrentEmployeeId, normalizeAccountId, getWmsClient, normalizePhone, isValidPhone, normalizeName, normalizeUsername, generateUsername, findRawAccountByPhone, findRawAccountByUsername, getAvatarMeta, resolveRoleId, normalizeRoleIds, flattenRoleTreeMeta, resolveAssignableRoleScope, pruneDescendantRoleIds, resolveRequestedRoleIds, replaceEmployeeRoles, buildEmployeeRoleGroupMap, buildWechatBindingMap, getOperableEmployeeByAccountId, formatEmployeeRow, list, add, delete, update, getBindWechatCode, unbindWechat +- app/service/systems/setting/express.js (26) + - createError, getCurrentStoreId, getExpressListCacheKey, deleteCacheByKey, clearExpressListCache, normalizeDeleteIds, normalizeText, normalizeCode, normalizePage, getListWhereSpecialFieldMap, getSystemExpressList, getSystemExpressMap, normalizeSettingRow, findSettingById, findCodeConflict, ensureSystemExpressExists, ensureCodeAvailable, resolveListWhere, list, listBase, checkCodeUnique, create, update, findSettingsForDelete, ensureDeleteCodesNotReferenced, delete +- app/service/systems/setting/expressInterface.js (43) + - createError, getCurrentStoreId, getWarehousePlatformCacheKey, deleteCacheByKey, clearWarehousePlatformCache, normalizePlatformCode, normalizeText, normalizeOptionalText, normalizeOptionalJson, normalizeInteger, normalizeFlag, normalizePage, getListWhereSpecialFieldMap, resolveListWhere, getInterfaceInclude, getInterfaceFullAttributes, ensureModelFieldExists, resolveShopBinding, clonePlainValue, normalizeExpressRow, resolveIsSystemExpressCodeFlag, getPlatformExpressColumn, ensureSystemExpressCodeExists, ensurePrintPlatformExists, normalizePrintPlatformRow, getPrintPlatformList, resolveSysExpressCode, normalizeInterfaceRow, normalizeFullInterfaceRow, hasWarehousePlatformShopData, normalizeFullInterfaceRows, resolveWarehousePlatformTarget, findInterfaceById, findCodeConflict, findInterfaceConflict, ensureCodeAvailable, ensureInterfaceAvailable, list, listByWarehousePlatformCode, create, update, delete, loadExpressInterfaces +- app/service/systems/setting/packageMaterial.js (18) + - createError, getCurrentStoreId, normalizeRequiredText, normalizeOptionalText, normalizeOptionalDecimal, normalizeStatus, normalizePage, normalizeDeleteIds, getListWhereSpecialFieldMap, resolveListWhere, normalizeMaterialRow, ensureMaterialCodeUnique, findMaterialById, create, update, delete, get, search +- app/service/systems/setting/packageSupplier.js (16) + - createError, getCurrentStoreId, normalizeRequiredText, normalizeOptionalText, normalizeStatus, normalizePage, normalizeDeleteIds, getListWhereSpecialFieldMap, resolveListWhere, normalizeSupplierRow, ensureSupplierCodeUnique, findSupplierById, create, update, delete, get +- app/service/systems/setting/permission.js (26) + - createError, getCurrentStoreId, getCurrentEmployeeId, toPositiveNumber, getRole, getPermission, normalizePermissionType, normalizeOptionalString, normalizeParentId, normalizeSort, normalizeStatus, normalizeBooleanFlag, getAvailablePermissionIdSet, ensureParentPermissionExists, ensurePermissionsExist, normalizePermissionIds, normalizeIds, validatePermissions, clearRoleUsersCache, getCurrentEmployeePermissionIds, getCurrentRoleId, resolveVisiblePermissionRows, list, add, delete, update +- app/service/systems/setting/platform.js (26) + - createError, getCurrentStoreId, normalizeDeleteIds, getPlatformListCacheKey, getPlatformDetailCacheKey, getPlatformExistsCacheKey, deleteCacheByKey, clearPlatformCaches, normalizeRequiredText, normalizeOptionalText, normalizeInteger, normalizePage, getListWhereSpecialFieldMap, resolveListWhere, buildPlatformLabel, normalizePlatformRow, findSettingById, findCodeConflict, findPlatformCodeConflict, ensurePlatformExists, ensureCodeAvailable, ensurePlatformCodeAvailable, list, create, update, delete +- app/service/systems/setting/print_template.js (17) + - normalizeAndValidateBusinessType, listTemplatesByType, getTree, getTemplatesByType, save, createTemplate, deleteTemplate, getBusinessTypesAndItem, getGroupedPrintItems, getTableConfigs, clearBusinessTypesCache, getXmlByTemplate, buildXmlFromElements, renderElement, computeItemStyle, computeTableItemStyle, renderTable +- app/service/systems/setting/role.js (25) + - createError, getCurrentStoreId, getCurrentEmployeeId, toPositiveNumber, getEmployee, normalizeRoleIds, findAssignableRoles, clearEmployeeCache, getCurrentEmployeeRoleIds, collectDescendantRoleIds, buildRolePermissionMap, buildRoleTree, normalizeStoreScope, isRoleVisibleInScope, normalizePermissionIds, normalizePid, getManageableRole, validatePermissionSet, replaceRolePermissions, clearRoleUsersCache, list, permission, add, delete, update +- app/service/systems/setting/store_warehouse.js (35) + - createError, getCurrentStoreId, getCurrentAccountId, toPositiveNumber, normalizePage, normalizeStatusFlag, normalizeAuthStatus, normalizeNonNegativeInteger, normalizeText, normalizeDate, normalizeSignAction, normalizeTempCode, getTempCodeCacheKey, createTempCode, pickRemaskField, resolveRemaskValue, buildCurrentRemaskPatch, requireCurrentRemaskPatch, saveTempSignPayload, getTempSignPayload, clearTempSignPayload, buildTempSignView, getCurrentSubject, getCounterparty, buildListWhere, getRelationIncludes, resolvePairIds, serializeRelation, findScopedRelation, list, sign, trimContract, confirmSign, rename, unbind +- app/service/systems/setting/warehouse.js (11) + - getDefaultCodeFieldOptionsMap, normalizeWaveStrategyVersion, normalizeSubjectConfigInternalFields, sanitizeSubjectConfigForOutput, createError, getCurrentWarehouseId, deleteCacheByKey, clearWarehouseSettingCache, getFieldMeta, getSettings, saveSettings +- app/service/systems/shops.js (20) + - generatePendingShopName, createError, getCurrentWarehouseId, normalizeText, normalizeInteger, ensureShopPrintPlatformExists, getListWhereSpecialFieldMap, buildListWhere, normalizePagination, buildShopPrintPlatformInclude, formatShopRow, list, ensureShopNameUnique, add, findShopById, del, edit, generateAuthorizeRandomCode, createOrReuseAuthorizeReservation, getAuthorizeSessionKey - app/service/systems/sign.js (10) - Constants, toXml, signTopRequest, verifyTopRequest, verifyAndExtractParams, generateSignedParams, encryptHMAC, encryptHMACSHA256, encryptMD5, byte2hex -- app/service/systems/space.js (2) - - searchSpace, searchSpaces -- app/service/systems/stock_store.js (34) - - create, initQimenStockData, convertToQimenFormat, getItemInfoWithCache, getItemStorages, _calculateCacheTTL, clearItemStorageCache, lockItemStorages, ID, inbound, outbound, checkAndCreateWarehouseStock, getWarehouseStock, buildSequelizeCondition, processConditionValue, formatDate, isEmptyValue, getProhibitedType, getBarcodes, handleBatchChange, saveWarehouseStockBarcode, getStoreStocks, bindItem, unbindItem, getInfo, saveWarehouseStock, createWarehouseStock, validateSaveParams, stockLog, checkItemCodeUnique, handleBatchDelete, deleteUnit, deleteProhibited, search -- app/service/systems/storage/index.js (1) - - index -- app/service/systems/storage/receiving.js (16) - - getReceivingList, getReceivingDetail, batchCancelReceiving, isEmptyValue, buildSequelizeCondition, processConditionValue, create, get, addDetail, updateDetail, getStockStoreInfo, updateReceivingStats, deleteDetail, detailChange, invalid, completeReceiving -- app/service/systems/store.js (14) - - getStoreName, getStoreRemaskName, createStore, createWarehouse, joinStore, joinWarehouse, ensureEmployeeRoleBinding, assignAdminRoleToCreator, generateJoinToken, sendNotification, sendNotificationToAdmins, getStoreRoles, auditApply, loadStores -- app/service/systems/upload.js (14) - - initCOS, getUploadParams, hash_hmac, validateFileInfo, generateFileName, parseSizeToBytes, formatFileSize, getFrontendConfig, uploadFile, validateFile, uploadSuccessNotify, getMimeType, createFileReference, handleUploadCallback +- app/service/systems/space.js (3) + - _searchByKeyword, searchSpace, searchSpaces +- app/service/systems/stock_store.js (46) + - create, initQimenStockData, convertToQimenFormat, getItemInfoWithCache, getItemStorages, _calculateCacheTTL, clearItemStorageCache, _runWithTransaction, getStoreWarehousePolicyByStoreAndWarehouse, getStoreWarehousePolicyConfigByStockId, updateLockedQuantity, lockItemStorages, ID, inbound, normalizeOutboundMeta, getPickingRowsForOutbound, getPickingBatchMap, buildOutboundTransactionPayloads, outbound, checkAndCreateWarehouseStock, getWarehouseStock, exportWarehouseStock, exportExternalWarehouseStock, buildSequelizeCondition, processConditionValue, normalizeDate, formatDate, isEmptyValue, getProhibitedType, getBarcodes, handleBatchChange, saveWarehouseStockBarcode, getStoreStocks, bindItem, unbindItem, getInfo, saveWarehouseStock, createWarehouseStock, validateSaveParams, stockLog, checkItemCodeUnique, handleBatchDelete, deleteUnit, deleteProhibited, search, getStockDetail +- app/service/systems/stock_transaction.js (8) + - normalizeInboundOrderId, isOrderOutboundTransaction, resolveOutboundOrderReference, create, list, _resolveKeywordToStockIds, queryList, exportList +- app/service/systems/stock_warehouse.js (3) + - _buildStockDetailCacheKey, getStockDetails, invalidateStockDetailCache +- app/service/systems/storage/entry.js (24) + - normalizeExpenseRecordValue, normalizeExpenseRecordCondition, normalizeFilterValues, buildEntryStockTransactionExistsCondition, buildHasReceivingCondition, preprocessEntryListWhere, list, get, IN, enrichItemsWithAvailableReceivingDetails, normalizeCancelEntryOrderIds, getOwnedEntryOrderById, cancel, _rollbackReceivingStorageStatus, addItem, commit, removeItem, getReceivingDetailsForBind, containerList, quickInbound, receivingCompare, _buildMergedComparison, exportEntryOrders, exportStoreEntryOrders +- app/service/systems/storage/expiry.js (1) + - list +- app/service/systems/storage/index.js (10) + - findByStockAndBatch, findBySpace, findAvailableByWarehouse, findExpiringSoon, updateQuantity, lockQuantity, unlockQuantity, allocateQuantity, getStockSummary, getSpaceUsage +- app/service/systems/storage/inventory.js (13) + - createTransferStockTransactions, transferLocation, transferByProduct, resolveStockQueryToStockIds, getInventoryList, getStorageListByStockId, _aggregateStorageRowsBySpace, _loadInventoryWarningRanges, _formatBatchStorageRows, quickPutaway, directPutaway, exportInventoryList, _generateEntryOrderCode +- app/service/systems/storage/management.js (1) + - replenishmentDemand +- app/service/systems/storage/receiving.js (40) + - getReceivingList, _resolveStockQueryReceivingIds, getStoreReceivingList, getReceivingDetail, batchCancelReceiving, rejectReceiving, reviewReceiving, buildReviewReportSheets, sendStoreBoundNotice, sendReviewNotice, isEmptyValue, buildSequelizeCondition, processConditionValue, buildReceivingNumberPrefix, generateNextReceivingNumber, isReceivingNumberDuplicateError, create, save, bindStore, get, addDetail, bindDetailProduct, updateDetail, getStockStoreInfo, updateReceivingStats, deleteDetail, detailChange, invalid, formatReportDate, formatDeliveryMethod, getCompletionContactFields, Map, buildCompletionReportSheets, uploadCompletionExcelReport, sendCompletionNotice, completeReceiving, _syncProductDataFromReceiving, scanDetail, exportReceivingList, exportStoreReceivingList +- app/service/systems/storage/report.js (5) + - loadReportReferenceMaps, buildExportFilename, export, _resolveKeywordToStockIds, search +- app/service/systems/storage/stock_warehouse.js (3) + - _buildStockDetailCacheKey, getStockDetails, invalidateStockDetailCache +- app/service/systems/store_express_binding_policy.js (17) + - getCurrentWarehouseId, createError, normalizeText, normalizeInteger, normalizeWeightType, normalizeJsonArray, ensureExpressExists, getListWhereSpecialFieldMap, buildListWhere, normalizePagination, formatPolicyRow, list, ensureCustomNameUnique, add, findPolicyById, edit, del +- app/service/systems/store_warehouse.js (78) + - createError, getCurrentStoreId, getCurrentAccountId, toPositiveNumber, normalizePage, normalizeStatusFlag, normalizeAuthStatus, normalizeNonNegativeInteger, normalizeInteger, normalizeText, normalizeIntegerRange, normalizeEmail, getPolicyConfigFieldList, getPolicyConfigFieldMetaList, normalizePolicyConfig, getPolicyConfigCacheKey, hasPolicyConfigColumn, loadPolicyConfigByContractId, savePolicyConfigByContractId, getPolicyConfigDefaults, mergePolicyConfigWithDefaults, getEffectivePolicyConfigByContractId, ensureWarehouseSubject, getNoticeService, sendPrintQuantityAdjustNotice, resolveRelationId, normalizeDate, normalizeSignAction, normalizeTempCode, getTempCodeCacheKey, createTempCode, pickRemaskField, resolveRemaskValue, buildCurrentRemaskPatch, requireCurrentRemaskPatch, saveTempSignPayload, getTempSignPayload, clearTempSignPayload, buildTempSignView, getCurrentSubject, getCounterparty, buildListWhereByStoreId, buildListWhere, getRelationIncludes, getQimenContractCacheKey, clearQimenContractCache, getApiInterfaceType, getQimenInterfaceType, resolveQimenCustomerIdByAppKey, getQimenErpNameMapByAppKeys, serializeQimenConfig, getQimenConfigMap, getSingleQimenConfig, resolvePairIds, serializeRelation, findScopedRelation, listForStore, listForWarehouse, list, sign, trimContract, confirmSign, rename, adjustPrintQuantity, queryPrintQuantityLogs, exportPrintQuantityLogs, getPolicyConfigFields, getPolicyConfig, savePolicyConfig, listApiConfig, saveApiConfig, deleteQimenConfig, unbind, getContractConfigCacheKey, invalidateContractConfigCache, getContractConfig, openAccount, createUser +- app/service/systems/store.js (22) + - normalizeSubjectConfigInput, validateStoreData, checkCompanyNameExists, findByAccountId, findAllEnabled, findAllWarehouses, getStoreName, getStoreRemaskName, createStore, createWarehouse, joinStore, joinWarehouse, ensureEmployeeRoleBinding, assignAdminRoleToCreator, generateJoinToken, sendNotification, sendNotificationToAdmins, getStoreRoles, auditApply, loadStores, loadWarehouses, bindCode +- app/service/systems/upload.js (17) + - getTencentCloudConfig, getCosConfig, initCOS, getUploadParams, hash_hmac, generatePolicyAndSignature, validateFileInfo, generateFileName, parseSizeToBytes, formatFileSize, getFrontendConfig, uploadFile, validateFile, uploadSuccessNotify, getMimeType, createFileReference, handleUploadCallback +- app/service/systems/warehouseNotify.js (7) + - truncateLogBody, getCallbackConfig, MD5, buildSignature, writeLog, push, pushSystemMessage +- app/service/systems/wave_batch_closure.js (1) + - closeFinishedWaves +- app/service/systems/waybill.js (5) + - toOrder, list, detail, export, buildWaybillExportFile +- app/service/systems/workbench.js (19) + - list, detail, create, update, delete, bindCamera, business, _countWaveOrders, _getWaveOrderIds, Set, _buildPackChangeSummary, _writePackOperationLog, _packOrder, resolvePackTaskEndTime, _finishPack, _sendWeight, _writeWeighOpLog, _queryOrder, checkBarcodeExists +- app/service/warehouse.js (7) + - resolveWarehouseMethod, getWarehouseMethodService, dispatchWarehouseMethod, validateWarehouseParams, parseJsonBody, normalizeSignFields, processRequest +- app/service/warehouseMethods/inbox.js (2) + - push, parseSendTime +- app/service/warehouseMethods/index.js (1) + - ping +- app/service/warehouseMethods/store.js (1) + - list + + diff --git a/app/model/order_stockout.js b/app/model/order_stockout.js index 4b56eab..66f6c17 100644 --- a/app/model/order_stockout.js +++ b/app/model/order_stockout.js @@ -56,10 +56,10 @@ module.exports = app => { comment: '来源类型', }, order_status: { - type: ENUM('CREATING', 'CREATED', 'PENDING', 'COMPLETED', 'CANCELLED'), + type: ENUM('CREATING', 'CREATED', 'PENDING', 'COMPLETED', 'CANCELLED', 'TRANSFERRED'), allowNull: false, defaultValue: 'CREATED', - comment: '订单状态:CREATING=创建中, CREATED=已创建待审核, PENDING=已审核, COMPLETED=已完成, CANCELLED=已作废', + comment: '订单状态:CREATING=创建中, CREATED=已创建待审核, PENDING=已审核, COMPLETED=已完成, CANCELLED=已作废, TRANSFERRED=已转订单', }, sync_status: { type: ENUM('PENDING', 'SUCCESS', 'FAILED'), @@ -107,6 +107,81 @@ module.exports = app => { allowNull: true, comment: '备注', }, + receiver_company: { + type: STRING(200), + allowNull: true, + comment: '收件人公司名称(receiverInfo.company)', + }, + receiver_name: { + type: STRING(50), + allowNull: true, + comment: '收件人姓名(receiverInfo.name)', + }, + receiver_zip_code: { + type: STRING(50), + allowNull: true, + comment: '收件人邮编(receiverInfo.zipCode)', + }, + receiver_tel: { + type: STRING(50), + allowNull: true, + comment: '收件人固定电话(receiverInfo.tel)', + }, + receiver_mobile: { + type: STRING(50), + allowNull: true, + comment: '收件人移动电话(receiverInfo.mobile)', + }, + receiver_email: { + type: STRING(50), + allowNull: true, + comment: '收件人电子邮箱(receiverInfo.email)', + }, + receiver_country_code: { + type: STRING(50), + allowNull: true, + comment: '收件人国家二字码(receiverInfo.countryCode)', + }, + receiver_province: { + type: STRING(50), + allowNull: true, + comment: '收件人省份(receiverInfo.province)', + }, + receiver_city: { + type: STRING(50), + allowNull: true, + comment: '收件人城市(receiverInfo.city)', + }, + receiver_area: { + type: STRING(50), + allowNull: true, + comment: '收件人区域(receiverInfo.area)', + }, + receiver_town: { + type: STRING(50), + allowNull: true, + comment: '收件人村镇(receiverInfo.town)', + }, + receiver_detail_address: { + type: STRING(200), + allowNull: true, + comment: '收件人详细地址(receiverInfo.detailAddress)', + }, + receiver_id: { + type: STRING(50), + allowNull: true, + comment: '收件人证件号(receiverInfo.id)', + }, + source_platform_code: { + type: STRING(50), + allowNull: true, + comment: '来源平台编码(转订单时优先使用,为空时兜底平台)', + }, + source_platform_name: { + type: STRING(200), + allowNull: true, + comment: '来源平台名称快照', + }, express_code: { type: STRING(50), allowNull: true, @@ -252,6 +327,11 @@ module.exports = app => { return this.order_status === 'CANCELLED'; }; + /** 判断订单是否已转销售订单 */ + OrderStockout.prototype.isTransferred = function() { + return this.order_status === 'TRANSFERRED'; + }; + /** 当前订单是否允许审核 */ OrderStockout.prototype.canConfirm = function() { return [ 'CREATED', 'PENDING' ].includes(this.order_status); diff --git a/app/model/store_warehouse.js b/app/model/store_warehouse.js index b839bbe..6ebb694 100644 --- a/app/model/store_warehouse.js +++ b/app/model/store_warehouse.js @@ -119,6 +119,14 @@ module.exports = app => { required: false, description: '货主在当前仓下默认使用的快递编码', }), + Object.freeze({ + key: 'stockout_default_express_code', + name: '出库单默认快递', + type: 'list', + default: 'ZT', + required: false, + description: '货主在当前仓下出库单默认使用的快递编码,默认 ZT 自提', + }), Object.freeze({ key: 'default_platform_code', name: '默认平台', @@ -729,6 +737,10 @@ module.exports = app => { value: normalizePolicyConfigOptionValue(item), label: String(item.name || item.code || ''), })), + stockout_default_express_code: expressRows.map(item => ({ + value: normalizePolicyConfigOptionValue(item), + label: String(item.name || item.code || ''), + })), default_platform_code: platformRows.map(item => ({ value: normalizePolicyConfigOptionValue(item), label: String(item.name || item.code || ''), diff --git a/app/service/qimenMethods/order.js b/app/service/qimenMethods/order.js index 570c7ee..0501d0c 100644 --- a/app/service/qimenMethods/order.js +++ b/app/service/qimenMethods/order.js @@ -179,10 +179,35 @@ class orderServer extends MainService { }); if (!existingOrder) { + // current 表未命中时回退查询配送域表(dispatch): + // 订单已流转到配送表中且已取消,视为取消成功(幂等),直接返回 + const DispatchModel = await ctx.model.OrderDeliveryFactory.getDispatchModel(info.warehouseId); + const dispatchOrder = await DispatchModel.findOne({ + where: { + delivery_order_code: orderCode, + warehouse_id: info.warehouseId, + store_id: info.storeId, + }, + transaction, + lock: transaction.LOCK.UPDATE, + }); + + if (dispatchOrder && String(dispatchOrder.status || '').trim() === 'cancel') { + await transaction.rollback(); + return this.success('取消订单成功'); + } + await transaction.rollback(); return this.fail('未找到对应的订单'); } + // 幂等处理:订单在配送表中且已取消,直接返回取消成功 + const currentStatus = String(existingOrder.status || '').trim(); + if (currentStatus === 'cancel') { + await transaction.rollback(); + return this.success('取消订单成功'); + } + const pickStatus = String(existingOrder.pick_status || 'none').trim(); const printStatus = String(existingOrder.print_status || 'none').trim(); diff --git a/app/service/qimenMethods/stockout.js b/app/service/qimenMethods/stockout.js index 6c22db8..f1e1d46 100644 --- a/app/service/qimenMethods/stockout.js +++ b/app/service/qimenMethods/stockout.js @@ -40,6 +40,91 @@ class stockoutServer extends MainService { const totalOrderLines = deliveryOrder.totalOrderLines || orderLine.length; + // 快递编码解析(简化口径,独立于订单兜底链): + // 1. 货主开启 enable_external_express_code 且传了 logisticsCode 时,按 + // wms_express_setting 映射 → 系统快递列表 匹配; + // 2. 未传 / 未开启 / 匹配不到 → 使用出库单兜底快递编码(stockout_default_express_code, + // 默认 ZT 自提),不再回退订单默认快递;不走订单的快递策略漏斗(matchPolicy)。 + let expressCode = null; + let expressName = null; + try { + const deliveryOrderService = ctx.service.systems.deliveryOrder; + const policyConfig = await deliveryOrderService.getStoreWarehousePolicyConfig(storeId, warehouseId); + const expressList = await ctx.service.systems.express.getExpressList(); + const findExpress = code => { + const upperCode = String(code || '').trim().toUpperCase(); + if (!upperCode || !Array.isArray(expressList)) { + return null; + } + return expressList.find(item => item + && String(item.code || item.value || '').trim().toUpperCase() === upperCode) || null; + }; + const externalCode = String(deliveryOrder.logisticsCode || '').trim(); + const enableExternal = deliveryOrderService.normalizePolicyFlag( + policyConfig && policyConfig.enable_external_express_code + ); + + if (enableExternal && externalCode) { + // 1) wms_express_setting 外部编码映射 → 系统快递编码 + const settingSnapshot = await deliveryOrderService.resolveExpressSettingSnapshot(externalCode, warehouseId); + if (settingSnapshot && settingSnapshot.expressCode) { + const sysCode = String(settingSnapshot.expressCode).trim(); + const sysItem = findExpress(sysCode); + expressCode = sysCode; + expressName = sysItem + ? String(sysItem.name || sysItem.label || sysCode).trim() + : String(settingSnapshot.name || sysCode).trim(); + } else { + // 2) 系统快递列表直接匹配 + const matched = findExpress(externalCode); + if (matched) { + expressCode = String(matched.code || matched.value || externalCode).trim(); + expressName = String(matched.name || matched.label || expressCode).trim(); + } + } + } + + if (!expressCode) { + // 兜底:出库单兜底快递编码(货主配置,默认 ZT 自提),不回退订单默认快递 + const fallbackCode = String(policyConfig && policyConfig.stockout_default_express_code || '').trim() || 'ZT'; + const fallbackItem = findExpress(fallbackCode); + expressCode = fallbackItem + ? String(fallbackItem.code || fallbackItem.value || fallbackCode).trim() + : fallbackCode; + expressName = fallbackItem + ? String(fallbackItem.name || fallbackItem.label || fallbackCode).trim() + : fallbackCode; + } + } catch (err) { + ctx.logger.warn(`[stockout.create] 快递编码解析失败,保持为空: ${err.message}`); + } + + // 收件人信息解析(receiverInfo 13 个标准字段落库,供转订单与确认回传使用) + const receiver = deliveryOrder.receiverInfo && typeof deliveryOrder.receiverInfo === 'object' + ? deliveryOrder.receiverInfo + : {}; + const receiverFields = { + receiver_company: receiver.company, + receiver_name: receiver.name, + receiver_zip_code: receiver.zipCode, + receiver_tel: receiver.tel, + receiver_mobile: receiver.mobile, + receiver_email: receiver.email, + receiver_country_code: receiver.countryCode, + receiver_province: receiver.province, + receiver_city: receiver.city, + receiver_area: receiver.area, + receiver_town: receiver.town, + receiver_detail_address: receiver.detailAddress, + receiver_id: receiver.id, + }; + for (const key of Object.keys(receiverFields)) { + const rawValue = receiverFields[key]; + receiverFields[key] = rawValue === undefined || rawValue === null + ? null + : String(rawValue).trim() || null; + } + // 第一步:校验所有商品是否在 StockStore 中存在,并收集有效明细 const errors = []; const items = []; @@ -114,6 +199,9 @@ class stockoutServer extends MainService { ? new Date(deliveryOrder.createTime) : null, remark: deliveryOrder.remark || null, + express_code: expressCode, + express_name: expressName, + ...receiverFields, warehouse_id: warehouseId, store_id: storeId, qimen_owner_code: items[0].ownerCode, diff --git a/app/service/systemMethods/order/base.js b/app/service/systemMethods/order/base.js index 81c121d..5722385 100644 --- a/app/service/systemMethods/order/base.js +++ b/app/service/systemMethods/order/base.js @@ -61,6 +61,7 @@ const CREATE_CHANNEL_LABELS = Object.freeze({ MANUAL: '手工单', API: '接口', QM: '奇门', + STOCKOUT: '出库转单', }); const ORDER_TABLE_TYPE_ALIASES = Object.freeze({ current: 'current', diff --git a/app/service/systemMethods/storage/delivery.js b/app/service/systemMethods/storage/delivery.js index 4fda3d5..7ebcbbe 100644 --- a/app/service/systemMethods/storage/delivery.js +++ b/app/service/systemMethods/storage/delivery.js @@ -26,11 +26,12 @@ class StorageDeliveryService extends MainService { } /** - * 出库单跳转订单占位接口(兼容转发)。 - * @return {Promise} 占位失败结果 + * 出库单转订单(兼容转发)。 + * @param {Object} data 请求体 + * @return {Promise} 转订单结果 */ - async toOrder() { - return await this.ctx.service.systemMethods.storage.stockout.toOrder(); + async toOrder(data = {}) { + return await this.ctx.service.systemMethods.storage.stockout.toOrder(data); } /** diff --git a/app/service/systemMethods/storage/stockout.js b/app/service/systemMethods/storage/stockout.js index d91bd6f..e434bb3 100644 --- a/app/service/systemMethods/storage/stockout.js +++ b/app/service/systemMethods/storage/stockout.js @@ -103,11 +103,265 @@ class StorageStockoutService extends MainService { } /** - * 出库单转订单占位接口。 - * @return {Promise} 统一失败包装响应 + * 出库单转订单。 + * + * 将非订单出库单(wms_order_stockout)转为正式销售订单: + * 1. 新订单 create_channel 固定为 STOCKOUT; + * 2. 释放出库单占用的库存锁定,转由新订单重新锁定; + * 3. 转单成功后原出库单置为 CANCELLED,并记录已转订单号(幂等)。 + * + * 仅 CREATED / PENDING 状态的出库单允许转单;建单失败时自动补偿恢复出库单锁定。 + * + * @param {Object} data 请求体 + * @param {number} data.id 出库单ID(必填) + * @param {string} [data.delivery_order_code] 新订单号,不传自动生成(SK 前缀) + * @param {Object} [data.receiverInfo] 收件人信息(name/mobile/tel/province/city/area/town/detailAddress/zipCode) + * @return {Promise} 统一成功/失败包装响应 */ - async toOrder() { - return this.fail('接口暂未开放'); + async toOrder(data = {}) { + const { ctx } = this; + const id = Number(data.id || 0); + + if (!id) { + return this.fail('缺少出库单ID'); + } + + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + if (warehouseId <= 0) { + return this.fail('缺少仓库上下文'); + } + + const order = await ctx.model.OrderStockout.findOne({ + where: { id, warehouse_id: warehouseId, deleted_at: null }, + }); + if (!order) { + return this.fail('出库单不存在'); + } + + // 幂等:已转订单的出库单直接返回原订单信息 + const currentExtendProps = + order.extend_props && typeof order.extend_props === 'object' && !Array.isArray(order.extend_props) + ? order.extend_props + : {}; + if (currentExtendProps.transferred_order_id) { + return this.success('出库单已转订单', { + id: order.id, + stockout_order_code: order.stockout_order_code, + order_id: currentExtendProps.transferred_order_id, + delivery_order_code: currentExtendProps.transferred_order_code || '', + }); + } + + if (![ 'CREATED', 'PENDING' ].includes(order.order_status)) { + return this.fail(`出库单当前状态(${order.order_status})不允许转订单`); + } + + const items = await ctx.model.OrderStockoutItems.findAll({ + where: { order_id: order.id }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + if (!items || items.length === 0) { + return this.fail('出库单没有明细,无法转订单'); + } + + // 收货信息:出库单已存的 receiver_* 字段为基础,接口传入的非空 receiverInfo 字段覆盖 + const storedReceiverInfo = { + company: order.receiver_company || '', + name: order.receiver_name || '', + zipCode: order.receiver_zip_code || '', + tel: order.receiver_tel || '', + mobile: order.receiver_mobile || '', + email: order.receiver_email || '', + countryCode: order.receiver_country_code || '', + province: order.receiver_province || '', + city: order.receiver_city || '', + area: order.receiver_area || '', + town: order.receiver_town || '', + detailAddress: order.receiver_detail_address || '', + }; + const passedReceiverInfo = data.receiverInfo && typeof data.receiverInfo === 'object' + ? data.receiverInfo + : {}; + const receiverInfo = { ...storedReceiverInfo }; + for (const [ key, value ] of Object.entries(passedReceiverInfo)) { + if (value !== undefined && value !== null && String(value).trim() !== '') { + receiverInfo[key] = String(value).trim(); + } + } + + // 收货信息必填校验:name、(tel/mobile) 其一、省市区镇详细地址,缺失禁止转订单 + const missingFields = []; + if (!String(receiverInfo.name || '').trim()) { + missingFields.push('name(收件人姓名)'); + } + const receiverTel = String(receiverInfo.tel || '').trim(); + const receiverMobile = String(receiverInfo.mobile || '').trim(); + if (!receiverTel && !receiverMobile) { + missingFields.push('tel/mobile(固定电话或移动电话至少一项)'); + } + const addressFields = [ + [ 'province', '省' ], + [ 'city', '市' ], + [ 'area', '区' ], + [ 'town', '镇' ], + [ 'detailAddress', '详细地址' ], + ]; + for (const [ key, label ] of addressFields) { + if (!String(receiverInfo[key] || '').trim()) { + missingFields.push(`${key}(${label})`); + } + } + if (missingFields.length > 0) { + return this.fail(`收货信息缺失,不能转订单:缺少 ${missingFields.join('、')}`); + } + + const stockStoreService = ctx.service.systems.stockStore; + const lockMeta = { + orderType: 'QM_STOCKOUT', + orderNo: order.stockout_order_code, + orderId: order.id, + }; + + // 第一步:释放出库单占用的库存锁定(新订单创建时会重新锁定) + const releaseTransaction = await ctx.model.transaction(); + try { + for (const item of items) { + const qty = Number(item.plan_qty) || 0; + if (qty <= 0) continue; + const releaseResult = await stockStoreService.lockItemStorages( + item.stock_id, + -qty, + releaseTransaction, + null, + { ...lockMeta, remark: '出库单转订单释放锁定' } + ); + if (!releaseResult.success) { + throw new Error(`库存${item.stock_id}释放锁定失败: ${releaseResult.error}`); + } + } + await releaseTransaction.commit(); + } catch (err) { + await releaseTransaction.rollback().catch(() => {}); + ctx.logger.error(`[stockout.toOrder] 释放出库单锁定失败: ${err.message}`); + return this.fail(`转订单失败:${err.message}`); + } + + // 第二步:创建订单(create_channel=STOCKOUT,内部重新锁定库存) + // 快递编码沿用出库单已解析的 express_code(系统快递编码),平台不传 sourcePlatformCode 走兜底平台 + const deliveryOrderCode = String(data.delivery_order_code || '').trim() + || `SK${Date.now()}${Math.floor(Math.random() * 9000) + 1000}`; + + const orderLines = items.map((item, idx) => ({ + itemCode: item.item_code || '', + itemId: Number(item.item_id) || 0, + itemName: item.item_name || '', + planQty: Number(item.plan_qty) || 0, + stockId: Number(item.stock_id) || 0, + inventoryType: item.inventory_type || '', + orderLineNo: String(item.order_line_no || idx + 1), + ownerCode: item.owner_code || '', + sourceOrderCode: order.stockout_order_code, + })); + + const addOrderData = { + request: { + deliveryOrder: { + deliveryOrderCode, + orderType: order.order_type || 'QTCK', + createChannel: 'STOCKOUT', + logisticsCode: order.express_code || '', + sourcePlatformCode: order.source_platform_code || '', + receiverInfo, + remark: order.remark || '', + sourceOrderCode: order.stockout_order_code, + }, + orderLines: { orderLine: orderLines }, + }, + }; + + const info = { + storeId: order.store_id, + warehouseId, + appKey: (ctx.user && ctx.user.app_key) || '', + }; + + let addOrderResult = null; + try { + addOrderResult = await ctx.service.systems.deliveryOrder.addOrder(addOrderData, info, 'STOCKOUT'); + } catch (err) { + addOrderResult = { success: false, message: err.message, data: null }; + } + + const orderId = addOrderResult && addOrderResult.data && addOrderResult.data.orderId; + const isDuplicate = !!(addOrderResult && addOrderResult.success && addOrderResult.message === '订单已存在'); + + if (!addOrderResult || !addOrderResult.success || !orderId || isDuplicate) { + // 建单失败/订单号重复:补偿恢复出库单锁定 + await this._restoreStockoutLocks(stockStoreService, items, lockMeta, ctx); + return this.fail(`转订单失败:${(addOrderResult && addOrderResult.message) || '订单创建失败'}`); + } + + // 第三步:标记出库单已转订单(状态推进到 TRANSFERRED,该状态下禁止一键出库) + try { + await ctx.model.OrderStockout.update( + { + order_status: 'TRANSFERRED', + sync_message: `已转订单 ${deliveryOrderCode}`, + extend_props: { + ...currentExtendProps, + transferred_order_id: orderId, + transferred_order_code: deliveryOrderCode, + transferred_at: new Date(), + }, + updated_at: new Date(), + }, + { where: { id: order.id } } + ); + } catch (updateErr) { + // 订单已创建成功,仅出库单标记失败:记录告警,不回滚订单 + ctx.logger.error(`[stockout.toOrder] 标记出库单已转失败: ${updateErr.message}`); + } + + return this.success('转订单成功', { + id: order.id, + stockout_order_code: order.stockout_order_code, + order_id: orderId, + delivery_order_code: deliveryOrderCode, + step: addOrderResult.data.step, + }); + } + + /** + * 转订单失败时恢复出库单库存锁定(补偿)。 + * @param {Object} stockStoreService 库存服务 + * @param {Array} items 出库单明细 + * @param {Object} lockMeta 锁元信息 + * @param {Object} ctx 请求上下文 + * @return {Promise} 无返回值 + */ + async _restoreStockoutLocks(stockStoreService, items, lockMeta, ctx) { + const restoreTransaction = await ctx.model.transaction(); + try { + for (const item of items) { + const qty = Number(item.plan_qty) || 0; + if (qty <= 0) continue; + const restoreResult = await stockStoreService.lockItemStorages( + item.stock_id, + qty, + restoreTransaction, + null, + { ...lockMeta, remark: '出库单转订单失败恢复锁定' } + ); + if (!restoreResult.success) { + throw new Error(`库存${item.stock_id}恢复锁定失败: ${restoreResult.error}`); + } + } + await restoreTransaction.commit(); + } catch (err) { + await restoreTransaction.rollback().catch(() => {}); + ctx.logger.error(`[stockout.toOrder] 恢复出库单锁定失败: ${err.message}`); + } } /** @@ -392,6 +646,153 @@ class StorageStockoutService extends MainService { waybill_codes: order.waybill_codes, }); } + + /** + * 修改出库单信息。 + * + * 可修改范围:收件人(name/tel/mobile 等)、地址(province/city/area/town/detailAddress 等)、 + * 快递编码(express_code,自动解析 express_name)、来源平台(source_platform_code/name)。 + * 未传入的字段不修改;快递编码与平台相关字段不传即保持原值。 + * + * 限制:仅 CREATED / PENDING 状态允许修改;修改后收货信息不完整(name、(tel/mobile) 其一、 + * 省市区镇详细地址缺任一)时禁止提交。 + * + * @param {Object} data 请求体 + * @param {number} data.id 出库单ID(必填) + * @param {string} [data.name] 收件人姓名 + * @param {string} [data.tel] 固定电话 + * @param {string} [data.mobile] 移动电话 + * @param {string} [data.company] 公司名称 + * @param {string} [data.email] 电子邮箱 + * @param {string} [data.zipCode] 邮编 + * @param {string} [data.countryCode] 国家二字码 + * @param {string} [data.province] 省份 + * @param {string} [data.city] 城市 + * @param {string} [data.area] 区/县 + * @param {string} [data.town] 镇/街道 + * @param {string} [data.detailAddress] 详细地址 + * @param {string} [data.express_code] 快递公司编码(自动解析 express_name) + * @param {string} [data.source_platform_code] 来源平台编码 + * @param {string} [data.source_platform_name] 来源平台名称 + * @return {Promise} 统一成功/失败包装响应 + */ + async updateInfo(data = {}) { + const { ctx } = this; + const id = Number(data.id || 0); + + if (!id) { + return this.fail('缺少出库单ID'); + } + + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + if (warehouseId <= 0) { + return this.fail('缺少仓库上下文'); + } + + const order = await ctx.model.OrderStockout.findOne({ + where: { id, warehouse_id: warehouseId, deleted_at: null }, + }); + if (!order) { + return this.fail('出库单不存在'); + } + + if (![ 'CREATED', 'PENDING' ].includes(order.order_status)) { + return this.fail(`出库单当前状态(${order.order_status})不允许修改`); + } + + const updateData = { updated_at: new Date() }; + + // 收件人 / 地址字段:传入才更新,空串置 NULL + const receiverFieldMap = { + receiver_name: 'name', + receiver_tel: 'tel', + receiver_mobile: 'mobile', + receiver_company: 'company', + receiver_email: 'email', + receiver_zip_code: 'zipCode', + receiver_country_code: 'countryCode', + receiver_province: 'province', + receiver_city: 'city', + receiver_area: 'area', + receiver_town: 'town', + receiver_detail_address: 'detailAddress', + receiver_id: 'id', + }; + for (const [ column, param ] of Object.entries(receiverFieldMap)) { + if (data[param] !== undefined) { + updateData[column] = data[param] === null + ? null + : String(data[param]).trim() || null; + } + } + + // 快递编码:传入才更新,并自动解析 express_name(与 updateExpress 同口径) + if (data.express_code !== undefined) { + const expressCode = String(data.express_code || '').trim(); + if (expressCode) { + let expressName = ''; + try { + const expressMap = await ctx.service.systems.setting.express.getSystemExpressMap(); + const info = expressMap.get(expressCode.toUpperCase()); + expressName = info ? info.name : ''; + } catch (e) { + ctx.logger.warn('[updateInfo] 解析快递名称失败: ' + e.message); + } + updateData.express_code = expressCode; + updateData.express_name = expressName; + } else { + updateData.express_code = null; + updateData.express_name = null; + } + } + + // 来源平台:传入才更新,空串置 NULL + if (data.source_platform_code !== undefined) { + updateData.source_platform_code = String(data.source_platform_code || '').trim() || null; + } + if (data.source_platform_name !== undefined) { + updateData.source_platform_name = String(data.source_platform_name || '').trim() || null; + } + + // 修改后的收货信息完整性校验:name、(tel/mobile) 其一、省市区镇详细地址必填,缺失禁止提交 + const mergedReceiver = { + name: updateData.receiver_name !== undefined ? updateData.receiver_name : order.receiver_name, + tel: updateData.receiver_tel !== undefined ? updateData.receiver_tel : order.receiver_tel, + mobile: updateData.receiver_mobile !== undefined ? updateData.receiver_mobile : order.receiver_mobile, + province: updateData.receiver_province !== undefined ? updateData.receiver_province : order.receiver_province, + city: updateData.receiver_city !== undefined ? updateData.receiver_city : order.receiver_city, + area: updateData.receiver_area !== undefined ? updateData.receiver_area : order.receiver_area, + town: updateData.receiver_town !== undefined ? updateData.receiver_town : order.receiver_town, + detailAddress: updateData.receiver_detail_address !== undefined ? updateData.receiver_detail_address : order.receiver_detail_address, + }; + const missingFields = []; + if (!String(mergedReceiver.name || '').trim()) { + missingFields.push('name(收件人姓名)'); + } + if (!String(mergedReceiver.tel || '').trim() && !String(mergedReceiver.mobile || '').trim()) { + missingFields.push('tel/mobile(固定电话或移动电话至少一项)'); + } + const addressFields = [ + [ 'province', '省' ], + [ 'city', '市' ], + [ 'area', '区' ], + [ 'town', '镇' ], + [ 'detailAddress', '详细地址' ], + ]; + for (const [ key, label ] of addressFields) { + if (!String(mergedReceiver[key] || '').trim()) { + missingFields.push(`${key}(${label})`); + } + } + if (missingFields.length > 0) { + return this.fail(`收货信息缺失,禁止提交:缺少 ${missingFields.join('、')}`); + } + + await ctx.model.OrderStockout.update(updateData, { where: { id: order.id } }); + const updated = await ctx.model.OrderStockout.findByPk(order.id, { raw: true }); + + return this.success('修改成功', updated); + } } module.exports = StorageStockoutService; diff --git a/app/service/systemMethods/storeWarehouse/store.js b/app/service/systemMethods/storeWarehouse/store.js index 581daa0..efb2e1e 100644 --- a/app/service/systemMethods/storeWarehouse/store.js +++ b/app/service/systemMethods/storeWarehouse/store.js @@ -29,9 +29,9 @@ class StoreWarehouseStoreService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'list,sign,confirmSign,unbind,rename,openAccount,getPolicyConfig,getPolicyConfigFields,savePolicyConfig,listApiConfig,saveApiConfig,deleteQimenConfig,queryPrintQuantityLogs,queryStorePrintQuantityLogs,exportStorePrintQuantityLogs,exportStorePrintQuantityLogsTaskProgress,adjustPrintQuantity'; + const _noNeedRight = 'list,sign,confirmSign,unbind,rename,openAccount,createUser,getPolicyConfig,getPolicyConfigFields,savePolicyConfig,listApiConfig,saveApiConfig,deleteQimenConfig,queryPrintQuantityLogs,queryStorePrintQuantityLogs,exportStorePrintQuantityLogs,exportStorePrintQuantityLogsTaskProgress,adjustPrintQuantity'; const _noNeedLog = '*'; - const _noNeedAuth = 'list,sign,confirmSign,unbind,rename,openAccount,getPolicyConfig,getPolicyConfigFields,savePolicyConfig,listApiConfig,saveApiConfig,deleteQimenConfig,queryPrintQuantityLogs,queryStorePrintQuantityLogs,exportPrintQuantityLogs,exportStorePrintQuantityLogs,exportStorePrintQuantityLogsTaskProgress,adjustPrintQuantity'; + const _noNeedAuth = 'list,sign,confirmSign,unbind,rename,openAccount,createUser,getPolicyConfig,getPolicyConfigFields,savePolicyConfig,listApiConfig,saveApiConfig,deleteQimenConfig,queryPrintQuantityLogs,queryStorePrintQuantityLogs,exportStorePrintQuantityLogs,exportStorePrintQuantityLogsTaskProgress,adjustPrintQuantity'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -421,6 +421,43 @@ class StoreWarehouseStoreService extends MainService { } } + /** + * 为货主创建用户:按用户名查找账号,不存在则注册并随机生成密码返回, + * 两种情况统一完成货主工号绑定与货主管理员角色(id=5)授权。 + * + * @param {Object} data 请求数据。 + * @param {string} data.username 用户名(必填)。 + * @param {number|string} data.store_id 货主 ID(必填)。 + * @return {Promise} 统一响应结果。 + */ + async createUser(data = {}) { + const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse; + + if (!targetService || typeof targetService.createUser !== 'function') { + return this.fail('创建货主用户失败', { + code: 500, + }); + } + + try { + const requestData = normalizeStoreWarehousePayload(data); + const { + username, + store_id, + } = requestData; + + const result = await targetService.createUser({ + username, + store_id, + }); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '创建货主用户失败', { + code: Number(error.code) || 500, + }); + } + } + /** * 提交面单余额变更日志导出任务。 * 入参条件与 queryPrintQuantityLogs 的 where 语义一致,异步执行,立即返回 task_id。 diff --git a/app/service/systems/express_platform.js b/app/service/systems/express_platform.js index e0d2f67..8a4cb21 100644 --- a/app/service/systems/express_platform.js +++ b/app/service/systems/express_platform.js @@ -93,6 +93,52 @@ function isValidCainiaoTemplateUrl(templateUrl) { const DEFAULT_CAINIAO_TEMPLATE_URL = 'http://cloudprint.cainiao.com/cloudprint/template/getStandardTemplate.json?template_id=288948'; +/** + * 将仓库ID/订单ID/业务键三段标识打包为 64 位无符号整数(Uint64)。 + * + * 位宽分配("不够的补位"由左移自动补 0 完成): + * - warehouse_id:高 24 bit(hex 6 位,0x000000 ~ 0xFFFFFF) + * - order_id :中 32 bit(hex 8 位,0x00000000 ~ 0xFFFFFFFF) + * - business_key:低 8 bit (hex 2 位,0x00 ~ 0xFF) + * 合计 64 bit,拼出的 hex 固定 16 位(不足高位补 0)。 + * + * 例:f425c_3948e_1 → hex 补位 0f425c0003948e01 → 1099542414161645057 + * + * 纯函数(幂等):不含时间/随机因素,相同入参必然输出相同 Uint64,可安全重试。 + * + * @param {number|string} warehouseId 仓库ID。 + * @param {number|string} orderId 订单ID。 + * @param {number|string} businessKey 业务键(1=主单号,>1=子单号)。 + * @return {string} Uint64 的十进制字符串(超过 JS 安全整数 2^53,必须用字符串形式传输/序列化)。 + */ +/* eslint-disable no-bitwise -- Uint64 位打包/拆解必须使用位运算 */ +function toUint64(warehouseId, orderId, businessKey) { + const wh = BigInt(Number(warehouseId) || 0); + const oid = BigInt(Number(orderId) || 0); + const bk = BigInt(Number(businessKey) || 0); + if (wh < 0n || wh > 0xFFFFFFn) throw new Error(`toUint64: warehouse_id 超出 24 位范围: ${warehouseId}`); + if (oid < 0n || oid > 0xFFFFFFFFn) throw new Error(`toUint64: order_id 超出 32 位范围: ${orderId}`); + if (bk < 0n || bk > 0xFFn) throw new Error(`toUint64: business_key 超出 8 位范围: ${businessKey}`); + return ((wh << 40n) | (oid << 8n) | bk).toString(); +} + +/** + * 将 Uint64 反向拆解为仓库ID/订单ID/业务键(toUint64 的逆运算)。 + * + * @param {string|number|bigint} value Uint64 值(十进制字符串/数字/BigInt 均可)。 + * @return {{ warehouseId: number, orderId: number, businessKey: number }} 拆解结果。 + */ +function fromUint64(value) { + const v = BigInt(value); + if (v < 0n || v > 0xFFFFFFFFFFFFFFFFn) throw new Error(`fromUint64: 超出 64 位范围: ${value}`); + return { + warehouseId: Number(v >> 40n), + orderId: Number((v >> 8n) & 0xFFFFFFFFn), + businessKey: Number(v & 0xFFn), + }; +} +/* eslint-enable no-bitwise */ + /** * 快递平台服务类。 * @@ -717,7 +763,9 @@ class ExpressPlatformService extends MainService { logistictype: expressListItem[listByWarehousePlatformCode.platform_code] || '', providercode: expressListItem[listByWarehousePlatformCode.platform_code] || order.logistics_code || '', numpackage: order.package_count || '1', - businesstype: listByWarehousePlatformCode.product_type, + Businesstype: listByWarehousePlatformCode.product_type, + Expresstype: listByWarehousePlatformCode.product_type, + ProductType: listByWarehousePlatformCode.product_type || '', transtype: '0', transtypecode: '1', mainsubpaymode: '1', @@ -735,7 +783,6 @@ class ExpressPlatformService extends MainService { height: Number(order.height) || 0, volume: Number(order.volume) || 0, ispickup: listByWarehousePlatformCode.ispickup ?? 0, - ProductType: listByWarehousePlatformCode.product_type || '', Sipshopid: listByWarehousePlatformCode.platform_shop_id || '', oaid: order.oaid || '', cpcode: expressListItem[listByWarehousePlatformCode.platform_code] || '', @@ -894,10 +941,11 @@ class ExpressPlatformService extends MainService { } } if (matchedPlatform.platid === 672) { - if (!order.source_order_codes) { + /* if (!order.source_order_codes) { throw new Error('订单数据错误,缺失平台订单号'); } - playload.object_Id = order.source_order_codes.split(',')[0]; + */ + playload.object_Id = toUint64(order.warehouse_id, order.id, order_tmp.business_key); if (!order.extend_props.ewaybill_order_code) { throw new Error('订单数据错误,参数不全缺失extend_props.ewaybill_order_code,请复制次信息给ERP方反馈'); } @@ -2389,7 +2437,7 @@ class ExpressPlatformService extends MainService { object_id: `${order_tmp.order_delivery.warehouse_id}_${order_tmp.order_delivery.id}_${order_tmp.business_key}`, order_info: { order_channels_type: 'PDD', - trade_order_list: order_tmp.order_delivery && order_tmp.order_delivery.source_order_codes ? order_tmp.order_delivery.source_order_codes.split(',') : [ order_tmp.order_delivery && order_tmp.order_delivery.delivery_order_code || '' ], + trade_order_list: [`${order_tmp.order_delivery.warehouse_id}_${order_tmp.order_delivery.id}_${order_tmp.business_key}`], }, package_info: { items: (order_tmp.order_delivery && order_tmp.order_delivery.orderItems || []).map(item => ({ @@ -2397,6 +2445,7 @@ class ExpressPlatformService extends MainService { count: item.plan_qty, })) || [], id: `${order_tmp.order_delivery.warehouse_id}_${order_tmp.order_delivery.id}_${order_tmp.business_key}`, + total_packages_count: order_tmp.business_key || 1, }, recipient: { address: { @@ -2443,6 +2492,9 @@ class ExpressPlatformService extends MainService { }, }; console.log('拼多多平台接口构建的请求参数', JSON.stringify(pddPayload, null, 2)); + + await this.app.setCacheAsync('Pddquery', JSON.stringify(pddPayload), 3600); + // 这里写一个调用pdd_client的入参示例 // // @@ -2491,6 +2543,8 @@ class ExpressPlatformService extends MainService { data: builtRequest.requestBody, }); + await this.app.setCacheAsync('Pddresult', JSON.stringify(response), 3600); + const responseData = response && Object.prototype.hasOwnProperty.call(response, 'data') ? response.data : response; @@ -2791,4 +2845,8 @@ class ExpressPlatformService extends MainService { } } +// 静态挂载 Uint64 工具:供回包解析(SPH object_Id 反解)等场景复用 +ExpressPlatformService.toUint64 = toUint64; +ExpressPlatformService.fromUint64 = fromUint64; + module.exports = ExpressPlatformService; diff --git a/app/service/systems/store_warehouse.js b/app/service/systems/store_warehouse.js index 7cba590..8ca8be5 100644 --- a/app/service/systems/store_warehouse.js +++ b/app/service/systems/store_warehouse.js @@ -3276,6 +3276,167 @@ class SettingStoreWarehouseService extends Service { throw error; } } + + /** + * 为货主创建用户:按用户名查询账号,不存在则注册账号并返回随机生成的密码, + * 两种情况统一完成货主工号绑定与货主管理员角色(wms_role.id=5)授权,幂等执行。 + * 货主审核中(wms_store.status=2)时自动转为启用(1)。 + * + * @param {Object} [data={}] 请求参数。 + * @param {string} data.username 用户名(必填,3-50 位字母、数字或下划线)。 + * @param {number|string} data.store_id 货主 ID(必填)。 + * @return {Promise} 响应对象,data 包含 account_id、username、store_id、created; + * 仅新建账号时返回 password 明文密码。 + * @throws {Error} 参数缺失或格式非法时抛出 400,货主不存在时抛出 404, + * 货主管理员角色未初始化时抛出 500。 + */ + async createUser(data = {}) { + const { ctx } = this; + const { + username: rawUsername, + store_id: rawStoreId, + } = data; + + // 1. 校验必填参数 + const username = this.normalizeText(rawUsername, 'username', 50); + if (!username) { + throw this.createError('username 参数不能为空', 400); + } + if (!/^[a-zA-Z0-9_]{3,50}$/.test(username)) { + throw this.createError('用户名格式不合法,需为 3-50 位字母、数字或下划线', 400); + } + const storeId = this.toPositiveNumber(rawStoreId, 'store_id'); + + // 2. 校验货主存在(同时取 status 用于后续审核中状态修正) + const store = await ctx.model.Store.findOne({ + where: { id: storeId }, + attributes: [ 'id', 'status' ], + }); + if (!store) { + throw this.createError('货主不存在', 404); + } + + // 3. 查询账号是否存在 + const existingAccount = await ctx.model.Account.findOne({ + where: { username }, + attributes: [ 'id', 'username' ], + }); + + // 4. 随机生成密码(仅新建账号时使用) + const randomPassword = crypto.randomBytes(8).toString('base64').replace(/[+/=]/g, '') + .slice(0, 12); + + // 5. 事务内执行账号创建与授权绑定 + const transaction = await ctx.model.transaction(); + + try { + // 5.0 货主审核中(status=2)时自动转为启用(1),store 实例在事务外查询,更新时显式传入事务 + if (Number(store.status) === 2) { + await store.update({ status: 1 }, { transaction }); + } + + let accountId = null; + let created = false; + + if (existingAccount) { + // 账号已存在:不创建、不返回密码 + accountId = Number(existingAccount.id); + created = false; + } else { + // 账号不存在:复用注册服务,email/real_name 使用占位兜底 + const registerResult = await ctx.service.systems.auth.user.register({ + username, + password: randomPassword, + email: `${username}@placeholder.local`, + real_name: username, + }, transaction); + accountId = Number(registerResult.userId); + created = true; + } + + // 6. 货主工号绑定(幂等:已存在但 status=0 时恢复为 1) + const [ employee ] = await ctx.model.AccountStoreEmployee.findOrCreate({ + where: { + account_id: accountId, + store_id: storeId, + }, + defaults: { + account_id: accountId, + store_id: storeId, + status: 1, + real_name: username, + }, + transaction, + }); + + if (Number(employee.status) !== 1) { + await employee.update({ + status: 1, + }, { transaction }); + } + + // 7. 确认货主管理员角色(wms_role.id=5)已初始化 + const storeAdminRole = await ctx.model.Role.findByPk(5, { transaction }); + if (!storeAdminRole) { + throw this.createError('货主管理员角色(id=5)未初始化', 500); + } + + // 8. 授予货主管理员角色(幂等:findOrCreate) + await ctx.model.EmployeeRole.findOrCreate({ + where: { + employee_id: employee.id, + role_id: 5, + }, + defaults: { + employee_id: employee.id, + role_id: 5, + }, + transaction, + }); + + await transaction.commit(); + + // 9. 记录操作日志(不影响业务主流程) + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'store', + businessId: storeId, + operationCode: 'STORE_CREATE_USER', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + storeId: Number(storeId), + accountId: Number(accountId), + created, + }, + beforeChanges: null, + }); + } catch (logErr) { + ctx.logger.warn('[storeWarehouse.createUser] 写入操作日志失败,不影响业务', logErr); + } + + // 10. 组装响应:仅新建账号时返回明文密码 + const resultData = { + account_id: accountId, + username, + store_id: storeId, + created, + }; + if (created) { + resultData.password = randomPassword; + } + + return { + code: 200, + data: resultData, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } } module.exports = SettingStoreWarehouseService; diff --git a/database/migrations/20260825170000-add-receiver-info-to-wms-order-stockout.js b/database/migrations/20260825170000-add-receiver-info-to-wms-order-stockout.js new file mode 100644 index 0000000..327aa8f --- /dev/null +++ b/database/migrations/20260825170000-add-receiver-info-to-wms-order-stockout.js @@ -0,0 +1,66 @@ +'use strict'; + +const TABLE = 'wms_order_stockout'; + +/** + * 为出库单主表添加收件人信息字段(对应奇门 stockout.create 报文 receiverInfo 节点)。 + * + * 字段与奇门 receiverInfo 一一对应,列名统一加 receiver_ 前缀避免与订单表口径混淆。 + */ +module.exports = { + up: async (queryInterface, Sequelize) => { + const columns = await queryInterface.describeTable(TABLE); + + const receiverColumns = [ + { name: 'receiver_company', type: Sequelize.STRING(200), comment: '收件人公司名称(receiverInfo.company)' }, + { name: 'receiver_name', type: Sequelize.STRING(50), comment: '收件人姓名(receiverInfo.name)' }, + { name: 'receiver_zip_code', type: Sequelize.STRING(50), comment: '收件人邮编(receiverInfo.zipCode)' }, + { name: 'receiver_tel', type: Sequelize.STRING(50), comment: '收件人固定电话(receiverInfo.tel)' }, + { name: 'receiver_mobile', type: Sequelize.STRING(50), comment: '收件人移动电话(receiverInfo.mobile)' }, + { name: 'receiver_email', type: Sequelize.STRING(50), comment: '收件人电子邮箱(receiverInfo.email)' }, + { name: 'receiver_country_code', type: Sequelize.STRING(50), comment: '收件人国家二字码(receiverInfo.countryCode)' }, + { name: 'receiver_province', type: Sequelize.STRING(50), comment: '收件人省份(receiverInfo.province)' }, + { name: 'receiver_city', type: Sequelize.STRING(50), comment: '收件人城市(receiverInfo.city)' }, + { name: 'receiver_area', type: Sequelize.STRING(50), comment: '收件人区域(receiverInfo.area)' }, + { name: 'receiver_town', type: Sequelize.STRING(50), comment: '收件人村镇(receiverInfo.town)' }, + { name: 'receiver_detail_address', type: Sequelize.STRING(200), comment: '收件人详细地址(receiverInfo.detailAddress)' }, + { name: 'receiver_id', type: Sequelize.STRING(50), comment: '收件人证件号(receiverInfo.id)' }, + ]; + + for (const item of receiverColumns) { + if (!columns[item.name]) { + await queryInterface.addColumn(TABLE, item.name, { + type: item.type, + allowNull: true, + comment: item.comment, + }); + } + } + }, + + down: async queryInterface => { + const columns = await queryInterface.describeTable(TABLE); + + const receiverColumnNames = [ + 'receiver_company', + 'receiver_name', + 'receiver_zip_code', + 'receiver_tel', + 'receiver_mobile', + 'receiver_email', + 'receiver_country_code', + 'receiver_province', + 'receiver_city', + 'receiver_area', + 'receiver_town', + 'receiver_detail_address', + 'receiver_id', + ]; + + for (const name of receiverColumnNames) { + if (columns[name]) { + await queryInterface.removeColumn(TABLE, name); + } + } + }, +}; diff --git a/database/migrations/20260825180000-add-transferred-status-and-platform-to-wms-order-stockout.js b/database/migrations/20260825180000-add-transferred-status-and-platform-to-wms-order-stockout.js new file mode 100644 index 0000000..e6376e1 --- /dev/null +++ b/database/migrations/20260825180000-add-transferred-status-and-platform-to-wms-order-stockout.js @@ -0,0 +1,68 @@ +'use strict'; + +const TABLE = 'wms_order_stockout'; + +/** + * 出库单补充迁移: + * 1. order_status ENUM 追加 TRANSFERRED(已转订单),转订单成功后使用该状态; + * 2. 新增平台字段 source_platform_code / source_platform_name(修改接口"平台相关"与转订单回传使用)。 + */ +module.exports = { + up: async (queryInterface, Sequelize) => { + const columns = await queryInterface.describeTable(TABLE); + + // 1. order_status ENUM 追加 TRANSFERRED(保持默认值与原注释) + const statusType = String(columns.order_status && columns.order_status.type || '').toUpperCase(); + if (statusType && !statusType.includes("'TRANSFERRED'")) { + await queryInterface.sequelize.query( + 'ALTER TABLE `wms_order_stockout` MODIFY COLUMN `order_status` ' + + 'ENUM(\'CREATING\',\'CREATED\',\'PENDING\',\'COMPLETED\',\'CANCELLED\',\'TRANSFERRED\') ' + + 'NOT NULL DEFAULT \'CREATED\' ' + + 'COMMENT \'订单状态:CREATING=创建中, CREATED=已创建待审核, PENDING=已审核, COMPLETED=已完成, CANCELLED=已作废, TRANSFERRED=已转订单\'' + ); + } + + // 2. 平台字段 + if (!columns.source_platform_code) { + await queryInterface.addColumn(TABLE, 'source_platform_code', { + type: Sequelize.STRING(50), + allowNull: true, + comment: '来源平台编码(转订单时优先使用,为空时兜底平台)', + }); + } + + if (!columns.source_platform_name) { + await queryInterface.addColumn(TABLE, 'source_platform_name', { + type: Sequelize.STRING(200), + allowNull: true, + comment: '来源平台名称快照', + }); + } + }, + + down: async queryInterface => { + const columns = await queryInterface.describeTable(TABLE); + + // 已转订单的行先回退为已作废,再收缩 ENUM + const statusType = String(columns.order_status && columns.order_status.type || '').toUpperCase(); + if (statusType && statusType.includes("'TRANSFERRED'")) { + await queryInterface.sequelize.query( + 'UPDATE `wms_order_stockout` SET `order_status` = \'CANCELLED\' WHERE `order_status` = \'TRANSFERRED\'' + ); + await queryInterface.sequelize.query( + 'ALTER TABLE `wms_order_stockout` MODIFY COLUMN `order_status` ' + + 'ENUM(\'CREATING\',\'CREATED\',\'PENDING\',\'COMPLETED\',\'CANCELLED\') ' + + 'NOT NULL DEFAULT \'CREATED\' ' + + 'COMMENT \'订单状态:CREATING=创建中, CREATED=已创建待审核, PENDING=已审核, COMPLETED=已完成, CANCELLED=已作废\'' + ); + } + + if (columns.source_platform_code) { + await queryInterface.removeColumn(TABLE, 'source_platform_code'); + } + + if (columns.source_platform_name) { + await queryInterface.removeColumn(TABLE, 'source_platform_name'); + } + }, +}; diff --git a/methods/changes/qimen.json b/methods/changes/qimen.json index aa94da4..e92ae8d 100644 --- a/methods/changes/qimen.json +++ b/methods/changes/qimen.json @@ -1,4 +1,50 @@ [ + { + "version": "2026.08.25-stockout-create-express-fallback-zt", + "date": "2026-08-25", + "summary": "stockout.create 快递兜底口径调整:兜底仅使用出库单兜底快递编码(policy_config.stockout_default_express_code,默认 ZT 自提),不再回退订单默认快递(default_express_code/全局 STO);快递解析改为独立实现,不再复用订单侧 resolveExpressSnapshot 兜底链。", + "methods": [ + "stockout.create" + ], + "notes": [ + "qimenMethods/stockout.js create 快递解析重写:开启 enable_external_express_code 且传 logisticsCode 时按 wms_express_setting 映射 → 系统快递列表匹配;未传/未开启/匹配不到时取 stockout_default_express_code(为空则 'ZT'),从系统快递列表解析名称,仍不存在则编码=名称=ZT", + "app/model/store_warehouse.js POLICY_CONFIG_FIELDS:新增 stockout_default_express_code(名称:出库单默认快递,type list,default 'ZT'),getPolicyConfigFieldListWithOptions 同步注入快递选项,与 default_express_code 表现一致", + "注意:ZT 需在系统快递列表中维护(自提),否则出库单 express_code/express_name 直接落库 ZT" + ], + "type": "updated", + "module": "stockout" + }, + { + "version": "2026.08.25-stockout-create-receiver-info", + "date": "2026-08-25", + "summary": "stockout.create 解析 receiverInfo 落库(13 个标准字段)并接入出库单兜底快递编码:快递解析在未传 logisticsCode 或匹配不到时,优先使用货主合约配置 stockout_default_express_code(出库单兜底快递),为空再回退 default_express_code/全局 STO。", + "methods": [ + "stockout.create" + ], + "notes": [ + "qimenMethods/stockout.js create 新增 receiverInfo 解析:company/name/zipCode/tel/mobile/email/countryCode/province/city/area/town/detailAddress/id 共 13 字段落库 receiver_* 列(空值转 NULL)", + "快递解析改为传入覆盖默认快递后的 expressPolicyConfig(default_express_code = stockout_default_express_code || default_express_code)复用 resolveExpressSnapshot 匹配链路", + "app/model/store_warehouse.js POLICY_CONFIG_FIELDS 新增 stockout_default_express_code(type list,默认空,描述:出库单未传快递编码或匹配不到时使用的兜底快递编码)", + "receiverInfo 中的 idType/idNumber 扩展字段暂不落库(数据库未建列)" + ], + "type": "updated", + "module": "stockout" + }, + { + "version": "2026.08.25-stockout-create-express-resolve", + "date": "2026-08-25", + "summary": "stockout.create 新增 logisticsCode 快递编码解析(简化口径):货主开启 enable_external_express_code 时按 wms_express_setting → 系统快递列表匹配,匹配不到(含未开启)一律兜底默认快递,不走订单快递策略漏斗(matchPolicy)。解析结果落库 express_code/express_name。", + "methods": [ + "stockout.create" + ], + "notes": [ + "qimenMethods/stockout.js create 在事务外解析 deliveryOrder.logisticsCode:调 deliveryOrder.getStoreWarehousePolicyConfig 读策略开关 + deliveryOrder.resolveExpressSnapshot(编码映射+兜底,不含策略漏斗),取 sysLogisticsCode/sysLogisticsName 落库 express_code/express_name", + "解析失败仅告警不阻断建单(express_code/express_name 保持 NULL),confirm 前仍可走 storage.stockout.updateExpress 手工补填", + "注意:出库单 express_code 存系统快递编码,stockout.confirm 出站回传 logisticsCode 时直接使用该值" + ], + "type": "updated", + "module": "stockout" + }, { "version": "2026.07.01-qimen-01", "date": "2026-07-01", diff --git a/methods/changes/system.json b/methods/changes/system.json index dcb572f..f6bb4bc 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,87 @@ [ + { + "version": "2026.08.25-stockout-updateInfo-transferred", + "date": "2026-08-25", + "type": "added", + "summary": "新增 storage.stockout.updateInfo 修改出库单信息接口,并引入 TRANSFERRED 状态:转订单成功后出库单置为 TRANSFERRED(已转订单),该状态下禁止一键出库。", + "methods": [ + "storage.stockout.updateInfo", + "storage.stockout.toOrder" + ], + "notes": [ + "storage.stockout.updateInfo:修改范围限收件人(name/tel/mobile/company/email)、地址(province/city/area/town/detailAddress/zipCode/countryCode)、快递编码(express_code,自动解析 express_name)、来源平台(source_platform_code/name),未传入不修改;仅 CREATED/PENDING 状态允许修改(400);修改后收货信息不完整(name、(tel/mobile) 其一、省市区镇详细地址)禁止提交并列出缺失字段", + "数据库迁移 20260825180000-add-transferred-status-and-platform-to-wms-order-stockout.js:order_status ENUM 追加 TRANSFERRED + 新增 source_platform_code(50)/source_platform_name(200) 列,开发库已执行并核验", + "app/model/order_stockout.js:ENUM 补 TRANSFERRED、新增两平台字段、新增 isTransferred() 辅助方法", + "storage.stockout.toOrder:转单成功后 order_status 置 TRANSFERRED(原 CANCELLED);deliveryOrder.sourcePlatformCode 优先用出库单已存平台,为空走兜底平台;confirm(一键出库)经 canConfirm 拒绝 TRANSFERRED 状态", + "同步更新 methods/system.json:新增 updateInfo 接口文档,更新 toOrder 描述与状态说明" + ], + "module": "storage.stockout" + }, + { + "version": "2026.08.25-stockout-toOrder-receiver-validate", + "date": "2026-08-25", + "type": "fixed", + "summary": "storage.stockout.toOrder 增加收货信息必填校验与同快递建单:name、(tel/mobile) 至少一项、省市区镇详细地址缺失时拒绝转单并提示缺失字段;收货信息优先接口传入,未传回填出库单已存的 receiver_* 字段;新订单快递编码沿用出库单 express_code(相同快递),平台不传 sourcePlatformCode 走兜底平台。", + "methods": [ + "storage.stockout.toOrder" + ], + "notes": [ + "app/service/systemMethods/storage/stockout.js toOrder:释放锁前先合并收货信息(storedReceiverInfo 从出库单 receiver_company/name/zip_code/tel/mobile/email/country_code/province/city/area/town/detail_address 回填,接口 receiverInfo 非空字段覆盖)并逐项校验,缺项返回 fail 提示缺失字段列表", + "建单参数:logisticsCode = 出库单 express_code(create 时已解析的系统快递编码),不传 sourcePlatformCode(resolvePlatformSnapshot 自动使用合约兜底平台)", + "同步更新 methods/system.json 中 storage.stockout.toOrder 的 description 与 receiverInfo 参数说明" + ], + "module": "storage.stockout" + }, + { + "version": "2026.08.25-stockout-receiver-info-db", + "date": "2026-08-25", + "type": "added", + "summary": "wms_order_stockout 表新增 13 个收件人字段(receiver_* 前缀),对应奇门 stockout.create 报文 receiverInfo 节点(company/name/zipCode/tel/mobile/email/countryCode/province/city/area/town/detailAddress/id),为出库单解析收件人信息与转订单回填做准备。", + "methods": [ + "storage.stockout.toOrder", + "stockout.create" + ], + "notes": [ + "database/migrations/20260825170000-add-receiver-info-to-wms-order-stockout.js 新增 13 列:receiver_company(200)/receiver_name(50)/receiver_zip_code(50)/receiver_tel(50)/receiver_mobile(50)/receiver_email(50)/receiver_country_code(50)/receiver_province(50)/receiver_city(50)/receiver_area(50)/receiver_town(50)/receiver_detail_address(200)/receiver_id(50),均允许 NULL;up/down 均带 describeTable 幂等保护", + "app/model/order_stockout.js 同步新增 13 个字段定义(remark 与 express_code 之间)", + "开发库已执行迁移并核验 SHOW COLUMNS 全部落库;生产库需在发布时按 db-migration-envs 规范执行" + ], + "module": "storage.stockout" + }, + { + "version": "2026.08.25-storage.stockout.toOrder", + "date": "2026-08-25", + "type": "added", + "summary": "storage.stockout.toOrder 从占位接口落地为真实实现:将非订单出库单(wms_order_stockout)转为正式销售订单,新订单 create_channel 固定为 STOCKOUT;转单时释放出库单库存锁定(QM_STOCKOUT)并转由新订单重新锁定,成功后原出库单置为 CANCELLED 并写入 extend_props.transferred_order_id(幂等,重复调用直接返回已转订单信息)。", + "methods": [ + "storage.stockout.toOrder" + ], + "notes": [ + "app/service/systemMethods/storage/stockout.js toOrder 实现:入参 id(出库单ID,必填)、delivery_order_code(可选,不传自动生成 SK 前缀单号)、receiverInfo(可选收件人信息);校验出库单存在且 order_status 为 CREATED/PENDING(否则 400),extend_props.transferred_order_id 存在时幂等返回已转订单", + "锁转移:事务内逐明细 lockItemStorages(-plan_qty, orderType=QM_STOCKOUT) 释放出库单锁 → 调 deliveryOrder.addOrder(data, info, 'STOCKOUT') 建单并重新锁库存 → 建单失败/订单号重复时 _restoreStockoutLocks 补偿恢复锁定;建单成功后更新出库单 order_status=CANCELLED 并记录 transferred_order_id/transferred_order_code/transferred_at", + "新订单明细手工单风格传 stockId(wms_stock_warehouse.id),sourceOrderCode 写入出库单号便于追溯;create_channel=STOCKOUT 不触发 addOrder 的 API/QM 异步流程,也不会被自动同步任务推送", + "app/service/systemMethods/storage/delivery.js toOrder 兼容转发改为透传 data 参数", + "app/service/systemMethods/order/base.js CREATE_CHANNEL_LABELS 新增 STOCKOUT: '出库转单',订单工作台渠道列正确显示中文标签", + "同步更新 methods/system.json 中 storage.stockout.toOrder 接口文档" + ], + "module": "storage.stockout" + }, + { + "version": "2026.08.25-storeWarehouse.store.createUser", + "date": "2026-08-25", + "type": "added", + "summary": "新增 storeWarehouse.store.createUser:为货主创建用户。按用户名查询平台账号:账号不存在则自动注册并随机生成 12 位密码返回;两种情况统一完成货主工号绑定并授予货主管理员角色(wms_role.id=5)。幂等:重复调用不会重复创建账号或绑定。", + "methods": [ + "storeWarehouse.store.createUser" + ], + "notes": [ + "app/service/systems/store_warehouse.js 新增 createUser:校验 username(必填 + 3-50 位字母数字下划线,400)与 store_id(必填正整数,400)→ 货主存在校验(404)→ 按用户名查询账号(不存在则复用 auth.user.register 注册并随机生成 12 位密码)→ 事务内 AccountStoreEmployee.findOrCreate 绑定货主工号(已存在且 status!=1 时恢复为 1)→ 校验货主管理员角色 wms_role.id=5 已初始化(缺失抛 500)→ EmployeeRole.findOrCreate 授予角色(幂等)", + "app/service/systemMethods/storeWarehouse/store.js 新增 createUser 包装方法;构造器 _noNeedRight/_noNeedAuth 白名单加入 createUser(isNeedLogin=true 需登录、isNeedAuth=false)", + "响应 data:account_id、username、store_id、created(是否本次新建账号;false 表示账号已存在仅完成授权)、password(仅 created=true 时返回 12 位随机明文密码)", + "同步更新 methods/system.json 中 storeWarehouse.store.createUser 接口文档" + ], + "module": "storeWarehouse" + }, { "version": "2026.08.25-returnUnpack.forceRecord", "date": "2026-08-25", diff --git a/methods/system.json b/methods/system.json index e78c540..6477415 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1,8 +1,8 @@ { "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", - "version": "0.3.35", - "updatedAt": "2026-08-22", + "version": "0.3.36", + "updatedAt": "2026-08-25", "headers": [ { "name": "platform", @@ -23226,8 +23226,8 @@ }, { "method": "storage.stockout.toOrder", - "name": "出库单转订单(占位)", - "description": "占位接口,暂未开放。当前仅保留方法名用于后续扩展,逻辑暂不能使用。参数 id / delivery_order_code 暂未启用。", + "name": "出库单转订单", + "description": "将非订单出库单转为正式销售订单:新订单 create_channel 固定为 STOCKOUT;转单时释放出库单占用的库存锁定并转由新订单重新锁定;转单成功后原出库单置为 TRANSFERRED(已转订单,该状态禁止一键出库)并记录已转订单号(幂等,重复调用返回原订单信息)。仅 CREATED / PENDING 状态允许转单;建单失败自动补偿恢复出库单锁定。收货信息必填:name、(tel/mobile) 至少一项、省市区镇详细地址,缺失返回错误禁止转单;收货信息优先接口传入,未传回填出库单已存的收件人字段;快递编码沿用出库单已解析的 express_code,平台优先使用出库单已存 source_platform_code,为空使用兜底平台。", "isNeedAuth": false, "isNeedLogin": true, "isNeedRight": false, @@ -23243,30 +23243,65 @@ { "name": "id", "type": "number", - "required": false, + "required": true, "source": "body", - "description": "预留参数,暂未启用;当前仅保留字段名用于后续扩展。" + "description": "出库单ID(必填)" }, { "name": "delivery_order_code", "type": "string", "required": false, "source": "body", - "description": "预留参数,暂未启用;当前仅保留字段名用于后续扩展。" + "description": "新订单号,不传自动生成(SK 前缀)" + }, + { + "name": "receiverInfo", + "type": "object", + "required": false, + "source": "body", + "description": "收件人信息(name/mobile/tel/province/city/area/town/detailAddress/zipCode 等),不传时回填出库单已存的收件人字段;name、(tel/mobile) 其一、省市区镇详细地址必填,缺失则报错不能转订单" } ], "response": [ { - "name": "_note", + "name": "id", + "type": "number", + "required": true, + "description": "出库单ID" + }, + { + "name": "stockout_order_code", "type": "string", + "required": true, + "description": "出库单号" + }, + { + "name": "order_id", + "type": "number", + "required": true, + "description": "新订单ID" + }, + { + "name": "delivery_order_code", + "type": "string", + "required": true, + "description": "新订单号" + }, + { + "name": "step", + "type": "number", "required": false, - "description": "占位接口,当前无有效业务响应" + "description": "订单步骤(0=待审核,1=待处理)" } ], "errors": [ { - "code": "405", - "description": "占位接口,暂未开放" + "code": "400", + "description": "出库单不存在 / 状态不允许转单 / 无明细 / 订单创建失败" + }, + { + "code": "500", + "description": "释放或恢复库存锁定失败" } ] }, @@ -23497,6 +23532,154 @@ "description": "express_codes 必须是数组或 null" } ] + }, + { + "method": "storage.stockout.updateInfo", + "name": "修改出库单信息", + "description": "修改出库单信息:收件人(name/tel/mobile/company/email 等)、地址(province/city/area/town/detailAddress/zipCode/countryCode)、快递编码(express_code,自动解析 express_name)、来源平台(source_platform_code/source_platform_name)。未传入的字段不修改;修改后收货信息不完整(name、(tel/mobile) 其一、省市区镇详细地址缺任一)禁止提交。仅 CREATED/PENDING 状态允许修改。", + "isNeedAuth": true, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "出库单ID(必填)" + }, + { + "name": "name", + "type": "string", + "required": false, + "source": "body", + "description": "收件人姓名" + }, + { + "name": "tel", + "type": "string", + "required": false, + "source": "body", + "description": "收件人固定电话" + }, + { + "name": "mobile", + "type": "string", + "required": false, + "source": "body", + "description": "收件人移动电话" + }, + { + "name": "company", + "type": "string", + "required": false, + "source": "body", + "description": "收件人公司名称" + }, + { + "name": "email", + "type": "string", + "required": false, + "source": "body", + "description": "收件人电子邮箱" + }, + { + "name": "zipCode", + "type": "string", + "required": false, + "source": "body", + "description": "邮编" + }, + { + "name": "countryCode", + "type": "string", + "required": false, + "source": "body", + "description": "国家二字码" + }, + { + "name": "province", + "type": "string", + "required": false, + "source": "body", + "description": "省份" + }, + { + "name": "city", + "type": "string", + "required": false, + "source": "body", + "description": "城市" + }, + { + "name": "area", + "type": "string", + "required": false, + "source": "body", + "description": "区/县" + }, + { + "name": "town", + "type": "string", + "required": false, + "source": "body", + "description": "镇/街道" + }, + { + "name": "detailAddress", + "type": "string", + "required": false, + "source": "body", + "description": "详细地址" + }, + { + "name": "express_code", + "type": "string", + "required": false, + "source": "body", + "description": "快递公司编码,传入后自动解析 express_name" + }, + { + "name": "source_platform_code", + "type": "string", + "required": false, + "source": "body", + "description": "来源平台编码" + }, + { + "name": "source_platform_name", + "type": "string", + "required": false, + "source": "body", + "description": "来源平台名称" + } + ], + "response": [ + { + "name": "data", + "type": "object", + "required": true, + "description": "更新后的出库单完整记录(wms_order_stockout 表字段,含 receiver_*、express_*、source_platform_* 等)" + } + ], + "errors": [ + { + "code": "400", + "description": "缺少出库单ID / 出库单不存在 / 状态不允许修改" + }, + { + "code": "400", + "description": "收货信息缺失,禁止提交(列出缺失字段)" + } + ] } ] }, @@ -26763,6 +26946,98 @@ "message": "签约关系不存在" } ] + }, + { + "method": "storeWarehouse.store.createUser", + "description": "为货主创建用户:按用户名查询平台账号,账号不存在则自动注册并随机生成 12 位密码返回;两种情况统一完成货主工号绑定并授予货主管理员角色(wms_role.id=5)。幂等:重复调用不会重复创建账号或绑定", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(当前登录主体操作)" + } + ], + "params": [ + { + "name": "username", + "type": "string", + "required": true, + "source": "body", + "description": "用户名,3-50 位字母、数字或下划线,全局唯一" + }, + { + "name": "store_id", + "type": "number", + "required": true, + "source": "body", + "description": "货主 ID" + } + ], + "response": [ + { + "name": "account_id", + "type": "number", + "required": true, + "description": "账号 ID" + }, + { + "name": "username", + "type": "string", + "required": true, + "description": "用户名" + }, + { + "name": "store_id", + "type": "number", + "required": true, + "description": "货主 ID" + }, + { + "name": "created", + "type": "boolean", + "required": true, + "description": "是否本次新建账号;false 表示账号已存在仅完成授权" + }, + { + "name": "password", + "type": "string", + "required": false, + "description": "仅 created=true 时返回:随机生成的初始明文密码(12 位,随机大小写字母/数字)" + } + ], + "errors": [ + { + "code": 400, + "message": "username 参数不能为空" + }, + { + "code": 400, + "message": "用户名格式不合法,需为 3-50 位字母、数字或下划线" + }, + { + "code": 400, + "message": "store_id 参数不能为空" + }, + { + "code": 401, + "message": "未提供有效的认证令牌" + }, + { + "code": 404, + "message": "货主不存在" + }, + { + "code": 500, + "message": "货主管理员角色(id=5)未初始化" + }, + { + "code": 500, + "message": "服务内部错误" + } + ] } ] }, From 73d12cdf1a8d54876dcdcfe7aa0c04b26a69f974 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Wed, 26 Aug 2026 15:31:34 +0800 Subject: [PATCH 273/550] =?UTF-8?q?feat(order):=20=E8=AE=A2=E5=8D=95?= =?UTF-8?q?=E6=96=B0=E5=A2=9E=20oaid=5Forder=5Fsource=5Fcode=20=E5=AD=97?= =?UTF-8?q?=E6=AE=B5=E8=90=BD=E5=BA=93=EF=BC=8C=E5=8F=96=E5=8F=B7=E9=93=BE?= =?UTF-8?q?=E8=B7=AF=20plattradeno=20=E4=BC=98=E5=85=88=E5=8F=96=E8=AF=A5?= =?UTF-8?q?=E5=AD=97=E6=AE=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/model/order_delivery.js | 5 ++ app/service/systems/delivery_order.js | 2 + app/service/systems/express.js | 1 + app/service/systems/express_platform.js | 4 +- script/fix-order-oaid-column.cjs | 73 +++++++++++++++++++++++++ 5 files changed, 83 insertions(+), 2 deletions(-) create mode 100644 script/fix-order-oaid-column.cjs diff --git a/app/model/order_delivery.js b/app/model/order_delivery.js index efb37d1..21a6aa0 100644 --- a/app/model/order_delivery.js +++ b/app/model/order_delivery.js @@ -81,6 +81,11 @@ module.exports = app => { allowNull: true, comment: '来源平台名称', }, + oaid_order_source_code: { + type: STRING(50), + allowNull: true, + comment: 'OAID订单来源编码', + }, create_channel: { type: STRING(20), allowNull: false, diff --git a/app/service/systems/delivery_order.js b/app/service/systems/delivery_order.js index 2d286ba..be919f2 100644 --- a/app/service/systems/delivery_order.js +++ b/app/service/systems/delivery_order.js @@ -1306,6 +1306,7 @@ class DeliveryOrderService extends Service { orderFlag, sourcePlatformCode, sourcePlatformName, + oaidOrderSourceCode, placeOrderTime, payTime, payNo, @@ -1357,6 +1358,7 @@ class DeliveryOrderService extends Service { order_flag: orderFlag || '', source_platform_code: sourcePlatformCode || '', source_platform_name: sourcePlatformName || '', + oaid_order_source_code: oaidOrderSourceCode || '', create_channel: String(createChannel || 'MANUAL').trim().toUpperCase() || 'MANUAL', sys_platform_code: platformSnapshot.sysPlatformCode, sys_platform_name: platformSnapshot.sysPlatformName, diff --git a/app/service/systems/express.js b/app/service/systems/express.js index fb97ab2..538ebe0 100644 --- a/app/service/systems/express.js +++ b/app/service/systems/express.js @@ -17,6 +17,7 @@ const WAYBILL_ORDER_DELIVERY_MIN_ATTRIBUTES = Object.freeze([ 'delivery_order_code', 'source_platform_code', 'source_platform_name', + 'oaid_order_source_code', 'sys_platform_code', 'sys_platform_name', 'order_type', diff --git a/app/service/systems/express_platform.js b/app/service/systems/express_platform.js index 8a4cb21..fdb30ef 100644 --- a/app/service/systems/express_platform.js +++ b/app/service/systems/express_platform.js @@ -749,7 +749,7 @@ class ExpressPlatformService extends MainService { const order = order_tmp.order_delivery; console.log('order', order); const expressListItem = ExpressList.find(item => item.code === listByWarehousePlatformCode.sys_express_code) || {}; - let plattradeno = order.source_order_codes; + let plattradeno = order.oaid_order_source_code || order.source_order_codes || ''; if (listByWarehousePlatformCode.platform_code === 'DY' && order.from_key === 23060081 && !!order.pay_no && plattradeno.indexOf(',') > -1) { plattradeno = order.pay_no; } @@ -2437,7 +2437,7 @@ class ExpressPlatformService extends MainService { object_id: `${order_tmp.order_delivery.warehouse_id}_${order_tmp.order_delivery.id}_${order_tmp.business_key}`, order_info: { order_channels_type: 'PDD', - trade_order_list: [`${order_tmp.order_delivery.warehouse_id}_${order_tmp.order_delivery.id}_${order_tmp.business_key}`], + trade_order_list: [ `${order_tmp.order_delivery.warehouse_id}_${order_tmp.order_delivery.id}_${order_tmp.business_key}` ], }, package_info: { items: (order_tmp.order_delivery && order_tmp.order_delivery.orderItems || []).map(item => ({ diff --git a/script/fix-order-oaid-column.cjs b/script/fix-order-oaid-column.cjs new file mode 100644 index 0000000..29fcbed --- /dev/null +++ b/script/fix-order-oaid-column.cjs @@ -0,0 +1,73 @@ +'use strict'; + +/** + * 幂等补齐订单分表的 oaid_order_source_code 列。 + * + * 背景:该列由订单模型(app/model/order_delivery.js)定义,分表工厂 + * (order_delivery_factory.js)在首次访问某张分表时自动同步;history / + * outsourced 等长期不被访问的表可能滞后,可用本脚本提前补齐。 + * + * 用法: + * 开发:node script/fix-order-oaid-column.cjs + * 生产:PowerShell 中 $env:NODE_ENV='production'; node script/fix-order-oaid-column.cjs + * + * 安全:只 ADD 缺失列(VARCHAR(50) NULL,与模型定义一致),不触碰 id / + * AUTO_INCREMENT,不修改已有列,可重复执行。 + */ +(async () => { + try { + const configs = require('../database/config.js'); + const env = process.env.NODE_ENV || 'development'; + const cfg = configs[env]; + if (!cfg) { + console.error('NO_CONFIG_FOR_ENV'); + process.exit(2); + } + + const mysql = require('mysql2/promise'); + const conn = await mysql.createConnection({ + host: cfg.host, + port: cfg.port || 3306, + user: cfg.username, + password: cfg.password, + database: cfg.database, + }); + + const [ tables ] = await conn.query( + `SELECT TABLE_NAME FROM information_schema.TABLES + WHERE TABLE_SCHEMA = ? AND TABLE_NAME LIKE 'wms_order_delivery\\_%' + ORDER BY TABLE_NAME`, + [ cfg.database ] + ); + + console.log(`环境: ${env}, 库: ${cfg.host}:${cfg.port}/${cfg.database}`); + console.log(`订单分表数量: ${tables.length}\n`); + + const columnSql = 'ADD COLUMN oaid_order_source_code VARCHAR(50) NULL COMMENT \'OAID订单来源编码\''; + let added = 0; + let ok = 0; + + for (const row of tables) { + const tableName = row.TABLE_NAME || row.table_name; + const [ columns ] = await conn.query( + `SELECT COLUMN_NAME FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND COLUMN_NAME = 'oaid_order_source_code'`, + [ cfg.database, tableName ] + ); + if (columns.length === 0) { + await conn.query(`ALTER TABLE \`${tableName}\` ${columnSql}`); + console.log(`[ADD] ${tableName} 已补齐列`); + added += 1; + } else { + ok += 1; + } + } + + console.log(`\n完成: 已存在 ${ok} 张, 新增 ${added} 张`); + await conn.end(); + process.exit(0); + } catch (err) { + console.error('ERROR', err.message); + process.exit(3); + } +})(); From 93c0a620c7f801663bec6ad4c3b32e974728ea34 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Wed, 26 Aug 2026 15:35:35 +0800 Subject: [PATCH 274/550] =?UTF-8?q?feat(stockout):=20=E5=87=BA=E5=BA=93?= =?UTF-8?q?=E5=8D=95=E6=93=8D=E4=BD=9C=E6=97=A5=E5=BF=97/=E5=8F=96?= =?UTF-8?q?=E6=B6=88/=E7=A1=AE=E8=AE=A4=E5=9B=9E=E4=BC=A0=E4=B8=8E=20STOCK?= =?UTF-8?q?OUT=20=E6=B8=A0=E9=81=93=E8=AE=A2=E5=8D=95=E5=90=8C=E6=AD=A5?= =?UTF-8?q?=EF=BC=8Cworkbench=20=E6=9F=A5=E8=AF=A2=E4=B8=8E=E6=89=93?= =?UTF-8?q?=E5=8C=85=E7=8A=B6=E6=80=81=E5=9B=9E=E5=86=99=EF=BC=8C=E9=BB=98?= =?UTF-8?q?=E8=AE=A4=E5=BA=93=E4=BD=8D=E9=85=8D=E7=BD=AE=E5=8F=8A=E6=9D=83?= =?UTF-8?q?=E9=99=90=E8=BF=81=E7=A7=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/model/store.js | 12 + app/service/systemMethods/storage/stockout.js | 341 ++++++++- app/service/systems/operation_log.js | 13 + app/service/systems/order_async.js | 647 ++++++++++++++++++ app/service/systems/order_packing.js | 16 +- .../systems/order_storage_allocation.js | 7 +- app/service/systems/setting/warehouse.js | 54 ++ app/service/systems/storage/inventory.js | 19 +- app/service/systems/storage/receiving.js | 17 +- app/service/systems/workbench.js | 169 +++-- ...0000-add-stockout-updateInfo-permission.js | 58 ++ ...26093000-add-stockout-cancel-permission.js | 56 ++ ...100000-add-stockout-listLogs-permission.js | 56 ++ methods/changes/system.json | 167 ++++- methods/system.json | 150 +++- script/backfill-pack-status-fin.cjs | 173 +++++ 16 files changed, 1884 insertions(+), 71 deletions(-) create mode 100644 database/migrations/20260826090000-add-stockout-updateInfo-permission.js create mode 100644 database/migrations/20260826093000-add-stockout-cancel-permission.js create mode 100644 database/migrations/20260826100000-add-stockout-listLogs-permission.js create mode 100644 script/backfill-pack-status-fin.cjs diff --git a/app/model/store.js b/app/model/store.js index c70cbfc..2d5ddde 100644 --- a/app/model/store.js +++ b/app/model/store.js @@ -59,6 +59,7 @@ module.exports = app => { receiver_address: '', group_wave_prefix: 'B', delete_order_wave_prefix: 'A', + default_location_id: null, single_order_pack_max_minutes: 3, group_order_pack_max_minutes: 40, inventory_warning_rules: DEFAULT_INVENTORY_WARNING_RULES, @@ -329,6 +330,17 @@ module.exports = app => { normalized.inventory_warning_rules = normalizeInventoryWarningRules(parsed.inventory_warning_rules); normalized.auto_outbound_rules = normalizeAutoOutboundRules(parsed.auto_outbound_rules); + const rawDefaultLocationId = parsed.default_location_id; + if (rawDefaultLocationId === undefined || rawDefaultLocationId === null || rawDefaultLocationId === '') { + normalized.default_location_id = null; + } else { + const defaultLocationId = Number(rawDefaultLocationId); + if (!Number.isInteger(defaultLocationId) || defaultLocationId <= 0) { + throw new Error('subject_config.default_location_id 必须是正整数库位ID'); + } + normalized.default_location_id = defaultLocationId; + } + if (Object.prototype.hasOwnProperty.call(parsed, 'cutoff_order_enabled')) { normalized.cutoff_order_enabled = normalizeBooleanFlag(parsed.cutoff_order_enabled, 'subject_config.cutoff_order_enabled'); } diff --git a/app/service/systemMethods/storage/stockout.js b/app/service/systemMethods/storage/stockout.js index e434bb3..8b65ce7 100644 --- a/app/service/systemMethods/storage/stockout.js +++ b/app/service/systemMethods/storage/stockout.js @@ -82,6 +82,8 @@ class StorageStockoutService extends MainService { const finalWhere = { [Op.and]: andConditions }; const { count, rows } = await OrderStockoutModel.findAndCountAll({ + // 必须返回 id:前端行点击/详情/打印/确认等均依赖 row.id(与 receiving 等列表保持一致) + attributes: { exclude: [ 'warehouse_name' ] }, where: finalWhere, order: [[ sortField, sortOrder ], [ 'id', 'DESC' ]], limit: pageSize, @@ -89,6 +91,22 @@ class StorageStockoutService extends MainService { raw: true, }); + // 补充货主名称:store_name 快照为空时按 store_id 解析 wms_store.company_name + const storeIds = [ ...new Set(rows.map(row => Number(row.store_id)).filter(id => Number.isFinite(id) && id > 0)) ]; + if (storeIds.length > 0) { + const stores = await ctx.model.Store.findAll({ + where: { id: { [Op.in]: storeIds } }, + attributes: [ 'id', 'company_name' ], + raw: true, + }); + const nameMap = new Map(stores.map(item => [ Number(item.id), String(item.company_name || '') ])); + for (const row of rows) { + if (!row.store_name) { + row.store_name = nameMap.get(Number(row.store_id)) || ''; + } + } + } + return this.success('ok', { list: rows, pagination: { @@ -323,6 +341,12 @@ class StorageStockoutService extends MainService { ctx.logger.error(`[stockout.toOrder] 标记出库单已转失败: ${updateErr.message}`); } + await this._writeStockoutOperationLog( + order, + 'STOCKOUT_TO_ORDER', + `出库单已转订单 ${deliveryOrderCode}(order_id=${orderId}),已释放库存锁定` + ); + return this.success('转订单成功', { id: order.id, stockout_order_code: order.stockout_order_code, @@ -364,6 +388,44 @@ class StorageStockoutService extends MainService { } } + /** + * 写 wms_operation_log 操作日志(businessType=stockout),失败仅告警不影响主流程。 + * @param {Object} order 出库单实例或行 + * @param {string} operationCode 操作编码 + * @param {string} message 日志内容 + * @param {Object} [options={}] 选项,可含 transaction + * @return {Promise} 无返回值 + */ + async _writeStockoutOperationLog(order, operationCode, message, options = {}) { + const { ctx } = this; + const opLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog; + if (!opLogService || typeof opLogService.createOperationLogs !== 'function') { + ctx.logger.warn('[stockout] 操作日志服务不可用,跳过记录'); + return; + } + const user = ctx.user || {}; + try { + await opLogService.createOperationLogs([ + { + businessType: 'stockout', + businessId: order.id, + operationCode, + operator: { + id: user.employees_id ?? user.id ?? null, + name: String(user.employees_name || user.real_name || user.name || 'system'), + }, + extras: { + warehouseId: Number(ctx.user && ctx.user.store_id) || order.warehouse_id || null, + message, + externalLogType: 'NONE', + }, + }, + ], { transaction: options.transaction }); + } catch (err) { + ctx.logger.warn(`[stockout] 写操作日志失败: ${err.message}`); + } + } + /** * 出库单明细查询。 * @param {Object} data 请求体 @@ -421,10 +483,91 @@ class StorageStockoutService extends MainService { }); } + /** + * 查询出库单操作日志(分页)。 + * 日志业务类型 business_type=stockout,business_id=出库单ID; + * 覆盖创建/审核/转订单/确认/修改/取消等操作(STOCKOUT_* 操作编码)。 + * @param {Object} data 请求体 + * @param {number} [data.id] 出库单ID(与 stockout_order_code 至少传一个) + * @param {string} [data.stockout_order_code] 出库单号 + * @param {Object} [data.pagination] 分页对象,支持 page / pageSize(或 page_size) + * @return {Promise} 统一成功包装响应 { list, pagination } + */ + async listLogs(data = {}) { + const { ctx, service } = this; + const requestData = data && typeof data === 'object' ? data : {}; + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + const id = Number(requestData.id || 0); + const stockoutOrderCode = String(requestData.stockout_order_code || '').trim(); + // 分页参数:兼容顶层 page/pageSize(与订单日志 order.queryOrderLogs 一致)与 pagination 对象两种写法 + const pagination = requestData.pagination && typeof requestData.pagination === 'object' + ? requestData.pagination + : {}; + const page = requestData.page ?? pagination.page; + const pageSize = requestData.pageSize ?? pagination.pageSize ?? pagination.page_size; + + if (!id && !stockoutOrderCode) { + return this.fail('id 或 stockout_order_code 至少传一个'); + } + + const emptyResult = { + list: [], + pagination: { + page: Number.parseInt(page, 10) || 1, + pageSize: Number.parseInt(pageSize, 10) || 20, + total: 0, + totalPages: 0, + }, + }; + + // 定位出库单ID(日志 business_id 存的是出库单ID) + let stockoutId = id; + if (!stockoutId) { + const order = await ctx.model.OrderStockout.findOne({ + where: { + stockout_order_code: stockoutOrderCode, + warehouse_id: warehouseId, + deleted_at: null, + }, + attributes: [ 'id' ], + raw: true, + }); + + if (!order || !order.id) { + return this.success('ok', { + data: emptyResult, + code: 200, + }); + } + + stockoutId = Number(order.id); + } + + try { + const result = await service.systems.operationLog.queryStockoutLogs({ + id: stockoutId, + page, + pageSize, + warehouseId, + }); + + return this.success('ok', { + data: result, + code: 200, + }); + } catch (e) { + // 与订单日志接口一致:查询异常时以 200 包装返回错误信息 + return this.success(e.message, { + code: 200, + }); + } + } + /** * 出库单确认(直出)。 * 不改变内部库存,直接按出库单明细的计划数量确认。 - * 出站同步 taobao.qimen.stockout.confirm 成功后,状态才推进到 COMPLETED。 + * 出站同步 taobao.qimen.stockout.confirm 成功后,释放创建时占用的库存锁定(QM_STOCKOUT,写 UNLOCK 流水), + * 状态才推进到 COMPLETED。 * 要求 express_code 已填写,否则拒绝确认。 * @param {Object} data 请求体 * @param {number} data.id 出库单ID(必填) @@ -549,10 +692,56 @@ class StorageStockoutService extends MainService { // 第三步:根据出站结果更新状态 if (qimenSuccess) { - await ctx.model.OrderStockout.update( - { order_status: 'COMPLETED', sync_status: 'SUCCESS', sync_message: '', updated_at: new Date() }, - { where: { id: order.id } } - ); + // 直出确认:释放出库单占用的库存锁定(QM_STOCKOUT,负数量释放并自动写 UNLOCK 流水), + // 与状态推进到 COMPLETED 在同一事务内完成,失败回滚可重试。 + const finalizeTransaction = await ctx.model.transaction(); + try { + let totalReleaseQty = 0; + for (const item of items) { + const qty = Number(item.plan_qty) || 0; + if (qty <= 0) continue; + const releaseResult = await ctx.service.systems.stockStore.lockItemStorages( + item.stock_id, + -qty, + finalizeTransaction, + null, + { + orderType: 'QM_STOCKOUT', + orderNo: order.stockout_order_code, + orderId: order.id, + remark: '出库单确认释放锁定', + } + ); + if (!releaseResult.success) { + // 已释放过(锁定不足)视为幂等成功,避免阻断重试 + const alreadyReleased = String(releaseResult.error || '').includes('释放数量超过已锁定库存'); + if (alreadyReleased) { + ctx.logger.warn(`[stockout.confirm] 库存${item.stock_id}锁定已释放,跳过: ${releaseResult.error}`); + continue; + } + throw new Error(`库存${item.stock_id}释放锁定失败: ${releaseResult.error}`); + } + totalReleaseQty += qty; + } + + await this._writeStockoutOperationLog( + order, + 'STOCKOUT_CONFIRM', + `出库单确认完成(直出),释放锁定库存 ${totalReleaseQty}`, + { transaction: finalizeTransaction } + ); + + await ctx.model.OrderStockout.update( + { order_status: 'COMPLETED', sync_status: 'SUCCESS', sync_message: '', updated_at: new Date() }, + { where: { id: order.id }, transaction: finalizeTransaction } + ); + + await finalizeTransaction.commit(); + } catch (err) { + await finalizeTransaction.rollback().catch(() => {}); + ctx.logger.error(`[stockout.confirm] 释放锁定失败: ${order.stockout_order_code} - ${err.message}`); + return this.fail(`确认失败:${err.message}`); + } ctx.logger.info(`[stockout.confirm] 确认完成: ${order.stockout_order_code}`); return this.success('确认成功', { @@ -576,6 +765,104 @@ class StorageStockoutService extends MainService { return this.fail(`出站同步失败: ${qimenMessage || '未发起出站通知'}`); } + /** + * 出库单取消。 + * + * 仅 CREATED / PENDING 状态允许取消;事务内释放创建时占用的库存锁定(QM_STOCKOUT, + * 写 UNLOCK 流水),状态置为 CANCELLED,并写 wms_operation_log 操作日志。 + * 已转订单(TRANSFERRED)与已完成(COMPLETED)状态禁止取消。 + * + * @param {Object} data 请求体 + * @param {number} data.id 出库单ID(必填) + * @return {Promise} 统一成功/失败包装响应 + */ + async cancel(data = {}) { + const { ctx } = this; + const id = Number(data.id || 0); + + if (!id) { + return this.fail('缺少出库单ID'); + } + + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + if (warehouseId <= 0) { + return this.fail('缺少仓库上下文'); + } + + const order = await ctx.model.OrderStockout.findOne({ + where: { id, warehouse_id: warehouseId, deleted_at: null }, + }); + if (!order) { + return this.fail('出库单不存在'); + } + + if (!order.canCancel || !order.canCancel()) { + return this.fail(`出库单当前状态(${order.order_status})不允许取消`); + } + + const items = await ctx.model.OrderStockoutItems.findAll({ + where: { order_id: order.id }, + raw: true, + }); + + // 释放创建时占用的库存锁定 + 状态置 CANCELLED + 操作日志,同一事务 + const cancelTransaction = await ctx.model.transaction(); + try { + let releasedQty = 0; + for (const item of items) { + const qty = Number(item.plan_qty) || 0; + if (qty <= 0) continue; + const releaseResult = await ctx.service.systems.stockStore.lockItemStorages( + item.stock_id, + -qty, + cancelTransaction, + null, + { + orderType: 'QM_STOCKOUT', + orderNo: order.stockout_order_code, + orderId: order.id, + remark: '出库单取消释放锁定', + } + ); + if (!releaseResult.success) { + // 已释放过(锁定不足)视为幂等成功,避免阻断 + const alreadyReleased = String(releaseResult.error || '').includes('释放数量超过已锁定库存'); + if (alreadyReleased) { + ctx.logger.warn(`[stockout.cancel] 库存${item.stock_id}锁定已释放,跳过: ${releaseResult.error}`); + continue; + } + throw new Error(`库存${item.stock_id}释放锁定失败: ${releaseResult.error}`); + } + releasedQty += qty; + } + + await ctx.model.OrderStockout.update( + { order_status: 'CANCELLED', sync_message: '已取消', updated_at: new Date() }, + { where: { id: order.id }, transaction: cancelTransaction } + ); + + await this._writeStockoutOperationLog( + order, + 'STOCKOUT_CANCEL', + `出库单已取消,释放锁定库存 ${releasedQty}`, + { transaction: cancelTransaction } + ); + + await cancelTransaction.commit(); + } catch (err) { + await cancelTransaction.rollback().catch(() => {}); + ctx.logger.error(`[stockout.cancel] 取消失败: ${order.stockout_order_code} - ${err.message}`); + return this.fail(`取消失败:${err.message}`); + } + + ctx.logger.info(`[stockout.cancel] 取消完成: ${order.stockout_order_code}`); + return this.success('取消成功', { + id: order.id, + stockout_order_code: order.stockout_order_code, + order_status: 'CANCELLED', + }); + } + /** * 更新出库单快递和运单号。 * 用于在确认前填写 express_code / waybill_code / waybill_codes。 @@ -671,6 +958,7 @@ class StorageStockoutService extends MainService { * @param {string} [data.area] 区/县 * @param {string} [data.town] 镇/街道 * @param {string} [data.detailAddress] 详细地址 + * @param {string} [data.receiver_id] 收件人证件号 * @param {string} [data.express_code] 快递公司编码(自动解析 express_name) * @param {string} [data.source_platform_code] 来源平台编码 * @param {string} [data.source_platform_name] 来源平台名称 @@ -701,28 +989,30 @@ class StorageStockoutService extends MainService { } const updateData = { updated_at: new Date() }; + const changedLabels = []; // 收件人 / 地址字段:传入才更新,空串置 NULL const receiverFieldMap = { - receiver_name: 'name', - receiver_tel: 'tel', - receiver_mobile: 'mobile', - receiver_company: 'company', - receiver_email: 'email', - receiver_zip_code: 'zipCode', - receiver_country_code: 'countryCode', - receiver_province: 'province', - receiver_city: 'city', - receiver_area: 'area', - receiver_town: 'town', - receiver_detail_address: 'detailAddress', - receiver_id: 'id', + receiver_name: [ 'name', '收件人姓名' ], + receiver_tel: [ 'tel', '固定电话' ], + receiver_mobile: [ 'mobile', '移动电话' ], + receiver_company: [ 'company', '公司名称' ], + receiver_email: [ 'email', '电子邮箱' ], + receiver_zip_code: [ 'zipCode', '邮编' ], + receiver_country_code: [ 'countryCode', '国家' ], + receiver_province: [ 'province', '省份' ], + receiver_city: [ 'city', '城市' ], + receiver_area: [ 'area', '区县' ], + receiver_town: [ 'town', '镇街道' ], + receiver_detail_address: [ 'detailAddress', '详细地址' ], + receiver_id: [ 'receiver_id', '证件号' ], }; - for (const [ column, param ] of Object.entries(receiverFieldMap)) { + for (const [ column, [ param, label ]] of Object.entries(receiverFieldMap)) { if (data[param] !== undefined) { updateData[column] = data[param] === null ? null : String(data[param]).trim() || null; + changedLabels.push(label); } } @@ -744,14 +1034,19 @@ class StorageStockoutService extends MainService { updateData.express_code = null; updateData.express_name = null; } + changedLabels.push('快递编码'); } // 来源平台:传入才更新,空串置 NULL if (data.source_platform_code !== undefined) { updateData.source_platform_code = String(data.source_platform_code || '').trim() || null; + changedLabels.push('来源平台'); } if (data.source_platform_name !== undefined) { updateData.source_platform_name = String(data.source_platform_name || '').trim() || null; + if (!changedLabels.includes('来源平台')) { + changedLabels.push('来源平台'); + } } // 修改后的收货信息完整性校验:name、(tel/mobile) 其一、省市区镇详细地址必填,缺失禁止提交 @@ -791,6 +1086,14 @@ class StorageStockoutService extends MainService { await ctx.model.OrderStockout.update(updateData, { where: { id: order.id } }); const updated = await ctx.model.OrderStockout.findByPk(order.id, { raw: true }); + if (changedLabels.length > 0) { + await this._writeStockoutOperationLog( + order, + 'STOCKOUT_UPDATE_INFO', + `修改出库单信息:${changedLabels.join('、')}` + ); + } + return this.success('修改成功', updated); } } diff --git a/app/service/systems/operation_log.js b/app/service/systems/operation_log.js index 923d2d0..00faaaf 100644 --- a/app/service/systems/operation_log.js +++ b/app/service/systems/operation_log.js @@ -319,6 +319,19 @@ class operationLogService extends Service { return await this.queryLogsByBusinessType(query, 'entry_order'); } + /** + * 查询出库单操作日志。 + * @param {Object} query 查询参数。 + * @param {string|number} query.id 出库单ID。 + * @param {string|number} query.warehouseId 仓库ID。 + * @param {number} [query.page=1] 页码。 + * @param {number} [query.pageSize=20] 每页数量。 + * @return {Promise<{list: Object[], pagination: Object}>} 分页结果。 + */ + async queryStockoutLogs(query = {}) { + return await this.queryLogsByBusinessType(query, 'stockout'); + } + async getMessageDetail(data) { const { id, type } = data; const { ctx } = this; diff --git a/app/service/systems/order_async.js b/app/service/systems/order_async.js index 572e94c..605ca87 100644 --- a/app/service/systems/order_async.js +++ b/app/service/systems/order_async.js @@ -5,6 +5,7 @@ const MainService = require('../main'); const CREATE_CHANNEL_QM = 'QM'; const CREATE_CHANNEL_MANUAL = 'MANUAL'; const CREATE_CHANNEL_API = 'API'; +const CREATE_CHANNEL_STOCKOUT = 'STOCKOUT'; const RETRYABLE_DATABASE_ERROR_CODES = new Set([ 1205, 1213, 'ER_LOCK_WAIT_TIMEOUT', 'ER_LOCK_DEADLOCK' ]); const TRANSACTION_LOCK_RETRY_MAX_ATTEMPTS = 3; const TRANSACTION_LOCK_RETRY_BASE_DELAY_MS = 50; @@ -935,6 +936,638 @@ async function finalizeLocalChannelOrdersInternal(service, createChannel, groupe }; } +/** + * 构建出库单确认回传数据(taobao.qimen.stockout.confirm / OpenAPI 回调共用)。 + * + * 快递信息取订单侧实际发货信息:物流编码优先订单 sys_logistics_code → logistics_code → + * 出库单 express_code;运单号来自 wms_order_express 表(waybillCodes)。 + * + * @param {Object} service 服务实例 + * @param {Object} stockoutOrder 出库单主表记录(raw) + * @param {Object} orderRow 订单主表记录(raw) + * @param {Array} stockoutItems 出库单明细(raw 数组) + * @param {Array} [waybillCodes] 运单号列表 + * @return {Object} 出库单确认回传请求体 + */ +function buildStockoutConfirmDataInternal(service, stockoutOrder, orderRow, stockoutItems, waybillCodes = []) { + const now = service.app.formatDate(new Date()); + // STOCKOUT 渠道运单号只认 wms_order_express 表(分配快递号时写入), + // 不回退订单主表 express_code(该字段是面单号前置,不是完整运单号) + const normalizedWaybillCodes = (Array.isArray(waybillCodes) ? waybillCodes : []) + .map(code => String(code || '').trim()) + .filter(code => !!code); + const expressCode = String( + orderRow.sys_logistics_code + || orderRow.logistics_code + || stockoutOrder.express_code + || 'OTHER' + ).trim(); + const expressName = String( + orderRow.sys_logistics_name + || orderRow.logistics_name + || stockoutOrder.express_name + || 'OTHER' + ).trim(); + const stockoutOrderCode = String(stockoutOrder.stockout_order_code || '').trim(); + const packageCode = String(orderRow.package_code || '').trim() || stockoutOrderCode; + const orderLines = (Array.isArray(stockoutItems) ? stockoutItems : []).map(item => { + const planQty = Number(item.plan_qty) || 0; + const actualQty = Number(item.actual_qty) || planQty; + + return { + orderLineNo: String(item.order_line_no || '').trim(), + ownerCode: String(item.owner_code || stockoutOrder.qimen_owner_code || '').trim(), + itemCode: String(item.item_code || '').trim(), + itemId: item.item_id, + itemName: String(item.item_name || '').trim(), + planQty, + actualQty, + inventoryType: String(item.inventory_type || 'ZP').trim(), + }; + }); + + return { + deliveryOrder: { + totalOrderLines: Number(stockoutOrder.total_order_lines) || orderLines.length, + deliveryOrderCode: stockoutOrderCode, + deliveryOrderId: Number(stockoutOrder.id) || undefined, + warehouseCode: String(stockoutOrder.qimen_warehouse_code || '').trim(), + orderType: String(stockoutOrder.order_type || '').trim(), + status: 'DELIVERED', + outBizCode: stockoutOrderCode, + confirmType: 0, + orderConfirmTime: now, + operatorCode: '', + operatorName: '', + }, + packages: { + package: normalizedWaybillCodes.map(waybillCode => ({ + logisticsCode: expressCode, + logisticsName: expressName, + expressCode: waybillCode, + packageCode, + items: orderLines.map(line => ({ + itemCode: line.itemCode, + itemId: line.itemId, + quantity: line.actualQty, + })), + })), + }, + orderLines, + }; +} + +/** + * 通知外部出库单确认结果(按出库单 source_type 分流)。 + * + * - QM:奇门 taobao.qimen.stockout.confirm,flag=success 视为成功; + * - API:OpenAPI 签名回调(event=stockout_completed); + * - 其他(WMS 等内部来源):无需通知外部,直接视为成功。 + * + * @param {Object} service 服务实例 + * @param {Object} stockoutOrder 出库单主表记录(raw) + * @param {Object} requestData 出库单确认回传请求体 + * @param {Object} [context] 上下文(含 appKey) + * @return {Promise<{success: boolean, message: string}>} 通知结果 + */ +async function notifyStockoutExternalInternal(service, stockoutOrder, requestData, context = {}) { + const { ctx, app } = service; + const sourceType = String(stockoutOrder.source_type || 'QM').trim().toUpperCase(); + + if (sourceType === 'QM') { + if (!app.qimenClient || typeof app.qimenClient.send !== 'function') { + return { success: false, message: '奇门客户端未初始化' }; + } + + if (!stockoutOrder.qimen_owner_code) { + return { success: false, message: '出库单缺少奇门货主编码' }; + } + + try { + const sendResult = await app.qimenClient.send( + 'taobao.qimen.stockout.confirm', + stockoutOrder.qimen_owner_code, + requestData, + { ctx } + ); + const response = (sendResult && sendResult.xmlArray && sendResult.xmlArray.response) + ? (Array.isArray(sendResult.xmlArray.response) ? sendResult.xmlArray.response[0] : sendResult.xmlArray.response) + : {}; + const flag = String(response.flag || '').trim(); + if (flag === 'success') { + return { success: true, message: '' }; + } + + return { + success: false, + message: `${response.code || ''} ${response.message || '奇门出库单确认失败'}`.trim(), + }; + } catch (error) { + return { success: false, message: error.message || '奇门出库单确认异常' }; + } + } + + if (sourceType === 'API') { + const callbackService = ctx.service.openapi && ctx.service.openapi.callback; + const appKey = String(context.appKey || '').trim(); + + if (!callbackService || typeof callbackService.sendByAppKey !== 'function') { + return { success: false, message: 'OpenAPI 回调服务未初始化' }; + } + + if (!appKey) { + return { success: false, message: '缺少 appKey,无法回传出库单' }; + } + + try { + const callbackResult = await callbackService.sendByAppKey({ + appKey, + event: 'stockout_completed', + data: { + stockoutOrderCode: stockoutOrder.stockout_order_code, + status: 'completed', + ...requestData, + }, + metadata: { + warehouseId: Number(stockoutOrder.warehouse_id) || 0, + storeId: Number(stockoutOrder.store_id) || 0, + sourceType, + }, + }); + + if (callbackResult && callbackResult.success === true) { + return { success: true, message: '' }; + } + + return { + success: false, + message: String(callbackResult && callbackResult.error || 'OpenAPI 回传失败').trim(), + }; + } catch (error) { + return { success: false, message: error.message || 'OpenAPI 回传异常' }; + } + } + + // WMS 等内部来源:无需通知外部 + return { success: true, message: '' }; +} + +/** + * 出库单回传成功后的收尾: + * 同一事务内 ① 写回出库单快递信息并推进 COMPLETED/SUCCESS; + * ② 按订单明细扣减库存(outbound,自动释放订单锁定);③ 订单 sync_status=fin。 + * + * @param {Object} service 服务实例 + * @param {Object} orderModel 订单模型 + * @param {Object} orderItemsModel 订单明细模型 + * @param {number} orderId 订单ID + * @param {number} warehouseId 仓库ID + * @param {Object} stockoutOrder 出库单记录(raw) + * @param {Object} expressWriteback 出库单快递写回字段 + * @param {Object} [orderRow] 订单记录(raw) + * @return {Promise} 失败抛异常 + */ +async function finalizeSuccessfulStockoutSyncInternal(service, orderModel, orderItemsModel, orderId, warehouseId, stockoutOrder, expressWriteback, orderRow = null) { + const stockStoreService = service.ctx.service && service.ctx.service.systems && service.ctx.service.systems.stockStore; + + if (!service.ctx.model || typeof service.ctx.model.transaction !== 'function') { + throw new Error('事务能力未初始化'); + } + + if (!stockStoreService || typeof stockStoreService.outbound !== 'function') { + throw new Error('库存出库服务未初始化'); + } + + await runTransactionWithLockRetryInternal(service, 'finalizeSuccessfulStockoutSync', async transaction => { + let resolvedOrderRow = orderRow; + if (orderModel && typeof orderModel.findOne === 'function') { + resolvedOrderRow = await orderModel.findOne({ + where: { + id: orderId, + warehouse_id: warehouseId, + }, + attributes: [ 'id', 'delivery_order_code', 'order_type', 'source_order_codes', 'sync_status' ], + lock: transaction.LOCK.UPDATE, + raw: true, + transaction, + }); + } + + const stockoutUpdate = { + ...expressWriteback, + order_status: 'COMPLETED', + sync_status: 'SUCCESS', + sync_message: '', + updated_at: new Date(), + }; + + // 防重:订单已完成同步(并发重试触发),仅补齐出库单写回后跳过扣减 + if (resolvedOrderRow && String(resolvedOrderRow.sync_status || '').trim() === 'fin') { + await service.ctx.model.OrderStockout.update(stockoutUpdate, { + where: { id: stockoutOrder.id }, + transaction, + }); + service.ctx.logger.info(`[order_async] 订单已完成同步,跳过重复出库 orderId=${orderId}`); + return; + } + + const freshOrderItems = await orderItemsModel.findAll({ + where: { order_id: orderId }, + raw: true, + transaction, + }); + + for (const orderItem of Array.isArray(freshOrderItems) ? freshOrderItems : []) { + const itemId = Number(orderItem && orderItem.item_id); + const quantity = resolveQimenSyncItemQuantityInternal(orderItem); + + if (!Number.isFinite(itemId) || itemId <= 0 || quantity <= 0) { + continue; + } + + const stockId = Number(orderItem && orderItem.stock_id) || 0; + const outboundResult = await stockStoreService.outbound(itemId, quantity, transaction, { + orderId: Number(resolvedOrderRow && resolvedOrderRow.id) || Number(orderId) || null, + orderNo: String(resolvedOrderRow && resolvedOrderRow.delivery_order_code || '').trim() || null, + orderItemId: Number(orderItem && (orderItem.id || orderItem.order_item_id)) || null, + sourceOrderCodes: String(resolvedOrderRow && resolvedOrderRow.source_order_codes || '').trim() || undefined, + }, { stockId: stockId > 0 ? stockId : undefined }); + + if (!outboundResult || outboundResult.success !== true) { + throw new Error(String(outboundResult && outboundResult.error || `订单${orderId}库存扣减失败`).trim()); + } + } + + // 写回出库单快递信息 + 状态推进 + await service.ctx.model.OrderStockout.update(stockoutUpdate, { + where: { id: stockoutOrder.id }, + transaction, + }); + + await orderModel.update({ + sync_status: 'fin', + inspection_status: 'padding', + step: 2, + order_flag: '', + updated_at: new Date(), + }, { + where: { + id: orderId, + warehouse_id: warehouseId, + status: { + [service.app.Sequelize.Op.ne]: 'cancel', + }, + }, + transaction, + }); + }); +} + +/** + * 单个 STOCKOUT 订单回传处理: + * 反查出库单 → 收集订单实际快递信息 → 通知外部 → 成功后写回出库单并扣库存完成同步; + * 失败时订单 sync_status=error 并标记待处理异常,出库单 sync_status=FAILED 记录失败原因。 + * + * @param {Object} service 服务实例 + * @param {Object} orderModel 订单模型 + * @param {Object} orderItemsModel 订单明细模型 + * @param {number} orderId 订单ID + * @param {number} warehouseId 仓库ID + * @param {Object} orderRow 订单记录(raw) + * @param {Array} orderItems 订单明细(raw 数组) + * @param {Object} [context] 上下文 + * @param {Array} [waybillCodes] 运单号列表 + * @return {Promise} 处理结果 + */ +async function processStockoutOrderInternal(service, orderModel, orderItemsModel, orderId, warehouseId, orderRow, orderItems, context = {}, waybillCodes = []) { + const { ctx } = service; + const deliveryOrderCode = String(orderRow && orderRow.delivery_order_code || '').trim(); + const buildFailure = (message, extra = {}) => ({ + order_id: orderId, + delivery_order_code: deliveryOrderCode, + status: 'failed', + message, + ...extra, + }); + + if (!orderRow) { + return buildFailure('发货单不存在'); + } + + // 反查出库单:订单 source_order_codes 的首个来源单号(转订单时为出库单号), + // 兜底取订单明细 source_order_code + const sourceOrderCodes = String(orderRow.source_order_codes || '') + .split(',') + .map(code => String(code || '').trim()) + .filter(code => !!code); + const sourceItem = Array.isArray(orderItems) + ? orderItems.find(item => item && String(item.source_order_code || '').trim()) + : null; + const itemSourceOrderCode = String(sourceItem && sourceItem.source_order_code || '').trim(); + const stockoutOrderCode = String(sourceOrderCodes[0] || itemSourceOrderCode || '').trim(); + + if (!stockoutOrderCode) { + const message = '出库单转订单回传失败:未找到订单来源出库单号'; + await markPendingExceptionInternal(service, orderModel, orderId, warehouseId, message); + return buildFailure(message); + } + + const stockoutOrder = await ctx.model.OrderStockout.findOne({ + where: { + stockout_order_code: stockoutOrderCode, + warehouse_id: warehouseId, + deleted_at: null, + }, + raw: true, + }); + + if (!stockoutOrder) { + const message = `出库单转订单回传失败:出库单(${stockoutOrderCode})不存在`; + await markPendingExceptionInternal(service, orderModel, orderId, warehouseId, message); + return buildFailure(message); + } + + // 幂等:出库单已完成同步(并发/重试场景),跳过外部通知,直接收尾 + if (String(stockoutOrder.sync_status || '').trim() === 'SUCCESS') { + service.ctx.logger.info(`[syncStockoutOrders] 出库单已完成同步,跳过通知直接收尾 stockoutOrderCode=${stockoutOrderCode}`); + try { + await finalizeSuccessfulStockoutSyncInternal(service, orderModel, orderItemsModel, orderId, warehouseId, stockoutOrder, {}, orderRow); + return { + order_id: orderId, + delivery_order_code: deliveryOrderCode, + status: 'success', + message: '出库单已同步,订单收尾完成', + }; + } catch (error) { + const message = `出库单回传后收尾失败:${error.message}`; + await orderModel.update({ + sync_status: 'error', + order_flag: message, + updated_at: new Date(), + }, { + where: { id: orderId, warehouse_id: warehouseId }, + }); + await markPendingExceptionInternal(service, orderModel, orderId, warehouseId, message); + return buildFailure(message); + } + } + + // 运单号校验:订单未分配运单号时无法回传出库单 + // STOCKOUT 渠道运单号只认 wms_order_express 表,不回退订单主表 express_code(面单号前置) + const normalizedWaybillCodes = (Array.isArray(waybillCodes) ? waybillCodes : []) + .map(code => String(code || '').trim()) + .filter(code => !!code); + if (normalizedWaybillCodes.length === 0) { + const message = '出库单转订单回传失败:订单未分配运单号'; + await orderModel.update({ + sync_status: 'error', + order_flag: message, + updated_at: new Date(), + }, { + where: { id: orderId, warehouse_id: warehouseId }, + }); + await markPendingExceptionInternal(service, orderModel, orderId, warehouseId, message); + return buildFailure(message); + } + + const stockoutItems = await ctx.model.OrderStockoutItems.findAll({ + where: { order_id: stockoutOrder.id }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + // 快递信息写回字段(回传成功落库):物流编码/名称 + 运单号列表 + const expressWriteback = { + waybill_code: normalizedWaybillCodes[0] || '', + waybill_codes: normalizedWaybillCodes, + express_code: String( + orderRow.sys_logistics_code + || orderRow.logistics_code + || stockoutOrder.express_code + || '' + ).trim(), + express_name: String( + orderRow.sys_logistics_name + || orderRow.logistics_name + || stockoutOrder.express_name + || '' + ).trim(), + }; + + // 通知外部(奇门 stockout.confirm / OpenAPI 回调,按出库单 source_type 分流) + const requestData = buildStockoutConfirmDataInternal(service, stockoutOrder, orderRow, stockoutItems, normalizedWaybillCodes); + const notifyResult = await notifyStockoutExternalInternal(service, stockoutOrder, requestData, { + ...context, + appKey: String(context.appKey || orderRow.from_key || '').trim(), + }); + + if (!notifyResult || notifyResult.success !== true) { + const message = `出库单转订单回传失败:${String(notifyResult && notifyResult.message || '通知外部失败').trim()}`; + await orderModel.update({ + sync_status: 'error', + order_flag: message, + updated_at: new Date(), + }, { + where: { id: orderId, warehouse_id: warehouseId }, + }); + await ctx.model.OrderStockout.update({ + sync_status: 'FAILED', + sync_message: message, + updated_at: new Date(), + }, { + where: { id: stockoutOrder.id }, + }); + await markPendingExceptionInternal(service, orderModel, orderId, warehouseId, message); + return buildFailure(message); + } + + try { + await finalizeSuccessfulStockoutSyncInternal( + service, + orderModel, + orderItemsModel, + orderId, + warehouseId, + stockoutOrder, + expressWriteback, + orderRow + ); + } catch (error) { + const message = `出库单回传后库存扣减失败:${error.message}`; + await orderModel.update({ + sync_status: 'error', + order_flag: message, + updated_at: new Date(), + }, { + where: { id: orderId, warehouse_id: warehouseId }, + }); + await markPendingExceptionInternal(service, orderModel, orderId, warehouseId, message); + return buildFailure(message); + } + + service.ctx.logger.info(`[syncStockoutOrders] 出库单回传成功 stockoutOrderCode=${stockoutOrderCode} orderId=${orderId}`); + + return { + order_id: orderId, + delivery_order_code: deliveryOrderCode, + status: 'success', + message: '出库单回传成功', + }; +} + +/** + * STOCKOUT 创建渠道订单同步入口。 + * + * 从待处理订单同步入口(syncOrderIds)按 create_channel 分组路由到本函数: + * 反查对应出库单,把订单实际快递编码/运单号写回出库单并通知外部 + * (QM→奇门 stockout.confirm,API→OpenAPI 回调),成功后才扣减库存完成同步。 + * + * @param {Object} service 服务实例 + * @param {Object} groupedOrder 分组后的订单 + * @param {Object} context 上下文 + * @return {Promise} 同步结果 + */ +async function syncStockoutOrdersInternal(service, groupedOrder = {}, context = {}) { + const orderIds = Array.isArray(groupedOrder.order_ids) + ? groupedOrder.order_ids.map(orderId => Number(orderId)).filter(orderId => Number.isFinite(orderId) && orderId > 0) + : []; + const warehouseId = Number(context.warehouseId || 0); + + if (orderIds.length === 0) { + return { + create_channel: CREATE_CHANNEL_STOCKOUT, + order_ids: [], + order_count: 0, + warehouse_id: warehouseId, + handler: 'syncStockoutOrders', + sync_target: 'stockout', + orders: [], + sync_results: [], + route_state: 'rejected', + status: 'failed', + message: 'STOCKOUT 同步订单不能为空', + success_count: 0, + failed_count: 0, + }; + } + + if (warehouseId <= 0) { + return { + create_channel: CREATE_CHANNEL_STOCKOUT, + order_ids: orderIds, + order_count: Number.isFinite(Number(groupedOrder.order_count)) ? Number(groupedOrder.order_count) : orderIds.length, + warehouse_id: warehouseId, + handler: 'syncStockoutOrders', + sync_target: 'stockout', + orders: Array.isArray(groupedOrder.orders) ? groupedOrder.orders.map(order => ({ ...order })) : [], + sync_results: [], + route_state: 'rejected', + status: 'failed', + message: '缺少仓库上下文', + success_count: 0, + failed_count: orderIds.length, + }; + } + + const orderModel = await service.ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); + const orderItemsModel = await service.ctx.model.OrderItemsFactory.getCurrentModel(warehouseId); + const { Op } = service.app.Sequelize; + const [ orderRows, orderItemRows ] = await Promise.all([ + orderModel.findAll({ + where: { + id: { + [Op.in]: orderIds, + }, + warehouse_id: warehouseId, + }, + raw: true, + }), + orderItemsModel.findAll({ + where: { + order_id: { + [Op.in]: orderIds, + }, + }, + raw: true, + }), + ]); + + const orderMap = new Map(); + for (const orderRow of Array.isArray(orderRows) ? orderRows : []) { + if (orderRow && Number(orderRow.id) > 0) { + if (String(orderRow.sync_status || '').trim() === 'fin') { + service.ctx.logger.info(`[syncStockoutOrders] 订单已完成同步,跳过派发 orderId=${orderRow.id}`); + continue; + } + orderMap.set(Number(orderRow.id), orderRow); + } + } + + const waybillCodeMap = await buildOrderWaybillCodeMapInternal(service, orderIds); + + const itemsByOrderId = new Map(); + for (const orderItem of Array.isArray(orderItemRows) ? orderItemRows : []) { + const itemOrderId = Number(orderItem && orderItem.order_id); + if (!Number.isFinite(itemOrderId) || itemOrderId <= 0) { + continue; + } + + if (!itemsByOrderId.has(itemOrderId)) { + itemsByOrderId.set(itemOrderId, []); + } + + itemsByOrderId.get(itemOrderId).push(orderItem); + } + + const progressCacheKey = getSyncOrderIdsProgressCacheKey(context.request_id); + const uniqueOrderIds = [ ...new Set(orderIds) ]; + const syncResults = []; + for (let i = 0; i < uniqueOrderIds.length; i += DISPATCH_BATCH_SIZE) { + const batch = uniqueOrderIds.slice(i, i + DISPATCH_BATCH_SIZE); + const batchResults = await Promise.all(batch.map(orderId => { + const dispatchedOrderRow = orderMap.get(orderId); + if (!dispatchedOrderRow) { + service.ctx.logger.info(`[syncStockoutOrders] 订单已过滤,跳过 orderId=${orderId}`); + return { order_id: orderId, status: 'skipped', message: '订单已完成同步,跳过' }; + } + + return processStockoutOrderInternal( + service, + orderModel, + orderItemsModel, + orderId, + warehouseId, + dispatchedOrderRow, + itemsByOrderId.get(orderId) || [], + context, + waybillCodeMap.get(orderId) + ); + })); + syncResults.push(...batchResults); + await updateDispatchBatchProgress(service, progressCacheKey, batchResults.length); + } + + const successCount = syncResults.filter(item => item.status === 'success').length; + const failedCount = syncResults.filter(item => item.status === 'failed').length; + const overallSuccess = failedCount === 0 && successCount === syncResults.length; + + return { + create_channel: CREATE_CHANNEL_STOCKOUT, + order_ids: orderIds, + order_count: Number.isFinite(Number(groupedOrder.order_count)) ? Number(groupedOrder.order_count) : orderIds.length, + warehouse_id: warehouseId, + handler: 'syncStockoutOrders', + sync_target: 'stockout', + orders: Array.isArray(groupedOrder.orders) ? groupedOrder.orders.map(order => ({ ...order })) : [], + sync_results: syncResults, + route_state: overallSuccess ? 'accepted' : 'rejected', + status: overallSuccess ? 'success' : 'failed', + message: overallSuccess ? '出库单回传成功' : '出库单回传失败', + success_count: successCount, + failed_count: failedCount, + }; +} + function buildManualSyncNoticePayloadInternal(syncResult = {}, context = {}) { const orderIds = Array.isArray(syncResult.order_ids) ? syncResult.order_ids.map(orderId => Number(orderId)).filter(orderId => Number.isFinite(orderId) && orderId > 0) @@ -1825,6 +2458,20 @@ class OrderAsyncService extends MainService { async syncApiOrders(groupedOrder = {}, context = {}) { return await finalizeLocalChannelOrdersInternal(this, CREATE_CHANNEL_API, groupedOrder, context, 'api'); } + + /** + * STOCKOUT 创建入口处理(出库单转订单回传)。 + * + * 回传时把订单实际快递编码/运单号写回出库单,并按出库单来源通知外部 + * (QM→奇门 stockout.confirm,API→OpenAPI 回调),成功后才扣减库存完成同步。 + * + * @param {Object} groupedOrder 分组后的订单。 + * @param {Object} context 上下文。 + * @return {Promise} 处理结果。 + */ + async syncStockoutOrders(groupedOrder = {}, context = {}) { + return await syncStockoutOrdersInternal(this, groupedOrder, context); + } } module.exports = OrderAsyncService; diff --git a/app/service/systems/order_packing.js b/app/service/systems/order_packing.js index f069d26..6fd3096 100644 --- a/app/service/systems/order_packing.js +++ b/app/service/systems/order_packing.js @@ -587,12 +587,26 @@ class OrderPackingService extends Service { const updates = { end_time: finalEndTime }; // 若任务状态不是已完成(2),同步更新为已完成 - if (record.status !== 2) { + const wasFinished = record.status === 2; + if (!wasFinished) { updates.status = 2; } await record.update(updates); + // 任务由未结束转为已完成时,同步更新关联订单打包状态(与 workbench.finishPack 语义一致) + if (!wasFinished && updates.status === 2 && workbenchService + && typeof workbenchService._updateOrderPackStatus === 'function') { + const isGroupTask = Number(record.pack_mode) === 2; + const taskWaveId = isGroupTask ? Number(record.wave_id || 0) : 0; + await workbenchService._updateOrderPackStatus(warehouseId, { + orderId: Number(record.order_id || 0), + waveId: taskWaveId, + packStatus: 2, + caller: 'OrderPacking.setEndTime', + }); + } + return { code: 200, message: '结束时间设置成功', diff --git a/app/service/systems/order_storage_allocation.js b/app/service/systems/order_storage_allocation.js index f0e3f31..81257d0 100644 --- a/app/service/systems/order_storage_allocation.js +++ b/app/service/systems/order_storage_allocation.js @@ -1568,7 +1568,8 @@ class OrderStorageAllocationService extends MainService { * 待处理订单同步入口。 * * 先完成订单查询、过滤与分组,再按 `create_channel` 路由到 - * `orderAsync.syncQmOrders`、`orderAsync.syncManualOrders`、`orderAsync.syncApiOrders` 三个处理入口。 + * `orderAsync.syncQmOrders`、`orderAsync.syncManualOrders`、`orderAsync.syncApiOrders`、 + * `orderAsync.syncStockoutOrders` 四个处理入口。 * * @param {Object} data 请求体。 * @return {Promise} 同步结果。 @@ -1966,6 +1967,10 @@ class OrderStorageAllocationService extends MainService { result = await orderAsyncService.syncQmOrders(groupedOrder, routeContext); } else if (createChannel === 'API') { result = await orderAsyncService.syncApiOrders(groupedOrder, routeContext); + } else if (createChannel === 'STOCKOUT') { + // 出库单转订单渠道:回传时把快递编码/运单号写回出库单并通知外部, + // 成功后才完成订单同步 + result = await orderAsyncService.syncStockoutOrders(groupedOrder, routeContext); } else { result = await orderAsyncService.syncManualOrders(groupedOrder, routeContext); } diff --git a/app/service/systems/setting/warehouse.js b/app/service/systems/setting/warehouse.js index 77a1856..78ec94c 100644 --- a/app/service/systems/setting/warehouse.js +++ b/app/service/systems/setting/warehouse.js @@ -292,6 +292,14 @@ const WAREHOUSE_SETTING_FIELDS = Object.freeze([ description: '团购打包最大时长,单位:分钟,默认 40', min: 1, }), + Object.freeze({ + key: 'default_location_id', + name: '默认库位', + type: 'location', + default: null, + required: false, + description: '仓库未指定库位入库/上架时使用的默认库位(库位ID)', + }), Object.freeze({ key: INTERNAL_WAVE_STRATEGY_VERSION_KEY, name: '仓库波次策略版本号', @@ -560,6 +568,47 @@ class SettingWarehouseService extends Service { }; } + /** + * 校验默认库位是否属于当前仓库。 + * + * 传入的 default_location_id 为库位ID(wms_location_space.id),仅当该库位 + * 属于当前仓库且未删除、已启用时才允许写入。 + * + * @param {*} locationIdValue 待校验的库位ID。 + * @param {number} warehouseId 当前仓库 ID。 + * @return {Promise} 无返回值。 + * @throws {Error} 库位ID非法或不属于当前仓库时抛出,状态码 400。 + */ + async validateDefaultLocation(locationIdValue, warehouseId) { + if (locationIdValue === undefined || locationIdValue === null || locationIdValue === '') { + return; + } + + const locationId = Number(locationIdValue); + if (!Number.isInteger(locationId) || locationId <= 0) { + throw this.createError('default_location_id 必须是正整数库位ID', 400); + } + + const locationModel = this.ctx && this.ctx.model && this.ctx.model.LocationSpace; + if (!locationModel || typeof locationModel.findOne !== 'function') { + return; + } + + const locationSpace = await locationModel.findOne({ + where: { + id: locationId, + warehouse_id: warehouseId, + is_enabled: true, + deleted_at: null, + }, + attributes: [ 'id' ], + }); + + if (!locationSpace) { + throw this.createError(`默认库位 ${locationId} 不属于当前仓库`, 400); + } + } + /** * 修改当前仓库设置并清理当前仓库缓存。 * @@ -589,6 +638,11 @@ class SettingWarehouseService extends Service { throw this.createError('subject_config 参数不能为空且必须是对象', 400); } + // 默认库位必须属于当前仓库(值为库位ID) + if (Object.prototype.hasOwnProperty.call(nextPatch, 'default_location_id')) { + await this.validateDefaultLocation(nextPatch.default_location_id, warehouseId); + } + const nextPatchForMerge = { ...nextPatch, }; diff --git a/app/service/systems/storage/inventory.js b/app/service/systems/storage/inventory.js index ad364b1..5b2e918 100644 --- a/app/service/systems/storage/inventory.js +++ b/app/service/systems/storage/inventory.js @@ -1989,6 +1989,21 @@ class InventoryService extends Service { const storeId = receiving.store_id; + // 默认库位:优先使用仓库设置 default_location_id,未设置则兜底库位 1 + let defaultSpaceId = 1; + try { + const deliveryOrderService = ctx.service && ctx.service.systems && ctx.service.systems.deliveryOrder; + const subjectConfig = deliveryOrderService && typeof deliveryOrderService.getStoreSubjectConfig === 'function' + ? await deliveryOrderService.getStoreSubjectConfig(warehouseId) + : null; + const configuredLocationId = Number(subjectConfig && subjectConfig.default_location_id || 0); + if (Number.isInteger(configuredLocationId) && configuredLocationId > 0) { + defaultSpaceId = configuredLocationId; + } + } catch (error) { + ctx.logger.warn('[inventory.directPutaway] 读取仓库默认库位失败,兜底库位 1: %s', error.message); + } + // ────────── 3. 检查货主配置:是否允许收货单直入库存 ────────── const storeWarehouse = await ctx.model.StoreWarehouse.findOne({ where: { store_id: storeId, warehouse_id: warehouseId, warehouse_use_status: 1 }, @@ -2210,8 +2225,8 @@ class InventoryService extends Service { const qty = Number(detail.actual_quantity) || 0; if (qty <= 0) continue; - // 收货明细有库位则按其库位入库,否则使用默认库位 - const spaceId = Number(detail.space_id) > 0 ? Number(detail.space_id) : 1; + // 收货明细有库位则按其库位入库,否则使用仓库默认库位(未设置时兜底库位 1) + const spaceId = Number(detail.space_id) > 0 ? Number(detail.space_id) : defaultSpaceId; const batchNo = detail.batch_number || entryOrderCode; const productionDate = detail.production_date || null; const expiryDate = detail.expiry_date || null; diff --git a/app/service/systems/storage/receiving.js b/app/service/systems/storage/receiving.js index 444707d..56a4c9f 100644 --- a/app/service/systems/storage/receiving.js +++ b/app/service/systems/storage/receiving.js @@ -2642,6 +2642,21 @@ class ReceivingService extends Service { } try { + // 默认库位:优先使用仓库设置 default_location_id,未设置则兜底库位 1 + let defaultSpaceId = 1; + try { + const deliveryOrderService = ctx.service && ctx.service.systems && ctx.service.systems.deliveryOrder; + const subjectConfig = deliveryOrderService && typeof deliveryOrderService.getStoreSubjectConfig === 'function' + ? await deliveryOrderService.getStoreSubjectConfig(warehouse_id) + : null; + const configuredLocationId = Number(subjectConfig && subjectConfig.default_location_id || 0); + if (Number.isInteger(configuredLocationId) && configuredLocationId > 0) { + defaultSpaceId = configuredLocationId; + } + } catch (error) { + ctx.logger.warn('[receiving.addDetail] 读取仓库默认库位失败,兜底库位 1: %s', error.message); + } + const defaultDetail = { receiving_id, product_name: '新商品', @@ -2657,7 +2672,7 @@ class ReceivingService extends Service { production_date: null, expiry_date: null, remark: '', - space_id: 1, + space_id: defaultSpaceId, creator_id, }; diff --git a/app/service/systems/workbench.js b/app/service/systems/workbench.js index c5b0bd9..3074cd0 100644 --- a/app/service/systems/workbench.js +++ b/app/service/systems/workbench.js @@ -353,6 +353,8 @@ class WorkbenchService extends Service { const changeSummary = this._buildPackChangeSummary(packData); const operationCode = isSandan === 1 ? 'ORDER_PACK' : 'ORDER_PACK_GROUP'; + const isFinish = Number(packData && packData.status) >= 2; + const actionText = isFinish ? '打包完成' : '开始打包'; if (isSandan === 1) { // 散单:写入单个订单操作日志 @@ -363,7 +365,7 @@ class WorkbenchService extends Service { operator, extras: { warehouseId, - message: `散单打包完成:${changeSummary}`, + message: `散单${actionText}:${changeSummary}`, }, }]); ctx.logger.info('[Workbench._writePackOperationLog] 散单操作日志已写入 orderId=%d', orderId); @@ -378,7 +380,7 @@ class WorkbenchService extends Service { operator, extras: { warehouseId, - message: `打包完成:${changeSummary}`, + message: `${actionText}:${changeSummary}`, }, }]); return; @@ -394,13 +396,13 @@ class WorkbenchService extends Service { operator, extras: { warehouseId, - message: `打包完成(波次 ${waveNo || waveId}):${changeSummary}`, + message: `${actionText}(波次 ${waveNo || waveId}):${changeSummary}`, }, }]); return; } - const messagePrefix = `团购打包完成(波次 ${waveNo || waveId},共${waveOrderIds.length}单):`; + const messagePrefix = `${isFinish ? '团购打包完成' : '团购开始打包'}(波次 ${waveNo || waveId},共${waveOrderIds.length}单):`; const payloads = waveOrderIds.map(oid => ({ businessType: 'order', businessId: String(oid), @@ -426,6 +428,75 @@ class WorkbenchService extends Service { } } + /** + * 更新订单打包状态字段(散单按订单ID更新单笔,团购按波次批量更新)。 + * 遍历 current + dispatch 分表,异常仅记录日志不影响主流程。 + * 团购批量更新时跳过拦截订单(intercept_status 空值按 none 处理)。 + * + * @param {number} warehouseId 仓库ID + * @param {Object} options + * @param {number} options.orderId 订单ID(散单使用) + * @param {number} options.waveId 波次ID(>0 时按团购批量更新) + * @param {number|string} options.packStatus 任务状态数值(1=打包中 2=已完成) + * @param {string} [options.caller] 调用方标识(仅用于日志) + * @returns {Promise} 实际写入的 pack_status 值 + */ + async _updateOrderPackStatus(warehouseId, { orderId, waveId, packStatus, caller = 'Workbench' }) { + const { ctx } = this; + const statusNum = parseInt(packStatus); + const orderPackStatus = statusNum >= 2 ? 'fin' : (statusNum === 1 ? 'padding' : 'fin'); + const orderUpdateData = { pack_status: orderPackStatus }; + + const orderDeliveryFactory = ctx.model.OrderDeliveryFactory; + const tableOrders = [ + { label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) }, + { label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) }, + ]; + + if (waveId > 0) { + // 团购:批量更新波次下所有未拦截订单 + for (const entry of tableOrders) { + try { + const model = await entry.getModel(); + if (!model) continue; + const affected = await model.update(orderUpdateData, { + where: { + wave_id: waveId, + warehouse_id: warehouseId, + intercept_status: { [ctx.app.Sequelize.Op.in]: [ 'none', null ] }, + }, + }); + if (affected[0] > 0) { + ctx.logger.info('[%s._updateOrderPackStatus] 团购批量更新订单打包状态 waveId=%d pack_status=%s table=%s affected=%d', + caller, waveId, orderPackStatus, entry.label, affected[0]); + } + } catch (err) { + ctx.logger.warn('[%s._updateOrderPackStatus] 更新分表 %s 失败: %s', caller, entry.label, err.message); + } + } + } else { + // 散单:按订单ID更新单个订单 + for (const entry of tableOrders) { + try { + const model = await entry.getModel(); + if (!model) continue; + const affected = await model.update(orderUpdateData, { + where: { id: orderId, warehouse_id: warehouseId }, + }); + if (affected[0] > 0) { + ctx.logger.info('[%s._updateOrderPackStatus] 更新订单打包状态 orderId=%d pack_status=%s table=%s', + caller, orderId, orderPackStatus, entry.label); + break; + } + } catch (err) { + ctx.logger.warn('[%s._updateOrderPackStatus] 更新分表 %s 失败: %s', caller, entry.label, err.message); + } + } + } + + return orderPackStatus; + } + /** * 打包任务写入:根据发货单号查询订单并创建/更新打包任务记录 * @param {Object} params - { delivery_order_code, wave_no, warehouse_id, workbench_id, status, pack_time } @@ -601,44 +672,13 @@ class WorkbenchService extends Service { const packTask = await ctx.model.PackTask.create(packData); ctx.logger.info('[Workbench._packOrder] 创建打包任务 taskId=%d orderId=%d', packTask.id, orderId); - // 步骤6.5:更新订单的打包状态字段 - const orderPackStatus = (packStatus !== undefined && parseInt(packStatus) >= 2) ? 'fin' - : (packStatus !== undefined && parseInt(packStatus) === 1) ? 'padding' - : 'fin'; - const orderUpdateData = { pack_status: orderPackStatus }; - - if (isSandan === 1) { - // 散单:更新单个订单 - for (const entry of tableOrders) { - try { - const model = await entry.getModel(); - if (!model) continue; - const affected = await model.update(orderUpdateData, { - where: { id: orderId, warehouse_id: warehouseId }, - }); - if (affected[0] > 0) { - ctx.logger.info('[Workbench._packOrder] 更新订单打包状态 orderId=%d pack_status=%s table=%s', - orderId, orderPackStatus, entry.label); - break; - } - } catch (_err) { continue; } - } - } else if (waveId > 0) { - // 团购:批量更新波次下所有订单(拦截订单不更新) - for (const entry of tableOrders) { - try { - const model = await entry.getModel(); - if (!model) continue; - const affected = await model.update(orderUpdateData, { - where: { wave_id: waveId, warehouse_id: warehouseId, intercept_status: 'none' }, - }); - if (affected[0] > 0) { - ctx.logger.info('[Workbench._packOrder] 团购批量更新订单打包状态 waveId=%d pack_status=%s table=%s affected=%d', - waveId, orderPackStatus, entry.label, affected[0]); - } - } catch (_err) { continue; } - } - } + // 步骤6.5:更新订单的打包状态字段(散单按订单更新,团购按波次批量更新) + await this._updateOrderPackStatus(warehouseId, { + orderId, + waveId: isSandan === 1 ? 0 : waveId, + packStatus, + caller: 'Workbench._packOrder', + }); // 步骤7:写入打包人员信息 const users = Array.isArray(usersParam) ? usersParam : []; @@ -844,6 +884,37 @@ class WorkbenchService extends Service { ctx.logger.info('[Workbench._finishPack] 工作台 %d 结束打包任务 taskId=%d orderId=%d', validWorkbenchId, lastTask.id, lastTask.order_id); + // 同步更新关联订单打包状态:散单更新单笔订单,团购批量更新波次下所有未拦截订单 + const isGroupTask = Number(lastTask.pack_mode) === 2; + const taskOrderId = Number(lastTask.order_id || 0); + const taskWaveId = isGroupTask ? Number(lastTask.wave_id || 0) : 0; + await this._updateOrderPackStatus(warehouseId, { + orderId: taskOrderId, + waveId: taskWaveId, + packStatus: 2, + caller: 'Workbench._finishPack', + }); + + // 写入完成操作日志(团购批量写波次订单,操作人取自任务记录 operator_text) + const operatorText = String(lastTask.operator_text || ''); + await this._writePackOperationLog({ + warehouseId, + orderId: taskOrderId, + waveId: taskWaveId, + waveNo: lastTask.wave_no || '', + isSandan: isGroupTask ? 0 : 1, + packData: { + pack_mode: lastTask.pack_mode, + status: 2, + pack_quantity: lastTask.pack_quantity, + item_quantity: lastTask.item_quantity, + sku_count: lastTask.sku_count, + workbench_id: validWorkbenchId, + wave_no: lastTask.wave_no, + }, + users: operatorText ? [{ real_name: operatorText }] : [], + }); + return { workbench_id: validWorkbenchId, finished: true, @@ -1203,13 +1274,24 @@ class WorkbenchService extends Service { const { order_id: orderId, waybill_code: waybillCode } = expressRecord; - // 步骤2:遍历 current → dispatch 分表查找订单详情 + // 步骤2:序列表定位优先(命中则先查对应分表),未命中按 current → dispatch 回退遍历 const orderDeliveryFactory = ctx.model.OrderDeliveryFactory; const tableOrders = [ { label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) }, { label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) }, ]; + try { + if (orderDeliveryFactory && typeof orderDeliveryFactory.getOrderLocation === 'function') { + const preferredLocation = await orderDeliveryFactory.getOrderLocation(orderId, warehouseId); + if (preferredLocation) { + tableOrders.sort((a, b) => (a.label === preferredLocation ? -1 : b.label === preferredLocation ? 1 : 0)); + } + } + } catch (locErr) { + ctx.logger.warn('[Workbench._queryOrder] 序列表定位失败,按默认顺序遍历: %s', locErr.message); + } + let orderRow = null; let sourceTable = null; for (const entry of tableOrders) { @@ -1375,6 +1457,7 @@ class WorkbenchService extends Service { wave_no: orderRow.wave_no, post_status: orderRow.post_status, pick_status: orderRow.pick_status, + pack_status: orderRow.pack_status, recheck_status: orderRow.recheck_status, outbound_status: orderRow.outbound_status, items_count: orderRow.items_count, diff --git a/database/migrations/20260826090000-add-stockout-updateInfo-permission.js b/database/migrations/20260826090000-add-stockout-updateInfo-permission.js new file mode 100644 index 0000000..260c3e5 --- /dev/null +++ b/database/migrations/20260826090000-add-stockout-updateInfo-permission.js @@ -0,0 +1,58 @@ +'use strict'; + +/** + * 为 storage.stockout.updateInfo 添加 API 权限并授权。 + * + * 权限 ID(固定):563 — storage.stockout.updateInfo 修改出库单信息 + * 授权角色:经理(8)、仓库组-主管(26)、客服组-主管(28)、生产组-主管(29)、客服组-员工(30) + */ +module.exports = { + up: async queryInterface => { + // ===== 第一步:写入权限行 ===== + await queryInterface.sequelize.query(` + INSERT INTO wms_permission (id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at) + VALUES (563, 'storage.stockout.updateInfo', NULL, 'storage.stockout.updateInfo', NULL, 'API:修改出库单信息', NULL, 0, 0, NULL, 'api', 0, 1, NOW(), NOW()) + ON DUPLICATE KEY UPDATE path='storage.stockout.updateInfo', meta_title='API:修改出库单信息', type='api' + `); + + // ===== 第二步:授权给经理及各主管/客服员工角色 ===== + const roleIds = [ 8, 26, 28, 29, 30 ]; + + for (const roleId of roleIds) { + await queryInterface.sequelize.query(` + UPDATE wms_role + SET permissions = JSON_ARRAY_APPEND(permissions, '$', CAST(563 AS UNSIGNED)), + updated_at = NOW() + WHERE id = ${roleId} + AND permissions IS NOT NULL + AND permissions != '*' + AND permissions != '[]' + AND JSON_VALID(permissions) = 1 + AND JSON_CONTAINS(permissions, '563', '$') = 0 + `); + } + }, + + down: async queryInterface => { + const roleIds = [ 8, 26, 28, 29, 30 ]; + + for (const roleId of roleIds) { + await queryInterface.sequelize.query(` + UPDATE wms_role + SET permissions = JSON_REMOVE( + permissions, + JSON_UNQUOTE(JSON_SEARCH(permissions, 'one', '563')) + ), + updated_at = NOW() + WHERE id = ${roleId} + AND permissions IS NOT NULL + AND permissions != '*' + AND permissions != '[]' + `); + } + + await queryInterface.sequelize.query(` + DELETE FROM wms_permission WHERE id = 563 + `); + }, +}; diff --git a/database/migrations/20260826093000-add-stockout-cancel-permission.js b/database/migrations/20260826093000-add-stockout-cancel-permission.js new file mode 100644 index 0000000..134694e --- /dev/null +++ b/database/migrations/20260826093000-add-stockout-cancel-permission.js @@ -0,0 +1,56 @@ +'use strict'; + +/** + * 为 storage.stockout.cancel 添加 API 权限并授权。 + * + * 权限 ID(固定):564 — storage.stockout.cancel 出库单取消 + * 授权角色:经理(8)、仓库组-主管(26)、客服组-主管(28)、生产组-主管(29)、客服组-员工(30) + */ +module.exports = { + up: async queryInterface => { + await queryInterface.sequelize.query(` + INSERT INTO wms_permission (id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at) + VALUES (564, 'storage.stockout.cancel', NULL, 'storage.stockout.cancel', NULL, 'API:出库单取消', NULL, 0, 0, NULL, 'api', 0, 1, NOW(), NOW()) + ON DUPLICATE KEY UPDATE path='storage.stockout.cancel', meta_title='API:出库单取消', type='api' + `); + + const roleIds = [ 8, 26, 28, 29, 30 ]; + + for (const roleId of roleIds) { + await queryInterface.sequelize.query(` + UPDATE wms_role + SET permissions = JSON_ARRAY_APPEND(permissions, '$', CAST(564 AS UNSIGNED)), + updated_at = NOW() + WHERE id = ${roleId} + AND permissions IS NOT NULL + AND permissions != '*' + AND permissions != '[]' + AND JSON_VALID(permissions) = 1 + AND JSON_CONTAINS(permissions, '564', '$') = 0 + `); + } + }, + + down: async queryInterface => { + const roleIds = [ 8, 26, 28, 29, 30 ]; + + for (const roleId of roleIds) { + await queryInterface.sequelize.query(` + UPDATE wms_role + SET permissions = JSON_REMOVE( + permissions, + JSON_UNQUOTE(JSON_SEARCH(permissions, 'one', '564')) + ), + updated_at = NOW() + WHERE id = ${roleId} + AND permissions IS NOT NULL + AND permissions != '*' + AND permissions != '[]' + `); + } + + await queryInterface.sequelize.query(` + DELETE FROM wms_permission WHERE id = 564 + `); + }, +}; diff --git a/database/migrations/20260826100000-add-stockout-listLogs-permission.js b/database/migrations/20260826100000-add-stockout-listLogs-permission.js new file mode 100644 index 0000000..d31f701 --- /dev/null +++ b/database/migrations/20260826100000-add-stockout-listLogs-permission.js @@ -0,0 +1,56 @@ +'use strict'; + +/** + * 为 storage.stockout.listLogs 添加 API 权限并授权。 + * + * 权限 ID(固定):565 — storage.stockout.listLogs 出库单操作日志查询 + * 授权角色:经理(8)、仓库组-主管(26)、客服组-主管(28)、生产组-主管(29)、客服组-员工(30) + */ +module.exports = { + up: async queryInterface => { + await queryInterface.sequelize.query(` + INSERT INTO wms_permission (id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at) + VALUES (565, 'storage.stockout.listLogs', NULL, 'storage.stockout.listLogs', NULL, 'API:出库单操作日志', NULL, 0, 0, NULL, 'api', 0, 1, NOW(), NOW()) + ON DUPLICATE KEY UPDATE path='storage.stockout.listLogs', meta_title='API:出库单操作日志', type='api' + `); + + const roleIds = [ 8, 26, 28, 29, 30 ]; + + for (const roleId of roleIds) { + await queryInterface.sequelize.query(` + UPDATE wms_role + SET permissions = JSON_ARRAY_APPEND(permissions, '$', CAST(565 AS UNSIGNED)), + updated_at = NOW() + WHERE id = ${roleId} + AND permissions IS NOT NULL + AND permissions != '*' + AND permissions != '[]' + AND JSON_VALID(permissions) = 1 + AND JSON_CONTAINS(permissions, '565', '$') = 0 + `); + } + }, + + down: async queryInterface => { + const roleIds = [ 8, 26, 28, 29, 30 ]; + + for (const roleId of roleIds) { + await queryInterface.sequelize.query(` + UPDATE wms_role + SET permissions = JSON_REMOVE( + permissions, + JSON_UNQUOTE(JSON_SEARCH(permissions, 'one', '565')) + ), + updated_at = NOW() + WHERE id = ${roleId} + AND permissions IS NOT NULL + AND permissions != '*' + AND permissions != '[]' + `); + } + + await queryInterface.sequelize.query(` + DELETE FROM wms_permission WHERE id = 565 + `); + }, +}; diff --git a/methods/changes/system.json b/methods/changes/system.json index f6bb4bc..e09e68e 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,168 @@ [ + { + "version": "2026.08.26-workbench-queryOrder-pack-status", + "date": "2026-08-26", + "type": "enhanced", + "summary": "工作台 workbench.business(queryOrder) 查询订单增强:接入订单序列表(wms_order_id_location_*)优先定位分表,未命中按 current→dispatch 回退遍历;响应 order 对象新增 pack_status 字段(散单/团购均返回)。", + "methods": [ + "workbench.business" + ], + "notes": [ + "app/service/systems/workbench.js _queryOrder 步骤2:先经 orderDeliveryFactory.getOrderLocation(orderId, warehouseId) 获取序列表位置,命中则优先查对应分表,失败/未命中保持原 current→dispatch 遍历,与 _sendWeight/waybill/order_express 等模块的序列表优先定位语义一致", + "_queryOrder 响应 order 对象新增 pack_status(none/padding/fin/error),与 pick_status/recheck_status 等状态机并列,工作台可根据打包状态判断该单是否已打包", + "备注:_packOrder 订单查找仍按 delivery_order_code 双表遍历(序列表按 id 定位,发货单号场景暂不适用)" + ], + "module": "workbench" + }, + { + "version": "2026.08.26-finishPack-sync-order-pack-status", + "date": "2026-08-26", + "type": "fixed", + "summary": "修复打包任务结束事件不更新订单打包状态的问题:workbench.finishPack 结束任务后同步更新关联订单 pack_status 为 fin(散单按订单更新,团购按波次批量更新未拦截订单)并写完成操作日志;order.packing.setEndTime 手动结束同样同步订单;打包操作日志文案按任务状态区分(开始打包/打包完成),不再在开始打包时误写“打包完成”。", + "methods": [], + "notes": [ + "问题定位:波次 B2026082503311(团购 7 单)开始打包时 packOrder(status=1) 写入的日志前缀硬编码为“团购打包完成”,实际尾部为“任务状态: 打包中”;设备结束事件走 finishPack 仅更新 wms_pack_task(end_time/status=2),未更新订单,导致订单 pack_status 停留在 padding", + "app/service/systems/workbench.js 新增 _updateOrderPackStatus:遍历 current+dispatch 分表,散单按 order_id 更新单笔,团购按 wave_id 批量更新(intercept_status 空值按 none 处理,拦截订单跳过),异常仅记日志不影响主流程;_packOrder 步骤6.5 改为复用该方法", + "app/service/systems/workbench.js _finishPack:任务结束后按 pack_mode 判定散单/团购,调用 _updateOrderPackStatus(packStatus=2) 同步订单,并按任务记录(含 operator_text 回填操作人)写入完成操作日志", + "app/service/systems/order_packing.js setEndTime:任务由未完成转为已完成时同样调用 _updateOrderPackStatus 同步订单,与 finishPack 语义对齐", + "app/service/systems/workbench.js _writePackOperationLog:日志前缀按 status 区分——status>=2 写“打包完成”,否则写“开始打包”,保留原有字段变更描述", + "定时任务 auto_finish_pack_task 超时自动结束仅关闭任务记录、不更新订单(保持原语义,避免超时误标订单完成),如需要可在后续版本评估同步" + ], + "module": "workbench" + }, + { + "version": "2026.08.26-stockout-listLogs", + "date": "2026-08-26", + "type": "added", + "summary": "新增 storage.stockout.listLogs 出库单操作日志查询接口:按出库单ID或出库单号分页查询 wms_operation_log(business_type=stockout,business_id=出库单ID),覆盖转订单/确认/修改/取消等 STOCKOUT_* 操作,按创建时间倒序;配套 operationLog.queryStockoutLogs 服务方法与权限 565。", + "methods": [ + "storage.stockout.listLogs" + ], + "notes": [ + "app/service/systemMethods/storage/stockout.js 新增 listLogs:支持 id 或 stockout_order_code 定位(出库单号先查表换ID),pagination.page/pageSize(兼容 page_size);出库单不存在返回空列表不报错;仓库上下文取 ctx.user.store_id", + "app/service/systems/operation_log.js 新增 queryStockoutLogs:复用 queryLogsByBusinessType(query, 'stockout')", + "database/migrations/20260826100000-add-stockout-listLogs-permission.js:权限 565,授权角色 8/26/28/29/30,开发库已执行", + "storage.stockout.listItems 出库单明细接口此前已存在(按 stockout_order_code/id 查 wms_order_stockout_items),本次仅补 listLogs 文档", + "实测:listLogs 按 stockout_order_code 与 id=22 均返回分页日志(STOCKOUT_TO_ORDER/STOCKOUT_UPDATE_INFO,含操作人/时间/消息/平台名),pagination.total=4 正确;注意权限迁移后短时间内用户权限上下文缓存可能未刷新导致 403,刷新后正常" + ], + "module": "storage.stockout" + }, + { + "version": "2026.08.26-stockout-order-sync-channel", + "date": "2026-08-26", + "type": "added", + "summary": "订单回传区分 STOCKOUT 创建渠道:待处理订单同步入口(syncOrderIds)按 create_channel 路由新增 syncStockoutOrders,回传时把订单实际快递编码/运单号写回出库单(express_code/express_name/waybill_code/waybill_codes),并按出库单来源通知外部(QM→奇门 taobao.qimen.stockout.confirm,API→OpenAPI 回调 event=stockout_completed,WMS 内部来源直接成功);通知成功后才扣减订单库存并完成同步(sync_status=fin、出库单 COMPLETED/SUCCESS),失败则订单 sync_status=error 标记待处理异常、出库单 sync_status=FAILED 记录失败原因。", + "methods": [ + "order.pendingOrder.syncOrderIds" + ], + "notes": [ + "app/service/systems/order_async.js 新增 syncStockoutOrders/syncStockoutOrdersInternal/processStockoutOrderInternal/notifyStockoutExternalInternal/buildStockoutConfirmDataInternal/finalizeSuccessfulStockoutSyncInternal:反查出库单(订单 source_order_codes 首项或明细 source_order_code),运单号仅认 wms_order_express 表(不回退订单主表 express_code 面单前置);收尾事务内写回出库单 + 订单明细 outbound 扣库存 + sync_status=fin,SELECT FOR UPDATE 防重幂等", + "app/service/systems/order_storage_allocation.js syncOrderIds 渠道路由新增 STOCKOUT 分支(原落入 MANUAL 兜底,不通知外部)", + "出库单已 SUCCESS 的重试场景跳过重复通知,直接收尾;订单未分配运单号时回传失败并提示", + "所有回传入口(pendingOrder.syncOrderIds 异步包装、express_platform 自动同步回传)均汇聚到同一路由,改动一处覆盖全部", + "订单表无 sync_message 列:回传失败提示落在 order_flag 字段(markPendingExceptionInternal 同步置 inspection_status=error/step=3)", + "实测失败路径:测试订单 122172(TEST-SO-20260826004828-003 转单)回传奇门 stockout.confirm 返回 JST_Error,订单 sync_status=error + order_flag 提示,出库单保持 TRANSFERRED + sync_status=FAILED + sync_message 记录原因", + "实测成功路径:出库单 source_type 临时改 WMS(内部来源直接成功)触发回传,订单 sync_status=fin/order_flag 清空/step=2,出库单 COMPLETED/SUCCESS + 写回 express_code=SF/waybill_code/waybill_codes,库存 101389 quantity 100→95、locked 8→3,流水闭环 LOCK(QM_STOCKOUT)→UNLOCK(转单释放)→LOCK(DELIVERY_ORDER)→OUTBOUND(订单出库)" + ], + "module": "order.pendingOrder" + }, + { + "version": "2026.08.26-stockout-cancel", + "date": "2026-08-26", + "type": "added", + "summary": "新增 storage.stockout.cancel 出库单取消:仅 CREATED/PENDING 允许取消;事务内释放创建时占用的库存锁定(QM_STOCKOUT,写 UNLOCK 流水)并置 CANCELLED,写 wms_operation_log 操作日志(STOCKOUT_CANCEL);TRANSFERRED/COMPLETED 禁止取消。新增权限 564 并授权。", + "methods": [ + "storage.stockout.cancel" + ], + "notes": [ + "app/service/systemMethods/storage/stockout.js 新增 cancel:复用 lockItemStorages 负数量释放(锁定不足幂等跳过),与状态更新、操作日志同事务;仓库隔离与 confirm/updateInfo 一致", + "database/migrations/20260826093000-add-stockout-cancel-permission.js:权限 564,授权角色 8/26/28/29/30,开发库已执行", + "实测:取消测试单后 locked_quantity 101379 3→2,UNLOCK 流水(出库单取消释放锁定)与 STOCKOUT_CANCEL 操作日志均落库", + "同步更新 methods/system.json 新增 cancel 接口文档" + ], + "module": "storage.stockout" + }, + { + "version": "2026.08.26-stockout-operation-log", + "date": "2026-08-26", + "type": "added", + "summary": "storage.stockout 链路补写 wms_operation_log 操作日志(businessType=stockout):confirm 直出成功、toOrder 转单成功、updateInfo 修改均写操作记录;新增 updateInfo API 权限 563 并授权;修复 updateInfo 证件号参数名与出库单 ID 冲突。", + "methods": [ + "storage.stockout.confirm", + "storage.stockout.toOrder", + "storage.stockout.updateInfo" + ], + "notes": [ + "app/service/systemMethods/storage/stockout.js 新增 _writeStockoutOperationLog(operationLog.createOperationLogs,失败仅告警不影响主流程):confirm 成功路径与状态更新同事务写 STOCKOUT_CONFIRM(含释放锁总量);toOrder 转单后写 STOCKOUT_TO_ORDER(含新订单号);updateInfo 写 STOCKOUT_UPDATE_INFO(含改动字段摘要)", + "修复:updateInfo 收件人证件号参数由 id 改为 receiver_id(原与出库单ID参数冲突,会把 data.id 误写入 receiver_id 字段)", + "database/migrations/20260826090000-add-stockout-updateInfo-permission.js:新增权限 563(storage.stockout.updateInfo),授权角色 8/26/28/29/30,开发库已执行", + "实测:updateInfo 修改后 wms_operation_log 落库(business_type=stockout、operation_code=STOCKOUT_UPDATE_INFO、operator 阿猫、message 含改动摘要)" + ], + "module": "storage.stockout" + }, + { + "version": "2026.08.26-stockout-confirm-release-lock", + "date": "2026-08-26", + "type": "fixed", + "summary": "storage.stockout.confirm 直出确认后释放出库单创建时占用的库存锁定:出站通知成功后,事务内逐明细 lockItemStorages(-plan_qty, orderType=QM_STOCKOUT) 释放锁定并自动写 UNLOCK 流水,与状态推进到 COMPLETED 同事务提交,失败回滚可重试;释放遇\"锁定不足\"视为幂等成功跳过。", + "methods": [ + "storage.stockout.confirm" + ], + "notes": [ + "修复前:confirm 直出成功后 locked_quantity 一直占用(出库单无取消入口,锁只能靠转订单释放)", + "出站通知失败时锁保持、状态不变(sync_status=FAILED),重试 confirm 成功后才会释放;已释放场景(锁定不足)跳过不阻断", + "实测:本地 confirm 真实出站淘宝奇门返回 JST_Error 单号转换失败,锁保持(101379.locked=3/101389.locked=8 不变),符合设计;释放+UNLOCK 流水由 lockItemStorages 负数量链路保证" + ], + "module": "storage.stockout" + }, + { + "version": "2026.08.26-directPutaway-default-location", + "date": "2026-08-26", + "type": "updated", + "summary": "storage.inventory.directPutaway 默认库位改为读取仓库设置:直入库存写 wms_storage 时,收货明细 space_id 无效则使用 wms_store.subject_config.default_location_id(经 deliveryOrder.getStoreSubjectConfig 缓存优先读取),未设置时兜底库位 1。", + "methods": [ + "storage.inventory.directPutaway" + ], + "notes": [ + "app/service/systems/storage/inventory.js directPutaway:步骤 10 写 wms_storage 的 spaceId 由硬编码 1 改为 defaultSpaceId(收货明细有库位仍按其库位),defaultSpaceId 在方法前段读取仓库设置(正整数有效才采用,否则 1),读取失败仅告警不影响入库", + "与 storage.receiving.addDetail 默认库位口径一致(仓库设置优先,兜底 1)", + "同步更新 methods/system.json directPutaway 的库位规则说明" + ], + "module": "storage.inventory" + }, + { + "version": "2026.08.26-receiving-addDetail-default-location", + "date": "2026-08-26", + "type": "updated", + "summary": "storage.receiving.addDetail 默认库位改为读取仓库设置:新增明细时 space_id 默认取 wms_store.subject_config.default_location_id(经 deliveryOrder.getStoreSubjectConfig 缓存优先读取),未设置时兜底库位 1;前端传入 item.space_id 时仍按传入值。", + "methods": [ + "storage.receiving.addDetail" + ], + "notes": [ + "app/service/systems/storage/receiving.js addDetail:默认明细 space_id 由硬编码 1 改为优先读仓库设置 default_location_id(正整数有效才采用),否则兜底 1;读取失败仅告警不影响创建", + "依赖 deliveryOrder.getStoreSubjectConfig(缓存 10 分钟),saveSettings 保存仓库设置时会同步清理该缓存键", + "同步更新 methods/system.json addDetail 的 item.space_id 描述" + ], + "module": "storage.receiving" + }, + { + "version": "2026.08.26-warehouse-setting-default-location", + "date": "2026-08-26", + "type": "added", + "summary": "仓库设置(wms_store.subject_config)新增\"默认库位\"字段 default_location_id(type location):setting.warehouse.getFieldMeta 字段元信息新增该字段(不返回库位选项列表,库位数量大,前端按仓库搜索选择),saveSettings 传入时校验库位属于当前仓库,否则报 400 拒绝写入。", + "methods": [ + "setting.warehouse.getFieldMeta", + "setting.warehouse.getSettings", + "setting.warehouse.saveSettings" + ], + "notes": [ + "app/service/systems/setting/warehouse.js WAREHOUSE_SETTING_FIELDS 新增 default_location_id(名称:默认库位,type location,default null,描述:仓库未指定库位入库/上架时使用的默认库位);getFieldMeta 不注入库位选项列表(库位数量大,前端按 type=location 自行按仓库搜索库位)", + "saveSettings 新增 validateDefaultLocation:传入 default_location_id 时校验其属于当前仓库,否则 400 '默认库位 {id} 不属于当前仓库';传 null/空清空", + "app/model/store.js DEFAULT_SUBJECT_CONFIG 新增 default_location_id: null;normalizeSubjectConfig 新增正整数校验分支(空值置 null)", + "同步更新 methods/system.json:getSettings 响应、saveSettings 参数补充 default_location_id 说明" + ], + "module": "setting.warehouse" + }, { "version": "2026.08.25-stockout-updateInfo-transferred", "date": "2026-08-25", @@ -13,7 +177,8 @@ "数据库迁移 20260825180000-add-transferred-status-and-platform-to-wms-order-stockout.js:order_status ENUM 追加 TRANSFERRED + 新增 source_platform_code(50)/source_platform_name(200) 列,开发库已执行并核验", "app/model/order_stockout.js:ENUM 补 TRANSFERRED、新增两平台字段、新增 isTransferred() 辅助方法", "storage.stockout.toOrder:转单成功后 order_status 置 TRANSFERRED(原 CANCELLED);deliveryOrder.sourcePlatformCode 优先用出库单已存平台,为空走兜底平台;confirm(一键出库)经 canConfirm 拒绝 TRANSFERRED 状态", - "同步更新 methods/system.json:新增 updateInfo 接口文档,更新 toOrder 描述与状态说明" + "同步更新 methods/system.json:新增 updateInfo 接口文档,更新 toOrder 描述与状态说明", + "实测(2026-08-26,测试单 20):正常修改 name/mobile/detailAddress + express_code=SF(自动解析 express_name=顺丰速运)+ source_platform_code 均落库,未传字段不变;detailAddress 清空被拦截(收货信息缺失,禁止提交:缺少 detailAddress(详细地址));COMPLETED 单被拦截(不允许修改);操作日志 STOCKOUT_UPDATE_INFO 含改动字段摘要(收件人姓名、移动电话、详细地址、快递编码、来源平台);测试数据已恢复原貌、日志保留" ], "module": "storage.stockout" }, diff --git a/methods/system.json b/methods/system.json index 6477415..68c3243 100644 --- a/methods/system.json +++ b/methods/system.json @@ -13939,6 +13939,12 @@ "type": "number", "required": false, "description": "团购打包最大时长,单位:分钟,默认 40" + }, + { + "name": "subject_config.default_location_id", + "type": "number", + "required": false, + "description": "默认库位(库位ID,未配置时为 null)" } ], "errors": [ @@ -14203,6 +14209,13 @@ "required": false, "source": "body.subject_config", "description": "团购打包最大时长,单位:分钟,默认 40,须为大于 0 的整数" + }, + { + "name": "subject_config.default_location_id", + "type": "number", + "required": false, + "source": "body.subject_config", + "description": "默认库位(库位ID,须属于当前仓库且未删除、已启用,否则报 400;传 null 清空)" } ], "response": [ @@ -21342,7 +21355,7 @@ { "name": "space_id", "type": "number", - "description": "库位 ID" + "description": "库位 ID;未传时默认使用仓库设置 subject_config.default_location_id,未设置则兜底库位 1" }, { "name": "system_product_id", @@ -23204,7 +23217,7 @@ "name": "list", "type": "array", "required": true, - "description": "出库单列表(wms_order_stockout 表记录,含 sync_status/sync_message 出站同步状态字段)" + "description": "出库单列表(wms_order_stockout 表记录,含 store_id/store_name 货主信息与 sync_status/sync_message 出站同步状态字段;不含 id、warehouse_id、warehouse_name)" }, { "name": "pagination", @@ -23361,6 +23374,79 @@ } ] }, + { + "method": "storage.stockout.listLogs", + "name": "出库单操作日志", + "description": "查询出库单操作日志(分页)。日志业务类型 business_type=stockout、business_id=出库单ID,覆盖转订单(STOCKOUT_TO_ORDER)、确认直出(STOCKOUT_CONFIRM)、修改信息(STOCKOUT_UPDATE_INFO)、取消(STOCKOUT_CANCEL)等操作。按创建时间倒序。", + "isNeedAuth": true, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": false, + "source": "body", + "description": "出库单ID;与 stockout_order_code 至少传一个" + }, + { + "name": "stockout_order_code", + "type": "string", + "required": false, + "source": "body", + "description": "出库单号(推荐);与 id 至少传一个" + }, + { + "name": "page", + "type": "number", + "required": false, + "source": "body", + "description": "页码(默认1);与订单日志接口一致,支持顶层传参" + }, + { + "name": "pageSize", + "type": "number", + "required": false, + "source": "body", + "description": "每页数量(默认20,兼容 page_size)" + }, + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页对象写法({ page, pageSize }),与顶层 page/pageSize 二选一,顶层优先" + } + ], + "response": [ + { + "name": "data.list", + "type": "array", + "required": true, + "description": "操作日志列表(含 operation_code/operation_name/operator_name/message/created_at 等,与订单日志字段一致)" + }, + { + "name": "data.pagination", + "type": "object", + "required": true, + "description": "分页信息 { page, pageSize, total, totalPages }" + } + ], + "errors": [ + { + "code": "400", + "description": "id 或 stockout_order_code 至少传一个 / 缺少仓库上下文" + } + ] + }, { "method": "storage.stockout.confirm", "name": "出库单确认(直出)", @@ -23640,6 +23726,13 @@ "source": "body", "description": "详细地址" }, + { + "name": "receiver_id", + "type": "string", + "required": false, + "source": "body", + "description": "收件人证件号" + }, { "name": "express_code", "type": "string", @@ -23680,6 +23773,57 @@ "description": "收货信息缺失,禁止提交(列出缺失字段)" } ] + }, + { + "method": "storage.stockout.cancel", + "name": "出库单取消", + "description": "取消出库单:仅 CREATED/PENDING 状态允许取消;事务内释放创建时占用的库存锁定(QM_STOCKOUT,写 UNLOCK 流水),状态置为 CANCELLED,并写 wms_operation_log 操作日志(STOCKOUT_CANCEL)。TRANSFERRED(已转订单)与 COMPLETED(已完成)状态禁止取消。", + "isNeedAuth": true, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "出库单ID(必填)" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "出库单ID" + }, + { + "name": "stockout_order_code", + "type": "string", + "required": true, + "description": "出库单号" + }, + { + "name": "order_status", + "type": "string", + "required": true, + "description": "取消后状态(CANCELLED)" + } + ], + "errors": [ + { + "code": "400", + "description": "缺少出库单ID / 出库单不存在 / 状态不允许取消 / 释放锁定失败" + } + ] } ] }, @@ -23787,7 +23931,7 @@ }, { "method": "storage.inventory.directPutaway", - "description": "收货单直入库存(一步完成):将已审核的收货单(completed + is_review=true)未入库明细直接写入 wms_storage 库位库存(按收货明细的库位 space_id 入库)并生成入库单(SCRK,一步置为 COMPLETED),入库单明细与收货明细一一对应(不合并,逐行保留库位/批次/效期),同时更新 wms_stock_warehouse 总库存并写入出入库流水(wms_stock_transaction / wms_storage_transaction),并写入 wms_inbound_direct_log(status=committed,与 storage.entry.commit 链路口径一致),回填收货单及其明细的入库状态。要求货主仓库签约配置 policy_config.allow_receiving_direct_putaway=1 开启直入库存功能。", + "description": "收货单直入库存(一步完成):将已审核的收货单(completed + is_review=true)未入库明细直接写入 wms_storage 库位库存并生成入库单(SCRK,一步置为 COMPLETED),入库单明细与收货明细一一对应(不合并,逐行保留库位/批次/效期),同时更新 wms_stock_warehouse 总库存并写入出入库流水(wms_stock_transaction / wms_storage_transaction),并写入 wms_inbound_direct_log(status=committed,与 storage.entry.commit 链路口径一致),回填收货单及其明细的入库状态。库位规则:收货明细 space_id 有效则按其库位入库,否则使用仓库设置 subject_config.default_location_id,未设置则兜底库位 1。要求货主仓库签约配置 policy_config.allow_receiving_direct_putaway=1 开启直入库存功能。", "isNeedAuth": true, "isNeedLogin": true, "params": [ diff --git a/script/backfill-pack-status-fin.cjs b/script/backfill-pack-status-fin.cjs new file mode 100644 index 0000000..23ecc8a --- /dev/null +++ b/script/backfill-pack-status-fin.cjs @@ -0,0 +1,173 @@ +'use strict'; + +/** + * 回补历史"打包完成但订单仍为打包中(padding)"的存量数据。 + * + * 背景:workbench.finishPack / order_packing.setEndTime 曾只结束 wms_pack_task, + * 不更新订单 pack_status,导致大量订单停留在 padding(打包中)。 + * + * 回补规则(以 wms_pack_task 为基准,status=2 视为打包已完成): + * - 团购任务(pack_mode=2):按 wave_no 批量更新对应仓库分表中 + * pack_status='padding' 且未被拦截(intercept_status IN ('none', NULL))的订单 → 'fin' + * - 散单任务(pack_mode=1):按 order_id 更新单个订单(同样只改 padding 且未拦截) + * - 仅更新任务已完成(status=2)对应订单;仍在打包(status=1)或拦截中的订单不动 + * + * 用法: + * node script/backfill-pack-status-fin.cjs # 预览模式:只统计不修改 + * node script/backfill-pack-status-fin.cjs --apply # 实际执行 + * + * 连接配置:默认 script/db-query-prod-config.js(生产库)。 + */ + +const path = require('path'); +const { createRequire } = require('module'); + +const APPLY = process.argv.includes('--apply'); + +async function main() { + const projectRoot = path.resolve(__dirname, '..'); + const projectRequire = createRequire(path.join(projectRoot, 'package.json')); + const mysql = projectRequire('mysql2/promise'); + + const configPath = path.join(__dirname, 'db-query-prod-config.js'); + const cfg = require(configPath); + const client = cfg && cfg.mysql && cfg.mysql.clients && cfg.mysql.clients.wms; + if (!client) { + throw new Error(`未找到 mysql clients.wms 配置: ${configPath}`); + } + + const conn = await mysql.createConnection({ + host: client.host, + port: Number(client.port), + user: client.user, + password: client.password, + database: client.database, + charset: client.charset || 'utf8mb4', + timezone: 'Z', + multipleStatements: true, + }); + + try { + // 1. 读取所有已完成的打包任务 + const [ tasks ] = await conn.query( + 'SELECT warehouse_id, pack_mode, order_id, wave_no FROM wms_pack_task WHERE status = 2 AND deleted_at IS NULL' + ); + + const byWarehouse = new Map(); + for (const t of tasks) { + const wh = Number(t.warehouse_id || 0); + if (!byWarehouse.has(wh)) byWarehouse.set(wh, { groupWaves: new Set(), singleOrders: new Set() }); + const bucket = byWarehouse.get(wh); + if (Number(t.pack_mode) === 2 && t.wave_no) { + bucket.groupWaves.add(String(t.wave_no)); + } else if (t.order_id) { + bucket.singleOrders.add(Number(t.order_id)); + } + } + + console.log(`任务统计: ${tasks.length} 条已完成任务,涉及仓库 ${byWarehouse.size} 个`); + for (const [ wh, b ] of byWarehouse.entries()) { + console.log(` 仓库 ${wh}: 团购波次 ${b.groupWaves.size} 个,散单订单 ${b.singleOrders.size} 笔`); + } + + const chunk = list => { + const out = []; + for (let i = 0; i < list.length; i += 500) out.push(list.slice(i, i + 500)); + return out; + }; + + let totalGroupAffected = 0; + let totalSingleAffected = 0; + const detail = []; + + // 2. 逐仓库处理其 current / dispatch 分表 + for (const [ wh, b ] of byWarehouse.entries()) { + const tables = []; + const [ tableRows ] = await conn.query('SHOW TABLES LIKE \'wms_order_delivery%\''); + const names = tableRows.map(r => Object.values(r)[0]); + for (const n of names) { + if (n.includes('_history') || n.includes('_outsourced') || n.includes('_bak')) continue; + // current 表(无后缀或带仓库后缀)与 dispatch 表都纳入 + tables.push(n); + } + + const waveList = [ ...b.groupWaves ]; + const orderList = [ ...b.singleOrders ]; + + for (const tbl of tables) { + // 团购:按 wave_no 批量更新 + for (const waves of chunk(waveList)) { + const waveIn = waves.map(w => conn.escape(w)).join(','); + const sql = `UPDATE ${tbl} SET pack_status = 'fin' + WHERE pack_status = 'padding' + AND intercept_status IN ('none', NULL) + AND wave_no IN (${waveIn})`; + if (APPLY) { + const [ r ] = await conn.query(sql); + if (r.affectedRows > 0) { + totalGroupAffected += r.affectedRows; + detail.push({ tbl, kind: 'group', waves: waves.length, affected: r.affectedRows }); + } + } else { + const [ preview ] = await conn.query( + `SELECT COUNT(1) AS cnt FROM ${tbl} + WHERE pack_status = 'padding' + AND intercept_status IN ('none', NULL) + AND wave_no IN (${waveIn})` + ); + const cnt = Number(preview[0].cnt || 0); + if (cnt > 0) { + totalGroupAffected += cnt; + detail.push({ tbl, kind: 'group', waves: waves.length, affected: cnt }); + } + } + } + + // 散单:按 order_id 更新 + for (const orders of chunk(orderList)) { + const orderIn = orders.join(','); + if (APPLY) { + const sql = `UPDATE ${tbl} SET pack_status = 'fin' + WHERE pack_status = 'padding' + AND intercept_status IN ('none', NULL) + AND id IN (${orderIn})`; + const [ r ] = await conn.query(sql); + if (r.affectedRows > 0) { + totalSingleAffected += r.affectedRows; + detail.push({ tbl, kind: 'single', orders: orders.length, affected: r.affectedRows }); + } + } else { + const [ preview ] = await conn.query( + `SELECT COUNT(1) AS cnt FROM ${tbl} + WHERE pack_status = 'padding' + AND intercept_status IN ('none', NULL) + AND id IN (${orderIn})` + ); + const cnt = Number(preview[0].cnt || 0); + if (cnt > 0) { + totalSingleAffected += cnt; + detail.push({ tbl, kind: 'single', orders: orders.length, affected: cnt }); + } + } + } + } + } + + console.log(''); + console.log(`==== ${APPLY ? '已执行' : '预览(加 --apply 执行)'} ====`); + console.log(`团购订单将更新: ${totalGroupAffected}`); + console.log(`散单订单将更新: ${totalSingleAffected}`); + console.log(`合计: ${totalGroupAffected + totalSingleAffected}`); + if (detail.length > 0) { + console.log('明细:'); + for (const d of detail) console.log(` ${d.tbl} [${d.kind}] ${d.kind === 'group' ? d.waves + ' 波次' : d.orders + ' 订单'} → ${d.affected} 单`); + } + } finally { + await conn.end(); + } +} + +main().catch(err => { + console.error('回补脚本执行失败:', err.message); + process.exit(1); +}); From fbd9ac2326650c9bb2f6f77f32066f11eb854c30 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Wed, 26 Aug 2026 17:22:52 +0800 Subject: [PATCH 275/550] =?UTF-8?q?feat(receiving):=20=E6=94=B6=E8=B4=A7?= =?UTF-8?q?=E5=8D=95=E9=80=9A=E7=9F=A5=E6=A8=A1=E6=9D=BF=E8=B0=83=E6=95=B4?= =?UTF-8?q?=EF=BC=88=E8=BD=A6=E7=89=8C/=E5=BF=AB=E9=80=92=E5=8D=95?= =?UTF-8?q?=E5=8F=B7=E6=9C=AA=E7=99=BB=E8=AE=B0=E6=98=BE=E7=A4=BA=E6=97=A0?= =?UTF-8?q?=EF=BC=89=E5=B9=B6=E6=96=B0=E5=A2=9E=E5=AE=8C=E6=88=90=E6=97=B6?= =?UTF-8?q?=E6=9C=AA=E5=8C=B9=E9=85=8D=E5=95=86=E5=93=81=E8=B4=A7=E4=B8=BB?= =?UTF-8?q?=E9=80=9A=E7=9F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/model/notification_webhook.js | 3 +- app/service/systems/notice/index.js | 10 ++ app/service/systems/storage/receiving.js | 115 ++++++++++++++++++++--- methods/changes/warehouse.json | 31 ++++++ 4 files changed, 146 insertions(+), 13 deletions(-) diff --git a/app/model/notification_webhook.js b/app/model/notification_webhook.js index 86f6c8d..ce94b33 100644 --- a/app/model/notification_webhook.js +++ b/app/model/notification_webhook.js @@ -41,7 +41,8 @@ module.exports = app => { Object.freeze({ code: 'receiving_completed', name: '收货完成', business: 'receiving', description: '收货单完成后的通知' }), Object.freeze({ code: 'receiving_rejected', name: '收货驳回', business: 'receiving', description: '收货单被驳回并恢复为收货中后的通知' }), Object.freeze({ code: 'receiving_reviewed', name: '收货审核完成', business: 'receiving', description: '收货单批量审核通过后的通知' }), - Object.freeze({ code: 'receiving_store_bound', name: '收货单创建/绑定货主', business: 'receiving', description: '收货单创建或首次绑定货主时提醒货主填写车牌号/快递号的通知' }), + Object.freeze({ code: 'receiving_store_bound', name: '收货单创建/绑定货主', business: 'receiving', description: '收货单创建或首次绑定货主时的通知(展示车牌号/快递单号登记状态,未登记显示无)' }), + Object.freeze({ code: 'receiving_store_unmatched', name: '收货完成未匹配商品提醒', business: 'receiving', description: '收货单完成时存在未匹配商品明细,通知货主核实商品资料' }), Object.freeze({ code: 'order_sync_completed', name: '订单同步完成', business: 'order', description: '本地创建入口同步完成后的通知' }), Object.freeze({ code: 'order_cancel_intercepted', name: '订单取消拦截', business: 'order', description: '订单取消失败并触发拦截执行后的通知' }), Object.freeze({ code: 'wave_strategy_quick_scan_failed', name: '波次策略兜底扫描失败', business: 'order', description: '定时兜底扫描任务在仓库维度触发失败时通知' }), diff --git a/app/service/systems/notice/index.js b/app/service/systems/notice/index.js index 269d58f..0f30e6f 100644 --- a/app/service/systems/notice/index.js +++ b/app/service/systems/notice/index.js @@ -27,6 +27,7 @@ const DEFAULT_REGISTERED_EVENT_CODES = Object.freeze([ 'receiving_rejected', 'receiving_reviewed', 'receiving_store_bound', + 'receiving_store_unmatched', 'order_cancel_intercepted', 'wave_strategy_quick_scan_failed', 'store_warehouse_print_quantity_adjusted', @@ -63,6 +64,15 @@ const FIXED_GROUP_SUBSCRIPTIONS = Object.freeze({ ]), }), ]), + receiving_store_unmatched: Object.freeze([ + Object.freeze({ + groupType: 'store', + subType: 'receiving', + fallbackTargets: Object.freeze([ + Object.freeze({ groupType: 'store', subType: 'after_sales' }), + ]), + }), + ]), order_cancel_intercepted: Object.freeze([ Object.freeze({ groupType: 'warehouse', subType: 'exception' }), ]), diff --git a/app/service/systems/storage/receiving.js b/app/service/systems/storage/receiving.js index 56a4c9f..5af09f4 100644 --- a/app/service/systems/storage/receiving.js +++ b/app/service/systems/storage/receiving.js @@ -1494,8 +1494,8 @@ class ReceivingService extends Service { } /** - * 发送收货单创建/首次绑定货主通知(receiving_store_bound),提醒货主确认/补填车牌号或快递单号。 - * 已填写车牌号或快递单号时,文案展示已登记信息;均未填写时才提示及时补充。 + * 发送收货单创建/首次绑定货主通知(receiving_store_bound)。 + * 车牌号/快递单号始终展示登记状态:已登记显示「车牌号:X 已登记」「快递单号:X 已登记」,未登记显示「车牌号:无」「快递单号:无」。 * 路由由 notice 固定订阅回退链处理:货主收货群 → 无则货主售后群 → 均无则仓库异常群。 * @param {Object} options 发送参数 * @param {Object} options.receiving 收货单快照 @@ -1525,16 +1525,10 @@ class ReceivingService extends Service { const licensePlate = String(receiving.license_plate || '').trim(); const trackingNumber = String(receiving.tracking_number || '').trim(); - const vehicleInfoLines = []; - if (licensePlate) { - vehicleInfoLines.push(`车牌号:${licensePlate} 已登记`); - } - if (trackingNumber) { - vehicleInfoLines.push(`快递单号:${trackingNumber} 已登记`); - } - if (vehicleInfoLines.length === 0) { - vehicleInfoLines.push('请确认是否已填写车牌号或快递单号,未填写请及时补充'); - } + const vehicleInfoLines = [ + licensePlate ? `车牌号:${licensePlate} 已登记` : '车牌号:无', + trackingNumber ? `快递单号:${trackingNumber} 已登记` : '快递单号:无', + ]; const contentLines = [ `收货单号:${receivingNumber} 正在收货`, @@ -4309,6 +4303,76 @@ class ReceivingService extends Service { }); } + /** + * 发送收货完成未匹配商品货主通知(receiving_store_unmatched),提醒货主核实未匹配商品资料。 + * 路由由 notice 固定订阅回退链处理:货主收货群 → 无则货主售后群 → 均无则仓库异常群。 + * @param {Object} options 发送参数 + * @param {Object} options.receiving 收货单快照 + * @param {Array} [options.unmatchedDetails=[]] 未匹配明细列表(含 barcode/product_name) + * @return {Promise} 发送结果 + */ + async sendStoreUnmatchedNotice({ receiving, unmatchedDetails = [] } = {}) { + const { ctx } = this; + const rawNoticeService = ctx && ctx.service && ctx.service.systems && ctx.service.systems.notice; + const noticeService = rawNoticeService && typeof rawNoticeService.send === 'function' + ? rawNoticeService + : (rawNoticeService && rawNoticeService.index && typeof rawNoticeService.index.send === 'function' + ? rawNoticeService.index + : null); + + if (!receiving || !noticeService || !Array.isArray(unmatchedDetails) || unmatchedDetails.length === 0) { + return null; + } + + const warehouseId = Number(receiving.warehouse_id || (ctx.user && ctx.user.store_id) || 0); + const storeId = Number(receiving.store_id || 0); + if (!Number.isFinite(warehouseId) || warehouseId <= 0 || !Number.isFinite(storeId) || storeId <= 0) { + return null; + } + + const receivingNumber = String(receiving.receiving_number || receiving.id || '').trim(); + const storeFrontendUrl = String(ctx.app.config.storeFrontendUrl || ctx.app.config.frontendUrl || '').trim(); + const barcodeLines = unmatchedDetails.map((detail, index) => `${index + 1}.${String(detail.barcode || '').trim() || '无条码'},`); + const contentLines = [ + `收货单号:${receivingNumber} 提交完成收货,有未匹配商品资料`, + '条码:', + ...barcodeLines, + '核实是否是新商品未推送资料', + `详情以及收货图片查看:${storeFrontendUrl}/storage/receiving_owner?id=${receivingNumber}`, + '如果没有账户请联系人工客服开通', + ]; + const content = contentLines.join('\n') + '。'; + + return await noticeService.send({ + warehouseId, + storeId, + messageType: 'text', + businessName: 'receiving', + event: 'receiving_store_unmatched', + channel: 'warehouse', + title: `收货单${receivingNumber}有未匹配商品资料`, + content, + storeContent: content, + businessId: receiving.id, + subject: { + id: warehouseId, + type: 'warehouse', + name: String((ctx.user && (ctx.user.store_name || ctx.user.company_name)) || ''), + }, + sender: { + id: (ctx.user && (ctx.user.employees_id || ctx.user.id)) || null, + name: (ctx.user && ctx.user.employees_name) || '', + }, + metadata: { + receivingId: receiving.id, + receivingNumber, + warehouseId, + storeId, + unmatchedBarcodes: unmatchedDetails.map(detail => detail.barcode || ''), + }, + }); + } + /** * 完成收货单:校验明细、更新状态并写入库存。 * @param {Object} data 请求体 @@ -4619,6 +4683,33 @@ class ReceivingService extends Service { }); } + // 11.1 存在未匹配商品明细且已绑定货主时,通知货主核实商品资料(失败不影响主流程) + if (unmatchedDetails.length > 0 && Number(receiving.store_id || 0) > 0) { + try { + const unmatchedNoticeResult = await this.sendStoreUnmatchedNotice({ + receiving: receivingSnapshot, + unmatchedDetails: unmatchedDetails.map(detail => ({ + barcode: detail.barcode, + product_name: detail.product_name, + })), + }); + ctx.logger.info('收货完成未匹配商品货主通知结果', { + receiving_id: id, + receiving_number: receiving.receiving_number, + warehouseId, + unmatchedCount: unmatchedDetails.length, + success: !!(unmatchedNoticeResult && unmatchedNoticeResult.success), + message: unmatchedNoticeResult && unmatchedNoticeResult.message, + }); + } catch (notifyError) { + ctx.logger.error(`收货完成未匹配商品货主通知发送失败: ${notifyError.message}`, { + receiving_id: id, + warehouseId, + error: notifyError.stack, + }); + } + } + ctx.logger.info('收货单已完成', { receiving_id: id, receiving_number: receiving.receiving_number, diff --git a/methods/changes/warehouse.json b/methods/changes/warehouse.json index 667bc9f..8f1b5d4 100644 --- a/methods/changes/warehouse.json +++ b/methods/changes/warehouse.json @@ -239,5 +239,36 @@ "背景:R20682003 创建时已写入车牌粤EH22E2,但通知为固定提醒文案导致货主误以为车牌未生效" ], "module": "receiving" + }, + { + "version": "2026-08-26-warehouse-01", + "date": "2026-08-26", + "type": "changed", + "summary": "调整 receiving_store_bound 通知模板:不再向货主发送「请确认是否已填写车牌号或快递单号,未填写请及时补充」提示,车牌号/快递单号未登记时展示「车牌号:无 / 快递单号:无」", + "methods": [ + "notify.reply" + ], + "notes": [ + "storage/receiving.js sendStoreBoundNotice:车牌号/快递单号两行始终输出,已登记显示「车牌号:X 已登记」「快递单号:X 已登记」,未登记显示「车牌号:无」「快递单号:无」", + "notification_webhook.js AVAILABLE_EVENTS.receiving_store_bound 描述同步更新:展示车牌号/快递单号登记状态", + "背景:车牌号/快递单号由仓库侧登记,货主端无法填写,「请确认/及时补充」提示对货主无意义,改为直接展示登记状态" + ], + "module": "receiving" + }, + { + "version": "2026-08-26-warehouse-02", + "date": "2026-08-26", + "type": "added", + "summary": "新增收货完成未匹配商品货主通知(receiving_store_unmatched):收货单提交完成时存在未匹配商品明细,通知货主核实是否为新商品未推送资料", + "methods": [ + "notify.reply" + ], + "notes": [ + "新事件码 receiving_store_unmatched 注册(notification_webhook.js AVAILABLE_EVENTS 与 notice/index.js DEFAULT_REGISTERED_EVENT_CODES)", + "FIXED_GROUP_SUBSCRIPTIONS.receiving_store_unmatched:仅货主侧目标 store:receiving + fallbackTargets store:after_sales(与 receiving_store_bound 一致)", + "storage/receiving.js 新增 sendStoreUnmatchedNotice:内容「收货单号:xxx 提交完成收货,有未匹配商品资料 / 条码:1.xxx,2.xxx / 核实是否是新商品未推送资料 / 详情以及收货图片查看:货主端 receiving_owner 链接 / 如果没有账户请联系人工客服开通」", + "触发点:completeReceiving 事务提交后,unmatchedDetails 非空且已绑定货主时发送,失败不影响主流程" + ], + "module": "receiving" } ] From a6d67a17fe161890b63b01118af088407c1974ee Mon Sep 17 00:00:00 2001 From: liufumingren Date: Wed, 26 Aug 2026 17:24:03 +0800 Subject: [PATCH 276/550] =?UTF-8?q?feat(order):=20=E5=BF=AB=E9=80=92?= =?UTF-8?q?=E7=AD=96=E7=95=A5=E6=BC=8F=E6=96=97=E6=94=AF=E6=8C=81=E5=A4=96?= =?UTF-8?q?=E9=83=A8=E7=BC=96=E7=A0=81=E5=BC=80=E5=90=AF=E6=97=B6=E4=BB=85?= =?UTF-8?q?=E5=8C=B9=E9=85=8D=E7=BA=AF=E8=B4=A7=E4=B8=BB=E7=BB=B4=E5=BA=A6?= =?UTF-8?q?=E7=AD=96=E7=95=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/systems/delivery_order.js | 26 +++++++++++---------- app/service/systems/express_policy.js | 33 +++++++++++++++++++++++++-- 2 files changed, 45 insertions(+), 14 deletions(-) diff --git a/app/service/systems/delivery_order.js b/app/service/systems/delivery_order.js index be919f2..8cb969c 100644 --- a/app/service/systems/delivery_order.js +++ b/app/service/systems/delivery_order.js @@ -797,22 +797,18 @@ class DeliveryOrderService extends Service { }; // ===== 快递绑定策略漏斗匹配(items 处理后 weight 可用) ===== - // enable_external_express_code 开启时以外部快递匹配结果为准(匹配不到已在 resolveExpressSnapshot 兜底默认快递),跳过策略漏斗覆盖 + // enable_external_express_code 开启时仅"纯货主维度"策略参与漏斗,命中后覆盖外部快递匹配结果; + // 关闭时全维度策略参与,沿用原有逻辑 try { const funnelPolicyConfig = await this.getStoreWarehousePolicyConfig(info.storeId, info.warehouseId); const enableExternalExpressCode = this.resolveEnableExternalExpressCode(funnelPolicyConfig, funnelPolicyConfig); - if (enableExternalExpressCode) { - ctx.logger.info('[ExpressPolicyMatch] enable_external_express_code 开启,跳过快递策略漏斗,保留外部快递匹配或兜底结果', { - orderId, - orderCode: deliveryOrder.deliveryOrderCode, - logisticsCode: orderData.logistics_code, - sysLogisticsCode: orderData.sys_logistics_code, - }); - } const receiverInfo = deliveryOrder.receiverInfo; const shopNick = deliveryOrder.shopNick; - const hasEnoughData = !enableExternalExpressCode - && (shopNick || (receiverInfo && (receiverInfo.province || receiverInfo.city))); + // 外部编码开启:仅需货主ID即可参与漏斗(只匹配纯货主维度策略); + // 外部编码关闭:需 shopNick 或收货省/市信息 + const hasEnoughData = enableExternalExpressCode + ? Boolean(info.storeId) + : Boolean(shopNick || (receiverInfo && (receiverInfo.province || receiverInfo.city))); if (hasEnoughData) { const address = [ @@ -834,6 +830,10 @@ class DeliveryOrderService extends Service { prohibitedTypeIds: itemsInfo && Array.isArray(itemsInfo.prohibited_type_ids) ? itemsInfo.prohibited_type_ids : null, + }, + { + // 启用外部编码时仅匹配纯货主维度策略,命中后覆盖外部快递映射结果 + onlyStoreDimension: enableExternalExpressCode, } ); @@ -904,7 +904,9 @@ class DeliveryOrderService extends Service { this.appendOrderOperationLog( operationLogs, ORDER_OPERATION_CODES.EXPRESS_FALLBACK, - `未命中快递策略,使用默认快递: ${fallbackName || fallbackCode}` + enableExternalExpressCode + ? `未命中货主快递策略,保留外部快递: ${fallbackName || fallbackCode}` + : `未命中快递策略,使用默认快递: ${fallbackName || fallbackCode}` ); } } diff --git a/app/service/systems/express_policy.js b/app/service/systems/express_policy.js index 0df2b1f..19107f6 100644 --- a/app/service/systems/express_policy.js +++ b/app/service/systems/express_policy.js @@ -177,6 +177,27 @@ class ExpressPolicyService extends Service { return policyArray.some(v => Number(v) === Number(value)); } + /** + * 判断策略是否为"纯货主维度"策略: + * store_ids 非空,且 shop_name / prohibited_type_id / regions / exclude_regions / 重量区间全部未限定。 + * + * @param {Object} policy 策略行 + * @return {boolean} 是否为纯货主策略 + */ + _isStoreOnlyPolicy(policy = {}) { + const asArray = v => (Array.isArray(v) ? v : []); + if (asArray(policy.store_ids).length === 0) { + return false; + } + const hasOtherDimension = asArray(policy.shop_name).length > 0 + || asArray(policy.prohibited_type_id).length > 0 + || asArray(policy.regions).length > 0 + || asArray(policy.exclude_regions).length > 0 + || (policy.min_weight_g !== null && policy.min_weight_g !== undefined) + || (policy.max_weight_g !== null && policy.max_weight_g !== undefined); + return !hasOtherDimension; + } + /** * 按策略优先级漏斗筛选,返回命中策略的快递编码与重量段类型。 * @@ -195,9 +216,11 @@ class ExpressPolicyService extends Service { * @param {Array} [params.prohibitedTypeIds] 商品违禁品类型 ID 数组 * @param {string} [params.address] 省市区详细地址(单个字符串) * @param {number} [params.weight] 重量(克) - * @return {Promise<{expressCode: string|null, weightType: number|null}>} + * @param {Object} [options] 匹配选项 + * @param {boolean} [options.onlyStoreDimension=false] 仅匹配"纯货主维度"策略(store_ids 非空且其它维度全空) + * @return {Promise<{expressCode: string|null, weightType: number|null}>} 命中策略的快递编码与重量段类型,未命中时 expressCode 为 null */ - async matchPolicy(warehouseId, params = {}) { + async matchPolicy(warehouseId, params = {}, options = {}) { const { storeId, customShopName, @@ -205,6 +228,7 @@ class ExpressPolicyService extends Service { address, weight, } = params; + const { onlyStoreDimension = false } = options; const policies = await this.getWarehousePolicies(warehouseId); if (!Array.isArray(policies) || policies.length === 0) { @@ -212,6 +236,11 @@ class ExpressPolicyService extends Service { } for (const policy of policies) { + // 0) 维度白名单:onlyStoreDimension 开启时跳过非纯货主策略 + if (onlyStoreDimension && !this._isStoreOnlyPolicy(policy)) { + continue; + } + // 1) store_ids — 未限定(NULL)视为不限;否则传入 storeId 必须在范围内 if (!this._matchValueInArray(policy.store_ids, storeId)) { continue; From c5477cf6cb68376a1b80d73585845da149e5c9ec Mon Sep 17 00:00:00 2001 From: liufumingren Date: Wed, 26 Aug 2026 17:24:05 +0800 Subject: [PATCH 277/550] =?UTF-8?q?feat(order):=20wave.batchList=20?= =?UTF-8?q?=E6=94=AF=E6=8C=81=E8=B4=A7=E4=B8=BB=E7=AD=9B=E9=80=89=E4=B8=8E?= =?UTF-8?q?=E8=B4=A7=E4=B8=BB=E5=90=8D=E7=A7=B0=E5=B1=95=E7=A4=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/systemMethods/order/wave.js | 153 +++++++++++++++++++++++- methods/changes/system.json | 34 ++++++ methods/system.json | 6 +- 3 files changed, 187 insertions(+), 6 deletions(-) diff --git a/app/service/systemMethods/order/wave.js b/app/service/systemMethods/order/wave.js index d8b1dc3..866799c 100644 --- a/app/service/systemMethods/order/wave.js +++ b/app/service/systemMethods/order/wave.js @@ -1545,7 +1545,7 @@ class WaveService extends OrderBaseService { * 构建波次列表 where 条件(白名单字段)。 * * @param {Object} whereData 查询 where 入参。 - * @return {{ sql: string, replacements: Object, storageAssignmentStatus: string, expressAssignmentStatus: string, printAssignmentStatus: string }} SQL 条件片段、参数与分配状态筛选值。 + * @return {{ sql: string, replacements: Object, storageAssignmentStatus: string, expressAssignmentStatus: string, printAssignmentStatus: string, reviewAssignmentStatus: string, storeIds: number[] }} SQL 条件片段、参数与分配状态筛选值。 */ buildBatchListWhereClause(whereData = {}) { const normalizedWhere = this.isPlainObject(whereData) ? whereData : {}; @@ -1576,6 +1576,7 @@ class WaveService extends OrderBaseService { 'express_assignment_status', 'print_assignment_status', 'review_assignment_status', + 'store_id', ]; const invalidFields = whereKeys.filter(key => !allowedFields.includes(key)); @@ -1700,6 +1701,37 @@ class WaveService extends OrderBaseService { appendMinCondition('processed_orders_min', 'processed_orders', 'whereProcessedOrdersMin'); appendMaxCondition('processed_orders_max', 'processed_orders', 'whereProcessedOrdersMax'); + // store_id 货主筛选:支持单值/数组/{operator,value} 结构,归一化为正整数数组(去重)。 + // 过滤语义:返回包含任一筛选货主订单的波次(含混合货主波次)。 + const normalizeStoreIdList = value => { + if (value === undefined || value === null || value === '') { + return []; + } + + const rawValue = this.isPlainObject(value) && Object.prototype.hasOwnProperty.call(value, 'value') + ? value.value + : value; + const sourceList = Array.isArray(rawValue) ? rawValue : [ rawValue ]; + const normalizedIds = []; + + for (const item of sourceList) { + if (item === undefined || item === null || item === '') { + continue; + } + + const numberValue = Number(String(item).trim()); + if (!Number.isInteger(numberValue) || numberValue <= 0) { + throw new Error('store_id 参数不合法'); + } + + normalizedIds.push(numberValue); + } + + return [ ...new Set(normalizedIds) ]; + }; + + const storeIds = normalizeStoreIdList(normalizedWhere.store_id); + const storageAssignmentStatus = this.normalizeBatchListStorageAssignmentStatusFilter( normalizedWhere.storage_assignment_status ); @@ -1720,6 +1752,7 @@ class WaveService extends OrderBaseService { expressAssignmentStatus, printAssignmentStatus, reviewAssignmentStatus, + storeIds, }; } @@ -4265,6 +4298,83 @@ class WaveService extends OrderBaseService { }); } + /** + * 解析波次列表的货主名称映射(store_id → 名称)。 + * + * 货主名称口径与售后/库存列表一致:合约表 wms_store_warehouse.store_remask + * (货主备注名称,store_id+warehouse_id 维度)优先,无合约或备注为空时回退 + * wms_store.company_name(公司全称)。 + * + * @param {Object[]} batchRows 波次行数据(含 order_total/owner_distinct_count/owner_named_count/owner_store_id)。 + * @param {number|string} [warehouseId=0] 当前仓库ID。 + * @return {Promise>} store_id → 货主名称。 + */ + async resolveWaveBatchOwnerStoreNameMap(batchRows = [], warehouseId = 0) { + const nameMap = new Map(); + const ownerStoreIds = []; + + for (const batch of batchRows) { + const orderCount = Number(batch && batch.order_total || 0); + const ownerDistinctCount = Number(batch && batch.owner_distinct_count || 0); + const ownerNamedCount = Number(batch && batch.owner_named_count || 0); + const ownerStoreId = Number(batch && batch.owner_store_id || 0); + if (orderCount > 0 && ownerDistinctCount === 1 && ownerNamedCount === orderCount && ownerStoreId > 0) { + ownerStoreIds.push(ownerStoreId); + } + } + + const uniqueStoreIds = [ ...new Set(ownerStoreIds) ]; + if (uniqueStoreIds.length === 0) { + return nameMap; + } + + const normalizedWarehouseId = Number(warehouseId || 0); + try { + // 1. 合约表货主备注名称(store_id + warehouse_id 维度) + const contractMap = new Map(); + if (normalizedWarehouseId > 0) { + const contractRows = await this.ctx.model.StoreWarehouse.findAll({ + where: { + store_id: { [Op.in]: uniqueStoreIds }, + warehouse_id: normalizedWarehouseId, + }, + attributes: [ 'store_id', 'store_remask' ], + raw: true, + }); + for (const row of contractRows) { + const remask = String(row.store_remask || '').trim(); + if (remask) { + contractMap.set(Number(row.store_id), remask); + } + } + } + + // 2. 货主公司全称兜底 + const storeRows = await this.ctx.model.Store.findAll({ + where: { id: { [Op.in]: uniqueStoreIds } }, + attributes: [ 'id', 'company_name' ], + raw: true, + }); + for (const row of storeRows) { + const companyName = String(row.company_name || '').trim(); + if (companyName) { + nameMap.set(Number(row.id), companyName); + } + } + + // 3. 备注名称覆盖公司全称 + for (const storeId of uniqueStoreIds) { + if (contractMap.has(storeId)) { + nameMap.set(storeId, contractMap.get(storeId)); + } + } + } catch (error) { + this.ctx.logger?.warn?.('resolveWaveBatchOwnerStoreNameMap 解析货主名称失败:', error?.message || error); + } + + return nameMap; + } + /** * 波次列表查询。 * @@ -4300,6 +4410,20 @@ class WaveService extends OrderBaseService { AND wave_status IN (:waveStatusList) ${whereClause.sql} `; + const storeIdFilter = Array.isArray(whereClause.storeIds) ? whereClause.storeIds : []; + const ownerFilterJoinSql = storeIdFilter.length > 0 ? ` + INNER JOIN ( + SELECT candidate_wave.wave_id + FROM ( + SELECT wave_id + FROM wms_wave_batch + WHERE ${baseBatchWhereSql} + ) candidate_wave + INNER JOIN ${orderTableName} od ON od.wave_id = candidate_wave.wave_id + AND od.store_id IN (:whereStoreIds) + GROUP BY candidate_wave.wave_id + ) wave_owner_filter ON wave_owner_filter.wave_id = wb.wave_id + ` : ''; const batchListFromSql = ` FROM ( SELECT @@ -4337,7 +4461,10 @@ class WaveService extends OrderBaseService { SUM(CASE WHEN od.inspection_status NOT IN ('fin', 'error') THEN 1 ELSE 0 END) AS review_none_count, SUM(CASE WHEN od.pick_status = 'none' THEN 1 ELSE 0 END) AS pick_none_count, SUM(CASE WHEN od.pick_status = 'fin' THEN 1 ELSE 0 END) AS pick_fin_count, - SUM(CASE WHEN od.pick_status = 'error' THEN 1 ELSE 0 END) AS pick_error_count + SUM(CASE WHEN od.pick_status = 'error' THEN 1 ELSE 0 END) AS pick_error_count, + COUNT(DISTINCT NULLIF(od.store_id, 0)) AS owner_distinct_count, + MAX(NULLIF(od.store_id, 0)) AS owner_store_id, + SUM(CASE WHEN NULLIF(od.store_id, 0) IS NOT NULL THEN 1 ELSE 0 END) AS owner_named_count FROM ( SELECT wave_id FROM wms_wave_batch @@ -4346,6 +4473,7 @@ class WaveService extends OrderBaseService { LEFT JOIN ${orderTableName} od ON od.wave_id = candidate_wave.wave_id GROUP BY candidate_wave.wave_id ) wave_order_stats ON wave_order_stats.wave_id = wb.wave_id + ${ownerFilterJoinSql} LEFT JOIN wms_express e ON e.code = wb.logistics_name WHERE 1 = 1 ${storageAssignmentFilterClause.sql} @@ -4386,7 +4514,10 @@ class WaveService extends OrderBaseService { COALESCE(wave_order_stats.review_none_count, 0) AS review_none_count, COALESCE(wave_order_stats.pick_none_count, 0) AS pick_none_count, COALESCE(wave_order_stats.pick_fin_count, 0) AS pick_fin_count, - COALESCE(wave_order_stats.pick_error_count, 0) AS pick_error_count + COALESCE(wave_order_stats.pick_error_count, 0) AS pick_error_count, + COALESCE(wave_order_stats.owner_distinct_count, 0) AS owner_distinct_count, + wave_order_stats.owner_store_id, + COALESCE(wave_order_stats.owner_named_count, 0) AS owner_named_count ${batchListFromSql} ORDER BY wb.total_orders DESC, wb.wave_id DESC LIMIT :limit OFFSET :offset @@ -4407,6 +4538,7 @@ class WaveService extends OrderBaseService { ...expressAssignmentFilterClause.replacements, ...printAssignmentFilterClause.replacements, ...reviewAssignmentFilterClause.replacements, + ...(storeIdFilter.length > 0 ? { whereStoreIds: storeIdFilter } : {}), limit: pageSize, offset, }, @@ -4420,6 +4552,7 @@ class WaveService extends OrderBaseService { ...expressAssignmentFilterClause.replacements, ...printAssignmentFilterClause.replacements, ...reviewAssignmentFilterClause.replacements, + ...(storeIdFilter.length > 0 ? { whereStoreIds: storeIdFilter } : {}), }, }), ]); @@ -4443,6 +4576,8 @@ class WaveService extends OrderBaseService { }); } + const ownerStoreNameMap = await this.resolveWaveBatchOwnerStoreNameMap(rawList, warehouseId); + const list = rawList.map(batch => { const waveId = Number(batch && batch.wave_id || 0); const orderCount = Number(batch && batch.order_total || 0); @@ -4460,6 +4595,17 @@ class WaveService extends OrderBaseService { const reviewFinCount = Number(batch && batch.review_fin_count || 0); const reviewErrorCount = Number(batch && batch.review_error_count || 0); const unreviewedOrderCount = orderCount - reviewFinCount; + const ownerDistinctCount = Number(batch && batch.owner_distinct_count || 0); + const ownerNamedCount = Number(batch && batch.owner_named_count || 0); + const ownerStoreId = Number(batch && batch.owner_store_id || 0); + + // 货主展示:仅当所有订单均存在货主(store_id)且货主唯一时返回货主名称,否则返回“混合”。 + const ownerName = orderCount > 0 + && ownerDistinctCount === 1 + && ownerNamedCount === orderCount + && ownerStoreId > 0 + ? (ownerStoreNameMap.get(ownerStoreId) || '') + : '混合'; // 复核状态判定:error 统一归入未复核 let reviewAssignmentStatus; @@ -4506,6 +4652,7 @@ class WaveService extends OrderBaseService { }), review_assignment_status: reviewAssignmentStatus, unreviewed_order_count: unreviewedOrderCount, + store_name: ownerName, }; }); diff --git a/methods/changes/system.json b/methods/changes/system.json index e09e68e..92698d6 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,38 @@ [ + { + "version": "2026.08.26-wave-batchList-store-id-filter", + "date": "2026-08-26", + "type": "enhanced", + "summary": "order.wave.batchList 新增 where.store_id(货主ID)过滤:支持单值/数组/{operator,value} 结构(正整数),返回包含任一筛选货主订单的波次(含混合货主波次);未在 wms_wave_batch 加冗余 store_id 字段,通过订单分表 INNER JOIN 聚合匹配,零迁移零回填零口径漂移风险。", + "methods": [ + "order.wave.batchList" + ], + "notes": [ + "app/service/systemMethods/order/wave.js buildBatchListWhereClause:allowedFields 新增 store_id,normalizeStoreIdList 归一化(单值/数组/{operator,value}→正整数数组去重,非法值抛错),返回值新增 storeIds", + "batchList:storeIds 非空时在 wave_order_stats 之后追加 INNER JOIN wave_owner_filter(订单表 od.wave_id 匹配且 od.store_id IN (:whereStoreIds) 按 wave_id 分组),listSql/countSql replacements 新增 whereStoreIds", + "设计决策:不在 wms_wave_batch 增加 store_id 冗余字段(混合填0),理由——batchList 原本就必须 LEFT JOIN 订单表做状态聚合,货主过滤挂同一次 JOIN 零额外成本;订单表已有 store_id 单列索引;冗余需覆盖抓取入波/策略任务建波/batchRemoveOrders/batchRemoveExceptionOrders 等 10+ 处写入点维护,遗漏即口径漂移;owner_name 展示已实时聚合订单 store_id,避免双口径", + "实测:{operator:'',value:[1000281,1000000]} 过滤 wave_type=1&source=0 返回 196 条(库中该货主订单波次);单值/数组形式均返回 5 条;不存在货主 0 条;非法值报错;无过滤 baseline 278 条不受影响;原请求含 wave_status=0 返回 0 因库中活动波次均为 status=1", + "同步更新 methods/system.json 的 batchList where 白名单说明" + ], + "module": "order.wave" + }, + { + "version": "2026.08.26-wave-batchList-store-name", + "date": "2026-08-26", + "type": "enhanced", + "summary": "order.wave.batchList 响应每条记录新增 store_name(货主信息):按波次内订单 store_id(货主ID)聚合,所有订单均为同一货主时返回货主名称,否则(多个货主、存在无货主订单或空波次)返回“混合”;货主名称优先取合约表 wms_store_warehouse.store_remask(货主备注名称),无合约或备注为空时回退 wms_store.company_name(公司全称)。", + "methods": [ + "order.wave.batchList" + ], + "notes": [ + "app/service/systemMethods/order/wave.js batchList:wave_order_stats 子查询新增 owner_distinct_count(COUNT(DISTINCT NULLIF(store_id,0)))、owner_named_count(SUM 非空判定)、owner_store_id(MAX(NULLIF(store_id,0)))三个聚合字段,listSql SELECT 透出", + "新增 resolveWaveBatchOwnerStoreNameMap:仅对满足单货主的波次批量查 StoreWarehouse(store_id+warehouse_id)取 store_remask,再查 wms_store.company_name 兑底,remask 覆盖 company_name;查询失败仅告警不影响列表", + "判定口径:orderCount>0 且 ownerDistinctCount===1 且 ownerNamedCount===orderCount 且 ownerStoreId>0 才返回货主名称,否则返回“混合”(0 单波次同样返回“混合”)", + "货主名称口径与 afterSale._enrichListStoreNames、inventory.store_name 一致(store_remask 优先、company_name 兑底);早期草稿曾按 shop_nick 店铺名称实现,已按项目货主口径修正", + "同步更新 methods/system.json 的 batchList 描述与 response.list 字段说明" + ], + "module": "order.wave" + }, { "version": "2026.08.26-workbench-queryOrder-pack-status", "date": "2026-08-26", diff --git a/methods/system.json b/methods/system.json index 68c3243..339578f 100644 --- a/methods/system.json +++ b/methods/system.json @@ -28507,7 +28507,7 @@ "list": [ { "method": "order.wave.batchList", - "description": "波次列表查询。仅使用当前登录操作者仓库上下文(禁止传入 warehouse_id/warehouseId)。支持 where 白名单过滤,固定查询 wave_status=0/1;返回波次基础信息及分配状态汇总(storage_assignment_status / express_assignment_status / print_assignment_status / pick_assignment_status / review_assignment_status)。支持 only_todo=1 仅返回仍有未复核订单的波次,并返回复核状态汇总(review_assignment_status)与未复核数量(unreviewed_order_count)。", + "description": "波次列表查询。仅使用当前登录操作者仓库上下文(禁止传入 warehouse_id/warehouseId)。支持 where 白名单过滤,固定查询 wave_status=0/1;返回波次基础信息及分配状态汇总(storage_assignment_status / express_assignment_status / print_assignment_status / pick_assignment_status / review_assignment_status)。支持 only_todo=1 仅返回仍有未复核订单的波次,并返回复核状态汇总(review_assignment_status)与未复核数量(unreviewed_order_count)。列表每条记录返回货主信息 store_name:当波次内所有订单均为同一货主(store_id)时返回货主名称,否则返回“混合”。货主名称优先取合约表 wms_store_warehouse.store_remask(货主备注名称),无合约或备注为空时回退 wms_store.company_name(公司全称)。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -28538,7 +28538,7 @@ "type": "object", "required": false, "source": "body", - "description": "筛选白名单字段(object,可选)。仅支持下列字段过滤,且禁止传入 warehouse_id / warehouseId:\n- wave_id(等值)\n- wave_no(模糊)\n- wave_type(等值)\n- wave_status(等值,接口固定叠加状态 0/1)\n- creator(模糊)\n- logistics_name(模糊)\n- item_part_type(等值)\n- item_part(模糊)\n- item_snapshot_key(模糊)\n- item_detail_machine(模糊)\n- distinguish_express(等值)\n- total_orders_min / total_orders_max(范围)\n- processed_orders_min / processed_orders_max(范围)\n- express_assignment_status(等值,string,可选,英文枚举,取值:unassigned、partially_assigned、assigned;语义:按快递分配聚合判断,assigned 表示聚合后全部 fin,partially_assigned 表示部分已分配且不含 error,unassigned 表示全 none 或包含 error(异常并入未分配集合))。\n- print_assignment_status(等值,string,可选,英文枚举,取值:unprinted、partially_printed、printed;语义:按打印分配聚合判断,printed 表示聚合后全部已打印)。\n- storage_assignment_status(等值,string,可选,取值:未分配、部分分配、已分配;默认不传不做限制)。过滤语义:已分配=聚合后全部 fin;部分分配=不含 error,且既不是全 none,也不是全 fin;未分配=全 none 或包含 error(异常并入未分配筛选集合)。说明:返回字段 storage_assignment_status 的展示值保持不变,包含 error 时仍可显示“分配异常”;此处 where 的过滤语义会把异常计入“未分配”,以避免把过滤语义与展示值混淆。\n- source(可选,number)来源过滤:0=普通波次(正常后台操作),1=管理后台策略任务,2=PDA策略任务;不传则不过滤。\n说明:express_assignment_status 与 print_assignment_status 要求使用英文枚举值;storage_assignment_status 仍向后兼容中文展示值。若传入的枚举值不在允许集合内,接口会返回 400(参数校验失败),并在 message 中说明错误字段与允许取值。\n- review_assignment_status(等值,string,可选,英文枚举:unreviewed、partially_reviewed、reviewed;分别表示未复核、部分复核、已复核)。" + "description": "筛选白名单字段(object,可选)。仅支持下列字段过滤,且禁止传入 warehouse_id / warehouseId:\n- wave_id(等值)\n- wave_no(模糊)\n- wave_type(等值)\n- wave_status(等值,接口固定叠加状态 0/1)\n- creator(模糊)\n- logistics_name(模糊)\n- item_part_type(等值)\n- item_part(模糊)\n- item_snapshot_key(模糊)\n- item_detail_machine(模糊)\n- distinguish_express(等值)\n- total_orders_min / total_orders_max(范围)\n- processed_orders_min / processed_orders_max(范围)\n- express_assignment_status(等值,string,可选,英文枚举,取值:unassigned、partially_assigned、assigned;语义:按快递分配聚合判断,assigned 表示聚合后全部 fin,partially_assigned 表示部分已分配且不含 error,unassigned 表示全 none 或包含 error(异常并入未分配集合))。\n- print_assignment_status(等值,string,可选,英文枚举,取值:unprinted、partially_printed、printed;语义:按打印分配聚合判断,printed 表示聚合后全部已打印)。\n- storage_assignment_status(等值,string,可选,取值:未分配、部分分配、已分配;默认不传不做限制)。过滤语义:已分配=聚合后全部 fin;部分分配=不含 error,且既不是全 none,也不是全 fin;未分配=全 none 或包含 error(异常并入未分配筛选集合)。说明:返回字段 storage_assignment_status 的展示值保持不变,包含 error 时仍可显示“分配异常”;此处 where 的过滤语义会把异常计入“未分配”,以避免把过滤语义与展示值混淆。\n- source(可选,number)来源过滤:0=普通波次(正常后台操作),1=管理后台策略任务,2=PDA策略任务;不传则不过滤。\n说明:express_assignment_status 与 print_assignment_status 要求使用英文枚举值;storage_assignment_status 仍向后兼容中文展示值。若传入的枚举值不在允许集合内,接口会返回 400(参数校验失败),并在 message 中说明错误字段与允许取值。\n- review_assignment_status(等值,string,可选,英文枚举:unreviewed、partially_reviewed、reviewed;分别表示未复核、部分复核、已复核)。\n- store_id(货主ID,可选,正整数,支持单值/数组/{operator,value} 结构,如 {\"operator\":\"\",\"value\":[1000281,1000000]};语义:返回包含任一筛选货主订单的波次,含混合货主波次;单值与数组均按 in 匹配)。" } ], "response": [ @@ -28546,7 +28546,7 @@ "name": "list", "type": "array", "required": true, - "description": "波次列表,包含波次基础信息与状态汇总(order_count / storage_assignment_status / express_assignment_status / print_assignment_status / pick_assignment_status / review_assignment_status / unreviewed_order_count)。其中 pick_assignment_status 按订单 pick_status 聚合判定,取值:未拣货/部分拣货/已拣货/拣货异常。每条记录新增字段 source(number):来源标识,0=普通波次(正常后台操作),1=管理后台策略任务,2=PDA策略任务。" + "description": "波次列表,包含波次基础信息与状态汇总(order_count / storage_assignment_status / express_assignment_status / print_assignment_status / pick_assignment_status / review_assignment_status / unreviewed_order_count)。其中 pick_assignment_status 按订单 pick_status 聚合判定,取值:未拣货/部分拣货/已拣货/拣货异常。每条记录新增字段 source(number):来源标识,0=普通波次(正常后台操作),1=管理后台策略任务,2=PDA策略任务。每条记录新增字段 store_name(string):货主信息,当波次内所有订单均为同一货主(store_id)时返回货主名称,否则返回“混合”;货主名称优先取合约表 wms_store_warehouse.store_remask(货主备注名称),无合约或备注为空时回退 wms_store.company_name(公司全称)。" }, { "name": "pagination", From adb74053963d94c2f2a7f7c49a517451c639842e Mon Sep 17 00:00:00 2001 From: liufumingren Date: Wed, 26 Aug 2026 17:40:49 +0800 Subject: [PATCH 278/550] =?UTF-8?q?feat(receiving):=20=E5=AE=A1=E6=A0=B8?= =?UTF-8?q?=E9=80=9A=E8=BF=87=E9=80=9A=E7=9F=A5=E8=BF=94=E5=9B=9E=20Excel?= =?UTF-8?q?=20=E5=AE=A1=E6=A0=B8=E6=98=8E=E7=BB=86=E4=B8=8B=E8=BD=BD?= =?UTF-8?q?=E9=93=BE=E6=8E=A5=EF=BC=8C=E5=A4=B1=E8=B4=A5=E5=9B=9E=E9=80=80?= =?UTF-8?q?=E6=AD=A3=E6=96=87=E5=B1=95=E7=A4=BA=E6=98=8E=E7=BB=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/systems/storage/receiving.js | 159 +++++++++++++++-------- methods/changes/warehouse.json | 16 +++ 2 files changed, 123 insertions(+), 52 deletions(-) diff --git a/app/service/systems/storage/receiving.js b/app/service/systems/storage/receiving.js index 5af09f4..786315b 100644 --- a/app/service/systems/storage/receiving.js +++ b/app/service/systems/storage/receiving.js @@ -1190,33 +1190,33 @@ class ReceivingService extends Service { reviewer: reviewerName, }); - // 1. 发送文字通知 + // 0. 加载明细并反查货主商品编码(通知文案与报表共用,失败不影响主流程) + let details = []; + let itemCodeMap = new Map(); try { - const textResult = await this.sendReviewNotice({ receiving: receivingSnapshot, reviewer }); - ctx.logger.info('[receiving.reviewReceiving] 文字通知结果', { + details = await ctx.model.ReceivingDetail.findAll({ + where: { receiving_id: r.id }, + }); + itemCodeMap = await this.resolveReviewDetailItemCodeMap(details); + } catch (detailErr) { + ctx.logger.error('[receiving.reviewReceiving] 加载明细失败', { receiving_id: r.id, receiving_number: r.receiving_number, - success: !!(textResult && textResult.success), - message: textResult && textResult.message, - matchedHookCount: Number(textResult && textResult.data && textResult.data.matchedHookCount || 0), - sentCount: Number(textResult && textResult.data && textResult.data.sentCount || 0), - failedCount: Number(textResult && textResult.data && textResult.data.failedCount || 0), - }); - } catch (textErr) { - ctx.logger.error('[receiving.reviewReceiving] 文字通知发送失败', { - receiving_id: r.id, - error: textErr.message, + error: detailErr.message, }); } - // 2. 加载明细与图片,生成 Excel 报表 + // 1. 加载明细与图片,生成 Excel 报表(复用步骤 0 已加载的明细,为空时回退重新查询) let reviewReport = null; try { - const details = await ctx.model.ReceivingDetail.findAll({ - where: { receiving_id: r.id }, - }); + let reportDetails = details; + if (reportDetails.length === 0) { + reportDetails = await ctx.model.ReceivingDetail.findAll({ + where: { receiving_id: r.id }, + }); + } - const detailIds = details.map(d => String(d.id)); + const detailIds = reportDetails.map(d => String(d.id)); const detailImageMap = new Map(); if (detailIds.length > 0) { const detailImageRefs = await ctx.model.FileReference.findAll({ @@ -1239,10 +1239,10 @@ class ReceivingService extends Service { }); const stats = { - total_details: details.length, - matched_details: details.filter(d => d.system_product_id).length, - unmatched_details: details.filter(d => !d.system_product_id).length, - total_quantity: details.reduce((sum, d) => sum + (d.actual_quantity || 0), 0), + total_details: reportDetails.length, + matched_details: reportDetails.filter(d => d.system_product_id).length, + unmatched_details: reportDetails.filter(d => !d.system_product_id).length, + total_quantity: reportDetails.reduce((sum, d) => sum + (d.actual_quantity || 0), 0), }; const excelService = ctx.service && ctx.service.systems && ctx.service.systems.excel; @@ -1257,7 +1257,7 @@ class ReceivingService extends Service { businessId: r.id, expireDays: 90, sheets: this.buildReviewReportSheets({ - receiving: { ...receivingSnapshot, details }, + receiving: { ...receivingSnapshot, details: reportDetails }, reviewer, stats, detailImageMap, @@ -1273,32 +1273,37 @@ class ReceivingService extends Service { url: reviewReport && (reviewReport.url || reviewReport.cdnUrl || reviewReport.cosUrl || ''), }); } catch (reportErr) { - ctx.logger.error('[receiving.reviewReceiving] Excel报表生成失败,跳过文件通知', { + ctx.logger.error('[receiving.reviewReceiving] Excel报表生成失败,回退正文展示明细列表', { receiving_id: r.id, error: reportErr.message, }); } - // 3. 发送文件通知(仅当 Excel 上传成功时) - if (reviewReport) { - try { - const fileResult = await this.sendReviewNotice({ receiving: receivingSnapshot, reviewer, reviewReport }); - ctx.logger.info('[receiving.reviewReceiving] 文件通知结果', { - receiving_id: r.id, - receiving_number: r.receiving_number, - success: !!(fileResult && fileResult.success), - message: fileResult && fileResult.message, - matchedHookCount: Number(fileResult && fileResult.data && fileResult.data.matchedHookCount || 0), - sentCount: Number(fileResult && fileResult.data && fileResult.data.sentCount || 0), - failedCount: Number(fileResult && fileResult.data && fileResult.data.failedCount || 0), - reportUrl: reviewReport.url || reviewReport.cdnUrl || reviewReport.cosUrl || '', - }); - } catch (fileErr) { - ctx.logger.error('[receiving.reviewReceiving] 文件通知发送失败', { - receiving_id: r.id, - error: fileErr.message, - }); - } + // 2. 发送审核完成通知:Excel 生成成功直接带下载链接,失败则回退正文展示全部明细 + try { + const noticeResult = await this.sendReviewNotice({ + receiving: receivingSnapshot, + reviewer, + reviewReport, + details, + itemCodeMap, + }); + ctx.logger.info('[receiving.reviewReceiving] 审核完成通知结果', { + receiving_id: r.id, + receiving_number: r.receiving_number, + hasReport: !!reviewReport, + success: !!(noticeResult && noticeResult.success), + message: noticeResult && noticeResult.message, + matchedHookCount: Number(noticeResult && noticeResult.data && noticeResult.data.matchedHookCount || 0), + sentCount: Number(noticeResult && noticeResult.data && noticeResult.data.sentCount || 0), + failedCount: Number(noticeResult && noticeResult.data && noticeResult.data.failedCount || 0), + reportUrl: reviewReport && (reviewReport.url || reviewReport.cdnUrl || reviewReport.cosUrl || ''), + }); + } catch (noticeErr) { + ctx.logger.error('[receiving.reviewReceiving] 审核完成通知发送失败', { + receiving_id: r.id, + error: noticeErr.message, + }); } ctx.logger.info('[receiving.reviewReceiving] 单据通知处理完成', { @@ -1573,12 +1578,16 @@ class ReceivingService extends Service { * @param {Object} options.receiving 收货单快照 * @param {Object} [options.reviewer={}] 审核人信息 * @param {Object|null} [options.reviewReport=null] 审核报表(有值则发文件通知) + * @param {Array|null} [options.details=null] 收货明细列表(用于通知文案展示全部明细) + * @param {Map|null} [options.itemCodeMap=null] system_product_id → item_code 映射 * @return {Promise} 发送结果 */ async sendReviewNotice({ receiving, reviewer = {}, reviewReport = null, + details = null, + itemCodeMap = null, } = {}) { const { ctx } = this; const rawNoticeService = ctx && ctx.service && ctx.service.systems && ctx.service.systems.notice; @@ -1603,13 +1612,23 @@ class ReceivingService extends Service { (reviewReport && (reviewReport.filename || reviewReport.fileKey || reviewReport.key)) || `审核明细_${receivingNumber}.xlsx` ).trim(); - const content = [ - `收货单号:${receivingNumber}`, - `货主:${receiving.store_name || '未知'}`, - `审核人:${reviewerName || '未知'}`, - `审核时间:${this.formatReportDate(receiving.updated_at || new Date())}`, - `备注:${receiving.remark || '无'}`, - ].join('\n') + '。'; + const detailList = Array.isArray(details) ? details : []; + const codeMap = itemCodeMap instanceof Map ? itemCodeMap : new Map(); + const productLines = detailList.map((detail, index) => { + const stockId = Number(detail.system_product_id || 0); + const itemCode = (stockId > 0 && codeMap.get(stockId)) || String(detail.barcode || '').trim() || '未知编码'; + const productName = String(detail.product_name || '').trim() || '未知商品'; + const quantity = Number(detail.actual_quantity || 0); + return `${index + 1}.${itemCode} ${productName} ${quantity}`; + }); + const contentLines = [ `收货单号:${receivingNumber} 完成收货审核` ]; + if (reportUrl) { + contentLines.push('', `审核明细下载:${reportUrl}`); + } else if (productLines.length > 0) { + contentLines.push('', '商品:', ...productLines); + } + contentLines.push('', '请及时提交入库单入库'); + const content = contentLines.join('\n') + '。'; return await noticeService.send({ warehouseId, @@ -1618,7 +1637,7 @@ class ReceivingService extends Service { businessName: 'receiving', event: 'receiving_reviewed', channel: 'warehouse', - title: `收货单${receivingNumber}审核完成`, + title: `收货单${receivingNumber}完成收货审核`, content, url: reportUrl || undefined, fileName: reportUrl ? reportFileName : '', @@ -1642,6 +1661,42 @@ class ReceivingService extends Service { }); } + /** + * 反查货主商品编码:收货明细 system_product_id 对应 wms_stock_store.stock_id,取 item_code 作为商品编码。 + * @param {Array} details 收货明细列表(含 system_product_id) + * @return {Promise>} system_product_id → item_code + */ + async resolveReviewDetailItemCodeMap(details = []) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const codeMap = new Map(); + if (!Array.isArray(details) || details.length === 0) return codeMap; + + const stockIds = [ ...new Set( + details.map(detail => Number(detail.system_product_id || 0)).filter(id => Number.isFinite(id) && id > 0) + ) ]; + if (stockIds.length === 0) return codeMap; + + const rows = await ctx.model.StockStore.findAll({ + where: { + stock_id: { [Op.in]: stockIds }, + delete_at: null, + }, + attributes: [ 'stock_id', 'item_code' ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + rows.forEach(row => { + const stockId = Number(row.stock_id); + if (!stockId || codeMap.has(stockId)) return; + const itemCode = String(row.item_code || '').trim(); + if (itemCode) codeMap.set(stockId, itemCode); + }); + + return codeMap; + } + isEmptyValue(value) { if (value === undefined || value === null) { return true; diff --git a/methods/changes/warehouse.json b/methods/changes/warehouse.json index 8f1b5d4..dbb04cc 100644 --- a/methods/changes/warehouse.json +++ b/methods/changes/warehouse.json @@ -270,5 +270,21 @@ "触发点:completeReceiving 事务提交后,unmatchedDetails 非空且已绑定货主时发送,失败不影响主流程" ], "module": "receiving" + }, + { + "version": "2026-08-26-warehouse-03", + "date": "2026-08-26", + "type": "changed", + "summary": "审核通过通知(receiving_reviewed)改为返回 Excel 审核明细下载链接,Excel 生成失败时回退正文展示全部明细(item_code 反查 stock_store)", + "methods": [ + "notify.reply" + ], + "notes": [ + "storage/receiving.js 新增 resolveReviewDetailItemCodeMap:批量反查 wms_stock_store(stock_id=明细 system_product_id,delete_at 为空),返回 system_product_id → item_code 映射", + "sendReviewNotice 内容改为「收货单号:Rxx 完成收货审核 / 审核明细下载:Excel链接 / 请及时提交入库单入库」,标题改为完成收货审核;Excel 生成失败时回退正文展示全部明细(1.商品编码 名称 数量)", + "reviewReceiving 调整为先生成 Excel 再发一次通知(成功带下载链接,失败回退文字),替代原「先文字后文件」两次发送", + "item_code 反查不到时回退明细条码,仍无则显示未知编码" + ], + "module": "receiving" } ] From f8915a5733b08f99bd837d9ebfc606971a33d5ca Mon Sep 17 00:00:00 2001 From: liufumingren Date: Thu, 27 Aug 2026 17:58:52 +0800 Subject: [PATCH 279/550] =?UTF-8?q?fix(openapi/storage):=20=E4=BF=AE?= =?UTF-8?q?=E5=A4=8D=E6=9C=8D=E5=8A=A1=E5=91=BD=E5=90=8D=E5=86=B2=E7=AA=81?= =?UTF-8?q?=E3=80=81=E5=AE=8C=E5=96=84=E5=AF=BC=E5=85=A5=E5=85=A5=E5=BA=93?= =?UTF-8?q?=E6=94=B6=E8=B4=A7=E5=8D=95=E5=8D=A0=E7=94=A8=E4=B8=8E=E5=85=A5?= =?UTF-8?q?=E5=BA=93=E5=8D=95=E8=AF=A6=E6=83=85=E5=AD=97=E6=AE=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - openapi.js 重命名为 openapiEntry.js,消除与 openapi/ 目录同名冲突,恢复 ctx.service.openapi.callback 可用,修复 quickInbound API 回传报 Cannot read properties of undefined (reading 'sendWithRetry') - 导入/PDA 入库 commit 新增非绑定模式收货单占用:带 receiving_detail_id 的记录优先按明细扣减,剩余导入量按 stock_id 匹配绑定收货单明细占用并回写收货单入库状态 - storage.entry.get 响应新增 total_order_lines / total_quantity / received_quantity 字段 - 同步 AI_METHOD_ROUTING.md 与 methods/changes 变更记录 --- AI_METHOD_ROUTING.md | 2 +- app/controller/openapi.js | 2 +- app/service/{openapi.js => openapiEntry.js} | 0 app/service/systems/inbound_direct_log.js | 70 ++++++++++++++++++++- app/service/systems/storage/entry.js | 7 ++- methods/changes/openapi.json | 12 ++++ methods/changes/system.json | 35 +++++++++++ 7 files changed, 124 insertions(+), 4 deletions(-) rename app/service/{openapi.js => openapiEntry.js} (100%) diff --git a/AI_METHOD_ROUTING.md b/AI_METHOD_ROUTING.md index 75ff282..f268883 100644 --- a/AI_METHOD_ROUTING.md +++ b/AI_METHOD_ROUTING.md @@ -147,7 +147,7 @@ rg "class .*Service|module.exports" app/service/qimenMethods - receive - app/service/main.js (18) - success, fail, normalizeDate, setInfo, getInfo, isPlainObject, normalizeWhereCondition, normalizeWhereParams, extractWhereValues, prepareWhereContext, findQimenAppWithContract, queryFromDatabase, checkAuth, checkApiPermission, extractApiPermissionState, collectApiPermissionValue, setUserContext, systemInit -- app/service/openapi.js (9) +- app/service/openapiEntry.js (9) - resolveOpenapiMethod, getOpenapiMethodService, resolveOpenapiContract, getInfo, dispatchOpenapiMethod, validateOpenapiParams, parseJsonBody, normalizeSignFields, processRequest - app/service/openapi/callback.js (4) - signCallback, sendWithRetry, sendByAppKey, logCallback diff --git a/app/controller/openapi.js b/app/controller/openapi.js index 8a9495d..24a959b 100644 --- a/app/controller/openapi.js +++ b/app/controller/openapi.js @@ -30,7 +30,7 @@ class OpenapiController extends Controller { const { ctx } = this; try { - const result = await ctx.service.openapi.processRequest(); + const result = await ctx.service.openapiEntry.processRequest(); if (result.ok) { ctx.status = Number(result.httpStatus) || 200; ctx.body = toSuccess(result.data, result.message || 'ok'); diff --git a/app/service/openapi.js b/app/service/openapiEntry.js similarity index 100% rename from app/service/openapi.js rename to app/service/openapiEntry.js diff --git a/app/service/systems/inbound_direct_log.js b/app/service/systems/inbound_direct_log.js index 77d6cc4..0b9e309 100644 --- a/app/service/systems/inbound_direct_log.js +++ b/app/service/systems/inbound_direct_log.js @@ -1156,9 +1156,12 @@ class InboundDirectLogService extends Service { ); } - // 回写收货单和收货明细的入库状态 + // 回写收货单和收货明细的入库状态(绑定模式:按 receiving_detail_id 优先扣减) await this._syncReceivingStorageStatus({ entryItemIds, transaction }); + // 非绑定模式剩余导入量:按 stock_id 匹配绑定收货单明细占用(绑定模式优先,剩余兜底) + await this._applyReceivingStockOccupancy({ entryOrder: eo, directLogs, transaction }); + // 更新入库单状态为 COMPLETED await eo.update({ order_status: 'COMPLETED', @@ -1682,6 +1685,71 @@ class InboundDirectLogService extends Service { ); } } + + /** + * 非绑定模式收货单占用:导入记录未携带 receiving_detail_id 时, + * 将剩余导入量按 stock_id(=收货明细 system_product_id)匹配到绑定收货单明细上, + * 依次占用剩余可入数量(actual_quantity - stored_quantity), + * 回写 stored_quantity/storage_status 并汇总收货单主表 storage_status。 + * 携带 receiving_detail_id 的导入记录已由 _syncReceivingStorageStatus 优先处理, + * 本方法只处理未携带 receiving_detail_id 的剩余部分(必须先调用前者)。 + * + * @param {Object} params 参数 + * @param {Object} params.entryOrder 入库单实例 + * @param {Array} params.directLogs 入库单下所有未删除的导入/PDA 入库记录 + * @param {Object} params.transaction Sequelize 事务对象 + * @return {Promise} + */ + async _applyReceivingStockOccupancy({ entryOrder, directLogs, transaction }) { + const { ctx, app } = this; + + // 1. 入库单未绑定收货单 → 跳过 + const bindings = await ctx.model.EntryOrderReceiving.findAll({ + where: { entry_order_id: entryOrder.id, deleted_at: null }, + attributes: [ 'receiving_id' ], + raw: true, + transaction, + }); + const receivingIds = [ ...new Set((bindings || []).map(b => Number(b.receiving_id)).filter(Boolean)) ]; + if (receivingIds.length === 0) return; + + // 2. 汇总未携带 receiving_detail_id 的导入量(绑定模式已优先处理,这里只取剩余部分) + const stockInboundQtyMap = new Map(); + for (const log of directLogs) { + if (log.receiving_detail_id) continue; + const stockId = Number(log.stock_id); + const qty = Number(log.quantity) || 0; + if (!stockId || qty <= 0) continue; + stockInboundQtyMap.set( + stockId, + { inboundQty: (stockInboundQtyMap.get(stockId)?.inboundQty || 0) + qty } + ); + } + if (stockInboundQtyMap.size === 0) return; + + // 3. 查询绑定收货单明细(事务内读取,stored_quantity 已包含绑定模式扣减结果) + const boundDetails = await ctx.model.ReceivingDetail.findAll({ + where: { + receiving_id: { [app.Sequelize.Op.in]: receivingIds }, + system_product_id: { [app.Sequelize.Op.ne]: null }, + }, + attributes: [ 'id', 'receiving_id', 'system_product_id', 'actual_quantity', 'stored_quantity' ], + raw: true, + transaction, + }); + if (!boundDetails || boundDetails.length === 0) return; + + // 4. 复用 storage.entry 的收货单占用逻辑(与 quickInbound 一致,事务内行锁防并发超分) + await ctx.service.systems.storage.entry._applyReceivingInboundUsage({ + receivingDetailRows: boundDetails, + stockInboundQtyMap, + transaction, + }); + + ctx.logger.info( + `[InboundDirectLog] 非绑定模式导入已按 stock_id 占用收货单明细,entryOrderId=${entryOrder.id}` + ); + } } module.exports = InboundDirectLogService; diff --git a/app/service/systems/storage/entry.js b/app/service/systems/storage/entry.js index 956e6ad..644a9d3 100644 --- a/app/service/systems/storage/entry.js +++ b/app/service/systems/storage/entry.js @@ -576,7 +576,9 @@ class EntryService extends Service { * @param {number} data.id 入库单主键 ID(必填) * @param {string} [mode='warehouse'] 查询维度:'warehouse' 按仓库校验权限(默认),'store' 按货主校验权限 * @return {Promise} code/data/message 结构 - * - data.entryOrder: { id, entry_order_code, order_status, store_remask } + * - data.entryOrder: { id, entry_order_code, order_status, total_order_lines, store_remask } + * - data.total_quantity: 应入库总数量(明细 planned 之和) + * - data.received_quantity: 已入库总数量(明细 completed 之和) * - data.items: [{ id, stock_id, planned, completed, stock, bindings }] * - data.receivingBindings: [{ id, receiving_id, receiving }] */ @@ -827,8 +829,11 @@ class EntryService extends Service { id: entryOrder.id, entry_order_code: entryOrder.entry_order_code, order_status: entryOrder.order_status, + total_order_lines: entryOrder.total_order_lines, store_remask: (storeWarehouse && storeWarehouse.store_remask) || '', }, + total_quantity: items.reduce((sum, item) => sum + (Number(item.planned) || 0), 0), + received_quantity: items.reduce((sum, item) => sum + (Number(item.completed) || 0), 0), items, receivingBindings, }, diff --git a/methods/changes/openapi.json b/methods/changes/openapi.json index f7485fb..02014e4 100644 --- a/methods/changes/openapi.json +++ b/methods/changes/openapi.json @@ -1,4 +1,16 @@ [ + { + "version": "2026.08.27-openapi-service-conflict-fix", + "date": "2026-08-27", + "summary": "修复 Egg 服务命名冲突:app/service/openapi.js 重命名为 openapiEntry.js,恢复 ctx.service.openapi.callback 可用", + "methods": [], + "notes": [ + "根因:app/service/openapi.js 文件与 app/service/openapi/ 目录同名,Egg ContextLoader 把目录里的 callback/callbackRegistry 挂成 OpenapiService 类的静态属性,实例上不可见,导致运行时 ctx.service.openapi.callback 为 undefined", + "修复:openapi.js 重命名为 openapiEntry.js(服务路径 ctx.service.openapiEntry),app/controller/openapi.js 的 processRequest 引用同步更新,AI_METHOD_ROUTING.md 同步", + "影响:storage.entry.quickInbound 对 API 来源直入单回传 entry_order_direct_inbound_completed 事件不再报 Cannot read properties of undefined (reading 'sendWithRetry'),库存两段式(先回传后写库)可正常执行" + ], + "type": "fixed" + }, { "version": "2026.06.04-openapi-04", "date": "2026-06-04", diff --git a/methods/changes/system.json b/methods/changes/system.json index 92698d6..2d28289 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,39 @@ [ + { + "version": "2026.08.27-storage-entry-get-total-order-lines", + "date": "2026-08-27", + "type": "enhanced", + "summary": "storage.entry.get 响应新增 total_order_lines(entryOrder 内)、total_quantity(应入库总数量)、received_quantity(已入库总数量)字段", + "methods": [ + "storage.entry.get", + "storage.entry.getStore" + ], + "notes": [ + "app/service/systems/storage/entry.js get:返回 data.entryOrder 新增 total_order_lines(直接取 wms_entry_order.total_order_lines)", + "data 顶层新增 total_quantity = 明细 planned 之和(应入库总数量)、received_quantity = 明细 completed 之和(已入库总数量)", + "getStore 共用同一底层实现,自动获得这些字段", + "同步更新 get 方法 JSDoc 注释" + ], + "module": "storage.entry" + }, + { + "version": "2026.08.27-directInbound-receiving-stock-occupancy", + "date": "2026-08-27", + "type": "enhanced", + "summary": "storage.entry.commit 导入/PDA 入库支持绑定收货单占用:带 receiving_detail_id 的导入记录优先按明细扣减,未带 receiving_detail_id 的剩余导入量按 stock_id 匹配收货单明细占用并回写收货单入库状态", + "methods": [ + "storage.entry.commit", + "storage.directInbound.commit" + ], + "notes": [ + "app/service/systems/inbound_direct_log.js commit onSuccess 事务内新增 _applyReceivingStockOccupancy:绑定收货单(wms_entry_order_receiving)存在时,汇总未携带 receiving_detail_id 的导入记录数量,按 stock_id(=收货明细 system_product_id)匹配占用", + "优先级:携带 receiving_detail_id 的记录先由 _syncReceivingStorageStatus 按明细扣减,随后剩余量复用 storage.entry._applyReceivingInboundUsage 按 stock_id 依次占用收货明细剩余可入数量(actual_quantity - stored_quantity),事务内行锁防并发超分", + "占用后回写收货明细 stored_quantity/storage_status(all/partial),并汇总更新收货单主表 storage_status", + "未绑定收货单或无剩余导入量时跳过,不影响原有非绑定模式入库行为", + "storage.entry._applyReceivingInboundUsage 日志前缀由 [storage.entry.quickInbound] 改为 [storage.entry](方法现被 quickInbound 与 commit 两个流程复用)" + ], + "module": "storage.entry" + }, { "version": "2026.08.26-wave-batchList-store-id-filter", "date": "2026-08-26", From a2dce0d52058918ee621956a885f7ba98f314bba Mon Sep 17 00:00:00 2001 From: liufumingren Date: Thu, 27 Aug 2026 18:02:49 +0800 Subject: [PATCH 280/550] =?UTF-8?q?fix(order):=20=E8=AE=A2=E5=8D=95?= =?UTF-8?q?=E5=AF=BC=E5=87=BA=E6=90=BA=E5=B8=A6=E4=BA=A7=E5=93=81=E6=9F=A5?= =?UTF-8?q?=E8=AF=A2=E5=AF=BC=E5=87=BA=E5=A4=B1=E8=B4=A5=EF=BC=8C=E5=AF=BC?= =?UTF-8?q?=E5=87=BA=E9=93=BE=E8=B7=AF=E8=A1=A5=E9=BD=90=20stock=5Fquery?= =?UTF-8?q?=20=E8=99=9A=E6=8B=9F=E7=AD=9B=E9=80=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/systems/order_export.js | 10 +++++++++- methods/changes/system.json | 15 +++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/app/service/systems/order_export.js b/app/service/systems/order_export.js index a61626c..4951545 100644 --- a/app/service/systems/order_export.js +++ b/app/service/systems/order_export.js @@ -619,7 +619,8 @@ class OrderExportService extends OrderBaseService { }); const { where: sanitizedWhere, expressNumbers } = this.extractOrderListExpressVirtualFilter(where); const { where: whereAfterBuyerMessage, buyerMessageHas } = this.extractBuyerMessageHasVirtualFilter(sanitizedWhere); - const { where: whereAfterWaveIndex, waveIndexCondition } = this.extractWaveIndexVirtualFilter(whereAfterBuyerMessage); + const { where: whereAfterStockQuery, stockQuery } = this.extractStockQueryVirtualFilter(whereAfterBuyerMessage); + const { where: whereAfterWaveIndex, waveIndexCondition } = this.extractWaveIndexVirtualFilter(whereAfterStockQuery); const { where: whereAfterWaveScope, waveScope } = this.extractWaveScopeVirtualFilter(whereAfterWaveIndex); const mergedWhere = this.mergeWhereObjects( target.defaultWhereModuleName ? this.getDefaultWhere(target.defaultWhereModuleName) : {}, @@ -643,6 +644,13 @@ class OrderExportService extends OrderBaseService { queryWhere = this.appendConditionToWhere(queryWhere, buyerMessageCondition); } + if (stockQuery) { + // 仅传 table_type 时推导出与当前表类型一致的模块名,保证 order_items 表类型正确 + const stockQueryModuleName = target.defaultWhereModuleName || target.sortModuleName || 'order'; + const stockOrderIds = await this.findOrderIdsByStockQuery(stockQuery, stockQueryModuleName, warehouseId); + queryWhere = this.appendOrderIdsFilterToWhere(queryWhere, stockOrderIds); + } + if (waveIndexCondition) { const waveIndexOrderIds = await this.findOrderIdsByWaveIndexCondition(waveIndexCondition, warehouseId); queryWhere = this.appendOrderIdsFilterToWhere(queryWhere, waveIndexOrderIds); diff --git a/methods/changes/system.json b/methods/changes/system.json index 2d28289..bf891eb 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,19 @@ [ + { + "version": "2026.08.27-order-export-stock-query", + "date": "2026-08-27", + "type": "fixed", + "summary": "order.export 修复携带产品查询(where.stock_query)时导出失败(Unknown column ... in where clause):导出链路补齐 stock_query 虚拟筛选提取,按商品编码/名称/ID/条码解析为订单ID集合后注入主查询,与 order.list 语义一致", + "methods": [ + "order.export" + ], + "notes": [ + "app/service/systems/order_export.js exportOrders:在 extractBuyerMessageHasVirtualFilter 之后新增 extractStockQueryVirtualFilter,从 where 提取并移除 stock_query,避免其残留在 where 中经 buildWhere/parseWhereConditions 被当作数据库字段解析,导致 SQL Unknown column 报错", + "stockQuery 非空时调用 findOrderIdsByStockQuery(商品编码/名称/ID/条码模糊匹配 → stock_id 集合 → order_items 关联订单ID),再经 appendOrderIdsFilterToWhere 注入主查询;无匹配商品时导出结果为空,与 order.list 行为一致", + "stockQuery 模块名取 target.defaultWhereModuleName || target.sortModuleName || 'order',保证仅传 table_type 时按表类型推导对应模块(current/history 等)的 order_items 表类型" + ], + "module": "order" + }, { "version": "2026.08.27-storage-entry-get-total-order-lines", "date": "2026-08-27", From 80c73bb34b3dda7ad1a0773cd05cf8992b3649be Mon Sep 17 00:00:00 2001 From: liufumingren Date: Thu, 27 Aug 2026 20:11:52 +0800 Subject: [PATCH 281/550] =?UTF-8?q?feat(order):=20=E8=AE=A2=E5=8D=95?= =?UTF-8?q?=E5=88=9B=E5=BB=BA=E8=87=AA=E5=8A=A8=E5=88=86=E9=85=8D=E5=BF=AB?= =?UTF-8?q?=E9=80=92=E6=94=B9=E4=B8=BA=E9=98=9F=E5=88=97+=E5=AE=9A?= =?UTF-8?q?=E6=97=B6=E6=89=B9=E9=87=8F=E6=B6=88=E8=B4=B9=EF=BC=8C=E6=B6=88?= =?UTF-8?q?=E9=99=A4=E5=8F=96=E5=8F=B7=E6=AD=BB=E9=94=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 wms_waybill_allocate_queue 队列表(migration + model),订单创建异步流程仅入队(截单/未审核不入队) - 新增 consume_waybill_allocate_queue 定时任务:15s/worker/重入保护,按仓库+货主串行批量消费,同关系下同一时刻仅一个取号事务 - express_platform 三处结算事务统一先 FOR UPDATE wms_store_warehouse 再更新 wms_order_express(lockAndDeductWaybillSettlement),消除 AB-BA 死锁 --- app/model/waybill_allocate_queue.js | 102 ++++++ .../consume_waybill_allocate_queue.js | 255 ++++++++++++++ app/service/systems/delivery_order.js | 67 +++- app/service/systems/express_platform.js | 323 ++++++------------ ...60000-create-wms-waybill-allocate-queue.js | 107 ++++++ 5 files changed, 627 insertions(+), 227 deletions(-) create mode 100644 app/model/waybill_allocate_queue.js create mode 100644 app/schedule/consume_waybill_allocate_queue.js create mode 100644 database/migrations/20260827160000-create-wms-waybill-allocate-queue.js diff --git a/app/model/waybill_allocate_queue.js b/app/model/waybill_allocate_queue.js new file mode 100644 index 0000000..592e1f7 --- /dev/null +++ b/app/model/waybill_allocate_queue.js @@ -0,0 +1,102 @@ +'use strict'; + +/** + * 订单创建后自动分配快递的消费队列模型。 + * + * 订单创建后的异步流程只入队(截单/未审核不入队),由定时任务 + * app/schedule/consume_waybill_allocate_queue.js 按仓库+货主串行批量消费, + * 避免高并发逐单取号时的 InnoDB AB-BA 死锁。 + * + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} Sequelize 模型。 + */ +module.exports = app => { + const { BIGINT, INTEGER, STRING, DATE } = app.Sequelize; + + const WaybillAllocateQueue = app.model.define('waybill_allocate_queue', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '订单ID(关联订单分表)', + }, + business_key: { + type: INTEGER(3), + allowNull: false, + defaultValue: 1, + comment: '业务键(与 wms_order_express.business_key 一致)', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID(消费分组与数据隔离维度)', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '货主ID(消费分组维度)', + }, + status: { + type: STRING(20), + allowNull: false, + defaultValue: 'pending', + comment: '状态:pending/processing/done/failed', + }, + retry_count: { + type: INTEGER(3), + allowNull: false, + defaultValue: 0, + comment: '重试次数', + }, + next_retry_at: { + type: DATE, + allowNull: true, + comment: '下次可消费时间(失败退避)', + }, + error_message: { + type: STRING(500), + allowNull: true, + comment: '最近一次失败原因', + }, + created_at: { + type: DATE, + allowNull: false, + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + comment: '更新时间', + }, + }, { + tableName: 'wms_waybill_allocate_queue', + freezeTableName: true, + underscored: true, + timestamps: false, + comment: '订单创建后自动分配快递消费队列', + indexes: [ + { + name: 'uk_order_id_business_key', + unique: true, + fields: [ 'order_id', 'business_key' ], + }, + { + name: 'idx_status_id', + fields: [ 'status', 'id' ], + }, + { + name: 'idx_status_updated_at', + fields: [ 'status', 'updated_at' ], + }, + ], + }); + + return WaybillAllocateQueue; +}; diff --git a/app/schedule/consume_waybill_allocate_queue.js b/app/schedule/consume_waybill_allocate_queue.js new file mode 100644 index 0000000..8e2034e --- /dev/null +++ b/app/schedule/consume_waybill_allocate_queue.js @@ -0,0 +1,255 @@ +'use strict'; + +/** + * 定时消费订单创建时入队的自动分配快递队列(wms_waybill_allocate_queue)。 + * + * 背景:订单创建后的异步流程逐单直接取号,大批量订单创建时 N 条并发取号事务 + * 与结算事务产生 wms_store_warehouse / wms_order_express 的 AB-BA 死锁。 + * 本任务按仓库+货主串行消费,保证同一签约关系下同一时刻只有一个取号事务在跑。 + * + * 截单语义:订单创建时已判定(截单/未审核不入队),已入队的正常消费,消费侧不再校验截单。 + * 间隔 15 秒、type: worker(仅一个 worker 执行),带重入保护。 + */ + +const MAX_CONSUME_ROWS_PER_WINDOW = 200; +const MAX_RETRY_COUNT = 3; +const RETRY_BASE_DELAY_MS = 60 * 1000; +const PROCESSING_STALE_MS = 10 * 60 * 1000; +const MAX_ERROR_MESSAGE_LENGTH = 500; + +module.exports = { + schedule: { + interval: '15s', + type: 'worker', + immediate: false, + disable: false, + }, + + async task(ctx) { + // 防止重入 + if (ctx.app._consumeWaybillAllocateQueueRunning) return; + ctx.app._consumeWaybillAllocateQueueRunning = true; + + try { + await consumePendingRows(ctx); + } catch (err) { + ctx.logger.error(`[consume-waybill-allocate-queue] 消费异常: ${err.message}`, { stack: err.stack }); + } finally { + ctx.app._consumeWaybillAllocateQueueRunning = false; + } + }, +}; + +/** + * 批量更新队列行状态。 + * @param {Object} ctx Egg 上下文。 + * @param {Array} rows 队列行(含 id)。 + * @param {string} status 目标状态。 + * @param {string|null} errorMessage 失败原因。 + * @return {Promise} 无返回值。 + */ +async function updateQueueRowsStatus(ctx, rows, status, errorMessage) { + const queueModel = ctx.model && ctx.model.WaybillAllocateQueue; + if (!queueModel || !Array.isArray(rows) || rows.length === 0) { + return; + } + + const { Op } = ctx.app.Sequelize; + const ids = rows.map(row => Number(row.id)).filter(id => Number.isInteger(id) && id > 0); + if (ids.length === 0) { + return; + } + + await queueModel.update({ + status, + error_message: errorMessage ? String(errorMessage).slice(0, MAX_ERROR_MESSAGE_LENGTH) : null, + updated_at: new Date(), + }, { + where: { + id: { + [Op.in]: ids, + }, + }, + }); +} + +/** + * 组消费失败或未完成时:重试次数+1,未超限退回 pending(带退避),超限转 failed。 + * @param {Object} ctx Egg 上下文。 + * @param {Array} rows 队列行。 + * @param {string} errorMessage 失败原因。 + * @param {boolean} failImmediately 是否立即判失败(如 warehouse_id 缺失,重试无意义)。 + * @return {Promise} 无返回值。 + */ +async function markGroupRetryOrFailed(ctx, rows, errorMessage, failImmediately) { + const queueModel = ctx.model && ctx.model.WaybillAllocateQueue; + if (!queueModel || !Array.isArray(rows) || rows.length === 0) { + return; + } + + const normalizedErrorMessage = String(errorMessage || '运单分配失败'); + + for (const row of rows) { + const rowId = Number(row.id); + if (!Number.isInteger(rowId) || rowId <= 0) { + continue; + } + + const retryCount = Number(row.retry_count) || 0; + if (failImmediately || retryCount + 1 >= MAX_RETRY_COUNT) { + await queueModel.update({ + status: 'failed', + retry_count: retryCount + 1, + error_message: normalizedErrorMessage.slice(0, MAX_ERROR_MESSAGE_LENGTH), + updated_at: new Date(), + }, { + where: { id: rowId }, + }); + } else { + const delay = (retryCount + 1) * RETRY_BASE_DELAY_MS; + await queueModel.update({ + status: 'pending', + retry_count: retryCount + 1, + next_retry_at: new Date(Date.now() + delay), + error_message: null, + updated_at: new Date(), + }, { + where: { id: rowId }, + }); + } + } +} + +/** + * 拉取并消费待分配队列。 + * @param {Object} ctx Egg 上下文。 + * @return {Promise} 无返回值。 + */ +async function consumePendingRows(ctx) { + const queueModel = ctx.model && ctx.model.WaybillAllocateQueue; + const expressService = ctx.service && ctx.service.systems && ctx.service.systems.express; + if (!queueModel || typeof queueModel.findAll !== 'function' + || !expressService || typeof expressService.createWaybillCodePipeline !== 'function') { + return; + } + + const { Op } = ctx.app.Sequelize; + + // 1) 兜底恢复:上次运行中断遗留的 processing 行退回 pending + await queueModel.update({ + status: 'pending', + updated_at: new Date(), + }, { + where: { + status: 'processing', + updated_at: { + [Op.lt]: new Date(Date.now() - PROCESSING_STALE_MS), + }, + }, + }); + + // 2) 拉取待消费行 + const now = new Date(); + const pendingRows = await queueModel.findAll({ + where: { + status: 'pending', + [Op.or]: [ + { next_retry_at: null }, + { next_retry_at: { [Op.lte]: now } }, + ], + }, + order: [[ 'id', 'ASC' ]], + limit: MAX_CONSUME_ROWS_PER_WINDOW, + raw: true, + }); + + if (!Array.isArray(pendingRows) || pendingRows.length === 0) { + return; + } + + // 3) 标记消费中(单 worker + 重入保护下仅作状态记录) + const pendingIds = pendingRows.map(row => Number(row.id)).filter(id => Number.isInteger(id) && id > 0); + if (pendingIds.length > 0) { + await queueModel.update({ + status: 'processing', + updated_at: new Date(), + }, { + where: { + id: { + [Op.in]: pendingIds, + }, + }, + }); + } + + // 4) 按 warehouse_id + store_id 分组,逐组串行消费 + const groupMap = new Map(); + for (const row of pendingRows) { + const warehouseId = Number(row.warehouse_id) || 0; + const storeId = Number(row.store_id) || 0; + const groupKey = `${warehouseId}:${storeId}`; + if (!groupMap.has(groupKey)) { + groupMap.set(groupKey, { + warehouseId, + storeId, + rows: [], + }); + } + groupMap.get(groupKey).rows.push(row); + } + + const orderExpressModel = ctx.model && ctx.model.OrderExpress; + + for (const group of groupMap.values()) { + const orders = group.rows + .map(row => { + const orderId = Number(row.order_id); + const businessKey = Number(row.business_key) || 1; + return { order_id: orderId, business_key: businessKey }; + }) + .filter(order => Number.isInteger(order.order_id) && order.order_id > 0); + + if (group.warehouseId <= 0 || orders.length === 0) { + await markGroupRetryOrFailed(ctx, group.rows, '队列数据缺少有效 warehouse_id/order_id', true); + continue; + } + + try { + await expressService.createWaybillCodePipeline(orders, { + awaitTasks: true, + warehouseId: group.warehouseId, + }); + + // 5) 判定结果:取到单号(status=1)的订单视为完成 + const doneKeySet = new Set(); + if (orderExpressModel && typeof orderExpressModel.findAll === 'function') { + const doneRows = await orderExpressModel.findAll({ + where: { + warehouse_id: group.warehouseId, + [Op.or]: orders.map(order => ({ + order_id: order.order_id, + business_key: order.business_key, + })), + status: 1, + }, + attributes: [ 'order_id', 'business_key' ], + raw: true, + }); + for (const doneRow of Array.isArray(doneRows) ? doneRows : []) { + doneKeySet.add(`${Number(doneRow.order_id)}:${Number(doneRow.business_key)}`); + } + } + + const doneRows = group.rows.filter(row => doneKeySet.has(`${Number(row.order_id)}:${Number(row.business_key) || 1}`)); + const restRows = group.rows.filter(row => !doneKeySet.has(`${Number(row.order_id)}:${Number(row.business_key) || 1}`)); + + await updateQueueRowsStatus(ctx, doneRows, 'done', null); + await markGroupRetryOrFailed(ctx, restRows, '运单分配未完成', false); + + ctx.logger.info(`[consume-waybill-allocate-queue] 组消费完成 warehouse_id=${group.warehouseId} store_id=${group.storeId} total=${group.rows.length} done=${doneRows.length} rest=${restRows.length}`); + } catch (error) { + ctx.logger.error(`[consume-waybill-allocate-queue] 组消费失败 warehouse_id=${group.warehouseId} store_id=${group.storeId}: ${error.message}`); + await markGroupRetryOrFailed(ctx, group.rows, error && error.message ? error.message : String(error), false); + } + } +} diff --git a/app/service/systems/delivery_order.js b/app/service/systems/delivery_order.js index 8cb969c..dedf7a1 100644 --- a/app/service/systems/delivery_order.js +++ b/app/service/systems/delivery_order.js @@ -1862,6 +1862,63 @@ class DeliveryOrderService extends Service { }; } + /** + * 将订单入队到自动分配快递消费队列(wms_waybill_allocate_queue)。 + * + * 仅写入队列不取号,由定时任务 app/schedule/consume_waybill_allocate_queue.js + * 按仓库+货主串行批量消费。入队幂等(uk_order_id_business_key),重复入队忽略。 + * 调用方需保证截单/未审核订单不会走到此方法。 + * + * @param {Object} context 异步处理上下文。 + * @return {Promise} 无返回值。 + */ + async enqueueAutoWaybillAllocation(context) { + const queueModel = this.ctx.model && this.ctx.model.WaybillAllocateQueue; + if (!queueModel || typeof queueModel.findOrCreate !== 'function') { + this.ctx.logger.warn('[DeliveryOrderService.enqueueAutoWaybillAllocation] 运单分配队列模型未初始化,跳过入队'); + return; + } + + const orderId = Number(context && context.orderId || 0); + const warehouseId = Number(context && context.warehouseId || 0); + const storeId = Number(context && context.storeId || 0); + if (!Number.isInteger(orderId) || orderId <= 0 || !Number.isInteger(warehouseId) || warehouseId <= 0) { + return; + } + + try { + await queueModel.findOrCreate({ + where: { + order_id: orderId, + business_key: 1, + }, + defaults: { + order_id: orderId, + business_key: 1, + warehouse_id: warehouseId, + store_id: storeId > 0 ? storeId : 0, + status: 'pending', + retry_count: 0, + next_retry_at: null, + error_message: null, + created_at: new Date(), + updated_at: new Date(), + }, + }); + this.ctx.logger.info('[DeliveryOrderService.enqueueAutoWaybillAllocation] 订单已入队等待批量分配快递', { + orderId, + warehouseId, + storeId, + }); + } catch (error) { + // 唯一键冲突(重复入队)或 DB 异常仅记录,不阻断订单创建后续异步流程 + this.ctx.logger.warn('[DeliveryOrderService.enqueueAutoWaybillAllocation] 入队失败: %s', error.message, { + orderId, + error: error.message, + }); + } + } + /** * 构建储位分配显式请求体。 * @@ -2540,13 +2597,9 @@ class DeliveryOrderService extends Service { if (isAutoAllocateExpressEnabled) { await this.runAsyncProcessStep('allocateExpress', async () => { - const request = this.buildExpressAllocateRequest(context); - await this.withPatchedCtxUser({ - store_id: context.warehouseId, - warehouse_id: context.warehouseId, - }, async () => { - await this.ctx.service.systemMethods.order.pendingOrder.allocateExpressCode(request); - }); + // 不再逐单直接取号:改为写入消费队列,由定时任务按仓库+货主串行批量消费, + // 避免大批量订单创建时 N 条并发取号事务的 AB-BA 死锁。截单/未审核订单在此处不会入队。 + await this.enqueueAutoWaybillAllocation(context); }); } diff --git a/app/service/systems/express_platform.js b/app/service/systems/express_platform.js index fdb30ef..6136e96 100644 --- a/app/service/systems/express_platform.js +++ b/app/service/systems/express_platform.js @@ -1560,6 +1560,10 @@ class ExpressPlatformService extends MainService { }); try { await this.ctx.model.transaction(async transaction => { + // 统一加锁顺序:先锁 store_warehouse 再更新 order_express, + // 与 createWaybillCode 回写事务一致,避免 AB-BA 死锁 + await this.lockAndDeductWaybillSettlement(settlementRelationMap, storeWarehouseModel, transaction); + for (const item of successUpdates) { const warehouseId = Number(item.warehouse_id) || 0; const orderId = Number(item.order_id) || 0; @@ -1587,78 +1591,6 @@ class ExpressPlatformService extends MainService { }); } } - - 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 回写事务异常', { @@ -2239,6 +2171,97 @@ class ExpressPlatformService extends MainService { return settlementRelationMap; } + /** + * 事务内按 store:warehouse 扣减打印余量并写扣减流水。 + * + * 必须在结算事务内最先执行:先锁 wms_store_warehouse,再更新 wms_order_express, + * 与 createWaybillCode 回写事务(先锁 store_warehouse 后锁 order_express)保持 + * 一致加锁顺序,消除两类事务间的 AB-BA 死锁。 + * + * @param {Map} settlementRelationMap 结算关系聚合。 + * @param {Object} storeWarehouseModel 签约关系模型。 + * @param {Object} transaction Sequelize 事务。 + * @return {Promise} 无返回值。 + */ + async lockAndDeductWaybillSettlement(settlementRelationMap = new Map(), storeWarehouseModel, transaction) { + if (!storeWarehouseModel + || typeof storeWarehouseModel.findAll !== 'function' + || !settlementRelationMap + || settlementRelationMap.size === 0) { + return; + } + + 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, + }); + } + } + /** * 回写成功获取的面单结果,并扣减打印余量与写入操作日志。 * @@ -2258,6 +2281,10 @@ class ExpressPlatformService extends MainService { if (typeof this.ctx.model.transaction === 'function') { await this.ctx.model.transaction(async transaction => { + // 统一加锁顺序:先锁 store_warehouse 再更新 order_express, + // 与 createWaybillCode 回写事务一致,避免 AB-BA 死锁 + await this.lockAndDeductWaybillSettlement(settlementRelationMap, storeWarehouseModel, transaction); + for (const item of normalizedSuccessUpdates) { if (!item.warehouse_id || !item.order_id || !item.business_key) { throw new Error('平台接口返回 object_id 无法解析'); @@ -2282,80 +2309,6 @@ class ExpressPlatformService extends MainService { }); } } - - 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, - }); - } - } }); } @@ -2661,6 +2614,10 @@ 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 => { + // 统一加锁顺序:先锁 store_warehouse 再更新 order_express, + // 与 createWaybillCode 回写事务一致,避免 AB-BA 死锁 + await this.lockAndDeductWaybillSettlement(settlementRelationMap, storeWarehouseModel, transaction); + for (const item of successUpdates) { if (!item.warehouse_id || !item.order_id || !item.business_key) { throw new Error('拼多多平台接口返回 object_id 无法解析'); @@ -2685,80 +2642,6 @@ class ExpressPlatformService extends MainService { }); } } - - 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, - }); - } - } }); } diff --git a/database/migrations/20260827160000-create-wms-waybill-allocate-queue.js b/database/migrations/20260827160000-create-wms-waybill-allocate-queue.js new file mode 100644 index 0000000..0db2247 --- /dev/null +++ b/database/migrations/20260827160000-create-wms-waybill-allocate-queue.js @@ -0,0 +1,107 @@ +'use strict'; + +/** + * 创建订单创建后自动分配快递的消费队列表 wms_waybill_allocate_queue。 + * + * 背景:订单创建后的异步流程原为逐单直接取号,大批量订单创建时会产生 N 条并发 + * createWaybillCode 回写事务与结算事务的 AB-BA 死锁(wms_store_warehouse 与 + * wms_order_express 锁序相反)。改造为创建时只入队(截单/未审核不入队),由定时 + * 任务按仓库+货主串行批量消费。 + * + * 字段: + * - order_id / business_key:待分配运单的订单与业务键(与 wms_order_express 一致) + * - warehouse_id / store_id:消费分组与数据隔离维度 + * - status:pending(待消费)/ processing(消费中)/ done(完成)/ failed(超限失败) + * - retry_count / next_retry_at / error_message:重试与失败信息 + * + * 索引: + * - uk_order_id_business_key:幂等入队唯一键 + * - idx_status_id:消费拉取(status=pending 按 id 升序) + * - idx_status_updated_at:处理中兜底恢复扫描 + */ + +const TABLE_NAME = 'wms_waybill_allocate_queue'; + +module.exports = { + async up(queryInterface, Sequelize) { + const { BIGINT, INTEGER, STRING, DATE } = Sequelize; + await queryInterface.createTable(TABLE_NAME, { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '订单ID(关联订单分表)', + }, + business_key: { + type: INTEGER(3), + allowNull: false, + defaultValue: 1, + comment: '业务键(与 wms_order_express.business_key 一致)', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID(消费分组与数据隔离维度)', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '货主ID(消费分组维度)', + }, + status: { + type: STRING(20), + allowNull: false, + defaultValue: 'pending', + comment: '状态:pending/processing/done/failed', + }, + retry_count: { + type: INTEGER(3), + allowNull: false, + defaultValue: 0, + comment: '重试次数', + }, + next_retry_at: { + type: DATE, + allowNull: true, + comment: '下次可消费时间(失败退避)', + }, + error_message: { + type: STRING(500), + allowNull: true, + comment: '最近一次失败原因', + }, + created_at: { + type: DATE, + allowNull: false, + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + comment: '更新时间', + }, + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'order_id', 'business_key' ], { + name: 'uk_order_id_business_key', + unique: true, + }); + await queryInterface.addIndex(TABLE_NAME, [ 'status', 'id' ], { + name: 'idx_status_id', + }); + await queryInterface.addIndex(TABLE_NAME, [ 'status', 'updated_at' ], { + name: 'idx_status_updated_at', + }); + }, + + async down(queryInterface) { + await queryInterface.dropTable(TABLE_NAME); + }, +}; From f2fe5311aaf87534f09fbfc487005366c1ad799d Mon Sep 17 00:00:00 2001 From: liufumingren Date: Thu, 27 Aug 2026 23:38:46 +0800 Subject: [PATCH 282/550] =?UTF-8?q?chore(script):=20=E8=B0=83=E8=AF=95?= =?UTF-8?q?=E8=84=9A=E6=9C=AC=E7=A7=BB=E5=85=A5=20temp/=20=E4=B8=8D?= =?UTF-8?q?=E5=86=8D=E7=BA=B3=E5=85=A5=E7=89=88=E6=9C=AC=E6=8E=A7=E5=88=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 1 + script/debug-complete-receiving.cjs | 116 ----------- script/debug-inbox-push.cjs | 245 ---------------------- script/debug-send-receiving-webhooks.cjs | 252 ----------------------- script/debug-warehouse-push-receiver.cjs | 206 ------------------ script/debug-webhook-receiver.cjs | 134 ------------ 6 files changed, 1 insertion(+), 953 deletions(-) delete mode 100644 script/debug-complete-receiving.cjs delete mode 100644 script/debug-inbox-push.cjs delete mode 100644 script/debug-send-receiving-webhooks.cjs delete mode 100644 script/debug-warehouse-push-receiver.cjs delete mode 100644 script/debug-webhook-receiver.cjs diff --git a/.gitignore b/.gitignore index 1f9cb63..d91c223 100644 --- a/.gitignore +++ b/.gitignore @@ -38,3 +38,4 @@ versioning/* !versioning/.gitkeep app/public/exports/ +script/debug-*.cjs diff --git a/script/debug-complete-receiving.cjs b/script/debug-complete-receiving.cjs deleted file mode 100644 index 09d2255..0000000 --- a/script/debug-complete-receiving.cjs +++ /dev/null @@ -1,116 +0,0 @@ -'use strict'; - -/** - * 调试脚本:为指定账号铸造 JWT 并调用系统接口完成收货。 - * 用法: - * node script/debug-complete-receiving.cjs --receiving-id=1512 --account-id=1 - * node script/debug-complete-receiving.cjs --receiving-id=1512 --account-id=1 --host=127.0.0.1 --port=6060 - */ - -const http = require('node:http'); -const jwt = require('jsonwebtoken'); - -const JWT_SECRET = 'E5#ex.g@,GfL_8?'; -const JWT_EXPIRES_IN = 14400; - -function parseArgs(argv) { - const options = { - receivingId: 0, - accountId: 1, - host: '127.0.0.1', - port: 6060, - remark: '', - }; - - for (const arg of argv) { - if (!arg.startsWith('--')) { - continue; - } - const [ rawKey, ...rest ] = arg.slice(2).split('='); - const value = rest.join('='); - switch (rawKey) { - case 'receiving-id': - options.receivingId = Number(value || options.receivingId); - break; - case 'account-id': - options.accountId = Number(value || options.accountId); - break; - case 'host': - options.host = value || options.host; - break; - case 'port': - options.port = Number(value || options.port); - break; - case 'remark': - options.remark = value || ''; - break; - default: - break; - } - } - - return options; -} - -function postSystemMethod(options, token, method, body) { - return new Promise((resolve, reject) => { - const bodyJson = JSON.stringify(body); - const path = `/system?method=${encodeURIComponent(method)}&v=1×tamp=${Math.floor(Date.now() / 1000)}`; - const req = http.request({ - hostname: options.host, - port: options.port, - path, - method: 'POST', - headers: { - platform: 'web', - project: 'wms', - Authorization: `Bearer ${token}`, - 'Content-Type': 'application/json', - 'Content-Length': Buffer.byteLength(bodyJson), - }, - }, res => { - let data = ''; - res.on('data', chunk => { - data += chunk; - }); - res.on('end', () => { - resolve({ status: res.statusCode, body: data }); - }); - }); - req.on('error', reject); - req.write(bodyJson); - req.end(); - }); -} - -async function main() { - const options = parseArgs(process.argv.slice(2)); - if (!options.receivingId) { - console.error('缺少 --receiving-id'); - process.exit(1); - } - - const token = jwt.sign({ - id: options.accountId, - platform_code: 'web', - current_store_id: 100000, - }, JWT_SECRET, { expiresIn: JWT_EXPIRES_IN }); - - console.log(`[debug-complete-receiving] accountId=${options.accountId} receivingId=${options.receivingId}`); - const result = await postSystemMethod(options, token, 'storage.receiving.completeReceiving', { - id: options.receivingId, - remark: options.remark || undefined, - }); - - console.log(`HTTP ${result.status}`); - try { - console.log(JSON.stringify(JSON.parse(result.body), null, 2).substring(0, 3000)); - } catch (_) { - console.log(result.body.substring(0, 1000)); - } -} - -main().catch(error => { - console.error('[debug-complete-receiving] failed:', error.message); - process.exit(1); -}); diff --git a/script/debug-inbox-push.cjs b/script/debug-inbox-push.cjs deleted file mode 100644 index 82378a5..0000000 --- a/script/debug-inbox-push.cjs +++ /dev/null @@ -1,245 +0,0 @@ -'use strict'; - -/** - * 站内信消息推送调试脚本(模拟 IM 桥向仓库推送入站消息,走真实验签链路)。 - * - * 用法: - * node script/debug-inbox-push.cjs - * 默认: 向 test-stock-group 推送「查退回 <随机不存在运单号>」 - * node script/debug-inbox-push.cjs --content "查退回 888888888888888" - * node script/debug-inbox-push.cjs --waybill 888888888888888 --groupId test-stock-group --userName 测试用户 - * - * 行为: - * 1. 按 app/lib/api_sign.js 规则签名,POST /warehouse?method=inbox.push - * 2. 等待 AI 异步处理(默认 15s) - * 3. 回查本地库: 入站消息 / AI 思考过程 / 回信内容 / wms_return_query_log 登记 - */ - -const crypto = require('crypto'); -const http = require('http'); -const mysql = require('mysql2/promise'); - -// ========================== 稳定序列化(与 app/lib/api_sign.js 一致) ========================== - -function isPlainObject(value) { - return Object.prototype.toString.call(value) === '[object Object]'; -} - -function stableStringify(value) { - if (value === undefined) return ''; - if (value === null || typeof value !== 'object') return JSON.stringify(value); - if (Array.isArray(value)) { - return `[${value.map(item => stableStringify(item)).join(',')}]`; - } - if (!isPlainObject(value)) return JSON.stringify(value); - const keys = Object.keys(value).sort(); - return `{${keys.map(key => `${JSON.stringify(key)}:${stableStringify(value[key])}`).join(',')}}`; -} - -function md5(str) { - return crypto.createHash('md5').update(str, 'utf8').digest('hex') - .toLowerCase(); -} - -function buildSign(query, body, secret) { - const ignoreSet = new Set([ 'sign', 'signature' ]); - const keys = Object.keys(query) - .filter(key => !ignoreSet.has(String(key).toLowerCase())) - .filter(key => query[key] !== undefined) - .sort(); - const canonicalQuery = keys.map(key => { - const v = query[key]; - if (v === undefined || v === null) return `${key}=`; - if (typeof v === 'object') return `${key}=${stableStringify(v)}`; - return `${key}=${String(v)}`; - }).join('&'); - const bodySign = md5(stableStringify(body)); - const signText = `${canonicalQuery}${secret}${bodySign}`; - return { canonicalQuery, bodySign, sign: md5(signText) }; -} - -// ========================== 参数解析 ========================== - -const ARGS = {}; -for (let i = 2; i < process.argv.length; i++) { - const arg = process.argv[i]; - const match = arg.match(/^--([^=]+)=(.*)$/); - if (match) { - ARGS[match[1]] = match[2]; - } else if (arg.startsWith('--')) { - ARGS[arg.slice(2)] = process.argv[i + 1]; - i++; - } -} - -const CONFIG = { - baseUrl: ARGS.baseUrl || 'http://127.0.0.1:6060', - appKey: ARGS.appKey || 'APP2025011514315678', - appSecret: ARGS.appSecret || 'sec_xyz789uvw012abc345def678ghi901jkl234mno567pqr890', - groupId: ARGS.groupId || 'test-stock-group', - groupName: ARGS.groupName || '库存查询测试群', - userId: ARGS.userId || 'debug_user', - userName: ARGS.userName || '测试用户', - waitMs: Number(ARGS.waitMs || 15000), - waybill: ARGS.waybill || `${Date.now()}99`, -}; - -if (ARGS.content) { - CONFIG.content = ARGS.content; -} else { - CONFIG.content = `查退回 ${CONFIG.waybill}`; -} - -// ========================== HTTP 推送 ========================== - -function postWarehouse(method, body) { - const query = { - method, - v: '1.0', - timestamp: Math.floor(Date.now() / 1000), - app_key: CONFIG.appKey, - }; - const { sign } = buildSign(query, body, CONFIG.appSecret); - query.sign = sign; - - const qs = Object.entries(query) - .map(([ k, v ]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`) - .join('&'); - const bodyStr = JSON.stringify(body); - const url = `${CONFIG.baseUrl}/warehouse?${qs}`; - - return new Promise((resolve, reject) => { - const req = http.request(url, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'Content-Length': Buffer.byteLength(bodyStr), - }, - timeout: 20000, - }, res => { - let data = ''; - res.on('data', chunk => (data += chunk)); - res.on('end', () => { - try { resolve({ status: res.statusCode, body: JSON.parse(data) }); } catch (e) { resolve({ status: res.statusCode, body: data }); } - }); - }); - req.on('error', reject); - req.on('timeout', () => { req.destroy(); reject(new Error('Request timeout')); }); - req.write(bodyStr); - req.end(); - }); -} - -function sleep(ms) { - return new Promise(resolve => setTimeout(resolve, ms)); -} - -// ========================== 本地库回查 ========================== - -async function queryDb(sql) { - const conn = await mysql.createConnection({ - host: '127.0.0.1', - port: 3307, - user: 'wms', - password: 'dspxmRwRdRbWtbm7', - database: 'wms', - }); - try { - const [ rows ] = await conn.query(sql); - return rows; - } finally { - await conn.end(); - } -} - -// ========================== 主流程 ========================== - -(async () => { - const requestId = `debug-return-${Date.now()}`; - console.log('========== 站内信模拟推送 =========='); - console.log(` 群: ${CONFIG.groupId} (${CONFIG.groupName})`); - console.log(` 用户: ${CONFIG.userName}`); - console.log(` 内容: ${CONFIG.content}`); - console.log(` requestId: ${requestId}`); - - const r = await postWarehouse('inbox.push', { - requestId, - content: CONFIG.content, - groupId: CONFIG.groupId, - groupName: CONFIG.groupName, - userId: CONFIG.userId, - userName: CONFIG.userName, - targetType: 'im', - }); - - console.log(` HTTP ${r.status}: ${JSON.stringify(r.body).slice(0, 300)}`); - if (r.status !== 200 || (r.body && r.body.ok === false)) { - console.error('推送失败,请检查签名与仓库应用配置'); - process.exit(1); - } - - console.log(`\n等待 AI 异步处理 ${CONFIG.waitMs / 1000}s ...`); - await sleep(CONFIG.waitMs); - - const extId = `api:${CONFIG.appKey}:${requestId}`; - - // 1. 入站消息 + AI 思考 - const inbound = await queryDb( - `SELECT id, direction, content, ai_thoughts, push_status, created_at - FROM wms_inbox_message WHERE ext_id='${extId}' ORDER BY id DESC LIMIT 1` - ); - console.log('\n[入站消息]'); - if (inbound.length === 0) { - console.log(' 未找到(消息可能尚未入库)'); - } else { - console.log(` id=${inbound[0].id} push_status=${inbound[0].push_status}`); - console.log(` content: ${inbound[0].content}`); - const thoughts = inbound[0].ai_thoughts; - if (thoughts && typeof thoughts === 'string') { - try { - const parsed = JSON.parse(thoughts); - console.log(` ai_thoughts: ${JSON.stringify(parsed).slice(0, 400)}`); - } catch (e) { - console.log(` ai_thoughts(raw): ${String(thoughts).slice(0, 400)}`); - } - } else { - console.log(' ai_thoughts: 无'); - } - } - - // 2. 回信内容 - const outbound = await queryDb( - `SELECT id, direction, content, created_at - FROM wms_inbox_message - WHERE direction='outbound' AND group_id='${CONFIG.groupId}' - ORDER BY id DESC LIMIT 1` - ); - console.log('\n[最新回信]'); - if (outbound.length === 0) { - console.log(' 无回信'); - } else { - console.log(` id=${outbound[0].id} created_at=${outbound[0].created_at}`); - console.log(` content:\n${outbound[0].content}`); - } - - // 3. 退回查询登记 - const waybill = CONFIG.waybill; - const queryLog = await queryDb( - `SELECT id, warehouse_id, store_id, waybill_code, remark, is_notified, is_back, created_at - FROM wms_return_query_log WHERE waybill_code='${waybill}' ORDER BY id DESC LIMIT 3` - ); - console.log('\n[wms_return_query_log 登记]'); - if (queryLog.length === 0) { - console.log(' 无登记'); - } else { - queryLog.forEach(row => { - console.log(` id=${row.id} store_id=${row.store_id} is_back=${row.is_back} is_notified=${row.is_notified} remark=${row.remark} ${row.created_at}`); - }); - } - - console.log('\n完成。测试记录按需保留,无需删除。'); - process.exit(0); -})().catch(e => { - console.error('异常:', e.message); - process.exit(1); -}); diff --git a/script/debug-send-receiving-webhooks.cjs b/script/debug-send-receiving-webhooks.cjs deleted file mode 100644 index 663c4a4..0000000 --- a/script/debug-send-receiving-webhooks.cjs +++ /dev/null @@ -1,252 +0,0 @@ -'use strict'; - -const path = require('node:path'); -const urllib = require('urllib'); - -const DEFAULT_FILE_URL = 'https://ye4s.file.gzxunren.com/exports/receiving/completed/100000/20260405/%E6%94%B6%E8%B4%A7%E5%AE%8C%E6%88%90_R20547058.xlsx'; -const DEFAULT_FILE_NAME = '收货完成_R20547058.xlsx'; - -function parseArgs(argv) { - const options = { - url: process.env.WEBHOOK_DEBUG_URL || '', - textUrl: process.env.WEBHOOK_DEBUG_TEXT_URL || '', - fileUrl: process.env.WEBHOOK_DEBUG_FILE_URL || '', - mode: process.env.WEBHOOK_DEBUG_MODE || 'both', - warehouseId: Number(process.env.WEBHOOK_DEBUG_WAREHOUSE_ID || 100000), - storeId: Number(process.env.WEBHOOK_DEBUG_STORE_ID || 1000016), - receivingId: Number(process.env.WEBHOOK_DEBUG_RECEIVING_ID || 202604050001), - receivingNumber: process.env.WEBHOOK_DEBUG_RECEIVING_NUMBER || 'SIM202604050001', - fileResourceUrl: process.env.WEBHOOK_DEBUG_REPORT_URL || DEFAULT_FILE_URL, - fileName: process.env.WEBHOOK_DEBUG_REPORT_FILE || DEFAULT_FILE_NAME, - timeout: Number(process.env.WEBHOOK_DEBUG_TIMEOUT || 10000), - }; - - for (const arg of argv) { - if (!arg.startsWith('--')) { - continue; - } - - const [rawKey, ...rest] = arg.slice(2).split('='); - const value = rest.join('='); - switch (rawKey) { - case 'url': - options.url = value || options.url; - break; - case 'text-url': - options.textUrl = value || options.textUrl; - break; - case 'file-url': - options.fileUrl = value || options.fileUrl; - break; - case 'mode': - options.mode = value || options.mode; - break; - case 'warehouse-id': - options.warehouseId = Number(value || options.warehouseId); - break; - case 'store-id': - options.storeId = Number(value || options.storeId); - break; - case 'receiving-id': - options.receivingId = Number(value || options.receivingId); - break; - case 'receiving-number': - options.receivingNumber = value || options.receivingNumber; - break; - case 'report-url': - options.fileResourceUrl = value || options.fileResourceUrl; - break; - case 'report-file': - options.fileName = value || options.fileName; - break; - case 'timeout': - options.timeout = Number(value || options.timeout); - break; - case 'help': - options.help = true; - break; - default: - break; - } - } - - if (!options.textUrl) { - options.textUrl = options.url; - } - if (!options.fileUrl) { - options.fileUrl = options.url; - } - - return options; -} - -function printHelp() { - console.log(`用法:\n npm run debug:webhook:receiving -- --url=http://127.0.0.1:7071/notic\n npm run debug:webhook:receiving -- --text-url=http://127.0.0.1:7071/notic --file-url=http://127.0.0.1:7071/notic2\n\n说明:\n - 默认发送两次请求:text + file\n - 默认模拟 warehouseId=100000, storeId=1000016 的收货完成通知\n - 可通过 --mode=text 或 --mode=file 只发送一种\n`); -} - -function buildBasePayload(options) { - return { - traceId: `debug_${Date.now()}_${Math.random().toString(16).slice(2, 8)}`, - event: 'receiving_completed', - businessName: 'receiving', - warehouseId: Number(options.warehouseId), - storeId: Number(options.storeId), - businessId: Number(options.receivingId), - occurredAt: new Date().toISOString(), - subject: { - id: Number(options.warehouseId), - type: 'warehouse', - name: `测试仓${options.warehouseId}`, - code: '', - config: { - max_notice_webhook_count: 5, - }, - }, - store: { - id: Number(options.storeId), - name: `测试货主${options.storeId}`, - businessLicense: `BL-${options.storeId}`, - storeRemask: `货主${options.storeId}备注`, - }, - sender: { - id: 90001, - name: '调试脚本', - }, - receivers: [], - metadata: { - debug: true, - sourceScript: path.basename(__filename), - receivingId: Number(options.receivingId), - receivingNumber: options.receivingNumber, - warehouseId: Number(options.warehouseId), - storeId: Number(options.storeId), - stats: { - total_details: 10, - matched_details: 10, - unmatched_details: 0, - total_quantity: 120, - }, - completionReport: null, - }, - }; -} - -function buildTextPayload(options) { - const payload = buildBasePayload(options); - const title = `收货单${options.receivingNumber}已完成`; - const content = `收货单${options.receivingNumber}已完成,匹配商品10件,未匹配商品0件,总数量120,完成人调试脚本。`; - payload.message = { - type: 'text', - title, - content, - url: '', - fileName: '', - mimeType: '', - body: content, - }; - return payload; -} - -function buildFilePayload(options) { - const payload = buildBasePayload(options); - const title = `收货单${options.receivingNumber}已完成`; - const content = `收货单${options.receivingNumber}已完成,匹配商品10件,未匹配商品0件,总数量120,完成人调试脚本。`; - payload.message = { - type: 'file', - title, - content, - url: options.fileResourceUrl, - fileName: options.fileName, - mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - body: content, - }; - payload.metadata.completionReport = { - fileKey: options.fileName, - url: options.fileResourceUrl, - }; - return payload; -} - -async function postJson(url, data, timeout) { - const response = await urllib.request(url, { - method: 'POST', - headers: { - 'content-type': 'application/json', - }, - data: JSON.stringify(data), - timeout: Number(timeout) || 10000, - dataType: 'text', - }); - - return { - status: response.status, - body: String(response.data || ''), - }; -} - -async function main() { - const options = parseArgs(process.argv.slice(2)); - if (options.help) { - printHelp(); - return; - } - - if (!options.textUrl && !options.fileUrl) { - throw new Error('请通过 --url 或 --text-url/--file-url 指定接收端地址'); - } - - const tasks = []; - if ([ 'both', 'text' ].includes(options.mode) && options.textUrl) { - tasks.push({ - label: 'text', - url: options.textUrl, - payload: buildTextPayload(options), - }); - } - if ([ 'both', 'file' ].includes(options.mode) && options.fileUrl) { - tasks.push({ - label: 'file', - url: options.fileUrl, - payload: buildFilePayload(options), - }); - } - - if (tasks.length === 0) { - throw new Error(`mode=${options.mode} 下没有可发送的 webhook 请求`); - } - - const results = []; - for (const task of tasks) { - console.log(`\n[send] ${task.label.toUpperCase()} -> ${task.url}`); - const response = await postJson(task.url, task.payload, options.timeout); - console.log(`[response] status=${response.status} body=${response.body}`); - results.push({ - label: task.label, - url: task.url, - status: response.status, - body: response.body, - traceId: task.payload.traceId, - event: task.payload.event, - }); - } - - const failedCount = results.filter(item => Number(item.status) < 200 || Number(item.status) >= 300).length; - console.log('\n[summary]'); - console.log(JSON.stringify({ - options: { - ...options, - timeout: Number(options.timeout), - }, - results, - failedCount, - }, null, 2)); - - if (failedCount > 0) { - process.exitCode = 1; - } -} - -main().catch(error => { - console.error('[debug-send-receiving-webhooks] failed:', error.message); - process.exit(1); -}); \ No newline at end of file diff --git a/script/debug-warehouse-push-receiver.cjs b/script/debug-warehouse-push-receiver.cjs deleted file mode 100644 index 10ae413..0000000 --- a/script/debug-warehouse-push-receiver.cjs +++ /dev/null @@ -1,206 +0,0 @@ -'use strict'; - -/** - * 仓库接口消息推送 — 本地调试接收服务。 - * 模拟外部适配器:接收 WMS 出站推送(notify.reply / notify.event 等), - * 打印完整回信(query 签名参数 + headers + body)到控制台与日志文件,方便调试。 - * - * 默认配置匹配线上仓库「仓库管理系统oms」: - * app_key=APP2025011514315678 - * app_secret=sec_xyz789uvw012abc345def678ghi901jkl234mno567pqr890 - * callback_url=http://localhost:6061/push - * - * 用法: - * npm run debug:warehouse:push-receiver - * node script/debug-warehouse-push-receiver.cjs --port=6061 --path=/push --log-file=run/push.log - * node script/debug-warehouse-push-receiver.cjs --no-verify # 跳过 MD5 验签 - */ - -const http = require('node:http'); -const fs = require('node:fs'); -const path = require('node:path'); -const crypto = require('node:crypto'); -const { URL } = require('node:url'); - -const DEFAULT_HOST = '127.0.0.1'; -const DEFAULT_PORT = 6061; -const DEFAULT_PATH = '/push'; -const DEFAULT_APP_KEY = 'APP2025011514315678'; -const DEFAULT_APP_SECRET = 'sec_xyz789uvw012abc345def678ghi901jkl234mno567pqr890'; -const DEFAULT_LOG_FILE = path.join(process.cwd(), 'run', 'warehouse-push-receiver.log'); - -function parseArgs(argv) { - const options = { - host: process.env.PUSH_RECEIVER_HOST || DEFAULT_HOST, - port: Number(process.env.PUSH_RECEIVER_PORT || DEFAULT_PORT), - path: process.env.PUSH_RECEIVER_PATH || DEFAULT_PATH, - appKey: process.env.PUSH_RECEIVER_APP_KEY || DEFAULT_APP_KEY, - appSecret: process.env.PUSH_RECEIVER_APP_SECRET || DEFAULT_APP_SECRET, - logFile: process.env.PUSH_RECEIVER_LOG_FILE || DEFAULT_LOG_FILE, - verifySign: ![ '0', 'false' ].includes(String(process.env.PUSH_RECEIVER_VERIFY_SIGN || '1').toLowerCase()), - help: false, - }; - - for (const arg of argv) { - if (!arg.startsWith('--')) { - continue; - } - - const [ rawKey, ...rest ] = arg.slice(2).split('='); - const value = rest.join('='); - switch (rawKey) { - case 'host': - options.host = value || options.host; - break; - case 'port': - options.port = Number(value || options.port); - break; - case 'path': - options.path = value.startsWith('/') ? value : `/${value}`; - break; - case 'app-key': - options.appKey = value || options.appKey; - break; - case 'app-secret': - options.appSecret = value || options.appSecret; - break; - case 'log-file': - options.logFile = value || options.logFile; - break; - case 'no-verify': - options.verifySign = false; - break; - case 'help': - options.help = true; - break; - default: - break; - } - } - - return options; -} - -function printHelp() { - console.log(`用法: - npm run debug:warehouse:push-receiver - node script/debug-warehouse-push-receiver.cjs --port=6061 --path=/push --log-file=run/push.log - node script/debug-warehouse-push-receiver.cjs --no-verify - -参数: - --host=127.0.0.1 监听地址 - --port=6061 监听端口 - --path=/push 接收路径 - --app-key=... 期望的 app_key(仅用于展示) - --app-secret=... 验签密钥(MD5(appSecret + timestamp + bodyJson)) - --log-file=... 日志文件(默认 run/warehouse-push-receiver.log) - --no-verify 跳过 MD5 验签 - -环境变量: - PUSH_RECEIVER_HOST / PUSH_RECEIVER_PORT / PUSH_RECEIVER_PATH - PUSH_RECEIVER_APP_KEY / PUSH_RECEIVER_APP_SECRET / PUSH_RECEIVER_LOG_FILE - PUSH_RECEIVER_VERIFY_SIGN=0 关闭验签`); -} - -function readRequestBody(req) { - return new Promise((resolve, reject) => { - const chunks = []; - req.on('data', chunk => chunks.push(chunk)); - req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8'))); - req.on('error', reject); - }); -} - -function writeLog(logFile, text) { - const line = text.endsWith('\n') ? text : text + '\n'; - try { - fs.appendFileSync(logFile, line, 'utf8'); - console.log(`[push-receiver] 已写入日志文件: ${logFile}`); - } catch (error) { - console.error('[push-receiver] 写日志文件失败:', error.message); - } -} - -function md5(value) { - return crypto.createHash('md5').update(value).digest('hex'); -} - -async function start() { - const options = parseArgs(process.argv.slice(2)); - if (options.help) { - printHelp(); - return; - } - - const logFile = path.resolve(options.logFile); - const logDir = path.dirname(logFile); - fs.mkdirSync(logDir, { recursive: true }); - - const server = http.createServer(async (req, res) => { - const url = new URL(req.url, `http://${req.headers.host || `${options.host}:${options.port}`}`); - const startedAt = new Date().toISOString(); - const rawBody = await readRequestBody(req); - const query = Object.fromEntries(url.searchParams.entries()); - - if (url.pathname === '/health') { - res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' }); - res.end(JSON.stringify({ ok: true, service: 'warehouse-push-receiver' })); - return; - } - - if (req.method !== 'POST' || url.pathname !== options.path) { - res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' }); - res.end(`404 Not Found(接收路径为 ${options.path})`); - return; - } - - // MD5 验签:sign = MD5(appSecret + timestamp + bodyJson) - const timestamp = String(query.timestamp || ''); - const providedSign = String(query.sign || ''); - const expectedSign = options.appSecret ? md5(options.appSecret + timestamp + rawBody) : ''; - const signOk = !options.verifySign || (timestamp && providedSign === expectedSign); - - let parsedBody = rawBody; - try { - parsedBody = rawBody ? JSON.parse(rawBody) : null; - } catch (_) { - // keep raw text - } - - const logText = [ - '================ 收到仓库接口推送 ================', - `[time] ${startedAt}`, - `[route] POST ${url.pathname}`, - `[query] ${JSON.stringify(query, null, 2)}`, - options.verifySign - ? `[sign] ${signOk ? '验签通过' : `验签失败(期望 ${expectedSign})`}` - : '[sign] 已关闭验签', - `[header] ${JSON.stringify(req.headers, null, 2)}`, - `[body] ${JSON.stringify(parsedBody, null, 2)}`, - '==================================================', - ].join('\n'); - - console.log('\n' + logText); - writeLog(logFile, `${logText}\n`); - - // 始终返回 HTTP 200 + code=200,便于 WMS 判定推送成功 - const responseBody = JSON.stringify({ code: 200, message: 'ok', received_at: startedAt }); - res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' }); - res.end(responseBody); - }); - - server.listen(options.port, options.host, () => { - console.log('[warehouse-push-receiver] listening on http://' + options.host + ':' + options.port + options.path); - console.log(`[warehouse-push-receiver] app_key=${options.appKey}`); - console.log(`[warehouse-push-receiver] app_secret=${options.appSecret ? options.appSecret.slice(0, 8) + '…' : '(空)'}`); - console.log(`[warehouse-push-receiver] 验签=${options.verifySign ? '开启' : '关闭'}`); - console.log(`[warehouse-push-receiver] 日志文件=${logFile}`); - console.log(`[warehouse-push-receiver] 健康检查: GET http://${options.host}:${options.port}/health`); - console.log('[warehouse-push-receiver] 按 Ctrl+C 停止'); - }); -} - -start().catch(error => { - console.error('[warehouse-push-receiver] failed:', error); - process.exit(1); -}); diff --git a/script/debug-webhook-receiver.cjs b/script/debug-webhook-receiver.cjs deleted file mode 100644 index bce6436..0000000 --- a/script/debug-webhook-receiver.cjs +++ /dev/null @@ -1,134 +0,0 @@ -'use strict'; - -const http = require('node:http'); -const { URL } = require('node:url'); - -function parseArgs(argv) { - const options = { - host: process.env.WEBHOOK_DEBUG_HOST || '127.0.0.1', - port: Number(process.env.WEBHOOK_DEBUG_PORT || 7071), - defaultResponse: process.env.WEBHOOK_DEBUG_RESPONSE || '1', - noticResponse: process.env.WEBHOOK_DEBUG_NOTIC_RESPONSE || '', - notic2Response: process.env.WEBHOOK_DEBUG_NOTIC2_RESPONSE || '', - }; - - for (const arg of argv) { - if (!arg.startsWith('--')) { - continue; - } - const [rawKey, ...rest] = arg.slice(2).split('='); - const value = rest.join('='); - switch (rawKey) { - case 'host': - options.host = value || options.host; - break; - case 'port': - options.port = Number(value || options.port); - break; - case 'response': - options.defaultResponse = value || options.defaultResponse; - break; - case 'notic-response': - options.noticResponse = value || options.noticResponse; - break; - case 'notic2-response': - options.notic2Response = value || options.notic2Response; - break; - case 'help': - options.help = true; - break; - default: - break; - } - } - - return options; -} - -function printHelp() { - console.log(`用法:\n npm run debug:webhook:receiver\n npm run debug:webhook:receiver -- --port=7071 --notic-response=1 --notic2-response=0\n\n环境变量:\n WEBHOOK_DEBUG_PORT=7071\n WEBHOOK_DEBUG_RESPONSE=1\n WEBHOOK_DEBUG_NOTIC_RESPONSE=1\n WEBHOOK_DEBUG_NOTIC2_RESPONSE=0\n`); -} - -function readRequestBody(req) { - return new Promise((resolve, reject) => { - const chunks = []; - req.on('data', chunk => chunks.push(chunk)); - req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8'))); - req.on('error', reject); - }); -} - -function buildResponseBody(pathname, options) { - if (pathname === '/notic2' && options.notic2Response) { - return options.notic2Response; - } - if (pathname === '/notic' && options.noticResponse) { - return options.noticResponse; - } - return options.defaultResponse; -} - -async function start() { - const options = parseArgs(process.argv.slice(2)); - if (options.help) { - printHelp(); - return; - } - - const server = http.createServer(async (req, res) => { - const url = new URL(req.url, `http://${req.headers.host || `${options.host}:${options.port}`}`); - const startedAt = new Date().toISOString(); - const rawBody = await readRequestBody(req); - let parsedBody = rawBody; - - try { - parsedBody = rawBody ? JSON.parse(rawBody) : null; - } catch (_) { - // keep raw text - } - - console.log('\n================ WEBHOOK DEBUG RECEIVER ================'); - console.log(`[time] ${startedAt}`); - console.log(`[route] ${req.method} ${url.pathname}`); - console.log('[query] ', Object.fromEntries(url.searchParams.entries())); - console.log('[header]', req.headers); - console.log('[body] ', JSON.stringify(parsedBody, null, 2)); - - if (![ '/notic', '/notic2', '/health' ].includes(url.pathname)) { - res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' }); - res.end('404 Not Found'); - return; - } - - if (url.pathname === '/health') { - res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' }); - res.end(JSON.stringify({ ok: true, service: 'webhook-debug-receiver' })); - return; - } - - const responseBody = buildResponseBody(url.pathname, options); - const statusCode = String(responseBody).startsWith('{') || String(responseBody).startsWith('[') ? 200 : 200; - const contentType = String(responseBody).startsWith('{') || String(responseBody).startsWith('[') - ? 'application/json; charset=utf-8' - : 'text/plain; charset=utf-8'; - - res.writeHead(statusCode, { 'content-type': contentType }); - res.end(responseBody); - - console.log(`[reply] ${url.pathname} -> ${responseBody}`); - console.log('========================================================\n'); - }); - - server.listen(options.port, options.host, () => { - console.log(`[webhook-debug-receiver] listening on http://${options.host}:${options.port}`); - console.log(`[webhook-debug-receiver] endpoints:`); - console.log(` - POST http://${options.host}:${options.port}/notic`); - console.log(` - POST http://${options.host}:${options.port}/notic2`); - console.log(` - GET http://${options.host}:${options.port}/health`); - }); -} - -start().catch(error => { - console.error('[webhook-debug-receiver] failed:', error); - process.exit(1); -}); \ No newline at end of file From fd565fda7b82ad695009ffe43d96b13f5b68d21d Mon Sep 17 00:00:00 2001 From: liufumingren Date: Thu, 27 Aug 2026 23:41:43 +0800 Subject: [PATCH 283/550] =?UTF-8?q?feat(inbox):=20=E8=A7=84=E5=88=99?= =?UTF-8?q?=E5=BC=95=E6=93=8E=E6=88=90=E4=B8=BA=E4=B8=BB=E5=9B=9E=E5=A4=8D?= =?UTF-8?q?=E8=B7=AF=E5=BE=84=EF=BC=8C=E9=80=80=E5=9B=9E=E6=94=B6=E4=BB=B6?= =?UTF-8?q?=E7=99=BB=E8=AE=B0=E6=8C=89=E4=BB=93=E5=BA=93+=E8=B4=A7?= =?UTF-8?q?=E4=B8=BB=E8=81=9A=E5=90=88=E9=80=9A=E7=9F=A5=E8=B4=A7=E4=B8=BB?= =?UTF-8?q?=E7=BE=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/model/return_received.js | 6 + app/schedule/notify_return_received.js | 40 ++ app/service/inbox/ai.js | 2 +- app/service/inbox/functions.js | 189 ++++--- app/service/inbox/groups.js | 4 +- app/service/inbox/processor.js | 92 +++- app/service/inbox/rules.js | 466 ++++++++++++++++++ app/service/inbox/tools.js | 51 ++ app/service/systems/return_received.js | 151 ++++++ app/service/systems/return_unpack.js | 188 ++++++- config/config.default.js | 4 + ...-add-is-notified-to-wms-return-received.js | 29 ++ 12 files changed, 1071 insertions(+), 151 deletions(-) create mode 100644 app/schedule/notify_return_received.js create mode 100644 app/service/inbox/rules.js create mode 100644 app/service/inbox/tools.js create mode 100644 database/migrations/20260827170000-add-is-notified-to-wms-return-received.js diff --git a/app/model/return_received.js b/app/model/return_received.js index 40cc62a..2201fd5 100644 --- a/app/model/return_received.js +++ b/app/model/return_received.js @@ -60,6 +60,12 @@ module.exports = app => { allowNull: true, comment: '备注', }, + is_notified: { + type: app.Sequelize.TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '登记是否已通知货主群:0=未通知,1=已通知', + }, }, { tableName: 'wms_return_received', comment: '退回收到登记表', diff --git a/app/schedule/notify_return_received.js b/app/schedule/notify_return_received.js new file mode 100644 index 0000000..1a8be53 --- /dev/null +++ b/app/schedule/notify_return_received.js @@ -0,0 +1,40 @@ +'use strict'; + +/** + * 退回收件登记聚合通知定时任务。 + * 每分钟在单 worker 中扫描一次:对"登记时间超过防抖窗口(默认 5 分钟)且未通知"的登记, + * 只对货主查退回时登记过的运单,按 仓库+货主 聚合推送到货主售后群,并标记 is_notified=1。 + */ +module.exports = { + schedule: { + interval: '1m', + type: 'worker', + immediate: false, + disable: false, + }, + + /** + * 执行退回收件登记聚合通知。 + * + * @param {Object} ctx Egg 上下文。 + * @return {Promise} 无返回值。 + */ + async task(ctx) { + if (ctx.app._returnReceivedNotifyRunning) { + return; + } + + ctx.app._returnReceivedNotifyRunning = true; + + try { + const result = await ctx.service.systems.returnReceived.notifyPending(); + ctx.logger.info( + `[notify-return-received] 聚合通知完成 notified=${result && result.notified || 0} skipped=${result && result.skipped || 0}` + ); + } catch (error) { + ctx.logger.error(`[notify-return-received] 任务执行失败: ${error.message}`); + } finally { + ctx.app._returnReceivedNotifyRunning = false; + } + }, +}; diff --git a/app/service/inbox/ai.js b/app/service/inbox/ai.js index a7317db..834e971 100644 --- a/app/service/inbox/ai.js +++ b/app/service/inbox/ai.js @@ -270,7 +270,7 @@ ${historyContext} - 【规则 - handleStoreFeedback】货主售后群中客户反馈"错发/发错""破损/坏了""多发/发多""少发/漏发"且提供了运单号时,调用 handleStoreFeedback 创建售后工单(初始状态未开始处理,不通知快递群);若消息中无运单号,先向客户确认运单号再调用 - 【规则 - handleExpressFeedback】快递售后群中,快递客服反馈处理进度/结果(如"已通知网点""网点正在处理""已拦截""已联系收件人""改地址失败/无法改""已签收""加急处理"等)且消息含运单号时,必须调用 handleExpressFeedback(keyword=运单号,多个用逗号分隔)。该函数会自动查找已有售后工单追加反馈并回信到相关群,无工单则自动创建。严禁把快递客服的进度/结果反馈判定为无需处理而 silent;若消息无运单号,先用 recallHistory 或询问确认运单号,严禁跳过 - 【规则 - handleExpressFeedback 证据核实】快递售后群中快递方发消息要求"提供交易记录截图/未收到依据/核实签收/带日期单号"等证据类诉求且消息含运单号时,同样必须调用 handleExpressFeedback(as_sub_type=verify_delivery),由函数创建售后工单并回信到货主售后群;严禁仅回复"收到/已记录"等确认话术而不调用函数 -- 【规则 - changeAddr】货主售后群中客户消息含"改地址/改电话/改联系人/改收件人/地址更改/改手机/催退回/尽快安排派送/催促退回"等诉求且提供了运单号时,调用 changeAddr(issue_type:addr=改地址类诉求,return=催退回类诉求);函数会创建售后工单并把客户原文转发到对应快递群,返回的 data.message 是模板消息必须原样回复;若消息中无运单号,先向客户确认运单号再调用 +- 【规则 - changeAddr】货主售后群中客户消息含"改地址/改电话/改联系人/改收件人/地址更改/改手机/催退回/催促退回/催件/催派送/尽快安排派送"等诉求且提供了运单号时,调用 changeAddr(issue_type:addr=改地址类诉求,return=催退回类诉求,urge=催件/催派送类诉求;注意区分:"催退回/催促退回"用 return,"催件/催派送/尽快安排派送"用 urge,严禁把催件判定为 return);函数会创建售后工单并把客户原文转发到对应快递群,返回的 data.message 是模板消息必须原样回复;若消息中无运单号,先向客户确认运单号再调用 - 【规则 - weishoudao】货主售后群中客户消息含"核实签收/未收到/是否发出/是否已经发货/核实/没有找到快递"等诉求且提供了运单号时,调用 weishoudao 创建核实签收售后工单,并把"运单号+核实签收"转发到对应快递群;返回的 data.message 是模板消息必须原样回复;若消息中无运单号,先向客户确认运单号再调用 - 【规则 - changeExpress】货主售后群中客户要求"改快递/换快递/改圆通/改中通/改顺丰"等且提供了订单号时,调用 changeExpress(keyword=订单号,express=目标快递名称或编码);仅待处理表中未分配快递的订单可以修改,已分配快递或不在待处理表的订单不能修改;返回的 data.message 是模板消息必须原样回复;若消息中缺订单号或目标快递,先向客户确认再调用 - 【规则 - queryPackVideo】用户询问"打包视频/打包录像/装箱视频"且提供了运单号时,调用 queryPackVideo 查询(散单按订单、团购单按波次找打包记录);仅查询不建工单;返回的 data.message 是模板消息必须原样回复;若消息中无运单号,先向客户确认运单号再调用 diff --git a/app/service/inbox/functions.js b/app/service/inbox/functions.js index d616428..42f6f1c 100644 --- a/app/service/inbox/functions.js +++ b/app/service/inbox/functions.js @@ -1513,11 +1513,11 @@ class InboxFunctionsService extends Service { }); this.register('queryReturn', { - description: '查询退回包裹明细(查退回)。用户发送"查退回+运单号"时调用。传入运单号,查询退回收到/退回拆包/未退回登记状态:已拆包返回拆包明细与录像地址模板消息,未退回则自动登记到退回查询表。注意:仅查询退回状态使用,与 interceptWaybill 拦截、queryOrder 订单查询不同', + description: '查询退回包裹明细(查退回)。用户发送"查退回+运单号"时调用,支持多行/多个运单号(换行、逗号、空格分隔),每个单号分别返回一条结果。传入运单号,查询退回收到/退回拆包/未退回登记状态:已拆包返回拆包明细与录像地址模板消息,未退回则自动登记到退回查询表。注意:仅查询退回状态使用,与 interceptWaybill 拦截、queryOrder 订单查询不同', weight: 90, keywords: [ '查退回', '查退件', '退回查询', '退回明细', '查拆包', '退件查询', '退回进度' ], params: { - waybill_code: { type: 'string', required: true, description: '退回包裹运单号,如"查退回 465570943491370"中的465570943491370' }, + waybill_code: { type: 'string', required: true, description: '退回包裹运单号,支持多个(换行/逗号/空格分隔),如"查退回 465570943491370\nSF123456"' }, }, groups: [ GROUP.COMMON ], handler: async (params = {}) => { @@ -1531,71 +1531,91 @@ class InboxFunctionsService extends Service { // 兼容把"查退回 123456"整体传入的情况 const match = raw.match(/查退[回件]\s*[::]?\s*(.+)$/); if (match) raw = String(match[1]).trim(); - // 去掉空白与常见中文标点,保留运单号本体(字母/数字/横线等) - const waybill = raw.replace(/[\s,,。;;]+/g, ''); - if (!waybill) return { success: false, error: '未解析到有效运单号' }; + + // 解析多个单号:换行/逗号/空格/常见中文标点分隔,去重保序 + const waybills = [ ...new Set( + raw.split(/[\s,,。;;]+/) + .map(s => s.trim()) + .filter(Boolean) + ) ]; + if (waybills.length === 0) return { success: false, error: '未解析到有效运单号' }; if (!warehouseId) return { success: false, error: '无法获取仓库信息' }; try { - const result = await ctx.service.systems.returnUnpack.queryByWaybill({ - waybill_code: waybill, - warehouse_id: warehouseId, - store_id: storeId, - }); + const messages = []; + const statuses = []; + for (const waybill of waybills) { + try { + const result = await ctx.service.systems.returnUnpack.queryByWaybill({ + waybill_code: waybill, + warehouse_id: warehouseId, + store_id: storeId, + }); - const warehouseLabel = result.warehouse_name || '仓库'; - let message = ''; + const warehouseLabel = result.warehouse_name || '仓库'; + let message = ''; - if (result.status === 'unpacked') { - const unpack = result.unpack || {}; - const details = result.details || []; - const videos = result.videos || []; - const orderInfo = result.order_info || {}; + if (result.status === 'unpacked') { + const unpack = result.unpack || {}; + const details = result.details || []; + const videos = result.videos || []; + const orderInfo = result.order_info || {}; - const lines = []; - lines.push(`${waybill}已在已退件中登记,登记信息为:`); - lines.push(''); - lines.push(`运单号:${waybill}`); - lines.push(`是否原单:${unpack.order_express_id ? '是' : '否'}`); - lines.push(`交易单号:${orderInfo.trade_no || ''}`); - lines.push(`快递:${orderInfo.express || ''}`); - lines.push(`店铺名称:${orderInfo.shop_name || ''}`); - lines.push(`${warehouseLabel}收到且已拆包,拆包明细为:`); - if (details.length > 0) { - for (const detail of details) { - lines.push(`商品名称:${detail.item_name || ''}`); - lines.push(`条码:${detail.barcode || ''}`); - lines.push(`数量:${detail.quantity || 0}`); - lines.push(`是否破损:${detail.product_status === 'damaged' ? '是' : '否'}`); + const lines = []; + lines.push(`${waybill}已在已退件中登记,登记信息为:`); + lines.push(''); + lines.push(`运单号:${waybill}`); + lines.push(`是否原单:${unpack.order_express_id ? '是' : '否'}`); + lines.push(`交易单号:${orderInfo.trade_no || ''}`); + lines.push(`快递:${orderInfo.express || ''}`); + lines.push(`店铺名称:${orderInfo.shop_name || ''}`); + lines.push(`${warehouseLabel}收到且已拆包,拆包明细为:`); + if (details.length > 0) { + for (const detail of details) { + lines.push(`商品名称:${detail.item_name || ''}`); + lines.push(`条码:${detail.barcode || ''}`); + lines.push(`数量:${detail.quantity || 0}`); + lines.push(`是否破损:${detail.product_status === 'damaged' ? '是' : '否'}`); + } + } else { + lines.push('暂无拆包明细,拆包完成后可再次查询'); + } + lines.push(''); + lines.push('退件录像地址为:'); + if (videos.length > 0) { + for (const video of videos) { + if (video.video_url) lines.push(String(video.video_url)); + } + } else { + lines.push('暂无'); + } + lines.push('拆包视频保存会有延迟,可以在稍后发送:查退回+运单号,查询'); + message = lines.join('\n'); + } else if (result.status === 'received') { + message = `包裹${waybill}已收到未拆包,拆包登记后,将自动发送通知拆包信息`; + } else if (result.status === 'not_returned') { + message = `${waybill}尚未退回仓库,已在未退回表中登记成功,等待包裹退件登记后,将自动发送通知包裹信息`; + } else { + message = `未查询到运单号${waybill}的退回信息,请核实单号后重试`; } - } else { - lines.push('暂无拆包明细,拆包完成后可再次查询'); + + messages.push(message); + statuses.push(result.status); + } catch (error) { + ctx.logger.warn(`[inbox functions] 退回查询单号失败 ${waybill}: ${error.message}`); + messages.push(`${waybill}退回查询失败:${error.message}`); + statuses.push('error'); } - lines.push(''); - lines.push('退件录像地址为:'); - if (videos.length > 0) { - for (const video of videos) { - if (video.video_url) lines.push(String(video.video_url)); - } - } else { - lines.push('暂无'); - } - lines.push('拆包视频保存会有延迟,可以在稍后发送:查退回+运单号,查询'); - message = lines.join('\n'); - } else if (result.status === 'received') { - message = `包裹${waybill}已收到未拆包,拆包登记后,将自动发送通知拆包信息`; - } else if (result.status === 'not_returned') { - message = `${waybill}尚未退回仓库,已在未退回表中登记成功,等待包裹退件登记后,将自动发送通知包裹信息`; - } else { - message = `未查询到运单号${waybill}的退回信息,请核实单号后重试`; } return { success: true, data: { - status: result.status, - waybill_code: waybill, - message, + status: statuses[0], + waybill_code: waybills[0], + total: waybills.length, + message: messages[0], // 兼容单条回复(AI 兜底路径取首条) + messages, // 规则引擎多行回复:每个单号一条消息 direct_reply: true, }, }; @@ -2079,12 +2099,12 @@ class InboxFunctionsService extends Service { }); this.register('changeAddr', { - description: '货主售后群改地址/催退回处理。客户消息含"改地址/改电话/改联系人/改收件人/地址更改/改手机/催退回/尽快安排派送/催促退回"等诉求且提供了运单号时调用:创建售后工单(改地址/催退回),并将客户原文转发到对应快递的售后群通知快递处理', + description: '货主售后群改地址/催退回/催件处理。客户消息含"改地址/改电话/改联系人/改收件人/地址更改/改手机/催退回/催促退回/催件/催派送/尽快安排派送"等诉求且提供了运单号时调用:创建售后工单(改地址/催退回/催件),并将客户原文转发到对应快递的售后群通知快递处理', weight: 89, - keywords: [ '改地址', '改电话', '改联系人', '改收件人', '地址更改', '改手机', '催退回', '尽快安排派送', '催促退回' ], + keywords: [ '改地址', '改电话', '改联系人', '改收件人', '地址更改', '改手机', '催退回', '催促退回', '催件', '催派送', '尽快安排派送' ], params: { keyword: { type: 'string', required: true, description: '运单号,多个用逗号或空格分隔,如 SF111,SF222' }, - issue_type: { type: 'string', required: true, description: '诉求类型:addr(改地址类诉求)/return(催退回类诉求)' }, + issue_type: { type: 'string', required: true, description: '诉求类型:addr(改地址类诉求)/return(催退回类诉求)/urge(催件/催派送类诉求),注意区分:催退回用 return,催件/催派送用 urge' }, }, groups: [ GROUP.BOUND_STORE_AFTER_SALES ], handler: async (params = {}) => { @@ -2106,6 +2126,8 @@ class InboxFunctionsService extends Service { 改地址: { sub_type: 'change_address', label: '改地址' }, return: { sub_type: 'rejected', label: '催退回' }, 催退回: { sub_type: 'rejected', label: '催退回' }, + urge: { sub_type: 'urge', label: '催件' }, + 催件: { sub_type: 'urge', label: '催件' }, }; const issue = ISSUE_TYPE_MAP[issueTypeRaw] || ISSUE_TYPE_MAP.addr; @@ -2278,11 +2300,14 @@ class InboxFunctionsService extends Service { } // 第六步:客户回信模板(单号+诉求,区分是否已通知快递) + // key 必须与 issue.sub_type 对齐(change_address/rejected/urge), + // 此前误用 addr/return 导致永远回退到改地址文案 const REPLY_TEXT = { - addr: { done: '修改地址已经登记', notify: '并已通知快递修改' }, - return: { done: '催退回已经登记', notify: '并已通知快递处理' }, + change_address: { done: '修改地址已经登记', notify: '并已通知快递修改' }, + rejected: { done: '催退回已经登记', notify: '并已通知快递处理' }, + urge: { done: '催件已经登记', notify: '并已通知快递处理' }, }; - const replyText = REPLY_TEXT[issue.sub_type] || REPLY_TEXT.addr; + const replyText = REPLY_TEXT[issue.sub_type] || REPLY_TEXT.change_address; const lines = expressList.map(e => { const head = `运单${e.waybill_code}${replyText.done}`; return notifiedWaybillIds.has(e.id) @@ -3171,10 +3196,11 @@ class InboxFunctionsService extends Service { raw: true, }); // 视频地址拼接 CDN 域名(与 order.packing.list、queryReturn 对齐) - const recordingComputerId = await this._getRecordingComputerId(warehouseId); + const inboxTools = ctx.service.inbox.tools; + const recordingComputerId = await inboxTools.getRecordingComputerId(warehouseId); const urls = videos .filter(v => String(v.status || '') !== 'failed') - .map(v => this._buildVideoUrl(warehouseId, recordingComputerId, v.video_url)) + .map(v => inboxTools.buildVideoUrl(warehouseId, recordingComputerId, v.video_url)) .filter(Boolean); if (urls.length === 0) { @@ -3924,45 +3950,6 @@ class InboxFunctionsService extends Service { }; } } - - /** - * 获取仓库的录制电脑 ID(带缓存)。 - * @param {number} warehouseId 仓库ID - * @return {Promise} 录制电脑ID,找不到返回 null - */ - async _getRecordingComputerId(warehouseId) { - const cacheKey = `_recordingComputer_${warehouseId}`; - if (this[cacheKey] !== undefined) { - return this[cacheKey]; - } - const row = await this.ctx.model.PrintComputer.findOne({ - where: { warehouse_id: warehouseId, is_recording: true, deleted_at: null }, - attributes: [ 'id' ], - raw: true, - }); - this[cacheKey] = row ? row.id : null; - return this[cacheKey]; - } - - /** - * 构建视频完整 URL。 - * 格式:http://w{warehouseId}-c{recordingComputerId}.o.gztbyc.com{videoPath} - * @param {number} warehouseId 仓库ID - * @param {number|null} recordingComputerId 录制电脑ID - * @param {string} videoPath 视频路径 - * @return {string} 完整 URL - */ - _buildVideoUrl(warehouseId, recordingComputerId, videoPath) { - const path = String(videoPath || '').trim(); - if (!path || !recordingComputerId) { - return path; - } - // 已是完整 URL 时原样返回,避免重复拼接 - if (/^https?:\/\//i.test(path)) { - return path; - } - return `http://w${warehouseId}-c${recordingComputerId}.o.gztbyc.com${path}`; - } } module.exports = InboxFunctionsService; diff --git a/app/service/inbox/groups.js b/app/service/inbox/groups.js index f68b811..acfa82b 100644 --- a/app/service/inbox/groups.js +++ b/app/service/inbox/groups.js @@ -139,7 +139,9 @@ class InboxGroupsService extends Service { const storeId = Number(ctx.inboxContext?.store_id || 0); const gtDef = GROUP_TYPES.find(gt => gt.type === groupType); - if (gtDef && (groupType === 'express' || storeId > 0)) { + // warehouse/express 群不绑定货主(store_id 允许为空),无条件激活主分组; + // store 群必须有货主归属(storeId > 0)才激活,防止未绑定货主的群越权调用函数。 + if (gtDef && (groupType === 'express' || groupType === 'warehouse' || storeId > 0)) { groups.push(gtDef.mainGroup); const subMap = VALID_SUB_TYPES[groupType]; if (subMap && subMap[subType]) { diff --git a/app/service/inbox/processor.js b/app/service/inbox/processor.js index 7e17f10..0458ec9 100644 --- a/app/service/inbox/processor.js +++ b/app/service/inbox/processor.js @@ -14,17 +14,11 @@ const DEFAULT_HISTORY_MESSAGE_MAX_AGE_MS = 10 * 60 * 1000; */ class InboxProcessorService extends Service { - constructor(ctx) { - super(ctx); - /** - * 群信息缓存(groupId:warehouseId → { group_type, sub_type, ai_enabled, ext_data })。 - * 生命周期跟随进程,写回 ext_data 时清除对应条目。 - */ - this._groupCache = new Map(); - } - /** - * 从缓存或 DB 拉取群信息。若群 ext_data 为空且消息携带 ext_data,自动写回并清缓存。 + * 从数据库拉取群信息(不缓存)。 + * Egg Service 按请求实例化,进程内缓存无法跨请求共享, + * 直接查库可保证 inbox.group.update/reset 修改群配置后下一条消息立即生效。 + * 若群 ext_data 为空且消息携带 ext_data,自动写回群配置。 * @param {string} groupId 外部群ID * @param {number} warehouseId 仓库ID * @param {Object|null} msgExtData 入站消息的 ext_data @@ -32,11 +26,6 @@ class InboxProcessorService extends Service { */ async _loadGroupInfo(groupId, warehouseId, msgExtData) { const { ctx } = this; - const cacheKey = `${groupId}:${warehouseId}`; - - // 命中缓存直接返回 - const cached = this._groupCache.get(cacheKey); - if (cached) return cached; let group = null; try { @@ -72,8 +61,6 @@ class InboxProcessorService extends Service { } } - // 写入缓存 - this._groupCache.set(cacheKey, info); return info; } @@ -246,7 +233,70 @@ class InboxProcessorService extends Service { // 5.2 注入入站消息ID,供下游函数(如 interceptWaybill)关联工单 ctx.inboxContext.inbound_message_id = parentId || null; - // 6. DeepSeek 两步交互(AI 内部自行判断真人接管) + // 6. 关键词规则引擎(主回复路径,不走 AI,节省推理费用) + const ruleResult = await ctx.service.inbox.rules.handle(String(data.content || '').trim()); + if (ruleResult.handled) { + // 记录规则命中轨迹到入站消息,便于排查 + if (ruleResult.thoughts && ruleResult.thoughts.length > 0) { + try { + await InboxMessage.update( + { ai_thoughts: ruleResult.thoughts }, + { where: { ext_id: extId } } + ); + } catch (e) { + ctx.logger.warn(`[inbox processor] 保存规则处理记录失败: ${e.message}`); + } + } + + if (ruleResult.silent) { + ctx.logger.info(`[inbox processor] 规则静默(无需回复) ext_id=${extId}`); + return; + } + + if (ruleResult.reply) { + // 支持多条回复(如查退回多单号):逐条独立回信 + const replies = Array.isArray(ruleResult.reply) ? ruleResult.reply : [ ruleResult.reply ]; + ctx.logger.info( + `[inbox processor] 规则引擎处理完成 ext_id=${extId} ` + + `fn=${ruleResult.fn || '-'} key=${ruleResult.matchedKey || '-'} replies=${replies.length}` + ); + // 快递群:仅执行函数,不回信 + if (groupType === 'express') { + ctx.logger.info(`[inbox processor] 快递群规则处理完成(不回信) ext_id=${extId}`); + return; + } + for (let idx = 0; idx < replies.length; idx++) { + const replyContent = replies[idx]; + // 多条回复时每条独立 ext_id,避免回执唯一键冲突 + const replyExtId = replies.length > 1 ? `${extId}:r${idx}` : extId; + await this.writeOutboundReply({ + warehouse_id: warehouseId, + ext_id: replyExtId, + parent_id: parentId, + ext_data: data.ext_data || null, + group_id: ctx.inboxContext?.group_id || data.group_id || null, + user_id: ctx.inboxContext?.user_id || data.user_id || null, + group_name: ctx.inboxContext?.group_name || data.group_name || null, + user_name: ctx.inboxContext?.user_name || data.user_name || null, + }, replyContent, 'rule_reply'); + } + } else { + ctx.logger.info(`[inbox processor] 规则已执行但无回复内容 ext_id=${extId} fn=${ruleResult.fn || '-'}`); + } + return; + } + + // 6.5 AI 兜底(默认关闭,config.inbox.aiFallback=true 时启用) + const aiFallback = !!(this.app.config.inbox && this.app.config.inbox.aiFallback); + if (!aiFallback) { + ctx.logger.info( + `[inbox processor] 规则未命中且AI兜底关闭,静默 ext_id=${extId} ` + + `content=${String(data.content || '').slice(0, 80)}` + ); + return; + } + + // 7. DeepSeek 两步交互(AI 兜底,内部自行判断真人接管) const aiResult = await ctx.service.inbox.ai.processWithAI({ content: data.content || '', ext_data: data.ext_data || null, @@ -277,7 +327,7 @@ class InboxProcessorService extends Service { `function=${aiResult.functionName || 'direct'} reply_length=${replyContent.length}` ); - // 7. AI 推理写入入站消息(便于排查) + // 7.1 AI 推理写入入站消息(便于排查) if (aiResult.thoughts && aiResult.thoughts.length > 0) { try { await InboxMessage.update( @@ -289,13 +339,13 @@ class InboxProcessorService extends Service { } } - // 8. 快递群:仅执行函数,不回信 + // 8. 快递群:仅执行函数,不回信(AI 兜底分支) if (groupType === 'express') { ctx.logger.info(`[inbox processor] 快递群AI处理完成(不回信) ext_id=${extId}`); return; } - // 9. 统一回信 + // 9. 统一回信(AI 兜底分支) await this.writeOutboundReply({ warehouse_id: warehouseId, ext_id: extId, diff --git a/app/service/inbox/rules.js b/app/service/inbox/rules.js new file mode 100644 index 0000000..e812236 --- /dev/null +++ b/app/service/inbox/rules.js @@ -0,0 +1,466 @@ +'use strict'; + +/* eslint-disable no-use-before-define */ +/* 规则表/常量按“配置在后、逻辑在前”组织,类方法通过函数声明提升访问,此处禁用声明顺序检查 */ + +const Service = require('egg').Service; + +/** + * 站内信关键词规则引擎(主回复路径,替代 AI 推理)。 + * + * 设计参考 PHP Chat.php 的规则表结构: + * - 按群类型(store/warehouse/express)维护规则表,顺序即优先级,先命中先执行; + * - 每条规则:关键词数组 → inbox 函数,命中后从消息中提取运单号/订单号直接调用函数; + * - 函数返回的模板消息(direct_reply/message)原样回信; + * - 确认/感谢类短消息、未命中消息默认静默,不触发 AI,节省推理费用; + * - AI 仅在 config.inbox.aiFallback=true 时作为兜底。 + */ +class InboxRulesService extends Service { + + /** + * 规则引擎主入口:关键词匹配 + 参数提取 + 函数调用。 + * + * @param {string} content 消息正文。 + * @return {Promise} 处理结果: + * - { handled: false }:未命中任何规则(由调用方决定是否 AI 兜底/静默)。 + * - { handled: true, silent: true }:命中静默规则,不回复。 + * - { handled: true, reply: string, fn, params, result, matchedKey, thoughts }:已执行函数并生成回复。 + */ + async handle(content) { + const { ctx } = this; + const text = String(content || '').trim(); + if (!text) return { handled: false }; + + const groupType = String(ctx.inboxContext?.group_type || '').trim(); + const rules = RULE_TABLES[groupType]; + if (!Array.isArray(rules) || rules.length === 0) { + ctx.logger.info(`[inbox rules] 无规则表 group_type=${groupType || '-'}`); + return { handled: false }; + } + + const groupsSvc = ctx.service.inbox.groups; + const funcSvc = ctx.service.inbox.functions; + const activeGroups = groupsSvc.resolveActiveGroups(); + + // 收集所有命中规则:命中关键词最长者优先(长词优先)。 + // 相反语义的短词(如“拦截”vs“取消拦截”)不再依赖人工排序, + // 长词“取消拦截”天然排在短词“拦截”之前,短词不会吞掉长词语义。 + const candidates = []; + for (const rule of rules) { + if (rule.any) { + candidates.push({ rule, key: 'any', keyLen: Infinity }); + continue; + } + const hitKey = rule.keys.find(k => text.includes(k)); + if (hitKey) candidates.push({ rule, key: hitKey, keyLen: hitKey.length }); + } + // 稳定排序:keyLen 相同保持规则表顺序(先定义者优先) + candidates.sort((a, b) => b.keyLen - a.keyLen); + + for (const cand of candidates) { + const rule = cand.rule; + + // 防误判守卫(如拦截 vs 查询物流) + if (rule.guard && !rule.guard(text)) { + ctx.logger.info(`[inbox rules] 规则 ${rule.fn} 未通过防误判守卫: ${text.slice(0, 50)}`); + continue; + } + + // 内置帮助指令 + if (rule.fn === '__help__') { + const reply = HELP_TEXTS[groupType] || '当前群暂无可用的快捷指令'; + return { + handled: true, reply, fn: '__help__', params: {}, result: null, matchedKey: 'help', + thoughts: [{ round: 0, action: 'rule', function: '__help__', params: {}, reason: '帮助指令命中: help', functionResult: null }], + }; + } + + // 函数可用性校验(复用群分组权限,防止越权调用) + const def = funcSvc.registry.get(rule.fn); + if (!def || !groupsSvc.isFunctionAvailable(def, activeGroups)) { + ctx.logger.info( + `[inbox rules] 函数 ${rule.fn} 当前群不可用,跳过 groups=${def ? def.groups.join(',') : '-'} active=${activeGroups.join(',')}` + ); + continue; + } + + // 参数提取 + const params = {}; + if (rule.waybill) { + const waybills = extractWaybills(text); + if (waybills.length === 0) { + if (rule.noWaybillSilent) { + return { handled: true, silent: true }; + } + return { + handled: true, + reply: rule.tip || '请提供运单号(发送:指令+运单号,多个单号用逗号或空格分隔)', + fn: rule.fn, params: {}, result: null, matchedKey: rule.keys?.[0], + thoughts: [{ round: 0, action: 'rule', function: rule.fn, params: {}, reason: '参数不足-引导提示', functionResult: null }], + }; + } + // 默认参数名 keyword,个别函数(如 queryReturn)用 waybill_code + params[rule.paramName || 'keyword'] = waybills.join(','); + } + if (rule.order) { + const orders = extractOrders(text); + if (orders.length === 0) { + return { + handled: true, + reply: rule.tip || '请提供订单号(发货单号或平台单号)', + fn: rule.fn, params: {}, result: null, matchedKey: rule.keys?.[0], + thoughts: [{ round: 0, action: 'rule', function: rule.fn, params: {}, reason: '参数不足-引导提示', functionResult: null }], + }; + } + params[rule.paramName || 'keyword'] = orders.join(','); + } + if (rule.issueType) params.issue_type = rule.issueType; + if (rule.express) params.express = rule.express; + if (rule.expressSubType) { + const sub = resolveExpressSubType(text); + if (sub) params.as_sub_type = sub; + } + if (rule.expressFromText) { + const expressName = extractExpressName(text); + if (!expressName) { + return { + handled: true, + reply: rule.tip || '请指定目标快递(圆通/中通/申通/顺丰/韵达/极兔/邮政/EMS/京东)', + fn: rule.fn, params: {}, result: null, matchedKey: rule.keys?.[0], + thoughts: [{ round: 0, action: 'rule', function: rule.fn, params: {}, reason: '参数不足-引导提示', functionResult: null }], + }; + } + params.express = expressName; + } + if (rule.stockSearch) { + const kw = stripKeyword(text, rule.keys || []); + if (!kw) { + return { + handled: true, + reply: rule.tip || '请提供商品名称、编码或条码', + fn: rule.fn, params: {}, result: null, matchedKey: rule.keys?.[0], + thoughts: [{ round: 0, action: 'rule', function: rule.fn, params: {}, reason: '参数不足-引导提示', functionResult: null }], + }; + } + params.keyword = kw; + } + + // 执行函数 + const result = await funcSvc.callFunction(rule.fn, params); + const reply = this.buildReply(rule.fn, result); + + const matchedKey = cand.key; + ctx.logger.info( + `[inbox rules] HIT fn=${rule.fn} key=${matchedKey} params=${JSON.stringify(params)} success=${!!result.success}` + ); + + return { + handled: true, + fn: rule.fn, + params, + result, + reply, + matchedKey, + thoughts: [{ + round: 0, + action: 'rule', + function: rule.fn, + params, + reason: `关键词规则命中: ${matchedKey}`, + functionResult: result, + }], + }; + } + + // 确认/感谢类短消息 → 静默(PHP nothing 规则) + if (SILENT_RE.test(text)) { + ctx.logger.info(`[inbox rules] 静默规则命中: ${text.slice(0, 50)}`); + return { handled: true, silent: true }; + } + + return { handled: false }; + } + + /** + * 根据函数执行结果构建回复文本。 + * 优先 direct_reply 模板消息(支持 messages 数组多行回复),其次 data.message,商品搜索做格式化,失败返回错误文案。 + * + * @param {string} fn 函数名。 + * @param {Object} result callFunction 返回结果。 + * @return {string|string[]|null} 回复文本(数组表示多条消息逐个回复),null 表示无需回复。 + */ + buildReply(fn, result) { + if (!result || typeof result !== 'object') return null; + if (result.success === false) { + return String(result.error || '操作失败,请联系客服处理'); + } + const data = result.data || {}; + if (data.direct_reply === true && Array.isArray(data.messages) && data.messages.length > 0) { + return data.messages.map(m => String(m)); + } + if (data.direct_reply === true && typeof data.message === 'string' && data.message) { + return data.message; + } + if (typeof data.message === 'string' && data.message) { + return data.message; + } + if (fn === 'searchStock' || fn === 'searchWarehouseStock') { + return this.formatStock(data); + } + return null; + } + + /** + * 商品搜索结果的纯文本格式化。 + * @param {Object} data 函数返回的 data。 + * @return {string} 格式化文本。 + */ + formatStock(data = {}) { + const items = Array.isArray(data.items) ? data.items : []; + if (items.length === 0) { + return String(data.hint || '未找到匹配商品,请尝试其他关键词'); + } + const lines = items.slice(0, 10).map((s, i) => { + const code = s.item_code || ''; + const name = s.item_name || ''; + const available = s.stock_available != null ? s.stock_available : 0; + const extra = s.prohibited_type ? `(违禁品:${s.prohibited_type})` : ''; + return `${i + 1}. ${code} ${name} 可用库存:${available}${extra}`; + }); + return `找到 ${items.length} 个商品:\n${lines.join('\n')}`; + } +} + +// ============================ 提取工具 ============================ + +/** + * 提取运单号(参考 PHP Chat.php getPostNums,结合 Node 运单特征)。 + * 排除:售后工单号(AS开头)、手机号、日期时间戳、纯字母串。 + * @param {string} text 消息正文。 + * @return {string[]} 去重后的运单号列表。 + */ +function extractWaybills(text) { + const raw = text.match(/[A-Za-z0-9_-]{10,24}/g) || []; + return [ ...new Set(raw) ].filter(t => { + if (/^AS\d+$/i.test(t)) return false; // 售后工单号 + if (/^1\d{10}$/.test(t)) return false; // 手机号 + if (/^\+?86[- ]?1\d{10}$/.test(t)) return false; // 国际区号手机(含/不含 +) + if (/^\d{3,4}-\d{7,8}$/.test(t)) return false; // 座机带横线(020-12345678) + if (/^0\d{9,11}$/.test(t)) return false; // 0开头座机/服务号(02012345678) + if (/^400\d{7}$/.test(t)) return false; // 400 服务电话 + if (/^\d{4}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{4,}$/.test(t)) return false; // 日期时间戳 + if (/^[A-Za-z_-]+$/.test(t)) return false; // 纯字母 + return true; + }); +} + +/** + * 提取订单号(发货单/平台单)。 + * 优先 SYS/SO/DD 前缀及字母数字混合号,兜底 12~20 位纯数字。 + * 前缀需独立成词(前不能紧邻字母数字),避免从长字符串中截取尾部 + * (如 NOTEXISTPOSTNUM20260814 误截成 TPOSTNUM20260814)。 + * @param {string} text 消息正文。 + * @return {string[]} 去重后的订单号列表。 + */ +function extractOrders(text) { + const raw = text.match(/(? 0) return list; + const nums = text.match(/(? !/^1\d{10}$/.test(t)); +} + +/** 改快递规则支持的目标快递名(长名在前,优先提取完整名称,避免“中通快运”被短名截断) */ +const EXPRESS_NAMES = [ '中通快运', '中通快递', '极兔速递', '京东快递', '圆通快递', '申通快递', '顺丰速运', '韵达快递', '邮政小包', '圆通', '中通', '申通', '顺丰', '韵达', '极兔', '邮政', 'EMS', '京东', '德邦' ]; + +/** + * 快递反馈 → 售后子类型映射(长词优先,避免“核实签收”被“签收”截断)。 + * 未命中保持默认 logistics_issue(物流异常)。 + */ +const EXPRESS_SUB_TYPE_RULES = [ + { keys: [ '核实签收', '签收核实', '已签收', '签收' ], sub: 'verify_delivery' }, + { keys: [ '破损', '坏了', '破损件' ], sub: 'damage' }, + { keys: [ '少发', '漏发', '发少' ], sub: 'missing_item' }, + { keys: [ '改地址', '地址更改', '改址' ], sub: 'change_address' }, + { keys: [ '换快递', '改快递' ], sub: 'change_carrier' }, + { keys: [ '催件', '催派', '催促' ], sub: 'urge' }, + { keys: [ '发货延迟', '延迟发货', '催发货' ], sub: 'delivery_delay' }, + { keys: [ '拒收' ], sub: 'rejected' }, +]; + +/** + * 从快递反馈文本推断售后子类型(长词优先)。 + * @param {string} text 消息正文。 + * @return {string|null} 售后子类型,未命中返回 null(由函数默认 logistics_issue)。 + */ +function resolveExpressSubType(text) { + let best = null; + let bestLen = 0; + for (const item of EXPRESS_SUB_TYPE_RULES) { + for (const k of item.keys) { + if (text.includes(k) && k.length > bestLen) { + best = item.sub; + bestLen = k.length; + } + } + } + return best; +} + +/** + * 从消息文本中解析目标快递名称(通用“改快递/换快递”规则用)。 + * @param {string} text 消息正文。 + * @return {string|null} 快递名称,未命中返回 null。 + */ +function extractExpressName(text) { + const lower = String(text || '').toLowerCase(); + return EXPRESS_NAMES.find(name => lower.includes(name.toLowerCase())) || null; +} + +/** + * 去除命中的关键词,取剩余文本作为查询词(查库存场景)。 + * @param {string} text 消息正文。 + * @param {string[]} keys 命中关键词列表。 + * @return {string} 剩余文本。 + */ +function stripKeyword(text, keys) { + let t = String(text || ''); + for (const k of keys) { + t = t.split(k).join(' '); + } + return t.replace(/\s+/g, ' ').trim(); +} + +/** 确认/感谢类短消息 → 静默 */ +const SILENT_RE = /^(好|好的|好的呢|好嘞|嗯|嗯嗯|哦|哦哦|ok|okay|收到|谢谢|感谢|谢谢啦|谢了|好了|可以|行|行了|对啊|是的|对|知道了|明白|了解了|1)\s*[!!。.,~~👍🙏❤️]*$/i; + +// ============================ 规则表(顺序即优先级) ============================ + +/** + * 拦截类规则的防误判守卫:询问物流进度/查快递等不是拦截请求, + * 取消/撤销类语义属于 cancelIntercept(双保险,长词优先已能保证) + * @param {string} t 消息正文 + * @return {boolean} 是否允许命中拦截规则 + */ +const INTERCEPT_GUARD = t => !/(到哪|在哪|哪里|快递到|物流|轨迹|查单|查快递|查物流|到哪里|取消拦截|撤销拦截|解除拦截|不拦截|不用拦截)/.test(t); + +/** 货主群(store) */ +const STORE_RULES = [ + { keys: [ '取消拦截', '撤销拦截', '解除拦截', '不拦截', '不用拦截' ], fn: 'cancelIntercept', waybill: true, + tip: '如需取消拦截,发送:取消拦截+运单号(多个单号用逗号或空格分隔)\n例:取消拦截 SF123,SF456' }, + { keys: [ '拦截', '追回', '召回' ], fn: 'interceptWaybill', waybill: true, guard: INTERCEPT_GUARD, + tip: '如需拦截运单,发送:拦截+运单号(多个单号用逗号或空格分隔)\n例:拦截 SF123,SF456' }, + { keys: [ '揽收', '上门取件', '退货取件', '让快递来拿' ], fn: 'requestPickup', waybill: true, + tip: '如需安排上门揽收,发送:揽收+运单号\n例:揽收 SF123' }, + { keys: [ '少发', '发少' ], fn: 'handleStoreFeedback', issueType: 'missing', waybill: true, + tip: '如需反馈少发,发送:少发+运单号\n例:少发 SF123' }, + { keys: [ '重量', '查重', '核实重量', '核重', '称重' ], fn: 'queryWeight', waybill: true, + tip: '如需查询库内称重,发送:称重+运单号\n例:称重 SF123' }, + { keys: [ '错发', '发错' ], fn: 'handleStoreFeedback', issueType: 'wrong', waybill: true, + tip: '如需反馈错发,发送:错发+运单号\n例:错发 SF123' }, + { keys: [ '破损', '坏了' ], fn: 'handleStoreFeedback', issueType: 'damaged', waybill: true, + tip: '如需反馈破损,发送:破损+运单号\n例:破损 SF123' }, + { keys: [ '多发', '发多' ], fn: 'handleStoreFeedback', issueType: 'multiple', waybill: true, + tip: '如需反馈多发,发送:多发+运单号\n例:多发 SF123' }, + { keys: [ '改地址', '改电话', '改联系人', '改收件人', '地址更改', '改手机' ], fn: 'changeAddr', issueType: 'addr', waybill: true, + tip: '如需修改地址,发送:改地址+运单号\n例:改地址 SF123' }, + // 注意顺序:催退回/催促退回 必须在 催件/催促 之前("催促退回"含"催促") + { keys: [ '催退回', '催促退回' ], fn: 'changeAddr', issueType: 'return', waybill: true, + tip: '如需催退回,发送:催退回+运单号\n例:催退回 SF123' }, + { keys: [ '催件', '催派', '催促', '尽快安排派送', '未中转', '物流停滞' ], fn: 'changeAddr', issueType: 'urge', waybill: true, + tip: '如需催件,发送:催件+运单号\n例:催件 SF123' }, + { keys: [ '查退回', '是否已退回' ], fn: 'queryReturn', waybill: true, paramName: 'waybill_code', + tip: '如需查退回,发送:查退回+运单号\n例:查退回 SF123' }, + { keys: [ '退回', '拒收' ], fn: 'queryReturn', waybill: true, paramName: 'waybill_code', + tip: '如需查退回,发送:查退回+运单号\n例:查退回 SF123' }, + { keys: [ '核实签收', '未收到', '是否发出', '是否已经发货', '没有找到快递' ], fn: 'weishoudao', waybill: true, + tip: '如需核实签收,发送:核实签收+运单号\n例:核实签收 SF123' }, + { keys: [ '出单', '打单', '打印单', '催发货', '分配快递号' ], fn: 'createPostnum', order: true, + tip: '如需出单/分配快递号,发送:出单+订单号\n例:出单 SYS2026010100001' }, + // 通用格式:改快递+订单号+快递名(放在固定“改圆通”等规则之前,两者关键词互不冲突) + { keys: [ '改快递', '换快递' ], fn: 'changeExpress', expressFromText: true, order: true, + tip: '如需改快递,发送:改快递+订单号+快递名称\n例:改快递 SYS2026010100001 圆通' }, + { keys: [ '改圆通' ], fn: 'changeExpress', express: '圆通', order: true, + tip: '如需改快递,发送:改圆通+订单号\n例:改圆通 SYS2026010100001' }, + { keys: [ '改中通' ], fn: 'changeExpress', express: '中通', order: true, + tip: '如需改快递,发送:改中通+订单号' }, + { keys: [ '改申通' ], fn: 'changeExpress', express: '申通', order: true, + tip: '如需改快递,发送:改申通+订单号' }, + { keys: [ '改极兔' ], fn: 'changeExpress', express: '极兔', order: true, + tip: '如需改快递,发送:改极兔+订单号' }, + { keys: [ '改韵达' ], fn: 'changeExpress', express: '韵达', order: true, + tip: '如需改快递,发送:改韵达+订单号' }, + { keys: [ '改顺丰' ], fn: 'changeExpress', express: '顺丰', order: true, + tip: '如需改快递,发送:改顺丰+订单号' }, + { keys: [ '改邮政' ], fn: 'changeExpress', express: '邮政', order: true, + tip: '如需改快递,发送:改邮政+订单号' }, + { keys: [ '改EMS', '改ems' ], fn: 'changeExpress', express: 'EMS', order: true, + tip: '如需改快递,发送:改EMS+订单号' }, + { keys: [ '改京东' ], fn: 'changeExpress', express: '京东', order: true, + tip: '如需改快递,发送:改京东+订单号' }, + { keys: [ '仓库地址', '退货地址', '退件地址', '寄回地址', '收货地址' ], fn: 'queryWarehouseAddress' }, + { keys: [ '打包视频', '装箱视频' ], fn: 'queryPackVideo', waybill: true, + tip: '如需查询打包视频,发送:打包视频+运单号\n例:打包视频 SF123' }, + { keys: [ '查库存' ], fn: 'searchStock', stockSearch: true, + tip: '如需查库存,发送:查库存+商品名称/编码/条码' }, + { keys: [ 'help', '指令', '帮助' ], fn: '__help__' }, +]; + +/** 仓库内部群(warehouse,客服子类型可用的函数较多,不可用函数自动跳过) */ +const WAREHOUSE_RULES = [ + { keys: [ '取消拦截', '撤销拦截', '解除拦截', '不拦截', '不用拦截' ], fn: 'cancelIntercept', waybill: true, + tip: '如需取消拦截,发送:取消拦截+运单号' }, + { keys: [ '拦截', '追回', '召回' ], fn: 'interceptWaybill', waybill: true, guard: INTERCEPT_GUARD, + tip: '如需拦截运单,发送:拦截+运单号' }, + { keys: [ '揽收', '上门取件' ], fn: 'requestPickup', waybill: true, + tip: '如需安排上门揽收,发送:揽收+运单号' }, + { keys: [ '查退回', '是否已退回' ], fn: 'queryReturn', waybill: true, paramName: 'waybill_code', + tip: '如需查退回,发送:查退回+运单号' }, + { keys: [ '重量', '查重', '核实重量', '核重', '称重' ], fn: 'queryWeight', waybill: true, + tip: '如需查询库内称重,发送:称重+运单号' }, + { keys: [ '打包视频', '装箱视频' ], fn: 'queryPackVideo', waybill: true, + tip: '如需查询打包视频,发送:打包视频+运单号' }, + { keys: [ '仓库地址', '退货地址', '退件地址', '寄回地址', '收货地址' ], fn: 'queryWarehouseAddress' }, + { keys: [ '查库存' ], fn: 'searchWarehouseStock', stockSearch: true, + tip: '如需查库存,发送:查库存+商品名称/编码/条码' }, + { keys: [ 'help', '指令', '帮助' ], fn: '__help__' }, +]; + +/** 快递售后群(express)规则表:消息含运单号即按反馈处理(按关键词推断子类型),无运单号静默 */ +const EXPRESS_RULES = [ + { any: true, fn: 'handleExpressFeedback', waybill: true, noWaybillSilent: true, expressSubType: true }, +]; + +/** 规则表:按群类型选择 */ +const RULE_TABLES = { + store: STORE_RULES, + warehouse: WAREHOUSE_RULES, + express: EXPRESS_RULES, +}; + +// ============================ 帮助文本 ============================ + +const HELP_TEXTS = { + store: '当前群支持以下指令(发送:指令+单号,多个单号用逗号或空格分隔):\n' + + '· 拦截+运单号 / 取消拦截+运单号\n' + + '· 揽收+运单号\n' + + '· 催件+运单号 / 催退回+运单号\n' + + '· 改地址+运单号\n' + + '· 称重+运单号 / 查退回+运单号 / 核实签收+运单号\n' + + '· 打包视频+运单号\n' + + '· 少发/错发/破损/多发+运单号\n' + + '· 出单+订单号\n' + + '· 改圆通/改中通/改申通/改顺丰/改韵达/改极兔/改邮政/改EMS/改京东+订单号\n' + + '· 仓库地址\n' + + '· 查库存+商品名称或条码', + warehouse: '当前群支持以下指令:\n' + + '· 拦截+运单号 / 取消拦截+运单号\n' + + '· 揽收+运单号\n' + + '· 查退回+运单号 / 称重+运单号\n' + + '· 打包视频+运单号\n' + + '· 仓库地址\n' + + '· 查库存+商品名称或条码', + express: '发送运单号+处理情况,系统将自动记录并回信货主群。', +}; + +module.exports = InboxRulesService; diff --git a/app/service/inbox/tools.js b/app/service/inbox/tools.js new file mode 100644 index 0000000..bafa37c --- /dev/null +++ b/app/service/inbox/tools.js @@ -0,0 +1,51 @@ +'use strict'; + +const Service = require('egg').Service; + +/** + * 站内信工具方法集合(与业务函数无关的辅助逻辑)。 + * 从 inbox/functions.js 拆出,保持 functions.js 只负责业务函数注册与执行。 + */ +class InboxToolsService extends Service { + + /** + * 获取仓库的录制电脑 ID(带缓存)。 + * @param {number} warehouseId 仓库ID + * @return {Promise} 录制电脑ID,找不到返回 null + */ + async getRecordingComputerId(warehouseId) { + const cacheKey = `_recordingComputer_${warehouseId}`; + if (this[cacheKey] !== undefined) { + return this[cacheKey]; + } + const row = await this.ctx.model.PrintComputer.findOne({ + where: { warehouse_id: warehouseId, is_recording: true, deleted_at: null }, + attributes: [ 'id' ], + raw: true, + }); + this[cacheKey] = row ? row.id : null; + return this[cacheKey]; + } + + /** + * 构建视频完整 URL。 + * 格式:http://w{warehouseId}-c{recordingComputerId}.o.gztbyc.com{videoPath} + * @param {number} warehouseId 仓库ID + * @param {number|null} recordingComputerId 录制电脑ID + * @param {string} videoPath 视频路径 + * @return {string} 完整 URL + */ + buildVideoUrl(warehouseId, recordingComputerId, videoPath) { + const path = String(videoPath || '').trim(); + if (!path || !recordingComputerId) { + return path; + } + // 已是完整 URL 时原样返回,避免重复拼接 + if (/^https?:\/\//i.test(path)) { + return path; + } + return `http://w${warehouseId}-c${recordingComputerId}.o.gztbyc.com${path}`; + } +} + +module.exports = InboxToolsService; diff --git a/app/service/systems/return_received.js b/app/service/systems/return_received.js index d4f591d..f886d28 100644 --- a/app/service/systems/return_received.js +++ b/app/service/systems/return_received.js @@ -98,6 +98,35 @@ class ReturnReceivedService extends Service { ctx.logger.warn(`[returnReceived.create] 反查原运单失败: ${err.message}`); } + // 非原单退回:匹配货主登记表(wms_return_query_log,货主查询/登记过退回的运单),把件归属到对应货主 + // 兼容一单多件分段单号:精确 + 剥尾段 + 前缀段 + if (!orderExpressId && !storeId) { + try { + const base = waybillCode.replace(/(?:-\d+){2,}-?$/, ''); + const queryLog = await ctx.model.ReturnQueryLog.findOne({ + where: { + warehouse_id: warehouseId, + store_id: { [Op.gt]: 0 }, + [Op.or]: [ + { waybill_code: waybillCode }, + ...(base !== waybillCode ? [{ waybill_code: base }] : []), + { waybill_code: { [Op.like]: `${base}-%` } }, + ], + }, + order: [[ 'id', 'DESC' ]], + raw: true, + }); + if (queryLog && Number(queryLog.store_id) > 0) { + storeId = Number(queryLog.store_id); + ctx.logger.info( + `[returnReceived.create] 匹配货主登记表归属: ${waybillCode} -> store_id=${storeId}` + ); + } + } catch (err) { + ctx.logger.warn(`[returnReceived.create] 匹配货主登记表失败: ${err.message}`); + } + } + const created = await ctx.model.ReturnReceived.create({ warehouse_id: warehouseId, waybill_code: waybillCode, @@ -132,6 +161,9 @@ class ReturnReceivedService extends Service { const createdRow = created && typeof created.toJSON === 'function' ? created.toJSON() : created; const enriched = await this._enrichReturn(createdRow); + + // 通知不在此处即时发送:由定时任务聚合(等 delayMs 无新登记后,按货主合并推送,只对货主查退回时登记过的运单通知) + return { record: enriched, is_original_return: Boolean(enriched.order_express_id), @@ -140,6 +172,125 @@ class ReturnReceivedService extends Service { }; } + /** + * 聚合通知待通知的登记(定时任务调用)。 + * 规则: + * 1. 只通知登记时间早于阈值(默认 5 分钟)的登记,等待新登记防抖合并; + * 2. 只对货主在退回查询登记表(wms_return_query_log)登记过的运单通知; + * 3. 按 仓库+货主 分组,合并成一条消息推送到货主售后群; + * 4. 推送后标记 is_notified=1,不重复通知。 + * + * @param {Object} [opts] 可选参数。 + * @param {number} [opts.delayMs] 防抖窗口毫秒数,不传用 config.inbox.returnReceivedNotifyDelayMs(默认 5 分钟)。 + * @return {Promise} { notified, skipped }。 + */ + async notifyPending(opts = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + const delayNum = Number(opts.delayMs); + const delayMs = Number.isFinite(delayNum) && delayNum >= 0 + ? delayNum + : (Number(app.config.inbox?.returnReceivedNotifyDelayMs) || 5 * 60 * 1000); + const before = new Date(Date.now() - delayMs); + + // 待通知登记:已过防抖窗口、有货主、未通知 + const rows = await ctx.model.ReturnReceived.findAll({ + attributes: [ 'id', 'warehouse_id', 'waybill_code', 'store_id' ], + where: { + is_notified: 0, + store_id: { [Op.gt]: 0 }, + created_at: { [Op.lte]: before }, + }, + order: [[ 'id', 'ASC' ]], + limit: 200, + raw: true, + }); + if (rows.length === 0) { + return { notified: 0, skipped: 0 }; + } + + // 过滤:只对货主查退回时登记过的运单通知(匹配货主登记表,兼容分段单号) + const candidates = []; + for (const row of rows) { + const base = String(row.waybill_code || '').replace(/(?:-\d+){2,}-?$/, ''); + try { + const log = await ctx.model.ReturnQueryLog.findOne({ + attributes: [ 'id' ], + where: { + warehouse_id: row.warehouse_id, + [Op.or]: [ + { waybill_code: row.waybill_code }, + ...(base && base !== row.waybill_code ? [{ waybill_code: base }] : []), + ...(base ? [{ waybill_code: { [Op.like]: `${base}-%` } }] : []), + ], + }, + raw: true, + }); + if (log) candidates.push(row); + } catch (err) { + ctx.logger.warn(`[returnReceived.notifyPending] 查货主登记表失败 ${row.waybill_code}: ${err.message}`); + } + } + + const skipped = rows.length - candidates.length; + if (candidates.length === 0) { + return { notified: 0, skipped }; + } + + // 按 仓库+货主 分组聚合 + const buckets = new Map(); + for (const row of candidates) { + const key = `${row.warehouse_id}:${row.store_id}`; + if (!buckets.has(key)) { + buckets.set(key, { warehouse_id: row.warehouse_id, store_id: row.store_id, ids: [], waybills: [] }); + } + const bucket = buckets.get(key); + bucket.ids.push(row.id); + bucket.waybills.push(row.waybill_code); + } + + let notified = 0; + for (const bucket of buckets.values()) { + try { + const groups = await ctx.service.systems.inbox.group.findStoreAfterSalesGroups({ + storeIds: [ bucket.store_id ], + warehouseId: bucket.warehouse_id, + }); + if (groups.length === 0) { + ctx.logger.info( + `[returnReceived.notifyPending] 未找到货主售后群 warehouse=${bucket.warehouse_id} store=${bucket.store_id}` + ); + continue; + } + const content = `退回包裹已扫描登记:\n${bucket.waybills.join('\n')}\n仓库将安排拆包,拆包完成后将自动通知拆包明细`; + for (const g of groups) { + ctx.service.inbox.processor.pushSystemNotification({ + warehouse_id: bucket.warehouse_id, + group_id: g.group_id, + group_name: g.group_name, + content, + ext_data: g.ext_data || null, + store_id: g.store_id || null, + }); + } + await ctx.model.ReturnReceived.update( + { is_notified: 1 }, + { where: { id: { [Op.in]: bucket.ids } } } + ); + notified += bucket.ids.length; + ctx.logger.info( + `[returnReceived.notifyPending] 聚合通知 warehouse=${bucket.warehouse_id} store=${bucket.store_id} ` + + `groups=${groups.length} count=${bucket.ids.length} waybills=${bucket.waybills.join(',')}` + ); + } catch (err) { + ctx.logger.warn(`[returnReceived.notifyPending] 通知失败: ${err.message}`); + } + } + + return { notified, skipped }; + } + /** * 处理退回运单关联的未完结拦截工单(写入「退回包裹已收到」并完结)。 * 仅更新工单状态,不处理库存信息(参考库内拦截 interceptScan 的工单处理部分)。 diff --git a/app/service/systems/return_unpack.js b/app/service/systems/return_unpack.js index b5d1593..44df27b 100644 --- a/app/service/systems/return_unpack.js +++ b/app/service/systems/return_unpack.js @@ -528,16 +528,20 @@ class ReturnUnpackService extends Service { { where: { id: unpack.id } } ); - // 同步更新退回查询记录:按 warehouse_id + waybill_code 反查命中则 is_back=1 + // 同步更新退回查询记录:按 warehouse_id + 运单号(兼容分段单号)反查命中则 is_back=1 + const { Op } = ctx.app.Sequelize; try { await ctx.model.ReturnQueryLog.update( { is_back: 1 }, - { where: { warehouse_id: unpack.warehouse_id, waybill_code: unpack.waybill_code } } + { where: { warehouse_id: unpack.warehouse_id, [Op.or]: this._buildWaybillMatch(unpack.waybill_code) } } ); } catch (err) { ctx.logger.warn(`[returnUnpack.submit] 更新退回查询记录 is_back 失败: ${err.message}`); } + // 拆包完成后通知货主群:登记表/拆包单有货主归属且未通知的,推送到货主售后群并标记 is_notified=1 + await this._notifyUnpacked(unpack); + const updated = await ctx.model.ReturnUnpack.findOne({ where: { id: unpack.id }, raw: true, @@ -548,6 +552,91 @@ class ReturnUnpackService extends Service { }; } + /** + * 拆包完成后通知货主群。 + * 通知集合:仅退回查询登记表中该运单已退回(is_back=1)且未通知(is_notified=0)、有货主归属的记录; + * 货主从未查询过退回(登记表无匹配)的不通知。推送成功后标记 is_notified=1。 + * + * @param {Object} unpack 拆包单主表记录 + * @return {Promise} 异常仅记日志不阻塞主流程 + */ + async _notifyUnpacked(unpack) { + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + const warehouseId = Number(unpack.warehouse_id || 0); + try { + const logs = await ctx.model.ReturnQueryLog.findAll({ + attributes: [ 'id', 'store_id', 'waybill_code' ], + where: { + warehouse_id: warehouseId, + [Op.or]: this._buildWaybillMatch(unpack.waybill_code), + is_back: 1, + is_notified: 0, + }, + raw: true, + }); + + // 通知对象:store_id → 运单号集合(仅货主查询过退回的登记,store_id 必须有归属) + const notifyMap = new Map(); + for (const log of logs) { + const sid = Number(log.store_id || 0); + if (sid <= 0) continue; + if (!notifyMap.has(sid)) notifyMap.set(sid, new Set()); + notifyMap.get(sid).add(log.waybill_code || unpack.waybill_code); + } + + if (notifyMap.size === 0) { + ctx.logger.info( + `[returnUnpack._notifyUnpacked] 无货主查询过退回的登记,跳过通知 waybill=${unpack.waybill_code}` + ); + return; + } + + // 查货主售后群 + const storeIds = [ ...notifyMap.keys() ]; + const groups = await ctx.service.systems.inbox.group.findStoreAfterSalesGroups({ + storeIds, + warehouseId, + }); + if (groups.length === 0) { + ctx.logger.info( + `[returnUnpack._notifyUnpacked] 未找到货主售后群,跳过通知 storeIds=${storeIds.join(',')}` + ); + return; + } + + // 按群推送(一条消息含该货主的全部运单) + for (const g of groups) { + const waybills = [ ...(notifyMap.get(Number(g.store_id)) || new Set()) ]; + if (waybills.length === 0) continue; + const content = `退回包裹已拆包完成:\n${waybills.join('\n')}\n发送:查退回+运单号,可查看拆包明细`; + ctx.service.inbox.processor.pushSystemNotification({ + warehouse_id: warehouseId, + group_id: g.group_id, + group_name: g.group_name, + content, + ext_data: g.ext_data || null, + store_id: g.store_id || null, + }); + } + + // 标记已通知 + const notifiedIds = logs.map(l => l.id); + if (notifiedIds.length > 0) { + await ctx.model.ReturnQueryLog.update( + { is_notified: 1 }, + { where: { id: { [Op.in]: notifiedIds } } } + ); + } + ctx.logger.info( + `[returnUnpack._notifyUnpacked] 拆包通知完成 waybill=${unpack.waybill_code} ` + + `groups=${groups.length} logs=${notifiedIds.length}` + ); + } catch (err) { + ctx.logger.warn(`[returnUnpack._notifyUnpacked] 拆包通知失败: ${err.message}`); + } + } + /** * 强制重新录制拆包视频:重置视频记录状态并推送打印服务强制录制。 * 参考 order.packing.forceRecord:校验仓库录制电脑在线后,将视频记录重置为 @@ -889,6 +978,51 @@ class ReturnUnpackService extends Service { }; } + /** + * 构建运单号灵活匹配条件:精确单号 + 剥尾段单号 + 前缀段单号。 + * 兼容京东等一单多件的分段单号(如 JDX057904621547-1-1- 与 JDX057904621547 互相匹配)。 + * @param {string} waybillCode 运单号 + * @return {Array} Sequelize Op.or 条件数组 + */ + _buildWaybillMatch(waybillCode) { + const { Op } = this.app.Sequelize; + const code = String(waybillCode || '').trim(); + // 剥掉尾部多段数字段(一单多件格式:-包裹序号-总件数[-]) + const base = code.replace(/(?:-\d+){2,}-?$/, ''); + // 转义 like 通配符,避免输入中的 % _ 扩大匹配范围 + const escapedBase = String(base || '').replace(/[%_\\]/g, m => `\\${m}`); + const or = [{ waybill_code: code }]; + if (base && base !== code) or.push({ waybill_code: base }); + if (escapedBase) or.push({ waybill_code: { [Op.like]: `${escapedBase}-%` } }); + return or; + } + + /** + * 运单号灵活查询:精确单号优先,其次剥尾段单号,再次前缀段。 + * @param {Object} model Sequelize 模型 + * @param {Object} extraWhere 额外查询条件 + * @param {string} waybillCode 运单号 + * @param {string[]} [attributes] 返回字段 + * @param {Array} [order] 排序(默认 created_at DESC, id DESC) + * @return {Promise} 命中的行,未命中返回 null + */ + async _findWaybillFlexible(model, extraWhere, waybillCode, attributes, order) { + const { Op } = this.app.Sequelize; + const code = String(waybillCode || '').trim(); + const base = code.replace(/(?:-\d+){2,}-?$/, ''); + const options = { + where: { ...extraWhere, [Op.or]: this._buildWaybillMatch(code) }, + order: order && order.length > 0 ? order : [[ 'created_at', 'DESC' ], [ 'id', 'DESC' ]], + limit: 5, + raw: true, + }; + if (Array.isArray(attributes) && attributes.length > 0) options.attributes = attributes; + const rows = await model.findAll(options); + if (!rows || rows.length === 0) return null; + const rank = row => (row.waybill_code === code ? 0 : (row.waybill_code === base ? 1 : 2)); + return rows.slice().sort((a, b) => rank(a) - rank(b))[0]; + } + /** * 查询退回明细(按运单号,跨退回相关表汇总)。 * 依次查询:拆包主表+明细+视频(已拆包)→ 退回收到表(已收到未拆包)→ 退回查询登记表(未退回)。 @@ -919,15 +1053,12 @@ class ReturnUnpackService extends Service { const warehouseName = await this._resolveWarehouseName(warehouseId); // 1. 已拆包:同一运单号取最新一条有效拆包单(跳过已作废) - const unpack = await ctx.model.ReturnUnpack.findOne({ - where: { - warehouse_id: warehouseId, - waybill_code: waybillCode, - status: { [Op.ne]: 'cancelled' }, - }, - order: [[ 'created_at', 'DESC' ], [ 'id', 'DESC' ]], - raw: true, - }); + // 兼容一单多件分段单号:JDX057904621547 可命中 JDX057904621547-1-1- + const unpack = await this._findWaybillFlexible( + ctx.model.ReturnUnpack, + { warehouse_id: warehouseId, status: { [Op.ne]: 'cancelled' } }, + waybillCode + ); if (unpack) { // 货主隔离:限定货主查询且拆包单已归属其他货主 → 不暴露数据 @@ -982,12 +1113,12 @@ class ReturnUnpackService extends Service { }; } - // 2. 已收到未拆包:退回收到表登记过 - const received = await ctx.model.ReturnReceived.findOne({ - where: { warehouse_id: warehouseId, waybill_code: waybillCode }, - order: [[ 'created_at', 'DESC' ], [ 'id', 'DESC' ]], - raw: true, - }); + // 2. 已收到未拆包:退回收到表登记过(兼容分段单号) + const received = await this._findWaybillFlexible( + ctx.model.ReturnReceived, + { warehouse_id: warehouseId }, + waybillCode + ); if (received) { if (storeId > 0 && Number(received.store_id || 0) > 0 && Number(received.store_id) !== storeId) { @@ -1056,11 +1187,11 @@ class ReturnUnpackService extends Service { } // 3. 未退回:查询退回查询登记表,无登记则自动登记(等待拆包后处理) - const queryLog = await ctx.model.ReturnQueryLog.findOne({ - where: { warehouse_id: warehouseId, waybill_code: waybillCode }, - order: [[ 'id', 'DESC' ]], - raw: true, - }); + const queryLog = await this._findWaybillFlexible( + ctx.model.ReturnQueryLog, + { warehouse_id: warehouseId }, + waybillCode + ); if (queryLog) { return { @@ -1143,11 +1274,14 @@ class ReturnUnpackService extends Service { async _resolveStoreIdByWaybill(waybillCode, warehouseId) { const { ctx } = this; try { - const express = await ctx.model.OrderExpress.findOne({ - where: { waybill_code: waybillCode, warehouse_id: warehouseId }, - attributes: [ 'store_id' ], - raw: true, - }); + // 兼容一单多件分段单号(京东 JDX...-1-1- 等) + const express = await this._findWaybillFlexible( + ctx.model.OrderExpress, + { warehouse_id: warehouseId }, + waybillCode, + [ 'store_id', 'waybill_code' ], + [[ 'id', 'DESC' ]] + ); return express && Number(express.store_id) > 0 ? Number(express.store_id) : 0; } catch (err) { ctx.logger.warn(`[returnUnpack._resolveStoreIdByWaybill] 反查货主失败: ${err.message}`); diff --git a/config/config.default.js b/config/config.default.js index 15c0d5e..275e88b 100644 --- a/config/config.default.js +++ b/config/config.default.js @@ -58,6 +58,10 @@ module.exports = appInfo => { imageBaseUrl: '', // 商品图片域名,为空时用请求 ctx.host // 历史消息过滤:消息原始发送时间距今超过该阈值(毫秒)则跳过 AI 处理,防止补推历史消息被当成新工单 historyMessageMaxAgeMs: 10 * 60 * 1000, + // AI 兜底开关:规则引擎未命中时是否回退 AI 推理(默认关闭,节省费用;开启后未命中消息走 AI) + aiFallback: false, + // 退回收件登记聚合通知防抖窗口(毫秒):等该时长无新登记后合并推送,默认 5 分钟 + returnReceivedNotifyDelayMs: 5 * 60 * 1000, }; config.tencentCloud = { diff --git a/database/migrations/20260827170000-add-is-notified-to-wms-return-received.js b/database/migrations/20260827170000-add-is-notified-to-wms-return-received.js new file mode 100644 index 0000000..9eddc36 --- /dev/null +++ b/database/migrations/20260827170000-add-is-notified-to-wms-return-received.js @@ -0,0 +1,29 @@ +'use strict'; + +const TABLE = 'wms_return_received'; + +/** + * 退回收件登记表新增 is_notified 字段: + * 标记"登记已通知货主群"(0=未通知,1=已通知)。 + * 供定时任务聚合通知(等 5 分钟无新登记后按货主合并推送,只对货主查退回时登记过的运单通知)。 + */ +module.exports = { + up: async (queryInterface, Sequelize) => { + const columns = await queryInterface.describeTable(TABLE); + if (!columns.is_notified) { + await queryInterface.addColumn(TABLE, 'is_notified', { + type: Sequelize.TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '登记是否已通知货主群:0=未通知,1=已通知', + }); + } + }, + + down: async queryInterface => { + const columns = await queryInterface.describeTable(TABLE); + if (columns.is_notified) { + await queryInterface.removeColumn(TABLE, 'is_notified'); + } + }, +}; From 59eb736740b94eb2fac62c15cf5e88ad14b3808a Mon Sep 17 00:00:00 2001 From: liufumingren Date: Thu, 27 Aug 2026 23:41:47 +0800 Subject: [PATCH 284/550] =?UTF-8?q?feat(storage):=20=E8=A1=A5=E8=B4=A7?= =?UTF-8?q?=E9=9C=80=E6=B1=82=E6=94=AF=E6=8C=81=E8=B4=A7=E4=B8=BB=E7=AD=9B?= =?UTF-8?q?=E9=80=89=E5=B9=B6=E8=A1=A5=E5=85=85=E8=B4=A7=E4=B8=BB=E5=90=8D?= =?UTF-8?q?=E7=A7=B0=E4=B8=8ESKU=E6=9D=A1=E7=A0=81=EF=BC=8C=E5=BF=AB?= =?UTF-8?q?=E6=8D=B7=E7=9B=B4=E5=85=A5=E6=8C=89=E7=BB=91=E5=AE=9A=E6=94=B6?= =?UTF-8?q?=E8=B4=A7=E5=8D=95=E6=88=AA=E6=96=AD=E5=B9=B6=E5=9B=9E=E5=86=99?= =?UTF-8?q?=E5=85=A5=E5=BA=93=E7=8A=B6=E6=80=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../systemMethods/storage/management.js | 25 ++ app/service/systems/storage/entry.js | 232 ++++++++++++++++-- app/service/systems/storage/management.js | 80 +++++- 3 files changed, 310 insertions(+), 27 deletions(-) diff --git a/app/service/systemMethods/storage/management.js b/app/service/systemMethods/storage/management.js index 53e0d15..765c77a 100644 --- a/app/service/systemMethods/storage/management.js +++ b/app/service/systemMethods/storage/management.js @@ -27,6 +27,7 @@ class StorageManagementMethodService extends MainService { * @param {Object} [data={}] 请求参数。 * @param {Object} [data.pagination] 分页参数。 * @param {Object} [data.sort] 排序参数。 + * @param {number|number[]} [data.store_id] 货主筛选:单值或数组(正整数),也可通过 data.where.store_id 传入;不传时返回全部货主。 * @return {Promise} 统一 success 包装的补货需求明细、汇总与分页信息。 */ async replenishmentDemand(data = {}) { @@ -34,9 +35,33 @@ class StorageManagementMethodService extends MainService { const requestData = this.isPlainObject(data) ? data : {}; const pagination = requestData.pagination || {}; const sort = requestData.sort || requestData.order || {}; + const where = this.isPlainObject(requestData.where) ? requestData.where : {}; + + // 货主筛选:支持顶层 store_id / store_ids,或 where.store_id(单值/数组) + const rawStoreIdValue = requestData.store_id !== undefined && requestData.store_id !== null + ? requestData.store_id + : (requestData.store_ids !== undefined && requestData.store_ids !== null + ? requestData.store_ids + : where.store_id); + + let storeIds = []; + if (rawStoreIdValue !== undefined && rawStoreIdValue !== null && rawStoreIdValue !== '') { + const rawList = Array.isArray(rawStoreIdValue) ? rawStoreIdValue : [ rawStoreIdValue ]; + const normalizedStoreIds = new Set(); + for (const item of rawList) { + const value = Number(item); + if (!Number.isFinite(value) || value <= 0 || !Number.isInteger(value)) { + throw new Error(`store_id 必须是正整数,非法值: ${item}`); + } + normalizedStoreIds.add(value); + } + storeIds = Array.from(normalizedStoreIds); + } + const result = await service.systems.storage.management.replenishmentDemand({ pagination, sort, + storeIds, }); return this.success('补货需求计算完成', result); } diff --git a/app/service/systems/storage/entry.js b/app/service/systems/storage/entry.js index 644a9d3..8a2278f 100644 --- a/app/service/systems/storage/entry.js +++ b/app/service/systems/storage/entry.js @@ -1416,7 +1416,107 @@ class EntryService extends Service { } /** - * 快捷直入/虚拟入库:将入库单的所有商品按明细数量全部直入到虚拟库位(space_id=2),跳过收货、质检等正常流程。 + * 快捷直入后回写绑定收货单的明细已入库数量与入库状态(事务内)。 + * 按 stock_id(=收货明细 system_product_id)把本次入库量依次分配到收货明细上, + * 每个明细最多分配其剩余可入数量(actual_quantity - stored_quantity), + * 分配后更新明细 stored_quantity/storage_status,并按各明细实际入库量 + * (stored_quantity 与 actual_quantity 比较)汇总更新收货单主表 storage_status: + * 全部明细均已足量入库才置 all,否则有部分入库置 partial,全部未入库置 none。 + * @param {Object} params 参数 + * @param {Array} params.receivingDetailRows 收货明细快照 [{ id, receiving_id, system_product_id, actual_quantity, stored_quantity }] + * @param {Map} params.stockInboundQtyMap stock_id -> 本次入库量 + * @param {Object} params.transaction Sequelize 事务对象 + * @return {Promise} + */ + async _applyReceivingInboundUsage({ receivingDetailRows, stockInboundQtyMap, transaction }) { + const { ctx, app } = this; + + if (!receivingDetailRows || receivingDetailRows.length === 0) return; + + // 1. 事务内行锁重新读取收货明细,避免并发超额分配 + const detailIds = receivingDetailRows.map(d => d.id); + const lockedDetails = await ctx.model.ReceivingDetail.findAll({ + where: { id: { [app.Sequelize.Op.in]: detailIds } }, + lock: transaction.LOCK.UPDATE, + order: [[ 'id', 'ASC' ]], + transaction, + raw: true, + }); + + // 2. 按 system_product_id(=stock_id)分组,同一商品多条明细按 id 升序依次分配 + const detailsByStock = new Map(); + for (const d of lockedDetails) { + const spid = Number(d.system_product_id); + if (!spid) continue; + if (!detailsByStock.has(spid)) detailsByStock.set(spid, []); + detailsByStock.get(spid).push(d); + } + + const touchedReceivingIds = new Set(); + + // 3. 逐商品分配本次入库量:使用了多少就写多少 + for (const [ stockId, plan ] of stockInboundQtyMap) { + let left = Number(plan.inboundQty) || 0; + const details = detailsByStock.get(Number(stockId)) || []; + for (const detail of details) { + if (left <= 0) break; + const actual = Number(detail.actual_quantity) || 0; + const stored = Number(detail.stored_quantity) || 0; + const remain = Math.max(0, actual - stored); + if (remain <= 0) continue; + const delta = Math.min(left, remain); + const newStored = stored + delta; + const storageStatus = newStored >= actual ? 'all' : 'partial'; + await ctx.model.ReceivingDetail.update({ + stored_quantity: newStored, + storage_status: storageStatus, + updated_at: new Date(), + }, { + where: { id: detail.id }, + transaction, + }); + touchedReceivingIds.add(Number(detail.receiving_id)); + left -= delta; + } + } + + // 4. 按实际入库量汇总更新收货单主表 storage_status: + // 全部明细均已足量入库(stored >= actual)→ all;存在部分入库 → partial;全部未入库 → none + for (const receivingId of touchedReceivingIds) { + const allDetails = await ctx.model.ReceivingDetail.findAll({ + where: { receiving_id: receivingId }, + attributes: [ 'actual_quantity', 'stored_quantity' ], + raw: true, + transaction, + }); + + let masterStatus = 'none'; + const fullyStored = allDetails.length > 0 + && allDetails.every(d => (Number(d.stored_quantity) || 0) >= (Number(d.actual_quantity) || 0)); + if (fullyStored) { + masterStatus = 'all'; + } else if (allDetails.some(d => (Number(d.stored_quantity) || 0) > 0)) { + masterStatus = 'partial'; + } + + await ctx.model.Receiving.update({ + storage_status: masterStatus, + updated_at: new Date(), + }, { + where: { id: receivingId }, + transaction, + }); + } + + ctx.logger.info( + `[storage.entry] 已回写收货单入库状态,receivingIds=[${[ ...touchedReceivingIds ].join(',')}]` + ); + } + + /** + * 快捷直入/虚拟入库:将入库单明细直入到虚拟库位(space_id=2),跳过收货、质检等正常流程。 + * 有绑定收货单时,只取收货单中与入库单明细有交集(按 stock_id 判断)且剩余可入数量的部分直入, + * 并回写收货单明细已入库数量;未绑定收货单时按明细计划数量全量直入。 * 采用"先同步后写库"两段式:① 先发奇门/OpenAPI 回传,② 回传成功后再开启事务写库存。 * @param {Object} data 请求体 * @param {number} data.id 入库单ID @@ -1479,18 +1579,79 @@ class EntryService extends Service { }; } + // 2.1 查询绑定收货单("已绑定"状态),按 stock_id 聚合收货明细剩余可入数量 + const bindings = await ctx.model.EntryOrderReceiving.findAll({ + where: { entry_order_id: entryOrder.id, deleted_at: null }, + attributes: [ 'receiving_id' ], + raw: true, + }); + const receivingIds = [ ...new Set((bindings || []).map(b => Number(b.receiving_id)).filter(Boolean)) ]; + + // 收货明细快照(用于事务内行锁回写),stockRemainingMap: null=未绑定(全量直入) + let receivingDetailsSnapshot = []; + let stockRemainingMap = null; + if (receivingIds.length > 0) { + const boundDetails = await ctx.model.ReceivingDetail.findAll({ + where: { + receiving_id: { [app.Sequelize.Op.in]: receivingIds }, + system_product_id: { [app.Sequelize.Op.ne]: null }, + }, + attributes: [ 'id', 'receiving_id', 'system_product_id', 'actual_quantity', 'stored_quantity' ], + raw: true, + }); + receivingDetailsSnapshot = boundDetails; + stockRemainingMap = new Map(); + for (const d of boundDetails) { + const spid = Number(d.system_product_id); + const remaining = Math.max(0, (Number(d.actual_quantity) || 0) - (Number(d.stored_quantity) || 0)); + stockRemainingMap.set(spid, (stockRemainingMap.get(spid) || 0) + remaining); + } + } + + // 2.2 按入库单明细计算实际直入数量:有绑定时只取收货单中有交集(stock_id)且剩余可入的数量 + const inboundPlans = entryItems.map(item => { + const planQty = Number(item.count) || 0; + let inboundQty = planQty; + if (stockRemainingMap) { + const stockId = Number(item.stock_id) || 0; + if (!stockId || !stockRemainingMap.has(stockId)) { + inboundQty = 0; // 收货单无交集商品,跳过 + } else { + const remaining = stockRemainingMap.get(stockId) || 0; + inboundQty = Math.min(planQty, remaining); + stockRemainingMap.set(stockId, remaining - inboundQty); + } + } + return { item, planQty, inboundQty }; + }); + + const effectivePlans = inboundPlans.filter(p => p.inboundQty > 0); + if (effectivePlans.length === 0) { + return { + code: 400, + message: stockRemainingMap + ? '收货单中无交集商品或剩余可入数量不足,无法快捷直入' + : '入库明细数量均为0,无法快捷直入', + data: { id: entryOrder.id, entry_order_code: entryOrder.entry_order_code }, + }; + } + + // 存在被截断/跳过的明细时按部分入库回传(confirmType=1, PARTFULFILLED) + const isPartialInbound = inboundPlans.some(p => p.inboundQty < p.planQty); + // ===== 阶段一 + 阶段二合并为统一调用 ===== const syncResult = await ctx.service.systems.inboundDirectLog.qimenEntrySync({ entryOrder, - orderLines: entryItems.map((item, idx) => ({ + orderLines: effectivePlans.map((plan, idx) => ({ orderLineNo: idx + 1, - ownerCode: item.owner_code || '', - itemCode: item.item_code || '', - itemId: item.item_id || '', - inventoryType: item.inventory_type || 'ZP', - planQty: Number(item.count) || 0, - actualQty: Number(item.count) || 0, + ownerCode: plan.item.owner_code || '', + itemCode: plan.item.item_code || '', + itemId: plan.item.item_id || '', + inventoryType: plan.item.inventory_type || 'ZP', + planQty: plan.planQty, + actualQty: plan.inboundQty, })), + isFin: !isPartialInbound, outBizCode: `DIRECT_INBOUND_${Date.now()}`, remark: '导入/PDA直接入库提交', operator: { @@ -1506,27 +1667,39 @@ class EntryService extends Service { const processedStockIds = new Set(); let totalInboundQty = 0; + let totalPlanQty = 0; + + // 按 stock_id 汇总本次实际入库量与库存类型(有绑定收货单时实际入库量 ≤ 计划量) + const stockPlanMap = new Map(); + for (const plan of inboundPlans) { + totalPlanQty += plan.planQty; + if (plan.inboundQty <= 0) continue; + const stockId = Number(plan.item.stock_id); + if (!stockId) continue; + const cur = stockPlanMap.get(stockId) || { inboundQty: 0, inventoryType: plan.item.inventory_type || 'ZP' }; + cur.inboundQty += plan.inboundQty; + stockPlanMap.set(stockId, cur); + totalInboundQty += plan.inboundQty; + } + + if (totalInboundQty <= 0) { + throw new Error('无有效可入明细,快捷直入失败'); + } try { - for (const item of entryItems) { - const stockId = item.stock_id; - if (!stockId) continue; - - const planQty = Number(item.count) || 0; - if (planQty <= 0) continue; - - const inventoryType = item.inventory_type || 'ZP'; - + // 回写入库单明细:本次实际入库多少写多少(跳过明细写 0) + for (const plan of inboundPlans) { await ctx.model.EntryItems.update({ - received_quantity: planQty, + received_quantity: plan.inboundQty, }, { - where: { id: item.id }, + where: { id: plan.item.id }, transaction, }); + } - if (processedStockIds.has(String(stockId))) continue; - processedStockIds.add(String(stockId)); - totalInboundQty += planQty; + for (const [ stockId, plan ] of stockPlanMap) { + const planQty = plan.inboundQty; + const inventoryType = plan.inventoryType; const stockRecord = await ctx.model.StockWarehouse.findOne({ where: { id: stockId, is_valid: 'Y', deleted_at: null }, @@ -1658,12 +1831,22 @@ class EntryService extends Service { }, { transaction }); } + // 回写绑定收货单明细已入库数量与入库状态(有绑定收货单时) + if (receivingDetailsSnapshot.length > 0) { + await this._applyReceivingInboundUsage({ + receivingDetailRows: receivingDetailsSnapshot, + stockInboundQtyMap: stockPlanMap, + transaction, + }); + } + await eo.update({ order_status: 'COMPLETED', sync_status: 'SUCCESS', sync_message: JSON.stringify({ completedAt: new Date(), totalQuantity: totalInboundQty, + planQuantity: totalPlanQty, itemCount: processedStockIds.size, source: 'quick_inbound', }), @@ -1715,8 +1898,9 @@ class EntryService extends Service { entry_order_code: entryOrder.entry_order_code, order_status: 'COMPLETED', sync_status: 'SUCCESS', - items_count: entryItems.length, - total_quantity: entryItems.reduce((s, item) => s + (Number(item.count) || 0), 0), + items_count: effectivePlans.length, + total_quantity: effectivePlans.reduce((s, p) => s + p.inboundQty, 0), + plan_quantity: entryItems.reduce((s, item) => s + (Number(item.count) || 0), 0), }, }; } diff --git a/app/service/systems/storage/management.js b/app/service/systems/storage/management.js index f57d34d..09a0a68 100644 --- a/app/service/systems/storage/management.js +++ b/app/service/systems/storage/management.js @@ -54,12 +54,17 @@ class StorageManagementService extends Service { * @param {Object} [options.sort] 排序参数。 * @param {string} [options.sort.sortField='shortage'] 排序字段,默认 shortage。 * @param {string} [options.sort.sortOrder='DESC'] 排序方向,ASC/DESC。 + * @param {number[]} [options.storeIds] 货主筛选:仅返回指定货主的 SKU,空数组表示不筛选。 * @return {Promise} 补货需求明细、汇总与分页信息。 */ async replenishmentDemand(options = {}) { const { ctx, app } = this; const { Op } = app.Sequelize; + // 货主筛选集合(空数组 = 不筛选) + const storeIds = Array.isArray(options.storeIds) ? options.storeIds : []; + const storeFilterSet = storeIds.length > 0 ? new Set(storeIds) : null; + // 仓库上下文:从用户上下文获取 const warehouseId = toNumber(ctx.user?.store_id ?? ctx.user?.warehouse_id, 0); @@ -127,7 +132,7 @@ class StorageManagementService extends Service { is_valid: 'Y', deleted_at: null, }, - attributes: [ 'id', 'item_code', 'item_name' ], + attributes: [ 'id', 'item_code', 'item_name', 'store_id' ], raw: true, }) : []; @@ -139,6 +144,7 @@ class StorageManagementService extends Service { const stockId = toNumber(row.id, 0); if (stockId <= 0) continue; stockInfoMap.set(stockId, { + store_id: toNumber(row.store_id, 0), stock_code: String(row.item_code || ''), stock_name: String(row.item_name || ''), }); @@ -153,7 +159,7 @@ class StorageManagementService extends Service { id: { [Op.in]: missedStockIds }, deleted_at: null, }, - attributes: [ 'id', 'item_code', 'item_name' ], + attributes: [ 'id', 'item_code', 'item_name', 'store_id' ], raw: true, }); @@ -161,6 +167,7 @@ class StorageManagementService extends Service { const stockId = toNumber(row.id, 0); if (stockId <= 0 || stockInfoMap.has(stockId)) continue; stockInfoMap.set(stockId, { + store_id: toNumber(row.store_id, 0), stock_code: String(row.item_code || ''), stock_name: String(row.item_name || ''), }); @@ -174,7 +181,7 @@ class StorageManagementService extends Service { where: { id: { [Op.in]: stillMissedStockIds }, }, - attributes: [ 'id', 'item_code', 'item_name' ], + attributes: [ 'id', 'item_code', 'item_name', 'store_id' ], raw: true, }); @@ -182,12 +189,72 @@ class StorageManagementService extends Service { const stockId = toNumber(row.id, 0); if (stockId <= 0 || stockInfoMap.has(stockId)) continue; stockInfoMap.set(stockId, { + store_id: toNumber(row.store_id, 0), stock_code: String(row.item_code || ''), stock_name: String(row.item_name || ''), }); } } + // 4.5) 查询货主名称与 SKU 条码 + const ownerStoreIds = Array.from( + new Set( + Array.from(stockInfoMap.values()) + .map(info => toNumber(info.store_id, 0)) + .filter(id => id > 0) + ) + ); + + const [ storeWarehouseRows, storeRows, barcodeRows ] = await Promise.all([ + ownerStoreIds.length > 0 + ? ctx.model.StoreWarehouse.findAll({ + where: { + store_id: { [Op.in]: ownerStoreIds }, + warehouse_id: warehouseId, + }, + attributes: [ 'store_id', 'store_remask' ], + raw: true, + }) + : [], + ownerStoreIds.length > 0 + ? ctx.model.Store.findAll({ + where: { id: { [Op.in]: ownerStoreIds } }, + attributes: [ 'id', 'company_name' ], + raw: true, + }) + : [], + ctx.model.StockBarcode.findAll({ + where: { stock_id: { [Op.in]: allStockIds } }, + attributes: [ 'id', 'stock_id', 'barcode' ], + raw: true, + }), + ]); + + // 货主名称:签约表备注名 store_remask 优先,商家表 company_name 兜底 + const storeNameMap = new Map(); + for (const row of Array.isArray(storeRows) ? storeRows : []) { + const storeId = toNumber(row.id, 0); + if (storeId > 0) storeNameMap.set(storeId, String(row.company_name || '')); + } + for (const row of Array.isArray(storeWarehouseRows) ? storeWarehouseRows : []) { + const storeId = toNumber(row.store_id, 0); + const remask = String(row.store_remask || '').trim(); + if (storeId > 0 && remask) storeNameMap.set(storeId, remask); + } + + // SKU 条码按 stock_id 分组 + const barcodeMap = new Map(); + for (const row of Array.isArray(barcodeRows) ? barcodeRows : []) { + const stockId = toNumber(row.stock_id, 0); + if (stockId <= 0) continue; + const barcodeList = barcodeMap.get(stockId) || []; + barcodeList.push({ + id: toNumber(row.id, 0), + barcode: String(row.barcode || ''), + }); + barcodeMap.set(stockId, barcodeList); + } + // 5) 查询所有可用库存(不区分分拣/存货区),再按库位类型分类汇总 const storageRows = allStockIds.length > 0 ? await ctx.model.Storage.findAll({ @@ -263,6 +330,10 @@ class StorageManagementService extends Service { for (const stockId of allStockIds) { const info = stockInfoMap.get(stockId) || { stock_code: `SKU#${stockId}`, stock_name: `商品#${stockId}` }; + + // 货主筛选:仅返回指定货主的 SKU + if (storeFilterSet && !storeFilterSet.has(info.store_id || 0)) continue; + const totalDemand = demandByStockId.get(stockId) || 0; const pickZoneQty = pickZoneQtyByStockId.get(stockId) || 0; const storageZoneQty = storageZoneQtyByStockId.get(stockId) || 0; @@ -280,6 +351,9 @@ class StorageManagementService extends Service { stock_id: stockId, stock_code: info.stock_code, stock_name: info.stock_name, + store_id: info.store_id || 0, + store_name: storeNameMap.get(info.store_id) || '', + barcodes: barcodeMap.get(stockId) || [], pick_zone_quantity: pickZoneQty, storage_zone_quantity: storageZoneQty, total_demand: totalDemand, From 33a92bdc8d5acf1666421c6e4d274c9532372819 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Thu, 27 Aug 2026 23:41:50 +0800 Subject: [PATCH 285/550] =?UTF-8?q?fix(pack):=20=E6=89=93=E5=8C=85?= =?UTF-8?q?=E4=BA=BA=E6=9C=AA=E7=9F=A5=E8=B4=A6=E5=8F=B7=E5=86=99NULL?= =?UTF-8?q?=E5=B9=B6=E5=8E=BB=E9=87=8D=EF=BC=8C=E9=81=BF=E5=85=8D=E5=A4=9A?= =?UTF-8?q?=E4=BA=BA=E6=89=93=E5=8C=85=E8=A7=A6=E5=8F=91=E5=94=AF=E4=B8=80?= =?UTF-8?q?=E7=B4=A2=E5=BC=95=E5=86=B2=E7=AA=81=E4=B8=AD=E6=96=AD=E6=89=93?= =?UTF-8?q?=E5=8C=85=E6=B5=81=E7=A8=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/model/pack_task_packer.js | 4 +- app/service/systems/workbench.js | 31 +++++++++--- ...null-account-id-in-wms-pack-task-packer.js | 50 +++++++++++++++++++ 3 files changed, 76 insertions(+), 9 deletions(-) create mode 100644 database/migrations/20260826120000-allow-null-account-id-in-wms-pack-task-packer.js diff --git a/app/model/pack_task_packer.js b/app/model/pack_task_packer.js index 65d2e39..f645979 100644 --- a/app/model/pack_task_packer.js +++ b/app/model/pack_task_packer.js @@ -17,8 +17,8 @@ module.exports = app => { }, account_id: { type: BIGINT(20).UNSIGNED, - allowNull: false, - comment: '账号ID,关联 wms_account.id', + allowNull: true, + comment: '账号ID,关联 wms_account.id;未知账号为 NULL(唯一索引对 NULL 不生效,允许多名无账号打包人)', }, account_name: { type: STRING(128), diff --git a/app/service/systems/workbench.js b/app/service/systems/workbench.js index 3074cd0..314cbab 100644 --- a/app/service/systems/workbench.js +++ b/app/service/systems/workbench.js @@ -684,13 +684,30 @@ class WorkbenchService extends Service { const users = Array.isArray(usersParam) ? usersParam : []; let operatorText = ''; if (users.length > 0) { - const packerRecords = users.map((user, idx) => ({ - pack_task_id: packTask.id, - account_id: user.wms_account_id != null ? parseInt(user.wms_account_id) || 0 : 0, - account_name: user.real_name || '', - seq: idx, - })); - await ctx.model.PackTaskPacker.bulkCreate(packerRecords); + // account_id 未知时写 null(表列允许 NULL):唯一索引 uix_pack_task_account 对 + // NULL 不生效,避免多人打包(account_id 全为 0)时违反唯一约束导致主流程中断。 + // 真实账号仍按 account_id 去重;无账号时按姓名去重。 + const seenPackerKeys = new Set(); + const packerRecords = []; + for (const user of users) { + const accountIdRaw = user.wms_account_id != null + ? user.wms_account_id + : (user.id != null ? user.id : null); + const accountId = accountIdRaw != null ? (parseInt(accountIdRaw) || null) : null; + const accountName = user.real_name || ''; + const dedupeKey = accountId !== null ? `id:${accountId}` : `name:${accountName}`; + if (seenPackerKeys.has(dedupeKey)) continue; + seenPackerKeys.add(dedupeKey); + packerRecords.push({ + pack_task_id: packTask.id, + account_id: accountId, + account_name: accountName, + seq: packerRecords.length, + }); + } + if (packerRecords.length > 0) { + await ctx.model.PackTaskPacker.bulkCreate(packerRecords); + } operatorText = users.map(u => u.real_name || '').filter(Boolean).join(','); // 回写 operator_text 到打包任务 await packTask.update({ operator_text: operatorText }); diff --git a/database/migrations/20260826120000-allow-null-account-id-in-wms-pack-task-packer.js b/database/migrations/20260826120000-allow-null-account-id-in-wms-pack-task-packer.js new file mode 100644 index 0000000..579b517 --- /dev/null +++ b/database/migrations/20260826120000-allow-null-account-id-in-wms-pack-task-packer.js @@ -0,0 +1,50 @@ +'use strict'; + +const TABLE_NAME = 'wms_pack_task_packer'; + +/** + * 允许 account_id 为 NULL。 + * 背景:打包任务写入多名打包人时,PDA 上传的 wms_account_id 可能为 null, + * 旧代码统一兜底为 0,多人场景下多条 (pack_task_id, account_id=0) 违反 + * 唯一索引 uix_pack_task_account,导致 bulkCreate 抛 UniqueConstraintError, + * 进而中断 _packOrder 后续步骤(OSD 下发、操作日志)。 + * MySQL 唯一索引对 NULL 不生效,故未知账号改为写 NULL。 + */ +module.exports = { + up: async (queryInterface, Sequelize) => { + const tableInfo = await queryInterface.describeTable(TABLE_NAME); + const col = tableInfo.account_id; + if (!col) { + throw new Error(`[Migration] ${TABLE_NAME}.account_id 不存在`); + } + if (col.allowNull === false) { + await queryInterface.changeColumn(TABLE_NAME, 'account_id', { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '账号ID,关联 wms_account.id;未知账号为 NULL', + }); + console.log(`[Migration] ${TABLE_NAME}.account_id 已改为允许 NULL`); + } else { + console.log(`[Migration] ${TABLE_NAME}.account_id 已允许 NULL,跳过`); + } + }, + + down: async (queryInterface, Sequelize) => { + const tableInfo = await queryInterface.describeTable(TABLE_NAME); + const col = tableInfo.account_id; + if (!col) return; + + if (col.allowNull === true) { + // 回滚前把 NULL 归位为 0,避免改回 NOT NULL 失败 + await queryInterface.sequelize.query( + `UPDATE ${TABLE_NAME} SET account_id = 0 WHERE account_id IS NULL` + ); + await queryInterface.changeColumn(TABLE_NAME, 'account_id', { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '账号ID,关联 wms_account.id', + }); + console.log(`[Migration] ${TABLE_NAME}.account_id 已恢复为 NOT NULL`); + } + }, +}; From 4ddcbe60a4cf8d57130467b0345da65a61562434 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Thu, 27 Aug 2026 23:41:54 +0800 Subject: [PATCH 286/550] =?UTF-8?q?feat(order):=20=E5=8F=96=E6=B6=88?= =?UTF-8?q?=E8=AE=A2=E5=8D=95=E4=BA=8B=E5=8A=A1=E5=8E=9F=E5=AD=90=E5=8C=96?= =?UTF-8?q?=EF=BC=8C=E5=82=A8=E4=BD=8D=E5=88=86=E9=85=8D=E6=94=AF=E6=8C=81?= =?UTF-8?q?=E5=85=81=E8=AE=B8=E5=8F=97=E9=99=90=E5=BA=93=E4=BD=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../systemMethods/order/pendingOrder.js | 274 ++++++++++-------- .../systems/order_storage_allocation.js | 74 +++-- .../systems/order_storage_allocation.test.js | 113 ++++++++ 3 files changed, 315 insertions(+), 146 deletions(-) diff --git a/app/service/systemMethods/order/pendingOrder.js b/app/service/systemMethods/order/pendingOrder.js index c3f0fa0..1370a40 100644 --- a/app/service/systemMethods/order/pendingOrder.js +++ b/app/service/systemMethods/order/pendingOrder.js @@ -2388,6 +2388,10 @@ class PendingOrderService extends OrderBaseService { /** * 将待处理订单取消,并关闭到已取消状态。 * 仅允许取消当前仓库内处于待审核、待处理、待处理异常语义的订单。 + * + * 取消、波次清理、储位释放与创建锁释放在同一事务内完成: + * 任一环节失败整体回滚,避免"已取消但库存锁定未释放"的中间态。 + * * @param {Object} data 请求体。 * @param {number[]} data.ids 订单ID 数组。 * @return {Promise} 更新后的订单信息。 @@ -2403,91 +2407,106 @@ class PendingOrderService extends OrderBaseService { const model = await this.getOrderModel('order', warehouseId); const where = this.buildOrderWhere(orderIds, warehouseId); - const existingOrders = await model.findAll({ - where, - raw: true, - }); + const transaction = await this.ctx.model.transaction(); + let normalizedOrders = []; + let firstOrder = null; + let affectedRows = 0; - if (!Array.isArray(existingOrders) || existingOrders.length === 0) { - return this.success('取消成功', { - updated_count: 0, - ids: [], + try { + // 锁定订单行后读取最新状态,与储位分配事务串行化,避免读到过期快照 + const existingOrders = await model.findAll({ + where, + transaction, + lock: transaction.LOCK.UPDATE, + raw: true, }); - } - if (existingOrders.length !== orderIds.length) { - throw new Error('订单不存在或不属于当前仓库'); - } + if (!Array.isArray(existingOrders) || existingOrders.length === 0) { + await transaction.rollback(); + return this.success('取消成功', { + updated_count: 0, + ids: [], + }); + } - const nonCancelableOrder = existingOrders.find(order => !this.isCancelablePendingOrder(order)); - if (nonCancelableOrder) { - throw new Error('订单当前状态不允许取消'); - } + if (existingOrders.length !== orderIds.length) { + throw new Error('订单不存在或不属于当前仓库'); + } - // 已同步订单不允许取消,转为拦截处理 - const syncedOrders = existingOrders.filter( - order => String(order.sync_status || '').trim() === 'fin' - ); - if (syncedOrders.length > 0) { - const syncedOrderIds = syncedOrders.map(order => Number(order.id)).filter( - id => Number.isInteger(id) && id > 0 + const nonCancelableOrder = existingOrders.find(order => !this.isCancelablePendingOrder(order)); + if (nonCancelableOrder) { + throw new Error('订单当前状态不允许取消'); + } + + // 已同步订单不允许取消,转为拦截处理 + const syncedOrders = existingOrders.filter( + order => String(order.sync_status || '').trim() === 'fin' ); - if (syncedOrderIds.length > 0) { - const syncNow = new Date(); - await model.update( - { - intercept_status: 'requested', - updated_at: syncNow, - }, - { - where: { - id: syncedOrderIds, - }, - } + if (syncedOrders.length > 0) { + const syncedOrderIds = syncedOrders.map(order => Number(order.id)).filter( + id => Number.isInteger(id) && id > 0 ); - // 同步更新运单表拦截标记 - try { - const { Op: cancelOp } = this.app.Sequelize; - await this.ctx.model.OrderExpress.update( - { is_intercept: 'Y' }, - { where: { order_id: { [cancelOp.in]: syncedOrderIds }, warehouse_id: warehouseId } } + if (syncedOrderIds.length > 0) { + const syncNow = new Date(); + await model.update( + { + intercept_status: 'requested', + updated_at: syncNow, + }, + { + where: { + id: syncedOrderIds, + }, + transaction, + } ); - } catch (expressErr) { - this.ctx.logger.warn( - `[PendingOrderService.cancelOrder] 更新运单拦截标记失败, count=${syncedOrderIds.length}, error=${expressErr.message}` + // 同步更新运单表拦截标记 + try { + const { Op: cancelOp } = this.app.Sequelize; + await this.ctx.model.OrderExpress.update( + { is_intercept: 'Y' }, + { where: { order_id: { [cancelOp.in]: syncedOrderIds }, warehouse_id: warehouseId }, transaction } + ); + } catch (expressErr) { + this.ctx.logger.warn( + `[PendingOrderService.cancelOrder] 更新运单拦截标记失败, count=${syncedOrderIds.length}, error=${expressErr.message}` + ); + } + this.ctx.logger.info( + `[PendingOrderService.cancelOrder] 订单已同步,不可取消,已转为拦截处理,订单ID: ${syncedOrderIds.join(',')}` ); } - this.ctx.logger.info( - `[PendingOrderService.cancelOrder] 订单已同步,不可取消,已转为拦截处理,订单ID: ${syncedOrderIds.join(',')}` - ); + + // 拦截标记已写入,提交后抛出业务错误(调用方按"已转拦截"处理) + await transaction.commit(); + + const syncedCodes = syncedOrders + .map(order => String(order.delivery_order_code || order.pre_delivery_order_code || order.id || '').trim()) + .filter(Boolean) + .join(', '); + throw new Error(`订单已同步,不可取消,已转为拦截处理:${syncedCodes}`); } - const syncedCodes = syncedOrders - .map(order => String(order.delivery_order_code || order.pre_delivery_order_code || order.id || '').trim()) - .filter(Boolean) - .join(', '); - throw new Error(`订单已同步,不可取消,已转为拦截处理:${syncedCodes}`); - } - const now = new Date(); - const updateValues = { - status: PENDING_CANCEL_STATUS, - step: PENDING_CANCEL_STEP, - outbound_status: PENDING_OUTBOUND_STATUS, - updated_at: now, - }; + const now = new Date(); + const updateValues = { + status: PENDING_CANCEL_STATUS, + step: PENDING_CANCEL_STEP, + outbound_status: PENDING_OUTBOUND_STATUS, + updated_at: now, + }; - const updateResult = await model.update(updateValues, { - where, - }); + const updateResult = await model.update(updateValues, { + where, + transaction, + }); - const affectedRows = Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0); - if (affectedRows <= 0) { - throw new Error('订单不存在或不属于当前仓库'); - } + affectedRows = Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0); + if (affectedRows <= 0) { + throw new Error('订单不存在或不属于当前仓库'); + } - const ordersWithWave = existingOrders.filter(order => Number(order.wave_id) > 0); - if (ordersWithWave.length > 0) { - try { + const ordersWithWave = existingOrders.filter(order => Number(order.wave_id) > 0); + if (ordersWithWave.length > 0) { const { Op } = this.app.Sequelize; const WaveBatch = this.ctx.model.WaveBatch; @@ -2509,13 +2528,14 @@ class PendingOrderService extends OrderBaseService { }, warehouse_id: warehouseId, }, + transaction, } ); await this.ctx.service.systemMethods.order.wave.deleteOrderWaveIndexByOrderIds({ warehouseId, orderIds: waveOrderIds, - transaction: undefined, + transaction, }); // 重建受影响波次的订单索引(wave_index 重新排序) @@ -2527,6 +2547,7 @@ class PendingOrderService extends OrderBaseService { warehouseId, waveIds: affectedWaveIds, orderModel: model, + transaction, }); } } @@ -2551,6 +2572,7 @@ class PendingOrderService extends OrderBaseService { [Op.gt]: 0, }, }, + transaction, }); const wave = await WaveBatch.findOne({ @@ -2560,6 +2582,7 @@ class PendingOrderService extends OrderBaseService { }, attributes: [ 'wave_id', 'total_orders', 'wave_status' ], raw: true, + transaction, }); if (!wave) { @@ -2580,6 +2603,7 @@ class PendingOrderService extends OrderBaseService { wave_id: waveId, warehouse_id: warehouseId, }, + transaction, } ); } else { @@ -2592,61 +2616,66 @@ class PendingOrderService extends OrderBaseService { wave_id: waveId, warehouse_id: warehouseId, }, + transaction, } ); } } } - } catch (waveErr) { - this.ctx.logger.warn('[PendingOrderService.cancelOrder] 清理波次关联失败,不影响订单取消', waveErr); } - } - // 释放储位分配和库存锁定 - try { + // 释放储位分配和库存锁定(复用同一事务,取消与释放原子生效) await this.service.systems.orderStorageAllocation.cancelAllocateStorage({ order_ids: orderIds, + transaction, }); - } catch (allocErr) { - this.ctx.logger.warn('[PendingOrderService.cancelOrder] 释放储位分配失败,不影响订单取消', allocErr); - } - // 释放创建锁(lockItemStorages 加的锁,不含 picking 锁) - try { + // 释放创建锁(lockItemStorages 加的锁,不含 picking 锁) await this.releaseCreationLockForCancel({ orderIds, warehouseId, + transaction, }); - } catch (releaseErr) { - this.ctx.logger.warn('[PendingOrderService.cancelOrder] 释放创建锁失败,不影响订单取消', releaseErr); + + const updatedOrders = await model.findAll({ + where, + transaction, + raw: true, + }); + + if (!Array.isArray(updatedOrders) || updatedOrders.length === 0) { + throw new Error('订单不存在或不属于当前仓库'); + } + + const orderMap = new Map(updatedOrders.map(order => [ Number(order.id), order ])); + normalizedOrders = orderIds + .map(orderId => orderMap.get(orderId)) + .filter(Boolean) + .map(order => ({ + id: order.id, + status: order.status, + step: Number(order.step ?? PENDING_CANCEL_STEP), + updated_at: order.updated_at, + })); + + if (normalizedOrders.length === 0) { + throw new Error('订单不存在或不属于当前仓库'); + } + + firstOrder = normalizedOrders[0]; + + await transaction.commit(); + } catch (error) { + if (!transaction.finished) { + try { + await transaction.rollback(); + } catch (rollbackError) { + this.ctx.logger.error('[PendingOrderService.cancelOrder] 事务回滚失败', rollbackError); + } + } + throw error; } - const updatedOrders = await model.findAll({ - where, - raw: true, - }); - - if (!Array.isArray(updatedOrders) || updatedOrders.length === 0) { - throw new Error('订单不存在或不属于当前仓库'); - } - - const orderMap = new Map(updatedOrders.map(order => [ Number(order.id), order ])); - const normalizedOrders = orderIds - .map(orderId => orderMap.get(orderId)) - .filter(Boolean) - .map(order => ({ - id: order.id, - status: order.status, - step: Number(order.step ?? PENDING_CANCEL_STEP), - updated_at: order.updated_at, - })); - - if (normalizedOrders.length === 0) { - throw new Error('订单不存在或不属于当前仓库'); - } - - const firstOrder = normalizedOrders[0]; - // 写入取消操作日志(不影响主流程) try { const operator = this.getOrderLogOperator(); @@ -6409,9 +6438,10 @@ ${numbered}`; * @param {Object} options - 释放参数。 * @param {number[]} options.orderIds - 订单ID 数组。 * @param {number} options.warehouseId - 仓库ID。 + * @param {Object} [options.transaction] - 可选外部事务;传入时复用,由调用方负责提交与回滚。 * @return {Promise} */ - async releaseCreationLockForCancel({ orderIds, warehouseId } = {}) { + async releaseCreationLockForCancel({ orderIds, warehouseId, transaction: externalTransaction } = {}) { const { ctx, app } = this; const { Op } = app.Sequelize; @@ -6431,7 +6461,7 @@ ${numbered}`; return; } - const transaction = await ctx.model.transaction(); + const transaction = externalTransaction || await ctx.model.transaction(); try { // 直接从 order_items 读取 plan_qty,按 stock_id 汇总 @@ -6446,7 +6476,9 @@ ${numbered}`; }); if (!Array.isArray(orderItems) || orderItems.length === 0) { - await transaction.commit(); + if (!externalTransaction) { + await transaction.commit(); + } return; } @@ -6461,7 +6493,9 @@ ${numbered}`; } if (stockReleaseMap.size === 0) { - await transaction.commit(); + if (!externalTransaction) { + await transaction.commit(); + } return; } @@ -6482,12 +6516,16 @@ ${numbered}`; } } - await transaction.commit(); + if (!externalTransaction) { + await transaction.commit(); + } } catch (error) { - try { - await transaction.rollback(); - } catch (rollbackError) { - ctx.logger.error('[PendingOrderService.releaseCreationLockForCancel] 回滚失败', rollbackError); + if (!externalTransaction) { + try { + await transaction.rollback(); + } catch (rollbackError) { + ctx.logger.error('[PendingOrderService.releaseCreationLockForCancel] 回滚失败', rollbackError); + } } throw error; } diff --git a/app/service/systems/order_storage_allocation.js b/app/service/systems/order_storage_allocation.js index 81257d0..920740c 100644 --- a/app/service/systems/order_storage_allocation.js +++ b/app/service/systems/order_storage_allocation.js @@ -832,10 +832,12 @@ class OrderStorageAllocationService extends MainService { as: 'locationType', required: true, attributes: [ 'id', 'type_code', 'type_name', 'allow_allocation', 'is_active' ], - where: { - allow_allocation: 1, - is_active: 1, - }, + ...(allowStorageLocation ? {} : { + where: { + allow_allocation: 1, + is_active: 1, + }, + }), }, ], }, @@ -851,6 +853,7 @@ class OrderStorageAllocationService extends MainService { stockIdCount: stockIds.length, stockIdSample: stockIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), storageRowCount: Array.isArray(storageRows) ? storageRows.length : 0, + allowStorageLocation, }); const storageRowsByStockId = new Map(); @@ -1057,15 +1060,19 @@ class OrderStorageAllocationService extends MainService { }); if (candidateStorageRows.length === 0) { - shortageDiagnostics = await diagnoseStorageTypeRestriction({ - ctx, - Op, - warehouseId, - stockId, - transaction, - cache: shortageReasonCache, - }); - shortageReason = String(shortageDiagnostics.reason || '').trim(); + shortageDiagnostics = allowStorageLocation + ? null + : await diagnoseStorageTypeRestriction({ + ctx, + Op, + warehouseId, + stockId, + transaction, + cache: shortageReasonCache, + }); + shortageReason = shortageDiagnostics + ? String(shortageDiagnostics.reason || '').trim() + : ''; writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 无候选库位,标记缺货原因', { orderId, @@ -2143,13 +2150,16 @@ class OrderStorageAllocationService extends MainService { }; } - const transaction = await ctx.model.transaction(); + // 支持外部事务:由调用方(如取消订单流程)传入时复用,保证"取消+释放"原子生效 + const externalTransaction = data && data.transaction ? data.transaction : null; + const transaction = externalTransaction || await ctx.model.transaction(); const { Op } = app.Sequelize; const now = new Date(); writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 事务已创建', { warehouseId, orderIds, + hasExternalTransaction: Boolean(externalTransaction), }); try { @@ -2228,7 +2238,9 @@ class OrderStorageAllocationService extends MainService { }); if (eligibleOrderIds.length === 0) { - await transaction.commit(); + if (!externalTransaction) { + await transaction.commit(); + } return { code: 200, message: '没有需要取消分配的订单', @@ -2307,7 +2319,9 @@ class OrderStorageAllocationService extends MainService { } if (cancellableOrderIds.length === 0) { - await transaction.commit(); + if (!externalTransaction) { + await transaction.commit(); + } return { code: 200, message: '没有需要取消分配的订单', @@ -2514,7 +2528,9 @@ class OrderStorageAllocationService extends MainService { stock_unlock_summary: [], }; - await transaction.commit(); + if (!externalTransaction) { + await transaction.commit(); + } writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 事务提交完成', { warehouseId, @@ -2529,17 +2545,19 @@ class OrderStorageAllocationService extends MainService { data: responseData, }; } catch (error) { - writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 发生异常,准备回滚事务', { - warehouseId, - orderIds, - error, - }); - await transaction.rollback(); - writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 事务回滚完成', { - warehouseId, - orderIds, - error, - }); + if (!externalTransaction) { + writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 发生异常,准备回滚事务', { + warehouseId, + orderIds, + error, + }); + await transaction.rollback(); + writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 事务回滚完成', { + warehouseId, + orderIds, + error, + }); + } throw error; } } diff --git a/test/app/service/systems/order_storage_allocation.test.js b/test/app/service/systems/order_storage_allocation.test.js index 720c13c..fd895ee 100644 --- a/test/app/service/systems/order_storage_allocation.test.js +++ b/test/app/service/systems/order_storage_allocation.test.js @@ -265,6 +265,7 @@ function createHarness(options = {}) { Storage: { async findAll(options = {}) { captures.storageFindAllWhere = options.where; + captures.storageFindAllInclude = options.include; return storageRows.filter(row => matchesWhere(row, options.where)).map(row => ({ ...row })); }, }, @@ -540,6 +541,118 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => { assert.equal(orders[1].storage_status, 'fin'); }); + it('should ignore location type restriction when allow_storage_location is true', async () => { + const { service, captures } = createHarness({ + orders: [ + { id: 901, warehouse_id: 100000, storage_status: 'none', order_flag: '', step: 2 }, + ], + orderItems: [ + { id: 9011, order_id: 901, stock_id: 9011, plan_qty: 1, order_line_no: '1' }, + ], + stockRows: [ + { id: 9011, item_code: 'SKU-9011', item_name: '测试商品9011', warehouse_id: 100000, deleted_at: null, is_valid: 'Y', locked_quantity: 0 }, + ], + storageRows: [ + { + id: 90101, + warehouse_id: 100000, + stock_id: 9011, + is_enabled: 1, + delete_at: null, + available_quantity: 1, + quantity: 1, + locked_quantity: 0, + production_date: null, + inbound_time: '2026-04-15 08:00:00', + space_id: 90501, + space: { + id: 90501, + space_code: 'ST-901', + custom_name: '受限存储位', + is_preferred_pick: false, + locationType: { + id: 9, + allow_allocation: 0, + is_active: 0, + }, + }, + }, + ], + }); + + const result = await service.allocateStorage({ + allow_storage_location: true, + order_ids: [ 901 ], + }); + + assert.equal(result.code, 200); + assert.equal(result.data.allocated_order_ids.length, 1); + + const locationTypeInclude = captures.storageFindAllInclude + && captures.storageFindAllInclude[0] + && captures.storageFindAllInclude[0].include + && captures.storageFindAllInclude[0].include[0]; + assert.ok(locationTypeInclude, 'locationType include 应存在'); + assert.equal(Object.prototype.hasOwnProperty.call(locationTypeInclude, 'where'), false); + }); + + it('should keep location type restriction when allow_storage_location is false', async () => { + const { service, captures } = createHarness({ + orders: [ + { id: 902, warehouse_id: 100000, storage_status: 'none', order_flag: '', step: 2 }, + ], + orderItems: [ + { id: 9021, order_id: 902, stock_id: 9021, plan_qty: 1, order_line_no: '1' }, + ], + stockRows: [ + { id: 9021, item_code: 'SKU-9021', item_name: '测试商品9021', warehouse_id: 100000, deleted_at: null, is_valid: 'Y', locked_quantity: 0 }, + ], + storageRows: [ + { + id: 90201, + warehouse_id: 100000, + stock_id: 9021, + is_enabled: 1, + delete_at: null, + available_quantity: 1, + quantity: 1, + locked_quantity: 0, + production_date: null, + inbound_time: '2026-04-15 08:00:00', + space_id: 90502, + space: { + id: 90502, + space_code: 'ST-902', + custom_name: '存储位902', + is_preferred_pick: false, + locationType: { + id: 1, + allow_allocation: 1, + is_active: 1, + }, + }, + }, + ], + }); + + const result = await service.allocateStorage({ + allow_storage_location: false, + order_ids: [ 902 ], + }); + + assert.equal(result.code, 200); + + const locationTypeInclude = captures.storageFindAllInclude + && captures.storageFindAllInclude[0] + && captures.storageFindAllInclude[0].include + && captures.storageFindAllInclude[0].include[0]; + assert.ok(locationTypeInclude, 'locationType include 应存在'); + assert.deepEqual(locationTypeInclude.where, { + allow_allocation: 1, + is_active: 1, + }); + }); + it('should skip cancelled orders when allocating storage', async () => { const { service, captures, orders } = createHarness({ orders: [ From d6d7b23f52a7a0bda4bb39ac6cf12a8294316baf Mon Sep 17 00:00:00 2001 From: liufumingren Date: Thu, 27 Aug 2026 23:42:22 +0800 Subject: [PATCH 287/550] =?UTF-8?q?feat(order):=20=E8=AE=A2=E5=8D=95?= =?UTF-8?q?=E5=AF=BC=E5=87=BA=E6=94=AF=E6=8C=81=E5=B9=B6=E5=8F=91=E5=88=86?= =?UTF-8?q?=E9=A1=B5=E6=9F=A5=E8=AF=A2=E3=80=81=E5=A4=9Asheet=E7=BB=AD?= =?UTF-8?q?=E5=86=99=E3=80=81=E8=A1=A8=E5=A4=B4=E5=88=97=E7=99=BD=E5=90=8D?= =?UTF-8?q?=E5=8D=95=E4=B8=8E=E4=B8=8A=E4=BC=A0=E5=A4=A7=E5=B0=8F=E4=B8=8A?= =?UTF-8?q?=E9=99=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/systemMethods/order/index.js | 8 + app/service/systems/order_export.js | 621 +++++++++++++++-------- app/service/systems/upload.js | 22 +- 3 files changed, 445 insertions(+), 206 deletions(-) diff --git a/app/service/systemMethods/order/index.js b/app/service/systemMethods/order/index.js index 278e43a..756d512 100644 --- a/app/service/systemMethods/order/index.js +++ b/app/service/systemMethods/order/index.js @@ -32,6 +32,8 @@ class OrderIndexService extends OrderBaseService { * @param {string} [data.module_name] 订单模块名(下划线写法)。 * @param {string} [data.export_mode] 导出模式:waybill(默认,按运单展开)或 item(按商品明细展开)。 * @param {string} [data.exportMode] 导出模式(驼峰写法)。 + * @param {Array} [data.export_columns] 导出表头字段白名单(中文表头数组),不传或空数组输出全部列;非法表头会报错。 + * @param {Array} [data.exportColumns] 导出表头字段白名单(驼峰写法)。 * @param {Object} [data.where] 查询条件。 * @param {Object} [data.sort] 排序参数。 * @return {Promise} 统一成功包装响应。 @@ -45,6 +47,8 @@ class OrderIndexService extends OrderBaseService { module_name: moduleNameSnake, export_mode: exportModeSnake, exportMode: exportModeCamel, + export_columns: exportColumnsSnake, + exportColumns: exportColumnsCamel, where, sort, } = requestData; @@ -78,10 +82,14 @@ class OrderIndexService extends OrderBaseService { }); const exportMode = exportModeSnake || exportModeCamel || ''; + const exportColumns = Array.isArray(exportColumnsSnake) + ? exportColumnsSnake + : (Array.isArray(exportColumnsCamel) ? exportColumnsCamel : []); const result = await this.service.systems.orderExport.exportOrders({ tableType, moduleName: module, export_mode: exportMode, + export_columns: exportColumns, where: this.isPlainObject(where) ? { ...where } : {}, sort: this.isPlainObject(sort) ? { ...sort } : {}, onProgress: async progress => { diff --git a/app/service/systems/order_export.js b/app/service/systems/order_export.js index 4951545..0a777bc 100644 --- a/app/service/systems/order_export.js +++ b/app/service/systems/order_export.js @@ -8,7 +8,10 @@ const path = require('node:path'); const ExcelJS = require('exceljs'); const OrderBaseService = require('../systemMethods/order/base'); -const DEFAULT_EXPORT_PAGE_SIZE = 200; +const DEFAULT_EXPORT_PAGE_SIZE = 1000; +const ORDER_EXPORT_QUERY_CONCURRENCY = 2; +const ORDER_EXPORT_MAX_ROWS_PER_SHEET = 1000000; +const ORDER_EXPORT_UPLOAD_MAX_SIZE_BYTES = 1024 * 1024 * 1024; // 订单导出上传文件上限 1GB const ORDER_EXPORT_WORKSHEET_NAME = '订单导出'; const ORDER_EXPORT_ALLOWED_TABLE_TYPES = new Set([ 'current', 'history', 'dispatch', 'outsourced' ]); const ORDER_EXPORT_MODULE_MAP = Object.freeze({ @@ -118,6 +121,14 @@ const ORDER_EXPORT_ITEM_COLUMNS = Object.freeze([ { header: '归档时间', key: 'archive_time', width: 20 }, ]); +/** 全部可导出表头字段(waybill 与 item 两种模式的并集,用于入参校验) */ +const ORDER_EXPORT_ALL_COLUMN_HEADERS = Object.freeze( + new Set([ + ...ORDER_EXPORT_COLUMNS.map(column => column.header), + ...ORDER_EXPORT_ITEM_COLUMNS.map(column => column.header), + ]) +); + /** 订单状态中文翻译映射 */ const ORDER_STATUS_LABELS = Object.freeze({ status: { @@ -251,11 +262,45 @@ class OrderExportService extends OrderBaseService { /** * 获取订单导出列配置。 * @param {string} [mode='waybill'] 导出模式:'waybill'(按运单展开)或 'item'(按商品明细展开)。 + * @param {Array} [selectedHeaders=[]] 表头字段白名单(中文);不传/空数组返回全部列。 * @return {Array} 导出列配置。 */ - getOrderExportColumns(mode = 'waybill') { + getOrderExportColumns(mode = 'waybill', selectedHeaders = []) { const columns = mode === 'item' ? ORDER_EXPORT_ITEM_COLUMNS : ORDER_EXPORT_COLUMNS; - return columns.map(column => ({ ...column })); + const safeHeaders = Array.isArray(selectedHeaders) ? selectedHeaders : []; + const headerSet = new Set( + safeHeaders.map(header => String(header || '').trim()).filter(Boolean) + ); + if (headerSet.size === 0) { + return columns.map(column => ({ ...column })); + } + return columns + .filter(column => headerSet.has(column.header)) + .map(column => ({ ...column })); + } + + /** + * 校验并规范导出表头字段入参(中文表头数组)。 + * 不传/空数组返回空数组(表示输出全部列);存在非法表头时抛错。 + * @param {Array|*} rawColumns 原始入参。 + * @return {Array} 去重后的表头数组。 + */ + normalizeExportColumns(rawColumns) { + if (!Array.isArray(rawColumns)) { + return []; + } + + const selectedHeaders = [ ...new Set( + rawColumns.map(header => String(header || '').trim()).filter(Boolean) + ) ]; + const invalidHeaders = selectedHeaders.filter( + header => !ORDER_EXPORT_ALL_COLUMN_HEADERS.has(header) + ); + if (invalidHeaders.length > 0) { + throw new Error(`不支持的导出表头字段: ${invalidHeaders.join(', ')}`); + } + + return selectedHeaders; } /** @@ -330,7 +375,7 @@ class OrderExportService extends OrderBaseService { /** * 映射订单导出数据行。 - * - waybill 模式:按运单号展开,每个运单一组。 + * - waybill 模式:按运单号展开,每个运单一组;商品种数/件数仅主单号行体现,子单号行置 0。 * - item 模式:按商品明细展开,每个商品一行;运单信息汇总填充。 * @param {Object} orderRow 订单行。 * @param {Object} [context] 导出上下文,包含批量查询的辅助数据。 @@ -507,20 +552,26 @@ class OrderExportService extends OrderBaseService { }]; } - return expressList.map(exp => ({ - ...commonFields, - items_detail: this.normalizeExportCellValue(itemsDetail), - waybill_code: exp.waybill_code || '', - business_type: Number(exp.business_key) === 1 ? '主单号' : '子单号', - logistics_interface_name: this.normalizeExportCellValue(exp.logistics_interface_name), - package_material_id: exp.package_material_id != null ? Number(exp.package_material_id) : '', - package_material_code: this.normalizeExportCellValue( - exp.package_material_id != null ? (safePackageMaterialMap.get(Number(exp.package_material_id)) || '') : '' - ), - package_material_name: this.normalizeExportCellValue(exp.package_material_name_snapshot), - waybill_allocated_at: formatDateSafe(exp.create_at), - weighing_weight: exp.weighing_weight != null ? Number(exp.weighing_weight) : '', - })); + return expressList.map(exp => { + const isMainWaybill = Number(exp.business_key) === 1; + return { + ...commonFields, + items_detail: this.normalizeExportCellValue(itemsDetail), + // 商品种数/件数为订单级数据,仅主单号行体现;子单号行置 0,避免与主单号重复 + items_count: isMainWaybill ? commonFields.items_count : 0, + items_total: isMainWaybill ? commonFields.items_total : 0, + waybill_code: exp.waybill_code || '', + business_type: isMainWaybill ? '主单号' : '子单号', + logistics_interface_name: this.normalizeExportCellValue(exp.logistics_interface_name), + package_material_id: exp.package_material_id != null ? Number(exp.package_material_id) : '', + package_material_code: this.normalizeExportCellValue( + exp.package_material_id != null ? (safePackageMaterialMap.get(Number(exp.package_material_id)) || '') : '' + ), + package_material_name: this.normalizeExportCellValue(exp.package_material_name_snapshot), + waybill_allocated_at: formatDateSafe(exp.create_at), + weighing_weight: exp.weighing_weight != null ? Number(exp.weighing_weight) : '', + }; + }); } /** @@ -557,6 +608,7 @@ class OrderExportService extends OrderBaseService { key: uploadKey, category: 'document', mimetype: 'xls,xlsx,csv', + maxSizeBytes: ORDER_EXPORT_UPLOAD_MAX_SIZE_BYTES, }); let fileRecord = null; @@ -586,13 +638,231 @@ class OrderExportService extends OrderBaseService { }; } + /** + * 构建单个导出页:分页查询订单 + 批量富化 + 映射导出行。 + * @param {Object} options 分页构建参数。 + * @param {number} options.page 页码(从 1 开始)。 + * @param {number} options.pageSize 分页大小。 + * @param {Object} options.queryWhere 查询条件。 + * @param {Array>} options.order 排序参数。 + * @param {Object} options.orderModel 订单头模型。 + * @param {Object} options.target 导出目标。 + * @param {number|string} options.warehouseId 仓库ID。 + * @param {string} options.mode 导出模式:'waybill' 或 'item'。 + * @return {Promise<{exportRows: Array, orderCount: number}>} 导出行数组与订单数。 + */ + async buildOrderExportPage(options = {}) { + const safeOptions = this.isPlainObject(options) ? options : {}; + const { + page, + pageSize, + queryWhere, + order, + orderModel, + target, + warehouseId, + mode, + } = safeOptions; + + const rows = await orderModel.findAll({ + where: queryWhere, + limit: pageSize, + offset: (page - 1) * pageSize, + order, + raw: true, + }); + + if (!Array.isArray(rows) || rows.length === 0) { + return { exportRows: [], orderCount: 0 }; + } + + const normalizedRows = rows.map(row => + this.normalizeOrderListItem(this.toPlainRow(row)) + ); + const rowsWithWaveIndex = await this.attachOrderWaveIndex(normalizedRows); + + const orderIds = rowsWithWaveIndex.map(r => Number(r.id || 0)).filter(id => id > 0); + + // 批量查询商品明细(wms_order_items) + const itemsMap = new Map(); + if (orderIds.length > 0) { + try { + const itemsModel = await this.getOrderItemsModelByTableType(target.tableType, warehouseId); + const itemsRows = await itemsModel.findAll({ + where: { order_id: { [this.app.Sequelize.Op.in]: orderIds } }, + attributes: [ 'order_id', 'item_name', 'plan_qty', 'stock_id' ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + for (const item of (Array.isArray(itemsRows) ? itemsRows : [])) { + const oid = Number(item.order_id || 0); + if (oid > 0) { + if (!itemsMap.has(oid)) { + itemsMap.set(oid, []); + } + itemsMap.get(oid).push(item); + } + } + } catch (err) { + this.app.logger.warn(`[order_export] 批量查询订单商品明细失败: ${err.message}`); + } + } + + // 批量查询仓库商品名称、条码与图片(复用 getStockDetails 缓存) + const stockNameMap = new Map(); + const barcodeMap = new Map(); + const imageUrlMap = new Map(); + if (itemsMap.size > 0 && this.ctx && this.ctx.model && this.ctx.model.StockWarehouse) { + try { + const stockIds = [ + ...new Set( + [ ...itemsMap.values() ] + .flat() + .map(item => Number(item.stock_id || 0)) + .filter(id => id > 0) + ), + ]; + if (stockIds.length > 0) { + const stockDetails = await this.ctx.service.systems.stockWarehouse.getStockDetails( + stockIds, + { warehouseId } + ); + for (const detail of stockDetails) { + const sid = Number(detail.id || 0); + if (sid > 0) { + stockNameMap.set(sid, String(detail.item_name || '').trim()); + // 从 getStockDetails 的 barcodes 中提取条码并转为逗号拼接 + const barcodesRaw = Array.isArray(detail.barcodes) + ? detail.barcodes.map(bc => String(bc.barcode || '').trim()).filter(Boolean) + : []; + if (barcodesRaw.length > 0) { + barcodeMap.set(sid, [ ...new Set(barcodesRaw) ].join(', ')); + } + // 图片字段(有图片标记但实际 URL 需要额外查询) + if (detail.is_images === 'Y') { + imageUrlMap.set(sid, ''); + } + } + } + } + } catch (err) { + this.app.logger.warn(`[order_export] 批量查询商品详情失败: ${err.message}`); + } + } + + // 批量查询货主备注(wms_store_warehouse.store_remask) + const storeRemarkMap = new Map(); + if (orderIds.length > 0 && this.ctx && this.ctx.model && this.ctx.model.StoreWarehouse) { + try { + const storeIds = [ + ...new Set( + rowsWithWaveIndex + .map(r => Number(r.store_id || 0)) + .filter(id => id > 0) + ), + ]; + if (storeIds.length > 0) { + const swRows = await this.ctx.model.StoreWarehouse.findAll({ + where: { + store_id: { [this.app.Sequelize.Op.in]: storeIds }, + warehouse_id: warehouseId, + }, + attributes: [ 'store_id', 'store_remask' ], + raw: true, + }); + for (const sw of (Array.isArray(swRows) ? swRows : [])) { + const sid = Number(sw.store_id || 0); + if (sid > 0 && !storeRemarkMap.has(sid)) { + storeRemarkMap.set(sid, String(sw.store_remask || '').trim()); + } + } + } + } catch (err) { + this.app.logger.warn(`[order_export] 批量查询货主备注失败: ${err.message}`); + } + } + + // 批量查询运单数据(wms_order_express),按订单ID分组 + const expressMap = new Map(); + if (orderIds.length > 0 && this.ctx && this.ctx.model && this.ctx.model.OrderExpress) { + try { + const expressRows = await this.ctx.model.OrderExpress.findAll({ + where: { + order_id: { [this.app.Sequelize.Op.in]: orderIds }, + warehouse_id: warehouseId, + }, + attributes: [ 'id', 'order_id', 'waybill_code', 'business_key', 'logistics_interface_name', 'package_material_id', 'package_material_name_snapshot', 'create_at', 'weighing_weight' ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + for (const exp of (Array.isArray(expressRows) ? expressRows : [])) { + const oid = Number(exp.order_id || 0); + if (oid > 0) { + if (!expressMap.has(oid)) { + expressMap.set(oid, []); + } + expressMap.get(oid).push(exp); + } + } + } catch (err) { + this.app.logger.warn(`[order_export] 批量查询运单数据失败: ${err.message}`); + } + } + + // 批量查询包材编码(wms_package_material),按 package_material_id 分组 + const packageMaterialMap = new Map(); + if (expressMap.size > 0 && this.ctx && this.ctx.model && this.ctx.model.PackageMaterial) { + try { + const materialIds = [ + ...new Set( + [ ...expressMap.values() ] + .flat() + .map(exp => Number(exp.package_material_id || 0)) + .filter(id => id > 0) + ), + ]; + if (materialIds.length > 0) { + const pmRows = await this.ctx.model.PackageMaterial.findAll({ + where: { id: { [this.app.Sequelize.Op.in]: materialIds } }, + attributes: [ 'id', 'material_code' ], + raw: true, + }); + for (const pm of (Array.isArray(pmRows) ? pmRows : [])) { + const pid = Number(pm.id || 0); + if (pid > 0 && !packageMaterialMap.has(pid)) { + packageMaterialMap.set(pid, String(pm.material_code || '').trim()); + } + } + } + } catch (err) { + this.app.logger.warn(`[order_export] 批量查询包材编码失败: ${err.message}`); + } + } + + const exportContext = { itemsMap, storeRemarkMap, stockNameMap, barcodeMap, imageUrlMap, expressMap, packageMaterialMap }; + + const exportRows = []; + for (const row of rowsWithWaveIndex) { + const rowExportRows = this.mapOrderExportRow(row, exportContext, mode); + exportRows.push(...rowExportRows); + } + + return { exportRows, orderCount: rowsWithWaveIndex.length }; + } + /** * 导出订单列表。 + * 查询采用 ORDER_EXPORT_QUERY_CONCURRENCY 个 worker 并发分页查询, + * 先查询完成的页先入 FIFO 队列,由单一串行 writer 按入队顺序写入文件(行序按完成顺序,非列表顺序)。 + * 单个 sheet 最多写入 ORDER_EXPORT_MAX_ROWS_PER_SHEET 行数据,超出后自动新建下一个 sheet 续写。 * @param {Object} options 导出参数。 * @param {string} [options.tableType] 表类型。 * @param {string} [options.moduleName] 模块名。 * @param {Object} [options.where] 查询条件。 * @param {Object} [options.sort] 排序参数。 + * @param {string} [options.export_mode] 导出模式:waybill 或 item。 + * @param {Array} [options.export_columns] 导出表头字段白名单(中文表头数组),不传输出全部列。 + * @param {Array} [options.exportColumns] 导出表头字段白名单(驼峰写法)。 * @param {Function} [options.onProgress] 进度回调。 * @return {Promise} 上传结果与统计信息。 */ @@ -676,10 +946,35 @@ class OrderExportService extends OrderBaseService { const worksheet = workbook.addWorksheet(ORDER_EXPORT_WORKSHEET_NAME); const exportMode = String(safeOptions.export_mode || '').trim() || 'waybill'; const mode = exportMode === 'item' ? 'item' : 'waybill'; - worksheet.columns = this.getOrderExportColumns(mode); + const selectedHeaders = this.normalizeExportColumns( + safeOptions.export_columns ?? safeOptions.exportColumns + ); + const resolvedColumns = this.getOrderExportColumns(mode, selectedHeaders); + worksheet.columns = resolvedColumns; let currentCount = 0; - let page = 1; + // 分 sheet 写入:每个 sheet 最多 ORDER_EXPORT_MAX_ROWS_PER_SHEET 行数据, + // 超出后提交当前 sheet 并新建下一个 sheet(名称:订单导出、订单导出2、…),新 sheet 同样带表头。 + let currentWorksheet = worksheet; + let currentSheetIndex = 1; + let currentSheetRows = 0; + + const ensureSheetCapacity = () => { + if (currentSheetRows < ORDER_EXPORT_MAX_ROWS_PER_SHEET) { + return; + } + currentWorksheet.commit(); + currentSheetIndex += 1; + currentWorksheet = workbook.addWorksheet(`${ORDER_EXPORT_WORKSHEET_NAME}${currentSheetIndex}`); + currentWorksheet.columns = resolvedColumns; + currentSheetRows = 0; + }; + + const writeExportRow = exportRow => { + ensureSheetCapacity(); + currentWorksheet.addRow(exportRow).commit(); + currentSheetRows += 1; + }; try { await progressHandler({ @@ -690,205 +985,124 @@ class OrderExportService extends OrderBaseService { message: totalCount > 0 ? `已命中 ${totalCount} 条订单,开始导出` : '未命中数据,开始生成空文件', }); - while (currentCount < totalCount) { - const rows = await orderModel.findAll({ - where: queryWhere, - limit: pageSize, - offset: (page - 1) * pageSize, - order, - raw: true, - }); + const totalPages = totalCount > 0 ? Math.ceil(totalCount / pageSize) : 0; - if (!Array.isArray(rows) || rows.length === 0) { - break; + // FIFO 队列:各 worker 查询完成的页按完成顺序入队,由单一 writer 串行落盘 + const exportPageQueue = []; + let exportQueueHead = 0; + let pagesCompleted = 0; + let queueDone = false; + let queueWake = null; + let firstError = null; + + const wakeWriter = () => { + if (queueWake) { + const resolveWake = queueWake; + queueWake = null; + resolveWake(); } + }; + const enqueueExportRows = exportRows => { + if (Array.isArray(exportRows) && exportRows.length > 0) { + exportPageQueue.push(exportRows); + wakeWriter(); + } + }; + const finishExportQueue = () => { + queueDone = true; + wakeWriter(); + }; + const waitForQueueWake = () => new Promise(resolve => { + queueWake = resolve; + }); - const normalizedRows = rows.map(row => - this.normalizeOrderListItem(this.toPlainRow(row)) - ); - const rowsWithWaveIndex = await this.attachOrderWaveIndex(normalizedRows); + // 串行 writer:按入队顺序写入 ExcelJS 流,避免并发 commit 导致的行序竞态 + const writerLoop = (async () => { + try { + for (;;) { + while (exportQueueHead < exportPageQueue.length) { + const exportRows = exportPageQueue[exportQueueHead]; + exportQueueHead += 1; + for (const exportRow of exportRows) { + writeExportRow(exportRow); + } + } + if (exportQueueHead > 0) { + if (exportQueueHead >= exportPageQueue.length) { + exportPageQueue.length = 0; + exportQueueHead = 0; + } else { + exportPageQueue.splice(0, exportQueueHead); + exportQueueHead = 0; + } + } + if (queueDone || firstError) { + break; + } + await waitForQueueWake(); + } + } catch (err) { + if (!firstError) { + firstError = err; + } + queueDone = true; + wakeWriter(); + } + })(); - const orderIds = rowsWithWaveIndex.map(r => Number(r.id || 0)).filter(id => id > 0); - - // 批量查询商品明细(wms_order_items) - const itemsMap = new Map(); - if (orderIds.length > 0) { + // 有界并发查询:限制 2 个 worker,先查询完成的页先入队 + let nextPage = 1; + const runWorker = async () => { + while (!firstError) { + const page = nextPage; + nextPage += 1; + if (page > totalPages) { + break; + } try { - const itemsModel = await this.getOrderItemsModelByTableType(target.tableType, warehouseId); - const itemsRows = await itemsModel.findAll({ - where: { order_id: { [this.app.Sequelize.Op.in]: orderIds } }, - attributes: [ 'order_id', 'item_name', 'plan_qty', 'stock_id' ], - order: [[ 'id', 'ASC' ]], - raw: true, + const pageResult = await this.buildOrderExportPage({ + page, + pageSize, + queryWhere, + order, + orderModel, + target, + warehouseId, + mode, }); - for (const item of (Array.isArray(itemsRows) ? itemsRows : [])) { - const oid = Number(item.order_id || 0); - if (oid > 0) { - if (!itemsMap.has(oid)) { - itemsMap.set(oid, []); - } - itemsMap.get(oid).push(item); - } - } - } catch (err) { - this.app.logger.warn(`[order_export] 批量查询订单商品明细失败: ${err.message}`); - } - } - - // 批量查询仓库商品名称、条码与图片(复用 getStockDetails 缓存) - const stockNameMap = new Map(); - const barcodeMap = new Map(); - const imageUrlMap = new Map(); - if (itemsMap.size > 0 && this.ctx && this.ctx.model && this.ctx.model.StockWarehouse) { - try { - const stockIds = [ - ...new Set( - [ ...itemsMap.values() ] - .flat() - .map(item => Number(item.stock_id || 0)) - .filter(id => id > 0) - ), - ]; - if (stockIds.length > 0) { - const stockDetails = await this.ctx.service.systems.stockWarehouse.getStockDetails( - stockIds, - { warehouseId } - ); - for (const detail of stockDetails) { - const sid = Number(detail.id || 0); - if (sid > 0) { - stockNameMap.set(sid, String(detail.item_name || '').trim()); - // 从 getStockDetails 的 barcodes 中提取条码并转为逗号拼接 - const barcodesRaw = Array.isArray(detail.barcodes) - ? detail.barcodes.map(bc => String(bc.barcode || '').trim()).filter(Boolean) - : []; - if (barcodesRaw.length > 0) { - barcodeMap.set(sid, [ ...new Set(barcodesRaw) ].join(', ')); - } - // 图片字段(有图片标记但实际 URL 需要额外查询) - if (detail.is_images === 'Y') { - imageUrlMap.set(sid, ''); - } - } - } - } - } catch (err) { - this.app.logger.warn(`[order_export] 批量查询商品详情失败: ${err.message}`); - } - } - - // 批量查询货主备注(wms_store_warehouse.store_remask) - const storeRemarkMap = new Map(); - if (orderIds.length > 0 && this.ctx && this.ctx.model && this.ctx.model.StoreWarehouse) { - try { - const storeIds = [ - ...new Set( - rowsWithWaveIndex - .map(r => Number(r.store_id || 0)) - .filter(id => id > 0) - ), - ]; - if (storeIds.length > 0) { - const swRows = await this.ctx.model.StoreWarehouse.findAll({ - where: { - store_id: { [this.app.Sequelize.Op.in]: storeIds }, - warehouse_id: warehouseId, - }, - attributes: [ 'store_id', 'store_remask' ], - raw: true, - }); - for (const sw of (Array.isArray(swRows) ? swRows : [])) { - const sid = Number(sw.store_id || 0); - if (sid > 0 && !storeRemarkMap.has(sid)) { - storeRemarkMap.set(sid, String(sw.store_remask || '').trim()); - } - } - } - } catch (err) { - this.app.logger.warn(`[order_export] 批量查询货主备注失败: ${err.message}`); - } - } - - // 批量查询运单数据(wms_order_express),按订单ID分组 - const expressMap = new Map(); - if (orderIds.length > 0 && this.ctx && this.ctx.model && this.ctx.model.OrderExpress) { - try { - const expressRows = await this.ctx.model.OrderExpress.findAll({ - where: { - order_id: { [this.app.Sequelize.Op.in]: orderIds }, - warehouse_id: warehouseId, - }, - attributes: [ 'id', 'order_id', 'waybill_code', 'business_key', 'logistics_interface_name', 'package_material_id', 'package_material_name_snapshot', 'create_at', 'weighing_weight' ], - order: [[ 'id', 'ASC' ]], - raw: true, + enqueueExportRows(pageResult.exportRows); + currentCount += pageResult.orderCount; + pagesCompleted += 1; + await progressHandler({ + status: 'running', + progress: Math.min(99, Math.max(5, Math.round((currentCount / Math.max(totalCount, 1)) * 90))), + currentCount, + totalCount, + message: `已完成 ${currentCount}/${totalCount} 条订单查询(${pagesCompleted}/${totalPages} 页)`, }); - for (const exp of (Array.isArray(expressRows) ? expressRows : [])) { - const oid = Number(exp.order_id || 0); - if (oid > 0) { - if (!expressMap.has(oid)) { - expressMap.set(oid, []); - } - expressMap.get(oid).push(exp); - } - } } catch (err) { - this.app.logger.warn(`[order_export] 批量查询运单数据失败: ${err.message}`); - } - } - - // 批量查询包材编码(wms_package_material),按 package_material_id 分组 - const packageMaterialMap = new Map(); - if (expressMap.size > 0 && this.ctx && this.ctx.model && this.ctx.model.PackageMaterial) { - try { - const materialIds = [ - ...new Set( - [ ...expressMap.values() ] - .flat() - .map(exp => Number(exp.package_material_id || 0)) - .filter(id => id > 0) - ), - ]; - if (materialIds.length > 0) { - const pmRows = await this.ctx.model.PackageMaterial.findAll({ - where: { id: { [this.app.Sequelize.Op.in]: materialIds } }, - attributes: [ 'id', 'material_code' ], - raw: true, - }); - for (const pm of (Array.isArray(pmRows) ? pmRows : [])) { - const pid = Number(pm.id || 0); - if (pid > 0 && !packageMaterialMap.has(pid)) { - packageMaterialMap.set(pid, String(pm.material_code || '').trim()); - } - } + if (!firstError) { + firstError = err; } - } catch (err) { - this.app.logger.warn(`[order_export] 批量查询包材编码失败: ${err.message}`); + break; } } + }; - const exportContext = { itemsMap, storeRemarkMap, stockNameMap, barcodeMap, imageUrlMap, expressMap, packageMaterialMap }; + const workers = Array.from( + { length: Math.min(ORDER_EXPORT_QUERY_CONCURRENCY, totalPages) }, + () => runWorker() + ); - for (const row of rowsWithWaveIndex) { - const exportRows = this.mapOrderExportRow(row, exportContext, mode); - for (const exportRow of exportRows) { - worksheet.addRow(exportRow).commit(); - } - } + await Promise.all(workers); + finishExportQueue(); + await writerLoop; - currentCount += rowsWithWaveIndex.length; - - await progressHandler({ - status: 'running', - progress: Math.min(99, Math.max(5, Math.round((currentCount / Math.max(totalCount, 1)) * 90))), - currentCount, - totalCount, - message: `正在导出第 ${page} 页,共 ${Math.ceil(totalCount / pageSize) || 1} 页`, - }); - - page += 1; + if (firstError) { + throw firstError; } - worksheet.commit(); + currentWorksheet.commit(); await workbook.commit(); const uploadResult = await this.uploadOrderExportFile({ @@ -913,6 +1127,7 @@ class OrderExportService extends OrderBaseService { module_name: target.defaultWhereModuleName || '', current_count: currentCount, total_count: totalCount, + sheet_count: currentSheetIndex, }; } catch (error) { const workbookStream = workbook.stream; diff --git a/app/service/systems/upload.js b/app/service/systems/upload.js index ba971f6..61297f6 100644 --- a/app/service/systems/upload.js +++ b/app/service/systems/upload.js @@ -220,6 +220,21 @@ class UploadService extends Service { policyHash, }; } + /** + * 解析单次上传的文件大小上限。 + * 优先使用调用方传入的 options.maxSizeBytes,否则回退到 cos.maxsize 配置。 + * @param {Object} options 上传选项。 + * @return {number} 文件大小上限(字节)。 + */ + resolveUploadMaxSizeBytes(options = {}) { + const requested = options && options.maxSizeBytes; + if (typeof requested === 'number' && Number.isFinite(requested) && requested > 0) { + return requested; + } + + const { maxsize } = this.getCosConfig(); + return this.parseSizeToBytes(maxsize); + } /** * 验证文件信息 * @param {Object} root0 文件信息对象 @@ -229,7 +244,7 @@ class UploadService extends Service { validateFileInfo({ fileName, fileSize }) { const { maxsize, mimetype } = this.getCosConfig(); - // 验证文件大小 + // 验证文件大小(使用 cos.maxsize 配置) const maxSizeBytes = this.parseSizeToBytes(maxsize); if (fileSize > maxSizeBytes) { throw new Error(`文件大小不能超过 ${this.formatFileSize(maxSizeBytes)}`); @@ -394,10 +409,11 @@ class UploadService extends Service { * @param {Object} options 上传选项 */ validateFile(fileStream, options = {}) { - const { maxsize, mimetype } = this.getCosConfig(); + const { mimetype } = this.getCosConfig(); const { filename, fileSize } = fileStream; - const maxSizeBytes = this.parseSizeToBytes(maxsize); + // 验证文件大小:单次上传可通过 options.maxSizeBytes 覆盖上限,否则使用 cos.maxsize 配置 + const maxSizeBytes = this.resolveUploadMaxSizeBytes(options); if (fileSize > maxSizeBytes) { throw new Error(`文件大小不能超过 ${this.formatFileSize(maxSizeBytes)}`); } From a5eba20a5e3457641f3bc255e966f91962c975ca Mon Sep 17 00:00:00 2001 From: liufumingren Date: Thu, 27 Aug 2026 23:43:41 +0800 Subject: [PATCH 288/550] =?UTF-8?q?docs(methods):=20=E5=90=8C=E6=AD=A5=20s?= =?UTF-8?q?ystem=20=E6=8E=A5=E5=8F=A3=E6=96=87=E6=A1=A3=E8=87=B3=200.3.37?= =?UTF-8?q?=20=E5=B9=B6=E8=BF=BD=E5=8A=A0=205=20=E6=9D=A1=E5=8F=98?= =?UTF-8?q?=E6=9B=B4=E8=AE=B0=E5=BD=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - order.export 新增 export_columns 导出表头白名单参数 - order.pendingOrder.allocateStorage 修复 allow_storage_location=true 未生效 - storage.entry.quickInbound 支持按绑定收货单交集直入并回写收货单入库状态 - storage.management.replenishmentDemand 新增货主筛选参数与 store_name/barcodes 响应字段 --- methods/changes/system.json | 83 +++++++++++++++++++++++++++++++++++++ methods/system.json | 74 +++++++++++++++++++++++++++++---- 2 files changed, 150 insertions(+), 7 deletions(-) diff --git a/methods/changes/system.json b/methods/changes/system.json index bf891eb..8f8ec9c 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,20 @@ [ + { + "version": "2026.08.27-order-allocateStorage-allow-storage-location", + "date": "2026-08-27", + "type": "fixed", + "summary": "order.pendingOrder.allocateStorage 修复 allow_storage_location=true 未生效:分配储位时仍强制校验库位类型 allow_allocation=1/is_active=1,存储储位被过滤。现在 allow_storage_location=true 时直接分配储位,无视库位类型的可分配/启用限制", + "methods": [ + "order.pendingOrder.allocateStorage" + ], + "notes": [ + "app/service/systems/order_storage_allocation.js allocatePicking:storageRows 查询的 locationType include where(allow_allocation:1/is_active:1)改为仅当 allowStorageLocation=false 时生效;true 时不再过滤库位类型限制", + "无候选库位时的缺货诊断 diagnoseStorageTypeRestriction 仅在 allowStorageLocation=false 时执行,避免「库位类型不可分配/未启用」被误报为缺货原因", + "可分配库存查询完成日志补充 allowStorageLocation 字段", + "同步更新 methods/system.json:order.pendingOrder.allocateStorage 描述与 allow_storage_location 参数说明" + ], + "module": "order" + }, { "version": "2026.08.27-order-export-stock-query", "date": "2026-08-27", @@ -49,6 +65,73 @@ ], "module": "storage.entry" }, + { + "version": "2026.08.27-storage-management-replenishmentDemand-owner-filter", + "date": "2026-08-27", + "type": "enhanced", + "summary": "storage.management.replenishmentDemand 新增货主筛选:store_id(单值或数组)或 where.store_id 传入,仅返回指定货主的 SKU,summary 同步只统计筛选后数据", + "methods": [ + "storage.management.replenishmentDemand" + ], + "notes": [ + "app/service/systemMethods/storage/management.js replenishmentDemand:解析 store_id / store_ids / where.store_id(单值/数组),归一化为正整数数组去重,非法值(非正整数)抛错;空值不筛选。", + "app/service/systems/storage/management.js replenishmentDemand:options.storeIds 构建 Set,组装输出循环内非命中货主 SKU 直接跳过,list 与 summary 统计口径一致(仅含筛选货主)。", + "同步更新 methods/system.json 参数文档(新增 store_id 参数说明)。" + ], + "module": "storage.management" + }, + { + "version": "2026.08.27-quickInbound-receiving-intersection", + "date": "2026-08-27", + "type": "enhanced", + "summary": "storage.entry.quickInbound 支持绑定收货单交集直入:有绑定时按 stock_id 只取收货单中剩余可入数量(actual_quantity - stored_quantity)与入库明细的较小值直入,并回写收货单明细已入库数量与收货单入库状态", + "methods": [ + "storage.entry.quickInbound" + ], + "notes": [ + "app/service/systems/storage/entry.js quickInbound:新增绑定收货单查询(wms_entry_order_receiving),按 stock_id(=收货明细 system_product_id)聚合剩余可入数量 actual_quantity - stored_quantity", + "入库明细实际直入量 = min(计划数量, 剩余可入数量);无交集商品跳过(明细 received_quantity 写 0),全部无交集或剩余为 0 时返回 400「收货单中无交集商品或剩余可入数量不足,无法快捷直入」", + "未绑定收货单保持原行为:按明细计划数量全量直入", + "存在截断/跳过明细时 isFin=false(confirmType=1, PARTFULFILLED)回传奇门/API", + "新增 _applyReceivingInboundUsage 事务内回写:行锁重读收货明细,按明细 id 升序分配本次入库量(每个明细最多分配其剩余可入数量),更新 stored_quantity(使用了多少写多少)与 storage_status(all/partial),并汇总更新收货单主表 storage_status", + "收货单主表 storage_status 按实际数量判定:全部明细 stored_quantity >= actual_quantity 才置 all;有部分入库置 partial;全部未入库置 none——收货单未全部使用所有商品时不会转为全部入库", + "入库单明细 received_quantity 改为写实际入库量(原来写计划数量)", + "响应新增 plan_quantity(计划入库总数量),total_quantity 语义改为实际入库总数量,items_count 语义改为实际入库明细条目数" + ], + "module": "storage.entry" + }, + { + "version": "2026.08.27-storage-management-replenishmentDemand-owner-barcode", + "date": "2026-08-27", + "type": "enhanced", + "summary": "storage.management.replenishmentDemand 响应 list 每项新增 store_id(货主ID)、store_name(货主名称)、barcodes(SKU 条码列表)字段", + "methods": [ + "storage.management.replenishmentDemand" + ], + "notes": [ + "app/service/systems/storage/management.js replenishmentDemand:StockWarehouse 三处查询(严格/宽松/终极兜底)attributes 均新增 store_id,stockInfoMap 记录货主ID。", + "新增货主名称查询:StoreWarehouse(store_remask 签约表备注名)优先、Store(company_name 商家公司名)兜底;新增 StockBarcode 按 stock_id 批量查询条码并分组为 barcodes: [{id, barcode}]。", + "货主与条码查询与库存查询为顺序执行(货主/条码三表在 Promise.all 内并行)。", + "响应字段:store_id (number) 货主ID;store_name (string) 货主名称;barcodes (array) 条码列表,children: id (number)/barcode (string)。", + "同步更新 methods/system.json 响应文档。" + ], + "module": "storage.management" + }, + { + "version": "2026.08.27-order-export-columns", + "date": "2026-08-27", + "type": "enhanced", + "summary": "order.export 新增 export_columns/exportColumns 导出表头字段白名单参数(中文表头数组):不传或空数组输出全部列;传入时仅输出指定列;校验枚举覆盖 waybill/item 两种模式全部 51 个中文表头,非法表头抛错并列出非法值。", + "methods": [ + "order.export" + ], + "notes": [ + "app/service/systems/order_export.js:新增 ORDER_EXPORT_ALL_COLUMN_HEADERS(waybill/item 两种模式表头并集,共 51 个);getOrderExportColumns(mode, selectedHeaders) 支持按中文表头过滤;新增 normalizeExportColumns(数组去重/trim/非法值抛错);exportOrders 读取 export_columns/exportColumns(下划线优先)并作用到初始 sheet 与自动续写的后续 sheet(resolvedColumns 复用)", + "app/service/systemMethods/order/index.js export:解构 export_columns/exportColumns 并透传数组,未传时传空数组(输出全部列)", + "methods/system.json order.export 新增 export_columns/exportColumns 参数文档:枚举全量 51 个中文表头,并标注仅 waybill 模式输出(系统订单号、外部订单号、平台单号、抓取波次号、商品明细)与仅 item 模式输出(订单ID、订单号、外部单号、波次号、仓库商品名称、商品条码、商品图片、数量)的字段" + ], + "module": "order" + }, { "version": "2026.08.26-wave-batchList-store-id-filter", "date": "2026-08-26", diff --git a/methods/system.json b/methods/system.json index 339578f..768800e 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1,8 +1,8 @@ { "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", - "version": "0.3.36", - "updatedAt": "2026-08-25", + "version": "0.3.37", + "updatedAt": "2026-08-27", "headers": [ { "name": "platform", @@ -2537,6 +2537,13 @@ "required": false, "source": "body", "description": "导出模式:waybill(默认,按运单展开,items_detail 列汇总商品)或 item(按商品明细展开,每商品一行);支持 export_mode 与 exportMode 两种写法" + }, + { + "name": "export_columns / exportColumns", + "type": "array", + "required": false, + "source": "body", + "description": "导出表头字段白名单(中文表头字符串数组,如 [\"系统订单号\",\"外部订单号\"]);不传或空数组时输出全部列。枚举(共 51 个,校验不区分导出模式):系统订单号、外部订单号、平台单号、订单ID、订单号、外部单号、订单状态、抓取波次号、波次号、波次序号、货主、平台、店铺昵称、收件人、收件人电话、省、市、区、镇、详细地址、商品明细、仓库商品名称、商品条码、商品图片、数量、物流公司、运单号、业务类型、运单接口、包材ID、包材编码、包材名称、分配时间、商品种数、商品件数、商品重量、称重重量(g)、订单金额、实收金额、创建时间、支付时间、发货时间、出库状态、复核状态、复核完成状态、配货状态、打包状态、备注、买家留言、卖家留言、归档时间。其中仅 waybill 模式输出:系统订单号、外部订单号、平台单号、抓取波次号、商品明细;仅 item 模式输出:订单ID、订单号、外部单号、波次号、仓库商品名称、商品条码、商品图片、数量;其余为两种模式通用(选了当前模式不存在的表头时该列自动忽略)。传入非法表头会报错(错误信息列出非法值);支持 export_columns 与 exportColumns 两种写法" } ], "response": [ @@ -3412,7 +3419,7 @@ }, { "method": "order.pendingOrder.allocateStorage", - "description": "按订单批量分配储位(迁移自 order.storageAllocation.allocateStorage)。这是一个异步提交接口:调用后接口立即返回受理信息(包含 request_id),后端异步执行实际的储位分配与锁定操作;仓库上下文由当前登录用户提供(ctx.user.store_id)。接口不会在同步响应中返回分配明细(如 requested_order_ids、allocated_order_ids 等),客户端可通过请求 ID 或事件/查询链路获取最终结果。已锁定订单(lock_status 非 none)会在分配流水线中被跳过(底层分配结果 skipped_orders 中记录 skipped_reason='locked')。", + "description": "按订单批量分配储位(迁移自 order.storageAllocation.allocateStorage)。这是一个异步提交接口:调用后接口立即返回受理信息(包含 request_id),后端异步执行实际的储位分配与锁定操作;仓库上下文由当前登录用户提供(ctx.user.store_id)。接口不会在同步响应中返回分配明细(如 requested_order_ids、allocated_order_ids 等),客户端可通过请求 ID 或事件/查询链路获取最终结果。已锁定订单(lock_status 非 none)会在分配流水线中被跳过(底层分配结果 skipped_orders 中记录 skipped_reason='locked')。默认仅从库位类型允许分配且启用的储位中分配;传入 allow_storage_location=true 时直接分配储位,无视库位类型的 allow_allocation/is_active 限制。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -3429,7 +3436,7 @@ "type": "boolean", "required": false, "source": "body", - "description": "是否允许使用存储储位,支持多种字段别名。" + "description": "是否允许使用存储储位,支持多种字段别名。为 true 时直接分配储位,无视库位类型的 allow_allocation/is_active 限制;缺省时仅校验可分配储位。" }, { "name": "order_ids / orderIds / ids / order_id / orderId / id", @@ -22579,7 +22586,7 @@ }, { "method": "storage.entry.quickInbound", - "description": "快捷直入(虚拟入库):将入库单所有商品按明细数量一键直入到虚拟库位(space_id=2),跳过收货/质检流程,入库单状态变为COMPLETED。仅支持 CREATED 状态的入库单;CANCELLED(已作废)、COMPLETED(已完成)、PENDING 等其他状态均拒绝操作。事务内操作:更新入库明细收货量、累加库存总量、写入库存流水、写入虚拟库位库存、变更入库单状态为 COMPLETED。事务外异步回传奇门/API。", + "description": "快捷直入(虚拟入库):将入库单商品直入到虚拟库位(space_id=2),跳过收货/质检流程。有绑定收货单时,只取收货单中与入库单明细有交集(按 stock_id 判断)且剩余可入数量(actual_quantity - stored_quantity)的商品直入,实际入库量 = min(明细计划数量, 收货单剩余可入数量),并在事务内回写收货单明细已入库数量与收货单入库状态;未绑定收货单时按明细计划数量全量直入。仅支持 CREATED 状态的入库单;CANCELLED(已作废)、COMPLETED(已完成)、PENDING 等其他状态均拒绝操作。事务内操作:更新入库明细收货量、累加库存总量、写入库存流水、写入虚拟库位库存、回写收货单明细、变更入库单状态为 COMPLETED。事务外异步回传奇门/API。", "isNeedAuth": false, "isNeedLogin": true, "headers": [], @@ -22621,13 +22628,19 @@ "name": "items_count", "type": "number", "required": true, - "description": "入库明细条目数" + "description": "实际入库明细条目数(有绑定收货单时为与收货单有交集且实际入库量大于0的明细数)" }, { "name": "total_quantity", "type": "number", "required": true, - "description": "入库总数量" + "description": "实际入库总数量(有绑定收货单时=与收货单交集部分的实际直入数量)" + }, + { + "name": "plan_quantity", + "type": "number", + "required": true, + "description": "计划入库总数量" } ], "errors": [ @@ -22654,6 +22667,14 @@ { "code": 400, "message": "请先添加入库明细" + }, + { + "code": 400, + "message": "收货单中无交集商品或剩余可入数量不足,无法快捷直入" + }, + { + "code": 400, + "message": "入库明细数量均为0,无法快捷直入" } ] }, @@ -25579,6 +25600,13 @@ "required": false, "source": "body", "description": "排序参数,支持 sortField / sortOrder。sortField 可选值:stock_id / pick_zone_quantity / storage_zone_quantity / total_demand / shortage / replenishment_needed,默认 shortage;sortOrder 可选 ASC / DESC,默认 DESC" + }, + { + "name": "store_id", + "type": "number|array", + "required": false, + "source": "body", + "description": "货主筛选:支持单值或数组(正整数),也可通过 where.store_id 传入;不传时返回全部货主;非法值(非正整数)报错" } ], "response": [ @@ -25606,6 +25634,38 @@ "required": true, "description": "SKU 名称" }, + { + "name": "store_id", + "type": "number", + "required": true, + "description": "货主ID" + }, + { + "name": "store_name", + "type": "string", + "required": true, + "description": "货主名称(货主签约表备注名优先,商家表公司名称兜底)" + }, + { + "name": "barcodes", + "type": "array", + "required": true, + "description": "SKU 条码列表", + "children": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "条码记录ID" + }, + { + "name": "barcode", + "type": "string", + "required": true, + "description": "条码内容" + } + ] + }, { "name": "pick_zone_quantity", "type": "number", From 403a73b250f06f6c3e84015f842ff655ebca94ef Mon Sep 17 00:00:00 2001 From: liufumingren Date: Thu, 27 Aug 2026 23:43:44 +0800 Subject: [PATCH 289/550] =?UTF-8?q?docs(routing):=20=E6=9B=B4=E6=96=B0=20i?= =?UTF-8?q?nbox=20=E6=9C=8D=E5=8A=A1=E5=87=BD=E6=95=B0=E6=B8=85=E5=8D=95?= =?UTF-8?q?=EF=BC=8C=E6=96=B0=E5=A2=9E=20tools.js?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - functions.js 移除 _getRecordingComputerId/_buildVideoUrl(5→3) - 新增 tools.js:getRecordingComputerId、buildVideoUrl --- AI_METHOD_ROUTING.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/AI_METHOD_ROUTING.md b/AI_METHOD_ROUTING.md index f268883..a5b88d9 100644 --- a/AI_METHOD_ROUTING.md +++ b/AI_METHOD_ROUTING.md @@ -133,8 +133,10 @@ rg "class .*Service|module.exports" app/service/qimenMethods - ping, ssoCodeToId, getStoreEmployees - app/service/inbox/ai.js (3) - callDeepSeek, getConversationHistory, processWithAI -- app/service/inbox/functions.js (5) - - registerBuiltinFunctions, register, callFunction, _getRecordingComputerId, _buildVideoUrl +- app/service/inbox/functions.js (3) + - registerBuiltinFunctions, register, callFunction +- app/service/inbox/tools.js (2) + - getRecordingComputerId, buildVideoUrl - app/service/inbox/groups.js (4) - resolveActiveGroups, isFunctionAvailable, getFunctionList, buildFunctionListText - app/service/inbox/index.js (5) From 15e109f992424cf6a1ba0e2e07c521d2a578b1ff Mon Sep 17 00:00:00 2001 From: liufumingren Date: Fri, 28 Aug 2026 04:42:22 +0800 Subject: [PATCH 290/550] =?UTF-8?q?fix(notice):=20=E6=94=B6=E8=B4=A7?= =?UTF-8?q?=E9=80=9A=E7=9F=A5=E9=93=BE=E8=B7=AF=E4=BF=AE=E5=A4=8D=EF=BC=88?= =?UTF-8?q?=E5=B9=82=E7=AD=89=E9=94=AE=E5=90=AB=E4=BA=8B=E4=BB=B6=E7=BB=B4?= =?UTF-8?q?=E5=BA=A6=E3=80=81ext=5Fdata=20=E9=80=8F=E4=BC=A0=E3=80=81?= =?UTF-8?q?=E5=AE=A1=E6=A0=B8=E6=A8=A1=E6=9D=BF=E4=B8=8E=E6=94=B6=E8=B4=A7?= =?UTF-8?q?=E4=BA=BA=E8=A1=8C=E8=B0=83=E6=95=B4=E3=80=81=E5=95=86=E5=93=81?= =?UTF-8?q?=E7=BC=96=E7=A0=81=E5=8F=8D=E6=9F=A5=E5=85=9C=E5=BA=95=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/systems/notice/index.js | 6 +- app/service/systems/storage/receiving.js | 97 +++++++++++++++++++----- app/service/systems/warehouseNotify.js | 20 +++-- methods/changes/warehouse.json | 75 ++++++++++++++++++ 4 files changed, 173 insertions(+), 25 deletions(-) diff --git a/app/service/systems/notice/index.js b/app/service/systems/notice/index.js index 0f30e6f..192958b 100644 --- a/app/service/systems/notice/index.js +++ b/app/service/systems/notice/index.js @@ -924,6 +924,7 @@ class NoticeService extends Service { warehouse_id: warehouseId, [Op.or]: conditions, }, + order: [[ 'id', 'ASC' ]], raw: true, }); @@ -934,6 +935,7 @@ class NoticeService extends Service { group_name: row.group_name || '', group_type: row.group_type || '', sub_type: row.sub_type || '', + ext_data: row.ext_data || null, })); } catch (error) { this.ctx.logger.warn(`[NoticeService.findSubscribedGroups] 查询订阅群失败: ${error.message}`); @@ -1167,7 +1169,9 @@ class NoticeService extends Service { storeId: group.group_type === 'store' ? payload.storeId : null, group, content: `${failPrefix}${baseContent}${fileLine}`.trim(), - extId: payload.businessId || payload.traceId, + // ext_id 幂等键需含事件维度:同一业务单在不同事件(创建/完成/审核)应各落一条消息,避免被幂等复用吞掉 + extId: payload.businessId ? `${payload.businessId}:${payload.event}` : payload.traceId, + extData: group.ext_data || null, }); }); const results = await Promise.all(tasks); diff --git a/app/service/systems/storage/receiving.js b/app/service/systems/storage/receiving.js index 786315b..b520eec 100644 --- a/app/service/systems/storage/receiving.js +++ b/app/service/systems/storage/receiving.js @@ -1249,7 +1249,7 @@ class ReceivingService extends Service { if (excelService && typeof excelService.generateAndUpload === 'function') { const receivingNumber = String(r.receiving_number || r.id).replace(/[\\/:*?"<>|]/g, '_'); reviewReport = await excelService.generateAndUpload({ - filename: `审核明细_${receivingNumber}.xlsx`, + filename: `receiving_review_${receivingNumber}.xlsx`, dir: `exports/receiving/reviewed/${warehouse_id}`, category: 'document', saveRecord: true, @@ -1535,10 +1535,13 @@ class ReceivingService extends Service { trackingNumber ? `快递单号:${trackingNumber} 已登记` : '快递单号:无', ]; + const receiverName = this.resolveReceivingCreatorName(receiving); + const contentLines = [ `收货单号:${receivingNumber} 正在收货`, `货主:${storeLabel}`, ...vehicleInfoLines, + `收货人:${receiverName || '无'}`, ]; const content = [ ...contentLines ].join('\n') + '。'; const storeContent = [ ...contentLines, `快速查看:${storeFrontendUrl}/storage/receiving_owner?id=${receivingNumber}` ].join('\n') + '。'; @@ -1572,6 +1575,34 @@ class ReceivingService extends Service { }); } + /** + * 解析收货单创建人(收货人)姓名:优先 creator_snapshot 快照,回退当前操作人。 + * @param {Object} receiving 收货单快照 + * @return {string} 姓名,无则空字符串 + */ + resolveReceivingCreatorName(receiving = {}) { + const { ctx } = this; + const rawSnapshot = receiving.creator_snapshot || null; + let name = ''; + + if (typeof rawSnapshot === 'string' && rawSnapshot.trim()) { + try { + const snapshot = JSON.parse(rawSnapshot); + name = String(snapshot && (snapshot.name || snapshot.employees_name || snapshot.real_name) || '').trim(); + } catch (_) { + /* 快照解析失败忽略 */ + } + } else if (rawSnapshot && typeof rawSnapshot === 'object') { + name = String(rawSnapshot.name || rawSnapshot.employees_name || rawSnapshot.real_name || '').trim(); + } + + if (!name) { + name = String((ctx.user && ctx.user.employees_name) || '').trim(); + } + + return name; + } + /** * 发送审核完成通知(receiving_reviewed),支持文字/文件两种类型。 * @param {Object} options 发送参数 @@ -1608,9 +1639,6 @@ class ReceivingService extends Service { const reportUrl = String( (reviewReport && (reviewReport.url || reviewReport.cdnUrl || reviewReport.cosUrl || reviewReport.fileUrl)) || '' ).trim(); - const reportFileName = String( - (reviewReport && (reviewReport.filename || reviewReport.fileKey || reviewReport.key)) || `审核明细_${receivingNumber}.xlsx` - ).trim(); const detailList = Array.isArray(details) ? details : []; const codeMap = itemCodeMap instanceof Map ? itemCodeMap : new Map(); @@ -1627,21 +1655,18 @@ class ReceivingService extends Service { } else if (productLines.length > 0) { contentLines.push('', '商品:', ...productLines); } - contentLines.push('', '请及时提交入库单入库'); + contentLines.push('', `请及时提交入库单入库,入库单务必备注${receivingNumber}`); const content = contentLines.join('\n') + '。'; return await noticeService.send({ warehouseId, storeId: Number.isFinite(storeId) && storeId > 0 ? storeId : undefined, - messageType: reportUrl ? 'file' : 'text', + messageType: 'text', businessName: 'receiving', event: 'receiving_reviewed', channel: 'warehouse', title: `收货单${receivingNumber}完成收货审核`, content, - url: reportUrl || undefined, - fileName: reportUrl ? reportFileName : '', - mimeType: reportUrl ? 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' : '', businessId: receiving.id, subject: { id: warehouseId, @@ -1662,7 +1687,8 @@ class ReceivingService extends Service { } /** - * 反查货主商品编码:收货明细 system_product_id 对应 wms_stock_store.stock_id,取 item_code 作为商品编码。 + * 反查商品编码:收货明细 system_product_id 优先反查 wms_stock_store.stock_id 取 item_code; + * 无对应货主商品资料时兜底取 wms_stock_warehouse.item_code(库存商品维度)。 * @param {Array} details 收货明细列表(含 system_product_id) * @return {Promise>} system_product_id → item_code */ @@ -1677,15 +1703,21 @@ class ReceivingService extends Service { ) ]; if (stockIds.length === 0) return codeMap; - const rows = await ctx.model.StockStore.findAll({ - where: { - stock_id: { [Op.in]: stockIds }, - delete_at: null, - }, - attributes: [ 'stock_id', 'item_code' ], - order: [[ 'id', 'ASC' ]], - raw: true, - }); + // 1. 货主商品资料:wms_stock_store.stock_id → item_code(失败不影响主流程) + let rows = []; + try { + rows = await ctx.model.StockStore.findAll({ + where: { + stock_id: { [Op.in]: stockIds }, + delete_at: null, + }, + attributes: [ 'stock_id', 'item_code' ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + } catch (storeErr) { + ctx.logger.warn(`[resolveReviewDetailItemCodeMap] 反查货主商品资料失败: ${storeErr.message}`); + } rows.forEach(row => { const stockId = Number(row.stock_id); @@ -1694,6 +1726,30 @@ class ReceivingService extends Service { if (itemCode) codeMap.set(stockId, itemCode); }); + // 2. 兜底:无对应 stock_store 时取 wms_stock_warehouse.item_code + const missingStockIds = stockIds.filter(id => !codeMap.has(id)); + if (missingStockIds.length > 0) { + try { + const warehouseRows = await ctx.model.StockWarehouse.findAll({ + where: { + id: { [Op.in]: missingStockIds }, + deleted_at: null, + }, + attributes: [ 'id', 'item_code' ], + raw: true, + }); + + warehouseRows.forEach(row => { + const stockId = Number(row.id); + if (!stockId || codeMap.has(stockId)) return; + const itemCode = String(row.item_code || '').trim(); + if (itemCode) codeMap.set(stockId, itemCode); + }); + } catch (warehouseErr) { + ctx.logger.warn(`[resolveReviewDetailItemCodeMap] 兜底反查仓库商品失败: ${warehouseErr.message}`); + } + } + return codeMap; } @@ -2126,6 +2182,7 @@ class ReceivingService extends Service { store_name: result.store_name, license_plate: result.license_plate, tracking_number: result.tracking_number, + creator_snapshot: result.creator_snapshot, }, }); } catch (noticeErr) { @@ -2489,6 +2546,7 @@ class ReceivingService extends Service { store_name: storeName, license_plate: receiving.license_plate, tracking_number: receiving.tracking_number, + creator_snapshot: receiving.creator_snapshot, }, }); } catch (noticeErr) { @@ -3367,6 +3425,7 @@ class ReceivingService extends Service { store_name: storeName, license_plate: receiving.license_plate, tracking_number: receiving.tracking_number, + creator_snapshot: receiving.creator_snapshot, }, }); } catch (noticeErr) { diff --git a/app/service/systems/warehouseNotify.js b/app/service/systems/warehouseNotify.js index 0718290..ed22760 100644 --- a/app/service/systems/warehouseNotify.js +++ b/app/service/systems/warehouseNotify.js @@ -232,12 +232,13 @@ class WarehouseNotifyService extends Service { * @param {Object} options 推送参数。 * @param {number} options.warehouseId 仓库 ID。 * @param {number} [options.storeId] 货主 ID。 - * @param {Object} options.group 目标群 { group_id, group_name }。 + * @param {Object} options.group 目标群 { group_id, group_name, ext_data }。 * @param {string} [options.content=''] 通知正文。 * @param {number|string} [options.extId] 业务单号(用于幂等 ext_id)。 + * @param {Object} [options.extData] 群扩展数据(渠道信息,落库与推送透传)。 * @return {Promise} 推送结果(含 messageId)。 */ - async pushSystemMessage({ warehouseId, storeId = null, group, content = '', extId = null } = {}) { + async pushSystemMessage({ warehouseId, storeId = null, group, content = '', extId = null, extData = null } = {}) { const { ctx } = this; const groupId = String((group && group.group_id) || '').trim(); const groupName = String((group && group.group_name) || '').trim(); @@ -251,9 +252,17 @@ class WarehouseNotifyService extends Service { }; } - // 幂等 ext_id:业务单号 + 群维度,网络重推时复用同一条消息记录 + // 幂等 ext_id:业务单号 + 事件 + 群维度,网络重推时复用同一条消息记录;超长时降级哈希兜底 const sourceExtId = String(extId || `sys:notice:${Date.now()}:${Math.random().toString(36).slice(2, 8)}`); - const uniqueExtId = `sys:notice:${sourceExtId}:${groupId}`; + let uniqueExtId = `sys:notice:${sourceExtId}:${groupId}`; + if (uniqueExtId.length > 128) { + const crypto = require('crypto'); + const digest = crypto.createHash('md5') + .update(uniqueExtId) + .digest('hex') + .slice(0, 12); + uniqueExtId = `sys:notice:${sourceExtId.slice(0, 100)}:${digest}`; + } const InboxMessage = ctx.model && ctx.model.InboxMessage; const normalizedContent = String(content || '').trim() || '系统通知'; @@ -283,7 +292,7 @@ class WarehouseNotifyService extends Service { group_name: groupName, user_name: null, content: normalizedContent, - ext_data: null, + ext_data: extData || null, flags: {}, push_status: 1, push_started_at: new Date(), @@ -302,6 +311,7 @@ class WarehouseNotifyService extends Service { type: 'system', content: normalizedContent, ext_id: sourceExtId, + ext_data: extData || null, group_id: groupId, group_name: groupName, timestamp: Math.floor(Date.now() / 1000), diff --git a/methods/changes/warehouse.json b/methods/changes/warehouse.json index dbb04cc..759534f 100644 --- a/methods/changes/warehouse.json +++ b/methods/changes/warehouse.json @@ -286,5 +286,80 @@ "item_code 反查不到时回退明细条码,仍无则显示未知编码" ], "module": "receiving" + }, + { + "version": "2026-08-28-warehouse-01", + "date": "2026-08-28", + "type": "fixed", + "summary": "审核明细 Excel 文件名去中文(审核明细_ → receiving_review_),通知正文修正为「请及时提交入库单入库,入库单务必备注Rxx」,不再额外拼接明细文件行", + "methods": [ + "notify.reply" + ], + "notes": [ + "storage/receiving.js reviewReceiving:Excel 上传文件名改为 receiving_review_{单号}.xlsx,URL 不再含中文,无需转码", + "sendReviewNotice:messageType 固定 text、不再传 url/fileName/mimeType,避免 notice 层追加「明细文件:文件名 链接」行;下载链接直接内嵌正文「审核明细下载:url」", + "正文末尾改为「请及时提交入库单入库,入库单务必备注Rxx」,接收方只处理 content 字段,链接以文本形式可见" + ], + "module": "receiving" + }, + { + "version": "2026-08-28-warehouse-02", + "date": "2026-08-28", + "type": "fixed", + "summary": "审核明细商品编码反查增加兜底:无对应 wms_stock_store 时回退取 wms_stock_warehouse.item_code,避免部分商品无货主资料时编码缺失", + "methods": [ + "notify.reply" + ], + "notes": [ + "storage/receiving.js resolveReviewDetailItemCodeMap:先按 stock_id 反查 wms_stock_store.item_code,未命中的 system_product_id 兜底查 wms_stock_warehouse(deleted_at 为空)取 item_code", + "两段反查均独立 try/catch,失败仅记日志不阻断审核通知主流程" + ], + "module": "receiving" + }, + { + "version": "2026-08-28-warehouse-03", + "date": "2026-08-28", + "type": "fixed", + "summary": "notice 群推送链路补齐 ext_data 透传:查群带回群扩展数据,pushSystemMessage 落库与推送均携带,对齐 pushSystemNotification 已有方式", + "methods": [ + "notify.reply" + ], + "notes": [ + "systems/notice/index.js findSubscribedGroups 返回群对象新增 ext_data 字段(取 inbox_group.ext_data)", + "sendToWarehouseChannel 调 pushSystemMessage 时新增 extData=group.ext_data || null", + "systems/warehouseNotify.js pushSystemMessage 新增 extData 入参:wms_inbox_message outbound 行 ext_data 落库,notify.reply 推送体 data.ext_data 透传(与 processor.writeOutboundReply 一致)" + ], + "module": "receiving" + }, + { + "version": "2026-08-28-warehouse-04", + "date": "2026-08-28", + "type": "fixed", + "summary": "修复通知消息幂等键吞消息:ext_id 加入事件维度,同一业务单不同事件各落一条 outbound 消息", + "methods": [ + "notify.reply" + ], + "notes": [ + "systems/notice/index.js sendToWarehouseChannel:extId 改为 businessId:event(同一收货单的创建/完成/审核事件各落一条 outbound 消息,不再被 sys:notice:{businessId}:{groupId} 幂等复用)", + "findSubscribedGroups 查询增加 ORDER BY id ASC,保证取群顺序稳定", + "systems/warehouseNotify.js:uniqueExtId 超过 VARCHAR(128) 时降级 md5 哈希兜底", + "线上案例:R20691023 审核消息因与「正在收货」共用 ext_id 被幂等吞掉,消息表无审核记录" + ], + "module": "receiving" + }, + { + "version": "2026-08-28-warehouse-05", + "date": "2026-08-28", + "type": "added", + "summary": "收货单创建/首次绑定货主通知(receiving_store_bound)新增收货人行:优先取 creator_snapshot 创建人姓名,回退当前操作人,无值显示无", + "methods": [ + "notify.reply" + ], + "notes": [ + "storage/receiving.js 新增 resolveReceivingCreatorName:解析 creator_snapshot(字符串 JSON 或对象)取 name/employees_name/real_name,回退 ctx.user.employees_name", + "sendStoreBoundNotice 模板在车牌/快递行后增加「收货人:姓名/无」,修复线上显示「收货人:{}」的空对象问题", + "三个触发点(create/bindStore/updateReceivingStats)的 receiving 快照均补充 creator_snapshot 字段" + ], + "module": "receiving" } ] From 54065d7ee15ba4ecd625da9723a563bcb4227c64 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sat, 29 Aug 2026 19:44:07 +0800 Subject: [PATCH 291/550] =?UTF-8?q?feat(returnUnpack):=20=E6=8B=86?= =?UTF-8?q?=E5=8C=85=E6=9C=80=E5=A4=A7=E5=BD=95=E5=88=B6=E6=97=B6=E9=95=BF?= =?UTF-8?q?=E9=85=8D=E7=BD=AE(=E9=BB=98=E8=AE=A45=E5=88=86=E9=92=9F),?= =?UTF-8?q?=E6=8F=90=E4=BA=A4=E6=97=B6=E6=88=AA=E6=96=AD=E7=BB=93=E6=9D=9F?= =?UTF-8?q?=E6=97=B6=E9=97=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/model/store.js | 12 ++++++ app/service/systems/return_unpack.js | 55 +++++++++++++++++++++++- app/service/systems/setting/warehouse.js | 9 ++++ methods/changes/system.json | 21 +++++++++ methods/system.json | 19 ++++++-- 5 files changed, 111 insertions(+), 5 deletions(-) diff --git a/app/model/store.js b/app/model/store.js index 2d5ddde..1fef906 100644 --- a/app/model/store.js +++ b/app/model/store.js @@ -62,6 +62,7 @@ module.exports = app => { default_location_id: null, single_order_pack_max_minutes: 3, group_order_pack_max_minutes: 40, + return_unpack_max_record_minutes: 5, inventory_warning_rules: DEFAULT_INVENTORY_WARNING_RULES, auto_outbound_rules: DEFAULT_AUTO_OUTBOUND_RULES, cutoff_order_enabled: 1, @@ -267,6 +268,17 @@ module.exports = app => { normalized.group_order_pack_max_minutes = groupOrderPackMaxMinutes; } + const rawReturnUnpackMaxRecordMinutes = parsed.return_unpack_max_record_minutes; + if (rawReturnUnpackMaxRecordMinutes === undefined || rawReturnUnpackMaxRecordMinutes === null || rawReturnUnpackMaxRecordMinutes === '') { + normalized.return_unpack_max_record_minutes = DEFAULT_SUBJECT_CONFIG.return_unpack_max_record_minutes; + } else { + const returnUnpackMaxRecordMinutes = Number(rawReturnUnpackMaxRecordMinutes); + if (!Number.isInteger(returnUnpackMaxRecordMinutes) || returnUnpackMaxRecordMinutes <= 0) { + throw new Error('subject_config.return_unpack_max_record_minutes 必须是大于 0 的整数'); + } + normalized.return_unpack_max_record_minutes = returnUnpackMaxRecordMinutes; + } + const rawExcludeRemarks = parsed.auto_allocate_express_exclude_remarks; if (rawExcludeRemarks === undefined || rawExcludeRemarks === null || rawExcludeRemarks === '') { normalized.auto_allocate_express_exclude_remarks = []; diff --git a/app/service/systems/return_unpack.js b/app/service/systems/return_unpack.js index 44df27b..e2d7556 100644 --- a/app/service/systems/return_unpack.js +++ b/app/service/systems/return_unpack.js @@ -509,7 +509,57 @@ class ReturnUnpackService extends Service { } /** - * 提交确认:未完成拆包单转 completed 终态,回写结束时间, + * 按仓库配置的拆包最大录制时长约束提交结束时间。 + * 候选结束时间超过 开始时间+上限时长 时,截断为上限时间点。 + * 开始时间缺失、配置非法或读取失败时不约束,原样返回。 + * + * @param {Object} unpack 拆包单主表记录(需含 id / warehouse_id / start_time)。 + * @param {Date} candidateEndTime 候选结束时间。 + * @return {Promise} 约束后的结束时间。 + */ + async _resolveSubmitEndTime(unpack, candidateEndTime) { + const { ctx } = this; + const candidate = candidateEndTime instanceof Date ? candidateEndTime : new Date(candidateEndTime); + + if (!unpack || !Number.isFinite(candidate.getTime())) { + return candidateEndTime; + } + + const startMs = new Date(unpack.start_time).getTime(); + if (!Number.isFinite(startMs)) { + return candidateEndTime; + } + + let limitMinutes = null; + try { + const warehouseId = Number(unpack.warehouse_id || 0); + const subjectConfig = await ctx.service.systems.deliveryOrder.getStoreSubjectConfig(warehouseId); + limitMinutes = Number(subjectConfig && subjectConfig.return_unpack_max_record_minutes); + } catch (error) { + ctx.logger.warn(`[returnUnpack.submit] 读取仓库拆包时长配置失败: ${error.message}`); + } + + // 未配置有效时长时不约束结束时间 + if (!Number.isInteger(limitMinutes) || limitMinutes <= 0) { + return candidateEndTime; + } + + const maxEndMs = startMs + limitMinutes * 60 * 1000; + if (candidate.getTime() > maxEndMs) { + const cappedEndTime = new Date(maxEndMs); + ctx.logger.info( + `[returnUnpack.submit] 结束时间超过拆包录制上限,截断为上限时间 unpack_id=${unpack.id} ` + + `limitMinutes=${limitMinutes} candidate=${candidate.toISOString()} end=${cappedEndTime.toISOString()}` + ); + return cappedEndTime; + } + + return candidateEndTime; + } + + /** + * 提交确认:未完成拆包单转 completed 终态,回写结束时间(超过仓库配置的 + * 拆包最大录制时长时自动截断为开始时间+上限), * 并同步更新退回查询记录 is_back=1(标记该运单号已退回)。 * * @param {Object} params 提交参数。 @@ -523,8 +573,9 @@ class ReturnUnpackService extends Service { this._assertUnpacking(unpack); const now = new Date(); + const endTime = await this._resolveSubmitEndTime(unpack, now); await ctx.model.ReturnUnpack.update( - { status: 'completed', end_time: now }, + { status: 'completed', end_time: endTime }, { where: { id: unpack.id } } ); diff --git a/app/service/systems/setting/warehouse.js b/app/service/systems/setting/warehouse.js index 78ec94c..5f4a31d 100644 --- a/app/service/systems/setting/warehouse.js +++ b/app/service/systems/setting/warehouse.js @@ -292,6 +292,15 @@ const WAREHOUSE_SETTING_FIELDS = Object.freeze([ description: '团购打包最大时长,单位:分钟,默认 40', min: 1, }), + Object.freeze({ + key: 'return_unpack_max_record_minutes', + name: '拆包最大录制时长(分钟)', + type: 'integer', + default: 5, + required: false, + description: '拆包最大录制时长,单位:分钟,默认 5;超过上限时提交的结束时间自动截断为开始时间+上限', + min: 1, + }), Object.freeze({ key: 'default_location_id', name: '默认库位', diff --git a/methods/changes/system.json b/methods/changes/system.json index 8f8ec9c..f526dbe 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,25 @@ [ + { + "version": "2026.08.29-return-unpack-max-record-minutes", + "date": "2026-08-29", + "type": "enhanced", + "summary": "仓库设置新增「拆包最大录制时长」配置 return_unpack_max_record_minutes(分钟,默认 5,min 1):returnUnpack.submit 提交确认时,结束时间超过 开始时间+配置上限 时自动截断为上限时间点", + "methods": [ + "setting.warehouse.getSettings", + "setting.warehouse.getFieldMeta", + "setting.warehouse.saveSettings", + "returnUnpack.submit" + ], + "notes": [ + "app/service/systems/setting/warehouse.js WAREHOUSE_SETTING_FIELDS 新增 return_unpack_max_record_minutes(名称:拆包最大录制时长(分钟),type integer,非必填,默认 5,min 1,描述:超过上限时提交的结束时间自动截断为开始时间+上限),与 single_order_pack_max_minutes(默认 3)/ group_order_pack_max_minutes(默认 40)并列;getFieldMeta 自动返回该字段元信息", + "app/model/store.js DEFAULT_SUBJECT_CONFIG 增加 return_unpack_max_record_minutes: 5;normalizeSubjectConfig 非法值(非正整数)抛「subject_config.return_unpack_max_record_minutes 必须是大于 0 的整数」,空值回退默认 5", + "app/service/systems/return_unpack.js submit() 新增私有方法 _resolveSubmitEndTime:候选 end_time 超过 start_time + 配置上限分钟时截断为上限时间点并记录 info 日志;配置读取 ctx.service.systems.deliveryOrder.getStoreSubjectConfig,配置非法/读取失败/start_time 缺失时不约束;其余行为不变(completed 终态、回写 is_back=1、货主群通知等均不变)", + "methods/system.json:setting.warehouse.getSettings 响应与 setting.warehouse.saveSettings 入参新增 subject_config.return_unpack_max_record_minutes 字段文档;returnUnpack.submit description 与响应 record 补充「结束时间超过仓库配置的拆包最大录制时长上限时自动截断为开始时间+上限」语义;getFieldMeta 为通用字段元信息结构,无逐字段清单,无需改动", + "向后兼容:新增字段可选,不影响既有仓库设置读写;本次仅文档同步,业务代码由 wms-dev-agent 完成", + "methods/system.json 版本 0.3.45 -> 0.3.46(docMeta.version),updatedAt 保持 2026-08-29" + ], + "module": "returnUnpack" + }, { "version": "2026.08.27-order-allocateStorage-allow-storage-location", "date": "2026-08-27", diff --git a/methods/system.json b/methods/system.json index 768800e..ba941c1 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1,7 +1,7 @@ { "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", - "version": "0.3.37", + "version": "0.3.46", "updatedAt": "2026-08-27", "headers": [ { @@ -13947,6 +13947,12 @@ "required": false, "description": "团购打包最大时长,单位:分钟,默认 40" }, + { + "name": "subject_config.return_unpack_max_record_minutes", + "type": "number", + "required": false, + "description": "拆包最大录制时长,单位:分钟,默认 5,min 1;超过上限时拆包提交的结束时间自动截断为开始时间+上限" + }, { "name": "subject_config.default_location_id", "type": "number", @@ -14217,6 +14223,13 @@ "source": "body.subject_config", "description": "团购打包最大时长,单位:分钟,默认 40,须为大于 0 的整数" }, + { + "name": "subject_config.return_unpack_max_record_minutes", + "type": "number", + "required": false, + "source": "body.subject_config", + "description": "拆包最大录制时长,单位:分钟,默认 5,min 1,须为大于 0 的整数(非法值报 400:subject_config.return_unpack_max_record_minutes 必须是大于 0 的整数);超过上限时拆包提交的结束时间自动截断为开始时间+上限" + }, { "name": "subject_config.default_location_id", "type": "number", @@ -37390,7 +37403,7 @@ }, { "method": "returnUnpack.submit", - "description": "提交确认:未完成(unpacking)拆包单转 completed 终态并回写 end_time(拆包结束时间);同步按 warehouse_id+waybill_code 更新 wms_return_query_log.is_back=1(标记该运单号已退回,更新失败不阻断主流程)。提交后进入终态,不可再录/移除明细。仓库隔离校验(仅本仓库拆包单)。", + "description": "提交确认:未完成(unpacking)拆包单转 completed 终态并回写 end_time(拆包结束时间;结束时间超过仓库配置的拆包最大录制时长上限时,自动截断为 开始时间+上限——仓库配置项 subject_config.return_unpack_max_record_minutes,默认 5 分钟,配置缺失/非法或开始时间缺失时不约束);同步按 warehouse_id+waybill_code 更新 wms_return_query_log.is_back=1(标记该运单号已退回,更新失败不阻断主流程)。提交后进入终态,不可再录/移除明细。仓库隔离校验(仅本仓库拆包单)。", "isNeedAuth": true, "isNeedLogin": true, "headers": [], @@ -37408,7 +37421,7 @@ "name": "record", "type": "object", "required": true, - "description": "更新后的主表记录(含 status=completed、end_time 及格式化时间字段)" + "description": "更新后的主表记录(含 status=completed、end_time 及格式化时间字段;end_time 为按仓库拆包最大录制时长上限约束后的结束时间,超过上限时截断为 开始时间+上限)" } ], "errors": [ From d36a46c5ab23a83e1ab638e74d0a181cbb3cf6de Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sat, 29 Aug 2026 21:04:47 +0800 Subject: [PATCH 292/550] =?UTF-8?q?fix(order):=20=E5=8F=96=E6=B6=88?= =?UTF-8?q?=E6=B3=A2=E6=AC=A1=E5=A2=9E=E5=8A=A0=E6=8B=A3=E8=B4=A7=E7=8A=B6?= =?UTF-8?q?=E6=80=81=E6=A0=A1=E9=AA=8C=EF=BC=8C=E6=8B=A3=E8=B4=A7=E4=B8=AD?= =?UTF-8?q?/=E5=B7=B2=E5=AE=8C=E6=88=90=E6=B3=A2=E6=AC=A1=E7=A6=81?= =?UTF-8?q?=E6=AD=A2=E5=8F=96=E6=B6=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/systemMethods/order/wave.js | 150 +++++- methods/changes/system.json | 19 + methods/system.json | 73 ++- .../order/wave.batchCancel.test.js | 429 +++++++++++++++++- 4 files changed, 640 insertions(+), 31 deletions(-) diff --git a/app/service/systemMethods/order/wave.js b/app/service/systemMethods/order/wave.js index 866799c..63dd110 100644 --- a/app/service/systemMethods/order/wave.js +++ b/app/service/systemMethods/order/wave.js @@ -4926,6 +4926,8 @@ class WaveService extends OrderBaseService { * 批量解除波次任务提交接口。 * * 仅处理当前登录仓库下的波次与订单,提交后异步执行。 + * 提交前校验:波次属于活动拣货任务、波次内存在已拣货完成或拣货中的订单、 + * 或波次状态已进入拣货中及后续环节时,拒绝取消波次。 * * @param {Object} data 请求参数。 * @param {number|string} [data.warehouse_id] 仓库ID(可选,若传入必须与当前上下文一致)。 @@ -4973,6 +4975,64 @@ class WaveService extends OrderBaseService { throw new Error('波次属于活动拣货任务,请通过任务取消接口处理'); } + // 业务规则校验:波次内存在已拣货完成或拣货中的订单时禁止取消波次 + const orderModelForGuard = await this.getOrderModel('pendingOrder', warehouseId); + const pickedOrderRows = await orderModelForGuard.findAll({ + attributes: [ 'id', 'wave_id', 'wave_no', 'pick_status' ], + where: { + warehouse_id: warehouseId, + wave_id: { [Op.in]: normalizedWaveIds }, + pick_status: { [Op.in]: [ 'padding', 'fin' ] }, + }, + raw: true, + }); + const normalizedPickedOrderRows = Array.isArray(pickedOrderRows) ? pickedOrderRows : []; + if (normalizedPickedOrderRows.length > 0) { + const blockedWaveIds = [ ...new Set(normalizedPickedOrderRows + .map(row => Number(row && row.wave_id || 0)) + .filter(waveId => Number.isInteger(waveId) && waveId > 0)) ]; + const blockedOrderIds = normalizedPickedOrderRows + .map(row => Number(row && row.id || 0)) + .filter(orderId => Number.isInteger(orderId) && orderId > 0); + const shownOrderIds = blockedOrderIds.slice(0, 20).join(', '); + const orderIdSuffix = blockedOrderIds.length > 20 ? ' 等' : ''; + return this.fail( + `波次内存在已拣货完成或拣货中的订单,禁止取消波次:波次 ${blockedWaveIds.join(', ')},订单 ${shownOrderIds}${orderIdSuffix}`, + { + wave_ids: blockedWaveIds, + order_ids: blockedOrderIds, + }, + 400 + ); + } + + // 兜底校验:波次状态已进入拣货中及后续环节(拣货中/拣货完成/复核完成/打包完成)时禁止取消 + const advancedWaveRows = await this.ctx.model.query( + `SELECT wave_id, wave_no, wave_status + FROM wms_wave_batch + WHERE warehouse_id = :warehouseId + AND wave_id IN (:waveIds) + AND wave_status >= 3`, + { + replacements: { + warehouseId, + waveIds: normalizedWaveIds, + }, + type: this.ctx.model.QueryTypes.SELECT, + } + ); + const normalizedAdvancedWaveRows = Array.isArray(advancedWaveRows) ? advancedWaveRows : []; + if (normalizedAdvancedWaveRows.length > 0) { + const blockedWaveIds = normalizedAdvancedWaveRows + .map(row => Number(row && row.wave_id || 0)) + .filter(waveId => Number.isInteger(waveId) && waveId > 0); + return this.fail( + `波次已进入拣货或后续环节,禁止取消波次:波次 ${blockedWaveIds.join(', ')}`, + { wave_ids: blockedWaveIds }, + 400 + ); + } + const requestedTaskId = this.normalizeBatchCancelTaskId(data); const taskId = requestedTaskId || this.generateBatchCancelTaskId(warehouseId); const existingTask = await this.getBatchCancelTaskProgress(taskId); @@ -8248,6 +8308,9 @@ class WaveService extends OrderBaseService { /** * 执行批量解除波次后台任务。 * + * 逐个波次处理:波次已进入拣货中及后续环节、或波次内存在已拣货完成/拣货中的订单时, + * 跳过该波次并记录到 skipped_waves,避免删除已拣货波次;其余波次正常取消。 + * * @param {Object} params 任务参数。 * @param {string} params.taskId 任务ID。 * @param {number|string} [params.warehouseId] 仓库ID(兜底)。 @@ -8310,7 +8373,7 @@ class WaveService extends OrderBaseService { const orderModel = await this.getOrderModel('pendingOrder', warehouseId); const querySql = ` - SELECT wave_id, wave_no + SELECT wave_id, wave_no, wave_status FROM wms_wave_batch WHERE warehouse_id = :warehouseId AND wave_id IN (:ids) @@ -8327,6 +8390,7 @@ class WaveService extends OrderBaseService { .map(row => ({ wave_id: Number(row && row.wave_id || 0), wave_no: String(row && row.wave_no || '').trim(), + wave_status: Number(row && row.wave_status || 0), })) .filter(item => Number.isInteger(item.wave_id) && item.wave_id > 0); @@ -8343,6 +8407,8 @@ class WaveService extends OrderBaseService { affected_wave_ids: [], affected_order_count: 0, canceled_wave_count: 0, + skipped_wave_ids: [], + skipped_wave_count: 0, duration_ms: Date.now() - startTime, }, }); @@ -8354,13 +8420,64 @@ class WaveService extends OrderBaseService { let canceledWaveCount = 0; const affectedWaveIds = []; const removedOrderIdSet = new Set(); + const skippedWaves = []; for (const wave of targetWaves) { const waveId = Number(wave.wave_id || 0); const waveNo = String(wave.wave_no || '').trim() || '未知波次'; + const waveStatus = Number(wave.wave_status || 0); + + // 兜底校验:波次已进入拣货中及后续环节时跳过取消,避免删除已拣货波次 + if (waveStatus >= 3) { + skippedWaves.push({ + wave_id: waveId, + wave_no: waveNo, + reason: 'wave_status_blocked', + wave_status: waveStatus, + }); + processedWaveCount += 1; + await this.setBatchCancelTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + total_wave_count: targetWaves.length, + processed_wave_count: processedWaveCount, + progress_percent: Math.min(100, Math.round((processedWaveCount / targetWaves.length) * 100)), + }); + continue; + } + const transaction = await this.ctx.model.transaction(); try { + // 业务规则校验:波次内存在已拣货完成或拣货中的订单时跳过取消,防止删除已拣货波次 + const pickedOrderGuardRows = await orderModel.findAll({ + attributes: [ 'id', 'pick_status' ], + where: { + wave_id: waveId, + pick_status: { [Op.in]: [ 'padding', 'fin' ] }, + }, + raw: true, + transaction, + }); + + const normalizedPickedOrderGuardRows = Array.isArray(pickedOrderGuardRows) ? pickedOrderGuardRows : []; + if (normalizedPickedOrderGuardRows.length > 0) { + await transaction.rollback(); + skippedWaves.push({ + wave_id: waveId, + wave_no: waveNo, + reason: 'picked_orders_exist', + picked_order_count: normalizedPickedOrderGuardRows.length, + }); + processedWaveCount += 1; + await this.setBatchCancelTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + total_wave_count: targetWaves.length, + processed_wave_count: processedWaveCount, + progress_percent: Math.min(100, Math.round((processedWaveCount / targetWaves.length) * 100)), + }); + continue; + } + const affectedOrderRows = await orderModel.findAll({ attributes: [ 'id', 'wave_id', 'wave_no' ], where: { @@ -8476,6 +8593,9 @@ class WaveService extends OrderBaseService { affected_wave_ids: affectedWaveIds, affected_order_count: affectedOrderCount, canceled_wave_count: canceledWaveCount, + skipped_wave_ids: skippedWaves.map(item => item.wave_id), + skipped_wave_count: skippedWaves.length, + skipped_waves: skippedWaves, duration_ms: Date.now() - startTime, }, }); @@ -8502,6 +8622,9 @@ class WaveService extends OrderBaseService { affected_wave_ids: affectedWaveIds, affected_order_count: affectedOrderCount, canceled_wave_count: canceledWaveCount, + skipped_wave_ids: skippedWaves.map(item => item.wave_id), + skipped_wave_count: skippedWaves.length, + skipped_waves: skippedWaves, duration_ms: durationMs, }, }); @@ -12426,13 +12549,17 @@ class WaveService extends OrderBaseService { /** * 公共拣货任务取消流程。 * - * 仅允许取消状态为 0/1/2/3 的任务。取消后会回收拣货车绑定。 + * 仅允许取消状态为 0/1 的任务。取消后会回收拣货车绑定,并物理删除该任务 + * 的任务-订单关联记录(wms_wave_pick_task_order),避免订单回池后残留脏数据。 * * 按任务来源区分行为: - * - source=1(PDA 抓取):释放关联波次(清空订单 wave_id、删除 wms_wave_batch), - * 使订单可重新参与后续策略抓取;状态为 2/3 时还会回退拣货状态。 + * - source=0/1(PDA 抓取):释放关联波次(清空订单 wave_id、删除 wms_wave_batch), + * 使订单可重新参与后续策略抓取。 * - source=2(后台/扫描创建):不释放波次,仅作废任务(更新状态为 9、解绑拣货车)。 * + * 所有来源均会清理任务-波次关联(wms_wave_pick_task_wave)与任务-订单关联记录 + * (wms_wave_pick_task_order)。 + * * @param {Object} [params={}] 取消参数。 * @param {Array} params.taskIds 任务ID列表。 * @param {number} params.warehouseId 仓库ID。 @@ -12690,6 +12817,21 @@ class WaveService extends OrderBaseService { }); } + // 清理任务-订单关联记录(所有来源都需要): + // 任务取消后订单回池,wms_wave_pick_task_order 的关联记录属于脏数据,必须物理删除, + // 否则会污染后续任务进度统计、复核状态批量更新及车标快照兜底查询 + await this.ctx.model.query(` + DELETE FROM wms_wave_pick_task_order + WHERE task_id = :taskId + AND warehouse_id = :warehouseId + `, { + replacements: { + taskId, + warehouseId, + }, + transaction, + }); + // 当任务状态为待复核(2)或已完成(3)时,回退订单拣货状态(仅 PDA 抓取) if (!isScanCreated && [ 2, 3 ].includes(taskStatus)) { await this.ctx.model.query(` diff --git a/methods/changes/system.json b/methods/changes/system.json index f526dbe..c984ee9 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,23 @@ [ + { + "version": "2026.08.29-wave-batchCancel-pick-status-guard", + "date": "2026-08-29", + "type": "enhanced", + "summary": "取消波次增加拣货状态校验:order.wave.batchCancel 提交前新增两道业务校验(code 400)——波次内存在拣货中或拣货完成(pick_status 为 padding/fin)的订单、或波次状态已进入拣货及后续环节(wms_wave_batch.wave_status >= 3)时禁止取消波次;runBatchCancelTask 异步兜底命中上述条件跳过该波次并继续处理其余波次;order.wave.batchCancelTaskProgress 任务结果新增 skipped_wave_ids / skipped_wave_count / skipped_waves 字段。", + "methods": [ + "order.wave.batchCancel", + "order.wave.batchCancelTaskProgress" + ], + "notes": [ + "app/service/systemMethods/order/wave.js batchCancel():活动拣货任务校验后新增两道 400 校验——① getOrderModel('pendingOrder', warehouseId) 查询波次内 pick_status IN ('padding','fin') 的订单,命中返回「波次内存在已拣货完成或拣货中的订单,禁止取消波次」(附 wave_ids 与最多前 20 个 order_ids);② 查询 wms_wave_batch 中 wave_status >= 3 的波次,命中返回「波次已进入拣货或后续环节,禁止取消波次」(附 wave_ids)", + "runBatchCancelTask():目标波次查询新增 wave_status 列;逐波次处理时先校验 wave_status >= 3(跳过明细 reason=wave_status_blocked,附 wave_status),再在事务内校验波次内 pick_status IN ('padding','fin') 的订单(reason=picked_orders_exist,附 picked_order_count),命中则回滚事务、跳过该波次并继续处理其余波次;无目标波次时 result 返回空 skipped_wave_ids 数组与 skipped_wave_count=0", + "任务结果:success 与 failed 终态的 result 均新增 skipped_wave_ids(被跳过波次 ID 列表)、skipped_wave_count(数量)、skipped_waves(明细数组,字段 wave_id/wave_no/reason/wave_status/picked_order_count,其中 wave_status 仅 reason=wave_status_blocked、picked_order_count 仅 reason=picked_orders_exist)", + "methods/system.json:order.wave.batchCancel 的 description 补充校验规则说明、errors 新增两条 400 描述;order.wave.batchCancelTaskProgress 的 description 与 response 补充 skipped_wave_ids / skipped_wave_count / skipped_waves 字段说明(含 children 明细),并同步更新 result 字段描述(补充 ids/affected_wave_ids/affected_order_count/skipped_* 等字段枚举)", + "methods/system.json 版本 0.3.47 -> 0.3.48(docMeta.version),updatedAt 保持 2026-08-29", + "本次仅文档同步,业务代码改动已完成(git diff app/service/systemMethods/order/wave.js),未修改 app/ 下任何代码,未执行数据库/Redis 操作" + ], + "module": "order.wave" + }, { "version": "2026.08.29-return-unpack-max-record-minutes", "date": "2026-08-29", diff --git a/methods/system.json b/methods/system.json index ba941c1..bf188c0 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1,8 +1,8 @@ { "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", - "version": "0.3.46", - "updatedAt": "2026-08-27", + "version": "0.3.48", + "updatedAt": "2026-08-29", "headers": [ { "name": "platform", @@ -9151,7 +9151,7 @@ }, { "method": "order.wave.batchCancel", - "description": "提交批量解除波次异步任务。该接口为异步任务提交接口,立即返回 task_id,后端异步按当前仓库 + wave_ids 拉取待处理波次并执行解除操作;可通过 order.wave.batchCancelTaskProgress 查询进度与结果。", + "description": "提交批量解除波次异步任务。该接口为异步任务提交接口,立即返回 task_id,后端异步按当前仓库 + wave_ids 拉取待处理波次并执行解除操作;可通过 order.wave.batchCancelTaskProgress 查询进度与结果。新增业务校验:波次内存在拣货中或拣货完成(pick_status 为 padding/fin)的订单,或波次状态已进入拣货及后续环节(wms_wave_batch.wave_status >= 3)时,禁止取消波次并返回 400;异步任务执行时命中上述条件的波次将被跳过,跳过明细见任务进度 result 的 skipped_waves。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -9213,21 +9213,29 @@ "errors": [ { "code": "400", - "description": "未识别到当前仓库上下文" + "message": "未识别到当前仓库上下文" }, { "code": "400", - "description": "wave_ids 参数不能为空或格式错误" + "message": "wave_ids 参数不能为空或格式错误" + }, + { + "code": "400", + "message": "波次内存在已拣货完成或拣货中的订单,禁止取消波次(订单 pick_status 为 padding/fin;响应附带命中波次 wave_ids 与订单 order_ids)" + }, + { + "code": "400", + "message": "波次已进入拣货或后续环节,禁止取消波次(wms_wave_batch.wave_status >= 3;响应附带命中波次 wave_ids)" }, { "code": "500", - "description": "任务提交失败或内部错误" + "message": "任务提交失败或内部错误" } ] }, { "method": "order.wave.batchCancelTaskProgress", - "description": "查询批量解除波次任务进度:按 task_id 查询任务状态与统计信息;兼容 taskId 参数名。响应包含 state、progress_percent、processed_wave_count、total_wave_count;当 state 为 success/failed 时返回额外字段说明。", + "description": "查询批量解除波次任务进度:按 task_id 查询任务状态与统计信息;兼容 taskId 参数名。响应包含 state、progress_percent、processed_wave_count、total_wave_count;当 state 为 success/failed 时返回额外字段说明。成功/失败终态的任务结果 result 中包含 skipped_wave_ids、skipped_wave_count、skipped_waves:因波次内存在已拣货完成或拣货中的订单(pick_status 为 padding/fin)或波次已进入拣货及后续环节(wave_status >= 3)被跳过取消的波次明细。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -9300,17 +9308,62 @@ "name": "result", "type": "object", "required": false, - "description": "成功时返回的汇总结果(仅在 state=success 时返回),例如 { \"processed_wave_count\": number, \"canceled_wave_count\": number }" + "description": "成功时返回的汇总结果(仅在 state=success 时返回),包含 ids、affected_wave_ids、affected_order_count、canceled_wave_count、skipped_wave_ids、skipped_wave_count、skipped_waves、duration_ms 等字段" + }, + { + "name": "skipped_wave_ids", + "type": "array", + "required": false, + "description": "因业务校验被跳过取消的波次 ID 列表(成功/失败终态的任务结果 result 中返回,数组元素为 number)" + }, + { + "name": "skipped_wave_count", + "type": "number", + "required": false, + "description": "被跳过取消的波次数量(等于 skipped_wave_ids 长度)" + }, + { + "name": "skipped_waves", + "type": "array", + "required": false, + "description": "被跳过取消的波次明细(成功/失败终态的任务结果 result 中返回)。跳过原因两类:波次已进入拣货及后续环节(wave_status >= 3)、波次内存在已拣货完成或拣货中的订单(pick_status 为 padding/fin)", + "children": [ + { + "name": "wave_id", + "type": "number", + "description": "被跳过取消的波次 ID" + }, + { + "name": "wave_no", + "type": "string", + "description": "波次号" + }, + { + "name": "reason", + "type": "string", + "description": "跳过原因枚举:wave_status_blocked(波次已进入拣货或后续环节,wave_status >= 3)/ picked_orders_exist(波次内存在已拣货完成或拣货中的订单)" + }, + { + "name": "wave_status", + "type": "number", + "description": "波次当前状态(仅 reason=wave_status_blocked 时返回)" + }, + { + "name": "picked_order_count", + "type": "number", + "description": "命中已拣货完成或拣货中状态的订单数量(仅 reason=picked_orders_exist 时返回)" + } + ] } ], "errors": [ { "code": "400", - "description": "task_id 参数不能为空" + "message": "task_id 参数不能为空" }, { "code": "500", - "description": "查询失败或内部错误" + "message": "查询失败或内部错误" } ] }, diff --git a/test/app/service/systemMethods/order/wave.batchCancel.test.js b/test/app/service/systemMethods/order/wave.batchCancel.test.js index 98bd356..6f570df 100644 --- a/test/app/service/systemMethods/order/wave.batchCancel.test.js +++ b/test/app/service/systemMethods/order/wave.batchCancel.test.js @@ -1,27 +1,72 @@ 'use strict'; const assert = require('node:assert/strict'); +const { Op } = require('sequelize'); const WaveService = require('../../../../../app/service/systemMethods/order/wave'); +/** 批量取消任务缓存键前缀(与 wave.js 中的常量保持一致)。 */ +const BATCH_CANCEL_TASK_CACHE_KEY_PREFIX = 'wave:batch-cancel:'; + +/** + * 等待若干轮事件循环(用于等待 batchCancel 内 setImmediate 触发的后台任务)。 + * + * @param {number} [ticks=3] 轮次。 + * @return {Promise} 等待完成。 + */ +function waitImmediate(ticks = 3) { + return new Promise(resolve => { + let remaining = ticks; + const step = () => { + remaining -= 1; + if (remaining <= 0) { + resolve(); + return; + } + setImmediate(step); + }; + setImmediate(step); + }); +} + /** * 创建 batchCancel 轻量测试上下文。 * + * @param {Object} [options] 场景配置。 + * @param {Array} [options.orders] 订单记录(id/wave_id/wave_no/pick_status)。 + * @param {Array} [options.waves] 波次记录(wave_id/wave_no/wave_status)。 + * @param {Array} [options.activePickTaskWaves] 活动拣货任务波次行(wave_id)。 + * @param {number} [options.warehouseId] 仓库ID(默认固定测试仓库 100000)。 * @return {{ service: WaveService, state: Object }} 服务实例与状态记录。 */ -function createHarness() { +function createHarness(options = {}) { + const warehouseId = Number(options.warehouseId || 100000); const cacheStore = new Map(); const state = { sqlCalls: [], - orders: [ - { id: 101, wave_id: 11, wave_no: 'W11' }, - { id: 102, wave_id: 11, wave_no: 'W11' }, - ], + cacheKeys: [], + orderFindAllCalls: [], + orderUpdateCalls: [], + canceledWaveIds: [], + rollbackCount: 0, + backgroundTaskCalls: [], + orders: (options.orders || [ + { id: 101, wave_id: 11, wave_no: 'W11', pick_status: 'none' }, + { id: 102, wave_id: 11, wave_no: 'W11', pick_status: 'none' }, + ]).map(row => ({ ...row })), + waves: (options.waves || [ + { wave_id: 11, wave_no: 'W11', wave_status: 0 }, + ]).map(row => ({ ...row })), + activePickTaskWaves: options.activePickTaskWaves || [], }; const transaction = { - async commit() {}, - async rollback() {}, + async commit() { + // 轻量测试用空事务:提交不做任何事 + }, + async rollback() { + state.rollbackCount += 1; + }, }; const ctx = { @@ -29,13 +74,16 @@ function createHarness() { config: {}, async setCacheAsync(key, value) { cacheStore.set(key, value); + if (!state.cacheKeys.includes(key)) { + state.cacheKeys.push(key); + } }, async getCacheAsync(key) { return cacheStore.get(key) || null; }, }, user: { - store_id: 100000, + store_id: warehouseId, }, logger: { info() {}, @@ -52,10 +100,21 @@ function createHarness() { async query(sql, options = {}) { state.sqlCalls.push({ sql, options }); - if (sql.includes('SELECT wave_id, wave_no') && options.type === 'SELECT') { - return [ - { wave_id: 11, wave_no: 'W11' }, - ]; + // 入口校验:活动拣货任务波次查询 + if (sql.includes('wms_wave_pick_task_wave')) { + return state.activePickTaskWaves; + } + + // 波次批量表查询(入口 wave_status >= 3 兜底校验 / 后台任务波次加载) + if (sql.includes('SELECT wave_id, wave_no, wave_status')) { + const replacements = options.replacements || {}; + const rawIds = replacements.ids || replacements.waveIds || []; + const requestedIds = (Array.isArray(rawIds) ? rawIds : [ rawIds ]).map(id => Number(id)); + const matched = state.waves.filter(item => requestedIds.includes(Number(item.wave_id))); + if (sql.includes('wave_status >= 3')) { + return matched.filter(item => Number(item.wave_status) >= 3); + } + return matched; } if (sql.includes('DELETE FROM wms_order_wave_index')) { @@ -63,6 +122,8 @@ function createHarness() { } if (sql.includes('UPDATE wms_wave_batch') && sql.includes('SET wave_status = -1')) { + const waveId = Number(options.replacements && options.replacements.waveId || 0); + state.canceledWaveIds.push(waveId); return [[], { affectedRows: 1 }]; } @@ -73,15 +134,40 @@ function createHarness() { const service = new WaveService(ctx); service.batchCreateOrderOperationLogs = async () => 0; + // 快扫副表清理/触发为取消链路外的旁路副作用,stub 掉以保持用例确定性(非取消语义本身) + service.enqueueWaveStrategyQuickScanPostOrderChange = () => {}; + + const matchWaveId = (row, waveIdCondition) => { + if (waveIdCondition && waveIdCondition[Op.in]) { + return waveIdCondition[Op.in].map(id => Number(id)).includes(Number(row.wave_id || 0)); + } + return Number(row.wave_id || 0) === Number(waveIdCondition || 0); + }; + const matchPickStatus = (row, pickStatusCondition) => { + if (pickStatusCondition === undefined) { + return true; + } + if (pickStatusCondition && pickStatusCondition[Op.in]) { + return pickStatusCondition[Op.in].includes(String(row.pick_status || '')); + } + return String(row.pick_status || '') === String(pickStatusCondition); + }; + service.getOrderModel = async () => ({ - async findAll() { - return state.orders.map(item => ({ ...item })); + async findAll(options = {}) { + const where = (options && options.where) || {}; + state.orderFindAllCalls.push({ where }); + return state.orders + .filter(item => matchWaveId(item, where.wave_id)) + .filter(item => matchPickStatus(item, where.pick_status)) + .map(item => ({ ...item })); }, async update(values = {}, options = {}) { - const waveId = Number(options.where && options.where.wave_id || 0); + const where = (options && options.where) || {}; + state.orderUpdateCalls.push({ values, where }); let affected = 0; for (const row of state.orders) { - if (Number(row.wave_id || 0) !== waveId) { + if (!matchWaveId(row, where.wave_id)) { continue; } @@ -117,10 +203,319 @@ describe('test/app/service/systemMethods/order/wave.batchCancel.test.js', () => const deleteCall = state.sqlCalls.find(call => call.sql.includes('DELETE FROM wms_order_wave_index')); assert.ok(deleteCall, '应删除波次索引'); - assert.deepEqual(deleteCall.options.replacements.orderIds.sort((a, b) => a - b), [ 101, 102 ]); + assert.deepEqual( + deleteCall.options.replacements.waveIds.map(id => Number(id)), + [ 11 ] + ); const progress = await service.getBatchCancelTaskProgress('task_cancel_1'); assert.equal(progress.state, 'success'); assert.equal(progress.result.canceled_wave_count, 1); + assert.equal(progress.result.skipped_wave_count, 0); + assert.deepEqual(progress.result.skipped_wave_ids, []); + assert.deepEqual(progress.result.skipped_waves, []); + assert.equal(state.orders.every(order => order.wave_id === 0), true, '取消后订单应被移出波次'); + }); + + it('batchCancel 波次内存在拣货中订单时应整体拒绝,不删除波次、不移出订单', async () => { + const { service, state } = createHarness({ + waves: [ + { wave_id: 11, wave_no: 'W11', wave_status: 0 }, + { wave_id: 12, wave_no: 'W12', wave_status: 0 }, + ], + orders: [ + { id: 101, wave_id: 11, wave_no: 'W11', pick_status: 'padding' }, + { id: 102, wave_id: 11, wave_no: 'W11', pick_status: 'none' }, + { id: 103, wave_id: 12, wave_no: 'W12', pick_status: 'none' }, + ], + }); + + const result = await service.batchCancel({ + warehouse_id: 100000, + wave_ids: [ 11, 12 ], + }); + + assert.equal(result.flag, 'failure'); + assert.equal(result.code, 400); + assert.match(result.message, /禁止取消波次/); + assert.deepEqual(result.wave_ids, [ 11 ], '应仅返回存在拣货中订单的波次'); + assert.deepEqual(result.order_ids, [ 101 ], '应返回命中拣货中订单'); + + // 整体拒绝:不得执行任何取消动作 + assert.equal( + state.sqlCalls.some(call => call.sql.includes('DELETE FROM wms_order_wave_index')), + false, + '整体拒绝时不得删除波次索引' + ); + assert.equal( + state.sqlCalls.some(call => call.sql.includes('SET wave_status = -1')), + false, + '整体拒绝时不得更新波次状态' + ); + assert.equal(state.orderUpdateCalls.length, 0, '整体拒绝时不得移出订单'); + assert.equal( + state.cacheKeys.some(key => key.startsWith(BATCH_CANCEL_TASK_CACHE_KEY_PREFIX)), + false, + '整体拒绝时不得提交后台取消任务' + ); + assert.equal(state.orders.every(order => order.wave_id !== 0), true, '所有订单应保持原波次'); + assert.equal( + state.orderFindAllCalls.some(call => call.where.pick_status && call.where.pick_status[Op.in]), + true, + '应执行拣货状态守卫查询' + ); + }); + + it('batchCancel 波次内存在拣货完成订单时应整体拒绝', async () => { + const { service, state } = createHarness({ + waves: [ + { wave_id: 11, wave_no: 'W11', wave_status: 1 }, + ], + orders: [ + { id: 101, wave_id: 11, wave_no: 'W11', pick_status: 'fin' }, + { id: 102, wave_id: 11, wave_no: 'W11', pick_status: 'none' }, + ], + }); + + const result = await service.batchCancel({ + warehouse_id: 100000, + wave_ids: [ 11 ], + }); + + assert.equal(result.flag, 'failure'); + assert.equal(result.code, 400); + assert.match(result.message, /禁止取消波次/); + assert.deepEqual(result.wave_ids, [ 11 ]); + assert.deepEqual(result.order_ids, [ 101 ]); + assert.equal( + state.sqlCalls.some(call => call.sql.includes('SET wave_status = -1')), + false + ); + assert.equal(state.orderUpdateCalls.length, 0); + assert.equal( + state.cacheKeys.some(key => key.startsWith(BATCH_CANCEL_TASK_CACHE_KEY_PREFIX)), + false + ); + }); + + it('batchCancel 波次已进入拣货及后续环节(wave_status >= 3)时应拒绝', async () => { + const { service, state } = createHarness({ + waves: [ + { wave_id: 11, wave_no: 'W11', wave_status: 3 }, + ], + orders: [ + { id: 101, wave_id: 11, wave_no: 'W11', pick_status: 'none' }, + ], + }); + + const result = await service.batchCancel({ + warehouse_id: 100000, + wave_ids: [ 11 ], + }); + + assert.equal(result.flag, 'failure'); + assert.equal(result.code, 400); + assert.match(result.message, /禁止取消波次/); + assert.deepEqual(result.wave_ids, [ 11 ]); + assert.equal( + state.sqlCalls.some(call => call.sql.includes('wave_status >= 3')), + true, + '应执行 wave_status >= 3 兜底校验查询' + ); + assert.equal( + state.sqlCalls.some(call => call.sql.includes('SET wave_status = -1')), + false + ); + assert.equal(state.orderUpdateCalls.length, 0); + assert.equal( + state.cacheKeys.some(key => key.startsWith(BATCH_CANCEL_TASK_CACHE_KEY_PREFIX)), + false + ); + }); + + it('batchCancel 未拣货波次(pick_status=none、wave_status<3)应正常提交取消任务', async () => { + const { service, state } = createHarness({ + waves: [ + { wave_id: 11, wave_no: 'W11', wave_status: 1 }, + ], + orders: [ + { id: 101, wave_id: 11, wave_no: 'W11', pick_status: 'none' }, + { id: 102, wave_id: 11, wave_no: 'W11', pick_status: 'none' }, + ], + }); + + service.runBatchCancelTask = async params => { + state.backgroundTaskCalls.push({ ...params }); + }; + + const result = await service.batchCancel({ + warehouse_id: 100000, + wave_ids: [ 11 ], + }); + + assert.equal(result.flag, 'success'); + assert.equal(typeof result.task_id, 'string'); + assert.ok(result.task_id.length > 0); + assert.equal(result.message, '批量解除波次任务已提交。'); + + await waitImmediate(); + assert.equal(state.backgroundTaskCalls.length, 1, '应触发后台取消任务'); + assert.deepEqual(state.backgroundTaskCalls[0], { + taskId: result.task_id, + warehouseId: 100000, + waveIds: [ 11 ], + }); + + const submitted = await service.getBatchCancelTaskProgress(result.task_id); + assert.equal(submitted.state, 'submitted'); + assert.equal(submitted.warehouse_id, 100000); + assert.equal(submitted.wave_ids, '11'); + }); + + it('runBatchCancelTask 波次已进入拣货及后续环节时应跳过并返回 skipped_waves', async () => { + const { service, state } = createHarness({ + waves: [ + { wave_id: 11, wave_no: 'W11', wave_status: 3 }, + ], + orders: [ + { id: 101, wave_id: 11, wave_no: 'W11', pick_status: 'none' }, + ], + }); + + await service.setBatchCancelTaskProgress('task_skip_status', 'submitted', { + warehouse_id: 100000, + wave_ids: '11', + wave_id_list: [ 11 ], + }); + + await service.runBatchCancelTask({ + taskId: 'task_skip_status', + warehouseId: 100000, + waveIds: [ 11 ], + }); + + const progress = await service.getBatchCancelTaskProgress('task_skip_status'); + assert.equal(progress.state, 'success'); + assert.equal(progress.result.canceled_wave_count, 0); + assert.equal(progress.result.skipped_wave_count, 1); + assert.deepEqual(progress.result.skipped_wave_ids, [ 11 ]); + assert.deepEqual(progress.result.skipped_waves, [ + { wave_id: 11, wave_no: 'W11', reason: 'wave_status_blocked', wave_status: 3 }, + ]); + + // 跳过时不得执行任何取消动作 + assert.equal( + state.sqlCalls.some(call => call.sql.includes('SET wave_status = -1')), + false + ); + assert.equal( + state.sqlCalls.some(call => call.sql.includes('DELETE FROM wms_order_wave_index')), + false + ); + assert.equal(state.orderUpdateCalls.length, 0); + assert.equal(state.orders[0].wave_id, 11, '订单应保持原波次'); + }); + + it('runBatchCancelTask 波次内存在拣货中/拣货完成订单时应跳过并记录 picked_orders_exist', async () => { + const { service, state } = createHarness({ + waves: [ + { wave_id: 11, wave_no: 'W11', wave_status: 0 }, + ], + orders: [ + { id: 101, wave_id: 11, wave_no: 'W11', pick_status: 'padding' }, + { id: 102, wave_id: 11, wave_no: 'W11', pick_status: 'fin' }, + { id: 103, wave_id: 11, wave_no: 'W11', pick_status: 'none' }, + ], + }); + + await service.setBatchCancelTaskProgress('task_skip_picked', 'submitted', { + warehouse_id: 100000, + wave_ids: '11', + wave_id_list: [ 11 ], + }); + + await service.runBatchCancelTask({ + taskId: 'task_skip_picked', + warehouseId: 100000, + waveIds: [ 11 ], + }); + + const progress = await service.getBatchCancelTaskProgress('task_skip_picked'); + assert.equal(progress.state, 'success'); + assert.equal(progress.result.canceled_wave_count, 0); + assert.equal(progress.result.skipped_wave_count, 1); + assert.deepEqual(progress.result.skipped_wave_ids, [ 11 ]); + assert.equal(progress.result.skipped_waves.length, 1); + assert.equal(progress.result.skipped_waves[0].wave_id, 11); + assert.equal(progress.result.skipped_waves[0].wave_no, 'W11'); + assert.equal(progress.result.skipped_waves[0].reason, 'picked_orders_exist'); + assert.equal(progress.result.skipped_waves[0].picked_order_count, 2); + + assert.equal(state.rollbackCount, 1, '命中拣货守卫后应回滚事务'); + assert.equal( + state.sqlCalls.some(call => call.sql.includes('SET wave_status = -1')), + false + ); + assert.equal( + state.sqlCalls.some(call => call.sql.includes('DELETE FROM wms_order_wave_index')), + false + ); + assert.equal(state.orderUpdateCalls.length, 0); + assert.equal(state.orders.every(order => order.wave_id === 11), true, '订单应保持原波次'); + }); + + it('runBatchCancelTask 混合波次:正常波次取消、命中条件的波次跳过', async () => { + const { service, state } = createHarness({ + waves: [ + { wave_id: 11, wave_no: 'W11', wave_status: 0 }, + { wave_id: 12, wave_no: 'W12', wave_status: 3 }, + { wave_id: 13, wave_no: 'W13', wave_status: 0 }, + ], + orders: [ + { id: 101, wave_id: 11, wave_no: 'W11', pick_status: 'none' }, + { id: 102, wave_id: 11, wave_no: 'W11', pick_status: 'none' }, + { id: 103, wave_id: 12, wave_no: 'W12', pick_status: 'none' }, + { id: 104, wave_id: 13, wave_no: 'W13', pick_status: 'padding' }, + { id: 105, wave_id: 13, wave_no: 'W13', pick_status: 'none' }, + ], + }); + + await service.setBatchCancelTaskProgress('task_mixed', 'submitted', { + warehouse_id: 100000, + wave_ids: '11,12,13', + wave_id_list: [ 11, 12, 13 ], + }); + + await service.runBatchCancelTask({ + taskId: 'task_mixed', + warehouseId: 100000, + waveIds: [ 11, 12, 13 ], + }); + + const progress = await service.getBatchCancelTaskProgress('task_mixed'); + assert.equal(progress.state, 'success'); + assert.equal(progress.result.canceled_wave_count, 1); + assert.deepEqual(progress.result.affected_wave_ids, [ 11 ]); + assert.equal(progress.result.affected_order_count, 2); + assert.equal(progress.result.skipped_wave_count, 2); + assert.deepEqual(progress.result.skipped_wave_ids, [ 12, 13 ]); + assert.deepEqual( + progress.result.skipped_waves.map(item => item.reason), + [ 'wave_status_blocked', 'picked_orders_exist' ] + ); + + assert.deepEqual(state.canceledWaveIds, [ 11 ], '仅正常波次执行取消'); + const deleteCall = state.sqlCalls.find(call => call.sql.includes('DELETE FROM wms_order_wave_index')); + assert.deepEqual( + deleteCall.options.replacements.waveIds.map(id => Number(id)), + [ 11 ] + ); + assert.deepEqual( + state.orders.filter(order => [ 101, 102 ].includes(order.id)).map(order => order.wave_id), + [ 0, 0 ], + '正常波次订单应被移出波次' + ); + assert.equal(state.orders.find(order => order.id === 103).wave_id, 12, '被跳过波次订单保持原波次'); + assert.equal(state.orders.find(order => order.id === 104).wave_id, 13, '被跳过波次订单保持原波次'); }); }); From 3100bddce1ad07f4e124e4292de24e956561e8b0 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sun, 30 Aug 2026 07:28:01 +0800 Subject: [PATCH 293/550] =?UTF-8?q?feat(report):=20=E9=85=8D=E7=BD=AE?= =?UTF-8?q?=E9=A9=B1=E5=8A=A8=E9=80=9A=E7=94=A8=E6=8A=A5=E8=A1=A8=E4=B8=8E?= =?UTF-8?q?=E8=B4=A7=E4=B8=BB=E5=AE=9A=E6=97=B6=E6=8A=95=E9=80=92=EF=BC=8C?= =?UTF-8?q?Excel=20=E6=96=87=E6=9C=AC=E5=88=97=E8=90=BD=E5=9C=B0=E4=B8=8E?= =?UTF-8?q?=E6=88=90=E5=91=98=E7=BA=A7=E9=80=9A=E7=9F=A5=E6=8E=A8=E9=80=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 + app/lib/report/day_window.js | 171 ++ app/lib/report/formatters.js | 167 ++ app/lib/report/notifyTemplate.js | 101 ++ app/lib/report/render.js | 233 +++ app/model/report_definition.js | 86 + app/model/report_delivery_log.js | 134 ++ app/model/report_delivery_plan.js | 115 ++ app/schedule/report_delivery_dispatch.js | 42 + app/service/systemMethods/report.js | 294 ++++ .../systemMethods/report/definition.js | 137 ++ .../systemMethods/report/deliveryLog.js | 50 + .../systemMethods/report/deliveryPlan.js | 130 ++ app/service/systems/excel.js | 76 + app/service/systems/notice/index.js | 9 +- app/service/systems/report.js | 610 +++++++ app/service/systems/report/queries/index.js | 57 + .../report/queries/sevenDayStockFlow.js | 282 ++++ app/service/systems/reportDelivery.js | 1475 +++++++++++++++++ app/service/systems/warehouseNotify.js | 79 +- ...20000-create-wms-report-delivery-tables.js | 321 ++++ ...dd-notify-fields-to-wms-report-delivery.js | 77 + ...70000-normalize-report-channel-to-inbox.js | 55 + ...000-restructure-report-definition-by-id.js | 166 ++ ...00-add-name-to-wms-report-delivery-plan.js | 56 + docs/report-config-guide.md | 342 ++++ 26 files changed, 5246 insertions(+), 21 deletions(-) create mode 100644 app/lib/report/day_window.js create mode 100644 app/lib/report/formatters.js create mode 100644 app/lib/report/notifyTemplate.js create mode 100644 app/lib/report/render.js create mode 100644 app/model/report_definition.js create mode 100644 app/model/report_delivery_log.js create mode 100644 app/model/report_delivery_plan.js create mode 100644 app/schedule/report_delivery_dispatch.js create mode 100644 app/service/systemMethods/report.js create mode 100644 app/service/systemMethods/report/definition.js create mode 100644 app/service/systemMethods/report/deliveryLog.js create mode 100644 app/service/systemMethods/report/deliveryPlan.js create mode 100644 app/service/systems/report.js create mode 100644 app/service/systems/report/queries/index.js create mode 100644 app/service/systems/report/queries/sevenDayStockFlow.js create mode 100644 app/service/systems/reportDelivery.js create mode 100644 database/migrations/20260829120000-create-wms-report-delivery-tables.js create mode 100644 database/migrations/20260829160000-add-notify-fields-to-wms-report-delivery.js create mode 100644 database/migrations/20260829170000-normalize-report-channel-to-inbox.js create mode 100644 database/migrations/20260830120000-restructure-report-definition-by-id.js create mode 100644 database/migrations/20260830130000-add-name-to-wms-report-delivery-plan.js create mode 100644 docs/report-config-guide.md diff --git a/README.md b/README.md index d237237..2ecfed1 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ - Method 路由映射说明:`AI_METHOD_ROUTING.md` - system 接口文档源:`methods/system.json` - qimen 接口文档源:`methods/qimen.json` +- 配置驱动报表配置说明:`docs/report-config-guide.md` - 日报:`day.log` ## 项目目录结构 @@ -39,6 +40,7 @@ - `AI_METHOD_ROUTING.md`:接口入口与 method 到代码文件的映射。 - `methods/system.json`:system 接口定义(headers、groups、params、response、errors)。 - `methods/qimen.json`:qimen 接口定义(按奇门协议组织)。 +- `docs/report-config-guide.md`:配置驱动通用报表(wms_report_definition 三段 JSON 配置、内置查询器口径)与货主定时投递说明。 - `day.log`:每日工作留痕。 ## 快速开始 diff --git a/app/lib/report/day_window.js b/app/lib/report/day_window.js new file mode 100644 index 0000000..9b30a27 --- /dev/null +++ b/app/lib/report/day_window.js @@ -0,0 +1,171 @@ +'use strict'; + +/** + * 报表「日窗口」纯函数工具模块(无 ctx 依赖,可单测)。 + * + * 日窗口定义:[D 07:00, D+1 07:00) 半开区间(毫秒时间戳), + * 与旧 PHP《7日出入库数据》(Wms.php putout_putin_storage7) 的 + * 07:00 切日口径保持一致,统一使用服务器本地时区(不依赖 UTC)。 + */ + +const DEFAULT_DAY_COUNT = 7; +const DEFAULT_CUTOVER_HOUR = 7; + +/** + * 数字补零为两位字符串。 + * @param {number} value 数值 + * @return {string} 补零后的两位字符串 + */ +function pad2(value) { + return String(value).padStart(2, '0'); +} + +/** + * 按本地时区构建连续的日窗口列表(最旧在前)。 + * + * 规则: + * 1. 每个窗口为 [D 07:00, D+1 07:00)(cutoverHour 可配置),start 含、end 不含; + * 2. 最新窗口是「包含 now 的窗口」:now 当日已过切点时从今日切点起算, + * 未过切点时从昨日切点起算; + * 3. 窗口共 dayCount 个,按时间从旧到新排列; + * 4. 通过 `new Date(y, m, d + offset, hour)` 构造,规避夏令时导致的 24h 步进偏差。 + * + * @param {Object} [options={}] 构建选项 + * @param {number} [options.dayCount=7] 窗口数量 + * @param {number} [options.cutoverHour=7] 切点小时(0-23) + * @param {number|Date} [options.now=Date.now()] 参考时刻 + * @return {Array<{start: number, end: number}>} 日窗口列表(毫秒,最旧在前) + */ +function buildDayWindows({ dayCount = DEFAULT_DAY_COUNT, cutoverHour = DEFAULT_CUTOVER_HOUR, now = Date.now() } = {}) { + const normalizedCount = Math.max(1, Math.floor(Number(dayCount) || DEFAULT_DAY_COUNT)); + const normalizedHour = Math.min(23, Math.max(0, Math.floor(Number(cutoverHour) || 0))); + const current = new Date(Number(now) || Date.now()); + + // 今天切点:本地时区当日 07:00 + let anchor = new Date( + current.getFullYear(), + current.getMonth(), + current.getDate(), + normalizedHour, + 0, + 0, + 0 + ); + + // 未到今日切点:最新窗口尚未开始,从昨日切点起算 + if (current.getTime() < anchor.getTime()) { + anchor = new Date( + anchor.getFullYear(), + anchor.getMonth(), + anchor.getDate() - 1, + normalizedHour, + 0, + 0, + 0 + ); + } + + const windows = []; + for (let index = 0; index < normalizedCount; index += 1) { + // 最旧在前:dayOffset 从 -(count-1) 递增到 0 + const dayOffset = index - (normalizedCount - 1); + const start = new Date( + anchor.getFullYear(), + anchor.getMonth(), + anchor.getDate() + dayOffset, + normalizedHour, + 0, + 0, + 0 + ); + const end = new Date( + anchor.getFullYear(), + anchor.getMonth(), + anchor.getDate() + dayOffset + 1, + normalizedHour, + 0, + 0, + 0 + ); + windows.push({ + start: start.getTime(), + end: end.getTime(), + }); + } + + return windows; +} + +/** + * 按 PHP date() 风格的 token 格式化窗口开始日期(本地时区,无前导零)。 + * + * 支持的 token: + * Y=四位年;y=两位年;m=补零月;n=无前导零月;d=补零日;j=无前导零日; + * H=补零小时;i=补零分钟;s=补零秒。其余字符原样保留。 + * + * @param {Array<{start: number, end: number}>} windows 日窗口列表 + * @param {number} index 窗口下标 + * @param {string} [pattern='Y/n/j'] 日期格式模板(如 '2026/8/23') + * @return {string} 格式化后的日期字符串 + */ +function formatWindowStart(windows, index, pattern = 'Y/n/j') { + const windowItem = Array.isArray(windows) ? windows[index] : null; + if (!windowItem || !Number.isFinite(Number(windowItem.start))) { + return ''; + } + + const date = new Date(Number(windowItem.start)); + const tokens = { + Y: String(date.getFullYear()), + y: String(date.getFullYear()).slice(2), + m: pad2(date.getMonth() + 1), + n: String(date.getMonth() + 1), + d: pad2(date.getDate()), + j: String(date.getDate()), + H: pad2(date.getHours()), + i: pad2(date.getMinutes()), + s: pad2(date.getSeconds()), + }; + + return String(pattern || 'Y/n/j').replace(/[YymndjHis]/g, character => tokens[character]); +} + +/** + * 取时刻的本地 'HH:mm'(补零)。 + * @param {Date|number} date 日期对象或毫秒时间戳 + * @return {string} 'HH:mm' 格式字符串 + */ +function hhmmOf(date) { + const normalizedDate = date instanceof Date ? date : new Date(Number(date) || Date.now()); + return `${pad2(normalizedDate.getHours())}:${pad2(normalizedDate.getMinutes())}`; +} + +/** + * 取时刻的本地自然日('YYYY-MM-DD')。 + * @param {Date|number} date 日期对象或毫秒时间戳 + * @return {string} 'YYYY-MM-DD' 格式字符串 + */ +function scheduleDateOf(date) { + const normalizedDate = date instanceof Date ? date : new Date(Number(date) || Date.now()); + return `${normalizedDate.getFullYear()}-${pad2(normalizedDate.getMonth() + 1)}-${pad2(normalizedDate.getDate())}`; +} + +/** + * 从窗口参数对象解析 dayCount/cutoverHour,供查询器与元数据接口共用。 + * 口径与查询器保持一致:dayCount 缺省 7(<=0 视为 7),cutoverHour 缺省 7 且钳制到 0-23。 + * @param {Object} [params={}] 窗口参数(支持 dayCount/day_count、cutoverHour/cutover_hour) + * @return {{dayCount: number, cutoverHour: number}} 归一化窗口参数 + */ +function resolveWindowConfig(params = {}) { + const dayCount = Math.max(1, Math.floor(Number(params.dayCount || params.day_count || 7))); + const cutoverHour = Math.min(23, Math.max(0, Math.floor(Number(params.cutoverHour ?? params.cutover_hour ?? 7)))); + return { dayCount, cutoverHour }; +} + +module.exports = { + buildDayWindows, + formatWindowStart, + hhmmOf, + scheduleDateOf, + resolveWindowConfig, +}; diff --git a/app/lib/report/formatters.js b/app/lib/report/formatters.js new file mode 100644 index 0000000..4d1b61d --- /dev/null +++ b/app/lib/report/formatters.js @@ -0,0 +1,167 @@ +'use strict'; + +/** + * 报表单元格格式化器注册表(纯函数模块,无 ctx 依赖,可单测)。 + * + * 设计约定: + * 1. 所有格式化器首参为单元格原始值(value),其余参数为格式化参数; + * 2. 数值计算统一走「截断取整」(等价旧 PHP 的 intval 语义,向零取整); + * 3. 低库存补偿口径与旧 PHP《7日出入库数据》保持一致: + * 可用库存 < 20 且 7 日入库 < 20 时视为低库存,触发补偿与预警。 + */ + +/** + * 安全转数值:非有限数值一律按 0 处理。 + * @param {*} value 原始值 + * @return {number} 数值 + */ +function toFiniteNumber(value) { + const number = Number(value); + return Number.isFinite(number) ? number : 0; +} + +/** + * 截断取整(PHP intval 语义,向零取整)。 + * @param {*} value 原始值 + * @return {number} 整数 + */ +function integer(value) { + return Math.trunc(toFiniteNumber(value)); +} + +/** + * 零值占位:0 / '0' / null / undefined / '' 统一显示为 '-'。 + * 说明:'0' 一并转 '-',与 PHP empty('0') 为真的旧口径保持一致。 + * @param {*} value 原始值 + * @return {*} 非零原值或 '-' + */ +function zeroToDash(value) { + if (value === 0 || value === '0' || value === null || value === undefined || value === '') { + return '-'; + } + return value; +} + +/** + * 布尔转中文:真值 → '是',假值 → '否'。 + * 说明:''、0、'0'、null、undefined、false 均视为假,与 PHP 布尔语义对齐。 + * @param {*} flag 原始值 + * @return {string} '是' 或 '否' + */ +function yesNo(flag) { + const falsy = flag === false + || flag === null + || flag === undefined + || flag === '' + || flag === 0 + || flag === '0' + || String(flag).toLowerCase() === 'false'; + return falsy ? '否' : '是'; +} + +/** + * 7 日日均 ×10 取整(保留一位小数但避免浮点误差)。 + * 公式:int(total / days * 10),与旧 PHP intval($ck / 7 * 10) 一致。 + * @param {*} value 周期合计值 + * @param {*} days 天数 + * @return {number} 日均×10 的整数 + */ +function avgDaysPerWeek(value, days) { + const total = toFiniteNumber(value); + const dayCount = toFiniteNumber(days); + if (dayCount <= 0) { + return 0; + } + return Math.trunc((total / dayCount) * 10); +} + +/** + * 建议补货量(含低库存补偿): + * 基础值 int(ck_total / 7 * 10);仅当低库存(available < 20 且 rk_total < 20)时 + * 补偿到不低于 30(保证低库存货主获得最小补货建议)。 + * @param {*} ckTotal 7 日总出库 + * @param {*} available 可用库存 + * @param {*} rkTotal 7 日总入库 + * @return {number} 建议补货量 + */ +function suggestWithCompensate(ckTotal, available, rkTotal) { + const base = Math.trunc((toFiniteNumber(ckTotal) / 7) * 10); + const availableNumber = toFiniteNumber(available); + const rkNumber = toFiniteNumber(rkTotal); + if (availableNumber < 20 && rkNumber < 20) { + return Math.max(base, 30); + } + return base; +} + +/** + * 库存预警判定(布尔): + * 1. 按 7 日均出库 ×4 折算的周转阈值高于可用库存(int(ck/7*4) - available > 0); + * 2. 或处于低库存状态(available < 20 且 rk_total < 20)。 + * 展示时建议叠加 yesNo 格式化器转中文。 + * @param {*} ckTotal 7 日总出库 + * @param {*} available 可用库存 + * @param {*} rkTotal 7 日总入库 + * @return {boolean} 是否预警 + */ +function warnOf(ckTotal, available, rkTotal) { + const threshold = Math.trunc((toFiniteNumber(ckTotal) / 7) * 4); + return threshold - toFiniteNumber(available) > 0 + || (toFiniteNumber(available) < 20 && toFiniteNumber(rkTotal) < 20); +} + +/** + * 文本前缀工厂:返回一个给文本加前缀的格式化函数。 + * 典型用法:`'` 前缀防科学计数法(Excel 将长数字串强制按文本展示)。 + * @param {string} [prefix=''] 前缀 + * @return {Function} 格式化函数 (value) => `${prefix}${value}` + */ +function textPrefix(prefix = '') { + return value => `${String(prefix || '')}${value === null || value === undefined ? '' : String(value)}`; +} + +/** + * 格式化器注册表(配置驱动报表按名称引用)。 + * @type {Object} + */ +const FORMATTERS = Object.freeze({ + textPrefix: (value, prefix) => textPrefix(prefix)(value), + zeroToDash, + yesNo, + integer, + avgDaysPerWeek, + suggestWithCompensate, + warnOf, +}); + +/** + * 按名称应用格式化器。 + * @param {string} name 格式化器名称 + * @param {*} value 单元格原始值 + * @param {...*} args 格式化器额外参数 + * @return {*} 格式化结果 + * @throws {Error} 未知格式化器名称时抛出 + */ +function applyFormat(name, value, ...args) { + const formatterName = String(name || '').trim(); + if (!formatterName) { + return value; + } + const formatter = FORMATTERS[formatterName]; + if (typeof formatter !== 'function') { + throw new Error(`未知的报表格式化器: ${formatterName}`); + } + return formatter(value, ...args); +} + +module.exports = { + FORMATTERS, + applyFormat, + textPrefix, + zeroToDash, + yesNo, + integer, + avgDaysPerWeek, + suggestWithCompensate, + warnOf, +}; diff --git a/app/lib/report/notifyTemplate.js b/app/lib/report/notifyTemplate.js new file mode 100644 index 0000000..e3b0149 --- /dev/null +++ b/app/lib/report/notifyTemplate.js @@ -0,0 +1,101 @@ +'use strict'; + +/** + * 货主报表文本通知模板渲染器(纯函数模块,无 ctx 依赖,可单测)。 + * + * 标签白名单(其余 {xxx} 一律不替换,保存入口由 reportDelivery.savePlan 校验拦截): + * - {time} 发送时间,格式 YYYY-MM-DD HH:mm + * - {url} 报表文件下载链接(url 为空时替换为兜底文案) + * - {report_name} 报表名称 + * - {biz_date} 数据日期 YYYY-MM-DD + */ + +/** 模板标签白名单 */ +const ALLOWED_TAGS = Object.freeze([ 'time', 'url', 'report_name', 'biz_date' ]); + +/** + * url 为空时的兜底文案。 + * 理由:生成结果 url 可能因异步上传尚未就绪,以占位文案保证通知可达, + * 避免因链接缺失引发整链路失败重试风暴;实际链接可在投递记录中查看。 + */ +const EMPTY_URL_FALLBACK = '文件生成中,稍后可在投递记录中查看'; + +/** 模板标签匹配正则:{xxx} 占位 */ +const TAG_PATTERN = /\{([^{}]+)\}/g; + +/** + * 提取模板中出现过的全部标签名(按出现顺序,含重复项)。 + * @param {string} template 模板字符串 + * @return {Array} 标签名数组 + */ +function extractTagNames(template) { + const names = []; + const source = String(template || ''); + let match = TAG_PATTERN.exec(source); + while (match) { + names.push(String(match[1]).trim()); + match = TAG_PATTERN.exec(source); + } + return names; +} + +/** + * 校验模板标签是否全部位于白名单内(未知标签不替换、保存时拒绝)。 + * @param {string} template 模板字符串 + * @return {{valid: boolean, invalidTags: Array}} 校验结果(invalidTags 已去重) + */ +function validateNotifyTemplate(template) { + const names = extractTagNames(template); + const invalidSet = new Set(); + for (const name of names) { + if (!ALLOWED_TAGS.includes(name)) { + invalidSet.add(name); + } + } + return { valid: invalidSet.size === 0, invalidTags: [ ...invalidSet ] }; +} + +/** + * 渲染通知模板:仅替换白名单标签,未知标签原样保留(保存入口已校验拦截)。 + * @param {string} template 模板字符串 + * @param {Object} [context={}] 渲染上下文 + * @param {string} [context.time=''] 发送时间(YYYY-MM-DD HH:mm) + * @param {string} [context.url=''] 报表文件下载链接(空则替换为兜底文案) + * @param {string} [context.reportName=''] 报表名称 + * @param {string} [context.bizDate=''] 数据日期(YYYY-MM-DD) + * @return {string} 渲染后的通知文本 + */ +function renderNotifyTemplate(template, context = {}) { + const url = String((context && context.url) || '').trim() || EMPTY_URL_FALLBACK; + const replacements = { + time: String((context && context.time) || ''), + url, + report_name: String((context && context.reportName) || ''), + biz_date: String((context && context.bizDate) || ''), + }; + return String(template || '').replace(TAG_PATTERN, (raw, name) => { + const key = String(name).trim(); + return Object.prototype.hasOwnProperty.call(replacements, key) ? replacements[key] : raw; + }); +} + +/** + * 格式化发送时间为 YYYY-MM-DD HH:mm(服务器本地时区)。 + * @param {Date} [date=new Date()] 时刻 + * @return {string} 格式化后的时间字符串 + */ +function formatNotifyTime(date) { + const target = date instanceof Date ? date : new Date(); + const pad = value => String(value).padStart(2, '0'); + return `${target.getFullYear()}-${pad(target.getMonth() + 1)}-${pad(target.getDate())} ` + + `${pad(target.getHours())}:${pad(target.getMinutes())}`; +} + +module.exports = { + ALLOWED_TAGS, + EMPTY_URL_FALLBACK, + extractTagNames, + validateNotifyTemplate, + renderNotifyTemplate, + formatNotifyTime, +}; diff --git a/app/lib/report/render.js b/app/lib/report/render.js new file mode 100644 index 0000000..1b82da8 --- /dev/null +++ b/app/lib/report/render.js @@ -0,0 +1,233 @@ +'use strict'; + +const { applyFormat } = require('./formatters'); +const { formatWindowStart } = require('./day_window'); + +/** + * 报表渲染翻译层(纯函数模块,无 ctx 依赖,可单测)。 + * + * 输入:报表类型 type 的硬编码字段注册清单(fields,按勾选顺序)+ 查询器产出的数据 rows; + * 输出:适配 `app/service/systems/excel.js` 的 sheets 参数结构 + * ({ name, columns, rows, merges, styledRows, textColumns? })。 + * + * 约定(与 excel.js 的 buildExcelJsWorkbook 对齐): + * 1. 数据以 AOA(二维数组)形式输出,表头行内联在 rows 首位,columns 恒传空数组; + * 2. merges 统一输出 {s:{r,c}, e:{r,c}} 结构(excel.js 两套构建器均支持); + * 3. textColumns 输出 0 基列索引,由 excel.js 落地为文本单元格。 + * + * 列规则(全部由字段注册清单硬编码决定,无 sheet_config 自定义): + * 1. string 字段 → 静态列(header=label),asText=true 时加入 textColumns; + * 2. number 字段 → 静态列,统一 zeroToDash(0/''/null 显示 '-'); + * 3. boolean 字段 → 静态列,统一 yesNo(真→是,假→否); + * 4. array 字段 → 窗口展开列:per=窗口数,pair=children keys,表头第 1 行按窗口 + * 输出 '{date}' 日期(Y/n/j 无前导零)并在每窗口 pair.length>1 时横向合并, + * 表头第 2 行按 children label 填充;子字段为 number 时单元格统一 zeroToDash; + * 5. 存在展开列时启用两行表头,其余列表头纵向合并(如 A1:A2)。 + */ + +/** + * 判断字段是否为普通对象。 + * @param {*} field 待判断字段 + * @return {boolean} 是否普通对象 + */ +function isPlainObject(field) { + return Boolean(field) && typeof field === 'object' && !Array.isArray(field); +} + +/** + * 规范化字段注册清单:仅保留含 key 的对象,key 统一为字符串。 + * @param {Array} fields 字段清单(注册表 fields,按勾选顺序) + * @return {Array} 规范化字段清单 + */ +function normalizeFields(fields) { + if (!Array.isArray(fields)) { + return []; + } + return fields + .filter(field => isPlainObject(field) && String(field.key || '').trim()) + .map(field => ({ ...field, key: String(field.key).trim() })); +} + +/** + * 按类型字段清单构建列计划(含窗口展开与表头合并)。 + * @param {Object} [options={}] 构建选项 + * @param {Array} [options.fields=[]] 字段注册清单(按勾选顺序) + * @param {Array} [options.windows=[]] 日窗口列表(展开列 per 取窗口数) + * @return {{columns: Array, headerRowCount: number, generatedMerges: Array}} 列计划 + */ +function buildColumnPlan({ fields = [], windows = [] } = {}) { + const safeFields = normalizeFields(fields); + const safeWindows = Array.isArray(windows) ? windows : []; + const expandPer = Math.max(1, safeWindows.length || 7); + + const columns = []; + const generatedMerges = []; + let expandStartColumn = -1; + + for (const field of safeFields) { + if (field.type === 'array') { + const children = Array.isArray(field.children) ? field.children : []; + const pair = children.length > 0 ? children : [{ key: 'value', label: '值', type: 'string' }]; + expandStartColumn = columns.length; + for (let windowIndex = 0; windowIndex < expandPer; windowIndex += 1) { + for (let pairIndex = 0; pairIndex < pair.length; pairIndex += 1) { + columns.push({ + type: 'expand', + windowIndex, + pairIndex, + pair: pair[pairIndex] && isPlainObject(pair[pairIndex]) ? pair[pairIndex] : {}, + headerRow1Template: '{date}', + headerRow2List: pair.map(child => String((child && child.label) || '')), + }); + } + if (pair.length > 1) { + // 每窗口多列表头横向合并(如 D1:E1 … P1:Q1) + const groupStart = expandStartColumn + windowIndex * pair.length; + generatedMerges.push({ + s: { r: 0, c: groupStart }, + e: { r: 0, c: groupStart + pair.length - 1 }, + }); + } + } + continue; + } + columns.push({ + type: field.type === 'array' ? 'static' : (field.type || 'string'), + header: String(field.label || field.key || ''), + field: field.key, + asText: field.asText === true, + }); + } + + const hasExpandColumn = columns.some(column => column.type === 'expand'); + const headerRowCount = hasExpandColumn ? 2 : 1; + + // 两行表头下,非展开列按列纵向合并(A1:A2 等) + if (headerRowCount === 2) { + columns.forEach((column, columnIndex) => { + if (column.type !== 'expand') { + generatedMerges.push({ + s: { r: 0, c: columnIndex }, + e: { r: 1, c: columnIndex }, + }); + } + }); + } + + return { + columns, + headerRowCount, + generatedMerges, + }; +} + +/** + * 构建表头第 1 行(展开列按窗口开始日期输出 'Y/n/j' 无前导零)。 + * @param {Array} columns 列计划 + * @param {Array} windows 日窗口列表 + * @return {Array} 表头第 1 行 + */ +function buildHeaderRow1(columns, windows = []) { + return columns.map(column => { + if (column.type === 'expand') { + return formatWindowStart(windows, column.windowIndex, 'Y/n/j'); + } + return column.header; + }); +} + +/** + * 构建表头第 2 行(单行表头模式下返回 null;展开列按 pair label 填充)。 + * @param {Array} columns 列计划 + * @param {number} headerRowCount 表头行数 + * @return {Array|null} 表头第 2 行 + */ +function buildHeaderRow2(columns, headerRowCount) { + if (headerRowCount !== 2) { + return null; + } + return columns.map(column => { + if (column.type === 'expand') { + const list = column.headerRow2List; + return list.length > 0 ? list[column.pairIndex % list.length] || '' : ''; + } + return ''; + }); +} + +/** + * 渲染单个单元格(按列类型与字段类型硬编码格式化口径)。 + * @param {Object} column 列计划 + * @param {Object} row 数据行 + * @return {*} 单元格值 + */ +function renderCell(column, row = {}) { + if (column.type === 'expand') { + const daily = Array.isArray(row.daily) ? row.daily : []; + const day = daily[column.windowIndex]; + const value = day && typeof day === 'object' ? day[column.pair.key] : 0; + return applyFormat(column.pair.type === 'number' ? 'zeroToDash' : '', value); + } + + const value = row[column.field]; + if (column.type === 'boolean') { + return applyFormat('yesNo', value); + } + if (column.type === 'number') { + return applyFormat('zeroToDash', value); + } + return value; +} + +/** + * 按类型字段注册清单渲染 sheet(配置极简:无 sheet_config 自定义列/合并/样式)。 + * + * @param {Object} [options={}] 渲染选项 + * @param {string} [options.type=''] 报表类型(查询器注册 key,仅透传不参与渲染口径) + * @param {string} [options.title='报表'] sheet 名称(报表标题) + * @param {Array} [options.fields=[]] 字段注册清单(按勾选顺序) + * @param {Array} [options.rows=[]] 查询器产出的数据行 + * @param {Array} [options.windows=[]] 日窗口列表 + * @return {Object} excel.js sheet 参数 + * ({name, columns, rows, merges, styledRows},存在 asText 列时附带 textColumns) + */ +function renderSheetByType({ type = '', title = '报表', fields = [], rows = [], windows = [] } = {}) { + void type; + const plan = buildColumnPlan({ fields, windows }); + const safeRows = Array.isArray(rows) ? rows : []; + + const headerRow1 = buildHeaderRow1(plan.columns, windows); + const headerRow2 = buildHeaderRow2(plan.columns, plan.headerRowCount); + + const aoaRows = [ headerRow1 ]; + if (headerRow2) { + aoaRows.push(headerRow2); + } + for (const row of safeRows) { + aoaRows.push(plan.columns.map(column => renderCell(column, row))); + } + + // asText 列收集为 0 基列索引,交由 excel.js 落地文本单元格(无 asText 时不输出) + const textColumns = plan.columns + .map((column, columnIndex) => (column.asText ? columnIndex : -1)) + .filter(columnIndex => columnIndex >= 0); + + const result = { + name: String(title || '报表'), + columns: [], + rows: aoaRows, + merges: plan.generatedMerges, + styledRows: [], + }; + + if (textColumns.length > 0) { + result.textColumns = textColumns; + } + + return result; +} + +module.exports = { + renderSheetByType, + buildColumnPlan, +}; diff --git a/app/model/report_definition.js b/app/model/report_definition.js new file mode 100644 index 0000000..32a9693 --- /dev/null +++ b/app/model/report_definition.js @@ -0,0 +1,86 @@ +'use strict'; + +/** + * 报表模板定义 Model。 + * 报表采用「配置驱动」:name/type(注册方法 key)/file_name(导出文件名模板)/fields(勾选字段), + * 唯一性由主键 id 承担,新报表只需加配置行,免发版。 + * + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} Sequelize 模型。 + */ +module.exports = app => { + const { BIGINT, STRING, TINYINT, DATE } = app.Sequelize; + + const ReportDefinition = app.model.define('report_definition', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + name: { + type: STRING(100), + allowNull: false, + comment: '报表名称', + }, + type: { + type: STRING(50), + allowNull: false, + comment: '报表类型(内置查询器注册 key,如 stockFlow)', + }, + file_name: { + type: STRING(200), + allowNull: false, + comment: '导出文件名模板(支持 {date} 占位,如 7日出入库_{date}.xlsx)', + }, + fields: { + type: app.Sequelize.JSON, + allowNull: true, + comment: '勾选的字段 key 数组(列头/合并/样式/格式化由类型硬编码字段规格决定)', + }, + is_enabled: { + type: TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '是否启用:0=停用 1=启用', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + created_at: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + tableName: 'wms_report_definition', + freezeTableName: true, + underscored: true, + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + deletedAt: 'deleted_at', + paranoid: true, + comment: '报表模板定义表', + indexes: [ + { name: 'idx_deleted_at', fields: [ 'deleted_at' ] }, + ], + }); + + return ReportDefinition; +}; diff --git a/app/model/report_delivery_log.js b/app/model/report_delivery_log.js new file mode 100644 index 0000000..29a68a4 --- /dev/null +++ b/app/model/report_delivery_log.js @@ -0,0 +1,134 @@ +'use strict'; + +/** + * 报表投递记录 Model。 + * 状态机 pending → exporting → delivered/failed/cancelled; + * 失败按退避重试(retry_count/next_retry_at),幂等键 + * uk_store_report_biz_time 保证同一货主同一报表定义同一数据日期同一时间点不重复投递; + * report_definition_id 关联报表定义,report_name 为投递时报表名称快照(审计回放)。 + * + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} Sequelize 模型。 + */ +module.exports = app => { + const { BIGINT, INTEGER, STRING, DATE, DATEONLY } = app.Sequelize; + + const ReportDeliveryLog = app.model.define('report_delivery_log', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '仓库ID(生成报表时注入的仓库维度)', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '货主ID(wms_store.id)', + }, + report_definition_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '报表定义ID(wms_report_definition.id)', + }, + report_name: { + type: STRING(100), + allowNull: true, + comment: '报表名称快照(投递时的定义 name,审计回放)', + }, + biz_date: { + type: DATEONLY, + allowNull: false, + comment: '数据日期(T-1 自然日)', + }, + time_point: { + type: STRING(5), + allowNull: false, + comment: '命中的投递时间点(HH:mm)', + }, + status: { + type: STRING(20), + allowNull: false, + defaultValue: 'pending', + comment: '状态:pending/exporting/delivered/failed/cancelled', + }, + channel: { + type: STRING(20), + allowNull: false, + defaultValue: 'inbox', + comment: '投递渠道快照:inbox=站内信群(wecom/link 已弃用)', + }, + file_url: { + type: STRING(500), + allowNull: true, + comment: '报表文件下载链接(COS 带有效期)', + }, + retry_count: { + type: INTEGER(3), + allowNull: false, + defaultValue: 0, + comment: '重试次数', + }, + next_retry_at: { + type: DATE, + allowNull: true, + comment: '下次可投递时间(失败退避)', + }, + error_message: { + type: STRING(500), + allowNull: true, + comment: '最近一次失败原因', + }, + delivered_at: { + type: DATE, + allowNull: true, + comment: '投递成功时间', + }, + notify_targets: { + type: app.Sequelize.JSON, + allowNull: true, + comment: '投递目标快照:{group_ids:[],member_ids:[]}(本次实际发送的群/成员,审计回放)', + }, + created_at: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + tableName: 'wms_report_delivery_log', + freezeTableName: true, + underscored: true, + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + deletedAt: 'deleted_at', + paranoid: true, + comment: '报表投递记录表', + indexes: [ + { name: 'uk_store_report_biz_time', unique: true, fields: [ 'store_id', 'report_definition_id', 'biz_date', 'time_point', 'deleted_at' ] }, + { name: 'idx_status_id', fields: [ 'status', 'id' ] }, + { name: 'idx_status_updated_at', fields: [ 'status', 'updated_at' ] }, + { name: 'idx_deleted_at', fields: [ 'deleted_at' ] }, + ], + }); + + return ReportDeliveryLog; +}; diff --git a/app/model/report_delivery_plan.js b/app/model/report_delivery_plan.js new file mode 100644 index 0000000..83b3cf0 --- /dev/null +++ b/app/model/report_delivery_plan.js @@ -0,0 +1,115 @@ +'use strict'; + +/** + * 货主报表投递计划 Model。 + * 每个货主(store_id)对每个报表定义(report_definition_id)可配置每日多个投递时间点 + * (schedule_times JSON 数组),由分钟级扫描调度按 HH:mm 命中后生成并投递报表。 + * + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} Sequelize 模型。 + */ +module.exports = app => { + const { BIGINT, INTEGER, STRING, TINYINT, DATE } = app.Sequelize; + + const ReportDeliveryPlan = app.model.define('report_delivery_plan', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '货主ID(wms_store.id)', + }, + report_definition_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '报表定义ID(wms_report_definition.id)', + }, + name: { + type: STRING(100), + allowNull: true, + comment: '计划名称(前端展示用,缺省时可用报表名称兜底)', + }, + schedule_times: { + type: app.Sequelize.JSON, + allowNull: false, + comment: '每日投递时间点数组,如 ["08:30","17:00"](HH:mm)', + }, + channel: { + type: STRING(20), + allowNull: false, + defaultValue: 'inbox', + comment: '投递渠道:inbox=站内信群(wecom/link 已弃用)', + }, + enabled: { + type: TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '是否启用:0=停用 1=启用', + }, + late_grace_minutes: { + type: INTEGER(11), + allowNull: false, + defaultValue: 60, + comment: '补投宽限分钟:重启/漏跑后在该窗口内补投,超窗作废', + }, + notify_template: { + type: STRING(500), + allowNull: true, + comment: '文本通知模板,支持 {time}/{url}/{report_name}/{biz_date} 标签', + }, + notify_group_ids: { + type: app.Sequelize.JSON, + allowNull: true, + comment: '通知群ID数组(wms_inbox_group.id,多选;空=不指定群)', + }, + notify_member_ids: { + type: app.Sequelize.JSON, + allowNull: true, + comment: '通知成员ID数组(外部IM用户ID,多选;目标侧支持数组)', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + created_at: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + tableName: 'wms_report_delivery_plan', + freezeTableName: true, + underscored: true, + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + deletedAt: 'deleted_at', + paranoid: true, + comment: '货主报表投递计划表', + indexes: [ + { name: 'uk_store_report_definition', unique: true, fields: [ 'store_id', 'report_definition_id', 'deleted_at' ] }, + { name: 'idx_enabled_deleted', fields: [ 'enabled', 'deleted_at' ] }, + { name: 'idx_deleted_at', fields: [ 'deleted_at' ] }, + ], + }); + + return ReportDeliveryPlan; +}; diff --git a/app/schedule/report_delivery_dispatch.js b/app/schedule/report_delivery_dispatch.js new file mode 100644 index 0000000..8f8ab29 --- /dev/null +++ b/app/schedule/report_delivery_dispatch.js @@ -0,0 +1,42 @@ +'use strict'; + +/** + * 货主报表定时投递调度。 + * 每分钟在单 worker 中扫描一次 wms_report_delivery_plan, + * 命中投递时间点(含宽限)后幂等生成并投递报表(进程内布尔防重入)。 + */ +module.exports = { + schedule: { + interval: '1m', + type: 'worker', + immediate: false, + disable: false, + }, + + /** + * 执行报表投递调度。 + * @param {Object} ctx Egg 上下文。 + * @return {Promise} 无返回值。 + */ + async task(ctx) { + if (ctx.app._reportDeliveryDispatchRunning) { + return; + } + + ctx.app._reportDeliveryDispatchRunning = true; + + try { + const summary = await ctx.service.systems.reportDelivery.dispatch(); + + ctx.logger.info( + `[report-delivery-dispatch] 本轮投递完成:扫描 ${summary && summary.scanned || 0} 个计划,` + + `投递 ${summary && summary.delivered || 0},失败 ${summary && summary.failed || 0},` + + `跳过 ${summary && summary.skipped || 0}` + ); + } catch (error) { + ctx.logger.error(`[report-delivery-dispatch] 投递调度执行失败: ${error.message}`); + } finally { + ctx.app._reportDeliveryDispatchRunning = false; + } + }, +}; diff --git a/app/service/systemMethods/report.js b/app/service/systemMethods/report.js new file mode 100644 index 0000000..8c219af --- /dev/null +++ b/app/service/systemMethods/report.js @@ -0,0 +1,294 @@ +'use strict'; + +const MainService = require('../main'); +const ReportDeliveryPlanMethodService = require('./report/deliveryPlan'); +const ReportDeliveryLogMethodService = require('./report/deliveryLog'); +const ReportDefinitionMethodService = require('./report/definition'); + +const REPORT_GENERATE_TASK_CACHE_KEY_PREFIX = 'report_generate_task_'; +const REPORT_GENERATE_TASK_CACHE_TTL_SECONDS = 1800; + +/** + * 系统方法层:report(配置驱动通用报表接口包装层)。 + * 仅做出口包装与导出任务编排,业务逻辑下沉 systems/report。 + */ +class ReportMethodService extends MainService { + /** + * 初始化 report 方法层:配置免鉴权清单,并挂载子目录服务实例。 + * report.js 与 report/ 子目录同名并存时,egg 会把子目录服务作为静态属性挂在类构造器上, + * ctx 层实例化后静态属性不可见,需按 storeWarehouse 同款模式在实例上显式挂载, + * 保证 /system 网关可按 report.deliveryPlan.* / report.deliveryLog.* 路径解析。 + * @param {Egg.Context} ctx Egg 上下文对象。 + */ + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'generate,generateTaskProgress,meta'; + const _noNeedLog = 'generate,generateTaskProgress'; + const _noNeedAuth = 'generate,generateTaskProgress,meta'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + // 显式挂载子目录服务实例(与 storeWarehouse.js 挂载 store/warehouse 的模式一致) + this.deliveryPlan = new ReportDeliveryPlanMethodService(ctx); + this.deliveryLog = new ReportDeliveryLogMethodService(ctx); + this.definition = new ReportDefinitionMethodService(ctx); + } + + /** + * 提交报表导出异步任务(手动导出)。 + * warehouse_id 由服务端从登录上下文自动注入,前端无需传递。 + * @param {Object} data 请求体 + * @param {number} data.report_id 报表定义ID(必填,兼容 reportId) + * @param {number} [data.reportId] 报表定义ID(驼峰写法,优先级高于 report_id) + * @param {number} [data.store_id] 货主ID(可选,货主维度报表时传入) + * @param {Object} [data.params] 查询器业务参数(如 bizDate) + * @return {Promise} 统一 success 包装,data 为导出任务信息 + */ + async generate(data = {}) { + const { service } = this; + const { + report_id: reportIdSnake, + reportId: reportIdCamel, + store_id: storeIdSnake, + storeId: storeIdCamel, + params = {}, + } = data; + + const reportId = Number(reportIdCamel ?? reportIdSnake ?? 0) || 0; + if (!Number.isInteger(reportId) || reportId <= 0) { + return this.fail('报表ID report_id 必须为正整数'); + } + + // 服务端注入仓库维度(禁止前端传 warehouse_id) + const warehouseId = Number(this.ctx.user && this.ctx.user.store_id) || 0; + const storeId = Number(storeIdCamel ?? storeIdSnake ?? 0) || 0; + + const taskId = this.generateExportTaskId(); + const taskPayload = { + task_id: taskId, + status: 'submitted', + progress: 0, + message: '导出任务已提交', + result: null, + error: '', + }; + + await this.setExportTaskProgress(taskId, taskPayload); + + setImmediate(async () => { + try { + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'running', + progress: 10, + message: '导出任务执行中', + result: null, + error: '', + }); + + const result = await service.systems.report.generate({ + reportId, + storeId: storeId > 0 ? storeId : null, + warehouseId, + params, + }); + + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'success', + progress: 100, + message: '导出任务完成', + result, + error: '', + }); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'failed', + progress: 100, + message: '导出任务失败', + result: null, + error: errorMessage, + }); + } + }); + + return this.success('ok', { + ...taskPayload, + update_time: Date.now(), + }); + } + + /** + * 查询报表前端可读的列元数据(全量注册字段 + 勾选标记 + 窗口参数,不执行真实数据查询)。 + * @param {Object} data 请求体 + * @param {number} data.report_id 报表定义ID(必填,兼容 reportId) + * @param {number} [data.reportId] 报表定义ID(驼峰写法,优先级高于 report_id) + * @return {Promise} 统一 success 包装,data 为报表元数据 + */ + async meta(data = {}) { + const { service } = this; + const { + report_id: reportIdSnake, + reportId: reportIdCamel, + } = data; + + const reportId = Number(reportIdCamel ?? reportIdSnake ?? 0) || 0; + if (!Number.isInteger(reportId) || reportId <= 0) { + return this.fail('报表ID report_id 必须为正整数'); + } + + const reportMeta = await service.systems.report.getMeta({ reportId }); + const { id, ...rest } = reportMeta; + + return this.success('ok', { + report_id: id, + ...rest, + }); + } + + /** + * 查询报表导出任务进度。 + * @param {Object} data 请求体 + * @param {string} [data.task_id] 任务ID(下划线写法) + * @param {string} [data.taskId] 任务ID(驼峰写法) + * @return {Promise} 统一 success 包装 + */ + async generateTaskProgress(data = {}) { + const taskId = this.normalizeExportTaskId(data); + if (!taskId) { + return this.success('ok', { + task_id: '', + status: 'not_found', + progress: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const cachedTask = await this.getExportTaskProgress(taskId); + if (!cachedTask) { + return this.success('ok', { + task_id: taskId, + status: 'not_found', + progress: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {}; + const downloadUrl = String( + safeResult.url + || safeResult.cndUrl + || safeResult.cosUrl + || safeResult.fileKey + || '' + ); + + return this.success('ok', { + task_id: taskId, + ...cachedTask, + download_url: downloadUrl, + }); + } + + // ==================== 导出任务辅助方法(局部实现,不新增公共代码) ==================== + + /** + * 生成报表导出任务ID。 + * @return {string} 导出任务ID + */ + generateExportTaskId() { + const warehouseId = this.ctx?.user?.store_id || 'unknown'; + const timestamp = Date.now(); + const randomToken = Math.random().toString(36).slice(2, 10); + return `report_generate_${warehouseId}_${timestamp}_${randomToken}`; + } + + /** + * 归一化导出任务ID。 + * @param {Object} data 请求体 + * @return {string} 归一化后的任务ID + */ + normalizeExportTaskId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.task_id || normalizedData.taskId || '').trim(); + } + + /** + * 获取导出任务缓存键。 + * @param {string} taskId 任务ID + * @return {string} 缓存键 + */ + getExportTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + return `${REPORT_GENERATE_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 写入导出任务进度缓存。 + * @param {string} taskId 任务ID + * @param {Object} payload 任务状态载荷 + * @return {Promise} 无返回值 + */ + async setExportTaskProgress(taskId = '', payload = {}) { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.setCacheAsync !== 'function') { + return; + } + + const safePayload = this.isPlainObject(payload) ? payload : {}; + const progressPayload = { + task_id: String(taskId || '').trim(), + status: String(safePayload.status || 'submitted').trim() || 'submitted', + progress: Number.isFinite(Number(safePayload.progress)) ? Math.min(100, Math.max(0, Math.round(Number(safePayload.progress)))) : 0, + message: String(safePayload.message || ''), + result: safePayload.result ?? null, + error: String(safePayload.error || ''), + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync(cacheKey, progressPayload, REPORT_GENERATE_TASK_CACHE_TTL_SECONDS); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + this.ctx.logger.warn(`[report.generate] 写入导出任务缓存失败: ${errorMessage}`); + } + } + + /** + * 读取导出任务进度缓存。 + * @param {string} taskId 任务ID + * @return {Promise} 任务缓存 + */ + async getExportTaskProgress(taskId = '') { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.getCacheAsync !== 'function') { + return null; + } + + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (!this.isPlainObject(cached)) { + return null; + } + return cached; + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + this.ctx.logger.warn(`[report.generateTaskProgress] 读取导出任务缓存失败: ${errorMessage}`); + return null; + } + } +} + +module.exports = ReportMethodService; diff --git a/app/service/systemMethods/report/definition.js b/app/service/systemMethods/report/definition.js new file mode 100644 index 0000000..94ce9af --- /dev/null +++ b/app/service/systemMethods/report/definition.js @@ -0,0 +1,137 @@ +'use strict'; + +const MainService = require('../../main'); + +/** + * 系统方法层:report.definition(报表定义管理接口包装层)。 + * 仅做出口包装与参数解构,业务逻辑下沉 systems/report。 + */ +class ReportDefinitionMethodService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + // typeList 为只读公共元数据:免权限/免鉴权/免日志(与 report.meta 惯例一致),仍要求登录; + // save/list/delete 属定义管理类操作:不声明免权限,仅通配符角色(超级管理员/仓库管理员)可用, + // 后续由 wms_permission 同步流程按需授权,不扩大任何角色授权范围 + const _noNeedRight = 'typeList'; + const _noNeedLog = 'typeList'; + const _noNeedAuth = 'typeList'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 查询报表类型注册清单(内置查询器 + 标题/描述/窗口参数 + 全量字段清单)。 + * 免权限只读(仅登录),供前端报表配置页渲染类型下拉与字段勾选。 + * @param {Object} data 请求体(无必填参数,兼容空对象) + * @return {Promise} 统一 success 包装,data 为 { list: Array } 注册类型清单 + */ + async typeList(data = {}) { + void data; + const { service } = this; + const types = await service.systems.report.listRegisteredTypes(); + return this.success('ok', { + list: types, + }); + } + + /** + * 新增/更新报表定义(按 id upsert:未传 id 视为新增,未传字段不覆盖)。 + * @param {Object} data 请求体 + * @param {number} [data.id] 报表定义ID(正整数;不传视为新增) + * @param {string} data.name 报表名称(必填,≤100) + * @param {string} data.type 报表类型(注册方法 key,如 stockFlow;新增必填) + * @param {string} data.file_name 导出文件名模板(支持 {date};新增必填,≤200,兼容 fileName) + * @param {Array} data.fields 勾选字段 key 数组(新增必填,须为该类型注册字段子集) + * @param {number} [data.is_enabled] 是否启用(0/1) + * @param {string} [data.remark] 备注(≤500) + * @return {Promise} 统一 success 包装,data 为保存后的报表定义视图 + */ + async save(data = {}) { + const { service } = this; + const { + id, + name, + type, + file_name: fileNameSnake, + fileName: fileNameCamel, + fields, + is_enabled: isEnabled, + remark, + } = data; + + // 仅附加入参中存在的字段(undefined 不进入参数对象),保持「未传不覆盖」语义 + const saveArgs = { id, name, type }; + const normalizedFileName = fileNameCamel !== undefined ? fileNameCamel : fileNameSnake; + if (normalizedFileName !== undefined) { + saveArgs.fileName = normalizedFileName; + } + if (fields !== undefined) { + saveArgs.fields = fields; + } + if (isEnabled !== undefined) { + saveArgs.isEnabled = isEnabled; + } + if (remark !== undefined) { + saveArgs.remark = remark; + } + + try { + const result = await service.systems.report.saveDefinition(saveArgs); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '报表定义保存失败'); + } + } + + /** + * 分页查询报表定义列表。 + * @param {Object} data 请求体 + * @param {Object} [data.where] 查询条件(name 模糊关键字、type/is_enabled 精确) + * @param {Object} [data.pagination] 分页 { page, pageSize } + * @param {Object} [data.sort] 排序 { sortField, sortOrder }(白名单:id/name/type/is_enabled/created_at/updated_at) + * @return {Promise} 统一 success 包装,data 为 { list, total, page, pageSize } + */ + async list(data = {}) { + const { service } = this; + const { whereValue = {} } = this.prepareWhereContext(data); + const { + name: nameKeyword, + type, + is_enabled: isEnabled, + } = whereValue; + const { pagination = {}, sort = {} } = data; + + try { + const result = await service.systems.report.listDefinitions({ + nameKeyword, + type, + isEnabled, + pagination, + sort, + }); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '报表定义列表查询失败'); + } + } + + /** + * 软删除报表定义(存在启用中的投递计划引用时拦截)。 + * @param {Object} data 请求体 + * @param {number} data.id 报表定义ID(必填,正整数) + * @return {Promise} 统一 success 包装,data 为 { id, deleted } + */ + async delete(data = {}) { + const { service } = this; + const { id } = data; + + try { + const result = await service.systems.report.deleteDefinition({ id }); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '报表定义删除失败'); + } + } +} + +module.exports = ReportDefinitionMethodService; diff --git a/app/service/systemMethods/report/deliveryLog.js b/app/service/systemMethods/report/deliveryLog.js new file mode 100644 index 0000000..e9f0179 --- /dev/null +++ b/app/service/systemMethods/report/deliveryLog.js @@ -0,0 +1,50 @@ +'use strict'; + +const MainService = require('../../main'); + +/** + * 系统方法层:report.deliveryLog(货主报表投递记录审计查询接口包装层)。 + * 仅做出口包装与参数解构,业务逻辑下沉 systems/reportDelivery。 + */ +class ReportDeliveryLogMethodService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + // 审计查询属于管理类操作:不声明免权限,仅通配符角色(超级管理员/仓库管理员)可用, + // 后续由 wms_permission 同步流程按需授权,不扩大任何角色授权范围 + const _noNeedRight = ''; + const _noNeedLog = ''; + const _noNeedAuth = ''; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 分页查询投递记录(审计)。 + * @param {Object} data 请求体 + * @param {Object} [data.where] 查询条件(store_id/report_id/status) + * @param {Object} [data.pagination] 分页 { page, pageSize } + * @param {Object} [data.sort] 排序 { sortField, sortOrder } + * @return {Promise} 统一 success 包装 + */ + async list(data = {}) { + const { service } = this; + const { whereValue = {} } = this.prepareWhereContext(data); + const { + store_id: storeId, + report_id: reportId, + status, + } = whereValue; + const { pagination = {}, sort = {} } = data; + + const result = await service.systems.reportDelivery.listLogs({ + storeId, + reportId, + status, + pagination, + sort, + }); + return this.success('ok', result); + } +} + +module.exports = ReportDeliveryLogMethodService; diff --git a/app/service/systemMethods/report/deliveryPlan.js b/app/service/systemMethods/report/deliveryPlan.js new file mode 100644 index 0000000..e75a63b --- /dev/null +++ b/app/service/systemMethods/report/deliveryPlan.js @@ -0,0 +1,130 @@ +'use strict'; + +const MainService = require('../../main'); + +/** + * 系统方法层:report.deliveryPlan(货主报表投递计划接口包装层)。 + * 仅做出口包装与参数解构,业务逻辑下沉 systems/reportDelivery。 + */ +class ReportDeliveryPlanMethodService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + // 计划管理属于管理类操作:不声明免权限,仅通配符角色(超级管理员/仓库管理员)可用, + // 后续由 wms_permission 同步流程按需授权,不扩大任何角色授权范围 + const _noNeedRight = ''; + const _noNeedLog = ''; + const _noNeedAuth = ''; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 新增/更新投递计划(货主+报表定义ID唯一,存在则更新)。 + * @param {Object} data 请求体 + * @param {number} data.store_id 货主ID(必填) + * @param {number} data.report_id 报表定义ID(必填,兼容 reportId) + * @param {Array} data.schedule_times 每日投递时间点数组(HH:mm,自动去重排序) + * @param {string} [data.channel='inbox'] 投递渠道(仅支持 inbox) + * @param {number} [data.late_grace_minutes=60] 补投宽限分钟(0-1440) + * @param {string|null} [data.name] 计划名称(可空;未传不覆盖,null/空串清空,非空 trim ≤100) + * @param {string} [data.remark] 备注 + * @param {string} [data.notify_template] 文本通知模板(≤500,白名单标签 {time}/{url}/{report_name}/{biz_date}) + * @param {Array} [data.notify_group_ids] 通知群ID数组(wms_inbox_group.id,≤20) + * @param {Array} [data.notify_member_ids] 通知成员ID数组(外部IM用户ID,≤100) + * @return {Promise} 统一 success 包装 + */ + async save(data = {}) { + const { service } = this; + const { + store_id: storeId, + report_id: reportIdSnake, + reportId: reportIdCamel, + schedule_times: scheduleTimes, + channel, + late_grace_minutes: lateGraceMinutes, + name, + remark, + notify_template: notifyTemplate, + notify_group_ids: notifyGroupIds, + notify_member_ids: notifyMemberIds, + } = data; + + // 基础参数解构透传;通知类参数仅在入参存在时附加, + // 保持旧调用形状与既有回归断言一致(undefined 不进入参数对象) + const saveArgs = { + storeId, + reportId: reportIdCamel !== undefined ? reportIdCamel : reportIdSnake, + scheduleTimes, + channel, + lateGraceMinutes, + remark, + }; + if (name !== undefined) { + saveArgs.name = name; + } + if (notifyTemplate !== undefined) { + saveArgs.notifyTemplate = notifyTemplate; + } + if (notifyGroupIds !== undefined) { + saveArgs.notifyGroupIds = notifyGroupIds; + } + if (notifyMemberIds !== undefined) { + saveArgs.notifyMemberIds = notifyMemberIds; + } + + const result = await service.systems.reportDelivery.savePlan(saveArgs); + return this.success('ok', result); + } + + /** + * 快速复制投递计划到其他货主(目标已存在相同报表定义计划时跳过,不覆盖不报错)。 + * @param {Object} data 请求体 + * @param {number} data.id 源计划ID(必填,正整数) + * @param {Array} data.store_ids 目标货主ID数组(必填,兼容 storeIds 驼峰) + * @return {Promise} 统一 success 包装,data={ created, skipped } + */ + async copy(data = {}) { + const { service } = this; + const { + id, + store_ids: storeIdsSnake, + storeIds: storeIdsCamel, + } = data; + + // 兼容 storeIds 驼峰入参,优先取驼峰形式,保持与 save 的 reportId 兼容口径一致 + const storeIds = storeIdsCamel !== undefined ? storeIdsCamel : storeIdsSnake; + + const result = await service.systems.reportDelivery.copyPlan({ id, storeIds }); + return this.success('ok', result); + } + + /** + * 分页查询投递计划列表。 + * @param {Object} data 请求体 + * @param {Object} [data.where] 查询条件(store_id/report_id/enabled) + * @param {Object} [data.pagination] 分页 { page, pageSize } + * @param {Object} [data.sort] 排序 { sortField, sortOrder } + * @return {Promise} 统一 success 包装 + */ + async list(data = {}) { + const { service } = this; + const { whereValue = {} } = this.prepareWhereContext(data); + const { + store_id: storeId, + report_id: reportId, + enabled, + } = whereValue; + const { pagination = {}, sort = {} } = data; + + const result = await service.systems.reportDelivery.listPlans({ + storeId, + reportId, + enabled, + pagination, + sort, + }); + return this.success('ok', result); + } +} + +module.exports = ReportDeliveryPlanMethodService; diff --git a/app/service/systems/excel.js b/app/service/systems/excel.js index ac26405..64ab415 100644 --- a/app/service/systems/excel.js +++ b/app/service/systems/excel.js @@ -135,6 +135,7 @@ class ExcelService extends Service { buildWorksheet(sheetConfig = {}) { const { merges = [], + textColumns = [], } = sheetConfig; const { aoaData, @@ -151,6 +152,8 @@ class ExcelService extends Service { worksheet['!merges'] = merges; } + this.applyTextColumnsToSheetJs(worksheet, textColumns); + return worksheet; } @@ -198,6 +201,7 @@ class ExcelService extends Service { merges = [], embeddedImages = [], styledRows = [], + textColumns = [], } = sheetConfig; const { normalizedColumns, @@ -258,6 +262,10 @@ class ExcelService extends Service { this.applyStyledRows(worksheet, styledRows); } + if (Array.isArray(textColumns) && textColumns.length > 0) { + this.applyTextColumnsToExcelJs(worksheet, textColumns); + } + if (Array.isArray(embeddedImages) && embeddedImages.length > 0) { await this.addEmbeddedImages(workbook, worksheet, embeddedImages); } @@ -437,6 +445,74 @@ class ExcelService extends Service { }); } + /** + * SheetJS 路径:将 textColumns 指定列落地为文本单元格。 + * 单元格类型强制为文本(t:'s')、值转字符串,并附加文本数字格式(z:'@'), + * 防止长数字串被 Excel 按数值展示成科学计数法。 + * @param {Object} worksheet SheetJS 工作表对象 + * @param {Array} [textColumns=[]] 0 基文本列索引列表 + * @return {void} 无返回值 + */ + applyTextColumnsToSheetJs(worksheet, textColumns = []) { + if (!worksheet || !Array.isArray(textColumns) || textColumns.length === 0) { + return; + } + + const columnSet = new Set( + textColumns.map(index => Math.max(0, Math.floor(Number(index) || 0))) + ); + const range = XLSX.utils.decode_range(worksheet['!ref'] || 'A1'); + + for (let row = range.s.r; row <= range.e.r; row += 1) { + for (const column of columnSet) { + if (column > range.e.c) { + continue; + } + const address = XLSX.utils.encode_cell({ r: row, c: column }); + const cell = worksheet[address]; + if (!cell) { + continue; + } + if (cell.v !== null && cell.v !== undefined) { + cell.t = 's'; + cell.v = String(cell.v); + } + cell.z = '@'; + } + } + } + + /** + * ExcelJS 路径:将 textColumns 指定列落地为文本单元格。 + * 单元格值转为字符串(原始对象类型除外),并设置文本数字格式 numFmt='@', + * 防止长数字串被 Excel 按数值展示成科学计数法。 + * @param {Object} worksheet ExcelJS 工作表对象 + * @param {Array} [textColumns=[]] 0 基文本列索引列表 + * @return {void} 无返回值 + */ + applyTextColumnsToExcelJs(worksheet, textColumns = []) { + if (!worksheet || !Array.isArray(textColumns) || textColumns.length === 0) { + return; + } + + const columnSet = new Set( + textColumns.map(index => Math.max(1, Math.floor(Number(index) || 0) + 1)) + ); + + for (let row = 1; row <= worksheet.rowCount; row += 1) { + worksheet.getRow(row).eachCell({ includeEmpty: false }, (cell, columnNumber) => { + if (!columnSet.has(columnNumber)) { + return; + } + const value = cell.value; + if (value !== null && value !== undefined && typeof value !== 'object') { + cell.value = String(value); + } + cell.numFmt = '@'; + }); + } + } + async addEmbeddedImages(workbook, worksheet, embeddedImages = []) { for (const imageConfig of embeddedImages) { if (!imageConfig) { diff --git a/app/service/systems/notice/index.js b/app/service/systems/notice/index.js index 192958b..ed67f7d 100644 --- a/app/service/systems/notice/index.js +++ b/app/service/systems/notice/index.js @@ -263,14 +263,19 @@ class NoticeService extends Service { const codes = notificationWebhookModel.getAvailableEventCodes() .map(item => String(item || '').trim().toLowerCase()) .filter(Boolean); - return codes.length > 0 ? codes : [ ...DEFAULT_REGISTERED_EVENT_CODES ]; + // 默认注册事件码始终生效(与模型配置合并,便于服务内按现有模式追加新事件码) + return codes.length > 0 + ? [ ...new Set([ ...codes, ...DEFAULT_REGISTERED_EVENT_CODES ]) ] + : [ ...DEFAULT_REGISTERED_EVENT_CODES ]; } if (Array.isArray(notificationWebhookModel.AVAILABLE_EVENTS)) { const codes = notificationWebhookModel.AVAILABLE_EVENTS .map(item => String(item && item.code || '').trim().toLowerCase()) .filter(Boolean); - return codes.length > 0 ? codes : [ ...DEFAULT_REGISTERED_EVENT_CODES ]; + return codes.length > 0 + ? [ ...new Set([ ...codes, ...DEFAULT_REGISTERED_EVENT_CODES ]) ] + : [ ...DEFAULT_REGISTERED_EVENT_CODES ]; } return [ ...DEFAULT_REGISTERED_EVENT_CODES ]; diff --git a/app/service/systems/report.js b/app/service/systems/report.js new file mode 100644 index 0000000..318c041 --- /dev/null +++ b/app/service/systems/report.js @@ -0,0 +1,610 @@ +'use strict'; + +const { Service } = require('egg'); +const { renderSheetByType } = require('../../lib/report/render'); +const { scheduleDateOf } = require('../../lib/report/day_window'); +const QUERIES = require('./report/queries'); + +/** + * 配置驱动通用报表引擎(systems 层)。 + * + * 链路:wms_report_definition(配置:type/file_name/fields) → 内置查询器(QUERIES 注册表) + * → render.js(按类型硬编码字段规格渲染) → excel.generateAndUpload / generateBuffer(产物)。 + * 本服务仅做编排与出口包装,具体口径由查询器实现并注释假设; + * 定义唯一性由 id(主键)承担,plan/log 均按 report_definition_id 关联。 + */ +class ReportService extends Service { + /** + * 按 ID 读取启用的报表定义(is_enabled=1,软删自动排除)。 + * @param {number|string} id 报表定义ID(正整数) + * @return {Promise} 报表定义视图(fields 已解析为字符串数组) + * @throws {Error} ID 非法、模型不可用或定义不存在/停用时抛出 + */ + async getDefinition(id) { + const { ctx } = this; + const model = ctx.model && ctx.model.ReportDefinition; + if (!model || typeof model.findOne !== 'function') { + throw new Error('报表定义模型 ReportDefinition 不可用'); + } + const normalizedId = Number(id) || 0; + if (!Number.isInteger(normalizedId) || normalizedId <= 0) { + throw new Error('报表ID report_id 必须为正整数'); + } + const row = await model.findOne({ + where: { + id: normalizedId, + is_enabled: 1, + }, + raw: true, + }); + if (!row) { + throw new Error(`报表定义不存在或已停用: id=${normalizedId}`); + } + return this.definitionToView(row); + } + + /** + * 解析 fields 字段:数组原样返回、JSON 字符串解析,其余按空数组兜底(元素统一为字符串)。 + * @param {*} value 字段原始值 + * @return {Array} 字段 key 数组 + */ + parseFieldsField(value) { + let list = value; + if (typeof value === 'string' && value.trim()) { + try { + list = JSON.parse(value); + } catch (error) { + this.ctx.logger.warn(`[report] 报表定义 fields JSON 解析失败: ${error.message}`); + return []; + } + } + if (!Array.isArray(list)) { + return []; + } + return list + .map(item => String(item || '').trim()) + .filter(Boolean); + } + + /** + * 报表定义记录转视图对象(fields 统一解析为字符串数组,时间字段透传)。 + * @param {Object} row 报表定义记录(实例或 raw) + * @return {Object|null} 视图对象(记录为空时返回 null) + */ + definitionToView(row) { + if (!row) { + return null; + } + return { + id: Number(row.id) || 0, + name: String(row.name || ''), + type: String(row.type || ''), + file_name: String(row.file_name || ''), + fields: this.parseFieldsField(row.fields), + is_enabled: Number(row.is_enabled ?? 1), + remark: String(row.remark || ''), + created_at: row.created_at || null, + updated_at: row.updated_at || null, + }; + } + + /** + * 读取注册表描述条目(未知类型抛可读错误)。 + * @param {string} type 报表类型(注册方法 key) + * @return {{key: string, title: string, description: string, window: Object, fields: Array}} 描述条目 + * @throws {Error} 类型未注册时抛出 + */ + resolveTypeEntry(type) { + const normalizedType = String(type || '').trim(); + const entries = typeof QUERIES.describe === 'function' ? QUERIES.describe() : []; + const entry = entries.find(item => item && item.key === normalizedType); + if (!entry) { + throw new Error(`未知的报表类型: ${normalizedType}`); + } + return entry; + } + + /** + * 读取查询器函数(未知类型抛错)。 + * @param {string} type 报表类型(注册方法 key) + * @return {Function} 查询器函数 + */ + resolveQuerier(type) { + const normalizedType = String(type || '').trim(); + const querier = QUERIES[normalizedType]; + if (typeof querier !== 'function') { + throw new Error(`未知的报表类型: ${normalizedType}`); + } + return querier; + } + + /** + * 输出注册表全量清单(供 method 层 report.definition.typeList 复用)。 + * @return {Array<{key: string, title: string, description: string, window: Object, fields: Array}>} 注册清单 + */ + listRegisteredTypes() { + return typeof QUERIES.describe === 'function' ? QUERIES.describe() : []; + } + + /** + * 校验勾选字段均为该类型注册字段的子集(顶层字段 key),非法 key 列出可读错误。 + * @param {string} type 报表类型(注册方法 key) + * @param {Array} fields 勾选字段 key 数组 + * @return {Array} 去重后的合法字段 key 数组(保持传入顺序) + * @throws {Error} 含非法字段 key 时抛出 + */ + validateTypeFields(type, fields) { + const entry = this.resolveTypeEntry(type); + const registeredKeys = new Set((Array.isArray(entry.fields) ? entry.fields : []).map(field => field && field.key)); + const safeFields = Array.isArray(fields) ? fields : []; + const seen = new Set(); + const normalized = []; + const illegal = []; + for (const item of safeFields) { + const key = String(item || '').trim(); + if (!key) { + continue; + } + if (!registeredKeys.has(key)) { + if (!illegal.includes(key)) { + illegal.push(key); + } + continue; + } + if (!seen.has(key)) { + seen.add(key); + normalized.push(key); + } + } + if (illegal.length > 0) { + throw new Error( + `fields 含非法字段: ${illegal.join(', ')}` + + `(报表类型 ${type} 可用字段: ${[ ...registeredKeys ].join(', ') || '-'})` + ); + } + return normalized; + } + + /** + * 按字段 key 顺序解析注册字段规格(用于渲染列顺序)。 + * @param {Object} entry 注册表描述条目 + * @param {Array} fields 勾选字段 key 数组 + * @return {Array} 按勾选顺序排列的字段规格清单 + */ + resolveOrderedFields(entry, fields) { + const entryFields = Array.isArray(entry.fields) ? entry.fields : []; + const fieldMap = new Map(entryFields.map(field => [ field && field.key, field ])); + const safeFields = Array.isArray(fields) ? fields : []; + return safeFields + .map(key => fieldMap.get(key)) + .filter(Boolean); + } + + /** + * 构建导出文件名(支持 file_name 模板的 {date} 占位)。 + * @param {Object} definition 报表定义视图 + * @param {string} [bizDate=''] 数据日期(YYYY-MM-DD,缺省用今天) + * @return {string} 文件名 + */ + buildFilename(definition, bizDate = '') { + const dateText = String(bizDate || '').trim() || scheduleDateOf(new Date()); + const template = String((definition && definition.file_name) || '').trim() + || `${String((definition && definition.name) || 'report')}_${dateText}.xlsx`; + const filename = template.includes('{date}') + ? template.replace(/\{date\}/g, dateText) + : template; + return filename.endsWith('.xlsx') || filename.endsWith('.xls') ? filename : `${filename}.xlsx`; + } + + /** + * 查询数据并翻译为 excel.js 的 sheets 参数(generate/generateBuffer 共用)。 + * @param {Object} options 入参 + * @param {number|string} options.reportId 报表定义ID + * @param {number|null} [options.storeId] 货主ID + * @param {number|null} [options.warehouseId] 仓库ID + * @param {Object} [options.params] 查询器业务参数(如 bizDate) + * @return {Promise<{sheets: Array, filename: string, queryData: Object}>} 翻译结果 + */ + async buildWorkbookSheets({ reportId, storeId = null, warehouseId = null, params = {} }) { + const definition = await this.getDefinition(reportId); + const entry = this.resolveTypeEntry(definition.type); + const querier = this.resolveQuerier(definition.type); + + const queryData = await querier({ + ctx: this.ctx, + storeId, + warehouseId, + params: params || {}, + }); + + const orderedFields = this.resolveOrderedFields(entry, definition.fields); + const sheet = renderSheetByType({ + type: definition.type, + title: entry.title, + fields: orderedFields, + rows: Array.isArray(queryData.rows) ? queryData.rows : [], + windows: Array.isArray(queryData.windows) ? queryData.windows : [], + }); + + return { + sheets: [ sheet ], + filename: this.buildFilename(definition, params && params.bizDate), + queryData, + }; + } + + /** + * 生成报表 Excel 并上传,返回 fileKey/url(供手动导出与货主投递复用)。 + * @param {Object} options 入参 + * @param {number|string} options.reportId 报表定义ID + * @param {number|null} [options.storeId] 货主ID + * @param {number|null} [options.warehouseId] 仓库ID + * @param {Object} [options.params] 查询器业务参数(如 bizDate) + * @return {Promise<{fileKey: string, url: string, filename: string, size: number}>} 上传结果 + */ + async generate({ reportId, storeId = null, warehouseId = null, params = {} }) { + const { sheets, filename } = await this.buildWorkbookSheets({ + reportId, + storeId, + warehouseId, + params, + }); + + const uploadResult = await this.ctx.service.systems.excel.generateAndUpload({ + filename, + dir: `exports/report/${String(reportId).trim()}`, + category: 'document', + sheets, + }); + + const fileKey = String(uploadResult.fileKey || uploadResult.fileName || '').trim(); + const url = String( + uploadResult.url + || uploadResult.cdnUrl + || uploadResult.cosUrl + || fileKey + || '' + ).trim(); + + return { + fileKey, + url, + filename: String(uploadResult.filename || filename), + size: Number(uploadResult.size) || 0, + }; + } + + /** + * 生成报表 Excel 缓冲(内部入口,供后续复用/直推下载)。 + * @param {Object} options 入参 + * @param {number|string} options.reportId 报表定义ID + * @param {number|null} [options.storeId] 货主ID + * @param {number|null} [options.warehouseId] 仓库ID + * @param {Object} [options.params] 查询器业务参数(如 bizDate) + * @return {Promise<{buffer: Buffer, filename: string, contentType: string}>} 缓冲结果 + */ + async generateBuffer({ reportId, storeId = null, warehouseId = null, params = {} }) { + const { sheets, filename } = await this.buildWorkbookSheets({ + reportId, + storeId, + warehouseId, + params, + }); + + const buffer = await this.ctx.service.systems.excel.generateBuffer({ + bookType: 'xlsx', + sheets, + }); + + return { + buffer, + filename, + contentType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + }; + } + + /** + * 读取报表前端可读的列元数据(全量注册字段 + 勾选标记 + 窗口参数,不执行真实数据查询)。 + * @param {Object} options 入参 + * @param {number|string} options.reportId 报表定义ID + * @return {Promise} { id, name, type, file_name, window: {dayCount, cutoverHour}, fields } + */ + async getMeta({ reportId }) { + const definition = await this.getDefinition(reportId); + const entry = this.resolveTypeEntry(definition.type); + const selectedSet = new Set(definition.fields); + + return { + id: definition.id, + name: definition.name, + type: definition.type, + file_name: definition.file_name, + window: { + dayCount: Number((entry.window && entry.window.dayCount) || 7), + cutoverHour: Number((entry.window && entry.window.cutoverHour) || 7), + }, + fields: (Array.isArray(entry.fields) ? entry.fields : []).map(field => ({ + ...field, + selected: selectedSet.has(field.key), + })), + }; + } + + /** + * 新增/更新报表定义(按 id upsert;未传 id 视为新增)。 + * 更新语义:未传入的字段(undefined)不覆盖既有值;传入非法值会校验报错。 + * 校验项:name 必填、type 必须为注册表已有类型、file_name 必填(新增时)、 + * fields 必须为该类型注册字段的子集。 + * @param {Object} options 入参 + * @param {number} [options.id] 报表定义ID(正整数;不传视为新增) + * @param {string} options.name 报表名称(必填,≤100) + * @param {string} options.type 报表类型(注册方法 key,如 stockFlow;新增必填) + * @param {string} options.fileName 导出文件名模板(支持 {date};新增必填,≤200) + * @param {Array} options.fields 勾选字段 key 数组(新增必填,须为该类型注册字段子集) + * @param {number} [options.isEnabled] 是否启用(0/1) + * @param {string} [options.remark] 备注(≤500) + * @return {Promise} 保存后的报表定义视图 + * @throws {Error} 参数非法、类型未知或字段非法时抛出业务可读错误 + */ + async saveDefinition({ + id, + name = '', + type, + fileName, + fields, + isEnabled, + remark, + } = {}) { + const { ctx } = this; + const model = ctx.model && ctx.model.ReportDefinition; + if (!model || typeof model.findOne !== 'function') { + throw new Error('报表定义模型 ReportDefinition 不可用'); + } + + const normalizedId = id === undefined || id === null || id === '' + ? null + : Number(id) || 0; + if (normalizedId !== null && (!Number.isInteger(normalizedId) || normalizedId <= 0)) { + throw new Error('报表ID id 必须为正整数'); + } + + const normalizedName = String(name || '').trim(); + if (!normalizedName) { + throw new Error('报表名称 name 不能为空'); + } + if (normalizedName.length > 100) { + throw new Error('报表名称 name 不能超过 100 字符'); + } + + // 软删记录也纳入查找(按 id 主键查重,paranoid: false 支持恢复), + // 并复用既有记录 type 完成 fields 校验(避免重复查库) + const existing = normalizedId !== null + ? await this.findDefinitionById(model, normalizedId) + : null; + if (normalizedId !== null && !existing) { + throw new Error(`报表定义不存在: id=${normalizedId}`); + } + + // 未传 type(undefined)不校验也不覆盖既有值;显式传空/未知类型仍报错 + let normalizedType; + if (type !== undefined) { + normalizedType = String(type || '').trim(); + this.resolveTypeEntry(normalizedType); + } + + // 未传 fields(undefined)不校验;显式传值须为该类型注册字段子集 + let normalizedFields; + if (fields !== undefined) { + if (!Array.isArray(fields)) { + throw new Error('报表字段 fields 必须为数组'); + } + // 校验查询器取本次 type,其次取既有记录 type + const fieldsValidationType = normalizedType !== undefined + ? normalizedType + : (existing && existing.type); + if (!fieldsValidationType) { + throw new Error('报表类型 type 不能为空'); + } + normalizedFields = this.validateTypeFields(fieldsValidationType, fields); + } + + // 未传 fileName(undefined)不覆盖既有值;新增时必填 + let normalizedFileName; + if (fileName !== undefined) { + normalizedFileName = String(fileName || '').trim(); + if (!normalizedFileName) { + throw new Error('导出文件名 file_name 不能为空'); + } + if (normalizedFileName.length > 200) { + throw new Error('导出文件名 file_name 不能超过 200 字符'); + } + } + + if (isEnabled !== undefined) { + const enabledNum = Number(isEnabled); + if (enabledNum !== 0 && enabledNum !== 1) { + throw new Error('is_enabled 仅支持 0/1'); + } + } + + // 新增时必须提供 type/file_name/fields(existing 已在上方按 id 查询一次) + if (!existing) { + if (normalizedType === undefined) { + throw new Error('报表类型 type 不能为空'); + } + if (normalizedFileName === undefined) { + throw new Error('导出文件名 file_name 不能为空'); + } + if (normalizedFields === undefined) { + throw new Error('报表字段 fields 不能为空'); + } + } + + const payload = { + name: normalizedName, + }; + if (normalizedType !== undefined) { + payload.type = normalizedType; + } + if (normalizedFileName !== undefined) { + payload.file_name = normalizedFileName; + } + if (normalizedFields !== undefined) { + payload.fields = normalizedFields; + } + if (isEnabled !== undefined) { + payload.is_enabled = Number(isEnabled) ? 1 : 0; + } + if (remark !== undefined) { + payload.remark = String(remark || '').slice(0, 500); + } + + let saved; + if (existing) { + if (existing.deleted_at) { + // 命中软删记录:恢复后按入参更新 + await existing.restore(); + } + await existing.update(payload); + saved = existing; + } else { + const created = await model.create(payload); + saved = created && created.toJSON ? created.toJSON() : created; + } + + return this.definitionToView(saved); + } + + /** + * 按 ID 查找报表定义(paranoid: false,软删记录也返回,供恢复与校验复用)。 + * @param {Object} model ReportDefinition 模型 + * @param {number|null} id 报表定义ID(null 时直接返回 null) + * @return {Promise} 记录实例(含软删记录),不存在返回 null + */ + async findDefinitionById(model, id) { + if (id === null || Number(id) <= 0) { + return null; + } + return model.findOne({ + where: { id: Number(id) }, + paranoid: false, + }); + } + + /** + * 分页查询报表定义列表(name 模糊、type/is_enabled 精确,sortField 白名单)。 + * @param {Object} [options={}] 入参 + * @param {string} [options.nameKeyword=''] name 模糊关键字 + * @param {string} [options.type=''] 报表类型精确筛选(注册方法 key) + * @param {number|string} [options.isEnabled=null] 启用状态精确筛选(0/1) + * @param {Object} [options.pagination={}] 分页 { page, pageSize } + * @param {Object} [options.sort={}] 排序 { sortField, sortOrder } + * @return {Promise<{list: Array, total: number, page: number, pageSize: number}>} 列表结果 + */ + async listDefinitions({ + nameKeyword = '', + type = '', + isEnabled = null, + pagination = {}, + sort = {}, + } = {}) { + const { ctx } = this; + const model = ctx.model && ctx.model.ReportDefinition; + if (!model) { + throw new Error('报表定义模型 ReportDefinition 不可用'); + } + const { Op } = ctx.app.Sequelize; + + const escapeLike = value => String(value || '').replace(/[\\%_]/g, match => `\\${match}`); + + const where = {}; + const normalizedNameKeyword = String(nameKeyword || '').trim(); + if (normalizedNameKeyword) { + where.name = { [Op.like]: `%${escapeLike(normalizedNameKeyword)}%` }; + } + const normalizedType = String(type || '').trim(); + if (normalizedType) { + this.resolveTypeEntry(normalizedType); + where.type = normalizedType; + } + if (isEnabled !== null && isEnabled !== undefined && isEnabled !== '') { + where.is_enabled = Number(isEnabled) ? 1 : 0; + } + + const page = Math.max(1, Math.floor(Number(pagination.page) || 1)); + const pageSize = Math.min(200, Math.max(1, Math.floor(Number(pagination.pageSize) || 20))); + + const allowedSortFields = [ 'id', 'name', 'type', 'is_enabled', 'created_at', 'updated_at' ]; + const sortField = String(sort.sortField || sort.sort_field || 'id').trim(); + const sortOrder = String(sort.sortOrder || sort.sort_order || 'desc').trim().toLowerCase() === 'asc' ? 'ASC' : 'DESC'; + const order = allowedSortFields.includes(sortField) + ? [[ sortField, sortOrder ]] + : [[ 'id', 'DESC' ]]; + + const [ rows, total ] = await Promise.all([ + model.findAll({ + where, + order, + offset: (page - 1) * pageSize, + limit: pageSize, + raw: true, + }), + model.count({ where }), + ]); + + return { + list: (Array.isArray(rows) ? rows : []).map(row => this.definitionToView(row)), + total: Number(total) || 0, + page, + pageSize, + }; + } + + /** + * 软删除报表定义。 + * 删除前检查投递计划引用:仅拦截「启用中」的计划,停用计划不阻断—— + * 停用计划不再生产投递任务,历史投递日志按 report_definition_id 关联不受定义删除影响。 + * 重复删除同一 ID 按幂等成功处理,避免前端重复点击报错。 + * @param {Object} options 入参 + * @param {number|string} options.id 报表定义ID(必填,正整数) + * @return {Promise<{id: number, deleted: number}>} 删除结果(deleted 恒为 1) + * @throws {Error} ID 非法、定义不存在或存在启用中的投递计划引用时抛出业务可读错误 + */ + async deleteDefinition({ id } = {}) { + const { ctx } = this; + const model = ctx.model && ctx.model.ReportDefinition; + if (!model) { + throw new Error('报表定义模型 ReportDefinition 不可用'); + } + const normalizedId = Number(id) || 0; + if (!Number.isInteger(normalizedId) || normalizedId <= 0) { + throw new Error('报表ID id 必须为正整数'); + } + + // 引用拦截:仅统计启用中的投递计划(enabled=1) + const planModel = ctx.model && ctx.model.ReportDeliveryPlan; + if (planModel && typeof planModel.count === 'function') { + const activePlanCount = await planModel.count({ + where: { + report_definition_id: normalizedId, + enabled: 1, + }, + }); + if (activePlanCount > 0) { + throw new Error(`存在 ${activePlanCount} 个启用的投递计划引用该报表,请先停用计划`); + } + } + + const existing = await this.findDefinitionById(model, normalizedId); + if (!existing) { + throw new Error(`报表定义不存在: id=${normalizedId}`); + } + if (existing.deleted_at) { + return { id: normalizedId, deleted: 1 }; + } + await existing.destroy(); + return { id: normalizedId, deleted: 1 }; + } +} + +module.exports = ReportService; diff --git a/app/service/systems/report/queries/index.js b/app/service/systems/report/queries/index.js new file mode 100644 index 0000000..45c85a5 --- /dev/null +++ b/app/service/systems/report/queries/index.js @@ -0,0 +1,57 @@ +'use strict'; + +const sevenDayStockFlow = require('./sevenDayStockFlow'); + +/** + * 报表内置查询器注册表。 + * key 对应 wms_report_definition.type; + * 新增查询器时在此登记,签名统一为 + * async ({ ctx, storeId, warehouseId, params }) => ({ windows, rows, meta })。 + * 每个查询器需在模块上挂载静态字段清单 `fields`(如 module.exports.fields) + * 与缺省窗口参数 `defaultWindow`,供报表引擎 report.meta / report.definition.typeList 读取。 + * 注意:该对象会作为 service 模块导出,egg 加载器需要在其上挂载 + * `Symbol(EGG_LOADER_ITEM_FULLPATH)` 等内部符号,因此禁止对导出对象使用 + * Object.freeze / Object.seal / Object.preventExtensions。 + * @type {Object} + */ +const QUERIES = { + stockFlow: sevenDayStockFlow, +}; + +/** + * 注册表描述元数据:key/title/description/window/fields。 + * @type {Array<{key: string, title: string, description: string, window: Object, fields: Array}>} + */ +const DESCRIPTIONS = [ + { + key: 'stockFlow', + title: '库存变化以及补货报表', + description: '按日窗口聚合出入库流水与正品库存,输出每 SKU 每日出/入库、可用/总库存、' + + '锁定数、待出、日均出/入库、预计可售天数、建议补货量与库存预警', + window: { + ...(sevenDayStockFlow.defaultWindow || { dayCount: 7, cutoverHour: 7 }), + }, + fields: (Array.isArray(sevenDayStockFlow.fields) ? sevenDayStockFlow.fields : []).map(field => ({ ...field })), + }, +]; + +/** + * 输出注册表可读描述(含全量字段清单),供 report.definition.typeList / report.meta 复用。 + * 返回副本,避免调用方误改注册表元数据。 + * @return {Array<{key: string, title: string, description: string, window: Object, fields: Array}>} 注册描述列表 + */ +function describe() { + return DESCRIPTIONS.map(entry => ({ + ...entry, + window: { ...(entry.window || {}) }, + fields: (Array.isArray(entry.fields) ? entry.fields : []).map(field => ({ + ...field, + children: Array.isArray(field.children) ? field.children.map(child => ({ ...child })) : undefined, + })), + })); +} + +// egg 加载器要求导出对象可扩展,describe 作为方法属性挂在 QUERIES 上 +QUERIES.describe = describe; + +module.exports = QUERIES; diff --git a/app/service/systems/report/queries/sevenDayStockFlow.js b/app/service/systems/report/queries/sevenDayStockFlow.js new file mode 100644 index 0000000..6d541d4 --- /dev/null +++ b/app/service/systems/report/queries/sevenDayStockFlow.js @@ -0,0 +1,282 @@ +'use strict'; + +const { buildDayWindows, resolveWindowConfig } = require('../../../../lib/report/day_window'); +const { avgDaysPerWeek, suggestWithCompensate, warnOf } = require('../../../../lib/report/formatters'); + +/** + * 库存变化以及补货报表查询器的静态字段清单(前端可读列元数据)。 + * key 与查询器返回的行字段一一对应;computed=true 表示由查询器预计算、非原始表字段; + * asText=true 表示渲染层将该列落地为 Excel 文本单元格(长数字串防科学计数法); + * daily 为数组类型,children 描述每日出入库子字段。 + * @type {Array} + */ +const FIELDS = Object.freeze([ + { key: 'stock_id', label: '库存ID', type: 'number' }, + { key: 'item_code', label: '商品编码', type: 'string', asText: true }, + { key: 'item_name', label: '商品名称', type: 'string' }, + { key: 'barcode', label: '条码', type: 'string', asText: true }, + { + key: 'daily', + label: '每日出入库', + type: 'array', + children: [ + { key: 'ck', label: '出库数', type: 'number' }, + { key: 'rk', label: '入库数', type: 'number' }, + ], + }, + { key: 'ck_total', label: '出库合计', type: 'number' }, + { key: 'rk_total', label: '入库合计', type: 'number' }, + { key: 'available', label: '可用库存', type: 'number' }, + { key: 'total', label: '总库存', type: 'number' }, + { key: 'pending', label: '待出库存', type: 'number' }, + { key: 'locked', label: '锁定数', type: 'number' }, + { key: 'ck_avg', label: '出库日均(×10)', type: 'number', computed: true }, + { key: 'rk_avg', label: '入库日均(×10)', type: 'number', computed: true }, + { key: 'stock_days', label: '预计可售天数', type: 'number', computed: true }, + { key: 'suggest', label: '建议补货量', type: 'number', computed: true }, + { key: 'warn', label: '库存预警', type: 'boolean', computed: true }, +]); + +/** + * stockFlow 查询器缺省窗口参数(与旧 7 日出入库口径一致,可被 params 覆盖)。 + * @type {{dayCount: number, cutoverHour: number}} + */ +const DEFAULT_WINDOW = Object.freeze({ dayCount: 7, cutoverHour: 7 }); + +/** + * 内置查询器:库存变化以及补货报表(旧 PHP《7日出入库数据》Wms.php putout_putin_storage7 口径)。 + * + * 口径与假设(供测试复核): + * 1. 窗口:dayCount 个 [D cutoverHour:00, D+1 cutoverHour:00) 本地时区窗口 + * (缺省 7 天、07:00 切点,可由 params.dayCount/cutoverHour 覆盖); + * 2. 流水:wms_stock_transaction,transaction_type IN (INBOUND, OUTBOUND),显式排除 LOCK/UNLOCK, + * 按 created_at 落入窗口,INBOUND→rk、OUTBOUND→ck; + * 3. 可用/总库存口径:wms_storage(库位级正品明细),inventory_type='ZP'、is_enabled=1、未删除, + * SUM(quantity)=总库存、SUM(available_quantity)=可用库存、SUM(locked_quantity)=锁定数, + * 待出库存=总库存-可用库存;与 wms_stock_warehouse 主表的 quantity/locked_quantity 可能存在口径差异; + * 4. 条码口径:wms_stock_barcodes 多值取字典序第一条(表内无主条码标志,旧 PHP 取 MIN(barcode) 语义); + * 5. 行范围:窗口内有流水 或 有正品库存 的 SKU 均出列,按 item_code 升序、stock_id 升序; + * 6. 日均口径:ck_avg/rk_avg = int(合计/天数×10)(formatters.avgDaysPerWeek); + * 7. 预计可售天数:出库日均>0 时 int(可用库存×10/出库日均×10),无出库时为 null; + * 8. suggest/warn 由 formatters 注册表计算(低库存补偿:available<20 且 rk_total<20)。 + * + * @param {Object} args 查询器入参 + * @param {Object} args.ctx Egg 上下文 + * @param {number|null} args.storeId 货主ID(可选,<=0 时不按货主过滤) + * @param {number|null} args.warehouseId 仓库ID(必填) + * @param {Object} [args.params={}] 业务参数(dayCount/cutoverHour 窗口覆盖等) + * @return {Promise<{windows: Array, rows: Array, meta: Object}>} 查询结果 + */ +async function sevenDayStockFlow({ ctx, storeId = null, warehouseId = null, params = {} }) { + const { app } = ctx; + const { Op } = app.Sequelize; + + const { dayCount, cutoverHour } = resolveWindowConfig(params || {}); + const windows = buildDayWindows({ dayCount, cutoverHour }); + + const normalizedWarehouseId = Number(warehouseId) || 0; + if (normalizedWarehouseId <= 0) { + throw new Error('stockFlow 查询器缺少仓库维度 warehouseId'); + } + const normalizedStoreId = Number(storeId) || 0; + + const windowStart = windows[0].start; + const windowEnd = windows[windows.length - 1].end; + + // 1) 流水聚合(排除 LOCK/UNLOCK) + const transactionWhere = { + warehouse_id: normalizedWarehouseId, + transaction_type: { [Op.in]: [ 'INBOUND', 'OUTBOUND' ] }, + created_at: { + [Op.gte]: new Date(windowStart), + [Op.lt]: new Date(windowEnd), + }, + }; + if (normalizedStoreId > 0) { + transactionWhere.store_id = normalizedStoreId; + } + + const transactionRows = await ctx.model.StockTransaction.findAll({ + where: transactionWhere, + attributes: [ 'stock_id', 'transaction_type', 'quantity', 'created_at' ], + raw: true, + }); + + // stockId → { daily: [{ck, rk}], ckTotal, rkTotal } + const flowMap = new Map(); + const upsertSlot = stockId => { + if (!flowMap.has(stockId)) { + flowMap.set(stockId, { + daily: Array.from({ length: dayCount }, () => ({ ck: 0, rk: 0 })), + ckTotal: 0, + rkTotal: 0, + }); + } + return flowMap.get(stockId); + }; + + for (const row of transactionRows) { + const stockId = Number(row.stock_id); + if (!Number.isInteger(stockId) || stockId <= 0) { + continue; + } + const quantity = Number(row.quantity) || 0; + const createdMs = new Date(row.created_at).getTime(); + let windowIndex = -1; + for (let index = 0; index < windows.length; index += 1) { + if (createdMs >= windows[index].start && createdMs < windows[index].end) { + windowIndex = index; + break; + } + } + if (windowIndex < 0) { + continue; + } + const slot = upsertSlot(stockId); + if (row.transaction_type === 'OUTBOUND') { + slot.daily[windowIndex].ck += quantity; + slot.ckTotal += quantity; + } else { + slot.daily[windowIndex].rk += quantity; + slot.rkTotal += quantity; + } + } + + // 2) 可用/总库存(正品库位明细聚合) + const storageWhere = { + warehouse_id: normalizedWarehouseId, + inventory_type: 'ZP', + is_enabled: 1, + }; + if (normalizedStoreId > 0) { + storageWhere.store_id = normalizedStoreId; + } + + const inventoryRows = await ctx.model.Storage.findAll({ + where: storageWhere, + attributes: [ + 'stock_id', + [ app.Sequelize.fn('SUM', app.Sequelize.col('quantity')), 'total_quantity' ], + [ app.Sequelize.fn('SUM', app.Sequelize.col('locked_quantity')), 'total_locked' ], + [ app.Sequelize.fn('SUM', app.Sequelize.col('available_quantity')), 'total_available' ], + ], + group: [ 'stock_id' ], + raw: true, + }); + + const inventoryMap = new Map(); + for (const row of inventoryRows) { + const stockId = Number(row.stock_id); + if (!Number.isInteger(stockId) || stockId <= 0) { + continue; + } + const totalQuantity = Number(row.total_quantity) || 0; + const totalAvailable = Number(row.total_available) || 0; + inventoryMap.set(stockId, { + total: totalQuantity, + available: totalAvailable, + locked: Number(row.total_locked) || 0, + pending: totalQuantity - totalAvailable, + }); + } + + // 3) 商品资料与条码(条码多值取字典序第一条,假设:无主条码标志,等价旧 PHP MIN(barcode)) + const stockIds = [ ...new Set([ ...flowMap.keys(), ...inventoryMap.keys() ]) ]; + let stockRows = []; + let barcodeRows = []; + if (stockIds.length > 0) { + [ stockRows, barcodeRows ] = await Promise.all([ + ctx.model.StockWarehouse.findAll({ + where: { id: { [Op.in]: stockIds } }, + attributes: [ 'id', 'item_code', 'item_name' ], + raw: true, + }), + ctx.model.StockBarcode.findAll({ + where: { stock_id: { [Op.in]: stockIds } }, + attributes: [ 'stock_id', 'barcode' ], + order: [[ 'barcode', 'ASC' ]], + raw: true, + }), + ]); + } + + const stockMap = new Map(); + for (const row of stockRows) { + stockMap.set(Number(row.id), { + itemCode: String(row.item_code || '').trim(), + itemName: String(row.item_name || '').trim(), + }); + } + + const barcodeMap = new Map(); + for (const row of barcodeRows) { + const stockId = Number(row.stock_id); + const barcode = String(row.barcode || '').trim(); + // 查询已按 barcode 升序,首个即字典序第一条 + if (!barcodeMap.has(stockId) && barcode) { + barcodeMap.set(stockId, barcode); + } + } + + // 4) 组装数据行 + const rows = stockIds.map(stockId => { + const flow = flowMap.get(stockId) || { + daily: Array.from({ length: dayCount }, () => ({ ck: 0, rk: 0 })), + ckTotal: 0, + rkTotal: 0, + }; + const inventory = inventoryMap.get(stockId) || { total: 0, available: 0, locked: 0, pending: 0 }; + const stock = stockMap.get(stockId) || { itemCode: '', itemName: '' }; + const available = inventory.available; + const total = inventory.total; + const ckTotal = flow.ckTotal; + const rkTotal = flow.rkTotal; + const ckAvg = avgDaysPerWeek(ckTotal, dayCount); + const rkAvg = avgDaysPerWeek(rkTotal, dayCount); + // 预计可售天数:日均出库 = ckAvg/10,避免浮点误差改用 (available×10)/ckAvg 取整 + const stockDays = ckAvg > 0 ? Math.floor((available * 10) / ckAvg) : null; + + return { + stock_id: stockId, + item_code: stock.itemCode, + item_name: stock.itemName, + barcode: barcodeMap.get(stockId) || '', + daily: flow.daily, + ck_total: ckTotal, + rk_total: rkTotal, + available, + total, + pending: inventory.pending, + locked: inventory.locked, + ck_avg: ckAvg, + rk_avg: rkAvg, + stock_days: stockDays, + suggest: suggestWithCompensate(ckTotal, available, rkTotal), + warn: warnOf(ckTotal, available, rkTotal), + }; + }); + + rows.sort((left, right) => { + if (left.item_code !== right.item_code) { + return left.item_code < right.item_code ? -1 : 1; + } + return left.stock_id - right.stock_id; + }); + + return { + windows, + rows, + meta: { + warehouseId: normalizedWarehouseId, + storeId: normalizedStoreId, + dayCount, + cutoverHour, + }, + }; +} + +module.exports = sevenDayStockFlow; +// 静态字段清单挂到查询器模块上,供报表引擎与注册表 describe 读取(不执行真实数据查询) +module.exports.fields = FIELDS; +// 缺省窗口参数挂到查询器模块上,供注册表 describe 与 report.meta 读取 +module.exports.defaultWindow = DEFAULT_WINDOW; diff --git a/app/service/systems/reportDelivery.js b/app/service/systems/reportDelivery.js new file mode 100644 index 0000000..ee00c6b --- /dev/null +++ b/app/service/systems/reportDelivery.js @@ -0,0 +1,1475 @@ +'use strict'; + +const { Service } = require('egg'); +const { scheduleDateOf } = require('../../lib/report/day_window'); +const { + validateNotifyTemplate, + renderNotifyTemplate, + formatNotifyTime, +} = require('../../lib/report/notifyTemplate'); + +/** + * 货主报表定时投递编排服务(systems 层)。 + * + * 职责: + * 1. dispatch:分钟级扫描 wms_report_delivery_plan(enabled=1),按 HH:mm + 宽限窗口命中后 + * 对每个(货主+报表+数据日期+时间点)幂等生成报表并投递; + * 2. 投递记录状态机与 wms_report_delivery_log.status 一致: + * pending → exporting → delivered / failed / cancelled; + * 3. 失败退避重试(照搬 wms_waybill_allocate_queue 风格:MAX_RETRY=3, + * 退避 = retry_count × 60s);重试扫描条件:status=failed 且 retry_count<3 且 next_retry_at<=now; + * 4. 投递计划/投递记录的增改查(供 systemMethods 薄出口调用)。 + */ + +const DELIVERY_STATUS = Object.freeze({ + PENDING: 'pending', + EXPORTING: 'exporting', + DELIVERED: 'delivered', + FAILED: 'failed', + CANCELLED: 'cancelled', +}); + +/** 投递渠道(渠道已收敛:仅支持 inbox,wecom/link 已弃用) */ +const DELIVERY_CHANNELS = Object.freeze([ 'inbox' ]); +const DEFAULT_CHANNEL = 'inbox'; +const DEFAULT_GRACE_MINUTES = 60; +const MAX_RETRY_COUNT = 3; +const RETRY_BASE_DELAY_MS = 60 * 1000; +const EXPORTING_STALE_MS = 30 * 60 * 1000; +const MAX_ERROR_MESSAGE_LENGTH = 500; +const HHMM_PATTERN = /^([01]\d|2[0-3]):[0-5]\d$/; +/** 通知模板长度上限(与表结构 STRING(500) 一致) */ +const NOTIFY_TEMPLATE_MAX_LENGTH = 500; +/** 计划名称长度上限(与表结构 STRING(100) 一致) */ +const PLAN_NAME_MAX_LENGTH = 100; +/** 通知群多选上限 */ +const MAX_NOTIFY_GROUP_IDS = 20; +/** 通知成员多选上限 */ +const MAX_NOTIFY_MEMBER_IDS = 100; + +class ReportDeliveryService extends Service { + // ==================== 计划/记录查询(供 method 层复用) ==================== + + /** + * 校验并规范化投递时间点(HH:mm 格式、去重、升序排序)。 + * @param {Array|string} rawTimes 原始时间点(数组或 JSON 字符串) + * @return {Array} 规范化时间点数组 + * @throws {Error} 含非法格式时抛出 + */ + normalizeScheduleTimes(rawTimes) { + let list = rawTimes; + if (typeof list === 'string') { + try { + list = JSON.parse(list); + } catch (error) { + throw new Error('schedule_times 必须为 HH:mm 字符串数组'); + } + } + if (!Array.isArray(list) || list.length === 0) { + throw new Error('schedule_times 必须为 HH:mm 字符串数组且不能为空'); + } + const seen = new Set(); + const normalized = []; + for (const item of list) { + const timePoint = String(item || '').trim(); + if (!HHMM_PATTERN.test(timePoint)) { + throw new Error(`schedule_times 含非法时间点(需 HH:mm 24 小时制): ${timePoint}`); + } + if (!seen.has(timePoint)) { + seen.add(timePoint); + normalized.push(timePoint); + } + } + normalized.sort(); + return normalized; + } + + /** + * 解析 JSON 数组字段:数组原样、JSON 字符串解析、null/undefined/'' 返回 null。 + * @param {*} value 原始值 + * @param {string} label 字段名(错误提示用) + * @return {Array|null} 数组或 null + * @throws {Error} 非数组或 JSON 解析失败时抛出业务可读错误 + */ + parseJsonArray(value, label) { + if (value === null || value === undefined || value === '') { + return null; + } + let list = value; + if (typeof value === 'string') { + try { + list = JSON.parse(value); + } catch (error) { + throw new Error(`${label} 必须为数组`); + } + } + if (!Array.isArray(list)) { + throw new Error(`${label} 必须为数组`); + } + return list; + } + + /** + * 视图安全的 JSON 数组读取(兼容字符串/数组/null,无法解析时返回 null)。 + * @param {*} value 字段原始值 + * @return {Array|null} 数组或 null + */ + readJsonArray(value) { + if (Array.isArray(value)) { + return value; + } + if (typeof value === 'string' && value.trim()) { + try { + const parsed = JSON.parse(value); + return Array.isArray(parsed) ? parsed : null; + } catch (error) { + return null; + } + } + return null; + } + + /** + * 视图安全的 JSON 对象读取(兼容对象/字符串/null,无法解析时返回 null)。 + * @param {*} value 字段原始值 + * @return {Object|null} 对象或 null + */ + readJsonObject(value) { + if (value && typeof value === 'object' && !Array.isArray(value)) { + return value; + } + if (typeof value === 'string' && value.trim()) { + try { + const parsed = JSON.parse(value); + return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null; + } catch (error) { + return null; + } + } + return null; + } + + /** + * 校验并规范化文本通知模板(长度 ≤500 + 标签白名单)。 + * 空值/null/空串均视为未启用(返回空字符串)。 + * @param {*} value 原始模板值 + * @return {string} 规范化后的模板(未配置时为空字符串) + * @throws {Error} 超长或含白名单外标签时抛出业务可读错误 + */ + normalizeNotifyTemplate(value) { + if (value === null || value === undefined || value === '') { + return ''; + } + const normalized = String(value).trim(); + if (!normalized) { + return ''; + } + if (normalized.length > NOTIFY_TEMPLATE_MAX_LENGTH) { + throw new Error(`通知模板 notify_template 长度不能超过 ${NOTIFY_TEMPLATE_MAX_LENGTH} 字符`); + } + const check = validateNotifyTemplate(normalized); + if (!check.valid) { + throw new Error( + `通知模板含未知标签(仅支持 {time}/{url}/{report_name}/{biz_date}): ${check.invalidTags.join(', ')}` + ); + } + return normalized; + } + + /** + * 校验并规范化计划名称(仅展示字段,不参与幂等/关联逻辑)。 + * undefined=未传入(不覆盖既有值);null/空串/全空白=显式清空(返回 null); + * 非空时 trim 且长度 ≤ PLAN_NAME_MAX_LENGTH,超长抛出业务可读错误。 + * @param {*} value 原始名称值 + * @return {string|null|undefined} 规范化名称(未传入返回 undefined,清空返回 null) + * @throws {Error} 非空且超长时抛出业务可读错误 + */ + normalizePlanName(value) { + if (value === undefined) { + return undefined; + } + if (value === null || value === '') { + return null; + } + const normalized = String(value).trim(); + if (!normalized) { + return null; + } + if (normalized.length > PLAN_NAME_MAX_LENGTH) { + throw new Error(`计划名称 name 长度不能超过 ${PLAN_NAME_MAX_LENGTH} 字符`); + } + return normalized; + } + + /** + * 校验并规范化通知群ID列表(wms_inbox_group.id 数组)。 + * 元素需为正整数、自动去重并升序排序、上限 MAX_NOTIFY_GROUP_IDS;null/空数组均允许(表示未选择群)。 + * @param {*} value 原始值(数组或 JSON 字符串) + * @return {Array|null} 规范化后的正整数数组(去重升序),未选择返回 null + * @throws {Error} 元素非法或超上限时抛出业务可读错误 + */ + normalizeNotifyGroupIds(value) { + const list = this.parseJsonArray(value, '通知群 notify_group_ids'); + if (list === null) { + return null; + } + if (list.length > MAX_NOTIFY_GROUP_IDS) { + throw new Error(`通知群 notify_group_ids 最多选择 ${MAX_NOTIFY_GROUP_IDS} 个群`); + } + const seen = new Set(); + const normalized = []; + for (const item of list) { + const id = Number(item); + if (!Number.isInteger(id) || id <= 0) { + throw new Error(`通知群 notify_group_ids 含非法群ID(需正整数): ${item}`); + } + if (!seen.has(id)) { + seen.add(id); + normalized.push(id); + } + } + normalized.sort((a, b) => a - b); + return normalized; + } + + /** + * 校验并规范化通知成员ID列表(外部 IM 用户 ID 字符串数组)。 + * 元素需为非空字符串、自动去重、上限 MAX_NOTIFY_MEMBER_IDS;null/空数组均允许(表示未选择成员)。 + * @param {*} value 原始值(数组或 JSON 字符串) + * @return {Array|null} 规范化后的字符串数组(去重),未选择返回 null + * @throws {Error} 元素非法或超上限时抛出业务可读错误 + */ + normalizeNotifyMemberIds(value) { + const list = this.parseJsonArray(value, '通知成员 notify_member_ids'); + if (list === null) { + return null; + } + if (list.length > MAX_NOTIFY_MEMBER_IDS) { + throw new Error(`通知成员 notify_member_ids 最多选择 ${MAX_NOTIFY_MEMBER_IDS} 个成员`); + } + const seen = new Set(); + const normalized = []; + for (const item of list) { + const memberId = String(item || '').trim(); + if (!memberId) { + throw new Error('通知成员 notify_member_ids 含空成员ID(需非空字符串)'); + } + if (!seen.has(memberId)) { + seen.add(memberId); + normalized.push(memberId); + } + } + return normalized; + } + + /** + * 校验通知群ID是否全部存在(软删自动排除,不校验 is_blocked: + * 屏蔽属于发送时过滤维度,保存时允许暂被屏蔽的群仍可选中)。 + * @param {Array} groupIds 群ID列表 + * @return {Promise} + * @throws {Error} 存在无效群ID时抛出(列出不存在或已删除的ID) + */ + async validateNotifyGroupExists(groupIds) { + const { ctx } = this; + const model = ctx.model && ctx.model.InboxGroup; + if (!model || typeof model.findAll !== 'function') { + throw new Error('站内信群模型 InboxGroup 不可用,无法校验通知群配置'); + } + const { Op } = ctx.app.Sequelize; + const rows = await model.findAll({ + where: { id: { [Op.in]: groupIds } }, + attributes: [ 'id' ], + raw: true, + }); + const found = new Set((Array.isArray(rows) ? rows : []).map(row => Number(row.id))); + const missing = groupIds.filter(id => !found.has(id)); + if (missing.length > 0) { + throw new Error(`通知群 notify_group_ids 含不存在或已删除的群ID: ${missing.join(', ')}`); + } + } + + /** + * 保存/更新投递计划(存在则更新,不存在则创建;货主+报表定义ID唯一)。 + * @param {Object} options 入参 + * @param {number} options.storeId 货主ID + * @param {number|string} options.reportId 报表定义ID + * @param {Array} options.scheduleTimes 投递时间点(HH:mm) + * @param {string} [options.channel='inbox'] 投递渠道(仅支持 inbox) + * @param {number} [options.lateGraceMinutes=60] 补投宽限分钟 + * @param {string} [options.remark] 备注 + * @param {string|null} [options.name] 计划名称(可空;未传不覆盖,null/空串清空,非空 trim ≤100) + * @param {string} [options.notifyTemplate] 文本通知模板(≤500,白名单标签 {time}/{url}/{report_name}/{biz_date}) + * @param {Array|string} [options.notifyGroupIds] 通知群ID数组(wms_inbox_group.id,≤20) + * @param {Array|string} [options.notifyMemberIds] 通知成员ID数组(外部IM用户ID,≤100) + * @return {Promise} 保存后的计划记录 + * @throws {Error} 参数非法或并发首次保存撞唯一索引且降级重查不到记录时抛出业务可读错误 + */ + async savePlan({ + storeId, + reportId, + scheduleTimes, + channel = DEFAULT_CHANNEL, + lateGraceMinutes = DEFAULT_GRACE_MINUTES, + remark = '', + name, + notifyTemplate, + notifyGroupIds, + notifyMemberIds, + }) { + const { ctx } = this; + const model = ctx.model && ctx.model.ReportDeliveryPlan; + if (!model) { + throw new Error('投递计划模型 ReportDeliveryPlan 不可用'); + } + + const normalizedStoreId = Number(storeId) || 0; + if (normalizedStoreId <= 0) { + throw new Error('货主ID store_id 不能为空'); + } + const normalizedReportId = Number(reportId) || 0; + if (!Number.isInteger(normalizedReportId) || normalizedReportId <= 0) { + throw new Error('报表ID report_id 必须为正整数'); + } + // 校验报表定义存在且启用 + await ctx.service.systems.report.getDefinition(normalizedReportId); + + const normalizedTimes = this.normalizeScheduleTimes(scheduleTimes); + const normalizedChannel = String(channel || DEFAULT_CHANNEL).trim().toLowerCase() || DEFAULT_CHANNEL; + if (!DELIVERY_CHANNELS.includes(normalizedChannel)) { + throw new Error(`投递渠道仅支持 inbox: ${channel}`); + } + const graceMinutes = Math.max(0, Math.min(1440, Math.floor(Number(lateGraceMinutes) || 0))); + + // 计划名称校验(未传入 undefined 时保持既有字段不动,避免更新时误清空) + let normalizedName; + if (name !== undefined) { + normalizedName = this.normalizePlanName(name); + } + + // 文本通知配置校验(未传入 undefined 时保持既有字段不动,避免更新时误清空) + let normalizedNotifyTemplate; + let normalizedNotifyGroupIds; + let normalizedNotifyMemberIds; + if (notifyTemplate !== undefined) { + normalizedNotifyTemplate = this.normalizeNotifyTemplate(notifyTemplate); + } + if (notifyGroupIds !== undefined) { + normalizedNotifyGroupIds = this.normalizeNotifyGroupIds(notifyGroupIds); + if (normalizedNotifyGroupIds !== null && normalizedNotifyGroupIds.length > 0) { + await this.validateNotifyGroupExists(normalizedNotifyGroupIds); + } + } + if (notifyMemberIds !== undefined) { + normalizedNotifyMemberIds = this.normalizeNotifyMemberIds(notifyMemberIds); + } + + const payload = { + store_id: normalizedStoreId, + report_definition_id: normalizedReportId, + schedule_times: normalizedTimes, + channel: normalizedChannel, + late_grace_minutes: graceMinutes, + remark: String(remark || '').slice(0, 500), + }; + if (normalizedName !== undefined) { + payload.name = normalizedName; + } + if (normalizedNotifyTemplate !== undefined) { + payload.notify_template = normalizedNotifyTemplate; + } + if (normalizedNotifyGroupIds !== undefined) { + payload.notify_group_ids = normalizedNotifyGroupIds; + } + if (normalizedNotifyMemberIds !== undefined) { + payload.notify_member_ids = normalizedNotifyMemberIds; + } + + const existing = await model.findOne({ + where: { + store_id: normalizedStoreId, + report_definition_id: normalizedReportId, + }, + }); + if (existing) { + await existing.update(payload); + return this.planToView(existing); + } + try { + const created = await model.create(payload); + return this.planToView(created); + } catch (error) { + // 并发首次保存撞 uk_store_report_definition 唯一索引:降级为重查并更新(与 processOne 的 findOrCreate 降级一致) + if (error && error.name === 'SequelizeUniqueConstraintError') { + const winner = await model.findOne({ + where: { + store_id: normalizedStoreId, + report_definition_id: normalizedReportId, + }, + }); + if (winner) { + await winner.update(payload); + return this.planToView(winner); + } + throw new Error('该货主已存在此报表的投递计划,保存冲突,请重试'); + } + throw error; + } + } + + /** + * 快速复制投递计划到其他货主(货主+报表定义ID唯一,目标已存在同报表定义计划时跳过)。 + * + * 规则: + * 1. id 必须为正整数,源计划不存在(含软删)时抛出业务可读错误; + * 2. storeIds 必须为非空数组且元素为正整数,自动去重; + * 与源计划 store_id 相同的项计入 skipped(原因:与源计划货主相同), + * 全部剔除后为空时仍正常返回(created=[],skipped 标注原因); + * 3. 目标货主必须在 wms_store 存在且状态正常(status=1,软删自动排除), + * 不存在或不合法者计入 skipped(原因:货主不存在或状态异常); + * 4. 目标货主已存在同 report_definition_id 的计划(软删排除)时跳过 + * (原因:已存在同报表定义计划),不覆盖不报错; + * 5. 新建计划时 notify_group_ids / notify_member_ids 置空(null,通知配置不复制), + * enabled 等其余配置字段原样复制(enabled 保持“复制”语义,复制源计划启停状态); + * 6. 批量创建使用事务包裹,保证一致性;并发撞唯一索引时降级为 skipped 不中断其余创建。 + * + * @param {Object} options 入参 + * @param {number|string} options.id 源计划ID(正整数) + * @param {Array} options.storeIds 目标货主ID数组(元素需正整数,允许 JSON 字符串) + * @return {Promise<{created: Array<{id: number, store_id: number}>, skipped: Array<{store_id: number, reason: string}>}>} + * 复制结果:created 为新建成功的计划(id=新计划ID,store_id=目标货主ID), + * skipped 为跳过项(store_id=目标货主ID,reason=跳过原因) + * @throws {Error} id 非法、源计划不存在、storeIds 非空数组校验失败或元素非法时抛出业务可读错误 + */ + async copyPlan({ id, storeIds }) { + const { ctx } = this; + const model = ctx.model && ctx.model.ReportDeliveryPlan; + if (!model) { + throw new Error('投递计划模型 ReportDeliveryPlan 不可用'); + } + + // 源计划校验(findByPk 受 paranoid 约束,软删自动排除,不存在返回 null) + const normalizedId = Number(id) || 0; + if (!Number.isInteger(normalizedId) || normalizedId <= 0) { + throw new Error('计划ID无效'); + } + const source = await model.findByPk(normalizedId); + if (!source) { + throw new Error('计划不存在'); + } + + // 目标货主数组校验:非空数组、元素为正整数、自动去重(JSON 字符串兼容,与 save 口径一致) + const rawList = this.parseJsonArray(storeIds, '目标货主 store_ids'); + if (rawList === null || rawList.length === 0) { + throw new Error('目标货主 store_ids 必须为非空数组'); + } + const seen = new Set(); + const targetStoreIds = []; + for (const item of rawList) { + const storeId = Number(item) || 0; + if (!Number.isInteger(storeId) || storeId <= 0) { + throw new Error(`目标货主 store_ids 含非法货主ID(需正整数): ${item}`); + } + if (!seen.has(storeId)) { + seen.add(storeId); + targetStoreIds.push(storeId); + } + } + + const sourceStoreId = Number(source.store_id) || 0; + const skipped = []; + const candidates = []; + for (const storeId of targetStoreIds) { + if (storeId === sourceStoreId) { + skipped.push({ store_id: storeId, reason: '与源计划货主相同' }); + } else { + candidates.push(storeId); + } + } + + // 目标货主存在性校验(wms_store 状态正常 status=1,软删自动排除) + const validTargets = []; + if (candidates.length > 0) { + const storeModel = ctx.model && ctx.model.Store; + if (!storeModel || typeof storeModel.findAll !== 'function') { + throw new Error('货主模型 Store 不可用,无法校验目标货主'); + } + const { Op } = ctx.app.Sequelize; + const storeRows = await storeModel.findAll({ + where: { id: { [Op.in]: candidates }, status: 1 }, + attributes: [ 'id' ], + raw: true, + }); + const foundSet = new Set((Array.isArray(storeRows) ? storeRows : []).map(row => Number(row.id) || 0)); + for (const storeId of candidates) { + if (foundSet.has(storeId)) { + validTargets.push(storeId); + } else { + skipped.push({ store_id: storeId, reason: '货主不存在或状态异常' }); + } + } + } + + const created = []; + if (validTargets.length > 0) { + // 已存在同报表定义计划的目标货主跳过(软删排除,与唯一索引口径一致) + const { Op } = ctx.app.Sequelize; + const existingRows = await model.findAll({ + where: { + store_id: { [Op.in]: validTargets }, + report_definition_id: Number(source.report_definition_id) || 0, + }, + attributes: [ 'store_id' ], + raw: true, + }); + const existingSet = new Set((Array.isArray(existingRows) ? existingRows : []).map(row => Number(row.store_id) || 0)); + const toCreate = []; + for (const storeId of validTargets) { + if (existingSet.has(storeId)) { + skipped.push({ store_id: storeId, reason: '已存在同报表定义计划' }); + } else { + toCreate.push(storeId); + } + } + + if (toCreate.length > 0) { + // 其余配置字段原样复制;通知配置不复制(置空);enabled 原样复制保持“复制”语义 + const payload = { + report_definition_id: Number(source.report_definition_id) || 0, + schedule_times: Array.isArray(source.schedule_times) ? source.schedule_times : [], + channel: String(source.channel || DEFAULT_CHANNEL), + late_grace_minutes: Number(source.late_grace_minutes ?? DEFAULT_GRACE_MINUTES), + name: source.name == null ? null : String(source.name), + remark: source.remark == null ? null : String(source.remark), + notify_template: source.notify_template == null ? null : String(source.notify_template), + notify_group_ids: null, + notify_member_ids: null, + enabled: Number(source.enabled ?? 1), + }; + + const transaction = await ctx.model.transaction(); + try { + for (const storeId of toCreate) { + try { + const row = await model.create({ ...payload, store_id: storeId }, { transaction }); + created.push({ id: Number(row.id) || 0, store_id: storeId }); + } catch (error) { + // 并发下撞 uk_store_report_definition 唯一索引:降级为 skipped,不中断其余创建 + if (error && error.name === 'SequelizeUniqueConstraintError') { + skipped.push({ store_id: storeId, reason: '已存在同报表定义计划' }); + } else { + throw error; + } + } + } + await transaction.commit(); + } catch (error) { + await transaction.rollback(); + throw error; + } + } + } + + return { created, skipped }; + } + + /** + * 计划记录转视图对象。 + * @param {Object} plan 计划记录(实例或 raw) + * @return {Object} 视图对象 + */ + planToView(plan) { + if (!plan) { + return null; + } + return { + id: Number(plan.id) || 0, + store_id: Number(plan.store_id) || 0, + report_definition_id: Number(plan.report_definition_id) || 0, + schedule_times: Array.isArray(plan.schedule_times) ? plan.schedule_times : [], + channel: String(plan.channel || DEFAULT_CHANNEL), + enabled: Number(plan.enabled ?? 1), + late_grace_minutes: Number(plan.late_grace_minutes ?? DEFAULT_GRACE_MINUTES), + name: String(plan.name || ''), + remark: String(plan.remark || ''), + notify_template: String(plan.notify_template || ''), + notify_group_ids: this.readJsonArray(plan.notify_group_ids), + notify_member_ids: this.readJsonArray(plan.notify_member_ids), + created_at: plan.created_at || null, + updated_at: plan.updated_at || null, + }; + } + + /** + * 分页查询投递计划列表。 + * @param {Object} [options={}] 入参 + * @param {number} [options.storeId] 货主ID + * @param {number|string} [options.reportId] 报表定义ID + * @param {number|string} [options.enabled] 启用状态(0/1) + * @param {Object} [options.pagination={}] 分页 { page, pageSize } + * @param {Object} [options.sort={}] 排序 { sortField, sortOrder } + * @return {Promise<{list: Array, total: number, page: number, pageSize: number}>} 列表结果, + * 每条计划含 store_name(货主公司全称,货主已删除或不存在时为空串) + */ + async listPlans({ storeId = null, reportId = null, enabled = null, pagination = {}, sort = {} } = {}) { + const { ctx } = this; + const model = ctx.model && ctx.model.ReportDeliveryPlan; + if (!model) { + throw new Error('投递计划模型 ReportDeliveryPlan 不可用'); + } + + const where = {}; + const normalizedStoreId = Number(storeId) || 0; + if (normalizedStoreId > 0) { + where.store_id = normalizedStoreId; + } + const normalizedReportId = Number(reportId) || 0; + if (normalizedReportId > 0) { + where.report_definition_id = normalizedReportId; + } + if (enabled !== null && enabled !== undefined && enabled !== '') { + where.enabled = Number(enabled) ? 1 : 0; + } + + const page = Math.max(1, Math.floor(Number(pagination.page) || 1)); + const pageSize = Math.min(200, Math.max(1, Math.floor(Number(pagination.pageSize) || 20))); + + const allowedSortFields = [ 'id', 'created_at', 'updated_at', 'store_id', 'report_definition_id' ]; + const sortField = String(sort.sortField || sort.sort_field || 'id').trim(); + const sortOrder = String(sort.sortOrder || sort.sort_order || 'desc').trim().toLowerCase() === 'asc' ? 'ASC' : 'DESC'; + const order = allowedSortFields.includes(sortField) + ? [[ sortField, sortOrder ]] + : [[ 'id', 'DESC' ]]; + + const [ rows, total ] = await Promise.all([ + model.findAll({ + where, + order, + offset: (page - 1) * pageSize, + limit: pageSize, + raw: true, + }), + model.count({ where }), + ]); + + const planRows = Array.isArray(rows) ? rows : []; + + // 批量查询货主名称(一次 IN 查询避免 N+1):软删除货主自动排除, + // 货主已删除或不存在时 store_name 回退为空串 + const storeIds = [ ...new Set(planRows.map(row => Number(row.store_id) || 0).filter(id => id > 0)) ]; + const storeNameMap = new Map(); + if (storeIds.length > 0) { + const storeModel = ctx.model && ctx.model.Store; + if (storeModel && typeof storeModel.findAll === 'function') { + const { Op } = ctx.app.Sequelize; + const storeRows = await storeModel.findAll({ + where: { id: { [Op.in]: storeIds } }, + attributes: [ 'id', 'company_name' ], + raw: true, + }); + for (const storeRow of Array.isArray(storeRows) ? storeRows : []) { + storeNameMap.set(Number(storeRow.id) || 0, String(storeRow.company_name || '')); + } + } + } + + return { + list: planRows.map(row => ({ + id: Number(row.id) || 0, + store_id: Number(row.store_id) || 0, + store_name: storeNameMap.get(Number(row.store_id) || 0) || '', + report_definition_id: Number(row.report_definition_id) || 0, + schedule_times: Array.isArray(row.schedule_times) ? row.schedule_times : [], + channel: String(row.channel || DEFAULT_CHANNEL), + enabled: Number(row.enabled ?? 1), + late_grace_minutes: Number(row.late_grace_minutes ?? DEFAULT_GRACE_MINUTES), + name: String(row.name || ''), + remark: String(row.remark || ''), + notify_template: String(row.notify_template || ''), + notify_group_ids: this.readJsonArray(row.notify_group_ids), + notify_member_ids: this.readJsonArray(row.notify_member_ids), + created_at: row.created_at || null, + updated_at: row.updated_at || null, + })), + total: Number(total) || 0, + page, + pageSize, + }; + } + + /** + * 分页查询投递记录(审计)。 + * @param {Object} [options={}] 入参 + * @param {number} [options.storeId] 货主ID + * @param {number|string} [options.reportId] 报表定义ID + * @param {string} [options.status] 状态过滤 + * @param {Object} [options.pagination={}] 分页 { page, pageSize } + * @param {Object} [options.sort={}] 排序 { sortField, sortOrder } + * @return {Promise<{list: Array, total: number, page: number, pageSize: number}>} 列表结果 + */ + async listLogs({ storeId = null, reportId = null, status = '', pagination = {}, sort = {} } = {}) { + const { ctx } = this; + const model = ctx.model && ctx.model.ReportDeliveryLog; + if (!model) { + throw new Error('投递记录模型 ReportDeliveryLog 不可用'); + } + + const where = {}; + const normalizedStoreId = Number(storeId) || 0; + if (normalizedStoreId > 0) { + where.store_id = normalizedStoreId; + } + const normalizedReportId = Number(reportId) || 0; + if (normalizedReportId > 0) { + where.report_definition_id = normalizedReportId; + } + const normalizedStatus = String(status || '').trim(); + if (normalizedStatus && Object.values(DELIVERY_STATUS).includes(normalizedStatus)) { + where.status = normalizedStatus; + } + + const page = Math.max(1, Math.floor(Number(pagination.page) || 1)); + const pageSize = Math.min(200, Math.max(1, Math.floor(Number(pagination.pageSize) || 20))); + + const allowedSortFields = [ 'id', 'created_at', 'updated_at', 'biz_date', 'delivered_at' ]; + const sortField = String(sort.sortField || sort.sort_field || 'id').trim(); + const sortOrder = String(sort.sortOrder || sort.sort_order || 'desc').trim().toLowerCase() === 'asc' ? 'ASC' : 'DESC'; + const order = allowedSortFields.includes(sortField) + ? [[ sortField, sortOrder ]] + : [[ 'id', 'DESC' ]]; + + const [ rows, total ] = await Promise.all([ + model.findAll({ + where, + order, + offset: (page - 1) * pageSize, + limit: pageSize, + raw: true, + }), + model.count({ where }), + ]); + + return { + list: (Array.isArray(rows) ? rows : []).map(row => ({ + id: Number(row.id) || 0, + warehouse_id: Number(row.warehouse_id) || 0, + store_id: Number(row.store_id) || 0, + report_definition_id: Number(row.report_definition_id) || 0, + report_name: String(row.report_name || ''), + biz_date: row.biz_date || '', + time_point: String(row.time_point || ''), + status: String(row.status || DELIVERY_STATUS.PENDING), + channel: String(row.channel || DEFAULT_CHANNEL), + file_url: String(row.file_url || ''), + retry_count: Number(row.retry_count) || 0, + next_retry_at: row.next_retry_at || null, + error_message: String(row.error_message || ''), + delivered_at: row.delivered_at || null, + notify_targets: this.readJsonObject(row.notify_targets), + created_at: row.created_at || null, + updated_at: row.updated_at || null, + })), + total: Number(total) || 0, + page, + pageSize, + }; + } + + // ==================== 投递调度 ==================== + + /** + * 计算当前时刻命中的时间点(含 late_grace_minutes 宽限窗口)。 + * 宽限跨零点场景:now 为次日凌晨时,昨日深夜时间点仍可在宽限内命中。 + * @param {Array} scheduleTimes 计划时间点(HH:mm) + * @param {Date} now 触发时刻 + * @param {number} graceMinutes 宽限分钟 + * @return {Array} 命中的时间点 + */ + hitTimePoints(scheduleTimes, now, graceMinutes) { + const normalizedGrace = Math.max(0, Math.min(1440, Math.floor(Number(graceMinutes) || 0))); + const nowMinutes = now.getHours() * 60 + now.getMinutes(); + const hits = []; + for (const timePoint of scheduleTimes) { + const parts = String(timePoint).split(':'); + const timeMinutes = Number(parts[0]) * 60 + Number(parts[1]); + const diff = nowMinutes - timeMinutes; + const wrapDiff = nowMinutes + 24 * 60 - timeMinutes; + if ((diff >= 0 && diff <= normalizedGrace) || wrapDiff <= normalizedGrace) { + hits.push(timePoint); + } + } + return hits; + } + + /** + * 计算触发时刻的数据日期(T-1 本地自然日)。 + * @param {Date} now 触发时刻 + * @return {string} 'YYYY-MM-DD' + */ + bizDateOfTrigger(now) { + return scheduleDateOf(new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1)); + } + + /** + * 计算命中时间点对应的数据日期(报表数据截止日 = 时间点所属自然日的 T-1)。 + * + * 口径:同一时间点在「正常投递」与「跨零点补投」时必须落在相同 biz_date, + * 保证幂等键 (store_id, report_definition_id, biz_date, time_point) 防重不防漏: + * - 当日命中(timePoint 的 HH:mm <= now 的 HH:mm):时间点属于触发自然日, + * biz_date = 触发日 - 1; + * - 跨零点补投(timePoint 的 HH:mm > now 的 HH:mm,即昨日深夜时间点): + * 时间点属于昨日自然日,biz_date = 昨日 - 1(触发日 - 2), + * 与昨日正常投递口径一致,避免与次日正常投递撞幂等键。 + * + * @param {Date} now 触发时刻 + * @param {string} timePoint 命中的投递时间点(HH:mm) + * @return {string} 'YYYY-MM-DD' + */ + bizDateOfTimePoint(now, timePoint) { + const parts = String(timePoint).split(':'); + const timeMinutes = Number(parts[0]) * 60 + Number(parts[1]); + const nowMinutes = now.getHours() * 60 + now.getMinutes(); + const scheduleDayOffset = timeMinutes > nowMinutes ? -2 : -1; + return scheduleDateOf(new Date(now.getFullYear(), now.getMonth(), now.getDate() + scheduleDayOffset)); + } + + /** + * 解析货主所属仓库:优先首条有效合约(auth_status=2 且未停用),否则回退最早一条合约。 + * 假设:货主报表按单仓库生成,取最早合约的仓库维度(供测试复核)。 + * @param {number} storeId 货主ID + * @return {Promise} 仓库ID,未找到返回 0 + */ + async resolveStoreWarehouse(storeId) { + const { ctx } = this; + const model = ctx.model && ctx.model.StoreWarehouse; + if (!model || typeof model.findAll !== 'function') { + return 0; + } + const normalizedStoreId = Number(storeId) || 0; + if (normalizedStoreId <= 0) { + return 0; + } + const rows = await model.findAll({ + where: { store_id: normalizedStoreId }, + attributes: [ 'store_id', 'warehouse_id', 'auth_status', 'warehouse_use_status' ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + const list = Array.isArray(rows) ? rows : []; + const active = list.find(row => Number(row.auth_status) === 2 && Number(row.warehouse_use_status) !== 0); + const chosen = active || list[0]; + return chosen ? Number(chosen.warehouse_id) || 0 : 0; + } + + /** + * 投递成功回写(delivered),并落文本通知目标快照(可选)。 + * @param {Object} log 投递记录实例 + * @param {Object} fileResult 生成结果 { fileKey, url, filename } + * @param {Object|null} [notifyTargets=null] 文本通知目标快照 { group_ids, member_ids, notify_text } + * @return {Promise} + */ + async markDelivered(log, fileResult, notifyTargets = null) { + await log.update({ + status: DELIVERY_STATUS.DELIVERED, + // 表结构仅 file_url 一列承载产物地址(无 file_key/task_id 列),url 缺失时退化为 fileKey + file_url: String(fileResult.url || fileResult.fileKey || '').slice(0, 500), + error_message: null, + next_retry_at: null, + delivered_at: new Date(), + notify_targets: notifyTargets || null, + }); + } + + /** + * 投递失败回写(failed + 退避重试,MAX_RETRY=3,照搬 wms_waybill_allocate_queue 风格)。 + * @param {Object} log 投递记录实例 + * @param {string} errorMessage 失败原因 + * @return {Promise} + */ + async markFailed(log, errorMessage) { + const retryCount = Number(log.retry_count) || 0; + const nextCount = retryCount + 1; + const normalizedMessage = String(errorMessage || '报表投递失败').slice(0, MAX_ERROR_MESSAGE_LENGTH); + await log.update({ + status: DELIVERY_STATUS.FAILED, + retry_count: nextCount, + next_retry_at: nextCount >= MAX_RETRY_COUNT + ? null + : new Date(Date.now() + nextCount * RETRY_BASE_DELAY_MS), + error_message: normalizedMessage, + }); + } + + /** + * 置为导出中(exporting),并回填生成报表使用的仓库维度与报表名称快照。 + * @param {Object} log 投递记录实例 + * @param {number} warehouseId 仓库ID + * @param {string} [reportName=''] 报表名称快照 + * @return {Promise} + */ + async markExporting(log, warehouseId, reportName = '') { + await log.update({ + status: DELIVERY_STATUS.EXPORTING, + warehouse_id: Number(warehouseId) || 0, + report_name: String(reportName || '').slice(0, 100), + error_message: null, + }); + } + + /** + * 构建投递通知正文(站内信 inbox 文案)。 + * @param {Object} definition 报表定义 + * @param {string} bizDate 数据日期 + * @param {string} fileUrl 文件链接 + * @return {string} 通知正文 + */ + buildMessageContent(definition, bizDate, fileUrl) { + const reportName = String((definition && definition.name) || '报表'); + return `【${reportName}】${bizDate} 数据报表已生成,点击查看:${fileUrl}`; + } + + /** + * 按渠道投递(渠道已收敛,仅支持 inbox 站内信群推送)。 + * + * 规则: + * 1. 历史计划残留 wecom/link 等已弃用渠道时,按 inbox 兜底执行并记录 warn 日志 + * (不直接抛错:避免历史计划在 failed 退避循环中耗尽重试次数后永久卡死); + * 2. 推送失败(success=false 或消息记录回写 push_status=3)时,立即复用 + * ctx.service.inbox.message.retry 重推一次(重置 push_status=0 异步重推, + * ext_id 幂等复用同一条消息记录,不重复写); + * 3. 重推仍失败(retry 自身抛错)时向上抛错,交由上层 failed 退避循环 + * (MAX_RETRY=3,退避 = retry_count × 60s); + * 4. 完成后按计划配置附带发送文本通知(与投递渠道独立)。 + * + * @param {Object} options 入参 + * @param {Object} options.plan 投递计划 + * @param {Object} options.definition 报表定义 + * @param {Object} options.fileResult 生成结果 + * @param {number} options.warehouseId 仓库ID + * @param {number} options.storeId 货主ID + * @param {string} options.bizDate 数据日期 + * @param {string} options.timePoint 命中时间点 + * @param {Date} [options.now=new Date()] 触发时刻(渲染 {time} 用) + * @return {Promise} 文本通知目标快照(未配置通知时返回 null) + * @throws {Error} 投递失败且重推失败时抛出 + */ + async deliverByChannel({ plan, definition, fileResult, warehouseId, storeId, bizDate, timePoint, now = null }) { + const { ctx } = this; + const rawChannel = String(plan.channel || DEFAULT_CHANNEL).trim().toLowerCase() || DEFAULT_CHANNEL; + const fileUrl = String(fileResult.url || fileResult.fileKey || ''); + const reportDefinitionId = Number(plan.report_definition_id) || 0; + const idempotentKey = `report:${reportDefinitionId}:${bizDate}:${timePoint}`; + + // 渠道收敛:wecom/link 已弃用,历史残留数据按 inbox 兜底执行,避免历史计划投递卡死 + if (rawChannel !== 'inbox') { + ctx.logger.warn( + `[reportDelivery] 计划投递渠道 ${rawChannel} 已弃用,按 inbox 兜底投递(store_id=${storeId}, report_definition_id=${reportDefinitionId})` + ); + } + + // inbox:站内信群推送(唯一渠道) + const inboxGroupModel = ctx.model && ctx.model.InboxGroup; + if (!inboxGroupModel || typeof inboxGroupModel.findOne !== 'function') { + throw new Error('站内信群模型 InboxGroup 不可用'); + } + const groupRow = await inboxGroupModel.findOne({ + where: { + warehouse_id: warehouseId, + store_id: storeId, + group_type: 'store', + is_blocked: 0, + }, + attributes: [ 'group_id', 'group_name', 'ext_data' ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + if (!groupRow || !groupRow.group_id) { + throw new Error(`货主 ${storeId} 未配置站内信群,无法投递`); + } + + const warehouseNotify = ctx.service && ctx.service.systems && ctx.service.systems.warehouseNotify; + if (!warehouseNotify || typeof warehouseNotify.pushSystemMessage !== 'function') { + throw new Error('通知推送服务 warehouseNotify.pushSystemMessage 不可用'); + } + const pushResult = await warehouseNotify.pushSystemMessage({ + warehouseId, + storeId, + group: { + group_id: groupRow.group_id, + group_name: groupRow.group_name || '货主群', + ext_data: groupRow.ext_data || null, + }, + content: this.buildMessageContent(definition, bizDate, fileUrl), + extId: idempotentKey, + extData: { + report_definition_id: reportDefinitionId, + biz_date: bizDate, + time_point: timePoint, + file_url: fileUrl, + }, + }); + + // 推送失败判定(双保险):success=false;或消息记录回写 push_status=3(推送链路异常时兜底识别) + const messageId = (pushResult && Number(pushResult.messageId)) || 0; + let pushFailed = !pushResult || pushResult.success === false; + if (!pushFailed && messageId > 0) { + const InboxMessage = ctx.model && ctx.model.InboxMessage; + if (InboxMessage && typeof InboxMessage.findOne === 'function') { + try { + const row = await InboxMessage.findOne({ + where: { id: messageId }, + attributes: [ 'push_status' ], + raw: true, + }); + if (row && Number(row.push_status) === 3) { + pushFailed = true; + } + } catch (statusErr) { + ctx.logger.warn(`[reportDelivery] 读取消息推送状态失败: ${statusErr.message}`); + } + } + } + + if (pushFailed) { + const reason = (pushResult && (pushResult.reason || pushResult.error)) || '站内信推送失败'; + // 立即重推一次:复用 inbox.message.retry(重置 push_status=0 并异步重推;ext_id 幂等复用 + // 同一条消息记录,不重复写)。retry 自身抛错视为重推失败,向上抛出进入 failed 退避循环 + const retryService = ctx.service && ctx.service.inbox && ctx.service.inbox.message; + if (messageId > 0 && retryService && typeof retryService.retry === 'function') { + try { + await retryService.retry({ warehouseId, id: messageId }); + ctx.logger.warn(`[reportDelivery] 站内信推送失败已受理立即重推(message_id=${messageId}): ${reason}`); + } catch (retryErr) { + const retryReason = retryErr && retryErr.message ? retryErr.message : `${retryErr}`; + throw new Error(`站内信推送失败且重推失败: ${reason} / ${retryReason}`); + } + } else { + throw new Error(reason); + } + } + + // 文本通知(可选):与投递渠道独立;未配置时返回 null 保持既有行为不变 + return this.sendNotifyIfConfigured({ + plan, + definition, + fileResult, + warehouseId, + storeId, + bizDate, + timePoint, + now, + }); + } + + /** + * 按计划配置发送文本通知(模板渲染 + 定向群/成员推送)。 + * + * 规则: + * 1. 未配置模板或未选择任何群/成员时直接返回 null(保持既有投递行为不变); + * 2. 通知群(notify_group_ids 内部ID)→ 查 wms_inbox_group 取外部 group_id/group_name, + * 过滤 is_blocked=1、软删自动排除、仓库维度一致;逐群推送(群维度协议字段为单值); + * 3. 通知成员(notify_member_ids 外部IM用户ID)→ 推送体 user_id 直接传数组,不循环拆发; + * 选择群时成员数组随每个群推送携带,未选择群时单独做一次仅成员推送; + * 4. {url} 为空时由渲染器替换为兜底文案(生成中占位),不阻断投递; + * 5. 推送失败抛出异常交由上层走失败退避重试(消息落库按 ext_id 幂等防重)。 + * + * @param {Object} options 入参 + * @param {Object} options.plan 投递计划 + * @param {Object} options.definition 报表定义 + * @param {Object} options.fileResult 生成结果 + * @param {number} options.warehouseId 仓库ID + * @param {number} options.storeId 货主ID + * @param {string} options.bizDate 数据日期 + * @param {string} options.timePoint 命中时间点 + * @param {Date} [options.now] 触发时刻 + * @return {Promise} 快照 { group_ids, member_ids, notify_text },未配置返回 null + * @throws {Error} 目标不可达或推送失败时抛出 + */ + async sendNotifyIfConfigured({ plan, definition, fileResult, warehouseId, storeId, bizDate, timePoint, now = null }) { + const { ctx } = this; + const template = String((plan && plan.notify_template) || '').trim(); + if (!template) { + return null; + } + const groupIds = this.readJsonArray(plan && plan.notify_group_ids) || []; + const memberIds = this.readJsonArray(plan && plan.notify_member_ids) || []; + if (groupIds.length === 0 && memberIds.length === 0) { + return null; + } + + const reportDefinitionId = Number((plan && plan.report_definition_id) || 0); + const fileUrl = String(fileResult.url || fileResult.fileKey || ''); + const reportName = String((definition && definition.name) || '报表'); + const notifyText = renderNotifyTemplate(template, { + time: formatNotifyTime(now || new Date()), + url: fileUrl, + reportName, + bizDate, + }); + + // 目标解析:内部群ID → 外部群信息(is_blocked=0、软删排除、仓库维度一致) + let groups = []; + if (groupIds.length > 0) { + const inboxGroupModel = ctx.model && ctx.model.InboxGroup; + if (!inboxGroupModel || typeof inboxGroupModel.findAll !== 'function') { + throw new Error('站内信群模型 InboxGroup 不可用,无法发送文本通知'); + } + const { Op } = ctx.app.Sequelize; + const rows = await inboxGroupModel.findAll({ + where: { + id: { [Op.in]: groupIds }, + warehouse_id: Number(warehouseId) || 0, + is_blocked: 0, + }, + attributes: [ 'id', 'group_id', 'group_name', 'ext_data' ], + raw: true, + }); + groups = Array.isArray(rows) ? rows : []; + } + + if (groups.length === 0 && memberIds.length === 0) { + throw new Error('文本通知目标不可达(通知群不存在、已删除、被屏蔽或未选择群/成员)'); + } + + const warehouseNotify = ctx.service && ctx.service.systems && ctx.service.systems.warehouseNotify; + if (!warehouseNotify || typeof warehouseNotify.pushSystemMessage !== 'function') { + throw new Error('通知推送服务 warehouseNotify.pushSystemMessage 不可用'); + } + + const notifyExtId = `report:notify:${reportDefinitionId}:${bizDate}:${timePoint}`; + const commonOptions = { + warehouseId, + storeId, + userIds: memberIds, + content: notifyText, + extId: notifyExtId, + extData: { + report_definition_id: reportDefinitionId, + biz_date: bizDate, + time_point: timePoint, + file_url: fileUrl, + }, + }; + + const sentGroupIds = []; + const results = []; + // 群多选:群维度协议字段为单值(group_id/group_name),逐群推送;成员 user_id 数组随群推送整体透传 + for (const groupRow of groups) { + results.push(await warehouseNotify.pushSystemMessage({ + ...commonOptions, + group: { + group_id: groupRow.group_id, + group_name: groupRow.group_name || '货主群', + ext_data: groupRow.ext_data || null, + }, + })); + sentGroupIds.push(Number(groupRow.id)); + } + // 仅成员(未选择任何群):单独一次成员推送,user_id 直接传数组不循环拆发 + if (memberIds.length > 0 && results.length === 0) { + results.push(await warehouseNotify.pushSystemMessage(commonOptions)); + } + + const failed = results.filter(result => !result || result.success === false); + if (failed.length > 0) { + const reason = (failed[0] && (failed[0].reason || failed[0].error)) || '文本通知推送失败'; + throw new Error(`文本通知推送失败: ${reason}`); + } + + return { + group_ids: sentGroupIds, + member_ids: memberIds, + notify_text: notifyText, + }; + } + + /** + * 处理单个(计划 × 时间点)的幂等生成与投递。 + * @param {Object} options 入参 + * @param {Object} options.plan 投递计划 + * @param {number} options.storeId 货主ID + * @param {number} options.reportId 报表定义ID + * @param {string} options.timePoint 命中时间点 + * @param {string} options.bizDate 数据日期 + * @param {Date} options.now 触发时刻 + * @return {Promise} 处理结果标记(delivered/failed/skipped) + */ + async processOne({ plan, storeId, reportId, timePoint, bizDate, now }) { + const { ctx } = this; + const logModel = ctx.model && ctx.model.ReportDeliveryLog; + if (!logModel) { + throw new Error('投递记录模型 ReportDeliveryLog 不可用'); + } + + const uniqueWhere = { + store_id: storeId, + report_definition_id: reportId, + biz_date: bizDate, + time_point: timePoint, + }; + + let log = await logModel.findOne({ where: uniqueWhere }); + + if (log) { + const status = String(log.status || ''); + if (status !== DELIVERY_STATUS.FAILED) { + // 已投递/投递中/取消的记录直接跳过(幂等) + return 'skipped'; + } + const retryCount = Number(log.retry_count) || 0; + if (retryCount >= MAX_RETRY_COUNT) { + return 'skipped'; + } + const nextRetryAt = log.next_retry_at ? new Date(log.next_retry_at) : null; + if (nextRetryAt && nextRetryAt.getTime() > now.getTime()) { + // 退避未到期 + return 'skipped'; + } + } else { + try { + [ log ] = await logModel.findOrCreate({ + where: uniqueWhere, + defaults: { + ...uniqueWhere, + warehouse_id: 0, + report_name: '', + status: DELIVERY_STATUS.PENDING, + channel: String(plan.channel || DEFAULT_CHANNEL), + }, + }); + } catch (error) { + // 并发撞唯一键时降级为查询 + log = await logModel.findOne({ where: uniqueWhere }); + } + if (log && String(log.status || '') !== DELIVERY_STATUS.PENDING && String(log.status || '') !== DELIVERY_STATUS.FAILED) { + return 'skipped'; + } + } + + if (!log) { + return 'skipped'; + } + + const warehouseId = await this.resolveStoreWarehouse(storeId); + if (warehouseId <= 0) { + await this.markFailed(log, `货主 ${storeId} 未找到有效合约仓库`); + return 'failed'; + } + + // 读取报表定义一次(报表名称快照 + 投递通知文案共用,生成步骤内部会再按 id 读取) + const definition = await ctx.service.systems.report.getDefinition(reportId); + await this.markExporting(log, warehouseId, definition.name); + + // 生成上传(失败进入退避重试) + let fileResult; + try { + fileResult = await ctx.service.systems.report.generate({ + reportId, + storeId, + warehouseId, + params: { + bizDate, + timePoint, + }, + }); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + this.ctx.logger.error(`[reportDelivery] 报表生成失败 ${reportId}/${storeId}/${bizDate}/${timePoint}: ${errorMessage}`); + await this.markFailed(log, `报表生成失败: ${errorMessage}`); + return 'failed'; + } + + // 投递(失败进入退避重试) + try { + const notifyTargets = await this.deliverByChannel({ + plan, + definition, + fileResult, + warehouseId, + storeId, + bizDate, + timePoint, + now, + }); + await this.markDelivered(log, fileResult, notifyTargets); + return 'delivered'; + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + this.ctx.logger.error(`[reportDelivery] 报表投递失败 ${reportId}/${storeId}/${bizDate}/${timePoint}: ${errorMessage}`); + await this.markFailed(log, `报表投递失败: ${errorMessage}`); + return 'failed'; + } + } + + /** + * 计划时间点解析:兼容数组与 JSON 字符串(防止手工数据写成字符串)。 + * @param {Array|string} value 原始值 + * @return {Array} 时间点数组 + */ + parseScheduleTimes(value) { + if (Array.isArray(value)) { + return value; + } + if (typeof value === 'string' && value.trim()) { + try { + const parsed = JSON.parse(value); + return Array.isArray(parsed) ? parsed : []; + } catch (error) { + return []; + } + } + return []; + } + + /** + * 分钟级投递调度入口(schedule 调用)。 + * + * 流程: + * 1. 兜底回退:exporting 超过 EXPORTING_STALE_MS 的记录视为进程中断,置为 failed + * 并重置 retry_count=0、next_retry_at=now,交由重试扫描立即重排(防卡死); + * 2. 计划扫描:对每个命中时间点按「时间点归属自然日 - 1」计算 biz_date + * (跨零点补投落漏跑日),幂等生成并投递; + * 3. 重试扫描:status=failed 且 retry_count<3 且 next_retry_at<=now 的记录直接重试, + * 不依赖计划时间点再次命中。 + * @return {Promise} 本轮扫描汇总 { scanned, delivered, failed, skipped } + */ + async dispatch() { + const { ctx, app } = this; + const planModel = ctx.model && ctx.model.ReportDeliveryPlan; + const logModel = ctx.model && ctx.model.ReportDeliveryLog; + if (!planModel || !logModel) { + return { scanned: 0, delivered: 0, failed: 0, skipped: 0 }; + } + + const { Op } = app.Sequelize; + const now = new Date(); + + // 兜底:导出中超过 30 分钟视为进程中断,置为 failed 并重置退避参数(retry_count=0、 + // next_retry_at=now)交给重试链路立即重排。不能回退为 pending:既有 pending 会被 + // processOne 幂等跳过,且重试扫描只捡 failed,会导致该记录永久卡死(缺陷 D1)。 + await logModel.update({ + status: DELIVERY_STATUS.FAILED, + retry_count: 0, + next_retry_at: now, + error_message: '报表导出超时中断,已自动重排投递', + updated_at: now, + }, { + where: { + status: DELIVERY_STATUS.EXPORTING, + updated_at: { + [Op.lt]: new Date(now.getTime() - EXPORTING_STALE_MS), + }, + }, + }); + + const plans = await planModel.findAll({ + where: { enabled: 1 }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + const summary = { + scanned: Array.isArray(plans) ? plans.length : 0, + delivered: 0, + failed: 0, + skipped: 0, + }; + + for (const plan of plans || []) { + const scheduleTimes = this.parseScheduleTimes(plan.schedule_times); + if (scheduleTimes.length === 0) { + continue; + } + const graceMinutes = Number(plan.late_grace_minutes ?? DEFAULT_GRACE_MINUTES); + const hits = this.hitTimePoints(scheduleTimes, now, graceMinutes); + if (hits.length === 0) { + continue; + } + + const storeId = Number(plan.store_id) || 0; + const reportId = Number(plan.report_definition_id) || 0; + if (storeId <= 0 || reportId <= 0) { + ctx.logger.warn(`[reportDelivery] 跳过无效计划 id=${plan.id}(store_id=${storeId}, report_definition_id=${reportId})`); + continue; + } + + for (const timePoint of hits) { + try { + // 按命中时间点归属自然日计算 biz_date:跨零点补投落在漏跑日(T-2), + // 与次日正常投递的幂等键互不碰撞(缺陷 D2) + const hitBizDate = this.bizDateOfTimePoint(now, timePoint); + const mark = await this.processOne({ plan, storeId, reportId, timePoint, bizDate: hitBizDate, now }); + if (mark === 'delivered') { + summary.delivered += 1; + } else if (mark === 'failed') { + summary.failed += 1; + } else { + summary.skipped += 1; + } + } catch (error) { + summary.failed += 1; + const errorMessage = error && error.message ? error.message : `${error}`; + ctx.logger.error(`[reportDelivery] 处理异常 ${reportId}/${storeId}/${timePoint}: ${errorMessage}`); + } + } + } + + // 重试扫描:status=failed 且 retry_count<3 且 next_retry_at<=now 的记录 + // (不依赖计划时间点再次命中,退避到期即重试) + const failedLogs = await logModel.findAll({ + where: { + status: DELIVERY_STATUS.FAILED, + retry_count: { [Op.lt]: MAX_RETRY_COUNT }, + next_retry_at: { [Op.lte]: now }, + }, + order: [[ 'id', 'ASC' ]], + limit: 200, + raw: true, + }); + + const retryPlans = new Map(); + for (const failedLog of failedLogs || []) { + const storeId = Number(failedLog.store_id) || 0; + const reportId = Number(failedLog.report_definition_id) || 0; + const bizDate = String(failedLog.biz_date || ''); + const timePoint = String(failedLog.time_point || ''); + if (storeId <= 0 || reportId <= 0 || !bizDate || !timePoint) { + continue; + } + const planKey = `${storeId}:${reportId}`; + let plan = retryPlans.get(planKey); + if (plan === undefined) { + plan = await planModel.findOne({ + where: { + store_id: storeId, + report_definition_id: reportId, + enabled: 1, + }, + raw: true, + }); + retryPlans.set(planKey, plan || null); + } + if (!plan) { + // 计划已停用/删除:不再重试 + continue; + } + try { + const mark = await this.processOne({ plan, storeId, reportId, timePoint, bizDate, now }); + if (mark === 'delivered') { + summary.delivered += 1; + } else if (mark === 'failed') { + summary.failed += 1; + } else { + summary.skipped += 1; + } + } catch (error) { + summary.failed += 1; + const errorMessage = error && error.message ? error.message : `${error}`; + ctx.logger.error(`[reportDelivery] 重试处理异常 ${reportId}/${storeId}/${timePoint}: ${errorMessage}`); + } + } + + return summary; + } +} + +module.exports = ReportDeliveryService; diff --git a/app/service/systems/warehouseNotify.js b/app/service/systems/warehouseNotify.js index ed22760..81d794b 100644 --- a/app/service/systems/warehouseNotify.js +++ b/app/service/systems/warehouseNotify.js @@ -224,26 +224,55 @@ class WarehouseNotifyService extends Service { } /** - * 向指定群推送系统级业务通知(复用 notify.reply,type=system)。 + * 向指定群(可选)与成员(可选)推送系统级业务通知(复用 notify.reply,type=system)。 * 对方接口只处理 content 内容,推送体仅保留协议必需字段: - * type / content / ext_id / group_id / group_name / timestamp。 + * type / content / ext_id / group_id / group_name / user_id / timestamp。 * 推送前写入 wms_inbox_message(direction=outbound,source_type=system), * 推送后按结果回写 push_status(2=已送达 / 3=失败)与 push_response。 + * + * 向后兼容:不传 userIds 且传入 group 时,行为与旧版本完全一致 + * (校验、幂等 ext_id、落库字段、推送体均不变)。 + * * @param {Object} options 推送参数。 * @param {number} options.warehouseId 仓库 ID。 * @param {number} [options.storeId] 货主 ID。 - * @param {Object} options.group 目标群 { group_id, group_name, ext_data }。 + * @param {Object|null} [options.group=null] 目标群 { group_id, group_name, ext_data } + * (新增允许为 null:仅成员推送场景)。 + * @param {Array|null} [options.userIds=null] 目标成员外部 IM 用户 ID 数组 + * (新增,目标侧协议支持 user_id 数组:整体透传不循环拆发)。 * @param {string} [options.content=''] 通知正文。 * @param {number|string} [options.extId] 业务单号(用于幂等 ext_id)。 * @param {Object} [options.extData] 群扩展数据(渠道信息,落库与推送透传)。 * @return {Promise} 推送结果(含 messageId)。 */ - async pushSystemMessage({ warehouseId, storeId = null, group, content = '', extId = null, extData = null } = {}) { + async pushSystemMessage({ + warehouseId, + storeId = null, + group = null, + userIds = null, + content = '', + extId = null, + extData = null, + } = {}) { const { ctx } = this; const groupId = String((group && group.group_id) || '').trim(); const groupName = String((group && group.group_name) || '').trim(); + // 成员ID规范化:仅接受字符串数组,去重并过滤空值(向后兼容:旧调用不传时为空数组) + const normalizedUserIds = Array.isArray(userIds) + ? [ ...new Set(userIds.map(item => String(item || '').trim()).filter(Boolean)) ] + : []; - if (!groupId || !groupName) { + // 向后兼容:无群且无成员时保持旧版 skip 语义(原判断 !groupId || !groupName) + if (!groupId && normalizedUserIds.length === 0) { + return { + success: false, + skipped: true, + reason: '目标群缺少 group_id 或 group_name', + warehouseId, + }; + } + // 指定了群但缺群名:与旧版一致返回 skip(群维度协议要求 group_name) + if (groupId && !groupName) { return { success: false, skipped: true, @@ -252,11 +281,13 @@ class WarehouseNotifyService extends Service { }; } - // 幂等 ext_id:业务单号 + 事件 + 群维度,网络重推时复用同一条消息记录;超长时降级哈希兜底 + // 幂等 ext_id:业务单号 + 事件 + 目标维度(群优先、仅成员时按成员集合), + // 网络重推时复用同一条消息记录;超长时降级哈希兜底 const sourceExtId = String(extId || `sys:notice:${Date.now()}:${Math.random().toString(36).slice(2, 8)}`); - let uniqueExtId = `sys:notice:${sourceExtId}:${groupId}`; + const memberKey = normalizedUserIds.length > 0 ? `members:${normalizedUserIds.join(',')}` : ''; + const targetKey = groupId || memberKey; + let uniqueExtId = `sys:notice:${sourceExtId}:${targetKey}`; if (uniqueExtId.length > 128) { - const crypto = require('crypto'); const digest = crypto.createHash('md5') .update(uniqueExtId) .digest('hex') @@ -287,9 +318,11 @@ class WarehouseNotifyService extends Service { source_type: 'system', source_extra: 'notice', target_type: 'api', - group_id: groupId, + group_id: groupId || null, + // 成员数组仅随推送体 user_id 透传并记录在 report_delivery_log.notify_targets 快照中, + // 消息表 user_id 列(STRING(100))不承载数组,避免超长截断 user_id: null, - group_name: groupName, + group_name: groupName || null, user_name: null, content: normalizedContent, ext_data: extData || null, @@ -304,18 +337,26 @@ class WarehouseNotifyService extends Service { } } + // 推送体:群字段仅指定群时携带;成员 user_id 直接传数组(目标侧协议支持),不循环拆发 + const pushData = { + type: 'system', + content: normalizedContent, + ext_id: sourceExtId, + ext_data: extData || null, + timestamp: Math.floor(Date.now() / 1000), + }; + if (groupId) { + pushData.group_id = groupId; + pushData.group_name = groupName; + } + if (normalizedUserIds.length > 0) { + pushData.user_id = normalizedUserIds; + } + const result = await this.push({ warehouseId, method: 'notify.reply', - data: { - type: 'system', - content: normalizedContent, - ext_id: sourceExtId, - ext_data: extData || null, - group_id: groupId, - group_name: groupName, - timestamp: Math.floor(Date.now() / 1000), - }, + data: pushData, }); // 回写推送状态(失败仅记日志,不影响业务) diff --git a/database/migrations/20260829120000-create-wms-report-delivery-tables.js b/database/migrations/20260829120000-create-wms-report-delivery-tables.js new file mode 100644 index 0000000..5ff551a --- /dev/null +++ b/database/migrations/20260829120000-create-wms-report-delivery-tables.js @@ -0,0 +1,321 @@ +'use strict'; + +/** + * 创建报表投递三表:报表模板定义 / 货主投递计划 / 投递记录。 + * + * 背景:货主侧 7 日出入库报表采用「配置驱动 + 定时投递」方案: + * 报表模板可配置上新(免发版),每个货主可配置每日多个投递时间点, + * 由分钟级扫描调度命中后生成报表并按渠道投递。 + * + * 三表职责: + * - wms_report_definition:报表模板定义(code/name/scope + output/source/sheet 三段 JSON 配置) + * - wms_report_delivery_plan:货主每日投递计划(schedule_times JSON 时间点数组) + * - wms_report_delivery_log:投递记录(pending→exporting→delivered/failed/cancelled 状态机 + 退避重试) + * + * 约定: + * - 逻辑关联、无物理外键(与项目现状一致) + * - 唯一索引按项目惯例含 deleted_at,避免软删后重建撞唯一键 + * - 幂等键 uk_store_report_biz_time 保证同一货主同一报表同一数据日期同一时间点不重复投递 + */ + +const TABLE_DEFINITION = 'wms_report_definition'; +const TABLE_PLAN = 'wms_report_delivery_plan'; +const TABLE_LOG = 'wms_report_delivery_log'; + +module.exports = { + async up(queryInterface, Sequelize) { + const { BIGINT, INTEGER, STRING, TINYINT, DATE, DATEONLY, ENUM } = Sequelize; + const tables = await queryInterface.showAllTables(); + const tableNames = tables.map(t => (typeof t === 'string' ? t : t.tableName)); + + if (!tableNames.includes(TABLE_DEFINITION)) { + await queryInterface.createTable(TABLE_DEFINITION, { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + code: { + type: STRING(100), + allowNull: false, + comment: '报表编码,全局唯一(如 week_inout_7d)', + }, + name: { + type: STRING(100), + allowNull: false, + comment: '报表名称', + }, + scope: { + type: ENUM('warehouse', 'store', 'open'), + allowNull: false, + defaultValue: 'warehouse', + comment: '适用维度:warehouse=仓库 store=货主 open=通用', + }, + description: { + type: STRING(500), + allowNull: true, + comment: '报表描述', + }, + output_config: { + type: Sequelize.JSON, + allowNull: true, + comment: '输出配置(文件名/目录等)', + }, + source_config: { + type: Sequelize.JSON, + allowNull: true, + comment: '数据源配置(查询器 key + 窗口参数)', + }, + sheet_config: { + type: Sequelize.JSON, + allowNull: true, + comment: '工作表配置(列定义/合并/样式/行过滤/列级 format)', + }, + is_enabled: { + type: TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '是否启用:0=停用 1=启用', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + created_at: { + type: DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + comment: '报表模板定义表', + engine: 'InnoDB', + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + }); + + await queryInterface.addIndex(TABLE_DEFINITION, [ 'code', 'deleted_at' ], { + unique: true, + name: 'uk_code', + }); + await queryInterface.addIndex(TABLE_DEFINITION, [ 'deleted_at' ], { + name: 'idx_deleted_at', + }); + } + + if (!tableNames.includes(TABLE_PLAN)) { + await queryInterface.createTable(TABLE_PLAN, { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '货主ID(wms_store.id)', + }, + report_code: { + type: STRING(100), + allowNull: false, + comment: '报表编码(wms_report_definition.code)', + }, + schedule_times: { + type: Sequelize.JSON, + allowNull: false, + comment: '每日投递时间点数组,如 ["08:30","17:00"](HH:mm)', + }, + channel: { + type: STRING(20), + allowNull: false, + defaultValue: 'wecom', + comment: '投递渠道:wecom=企业微信 inbox=站内信群 link=链接', + }, + enabled: { + type: TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '是否启用:0=停用 1=启用', + }, + late_grace_minutes: { + type: INTEGER(11), + allowNull: false, + defaultValue: 60, + comment: '补投宽限分钟:重启/漏跑后在该窗口内补投,超窗作废', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + created_at: { + type: DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + comment: '货主报表投递计划表', + engine: 'InnoDB', + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + }); + + await queryInterface.addIndex(TABLE_PLAN, [ 'store_id', 'report_code', 'deleted_at' ], { + unique: true, + name: 'uk_store_report_code', + }); + await queryInterface.addIndex(TABLE_PLAN, [ 'enabled', 'deleted_at' ], { + name: 'idx_enabled_deleted', + }); + await queryInterface.addIndex(TABLE_PLAN, [ 'deleted_at' ], { + name: 'idx_deleted_at', + }); + } + + if (!tableNames.includes(TABLE_LOG)) { + await queryInterface.createTable(TABLE_LOG, { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '仓库ID(生成报表时注入的仓库维度)', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '货主ID(wms_store.id)', + }, + report_code: { + type: STRING(100), + allowNull: false, + comment: '报表编码(wms_report_definition.code)', + }, + biz_date: { + type: DATEONLY, + allowNull: false, + comment: '数据日期(T-1 自然日)', + }, + time_point: { + type: STRING(5), + allowNull: false, + comment: '命中的投递时间点(HH:mm)', + }, + status: { + type: STRING(20), + allowNull: false, + defaultValue: 'pending', + comment: '状态:pending/exporting/delivered/failed/cancelled', + }, + channel: { + type: STRING(20), + allowNull: false, + defaultValue: 'wecom', + comment: '投递渠道快照:wecom=企业微信 inbox=站内信群 link=链接', + }, + file_url: { + type: STRING(500), + allowNull: true, + comment: '报表文件下载链接(COS 带有效期)', + }, + retry_count: { + type: INTEGER(3), + allowNull: false, + defaultValue: 0, + comment: '重试次数', + }, + next_retry_at: { + type: DATE, + allowNull: true, + comment: '下次可投递时间(失败退避)', + }, + error_message: { + type: STRING(500), + allowNull: true, + comment: '最近一次失败原因', + }, + delivered_at: { + type: DATE, + allowNull: true, + comment: '投递成功时间', + }, + created_at: { + type: DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + comment: '报表投递记录表', + engine: 'InnoDB', + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + }); + + await queryInterface.addIndex(TABLE_LOG, [ 'store_id', 'report_code', 'biz_date', 'time_point', 'deleted_at' ], { + unique: true, + name: 'uk_store_report_biz_time', + }); + await queryInterface.addIndex(TABLE_LOG, [ 'status', 'id' ], { + name: 'idx_status_id', + }); + await queryInterface.addIndex(TABLE_LOG, [ 'status', 'updated_at' ], { + name: 'idx_status_updated_at', + }); + await queryInterface.addIndex(TABLE_LOG, [ 'deleted_at' ], { + name: 'idx_deleted_at', + }); + } + }, + + async down(queryInterface) { + await queryInterface.dropTable(TABLE_LOG); + await queryInterface.dropTable(TABLE_PLAN); + await queryInterface.dropTable(TABLE_DEFINITION); + }, +}; diff --git a/database/migrations/20260829160000-add-notify-fields-to-wms-report-delivery.js b/database/migrations/20260829160000-add-notify-fields-to-wms-report-delivery.js new file mode 100644 index 0000000..d167664 --- /dev/null +++ b/database/migrations/20260829160000-add-notify-fields-to-wms-report-delivery.js @@ -0,0 +1,77 @@ +'use strict'; + +const TABLE_PLAN = 'wms_report_delivery_plan'; +const TABLE_LOG = 'wms_report_delivery_log'; + +/** + * 报表投递通知能力增强: + * - wms_report_delivery_plan 新增 notify_template(文本通知模板)、 + * notify_group_ids(通知群ID数组)、notify_member_ids(通知成员ID数组) + * - wms_report_delivery_log 新增 notify_targets(本次实际投递的群/成员快照,审计回放) + * + * 全部字段可空,不影响存量投递计划与投递记录。 + */ +module.exports = { + /** + * 执行迁移:依次新增通知相关字段(幂等:已存在则跳过)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + up: async (queryInterface, Sequelize) => { + const planColumns = await queryInterface.describeTable(TABLE_PLAN); + if (!planColumns.notify_template) { + await queryInterface.addColumn(TABLE_PLAN, 'notify_template', { + type: Sequelize.STRING(500), + allowNull: true, + comment: '文本通知模板,支持 {time}/{url}/{report_name}/{biz_date} 标签', + }); + } + if (!planColumns.notify_group_ids) { + await queryInterface.addColumn(TABLE_PLAN, 'notify_group_ids', { + type: Sequelize.JSON, + allowNull: true, + comment: '通知群ID数组(wms_inbox_group.id,多选;空=不指定群)', + }); + } + if (!planColumns.notify_member_ids) { + await queryInterface.addColumn(TABLE_PLAN, 'notify_member_ids', { + type: Sequelize.JSON, + allowNull: true, + comment: '通知成员ID数组(外部IM用户ID,多选;目标侧支持数组)', + }); + } + + const logColumns = await queryInterface.describeTable(TABLE_LOG); + if (!logColumns.notify_targets) { + await queryInterface.addColumn(TABLE_LOG, 'notify_targets', { + type: Sequelize.JSON, + allowNull: true, + comment: '投递目标快照:{group_ids:[],member_ids:[]}(本次实际发送的群/成员,审计回放)', + }); + } + }, + + /** + * 回滚迁移:按新增顺序的逆序删除字段(幂等:不存在则跳过)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} 无返回值 + */ + down: async queryInterface => { + const planColumns = await queryInterface.describeTable(TABLE_PLAN); + if (planColumns.notify_member_ids) { + await queryInterface.removeColumn(TABLE_PLAN, 'notify_member_ids'); + } + if (planColumns.notify_group_ids) { + await queryInterface.removeColumn(TABLE_PLAN, 'notify_group_ids'); + } + if (planColumns.notify_template) { + await queryInterface.removeColumn(TABLE_PLAN, 'notify_template'); + } + + const logColumns = await queryInterface.describeTable(TABLE_LOG); + if (logColumns.notify_targets) { + await queryInterface.removeColumn(TABLE_LOG, 'notify_targets'); + } + }, +}; diff --git a/database/migrations/20260829170000-normalize-report-channel-to-inbox.js b/database/migrations/20260829170000-normalize-report-channel-to-inbox.js new file mode 100644 index 0000000..4390062 --- /dev/null +++ b/database/migrations/20260829170000-normalize-report-channel-to-inbox.js @@ -0,0 +1,55 @@ +'use strict'; + +const TABLE_PLAN = 'wms_report_delivery_plan'; +const TABLE_LOG = 'wms_report_delivery_log'; + +/** + * 报表投递渠道收敛为 inbox(wecom/link 已弃用)。 + * + * - wms_report_delivery_plan.channel:默认值 wecom → inbox,comment 收敛 + * - wms_report_delivery_log.channel:默认值 wecom → inbox,comment 收敛 + * - 存量数据归一化:channel IN ('wecom','link') 的行统一更新为 'inbox' + * + * down 仅回退列默认值与 comment;数据 UPDATE 不回退(历史行无法还原原渠道)。 + */ +module.exports = { + async up(queryInterface, Sequelize) { + // 1. 计划表:默认值 + comment 收敛 + await queryInterface.changeColumn(TABLE_PLAN, 'channel', { + type: Sequelize.STRING(20), + allowNull: false, + defaultValue: 'inbox', + comment: '投递渠道:inbox=站内信群(wecom/link 已弃用)', + }); + await queryInterface.sequelize.query( + `UPDATE ${TABLE_PLAN} SET channel = 'inbox' WHERE channel IN ('wecom', 'link')` + ); + + // 2. 记录表:默认值 + comment 收敛 + await queryInterface.changeColumn(TABLE_LOG, 'channel', { + type: Sequelize.STRING(20), + allowNull: false, + defaultValue: 'inbox', + comment: '投递渠道快照:inbox=站内信群(wecom/link 已弃用)', + }); + await queryInterface.sequelize.query( + `UPDATE ${TABLE_LOG} SET channel = 'inbox' WHERE channel IN ('wecom', 'link')` + ); + }, + + async down(queryInterface, Sequelize) { + // 仅回退默认值与 comment;存量数据不回退(已归一化为 inbox 的行无法还原原渠道) + await queryInterface.changeColumn(TABLE_PLAN, 'channel', { + type: Sequelize.STRING(20), + allowNull: false, + defaultValue: 'wecom', + comment: '投递渠道:wecom=企业微信 inbox=站内信群 link=链接', + }); + await queryInterface.changeColumn(TABLE_LOG, 'channel', { + type: Sequelize.STRING(20), + allowNull: false, + defaultValue: 'wecom', + comment: '投递渠道快照:wecom=企业微信 inbox=站内信群 link=链接', + }); + }, +}; diff --git a/database/migrations/20260830120000-restructure-report-definition-by-id.js b/database/migrations/20260830120000-restructure-report-definition-by-id.js new file mode 100644 index 0000000..3ca6f12 --- /dev/null +++ b/database/migrations/20260830120000-restructure-report-definition-by-id.js @@ -0,0 +1,166 @@ +'use strict'; + +/** + * 报表定义模型重构:code 关联 → 主键 id 关联。 + * + * 背景:报表定义模型已重构(definition 以主键 id 唯一,删除 code/scope/description + * 及 output_config/source_config/sheet_config 三个 JSON 配置列,新增 type/file_name/fields; + * plan/log 改用 report_definition_id 关联定义),本迁移同步数据库结构。 + * + * 三步改造: + * 1. wms_report_definition:删 uk_code,加 type/file_name/fields 三列,回填 id=1 + * 存量数据,物理删除已软删的 e2e 演示行(id=2),删除 code/scope/description + * 及三个 JSON 配置列,最后去掉 type 默认值(新配置必须显式声明类型); + * 2. wms_report_delivery_plan:加 report_definition_id 并回填,唯一键 + * uk_store_report_code → uk_store_report_definition; + * 3. wms_report_delivery_log:加 report_definition_id/report_name 并回填, + * 唯一键 uk_store_report_biz_time 改为基于 report_definition_id。 + * + * 执行顺序说明(关键约束):plan/log 的回填依赖 definition.code 关联 + * (JOIN ... ON d.code = p.report_code),因此 definition 旧列(含 code)的删除 + * 被延后到 plan/log 回填核验通过之后执行,最终表结构与规格逐项一致。 + * + * down 不可逆:旧列及其数据已被物理删除,无法从库内还原,故 down 直接抛错, + * 如需回退请从备份恢复。 + */ + +const TABLE_DEFINITION = 'wms_report_definition'; +const TABLE_PLAN = 'wms_report_delivery_plan'; +const TABLE_LOG = 'wms_report_delivery_log'; + +// id=1 存量报表勾选字段 key 数组(与代码侧 stockFlow 查询器字段规格一致) +const STOCK_FLOW_FIELDS = [ + 'item_code', 'item_name', 'barcode', 'daily', 'ck_total', 'rk_total', 'available', + 'total', 'pending', 'locked', 'ck_avg', 'rk_avg', 'stock_days', 'suggest', 'warn', +]; + +module.exports = { + async up(queryInterface) { + const { sequelize } = queryInterface; + const q = sql => sequelize.query(sql); + const log = msg => console.log(`[report-definition-by-id] ${msg}`); + + /** + * 执行计数校验 SQL,返回行数;不满足期望时抛错,阻止后续破坏性 DDL。 + * @param {string} sql 返回 cnt 列的 SELECT COUNT 语句。 + * @param {number} expected 期望的行数。 + * @param {string} message 校验失败时的错误描述。 + */ + const assertCount = async (sql, expected, message) => { + const [ rows ] = await q(sql); + const count = Number(rows[0].cnt); + console.log(`[report-definition-by-id] 核验:${message}(实际 ${count},期望 ${expected})`); + if (count !== expected) { + throw new Error(`[report-definition-by-id] ${message} 核验失败:实际 ${count},期望 ${expected}`); + } + }; + + // ============ Step 1(前半):wms_report_definition 结构准备 ============ + // 1.1 删除 uk_code 唯一索引(code 即将废弃) + await queryInterface.removeIndex(TABLE_DEFINITION, 'uk_code'); + log('definition:已删除唯一索引 uk_code'); + + // 1.2 新增 type / file_name / fields 三列(按规格顺序放在 name 之后) + await q(`ALTER TABLE \`${TABLE_DEFINITION}\` + ADD COLUMN \`type\` VARCHAR(50) NOT NULL DEFAULT 'stockFlow' COMMENT '报表类型(内置查询器注册 key)' AFTER \`name\`, + ADD COLUMN \`file_name\` VARCHAR(200) NOT NULL DEFAULT '' COMMENT '导出文件名模板(支持 {date} 占位)' AFTER \`type\`, + ADD COLUMN \`fields\` JSON NULL COMMENT '勾选字段 key 数组' AFTER \`file_name\``); + log('definition:已新增 type/file_name/fields 三列'); + + // 1.3 回填 id=1 存量数据(7日出入库报表) + await q(`UPDATE \`${TABLE_DEFINITION}\` SET + \`type\` = 'stockFlow', + \`file_name\` = '7日出入库_{date}', + \`fields\` = JSON_ARRAY(${STOCK_FLOW_FIELDS.map(f => `'${f}'`).join(', ')}) + WHERE \`id\` = 1`); + log('definition:已回填 id=1 的 type/file_name/fields'); + + // 1.4 物理删除已软删的 e2e 演示行(id=2) + await q(`DELETE FROM \`${TABLE_DEFINITION}\` + WHERE \`id\` = 2 AND \`deleted_at\` IS NOT NULL AND \`code\` = 'e2e_demo_report'`); + log('definition:已删除软删状态下的 e2e 演示行(id=2)'); + + // ============ Step 2:wms_report_delivery_plan 改 id 关联 ============ + // 2.1 新增 report_definition_id(按规格顺序放在 store_id 之后) + await q(`ALTER TABLE \`${TABLE_PLAN}\` + ADD COLUMN \`report_definition_id\` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0 + COMMENT '报表定义ID(wms_report_definition.id)' AFTER \`store_id\``); + log('plan:已新增 report_definition_id'); + + // 2.2 按 code 关联回填(必须在 definition.code 删除前完成) + await q(`UPDATE \`${TABLE_PLAN}\` p + JOIN \`${TABLE_DEFINITION}\` d ON d.\`code\` = p.\`report_code\` + SET p.\`report_definition_id\` = d.\`id\``); + log('plan:已按 code 关联回填 report_definition_id'); + + // 2.3 核验:report_definition_id=0 的行数必须为 0,否则抛出异常 + await assertCount( + `SELECT COUNT(*) AS cnt FROM \`${TABLE_PLAN}\` WHERE \`report_definition_id\` = 0`, + 0, + 'plan 回填后 report_definition_id=0 的行数必须为 0' + ); + + // 2.4 删除旧唯一键与 report_code,建立新唯一键 + await queryInterface.removeIndex(TABLE_PLAN, 'uk_store_report_code'); + await q(`ALTER TABLE \`${TABLE_PLAN}\` DROP COLUMN \`report_code\``); + await q(`ALTER TABLE \`${TABLE_PLAN}\` + ADD UNIQUE INDEX \`uk_store_report_definition\` (\`store_id\`, \`report_definition_id\`, \`deleted_at\`)`); + log('plan:已切换唯一键 uk_store_report_definition 并删除 report_code'); + + // ============ Step 3:wms_report_delivery_log 改 id 关联 ============ + // 3.1 新增 report_definition_id / report_name(按规格顺序放在 store_id 之后) + await q(`ALTER TABLE \`${TABLE_LOG}\` + ADD COLUMN \`report_definition_id\` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0 + COMMENT '报表定义ID(wms_report_definition.id)' AFTER \`store_id\`, + ADD COLUMN \`report_name\` VARCHAR(100) NULL + COMMENT '报表名称快照(投递时定义 name)' AFTER \`report_definition_id\``); + log('log:已新增 report_definition_id/report_name'); + + // 3.2 按 code 关联回填(必须在 definition.code 删除前完成) + await q(`UPDATE \`${TABLE_LOG}\` l + JOIN \`${TABLE_DEFINITION}\` d ON d.\`code\` = l.\`report_code\` + SET l.\`report_definition_id\` = d.\`id\`, l.\`report_name\` = d.\`name\``); + log('log:已按 code 关联回填 report_definition_id/report_name'); + + // 3.3 核验:report_definition_id=0 的行数必须为 0,否则抛出异常 + await assertCount( + `SELECT COUNT(*) AS cnt FROM \`${TABLE_LOG}\` WHERE \`report_definition_id\` = 0`, + 0, + 'log 回填后 report_definition_id=0 的行数必须为 0' + ); + + // 3.4 删除旧唯一键与 report_code,建立新唯一键 + await queryInterface.removeIndex(TABLE_LOG, 'uk_store_report_biz_time'); + await q(`ALTER TABLE \`${TABLE_LOG}\` DROP COLUMN \`report_code\``); + await q(`ALTER TABLE \`${TABLE_LOG}\` + ADD UNIQUE INDEX \`uk_store_report_biz_time\` + (\`store_id\`, \`report_definition_id\`, \`biz_date\`, \`time_point\`, \`deleted_at\`)`); + log('log:已切换唯一键 uk_store_report_biz_time 并删除 report_code'); + + // ============ Step 1(后半):删除 definition 旧列并收尾 ============ + // plan/log 回填已核验通过,此时删除 definition 旧列(含 code)是安全的 + await q(`ALTER TABLE \`${TABLE_DEFINITION}\` + DROP COLUMN \`code\`, + DROP COLUMN \`scope\`, + DROP COLUMN \`description\`, + DROP COLUMN \`output_config\`, + DROP COLUMN \`source_config\`, + DROP COLUMN \`sheet_config\``); + log('definition:已删除 code/scope/description 及三个 JSON 配置列'); + + // 去掉 type 默认值:新配置行必须显式声明报表类型 + await q(`ALTER TABLE \`${TABLE_DEFINITION}\` ALTER COLUMN \`type\` DROP DEFAULT`); + log('definition:已去掉 type 默认值'); + + log('全部完成'); + }, + + async down() { + // 本迁移破坏性删除旧列数据(code/scope/description 及三个 JSON 配置列、 + // e2e 演示行、plan/log 的 report_code 列),库内已无原始数据可还原,不可自动回滚。 + throw new Error( + '[report-definition-by-id] 本迁移不可逆:definition 旧列及其数据、e2e 演示行、plan/log 的 report_code 列已被删除,' + + '库内无法还原原始数据。如需回退,请从备份恢复数据库或手工重建相关列与数据。' + ); + }, +}; diff --git a/database/migrations/20260830130000-add-name-to-wms-report-delivery-plan.js b/database/migrations/20260830130000-add-name-to-wms-report-delivery-plan.js new file mode 100644 index 0000000..e928331 --- /dev/null +++ b/database/migrations/20260830130000-add-name-to-wms-report-delivery-plan.js @@ -0,0 +1,56 @@ +'use strict'; + +const TABLE_PLAN = 'wms_report_delivery_plan'; + +/** + * 为报表投递计划表新增计划名称字段 name。 + * + * 背景:报表投递计划在管理端列表/详情展示时需要展示计划名称(前端展示用), + * 因此为 wms_report_delivery_plan 新增 name 列,按规格位于 report_definition_id 之后。 + * + * 全部存量计划允许 name 为空(可空列),不影响既有投递计划与投递逻辑。 + */ +module.exports = { + /** + * 执行迁移:新增 name 列(幂等:已存在则跳过)。 + * + * 说明:sequelize 的 addColumn 不支持指定列位置(AFTER), + * 为满足「位于 report_definition_id 之后」的规格要求, + * 使用原生 DDL 控制列位置,与项目既有迁移 + * (restructure-report-definition-by-id)的做法一致。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} 无返回值 + */ + async up(queryInterface) { + const { sequelize } = queryInterface; + const columns = await queryInterface.describeTable(TABLE_PLAN); + + // 幂等保护:已存在 name 列时跳过 + if (columns.name) { + return; + } + + await sequelize.query( + `ALTER TABLE \`${TABLE_PLAN}\` + ADD COLUMN \`name\` VARCHAR(100) NULL COMMENT '计划名称(前端展示用)' + AFTER \`report_definition_id\`` + ); + }, + + /** + * 回滚迁移:删除 name 列(幂等:不存在则跳过)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} 无返回值 + */ + async down(queryInterface) { + const columns = await queryInterface.describeTable(TABLE_PLAN); + + // 幂等保护:不存在 name 列时跳过 + if (!columns.name) { + return; + } + + await queryInterface.removeColumn(TABLE_PLAN, 'name'); + }, +}; diff --git a/docs/report-config-guide.md b/docs/report-config-guide.md new file mode 100644 index 0000000..f3fdb05 --- /dev/null +++ b/docs/report-config-guide.md @@ -0,0 +1,342 @@ +# 配置驱动通用报表与货主定时投递 — 配置结构说明 + +> 本文档与代码实现保持一致(模型:`app/model/report_definition.js`;引擎:`app/service/systems/report.js`; +> 渲染翻译层:`app/lib/report/render.js`;内置查询器:`app/service/systems/report/queries/*`; +> 投递编排:`app/service/systems/reportDelivery.js`)。 +> 接口定义见 `methods/system.json` 分组「通用报表模块」(module=report)。 + +> 破坏性变更(2026-08-30 模型重构):报表定义由 `code` 编码改为主键 `id` 关联,接口入参 `report_code` +> 全部替换为 `report_id`(=报表定义ID,兼容 `reportId` 驼峰);`code/scope/description` 与 +> `output_config/source_config/sheet_config` 三段 JSON 配置字段已随模型删除, +> 列渲染由注册类型硬编码字段规格自动完成(无自定义列配置)。 + +## 1. 总览 + +报表采用「配置驱动」:`wms_report_definition` 一行配置 = 一个报表(`type` + `fields` 极简配置), +大部分新报表场景只需加配置行或新增内置查询器类型,免发版。 + +模型 `app/model/report_definition.js` 关键字段: + +| 列 | 类型 | 说明 | +|---|---|---| +| `id` | BIGINT UNSIGNED | 主键,报表定义ID(接口入参 `report_id`,唯一性由主键承担) | +| `name` | STRING(100) | 报表名称 | +| `type` | STRING(50) | 报表类型(内置查询器注册 key,如 `stockFlow`) | +| `file_name` | STRING(200) | 导出文件名模板(支持 `{date}` 占位,如 `7日出入库_{date}.xlsx`) | +| `fields` | JSON | 勾选的字段 key 数组(该类型注册字段的子集;列头/合并/样式/格式化由类型硬编码字段规格决定) | +| `is_enabled` | TINYINT(1) | 是否启用:0=停用 1=启用(导出只读 is_enabled=1 的定义) | +| `remark` | STRING(500) | 备注 | +| `created_at`/`updated_at`/`deleted_at` | DATE | 时间戳与软删标记 | + +生成链路: + +```text +report.generate(method 层,异步任务,入参 report_id) + -> systems/report.js getDefinition(读定义,is_enabled=1,软删自动排除) + -> resolveTypeEntry / resolveQuerier(type 查注册表) + -> 内置查询器取数 {windows, rows, meta} + -> lib/report/render.js renderSheetByType(按类型硬编码字段规格渲染) + -> excel.generateAndUpload(产物 fileKey/url/filename/size) +``` + +## 2. 注册类型(report.definition.typeList / wms_report_definition.type) + +查询器注册表 `app/service/systems/report/queries/index.js`,`type` 即注册方法 key; +查询器签名统一:`async ({ ctx, storeId, warehouseId, params }) => ({ windows, rows, meta })`, +每个查询器模块挂载静态字段清单 `fields` 与缺省窗口参数 `defaultWindow`。 + +当前注册类型: + +| key | 标题 | 说明 | +|---|---|---| +| `stockFlow` | 库存变化以及补货报表 | 按日窗口聚合出入库流水与正品库存,输出每 SKU 每日出/入库、可用/总库存、锁定数、待出、日均出/入库、预计可售天数、建议补货量与库存预警 | + +`stockFlow` 缺省窗口参数:`window = { dayCount: 7, cutoverHour: 7 }`。 + +`stockFlow` 全量字段清单(16 个顶层字段,`report.definition.typeList` / `report.meta` 直接返回该规格): + +| key | label | type | computed | asText | 说明 | +|---|---|---|---|---|---| +| `stock_id` | 库存ID | number | - | - | | +| `item_code` | 商品编码 | string | - | ✅ | 文本单元格落地,防科学计数法 | +| `item_name` | 商品名称 | string | - | - | | +| `barcode` | 条码 | string | - | ✅ | 文本单元格落地,防科学计数法 | +| `daily` | 每日出入库 | array | - | - | children:`ck`(出库数,number)/ `rk`(入库数,number) | +| `ck_total` | 出库合计 | number | - | - | | +| `rk_total` | 入库合计 | number | - | - | | +| `available` | 可用库存 | number | - | - | | +| `total` | 总库存 | number | - | - | | +| `pending` | 待出库存 | number | - | - | | +| `locked` | 锁定数 | number | - | - | | +| `ck_avg` | 出库日均(×10) | number | ✅ | - | 预计算字段 | +| `rk_avg` | 入库日均(×10) | number | ✅ | - | 预计算字段 | +| `stock_days` | 预计可售天数 | number | ✅ | - | 预计算字段 | +| `suggest` | 建议补货量 | number | ✅ | - | 预计算字段 | +| `warn` | 库存预警 | boolean | ✅ | - | 预计算字段 | + +### 2.1 stockFlow 口径与假设(8 条,供测试复核) + +1. **窗口**:`dayCount` 个 `[D cutoverHour:00, D+1 cutoverHour:00)` 本地时区半开区间 + (缺省 7 天、07:00 切点,可由请求 `params.dayCount/cutoverHour` 覆盖)。 +2. **流水**:`wms_stock_transaction`,`transaction_type IN (INBOUND, OUTBOUND)`,显式排除 LOCK/UNLOCK, + 按 `created_at` 落入窗口,INBOUND→rk、OUTBOUND→ck。 +3. **库存口径**:`wms_storage`(库位级正品明细),`inventory_type='ZP'`、`is_enabled=1`、未删除, + `SUM(quantity)`=总库存、`SUM(available_quantity)`=可用库存、`SUM(locked_quantity)`=锁定数、 + 待出库存=总库存-可用库存;与 `wms_stock_warehouse` 主表的 `quantity/locked_quantity` 可能存在口径差异。 +4. **条码**:`wms_stock_barcodes` 多值取字典序第一条(表内无主条码标志,等价旧 PHP `MIN(barcode)` 语义)。 +5. **行范围**:窗口内有流水或有正品库存的 SKU 均出列,按 `item_code` 升序、`stock_id` 升序。 +6. **日均口径**:`ck_avg/rk_avg = int(合计/天数×10)`(`formatters.avgDaysPerWeek`)。 +7. **预计可售天数**:出库日均>0 时 `int(可用库存×10/出库日均×10)`(`available×10/ckAvg` 取整),无出库时为 null。 +8. **suggest/warn**:由 `formatters` 注册表计算。低库存补偿:`available < 20` 且 `rk_total < 20` 时 + 建议补货量补偿到不低于 30;预警判定由 `warnOf(ck_total, available, rk_total)` 计算。 + +## 3. 渲染规则(renderSheetByType,无 sheet_config) + +列定义不再由 `sheet_config.columns` 配置,而由**注册类型字段规格硬编码自动生成** +(`app/lib/report/render.js` `renderSheetByType`,按定义勾选字段顺序渲染): + +| 字段类型 | 渲染规则 | +|---|---| +| `string` | 静态列(表头=label);字段规格 `asText: true` 时整列落地为 Excel 文本单元格 | +| `number` | 静态列,统一 `zeroToDash`(`0 / '0' / null / ''` 显示 `-`) | +| `boolean` | 静态列,统一 `yesNo`(真→'是'、假→'否',PHP 布尔语义) | +| `array` | 窗口展开列:per=窗口数(缺省 7)、pair=children 字段键;表头第 1 行每窗口输出窗口开始日期 `'Y/n/j'`(无前导零,如 `2026/8/23`),pair 数>1 时每窗口表头横向合并(如 D1:E1 … P1:Q1);表头第 2 行按 children label 填充;子字段 number 统一 `zeroToDash` | + +- 存在展开列时启用两行表头,其余列表头纵向合并(如 A1:A2),合并区域**自动生成**,无需配置。 +- **asText(文本单元格)**:由类型字段规格硬编码(如 `item_code`/`barcode` 声明 `asText: true`), + 渲染层 `renderSheetByType` 将声明 `asText` 的列收集为 `textColumns`(0 基列索引数组,未声明任何 `asText` 列时不输出该字段), + 由 `app/service/systems/excel.js` 落地:ExcelJS 路径逐单元格 `numFmt='@'` 并把值转为字符串(原始对象除外), + SheetJS 路径逐单元格 `t:'s'`、`z:'@'` 并把值字符串化。适用于条码、商品编码等长数字串 + (防止被 Excel 按数值展示成科学计数法),**无需**再配合 `textPrefix` 的 `'` 前缀 + (`textPrefix` 格式化器保留注册仅向后兼容)。 +- sheet 名称为类型标题(如「库存变化以及补货报表」);`columns` 恒输出空数组 + (数据以 AOA 二维数组形式输出,表头行内联在 rows 首位)。 + +## 4. 导出文件名(file_name) + +- `file_name` 为文件名模板,`{date}` 替换为数据日期(请求 `params.bizDate`,缺省服务器当天,`YYYY-MM-DD`)。 +- 缺省模板:`_.xlsx`;不以 `.xlsx`/`.xls` 结尾时自动补 `.xlsx`。 +- 上传目录:`exports/report//`。 + +## 5. 货主定时投递(wms_report_delivery_plan / wms_report_delivery_log) + +- **投递计划** `wms_report_delivery_plan`:`store_id + report_definition_id` 唯一(唯一索引 `uk_store_report_definition`, + `report_definition_id` 即报表定义ID、接口入参 `report_id`);`schedule_times`(HH:mm 数组,去重升序)、 + `channel`(**仅支持 `inbox`,默认 `inbox`**;wecom/link 已弃用,保存时传非法渠道报错「投递渠道仅支持 inbox: 」)、 + `late_grace_minutes`(补投宽限 0-1440,默认 60)、`name`(计划名称,仅展示字段,≤100 字符,可空)、`enabled`。 +- **计划名称 `name`**(2026-08-30 新增,仅展示字段,不参与 `store_id + report_definition_id` 幂等/关联逻辑): + `report.deliveryPlan.save` 可选入参(未传不覆盖既有值;`null`/空串/全空白归一化为 `null` 显式清空; + 非空 `trim` 后最长 100 字符,超长报错「计划名称 name 长度不能超过 100 字符」); + `save` 成功响应与 `report.deliveryPlan.list` 列表项均返回 `name`(未设置时为空字符串)。 + +```json +// report.deliveryPlan.save(name 可选) +{ + "store_id": 1001, + "report_id": 1, + "schedule_times": ["09:00", "17:30"], + "name": "每日库存报表投递", + "late_grace_minutes": 60 +} +``` +- **渠道收敛兜底**:历史计划残留的 wecom/link 渠道在投递时**按 inbox 兜底执行**(仅记录 warn 日志,不抛错,避免历史计划卡死)。 +- **迁移归一化**:迁移 `20260829170000` 已把两表 `channel` 列默认值 wecom → inbox、comment 收敛, + 存量 `channel IN ('wecom','link')` 行统一 UPDATE 为 `inbox`(模型 `defaultValue: 'inbox'` 同步); + `report.deliveryPlan.list` / `report.deliveryLog.list` 响应 `channel` 恒为 `inbox`。 +- **投递记录** `wms_report_delivery_log`:状态机与 `status` 一致: + `pending → exporting → delivered / failed / cancelled`;`report_definition_id` 关联报表定义ID, + `report_name` 为投递时报表名称快照(审计回放,定义删除后仍可追溯)。 +- **调度**(`reportDelivery.dispatch`,分钟级):按 HH:mm + 宽限窗口命中后, + 对每个 `(store_id, report_definition_id, biz_date, time_point)` 幂等生成报表并投递(防重不防漏)。 +- **失败自动重推**:inbox 推送失败(`success=false` 或消息回写 `push_status=3`)时,立即复用 + `inbox.message.retry` **重推一次**(`ext_id` 幂等复用同一条消息记录,不重复写);重推仍失败进入 + `failed` 退避重试:`MAX_RETRY=3`,退避 `retry_count × 60s`;重试扫描条件 + `status=failed 且 retry_count<3 且 next_retry_at<=now`;卡在 exporting 超过 30 分钟视为陈旧可重扫。 +- **biz_date 口径**:正常投递为触发日 T-1;跨零点补投(时间点晚于当前时刻)为触发日 T-2, + 与昨日正常投递口径一致,避免与次日正常投递撞幂等键。 + +### 5.1 文本通知模板与定向群/成员(notify_template / notify_group_ids / notify_member_ids) + +投递计划可在投递完成后附带发送一条文本通知(与投递渠道独立,inbox 渠道投递后同样生效;未配置时行为与旧版完全一致)。 +三个字段均为可选,仅在 `report.deliveryPlan.save` 入参存在时生效(更新时未传保持原值)。 + +#### 5.1.1 notify_template(文本通知模板) + +- 最长 **500** 字符,超出报错;空值/未传视为未启用。 +- 标签白名单(仅以下 4 个标签会被渲染,其余 `{xxx}` 视为未知标签,保存时报错并列出非法标签): + +| 标签 | 渲染内容 | +|---|---| +| `{time}` | 发送时间,格式 `YYYY-MM-DD HH:mm` | +| `{url}` | 报表文件下载链接;链接为空时替换为兜底文案「文件生成中,稍后可在投递记录中查看」 | +| `{report_name}` | 报表名称 | +| `{biz_date}` | 数据日期 `YYYY-MM-DD` | + +- 示例模板:`【{report_name}】{biz_date} 数据报表已生成,下载:{url}(生成时间 {time})` + +#### 5.1.2 notify_group_ids(通知群,定向内部群) + +- 元素为 `wms_inbox_group.id`(内部群 ID),**正整数**、自动去重并升序,最多 **20** 个。 +- 保存时校验存在性:软删(已删除)的群报错并**列出缺失 ID**;被屏蔽(`is_blocked=1`)的群仍可选中, + 屏蔽属于发送时过滤维度。 +- 发送时逐群推送(群维度协议字段 `group_id`/`group_name` 为单值),并再次过滤 + `is_blocked=1`、软删、仓库维度不一致的群;此类群不发送且不进入投递记录快照。 + +#### 5.1.3 notify_member_ids(通知成员,定向外部成员) + +- 元素为**外部 IM 用户 ID**,**非空字符串**、自动去重,最多 **100** 个。 +- 推送时 `user_id` **数组整体透传**(目标侧协议支持 user_id 数组),不循环拆发; + 选择群时成员数组随每个群推送携带,未选择群时单独做一次仅成员推送。 + +#### 5.1.4 发送规则与投递记录快照 + +- 未配置模板或未选择任何群/成员时**不发送**(投递行为不变)。 +- 发送时机:报表生成并完成渠道投递后(`delivered` 回写前),失败抛异常走失败退避重试 + (`MAX_RETRY=3`,退避 `retry_count × 60s`)。 +- 发送结果快照 `notify_targets` 随投递记录落库并在 `report.deliveryLog.list` 返回: + +```json +{ + "group_ids": [1, 3], + "member_ids": ["user-1001", "user-1002"], + "notify_text": "【7日出入库数据】2026-08-28 数据报表已生成,下载:https://...(生成时间 2026-08-29 09:00)" +} +``` + +- `group_ids` 为**实际发送**的群内部 ID 列表;`member_ids` 为实际发送的成员 ID 列表; + `notify_text` 为标签替换后的最终文本;未发送文本通知时快照为 `null`。 + +## 6. 报表定义保存示例(report.definition.save) + +```json +{ + "name": "库存变化以及补货报表", + "type": "stockFlow", + "fileName": "库存变化_{date}.xlsx", + "fields": ["item_code", "item_name", "barcode", "daily", "ck_total", "rk_total", "available", "total", "pending", "locked", "ck_avg", "suggest", "warn"], + "is_enabled": 1, + "remark": "" +} +``` + +- `type` 必须命中注册表(当前仅 `stockFlow`,未知报「未知的报表类型: 」); + `fields` 必须为该类型注册字段子集(16 个顶层字段任意勾选,含非法 key 报可读错误并列出可用字段)。 +- `file_name` 兼容 `fileName` 驼峰写法(驼峰优先);新增必填 `name`/`type`/`file_name`/`fields`; + 更新按 `id` upsert,未传字段不覆盖;软删记录命中时自动恢复。 +- 保存成功后响应即报表定义视图: + `{ id, name, type, file_name, fields, is_enabled, remark, created_at, updated_at }`。 + +## 7. report.definition.typeList / report.meta(前端元数据接口) + +### 7.1 用途 + +- `report.definition.typeList`:免权限只读(仅登录),返回注册类型清单 + `[{ key, title, description, window, fields }]`,供前端报表设计器渲染「报表类型」选择与字段树。 +- `report.meta`:免权限只读(仅登录,保留审计日志),按 `report_id` 返回 + `report_id/name/type/file_name/window/fields`(fields 含 `selected` 勾选标记与 `asText` 标记), + **不执行真实数据查询**。 + +实现:`report.definition.typeList` → `app/service/systemMethods/report/definition.js` → `systems/report.js listRegisteredTypes`; +`report.meta` → `app/service/systemMethods/report.js` → `systems/report.js getMeta`。 + +> 鉴权/日志口径:`report.definition.typeList` 在 `definition.js` 的 `systemInit` 名单内 +> (`_noNeedRight/_noNeedAuth/_noNeedLog='typeList'`:免权限 + 免鉴权 + 不写审计日志,仅登录; +> 同模块 `save/list/delete` 未声明免权限,仍需授权);`report.meta` 在 `_noNeedRight/_noNeedAuth` 名单内 +> (免权限 + 免仓库有效期校验,仅登录),未列入 `_noNeedLog` → **保留审计日志** +> (`generate`/`generateTaskProgress` 不写审计日志,二者行为不同)。 + +### 7.2 请求示例 + +```json +// report.definition.typeList(无必填参数) +{} + +// report.meta +{ "report_id": 1 } +``` + +- `report_id` 与 `reportId` 二选一(均传时优先 `reportId`);为空返回 + `flag=failure, code=0, message=报表ID report_id 必须为正整数`(HTTP 200)。 +- 定义不存在或已停用 → HTTP 500,`接口错误: 报表定义不存在或已停用: id=`。 + +### 7.3 响应示例 + +```json +// report.definition.typeList +{ + "flag": "success", + "code": 1, + "message": "ok", + "list": [ + { + "key": "stockFlow", + "title": "库存变化以及补货报表", + "description": "按日窗口聚合出入库流水与正品库存,……", + "window": { "dayCount": 7, "cutoverHour": 7 }, + "fields": [ + { "key": "item_code", "label": "商品编码", "type": "string", "asText": true }, + { "key": "daily", "label": "每日出入库", "type": "array", "children": [ + { "key": "ck", "label": "出库数", "type": "number" }, + { "key": "rk", "label": "入库数", "type": "number" } + ]}, + { "key": "suggest", "label": "建议补货量", "type": "number", "computed": true } + ] + } + ] +} + +// report.meta +{ + "flag": "success", + "code": 1, + "message": "ok", + "report_id": 1, + "name": "库存变化以及补货报表", + "type": "stockFlow", + "file_name": "库存变化_{date}.xlsx", + "window": { "dayCount": 7, "cutoverHour": 7 }, + "fields": [ + { "key": "item_code", "label": "商品编码", "type": "string", "asText": true, "selected": true }, + { "key": "barcode", "label": "条码", "type": "string", "asText": true, "selected": false } + ] +} +``` + +字段元素结构:`{ key, label, type, computed?, asText?, children?, selected? }`: + +- `type`:`string` / `number` / `boolean` / `array`; +- `computed: true`:预计算字段(非原始表字段,如 `suggest`/`warn`); +- `asText: true`:该列以文本单元格落地(由类型字段规格硬编码,如 `item_code`/`barcode`); +- `children`:数组类型字段的子字段(如 `daily` 的 `ck`/`rk`); +- `selected`(仅 `report.meta` 返回):该报表定义是否勾选此字段。 + +### 7.4 前端如何获取可用字段 + +1. 调用 `method=report.definition.typeList`(`POST /system`,header 带 `Authorization: Bearer ` 与 `platform`) + 获取全部注册类型与字段树; +2. 保存报表定义时按类型字段树勾选 `fields`(`method=report.definition.save`); +3. 渲染/导出前调用 `method=report.meta`(入参 `report_id`)取窗口参数 `window.dayCount/cutoverHour` 与勾选标记 `selected`; +4. 导出 sheet 的列由「勾选字段 × 类型硬编码规格」自动生成,前端无需下发任何列配置。 + +## 8. 报表定义管理接口(report.definition.save / list / delete) + +管理侧维护 `wms_report_definition` 的 3 个接口,均需登录且需鉴权(`isNeedAuth=true`、`isNeedLogin=true`, +`POST /system`,header 带 `Authorization: Bearer ` 与 `platform`)。 + +- `report.definition.save`:按 `id` upsert(未传 id 新增),入参 + `{ id?, name, type, file_name/fileName, fields, is_enabled?, remark? }`; + `type` 必须命中注册表、`fields` 必须为该类型注册字段子集(非法 key 报可读错误列出); + 新增必填 `name/type/file_name/fields`;软删记录命中时自动恢复。 +- `report.definition.list`:`where { name, type, is_enabled }` + `pagination` + `sort` + (sort 白名单 `id/name/type/is_enabled/created_at/updated_at`,默认 id DESC); + 响应每行 `{ id, name, type, file_name, fields, is_enabled, remark, created_at, updated_at }`,软删自动排除。 +- `report.definition.delete`:入参 `id`;删除前按 `report_definition_id` 统计投递计划引用, + 仅拦截「启用中」的计划(`enabled=1`,报「存在 N 个启用的投递计划引用该报表,请先停用计划」), + 停用计划不阻断;重复删除同一 ID 幂等成功(`deleted` 恒为 1)。 +实现:`app/service/systemMethods/report/definition.js` → `app/service/systems/report.js` 的 +`saveDefinition` / `listDefinitions` / `deleteDefinition`。 + +> 鉴权口径:三个接口 `systemInit` 均未声明免权限(`isNeedAuth=true`),仅通配符角色 +> (超级管理员/仓库管理员)或已授权角色可用;本次仅文档同步,未扩任何角色授权 +> (权限缺口可用 `npm run permission:sync:system-api -- --dry-run` 预演)。 + From 0a54f8028b8231b4274463c1ebaf9007702bf802 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sun, 30 Aug 2026 07:28:05 +0800 Subject: [PATCH 294/550] =?UTF-8?q?feat(inbox):=20=E7=AB=99=E5=86=85?= =?UTF-8?q?=E4=BF=A1=E5=88=86=E7=BB=84=E5=BF=AB=E9=80=9F=E5=88=97=E8=A1=A8?= =?UTF-8?q?=E4=B8=8E=E5=A4=9A=E7=BE=A4=E6=88=90=E5=91=98=E8=81=9A=E5=90=88?= =?UTF-8?q?=EF=BC=8C=E6=94=AF=E6=8C=81=20groupIds=20=E6=95=B0=E7=BB=84?= =?UTF-8?q?=E5=85=A5=E5=8F=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/systemMethods/inbox.js | 61 +++++- app/service/systems/inbox/group.js | 174 ++++++++++++++++++ ...0000-add-inbox-group-select-permissions.js | 121 ++++++++++++ ...0-add-store-id-index-to-wms-inbox-group.js | 59 ++++++ 4 files changed, 413 insertions(+), 2 deletions(-) create mode 100644 database/migrations/20260829180000-add-inbox-group-select-permissions.js create mode 100644 database/migrations/20260830150000-add-store-id-index-to-wms-inbox-group.js diff --git a/app/service/systemMethods/inbox.js b/app/service/systemMethods/inbox.js index 387a7a3..9279b8c 100644 --- a/app/service/systemMethods/inbox.js +++ b/app/service/systemMethods/inbox.js @@ -9,11 +9,13 @@ const MainService = require('../main'); class InboxSystemService extends MainService { /** * 群管理子入口,供 /system dispatcher 按 inbox.group.* 路径访问。 - * @return {{list: Function, disable: Function, update: Function, reset: Function, messages: Function, checkAuth: Function}} + * @return {{list: Function, quickList: Function, members: Function, disable: Function, update: Function, reset: Function, messages: Function, checkAuth: Function}} 群管理子入口方法集合。 */ get group() { return { list: data => this.groupList(data), + quickList: data => this.groupQuickList(data), + members: data => this.groupMembers(data), disable: data => this.groupDisable(data), update: data => this.groupUpdate(data), reset: data => this.groupReset(data), @@ -24,7 +26,7 @@ class InboxSystemService extends MainService { /** * 消息管理子入口,供 /system dispatcher 按 inbox.message.* 路径访问。 - * @return {{list: Function, detail: Function, thread: Function, reply: Function, stats: Function, checkAuth: Function}} + * @return {{list: Function, detail: Function, thread: Function, reply: Function, stats: Function, checkAuth: Function}} 消息管理子入口方法集合。 */ get message() { const { ctx } = this; @@ -100,6 +102,61 @@ class InboxSystemService extends MainService { }); } + /** + * 群快速查询(下拉选择用,不分页)。 + * 双维度可选过滤,均不传时返回所有仓库/货主的群: + * - store_id:货主维度,透传为底层参数 storeId; + * - warehouse_id:仓库维度,透传为底层参数 warehouseId; + * - 两者可同时传(AND 关系),也可都不传(不加对应过滤条件)。 + * + * @param {Object} data 请求数据。 + * @param {string} [data.keyword] 关键词,模糊匹配群名称与外部群ID。 + * @param {string} [data.groupType] 按群类型筛选:store / warehouse / express。 + * @param {number} [data.limit=20] 返回条数上限,最大 100。 + * @param {number|string} [data.store_id] 货主ID(可选,对应 wms_inbox_group.store_id 列)。 + * @param {number|string} [data.warehouse_id] 仓库ID(可选,对应 wms_inbox_group.warehouse_id 列)。 + * @return {Promise} { list: 群快速列表 }。 + */ + async groupQuickList(data = {}) { + const { ctx } = this; + const { + keyword, groupType, limit, + store_id: storeId, + warehouse_id: warehouseId, + } = data; + + return await ctx.service.systems.inbox.group.quickList({ + storeId, + warehouseId, + keyword, + groupType, + limit, + }); + } + + /** + * 查询一个或多个群的成员列表(下拉选择用,多群聚合)。 + * warehouseId 从 ctx.user.store_id 自动注入,不信任前端传值。 + * + * @param {Object} data 请求数据。 + * @param {Array} data.groupIds 群内部主键ID数组(必填,非空且每个元素为正整数)。 + * @param {string} [data.keyword] 关键词,模糊匹配 user_name / user_id。 + * @param {number} [data.limit=20] 返回条数上限,最大 100。 + * @return {Promise} { list: 群成员列表 }。 + */ + async groupMembers(data = {}) { + const { ctx } = this; + const { groupIds, keyword, limit } = data; + const warehouseId = Number(ctx.user?.store_id || 0); + + return await ctx.service.systems.inbox.group.members({ + groupIds, + warehouseId, + keyword, + limit, + }); + } + /** * 禁用 / 解禁群。 * warehouseId 从 ctx.user.store_id 自动注入。 diff --git a/app/service/systems/inbox/group.js b/app/service/systems/inbox/group.js index e17a589..be2e4f2 100644 --- a/app/service/systems/inbox/group.js +++ b/app/service/systems/inbox/group.js @@ -193,6 +193,180 @@ class InboxGroupService extends Service { return { total: count, list }; } + /** + * 群快速查询(下拉选择用,不分页)。 + * 关键词同时模糊匹配群名称与外部群ID,按创建时间倒序返回轻量字段, + * 软删除记录由 paranoid 自动排除。 + * 双维度可选过滤,均不传时 where 不含这两列、返回所有仓库/货主的群: + * - store_id(货主维度)↔ wms_inbox_group.store_id 列; + * - warehouse_id(仓库维度)↔ wms_inbox_group.warehouse_id 列; + * - 两者可同时传(AND 关系),也可都不传(不加对应过滤条件)。 + * + * @param {Object} data 请求数据。 + * @param {number|string} [data.storeId] 货主ID(可选,来自 API 入参 store_id,映射到 wms_inbox_group.store_id 列; + * 传入时须为可解析的正整数,否则抛错「store_id 无效」;不传或为空时不加货主过滤)。 + * @param {number|string} [data.warehouseId] 仓库ID(可选,来自 API 入参 warehouse_id,映射到 wms_inbox_group.warehouse_id 列; + * 传入时须为可解析的正整数,否则抛错「warehouse_id 无效」;不传或为空时不加仓库过滤)。 + * @param {string} [data.keyword] 关键词,模糊匹配 group_name / group_id。 + * @param {string} [data.groupType] 按群类型筛选:store / warehouse / express。 + * @param {number} [data.limit=20] 返回条数上限,最大 100。 + * @return {Promise<{list: Array<{id: number, group_id: (string|null), group_name: string, group_type: (string|null), sub_type: (string|null), is_blocked: number}>}>} 群快速列表。 + */ + async quickList(data = {}) { + const { ctx } = this; + const { InboxGroup } = ctx.model; + const { Op } = ctx.app.Sequelize; + + const keyword = String(data.keyword || '').trim(); + const groupType = String(data.groupType || '').trim(); + const limit = Math.min(100, Math.max(1, Number(data.limit) || 20)); + + const where = {}; + + // store_id(货主维度,对应 wms_inbox_group.store_id 列)可选: + // 传入时校验为可解析的正整数,设置 where.store_id;不传或为空串时不加货主过滤 + const storeIdRaw = String(data.storeId ?? '').trim(); + if (storeIdRaw) { + const storeId = Number(storeIdRaw); + if (!Number.isInteger(storeId) || storeId <= 0) throw new Error('store_id 无效'); + where.store_id = storeId; + } + + // warehouse_id(仓库维度,对应 wms_inbox_group.warehouse_id 列)可选: + // 传入时校验为可解析的正整数,设置 where.warehouse_id;不传或为空串时不加仓库过滤 + const warehouseIdRaw = String(data.warehouseId ?? '').trim(); + if (warehouseIdRaw) { + const warehouseId = Number(warehouseIdRaw); + if (!Number.isInteger(warehouseId) || warehouseId <= 0) throw new Error('warehouse_id 无效'); + where.warehouse_id = warehouseId; + } + + if (groupType) where.group_type = groupType; + if (keyword) { + where[Op.or] = [ + { group_name: { [Op.like]: `%${keyword}%` } }, + { group_id: { [Op.like]: `%${keyword}%` } }, + ]; + } + + const rows = await InboxGroup.findAll({ + attributes: [ 'id', 'group_id', 'group_name', 'group_type', 'sub_type', 'is_blocked' ], + where, + order: [[ 'created_at', 'DESC' ]], + limit, + raw: true, + }); + + return { list: rows }; + } + + /** + * 查询一个或多个群的成员列表(下拉选择用,多群聚合)。 + * 先用内部主键数组 + 仓库批量校验群存在(软删自动排除,attributes 只取 id/group_id, + * 找不到任何匹配群抛「群不存在或无权限操作」),再收集所有群的外部群ID(去重、剔除空值), + * 按外部群ID集合在消息表中聚合去重成员:取每个 user_id 最新一条消息的 user_name + * (消息按 id 倒序,首次出现的即最新),关键词在聚合后对 user_name / user_id 做包含匹配, + * 最后截断到 limit 条。外部群ID集合为空时直接返回空列表。 + * 局限说明:多群共享同一聚合池,最多取最近 500 条消息,更早消息中的成员不会出现在结果中; + * user_id 为 NULL / 空串的消息被排除;关键词匹配大小写不敏感。 + * + * @param {Object} data 请求数据。 + * @param {Array} data.groupIds wms_inbox_group 内部主键ID数组(必填,非空且每个元素为正整数)。 + * @param {number} data.warehouseId 仓库ID(必填,由 controller 注入)。 + * @param {string} [data.keyword] 关键词,模糊匹配 user_name / user_id。 + * @param {number} [data.limit=20] 返回条数上限,最大 100。 + * @return {Promise<{list: Array<{user_id: string, user_name: string}>}>} 群成员列表。 + */ + async members(data = {}) { + const { ctx } = this; + const { InboxGroup, InboxMessage } = ctx.model; + const { Op } = ctx.app.Sequelize; + + const warehouseId = Number(data.warehouseId); + if (!warehouseId) throw new Error('warehouseId 无效'); + + // groupIds 校验:非空数组且每个元素为数字或可解析数字字符串的正整数 + const rawGroupIds = data.groupIds; + if (!Array.isArray(rawGroupIds) || rawGroupIds.length === 0) { + throw new Error('groupIds 无效'); + } + const groupIds = rawGroupIds.map(item => { + if (typeof item !== 'number' && typeof item !== 'string') return NaN; + return Number(item); + }); + if (groupIds.some(id => !Number.isInteger(id) || id <= 0)) { + throw new Error('groupIds 无效'); + } + + // 批量校验群存在(软删自动排除),attributes 只取 id / group_id + const groups = await InboxGroup.findAll({ + attributes: [ 'id', 'group_id' ], + where: { id: { [Op.in]: groupIds }, warehouse_id: warehouseId }, + raw: true, + }); + if (!groups || groups.length === 0) { + throw new Error('群不存在或无权限操作'); + } + + // 收集所有群的外部群ID(去重、剔除空值),全部为空则没有可关联的消息成员 + const externalGroupIds = [ ...new Set( + groups.map(g => String(g.group_id || '').trim()).filter(Boolean) + ) ]; + if (externalGroupIds.length === 0) { + return { list: [] }; + } + + const keyword = String(data.keyword || '').trim(); + const limit = Math.min(100, Math.max(1, Number(data.limit) || 20)); + + // 拉取多群最近消息集合(软删除由 paranoid 自动排除),共享同一聚合池。 + // 局限说明:聚合池最多取最近 500 条消息,更早消息中的成员不会出现在结果中。 + // user_id 同时排除 NULL 与空串(用字段级 Op.and 避免同名键覆盖), + // 防止脏数据进入聚合池并输出 "null"/"" 成员。 + const messages = await InboxMessage.findAll({ + attributes: [ 'id', 'user_id', 'user_name' ], + where: { + warehouse_id: warehouseId, + group_id: { [Op.in]: externalGroupIds }, + user_id: { + [Op.and]: [ + { [Op.ne]: null }, + { [Op.ne]: '' }, + ], + }, + }, + order: [[ 'id', 'DESC' ]], + limit: 500, + raw: true, + }); + + // 按 user_id 去重:消息已按 id 倒序,首次出现即该用户最新消息。 + // JS 层兜底:跳过 null/undefined user_id,防止 String(null) 变成 "null" 输出。 + const memberMap = new Map(); + for (const msg of messages) { + if (msg.user_id === null || msg.user_id === undefined) continue; + const userId = String(msg.user_id).trim(); + if (!userId || memberMap.has(userId)) continue; + memberMap.set(userId, String(msg.user_name || '').trim()); + } + + let list = Array.from(memberMap.entries()) + .map(([ user_id, user_name ]) => ({ user_id, user_name })); + + // 关键词在聚合结果上过滤 user_name / user_id: + // 统一转小写后做包含匹配,与 quickList 的 SQL LIKE(MySQL 默认大小写不敏感)语义一致 + if (keyword) { + const lowerKeyword = keyword.toLowerCase(); + list = list.filter(item => { + const userName = String(item.user_name || '').toLowerCase(); + const userId = String(item.user_id || '').toLowerCase(); + return userName.includes(lowerKeyword) || userId.includes(lowerKeyword); + }); + } + + return { list: list.slice(0, limit) }; + } + /** * 禁用 / 解禁群。 * diff --git a/database/migrations/20260829180000-add-inbox-group-select-permissions.js b/database/migrations/20260829180000-add-inbox-group-select-permissions.js new file mode 100644 index 0000000..f31ebf1 --- /dev/null +++ b/database/migrations/20260829180000-add-inbox-group-select-permissions.js @@ -0,0 +1,121 @@ +'use strict'; + +/** + * 为群选择 / 群成员选择下拉接口创建 API 权限记录并授权。 + * + * 权限明细(固定 ID,当前迁移内 max_id=565): + * 566 — inbox.group.quickList API:群快速查询 + * 567 — inbox.group.members API:群成员列表 + * + * 角色授权(客服组-主管及以上): + * 26(仓库组-主管) → 28(客服组-主管) → 29(生产组-主管) → 8(经理) + * 超级管理员(7)/仓库管理员(2) 已持有 * 通配符,自动拥有,无需处理 + * + * 幂等:INSERT IGNORE 创建权限记录;角色权限数组追加后去重排序,已存在跳过。 + */ + +const TABLE = 'wms_permission'; +const ROLE_TABLE = 'wms_role'; +const COLUMNS = 'id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at'; + +/** 权限ID → 授权角色ID列表(不含通配符角色) */ +const PERMISSION_ROLES = { + 566: [ 26, 28, 29, 8 ], + 567: [ 26, 28, 29, 8 ], +}; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + // ── 1. 创建 API 权限记录(固定 ID)── + const apis = [ + [ 566, 'inbox.group.quickList', 'API:群快速查询' ], + [ 567, 'inbox.group.members', 'API:群成员列表' ], + ]; + + for (const [ id, path, metaTitle ] of apis) { + await queryInterface.sequelize.query( + `INSERT IGNORE INTO \`${TABLE}\` (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`, + { replacements: [ id, path, null, path, null, metaTitle, null, 0, 0, null, 'api', 0, 1 ] } + ); + } + + // ── 2. 角色授权注入 ── + for (const permId of Object.keys(PERMISSION_ROLES).map(Number)) { + for (const roleId of PERMISSION_ROLES[permId]) { + const rows = await queryInterface.sequelize.query( + `SELECT id, permissions FROM \`${ROLE_TABLE}\` WHERE id = ?`, + { replacements: [ roleId ], type: queryInterface.sequelize.QueryTypes.SELECT } + ); + const record = Array.isArray(rows) ? rows[0] : null; + if (!record) { + continue; + } + + // 通配符角色跳过 + if (record.permissions === '*') { + continue; + } + + let perms; + try { + perms = typeof record.permissions === 'string' + ? JSON.parse(record.permissions) + : record.permissions; + } catch (e) { + perms = null; + } + + if (!Array.isArray(perms)) { + continue; + } + + if (!perms.includes(permId)) { + perms.push(permId); + perms.sort((a, b) => Number(a) - Number(b)); + await queryInterface.sequelize.query( + `UPDATE \`${ROLE_TABLE}\` SET permissions = ? WHERE id = ?`, + { replacements: [ JSON.stringify(perms), roleId ] } + ); + } + } + } + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + await queryInterface.sequelize.query( + 'DELETE FROM `wms_permission` WHERE id IN (566, 567)' + ); + + const permIds = [ 566, 567 ]; + for (const roleId of Object.values(PERMISSION_ROLES).flat()) { + const rows = await queryInterface.sequelize.query( + `SELECT id, permissions FROM \`${ROLE_TABLE}\` WHERE id = ?`, + { replacements: [ roleId ], type: queryInterface.sequelize.QueryTypes.SELECT } + ); + const record = Array.isArray(rows) ? rows[0] : null; + if (!record || record.permissions === '*') { + continue; + } + + let perms; + try { + perms = typeof record.permissions === 'string' + ? JSON.parse(record.permissions) + : record.permissions; + } catch (e) { + perms = null; + } + if (!Array.isArray(perms) || !perms.some(p => permIds.includes(p))) { + continue; + } + + perms = perms.filter(p => !permIds.includes(p)); + await queryInterface.sequelize.query( + `UPDATE \`${ROLE_TABLE}\` SET permissions = ? WHERE id = ?`, + { replacements: [ JSON.stringify(perms), roleId ] } + ); + } + }, +}; diff --git a/database/migrations/20260830150000-add-store-id-index-to-wms-inbox-group.js b/database/migrations/20260830150000-add-store-id-index-to-wms-inbox-group.js new file mode 100644 index 0000000..da87944 --- /dev/null +++ b/database/migrations/20260830150000-add-store-id-index-to-wms-inbox-group.js @@ -0,0 +1,59 @@ +'use strict'; + +/** + * 为站内信群表补充货主维度查询索引。 + * + * 背景:inbox.group.quickList 接口支持双维度过滤: + * - store_id(货主维度)→ wms_inbox_group.store_id 列 + * - warehouse_id(仓库维度)→ wms_inbox_group.warehouse_id 列 + * 两者可单独或同时(AND)过滤。store_id 列此前无索引, + * 单独按货主过滤或与仓库 AND 过滤时会走全表扫描。 + * + * wms_inbox_group: + * - idx_store_id: (store_id) + * 用于按货主维度过滤群列表。warehouse_id 维度已由唯一索引 + * uk_warehouse_group_id(warehouse_id, group_id) 的前导列覆盖,无需新增仓库单列索引; + * 双条件 AND 场景由 idx_store_id 与 uk_warehouse_group_id 组合命中, + * 群表数据量小,单列索引已足够,不引入复合索引以控制索引维护成本。 + */ + +const TABLE_NAME = 'wms_inbox_group'; +const INDEX_NAME = 'idx_store_id'; + +async function indexExists(queryInterface, tableName, indexName) { + const indexes = await queryInterface.showIndex(tableName); + return (indexes || []).some(i => (typeof i === 'string' ? i : i.name) === indexName); +} + +async function addIndexIfNotExists(queryInterface, tableName, indexName, options = {}) { + if (await indexExists(queryInterface, tableName, indexName)) { + console.log(`[idx] ${tableName}.${indexName} 已存在,跳过`); + return; + } + await queryInterface.addIndex(tableName, options.fields, { + name: indexName, + unique: !!options.unique, + }); + console.log(`[idx] ${tableName}.${indexName} 已创建`); +} + +async function dropIndexIfExists(queryInterface, tableName, indexName) { + if (await indexExists(queryInterface, tableName, indexName)) { + await queryInterface.removeIndex(tableName, indexName); + console.log(`[idx] ${tableName}.${indexName} 已删除`); + } +} + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + await addIndexIfNotExists(queryInterface, TABLE_NAME, INDEX_NAME, { + fields: [ 'store_id' ], + }); + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + await dropIndexIfExists(queryInterface, TABLE_NAME, INDEX_NAME); + }, +}; From 05177d00f72a0af5931a1b79028a379effb82e6c Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sun, 30 Aug 2026 07:28:08 +0800 Subject: [PATCH 295/550] =?UTF-8?q?feat(returnUnpack):=20=E6=8B=86?= =?UTF-8?q?=E5=8C=85=E5=8D=95=E5=BC=82=E6=AD=A5=E5=AF=BC=E5=87=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/systemMethods/returnUnpack.js | 272 ++++++++++++- app/service/systems/return_unpack.js | 462 +++++++++++++++++++++- 2 files changed, 719 insertions(+), 15 deletions(-) diff --git a/app/service/systemMethods/returnUnpack.js b/app/service/systemMethods/returnUnpack.js index 20c6c0e..2a19022 100644 --- a/app/service/systemMethods/returnUnpack.js +++ b/app/service/systemMethods/returnUnpack.js @@ -2,6 +2,9 @@ const MainService = require('../main'); +const RETURN_UNPACK_EXPORT_TASK_CACHE_KEY_PREFIX = 'return_unpack_export_task_'; +const RETURN_UNPACK_EXPORT_TASK_CACHE_TTL_SECONDS = 1800; + /** * 系统方法层:returnUnpack(退回拆包模块接口包装层)。 * 主要职责:统一包装系统方法接口,处理权限、where 解析等公共逻辑, @@ -12,12 +15,13 @@ class ReturnUnpackMethodService extends MainService { super(ctx); // 免登录方法列表:空(全部需要登录) const _noNeedLogin = ''; - // 免权限方法列表:空(全部走 API 权限校验;detail 走固定 ID 548 客服授权,与设计一致) - const _noNeedRight = ''; - // 免日志方法列表:空(全部记录日志) - const _noNeedLog = ''; - // 免鉴权(仓库有效期检查)方法列表:空(全部检查有效期) - const _noNeedAuth = ''; + // 免权限方法列表:export/exportTaskProgress 免权限(异步任务模式,与 order.export 口径一致,无 wms_permission 记录); + // 其余走 API 权限校验(detail 走固定 ID 548 客服授权,与设计一致) + const _noNeedRight = 'export,exportTaskProgress'; + // 免日志方法列表:导出与进度查询不记录操作日志(与订单导出口径一致) + const _noNeedLog = 'export,exportTaskProgress'; + // 免鉴权(仓库有效期检查)方法列表:导出与进度查询不检查仓库有效期(与订单导出口径一致) + const _noNeedAuth = 'export,exportTaskProgress'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -247,6 +251,262 @@ class ReturnUnpackMethodService extends MainService { return this._call(() => this.service.systems.returnUnpack.detail(Number(id)), '查询详情失败'); } + /** + * 提交退回拆包导出任务(异步任务模式,与 order.export 口径一致)。 + * 入参 where/sort 与 list 完全一致;提交后立即返回 task_id, + * 后台异步生成双 Sheet Excel(正常退回运单号列表 + 明细表)并上传, + * 通过 exportTaskProgress 查询进度与下载链接。 + * + * @param {Object} data 请求体。 + * @param {Object} [data.where] 筛选条件(与 list 的 where 语义一致)。 + * @param {Object} [data.sort] 排序参数(与 list 的 sort 语义一致)。 + * @return {Promise} 统一成功包装响应(含 task_id/status/progress 等任务信息)。 + */ + async export(data = {}) { + const { service } = this; + const { sort } = data; + const { where } = this.prepareWhereContext(data, {}); + + // 仓库隔离:由服务端从当前上下文自动注入,禁止前端传入 + const warehouseId = Number(this.ctx.user && this.ctx.user.store_id || 0); + const enforcedWhere = { ...where }; + if (warehouseId > 0) { + enforcedWhere.warehouse_id = { operator: 'eq', value: warehouseId }; + } + + const taskId = this.generateExportTaskId(warehouseId); + const taskPayload = { + task_id: taskId, + status: 'submitted', + progress: 0, + current_count: 0, + total_count: 0, + message: '退回拆包导出任务已提交', + result: null, + error: '', + }; + + await this.setExportTaskProgress(taskId, taskPayload); + + setImmediate(async () => { + try { + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'running', + progress: 5, + current_count: 0, + total_count: 0, + message: '退回拆包导出任务执行中', + result: null, + error: '', + }); + + const result = await service.systems.returnUnpack.exportUnpack({ + where: enforcedWhere, + sort, + warehouseId, + onProgress: async progress => { + const safeProgress = this.isPlainObject(progress) ? progress : {}; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: safeProgress.status || 'running', + progress: safeProgress.progress, + current_count: safeProgress.currentCount, + total_count: safeProgress.totalCount, + message: safeProgress.message || '退回拆包导出任务执行中', + result: safeProgress.result || null, + error: '', + }); + }, + }); + + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'success', + progress: 100, + current_count: result.current_count || 0, + total_count: result.total_count || 0, + message: '退回拆包导出任务完成', + result, + error: '', + }); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'failed', + progress: 100, + current_count: 0, + total_count: 0, + message: '退回拆包导出任务失败', + result: null, + error: errorMessage, + }); + } + }); + + return this.success('ok', { + ...taskPayload, + update_time: Date.now(), + }); + } + + /** + * 查询退回拆包导出任务进度(与 order.exportTaskProgress 口径一致)。 + * + * @param {Object} data 请求体。 + * @param {string} [data.task_id] 任务ID(下划线写法)。 + * @param {string} [data.taskId] 任务ID(驼峰写法)。 + * @return {Promise} 统一成功包装响应 + * (含 task_id/status/progress/current_count/total_count/message/error/download_url/update_time)。 + */ + async exportTaskProgress(data = {}) { + const taskId = this.normalizeExportTaskId(data); + if (!taskId) { + return this.success('ok', { + task_id: '', + status: 'not_found', + progress: 0, + current_count: 0, + total_count: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const cachedTask = await this.getExportTaskProgress(taskId); + if (!cachedTask) { + return this.success('ok', { + task_id: taskId, + status: 'not_found', + progress: 0, + current_count: 0, + total_count: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {}; + const downloadUrl = String( + safeResult.url + || safeResult.cdnUrl + || safeResult.cosUrl + || safeResult.fileKey + || '' + ); + + return this.success('ok', { + task_id: taskId, + ...cachedTask, + download_url: downloadUrl, + }); + } + + /** + * 生成退回拆包导出任务ID。 + * @param {number|string} [warehouseId=''] 仓库ID(缺省兜底取当前上下文 store_id)。 + * @return {string} 导出任务ID。 + */ + generateExportTaskId(warehouseId = '') { + const normalizedWarehouseId = warehouseId || this.ctx?.user?.store_id || 'unknown'; + const timestamp = Date.now(); + const randomToken = Math.random().toString(36).slice(2, 10); + return `return_unpack_export_${normalizedWarehouseId}_${timestamp}_${randomToken}`; + } + + /** + * 归一化退回拆包导出任务ID。 + * @param {Object} data 请求体。 + * @param {string} [data.task_id] 任务ID(下划线写法)。 + * @param {string} [data.taskId] 任务ID(驼峰写法)。 + * @return {string} 归一化后的任务ID。 + */ + normalizeExportTaskId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.task_id || normalizedData.taskId || '').trim(); + } + + /** + * 获取退回拆包导出任务缓存键。 + * @param {string} taskId 任务ID。 + * @return {string} 缓存键。 + */ + getExportTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + return `${RETURN_UNPACK_EXPORT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 写入退回拆包导出任务进度缓存(Redis TTL 30 分钟)。 + * @param {string} taskId 任务ID。 + * @param {Object} payload 任务状态载荷。 + * @return {Promise} 无返回值。 + */ + async setExportTaskProgress(taskId = '', payload = {}) { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.setCacheAsync !== 'function') { + return; + } + + const safePayload = this.isPlainObject(payload) ? payload : {}; + const normalizeCount = value => { + const numericValue = Number(value); + return Number.isFinite(numericValue) && numericValue >= 0 ? Math.round(numericValue) : 0; + }; + const progressPayload = { + task_id: String(taskId || '').trim(), + status: String(safePayload.status || 'submitted').trim() || 'submitted', + progress: Number.isFinite(Number(safePayload.progress)) ? Math.min(100, Math.max(0, Math.round(Number(safePayload.progress)))) : 0, + current_count: normalizeCount(safePayload.current_count), + total_count: normalizeCount(safePayload.total_count), + message: String(safePayload.message || ''), + result: safePayload.result ?? null, + error: String(safePayload.error || ''), + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync(cacheKey, progressPayload, RETURN_UNPACK_EXPORT_TASK_CACHE_TTL_SECONDS); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + this.ctx.logger.warn(`[returnUnpack.export] 写入导出任务缓存失败: ${errorMessage}`); + } + } + + /** + * 读取退回拆包导出任务进度缓存。 + * @param {string} taskId 任务ID。 + * @return {Promise} 任务缓存,未命中返回 null。 + */ + async getExportTaskProgress(taskId = '') { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.getCacheAsync !== 'function') { + return null; + } + + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (!this.isPlainObject(cached)) { + return null; + } + return cached; + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + this.ctx.logger.warn(`[returnUnpack.export] 读取导出任务缓存失败: ${errorMessage}`); + return null; + } + } + /** * 删除拆包单(删,后台管理,不限制状态)。 * diff --git a/app/service/systems/return_unpack.js b/app/service/systems/return_unpack.js index e2d7556..00d986f 100644 --- a/app/service/systems/return_unpack.js +++ b/app/service/systems/return_unpack.js @@ -1,7 +1,18 @@ 'use strict'; +const crypto = require('node:crypto'); +const fs = require('node:fs'); +const fsp = require('node:fs/promises'); +const os = require('node:os'); +const path = require('node:path'); +const ExcelJS = require('exceljs'); const Service = require('egg').Service; +/** 退回拆包导出主表分页拉取大小 */ +const RETURN_UNPACK_EXPORT_PAGE_SIZE = 500; +/** 退回拆包导出明细分批拉取大小 */ +const RETURN_UNPACK_DETAIL_BATCH_SIZE = 100; + /** * 退回拆包模块业务逻辑层。 * 负责 wms_return_unpack(主表)/ wms_return_unpack_detail(明细)/ wms_return_unpack_video(视频)/ @@ -950,6 +961,431 @@ class ReturnUnpackService extends Service { }; } + /** + * 导出退回拆包数据(双 Sheet:正常退回运单号列表 + 明细表)。 + * 复用 list 的 where/sort 语义;仓库隔离由方法层注入 warehouse_id,此处再强制兑底; + * 分页拉取主表全量数据后批量关联明细/货主名称/快递类型,流式生成 Excel 并上传。 + * + * @param {Object} options 导出选项。 + * @param {Object} [options.where] 标准化 where 条件(与 list 一致)。 + * @param {Object} [options.sort] 排序参数(与 list 一致)。 + * @param {number} [options.warehouseId] 仓库ID(由方法层从上下文注入)。 + * @param {Function} [options.onProgress] 进度回调。 + * @return {Promise} 上传结果与统计信息(含 url/cdnUrl/cosUrl/fileKey/current_count/total_count/total_details/sheet_count, + * url 优先取上传服务返回的完整 URL,兜底取落库记录 file_url/fileUrl,最后才回退 COS key)。 + */ + async exportUnpack(options = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const safeOptions = options && typeof options === 'object' && !Array.isArray(options) ? options : {}; + const where = safeOptions.where && typeof safeOptions.where === 'object' ? { ...safeOptions.where } : {}; + const sort = safeOptions.sort && typeof safeOptions.sort === 'object' ? { ...safeOptions.sort } : {}; + const warehouseId = Number(safeOptions.warehouseId || 0); + const progressHandler = typeof safeOptions.onProgress === 'function' + ? safeOptions.onProgress + : async () => {}; + + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + throw this.createBusinessError('缺少仓库上下文', 400); + } + + // 复用 list 的 where/sort 语义,并强制仓库隔离(服务端注入,前端无需传 warehouse_id) + const queryWhere = this._buildListWhere(where, Op); + queryWhere.warehouse_id = warehouseId; + const order = this._buildListOrder(sort, 'return_unpack'); + + const totalCount = await ctx.model.ReturnUnpack.count({ where: queryWhere }); + + await progressHandler({ + status: 'running', + progress: totalCount > 0 ? 10 : 85, + currentCount: 0, + totalCount, + message: totalCount > 0 ? `已命中 ${totalCount} 条拆包单,开始导出` : '未命中数据,开始生成空文件', + }); + + // ---- 分页拉取主表全量数据 ---- + const allUnpackRows = []; + let page = 1; + while (allUnpackRows.length < totalCount) { + const rows = await ctx.model.ReturnUnpack.findAll({ + where: queryWhere, + order, + limit: RETURN_UNPACK_EXPORT_PAGE_SIZE, + offset: (page - 1) * RETURN_UNPACK_EXPORT_PAGE_SIZE, + raw: true, + }); + if (!Array.isArray(rows) || rows.length === 0) { + break; + } + allUnpackRows.push(...rows); + page += 1; + await progressHandler({ + status: 'running', + progress: Math.min(30, 10 + Math.round((allUnpackRows.length / Math.max(totalCount, 1)) * 20)), + currentCount: allUnpackRows.length, + totalCount, + message: `正在拉取拆包单列表,已完成 ${allUnpackRows.length}/${totalCount}`, + }); + } + + // ---- 批量拉取明细(按 unpack_id 分批) ---- + const unpackIds = allUnpackRows + .map(row => Number(row.id)) + .filter(id => Number.isInteger(id) && id > 0); + /** @type {Map>} */ + const detailsMap = new Map(); + if (unpackIds.length > 0) { + const totalBatches = Math.ceil(unpackIds.length / RETURN_UNPACK_DETAIL_BATCH_SIZE); + for (let batchIdx = 0; batchIdx < unpackIds.length; batchIdx += RETURN_UNPACK_DETAIL_BATCH_SIZE) { + const batchIds = unpackIds.slice(batchIdx, batchIdx + RETURN_UNPACK_DETAIL_BATCH_SIZE); + const details = await ctx.model.ReturnUnpackDetail.findAll({ + where: { unpack_id: { [Op.in]: batchIds } }, + order: [[ 'unpack_id', 'ASC' ], [ 'id', 'ASC' ]], + raw: true, + }); + for (const detail of details) { + const key = Number(detail.unpack_id); + if (!detailsMap.has(key)) { + detailsMap.set(key, []); + } + detailsMap.get(key).push(detail); + } + const currentBatch = Math.floor(batchIdx / RETURN_UNPACK_DETAIL_BATCH_SIZE) + 1; + await progressHandler({ + status: 'running', + progress: Math.min(50, 30 + Math.round((currentBatch / totalBatches) * 20)), + currentCount: allUnpackRows.length, + totalCount, + message: `正在拉取拆包明细,已完成批次 ${currentBatch}/${totalBatches}`, + }); + } + } + const totalDetails = allUnpackRows.reduce( + (sum, row) => sum + (detailsMap.get(Number(row.id)) || []).length, + 0 + ); + + // ---- 批量解析货主名称与快递类型 ---- + const storeNameMap = await this._resolveStoreNameMap(allUnpackRows, Op); + const expressNameMap = await this._resolveExpressNameMap(allUnpackRows, Op); + + await progressHandler({ + status: 'running', + progress: 55, + currentCount: allUnpackRows.length, + totalCount, + message: '正在生成 Excel 文件...', + }); + + // ---- 生成 Excel(流式写入,两个 Sheet) ---- + const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'wms-return-unpack-export-')); + const now = new Date(); + const dateToken = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}`; + const filename = `退回拆包导出_${dateToken}.xlsx`; + const filePath = path.join(tempDir, filename); + const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({ + filename: filePath, + useStyles: false, + useSharedStrings: false, + }); + + const normalizeCellValue = value => { + if (value === null || value === undefined) return ''; + if (value instanceof Date) return app.formatDate ? app.formatDate(value) : value.toISOString(); + return value; + }; + const formatDateOnly = value => (value ? app.formatDate(value, 'YYYY-MM-DD') : ''); + const formatDateTime = value => (value ? app.formatDate(value) : ''); + + try { + // Sheet 1: 正常退回运单号列表 + const sheet1 = workbook.addWorksheet('正常退回运单号列表'); + const mainColumns = [ + { header: '货主', key: 'store_name', width: 20 }, + { header: '快递号', key: 'waybill_code', width: 22 }, + { header: '商品类数', key: 'total_items', width: 12 }, + { header: '商品总数', key: 'total_quantity', width: 12 }, + { header: '记录人员', key: 'unpacker_name', width: 14 }, + { header: '记录日期', key: 'unpack_date', width: 14 }, + { header: '开始时间', key: 'start_time', width: 20 }, + { header: '结束时间', key: 'end_time', width: 20 }, + { header: '是否原单', key: 'is_original_return', width: 10 }, + { header: '快递类型', key: 'express', width: 14 }, + { header: '自定义店铺', key: 'shop_name', width: 20 }, + { header: '平台单号', key: 'source_order_codes', width: 24 }, + ]; + sheet1.columns = mainColumns; + + for (const row of allUnpackRows) { + const storeId = Number(row.store_id || 0); + const expressId = Number(row.order_express_id || 0); + sheet1.addRow({ + store_name: normalizeCellValue(storeId > 0 ? (storeNameMap.get(storeId) || '') : ''), + waybill_code: normalizeCellValue(row.waybill_code), + total_items: row.total_items, + total_quantity: row.total_quantity, + unpacker_name: normalizeCellValue(row.unpacker_name), + unpack_date: formatDateOnly(row.unpack_date), + start_time: formatDateTime(row.start_time), + end_time: formatDateTime(row.end_time), + is_original_return: row.order_express_id ? '是' : '否', + express: normalizeCellValue(expressId > 0 ? (expressNameMap.get(expressId) || '') : ''), + shop_name: normalizeCellValue(row.shop_name), + source_order_codes: normalizeCellValue(row.source_order_codes), + }).commit(); + } + sheet1.commit(); + + await progressHandler({ + status: 'running', + progress: 70, + currentCount: allUnpackRows.length, + totalCount, + message: '正在写入拆包明细...', + }); + + // Sheet 2: 明细表 + const sheet2 = workbook.addWorksheet('明细表'); + const detailColumns = [ + { header: '货主', key: 'store_name', width: 20 }, + { header: '快递号', key: 'waybill_code', width: 22 }, + { header: '商品名称', key: 'item_name', width: 24 }, + { header: '商品编码', key: 'item_code', width: 18 }, + { header: '条码', key: 'barcode', width: 20 }, + { header: '颜色', key: 'color', width: 12 }, + { header: '规格', key: 'spec', width: 20 }, + { header: '数量', key: 'quantity', width: 10 }, + { header: '是否残次', key: 'is_damaged', width: 10 }, + { header: '记录人员ID', key: 'unpacker_id', width: 14 }, + { header: '记录日期', key: 'unpack_date', width: 14 }, + { header: '备注', key: 'remark', width: 30 }, + { header: '是否原单', key: 'is_original_return', width: 10 }, + { header: '快递类型', key: 'express', width: 14 }, + { header: '自定义店铺', key: 'shop_name', width: 20 }, + { header: '平台单号', key: 'source_order_codes', width: 24 }, + ]; + sheet2.columns = detailColumns; + + let detailWrittenCount = 0; + for (const row of allUnpackRows) { + const storeId = Number(row.store_id || 0); + const expressId = Number(row.order_express_id || 0); + const storeName = storeId > 0 ? (storeNameMap.get(storeId) || '') : ''; + const expressName = expressId > 0 ? (expressNameMap.get(expressId) || '') : ''; + const details = detailsMap.get(Number(row.id)) || []; + for (const detail of details) { + sheet2.addRow({ + store_name: normalizeCellValue(storeName), + waybill_code: normalizeCellValue(row.waybill_code), + item_name: normalizeCellValue(detail.item_name), + item_code: normalizeCellValue(detail.item_code), + barcode: normalizeCellValue(detail.barcode), + color: this._extractDetailColor(detail), + spec: normalizeCellValue(detail.spec), + quantity: detail.quantity, + is_damaged: detail.product_status === 'damaged' ? '是' : '否', + unpacker_id: row.unpacker_id, + unpack_date: formatDateOnly(row.unpack_date), + remark: normalizeCellValue(detail.remark), + is_original_return: row.order_express_id ? '是' : '否', + express: normalizeCellValue(expressName), + shop_name: normalizeCellValue(row.shop_name), + source_order_codes: normalizeCellValue(row.source_order_codes), + }).commit(); + } + detailWrittenCount += 1; + if (detailWrittenCount % RETURN_UNPACK_DETAIL_BATCH_SIZE === 0 || detailWrittenCount === allUnpackRows.length) { + await progressHandler({ + status: 'running', + progress: Math.min(90, 70 + Math.round((detailWrittenCount / Math.max(allUnpackRows.length, 1)) * 20)), + currentCount: allUnpackRows.length, + totalCount, + message: `正在写入拆包明细,已完成 ${detailWrittenCount}/${allUnpackRows.length} 条拆包单`, + }); + } + } + sheet2.commit(); + + await workbook.commit(); + + await progressHandler({ + status: 'running', + progress: 92, + currentCount: allUnpackRows.length, + totalCount, + message: '正在上传文件...', + }); + + // ---- 上传文件 ---- + const uploadService = ctx?.service?.systems?.upload; + if (!uploadService || typeof uploadService.uploadFile !== 'function') { + throw new Error('上传服务不可用'); + } + + const stat = await fsp.stat(filePath); + const randomToken = crypto.randomBytes(6).toString('hex'); + const uploadKey = `exports/return_unpack/${warehouseId}/${Date.now()}_${randomToken}.xlsx`; + const uploadStream = fs.createReadStream(filePath); + uploadStream.filename = filename; + uploadStream.mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; + uploadStream.fileSize = stat.size; + + const uploadResult = await uploadService.uploadFile(uploadStream, { + key: uploadKey, + category: 'document', + mimetype: 'xls,xlsx,csv', + }); + + let fileRecord = null; + if (typeof uploadService.uploadSuccessNotify === 'function') { + fileRecord = await uploadService.uploadSuccessNotify({ + url: uploadResult.fileName, + fileKey: uploadResult.fileName, + fileName: filename, + fileType: 'document', + mimeType: uploadStream.mimeType, + fileSize: stat.size, + userId: ctx.userId, + description: `退回拆包导出(仓库${warehouseId}),共${totalCount}条拆包单`, + }); + } + + // 优先取 uploadFile 返回的完整 URL,其次取 uploadSuccessNotify 落库记录(兼容 data 包裹),最后才回退 COS key + const safeUploadResult = typeof uploadResult === 'object' && uploadResult !== null ? uploadResult : {}; + const resolvedFileRecord = (fileRecord && (fileRecord.data || fileRecord)) || null; + const fileUrlFromRecord = resolvedFileRecord + ? (resolvedFileRecord.file_url || resolvedFileRecord.fileUrl || resolvedFileRecord.url || '') + : ''; + const uploadResultUrl = safeUploadResult.url || safeUploadResult.cdnUrl || safeUploadResult.cosUrl || ''; + + const uploadInfo = { + filename, + fileKey: safeUploadResult.fileName || uploadKey, + url: uploadResultUrl || fileUrlFromRecord || safeUploadResult.fileName || uploadKey, + cdnUrl: safeUploadResult.cdnUrl || safeUploadResult.url || '', + cosUrl: safeUploadResult.cosUrl || '', + current_count: allUnpackRows.length, + total_count: totalCount, + total_details: totalDetails, + sheet_count: 2, + }; + + await progressHandler({ + status: 'success', + progress: 100, + currentCount: allUnpackRows.length, + totalCount, + message: '导出任务完成', + result: uploadInfo, + }); + + return uploadInfo; + } catch (error) { + const workbookStream = workbook.stream; + if (workbookStream && typeof workbookStream.destroy === 'function') { + workbookStream.destroy(); + } + throw error; + } finally { + // 清理临时文件(不存在或删除失败均忽略) + try { await fsp.rm(tempDir, { recursive: true, force: true }); } catch (err) { /* ignore */ } + } + } + + /** + * 批量解析货主名称映射(store_id → wms_store.company_name)。 + * @param {Array} rows 主表行数组。 + * @param {Object} Op Sequelize Op 对象。 + * @return {Promise>} store_id → 货主名称映射。 + */ + async _resolveStoreNameMap(rows = [], Op) { + const { ctx } = this; + const storeIds = [ ...new Set( + (Array.isArray(rows) ? rows : []) + .map(row => Number(row && row.store_id || 0)) + .filter(id => Number.isInteger(id) && id > 0) + ) ]; + /** @type {Map} */ + const nameMap = new Map(); + if (storeIds.length === 0) { + return nameMap; + } + try { + const stores = await ctx.model.Store.findAll({ + where: { id: { [Op.in]: storeIds } }, + attributes: [ 'id', 'company_name' ], + raw: true, + }); + for (const store of stores) { + nameMap.set(Number(store.id), store.company_name ? String(store.company_name) : ''); + } + } catch (err) { + ctx.logger.warn(`[returnUnpack.export] 批量解析货主名称失败: ${err.message}`); + } + return nameMap; + } + + /** + * 批量解析快递类型映射(order_express_id → wms_order_express.logistics_name)。 + * @param {Array} rows 主表行数组。 + * @param {Object} Op Sequelize Op 对象。 + * @return {Promise>} order_express_id → 快递类型映射。 + */ + async _resolveExpressNameMap(rows = [], Op) { + const { ctx } = this; + const expressIds = [ ...new Set( + (Array.isArray(rows) ? rows : []) + .map(row => Number(row && row.order_express_id || 0)) + .filter(id => Number.isInteger(id) && id > 0) + ) ]; + /** @type {Map} */ + const nameMap = new Map(); + if (expressIds.length === 0) { + return nameMap; + } + try { + const expresses = await ctx.model.OrderExpress.findAll({ + where: { id: { [Op.in]: expressIds } }, + attributes: [ 'id', 'logistics_name' ], + raw: true, + }); + for (const express of expresses) { + nameMap.set(Number(express.id), express.logistics_name ? String(express.logistics_name) : ''); + } + } catch (err) { + ctx.logger.warn(`[returnUnpack.export] 批量解析快递类型失败: ${err.message}`); + } + return nameMap; + } + + /** + * 从明细快照/规格中提取颜色(优先 product_snapshot.sku_property,兜底 spec 字段)。 + * 颜色约定以「颜色:xxx」形式出现在 SKU 规格串中,未命中返回空字符串。 + * @param {Object} detail 明细行。 + * @return {string} 颜色文本,未命中返回空字符串。 + */ + _extractDetailColor(detail = {}) { + let spec = detail && detail.spec ? String(detail.spec) : ''; + const snapshot = detail && detail.product_snapshot; + if (snapshot) { + try { + const parsed = typeof snapshot === 'string' ? JSON.parse(snapshot) : snapshot; + if (parsed && typeof parsed === 'object' && !Array.isArray(parsed) && parsed.sku_property) { + spec = String(parsed.sku_property); + } + } catch (err) { + // 快照解析失败时退回 spec 字段 + } + } + const normalized = String(spec || '').trim(); + if (!normalized) { + return ''; + } + const match = normalized.match(/颜色[::]\s*([^;;,,]+)/); + return match && match[1] ? String(match[1]).trim() : ''; + } + /** * 查询拆包单详情:主表 + 明细 + 视频 + 退回收到单 + 原订单详情(原单退回时)。 * @@ -1741,11 +2177,13 @@ class ReturnUnpackService extends Service { /** * 生成拆包单号(原子取号)。 * 格式:RP + YYYYMMDD + 6位序号(如 RP20260813000001)。 - * 取号基于序列表 wms_number_sequence 的单条 upsert 原子递增: - * INSERT ... VALUES (LAST_INSERT_ID(:seed + 1)) ON DUPLICATE KEY UPDATE - * current_seq = LAST_INSERT_ID(GREATEST(current_seq, :seed) + 1) + * 取号基于序列表 wms_number_sequence 的 upsert 原子递增(唯一键 uk_warehouse_biz_date 串行化并发事务): + * INSERT ... VALUES (:seed + 1) ON DUPLICATE KEY UPDATE + * current_seq = GREATEST(current_seq, :seed) + 1 * 其中 :seed 为当日主表已有最大序号,保证历史数据对齐(首日启用不撞已有单号); - * 同事务(同连接)内回读 LAST_INSERT_ID() 取回本次分配序号,并发下无撞号。 + * upsert 后通过带锁当前读(SELECT ... FOR UPDATE)回读 current_seq, + * 避免 REPEATABLE READ 快照读读到旧值导致撞号或跳号。 + * 注意:不再依赖 LAST_INSERT_ID() 回读,因为 fresh INSERT 时其会被序列表自增主键覆盖。 * * @param {number} warehouseId 仓库ID。 * @return {Promise} 拆包单号。 @@ -1774,25 +2212,31 @@ class ReturnUnpackService extends Service { ); const seed = Number(seedRows && seedRows[0] && seedRows[0].max_seq) || 0; - // 原子取号:单条 upsert 内递增并设置连接级 LAST_INSERT_ID + // 原子取号:单条 upsert 内按唯一键串行化并发事务递增 current_seq await ctx.model.query( `INSERT INTO wms_number_sequence (warehouse_id, biz_type, date_part, current_seq, created_at, updated_at) - VALUES (:warehouseId, :bizType, :datePart, LAST_INSERT_ID(:seed + 1), NOW(), NOW()) - ON DUPLICATE KEY UPDATE current_seq = LAST_INSERT_ID(GREATEST(current_seq, :seed) + 1), updated_at = NOW()`, + VALUES (:warehouseId, :bizType, :datePart, :seed + 1, NOW(), NOW()) + ON DUPLICATE KEY UPDATE current_seq = GREATEST(current_seq, :seed) + 1, updated_at = NOW()`, { replacements: { warehouseId, bizType, datePart, seed }, transaction, } ); + // 带锁当前读回读:同事务已通过 upsert 持有该行排他锁(或经唯一键冲突等待串行化), + // FOR UPDATE 返回本事务最新写入值或最新提交版本,不受旧快照影响 const rows = await ctx.model.query( - 'SELECT LAST_INSERT_ID() AS seq', + `SELECT current_seq + FROM wms_number_sequence + WHERE warehouse_id = :warehouseId AND biz_type = :bizType AND date_part = :datePart + FOR UPDATE`, { + replacements: { warehouseId, bizType, datePart }, type: ctx.model.QueryTypes.SELECT, transaction, } ); - return Number(rows && rows[0] && rows[0].seq) || 1; + return Number(rows && rows[0] && rows[0].current_seq) || 1; }); if (sequence > 999999) { From 21899110734a764d4668258bffaa6ea6331e45fb Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sun, 30 Aug 2026 07:28:12 +0800 Subject: [PATCH 296/550] =?UTF-8?q?fix(order):=20=E8=BF=90=E5=8D=95?= =?UTF-8?q?=E5=8F=B7=E6=A3=80=E7=B4=A2=E4=BC=98=E5=8C=96=EF=BC=88=E5=88=86?= =?UTF-8?q?=E6=AE=B5=E5=90=8E=E7=BC=80=E5=89=A5=E7=A6=BB=E7=AD=89=E5=80=BC?= =?UTF-8?q?=E5=8C=B9=E9=85=8D=E3=80=81=E7=9F=AD=E8=AF=8D=E7=A6=81=E9=99=8D?= =?UTF-8?q?=E7=BA=A7=E3=80=81=E6=95=B0=E7=BB=84=E7=B2=BE=E7=A1=AE=E5=8C=B9?= =?UTF-8?q?=E9=85=8D=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/lib/waybill_code.js | 35 +++++++++++ .../systemMethods/order/deliveryOrder.js | 15 ++++- app/service/systems/order_packing.js | 58 +++++++++++++++---- app/service/systems/waybill.js | 23 ++++++-- 4 files changed, 115 insertions(+), 16 deletions(-) create mode 100644 app/lib/waybill_code.js diff --git a/app/lib/waybill_code.js b/app/lib/waybill_code.js new file mode 100644 index 0000000..d5dee3c --- /dev/null +++ b/app/lib/waybill_code.js @@ -0,0 +1,35 @@ +'use strict'; + +/** + * 运单号公共工具。 + * 统一处理一单多件分段单号(如 JDX057941864338-1-1-)的包裹序号后缀剥离与 like 通配符转义, + * 保证「剥离后缀后主体运单号必须等值匹配」的业务规则在各扫描入口保持一致。 + */ + +/** + * 剥离运单号尾部的包裹序号段(一单多件分段格式:-包裹序号-总件数[-])。 + * 例如 'JDX057941864338-1-1-' → 'JDX057941864338'; + * 'JDX057941864338' 无分段后缀时原样返回。 + * + * @param {string} waybillCode 运单号 + * @return {string} 剥离分段后缀后的主体运单号 + */ +function stripWaybillSegmentSuffix(waybillCode) { + return String(waybillCode || '').trim().replace(/(?:-\d+){2,}-?$/, ''); +} + +/** + * 转义 like 匹配中的通配符(% _ \),避免用户输入中的特殊字符扩大匹配范围。 + * 用于「主体运单号 + -%」前缀匹配场景,确保主体部分被等值比较。 + * + * @param {string} value 待转义的字符串 + * @return {string} 转义后的字符串 + */ +function escapeLikeWildcards(value) { + return String(value || '').replace(/[%_\\]/g, m => `\\${m}`); +} + +module.exports = { + stripWaybillSegmentSuffix, + escapeLikeWildcards, +}; diff --git a/app/service/systemMethods/order/deliveryOrder.js b/app/service/systemMethods/order/deliveryOrder.js index 6e70925..d2272ea 100644 --- a/app/service/systemMethods/order/deliveryOrder.js +++ b/app/service/systemMethods/order/deliveryOrder.js @@ -3,6 +3,7 @@ const OrderBaseService = require('./base'); const fs = require('fs'); const path = require('path'); +const { stripWaybillSegmentSuffix, escapeLikeWildcards } = require('../../../lib/waybill_code'); const DEBUG_LOG = path.join(__dirname, '..', '..', '..', '..', 'temp', 'quickSearch_debug.log'); @@ -62,7 +63,8 @@ class DeliveryOrderService extends OrderBaseService { /** * 订单快速搜索。 - * 跨表联合搜索:运单号(wms_order_express,精确)、发货单号/外部订单号/平台交易单号(dispatch 表,模糊)。 + * 跨表联合搜索:运单号(wms_order_express,精确匹配,含剥离一单多件分段后缀后的主体等值匹配)、 + * 发货单号/外部订单号/平台交易单号(dispatch 表,模糊)。 * 返回匹配的订单列表(最多 20 条),包含订单关键信息及关联运单号。 * * @param {Object} data 请求体。 @@ -96,10 +98,19 @@ class DeliveryOrderService extends OrderBaseService { // ====== 第一步:express 表 OR 搜索 ====== dbg('--- Step1: express OR query ---'); + // 业务规则:运单号先剥离一单多件包裹序号后缀(如 -1-1-),主体必须等值匹配, + // 不得落入模糊 like;发货单号/平台交易单号保留模糊匹配能力 + const waybillBase = stripWaybillSegmentSuffix(keyword); + const escapedWaybillBase = escapeLikeWildcards(waybillBase); + const waybillConditions = [ + { waybill_code: keyword }, + ...(waybillBase !== keyword ? [{ waybill_code: waybillBase }] : []), + ...(escapedWaybillBase ? [{ waybill_code: { [Op.like]: `${escapedWaybillBase}-%` } }] : []), + ]; const expressWhere = { warehouse_id: warehouseId, [Op.or]: [ - { waybill_code: keyword }, + ...waybillConditions, { delivery_order_code: { [Op.like]: `%${keyword}%` } }, { source_order_codes: { [Op.like]: `%${keyword}%` } }, ], diff --git a/app/service/systems/order_packing.js b/app/service/systems/order_packing.js index 6fd3096..46c3f78 100644 --- a/app/service/systems/order_packing.js +++ b/app/service/systems/order_packing.js @@ -1,6 +1,15 @@ 'use strict'; const Service = require('egg').Service; +const { stripWaybillSegmentSuffix, escapeLikeWildcards } = require('../../lib/waybill_code'); + +/** + * 快捷搜索运单号模糊降级的最小关键词长度。 + * 运单号通常较长(如 JDX057941864338),短于该长度的输入(如单字符 "7")没有模糊搜索意义, + * 且 %短词% 极易误命中海量历史单号(实测 "7" 可命中 24149 行), + * 违背「不完整短串不得命中订单」的业务约束,因此禁止短词降级进入 %kw% 模糊分支。 + */ +const QUICK_WHERE_WAYBILL_FUZZY_MIN_LENGTH = 4; /** * 打包任务服务层(仓库侧)。 @@ -48,11 +57,11 @@ class OrderPackingService extends Service { * @param {Object} where 筛选条件对象 * @param {Object} [where.status] 任务状态:0=待处理 1=打包中 2=已完成 3=异常 * @param {Object} [where.pack_mode] 打包模式:1=散单 2=团购 - * @param {Object} [where.waybill_code] 运单号(通过 wms_order_express 解析 order_id 后过滤,支持 eq/like) + * @param {Object} [where.waybill_code] 运单号(通过 wms_order_express 解析 order_id 后过滤;先剥离一单多件分段后缀,主体运单号等值匹配) * @param {Object} [where.wave_no] 波次号(模糊匹配) * @param {Object} [where.order_id] 订单ID(精确匹配) * @param {Object} [where.workbench_id] 工作台ID(精确匹配) - * @param {Object} [where.quickWhere] 快捷搜索:支持波次号模糊匹配;运单号通过 express→order→wave 链路解析(团购按波次号查、散单按订单ID查) + * @param {Object} [where.quickWhere] 快捷搜索:支持波次号模糊匹配;运单号通过 express→order→wave 链路解析(团购按波次号查、散单按订单ID查;运单号先剥离分段后缀等值匹配,精确未命中且关键词长度≥4 时才降级模糊,短词禁止降级避免误命中) * @param {Object} [where.start_time] 开始打包时间范围,支持 {operator:'between', value:[start,end]} * @param {Object} [where.start_time_start] 开始打包时间起始(兼容旧写法) * @param {Object} [where.start_time_end] 开始打包时间结束(兼容旧写法) @@ -102,20 +111,25 @@ class OrderPackingService extends Service { } // 运单号筛选:通过 wms_order_express 表解析 order_id,再按 order_id 过滤(wms_pack_task.waybill_code 通常为空) + // 业务规则:先剥离一单多件包裹序号后缀(如 -1-1-),剩余主体运单号必须等值匹配,不得落入模糊 like 分支 if (where.waybill_code) { const waybillValue = where.waybill_code?.value ?? where.waybill_code; - const waybillOperator = (where.waybill_code?.operator || 'like').toLowerCase(); if (waybillValue && String(waybillValue).trim()) { const trimmedValue = String(waybillValue).trim(); + // 剥离分段后缀得到主体运单号(JDX057941864338-1-1- → JDX057941864338) + const baseWaybill = stripWaybillSegmentSuffix(trimmedValue); + const escapedBase = escapeLikeWildcards(baseWaybill); + // 等值匹配集合:完整单号等值 + 主体单号等值 + 主体单号前缀段(主体相同、分段序号不同) + const waybillConditions = [ + { waybill_code: trimmedValue }, + ...(baseWaybill !== trimmedValue ? [{ waybill_code: baseWaybill }] : []), + ...(escapedBase ? [{ waybill_code: { [Op.like]: `${escapedBase}-%` } }] : []), + ]; const expressWhere = { warehouse_id: warehouseId, delete_at: null, + [Op.or]: waybillConditions, }; - if (waybillOperator === 'eq') { - expressWhere.waybill_code = trimmedValue; - } else { - expressWhere.waybill_code = { [Op.like]: `%${trimmedValue}%` }; - } const expressRecords = await ctx.model.OrderExpress.findAll({ where: expressWhere, attributes: [ 'order_id' ], @@ -167,15 +181,39 @@ class OrderPackingService extends Service { // 2. 运单号解析:express → order → wave // 团购波次 → 按 wave_no 查 packing 表;散单 → 按 order_id 查 packing 表 - const expressRecords = await ctx.model.OrderExpress.findAll({ + // 业务规则:先剥离包裹序号后缀(如 -1-1-),主体运单号等值匹配为最高优先级; + // 精确未命中时才降级为模糊 like,保留快捷搜索能力 + const baseKw = stripWaybillSegmentSuffix(kw); + const escapedKw = escapeLikeWildcards(baseKw); + const exactWaybillConditions = [ + { waybill_code: kw }, + ...(baseKw !== kw ? [{ waybill_code: baseKw }] : []), + ...(escapedKw ? [{ waybill_code: { [Op.like]: `${escapedKw}-%` } }] : []), + ]; + let expressRecords = await ctx.model.OrderExpress.findAll({ where: { - waybill_code: { [Op.like]: `%${kw}%` }, + [Op.or]: exactWaybillConditions, warehouse_id: warehouseId, delete_at: null, }, attributes: [ 'order_id' ], raw: true, }); + // 精确未命中 → 降级为模糊匹配(兼容快捷搜索输入非完整运单号的场景) + // 关键词校验:短词(trim 后长度小于 QUICK_WHERE_WAYBILL_FUZZY_MIN_LENGTH,含纯单字符) + // 禁止降级进入 %kw% 模糊分支——运单号通常较长,%短词% 极易误命中大量历史单号, + // 违背「不完整短串不得命中订单」的业务约束,此时运单号解析保持空结果 + if (expressRecords.length === 0 && kw.length >= QUICK_WHERE_WAYBILL_FUZZY_MIN_LENGTH) { + expressRecords = await ctx.model.OrderExpress.findAll({ + where: { + waybill_code: { [Op.like]: `%${kw}%` }, + warehouse_id: warehouseId, + delete_at: null, + }, + attributes: [ 'order_id' ], + raw: true, + }); + } if (expressRecords.length > 0) { const orderIds = [ ...new Set(expressRecords.map(r => r.order_id).filter(Boolean)) ]; diff --git a/app/service/systems/waybill.js b/app/service/systems/waybill.js index 3116243..9b05dfc 100644 --- a/app/service/systems/waybill.js +++ b/app/service/systems/waybill.js @@ -154,7 +154,7 @@ class WaybillService extends MainService { * 主单号通过 SELF JOIN 同 order_id 下 business_key=1 的记录获取。 * * @param {Object} [options={}] 查询参数。 - * @param {Object} [options.where] 筛选条件,支持 waybillCode / mainWaybillCode / orderId / orderNo / logisticsCode / logisticsInterfaceId / platformCode / status / isBack / isIntercept / isGalaxyReceive / packageMaterialId / hasWeighingWeight / keyword / createdAt({operator:'between', value:[start,end]},兼容 createAt 别名)/ createdAtStart / createdAtEnd(旧写法兼容)。 + * @param {Object} [options.where] 筛选条件,支持 waybillCode(字符串模糊匹配 / 字符串数组精确匹配)/ mainWaybillCode / orderId / orderNo / logisticsCode / logisticsInterfaceId / platformCode / status / isBack / isIntercept / isGalaxyReceive / packageMaterialId / hasWeighingWeight / keyword / createdAt({operator:'between', value:[start,end]},兼容 createAt 别名)/ createdAtStart / createdAtEnd(旧写法兼容)。 * @param {Object} [options.pagination] 分页参数 { page, pageSize },默认 page=1, pageSize=20。 * @param {Object} [options.sort] 排序参数 { field, order },默认 create_at desc。 * @return {Promise} 运单列表与分页信息 { list, pagination }。 @@ -222,9 +222,16 @@ class WaybillService extends MainService { } } - // 运单号模糊搜索 + // 运单号搜索:数组精确匹配(Op.in),字符串保持模糊匹配(Op.like) const waybillCode = val(where.waybillCode); - if (waybillCode && String(waybillCode).trim()) { + if (Array.isArray(waybillCode)) { + const waybillCodeList = waybillCode + .map(item => (item === undefined || item === null ? '' : String(item).trim())) + .filter(item => item !== ''); + if (waybillCodeList.length > 0) { + queryWhere.waybill_code = { [Op.in]: waybillCodeList }; + } + } else if (waybillCode && String(waybillCode).trim()) { queryWhere.waybill_code = { [Op.like]: `%${String(waybillCode).trim()}%` }; } @@ -756,8 +763,16 @@ class WaybillService extends MainService { } } + // 运单号搜索:数组精确匹配(Op.in),字符串保持模糊匹配(Op.like),与 list 保持一致 const waybillCodeExport = val(where.waybillCode); - if (waybillCodeExport && String(waybillCodeExport).trim()) { + if (Array.isArray(waybillCodeExport)) { + const waybillCodeListExport = waybillCodeExport + .map(item => (item === undefined || item === null ? '' : String(item).trim())) + .filter(item => item !== ''); + if (waybillCodeListExport.length > 0) { + queryWhere.waybill_code = { [Op.in]: waybillCodeListExport }; + } + } else if (waybillCodeExport && String(waybillCodeExport).trim()) { queryWhere.waybill_code = { [Op.like]: `%${String(waybillCodeExport).trim()}%` }; } const orderIdExport = val(where.orderId); From 3442ed52432e803434720a1db9b87399bae07563 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sun, 30 Aug 2026 07:28:17 +0800 Subject: [PATCH 297/550] =?UTF-8?q?fix(order):=20=E6=B3=A2=E6=AC=A1?= =?UTF-8?q?=E5=8F=96=E5=8F=B7=E5=8E=9F=E5=AD=90=E6=80=A7=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/systemMethods/order/wave.js | 28 ++++++++++++++++++------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/app/service/systemMethods/order/wave.js b/app/service/systemMethods/order/wave.js index 63dd110..9f289ec 100644 --- a/app/service/systemMethods/order/wave.js +++ b/app/service/systemMethods/order/wave.js @@ -565,11 +565,13 @@ class WaveService extends OrderBaseService { /** * 获取当天前缀下的下一个波次序号(原子取号)。 * - * 基于序列表 wms_number_sequence 的单条 upsert 原子递增: - * INSERT ... VALUES (LAST_INSERT_ID(:seed + 1)) ON DUPLICATE KEY UPDATE - * current_seq = LAST_INSERT_ID(GREATEST(current_seq, :seed) + 1) + * 基于序列表 wms_number_sequence 的 upsert 原子递增(唯一键 uk_warehouse_biz_date 串行化并发事务): + * INSERT ... VALUES (:seed + 1) ON DUPLICATE KEY UPDATE + * current_seq = GREATEST(current_seq, :seed) + 1 * 其中 :seed 为当日该前缀主表已有最大序号,保证与历史编号对齐; - * 同事务(同连接)内回读 LAST_INSERT_ID() 取回本次分配序号,并发下不再撞号。 + * upsert 后通过带锁当前读(SELECT ... FOR UPDATE)回读 current_seq, + * 避免 REPEATABLE READ 快照读读到旧值导致撞号或跳号。 + * 注意:不再依赖 LAST_INSERT_ID() 回读,因为 fresh INSERT 时其会被序列表自增主键覆盖。 * * @param {string} prefix 波次编号前缀。 * @param {string} datePart 日期片段(YYYYMMDD)。 @@ -602,8 +604,8 @@ class WaveService extends OrderBaseService { // 原子取号:全局维度(warehouse_id=0)按「前缀+日期」递增,唯一键串行化并发事务 await this.ctx.model.query( `INSERT INTO wms_number_sequence (warehouse_id, biz_type, date_part, current_seq, created_at, updated_at) - VALUES (:warehouseId, :bizType, :datePart, LAST_INSERT_ID(:seed + 1), NOW(), NOW()) - ON DUPLICATE KEY UPDATE current_seq = LAST_INSERT_ID(GREATEST(current_seq, :seed) + 1), updated_at = NOW()`, + VALUES (:warehouseId, :bizType, :datePart, :seed + 1, NOW(), NOW()) + ON DUPLICATE KEY UPDATE current_seq = GREATEST(current_seq, :seed) + 1, updated_at = NOW()`, { replacements: { warehouseId: 0, @@ -615,14 +617,24 @@ class WaveService extends OrderBaseService { } ); + // 带锁当前读回读:同事务已通过 upsert 持有该行排他锁(或经唯一键冲突等待串行化), + // FOR UPDATE 返回本事务最新写入值或最新提交版本,不受旧快照影响 const seqRows = await this.ctx.model.query( - 'SELECT LAST_INSERT_ID() AS seq', + `SELECT current_seq + FROM wms_number_sequence + WHERE warehouse_id = :warehouseId AND biz_type = :bizType AND date_part = :datePart + FOR UPDATE`, { + replacements: { + warehouseId: 0, + bizType, + datePart: normalizedDatePart, + }, type: this.ctx.model.QueryTypes.SELECT, transaction, } ); - const sequence = Number(seqRows && seqRows[0] && seqRows[0].seq || 0); + const sequence = Number(seqRows && seqRows[0] && seqRows[0].current_seq || 0); if (!Number.isInteger(sequence) || sequence <= 0) { return 1; } From 7b0004a7e301fc8d5ac7293a109415f54777e434 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sun, 30 Aug 2026 07:28:21 +0800 Subject: [PATCH 298/550] =?UTF-8?q?perf(order):=20current=20=E5=88=86?= =?UTF-8?q?=E8=A1=A8=20wave=5Fid=20=E5=89=8D=E5=AF=BC=E7=B4=A2=E5=BC=95?= =?UTF-8?q?=E4=B8=8E=E6=A8=A1=E5=9E=8B=E9=A2=84=E6=9C=9F=E5=AE=9A=E4=B9=89?= =?UTF-8?q?=E5=90=8C=E6=AD=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/model/order_delivery_table_schema.js | 11 ++ ...-wave-id-index-to-order-delivery-shards.js | 133 ++++++++++++++++ ...queryorder-wave-index-optimization-plan.md | 148 ++++++++++++++++++ 3 files changed, 292 insertions(+) create mode 100644 database/migrations/20260830100000-add-wave-id-index-to-order-delivery-shards.js create mode 100644 docs/queryorder-wave-index-optimization-plan.md diff --git a/app/model/order_delivery_table_schema.js b/app/model/order_delivery_table_schema.js index 0ca9eff..f86252d 100644 --- a/app/model/order_delivery_table_schema.js +++ b/app/model/order_delivery_table_schema.js @@ -568,6 +568,17 @@ function buildIndexOptions(warehouseId, type) { name: `idx_${prefix}_hash_crc`, fields: [ 'items_hash', 'items_crc', 'warehouse_id' ], }, + // wave_id 前导索引仅 current 分表需要:dispatch 通过 baseIndexes 自动继承; + // history/outsourced 分表未在迁移中加该索引,模型不得生成预期定义, + // 否则运行时 drift 同步会向其自动补建索引,造成模型与实际库不一致。 + ...(modelType === MANAGED_TYPES.CURRENT + ? [ + { + name: `idx_${prefix}_wave_id`, + fields: [ 'wave_id' ], + }, + ] + : []), { name: `idx_${prefix}_wave`, fields: [ 'status', 'wave_id' ], diff --git a/database/migrations/20260830100000-add-wave-id-index-to-order-delivery-shards.js b/database/migrations/20260830100000-add-wave-id-index-to-order-delivery-shards.js new file mode 100644 index 0000000..9c3d221 --- /dev/null +++ b/database/migrations/20260830100000-add-wave-id-index-to-order-delivery-shards.js @@ -0,0 +1,133 @@ +'use strict'; + +/** + * queryOrder 波次计数性能优化:为 current/dispatch 分表增加 wave_id 前导索引。 + * + * 背景: + * - app/service/systems/workbench.js 的 _countWaveOrders 会对 current + dispatch 两族分表执行 + * `SELECT COUNT(*) FROM ... WHERE wave_id=? AND warehouse_id=?`; + * - 现有索引 `idx_{wh}_current_wave` 为 (status, wave_id),前导列 status 不在谓词中, + * 生产 dispatch 分表(约 25.38 万行 / 524MB)需全表扫描约 12.69 万行; + * - 本迁移动态枚举 `wms_order_delivery_{wh}` 与 `wms_order_delivery_{wh}_dispatch`, + * 为每张分表新增二级索引 `idx_{wh}_current_wave_id (wave_id)`。 + * + * 设计说明: + * - 分表按仓库隔离,warehouse_id 在单张分表内为常量,索引无需包含 warehouse_id; + * - 使用 ALGORITHM=INPLACE, LOCK=NONE(MySQL 5.6+ 支持在线加二级索引), + * 不重建表、不锁写,适合低峰期执行; + * - 幂等:索引已存在则跳过;索引命名与 app/model/order_delivery_table_schema.js + * 的 buildIndexOptions 即将补充的定义一致,避免应用运行时 drift 同步重复建索引。 + * + * ⚠️ 本文件为「未执行」草案,仅在用户完成风险确认后,通过迁移流程执行。 + */ + +const SHARD_PATTERNS = [ + { type: 'current', pattern: /^wms_order_delivery_(\d+)$/ }, + { type: 'dispatch', pattern: /^wms_order_delivery_(\d+)_dispatch$/ }, +]; + +/** + * 解析分表名。 + * @param {string} tableName 表名。 + * @return {{ type: string, warehouseId: string }|null} 解析结果。 + */ +function parseShardTableName(tableName) { + for (const item of SHARD_PATTERNS) { + const match = item.pattern.exec(tableName); + if (match) { + return { type: item.type, warehouseId: match[1] }; + } + } + return null; +} + +/** + * 构建 wave_id 前导索引名(与 buildIndexOptions 命名一致)。 + * @param {string} warehouseId 仓库ID。 + * @return {string} 索引名。 + */ +function buildWaveIdIndexName(warehouseId) { + return `idx_${warehouseId}_current_wave_id`; +} + +/** + * 列举库内所有 current/dispatch 分表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise>} 分表名列表。 + */ +async function listManagedShards(queryInterface) { + const [ rows ] = await queryInterface.sequelize.query( + 'SELECT TABLE_NAME AS tableName FROM INFORMATION_SCHEMA.TABLES ' + + 'WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME LIKE \'wms_order_delivery\\_%\' ' + + 'ORDER BY TABLE_NAME' + ); + return (rows || []) + .map(row => String(row.tableName || row.TABLE_NAME || '')) + .filter(name => parseShardTableName(name)); +} + +/** + * 判断索引是否已存在。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @param {string} indexName 索引名。 + * @return {Promise} 是否存在。 + */ +async function indexExists(queryInterface, tableName, indexName) { + const indexes = await queryInterface.showIndex(tableName); + return (indexes || []).some(index => { + const name = String(index && (index.name || index.Key_name || index.key_name) || ''); + return name.toLowerCase() === String(indexName).toLowerCase(); + }); +} + +module.exports = { + /** + * 执行迁移:为 current/dispatch 分表增加 wave_id 前导索引。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface) { + const shards = await listManagedShards(queryInterface); + const results = []; + + for (const tableName of shards) { + const parsed = parseShardTableName(tableName); + const indexName = buildWaveIdIndexName(parsed.warehouseId); + + if (await indexExists(queryInterface, tableName, indexName)) { + results.push({ tableName, action: 'skip', reason: 'exists' }); + continue; + } + + await queryInterface.sequelize.query( + `ALTER TABLE \`${tableName}\` ADD INDEX \`${indexName}\` (\`wave_id\`), ALGORITHM=INPLACE, LOCK=NONE` + ); + results.push({ tableName, action: 'added', indexName }); + } + + console.log('[20260830100000-add-wave-id-index] up results:', JSON.stringify(results)); + }, + + /** + * 回滚迁移:移除 wave_id 前导索引。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface) { + const shards = await listManagedShards(queryInterface); + + for (const tableName of shards) { + const parsed = parseShardTableName(tableName); + const indexName = buildWaveIdIndexName(parsed.warehouseId); + + if (!(await indexExists(queryInterface, tableName, indexName))) { + continue; + } + + await queryInterface.sequelize.query( + `ALTER TABLE \`${tableName}\` DROP INDEX \`${indexName}\`, ALGORITHM=INPLACE, LOCK=NONE` + ); + } + }, +}; diff --git a/docs/queryorder-wave-index-optimization-plan.md b/docs/queryorder-wave-index-optimization-plan.md new file mode 100644 index 0000000..d15d51d --- /dev/null +++ b/docs/queryorder-wave-index-optimization-plan.md @@ -0,0 +1,148 @@ +# queryOrder 波次计数性能优化方案(只读评估 + 方案文件,未执行) + +> 状态:**待用户风险确认**。本方案全程只读评估,未执行任何 DDL / 数据变更。 +> 编制:wms-db-agent|日期:2026-08-30 + +## 1. 背景与瓶颈定位 + +- 业务链路:工作台 queryOrder → `app/service/systems/workbench.js` + - `_countWaveOrders()`:对 current + dispatch 两族分表执行 `SELECT COUNT(*) WHERE wave_id=? AND warehouse_id=?` + - `_getWaveOrderIds()`:同谓词取订单 id 列表 +- 现状瓶颈(上一轮 DB agent 已定位 + 用户提供生产数据): + - 现有索引 `idx_{wh}_current_wave` 为 `(status, wave_id)`,前导列 `status` 不在谓词中; + - 生产 dispatch 分表约 **25.38 万行 / 524MB**,单次 COUNT 全表扫描约 **12.69 万行**;生产 MySQL **5.7.44**。 +- 关联问题:序列表 `wms_order_id_location_{wh}` 缺约 **12.4 万**存量订单 id 记录 → queryOrder 定位回退为分表遍历(见 §5)。 + +## 2. 分表索引生成机制 + +### 2.1 模型层定义 + +- `app/model/order_delivery_table_schema.js`: + - `buildIndexOptions(warehouseId, type)` 生成每张分表的索引列表; + - current 类型共 8 个索引,其中 `idx_{wh}_current_wave = (status, wave_id)`(瓶颈索引); + - dispatch 类型复用 current 的基础索引:`baseIndexes[0..2] + idx_dispatch_{wh}_dispatch_lane (dispatch_lane, status) + baseIndexes.slice(3)`,即 dispatch 分表同样继承 `idx_{wh}_current_wave`; + - `buildIndexLines()` 用于建表 DDL;`buildTableOptions()` 供动态模型 define。 +- 基表模型 `app/model/order_delivery.js` 自带索引列表(`wave_id = (status, wave_id)` 等)——基表 `wms_order_delivery` 非分表,**不在本次范围**(可选加,默认不加)。 + +### 2.2 运行时 drift 同步(⚠️ 关键风险) + +- `app/model/order_delivery_factory.js`:`getOrCreateModel` → `ensureManagedTableSchema` → `needsTableSchemaSync`(比对期望索引)→ `alterManagedTableSchema`(**只补缺失索引、不删已有索引**)。 +- 每次进程首次使用某分表模型时触发(模型有内存缓存)。 +- 结论:**若先改 schema 文件再部署代码,应用会在首个请求时自动对 524MB 大表执行建索引 DDL(无 ALGORITHM/LOCK 控制、无法择时)**。 +- 因此正确顺序必须是:**先执行迁移(低峰期)→ 再落盘 schema 代码变更 → 再部署**;这样应用运行时 drift 检查发现索引已存在,不会重复建。 + +### 2.3 现有索引核对(开发环境,只读 SHOW INDEX) + +开发环境(config.local.js,客户端 wms)确认 current/dispatch 分表现有索引与模型一致,瓶颈索引为: + +| 表(开发环境示例) | 瓶颈索引 | 列 | +|---|---|---| +| wms_order_delivery_1000028_dispatch | idx_1000028_current_wave | status, wave_id | +| wms_order_delivery_1000028 | idx_1000028_current_wave | status, wave_id | + +开发环境分表规模(只读 information_schema):`wms_order_delivery_100000` 66,976 行 / 41.6MB;`wms_order_delivery_100000_dispatch` 2,488 行。生产分表规模以用户提供数据为准(dispatch 25.38 万行 / 524MB),执行前需实测。 + +## 3. 修改点清单 + +### 3.1 模型 schema(本次仅书面标注,未改文件) + +> 为避免与 wms-dev-agent 的修复冲突,本 agent **不直接修改 schema 代码**,待用户确认后由 wms-dev-agent 落盘;或在用户授权后由本 agent 改。 + +- 文件:`app/model/order_delivery_table_schema.js` +- 函数:`buildIndexOptions`,current 分支共享 `indexes` 数组内、`idx_${prefix}_wave` 之前插入: + +```js +{ + name: `idx_${prefix}_wave_id`, + fields: [ 'wave_id' ], +}, +``` + +- dispatch 分支**无需修改**(通过 `baseIndexes` 自动继承)。 +- 索引名与迁移草案一致:`idx_{wh}_current_wave_id`(dispatch 表沿用 `_current_` 前缀,与既有继承索引命名习惯一致)。 + +### 3.2 迁移文件(已创建,未执行) + +- 路径:`database/migrations/20260830100000-add-wave-id-index-to-order-delivery-shards.js` +- 要点: + - 动态枚举 `wms_order_delivery_{wh}` 与 `wms_order_delivery_{wh}_dispatch`(information_schema,不写死仓库 id); + - 幂等:`SHOW INDEX` 已存在则跳过; + - 使用原生 `ALTER TABLE ... ADD INDEX ..., ALGORITHM=INPLACE, LOCK=NONE`(Sequelize `addIndex` 不支持传算法/锁参数,故用原生 SQL); + - `down` 为 `DROP INDEX`(同样 INPLACE/LOCK=NONE); + - 语法已通过 `node --check`;**未对任何环境执行**。 + +## 4. 生产执行风险评估与建议 + +### 4.1 MySQL 5.7.44 在线 DDL 支持 + +- InnoDB 添加二级索引支持 `ALGORITHM=INPLACE, LOCK=NONE`(MySQL 5.6+,5.7 完整支持):不重建表、不锁写、并发 DML 允许。 +- 前置检查项: + 1. `SHOW VARIABLES LIKE 'old_alter_table'` 应为 `OFF`(默认); + 2. 确认表引擎 InnoDB(本项目分表均为 InnoDB); + 3. 执行前实测各分表行数与大小。 + +### 4.2 预估耗时与索引体积 + +- 索引体积:`wave_id BIGINT(20)`(8 字节)+ 主键 8 字节,25.38 万行约 **4–6 MB**,几乎不增加磁盘压力; +- 建索引耗时:全表扫描 524MB + 排序 25 万行键值,低负载 SSD 上单个 dispatch 分表约 **数十秒–5 分钟**;current 分表按行数同比。多仓多表总窗口建议预留 **15–30 分钟**。 +- 副作用:每个分表多一个二级索引,INSERT 时多写约 20 字节/行,可忽略。 + +### 4.3 建议执行窗口 + +- 低峰期:**凌晨 02:00–05:00** 或周末低峰;避开波次扫描定时任务(`app/schedule/sync_finished_wave_batch.js`)、批量导入与大促。 +- 逐表执行并监控:`SHOW PROCESSLIST`、`INFORMATION_SCHEMA.INNODB_TRX`(确认无长事务)。 + +### 4.4 执行方式(红线) + +- ❌ 禁止对生产库直接执行裸 `ALTER TABLE`;❌ 禁止用 `script/db-query.ps1` 查/改生产(它永远是开发环境)。 +- ✅ 生产必须走迁移流程: + - 全量:`$env:NODE_ENV='production'; npx sequelize-cli db:migrate --migrations-path database/migrations --env production` + - 或单条:`node script/run-single-migration.cjs 20260830100000-add-wave-id-index-to-order-delivery-shards.js`(内部连 `database/config.js` 的 production) +- ⚠️ **生产当前有 4 条 pending 迁移**(只读 `db:migrate:status --env production` 结果):`20260829120000` / `20260829160000` / `20260829170000` / `20260829180000`(report-delivery 相关)。`run-single-migration.cjs` 会拒绝跨序执行 → **先跑完这 4 条**再跑本条;用 `db:migrate` 则按序自动全部执行。 +- 开发环境基线:迁移全部 up(最新 `20260829180000`);本条迁移在开发/生产两边均显示 `down`(未执行,符合"草案"状态)。 + +### 4.5 回滚 + +- `down`:`DROP INDEX`(INPLACE/LOCK=NONE,秒级完成),不重建表、不影响数据。 + +## 5. 存量回填评估(script/backfill-order-id-location.cjs) + +### 5.1 适用性 + +- 目标:将分表存量 id 补入 `wms_order_id_location_{wh}`(id → location 映射),修复 queryOrder 定位回退(约 12.4 万行缺失)。 +- 脚本能力:`--dry-run`、`--warehouse-id=`、`--batch-size=`(100–50000,默认 1000)、`--db-client=`、`--config-path=`。 +- ⚠️ 默认连开发库(config.local.js);**生产必须** `--config-path=script/db-query-prod-config.js --db-client=wms`。 +- 流程:枚举分表 → 确保序列表存在(缺失时 CREATE TABLE)→ 分批 LEFT JOIN(PK 序)找缺失 id → 多行 `INSERT ... ON DUPLICATE KEY UPDATE` → 每仓结束抬 `AUTO_INCREMENT = MAX(id)+50`。 + +### 5.2 数据量与分批建议 + +- 约 12.4 万行;默认 batch=1000 约 124 批。每批重新执行 LEFT JOIN(无物化),最大分表 25 万行 × 124 批 ≈ 3 千万次 PK 探测,低峰可接受;建议 `--batch-size=5000` 减少轮次。 +- 建议顺序:`--dry-run` 全量预演 → 核对输出 → 按仓库逐个 `--warehouse-id=` 执行 → 前后核对 `COUNT(*)`。 + +### 5.3 风险点 + +1. **id 碰撞(最高风险)**:回填期间若序列表 AUTO_INCREMENT 仍低于缺失 id 区间,新订单可能分配到相同 id,`ON DUPLICATE KEY UPDATE` 会把新订单的 location 覆盖为来源表 location。执行前必须核对:`AUTO_INCREMENT` vs 缺失 id 最大值;务必在**最低写入时段**执行。 +2. **DDL**:`ensureSequenceTable` 可能 CREATE TABLE;结束会 `ALTER TABLE ... AUTO_INCREMENT`(小表、秒级)——均属 DDL/写操作,需用户确认。 +3. **location 覆盖**:id 已存在于序列表时会被覆盖(脚本语义如此)。 +4. **无断点续跑**:中断后重跑安全(幂等 upsert),但需重新扫描。 +5. **与加索引互补**:索引修波次计数,回填修订单定位,两者独立、可分开执行。 + +## 6. 需要用户确认的风险问题清单(交 Dispatcher 转达) + +1. 是否允许在**生产**执行加索引 DDL?(未确认前不执行) +2. 执行方式:全量 `db:migrate`(会自动先执行生产 pending 的 4 条 20260829* 迁移)还是单条 `run-single-migration.cjs`(需先补跑那 4 条)?是否同意先执行那 4 条? +3. 执行窗口:请指定具体时间(建议凌晨 02:00–05:00);期间可接受轻微 I/O 压力? +4. 索引范围:确认 current + dispatch 两族分表、**全部仓库**都加? +5. 是否允许对 `wms_order_id_location_{wh}` 回填写数据(约 12.4 万行)?是否先 `--dry-run` 预演? +6. 回填窗口与 id 碰撞:是否可安排在最低写入时段?是否同意先核对序列表 AUTO_INCREMENT 区间? +7. schema 代码变更(`buildIndexOptions` 新增 `idx_{prefix}_wave_id`):是否由 wms-dev-agent 落盘?确认部署顺序 = **先迁移、后代码**。 +8. 回滚授权:若上线后异常,是否允许执行 down(DROP INDEX)? + +## 7. 建议执行顺序 + +1. 用户完成 §6 风险确认; +2. 生产低峰期执行迁移(含前置 4 条 pending); +3. 生产 `SHOW INDEX` + `EXPLAIN` 验证新索引生效; +4. wms-dev-agent 落盘 `buildIndexOptions` 变更并部署(避免运行时 drift 重复建索引); +5. (可选)序列表回填(先 dry-run); +6. 观察 queryOrder 链路耗时与错误率。 \ No newline at end of file From ebaf5d0051f493732c5c7d8cc221b3249b7cc93d Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sun, 30 Aug 2026 07:28:25 +0800 Subject: [PATCH 299/550] =?UTF-8?q?feat(order):=20=E8=AE=A2=E5=8D=95?= =?UTF-8?q?=E5=AF=BC=E5=87=BA=E6=96=B0=E5=A2=9E"=E6=9D=A5=E6=BA=90"?= =?UTF-8?q?=E5=88=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/systems/order_export.js | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/app/service/systems/order_export.js b/app/service/systems/order_export.js index 0a777bc..ab5fc10 100644 --- a/app/service/systems/order_export.js +++ b/app/service/systems/order_export.js @@ -34,6 +34,7 @@ const ORDER_EXPORT_COLUMNS = Object.freeze([ { header: '波次序号', key: 'wave_index', width: 12 }, { header: '货主', key: 'store_id', width: 20 }, { header: '平台', key: 'sys_platform_name', width: 16 }, + { header: '来源', key: 'create_channel', width: 12 }, { header: '店铺昵称', key: 'shop_nick', width: 20 }, { header: '收件人', key: 'receiver_name', width: 16 }, { header: '收件人电话', key: 'receiver_mobile', width: 18 }, @@ -81,6 +82,7 @@ const ORDER_EXPORT_ITEM_COLUMNS = Object.freeze([ { header: '波次序号', key: 'wave_index', width: 12 }, { header: '货主', key: 'store_id', width: 20 }, { header: '平台', key: 'sys_platform_name', width: 16 }, + { header: '来源', key: 'create_channel', width: 12 }, { header: '店铺昵称', key: 'shop_nick', width: 20 }, { header: '收件人', key: 'receiver_name', width: 16 }, { header: '收件人电话', key: 'receiver_mobile', width: 18 }, @@ -281,6 +283,8 @@ class OrderExportService extends OrderBaseService { /** * 校验并规范导出表头字段入参(中文表头数组)。 + * 白名单基于 ORDER_EXPORT_ALL_COLUMN_HEADERS(两模式列头并集), + * 新增列(如“来源”)在列配置中登记后即自动可用。 * 不传/空数组返回空数组(表示输出全部列);存在非法表头时抛错。 * @param {Array|*} rawColumns 原始入参。 * @return {Array} 去重后的表头数组。 @@ -452,6 +456,7 @@ class OrderExportService extends OrderBaseService { wave_index: this.normalizeExportCellValue(safeOrderRow.wave_index ?? 0), store_id: this.normalizeExportCellValue(storeRemark || safeOrderRow.store_name || safeOrderRow.store_id), sys_platform_name: this.normalizeExportCellValue(safeOrderRow.sys_platform_name), + create_channel: this.formatCreateChannelLabel(String(safeOrderRow.create_channel || '')), shop_nick: this.normalizeExportCellValue(safeOrderRow.shop_nick), receiver_name: this.normalizeExportCellValue(safeOrderRow.name || ''), receiver_mobile: this.normalizeExportCellValue(safeOrderRow.mobile || safeOrderRow.tel || ''), From 58cc5bb7b617977aa58e3c018dc7dc591fb1fca1 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sun, 30 Aug 2026 07:28:29 +0800 Subject: [PATCH 300/550] =?UTF-8?q?feat(storage):=20=E5=BF=AB=E6=8D=B7?= =?UTF-8?q?=E7=9B=B4=E5=85=A5=E5=9B=9E=E5=86=99=E8=99=9A=E6=8B=9F=E5=85=A5?= =?UTF-8?q?=E5=BA=93=E6=A0=87=E8=AE=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/model/entry_order.js | 6 +++ app/service/systems/storage/entry.js | 3 ++ ...d-is-virtual-inbound-to-wms-entry-order.js | 40 +++++++++++++++++++ 3 files changed, 49 insertions(+) create mode 100644 database/migrations/20260828100000-add-is-virtual-inbound-to-wms-entry-order.js diff --git a/app/model/entry_order.js b/app/model/entry_order.js index 91f3267..5c63bf6 100644 --- a/app/model/entry_order.js +++ b/app/model/entry_order.js @@ -143,6 +143,12 @@ module.exports = app => { defaultValue: 0, comment: '费用是否记录', }, + is_virtual_inbound: { + type: TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '是否虚拟入库:0=否 1=是', + }, store_name: { type: STRING(200), allowNull: true, diff --git a/app/service/systems/storage/entry.js b/app/service/systems/storage/entry.js index 8a2278f..02c09dd 100644 --- a/app/service/systems/storage/entry.js +++ b/app/service/systems/storage/entry.js @@ -1517,6 +1517,7 @@ class EntryService extends Service { * 快捷直入/虚拟入库:将入库单明细直入到虚拟库位(space_id=2),跳过收货、质检等正常流程。 * 有绑定收货单时,只取收货单中与入库单明细有交集(按 stock_id 判断)且剩余可入数量的部分直入, * 并回写收货单明细已入库数量;未绑定收货单时按明细计划数量全量直入。 + * 有绑定收货单时回写 is_virtual_inbound=0(非虚拟入库),无绑定收货单时回写 is_virtual_inbound=1(虚拟入库)。 * 采用"先同步后写库"两段式:① 先发奇门/OpenAPI 回传,② 回传成功后再开启事务写库存。 * @param {Object} data 请求体 * @param {number} data.id 入库单ID @@ -1843,6 +1844,8 @@ class EntryService extends Service { await eo.update({ order_status: 'COMPLETED', sync_status: 'SUCCESS', + // 有绑定收货单 → 非虚拟入库(0);无绑定收货单 → 虚拟入库(1) + is_virtual_inbound: receivingIds.length > 0 ? 0 : 1, sync_message: JSON.stringify({ completedAt: new Date(), totalQuantity: totalInboundQty, diff --git a/database/migrations/20260828100000-add-is-virtual-inbound-to-wms-entry-order.js b/database/migrations/20260828100000-add-is-virtual-inbound-to-wms-entry-order.js new file mode 100644 index 0000000..b8631f5 --- /dev/null +++ b/database/migrations/20260828100000-add-is-virtual-inbound-to-wms-entry-order.js @@ -0,0 +1,40 @@ +'use strict'; + +const TABLE = 'wms_entry_order'; + +/** + * 入库单主表新增 is_virtual_inbound 字段: + * 标记该入库单是否为虚拟入库(0=否,1=是)。 + * 快捷直入时,无绑定收货单的入库单为虚拟入库,有绑定收货单的为非虚拟入库。 + */ +module.exports = { + /** + * 执行迁移:新增 is_virtual_inbound 字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + up: async (queryInterface, Sequelize) => { + const columns = await queryInterface.describeTable(TABLE); + if (!columns.is_virtual_inbound) { + await queryInterface.addColumn(TABLE, 'is_virtual_inbound', { + type: Sequelize.TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '是否虚拟入库:0=否 1=是', + }); + } + }, + + /** + * 回滚迁移:删除 is_virtual_inbound 字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} 无返回值 + */ + down: async queryInterface => { + const columns = await queryInterface.describeTable(TABLE); + if (columns.is_virtual_inbound) { + await queryInterface.removeColumn(TABLE, 'is_virtual_inbound'); + } + }, +}; From 373bb84294242c12fe343b238c1503388a25ab98 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sun, 30 Aug 2026 07:28:36 +0800 Subject: [PATCH 301/550] =?UTF-8?q?chore(db):=20=E6=95=B0=E6=8D=AE?= =?UTF-8?q?=E5=BA=93=E8=84=9A=E6=9C=AC=E8=BF=9E=E6=8E=A5=E7=9B=AE=E6=A0=87?= =?UTF-8?q?=E4=BF=9D=E6=8A=A4=EF=BC=88WMS=5FDB=5FTARGET=20=E6=98=BE?= =?UTF-8?q?=E5=BC=8F=E8=A7=A3=E6=9E=90=E9=98=B2=E8=AF=AF=E8=BF=9E=E7=94=9F?= =?UTF-8?q?=E4=BA=A7=E5=BA=93=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- database/config.js | 86 +++++++++++++++++++++++++++++++-- script/db-query-prod-config.js | 7 ++- script/db-query.ps1 | 4 ++ script/run-single-migration.cjs | 32 +++++++++--- script/update-api-doc.cjs | 33 +++++++++++-- 5 files changed, 149 insertions(+), 13 deletions(-) diff --git a/database/config.js b/database/config.js index 312e2b4..9d0727a 100644 --- a/database/config.js +++ b/database/config.js @@ -3,10 +3,21 @@ const fs = require('node:fs'); const path = require('node:path'); +/** + * 判断值是否为普通对象(非数组、非 null)。 + * @param {*} value 待判断的值。 + * @return {boolean} 是普通对象返回 true。 + */ function isPlainObject(value) { return !!value && typeof value === 'object' && !Array.isArray(value); } +/** + * 深合并两个普通对象,返回新对象,不修改入参。 + * @param {object} target 目标对象。 + * @param {object} source 来源对象。 + * @return {object} 合并后的新对象。 + */ function mergeDeep(target, source) { const output = isPlainObject(target) ? { ...target } : {}; if (!isPlainObject(source)) { @@ -26,6 +37,11 @@ function mergeDeep(target, source) { return output; } +/** + * 加载 Egg 配置文件,兼容工厂函数与普通对象两种形式。 + * @param {string} configPath 配置文件绝对路径。 + * @return {object} 解析后的配置对象,文件不存在时返回空对象。 + */ function loadEggConfig(configPath) { if (!fs.existsSync(configPath)) { return {}; @@ -39,6 +55,13 @@ function loadEggConfig(configPath) { return isPlainObject(config) ? config : {}; } +/** + * 从 Egg 配置中解析指定名称的 MySQL 客户端。 + * @param {object} appConfig Egg 应用配置。 + * @param {string} clientName MySQL 客户端名称。 + * @return {object} 解析出的 MySQL 客户端连接配置。 + * @throws {Error} 找不到指定客户端时抛出异常。 + */ function resolveMysqlClient(appConfig, clientName) { const clients = appConfig && appConfig.mysql && appConfig.mysql.clients; if (clients && clients[clientName]) { @@ -52,8 +75,62 @@ function resolveMysqlClient(appConfig, clientName) { throw new Error(`MySQL client "${clientName}" not found in Egg config.`); } +/** + * 解析数据库连接目标标记,防止 NODE_ENV 残留导致误连生产库。 + * 优先级:WMS_DB_TARGET(显式标记) > NODE_ENV(兜底判断)。 + * @param {string | undefined} envTarget 显式目标标记(WMS_DB_TARGET 环境变量值)。 + * @param {string | undefined} nodeEnv NODE_ENV 环境变量值。 + * @return {{ target: string, source: string, explicit: boolean }} 解析结果:target 为 'production' 或 'local',source 为判定来源,explicit 表示是否显式指定。 + */ +function resolveDbTarget(envTarget, nodeEnv) { + const explicit = String(envTarget || '').trim().toLowerCase(); + if (explicit === 'production' || explicit === 'prod') { + return { target: 'production', source: 'WMS_DB_TARGET', explicit: true }; + } + if (explicit === 'local' || explicit === 'dev' || explicit === 'development') { + return { target: 'local', source: 'WMS_DB_TARGET', explicit: true }; + } + if (explicit) { + console.warn(`[DB-CONFIG] 未知的 WMS_DB_TARGET="${explicit}",已忽略并回退到 NODE_ENV 判断;可选值:local | production`); + } + + const nodeEnvLower = String(nodeEnv || '').trim().toLowerCase(); + return { + target: nodeEnvLower === 'production' ? 'production' : 'local', + source: nodeEnvLower === 'production' ? 'NODE_ENV' : 'default', + explicit: false, + }; +} + +/** + * 打印数据库连接目标提示(输出到 stderr,避免污染 stdout 上的 JSON 结果)。 + * production 目标额外打印醒目告警,提醒操作者确认连接目标。 + * @param {{ host: string, port: (number|string), database: string }} client 解析后的 MySQL 连接配置。 + * @param {{ target: string, source: string }} resolved 目标解析结果。 + * @return {void} + */ +function printDbTargetNotice(client, resolved) { + const detail = `host=${client.host} port=${client.port} database=${client.database} (判定来源: ${resolved.source})`; + if (resolved.target === 'production') { + console.warn(''); + console.warn('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!'); + console.warn('[DB-CONFIG] ⚠ 警告:当前解析为【生产数据库】连接目标'); + console.warn(`[DB-CONFIG] ⚠ ${detail}`); + console.warn('[DB-CONFIG] ⚠ 请确认这是预期环境;如属误判,请设置 WMS_DB_TARGET=local 强制使用开发库配置。'); + console.warn('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!'); + console.warn(''); + } else { + console.warn(`[DB-CONFIG] 数据库连接目标: ${detail}`); + } +} + const projectRoot = path.resolve(__dirname, '..'); +// 解析连接目标:显式标记 WMS_DB_TARGET 优先于 NODE_ENV 兜底判断, +// 避免终端残留 NODE_ENV=production 导致迁移/脚本误连生产库 +const dbTarget = resolveDbTarget(process.env.WMS_DB_TARGET, process.env.NODE_ENV); +const isProductionTarget = dbTarget.target === 'production'; + let mysqlClient; if (process.env.DB_HOST) { mysqlClient = { @@ -63,13 +140,13 @@ if (process.env.DB_HOST) { password: process.env.DB_PASSWORD, database: process.env.DB_NAME || 'wms', }; + printDbTargetNotice(mysqlClient, { target: 'manual', source: 'DB_HOST' }); } 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 localConfig = isProductionTarget ? {} : loadEggConfig(path.join(projectRoot, 'config', 'config.local.js')); const appConfig = mergeDeep(defaultConfig, localConfig); const clientName = process.env.SEQUELIZE_DB_CLIENT || 'wms'; - if (isProduction) { + if (isProductionTarget) { const sequelizeConfig = appConfig && appConfig.sequelize; if (sequelizeConfig && sequelizeConfig.host) { mysqlClient = { @@ -85,6 +162,7 @@ if (process.env.DB_HOST) { } else { mysqlClient = resolveMysqlClient(appConfig, clientName); } + printDbTargetNotice(mysqlClient, dbTarget); } const baseConfig = { @@ -108,4 +186,6 @@ module.exports = { development: { ...baseConfig }, test: { ...baseConfig }, production: { ...baseConfig }, + // 解析出的连接目标元信息,供迁移脚本等调用方做断言与提示(不影响 sequelize-cli 读取 env 配置) + dbTarget, }; diff --git a/script/db-query-prod-config.js b/script/db-query-prod-config.js index 5fbc022..18781c3 100644 --- a/script/db-query-prod-config.js +++ b/script/db-query-prod-config.js @@ -1,4 +1,9 @@ -module.exports = { +/** + * ⚠ 生产数据库连接配置(仅用于 script/db-query.ps1 显式指定 -ConfigPath 时)。 + * 默认情况下 db-query.ps1 使用 config/config.local.js(开发库), + * 只有显式传入本文件才会连接生产库,请确认后再使用。 + */ +module.exports = { mysql: { clients: { wms: { diff --git a/script/db-query.ps1 b/script/db-query.ps1 index 1504697..5ccbe96 100644 --- a/script/db-query.ps1 +++ b/script/db-query.ps1 @@ -63,6 +63,9 @@ const { createRequire } = require("module"); const [rows] = await connection.query(query); const payload = JSON.stringify({ client: clientName, + host: client.host, + port: client.port, + database: client.database, rowCount: Array.isArray(rows) ? rows.length : 0, rows, }); @@ -105,6 +108,7 @@ try { Remove-Item -Path $jsonOutFile -ErrorAction SilentlyContinue } Write-Host "Client: $($result.client)" +Write-Host "Target: $($result.host):$($result.port)/$($result.database)" Write-Host "Rows: $($result.rowCount)" if ($AsTable) { diff --git a/script/run-single-migration.cjs b/script/run-single-migration.cjs index a72c070..d34ddaa 100644 --- a/script/run-single-migration.cjs +++ b/script/run-single-migration.cjs @@ -2,8 +2,14 @@ const fs = require('fs'); const SequelizeLib = require('sequelize'); -(async () => { - const migrationName = process.argv[2] || process.env.MIGRATION_NAME; +/** + * 单条迁移执行主流程:加载数据库配置、执行迁移并验证结果,支持 --dry-run 预览。 + * @return {Promise} 无返回值,通过 process.exitCode 表达执行结果。 + */ +async function main() { + const args = process.argv.slice(2); + const dryRun = args.includes('--dry-run'); + const migrationName = args.find(arg => !arg.startsWith('--')) || process.env.MIGRATION_NAME; if (!migrationName) { console.error('ERROR: 必须通过命令行参数或环境变量 MIGRATION_NAME 传入迁移文件名。'); console.error('USAGE: node ./script/run-single-migration.cjs 20260523130000-add-cainiao-to-wms-express.js'); @@ -28,6 +34,18 @@ const SequelizeLib = require('sequelize'); } const config = dbConfig.production; + const targetMeta = dbConfig.dbTarget || { target: 'unknown', source: 'unknown' }; + console.log(`[RUN-MIGRATION] 连接目标: host=${config.host} port=${config.port} database=${config.database} (判定来源: ${targetMeta.source})`); + if (targetMeta.target === 'production') { + console.warn('[RUN-MIGRATION] ⚠ 目标为生产库,请确认后再执行;如属误判请设置 WMS_DB_TARGET=local 后重试。'); + } + if (dryRun) { + console.log('[RUN-MIGRATION] DRY-RUN 模式:仅展示执行计划,不连接数据库、不执行任何 DDL。'); + console.log(`[RUN-MIGRATION] 计划执行迁移文件: ${migrationName}`); + console.log(`[RUN-MIGRATION] 目标库: ${config.host}:${config.port}/${config.database}`); + return; + } + const sequelize = new SequelizeLib(config.database, config.username, config.password, { host: config.host, port: config.port, @@ -97,7 +115,7 @@ const SequelizeLib = require('sequelize'); // record migration in SequelizeMeta try { - await sequelize.query('INSERT INTO SequelizeMeta(name) VALUES(?)', { replacements: [migrationName] }); + await sequelize.query('INSERT INTO SequelizeMeta(name) VALUES(?)', { replacements: [ migrationName ] }); } catch (e) { console.error('ERROR: 无法在 SequelizeMeta 中记录迁移:', e && e.message ? e.message : e); process.exitCode = 5; @@ -115,7 +133,7 @@ const SequelizeLib = require('sequelize'); }; // migration recorded? - const checkRow = await sequelize.query('SELECT name FROM SequelizeMeta WHERE name = ?', { replacements: [migrationName], type: SequelizeLib.QueryTypes.SELECT }); + const checkRow = await sequelize.query('SELECT name FROM SequelizeMeta WHERE name = ?', { replacements: [ migrationName ], type: SequelizeLib.QueryTypes.SELECT }); result.migrationRecorded = (checkRow && checkRow.length > 0); // table exists? @@ -124,7 +142,7 @@ const SequelizeLib = require('sequelize'); if (result.tableExists) { const desc = await queryInterface.describeTable('wms_order_wave_strategy_match'); - const needed = ['id', 'warehouse_id', 'order_id', 'strategy_id', 'create_time']; + const needed = [ 'id', 'warehouse_id', 'order_id', 'strategy_id', 'create_time' ]; for (const col of needed) { result.columns[col] = !!desc[col]; if (desc[col]) { @@ -159,4 +177,6 @@ const SequelizeLib = require('sequelize'); // close await sequelize.close(); process.exitCode = 0; -})(); +} + +main(); diff --git a/script/update-api-doc.cjs b/script/update-api-doc.cjs index 8efdc35..af9e431 100644 --- a/script/update-api-doc.cjs +++ b/script/update-api-doc.cjs @@ -77,7 +77,10 @@ function readJsonFile(filePath) { } function detectIndent(raw) { - const match = raw.match(/^([ \t]+)"[^"]+":/m); + // 取第一个带缩进的值行(对象键、数组元素对象 `{` 或字符串元素)作为单层缩进; + // 根为数组的文档(methods/changes/*.json)首行 `[` 后紧跟元素 `{`, + // 避免把第二层缩进误判为单层缩进,导致全文件重排 + const match = raw.match(/^([ \t]+)[\[{"]/m); return match ? match[1] : ' '; } @@ -212,6 +215,15 @@ function validateSpec(spec, args) { methodNames.add(item.method); }); + let deleteMethods = []; + if (Object.prototype.hasOwnProperty.call(spec, 'deleteMethods')) { + ensureStringArray(spec.deleteMethods, 'spec.deleteMethods'); + deleteMethods = spec.deleteMethods; + } + deleteMethods.forEach(item => { + assert(!methodNames.has(item), `Method conflict: ${item} appears in both spec.methods and spec.deleteMethods.`); + }); + if (!args.docOnly) { validateChange(spec.change, 'spec.change'); } else if (Object.prototype.hasOwnProperty.call(spec, 'change')) { @@ -225,6 +237,7 @@ function validateSpec(spec, args) { docMeta: spec.docMeta || {}, group: spec.group, methods: spec.methods, + deleteMethods, change: spec.change || null, }; } @@ -251,7 +264,7 @@ function cloneJson(value) { return JSON.parse(JSON.stringify(value)); } -function applyDocUpdate(doc, groupSpec, methods, docMeta) { +function applyDocUpdate(doc, groupSpec, methods, docMeta, deleteMethods = []) { const groups = doc.methods.groups; let groupIndex = findGroupIndex(groups, groupSpec); @@ -275,6 +288,8 @@ function applyDocUpdate(doc, groupSpec, methods, docMeta) { inserted: [], updated: [], moved: [], + deleted: [], + deleteNotFound: [], }; for (const methodDoc of methods) { @@ -298,6 +313,16 @@ function applyDocUpdate(doc, groupSpec, methods, docMeta) { summary.moved.push(methodDoc.method); } + for (const methodName of deleteMethods) { + const location = findMethodLocation(groups, methodName); + if (!location) { + summary.deleteNotFound.push(methodName); + continue; + } + groups[location.groupIndex].list.splice(location.methodIndex, 1); + summary.deleted.push(methodName); + } + if (docMeta.updatedAt) { doc.updatedAt = docMeta.updatedAt; } @@ -339,7 +364,7 @@ function main() { } const docNext = cloneJson(docState.json); - const summary = applyDocUpdate(docNext, normalized.group, normalized.methods, normalized.docMeta); + const summary = applyDocUpdate(docNext, normalized.group, normalized.methods, normalized.docMeta, normalized.deleteMethods); JSON.parse(JSON.stringify(docNext)); let changeNext = null; @@ -354,6 +379,8 @@ function main() { console.log(`inserted: ${summary.inserted.length ? summary.inserted.join(', ') : '-'}`); console.log(`updated: ${summary.updated.length ? summary.updated.join(', ') : '-'}`); console.log(`moved: ${summary.moved.length ? summary.moved.join(', ') : '-'}`); + console.log(`deleted: ${summary.deleted.length ? summary.deleted.join(', ') : '-'}`); + console.log(`delete-not-found: ${summary.deleteNotFound.length ? summary.deleteNotFound.join(', ') : '-'}`); if (!args.docOnly && normalized.change) { console.log(`change version: ${normalized.change.version}`); } From a75612c22dc7da47eefbb445ab3537b68cf29a06 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sun, 30 Aug 2026 07:28:39 +0800 Subject: [PATCH 302/550] =?UTF-8?q?docs(routing):=20AI=5FMETHOD=5FROUTING?= =?UTF-8?q?=20=E8=B7=AF=E7=94=B1=E8=A1=A8=E5=90=8C=E6=AD=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- AI_METHOD_ROUTING.md | 156 ++++++++++++++++++++++++++++++++----------- 1 file changed, 116 insertions(+), 40 deletions(-) diff --git a/AI_METHOD_ROUTING.md b/AI_METHOD_ROUTING.md index a5b88d9..ebe992d 100644 --- a/AI_METHOD_ROUTING.md +++ b/AI_METHOD_ROUTING.md @@ -76,6 +76,24 @@ POST http://127.0.0.1:6060/system?method=print.getComputerPrinter&v=1.0×tam - 对应文件:`app/service/systemMethods/printer/station.js` - 对应方法:`list()` +4) `method=report.generate` +- service 路径:`report` +- 函数名:`generate` +- 对应文件:`app/service/systemMethods/report.js` +- 对应方法:`generate(data)` + +5) `method=report.deliveryPlan.save` +- service 路径:`report.deliveryPlan` +- 函数名:`save` +- 对应文件:`app/service/systemMethods/report/deliveryPlan.js` +- 对应方法:`save(data)` + +6) `method=report.deliveryLog.list` +- service 路径:`report.deliveryLog` +- 函数名:`list` +- 对应文件:`app/service/systemMethods/report/deliveryLog.js` +- 对应方法:`list(data)` + ### 4.2 /qimen 示例 1) `method=deliveryorder.xxx` @@ -102,6 +120,46 @@ rg "class .*Service|module.exports" app/service/qimenMethods ``` ## 后续所有的method新增变更全部需要维护到下方 +## 5.1 report(配置驱动通用报表 + 货主定时投递)能力速查 + +| method | 实现文件 | 函数 | 登录 | 鉴权/权限 | +|---|---|---|---|---| +| report.generate | app/service/systemMethods/report.js | generate | 需登录 | 免权限(systemInit 声明 generate/generateTaskProgress/meta 免权限) | +| report.generateTaskProgress | app/service/systemMethods/report.js | generateTaskProgress | 需登录 | 免权限 | +| report.meta | app/service/systemMethods/report.js | meta | 需登录 | 免权限(_noNeedRight/_noNeedAuth 含 meta;未列入 _noNeedLog,保留审计日志) | +| report.definition.typeList | app/service/systemMethods/report/definition.js | typeList | 需登录 | 免权限(_noNeedRight/_noNeedAuth/_noNeedLog 含 typeList;同模块 save/list/delete 仍需授权) | +| report.deliveryPlan.save | app/service/systemMethods/report/deliveryPlan.js | save | 需登录 | 需授权(未声明免权限) | +| report.deliveryPlan.list | app/service/systemMethods/report/deliveryPlan.js | list | 需登录 | 需授权 | +| report.deliveryPlan.copy | app/service/systemMethods/report/deliveryPlan.js | copy | 需登录 | 需授权(未声明免权限) | +| report.deliveryLog.list | app/service/systemMethods/report/deliveryLog.js | list | 需登录 | 需授权 | +| report.definition.save | app/service/systemMethods/report/definition.js | save | 需登录 | 需授权(未声明免权限) | +| report.definition.list | app/service/systemMethods/report/definition.js | list | 需登录 | 需授权 | +| report.definition.delete | app/service/systemMethods/report/definition.js | delete | 需登录 | 需授权 | + +- 底层编排:`app/service/systems/report.js`(报表定义读取/类型注册表解析/工作簿生成,含 listRegisteredTypes/saveDefinition/listDefinitions/deleteDefinition 定义管理)、`app/service/systems/reportDelivery.js`(投递计划/记录 CRUD 与分钟级投递调度,含文本通知模板渲染与定向群/成员推送)、`app/lib/report/notifyTemplate.js`(标签白名单 {time}/{url}/{report_name}/{biz_date} 渲染) +- 配置与口径:`wms_report_definition` 极简配置(name/type/file_name/fields/is_enabled/remark,唯一性由主键 id 承担),注册类型与字段规格见 `app/service/systems/report/queries/index.js`(当前仅 stockFlow),详见 `docs/report-config-guide.md` +- 接口文档:`methods/system.json` 分组「通用报表模块」(module=report),变更记录见 `methods/changes/system.json` 版本 `2026.08.30-report-delivery-plan-copy`、`2026.08.30-report-delivery-plan-name-field`、`2026.08.30-report-type-list-merge-into-definition`、`2026.08.30-report-definition-model-refactor`、`2026.08.29-report-config-driven-generate-delivery`、`2026.08.29-report-meta`、`2026.08.29-report-delivery-notify-template-targets`、`2026.08.29-report-delivery-channel-converge`、`2026.08.29-report-definition-management`、`2026.08.29-report-channel-normalize-doc-audit` +- 报表定义模型重构(2026-08-30,破坏性变更):报表定义由 code 编码改为主键 id 关联,`report.generate`/`report.meta`/`report.deliveryPlan.save` 入参 `report_code` 改为 `report_id`(=报表定义ID,兼容 reportId 驼峰,前端需同步改);`code/scope` 与 `output_config/source_config/sheet_config` 三段 JSON 配置已随模型删除,列渲染由类型硬编码字段规格自动完成;`report.definition.save` 入参 `{id?,name,type,file_name/fileName,fields,is_enabled?,remark?}`(type 须命中注册表、fields 须为该类型注册字段子集),`report.definition.list` where 改 `{name,type,is_enabled}` + sort 白名单 id/name/type/is_enabled/created_at/updated_at,`report.definition.delete` 入参 id 且引用拦截按 report_definition_id 统计;`report.deliveryPlan.*`/`report.deliveryLog.list` 关联键改 report_definition_id(log 响应带 report_name 快照);新增免权限只读 `report.definition.typeList` 返回注册类型清单(由独立模块 report/type.js 并入 report/definition.js);详见 `docs/report-config-guide.md` 第 1/2/3/6/7/8 节 +- 投递渠道收敛(2026-08-29):`report.deliveryPlan.save` 的 channel 仅支持 inbox(默认 inbox,wecom/link 已弃用,非法渠道报「投递渠道仅支持 inbox: 」);历史 wecom/link 计划投递时按 inbox 兜底;inbox 推送失败经 inbox.message.retry 自动重推一次,仍失败进入 failed 退避(MAX_RETRY=3) +- 文本通知(2026-08-29):`report.deliveryPlan.save` 可选入参 notify_template/notify_group_ids/notify_member_ids(仅入参存在时生效),`report.deliveryLog.list` 响应带 notify_targets 投递目标快照,详见 `docs/report-config-guide.md` 5.1 节 +- 计划名称(2026-08-30):`report.deliveryPlan.save` 可选入参 `name`(string|null;未传不覆盖,null/空串/全空白清空,非空 trim 后 ≤100 超长报错「计划名称 name 长度不能超过 100 字符」),`save` 响应与 `report.deliveryPlan.list` 列表项新增 `name`(缺省 '');仅展示字段,不参与幂等/关联;详见 `docs/report-config-guide.md` 第 5 节 +- 批量复制(2026-08-30):新增 `report.deliveryPlan.copy` 入参 `{id, store_ids}`(store_ids 非空正整数数组,自动去重,兼容 storeIds 驼峰),把源计划快速复制到多个目标货主;目标货主已存在同 report_definition_id 计划跳过不覆盖、货主不存在或状态异常跳过、与源计划货主相同跳过(reason 枚举见 methods/system.json);notify_group_ids/notify_member_ids 通知配置不复制(新计划置空)、enabled 原样复制(保持复制语义),其余字段(report_definition_id/schedule_times/channel/late_grace_minutes/name/remark/notify_template)原样复制;事务批量创建,唯一键冲突单条降级 skipped;需登录需鉴权(与 save/list 同口径) +- 渲染规则(2026-08-30):无 sheet_config,列由 `app/lib/report/render.js` `renderSheetByType` 按类型硬编码字段规格生成(string 静态列、number 统一 zeroToDash、boolean 统一 yesNo、array 窗口展开列);asText 由类型字段规格硬编码(item_code/barcode),渲染层输出 textColumns(0 基列索引)由 excel.js 落地文本单元格(长数字串防科学计数法);详见 `docs/report-config-guide.md` 第 3 节 +- 授权提示:需授权接口已登记 isNeedAuth=true,后续用 `npm run permission:sync:system-api -- --dry-run` 预演并按标准流程授权(不扩大任何角色授权) + +## 5.2 inbox.group(站内信群管理)能力速查 + +| method | 实现文件 | 函数 | 登录 | 鉴权/权限 | +|---|---|---|---|---| +| inbox.group.quickList | app/service/systemMethods/inbox.js → app/service/systems/inbox/group.js | groupQuickList / quickList | 需登录 | 需权限 566(API:群快速查询,已授权角色 26/28/29/8;超级管理员/仓库管理员持 * 通配符自动拥有) | +| inbox.group.members | app/service/systemMethods/inbox.js → app/service/systems/inbox/group.js | groupMembers / members | 需登录 | 需权限 567(API:群成员列表,已授权角色 26/28/29/8;超级管理员/仓库管理员持 * 通配符自动拥有) | + +- 底层实现:`app/service/systems/inbox/group.js` quickList(双维度可选过滤:store_id=货主维度(对应 wms_inbox_group.store_id 列)/ warehouse_id=仓库维度(对应 wms_inbox_group.warehouse_id 列),两者均可选、可同时传(AND 关系)、也可都不传(返回所有仓库/货主的群),非法值分别报「store_id 无效」「warehouse_id 无效」;keyword 同时模糊匹配 group_name/group_id、groupType 筛选 store/warehouse/express、limit 默认20上限100,无分页,按 created_at 倒序,软删自动排除)、members(groupIds 必填(非空数组,每个元素为正整数),先按内部主键ID数组+仓库批量校验群存在,再聚合多群外部群ID(去重、剔空),在 wms_inbox_message 按外部群ID集合聚合去重取每个 user_id 最新一条 user_name(多群共享同一 500 条聚合池,user_id 为 NULL/空串的消息被排除),keyword 对聚合结果小写包含过滤 user_name/user_id 后截断;外部群ID集合为空返回空列表) +- 仓库口径(2026-08-30 变更):quickList 透传前端入参 `store_id`(货主维度)/`warehouse_id`(仓库维度),不再从登录上下文注入任何仓库值;members 的 warehouseId 仍从 `ctx.user.store_id` 服务端注入,不信任前端传值 +- 多群聚合(2026-08-30 破坏性入参变更):inbox.group.members 入参由单个 `groupId` 改为 `groupIds`(数组,必填,非空,每个元素为正整数),一次查询多个群的成员并跨群按 user_id 去重;多群共享同一 500 条消息聚合池(更早消息中的成员不会出现在结果中);移除 `groupId` 入参,调用方需同步升级 +- 权限:迁移 `database/migrations/20260829180000-add-inbox-group-select-permissions.js`(固定权限 ID 566/567、type=api、INSERT IGNORE 幂等);inbox systemMethods 未声明 systemInit 免权限,两接口走标准 API 权限校验 +- 接口文档:`methods/system.json` 分组「站内信」(module=inbox),变更记录见 `methods/changes/system.json` 版本 `2026.08.30-inbox-group-members-groupids-array`、`2026.08.30-inbox-group-quicklist-dual-dim-filter`(修正/取代 `2026.08.30-inbox-group-quicklist-store-id`)、`2026.08.29-inbox-group-quick-list-members` +- 索引迁移(待发布时执行):`database/migrations/20260830150000-add-store-id-index-to-wms-inbox-group.js` 为 wms_inbox_group.store_id 新增索引 idx_store_id(幂等 up/down,尚未执行) ## method结束 @@ -114,10 +172,10 @@ rg "class .*Service|module.exports" app/service/qimenMethods - 临时清单输出:temp/tmp-service-method-inventory.md -自动生成时间: 2026-08-25T06:27:16.894Z +自动生成时间: 2026-08-28T20:06:02.056Z 扫描范围: app/service/**/*.js -文件数: 193 +文件数: 203 - app/service/api.js (1) - callMethod @@ -135,8 +193,6 @@ rg "class .*Service|module.exports" app/service/qimenMethods - callDeepSeek, getConversationHistory, processWithAI - app/service/inbox/functions.js (3) - registerBuiltinFunctions, register, callFunction -- app/service/inbox/tools.js (2) - - getRecordingComputerId, buildVideoUrl - app/service/inbox/groups.js (4) - resolveActiveGroups, isFunctionAvailable, getFunctionList, buildFunctionListText - app/service/inbox/index.js (5) @@ -147,14 +203,18 @@ rg "class .*Service|module.exports" app/service/qimenMethods - _loadGroupInfo, isStaleMessage, process, handleApiMessage, tryBindGroup, writeOutboundReply, isBlocked, invalidateBlockCache, getApiAppCallbackConfig, getApiAppCallbackUrl, pushSystemNotification, extractWarehouseId, extractStoreId, getWarehouseIdFromContext, getStoreIdFromContext - app/service/inbox/receiver.js (1) - receive +- app/service/inbox/rules.js (3) + - handle, buildReply, formatStock +- app/service/inbox/tools.js (2) + - getRecordingComputerId, buildVideoUrl - app/service/main.js (18) - success, fail, normalizeDate, setInfo, getInfo, isPlainObject, normalizeWhereCondition, normalizeWhereParams, extractWhereValues, prepareWhereContext, findQimenAppWithContract, queryFromDatabase, checkAuth, checkApiPermission, extractApiPermissionState, collectApiPermissionValue, setUserContext, systemInit -- app/service/openapiEntry.js (9) - - resolveOpenapiMethod, getOpenapiMethodService, resolveOpenapiContract, getInfo, dispatchOpenapiMethod, validateOpenapiParams, parseJsonBody, normalizeSignFields, processRequest - app/service/openapi/callback.js (4) - signCallback, sendWithRetry, sendByAppKey, logCallback - app/service/openapi/callbackRegistry.js (0) - +- app/service/openapiEntry.js (9) + - resolveOpenapiMethod, getOpenapiMethodService, resolveOpenapiContract, getInfo, dispatchOpenapiMethod, validateOpenapiParams, parseJsonBody, normalizeSignFields, processRequest - app/service/openapiMethods/callback.js (2) - resolveAppInfo, test - app/service/openapiMethods/deliveryorder.js (2) @@ -239,8 +299,8 @@ rg "class .*Service|module.exports" app/service/qimenMethods - list, reviewOrder - app/service/systemMethods/order/storageAllocation.js (0) - -- app/service/systemMethods/order/wave.js (222) - - buildBatchAllocateExpressTraceId, buildOrderOperationLogRows, batchCreateOrderOperationLogs, buildMachineStructureToken, parseMachineStructureToken, getOrderItemPart, getDefaultWaveQuantity, getMinGroupOrderFetchQuantity, getGroupWavePrefix, getSingleFetchByIdsWavePrefix, getWarehouseSubjectConfig, getWarehouseSubjectConfigValue, normalizeFetchStructureRequests, generateWaveId, getCurrentDatePart, VALUES, getNextWaveNoSequence, buildWaveNo, id, getWaveCreator, extractInsertId, extractLastInsertId, isDuplicateEntryError, createWaveBatchReady, buildFetchWhere, fetchSingleStructure, normalizeBoolean, normalizePositiveInteger, normalizeRequiredPositiveInteger, normalizeIdsInput, normalizePagination, normalizeWaveStatusList, normalizeBatchListStorageAssignmentStatusFilter, normalizeBatchListExpressAssignmentStatusFilter, normalizeBatchListPrintAssignmentStatusFilter, normalizeBatchListReviewAssignmentStatusFilter, getBatchListAssignmentFilterSchema, normalizeBatchListAssignmentStatusFilterByType, normalizeBatchListAssignmentStatusFilter, getModelTableSqlName, buildBatchListStorageAssignmentFilterClause, buildBatchListExpressAssignmentFilterClause, buildBatchListPrintAssignmentFilterClause, buildBatchListReviewAssignmentFilterClause, buildBatchListAssignmentStatusFilterClauseByType, buildBatchListAssignmentStatusFilterClause, buildBatchListWhereClause, normalizeWavePickTaskListPagination, normalizeWavePickTaskListRequest, buildWavePickTaskListWhereClause, resolveAssignmentStatus, normalizeSkuText, normalizeShopName, parseItemSnapshot, normalizeOrderItemRow, mergeOrderItemDetails, buildItemSummary, buildOrderItemSnapshot, buildItemSnapshotKey, orderMatchesIncludeSku, buildCoarseGroupKey, buildStatusSummary, buildGroupKey, groupOrderFetchList, singleOrderFetchList, waveStrategyList, getWaveStrategyNextFetchOrderCountMap, getWaveStrategyDebugFetchOrderListMap, previewWaveStrategyNextFetchOrderCount, getWaveStrategyMatchedOrderCountFilteredMap, waveStrategyCreate, waveStrategyUpdate, bumpWaveStrategyVersionAndInvalidateCache, getWaveStrategyModel, normalizeWaveStrategyId, normalizeWaveStrategyUpsertPayload, normalizeWaveStrategyWavePrefix, resolveWaveStrategyFetchWavePrefix, patchWaveStrategyIntegerField, validateWaveStrategyAllowedOwners, validateWaveStrategyAllowedExpresses, getWaveStrategyAvailableOwnerSet, getWaveStrategyAvailableExpressSet, applyWaveStrategyMaxSameStructureConstraint, normalizeWaveStrategyFallbackOrderListWhere, resolveWaveStrategyFallbackTrackingNo, resolveWaveStrategyFallbackStoreName, resolveWaveStrategyFallbackSysLogisticsName, buildWaveStrategyFallbackOrderListItem, waveStrategyFallbackOrderList, batchList, wavePickTaskList, batchCancel, batchCancelTaskProgress, batchAllocateExpress, batchAllocateExpressTaskProgress, batchAllocateStorage, batchAllocateStorageTaskProgress, submitWaveStrategyQuickScanForWarehouse, waveStrategyQuickScan, waveStrategyQuickScanTaskProgress, buildWaveStrategyQuickScanOrderWhere, getWaveStrategyQuickScanStrategyRows, getWaveStrategyQuickScanMatchModel, syncWaveStrategyQuickScanMatchedStrategies, cleanupWaveStrategyQuickScanMatchedStrategies, cleanupWaveStrategyQuickScanMatchedStrategiesByOrderIds, enqueueWaveStrategyQuickScanPostOrderChange, executeWaveStrategyQuickScan, runWaveStrategyQuickScanTask, batchUpdateWaveStrategyQuickScanOrders, generateWaveStrategyQuickScanTaskId, normalizeWaveStrategyQuickScanTaskId, getWaveStrategyQuickScanTaskCacheKey, setWaveStrategyQuickScanTaskProgress, getWaveStrategyQuickScanTaskProgress, getWaveStrategyQuickScanWarehouseLockCacheKey, setWaveStrategyQuickScanWarehouseLock, getWaveStrategyQuickScanWarehouseLock, clearWaveStrategyQuickScanWarehouseLock, normalizeWaveStrategyQuickScanVersion, normalizeWaveStrategyQuickScanList, normalizeWaveStrategyQuickScanNumberOrNull, normalizeWaveStrategyQuickScanBoolean, normalizeWaveStrategyQuickScanStringList, getWaveStrategyQuickScanStructureKey, getWaveStrategyQuickScanExpressKey, filterCandidateOrdersByRequireSameExpress, isWaveStrategyQuickScanOrderMatched, getWaveStrategyQuickScanMatchedStrategyIds, isWaveStrategyQuickScanOrderMatchedSingleStrategy, isWaveStrategyQuickScanValueInRange, resolveGroupCandidateOrderIdsForSingleFetch, singleFetchByIds, batchRemoveOrders, resortWaveIndex, batchRemoveExceptionOrders, batchRemoveExceptionOrdersTaskProgress, generateBatchCancelTaskId, normalizeBatchCancelTaskId, generateBatchRemoveExceptionOrdersTaskId, normalizeBatchRemoveExceptionOrdersTaskId, normalizeBatchRemoveExceptionOrdersWaveIds, getBatchRemoveExceptionOrdersTaskCacheKey, setBatchRemoveExceptionOrdersTaskProgress, getBatchRemoveExceptionOrdersTaskProgress, isExceptionRemovableOrder, runBatchRemoveExceptionOrdersTask, normalizeBatchCancelWaveIds, getBatchCancelTaskCacheKey, setBatchCancelTaskProgress, getBatchCancelTaskProgress, runBatchCancelTask, generateBatchAllocateExpressTaskId, normalizeBatchAllocateExpressTaskId, normalizeBatchAllocateExpressWaveIds, getBatchAllocateExpressTaskCacheKey, setBatchAllocateExpressTaskProgress, getBatchAllocateExpressTaskProgress, generateBatchAllocateStorageTaskId, normalizeBatchAllocateStorageTaskId, normalizeBatchAllocateStorageWaveIds, normalizeBatchAllocateStorageTaskCount, buildBatchAllocateStorageRunningProgressPayload, normalizeBatchAllocateStorageOrderIds, getBatchAllocateStorageTaskCacheKey, getBatchAllocateStorageWarehouseLockKey, tryAcquireBatchAllocateStorageWarehouseLock, releaseBatchAllocateStorageWarehouseLock, setBatchAllocateStorageTaskProgress, getBatchAllocateStorageTaskProgress, isMissingBusinessKeyColumnError, runBatchAllocateExpressTask, runBatchAllocateStorageTask, batchAutoGrouping, batchFinishAutoGrouping, generateFetchTaskId, normalizeFetchTaskId, getFetchTaskCacheKey, setFetchTaskProgress, getFetchTaskProgress, fetchTaskProgress, runFetchTask, submitFetchTask, groupFetch, singleFetch, resolveWaveStrategyFetchPickMode, buildWaveStrategyFetchBoxAssignments, prepareWaveStrategyFetchPlan, in, ensureNoActiveWavePickTaskForOperator, getWaveStrategyFetchCandidateOrders, groupWaveStrategyFetchCandidateOrdersByStructure, buildWaveStrategyFetchOrderSkuMap, selectWaveStrategyFetchOrdersBySkuLimit, createWaveBatchByOrderIdsInTransaction, autoPopulateWaveStrategyFetchSelections, executeWaveStrategyDirectFetch, createWavePickTaskFromPlan, buildTaskCreatePayload, buildTaskWaveRows, buildTaskOrderRows, buildTaskSkuRows, buildTaskBoxRows, bindPickCartForTask, initTaskCheckpointAndLogs, ensurePickCartAvailable, generateWavePickTaskNo, createWavePickTaskWithRetry, isTaskNoDuplicateError, bulkInsertRows, parseWaveStrategyExistingTaskInfo, waveStrategyFetchPda, cancelWavePickTasksInternal, wavePickTaskCancel, wavePickTaskCancelSelf, waveStrategyFetchAdmin, deleteOrderWaveIndexByOrderIds, deleteOrderWaveIndexByWaveIds, rebuildOrderWaveIndex, replaceOrderWaveIndexByWaveIds, fetch +- app/service/systemMethods/order/wave.js (223) + - buildBatchAllocateExpressTraceId, buildOrderOperationLogRows, batchCreateOrderOperationLogs, buildMachineStructureToken, parseMachineStructureToken, getOrderItemPart, getDefaultWaveQuantity, getMinGroupOrderFetchQuantity, getGroupWavePrefix, getSingleFetchByIdsWavePrefix, getWarehouseSubjectConfig, getWarehouseSubjectConfigValue, normalizeFetchStructureRequests, generateWaveId, getCurrentDatePart, VALUES, getNextWaveNoSequence, buildWaveNo, id, getWaveCreator, extractInsertId, extractLastInsertId, isDuplicateEntryError, createWaveBatchReady, buildFetchWhere, fetchSingleStructure, normalizeBoolean, normalizePositiveInteger, normalizeRequiredPositiveInteger, normalizeIdsInput, normalizePagination, normalizeWaveStatusList, normalizeBatchListStorageAssignmentStatusFilter, normalizeBatchListExpressAssignmentStatusFilter, normalizeBatchListPrintAssignmentStatusFilter, normalizeBatchListReviewAssignmentStatusFilter, getBatchListAssignmentFilterSchema, normalizeBatchListAssignmentStatusFilterByType, normalizeBatchListAssignmentStatusFilter, getModelTableSqlName, buildBatchListStorageAssignmentFilterClause, buildBatchListExpressAssignmentFilterClause, buildBatchListPrintAssignmentFilterClause, buildBatchListReviewAssignmentFilterClause, buildBatchListAssignmentStatusFilterClauseByType, buildBatchListAssignmentStatusFilterClause, buildBatchListWhereClause, normalizeWavePickTaskListPagination, normalizeWavePickTaskListRequest, buildWavePickTaskListWhereClause, resolveAssignmentStatus, normalizeSkuText, normalizeShopName, parseItemSnapshot, normalizeOrderItemRow, mergeOrderItemDetails, buildItemSummary, buildOrderItemSnapshot, buildItemSnapshotKey, orderMatchesIncludeSku, buildCoarseGroupKey, buildStatusSummary, buildGroupKey, groupOrderFetchList, singleOrderFetchList, waveStrategyList, getWaveStrategyNextFetchOrderCountMap, getWaveStrategyDebugFetchOrderListMap, previewWaveStrategyNextFetchOrderCount, getWaveStrategyMatchedOrderCountFilteredMap, waveStrategyCreate, waveStrategyUpdate, bumpWaveStrategyVersionAndInvalidateCache, getWaveStrategyModel, normalizeWaveStrategyId, normalizeWaveStrategyUpsertPayload, normalizeWaveStrategyWavePrefix, resolveWaveStrategyFetchWavePrefix, patchWaveStrategyIntegerField, validateWaveStrategyAllowedOwners, validateWaveStrategyAllowedExpresses, getWaveStrategyAvailableOwnerSet, getWaveStrategyAvailableExpressSet, applyWaveStrategyMaxSameStructureConstraint, normalizeWaveStrategyFallbackOrderListWhere, resolveWaveStrategyFallbackTrackingNo, resolveWaveStrategyFallbackStoreName, resolveWaveStrategyFallbackSysLogisticsName, buildWaveStrategyFallbackOrderListItem, waveStrategyFallbackOrderList, resolveWaveBatchOwnerStoreNameMap, batchList, wavePickTaskList, batchCancel, batchCancelTaskProgress, batchAllocateExpress, batchAllocateExpressTaskProgress, batchAllocateStorage, batchAllocateStorageTaskProgress, submitWaveStrategyQuickScanForWarehouse, waveStrategyQuickScan, waveStrategyQuickScanTaskProgress, buildWaveStrategyQuickScanOrderWhere, getWaveStrategyQuickScanStrategyRows, getWaveStrategyQuickScanMatchModel, syncWaveStrategyQuickScanMatchedStrategies, cleanupWaveStrategyQuickScanMatchedStrategies, cleanupWaveStrategyQuickScanMatchedStrategiesByOrderIds, enqueueWaveStrategyQuickScanPostOrderChange, executeWaveStrategyQuickScan, runWaveStrategyQuickScanTask, batchUpdateWaveStrategyQuickScanOrders, generateWaveStrategyQuickScanTaskId, normalizeWaveStrategyQuickScanTaskId, getWaveStrategyQuickScanTaskCacheKey, setWaveStrategyQuickScanTaskProgress, getWaveStrategyQuickScanTaskProgress, getWaveStrategyQuickScanWarehouseLockCacheKey, setWaveStrategyQuickScanWarehouseLock, getWaveStrategyQuickScanWarehouseLock, clearWaveStrategyQuickScanWarehouseLock, normalizeWaveStrategyQuickScanVersion, normalizeWaveStrategyQuickScanList, normalizeWaveStrategyQuickScanNumberOrNull, normalizeWaveStrategyQuickScanBoolean, normalizeWaveStrategyQuickScanStringList, getWaveStrategyQuickScanStructureKey, getWaveStrategyQuickScanExpressKey, filterCandidateOrdersByRequireSameExpress, isWaveStrategyQuickScanOrderMatched, getWaveStrategyQuickScanMatchedStrategyIds, isWaveStrategyQuickScanOrderMatchedSingleStrategy, isWaveStrategyQuickScanValueInRange, resolveGroupCandidateOrderIdsForSingleFetch, singleFetchByIds, batchRemoveOrders, resortWaveIndex, batchRemoveExceptionOrders, batchRemoveExceptionOrdersTaskProgress, generateBatchCancelTaskId, normalizeBatchCancelTaskId, generateBatchRemoveExceptionOrdersTaskId, normalizeBatchRemoveExceptionOrdersTaskId, normalizeBatchRemoveExceptionOrdersWaveIds, getBatchRemoveExceptionOrdersTaskCacheKey, setBatchRemoveExceptionOrdersTaskProgress, getBatchRemoveExceptionOrdersTaskProgress, isExceptionRemovableOrder, runBatchRemoveExceptionOrdersTask, normalizeBatchCancelWaveIds, getBatchCancelTaskCacheKey, setBatchCancelTaskProgress, getBatchCancelTaskProgress, runBatchCancelTask, generateBatchAllocateExpressTaskId, normalizeBatchAllocateExpressTaskId, normalizeBatchAllocateExpressWaveIds, getBatchAllocateExpressTaskCacheKey, setBatchAllocateExpressTaskProgress, getBatchAllocateExpressTaskProgress, generateBatchAllocateStorageTaskId, normalizeBatchAllocateStorageTaskId, normalizeBatchAllocateStorageWaveIds, normalizeBatchAllocateStorageTaskCount, buildBatchAllocateStorageRunningProgressPayload, normalizeBatchAllocateStorageOrderIds, getBatchAllocateStorageTaskCacheKey, getBatchAllocateStorageWarehouseLockKey, tryAcquireBatchAllocateStorageWarehouseLock, releaseBatchAllocateStorageWarehouseLock, setBatchAllocateStorageTaskProgress, getBatchAllocateStorageTaskProgress, isMissingBusinessKeyColumnError, runBatchAllocateExpressTask, runBatchAllocateStorageTask, batchAutoGrouping, batchFinishAutoGrouping, generateFetchTaskId, normalizeFetchTaskId, getFetchTaskCacheKey, setFetchTaskProgress, getFetchTaskProgress, fetchTaskProgress, runFetchTask, submitFetchTask, groupFetch, singleFetch, resolveWaveStrategyFetchPickMode, buildWaveStrategyFetchBoxAssignments, prepareWaveStrategyFetchPlan, in, ensureNoActiveWavePickTaskForOperator, getWaveStrategyFetchCandidateOrders, groupWaveStrategyFetchCandidateOrdersByStructure, buildWaveStrategyFetchOrderSkuMap, selectWaveStrategyFetchOrdersBySkuLimit, createWaveBatchByOrderIdsInTransaction, autoPopulateWaveStrategyFetchSelections, executeWaveStrategyDirectFetch, createWavePickTaskFromPlan, buildTaskCreatePayload, buildTaskWaveRows, buildTaskOrderRows, buildTaskSkuRows, buildTaskBoxRows, bindPickCartForTask, initTaskCheckpointAndLogs, ensurePickCartAvailable, generateWavePickTaskNo, createWavePickTaskWithRetry, isTaskNoDuplicateError, bulkInsertRows, parseWaveStrategyExistingTaskInfo, waveStrategyFetchPda, cancelWavePickTasksInternal, wavePickTaskCancel, wavePickTaskCancelSelf, waveStrategyFetchAdmin, deleteOrderWaveIndexByOrderIds, deleteOrderWaveIndexByWaveIds, rebuildOrderWaveIndex, replaceOrderWaveIndexByWaveIds, fetch - app/service/systemMethods/outbound.js (1) - autoOutbound - app/service/systemMethods/pick.js (14) @@ -253,10 +313,16 @@ rg "class .*Service|module.exports" app/service/qimenMethods - list, update, setRecording, cancelRecording, delete - app/service/systemMethods/printer/station.js (1) - list +- app/service/systemMethods/report.js (7) + - generate, generateTaskProgress, generateExportTaskId, normalizeExportTaskId, getExportTaskCacheKey, setExportTaskProgress, getExportTaskProgress +- app/service/systemMethods/report/deliveryLog.js (1) + - list +- app/service/systemMethods/report/deliveryPlan.js (2) + - save, list - app/service/systemMethods/returnReceived.js (5) - _call, create, list, detail, delete -- app/service/systemMethods/returnUnpack.js (13) - - _call, create, addDetail, updateDetail, removeDetail, cancel, submit, forceRecord, list, detailList, videoList, detail, delete +- app/service/systemMethods/returnUnpack.js (15) + - _call, create, addDetail, updateDetail, removeDetail, cancel, submit, forceRecord, list, detailList, videoList, detail, export, exportTaskProgress, delete - app/service/systemMethods/returnWaybill.js (6) - _call, create, update, list, detail, delete - app/service/systemMethods/setting/account.js (7) @@ -307,8 +373,8 @@ rg "class .*Service|module.exports" app/service/qimenMethods - replenishmentDemand - app/service/systemMethods/storage/receiving.js (29) - getReceivingList, getStoreReceivingList, getReceivingDetail, batchCancelReceiving, create, bindStore, bindDetailProduct, addItem, removeItem, save, get, addDetail, deleteDetail, detailChange, cancel, completeReceiving, rejectReceiving, reviewReceiving, queryReceivingLogs, scanDetail, export, exportTaskProgress, generateExportTaskId, normalizeExportTaskId, getExportTaskCacheKey, setExportTaskProgress, getExportTaskProgress, storeExport, storeExportTaskProgress -- app/service/systemMethods/storage/stockout.js (5) - - list, toOrder, listItems, confirm, updateExpress +- app/service/systemMethods/storage/stockout.js (10) + - list, toOrder, _restoreStockoutLocks, _writeStockoutOperationLog, listItems, listLogs, confirm, cancel, updateExpress, updateInfo - app/service/systemMethods/storage/transaction.js (1) - list - app/service/systemMethods/store_express_binding_policy.js (5) @@ -347,24 +413,24 @@ rg "class .*Service|module.exports" app/service/qimenMethods - list, detail, create, update, delete - app/service/systems/comboGoods.js (15) - fetchStockInfoMap, buildSimpleNotation, buildNameNotation, validateItems, getTargetStoreIdFromMap, checkCustomCodeUniqueForCreate, checkCustomCodeUniqueForUpdate, list, buildListWhere, create, update, delete, search, searchByIdOrCode, enrichComboList -- app/service/systems/delivery_order.js (47) - - getStoreSubjectConfigCacheKey, normalizeStoreSubjectConfig, getStoreSubjectConfig, findCodeOption, getOptionName, appendOrderOperationLog, getOrderLogOperator, getOrderLogWarehouseId, flushOrderOperationLogs, findPlatformOptionByCode, getPlatformSnapshotCode, getPlatformSnapshotName, resolvePlatformSnapshot, resolveExpressCodeFromSetting, resolveExpressSettingSnapshot, resolveEnableExternalExpressCode, resolveExpressSnapshot, addOrder, isPrimaryKeyDuplicate, formatOrderCreateError, resolveOrderStep, generateItemsHash, calculateCRC32, normalizeOrderFromKey, resolveOperatorName, prepareOrderData, addOrderLines, buildOrderItemSnapshot, safeParseFloat, withPatchedCtxUser, buildAsyncProcessContext, buildExpressAllocateRequest, buildStorageAllocateRequest, getStoreWarehousePolicyConfig, normalizePolicyFlag, resolveCutoffOrderConfig, isPastCutoffTime, buildAutoGroupingStructure, findAutoGroupingWaveId, appendOrderToWave, countCandidateGroupOrders, createGroupingWave, markWaveAutoGrouping, finishAutoGroupingIfNeeded, runAutoGrouping, runAsyncProcessStep, asyncProcessOrderCreated +- app/service/systems/delivery_order.js (48) + - getStoreSubjectConfigCacheKey, normalizeStoreSubjectConfig, getStoreSubjectConfig, findCodeOption, getOptionName, appendOrderOperationLog, getOrderLogOperator, getOrderLogWarehouseId, flushOrderOperationLogs, findPlatformOptionByCode, getPlatformSnapshotCode, getPlatformSnapshotName, resolvePlatformSnapshot, resolveExpressCodeFromSetting, resolveExpressSettingSnapshot, resolveEnableExternalExpressCode, resolveExpressSnapshot, addOrder, isPrimaryKeyDuplicate, formatOrderCreateError, resolveOrderStep, generateItemsHash, calculateCRC32, normalizeOrderFromKey, resolveOperatorName, prepareOrderData, addOrderLines, buildOrderItemSnapshot, safeParseFloat, withPatchedCtxUser, buildAsyncProcessContext, buildExpressAllocateRequest, enqueueAutoWaybillAllocation, buildStorageAllocateRequest, getStoreWarehousePolicyConfig, normalizePolicyFlag, resolveCutoffOrderConfig, isPastCutoffTime, buildAutoGroupingStructure, findAutoGroupingWaveId, appendOrderToWave, countCandidateGroupOrders, createGroupingWave, markWaveAutoGrouping, finishAutoGroupingIfNeeded, runAutoGrouping, runAsyncProcessStep, asyncProcessOrderCreated - app/service/systems/entry_order.js (16) - addOrder, getLineCount, received, success, fail, findByOrderCode, findByStatus, getStatsByWarehouse, updateSyncStatus, updateOrderStatus, calculateReceivedQuantities, batchUpdateReceived, getOrderProgress, tryCreateEntryOrder, addItems, reviewEntry - app/service/systems/excel.js (24) - getContentType, sanitizeSheetName, normalizeHeaders, normalizeColumns, prepareSheetData, hasEmbeddedImages, buildWorksheet, buildWorkbook, buildExcelJsWorkbook, inferImageExtension, resolveImageSource, mergeCellStyle, applyStyledRows, addEmbeddedImages, generateBuffer, writeFile, writeAtomicBufferFile, sanitizeFilename, buildUploadKey, generateAndUpload, sendFile, parseBuffer, parseFile, workbookToJSON -- app/service/systems/express_platform.js (15) - - getOrderLogOperator, buildOrderExpressVerPatch, buildExpressPlatformTraceId, OrderExpress, cleanupFailedWaybillOrders, buildFailedOrderCleanupList, polyapi, cainiao, parsePlatformPrintData, stringifyPlatformPrintData, buildWaybillOrderMetaMap, buildWaybillSettlementRelationMap, persistWaybillSuccessUpdates, normalizePddExtData, pdd -- app/service/systems/express_policy.js (9) - - getWarehousePolicyCacheKey, getWarehousePolicyCacheTTL, clearWarehousePolicyCache, fetchWarehousePoliciesFromDB, getWarehousePolicies, _matchAnyToken, _matchAnyIntersect, _matchValueInArray, matchPolicy +- app/service/systems/express_platform.js (16) + - getOrderLogOperator, buildOrderExpressVerPatch, buildExpressPlatformTraceId, OrderExpress, cleanupFailedWaybillOrders, buildFailedOrderCleanupList, polyapi, cainiao, parsePlatformPrintData, stringifyPlatformPrintData, buildWaybillOrderMetaMap, buildWaybillSettlementRelationMap, lockAndDeductWaybillSettlement, persistWaybillSuccessUpdates, normalizePddExtData, pdd +- app/service/systems/express_policy.js (10) + - getWarehousePolicyCacheKey, getWarehousePolicyCacheTTL, clearWarehousePolicyCache, fetchWarehousePoliciesFromDB, getWarehousePolicies, _matchAnyToken, _matchAnyIntersect, _matchValueInArray, _isStoreOnlyPolicy, matchPolicy - app/service/systems/express.js (72) - getExpressListCacheKey, getCurrentWarehouseId, buildWaybillTraceId, getOrderLogOperator, getOrderLogWarehouseId, createAllocateExpressFailureLogs, normalizeWaybillBusinessKeys, normalizeWaybillCreatePlatformCode, normalizeWaybillPolicyConfig, buildWaybillBalanceExceptionText, normalizeWaybillCreateOrders, buildWaybillCreateRelationGroups, collectWaybillRelationProcessingState, buildWaybillRelationLockMap, lockWaybillRelationBalance, markWaybillOrdersAsException, writeWaybillOrderExceptions, writeDispatchOrderFlags, markWaybillAsyncOrdersAsError, buildMergedExpressLabel, normalizeExpressSettingRow, loadExpressSettingListFromDatabase, buildExpressSettingCustomCodeList, buildMergedExpressList, getExpressProductTypeListCacheKey, normalizeExpressProductTypeRow, normalizeExpressCodeKey, isSfExpressCode, extractExpressProductTypesFromTypeDesc, collectPddSfTimedDeliveryProductTypes, clearExpressProductTypeCache, upsertExpressProductTypeList, syncPddSfTimedDeliveryExpressProductTypes, normalizeExpressRow, loadExpressList, loadExpressListFromCache, loadExpressListFromDatabase, getSystemExpressList, loadExpressProductTypeListFromDatabase, getExpressList, getExpressProductTypeList, normalizeWaybillPrintPlatformCode, loadWaybillPrintPlatformCodeMap, loadWaybillAsyncRequestPlatformCodeMap, Map, resolveWaybillAsyncRequestPlatformCode, resolveWaybillGroupPrintPlatformCode, groupWaybillOrdersByPlatformAndLogistics, splitWaybillOrdersIntoBatches, pickWaybillExpressInterface, resolveWaybillAsyncPlatformCode, groupWaybillAsyncOrdersByPlatform, buildWaybillOrderDeliveryMap, normalizeWaybillAsyncText, normalizeWaybillAsyncNumber, formatWaybillAsyncDate, normalizeWaybillAsyncItems, buildWaybillAsyncRouteInfo, buildWaybillAsyncOrderInfo, buildWaybillAsyncReceiverInfo, buildWaybillAsyncSettlementInfo, buildWaybillAsyncItemsSummary, buildWaybillAsyncOrderListItem, buildWaybillAsyncBizcontentSkeleton, shouldDispatchWaybillAsyncPerOrder, dispatchWaybillAsyncPlatform, resolveWaybillAsyncDispatchPlatformCode, hardDeleteWaybillAsyncOrderExpressRows, getWaybillAsyncOrderDeliveryModel, createWaybillCodePipeline, asyncTask, createWaybillCode - app/service/systems/fast_where.js (13) - buildTree, getTreeByType, buildSubTree, getWithChildrenByType, getAllChildren, getByType, getGroups, getChildrenByPid, getTreeChildrenByPid, create, update, findById, delete - app/service/systems/file.js (2) - getImages, ReferenceFile -- app/service/systems/inbound_direct_log.js (10) - - getItems, _addSingleItem, _bindReceivingDetail, addItem, removeItem, commit, _sendOpenApiCallback, operationLog, qimenEntrySync, _syncReceivingStorageStatus +- app/service/systems/inbound_direct_log.js (11) + - getItems, _addSingleItem, _bindReceivingDetail, addItem, removeItem, commit, _sendOpenApiCallback, operationLog, qimenEntrySync, _syncReceivingStorageStatus, _applyReceivingStockOccupancy - app/service/systems/inbox/group.js (8) - list, disable, update, reset, validateExpressInterfaces, validateSystemExpressCode, findGroupsByExpress, findStoreAfterSalesGroups - app/service/systems/license_plate.js (7) @@ -381,16 +447,16 @@ rg "class .*Service|module.exports" app/service/qimenMethods - buildTextContent, buildMarkdownContent, buildRequestData, send - app/service/systems/notice/index.js (28) - getDriver, normalizeMessageType, toObject, normalizeEventList, matchesEvents, buildTraceId, getRegisteredEventCodes, isValidEventCode, assertEventRegistered, getRetryDelays, sleep, isSuccessfulResponse, getFailureMessage, persistFailureLog, sendWithRetry, getStoreInfoCacheKey, resolveStoreInfo, resolveSubjectConfig, normalizePayload, buildOutgoingPayload, getWebhookLimit, findMatchedWebhooks, getFixedGroupTargets, findSubscribedGroups, resolveStoreLabelInternal, sendToWarehouseChannel, send, sendViaWebhooks -- app/service/systems/operation_log.js (13) - - buildOperationLogData, buildBusinessLogWhere, formatOperationLogRows, createOperationLog, createOperationLogs, queryLogsByBusinessType, queryStockLogs, queryOrderLogs, queryAllOrderLogs, queryAllLogsByBusinessType, queryReceivingLogs, queryEntryOrderLogs, getMessageDetail -- app/service/systems/order_async.js (5) - - finalizeSuccessfulQimenSync, syncQmOrders, syncManualOrders, flushDeferredOrderSyncNotices, syncApiOrders +- app/service/systems/operation_log.js (14) + - buildOperationLogData, buildBusinessLogWhere, formatOperationLogRows, createOperationLog, createOperationLogs, queryLogsByBusinessType, queryStockLogs, queryOrderLogs, queryAllOrderLogs, queryAllLogsByBusinessType, queryReceivingLogs, queryEntryOrderLogs, queryStockoutLogs, getMessageDetail +- app/service/systems/order_async.js (6) + - finalizeSuccessfulQimenSync, syncQmOrders, syncManualOrders, flushDeferredOrderSyncNotices, syncApiOrders, syncStockoutOrders - app/service/systems/order_auto_outbound.js (7) - getEnabledAutoOutboundWarehouses, normalizeSubjectConfigForAutoOutbound, buildAutoOutboundWhere, findAutoOutboundOrders, findOrderIdsWithWeigh, processWarehouseAutoOutbound, executeAutoOutbound - app/service/systems/order_delivery_migration.js (15) - syncOutboundOrdersToDelivery, retryTimeoutOutboundOrdersToDelivery, syncOutboundOrdersByStatus, normalizeWarehouseIds, listCurrentWarehouseIds, normalizeOutboundStatuses, buildMigrationQueryOptions, getOutboundMigrationErrorInfo, markOutboundOrdersTimeout, buildDispatchKey, buildDispatchRow, buildDispatchItemRow, getMigrationModels, buildTargetOrderIdMap, syncOutboundOrdersForWarehouse -- app/service/systems/order_export.js (12) - - getExportPageSize, normalizeExportModuleName, getSortModuleNameByTableType, resolveExportTarget, getOrderExportColumns, buildOrderExportFilename, buildUploadKey, toPlainRow, normalizeExportCellValue, mapOrderExportRow, uploadOrderExportFile, exportOrders +- app/service/systems/order_export.js (14) + - getExportPageSize, normalizeExportModuleName, getSortModuleNameByTableType, resolveExportTarget, getOrderExportColumns, normalizeExportColumns, buildOrderExportFilename, buildUploadKey, toPlainRow, normalizeExportCellValue, mapOrderExportRow, uploadOrderExportFile, buildOrderExportPage, exportOrders - app/service/systems/order_express.js (30) - createBusinessError, normalizeOrderId, normalizeWaybillCode, normalizePackageMaterialCode, normalizePackageMaterialId, normalizeBindOrderId, getCurrentWarehouseId, findActivePackageMaterialById, findActivePackageMaterialByCode, findValidOrderExpressByOrderAndWaybill, findOrderInterceptStatus, assertOrderNotIntercepted, normalizeWeighingWeight, findValidOrderExpressRows, updateWeighingWeight, updateWeighingWeightByWaybill, _updateWaveAllOrdersWeight, _buildWaveWeighingSummary, _getStoreName, _getWaveSysLogisticsName, _updateSingleOrderWeight, _updateWaveOrderWeight, _writeWeighActionLog, _tryWaveCompatibility, _upsertPackageMaterialItemRelation, bindExpressPackageMaterial, bindExpressPackageMaterialByWaybill, _bindSingleExpressPackageMaterial, _bindWavePackageMaterialByBusinessKey, _writePackageMaterialActionLog - app/service/systems/order_outbound.js (1) @@ -427,10 +493,20 @@ rg "class .*Service|module.exports" app/service/qimenMethods - qimenClient, send, sendRequest - app/service/systems/receiving_entry_match.js (12) - matchAfterEntryCompleted, _bindEntryOrderReceiving, bindEntryOrderReceiving, _getRecentReceivingOrders, _findReceivingByRemark, _compareDetails, _sendCallback, _sendQimenCallback, _sendOpenApiCallback, _markReceivingPartialStorage, _commitBinding, unbindEntryOrderReceiving -- app/service/systems/return_received.js (14) - - createBusinessError, create, _handleInterceptAfterSale, _updateOrderInterceptStatus, list, detail, delete, _findByIdChecked, _enrichReturn, _resolveStoreRemark, _buildListWhere, _resolveConditionValue, _extractConditionValue, _buildListOrder -- app/service/systems/return_unpack.js (35) - - _getRecordingComputerId, _buildVideoUrl, createBusinessError, create, addDetail, updateDetail, removeDetail, cancel, submit, forceRecord, list, detailList, videoList, detail, queryByWaybill, _resolveWarehouseName, _resolveStoreIdByWaybill, _resolveReturnOrderInfo, delete, _findByIdChecked, _assertUnpacking, _findDetailChecked, _recalcMain, _enrichRow, _flattenVideos, _enrichDetailsWithStock, _resolveStoreRemark, VALUES, _generateUnpackNo, _buildListWhere, _buildDetailListWhere, _buildVideoListWhere, _buildVideoListOrder, _resolveConditionValue, _buildListOrder +- app/service/systems/report.js (7) + - getDefinition, parseJsonField, resolveQuerier, buildFilename, buildWorkbookSheets, generate, generateBuffer +- app/service/systems/report/queries/generic.js (0) + - +- app/service/systems/report/queries/index.js (0) + - +- app/service/systems/report/queries/sevenDayStockFlow.js (0) + - +- app/service/systems/reportDelivery.js (17) + - normalizeScheduleTimes, savePlan, planToView, listPlans, listLogs, hitTimePoints, bizDateOfTrigger, bizDateOfTimePoint, resolveStoreWarehouse, markDelivered, markFailed, markExporting, buildMessageContent, deliverByChannel, processOne, parseScheduleTimes, dispatch +- app/service/systems/return_received.js (15) + - createBusinessError, create, notifyPending, _handleInterceptAfterSale, _updateOrderInterceptStatus, list, detail, delete, _findByIdChecked, _enrichReturn, _resolveStoreRemark, _buildListWhere, _resolveConditionValue, _extractConditionValue, _buildListOrder +- app/service/systems/return_unpack.js (42) + - _getRecordingComputerId, _buildVideoUrl, createBusinessError, create, addDetail, updateDetail, removeDetail, cancel, submit, _notifyUnpacked, forceRecord, list, detailList, videoList, exportUnpack, _resolveStoreNameMap, _resolveExpressNameMap, _extractDetailColor, detail, _buildWaybillMatch, _findWaybillFlexible, queryByWaybill, _resolveWarehouseName, _resolveStoreIdByWaybill, _resolveReturnOrderInfo, delete, _findByIdChecked, _assertUnpacking, _findDetailChecked, _recalcMain, _enrichRow, _flattenVideos, _enrichDetailsWithStock, _resolveStoreRemark, VALUES, _generateUnpackNo, _buildListWhere, _buildDetailListWhere, _buildVideoListWhere, _buildVideoListOrder, _resolveConditionValue, _buildListOrder - app/service/systems/return_waybill.js (12) - createBusinessError, create, update, list, detail, delete, _findByIdChecked, _assertStoreContract, _formatRow, _buildListWhere, _resolveConditionValue, _buildListOrder - app/service/systems/setting/account.js (31) @@ -453,8 +529,8 @@ rg "class .*Service|module.exports" app/service/qimenMethods - createError, getCurrentStoreId, getCurrentEmployeeId, toPositiveNumber, getEmployee, normalizeRoleIds, findAssignableRoles, clearEmployeeCache, getCurrentEmployeeRoleIds, collectDescendantRoleIds, buildRolePermissionMap, buildRoleTree, normalizeStoreScope, isRoleVisibleInScope, normalizePermissionIds, normalizePid, getManageableRole, validatePermissionSet, replaceRolePermissions, clearRoleUsersCache, list, permission, add, delete, update - app/service/systems/setting/store_warehouse.js (35) - createError, getCurrentStoreId, getCurrentAccountId, toPositiveNumber, normalizePage, normalizeStatusFlag, normalizeAuthStatus, normalizeNonNegativeInteger, normalizeText, normalizeDate, normalizeSignAction, normalizeTempCode, getTempCodeCacheKey, createTempCode, pickRemaskField, resolveRemaskValue, buildCurrentRemaskPatch, requireCurrentRemaskPatch, saveTempSignPayload, getTempSignPayload, clearTempSignPayload, buildTempSignView, getCurrentSubject, getCounterparty, buildListWhere, getRelationIncludes, resolvePairIds, serializeRelation, findScopedRelation, list, sign, trimContract, confirmSign, rename, unbind -- app/service/systems/setting/warehouse.js (11) - - getDefaultCodeFieldOptionsMap, normalizeWaveStrategyVersion, normalizeSubjectConfigInternalFields, sanitizeSubjectConfigForOutput, createError, getCurrentWarehouseId, deleteCacheByKey, clearWarehouseSettingCache, getFieldMeta, getSettings, saveSettings +- app/service/systems/setting/warehouse.js (12) + - getDefaultCodeFieldOptionsMap, normalizeWaveStrategyVersion, normalizeSubjectConfigInternalFields, sanitizeSubjectConfigForOutput, createError, getCurrentWarehouseId, deleteCacheByKey, clearWarehouseSettingCache, getFieldMeta, getSettings, validateDefaultLocation, saveSettings - app/service/systems/shops.js (20) - generatePendingShopName, createError, getCurrentWarehouseId, normalizeText, normalizeInteger, ensureShopPrintPlatformExists, getListWhereSpecialFieldMap, buildListWhere, normalizePagination, buildShopPrintPlatformInclude, formatShopRow, list, ensureShopNameUnique, add, findShopById, del, edit, generateAuthorizeRandomCode, createOrReuseAuthorizeReservation, getAuthorizeSessionKey - app/service/systems/sign.js (10) @@ -467,8 +543,8 @@ rg "class .*Service|module.exports" app/service/qimenMethods - normalizeInboundOrderId, isOrderOutboundTransaction, resolveOutboundOrderReference, create, list, _resolveKeywordToStockIds, queryList, exportList - app/service/systems/stock_warehouse.js (3) - _buildStockDetailCacheKey, getStockDetails, invalidateStockDetailCache -- app/service/systems/storage/entry.js (24) - - normalizeExpenseRecordValue, normalizeExpenseRecordCondition, normalizeFilterValues, buildEntryStockTransactionExistsCondition, buildHasReceivingCondition, preprocessEntryListWhere, list, get, IN, enrichItemsWithAvailableReceivingDetails, normalizeCancelEntryOrderIds, getOwnedEntryOrderById, cancel, _rollbackReceivingStorageStatus, addItem, commit, removeItem, getReceivingDetailsForBind, containerList, quickInbound, receivingCompare, _buildMergedComparison, exportEntryOrders, exportStoreEntryOrders +- app/service/systems/storage/entry.js (25) + - normalizeExpenseRecordValue, normalizeExpenseRecordCondition, normalizeFilterValues, buildEntryStockTransactionExistsCondition, buildHasReceivingCondition, preprocessEntryListWhere, list, get, IN, enrichItemsWithAvailableReceivingDetails, normalizeCancelEntryOrderIds, getOwnedEntryOrderById, cancel, _rollbackReceivingStorageStatus, addItem, commit, removeItem, getReceivingDetailsForBind, containerList, _applyReceivingInboundUsage, quickInbound, receivingCompare, _buildMergedComparison, exportEntryOrders, exportStoreEntryOrders - app/service/systems/storage/expiry.js (1) - list - app/service/systems/storage/index.js (10) @@ -477,8 +553,8 @@ rg "class .*Service|module.exports" app/service/qimenMethods - createTransferStockTransactions, transferLocation, transferByProduct, resolveStockQueryToStockIds, getInventoryList, getStorageListByStockId, _aggregateStorageRowsBySpace, _loadInventoryWarningRanges, _formatBatchStorageRows, quickPutaway, directPutaway, exportInventoryList, _generateEntryOrderCode - app/service/systems/storage/management.js (1) - replenishmentDemand -- app/service/systems/storage/receiving.js (40) - - getReceivingList, _resolveStockQueryReceivingIds, getStoreReceivingList, getReceivingDetail, batchCancelReceiving, rejectReceiving, reviewReceiving, buildReviewReportSheets, sendStoreBoundNotice, sendReviewNotice, isEmptyValue, buildSequelizeCondition, processConditionValue, buildReceivingNumberPrefix, generateNextReceivingNumber, isReceivingNumberDuplicateError, create, save, bindStore, get, addDetail, bindDetailProduct, updateDetail, getStockStoreInfo, updateReceivingStats, deleteDetail, detailChange, invalid, formatReportDate, formatDeliveryMethod, getCompletionContactFields, Map, buildCompletionReportSheets, uploadCompletionExcelReport, sendCompletionNotice, completeReceiving, _syncProductDataFromReceiving, scanDetail, exportReceivingList, exportStoreReceivingList +- app/service/systems/storage/receiving.js (43) + - getReceivingList, _resolveStockQueryReceivingIds, getStoreReceivingList, getReceivingDetail, batchCancelReceiving, rejectReceiving, reviewReceiving, buildReviewReportSheets, sendStoreBoundNotice, resolveReceivingCreatorName, sendReviewNotice, resolveReviewDetailItemCodeMap, isEmptyValue, buildSequelizeCondition, processConditionValue, buildReceivingNumberPrefix, generateNextReceivingNumber, isReceivingNumberDuplicateError, create, save, bindStore, get, addDetail, bindDetailProduct, updateDetail, getStockStoreInfo, updateReceivingStats, deleteDetail, detailChange, invalid, formatReportDate, formatDeliveryMethod, getCompletionContactFields, Map, buildCompletionReportSheets, uploadCompletionExcelReport, sendCompletionNotice, sendStoreUnmatchedNotice, completeReceiving, _syncProductDataFromReceiving, scanDetail, exportReceivingList, exportStoreReceivingList - app/service/systems/storage/report.js (5) - loadReportReferenceMaps, buildExportFilename, export, _resolveKeywordToStockIds, search - app/service/systems/storage/stock_warehouse.js (3) @@ -489,16 +565,16 @@ rg "class .*Service|module.exports" app/service/qimenMethods - createError, getCurrentStoreId, getCurrentAccountId, toPositiveNumber, normalizePage, normalizeStatusFlag, normalizeAuthStatus, normalizeNonNegativeInteger, normalizeInteger, normalizeText, normalizeIntegerRange, normalizeEmail, getPolicyConfigFieldList, getPolicyConfigFieldMetaList, normalizePolicyConfig, getPolicyConfigCacheKey, hasPolicyConfigColumn, loadPolicyConfigByContractId, savePolicyConfigByContractId, getPolicyConfigDefaults, mergePolicyConfigWithDefaults, getEffectivePolicyConfigByContractId, ensureWarehouseSubject, getNoticeService, sendPrintQuantityAdjustNotice, resolveRelationId, normalizeDate, normalizeSignAction, normalizeTempCode, getTempCodeCacheKey, createTempCode, pickRemaskField, resolveRemaskValue, buildCurrentRemaskPatch, requireCurrentRemaskPatch, saveTempSignPayload, getTempSignPayload, clearTempSignPayload, buildTempSignView, getCurrentSubject, getCounterparty, buildListWhereByStoreId, buildListWhere, getRelationIncludes, getQimenContractCacheKey, clearQimenContractCache, getApiInterfaceType, getQimenInterfaceType, resolveQimenCustomerIdByAppKey, getQimenErpNameMapByAppKeys, serializeQimenConfig, getQimenConfigMap, getSingleQimenConfig, resolvePairIds, serializeRelation, findScopedRelation, listForStore, listForWarehouse, list, sign, trimContract, confirmSign, rename, adjustPrintQuantity, queryPrintQuantityLogs, exportPrintQuantityLogs, getPolicyConfigFields, getPolicyConfig, savePolicyConfig, listApiConfig, saveApiConfig, deleteQimenConfig, unbind, getContractConfigCacheKey, invalidateContractConfigCache, getContractConfig, openAccount, createUser - app/service/systems/store.js (22) - normalizeSubjectConfigInput, validateStoreData, checkCompanyNameExists, findByAccountId, findAllEnabled, findAllWarehouses, getStoreName, getStoreRemaskName, createStore, createWarehouse, joinStore, joinWarehouse, ensureEmployeeRoleBinding, assignAdminRoleToCreator, generateJoinToken, sendNotification, sendNotificationToAdmins, getStoreRoles, auditApply, loadStores, loadWarehouses, bindCode -- app/service/systems/upload.js (17) - - getTencentCloudConfig, getCosConfig, initCOS, getUploadParams, hash_hmac, generatePolicyAndSignature, validateFileInfo, generateFileName, parseSizeToBytes, formatFileSize, getFrontendConfig, uploadFile, validateFile, uploadSuccessNotify, getMimeType, createFileReference, handleUploadCallback +- app/service/systems/upload.js (18) + - getTencentCloudConfig, getCosConfig, initCOS, getUploadParams, hash_hmac, generatePolicyAndSignature, resolveUploadMaxSizeBytes, validateFileInfo, generateFileName, parseSizeToBytes, formatFileSize, getFrontendConfig, uploadFile, validateFile, uploadSuccessNotify, getMimeType, createFileReference, handleUploadCallback - app/service/systems/warehouseNotify.js (7) - truncateLogBody, getCallbackConfig, MD5, buildSignature, writeLog, push, pushSystemMessage - app/service/systems/wave_batch_closure.js (1) - closeFinishedWaves - app/service/systems/waybill.js (5) - toOrder, list, detail, export, buildWaybillExportFile -- app/service/systems/workbench.js (19) - - list, detail, create, update, delete, bindCamera, business, _countWaveOrders, _getWaveOrderIds, Set, _buildPackChangeSummary, _writePackOperationLog, _packOrder, resolvePackTaskEndTime, _finishPack, _sendWeight, _writeWeighOpLog, _queryOrder, checkBarcodeExists +- app/service/systems/workbench.js (20) + - list, detail, create, update, delete, bindCamera, business, _countWaveOrders, _getWaveOrderIds, Set, _buildPackChangeSummary, _writePackOperationLog, _updateOrderPackStatus, _packOrder, resolvePackTaskEndTime, _finishPack, _sendWeight, _writeWeighOpLog, _queryOrder, checkBarcodeExists - app/service/warehouse.js (7) - resolveWarehouseMethod, getWarehouseMethodService, dispatchWarehouseMethod, validateWarehouseParams, parseJsonBody, normalizeSignFields, processRequest - app/service/warehouseMethods/inbox.js (2) From 41bede5391dffe54bdee8f550846640f6e9a8f17 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sun, 30 Aug 2026 07:28:43 +0800 Subject: [PATCH 303/550] =?UTF-8?q?docs(methods):=20=E5=90=8C=E6=AD=A5=20s?= =?UTF-8?q?ystem=20=E6=8E=A5=E5=8F=A3=E6=96=87=E6=A1=A3=E8=87=B3=200.3.58?= =?UTF-8?q?=20=E5=B9=B6=E8=BF=BD=E5=8A=A0=2021=20=E6=9D=A1=E5=8F=98?= =?UTF-8?q?=E6=9B=B4=E8=AE=B0=E5=BD=95=EF=BC=88=E6=9C=80=E6=96=B0=202026.0?= =?UTF-8?q?8.30-report-delivery-plan-copy=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- methods/changes/system.json | 420 +++++++ methods/system.json | 2213 ++++++++++++++++++++++++++++++++++- 2 files changed, 2612 insertions(+), 21 deletions(-) diff --git a/methods/changes/system.json b/methods/changes/system.json index c984ee9..3e99e45 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,203 @@ [ + { + "version": "2026.08.30-report-delivery-plan-copy", + "date": "2026-08-30", + "type": "added", + "summary": "新增 report.deliveryPlan.copy 批量复制接口:传入源计划ID id 与目标货主ID数组 store_ids(非空正整数数组,自动去重,兼容 storeIds 驼峰),快速复制源计划到其他货主;目标货主已存在同 report_definition_id 计划时跳过不覆盖;notify_group_ids/notify_member_ids 通知配置不复制(新计划置空);enabled 原样复制(保持复制语义),其余字段(report_definition_id/schedule_times/channel/late_grace_minutes/name/remark/notify_template)原样复制;事务批量创建,唯一键冲突单条降级 skipped。", + "methods": [ + "report.deliveryPlan.copy" + ], + "notes": [ + "app/service/systemMethods/report/deliveryPlan.js copy:解构 id/store_ids(兼容 storeIds 驼峰,优先取驼峰形式,与 save 的 reportId 兼容口径一致),透传 systems.reportDelivery.copyPlan({ id, storeIds }),统一 success 包装 data={ created, skipped };systemInit 未声明免权限(_noNeedLogin/_noNeedRight/_noNeedAuth 均为空),与 save/list 同权限口径(需登录需鉴权,仅通配符角色或已授权角色可用)", + "app/service/systems/reportDelivery.js copyPlan:id 必须为正整数(否则抛「计划ID无效」),findByPk 软删排除、不存在抛「计划不存在」;store_ids 经 parseJsonArray 解析为非空数组且元素为正整数并自动去重(空/非数组抛「目标货主 store_ids 必须为非空数组」,非法元素抛「目标货主 store_ids 含非法货主ID(需正整数): 」);与源计划 store_id 相同的目标计入 skipped(与源计划货主相同);wms_store 校验存在且 status=1(否则 skipped:货主不存在或状态异常);目标已存在同 report_definition_id 计划(软删排除)跳过(已存在同报表定义计划);新建 payload 中 notify_group_ids/notify_member_ids 置 null(通知配置不复制)、enabled 原样复制,其余字段原样复制;事务批量创建,并发撞 uk_store_report_definition 唯一索引时单条降级 skipped、不中断其余创建", + "methods/system.json 通用报表模块(module=report):新增 report.deliveryPlan.copy 条目(description/headers/params id+store_ids+storeIds/response created+skipped(reason 枚举 与源计划货主相同/货主不存在或状态异常/已存在同报表定义计划)/errors);isNeedAuth=true、isNeedLogin=true;版本 0.3.57 -> 0.3.58(docMeta.version),updatedAt 保持 2026-08-30", + "AI_METHOD_ROUTING.md 5.1 节路由表新增 report.deliveryPlan.copy 行(service 路径 app/service/systemMethods/report/deliveryPlan.js、函数 copy、需登录、需授权),并新增批量复制特性说明;变更记录列表顶部追加本版本", + "权限口径不变:report.deliveryPlan.copy 与 save/list 相同(isNeedAuth=true、isNeedLogin=true),未执行权限变更、未扩大任何角色授权", + "本次仅文档同步,业务代码由 wms-dev-agent 完成,未修改 app/ 下任何代码,未执行数据库/Redis 操作,未运行测试" + ], + "module": "report" + }, + { + "version": "2026.08.30-inbox-group-members-groupids-array", + "date": "2026-08-30", + "type": "changed", + "summary": "inbox.group.members 入参由单个 groupId 改为数组 groupIds(必填,非空且每个元素为正整数,对应 wms_inbox_group.id),一次查询多个群的成员并在消息层多群聚合去重(多群共享同一 500 条聚合池);破坏性入参变更(移除 groupId),调用方需同步升级。", + "methods": [ + "inbox.group.members" + ], + "notes": [ + "app/service/systemMethods/inbox.js groupMembers:解构 groupIds 透传给 systems 层;warehouseId 仍从 ctx.user?.store_id 服务端注入(Number 化),不信任前端传值;keyword/limit 透传不变", + "app/service/systems/inbox/group.js members:groupIds 校验为非空数组且每个元素为数字或可解析数字字符串的正整数(否则抛「groupIds 无效」);InboxGroup.findAll({ where: { id: { [Op.in]: groupIds }, warehouse_id } }) 批量校验群存在(软删自动排除),无匹配抛「群不存在或无权限操作」;聚合所有群外部 group_id(去重、剔空),全为空返回 { list: [] };消息按 group_id IN + warehouse_id 拉取(id 倒序、limit 500 共享聚合池、user_id 排除 NULL/空串、软删排除);按 user_id 去重取最新 user_name;keyword 对聚合结果做 user_name/user_id 小写包含过滤;截断到 limit(默认20上限100)", + "methods/system.json 站内信分组(module=inbox):inbox.group.members 描述改为多群聚合语义;params 删除 groupId、新增 groupIds(array,必填,非空数组,元素为正整数,对应 wms_inbox_group.id);errors 400 由「群ID无效 / warehouseId 无效」改为「groupIds 无效 / warehouseId 无效」;headers/响应结构/权限口径不变(warehouseId 仍服务端注入、567 权限);版本 0.3.56 -> 0.3.57(docMeta.version),updatedAt 保持 2026-08-30", + "AI_METHOD_ROUTING.md 5.2 节:members 底层实现描述由「groupId 必填」改为「groupIds 必填(数组,多群聚合)」;变更记录列表新增本版本", + "权限不变:仍需 567(inbox.group.members,isNeedAuth=true、isNeedLogin=true),未执行权限变更", + "本次仅文档同步,业务代码由 wms-dev-agent 完成,未修改 app/ 下任何代码,未执行数据库/Redis 操作,未运行测试" + ], + "module": "inbox" + }, + { + "version": "2026.08.30-inbox-group-quicklist-dual-dim-filter", + "date": "2026-08-30", + "type": "changed", + "summary": "inbox.group.quickList 改为双维度可选过滤:store_id(货主维度,对应 wms_inbox_group.store_id 列)与 warehouse_id(仓库维度,对应 wms_inbox_group.warehouse_id 列)均可选,可单独传、可同时传(AND),也可都不传(返回所有仓库/货主的群);本记录修正并取代 2026.08.30-inbox-group-quicklist-store-id(该版将 store_id 错误映射为 warehouse_id 列);新增 store_id 列索引迁移(待发布时执行)。", + "methods": [ + "inbox.group.quickList" + ], + "notes": [ + "取代关系:本记录修正并取代 2026.08.30-inbox-group-quicklist-store-id 的口径——上一版将入参 store_id 错误映射为 wms_inbox_group.warehouse_id(仓库维度),本版明确 store_id=货主维度(对应 store_id 列)、warehouse_id=仓库维度(对应 warehouse_id 列),两维度均可选可组合,均不传时返回所有仓库/货主的群", + "app/service/systemMethods/inbox.js groupQuickList:解构透传 data.store_id(storeId)与 data.warehouse_id(warehouseId)给 systems 层,不再从 ctx.user 注入任何仓库值;其余入参 keyword/groupType/limit 不变", + "app/service/systems/inbox/group.js quickList:双列可选过滤——store_id(货主维度,String 化 trim 非空时 Number 化并校验 Number.isInteger 且 >0,否则抛「store_id 无效」)设置 where.store_id;warehouse_id(仓库维度,同样校验否则抛「warehouse_id 无效」)设置 where.warehouse_id;两者可同时传(AND)也可都不传(不加对应过滤条件);keyword 模糊匹配 group_name/group_id、groupType 筛选、limit 默认20上限100、created_at 倒序、软删自动排除均不变", + "database/migrations/20260830150000-add-store-id-index-to-wms-inbox-group.js:为 wms_inbox_group.store_id 新增索引 idx_store_id(幂等 up/down,尚未执行,待发布时执行);warehouse_id 维度已由 uk_warehouse_group_id(warehouse_id, group_id) 前导列覆盖,双条件 AND 由两索引组合命中", + "methods/system.json 站内信分组(module=inbox):inbox.group.quickList 描述改为双维度可选过滤口径;params 修正 store_id(货主维度,对应 store_id 列)并新增 warehouse_id(可选正整数,对应 warehouse_id 列);errors 400 由「store_id 无效」改为「store_id 无效 / warehouse_id 无效」;headers 保持登录凭证口径(不从中解析仓库上下文);版本 0.3.55 -> 0.3.56(docMeta.version),updatedAt 保持 2026-08-30", + "AI_METHOD_ROUTING.md 5.2 节:quickList 底层实现与仓库口径改为双维度口径(store_id=货主维度 / warehouse_id=仓库维度,均可选可组合、不传返回全部、不再从登录上下文注入),变更记录列表新增本版本并标注修正/取代上一版", + "权限不变:仍需 566(inbox.group.quickList,isNeedAuth=true、isNeedLogin=true),未执行权限变更", + "本次仅文档同步,业务代码由 wms-dev-agent 完成,未修改 app/ 下任何代码,未执行数据库/Redis 操作,未运行测试" + ], + "module": "inbox" + }, + { + "version": "2026.08.30-inbox-group-quicklist-store-id", + "date": "2026-08-30", + "type": "changed", + "summary": "inbox.group.quickList 新增可选入参 store_id(对应 wms_inbox_group.warehouse_id):传入时仅返回该仓库的群,不传或为空时返回所有仓库的群;旧口径「warehouseId 由服务端从登录上下文自动注入、不信任前端传值」作废,改为透传前端入参 store_id。", + "methods": [ + "inbox.group.quickList" + ], + "notes": [ + "app/service/systemMethods/inbox.js groupQuickList:不再从 ctx.user.store_id 自动注入 warehouseId,改为解构透传 data.store_id(storeId)给 systems 层;其余入参 keyword/groupType/limit 不变", + "app/service/systems/inbox/group.js quickList:storeId 可选(String(data.storeId ?? '').trim() 非空时 Number 化并校验 Number.isInteger 且 >0,否则抛「store_id 无效」);传入时 where.warehouse_id = storeId 过滤,不传或为空时不加 warehouse_id 过滤、返回所有仓库的群;keyword 模糊匹配 group_name/group_id、groupType 筛选、limit 默认20上限100、created_at 倒序、软删自动排除均不变", + "methods/system.json 站内信分组(module=inbox):inbox.group.quickList 描述删除「warehouseId 由服务端从登录上下文自动注入」,补 store_id 口径(可选正整数,对应 warehouse_id,不传返回全部);params 新增 store_id(number|string,可选);errors 400 由「warehouseId 无效」改为「store_id 无效」;headers 描述改为登录凭证口径(不再从中解析 warehouseId 仓库上下文);版本 0.3.54 -> 0.3.55(docMeta.version),updatedAt 保持 2026-08-30", + "AI_METHOD_ROUTING.md 5.2 节:quickList 底层实现补 store_id 口径;仓库口径拆分为「quickList 透传前端 store_id(不再服务端注入)/ members 仍从 ctx.user.store_id 服务端注入」", + "权限不变:仍需 566(inbox.group.quickList,isNeedAuth=true、isNeedLogin=true),未执行权限变更", + "本次仅文档同步,业务代码由 wms-dev-agent 完成,未修改 app/ 下任何代码,未执行数据库/Redis 操作,未运行测试" + ], + "module": "inbox" + }, + { + "version": "2026.08.30-report-delivery-plan-name-field", + "date": "2026-08-30", + "type": "enhanced", + "summary": "投递计划新增计划名称 name 字段:report.deliveryPlan.save 新增可选入参 name(string|null;未传不覆盖,null/空串/全空白归一化为 null 显式清空,非空 trim 后 ≤100 超长报错),save 成功响应与 report.deliveryPlan.list 列表项新增 name 字段(缺省空串);name 仅展示字段,不参与幂等/关联逻辑。", + "methods": [ + "report.deliveryPlan.save", + "report.deliveryPlan.list" + ], + "notes": [ + "app/service/systems/reportDelivery.js:新增 normalizePlanName(value)(undefined=未传不覆盖返回 undefined;null/空串/全空白返回 null 显式清空;非空 trim 且 ≤PLAN_NAME_MAX_LENGTH(100),超长抛「计划名称 name 长度不能超过 100 字符」);savePlan 仅在 name !== undefined 时规范化并写入 payload.name,更新时不误清空", + "app/service/systems/reportDelivery.js planToView:响应视图新增 name: String(plan.name || '')(缺省空串),save 成功响应与 list 列表项均带该字段", + "app/service/systemMethods/report/deliveryPlan.js save:解构透传 name(仅入参存在时附加 saveArgs.name,保持旧调用形状与既有回归断言一致)", + "wms_report_delivery_plan 新增 name 列(STRING(100) allowNull,comment「计划名称(前端展示用,缺省时可用报表名称兜底)」;迁移 20260830130000-add-name-to-wms-report-delivery-plan 已完成);name 仅展示字段,不参与 store_id+report_definition_id 幂等/关联逻辑", + "methods/system.json 通用报表模块:report.deliveryPlan.save params 新增 name(string|null)、response 新增 name(缺省 '')、errors 新增「计划名称 name 长度不能超过 100 字符」;report.deliveryPlan.list response children 新增 name;版本 0.3.53 -> 0.3.54(docMeta.version),updatedAt 保持 2026-08-30", + "docs/report-config-guide.md 第 5 节投递计划补 name 字段口径与保存示例;AI_METHOD_ROUTING.md 5.1 节补 name 变更条目与最新 changes 版本", + "权限口径不变:report.deliveryPlan.save/list 仍 isNeedAuth=true(未声明免权限),仅执行 npm run permission:sync:system-api -- --dry-run 预演(不 apply、不扩任何角色授权)", + "本次仅文档同步,未修改 app/ 下业务代码,未执行数据库/Redis 操作,未运行测试" + ], + "module": "report" + }, + { + "version": "2026.08.30-report-type-list-merge-into-definition", + "date": "2026-08-30", + "type": "changed", + "summary": "枚举接口并入 definition:report.type.list → report.definition.typeList。免权限只读的类型注册清单查询由独立模块 report/type.js 并入 report/definition.js(typeList 方法,systemInit 声明 _noNeedRight/_noNeedAuth/_noNeedLog='typeList',仅要求登录);同模块 save/list/delete 仍需授权。", + "methods": [ + "report.definition.typeList", + "report.type.list" + ], + "notes": [ + "app/service/systemMethods/report/type.js 已删除;app/service/systemMethods/report/definition.js 新增 typeList(data) 方法(无必填入参,忽略请求体),返回 success('ok', { list }),list 由 systems/report.js listRegisteredTypes() 提供(QUERIES.describe() 注册表全量描述,当前仅 stockFlow)", + "权限口径:definition.js systemInit 声明 _noNeedRight/_noNeedAuth/_noNeedLog='typeList'(免权限/免鉴权/免审计日志,仅要求登录);同模块 save/list/delete 未声明免权限,仍需授权(isNeedAuth=true),同一模块内权限口径差异已在 method description 中注明", + "methods/system.json 通用报表模块:删除 report.type.list,新增 report.definition.typeList(isNeedAuth=false、isNeedLogin=true、无入参;响应 { list: [{key,title,description,window:{dayCount,cutoverHour},fields:[{key,label,type,computed?,asText?,children?}]}] },字段口径与原 report.type.list 一致);版本 0.3.52 -> 0.3.53(docMeta.version),updatedAt 保持 2026-08-30", + "docs/report-config-guide.md:report.type.list 全部替换为 report.definition.typeList(第 2/7 节标题、字段口径说明、请求/响应示例与设计器接口链),实现链由 report/type.js 改为 report/definition.js;AI_METHOD_ROUTING.md report 能力清单更新(report.definition.typeList → definition.js typeList)", + "权限仅执行 npm run permission:sync:system-api -- --dry-run 预演(不 apply、不扩任何角色授权)", + "本次仅文档同步(含文档脚本 update-api-doc.cjs 的 deleteMethods 能力扩展与缩进检测修正),未修改 app/ 下业务代码,未执行数据库/Redis 操作,未运行测试" + ], + "module": "report" + }, + { + "version": "2026.08.30-report-definition-model-refactor", + "date": "2026-08-30", + "type": "changed", + "summary": "报表定义模型重构:code→id 关联、type/fields 极简配置、注册表 stockFlow、新增 report.type.list。破坏性变更:report.generate/report.meta/report.deliveryPlan.* 的 report_code 入参全部替换为 report_id(=报表定义ID,兼容 reportId 驼峰),前端需同步改 report_id。", + "methods": [ + "report.generate", + "report.meta", + "report.type.list", + "report.definition.save", + "report.definition.list", + "report.definition.delete", + "report.deliveryPlan.save", + "report.deliveryPlan.list", + "report.deliveryLog.list" + ], + "notes": [ + "模型重构(app/model/report_definition.js):移除 code/scope/description 与 output_config/source_config/sheet_config 三段 JSON 配置列,改为 name/type/file_name/fields/is_enabled/remark + 主键 id(唯一性由 id 承担,删除 uk_code);投递计划/记录表外键由 report_code 改为 report_definition_id,投递记录新增 report_name 名称快照", + "app/service/systemMethods/report.js:generate/meta 入参 report_code 改为 report_id(reportId 驼峰优先);meta 响应由 report_code/name/scope/query/window/fields 改为 report_id/name/type/file_name/window/fields(fields 新增 selected 勾选标记与 asText 标记);generateTaskProgress 不变", + "新增 app/service/systemMethods/report/type.js:report.type.list 免权限只读(systemInit 声明 _noNeedRight/_noNeedAuth/_noNeedLog 含 list,仅要求登录),返回注册类型清单 [{key,title,description,window:{dayCount,cutoverHour},fields:[{key,label,type,computed,asText,children}]}];当前仅注册 stockFlow(标题「库存变化以及补货报表」)", + "app/service/systemMethods/report/definition.js:save 入参 {id?,name,type,file_name/fileName,fields,is_enabled,remark}(type 必须命中注册表、fields 必须为该类型注册字段子集,非法 key 报可读错误并列出可用字段;新增必填 type/file_name/fields);list where 改 name/type/is_enabled,sort 白名单 id/name/type/is_enabled/created_at/updated_at;delete 入参 id,引用拦截按 report_definition_id 统计启用中计划", + "app/service/systems/report.js:新增 listRegisteredTypes/resolveTypeEntry/validateTypeFields,saveDefinition/listDefinitions/deleteDefinition 按 id 重写;渲染由 app/lib/report/render.js renderSheetByType 按类型硬编码字段规格完成(asText 由类型字段规格硬编码自动应用,string 字段 asText=true 时落地文本单元格),sheet_config 已删除", + "app/service/systems/reportDelivery.js:savePlan/listPlans/listLogs 关联键由 report_code 改为 report_definition_id,listLogs 响应新增 report_name 快照;幂等键与唯一索引 uk_store_report_definition 同步改为 report_definition_id", + "methods/system.json 通用报表模块:report.generate/report.meta/report.definition.save/report.definition.list/report.definition.delete/report.deliveryPlan.save/report.deliveryPlan.list/report.deliveryLog.list 8 个 method 按新形态重写,新增 report.type.list(report.generateTaskProgress 不受影响保持原样);版本 0.3.51 -> 0.3.52(docMeta.version),updatedAt 保持 2026-08-30", + "docs/report-config-guide.md 整体改写(注册类型 stockFlow 标题/描述/16 字段表、report.type.list 用法、definition 保存示例 fileName+type+fields、plan 用 report_id、删除 sheet_config/asText 旧说明并按新渲染规则改写);AI_METHOD_ROUTING.md report 能力清单刷新", + "权限口径:report.type.list 免权限(isNeedAuth=false);其余 report.* 沿用既有授权口径(管理类接口 isNeedAuth=true);仅执行 npm run permission:sync:system-api -- --dry-run 预演,未 apply、未扩任何角色授权", + "本次仅文档同步,未修改 app/ 下任何代码,未执行数据库/Redis 操作,未运行测试" + ], + "module": "report" + }, + { + "version": "2026.08.30-order-export-create-channel-column", + "date": "2026-08-30", + "type": "enhanced", + "summary": "订单导出(order.export)waybill/item 两种导出模式在「平台」列之后新增导出列「来源」(字段 create_channel,中文取值:手工单/接口/奇门/出库转单);该列已自动纳入导出表头白名单 ORDER_EXPORT_ALL_COLUMN_HEADERS(waybill/item 两模式列头并集),export_columns/exportColumns 入参已支持传「来源」,不传或空数组时默认输出全部列。", + "methods": [ + "order.export" + ], + "notes": [ + "app/service/systems/order_export.js:ORDER_EXPORT_COLUMNS(waybill 模式)与 ORDER_EXPORT_ITEM_COLUMNS(item 模式)均在「平台」(sys_platform_name)之后新增 { header: '来源', key: 'create_channel', width: 12 }", + "ORDER_EXPORT_ALL_COLUMN_HEADERS 为 waybill/item 两模式列头并集(Object.freeze(new Set(...))),「来源」在列配置登记后自动可用:export_columns/exportColumns 传「来源」合法(校验不区分导出模式),不传或空数组时输出全部列(含来源)", + "取值翻译:app/service/systemMethods/order/base.js CREATE_CHANNEL_LABELS = { MANUAL: '手工单', API: '接口', QM: '奇门', STOCKOUT: '出库转单' },formatCreateChannelLabel 未命中映射时原样返回 create_channel 原文", + "methods/system.json:order.export 的 export_columns/exportColumns 参数描述中枚举由 51 个更新为 52 个(在「平台」之后插入「来源」),并补充来源列取值、位置(平台列之后)与两种模式均输出的说明;order.exportTaskProgress 无导出列枚举内容,无需改动", + "methods/system.json 版本 0.3.50 -> 0.3.51(docMeta.version),updatedAt 2026-08-29 -> 2026-08-30", + "本次仅文档同步,业务代码由 wms-dev-agent 完成,未修改 app/ 下任何代码,未执行数据库/Redis 操作,未运行测试" + ], + "module": "order.index" + }, + { + "version": "2026.08.29-waybill-warehouse-waybillCode-array-exact-match", + "date": "2026-08-29", + "type": "enhanced", + "summary": "运单列表与导出接口的 where.waybillCode 支持字符串数组精确匹配:waybill.warehouse.list / waybill.warehouse.export 的 where.waybillCode 由「仅字符串模糊搜索」扩展为「字符串模糊搜索(LIKE '%值%',向后兼容)/ 字符串数组精确匹配(Op.in,元素自动 trim 并过滤空值,空数组或全空值不加该筛选条件)」,修复此前数组入参被逗号拼接后做 LIKE 导致搜索无结果的问题。", + "methods": [ + "waybill.warehouse.list", + "waybill.warehouse.export" + ], + "notes": [ + "app/service/systems/waybill.js list() 第 226-235 行:where.waybillCode 为数组时先逐元素 String 化并 trim、过滤空值,非空则 waybill_code = { [Op.in]: waybillCodeList } 精确匹配;字符串时保持 waybill_code = { [Op.like]: '%trim%', } 模糊匹配(向后兼容)", + "export 的筛选条件构建(第 767-776 行)与 list 逻辑一致:数组 Op.in 精确匹配、字符串 Op.like 模糊匹配", + "修复前行为:数组入参会被逗号拼接后进入 LIKE 分支,导致搜索无结果;修复后数组元素 trim 并过滤空值,空数组/全空值不加 waybill_code 筛选条件", + "methods/system.json:waybill.warehouse.list 与 waybill.warehouse.export 的 where.waybillCode 参数 type 由 string 更新为 string|string[],description 补充字符串模糊搜索与字符串数组精确匹配(元素 trim、过滤空值)规则", + "methods/system.json 版本 0.3.49 -> 0.3.50(docMeta.version),updatedAt 保持 2026-08-29", + "本次仅文档同步,业务代码已由开发侧修复(app/service/systems/waybill.js),未修改 app/ 下任何代码,未执行数据库/Redis 操作" + ], + "module": "waybill.warehouse" + }, + { + "version": "2026.08.29-order-packing-quickWhere-short-kw-guard", + "date": "2026-08-29", + "type": "enhanced", + "summary": "order.packing.list 的 where.quickWhere 运单号降级模糊新增关键词长度校验:精确未命中后仅当 trim 后关键词长度 ≥ 4(QUICK_WHERE_WAYBILL_FUZZY_MIN_LENGTH)才降级 LIKE '%kw%' 模糊查询;长度 < 4 的短词(含单字符)禁止降级、运单号解析直接返回空结果(避免 %短词% 误命中海量历史单号);波次号模糊逻辑不变。", + "methods": [ + "order.packing.list" + ], + "notes": [ + "app/service/systems/order_packing.js 第 12 行模块常量 QUICK_WHERE_WAYBILL_FUZZY_MIN_LENGTH = 4:注释说明短于该长度的输入(如单字符 \"7\")没有模糊搜索意义且 %短词% 极易误命中海量历史单号(实测 \"7\" 可命中 24149 行),因此禁止短词降级进入 %kw% 模糊分支", + "list() 的 where.quickWhere 分支:波次号直接 LIKE '%kw%' 模糊不变;运单号先按「完整单号等值 + 剥离分段后缀主体等值 + 主体前缀 LIKE '主体-%'」精确集合查询 wms_order_express,第 206 行条件 expressRecords.length === 0 && kw.length >= QUICK_WHERE_WAYBILL_FUZZY_MIN_LENGTH 才降级 waybill_code LIKE '%kw%';短词(长度 < 4)不进入模糊分支,运单号解析保持空结果(仅保留波次号模糊条件)", + "list() JSDoc 第 64 行 where.quickWhere 描述已同步:精确未命中且关键词长度≥4 时才降级模糊,短词禁止降级避免误命中", + "methods/system.json:order.packing.list 的 where.quickWhere 参数描述补充「精确未命中且关键词长度 ≥ 4 才降级 %kw% 模糊;长度 < 4 短词不降级、直接返回空;波次号模糊不变」规则", + "methods/system.json 版本 0.3.48 -> 0.3.49(docMeta.version),updatedAt 保持 2026-08-29", + "本次仅文档同步,业务代码由 wms-dev-agent 完成,未修改 app/ 下任何代码,未执行数据库/Redis 操作" + ], + "module": "order.packing" + }, { "version": "2026.08.29-wave-batchCancel-pick-status-guard", "date": "2026-08-29", @@ -18,6 +217,26 @@ ], "module": "order.wave" }, + { + "version": "2026.08.29-order-packing-waybill-code-match", + "date": "2026-08-29", + "type": "enhanced", + "summary": "打包获取订单与订单快捷搜索的运单号匹配规则收敛:order.packing.list 的 where.waybill_code 由默认「%值%」模糊匹配改为「完整单号等值 + 剥离 -1-1- 分段后缀后主体单号等值 + 主体前缀 LIKE '主体-%'」精确匹配(不再支持部分单号模糊,无匹配返回空);quickWhere 运单号解析先按上述等值集合精确匹配、精确未命中才降级为 %kw% 模糊查询,波次号模糊逻辑不变;order.deliveryOrder.quickSearch 运单号条件同步扩展为「完整等值 + 主体等值 + 主体前缀 LIKE」,运单号不再落入模糊分支,发货单号/原始平台订单号模糊匹配不变(平台交易单号 pay_no 仅回显不参与匹配,修正文档过期描述)。", + "methods": [ + "order.packing.list", + "order.deliveryOrder.quickSearch" + ], + "notes": [ + "新增公共工具 app/lib/waybill_code.js:stripWaybillSegmentSuffix 剥离运单号尾部一单多件包裹序号分段(正则 /(?:-\\d+){2,}-?$/,如 JDX057941864338-1-1- → JDX057941864338,无分段原样返回);escapeLikeWildcards 转义 like 通配符 % _ \\,保证主体前缀匹配的主体部分被等值比较", + "app/service/systems/order_packing.js list():where.waybill_code 通过 wms_order_express 解析 order_id(wms_pack_task.waybill_code 通常为空),条件集合为 [waybill_code=完整单号, waybill_code=剥离后缀后主体, waybill_code LIKE '转义主体-%'] 的 OR 组合,命中后按 order_id IN 过滤,无命中强制空结果(queryWhere.id=-1);不再使用 like '%值%' 模糊匹配", + "order_packing.js list() 的 where.quickWhere:波次号直接 LIKE '%kw%' 模糊不变;运单号解析先按上述精确集合查询,expressRecords 为空才降级为 waybill_code LIKE '%kw%'(兼容输入部分单号场景);团购按 wave_no、散单按 order_id 查询链路不变", + "app/service/systemMethods/order/deliveryOrder.js quickSearch():express 表 OR 条件中运单号扩展为 [完整等值, 主体等值, 主体前缀 LIKE '主体-%'],运单号不再落入 %kw% 模糊分支;delivery_order_code / source_order_codes 仍为 LIKE '%kw%' 模糊匹配;pay_no 不在搜索条件中(仅第三步订单详情输出回显),原文档「平台交易单号 pay_no(模糊)」为过期描述已按实现修正", + "methods/system.json:order.packing.list 的 where.waybill_code 描述由「运单号(模糊匹配)」改为完整单号/剥离分段后缀主体/主体前缀三种匹配规则说明,quickWhere 描述补充「先精确后降级模糊」优先级;order.deliveryOrder.quickSearch 的 description 与 keyword 参数描述同步修正(express 表匹配口径、pay_no 仅回显);quickSearch 条目补充空 headers 数组以符合文档校验结构", + "methods/system.json 版本 0.3.46 -> 0.3.47(docMeta.version),updatedAt 保持 2026-08-29", + "本次仅文档同步,业务代码由 wms-dev-agent 完成,未修改 app/ 下任何代码,未执行数据库/Redis 操作" + ], + "module": "order.packing" + }, { "version": "2026.08.29-return-unpack-max-record-minutes", "date": "2026-08-29", @@ -39,6 +258,207 @@ ], "module": "returnUnpack" }, + { + "version": "2026.08.29-returnUnpack.export", + "date": "2026-08-29", + "type": "enhanced", + "summary": "新增退回拆包导出与进度查询接口:returnUnpack.export(提交异步导出任务,入参 where/sort 语义与 returnUnpack.list 一致,warehouse_id 由服务端注入 ctx.user.store_id;后台生成双 Sheet Excel:Sheet1 正常退回运单号列表、Sheet2 明细表并上传)与 returnUnpack.exportTaskProgress(按 task_id 查询任务进度与下载链接,未命中返回 status=not_found)。任务缓存 Redis TTL 30 分钟,状态口径 submitted→running→数据拉取(10~30)→明细拉取(30~50)→Excel(55~90)→上传(92)→success(100),失败 failed+error。两接口免权限免日志口径与 order.export 一致(isNeedAuth=false、isNeedLogin=true)。", + "methods": [ + "returnUnpack.export", + "returnUnpack.exportTaskProgress" + ], + "notes": [ + "app/service/systemMethods/returnUnpack.js 新增 export/exportTaskProgress 与任务缓存辅助方法(generateExportTaskId/normalizeExportTaskId/setExportTaskProgress/getExportTaskProgress):缓存键前缀 return_unpack_export_task_,Redis TTL 1800 秒(30 分钟);export 提交后 setImmediate 异步执行并逐阶段回写进度;exportTaskProgress 入参兼容 task_id/taskId,download_url 从 result.url/cdnUrl/cosUrl/fileKey 兜底取(代码中同时兼容 cndUrl 拼写);task_id 为空或缓存未命中返回 status=not_found(正常响应非报错)", + "systemInit 免权限声明:_noNeedRight/_noNeedAuth/_noNeedLog 均含 export,exportTaskProgress(异步任务模式,与 order.export 口径一致,无 wms_permission 记录);_noNeedLogin 不含(两接口均需登录,isNeedAuth=false、isNeedLogin=true)", + "app/service/systems/return_unpack.js 新增 exportUnpack:复用 _buildListWhere/_buildListOrder(与 list 语义一致)并强制 warehouse_id=注入值;主表全量分页拉取(每页 500,无行数上限),明细按 unpack_id 分批(每批 100)拉取;货主名批量映射 wms_store.company_name、快递类型映射 wms_order_express.logistics_name(各自独立 try/catch,解析失败降级为空字符串不阻断导出)", + "双 Sheet 结构:Sheet1「正常退回运单号列表」列=货主/快递号/商品类数/商品总数/记录人员/记录日期/开始时间/结束时间/是否原单(是/否)/快递类型/自定义店铺/平台单号;Sheet2「明细表」列=货主/快递号/商品名称/商品编码/条码/颜色/规格/数量/是否残次(是/否)/记录人员ID/记录日期/备注/是否原单(是/否)/快递类型/自定义店铺/平台单号;颜色取自明细 product_snapshot.sku_property 中「颜色:xxx」片段(兜底 spec 字段),无颜色信息为空;是否原单按 order_express_id 有值输出是/否;是否残次按 product_status=damaged 输出是/否", + "导出上传:ExcelJS 流式写入临时文件后经 systems.upload.uploadFile 上传(key=exports/return_unpack/{warehouseId}/{timestamp}_{token}.xlsx,mimetype xlsx,category=document),结果含 filename/url/fileKey/cdnUrl/cosUrl/current_count/total_count/total_details/sheet_count=2;Sheet1 不加 status 过滤(如需只导特定状态由调用方传 where.status)", + "methods/system.json 退回拆包模块(module=returnUnpack)新增 returnUnpack.export 与 returnUnpack.exportTaskProgress 两个 method 条目(追加于 returnUnpack.delete 之后),版本 0.3.44 -> 0.3.45(docMeta.version),updatedAt 保持 2026-08-29", + "权限说明:export/exportTaskProgress 免权限(无 wms_permission 记录),仅登录可用;本次仅文档、未扩任何角色授权,不执行权限同步 apply", + "仅文档变更,未改任何业务代码、表结构,未执行数据库/Redis 操作" + ], + "module": "returnUnpack" + }, + { + "version": "2026.08.29-report-channel-normalize-doc-audit", + "date": "2026-08-29", + "type": "docs", + "summary": "渠道默认值归一化 inbox + 文档一致性校对:全量核对「通用报表模块」全部 report.* method(generate/generateTaskProgress/meta/deliveryPlan.save/list/deliveryLog.list/definition.save/list/delete)与当前实现(app/service/systemMethods/report.js 及 report/ 子目录、app/service/systems/report.js、app/service/systems/reportDelivery.js、模型 report_definition/report_delivery_plan/report_delivery_log、迁移 20260829170000),仅发现 report.deliveryPlan.list / report.deliveryLog.list 响应 channel 字段存在过期描述(wecom/inbox/link),已修正为仅 inbox;其余 method 的 params/response/errors 均与实现一致,无接口行为变化。", + "methods": [ + "report.deliveryPlan.list", + "report.deliveryLog.list" + ], + "notes": [ + "迁移 database/migrations/20260829170000-normalize-report-channel-to-inbox.js:wms_report_delivery_plan / wms_report_delivery_log 的 channel 默认值 wecom → inbox、comment 收敛,存量 channel IN (wecom,link) 统一 UPDATE 为 inbox;模型同步(app/model/report_delivery_plan.js、app/model/report_delivery_log.js defaultValue: inbox)", + "代码核对:app/service/systems/reportDelivery.js 的 DELIVERY_CHANNELS 收敛为 [inbox]、DEFAULT_CHANNEL=inbox;deliverByChannel 对非 inbox 渠道记录 warn 日志后按 inbox 兜底投递(不抛错);inbox 推送失败(success=false 或 push_status=3)立即经 ctx.service.inbox.message.retry 重推一次,重推失败进入 failed 退避重试(MAX_RETRY=3,退避 retry_count × 60s)", + "修正点:report.deliveryPlan.list / report.deliveryLog.list 响应 channel 字段描述由「投递渠道:wecom/inbox/link」修正为「投递渠道:inbox(渠道已收敛,仅支持 inbox;历史数据已由迁移 20260829170000 归一化)」;仅文档描述修正,params/response 结构、错误码无任何变化", + "report.definition.save 的 19 条错误、report.definition.list 排序白名单 id/code/name/scope/is_enabled/created_at/updated_at、notify_template(≤500,标签白名单 {time}/{url}/{report_name}/{biz_date})/notify_group_ids(正整数去重 ≤20,校验存在性排除软删)/notify_member_ids(非空字符串去重 ≤100)参数与校验规则均与代码一致,未改动", + "report.generate/report.generateTaskProgress 免权限(_noNeedRight/_noNeedAuth 声明)、report.meta 免权限但保留审计日志(未列入 _noNeedLog)、report.deliveryPlan.*/report.deliveryLog.list/report.definition.* 需授权(isNeedAuth=true,未声明免权限)口径均与 systemInit 声明一致", + "methods/system.json 版本 0.3.43 -> 0.3.44(docMeta.version),updatedAt 保持 2026-08-29", + "配套文档核对:docs/report-config-guide.md 第 5 节渠道说明已与「仅 inbox + 兜底 + 重推」一致(补充迁移归一化说明);第 8 节 report.definition.save/list/delete 用法与实现一致;AI_METHOD_ROUTING.md 5.1 report 能力速查与路由说明已最新", + "权限:仅执行 npm run permission:sync:system-api -- --dry-run 预演缺口,未执行 apply、未扩任何角色授权", + "仅文档变更,未改任何业务代码、表结构,未执行数据库/Redis 操作" + ], + "module": "report" + }, + { + "version": "2026.08.29-report-definition-management", + "date": "2026-08-29", + "type": "enhanced", + "summary": "通用报表模块新增报表定义管理接口:report.definition.save/list/delete(wms_report_definition 管理侧 CRUD,均需登录且需鉴权 isNeedAuth=true,未扩任何角色授权)。save 按 code upsert(未传字段不覆盖),code 格式 ^[a-z][a-z0-9_]{1,63}$(长度 2-64)、name 必填 ≤100、scope 枚举 warehouse/store/open(默认 warehouse),output_config/source_config/sheet_config 三段 JSON 配置支持对象或 JSON 字符串,source_config.query 须为注册表已有查询器,sheet_config 列结构校验(static/expand/computed,expand pair 与查询器字段清单对齐),response 平铺 report_code;list 支持 where{code,name,scope,is_enabled}(code/name 模糊、scope/is_enabled 精确)/pagination/sort(白名单 id/code/name/scope/is_enabled/created_at/updated_at),response 全量字段含三段 JSON 配置;delete 按 code 软删(幂等),启用中的投递计划引用时拦截「存在 N 个启用的投递计划引用该报表,请先停用计划」。", + "methods": [ + "report.definition.save", + "report.definition.list", + "report.definition.delete" + ], + "notes": [ + "app/service/systemMethods/report/definition.js 新增:save/list/delete 仅做出口包装与参数解构(save 仅附加入参中存在的字段,undefined 不进入参数对象,保持「未传不覆盖」语义;list 经 prepareWhereContext 解析 where 后取 code/name/scope/is_enabled),业务逻辑下沉 app/service/systems/report.js saveDefinition/listDefinitions/deleteDefinition", + "saveDefinition:code 规范化 trim 后校验(空/格式非法分别报「报表编码 code 不能为空」「报表编码 code 格式非法:须以小写字母开头,仅含小写字母/数字/下划线,长度 2-64」,正则 ^[a-z][a-z0-9_]{1,63}$);name trim 必填 ≤100;scope 枚举校验;JSON 字段仅非 undefined 时经 parseRequiredJson 解析(对象原样返回/JSON 字符串解析/其余报「 解析失败:须为对象或合法 JSON 字符串」);source_config 的 query 必须为注册表已有查询器(resolveQueryKey 缺省 generic,未知报「未知的报表查询器: 」);sheet_config 经 validateDefinitionSheetConfig 校验列结构(columns 数组、列类型仅 static/expand/computed、static 列须有 field 或 value、computed 列须有 field 或 formatter、expand pair 须与查询器静态字段清单对齐否则报「sheet_config expand 列 pair 元素 '' 不在查询器 的字段清单中(可用: )」);is_enabled 仅 0/1;description/remark ≤500 截断", + "upsert 细节:uk_code 唯一索引含 deleted_at,findOne 以 paranoid:false 完整查重;命中软删记录先 restore 再 update(restore 撞唯一索引报「存在多个同名已删除记录,无法自动恢复,请更换报表编码」);并发首次创建撞 SequelizeUniqueConstraintError 降级为重查并更新(查不到报「报表编码已存在,保存冲突,请重试」);保存成功返回 definitionToView 视图(JSON 字段解析为对象)", + "listDefinitions:code/name LIKE 模糊(escapeLike 转义 \\%_)、scope 精确(非法报「scope 仅支持 warehouse/store/open,非法: 」)、is_enabled 空值不过滤(Number 化 0/1);pagination page≥1、pageSize 夹取 1-200;sort 白名单 id/code/name/scope/is_enabled/created_at/updated_at(sortField/sortOrder 兼容 sort_field/sort_order 别名,非法字段回退 id DESC);findAll+count 并行,raw 行映射 definitionToView", + "deleteDefinition:先按 report_code+enabled=1 统计 wms_report_delivery_plan 启用中引用(>0 报「存在 个启用的投递计划引用该报表,请先停用计划」),停用计划不阻断;再按 code paranoid:false 查定义(不存在报「报表定义不存在: 」,已软删幂等返回 deleted=1),否则 destroy 软删", + "method 层统一 catch 后 this.fail(error.message):错误响应 code=0、flag=failure(与 report.meta 惯例一致);save/delete 成功响应将定义 code 平铺为 report_code(避免覆盖统一响应 code=1)", + "systemInit 未声明 _noNeedLogin/_noNeedRight/_noNeedAuth 免权限 → 3 个接口均 isNeedAuth=true、isNeedLogin=true,仅通配符角色(超级管理员/仓库管理员)或后续 wms_permission 同步授权角色可用;本次仅文档、未扩任何角色授权,不执行权限同步 apply", + "methods/system.json 通用报表模块(module=report)新增 3 个 method 条目(追加于 report.meta 之后),版本 0.3.42 -> 0.3.43", + "配套文档:docs/report-config-guide.md 新增第 8 节「报表模板管理接口」;AI_METHOD_ROUTING.md 5.1 report 能力速查表登记 3 个新 method", + "仅文档变更,未改任何业务代码,未执行数据库/Redis 操作" + ], + "module": "report" + }, + { + "version": "2026.08.29-inbox-group-quick-list-members", + "date": "2026-08-29", + "type": "enhanced", + "summary": "新增站内信群选择下拉接口:inbox.group.quickList(群快速查询,keyword 模糊匹配群名称/外部群ID、groupType 筛选 store/warehouse/express、limit 默认20上限100,warehouseId 服务端注入,无分页,按创建时间倒序)与 inbox.group.members(群成员筛选,groupId 必填,按外部群ID在消息表聚合去重成员取每 user_id 最新 user_name,keyword 过滤后截断,外部群ID为空返回空列表);新增 API 权限 566(quickList)/567(members),授权角色 8/26/28/29,两接口均需登录且需鉴权。", + "methods": [ + "inbox.group.quickList", + "inbox.group.members" + ], + "notes": [ + "app/service/systems/inbox/group.js quickList:where 含 warehouse_id(服务端注入),keyword 对 group_name/group_id 双字段 LIKE 模糊匹配,limit 截断为 1-100(默认20),findAll 仅取 id/group_id/group_name/group_type/sub_type/is_blocked,按 created_at DESC,软删除由 paranoid 自动排除", + "app/service/systems/inbox/group.js members:先按 id+warehouse_id 查 wms_inbox_group(不存在抛「群不存在或无权限操作」,id 无效抛「群ID无效」);externalGroupId 为空直接返回 {list:[]};再按外部群ID+仓库查 wms_inbox_message(最近 500 条按 id DESC,user_id 非空),Map 按 user_id 去重取首次(最新)user_name,keyword 在聚合结果上过滤 user_name/user_id,最后 slice(0, limit)", + "app/service/systemMethods/inbox.js group.quickList/group.members 子入口:warehouseId 从 ctx.user.store_id 自动注入,不信任前端传值;inbox systemMethods 未声明 systemInit 免权限,两接口走标准 API 权限校验(isNeedAuth=true、isNeedLogin=true)", + "权限迁移 database/migrations/20260829180000-add-inbox-group-select-permissions.js:固定权限 ID 566(inbox.group.quickList,API:群快速查询)/567(inbox.group.members,API:群成员列表),type=api,授权角色 26(仓库组-主管)/28(客服组-主管)/29(生产组-主管)/8(经理);超级管理员(7)/仓库管理员(2) 持 * 通配符自动拥有;INSERT IGNORE 幂等,角色权限数组追加后去重排序", + "methods/system.json 站内信分组(module=inbox)新增 2 个 method 条目(追加于 inbox.group.messages 之后),版本 0.3.41 -> 0.3.42", + "AI_METHOD_ROUTING.md 新增 5.2 inbox.group(站内信群管理)能力速查小节,登记两接口的实现文件/函数/登录/鉴权信息", + "仅文档变更,未改任何代码,未执行数据库/Redis 操作" + ], + "module": "inbox" + }, + { + "version": "2026.08.29-report-delivery-channel-converge", + "date": "2026-08-29", + "type": "changed", + "summary": "报表投递渠道收敛:report.deliveryPlan.save 的 channel 收敛为仅支持 inbox(默认 inbox,移除 wecom/link,非法渠道报「投递渠道仅支持 inbox: 」);历史 wecom/link 计划投递时按 inbox 兜底执行(warn 日志不抛错);inbox 推送失败立即经 inbox.message.retry 重推一次(ext_id 幂等复用消息记录),重推仍失败进入 failed 退避重试(MAX_RETRY=3,退避 retry_count × 60s)。", + "methods": [ + "report.deliveryPlan.save" + ], + "notes": [ + "app/service/systems/reportDelivery.js:DELIVERY_CHANNELS 收敛为 ['inbox'],DEFAULT_CHANNEL='inbox';savePlan 对 channel 规范化(trim+lowercase,缺省默认 inbox)后不在白名单则抛「投递渠道仅支持 inbox: 」(原「投递渠道不合法(wecom/inbox/link)」文案已移除)", + "deliverByChannel:rawChannel !== 'inbox' 时记录 warn 日志「计划投递渠道 已弃用,按 inbox 兜底投递」后按 inbox 执行,不直接抛错(避免历史计划在 failed 退避循环中耗尽重试次数后永久卡死)", + "inbox 推送失败判定双保险:pushResult.success=false 或消息记录回写 push_status=3;失败时复用 ctx.service.inbox.message.retry 重推一次(重置 push_status=0 异步重推,ext_id 幂等复用同一条消息记录不重复写);retry 自身抛错则抛「站内信推送失败且重推失败: <原因>」,交由上层 failed 退避循环(MAX_RETRY=3,退避 = retry_count × 60s)", + "methods/system.json 通用报表模块:report.deliveryPlan.save 的 channel 参数枚举收敛为仅 inbox(默认 inbox)、响应 channel 字段说明同步收敛、errors 中渠道错误文案更新为「投递渠道仅支持 inbox: 」;版本 0.3.40 -> 0.3.41", + "配套文档:docs/report-config-guide.md 投递章节更新渠道说明(移除 wecom/link、历史渠道按 inbox 兜底、inbox 推送失败自动重推);AI_METHOD_ROUTING.md 同步补充渠道收敛说明与变更版本号", + "授权说明:本次仅文档、未扩任何角色授权。report.deliveryPlan.save/list、report.deliveryLog.list 仍为需授权接口(isNeedAuth=true),不涉及权限同步操作" + ], + "module": "report" + }, + { + "version": "2026.08.29-report-delivery-notify-template-targets", + "date": "2026-08-29", + "type": "enhanced", + "summary": "报表投递新增文本通知与定向群/成员:report.deliveryPlan.save 新增可选参数 notify_template(≤500 字符,标签白名单 {time}/{url}/{report_name}/{biz_date},未知标签报错列出非法标签)、notify_group_ids(wms_inbox_group.id 正整数去重 ≤20,保存时校验存在性且排除软删,缺失报错列出缺失 ID)、notify_member_ids(外部 IM 用户 ID 非空字符串去重 ≤100);report.deliveryPlan.list 响应带出上述 3 个配置字段;report.deliveryLog.list 响应新增 notify_targets 投递目标快照({group_ids, member_ids, notify_text})。", + "methods": [ + "report.deliveryPlan.save", + "report.deliveryPlan.list", + "report.deliveryLog.list" + ], + "notes": [ + "app/service/systems/reportDelivery.js savePlan:notify_template/notify_group_ids/notify_member_ids 三个可选参数仅在入参存在(!== undefined)时生效,未传不进入 payload(更新时保持既有字段不动,不传参数行为与旧版完全一致)", + "savePlan 校验:notify_template trim 后 ≤500 字符;notify_group_ids 正整数、去重升序、≤20,保存时 validateNotifyGroupExists 校验 wms_inbox_group 存在性(软删自动排除,不校验 is_blocked:被屏蔽群仍可选中,屏蔽属于发送时过滤维度);notify_member_ids 非空字符串、去重、≤100;两者支持数组或 JSON 字符串数组,非数组报「必须为数组」", + "标签白名单渲染:app/lib/report/notifyTemplate.js ALLOWED_TAGS={time,url,report_name,biz_date},validateNotifyTemplate 提取 {xxx} 标签并列出非法标签,renderNotifyTemplate 仅替换白名单标签;{url} 为空时替换为兜底文案「文件生成中,稍后可在投递记录中查看」,不阻断投递", + "发送链路:reportDelivery.deliverByChannel 投递完成后调用 sendNotifyIfConfigured(与渠道独立,link 渠道同样生效);未配置模板或未选任何群/成员返回 null(不发送);群多选按 wms_inbox_group 逐群推送(群维度协议字段单值),发送时过滤 is_blocked=1/软删/仓库维度不一致;成员 user_id 数组整体透传不循环拆发,选择群时随每个群推送携带,未选择群时单独一次仅成员推送;目标不可达或推送失败抛异常走失败退避重试", + "快照:sendNotifyIfConfigured 返回 {group_ids(实际发送的内部群ID), member_ids, notify_text},markDelivered 随 delivered 写入 wms_report_delivery_log.notify_targets;listLogs 以 readJsonObject 读取并输出(未配置时为 null)", + "app/service/systems/warehouseNotify.js pushSystemMessage 新增 userIds 参数(仅接受字符串数组,去重过滤空值),推送体 user_id 直接传数组(目标侧协议支持);向后兼容:不传 userIds 且传 group 时校验、幂等 ext_id、落库字段、推送体均与旧版一致;消息表 user_id 列不承载数组(避免超长截断),成员仅随推送体透传并记录在投递日志快照", + "method 层 app/service/systemMethods/report/deliveryPlan.js save:仅当 notify_template/notify_group_ids/notify_member_ids 在入参存在时附加到 saveArgs(undefined 不进入参数对象),保持旧调用形状与既有回归断言一致", + "授权说明:本次仅文档、未扩任何角色授权。report.deliveryPlan.save/list、report.deliveryLog.list 仍为需授权接口(isNeedAuth=true),不涉及权限同步操作", + "methods/system.json 通用报表模块更新 3 个 method 的 params/response/errors(版本 0.3.39 -> 0.3.40);配套文档 docs/report-config-guide.md 投递章节新增「文本通知模板与定向群/成员」小节" + ], + "module": "report" + }, + { + "version": "2026.08.29-report-meta", + "date": "2026-08-29", + "type": "enhanced", + "summary": "新增 report.meta(免权限只读列元数据接口,供前端报表设计器拉取可用字段):按报表编码返回 wms_report_definition 的 report_code/name/scope/query 与窗口参数 window{dayCount,cutoverHour},以及查询器静态字段清单 fields(查询器模块挂载的 querier.fields,未挂载返回空数组),不执行真实数据查询。", + "methods": [ + "report.meta" + ], + "notes": [ + "app/service/systemMethods/report.js meta:入参 report_code/reportCode 双写法(驼峰优先),为空返回 fail「报表编码 report_code 不能为空」(flag=failure、code=0、HTTP 200);调用 systems/report.getMeta 后组装 {report_code, name, scope, query, window, fields}(getMeta 的 code 字段回显为 report_code)", + "systemInit 声明:_noNeedRight/_noNeedAuth 含 meta(免权限 + 免仓库有效期鉴权,仅登录),_noNeedLogin 不含 meta(必须登录);_noNeedLog 未含 meta → meta 保留审计日志(generate/generateTaskProgress 不写审计日志,两者行为不同,已在接口文档与配置指南中如实标注)", + "app/service/systems/report.js getMeta:读 wms_report_definition(is_enabled=1,不存在/停用抛「报表定义不存在或已停用: 」,经 controller 兜底为 HTTP 500 接口错误);window 由 app/lib/report/day_window.resolveWindowConfig 解析(默认 dayCount=7、cutoverHour=7,[D 07:00, D+1 07:00) 半开区间,source_config 可覆盖);fields 由 resolveQuerierFields 读取查询器模块静态字段 querier.fields(未挂载返回空数组)", + "静态字段清单挂载方式:查询器模块以 FIELDS 常量挂载到导出函数(queries/sevenDayStockFlow.js 挂载 12 个顶层字段 stock_id/item_code/item_name/barcode/daily/ck_total/rk_total/available/total/pending/suggest/warn;daily 为数组类型含 ck/rk 子字段,suggest/warn 为 computed=true 格式化器预计算字段;queries/generic.js 未挂载,fields 返回空数组)", + "授权说明:本次仅文档、未扩任何角色授权。report.meta 免权限(isNeedAuth=false),不涉及权限同步操作", + "methods/system.json 通用报表模块分组新增 report.meta 登记(版本 0.3.38 -> 0.3.39);配套文档 docs/report-config-guide.md 新增 report.meta 小节,AI_METHOD_ROUTING.md 刷新 report.meta 条目" + ], + "module": "report" + }, + { + "version": "2026.08.29-report-config-driven-generate-delivery", + "date": "2026-08-29", + "type": "enhanced", + "summary": "新增配置驱动通用报表与货主定时投递接口:report.generate(提交报表导出异步任务,仅登录免权限)、report.generateTaskProgress(查询导出任务进度,仅登录免权限)、report.deliveryPlan.save/list(货主报表投递计划新增/更新与分页查询,需授权)、report.deliveryLog.list(投递记录审计分页查询,需授权)。", + "methods": [ + "report.generate", + "report.generateTaskProgress", + "report.deliveryPlan.save", + "report.deliveryPlan.list", + "report.deliveryLog.list" + ], + "notes": [ + "app/service/systemMethods/report.js:systemInit 声明 _noNeedRight/_noNeedAuth = generate,generateTaskProgress(免权限+免仓库有效期鉴权,仅登录);generate 的 warehouse_id 由服务端从登录上下文 ctx.user.store_id 自动注入,禁止前端传递;store_id 支持 store_id/storeId 双写法,<=0 视为不按货主过滤", + "app/service/systemMethods/report/deliveryPlan.js 与 report/deliveryLog.js:systemInit 未声明免权限(_noNeedRight/_noNeedAuth 均为空),为需授权管理类接口;methods/system.json 中 isNeedAuth=true 已登记", + "权限同步:本次仅写文档、未执行任何授权操作。report.deliveryPlan.save/list、report.deliveryLog.list 为需授权接口,后续请先执行 npm run permission:sync:system-api -- --dry-run 预演,再按标准流程授权;不扩大任何角色授权范围", + "实现依赖:app/service/systems/report.js(getDefinition/resolveQuerier/buildWorkbookSheets/generate/generateBuffer)、app/service/systems/reportDelivery.js(savePlan/listPlans/listLogs/dispatch 投递编排)、app/lib/report/*(render/day_window/formatters 纯函数模块)、内置查询器注册表 app/service/systems/report/queries/index.js(sevenDayStockFlow/generic)", + "报表配置驱动:wms_report_definition(app/model/report_definition.js)以 code/name/scope + output_config/source_config/sheet_config 三段 JSON 配置驱动,新报表优先加配置行、免发版;sheet_config 支持静态列/窗口展开列/计算列、headerRow1 的 {date} 模板、merges 绝对引用、style、rowFilter", + "methods/system.json 新增「通用报表模块」分组(module=report,groupName=通用报表模块),登记 5 个 method 的参数(source=body)、响应与错误码;版本 0.3.37 -> 0.3.38", + "配套文档:docs/report-config-guide.md 新增报表配置结构说明(三段 JSON 配置、列定义、{date} 模板、merges、style、rowFilter、查询器注册表与内置查询器口径假设);AI_METHOD_ROUTING.md 同步刷新 report 相关路由说明与服务清单" + ], + "module": "report" + }, + { + "version": "2026.08.28-workbench-queryOrder-intercept-pack-flag", + "date": "2026-08-28", + "type": "enhanced", + "summary": "workbench.business(queryOrder/query) 查询订单响应增强:order 对象新增 intercept_status 字段(拦截状态原始值,散单/团购均返回,与既有 pack_status 并列);散单(isSandan=1)时 order 额外返回 intercept_flag/pack_flag 两个 0/1 标志(拦截状态不等于 none 时 intercept_flag=1 否则 0,打包状态不等于 none 时 pack_flag=1 否则 0),团购不返回这两个标志;空值/null 统一归一化为 none。", + "methods": [ + "workbench.business" + ], + "notes": [ + "app/service/systems/workbench.js _queryOrder 步骤6:intercept_status/pack_status 空值/null 归一化为 none(String(v||'').trim() || 'none'),interceptFlag = 状态 !== none ? 1 : 0,packFlag 同理", + "_queryOrder 响应 order 对象新增 intercept_status(原始值,散单/团购均返回),与既有 pack_status 并列,原始状态字段原样保留、不破坏既有调用方", + "仅散单(isSandan===1)向 result.order 追加 intercept_flag/pack_flag;团购(isSandan===0)不追加这两个标志字段,pack_status/intercept_status 原始值仍原样返回", + "methods/system.json workbench.business 同步补充 queryOrder/query 响应结构:order.intercept_status 字段说明、散单场景 order.intercept_flag/order.pack_flag 字段说明与取值语义(状态不等于 none 返回 1,否则返回 0)" + ], + "module": "workbench" + }, + { + "version": "2026.08.28-storage-entry-quickInbound-is-virtual-inbound", + "date": "2026-08-28", + "type": "enhanced", + "summary": "storage.entry.quickInbound 事务内回写 is_virtual_inbound(是否虚拟入库):有绑定收货单 → 0(非虚拟入库),无绑定收货单 → 1(虚拟入库),与 order_status=COMPLETED 同一事务写入;wms_entry_order 新增 is_virtual_inbound 字段(TINYINT(1) NOT NULL DEFAULT 0)", + "methods": [ + "storage.entry.quickInbound" + ], + "notes": [ + "app/service/systems/storage/entry.js quickInbound:eo.update 事务内新增 is_virtual_inbound 回写,值为 receivingIds.length > 0 ? 0 : 1(有绑定收货单 → 非虚拟入库,无绑定收货单 → 虚拟入库),与 order_status=COMPLETED、sync_status=SUCCESS 同一事务提交", + "app/model/entry_order.js:wms_entry_order 新增 is_virtual_inbound 字段(TINYINT(1),allowNull:false,defaultValue:0,comment:是否虚拟入库:0=否 1=是)", + "database/migrations/20260828100000-add-is-virtual-inbound-to-wms-entry-order.js:新增迁移(describeTable 已存在时跳过 addColumn),down 删除字段;迁移文件仅创建,本次文档任务未执行", + "methods/system.json storage.entry.quickInbound 说明文字补充 is_virtual_inbound 判定规则;入参/出参不变(quickInbound 响应未返回该字段,list/get 查询白名单亦未包含该字段)" + ], + "module": "storage.entry" + }, { "version": "2026.08.27-order-allocateStorage-allow-storage-location", "date": "2026-08-27", diff --git a/methods/system.json b/methods/system.json index bf188c0..4ab019d 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1,8 +1,8 @@ { "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", - "version": "0.3.48", - "updatedAt": "2026-08-29", + "version": "0.3.58", + "updatedAt": "2026-08-30", "headers": [ { "name": "platform", @@ -2543,7 +2543,7 @@ "type": "array", "required": false, "source": "body", - "description": "导出表头字段白名单(中文表头字符串数组,如 [\"系统订单号\",\"外部订单号\"]);不传或空数组时输出全部列。枚举(共 51 个,校验不区分导出模式):系统订单号、外部订单号、平台单号、订单ID、订单号、外部单号、订单状态、抓取波次号、波次号、波次序号、货主、平台、店铺昵称、收件人、收件人电话、省、市、区、镇、详细地址、商品明细、仓库商品名称、商品条码、商品图片、数量、物流公司、运单号、业务类型、运单接口、包材ID、包材编码、包材名称、分配时间、商品种数、商品件数、商品重量、称重重量(g)、订单金额、实收金额、创建时间、支付时间、发货时间、出库状态、复核状态、复核完成状态、配货状态、打包状态、备注、买家留言、卖家留言、归档时间。其中仅 waybill 模式输出:系统订单号、外部订单号、平台单号、抓取波次号、商品明细;仅 item 模式输出:订单ID、订单号、外部单号、波次号、仓库商品名称、商品条码、商品图片、数量;其余为两种模式通用(选了当前模式不存在的表头时该列自动忽略)。传入非法表头会报错(错误信息列出非法值);支持 export_columns 与 exportColumns 两种写法" + "description": "导出表头字段白名单(中文表头字符串数组,如 [\"系统订单号\",\"外部订单号\"]);不传或空数组时输出全部列。枚举(共 52 个,校验不区分导出模式):系统订单号、外部订单号、平台单号、订单ID、订单号、外部单号、订单状态、抓取波次号、波次号、波次序号、货主、平台、来源、店铺昵称、收件人、收件人电话、省、市、区、镇、详细地址、商品明细、仓库商品名称、商品条码、商品图片、数量、物流公司、运单号、业务类型、运单接口、包材ID、包材编码、包材名称、分配时间、商品种数、商品件数、商品重量、称重重量(g)、订单金额、实收金额、创建时间、支付时间、发货时间、出库状态、复核状态、复核完成状态、配货状态、打包状态、备注、买家留言、卖家留言、归档时间。其中仅 waybill 模式输出:系统订单号、外部订单号、平台单号、抓取波次号、商品明细;仅 item 模式输出:订单ID、订单号、外部单号、波次号、仓库商品名称、商品条码、商品图片、数量;其余为两种模式通用(选了当前模式不存在的表头时该列自动忽略)。来源列(字段 create_channel,中文取值:手工单/接口/奇门/出库转单)位于平台列之后,waybill/item 两种模式均输出。传入非法表头会报错(错误信息列出非法值);支持 export_columns 与 exportColumns 两种写法" } ], "response": [ @@ -6918,7 +6918,7 @@ "name": "waybill_code", "type": "string", "required": false, - "description": "运单号(模糊匹配)" + "description": "运单号。通过 wms_order_express 表解析 order_id 后按订单过滤(wms_pack_task.waybill_code 通常为空)。匹配规则(不再支持部分单号模糊匹配):①完整单号等值匹配;②剥离一单多件包裹序号分段后缀(如 -1-1-)后的主体单号等值匹配;③主体单号前缀匹配(LIKE '主体-%',同主体不同分段序号,通配符已转义)。无任何匹配时返回空列表" }, { "name": "wave_no", @@ -6942,7 +6942,7 @@ "name": "quickWhere", "type": "string", "required": false, - "description": "快捷搜索:波次号模糊匹配 + 运单号通过 express→order→wave 链路解析" + "description": "快捷搜索:波次号模糊匹配(LIKE '%kw%',逻辑不变)+ 运单号经 express→order→wave 链路解析(团购按波次号查、散单按订单ID查)。运单号匹配优先级:先按「完整单号等值 + 剥离一单多件分段后缀(如 -1-1-)后的主体单号等值 + 主体前缀 LIKE '主体-%'」精确匹配;精确未命中且关键词 trim 后长度 ≥ 4(QUICK_WHERE_WAYBILL_FUZZY_MIN_LENGTH)时才降级为 LIKE '%kw%' 模糊查询(兼容输入部分单号的场景);trim 后长度 < 4 的短词(含单字符如 \"7\")禁止降级模糊,运单号解析直接返回空结果(避免 %短词% 误命中海量历史单号);波次号模糊逻辑不变" }, { "name": "start_time", @@ -11199,16 +11199,17 @@ }, { "method": "order.deliveryOrder.quickSearch", - "description": "订单快速搜索。跨表联合搜索:运单号(wms_order_express 精确匹配)、发货单号/外部订单号/平台交易单号(dispatch 表模糊匹配)。返回匹配的订单列表(最多20条),包含关键字段及关联运单号。", + "description": "订单快速搜索。跨表联合搜索:运单号(wms_order_express,支持完整单号等值、剥离一单多件包裹序号分段后缀(如 -1-1-)后的主体单号等值、主体前缀 LIKE '主体-%' 匹配,不再做部分单号模糊匹配)、发货单号 delivery_order_code / 原始平台订单号 source_order_codes(express 表快照字段,模糊匹配)。返回匹配的订单列表(最多20条),包含关键字段及关联运单号;平台交易单号 pay_no 仅作为结果字段回显,不参与搜索匹配。", "isNeedAuth": false, "isNeedLogin": true, + "headers": [], "params": [ { "name": "keyword", "type": "string", "required": true, "source": "body", - "description": "搜索关键词。同时匹配运单号(精确)、发货单号 delivery_order_code(模糊)、外部订单号 source_order_codes(模糊)、平台交易单号 pay_no(模糊)" + "description": "搜索关键词。运单号按「完整单号等值 + 剥离一单多件分段后缀(如 -1-1-)后的主体单号等值 + 主体前缀 LIKE '主体-%'」匹配(不做部分单号模糊);发货单号 delivery_order_code、原始平台订单号 source_order_codes 为模糊匹配(LIKE '%kw%');平台交易单号 pay_no 仅回显、不参与匹配" } ], "response": [ @@ -22652,7 +22653,7 @@ }, { "method": "storage.entry.quickInbound", - "description": "快捷直入(虚拟入库):将入库单商品直入到虚拟库位(space_id=2),跳过收货/质检流程。有绑定收货单时,只取收货单中与入库单明细有交集(按 stock_id 判断)且剩余可入数量(actual_quantity - stored_quantity)的商品直入,实际入库量 = min(明细计划数量, 收货单剩余可入数量),并在事务内回写收货单明细已入库数量与收货单入库状态;未绑定收货单时按明细计划数量全量直入。仅支持 CREATED 状态的入库单;CANCELLED(已作废)、COMPLETED(已完成)、PENDING 等其他状态均拒绝操作。事务内操作:更新入库明细收货量、累加库存总量、写入库存流水、写入虚拟库位库存、回写收货单明细、变更入库单状态为 COMPLETED。事务外异步回传奇门/API。", + "description": "快捷直入(虚拟入库):将入库单商品直入到虚拟库位(space_id=2),跳过收货/质检流程。有绑定收货单时,只取收货单中与入库单明细有交集(按 stock_id 判断)且剩余可入数量(actual_quantity - stored_quantity)的商品直入,实际入库量 = min(明细计划数量, 收货单剩余可入数量),并在事务内回写收货单明细已入库数量与收货单入库状态;未绑定收货单时按明细计划数量全量直入。仅支持 CREATED 状态的入库单;CANCELLED(已作废)、COMPLETED(已完成)、PENDING 等其他状态均拒绝操作。事务内操作:更新入库明细收货量、累加库存总量、写入库存流水、写入虚拟库位库存、回写收货单明细、变更入库单状态为 COMPLETED,并在同一事务内回写入库单 is_virtual_inbound(是否虚拟入库):有绑定收货单 → 0(非虚拟入库),无绑定收货单 → 1(虚拟入库)。事务外异步回传奇门/API。", "isNeedAuth": false, "isNeedLogin": true, "headers": [], @@ -31467,7 +31468,7 @@ }, { "method": "workbench.business", - "description": "工作台业务入口(免登录免鉴权,入参 name + data,业务逻辑待实现)", + "description": "工作台业务入口(免登录免鉴权,入参 name + data)。name 支持 queryOrder/query(条码查订单,data 需 barcode+warehouseId)、packOrder(开始打包)、finishPack(结束打包)、sendWeight(称重);不支持的业务名称报错。以下响应结构为 queryOrder/query(条码查订单)的返回。", "isNeedAuth": false, "isNeedLogin": false, "headers": [], @@ -31477,31 +31478,216 @@ "type": "string", "required": true, "source": "body", - "description": "业务名称(用于分发具体逻辑)" + "description": "业务名称:queryOrder/query(条码查订单)、packOrder、finishPack、sendWeight" }, { "name": "data", "type": "object", "required": false, "source": "body", - "description": "业务数据(透传)" + "description": "业务数据(透传)。queryOrder/query 需 barcode(运单号,必填)+ warehouseId(仓库ID,必填)" } ], "response": [ { - "name": "name", + "name": "barcode", "type": "string", "required": true, - "description": "回显业务名称" + "description": "条码(运单号)" }, { - "name": "received", - "type": "boolean", + "name": "waybill_code", + "type": "string", "required": true, - "description": "是否已接收" + "description": "运单号" + }, + { + "name": "isSandan", + "type": "number", + "required": true, + "description": "是否散单:1=散单 0=团购(波次类型 wave_type=1 时判定为团购)" + }, + { + "name": "store_remark", + "type": "string", + "required": true, + "description": "货主备注(合约表 store_warehouse.store_remask,无合约或为空时为空字符串)" + }, + { + "name": "express", + "type": "object", + "required": true, + "description": "运单信息:logistics_name(快递公司名称)、weighing_weight(称重重量)、package_material_name(包材名称快照)" + }, + { + "name": "order", + "type": "object", + "required": true, + "description": "订单详情", + "children": [ + { + "name": "id", + "type": "number", + "description": "订单ID" + }, + { + "name": "delivery_order_code", + "type": "string", + "description": "发货单号" + }, + { + "name": "order_type", + "type": "number", + "description": "订单类型" + }, + { + "name": "warehouse_id", + "type": "number", + "description": "仓库ID" + }, + { + "name": "store_id", + "type": "number", + "description": "货主ID" + }, + { + "name": "status", + "type": "number", + "description": "订单状态" + }, + { + "name": "step", + "type": "number", + "description": "订单步骤" + }, + { + "name": "wave_id", + "type": "number", + "description": "波次ID" + }, + { + "name": "wave_no", + "type": "string", + "description": "波次号" + }, + { + "name": "post_status", + "type": "string", + "description": "过账状态" + }, + { + "name": "pick_status", + "type": "string", + "description": "拣货状态" + }, + { + "name": "pack_status", + "type": "string", + "description": "打包状态(原始值):none/padding/fin/error,空值/null 归一化为 none" + }, + { + "name": "intercept_status", + "type": "string", + "description": "拦截状态(原始值):空值/null 归一化为 none;散单/团购均返回" + }, + { + "name": "recheck_status", + "type": "string", + "description": "复核状态" + }, + { + "name": "outbound_status", + "type": "string", + "description": "出库状态" + }, + { + "name": "items_count", + "type": "number", + "description": "商品件数" + }, + { + "name": "items_total", + "type": "number", + "description": "商品总数" + }, + { + "name": "items_weight", + "type": "number", + "description": "商品总重量" + }, + { + "name": "source_platform_code", + "type": "string", + "description": "来源平台编码" + }, + { + "name": "logistics_name", + "type": "string", + "description": "快递公司名称" + }, + { + "name": "create_at", + "type": "string", + "description": "创建时间" + }, + { + "name": "updated_at", + "type": "string", + "description": "更新时间" + }, + { + "name": "intercept_flag", + "type": "number", + "description": "拦截标志(仅散单 isSandan=1 返回,团购不返回):拦截状态(intercept_status)不等于 none 时为 1,等于 none 时为 0" + }, + { + "name": "pack_flag", + "type": "number", + "description": "打包标志(仅散单 isSandan=1 返回,团购不返回):打包状态(pack_status)不等于 none 时为 1,等于 none 时为 0" + } + ] + }, + { + "name": "items", + "type": "array", + "required": true, + "description": "订单商品明细,每项含 id/order_id/item_id/item_code/item_name/plan_qty/actual_price/stock_id/order_line_no/inventory_type/sku_property/stock_unit/barcodes/image_url" + }, + { + "name": "source_table", + "type": "string", + "required": true, + "description": "订单命中分表:current(待处理表)或 dispatch(配送表)" + }, + { + "name": "batch", + "type": "object", + "required": false, + "description": "波次汇总(仅团购 isSandan=0 返回):wave_id(波次ID)、wave_no(波次号)、wave_type(波次类型,1=团购)、total_orders(波次订单总数)" } ], - "errors": [] + "errors": [ + { + "code": "400", + "message": "条码不能为空" + }, + { + "code": "400", + "message": "仓库ID不能为空" + }, + { + "code": "400", + "message": "未找到条码 [xxx] 对应的运单记录" + }, + { + "code": "400", + "message": "未在待处理或配送表中找到订单 [id=xxx, warehouse=xxx]" + }, + { + "code": "400", + "message": "不支持的业务类型: xxx" + } + ] }, { "method": "workbench.bindCamera", @@ -32535,10 +32721,10 @@ }, { "name": "where.waybillCode", - "type": "string", + "type": "string|string[]", "required": false, "source": "body.where", - "description": "运单号(模糊搜索)" + "description": "运单号筛选:字符串时为模糊搜索(LIKE '%值%',向后兼容);字符串数组时为精确匹配(Op.in,元素自动 trim 并过滤空值,空数组或全空值时不加该筛选条件)" }, { "name": "where.mainWaybillCode", @@ -33356,10 +33542,10 @@ }, { "name": "where.waybillCode", - "type": "string", + "type": "string|string[]", "required": false, "source": "body.where", - "description": "运单号(模糊搜索)" + "description": "运单号筛选:字符串时为模糊搜索(LIKE '%值%',向后兼容);字符串数组时为精确匹配(Op.in,元素自动 trim 并过滤空值,空数组或全空值时不加该筛选条件)" }, { "name": "where.mainWaybillCode", @@ -35530,6 +35716,178 @@ "message": "groupId 不能为空 / warehouseId 无效" } ] + }, + { + "method": "inbox.group.quickList", + "description": "群快速查询(下拉选择用,不分页):关键词同时模糊匹配群名称与外部群ID,按创建时间倒序返回轻量字段,软删除记录自动排除;支持双维度可选过滤:store_id(货主维度,对应 wms_inbox_group.store_id 列)与 warehouse_id(仓库维度,对应 wms_inbox_group.warehouse_id 列)均可选,可单独传、可同时传(AND 关系),也可都不传(返回所有仓库/货主的群),非法值分别报「store_id 无效」「warehouse_id 无效」。需 566 权限(inbox.group.quickList,已授权仓库组-主管/客服组-主管/生产组-主管/经理,超级管理员与仓库管理员持通配符自动拥有)", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(登录凭证,权限校验用)" + } + ], + "params": [ + { + "name": "store_id", + "type": "number|string", + "required": false, + "source": "body", + "description": "货主ID(可选,货主维度,对应 wms_inbox_group.store_id 列):传入时须为正整数,仅返回该货主的群;不传或为空时不加货主过滤(返回所有货主的群);与 warehouse_id 可单独传或同时传(AND 关系)" + }, + { + "name": "warehouse_id", + "type": "number|string", + "required": false, + "source": "body", + "description": "仓库ID(可选,仓库维度,对应 wms_inbox_group.warehouse_id 列):传入时须为正整数,仅返回该仓库的群;不传或为空时不加仓库过滤(返回所有仓库的群);与 store_id 可单独传或同时传(AND 关系)" + }, + { + "name": "keyword", + "type": "string", + "required": false, + "source": "body", + "description": "关键词,模糊匹配 group_name(群名称)与 group_id(外部群ID)" + }, + { + "name": "groupType", + "type": "string", + "required": false, + "source": "body", + "description": "群类型筛选:store(货主) / warehouse(仓库) / express(快递)" + }, + { + "name": "limit", + "type": "number", + "required": false, + "source": "body", + "description": "返回条数上限,默认20,最大100(无分页)" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "群快速列表(按创建时间倒序,无分页),每项含 id/group_id/group_name/group_type/sub_type/is_blocked", + "children": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "群记录主键ID(wms_inbox_group.id)" + }, + { + "name": "group_id", + "type": "string", + "required": false, + "description": "外部群ID(未绑定时为 null)" + }, + { + "name": "group_name", + "type": "string", + "required": true, + "description": "群名称" + }, + { + "name": "group_type", + "type": "string", + "required": false, + "description": "群类型:store / warehouse / express(未配置时为 null)" + }, + { + "name": "sub_type", + "type": "string", + "required": false, + "description": "群子类型(未配置时为 null)" + }, + { + "name": "is_blocked", + "type": "number", + "required": true, + "description": "是否屏蔽:1=屏蔽 0=正常" + } + ] + } + ], + "errors": [ + { + "code": "400", + "message": "store_id 无效 / warehouse_id 无效" + } + ] + }, + { + "method": "inbox.group.members", + "description": "查询一个或多个群的成员列表(下拉选择用,多群聚合):先按内部主键ID数组+仓库批量校验群存在(软删除自动排除),再聚合所有群的外部群ID(去重、剔除空值),按外部群ID集合在消息表中聚合去重成员(每个 user_id 取最新一条消息的 user_name),关键词在聚合结果上过滤,最后截断到 limit 条;所有外部群ID为空时返回空列表。多群共享同一聚合池(最多取最近 500 条消息,更早消息中的成员不会出现在结果中);user_id 为 NULL/空串的消息被排除。warehouseId 由服务端从登录上下文自动注入。需 567 权限(inbox.group.members,已授权仓库组-主管/客服组-主管/生产组-主管/经理,超级管理员与仓库管理员持通配符自动拥有)", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(从中解析 warehouseId 仓库上下文)" + } + ], + "params": [ + { + "name": "groupIds", + "type": "array", + "required": true, + "source": "body", + "description": "群记录主键ID数组(wms_inbox_group.id,必填,非空数组,每个元素为正整数,支持数字或可解析数字字符串)" + }, + { + "name": "keyword", + "type": "string", + "required": false, + "source": "body", + "description": "关键词,模糊匹配 user_name(用户名)与 user_id(用户ID),对聚合结果做小写包含过滤" + }, + { + "name": "limit", + "type": "number", + "required": false, + "source": "body", + "description": "返回条数上限,默认20,最大100(无分页)" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "群成员列表(多群聚合去重,无分页),每项含 user_id/user_name;所有群外部群ID为空时返回空列表", + "children": [ + { + "name": "user_id", + "type": "string", + "required": true, + "description": "成员用户ID(外部IM用户ID,跨群去重)" + }, + { + "name": "user_name", + "type": "string", + "required": true, + "description": "成员用户名(该用户最新一条消息的 user_name,无则为空字符串)" + } + ] + } + ], + "errors": [ + { + "code": "400", + "message": "groupIds 无效 / warehouseId 无效" + }, + { + "code": "500", + "message": "群不存在或无权限操作" + } + ] } ] }, @@ -37946,6 +38304,179 @@ "message": "服务器内部错误" } ] + }, + { + "method": "returnUnpack.export", + "description": "提交退回拆包导出任务(异步)。入参 where/sort 语义与 returnUnpack.list 一致;warehouse_id 由服务端从 ctx.user.store_id 注入,禁止前端传入。提交后立即返回 task_id,后台异步生成双 Sheet Excel(Sheet1「正常退回运单号列表」+ Sheet2「明细表」)并上传,导出进度/下载请通过 returnUnpack.exportTaskProgress 查询。数据来源 wms_return_unpack 主表 + wms_return_unpack_detail 明细表;货主名取自 wms_store.company_name,快递类型取自 wms_order_express.logistics_name;颜色列取自明细 product_snapshot.sku_property 中「颜色:xxx」片段(兜底 spec),无颜色信息为空;全量分页拉取,无行数上限;Sheet1 不加 status 过滤(如需只导特定状态由调用方传 where.status)。任务缓存 Redis TTL 30 分钟;状态口径 submitted → running → 数据拉取(10~30) → 明细拉取(30~50) → Excel(55~90) → 上传(92) → success(100),失败 failed + error。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "查询条件,语义与 returnUnpack.list 的 where 一致(支持 {operator,value,type} 标准结构或直接值;字段含 unpack_no/waybill_code 模糊、unpack_date/start_time/end_time/created_at/updated_at 范围、status/detail_status/store_id/order_express_id/order_id/unpacker_id/return_received_id 等值、has_video/video_enable 等);禁止传入 warehouse_id/warehouseId(服务端注入);不传 status 时不过滤状态" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数,语义与 returnUnpack.list 的 sort 一致:sortField 白名单 id/created_at/updated_at/unpack_date/start_time/end_time/unpack_no/waybill_code,sortOrder asc/desc,默认 created_at desc" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务 ID(后端生成,格式 return_unpack_export_{warehouseId}_{timestamp}_{random})" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "任务状态,枚举:submitted/running/success/failed/not_found(提交成功时为 submitted)" + }, + { + "name": "progress", + "type": "number", + "required": true, + "description": "当前进度百分比(0-100),提交时返回 0" + }, + { + "name": "current_count", + "type": "number", + "required": true, + "description": "当前已处理记录数(拆包单条数)" + }, + { + "name": "total_count", + "type": "number", + "required": true, + "description": "总记录数(若有)" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "任务提示信息" + }, + { + "name": "result", + "type": "object", + "required": true, + "description": "任务执行结果(提交时为 null;后台完成后为上传信息对象,含 filename/url/fileKey/cdnUrl/cosUrl/current_count/total_count/total_details/sheet_count)" + }, + { + "name": "error", + "type": "string", + "required": true, + "description": "失败时的错误信息(可选,非失败时为空字符串)" + }, + { + "name": "update_time", + "type": "number", + "required": true, + "description": "任务更新时间(Unix 毫秒时间戳)" + } + ], + "errors": [ + { + "code": "400", + "message": "参数格式不正确或 where 条件非法" + }, + { + "code": "500", + "message": "导出任务提交失败" + } + ] + }, + { + "method": "returnUnpack.exportTaskProgress", + "description": "按 task_id 查询退回拆包导出任务进度,返回 task_id、status、progress、current_count、total_count、message、result、error、download_url、update_time;上传完成后 download_url 返回下载链接(从 result.url/cdnUrl/cosUrl/fileKey 兜底取);任务缓存 Redis TTL 30 分钟,task_id 缺失或缓存未命中时 status=not_found(正常响应,非报错)。状态口径 submitted → running → 数据拉取(10~30) → 明细拉取(30~50) → Excel(55~90) → 上传(92) → success(100),失败 failed + error。免权限免日志口径与 order.exportTaskProgress 一致。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "task_id / taskId", + "type": "string", + "required": true, + "source": "body|query", + "description": "任务 ID,兼容 task_id(下划线)与 taskId(驼峰)两种写法" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务 ID(task_id 缺失时为回显的空字符串,status=not_found)" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "任务状态:submitted/running/success/failed/not_found" + }, + { + "name": "progress", + "type": "number", + "required": true, + "description": "进度百分比(0-100)" + }, + { + "name": "current_count", + "type": "number", + "required": true, + "description": "当前已处理记录数(拆包单条数)" + }, + { + "name": "total_count", + "type": "number", + "required": true, + "description": "总记录数" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "任务提示信息" + }, + { + "name": "result", + "type": "object", + "required": true, + "description": "任务执行结果对象(完成后含 filename/url/fileKey/cdnUrl/cosUrl 等;未完成或 not_found 时为 null)" + }, + { + "name": "error", + "type": "string", + "required": true, + "description": "失败时的错误信息(可选,非失败时为空字符串)" + }, + { + "name": "download_url", + "type": "string", + "required": true, + "description": "任务完成后下载链接(从 result.url/cdnUrl/cosUrl/fileKey 兜底取);未完成或不存在时为空字符串" + }, + { + "name": "update_time", + "type": "number", + "required": true, + "description": "最近一次状态更新时间(Unix 毫秒时间戳)" + } + ], + "errors": [ + { + "code": "500", + "message": "查询失败或内部错误" + } + ] } ] }, @@ -38304,6 +38835,1646 @@ ] } ] + }, + { + "groupName": "通用报表模块", + "module": "report", + "list": [ + { + "method": "report.generate", + "description": "提交报表导出异步任务(手动导出):按报表定义ID读取 wms_report_definition(is_enabled=1)配置,经注册类型对应的内置查询器(type=stockFlow 等)取数,并按类型硬编码字段规格(app/lib/report/render.js renderSheetByType)渲染 Excel 上传。立即返回任务受理信息(task_id/status=submitted),后台异步执行(执行中的错误体现在任务进度 error 字段),完成后可通过 report.generateTaskProgress 轮询进度并获取下载链接。warehouse_id 由服务端从登录上下文(ctx.user.store_id)自动注入,前端无需传递。仅登录即可调用(免权限:systemInit 声明 generate/generateTaskProgress/meta 免权限;generate 不写审计日志)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "report_id", + "type": "number", + "required": false, + "source": "body", + "description": "报表定义ID(必填,与 reportId 二选一;均传时优先 reportId)。须为 wms_report_definition 中已启用(is_enabled=1)的报表定义" + }, + { + "name": "reportId", + "type": "number", + "required": false, + "source": "body", + "description": "报表定义ID驼峰别名(兼容,优先级高于 report_id)" + }, + { + "name": "store_id", + "type": "number", + "required": false, + "source": "body", + "description": "货主ID(可选,货主维度报表时传入;>0 生效,<=0 视为不按货主过滤)" + }, + { + "name": "storeId", + "type": "number", + "required": false, + "source": "body", + "description": "货主ID驼峰别名(兼容,优先级高于 store_id)" + }, + { + "name": "params", + "type": "object", + "required": false, + "source": "body", + "description": "查询器业务参数(透传给内置查询器,如 bizDate/dayCount/cutoverHour)" + }, + { + "name": "params.bizDate", + "type": "string", + "required": false, + "source": "body", + "description": "数据日期(YYYY-MM-DD),用于导出文件名 file_name 模板的 {date} 占位;缺省取服务器当天" + }, + { + "name": "params.dayCount", + "type": "number", + "required": false, + "source": "body", + "description": "窗口数量覆盖(stockFlow 查询器经 resolveWindowConfig 解析,缺省 7,<=0 视为 7)" + }, + { + "name": "params.cutoverHour", + "type": "number", + "required": false, + "source": "body", + "description": "切点小时覆盖(缺省 7,钳制到 0-23)" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "导出任务ID(report_generate_ 前缀)" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "任务状态:submitted/running/success/failed。受理时恒为 submitted,最终状态经 report.generateTaskProgress 查询" + }, + { + "name": "progress", + "type": "number", + "required": true, + "description": "任务进度百分比(0-100)" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "任务状态说明(受理时为「导出任务已提交」)" + }, + { + "name": "result", + "type": "object|null", + "required": true, + "description": "任务结果对象;导出成功后为 { fileKey, url, filename, size },未完成或失败时为 null" + }, + { + "name": "error", + "type": "string", + "required": true, + "description": "失败时的错误信息;成功时为空字符串" + }, + { + "name": "update_time", + "type": "number", + "required": true, + "description": "任务状态更新时间(毫秒时间戳)" + } + ], + "errors": [ + { + "code": 0, + "message": "报表ID report_id 必须为正整数" + } + ] + }, + { + "method": "report.generateTaskProgress", + "description": "查询报表导出任务进度与结果:按 task_id 读取任务缓存(缓存 TTL 1800 秒)。status 可能值:submitted/running/success/failed/not_found;任务成功后 download_url 返回报表文件下载链接。仅登录即可调用(免权限)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "task_id", + "type": "string", + "required": false, + "source": "body", + "description": "导出任务ID(下划线写法,与 taskId 二选一)" + }, + { + "name": "taskId", + "type": "string", + "required": false, + "source": "body", + "description": "导出任务ID(驼峰写法,兼容别名)" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "导出任务ID;未传入时为空字符串" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "任务状态:submitted/running/success/failed/not_found(任务不存在时)" + }, + { + "name": "progress", + "type": "number", + "required": true, + "description": "任务进度百分比(0-100);not_found 时为 0" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "任务状态说明" + }, + { + "name": "result", + "type": "object|null", + "required": true, + "description": "任务结果对象;导出成功后为 { fileKey, url, filename, size },未完成或失败时为 null" + }, + { + "name": "error", + "type": "string", + "required": true, + "description": "失败时的错误信息;成功时为空字符串" + }, + { + "name": "download_url", + "type": "string", + "required": true, + "description": "任务成功后返回的下载链接(取 result.url/cndUrl/cosUrl/fileKey 兜底);未完成或失败时为空字符串" + }, + { + "name": "update_time", + "type": "number", + "required": true, + "description": "任务状态更新时间(毫秒时间戳)" + } + ], + "errors": [] + }, + { + "method": "report.deliveryPlan.save", + "description": "新增/更新货主报表投递计划(货主 store_id + 报表定义ID report_id 唯一,存在则更新):先校验报表定义存在且启用(wms_report_definition.is_enabled=1),schedule_times 自动去重并按升序排序,channel 仅支持 inbox(默认 inbox,wecom/link 已弃用,非法渠道报错;历史 wecom/link 计划在投递时按 inbox 兜底执行),late_grace_minutes 夹取到 0-1440。可选计划名称 name(仅展示字段,不参与幂等/关联逻辑;未传不覆盖,null/空串/全空白清空,非空 trim 后 ≤100 字符,超长报错)。inbox 推送失败自动经 inbox.message.retry 立即重推一次,重推仍失败进入 failed 退避重试(MAX_RETRY=3,退避 retry_count × 60s)。可选文本通知配置:notify_template(≤500,标签白名单 {time}/{url}/{report_name}/{biz_date},未知标签报错)、notify_group_ids(wms_inbox_group.id,正整数去重 ≤20,保存时校验存在性且排除软删)、notify_member_ids(外部 IM 用户 ID,非空字符串去重 ≤100);三者仅在入参存在时生效(未传保持原值,不传行为与旧版一致)。需授权接口(管理类操作,systemInit 未声明免权限,仅通配符角色或已授权角色可用)。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "store_id", + "type": "number", + "required": true, + "source": "body", + "description": "货主ID(必填,正整数;<=0 报错)" + }, + { + "name": "report_id", + "type": "number", + "required": false, + "source": "body", + "description": "报表定义ID(必填,与 reportId 二选一;均传时优先 reportId)。须为已启用(is_enabled=1)的报表定义" + }, + { + "name": "reportId", + "type": "number", + "required": false, + "source": "body", + "description": "报表定义ID驼峰别名(兼容,优先级高于 report_id)" + }, + { + "name": "schedule_times", + "type": "array", + "required": true, + "source": "body", + "description": "每日投递时间点数组(HH:mm 24 小时制,非空;自动去重并按升序排序;支持 JSON 字符串数组)" + }, + { + "name": "channel", + "type": "string", + "required": false, + "source": "body", + "description": "投递渠道(可选):仅支持 inbox,默认 inbox;wecom/link 已弃用,传入非法渠道报错「投递渠道仅支持 inbox: 」;历史 wecom/link 计划在投递时按 inbox 兜底执行", + "list": [ + { + "value": "inbox", + "name": "站内信" + } + ] + }, + { + "name": "late_grace_minutes", + "type": "number", + "required": false, + "source": "body", + "description": "补投宽限分钟(0-1440),默认 60;越界值夹取到 0-1440" + }, + { + "name": "name", + "type": "string|null", + "required": false, + "source": "body", + "description": "计划名称(可选,仅展示字段,不参与幂等/关联逻辑)。未传不覆盖既有值;null/空串/全空白归一化为 null(显式清空);非空 trim 后最长 100 字符,超长报错「计划名称 name 长度不能超过 100 字符」" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注(最长 500 字符,超出截断)" + }, + { + "name": "notify_template", + "type": "string", + "required": false, + "source": "body", + "description": "文本通知模板(可选,最长 500 字符,超出报错)。支持标签 {time}/{url}/{report_name}/{biz_date},含白名单外标签时报错并列出非法标签;空值视为未启用(清空配置);仅入参存在时生效,未传不修改既有配置" + }, + { + "name": "notify_group_ids", + "type": "array", + "required": false, + "source": "body", + "description": "通知群ID数组(可选,wms_inbox_group.id;正整数自动去重并升序,最多 20 个;保存时校验存在性,软删已删除的群报错并列出缺失 ID,被屏蔽的群仍可选中;支持 JSON 字符串数组;空数组视为不选择群)" + }, + { + "name": "notify_member_ids", + "type": "array", + "required": false, + "source": "body", + "description": "通知成员ID数组(可选,外部 IM 用户 ID;非空字符串自动去重,最多 100 个;推送时 user_id 支持数组整体透传不循环拆发;支持 JSON 字符串数组;空数组视为不选择成员)" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "投递计划ID" + }, + { + "name": "store_id", + "type": "number", + "required": true, + "description": "货主ID" + }, + { + "name": "report_definition_id", + "type": "number", + "required": true, + "description": "报表定义ID(wms_report_definition.id)" + }, + { + "name": "schedule_times", + "type": "array", + "required": true, + "description": "每日投递时间点数组(HH:mm,去重升序)" + }, + { + "name": "channel", + "type": "string", + "required": true, + "description": "投递渠道:inbox(渠道已收敛,仅支持 inbox)" + }, + { + "name": "enabled", + "type": "number", + "required": true, + "description": "是否启用:0=停用 1=启用" + }, + { + "name": "late_grace_minutes", + "type": "number", + "required": true, + "description": "补投宽限分钟(0-1440)" + }, + { + "name": "name", + "type": "string", + "required": true, + "description": "计划名称(未设置时为空字符串)" + }, + { + "name": "remark", + "type": "string", + "required": true, + "description": "备注" + }, + { + "name": "notify_template", + "type": "string", + "required": true, + "description": "文本通知模板(未配置时为空字符串)" + }, + { + "name": "notify_group_ids", + "type": "array|null", + "required": true, + "description": "通知群ID数组(内部 wms_inbox_group.id,去重升序;未选择时 null)" + }, + { + "name": "notify_member_ids", + "type": "array|null", + "required": true, + "description": "通知成员ID数组(外部 IM 用户 ID,去重;未选择时 null)" + }, + { + "name": "created_at", + "type": "string", + "required": true, + "description": "创建时间" + }, + { + "name": "updated_at", + "type": "string", + "required": true, + "description": "更新时间" + } + ], + "errors": [ + { + "code": 500, + "message": "货主ID store_id 不能为空" + }, + { + "code": 500, + "message": "报表ID report_id 必须为正整数" + }, + { + "code": 500, + "message": "报表定义不存在或已停用: id=" + }, + { + "code": 500, + "message": "schedule_times 必须为 HH:mm 字符串数组且不能为空" + }, + { + "code": 500, + "message": "schedule_times 含非法时间点(需 HH:mm 24 小时制):